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

@c %**end of header

@copying
@quotation
Python 3.14.3, 2月 19, 2026

Author name not set

Copyright @copyright{} 2001 Python Software Foundation
@end quotation

@end copying

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

@c %** start of user preamble

@c %** end of user preamble

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

@c %**start of body
@anchor{contents doc}@anchor{13b}
@menu
* What's New in Python:: 
* Python チュートリアル:: 
* Python のセットアップと利用:: 
* Python 言語リファレンス:: 
* Python 標準ライブラリ:: 
* Python インタプリタの拡張と埋め込み:: 
* Python/C API リファレンスマニュアル:: 
* Python モジュールのインストール:: 
* Python HOWTO:: 
* Python よくある質問:: 
* 非推奨: 非推奨<14>. 
* 用語集: 用語集<2>. 
* このドキュメントについて:: 
* バグへの対処:: 
* Copyright:: 
* 歴史とライセンス:: 
* Pythonモジュール索引:: 
* 索引:: 

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

What's New in Python

* What's new in Python 3.14: What's new in Python 3 14. 
* What's New In Python 3.13: What's New In Python 3 13. 
* What's New In Python 3.12: What's New In Python 3 12. 
* What's New In Python 3.11: What's New In Python 3 11. 
* What's New In Python 3.10: What's New In Python 3 10. 
* What's New In Python 3.9: What's New In Python 3 9. 
* What's New In Python 3.8: What's New In Python 3 8. 
* What's New In Python 3.7: What's New In Python 3 7. 
* What's New In Python 3.6: What's New In Python 3 6. 
* What's New In Python 3.5: What's New In Python 3 5. 
* What's New In Python 3.4: What's New In Python 3 4. 
* What's New In Python 3.3: What's New In Python 3 3. 
* What's New In Python 3.2: What's New In Python 3 2. 
* What's New In Python 3.1: What's New In Python 3 1. 
* What's New In Python 3.0: What's New In Python 3 0. 
* What's New in Python 2.7: What's New in Python 2 7. 
* What's New in Python 2.6: What's New in Python 2 6. 
* What's New in Python 2.5: What's New in Python 2 5. 
* What's New in Python 2.4: What's New in Python 2 4. 
* What's New in Python 2.3: What's New in Python 2 3. 
* What's New in Python 2.2: What's New in Python 2 2. 
* What's New in Python 2.1: What's New in Python 2 1. 
* What's New in Python 2.0: What's New in Python 2 0. 
* 変更履歴:: 

What's new in Python 3.14

* 概要: 概要 -- リリースハイライト. リリースハイライト
* 新しい機能:: 
* Other language changes:: 
* 新しいモジュール:: 
* Improved modules:: 
* 最適化:: 
* 削除:: 
* 非推奨:: 
* CPython バイトコードの変更:: 
* C API changes:: 
* Build changes:: 
* Porting to Python 3.14: Porting to Python 3 14. 
* Notable changes in 3.14.1: Notable changes in 3 14 1. 

新しい機能

* PEP 649 と PEP 749; アノテーションの遅延評価: PEP 649 と PEP 749 アノテーションの遅延評価. 
* PEP 734; Multiple interpreters in the standard library: PEP 734 Multiple interpreters in the standard library. 
* PEP 750; テンプレート文字列リテラル: PEP 750 テンプレート文字列リテラル. 
* PEP 768; Safe external debugger interface: PEP 768 Safe external debugger interface. 
* A new type of interpreter:: 
* Free-threaded mode improvements:: 
* エラーメッセージの改善:: 
* PEP 784; Zstandard support in the standard library: PEP 784 Zstandard support in the standard library. 
* Asyncio introspection capabilities:: 
* Concurrent safe warnings control:: 

Other language changes

* Built-ins:: 
* コマンドラインと環境:: 
* PEP 758; Allow except and except* expressions without brackets: PEP 758 Allow except and except* expressions without brackets. 
* PEP 765; Control flow in finally blocks: PEP 765 Control flow in finally blocks. 
* Incremental garbage collection:: 
* Default interactive shell:: 

Improved modules

* argparse:: 
* ast:: 
* asyncio:: 
* calendar:: 
* concurrent.futures: concurrent futures. 
* configparser:: 
* contextvars:: 
* ctypes:: 
* curses:: 
* datetime:: 
* decimal:: 
* difflib:: 
* dis:: 
* errno:: 
* faulthandler:: 
* fnmatch:: 
* fractions:: 
* functools:: 
* getopt:: 
* getpass:: 
* graphlib:: 
* heapq:: 
* hmac:: 
* http:: 
* imaplib:: 
* inspect:: 
* io:: 
* json:: 
* linecache:: 
* logging.handlers: logging handlers. 
* math:: 
* mimetypes:: 
* multiprocessing:: 
* operator:: 
* os:: 
* os.path: os path. 
* pathlib:: 
* pdb:: 
* pickle:: 
* プラットフォーム:: 
* pydoc:: 
* re:: 
* socket:: 
* ssl:: 
* struct:: 
* symtable:: 
* sys:: 
* sys.monitoring: sys monitoring. 
* sysconfig:: 
* tarfile:: 
* threading:: 
* tkinter:: 
* turtle:: 
* types:: 
* typing:: 
* unicodedata:: 
* unittest:: 
* urllib:: 
* uuid:: 
* webbrowser:: 
* zipfile:: 

最適化

* asyncio: asyncio<2>. 
* base64:: 
* bdb:: 
* difflib: difflib<2>. 
* gc:: 
* io: io<2>. 
* pathlib: pathlib<2>. 
* pdb: pdb<2>. 
* textwrap:: 
* uuid: uuid<2>. 
* zlib:: 

削除

* argparse: argparse<2>. 
* ast: ast<2>. 
* asyncio: asyncio<3>. 
* email:: 
* importlib.abc: importlib abc. 
* itertools:: 
* pathlib: pathlib<3>. 
* pkgutil:: 
* pty:: 
* sqlite3:: 
* urllib: urllib<2>. 

非推奨

* New deprecations:: 
* Pending removal in Python 3.15: Pending removal in Python 3 15. 
* Pending removal in Python 3.16: Pending removal in Python 3 16. 
* Pending removal in Python 3.17: Pending removal in Python 3 17. 
* Pending removal in Python 3.18: Pending removal in Python 3 18. 
* Pending removal in Python 3.19: Pending removal in Python 3 19. 
* Pending removal in future versions:: 

CPython バイトコードの変更

* Pseudo-instructions:: 

C API changes

* Python configuration C API:: 
* New features in the C API:: 
* Limited C API changes:: 
* Removed C APIs:: 
* Deprecated C APIs:: 

Deprecated C APIs

* Pending removal in Python 3.15: Pending removal in Python 3 15<2>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<2>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<2>. 
* Pending removal in future versions: Pending removal in future versions<2>. 

Build changes

* build-details.json: build-details json. 
* Discontinuation of PGP signatures:: 
* Free-threaded Python is officially supported:: 
* Binary releases for the experimental just-in-time compiler:: 

Porting to Python 3.14

* Python API の変更:: 
* Changes in annotations (PEP 649 and PEP 749): Changes in annotations PEP 649 and PEP 749. 
* C API の変更:: 

Changes in annotations (PEP 649 and PEP 749)

* Implications for annotated code:: 
* Implications for readers of __annotations__:: 
* Related changes:: 
* from __future__ import annotations:: 

What's New In Python 3.13

* 概要: 概要 -- リリースハイライト<2>. リリースハイライト
* 新しい機能: 新しい機能<2>. 
* その他の言語変更:: 
* 新たなモジュール:: 
* 改良されたモジュール:: 
* 最適化: 最適化<2>. 
* Removed Modules And APIs:: 
* New Deprecations:: 
* CPython Bytecode Changes:: 
* C API の変更: C API の変更<2>. 
* Build Changes:: 
* Porting to Python 3.13: Porting to Python 3 13. 
* Regression Test Changes:: 

新しい機能

* 改善された対話的インタープリタ:: 
* エラーメッセージの改善: エラーメッセージの改善<2>. 
* フリースレッドの CPython:: 
* 実験的な Just-in-time (JIT) コンパイラ;: 実験的な Just-in-time JIT コンパイラ. 
* Defined mutation semantics for locals(): Defined mutation semantics for locals. 
* Support for mobile platforms:: 

改良されたモジュール

* argparse: argparse<3>. 
* 配列:: 
* ast: ast<3>. 
* asyncio: asyncio<4>. 
* base64: base64<2>. 
* compileall:: 
* concurrent.futures: concurrent futures<2>. 
* configparser: configparser<2>. 
* copy:: 
* ctypes: ctypes<2>. 
* dbm:: 
* dis: dis<2>. 
* doctest:: 
* email: email<2>. 
* enum:: 
* fractions: fractions<2>. 
* glob:: 
* importlib:: 
* io: io<3>. 
* ipaddress:: 
* itertools: itertools<2>. 
* marshal:: 
* math: math<2>. 
* mimetypes: mimetypes<2>. 
* mmap:: 
* multiprocessing: multiprocessing<2>. 
* os: os<2>. 
* os.path: os path<2>. 
* pathlib: pathlib<4>. 
* pdb: pdb<3>. 
* queue:: 
* random:: 
* re: re<2>. 
* shutil:: 
* site:: 
* sqlite3: sqlite3<2>. 
* ssl: ssl<2>. 
* statistics:: 
* subprocess:: 
* sys: sys<2>. 
* tempfile:: 
* time:: 
* tkinter: tkinter<2>. 
* traceback:: 
* types: types<2>. 
* typing: typing<2>. 
* unicodedata: unicodedata<2>. 
* venv:: 
* warnings:: 
* xml:: 
* zipimport:: 

Removed Modules And APIs

* PEP 594; Remove "dead batteries" from the standard library: PEP 594 Remove "dead batteries" from the standard library. 
* 2to3:: 
* builtins:: 
* configparser: configparser<3>. 
* importlib.metadata: importlib metadata. 
* locale:: 
* opcode:: 
* optparse:: 
* pathlib: pathlib<5>. 
* re: re<3>. 
* tkinter.tix: tkinter tix. 
* turtle: turtle<2>. 
* typing: typing<3>. 
* unittest: unittest<2>. 
* urllib: urllib<3>. 
* webbrowser: webbrowser<2>. 

New Deprecations

* Pending removal in Python 3.14: Pending removal in Python 3 14. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<3>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<3>. 
* Pending removal in Python 3.17: Pending removal in Python 3 17<2>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<3>. 
* Pending removal in Python 3.19: Pending removal in Python 3 19<2>. 
* Pending removal in future versions: Pending removal in future versions<3>. 

C API の変更

* 新しい機能: 新しい機能<3>. 
* Changed C APIs:: 
* Limited C API Changes:: 
* Removed C APIs: Removed C APIs<2>. 
* Deprecated C APIs: Deprecated C APIs<2>. 

Deprecated C APIs

* Pending removal in Python 3.14: Pending removal in Python 3 14<2>. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<4>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<4>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<4>. 
* Pending removal in future versions: Pending removal in future versions<4>. 

Porting to Python 3.13

* Python API の変更: Python API の変更<2>. 
* C API の変更: C API の変更<3>. 

What's New In Python 3.12

* 概要: 概要 -- リリースハイライト<3>. リリースハイライト
* 新しい機能: 新しい機能<4>. 
* 型ヒントに関連する新しい機能:: 
* その他の言語変更: その他の言語変更<2>. 
* 新たなモジュール: 新たなモジュール<2>. 
* 改良されたモジュール: 改良されたモジュール<2>. 
* 最適化: 最適化<3>. 
* CPython バイトコードの変更: CPython バイトコードの変更<2>. 
* Demos and Tools:: 
* 非推奨: 非推奨<2>. 
* 削除: 削除<2>. 
* Python 3.12 への移植: Python 3 12 への移植. 
* Build Changes: Build Changes<2>. 
* C API の変更: C API の変更<4>. 

新しい機能

* PEP 695; 型パラメータの構文: PEP 695 型パラメータの構文. 
* PEP 701; f-strings の構文的な形式化: PEP 701 f-strings の構文的な形式化. 
* PEP 684; インタープリタごとの GIL: PEP 684 インタープリタごとの GIL. 
* PEP 669; CPython の低影響モニタリング: PEP 669 CPython の低影響モニタリング. 
* PEP 688; バッファプロトコルを Python で利用可能にする: PEP 688 バッファプロトコルを Python で利用可能にする. 
* PEP 709; 内包表記のインライン化: PEP 709 内包表記のインライン化. 
* エラーメッセージの改善: エラーメッセージの改善<3>. 

型ヒントに関連する新しい機能

* PEP 692; Using TypedDict for more precise **kwargs typing: PEP 692 Using TypedDict for more precise **kwargs typing. 
* PEP 698; Override Decorator for Static Typing: PEP 698 Override Decorator for Static Typing. 

改良されたモジュール

* array:: 
* asyncio: asyncio<5>. 
* calendar: calendar<2>. 
* csv:: 
* dis: dis<3>. 
* fractions: fractions<3>. 
* importlib.resources: importlib resources. 
* inspect: inspect<2>. 
* itertools: itertools<3>. 
* math: math<3>. 
* os: os<3>. 
* os.path: os path<3>. 
* pathlib: pathlib<6>. 
* プラットフォーム: プラットフォーム<2>. 
* pdb: pdb<4>. 
* random: random<2>. 
* shutil: shutil<2>. 
* sqlite3: sqlite3<3>. 
* statistics: statistics<2>. 
* sys: sys<3>. 
* tempfile: tempfile<2>. 
* threading: threading<2>. 
* tkinter: tkinter<3>. 
* tokenize:: 
* types: types<3>. 
* typing: typing<4>. 
* unicodedata: unicodedata<3>. 
* unittest: unittest<3>. 
* uuid: uuid<3>. 

非推奨

* Pending removal in Python 3.13: Pending removal in Python 3 13. 
* Pending removal in Python 3.14: Pending removal in Python 3 14<3>. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<5>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<5>. 
* Pending removal in Python 3.17: Pending removal in Python 3 17<3>. 
* Pending removal in future versions: Pending removal in future versions<5>. 

削除

* asynchat and asyncore:: 
* configparser: configparser<4>. 
* distutils:: 
* ensurepip:: 
* enum: enum<2>. 
* ftplib:: 
* gzip:: 
* hashlib:: 
* importlib: importlib<2>. 
* imp:: 
* io: io<4>. 
* locale: locale<2>. 
* smtpd:: 
* sqlite3: sqlite3<4>. 
* ssl: ssl<3>. 
* unittest: unittest<4>. 
* webbrowser: webbrowser<3>. 
* xml.etree.ElementTree: xml etree ElementTree. 
* zipimport: zipimport<2>. 
* その他:: 

Python 3.12 への移植

* Python API の変更: Python API の変更<3>. 

C API の変更

* 新しい機能: 新しい機能<5>. 
* Python 3.12 への移植: Python 3 12 への移植<2>. 
* 非推奨: 非推奨<3>. 
* 削除: 削除<3>. 

非推奨

* Pending removal in Python 3.14: Pending removal in Python 3 14<4>. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<6>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<6>. 
* Pending removal in future versions: Pending removal in future versions<6>. 

What's New In Python 3.11

* 概要: 概要 -- リリースハイライト<4>. リリースハイライト
* 新しい機能: 新しい機能<6>. 
* 型ヒントに関連する新しい機能: 型ヒントに関連する新しい機能<2>. 
* その他の言語変更: その他の言語変更<3>. 
* その他の CPython の実装の変更:: 
* 新たなモジュール: 新たなモジュール<3>. 
* 改良されたモジュール: 改良されたモジュール<3>. 
* 最適化: 最適化<4>. 
* Faster CPython:: 
* CPython バイトコードの変更: CPython バイトコードの変更<3>. 
* 非推奨: 非推奨<4>. 
* Pending Removal in Python 3.12: Pending Removal in Python 3 12. 
* 削除: 削除<4>. 
* Porting to Python 3.11: Porting to Python 3 11. 
* Build Changes: Build Changes<3>. 
* C API の変更: C API の変更<5>. 
* Python 3.11.4での重要な変更点: Python 3 11 4での重要な変更点. 
* Python 3.11.5での重要な変更点: Python 3 11 5での重要な変更点. 

新しい機能

* PEP 657; トレースバックのエラー位置の詳細化: PEP 657 トレースバックのエラー位置の詳細化. 
* PEP 654; 例外グループと except*: PEP 654 例外グループと except*. 
* PEP 678; ノートによって例外を充実させる: PEP 678 ノートによって例外を充実させる. 
* Windows py.exe ランチャーの改善: Windows py exe ランチャーの改善. 

型ヒントに関連する新しい機能

* PEP 646; Variadic generics: PEP 646 Variadic generics. 
* PEP 655; Marking individual TypedDict items as required or not-required: PEP 655 Marking individual TypedDict items as required or not-required. 
* PEP 673; Self 型: PEP 673 Self 型. 
* PEP 675; Arbitrary literal string type: PEP 675 Arbitrary literal string type. 
* PEP 681; Data class transforms: PEP 681 Data class transforms. 
* PEP 563 may not be the future:: 

改良されたモジュール

* asyncio: asyncio<6>. 
* contextlib:: 
* データクラス:: 
* datetime: datetime<2>. 
* enum: enum<3>. 
* fcntl:: 
* fractions: fractions<4>. 
* functools: functools<2>. 
* gzip: gzip<2>. 
* hashlib: hashlib<2>. 
* IDLE と idelelib:: 
* inspect: inspect<3>. 
* locale: locale<3>. 
* logging:: 
* math: math<4>. 
* operator: operator<2>. 
* os: os<4>. 
* pathlib: pathlib<7>. 
* re: re<4>. 
* shutil: shutil<3>. 
* socket: socket<2>. 
* sqlite3: sqlite3<5>. 
* string:: 
* sys: sys<4>. 
* sysconfig: sysconfig<2>. 
* tempfile: tempfile<3>. 
* threading: threading<3>. 
* time: time<2>. 
* tkinter: tkinter<4>. 
* traceback: traceback<2>. 
* typing: typing<5>. 
* unicodedata: unicodedata<4>. 
* unittest: unittest<5>. 
* venv: venv<2>. 
* warnings: warnings<2>. 
* zipfile: zipfile<2>. 

Faster CPython

* Faster Startup:: 
* Faster Runtime:: 
* Misc:: 
* FAQ:: 
* About:: 

Faster Startup

* Frozen imports / Static code objects:: 

Faster Runtime

* Cheaper@comma{} lazy Python frames: Cheaper lazy Python frames. 
* Inlined Python function calls:: 
* PEP 659; Specializing Adaptive Interpreter: PEP 659 Specializing Adaptive Interpreter. 

FAQ

* How should I write my code to utilize these speedups?:: 
* Will CPython 3.11 use more memory?: Will CPython 3 11 use more memory?. 
* I don't see any speedups in my workload. Why?: I don't see any speedups in my workload Why?. 
* Is there a JIT compiler?:: 

CPython バイトコードの変更

* New opcodes:: 
* Replaced opcodes:: 
* Changed/removed opcodes:: 

非推奨

* Language/Builtins:: 
* モジュール:: 
* Standard Library:: 

C API の変更

* 新しい機能: 新しい機能<7>. 
* Porting to Python 3.11: Porting to Python 3 11<2>. 
* 非推奨: 非推奨<5>. 
* Pending Removal in Python 3.12: Pending Removal in Python 3 12<2>. 
* 削除: 削除<5>. 

Python 3.11.4での重要な変更点

* tarfile: tarfile<2>. 

Python 3.11.5での重要な変更点

* OpenSSL:: 

What's New In Python 3.10

* 概要: 概要 -- リリースハイライト<5>. リリースハイライト
* 新しい機能: 新しい機能<8>. 
* 型ヒントに関連する新しい機能: 型ヒントに関連する新しい機能<3>. 
* その他の言語変更: その他の言語変更<4>. 
* 新たなモジュール: 新たなモジュール<4>. 
* 改良されたモジュール: 改良されたモジュール<4>. 
* 最適化: 最適化<5>. 
* 非推奨: 非推奨<6>. 
* 削除: 削除<6>. 
* Porting to Python 3.10: Porting to Python 3 10. 
* CPython バイトコードの変更: CPython バイトコードの変更<4>. 
* Build Changes: Build Changes<4>. 
* C API の変更: C API の変更<7>. 
* Notable security feature in 3.10.7: Notable security feature in 3 10 7. 
* Notable security feature in 3.10.8: Notable security feature in 3 10 8. 
* Notable changes in 3.10.12: Notable changes in 3 10 12. 

新しい機能

* カッコ内のコンテキストマネージャー:: 
* エラーメッセージの改善: エラーメッセージの改善<4>. 
* PEP 626; デバッグおよびその他のツール用の正確な行番号。: PEP 626 デバッグおよびその他のツール用の正確な行番号。. 
* PEP 634; 構造的パターンマッチ: PEP 634 構造的パターンマッチ. 
* Optional EncodingWarning and encoding="locale" option:: 

エラーメッセージの改善

* SyntaxErrors:: 
* IndentationErrors:: 
* AttributeErrors:: 
* NameErrors:: 

PEP 634: 構造的パターンマッチ

* 構文と演算:: 
* 宣言的なアプローチ:: 
* 単純パターン; リテラルとのマッチ: 単純パターン リテラルとのマッチ. 
* リテラルと変数を組み合わせたパターン:: 
* パターンとクラス:: 
* ネストしたパターン:: 
* 複雑なパターンとワイルドカード:: 
* ガード:: 
* その他の主要な機能:: 

単純パターン: リテラルとのマッチ

* ワイルドカードがないときの振る舞い:: 

パターンとクラス

* 位置パラメータを用いたパターン:: 

型ヒントに関連する新しい機能

* PEP 604; New Type Union Operator: PEP 604 New Type Union Operator. 
* PEP 612; Parameter Specification Variables: PEP 612 Parameter Specification Variables. 
* PEP 613; TypeAlias: PEP 613 TypeAlias. 
* PEP 647; User-Defined Type Guards: PEP 647 User-Defined Type Guards. 

改良されたモジュール

* asyncio: asyncio<7>. 
* argparse: argparse<4>. 
* array: array<2>. 
* asynchat@comma{} asyncore@comma{} smtpd: asynchat asyncore smtpd. 
* base64: base64<3>. 
* bdb: bdb<2>. 
* bisect:: 
* codecs:: 
* collections.abc: collections abc. 
* contextlib: contextlib<2>. 
* curses: curses<2>. 
* データクラス: データクラス<2>. 
* distutils: distutils<2>. 
* doctest: doctest<2>. 
* エンコーディング:: 
* enum: enum<4>. 
* fileinput:: 
* faulthandler: faulthandler<2>. 
* gc: gc<2>. 
* glob: glob<2>. 
* hashlib: hashlib<3>. 
* hmac: hmac<2>. 
* IDLE と idelelib: IDLE と idelelib<2>. 
* importlib.metadata: importlib metadata<2>. 
* inspect: inspect<4>. 
* itertools: itertools<4>. 
* linecache: linecache<2>. 
* os: os<5>. 
* os.path: os path<4>. 
* pathlib: pathlib<8>. 
* プラットフォーム: プラットフォーム<3>. 
* pprint:: 
* py_compile:: 
* pyclbr:: 
* shelve:: 
* statistics: statistics<3>. 
* site: site<2>. 
* socket: socket<3>. 
* ssl: ssl<4>. 
* sqlite3: sqlite3<6>. 
* sys: sys<5>. 
* _thread:: 
* threading: threading<4>. 
* traceback: traceback<3>. 
* types: types<4>. 
* typing: typing<6>. 
* unittest: unittest<6>. 
* urllib.parse: urllib parse. 
* xml: xml<2>. 
* zipimport: zipimport<3>. 

データクラス

* __slots__:: 
* Keyword-only fields:: 

Porting to Python 3.10

* Changes in the Python syntax:: 
* Python API の変更: Python API の変更<4>. 
* C API の変更: C API の変更<6>. 

C API の変更

* PEP 652; Maintaining the Stable ABI: PEP 652 Maintaining the Stable ABI. 
* 新しい機能: 新しい機能<9>. 
* Porting to Python 3.10: Porting to Python 3 10<2>. 
* 非推奨: 非推奨<7>. 
* 削除: 削除<7>. 

Notable changes in 3.10.12

* tarfile: tarfile<3>. 

What's New In Python 3.9

* 概要: 概要 -- リリースハイライト<6>. リリースハイライト
* コード中の非推奨警告(DeprecationWarning)をチェックして下さい: コード中の非推奨警告 DeprecationWarning をチェックして下さい. 
* 新しい機能: 新しい機能<10>. 
* その他の言語変更: その他の言語変更<5>. 
* 新たなモジュール: 新たなモジュール<5>. 
* 改良されたモジュール: 改良されたモジュール<5>. 
* 最適化: 最適化<6>. 
* 非推奨: 非推奨<8>. 
* 削除: 削除<8>. 
* Python 3.9への移植: Python 3 9への移植. 
* Build Changes: Build Changes<5>. 
* C API の変更: C API の変更<9>. 
* Python 3.9.1 での重要な変更点: Python 3 9 1 での重要な変更点. 
* Python 3.9.2 での重要な変更点: Python 3 9 2 での重要な変更点. 
* Python 3.9.3 での重要な変更点: Python 3 9 3 での重要な変更点. 
* Python 3.9.5での重要な変更点: Python 3 9 5での重要な変更点. 
* Notable security feature in 3.9.14: Notable security feature in 3 9 14. 
* Notable changes in 3.9.17: Notable changes in 3 9 17. 

新しい機能

* 辞書のマージと更新演算子:: 
* prefixとsuffixを削除する新しい文字列メソッド:: 
* 標準コレクション型の型ヒントにおける総称型 (generics) の使用: 標準コレクション型の型ヒントにおける総称型 generics の使用. 
* 新しいパーサー:: 

新たなモジュール

* zoneinfo:: 
* graphlib: graphlib<2>. 

改良されたモジュール

* ast: ast<4>. 
* asyncio: asyncio<8>. 
* compileall: compileall<2>. 
* concurrent.futures: concurrent futures<3>. 
* curses: curses<3>. 
* datetime: datetime<3>. 
* distutils: distutils<3>. 
* fcntl: fcntl<2>. 
* ftplib: ftplib<2>. 
* gc: gc<3>. 
* hashlib: hashlib<4>. 
* http: http<2>. 
* IDLE と idelelib: IDLE と idelelib<3>. 
* imaplib: imaplib<2>. 
* importlib: importlib<3>. 
* inspect: inspect<5>. 
* ipaddress: ipaddress<2>. 
* math: math<5>. 
* multiprocessing: multiprocessing<3>. 
* nntplib:: 
* os: os<6>. 
* pathlib: pathlib<9>. 
* pdb: pdb<5>. 
* poplib:: 
* pprint: pprint<2>. 
* pydoc: pydoc<2>. 
* random: random<3>. 
* signal:: 
* smtplib:: 
* socket: socket<4>. 
* time: time<3>. 
* sys: sys<6>. 
* tracemalloc:: 
* typing: typing<7>. 
* unicodedata: unicodedata<5>. 
* venv: venv<3>. 
* xml: xml<3>. 

Python 3.9への移植

* Python API の変更: Python API の変更<5>. 
* C API の変更: C API の変更<8>. 
* CPython バイトコードの変更: CPython バイトコードの変更<5>. 

C API の変更

* 新しい機能: 新しい機能<11>. 
* Python 3.9への移植: Python 3 9への移植<2>. 
* 削除: 削除<9>. 

Python 3.9.1 での重要な変更点

* typing: typing<8>. 
* macOS 11.0 (Big Sur) と Appleシリコンの Mac のサポート: macOS 11 0 Big Sur と Appleシリコンの Mac のサポート. 

Python 3.9.2 での重要な変更点

* collections.abc: collections abc<2>. 
* urllib.parse: urllib parse<2>. 

Python 3.9.5での重要な変更点

* urllib.parse: urllib parse<3>. 

Notable changes in 3.9.17

* tarfile: tarfile<4>. 

What's New In Python 3.8

* 概要: 概要 -- リリースハイライト<7>. リリースハイライト
* 新しい機能: 新しい機能<12>. 
* その他の言語変更: その他の言語変更<6>. 
* 新たなモジュール: 新たなモジュール<6>. 
* 改良されたモジュール: 改良されたモジュール<6>. 
* 最適化: 最適化<7>. 
* ビルドならびに C API の変更:: 
* 非推奨: 非推奨<9>. 
* API と機能の削除:: 
* Python 3.8 への移植: Python 3 8 への移植. 
* Python3.8.1 での重要な変更点: Python3 8 1 での重要な変更点. 
* Python3.8.2 での重要な変更点: Python3 8 2 での重要な変更点. 
* Notable changes in Python 3.8.3: Notable changes in Python 3 8 3. 
* Python3.8.8 での重要な変更点: Python3 8 8 での重要な変更点. 
* Notable changes in Python 3.8.9: Notable changes in Python 3 8 9. 
* Notable changes in Python 3.8.10: Notable changes in Python 3 8 10. 
* Notable changes in Python 3.8.10: Notable changes in Python 3 8 10<2>. 
* Notable changes in Python 3.8.12: Notable changes in Python 3 8 12. 
* Notable security feature in 3.8.14: Notable security feature in 3 8 14. 
* Notable changes in 3.8.17: Notable changes in 3 8 17. 

新しい機能

* 代入式:: 
* 位置専用引数:: 
* コンパイル済みのバイトコードファイルのキャッシュを併存させるファイルシステム:: 
* デバッグビルドとリリースビルドのABI 共通化:: 
* f-string での = を用いたオブジェクトの表現:: 
* PEP 578; Pythonランタイムの監査フック: PEP 578 Pythonランタイムの監査フック. 
* PEP 587; Python 初期化設定: PEP 587 Python 初期化設定. 
* PEP 590; Vectorcall; a fast calling protocol for CPython: PEP 590 Vectorcall a fast calling protocol for CPython. 
* Pickle プロトコルバージョン 5 による帯域外データバッファ:: 

改良されたモジュール

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

Python 3.8 への移植

* Python の挙動の変更:: 
* Python API の変更: Python API の変更<6>. 
* C API の変更: C API の変更<10>. 
* CPython バイトコードの変更: CPython バイトコードの変更<6>. 
* Demos and Tools: Demos and Tools<2>. 

Notable changes in Python 3.8.10

* macOS 11.0 (Big Sur) と Appleシリコンの Mac のサポート: macOS 11 0 Big Sur と Appleシリコンの Mac のサポート<2>. 

Notable changes in Python 3.8.10

* urllib.parse: urllib parse<4>. 

Notable changes in Python 3.8.12

* Python API の変更: Python API の変更<7>. 

Notable changes in 3.8.17

* tarfile: tarfile<6>. 

What's New In Python 3.7

* 概要: 概要 -- リリースハイライト<8>. リリースハイライト
* 新しい機能: 新しい機能<13>. 
* その他の言語変更: その他の言語変更<7>. 
* 新たなモジュール: 新たなモジュール<7>. 
* 改良されたモジュール: 改良されたモジュール<7>. 
* C API の変更: C API の変更<11>. 
* Build Changes: Build Changes<6>. 
* 最適化: 最適化<8>. 
* その他の CPython の実装の変更: その他の CPython の実装の変更<2>. 
* 非推奨の Python の挙動:: 
* 非推奨の Python モジュール、関数、メソッド:: 
* C API の非推奨の関数ならびに型:: 
* サポート対象プラットフォームからの除外:: 
* API と機能の削除: API と機能の削除<2>. 
* Module Removals:: 
* Windows-only Changes:: 
* 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 での重要な変更点. 
* Notable changes in Python 3.7.11: Notable changes in Python 3 7 11. 
* Notable security feature in 3.7.14: Notable security feature in 3 7 14. 

新しい機能

* PEP 563; アノテーションの遅延評価: 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; Show DeprecationWarning in __main__: PEP 565 Show DeprecationWarning in __main__. 
* PEP 560; typing モジュールとジェネリック型に対する言語コアによるサポート: PEP 560 typing モジュールとジェネリック型に対する言語コアによるサポート. 
* PEP 552; Hash-based .pyc Files: PEP 552 Hash-based pyc Files. 
* PEP 545; Python Documentation Translations: PEP 545 Python Documentation Translations. 
* Python Development Mode (-X dev): Python Development Mode -X dev. 

新たなモジュール

* contextvars: contextvars<2>. 
* データクラス: データクラス<3>. 
* importlib.resources: importlib resources<2>. 

改良されたモジュール

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

非推奨の Python モジュール、関数、メソッド

* aifc:: 
* asyncio: asyncio<11>. 
* collections: collections<3>. 
* dbm: dbm<3>. 
* enum: enum<6>. 
* gettext: gettext<2>. 
* importlib: importlib<5>. 
* locale: locale<5>. 
* macpath:: 
* threading: threading<6>. 
* socket: socket<7>. 
* ssl: ssl<7>. 
* sunau:: 
* sys: sys<9>. 
* wave:: 

Python 3.7 への移植

* Python の挙動の変更: Python の挙動の変更<2>. 
* Python API の変更: Python API の変更<8>. 
* C API の変更: C API の変更<12>. 
* CPython バイトコードの変更: CPython バイトコードの変更<7>. 
* Windows-only Changes: Windows-only Changes<2>. 
* その他の CPython の実装の変更: その他の CPython の実装の変更<3>. 

What's New In Python 3.6

* 概要: 概要 -- リリースハイライト<9>. リリースハイライト
* 新しい機能: 新しい機能<14>. 
* その他の言語変更: その他の言語変更<8>. 
* 新たなモジュール: 新たなモジュール<8>. 
* 改良されたモジュール: 改良されたモジュール<8>. 
* 最適化: 最適化<9>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<2>. 
* その他の改善:: 
* 非推奨: 非推奨<10>. 
* 削除: 削除<10>. 
* Python 3.6 への移植: Python 3 6 への移植. 
* Notable changes in Python 3.6.2: Notable changes in Python 3 6 2. 
* Notable changes in Python 3.6.4: Notable changes in Python 3 6 4. 
* Notable changes in Python 3.6.5: Notable changes in Python 3 6 5. 
* Notable changes in Python 3.6.7: Notable changes in Python 3 6 7. 
* Notable changes in Python 3.6.10: Notable changes in Python 3 6 10. 
* Notable changes in Python 3.6.13: Notable changes in Python 3 6 13. 
* Notable changes in Python 3.6.14: Notable changes in Python 3 6 14. 

新しい機能

* PEP 498; フォーマット済み文字列リテラル: PEP 498 フォーマット済み文字列リテラル. 
* PEP 526; 変数アノテーションの文法: PEP 526 変数アノテーションの文法. 
* PEP 515; 数値リテラル内のアンダースコア: PEP 515 数値リテラル内のアンダースコア. 
* PEP 525; 非同期ジェネレータ: PEP 525 非同期ジェネレータ. 
* PEP 530; 非同期内包表記: PEP 530 非同期内包表記. 
* PEP 487; Simpler customization of class creation: PEP 487 Simpler customization of class creation. 
* 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 and SystemTap probing support:: 

新たなモジュール

* secrets:: 

改良されたモジュール

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

非推奨

* 新たなキーワード:: 
* 非推奨の Python 挙動:: 
* 非推奨の Python モジュール、関数、メソッド: 非推奨の Python モジュール、関数、メソッド<2>. 
* xml: xml<6>. 
* C API の非推奨の関数ならびに型: C API の非推奨の関数ならびに型<2>. 
* 非推奨のビルドオプション:: 

非推奨の Python モジュール、関数、メソッド

* asynchat:: 
* asyncore:: 
* dbm: dbm<4>. 
* distutils: distutils<6>. 
* grp:: 
* importlib: importlib<7>. 
* os: os<10>. 
* re: re<7>. 
* ssl: ssl<9>. 
* tkinter: tkinter<8>. 
* venv: venv<6>. 

削除

* API と機能の削除: API と機能の削除<3>. 

Python 3.6 への移植

* 'python' コマンドの挙動の変更:: 
* Python API の変更: Python API の変更<9>. 
* C API の変更: C API の変更<13>. 
* CPython バイトコードの変更: CPython バイトコードの変更<8>. 

Notable changes in Python 3.6.2

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

What's New In Python 3.5

* 概要: 概要 -- リリースハイライト<10>. リリースハイライト
* 新しい機能: 新しい機能<15>. 
* その他の言語変更: その他の言語変更<9>. 
* 新たなモジュール: 新たなモジュール<9>. 
* 改良されたモジュール: 改良されたモジュール<9>. 
* その他のモジュールレベルの変更:: 
* 最適化: 最適化<10>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<3>. 
* 非推奨: 非推奨<11>. 
* 削除: 削除<11>. 
* Python 3.5 への移植: Python 3 5 への移植. 
* Notable changes in Python 3.5.4: Notable changes in Python 3 5 4. 

新しい機能

* PEP 492 - コルーチン、 async と await 構文:: 
* PEP 465 - 行列の乗算専用の中置演算子:: 
* PEP 448 - 追加可能なアンパックへの一般化:: 
* PEP 461 - bytes および bytearray のパーセント書式化サポート:: 
* PEP 484 - 型ヒント:: 
* PEP 471 - os.scandir() 関数: PEP 471 - os scandir 関数 -- より良く、速いディレクトリイテレータ. より良く、速いディレクトリイテレータ
* PEP 475; EINTR で失敗したシステムコールの再試行: PEP 475 EINTR で失敗したシステムコールの再試行. 
* PEP 479; ジェネレータ内の StopIteration の処理の変更: PEP 479 ジェネレータ内の StopIteration の処理の変更. 
* PEP 485; 近似的に等しいことを調べる関数: PEP 485 近似的に等しいことを調べる関数. 
* PEP 486; Python ランチャーが仮想環境を認識する: PEP 486 Python ランチャーが仮想環境を認識する. 
* PEP 488; PYO ファイルの廃止: PEP 488 PYO ファイルの廃止. 
* PEP 489; 拡張モジュールの多段階初期化: PEP 489 拡張モジュールの多段階初期化. 

新たなモジュール

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

改良されたモジュール

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

ssl

* メモリ BIO サポート:: 
* Application-Layer Protocol Negotiation Support:: 
* その他の変更:: 

非推奨

* 新たなキーワード: 新たなキーワード<2>. 
* 非推奨の Python の挙動: 非推奨の Python の挙動<2>. 
* サポートされないオペレーティングシステム:: 
* 非推奨の Python モジュール、関数、メソッド: 非推奨の Python モジュール、関数、メソッド<3>. 

削除

* API と機能の削除: API と機能の削除<4>. 

Python 3.5 への移植

* Python の挙動の変更: Python の挙動の変更<3>. 
* Python API の変更: Python API の変更<10>. 
* C API の変更: C API の変更<14>. 

Notable changes in 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>. 

What's New In Python 3.4

* 概要: 概要 -- リリースハイライト<11>. リリースハイライト
* 新しい機能: 新しい機能<16>. 
* 新たなモジュール: 新たなモジュール<10>. 
* 改良されたモジュール: 改良されたモジュール<10>. 
* CPython の実装の変更:: 
* 非推奨: 非推奨<12>. 
* 削除: 削除<12>. 
* Python 3.4 への移植: Python 3 4 への移植. 
* 3.4.3 の変更: 3 4 3 の変更. 

新しい機能

* PEP 453; Python インストール時の PIP の明示的なブートストラッピング: PEP 453 Python インストール時の PIP の明示的なブートストラッピング. 
* PEP 446; 新規作成されたファイル記述子は継承不可: PEP 446 新規作成されたファイル記述子は継承不可. 
* Codec 処理の改良:: 
* PEP 451; インポートシステムのための ModuleSpec 型: PEP 451 インポートシステムのための ModuleSpec 型. 
* その他の言語変更: その他の言語変更<10>. 

PEP 453: Python インストール時の PIP の明示的なブートストラッピング

* デフォルトでの pip のブートストラッピング:: 
* ドキュメントの変更:: 

新たなモジュール

* asyncio: asyncio<14>. 
* ensurepip: ensurepip<2>. 
* enum: enum<9>. 
* pathlib: pathlib<14>. 
* selectors: selectors<2>. 
* statistics: statistics<6>. 
* tracemalloc: tracemalloc<4>. 

改良されたモジュール

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

CPython の実装の変更

* PEP 445; CPython のメモリアロケータのカスタマイズ: PEP 445 CPython のメモリアロケータのカスタマイズ. 
* PEP 442; オブジェクトの安全なファイナライゼーション: PEP 442 オブジェクトの安全なファイナライゼーション. 
* PEP 456; 安全で取り換え可能なハッシュアルゴリズム: PEP 456 安全で取り換え可能なハッシュアルゴリズム. 
* PEP 436; Argument Clinic: PEP 436 Argument Clinic. 
* その他のビルド並びに C API の変更:: 
* その他の改善: その他の改善<2>. 
* 大幅な最適化:: 

非推奨

* Python API の非推奨項目:: 
* 非推奨の機能:: 

削除

* サポートされなくなったオペレーティングシステム:: 
* API と機能の削除: API と機能の削除<5>. 
* コードの整理:: 

Python 3.4 への移植

* 'python' コマンドの挙動の変更: 'python' コマンドの挙動の変更<2>. 
* Python API の変更: Python API の変更<11>. 
* C API の変更: C API の変更<15>. 

3.4.3 の変更

* PEP 476; stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化: PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化. 

What's New In Python 3.3

* 概要: 概要 -- リリースハイライト<12>. リリースハイライト
* 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; 明示的なユニコードリテラル: PEP 414 明示的なユニコードリテラル. 
* PEP 3155; クラスと関数の正規名: PEP 3155 クラスと関数の正規名. 
* PEP 412; キー共有辞書: PEP 412 キー共有辞書. 
* PEP 362; 関数シグニチャオブジェクト: PEP 362 関数シグニチャオブジェクト. 
* PEP 421; sys.implementation の追加: PEP 421 sys implementation の追加. 
* インポート実装としての importlib の使用:: 
* その他の言語変更: その他の言語変更<11>. 
* 細粒度のインポートロック:: 
* 組み込みの関数と型:: 
* 新たなモジュール: 新たなモジュール<11>. 
* 改良されたモジュール: 改良されたモジュール<11>. 
* 最適化: 最適化<11>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<4>. 
* 非推奨: 非推奨<13>. 
* Python 3.3 への移植: Python 3 3 への移植. 

PEP 3118: 新たなメモリビューの実装とバッファプロトコルのドキュメント

* フィーチャー:: 
* API の変更:: 

PEP 393: 文字列の柔軟な表現

* 機能性:: 
* 性能およびリソース使用量:: 

PEP 421: sys.implementation の追加

* SimpleNamespace:: 

インポート実装としての importlib の使用

* 新たな API:: 
* 目に見える変化:: 

新たなモジュール

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

改良されたモジュール

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

decimal

* フィーチャー: フィーチャー<2>. 
* API の変更: API の変更<2>. 

email

* ポリシーフレームワーク:: 
* 新規ヘッダ API を伴った暫定ポリシー:: 
* その他のAPIの変更:: 

非推奨

* サポートされないオペレーティングシステム: サポートされないオペレーティングシステム<2>. 
* 非推奨の Python モジュール、関数、メソッド: 非推奨の Python モジュール、関数、メソッド<4>. 
* C API の非推奨の関数ならびに型: C API の非推奨の関数ならびに型<3>. 
* 非推奨の機能: 非推奨の機能<2>. 

Python 3.3 への移植

* Python コードの移植:: 
* C コードの移植:: 
* C 拡張のビルド:: 
* コマンドラインスイッチの変更:: 

What's New In Python 3.2

* PEP 384; 安定 ABI の定義: PEP 384 安定 ABI の定義. 
* PEP 389; argparse コマンドライン解析モジュール: PEP 389 argparse コマンドライン解析モジュール. 
* PEP 391; logging の辞書ベースの設定: PEP 391 logging の辞書ベースの設定. 
* PEP 3148; concurrent.futures モジュール: PEP 3148 concurrent futures モジュール. 
* PEP 3147; PYC リポジトリーディレクトリ: PEP 3147 PYC リポジトリーディレクトリ. 
* PEP 3149; ABI バージョンでタグ付けされた .so ファイル: PEP 3149 ABI バージョンでタグ付けされた so ファイル. 
* PEP 3333; Python Web Server Gateway Interface v1.0.1: PEP 3333 Python Web Server Gateway Interface v1 0 1. 
* その他の言語変更: その他の言語変更<12>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール:: 
* マルチスレッディング:: 
* 最適化: 最適化<12>. 
* Unicode 文字列型:: 
* Codecs:: 
* ドキュメント:: 
* IDLE:: 
* コードリポジトリ:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<5>. 
* Python 3.2 への移植: Python 3 2 への移植. 

新たなモジュール、改良されたモジュール、非推奨のモジュール

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

What's New In Python 3.1

* PEP 372; 順序付き辞書: PEP 372 順序付き辞書. 
* PEP 378; 1000区切りのための書式指定子: PEP 378 1000区切りのための書式指定子. 
* その他の言語変更: その他の言語変更<13>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール: 新たなモジュール、改良されたモジュール、非推奨のモジュール<2>. 
* 最適化: 最適化<13>. 
* IDLE: IDLE<2>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<6>. 
* Python 3.1 への移植: Python 3 1 への移植. 

What's New In Python 3.0

* よくある悩みの種:: 
* 構文の変更の概要:: 
* Python 2.6 で既にあった変更: Python 2 6 で既にあった変更. 
* ライブラリの変更:: 
* PEP 3101; 文字列整形の新たなアプローチ: PEP 3101 文字列整形の新たなアプローチ. 
* 例外に関する変更:: 
* その他の変更: その他の変更<2>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<7>. 
* 性能:: 
* Python 3.0 への移植: Python 3 0 への移植. 

よくある悩みの種

* print関数:: 
* リストからビューおよびイテレータへ:: 
* 順序比較:: 
* 整数:: 
* Unicode 対 8 ビット、ではなく、テキスト対データに:: 

構文の変更の概要

* 新たな構文:: 
* 変更された構文:: 
* 削除された操作:: 

その他の変更

* 演算子と特殊メソッド:: 
* 組み込み:: 

What's New in Python 2.7

* Python 2.x の今後: Python 2 x の今後. 
* Deprecation Warnings の扱いの変更:: 
* Python 3.1 の機能: Python 3 1 の機能. 
* PEP 372; collections に順序付き辞書を追加: PEP 372 collections に順序付き辞書を追加. 
* PEP 378; 1000区切りのための書式指定子: PEP 378 1000区切りのための書式指定子<2>. 
* PEP 389; コマンドライン解析のための argparse モジュール: PEP 389 コマンドライン解析のための argparse モジュール. 
* PEP 391; logging の辞書ベースの設定: PEP 391 logging の辞書ベースの設定<2>. 
* PEP 3106; 辞書 View: PEP 3106 辞書 View. 
* PEP 3137; memoryview オブジェクト: PEP 3137 memoryview オブジェクト. 
* その他の言語変更: その他の言語変更<14>. 
* 新しいモジュールと改良されたモジュール:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<8>. 
* その他の変更と修正:: 
* Python 2.7 への移植: Python 2 7 への移植. 
* Python 2.7 メンテナンスリリースで追加された新機能: Python 2 7 メンテナンスリリースで追加された新機能. 
* 謝辞:: 

その他の言語変更

* インタプリタの変更:: 
* 最適化: 最適化<14>. 

新しいモジュールと改良されたモジュール

* 新しいモジュール; importlib: 新しいモジュール importlib. 
* 新しいモジュール; sysconfig: 新しいモジュール sysconfig. 
* ttk; Tk のテーマ付きウィジェット: ttk Tk のテーマ付きウィジェット. 
* 更新されたモジュール; unittest: 更新されたモジュール unittest. 
* 更新されたモジュール; ElementTree 1.3: 更新されたモジュール ElementTree 1 3. 

ビルドならびに C API の変更

* カプセル:: 
* ポート特有の変更; Windows: ポート特有の変更 Windows. 
* ポート特有の変更; Mac OS X: ポート特有の変更 Mac OS X. 
* ポート特有の変更; FreeBSD: ポート特有の変更 FreeBSD. 

Python 2.7 メンテナンスリリースで追加された新機能

* デバッグモード用の2つの新しい環境変数:: 
* PEP 434; IDLE 拡張についての全てのブランチにおける例外的な扱い: PEP 434 IDLE 拡張についての全てのブランチにおける例外的な扱い. 
* PEP 466; Python 2.7 のためのネットワークセキュリティ拡張: PEP 466 Python 2 7 のためのネットワークセキュリティ拡張. 
* PEP 477; Python 2.7 への ensurepip (PEP 453) バックポート: PEP 477 Python 2 7 への ensurepip PEP 453 バックポート. 
* PEP 476; stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化: PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化<2>. 
* PEP 493; HTTPS verification migration tools for Python 2.7: PEP 493 HTTPS verification migration tools for Python 2 7. 
* 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: Python 2.7 への ensurepip (PEP 453) バックポート

* デフォルトでの pip のブートストラッピング: デフォルトでの pip のブートストラッピング<2>. 
* ドキュメントの変更: ドキュメントの変更<2>. 

What's New in 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; multiprocessing パッケージ: PEP 371 multiprocessing パッケージ. 
* 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; 数値の型階層: PEP 3141 数値の型階層. 
* その他の言語変更: その他の言語変更<15>. 
* 新しいモジュールと改良されたモジュール: 新しいモジュールと改良されたモジュール<2>. 
* 非推奨と削除:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<9>. 
* Python 2.6 への移植: Python 2 6 への移植. 
* 謝辞: 謝辞<2>. 

開発プロセスに関する変更

* 新しい課題トラッカー; Roundup: 新しい課題トラッカー Roundup. 
* 新しいドキュメンテーションフォーマット; Sphinx を使っての reStructuredText: 新しいドキュメンテーションフォーマット Sphinx を使っての reStructuredText. 

PEP 343: "with" ステートメント

* コンテキストマネージャを書く:: 
* contextlib モジュール:: 

PEP 3141: 数値の型階層

* fractions モジュール:: 

その他の言語変更

* 最適化: 最適化<15>. 
* インタプリタの変更: インタプリタの変更<2>. 

新しいモジュールと改良されたモジュール

* ast モジュール:: 
* The future_builtins module:: 
* json モジュール; JavaScript オブジェクト記法: json モジュール JavaScript オブジェクト記法. 
* plistlib モジュール; プロパティリストパーサ: plistlib モジュール プロパティリストパーサ. 
* ctypes の強化:: 
* SSL サポートの改善:: 

ビルドならびに C API の変更

* ポート特有の変更; Windows: ポート特有の変更 Windows<2>. 
* ポート特有の変更; Mac OS X: ポート特有の変更 Mac OS X<2>. 
* ポート特有の変更; IRIX: ポート特有の変更 IRIX. 

What's New in Python 2.5

* PEP 308; 条件式 (Conditional Expressions): PEP 308 条件式 Conditional Expressions. 
* PEP 309; 関数の部分適用: PEP 309 関数の部分適用. 
* PEP 314; Metadata for Python Software Packages v1.1: PEP 314 Metadata for Python Software Packages v1 1. 
* PEP 328; 絶対インポート、相対インポート: PEP 328 絶対インポート、相対インポート. 
* 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__' メソッド. 
* その他の言語変更: その他の言語変更<16>. 
* 新たなモジュール、改良されたモジュール、削除されたモジュール:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<10>. 
* Python 2.5 への移植: Python 2 5 への移植. 
* 謝辞: 謝辞<3>. 

PEP 343: "with" ステートメント

* コンテキストマネージャを書く: コンテキストマネージャを書く<2>. 
* contextlib モジュール: contextlib モジュール<2>. 

その他の言語変更

* 対話的なインタプリタの変更:: 
* 最適化: 最適化<16>. 

新たなモジュール、改良されたモジュール、削除されたモジュール

* ctypes パッケージ:: 
* ElementTree パッケージ:: 
* hashlib パッケージ:: 
* sqlite3 パッケージ:: 
* wsgiref パッケージ:: 

ビルドならびに C API の変更

* ポート特有の変更:: 

What's New in Python 2.4

* PEP 218; ビルトインの集合オブジェクト: PEP 218 ビルトインの集合オブジェクト. 
* PEP 237; 長整数と整数を一体化していく: PEP 237 長整数と整数を一体化していく. 
* PEP 289; ジェネレータ式: PEP 289 ジェネレータ式. 
* PEP 292; より単純な文字列置換 (string substitution): PEP 292 より単純な文字列置換 string substitution. 
* PEP 318; 関数とメソッドのためのデコレータ: PEP 318 関数とメソッドのためのデコレータ. 
* PEP 322; 逆順のイテレーション: PEP 322 逆順のイテレーション. 
* PEP 324; 新しい subprocess モジュール: PEP 324 新しい subprocess モジュール. 
* PEP 327; Decimal データ型: PEP 327 Decimal データ型. 
* PEP 328; マルチラインインポート: PEP 328 マルチラインインポート. 
* PEP 331; Locale に依存しない Float/String 変換: PEP 331 Locale に依存しない Float/String 変換. 
* その他の言語変更: その他の言語変更<17>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール: 新たなモジュール、改良されたモジュール、非推奨のモジュール<3>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<11>. 
* Python 2.4 への移植: Python 2 4 への移植. 
* 謝辞: 謝辞<4>. 

PEP 327: Decimal データ型

* なぜ Decimal が必要なのか?:: 
* Decimal 型:: 
* Context 型:: 

その他の言語変更

* 最適化: 最適化<17>. 

新たなモジュール、改良されたモジュール、非推奨のモジュール

* cookielib:: 
* doctest: doctest<5>. 

ビルドならびに C API の変更

* ポート特有の変更: ポート特有の変更<2>. 

What's New in Python 2.3

* PEP 218; 標準の集合データ型: PEP 218 標準の集合データ型. 
* PEP 255; 単純なジェネレータ: PEP 255 単純なジェネレータ. 
* PEP 263; ソースコードのエンコーディング: PEP 263 ソースコードのエンコーディング. 
* PEP 273; Zip アーカイブからモジュールをインポートする: PEP 273 Zip アーカイブからモジュールをインポートする. 
* PEP 277; Windows NT での Unicode ファイル名サポート: PEP 277 Windows NT での Unicode ファイル名サポート. 
* PEP 278; Universal Newline サポート: PEP 278 Universal Newline サポート. 
* PEP 279; enumerate(): PEP 279 enumerate. 
* PEP 282; ロギングパッケージ: PEP 282 ロギングパッケージ. 
* PEP 285; Boolean 型: PEP 285 Boolean 型. 
* PEP 293; コーデックエラーを処理するコールバック: PEP 293 コーデックエラーを処理するコールバック. 
* PEP 301; パッケージインデクスと、 Distutils のためのメタデータ: PEP 301 パッケージインデクスと、 Distutils のためのメタデータ. 
* PEP 302; 新たなインポートフック: PEP 302 新たなインポートフック. 
* PEP 305; カンマ区切り形式ファイル: PEP 305 カンマ区切り形式ファイル. 
* PEP 307; Pickle の機能拡張: PEP 307 Pickle の機能拡張. 
* 拡張スライス:: 
* その他の言語変更: その他の言語変更<18>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール: 新たなモジュール、改良されたモジュール、非推奨のモジュール<4>. 
* Pymalloc; 特殊化されたオブジェクトアロケータ: Pymalloc 特殊化されたオブジェクトアロケータ. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<12>. 
* その他の変更と修正: その他の変更と修正<2>. 
* Python 2.3 への移植: Python 2 3 への移植. 
* 謝辞: 謝辞<5>. 

その他の言語変更

* 文字列に関する変更:: 
* 最適化: 最適化<18>. 

新たなモジュール、改良されたモジュール、非推奨のモジュール

* 日付時刻型:: 
* optparse モジュール:: 

ビルドならびに C API の変更

* ポート特有の変更: ポート特有の変更<3>. 

What's New in Python 2.2

* はじめに:: 
* PEP 252 と PEP 253; 型とクラスについての変更: PEP 252 と PEP 253 型とクラスについての変更. 
* PEP 234; イテレータ: PEP 234 イテレータ. 
* PEP 255; 単純なジェネレータ: PEP 255 単純なジェネレータ<2>. 
* PEP 237; 長整数と整数を一体化していく: PEP 237 長整数と整数を一体化していく<2>. 
* PEP 238; 除算演算子を変更していく: PEP 238 除算演算子を変更していく. 
* Unicode の変更:: 
* PEP 227; 入れ子状のスコープ: PEP 227 入れ子状のスコープ. 
* 新しいモジュールと改良されたモジュール: 新しいモジュールと改良されたモジュール<3>. 
* インタプリタの変更と修正:: 
* その他の変更と修正: その他の変更と修正<3>. 
* 謝辞: 謝辞<6>. 

PEP 252 と PEP 253: 型とクラスについての変更

* 旧と新クラス:: 
* デスクリプタ:: 
* 多重継承; ダイヤモンドルール: 多重継承 ダイヤモンドルール. 
* 属性アクセス:: 
* 関連リンク:: 

What's New in Python 2.1

* はじめに: はじめに<2>. 
* PEP 227; 入れ子状のスコープ: PEP 227 入れ子状のスコープ<2>. 
* PEP 236; __future__ 指示文: PEP 236 __future__ 指示文. 
* PEP 207; 拡張比較: PEP 207 拡張比較. 
* PEP 230; 警告フレームワーク: PEP 230 警告フレームワーク. 
* PEP 229; 新しいビルドシステム: PEP 229 新しいビルドシステム. 
* PEP 205; 弱参照: PEP 205 弱参照. 
* PEP 232; 関数の属性: PEP 232 関数の属性. 
* PEP 235; 大文字小文字を区別しないプラットフォームでのモジュールの読み込み: PEP 235 大文字小文字を区別しないプラットフォームでのモジュールの読み込み. 
* PEP 217; 対話モード用 Display Hook: PEP 217 対話モード用 Display Hook. 
* PEP 208; 新しい型強制モデル: PEP 208 新しい型強制モデル. 
* PEP 241; Pythonソフトウェアパッケージのためのメタデータ: PEP 241 Pythonソフトウェアパッケージのためのメタデータ. 
* 新しいモジュールと改良されたモジュール: 新しいモジュールと改良されたモジュール<4>. 
* その他の変更と修正: その他の変更と修正<4>. 
* 謝辞: 謝辞<7>. 

What's New in Python 2.0

* はじめに: はじめに<3>. 
* Python 1.6 はいかがですか?: Python 1 6 はいかがですか?. 
* 新しい開発プロセス:: 
* Unicode 文字列型: Unicode 文字列型<2>. 
* リストの内包表記:: 
* 累算代入 (Augmented Assignment): 累算代入 Augmented Assignment. 
* 文字列メソッド:: 
* 循環参照のガベージコレクション:: 
* その他の言語コアの変更:: 
* Python 2.0 への移植: Python 2 0 への移植. 
* 拡張と埋め込みについての変更:: 
* Distutils; モジュールの簡単インストール: Distutils モジュールの簡単インストール. 
* XML モジュール:: 
* 更新されたモジュール:: 
* 新しいモジュール: 新しいモジュール<2>. 
* IDLE の改善:: 
* 削除されたモジュール、非推奨となったモジュール:: 
* 謝辞: 謝辞<8>. 

その他の言語コアの変更

* 言語のマイナー変更:: 
* ビルトイン関数の変更:: 

XML モジュール

* SAX2 サポート:: 
* DOM サポート:: 
* PyXML との関係:: 

変更履歴

* Python next:: 
* Python 3.14.3 final: Python 3 14 3 final. 
* Python 3.14.2 final: Python 3 14 2 final. 
* Python 3.14.1 final: Python 3 14 1 final. 
* Python 3.14.0 final: Python 3 14 0 final. 
* Python 3.14.0 release candidate 3: Python 3 14 0 release candidate 3. 
* Python 3.14.0 release candidate 2: Python 3 14 0 release candidate 2. 
* Python 3.14.0 release candidate 1: Python 3 14 0 release candidate 1. 
* Python 3.14.0 beta 4: Python 3 14 0 beta 4. 
* Python 3.14.0 beta 3: Python 3 14 0 beta 3. 
* Python 3.14.0 beta 2: Python 3 14 0 beta 2. 
* Python 3.14.0 beta 1: Python 3 14 0 beta 1. 
* Python 3.14.0 alpha 7: Python 3 14 0 alpha 7. 
* Python 3.14.0 alpha 6: Python 3 14 0 alpha 6. 
* Python 3.14.0 alpha 5: Python 3 14 0 alpha 5. 
* Python 3.14.0 alpha 4: Python 3 14 0 alpha 4. 
* Python 3.14.0 alpha 3: Python 3 14 0 alpha 3. 
* Python 3.14.0 alpha 2: Python 3 14 0 alpha 2. 
* Python 3.14.0 alpha 1: Python 3 14 0 alpha 1. 
* Python 3.13.0 beta 1: Python 3 13 0 beta 1. 
* Python 3.13.0 alpha 6: Python 3 13 0 alpha 6. 
* Python 3.13.0 alpha 5: Python 3 13 0 alpha 5. 
* Python 3.13.0 alpha 4: Python 3 13 0 alpha 4. 
* Python 3.13.0 alpha 3: Python 3 13 0 alpha 3. 
* Python 3.13.0 alpha 2: Python 3 13 0 alpha 2. 
* Python 3.13.0 alpha 1: Python 3 13 0 alpha 1. 
* Python 3.12.0 beta 1: Python 3 12 0 beta 1. 
* Python 3.12.0 alpha 7: Python 3 12 0 alpha 7. 
* Python 3.12.0 alpha 6: Python 3 12 0 alpha 6. 
* Python 3.12.0 alpha 5: Python 3 12 0 alpha 5. 
* Python 3.12.0 alpha 4: Python 3 12 0 alpha 4. 
* Python 3.12.0 alpha 3: Python 3 12 0 alpha 3. 
* Python 3.12.0 alpha 2: Python 3 12 0 alpha 2. 
* Python 3.12.0 alpha 1: Python 3 12 0 alpha 1. 
* Python 3.11.0 beta 1: Python 3 11 0 beta 1. 
* Python 3.11.0 alpha 7: Python 3 11 0 alpha 7. 
* Python 3.11.0 alpha 6: Python 3 11 0 alpha 6. 
* Python 3.11.0 alpha 5: Python 3 11 0 alpha 5. 
* Python 3.11.0 alpha 4: Python 3 11 0 alpha 4. 
* Python 3.11.0 alpha 3: Python 3 11 0 alpha 3. 
* Python 3.11.0 alpha 2: Python 3 11 0 alpha 2. 
* Python 3.11.0 alpha 1: Python 3 11 0 alpha 1. 
* Python 3.10.0 beta 1: Python 3 10 0 beta 1. 
* Python 3.10.0 alpha 7: Python 3 10 0 alpha 7. 
* Python 3.10.0 alpha 6: Python 3 10 0 alpha 6. 
* Python 3.10.0 alpha 5: Python 3 10 0 alpha 5. 
* Python 3.10.0 alpha 4: Python 3 10 0 alpha 4. 
* Python 3.10.0 alpha 3: Python 3 10 0 alpha 3. 
* Python 3.10.0 alpha 2: Python 3 10 0 alpha 2. 
* Python 3.10.0 alpha 1: Python 3 10 0 alpha 1. 
* Python 3.9.0 beta 1: Python 3 9 0 beta 1. 
* Python 3.9.0 alpha 6: Python 3 9 0 alpha 6. 
* Python 3.9.0 alpha 5: Python 3 9 0 alpha 5. 
* Python 3.9.0 alpha 4: Python 3 9 0 alpha 4. 
* Python 3.9.0 alpha 3: Python 3 9 0 alpha 3. 
* Python 3.9.0 alpha 2: Python 3 9 0 alpha 2. 
* Python 3.9.0 alpha 1: Python 3 9 0 alpha 1. 
* Python 3.8.0 beta 1: Python 3 8 0 beta 1. 
* Python 3.8.0 alpha 4: Python 3 8 0 alpha 4. 
* Python 3.8.0 alpha 3: Python 3 8 0 alpha 3. 
* Python 3.8.0 alpha 2: Python 3 8 0 alpha 2. 
* Python 3.8.0 alpha 1: Python 3 8 0 alpha 1. 
* Python 3.7.0 final: Python 3 7 0 final. 
* Python 3.7.0 release candidate 1: Python 3 7 0 release candidate 1. 
* Python 3.7.0 beta 5: Python 3 7 0 beta 5. 
* Python 3.7.0 beta 4: Python 3 7 0 beta 4. 
* Python 3.7.0 beta 3: Python 3 7 0 beta 3. 
* Python 3.7.0 beta 2: Python 3 7 0 beta 2. 
* Python 3.7.0 beta 1: Python 3 7 0 beta 1. 
* Python 3.7.0 alpha 4: Python 3 7 0 alpha 4. 
* Python 3.7.0 alpha 3: Python 3 7 0 alpha 3. 
* Python 3.7.0 alpha 2: Python 3 7 0 alpha 2. 
* Python 3.7.0 alpha 1: Python 3 7 0 alpha 1. 
* Python 3.6.6 final: Python 3 6 6 final. 
* Python 3.6.6 release candidate 1: Python 3 6 6 release candidate 1. 
* Python 3.6.5 final: Python 3 6 5 final. 
* Python 3.6.5 release candidate 1: Python 3 6 5 release candidate 1. 
* Python 3.6.4 final: Python 3 6 4 final. 
* Python 3.6.4 release candidate 1: Python 3 6 4 release candidate 1. 
* Python 3.6.3 final: Python 3 6 3 final. 
* Python 3.6.3 release candidate 1: Python 3 6 3 release candidate 1. 
* Python 3.6.2 final: Python 3 6 2 final. 
* Python 3.6.2 release candidate 2: Python 3 6 2 release candidate 2. 
* Python 3.6.2 release candidate 1: Python 3 6 2 release candidate 1. 
* Python 3.6.1 final: Python 3 6 1 final. 
* Python 3.6.1 release candidate 1: Python 3 6 1 release candidate 1. 
* Python 3.6.0 final: Python 3 6 0 final. 
* Python 3.6.0 release candidate 2: Python 3 6 0 release candidate 2. 
* Python 3.6.0 release candidate 1: Python 3 6 0 release candidate 1. 
* Python 3.6.0 beta 4: Python 3 6 0 beta 4. 
* Python 3.6.0 beta 3: Python 3 6 0 beta 3. 
* Python 3.6.0 beta 2: Python 3 6 0 beta 2. 
* Python 3.6.0 beta 1: Python 3 6 0 beta 1. 
* Python 3.6.0 alpha 4: Python 3 6 0 alpha 4. 
* Python 3.6.0 alpha 3: Python 3 6 0 alpha 3. 
* Python 3.6.0 alpha 2: Python 3 6 0 alpha 2. 
* Python 3.6.0 alpha 1: Python 3 6 0 alpha 1. 
* Python 3.5.5 final: Python 3 5 5 final. 
* Python 3.5.5 release candidate 1: Python 3 5 5 release candidate 1. 
* Python 3.5.4 final: Python 3 5 4 final. 
* Python 3.5.4 release candidate 1: Python 3 5 4 release candidate 1. 
* Python 3.5.3 final: Python 3 5 3 final. 
* Python 3.5.3 release candidate 1: Python 3 5 3 release candidate 1. 
* Python 3.5.2 final: Python 3 5 2 final. 
* Python 3.5.2 release candidate 1: Python 3 5 2 release candidate 1. 
* Python 3.5.1 final: Python 3 5 1 final. 
* Python 3.5.1 release candidate 1: Python 3 5 1 release candidate 1. 
* Python 3.5.0 final: Python 3 5 0 final. 
* Python 3.5.0 release candidate 4: Python 3 5 0 release candidate 4. 
* Python 3.5.0 release candidate 3: Python 3 5 0 release candidate 3. 
* Python 3.5.0 release candidate 2: Python 3 5 0 release candidate 2. 
* Python 3.5.0 release candidate 1: Python 3 5 0 release candidate 1. 
* Python 3.5.0 beta 4: Python 3 5 0 beta 4. 
* Python 3.5.0 beta 3: Python 3 5 0 beta 3. 
* Python 3.5.0 beta 2: Python 3 5 0 beta 2. 
* Python 3.5.0 beta 1: Python 3 5 0 beta 1. 
* Python 3.5.0 alpha 4: Python 3 5 0 alpha 4. 
* Python 3.5.0 alpha 3: Python 3 5 0 alpha 3. 
* Python 3.5.0 alpha 2: Python 3 5 0 alpha 2. 
* Python 3.5.0 alpha 1: Python 3 5 0 alpha 1. 

Python next

* macOS:: 
* Windows:: 
* ライブラリ:: 
* ドキュメント: ドキュメント<2>. 
* Core and Builtins:: 

Python 3.14.3 final

* Windows: Windows<2>. 
* Tools/Demos:: 
* テスト:: 
* セキュリティ:: 
* ライブラリ: ライブラリ<2>. 
* IDLE: IDLE<3>. 
* ドキュメント: ドキュメント<3>. 
* Core and Builtins: Core and Builtins<2>. 
* C API:: 
* ビルド:: 

Python 3.14.2 final

* セキュリティ: セキュリティ<2>. 
* ライブラリ: ライブラリ<3>. 
* Core and Builtins: Core and Builtins<3>. 
* ライブラリ: ライブラリ<4>. 

Python 3.14.1 final

* Windows: Windows<3>. 
* Tools/Demos: Tools/Demos<2>. 
* テスト: テスト<2>. 
* セキュリティ: セキュリティ<3>. 
* ライブラリ: ライブラリ<5>. 
* IDLE: IDLE<4>. 
* ドキュメント: ドキュメント<4>. 
* Core and Builtins: Core and Builtins<4>. 
* ライブラリ: ライブラリ<6>. 
* Core and Builtins: Core and Builtins<5>. 
* ライブラリ: ライブラリ<7>. 
* Core and Builtins: Core and Builtins<6>. 
* ライブラリ: ライブラリ<8>. 
* Core and Builtins: Core and Builtins<7>. 
* ライブラリ: ライブラリ<9>. 
* Core and Builtins: Core and Builtins<8>. 
* ライブラリ: ライブラリ<10>. 
* Core and Builtins: Core and Builtins<9>. 
* ライブラリ: ライブラリ<11>. 
* Core and Builtins: Core and Builtins<10>. 
* C API: C API<2>. 
* ビルド: ビルド<2>. 

Python 3.14.0 final

* macOS: macOS<2>. 
* Windows: Windows<4>. 
* Tools/Demos: Tools/Demos<3>. 
* セキュリティ: セキュリティ<4>. 
* ライブラリ: ライブラリ<12>. 

Python 3.14.0 release candidate 3

* Windows: Windows<5>. 
* Tools/Demos: Tools/Demos<4>. 
* セキュリティ: セキュリティ<5>. 
* ライブラリ: ライブラリ<13>. 
* Core and Builtins: Core and Builtins<11>. 

Python 3.14.0 release candidate 2

* macOS: macOS<3>. 
* Windows: Windows<6>. 
* ライブラリ: ライブラリ<14>. 
* ドキュメント: ドキュメント<5>. 
* Core and Builtins: Core and Builtins<12>. 
* C API: C API<3>. 
* ビルド: ビルド<3>. 

Python 3.14.0 release candidate 1

* Tools/Demos: Tools/Demos<5>. 
* セキュリティ: セキュリティ<6>. 
* ライブラリ: ライブラリ<15>. 
* Core and Builtins: Core and Builtins<13>. 
* ライブラリ: ライブラリ<16>. 
* Core and Builtins: Core and Builtins<14>. 
* ライブラリ: ライブラリ<17>. 
* Core and Builtins: Core and Builtins<15>. 
* C API: C API<4>. 
* ビルド: ビルド<4>. 

Python 3.14.0 beta 4

* Tools/Demos: Tools/Demos<6>. 
* テスト: テスト<3>. 
* セキュリティ: セキュリティ<7>. 
* ライブラリ: ライブラリ<18>. 
* ドキュメント: ドキュメント<6>. 
* Core and Builtins: Core and Builtins<16>. 
* C API: C API<5>. 
* ビルド: ビルド<5>. 

Python 3.14.0 beta 3

* Windows: Windows<7>. 
* テスト: テスト<4>. 
* セキュリティ: セキュリティ<8>. 
* ライブラリ: ライブラリ<19>. 
* ドキュメント: ドキュメント<7>. 
* Core and Builtins: Core and Builtins<17>. 
* ライブラリ: ライブラリ<20>. 
* Core and Builtins: Core and Builtins<18>. 
* ライブラリ: ライブラリ<21>. 
* Core and Builtins: Core and Builtins<19>. 
* ライブラリ: ライブラリ<22>. 
* Core and Builtins: Core and Builtins<20>. 
* C API: C API<6>. 
* ビルド: ビルド<6>. 

Python 3.14.0 beta 2

* Windows: Windows<8>. 
* Tools/Demos: Tools/Demos<7>. 
* テスト: テスト<5>. 
* セキュリティ: セキュリティ<9>. 
* ライブラリ: ライブラリ<23>. 
* Core and Builtins: Core and Builtins<21>. 
* C API: C API<7>. 
* ビルド: ビルド<7>. 

Python 3.14.0 beta 1

* Windows: Windows<9>. 
* Tools/Demos: Tools/Demos<8>. 
* テスト: テスト<6>. 
* セキュリティ: セキュリティ<10>. 
* ライブラリ: ライブラリ<24>. 
* IDLE: IDLE<5>. 
* ドキュメント: ドキュメント<8>. 
* Core and Builtins: Core and Builtins<22>. 
* ライブラリ: ライブラリ<25>. 
* Core and Builtins: Core and Builtins<23>. 
* ライブラリ: ライブラリ<26>. 
* Core and Builtins: Core and Builtins<24>. 
* ライブラリ: ライブラリ<27>. 
* C API: C API<8>. 
* ビルド: ビルド<8>. 

Python 3.14.0 alpha 7

* macOS: macOS<4>. 
* Windows: Windows<10>. 
* Tools/Demos: Tools/Demos<9>. 
* テスト: テスト<7>. 
* セキュリティ: セキュリティ<11>. 
* ライブラリ: ライブラリ<28>. 
* ドキュメント: ドキュメント<9>. 
* Core and Builtins: Core and Builtins<25>. 
* ライブラリ: ライブラリ<29>. 
* Core and Builtins: Core and Builtins<26>. 
* C API: C API<9>. 
* ビルド: ビルド<9>. 

Python 3.14.0 alpha 6

* macOS: macOS<5>. 
* Windows: Windows<11>. 
* Tools/Demos: Tools/Demos<10>. 
* テスト: テスト<8>. 
* セキュリティ: セキュリティ<12>. 
* ライブラリ: ライブラリ<30>. 
* ドキュメント: ドキュメント<10>. 
* Core and Builtins: Core and Builtins<27>. 
* ライブラリ: ライブラリ<31>. 
* Core and Builtins: Core and Builtins<28>. 
* ライブラリ: ライブラリ<32>. 
* Core and Builtins: Core and Builtins<29>. 
* C API: C API<10>. 
* ビルド: ビルド<10>. 

Python 3.14.0 alpha 5

* macOS: macOS<6>. 
* Tools/Demos: Tools/Demos<11>. 
* テスト: テスト<9>. 
* セキュリティ: セキュリティ<13>. 
* ライブラリ: ライブラリ<33>. 
* IDLE: IDLE<6>. 
* ドキュメント: ドキュメント<11>. 
* Core and Builtins: Core and Builtins<30>. 
* ライブラリ: ライブラリ<34>. 
* Core and Builtins: Core and Builtins<31>. 
* ライブラリ: ライブラリ<35>. 
* Core and Builtins: Core and Builtins<32>. 
* ライブラリ: ライブラリ<36>. 
* C API: C API<11>. 
* ビルド: ビルド<11>. 

Python 3.14.0 alpha 4

* macOS: macOS<7>. 
* Tools/Demos: Tools/Demos<12>. 
* テスト: テスト<10>. 
* ライブラリ: ライブラリ<37>. 
* Core and Builtins: Core and Builtins<33>. 
* ライブラリ: ライブラリ<38>. 
* Core and Builtins: Core and Builtins<34>. 
* ライブラリ: ライブラリ<39>. 
* Core and Builtins: Core and Builtins<35>. 
* C API: C API<12>. 
* ビルド: ビルド<12>. 

Python 3.14.0 alpha 3

* Windows: Windows<12>. 
* Tools/Demos: Tools/Demos<13>. 
* テスト: テスト<11>. 
* セキュリティ: セキュリティ<14>. 
* ライブラリ: ライブラリ<40>. 
* ドキュメント: ドキュメント<12>. 
* Core and Builtins: Core and Builtins<36>. 
* ライブラリ: ライブラリ<41>. 
* Core and Builtins: Core and Builtins<37>. 
* C API: C API<13>. 
* ビルド: ビルド<13>. 

Python 3.14.0 alpha 2

* Windows: Windows<13>. 
* Tools/Demos: Tools/Demos<14>. 
* テスト: テスト<12>. 
* セキュリティ: セキュリティ<15>. 
* ライブラリ: ライブラリ<42>. 
* ドキュメント: ドキュメント<13>. 
* Core and Builtins: Core and Builtins<38>. 
* ライブラリ: ライブラリ<43>. 
* Core and Builtins: Core and Builtins<39>. 
* ライブラリ: ライブラリ<44>. 
* Core and Builtins: Core and Builtins<40>. 
* ライブラリ: ライブラリ<45>. 
* C API: C API<14>. 
* ビルド: ビルド<14>. 

Python 3.14.0 alpha 1

* macOS: macOS<8>. 
* Windows: Windows<14>. 
* Tools/Demos: Tools/Demos<15>. 
* テスト: テスト<13>. 
* セキュリティ: セキュリティ<16>. 
* ライブラリ: ライブラリ<46>. 
* IDLE: IDLE<7>. 
* ドキュメント: ドキュメント<14>. 
* Core and Builtins: Core and Builtins<41>. 
* ライブラリ: ライブラリ<47>. 
* Core and Builtins: Core and Builtins<42>. 
* ライブラリ: ライブラリ<48>. 
* Core and Builtins: Core and Builtins<43>. 
* ライブラリ: ライブラリ<49>. 
* Core and Builtins: Core and Builtins<44>. 
* ライブラリ: ライブラリ<50>. 
* Core and Builtins: Core and Builtins<45>. 
* ライブラリ: ライブラリ<51>. 
* Core and Builtins: Core and Builtins<46>. 
* ライブラリ: ライブラリ<52>. 
* Core and Builtins: Core and Builtins<47>. 
* ライブラリ: ライブラリ<53>. 
* Core and Builtins: Core and Builtins<48>. 
* C API: C API<15>. 
* ビルド: ビルド<15>. 

Python 3.13.0 beta 1

* セキュリティ: セキュリティ<17>. 
* Core and Builtins: Core and Builtins<49>. 
* ライブラリ: ライブラリ<54>. 
* Core and Builtins: Core and Builtins<50>. 
* ライブラリ: ライブラリ<55>. 
* ドキュメント: ドキュメント<15>. 
* ビルド: ビルド<16>. 
* Windows: Windows<15>. 
* macOS: macOS<9>. 
* IDLE: IDLE<8>. 
* C API: C API<16>. 

Python 3.13.0 alpha 6

* Core and Builtins: Core and Builtins<51>. 
* ライブラリ: ライブラリ<56>. 
* Core and Builtins: Core and Builtins<52>. 
* ライブラリ: ライブラリ<57>. 
* ドキュメント: ドキュメント<16>. 
* テスト: テスト<14>. 
* ビルド: ビルド<17>. 
* Windows: Windows<16>. 
* C API: C API<17>. 

Python 3.13.0 alpha 5

* セキュリティ: セキュリティ<18>. 
* Core and Builtins: Core and Builtins<53>. 
* ライブラリ: ライブラリ<58>. 
* Core and Builtins: Core and Builtins<54>. 
* ライブラリ: ライブラリ<59>. 
* Core and Builtins: Core and Builtins<55>. 
* ライブラリ: ライブラリ<60>. 
* ドキュメント: ドキュメント<17>. 
* テスト: テスト<15>. 
* ビルド: ビルド<18>. 
* Windows: Windows<17>. 
* macOS: macOS<10>. 
* IDLE: IDLE<9>. 
* Tools/Demos: Tools/Demos<16>. 
* C API: C API<18>. 

Python 3.13.0 alpha 4

* セキュリティ: セキュリティ<19>. 
* Core and Builtins: Core and Builtins<56>. 
* ライブラリ: ライブラリ<61>. 
* ドキュメント: ドキュメント<18>. 
* テスト: テスト<16>. 
* ビルド: ビルド<19>. 
* Windows: Windows<18>. 
* macOS: macOS<11>. 
* IDLE: IDLE<10>. 
* Tools/Demos: Tools/Demos<17>. 
* C API: C API<19>. 

Python 3.13.0 alpha 3

* セキュリティ: セキュリティ<20>. 
* Core and Builtins: Core and Builtins<57>. 
* ライブラリ: ライブラリ<62>. 
* ドキュメント: ドキュメント<19>. 
* テスト: テスト<17>. 
* ビルド: ビルド<20>. 
* Windows: Windows<19>. 
* macOS: macOS<12>. 
* IDLE: IDLE<11>. 
* C API: C API<20>. 

Python 3.13.0 alpha 2

* Core and Builtins: Core and Builtins<58>. 
* ライブラリ: ライブラリ<63>. 
* テスト: テスト<18>. 
* ビルド: ビルド<21>. 
* Windows: Windows<20>. 
* macOS: macOS<13>. 
* IDLE: IDLE<12>. 
* Tools/Demos: Tools/Demos<18>. 
* C API: C API<21>. 

Python 3.13.0 alpha 1

* セキュリティ: セキュリティ<21>. 
* Core and Builtins: Core and Builtins<59>. 
* ライブラリ: ライブラリ<64>. 
* ドキュメント: ドキュメント<20>. 
* テスト: テスト<19>. 
* ビルド: ビルド<22>. 
* Windows: Windows<21>. 
* macOS: macOS<14>. 
* IDLE: IDLE<13>. 
* Tools/Demos: Tools/Demos<19>. 
* C API: C API<22>. 

Python 3.12.0 beta 1

* セキュリティ: セキュリティ<22>. 
* ライブラリ: ライブラリ<65>. 
* Core and Builtins: Core and Builtins<60>. 
* ライブラリ: ライブラリ<66>. 
* Core and Builtins: Core and Builtins<61>. 
* ライブラリ: ライブラリ<67>. 
* ドキュメント: ドキュメント<21>. 
* テスト: テスト<20>. 
* ビルド: ビルド<23>. 
* Windows: Windows<22>. 
* macOS: macOS<15>. 
* IDLE: IDLE<14>. 
* Tools/Demos: Tools/Demos<20>. 
* C API: C API<23>. 

Python 3.12.0 alpha 7

* Core and Builtins: Core and Builtins<62>. 
* ライブラリ: ライブラリ<68>. 
* Core and Builtins: Core and Builtins<63>. 
* ビルド: ビルド<24>. 
* Core and Builtins: Core and Builtins<64>. 
* ライブラリ: ライブラリ<69>. 
* ドキュメント: ドキュメント<22>. 
* テスト: テスト<21>. 
* ビルド: ビルド<25>. 
* Windows: Windows<23>. 
* Tools/Demos: Tools/Demos<21>. 
* C API: C API<24>. 

Python 3.12.0 alpha 6

* セキュリティ: セキュリティ<23>. 
* Core and Builtins: Core and Builtins<65>. 
* ライブラリ: ライブラリ<70>. 
* ドキュメント: ドキュメント<23>. 
* テスト: テスト<22>. 
* ビルド: ビルド<26>. 
* Windows: Windows<24>. 
* macOS: macOS<16>. 
* C API: C API<25>. 

Python 3.12.0 alpha 5

* セキュリティ: セキュリティ<24>. 
* Core and Builtins: Core and Builtins<66>. 
* ライブラリ: ライブラリ<71>. 
* ドキュメント: ドキュメント<24>. 
* テスト: テスト<23>. 
* ビルド: ビルド<27>. 
* Windows: Windows<25>. 

Python 3.12.0 alpha 4

* Core and Builtins: Core and Builtins<67>. 
* ライブラリ: ライブラリ<72>. 
* Core and Builtins: Core and Builtins<68>. 
* ライブラリ: ライブラリ<73>. 
* Core and Builtins: Core and Builtins<69>. 
* ライブラリ: ライブラリ<74>. 
* ドキュメント: ドキュメント<25>. 
* テスト: テスト<24>. 
* ビルド: ビルド<28>. 
* Windows: Windows<26>. 
* macOS: macOS<17>. 
* Tools/Demos: Tools/Demos<22>. 
* C API: C API<26>. 

Python 3.12.0 alpha 3

* セキュリティ: セキュリティ<25>. 
* Core and Builtins: Core and Builtins<70>. 
* ライブラリ: ライブラリ<75>. 
* Core and Builtins: Core and Builtins<71>. 
* ライブラリ: ライブラリ<76>. 
* ドキュメント: ドキュメント<26>. 
* テスト: テスト<25>. 
* ビルド: ビルド<29>. 
* Windows: Windows<27>. 
* macOS: macOS<18>. 
* Tools/Demos: Tools/Demos<23>. 
* C API: C API<27>. 

Python 3.12.0 alpha 2

* セキュリティ: セキュリティ<26>. 
* Core and Builtins: Core and Builtins<72>. 
* ビルド: ビルド<30>. 
* Core and Builtins: Core and Builtins<73>. 
* ライブラリ: ライブラリ<77>. 
* ドキュメント: ドキュメント<27>. 
* テスト: テスト<26>. 
* ビルド: ビルド<31>. 
* Windows: Windows<28>. 
* macOS: macOS<19>. 
* C API: C API<28>. 

Python 3.12.0 alpha 1

* セキュリティ: セキュリティ<27>. 
* Core and Builtins: Core and Builtins<74>. 
* ライブラリ: ライブラリ<78>. 
* Core and Builtins: Core and Builtins<75>. 
* ライブラリ: ライブラリ<79>. 
* Core and Builtins: Core and Builtins<76>. 
* ライブラリ: ライブラリ<80>. 
* Core and Builtins: Core and Builtins<77>. 
* ライブラリ: ライブラリ<81>. 
* Core and Builtins: Core and Builtins<78>. 
* ライブラリ: ライブラリ<82>. 
* Core and Builtins: Core and Builtins<79>. 
* ライブラリ: ライブラリ<83>. 
* Core and Builtins: Core and Builtins<80>. 
* ライブラリ: ライブラリ<84>. 
* Core and Builtins: Core and Builtins<81>. 
* ライブラリ: ライブラリ<85>. 
* Core and Builtins: Core and Builtins<82>. 
* ライブラリ: ライブラリ<86>. 
* Core and Builtins: Core and Builtins<83>. 
* ライブラリ: ライブラリ<87>. 
* ドキュメント: ドキュメント<28>. 
* テスト: テスト<27>. 
* ビルド: ビルド<32>. 
* Windows: Windows<29>. 
* macOS: macOS<20>. 
* IDLE: IDLE<15>. 
* Tools/Demos: Tools/Demos<24>. 
* C API: C API<29>. 

Python 3.11.0 beta 1

* セキュリティ: セキュリティ<28>. 
* Core and Builtins: Core and Builtins<84>. 
* ライブラリ: ライブラリ<88>. 
* Core and Builtins: Core and Builtins<85>. 
* ビルド: ビルド<33>. 
* Core and Builtins: Core and Builtins<86>. 
* ライブラリ: ライブラリ<89>. 
* ドキュメント: ドキュメント<29>. 
* テスト: テスト<28>. 
* ビルド: ビルド<34>. 
* Windows: Windows<30>. 
* macOS: macOS<21>. 
* Tools/Demos: Tools/Demos<25>. 
* C API: C API<30>. 

Python 3.11.0 alpha 7

* Core and Builtins: Core and Builtins<87>. 
* ライブラリ: ライブラリ<90>. 
* Core and Builtins: Core and Builtins<88>. 
* ライブラリ: ライブラリ<91>. 
* Core and Builtins: Core and Builtins<89>. 
* ライブラリ: ライブラリ<92>. 
* ドキュメント: ドキュメント<30>. 
* テスト: テスト<29>. 
* ビルド: ビルド<35>. 
* Windows: Windows<31>. 
* macOS: macOS<22>. 
* Tools/Demos: Tools/Demos<26>. 
* C API: C API<31>. 

Python 3.11.0 alpha 6

* Core and Builtins: Core and Builtins<90>. 
* ライブラリ: ライブラリ<93>. 
* Core and Builtins: Core and Builtins<91>. 
* ライブラリ: ライブラリ<94>. 
* Core and Builtins: Core and Builtins<92>. 
* ライブラリ: ライブラリ<95>. 
* Core and Builtins: Core and Builtins<93>. 
* ライブラリ: ライブラリ<96>. 
* ドキュメント: ドキュメント<31>. 
* テスト: テスト<30>. 
* ビルド: ビルド<36>. 
* Windows: Windows<32>. 
* IDLE: IDLE<16>. 
* C API: C API<32>. 

Python 3.11.0 alpha 5

* Core and Builtins: Core and Builtins<94>. 
* ライブラリ: ライブラリ<97>. 
* Core and Builtins: Core and Builtins<95>. 
* ライブラリ: ライブラリ<98>. 
* ビルド: ビルド<37>. 
* Core and Builtins: Core and Builtins<96>. 
* ライブラリ: ライブラリ<99>. 
* ドキュメント: ドキュメント<32>. 
* テスト: テスト<31>. 
* ビルド: ビルド<38>. 
* Windows: Windows<33>. 
* macOS: macOS<23>. 
* IDLE: IDLE<17>. 
* C API: C API<33>. 

Python 3.11.0 alpha 4

* Core and Builtins: Core and Builtins<97>. 
* ライブラリ: ライブラリ<100>. 
* Core and Builtins: Core and Builtins<98>. 
* ライブラリ: ライブラリ<101>. 
* Core and Builtins: Core and Builtins<99>. 
* ライブラリ: ライブラリ<102>. 
* Core and Builtins: Core and Builtins<100>. 
* ライブラリ: ライブラリ<103>. 
* ドキュメント: ドキュメント<33>. 
* テスト: テスト<32>. 
* ビルド: ビルド<39>. 
* Windows: Windows<34>. 
* macOS: macOS<24>. 
* C API: C API<34>. 

Python 3.11.0 alpha 3

* Core and Builtins: Core and Builtins<101>. 
* ライブラリ: ライブラリ<104>. 
* Core and Builtins: Core and Builtins<102>. 
* ライブラリ: ライブラリ<105>. 
* ドキュメント: ドキュメント<34>. 
* テスト: テスト<33>. 
* ビルド: ビルド<40>. 
* Windows: Windows<35>. 
* macOS: macOS<25>. 
* C API: C API<35>. 

Python 3.11.0 alpha 2

* Core and Builtins: Core and Builtins<103>. 
* ライブラリ: ライブラリ<106>. 
* ドキュメント: ドキュメント<35>. 
* テスト: テスト<34>. 
* ビルド: ビルド<41>. 
* Windows: Windows<36>. 
* macOS: macOS<26>. 
* IDLE: IDLE<18>. 
* C API: C API<36>. 

Python 3.11.0 alpha 1

* セキュリティ: セキュリティ<29>. 
* Core and Builtins: Core and Builtins<104>. 
* ライブラリ: ライブラリ<107>. 
* Core and Builtins: Core and Builtins<105>. 
* ライブラリ: ライブラリ<108>. 
* Core and Builtins: Core and Builtins<106>. 
* ライブラリ: ライブラリ<109>. 
* Core and Builtins: Core and Builtins<107>. 
* ライブラリ: ライブラリ<110>. 
* Core and Builtins: Core and Builtins<108>. 
* ライブラリ: ライブラリ<111>. 
* Core and Builtins: Core and Builtins<109>. 
* ライブラリ: ライブラリ<112>. 
* Core and Builtins: Core and Builtins<110>. 
* ライブラリ: ライブラリ<113>. 
* Core and Builtins: Core and Builtins<111>. 
* ライブラリ: ライブラリ<114>. 
* Core and Builtins: Core and Builtins<112>. 
* ライブラリ: ライブラリ<115>. 
* Core and Builtins: Core and Builtins<113>. 
* ライブラリ: ライブラリ<116>. 
* ドキュメント: ドキュメント<36>. 
* テスト: テスト<35>. 
* ビルド: ビルド<42>. 
* Windows: Windows<37>. 
* macOS: macOS<27>. 
* IDLE: IDLE<19>. 
* Tools/Demos: Tools/Demos<27>. 
* C API: C API<37>. 

Python 3.10.0 beta 1

* セキュリティ: セキュリティ<30>. 
* Core and Builtins: Core and Builtins<114>. 
* ライブラリ: ライブラリ<117>. 
* Core and Builtins: Core and Builtins<115>. 
* ライブラリ: ライブラリ<118>. 
* Core and Builtins: Core and Builtins<116>. 
* ライブラリ: ライブラリ<119>. 
* ドキュメント: ドキュメント<37>. 
* テスト: テスト<36>. 
* ビルド: ビルド<43>. 
* Windows: Windows<38>. 
* macOS: macOS<28>. 
* IDLE: IDLE<20>. 
* C API: C API<38>. 

Python 3.10.0 alpha 7

* セキュリティ: セキュリティ<31>. 
* Core and Builtins: Core and Builtins<117>. 
* ライブラリ: ライブラリ<120>. 
* Core and Builtins: Core and Builtins<118>. 
* ライブラリ: ライブラリ<121>. 
* ドキュメント: ドキュメント<38>. 
* テスト: テスト<37>. 
* ビルド: ビルド<44>. 
* Windows: Windows<39>. 
* IDLE: IDLE<21>. 
* C API: C API<39>. 

Python 3.10.0 alpha 6

* セキュリティ: セキュリティ<32>. 
* Core and Builtins: Core and Builtins<119>. 
* ライブラリ: ライブラリ<122>. 
* Core and Builtins: Core and Builtins<120>. 
* ライブラリ: ライブラリ<123>. 
* Core and Builtins: Core and Builtins<121>. 
* ライブラリ: ライブラリ<124>. 
* ドキュメント: ドキュメント<39>. 
* テスト: テスト<38>. 
* ビルド: ビルド<45>. 
* Windows: Windows<40>. 
* macOS: macOS<29>. 
* IDLE: IDLE<22>. 
* C API: C API<40>. 

Python 3.10.0 alpha 5

* セキュリティ: セキュリティ<33>. 
* Core and Builtins: Core and Builtins<122>. 
* ライブラリ: ライブラリ<125>. 
* Core and Builtins: Core and Builtins<123>. 
* ライブラリ: ライブラリ<126>. 
* ドキュメント: ドキュメント<40>. 
* テスト: テスト<39>. 
* ビルド: ビルド<46>. 
* Windows: Windows<41>. 
* macOS: macOS<30>. 
* IDLE: IDLE<23>. 
* C API: C API<41>. 

Python 3.10.0 alpha 4

* Core and Builtins: Core and Builtins<124>. 
* ライブラリ: ライブラリ<127>. 
* Core and Builtins: Core and Builtins<125>. 
* ライブラリ: ライブラリ<128>. 
* Core and Builtins: Core and Builtins<126>. 
* ライブラリ: ライブラリ<129>. 
* ドキュメント: ドキュメント<41>. 
* テスト: テスト<40>. 
* ビルド: ビルド<47>. 
* macOS: macOS<31>. 
* Tools/Demos: Tools/Demos<28>. 
* C API: C API<42>. 

Python 3.10.0 alpha 3

* セキュリティ: セキュリティ<34>. 
* Core and Builtins: Core and Builtins<127>. 
* ライブラリ: ライブラリ<130>. 
* Core and Builtins: Core and Builtins<128>. 
* ライブラリ: ライブラリ<131>. 
* Core and Builtins: Core and Builtins<129>. 
* ライブラリ: ライブラリ<132>. 
* Core and Builtins: Core and Builtins<130>. 
* ライブラリ: ライブラリ<133>. 
* ドキュメント: ドキュメント<42>. 
* テスト: テスト<41>. 
* ビルド: ビルド<48>. 
* Windows: Windows<42>. 
* macOS: macOS<32>. 
* IDLE: IDLE<24>. 
* Tools/Demos: Tools/Demos<29>. 
* C API: C API<43>. 

Python 3.10.0 alpha 2

* セキュリティ: セキュリティ<35>. 
* Core and Builtins: Core and Builtins<131>. 
* ライブラリ: ライブラリ<134>. 
* Core and Builtins: Core and Builtins<132>. 
* ライブラリ: ライブラリ<135>. 
* ドキュメント: ドキュメント<43>. 
* テスト: テスト<42>. 
* ビルド: ビルド<49>. 
* Windows: Windows<43>. 
* macOS: macOS<33>. 
* IDLE: IDLE<25>. 
* C API: C API<44>. 

Python 3.10.0 alpha 1

* セキュリティ: セキュリティ<36>. 
* Core and Builtins: Core and Builtins<133>. 
* ライブラリ: ライブラリ<136>. 
* Core and Builtins: Core and Builtins<134>. 
* ライブラリ: ライブラリ<137>. 
* Core and Builtins: Core and Builtins<135>. 
* ライブラリ: ライブラリ<138>. 
* Core and Builtins: Core and Builtins<136>. 
* ライブラリ: ライブラリ<139>. 
* Core and Builtins: Core and Builtins<137>. 
* ライブラリ: ライブラリ<140>. 
* Core and Builtins: Core and Builtins<138>. 
* ライブラリ: ライブラリ<141>. 
* Core and Builtins: Core and Builtins<139>. 
* ライブラリ: ライブラリ<142>. 
* Core and Builtins: Core and Builtins<140>. 
* ライブラリ: ライブラリ<143>. 
* Core and Builtins: Core and Builtins<141>. 
* ライブラリ: ライブラリ<144>. 
* Core and Builtins: Core and Builtins<142>. 
* ライブラリ: ライブラリ<145>. 
* Core and Builtins: Core and Builtins<143>. 
* ライブラリ: ライブラリ<146>. 
* Core and Builtins: Core and Builtins<144>. 
* ライブラリ: ライブラリ<147>. 
* Core and Builtins: Core and Builtins<145>. 
* ライブラリ: ライブラリ<148>. 
* Core and Builtins: Core and Builtins<146>. 
* ライブラリ: ライブラリ<149>. 
* Core and Builtins: Core and Builtins<147>. 
* ライブラリ: ライブラリ<150>. 
* ドキュメント: ドキュメント<44>. 
* テスト: テスト<43>. 
* ビルド: ビルド<50>. 
* Windows: Windows<44>. 
* macOS: macOS<34>. 
* IDLE: IDLE<26>. 
* C API: C API<45>. 

Python 3.9.0 beta 1

* セキュリティ: セキュリティ<37>. 
* Core and Builtins: Core and Builtins<148>. 
* ライブラリ: ライブラリ<151>. 
* ドキュメント: ドキュメント<45>. 
* テスト: テスト<44>. 
* ビルド: ビルド<51>. 
* Windows: Windows<45>. 
* macOS: macOS<35>. 
* Tools/Demos: Tools/Demos<30>. 
* C API: C API<46>. 

Python 3.9.0 alpha 6

* セキュリティ: セキュリティ<38>. 
* Core and Builtins: Core and Builtins<149>. 
* ライブラリ: ライブラリ<152>. 
* ドキュメント: ドキュメント<46>. 
* テスト: テスト<45>. 
* ビルド: ビルド<52>. 
* Windows: Windows<46>. 
* macOS: macOS<36>. 
* IDLE: IDLE<27>. 
* Tools/Demos: Tools/Demos<31>. 
* C API: C API<47>. 

Python 3.9.0 alpha 5

* セキュリティ: セキュリティ<39>. 
* Core and Builtins: Core and Builtins<150>. 
* ライブラリ: ライブラリ<153>. 
* ドキュメント: ドキュメント<47>. 
* テスト: テスト<46>. 
* ビルド: ビルド<53>. 
* Windows: Windows<47>. 
* macOS: macOS<37>. 
* IDLE: IDLE<28>. 
* Tools/Demos: Tools/Demos<32>. 
* C API: C API<48>. 

Python 3.9.0 alpha 4

* セキュリティ: セキュリティ<40>. 
* Core and Builtins: Core and Builtins<151>. 
* ライブラリ: ライブラリ<154>. 
* ドキュメント: ドキュメント<48>. 
* テスト: テスト<47>. 
* ビルド: ビルド<54>. 
* Windows: Windows<48>. 
* IDLE: IDLE<29>. 
* C API: C API<49>. 

Python 3.9.0 alpha 3

* Core and Builtins: Core and Builtins<152>. 
* ライブラリ: ライブラリ<155>. 
* ドキュメント: ドキュメント<49>. 
* ビルド: ビルド<55>. 
* IDLE: IDLE<30>. 
* C API: C API<50>. 

Python 3.9.0 alpha 2

* セキュリティ: セキュリティ<41>. 
* Core and Builtins: Core and Builtins<153>. 
* ライブラリ: ライブラリ<156>. 
* ドキュメント: ドキュメント<50>. 
* テスト: テスト<48>. 
* ビルド: ビルド<56>. 
* Windows: Windows<49>. 
* macOS: macOS<38>. 
* IDLE: IDLE<31>. 
* C API: C API<51>. 

Python 3.9.0 alpha 1

* セキュリティ: セキュリティ<42>. 
* Core and Builtins: Core and Builtins<154>. 
* ライブラリ: ライブラリ<157>. 
* ドキュメント: ドキュメント<51>. 
* テスト: テスト<49>. 
* ビルド: ビルド<57>. 
* Windows: Windows<50>. 
* macOS: macOS<39>. 
* IDLE: IDLE<32>. 
* Tools/Demos: Tools/Demos<33>. 
* C API: C API<52>. 

Python 3.8.0 beta 1

* セキュリティ: セキュリティ<43>. 
* Core and Builtins: Core and Builtins<155>. 
* ライブラリ: ライブラリ<158>. 
* ドキュメント: ドキュメント<52>. 
* テスト: テスト<50>. 
* ビルド: ビルド<58>. 
* Windows: Windows<51>. 
* macOS: macOS<40>. 
* IDLE: IDLE<33>. 
* Tools/Demos: Tools/Demos<34>. 
* C API: C API<53>. 

Python 3.8.0 alpha 4

* セキュリティ: セキュリティ<44>. 
* Core and Builtins: Core and Builtins<156>. 
* ライブラリ: ライブラリ<159>. 
* ドキュメント: ドキュメント<53>. 
* テスト: テスト<51>. 
* ビルド: ビルド<59>. 
* Windows: Windows<52>. 
* macOS: macOS<41>. 
* IDLE: IDLE<34>. 
* Tools/Demos: Tools/Demos<35>. 
* C API: C API<54>. 

Python 3.8.0 alpha 3

* セキュリティ: セキュリティ<45>. 
* Core and Builtins: Core and Builtins<157>. 
* ライブラリ: ライブラリ<160>. 
* ドキュメント: ドキュメント<54>. 
* テスト: テスト<52>. 
* ビルド: ビルド<60>. 
* Windows: Windows<53>. 
* IDLE: IDLE<35>. 
* Tools/Demos: Tools/Demos<36>. 
* C API: C API<55>. 

Python 3.8.0 alpha 2

* Core and Builtins: Core and Builtins<158>. 
* ライブラリ: ライブラリ<161>. 
* ドキュメント: ドキュメント<55>. 
* テスト: テスト<53>. 
* Windows: Windows<54>. 
* IDLE: IDLE<36>. 

Python 3.8.0 alpha 1

* セキュリティ: セキュリティ<46>. 
* Core and Builtins: Core and Builtins<159>. 
* ライブラリ: ライブラリ<162>. 
* ドキュメント: ドキュメント<56>. 
* テスト: テスト<54>. 
* ビルド: ビルド<61>. 
* Windows: Windows<55>. 
* macOS: macOS<42>. 
* IDLE: IDLE<37>. 
* Tools/Demos: Tools/Demos<37>. 
* C API: C API<56>. 

Python 3.7.0 final

* ライブラリ: ライブラリ<163>. 
* C API: C API<57>. 

Python 3.7.0 release candidate 1

* Core and Builtins: Core and Builtins<160>. 
* ライブラリ: ライブラリ<164>. 
* ドキュメント: ドキュメント<57>. 
* ビルド: ビルド<62>. 
* Windows: Windows<56>. 
* IDLE: IDLE<38>. 

Python 3.7.0 beta 5

* Core and Builtins: Core and Builtins<161>. 
* ライブラリ: ライブラリ<165>. 
* ドキュメント: ドキュメント<58>. 
* テスト: テスト<55>. 
* ビルド: ビルド<63>. 
* macOS: macOS<43>. 
* IDLE: IDLE<39>. 

Python 3.7.0 beta 4

* Core and Builtins: Core and Builtins<162>. 
* ライブラリ: ライブラリ<166>. 
* ドキュメント: ドキュメント<59>. 
* テスト: テスト<56>. 
* ビルド: ビルド<64>. 
* Windows: Windows<57>. 
* macOS: macOS<44>. 
* IDLE: IDLE<40>. 
* Tools/Demos: Tools/Demos<38>. 

Python 3.7.0 beta 3

* セキュリティ: セキュリティ<47>. 
* Core and Builtins: Core and Builtins<163>. 
* ライブラリ: ライブラリ<167>. 
* ドキュメント: ドキュメント<60>. 
* テスト: テスト<57>. 
* ビルド: ビルド<65>. 
* Windows: Windows<58>. 
* macOS: macOS<45>. 
* IDLE: IDLE<41>. 
* Tools/Demos: Tools/Demos<39>. 
* C API: C API<58>. 

Python 3.7.0 beta 2

* セキュリティ: セキュリティ<48>. 
* Core and Builtins: Core and Builtins<164>. 
* ライブラリ: ライブラリ<168>. 
* ドキュメント: ドキュメント<61>. 
* テスト: テスト<58>. 
* ビルド: ビルド<66>. 
* Windows: Windows<59>. 
* macOS: macOS<46>. 
* IDLE: IDLE<42>. 
* Tools/Demos: Tools/Demos<40>. 

Python 3.7.0 beta 1

* Core and Builtins: Core and Builtins<165>. 
* ライブラリ: ライブラリ<169>. 
* ドキュメント: ドキュメント<62>. 
* テスト: テスト<59>. 
* ビルド: ビルド<67>. 
* Windows: Windows<60>. 
* macOS: macOS<47>. 
* C API: C API<59>. 

Python 3.7.0 alpha 4

* Core and Builtins: Core and Builtins<166>. 
* ライブラリ: ライブラリ<170>. 
* ドキュメント: ドキュメント<63>. 
* テスト: テスト<60>. 
* Windows: Windows<61>. 
* Tools/Demos: Tools/Demos<41>. 
* C API: C API<60>. 

Python 3.7.0 alpha 3

* Core and Builtins: Core and Builtins<167>. 
* ライブラリ: ライブラリ<171>. 
* ドキュメント: ドキュメント<64>. 
* テスト: テスト<61>. 
* ビルド: ビルド<68>. 
* Windows: Windows<62>. 
* macOS: macOS<48>. 
* IDLE: IDLE<43>. 
* Tools/Demos: Tools/Demos<42>. 
* C API: C API<61>. 

Python 3.7.0 alpha 2

* Core and Builtins: Core and Builtins<168>. 
* ライブラリ: ライブラリ<172>. 
* ドキュメント: ドキュメント<65>. 
* ビルド: ビルド<69>. 
* IDLE: IDLE<44>. 
* C API: C API<62>. 

Python 3.7.0 alpha 1

* セキュリティ: セキュリティ<49>. 
* Core and Builtins: Core and Builtins<169>. 
* ライブラリ: ライブラリ<173>. 
* ドキュメント: ドキュメント<66>. 
* テスト: テスト<62>. 
* ビルド: ビルド<70>. 
* Windows: Windows<63>. 
* IDLE: IDLE<45>. 
* Tools/Demos: Tools/Demos<43>. 
* C API: C API<63>. 

Python 3.6.6 release candidate 1

* Core and Builtins: Core and Builtins<170>. 
* ライブラリ: ライブラリ<174>. 
* ドキュメント: ドキュメント<67>. 
* テスト: テスト<63>. 
* ビルド: ビルド<71>. 
* Windows: Windows<64>. 
* macOS: macOS<49>. 
* IDLE: IDLE<46>. 
* Tools/Demos: Tools/Demos<44>. 
* C API: C API<64>. 

Python 3.6.5 final

* テスト: テスト<64>. 
* ビルド: ビルド<72>. 

Python 3.6.5 release candidate 1

* セキュリティ: セキュリティ<50>. 
* Core and Builtins: Core and Builtins<171>. 
* ライブラリ: ライブラリ<175>. 
* ドキュメント: ドキュメント<68>. 
* テスト: テスト<65>. 
* ビルド: ビルド<73>. 
* Windows: Windows<65>. 
* macOS: macOS<50>. 
* IDLE: IDLE<47>. 
* Tools/Demos: Tools/Demos<45>. 
* C API: C API<65>. 

Python 3.6.4 release candidate 1

* Core and Builtins: Core and Builtins<172>. 
* ライブラリ: ライブラリ<176>. 
* ドキュメント: ドキュメント<69>. 
* テスト: テスト<66>. 
* ビルド: ビルド<74>. 
* Windows: Windows<66>. 
* macOS: macOS<51>. 
* IDLE: IDLE<48>. 
* Tools/Demos: Tools/Demos<46>. 
* C API: C API<66>. 

Python 3.6.3 final

* ライブラリ: ライブラリ<177>. 
* ビルド: ビルド<75>. 

Python 3.6.3 release candidate 1

* セキュリティ: セキュリティ<51>. 
* Core and Builtins: Core and Builtins<173>. 
* ライブラリ: ライブラリ<178>. 
* ドキュメント: ドキュメント<70>. 
* テスト: テスト<67>. 
* ビルド: ビルド<76>. 
* Windows: Windows<67>. 
* IDLE: IDLE<49>. 
* Tools/Demos: Tools/Demos<47>. 

Python 3.6.2 release candidate 2

* セキュリティ: セキュリティ<52>. 

Python 3.6.2 release candidate 1

* セキュリティ: セキュリティ<53>. 
* Core and Builtins: Core and Builtins<174>. 
* ライブラリ: ライブラリ<179>. 
* IDLE: IDLE<50>. 
* C API: C API<67>. 
* ビルド: ビルド<77>. 
* ドキュメント: ドキュメント<71>. 
* Tools/Demos: Tools/Demos<48>. 
* テスト: テスト<68>. 
* Windows: Windows<68>. 

Python 3.6.1 final

* Core and Builtins: Core and Builtins<175>. 
* ビルド: ビルド<78>. 

Python 3.6.1 release candidate 1

* Core and Builtins: Core and Builtins<176>. 
* ライブラリ: ライブラリ<180>. 
* IDLE: IDLE<51>. 
* Windows: Windows<69>. 
* C API: C API<68>. 
* ドキュメント: ドキュメント<72>. 
* テスト: テスト<69>. 
* ビルド: ビルド<79>. 

Python 3.6.0 release candidate 2

* Core and Builtins: Core and Builtins<177>. 
* Tools/Demos: Tools/Demos<49>. 
* Windows: Windows<70>. 
* ビルド: ビルド<80>. 

Python 3.6.0 release candidate 1

* Core and Builtins: Core and Builtins<178>. 
* ライブラリ: ライブラリ<181>. 
* C API: C API<69>. 
* ドキュメント: ドキュメント<73>. 
* Tools/Demos: Tools/Demos<50>. 

Python 3.6.0 beta 4

* Core and Builtins: Core and Builtins<179>. 
* ライブラリ: ライブラリ<182>. 
* ドキュメント: ドキュメント<74>. 
* テスト: テスト<70>. 
* ビルド: ビルド<81>. 

Python 3.6.0 beta 3

* Core and Builtins: Core and Builtins<180>. 
* ライブラリ: ライブラリ<183>. 
* Windows: Windows<71>. 
* ビルド: ビルド<82>. 
* テスト: テスト<71>. 

Python 3.6.0 beta 2

* Core and Builtins: Core and Builtins<181>. 
* ライブラリ: ライブラリ<184>. 
* Windows: Windows<72>. 
* C API: C API<70>. 
* ビルド: ビルド<83>. 
* テスト: テスト<72>. 

Python 3.6.0 beta 1

* Core and Builtins: Core and Builtins<182>. 
* ライブラリ: ライブラリ<185>. 
* IDLE: IDLE<52>. 
* C API: C API<71>. 
* テスト: テスト<73>. 
* ビルド: ビルド<84>. 
* Tools/Demos: Tools/Demos<51>. 
* Windows: Windows<73>. 

Python 3.6.0 alpha 4

* Core and Builtins: Core and Builtins<183>. 
* ライブラリ: ライブラリ<186>. 
* IDLE: IDLE<53>. 
* テスト: テスト<74>. 
* Windows: Windows<74>. 
* ビルド: ビルド<85>. 

Python 3.6.0 alpha 3

* セキュリティ: セキュリティ<54>. 
* Core and Builtins: Core and Builtins<184>. 
* ライブラリ: ライブラリ<187>. 
* IDLE: IDLE<54>. 
* C API: C API<72>. 
* ビルド: ビルド<86>. 
* Tools/Demos: Tools/Demos<52>. 
* ドキュメント: ドキュメント<75>. 
* テスト: テスト<75>. 

Python 3.6.0 alpha 2

* セキュリティ: セキュリティ<55>. 
* Core and Builtins: Core and Builtins<185>. 
* ライブラリ: ライブラリ<188>. 
* IDLE: IDLE<55>. 
* ドキュメント: ドキュメント<76>. 
* テスト: テスト<76>. 
* Windows: Windows<75>. 
* ビルド: ビルド<87>. 
* C API: C API<73>. 
* Tools/Demos: Tools/Demos<53>. 

Python 3.6.0 alpha 1

* セキュリティ: セキュリティ<56>. 
* Core and Builtins: Core and Builtins<186>. 
* ライブラリ: ライブラリ<189>. 
* IDLE: IDLE<56>. 
* ドキュメント: ドキュメント<77>. 
* テスト: テスト<77>. 
* ビルド: ビルド<88>. 
* Windows: Windows<76>. 
* Tools/Demos: Tools/Demos<54>. 
* C API: C API<74>. 

Python 3.5.5 release candidate 1

* セキュリティ: セキュリティ<57>. 
* Core and Builtins: Core and Builtins<187>. 
* ライブラリ: ライブラリ<190>. 

Python 3.5.4 final

* ライブラリ: ライブラリ<191>. 

Python 3.5.4 release candidate 1

* セキュリティ: セキュリティ<58>. 
* Core and Builtins: Core and Builtins<188>. 
* ライブラリ: ライブラリ<192>. 
* ドキュメント: ドキュメント<78>. 
* テスト: テスト<78>. 
* ビルド: ビルド<89>. 
* Windows: Windows<77>. 
* C API: C API<75>. 

Python 3.5.3 release candidate 1

* セキュリティ: セキュリティ<59>. 
* Core and Builtins: Core and Builtins<189>. 
* ライブラリ: ライブラリ<193>. 
* IDLE: IDLE<57>. 
* C API: C API<76>. 
* ドキュメント: ドキュメント<79>. 
* テスト: テスト<79>. 
* Tools/Demos: Tools/Demos<55>. 
* Windows: Windows<78>. 
* ビルド: ビルド<90>. 

Python 3.5.2 final

* Core and Builtins: Core and Builtins<190>. 
* テスト: テスト<80>. 
* IDLE: IDLE<58>. 

Python 3.5.2 release candidate 1

* セキュリティ: セキュリティ<60>. 
* Core and Builtins: Core and Builtins<191>. 
* ライブラリ: ライブラリ<194>. 
* IDLE: IDLE<59>. 
* ドキュメント: ドキュメント<80>. 
* テスト: テスト<81>. 
* ビルド: ビルド<91>. 
* Windows: Windows<79>. 
* Tools/Demos: Tools/Demos<56>. 

Python 3.5.1 final

* Core and Builtins: Core and Builtins<192>. 
* Windows: Windows<80>. 

Python 3.5.1 release candidate 1

* Core and Builtins: Core and Builtins<193>. 
* ライブラリ: ライブラリ<195>. 
* IDLE: IDLE<60>. 
* ドキュメント: ドキュメント<81>. 
* テスト: テスト<82>. 
* ビルド: ビルド<92>. 
* Windows: Windows<81>. 
* Tools/Demos: Tools/Demos<57>. 

Python 3.5.0 final

* ビルド: ビルド<93>. 

Python 3.5.0 release candidate 4

* ライブラリ: ライブラリ<196>. 
* ビルド: ビルド<94>. 

Python 3.5.0 release candidate 3

* Core and Builtins: Core and Builtins<194>. 
* ライブラリ: ライブラリ<197>. 

Python 3.5.0 release candidate 2

* Core and Builtins: Core and Builtins<195>. 
* ライブラリ: ライブラリ<198>. 

Python 3.5.0 release candidate 1

* Core and Builtins: Core and Builtins<196>. 
* ライブラリ: ライブラリ<199>. 
* IDLE: IDLE<61>. 
* ドキュメント: ドキュメント<82>. 
* テスト: テスト<83>. 

Python 3.5.0 beta 4

* Core and Builtins: Core and Builtins<197>. 
* ライブラリ: ライブラリ<200>. 
* ビルド: ビルド<95>. 

Python 3.5.0 beta 3

* Core and Builtins: Core and Builtins<198>. 
* ライブラリ: ライブラリ<201>. 
* テスト: テスト<84>. 
* ドキュメント: ドキュメント<83>. 
* ビルド: ビルド<96>. 

Python 3.5.0 beta 2

* Core and Builtins: Core and Builtins<199>. 
* ライブラリ: ライブラリ<202>. 

Python 3.5.0 beta 1

* Core and Builtins: Core and Builtins<200>. 
* ライブラリ: ライブラリ<203>. 
* IDLE: IDLE<62>. 
* テスト: テスト<85>. 
* ドキュメント: ドキュメント<84>. 
* Tools/Demos: Tools/Demos<58>. 

Python 3.5.0 alpha 4

* Core and Builtins: Core and Builtins<201>. 
* ライブラリ: ライブラリ<204>. 
* ビルド: ビルド<97>. 
* テスト: テスト<86>. 
* Tools/Demos: Tools/Demos<59>. 
* C API: C API<77>. 

Python 3.5.0 alpha 3

* Core and Builtins: Core and Builtins<202>. 
* ライブラリ: ライブラリ<205>. 
* ビルド: ビルド<98>. 
* テスト: テスト<87>. 
* Tools/Demos: Tools/Demos<60>. 

Python 3.5.0 alpha 2

* Core and Builtins: Core and Builtins<203>. 
* ライブラリ: ライブラリ<206>. 
* ビルド: ビルド<99>. 
* C API: C API<78>. 
* Windows: Windows<82>. 

Python 3.5.0 alpha 1

* Core and Builtins: Core and Builtins<204>. 
* ライブラリ: ライブラリ<207>. 
* IDLE: IDLE<63>. 
* ビルド: ビルド<100>. 
* C API: C API<79>. 
* ドキュメント: ドキュメント<85>. 
* テスト: テスト<88>. 
* Tools/Demos: Tools/Demos<61>. 
* Windows: Windows<83>. 

Python チュートリアル

* やる気を高めよう:: 
* Python インタプリタを使う:: 
* 形式ばらない Python の紹介:: 
* その他の制御フローツール:: 
* データ構造:: 
* モジュール: モジュール<2>. 
* 入力と出力:: 
* エラーと例外:: 
* クラス:: 
* 標準ライブラリミニツアー:: 
* 標準ライブラリミニツアー: 標準ライブラリミニツアー --- その 2. その 2
* 仮想環境とパッケージ:: 
* さあ何を？:: 
* 対話入力編集と履歴置換:: 
* 浮動小数点演算、その問題と制限:: 
* 付録:: 

Python インタプリタを使う

* インタプリタを起動する:: 
* インタプリタとその環境:: 

インタプリタを起動する

* 引数の受け渡し:: 
* 対話モード:: 

インタプリタとその環境

* ソースコードの文字コード:: 

形式ばらない Python の紹介

* Python を電卓として使う:: 
* プログラミングへの第一歩:: 

Python を電卓として使う

* 数:: 
* テキスト:: 
* リスト型 (list): リスト型 list. 

その他の制御フローツール

* if 文:: 
* for 文:: 
* range() 関数: range 関数. 
* break 文と continue 文:: 
* ループの else 節:: 
* pass 文:: 
* match 文:: 
* 関数を定義する:: 
* 関数定義についてもう少し:: 
* 間奏曲; コーディングスタイル: 間奏曲 コーディングスタイル. 

関数定義についてもう少し

* デフォルトの引数値:: 
* キーワード引数:: 
* 特殊なパラメータ:: 
* 任意引数リスト:: 
* 引数リストのアンパック:: 
* ラムダ式:: 
* ドキュメンテーション文字列:: 
* 関数のアノテーション:: 

特殊なパラメータ

* 位置またはキーワード引数:: 
* 位置専用引数: 位置専用引数<2>. 
* キーワード専用引数:: 
* 関数の例:: 
* 要約:: 

データ構造

* リスト型についてもう少し:: 
* del 文:: 
* タプルとシーケンス:: 
* 集合型:: 
* 辞書型 (dictionary): 辞書型 dictionary. 
* ループのテクニック:: 
* 条件についてもう少し:: 
* シーケンスとその他の型の比較:: 

リスト型についてもう少し

* リストをスタックとして使う:: 
* リストをキューとして使う:: 
* リストの内包表記: リストの内包表記<2>. 
* ネストしたリストの内包表記:: 

モジュール

* モジュールについてもうすこし:: 
* 標準モジュール:: 
* dir() 関数: dir 関数. 
* パッケージ:: 

モジュールについてもうすこし

* モジュールをスクリプトとして実行する:: 
* モジュール検索パス:: 
* "コンパイル" された Python ファイル:: 

パッケージ

* パッケージから * を import する:: 
* パッケージ内参照:: 
* 複数ディレクトリ中のパッケージ:: 

入力と出力

* 出力を見やすくフォーマットする:: 
* ファイルを読み書きする:: 

出力を見やすくフォーマットする

* フォーマット済み文字列リテラル:: 
* 文字列の format() メソッド: 文字列の format メソッド. 
* 文字列の手作業でのフォーマット:: 
* 古い文字列書式設定方法:: 

ファイルを読み書きする

* ファイルオブジェクトのメソッド:: 
* json による構造化されたデータの保存:: 

エラーと例外

* 構文エラー:: 
* 例外:: 
* 例外を処理する:: 
* 例外を送出する:: 
* 例外の連鎖:: 
* ユーザー定義例外:: 
* クリーンアップ動作を定義する:: 
* 定義済みクリーンアップ処理:: 
* 複数の関連しない例外の送出と処理:: 
* ノートによって例外を充実させる:: 

クラス

* 名前とオブジェクトについて:: 
* Python のスコープと名前空間:: 
* クラス初見:: 
* いろいろな注意点:: 
* 継承:: 
* プライベート変数:: 
* 残りのはしばし:: 
* イテレータ (iterator): イテレータ iterator. 
* ジェネレータ (generator): ジェネレータ generator. 
* ジェネレータ式:: 

Python のスコープと名前空間

* スコープと名前空間の例:: 

クラス初見

* クラス定義の構文:: 
* クラスオブジェクト:: 
* インスタンスオブジェクト:: 
* メソッドオブジェクト:: 
* クラスとインスタンス変数:: 

継承

* 多重継承:: 

標準ライブラリミニツアー

* OSへのインターフェース:: 
* ファイルのワイルドカード表記:: 
* コマンドライン引数:: 
* エラー出力のリダイレクトとプログラムの終了:: 
* 文字列のパターンマッチング:: 
* 数学:: 
* インターネットへのアクセス:: 
* 日付と時刻:: 
* データ圧縮:: 
* パフォーマンスの計測:: 
* 品質管理:: 
* バッテリー同梱:: 

標準ライブラリミニツアー --- その 2

* 出力のフォーマット:: 
* 文字列テンプレート:: 
* バイナリデータレコードの操作:: 
* マルチスレッディング: マルチスレッディング<2>. 
* ログ記録:: 
* 弱参照:: 
* リスト操作のためのツール:: 
* 10 進浮動小数演算:: 

仮想環境とパッケージ

* はじめに: はじめに<4>. 
* 仮想環境の作成:: 
* pip を使ったパッケージ管理:: 

対話入力編集と履歴置換

* タブ補完と履歴編集:: 
* 対話的インタープリタの代替:: 

浮動小数点演算、その問題と制限

* 表現エラー:: 

付録

* 対話モード: 対話モード<2>. 

対話モード

* エラー処理:: 
* 実行可能な Python スクリプト:: 
* 対話モード用の起動時実行ファイル:: 
* カスタマイズ用モジュール:: 

Python のセットアップと利用

* コマンドラインと環境: コマンドラインと環境<2>. 
* Unix プラットフォームで Python を使う:: 
* Python を構成する:: 
* Windows で Python を使う:: 
* macOS で Python を使う:: 
* Android で Python を使う:: 
* iOS で Python を使う:: 
* エディタと IDE:: 

コマンドラインと環境

* コマンドライン:: 
* 環境変数:: 

コマンドライン

* インターフェイスオプション:: 
* 一般オプション:: 
* その他のオプション:: 
* 色の制御:: 

環境変数

* デバッグモード変数:: 

Unix プラットフォームで Python を使う

* 最新バージョンの Python の取得とインストール:: 
* Python のビルド:: 
* Python に関係するパスとファイル:: 
* その他: その他<2>. 
* カスタムの OpenSSL:: 

最新バージョンの Python の取得とインストール

* Linux:: 
* FreeBSD と OpenBSD:: 

Linux

* IDLE のインストール:: 

Python を構成する

* ビルド要件:: 
* 生成されるファイル:: 
* Configureオプション:: 
* Python ビルドシステム:: 
* Compiler and linker flags:: 

ビルド要件

* オプションのモジュールの要件:: 

生成されるファイル

* 構成スクリプト:: 

Configureオプション

* 一般的なオプション:: 
* C コンパイラのオプション:: 
* リンカのオプション:: 
* サードパーティ依存関係のオプション:: 
* WebAssembly オプション:: 
* インストールオプション:: 
* パフォーマンスに関するオプション:: 
* Python デバッグビルド:: 
* Debug options:: 
* リンカのオプション: リンカのオプション<2>. 
* Libraries options:: 
* Security Options:: 
* macOS のオプション:: 
* iOS のオプション:: 
* クロスコンパイルのオプション:: 

Python ビルドシステム

* ビルドシステムの主要なファイル:: 
* 主要なビルドステップ:: 
* Main Makefile targets:: 
* C extensions:: 

Main Makefile targets

* make:: 
* make platform:: 
* make profile-opt:: 
* make clean:: 
* make distclean:: 
* make install:: 
* make test:: 
* make ci:: 
* make buildbottest:: 
* make regen-all:: 

Compiler and linker flags

* Preprocessor flags:: 
* Compiler flags:: 
* Linker flags:: 

Windows で Python を使う

* Python install manager:: 
* 埋め込み可能なパッケージ:: 
* nuget.org パッケージ: nuget org パッケージ. 
* 別のバンドル:: 
* Supported Windows versions:: 
* Removing the MAX_PATH limitation:: 
* UTF-8 モード:: 
* モジュールの検索:: 
* 追加のモジュール:: 
* Windows 上で Python をコンパイルする:: 
* The full installer (deprecated): The full installer deprecated. 
* Python launcher for Windows (deprecated): Python launcher for Windows deprecated. 

Python install manager

* Installation:: 
* 基本的な使い方:: 
* Command help:: 
* Listing runtimes:: 
* Installing runtimes:: 
* Offline installs:: 
* Uninstalling runtimes:: 
* Configuration:: 
* Shebang lines:: 
* Advanced installation:: 
* Administrative configuration:: 
* Installing free-threaded binaries:: 
* Troubleshooting:: 

埋め込み可能なパッケージ

* Python application:: 
* Python の埋め込み:: 

nuget.org パッケージ

* フリースレッドパッケージ (Free-threaded packages): フリースレッドパッケージ Free-threaded packages. 

追加のモジュール

* PyWin32:: 
* cx_Freeze:: 

The full installer (deprecated)

* インストール手順:: 
* Removing the MAX_PATH limitation: Removing the MAX_PATH limitation<2>. 
* Installing without UI:: 
* Installing without downloading:: 
* インストール後の変更:: 
* Installing free-threaded binaries: Installing free-threaded binaries<2>. 

Python launcher for Windows (deprecated)

* 最初に:: 
* Shebang lines: Shebang lines<2>. 
* シェバン行の引数:: 
* カスタマイズ:: 
* 診断:: 
* Dry run:: 
* Install on demand:: 
* Return codes:: 

最初に

* コマンドラインから起動する:: 
* 仮想環境 (Virtual environments): 仮想環境 Virtual environments. 
* スクリプトから起動する:: 
* ファイルの関連付けから起動する:: 

カスタマイズ

* INI ファイルによるカスタマイズ:: 
* デフォルトのPythonバージョンのカスタマイズ:: 

macOS で Python を使う

* Using Python for macOS from python.org: Using Python for macOS from python org. 
* Alternative Distributions:: 
* 追加の Python パッケージのインストール:: 
* GUI プログラミング:: 
* 高度なトピック:: 
* 他のリソース:: 

Using Python for macOS from python.org

* インストール手順: インストール手順<2>. 
* Python スクリプトの実行方法:: 

高度なトピック

* フリースレッドバイナリ (Free-threaded Binaries) のインストール: フリースレッドバイナリ Free-threaded Binaries のインストール. 
* Installing using the command line:: 
* Python アプリケーションの配布:: 
* App Store コンプライアンス:: 

Android で Python を使う

* Android アプリに Python を追加する:: 
* Android 向けの Python パッケージをビルドする:: 

iOS で Python を使う

* iOS ランタイムでの Python:: 
* iOS での Python のインストール:: 
* App Store コンプライアンス: App Store コンプライアンス<2>. 

iOS ランタイムでの Python

* iOS のバージョン互換性:: 
* プラットフォームの識別:: 
* 標準ライブラリの利用可能性:: 
* バイナリ拡張モジュール:: 
* コンパイラスタブバイナリ:: 

iOS での Python のインストール

* iOS アプリビルド用のツール:: 
* iOS プロジェクトに Python を追加する:: 
* Python パッケージのテスト:: 

App Store コンプライアンス

* 標準ライブラリ内の互換性のないコード:: 
* プライバシーマニフェスト:: 

エディタと IDE

* IDLE: IDLE --- Python のエディタとシェル. Python のエディタとシェル
* Other Editors and IDEs:: 

Python 言語リファレンス

* はじめに: はじめに<5>. 
* 字句解析:: 
* データモデル:: 
* 実行モデル:: 
* インポートシステム:: 
* 式 (expression): 式 expression. 
* 単純文 (simple statement): 単純文 simple statement. 
* 複合文 (compound statement): 複合文 compound statement. 
* トップレベル要素:: 
* 完全な文法仕様:: 

はじめに

* 別のPythonの実装:: 
* 本マニュアルにおける表記法:: 

本マニュアルにおける表記法

* Lexical and Syntactic definitions:: 

字句解析

* 行構造:: 
* その他のトークン:: 
* Names (identifiers and keywords): Names identifiers and keywords. 
* リテラル:: 
* 文字列およびバイト列リテラル:: 
* 数値リテラル:: 
* Operators and delimiters:: 

行構造

* 論理行 (logical line): 論理行 logical line. 
* 物理行 (physical line): 物理行 physical line. 
* コメント (Comments): コメント Comments. 
* エンコード宣言 (encoding declaration): エンコード宣言 encoding declaration. 
* 明示的な行継続:: 
* 非明示的な行継続:: 
* 空行:: 
* インデント:: 
* トークン間の空白:: 
* End marker:: 

Names (identifiers and keywords)

* キーワード (keyword): キーワード keyword. 
* ソフトキーワード:: 
* 予約済みの識別子種 (reserved classes of identifiers): 予約済みの識別子種 reserved classes of identifiers. 
* Non-ASCII characters in names:: 

文字列およびバイト列リテラル

* Triple-quoted strings:: 
* String prefixes:: 
* Formal grammar:: 
* Escape sequences:: 
* Bytes literals:: 
* Raw string literals:: 
* f-strings:: 
* t-strings:: 
* Formal grammar for f-strings:: 

Escape sequences

* Ignored end of line:: 
* Escaped characters:: 
* Octal character:: 
* Hexadecimal character:: 
* Named Unicode character:: 
* Hexadecimal Unicode characters:: 
* Unrecognized escape sequences:: 

数値リテラル

* 整数リテラル:: 
* Floating-point literals:: 
* 虚数 (imaginary) リテラル: 虚数 imaginary リテラル. 

データモデル

* オブジェクト、値、および型:: 
* 標準型の階層:: 
* 特殊メソッド名:: 
* コルーチン:: 

標準型の階層

* None:: 
* NotImplemented:: 
* Ellipsis:: 
* numbers.Number: numbers Number. 
* シーケンス型 (sequence): シーケンス型 sequence. 
* 集合型: 集合型<2>. 
* マッピング型 (mapping): マッピング型 mapping. 
* 呼び出し可能型 (callable type): 呼び出し可能型 callable type. 
* モジュール: モジュール<3>. 
* カスタムクラス型:: 
* クラスインスタンス (class instance): クラスインスタンス class instance. 
* I/O オブジェクト (ファイルオブジェクトの別名): I/O オブジェクト ファイルオブジェクトの別名. 
* 内部型 (internal type): 内部型 internal type. 

numbers.Number

* numbers.Integral (整数): numbers Integral 整数. 
* numbers.Real (float) (実数): numbers Real float 実数. 
* numbers.Complex (complex): numbers Complex complex. 

シーケンス型 (sequence)

* 変更不能なシーケンス (immutable sequence): 変更不能なシーケンス immutable sequence. 
* 変更可能なシーケンス型 (mutable sequence): 変更可能なシーケンス型 mutable sequence. 

マッピング型 (mapping)

* 辞書型 (dictionary): 辞書型 dictionary<2>. 

呼び出し可能型 (callable type)

* ユーザ定義関数 (user-defined function): ユーザ定義関数 user-defined function. 
* インスタンスメソッド:: 
* ジェネレータ関数 (generator function): ジェネレータ関数 generator function. 
* コルーチン関数 (coroutine function): コルーチン関数 coroutine function. 
* 非同期ジェネレータ関数 (asynchronous generator function): 非同期ジェネレータ関数 asynchronous generator function. 
* 組み込み関数 (built-in function): 組み込み関数 built-in function. 
* 組み込みメソッド (built-in method): 組み込みメソッド built-in method. 
* クラス: クラス<2>. 
* クラスのインスタンス:: 

ユーザ定義関数 (user-defined function)

* Special read-only attributes:: 
* Special writable attributes:: 

モジュール

* Import-related attributes on module objects:: 
* Other writable attributes on module objects:: 
* Module dictionaries:: 

カスタムクラス型

* Special attributes:: 
* Special methods:: 

クラスインスタンス (class instance)

* Special attributes: Special attributes<2>. 

内部型 (internal type)

* コードオブジェクト:: 
* フレーム (frame) オブジェクト: フレーム frame オブジェクト. 
* トレースバック (traceback) オブジェクト: トレースバック traceback オブジェクト. 
* スライス (slice) オブジェクト: スライス slice オブジェクト. 
* 静的メソッド (static method) オブジェクト: 静的メソッド static method オブジェクト. 
* クラスメソッドオブジェクト:: 

コードオブジェクト

* Special read-only attributes: Special read-only attributes<2>. 
* Methods on code objects:: 

フレーム (frame) オブジェクト

* Special read-only attributes: Special read-only attributes<3>. 
* Special writable attributes: Special writable attributes<2>. 
* Frame object methods:: 

特殊メソッド名

* 基本的なカスタマイズ:: 
* 属性値アクセスをカスタマイズする:: 
* クラス生成をカスタマイズする:: 
* インスタンスのカスタマイズとサブクラスチェック:: 
* ジェネリック型をエミュレートする:: 
* 呼び出し可能オブジェクトをエミュレートする:: 
* コンテナをエミュレートする:: 
* 数値型をエミュレートする:: 
* with文とコンテキストマネージャ:: 
* クラスパターンマッチの位置引数のカスタマイズ:: 
* Emulating buffer types:: 
* Annotations:: 
* 特殊メソッド検索:: 

属性値アクセスをカスタマイズする

* モジュールの属性値アクセスをカスタマイズする:: 
* デスクリプタ (descriptor) の実装: デスクリプタ descriptor の実装. 
* デスクリプタの呼び出し:: 
* __slots__: __slots__<2>. 

クラス生成をカスタマイズする

* メタクラス:: 
* MRO エントリの解決:: 
* 適切なメタクラスの決定:: 
* クラスの名前空間の準備:: 
* クラス本体の実行:: 
* クラスオブジェクトの作成:: 
* メタクラスの用途:: 

ジェネリック型をエミュレートする

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

コルーチン

* 待機可能オブジェクト (Awaitable Object): 待機可能オブジェクト Awaitable Object. 
* コルーチンオブジェクト:: 
* 非同期イテレータ (Asynchronous Iterator): 非同期イテレータ Asynchronous Iterator. 
* 非同期コンテキストマネージャ (Asynchronous Context Manager): 非同期コンテキストマネージャ Asynchronous Context Manager. 

実行モデル

* プログラムの構造:: 
* 名前づけと束縛 (naming and binding): 名前づけと束縛 naming and binding. 
* 例外: 例外<2>. 
* Runtime Components:: 

名前づけと束縛 (naming and binding)

* 名前の束縛:: 
* 名前解決:: 
* Annotation scopes:: 
* Lazy evaluation:: 
* 組み込みと制限付きの実行:: 
* 動的な機能とのやりとり:: 

Runtime Components

* General Computing Model:: 
* Python Runtime Model:: 

インポートシステム

* importlib: importlib<10>. 
* パッケージ: パッケージ<2>. 
* 検索:: 
* ロード:: 
* パスベース・ファインダー:: 
* 標準のインポートシステムを置き換える:: 
* Package Relative Imports:: 
* __main__ に対する特別な考慮:: 
* 参考資料:: 

パッケージ

* 通常のパッケージ:: 
* 名前空間パッケージ:: 

検索

* モジュールキャッシュ:: 
* ファインダーとローダー:: 
* インポートフック:: 
* メタパス:: 

ロード

* ローダー:: 
* サブモジュール:: 
* Module specs:: 
* __path__ attributes on modules:: 
* モジュールの repr:: 
* キャッシュされたバイトコードの無効化:: 

パスベース・ファインダー

* パスエントリ・ファインダー:: 
* パスエントリ・ファインダー・プロトコル:: 

__main__ に対する特別な考慮

* __main__.__spec__: __main__ __spec__. 

式 (expression)

* 算術変換 (arithmetic conversion): 算術変換 arithmetic conversion. 
* アトム、原子的要素 (atom): アトム、原子的要素 atom. 
* プライマリ:: 
* Await 式:: 
* べき乗演算 (power operator): べき乗演算 power operator. 
* 単項算術演算とビット単位演算 (unary arithmetic and bitwise operation): 単項算術演算とビット単位演算 unary arithmetic and bitwise operation. 
* 二項算術演算 (binary arithmetic operation): 二項算術演算 binary arithmetic operation. 
* シフト演算 (shifting operation): シフト演算 shifting operation. 
* ビット単位演算の二項演算 (binary bitwise operation): ビット単位演算の二項演算 binary bitwise operation. 
* 比較:: 
* ブール演算 (boolean operation): ブール演算 boolean operation. 
* 代入式: 代入式<2>. 
* 条件式 (Conditional Expressions): 条件式 Conditional Expressions. 
* ラムダ (lambda): ラムダ lambda. 
* 式のリスト:: 
* 評価順序:: 
* 演算子の優先順位:: 

アトム、原子的要素 (atom)

* Built-in constants:: 
* 識別子 (identifier、または名前 (name)): 識別子 identifier、または名前 name. 
* リテラル: リテラル<2>. 
* 丸括弧形式 (parenthesized form): 丸括弧形式 parenthesized form. 
* リスト、集合、辞書の表示:: 
* リスト表示:: 
* 集合表示:: 
* 辞書表示:: 
* ジェネレータ式: ジェネレータ式<2>. 
* Yield 式:: 

識別子 (identifier、または名前 (name))

* Private name mangling:: 

リテラル

* Literals and object identity:: 
* 文字列リテラルの結合 (concatenation): 文字列リテラルの結合 concatenation. 

Yield 式

* ジェネレータ-イテレータメソッド:: 
* 使用例:: 
* 非同期ジェネレータ関数 (asynchronous generator function): 非同期ジェネレータ関数 asynchronous generator function<2>. 
* 非同期ジェネレータイテレータメソッド:: 

プライマリ

* 属性参照:: 
* Subscriptions and slicings:: 
* 呼び出し (call): 呼び出し call. 

Subscriptions and slicings

* スライス表記 (slicing): スライス表記 slicing. 
* Comma-separated subscripts:: 
* "Starred" subscriptions:: 
* Formal subscription grammar:: 

比較

* 値の比較:: 
* 所属検査演算:: 
* 同一性の比較:: 

単純文 (simple statement)

* 式文 (expression statement): 式文 expression statement. 
* 代入文 (assignment statement): 代入文 assignment statement. 
* assert 文:: 
* pass 文: pass 文<2>. 
* del 文: del 文<2>. 
* return 文:: 
* yield 文:: 
* raise 文:: 
* break 文:: 
* continue 文:: 
* import 文:: 
* global 文:: 
* nonlocal 文:: 
* The type statement:: 

代入文 (assignment statement)

* 累算代入文 (augmented assignment statement): 累算代入文 augmented assignment statement. 
* 注釈付き代入文 (annotated assignment statements): 注釈付き代入文 annotated assignment statements. 

import 文

* future 文 (future statement): future 文 future statement. 

複合文 (compound statement)

* if 文: if 文<2>. 
* while 文:: 
* for 文: for 文<2>. 
* try 文:: 
* with 文:: 
* match 文: match 文<2>. 
* 関数定義:: 
* クラス定義:: 
* コルーチン: コルーチン<2>. 
* Type parameter lists:: 
* Annotations: Annotations<2>. 

try 文

* except 節:: 
* except* 節:: 
* else 節:: 
* finally 節:: 

match 文

* 概要:: 
* ガード: ガード<2>. 
* 論駁不可能なケースブロック:: 
* パターン:: 

パターン

* OR パターン:: 
* AS パターン:: 
* リテラルパターン:: 
* キャプチャパターン:: 
* ワイルドカードパターン:: 
* 値パターン:: 
* グループパターン:: 
* シーケンスパターン:: 
* マッピングパターン:: 
* クラスパターン:: 

コルーチン

* コルーチン関数定義:: 
* async for 文:: 
* async with 文:: 

Type parameter lists

* Generic functions:: 
* Generic classes:: 
* Generic type aliases:: 

トップレベル要素

* 完全な Python プログラム:: 
* ファイル入力:: 
* 対話的入力:: 
* 式入力:: 

Python 標準ライブラリ

* はじめに: はじめに<6>. 
* 組み込み関数:: 
* 組み込み定数:: 
* 組み込み型:: 
* 組み込み例外:: 
* テキスト処理サービス:: 
* バイナリデータ処理:: 
* データ型:: 
* 数値と数学モジュール:: 
* 関数型プログラミング用モジュール:: 
* ファイルとディレクトリへのアクセス:: 
* データの永続化:: 
* データ圧縮とアーカイブ:: 
* ファイルフォーマット:: 
* 暗号関連のサービス:: 
* 汎用オペレーティングシステムサービス:: 
* コマンドラインインターフェースライブラリ:: 
* 並行実行:: 
* ネットワーク通信とプロセス間通信:: 
* インターネット上のデータの操作:: 
* 構造化マークアップツール:: 
* インターネットプロトコルとサポート:: 
* マルチメディアサービス:: 
* 国際化:: 
* Graphical user interfaces with Tk:: 
* 開発ツール:: 
* デバッグとプロファイル:: 
* ソフトウェア・パッケージと配布:: 
* Python ランタイムサービス:: 
* カスタム Python インタプリタ:: 
* モジュールのインポート:: 
* Python言語サービス:: 
* MS Windows 固有のサービス:: 
* Unix-specific services:: 
* モジュールのコマンドラインインターフェース (CLI): モジュールのコマンドラインインターフェース CLI. 
* 取って代わられたモジュール群:: 
* 削除されたモジュール:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<6>. 

はじめに

* 利用可能性について:: 

利用可能性について

* WebAssembly プラットフォーム:: 
* モバイルプラットフォーム:: 

組み込み定数

* site モジュールで追加される定数:: 

組み込み型

* 真理値判定:: 
* ブール演算: ブール演算 --- and or not. and, or, not
* 比較: 比較<2>. 
* 数値型 int@comma{} float@comma{} complex: 数値型 int float complex. 
* ブーリアン型 - bool:: 
* イテレータ型:: 
* シーケンス型: シーケンス型 --- list tuple range. list, tuple, range
* Text and Binary Sequence Type Methods Summary:: 
* テキストシーケンス型: テキストシーケンス型 --- str. str
* バイナリシーケンス型: バイナリシーケンス型 --- bytes bytearray memoryview. bytes, bytearray, memoryview
* set（集合）型: set（集合）型 --- set frozenset. set, frozenset
* マッピング型: マッピング型 --- dict. dict
* コンテキストマネージャ型:: 
* 型アノテーション型: 型アノテーション型 --- ジェネリックエイリアス 、 ユニオン. ジェネリックエイリアス 、 ユニオン
* その他の組み込み型:: 
* 特殊属性:: 
* 整数と文字列の変換での長さ制限:: 

数値型 int, float, complex

* 整数型におけるビット単位演算:: 
* 整数型における追加のメソッド:: 
* 浮動小数点数に対する追加のメソッド:: 
* 複素数に対する追加のメソッド:: 
* 数値型のハッシュ化:: 

イテレータ型

* ジェネレータ型:: 

シーケンス型 --- list, tuple, range

* 共通のシーケンス演算:: 
* イミュータブルなシーケンス型:: 
* ミュータブルなシーケンス型:: 
* リスト型 (list): リスト型 list<2>. 
* タプル型 (tuple): タプル型 tuple. 
* range:: 

テキストシーケンス型 --- str

* 文字列メソッド: 文字列メソッド<2>. 
* Formatted String Literals (f-strings): Formatted String Literals f-strings. 
* Template String Literals (t-strings): Template String Literals t-strings. 
* printf 形式の文字列書式化:: 

Formatted String Literals (f-strings)

* Debug specifier:: 
* Conversion specifier:: 
* Format specifier:: 

バイナリシーケンス型 --- bytes, bytearray, memoryview

* バイトオブジェクト:: 
* bytearray オブジェクト:: 
* bytes と bytearray の操作:: 
* printf 形式での bytes の書式化:: 
* メモリビュー:: 

マッピング型 --- dict

* 辞書ビューオブジェクト:: 

型アノテーション型 --- ジェネリックエイリアス 、 ユニオン

* ジェネリックエイリアス型:: 
* Union 型:: 

ジェネリックエイリアス型

* 標準ジェネリッククラス:: 
* GenericAlias オブジェクトの特別な属性:: 

その他の組み込み型

* モジュール: モジュール<4>. 
* クラスおよびクラスインスタンス:: 
* 関数:: 
* メソッド:: 
* コードオブジェクト: コードオブジェクト<2>. 
* 型オブジェクト:: 
* ヌルオブジェクト:: 
* Ellipsis オブジェクト:: 
* NotImplemented オブジェクト:: 
* 内部オブジェクト:: 

整数と文字列の変換での長さ制限

* 影響のあるAPI:: 
* 上限値を設定する:: 
* 推奨設定:: 

組み込み例外

* 例外コンテキスト:: 
* 組み込み例外から継承する:: 
* 基底クラス:: 
* 具象例外:: 
* 警告:: 
* 例外グループ:: 
* 例外のクラス階層:: 

具象例外

* OS 例外:: 

テキスト処理サービス

* string: string --- 一般的な文字列操作. 一般的な文字列操作
* string.templatelib: string templatelib --- テンプレート文字列リテラルのサポート. テンプレート文字列リテラルのサポート
* 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 --- 一般的な文字列操作

* 文字列定数:: 
* カスタムの文字列書式化:: 
* 書式指定文字列の文法:: 
* Template strings ($-strings): Template strings $-strings. 
* ヘルパー関数:: 

書式指定文字列の文法

* 書式指定ミニ言語仕様:: 
* 書式指定例:: 

string.templatelib --- テンプレート文字列リテラルのサポート

* テンプレート文字列:: 
* 型:: 
* ヘルパー関数: ヘルパー関数<2>. 

re --- 正規表現操作

* 正規表現のシンタックス:: 
* モジュールコンテンツ:: 
* 正規表現オブジェクト:: 
* マッチオブジェクト:: 
* 正規表現の例:: 

モジュールコンテンツ

* フラグ:: 
* 関数: 関数<2>. 
* 例外: 例外<3>. 

正規表現の例

* ペアの確認:: 
* scanf() をシミュレートする: scanf をシミュレートする. 
* search() vs. match(): search vs match. 
* 電話帳を作る:: 
* テキストの秘匿:: 
* 全ての副詞を見つける:: 
* 全ての副詞とその位置を見つける:: 
* Raw 文字列記法:: 
* トークナイザを書く:: 

difflib --- 差分の計算の補助

* SequenceMatcherオブジェクト:: 
* SequenceMatcher の例:: 
* Differ オブジェクト:: 
* Differ の例:: 
* difflib のコマンドラインインターフェース:: 
* ndiff example:: 

readline --- GNU readline のインターフェース

* 初期化ファイル:: 
* 行バッファ:: 
* 履歴ファイル:: 
* 履歴リスト:: 
* 開始フック:: 
* 補完:: 
* 使用例: 使用例<2>. 

バイナリデータ処理

* struct: struct --- バイト列をパックされたバイナリデータとして解釈する. バイト列をパックされたバイナリデータとして解釈する
* codecs: codecs --- codec レジストリと基底クラス. codec レジストリと基底クラス

struct --- バイト列をパックされたバイナリデータとして解釈する

* 関数と例外:: 
* 書式文字列:: 
* アプリケーション:: 
* クラス: クラス<3>. 

書式文字列

* バイトオーダ、サイズ、アラインメント:: 
* 書式指定文字:: 
* 使用例: 使用例<3>. 

アプリケーション

* Native Formats:: 
* Standard Formats:: 

codecs --- codec レジストリと基底クラス

* Codec 基底クラス:: 
* エンコーディングと Unicode:: 
* 標準エンコーディング:: 
* Python 特有のエンコーディング:: 
* encodings: encodings --- Encodings package. Encodings package
* encodings.idna: encodings idna --- Internationalized Domain Names in Applications. Internationalized Domain Names in Applications
* encodings.mbcs: encodings mbcs --- Windows ANSI codepage. Windows ANSI codepage
* encodings.utf_8_sig: encodings utf_8_sig --- UTF-8 codec with BOM signature. UTF-8 codec with BOM signature

Codec 基底クラス

* エラーハンドラ:: 
* ステートレスなエンコードとデコード:: 
* インクリメンタルなエンコードとデコード:: 
* ストリームのエンコードとデコード:: 

インクリメンタルなエンコードとデコード

* IncrementalEncoder オブジェクト:: 
* IncrementalDecoder オブジェクト:: 

ストリームのエンコードとデコード

* StreamWriter オブジェクト:: 
* StreamReader オブジェクト:: 
* StreamReaderWriter オブジェクト:: 
* StreamRecoder オブジェクト:: 

Python 特有のエンコーディング

* テキストエンコーディング:: 
* バイナリ変換 (Binary Transforms): バイナリ変換 Binary Transforms. 
* Standalone Codec Functions:: 
* テキスト変換 (Text Transforms): テキスト変換 Text Transforms. 

データ型

* datetime: datetime --- 基本的な日付と時間の型. 基本的な日付と時間の型
* zoneinfo: zoneinfo --- IANA タイムゾーンのサポート. IANA タイムゾーンのサポート
* calendar: calendar --- 一般的なカレンダーに関係する機能群. 一般的なカレンダーに関係する機能群
* collections: collections --- コンテナデータ型. コンテナデータ型
* collections.abc: collections abc --- コンテナの抽象基底クラス. コンテナの抽象基底クラス
* heapq: heapq --- ヒープキューアルゴリズム. ヒープキューアルゴリズム
* bisect: bisect --- 配列二分法アルゴリズム. 配列二分法アルゴリズム
* array: array --- 効率的な数値配列. 効率的な数値配列
* weakref: weakref --- Weak references. Weak references
* types: types --- 動的な型生成と組み込み型の名前. 動的な型生成と組み込み型の名前
* copy: copy --- 浅いコピーおよび深いコピー操作. 浅いコピーおよび深いコピー操作
* pprint: pprint --- データの整形表示. データの整形表示
* reprlib: reprlib --- もう一つの repr の実装. もう一つの repr() の実装
* enum: enum --- 列挙型のサポート. 列挙型のサポート
* graphlib: graphlib --- グラフ構造を操作する機能. グラフ構造を操作する機能

datetime --- 基本的な日付と時間の型

* Aware and naive objects:: 
* 定数:: 
* Available types:: 
* timedelta objects:: 
* date objects:: 
* datetime objects:: 
* time objects:: 
* tzinfo objects:: 
* timezone objects:: 
* strftime() and strptime() behavior: strftime and strptime behavior. 

Available types

* Common properties:: 
* Determining if an object is aware or naive:: 

timedelta objects

* Examples of usage; timedelta: Examples of usage timedelta. 

date objects

* Examples of usage; date: Examples of usage date. 

datetime objects

* Examples of usage; datetime: Examples of usage datetime. 

time objects

* Examples of usage; time: Examples of usage time. 

strftime() and strptime() behavior

* strftime() and strptime() format codes: strftime and strptime format codes. 
* Technical detail:: 

zoneinfo --- IANA タイムゾーンのサポート

* ZoneInfo を使用する:: 
* データソース:: 
* ZoneInfo クラス:: 
* 関数: 関数<3>. 
* Globals:: 
* 例外と警告:: 

データソース

* Configuring the data sources:: 

Configuring the data sources

* Compile-time configuration:: 
* Environment configuration:: 
* Runtime configuration:: 

ZoneInfo クラス

* 文字列表現:: 
* Pickle serialization:: 

calendar --- 一般的なカレンダーに関係する機能群

* コマンドラインでの使用:: 

collections --- コンテナデータ型

* ChainMap オブジェクト:: 
* Counter オブジェクト:: 
* deque オブジェクト:: 
* defaultdict オブジェクト:: 
* namedtuple() 名前付きフィールドを持つタプルのファクトリ関数: namedtuple 名前付きフィールドを持つタプルのファクトリ関数. 
* OrderedDict オブジェクト:: 
* UserDict オブジェクト:: 
* UserList オブジェクト:: 
* UserString オブジェクト:: 

ChainMap オブジェクト

* ChainMap の例とレシピ:: 

deque オブジェクト

* deque のレシピ:: 

defaultdict オブジェクト

* defaultdict の使用例:: 

OrderedDict オブジェクト

* OrderedDict の例とレシピ:: 

collections.abc --- コンテナの抽象基底クラス

* コレクション抽象基底クラス:: 
* コレクションの抽象基底クラス: コレクションの抽象基底クラス -- 詳細な説明. 詳細な説明
* 例とレシピ:: 

heapq --- ヒープキューアルゴリズム

* 基本的な例:: 
* Other Applications:: 
* 優先度キュー実装の注釈:: 
* 理論:: 

bisect --- 配列二分法アルゴリズム

* パフォーマンスに関するメモ:: 
* ソート済みリストの探索:: 
* 使用例: 使用例<4>. 

weakref --- Weak references

* 弱参照オブジェクト:: 
* 使用例: 使用例<5>. 
* ファイナライザオブジェクト:: 
* Comparing finalizers with __del__() methods: Comparing finalizers with __del__ methods. 

types --- 動的な型生成と組み込み型の名前

* 動的な型生成:: 
* 標準的なインタプリタ型:: 
* 追加のユーティリティクラスと関数:: 
* コルーチンユーティリティ関数:: 

pprint --- データの整形表示

* 関数: 関数<4>. 
* PrettyPrinter オブジェクト:: 
* 使用例: 使用例<6>. 

reprlib --- もう一つの repr() の実装

* Reprオブジェクト:: 
* Reprオブジェクトをサブクラス化する:: 

enum --- 列挙型のサポート

* モジュールコンテンツ: モジュールコンテンツ<2>. 
* データ型: データ型<2>. 
* ユーティリティとデコレータ:: 
* 注釈:: 

データ型

* __dunder__ 名のサポート:: 
* _sunder_ 名のサポート:: 

graphlib --- グラフ構造を操作する機能

* 例外: 例外<4>. 

数値と数学モジュール

* numbers: numbers --- 数の抽象基底クラス. 数の抽象基底クラス
* math: math --- 数学関数. 数学関数
* cmath: cmath --- 複素数用の数学関数. 複素数用の数学関数
* decimal: decimal --- 10進固定小数点と浮動小数点の演算. 10進固定小数点と浮動小数点の演算
* fractions: fractions --- 有理数. 有理数
* random: random --- 疑似乱数を生成する. 疑似乱数を生成する
* statistics: statistics --- 数学的統計関数. 数学的統計関数

numbers --- 数の抽象基底クラス

* 数値塔:: 
* Notes for type implementers:: 

Notes for type implementers

* さらに数のABCを追加する:: 
* 算術演算の実装:: 

math --- 数学関数

* Number-theoretic functions:: 
* Floating point arithmetic:: 
* Floating point manipulation functions:: 
* Power@comma{} exponential and logarithmic functions: Power exponential and logarithmic functions. 
* Summation and product functions:: 
* 角度変換:: 
* 三角関数:: 
* 双曲線関数:: 
* 特殊関数:: 
* 定数: 定数<2>. 

cmath --- 複素数用の数学関数

* 極座標変換:: 
* 指数関数と対数関数:: 
* 三角関数: 三角関数<2>. 
* 双曲線関数: 双曲線関数<2>. 
* 類別関数:: 
* 定数: 定数<3>. 

decimal --- 10進固定小数点と浮動小数点の演算

* Quick-start tutorial:: 
* Decimal オブジェクト:: 
* Context オブジェクト:: 
* 定数: 定数<4>. 
* 丸めモード:: 
* シグナル:: 
* Floating-point notes:: 
* スレッドを使った処理:: 
* レシピ:: 
* Decimal FAQ:: 

Decimal オブジェクト

* 論理引数:: 

Floating-point notes

* 精度を上げて丸め誤差を抑制する:: 
* 特殊値:: 

random --- 疑似乱数を生成する

* 保守 (bookkeeping) 関数: 保守 bookkeeping 関数. 
* バイト列用の関数:: 
* 整数用の関数:: 
* シーケンス用の関数:: 
* Discrete distributions:: 
* 実数分布:: 
* 他の生成器:: 
* 再現性について:: 
* 使用例: 使用例<7>. 
* レシピ: レシピ<2>. 
* コマンドラインでの使用: コマンドラインでの使用<2>. 
* コマンドラインの例:: 

statistics --- 数学的統計関数

* 平均及び中心位置の測度:: 
* 分散の測度:: 
* 2入力間の関係の統計:: 
* 関数の詳細:: 
* 例外: 例外<5>. 
* NormalDist オブジェクト:: 
* 例とレシピ: 例とレシピ<2>. 

例とレシピ

* Classic probability problems:: 
* Monte Carlo inputs for simulations:: 
* Approximating binomial distributions:: 
* Naive bayesian classifier:: 

関数型プログラミング用モジュール

* itertools: itertools --- 効率的なループ用のイテレータ生成関数群. 効率的なループ用のイテレータ生成関数群
* functools: functools --- 高階関数と呼び出し可能オブジェクトの操作. 高階関数と呼び出し可能オブジェクトの操作
* operator: operator --- 関数形式の標準演算子. 関数形式の標準演算子

itertools --- 効率的なループ用のイテレータ生成関数群

* Itertool関数:: 
* Itertools レシピ:: 

functools --- 高階関数と呼び出し可能オブジェクトの操作

* partial オブジェクト:: 

operator --- 関数形式の標準演算子

* 演算子から関数への対応表:: 
* インプレース (in-place) 演算子: インプレース in-place 演算子. 

ファイルとディレクトリへのアクセス

* pathlib: pathlib --- オブジェクト指向のファイルシステムパス. オブジェクト指向のファイルシステムパス
* os.path: os path --- 一般的なパス名操作. 一般的なパス名操作
* stat: stat --- stat の結果を解釈する. stat() の結果を解釈する
* filecmp: filecmp --- ファイルとディレクトリの比較. ファイルとディレクトリの比較
* tempfile: tempfile --- 一時ファイルやディレクトリの作成. 一時ファイルやディレクトリの作成
* glob: glob --- Unix 形式のパス名のパターン展開. Unix 形式のパス名のパターン展開
* fnmatch: fnmatch --- Unix のファイル名パターンマッチ. Unix のファイル名パターンマッチ
* linecache: linecache --- テキストラインへのランダムアクセス. テキストラインへのランダムアクセス
* shutil: shutil --- 高水準のファイル操作. 高水準のファイル操作

pathlib --- オブジェクト指向のファイルシステムパス

* 基本的な使い方: 基本的な使い方<2>. 
* 例外: 例外<6>. 
* 純粋パス:: 
* 具象パス:: 
* Pattern language:: 
* glob モジュールとの比較:: 
* os と os.path モジュールの比較: os と os path モジュールの比較. 
* プロトコル:: 

純粋パス

* 全般的な性質:: 
* 演算子:: 
* 個別の構成要素へのアクセス:: 
* メソッドとプロパティ:: 

具象パス

* URIのパースと生成:: 
* パスの展開と解決:: 
* ファイルの種類とステータスを問い合わせる:: 
* ファイルを読み書きする: ファイルを読み書きする<2>. 
* ディレクトリを読む:: 
* ファイルとディレクトリの作成:: 
* Copying@comma{} moving and deleting: Copying moving and deleting. 
* パーミッションと所有者:: 

os と os.path モジュールの比較

* 対応するツール:: 

filecmp --- ファイルとディレクトリの比較

* dircmp クラス:: 

tempfile --- 一時ファイルやディレクトリの作成

* 使用例: 使用例<8>. 
* 非推奨の関数と変数:: 

glob --- Unix 形式のパス名のパターン展開

* 使用例: 使用例<9>. 

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 モジュールとの関係:: 
* データストリームの形式:: 
* モジュールインターフェース:: 
* pickle 化、非 pickle 化できるもの:: 
* クラスインスタンスの pickle 化:: 
* 型、関数、その他のオブジェクトに対するリダクションのカスタマイズ:: 
* アウトオブバウンドバッファ:: 
* グローバル変数を制限する:: 
* 性能: 性能<2>. 
* 使用例: 使用例<11>. 
* コマンドライン・インターフェース:: 

他の Python モジュールとの関係

* marshal との比較:: 
* json との比較:: 

クラスインスタンスの pickle 化

* 外部オブジェクトの永続化:: 
* ディスパッチテーブル:: 
* 状態を持つオブジェクトの扱い:: 

アウトオブバウンドバッファ

* 生産者 API:: 
* 消費者 API:: 
* 使用例: 使用例<10>. 

copyreg --- pickle サポート関数を登録する

* 使用例: 使用例<12>. 

shelve --- Python オブジェクトの永続化

* 制限事項:: 
* 使用例: 使用例<13>. 

dbm --- Unix "データベース" へのインターフェース

* dbm.sqlite3: dbm sqlite3 --- SQLite backend for dbm. SQLite backend for dbm
* dbm.gnu: dbm gnu --- GNU database manager. GNU database manager
* dbm.ndbm: dbm ndbm --- New Database Manager. New Database Manager
* dbm.dumb: dbm dumb --- Portable DBM implementation. Portable DBM implementation

sqlite3 --- SQLite データベース用の DB-API 2.0 インターフェース

* チュートリアル:: 
* リファレンス:: 
* ハウツー・ガイド:: 
* 説明:: 

リファレンス

* モジュール関数:: 
* モジュール定数:: 
* Connection オブジェクト:: 
* Cursor オブジェクト:: 
* Row オブジェクト:: 
* Blob オブジェクト:: 
* PrepareProtocol オブジェクト:: 
* 例外: 例外<7>. 
* SQLite と Python の型:: 
* デフォルトの適合関数(adapters)とデフォルトの変換関数(converters)(非推奨): デフォルトの適合関数 adapters とデフォルトの変換関数 converters 非推奨. 
* コマンドライン・インターフェース: コマンドライン・インターフェース<2>. 

ハウツー・ガイド

* プレースホルダを使用して SQL クエリに値を結び付ける方法:: 
* カスタム Python 型を SQLite 値に適合させる方法:: 
* SQLite 値をカスタム Python 型に変換する方法:: 
* 適合関数と変換関数のレシピ集:: 
* 接続(connection)ショートカット・メソッドの使い方: 接続 connection ショートカット・メソッドの使い方. 
* 接続(connection)コンテキストマネージャの使い方: 接続 connection コンテキストマネージャの使い方. 
* SQLite URI の操作方法:: 
* 行工場(row factories)の作成方法と使用方法: 行工場 row factories の作成方法と使用方法. 
* How to handle non-UTF-8 text encodings:: 

カスタム Python 型を SQLite 値に適合させる方法

* 適合可能オブジェクトの書き方:: 
* 適合用呼び出し可能オブジェクト(adapter callables)の登録方法: 適合用呼び出し可能オブジェクト adapter callables の登録方法. 

説明

* トランザクション制御:: 

トランザクション制御

* autocommit 属性に依るトランザクション制御:: 
* isolation_level 属性に依るトランザクション制御:: 

データ圧縮とアーカイブ

* compression パッケージ:: 
* compression.zstd: compression zstd --- Compression compatible with the Zstandard format. Compression compatible with the Zstandard format
* zlib: zlib --- gzip 互換の圧縮. gzip 互換の圧縮
* gzip: gzip --- gzip ファイルのサポート. gzip ファイルのサポート
* bz2: bz2 --- bzip2 圧縮のサポート. bzip2 圧縮のサポート
* lzma: lzma --- LZMA アルゴリズムを使用した圧縮. LZMA アルゴリズムを使用した圧縮
* zipfile: zipfile --- ZIP アーカイブの処理. ZIP アーカイブの処理
* tarfile: tarfile --- tar アーカイブファイルの読み書き. tar アーカイブファイルの読み書き

compression.zstd --- Compression compatible with the Zstandard format

* 例外: 例外<8>. 
* 圧縮ファイルへの読み書き:: 
* メモリ上での圧縮と展開:: 
* Zstandard dictionaries:: 
* Advanced parameter control:: 
* その他: その他<3>. 
* 使用例: 使用例<14>. 

gzip --- gzip ファイルのサポート

* 使い方の例:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<3>. 

コマンドライン・インターフェース

* コマンドラインオプション:: 

bz2 --- bzip2 圧縮のサポート

* ファイルの圧縮/解凍:: 
* 逐次圧縮および展開:: 
* 一括圧縮/解凍:: 
* 使い方の例: 使い方の例<2>. 

lzma --- LZMA アルゴリズムを使用した圧縮

* 圧縮ファイルへの読み書き: 圧縮ファイルへの読み書き<2>. 
* メモリ上での圧縮と展開: メモリ上での圧縮と展開<2>. 
* その他: その他<4>. 
* カスタムフィルタチェインの指定:: 
* 使用例: 使用例<15>. 

zipfile --- ZIP アーカイブの処理

* ZipFile objects:: 
* Path objects:: 
* PyZipFile objects:: 
* ZipInfo objects:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<4>. 
* Decompression pitfalls:: 

コマンドライン・インターフェース

* コマンドラインオプション: コマンドラインオプション<2>. 

Decompression pitfalls

* From file itself:: 
* File system limitations:: 
* Resources limitations:: 
* Interruption:: 
* Default behaviors of extraction:: 

tarfile --- tar アーカイブファイルの読み書き

* TarFile オブジェクト:: 
* TarInfo オブジェクト:: 
* Extraction filters:: 
* コマンドラインインターフェイス:: 
* 使用例: 使用例<16>. 
* サポートしている tar フォーマット:: 
* Unicode に関する問題:: 

Extraction filters

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

コマンドラインインターフェイス

* コマンドラインオプション: コマンドラインオプション<3>. 

使用例

* Reading examples:: 
* Writing examples:: 

ファイルフォーマット

* csv: csv --- CSV ファイルの読み書き. CSV ファイルの読み書き
* configparser: configparser --- 設定ファイルのパーサー. 設定ファイルのパーサー
* tomllib: tomllib --- TOML ファイルの解析. TOML ファイルの解析
* netrc: netrc --- netrc ファイルの処理. netrc ファイルの処理
* plistlib: plistlib --- Apple plist ファイルを生成・解析する. Apple .plist ファイルを生成・解析する

csv --- CSV ファイルの読み書き

* モジュールコンテンツ: モジュールコンテンツ<3>. 
* Dialect クラスと書式化パラメータ:: 
* reader オブジェクト:: 
* writer オブジェクト:: 
* 使用例: 使用例<17>. 

configparser --- 設定ファイルのパーサー

* クイックスタート:: 
* サポートされるデータ型:: 
* 代替値:: 
* サポートするINI ファイルの構造:: 
* Unnamed Sections:: 
* 値の補間:: 
* マップ型プロトコルアクセス:: 
* パーサーの振る舞いをカスタマイズする:: 
* レガシーな API の例:: 
* ConfigParser オブジェクト:: 
* RawConfigParser オブジェクト:: 
* 例外: 例外<9>. 

tomllib --- TOML ファイルの解析

* 使用例: 使用例<18>. 
* 変換表:: 

netrc --- netrc ファイルの処理

* netrc オブジェクト:: 

plistlib --- Apple .plist ファイルを生成・解析する

* 使用例: 使用例<19>. 

暗号関連のサービス

* hashlib: hashlib --- セキュアハッシュとメッセージダイジェスト. セキュアハッシュとメッセージダイジェスト
* hmac: hmac --- メッセージ認証のための鍵付きハッシュ化. メッセージ認証のための鍵付きハッシュ化
* secrets: secrets --- 機密を扱うために安全な乱数を生成する. 機密を扱うために安全な乱数を生成する

hashlib --- セキュアハッシュとメッセージダイジェスト

* ハッシュアルゴリズム:: 
* 使用法:: 
* コンストラクタ:: 
* 属性:: 
* Hash Objects:: 
* SHAKE 可変長ダイジェスト:: 
* ファイルのハッシュ化:: 
* 鍵導出:: 
* BLAKE2:: 

BLAKE2

* ハッシュオブジェクトの作成:: 
* 定数: 定数<5>. 
* 使用例: 使用例<20>. 
* クレジット;: クレジット. 

使用例

* 簡単なハッシュ化:: 
* Using different digest sizes:: 
* Keyed hashing:: 
* Randomized hashing:: 
* Personalization:: 
* ツリーモード:: 

secrets --- 機密を扱うために安全な乱数を生成する

* 乱数:: 
* トークンの生成:: 
* その他の関数:: 
* レシピとベストプラクティス:: 

トークンの生成

* トークンは何バイト使うべきか？:: 

汎用オペレーティングシステムサービス

* os: os --- 雑多なオペレーティングシステムインターフェース. 雑多なオペレーティングシステムインターフェース
* io: io --- ストリームを扱うコアツール. ストリームを扱うコアツール
* time: time --- 時刻データへのアクセスと変換. 時刻データへのアクセスと変換
* logging: logging --- Python 用のログ記録手段. Python 用のログ記録手段
* logging.config: logging config --- ログ記録の環境設定. ログ記録の環境設定
* logging.handlers: logging handlers --- ログ記録ハンドラー. ログ記録ハンドラー
* platform: platform --- 実行中プラットフォームの固有情報を参照する. 実行中プラットフォームの固有情報を参照する
* errno: errno --- 標準の errno システムシンボル. 標準の errno システムシンボル
* ctypes: ctypes --- Python 用の外部関数ライブラリ. Python 用の外部関数ライブラリ

os --- 雑多なオペレーティングシステムインターフェース

* ファイル名、コマンドライン引数、および環境変数:: 
* Python UTF-8 Mode:: 
* プロセスのパラメーター:: 
* ファイルオブジェクトの生成:: 
* ファイル記述子の操作:: 
* ファイルとディレクトリ:: 
* プロセス管理:: 
* スケジューラーへのインターフェイス:: 
* 雑多なシステム情報:: 
* 乱数: 乱数<2>. 

ファイル記述子の操作

* ターミナルのサイズの問い合わせ:: 
* ファイル記述子の継承:: 

ファイルとディレクトリ

* Timer File Descriptors:: 
* Linux 拡張属性:: 

io --- ストリームを扱うコアツール

* 概要: 概要<2>. 
* Text Encoding:: 
* 高水準のモジュールインターフェイス:: 
* クラス階層:: 
* Static Typing:: 
* 性能: 性能<3>. 

概要

* テキスト I/O:: 
* バイナリ I/O:: 
* Raw I/O:: 

Text Encoding

* Opt-in EncodingWarning:: 

クラス階層

* I/O 基底クラス:: 
* 生ファイルI/O:: 
* バッファ付きストリーム:: 
* テキスト I/O: テキスト I/O<2>. 

性能

* バイナリ I/O: バイナリ I/O<2>. 
* テキスト I/O: テキスト I/O<3>. 
* マルチスレッディング: マルチスレッディング<3>. 
* リエントラント性:: 

time --- 時刻データへのアクセスと変換

* 関数: 関数<5>. 
* Clock ID Constants:: 
* Timezone Constants:: 

logging --- Python 用のログ記録手段

* ロガーオブジェクト:: 
* ロギングレベル:: 
* ハンドラオブジェクト:: 
* フォーマッタオブジェクト:: 
* フィルタオブジェクト:: 
* LogRecord オブジェクト:: 
* LogRecord 属性:: 
* LoggerAdapter オブジェクト:: 
* スレッドセーフ性:: 
* モジュールレベルの関数:: 
* モジュールレベル属性:: 
* warnings モジュールとの統合:: 

logging.config --- ログ記録の環境設定

* 環境設定のための関数:: 
* セキュリティで考慮すべき点:: 
* 環境設定辞書スキーマ:: 
* 環境設定ファイルの書式:: 

環境設定辞書スキーマ

* 辞書スキーマの詳細:: 
* 増分設定:: 
* オブジェクトの接続:: 
* ユーザ定義オブジェクト:: 
* ハンドラの設定順序:: 
* 外部オブジェクトへのアクセス:: 
* 内部オブジェクトへのアクセス:: 
* インポート解決とカスタムインポーター:: 
* Configuring QueueHandler and QueueListener:: 

logging.handlers --- ログ記録ハンドラー

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

platform ---  実行中プラットフォームの固有情報を参照する

* Cross platform:: 
* Java platform:: 
* Windows platform:: 
* macOS platform:: 
* iOS platform:: 
* Unix platforms:: 
* Linux platforms:: 
* Android platform:: 
* コマンドラインでの使用: コマンドラインでの使用<3>. 

ctypes --- Python 用の外部関数ライブラリ

* ctypes チュートリアル:: 
* ctypesリファレンス:: 

ctypes チュートリアル

* 動的リンクライブラリをロードする:: 
* ロードしたdllから関数にアクセスする:: 
* 関数を呼び出す:: 
* 基本データ型:: 
* 続・関数を呼び出す:: 
* Calling variadic functions:: 
* 自作のデータ型とともに関数を呼び出す:: 
* 要求される引数の型を指定する (関数プロトタイプ): 要求される引数の型を指定する 関数プロトタイプ. 
* 戻り値の型:: 
* ポインタを渡す(または、パラメータの参照渡し): ポインタを渡す または、パラメータの参照渡し. 
* 構造体と共用体:: 
* Structure/union layout@comma{} alignment and byte order: Structure/union layout alignment and byte order. 
* 構造体と共用体におけるビットフィールド:: 
* 配列: 配列<2>. 
* ポインタ:: 
* Thread safety without the GIL:: 
* 型変換:: 
* 不完全型:: 
* コールバック関数:: 
* dllからエクスポートされた値へアクセスする:: 
* びっくり仰天:: 
* 可変サイズのデータ型:: 

ctypesリファレンス

* 共有ライブラリを見つける:: 
* Listing loaded shared libraries:: 
* 共有ライブラリをロードする:: 
* 外部関数:: 
* 関数プロトタイプ:: 
* ユーティリティー関数:: 
* データ型: データ型<3>. 
* 基本データ型: 基本データ型<2>. 
* 構造化データ型:: 
* 配列とポインタ:: 
* 例外: 例外<10>. 

コマンドラインインターフェースライブラリ

* argparse: argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー. コマンドラインオプションや引数、サブコマンド向けのパーサー
* optparse: optparse --- Parser for command line options. Parser for command line options
* getpass: getpass --- 可搬性のあるパスワード入力機構. 可搬性のあるパスワード入力機構
* fileinput: fileinput --- 複数の入力ストリームをまたいだ行を反復する. 複数の入力ストリームをまたいだ行を反復する
* curses: curses --- 文字セル表示のターミナル処理. 文字セル表示のターミナル処理
* curses.textpad: curses textpad --- Text input widget for curses programs. Text input widget for curses programs
* curses.ascii: curses ascii --- ASCII 文字のユーティリティー. ASCII 文字のユーティリティー
* curses.panel: curses panel --- curses のためのパネルスタック拡張. curses のためのパネルスタック拡張
* cmd: cmd --- 行指向のコマンドインタープリターのサポート. 行指向のコマンドインタープリターのサポート

argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー

* ArgumentParser オブジェクト:: 
* add_argument() メソッド: add_argument メソッド. 
* parse_args() メソッド: parse_args メソッド. 
* その他のユーティリティ:: 
* 例外: 例外<11>. 

ArgumentParser オブジェクト

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

add_argument() メソッド

* name または flags:: 
* action:: 
* nargs:: 
* const:: 
* default:: 
* type:: 
* choices:: 
* required:: 
* help:: 
* metavar:: 
* dest:: 
* deprecated:: 
* Action クラス:: 

parse_args() メソッド

* オプション値の文法:: 
* 不正な引数:: 
* - を含む引数:: 
* 引数の短縮形 (先頭文字でのマッチング): 引数の短縮形 先頭文字でのマッチング. 
* sys.argv 以外: sys argv 以外. 
* Namespace オブジェクト:: 

その他のユーティリティ

* Subcommands:: 
* FileType オブジェクト:: 
* 引数グループ:: 
* 相互排他:: 
* パーサーのデフォルト値:: 
* ヘルプの表示:: 
* 部分解析:: 
* ファイル解析のカスタマイズ:: 
* 終了メソッド:: 
* 混在した引数の解析:: 
* Registering custom types or actions:: 

例外

* Argparse チュートリアル:: 
* Migrating optparse code to argparse:: 

Argparse チュートリアル

* コンセプト:: 
* 基礎:: 
* 位置引数の入門:: 
* Optional引数の導入:: 
* 位置引数とOptional引数の併用:: 
* もうちょっとだけ学ぶ:: 
* argparse の出力を翻訳するには:: 
* Custom type converters:: 
* 結び:: 

Optional引数の導入

* 短いオプション:: 

もうちょっとだけ学ぶ

* 多義性のある引数の指定:: 
* 競合するオプション:: 

optparse --- Parser for command line options

* Choosing an argument parsing library:: 
* はじめに: はじめに<7>. 
* 背景:: 
* チュートリアル: チュートリアル<2>. 
* リファレンスガイド:: 
* オプション処理コールバック:: 
* Extending optparse:: 
* 例外: 例外<12>. 

背景

* 用語集:: 
* オプションとは何か:: 
* 位置引数とは何か:: 

チュートリアル

* オプション・アクションを理解する:: 
* store アクション:: 
* ブール値 (フラグ) オプションの処理: ブール値 フラグ オプションの処理. 
* その他のアクション:: 
* デフォルト値:: 
* ヘルプの生成:: 
* バージョン番号の出力:: 
* How optparse handles errors:: 
* 全てをつなぎ合わせる:: 

ヘルプの生成

* オプションをグループ化する:: 

リファレンスガイド

* parserを作る:: 
* パーザへのオプション追加:: 
* オプションの定義:: 
* オプション属性:: 
* 標準的なオプション・アクション:: 
* 標準のオプション型:: 
* 引数を解析する:: 
* オプション解析器への問い合わせと操作:: 
* オプション間の衝突:: 
* クリーンアップ:: 
* その他のメソッド:: 

オプション処理コールバック

* callbackオプションの定義:: 
* コールバック関数はどのように呼び出されるか:: 
* コールバック中で例外を送出する:: 
* コールバックの例 1; ありふれたコールバック: コールバックの例 1 ありふれたコールバック. 
* コールバックの例 2; オプションの順番をチェックする: コールバックの例 2 オプションの順番をチェックする. 
* コールバックの例 3; オプションの順番をチェックする (汎用的): コールバックの例 3 オプションの順番をチェックする 汎用的. 
* コールバックの例 4; 任意の条件をチェックする: コールバックの例 4 任意の条件をチェックする. 
* コールバックの例5; 固定引数: コールバックの例5 固定引数. 
* コールバックの例6; 可変個の引数: コールバックの例6 可変個の引数. 

Extending optparse

* 新しい型の追加:: 
* 新しいアクションの追加:: 

curses --- 文字セル表示のターミナル処理

* 関数: 関数<6>. 
* Window オブジェクト:: 
* 定数: 定数<6>. 

curses.textpad --- Text input widget for curses programs

* Textbox オブジェクト:: 

curses.panel --- curses のためのパネルスタック拡張

* 関数: 関数<7>. 
* Panel オブジェクト:: 

cmd --- 行指向のコマンドインタープリターのサポート

* Cmdオブジェクト:: 
* Cmd の例:: 

並行実行

* threading: threading --- スレッドベースの並列処理. スレッドベースの並列処理
* multiprocessing: multiprocessing --- プロセスベースの並列処理. プロセスベースの並列処理
* multiprocessing.shared_memory: multiprocessing shared_memory --- プロセス間で直接アクセス可能な共有メモリ. プロセス間で直接アクセス可能な共有メモリ
* concurrent パッケージ:: 
* concurrent.futures: concurrent futures --- 並列タスク実行. 並列タスク実行
* concurrent.interpreters: concurrent interpreters --- Multiple interpreters in the same process. Multiple interpreters in the same process
* subprocess: subprocess --- サブプロセス管理. サブプロセス管理
* sched: sched --- イベントスケジューラー. イベントスケジューラー
* queue: queue --- 同期キュークラス. 同期キュークラス
* contextvars: contextvars --- コンテキスト変数. コンテキスト変数
* _thread: _thread --- 低水準なスレッド API. 低水準なスレッド API

threading --- スレッドベースの並列処理

* はじめに: はじめに<8>. 
* GIL and performance considerations:: 
* リファレンス: リファレンス<2>. 
* with 文でのロック・条件変数・セマフォの使い方:: 

リファレンス

* Thread-local data:: 
* Thread objects:: 
* Lock objects:: 
* RLock objects:: 
* Condition objects:: 
* Semaphore objects:: 
* Semaphore example:: 
* Event objects:: 
* Timer objects:: 
* Barrier objects:: 

multiprocessing --- プロセスベースの並列処理

* はじめに: はじめに<9>. 
* リファレンス: リファレンス<3>. 
* プログラミングガイドライン:: 
* 使用例: 使用例<21>. 

はじめに

* Process クラス:: 
* コンテキストと開始方式:: 
* プロセス間でのオブジェクト交換:: 
* プロセス間の同期:: 
* プロセス間での状態の共有:: 
* ワーカープロセスのプールを使用:: 

リファレンス

* Global start method:: 
* Process クラスと例外:: 
* パイプ (Pipe) とキュー (Queue): パイプ Pipe とキュー Queue. 
* その他: その他<5>. 
* Connection オブジェクト: Connection オブジェクト<2>. 
* 同期プリミティブ:: 
* 共有 ctypes オブジェクト:: 
* マネージャー:: 
* Proxy オブジェクト:: 
* プロセスプール:: 
* リスナーとクライアント:: 
* 認証キー:: 
* ログ記録: ログ記録<2>. 
* The multiprocessing.dummy module: The multiprocessing dummy module. 

共有 ctypes オブジェクト

* The multiprocessing.sharedctypes module: The multiprocessing sharedctypes module. 

マネージャー

* カスタマイズされたマネージャー:: 
* リモートマネージャーを使用する:: 

Proxy オブジェクト

* クリーンアップ: クリーンアップ<2>. 

リスナーとクライアント

* アドレスフォーマット:: 

プログラミングガイドライン

* すべての開始方式について:: 
* 開始方式が spawn および forkserver の場合:: 

concurrent.futures --- 並列タスク実行

* Executor オブジェクト:: 
* ThreadPoolExecutor:: 
* InterpreterPoolExecutor:: 
* ProcessPoolExecutor:: 
* Future オブジェクト:: 
* モジュール関数: モジュール関数<2>. 
* 例外クラス:: 

ThreadPoolExecutor

* ThreadPoolExecutor の例:: 

ProcessPoolExecutor

* ProcessPoolExecutor の例:: 

concurrent.interpreters --- Multiple interpreters in the same process

* Key details:: 
* はじめに: はじめに<10>. 
* リファレンス: リファレンス<4>. 
* 基本的な使い方: 基本的な使い方<3>. 

はじめに

* Multiple Interpreters and Isolation:: 
* Running in an Interpreter:: 
* Concurrency and Parallelism:: 
* Communication Between Interpreters:: 
* "Sharing" Objects:: 

リファレンス

* Interpreter objects:: 
* 例外: 例外<13>. 
* Communicating Between Interpreters:: 

subprocess --- サブプロセス管理

* Using the subprocess Module:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<2>. 
* Popen オブジェクト:: 
* Windows Popen ヘルパー:: 
* 古い高水準 API:: 
* Replacing Older Functions with the subprocess Module:: 
* レガシーなシェル呼び出し関数:: 
* 注釈: 注釈<2>. 

Using the subprocess Module

* よく使われる引数:: 
* Popen コンストラクター:: 
* 例外: 例外<14>. 

Windows Popen ヘルパー

* Windows Constants:: 

Replacing Older Functions with the subprocess Module

* Replacing /bin/sh shell command substitution:: 
* シェルのパイプラインを置き換える:: 
* os.system() を置き換える: os system を置き換える. 
* os.spawn 関数群を置き換える: os spawn 関数群を置き換える. 
* Replacing os.popen(): Replacing os popen. 

注釈

* Timeout Behavior:: 
* Windows における引数シーケンスから文字列への変換:: 
* Disable use of posix_spawn(): Disable use of posix_spawn. 

sched --- イベントスケジューラー

* スケジューラオブジェクト:: 

queue --- 同期キュークラス

* キューオブジェクト:: 
* SimpleQueue オブジェクト:: 

キューオブジェクト

* Waiting for task completion:: 
* Terminating queues:: 

contextvars --- コンテキスト変数

* コンテキスト変数:: 
* マニュアルでのコンテキスト管理:: 
* asyncio サポート:: 

ネットワーク通信とプロセス間通信

* asyncio: asyncio --- 非同期 I/O. 非同期 I/O
* socket: socket --- 低水準ネットワークインターフェース. 低水準ネットワークインターフェース
* ssl: ssl --- ソケットオブジェクト用の TLS/SSL ラッパー. ソケットオブジェクト用の TLS/SSL ラッパー
* select: select --- I/O 完了の待機. I/O 完了の待機
* selectors: selectors --- 高水準の I/O 多重化. 高水準の I/O 多重化
* signal: signal --- 非同期イベントにハンドラーを設定する. 非同期イベントにハンドラーを設定する
* mmap: mmap --- メモリマップファイルのサポート. メモリマップファイルのサポート

asyncio --- 非同期 I/O

* Runners:: 
* コルーチンと Task:: 
* ストリーム:: 
* 同期プリミティブ: 同期プリミティブ<2>. 
* サブプロセス:: 
* キュー:: 
* 例外: 例外<16>. 
* Call Graph Introspection:: 
* イベントループ:: 
* Future:: 
* トランスポートとプロトコル:: 
* ポリシー:: 
* プラットフォームでのサポート:: 
* Extending:: 
* 高水準の API インデックス:: 
* 低水準の API インデックス:: 
* asyncio での開発:: 

Runners

* 非同期プログラムの実行:: 
* Runner context manager:: 
* Handling Keyboard Interruption:: 

コルーチンと Task

* コルーチン: コルーチン<3>. 
* Awaitable:: 
* Task の作成:: 
* タスクのキャンセル:: 
* Task Groups:: 
* スリープ:: 
* 並行な Task 実行:: 
* Eager Task Factory:: 
* キャンセルからの保護:: 
* タイムアウト:: 
* 要素の終了待機:: 
* スレッド内での実行:: 
* 外部スレッドからのスケジュール:: 
* イントロスペクション:: 
* Task オブジェクト:: 

Task Groups

* Terminating a Task Group:: 

ストリーム

* StreamReader:: 
* StreamWriter:: 
* 使用例: 使用例<22>. 

使用例

* ストリームを使った TCP Echo クライアント:: 
* ストリームを使った TCP Echo サーバー:: 
* HTTP ヘッダーの取得:: 
* ストリームを使ってデータを待つオープンソケットの登録:: 

同期プリミティブ

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

サブプロセス

* サブプロセスの生成:: 
* 定数: 定数<7>. 
* サブプロセスとやりとりする:: 

サブプロセスとやりとりする

* サブプロセスとスレッド:: 
* 使用例: 使用例<23>. 

キュー

* Queue:: 
* 優先度付きのキュー:: 
* LIFO キュー:: 
* 例外: 例外<15>. 
* 使用例: 使用例<24>. 

Call Graph Introspection

* Low level utility functions:: 

イベントループ

* イベントループのメソッド:: 
* コールバックのハンドル:: 
* Serverオブジェクト:: 
* イベントループの実装:: 
* 使用例: 使用例<25>. 

イベントループのメソッド

* ループの開始と停止:: 
* コールバックのスケジューリング:: 
* 遅延コールバックのスケジューリング:: 
* フューチャーとタスクの生成:: 
* ネットワーク接続の確立:: 
* ネットワークサーバの生成:: 
* ファイルの転送:: 
* TLS へのアップグレード:: 
* ファイル記述子の監視:: 
* ソケットオブジェクトと直接やりとりする:: 
* DNS:: 
* パイプとやりとりする:: 
* Unix シグナル:: 
* スレッドまたはプロセスプールでコードを実行する:: 
* エラーハンドリング API:: 
* デバッグモードの有効化:: 
* サブプロセスの実行:: 

使用例

* call_soon() を使った Hello World: call_soon を使った Hello World. 
* call_later() で現在の日時を表示する: call_later で現在の日時を表示する. 
* 読み込みイベント用ファイル記述子の監視:: 
* SIGINT および SIGTERM 用のシグナルハンドラーの設定:: 

Future

* Future の関数:: 
* Future オブジェクト: Future オブジェクト<2>. 

トランスポートとプロトコル

* トランスポート:: 
* プロトコル: プロトコル<2>. 
* 使用例: 使用例<26>. 

トランスポート

* トランスポートのクラス階層構造:: 
* 基底トランスポート:: 
* 読み出し専用のトランスポート:: 
* 書き込み専用のトランスポート:: 
* データグラムトランスポート:: 
* サブプロセス化されたトランスポート:: 

プロトコル

* 基底プロトコル:: 
* 基底プロトコル: 基底プロトコル<2>. 
* ストリーミングプロトコル:: 
* バッファリングされたストリーミングプロトコル:: 
* データグラムプロトコル:: 
* サブプロセスプロトコル:: 

使用例

* TCP エコーサーバー:: 
* TCP エコークライアント:: 
* UDP エコーサーバー:: 
* UDP エコークライアント:: 
* 既存のソケットへの接続:: 
* loop.subprocess_exec() と SubprocessProtocol: loop subprocess_exec と SubprocessProtocol. 

ポリシー

* ポリシーの取得と設定:: 
* ポリシーオブジェクト:: 
* ポリシーのカスタマイズ:: 

プラットフォームでのサポート

* 全てのプラットホーム:: 
* Windows: Windows<84>. 
* macOS: macOS<52>. 

Windows

* Windows におけるサブプロセスのサポート:: 

Extending

* Writing a Custom Event Loop:: 
* Future and Task private constructors:: 
* Task lifetime support:: 

高水準の API インデックス

* Task:: 
* キュー: キュー<2>. 
* サブプロセス: サブプロセス<2>. 
* ストリーム: ストリーム<2>. 
* 同期:: 
* 例外: 例外<17>. 

低水準の API インデックス

* イベントループの取得:: 
* イベントループのメソッド: イベントループのメソッド<2>. 
* トランスポート: トランスポート<2>. 
* プロトコル: プロトコル<3>. 
* イベントループのポリシー:: 

asyncio での開発

* デバッグモード:: 
* 並行処理とマルチスレッド処理:: 
* ブロッキングコードの実行:: 
* ログ記録: ログ記録<3>. 
* 待ち受け処理を伴わないコルーチンの検出:: 
* 回収されない例外の検出:: 

socket --- 低水準ネットワークインターフェース

* ソケットファミリー:: 
* モジュールの内容:: 
* socket オブジェクト:: 
* ソケットタイムアウトの注意事項:: 
* 使用例: 使用例<27>. 

モジュールの内容

* 例外: 例外<18>. 
* 定数: 定数<8>. 
* 関数: 関数<8>. 

関数

* ソケットの作成:: 
* その他の関数: その他の関数<2>. 

ソケットタイムアウトの注意事項

* タイムアウトと connect メソッド:: 
* タイムアウトと accept メソッド:: 

ssl --- ソケットオブジェクト用の TLS/SSL ラッパー

* 関数、定数、例外:: 
* SSL ソケット:: 
* SSL コンテキスト:: 
* 証明書:: 
* 使用例: 使用例<28>. 
* ノンブロッキングソケットについての注意事項:: 
* メモリ BIO サポート: メモリ BIO サポート<2>. 
* SSL セッション:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<3>. 
* TLS 1.3: TLS 1 3. 

関数、定数、例外

* ソケットの作成: ソケットの作成<2>. 
* コンテキストの作成:: 
* 例外: 例外<19>. 
* 乱数生成:: 
* 証明書の取り扱い:: 
* 定数: 定数<9>. 

証明書

* 証明書チェイン:: 
* CA 証明書:: 
* 秘密鍵と証明書の組み合わせ:: 
* 自己署名証明書:: 

使用例

* SSLサポートをテストする:: 
* クライアントサイドの処理:: 
* サーバサイドの処理:: 

セキュリティで考慮すべき点

* 最善のデフォルト値:: 
* 手動での設定:: 
* マルチプロセス化:: 

手動での設定

* 証明書の検証:: 
* プロトコルのバージョン:: 
* 暗号の選択:: 

select --- I/O 完了の待機

* /dev/poll ポーリングオブジェクト:: 
* エッジおよびレベルトリガポーリング (epoll) オブジェクト: エッジおよびレベルトリガポーリング epoll オブジェクト. 
* ポーリングオブジェクト:: 
* kqueue オブジェクト:: 
* kevent オブジェクト:: 

selectors --- 高水準の I/O 多重化

* はじめに: はじめに<11>. 
* クラス: クラス<4>. 
* 使用例: 使用例<29>. 

signal --- 非同期イベントにハンドラーを設定する

* 一般的なルール:: 
* モジュールの内容: モジュールの内容<2>. 
* 使用例: 使用例<30>. 
* Note on SIGPIPE:: 
* Note on Signal Handlers and Exceptions:: 

一般的なルール

* Python のシグナルハンドラの実行:: 
* シグナルとスレッド:: 

mmap --- メモリマップファイルのサポート

* MADV_* 定数:: 
* MAP_* 定数:: 

インターネット上のデータの操作

* email: email --- 電子メールと MIME 処理のためのパッケージ. 電子メールと MIME 処理のためのパッケージ
* json: json --- JSON エンコーダーとデコーダー. JSON エンコーダーとデコーダー
* mailbox: mailbox --- 様々な形式のメールボックスを操作する. 様々な形式のメールボックスを操作する
* mimetypes: mimetypes --- ファイル名を MIME タイプへマップする. ファイル名を MIME タイプへマップする
* base64: base64 --- Base16 Base32 Base64 Base85 データのエンコード. Base16, Base32, Base64, Base85 データのエンコード
* binascii: binascii --- バイナリ と ASCII 間の変換. バイナリ と ASCII 間の変換
* quopri: quopri --- MIME quoted-printable データのエンコードとデコード. MIME quoted-printable データのエンコードとデコード

email --- 電子メールと MIME 処理のためのパッケージ

* email.message; Representing an email message: email message Representing an email message. 
* email.parser; Parsing email messages: email parser Parsing email messages. 
* email.generator; Generating MIME documents: email generator Generating MIME documents. 
* email.policy; Policy Objects: email policy Policy Objects. 
* email.errors; Exception and Defect classes: email errors Exception and Defect classes. 
* email.headerregistry; Custom Header Objects: email headerregistry Custom Header Objects. 
* email.contentmanager; Managing MIME Content: email contentmanager Managing MIME Content. 
* email; 使用例: email 使用例. 
* email.message.Message; compat32 API を使用した電子メールメッセージの表現: email message Message compat32 API を使用した電子メールメッセージの表現. 
* email.mime; Creating email and MIME objects from scratch: email mime Creating email and MIME objects from scratch. 
* email.header; 国際化されたヘッダー: email header 国際化されたヘッダー. 
* email.charset; 文字集合の表現: email charset 文字集合の表現. 
* email.encoders; エンコーダー: email encoders エンコーダー. 
* email.utils; Miscellaneous utilities: email utils Miscellaneous utilities. 
* email.iterators; イテレータ: email iterators イテレータ. 

email.parser: Parsing email messages

* FeedParser API:: 
* Parser API:: 
* 追記事項:: 

email.contentmanager: Managing MIME Content

* Content Manager Instances:: 

json --- JSON エンコーダーとデコーダー

* 基本的な使い方: 基本的な使い方<4>. 
* エンコーダとデコーダ:: 
* 例外: 例外<20>. 
* 標準への準拠と互換性:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<5>. 

標準への準拠と互換性

* 文字エンコーディング:: 
* 無限および NaN の数値:: 
* オブジェクト中に重複した名前の扱い:: 
* トップレベルの非オブジェクト、非配列の値の扱い:: 
* 実装の制限:: 

コマンドライン・インターフェース

* コマンドラインオプション: コマンドラインオプション<4>. 

mailbox --- 様々な形式のメールボックスを操作する

* Mailbox オブジェクト:: 
* Message オブジェクト:: 
* 例外: 例外<21>. 
* 使用例: 使用例<31>. 

Mailbox オブジェクト

* Maildir オブジェクト:: 
* mbox オブジェクト:: 
* MH オブジェクト:: 
* Babyl オブジェクト:: 
* MMDF オブジェクト:: 

Message オブジェクト

* MaildirMessage オブジェクト:: 
* mboxMessage オブジェクト:: 
* MHMessage オブジェクト:: 
* BabylMessage オブジェクト:: 
* MMDFMessage オブジェクト:: 

mimetypes --- ファイル名を MIME タイプへマップする

* MimeTypes objects:: 
* コマンドラインでの使用: コマンドラインでの使用<4>. 
* コマンドラインの例: コマンドラインの例<2>. 

base64 --- Base16, Base32, Base64, Base85 データのエンコード

* RFC 4648 エンコーディング:: 
* Base85 エンコーディング:: 
* レガシーインターフェース:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<4>. 

構造化マークアップツール

* html: html --- HyperText Markup Language のサポート. HyperText Markup Language のサポート
* 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 メソッド:: 
* 使用例: 使用例<32>. 

XMLを扱うモジュール群

* XML security:: 

xml.etree.ElementTree --- ElementTree XML API

* チュートリアル: チュートリアル<3>. 
* XPath サポート:: 
* リファレンス: リファレンス<5>. 
* XInclude サポート:: 
* リファレンス: リファレンス<6>. 

チュートリアル

* XML 木構造と要素:: 
* XML の解析:: 
* 非ブロックパースのためのプル API:: 
* 関心ある要素の検索:: 
* XML ファイルの編集:: 
* XML 文書の構築:: 
* 名前空間のある XML の解析:: 

XPath サポート

* 使用例: 使用例<33>. 
* サポートされている XPath 構文:: 

リファレンス

* 関数: 関数<9>. 

XInclude サポート

* 使用例: 使用例<34>. 

リファレンス

* 関数: 関数<10>. 
* Element オブジェクト:: 
* ElementTree オブジェクト:: 
* QName オブジェクト:: 
* TreeBuilder オブジェクト:: 
* XMLParser オブジェクト:: 
* XMLPullParser オブジェクト:: 
* 例外: 例外<22>. 

xml.dom --- ドキュメントオブジェクトモデル API

* モジュールコンテンツ: モジュールコンテンツ<4>. 
* DOM 内のオブジェクト:: 
* 適合性:: 

DOM 内のオブジェクト

* DOMImplementation オブジェクト:: 
* Node オブジェクト:: 
* NodeList オブジェクト:: 
* DocumentType オブジェクト:: 
* Document オブジェクト:: 
* Element オブジェクト: Element オブジェクト<2>. 
* Attr オブジェクト:: 
* NamedNodeMap Objects:: 
* Comment オブジェクト:: 
* Text オブジェクトおよび CDATASection オブジェクト:: 
* ProcessingInstruction オブジェクト:: 
* 例外: 例外<23>. 

適合性

* 型の対応付け:: 
* アクセサメソッド:: 

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 オブジェクト:: 
* LexicalHandler Objects:: 

xml.sax.xmlreader --- XML パーサーのインターフェース

* XMLReader オブジェクト:: 
* IncrementalParser オブジェクト:: 
* Locator オブジェクト:: 
* InputSource オブジェクト:: 
* Attributes インターフェース:: 
* AttributesNS インターフェース:: 

xml.parsers.expat --- Expat を使用した高速な XML 解析

* XMLParser オブジェクト: XMLParser オブジェクト<2>. 
* ExpatError 例外:: 
* 使用例: 使用例<35>. 
* 内容モデルの記述:: 
* Expat エラー定数:: 

インターネットプロトコルとサポート

* webbrowser: webbrowser --- 便利なウェブブラウザコントローラー. 便利なウェブブラウザコントローラー
* wsgiref: wsgiref --- WSGI ユーティリティとリファレンス実装. WSGI ユーティリティとリファレンス実装
* urllib: urllib --- URL を扱うモジュール群. URL を扱うモジュール群
* urllib.request: urllib request --- URL を開くための大規模なライブラリ. URL を開くための大規模なライブラリ
* urllib.response: urllib response --- Response classes used by urllib. Response classes used by urllib
* urllib.parse: urllib parse --- URL を構成要素に解析する. URL を構成要素に解析する
* urllib.error: urllib error --- urllib request によって送出される例外クラス. urllib.request によって送出される例外クラス
* urllib.robotparser: urllib robotparser --- robots txt 用のパーサー. robots.txt 用のパーサー
* http: http --- HTTP モジュール群. HTTP モジュール群
* http.client: http client --- HTTP プロトコルクライアント. HTTP プロトコルクライアント
* ftplib: ftplib --- FTP プロトコルクライアント. FTP プロトコルクライアント
* poplib: poplib --- POP3 プロトコルクライアント. POP3 プロトコルクライアント
* imaplib: imaplib --- IMAP4 プロトコルクライアント. IMAP4 プロトコルクライアント
* smtplib: smtplib --- SMTP プロトコルクライアント. SMTP プロトコルクライアント
* uuid: uuid --- RFC 9562 に基づく UUID オブジェクト. RFC 9562 に基づく UUID オブジェクト
* socketserver: socketserver --- ネットワークサーバーのフレームワーク. ネットワークサーバーのフレームワーク
* http.server: http server --- HTTP サーバー. HTTP サーバー
* http.cookies: http cookies --- HTTP の状態管理. HTTP の状態管理
* http.cookiejar: http cookiejar --- HTTP クライアント用の Cookie 処理. 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 --- 便利なウェブブラウザコントローラー

* コマンドライン・インターフェース: コマンドライン・インターフェース<6>. 
* Browser controller objects:: 

wsgiref --- WSGI ユーティリティとリファレンス実装

* wsgiref.util: wsgiref util -- WSGI environment utilities. WSGI environment utilities
* wsgiref.headers: wsgiref headers -- WSGI response header tools. WSGI response header tools
* wsgiref.simple_server: wsgiref simple_server -- a simple WSGI HTTP server. a simple WSGI HTTP server
* wsgiref.validate: wsgiref validate --- WSGI conformance checker. WSGI conformance checker
* wsgiref.handlers: wsgiref handlers -- server/gateway base classes. server/gateway base classes
* wsgiref.types: wsgiref types -- WSGI types for static type checking. WSGI types for static type checking
* 使用例: 使用例<36>. 

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 オブジェクト:: 
* 使用例: 使用例<37>. 
* レガシーインターフェース: レガシーインターフェース<2>. 
* urllib.request Restrictions: urllib request Restrictions. 

urllib.parse --- URL を構成要素に解析する

* URL の解析:: 
* URL parsing security:: 
* ASCII エンコードバイト列の解析:: 
* 構造化された解析結果:: 
* URL のクオート:: 

http --- HTTP モジュール群

* HTTP ステータスコード:: 
* HTTP ステータスコードカテゴリ:: 
* HTTP メソッド:: 

http.client --- HTTP プロトコルクライアント

* HTTPConnection オブジェクト:: 
* HTTPResponse オブジェクト:: 
* 使用例: 使用例<38>. 
* HTTPMessage オブジェクト:: 

ftplib --- FTP プロトコルクライアント

* リファレンス: リファレンス<7>. 

リファレンス

* FTP オブジェクト:: 
* FTP_TLS オブジェクト:: 
* モジュール変数:: 

poplib --- POP3 プロトコルクライアント

* POP3 オブジェクト:: 
* POP3 の例:: 

imaplib --- IMAP4 プロトコルクライアント

* IMAP4 オブジェクト:: 
* IMAP4 の使用例:: 

smtplib --- SMTP プロトコルクライアント

* SMTP オブジェクト:: 
* SMTP 使用例:: 

uuid --- RFC 9562 に基づく UUID オブジェクト

* コマンドラインからの使用:: 
* 使用例: 使用例<39>. 
* Command-Line Example:: 

socketserver --- ネットワークサーバーのフレームワーク

* サーバ生成に関するノート:: 
* Serverオブジェクト: Serverオブジェクト<2>. 
* Request Handler Objects:: 
* 使用例: 使用例<40>. 

使用例

* socketserver.TCPServer の例: socketserver TCPServer の例. 
* socketserver.UDPServer の例: socketserver UDPServer の例. 
* 非同期処理の Mix-in:: 

http.server --- HTTP サーバー

* コマンドライン・インターフェース: コマンドライン・インターフェース<7>. 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<5>. 

http.cookies --- HTTP の状態管理

* Cookieオブジェクト:: 
* Morselオブジェクト:: 
* 使用例: 使用例<41>. 

http.cookiejar --- HTTP クライアント用の Cookie 処理

* CookieJar および FileCookieJar オブジェクト:: 
* FileCookieJar のサブクラスと web ブラウザとの連携:: 
* CookiePolicy オブジェクト:: 
* DefaultCookiePolicy オブジェクト:: 
* Cookieオブジェクト: Cookieオブジェクト<2>. 
* 使用例: 使用例<42>. 

xmlrpc.client --- XML-RPC クライアントアクセス

* ServerProxy オブジェクト:: 
* DateTime オブジェクト:: 
* Binary オブジェクト:: 
* Fault オブジェクト:: 
* ProtocolError オブジェクト:: 
* MultiCall オブジェクト:: 
* 補助関数:: 
* クライアントのサンプル:: 
* クライアントとサーバーの利用例:: 

xmlrpc.server --- 基本的な XML-RPC サーバー

* SimpleXMLRPCServer オブジェクト:: 
* CGIXMLRPCRequestHandler:: 
* XMLRPC サーバの文書化:: 
* DocXMLRPCServer オブジェクト:: 
* DocCGIXMLRPCRequestHandler:: 

SimpleXMLRPCServer オブジェクト

* SimpleXMLRPCServer の例:: 

ipaddress --- IPv4/IPv6 操作ライブラリ

* 便利なファクトリ関数:: 
* IP アドレス:: 
* IP ネットワーク定義:: 
* インターフェイスオブジェクト:: 
* その他のモジュールレベル関数:: 
* Custom Exceptions:: 

IP アドレス

* Address オブジェクト:: 
* 文字列と整数への変換:: 
* 演算子: 演算子<2>. 

演算子

* 比較演算子:: 
* 算術演算:: 

IP ネットワーク定義

* プリフィックス@comma{} ネットマスク、ホストマスク: プリフィックス ネットマスク、ホストマスク. 
* Network オブジェクト:: 
* 演算子: 演算子<3>. 

演算子

* 論理演算子:: 
* イテレーション:: 
* アドレスのコンテナとしてのネットワーク:: 

インターフェイスオブジェクト

* 演算子: 演算子<4>. 

演算子

* 論理演算子: 論理演算子<2>. 

マルチメディアサービス

* wave: wave --- WAV ファイルの読み書き. WAV ファイルの読み書き
* colorsys: colorsys --- 色体系間の変換. 色体系間の変換

wave --- WAV ファイルの読み書き

* Wave_read オブジェクト:: 
* Wave_write オブジェクト:: 

国際化

* gettext: gettext --- 多言語国際化サービス. 多言語国際化サービス
* locale: locale --- 国際化サービス. 国際化サービス

gettext --- 多言語国際化サービス

* GNU gettext API:: 
* クラス形式の API:: 
* プログラムやモジュールを国際化する:: 
* 謝辞: 謝辞<9>. 

クラス形式の API

* NullTranslations クラス:: 
* GNUTranslations クラス:: 
* Solaris メッセージカタログ機構のサポート:: 
* Catalog コンストラクタ:: 

プログラムやモジュールを国際化する

* モジュールを地域化する:: 
* アプリケーションを地域化する:: 
* 動作中 (on the fly) に言語を切り替える: 動作中 on the fly に言語を切り替える. 
* 翻訳処理の遅延解決:: 

locale --- 国際化サービス

* ロケールの背景、詳細、ヒント、助言および補足説明:: 
* Locale names:: 
* Python 拡張の作者と、Python を埋め込むようなプログラムに関して:: 
* メッセージカタログへのアクセス:: 

Graphical user interfaces with Tk

* 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 のテーマ付きウィジェット
* IDLE: IDLE --- Python のエディタとシェル<2>. Python のエディタとシェル
* turtle: turtle --- Turtle graphics. Turtle graphics

tkinter --- Tcl/Tk の Python インターフェース

* Architecture:: 
* Tkinter モジュール:: 
* Tkinter お助け手帳:: 
* Threading model:: 
* 簡単なリファレンス:: 
* ファイルハンドラ:: 

Tkinter お助け手帳

* A Hello World Program:: 
* Important Tk Concepts:: 
* Understanding How Tkinter Wraps Tcl/Tk:: 
* How do I...? What option does...?: How do I ? What option does ?. 
* Navigating the Tcl/Tk Reference Manual:: 

簡単なリファレンス

* オプションの設定:: 
* Packer:: 
* Packer のオプション:: 
* ウィジェット変数を関連付ける:: 
* ウィンドウマネージャ:: 
* Tk オプションデータ型:: 
* バインドとイベント:: 
* index パラメータ:: 
* 画像:: 

Tkinter ダイアログ

* tkinter.simpledialog: tkinter simpledialog --- Standard Tkinter input dialogs. Standard Tkinter input dialogs
* tkinter.filedialog: tkinter filedialog --- File selection dialogs. File selection dialogs
* tkinter.commondialog: tkinter commondialog --- Dialog window templates. Dialog window templates

tkinter.filedialog --- File selection dialogs

* ネイティブの読み込み/保存ダイアログ:: 

tkinter.ttk --- Tk のテーマ付きウィジェット

* Ttk を使う:: 
* Ttk ウィジェット:: 
* ウィジェット:: 
* コンボボックス:: 
* Spinbox:: 
* ノートブック:: 
* プログレスバー:: 
* セパレータ:: 
* サイズグリップ:: 
* ツリービュー:: 
* Ttk スタイル:: 

ウィジェット

* 標準オプション:: 
* スクロール可能ウィジェットのオプション:: 
* ラベルオプション:: 
* 互換性オプション:: 
* ウィジェットの状態:: 
* ttk.Widget: ttk Widget. 

コンボボックス

* オプション:: 
* 仮想イベント:: 
* ttk.Combobox: ttk Combobox. 

Spinbox

* オプション: オプション<2>. 
* 仮想イベント: 仮想イベント<2>. 
* ttk.Spinbox: ttk Spinbox. 

ノートブック

* オプション: オプション<3>. 
* タブオプション:: 
* タブ識別子:: 
* 仮想イベント: 仮想イベント<3>. 
* ttk.Notebook: ttk Notebook. 

プログレスバー

* オプション: オプション<4>. 
* ttk.Progressbar: ttk Progressbar. 

セパレータ

* オプション: オプション<5>. 

サイズグリップ

* プラットフォーム固有のメモ:: 
* バグ:: 

ツリービュー

* オプション: オプション<6>. 
* 要素オプション:: 
* タグオプション:: 
* カラム識別子:: 
* 仮想イベント: 仮想イベント<4>. 
* ttk.Treeview: ttk Treeview. 

Ttk スタイル

* レイアウト:: 

IDLE --- Python のエディタとシェル

* メニュー:: 
* Editing and Navigation:: 
* Startup and Code Execution:: 
* Help and Preferences:: 
* idlelib: idlelib --- implementation of IDLE application. implementation of IDLE application

メニュー

* File メニュー (Shell ウィンドウ、Editor ウィンドウ): File メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Edit メニュー (Shell ウィンドウ、Editor ウィンドウ): Edit メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Format メニュー (Shell ウィンドウ、Editor ウィンドウ): Format メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Run メニュー (Editor ウィンドウのみ): Run メニュー Editor ウィンドウのみ. 
* Shell メニュー (Shell ウィンドウのみ): Shell メニュー Shell ウィンドウのみ. 
* Debug メニュー (Shell ウィンドウのみ): Debug メニュー Shell ウィンドウのみ. 
* Options メニュー (Shell ウィンドウ、Editor ウィンドウ): Options メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Window メニュー (Shell ウィンドウ、Editor ウィンドウ): Window メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Help メニュー (Shell ウィンドウ、Editor ウィンドウ): Help メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Context menus:: 

Editing and Navigation

* Editor windows:: 
* Key bindings:: 
* 自動的な字下げ:: 
* 検索と置換:: 
* 補完 (Completions): 補完 Completions. 
* 呼び出しヒント (Calltips): 呼び出しヒント Calltips. 
* Format block:: 
* Code Context:: 
* Shell window:: 
* テキストの色:: 

Startup and Code Execution

* コマンドラインでの使用: コマンドラインでの使用<5>. 
* Startup failure:: 
* Running user code:: 
* User output in Shell:: 
* Developing tkinter applications:: 
* サブプロセスを起こさずに起動する:: 

Help and Preferences

* Help sources:: 
* Setting preferences [お好み設定]:: 
* IDLE on macOS:: 
* Extensions [拡張]:: 

turtle --- Turtle graphics

* はじめに: はじめに<12>. 
* Get started:: 
* チュートリアル: チュートリアル<4>. 
* How to...: How to. 
* Turtle graphics reference:: 
* RawTurtle/Turtle のメソッドと対応する関数:: 
* TurtleScreen/Screen のメソッドと対応する関数:: 
* Public classes:: 
* 説明: 説明<2>. 
* ヘルプと設定:: 
* turtledemo: turtledemo --- Demo scripts. Demo scripts
* python 2.6からの変更点: python 2 6からの変更点. 
* python 3.0からの変更点: python 3 0からの変更点. 

チュートリアル

* Starting a turtle environment:: 
* Basic drawing:: 
* Making algorithmic patterns:: 

Basic drawing

* Pen の制御:: 
* The turtle's position:: 

How to...

* Get started as quickly as possible:: 
* Automatically begin and end filling:: 
* Use the turtle module namespace:: 
* Use turtle graphics in a script:: 
* Use object-oriented turtle graphics:: 

Turtle graphics reference

* Turtle のメソッド:: 
* TurtleScreen/Screen のメソッド:: 

RawTurtle/Turtle のメソッドと対応する関数

* Turtle の動き:: 
* Turtle の状態を知る:: 
* 設定と計測:: 
* Pen の制御: Pen の制御<2>. 
* タートルの状態:: 
* イベントを利用する:: 
* 特別な Turtle のメソッド:: 
* Compound shapes:: 

Pen の制御

* 描画状態:: 
* 色の制御: 色の制御<2>. 
* 塗りつぶし:: 
* さらなる描画の制御:: 

タートルの状態

* 可視性:: 
* 見た目:: 

TurtleScreen/Screen のメソッドと対応する関数

* ウィンドウの制御:: 
* アニメーションの制御:: 
* スクリーンイベントを利用する:: 
* 入力メソッド:: 
* 設定と特殊なメソッド:: 
* Screen 独自のメソッド、TurtleScreen から継承したもの以外:: 

ヘルプと設定

* ヘルプの使い方:: 
* ドキュメント文字列の翻訳:: 
* Screen および Turtle の設定方法:: 

開発ツール

* typing: typing --- Support for type hints. Support for type hints
* pydoc: pydoc --- ドキュメント生成とオンラインヘルプシステム. ドキュメント生成とオンラインヘルプシステム
* Python 開発モード:: 
* doctest: doctest --- 対話型の Python の例をテストする. 対話型の Python の例をテストする
* unittest: unittest --- ユニットテストフレームワーク. ユニットテストフレームワーク
* unittest.mock: unittest mock --- モックオブジェクトライブラリ. モックオブジェクトライブラリ
* unittest.mock: unittest mock --- 入門. 入門
* test: test --- Regression tests package for Python. Regression tests package for 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
* test.support.threading_helper: test support threading_helper --- Utilities for threading tests. Utilities for threading tests
* test.support.os_helper: test support os_helper --- Utilities for os tests. Utilities for os tests
* test.support.import_helper: test support import_helper --- Utilities for import tests. Utilities for import tests
* test.support.warnings_helper: test support warnings_helper --- Utilities for warnings tests. Utilities for warnings tests

typing --- Support for type hints

* Python 型システムの仕様:: 
* 型エイリアス:: 
* NewType:: 
* 呼び出し可能オブジェクトのアノテーション:: 
* ジェネリクス:: 
* タプルのアノテーション:: 
* クラスオブジェクトの型:: 
* Annotating generators and coroutines:: 
* ユーザー定義のジェネリック型:: 
* Any 型:: 
* 名前的部分型 vs 構造的部分型:: 
* モジュールの内容: モジュールの内容<3>. 
* メジャーな機能の非推奨時系列:: 

モジュールの内容

* 特殊型付けプリミティブ:: 
* プロトコル: プロトコル<4>. 
* ABCs and Protocols for working with I/O:: 
* Functions and decorators:: 
* Introspection helpers:: 
* 定数: 定数<10>. 
* 非推奨のエイリアス:: 

特殊型付けプリミティブ

* 特殊型:: 
* 特殊形式:: 
* Building generic types and type aliases:: 
* Other special directives:: 

非推奨のエイリアス

* Aliases to built-in types:: 
* Aliases to types in collections:: 
* Aliases to other concrete types:: 
* Aliases to container ABCs in collections.abc: Aliases to container ABCs in collections abc. 
* Aliases to asynchronous ABCs in collections.abc: Aliases to asynchronous ABCs in collections abc. 
* Aliases to other ABCs in collections.abc: Aliases to other ABCs in collections abc. 
* Aliases to contextlib ABCs:: 

Python 開発モード

* Python 開発モードの影響:: 
* ResourceWarning の例:: 
* Bad file descriptor error example:: 

doctest --- 対話型の Python の例をテストする

* 簡単な利用法; docstring 中の実行例をチェックする: 簡単な利用法 docstring 中の実行例をチェックする. 
* 簡単な利用法; テキストファイル中の実行例をチェックする: 簡単な利用法 テキストファイル中の実行例をチェックする. 
* コマンドラインでの使用: コマンドラインでの使用<6>. 
* doctest のからくり:: 
* 基本 API:: 
* 単体テスト API:: 
* 拡張 API:: 
* デバッグ:: 
* アドバイス:: 

doctest のからくり

* どの docstring が検証されるのか?:: 
* docstring 内の実行例をどのように認識するのか?:: 
* 実行コンテキストとは何か?:: 
* 例外はどう扱えばよいか?:: 
* オプションフラグ:: 
* ディレクティブ (Directives): ディレクティブ Directives. 
* 警告: 警告<2>. 

拡張 API

* DocTest オブジェクト:: 
* Example オブジェクト:: 
* DocTestFinder オブジェクト:: 
* DocTestParser オブジェクト:: 
* TestResults objects:: 
* DocTestRunner オブジェクト:: 
* OutputChecker オブジェクト:: 

unittest --- ユニットテストフレームワーク

* 基本的な例: 基本的な例<2>. 
* コマンドラインインターフェイス: コマンドラインインターフェイス<2>. 
* テストディスカバリ:: 
* テストコードの構成:: 
* 既存テストコードの再利用:: 
* テストのスキップと予期された失敗:: 
* サブテストを利用して繰り返しテストの区別を付ける:: 
* クラスと関数:: 
* クラスとモジュールのフィクスチャ:: 
* シグナルハンドリング:: 

コマンドラインインターフェイス

* コマンドラインオプション: コマンドラインオプション<5>. 

クラスと関数

* テストクラス:: 
* テストのグループ化:: 
* テストのロードと起動:: 

テストのロードと起動

* load_tests プロトコル:: 

クラスとモジュールのフィクスチャ

* setUpClass と tearDownClass:: 
* setUpModule と tearDownModule:: 

unittest.mock --- モックオブジェクトライブラリ

* クイックガイド:: 
* Mock クラス:: 
* patcher:: 
* MagicMock と magic method のサポート:: 
* ヘルパー:: 
* Order of precedence of side_effect@comma{} return_value and wraps: Order of precedence of side_effect return_value and wraps. 

Mock クラス

* 呼び出し:: 
* 属性の削除:: 
* Mock の名前と name 属性:: 
* 属性として設定されるモック:: 

patcher

* patch:: 
* patch.object: patch object. 
* patch.dict: patch dict. 
* patch.multiple: patch multiple. 
* patch のメソッド; start と stop: patch のメソッド start と stop. 
* ビルトインをパッチする:: 
* TEST_PREFIX:: 
* patch デコレータをネストする:: 
* どこにパッチするか:: 
* デスクリプタやプロキシオブジェクトにパッチする:: 

MagicMock と magic method のサポート

* Magic Method をモックする:: 
* Magic Mock:: 

ヘルパー

* sentinel:: 
* DEFAULT:: 
* call:: 
* create_autospec:: 
* ANY:: 
* FILTER_DIR:: 
* mock_open:: 
* autospec を使う:: 
* Sealing mocks:: 

unittest.mock --- 入門

* Mock を使う:: 
* patch デコレータ:: 
* さらなる例:: 

Mock を使う

* Mock のパッチ用メソッド:: 
* オブジェクトのメソッド呼び出しに対するモック:: 
* クラスをモックする:: 
* モックに名前をつける:: 
* 全ての呼び出しのトラッキング:: 
* 戻り値や属性を設定する:: 
* モックから例外を発生させる:: 
* side_effect の関数と iterable:: 
* 非同期イテレータをモックする:: 
* 非同期コンテキストマネージャをモックする:: 
* 既存のオブジェクトから Mock を作る:: 
* Using side_effect to return per file content:: 

さらなる例

* chained call をモックする:: 
* 部分的なモック:: 
* ジェネレータメソッドをモックする:: 
* 同じパッチを全てのメソッドに適用する:: 
* Unboundメソッドをモックする:: 
* モックで複数回の呼び出しをチェックする:: 
* ミュータブルな引数に対処する:: 
* patch をネストする:: 
* MagicMock で辞書をモックする:: 
* Mock のサブクラスと属性:: 
* patch.dict で import をモックする: patch dict で import をモックする. 
* Tracking order of calls and less verbose call assertions:: 
* More complex argument matching:: 

test --- Regression tests package for Python

* Writing Unit Tests for the test package:: 
* コマンドラインインターフェースを利用してテストを実行する:: 

デバッグとプロファイル

* 監査イベント表:: 
* bdb: bdb --- デバッガーフレームワーク. デバッガーフレームワーク
* faulthandler: faulthandler --- Python トレースバックをダンプする. Python トレースバックをダンプする
* pdb: pdb --- The Python Debugger. The Python Debugger
* Python プロファイラ:: 
* timeit: timeit --- 小さなコードスニペットの実行時間計測. 小さなコードスニペットの実行時間計測
* trace: trace --- Python 文実行のトレースと追跡. Python 文実行のトレースと追跡
* tracemalloc: tracemalloc --- メモリ割り当ての追跡. メモリ割り当ての追跡

faulthandler --- Python トレースバックをダンプする

* tracebackのダンプ:: 
* Dumping the C stack:: 
* フォールトハンドラの状態:: 
* タイムアウト後にtracebackをダンプする:: 
* ユーザシグナルに対してtracebackをダンプする:: 
* ファイル記述子の問題:: 
* 使用例: 使用例<43>. 

Dumping the C stack

* C Stack Compatibility:: 

pdb --- The Python Debugger

* コマンドライン・インターフェース: コマンドライン・インターフェース<8>. 
* Debugger commands:: 

Python プロファイラ

* プロファイラとは:: 
* かんたんユーザマニュアル:: 
* profile and cProfile Module Reference:: 
* Stats クラス:: 
* 決定論的プロファイリングとは:: 
* 制限事項: 制限事項<2>. 
* キャリブレーション (補正): キャリブレーション 補正. 
* カスタムな時刻取得用関数を使う:: 

timeit --- 小さなコードスニペットの実行時間計測

* 基本的な例: 基本的な例<3>. 
* Python インターフェイス:: 
* コマンドラインインターフェイス: コマンドラインインターフェイス<3>. 
* 使用例: 使用例<44>. 

trace --- Python 文実行のトレースと追跡

* コマンドラインからの使用: コマンドラインからの使用<2>. 
* プログラミングインターフェース:: 

コマンドラインからの使用

* 主要なオプション:: 
* 修飾的オプション:: 
* フィルターオプション:: 

tracemalloc --- メモリ割り当ての追跡

* 使用例: 使用例<45>. 
* API:: 

使用例

* 上位10を表示する:: 
* 差を計算する:: 
* メモリブロックのトレースバックを取得する:: 
* top を整形化する:: 

top を整形化する

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

API

* 関数: 関数<11>. 
* DomainFilter:: 
* Filter:: 
* Frame:: 
* Snapshot:: 
* Statistic:: 
* StatisticDiff:: 
* Trace:: 
* Traceback:: 

ソフトウェア・パッケージと配布

* ensurepip: ensurepip --- pip インストーラーのブートストラップ. pip インストーラーのブートストラップ
* venv: venv --- 仮想環境の作成. 仮想環境の作成
* zipapp: zipapp --- 実行可能な Python zip アーカイブを管理する. 実行可能な Python zip アーカイブを管理する

ensurepip --- pip インストーラーのブートストラップ

* コマンドライン・インターフェース: コマンドライン・インターフェース<9>. 
* モジュール API:: 

venv --- 仮想環境の作成

* 仮想環境の作成: 仮想環境の作成<2>. 
* 仮想環境のしくみ:: 
* API: API<2>. 
* EnvBuilder を拡張する例:: 

zipapp --- 実行可能な Python zip アーカイブを管理する

* 基本的な例: 基本的な例<4>. 
* コマンドラインインターフェイス: コマンドラインインターフェイス<4>. 
* Python API:: 
* 使用例: 使用例<46>. 
* インタープリタの指定:: 
* Creating Standalone Applications with zipapp:: 
* The Python Zip Application Archive Format:: 

Creating Standalone Applications with zipapp

* Caveats:: 

Python ランタイムサービス

* sys: sys --- システム固有のパラメーターと関数. システム固有のパラメーターと関数
* sys.monitoring: sys monitoring --- 実行イベントモニタリング. 実行イベントモニタリング
* sysconfig: sysconfig --- Python の構成情報へのアクセスを提供する. Python の構成情報へのアクセスを提供する
* builtins: builtins --- 組み込みオブジェクト. 組み込みオブジェクト
* __main__: __main__ --- トップレベルのコード環境. トップレベルのコード環境
* warnings: warnings --- 警告の制御. 警告の制御
* dataclasses: dataclasses --- データクラス. データクラス
* contextlib: contextlib --- with 文コンテキスト用ユーティリティ. with 文コンテキスト用ユーティリティ
* abc: abc --- 抽象基底クラス. 抽象基底クラス
* atexit: atexit --- 終了ハンドラー. 終了ハンドラー
* traceback: traceback --- スタックトレースの表示または取得. スタックトレースの表示または取得
* __future__: __future__ --- future 文の定義. future 文の定義
* gc: gc --- ガベージコレクターインターフェース. ガベージコレクターインターフェース
* inspect: inspect --- 活動中のオブジェクトを調査する. 活動中のオブジェクトを調査する
* annotationlib: annotationlib --- Functionality for introspecting annotations. Functionality for introspecting annotations
* site: site --- サイト固有の設定フック. サイト固有の設定フック

sys.monitoring --- 実行イベントモニタリング

* Tool identifiers:: 
* Events:: 
* Turning events on and off:: 
* Registering callback functions:: 

Tool identifiers

* Registering and using tools:: 

Events

* Local events:: 
* Deprecated event:: 
* Ancillary events:: 
* Other events:: 
* The STOP_ITERATION event:: 

Turning events on and off

* Setting events globally:: 
* Per code object events:: 
* Disabling events:: 

Registering callback functions

* Callback function arguments:: 

sysconfig --- Python の構成情報へのアクセスを提供する

* 構成変数:: 
* インストールパス:: 
* User scheme:: 
* Home scheme:: 
* Prefix scheme:: 
* Installation path functions:: 
* その他の関数: その他の関数<3>. 
* コマンドラインでの使用: コマンドラインでの使用<7>. 

User scheme

* posix_user:: 
* nt_user:: 
* osx_framework_user:: 

Home scheme

* posix_home:: 

Prefix scheme

* posix_prefix:: 
* nt:: 

__main__ --- トップレベルのコード環境

* __name__ == '__main__':: 
* __main__.py in Python Packages: __main__ py in Python Packages. 
* import __main__:: 

__name__ == '__main__'

* 「トップレベルのスクリプト環境」とは:: 
* 通常の使われ方:: 
* パッケージングで考慮すべき点:: 

__main__.py in Python Packages

* 通常の使われ方: 通常の使われ方<2>. 

warnings --- 警告の制御

* 警告カテゴリ:: 
* 警告フィルタ:: 
* 一時的に警告を抑制する:: 
* 警告のテスト:: 
* Updating Code For New Versions of Dependencies:: 
* 利用可能な関数:: 
* 利用可能なコンテキストマネージャー:: 
* Concurrent safety of Context Managers:: 

警告フィルタ

* Repeated Warning Suppression Criteria:: 
* Describing Warning Filters:: 
* デフォルトの警告フィルタ:: 
* Overriding the default filter:: 

dataclasses --- データクラス

* モジュールの内容: モジュールの内容<4>. 
* 初期化後の処理:: 
* クラス変数:: 
* 初期化限定変数:: 
* 凍結されたインスタンス:: 
* 継承: 継承<2>. 
* Re-ordering of keyword-only parameters in __init__(): Re-ordering of keyword-only parameters in __init__. 
* デフォルトファクトリ関数:: 
* 可変なデフォルト値:: 
* Descriptor-typed fields:: 

contextlib --- with 文コンテキスト用ユーティリティ

* ユーティリティ:: 
* 例とレシピ: 例とレシピ<3>. 
* 単回使用、再利用可能、およびリエントラントなコンテキストマネージャ:: 

例とレシピ

* 可変数個のコンテキストマネージャーをサポートする:: 
* __enter__ メソッドからの例外をキャッチする:: 
* __enter__ 実装内のクリーンアップ:: 
* try-finally + flag 変数パターンを置き換える:: 
* コンテキストマネージャーを関数デコレーターとして使う:: 

単回使用、再利用可能、およびリエントラントなコンテキストマネージャ

* リエントラントなコンテキストマネージャ:: 
* 再利用可能なコンテキストマネージャ:: 

atexit --- 終了ハンドラー

* atexit Example:: 

traceback --- スタックトレースの表示または取得

* モジュールレベルの関数: モジュールレベルの関数<2>. 
* TracebackException オブジェクト:: 
* StackSummary オブジェクト:: 
* FrameSummary オブジェクト:: 
* Examples of Using the Module-Level Functions:: 
* Examples of Using TracebackException:: 

__future__ --- future 文の定義

* モジュールコンテンツ: モジュールコンテンツ<5>. 

inspect --- 活動中のオブジェクトを調査する

* 型とメンバー:: 
* ソースコードの情報取得:: 
* Signature オブジェクトで呼び出し可能オブジェクトを内省する:: 
* クラスと関数: クラスと関数<2>. 
* インタープリタスタック:: 
* 属性の静的なフェッチ:: 
* Current State of Generators@comma{} Coroutines@comma{} and Asynchronous Generators: Current State of Generators Coroutines and Asynchronous Generators. 
* Code Objects Bit Flags:: 
* Buffer flags:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<10>. 

annotationlib --- Functionality for introspecting annotations

* Annotation semantics:: 
* クラス: クラス<5>. 
* 関数: 関数<12>. 
* レシピ: レシピ<3>. 
* Limitations of the STRING format:: 
* Limitations of the FORWARDREF format:: 
* Security implications of introspecting annotations:: 

レシピ

* Using annotations in a metaclass:: 

site --- サイト固有の設定フック

* sitecustomize:: 
* usercustomize:: 
* readline の設定:: 
* モジュールの内容: モジュールの内容<5>. 
* コマンドライン・インターフェース: コマンドライン・インターフェース<11>. 

カスタム Python インタプリタ

* code: code --- インタープリター基底クラス. インタープリター基底クラス
* codeop: codeop --- Python コードをコンパイルする. Python コードをコンパイルする

code --- インタープリター基底クラス

* 対話的なインタプリタオブジェクト:: 
* 対話的なコンソールオブジェクト:: 

モジュールのインポート

* zipimport: zipimport --- Zip アーカイブからモジュールをインポートする. Zip アーカイブからモジュールをインポートする
* pkgutil: pkgutil --- パッケージ拡張ユーティリティ. パッケージ拡張ユーティリティ
* modulefinder: modulefinder --- スクリプト中で使用されているモジュールの検索. スクリプト中で使用されているモジュールの検索
* runpy: runpy --- Python モジュールの位置特定と実行. Python モジュールの位置特定と実行
* importlib: importlib --- import の実装. import の実装
* importlib.resources: importlib resources -- パッケージリソースの読み取り、オープン、アクセス. パッケージリソースの読み取り、オープン、アクセス
* importlib.resources.abc: importlib resources abc -- リソースの抽象基底クラス. リソースの抽象基底クラス
* importlib.metadata: importlib metadata -- パッケージメタデータへのアクセス. パッケージメタデータへのアクセス
* sys.path モジュール検索パスの初期化: sys path モジュール検索パスの初期化. 

zipimport --- Zip アーカイブからモジュールをインポートする

* zipimporter オブジェクト:: 
* 使用例: 使用例<47>. 

modulefinder --- スクリプト中で使用されているモジュールの検索

* ModuleFinder の使用例:: 

importlib --- import の実装

* はじめに: はじめに<13>. 
* 関数: 関数<13>. 
* importlib.abc: importlib abc -- Abstract base classes related to import. Abstract base classes related to import
* importlib.machinery: importlib machinery -- Importers and path hooks. Importers and path hooks
* importlib.util: importlib util -- Utility code for importers. Utility code for importers
* 使用例: 使用例<48>. 

使用例

* プログラムからのインポート:: 
* モジュールがインポートできるか確認する:: 
* ソースファイルから直接インポートする:: 
* Implementing lazy imports:: 
* インポーターのセットアップ:: 
* Approximating importlib.import_module(): Approximating importlib import_module. 

importlib.resources -- パッケージリソースの読み取り、オープン、アクセス

* 関数 API:: 

importlib.metadata -- パッケージメタデータへのアクセス

* 概要: 概要<3>. 
* 機能 API:: 
* Distributions:: 
* Distribution Discovery:: 
* Implementing Custom Providers:: 

機能 API

* エントリポイント:: 
* 配布物メタデータ:: 
* 配布物バージョン:: 
* 配布物ファイル:: 
* 配布物の要件:: 
* Mapping import to distribution packages:: 

Implementing Custom Providers

* 使用例: 使用例<49>. 

sys.path モジュール検索パスの初期化

* Virtual Environments:: 
* _pth files:: 
* 埋め込みの Python:: 

Python言語サービス

* ast: ast --- Abstract syntax trees. Abstract syntax trees
* symtable: symtable --- コンパイラーの記号表へのアクセス. コンパイラーの記号表へのアクセス
* token: token --- Python 解析木で使われる定数. Python 解析木で使われる定数
* keyword: keyword --- Python キーワードのテスト. Python キーワードのテスト
* tokenize: tokenize --- Python ソース用のトークナイザー. Python ソース用のトークナイザー
* tabnanny: tabnanny --- あいまいなインデントの検出. あいまいなインデントの検出
* pyclbr: pyclbr --- Python モジュールブラウザーサポート. Python モジュールブラウザーサポート
* py_compile: py_compile --- Python ソースファイルをコンパイルする. Python ソースファイルをコンパイルする
* compileall: compileall --- Python ライブラリをバイトコンパイルする. Python ライブラリをバイトコンパイルする
* dis: dis --- Python バイトコードの逆アセンブラー. Python バイトコードの逆アセンブラー
* pickletools: pickletools --- pickle 開発者用のツール群. pickle 開発者用のツール群

ast --- Abstract syntax trees

* Abstract grammar:: 
* Node クラス:: 
* ast helpers:: 
* Compiler flags: Compiler flags<2>. 
* コマンドラインでの使用: コマンドラインでの使用<8>. 

Node クラス

* Root nodes:: 
* リテラル: リテラル<3>. 
* 変数:: 
* 式 (expression): 式 expression<2>. 
* 文 (Statements): 文 Statements. 
* 制御フロー:: 
* Pattern matching:: 
* Type annotations:: 
* Type parameters:: 
* 関数およびクラス定義:: 
* async と await:: 

式 (expression)

* 配列要素の参照 (Subscripting): 配列要素の参照 Subscripting. 
* 内包表記 (Comprehension): 内包表記 Comprehension. 

文 (Statements)

* インポート:: 

symtable --- コンパイラーの記号表へのアクセス

* 記号表の生成:: 
* 記号表の検査:: 
* コマンドラインからの使用: コマンドラインからの使用<3>. 

tokenize --- Python ソース用のトークナイザー

* 入力のトークナイズ:: 
* コマンドラインからの使用: コマンドラインからの使用<4>. 
* 使用例: 使用例<50>. 

pyclbr --- Python モジュールブラウザーサポート

* Function オブジェクト:: 
* クラスオブジェクト: クラスオブジェクト<2>. 

py_compile --- Python ソースファイルをコンパイルする

* コマンドラインインターフェイス: コマンドラインインターフェイス<5>. 

compileall --- Python ライブラリをバイトコンパイルする

* コマンドラインでの使用: コマンドラインでの使用<9>. 
* パブリックな関数:: 

dis --- Python バイトコードの逆アセンブラー

* コマンドライン・インターフェース: コマンドライン・インターフェース<12>. 
* バイトコード解析:: 
* 解析関数:: 
* Python バイトコード命令:: 
* 命令コードコレクション:: 

pickletools --- pickle 開発者用のツール群

* コマンドラインでの使用: コマンドラインでの使用<10>. 
* Programmatic interface:: 

コマンドラインでの使用

* コマンドラインオプション: コマンドラインオプション<6>. 

MS Windows 固有のサービス

* msvcrt: msvcrt --- MS VC++ ランタイムの有用なルーチン群. MS VC++ ランタイムの有用なルーチン群
* winreg: winreg --- Windows レジストリへのアクセス. Windows レジストリへのアクセス
* winsound: winsound --- Windows 用の音声再生インターフェース. Windows 用の音声再生インターフェース

msvcrt --- MS VC++ ランタイムの有用なルーチン群

* ファイル操作関連:: 
* コンソール I/O 関連:: 
* その多の関数:: 

winreg --- Windows レジストリへのアクセス

* 関数: 関数<14>. 
* 定数: 定数<11>. 
* レジストリハンドルオブジェクト:: 

定数

* HKEY_* 定数:: 
* アクセス権限:: 
* 値の型:: 

アクセス権限

* 64-bit 特有のアクセス権:: 

Unix-specific services

* shlex: shlex --- 単純な字句解析. 単純な字句解析
* posix: posix --- 最も一般的な POSIX システムコール群. 最も一般的な POSIX システムコール群
* pwd: pwd --- パスワードデータベース. パスワードデータベース
* grp: grp --- グループデータベース. グループデータベース
* termios: termios --- POSIX スタイルの端末制御. POSIX スタイルの端末制御
* tty: tty --- 端末制御用の関数群. 端末制御用の関数群
* pty: pty --- 擬似端末ユーティリティ. 擬似端末ユーティリティ
* fcntl: fcntl --- fcntl および ioctl システムコール. fcntl および ioctl システムコール
* resource: resource --- リソース使用情報. リソース使用情報
* syslog: syslog --- Unix syslog ライブラリルーチン群. Unix syslog ライブラリルーチン群

shlex --- 単純な字句解析

* shlex オブジェクト:: 
* 解析規則:: 
* Improved Compatibility with Shells:: 

posix --- 最も一般的な POSIX システムコール群

* ラージファイルのサポート:: 
* 注目すべきモジュールの内容:: 

termios --- POSIX スタイルの端末制御

* 使用例: 使用例<51>. 

pty --- 擬似端末ユーティリティ

* 使用例: 使用例<52>. 

resource --- リソース使用情報

* リソースの制限:: 
* リソースの使用状態:: 

syslog --- Unix syslog ライブラリルーチン群

* 使用例: 使用例<53>. 

使用例

* シンプルな例:: 

取って代わられたモジュール群

* getopt: getopt --- C-style parser for command line options. C-style parser for command line options

削除されたモジュール

* aifc: aifc --- Read and write AIFF and AIFC files. Read and write AIFF and AIFC files
* asynchat: asynchat --- Asynchronous socket command/response handler. Asynchronous socket command/response handler
* asyncore: asyncore --- Asynchronous socket handler. Asynchronous socket handler
* audioop: audioop --- Manipulate raw audio data. Manipulate raw audio data
* cgi: cgi --- Common Gateway Interface のサポート. Common Gateway Interface のサポート
* cgitb: cgitb --- Traceback manager for CGI scripts. Traceback manager for CGI scripts
* chunk: chunk --- Read IFF chunked data. Read IFF chunked data
* crypt: crypt --- Function to check Unix passwords. Function to check Unix passwords
* distutils: distutils --- Building and installing Python modules. Building and installing Python modules
* imghdr: imghdr --- Determine the type of an image. Determine the type of an image
* imp: imp --- Access the import internals. Access the import internals
* mailcap: mailcap --- Mailcap file handling. Mailcap file handling
* msilib: msilib --- Read and write Microsoft Installer files. Read and write Microsoft Installer files
* nis: nis --- Interface to Sun’s NIS Yellow Pages. Interface to Sun’s NIS (Yellow Pages)
* nntplib: nntplib --- NNTP protocol client. NNTP protocol client
* ossaudiodev: ossaudiodev --- Access to OSS-compatible audio devices. Access to OSS-compatible audio devices
* pipes: pipes --- Interface to shell pipelines. Interface to shell pipelines
* smtpd: smtpd --- SMTP Server. SMTP Server
* sndhdr: sndhdr --- Determine type of sound file. Determine type of sound file
* spwd: spwd --- The shadow password database. The shadow password database
* sunau: sunau --- Read and write Sun AU files. Read and write Sun AU files
* telnetlib: telnetlib --- Telnet client. Telnet client
* uu: uu --- Encode and decode uuencode files. Encode and decode uuencode files
* xdrlib: xdrlib --- Encode and decode XDR data. Encode and decode XDR data

Python インタプリタの拡張と埋め込み

* おすすめのサードパーティツール:: 
* サードパーティツールなしで拡張を作る:: 
* 大規模なアプリケーションへの Python ランタイムの埋め込み:: 

サードパーティツールなしで拡張を作る

* C や C++ による Python の拡張:: 
* 拡張の型の定義; チュートリアル: 拡張の型の定義 チュートリアル. 
* 拡張の型の定義; 雑多なトピック: 拡張の型の定義 雑多なトピック. 
* C および C++ 拡張のビルド:: 
* Windows 上での C および C++ 拡張モジュールのビルド:: 

C や C++ による Python の拡張

* 簡単な例:: 
* 幕間小話; エラーと例外: 幕間小話 エラーと例外. 
* 例に戻る:: 
* モジュールのメソッドテーブルと初期化関数:: 
* コンパイルとリンク:: 
* C から Python 関数を呼び出す:: 
* 拡張モジュール関数でのパラメタ展開:: 
* 拡張モジュール関数のキーワードパラメタ:: 
* 任意の値を構築する:: 
* 参照カウント法:: 
* C++での拡張モジュール作成:: 
* 拡張モジュールに C API を提供する:: 

参照カウント法

* Python における参照カウント法:: 
* 所有権にまつわる規則:: 
* 薄氷:: 
* NULL ポインタ:: 

拡張の型の定義: チュートリアル

* 基本的なこと:: 
* 基本のサンプルにデータとメソッドを追加する:: 
* データ属性をこまかく制御する:: 
* 循環ガベージコレクションをサポートする:: 
* 他の型のサブクラスを作る:: 

拡張の型の定義: 雑多なトピック

* ファイナライズとメモリ解放:: 
* オブジェクト表現:: 
* 属性を管理する:: 
* オブジェクトの比較:: 
* 抽象的なプロトコルのサポート:: 
* 弱参照(Weak Reference)のサポート: 弱参照 Weak Reference のサポート. 
* その他いろいろ:: 

属性を管理する

* 総称的な属性を管理する:: 
* 特定の型に特化した属性の管理:: 

C および C++ 拡張のビルド

* setuptools による C および C++ 拡張のビルド:: 

Windows 上での C および C++ 拡張モジュールのビルド

* 型どおりのアプローチ:: 
* Unix と Windows の相違点:: 
* DLL 使用の実際:: 

大規模なアプリケーションへの Python ランタイムの埋め込み

* 他のアプリケーションへの Python の埋め込み:: 

他のアプリケーションへの Python の埋め込み

* 高水準の埋め込み:: 
* 超高水準の埋め込みから踏み出す; 概要: 超高水準の埋め込みから踏み出す 概要. 
* 純粋な埋め込み:: 
* 埋め込まれた Python の拡張:: 
* C++による Python の埋め込み:: 
* Unix 系システムにおけるコンパイルとリンク:: 

Python/C API リファレンスマニュアル

* はじめに: はじめに<14>. 
* C API の安定性:: 
* 超高水準レイヤ:: 
* 参照カウント:: 
* 例外処理:: 
* 拡張モジュールの定義:: 
* ユーティリティ: ユーティリティ<2>. 
* 抽象オブジェクトレイヤ (Abstract Objects Layer): 抽象オブジェクトレイヤ Abstract Objects Layer. 
* 具象オブジェクト (concrete object) レイヤ: 具象オブジェクト concrete object レイヤ. 
* 初期化 (initialization)、終了処理 (finalization)、スレッド: 初期化 initialization 、終了処理 finalization 、スレッド. 
* Python 初期化設定:: 
* メモリ管理:: 
* オブジェクト実装サポート (object implementation support): オブジェクト実装サポート object implementation support. 
* API と ABI のバージョニング:: 
* Monitoring C API:: 
* Generating Execution Events:: 

はじめに

* 言語バージョン互換性:: 
* コーディング基準:: 
* インクルードファイル:: 
* 便利なマクロ:: 
* オブジェクト、型および参照カウント:: 
* 例外: 例外<24>. 
* Python の埋め込み: Python の埋め込み<2>. 
* デバッグ版ビルド (Debugging Builds): デバッグ版ビルド Debugging Builds. 
* おすすめのサードパーティツール: おすすめのサードパーティツール<2>. 

便利なマクロ

* Docstring macros:: 
* General utility macros:: 
* Declaration utilities:: 
* Outdated macros:: 

General utility macros

* Numeric utilities:: 
* Assertion utilities:: 
* Type size utilities:: 
* Macro definition utilities:: 

オブジェクト、型および参照カウント

* 参照カウント法: 参照カウント法<2>. 
* 型: 型<2>. 

参照カウント法

* 参照カウントの詳細:: 

C API の安定性

* Unstable C API:: 
* 安定 ABI (Stable Appliction Binary Interface): 安定 ABI Stable Appliction Binary Interface. 
* プラットフォームで考慮すべき点:: 
* 限定版APIの内容:: 

安定 ABI (Stable Appliction Binary Interface)

* Limited C API:: 
* Stable ABI:: 
* APIスコープとパフォーマンスの制限:: 
* 制限付きAPIの注意点:: 

超高水準レイヤ

* Available start symbols:: 
* Stack Effects:: 

例外処理

* 出力とクリア:: 
* 例外の送出:: 
* 警告: 警告<3>. 
* エラーインジケータの問い合わせ:: 
* シグナルハンドリング: シグナルハンドリング<2>. 
* 例外クラス: 例外クラス<2>. 
* 例外オブジェクト:: 
* Unicode 例外オブジェクト:: 
* 再帰の管理:: 
* Exception and warning types:: 
* Tracebacks:: 

Exception and warning types

* Exception types:: 
* OSError aliases:: 
* Warning types:: 

拡張モジュールの定義

* 複数のモジュールインスタンス:: 
* 初期化関数:: 
* 多段階初期化:: 
* 従来の一段階初期化:: 

ユーティリティ

* オペレーティングシステム関連のユーティリティ:: 
* システム関数:: 
* プロセス制御:: 
* モジュールのインポート: モジュールのインポート<2>. 
* データ整列化 (data marshalling) のサポート: データ整列化 data marshalling のサポート. 
* 引数の解釈と値の構築:: 
* 文字列の変換と書式化:: 
* Character classification and conversion:: 
* PyHash API:: 
* リフレクション:: 
* codec レジストリとサポート関数:: 
* PyTime C API:: 
* Support for Perf Maps:: 

引数の解釈と値の構築

* 引数を解析する: 引数を解析する<2>. 
* 値の構築:: 

引数を解析する

* 文字列とバッファ:: 
* 数: 数<2>. 
* その他のオブジェクト:: 
* API 関数:: 

codec レジストリとサポート関数

* コーデック検索API:: 
* Unicode エラーハンドラ用レジストリ API:: 
* Codec utility variables:: 

PyTime C API

* 型: 型<3>. 
* Clock Functions:: 
* Raw Clock Functions:: 
* Conversion functions:: 

抽象オブジェクトレイヤ (Abstract Objects Layer)

* オブジェクトプロトコル (object protocol): オブジェクトプロトコル object protocol. 
* Call プロトコル:: 
* 数値型プロトコル (number protocol): 数値型プロトコル number protocol. 
* シーケンス型プロトコル (sequence protocol): シーケンス型プロトコル sequence protocol. 
* マップ型プロトコル (mapping protocol): マップ型プロトコル mapping protocol. 
* イテレータプロトコル (iterator protocol): イテレータプロトコル iterator protocol. 
* バッファプロトコル (buffer Protocol): バッファプロトコル buffer Protocol. 

Call プロトコル

* The tp_call Protocol:: 
* The Vectorcall Protocol:: 
* Object Calling API:: 
* Call Support API:: 

The Vectorcall Protocol

* 再帰の管理: 再帰の管理<2>. 
* Vectorcall Support API:: 

バッファプロトコル (buffer Protocol)

* buffer 構造体:: 
* バッファリクエストのタイプ:: 
* 複雑な配列:: 
* バッファ関連の関数:: 

バッファリクエストのタイプ

* リクエストに依存しないフィールド:: 
* readonly@comma{} format: readonly format. 
* shape@comma{} strides@comma{} suboffsets: shape strides suboffsets. 
* 隣接性のリクエスト:: 
* 複合リクエスト:: 

複雑な配列

* NumPy スタイル; shape@comma{} strides: NumPy スタイル shape strides. 
* PIL スタイル; shape@comma{} strides@comma{} suboffsets: PIL スタイル shape strides suboffsets. 

具象オブジェクト (concrete object) レイヤ

* 基本オブジェクト (fundamental object): 基本オブジェクト fundamental object. 
* 数値型オブジェクト (numeric object): 数値型オブジェクト numeric object. 
* シーケンスオブジェクト (sequence object): シーケンスオブジェクト sequence object. 
* Container オブジェクト:: 
* Function オブジェクト: Function オブジェクト<2>. 
* その他のオブジェクト: その他のオブジェクト<2>. 
* C API for extension modules:: 

基本オブジェクト (fundamental object)

* 型オブジェクト: 型オブジェクト<2>. 
* None オブジェクト:: 

型オブジェクト

* Creating Heap-Allocated Types:: 

数値型オブジェクト (numeric object)

* 整数型オブジェクト (integer object): 整数型オブジェクト integer object. 
* Boolean オブジェクト:: 
* Floating-Point Objects:: 
* 複素数オブジェクト:: 

整数型オブジェクト (integer object)

* Export API:: 
* PyLongWriter API:: 
* Deprecated API:: 

Floating-Point Objects

* Pack and Unpack functions:: 

Pack and Unpack functions

* Pack functions:: 
* Unpack functions:: 

複素数オブジェクト

* C 構造体としての複素数:: 
* Python オブジェクトとしての複素数型:: 

シーケンスオブジェクト (sequence object)

* バイトオブジェクト: バイトオブジェクト<2>. 
* bytearray オブジェクト: bytearray オブジェクト<2>. 
* Unicode オブジェクトと codec:: 
* タプルオブジェクト (tuple object): タプルオブジェクト tuple object. 
* Struct Sequence オブジェクト:: 
* リストオブジェクト:: 

bytearray オブジェクト

* 型チェックマクロ:: 
* ダイレクト API 関数:: 
* マクロ:: 

Unicode オブジェクトと codec

* Unicode オブジェクト:: 
* 組み込み codec (built-in codec): 組み込み codec built-in codec. 
* メソッドおよびスロット関数 (slot function): メソッドおよびスロット関数 slot function. 
* PyUnicodeWriter:: 
* Deprecated API: Deprecated API<2>. 

Unicode オブジェクト

* Unicode 型:: 
* Unicode 文字プロパティ:: 
* Unicode 文字列の生成とアクセス:: 
* ロケールエンコーディング:: 
* ファイルシステムエンコーディング:: 
* wchar_t サポート:: 

組み込み codec (built-in codec)

* 汎用 codec:: 
* 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:: 
* Windows 用の MBCS codec:: 

Container オブジェクト

* 辞書オブジェクト (dictionary object): 辞書オブジェクト dictionary object. 
* Set オブジェクト:: 

辞書オブジェクト (dictionary object)

* Dictionary View Objects:: 
* Ordered Dictionaries:: 

Set オブジェクト

* Deprecated API: Deprecated API<3>. 

Function オブジェクト

* Function オブジェクト: Function オブジェクト<3>. 
* インスタンスメソッドオブジェクト(Instance Method Objects): インスタンスメソッドオブジェクト Instance Method Objects. 
* メソッドオブジェクト: メソッドオブジェクト<2>. 
* セルオブジェクト (cell object): セルオブジェクト cell object. 
* コードオブジェクト: コードオブジェクト<3>. 
* Code Object Flags:: 
* Extra information:: 

その他のオブジェクト

* ファイルオブジェクト:: 
* モジュールオブジェクト (module object): モジュールオブジェクト module object. 
* Module definitions:: 
* Creating extension modules dynamically:: 
* サポート関数:: 
* イテレータオブジェクト (iterator object): イテレータオブジェクト iterator object. 
* デスクリプタオブジェクト (descriptor object): デスクリプタオブジェクト descriptor object. 
* スライスオブジェクト (slice object): スライスオブジェクト slice object. 
* memoryview オブジェクト:: 
* Pickle buffer objects:: 
* 弱参照オブジェクト: 弱参照オブジェクト<2>. 
* カプセル: カプセル<2>. 
* フレーム (frame) オブジェクト: フレーム frame オブジェクト<2>. 
* ジェネレータオブジェクト:: 
* コルーチンオブジェクト: コルーチンオブジェクト<2>. 
* コンテキスト変数オブジェクト:: 
* 型ヒントのためのオブジェクト:: 

ファイルオブジェクト

* Deprecated API: Deprecated API<4>. 

Module definitions

* Module slots:: 

サポート関数

* Module lookup (single-phase initialization): Module lookup single-phase initialization. 

イテレータオブジェクト (iterator object)

* Range Objects:: 
* Builtin Iterator Types:: 
* Other Iterator Objects:: 

デスクリプタオブジェクト (descriptor object)

* Built-in descriptors:: 

スライスオブジェクト (slice object)

* Ellipsis オブジェクト: Ellipsis オブジェクト<2>. 

フレーム (frame) オブジェクト

* Frame Locals Proxies:: 
* Legacy Local Variable APIs:: 
* Internal Frames:: 

ジェネレータオブジェクト

* Asynchronous Generator Objects:: 
* Deprecated API: Deprecated API<5>. 

C API for extension modules

* Curses C API:: 
* Internal data:: 
* DateTime オブジェクト: DateTime オブジェクト<2>. 
* Internal data: Internal data<2>. 

初期化 (initialization)、終了処理 (finalization)、スレッド

* Python 初期化以前:: 
* グローバルな設定変数:: 
* インタープリタの初期化と終了処理:: 
* プロセスワイドのパラメータ:: 
* スレッド状態 (thread state) とグローバルインタプリタロック (global interpreter lock): スレッド状態 thread state とグローバルインタプリタロック global interpreter lock. 
* サブインタプリタサポート:: 
* 非同期通知:: 
* プロファイルとトレース (profiling and tracing): プロファイルとトレース profiling and tracing. 
* Reference tracing:: 
* 高度なデバッガサポート (advanced debugger support): 高度なデバッガサポート advanced debugger support. 
* スレッドローカルストレージのサポート:: 
* 同期プリミティブ: 同期プリミティブ<3>. 
* Operating System Thread APIs:: 

スレッド状態 (thread state) とグローバルインタプリタロック (global interpreter lock)

* Detaching the thread state from extension code:: 
* Python 以外で作られたスレッド:: 
* Supporting subinterpreters in non-Python threads:: 
* Cautions about fork(): Cautions about fork. 
* Cautions regarding runtime finalization:: 
* 高レベルAPI:: 
* 低レベルAPI:: 

サブインタプリタサポート

* A Per-Interpreter GIL:: 
* バグと注意事項:: 

スレッドローカルストレージのサポート

* スレッド固有ストレージ (Thread Specific Storage@comma{} TSS) API: スレッド固有ストレージ Thread Specific Storage TSS API. 
* スレッドローカルストレージ (TLS) API: スレッドローカルストレージ TLS API. 

スレッド固有ストレージ (Thread Specific Storage, TSS) API

* 動的メモリ確保:: 
* メソッド: メソッド<2>. 

同期プリミティブ

* Python Critical Section API:: 
* Legacy Locking APIs:: 

Python 初期化設定

* PyInitConfig C API:: 
* Configuration Options:: 
* Runtime Python configuration API:: 
* PyConfig C API:: 
* Py_GetArgcArgv(): Py_GetArgcArgv. 
* Delaying main module execution:: 

PyInitConfig C API

* 使用例: 使用例<54>. 
* 設定の作成:: 
* エラー処理: エラー処理<2>. 
* Get Options:: 
* Set Options:: 
* Module:: 
* Initialize Python:: 

PyConfig C API

* 使用例: 使用例<55>. 
* PyWideStringList:: 
* PyStatus:: 
* PyPreConfig:: 
* Preinitialize Python with PyPreConfig:: 
* PyConfig:: 
* Initialization with PyConfig:: 
* Isolated Configuration:: 
* Python Configuration:: 
* Python Path Configuration:: 

メモリ管理

* 概要: 概要<4>. 
* Allocator Domains:: 
* 生メモリインターフェース:: 
* メモリインターフェース:: 
* オブジェクトアロケータ:: 
* Default Memory Allocators:: 
* メモリアロケータをカスタマイズする:: 
* Debug hooks on the Python memory allocators:: 
* pymalloc アロケータ:: 
* The mimalloc allocator:: 
* tracemalloc C API:: 
* 使用例: 使用例<56>. 

メモリインターフェース

* 非推奨のエイリアス: 非推奨のエイリアス<2>. 

pymalloc アロケータ

* pymalloc アリーナアロケータのカスタマイズ:: 

オブジェクト実装サポート (object implementation support)

* オブジェクトをヒープ上にメモリ確保する:: 
* Object Life Cycle:: 
* 共通のオブジェクト構造体 (common object structure): 共通のオブジェクト構造体 common object structure. 
* Type Object Structures:: 
* 循環参照ガベージコレクションをサポートする:: 

オブジェクトをヒープ上にメモリ確保する

* 非推奨のエイリアス: 非推奨のエイリアス<3>. 

Object Life Cycle

* Life Events:: 
* Cyclic Isolate Destruction:: 
* 関数: 関数<15>. 

共通のオブジェクト構造体 (common object structure)

* Base object types and macros:: 
* Implementing functions and methods:: 
* Accessing attributes of extension types:: 

Accessing attributes of extension types

* Member flags:: 
* Member types:: 
* Defining Getters and Setters:: 

Type Object Structures

* クイックリファレンス:: 
* PyTypeObject 定義:: 
* PyObject スロット:: 
* PyVarObject スロット:: 
* PyTypeObject スロット:: 
* Static Types:: 
* Heap Types:: 
* 数値オブジェクト構造体:: 
* マップオブジェクト構造体:: 
* シーケンスオブジェクト構造体:: 
* バッファオブジェクト構造体 (buffer object structure): バッファオブジェクト構造体 buffer object structure. 
* async オブジェクト構造体:: 
* Slot Type typedefs:: 
* 使用例: 使用例<57>. 

クイックリファレンス

* tp スロット:: 
* sub-slots:: 
* スロットの定義型 (typedef): スロットの定義型 typedef. 

循環参照ガベージコレクションをサポートする

* Controlling the Garbage Collector State:: 
* Querying Garbage Collector State:: 

API と ABI のバージョニング

* Build-time version constants:: 
* Run-time version:: 
* Bit-packing macros:: 

Generating Execution Events

* Managing the Monitoring State:: 

Python モジュールのインストール

* 重要用語集:: 
* 基本的な使い方: 基本的な使い方<5>. 
* どうすればいいの...？: どうすればいいの ？. 
* よくあるインストールに関する問題:: 

どうすればいいの...？

* ... pip を 3.4 より前のバージョンの Python でインストールするには？: pip を 3 4 より前のバージョンの Python でインストールするには？. 
* ... パッケージを現在のユーザ用のみにインストールするには？: パッケージを現在のユーザ用のみにインストールするには？. 
* ... 科学技術計算用の Python パッケージをインストールするには？: 科学技術計算用の Python パッケージをインストールするには？. 
* ... インストールされた複数のバージョンの Python を並行して使うには？: インストールされた複数のバージョンの Python を並行して使うには？. 

よくあるインストールに関する問題

* Linux で、システムの Python 内にインストールする:: 
* pip がインストールされていない:: 
* バイナリの拡張のインストール:: 

Python HOWTO

* A Conceptual Overview of asyncio:: 
* Python 3 への拡張モジュール移植:: 
* Python で Curses プログラミング:: 
* デスクリプタ ガイド:: 
* Debugging C API extensions and CPython Internals with GDB:: 
* 列挙型 HOWTO:: 
* 関数型プログラミング HOWTO:: 
* Logging HOWTO:: 
* Logging クックブック:: 
* 正規表現 HOWTO:: 
* ソケットプログラミング HOWTO:: 
* ソートのテクニック:: 
* Unicode HOWTO:: 
* urllib パッケージを使ってインターネット上のリソースを取得するには:: 
* ipaddressモジュールの紹介:: 
* DTrace と SystemTap で CPython を測定する:: 
* Python support for the Linux perf profiler:: 
* Annotations Best Practices:: 
* 拡張モジュールを分離する:: 
* timer file descriptor HOWTO:: 
* The Python 2.3 Method Resolution Order: The Python 2 3 Method Resolution Order. 
* Python support for free threading:: 
* C API Extension Support for Free Threading:: 
* Remote debugging attachment protocol:: 
* Permission requirements:: 
* Locating the PyRuntime structure:: 
* Reading _Py_DebugOffsets:: 
* Locating the interpreter and thread state:: 
* Writing control information:: 
* Summary:: 

A Conceptual Overview of asyncio

* A conceptual overview part 1; the high-level: A conceptual overview part 1 the high-level. 
* A conceptual overview part 2; the nuts and bolts: A conceptual overview part 2 the nuts and bolts. 

A conceptual overview part 1: the high-level

* イベントループ: イベントループ<2>. 
* Asynchronous functions and coroutines:: 
* Task: Task<2>. 
* await:: 

A conceptual overview part 2: the nuts and bolts

* The inner workings of coroutines:: 
* Future: Future<2>. 
* A homemade asyncio.sleep: A homemade asyncio sleep. 

Python で Curses プログラミング

* curses ってなに?:: 
* curses アプリケーションの起動と終了:: 
* ウィンドウとパッド:: 
* テキストの表示:: 
* ユーザ入力:: 
* より多くの情報:: 

curses ってなに?

* Python の curses module:: 

テキストの表示

* 属性とカラー:: 

デスクリプタ ガイド

* 入門:: 
* 実践的なサンプル:: 
* 技術的なチュートリアル:: 
* ピュアPythonの等価実装:: 

入門

* シンプルな例; 定数を返すデスクリプタ: シンプルな例 定数を返すデスクリプタ. 
* 動的なルックアップ:: 
* 管理された属性:: 
* 名前のカスタマイズ:: 
* まとめ:: 

実践的なサンプル

* バリデータクラス:: 
* カスタムバリデータ:: 
* 実践的なアプリケーション:: 

技術的なチュートリアル

* 概要: 概要<5>. 
* 定義と導入:: 
* デスクリプタプロトコル:: 
* デスクリプタ呼び出しの概要:: 
* インスタンスからの呼び出し:: 
* クラスからの呼び出し:: 
* superからの呼び出し:: 
* 呼び出しロジックのまとめ:: 
* 自動的の名前の伝達:: 
* ORMのサンプル:: 

ピュアPythonの等価実装

* プロパティ:: 
* 関数とメソッド:: 
* メソッドの種類:: 
* 静的メソッド:: 
* クラスメソッド:: 
* メンバーオブジェクトと __slots__:: 

Debugging C API extensions and CPython Internals with GDB

* Prerequisites:: 
* Using the Debug build and Development mode:: 
* Using the python-gdb extension:: 
* Use with GDB commands:: 

Prerequisites

* Setup with Python built from source:: 
* Setup for Python from a Linux distro:: 

Using the python-gdb extension

* Pretty-printers:: 
* py-list:: 
* py-up and py-down:: 
* py-bt:: 
* py-print:: 
* py-locals:: 

列挙型 HOWTO

* 列挙型メンバーおよびそれらの属性へのプログラム的アクセス:: 
* 列挙型メンバーと値の重複:: 
* 番号付けの値が一意であることの確認:: 
* 値の自動設定を使う:: 
* イテレーション: イテレーション<2>. 
* 比較: 比較<3>. 
* 列挙型で許されるメンバーと属性:: 
* Enumのサブクラス化の制限:: 
* データクラスのサポート:: 
* Pickle 化:: 
* 関数 API: 関数 API<2>. 
* 派生列挙型:: 
* When to use __new__() vs. __init__(): When to use __new__ vs __init__. 
* EnumとFlagはどう違うのか？:: 
* Enum クックブック:: 
* EnumType のサブクラスを作る:: 

派生列挙型

* IntEnum:: 
* StrEnum:: 
* IntFlag:: 
* Flag:: 
* その他: その他<6>. 

When to use __new__() vs. __init__()

* 細かい点:: 

細かい点

* __dunder__ 名のサポート: __dunder__ 名のサポート<2>. 
* _sunder_ 名のサポート: _sunder_ 名のサポート<2>. 
* _Private__names:: 
* Enum メンバー型:: 
* Creating members that are mixed with other data types:: 
* Enum クラスとメンバーの真偽値:: 
* メソッド付きの Enum クラス:: 
* Flag のメンバーの組み合わせ:: 
* Flag and IntFlag minutia:: 

EnumとFlagはどう違うのか？

* Enum クラス:: 
* Flag クラス:: 
* Enum メンバー (インスタンス): Enum メンバー インスタンス. 
* Flag メンバー:: 

Enum クックブック

* 値の省略:: 
* OrderedEnum:: 
* DuplicateFreeEnum:: 
* MultiValueEnum:: 
* Planet:: 
* TimePeriod:: 

値の省略

* auto を使う:: 
* object を使う:: 
* 解説文字列を使う:: 
* Using a custom __new__(): Using a custom __new__. 

関数型プログラミング HOWTO

* はじめに: はじめに<15>. 
* イテレータ (iterator): イテレータ iterator<2>. 
* ジェネレータ式とリスト内包表記:: 
* ジェネレータ (generator): ジェネレータ generator<2>. 
* 組み込み関数 (built-in function): 組み込み関数 built-in function<2>. 
* itertools モジュール:: 
* functools モジュール:: 
* 小さな関数とラムダ式:: 
* 更新履歴と謝辞:: 
* 参考資料: 参考資料<2>. 

はじめに

* 形式的証明可能性:: 
* モジュラー性:: 
* デバッグやテストの簡単さ:: 
* 結合性:: 

イテレータ (iterator)

* イテレータ対応のデータ型:: 

ジェネレータ (generator)

* ジェネレータに値を渡す:: 

itertools モジュール

* 新しいイテレータを作る:: 
* 要素に対して関数を呼ぶ:: 
* 要素を選択する:: 
* 組合せ関数:: 
* 要素をグループ分けする:: 

functools モジュール

* operator モジュール:: 

参考資料

* 一般論:: 
* Python 特有の話:: 
* Python 文書:: 

Logging HOWTO

* 基本 logging チュートリアル:: 
* 上級ロギングチュートリアル:: 
* ロギングレベル: ロギングレベル<2>. 
* 便利なハンドラ:: 
* ログ記録中に発生する例外:: 
* 任意のオブジェクトをメッセージに使用する:: 
* 最適化: 最適化<19>. 
* その他のリソース:: 

基本 logging チュートリアル

* logging を使うとき:: 
* 簡単な例: 簡単な例<2>. 
* ファイルへの logging:: 
* 変数データのロギング:: 
* 表示されるメッセージのフォーマットの変更:: 
* メッセージ内での日付と時刻の表示:: 
* 次のステップ:: 

上級ロギングチュートリアル

* Logging Flow:: 
* ロガー:: 
* ハンドラ:: 
* フォーマッタ:: 
* ロギングの環境設定:: 
* 環境設定が与えられないとどうなるか:: 
* ライブラリのためのロギングの設定:: 

ロギングレベル

* カスタムレベル:: 

Logging クックブック

* 複数のモジュールで logging を使う:: 
* 複数のスレッドからのロギング:: 
* 複数の handler と formatter:: 
* 複数の出力先にログを出力する:: 
* ログレベルのカスタム処理:: 
* 設定サーバの例:: 
* ブロックする handler を扱う:: 
* ネットワーク越しの logging イベントの送受信:: 
* コンテキスト情報をログ記録出力に付加する:: 
* contextvars の利用:: 
* ハンドラ内でのコンテキスト情報の付与:: 
* 複数のプロセスからの単一ファイルへのログ記録:: 
* ファイルをローテートする:: 
* 別の format スタイルを利用する:: 
* LogRecord のカスタマイズ:: 
* Subclassing QueueHandler and QueueListener- a ZeroMQ example:: 
* Subclassing QueueHandler and QueueListener- a pynng example:: 
* 辞書ベースで構成する例:: 
* rotator と namer を使ってログローテートをカスタマイズする:: 
* より手の込んだ multiprocessing の例:: 
* SysLogHandler に送るメッセージに BOM を挿入する:: 
* 構造化ログを実装する:: 
* handler を dictConfig() を使ってカスタマイズする: handler を dictConfig を使ってカスタマイズする. 
* 固有の書式化スタイルをアプリケーション全体で使う:: 
* filter を dictConfig() を使ってカスタマイズする: filter を dictConfig を使ってカスタマイズする. 
* 例外の書式化をカスタマイズする:: 
* ロギングメッセージを喋る:: 
* ロギングメッセージをバッファリングし、条件に従って出力する:: 
* バッファリングしながらロギングメッセージを email で送信する:: 
* 設定によって時刻を UTC(GMT) で書式化する: 設定によって時刻を UTC GMT で書式化する. 
* ロギングの選択にコンテキストマネージャを使う:: 
* CLIアプリケーションスターターテンプレート:: 
* Qt GUIのログ出力:: 
* RFC5424 をサポートする syslog へのロギング:: 
* ロガーを出力ストリームのように取り扱う方法:: 
* How to uniformly handle newlines in logging output:: 
* 避けるべきパターン:: 
* その他のリソース: その他のリソース<2>. 

ネットワーク越しの logging イベントの送受信

* 作成中のロギングソケットのリスナーを実行する:: 

コンテキスト情報をログ記録出力に付加する

* LoggerAdapter を使ったコンテキスト情報の伝達:: 
* Filter を使ったコンテキスト情報の伝達:: 

LoggerAdapter を使ったコンテキスト情報の伝達

* コンテキスト情報を渡すために dict 以外のオブジェクトを使う:: 

複数のプロセスからの単一ファイルへのログ記録

* concurrent.futures.ProcessPoolExecutorの利用: concurrent futures ProcessPoolExecutorの利用. 
* Gunicorn と uWSGI を用いた Web アプリケーションのデプロイ:: 

Subclassing QueueHandler and QueueListener- a ZeroMQ example

* Subclass QueueHandler:: 
* Subclass QueueListener:: 

Subclassing QueueHandler and QueueListener- a pynng example

* Subclass QueueListener: Subclass QueueListener<2>. 
* Subclass QueueHandler: Subclass QueueHandler<2>. 

固有の書式化スタイルをアプリケーション全体で使う

* LogRecord ファクトリを使う:: 
* カスタムなメッセージオブジェクトを使う:: 

避けるべきパターン

* 同じログファイルを何度も開く:: 
* ロガーをクラスの属性にするか、パラメータで渡す:: 
* ライブラリ内でロガーに NullHandler 以外のハンドラーを追加する:: 
* 大量のロガーを作成する:: 

正規表現 HOWTO

* はじめに: はじめに<16>. 
* 単純なパターン:: 
* 正規表現を使う:: 
* パターンの能力をさらに:: 
* 文字列を変更する:: 
* よくある問題:: 
* フィードバック:: 

単純なパターン

* 文字のマッチング:: 
* 繰り返し:: 

正規表現を使う

* 正規表現をコンパイルする:: 
* バックスラッシュ感染症:: 
* マッチの実行:: 
* モジュールレベルの関数: モジュールレベルの関数<3>. 
* コンパイルフラグ:: 

パターンの能力をさらに

* さらなる特殊文字:: 
* グルーピング:: 
* 取り出さないグループと名前つきグループ:: 
* 先読みアサーション (Lookahead Assertions): 先読みアサーション Lookahead Assertions. 

文字列を変更する

* 文字列の分割:: 
* 検索と置換: 検索と置換<2>. 

よくある問題

* 文字列メソッドを利用する:: 
* match() 対 search(): match 対 search. 
* 貪欲 (greedy) 対非貪欲 (non-greedy): 貪欲 greedy 対非貪欲 non-greedy. 
* re.VERBOSE の利用: re VERBOSE の利用. 

ソケットプログラミング HOWTO

* ソケット:: 
* ソケットの作成: ソケットの作成<3>. 
* ソケットの利用:: 
* 切断:: 
* ノンブロッキングソケット:: 

ソケット

* 歴史:: 

ソケットの作成

* IPC:: 

ソケットの利用

* バイナリデータ:: 

切断

* ソケットが死ぬと:: 

ソートのテクニック

* ソートの基本:: 
* Key 関数:: 
* operator モジュールの関数や partial 関数による評価:: 
* 昇順と降順:: 
* ソートの安定性と複合的なソート:: 
* デコレート - ソート - アンデコレート (DSU): デコレート - ソート - アンデコレート DSU. 
* 比較関数:: 
* Strategies For Unorderable Types and Values:: 
* 残りのはしばし: 残りのはしばし<2>. 
* 部分的なソート:: 

Unicode HOWTO

* Unicode 入門:: 
* Python の Unicode サポート:: 
* Unicode データを読み書きする:: 
* 謝辞: 謝辞<10>. 

Unicode 入門

* 定義:: 
* エンコーディング: エンコーディング<3>. 
* 参考資料: 参考資料<3>. 

Python の Unicode サポート

* 文字列型:: 
* バイト列への変換:: 
* Python ソースコード内の Unicode リテラル:: 
* Unicode プロパティ:: 
* Comparing Strings:: 
* Unicode 正規表現:: 
* 参考資料: 参考資料<4>. 

Unicode データを読み書きする

* Unicode ファイル名:: 
* Unicode 対応のプログラムを書くための Tips:: 
* 参考資料: 参考資料<5>. 

Unicode 対応のプログラムを書くための Tips

* ファイルエンコーディングの変換:: 
* 不明なエンコーディングのファイル:: 

urllib パッケージを使ってインターネット上のリソースを取得するには

* はじめに: はじめに<17>. 
* URL を取得する:: 
* 例外を処理する: 例外を処理する<2>. 
* info と geturl:: 
* Openers と Handlers:: 
* Basic 認証:: 
* プロキシ:: 
* ソケットとレイヤー:: 
* 脚注:: 

URL を取得する

* データ:: 
* ヘッダ:: 

例外を処理する

* URLError:: 
* HTTPError:: 
* エラーをラップする:: 

HTTPError

* エラーコード:: 

エラーをラップする

* その1:: 
* その2:: 

ipaddressモジュールの紹介

* アドレス/ネットワーク/インターフェースオブジェクトの作成:: 
* アドレス/ネットワーク/インターフェースオブジェクト:: 
* アドレスのリストとしてのネットワーク:: 
* 比較: 比較<4>. 
* 他のモジュールでIPアドレスを使用する:: 
* インスタンスの生成に失敗した場合にさらに詳細を取得する:: 

アドレス/ネットワーク/インターフェースオブジェクトの作成

* IPバージョンについての注意:: 
* IPホストアドレス:: 
* ネットワークを定義する:: 
* ホストインターフェース:: 

DTrace と SystemTap で CPython を測定する

* 静的マーカーの有効化:: 
* 静的 DTrace プローブ:: 
* 静的 SystemTap マーカー:: 
* 利用可能な静的マーカー:: 
* SystemTap Tapset:: 
* 使用例: 使用例<58>. 

Python support for the Linux perf profiler

* How to enable perf profiling support:: 
* How to obtain the best results:: 
* How to work without frame pointers:: 

Annotations Best Practices

* Accessing The Annotations Dict Of An Object In Python 3.10 And Newer: Accessing The Annotations Dict Of An Object In Python 3 10 And Newer. 
* Accessing The Annotations Dict Of An Object In Python 3.9 And Older: Accessing The Annotations Dict Of An Object In Python 3 9 And Older. 
* Manually Un-Stringizing Stringized Annotations:: 
* Best Practices For __annotations__ In Any Python Version:: 
* __annotations__ Quirks:: 

拡張モジュールを分離する

* Who should read this:: 
* 背景: 背景<2>. 
* Making Modules Safe with Multiple Interpreters:: 
* Heap Types: Heap Types<2>. 
* 取り掛かり中の問題:: 

背景

* Enter Per-Module State:: 
* Isolated Module Objects:: 
* Surprising Edge Cases:: 

Making Modules Safe with Multiple Interpreters

* Managing Global State:: 
* Managing Per-Module State:: 
* Opt-Out; Limiting to One Module Object per Process: Opt-Out Limiting to One Module Object per Process. 
* Module State Access from Functions:: 

Heap Types

* Changing Static Types to Heap Types:: 
* Defining Heap Types:: 
* Garbage-Collection Protocol:: 
* Module State Access from Classes:: 
* Module State Access from Regular Methods:: 
* Module State Access from Slot Methods@comma{} Getters and Setters: Module State Access from Slot Methods Getters and Setters. 
* Lifetime of the Module State:: 

Garbage-Collection Protocol

* tp_traverse in Python 3.8 and lower: tp_traverse in Python 3 8 and lower. 
* Delegating tp_traverse:: 
* Defining tp_dealloc:: 
* Not overriding tp_free:: 
* Avoiding PyObject_New:: 

取り掛かり中の問題

* クラスごとのスコープ:: 
* Lossless Conversion to Heap Types:: 

timer file descriptor HOWTO

* 使用例: 使用例<59>. 

The Python 2.3 Method Resolution Order

* The beginning:: 
* The C3 Method Resolution Order:: 
* 使用例: 使用例<60>. 
* Bad Method Resolution Orders:: 
* The end:: 
* Resources:: 

Python support for free threading

* Installation: Installation<2>. 
* Identifying free-threaded Python:: 
* The global interpreter lock in free-threaded Python:: 
* Thread safety:: 
* Known limitations:: 
* Behavioral changes:: 

Known limitations

* Immortalization:: 
* フレーム (frame) オブジェクト: フレーム frame オブジェクト<3>. 
* イテレータ (iterator): イテレータ iterator<3>. 
* Single-threaded performance:: 

Behavioral changes

* Context variables:: 
* Warning filters:: 

C API Extension Support for Free Threading

* Identifying the Free-Threaded Build in C:: 
* Module Initialization:: 
* General API Guidelines:: 
* Borrowed References:: 
* Memory Allocation APIs:: 
* Thread State and GIL APIs:: 
* Protecting Internal Extension State:: 
* Critical Sections:: 
* Building Extensions for the Free-Threaded Build:: 

Module Initialization

* Multi-Phase Initialization:: 
* Single-Phase Initialization:: 

General API Guidelines

* Container Thread Safety:: 

Container Thread Safety

* PyDict_Next:: 

Critical Sections

* What Are Critical Sections?:: 
* Using Critical Sections:: 
* How Critical Sections Work:: 
* Deadlock Avoidance:: 
* Important Considerations:: 

Building Extensions for the Free-Threaded Build

* Limited C API and Stable ABI:: 
* Windows: Windows<85>. 

Remote debugging attachment protocol

* Disabling remote debugging:: 

Python よくある質問

* 一般 Python FAQ:: 
* プログラミング FAQ:: 
* デザインと歴史 FAQ:: 
* ライブラリと拡張 FAQ:: 
* 拡張と埋め込み FAQ:: 
* Windows 上の Python FAQ:: 
* グラフィックユーザインターフェース FAQ:: 
* "なぜ Python が私のコンピュータにインストールされているのですか？" FAQ:: 

一般 Python FAQ

* 一般情報:: 
* 現実世界での Python:: 

一般情報

* Python とは何ですか？:: 
* Python Software Foundation とは何ですか？:: 
* 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 は初心者プログラマに向いている言語ですか？:: 

プログラミング FAQ

* 一般的な質問:: 
* コア言語:: 
* 数と文字列:: 
* 性能: 性能<4>. 
* シーケンス(タプル/リスト): シーケンス タプル/リスト. 
* オブジェクト:: 
* モジュール: モジュール<5>. 

一般的な質問

* ブレークポイントやシングルステップ実行などを備えたソースコードレベルデバッガはありますか？:: 
* バグの発見や静的解析に役立つツールはありますか？:: 
* どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？:: 
* Python プログラムのためのコーディングスタンダードやスタイルガイドはありますか？:: 

コア言語

* なぜ変数に値があるのに UnboundLocalError が出るのですか？:: 
* Python のローカルとグローバル変数のルールは何ですか？:: 
* ループの中で異なる値で定義されたラムダ式が、同じ値を返すのはなぜですか？:: 
* グローバル変数をモジュール間で共有するにはどうしたらいいですか？:: 
* モジュールで import を使う際の「ベストプラクティス」は何ですか？:: 
* なぜオブジェクト間でデフォルト値が共有されるのですか？:: 
* オプションパラメータやキーワードパラメータを関数から関数へ渡すにはどうしたらいいですか？:: 
* 実引数と仮引数の違いは何ですか?:: 
* なぜ list 'y' を変更すると list 'x' も変更されるのですか?:: 
* 出力引数のある関数 (参照渡し) はどのように書きますか？: 出力引数のある関数 参照渡し はどのように書きますか？. 
* Python で高次関数はどのようにつくりますか？:: 
* Python のオブジェクトはどのようにコピーしますか？:: 
* オブジェクトのメソッドや属性はどのように見つけますか？:: 
* コードはどのようにオブジェクトの名前を見つけるのですか？:: 
* カンマ演算子はなぜ優先されるのですか？:: 
* C の "?;" 三項演算子と等価なものはありますか？: C の "? " 三項演算子と等価なものはありますか？. 
* Python で解し難いワンライナーを書くことはできますか？:: 
* 関数の引数リストにあるスラッシュ (/) は何を意味しますか？: 関数の引数リストにあるスラッシュ / は何を意味しますか？. 

数と文字列

* 十六進数や八進数を指定するにはどうしたらいいですか？:: 
* なぜ -22 // 10 は -3 を返すのですか？:: 
* どうすれば SyntaxError を起こさずに整数リテラルの属性を得られますか？:: 
* 文字列を数に変換するにはどうしたらいいですか？:: 
* 数を文字列に変換するにはどうしたらいいですか？:: 
* 文字列をインプレースに変更するにはどうしたらいいですか？:: 
* 関数やメソッドを呼ぶのに文字列を使うにはどうしたらいいですか？:: 
* Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?: Is there an equivalent to Perl's chomp for removing trailing newlines from strings?. 
* Is there a scanf() or sscanf() equivalent?: Is there a scanf or sscanf equivalent?. 
* What does UnicodeDecodeError or UnicodeEncodeError error mean?:: 
* raw string を奇数個のバックスラッシュで終えることはできますか？:: 

性能

* プログラムが遅すぎます。どうしたら速くなりますか？:: 
* 多くの文字列を結合するのに最も効率的な方法は何ですか？:: 

シーケンス(タプル/リスト)

* タプル、リスト間の変更はどのようにするのですか？:: 
* 負の添え字は何ですか？:: 
* シーケンスを逆順にイテレートするにはどうしたらいいですか？:: 
* リストから重複を取り除くにはどうしますか？:: 
* How do you remove multiple items from a list?:: 
* Python で配列を作るにはどうしますか？:: 
* 多次元のリストを作るにはどうしますか？:: 
* オブジェクトのシーケンスにメソッドや関数を適用するにはどうしますか？:: 
* なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?:: 
* 複雑なソートがしたいのですが、Python でシュワルツ変換はできますか？:: 
* リストを別のリストの値によってソートするにはどうしますか？:: 

オブジェクト

* クラスとは何ですか？:: 
* メソッドとは何ですか？:: 
* self とは何ですか？:: 
* あるオブジェクトが、与えられたクラスやそのサブクラスのインスタンスであるかを調べるにはどうしますか？:: 
* 委譲とは何ですか？:: 
* 基底クラスで定義されたメソッドを、そのクラスを継承した派生クラスから呼び出すにはどうしますか？:: 
* 基底クラスの名前を変えやすいコードを書くにはどうしますか？:: 
* 静的なクラスデータや静的なクラスメソッドを作るにはどうしますか？:: 
* Python でコンストラクタ(やメソッド)をオーバーロードするにはどうしたらいいですか？: Python でコンストラクタ やメソッド をオーバーロードするにはどうしたらいいですか？. 
* __spam を使おうとしたら _SomeClassName__spam からエラーがでました。:: 
* クラスに __del__ メソッドを定義しているのですが、オブジェクトを削除したときに呼ばれません。:: 
* 与えられたクラスのすべてのインスタンスのリストを得るにはどうしますか？:: 
* なぜ id() の結果は一意でないように見えるのですか?: なぜ id の結果は一意でないように見えるのですか?. 
* いつ is 演算子での同一性テストが頼れますか？:: 
* どうすればサブクラスはイミュータブルなインスタンスに格納されたデータを制御できますか？:: 
* メソッド呼び出しをキャッシュするには どうしたらいいですか？:: 

モジュール

* .pyc ファイルを作るにはどうしますか？: pyc ファイルを作るにはどうしますか？. 
* 現在のモジュール名を知るにはどうしますか？:: 
* 相互にインポートしあうモジュールを作るにはどうしたらいいですか？:: 
* __import__('x.y.z') は <module 'x'> を返しますが、z を得るためにはどうしますか？: __import__ 'x y z' は <module 'x'> を返しますが、z を得るためにはどうしますか？. 
* インポートされたモジュールを編集してから再インポートしましたが、変化が現れません。なぜですか？:: 

デザインと歴史 FAQ

* Python はなぜ文のグループ化にインデントを使うのですか？:: 
* なぜ単純な算術演算が奇妙な結果になるのですか？:: 
* なぜ浮動小数点数の計算はこんなに不正確なんですか？:: 
* なぜ Python の文字列はイミュータブルなのですか？:: 
* なぜメソッドの定義や呼び出しにおいて 'self' を明示しなければならないのですか？:: 
* 式中で代入ができないのはなぜですか？:: 
* Python にメソッドを使う機能 (list.index() 等) と関数を使う機能 (len(list) 等) があるのはなぜですか？: Python にメソッドを使う機能 list index 等 と関数を使う機能 len list 等 があるのはなぜですか？. 
* join() がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？: join がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？. 
* 例外はどれくらい速いのですか？:: 
* Python に switch や case 文がないのはなぜですか？:: 
* OS 特有のスレッド実装に依らずにインタプリタでスレッドをエミュレートすることはできないのですか？:: 
* なぜラムダ式は文を含むことができないのですか?:: 
* Python は C やその他の言語のように機械語にコンパイルできますか？:: 
* Python はメモリをどのように管理するのですか？:: 
* CPython はなぜ伝統的なガベージコレクションスキームを使わないのですか？:: 
* なぜ CPython の終了時にすべてのメモリが解放されるわけではないのですか？:: 
* なぜタプルとリストという別のデータ型が用意されているのですか？:: 
* CPythonでリストはどのように実装されているのですか？:: 
* CPythonで辞書はどのように実装されていますか？:: 
* なぜ辞書のキーはイミュータブルでなくてはならないのですか？:: 
* なぜ list.sort() はソートされたリストを返さないのですか？: なぜ list sort はソートされたリストを返さないのですか？. 
* Python ではどのようにインターフェース仕様を特定し適用するのですか？:: 
* なぜ goto が無いのですか？:: 
* なぜ raw 文字列 (r-strings) はバックスラッシュで終わってはいけないのですか？: なぜ raw 文字列 r-strings はバックスラッシュで終わってはいけないのですか？. 
* 属性の代入に "with" 文が使えないのはなぜですか？:: 
* なぜジェネレータは with 文をサポートしないのですか？:: 
* if/while/def/class 文にコロンが必要なのはなぜですか？:: 
* なぜ Python ではリストやタプルの最後にカンマがあっても良いのですか？:: 

ライブラリと拡張 FAQ

* ライブラリ一般の質問:: 
* よくある作業:: 
* スレッド:: 
* 入力と出力: 入力と出力<2>. 
* ネットワーク/インターネットプログラミング:: 
* データベース:: 
* 数学と数:: 

ライブラリ一般の質問

* 作業 X を行うためのモジュールやアプリケーションを探すにはどうしますか？:: 
* math.py (socket.py@comma{} regex.py@comma{} etc.) のソースファイルはどこにありますか？: math py socket py regex py etc のソースファイルはどこにありますか？. 
* Python のスクリプトを Unix で実行可能にするにはどうしますか？:: 
* Python には curses/termcap パッケージはありますか？:: 
* Python には C の onexit() に相当するものはありますか？: Python には C の onexit に相当するものはありますか？. 
* シグナルハンドラが動かないのですがなぜですか？:: 

よくある作業

* Python のプログラムやコンポーネントをテストするにはどうしますか？:: 
* Python のドキュメント文字列からドキュメントを生成するにはどうしますか？:: 
* 一度に一つの押鍵を取得するにはどうしますか？:: 

スレッド

* スレッドを使ったプログラムを書くにはどうしますか？:: 
* スレッドが一つも実行されていないようです。なぜですか？:: 
* たくさんのワーカースレッドに作業を割り振るにはどうしますか？:: 
* グローバルな値のどんな種類の変更がスレッドセーフになるのですか？:: 
* グローバルインタプリタロック (Global Interpreter Lock) を取り除くことはできないのですか？: グローバルインタプリタロック Global Interpreter Lock を取り除くことはできないのですか？. 

入力と出力

* ファイルを削除するにはどうしますか？ (その他、ファイルに関する質問...): ファイルを削除するにはどうしますか？ その他、ファイルに関する質問. 
* ファイルをコピーするにはどうしますか？:: 
* バイナリデータを読み書きするにはどうしますか？:: 
* os.popen() によって作られたパイプで os.read() が使われていないようです。なぜですか？: os popen によって作られたパイプで os read が使われていないようです。なぜですか？. 
* シリアル (RS232) ポートにアクセスするにはどうしますか？: シリアル RS232 ポートにアクセスするにはどうしますか？. 
* sys.stdout (stdin@comma{} stderr) を閉じようとしても実際に閉じられないのはなぜですか？: sys stdout stdin stderr を閉じようとしても実際に閉じられないのはなぜですか？. 

ネットワーク/インターネットプログラミング

* Python の WWW ツールには何がありますか？:: 
* どのモジュールが HTML の生成の役に立ちますか？:: 
* Python のスクリプトからメールを送るにはどうしますか？:: 
* ソケットの connect() メソッドでブロッキングされなくするにはどうしますか？: ソケットの connect メソッドでブロッキングされなくするにはどうしますか？. 

データベース

* Python にはデータベースパッケージへのインターフェースはありますか？:: 
* Python で永続的なオブジェクトを実装するにはどうしますか？:: 

数学と数

* Python で乱数を生成するにはどうしますか？:: 

拡張と埋め込み FAQ

* 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++ へインターフェースするにはどうしますか？:: 
* セットアップファイルでモジュールを追加しようとしたらメイクに失敗しました。なぜですか？:: 
* 拡張をデバッグするにはどうしますか？:: 
* Linux システムで Python モジュールをコンパイルしたいのですが、見つからないファイルがあります。なぜですか？:: 
* "不完全 (incomplete) な入力" を "不適切 (invalid) な入力" から区別するにはどうしますか？: "不完全 incomplete な入力" を "不適切 invalid な入力" から区別するにはどうしますか？. 
* 未定義の g++ シンボル __builtin_new や __pure_virtual を見つけるにはどうしますか？:: 
* メソッドのいくつかは C で、その他は Python で実装されたオブジェクトクラスを (継承などで) 作ることはできますか？: メソッドのいくつかは C で、その他は Python で実装されたオブジェクトクラスを 継承などで 作ることはできますか？. 

Windows 上の Python FAQ

* Python プログラムを Windows で動かすにはどうしますか？:: 
* Python スクリプトを実行可能にするにはどうしますか？:: 
* Python の起動に時間がかかることがあるのはなぜですか？:: 
* どうすれば Python スクリプトを EXE に出来ますか?:: 
* *.pyd ファイルは DLL と同じですか？: * pyd ファイルは DLL と同じですか？. 
* Python を Windows アプリケーションに埋め込むにはどうしたらいいですか？:: 
* エディタが Python ソースにタブを勝手に挿入しないようにするにはどうしますか？:: 
* ブロックすることなく押鍵を検出するにはどうしますか？:: 
* missing api-ms-win-crt-runtime-l1-1-0.dll エラーを解決するにはどうしますか？: missing api-ms-win-crt-runtime-l1-1-0 dll エラーを解決するにはどうしますか？. 

グラフィックユーザインターフェース FAQ

* 一般的な GUI の質問:: 
* Python の GUI ツールキットには何がありますか？:: 
* Tkinter の質問:: 

Tkinter の質問

* Tkinter アプリケーションを凍結するにはどうしますか？:: 
* I/O を待つ間に扱われる Tk イベントを作れますか？:: 
* Tkinter で働くキーバインディングが得られません。なぜですか？:: 

"なぜ Python が私のコンピュータにインストールされているのですか？" FAQ

* Python とは何ですか？: Python とは何ですか？<2>. 
* なぜ Python が私のマシンにインストールされているのですか？:: 
* Python を削除してもいいですか？:: 

非推奨

* Pending removal in Python 3.15: Pending removal in Python 3 15<7>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<7>. 
* Pending removal in Python 3.17: Pending removal in Python 3 17<4>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<5>. 
* Pending removal in Python 3.19: Pending removal in Python 3 19<3>. 
* Pending removal in future versions: Pending removal in future versions<7>. 
* C API deprecations:: 

C API deprecations

* Pending removal in Python 3.15: Pending removal in Python 3 15<8>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<6>. 
* Pending removal in future versions: Pending removal in future versions<8>. 

このドキュメントについて

* Pythonドキュメントへの貢献者:: 

バグへの対処

* ドキュメントの不備:: 
* Python の課題管理システムを使う:: 
* Python への貢献をはじめる:: 

歴史とライセンス

* Python の歴史:: 
* Terms and conditions for accessing or otherwise using Python:: 
* Licenses and Acknowledgements for Incorporated Software:: 

Terms and conditions for accessing or otherwise using Python

* PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2:: 
* BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0: BEOPEN COM LICENSE AGREEMENT FOR PYTHON 2 0. 
* CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1: CNRI LICENSE AGREEMENT FOR PYTHON 1 6 1. 
* CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2: CWI LICENSE AGREEMENT FOR PYTHON 0 9 0 THROUGH 1 2. 
* ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION:: 

Licenses and Acknowledgements for Incorporated Software

* Mersenne Twister:: 
* ソケット: ソケット<2>. 
* Asynchronous socket services:: 
* Cookie management:: 
* Execution tracing:: 
* UUencode and UUdecode functions:: 
* XML Remote Procedure Calls:: 
* test_epoll:: 
* Select kqueue:: 
* SipHash24:: 
* strtod と dtoa:: 
* OpenSSL: OpenSSL<2>. 
* expat:: 
* libffi:: 
* zlib: zlib<4>. 
* cfuhash:: 
* libmpdec:: 
* W3C C14N test suite:: 
* mimalloc:: 
* asyncio: asyncio<15>. 
* Global Unbounded Sequences (GUS): Global Unbounded Sequences GUS. 
* Zstandard bindings:: 

@end detailmenu
@end menu

@node What's New in Python,Python チュートリアル,Top,Top
@anchor{whatsnew/index doc}@anchor{13c}@anchor{whatsnew/index python-documentation-contents}@anchor{13d}@anchor{whatsnew/index what-s-new-in-python}@anchor{13e}@anchor{whatsnew/index whatsnew-index}@anchor{13f}
@chapter What's New in Python


この"What's New in Python"という一連の文書はPythonのメジャーバージョンにおける最も重要な変更点を紹介します。新しくリリースされた後でも最新の状態であり続けたい人にとって必読のものです。

@menu
* What's new in Python 3.14: What's new in Python 3 14. 
* What's New In Python 3.13: What's New In Python 3 13. 
* What's New In Python 3.12: What's New In Python 3 12. 
* What's New In Python 3.11: What's New In Python 3 11. 
* What's New In Python 3.10: What's New In Python 3 10. 
* What's New In Python 3.9: What's New In Python 3 9. 
* What's New In Python 3.8: What's New In Python 3 8. 
* What's New In Python 3.7: What's New In Python 3 7. 
* What's New In Python 3.6: What's New In Python 3 6. 
* What's New In Python 3.5: What's New In Python 3 5. 
* What's New In Python 3.4: What's New In Python 3 4. 
* What's New In Python 3.3: What's New In Python 3 3. 
* What's New In Python 3.2: What's New In Python 3 2. 
* What's New In Python 3.1: What's New In Python 3 1. 
* What's New In Python 3.0: What's New In Python 3 0. 
* What's New in Python 2.7: What's New in Python 2 7. 
* What's New in Python 2.6: What's New in Python 2 6. 
* What's New in Python 2.5: What's New in Python 2 5. 
* What's New in Python 2.4: What's New in Python 2 4. 
* What's New in Python 2.3: What's New in Python 2 3. 
* What's New in Python 2.2: What's New in Python 2 2. 
* What's New in Python 2.1: What's New in Python 2 1. 
* What's New in Python 2.0: What's New in Python 2 0. 
* 変更履歴:: 

@end menu

@node What's new in Python 3 14,What's New In Python 3 13,,What's New in Python
@anchor{whatsnew/3 14 doc}@anchor{140}@anchor{whatsnew/3 14 what-s-new-in-python-3-14}@anchor{141}
@section What's new in Python 3.14


@*エディタ: 
Adam Turner と Hugo van Kemenade


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the issue number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :gh:`12345`.)
@c 
@c This saves the maintainer the effort of going through the VCS log
@c when researching a change.

この記事では Python 3.13 と比較した Python 3.14 の新機能を解説します。Python 3.14 は2025年10月7日にリリースされました。全詳細については @ref{142,,変更履歴} をご覧ください。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 745
PEP 745@footnote{https://peps.python.org/pep-0745/} -- Python 3.14 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト. リリースハイライト
* 新しい機能:: 
* Other language changes:: 
* 新しいモジュール:: 
* Improved modules:: 
* 最適化:: 
* 削除:: 
* 非推奨:: 
* CPython バイトコードの変更:: 
* C API changes:: 
* Build changes:: 
* Porting to Python 3.14: Porting to Python 3 14. 
* Notable changes in 3.14.1: Notable changes in 3 14 1. 

@end menu

@node 概要 -- リリースハイライト,新しい機能,,What's new in Python 3 14
@anchor{whatsnew/3 14 summary-release-highlights}@anchor{143}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.14.
@c Brevity is key.

Python 3.14 はプログラミング言語 Python の最新のリリースです。言語自体への変更や、実装、標準ライブラリのアップデートが含まれます。一番大きな変更点は、新しい @ref{144,,テンプレート文字列リテラル}、@ref{145,,アノテーションの遅延評価}、標準ライブラリへの @ref{146,,subinterpreters} の追加です。

ライブラリの変更内容には @ref{147,,asyncio のイントロスペクション機能} の重要な改善、 新モジュール @ref{23,,compression.zstd} による @ref{148,,Zstandard のサポート} 、 REPL における構文ハイライトが、通常の非推奨化や削除、また利便性と正確性の向上に加えて含まれます。

本記事は、全ての新機能の仕様をを網羅的に説明する代わりに、分かりやすく概要を説明するものとなっています。詳細については @ref{149,,ライブラリリファレンス} や @ref{14a,,言語レファレンス} などを参照してください。各変更点の実装や設計の理由を網羅的に理解したい方は、該当の PEP を参照してください。ただし、 PEP は機能が実装されたあとは Python の最新バージョンに合わせて更新されないことが多いので注意してください。Python を以前のバージョンからアップグレードする際の注意点は @ref{14b,,Porting to Python 3.14} を参照してください。


__________________________________________________________________


@c PEP-sized items next.

インタプリタの改善:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} と 
@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/}: @ref{145,,アノテーションの遅延評価}

@item 
@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}: @ref{146,,標準ライブラリにおける複数インタープリタ}

@item 
@geindex Python Enhancement Proposals; PEP 750
PEP 750@footnote{https://peps.python.org/pep-0750/}: @ref{144,,テンプレート文字列}

@item 
@geindex Python Enhancement Proposals; PEP 758
PEP 758@footnote{https://peps.python.org/pep-0758/}: @ref{14c,,括弧を省略した except and except* 式を許可}

@item 
@geindex Python Enhancement Proposals; PEP 765
PEP 765@footnote{https://peps.python.org/pep-0765/}: @ref{14d,,finally ブロック内の制御フロー}

@item 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/}: @ref{14e,,CPython における安全な外部デバッガインターフェース}

@item 
@ref{14f,,新型のインタープリタ}

@item 
@ref{150,,フリースレッドモードの改善}

@item 
@ref{151,,エラーメッセージの改善}

@item 
@ref{152,,漸進的なガベージコレクション}
@end itemize

標準ライブラリーの顕著な改善


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 784
PEP 784@footnote{https://peps.python.org/pep-0784/}: @ref{148,,標準ライブラリでの Zstandard のサポート}

@item 
@ref{147,,Asyncio introspection capabilities}

@item 
@ref{153,,Concurrent safe warnings control}

@item 
@ref{154,,デフォルトの対話シェルでのシンタックスハイライトSyntax highlighting in the default interactive shell} と、複数の標準ライブラリのCLIでのカラー出力
@end itemize

C API の改善:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 741
PEP 741@footnote{https://peps.python.org/pep-0741/}: @ref{155,,Python configuration C API}
@end itemize

プラットフォームのサポート:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 776
PEP 776@footnote{https://peps.python.org/pep-0776/}: Emscripten が 
@geindex Python Enhancement Proposals; PEP 11#tier-3
tier 3@footnote{https://peps.python.org/pep-0011/#tier-3} として @ref{156,,公式にサポートされるプラットフォーム} となりました。
@end itemize

リリースの変更:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 779
PEP 779@footnote{https://peps.python.org/pep-0779/}: @ref{157,,フリースレッドな Python は公式にサポートされました}

@item 
@geindex Python Enhancement Proposals; PEP 761
PEP 761@footnote{https://peps.python.org/pep-0761/}: @ref{158,,公式のリリースについて、PGP 署名は廃止されました}

@item 
@ref{159,,Windows と macOS のバイナリリリースは、実験的なジャスト・イン・タイムコンパイラをサポートします}

@item 
@ref{156,,Android のためのバイナリリリースが提供されるようになりました}
@end itemize

@node 新しい機能,Other language changes,概要 -- リリースハイライト,What's new in Python 3 14
@anchor{whatsnew/3 14 new-features}@anchor{15a}
@subsection 新しい機能


@menu
* PEP 649 と PEP 749; アノテーションの遅延評価: PEP 649 と PEP 749 アノテーションの遅延評価. 
* PEP 734; Multiple interpreters in the standard library: PEP 734 Multiple interpreters in the standard library. 
* PEP 750; テンプレート文字列リテラル: PEP 750 テンプレート文字列リテラル. 
* PEP 768; Safe external debugger interface: PEP 768 Safe external debugger interface. 
* A new type of interpreter:: 
* Free-threaded mode improvements:: 
* エラーメッセージの改善:: 
* PEP 784; Zstandard support in the standard library: PEP 784 Zstandard support in the standard library. 
* Asyncio introspection capabilities:: 
* Concurrent safe warnings control:: 

@end menu

@node PEP 649 と PEP 749 アノテーションの遅延評価,PEP 734 Multiple interpreters in the standard library,,新しい機能
@anchor{whatsnew/3 14 pep-649-pep-749-deferred-evaluation-of-annotations}@anchor{15b}@anchor{whatsnew/3 14 whatsnew314-deferred-annotations}@anchor{145}
@subsubsection 
@geindex Python Enhancement Proposals; PEP 649
`PEP 649' と 
@geindex Python Enhancement Proposals; PEP 749
`PEP 749': アノテーションの遅延評価


The @ref{15c,,annotations} on functions, classes, and modules are no
longer evaluated eagerly. Instead, annotations are stored in special-purpose
@ref{15d,,annotate functions} and evaluated only when
necessary (except if @code{from __future__ import annotations} is used).

This change is designed to improve performance and usability of annotations
in Python in most circumstances. The runtime cost for defining annotations is
minimized, but it remains possible to introspect annotations at runtime.
It is no longer necessary to enclose annotations in strings if they
contain forward references.

The new @ref{6,,annotationlib} module provides tools for inspecting deferred
annotations. Annotations may be evaluated in the @ref{15e,,VALUE}
format (which evaluates annotations to runtime values, similar to the behavior in
earlier Python versions), the @ref{15f,,FORWARDREF} format
(which replaces undefined names with special markers), and the
@ref{160,,STRING} format (which returns annotations as strings).

This example shows how these formats behave:

@example
>>> from annotationlib import get_annotations, Format
>>> def func(arg: Undefined):
...     pass
>>> get_annotations(func, format=Format.VALUE)
Traceback (most recent call last):
  ...
NameError: name 'Undefined' is not defined
>>> get_annotations(func, format=Format.FORWARDREF)
@{'arg': ForwardRef('Undefined', owner=<function func at 0x...>)@}
>>> get_annotations(func, format=Format.STRING)
@{'arg': 'Undefined'@}
@end example

The @ref{161,,porting} section contains guidance
on changes that may be needed due to these changes, though in the majority of
cases, code will continue working as-is.

(Contributed by Jelle Zijlstra in 
@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/} and gh-119180@footnote{https://github.com/python/cpython/issues/119180};
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} was written by Larry Hastings.)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 649

@item PEP 649@footnote{https://peps.python.org/pep-0649/}

Deferred Evaluation Of Annotations Using Descriptors

@geindex Python Enhancement Proposals; PEP 749

@item PEP 749@footnote{https://peps.python.org/pep-0749/}

Implementing PEP 649
@end table


@node PEP 734 Multiple interpreters in the standard library,PEP 750 テンプレート文字列リテラル,PEP 649 と PEP 749 アノテーションの遅延評価,新しい機能
@anchor{whatsnew/3 14 pep-734-multiple-interpreters-in-the-standard-library}@anchor{162}@anchor{whatsnew/3 14 whatsnew314-multiple-interpreters}@anchor{146}
@subsubsection 
@geindex Python Enhancement Proposals; PEP 734
`PEP 734': Multiple interpreters in the standard library


The CPython runtime supports running multiple copies of Python in the
same process simultaneously and has done so for over 20 years.
Each of these separate copies is called an 'interpreter'.
However, the feature had been available only through
the @ref{163,,C-API}.

That limitation is removed in Python 3.14,
with the new @ref{25,,concurrent.interpreters} module.

There are at least two notable reasons why using multiple interpreters
has significant benefits:


@itemize *

@item 
they support a new (to Python), human-friendly concurrency model

@item 
true multi-core parallelism
@end itemize

For some use cases, concurrency in software improves efficiency and
can simplify design, at a high level.
At the same time, implementing and maintaining all but the simplest concurrency
is often a struggle for the human brain.
That especially applies to plain threads (for example, @ref{f3,,threading}),
where all memory is shared between all threads.

With multiple isolated interpreters, you can take advantage of a class
of concurrency models, like Communicating Sequential Processes (CSP)
or the actor model, that have found
success in other programming languages, like Smalltalk, Erlang,
Haskell, and Go. Think of multiple interpreters as threads
but with opt-in sharing.

Regarding multi-core parallelism: as of Python 3.12, interpreters
are now sufficiently isolated from one another to be used in parallel
(see 
@geindex Python Enhancement Proposals; PEP 684
PEP 684@footnote{https://peps.python.org/pep-0684/}). This unlocks a variety of CPU-intensive use cases
for Python that were limited by the @ref{164,,GIL}.

Using multiple interpreters is similar in many ways to
@ref{98,,multiprocessing}, in that they both provide isolated logical
"processes" that can run in parallel, with no sharing by default.
However, when using multiple interpreters, an application will use
fewer system resources and will operate more efficiently (since it
stays within the same process). Think of multiple interpreters as
having the isolation of processes with the efficiency of threads.

@c XXX Add an example or two.

@c XXX Link to the not-yet-added HOWTO doc.

While the feature has been around for decades, multiple interpreters
have not been used widely, due to low awareness and the lack of a
standard library module. Consequently, they currently have several
notable limitations, which are expected to improve significantly now
that the feature is going mainstream.

Current limitations:


@itemize *

@item 
starting each interpreter has not been optimized yet

@item 
each interpreter uses more memory than necessary
(work continues on extensive internal sharing between interpreters)

@item 
there aren't many options `yet' for truly sharing objects or other
data between interpreters (other than @ref{165,,memoryview})

@item 
many third-party extension modules on PyPI are not yet compatible
with multiple interpreters
(all standard library extension modules `are' compatible)

@item 
the approach to writing applications that use multiple isolated
interpreters is mostly unfamiliar to Python users, for now
@end itemize

The impact of these limitations will depend on future CPython
improvements, how interpreters are used, and what the community solves
through PyPI packages. Depending on the use case, the limitations may
not have much impact, so try it out!

Furthermore, future CPython releases will reduce or eliminate overhead
and provide utilities that are less appropriate on PyPI. In the
meantime, most of the limitations can also be addressed through
extension modules, meaning PyPI packages can fill any gap for 3.14, and
even back to 3.12 where interpreters were finally properly isolated and
stopped sharing the @ref{164,,GIL}. Likewise, libraries on PyPI are expected
to emerge for high-level abstractions on top of interpreters.

Regarding extension modules, work is in progress to update some PyPI
projects, as well as tools like Cython, pybind11, nanobind, and PyO3.
The steps for isolating an extension module are found at
@ref{166,,拡張モジュールを分離する}.
Isolating a module has a lot of overlap with what is required to support
@ref{150,,free-threading}, so the ongoing
work in the community in that area will help accelerate support
for multiple interpreters.

Also added in 3.14: @ref{167,,concurrent.futures.InterpreterPoolExecutor}.

(Contributed by Eric Snow in gh-134939@footnote{https://github.com/python/cpython/issues/134939}.)


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}


@node PEP 750 テンプレート文字列リテラル,PEP 768 Safe external debugger interface,PEP 734 Multiple interpreters in the standard library,新しい機能
@anchor{whatsnew/3 14 pep-750-template-string-literals}@anchor{168}@anchor{whatsnew/3 14 whatsnew314-template-string-literals}@anchor{144}
@subsubsection 
@geindex Python Enhancement Proposals; PEP 750
`PEP 750': テンプレート文字列リテラル


Template strings are a new mechanism for custom string processing.
They share the familiar syntax of f-strings but, unlike f-strings,
return an object representing the static and interpolated parts of
the string, instead of a simple @ref{169,,str}.

t-stringを書くには、プレフィックスとして @code{'f'} の代わりに @code{'t'} を使用します:

@example
>>> variety = 'Stilton'
>>> template = t'Try some @{variety@} cheese!'
>>> type(template)
<class 'string.templatelib.Template'>
@end example

@ref{16a,,Template} objects provide access to the static
and interpolated (in curly braces) parts of a string `before' they are combined.
Iterate over @code{Template} instances to access their parts in order:

@c variety = 'Stilton'
@c template = t'Try some {variety} cheese!'

@example
>>> list(template)
['Try some ', Interpolation('Stilton', 'variety', None, '@w{'}), ' cheese!']
@end example

It's easy to write (or call) code to process @code{Template} instances.
For example, here's a function that renders static parts lowercase and
@ref{16b,,Interpolation} instances uppercase:

@example
from string.templatelib import Interpolation

def lower_upper(template):
    """固定の箇所は小文字に、interpolationsは大文字に変換する"""
    parts = []
    for part in template:
        if isinstance(part, Interpolation):
            parts.append(str(part.value).upper())
        else:
            parts.append(part.lower())
    return '@w{'}.join(parts)

name = 'Wenslydale'
template = t'Mister @{name@}'
assert lower_upper(template) == 'mister WENSLYDALE'
@end example

Because @code{Template} instances distinguish between static strings and
interpolations at runtime, they can be useful for sanitising user input.
Writing a @code{html()} function that escapes user input in HTML is an exercise
left to the reader!
Template processing code can provide improved flexibility.
For instance, a more advanced @code{html()} function could accept
a @code{dict} of HTML attributes directly in the template:

@example
attributes = @{'src': 'limburger.jpg', 'alt': 'lovely cheese'@}
template = t'<img @{attributes@}>'
assert html(template) == '<img src="limburger.jpg" alt="lovely cheese" />'
@end example

Of course, template processing code does not need to return a string-like result.
An even `more' advanced @code{html()} could return a custom type representing
a DOM-like structure.

With t-strings in place, developers can write systems that sanitise SQL,
make safe shell operations, improve logging, tackle modern ideas in web
development (HTML, CSS, and so on), and implement lightweight custom business DSLs.

(Contributed by Jim Baker, Guido van Rossum, Paul Everitt, Koudai Aono,
Lysandros Nikolaou, Dave Peck, Adam Turner, Jelle Zijlstra, Bénédikt Tran,
and Pablo Galindo Salgado in gh-132661@footnote{https://github.com/python/cpython/issues/132661}.)


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 750
PEP 750@footnote{https://peps.python.org/pep-0750/}


@node PEP 768 Safe external debugger interface,A new type of interpreter,PEP 750 テンプレート文字列リテラル,新しい機能
@anchor{whatsnew/3 14 pep-768-safe-external-debugger-interface}@anchor{16c}@anchor{whatsnew/3 14 whatsnew314-remote-debugging}@anchor{14e}
@subsubsection 
@geindex Python Enhancement Proposals; PEP 768
`PEP 768': Safe external debugger interface


Python 3.14 introduces a zero-overhead debugging interface that allows
debuggers and profilers to safely attach to running Python processes
without stopping or restarting them.
This is a significant enhancement to Python's debugging capabilities,
meaning that unsafe alternatives are no longer required.

The new interface provides safe execution points for attaching debugger code
without modifying the interpreter's normal execution path
or adding any overhead at runtime.
Due to this, tools can now inspect and interact with Python applications
in real-time, which is a crucial capability for high-availability systems
and production environments.

For convenience, this interface is implemented in the @ref{16d,,sys.remote_exec()}
function. For example:

@example
import sys
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
    script_path = f.name
    f.write(f'import my_debugger; my_debugger.connect(@{os.getpid()@})')

# Execute in process with PID 1234
print('Behold! An offering:')
sys.remote_exec(1234, script_path)
@end example

This function allows sending Python code to be executed in a target process
at the next safe execution point.
However, tool authors can also implement the protocol directly as described
in the PEP, which details the underlying mechanisms used to safely attach to
running processes.

The debugging interface has been carefully designed with security in mind
and includes several mechanisms to control access:


@itemize *

@item 
A 
@geindex PYTHON_DISABLE_REMOTE_DEBUG
@geindex 環境変数; PYTHON_DISABLE_REMOTE_DEBUG
@ref{16e,,PYTHON_DISABLE_REMOTE_DEBUG} environment variable.

@item 
A @ref{16f,,-X disable-remote-debug} command-line option.

@item 
A @ref{170,,--without-remote-debug} configure flag to completely disable
the feature at build time.
@end itemize

(Contributed by Pablo Galindo Salgado, Matt Wozniski, and Ivona Stojanovic
in gh-131591@footnote{https://github.com/python/cpython/issues/131591}.)


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/}.


@node A new type of interpreter,Free-threaded mode improvements,PEP 768 Safe external debugger interface,新しい機能
@anchor{whatsnew/3 14 a-new-type-of-interpreter}@anchor{171}@anchor{whatsnew/3 14 whatsnew314-tail-call-interpreter}@anchor{14f}
@subsubsection A new type of interpreter


A new type of interpreter has been added to CPython.
It uses tail calls between small C functions that implement individual
Python opcodes, rather than one large C @code{case} statement.
For certain newer compilers, this interpreter provides
significantly better performance. Preliminary benchmarks suggest a geometric
mean of 3-5% faster on the standard @code{pyperformance} benchmark suite,
depending on platform and architecture.
The baseline is Python 3.14 built with Clang 19, without this new interpreter.

This interpreter currently only works with Clang 19 and newer
on x86-64 and AArch64 architectures.
However, a future release of GCC is expected to support this as well.

This feature is opt-in for now. Enabling profile-guided optimization is highly
recommendeded when using the new interpreter as it is the only configuration
that has been tested and validated for improved performance.
For further information, see @ref{172,,--with-tail-call-interp}.

@cartouche
@quotation 注釈 
This is not to be confused with tail call optimization@footnote{https://en.wikipedia.org/wiki/Tail_call} of Python
functions, which is currently not implemented in CPython.

This new interpreter type is an internal implementation detail of the CPython
interpreter.  It doesn't change the visible behavior of Python programs at
all.  It can improve their performance, but doesn't change anything else.
@end quotation
@end cartouche

(Contributed by Ken Jin in gh-128563@footnote{https://github.com/python/cpython/issues/128563}, with ideas on how to implement this
in CPython by Mark Shannon, Garrett Gu, Haoran Xu, and Josh Haberman.)

@node Free-threaded mode improvements,エラーメッセージの改善,A new type of interpreter,新しい機能
@anchor{whatsnew/3 14 free-threaded-mode-improvements}@anchor{173}@anchor{whatsnew/3 14 whatsnew314-free-threaded-cpython}@anchor{150}
@subsubsection Free-threaded mode improvements


CPython's free-threaded mode (
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}), initially added in 3.13,
has been significantly improved in Python 3.14.
The implementation described in PEP 703 has been finished, including C API
changes, and temporary workarounds in the interpreter were replaced with
more permanent solutions.
The specializing adaptive interpreter (
@geindex Python Enhancement Proposals; PEP 659
PEP 659@footnote{https://peps.python.org/pep-0659/}) is now enabled
in free-threaded mode, which along with many other optimizations
greatly improves its performance.
The performance penalty on single-threaded code in free-threaded mode
is now roughly 5-10%, depending on the platform and C compiler used.

From Python 3.14, when compiling extension modules for the free-threaded build of
CPython on Windows, the preprocessor variable @code{Py_GIL_DISABLED} now needs to
be specified by the build backend, as it will no longer be determined
automatically by the C compiler. For a running interpreter, the setting that
was used at compile time can be found using @ref{174,,sysconfig.get_config_var()}.

The new @ref{16f,,-X context_aware_warnings} flag controls if
@ref{153,,concurrent safe warnings control}
is enabled. The flag defaults to true for the free-threaded build
and false for the GIL-enabled build.

A new @ref{175,,thread_inherit_context} flag has been added,
which if enabled means that threads created with @ref{176,,threading.Thread}
start with a copy of the @ref{177,,Context()} of the caller of
@ref{178,,start()}.  Most significantly, this makes the warning
filtering context established by @ref{179,,catch_warnings} be
"inherited" by threads (or asyncio tasks) started within that context.  It also
affects other modules that use context variables, such as the @ref{3a,,decimal}
context manager.
This flag defaults to true for the free-threaded build and false for
the GIL-enabled build.

(Contributed by Sam Gross, Matt Page, Neil Schemenauer, Thomas Wouters,
Donghee Na, Kirill Podoprigora, Ken Jin, Itamar Oren, Brett Simmers,
Dino Viehland, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou, Kumar Aditya,
Edgar Margffoy, and many others.
Some of these contributors are employed by Meta, which has continued to provide
significant engineering resources to support this project.)

@node エラーメッセージの改善,PEP 784 Zstandard support in the standard library,Free-threaded mode improvements,新しい機能
@anchor{whatsnew/3 14 improved-error-messages}@anchor{17a}@anchor{whatsnew/3 14 whatsnew314-improved-error-messages}@anchor{151}
@subsubsection エラーメッセージの改善



@itemize *

@item 
The interpreter now provides helpful suggestions when it detects typos in Python
keywords. When a word that closely resembles a Python keyword is encountered,
the interpreter will suggest the correct keyword in the error message. This
feature helps programmers quickly identify and fix common typing mistakes. For
example:

@example
>>> whille True:
...     pass
Traceback (most recent call last):
  File "<stdin>", line 1
    whille True:
    ^^^^^^
SyntaxError: invalid syntax. Did you mean 'while'?
@end example

While the feature focuses on the most common cases, some variations of
misspellings may still result in regular syntax errors.
(Contributed by Pablo Galindo in gh-132449@footnote{https://github.com/python/cpython/issues/132449}.)

@item 
@ref{17b,,elif} statements that follow an @ref{17c,,else} block now have
a specific error message.
(Contributed by Steele Farnsworth in gh-129902@footnote{https://github.com/python/cpython/issues/129902}.)

@example
>>> if who == "me":
...     print("It's me!")
... else:
...     print("It's not me!")
... elif who is None:
...     print("Who is it?")
File "<stdin>", line 5
  elif who is None:
  ^^^^
SyntaxError: 'elif' block follows an 'else' block
@end example

@item 
If a statement is passed to the @ref{17d,,条件式 (Conditional Expressions)} after @ref{17c,,else},
or one of @ref{17e,,pass}, @ref{17f,,break}, or @ref{180,,continue}
is passed before @ref{181,,if}, then the
error message highlights where the @ref{182,,expression} is
required. (Contributed by Sergey Miryanov in gh-129515@footnote{https://github.com/python/cpython/issues/129515}.)

@example
>>> x = 1 if True else pass
Traceback (most recent call last):
  File "<string>", line 1
    x = 1 if True else pass
                       ^^^^
SyntaxError: expected expression after 'else', but statement is given

>>> x = continue if True else break
Traceback (most recent call last):
  File "<string>", line 1
    x = continue if True else break
        ^^^^^^^^
SyntaxError: expected expression before 'if', but statement is given
@end example

@item 
When incorrectly closed strings are detected, the error message suggests
that the string may be intended to be part of the string.
(Contributed by Pablo Galindo in gh-88535@footnote{https://github.com/python/cpython/issues/88535}.)

@example
>>> "The interesting object "The important object" is very important"
Traceback (most recent call last):
SyntaxError: invalid syntax. Is this intended to be part of the string?
@end example

@item 
When strings have incompatible prefixes, the error now shows
which prefixes are incompatible.
(Contributed by Nikita Sobolev in gh-133197@footnote{https://github.com/python/cpython/issues/133197}.)

@example
>>> ub'abc'
  File "<python-input-0>", line 1
    ub'abc'
    ^^
SyntaxError: 'u' and 'b' prefixes are incompatible
@end example

@item 
Improved error messages when using @code{as} with incompatible targets in:


@itemize -

@item 
Imports: @code{import ... as ...}

@item 
From imports: @code{from ... import ... as ...}

@item 
Except handlers: @code{except ... as ...}

@item 
Pattern-match cases: @code{case ... as ...}
@end itemize

(Contributed by Nikita Sobolev in gh-123539@footnote{https://github.com/python/cpython/issues/123539}, gh-123562@footnote{https://github.com/python/cpython/issues/123562}, and gh-123440@footnote{https://github.com/python/cpython/issues/123440}.)

@item 
Improved error message when trying to add an instance of an unhashable type to
a @ref{183,,dict} or @ref{184,,set}.
(Contributed by CF Bolz-Tereick and Victor Stinner in gh-132828@footnote{https://github.com/python/cpython/issues/132828}.)

@example
>>> s = set()
>>> s.add(@{'pages': 12, 'grade': 'A'@})
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    s.add(@{'pages': 12, 'grade': 'A'@})
    ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'dict' as a set element (unhashable type: 'dict')
>>> d = @{@}
>>> l = [1, 2, 3]
>>> d[l] = 12
Traceback (most recent call last):
  File "<python-input-4>", line 1, in <module>
    d[l] = 12
    ~^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
@end example

@item 
Improved error message when an object supporting the synchronous
context manager protocol is entered using @ref{185,,async with}
instead of @ref{186,,with},
and vice versa for the asynchronous context manager protocol.
(Contributed by Bénédikt Tran in gh-128398@footnote{https://github.com/python/cpython/issues/128398}.)
@end itemize

@node PEP 784 Zstandard support in the standard library,Asyncio introspection capabilities,エラーメッセージの改善,新しい機能
@anchor{whatsnew/3 14 pep-784-zstandard-support-in-the-standard-library}@anchor{187}@anchor{whatsnew/3 14 whatsnew314-zstandard}@anchor{148}
@subsubsection 
@geindex Python Enhancement Proposals; PEP 784
`PEP 784': Zstandard support in the standard library


The new @code{compression} package contains modules @code{compression.lzma},
@code{compression.bz2}, @code{compression.gzip} and @code{compression.zlib}
which re-export the @ref{8e,,lzma}, @ref{14,,bz2}, @ref{6b,,gzip} and @ref{139,,zlib}
modules respectively. The new import names under @code{compression} are the
preferred names for importing these compression modules from Python 3.14. However,
the existing modules names have not been deprecated. Any deprecation or removal
of the existing compression modules will occur no sooner than five years after
the release of 3.14.

The new @code{compression.zstd} module provides compression and decompression
APIs for the Zstandard format via bindings to Meta's zstd library@footnote{https://facebook.github.io/zstd/}. Zstandard is a widely adopted, highly
efficient, and fast compression format. In addition to the APIs introduced in
@code{compression.zstd}, support for reading and writing Zstandard compressed
archives has been added to the @ref{e4,,tarfile}, @ref{137,,zipfile}, and
@ref{ca,,shutil} modules.

Here's an example of using the new module to compress some data:

@example
from compression import zstd
import math

data = str(math.pi).encode() * 20
compressed = zstd.compress(data)
ratio = len(compressed) / len(data)
print(f"Achieved compression ratio of @{ratio@}")
@end example

As can be seen, the API is similar to the APIs of the @code{lzma} and
@code{bz2} modules.

(Contributed by Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun,
Victor Stinner, and Rogdham in gh-132983@footnote{https://github.com/python/cpython/issues/132983}.)


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 784
PEP 784@footnote{https://peps.python.org/pep-0784/}.


@node Asyncio introspection capabilities,Concurrent safe warnings control,PEP 784 Zstandard support in the standard library,新しい機能
@anchor{whatsnew/3 14 asyncio-introspection-capabilities}@anchor{188}@anchor{whatsnew/3 14 whatsnew314-asyncio-introspection}@anchor{147}
@subsubsection Asyncio introspection capabilities


Added a new command-line interface to inspect running Python processes
using asynchronous tasks, available via @code{python -m asyncio ps PID}
or @code{python -m asyncio pstree PID}.

The @code{ps} subcommand inspects the given process ID (PID) and displays
information about currently running asyncio tasks.
It outputs a task table: a flat listing of all tasks, their names,
their coroutine stacks, and which tasks are awaiting them.

The @code{pstree} subcommand fetches the same information, but instead renders a
visual async call tree, showing coroutine relationships in a hierarchical format.
This command is particularly useful for debugging long-running or stuck
asynchronous programs.
It can help developers quickly identify where a program is blocked,
what tasks are pending, and how coroutines are chained together.

For example given this code:

@example
import asyncio

async def play_track(track):
    await asyncio.sleep(5)
    print(f'🎵 Finished: @{track@}')

async def play_album(name, tracks):
    async with asyncio.TaskGroup() as tg:
        for track in tracks:
            tg.create_task(play_track(track), name=track)

async def main():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(
          play_album('Sundowning', ['TNDNBTG', 'Levitate']),
          name='Sundowning')
        tg.create_task(
          play_album('TMBTE', ['DYWTYLM', 'Aqua Regia']),
          name='TMBTE')

if __name__ == '__main__':
    asyncio.run(main())
@end example

Executing the new tool on the running process will yield a table like this:

@example
python -m asyncio ps 12345

tid        task id              task name            coroutine stack                                    awaiter chain                                      awaiter name    awaiter id
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1935500    0x7fc930c18050       Task-1               TaskGroup._aexit -> TaskGroup.__aexit__ -> main                                                                       0x0
1935500    0x7fc930c18230       Sundowning           TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TaskGroup._aexit -> TaskGroup.__aexit__ -> main    Task-1          0x7fc930c18050
1935500    0x7fc93173fa50       TMBTE                TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TaskGroup._aexit -> TaskGroup.__aexit__ -> main    Task-1          0x7fc930c18050
1935500    0x7fc93173fdf0       TNDNBTG              sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   Sundowning      0x7fc930c18230
1935500    0x7fc930d32510       Levitate             sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   Sundowning      0x7fc930c18230
1935500    0x7fc930d32890       DYWTYLM              sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TMBTE           0x7fc93173fa50
1935500    0x7fc93161ec30       Aqua Regia           sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TMBTE           0x7fc93173fa50
@end example

or a tree like this:

@example
python -m asyncio pstree 12345

└── (T) Task-1
    └──  main example.py:13
        └──  TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
            └──  TaskGroup._aexit Lib/asyncio/taskgroups.py:121
                ├── (T) Sundowning
                │   └──  album example.py:8
                │       └──  TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
                │           └──  TaskGroup._aexit Lib/asyncio/taskgroups.py:121
                │               ├── (T) TNDNBTG
                │               │   └──  play example.py:4
                │               │       └──  sleep Lib/asyncio/tasks.py:702
                │               └── (T) Levitate
                │                   └──  play example.py:4
                │                       └──  sleep Lib/asyncio/tasks.py:702
                └── (T) TMBTE
                    └──  album example.py:8
                        └──  TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
                            └──  TaskGroup._aexit Lib/asyncio/taskgroups.py:121
                                ├── (T) DYWTYLM
                                │   └──  play example.py:4
                                │       └──  sleep Lib/asyncio/tasks.py:702
                                └── (T) Aqua Regia
                                    └──  play example.py:4
                                        └──  sleep Lib/asyncio/tasks.py:702
@end example

If a cycle is detected in the async await graph (which could indicate a
programming issue), the tool raises an error and lists the cycle paths that
prevent tree construction:

@example
python -m asyncio pstree 12345

ERROR: await-graph contains cycles - cannot print a tree!

cycle: Task-2 → Task-3 → Task-2
@end example

(Contributed by Pablo Galindo, Łukasz Langa, Yury Selivanov, and Marta
Gomez Macias in gh-91048@footnote{https://github.com/python/cpython/issues/91048}.)

@node Concurrent safe warnings control,,Asyncio introspection capabilities,新しい機能
@anchor{whatsnew/3 14 concurrent-safe-warnings-control}@anchor{189}@anchor{whatsnew/3 14 whatsnew314-concurrent-warnings-control}@anchor{153}
@subsubsection Concurrent safe warnings control


The @ref{179,,warnings.catch_warnings} context manager will now optionally
use a context variable for warning filters. This is enabled by setting
the @ref{18a,,context_aware_warnings} flag, either with the @code{-X}
command-line option or an environment variable. This gives predictable
warnings control when using @ref{179,,catch_warnings} combined with
multiple threads or asynchronous tasks. The flag defaults to true for the
free-threaded build and false for the GIL-enabled build.

(Contributed by Neil Schemenauer and Kumar Aditya in gh-130010@footnote{https://github.com/python/cpython/issues/130010}.)

@node Other language changes,新しいモジュール,新しい機能,What's new in Python 3 14
@anchor{whatsnew/3 14 other-language-changes}@anchor{18b}
@subsection Other language changes



@itemize *

@item 
All Windows code pages are now supported as 'cpXXX' codecs on Windows.
(Contributed by Serhiy Storchaka in gh-123803@footnote{https://github.com/python/cpython/issues/123803}.)

@item 
Implement mixed-mode arithmetic rules combining real and complex numbers
as specified by the C standard since C99.
(Contributed by Sergey B Kirpichev in gh-69639@footnote{https://github.com/python/cpython/issues/69639}.)

@item 
More syntax errors are now detected regardless of optimisation and
the @ref{18c,,-O} command-line option.
This includes writes to @code{__debug__}, incorrect use of @ref{18d,,await},
and asynchronous comprehensions outside asynchronous functions.
For example, @code{python -O -c 'assert (__debug__ := 1)'}
or @code{python -O -c 'assert await 1'} now produce @ref{18e,,SyntaxError}s.
(Contributed by Irit Katriel and Jelle Zijlstra in gh-122245@footnote{https://github.com/python/cpython/issues/122245} & gh-121637@footnote{https://github.com/python/cpython/issues/121637}.)

@item 
When subclassing a pure C type, the C slots for the new type
are no longer replaced with a wrapped version on class creation
if they are not explicitly overridden in the subclass.
(Contributed by Tomasz Pytel in gh-132284@footnote{https://github.com/python/cpython/issues/132284}.)
@end itemize

@menu
* Built-ins:: 
* コマンドラインと環境:: 
* PEP 758; Allow except and except* expressions without brackets: PEP 758 Allow except and except* expressions without brackets. 
* PEP 765; Control flow in finally blocks: PEP 765 Control flow in finally blocks. 
* Incremental garbage collection:: 
* Default interactive shell:: 

@end menu

@node Built-ins,コマンドラインと環境,,Other language changes
@anchor{whatsnew/3 14 built-ins}@anchor{18f}
@subsubsection Built-ins



@itemize *

@item 
The @ref{190,,bytes.fromhex()} and @ref{191,,bytearray.fromhex()} methods now accept
ASCII @ref{192,,bytes} and @ref{193,,bytes-like objects}.
(Contributed by Daniel Pope in gh-129349@footnote{https://github.com/python/cpython/issues/129349}.)

@item 
Add class methods @ref{194,,float.from_number()} and @ref{195,,complex.from_number()}
to convert a number to @ref{196,,float} or @ref{197,,complex} type correspondingly.
They raise a @ref{198,,TypeError} if the argument is not a real number.
(Contributed by Serhiy Storchaka in gh-84978@footnote{https://github.com/python/cpython/issues/84978}.)

@item 
Support underscore and comma as thousands separators in the fractional part
for floating-point presentation types of the new-style string formatting
(with @ref{199,,format()} or @ref{19a,,f-strings}).
(Contributed by Sergey B Kirpichev in gh-87790@footnote{https://github.com/python/cpython/issues/87790}.)

@item 
The @ref{19b,,int()} function no longer delegates to @ref{19c,,__trunc__()}.
Classes that want to support conversion to @code{int()} must implement
either @ref{19d,,__int__()} or @ref{19e,,__index__()}.
(Contributed by Mark Dickinson in gh-119743@footnote{https://github.com/python/cpython/issues/119743}.)

@item 
The @ref{19f,,map()} function now has an optional keyword-only `strict' flag
like @ref{1a0,,zip()} to check that all the iterables are of equal length.
(Contributed by Wannes Boeykens in gh-119793@footnote{https://github.com/python/cpython/issues/119793}.)

@item 
The @ref{165,,memoryview} type now supports subscription,
making it a @ref{1a1,,generic type}.
(Contributed by Brian Schubert in gh-126012@footnote{https://github.com/python/cpython/issues/126012}.)

@item 
Using @ref{1a2,,NotImplemented} in a boolean context
will now raise a @ref{198,,TypeError}.
This has raised a @ref{1a3,,DeprecationWarning} since Python 3.9.
(Contributed by Jelle Zijlstra in gh-118767@footnote{https://github.com/python/cpython/issues/118767}.)

@item 
Three-argument @ref{1a4,,pow()} now tries calling @ref{1a5,,__rpow__()}
if necessary.
Previously it was only called in two-argument @code{pow()}
and the binary power operator.
(Contributed by Serhiy Storchaka in gh-130104@footnote{https://github.com/python/cpython/issues/130104}.)

@item 
@ref{1a6,,super} objects are now @ref{29,,copyable} and @ref{ab,,pickleable}.
(Contributed by Serhiy Storchaka in gh-125767@footnote{https://github.com/python/cpython/issues/125767}.)
@end itemize

@node コマンドラインと環境,PEP 758 Allow except and except* expressions without brackets,Built-ins,Other language changes
@anchor{whatsnew/3 14 command-line-and-environment}@anchor{1a7}
@subsubsection コマンドラインと環境



@itemize *

@item 
The import time flag can now track modules that are already loaded ('cached'),
via the new @ref{16f,,-X importtime=2}.
When such a module is imported, the @code{self} and @code{cumulative} times
are replaced by the string @code{cached}.

Values above @code{2} for @code{-X importtime} are now reserved for future use.

(Contributed by Noah Kim and Adam Turner in gh-118655@footnote{https://github.com/python/cpython/issues/118655}.)

@item 
The command-line option @ref{1a8,,-c} now automatically dedents its code
argument before execution. The auto-dedentation behavior mirrors
@ref{1a9,,textwrap.dedent()}.
(Contributed by Jon Crall and Steven Sun in gh-103998@footnote{https://github.com/python/cpython/issues/103998}.)

@item 
@code{-J} is no longer a reserved flag for Jython@footnote{https://www.jython.org/},
and now has no special meaning.
(Contributed by Adam Turner in gh-133336@footnote{https://github.com/python/cpython/issues/133336}.)
@end itemize

@node PEP 758 Allow except and except* expressions without brackets,PEP 765 Control flow in finally blocks,コマンドラインと環境,Other language changes
@anchor{whatsnew/3 14 pep-758-allow-except-and-except-expressions-without-brackets}@anchor{1aa}@anchor{whatsnew/3 14 whatsnew314-bracketless-except}@anchor{14c}
@subsubsection PEP 758: Allow @code{except} and @code{except*} expressions without brackets


The @ref{1ab,,except} and @ref{1ac,,except*} expressions
now allow brackets to be omitted when there are multiple exception types
and the @code{as} clause is not used.
For example:

@example
try:
    connect_to_server()
except TimeoutError, ConnectionRefusedError:
    print('The network has ceased to be!')
@end example

(Contributed by Pablo Galindo and Brett Cannon in 
@geindex Python Enhancement Proposals; PEP 758
PEP 758@footnote{https://peps.python.org/pep-0758/} and gh-131831@footnote{https://github.com/python/cpython/issues/131831}.)

@node PEP 765 Control flow in finally blocks,Incremental garbage collection,PEP 758 Allow except and except* expressions without brackets,Other language changes
@anchor{whatsnew/3 14 pep-765-control-flow-in-finally-blocks}@anchor{1ad}@anchor{whatsnew/3 14 whatsnew314-finally-syntaxwarning}@anchor{14d}
@subsubsection PEP 765: Control flow in @code{finally} blocks


The compiler now emits a @ref{1ae,,SyntaxWarning} when a @ref{1af,,return},
@ref{17f,,break}, or @ref{180,,continue} statement have the effect of
leaving a @ref{1b0,,finally} block.
This change is specified in 
@geindex Python Enhancement Proposals; PEP 765
PEP 765@footnote{https://peps.python.org/pep-0765/}.

In situations where this change is inconvenient (such as those where the
warnings are redundant due to code linting), the @ref{1b1,,warning filter} can be used to turn off all syntax warnings by adding
@code{ignore::SyntaxWarning} as a filter. This can be specified in combination
with a filter that converts other warnings to errors (for example, passing
@code{-Werror -Wignore::SyntaxWarning} as CLI options, or setting
@code{PYTHONWARNINGS=error,ignore::SyntaxWarning}).

Note that applying such a filter at runtime using the @ref{118,,warnings} module
will only suppress the warning in code that is compiled `after' the filter is
adjusted. Code that is compiled prior to the filter adjustment (for example,
when a module is imported) will still emit the syntax warning.

(Contributed by Irit Katriel in gh-130080@footnote{https://github.com/python/cpython/issues/130080}.)

@node Incremental garbage collection,Default interactive shell,PEP 765 Control flow in finally blocks,Other language changes
@anchor{whatsnew/3 14 incremental-garbage-collection}@anchor{1b2}@anchor{whatsnew/3 14 whatsnew314-incremental-gc}@anchor{152}
@subsubsection Incremental garbage collection


The cycle garbage collector is now incremental.
This means that maximum pause times are reduced
by an order of magnitude or more for larger heaps.

There are now only two generations: young and old.
When @ref{1b3,,gc.collect()} is not called directly, the
GC is invoked a little less frequently. When invoked, it
collects the young generation and an increment of the
old generation, instead of collecting one or more generations.

The behavior of @code{gc.collect()} changes slightly:


@itemize *

@item 
@code{gc.collect(1)}: Performs an increment of garbage collection,
rather than collecting generation 1.

@item 
Other calls to @code{gc.collect()} are unchanged.
@end itemize

(Contributed by Mark Shannon in gh-108362@footnote{https://github.com/python/cpython/issues/108362}.)

@node Default interactive shell,,Incremental garbage collection,Other language changes
@anchor{whatsnew/3 14 default-interactive-shell}@anchor{1b4}
@subsubsection Default interactive shell

@anchor{whatsnew/3 14 whatsnew314-pyrepl-highlighting}@anchor{154}

@itemize *

@item 
The default @ref{1b5,,interactive} shell now highlights Python syntax.
The feature is enabled by default, save if 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL}
or any other environment variable that disables colour is set.
See @ref{1b7,,色の制御} for details.

The default color theme for syntax highlighting strives for good contrast
and exclusively uses the 4-bit VGA standard ANSI color codes for maximum
compatibility. The theme can be customized using an experimental API
@code{_colorize.set_theme()}.
This can be called interactively or in the 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} script.
Note that this function has no stability guarantees,
and may change or be removed.

(Contributed by Łukasz Langa in gh-131507@footnote{https://github.com/python/cpython/issues/131507}.)

@item 
The default @ref{1b5,,interactive} shell now supports import auto-completion.
This means that typing @code{import co} and pressing @code{<Tab>} will suggest
modules starting with @code{co}. Similarly, typing @code{from concurrent import i}
will suggest submodules of @code{concurrent} starting with @code{i}.
Note that autocompletion of module attributes is not currently supported.
(Contributed by Tomas Roun in gh-69605@footnote{https://github.com/python/cpython/issues/69605}.)
@end itemize

@node 新しいモジュール,Improved modules,Other language changes,What's new in Python 3 14
@anchor{whatsnew/3 14 new-modules}@anchor{1b9}
@subsection 新しいモジュール



@itemize *

@item 
@ref{6,,annotationlib}:
For introspecting @ref{15c,,annotations}.
See @ref{145,,PEP 749} for more details.
(Contributed by Jelle Zijlstra in gh-119180@footnote{https://github.com/python/cpython/issues/119180}.)

@item 
@ref{22,,compression} (including @ref{23,,compression.zstd}):
A package for compression-related modules,
including a new module to support the Zstandard compression format.
See @ref{148,,PEP 784} for more details.
(Contributed by Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun,
Victor Stinner, and Rogdham in gh-132983@footnote{https://github.com/python/cpython/issues/132983}.)

@item 
@ref{25,,concurrent.interpreters}:
Support for multiple interpreters in the standard library.
See @ref{146,,PEP 734} for more details.
(Contributed by Eric Snow in gh-134939@footnote{https://github.com/python/cpython/issues/134939}.)

@item 
@ref{d9,,string.templatelib}:
Support for template string literals (t-strings).
See @ref{144,,PEP 750} for more details.
(Contributed by Jim Baker, Guido van Rossum, Paul Everitt, Koudai Aono,
Lysandros Nikolaou, Dave Peck, Adam Turner, Jelle Zijlstra, Bénédikt Tran,
and Pablo Galindo Salgado in gh-132661@footnote{https://github.com/python/cpython/issues/132661}.)
@end itemize

@node Improved modules,最適化,新しいモジュール,What's new in Python 3 14
@anchor{whatsnew/3 14 improved-modules}@anchor{1ba}
@subsection Improved modules


@menu
* argparse:: 
* ast:: 
* asyncio:: 
* calendar:: 
* concurrent.futures: concurrent futures. 
* configparser:: 
* contextvars:: 
* ctypes:: 
* curses:: 
* datetime:: 
* decimal:: 
* difflib:: 
* dis:: 
* errno:: 
* faulthandler:: 
* fnmatch:: 
* fractions:: 
* functools:: 
* getopt:: 
* getpass:: 
* graphlib:: 
* heapq:: 
* hmac:: 
* http:: 
* imaplib:: 
* inspect:: 
* io:: 
* json:: 
* linecache:: 
* logging.handlers: logging handlers. 
* math:: 
* mimetypes:: 
* multiprocessing:: 
* operator:: 
* os:: 
* os.path: os path. 
* pathlib:: 
* pdb:: 
* pickle:: 
* プラットフォーム:: 
* pydoc:: 
* re:: 
* socket:: 
* ssl:: 
* struct:: 
* symtable:: 
* sys:: 
* sys.monitoring: sys monitoring. 
* sysconfig:: 
* tarfile:: 
* threading:: 
* tkinter:: 
* turtle:: 
* types:: 
* typing:: 
* unicodedata:: 
* unittest:: 
* urllib:: 
* uuid:: 
* webbrowser:: 
* zipfile:: 

@end menu

@node argparse,ast,,Improved modules
@anchor{whatsnew/3 14 argparse}@anchor{1bb}
@subsubsection argparse



@itemize *

@item 
The default value of the @ref{1bc,,program name} for
@ref{1bd,,argparse.ArgumentParser} now reflects the way the Python
interpreter was instructed to find the @code{__main__} module code.
(Contributed by Serhiy Storchaka and Alyssa Coghlan in gh-66436@footnote{https://github.com/python/cpython/issues/66436}.)

@item 
Introduced the optional `suggest_on_error' parameter to
@ref{1bd,,argparse.ArgumentParser}, enabling suggestions for argument choices
and subparser names if mistyped by the user.
(Contributed by Savannah Ostrowski in gh-124456@footnote{https://github.com/python/cpython/issues/124456}.)

@item 
Enable color for help text, which can be disabled with the optional `color'
parameter to @ref{1bd,,argparse.ArgumentParser}.
This can also be controlled by @ref{1b7,,environment variables}.
(Contributed by Hugo van Kemenade in gh-130645@footnote{https://github.com/python/cpython/issues/130645}.)
@end itemize

@node ast,asyncio,argparse,Improved modules
@anchor{whatsnew/3 14 ast}@anchor{1be}
@subsubsection ast



@itemize *

@item 
Add @ref{1bf,,compare()}, a function for comparing two ASTs.
(Contributed by Batuhan Taskaya and Jeremy Hylton in gh-60191@footnote{https://github.com/python/cpython/issues/60191}.)

@item 
Add support for @ref{1c0,,copy.replace()} for AST nodes.
(Contributed by Bénédikt Tran in gh-121141@footnote{https://github.com/python/cpython/issues/121141}.)

@item 
Docstrings are now removed from an optimized AST in optimization level 2.
(Contributed by Irit Katriel in gh-123958@footnote{https://github.com/python/cpython/issues/123958}.)

@item 
The @ref{1c1,,repr()} output for AST nodes now includes more information.
(Contributed by Tomas Roun in gh-116022@footnote{https://github.com/python/cpython/issues/116022}.)

@item 
When called with an AST as input, the @ref{1c2,,parse()} function
now always verifies that the root node type is appropriate.
(Contributed by Irit Katriel in gh-130139@footnote{https://github.com/python/cpython/issues/130139}.)

@item 
Add new options to the command-line interface:
@ref{1c3,,--feature-version},
@ref{1c4,,--optimize}, and
@ref{1c5,,--show-empty}.
(Contributed by Semyon Moroz in gh-133367@footnote{https://github.com/python/cpython/issues/133367}.)
@end itemize

@node asyncio,calendar,ast,Improved modules
@anchor{whatsnew/3 14 asyncio}@anchor{1c6}
@subsubsection asyncio



@itemize *

@item 
The function and methods named @code{create_task()} now take an arbitrary
list of keyword arguments. All keyword arguments are passed to the
@ref{1c7,,Task} constructor or the custom task factory.
(See @ref{1c8,,set_task_factory()} for details.)
The @code{name} and @code{context} keyword arguments are no longer special;
the name should now be set using the @code{name} keyword argument of the factory,
and @code{context} may be @code{None}.

This affects the following function and methods:
@ref{1c9,,asyncio.create_task()},
@ref{1ca,,asyncio.loop.create_task()},
@ref{1cb,,asyncio.TaskGroup.create_task()}.

(Contributed by Thomas Grainger in gh-128307@footnote{https://github.com/python/cpython/issues/128307}.)

@item 
There are two new utility functions for
introspecting and printing a program's call graph:
@ref{1cc,,capture_call_graph()} and @ref{1cd,,print_call_graph()}.
See @ref{147,,Asyncio introspection capabilities} for more details.
(Contributed by Yury Selivanov, Pablo Galindo Salgado, and Łukasz Langa
in gh-91048@footnote{https://github.com/python/cpython/issues/91048}.)
@end itemize

@node calendar,concurrent futures,asyncio,Improved modules
@anchor{whatsnew/3 14 calendar}@anchor{1ce}
@subsubsection calendar

@anchor{whatsnew/3 14 whatsnew314-color-calendar}@anchor{1cf}

@itemize *

@item 
By default, today's date is highlighted in color in @ref{15,,calendar}'s
@ref{1d0,,command-line} text output.
This can be controlled by @ref{1b7,,environment variables}.
(Contributed by Hugo van Kemenade in gh-128317@footnote{https://github.com/python/cpython/issues/128317}.)
@end itemize

@node concurrent futures,configparser,calendar,Improved modules
@anchor{whatsnew/3 14 concurrent-futures}@anchor{1d1}
@subsubsection concurrent.futures

@anchor{whatsnew/3 14 whatsnew314-concurrent-futures-interp-pool}@anchor{167}

@itemize *

@item 
Add a new executor class, @ref{1d2,,InterpreterPoolExecutor},
which exposes multiple Python interpreters in the same process
('subinterpreters') to Python code.
This uses a pool of independent Python interpreters to execute calls
asynchronously.

This is separate from the new @ref{25,,interpreters} module
introduced by @ref{146,,PEP 734}.
(Contributed by Eric Snow in gh-124548@footnote{https://github.com/python/cpython/issues/124548}.)
@end itemize
@anchor{whatsnew/3 14 whatsnew314-concurrent-futures-start-method}@anchor{1d3}

@itemize *

@item 
On Unix platforms other than macOS, @ref{1d4,,'forkserver'} is now the default @ref{1d5,,start method} for
@ref{1d6,,ProcessPoolExecutor}
(replacing @ref{1d7,,'fork'}).
This change does not affect Windows or macOS, where @ref{1d8,,'spawn'} remains the default start method.

If the threading incompatible `fork' method is required, you must explicitly
request it by supplying a multiprocessing context `mp_context' to
@ref{1d6,,ProcessPoolExecutor}.

See @ref{1d9,,forkserver restrictions}
for information and differences with the `fork' method and how this change
may affect existing code with mutable global shared variables and/or shared
objects that can not be automatically @ref{ab,,pickled}.

(Contributed by Gregory P. Smith in gh-84559@footnote{https://github.com/python/cpython/issues/84559}.)

@item 
Add two new methods to @ref{1d6,,ProcessPoolExecutor},
@ref{1da,,terminate_workers()}
and @ref{1db,,kill_workers()},
as ways to terminate or kill all living worker processes in the given pool.
(Contributed by Charles Machalow in gh-130849@footnote{https://github.com/python/cpython/issues/130849}.)

@item 
Add the optional `buffersize' parameter to @ref{1dc,,Executor.map} to limit the number of submitted
tasks whose results have not yet been yielded. If the buffer is full,
iteration over the `iterables' pauses until a result is yielded from the
buffer.
(Contributed by Enzo Bonnal and Josh Rosenberg in gh-74028@footnote{https://github.com/python/cpython/issues/74028}.)
@end itemize

@node configparser,contextvars,concurrent futures,Improved modules
@anchor{whatsnew/3 14 configparser}@anchor{1dd}
@subsubsection configparser



@itemize *

@item 
@code{configparser} will no longer write config files it cannot read,
to improve security.
Attempting to @ref{1de,,write()} keys containing
delimiters or beginning with the section header pattern will raise an
@ref{1df,,InvalidWriteError}.
(Contributed by Jacob Lincoln in gh-129270@footnote{https://github.com/python/cpython/issues/129270}.)
@end itemize

@node contextvars,ctypes,configparser,Improved modules
@anchor{whatsnew/3 14 contextvars}@anchor{1e0}
@subsubsection contextvars



@itemize *

@item 
Support the @ref{1e1,,context manager} protocol
for @ref{1e2,,Token} objects.
(Contributed by Andrew Svetlov in gh-129889@footnote{https://github.com/python/cpython/issues/129889}.)
@end itemize

@node ctypes,curses,contextvars,Improved modules
@anchor{whatsnew/3 14 ctypes}@anchor{1e3}
@subsubsection ctypes



@itemize *

@item 
The layout of @ref{1e4,,bit fields}
in @ref{1e5,,Structure} and @ref{1e6,,Union} objects
is now a closer match to platform defaults (GCC/Clang or MSVC).
In particular, fields no longer overlap.
(Contributed by Matthias Görgens in gh-97702@footnote{https://github.com/python/cpython/issues/97702}.)

@item 
The @ref{1e7,,Structure._layout_} class attribute can now be set
to help match a non-default ABI.
(Contributed by Petr Viktorin in gh-97702@footnote{https://github.com/python/cpython/issues/97702}.)

@item 
The class of @ref{1e5,,Structure}/@ref{1e6,,Union}
field descriptors is now available as @ref{1e8,,CField},
and has new attributes to aid debugging and introspection.
(Contributed by Petr Viktorin in gh-128715@footnote{https://github.com/python/cpython/issues/128715}.)

@item 
On Windows, the @ref{1e9,,COMError} exception is now public.
(Contributed by Jun Komoda in gh-126686@footnote{https://github.com/python/cpython/issues/126686}.)

@item 
On Windows, the @ref{1ea,,CopyComPointer()} function is now public.
(Contributed by Jun Komoda in gh-127275@footnote{https://github.com/python/cpython/issues/127275}.)

@item 
Add @ref{1eb,,memoryview_at()}, a function to create a
@ref{165,,memoryview} object that refers to the supplied pointer and
length. This works like @ref{1ec,,ctypes.string_at()} except it avoids a
buffer copy, and is typically useful when implementing pure Python
callback functions that are passed dynamically-sized buffers.
(Contributed by Rian Hunter in gh-112018@footnote{https://github.com/python/cpython/issues/112018}.)

@item 
Complex types, @ref{1ed,,c_float_complex},
@ref{1ee,,c_double_complex}, and @ref{1ef,,c_longdouble_complex},
are now available if both the compiler and the @code{libffi} library support
complex C types.
(Contributed by Sergey B Kirpichev in gh-61103@footnote{https://github.com/python/cpython/issues/61103}.)

@item 
Add @ref{1f0,,ctypes.util.dllist()} for listing the shared libraries
loaded by the current process.
(Contributed by Brian Ward in gh-119349@footnote{https://github.com/python/cpython/issues/119349}.)

@item 
Move @ref{1f1,,ctypes.POINTER()} types cache from a global internal cache
(@code{_pointer_type_cache}) to the @ref{1f2,,_CData.__pointer_type__} attribute of the corresponding
@code{ctypes} types.
This will stop the cache from growing without limits in some situations.
(Contributed by Sergey Miryanov in gh-100926@footnote{https://github.com/python/cpython/issues/100926}.)

@item 
The @ref{1f3,,py_object} type now supports subscription,
making it a @ref{1a1,,generic type}.
(Contributed by Brian Schubert in gh-132168@footnote{https://github.com/python/cpython/issues/132168}.)

@item 
@code{ctypes} now supports @ref{1f4,,free-threading builds}.
(Contributed by Kumar Aditya and Peter Bierma in gh-127945@footnote{https://github.com/python/cpython/issues/127945}.)
@end itemize

@node curses,datetime,ctypes,Improved modules
@anchor{whatsnew/3 14 curses}@anchor{1f5}
@subsubsection curses



@itemize *

@item 
Add the @ref{1f6,,assume_default_colors()} function,
a refinement of the @ref{1f7,,use_default_colors()} function which
allows changing the color pair @code{0}.
(Contributed by Serhiy Storchaka in gh-133139@footnote{https://github.com/python/cpython/issues/133139}.)
@end itemize

@node datetime,decimal,curses,Improved modules
@anchor{whatsnew/3 14 datetime}@anchor{1f8}
@subsubsection datetime



@itemize *

@item 
Add the @ref{1f9,,strptime()} method to the
@ref{1fa,,datetime.date} and @ref{1fb,,datetime.time} classes.
(Contributed by Wannes Boeykens in gh-41431@footnote{https://github.com/python/cpython/issues/41431}.)
@end itemize

@node decimal,difflib,datetime,Improved modules
@anchor{whatsnew/3 14 decimal}@anchor{1fc}
@subsubsection decimal



@itemize *

@item 
Add @ref{1fd,,Decimal.from_number()} as an alternative constructor for
@ref{1fe,,Decimal}.
(Contributed by Serhiy Storchaka in gh-121798@footnote{https://github.com/python/cpython/issues/121798}.)

@item 
Expose @ref{1ff,,IEEEContext()} to support creation of contexts
corresponding to the IEEE 754 (2008) decimal interchange formats.
(Contributed by Sergey B Kirpichev in gh-53032@footnote{https://github.com/python/cpython/issues/53032}.)
@end itemize

@node difflib,dis,decimal,Improved modules
@anchor{whatsnew/3 14 difflib}@anchor{200}
@subsubsection difflib



@itemize *

@item 
Comparison pages with highlighted changes generated by the
@ref{201,,HtmlDiff} class now support 'dark mode'.
(Contributed by Jiahao Li in gh-129939@footnote{https://github.com/python/cpython/issues/129939}.)
@end itemize

@node dis,errno,difflib,Improved modules
@anchor{whatsnew/3 14 dis}@anchor{202}
@subsubsection dis



@itemize *

@item 
Add support for rendering full source location information of
@ref{203,,instructions}, rather than only the line number.
This feature is added to the following interfaces via the `show_positions'
keyword argument:


@itemize -

@item 
@ref{204,,dis.Bytecode}

@item 
@ref{205,,dis.dis()}

@item 
@ref{206,,dis.distb()}

@item 
@ref{207,,dis.disassemble()}
@end itemize

This feature is also exposed via @ref{208,,dis --show-positions}.
(Contributed by Bénédikt Tran in gh-123165@footnote{https://github.com/python/cpython/issues/123165}.)

@item 
Add the @ref{209,,dis --specialized} command-line option to
show specialized bytecode.
(Contributed by Bénédikt Tran in gh-127413@footnote{https://github.com/python/cpython/issues/127413}.)
@end itemize

@node errno,faulthandler,dis,Improved modules
@anchor{whatsnew/3 14 errno}@anchor{20a}
@subsubsection errno



@itemize *

@item 
Add the @ref{20b,,EHWPOISON} error code constant.
(Contributed by James Roy in gh-126585@footnote{https://github.com/python/cpython/issues/126585}.)
@end itemize

@node faulthandler,fnmatch,errno,Improved modules
@anchor{whatsnew/3 14 faulthandler}@anchor{20c}
@subsubsection faulthandler



@itemize *

@item 
Add support for printing the C stack trace on systems that
@ref{20d,,support it} via the new
@ref{20e,,dump_c_stack()} function or via the `c_stack' argument
in @ref{20f,,faulthandler.enable()}.
(Contributed by Peter Bierma in gh-127604@footnote{https://github.com/python/cpython/issues/127604}.)
@end itemize

@node fnmatch,fractions,faulthandler,Improved modules
@anchor{whatsnew/3 14 fnmatch}@anchor{210}
@subsubsection fnmatch



@itemize *

@item 
Add @ref{211,,filterfalse()}, a function to reject names
matching a given pattern.
(Contributed by Bénédikt Tran in gh-74598@footnote{https://github.com/python/cpython/issues/74598}.)
@end itemize

@node fractions,functools,fnmatch,Improved modules
@anchor{whatsnew/3 14 fractions}@anchor{212}
@subsubsection fractions



@itemize *

@item 
A @ref{213,,Fraction} object may now be constructed from any
object with the @code{as_integer_ratio()} method.
(Contributed by Serhiy Storchaka in gh-82017@footnote{https://github.com/python/cpython/issues/82017}.)

@item 
Add @ref{214,,Fraction.from_number()} as an alternative constructor for
@ref{213,,Fraction}.
(Contributed by Serhiy Storchaka in gh-121797@footnote{https://github.com/python/cpython/issues/121797}.)
@end itemize

@node functools,getopt,fractions,Improved modules
@anchor{whatsnew/3 14 functools}@anchor{215}
@subsubsection functools



@itemize *

@item 
Add the @ref{216,,Placeholder} sentinel.
This may be used with the @ref{217,,partial()}
or @ref{218,,partialmethod()} functions to reserve a place
for positional arguments in the returned @ref{219,,partial object}.
(Contributed by Dominykas Grigonis in gh-119127@footnote{https://github.com/python/cpython/issues/119127}.)

@item 
Allow the `initial' parameter of @ref{21a,,reduce()} to be passed
as a keyword argument.
(Contributed by Sayandip Dutta in gh-125916@footnote{https://github.com/python/cpython/issues/125916}.)
@end itemize

@node getopt,getpass,functools,Improved modules
@anchor{whatsnew/3 14 getopt}@anchor{21b}
@subsubsection getopt



@itemize *

@item 
Add support for options with optional arguments.
(Contributed by Serhiy Storchaka in gh-126374@footnote{https://github.com/python/cpython/issues/126374}.)

@item 
Add support for returning intermixed options and non-option arguments in order.
(Contributed by Serhiy Storchaka in gh-126390@footnote{https://github.com/python/cpython/issues/126390}.)
@end itemize

@node getpass,graphlib,getopt,Improved modules
@anchor{whatsnew/3 14 getpass}@anchor{21c}
@subsubsection getpass



@itemize *

@item 
Support keyboard feedback in the @ref{21d,,getpass()} function via
the keyword-only optional argument `echo_char'.
Placeholder characters are rendered whenever a character is entered,
and removed when a character is deleted.
(Contributed by Semyon Moroz in gh-77065@footnote{https://github.com/python/cpython/issues/77065}.)
@end itemize

@node graphlib,heapq,getpass,Improved modules
@anchor{whatsnew/3 14 graphlib}@anchor{21e}
@subsubsection graphlib



@itemize *

@item 
Allow @ref{21f,,TopologicalSorter.prepare()} to be called more than once
as long as sorting has not started.
(Contributed by Daniel Pope in gh-130914@footnote{https://github.com/python/cpython/issues/130914}.)
@end itemize

@node heapq,hmac,graphlib,Improved modules
@anchor{whatsnew/3 14 heapq}@anchor{220}
@subsubsection heapq



@itemize *

@item 
The @code{heapq} module has improved support for working with max-heaps,
via the following new functions:


@itemize *

@item 
@ref{221,,heapify_max()}

@item 
@ref{222,,heappush_max()}

@item 
@ref{223,,heappop_max()}

@item 
@ref{224,,heapreplace_max()}

@item 
@ref{225,,heappushpop_max()}
@end itemize
@end itemize

@node hmac,http,heapq,Improved modules
@anchor{whatsnew/3 14 hmac}@anchor{226}
@subsubsection hmac



@itemize *

@item 
Add a built-in implementation for HMAC (
@geindex RFC; RFC 2104
RFC 2104@footnote{https://datatracker.ietf.org/doc/html/rfc2104.html}) using formally verified
code from the HACL*@footnote{https://github.com/hacl-star/hacl-star/} project.
This implementation is used as a fallback when the OpenSSL implementation
of HMAC is not available.
(Contributed by Bénédikt Tran in gh-99108@footnote{https://github.com/python/cpython/issues/99108}.)
@end itemize

@node http,imaplib,hmac,Improved modules
@anchor{whatsnew/3 14 http}@anchor{227}
@subsubsection http



@itemize *

@item 
Directory lists and error pages generated by the @ref{76,,http.server}
module allow the browser to apply its default dark mode.
(Contributed by Yorik Hansen in gh-123430@footnote{https://github.com/python/cpython/issues/123430}.)

@item 
The @ref{76,,http.server} module now supports serving over HTTPS using the
@ref{228,,http.server.HTTPSServer} class. This functionality is exposed by
the command-line interface (@code{python -m http.server}) through the following
options:


@itemize *

@item 
@ref{229,,--tls-cert <path>}:
Path to the TLS certificate file.

@item 
@ref{22a,,--tls-key <path>}:
Optional path to the private key file.

@item 
@ref{22b,,--tls-password-file <path>}:
Optional path to the password file for the private key.
@end itemize

(Contributed by Semyon Moroz in gh-85162@footnote{https://github.com/python/cpython/issues/85162}.)
@end itemize

@node imaplib,inspect,http,Improved modules
@anchor{whatsnew/3 14 imaplib}@anchor{22c}
@subsubsection imaplib



@itemize *

@item 
Add @ref{22d,,IMAP4.idle()}, implementing the IMAP4
@code{IDLE} command as defined in 
@geindex RFC; RFC 2177
RFC 2177@footnote{https://datatracker.ietf.org/doc/html/rfc2177.html}.
(Contributed by Forest in gh-55454@footnote{https://github.com/python/cpython/issues/55454}.)
@end itemize

@node inspect,io,imaplib,Improved modules
@anchor{whatsnew/3 14 inspect}@anchor{22e}
@subsubsection inspect



@itemize *

@item 
@ref{22f,,signature()} takes a new argument `annotation_format' to control
the @ref{230,,annotationlib.Format} used for representing annotations.
(Contributed by Jelle Zijlstra in gh-101552@footnote{https://github.com/python/cpython/issues/101552}.)

@item 
@ref{231,,Signature.format()} takes a new argument `unquote_annotations'.
If true, string @ref{15c,,annotations} are displayed without
surrounding quotes.
(Contributed by Jelle Zijlstra in gh-101552@footnote{https://github.com/python/cpython/issues/101552}.)

@item 
Add function @ref{232,,ispackage()} to determine whether an object is a
@ref{233,,package} or not.
(Contributed by Zhikang Yan in gh-125634@footnote{https://github.com/python/cpython/issues/125634}.)
@end itemize

@node io,json,inspect,Improved modules
@anchor{whatsnew/3 14 io}@anchor{234}
@subsubsection io



@itemize *

@item 
Reading text from a non-blocking stream with @code{read} may now raise a
@ref{235,,BlockingIOError} if the operation cannot immediately return bytes.
(Contributed by Giovanni Siragusa in gh-109523@footnote{https://github.com/python/cpython/issues/109523}.)

@item 
Add the @ref{236,,Reader} and @ref{237,,Writer} protocols as simpler
alternatives to the pseudo-protocols @ref{238,,typing.IO},
@ref{239,,typing.TextIO}, and @ref{23a,,typing.BinaryIO}.
(Contributed by Sebastian Rittau in gh-127648@footnote{https://github.com/python/cpython/issues/127648}.)
@end itemize

@node json,linecache,io,Improved modules
@anchor{whatsnew/3 14 json}@anchor{23b}
@subsubsection json



@itemize *

@item 
Add exception notes for JSON serialization errors that allow
identifying the source of the error.
(Contributed by Serhiy Storchaka in gh-122163@footnote{https://github.com/python/cpython/issues/122163}.)

@item 
Allow using the @ref{86,,json} module as a script using the @ref{23c,,-m} switch:
@code{python -m json}.
This is now preferred to @code{python -m json.tool},
which is @ref{23d,,soft deprecated}.
See the @ref{23e,,JSON command-line interface} documentation.
(Contributed by Trey Hunner in gh-122873@footnote{https://github.com/python/cpython/issues/122873}.)

@item 
By default, the output of the @ref{23e,,JSON command-line interface} is highlighted in color.
This can be controlled by @ref{1b7,,environment variables}.
(Contributed by Tomas Roun in gh-131952@footnote{https://github.com/python/cpython/issues/131952}.)
@end itemize

@node linecache,logging handlers,json,Improved modules
@anchor{whatsnew/3 14 linecache}@anchor{23f}
@subsubsection linecache



@itemize *

@item 
@ref{240,,getline()} can now retrieve source code for frozen modules.
(Contributed by Tian Gao in gh-131638@footnote{https://github.com/python/cpython/issues/131638}.)
@end itemize

@node logging handlers,math,linecache,Improved modules
@anchor{whatsnew/3 14 logging-handlers}@anchor{241}
@subsubsection logging.handlers



@itemize *

@item 
@ref{242,,QueueListener} objects now support the
@ref{1e1,,context manager} protocol.
(Contributed by Charles Machalow in gh-132106@footnote{https://github.com/python/cpython/issues/132106}.)

@item 
@ref{243,,QueueListener.start} now
raises a @ref{244,,RuntimeError} if the listener is already started.
(Contributed by Charles Machalow in gh-132106@footnote{https://github.com/python/cpython/issues/132106}.)
@end itemize

@node math,mimetypes,logging handlers,Improved modules
@anchor{whatsnew/3 14 math}@anchor{245}
@subsubsection math



@itemize *

@item 
Added more detailed error messages for domain errors in the module.
(Contributed by Charlie Zhao and Sergey B Kirpichev in gh-101410@footnote{https://github.com/python/cpython/issues/101410}.)
@end itemize

@node mimetypes,multiprocessing,math,Improved modules
@anchor{whatsnew/3 14 mimetypes}@anchor{246}
@subsubsection mimetypes



@itemize *

@item 
Add a public @ref{247,,command-line} for the module,
invoked via @code{python -m mimetypes}.
(Contributed by Oleg Iarygin and Hugo van Kemenade in gh-93096@footnote{https://github.com/python/cpython/issues/93096}.)

@item 
Add several new MIME types based on RFCs and common usage:

@subsubheading Microsoft and 
@geindex RFC; RFC 8081
RFC 8081@footnote{https://datatracker.ietf.org/doc/html/rfc8081.html} MIME types for fonts



@itemize *

@item 
Embedded OpenType: @code{application/vnd.ms-fontobject}

@item 
OpenType Layout (OTF) @code{font/otf}

@item 
TrueType: @code{font/ttf}

@item 
WOFF 1.0 @code{font/woff}

@item 
WOFF 2.0 @code{font/woff2}
@end itemize

@subsubheading 
@geindex RFC; RFC 9559
RFC 9559@footnote{https://datatracker.ietf.org/doc/html/rfc9559.html} MIME types for Matroska audiovisual data container structures



@itemize *

@item 
audio with no video: @code{audio/matroska} (@code{.mka})

@item 
video: @code{video/matroska} (@code{.mkv})

@item 
stereoscopic video: @code{video/matroska-3d} (@code{.mk3d})
@end itemize

@subsubheading Images with RFCs



@itemize *

@item 
@geindex RFC; RFC 1494
RFC 1494@footnote{https://datatracker.ietf.org/doc/html/rfc1494.html}: CCITT Group 3 (@code{.g3})

@item 
@geindex RFC; RFC 3362
RFC 3362@footnote{https://datatracker.ietf.org/doc/html/rfc3362.html}: Real-time Facsimile, T.38 (@code{.t38})

@item 
@geindex RFC; RFC 3745
RFC 3745@footnote{https://datatracker.ietf.org/doc/html/rfc3745.html}: JPEG 2000 (@code{.jp2}), extension (@code{.jpx}) and compound (@code{.jpm})

@item 
@geindex RFC; RFC 3950
RFC 3950@footnote{https://datatracker.ietf.org/doc/html/rfc3950.html}: Tag Image File Format Fax eXtended, TIFF-FX (@code{.tfx})

@item 
@geindex RFC; RFC 4047
RFC 4047@footnote{https://datatracker.ietf.org/doc/html/rfc4047.html}: Flexible Image Transport System (@code{.fits})

@item 
@geindex RFC; RFC 7903
RFC 7903@footnote{https://datatracker.ietf.org/doc/html/rfc7903.html}: Enhanced Metafile (@code{.emf}) and Windows Metafile (@code{.wmf})
@end itemize

@subsubheading Other MIME type additions and changes



@itemize *

@item 
@geindex RFC; RFC 2361
RFC 2361@footnote{https://datatracker.ietf.org/doc/html/rfc2361.html}: Change type for @code{.avi} to @code{video/vnd.avi}
and for @code{.wav} to @code{audio/vnd.wave}

@item 
@geindex RFC; RFC 4337
RFC 4337@footnote{https://datatracker.ietf.org/doc/html/rfc4337.html}: Add MPEG-4 @code{audio/mp4} (@code{.m4a})

@item 
@geindex RFC; RFC 5334
RFC 5334@footnote{https://datatracker.ietf.org/doc/html/rfc5334.html}: Add Ogg media (@code{.oga}, @code{.ogg} and @code{.ogx})

@item 
@geindex RFC; RFC 6713
RFC 6713@footnote{https://datatracker.ietf.org/doc/html/rfc6713.html}: Add gzip @code{application/gzip} (@code{.gz})

@item 
@geindex RFC; RFC 9639
RFC 9639@footnote{https://datatracker.ietf.org/doc/html/rfc9639.html}: Add FLAC @code{audio/flac} (@code{.flac})

@item 
@geindex RFC; RFC 9512
RFC 9512@footnote{https://datatracker.ietf.org/doc/html/rfc9512.html} @code{application/yaml} MIME type for YAML files (@code{.yaml}
and @code{.yml})

@item 
Add 7z @code{application/x-7z-compressed} (@code{.7z})

@item 
Add Android Package @code{application/vnd.android.package-archive} (@code{.apk})
when not strict

@item 
Add deb @code{application/x-debian-package} (@code{.deb})

@item 
Add glTF binary @code{model/gltf-binary} (@code{.glb})

@item 
Add glTF JSON/ASCII @code{model/gltf+json} (@code{.gltf})

@item 
Add M4V @code{video/x-m4v} (@code{.m4v})

@item 
Add PHP @code{application/x-httpd-php} (@code{.php})

@item 
Add RAR @code{application/vnd.rar} (@code{.rar})

@item 
Add RPM @code{application/x-rpm} (@code{.rpm})

@item 
Add STL @code{model/stl} (@code{.stl})

@item 
Add Windows Media Video @code{video/x-ms-wmv} (@code{.wmv})

@item 
De facto: Add WebM @code{audio/webm} (@code{.weba})

@item 
ECMA-376@footnote{https://ecma-international.org/publications-and-standards/standards/ecma-376/}:
Add @code{.docx}, @code{.pptx} and @code{.xlsx} types

@item 
OASIS@footnote{https://docs.oasis-open.org/office/v1.2/cs01/OpenDocument-v1.2-cs01-part1.html#Appendix_C}:
Add OpenDocument @code{.odg}, @code{.odp}, @code{.ods} and @code{.odt} types

@item 
W3C@footnote{https://www.w3.org/TR/epub-33/#app-media-type}:
Add EPUB @code{application/epub+zip} (@code{.epub})
@end itemize

(Contributed by Sahil Prajapati and Hugo van Kemenade in gh-84852@footnote{https://github.com/python/cpython/issues/84852},
by Sasha "Nelie" Chernykh and Hugo van Kemenade in gh-132056@footnote{https://github.com/python/cpython/issues/132056},
and by Hugo van Kemenade in gh-89416@footnote{https://github.com/python/cpython/issues/89416}, gh-85957@footnote{https://github.com/python/cpython/issues/85957}, and gh-129965@footnote{https://github.com/python/cpython/issues/129965}.)
@end itemize

@node multiprocessing,operator,mimetypes,Improved modules
@anchor{whatsnew/3 14 multiprocessing}@anchor{248}
@subsubsection multiprocessing

@anchor{whatsnew/3 14 whatsnew314-multiprocessing-start-method}@anchor{249}

@itemize *

@item 
On Unix platforms other than macOS, @ref{1d4,,'forkserver'} is now the default @ref{1d5,,start method}
(replacing @ref{1d7,,'fork'}).
This change does not affect Windows or macOS, where @ref{1d8,,'spawn'} remains the default start method.

If the threading incompatible `fork' method is required, you must explicitly
request it via a context from @ref{24a,,get_context()} (preferred)
or change the default via @ref{24b,,set_start_method()}.

See @ref{1d9,,forkserver restrictions}
for information and differences with the `fork' method and how this change
may affect existing code with mutable global shared variables and/or shared
objects that can not be automatically @ref{ab,,pickled}.

(Contributed by Gregory P. Smith in gh-84559@footnote{https://github.com/python/cpython/issues/84559}.)

@item 
@ref{98,,multiprocessing}'s @code{'forkserver'} start method now authenticates
its control socket to avoid solely relying on filesystem permissions
to restrict what other processes could cause the forkserver to spawn workers
and run code.
(Contributed by Gregory P. Smith for gh-97514@footnote{https://github.com/python/cpython/issues/97514}.)

@item 
The @ref{24c,,multiprocessing proxy objects}
for `list' and `dict' types gain previously overlooked missing methods:

@quotation


@itemize *

@item 
@code{clear()} and @code{copy()} for proxies of @ref{24d,,list}

@item 
@ref{24e,,fromkeys()}, @code{reversed(d)}, @code{d | @{@}}, @code{@{@} | d},
@code{d |= @{'b': 2@}} for proxies of @ref{183,,dict}
@end itemize
@end quotation

(Contributed by Roy Hyunjin Han for gh-103134@footnote{https://github.com/python/cpython/issues/103134}.)

@item 
Add support for shared @ref{184,,set} objects via
@ref{24f,,SyncManager.set()}.
The @ref{184,,set()} in @ref{250,,Manager()} method is now available.
(Contributed by Mingyu Park in gh-129949@footnote{https://github.com/python/cpython/issues/129949}.)

@item 
Add the @ref{251,,interrupt()}
to @ref{252,,multiprocessing.Process} objects, which terminates the child
process by sending @ref{253,,SIGINT}. This enables
@ref{1b0,,finally} clauses to print a stack trace for the terminated
process. (Contributed by Artem Pulkin in gh-131913@footnote{https://github.com/python/cpython/issues/131913}.)
@end itemize

@node operator,os,multiprocessing,Improved modules
@anchor{whatsnew/3 14 operator}@anchor{254}
@subsubsection operator



@itemize *

@item 
Add @ref{255,,is_none()} and @ref{256,,is_not_none()} as a pair
of functions, such that @code{operator.is_none(obj)} is equivalent
to @code{obj is None} and @code{operator.is_not_none(obj)} is equivalent
to @code{obj is not None}.
(Contributed by Raymond Hettinger and Nico Mexis in gh-115808@footnote{https://github.com/python/cpython/issues/115808}.)
@end itemize

@node os,os path,operator,Improved modules
@anchor{whatsnew/3 14 os}@anchor{257}
@subsubsection os



@itemize *

@item 
Add the @ref{258,,reload_environ()} function to update @ref{259,,os.environ} and
@ref{25a,,os.environb} with changes to the environment made by
@ref{25b,,os.putenv()}, by @ref{25c,,os.unsetenv()}, or made outside Python in the
same process.
(Contributed by Victor Stinner in gh-120057@footnote{https://github.com/python/cpython/issues/120057}.)

@item 
Add the @ref{25d,,SCHED_DEADLINE} and @ref{25e,,SCHED_NORMAL} constants
to the @code{os} module.
(Contributed by James Roy in gh-127688@footnote{https://github.com/python/cpython/issues/127688}.)

@item 
Add the @ref{25f,,readinto()} function to read into a
@ref{260,,buffer object} from a file descriptor.
(Contributed by Cody Maloney in gh-129205@footnote{https://github.com/python/cpython/issues/129205}.)
@end itemize

@node os path,pathlib,os,Improved modules
@anchor{whatsnew/3 14 os-path}@anchor{261}
@subsubsection os.path



@itemize *

@item 
The `strict' parameter to @ref{262,,realpath()} accepts a new value,
@ref{263,,ALLOW_MISSING}.
If used, errors other than @ref{264,,FileNotFoundError} will be re-raised;
the resulting path can be missing but it will be free of symlinks.
(Contributed by Petr Viktorin for 
@geindex Common Vulnerabilities and Exposures; CVE 2025-4517
CVE 2025-4517@footnote{https://www.cve.org/CVERecord?id=CVE-2025-4517}.)
@end itemize

@node pathlib,pdb,os path,Improved modules
@anchor{whatsnew/3 14 pathlib}@anchor{265}
@subsubsection pathlib



@itemize *

@item 
Add methods to @ref{266,,pathlib.Path} to recursively copy or move files and
directories:


@itemize *

@item 
@ref{267,,copy()} copies a file or directory tree to a destination.

@item 
@ref{268,,copy_into()} copies `into' a destination directory.

@item 
@ref{269,,move()} moves a file or directory tree to a destination.

@item 
@ref{26a,,move_into()} moves `into' a destination directory.
@end itemize

(Contributed by Barney Gale in gh-73991@footnote{https://github.com/python/cpython/issues/73991}.)

@item 
Add the @ref{26b,,info} attribute, which stores an object
implementing the new @ref{26c,,pathlib.types.PathInfo} protocol. The
object supports querying the file type and internally caching
@ref{26d,,stat()} results. Path objects generated by
@ref{26e,,iterdir()} are initialized with file type information
gleaned from scanning the parent directory.
(Contributed by Barney Gale in gh-125413@footnote{https://github.com/python/cpython/issues/125413}.)
@end itemize

@node pdb,pickle,pathlib,Improved modules
@anchor{whatsnew/3 14 pdb}@anchor{26f}
@subsubsection pdb



@itemize *

@item 
The @ref{aa,,pdb} module now supports remote attaching to a running Python process
using a new @ref{270,,-p PID} command-line option:

@example
python -m pdb -p 1234
@end example

This will connect to the Python process with the given PID and allow you to
debug it interactively. Notice that due to how the Python interpreter works
attaching to a remote process that is blocked in a system call or waiting for
I/O will only work once the next bytecode instruction is executed or when the
process receives a signal.

This feature uses @ref{14e,,PEP 768}
and the new @ref{16d,,sys.remote_exec()} function to attach to the remote process
and send the PDB commands to it.

(Contributed by Matt Wozniski and Pablo Galindo in gh-131591@footnote{https://github.com/python/cpython/issues/131591}.)

@item 
Hardcoded breakpoints (@ref{271,,breakpoint()} and @ref{272,,set_trace()}) now
reuse the most recent @ref{273,,Pdb} instance that calls
@ref{274,,set_trace()}, instead of creating a new one each time.
As a result, all the instance specific data like @ref{275,,display} and
@ref{276,,commands} are preserved across hardcoded breakpoints.
(Contributed by Tian Gao in gh-121450@footnote{https://github.com/python/cpython/issues/121450}.)

@item 
Add a new argument `mode' to @ref{273,,pdb.Pdb}. Disable the @code{restart}
command when @ref{aa,,pdb} is in @code{inline} mode.
(Contributed by Tian Gao in gh-123757@footnote{https://github.com/python/cpython/issues/123757}.)

@item 
A confirmation prompt will be shown when the user tries to quit @ref{aa,,pdb}
in @code{inline} mode. @code{y}, @code{Y}, @code{<Enter>} or @code{EOF} will confirm
the quit and call @ref{277,,sys.exit()}, instead of raising @ref{278,,bdb.BdbQuit}.
(Contributed by Tian Gao in gh-124704@footnote{https://github.com/python/cpython/issues/124704}.)

@item 
Inline breakpoints like @ref{271,,breakpoint()} or @ref{272,,pdb.set_trace()} will
always stop the program at calling frame, ignoring the @code{skip} pattern
(if any).
(Contributed by Tian Gao in gh-130493@footnote{https://github.com/python/cpython/issues/130493}.)

@item 
@code{<tab>} at the beginning of the line in @ref{aa,,pdb} multi-line input will
fill in a 4-space indentation now, instead of inserting a @code{\t} character.
(Contributed by Tian Gao in gh-130471@footnote{https://github.com/python/cpython/issues/130471}.)

@item 
Auto-indent is introduced in @ref{aa,,pdb} multi-line input. It will either
keep the indentation of the last line or insert a 4-space indentation when
it detects a new code block.
(Contributed by Tian Gao in gh-133350@footnote{https://github.com/python/cpython/issues/133350}.)

@item 
@code{$_asynctask} is added to access the current asyncio task if applicable.
(Contributed by Tian Gao in gh-124367@footnote{https://github.com/python/cpython/issues/124367}.)

@item 
@ref{279,,pdb.set_trace_async()} is added to support debugging asyncio
coroutines. @ref{18d,,await} statements are supported with this
function.
(Contributed by Tian Gao in gh-132576@footnote{https://github.com/python/cpython/issues/132576}.)

@item 
Source code displayed in @ref{aa,,pdb} will be syntax-highlighted. This feature
can be controlled using the same methods as the default @ref{1b5,,interactive}
shell, in addition to the newly added @code{colorize} argument of @ref{273,,pdb.Pdb}.
(Contributed by Tian Gao and Łukasz Langa in gh-133355@footnote{https://github.com/python/cpython/issues/133355}.)
@end itemize

@node pickle,プラットフォーム,pdb,Improved modules
@anchor{whatsnew/3 14 pickle}@anchor{27a}
@subsubsection pickle



@itemize *

@item 
Set the default protocol version on the @ref{ab,,pickle} module to 5.
For more details, see @ref{27b,,pickle protocols}.

@item 
Add exception notes for pickle serialization errors that allow
identifying the source of the error.
(Contributed by Serhiy Storchaka in gh-122213@footnote{https://github.com/python/cpython/issues/122213}.)
@end itemize

@node プラットフォーム,pydoc,pickle,Improved modules
@anchor{whatsnew/3 14 platform}@anchor{27c}
@subsubsection プラットフォーム



@itemize *

@item 
Add @ref{27d,,invalidate_caches()}, a function to invalidate
cached results in the @code{platform} module.
(Contributed by Bénédikt Tran in gh-122549@footnote{https://github.com/python/cpython/issues/122549}.)
@end itemize

@node pydoc,re,プラットフォーム,Improved modules
@anchor{whatsnew/3 14 pydoc}@anchor{27e}
@subsubsection pydoc



@itemize *

@item 
@ref{15c,,Annotations} in help output are now usually
displayed in a format closer to that in the original source.
(Contributed by Jelle Zijlstra in gh-101552@footnote{https://github.com/python/cpython/issues/101552}.)
@end itemize

@node re,socket,pydoc,Improved modules
@anchor{whatsnew/3 14 re}@anchor{27f}
@subsubsection re



@itemize *

@item 
Support @code{\z} as a synonym for @code{\Z} in @ref{be,,regular expressions}.
It is interpreted unambiguously in many other regular expression engines,
unlike @code{\Z}, which has subtly different behavior.
(Contributed by Serhiy Storchaka in gh-133306@footnote{https://github.com/python/cpython/issues/133306}.)

@item 
@code{\B} in @ref{be,,regular expression} now matches the empty input string,
meaning that it is now always the opposite of @code{\b}.
(Contributed by Serhiy Storchaka in gh-124130@footnote{https://github.com/python/cpython/issues/124130}.)
@end itemize

@node socket,ssl,re,Improved modules
@anchor{whatsnew/3 14 socket}@anchor{280}
@subsubsection socket



@itemize *

@item 
Improve and fix support for Bluetooth sockets.


@itemize *

@item 
Fix support of Bluetooth sockets on NetBSD and DragonFly BSD.
(Contributed by Serhiy Storchaka in gh-132429@footnote{https://github.com/python/cpython/issues/132429}.)

@item 
Fix support for @ref{281,,BTPROTO_HCI} on FreeBSD.
(Contributed by Victor Stinner in gh-111178@footnote{https://github.com/python/cpython/issues/111178}.)

@item 
Add support for @ref{282,,BTPROTO_SCO} on FreeBSD.
(Contributed by Serhiy Storchaka in gh-85302@footnote{https://github.com/python/cpython/issues/85302}.)

@item 
Add support for `cid' and `bdaddr_type' in the address for
@ref{283,,BTPROTO_L2CAP} on FreeBSD.
(Contributed by Serhiy Storchaka in gh-132429@footnote{https://github.com/python/cpython/issues/132429}.)

@item 
Add support for `channel' in the address for
@ref{281,,BTPROTO_HCI} on Linux.
(Contributed by Serhiy Storchaka in gh-70145@footnote{https://github.com/python/cpython/issues/70145}.)

@item 
Accept an integer as the address for
@ref{281,,BTPROTO_HCI} on Linux.
(Contributed by Serhiy Storchaka in gh-132099@footnote{https://github.com/python/cpython/issues/132099}.)

@item 
Return `cid' in @ref{284,,getsockname()} for
@ref{283,,BTPROTO_L2CAP}.
(Contributed by Serhiy Storchaka in gh-132429@footnote{https://github.com/python/cpython/issues/132429}.)

@item 
Add many new constants.
(Contributed by Serhiy Storchaka in gh-132734@footnote{https://github.com/python/cpython/issues/132734}.)
@end itemize
@end itemize

@node ssl,struct,socket,Improved modules
@anchor{whatsnew/3 14 ssl}@anchor{285}
@subsubsection ssl



@itemize *

@item 
Indicate through the @ref{286,,HAS_PHA} Boolean whether the @code{ssl}
module supports TLSv1.3 post-handshake client authentication (PHA).
(Contributed by Will Childs-Klein in gh-128036@footnote{https://github.com/python/cpython/issues/128036}.)
@end itemize

@node struct,symtable,ssl,Improved modules
@anchor{whatsnew/3 14 struct}@anchor{287}
@subsubsection struct



@itemize *

@item 
Support the float complex and double complex C types in
the @ref{db,,struct} module (formatting characters @code{'F'} and @code{'D'}
respectively).
(Contributed by Sergey B Kirpichev in gh-121249@footnote{https://github.com/python/cpython/issues/121249}.)
@end itemize

@node symtable,sys,struct,Improved modules
@anchor{whatsnew/3 14 symtable}@anchor{288}
@subsubsection symtable



@itemize *

@item 
Expose the following @ref{289,,Symbol} methods:


@itemize *

@item 
@ref{28a,,is_comp_cell()}

@item 
@ref{28b,,is_comp_iter()}

@item 
@ref{28c,,is_free_class()}
@end itemize

(Contributed by Bénédikt Tran in gh-120029@footnote{https://github.com/python/cpython/issues/120029}.)
@end itemize

@node sys,sys monitoring,symtable,Improved modules
@anchor{whatsnew/3 14 sys}@anchor{28d}
@subsubsection sys



@itemize *

@item 
The previously undocumented special function @ref{28e,,sys.getobjects()},
which only exists in specialized builds of Python, may now return objects
from other interpreters than the one it's called in.
(Contributed by Eric Snow in gh-125286@footnote{https://github.com/python/cpython/issues/125286}.)

@item 
Add @ref{28f,,sys._is_immortal()} for determining if an object is @ref{290,,immortal}.
(Contributed by Peter Bierma in gh-128509@footnote{https://github.com/python/cpython/issues/128509}.)

@item 
On FreeBSD, @ref{291,,sys.platform} no longer contains the major version number.
It is always @code{'freebsd'}, instead of @code{'freebsd13'} or @code{'freebsd14'}.
(Contributed by Michael Osipov in gh-129393@footnote{https://github.com/python/cpython/issues/129393}.)

@item 
Raise @ref{1a3,,DeprecationWarning} for @ref{292,,sys._clear_type_cache()}. This
function was deprecated in Python 3.13 but it didn't raise a runtime warning.

@item 
Add @ref{16d,,sys.remote_exec()} to implement the new external debugger interface.
See @ref{14e,,PEP 768} for details.
(Contributed by Pablo Galindo Salgado, Matt Wozniski, and Ivona Stojanovic
in gh-131591@footnote{https://github.com/python/cpython/issues/131591}.)

@item 
Add the @ref{293,,sys._jit} namespace, containing utilities for introspecting
just-in-time compilation.
(Contributed by Brandt Bucher in gh-133231@footnote{https://github.com/python/cpython/issues/133231}.)
@end itemize

@node sys monitoring,sysconfig,sys,Improved modules
@anchor{whatsnew/3 14 sys-monitoring}@anchor{294}
@subsubsection sys.monitoring



@itemize *

@item 
Add two new monitoring events, @ref{295,,BRANCH_LEFT} and
@ref{296,,BRANCH_RIGHT}.
These replace and deprecate the @code{BRANCH} event.
(Contributed by Mark Shannon in gh-122548@footnote{https://github.com/python/cpython/issues/122548}.)
@end itemize

@node sysconfig,tarfile,sys monitoring,Improved modules
@anchor{whatsnew/3 14 sysconfig}@anchor{297}
@subsubsection sysconfig



@itemize *

@item 
Add @code{ABIFLAGS} key to @ref{298,,get_config_vars()} on Windows.
(Contributed by Xuehai Pan in gh-131799@footnote{https://github.com/python/cpython/issues/131799}.)
@end itemize

@node tarfile,threading,sysconfig,Improved modules
@anchor{whatsnew/3 14 tarfile}@anchor{299}
@subsubsection tarfile



@itemize *

@item 
@ref{29a,,data_filter()} now normalizes symbolic link targets in order to
avoid path traversal attacks.
(Contributed by Petr Viktorin in gh-127987@footnote{https://github.com/python/cpython/issues/127987} and 
@geindex Common Vulnerabilities and Exposures; CVE 2025-4138
CVE 2025-4138@footnote{https://www.cve.org/CVERecord?id=CVE-2025-4138}.)

@item 
@ref{29b,,extractall()} now skips fixing up directory attributes
when a directory was removed or replaced by another kind of file.
(Contributed by Petr Viktorin in gh-127987@footnote{https://github.com/python/cpython/issues/127987} and 
@geindex Common Vulnerabilities and Exposures; CVE 2024-12718
CVE 2024-12718@footnote{https://www.cve.org/CVERecord?id=CVE-2024-12718}.)

@item 
@ref{29c,,extract()} and @ref{29b,,extractall()}
now (re-)apply the extraction filter when substituting a link (hard or
symbolic) with a copy of another archive member, and when fixing up
directory attributes.
The former raises a new exception, @ref{29d,,LinkFallbackError}.
(Contributed by Petr Viktorin for 
@geindex Common Vulnerabilities and Exposures; CVE 2025-4330
CVE 2025-4330@footnote{https://www.cve.org/CVERecord?id=CVE-2025-4330} and 
@geindex Common Vulnerabilities and Exposures; CVE 2024-12718
CVE 2024-12718@footnote{https://www.cve.org/CVERecord?id=CVE-2024-12718}.)

@item 
@ref{29c,,extract()} and @ref{29b,,extractall()}
no longer extract rejected members when
@ref{29e,,errorlevel()} is zero.
(Contributed by Matt Prodani and Petr Viktorin in gh-112887@footnote{https://github.com/python/cpython/issues/112887}
and 
@geindex Common Vulnerabilities and Exposures; CVE 2025-4435
CVE 2025-4435@footnote{https://www.cve.org/CVERecord?id=CVE-2025-4435}.)
@end itemize

@node threading,tkinter,tarfile,Improved modules
@anchor{whatsnew/3 14 threading}@anchor{29f}
@subsubsection threading



@itemize *

@item 
@ref{178,,threading.Thread.start()} now sets the operating system thread name
to @ref{2a0,,threading.Thread.name}.
(Contributed by Victor Stinner in gh-59705@footnote{https://github.com/python/cpython/issues/59705}.)
@end itemize

@node tkinter,turtle,threading,Improved modules
@anchor{whatsnew/3 14 tkinter}@anchor{2a1}
@subsubsection tkinter



@itemize *

@item 
Make @ref{f6,,tkinter} widget methods @code{after()} and @code{after_idle()}
accept keyword arguments.
(Contributed by Zhikang Yan in gh-126899@footnote{https://github.com/python/cpython/issues/126899}.)

@item 
Add ability to specify a name for @code{tkinter.OptionMenu} and
@code{tkinter.ttk.OptionMenu}.
(Contributed by Zhikang Yan in gh-130482@footnote{https://github.com/python/cpython/issues/130482}.)
@end itemize

@node turtle,types,tkinter,Improved modules
@anchor{whatsnew/3 14 turtle}@anchor{2a2}
@subsubsection @code{turtle}



@itemize *

@item 
Add context managers for @ref{2a3,,turtle.fill()}, @ref{2a4,,turtle.poly()},
and @ref{2a5,,turtle.no_animation()}.
(Contributed by Marie Roald and Yngve Mardal Moe in gh-126350@footnote{https://github.com/python/cpython/issues/126350}.)
@end itemize

@node types,typing,turtle,Improved modules
@anchor{whatsnew/3 14 types}@anchor{2a6}
@subsubsection types



@itemize *

@item 
@ref{2a7,,types.UnionType} is now an alias for @ref{2a8,,typing.Union}.
See @ref{2a9,,below} for more details.
(Contributed by Jelle Zijlstra in gh-105499@footnote{https://github.com/python/cpython/issues/105499}.)
@end itemize

@node typing,unicodedata,types,Improved modules
@anchor{whatsnew/3 14 typing}@anchor{2aa}
@subsubsection typing

@anchor{whatsnew/3 14 whatsnew314-typing-union}@anchor{2a9}

@itemize *

@item 
The @ref{2a7,,types.UnionType} and @ref{2a8,,typing.Union} types are now
aliases for each other, meaning that both old-style unions
(created with @code{Union[int, str]}) and new-style unions (@code{int | str})
now create instances of the same runtime type. This unifies the behavior
between the two syntaxes, but leads to some differences in behavior that
may affect users who introspect types at runtime:


@itemize -

@item 
Both syntaxes for creating a union now produce the same string
representation in @ref{1c1,,repr()}.
For example, @code{repr(Union[int, str])} is now @code{"int | str"} instead of
@code{"typing.Union[int, str]"}.

@item 
Unions created using the old syntax are no longer cached.
Previously, running @code{Union[int, str]} multiple times would return
the same object (@code{Union[int, str] is Union[int, str]} would be @code{True}),
but now it will return two different objects.
Use @code{==} to compare unions for equality, not @code{is}.
New-style unions have never been cached this way.
This change could increase memory usage for some programs that use
a large number of unions created by subscripting @code{typing.Union}.
However, several factors offset this cost:
unions used in annotations are no longer evaluated by default in Python
3.14 because of 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}; an instance of @ref{2a7,,types.UnionType} is
itself much smaller than the object returned by @code{Union[]} was on prior
Python versions; and removing the cache also saves some space.
It is therefore unlikely that this change will cause a significant increase
in memory usage for most users.

@item 
Previously, old-style unions were implemented using the private class
@code{typing._UnionGenericAlias}.
This class is no longer needed for the implementation,
but it has been retained for backward compatibility,
with removal scheduled for Python 3.17.
Users should use documented introspection helpers like
@ref{2ab,,get_origin()} and @ref{2ac,,typing.get_args()} instead of
relying on private implementation details.

@item 
It is now possible to use @ref{2a8,,typing.Union} itself in
@ref{2ad,,isinstance()} checks.
For example, @code{isinstance(int | str, typing.Union)} will return @code{True};
previously this raised @ref{198,,TypeError}.

@item 
The @code{__args__} attribute of @ref{2a8,,typing.Union} objects is
no longer writable.

@item 
It is no longer possible to set any attributes on @ref{2a8,,Union}
objects.
This only ever worked for dunder attributes on previous versions, was never
documented to work, and was subtly broken in many cases.
@end itemize

(Contributed by Jelle Zijlstra in gh-105499@footnote{https://github.com/python/cpython/issues/105499}.)

@item 
@ref{2ae,,TypeAliasType} now supports star unpacking.
@end itemize

@node unicodedata,unittest,typing,Improved modules
@anchor{whatsnew/3 14 unicodedata}@anchor{2af}
@subsubsection unicodedata



@itemize *

@item 
The Unicode database has been updated to Unicode 16.0.0.
@end itemize

@node unittest,urllib,unicodedata,Improved modules
@anchor{whatsnew/3 14 unittest}@anchor{2b0}
@subsubsection unittest

@anchor{whatsnew/3 14 whatsnew314-color-unittest}@anchor{2b1}

@itemize *

@item 
@ref{10c,,unittest} output is now colored by default.
This can be controlled by @ref{1b7,,environment variables}.
(Contributed by Hugo van Kemenade in gh-127221@footnote{https://github.com/python/cpython/issues/127221}.)

@item 
unittest discovery supports @ref{2b2,,namespace package} as start
directory again. It was removed in Python 3.11.
(Contributed by Jacob Walls in gh-80958@footnote{https://github.com/python/cpython/issues/80958}.)

@item 
A number of new methods were added in the @ref{2b3,,TestCase} class
that provide more specialized tests.


@itemize -

@item 
@ref{2b4,,assertHasAttr()} and
@ref{2b5,,assertNotHasAttr()} check whether the object
has a particular attribute.

@item 
@ref{2b6,,assertIsSubclass()} and
@ref{2b7,,assertNotIsSubclass()} check whether the object
is a subclass of a particular class, or of one of a tuple of classes.

@item 
@ref{2b8,,assertStartsWith()},
@ref{2b9,,assertNotStartsWith()},
@ref{2ba,,assertEndsWith()} and
@ref{2bb,,assertNotEndsWith()} check whether the Unicode
or byte string starts or ends with particular strings.
@end itemize

(Contributed by Serhiy Storchaka in gh-71339@footnote{https://github.com/python/cpython/issues/71339}.)
@end itemize

@node urllib,uuid,unittest,Improved modules
@anchor{whatsnew/3 14 urllib}@anchor{2bc}
@subsubsection urllib



@itemize *

@item 
Upgrade HTTP digest authentication algorithm for @ref{111,,urllib.request} by
supporting SHA-256 digest authentication as specified in 
@geindex RFC; RFC 7616
RFC 7616@footnote{https://datatracker.ietf.org/doc/html/rfc7616.html}.
(Contributed by Calvin Bui in gh-128193@footnote{https://github.com/python/cpython/issues/128193}.)

@item 
Improve ergonomics and standards compliance when parsing and emitting
@code{file:} URLs.

In @ref{2bd,,url2pathname()}:


@itemize -

@item 
Accept a complete URL when the new `require_scheme' argument is set to
true.

@item 
Discard URL authority if it matches the local hostname.

@item 
Discard URL authority if it resolves to a local IP address when the new
`resolve_host' argument is set to true.

@item 
Discard URL query and fragment components.

@item 
Raise @ref{2be,,URLError} if a URL authority isn't local,
except on Windows where we return a UNC path as before.
@end itemize

In @ref{2bf,,pathname2url()}:


@itemize -

@item 
Return a complete URL when the new `add_scheme' argument is set to true.

@item 
Include an empty URL authority when a path begins with a slash. For
example, the path @code{/etc/hosts} is converted to the URL @code{///etc/hosts}.
@end itemize

On Windows, drive letters are no longer converted to uppercase, and @code{:}
characters not following a drive letter no longer cause an @ref{2c0,,OSError}
exception to be raised.

(Contributed by Barney Gale in gh-125866@footnote{https://github.com/python/cpython/issues/125866}.)
@end itemize

@node uuid,webbrowser,urllib,Improved modules
@anchor{whatsnew/3 14 uuid}@anchor{2c1}
@subsubsection uuid



@itemize *

@item 
Add support for UUID versions 6, 7, and 8 via @ref{2c2,,uuid6()},
@ref{2c3,,uuid7()}, and @ref{2c4,,uuid8()} respectively, as specified
in 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}.
(Contributed by Bénédikt Tran in gh-89083@footnote{https://github.com/python/cpython/issues/89083}.)

@item 
@ref{2c5,,NIL} and @ref{2c6,,MAX} are now available to represent the
Nil and Max UUID formats as defined by 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}.
(Contributed by Nick Pope in gh-128427@footnote{https://github.com/python/cpython/issues/128427}.)

@item 
Allow generating multiple UUIDs simultaneously on the command-line via
@ref{2c7,,python -m uuid --count}.
(Contributed by Simon Legner in gh-131236@footnote{https://github.com/python/cpython/issues/131236}.)
@end itemize

@node webbrowser,zipfile,uuid,Improved modules
@anchor{whatsnew/3 14 webbrowser}@anchor{2c8}
@subsubsection webbrowser



@itemize *

@item 
Names in the 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} environment variable can now refer to already
registered browsers for the @ref{11b,,webbrowser} module, instead of always
generating a new browser command.

This makes it possible to set 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} to the value of one of the
supported browsers on macOS.
@end itemize

@node zipfile,,webbrowser,Improved modules
@anchor{whatsnew/3 14 zipfile}@anchor{2c9}
@subsubsection zipfile



@itemize *

@item 
Added @ref{2ca,,ZipInfo._for_archive}, a method
to resolve suitable defaults for a @ref{2cb,,ZipInfo} object
as used by @ref{2cc,,ZipFile.writestr}.
(Contributed by Bénédikt Tran in gh-123424@footnote{https://github.com/python/cpython/issues/123424}.)

@item 
@ref{2cc,,ZipFile.writestr()} now respects the 
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH}
environment variable in order to better support reproducible builds.
(Contributed by Jiahao Li in gh-91279@footnote{https://github.com/python/cpython/issues/91279}.)
@end itemize

@c Add improved modules above alphabetically, not here at the end.

@node 最適化,削除,Improved modules,What's new in Python 3 14
@anchor{whatsnew/3 14 optimizations}@anchor{2cd}
@subsection 最適化



@itemize *

@item 
The import time for several standard library modules has been improved,
including @ref{6,,annotationlib}, @ref{9,,ast}, @ref{b,,asyncio}, @ref{f,,base64},
@ref{1a,,cmd}, @ref{2d,,csv}, @ref{67,,gettext}, @ref{81,,importlib.util}, @ref{8a,,locale},
@ref{93,,mimetypes}, @ref{a4,,optparse}, @ref{ab,,pickle}, @ref{b3,,pprint},
@ref{b5,,pstats}, @ref{c9,,shlex}, @ref{d1,,socket}, @ref{d8,,string}, @ref{dc,,subprocess},
@ref{f3,,threading}, @ref{102,,tomllib}, @ref{109,,types}, and @ref{137,,zipfile}.

(Contributed by Adam Turner, Bénédikt Tran, Chris Markiewicz, Eli Schwartz,
Hugo van Kemenade, Jelle Zijlstra, and others in gh-118761@footnote{https://github.com/python/cpython/issues/118761}.)

@item 
The interpreter now avoids some reference count modifications internally
when it's safe to do so.
This can lead to different values being returned from @ref{2ce,,sys.getrefcount()}
and @ref{2cf,,Py_REFCNT()} compared to previous versions of Python.
See @ref{2d0,,below} for details.
@end itemize

@menu
* asyncio: asyncio<2>. 
* base64:: 
* bdb:: 
* difflib: difflib<2>. 
* gc:: 
* io: io<2>. 
* pathlib: pathlib<2>. 
* pdb: pdb<2>. 
* textwrap:: 
* uuid: uuid<2>. 
* zlib:: 

@end menu

@node asyncio<2>,base64,,最適化
@anchor{whatsnew/3 14 id2}@anchor{2d1}
@subsubsection asyncio



@itemize *

@item 
Standard benchmark results have improved by 10-20% following the
implementation of a new per-thread doubly linked list
for @ref{1c7,,native tasks},
also reducing memory usage.
This enables external introspection tools such as
@ref{147,,python -m asyncio pstree}
to introspect the call graph of asyncio tasks running in all threads.
(Contributed by Kumar Aditya in gh-107803@footnote{https://github.com/python/cpython/issues/107803}.)

@item 
The module now has first class support for
@ref{1f4,,free-threading builds}.
This enables parallel execution of multiple event loops across
different threads, scaling linearly with the number of threads.
(Contributed by Kumar Aditya in gh-128002@footnote{https://github.com/python/cpython/issues/128002}.)
@end itemize

@node base64,bdb,asyncio<2>,最適化
@anchor{whatsnew/3 14 base64}@anchor{2d2}
@subsubsection base64



@itemize *

@item 
@ref{2d3,,b16decode()} is now up to six times faster.
(Contributed by Bénédikt Tran, Chris Markiewicz, and Adam Turner
in gh-118761@footnote{https://github.com/python/cpython/issues/118761}.)
@end itemize

@node bdb,difflib<2>,base64,最適化
@anchor{whatsnew/3 14 bdb}@anchor{2d4}
@subsubsection bdb



@itemize *

@item 
The basic debugger now has a @ref{e0,,sys.monitoring}-based backend,
which can be selected via the passing @code{'monitoring'}
to the @ref{2d5,,Bdb} class's new `backend' parameter.
(Contributed by Tian Gao in gh-124533@footnote{https://github.com/python/cpython/issues/124533}.)
@end itemize

@node difflib<2>,gc,bdb,最適化
@anchor{whatsnew/3 14 id3}@anchor{2d6}
@subsubsection difflib



@itemize *

@item 
The @ref{2d7,,IS_LINE_JUNK()} function is now up to twice as fast.
(Contributed by Adam Turner and Semyon Moroz in gh-130167@footnote{https://github.com/python/cpython/issues/130167}.)
@end itemize

@node gc,io<2>,difflib<2>,最適化
@anchor{whatsnew/3 14 gc}@anchor{2d8}
@subsubsection gc



@itemize *

@item 
The new @ref{152,,incremental garbage collector}
means that maximum pause times are reduced
by an order of magnitude or more for larger heaps.

Because of this optimization, the meaning of the results of
@ref{2d9,,get_threshold()} and @ref{2da,,set_threshold()} have changed,
along with @ref{2db,,get_count()} and @ref{2dc,,get_stats()}.


@itemize -

@item 
For backwards compatibility, @ref{2d9,,get_threshold()} continues to return
a three-item tuple.
The first value is the threshold for young collections, as before;
the second value determines the rate at which the old collection is scanned
(the default is 10, and higher values mean that the old collection
is scanned more slowly).
The third value is now meaningless and is always zero.

@item 
@ref{2da,,set_threshold()} now ignores any items after the second.

@item 
@ref{2db,,get_count()} and @ref{2dc,,get_stats()} continue to return
the same format of results.
The only difference is that instead of the results referring to
the young, aging and old generations,
the results refer to the young generation
and the aging and collecting spaces of the old generation.
@end itemize

In summary, code that attempted to manipulate the behavior of the cycle GC
may not work exactly as intended, but it is very unlikely to be harmful.
All other code will work just fine.

(Contributed by Mark Shannon in gh-108362@footnote{https://github.com/python/cpython/issues/108362}.)
@end itemize

@node io<2>,pathlib<2>,gc,最適化
@anchor{whatsnew/3 14 id4}@anchor{2dd}
@subsubsection io



@itemize *

@item 
Opening and reading files now executes fewer system calls.
Reading a small operating system cached file in full is up to 15% faster.
(Contributed by Cody Maloney and Victor Stinner
in gh-120754@footnote{https://github.com/python/cpython/issues/120754} and gh-90102@footnote{https://github.com/python/cpython/issues/90102}.)
@end itemize

@node pathlib<2>,pdb<2>,io<2>,最適化
@anchor{whatsnew/3 14 id5}@anchor{2de}
@subsubsection pathlib



@itemize *

@item 
@ref{2df,,Path.read_bytes} now uses unbuffered mode
to open files, which is between 9% and 17% faster to read in full.
(Contributed by Cody Maloney in gh-120754@footnote{https://github.com/python/cpython/issues/120754}.)
@end itemize

@node pdb<2>,textwrap,pathlib<2>,最適化
@anchor{whatsnew/3 14 id6}@anchor{2e0}
@subsubsection pdb



@itemize *

@item 
@ref{aa,,pdb} now supports two backends, based on either
@ref{2e1,,sys.settrace()} or @ref{e0,,sys.monitoring}.
Using the @ref{2e2,,pdb CLI} or @ref{271,,breakpoint()}
will always use the @ref{e0,,sys.monitoring} backend.
Explicitly instantiating @ref{273,,pdb.Pdb} and its derived classes
will use the @ref{2e1,,sys.settrace()} backend by default, which is configurable.
(Contributed by Tian Gao in gh-124533@footnote{https://github.com/python/cpython/issues/124533}.)
@end itemize

@node textwrap,uuid<2>,pdb<2>,最適化
@anchor{whatsnew/3 14 textwrap}@anchor{2e3}
@subsubsection textwrap



@itemize *

@item 
Optimize the @ref{1a9,,dedent()} function, improving performance by
an average of 2.4x, with larger improvements for bigger inputs,
and fix a bug with incomplete normalization of blank lines with whitespace
characters other than space and tab.
@end itemize

@node uuid<2>,zlib,textwrap,最適化
@anchor{whatsnew/3 14 id7}@anchor{2e4}
@subsubsection uuid



@itemize *

@item 
@ref{2e5,,uuid3()} and @ref{2e6,,uuid5()} are now both roughly 40% faster
for 16-byte names and 20% faster for 1024-byte names.
Performance for longer names remains unchanged.
(Contributed by Bénédikt Tran in gh-128150@footnote{https://github.com/python/cpython/issues/128150}.)

@item 
@ref{2e7,,uuid4()} is now c. 30% faster.
(Contributed by Bénédikt Tran in gh-128150@footnote{https://github.com/python/cpython/issues/128150}.)
@end itemize

@node zlib,,uuid<2>,最適化
@anchor{whatsnew/3 14 zlib}@anchor{2e8}
@subsubsection zlib



@itemize *

@item 
On Windows, zlib-ng@footnote{https://github.com/zlib-ng/zlib-ng}
is now used as the implementation of the @ref{139,,zlib} module
in the default binaries.
There are no known incompatibilities between @code{zlib-ng}
and the previously-used @code{zlib} implementation.
This should result in better performance at all compression levels.

It is worth noting that @code{zlib.Z_BEST_SPEED} (@code{1}) may result in
significantly less compression than the previous implementation,
whilst also significantly reducing the time taken to compress.

(Contributed by Steve Dower in gh-91349@footnote{https://github.com/python/cpython/issues/91349}.)
@end itemize

@node 削除,非推奨,最適化,What's new in Python 3 14
@anchor{whatsnew/3 14 removed}@anchor{2e9}
@subsection 削除


@menu
* argparse: argparse<2>. 
* ast: ast<2>. 
* asyncio: asyncio<3>. 
* email:: 
* importlib.abc: importlib abc. 
* itertools:: 
* pathlib: pathlib<3>. 
* pkgutil:: 
* pty:: 
* sqlite3:: 
* urllib: urllib<2>. 

@end menu

@node argparse<2>,ast<2>,,削除
@anchor{whatsnew/3 14 id8}@anchor{2ea}
@subsubsection argparse



@itemize *

@item 
Remove the `type', `choices', and `metavar' parameters
of @code{BooleanOptionalAction}.
These have been deprecated since Python 3.12.
(Contributed by Nikita Sobolev in gh-118805@footnote{https://github.com/python/cpython/issues/118805}.)

@item 
Calling @ref{2eb,,add_argument_group()}
on an argument group now raises a @ref{2ec,,ValueError}.
Similarly, @ref{2eb,,add_argument_group()}
or @ref{2ed,,add_mutually_exclusive_group()}
on a mutually exclusive group now both raise @ref{2ec,,ValueError}s.
This 'nesting' was never supported, often failed to work correctly,
and was unintentionally exposed through inheritance.
This functionality has been deprecated since Python 3.11.
(Contributed by Savannah Ostrowski in gh-127186@footnote{https://github.com/python/cpython/issues/127186}.)
@end itemize

@node ast<2>,asyncio<3>,argparse<2>,削除
@anchor{whatsnew/3 14 id9}@anchor{2ee}
@subsubsection ast



@itemize *

@item 
Remove the following classes, which have been deprecated aliases of
@ref{2ef,,Constant} since Python 3.8 and have emitted
deprecation warnings since Python 3.12:


@itemize *

@item 
@code{Bytes}

@item 
@code{Ellipsis}

@item 
@code{NameConstant}

@item 
@code{Num}

@item 
@code{Str}
@end itemize

As a consequence of these removals, user-defined @code{visit_Num}, @code{visit_Str},
@code{visit_Bytes}, @code{visit_NameConstant} and @code{visit_Ellipsis} methods
on custom @ref{2f0,,NodeVisitor} subclasses will no longer be called
when the @code{NodeVisitor} subclass is visiting an AST.
Define a @code{visit_Constant} method instead.

(Contributed by Alex Waygood in gh-119562@footnote{https://github.com/python/cpython/issues/119562}.)

@item 
Remove the following deprecated properties on @ref{2ef,,ast.Constant},
which were present for compatibility with the now-removed AST classes:


@itemize *

@item 
@code{Constant.n}

@item 
@code{Constant.s}
@end itemize

Use @code{Constant.value} instead.
(Contributed by Alex Waygood in gh-119562@footnote{https://github.com/python/cpython/issues/119562}.)
@end itemize

@node asyncio<3>,email,ast<2>,削除
@anchor{whatsnew/3 14 id10}@anchor{2f1}
@subsubsection asyncio



@itemize *

@item 
Remove the following classes, methods, and functions,
which have been deprecated since Python 3.12:


@itemize *

@item 
@code{AbstractChildWatcher}

@item 
@code{FastChildWatcher}

@item 
@code{MultiLoopChildWatcher}

@item 
@code{PidfdChildWatcher}

@item 
@code{SafeChildWatcher}

@item 
@code{ThreadedChildWatcher}

@item 
@code{AbstractEventLoopPolicy.get_child_watcher()}

@item 
@code{AbstractEventLoopPolicy.set_child_watcher()}

@item 
@code{get_child_watcher()}

@item 
@code{set_child_watcher()}
@end itemize

(Contributed by Kumar Aditya in gh-120804@footnote{https://github.com/python/cpython/issues/120804}.)

@item 
@ref{2f2,,asyncio.get_event_loop()} now raises a @ref{244,,RuntimeError}
if there is no current event loop,
and no longer implicitly creates an event loop.

(Contributed by Kumar Aditya in gh-126353@footnote{https://github.com/python/cpython/issues/126353}.)

@c TODO: move these patterns to the asyncio docs?
@c quite long for What's New

There's a few patterns that use @ref{2f2,,asyncio.get_event_loop()}, most
of them can be replaced with @ref{2f3,,asyncio.run()}.

If you're running an async function, simply use @ref{2f3,,asyncio.run()}.

Before:

@example
async def main():
    ...


loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
finally:
    loop.close()
@end example

After:

@example
async def main():
    ...

asyncio.run(main())
@end example

If you need to start something, for example, a server listening on a socket
and then run forever, use @ref{2f3,,asyncio.run()} and an
@ref{2f4,,asyncio.Event}.

Before:

@example
def start_server(loop): ...

loop = asyncio.get_event_loop()
try:
    start_server(loop)
    loop.run_forever()
finally:
    loop.close()
@end example

After:

@example
def start_server(loop): ...

async def main():
    start_server(asyncio.get_running_loop())
    await asyncio.Event().wait()

asyncio.run(main())
@end example

If you need to run something in an event loop, then run some blocking
code around it, use @ref{2f5,,asyncio.Runner}.

Before:

@example
async def operation_one(): ...
def blocking_code(): ...
async def operation_two(): ...

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(operation_one())
    blocking_code()
    loop.run_until_complete(operation_two())
finally:
    loop.close()
@end example

After:

@example
async def operation_one(): ...
def blocking_code(): ...
async def operation_two(): ...

with asyncio.Runner() as runner:
    runner.run(operation_one())
    blocking_code()
    runner.run(operation_two())
@end example
@end itemize

@node email,importlib abc,asyncio<3>,削除
@anchor{whatsnew/3 14 email}@anchor{2f6}
@subsubsection email



@itemize *

@item 
Remove @ref{2f7,,email.utils.localtime()}'s `isdst' parameter,
which was deprecated in and has been ignored since Python 3.12.
(Contributed by Hugo van Kemenade in gh-118798@footnote{https://github.com/python/cpython/issues/118798}.)
@end itemize

@node importlib abc,itertools,email,削除
@anchor{whatsnew/3 14 importlib-abc}@anchor{2f8}
@subsubsection importlib.abc



@itemize *

@item 
Remove deprecated @ref{7c,,importlib.abc} classes:


@itemize *

@item 
@code{ResourceReader}
(use @ref{2f9,,TraversableResources})

@item 
@code{Traversable}
(use @ref{2fa,,Traversable})

@item 
@code{TraversableResources}
(use @ref{2f9,,TraversableResources})
@end itemize

(Contributed by Jason R. Coombs and Hugo van Kemenade in gh-93963@footnote{https://github.com/python/cpython/issues/93963}.)
@end itemize

@node itertools,pathlib<3>,importlib abc,削除
@anchor{whatsnew/3 14 itertools}@anchor{2fb}
@subsubsection itertools



@itemize *

@item 
Remove support for copy, deepcopy, and pickle operations
from @ref{85,,itertools} iterators.
These have emitted a @ref{1a3,,DeprecationWarning} since Python 3.12.
(Contributed by Raymond Hettinger in gh-101588@footnote{https://github.com/python/cpython/issues/101588}.)
@end itemize

@node pathlib<3>,pkgutil,itertools,削除
@anchor{whatsnew/3 14 id11}@anchor{2fc}
@subsubsection pathlib



@itemize *

@item 
Remove support for passing additional keyword arguments
to @ref{266,,Path}.
In previous versions, any such arguments are ignored.
(Contributed by Barney Gale in gh-74033@footnote{https://github.com/python/cpython/issues/74033}.)

@item 
Remove support for passing additional positional arguments to
@ref{2fd,,PurePath.relative_to()} and @ref{2fe,,is_relative_to()}.
In previous versions, any such arguments are joined onto `other'.
(Contributed by Barney Gale in gh-78707@footnote{https://github.com/python/cpython/issues/78707}.)
@end itemize

@node pkgutil,pty,pathlib<3>,削除
@anchor{whatsnew/3 14 pkgutil}@anchor{2ff}
@subsubsection pkgutil



@itemize *

@item 
Remove the @code{get_loader()} and @code{find_loader()} functions,
which have been deprecated since Python 3.12.
(Contributed by Bénédikt Tran in gh-97850@footnote{https://github.com/python/cpython/issues/97850}.)
@end itemize

@node pty,sqlite3,pkgutil,削除
@anchor{whatsnew/3 14 pty}@anchor{300}
@subsubsection pty



@itemize *

@item 
Remove the @code{master_open()} and @code{slave_open()} functions,
which have been deprecated since Python 3.12.
Use @ref{301,,pty.openpty()} instead.
(Contributed by Nikita Sobolev in gh-118824@footnote{https://github.com/python/cpython/issues/118824}.)
@end itemize

@node sqlite3,urllib<2>,pty,削除
@anchor{whatsnew/3 14 sqlite3}@anchor{302}
@subsubsection sqlite3



@itemize *

@item 
Remove @code{version} and @code{version_info} from
the @ref{d4,,sqlite3} module;
use @ref{303,,sqlite_version} and @ref{304,,sqlite_version_info}
for the actual version number of the runtime SQLite library.
(Contributed by Hugo van Kemenade in gh-118924@footnote{https://github.com/python/cpython/issues/118924}.)

@item 
Using a sequence of parameters with named placeholders now
raises a @ref{305,,ProgrammingError},
having been deprecated since Python 3.12.
(Contributed by Erlend E. Aasland in gh-118928@footnote{https://github.com/python/cpython/issues/118928} and gh-101693@footnote{https://github.com/python/cpython/issues/101693}.)
@end itemize

@node urllib<2>,,sqlite3,削除
@anchor{whatsnew/3 14 id12}@anchor{306}
@subsubsection urllib



@itemize *

@item 
Remove the @code{Quoter} class from @ref{110,,urllib.parse},
which has been deprecated since Python 3.11.
(Contributed by Nikita Sobolev in gh-118827@footnote{https://github.com/python/cpython/issues/118827}.)

@item 
Remove the @code{URLopener} and @code{FancyURLopener} classes
from @ref{111,,urllib.request},
which have been deprecated since Python 3.3.

@code{myopener.open()} can be replaced with @ref{307,,urlopen()}.
@code{myopener.retrieve()} can be replaced with
@ref{308,,urlretrieve()}.
Customisations to the opener classes can be replaced by passing
customized handlers to @ref{309,,build_opener()}.
(Contributed by Barney Gale in gh-84850@footnote{https://github.com/python/cpython/issues/84850}.)
@end itemize

@node 非推奨,CPython バイトコードの変更,削除,What's new in Python 3 14
@anchor{whatsnew/3 14 deprecated}@anchor{30a}
@subsection 非推奨


@menu
* New deprecations:: 
* Pending removal in Python 3.15: Pending removal in Python 3 15. 
* Pending removal in Python 3.16: Pending removal in Python 3 16. 
* Pending removal in Python 3.17: Pending removal in Python 3 17. 
* Pending removal in Python 3.18: Pending removal in Python 3 18. 
* Pending removal in Python 3.19: Pending removal in Python 3 19. 
* Pending removal in future versions:: 

@end menu

@node New deprecations,Pending removal in Python 3 15,,非推奨
@anchor{whatsnew/3 14 new-deprecations}@anchor{30b}
@subsubsection New deprecations



@itemize *

@item 
Passing a complex number as the `real' or `imag' argument in the
@ref{197,,complex()} constructor is now deprecated;
complex numbers should only be passed as a single positional argument.
(Contributed by Serhiy Storchaka in gh-109218@footnote{https://github.com/python/cpython/issues/109218}.)

@item 
@ref{7,,argparse}:


@itemize *

@item 
Passing the undocumented keyword argument `prefix_chars' to the
@ref{2eb,,add_argument_group()} method is now deprecated.
(Contributed by Savannah Ostrowski in gh-125563@footnote{https://github.com/python/cpython/issues/125563}.)

@item 
Deprecated the @ref{30c,,argparse.FileType} type converter.
Anything relating to resource management should be handled
downstream, after the arguments have been parsed.
(Contributed by Serhiy Storchaka in gh-58032@footnote{https://github.com/python/cpython/issues/58032}.)
@end itemize

@item 
@ref{b,,asyncio}:


@itemize *

@item 
The @code{asyncio.iscoroutinefunction()} is now deprecated
and will be removed in Python 3.16;
use @ref{30d,,inspect.iscoroutinefunction()} instead.
(Contributed by Jiahao Li and Kumar Aditya in gh-122875@footnote{https://github.com/python/cpython/issues/122875}.)

@item 
The @ref{b,,asyncio} policy system is deprecated
and will be removed in Python 3.16.
In particular, the following classes and functions are deprecated:


@itemize *

@item 
@ref{30e,,asyncio.AbstractEventLoopPolicy}

@item 
@ref{30f,,asyncio.DefaultEventLoopPolicy}

@item 
@ref{310,,asyncio.WindowsSelectorEventLoopPolicy}

@item 
@ref{311,,asyncio.WindowsProactorEventLoopPolicy}

@item 
@ref{312,,asyncio.get_event_loop_policy()}

@item 
@ref{313,,asyncio.set_event_loop_policy()}
@end itemize

Users should use @ref{2f3,,asyncio.run()} or @ref{2f5,,asyncio.Runner} with
the `loop_factory' argument to use the desired event loop implementation.

For example, to use @ref{314,,asyncio.SelectorEventLoop} on Windows:

@example
import asyncio

async def main():
    ...

asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
@end example

(Contributed by Kumar Aditya in gh-127949@footnote{https://github.com/python/cpython/issues/127949}.)
@end itemize

@item 
@ref{1c,,codecs}:
The @ref{315,,codecs.open()} function is now deprecated,
and will be removed in a future version of Python.
Use @ref{316,,open()} instead.
(Contributed by Inada Naoki in gh-133036@footnote{https://github.com/python/cpython/issues/133036}.)

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
On non-Windows platforms, setting @ref{317,,Structure._pack_} to use a
MSVC-compatible default memory layout is now deprecated in favor of setting
@ref{1e7,,Structure._layout_} to @code{'ms'}, and will be removed in Python 3.19.
(Contributed by Petr Viktorin in gh-131747@footnote{https://github.com/python/cpython/issues/131747}.)

@item 
Calling @ref{1f1,,ctypes.POINTER()} on a string is now deprecated.
Use @ref{318,,incomplete types}
for self-referential structures.
Also, the internal @code{ctypes._pointer_type_cache} is deprecated.
See @ref{1f1,,ctypes.POINTER()} for updated implementation details.
(Contributed by Sergey Myrianov in gh-100926@footnote{https://github.com/python/cpython/issues/100926}.)
@end itemize

@item 
@ref{63,,functools}:
Calling the Python implementation of @ref{21a,,functools.reduce()} with `function'
or `sequence' as keyword arguments is now deprecated;
the parameters will be made positional-only in Python 3.16.
(Contributed by Kirill Podoprigora in gh-121676@footnote{https://github.com/python/cpython/issues/121676}.)

@item 
@ref{8b,,logging}:
Support for custom logging handlers with the `strm' argument
is now deprecated and scheduled for removal in Python 3.16.
Define handlers with the `stream' argument instead.
(Contributed by Mariusz Felisiak in gh-115032@footnote{https://github.com/python/cpython/issues/115032}.)

@item 
@ref{93,,mimetypes}:
Valid extensions are either empty or must start with '.' for
@ref{319,,mimetypes.MimeTypes.add_type()}.
Undotted extensions are deprecated and will
raise a @ref{2ec,,ValueError} in Python 3.16.
(Contributed by Hugo van Kemenade in gh-75223@footnote{https://github.com/python/cpython/issues/75223}.)

@item 
@code{nturl2path}:
This module is now deprecated. Call @ref{2bd,,urllib.request.url2pathname()}
and @ref{2bf,,pathname2url()} instead.
(Contributed by Barney Gale in gh-125866@footnote{https://github.com/python/cpython/issues/125866}.)

@item 
@ref{a5,,os}:
The @ref{31a,,os.popen()} and @ref{31b,,os.spawn*} functions
are now @ref{23d,,soft deprecated}.
They should no longer be used to write new code.
The @ref{dc,,subprocess} module is recommended instead.
(Contributed by Victor Stinner in gh-120743@footnote{https://github.com/python/cpython/issues/120743}.)

@item 
@ref{a8,,pathlib}:
@code{pathlib.PurePath.as_uri()} is now deprecated
and scheduled for removal in Python 3.19.
Use @ref{31c,,pathlib.Path.as_uri()} instead.
(Contributed by Barney Gale in gh-123599@footnote{https://github.com/python/cpython/issues/123599}.)

@item 
@ref{aa,,pdb}:
The undocumented @code{pdb.Pdb.curframe_locals} attribute is now a deprecated
read-only property, which will be removed in a future version of Python.
The low overhead dynamic frame locals access added in Python 3.13 by 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}
means the frame locals cache reference previously stored in this attribute
is no longer needed. Derived debuggers should access
@code{pdb.Pdb.curframe.f_locals} directly in Python 3.13 and later versions.
(Contributed by Tian Gao in gh-124369@footnote{https://github.com/python/cpython/issues/124369} and gh-125951@footnote{https://github.com/python/cpython/issues/125951}.)

@item 
@ref{de,,symtable}:
Deprecate @ref{31d,,symtable.Class.get_methods()} due to the lack of interest,
scheduled for removal in Python 3.16.
(Contributed by Bénédikt Tran in gh-119698@footnote{https://github.com/python/cpython/issues/119698}.)

@item 
@ref{f6,,tkinter}:
The @code{tkinter.Variable} methods @code{trace_variable()},
@code{trace_vdelete()} and @code{trace_vinfo()} are now deprecated.
Use @code{trace_add()}, @code{trace_remove()} and @code{trace_info()} instead.
(Contributed by Serhiy Storchaka in gh-120220@footnote{https://github.com/python/cpython/issues/120220}.)

@item 
@ref{110,,urllib.parse}:
Accepting objects with false values (like @code{0} and @code{[]}) except empty
strings, bytes-like objects and @code{None} in @ref{31e,,parse_qsl()}
and @ref{31f,,parse_qs()} is now deprecated.
(Contributed by Serhiy Storchaka in gh-116897@footnote{https://github.com/python/cpython/issues/116897}.)
@end itemize

@c Add deprecations above alphabetically, not here at the end.

@node Pending removal in Python 3 15,Pending removal in Python 3 16,New deprecations,非推奨
@anchor{whatsnew/3 14 pending-removal-in-python-3-15}@anchor{320}
@subsubsection Pending removal in Python 3.15



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{321,,__cached__} on a module while
failing to set @ref{322,,__spec__.cached}
is deprecated. In Python 3.15, @code{__cached__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})

@item 
Setting @ref{323,,__package__} on a module while
failing to set @ref{324,,__spec__.parent}
is deprecated. In Python 3.15, @code{__package__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})
@end itemize

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
The undocumented @code{ctypes.SetPointerType()} function
has been deprecated since Python 3.13.
@end itemize

@item 
@ref{76,,http.server}:


@itemize *

@item 
The obsolete and rarely used @ref{325,,CGIHTTPRequestHandler}
has been deprecated since Python 3.13.
No direct replacement exists.
`Anything' is better than CGI to interface
a web server with a request handler.

@item 
The @code{--cgi} flag to the @code{python -m http.server}
command-line interface has been deprecated since Python 3.13.
@end itemize

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@code{load_module()} method: use @code{exec_module()} instead.
@end itemize

@item 
@ref{8a,,locale}:


@itemize *

@item 
The @ref{326,,getdefaultlocale()} function
has been deprecated since Python 3.11.
Its removal was originally planned for Python 3.13 (gh-90817@footnote{https://github.com/python/cpython/issues/90817}),
but has been postponed to Python 3.15.
Use @ref{327,,getlocale()}, @ref{328,,setlocale()},
and @ref{329,,getencoding()} instead.
(Contributed by Hugo van Kemenade in gh-111187@footnote{https://github.com/python/cpython/issues/111187}.)
@end itemize

@item 
@ref{a8,,pathlib}:


@itemize *

@item 
@ref{32a,,PurePath.is_reserved()}
has been deprecated since Python 3.13.
Use @ref{32b,,os.path.isreserved()} to detect reserved paths on Windows.
@end itemize

@item 
@ref{af,,platform}:


@itemize *

@item 
@ref{32c,,java_ver()} has been deprecated since Python 3.13.
This function is only useful for Jython support, has a confusing API,
and is largely untested.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The `check_home' argument of @ref{32d,,sysconfig.is_python_build()} has been
deprecated since Python 3.12.
@end itemize

@item 
@ref{f3,,threading}:


@itemize *

@item 
@ref{32e,,RLock()} will take no arguments in Python 3.15.
Passing any arguments has been deprecated since Python 3.14,
as the Python version does not permit any arguments,
but the C version allows any number of positional or keyword arguments,
ignoring every argument.
@end itemize

@item 
@ref{109,,types}:


@itemize *

@item 
@ref{32f,,types.CodeType}: Accessing @ref{330,,co_lnotab} was
deprecated in 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/}
since 3.10 and was planned to be removed in 3.12,
but it only got a proper @ref{1a3,,DeprecationWarning} in 3.12.
May be removed in 3.15.
(Contributed by Nikita Sobolev in gh-101866@footnote{https://github.com/python/cpython/issues/101866}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize *

@item 
The undocumented keyword argument syntax for creating
@ref{331,,NamedTuple} classes
(for example, @code{Point = NamedTuple("Point", x=int, y=int)})
has been deprecated since Python 3.13.
Use the class-based syntax or the functional syntax instead.

@item 
When using the functional syntax of @ref{332,,TypedDict}s, failing
to pass a value to the `fields' parameter (@code{TD = TypedDict("TD")}) or
passing @code{None} (@code{TD = TypedDict("TD", None)}) has been deprecated
since Python 3.13.
Use @code{class TD(TypedDict): pass} or @code{TD = TypedDict("TD", @{@})}
to create a TypedDict with zero field.

@item 
The @ref{333,,typing.no_type_check_decorator()} decorator function
has been deprecated since Python 3.13.
After eight years in the @ref{10a,,typing} module,
it has yet to be supported by any major type checker.
@end itemize

@item 
@ref{119,,wave}:


@itemize *

@item 
The @ref{334,,getmark()}, @code{setmark()},
and @ref{335,,getmarkers()} methods of
the @ref{336,,Wave_read} and @ref{337,,Wave_write} classes
have been deprecated since Python 3.13.
@end itemize

@item 
@ref{138,,zipimport}:


@itemize *

@item 
@ref{338,,load_module()} has been deprecated since
Python 3.10. Use @ref{339,,exec_module()} instead.
(Contributed by Jiahao Li in gh-125746@footnote{https://github.com/python/cpython/issues/125746}.)
@end itemize
@end itemize

@node Pending removal in Python 3 16,Pending removal in Python 3 17,Pending removal in Python 3 15,非推奨
@anchor{whatsnew/3 14 pending-removal-in-python-3-16}@anchor{33a}
@subsubsection Pending removal in Python 3.16



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{33b,,__loader__} on a module while
failing to set @ref{33c,,__spec__.loader}
is deprecated. In Python 3.16, @code{__loader__} will cease to be set or
taken into consideration by the import system or the standard library.
@end itemize

@item 
@ref{8,,array}:


@itemize *

@item 
The @code{'u'} format code (@code{wchar_t})
has been deprecated in documentation since Python 3.3
and at runtime since Python 3.13.
Use the @code{'w'} format code (@ref{33d,,Py_UCS4})
for Unicode characters instead.
@end itemize

@item 
@ref{b,,asyncio}:


@itemize *

@item 
@code{asyncio.iscoroutinefunction()} is deprecated
and will be removed in Python 3.16;
use @ref{30d,,inspect.iscoroutinefunction()} instead.
(Contributed by Jiahao Li and Kumar Aditya in gh-122875@footnote{https://github.com/python/cpython/issues/122875}.)

@item 
@ref{b,,asyncio} policy system is deprecated and will be removed in Python 3.16.
In particular, the following classes and functions are deprecated:


@itemize *

@item 
@ref{30e,,asyncio.AbstractEventLoopPolicy}

@item 
@ref{30f,,asyncio.DefaultEventLoopPolicy}

@item 
@ref{310,,asyncio.WindowsSelectorEventLoopPolicy}

@item 
@ref{311,,asyncio.WindowsProactorEventLoopPolicy}

@item 
@ref{312,,asyncio.get_event_loop_policy()}

@item 
@ref{313,,asyncio.set_event_loop_policy()}
@end itemize

Users should use @ref{2f3,,asyncio.run()} or @ref{2f5,,asyncio.Runner} with
`loop_factory' to use the desired event loop implementation.

For example, to use @ref{314,,asyncio.SelectorEventLoop} on Windows:

@example
import asyncio

async def main():
    ...

asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
@end example

(Contributed by Kumar Aditya in gh-127949@footnote{https://github.com/python/cpython/issues/127949}.)
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Bitwise inversion on boolean types, @code{~True} or @code{~False}
has been deprecated since Python 3.12,
as it produces surprising and unintuitive results (@code{-2} and @code{-1}).
Use @code{not x} instead for the logical negation of a Boolean.
In the rare case that you need the bitwise inversion of
the underlying integer, convert to @code{int} explicitly (@code{~int(x)}).
@end itemize

@item 
@ref{63,,functools}:


@itemize *

@item 
Calling the Python implementation of @ref{21a,,functools.reduce()} with `function'
or `sequence' as keyword arguments has been deprecated since Python 3.14.
@end itemize

@item 
@ref{8b,,logging}:

Support for custom logging handlers with the `strm' argument is deprecated
and scheduled for removal in Python 3.16. Define handlers with the `stream'
argument instead. (Contributed by Mariusz Felisiak in gh-115032@footnote{https://github.com/python/cpython/issues/115032}.)

@item 
@ref{93,,mimetypes}:


@itemize *

@item 
Valid extensions start with a '.' or are empty for
@ref{319,,mimetypes.MimeTypes.add_type()}.
Undotted extensions are deprecated and will
raise a @ref{2ec,,ValueError} in Python 3.16.
(Contributed by Hugo van Kemenade in gh-75223@footnote{https://github.com/python/cpython/issues/75223}.)
@end itemize

@item 
@ref{ca,,shutil}:


@itemize *

@item 
The @code{ExecError} exception
has been deprecated since Python 3.14.
It has not been used by any function in @code{shutil} since Python 3.4,
and is now an alias of @ref{244,,RuntimeError}.
@end itemize

@item 
@ref{de,,symtable}:


@itemize *

@item 
The @ref{31d,,Class.get_methods} method
has been deprecated since Python 3.14.
@end itemize

@item 
@ref{df,,sys}:


@itemize *

@item 
The @ref{33e,,_enablelegacywindowsfsencoding()} function
has been deprecated since Python 3.13.
Use the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} environment variable instead.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The @code{sysconfig.expand_makefile_vars()} function
has been deprecated since Python 3.14.
Use the @code{vars} argument of @ref{340,,sysconfig.get_paths()} instead.
@end itemize

@item 
@ref{e4,,tarfile}:


@itemize *

@item 
The undocumented and unused @code{TarFile.tarfile} attribute
has been deprecated since Python 3.13.
@end itemize
@end itemize

@node Pending removal in Python 3 17,Pending removal in Python 3 18,Pending removal in Python 3 16,非推奨
@anchor{whatsnew/3 14 pending-removal-in-python-3-17}@anchor{341}
@subsubsection Pending removal in Python 3.17



@itemize *

@item 
@ref{1f,,collections.abc}:


@itemize -

@item 
@ref{342,,collections.abc.ByteString} is scheduled for removal in Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize -

@item 
Before Python 3.14, old-style unions were implemented using the private class
@code{typing._UnionGenericAlias}. This class is no longer needed for the implementation,
but it has been retained for backward compatibility, with removal scheduled for Python
3.17. Users should use documented introspection helpers like @ref{2ab,,typing.get_origin()}
and @ref{2ac,,typing.get_args()} instead of relying on private implementation details.

@item 
@ref{345,,typing.ByteString}, deprecated since Python 3.9, is scheduled for removal in
Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize
@end itemize

@node Pending removal in Python 3 18,Pending removal in Python 3 19,Pending removal in Python 3 17,非推奨
@anchor{whatsnew/3 14 pending-removal-in-python-3-18}@anchor{346}
@subsubsection Pending removal in Python 3.18



@itemize *

@item 
@ref{3a,,decimal}:


@itemize *

@item 
The non-standard and undocumented @ref{1fe,,Decimal} format
specifier @code{'N'}, which is only supported in the @code{decimal} module's
C implementation, has been deprecated since Python 3.13.
(Contributed by Serhiy Storchaka in gh-89902@footnote{https://github.com/python/cpython/issues/89902}.)
@end itemize
@end itemize

@node Pending removal in Python 3 19,Pending removal in future versions,Pending removal in Python 3 18,非推奨
@anchor{whatsnew/3 14 pending-removal-in-python-3-19}@anchor{347}
@subsubsection Pending removal in Python 3.19



@itemize *

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
Implicitly switching to the MSVC-compatible struct layout by setting
@ref{317,,_pack_} but not @ref{1e7,,_layout_}
on non-Windows platforms.
@end itemize
@end itemize

@node Pending removal in future versions,,Pending removal in Python 3 19,非推奨
@anchor{whatsnew/3 14 pending-removal-in-future-versions}@anchor{348}
@subsubsection Pending removal in future versions


The following APIs will be removed in the future,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{7,,argparse}:


@itemize *

@item 
Nesting argument groups and nesting mutually exclusive
groups are deprecated.

@item 
Passing the undocumented keyword argument `prefix_chars' to
@ref{2eb,,add_argument_group()} is now
deprecated.

@item 
The @ref{30c,,argparse.FileType} type converter is deprecated.
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Generators: @code{throw(type, exc, tb)} and @code{athrow(type, exc, tb)}
signature is deprecated: use @code{throw(exc)} and @code{athrow(exc)} instead,
the single argument signature.

@item 
Currently Python accepts numeric literals immediately followed by keywords,
for example @code{0in x}, @code{1or x}, @code{0if 1else 2}.  It allows confusing and
ambiguous expressions like @code{[0x1for x in y]} (which can be interpreted as
@code{[0x1 for x in y]} or @code{[0x1f or x in y]}).  A syntax warning is raised
if the numeric literal is immediately followed by one of keywords
@ref{349,,and}, @ref{17c,,else}, @ref{34a,,for}, @ref{181,,if},
@ref{34b,,in}, @ref{34c,,is} and @ref{34d,,or}.  In a future release it
will be changed to a syntax error. (gh-87999@footnote{https://github.com/python/cpython/issues/87999})

@item 
Support for @code{__index__()} and @code{__int__()} method returning non-int type:
these methods will be required to return an instance of a strict subclass of
@ref{19b,,int}.

@item 
Support for @code{__float__()} method returning a strict subclass of
@ref{196,,float}: these methods will be required to return an instance of
@ref{196,,float}.

@item 
Support for @code{__complex__()} method returning a strict subclass of
@ref{197,,complex}: these methods will be required to return an instance of
@ref{197,,complex}.

@item 
Passing a complex number as the `real' or `imag' argument in the
@ref{197,,complex()} constructor is now deprecated; it should only be passed
as a single positional argument.
(Contributed by Serhiy Storchaka in gh-109218@footnote{https://github.com/python/cpython/issues/109218}.)
@end itemize

@item 
@ref{15,,calendar}: @code{calendar.January} and @code{calendar.February} constants are
deprecated and replaced by @ref{34e,,calendar.JANUARY} and
@ref{34f,,calendar.FEBRUARY}.
(Contributed by Prince Roshan in gh-103636@footnote{https://github.com/python/cpython/issues/103636}.)

@item 
@ref{1c,,codecs}: use @ref{316,,open()} instead of @ref{315,,codecs.open()}. (gh-133038@footnote{https://github.com/python/cpython/issues/133038})

@item 
@ref{330,,codeobject.co_lnotab}: use the @ref{350,,codeobject.co_lines()} method
instead.

@item 
@ref{34,,datetime}:


@itemize *

@item 
@ref{351,,utcnow()}:
use @code{datetime.datetime.now(tz=datetime.UTC)}.

@item 
@ref{352,,utcfromtimestamp()}:
use @code{datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)}.
@end itemize

@item 
@ref{67,,gettext}: Plural value must be an integer.

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@ref{353,,cache_from_source()} `debug_override' parameter is
deprecated: use the `optimization' parameter instead.
@end itemize

@item 
@ref{7e,,importlib.metadata}:


@itemize *

@item 
@code{EntryPoints} tuple interface.

@item 
Implicit @code{None} on return values.
@end itemize

@item 
@ref{8b,,logging}: the @code{warn()} method has been deprecated
since Python 3.3, use @ref{354,,warning()} instead.

@item 
@ref{8f,,mailbox}: Use of StringIO input and text mode is deprecated, use
BytesIO and binary mode instead.

@item 
@ref{a5,,os}: Calling @ref{355,,os.register_at_fork()} in multi-threaded process.

@item 
@code{pydoc.ErrorDuringImport}: A tuple value for `exc_info' parameter is
deprecated, use an exception instance.

@item 
@ref{be,,re}: More strict rules are now applied for numerical group references
and group names in regular expressions.  Only sequence of ASCII digits is now
accepted as a numerical reference.  The group name in bytes patterns and
replacement strings can now only contain ASCII letters and digits and
underscore.
(Contributed by Serhiy Storchaka in gh-91760@footnote{https://github.com/python/cpython/issues/91760}.)

@item 
@code{sre_compile}, @code{sre_constants} and @code{sre_parse} modules.

@item 
@ref{ca,,shutil}: @ref{356,,rmtree()}'s `onerror' parameter is deprecated in
Python 3.12; use the `onexc' parameter instead.

@item 
@ref{d5,,ssl} options and protocols:


@itemize *

@item 
@ref{357,,ssl.SSLContext} without protocol argument is deprecated.

@item 
@ref{357,,ssl.SSLContext}: @ref{358,,set_npn_protocols()} and
@code{selected_npn_protocol()} are deprecated: use ALPN
instead.

@item 
@code{ssl.OP_NO_SSL*} options

@item 
@code{ssl.OP_NO_TLS*} options

@item 
@code{ssl.PROTOCOL_SSLv3}

@item 
@code{ssl.PROTOCOL_TLS}

@item 
@code{ssl.PROTOCOL_TLSv1}

@item 
@code{ssl.PROTOCOL_TLSv1_1}

@item 
@code{ssl.PROTOCOL_TLSv1_2}

@item 
@code{ssl.TLSVersion.SSLv3}

@item 
@code{ssl.TLSVersion.TLSv1}

@item 
@code{ssl.TLSVersion.TLSv1_1}
@end itemize

@item 
@ref{f3,,threading} methods:


@itemize *

@item 
@code{threading.Condition.notifyAll()}: use @ref{359,,notify_all()}.

@item 
@code{threading.Event.isSet()}: use @ref{35a,,is_set()}.

@item 
@code{threading.Thread.isDaemon()}, @ref{35b,,threading.Thread.setDaemon()}:
use @ref{35c,,threading.Thread.daemon} attribute.

@item 
@code{threading.Thread.getName()}, @ref{35d,,threading.Thread.setName()}:
use @ref{2a0,,threading.Thread.name} attribute.

@item 
@code{threading.currentThread()}: use @ref{35e,,threading.current_thread()}.

@item 
@code{threading.activeCount()}: use @ref{35f,,threading.active_count()}.
@end itemize

@item 
@ref{360,,typing.Text} (gh-92332@footnote{https://github.com/python/cpython/issues/92332}).

@item 
The internal class @code{typing._UnionGenericAlias} is no longer used to implement
@ref{2a8,,typing.Union}. To preserve compatibility with users using this private
class, a compatibility shim will be provided until at least Python 3.17. (Contributed by
Jelle Zijlstra in gh-105499@footnote{https://github.com/python/cpython/issues/105499}.)

@item 
@ref{361,,unittest.IsolatedAsyncioTestCase}: it is deprecated to return a value
that is not @code{None} from a test case.

@item 
@ref{110,,urllib.parse} deprecated functions: @ref{362,,urlparse()} instead


@itemize *

@item 
@code{splitattr()}

@item 
@code{splithost()}

@item 
@code{splitnport()}

@item 
@code{splitpasswd()}

@item 
@code{splitport()}

@item 
@code{splitquery()}

@item 
@code{splittag()}

@item 
@code{splittype()}

@item 
@code{splituser()}

@item 
@code{splitvalue()}

@item 
@code{to_bytes()}
@end itemize

@item 
@ref{11e,,wsgiref}: @code{SimpleHandler.stdout.write()} should not do partial
writes.

@item 
@ref{12b,,xml.etree.ElementTree}: Testing the truth value of an
@ref{363,,Element} is deprecated. In a future release it
will always return @code{True}. Prefer explicit @code{len(elem)} or
@code{elem is not None} tests instead.

@item 
@ref{292,,sys._clear_type_cache()} is deprecated:
use @ref{364,,sys._clear_internal_caches()} instead.
@end itemize

@node CPython バイトコードの変更,C API changes,非推奨,What's new in Python 3 14
@anchor{whatsnew/3 14 cpython-bytecode-changes}@anchor{365}
@subsection CPython バイトコードの変更



@itemize *

@item 
Replaced the opcode @code{BINARY_SUBSCR} by the @ref{366,,BINARY_OP}
opcode with the @code{NB_SUBSCR} oparg.
(Contributed by Irit Katriel in gh-100239@footnote{https://github.com/python/cpython/issues/100239}.)

@item 
Add the @ref{367,,BUILD_INTERPOLATION} and @ref{368,,BUILD_TEMPLATE}
opcodes to construct new @ref{16b,,Interpolation}
and @ref{16a,,Template} instances, respectively.
(Contributed by Lysandros Nikolaou and others in gh-132661@footnote{https://github.com/python/cpython/issues/132661};
see also @ref{144,,PEP 750; Template strings}).

@item 
Remove the @code{BUILD_CONST_KEY_MAP} opcode.
Use @ref{369,,BUILD_MAP} instead.
(Contributed by Mark Shannon in gh-122160@footnote{https://github.com/python/cpython/issues/122160}.)

@item 
Replace the @code{LOAD_ASSERTION_ERROR} opcode with
@ref{36a,,LOAD_COMMON_CONSTANT} and add support for loading
@ref{36b,,NotImplementedError}.

@item 
Add the @ref{36c,,LOAD_FAST_BORROW} and @ref{36d,,LOAD_FAST_BORROW_LOAD_FAST_BORROW}
opcodes to reduce reference counting overhead when the interpreter can prove
that the reference in the frame outlives the reference loaded onto the stack.
(Contributed by Matt Page in gh-130704@footnote{https://github.com/python/cpython/issues/130704}.)

@item 
Add the @ref{36e,,LOAD_SMALL_INT} opcode, which pushes a small integer
equal to the @code{oparg} to the stack.
The @code{RETURN_CONST} opcode is removed as it is no longer used.
(Contributed by Mark Shannon in gh-125837@footnote{https://github.com/python/cpython/issues/125837}.)

@item 
Add the new @ref{36f,,LOAD_SPECIAL} instruction.
Generate code for @ref{186,,with} and @ref{185,,async with} statements
using the new instruction.
Removed the @code{BEFORE_WITH} and @code{BEFORE_ASYNC_WITH} instructions.
(Contributed by Mark Shannon in gh-120507@footnote{https://github.com/python/cpython/issues/120507}.)

@item 
Add the @ref{370,,POP_ITER} opcode to support 'virtual' iterators.
(Contributed by Mark Shannon in gh-132554@footnote{https://github.com/python/cpython/issues/132554}.)
@end itemize

@menu
* Pseudo-instructions:: 

@end menu

@node Pseudo-instructions,,,CPython バイトコードの変更
@anchor{whatsnew/3 14 pseudo-instructions}@anchor{371}
@subsubsection Pseudo-instructions



@itemize *

@item 
Add the @code{ANNOTATIONS_PLACEHOLDER} pseudo instruction
to support partially executed module-level annotations with
@ref{145,,deferred evaluation of annotations}.
(Contributed by Jelle Zijlstra in gh-130907@footnote{https://github.com/python/cpython/issues/130907}.)

@item 
Add the @code{BINARY_OP_EXTEND} pseudo instruction,
which executes a pair of functions (guard and specialization functions)
accessed from the inline cache.
(Contributed by Irit Katriel in gh-100239@footnote{https://github.com/python/cpython/issues/100239}.)

@item 
Add three specializations for @ref{372,,CALL_KW};
@code{CALL_KW_PY} for calls to Python functions,
@code{CALL_KW_BOUND_METHOD} for calls to bound methods, and
@code{CALL_KW_NON_PY} for all other calls.
(Contributed by Mark Shannon in gh-118093@footnote{https://github.com/python/cpython/issues/118093}.)

@item 
Add the @ref{373,,JUMP_IF_TRUE} and @ref{374,,JUMP_IF_FALSE} pseudo instructions,
conditional jumps which do not impact the stack.
Replaced by the sequence @code{COPY 1}, @code{TO_BOOL}, @code{POP_JUMP_IF_TRUE/FALSE}.
(Contributed by Irit Katriel in gh-124285@footnote{https://github.com/python/cpython/issues/124285}.)

@item 
Add the @code{LOAD_CONST_MORTAL} pseudo instruction.
(Contributed by Mark Shannon in gh-128685@footnote{https://github.com/python/cpython/issues/128685}.)

@item 
Add the @ref{375,,LOAD_CONST_IMMORTAL} pseudo instruction,
which does the same as @code{LOAD_CONST}, but is more efficient
for immortal objects.
(Contributed by Mark Shannon in gh-125837@footnote{https://github.com/python/cpython/issues/125837}.)

@item 
Add the @ref{376,,NOT_TAKEN} pseudo instruction, used by @ref{e0,,sys.monitoring}
to record branch events (such as @ref{295,,BRANCH_LEFT}).
(Contributed by Mark Shannon in gh-122548@footnote{https://github.com/python/cpython/issues/122548}.)
@end itemize

@node C API changes,Build changes,CPython バイトコードの変更,What's new in Python 3 14
@anchor{whatsnew/3 14 c-api-changes}@anchor{377}
@subsection C API changes


@menu
* Python configuration C API:: 
* New features in the C API:: 
* Limited C API changes:: 
* Removed C APIs:: 
* Deprecated C APIs:: 

@end menu

@node Python configuration C API,New features in the C API,,C API changes
@anchor{whatsnew/3 14 python-configuration-c-api}@anchor{378}@anchor{whatsnew/3 14 whatsnew314-capi-config}@anchor{155}
@subsubsection Python configuration C API


Add a @ref{379,,PyInitConfig C API} to configure the Python
initialization without relying on C structures and the ability to make
ABI-compatible changes in the future.

Complete the 
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/} @ref{37a,,PyConfig C API} by adding
@ref{37b,,PyInitConfig_AddModule()} which can be used to add a built-in extension
module; a feature previously referred to as the "inittab".

Add @ref{37c,,PyConfig_Get()} and @ref{37d,,PyConfig_Set()} functions to get and set
the current runtime configuration.

@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/} 'Python Initialization Configuration' unified all the ways
to configure Python's initialization. This PEP also unifies the configuration
of Python's preinitialization and initialization in a single API.
Moreover, this PEP only provides a single choice to embed Python,
instead of having two 'Python' and 'Isolated' choices (PEP 587),
to further simplify the API.

The lower level PEP 587 PyConfig API remains available for use cases
with an intentionally higher level of coupling to CPython implementation details
(such as emulating the full functionality of CPython's CLI, including its
configuration mechanisms).

(Contributed by Victor Stinner in gh-107954@footnote{https://github.com/python/cpython/issues/107954}.)


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 741
PEP 741@footnote{https://peps.python.org/pep-0741/} and 
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/}


@node New features in the C API,Limited C API changes,Python configuration C API,C API changes
@anchor{whatsnew/3 14 new-features-in-the-c-api}@anchor{37e}
@subsubsection New features in the C API



@itemize *

@item 
Add @ref{37f,,Py_PACK_VERSION()} and @ref{380,,Py_PACK_FULL_VERSION()},
two new macros for bit-packing Python version numbers.
This is useful for comparisons with @ref{381,,Py_Version}
or @ref{382,,PY_VERSION_HEX}.
(Contributed by Petr Viktorin in gh-128629@footnote{https://github.com/python/cpython/issues/128629}.)

@item 
Add @ref{383,,PyBytes_Join(sep@comma{} iterable)} function,
similar to @code{sep.join(iterable)} in Python.
(Contributed by Victor Stinner in gh-121645@footnote{https://github.com/python/cpython/issues/121645}.)

@item 
Add functions to manipulate the configuration of the current
runtime Python interpreter
(@ref{155,,PEP 741; Python configuration C API}):


@itemize *

@item 
@ref{37c,,PyConfig_Get()}

@item 
@ref{384,,PyConfig_GetInt()}

@item 
@ref{37d,,PyConfig_Set()}

@item 
@ref{385,,PyConfig_Names()}
@end itemize

(Contributed by Victor Stinner in gh-107954@footnote{https://github.com/python/cpython/issues/107954}.)

@item 
Add functions to configure Python initialization
(@ref{155,,PEP 741; Python configuration C API}):


@itemize *

@item 
@ref{386,,Py_InitializeFromInitConfig()}

@item 
@ref{37b,,PyInitConfig_AddModule()}

@item 
@ref{387,,PyInitConfig_Create()}

@item 
@ref{388,,PyInitConfig_Free()}

@item 
@ref{389,,PyInitConfig_FreeStrList()}

@item 
@ref{38a,,PyInitConfig_GetError()}

@item 
@ref{38b,,PyInitConfig_GetExitCode()}

@item 
@ref{38c,,PyInitConfig_GetInt()}

@item 
@ref{38d,,PyInitConfig_GetStr()}

@item 
@ref{38e,,PyInitConfig_GetStrList()}

@item 
@ref{38f,,PyInitConfig_HasOption()}

@item 
@ref{390,,PyInitConfig_SetInt()}

@item 
@ref{391,,PyInitConfig_SetStr()}

@item 
@ref{392,,PyInitConfig_SetStrList()}
@end itemize

(Contributed by Victor Stinner in gh-107954@footnote{https://github.com/python/cpython/issues/107954}.)

@item 
Add @ref{393,,Py_fopen()} function to open a file.
This works similarly to the standard C @code{fopen()} function,
instead accepting a Python object for the `path' parameter
and setting an exception on error.
The corresponding new @ref{394,,Py_fclose()} function should be used
to close a file.
(Contributed by Victor Stinner in gh-127350@footnote{https://github.com/python/cpython/issues/127350}.)

@item 
Add @ref{395,,Py_HashBuffer()} to compute and return the hash value of a buffer.
(Contributed by Antoine Pitrou and Victor Stinner in gh-122854@footnote{https://github.com/python/cpython/issues/122854}.)

@item 
Add @ref{396,,PyImport_ImportModuleAttr()} and
@ref{397,,PyImport_ImportModuleAttrString()} helper functions to import a module
and get an attribute of the module.
(Contributed by Victor Stinner in gh-128911@footnote{https://github.com/python/cpython/issues/128911}.)

@item 
Add @ref{398,,PyIter_NextItem()} to replace @ref{399,,PyIter_Next()},
which has an ambiguous return value.
(Contributed by Irit Katriel and Erlend Aasland in gh-105201@footnote{https://github.com/python/cpython/issues/105201}.)

@item 
Add @ref{39a,,PyLong_GetSign()} function to get the sign of @ref{19b,,int} objects.
(Contributed by Sergey B Kirpichev in gh-116560@footnote{https://github.com/python/cpython/issues/116560}.)

@item 
Add @ref{39b,,PyLong_IsPositive()}, @ref{39c,,PyLong_IsNegative()}
and @ref{39d,,PyLong_IsZero()} for checking if @ref{39e,,PyLongObject}
is positive, negative, or zero, respectively.
(Contributed by James Roy and Sergey B Kirpichev in gh-126061@footnote{https://github.com/python/cpython/issues/126061}.)

@item 
Add new functions to convert C @code{<stdint.h>} numbers to/from
Python @ref{19b,,int} objects:


@itemize *

@item 
@ref{39f,,PyLong_AsInt32()}

@item 
@ref{3a0,,PyLong_AsInt64()}

@item 
@ref{3a1,,PyLong_AsUInt32()}

@item 
@ref{3a2,,PyLong_AsUInt64()}

@item 
@ref{3a3,,PyLong_FromInt32()}

@item 
@ref{3a4,,PyLong_FromInt64()}

@item 
@ref{3a5,,PyLong_FromUInt32()}

@item 
@ref{3a6,,PyLong_FromUInt64()}
@end itemize

(Contributed by Victor Stinner in gh-120389@footnote{https://github.com/python/cpython/issues/120389}.)

@item 
Add a new import and export API for Python @ref{19b,,int} objects
(
@geindex Python Enhancement Proposals; PEP 757
PEP 757@footnote{https://peps.python.org/pep-0757/}):


@itemize *

@item 
@ref{3a7,,PyLong_GetNativeLayout()}

@item 
@ref{3a8,,PyLong_Export()}

@item 
@ref{3a9,,PyLong_FreeExport()}

@item 
@ref{3aa,,PyLongWriter_Create()}

@item 
@ref{3ab,,PyLongWriter_Finish()}

@item 
@ref{3ac,,PyLongWriter_Discard()}
@end itemize

(Contributed by Sergey B Kirpichev and Victor Stinner in gh-102471@footnote{https://github.com/python/cpython/issues/102471}.)

@item 
Add @ref{3ad,,PyMonitoring_FireBranchLeftEvent()} and
@ref{3ae,,PyMonitoring_FireBranchRightEvent()} for generating
@ref{295,,BRANCH_LEFT} and @ref{296,,BRANCH_RIGHT}
events, respectively.
(Contributed by Mark Shannon in gh-122548@footnote{https://github.com/python/cpython/issues/122548}.)

@item 
Add @ref{3af,,PyType_Freeze()} function to make a type immutable.
(Contributed by Victor Stinner in gh-121654@footnote{https://github.com/python/cpython/issues/121654}.)

@item 
Add @ref{3b0,,PyType_GetBaseByToken()} and @ref{3b1,,Py_tp_token} slot
for easier superclass identification, which attempts to resolve the
type checking issue mentioned in 
@geindex Python Enhancement Proposals; PEP 630#type-checking
PEP 630@footnote{https://peps.python.org/pep-0630/#type-checking}.
(Contributed in gh-124153@footnote{https://github.com/python/cpython/issues/124153}.)

@item 
Add a new @ref{3b2,,PyUnicode_Equal()} function to test if two
strings are equal.
The function is also added to the Limited C API.
(Contributed by Victor Stinner in gh-124502@footnote{https://github.com/python/cpython/issues/124502}.)

@item 
Add a new @ref{3b3,,PyUnicodeWriter} API to create a Python @ref{169,,str}
object, with the following functions:


@itemize *

@item 
@ref{3b4,,PyUnicodeWriter_Create()}

@item 
@ref{3b5,,PyUnicodeWriter_DecodeUTF8Stateful()}

@item 
@ref{3b6,,PyUnicodeWriter_Discard()}

@item 
@ref{3b7,,PyUnicodeWriter_Finish()}

@item 
@ref{3b8,,PyUnicodeWriter_Format()}

@item 
@ref{3b9,,PyUnicodeWriter_WriteASCII()}

@item 
@ref{3ba,,PyUnicodeWriter_WriteChar()}

@item 
@ref{3bb,,PyUnicodeWriter_WriteRepr()}

@item 
@ref{3bc,,PyUnicodeWriter_WriteStr()}

@item 
@ref{3bd,,PyUnicodeWriter_WriteSubstring()}

@item 
@ref{3be,,PyUnicodeWriter_WriteUCS4()}

@item 
@ref{3bf,,PyUnicodeWriter_WriteUTF8()}

@item 
@ref{3c0,,PyUnicodeWriter_WriteWideChar()}
@end itemize

(Contributed by Victor Stinner in gh-119182@footnote{https://github.com/python/cpython/issues/119182}.)

@item 
The @code{k} and @code{K} formats in @ref{3c1,,PyArg_ParseTuple()} and
similar functions now use @ref{19e,,__index__()} if available,
like all other integer formats.
(Contributed by Serhiy Storchaka in gh-112068@footnote{https://github.com/python/cpython/issues/112068}.)

@item 
Add support for a new @code{p} format unit in @ref{3c2,,Py_BuildValue()}
that produces a Python @ref{3c3,,bool} object from a C integer.
(Contributed by Pablo Galindo in bpo-45325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45325}.)

@item 
Add @ref{3c4,,PyUnstable_IsImmortal()} for determining if
an object is @ref{290,,immortal}, for debugging purposes.
(Contributed by Peter Bierma in gh-128509@footnote{https://github.com/python/cpython/issues/128509}.)

@item 
Add @ref{3c5,,PyUnstable_Object_EnableDeferredRefcount()} for enabling
deferred reference counting, as outlined in 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}.

@item 
Add @ref{3c6,,PyUnstable_Object_IsUniquelyReferenced()} as
a replacement for @code{Py_REFCNT(op) == 1} on @ref{1f4,,free threaded} builds.
(Contributed by Peter Bierma in gh-133140@footnote{https://github.com/python/cpython/issues/133140}.)

@item 
Add @ref{3c7,,PyUnstable_Object_IsUniqueReferencedTemporary()} to
determine if an object is a unique temporary object on the
interpreter's operand stack.
This can be used in some cases as a replacement for checking
if @ref{2cf,,Py_REFCNT()} is @code{1} for Python objects passed
as arguments to C API functions.
(Contributed by Sam Gross in gh-133164@footnote{https://github.com/python/cpython/issues/133164}.)
@end itemize

@node Limited C API changes,Removed C APIs,New features in the C API,C API changes
@anchor{whatsnew/3 14 limited-c-api-changes}@anchor{3c8}
@subsubsection Limited C API changes



@itemize *

@item 
In the limited C API version 3.14 and newer, @ref{3c9,,Py_TYPE()} and
@ref{2cf,,Py_REFCNT()} are now implemented as an opaque function call
to hide implementation details.
(Contributed by Victor Stinner in gh-120600@footnote{https://github.com/python/cpython/issues/120600} and gh-124127@footnote{https://github.com/python/cpython/issues/124127}.)

@item 
Remove the @ref{3ca,,PySequence_Fast_GET_SIZE},
@ref{3cb,,PySequence_Fast_GET_ITEM},
and @ref{3cc,,PySequence_Fast_ITEMS}
macros from the limited C API, since they have always been broken
in the limited C API.
(Contributed by Victor Stinner in gh-91417@footnote{https://github.com/python/cpython/issues/91417}.)
@end itemize

@node Removed C APIs,Deprecated C APIs,Limited C API changes,C API changes
@anchor{whatsnew/3 14 removed-c-apis}@anchor{3cd}@anchor{whatsnew/3 14 whatsnew314-c-api-removed}@anchor{3ce}
@subsubsection Removed C APIs



@itemize *

@item 
Creating @ref{3cf,,immutable types} with
mutable bases was deprecated in Python 3.12,
and now raises a @ref{198,,TypeError}.
(Contributed by Nikita Sobolev in gh-119775@footnote{https://github.com/python/cpython/issues/119775}.)

@item 
Remove @code{PyDictObject.ma_version_tag} member, which was deprecated
in Python 3.12.
Use the @ref{3d0,,PyDict_AddWatcher()} API instead.
(Contributed by Sam Gross in gh-124296@footnote{https://github.com/python/cpython/issues/124296}.)

@item 
Remove the private @code{_Py_InitializeMain()} function.
It was a @ref{3d1,,provisional API} added to Python 3.8 by 
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/}.
(Contributed by Victor Stinner in gh-129033@footnote{https://github.com/python/cpython/issues/129033}.)

@item 
Remove the undocumented APIs @code{Py_C_RECURSION_LIMIT}
and @code{PyThreadState.c_recursion_remaining}.
These were added in 3.13 and have been removed without deprecation.
Use @ref{3d2,,Py_EnterRecursiveCall()} to guard against runaway
recursion in C code.
(Removed by Petr Viktorin in gh-133079@footnote{https://github.com/python/cpython/issues/133079}, see also gh-130396@footnote{https://github.com/python/cpython/issues/130396}.)
@end itemize

@node Deprecated C APIs,,Removed C APIs,C API changes
@anchor{whatsnew/3 14 deprecated-c-apis}@anchor{3d3}@anchor{whatsnew/3 14 whatsnew314-c-api-deprecated}@anchor{3d4}
@subsubsection Deprecated C APIs



@itemize *

@item 
The @code{Py_HUGE_VAL} macro is now @ref{23d,,soft deprecated}.
Use @code{Py_INFINITY} instead.
(Contributed by Sergey B Kirpichev in gh-120026@footnote{https://github.com/python/cpython/issues/120026}.)

@item 
The @code{Py_IS_NAN}, @code{Py_IS_INFINITY},
and @code{Py_IS_FINITE} macros are now @ref{23d,,soft deprecated}.
Use @code{isnan}, @code{isinf} and @code{isfinite}
instead, available from @code{math.h} since C99.
(Contributed by Sergey B Kirpichev in gh-119613@footnote{https://github.com/python/cpython/issues/119613}.)

@item 
Non-tuple sequences are now deprecated as argument for the @code{(items)}
format unit in @ref{3c1,,PyArg_ParseTuple()} and other @ref{3d5,,argument parsing} functions if `items' contains format units
which store a @ref{3d6,,borrowed buffer} or a
@ref{3d7,,borrowed reference}.
(Contributed by Serhiy Storchaka in gh-50333@footnote{https://github.com/python/cpython/issues/50333}.)

@item 
The @code{_PyMonitoring_FireBranchEvent} function is now deprecated
and should be replaced with calls to
@ref{3ad,,PyMonitoring_FireBranchLeftEvent()} and
@ref{3ae,,PyMonitoring_FireBranchRightEvent()}.

@item 
The previously undocumented function @ref{3d8,,PySequence_In()} is
now @ref{23d,,soft deprecated}.
Use @ref{3d9,,PySequence_Contains()} instead.
(Contributed by Yuki Kobayashi in gh-127896@footnote{https://github.com/python/cpython/issues/127896}.)
@end itemize

@c Add C API deprecations above alphabetically, not here at the end.

@menu
* Pending removal in Python 3.15: Pending removal in Python 3 15<2>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<2>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<2>. 
* Pending removal in future versions: Pending removal in future versions<2>. 

@end menu

@node Pending removal in Python 3 15<2>,Pending removal in Python 3 16<2>,,Deprecated C APIs
@anchor{whatsnew/3 14 id13}@anchor{3da}
@subsubsection Pending removal in Python 3.15



@itemize *

@item 
The @ref{3db,,PyImport_ImportModuleNoBlock()}:
Use @ref{3dc,,PyImport_ImportModule()} instead.

@item 
@ref{3dd,,PyWeakref_GetObject()} and @ref{3de,,PyWeakref_GET_OBJECT()}:
Use @ref{3df,,PyWeakref_GetRef()} instead. The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{3df,,PyWeakref_GetRef()} on Python 3.12 and older.

@item 
@ref{3e0,,Py_UNICODE} type and the @code{Py_UNICODE_WIDE} macro:
Use @code{wchar_t} instead.

@item 
@code{PyUnicode_AsDecodedObject()}:
Use @ref{3e1,,PyCodec_Decode()} instead.

@item 
@code{PyUnicode_AsDecodedUnicode()}:
Use @ref{3e1,,PyCodec_Decode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{169,,str}, such as @ref{192,,bytes}.

@item 
@code{PyUnicode_AsEncodedObject()}:
Use @ref{3e2,,PyCodec_Encode()} instead.

@item 
@code{PyUnicode_AsEncodedUnicode()}:
Use @ref{3e2,,PyCodec_Encode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{192,,bytes}, such as @ref{169,,str}.

@item 
Python initialization functions, deprecated in Python 3.13:


@itemize *

@item 
@ref{3e3,,Py_GetPath()}:
Use @ref{37c,,PyConfig_Get("module_search_paths")}
(@ref{3e4,,sys.path}) instead.

@item 
@ref{3e5,,Py_GetPrefix()}:
Use @ref{37c,,PyConfig_Get("base_prefix")}
(@ref{3e6,,sys.base_prefix}) instead. Use @ref{37c,,PyConfig_Get("prefix")} (@ref{3e7,,sys.prefix}) if @ref{3e8,,virtual environments} need to be handled.

@item 
@ref{3e9,,Py_GetExecPrefix()}:
Use @ref{37c,,PyConfig_Get("base_exec_prefix")}
(@ref{3ea,,sys.base_exec_prefix}) instead. Use
@ref{37c,,PyConfig_Get("exec_prefix")}
(@ref{3eb,,sys.exec_prefix}) if @ref{3e8,,virtual environments} need to
be handled.

@item 
@ref{3ec,,Py_GetProgramFullPath()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ee,,Py_GetProgramName()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ef,,Py_GetPythonHome()}:
Use @ref{37c,,PyConfig_Get("home")} or the
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable instead.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{37c,,PyConfig_Get()} on Python 3.13 and older.

@item 
Functions to configure Python's initialization, deprecated in Python 3.11:


@itemize *

@item 
@code{PySys_SetArgvEx()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{PySys_SetArgv()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{Py_SetProgramName()}:
Set @ref{3f2,,PyConfig.program_name} instead.

@item 
@code{Py_SetPythonHome()}:
Set @ref{3f3,,PyConfig.home} instead.

@item 
@ref{3f4,,PySys_ResetWarnOptions()}:
Clear @ref{3f5,,sys.warnoptions} and @code{warnings.filters} instead.
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} instead.

@item 
Global configuration variables:


@itemize *

@item 
@ref{3f8,,Py_DebugFlag}:
Use @ref{3f9,,PyConfig.parser_debug} or
@ref{37c,,PyConfig_Get("parser_debug")} instead.

@item 
@ref{3fa,,Py_VerboseFlag}:
Use @ref{3fb,,PyConfig.verbose} or
@ref{37c,,PyConfig_Get("verbose")} instead.

@item 
@ref{3fc,,Py_QuietFlag}:
Use @ref{3fd,,PyConfig.quiet} or
@ref{37c,,PyConfig_Get("quiet")} instead.

@item 
@ref{3fe,,Py_InteractiveFlag}:
Use @ref{3ff,,PyConfig.interactive} or
@ref{37c,,PyConfig_Get("interactive")} instead.

@item 
@ref{400,,Py_InspectFlag}:
Use @ref{401,,PyConfig.inspect} or
@ref{37c,,PyConfig_Get("inspect")} instead.

@item 
@ref{402,,Py_OptimizeFlag}:
Use @ref{403,,PyConfig.optimization_level} or
@ref{37c,,PyConfig_Get("optimization_level")} instead.

@item 
@ref{404,,Py_NoSiteFlag}:
Use @ref{405,,PyConfig.site_import} or
@ref{37c,,PyConfig_Get("site_import")} instead.

@item 
@ref{406,,Py_BytesWarningFlag}:
Use @ref{407,,PyConfig.bytes_warning} or
@ref{37c,,PyConfig_Get("bytes_warning")} instead.

@item 
@ref{408,,Py_FrozenFlag}:
Use @ref{409,,PyConfig.pathconfig_warnings} or
@ref{37c,,PyConfig_Get("pathconfig_warnings")} instead.

@item 
@ref{40a,,Py_IgnoreEnvironmentFlag}:
Use @ref{40b,,PyConfig.use_environment} or
@ref{37c,,PyConfig_Get("use_environment")} instead.

@item 
@ref{40c,,Py_DontWriteBytecodeFlag}:
Use @ref{40d,,PyConfig.write_bytecode} or
@ref{37c,,PyConfig_Get("write_bytecode")} instead.

@item 
@ref{40e,,Py_NoUserSiteDirectory}:
Use @ref{40f,,PyConfig.user_site_directory} or
@ref{37c,,PyConfig_Get("user_site_directory")} instead.

@item 
@ref{410,,Py_UnbufferedStdioFlag}:
Use @ref{411,,PyConfig.buffered_stdio} or
@ref{37c,,PyConfig_Get("buffered_stdio")} instead.

@item 
@ref{412,,Py_HashRandomizationFlag}:
Use @ref{413,,PyConfig.use_hash_seed}
and @ref{414,,PyConfig.hash_seed} or
@ref{37c,,PyConfig_Get("hash_seed")} instead.

@item 
@ref{415,,Py_IsolatedFlag}:
Use @ref{416,,PyConfig.isolated} or
@ref{37c,,PyConfig_Get("isolated")} instead.

@item 
@ref{417,,Py_LegacyWindowsFSEncodingFlag}:
Use @ref{418,,PyPreConfig.legacy_windows_fs_encoding} or
@ref{37c,,PyConfig_Get("legacy_windows_fs_encoding")} instead.

@item 
@ref{419,,Py_LegacyWindowsStdioFlag}:
Use @ref{41a,,PyConfig.legacy_windows_stdio} or
@ref{37c,,PyConfig_Get("legacy_windows_stdio")} instead.

@item 
@code{Py_FileSystemDefaultEncoding}, @code{Py_HasFileSystemDefaultEncoding}:
Use @ref{41b,,PyConfig.filesystem_encoding} or
@ref{37c,,PyConfig_Get("filesystem_encoding")} instead.

@item 
@code{Py_FileSystemDefaultEncodeErrors}:
Use @ref{41c,,PyConfig.filesystem_errors} or
@ref{37c,,PyConfig_Get("filesystem_errors")} instead.

@item 
@code{Py_UTF8Mode}:
Use @ref{41d,,PyPreConfig.utf8_mode} or
@ref{37c,,PyConfig_Get("utf8_mode")} instead.
(see @ref{41e,,Py_PreInitialize()})
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} to set these options. Or @ref{37c,,PyConfig_Get()} can be
used to get these options at runtime.
@end itemize

@node Pending removal in Python 3 16<2>,Pending removal in Python 3 18<2>,Pending removal in Python 3 15<2>,Deprecated C APIs
@anchor{whatsnew/3 14 id14}@anchor{41f}
@subsubsection Pending removal in Python 3.16



@itemize *

@item 
The bundled copy of @code{libmpdec}.
@end itemize

@node Pending removal in Python 3 18<2>,Pending removal in future versions<2>,Pending removal in Python 3 16<2>,Deprecated C APIs
@anchor{whatsnew/3 14 id15}@anchor{420}
@subsubsection Pending removal in Python 3.18



@itemize *

@item 
The following private functions are deprecated
and planned for removal in Python 3.18:


@itemize *

@item 
@code{_PyBytes_Join()}: use @ref{383,,PyBytes_Join()}.

@item 
@code{_PyDict_GetItemStringWithError()}: use @ref{421,,PyDict_GetItemStringRef()}.

@item 
@code{_PyDict_Pop()}: use @ref{422,,PyDict_Pop()}.

@item 
@code{_PyLong_Sign()}: use @ref{39a,,PyLong_GetSign()}.

@item 
@code{_PyLong_FromDigits()} and @code{_PyLong_New()}:
use @ref{3aa,,PyLongWriter_Create()}.

@item 
@code{_PyThreadState_UncheckedGet()}: use @ref{423,,PyThreadState_GetUnchecked()}.

@item 
@code{_PyUnicode_AsString()}: use @ref{424,,PyUnicode_AsUTF8()}.

@item 
@code{_PyUnicodeWriter_Init()}:
replace @code{_PyUnicodeWriter_Init(&writer)} with
@ref{3b4,,writer = PyUnicodeWriter_Create(0)}.

@item 
@code{_PyUnicodeWriter_Finish()}:
replace @code{_PyUnicodeWriter_Finish(&writer)} with
@ref{3b7,,PyUnicodeWriter_Finish(writer)}.

@item 
@code{_PyUnicodeWriter_Dealloc()}:
replace @code{_PyUnicodeWriter_Dealloc(&writer)} with
@ref{3b6,,PyUnicodeWriter_Discard(writer)}.

@item 
@code{_PyUnicodeWriter_WriteChar()}:
replace @code{_PyUnicodeWriter_WriteChar(&writer, ch)} with
@ref{3ba,,PyUnicodeWriter_WriteChar(writer@comma{} ch)}.

@item 
@code{_PyUnicodeWriter_WriteStr()}:
replace @code{_PyUnicodeWriter_WriteStr(&writer, str)} with
@ref{3bc,,PyUnicodeWriter_WriteStr(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteSubstring()}:
replace @code{_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)} with
@ref{3bd,,PyUnicodeWriter_WriteSubstring(writer@comma{} str@comma{} start@comma{} end)}.

@item 
@code{_PyUnicodeWriter_WriteASCIIString()}:
replace @code{_PyUnicodeWriter_WriteASCIIString(&writer, str)} with
@ref{3b9,,PyUnicodeWriter_WriteASCII(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteLatin1String()}:
replace @code{_PyUnicodeWriter_WriteLatin1String(&writer, str)} with
@ref{3bf,,PyUnicodeWriter_WriteUTF8(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_Prepare()}: (no replacement).

@item 
@code{_PyUnicodeWriter_PrepareKind()}: (no replacement).

@item 
@code{_Py_HashPointer()}: use @ref{425,,Py_HashPointer()}.

@item 
@code{_Py_fopen_obj()}: use @ref{393,,Py_fopen()}.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
these new public functions on Python 3.13 and older.
(Contributed by Victor Stinner in gh-128863@footnote{https://github.com/python/cpython/issues/128863}.)
@end itemize

@node Pending removal in future versions<2>,,Pending removal in Python 3 18<2>,Deprecated C APIs
@anchor{whatsnew/3 14 id16}@anchor{426}
@subsubsection Pending removal in future versions


The following APIs are deprecated and will be removed,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{427,,Py_TPFLAGS_HAVE_FINALIZE}:
Unneeded since Python 3.8.

@item 
@ref{428,,PyErr_Fetch()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42a,,PyErr_NormalizeException()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42b,,PyErr_Restore()}:
Use @ref{42c,,PyErr_SetRaisedException()} instead.

@item 
@ref{42d,,PyModule_GetFilename()}:
Use @ref{42e,,PyModule_GetFilenameObject()} instead.

@item 
@ref{42f,,PyOS_AfterFork()}:
Use @ref{430,,PyOS_AfterFork_Child()} instead.

@item 
@ref{431,,PySlice_GetIndicesEx()}:
Use @ref{432,,PySlice_Unpack()} and @ref{433,,PySlice_AdjustIndices()} instead.

@item 
@ref{434,,PyUnicode_READY()}:
Unneeded since Python 3.12

@item 
@code{PyErr_Display()}:
Use @ref{435,,PyErr_DisplayException()} instead.

@item 
@code{_PyErr_ChainExceptions()}:
Use @code{_PyErr_ChainExceptions1()} instead.

@item 
@code{PyBytesObject.ob_shash} member:
call @ref{436,,PyObject_Hash()} instead.

@item 
Thread Local Storage (TLS) API:


@itemize *

@item 
@ref{437,,PyThread_create_key()}:
Use @ref{438,,PyThread_tss_alloc()} instead.

@item 
@ref{439,,PyThread_delete_key()}:
Use @ref{43a,,PyThread_tss_free()} instead.

@item 
@ref{43b,,PyThread_set_key_value()}:
Use @ref{43c,,PyThread_tss_set()} instead.

@item 
@ref{43d,,PyThread_get_key_value()}:
Use @ref{43e,,PyThread_tss_get()} instead.

@item 
@ref{43f,,PyThread_delete_key_value()}:
Use @ref{440,,PyThread_tss_delete()} instead.

@item 
@ref{441,,PyThread_ReInitTLS()}:
Unneeded since Python 3.7.
@end itemize
@end itemize

@node Build changes,Porting to Python 3 14,C API changes,What's new in Python 3 14
@anchor{whatsnew/3 14 build-changes}@anchor{442}@anchor{whatsnew/3 14 whatsnew314-build-changes}@anchor{156}
@subsection Build changes



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 776
PEP 776@footnote{https://peps.python.org/pep-0776/}: Emscripten is now an officially supported platform at
@geindex Python Enhancement Proposals; PEP 11#tier-3
tier 3@footnote{https://peps.python.org/pep-0011/#tier-3}. As a part of this effort, more than 25 bugs in
Emscripten libc@footnote{https://emscripten.org/docs/porting/emscripten-runtime-environment.html} were fixed. Emscripten now includes support
for @ref{2e,,ctypes}, @ref{e7,,termios}, and @ref{5d,,fcntl}, as well as
experimental support for the new @ref{443,,default interactive shell}.
(Contributed by R. Hood Chatham in gh-127146@footnote{https://github.com/python/cpython/issues/127146}, gh-127683@footnote{https://github.com/python/cpython/issues/127683}, and gh-136931@footnote{https://github.com/python/cpython/issues/136931}.)

@item 
Official Android binary releases are now provided on python.org@footnote{https://www.python.org/downloads/android/}.

@item 
GNU Autoconf 2.72 is now required to generate @code{configure}.
(Contributed by Erlend Aasland in gh-115765@footnote{https://github.com/python/cpython/issues/115765}.)

@item 
@code{wasm32-unknown-emscripten} is now a 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} tier 3 platform.
(Contributed by R. Hood Chatham in gh-127146@footnote{https://github.com/python/cpython/issues/127146}, gh-127683@footnote{https://github.com/python/cpython/issues/127683}, and gh-136931@footnote{https://github.com/python/cpython/issues/136931}.)

@item 
@code{#pragma}-based linking with @code{python3*.lib} can now be switched off
with @ref{444,,Py_NO_LINK_LIB}.
(Contributed by Jean-Christophe Fillion-Robin in gh-82909@footnote{https://github.com/python/cpython/issues/82909}.)

@item 
CPython now enables a set of recommended compiler options by default
for improved security.
Use the @ref{445,,--disable-safety} @code{configure} option to disable them,
or the @ref{446,,--enable-slower-safety} option for a larger set
of compiler options, albeit with a performance cost.

@item 
The @code{WITH_FREELISTS} macro and @code{--without-freelists} @code{configure}
option have been removed.

@item 
The new @code{configure} option @ref{172,,--with-tail-call-interp}
may be used to enable the experimental tail call interpreter.
See @ref{14f,,A new type of interpreter} for further details.

@item 
To disable the new remote debugging support, use the
@ref{170,,--without-remote-debug} @code{configure} option.
This may be useful for security reasons.

@item 
iOS and macOS apps can now be configured to redirect @code{stdout} and
@code{stderr} content to the system log.
(Contributed by Russell Keith-Magee in gh-127592@footnote{https://github.com/python/cpython/issues/127592}.)

@item 
The iOS testbed is now able to stream test output while the test is running.
The testbed can also be used to run the test suite of projects other than
CPython itself.
(Contributed by Russell Keith-Magee in gh-127592@footnote{https://github.com/python/cpython/issues/127592}.)
@end itemize

@menu
* build-details.json: build-details json. 
* Discontinuation of PGP signatures:: 
* Free-threaded Python is officially supported:: 
* Binary releases for the experimental just-in-time compiler:: 

@end menu

@node build-details json,Discontinuation of PGP signatures,,Build changes
@anchor{whatsnew/3 14 build-details-json}@anchor{447}@anchor{whatsnew/3 14 whatsnew314-build-details}@anchor{448}
@subsubsection @code{build-details.json}


Installations of Python now contain a new file, @code{build-details.json}.
This is a static JSON document containing build details for CPython,
to allow for introspection without needing to run code.
This is helpful for use-cases such as Python launchers, cross-compilation,
and so on.

@code{build-details.json} must be installed in the platform-independent
standard library directory. This corresponds to the @ref{449,,'stdlib'} @ref{e1,,sysconfig} installation path,
which can be found by running @code{sysconfig.get_path('stdlib')}.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 739
PEP 739@footnote{https://peps.python.org/pep-0739/} -- @code{build-details.json} 1.0 -- a static description file
for Python build details


@node Discontinuation of PGP signatures,Free-threaded Python is officially supported,build-details json,Build changes
@anchor{whatsnew/3 14 discontinuation-of-pgp-signatures}@anchor{44a}@anchor{whatsnew/3 14 whatsnew314-no-more-pgp}@anchor{158}
@subsubsection Discontinuation of PGP signatures


PGP (Pretty Good Privacy) signatures will not be provided
for releases of Python 3.14 or future versions.
To verify CPython artifacts, users must use Sigstore verification materials@footnote{https://www.python.org/downloads/metadata/sigstore/}.
Releases have been signed using Sigstore@footnote{https://www.sigstore.dev/} since Python 3.11.

This change in release process was specified in 
@geindex Python Enhancement Proposals; PEP 761
PEP 761@footnote{https://peps.python.org/pep-0761/}.

@node Free-threaded Python is officially supported,Binary releases for the experimental just-in-time compiler,Discontinuation of PGP signatures,Build changes
@anchor{whatsnew/3 14 free-threaded-python-is-officially-supported}@anchor{44b}@anchor{whatsnew/3 14 whatsnew314-free-threaded-now-supported}@anchor{157}
@subsubsection Free-threaded Python is officially supported


The free-threaded build of Python is now supported and no longer experimental.
This is the start of phase II@footnote{https://discuss.python.org/t/37075} where
free-threaded Python is officially supported but still optional.

The free-threading team are confident that the project is on the right path,
and appreciate the continued dedication from everyone working to make
free-threading ready for broader adoption across the Python community.

With these recommendations and the acceptance of this PEP, the Python developer
community should broadly advertise that free-threading is a supported
Python build option now and into the future, and that it will not be removed
without a proper deprecation schedule.

Any decision to transition to phase III@footnote{https://discuss.python.org/t/37075},
with free-threading as the default or sole build of Python is still undecided,
and dependent on many factors both within CPython itself and the community.
This decision is for the future.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 779
PEP 779@footnote{https://peps.python.org/pep-0779/}

PEP 779's acceptance@footnote{https://discuss.python.org/t/84319/123}


@node Binary releases for the experimental just-in-time compiler,,Free-threaded Python is officially supported,Build changes
@anchor{whatsnew/3 14 binary-releases-for-the-experimental-just-in-time-compiler}@anchor{44c}@anchor{whatsnew/3 14 whatsnew314-jit-compiler}@anchor{159}
@subsubsection Binary releases for the experimental just-in-time compiler


The official macOS and Windows release binaries now include an `experimental'
just-in-time (JIT) compiler. Although it is `not' recommended for production
use, it can be tested by setting 
@geindex PYTHON_JIT
@geindex 環境変数; PYTHON_JIT
@ref{44d,,PYTHON_JIT=1} as an
environment variable. Downstream source builds and redistributors can use the
@ref{44e,,--enable-experimental-jit=yes-off} configuration option for similar
behavior.

The JIT is at an early stage and still in active development. As such, the
typical performance impact of enabling it can range from 10% slower to 20%
faster, depending on workload. To aid in testing and evaluation, a set of
introspection functions has been provided in the @ref{293,,sys._jit} namespace.
@ref{44f,,sys._jit.is_available()} can be used to determine if the current executable
supports JIT compilation, while @ref{450,,sys._jit.is_enabled()} can be used to tell
if JIT compilation has been enabled for the current process.

Currently, the most significant missing functionality is that native debuggers
and profilers like @code{gdb} and @code{perf} are unable to unwind through JIT frames
(Python debuggers and profilers, like @ref{aa,,pdb} or @ref{b4,,profile}, continue to
work without modification). Free-threaded builds do not support JIT compilation.

Please report any bugs or major performance regressions that you encounter!


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 744
PEP 744@footnote{https://peps.python.org/pep-0744/}


@node Porting to Python 3 14,Notable changes in 3 14 1,Build changes,What's new in Python 3 14
@anchor{whatsnew/3 14 porting-to-python-3-14}@anchor{14b}
@subsection Porting to Python 3.14


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python API の変更:: 
* Changes in annotations (PEP 649 and PEP 749): Changes in annotations PEP 649 and PEP 749. 
* C API の変更:: 

@end menu

@node Python API の変更,Changes in annotations PEP 649 and PEP 749,,Porting to Python 3 14
@anchor{whatsnew/3 14 changes-in-the-python-api}@anchor{451}
@subsubsection Python API の変更



@itemize *

@item 
On Unix platforms other than macOS, `forkserver' is now the default
@ref{1d5,,start method} for @ref{98,,multiprocessing}
and @ref{1d6,,ProcessPoolExecutor}, instead of `fork'.

See @ref{1d3,,(1)} and
@ref{249,,(2)} for details.

If you encounter @ref{452,,NameError}s or pickling errors coming out of
@ref{98,,multiprocessing} or @ref{24,,concurrent.futures}, see the
@ref{1d9,,forkserver restrictions}.

This change does not affect Windows or macOS, where @ref{1d8,,'spawn'} remains the default start method.

@item 
@ref{217,,functools.partial} is now a method descriptor.
Wrap it in @ref{453,,staticmethod()} if you want to preserve the old behavior.
(Contributed by Serhiy Storchaka and Dominykas Grigonis in gh-121027@footnote{https://github.com/python/cpython/issues/121027}.)

@item 
The @ref{152,,garbage collector is now incremental},
which means that the behavior of @ref{1b3,,gc.collect()} changes slightly:


@itemize *

@item 
@code{gc.collect(1)}: Performs an increment of garbage collection,
rather than collecting generation 1.

@item 
Other calls to @code{gc.collect()} are unchanged.
@end itemize

@item 
The @ref{454,,locale.nl_langinfo()} function now temporarily sets the @code{LC_CTYPE}
locale in some cases.
This temporary change affects other threads.
(Contributed by Serhiy Storchaka in gh-69998@footnote{https://github.com/python/cpython/issues/69998}.)

@item 
@ref{2a7,,types.UnionType} is now an alias for @ref{2a8,,typing.Union},
causing changes in some behaviors.
See @ref{2a9,,above} for more details.
(Contributed by Jelle Zijlstra in gh-105499@footnote{https://github.com/python/cpython/issues/105499}.)

@item 
The runtime behavior of annotations has changed in various ways; see
@ref{145,,above} for details. While most code that interacts
with annotations should continue to work, some undocumented details may behave
differently.

@item 
As part of making the @ref{93,,mimetypes} CLI public,
it now exits with @code{1} on failure instead of @code{0}
and @code{2} on incorrect command-line parameters instead of @code{1}.
Error messages are now printed to stderr.

@item 
The @code{\B} pattern in regular expression now matches the empty string
when given as the entire pattern, which may cause behavioural changes.

@item 
On FreeBSD, @ref{291,,sys.platform} no longer contains the major version number.
@end itemize

@node Changes in annotations PEP 649 and PEP 749,C API の変更,Python API の変更,Porting to Python 3 14
@anchor{whatsnew/3 14 changes-in-annotations-pep-649-and-pep-749}@anchor{455}@anchor{whatsnew/3 14 whatsnew314-porting-annotations}@anchor{161}
@subsubsection Changes in annotations (
@geindex Python Enhancement Proposals; PEP 649
`PEP 649' and 
@geindex Python Enhancement Proposals; PEP 749
`PEP 749')


This section contains guidance on changes that may be needed to annotations
or Python code that interacts with or introspects annotations,
due to the changes related to @ref{145,,deferred evaluation of annotations}.

In the majority of cases, working code from older versions of Python
will not require any changes.

@menu
* Implications for annotated code:: 
* Implications for readers of __annotations__:: 
* Related changes:: 
* from __future__ import annotations:: 

@end menu

@node Implications for annotated code,Implications for readers of __annotations__,,Changes in annotations PEP 649 and PEP 749
@anchor{whatsnew/3 14 implications-for-annotated-code}@anchor{456}
@subsubsection Implications for annotated code


If you define annotations in your code (for example, for use with a static type
checker), then this change probably does not affect you: you can keep
writing annotations the same way you did with previous versions of Python.

You will likely be able to remove quoted strings in annotations, which are frequently
used for forward references. Similarly, if you use @code{from __future__ import annotations}
to avoid having to write strings in annotations, you may well be able to
remove that import once you support only Python 3.14 and newer.
However, if you rely on third-party libraries that read annotations,
those libraries may need changes to support unquoted annotations before they
work as expected.

@node Implications for readers of __annotations__,Related changes,Implications for annotated code,Changes in annotations PEP 649 and PEP 749
@anchor{whatsnew/3 14 implications-for-readers-of-annotations}@anchor{457}
@subsubsection Implications for readers of @code{__annotations__}


If your code reads the @ref{458,,__annotations__} attribute on objects,
you may want to make changes in order to support code that relies on
deferred evaluation of annotations.
For example, you may want to use @ref{459,,annotationlib.get_annotations()} with
the @ref{15f,,FORWARDREF} format,
as the @ref{33,,dataclasses} module now does.

The external typing_extensions@footnote{https://pypi.org/project/typing_extensions/} package provides partial backports
of some of the functionality of the @ref{6,,annotationlib} module,
such as the @ref{230,,Format} enum and
the @ref{459,,get_annotations()} function.
These can be used to write cross-version code that takes advantage of
the new behavior in Python 3.14.

@node Related changes,from __future__ import annotations,Implications for readers of __annotations__,Changes in annotations PEP 649 and PEP 749
@anchor{whatsnew/3 14 related-changes}@anchor{45a}
@subsubsection Related changes


The changes in Python 3.14 are designed to rework how @code{__annotations__}
works at runtime while minimizing breakage to code that contains
annotations in source code and to code that reads @code{__annotations__}.
However, if you rely on undocumented details of the annotation behavior
or on private functions in the standard library, there are many ways in which
your code may not work in Python 3.14.
To safeguard your code against future changes, only use the documented
functionality of the @ref{6,,annotationlib} module.

In particular, do not read annotations directly from the namespace dictionary
attribute of type objects.
Use @ref{45b,,annotationlib.get_annotate_from_class_namespace()} during class
construction and @ref{459,,annotationlib.get_annotations()} afterwards.

In previous releases, it was sometimes possible to access class annotations
from an instance of an annotated class. This behavior was undocumented
and accidental, and will no longer work in Python 3.14.

@node from __future__ import annotations,,Related changes,Changes in annotations PEP 649 and PEP 749
@anchor{whatsnew/3 14 from-future-import-annotations}@anchor{45c}
@subsubsection @code{from __future__ import annotations}


In Python 3.7, 
@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/} introduced the @code{from __future__ import annotations}
@ref{45d,,future statement}, which turns all annotations into strings.

However, this statement is now deprecated and it is expected to be removed
in a future version of Python.
This removal will not happen until after Python 3.13 reaches its end of life
in 2029, being the last version of Python without support for deferred
evaluation of annotations.

In Python 3.14, the behavior of code using @code{from __future__ import annotations}
is unchanged.

@node C API の変更,,Changes in annotations PEP 649 and PEP 749,Porting to Python 3 14
@anchor{whatsnew/3 14 changes-in-the-c-api}@anchor{45e}
@subsubsection C API の変更



@itemize *

@item 
@ref{45f,,Py_Finalize()} now deletes all interned strings. This
is backwards incompatible to any C extension that holds onto an interned
string after a call to @ref{45f,,Py_Finalize()} and is then reused after a
call to @ref{460,,Py_Initialize()}.  Any issues arising from this behavior will
normally result in crashes during the execution of the subsequent call to
@ref{460,,Py_Initialize()} from accessing uninitialized memory. To fix, use
an address sanitizer to identify any use-after-free coming from
an interned string and deallocate it during module shutdown.
(Contributed by Eddie Elizondo in gh-113601@footnote{https://github.com/python/cpython/issues/113601}.)

@item 
The @ref{461,,Unicode Exception Objects} C API
now raises a @ref{198,,TypeError} if its exception argument is not
a @ref{462,,UnicodeError} object.
(Contributed by Bénédikt Tran in gh-127691@footnote{https://github.com/python/cpython/issues/127691}.)
@end itemize
@anchor{whatsnew/3 14 whatsnew314-refcount}@anchor{2d0}

@itemize *

@item 
The interpreter internally avoids some reference count modifications when
loading objects onto the operands stack by @ref{3d7,,borrowing}
references when possible. This can lead to smaller reference count values
compared to previous Python versions. C API extensions that checked
@ref{2cf,,Py_REFCNT()} of @code{1} to determine if an function argument is not
referenced by any other code should instead use
@ref{3c7,,PyUnstable_Object_IsUniqueReferencedTemporary()} as a safer replacement.

@item 
Private functions promoted to public C APIs:


@itemize *

@item 
@code{_PyBytes_Join()}: @ref{383,,PyBytes_Join()}

@item 
@code{_PyLong_IsNegative()}: @ref{39c,,PyLong_IsNegative()}

@item 
@code{_PyLong_IsPositive()}: @ref{39b,,PyLong_IsPositive()}

@item 
@code{_PyLong_IsZero()}: @ref{39d,,PyLong_IsZero()}

@item 
@code{_PyLong_Sign()}: @ref{39a,,PyLong_GetSign()}

@item 
@code{_PyUnicodeWriter_Dealloc()}: @ref{3b6,,PyUnicodeWriter_Discard()}

@item 
@code{_PyUnicodeWriter_Finish()}: @ref{3b7,,PyUnicodeWriter_Finish()}

@item 
@code{_PyUnicodeWriter_Init()}: use @ref{3b4,,PyUnicodeWriter_Create()}

@item 
@code{_PyUnicodeWriter_Prepare()}: (no replacement)

@item 
@code{_PyUnicodeWriter_PrepareKind()}: (no replacement)

@item 
@code{_PyUnicodeWriter_WriteChar()}: @ref{3ba,,PyUnicodeWriter_WriteChar()}

@item 
@code{_PyUnicodeWriter_WriteStr()}: @ref{3bc,,PyUnicodeWriter_WriteStr()}

@item 
@code{_PyUnicodeWriter_WriteSubstring()}: @ref{3bd,,PyUnicodeWriter_WriteSubstring()}

@item 
@code{_PyUnicode_EQ()}: @ref{3b2,,PyUnicode_Equal()}

@item 
@code{_PyUnicode_Equal()}: @ref{3b2,,PyUnicode_Equal()}

@item 
@code{_Py_GetConfig()}: @ref{37c,,PyConfig_Get()} and @ref{384,,PyConfig_GetInt()}

@item 
@code{_Py_HashBytes()}: @ref{395,,Py_HashBuffer()}

@item 
@code{_Py_fopen_obj()}: @ref{393,,Py_fopen()}

@item 
@code{PyMutex_IsLocked()} : @ref{463,,PyMutex_IsLocked()}
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get most of these new
functions on Python 3.13 and older.
@end itemize

@node Notable changes in 3 14 1,,Porting to Python 3 14,What's new in Python 3 14
@anchor{whatsnew/3 14 notable-changes-in-3-14-1}@anchor{464}@anchor{whatsnew/3 14 pythoncapi-compat-project}@anchor{465}
@subsection Notable changes in 3.14.1



@itemize *

@item 
Add @ref{466,,PyUnstable_ThreadState_SetStackProtection()} and
@ref{467,,PyUnstable_ThreadState_ResetStackProtection()} functions to set
the stack protection base address and stack protection size of a Python
thread state.
(Contributed by Victor Stinner in gh-139653@footnote{https://github.com/python/cpython/issues/139653}.)
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 13,What's New In Python 3 12,What's new in Python 3 14,What's New in Python
@anchor{whatsnew/3 13 doc}@anchor{468}@anchor{whatsnew/3 13 translation-repo}@anchor{469}@anchor{whatsnew/3 13 what-s-new-in-python-3-13}@anchor{46a}
@section What's New In Python 3.13


@*エディタ: 
Adam Turner と Thomas Wouters


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the issue number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :gh:`12345`.)
@c 
@c This saves the maintainer the effort of going through the VCS log
@c when researching a change.

この記事では Python 3.12 と比較した Python 3.13 の新機能を解説します。Python 3.13 は2024年10月7日にリリースされました。全詳細については @ref{142,,変更履歴} をご覧ください。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 719
PEP 719@footnote{https://peps.python.org/pep-0719/} -- Python 3.13 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト<2>. リリースハイライト
* 新しい機能: 新しい機能<2>. 
* その他の言語変更:: 
* 新たなモジュール:: 
* 改良されたモジュール:: 
* 最適化: 最適化<2>. 
* Removed Modules And APIs:: 
* New Deprecations:: 
* CPython Bytecode Changes:: 
* C API の変更: C API の変更<2>. 
* Build Changes:: 
* Porting to Python 3.13: Porting to Python 3 13. 
* Regression Test Changes:: 

@end menu

@node 概要 -- リリースハイライト<2>,新しい機能<2>,,What's New In Python 3 13
@anchor{whatsnew/3 13 summary-release-highlights}@anchor{46b}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.13.
@c Brevity is key.

Python 3.13 はプログラミング言語 Python の安定版のリリースです。言語自体への変更や、実装、標準ライブラリのアップデートが含まれます。一番大きな変更点は、新しい @ref{46c,,対話型インタープリタ} 、 @ref{46d,,フリースレッドモード} (
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}) 実行の実験的なサポート、 @ref{46e,,Just-In-Time コンパイラ} (
@geindex Python Enhancement Proposals; PEP 744
PEP 744@footnote{https://peps.python.org/pep-0744/}) です。

エラーメッセージも引き続き改善され、トレースバックがデフォルトで色付き表示になりました。また、組み込み関数 @ref{46f,,locals()} の戻り値のマッピングに変更を加えた際の @ref{470,,セマンティクスの定義} が追加されました。他にも、型引数がデフォルト値をサポートするようになりました。

ライブラリの変更点としては、非推奨 API ・モジュールの削除や、従来通り使いやすさの改善・バグ修正も行いました。Python 3.11  の廃止に伴い、レガシー標準ライブラリモジュールもいくつか @ref{471,,削除されました}  (
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}) 。

本記事は、全ての新機能の仕様をを網羅的に説明する代わりに、分かりやすく概要を説明するものとなっています。詳細については @ref{149,,ライブラリリファレンス} や @ref{14a,,言語レファレンス} などを参照してください。各変更点の実装や設計の理由を網羅的に理解したい方は、該当の PEP を参照してください。ただし、 PEP は機能が実装されたあとは Python の最新バージョンに合わせて更新されないことが多いので注意してください。Python を以前のバージョンからアップグレードする際の注意点は @ref{472,,Porting to Python 3.13} を参照してください。


__________________________________________________________________


@c PEP-sized items next.

インタープリタの改善点:


@itemize *

@item 
@ref{46c,,対話的インタープリタ} の大幅改善と @ref{473,,エラーメッセージの改善} 。

@item 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}: 組み込み関数 @ref{46f,,locals()} の戻り値のマッピングに変更を加えた際の @ref{470,,セマンティクスの定義} が言語仕様に追加されました。これにより、Python デバッガーなどのツールが最適化されたスコープ内のローカル変数を更新する際、たとえ並行処理だとしても、確実に更新することができるようになります。

@item 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}: CPython 3.13 では @ref{474,,global interpreter lock} を無効化した状態で実行する機能が実験的に追加されています。詳細は @ref{46d,,フリースレッドの CPython} を参照してください。

@item 
@geindex Python Enhancement Proposals; PEP 744
PEP 744@footnote{https://peps.python.org/pep-0744/}: 簡易的な @ref{46e,,JIT コンパイラ} が追加されました。現在、デフォルトでは無効になっています (が、今後有効になる可能性があります)。これによるパフォーマンスの向上は軽度ですが、以降のリリースで改善される見込みです。

@item 
新しい @ref{46c,,対話的インタープリタ} や @ref{473,,トレースバック} 、 @ref{475,,doctest} の出力において色付き文字に対応しました。この機能は環境変数 
@geindex PYTHON_COLORS
@geindex 環境変数; PYTHON_COLORS
@ref{476,,PYTHON_COLORS} または NO_COLOR@footnote{https://no-color.org/} で無効化できます。
@end itemize

Python のデータモデルの改善点:


@itemize *

@item 
クラスのボディ内の関数で @code{self.X} という形でアクセスされる属性がすべて @ref{477,,__static_attributes__} に格納されるようになりました。

@item 
クラス定義の最初の行の行番号が @ref{478,,__firstlineno__} に格納されるようになりました。
@end itemize

標準ライブラリーの顕著な改善点:


@itemize *

@item 
Python の @ref{479,,終了処理} において処理がブロックされているときに発生する新しい例外 @ref{47a,,PythonFinalizationError} が追加されました。

@item 
@ref{7,,argparse} モジュールでコマンドラインオプションや位置引数、サブコマンドを非推奨として指定する機能が追加されました。

@item 
Z85 data@footnote{https://rfc.zeromq.org/spec/32/} のエンコード・デコードを行う関数 @ref{47b,,base64.z85encode()} と @ref{47c,,base64.z85decode()} が追加されました。

@item 
多くの組み込み型や @ref{47d,,__replace__()} メソッドを定義している任意のクラスに対して使用できる関数 @ref{1c0,,copy.replace()} が @ref{29,,copy} モジュールに追加されました。

@item 
@ref{39,,dbm.sqlite3} モジュールが追加され、 @ref{35,,dbm} のデフォルトのバックエンドがこれに変更されました。

@item 
Linux のタイマー通知機能をもつファイル記述子を扱うための @ref{47e,,様々な関数} が @ref{a5,,os} モジュールに追加されました。

@item 
@ref{bd,,random} モジュールが @ref{47f,,コマンドラインインターフェース} を持つようになりました。
@end itemize

セキュリティの改善点:


@itemize *

@item 
@ref{480,,ssl.create_default_context()} がデフォルトのフラグとして @ref{481,,ssl.VERIFY_X509_PARTIAL_CHAIN} と:data:@cite{ssl.VERIFY_X509_STRICT} をセットするようになりました。
@end itemize

C API の改善点:


@itemize *

@item 
@ref{482,,Py_mod_gil} スロットは、拡張モジュールが @ref{164,,GIL} を無効化した状態での実行をサポート

@item 
@ref{483,,PyTime C API} が追加され、システムクロックへのアクセスが提供されるようになりました。

@item 
@ref{484,,PyMutex} は1バイトのみを占有する新しい軽量ミューテックスとなりました。

@item 
新しい @ref{485,,関数群} が、C API において 
@geindex Python Enhancement Proposals; PEP 669
PEP 669@footnote{https://peps.python.org/pep-0669/} の監視イベントを生成するために追加されました。
@end itemize

新しい型ヒントの機能:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 696
PEP 696@footnote{https://peps.python.org/pep-0696/}: 型引数（@ref{486,,typing.TypeVar}、@ref{487,,typing.ParamSpec}、@ref{488,,typing.TypeVarTuple}）をデフォルトでサポートします。

@item 
@geindex Python Enhancement Proposals; PEP 702
PEP 702@footnote{https://peps.python.org/pep-0702/}: 新たに追加された @ref{489,,warnings.deprecated()} デコレータは、型システムおよび実行時における非推奨のマーク付けをサポートします。

@item 
@geindex Python Enhancement Proposals; PEP 705
PEP 705@footnote{https://peps.python.org/pep-0705/}: @ref{48a,,typing.ReadOnly} は、型チェッカーに対して @ref{332,,typing.TypedDict} の項目を読み取り専用としてマークするために使用できます。

@item 
@geindex Python Enhancement Proposals; PEP 742
PEP 742@footnote{https://peps.python.org/pep-0742/}: @ref{48b,,typing.TypeIs} は、@ref{48c,,typing.TypeGuard} の代替として、より直感的な型の絞り込みの挙動を提供します。
@end itemize

プラットフォームのサポート:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 730
PEP 730@footnote{https://peps.python.org/pep-0730/}: Apple の iOS が 
@geindex Python Enhancement Proposals; PEP 11#tier-3
tier 3@footnote{https://peps.python.org/pep-0011/#tier-3} として @ref{48d,,公式にサポートされるプラットフォーム} となりました。

@item 
@geindex Python Enhancement Proposals; PEP 738
PEP 738@footnote{https://peps.python.org/pep-0738/} : Android が 
@geindex Python Enhancement Proposals; PEP 11#tier-3
tier 3@footnote{https://peps.python.org/pep-0011/#tier-3} として @ref{48d,,公式にサポートされるプラットフォーム} となりました。

@item 
@code{wasm32-wasi}  
@geindex Python Enhancement Proposals; PEP 11#tier-2
tier 2@footnote{https://peps.python.org/pep-0011/#tier-2} プラットフォームとしてサポートされるようになりました。

@item 
@code{wasm32-emscripten} が公式にサポートされるプラットフォームではなくなりました。
@end itemize

重要な削除


@itemize *

@item 
@ref{471,,PEP 594}: 残っていた 19 個の「不要なバッテリー」（旧式の標準ライブラリモジュール）が標準ライブラリから削除されました。削除されたモジュールは次のとおりです: @code{aifc}、@code{audioop}、@code{cgi}、@code{cgitb}、@code{chunk}、@code{crypt}、@code{imghdr}、@code{mailcap}、@code{msilib}、@code{nis}、@code{nntplib}、@code{ossaudiodev}、@code{pipes}、@code{sndhdr}、@code{spwd}、@code{sunau}、@code{telnetlib}、@code{uu}、@code{xdrlib}。

@item 
@code{2to3} ツールと @code{lib2to3} モジュールが削除されました（ Python 3.11 で非推奨となりました）

@item 
@code{tkinter.tix} モジュールが削除されました（ Python 3.6 で非推奨でした）

@item 
@code{locale.resetlocale()} 機能が削除されました。

@item 
@code{typing.io} と @code{typing.re} 名前空間が削除されました。

@item 
連鎖した @ref{48e,,classmethod} デスクリプタが削除されました。
@end itemize

リリーススケジュールの変更:

@geindex Python Enhancement Proposals; PEP 602
PEP 602@footnote{https://peps.python.org/pep-0602/} （「Python の年間リリースサイクル」）が更新され、新しいリリースの完全サポート（バグ修正）期間が 2 年に延長されました。この更新されたポリシーにより、次のような変更が適用されます:


@itemize *

@item 
Python 3.9--3.12 は1年半のフルサポート期間ののち、3年半のセキュリティ修正期間となります。

@item 
Python 3.13 以降のバージョンでは2年間のフルサポート期間、その後3年間のセキュリティ修正期間となります。
@end itemize

@node 新しい機能<2>,その他の言語変更,概要 -- リリースハイライト<2>,What's New In Python 3 13
@anchor{whatsnew/3 13 new-features}@anchor{48f}
@subsection 新しい機能


@menu
* 改善された対話的インタープリタ:: 
* エラーメッセージの改善: エラーメッセージの改善<2>. 
* フリースレッドの CPython:: 
* 実験的な Just-in-time (JIT) コンパイラ;: 実験的な Just-in-time JIT コンパイラ. 
* Defined mutation semantics for locals(): Defined mutation semantics for locals. 
* Support for mobile platforms:: 

@end menu

@node 改善された対話的インタープリタ,エラーメッセージの改善<2>,,新しい機能<2>
@anchor{whatsnew/3 13 a-better-interactive-interpreter}@anchor{490}@anchor{whatsnew/3 13 whatsnew313-better-interactive-interpreter}@anchor{46c}
@subsubsection 改善された対話的インタープリタ


PyPy project@footnote{https://pypy.org/} のコードをベースに作られた新しい Python @ref{1b5,,interactive} シェルがデフォルトで使われるようになりました。これからは、ターミナル上で @ref{491,,REPL} を起動すると、以下の機能が使えます:


@itemize *

@item 
複数行の編集。履歴機能もサポート。

@item 
@code{help} や @code{exit} 、  @code{quit} といったREPL 固有のコマンドが直接サポートされるようになり、関数として呼び出す必要がなくなりました。

@item 
デフォルトでプロンプトやトレースバックが @ref{1b7,,色付きで表示} されるようになりました。

@item 
インタラクティブなヘルプが @code{F1} で閲覧できるようになり、REPLとは別にコマンド履歴が記録されるようになりました。

@item 
@code{F2} で履歴を閲覧できるようになりました。出力や プロンプト内の @ref{492,,>>>} と @ref{493,,...} は表示されません。

@item 
@code{F3} で「ペーストモード」に切り替え、長いコードブロックをより簡単に貼り付けることができるようになりました (@code{F3} をもう一度押すことで通常のプロンプトに戻ることができます)。
@end itemize

新しいインタラクティブシェルを無効化するには、環境変数 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL} をセットします。インタラクティブモードの詳細については @ref{494,,対話モード} を参照してください。

（gh-111201@footnote{https://github.com/python/cpython/issues/111201} の Pablo Galindo Salgado, Łukasz Langa, and Lysandros Nikolaou らの PyPy プロジェクトのコードに基づく貢献。 Windows へのサポートは Dino Viehland, Anthony Shaw らによる貢献。）

@node エラーメッセージの改善<2>,フリースレッドの CPython,改善された対話的インタープリタ,新しい機能<2>
@anchor{whatsnew/3 13 improved-error-messages}@anchor{495}@anchor{whatsnew/3 13 whatsnew313-improved-error-messages}@anchor{473}
@subsubsection エラーメッセージの改善



@itemize *

@item 
インタープリタは、端末にトレースバックを表示する際に デフォルトでカラー表示を使用するようになりました。この機能は、新たに導入された 
@geindex PYTHON_COLORS
@geindex 環境変数; PYTHON_COLORS
@ref{476,,PYTHON_COLORS} 環境変数、および標準の NO_COLOR@footnote{https://no-color.org/} と FORCE_COLOR@footnote{https://force-color.org/} 環境変数を通じて @ref{1b7,,制御できます}。（この機能は Pablo Galindo Salgado により、gh-112730@footnote{https://github.com/python/cpython/issues/112730} にて貢献されました。）

@item 
よくある間違いとして、標準ライブラリのモジュールと同じ名前のスクリプトを作成してしまうことがあります。その結果エラーが発生した場合、Python はこれまでよりわかりやすいエラーメッセージを表示するようになりました:

@example
$ python random.py
Traceback (most recent call last):
  File "/home/me/random.py", line 1, in <module>
    import random
  File "/home/me/random.py", line 3, in <module>
    print(random.randint(5))
          ^^^^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/me/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)
@end example

同様に、スクリプトがインポートしようとするサードパーティ製モジュールと同じ名前を持ち、それによってエラーが発生した場合にも、Python はよりわかりやすいエラーメッセージを表示するようになりました:

@example
$ python numpy.py
Traceback (most recent call last):
  File "/home/me/numpy.py", line 1, in <module>
    import numpy as np
  File "/home/me/numpy.py", line 3, in <module>
    np.array([1, 2, 3])
    ^^^^^^^^
AttributeError: module 'numpy' has no attribute 'array' (consider renaming '/home/me/numpy.py' if it has the same name as a library you intended to import)
@end example

(Shantanu Jain による gh-95754@footnote{https://github.com/python/cpython/issues/95754} での貢献)

@item 
エラーメッセージは、関数に誤ったキーワード引数が渡された場合に、正しいキーワード引数を提案するようになりました:

@example
>>> "Better error messages!".split(max_split=1)
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    "Better error messages!".split(max_split=1)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
TypeError: split() got an unexpected keyword argument 'max_split'. Did you mean 'maxsplit'?
@end example

(Pablo Galindo Salgado と Shantanu Jain による gh-107944@footnote{https://github.com/python/cpython/issues/107944} での貢献)
@end itemize

@node フリースレッドの CPython,実験的な Just-in-time JIT コンパイラ,エラーメッセージの改善<2>,新しい機能<2>
@anchor{whatsnew/3 13 free-threaded-cpython}@anchor{496}@anchor{whatsnew/3 13 whatsnew313-free-threaded-cpython}@anchor{46d}
@subsubsection フリースレッドの CPython


@ref{474,,global interpreter lock} (GIL) を無効化するフリースレッドモードで CPython を実行する機能が実験的に追加されました。これは実験的機能のため、デフォルトで有効にはなっていません。フリースレッドモードで実行するには別の実行ファイルが必要で、通常 @code{python3.13t} か @code{python3.13t.exe} という名前です。入手するには、公式の @ref{497,,Windows} 版・ @ref{498,,macOS} 版インストーラで `フリースレッド' とラベルのついたビルド済みバイナリをインストールするか、もしくは CPython のソースコードを @ref{499,,--disable-gil} オプション付きでビルドすることもできます。

フリースレッドで実行することで、CPU コアの上で並列にスレッドを実行できるため、使用可能な処理性能をフルに活かすことができます。フリースレッドモードを使うだけでどのようなソフトウェアも恩恵を受けられるわけではないものの、スレッドを活用するように設計されたプログラムであれば、マルチコアのハードウェアでより高速に実行できることになります。ただし、 `フリースレッドモードは実験的機能' であり、改善が行われている最中です。バグに遭遇したり、シングルスレッドのパフォーマンスが大きく悪化する可能性があるので、注意してください。CPython のフリースレッド版ビルドでも、GIL を有効にした実行に対応しており、環境変数 
@geindex PYTHON_GIL
@geindex 環境変数; PYTHON_GIL
@ref{49a,,PYTHON_GIL} かコマンドラインオプション @ref{16f,,-X gil=1} によって有効化できます。

使用しているインタープリタがフリースレッドに対応しているかどうかは、 @ref{49b,,python -VV} を実行するか、 @ref{49c,,sys.version} に 「experimental free-threading build」が含まれているかどうかで確認できます。新しく追加された @code{sys._is_gil_enabled()} 関数により、 GIL が現在のプロセスで実際に有効になっているかを確認できます。

C-API 拡張モジュールは、フリースレッド用に別にビルドする必要があります。 @ref{164,,GIL} 無効状態での実行に対応している拡張モジュールは、 @ref{482,,Py_mod_gil} を使用してください。一段階初期化を使用する C 拡張は @ref{49d,,PyUnstable_Module_SetGIL()} を使用することで、 GIL 無効状態での実行に対応しているかどうかを指定してください。このような仕組みをいずれも使用しないモジュールがインポートされると、環境変数 
@geindex PYTHON_GIL
@geindex 環境変数; PYTHON_GIL
@ref{49a,,PYTHON_GIL} か @ref{16f,,-X gil=0} オプションが指定されていない限り、GIL が有効化されます。フリースレッド版の Python で C 拡張を含むパッケージをインストールするには、pip のバージョン が 24.1 以上である必要があります。

この機能が実現に至ったのは、たくさんの個人開発者の方や組織のおかげです。Python やサードパーティのプロジェクトに貢献する開発者の巨大なコミュニティが、フリースレッドへの対応やテストを行ってくださいました。特に大きな貢献のあった方は以下です: Sam Gross、Ken Jin、Donghee Na、Itamar Oren、Matt Page、Brett Simmers、Dino Viehland、Carl Meyer、Nathan Goldbaum、Ralf Gommers、Lysandros Nikolaou、ほか多数。このうちの多くが Meta の従業員であり、Meta はこのプロジェクトに多大な技術的な支援をしてくださいました。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/} "Making the Global Interpreter Lock Optional in CPython"
contains rationale and information surrounding this work.

Porting Extension Modules to Support Free-Threading@footnote{https://py-free-threading.github.io/porting/}: A community-maintained
porting guide for extension authors.


@node 実験的な Just-in-time JIT コンパイラ,Defined mutation semantics for locals,フリースレッドの CPython,新しい機能<2>
@anchor{whatsnew/3 13 an-experimental-just-in-time-jit-compiler}@anchor{49e}@anchor{whatsnew/3 13 whatsnew313-jit-compiler}@anchor{46e}
@subsubsection 実験的な Just-in-time (JIT) コンパイラ:


CPython を @code{--enable-experimental-jit} オプション付きで @cite{configure} してからビルドすると、just-in-time (JIT) コンパイラが追加され、Python プログラムの実行が速くなる可能性があります。Windows では @code{PCbuild/build.bat --experimental-jit} で JIT を有効化するか、 @code{--experimental-jit-interpreter} でティア2インタープリタを有効化してください。ビルドの必要事項やその他の補足情報は @code{Tools/jit/README.md} に掲載されています@footnote{https://github.com/python/cpython/blob/main/Tools/jit/README.md} 。

The @code{--enable-experimental-jit} option takes these (optional) values,
defaulting to @code{yes} if @code{--enable-experimental-jit} is present
without the optional value.


@itemize *

@item 
@code{no}: Disable the entire Tier 2 and JIT pipeline.

@item 
@code{yes}: Enable the JIT.
To disable the JIT at runtime, pass the environment variable @code{PYTHON_JIT=0}.

@item 
@code{yes-off}: Build the JIT but disable it by default.
To enable the JIT at runtime, pass the environment variable @code{PYTHON_JIT=1}.

@item 
@code{interpreter}: Enable the Tier 2 interpreter but disable the JIT.
The interpreter can be disabled by running with @code{PYTHON_JIT=0}.
@end itemize

The internal architecture is roughly as follows:


@itemize *

@item 
We start with specialized `Tier 1 bytecode'.
See @ref{49f,,What's new in 3.11} for details.

@item 
When the Tier 1 bytecode gets hot enough, it gets translated
to a new purely internal intermediate representation (IR),
called the `Tier 2 IR', and sometimes referred to as micro-ops ("uops").

@item 
The Tier 2 IR uses the same stack-based virtual machine as Tier 1,
but the instruction format is better suited to translation to machine code.

@item 
We have several optimization passes for Tier 2 IR, which are applied
before it is interpreted or translated to machine code.

@item 
There is a Tier 2 interpreter, but it is mostly intended for debugging
the earlier stages of the optimization pipeline.
The Tier 2 interpreter can be enabled by configuring Python
with @code{--enable-experimental-jit=interpreter}.

@item 
When the JIT is enabled, the optimized
Tier 2 IR is translated to machine code, which is then executed.

@item 
The machine code translation process uses a technique called
`copy-and-patch'. It has no runtime dependencies, but there is a new
build-time dependency on LLVM.
@end itemize


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 744
PEP 744@footnote{https://peps.python.org/pep-0744/}


(JIT by Brandt Bucher, inspired by a paper by Haoran Xu and Fredrik Kjolstad.
Tier 2 IR by Mark Shannon and Guido van Rossum.
Tier 2 optimizer by Ken Jin.)

@node Defined mutation semantics for locals,Support for mobile platforms,実験的な Just-in-time JIT コンパイラ,新しい機能<2>
@anchor{whatsnew/3 13 defined-mutation-semantics-for-locals}@anchor{4a0}@anchor{whatsnew/3 13 whatsnew313-locals-semantics}@anchor{470}
@subsubsection Defined mutation semantics for @code{locals()}


Historically, the expected result of mutating the return value of
@ref{46f,,locals()} has been left to individual Python implementations to define.
Starting from Python 3.13, 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/} standardises
the historical behavior of CPython for most code execution scopes,
but changes @ref{4a1,,optimized scopes}
(functions, generators, coroutines, comprehensions, and generator expressions)
to explicitly return independent snapshots of the currently assigned local
variables, including locally referenced nonlocal variables captured in closures.

This change to the semantics of @ref{46f,,locals()} in optimized scopes also
affects the default behavior of code execution functions that implicitly
target @code{locals()} if no explicit namespace is provided
(such as @ref{4a2,,exec()} and @ref{4a3,,eval()}).
In previous versions, whether or not changes could be accessed by calling
@code{locals()} after calling the code execution function was
implementation-dependent. In CPython specifically, such code would typically
appear to work as desired, but could sometimes fail in optimized scopes based
on other code (including debuggers and code execution tracing tools)
potentially resetting the shared snapshot in that scope.
Now, the code will always run against an independent snapshot of
the local variables in optimized scopes, and hence the changes will never
be visible in subsequent calls to @code{locals()}.
To access the changes made in these cases, an explicit namespace reference
must now be passed to the relevant function.
Alternatively, it may make sense to update affected code to use a higher level
code execution API that returns the resulting code execution namespace
(e.g. @ref{4a4,,runpy.run_path()} when executing Python files from disk).

To ensure debuggers and similar tools can reliably update local variables in
scopes affected by this change, @ref{4a5,,FrameType.f_locals} now
returns a write-through proxy to the frame's local and locally referenced
nonlocal variables in these scopes, rather than returning an inconsistently
updated shared @code{dict} instance with undefined runtime semantics.

See 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/} for more details, including related C API changes
and deprecations. Porting notes are also provided below for the affected
@ref{4a6,,Python APIs} and @ref{4a7,,C APIs}.

(PEP and implementation contributed by Mark Shannon and Tian Gao in
gh-74929@footnote{https://github.com/python/cpython/issues/74929}. Documentation updates provided by Guido van Rossum and
Alyssa Coghlan.)

@node Support for mobile platforms,,Defined mutation semantics for locals,新しい機能<2>
@anchor{whatsnew/3 13 support-for-mobile-platforms}@anchor{4a8}@anchor{whatsnew/3 13 whatsnew313-platform-support}@anchor{48d}
@subsubsection Support for mobile platforms


@geindex Python Enhancement Proposals; PEP 730
PEP 730@footnote{https://peps.python.org/pep-0730/}: iOS is now a 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} supported platform, with the
@code{arm64-apple-ios} and @code{arm64-apple-ios-simulator} targets at tier 3
(iPhone and iPad devices released after 2013 and the Xcode iOS simulator
running on Apple silicon hardware, respectively).
@code{x86_64-apple-ios-simulator}
(the Xcode iOS simulator running on older @code{x86_64} hardware)
is not a tier 3 supported platform, but will have best-effort support.
(PEP written and implementation contributed by Russell Keith-Magee in
gh-114099@footnote{https://github.com/python/cpython/issues/114099}.)

@geindex Python Enhancement Proposals; PEP 738
PEP 738@footnote{https://peps.python.org/pep-0738/}: Android is now a 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} supported platform, with the
@code{aarch64-linux-android} and @code{x86_64-linux-android} targets at tier 3.
The 32-bit targets @code{arm-linux-androideabi} and @code{i686-linux-android}
are not tier 3 supported platforms, but will have best-effort support.
(PEP written and implementation contributed by Malcolm Smith in
gh-116622@footnote{https://github.com/python/cpython/issues/116622}.)


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 730
PEP 730@footnote{https://peps.python.org/pep-0730/}, 
@geindex Python Enhancement Proposals; PEP 738
PEP 738@footnote{https://peps.python.org/pep-0738/}


@node その他の言語変更,新たなモジュール,新しい機能<2>,What's New In Python 3 13
@anchor{whatsnew/3 13 other-language-changes}@anchor{4a9}
@subsection その他の言語変更



@itemize *

@item 
The compiler now strips common leading whitespace
from every line in a docstring.
This reduces the size of the @ref{4aa,,bytecode cache}
(such as @code{.pyc} files), with reductions in file size of around 5%,
for example in @code{sqlalchemy.orm.session} from SQLAlchemy 2.0.
This change affects tools that use docstrings, such as @ref{3e,,doctest}.

@example
>>> def spam():
...     """
...         This is a docstring with
...           leading whitespace.
...
...         It even has multiple paragraphs!
...     """
...
>>> spam.__doc__
'\nThis is a docstring with\n  leading whitespace.\n\nIt even has multiple paragraphs!\n'
@end example

(Contributed by Inada Naoki in gh-81283@footnote{https://github.com/python/cpython/issues/81283}.)

@item 
@ref{4ab,,Annotation scopes} within class scopes
can now contain lambdas and comprehensions.
Comprehensions that are located within class scopes
are not inlined into their parent scope.

@example
class C[T]:
    type Alias = lambda: T
@end example

(Contributed by Jelle Zijlstra in gh-109118@footnote{https://github.com/python/cpython/issues/109118} and gh-118160@footnote{https://github.com/python/cpython/issues/118160}.)

@item 
@ref{45d,,Future statements} are no longer triggered by
relative imports of the @ref{0,,__future__} module,
meaning that statements of the form @code{from .__future__ import ...}
are now simply standard relative imports, with no special features activated.
(Contributed by Jeremiah Gabriel Pascual in gh-118216@footnote{https://github.com/python/cpython/issues/118216}.)

@item 
@ref{4ac,,global} declarations are now permitted in @ref{1ab,,except} blocks
when that global is used in the @ref{17c,,else} block.
Previously this raised an erroneous @ref{18e,,SyntaxError}.
(Contributed by Irit Katriel in gh-111123@footnote{https://github.com/python/cpython/issues/111123}.)

@item 
Add 
@geindex PYTHON_FROZEN_MODULES
@geindex 環境変数; PYTHON_FROZEN_MODULES
@ref{4ad,,PYTHON_FROZEN_MODULES}, a new environment variable that
determines whether frozen modules are ignored by the import machinery,
equivalent to the @ref{16f,,-X frozen_modules} command-line option.
(Contributed by Yilei Yang in gh-111374@footnote{https://github.com/python/cpython/issues/111374}.)

@item 
Add @ref{4ae,,support for the perf profiler} working
without frame pointers@footnote{https://en.wikipedia.org/wiki/Call_stack} through
the new environment variable 
@geindex PYTHON_PERF_JIT_SUPPORT
@geindex 環境変数; PYTHON_PERF_JIT_SUPPORT
@ref{4af,,PYTHON_PERF_JIT_SUPPORT}
and command-line option @ref{16f,,-X perf_jit}.
(Contributed by Pablo Galindo in gh-118518@footnote{https://github.com/python/cpython/issues/118518}.)

@item 
The location of a @code{.python_history} file can be changed via the
new 
@geindex PYTHON_HISTORY
@geindex 環境変数; PYTHON_HISTORY
@ref{4b0,,PYTHON_HISTORY} environment variable.
(Contributed by Levi Sabah, Zackery Spytz and Hugo van Kemenade
in gh-73965@footnote{https://github.com/python/cpython/issues/73965}.)

@item 
Classes have a new @ref{477,,__static_attributes__} attribute.
This is populated by the compiler with a tuple of the class's attribute names
which are assigned through @code{self.<name>} from any function in its body.
(Contributed by Irit Katriel in gh-115775@footnote{https://github.com/python/cpython/issues/115775}.)

@item 
The compiler now creates a @code{__firstlineno__} attribute on classes
with the line number of the first line of the class definition.
(Contributed by Serhiy Storchaka in gh-118465@footnote{https://github.com/python/cpython/issues/118465}.)

@item 
The @ref{4a2,,exec()} and @ref{4a3,,eval()} builtins now accept
the `globals' and `locals' arguments as keywords.
(Contributed by Raphael Gaschignard in gh-105879@footnote{https://github.com/python/cpython/issues/105879})

@item 
The @ref{4b1,,compile()} builtin now accepts a new flag,
@code{ast.PyCF_OPTIMIZED_AST}, which is similar to @code{ast.PyCF_ONLY_AST}
except that the returned AST is optimized according to
the value of the `optimize' argument.
(Contributed by Irit Katriel in gh-108113@footnote{https://github.com/python/cpython/issues/108113}).

@item 
Add a @ref{4b2,,__name__} attribute on @ref{4b3,,property} objects.
(Contributed by Eugene Toder in gh-101860@footnote{https://github.com/python/cpython/issues/101860}.)

@item 
Add @ref{47a,,PythonFinalizationError}, a new exception derived from
@ref{244,,RuntimeError} and used to signal when operations are blocked
during @ref{479,,finalization}.
The following callables now raise @code{PythonFinalizationError},
instead of @ref{244,,RuntimeError}:


@itemize *

@item 
@ref{4b4,,_thread.start_new_thread()}

@item 
@ref{4b5,,os.fork()}

@item 
@ref{4b6,,os.forkpty()}

@item 
@ref{4b7,,subprocess.Popen}
@end itemize

(Contributed by Victor Stinner in gh-114570@footnote{https://github.com/python/cpython/issues/114570}.)

@item 
Allow the `count' argument of @ref{4b8,,str.replace()} to be a keyword.
(Contributed by Hugo van Kemenade in gh-106487@footnote{https://github.com/python/cpython/issues/106487}.)

@item 
Many functions now emit a warning if a boolean value is passed as
a file descriptor argument.
This can help catch some errors earlier.
(Contributed by Serhiy Storchaka in gh-82626@footnote{https://github.com/python/cpython/issues/82626}.)

@item 
Added @code{name} and @code{mode} attributes
for compressed and archived file-like objects in
the @ref{14,,bz2}, @ref{8e,,lzma}, @ref{e4,,tarfile}, and @ref{137,,zipfile} modules.
(Contributed by Serhiy Storchaka in gh-115961@footnote{https://github.com/python/cpython/issues/115961}.)
@end itemize

@node 新たなモジュール,改良されたモジュール,その他の言語変更,What's New In Python 3 13
@anchor{whatsnew/3 13 new-modules}@anchor{4b9}
@subsection 新たなモジュール



@itemize *

@item 
@ref{39,,dbm.sqlite3}: An SQLite backend for @ref{35,,dbm}.
(Contributed by Raymond Hettinger and Erlend E. Aasland in gh-100414@footnote{https://github.com/python/cpython/issues/100414}.)
@end itemize

@node 改良されたモジュール,最適化<2>,新たなモジュール,What's New In Python 3 13
@anchor{whatsnew/3 13 improved-modules}@anchor{4ba}
@subsection 改良されたモジュール


@menu
* argparse: argparse<3>. 
* 配列:: 
* ast: ast<3>. 
* asyncio: asyncio<4>. 
* base64: base64<2>. 
* compileall:: 
* concurrent.futures: concurrent futures<2>. 
* configparser: configparser<2>. 
* copy:: 
* ctypes: ctypes<2>. 
* dbm:: 
* dis: dis<2>. 
* doctest:: 
* email: email<2>. 
* enum:: 
* fractions: fractions<2>. 
* glob:: 
* importlib:: 
* io: io<3>. 
* ipaddress:: 
* itertools: itertools<2>. 
* marshal:: 
* math: math<2>. 
* mimetypes: mimetypes<2>. 
* mmap:: 
* multiprocessing: multiprocessing<2>. 
* os: os<2>. 
* os.path: os path<2>. 
* pathlib: pathlib<4>. 
* pdb: pdb<3>. 
* queue:: 
* random:: 
* re: re<2>. 
* shutil:: 
* site:: 
* sqlite3: sqlite3<2>. 
* ssl: ssl<2>. 
* statistics:: 
* subprocess:: 
* sys: sys<2>. 
* tempfile:: 
* time:: 
* tkinter: tkinter<2>. 
* traceback:: 
* types: types<2>. 
* typing: typing<2>. 
* unicodedata: unicodedata<2>. 
* venv:: 
* warnings:: 
* xml:: 
* zipimport:: 

@end menu

@node argparse<3>,配列,,改良されたモジュール
@anchor{whatsnew/3 13 argparse}@anchor{4bb}
@subsubsection argparse



@itemize *

@item 
Add the `deprecated' parameter to the
@ref{4bc,,add_argument()}
and @code{add_parser()} methods, to enable deprecating
command-line options, positional arguments, and subcommands.
(Contributed by Serhiy Storchaka in gh-83648@footnote{https://github.com/python/cpython/issues/83648}.)
@end itemize

@node 配列,ast<3>,argparse<3>,改良されたモジュール
@anchor{whatsnew/3 13 array}@anchor{4bd}
@subsubsection 配列



@itemize *

@item 
Add the @code{'w'} type code (@code{Py_UCS4}) for Unicode characters.
It should be used instead of the deprecated @code{'u'} type code.
(Contributed by Inada Naoki in gh-80480@footnote{https://github.com/python/cpython/issues/80480}.)

@item 
Register @ref{4be,,array.array} as a @ref{4bf,,MutableSequence}
by implementing the @ref{4c0,,clear()} method.
(Contributed by Mike Zimin in gh-114894@footnote{https://github.com/python/cpython/issues/114894}.)
@end itemize

@node ast<3>,asyncio<4>,配列,改良されたモジュール
@anchor{whatsnew/3 13 ast}@anchor{4c1}
@subsubsection ast



@itemize *

@item 
The constructors of node types in the @ref{9,,ast} module are now
stricter in the arguments they accept,
with more intuitive behavior when arguments are omitted.

If an optional field on an AST node is not included as an argument when
constructing an instance, the field will now be set to @code{None}. Similarly,
if a list field is omitted, that field will now be set to an empty list,
and if an @code{expr_context} field is omitted, it defaults to
@ref{4c2,,Load()}.
(Previously, in all cases, the attribute would be missing on the newly
constructed AST node instance.)

In all other cases, where a required argument is omitted,
the node constructor will emit a @ref{1a3,,DeprecationWarning}.
This will raise an exception in Python 3.15.
Similarly, passing a keyword argument to the constructor
that does not map to a field on the AST node is now deprecated,
and will raise an exception in Python 3.15.

These changes do not apply to user-defined subclasses of @ref{4c3,,ast.AST}
unless the class opts in to the new behavior
by defining the @ref{4c4,,AST._field_types} mapping.

(Contributed by Jelle Zijlstra in gh-105858@footnote{https://github.com/python/cpython/issues/105858}, gh-117486@footnote{https://github.com/python/cpython/issues/117486}, and gh-118851@footnote{https://github.com/python/cpython/issues/118851}.)

@item 
@ref{1c2,,ast.parse()} now accepts an optional argument `optimize'
which is passed on to @ref{4b1,,compile()}.
This makes it possible to obtain an optimized AST.
(Contributed by Irit Katriel in gh-108113@footnote{https://github.com/python/cpython/issues/108113}.)
@end itemize

@node asyncio<4>,base64<2>,ast<3>,改良されたモジュール
@anchor{whatsnew/3 13 asyncio}@anchor{4c5}
@subsubsection asyncio



@itemize *

@item 
@ref{4c6,,asyncio.as_completed()} now returns an object that is both an
@ref{4c7,,asynchronous iterator} and a plain @ref{4c8,,iterator}
of @ref{4c9,,awaitables}.
The awaitables yielded by asynchronous iteration include original task
or future objects that were passed in,
making it easier to associate results with the tasks being completed.
(Contributed by Justin Arthur in gh-77714@footnote{https://github.com/python/cpython/issues/77714}.)

@item 
@ref{4ca,,asyncio.loop.create_unix_server()} will now automatically remove
the Unix socket when the server is closed.
(Contributed by Pierre Ossman in gh-111246@footnote{https://github.com/python/cpython/issues/111246}.)

@item 
@ref{4cb,,DatagramTransport.sendto()} will now send zero-length
datagrams if called with an empty bytes object.
The transport flow control also now accounts for the datagram header
when calculating the buffer size.
(Contributed by Jamie Phan in gh-115199@footnote{https://github.com/python/cpython/issues/115199}.)

@item 
Add @ref{4cc,,Queue.shutdown}
and @ref{4cd,,QueueShutDown} to manage queue termination.
(Contributed by Laurie Opperman and Yves Duprat in gh-104228@footnote{https://github.com/python/cpython/issues/104228}.)

@item 
Add the @ref{4ce,,Server.close_clients()} and @ref{4cf,,Server.abort_clients()}
methods, which more forcefully close an asyncio server.
(Contributed by Pierre Ossman in gh-113538@footnote{https://github.com/python/cpython/issues/113538}.)

@item 
Accept a tuple of separators in @ref{4d0,,StreamReader.readuntil()},
stopping when any one of them is encountered.
(Contributed by Bruce Merry in gh-81322@footnote{https://github.com/python/cpython/issues/81322}.)

@item 
Improve the behavior of @ref{4d1,,TaskGroup} when
an external cancellation collides with an internal cancellation.
For example, when two task groups are nested
and both experience an exception in a child task simultaneously,
it was possible that the outer task group would hang,
because its internal cancellation was swallowed by the inner task group.

In the case where a task group is cancelled externally
and also must raise an @ref{4d2,,ExceptionGroup},
it will now call the parent task's @ref{4d3,,cancel()} method.
This ensures that a @ref{4d4,,CancelledError} will be raised
at the next @ref{18d,,await}, so the cancellation is not lost.

An added benefit of these changes is that task groups now preserve
the cancellation count (@ref{4d5,,cancelling()}).

In order to handle some corner cases, @ref{4d6,,uncancel()} may now
reset the undocumented @code{_must_cancel} flag
when the cancellation count reaches zero.

(Inspired by an issue reported by Arthur Tacca in gh-116720@footnote{https://github.com/python/cpython/issues/116720}.)

@item 
When @ref{1cb,,TaskGroup.create_task()} is called on an inactive
@ref{4d1,,TaskGroup}, the given coroutine will be closed (which
prevents a @ref{4d7,,RuntimeWarning} about the given coroutine being
never awaited).
(Contributed by Arthur Tacca and Jason Zhang in gh-115957@footnote{https://github.com/python/cpython/issues/115957}.)

@item 
The function and methods named @code{create_task} have received a new
@code{**kwargs} argument that is passed through to the task constructor.
This change was accidentally added in 3.13.3,
and broke the API contract for custom task factories.
Several third-party task factories implemented workarounds for this.
In 3.13.4 and later releases the old factory contract is honored
once again (until 3.14).
To keep the workarounds working, the extra @code{**kwargs} argument still
allows passing additional keyword arguments to @ref{1c7,,Task}
and to custom task factories.

This affects the following function and methods:
@ref{1c9,,asyncio.create_task()},
@ref{1ca,,asyncio.loop.create_task()},
@ref{1cb,,asyncio.TaskGroup.create_task()}.
(Contributed by Thomas Grainger in gh-128307@footnote{https://github.com/python/cpython/issues/128307}.)
@end itemize

@node base64<2>,compileall,asyncio<4>,改良されたモジュール
@anchor{whatsnew/3 13 base64}@anchor{4d8}
@subsubsection base64



@itemize *

@item 
Add @ref{47b,,z85encode()} and @ref{47c,,z85decode()} functions
for encoding @ref{192,,bytes} as Z85 data@footnote{https://rfc.zeromq.org/spec/32/}
and decoding Z85-encoded data to @code{bytes}.
(Contributed by Matan Perelman in gh-75299@footnote{https://github.com/python/cpython/issues/75299}.)
@end itemize

@node compileall,concurrent futures<2>,base64<2>,改良されたモジュール
@anchor{whatsnew/3 13 compileall}@anchor{4d9}
@subsubsection compileall



@itemize *

@item 
The default number of worker threads and processes is now selected using
@ref{4da,,os.process_cpu_count()} instead of @ref{4db,,os.cpu_count()}.
(Contributed by Victor Stinner in gh-109649@footnote{https://github.com/python/cpython/issues/109649}.)
@end itemize

@node concurrent futures<2>,configparser<2>,compileall,改良されたモジュール
@anchor{whatsnew/3 13 concurrent-futures}@anchor{4dc}
@subsubsection concurrent.futures



@itemize *

@item 
The default number of worker threads and processes is now selected using
@ref{4da,,os.process_cpu_count()} instead of @ref{4db,,os.cpu_count()}.
(Contributed by Victor Stinner in gh-109649@footnote{https://github.com/python/cpython/issues/109649}.)
@end itemize

@node configparser<2>,copy,concurrent futures<2>,改良されたモジュール
@anchor{whatsnew/3 13 configparser}@anchor{4dd}
@subsubsection configparser



@itemize *

@item 
@ref{4de,,ConfigParser} now has support for unnamed sections,
which allows for top-level key-value pairs.
This can be enabled with the new `allow_unnamed_section' parameter.
(Contributed by Pedro Sousa Lacerda in gh-66449@footnote{https://github.com/python/cpython/issues/66449}.)
@end itemize

@node copy,ctypes<2>,configparser<2>,改良されたモジュール
@anchor{whatsnew/3 13 copy}@anchor{4df}
@subsubsection copy



@itemize *

@item 
The new @ref{1c0,,replace()} function and the @ref{47d,,replace protocol} make creating modified copies of objects much simpler.
This is especially useful when working with immutable objects.
The following types support the @ref{1c0,,replace()} function
and implement the replace protocol:


@itemize *

@item 
@ref{4e0,,collections.namedtuple()}

@item 
@ref{4e1,,dataclasses.dataclass}

@item 
@ref{4e2,,datetime.datetime}, @ref{1fa,,datetime.date}, @ref{1fb,,datetime.time}

@item 
@ref{4e3,,inspect.Signature}, @ref{4e4,,inspect.Parameter}

@item 
@ref{4e5,,types.SimpleNamespace}

@item 
@ref{4e6,,code objects}
@end itemize

Any user-defined class can also support @ref{1c0,,copy.replace()} by defining
the @ref{47d,,__replace__()} method.
(Contributed by Serhiy Storchaka in gh-108751@footnote{https://github.com/python/cpython/issues/108751}.)
@end itemize

@node ctypes<2>,dbm,copy,改良されたモジュール
@anchor{whatsnew/3 13 ctypes}@anchor{4e7}
@subsubsection ctypes



@itemize *

@item 
As a consequence of necessary internal refactoring, initialization of
internal metaclasses now happens in @code{__init__} rather
than in @code{__new__}. This affects projects that subclass these internal
metaclasses to provide custom initialization.
Generally:


@itemize -

@item 
Custom logic that was done in @code{__new__} after calling @code{super().__new__}
should be moved to @code{__init__}.

@item 
To create a class, call the metaclass, not only the metaclass's
@code{__new__} method.
@end itemize

See gh-124520@footnote{https://github.com/python/cpython/issues/124520} for discussion and links to changes in some affected
projects.

@item 
@ref{1e5,,ctypes.Structure} objects have a new @ref{4e8,,_align_}
attribute which allows the alignment of the structure being packed to/from
memory to be specified explicitly.
(Contributed by Matt Sanderson in gh-112433@footnote{https://github.com/python/cpython/issues/112433})
@end itemize

@node dbm,dis<2>,ctypes<2>,改良されたモジュール
@anchor{whatsnew/3 13 dbm}@anchor{4e9}
@subsubsection dbm



@itemize *

@item 
Add @ref{39,,dbm.sqlite3}, a new module which implements an SQLite backend,
and make it the default @code{dbm} backend.
(Contributed by Raymond Hettinger and Erlend E. Aasland in gh-100414@footnote{https://github.com/python/cpython/issues/100414}.)

@item 
Allow removing all items from the database through
the new @code{clear()} methods of the GDBM and NDBM database objects.
(Contributed by Donghee Na in gh-107122@footnote{https://github.com/python/cpython/issues/107122}.)
@end itemize

@node dis<2>,doctest,dbm,改良されたモジュール
@anchor{whatsnew/3 13 dis}@anchor{4ea}
@subsubsection dis



@itemize *

@item 
Change the output of @ref{3c,,dis} module functions to show logical
labels for jump targets and exception handlers, rather than offsets.
The offsets can be added with the new
@ref{4eb,,-O} command-line option
or the `show_offsets' argument.
(Contributed by Irit Katriel in gh-112137@footnote{https://github.com/python/cpython/issues/112137}.)

@item 
@ref{4ec,,get_instructions()} no longer represents cache entries
as separate instructions.
Instead, it returns them as part of the @ref{203,,Instruction},
in the new `cache_info' field.
The `show_caches' argument to @ref{4ec,,get_instructions()} is deprecated
and no longer has any effect.
(Contributed by Irit Katriel in gh-112962@footnote{https://github.com/python/cpython/issues/112962}.)
@end itemize

@node doctest,email<2>,dis<2>,改良されたモジュール
@anchor{whatsnew/3 13 doctest}@anchor{4ed}@anchor{whatsnew/3 13 whatsnew313-doctest}@anchor{475}
@subsubsection doctest



@itemize *

@item 
@ref{3e,,doctest} output is now colored by default.
This can be controlled via the new 
@geindex PYTHON_COLORS
@geindex 環境変数; PYTHON_COLORS
@ref{476,,PYTHON_COLORS} environment
variable as well as the canonical NO_COLOR@footnote{https://no-color.org/}
and FORCE_COLOR@footnote{https://force-color.org/} environment variables.
See also @ref{1b7,,色の制御}.
(Contributed by Hugo van Kemenade in gh-117225@footnote{https://github.com/python/cpython/issues/117225}.)

@item 
The @ref{4ee,,DocTestRunner.run()} method now counts the number of skipped tests.
Add the @ref{4ef,,DocTestRunner.skips} and @ref{4f0,,TestResults.skipped} attributes.
(Contributed by Victor Stinner in gh-108794@footnote{https://github.com/python/cpython/issues/108794}.)
@end itemize

@node email<2>,enum,doctest,改良されたモジュール
@anchor{whatsnew/3 13 email}@anchor{4f1}
@subsubsection email



@itemize *

@item 
Headers with embedded newlines are now quoted on output.
The @ref{44,,generator} will now refuse to serialize (write) headers
that are improperly folded or delimited, such that they would be parsed as
multiple headers or joined with adjacent data.
If you need to turn this safety feature off,
set @ref{4f2,,verify_generated_headers}.
(Contributed by Bas Bloemsaat and Petr Viktorin in gh-121650@footnote{https://github.com/python/cpython/issues/121650}.)

@item 
@ref{4f3,,getaddresses()} and @ref{4f4,,parseaddr()} now
return @code{('@w{'}, '@w{'})} pairs in more situations where invalid email addresses
are encountered instead of potentially inaccurate values.
The two functions have a new optional `strict' parameter (default @code{True}).
To get the old behavior (accepting malformed input), use @code{strict=False}.
@code{getattr(email.utils, 'supports_strict_parsing', False)} can be used
to check if the `strict' parameter is available.
(Contributed by Thomas Dwyer and Victor Stinner for gh-102988@footnote{https://github.com/python/cpython/issues/102988} to improve
the 
@geindex Common Vulnerabilities and Exposures; CVE 2023-27043
CVE 2023-27043@footnote{https://www.cve.org/CVERecord?id=CVE-2023-27043} fix.)
@end itemize

@node enum,fractions<2>,email<2>,改良されたモジュール
@anchor{whatsnew/3 13 enum}@anchor{4f5}
@subsubsection enum



@itemize *

@item 
@ref{4f6,,EnumDict} has been made public to better support subclassing
@ref{4f7,,EnumType}.
@end itemize

@node fractions<2>,glob,enum,改良されたモジュール
@anchor{whatsnew/3 13 fractions}@anchor{4f8}
@subsubsection fractions



@itemize *

@item 
@ref{213,,Fraction} objects now support the standard
@ref{4f9,,format specification mini-language} rules
for fill, alignment, sign handling, minimum width, and grouping.
(Contributed by Mark Dickinson in gh-111320@footnote{https://github.com/python/cpython/issues/111320}.)
@end itemize

@node glob,importlib,fractions<2>,改良されたモジュール
@anchor{whatsnew/3 13 glob}@anchor{4fa}
@subsubsection glob



@itemize *

@item 
Add @ref{4fb,,translate()}, a function to convert a path specification
with shell-style wildcards to a regular expression.
(Contributed by Barney Gale in gh-72904@footnote{https://github.com/python/cpython/issues/72904}.)
@end itemize

@node importlib,io<3>,glob,改良されたモジュール
@anchor{whatsnew/3 13 importlib}@anchor{4fc}
@subsubsection importlib



@itemize *

@item 
The following functions in @ref{7f,,importlib.resources} now allow accessing
a directory (or tree) of resources, using multiple positional arguments
(the `encoding' and `errors' arguments in the text-reading functions
are now keyword-only):


@itemize *

@item 
@ref{4fd,,is_resource()}

@item 
@ref{4fe,,open_binary()}

@item 
@ref{4ff,,open_text()}

@item 
@ref{500,,path()}

@item 
@ref{501,,read_binary()}

@item 
@ref{502,,read_text()}
@end itemize

These functions are no longer deprecated and are not scheduled for removal.
(Contributed by Petr Viktorin in gh-116608@footnote{https://github.com/python/cpython/issues/116608}.)

@item 
@ref{503,,contents()} remains deprecated in favor of
the fully-featured @ref{2fa,,Traversable} API.
However, there is now no plan to remove it.
(Contributed by Petr Viktorin in gh-116608@footnote{https://github.com/python/cpython/issues/116608}.)
@end itemize

@node io<3>,ipaddress,importlib,改良されたモジュール
@anchor{whatsnew/3 13 io}@anchor{504}
@subsubsection io



@itemize *

@item 
The @ref{505,,IOBase} finalizer now logs any errors raised by
the @ref{506,,close()} method with @ref{507,,sys.unraisablehook}.
Previously, errors were ignored silently by default,
and only logged in @ref{508,,Python Development Mode}
or when using a @ref{509,,Python debug build}.
(Contributed by Victor Stinner in gh-62948@footnote{https://github.com/python/cpython/issues/62948}.)
@end itemize

@node ipaddress,itertools<2>,io<3>,改良されたモジュール
@anchor{whatsnew/3 13 ipaddress}@anchor{50a}
@subsubsection ipaddress



@itemize *

@item 
Add the @ref{50b,,IPv4Address.ipv6_mapped} property,
which returns the IPv4-mapped IPv6 address.
(Contributed by Charles Machalow in gh-109466@footnote{https://github.com/python/cpython/issues/109466}.)

@item 
Fix @code{is_global} and @code{is_private} behavior in
@ref{50c,,IPv4Address}, @ref{50d,,IPv6Address},
@ref{50e,,IPv4Network}, and @ref{50f,,IPv6Network}.
(Contributed by Jakub Stasiak in gh-113171@footnote{https://github.com/python/cpython/issues/113171}.)
@end itemize

@node itertools<2>,marshal,ipaddress,改良されたモジュール
@anchor{whatsnew/3 13 itertools}@anchor{510}
@subsubsection itertools



@itemize *

@item 
@ref{511,,batched()} has a new `strict' parameter,
which raises a @ref{2ec,,ValueError} if the final batch is shorter
than the specified batch size.
(Contributed by Raymond Hettinger in gh-113202@footnote{https://github.com/python/cpython/issues/113202}.)
@end itemize

@node marshal,math<2>,itertools<2>,改良されたモジュール
@anchor{whatsnew/3 13 marshal}@anchor{512}
@subsubsection marshal



@itemize *

@item 
Add the `allow_code' parameter in module functions.
Passing @code{allow_code=False} prevents serialization and de-serialization
of code objects which are incompatible between Python versions.
(Contributed by Serhiy Storchaka in gh-113626@footnote{https://github.com/python/cpython/issues/113626}.)
@end itemize

@node math<2>,mimetypes<2>,marshal,改良されたモジュール
@anchor{whatsnew/3 13 math}@anchor{513}
@subsubsection math



@itemize *

@item 
The new function @ref{514,,fma()} performs fused multiply-add operations.
This computes @code{x * y + z} with only a single round,
and so avoids any intermediate loss of precision.
It wraps the @code{fma()} function provided by C99,
and follows the specification of the IEEE 754 "fusedMultiplyAdd" operation
for special cases.
(Contributed by Mark Dickinson and Victor Stinner in gh-73468@footnote{https://github.com/python/cpython/issues/73468}.)
@end itemize

@node mimetypes<2>,mmap,math<2>,改良されたモジュール
@anchor{whatsnew/3 13 mimetypes}@anchor{515}
@subsubsection mimetypes



@itemize *

@item 
Add the @ref{516,,guess_file_type()} function to guess a MIME type
from a filesystem path.
Using paths with @ref{517,,guess_type()} is now @ref{23d,,soft deprecated}.
(Contributed by Serhiy Storchaka in gh-66543@footnote{https://github.com/python/cpython/issues/66543}.)
@end itemize

@node mmap,multiprocessing<2>,mimetypes<2>,改良されたモジュール
@anchor{whatsnew/3 13 mmap}@anchor{518}
@subsubsection mmap



@itemize *

@item 
@ref{519,,mmap} is now protected from crashing on Windows when the
mapped memory is inaccessible due to file system errors or access violations.
(Contributed by Jannis Weigend in gh-118209@footnote{https://github.com/python/cpython/issues/118209}.)

@item 
@ref{519,,mmap} has a new @ref{51a,,seekable()} method
that can be used when a seekable file-like object is required.
The @ref{51b,,seek()} method now returns the new absolute position.
(Contributed by Donghee Na and Sylvie Liberman in gh-111835@footnote{https://github.com/python/cpython/issues/111835}.)

@item 
The new UNIX-only `trackfd' parameter for @ref{519,,mmap} controls
file descriptor duplication;
if false, the file descriptor specified by `fileno' will not be duplicated.
(Contributed by Zackery Spytz and Petr Viktorin in gh-78502@footnote{https://github.com/python/cpython/issues/78502}.)
@end itemize

@node multiprocessing<2>,os<2>,mmap,改良されたモジュール
@anchor{whatsnew/3 13 multiprocessing}@anchor{51c}
@subsubsection multiprocessing



@itemize *

@item 
The default number of worker threads and processes is now selected using
@ref{4da,,os.process_cpu_count()} instead of @ref{4db,,os.cpu_count()}.
(Contributed by Victor Stinner in gh-109649@footnote{https://github.com/python/cpython/issues/109649}.)
@end itemize

@node os<2>,os path<2>,multiprocessing<2>,改良されたモジュール
@anchor{whatsnew/3 13 os}@anchor{51d}
@subsubsection os



@itemize *

@item 
Add @ref{4da,,process_cpu_count()} function to get the number
of logical CPU cores usable by the calling thread of the current process.
(Contributed by Victor Stinner in gh-109649@footnote{https://github.com/python/cpython/issues/109649}.)

@item 
@ref{4db,,cpu_count()} and @ref{4da,,process_cpu_count()} can be overridden
through the new environment variable 
@geindex PYTHON_CPU_COUNT
@geindex 環境変数; PYTHON_CPU_COUNT
@ref{51e,,PYTHON_CPU_COUNT}
or the new command-line option @ref{16f,,-X cpu_count}.
This option is useful for users who need to limit CPU resources
of a container system without having to modify application code
or the container itself.
(Contributed by Donghee Na in gh-109595@footnote{https://github.com/python/cpython/issues/109595}.)

@item 
Add a @ref{47e,,low level interface} to Linux's
@code{timer file descriptors@footnote{https://manpages.debian.org/timerfd_create(2)}}
via @ref{51f,,timerfd_create()},
@ref{520,,timerfd_settime()}, @ref{521,,timerfd_settime_ns()},
@ref{522,,timerfd_gettime()}, @ref{523,,timerfd_gettime_ns()},
@ref{524,,TFD_NONBLOCK}, @ref{525,,TFD_CLOEXEC},
@ref{526,,TFD_TIMER_ABSTIME}, and @ref{527,,TFD_TIMER_CANCEL_ON_SET}
(Contributed by Masaru Tsuchiyama in gh-108277@footnote{https://github.com/python/cpython/issues/108277}.)

@item 
@ref{528,,lchmod()} and the `follow_symlinks' argument of @ref{529,,chmod()}
are both now available on Windows.
Note that the default value of `follow_symlinks'
in @code{lchmod()} is @code{False} on Windows.
(Contributed by Serhiy Storchaka in gh-59616@footnote{https://github.com/python/cpython/issues/59616}.)

@item 
@ref{52a,,fchmod()} and support for file descriptors in @ref{529,,chmod()}
are both now available on Windows.
(Contributed by Serhiy Storchaka in gh-113191@footnote{https://github.com/python/cpython/issues/113191}.)

@item 
On Windows, @ref{52b,,mkdir()} and @ref{52c,,makedirs()} now support passing
a `mode' value of @code{0o700} to apply access control to the new directory.
This implicitly affects @ref{52d,,tempfile.mkdtemp()}
and is a mitigation for 
@geindex Common Vulnerabilities and Exposures; CVE 2024-4030
CVE 2024-4030@footnote{https://www.cve.org/CVERecord?id=CVE-2024-4030}.
Other values for `mode' continue to be ignored.
(Contributed by Steve Dower in gh-118486@footnote{https://github.com/python/cpython/issues/118486}.)

@item 
@ref{52e,,posix_spawn()} now accepts @code{None} for the `env' argument,
which makes the newly spawned process use the current process environment.
(Contributed by Jakub Kulik in gh-113119@footnote{https://github.com/python/cpython/issues/113119}.)

@item 
@ref{52e,,posix_spawn()} can now use the @ref{52f,,POSIX_SPAWN_CLOSEFROM}
attribute in the `file_actions' parameter on platforms that support
@code{posix_spawn_file_actions_addclosefrom_np()}.
(Contributed by Jakub Kulik in gh-113117@footnote{https://github.com/python/cpython/issues/113117}.)
@end itemize

@node os path<2>,pathlib<4>,os<2>,改良されたモジュール
@anchor{whatsnew/3 13 os-path}@anchor{530}
@subsubsection os.path



@itemize *

@item 
Add @ref{32b,,isreserved()} to check if a path is reserved
on the current system.
This function is only available on Windows.
(Contributed by Barney Gale in gh-88569@footnote{https://github.com/python/cpython/issues/88569}.)

@item 
On Windows, @ref{531,,isabs()} no longer considers paths
starting with exactly one slash (@code{\} or @code{/}) to be absolute.
(Contributed by Barney Gale and Jon Foster in gh-44626@footnote{https://github.com/python/cpython/issues/44626}.)

@item 
@ref{262,,realpath()} now resolves MS-DOS style file names
even if the file is not accessible.
(Contributed by Moonsik Park in gh-82367@footnote{https://github.com/python/cpython/issues/82367}.)
@end itemize

@node pathlib<4>,pdb<3>,os path<2>,改良されたモジュール
@anchor{whatsnew/3 13 pathlib}@anchor{532}
@subsubsection pathlib



@itemize *

@item 
Add @ref{533,,UnsupportedOperation}, which is raised instead of
@ref{36b,,NotImplementedError} when a path operation isn't supported.
(Contributed by Barney Gale in gh-89812@footnote{https://github.com/python/cpython/issues/89812}.)

@item 
Add a new constructor for creating @ref{266,,Path} objects
from 'file' URIs (@code{file:///}), @ref{534,,Path.from_uri()}.
(Contributed by Barney Gale in gh-107465@footnote{https://github.com/python/cpython/issues/107465}.)

@item 
Add @ref{535,,PurePath.full_match()} for matching paths with
shell-style wildcards, including the recursive wildcard "@code{**}".
(Contributed by Barney Gale in gh-73435@footnote{https://github.com/python/cpython/issues/73435}.)

@item 
Add the @ref{536,,PurePath.parser} class attribute to store the
implementation of @ref{a6,,os.path} used
for low-level path parsing and joining.
This will be either @code{posixpath} or @code{ntpath}.

@item 
Add `recurse_symlinks' keyword-only argument to
@ref{537,,Path.glob()} and @ref{538,,rglob()}.
(Contributed by Barney Gale in gh-77609@footnote{https://github.com/python/cpython/issues/77609}.)

@item 
@ref{537,,Path.glob()} and @ref{538,,rglob()}
now return files and directories when given a pattern that ends with "@code{**}".
Previously, only directories were returned.
(Contributed by Barney Gale in gh-70303@footnote{https://github.com/python/cpython/issues/70303}.)

@item 
Add the `follow_symlinks' keyword-only argument to
@ref{539,,Path.is_file},
@ref{53a,,Path.is_dir},
@ref{53b,,Path.owner()}, and @ref{53c,,Path.group()}.
(Contributed by Barney Gale in gh-105793@footnote{https://github.com/python/cpython/issues/105793} and Kamil Turek in gh-107962@footnote{https://github.com/python/cpython/issues/107962}.)
@end itemize

@node pdb<3>,queue,pathlib<4>,改良されたモジュール
@anchor{whatsnew/3 13 pdb}@anchor{53d}
@subsubsection pdb



@itemize *

@item 
@ref{271,,breakpoint()} and @ref{272,,set_trace()} now enter the debugger immediately
rather than on the next line of code to be executed. This change prevents the
debugger from breaking outside of the context when @code{breakpoint()} is positioned
at the end of the context.
(Contributed by Tian Gao in gh-118579@footnote{https://github.com/python/cpython/issues/118579}.)

@item 
@code{sys.path[0]} is no longer replaced by the directory of the script
being debugged when @ref{53e,,sys.flags.safe_path} is set.
(Contributed by Tian Gao and Christian Walther in gh-111762@footnote{https://github.com/python/cpython/issues/111762}.)

@item 
@ref{136,,zipapp} is now supported as a debugging target.
(Contributed by Tian Gao in gh-118501@footnote{https://github.com/python/cpython/issues/118501}.)

@item 
Add ability to move between chained exceptions during
post-mortem debugging in @ref{53f,,pm()} using
the new @ref{540,,exceptions [exc_number]} command for Pdb.
(Contributed by Matthias Bussonnier in gh-106676@footnote{https://github.com/python/cpython/issues/106676}.)

@item 
Expressions and statements whose prefix is a pdb command are now correctly
identified and executed.
(Contributed by Tian Gao in gh-108464@footnote{https://github.com/python/cpython/issues/108464}.)
@end itemize

@node queue,random,pdb<3>,改良されたモジュール
@anchor{whatsnew/3 13 queue}@anchor{541}
@subsubsection queue



@itemize *

@item 
Add @ref{542,,Queue.shutdown} and @ref{543,,ShutDown}
to manage queue termination.
(Contributed by Laurie Opperman and Yves Duprat in gh-104750@footnote{https://github.com/python/cpython/issues/104750}.)
@end itemize

@node random,re<2>,queue,改良されたモジュール
@anchor{whatsnew/3 13 random}@anchor{544}
@subsubsection random



@itemize *

@item 
Add a @ref{47f,,command-line interface}.
(Contributed by Hugo van Kemenade in gh-118131@footnote{https://github.com/python/cpython/issues/118131}.)
@end itemize

@node re<2>,shutil,random,改良されたモジュール
@anchor{whatsnew/3 13 re}@anchor{545}
@subsubsection re



@itemize *

@item 
Rename @code{re.error} to @ref{546,,PatternError} for improved clarity.
@code{re.error} is kept for backward compatibility.
@end itemize

@node shutil,site,re<2>,改良されたモジュール
@anchor{whatsnew/3 13 shutil}@anchor{547}
@subsubsection shutil



@itemize *

@item 
Support the `dir_fd' and `follow_symlinks' keyword arguments
in @ref{548,,chown()}.
(Contributed by Berker Peksag and Tahia K in gh-62308@footnote{https://github.com/python/cpython/issues/62308})
@end itemize

@node site,sqlite3<2>,shutil,改良されたモジュール
@anchor{whatsnew/3 13 site}@anchor{549}
@subsubsection site



@itemize *

@item 
@code{.pth} files are now decoded using UTF-8 first,
and then with the @ref{54a,,locale encoding} if UTF-8 decoding fails.
(Contributed by Inada Naoki in gh-117802@footnote{https://github.com/python/cpython/issues/117802}.)
@end itemize

@node sqlite3<2>,ssl<2>,site,改良されたモジュール
@anchor{whatsnew/3 13 sqlite3}@anchor{54b}
@subsubsection sqlite3



@itemize *

@item 
A @ref{54c,,ResourceWarning} is now emitted if a @ref{54d,,Connection}
object is not @ref{54e,,closed} explicitly.
(Contributed by Erlend E. Aasland in gh-105539@footnote{https://github.com/python/cpython/issues/105539}.)

@item 
Add the `filter' keyword-only parameter to @ref{54f,,Connection.iterdump()}
for filtering database objects to dump.
(Contributed by Mariusz Felisiak in gh-91602@footnote{https://github.com/python/cpython/issues/91602}.)
@end itemize

@node ssl<2>,statistics,sqlite3<2>,改良されたモジュール
@anchor{whatsnew/3 13 ssl}@anchor{550}
@subsubsection ssl



@itemize *

@item 
The @ref{480,,create_default_context()} API now includes
@ref{481,,VERIFY_X509_PARTIAL_CHAIN} and @ref{551,,VERIFY_X509_STRICT}
in its default flags.

@cartouche
@quotation 注釈 
@ref{551,,VERIFY_X509_STRICT} may reject pre-
@geindex RFC; RFC 5280
RFC 5280@footnote{https://datatracker.ietf.org/doc/html/rfc5280.html}
or malformed certificates that the underlying OpenSSL implementation
might otherwise accept.
Whilst disabling this is not recommended, you can do so using:

@example
import ssl

ctx = ssl.create_default_context()
ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT
@end example
@end quotation
@end cartouche

(Contributed by William Woodruff in gh-112389@footnote{https://github.com/python/cpython/issues/112389}.)
@end itemize

@node statistics,subprocess,ssl<2>,改良されたモジュール
@anchor{whatsnew/3 13 statistics}@anchor{552}
@subsubsection statistics



@itemize *

@item 
Add @ref{553,,kde()} for kernel density estimation.
This makes it possible to estimate a continuous probability density function
from a fixed number of discrete samples.
(Contributed by Raymond Hettinger in gh-115863@footnote{https://github.com/python/cpython/issues/115863}.)

@item 
Add @ref{554,,kde_random()} for sampling from an
estimated probability density function created by @ref{553,,kde()}.
(Contributed by Raymond Hettinger in gh-115863@footnote{https://github.com/python/cpython/issues/115863}.)
@end itemize

@node subprocess,sys<2>,statistics,改良されたモジュール
@anchor{whatsnew/3 13 subprocess}@anchor{555}@anchor{whatsnew/3 13 whatsnew313-subprocess}@anchor{556}
@subsubsection subprocess



@itemize *

@item 
The @ref{dc,,subprocess} module now uses the @ref{52e,,posix_spawn()} function in
more situations.

Notably, when `close_fds' is @code{True} (the default),
@ref{52e,,posix_spawn()} will be used when the C library provides
@code{posix_spawn_file_actions_addclosefrom_np()},
which includes recent versions of Linux, FreeBSD, and Solaris.
On Linux, this should perform similarly to the existing
Linux @code{vfork()} based code.

A private control knob @code{subprocess._USE_POSIX_SPAWN} can
be set to @code{False} if you need to force @ref{dc,,subprocess}
to never use @ref{52e,,posix_spawn()}.
Please report your reason and platform details in
the @ref{557,,issue tracker} if you set this
so that we can improve our API selection logic for everyone.
(Contributed by Jakub Kulik in gh-113117@footnote{https://github.com/python/cpython/issues/113117}.)
@end itemize

@node sys<2>,tempfile,subprocess,改良されたモジュール
@anchor{whatsnew/3 13 sys}@anchor{558}
@subsubsection sys



@itemize *

@item 
Add the @ref{559,,_is_interned()} function to test if a string was interned.
This function is not guaranteed to exist in all implementations of Python.
(Contributed by Serhiy Storchaka in gh-78573@footnote{https://github.com/python/cpython/issues/78573}.)
@end itemize

@node tempfile,time,sys<2>,改良されたモジュール
@anchor{whatsnew/3 13 tempfile}@anchor{55a}
@subsubsection tempfile



@itemize *

@item 
On Windows, the default mode @code{0o700} used by @ref{52d,,tempfile.mkdtemp()} now
limits access to the new directory due to changes to @ref{52b,,os.mkdir()}.
This is a mitigation for 
@geindex Common Vulnerabilities and Exposures; CVE 2024-4030
CVE 2024-4030@footnote{https://www.cve.org/CVERecord?id=CVE-2024-4030}.
(Contributed by Steve Dower in gh-118486@footnote{https://github.com/python/cpython/issues/118486}.)
@end itemize

@node time,tkinter<2>,tempfile,改良されたモジュール
@anchor{whatsnew/3 13 time}@anchor{55b}
@subsubsection time



@itemize *

@item 
On Windows, @ref{55c,,monotonic()} now uses the
@code{QueryPerformanceCounter()} clock for a resolution of 1 microsecond,
instead of the @code{GetTickCount64()} clock which has
a resolution of 15.6 milliseconds.
(Contributed by Victor Stinner in gh-88494@footnote{https://github.com/python/cpython/issues/88494}.)

@item 
On Windows, @ref{55d,,time()} now uses the
@code{GetSystemTimePreciseAsFileTime()} clock for a resolution of 1 microsecond,
instead of the @code{GetSystemTimeAsFileTime()} clock which has
a resolution of 15.6 milliseconds.
(Contributed by Victor Stinner in gh-63207@footnote{https://github.com/python/cpython/issues/63207}.)
@end itemize

@node tkinter<2>,traceback,time,改良されたモジュール
@anchor{whatsnew/3 13 tkinter}@anchor{55e}
@subsubsection tkinter



@itemize *

@item 
Add @ref{f6,,tkinter} widget methods:
@code{tk_busy_hold()}, @code{tk_busy_configure()},
@code{tk_busy_cget()}, @code{tk_busy_forget()},
@code{tk_busy_current()}, and @code{tk_busy_status()}.
(Contributed by Miguel, klappnase and Serhiy Storchaka in gh-72684@footnote{https://github.com/python/cpython/issues/72684}.)

@item 
The @ref{f6,,tkinter} widget method @code{wm_attributes()} now accepts
the attribute name without the minus prefix to get window attributes,
for example @code{w.wm_attributes('alpha')}
and allows specifying attributes and values to set as keyword arguments,
for example @code{w.wm_attributes(alpha=0.5)}.
(Contributed by Serhiy Storchaka in gh-43457@footnote{https://github.com/python/cpython/issues/43457}.)

@item 
@code{wm_attributes()} can now return attributes as a @ref{183,,dict},
by using the new optional keyword-only parameter `return_python_dict'.
(Contributed by Serhiy Storchaka in gh-43457@footnote{https://github.com/python/cpython/issues/43457}.)

@item 
@code{Text.count()} can now return a simple @ref{19b,,int}
when the new optional keyword-only parameter `return_ints' is used.
Otherwise, the single count is returned as a 1-tuple or @code{None}.
(Contributed by Serhiy Storchaka in gh-97928@footnote{https://github.com/python/cpython/issues/97928}.)

@item 
Support the "vsapi" element type in
the @ref{55f,,element_create()} method of
@ref{560,,tkinter.ttk.Style}.
(Contributed by Serhiy Storchaka in gh-68166@footnote{https://github.com/python/cpython/issues/68166}.)

@item 
Add the @code{after_info()} method for Tkinter widgets.
(Contributed by Cheryl Sabella in gh-77020@footnote{https://github.com/python/cpython/issues/77020}.)

@item 
Add a new @code{copy_replace()} method to @code{PhotoImage}
to copy a region from one image to another,
possibly with pixel zooming, subsampling, or both.
(Contributed by Serhiy Storchaka in gh-118225@footnote{https://github.com/python/cpython/issues/118225}.)

@item 
Add `from_coords' parameter to the @code{PhotoImage} methods
@code{copy()}, @code{zoom()} and @code{subsample()}.
Add `zoom' and `subsample' parameters to the @code{PhotoImage} method
@code{copy()}.
(Contributed by Serhiy Storchaka in gh-118225@footnote{https://github.com/python/cpython/issues/118225}.)

@item 
Add the @code{PhotoImage} methods
@code{read()} to read an image from a file
and @code{data()} to get the image data.
Add `background' and `grayscale' parameters to the @code{write()} method.
(Contributed by Serhiy Storchaka in gh-118271@footnote{https://github.com/python/cpython/issues/118271}.)
@end itemize

@node traceback,types<2>,tkinter<2>,改良されたモジュール
@anchor{whatsnew/3 13 traceback}@anchor{561}
@subsubsection traceback



@itemize *

@item 
Add the @ref{562,,exc_type_str} attribute
to @ref{563,,TracebackException},
which holds a string display of the `exc_type'.
Deprecate the @ref{564,,exc_type} attribute,
which holds the type object itself.
Add parameter `save_exc_type' (default @code{True})
to indicate whether @code{exc_type} should be saved.
(Contributed by Irit Katriel in gh-112332@footnote{https://github.com/python/cpython/issues/112332}.)

@item 
Add a new `show_group' keyword-only parameter to
@ref{565,,TracebackException.format_exception_only()} to (recursively) format
the nested exceptions of a @ref{566,,BaseExceptionGroup} instance.
(Contributed by Irit Katriel in gh-105292@footnote{https://github.com/python/cpython/issues/105292}.)
@end itemize

@node types<2>,typing<2>,traceback,改良されたモジュール
@anchor{whatsnew/3 13 types}@anchor{567}
@subsubsection types



@itemize *

@item 
@ref{4e5,,SimpleNamespace} can now take a single positional argument
to initialise the namespace's arguments.
This argument must either be a mapping or an iterable of key-value pairs.
(Contributed by Serhiy Storchaka in gh-108191@footnote{https://github.com/python/cpython/issues/108191}.)
@end itemize

@node typing<2>,unicodedata<2>,types<2>,改良されたモジュール
@anchor{whatsnew/3 13 typing}@anchor{568}
@subsubsection typing



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 705
PEP 705@footnote{https://peps.python.org/pep-0705/}: Add @ref{48a,,ReadOnly}, a special typing construct
to mark a @ref{332,,TypedDict} item as read-only for type checkers.

@item 
@geindex Python Enhancement Proposals; PEP 742
PEP 742@footnote{https://peps.python.org/pep-0742/}: Add @ref{48b,,TypeIs}, a typing construct
that can be used to instruct a type checker how to narrow a type.

@item 
Add @ref{569,,NoDefault}, a sentinel object used to represent
the defaults of some parameters in the @ref{10a,,typing} module.
(Contributed by Jelle Zijlstra in gh-116126@footnote{https://github.com/python/cpython/issues/116126}.)

@item 
Add @ref{56a,,get_protocol_members()} to return the set of members
defining a @ref{56b,,typing.Protocol}.
(Contributed by Jelle Zijlstra in gh-104873@footnote{https://github.com/python/cpython/issues/104873}.)

@item 
Add @ref{56c,,is_protocol()} to check whether a class
is a @ref{56b,,Protocol}.
(Contributed by Jelle Zijlstra in gh-104873@footnote{https://github.com/python/cpython/issues/104873}.)

@item 
@ref{56d,,ClassVar} can now be nested in @ref{56e,,Final},
and vice versa.
(Contributed by Mehdi Drissi in gh-89547@footnote{https://github.com/python/cpython/issues/89547}.)
@end itemize

@node unicodedata<2>,venv,typing<2>,改良されたモジュール
@anchor{whatsnew/3 13 unicodedata}@anchor{56f}
@subsubsection unicodedata



@itemize *

@item 
Update the Unicode database to version 15.1.0@footnote{https://www.unicode.org/versions/Unicode15.1.0/}.
(Contributed by James Gerity in gh-109559@footnote{https://github.com/python/cpython/issues/109559}.)
@end itemize

@node venv,warnings,unicodedata<2>,改良されたモジュール
@anchor{whatsnew/3 13 venv}@anchor{570}
@subsubsection venv



@itemize *

@item 
Add support for creating source control management (SCM) ignore files
in a virtual environment's directory.
By default, Git is supported.
This is implemented as opt-in via the API,
which can be extended to support other SCMs
(@ref{571,,EnvBuilder} and @ref{572,,create()}),
and opt-out via the CLI, using @code{--without-scm-ignore-files}.
(Contributed by Brett Cannon in gh-108125@footnote{https://github.com/python/cpython/issues/108125}.)
@end itemize

@node warnings,xml,venv,改良されたモジュール
@anchor{whatsnew/3 13 warnings}@anchor{573}
@subsubsection warnings



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 702
PEP 702@footnote{https://peps.python.org/pep-0702/}: The new @ref{489,,warnings.deprecated()} decorator provides a way to
communicate deprecations to a @ref{574,,static type checker}
and to warn on usage of deprecated classes and functions.
A @ref{1a3,,DeprecationWarning} may also be emitted when
a decorated function or class is used at runtime.
(Contributed by Jelle Zijlstra in gh-104003@footnote{https://github.com/python/cpython/issues/104003}.)
@end itemize

@node xml,zipimport,warnings,改良されたモジュール
@anchor{whatsnew/3 13 xml}@anchor{575}
@subsubsection xml



@itemize *

@item 
Allow controlling Expat >=2.6.0 reparse deferral (
@geindex Common Vulnerabilities and Exposures; CVE 2023-52425
CVE 2023-52425@footnote{https://www.cve.org/CVERecord?id=CVE-2023-52425})
by adding five new methods:


@itemize *

@item 
@ref{576,,xml.etree.ElementTree.XMLParser.flush()}

@item 
@ref{577,,xml.etree.ElementTree.XMLPullParser.flush()}

@item 
@ref{578,,xml.parsers.expat.xmlparser.GetReparseDeferralEnabled()}

@item 
@ref{579,,xml.parsers.expat.xmlparser.SetReparseDeferralEnabled()}

@item 
@code{xml.sax.expatreader.ExpatParser.flush()}
@end itemize

(Contributed by Sebastian Pipping in gh-115623@footnote{https://github.com/python/cpython/issues/115623}.)

@item 
Add the @code{close()} method for the iterator returned by
@ref{57a,,iterparse()} for explicit cleanup.
(Contributed by Serhiy Storchaka in gh-69893@footnote{https://github.com/python/cpython/issues/69893}.)
@end itemize

@node zipimport,,xml,改良されたモジュール
@anchor{whatsnew/3 13 zipimport}@anchor{57b}
@subsubsection zipimport



@itemize *

@item 
Add support for ZIP64@footnote{https://en.wikipedia.org/wiki/Zip_(file_format)#ZIP64} format files.
Everybody loves huge data, right?
(Contributed by Tim Hatch in gh-94146@footnote{https://github.com/python/cpython/issues/94146}.)
@end itemize

@node 最適化<2>,Removed Modules And APIs,改良されたモジュール,What's New In Python 3 13
@anchor{whatsnew/3 13 optimizations}@anchor{57c}
@subsection 最適化



@itemize *

@item 
Several standard library modules have had
their import times significantly improved.
For example, the import time of the @ref{10a,,typing} module
has been reduced by around a third by removing dependencies
on @ref{be,,re} and @ref{27,,contextlib}.
Other modules to enjoy import-time speedups include
@ref{54,,email.utils}, @ref{5a,,enum}, @ref{63,,functools},
@ref{7e,,importlib.metadata}, and @ref{f3,,threading}.
(Contributed by Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas,
and others in gh-109653@footnote{https://github.com/python/cpython/issues/109653}.)

@item 
@ref{57d,,textwrap.indent()} is now around 30% faster than before for large input.
(Contributed by Inada Naoki in gh-107369@footnote{https://github.com/python/cpython/issues/107369}.)

@item 
The @ref{dc,,subprocess} module now uses the @ref{52e,,posix_spawn()} function in
more situations, including when `close_fds' is @code{True} (the default)
on many modern platforms.
This should provide a notable performance increase
when launching processes on FreeBSD and Solaris.
See the @ref{556,,subprocess} section above for details.
(Contributed by Jakub Kulik in gh-113117@footnote{https://github.com/python/cpython/issues/113117}.)
@end itemize

@node Removed Modules And APIs,New Deprecations,最適化<2>,What's New In Python 3 13
@anchor{whatsnew/3 13 removed-modules-and-apis}@anchor{57e}
@subsection Removed Modules And APIs


@menu
* PEP 594; Remove "dead batteries" from the standard library: PEP 594 Remove "dead batteries" from the standard library. 
* 2to3:: 
* builtins:: 
* configparser: configparser<3>. 
* importlib.metadata: importlib metadata. 
* locale:: 
* opcode:: 
* optparse:: 
* pathlib: pathlib<5>. 
* re: re<3>. 
* tkinter.tix: tkinter tix. 
* turtle: turtle<2>. 
* typing: typing<3>. 
* unittest: unittest<2>. 
* urllib: urllib<3>. 
* webbrowser: webbrowser<2>. 

@end menu

@node PEP 594 Remove "dead batteries" from the standard library,2to3,,Removed Modules And APIs
@anchor{whatsnew/3 13 pep-594-remove-dead-batteries-from-the-standard-library}@anchor{57f}@anchor{whatsnew/3 13 whatsnew313-pep594}@anchor{471}
@subsubsection PEP 594: Remove "dead batteries" from the standard library


@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} proposed removing 19 modules from the standard library,
colloquially referred to as 'dead batteries' due to their
historic, obsolete, or insecure status.
All of the following modules were deprecated in Python 3.11,
and are now removed:


@itemize *

@item 
@code{aifc}


@itemize *

@item 
standard-aifc@footnote{https://pypi.org/project/standard-aifc/}:
Use the redistribution of @code{aifc} library from PyPI.
@end itemize

@item 
@code{audioop}


@itemize *

@item 
audioop-lts@footnote{https://pypi.org/project/audioop-lts/}:
Use @code{audioop-lts} library from PyPI.
@end itemize

@item 
@code{chunk}


@itemize *

@item 
standard-chunk@footnote{https://pypi.org/project/standard-chunk/}:
Use the redistribution of @code{chunk} library from PyPI.
@end itemize

@item 
@code{cgi} and @code{cgitb}


@itemize *

@item 
@code{cgi.FieldStorage} can typically be replaced with
@ref{31e,,urllib.parse.parse_qsl()} for @code{GET} and @code{HEAD} requests,
and the @ref{48,,email.message} module or the multipart@footnote{https://pypi.org/project/multipart/} library
for @code{POST} and @code{PUT} requests.

@item 
@code{cgi.parse()} can be replaced by calling
@ref{31f,,urllib.parse.parse_qs()} directly on the desired query string,
unless the input is @code{multipart/form-data},
which should be replaced as described below for @code{cgi.parse_multipart()}.

@item 
@code{cgi.parse_header()} can be replaced with the functionality
in the @ref{3f,,email} package, which implements the same MIME RFCs.
For example, with @ref{580,,email.message.EmailMessage}:

@example
from email.message import EmailMessage

msg = EmailMessage()
msg['content-type'] = 'application/json; charset="utf8"'
main, params = msg.get_content_type(), msg['content-type'].params
@end example

@item 
@code{cgi.parse_multipart()} can be replaced with the functionality
in the @ref{3f,,email} package, which implements the same MIME RFCs,
or with the multipart@footnote{https://pypi.org/project/multipart/} library.
For example, the @ref{580,,email.message.EmailMessage}
and @ref{581,,email.message.Message} classes.

@item 
standard-cgi@footnote{https://pypi.org/project/standard-cgi/}: and standard-cgitb@footnote{https://pypi.org/project/standard-cgitb/}:
Use the redistribution of @code{cgi} and @code{cgitb} library from PyPI.
@end itemize

@item 
@code{crypt} and the private @code{_crypt} extension.
The @ref{6c,,hashlib} module may be an appropriate replacement
when simply hashing a value is required.
Otherwise, various third-party libraries on PyPI are available:


@itemize *

@item 
bcrypt@footnote{https://pypi.org/project/bcrypt/}:
Modern password hashing for your software and your servers.

@item 
argon2-cffi@footnote{https://pypi.org/project/argon2-cffi/}:
The secure Argon2 password hashing algorithm.

@item 
legacycrypt@footnote{https://pypi.org/project/legacycrypt/}:
@ref{2e,,ctypes} wrapper to the POSIX crypt library call
and associated functionality.

@item 
crypt_r@footnote{https://pypi.org/project/crypt_r/}:
Fork of the @code{crypt} module,
wrapper to the @code{crypt_r(3)@footnote{https://manpages.debian.org/crypt_r(3)}} library call
and associated functionality.

@item 
standard-crypt@footnote{https://pypi.org/project/standard-crypt/} and deprecated-crypt-alternative@footnote{https://pypi.org/project/deprecated-crypt-alternative/}:
Use the redistribution of @code{crypt} and reimplementation of @code{_crypt} libraries from PyPI.
@end itemize

@item 
@code{imghdr}:
The filetype@footnote{https://pypi.org/project/filetype/}, puremagic@footnote{https://pypi.org/project/puremagic/}, or python-magic@footnote{https://pypi.org/project/python-magic/} libraries
should be used as replacements.
For example, the @code{puremagic.what()} function can be used
to replace the @code{imghdr.what()} function for all file formats
that were supported by @code{imghdr}.


@itemize *

@item 
standard-imghdr@footnote{https://pypi.org/project/standard-imghdr/}:
Use the redistribution of @code{imghdr} library from PyPI.
@end itemize

@item 
@code{mailcap}:
Use the @ref{93,,mimetypes} module instead.


@itemize *

@item 
standard-mailcap@footnote{https://pypi.org/project/standard-mailcap/}:
Use the redistribution of @code{mailcap} library from PyPI.
@end itemize

@item 
@code{msilib}

@item 
@code{nis}

@item 
@code{nntplib}:
Use the pynntp@footnote{https://pypi.org/project/pynntp/} library from PyPI instead.


@itemize *

@item 
standard-nntplib@footnote{https://pypi.org/project/standard-nntplib/}:
Use the redistribution of @code{nntplib} library from PyPI.
@end itemize

@item 
@code{ossaudiodev}:
For audio playback, use the pygame@footnote{https://pypi.org/project/pygame/} library from PyPI instead.

@item 
@code{pipes}:
Use the @ref{dc,,subprocess} module instead.
Use @ref{582,,shlex.quote()} to replace the undocumented @code{pipes.quote}
function.


@itemize *

@item 
standard-pipes@footnote{https://pypi.org/project/standard-pipes/}:
Use the redistribution of @code{pipes} library from PyPI.
@end itemize

@item 
@code{sndhdr}:
The filetype@footnote{https://pypi.org/project/filetype/}, puremagic@footnote{https://pypi.org/project/puremagic/}, or python-magic@footnote{https://pypi.org/project/python-magic/} libraries
should be used as replacements.


@itemize *

@item 
standard-sndhdr@footnote{https://pypi.org/project/standard-sndhdr/}:
Use the redistribution of @code{sndhdr} library from PyPI.
@end itemize

@item 
@code{spwd}:
Use the python-pam@footnote{https://pypi.org/project/python-pam/} library from PyPI instead.

@item 
@code{sunau}


@itemize *

@item 
standard-sunau@footnote{https://pypi.org/project/standard-sunau/}:
Use the redistribution of @code{sunau} library from PyPI.
@end itemize

@item 
@code{telnetlib},
Use the telnetlib3@footnote{https://pypi.org/project/telnetlib3/} or Exscript@footnote{https://pypi.org/project/Exscript/} libraries from PyPI instead.


@itemize *

@item 
standard-telnetlib@footnote{https://pypi.org/project/standard-telnetlib/}:
Use the redistribution of @code{telnetlib} library from PyPI.
@end itemize

@item 
@code{uu}:
Use the @ref{f,,base64} module instead, as a modern alternative.


@itemize *

@item 
standard-uu@footnote{https://pypi.org/project/standard-uu/}:
Use the redistribution of @code{uu} library from PyPI.
@end itemize

@item 
@code{xdrlib}


@itemize *

@item 
standard-xdrlib@footnote{https://pypi.org/project/standard-xdrlib/}:
Use the redistribution of @code{xdrlib} library from PyPI.
@end itemize
@end itemize

(Contributed by Victor Stinner and Zachary Ware in gh-104773@footnote{https://github.com/python/cpython/issues/104773} and gh-104780@footnote{https://github.com/python/cpython/issues/104780}.)

@node 2to3,builtins,PEP 594 Remove "dead batteries" from the standard library,Removed Modules And APIs
@anchor{whatsnew/3 13 to3}@anchor{583}
@subsubsection 2to3



@itemize *

@item 
Remove the @code{2to3} program and the @code{lib2to3} module,
previously deprecated in Python 3.11.
(Contributed by Victor Stinner in gh-104780@footnote{https://github.com/python/cpython/issues/104780}.)
@end itemize

@node builtins,configparser<3>,2to3,Removed Modules And APIs
@anchor{whatsnew/3 13 builtins}@anchor{584}
@subsubsection builtins



@itemize *

@item 
Remove support for chained @ref{48e,,classmethod} descriptors
(introduced in gh-63272@footnote{https://github.com/python/cpython/issues/63272}).
These can no longer be used to wrap other descriptors,
such as @ref{4b3,,property}.
The core design of this feature was flawed and led to several problems.
To "pass-through" a @ref{48e,,classmethod}, consider using
the @code{__wrapped__} attribute that was added in Python 3.10.
(Contributed by Raymond Hettinger in gh-89519@footnote{https://github.com/python/cpython/issues/89519}.)

@item 
Raise a @ref{244,,RuntimeError} when calling @ref{585,,frame.clear()}
on a suspended frame (as has always been the case for an executing frame).
(Contributed by Irit Katriel in gh-79932@footnote{https://github.com/python/cpython/issues/79932}.)
@end itemize

@node configparser<3>,importlib metadata,builtins,Removed Modules And APIs
@anchor{whatsnew/3 13 id3}@anchor{586}
@subsubsection configparser



@itemize *

@item 
Remove the undocumented @code{LegacyInterpolation} class,
deprecated in the docstring since Python 3.2,
and at runtime since Python 3.11.
(Contributed by Hugo van Kemenade in gh-104886@footnote{https://github.com/python/cpython/issues/104886}.)
@end itemize

@node importlib metadata,locale,configparser<3>,Removed Modules And APIs
@anchor{whatsnew/3 13 importlib-metadata}@anchor{587}
@subsubsection importlib.metadata



@itemize *

@item 
Remove deprecated subscript (@ref{588,,__getitem__()}) access for
@ref{589,,EntryPoint} objects.
(Contributed by Jason R. Coombs in gh-113175@footnote{https://github.com/python/cpython/issues/113175}.)
@end itemize

@node locale,opcode,importlib metadata,Removed Modules And APIs
@anchor{whatsnew/3 13 locale}@anchor{58a}
@subsubsection locale



@itemize *

@item 
Remove the @code{locale.resetlocale()} function, deprecated in Python 3.11.
Use @code{locale.setlocale(locale.LC_ALL, "")} instead.
(Contributed by Victor Stinner in gh-104783@footnote{https://github.com/python/cpython/issues/104783}.)
@end itemize

@node opcode,optparse,locale,Removed Modules And APIs
@anchor{whatsnew/3 13 opcode}@anchor{58b}
@subsubsection opcode



@itemize *

@item 
Move @code{opcode.ENABLE_SPECIALIZATION} to @code{_opcode.ENABLE_SPECIALIZATION}.
This field was added in 3.12, it was never documented,
and is not intended for external use.
(Contributed by Irit Katriel in gh-105481@footnote{https://github.com/python/cpython/issues/105481}.)

@item 
Remove @code{opcode.is_pseudo()}, @code{opcode.MIN_PSEUDO_OPCODE},
and @code{opcode.MAX_PSEUDO_OPCODE}, which were added in Python 3.12,
but were neither documented nor exposed through @ref{3c,,dis},
and were not intended to be used externally.
(Contributed by Irit Katriel in gh-105481@footnote{https://github.com/python/cpython/issues/105481}.)
@end itemize

@node optparse,pathlib<5>,opcode,Removed Modules And APIs
@anchor{whatsnew/3 13 optparse}@anchor{58c}
@subsubsection optparse



@itemize *

@item 
This module is no longer considered @ref{23d,,soft deprecated}.
While @ref{7,,argparse} remains preferred for new projects that
aren't using a third party command line argument processing
library, there are aspects of the way @code{argparse} works that
mean the lower level @code{optparse} module may provide a better
foundation for `writing' argument processing libraries, and
for implementing command line applications which adhere more
strictly than @code{argparse} does to various Unix command line
processing conventions that originate in the behaviour of the
C @code{getopt()} function .
(Contributed by Alyssa Coghlan and Serhiy Storchaka in gh-126180@footnote{https://github.com/python/cpython/issues/126180}.)
@end itemize

@node pathlib<5>,re<3>,optparse,Removed Modules And APIs
@anchor{whatsnew/3 13 id4}@anchor{58d}
@subsubsection pathlib



@itemize *

@item 
Remove the ability to use @ref{266,,Path} objects as context managers.
This functionality was deprecated and has had no effect since Python 3.9.
(Contributed by Barney Gale in gh-83863@footnote{https://github.com/python/cpython/issues/83863}.)
@end itemize

@node re<3>,tkinter tix,pathlib<5>,Removed Modules And APIs
@anchor{whatsnew/3 13 id5}@anchor{58e}
@subsubsection re



@itemize *

@item 
Remove the undocumented, deprecated, and broken
@code{re.template()} function and @code{re.TEMPLATE} / @code{re.T} flag.
(Contributed by Serhiy Storchaka and Nikita Sobolev in gh-105687@footnote{https://github.com/python/cpython/issues/105687}.)
@end itemize

@node tkinter tix,turtle<2>,re<3>,Removed Modules And APIs
@anchor{whatsnew/3 13 tkinter-tix}@anchor{58f}
@subsubsection tkinter.tix



@itemize *

@item 
Remove the @code{tkinter.tix} module, deprecated in Python 3.6.
The third-party Tix library which the module wrapped is unmaintained.
(Contributed by Zachary Ware in gh-75552@footnote{https://github.com/python/cpython/issues/75552}.)
@end itemize

@node turtle<2>,typing<3>,tkinter tix,Removed Modules And APIs
@anchor{whatsnew/3 13 turtle}@anchor{590}
@subsubsection @code{turtle}



@itemize *

@item 
Remove the @code{RawTurtle.settiltangle()} method,
deprecated in the documentation since Python 3.1
and at runtime since Python 3.11.
(Contributed by Hugo van Kemenade in gh-104876@footnote{https://github.com/python/cpython/issues/104876}.)
@end itemize

@node typing<3>,unittest<2>,turtle<2>,Removed Modules And APIs
@anchor{whatsnew/3 13 id6}@anchor{591}
@subsubsection typing



@itemize *

@item 
Remove the @code{typing.io} and @code{typing.re} namespaces,
deprecated since Python 3.8.
The items in those namespaces can be imported directly
from the @ref{10a,,typing} module.
(Contributed by Sebastian Rittau in gh-92871@footnote{https://github.com/python/cpython/issues/92871}.)

@item 
Remove the keyword-argument method of creating
@ref{332,,TypedDict} types, deprecated in Python 3.11.
(Contributed by Tomas Roun in gh-104786@footnote{https://github.com/python/cpython/issues/104786}.)
@end itemize

@node unittest<2>,urllib<3>,typing<3>,Removed Modules And APIs
@anchor{whatsnew/3 13 unittest}@anchor{592}
@subsubsection unittest



@itemize *

@item 
Remove the following @ref{10c,,unittest} functions, deprecated in Python 3.11:


@itemize *

@item 
@code{unittest.findTestCases()}

@item 
@code{unittest.makeSuite()}

@item 
@code{unittest.getTestCaseNames()}
@end itemize

Use @ref{593,,TestLoader} methods instead:


@itemize *

@item 
@ref{594,,loadTestsFromModule()}

@item 
@ref{595,,loadTestsFromTestCase()}

@item 
@ref{596,,getTestCaseNames()}
@end itemize

(Contributed by Hugo van Kemenade in gh-104835@footnote{https://github.com/python/cpython/issues/104835}.)

@item 
Remove the untested and undocumented @code{TestProgram.usageExit()}
method, deprecated in Python 3.11.
(Contributed by Hugo van Kemenade in gh-104992@footnote{https://github.com/python/cpython/issues/104992}.)
@end itemize

@node urllib<3>,webbrowser<2>,unittest<2>,Removed Modules And APIs
@anchor{whatsnew/3 13 urllib}@anchor{597}
@subsubsection urllib



@itemize *

@item 
Remove the `cafile', `capath', and `cadefault' parameters of the
@ref{307,,urllib.request.urlopen()} function, deprecated in Python 3.6.
Use the `context' parameter instead with an @ref{357,,SSLContext} instance.
The @ref{598,,ssl.SSLContext.load_cert_chain()} function
can be used to load specific certificates,
or let @ref{480,,ssl.create_default_context()} select
the operating system's trusted certificate authority (CA) certificates.
(Contributed by Victor Stinner in gh-105382@footnote{https://github.com/python/cpython/issues/105382}.)
@end itemize

@node webbrowser<2>,,urllib<3>,Removed Modules And APIs
@anchor{whatsnew/3 13 webbrowser}@anchor{599}
@subsubsection webbrowser



@itemize *

@item 
Remove the untested and undocumented @code{MacOSX} class,
deprecated in Python 3.11.
Use the @code{MacOSXOSAScript} class (introduced in Python 3.2) instead.
(Contributed by Hugo van Kemenade in gh-104804@footnote{https://github.com/python/cpython/issues/104804}.)

@item 
Remove the deprecated @code{MacOSXOSAScript._name} attribute.
Use the @ref{59a,,MacOSXOSAScript.name}
attribute instead.
(Contributed by Nikita Sobolev in gh-105546@footnote{https://github.com/python/cpython/issues/105546}.)
@end itemize

@node New Deprecations,CPython Bytecode Changes,Removed Modules And APIs,What's New In Python 3 13
@anchor{whatsnew/3 13 new-deprecations}@anchor{59b}
@subsection New Deprecations



@itemize *

@item 
@ref{59c,,User-defined functions}:


@itemize *

@item 
Deprecate assignment to a function's @ref{59d,,__code__} attribute,
where the new code object's type does not match the function's type.
The different types are:
plain function, generator, async generator, and coroutine.
(Contributed by Irit Katriel in gh-81137@footnote{https://github.com/python/cpython/issues/81137}.)
@end itemize

@item 
@ref{8,,array}:


@itemize *

@item 
Deprecate the @code{'u'} format code (@code{wchar_t}) at runtime.
This format code has been deprecated in documentation since Python 3.3,
and will be removed in Python 3.16.
Use the @code{'w'} format code (@ref{33d,,Py_UCS4})
for Unicode characters instead.
(Contributed by Hugo van Kemenade in gh-80480@footnote{https://github.com/python/cpython/issues/80480}.)
@end itemize

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
Deprecate the undocumented @code{SetPointerType()} function,
to be removed in Python 3.15.
(Contributed by Victor Stinner in gh-105733@footnote{https://github.com/python/cpython/issues/105733}.)

@item 
@ref{23d,,Soft-deprecate} the @ref{59e,,ARRAY()}
function in favour of @code{type * length} multiplication.
(Contributed by Victor Stinner in gh-105733@footnote{https://github.com/python/cpython/issues/105733}.)
@end itemize

@item 
@ref{3a,,decimal}:


@itemize *

@item 
Deprecate the non-standard and undocumented @ref{1fe,,Decimal}
format specifier @code{'N'},
which is only supported in the @code{decimal} module's C implementation.
Scheduled to be removed in Python 3.18.
(Contributed by Serhiy Storchaka in gh-89902@footnote{https://github.com/python/cpython/issues/89902}.)
@end itemize

@item 
@ref{3c,,dis}:


@itemize *

@item 
Deprecate the @code{HAVE_ARGUMENT} separator.
Check membership in @ref{59f,,hasarg} instead.
(Contributed by Irit Katriel in gh-109319@footnote{https://github.com/python/cpython/issues/109319}.)
@end itemize

@item 
@ref{67,,gettext}:


@itemize *

@item 
Deprecate non-integer numbers as arguments to functions and methods
that consider plural forms in the @code{gettext} module,
even if no translation was found.
(Contributed by Serhiy Storchaka in gh-88434@footnote{https://github.com/python/cpython/issues/88434}.)
@end itemize

@item 
@ref{68,,glob}:


@itemize *

@item 
Deprecate the undocumented @code{glob0()} and @code{glob1()} functions.
Use @ref{5a0,,glob()} and pass a @ref{5a1,,path-like object} specifying
the root directory to the `root_dir' parameter instead.
(Contributed by Barney Gale in gh-117337@footnote{https://github.com/python/cpython/issues/117337}.)
@end itemize

@item 
@ref{76,,http.server}:


@itemize *

@item 
Deprecate @ref{325,,CGIHTTPRequestHandler},
to be removed in Python 3.15.
Process-based CGI HTTP servers have been out of favor for a very long time.
This code was outdated, unmaintained, and rarely used.
It has a high potential for both security and functionality bugs.
(Contributed by Gregory P. Smith in gh-109096@footnote{https://github.com/python/cpython/issues/109096}.)

@item 
Deprecate the @code{--cgi} flag to
the @code{python -m http.server} command-line interface,
to be removed in Python 3.15.
(Contributed by Gregory P. Smith in gh-109096@footnote{https://github.com/python/cpython/issues/109096}.)
@end itemize

@item 
@ref{93,,mimetypes}:


@itemize *

@item 
@ref{23d,,Soft-deprecate} file path arguments
to @ref{517,,guess_type()},
use @ref{516,,guess_file_type()} instead.
(Contributed by Serhiy Storchaka in gh-66543@footnote{https://github.com/python/cpython/issues/66543}.)
@end itemize

@item 
@ref{be,,re}:


@itemize *

@item 
Deprecate passing the optional `maxsplit', `count', or `flags' arguments
as positional arguments to the module-level
@ref{5a2,,split()}, @ref{5a3,,sub()}, and @ref{5a4,,subn()} functions.
These parameters will become @ref{5a5,,keyword-only}
in a future version of Python.
(Contributed by Serhiy Storchaka in gh-56166@footnote{https://github.com/python/cpython/issues/56166}.)
@end itemize

@item 
@ref{a8,,pathlib}:


@itemize *

@item 
Deprecate @ref{32a,,PurePath.is_reserved()},
to be removed in Python 3.15.
Use @ref{32b,,os.path.isreserved()} to detect reserved paths on Windows.
(Contributed by Barney Gale in gh-88569@footnote{https://github.com/python/cpython/issues/88569}.)
@end itemize

@item 
@ref{af,,platform}:


@itemize *

@item 
Deprecate @ref{32c,,java_ver()},
to be removed in Python 3.15.
This function is only useful for Jython support, has a confusing API,
and is largely untested.
(Contributed by Nikita Sobolev in gh-116349@footnote{https://github.com/python/cpython/issues/116349}.)
@end itemize

@item 
@ref{ba,,pydoc}:


@itemize *

@item 
Deprecate the undocumented @code{ispackage()} function.
(Contributed by Zackery Spytz in gh-64020@footnote{https://github.com/python/cpython/issues/64020}.)
@end itemize

@item 
@ref{d4,,sqlite3}:


@itemize *

@item 
Deprecate passing more than one positional argument to
the @ref{5a6,,connect()} function
and the @ref{54d,,Connection} constructor.
The remaining parameters will become keyword-only in Python 3.15.
(Contributed by Erlend E. Aasland in gh-107948@footnote{https://github.com/python/cpython/issues/107948}.)

@item 
Deprecate passing name, number of arguments, and the callable as keyword
arguments for @ref{5a7,,Connection.create_function()}
and @ref{5a8,,Connection.create_aggregate()}
These parameters will become positional-only in Python 3.15.
(Contributed by Erlend E. Aasland in gh-108278@footnote{https://github.com/python/cpython/issues/108278}.)

@item 
Deprecate passing the callback callable by keyword for the
@ref{5a9,,set_authorizer()},
@ref{5aa,,set_progress_handler()}, and
@ref{5ab,,set_trace_callback()}
@ref{54d,,Connection} methods.
The callback callables will become positional-only in Python 3.15.
(Contributed by Erlend E. Aasland in gh-108278@footnote{https://github.com/python/cpython/issues/108278}.)
@end itemize

@item 
@ref{df,,sys}:


@itemize *

@item 
Deprecate the @ref{33e,,_enablelegacywindowsfsencoding()} function,
to be removed in Python 3.16.
Use the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} environment variable instead.
(Contributed by Inada Naoki in gh-73427@footnote{https://github.com/python/cpython/issues/73427}.)
@end itemize

@item 
@ref{e4,,tarfile}:


@itemize *

@item 
Deprecate the undocumented and unused @code{TarFile.tarfile} attribute,
to be removed in Python 3.16.
(Contributed in gh-115256@footnote{https://github.com/python/cpython/issues/115256}.)
@end itemize

@item 
@ref{104,,traceback}:


@itemize *

@item 
Deprecate the @ref{564,,TracebackException.exc_type} attribute.
Use @ref{562,,TracebackException.exc_type_str} instead.
(Contributed by Irit Katriel in gh-112332@footnote{https://github.com/python/cpython/issues/112332}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize *

@item 
Deprecate the undocumented keyword argument syntax for creating
@ref{331,,NamedTuple} classes
(e.g. @code{Point = NamedTuple("Point", x=int, y=int)}),
to be removed in Python 3.15.
Use the class-based syntax or the functional syntax instead.
(Contributed by Alex Waygood in gh-105566@footnote{https://github.com/python/cpython/issues/105566}.)

@item 
Deprecate omitting the `fields' parameter when creating
a @ref{331,,NamedTuple} or @ref{332,,typing.TypedDict} class,
and deprecate passing @code{None} to the `fields' parameter of both types.
Python 3.15 will require a valid sequence for the `fields' parameter.
To create a NamedTuple class with zero fields,
use @code{class NT(NamedTuple): pass} or @code{NT = NamedTuple("NT", ())}.
To create a TypedDict class with zero fields,
use @code{class TD(TypedDict): pass} or @code{TD = TypedDict("TD", @{@})}.
(Contributed by Alex Waygood in gh-105566@footnote{https://github.com/python/cpython/issues/105566} and gh-105570@footnote{https://github.com/python/cpython/issues/105570}.)

@item 
Deprecate the @ref{333,,typing.no_type_check_decorator()} decorator function,
to be removed in Python 3.15.
After eight years in the @ref{10a,,typing} module,
it has yet to be supported by any major type checker.
(Contributed by Alex Waygood in gh-106309@footnote{https://github.com/python/cpython/issues/106309}.)

@item 
Deprecate @ref{5ac,,typing.AnyStr}.
In Python 3.16, it will be removed from @code{typing.__all__},
and a @ref{1a3,,DeprecationWarning} will be emitted at runtime
when it is imported or accessed.
It will be removed entirely in Python 3.18.
Use the new @ref{5ad,,type parameter syntax} instead.
(Contributed by Michael The in gh-107116@footnote{https://github.com/python/cpython/issues/107116}.)
@end itemize

@item 
@ref{119,,wave}:


@itemize *

@item 
Deprecate the @ref{334,,getmark()}, @code{setmark()},
and @ref{335,,getmarkers()} methods of
the @ref{336,,Wave_read} and @ref{337,,Wave_write} classes,
to be removed in Python 3.15.
(Contributed by Victor Stinner in gh-105096@footnote{https://github.com/python/cpython/issues/105096}.)
@end itemize
@end itemize

@c Add deprecations above alphabetically, not here at the end.

@menu
* Pending removal in Python 3.14: Pending removal in Python 3 14. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<3>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<3>. 
* Pending removal in Python 3.17: Pending removal in Python 3 17<2>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<3>. 
* Pending removal in Python 3.19: Pending removal in Python 3 19<2>. 
* Pending removal in future versions: Pending removal in future versions<3>. 

@end menu

@node Pending removal in Python 3 14,Pending removal in Python 3 15<3>,,New Deprecations
@anchor{whatsnew/3 13 pending-removal-in-python-3-14}@anchor{5ae}
@subsubsection Pending removal in Python 3.14



@itemize *

@item 
@ref{7,,argparse}: The `type', `choices', and `metavar' parameters
of @code{argparse.BooleanOptionalAction} are deprecated
and will be removed in 3.14.
(Contributed by Nikita Sobolev in gh-92248@footnote{https://github.com/python/cpython/issues/92248}.)

@item 
@ref{9,,ast}: The following features have been deprecated in documentation
since Python 3.8, now cause a @ref{1a3,,DeprecationWarning} to be emitted at
runtime when they are accessed or used, and will be removed in Python 3.14:


@itemize *

@item 
@code{ast.Num}

@item 
@code{ast.Str}

@item 
@code{ast.Bytes}

@item 
@code{ast.NameConstant}

@item 
@code{ast.Ellipsis}
@end itemize

Use @ref{2ef,,ast.Constant} instead.
(Contributed by Serhiy Storchaka in gh-90953@footnote{https://github.com/python/cpython/issues/90953}.)

@item 
@ref{b,,asyncio}:


@itemize *

@item 
The child watcher classes @code{asyncio.MultiLoopChildWatcher},
@code{asyncio.FastChildWatcher}, @code{asyncio.AbstractChildWatcher}
and @code{asyncio.SafeChildWatcher} are deprecated and
will be removed in Python 3.14.
(Contributed by Kumar Aditya in gh-94597@footnote{https://github.com/python/cpython/issues/94597}.)

@item 
@code{asyncio.set_child_watcher()}, @code{asyncio.get_child_watcher()},
@code{asyncio.AbstractEventLoopPolicy.set_child_watcher()} and
@code{asyncio.AbstractEventLoopPolicy.get_child_watcher()} are deprecated
and will be removed in Python 3.14.
(Contributed by Kumar Aditya in gh-94597@footnote{https://github.com/python/cpython/issues/94597}.)

@item 
The @ref{2f2,,get_event_loop()} method of the
default event loop policy now emits a @ref{1a3,,DeprecationWarning} if there
is no current event loop set and it decides to create one.
(Contributed by Serhiy Storchaka and Guido van Rossum in gh-100160@footnote{https://github.com/python/cpython/issues/100160}.)
@end itemize

@item 
@ref{3f,,email}: Deprecated the `isdst' parameter in @ref{2f7,,email.utils.localtime()}.
(Contributed by Alan Williams in gh-72346@footnote{https://github.com/python/cpython/issues/72346}.)

@item 
@ref{7c,,importlib.abc} deprecated classes:


@itemize *

@item 
@code{importlib.abc.ResourceReader}

@item 
@code{importlib.abc.Traversable}

@item 
@code{importlib.abc.TraversableResources}
@end itemize

Use @ref{80,,importlib.resources.abc} classes instead:


@itemize *

@item 
@ref{2fa,,importlib.resources.abc.Traversable}

@item 
@ref{2f9,,importlib.resources.abc.TraversableResources}
@end itemize

(Contributed by Jason R. Coombs and Hugo van Kemenade in gh-93963@footnote{https://github.com/python/cpython/issues/93963}.)

@item 
@ref{85,,itertools} had undocumented, inefficient, historically buggy,
and inconsistent support for copy, deepcopy, and pickle operations.
This will be removed in 3.14 for a significant reduction in code
volume and maintenance burden.
(Contributed by Raymond Hettinger in gh-101588@footnote{https://github.com/python/cpython/issues/101588}.)

@item 
@ref{98,,multiprocessing}: The default start method will change to a safer one on
Linux, BSDs, and other non-macOS POSIX platforms where @code{'fork'} is currently
the default (gh-84559@footnote{https://github.com/python/cpython/issues/84559}). Adding a runtime warning about this was deemed too
disruptive as the majority of code is not expected to care. Use the
@ref{24a,,get_context()} or
@ref{24b,,set_start_method()} APIs to explicitly specify when
your code `requires' @code{'fork'}.  See @ref{1d5,,コンテキストと開始方式}.

@item 
@ref{a8,,pathlib}: @ref{2fe,,is_relative_to()} and
@ref{2fd,,relative_to()}: passing additional arguments is
deprecated.

@item 
@ref{ae,,pkgutil}: @code{pkgutil.find_loader()} and @code{pkgutil.get_loader()}
now raise @ref{1a3,,DeprecationWarning};
use @ref{5af,,importlib.util.find_spec()} instead.
(Contributed by Nikita Sobolev in gh-97850@footnote{https://github.com/python/cpython/issues/97850}.)

@item 
@ref{b6,,pty}:


@itemize *

@item 
@code{master_open()}: use @ref{301,,pty.openpty()}.

@item 
@code{slave_open()}: use @ref{301,,pty.openpty()}.
@end itemize

@item 
@ref{d4,,sqlite3}:


@itemize *

@item 
@code{version} and @code{version_info}.

@item 
@ref{5b0,,execute()} and @ref{5b1,,executemany()}
if @ref{5b2,,named placeholders} are used and
`parameters' is a sequence instead of a @ref{183,,dict}.
@end itemize

@item 
@ref{10e,,urllib}:
@code{urllib.parse.Quoter} is deprecated: it was not intended to be a
public API.
(Contributed by Gregory P. Smith in gh-88168@footnote{https://github.com/python/cpython/issues/88168}.)
@end itemize

@node Pending removal in Python 3 15<3>,Pending removal in Python 3 16<3>,Pending removal in Python 3 14,New Deprecations
@anchor{whatsnew/3 13 pending-removal-in-python-3-15}@anchor{5b3}
@subsubsection Pending removal in Python 3.15



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{321,,__cached__} on a module while
failing to set @ref{322,,__spec__.cached}
is deprecated. In Python 3.15, @code{__cached__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})

@item 
Setting @ref{323,,__package__} on a module while
failing to set @ref{324,,__spec__.parent}
is deprecated. In Python 3.15, @code{__package__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})
@end itemize

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
The undocumented @code{ctypes.SetPointerType()} function
has been deprecated since Python 3.13.
@end itemize

@item 
@ref{76,,http.server}:


@itemize *

@item 
The obsolete and rarely used @ref{325,,CGIHTTPRequestHandler}
has been deprecated since Python 3.13.
No direct replacement exists.
`Anything' is better than CGI to interface
a web server with a request handler.

@item 
The @code{--cgi} flag to the @code{python -m http.server}
command-line interface has been deprecated since Python 3.13.
@end itemize

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@code{load_module()} method: use @code{exec_module()} instead.
@end itemize

@item 
@ref{8a,,locale}:


@itemize *

@item 
The @ref{326,,getdefaultlocale()} function
has been deprecated since Python 3.11.
Its removal was originally planned for Python 3.13 (gh-90817@footnote{https://github.com/python/cpython/issues/90817}),
but has been postponed to Python 3.15.
Use @ref{327,,getlocale()}, @ref{328,,setlocale()},
and @ref{329,,getencoding()} instead.
(Contributed by Hugo van Kemenade in gh-111187@footnote{https://github.com/python/cpython/issues/111187}.)
@end itemize

@item 
@ref{a8,,pathlib}:


@itemize *

@item 
@ref{32a,,PurePath.is_reserved()}
has been deprecated since Python 3.13.
Use @ref{32b,,os.path.isreserved()} to detect reserved paths on Windows.
@end itemize

@item 
@ref{af,,platform}:


@itemize *

@item 
@ref{32c,,java_ver()} has been deprecated since Python 3.13.
This function is only useful for Jython support, has a confusing API,
and is largely untested.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The `check_home' argument of @ref{32d,,sysconfig.is_python_build()} has been
deprecated since Python 3.12.
@end itemize

@item 
@ref{f3,,threading}:


@itemize *

@item 
@ref{32e,,RLock()} will take no arguments in Python 3.15.
Passing any arguments has been deprecated since Python 3.14,
as the Python version does not permit any arguments,
but the C version allows any number of positional or keyword arguments,
ignoring every argument.
@end itemize

@item 
@ref{109,,types}:


@itemize *

@item 
@ref{32f,,types.CodeType}: Accessing @ref{330,,co_lnotab} was
deprecated in 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/}
since 3.10 and was planned to be removed in 3.12,
but it only got a proper @ref{1a3,,DeprecationWarning} in 3.12.
May be removed in 3.15.
(Contributed by Nikita Sobolev in gh-101866@footnote{https://github.com/python/cpython/issues/101866}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize *

@item 
The undocumented keyword argument syntax for creating
@ref{331,,NamedTuple} classes
(for example, @code{Point = NamedTuple("Point", x=int, y=int)})
has been deprecated since Python 3.13.
Use the class-based syntax or the functional syntax instead.

@item 
When using the functional syntax of @ref{332,,TypedDict}s, failing
to pass a value to the `fields' parameter (@code{TD = TypedDict("TD")}) or
passing @code{None} (@code{TD = TypedDict("TD", None)}) has been deprecated
since Python 3.13.
Use @code{class TD(TypedDict): pass} or @code{TD = TypedDict("TD", @{@})}
to create a TypedDict with zero field.

@item 
The @ref{333,,typing.no_type_check_decorator()} decorator function
has been deprecated since Python 3.13.
After eight years in the @ref{10a,,typing} module,
it has yet to be supported by any major type checker.
@end itemize

@item 
@ref{119,,wave}:


@itemize *

@item 
The @ref{334,,getmark()}, @code{setmark()},
and @ref{335,,getmarkers()} methods of
the @ref{336,,Wave_read} and @ref{337,,Wave_write} classes
have been deprecated since Python 3.13.
@end itemize

@item 
@ref{138,,zipimport}:


@itemize *

@item 
@ref{338,,load_module()} has been deprecated since
Python 3.10. Use @ref{339,,exec_module()} instead.
(Contributed by Jiahao Li in gh-125746@footnote{https://github.com/python/cpython/issues/125746}.)
@end itemize
@end itemize

@node Pending removal in Python 3 16<3>,Pending removal in Python 3 17<2>,Pending removal in Python 3 15<3>,New Deprecations
@anchor{whatsnew/3 13 pending-removal-in-python-3-16}@anchor{5b4}
@subsubsection Pending removal in Python 3.16



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{33b,,__loader__} on a module while
failing to set @ref{33c,,__spec__.loader}
is deprecated. In Python 3.16, @code{__loader__} will cease to be set or
taken into consideration by the import system or the standard library.
@end itemize

@item 
@ref{8,,array}:


@itemize *

@item 
The @code{'u'} format code (@code{wchar_t})
has been deprecated in documentation since Python 3.3
and at runtime since Python 3.13.
Use the @code{'w'} format code (@ref{33d,,Py_UCS4})
for Unicode characters instead.
@end itemize

@item 
@ref{b,,asyncio}:


@itemize *

@item 
@code{asyncio.iscoroutinefunction()} is deprecated
and will be removed in Python 3.16;
use @ref{30d,,inspect.iscoroutinefunction()} instead.
(Contributed by Jiahao Li and Kumar Aditya in gh-122875@footnote{https://github.com/python/cpython/issues/122875}.)

@item 
@ref{b,,asyncio} policy system is deprecated and will be removed in Python 3.16.
In particular, the following classes and functions are deprecated:


@itemize *

@item 
@ref{30e,,asyncio.AbstractEventLoopPolicy}

@item 
@ref{30f,,asyncio.DefaultEventLoopPolicy}

@item 
@ref{310,,asyncio.WindowsSelectorEventLoopPolicy}

@item 
@ref{311,,asyncio.WindowsProactorEventLoopPolicy}

@item 
@ref{312,,asyncio.get_event_loop_policy()}

@item 
@ref{313,,asyncio.set_event_loop_policy()}
@end itemize

Users should use @ref{2f3,,asyncio.run()} or @ref{2f5,,asyncio.Runner} with
`loop_factory' to use the desired event loop implementation.

For example, to use @ref{314,,asyncio.SelectorEventLoop} on Windows:

@example
import asyncio

async def main():
    ...

asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
@end example

(Contributed by Kumar Aditya in gh-127949@footnote{https://github.com/python/cpython/issues/127949}.)
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Bitwise inversion on boolean types, @code{~True} or @code{~False}
has been deprecated since Python 3.12,
as it produces surprising and unintuitive results (@code{-2} and @code{-1}).
Use @code{not x} instead for the logical negation of a Boolean.
In the rare case that you need the bitwise inversion of
the underlying integer, convert to @code{int} explicitly (@code{~int(x)}).
@end itemize

@item 
@ref{63,,functools}:


@itemize *

@item 
Calling the Python implementation of @ref{21a,,functools.reduce()} with `function'
or `sequence' as keyword arguments has been deprecated since Python 3.14.
@end itemize

@item 
@ref{8b,,logging}:

Support for custom logging handlers with the `strm' argument is deprecated
and scheduled for removal in Python 3.16. Define handlers with the `stream'
argument instead. (Contributed by Mariusz Felisiak in gh-115032@footnote{https://github.com/python/cpython/issues/115032}.)

@item 
@ref{93,,mimetypes}:


@itemize *

@item 
Valid extensions start with a '.' or are empty for
@ref{319,,mimetypes.MimeTypes.add_type()}.
Undotted extensions are deprecated and will
raise a @ref{2ec,,ValueError} in Python 3.16.
(Contributed by Hugo van Kemenade in gh-75223@footnote{https://github.com/python/cpython/issues/75223}.)
@end itemize

@item 
@ref{ca,,shutil}:


@itemize *

@item 
The @code{ExecError} exception
has been deprecated since Python 3.14.
It has not been used by any function in @code{shutil} since Python 3.4,
and is now an alias of @ref{244,,RuntimeError}.
@end itemize

@item 
@ref{de,,symtable}:


@itemize *

@item 
The @ref{31d,,Class.get_methods} method
has been deprecated since Python 3.14.
@end itemize

@item 
@ref{df,,sys}:


@itemize *

@item 
The @ref{33e,,_enablelegacywindowsfsencoding()} function
has been deprecated since Python 3.13.
Use the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} environment variable instead.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The @code{sysconfig.expand_makefile_vars()} function
has been deprecated since Python 3.14.
Use the @code{vars} argument of @ref{340,,sysconfig.get_paths()} instead.
@end itemize

@item 
@ref{e4,,tarfile}:


@itemize *

@item 
The undocumented and unused @code{TarFile.tarfile} attribute
has been deprecated since Python 3.13.
@end itemize
@end itemize

@node Pending removal in Python 3 17<2>,Pending removal in Python 3 18<3>,Pending removal in Python 3 16<3>,New Deprecations
@anchor{whatsnew/3 13 pending-removal-in-python-3-17}@anchor{5b5}
@subsubsection Pending removal in Python 3.17



@itemize *

@item 
@ref{1f,,collections.abc}:


@itemize -

@item 
@ref{342,,collections.abc.ByteString} is scheduled for removal in Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize -

@item 
Before Python 3.14, old-style unions were implemented using the private class
@code{typing._UnionGenericAlias}. This class is no longer needed for the implementation,
but it has been retained for backward compatibility, with removal scheduled for Python
3.17. Users should use documented introspection helpers like @ref{2ab,,typing.get_origin()}
and @ref{2ac,,typing.get_args()} instead of relying on private implementation details.

@item 
@ref{345,,typing.ByteString}, deprecated since Python 3.9, is scheduled for removal in
Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize
@end itemize

@node Pending removal in Python 3 18<3>,Pending removal in Python 3 19<2>,Pending removal in Python 3 17<2>,New Deprecations
@anchor{whatsnew/3 13 pending-removal-in-python-3-18}@anchor{5b6}
@subsubsection Pending removal in Python 3.18



@itemize *

@item 
@ref{3a,,decimal}:


@itemize *

@item 
The non-standard and undocumented @ref{1fe,,Decimal} format
specifier @code{'N'}, which is only supported in the @code{decimal} module's
C implementation, has been deprecated since Python 3.13.
(Contributed by Serhiy Storchaka in gh-89902@footnote{https://github.com/python/cpython/issues/89902}.)
@end itemize
@end itemize

@node Pending removal in Python 3 19<2>,Pending removal in future versions<3>,Pending removal in Python 3 18<3>,New Deprecations
@anchor{whatsnew/3 13 pending-removal-in-python-3-19}@anchor{5b7}
@subsubsection Pending removal in Python 3.19



@itemize *

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
Implicitly switching to the MSVC-compatible struct layout by setting
@ref{317,,_pack_} but not @ref{1e7,,_layout_}
on non-Windows platforms.
@end itemize
@end itemize

@node Pending removal in future versions<3>,,Pending removal in Python 3 19<2>,New Deprecations
@anchor{whatsnew/3 13 pending-removal-in-future-versions}@anchor{5b8}
@subsubsection Pending removal in future versions


The following APIs will be removed in the future,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{7,,argparse}:


@itemize *

@item 
Nesting argument groups and nesting mutually exclusive
groups are deprecated.

@item 
Passing the undocumented keyword argument `prefix_chars' to
@ref{2eb,,add_argument_group()} is now
deprecated.

@item 
The @ref{30c,,argparse.FileType} type converter is deprecated.
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Generators: @code{throw(type, exc, tb)} and @code{athrow(type, exc, tb)}
signature is deprecated: use @code{throw(exc)} and @code{athrow(exc)} instead,
the single argument signature.

@item 
Currently Python accepts numeric literals immediately followed by keywords,
for example @code{0in x}, @code{1or x}, @code{0if 1else 2}.  It allows confusing and
ambiguous expressions like @code{[0x1for x in y]} (which can be interpreted as
@code{[0x1 for x in y]} or @code{[0x1f or x in y]}).  A syntax warning is raised
if the numeric literal is immediately followed by one of keywords
@ref{349,,and}, @ref{17c,,else}, @ref{34a,,for}, @ref{181,,if},
@ref{34b,,in}, @ref{34c,,is} and @ref{34d,,or}.  In a future release it
will be changed to a syntax error. (gh-87999@footnote{https://github.com/python/cpython/issues/87999})

@item 
Support for @code{__index__()} and @code{__int__()} method returning non-int type:
these methods will be required to return an instance of a strict subclass of
@ref{19b,,int}.

@item 
Support for @code{__float__()} method returning a strict subclass of
@ref{196,,float}: these methods will be required to return an instance of
@ref{196,,float}.

@item 
Support for @code{__complex__()} method returning a strict subclass of
@ref{197,,complex}: these methods will be required to return an instance of
@ref{197,,complex}.

@item 
Passing a complex number as the `real' or `imag' argument in the
@ref{197,,complex()} constructor is now deprecated; it should only be passed
as a single positional argument.
(Contributed by Serhiy Storchaka in gh-109218@footnote{https://github.com/python/cpython/issues/109218}.)
@end itemize

@item 
@ref{15,,calendar}: @code{calendar.January} and @code{calendar.February} constants are
deprecated and replaced by @ref{34e,,calendar.JANUARY} and
@ref{34f,,calendar.FEBRUARY}.
(Contributed by Prince Roshan in gh-103636@footnote{https://github.com/python/cpython/issues/103636}.)

@item 
@ref{1c,,codecs}: use @ref{316,,open()} instead of @ref{315,,codecs.open()}. (gh-133038@footnote{https://github.com/python/cpython/issues/133038})

@item 
@ref{330,,codeobject.co_lnotab}: use the @ref{350,,codeobject.co_lines()} method
instead.

@item 
@ref{34,,datetime}:


@itemize *

@item 
@ref{351,,utcnow()}:
use @code{datetime.datetime.now(tz=datetime.UTC)}.

@item 
@ref{352,,utcfromtimestamp()}:
use @code{datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)}.
@end itemize

@item 
@ref{67,,gettext}: Plural value must be an integer.

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@ref{353,,cache_from_source()} `debug_override' parameter is
deprecated: use the `optimization' parameter instead.
@end itemize

@item 
@ref{7e,,importlib.metadata}:


@itemize *

@item 
@code{EntryPoints} tuple interface.

@item 
Implicit @code{None} on return values.
@end itemize

@item 
@ref{8b,,logging}: the @code{warn()} method has been deprecated
since Python 3.3, use @ref{354,,warning()} instead.

@item 
@ref{8f,,mailbox}: Use of StringIO input and text mode is deprecated, use
BytesIO and binary mode instead.

@item 
@ref{a5,,os}: Calling @ref{355,,os.register_at_fork()} in multi-threaded process.

@item 
@code{pydoc.ErrorDuringImport}: A tuple value for `exc_info' parameter is
deprecated, use an exception instance.

@item 
@ref{be,,re}: More strict rules are now applied for numerical group references
and group names in regular expressions.  Only sequence of ASCII digits is now
accepted as a numerical reference.  The group name in bytes patterns and
replacement strings can now only contain ASCII letters and digits and
underscore.
(Contributed by Serhiy Storchaka in gh-91760@footnote{https://github.com/python/cpython/issues/91760}.)

@item 
@code{sre_compile}, @code{sre_constants} and @code{sre_parse} modules.

@item 
@ref{ca,,shutil}: @ref{356,,rmtree()}'s `onerror' parameter is deprecated in
Python 3.12; use the `onexc' parameter instead.

@item 
@ref{d5,,ssl} options and protocols:


@itemize *

@item 
@ref{357,,ssl.SSLContext} without protocol argument is deprecated.

@item 
@ref{357,,ssl.SSLContext}: @ref{358,,set_npn_protocols()} and
@code{selected_npn_protocol()} are deprecated: use ALPN
instead.

@item 
@code{ssl.OP_NO_SSL*} options

@item 
@code{ssl.OP_NO_TLS*} options

@item 
@code{ssl.PROTOCOL_SSLv3}

@item 
@code{ssl.PROTOCOL_TLS}

@item 
@code{ssl.PROTOCOL_TLSv1}

@item 
@code{ssl.PROTOCOL_TLSv1_1}

@item 
@code{ssl.PROTOCOL_TLSv1_2}

@item 
@code{ssl.TLSVersion.SSLv3}

@item 
@code{ssl.TLSVersion.TLSv1}

@item 
@code{ssl.TLSVersion.TLSv1_1}
@end itemize

@item 
@ref{f3,,threading} methods:


@itemize *

@item 
@code{threading.Condition.notifyAll()}: use @ref{359,,notify_all()}.

@item 
@code{threading.Event.isSet()}: use @ref{35a,,is_set()}.

@item 
@code{threading.Thread.isDaemon()}, @ref{35b,,threading.Thread.setDaemon()}:
use @ref{35c,,threading.Thread.daemon} attribute.

@item 
@code{threading.Thread.getName()}, @ref{35d,,threading.Thread.setName()}:
use @ref{2a0,,threading.Thread.name} attribute.

@item 
@code{threading.currentThread()}: use @ref{35e,,threading.current_thread()}.

@item 
@code{threading.activeCount()}: use @ref{35f,,threading.active_count()}.
@end itemize

@item 
@ref{360,,typing.Text} (gh-92332@footnote{https://github.com/python/cpython/issues/92332}).

@item 
The internal class @code{typing._UnionGenericAlias} is no longer used to implement
@ref{2a8,,typing.Union}. To preserve compatibility with users using this private
class, a compatibility shim will be provided until at least Python 3.17. (Contributed by
Jelle Zijlstra in gh-105499@footnote{https://github.com/python/cpython/issues/105499}.)

@item 
@ref{361,,unittest.IsolatedAsyncioTestCase}: it is deprecated to return a value
that is not @code{None} from a test case.

@item 
@ref{110,,urllib.parse} deprecated functions: @ref{362,,urlparse()} instead


@itemize *

@item 
@code{splitattr()}

@item 
@code{splithost()}

@item 
@code{splitnport()}

@item 
@code{splitpasswd()}

@item 
@code{splitport()}

@item 
@code{splitquery()}

@item 
@code{splittag()}

@item 
@code{splittype()}

@item 
@code{splituser()}

@item 
@code{splitvalue()}

@item 
@code{to_bytes()}
@end itemize

@item 
@ref{11e,,wsgiref}: @code{SimpleHandler.stdout.write()} should not do partial
writes.

@item 
@ref{12b,,xml.etree.ElementTree}: Testing the truth value of an
@ref{363,,Element} is deprecated. In a future release it
will always return @code{True}. Prefer explicit @code{len(elem)} or
@code{elem is not None} tests instead.

@item 
@ref{292,,sys._clear_type_cache()} is deprecated:
use @ref{364,,sys._clear_internal_caches()} instead.
@end itemize

@node CPython Bytecode Changes,C API の変更<2>,New Deprecations,What's New In Python 3 13
@anchor{whatsnew/3 13 cpython-bytecode-changes}@anchor{5b9}
@subsection CPython Bytecode Changes



@itemize *

@item 
The oparg of @ref{5ba,,YIELD_VALUE} is now
@code{1} if the yield is part of a yield-from or await, and @code{0} otherwise.
The oparg of @ref{5bb,,RESUME} was changed to add a bit indicating
if the except-depth is 1, which is needed to optimize closing of generators.
(Contributed by Irit Katriel in gh-111354@footnote{https://github.com/python/cpython/issues/111354}.)
@end itemize

@node C API の変更<2>,Build Changes,CPython Bytecode Changes,What's New In Python 3 13
@anchor{whatsnew/3 13 c-api-changes}@anchor{5bc}
@subsection C API の変更


@menu
* 新しい機能: 新しい機能<3>. 
* Changed C APIs:: 
* Limited C API Changes:: 
* Removed C APIs: Removed C APIs<2>. 
* Deprecated C APIs: Deprecated C APIs<2>. 

@end menu

@node 新しい機能<3>,Changed C APIs,,C API の変更<2>
@anchor{whatsnew/3 13 id7}@anchor{5bd}
@subsubsection 新しい機能



@itemize *

@item 
Add the @ref{485,,PyMonitoring C API}
for generating 
@geindex Python Enhancement Proposals; PEP 669
PEP 669@footnote{https://peps.python.org/pep-0669/} monitoring events:


@itemize *

@item 
@ref{5be,,PyMonitoringState}

@item 
@ref{5bf,,PyMonitoring_FirePyStartEvent()}

@item 
@ref{5c0,,PyMonitoring_FirePyResumeEvent()}

@item 
@ref{5c1,,PyMonitoring_FirePyReturnEvent()}

@item 
@ref{5c2,,PyMonitoring_FirePyYieldEvent()}

@item 
@ref{5c3,,PyMonitoring_FireCallEvent()}

@item 
@ref{5c4,,PyMonitoring_FireLineEvent()}

@item 
@ref{5c5,,PyMonitoring_FireJumpEvent()}

@item 
@code{PyMonitoring_FireBranchEvent}

@item 
@ref{5c6,,PyMonitoring_FireCReturnEvent()}

@item 
@ref{5c7,,PyMonitoring_FirePyThrowEvent()}

@item 
@ref{5c8,,PyMonitoring_FireRaiseEvent()}

@item 
@ref{5c9,,PyMonitoring_FireCRaiseEvent()}

@item 
@ref{5ca,,PyMonitoring_FireReraiseEvent()}

@item 
@ref{5cb,,PyMonitoring_FireExceptionHandledEvent()}

@item 
@ref{5cc,,PyMonitoring_FirePyUnwindEvent()}

@item 
@ref{5cd,,PyMonitoring_FireStopIterationEvent()}

@item 
@ref{5ce,,PyMonitoring_EnterScope()}

@item 
@ref{5cf,,PyMonitoring_ExitScope()}
@end itemize

(Contributed by Irit Katriel in gh-111997@footnote{https://github.com/python/cpython/issues/111997}).

@item 
Add @ref{484,,PyMutex}, a lightweight mutex that occupies a single byte,
and the new @ref{5d0,,PyMutex_Lock()} and @ref{5d1,,PyMutex_Unlock()} functions.
@code{PyMutex_Lock()} will release the @ref{164,,GIL} (if currently held)
if the operation needs to block.
(Contributed by Sam Gross in gh-108724@footnote{https://github.com/python/cpython/issues/108724}.)

@item 
Add the @ref{5d2,,PyTime C API} to provide access to system clocks:


@itemize *

@item 
@ref{5d3,,PyTime_t}.

@item 
@ref{5d4,,PyTime_MIN} and @ref{5d5,,PyTime_MAX}.

@item 
@ref{5d6,,PyTime_AsSecondsDouble()}.

@item 
@ref{5d7,,PyTime_Monotonic()}.

@item 
@ref{5d8,,PyTime_MonotonicRaw()}.

@item 
@ref{5d9,,PyTime_PerfCounter()}.

@item 
@ref{5da,,PyTime_PerfCounterRaw()}.

@item 
@ref{5db,,PyTime_Time()}.

@item 
@ref{5dc,,PyTime_TimeRaw()}.
@end itemize

(Contributed by Victor Stinner and Petr Viktorin in gh-110850@footnote{https://github.com/python/cpython/issues/110850}.)

@item 
Add the @ref{5dd,,PyDict_ContainsString()} function
with the same behavior as @ref{5de,,PyDict_Contains()},
but `key' is specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.
(Contributed by Victor Stinner in gh-108314@footnote{https://github.com/python/cpython/issues/108314}.)

@item 
Add the @ref{5e0,,PyDict_GetItemRef()} and @ref{421,,PyDict_GetItemStringRef()}
functions,
which behave similarly to @ref{5e1,,PyDict_GetItemWithError()},
but return a  @ref{5e2,,strong reference} instead of a @ref{3d7,,borrowed reference}.
Moreover, these functions return @code{-1} on error,
removing the need to check @code{PyErr_Occurred()}.
(Contributed by Victor Stinner in gh-106004@footnote{https://github.com/python/cpython/issues/106004}.)

@item 
Add the @ref{5e3,,PyDict_SetDefaultRef()} function,
which behaves similarly to @ref{5e4,,PyDict_SetDefault()},
but returns a @ref{5e2,,strong reference} instead of a @ref{3d7,,borrowed reference}.
This function returns @code{-1} on error,
@code{0} on insertion,
and @code{1} if the key was already present in the dictionary.
(Contributed by Sam Gross in gh-112066@footnote{https://github.com/python/cpython/issues/112066}.)

@item 
Add the @ref{422,,PyDict_Pop()} and @ref{5e5,,PyDict_PopString()} functions
to remove a key from a dictionary and optionally return the removed value.
This is similar to @ref{5e6,,dict.pop()},
though there is no default value,
and @ref{5e7,,KeyError} is not raised for missing keys.
(Contributed by Stefan Behnel and Victor Stinner in gh-111262@footnote{https://github.com/python/cpython/issues/111262}.)

@item 
Add the @ref{5e8,,PyMapping_GetOptionalItem()}
and @ref{5e9,,PyMapping_GetOptionalItemString()} functions
as alternatives to @ref{5ea,,PyObject_GetItem()}
and @ref{5eb,,PyMapping_GetItemString()} respectively.
The new functions do not raise @ref{5e7,,KeyError}
if the requested key is missing from the mapping.
These variants are more convenient and faster
if a missing key should not be treated as a failure.
(Contributed by Serhiy Storchaka in gh-106307@footnote{https://github.com/python/cpython/issues/106307}.)

@item 
Add the @ref{5ec,,PyObject_GetOptionalAttr()}
and @ref{5ed,,PyObject_GetOptionalAttrString()} functions
as alternatives to  @ref{5ee,,PyObject_GetAttr()}
and @ref{5ef,,PyObject_GetAttrString()} respectively.
The new functions do not raise @ref{5f0,,AttributeError}
if the requested attribute is not found on the object.
These variants are more convenient and faster
if the missing attribute should not be treated as a failure.
(Contributed by Serhiy Storchaka in gh-106521@footnote{https://github.com/python/cpython/issues/106521}.)

@item 
Add the @ref{5f1,,PyErr_FormatUnraisable()} function
as an extension to @ref{5f2,,PyErr_WriteUnraisable()}
that allows customizing the warning message.
(Contributed by Serhiy Storchaka in gh-108082@footnote{https://github.com/python/cpython/issues/108082}.)

@item 
Add new functions that return a @ref{5e2,,strong reference} instead of
a @ref{3d7,,borrowed reference} for frame locals, globals, and builtins,
as part of @ref{470,,PEP 667}:


@itemize *

@item 
@ref{5f3,,PyEval_GetFrameBuiltins()} replaces @ref{5f4,,PyEval_GetBuiltins()}

@item 
@ref{5f5,,PyEval_GetFrameGlobals()} replaces @ref{5f6,,PyEval_GetGlobals()}

@item 
@ref{5f7,,PyEval_GetFrameLocals()} replaces @ref{5f8,,PyEval_GetLocals()}
@end itemize

(Contributed by Mark Shannon and Tian Gao in gh-74929@footnote{https://github.com/python/cpython/issues/74929}.)

@item 
Add the @ref{5f9,,Py_GetConstant()} and @ref{5fa,,Py_GetConstantBorrowed()}
functions to get @ref{5e2,,strong}
or @ref{3d7,,borrowed} references to constants.
For example, @code{Py_GetConstant(Py_CONSTANT_ZERO)} returns a strong reference
to the constant zero.
(Contributed by Victor  Stinner in gh-115754@footnote{https://github.com/python/cpython/issues/115754}.)

@item 
Add the @ref{5fb,,PyImport_AddModuleRef()} function
as a replacement for @ref{5fc,,PyImport_AddModule()}
that returns a @ref{5e2,,strong reference} instead of a @ref{3d7,,borrowed reference}.
(Contributed by Victor Stinner in gh-105922@footnote{https://github.com/python/cpython/issues/105922}.)

@item 
Add the @ref{5fd,,Py_IsFinalizing()} function to check
whether the main Python interpreter is
@ref{479,,shutting down}.
(Contributed by Victor Stinner in gh-108014@footnote{https://github.com/python/cpython/issues/108014}.)

@item 
Add the @ref{5fe,,PyList_GetItemRef()} function
as a replacement for @ref{5ff,,PyList_GetItem()}
that returns a @ref{5e2,,strong reference} instead of a @ref{3d7,,borrowed reference}.
(Contributed by Sam Gross in gh-114329@footnote{https://github.com/python/cpython/issues/114329}.)

@item 
Add the @ref{600,,PyList_Extend()} and @ref{601,,PyList_Clear()} functions,
mirroring the Python @ref{602,,list.extend()} and @ref{603,,list.clear()} methods.
(Contributed by Victor Stinner in gh-111138@footnote{https://github.com/python/cpython/issues/111138}.)

@item 
Add the @ref{604,,PyLong_AsInt()} function.
It behaves similarly to @ref{605,,PyLong_AsLong()},
but stores the result in a C int instead of a C long.
(Contributed by Victor Stinner in gh-108014@footnote{https://github.com/python/cpython/issues/108014}.)

@item 
Add the @ref{606,,PyLong_AsNativeBytes()}, @ref{607,,PyLong_FromNativeBytes()},
and @ref{608,,PyLong_FromUnsignedNativeBytes()} functions
to simplify converting between native integer types
and Python @ref{19b,,int} objects.
(Contributed by Steve Dower in gh-111140@footnote{https://github.com/python/cpython/issues/111140}.)

@item 
Add @ref{609,,PyModule_Add()} function, which is similar to
@ref{60a,,PyModule_AddObjectRef()} and @ref{60b,,PyModule_AddObject()},
but always steals a reference to the value.
(Contributed by Serhiy Storchaka in gh-86493@footnote{https://github.com/python/cpython/issues/86493}.)

@item 
Add the @ref{60c,,PyObject_GenericHash()} function
that implements the default hashing function of a Python object.
(Contributed by Serhiy Storchaka in gh-113024@footnote{https://github.com/python/cpython/issues/113024}.)

@item 
Add the @ref{425,,Py_HashPointer()} function to hash a raw pointer.
(Contributed by Victor Stinner in gh-111545@footnote{https://github.com/python/cpython/issues/111545}.)

@item 
Add the @ref{60d,,PyObject_VisitManagedDict()} and
@ref{60e,,PyObject_ClearManagedDict()} functions.
which must be called by the traverse and clear functions of a type using
the @ref{60f,,Py_TPFLAGS_MANAGED_DICT} flag.
The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to
use these functions with Python 3.11 and 3.12.
(Contributed by Victor Stinner in gh-107073@footnote{https://github.com/python/cpython/issues/107073}.)

@item 
Add the @ref{610,,PyRefTracer_SetTracer()}
and @ref{611,,PyRefTracer_GetTracer()} functions,
which enable tracking object creation and destruction
in the same way that the @ref{105,,tracemalloc} module does.
(Contributed by Pablo Galindo in gh-93502@footnote{https://github.com/python/cpython/issues/93502}.)

@item 
Add the @ref{612,,PySys_AuditTuple()} function
as an alternative to @ref{613,,PySys_Audit()}
that takes event arguments as a Python @ref{614,,tuple} object.
(Contributed by Victor Stinner in gh-85283@footnote{https://github.com/python/cpython/issues/85283}.)

@item 
Add the @ref{423,,PyThreadState_GetUnchecked()} function
as an alternative to @ref{615,,PyThreadState_Get()}
that doesn't kill the process with a fatal error if it is @code{NULL}.
The caller is responsible for checking if the result is @code{NULL}.
(Contributed by Victor Stinner in gh-108867@footnote{https://github.com/python/cpython/issues/108867}.)

@item 
Add the @ref{616,,PyType_GetFullyQualifiedName()} function
to get the type's fully qualified name.
The module name is prepended if @ref{617,,type.__module__} is
a string and is not equal to either @code{'builtins'} or @code{'__main__'}.
(Contributed by Victor Stinner in gh-111696@footnote{https://github.com/python/cpython/issues/111696}.)

@item 
Add the @ref{618,,PyType_GetModuleName()} function
to get the type's module name. This is equivalent to getting the
@ref{617,,type.__module__} attribute.
(Contributed by Eric Snow and Victor Stinner in gh-111696@footnote{https://github.com/python/cpython/issues/111696}.)

@item 
Add the @ref{619,,PyUnicode_EqualToUTF8AndSize()}
and @ref{61a,,PyUnicode_EqualToUTF8()} functions
to compare a Unicode object with a const char* UTF-8 encoded string
and @code{1} if they are equal or @code{0} otherwise.
These functions do not raise exceptions.
(Contributed by Serhiy Storchaka in gh-110289@footnote{https://github.com/python/cpython/issues/110289}.)

@item 
Add the @ref{3df,,PyWeakref_GetRef()} function
as an alternative to  @ref{3dd,,PyWeakref_GetObject()}
that returns a @ref{5e2,,strong reference}
or @code{NULL} if the referent is no longer live.
(Contributed by Victor Stinner in gh-105927@footnote{https://github.com/python/cpython/issues/105927}.)

@item 
Add fixed variants of functions which silently ignore errors:


@itemize *

@item 
@ref{61b,,PyObject_HasAttrWithError()} replaces @ref{61c,,PyObject_HasAttr()}.

@item 
@ref{61d,,PyObject_HasAttrStringWithError()}
replaces @ref{61e,,PyObject_HasAttrString()}.

@item 
@ref{61f,,PyMapping_HasKeyWithError()} replaces @ref{620,,PyMapping_HasKey()}.

@item 
@ref{621,,PyMapping_HasKeyStringWithError()}
replaces @ref{622,,PyMapping_HasKeyString()}.
@end itemize

The new functions return @code{-1} for errors
and the standard @code{1} for true and @code{0} for false.

(Contributed by Serhiy Storchaka in gh-108511@footnote{https://github.com/python/cpython/issues/108511}.)
@end itemize

@node Changed C APIs,Limited C API Changes,新しい機能<3>,C API の変更<2>
@anchor{whatsnew/3 13 changed-c-apis}@anchor{623}
@subsubsection Changed C APIs



@itemize *

@item 
The `keywords' parameter of @ref{624,,PyArg_ParseTupleAndKeywords()}
and @ref{625,,PyArg_VaParseTupleAndKeywords()}
now has type char *const* in C
and const char *const* in C++,
instead of char**.
In C++, this makes these functions compatible with arguments
of type const char *const*, const char**,
or char *const* without an explicit type cast.
In C, the functions only support arguments of type char *const*.
This can be overridden with the @ref{626,,PY_CXX_CONST} macro.
(Contributed by Serhiy Storchaka in gh-65210@footnote{https://github.com/python/cpython/issues/65210}.)

@item 
@ref{624,,PyArg_ParseTupleAndKeywords()} now supports
non-ASCII keyword parameter names.
(Contributed by Serhiy Storchaka in gh-110815@footnote{https://github.com/python/cpython/issues/110815}.)

@item 
The @code{PyCode_GetFirstFree()} function is now unstable API
and is now named @ref{627,,PyUnstable_Code_GetFirstFree()}.
(Contributed by Bogdan Romanyuk in gh-115781@footnote{https://github.com/python/cpython/issues/115781}.)

@item 
The @ref{628,,PyDict_GetItem()}, @ref{629,,PyDict_GetItemString()},
@ref{620,,PyMapping_HasKey()}, @ref{622,,PyMapping_HasKeyString()},
@ref{61c,,PyObject_HasAttr()}, @ref{61e,,PyObject_HasAttrString()},
and @ref{62a,,PySys_GetObject()} functions,
each of which clears all errors which occurred when calling them
now reports these errors using @ref{507,,sys.unraisablehook()}.
You may replace them with other functions as recommended in the documentation.
(Contributed by Serhiy Storchaka in gh-106672@footnote{https://github.com/python/cpython/issues/106672}.)

@item 
Add support for the @code{%T}, @code{%#T}, @code{%N} and @code{%#N} formats
to @ref{62b,,PyUnicode_FromFormat()}:


@itemize *

@item 
@code{%T}: Get the fully qualified name of an object type

@item 
@code{%#T}: As above, but use a colon as the separator

@item 
@code{%N}: Get the fully qualified name of a type

@item 
@code{%#N}: As above, but use a colon as the separator
@end itemize

See 
@geindex Python Enhancement Proposals; PEP 737
PEP 737@footnote{https://peps.python.org/pep-0737/} for more information.
(Contributed by Victor Stinner in gh-111696@footnote{https://github.com/python/cpython/issues/111696}.)

@item 
You no longer have to define the @code{PY_SSIZE_T_CLEAN} macro before
including @code{Python.h} when using @code{#} formats in
@ref{62c,,format codes}.
APIs accepting the format codes always use @code{Py_ssize_t} for @code{#} formats.
(Contributed by Inada Naoki in gh-104922@footnote{https://github.com/python/cpython/issues/104922}.)

@item 
If Python is built in @ref{509,,debug mode}
or @ref{62d,,with assertions},
@ref{62e,,PyTuple_SET_ITEM()} and @ref{62f,,PyList_SET_ITEM()}
now check the index argument with an assertion.
(Contributed by Victor Stinner in gh-106168@footnote{https://github.com/python/cpython/issues/106168}.)
@end itemize

@node Limited C API Changes,Removed C APIs<2>,Changed C APIs,C API の変更<2>
@anchor{whatsnew/3 13 limited-c-api-changes}@anchor{630}
@subsubsection Limited C API Changes



@itemize *

@item 
The following functions are now included in the Limited C API:


@itemize *

@item 
@ref{631,,PyMem_RawMalloc()}

@item 
@ref{632,,PyMem_RawCalloc()}

@item 
@ref{633,,PyMem_RawRealloc()}

@item 
@ref{634,,PyMem_RawFree()}

@item 
@ref{613,,PySys_Audit()}

@item 
@ref{612,,PySys_AuditTuple()}

@item 
@ref{635,,PyType_GetModuleByDef()}
@end itemize

(Contributed by Victor Stinner in gh-85283@footnote{https://github.com/python/cpython/issues/85283} and gh-116936@footnote{https://github.com/python/cpython/issues/116936}.)

@item 
Python built with @ref{636,,--with-trace-refs} (tracing references)
now supports the @ref{637,,Limited API}.
(Contributed by Victor Stinner in gh-108634@footnote{https://github.com/python/cpython/issues/108634}.)
@end itemize

@node Removed C APIs<2>,Deprecated C APIs<2>,Limited C API Changes,C API の変更<2>
@anchor{whatsnew/3 13 removed-c-apis}@anchor{638}
@subsubsection Removed C APIs



@itemize *

@item 
Remove several functions, macros, variables, etc
with names prefixed by @code{_Py} or @code{_PY} (which are considered private).
If your project is affected  by one of these removals
and you believe that the removed API should remain available,
please @ref{557,,open a new issue} to request a public C API
and add @code{cc: @@vstinner} to the issue to notify Victor Stinner.
(Contributed by Victor Stinner in gh-106320@footnote{https://github.com/python/cpython/issues/106320}.)

@item 
Remove old buffer protocols deprecated in Python 3.0.
Use @ref{260,,バッファプロトコル (buffer Protocol)} instead.


@itemize *

@item 
@code{PyObject_CheckReadBuffer()}:
Use @ref{639,,PyObject_CheckBuffer()} to test
whether the object supports the buffer protocol.
Note that @ref{639,,PyObject_CheckBuffer()} doesn't guarantee
that @ref{63a,,PyObject_GetBuffer()} will succeed.
To test if the object is actually readable,
see the next example of @ref{63a,,PyObject_GetBuffer()}.

@item 
@code{PyObject_AsCharBuffer()}, @code{PyObject_AsReadBuffer()}:
Use @ref{63a,,PyObject_GetBuffer()} and @ref{63b,,PyBuffer_Release()} instead:

@example
Py_buffer view;
if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) @{
    return NULL;
@}
// Use `view.buf` and `view.len` to read from the buffer.
// You may need to cast buf as `(const char*)view.buf`.
PyBuffer_Release(&view);
@end example

@item 
@code{PyObject_AsWriteBuffer()}:
Use @ref{63a,,PyObject_GetBuffer()} and @ref{63b,,PyBuffer_Release()} instead:

@example
Py_buffer view;
if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) @{
    return NULL;
@}
// Use `view.buf` and `view.len` to write to the buffer.
PyBuffer_Release(&view);
@end example
@end itemize

(Contributed by Inada Naoki in gh-85275@footnote{https://github.com/python/cpython/issues/85275}.)

@item 
Remove various functions deprecated in Python 3.9:


@itemize *

@item 
@code{PyEval_CallObject()}, @code{PyEval_CallObjectWithKeywords()}:
Use @ref{63c,,PyObject_CallNoArgs()} or @ref{63d,,PyObject_Call()} instead.

@cartouche
@quotation 警告 
In @ref{63d,,PyObject_Call()}, positional arguments must be a @ref{614,,tuple}
and must not be @code{NULL},
and keyword arguments must be a @ref{183,,dict} or @code{NULL},
whereas the removed functions checked argument types
and accepted @code{NULL} positional and keyword arguments.
To replace @code{PyEval_CallObjectWithKeywords(func, NULL, kwargs)} with
@ref{63d,,PyObject_Call()},
pass an empty tuple as positional arguments using
@ref{63e,,PyTuple_New(0)}.
@end quotation
@end cartouche

@item 
@code{PyEval_CallFunction()}:
Use @ref{63f,,PyObject_CallFunction()} instead.

@item 
@code{PyEval_CallMethod()}:
Use @ref{640,,PyObject_CallMethod()} instead.

@item 
@code{PyCFunction_Call()}:
Use @ref{63d,,PyObject_Call()} instead.
@end itemize

(Contributed by Victor Stinner in gh-105107@footnote{https://github.com/python/cpython/issues/105107}.)

@item 
Remove the following old functions to configure the Python initialization,
deprecated in Python 3.11:


@itemize *

@item 
@code{PySys_AddWarnOptionUnicode()}:
Use @ref{641,,PyConfig.warnoptions} instead.

@item 
@code{PySys_AddWarnOption()}:
Use @ref{641,,PyConfig.warnoptions} instead.

@item 
@code{PySys_AddXOption()}:
Use @ref{642,,PyConfig.xoptions} instead.

@item 
@code{PySys_HasWarnOptions()}:
Use @ref{642,,PyConfig.xoptions} instead.

@item 
@code{PySys_SetPath()}:
Set @ref{643,,PyConfig.module_search_paths} instead.

@item 
@code{Py_SetPath()}:
Set @ref{643,,PyConfig.module_search_paths} instead.

@item 
@code{Py_SetStandardStreamEncoding()}:
Set @ref{644,,PyConfig.stdio_encoding} instead,
and set also maybe @ref{41a,,PyConfig.legacy_windows_stdio} (on Windows).

@item 
@code{_Py_SetProgramFullPath()}:
Set @ref{645,,PyConfig.executable} instead.
@end itemize

Use the new @ref{3f7,,PyConfig} API of the @ref{646,,Python Initialization Configuration} instead (
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/}), added to Python 3.8.
(Contributed by Victor Stinner in gh-105145@footnote{https://github.com/python/cpython/issues/105145}.)

@item 
Remove @code{PyEval_AcquireLock()} and @code{PyEval_ReleaseLock()} functions,
deprecated in Python 3.2.
They didn't update the current thread state.
They can be replaced with:


@itemize *

@item 
@ref{647,,PyEval_SaveThread()} and @ref{648,,PyEval_RestoreThread()};

@item 
low-level @ref{649,,PyEval_AcquireThread()} and @ref{648,,PyEval_RestoreThread()};

@item 
or @ref{64a,,PyGILState_Ensure()} and @ref{64b,,PyGILState_Release()}.
@end itemize

(Contributed by Victor Stinner in gh-105182@footnote{https://github.com/python/cpython/issues/105182}.)

@item 
Remove the @code{PyEval_ThreadsInitialized()} function,
deprecated in Python 3.9.
Since Python 3.7, @code{Py_Initialize()} always creates the GIL:
calling @code{PyEval_InitThreads()} does nothing and
@code{PyEval_ThreadsInitialized()} always returns non-zero.
(Contributed by Victor Stinner in gh-105182@footnote{https://github.com/python/cpython/issues/105182}.)

@item 
Remove the @code{_PyInterpreterState_Get()} alias to
@ref{64c,,PyInterpreterState_Get()}
which was kept for backward compatibility with Python 3.8.
The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{64c,,PyInterpreterState_Get()} on Python 3.8 and older.
(Contributed by Victor Stinner in gh-106320@footnote{https://github.com/python/cpython/issues/106320}.)

@item 
Remove the private @code{_PyObject_FastCall()} function:
use @code{PyObject_Vectorcall()} which is available since Python 3.8
(
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}).
(Contributed by Victor Stinner in gh-106023@footnote{https://github.com/python/cpython/issues/106023}.)

@item 
Remove the @code{cpython/pytime.h} header file,
which only contained private functions.
(Contributed by Victor Stinner in gh-106316@footnote{https://github.com/python/cpython/issues/106316}.)

@item 
Remove the undocumented @code{PY_TIMEOUT_MAX} constant from the limited C API.
(Contributed by Victor Stinner in gh-110014@footnote{https://github.com/python/cpython/issues/110014}.)

@item 
Remove the old trashcan macros @code{Py_TRASHCAN_SAFE_BEGIN}
and @code{Py_TRASHCAN_SAFE_END}.
Replace both with the new macros @code{Py_TRASHCAN_BEGIN}
and @code{Py_TRASHCAN_END}.
(Contributed by Irit Katriel in gh-105111@footnote{https://github.com/python/cpython/issues/105111}.)
@end itemize

@node Deprecated C APIs<2>,,Removed C APIs<2>,C API の変更<2>
@anchor{whatsnew/3 13 deprecated-c-apis}@anchor{64d}
@subsubsection Deprecated C APIs



@itemize *

@item 
Deprecate old Python initialization functions:


@itemize *

@item 
@ref{3f4,,PySys_ResetWarnOptions()}:
Clear @ref{3f5,,sys.warnoptions} and @code{warnings.filters} instead.

@item 
@ref{3e9,,Py_GetExecPrefix()}:
Get @ref{3eb,,sys.exec_prefix} instead.

@item 
@ref{3e3,,Py_GetPath()}:
Get @ref{3e4,,sys.path} instead.

@item 
@ref{3e5,,Py_GetPrefix()}:
Get @ref{3e7,,sys.prefix} instead.

@item 
@ref{3ec,,Py_GetProgramFullPath()}:
Get @ref{3ed,,sys.executable} instead.

@item 
@ref{3ee,,Py_GetProgramName()}:
Get @ref{3ed,,sys.executable} instead.

@item 
@ref{3ef,,Py_GetPythonHome()}:
Get @ref{3f3,,PyConfig.home}
or the 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable instead.
@end itemize

(Contributed by Victor Stinner in gh-105145@footnote{https://github.com/python/cpython/issues/105145}.)

@item 
@ref{23d,,Soft deprecate} the
@ref{5f4,,PyEval_GetBuiltins()}, @ref{5f6,,PyEval_GetGlobals()},
and @ref{5f8,,PyEval_GetLocals()} functions,
which return a @ref{3d7,,borrowed reference}.
(Soft deprecated as part of 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}.)

@item 
Deprecate the @ref{3db,,PyImport_ImportModuleNoBlock()} function,
which is just an alias to @ref{3dc,,PyImport_ImportModule()} since Python 3.3.
(Contributed by Victor Stinner in gh-105396@footnote{https://github.com/python/cpython/issues/105396}.)

@item 
@ref{23d,,Soft deprecate} the
@ref{60b,,PyModule_AddObject()} function.
It should be replaced with @ref{609,,PyModule_Add()}
or @ref{60a,,PyModule_AddObjectRef()}.
(Contributed by Serhiy Storchaka in gh-86493@footnote{https://github.com/python/cpython/issues/86493}.)

@item 
Deprecate the old @code{Py_UNICODE} and @code{PY_UNICODE_TYPE} types
and the @code{Py_UNICODE_WIDE} define.
Use the @code{wchar_t} type directly instead.
Since Python 3.3, @code{Py_UNICODE} and @code{PY_UNICODE_TYPE}
are just aliases to @code{wchar_t}.
(Contributed by Victor Stinner in gh-105156@footnote{https://github.com/python/cpython/issues/105156}.)

@item 
Deprecate the @ref{3dd,,PyWeakref_GetObject()} and
@ref{3de,,PyWeakref_GET_OBJECT()} functions,
which return a @ref{3d7,,borrowed reference}.
Replace them with the new @ref{3df,,PyWeakref_GetRef()} function,
which returns a @ref{5e2,,strong reference}.
The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{3df,,PyWeakref_GetRef()} on Python 3.12 and older.
(Contributed by Victor Stinner in gh-105927@footnote{https://github.com/python/cpython/issues/105927}.)
@end itemize

@c Add deprecations above alphabetically, not here at the end.

@menu
* Pending removal in Python 3.14: Pending removal in Python 3 14<2>. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<4>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<4>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<4>. 
* Pending removal in future versions: Pending removal in future versions<4>. 

@end menu

@node Pending removal in Python 3 14<2>,Pending removal in Python 3 15<4>,,Deprecated C APIs<2>
@anchor{whatsnew/3 13 id8}@anchor{64e}
@subsubsection Pending removal in Python 3.14



@itemize *

@item 
The @code{ma_version_tag} field in @ref{64f,,PyDictObject} for extension modules
(
@geindex Python Enhancement Proposals; PEP 699
PEP 699@footnote{https://peps.python.org/pep-0699/}; gh-101193@footnote{https://github.com/python/cpython/issues/101193}).

@item 
Creating @ref{3cf,,immutable types} with mutable
bases (gh-95388@footnote{https://github.com/python/cpython/issues/95388}).
@end itemize

@node Pending removal in Python 3 15<4>,Pending removal in Python 3 16<4>,Pending removal in Python 3 14<2>,Deprecated C APIs<2>
@anchor{whatsnew/3 13 id9}@anchor{650}
@subsubsection Pending removal in Python 3.15



@itemize *

@item 
The @ref{3db,,PyImport_ImportModuleNoBlock()}:
Use @ref{3dc,,PyImport_ImportModule()} instead.

@item 
@ref{3dd,,PyWeakref_GetObject()} and @ref{3de,,PyWeakref_GET_OBJECT()}:
Use @ref{3df,,PyWeakref_GetRef()} instead. The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{3df,,PyWeakref_GetRef()} on Python 3.12 and older.

@item 
@ref{3e0,,Py_UNICODE} type and the @code{Py_UNICODE_WIDE} macro:
Use @code{wchar_t} instead.

@item 
@code{PyUnicode_AsDecodedObject()}:
Use @ref{3e1,,PyCodec_Decode()} instead.

@item 
@code{PyUnicode_AsDecodedUnicode()}:
Use @ref{3e1,,PyCodec_Decode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{169,,str}, such as @ref{192,,bytes}.

@item 
@code{PyUnicode_AsEncodedObject()}:
Use @ref{3e2,,PyCodec_Encode()} instead.

@item 
@code{PyUnicode_AsEncodedUnicode()}:
Use @ref{3e2,,PyCodec_Encode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{192,,bytes}, such as @ref{169,,str}.

@item 
Python initialization functions, deprecated in Python 3.13:


@itemize *

@item 
@ref{3e3,,Py_GetPath()}:
Use @ref{37c,,PyConfig_Get("module_search_paths")}
(@ref{3e4,,sys.path}) instead.

@item 
@ref{3e5,,Py_GetPrefix()}:
Use @ref{37c,,PyConfig_Get("base_prefix")}
(@ref{3e6,,sys.base_prefix}) instead. Use @ref{37c,,PyConfig_Get("prefix")} (@ref{3e7,,sys.prefix}) if @ref{3e8,,virtual environments} need to be handled.

@item 
@ref{3e9,,Py_GetExecPrefix()}:
Use @ref{37c,,PyConfig_Get("base_exec_prefix")}
(@ref{3ea,,sys.base_exec_prefix}) instead. Use
@ref{37c,,PyConfig_Get("exec_prefix")}
(@ref{3eb,,sys.exec_prefix}) if @ref{3e8,,virtual environments} need to
be handled.

@item 
@ref{3ec,,Py_GetProgramFullPath()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ee,,Py_GetProgramName()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ef,,Py_GetPythonHome()}:
Use @ref{37c,,PyConfig_Get("home")} or the
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable instead.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{37c,,PyConfig_Get()} on Python 3.13 and older.

@item 
Functions to configure Python's initialization, deprecated in Python 3.11:


@itemize *

@item 
@code{PySys_SetArgvEx()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{PySys_SetArgv()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{Py_SetProgramName()}:
Set @ref{3f2,,PyConfig.program_name} instead.

@item 
@code{Py_SetPythonHome()}:
Set @ref{3f3,,PyConfig.home} instead.

@item 
@ref{3f4,,PySys_ResetWarnOptions()}:
Clear @ref{3f5,,sys.warnoptions} and @code{warnings.filters} instead.
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} instead.

@item 
Global configuration variables:


@itemize *

@item 
@ref{3f8,,Py_DebugFlag}:
Use @ref{3f9,,PyConfig.parser_debug} or
@ref{37c,,PyConfig_Get("parser_debug")} instead.

@item 
@ref{3fa,,Py_VerboseFlag}:
Use @ref{3fb,,PyConfig.verbose} or
@ref{37c,,PyConfig_Get("verbose")} instead.

@item 
@ref{3fc,,Py_QuietFlag}:
Use @ref{3fd,,PyConfig.quiet} or
@ref{37c,,PyConfig_Get("quiet")} instead.

@item 
@ref{3fe,,Py_InteractiveFlag}:
Use @ref{3ff,,PyConfig.interactive} or
@ref{37c,,PyConfig_Get("interactive")} instead.

@item 
@ref{400,,Py_InspectFlag}:
Use @ref{401,,PyConfig.inspect} or
@ref{37c,,PyConfig_Get("inspect")} instead.

@item 
@ref{402,,Py_OptimizeFlag}:
Use @ref{403,,PyConfig.optimization_level} or
@ref{37c,,PyConfig_Get("optimization_level")} instead.

@item 
@ref{404,,Py_NoSiteFlag}:
Use @ref{405,,PyConfig.site_import} or
@ref{37c,,PyConfig_Get("site_import")} instead.

@item 
@ref{406,,Py_BytesWarningFlag}:
Use @ref{407,,PyConfig.bytes_warning} or
@ref{37c,,PyConfig_Get("bytes_warning")} instead.

@item 
@ref{408,,Py_FrozenFlag}:
Use @ref{409,,PyConfig.pathconfig_warnings} or
@ref{37c,,PyConfig_Get("pathconfig_warnings")} instead.

@item 
@ref{40a,,Py_IgnoreEnvironmentFlag}:
Use @ref{40b,,PyConfig.use_environment} or
@ref{37c,,PyConfig_Get("use_environment")} instead.

@item 
@ref{40c,,Py_DontWriteBytecodeFlag}:
Use @ref{40d,,PyConfig.write_bytecode} or
@ref{37c,,PyConfig_Get("write_bytecode")} instead.

@item 
@ref{40e,,Py_NoUserSiteDirectory}:
Use @ref{40f,,PyConfig.user_site_directory} or
@ref{37c,,PyConfig_Get("user_site_directory")} instead.

@item 
@ref{410,,Py_UnbufferedStdioFlag}:
Use @ref{411,,PyConfig.buffered_stdio} or
@ref{37c,,PyConfig_Get("buffered_stdio")} instead.

@item 
@ref{412,,Py_HashRandomizationFlag}:
Use @ref{413,,PyConfig.use_hash_seed}
and @ref{414,,PyConfig.hash_seed} or
@ref{37c,,PyConfig_Get("hash_seed")} instead.

@item 
@ref{415,,Py_IsolatedFlag}:
Use @ref{416,,PyConfig.isolated} or
@ref{37c,,PyConfig_Get("isolated")} instead.

@item 
@ref{417,,Py_LegacyWindowsFSEncodingFlag}:
Use @ref{418,,PyPreConfig.legacy_windows_fs_encoding} or
@ref{37c,,PyConfig_Get("legacy_windows_fs_encoding")} instead.

@item 
@ref{419,,Py_LegacyWindowsStdioFlag}:
Use @ref{41a,,PyConfig.legacy_windows_stdio} or
@ref{37c,,PyConfig_Get("legacy_windows_stdio")} instead.

@item 
@code{Py_FileSystemDefaultEncoding}, @code{Py_HasFileSystemDefaultEncoding}:
Use @ref{41b,,PyConfig.filesystem_encoding} or
@ref{37c,,PyConfig_Get("filesystem_encoding")} instead.

@item 
@code{Py_FileSystemDefaultEncodeErrors}:
Use @ref{41c,,PyConfig.filesystem_errors} or
@ref{37c,,PyConfig_Get("filesystem_errors")} instead.

@item 
@code{Py_UTF8Mode}:
Use @ref{41d,,PyPreConfig.utf8_mode} or
@ref{37c,,PyConfig_Get("utf8_mode")} instead.
(see @ref{41e,,Py_PreInitialize()})
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} to set these options. Or @ref{37c,,PyConfig_Get()} can be
used to get these options at runtime.
@end itemize

@node Pending removal in Python 3 16<4>,Pending removal in Python 3 18<4>,Pending removal in Python 3 15<4>,Deprecated C APIs<2>
@anchor{whatsnew/3 13 id10}@anchor{651}
@subsubsection Pending removal in Python 3.16



@itemize *

@item 
The bundled copy of @code{libmpdec}.
@end itemize

@node Pending removal in Python 3 18<4>,Pending removal in future versions<4>,Pending removal in Python 3 16<4>,Deprecated C APIs<2>
@anchor{whatsnew/3 13 id11}@anchor{652}
@subsubsection Pending removal in Python 3.18



@itemize *

@item 
The following private functions are deprecated
and planned for removal in Python 3.18:


@itemize *

@item 
@code{_PyBytes_Join()}: use @ref{383,,PyBytes_Join()}.

@item 
@code{_PyDict_GetItemStringWithError()}: use @ref{421,,PyDict_GetItemStringRef()}.

@item 
@code{_PyDict_Pop()}: use @ref{422,,PyDict_Pop()}.

@item 
@code{_PyLong_Sign()}: use @ref{39a,,PyLong_GetSign()}.

@item 
@code{_PyLong_FromDigits()} and @code{_PyLong_New()}:
use @ref{3aa,,PyLongWriter_Create()}.

@item 
@code{_PyThreadState_UncheckedGet()}: use @ref{423,,PyThreadState_GetUnchecked()}.

@item 
@code{_PyUnicode_AsString()}: use @ref{424,,PyUnicode_AsUTF8()}.

@item 
@code{_PyUnicodeWriter_Init()}:
replace @code{_PyUnicodeWriter_Init(&writer)} with
@ref{3b4,,writer = PyUnicodeWriter_Create(0)}.

@item 
@code{_PyUnicodeWriter_Finish()}:
replace @code{_PyUnicodeWriter_Finish(&writer)} with
@ref{3b7,,PyUnicodeWriter_Finish(writer)}.

@item 
@code{_PyUnicodeWriter_Dealloc()}:
replace @code{_PyUnicodeWriter_Dealloc(&writer)} with
@ref{3b6,,PyUnicodeWriter_Discard(writer)}.

@item 
@code{_PyUnicodeWriter_WriteChar()}:
replace @code{_PyUnicodeWriter_WriteChar(&writer, ch)} with
@ref{3ba,,PyUnicodeWriter_WriteChar(writer@comma{} ch)}.

@item 
@code{_PyUnicodeWriter_WriteStr()}:
replace @code{_PyUnicodeWriter_WriteStr(&writer, str)} with
@ref{3bc,,PyUnicodeWriter_WriteStr(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteSubstring()}:
replace @code{_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)} with
@ref{3bd,,PyUnicodeWriter_WriteSubstring(writer@comma{} str@comma{} start@comma{} end)}.

@item 
@code{_PyUnicodeWriter_WriteASCIIString()}:
replace @code{_PyUnicodeWriter_WriteASCIIString(&writer, str)} with
@ref{3b9,,PyUnicodeWriter_WriteASCII(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteLatin1String()}:
replace @code{_PyUnicodeWriter_WriteLatin1String(&writer, str)} with
@ref{3bf,,PyUnicodeWriter_WriteUTF8(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_Prepare()}: (no replacement).

@item 
@code{_PyUnicodeWriter_PrepareKind()}: (no replacement).

@item 
@code{_Py_HashPointer()}: use @ref{425,,Py_HashPointer()}.

@item 
@code{_Py_fopen_obj()}: use @ref{393,,Py_fopen()}.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
these new public functions on Python 3.13 and older.
(Contributed by Victor Stinner in gh-128863@footnote{https://github.com/python/cpython/issues/128863}.)
@end itemize

@node Pending removal in future versions<4>,,Pending removal in Python 3 18<4>,Deprecated C APIs<2>
@anchor{whatsnew/3 13 id12}@anchor{653}
@subsubsection Pending removal in future versions


The following APIs are deprecated and will be removed,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{427,,Py_TPFLAGS_HAVE_FINALIZE}:
Unneeded since Python 3.8.

@item 
@ref{428,,PyErr_Fetch()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42a,,PyErr_NormalizeException()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42b,,PyErr_Restore()}:
Use @ref{42c,,PyErr_SetRaisedException()} instead.

@item 
@ref{42d,,PyModule_GetFilename()}:
Use @ref{42e,,PyModule_GetFilenameObject()} instead.

@item 
@ref{42f,,PyOS_AfterFork()}:
Use @ref{430,,PyOS_AfterFork_Child()} instead.

@item 
@ref{431,,PySlice_GetIndicesEx()}:
Use @ref{432,,PySlice_Unpack()} and @ref{433,,PySlice_AdjustIndices()} instead.

@item 
@ref{434,,PyUnicode_READY()}:
Unneeded since Python 3.12

@item 
@code{PyErr_Display()}:
Use @ref{435,,PyErr_DisplayException()} instead.

@item 
@code{_PyErr_ChainExceptions()}:
Use @code{_PyErr_ChainExceptions1()} instead.

@item 
@code{PyBytesObject.ob_shash} member:
call @ref{436,,PyObject_Hash()} instead.

@item 
Thread Local Storage (TLS) API:


@itemize *

@item 
@ref{437,,PyThread_create_key()}:
Use @ref{438,,PyThread_tss_alloc()} instead.

@item 
@ref{439,,PyThread_delete_key()}:
Use @ref{43a,,PyThread_tss_free()} instead.

@item 
@ref{43b,,PyThread_set_key_value()}:
Use @ref{43c,,PyThread_tss_set()} instead.

@item 
@ref{43d,,PyThread_get_key_value()}:
Use @ref{43e,,PyThread_tss_get()} instead.

@item 
@ref{43f,,PyThread_delete_key_value()}:
Use @ref{440,,PyThread_tss_delete()} instead.

@item 
@ref{441,,PyThread_ReInitTLS()}:
Unneeded since Python 3.7.
@end itemize
@end itemize

@node Build Changes,Porting to Python 3 13,C API の変更<2>,What's New In Python 3 13
@anchor{whatsnew/3 13 build-changes}@anchor{654}@anchor{whatsnew/3 13 pythoncapi-compat-project}@anchor{655}
@subsection Build Changes



@itemize *

@item 
@code{arm64-apple-ios} and @code{arm64-apple-ios-simulator} are both
now 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} tier 3 platforms.
(@ref{48d,,PEP 730} written
and implementation contributed by Russell Keith-Magee in gh-114099@footnote{https://github.com/python/cpython/issues/114099}.)

@item 
@code{aarch64-linux-android} and @code{x86_64-linux-android} are both
now 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} tier 3 platforms.
(@ref{48d,,PEP 738} written
and implementation contributed by Malcolm Smith in gh-116622@footnote{https://github.com/python/cpython/issues/116622}.)

@item 
@code{wasm32-wasi} is now a 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} tier 2 platform.
(Contributed by Brett Cannon in gh-115192@footnote{https://github.com/python/cpython/issues/115192}.)

@item 
@code{wasm32-emscripten} is no longer a 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} supported platform.
(Contributed by Brett Cannon in gh-115192@footnote{https://github.com/python/cpython/issues/115192}.)

@item 
Building CPython now requires a compiler with support for the C11 atomic
library, GCC built-in atomic functions, or MSVC interlocked intrinsics.

@item 
Autoconf 2.71 and aclocal 1.16.5 are now required to regenerate
the @code{configure} script.
(Contributed by Christian Heimes in gh-89886@footnote{https://github.com/python/cpython/issues/89886} and by Victor Stinner in gh-112090@footnote{https://github.com/python/cpython/issues/112090}.)

@item 
SQLite 3.15.2 or newer is required to build
the @ref{d4,,sqlite3} extension module.
(Contributed by Erlend Aasland in gh-105875@footnote{https://github.com/python/cpython/issues/105875}.)

@item 
CPython now bundles the mimalloc library@footnote{https://github.com/microsoft/mimalloc/} by default.
It is licensed under the MIT license;
see @ref{656,,mimalloc license}.
The bundled mimalloc has custom changes, see gh-113141@footnote{https://github.com/python/cpython/issues/113141} for details.
(Contributed by Dino Viehland in gh-109914@footnote{https://github.com/python/cpython/issues/109914}.)

@item 
The @code{configure} option @ref{657,,--with-system-libmpdec}
now defaults to @code{yes}.
The bundled copy of @code{libmpdec} will be removed in Python 3.16.

@item 
Python built with @code{configure} @ref{636,,--with-trace-refs}
(tracing references) is now ABI compatible with the Python release build
and @ref{509,,debug build}.
(Contributed by Victor Stinner in gh-108634@footnote{https://github.com/python/cpython/issues/108634}.)

@item 
On POSIX systems, the pkg-config (@code{.pc}) filenames now include the ABI
flags.  For example, the free-threaded build generates @code{python-3.13t.pc}
and the debug build generates @code{python-3.13d.pc}.

@item 
The @code{errno}, @code{fcntl}, @code{grp}, @code{md5}, @code{pwd}, @code{resource},
@code{termios}, @code{winsound},
@code{_ctypes_test}, @code{_multiprocessing.posixshmem}, @code{_scproxy}, @code{_stat},
@code{_statistics}, @code{_testconsole}, @code{_testimportmultiple} and @code{_uuid}
C extensions are now built with the @ref{637,,limited C API}.
(Contributed by Victor Stinner in gh-85283@footnote{https://github.com/python/cpython/issues/85283}.)
@end itemize

@node Porting to Python 3 13,Regression Test Changes,Build Changes,What's New In Python 3 13
@anchor{whatsnew/3 13 porting-to-python-3-13}@anchor{472}
@subsection Porting to Python 3.13


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python API の変更: Python API の変更<2>. 
* C API の変更: C API の変更<3>. 

@end menu

@node Python API の変更<2>,C API の変更<3>,,Porting to Python 3 13
@anchor{whatsnew/3 13 changes-in-the-python-api}@anchor{658}
@subsubsection Python API の変更

@anchor{whatsnew/3 13 pep667-porting-notes-py}@anchor{4a6}

@itemize *

@item 
@ref{470,,PEP 667} introduces several changes
to the semantics of @ref{46f,,locals()} and @ref{4a5,,f_locals}:


@itemize *

@item 
Calling @ref{46f,,locals()} in an @ref{4a1,,optimized scope} now produces an
independent snapshot on each call, and hence no longer implicitly updates
previously returned references. Obtaining the legacy CPython behavior now
requires explicit calls to update the initially returned dictionary with the
results of subsequent calls to @code{locals()}. Code execution functions that
implicitly target @code{locals()} (such as @code{exec} and @code{eval}) must be
passed an explicit namespace to access their results in an optimized scope.
(Changed as part of 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}.)

@item 
Calling @ref{46f,,locals()} from a comprehension at module or class scope
(including via @code{exec} or @code{eval}) once more behaves as if the comprehension
were running as an independent nested function (i.e. the local variables from
the containing scope are not included). In Python 3.12, this had changed
to include the local variables from the containing scope when implementing
@geindex Python Enhancement Proposals; PEP 709
PEP 709@footnote{https://peps.python.org/pep-0709/}. (Changed as part of 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}.)

@item 
Accessing @ref{4a5,,FrameType.f_locals} in an
@ref{4a1,,optimized scope} now returns a write-through proxy rather than a
snapshot that gets updated at ill-specified times. If a snapshot is desired,
it must be created explicitly with @code{dict} or the proxy's @code{.copy()} method.
(Changed as part of 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}.)
@end itemize

@item 
@ref{217,,functools.partial} now emits a @ref{659,,FutureWarning}
when used as a method.
The behavior will change in future Python versions.
Wrap it in @ref{453,,staticmethod()} if you want to preserve the old behavior.
(Contributed by Serhiy Storchaka in gh-121027@footnote{https://github.com/python/cpython/issues/121027}.)

@item 
An @ref{2c0,,OSError} is now raised by @ref{65a,,getpass.getuser()}
for any failure to retrieve a username,
instead of @ref{65b,,ImportError} on non-Unix platforms
or @ref{5e7,,KeyError} on Unix platforms where the password database is empty.

@item 
The value of the @code{mode} attribute of @ref{65c,,gzip.GzipFile}
is now a string (@code{'rb'} or @code{'wb'}) instead of an integer (@code{1} or @code{2}).
The value of the @code{mode} attribute of the readable file-like object
returned by @ref{65d,,zipfile.ZipFile.open()} is now @code{'rb'} instead of @code{'r'}.
(Contributed by Serhiy Storchaka in gh-115961@footnote{https://github.com/python/cpython/issues/115961}.)

@item 
@ref{65e,,mailbox.Maildir} now ignores files with a leading dot (@code{.}).
(Contributed by Zackery Spytz in gh-65559@footnote{https://github.com/python/cpython/issues/65559}.)

@item 
@ref{537,,pathlib.Path.glob()} and @ref{538,,rglob()} now return both
files and directories if a pattern that ends with "@code{**}" is given,
rather than directories only.
Add a trailing slash to keep the previous behavior and only match directories.

@item 
The @ref{f3,,threading} module now expects the @code{_thread} module
to have an @code{_is_main_interpreter()} function.
This function takes no arguments and returns @code{True}
if the current interpreter is the main interpreter.

Any library or application that provides a custom @code{_thread} module
must provide @code{_is_main_interpreter()},
just like the module's other "private" attributes.
(gh-112826@footnote{https://github.com/python/cpython/issues/112826}.)
@end itemize

@node C API の変更<3>,,Python API の変更<2>,Porting to Python 3 13
@anchor{whatsnew/3 13 changes-in-the-c-api}@anchor{65f}
@subsubsection C API の変更



@itemize *

@item 
@code{Python.h} no longer includes the @code{<ieeefp.h>} standard header. It was
included for the @code{finite()} function which is now provided by the
@code{<math.h>} header. It should now be included explicitly if needed. Remove
also the @code{HAVE_IEEEFP_H} macro.
(Contributed by Victor Stinner in gh-108765@footnote{https://github.com/python/cpython/issues/108765}.)

@item 
@code{Python.h} no longer includes these standard header files: @code{<time.h>},
@code{<sys/select.h>} and @code{<sys/time.h>}. If needed, they should now be
included explicitly. For example, @code{<time.h>} provides the @code{clock()} and
@code{gmtime()} functions, @code{<sys/select.h>} provides the @code{select()}
function, and @code{<sys/time.h>} provides the @code{futimes()}, @code{gettimeofday()}
and @code{setitimer()} functions.
(Contributed by Victor Stinner in gh-108765@footnote{https://github.com/python/cpython/issues/108765}.)

@item 
On Windows, @code{Python.h} no longer includes the @code{<stddef.h>} standard
header file. If needed, it should now be included explicitly. For example, it
provides @code{offsetof()} function, and @code{size_t} and @code{ptrdiff_t} types.
Including @code{<stddef.h>} explicitly was already needed by all other
platforms, the @code{HAVE_STDDEF_H} macro is only defined on Windows.
(Contributed by Victor Stinner in gh-108765@footnote{https://github.com/python/cpython/issues/108765}.)

@item 
If the @ref{660,,Py_LIMITED_API} macro is defined, @code{Py_BUILD_CORE},
@code{Py_BUILD_CORE_BUILTIN} and @code{Py_BUILD_CORE_MODULE} macros
are now undefined by @code{<Python.h>}.
(Contributed by Victor Stinner in gh-85283@footnote{https://github.com/python/cpython/issues/85283}.)

@item 
The old trashcan macros @code{Py_TRASHCAN_SAFE_BEGIN} and @code{Py_TRASHCAN_SAFE_END}
were removed. They should be replaced by the new macros @code{Py_TRASHCAN_BEGIN}
and @code{Py_TRASHCAN_END}.

A @code{tp_dealloc} function that has the old macros, such as:

@example
static void
mytype_dealloc(mytype *p)
@{
    PyObject_GC_UnTrack(p);
    Py_TRASHCAN_SAFE_BEGIN(p);
    ...
    Py_TRASHCAN_SAFE_END
@}
@end example

should migrate to the new macros as follows:

@example
static void
mytype_dealloc(mytype *p)
@{
    PyObject_GC_UnTrack(p);
    Py_TRASHCAN_BEGIN(p, mytype_dealloc)
    ...
    Py_TRASHCAN_END
@}
@end example

Note that @code{Py_TRASHCAN_BEGIN} has a second argument which
should be the deallocation function it is in. The new macros were
added in Python 3.8 and the old macros were deprecated in Python 3.11.
(Contributed by Irit Katriel in gh-105111@footnote{https://github.com/python/cpython/issues/105111}.)
@end itemize
@anchor{whatsnew/3 13 pep667-porting-notes-c}@anchor{4a7}

@itemize *

@item 
@ref{470,,PEP 667} introduces several changes
to frame-related functions:


@itemize *

@item 
The effects of mutating the dictionary returned from
@ref{5f8,,PyEval_GetLocals()} in an @ref{4a1,,optimized scope} have changed.
New dict entries added this way will now `only' be visible to
subsequent @ref{5f8,,PyEval_GetLocals()} calls in that frame,
as @ref{661,,PyFrame_GetLocals()}, @ref{46f,,locals()},
and @ref{4a5,,FrameType.f_locals} no longer access
the same underlying cached dictionary.
Changes made to entries for actual variable names and names added via
the write-through proxy interfaces will be overwritten on subsequent calls
to @ref{5f8,,PyEval_GetLocals()} in that frame.
The recommended code update depends on how the function was being used,
so refer to the deprecation notice on the function for details.

@item 
Calling @ref{661,,PyFrame_GetLocals()} in an @ref{4a1,,optimized scope}
now returns a write-through proxy rather than a snapshot
that gets updated at ill-specified times.
If a snapshot is desired, it must be created explicitly
(e.g. with @ref{662,,PyDict_Copy()}),
or by calling the new @ref{5f7,,PyEval_GetFrameLocals()} API.

@item 
@code{PyFrame_FastToLocals()} and @code{PyFrame_FastToLocalsWithError()}
no longer have any effect.
Calling these functions has been redundant since Python 3.11,
when @ref{661,,PyFrame_GetLocals()} was first introduced.

@item 
@code{PyFrame_LocalsToFast()} no longer has any effect.
Calling this function is redundant now that @ref{661,,PyFrame_GetLocals()}
returns a write-through proxy for @ref{4a1,,optimized scopes}.
@end itemize

@item 
Python 3.13 removed many private functions. Some of them can be replaced using these
alternatives:


@itemize *

@item 
@code{_PyDict_Pop()}: @ref{422,,PyDict_Pop()} or @ref{5e5,,PyDict_PopString()};

@item 
@code{_PyDict_GetItemWithError()}: @ref{5e0,,PyDict_GetItemRef()};

@item 
@code{_PyErr_WriteUnraisableMsg()}:  @ref{5f1,,PyErr_FormatUnraisable()};

@item 
@code{_PyEval_SetTrace()}: @ref{663,,PyEval_SetTrace()} or @ref{664,,PyEval_SetTraceAllThreads()};

@item 
@code{_PyList_Extend()}: @ref{600,,PyList_Extend()};

@item 
@code{_PyLong_AsInt()}: @ref{604,,PyLong_AsInt()};

@item 
@code{_PyMem_RawStrdup()}: @code{strdup()};

@item 
@code{_PyMem_Strdup()}: @code{strdup()};

@item 
@code{_PyObject_ClearManagedDict()}: @ref{60e,,PyObject_ClearManagedDict()};

@item 
@code{_PyObject_VisitManagedDict()}: @ref{60d,,PyObject_VisitManagedDict()};

@item 
@code{_PyThreadState_UncheckedGet()}: @ref{423,,PyThreadState_GetUnchecked()};

@item 
@code{_PyTime_AsSecondsDouble()}: @ref{5d6,,PyTime_AsSecondsDouble()};

@item 
@code{_PyTime_GetMonotonicClock()}: @ref{5d7,,PyTime_Monotonic()} or @ref{5d8,,PyTime_MonotonicRaw()};

@item 
@code{_PyTime_GetPerfCounter()}: @ref{5d9,,PyTime_PerfCounter()} or @ref{5da,,PyTime_PerfCounterRaw()};

@item 
@code{_PyTime_GetSystemClock()}: @ref{5db,,PyTime_Time()} or @ref{5dc,,PyTime_TimeRaw()};

@item 
@code{_PyTime_MAX}: @ref{5d5,,PyTime_MAX};

@item 
@code{_PyTime_MIN}: @ref{5d4,,PyTime_MIN};

@item 
@code{_PyTime_t}: @ref{5d3,,PyTime_t};

@item 
@code{_Py_HashPointer()}: @ref{425,,Py_HashPointer()};

@item 
@code{_Py_IsFinalizing()}: @ref{5fd,,Py_IsFinalizing()}.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get most of these new
functions on Python 3.12 and older.
@end itemize

@node Regression Test Changes,,Porting to Python 3 13,What's New In Python 3 13
@anchor{whatsnew/3 13 regression-test-changes}@anchor{665}
@subsection Regression Test Changes



@itemize *

@item 
Python built with @code{configure} @ref{666,,--with-pydebug} now
supports a @ref{16f,,-X presite=package.module} command-line
option. If used, it specifies a module that should be imported early
in the lifecycle of the interpreter, before @code{site.py} is executed.
(Contributed by Łukasz Langa in gh-110769@footnote{https://github.com/python/cpython/issues/110769}.)
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 12,What's New In Python 3 11,What's New In Python 3 13,What's New in Python
@anchor{whatsnew/3 12 doc}@anchor{667}@anchor{whatsnew/3 12 translation-repo}@anchor{668}@anchor{whatsnew/3 12 what-s-new-in-python-3-12}@anchor{669}
@section What's New In Python 3.12


@*編集者: 
Adam Turner


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the issue number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :gh:`12345`.)
@c 
@c This saves the maintainer the effort of going through the VCS log when
@c researching a change.

この記事では Python 3.11 と比較した Python 3.12 の新機能を解説します。Python 3.12 は2023年10月2日にリリースされました。全詳細については @ref{142,,変更履歴} をご覧ください。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 693
PEP 693@footnote{https://peps.python.org/pep-0693/} -- Python 3.12 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト<3>. リリースハイライト
* 新しい機能: 新しい機能<4>. 
* 型ヒントに関連する新しい機能:: 
* その他の言語変更: その他の言語変更<2>. 
* 新たなモジュール: 新たなモジュール<2>. 
* 改良されたモジュール: 改良されたモジュール<2>. 
* 最適化: 最適化<3>. 
* CPython バイトコードの変更: CPython バイトコードの変更<2>. 
* Demos and Tools:: 
* 非推奨: 非推奨<2>. 
* 削除: 削除<2>. 
* Python 3.12 への移植: Python 3 12 への移植. 
* Build Changes: Build Changes<2>. 
* C API の変更: C API の変更<4>. 

@end menu

@node 概要 -- リリースハイライト<3>,新しい機能<4>,,What's New In Python 3 12
@anchor{whatsnew/3 12 summary-release-highlights}@anchor{66a}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.12.
@c Brevity is key.

Python 3.12 is a stable release of the Python programming language,
with a mix of changes to the language and the standard library.
The library changes focus on cleaning up deprecated APIs, usability, and correctness.
Of note, the @code{distutils} package has been removed from the standard library.
Filesystem support in @ref{a5,,os} and @ref{a8,,pathlib} has seen a number of improvements,
and several modules have better performance.

@ref{66b,,f-strings} は多くの制限が取り除かれ、 'Did you mean ...' サジェストも改善され続けています。新しい @ref{66c,,型パラメータの構文} と @ref{66d,,type} 文は、 @ref{1a1,,ジェネリック} と @ref{66e,,型エイリアス} を静的型チェッカーで使用する際の人間工学を改善します。

この記事は全ての新機能の完全な仕様を提供しようとするものではなく、便利な概要について説明をするものです。
全詳細については、 @ref{149,,ライブラリリファレンス} や @ref{14a,,言語リファレンス} などのドキュメントを参照してください。
変更の実装や設計原理について完全に理解したい場合は、特定の新機能の PEP を参照してください。
しかし、一旦機能が完全に実装されると、普通 PEP は最新の状態に保たれないことに注意してください。


__________________________________________________________________


@c PEP-sized items next.

新たな構文機能:


@itemize *

@item 
@ref{66c,,PEP 695}, 型パラメータの構文と @ref{66d,,type} 文
@end itemize

新たな文法機能:


@itemize *

@item 
@ref{66f,,PEP 701}, 文法の中の @ref{66b,,f-strings}
@end itemize

インタープリタの改善:


@itemize *

@item 
@ref{670,,PEP 684}, インタープリタごとのユニークな @ref{474,,GIL}

@item 
@ref{671,,PEP 669}, 低影響なモニタリング

@item 
@ref{452,,NameError}, @ref{65b,,ImportError}, @ref{18e,,SyntaxError} 例外に対する @ref{672,,'Did you mean ...' サジェストを改善} しました
@end itemize

Python のデータモデルの改善:


@itemize *

@item 
@ref{673,,PEP 688}, Python の @ref{260,,バッファプロトコル} を使用します
@end itemize

標準ライブラリーの顕著な改善


@itemize *

@item 
@ref{266,,pathlib.Path} クラスがサブクラス化をサポートするようになりました

@item 
@ref{a5,,os} モジュールは Windows サポートのためにいくつかの改良が加えられました

@item 
@ref{d4,,sqlite3} モジュールに @ref{674,,コマンドライン・インターフェース} が追加されました

@item 
@ref{675,,runtime-checkable プロトコル} に対する @ref{2ad,,isinstance()} のチェックは、2倍～20倍のスピードアップを実現します

@item 
@ref{b,,asyncio} パッケージは多くのパフォーマンスを向上させ、いくつかのベンチマークでは75%のスピードアップを示しました。

@item 
@ref{116,,uuid} モジュールに @ref{676,,コマンドライン・インターフェース} が追加されました

@item 
@ref{66f,,PEP 701} の変更により、 @ref{101,,tokenize} モジュールによるトークンの生成は最大で64%速くなりました。
@end itemize

セキュリティの改善:


@itemize *

@item 
組み込みの @ref{6c,,hashlib} による SHA1, SHA3, SHA2-384, SHA2-512, MD5 の実装を、 HACL*@footnote{https://github.com/hacl-star/hacl-star/} プロジェクトから正式に検証されたコードに置き換えます。これらの組み込み実装は、 OpenSSL がそれらを提供しない場合にのみ使用されるフォールバックとして残ります。
@end itemize

C API の改善:


@itemize *

@item 
@ref{677,,PEP 697}, 不安定な C API 層

@item 
@ref{678,,PEP 683}, 不変オブジェクト
@end itemize

CPython の実装の改善:


@itemize *

@item 
@ref{679,,PEP 709}, 内包表記のインライン化

@item 
Linux @code{perf} プロファイラの @ref{4ae,,CPython サポート}

@item 
サポートされているプラットフォームでスタック・オーバーフロー保護を実装します
@end itemize

新しい型ヒントの機能:


@itemize *

@item 
@ref{67a,,PEP 692}, @ref{332,,TypedDict} を使用して @ref{67b,,**kwargs} をアノテートします

@item 
@ref{67c,,PEP 698}, @ref{67d,,typing.override()} デコレータ
@end itemize

重要な非推奨化、削除または制限:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/}: Python の C API の Unicode オブジェクトから @code{wstr} を削除し、全ての @ref{169,,str} オブジェクトのサイズを少なくとも 8 バイト減らします

@item 
@geindex Python Enhancement Proposals; PEP 632
PEP 632@footnote{https://peps.python.org/pep-0632/}: Remove the @code{distutils} package.
See 
@geindex Python Enhancement Proposals; PEP 0632#migration-advice
the migration guide@footnote{https://peps.python.org/pep-0632/#migration-advice}
for advice replacing the APIs it provided.
The third-party Setuptools@footnote{https://setuptools.pypa.io/en/latest/deprecated/distutils-legacy.html}
package continues to provide @code{distutils},
if you still require it in Python 3.12 and beyond.

@item 
gh-95299@footnote{https://github.com/python/cpython/issues/95299}: @ref{117,,venv} で作成された仮想環境には @code{setuptools} をプリインストールしません。これは @code{distutils}, @code{setuptools}, @code{pkg_resources}, @code{easy_install} がデフォルトでは利用できなることを意味します。これらを利用するには、 @ref{67e,,有効化された} 仮想環境で @code{pip install setuptools} を実行してください。

@item 
@code{asynchat}, @code{asyncore}, @code{imp} モジュールが、いくつかの @ref{2b3,,unittest.TestCase} @ref{67f,,メソッドのエイリアス} と共に削除されました。
@end itemize

@node 新しい機能<4>,型ヒントに関連する新しい機能,概要 -- リリースハイライト<3>,What's New In Python 3 12
@anchor{whatsnew/3 12 new-features}@anchor{680}
@subsection 新しい機能


@menu
* PEP 695; 型パラメータの構文: PEP 695 型パラメータの構文. 
* PEP 701; f-strings の構文的な形式化: PEP 701 f-strings の構文的な形式化. 
* PEP 684; インタープリタごとの GIL: PEP 684 インタープリタごとの GIL. 
* PEP 669; CPython の低影響モニタリング: PEP 669 CPython の低影響モニタリング. 
* PEP 688; バッファプロトコルを Python で利用可能にする: PEP 688 バッファプロトコルを Python で利用可能にする. 
* PEP 709; 内包表記のインライン化: PEP 709 内包表記のインライン化. 
* エラーメッセージの改善: エラーメッセージの改善<3>. 

@end menu

@node PEP 695 型パラメータの構文,PEP 701 f-strings の構文的な形式化,,新しい機能<4>
@anchor{whatsnew/3 12 pep-695-type-parameter-syntax}@anchor{681}@anchor{whatsnew/3 12 whatsnew312-pep695}@anchor{66c}
@subsubsection PEP 695: 型パラメータの構文


@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} のジェネリッククラスと関数は、型パラメータのスコープが不明確なまま冗長な構文を使用して宣言されており、差異の明示的な宣言が必要でした。

@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} は ジェネリッククラス と @ref{682,,関数} を作成するための、よりコンパクトで明示的な新しい方法を紹介します:

@example
def max[T](args: Iterable[T]) -> T:
    ...

class list[T]:
    def __getitem__(self, index: int, /) -> T:
        ...

    def append(self, element: T) -> None:
        ...
@end example

さらに、 PEP では @ref{683,,型エイリアス} を宣言する新しい方法が導入されました。 @ref{66d,,type} 文を使用し、 @ref{2ae,,TypeAliasType} のインスタンスを作成します:

@example
type Point = tuple[float, float]
@end example

型エイリアスは @ref{684,,ジェネリック} とすることもできます:

@example
type Point[T] = tuple[T, T]
@end example

新しい構文では、 @ref{488,,TypeVarTuple} と @ref{487,,ParamSpec} パラメータ、および @ref{486,,TypeVar} パラメータに境界や制約を宣言することができます:

@example
type IntFunc[**P] = Callable[P, int]  # ParamSpec
type LabeledTuple[*Ts] = tuple[str, *Ts]  # TypeVarTuple
type HashableSequence[T: Hashable] = Sequence[T]  # TypeVar with bound
type IntOrStrSequence[T: (int, str)] = Sequence[T]  # TypeVar with constraints
@end example

この構文で作成された型エイリアスの値や型変数の境界や制約はオンデマンドで評価されます (@ref{685,,遅延評価} を参照してください)。つまり、型エイリアスはファイルの後半で定義された他の型を参照することができます。

型パラメータリストを通して宣言された型パラメータは、宣言のスコープと入れ子になったスコープ内では表示されますが、外側のスコープでは表示されません。例えば、ジェネリッククラスのメソッドの型アノテーションやクラス本体で使用することができます。しかし、クラス定義後にモジュールスコープ内で使用することはできません。型パラメータの実行時の解釈の問題に関する詳細な説明は @ref{5ad,,Type parameter lists} を参照してください。

このようなスコープの解釈の問題をサポートするために、 @ref{4ab,,アノテーションスコープ} という新しいスコープが導入されました。アノテーションスコープはほとんどの場合関数スコープと同じように動作しますが、外側のクラススコープとは異なる方法で対話します。 Python 3.13 では、 @ref{15c,,アノテーション} もアノテーションスコープで評価されます。

より詳しくは 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} を参照してください。

(PEP は Eric Traut によって作成されました。実装は Jelle Zijlstra, Eric Traut らによって gh-103764@footnote{https://github.com/python/cpython/issues/103764} で行われました。)

@node PEP 701 f-strings の構文的な形式化,PEP 684 インタープリタごとの GIL,PEP 695 型パラメータの構文,新しい機能<4>
@anchor{whatsnew/3 12 pep-701-syntactic-formalization-of-f-strings}@anchor{686}@anchor{whatsnew/3 12 whatsnew312-pep701}@anchor{66f}
@subsubsection PEP 701: f-strings の構文的な形式化


@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/} は @ref{66b,,f-strings} の使い方の制限をいくつか解除しました。 f-string 内の式コンポーネントは有効な Python 式であれば何でも使用できるようになりました。これには、 f-string を含む文字列と同じ引用符を再利用する文字列、複数行の式、コメント、バックスラッシュ、 Unicode エスケープシーケンスなどが含まれます。これらについて詳しく説明します:


@itemize *

@item 
クォートの再利用: Python 3.11 では、 f-string を囲むクォートと同じクォートを再利用すると @ref{18e,,SyntaxError} が発生し、ユーザーは他の利用可能なクォート( f-string がシングルクォートを使用している場合に、ダブルクオートまたはトリプルクォートを使用するなど)を使用する必要があります。 Python 3.12 では次のようなことができるようになりました:

@example
>>> songs = ['Take me back to Eden', 'Alkaline', 'Ascensionism']
>>> f"This is the playlist: @{", ".join(songs)@}"
'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'
@end example

この変更以前は、 f-string のネスト方法に明示的な制限はありませんでしたが、 f-string の式コンポーネント内で文字列引用符を再利用できないという事実により、 f-string を任意にネストすることが不可能になったことに注意してください。実際、これは記述できる中で最もネストされた f-string です。

@example
>>> f"""@{f'@w{'}'@{f'@{f"@{1+1@}"@}'@}'@w{'}'@}"""
'2'
@end example

f-string には式コンポーネント内に任意の有効な Python 式を含めることができるため、 f-string を任意にネストできるようになりました。

@example
>>> f"@{f"@{f"@{f"@{f"@{f"@{1+1@}"@}"@}"@}"@}"@}"
'2'
@end example

@item 
複数行の式とコメント: Python 3.11 では、 f-string 式は1行で定義されなければいけませんでした。たとえ f-string 式が複数行にまたがっていても(リテラルリストが複数行にわたって定義されている場合など)、読みにくくなります。 Python 3.12 では、複数行にまたがる f-string を定義し、インラインコメントを追加できるようになりました:

@example
>>> f"This is the playlist: @{", ".join([
...     'Take me back to Eden',  # My, my, those eyes like fire
...     'Alkaline',              # Not acid nor alkaline
...     'Ascensionism'           # Take to the broken skies at last
... ])@}"
'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'
@end example

@item 
バックスラッシュと unicode 文字: Python 3.12 以前では f-string 式に @code{\} 文字を含めることはできませんでした。これは、 unicode @ref{687,,エスケープシーケンス} ( @code{\N@{snowman@}} など)にも影響しました。これは、 unicode のエスケープシーケンスにも影響し、これらは @code{\N} の部分を含んでいたため、以前は f-string の式コンポーネントの一部とすることができませんでした。このように式を定義することができます:

@example
>>> print(f"This is the playlist: @{"\n".join(songs)@}")
This is the playlist: Take me back to Eden
Alkaline
Ascensionism
>>> print(f"This is the playlist: @{"\N@{BLACK HEART SUIT@}".join(songs)@}")
This is the playlist: Take me back to Eden♥Alkaline♥Ascensionism
@end example
@end itemize

より詳しくは 
@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/} を参照してください。

この機能が実装されたことによる良い副作用として( 
@geindex Python Enhancement Proposals; PEP 617
PEG パーサ@footnote{https://peps.python.org/pep-0617/} で f-string を解析することにより)、 f-string のエラーメッセージがより正確になり、エラーの正確な位置が含まれるようになりました。例えば、 Python 3.11 では、以下の f-string は @ref{18e,,SyntaxError} をs送出させます:

@example
>>> my_string = f"@{x z y@}" + f"@{1 + 1@}"
  File "<stdin>", line 1
    (x z y)
     ^^^
SyntaxError: f-string: invalid syntax. Perhaps you forgot a comma?
@end example

しかし、エラーメッセージは行内の正確なエラーの位置を含まず、また式が人為的に括弧で囲まれています。 Python 3.12 では、 f-string は PEG パーサで解析されるため、エラーメッセージはより正確になり、行全体が表示されます:

@example
>>> my_string = f"@{x z y@}" + f"@{1 + 1@}"
  File "<stdin>", line 1
    my_string = f"@{x z y@}" + f"@{1 + 1@}"
                   ^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
@end example

(Pablo Galindo, Batuhan Taskaya, Lysandros Nikolaou, Christian Maureira-Fredes, および Marta Gomez によって、 gh-102856@footnote{https://github.com/python/cpython/issues/102856} で寄稿されました。PEP は Pablo Galindo, Batuhan Taskaya, Lysandros Nikolaou, および Marta Gomez によって作成されました)。

@node PEP 684 インタープリタごとの GIL,PEP 669 CPython の低影響モニタリング,PEP 701 f-strings の構文的な形式化,新しい機能<4>
@anchor{whatsnew/3 12 pep-684-a-per-interpreter-gil}@anchor{688}@anchor{whatsnew/3 12 whatsnew312-pep684}@anchor{670}
@subsubsection PEP 684: インタープリタごとの GIL


@geindex Python Enhancement Proposals; PEP 684
PEP 684@footnote{https://peps.python.org/pep-0684/} ではインタープリタごとの @ref{474,,GIL} が導入され、インタープリタごとの固有の GIL を使用してサブインタープリタを作成できるようになりました。これにより、 Python プログラムは複数の CPU コアを最大限に活用できるようになります。これは現在 C-API を通じてのみ利用できますが、 Python API は 
@geindex Python Enhancement Proposals; PEP 554
3.13@footnote{https://peps.python.org/pep-0554/} で利用可能になる予定です。

独自の GIL を持つインタープリタを作成するには、新しい @ref{689,,Py_NewInterpreterFromConfig()} 関数を使います:

@example
PyInterpreterConfig config = @{
    .check_multi_interp_extensions = 1,
    .gil = PyInterpreterConfig_OWN_GIL,
@};
PyThreadState *tstate = NULL;
PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
if (PyStatus_Exception(status)) @{
    return -1;
@}
/* The new interpreter is now active in the current thread. */
@end example

For further examples how to use the C-API for sub-interpreters with a
per-interpreter GIL, see @code{Modules/_xxsubinterpretersmodule.c}.

(寄稿: Eric Snow, gh-104210@footnote{https://github.com/python/cpython/issues/104210} ほか)

@node PEP 669 CPython の低影響モニタリング,PEP 688 バッファプロトコルを Python で利用可能にする,PEP 684 インタープリタごとの GIL,新しい機能<4>
@anchor{whatsnew/3 12 pep-669-low-impact-monitoring-for-cpython}@anchor{68a}@anchor{whatsnew/3 12 whatsnew312-pep669}@anchor{671}
@subsubsection PEP 669: CPython の低影響モニタリング


@geindex Python Enhancement Proposals; PEP 669
PEP 669@footnote{https://peps.python.org/pep-0669/} は、 CPython でイベントを監視するためのプロファイラ、デバッガー、およびその他のツール用の新しい @ref{e0,,API} を定義します。呼び出し、戻り値、行、例外、ジャンプなどを含む幅広いイベントをカバーします。つまり、使用した分だけ料金を支払い、オーバーヘッドがほぼゼロのデバッガーとカバレッジツールのサポートを提供します。詳細については @ref{e0,,sys.monitoring} を参照してください。

(Mark Shannon による gh-103082@footnote{https://github.com/python/cpython/issues/103082} での貢献)

@node PEP 688 バッファプロトコルを Python で利用可能にする,PEP 709 内包表記のインライン化,PEP 669 CPython の低影響モニタリング,新しい機能<4>
@anchor{whatsnew/3 12 pep-688-making-the-buffer-protocol-accessible-in-python}@anchor{68b}@anchor{whatsnew/3 12 whatsnew312-pep688}@anchor{673}
@subsubsection PEP 688: バッファプロトコルを Python で利用可能にする


@geindex Python Enhancement Proposals; PEP 688
PEP 688@footnote{https://peps.python.org/pep-0688/} は Python のコードから @ref{260,,バッファプロトコル} を利用する方法を導入します。 @ref{68c,,__buffer__()} メソッドを実装するクラスは今やバッファ型として利用可能です。

新規追加された @ref{343,,collections.abc.Buffer} ABC は、例えば型注釈で、バッファオブジェクトを表現する標準的な方法を提供します。新規追加された @ref{68d,,inspect.BufferFlags} enum はバッファ生成を調整するフラグを表現します。(Jelle Zijltra による gh-102500@footnote{https://github.com/python/cpython/issues/102500} での貢献。)

@node PEP 709 内包表記のインライン化,エラーメッセージの改善<3>,PEP 688 バッファプロトコルを Python で利用可能にする,新しい機能<4>
@anchor{whatsnew/3 12 pep-709-comprehension-inlining}@anchor{68e}@anchor{whatsnew/3 12 whatsnew312-pep709}@anchor{679}
@subsubsection PEP 709: 内包表記のインライン化


辞書、リスト、そして集合の内包表記は今やインライン化され、内包表記の毎回の実行の度に一度しか使われない関数オブジェクトが新規作成されることはなくなります。これにより内包表記の実行は最大２倍速くなります。詳しくは 
@geindex Python Enhancement Proposals; PEP 709
PEP 709@footnote{https://peps.python.org/pep-0709/} を参照してください。

Comprehension iteration variables remain isolated and don't overwrite a
variable of the same name in the outer scope, nor are they visible after the
comprehension. Inlining does result in a few visible behavior changes:


@itemize *

@item 
There is no longer a separate frame for the comprehension in tracebacks,
and tracing/profiling no longer shows the comprehension as a function call.

@item 
The @ref{de,,symtable} module will no longer produce child symbol tables for each
comprehension; instead, the comprehension's locals will be included in the
parent function's symbol table.

@item 
Calling @ref{46f,,locals()} inside a comprehension now includes variables
from outside the comprehension, and no longer includes the synthetic @code{.0}
variable for the comprehension "argument".

@item 
A comprehension iterating directly over @code{locals()} (e.g. @code{[k for k in
locals()]}) may see "RuntimeError: dictionary changed size during iteration"
when run under tracing (e.g. code coverage measurement). This is the same
behavior already seen in e.g. @code{for k in locals():}. To avoid the error, first
create a list of keys to iterate over: @code{keys = list(locals()); [k for k in
keys]}.
@end itemize

(Contributed by Carl Meyer and Vladimir Matveev in 
@geindex Python Enhancement Proposals; PEP 709
PEP 709@footnote{https://peps.python.org/pep-0709/}.)

@node エラーメッセージの改善<3>,,PEP 709 内包表記のインライン化,新しい機能<4>
@anchor{whatsnew/3 12 improved-error-messages}@anchor{672}
@subsubsection エラーメッセージの改善



@itemize *

@item 
Modules from the standard library are now potentially suggested as part of
the error messages displayed by the interpreter when a @ref{452,,NameError} is
raised to the top level. (Contributed by Pablo Galindo in gh-98254@footnote{https://github.com/python/cpython/issues/98254}.)

@example
>>> sys.version_info
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined. Did you forget to import 'sys'?
@end example

@item 
Improve the error suggestion for @ref{452,,NameError} exceptions for instances.
Now if a @ref{452,,NameError} is raised in a method and the instance has an
attribute that's exactly equal to the name in the exception, the suggestion
will include @code{self.<NAME>} instead of the closest match in the method
scope. (Contributed by Pablo Galindo in gh-99139@footnote{https://github.com/python/cpython/issues/99139}.)

@example
>>> class A:
...    def __init__(self):
...        self.blech = 1
...
...    def foo(self):
...        somethin = blech
...
>>> A().foo()
Traceback (most recent call last):
  File "<stdin>", line 1
    somethin = blech
               ^^^^^
NameError: name 'blech' is not defined. Did you mean: 'self.blech'?
@end example

@item 
Improve the @ref{18e,,SyntaxError} error message when the user types @code{import x
from y} instead of @code{from y import x}. (Contributed by Pablo Galindo in gh-98931@footnote{https://github.com/python/cpython/issues/98931}.)

@example
>>> import a.y.z from b.y.z
Traceback (most recent call last):
  File "<stdin>", line 1
    import a.y.z from b.y.z
    ^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Did you mean to use 'from ... import ...' instead?
@end example

@item 
@ref{65b,,ImportError} exceptions raised from failed @code{from <module> import
<name>} statements now include suggestions for the value of @code{<name>} based on the
available names in @code{<module>}. (Contributed by Pablo Galindo in gh-91058@footnote{https://github.com/python/cpython/issues/91058}.)

@example
>>> from collections import chainmap
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'chainmap' from 'collections'. Did you mean: 'ChainMap'?
@end example
@end itemize

@node 型ヒントに関連する新しい機能,その他の言語変更<2>,新しい機能<4>,What's New In Python 3 12
@anchor{whatsnew/3 12 new-features-related-to-type-hints}@anchor{68f}
@subsection 型ヒントに関連する新しい機能


This section covers major changes affecting 
@geindex Python Enhancement Proposals; PEP 484
type hints@footnote{https://peps.python.org/pep-0484/} and
the @ref{10a,,typing} module.

@menu
* PEP 692; Using TypedDict for more precise **kwargs typing: PEP 692 Using TypedDict for more precise **kwargs typing. 
* PEP 698; Override Decorator for Static Typing: PEP 698 Override Decorator for Static Typing. 

@end menu

@node PEP 692 Using TypedDict for more precise **kwargs typing,PEP 698 Override Decorator for Static Typing,,型ヒントに関連する新しい機能
@anchor{whatsnew/3 12 pep-692-using-typeddict-for-more-precise-kwargs-typing}@anchor{690}@anchor{whatsnew/3 12 whatsnew312-pep692}@anchor{67a}
@subsubsection PEP 692: Using @code{TypedDict} for more precise @code{**kwargs} typing


Typing @code{**kwargs} in a function signature as introduced by 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} allowed
for valid annotations only in cases where all of the @code{**kwargs} were of the
same type.

@geindex Python Enhancement Proposals; PEP 692
PEP 692@footnote{https://peps.python.org/pep-0692/} specifies a more precise way of typing @code{**kwargs} by relying on
typed dictionaries:

@example
from typing import TypedDict, Unpack

class Movie(TypedDict):
  name: str
  year: int

def foo(**kwargs: Unpack[Movie]): ...
@end example

より詳しくは 
@geindex Python Enhancement Proposals; PEP 692
PEP 692@footnote{https://peps.python.org/pep-0692/} を参照してください。

(Contributed by Franek Magiera in gh-103629@footnote{https://github.com/python/cpython/issues/103629}.)

@node PEP 698 Override Decorator for Static Typing,,PEP 692 Using TypedDict for more precise **kwargs typing,型ヒントに関連する新しい機能
@anchor{whatsnew/3 12 pep-698-override-decorator-for-static-typing}@anchor{691}@anchor{whatsnew/3 12 whatsnew312-pep698}@anchor{67c}
@subsubsection PEP 698: Override Decorator for Static Typing


A new decorator @ref{67d,,typing.override()} has been added to the @ref{10a,,typing}
module. It indicates to type checkers that the method is intended to override
a method in a superclass. This allows type checkers to catch mistakes where
a method that is intended to override something in a base class
does not in fact do so.

以下はプログラム例です:

@example
from typing import override

class Base:
  def get_color(self) -> str:
    return "blue"

class GoodChild(Base):
  @@override  # ok: overrides Base.get_color
  def get_color(self) -> str:
    return "yellow"

class BadChild(Base):
  @@override  # type checker error: does not override Base.get_color
  def get_colour(self) -> str:
    return "red"
@end example

See 
@geindex Python Enhancement Proposals; PEP 698
PEP 698@footnote{https://peps.python.org/pep-0698/} for more details.

(Contributed by Steven Troxler in gh-101561@footnote{https://github.com/python/cpython/issues/101561}.)

@node その他の言語変更<2>,新たなモジュール<2>,型ヒントに関連する新しい機能,What's New In Python 3 12
@anchor{whatsnew/3 12 other-language-changes}@anchor{692}
@subsection その他の言語変更



@itemize *

@item 
The parser now raises @ref{18e,,SyntaxError} when parsing source code containing
null bytes. (Contributed by Pablo Galindo in gh-96670@footnote{https://github.com/python/cpython/issues/96670}.)

@item 
A backslash-character pair that is not a valid escape sequence now generates
a @ref{1ae,,SyntaxWarning}, instead of @ref{1a3,,DeprecationWarning}.
For example, @code{re.compile("\d+\.\d+")} now emits a @ref{1ae,,SyntaxWarning}
(@code{"\d"} is an invalid escape sequence, use raw strings for regular
expression: @code{re.compile(r"\d+\.\d+")}).
In a future Python version, @ref{18e,,SyntaxError} will eventually be raised,
instead of @ref{1ae,,SyntaxWarning}.
(Contributed by Victor Stinner in gh-98401@footnote{https://github.com/python/cpython/issues/98401}.)

@item 
Octal escapes with value larger than @code{0o377} (ex: @code{"\477"}), deprecated
in Python 3.11, now produce a @ref{1ae,,SyntaxWarning}, instead of
@ref{1a3,,DeprecationWarning}.
In a future Python version they will be eventually a @ref{18e,,SyntaxError}.
(Contributed by Victor Stinner in gh-98401@footnote{https://github.com/python/cpython/issues/98401}.)

@item 
Variables used in the target part of comprehensions that are not stored to
can now be used in assignment expressions (@code{:=}).
For example, in @code{[(b := 1) for a, b.prop in some_iter]}, the assignment to
@code{b} is now allowed. Note that assigning to variables stored to in the target
part of comprehensions (like @code{a}) is still disallowed, as per 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/}.
(Contributed by Nikita Sobolev in gh-100581@footnote{https://github.com/python/cpython/issues/100581}.)

@item 
Exceptions raised in a class or type's @code{__set_name__} method are no longer
wrapped by a @ref{244,,RuntimeError}. Context information is added to the
exception as a 
@geindex Python Enhancement Proposals; PEP 678
PEP 678@footnote{https://peps.python.org/pep-0678/} note. (Contributed by Irit Katriel in gh-77757@footnote{https://github.com/python/cpython/issues/77757}.)

@item 
When a @code{try-except*} construct handles the entire @ref{4d2,,ExceptionGroup}
and raises one other exception, that exception is no longer wrapped in an
@ref{4d2,,ExceptionGroup}. Also changed in version 3.11.4. (Contributed by Irit
Katriel in gh-103590@footnote{https://github.com/python/cpython/issues/103590}.)

@item 
The Garbage Collector now runs only on the eval breaker mechanism of the
Python bytecode evaluation loop instead of object allocations. The GC can
also run when @ref{693,,PyErr_CheckSignals()} is called so C extensions that
need to run for a long time without executing any Python code also have a
chance to execute the GC periodically. (Contributed by Pablo Galindo in
gh-97922@footnote{https://github.com/python/cpython/issues/97922}.)

@item 
All builtin and extension callables expecting boolean parameters now accept
arguments of any type instead of just @ref{3c3,,bool} and @ref{19b,,int}.
(Contributed by Serhiy Storchaka in gh-60203@footnote{https://github.com/python/cpython/issues/60203}.)

@item 
@ref{165,,memoryview} now supports the half-float type (the "e" format code).
(Contributed by Donghee Na and Antoine Pitrou in gh-90751@footnote{https://github.com/python/cpython/issues/90751}.)

@item 
@ref{694,,slice} objects are now hashable, allowing them to be used as dict keys and
set items. (Contributed by Will Bradshaw, Furkan Onder, and Raymond Hettinger in gh-101264@footnote{https://github.com/python/cpython/issues/101264}.)

@item 
@ref{695,,sum()} now uses Neumaier summation to improve accuracy and commutativity
when summing floats or mixed ints and floats.
(Contributed by Raymond Hettinger in gh-100425@footnote{https://github.com/python/cpython/issues/100425}.)

@item 
@ref{1c2,,ast.parse()} now raises @ref{18e,,SyntaxError} instead of @ref{2ec,,ValueError}
when parsing source code containing null bytes. (Contributed by Pablo Galindo
in gh-96670@footnote{https://github.com/python/cpython/issues/96670}.)

@item 
The extraction methods in @ref{e4,,tarfile}, and @ref{696,,shutil.unpack_archive()},
have a new a `filter' argument that allows limiting tar features than may be
surprising or dangerous, such as creating files outside the destination
directory.
See @ref{697,,tarfile extraction filters} for details.
In Python 3.14, the default will switch to @code{'data'}.
(Contributed by Petr Viktorin in 
@geindex Python Enhancement Proposals; PEP 706
PEP 706@footnote{https://peps.python.org/pep-0706/}.)

@item 
@ref{698,,types.MappingProxyType} instances are now hashable if the underlying
mapping is hashable.
(Contributed by Serhiy Storchaka in gh-87995@footnote{https://github.com/python/cpython/issues/87995}.)

@item 
Add @ref{4ae,,support for the perf profiler} through the new
environment variable 
@geindex PYTHONPERFSUPPORT
@geindex 環境変数; PYTHONPERFSUPPORT
@ref{699,,PYTHONPERFSUPPORT}
and command-line option @ref{16f,,-X perf},
as well as the new @ref{69a,,sys.activate_stack_trampoline()},
@ref{69b,,sys.deactivate_stack_trampoline()},
and @ref{69c,,sys.is_stack_trampoline_active()} functions.
(Design by Pablo Galindo. Contributed by Pablo Galindo and Christian Heimes
with contributions from Gregory P. Smith [Google] and Mark Shannon
in gh-96123@footnote{https://github.com/python/cpython/issues/96123}.)
@end itemize

@node 新たなモジュール<2>,改良されたモジュール<2>,その他の言語変更<2>,What's New In Python 3 12
@anchor{whatsnew/3 12 new-modules}@anchor{69d}
@subsection 新たなモジュール



@itemize *

@item 
None.
@end itemize

@node 改良されたモジュール<2>,最適化<3>,新たなモジュール<2>,What's New In Python 3 12
@anchor{whatsnew/3 12 improved-modules}@anchor{69e}
@subsection 改良されたモジュール


@menu
* array:: 
* asyncio: asyncio<5>. 
* calendar: calendar<2>. 
* csv:: 
* dis: dis<3>. 
* fractions: fractions<3>. 
* importlib.resources: importlib resources. 
* inspect: inspect<2>. 
* itertools: itertools<3>. 
* math: math<3>. 
* os: os<3>. 
* os.path: os path<3>. 
* pathlib: pathlib<6>. 
* プラットフォーム: プラットフォーム<2>. 
* pdb: pdb<4>. 
* random: random<2>. 
* shutil: shutil<2>. 
* sqlite3: sqlite3<3>. 
* statistics: statistics<2>. 
* sys: sys<3>. 
* tempfile: tempfile<2>. 
* threading: threading<2>. 
* tkinter: tkinter<3>. 
* tokenize:: 
* types: types<3>. 
* typing: typing<4>. 
* unicodedata: unicodedata<3>. 
* unittest: unittest<3>. 
* uuid: uuid<3>. 

@end menu

@node array,asyncio<5>,,改良されたモジュール<2>
@anchor{whatsnew/3 12 array}@anchor{69f}
@subsubsection array



@itemize *

@item 
The @ref{4be,,array.array} class now supports subscripting, making it a
@ref{1a1,,generic type}. (Contributed by Jelle Zijlstra in gh-98658@footnote{https://github.com/python/cpython/issues/98658}.)
@end itemize

@node asyncio<5>,calendar<2>,array,改良されたモジュール<2>
@anchor{whatsnew/3 12 asyncio}@anchor{6a0}
@subsubsection asyncio



@itemize *

@item 
The performance of writing to sockets in @ref{b,,asyncio} has been
significantly improved. @code{asyncio} now avoids unnecessary copying when
writing to sockets and uses @ref{6a1,,sendmsg()} if the platform
supports it. (Contributed by Kumar Aditya in gh-91166@footnote{https://github.com/python/cpython/issues/91166}.)

@item 
Add @ref{6a2,,asyncio.eager_task_factory()} and @ref{6a3,,asyncio.create_eager_task_factory()}
functions to allow opting an event loop in to eager task execution,
making some use-cases 2x to 5x faster.
(Contributed by Jacob Bower & Itamar Oren in gh-102853@footnote{https://github.com/python/cpython/issues/102853}, gh-104140@footnote{https://github.com/python/cpython/issues/104140}, and gh-104138@footnote{https://github.com/python/cpython/issues/104138})

@item 
On Linux, @ref{b,,asyncio} uses @code{asyncio.PidfdChildWatcher} by default
if @ref{6a4,,os.pidfd_open()} is available and functional instead of
@code{asyncio.ThreadedChildWatcher}.
(Contributed by Kumar Aditya in gh-98024@footnote{https://github.com/python/cpython/issues/98024}.)

@item 
The event loop now uses the best available child watcher for each platform
(@code{asyncio.PidfdChildWatcher} if supported and
@code{asyncio.ThreadedChildWatcher} otherwise), so manually
configuring a child watcher is not recommended.
(Contributed by Kumar Aditya in gh-94597@footnote{https://github.com/python/cpython/issues/94597}.)

@item 
Add `loop_factory' parameter to @ref{2f3,,asyncio.run()} to allow specifying
a custom event loop factory.
(Contributed by Kumar Aditya in gh-99388@footnote{https://github.com/python/cpython/issues/99388}.)

@item 
Add C implementation of @ref{6a5,,asyncio.current_task()} for 4x-6x speedup.
(Contributed by Itamar Oren and Pranav Thulasiram Bhat in gh-100344@footnote{https://github.com/python/cpython/issues/100344}.)

@item 
@ref{6a6,,asyncio.iscoroutine()} now returns @code{False} for generators as
@ref{b,,asyncio} does not support legacy generator-based coroutines.
(Contributed by Kumar Aditya in gh-102748@footnote{https://github.com/python/cpython/issues/102748}.)

@item 
@ref{6a7,,asyncio.wait()} and @ref{4c6,,asyncio.as_completed()} now accepts generators
yielding tasks.
(Contributed by Kumar Aditya in gh-78530@footnote{https://github.com/python/cpython/issues/78530}.)
@end itemize

@node calendar<2>,csv,asyncio<5>,改良されたモジュール<2>
@anchor{whatsnew/3 12 calendar}@anchor{6a8}
@subsubsection calendar



@itemize *

@item 
Add enums @ref{6a9,,calendar.Month} and @ref{6aa,,calendar.Day}
defining months of the year and days of the week.
(Contributed by Prince Roshan in gh-103636@footnote{https://github.com/python/cpython/issues/103636}.)
@end itemize

@node csv,dis<3>,calendar<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 csv}@anchor{6ab}
@subsubsection csv



@itemize *

@item 
Add @ref{6ac,,csv.QUOTE_NOTNULL} and @ref{6ad,,csv.QUOTE_STRINGS} flags to
provide finer grained control of @code{None} and empty strings by
@ref{6ae,,reader} and @ref{6af,,writer} objects.
@end itemize

@node dis<3>,fractions<3>,csv,改良されたモジュール<2>
@anchor{whatsnew/3 12 dis}@anchor{6b0}
@subsubsection dis



@itemize *

@item 
Pseudo instruction opcodes (which are used by the compiler but
do not appear in executable bytecode) are now exposed in the
@ref{3c,,dis} module.
@ref{6b1,,HAVE_ARGUMENT} is still relevant to real opcodes,
but it is not useful for pseudo instructions. Use the new
@ref{59f,,dis.hasarg} collection instead.
(Contributed by Irit Katriel in gh-94216@footnote{https://github.com/python/cpython/issues/94216}.)

@item 
Add the @ref{6b2,,dis.hasexc} collection to signify instructions that set
an exception handler. (Contributed by Irit Katriel in gh-94216@footnote{https://github.com/python/cpython/issues/94216}.)
@end itemize

@node fractions<3>,importlib resources,dis<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 fractions}@anchor{6b3}
@subsubsection fractions



@itemize *

@item 
Objects of type @ref{213,,fractions.Fraction} now support float-style
formatting. (Contributed by Mark Dickinson in gh-100161@footnote{https://github.com/python/cpython/issues/100161}.)
@end itemize

@node importlib resources,inspect<2>,fractions<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 importlib-resources}@anchor{6b4}
@subsubsection importlib.resources



@itemize *

@item 
@ref{6b5,,importlib.resources.as_file()} now supports resource directories.
(Contributed by Jason R. Coombs in gh-97930@footnote{https://github.com/python/cpython/issues/97930}.)

@item 
Rename first parameter of @ref{6b6,,importlib.resources.files()} to `anchor'.
(Contributed by Jason R. Coombs in gh-100598@footnote{https://github.com/python/cpython/issues/100598}.)
@end itemize

@node inspect<2>,itertools<3>,importlib resources,改良されたモジュール<2>
@anchor{whatsnew/3 12 inspect}@anchor{6b7}
@subsubsection inspect



@itemize *

@item 
Add @ref{6b8,,inspect.markcoroutinefunction()} to mark sync functions that return
a @ref{6b9,,coroutine} for use with @ref{30d,,inspect.iscoroutinefunction()}.
(Contributed by Carlton Gibson in gh-99247@footnote{https://github.com/python/cpython/issues/99247}.)

@item 
Add @ref{6ba,,inspect.getasyncgenstate()} and @ref{6bb,,inspect.getasyncgenlocals()}
for determining the current state of asynchronous generators.
(Contributed by Thomas Krennwallner in gh-79940@footnote{https://github.com/python/cpython/issues/79940}.)

@item 
The performance of @ref{6bc,,inspect.getattr_static()} has been considerably
improved. Most calls to the function should be at least 2x faster than they
were in Python 3.11. (Contributed by Alex Waygood in gh-103193@footnote{https://github.com/python/cpython/issues/103193}.)
@end itemize

@node itertools<3>,math<3>,inspect<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 itertools}@anchor{6bd}
@subsubsection itertools



@itemize *

@item 
Add @ref{511,,itertools.batched()} for collecting into even-sized
tuples where the last batch may be shorter than the rest.
(Contributed by Raymond Hettinger in gh-98363@footnote{https://github.com/python/cpython/issues/98363}.)
@end itemize

@node math<3>,os<3>,itertools<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 math}@anchor{6be}
@subsubsection math



@itemize *

@item 
Add @ref{6bf,,math.sumprod()} for computing a sum of products.
(Contributed by Raymond Hettinger in gh-100485@footnote{https://github.com/python/cpython/issues/100485}.)

@item 
Extend @ref{6c0,,math.nextafter()} to include a `steps' argument
for moving up or down multiple steps at a time. (Contributed by
Matthias Goergens, Mark Dickinson, and Raymond Hettinger in gh-94906@footnote{https://github.com/python/cpython/issues/94906}.)
@end itemize

@node os<3>,os path<3>,math<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 os}@anchor{6c1}
@subsubsection os



@itemize *

@item 
Add @ref{6c2,,os.PIDFD_NONBLOCK} to open a file descriptor
for a process with @ref{6a4,,os.pidfd_open()} in non-blocking mode.
(Contributed by Kumar Aditya in gh-93312@footnote{https://github.com/python/cpython/issues/93312}.)

@item 
@ref{6c3,,os.DirEntry} now includes an @ref{6c4,,os.DirEntry.is_junction()}
method to check if the entry is a junction.
(Contributed by Charles Machalow in gh-99547@footnote{https://github.com/python/cpython/issues/99547}.)

@item 
Add @ref{6c5,,os.listdrives()}, @ref{6c6,,os.listvolumes()} and @ref{6c7,,os.listmounts()}
functions on Windows for enumerating drives, volumes and mount points.
(Contributed by Steve Dower in gh-102519@footnote{https://github.com/python/cpython/issues/102519}.)

@item 
@ref{26d,,os.stat()} and @ref{6c8,,os.lstat()} are now more accurate on Windows.
The @code{st_birthtime} field will now be filled with the creation time
of the file, and @code{st_ctime} is deprecated but still contains the
creation time (but in the future will return the last metadata change,
for consistency with other platforms). @code{st_dev} may be up to 64 bits
and @code{st_ino} up to 128 bits depending on your file system, and
@code{st_rdev} is always set to zero rather than incorrect values.
Both functions may be significantly faster on newer releases of
Windows. (Contributed by Steve Dower in gh-99726@footnote{https://github.com/python/cpython/issues/99726}.)
@end itemize

@node os path<3>,pathlib<6>,os<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 os-path}@anchor{6c9}
@subsubsection os.path



@itemize *

@item 
Add @ref{6ca,,os.path.isjunction()} to check if a given path is a junction.
(Contributed by Charles Machalow in gh-99547@footnote{https://github.com/python/cpython/issues/99547}.)

@item 
Add @ref{6cb,,os.path.splitroot()} to split a path into a triad
@code{(drive, root, tail)}. (Contributed by Barney Gale in gh-101000@footnote{https://github.com/python/cpython/issues/101000}.)
@end itemize

@node pathlib<6>,プラットフォーム<2>,os path<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 pathlib}@anchor{6cc}
@subsubsection pathlib



@itemize *

@item 
Add support for subclassing @ref{6cd,,pathlib.PurePath} and
@ref{266,,pathlib.Path}, plus their Posix- and Windows-specific variants.
Subclasses may override the @ref{6ce,,pathlib.PurePath.with_segments()} method
to pass information between path instances.

@item 
Add @ref{6cf,,pathlib.Path.walk()} for walking the directory trees and generating
all file or directory names within them, similar to @ref{6d0,,os.walk()}.
(Contributed by Stanislav Zmiev in gh-90385@footnote{https://github.com/python/cpython/issues/90385}.)

@item 
Add `walk_up' optional parameter to @ref{2fd,,pathlib.PurePath.relative_to()}
to allow the insertion of @code{..} entries in the result; this behavior is
more consistent with @ref{6d1,,os.path.relpath()}.
(Contributed by Domenico Ragusa in gh-84538@footnote{https://github.com/python/cpython/issues/84538}.)

@item 
Add @ref{6d2,,pathlib.Path.is_junction()} as a proxy to @ref{6ca,,os.path.isjunction()}.
(Contributed by Charles Machalow in gh-99547@footnote{https://github.com/python/cpython/issues/99547}.)

@item 
Add `case_sensitive' optional parameter to @ref{537,,pathlib.Path.glob()},
@ref{538,,pathlib.Path.rglob()} and @ref{6d3,,pathlib.PurePath.match()} for matching
the path's case sensitivity, allowing for more precise control over the matching process.
@end itemize

@node プラットフォーム<2>,pdb<4>,pathlib<6>,改良されたモジュール<2>
@anchor{whatsnew/3 12 platform}@anchor{6d4}
@subsubsection プラットフォーム



@itemize *

@item 
Add support for detecting Windows 11 and Windows Server releases past 2012.
Previously, lookups on Windows Server platforms newer than Windows Server 2012
and on Windows 11 would return @code{Windows-10}.
(Contributed by Steve Dower in gh-89545@footnote{https://github.com/python/cpython/issues/89545}.)
@end itemize

@node pdb<4>,random<2>,プラットフォーム<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 pdb}@anchor{6d5}
@subsubsection pdb



@itemize *

@item 
Add convenience variables to hold values temporarily for debug session
and provide quick access to values like the current frame or the return
value.
(Contributed by Tian Gao in gh-103693@footnote{https://github.com/python/cpython/issues/103693}.)
@end itemize

@node random<2>,shutil<2>,pdb<4>,改良されたモジュール<2>
@anchor{whatsnew/3 12 random}@anchor{6d6}
@subsubsection random



@itemize *

@item 
Add @ref{6d7,,random.binomialvariate()}.
(Contributed by Raymond Hettinger in gh-81620@footnote{https://github.com/python/cpython/issues/81620}.)

@item 
Add a default of @code{lambd=1.0} to @ref{6d8,,random.expovariate()}.
(Contributed by Raymond Hettinger in gh-100234@footnote{https://github.com/python/cpython/issues/100234}.)
@end itemize

@node shutil<2>,sqlite3<3>,random<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 shutil}@anchor{6d9}
@subsubsection shutil



@itemize *

@item 
@ref{6da,,shutil.make_archive()} now passes the `root_dir' argument to custom
archivers which support it.
In this case it no longer temporarily changes the current working directory
of the process to `root_dir' to perform archiving.
(Contributed by Serhiy Storchaka in gh-74696@footnote{https://github.com/python/cpython/issues/74696}.)

@item 
@ref{356,,shutil.rmtree()} now accepts a new argument `onexc' which is an
error handler like `onerror' but which expects an exception instance
rather than a `(typ, val, tb)' triplet. `onerror' is deprecated.
(Contributed by Irit Katriel in gh-102828@footnote{https://github.com/python/cpython/issues/102828}.)

@item 
@ref{6db,,shutil.which()} now consults the `PATHEXT' environment variable to
find matches within `PATH' on Windows even when the given `cmd' includes
a directory component.
(Contributed by Charles Machalow in gh-103179@footnote{https://github.com/python/cpython/issues/103179}.)

@ref{6db,,shutil.which()} will call @code{NeedCurrentDirectoryForExePathW} when
querying for executables on Windows to determine if the current working
directory should be prepended to the search path.
(Contributed by Charles Machalow in gh-103179@footnote{https://github.com/python/cpython/issues/103179}.)

@ref{6db,,shutil.which()} will return a path matching the `cmd' with a component
from @code{PATHEXT} prior to a direct match elsewhere in the search path on
Windows.
(Contributed by Charles Machalow in gh-103179@footnote{https://github.com/python/cpython/issues/103179}.)
@end itemize

@node sqlite3<3>,statistics<2>,shutil<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 sqlite3}@anchor{6dc}
@subsubsection sqlite3



@itemize *

@item 
Add a @ref{674,,command-line interface}.
(Contributed by Erlend E. Aasland in gh-77617@footnote{https://github.com/python/cpython/issues/77617}.)

@item 
Add the @ref{6dd,,sqlite3.Connection.autocommit} attribute
to @ref{54d,,sqlite3.Connection}
and the `autocommit' parameter to @ref{5a6,,sqlite3.connect()}
to control 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/}-compliant
@ref{6de,,transaction handling}.
(Contributed by Erlend E. Aasland in gh-83638@footnote{https://github.com/python/cpython/issues/83638}.)

@item 
Add `entrypoint' keyword-only parameter to
@ref{6df,,sqlite3.Connection.load_extension()},
for overriding the SQLite extension entry point.
(Contributed by Erlend E. Aasland in gh-103015@footnote{https://github.com/python/cpython/issues/103015}.)

@item 
Add @ref{6e0,,sqlite3.Connection.getconfig()} and
@ref{6e1,,sqlite3.Connection.setconfig()} to @ref{54d,,sqlite3.Connection}
to make configuration changes to a database connection.
(Contributed by Erlend E. Aasland in gh-103489@footnote{https://github.com/python/cpython/issues/103489}.)
@end itemize

@node statistics<2>,sys<3>,sqlite3<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 statistics}@anchor{6e2}
@subsubsection statistics



@itemize *

@item 
Extend @ref{6e3,,statistics.correlation()} to include as a @code{ranked} method
for computing the Spearman correlation of ranked data.
(Contributed by Raymond Hettinger in gh-95861@footnote{https://github.com/python/cpython/issues/95861}.)
@end itemize

@node sys<3>,tempfile<2>,statistics<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 sys}@anchor{6e4}
@subsubsection sys



@itemize *

@item 
Add the @ref{e0,,sys.monitoring} namespace to expose the new @ref{671,,PEP 669} monitoring API.
(Contributed by Mark Shannon in gh-103082@footnote{https://github.com/python/cpython/issues/103082}.)

@item 
Add @ref{69a,,sys.activate_stack_trampoline()} and
@ref{69b,,sys.deactivate_stack_trampoline()} for activating and deactivating
stack profiler trampolines,
and @ref{69c,,sys.is_stack_trampoline_active()} for querying if stack profiler
trampolines are active.
(Contributed by Pablo Galindo and Christian Heimes
with contributions from Gregory P. Smith [Google] and Mark Shannon
in gh-96123@footnote{https://github.com/python/cpython/issues/96123}.)

@item 
Add @ref{6e5,,sys.last_exc} which holds the last unhandled exception that
was raised (for post-mortem debugging use cases). Deprecate the
three fields that have the same information in its legacy form:
@ref{6e6,,sys.last_type}, @ref{6e7,,sys.last_value} and @ref{6e8,,sys.last_traceback}.
(Contributed by Irit Katriel in gh-102778@footnote{https://github.com/python/cpython/issues/102778}.)

@item 
@ref{6e9,,sys._current_exceptions()} now returns a mapping from thread-id to an
exception instance, rather than to a @code{(typ, exc, tb)} tuple.
(Contributed by Irit Katriel in gh-103176@footnote{https://github.com/python/cpython/issues/103176}.)

@item 
@ref{6ea,,sys.setrecursionlimit()} and @ref{6eb,,sys.getrecursionlimit()}.
The recursion limit now applies only to Python code. Builtin functions do
not use the recursion limit, but are protected by a different mechanism
that prevents recursion from causing a virtual machine crash.
@end itemize

@node tempfile<2>,threading<2>,sys<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 tempfile}@anchor{6ec}
@subsubsection tempfile



@itemize *

@item 
The @ref{6ed,,tempfile.NamedTemporaryFile} function has a new optional parameter
`delete_on_close' (Contributed by Evgeny Zorin in gh-58451@footnote{https://github.com/python/cpython/issues/58451}.)

@item 
@ref{52d,,tempfile.mkdtemp()} now always returns an absolute path, even if the
argument provided to the `dir' parameter is a relative path.
@end itemize

@node threading<2>,tkinter<3>,tempfile<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 threading}@anchor{6ee}
@subsubsection threading



@itemize *

@item 
Add @ref{6ef,,threading.settrace_all_threads()} and
@ref{6f0,,threading.setprofile_all_threads()} that allow to set tracing and
profiling functions in all running threads in addition to the calling one.
(Contributed by Pablo Galindo in gh-93503@footnote{https://github.com/python/cpython/issues/93503}.)
@end itemize

@node tkinter<3>,tokenize,threading<2>,改良されたモジュール<2>
@anchor{whatsnew/3 12 tkinter}@anchor{6f1}
@subsubsection tkinter



@itemize *

@item 
@code{tkinter.Canvas.coords()} now flattens its arguments.
It now accepts not only coordinates as separate arguments
(@code{x1, y1, x2, y2, ...}) and a sequence of coordinates
(@code{[x1, y1, x2, y2, ...]}), but also coordinates grouped in pairs
(@code{(x1, y1), (x2, y2), ...} and @code{[(x1, y1), (x2, y2), ...]}),
like @code{create_*()} methods.
(Contributed by Serhiy Storchaka in gh-94473@footnote{https://github.com/python/cpython/issues/94473}.)
@end itemize

@node tokenize,types<3>,tkinter<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 tokenize}@anchor{6f2}
@subsubsection tokenize



@itemize *

@item 
The @ref{101,,tokenize} module includes the changes introduced in 
@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/}.
(Contributed by Marta Gómez Macías and Pablo Galindo in gh-102856@footnote{https://github.com/python/cpython/issues/102856}.)
See @ref{6f3,,Python 3.12 への移植} for more information on the
changes to the @ref{101,,tokenize} module.
@end itemize

@node types<3>,typing<4>,tokenize,改良されたモジュール<2>
@anchor{whatsnew/3 12 types}@anchor{6f4}
@subsubsection types



@itemize *

@item 
Add @ref{6f5,,types.get_original_bases()} to allow for further introspection of
@ref{6f6,,ユーザー定義のジェネリック型} when subclassed. (Contributed by
James Hilton-Balfe and Alex Waygood in gh-101827@footnote{https://github.com/python/cpython/issues/101827}.)
@end itemize

@node typing<4>,unicodedata<3>,types<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 typing}@anchor{6f7}@anchor{whatsnew/3 12 whatsnew-typing-py312}@anchor{6f8}
@subsubsection typing



@itemize *

@item 
@ref{2ad,,isinstance()} checks against
@ref{675,,runtime-checkable protocols} now use
@ref{6bc,,inspect.getattr_static()} rather than @ref{6f9,,hasattr()} to lookup whether
attributes exist. This means that descriptors and @ref{6fa,,__getattr__()}
methods are no longer unexpectedly evaluated during @code{isinstance()} checks
against runtime-checkable protocols. However, it may also mean that some
objects which used to be considered instances of a runtime-checkable protocol
may no longer be considered instances of that protocol on Python 3.12+, and
vice versa. Most users are unlikely to be affected by this change.
(Contributed by Alex Waygood in gh-102433@footnote{https://github.com/python/cpython/issues/102433}.)

@item 
The members of a runtime-checkable protocol are now considered "frozen" at
runtime as soon as the class has been created. Monkey-patching attributes
onto a runtime-checkable protocol will still work, but will have no impact on
@ref{2ad,,isinstance()} checks comparing objects to the protocol. For example:

@example
>>> from typing import Protocol, runtime_checkable
>>> @@runtime_checkable
... class HasX(Protocol):
...     x = 1
...
>>> class Foo: ...
...
>>> f = Foo()
>>> isinstance(f, HasX)
False
>>> f.x = 1
>>> isinstance(f, HasX)
True
>>> HasX.y = 2
>>> isinstance(f, HasX)  # unchanged, even though HasX now also has a "y" attribute
True
@end example

This change was made in order to speed up @code{isinstance()} checks against
runtime-checkable protocols.

@item 
The performance profile of @ref{2ad,,isinstance()} checks against
@ref{675,,runtime-checkable protocols} has changed
significantly. Most @code{isinstance()} checks against protocols with only a few
members should be at least 2x faster than in 3.11, and some may be 20x
faster or more. However, @code{isinstance()} checks against protocols with many
members may be slower than in Python 3.11. (Contributed by Alex
Waygood in gh-74690@footnote{https://github.com/python/cpython/issues/74690} and gh-103193@footnote{https://github.com/python/cpython/issues/103193}.)

@item 
All @ref{332,,typing.TypedDict} and @ref{331,,typing.NamedTuple} classes now have the
@code{__orig_bases__} attribute. (Contributed by Adrian Garcia Badaracco in
gh-103699@footnote{https://github.com/python/cpython/issues/103699}.)

@item 
Add @code{frozen_default} parameter to @ref{6fb,,typing.dataclass_transform()}.
(Contributed by Erik De Bonte in gh-99957@footnote{https://github.com/python/cpython/issues/99957}.)
@end itemize

@node unicodedata<3>,unittest<3>,typing<4>,改良されたモジュール<2>
@anchor{whatsnew/3 12 unicodedata}@anchor{6fc}
@subsubsection unicodedata



@itemize *

@item 
The Unicode database has been updated to version 15.0.0. (Contributed by
Benjamin Peterson in gh-96734@footnote{https://github.com/python/cpython/issues/96734}).
@end itemize

@node unittest<3>,uuid<3>,unicodedata<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 unittest}@anchor{6fd}
@subsubsection unittest


Add a @code{--durations} command line option, showing the N slowest test cases:

@example
python3 -m unittest --durations=3 lib.tests.test_threading
.....
Slowest test durations
----------------------------------------------------------------------
1.210s     test_timeout (Lib.test.test_threading.BarrierTests)
1.003s     test_default_timeout (Lib.test.test_threading.BarrierTests)
0.518s     test_timeout (Lib.test.test_threading.EventTests)

(0.000 durations hidden.  Use -v to show these durations.)
----------------------------------------------------------------------
Ran 158 tests in 9.869s

OK (skipped=3)
@end example

(Contributed by Giampaolo Rodola in gh-48330@footnote{https://github.com/python/cpython/issues/48330})

@node uuid<3>,,unittest<3>,改良されたモジュール<2>
@anchor{whatsnew/3 12 uuid}@anchor{6fe}
@subsubsection uuid



@itemize *

@item 
Add a @ref{676,,command-line interface}.
(Contributed by Adam Chhina in gh-88597@footnote{https://github.com/python/cpython/issues/88597}.)
@end itemize

@node 最適化<3>,CPython バイトコードの変更<2>,改良されたモジュール<2>,What's New In Python 3 12
@anchor{whatsnew/3 12 optimizations}@anchor{6ff}
@subsection 最適化



@itemize *

@item 
Remove @code{wstr} and @code{wstr_length} members from Unicode objects.
It reduces object size by 8 or 16 bytes on 64bit platform. (
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/})
(Contributed by Inada Naoki in gh-92536@footnote{https://github.com/python/cpython/issues/92536}.)

@item 
Add experimental support for using the BOLT binary optimizer in the build
process, which improves performance by 1-5%.
(Contributed by Kevin Modzelewski in gh-90536@footnote{https://github.com/python/cpython/issues/90536} and tuned by Donghee Na in gh-101525@footnote{https://github.com/python/cpython/issues/101525})

@item 
Speed up the regular expression substitution (functions @ref{5a3,,re.sub()} and
@ref{5a4,,re.subn()} and corresponding @code{re.Pattern} methods) for
replacement strings containing group references by 2--3 times.
(Contributed by Serhiy Storchaka in gh-91524@footnote{https://github.com/python/cpython/issues/91524}.)

@item 
Speed up @ref{1c7,,asyncio.Task} creation by deferring expensive string formatting.
(Contributed by Itamar Oren in gh-103793@footnote{https://github.com/python/cpython/issues/103793}.)

@item 
The @ref{700,,tokenize.tokenize()} and @ref{701,,tokenize.generate_tokens()} functions are
up to 64% faster as a side effect of the changes required to cover 
@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/} in
the @ref{101,,tokenize} module. (Contributed by Marta Gómez Macías and Pablo Galindo
in gh-102856@footnote{https://github.com/python/cpython/issues/102856}.)

@item 
Speed up @ref{1a6,,super()} method calls and attribute loads via the
new @ref{702,,LOAD_SUPER_ATTR} instruction. (Contributed by Carl Meyer and
Vladimir Matveev in gh-103497@footnote{https://github.com/python/cpython/issues/103497}.)
@end itemize

@node CPython バイトコードの変更<2>,Demos and Tools,最適化<3>,What's New In Python 3 12
@anchor{whatsnew/3 12 cpython-bytecode-changes}@anchor{703}
@subsection CPython バイトコードの変更



@itemize *

@item 
Remove the @code{LOAD_METHOD} instruction. It has been merged into
@ref{704,,LOAD_ATTR}. @ref{704,,LOAD_ATTR} will now behave like the old
@code{LOAD_METHOD} instruction if the low bit of its oparg is set.
(Contributed by Ken Jin in gh-93429@footnote{https://github.com/python/cpython/issues/93429}.)

@item 
Remove the @code{JUMP_IF_FALSE_OR_POP} and @code{JUMP_IF_TRUE_OR_POP}
instructions. (Contributed by Irit Katriel in gh-102859@footnote{https://github.com/python/cpython/issues/102859}.)

@item 
Remove the @code{PRECALL} instruction. (Contributed by Mark Shannon in
gh-92925@footnote{https://github.com/python/cpython/issues/92925}.)

@item 
Add the @ref{705,,BINARY_SLICE} and @ref{706,,STORE_SLICE} instructions.
(Contributed by Mark Shannon in gh-94163@footnote{https://github.com/python/cpython/issues/94163}.)

@item 
Add the @ref{707,,CALL_INTRINSIC_1} instructions.
(Contributed by Mark Shannon in gh-99005@footnote{https://github.com/python/cpython/issues/99005}.)

@item 
Add the @ref{708,,CALL_INTRINSIC_2} instruction.
(Contributed by Irit Katriel in gh-101799@footnote{https://github.com/python/cpython/issues/101799}.)

@item 
Add the @ref{709,,CLEANUP_THROW} instruction.
(Contributed by Brandt Bucher in gh-90997@footnote{https://github.com/python/cpython/issues/90997}.)

@item 
Add the @code{END_SEND} instruction.
(Contributed by Mark Shannon in gh-103082@footnote{https://github.com/python/cpython/issues/103082}.)

@item 
Add the @ref{70a,,LOAD_FAST_AND_CLEAR} instruction as part of the
implementation of 
@geindex Python Enhancement Proposals; PEP 709
PEP 709@footnote{https://peps.python.org/pep-0709/}. (Contributed by Carl Meyer in gh-101441@footnote{https://github.com/python/cpython/issues/101441}.)

@item 
Add the @ref{70b,,LOAD_FAST_CHECK} instruction.
(Contributed by Dennis Sweeney in gh-93143@footnote{https://github.com/python/cpython/issues/93143}.)

@item 
Add the @ref{70c,,LOAD_FROM_DICT_OR_DEREF}, @ref{70d,,LOAD_FROM_DICT_OR_GLOBALS},
and @ref{70e,,LOAD_LOCALS} opcodes as part of the implementation of 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}.
Remove the @code{LOAD_CLASSDEREF} opcode, which can be replaced with
@ref{70e,,LOAD_LOCALS} plus @ref{70c,,LOAD_FROM_DICT_OR_DEREF}. (Contributed
by Jelle Zijlstra in gh-103764@footnote{https://github.com/python/cpython/issues/103764}.)

@item 
Add the @ref{702,,LOAD_SUPER_ATTR} instruction. (Contributed by Carl Meyer and
Vladimir Matveev in gh-103497@footnote{https://github.com/python/cpython/issues/103497}.)

@item 
Add the @code{RETURN_CONST} instruction. (Contributed by Wenyang Wang in gh-101632@footnote{https://github.com/python/cpython/issues/101632}.)
@end itemize

@node Demos and Tools,非推奨<2>,CPython バイトコードの変更<2>,What's New In Python 3 12
@anchor{whatsnew/3 12 demos-and-tools}@anchor{70f}
@subsection Demos and Tools



@itemize *

@item 
Remove the @code{Tools/demo/} directory which contained old demo scripts. A copy
can be found in the old-demos project@footnote{https://github.com/gvanrossum/old-demos}.
(Contributed by Victor Stinner in gh-97681@footnote{https://github.com/python/cpython/issues/97681}.)

@item 
Remove outdated example scripts of the @code{Tools/scripts/} directory.
A copy can be found in the old-demos project@footnote{https://github.com/gvanrossum/old-demos}.
(Contributed by Victor Stinner in gh-97669@footnote{https://github.com/python/cpython/issues/97669}.)
@end itemize

@node 非推奨<2>,削除<2>,Demos and Tools,What's New In Python 3 12
@anchor{whatsnew/3 12 deprecated}@anchor{710}
@subsection 非推奨



@itemize *

@item 
@ref{7,,argparse}: The `type', `choices', and `metavar' parameters
of @code{argparse.BooleanOptionalAction} are deprecated
and will be removed in 3.14.
(Contributed by Nikita Sobolev in gh-92248@footnote{https://github.com/python/cpython/issues/92248}.)

@item 
@ref{9,,ast}: The following @ref{9,,ast} features have been deprecated in documentation since
Python 3.8, now cause a @ref{1a3,,DeprecationWarning} to be emitted at runtime
when they are accessed or used, and will be removed in Python 3.14:


@itemize *

@item 
@code{ast.Num}

@item 
@code{ast.Str}

@item 
@code{ast.Bytes}

@item 
@code{ast.NameConstant}

@item 
@code{ast.Ellipsis}
@end itemize

Use @ref{2ef,,ast.Constant} instead.
(Contributed by Serhiy Storchaka in gh-90953@footnote{https://github.com/python/cpython/issues/90953}.)

@item 
@ref{b,,asyncio}:


@itemize *

@item 
The child watcher classes @code{asyncio.MultiLoopChildWatcher},
@code{asyncio.FastChildWatcher}, @code{asyncio.AbstractChildWatcher}
and @code{asyncio.SafeChildWatcher} are deprecated and
will be removed in Python 3.14.
(Contributed by Kumar Aditya in gh-94597@footnote{https://github.com/python/cpython/issues/94597}.)

@item 
@code{asyncio.set_child_watcher()}, @code{asyncio.get_child_watcher()},
@code{asyncio.AbstractEventLoopPolicy.set_child_watcher()} and
@code{asyncio.AbstractEventLoopPolicy.get_child_watcher()} are deprecated
and will be removed in Python 3.14.
(Contributed by Kumar Aditya in gh-94597@footnote{https://github.com/python/cpython/issues/94597}.)

@item 
The @ref{2f2,,get_event_loop()} method of the
default event loop policy now emits a @ref{1a3,,DeprecationWarning} if there
is no current event loop set and it decides to create one.
(Contributed by Serhiy Storchaka and Guido van Rossum in gh-100160@footnote{https://github.com/python/cpython/issues/100160}.)
@end itemize

@item 
@ref{15,,calendar}: @code{calendar.January} and @code{calendar.February} constants are deprecated and
replaced by @ref{34e,,calendar.JANUARY} and @ref{34f,,calendar.FEBRUARY}.
(Contributed by Prince Roshan in gh-103636@footnote{https://github.com/python/cpython/issues/103636}.)

@item 
@ref{1f,,collections.abc}: Deprecated @ref{342,,collections.abc.ByteString}.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj} implements
the @ref{260,,buffer protocol} at runtime. For use in type
annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview} were
also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)

@item 
@ref{34,,datetime}: @ref{4e2,,datetime.datetime}'s @ref{351,,utcnow()} and
@ref{352,,utcfromtimestamp()} are deprecated and will be
removed in a future version. Instead, use timezone-aware objects to represent
datetimes in UTC: respectively, call @ref{711,,now()} and
@ref{712,,fromtimestamp()}  with the `tz' parameter set to
@ref{713,,datetime.UTC}.
(Contributed by Paul Ganssle in gh-103857@footnote{https://github.com/python/cpython/issues/103857}.)

@item 
@ref{3f,,email}: Deprecate the `isdst' parameter in @ref{2f7,,email.utils.localtime()}.
(Contributed by Alan Williams in gh-72346@footnote{https://github.com/python/cpython/issues/72346}.)

@item 
@ref{7c,,importlib.abc}: Deprecated the following classes, scheduled for removal in
Python 3.14:


@itemize *

@item 
@code{importlib.abc.ResourceReader}

@item 
@code{importlib.abc.Traversable}

@item 
@code{importlib.abc.TraversableResources}
@end itemize

Use @ref{80,,importlib.resources.abc} classes instead:


@itemize *

@item 
@ref{2fa,,importlib.resources.abc.Traversable}

@item 
@ref{2f9,,importlib.resources.abc.TraversableResources}
@end itemize

(Contributed by Jason R. Coombs and Hugo van Kemenade in gh-93963@footnote{https://github.com/python/cpython/issues/93963}.)

@item 
@ref{85,,itertools}: Deprecate the support for copy, deepcopy, and pickle operations,
which is undocumented, inefficient, historically buggy, and inconsistent.
This will be removed in 3.14 for a significant reduction in code
volume and maintenance burden.
(Contributed by Raymond Hettinger in gh-101588@footnote{https://github.com/python/cpython/issues/101588}.)

@item 
@ref{98,,multiprocessing}: In Python 3.14, the default @ref{98,,multiprocessing}
start method will change to a safer one on Linux, BSDs,
and other non-macOS POSIX platforms where @code{'fork'} is currently
the default (gh-84559@footnote{https://github.com/python/cpython/issues/84559}). Adding a runtime warning about this was deemed too
disruptive as the majority of code is not expected to care. Use the
@ref{24a,,get_context()} or
@ref{24b,,set_start_method()} APIs to explicitly specify when
your code `requires' @code{'fork'}.  See @ref{1d5,,contexts and start methods}.

@item 
@ref{ae,,pkgutil}: @code{pkgutil.find_loader()} and @code{pkgutil.get_loader()}
are deprecated and will be removed in Python 3.14;
use @ref{5af,,importlib.util.find_spec()} instead.
(Contributed by Nikita Sobolev in gh-97850@footnote{https://github.com/python/cpython/issues/97850}.)

@item 
@ref{b6,,pty}: The module has two undocumented @code{master_open()} and @code{slave_open()}
functions that have been deprecated since Python 2 but only gained a
proper @ref{1a3,,DeprecationWarning} in 3.12. Remove them in 3.14.
(Contributed by Soumendra Ganguly and Gregory P. Smith in gh-85984@footnote{https://github.com/python/cpython/issues/85984}.)

@item 
@ref{a5,,os}:


@itemize *

@item 
The @code{st_ctime} fields return by @ref{26d,,os.stat()} and @ref{6c8,,os.lstat()} on
Windows are deprecated. In a future release, they will contain the last
metadata change time, consistent with other platforms. For now, they still
contain the creation time, which is also available in the new @code{st_birthtime}
field. (Contributed by Steve Dower in gh-99726@footnote{https://github.com/python/cpython/issues/99726}.)

@item 
On POSIX platforms, @ref{4b5,,os.fork()} can now raise a
@ref{1a3,,DeprecationWarning} when it can detect being called from a
multithreaded process. There has always been a fundamental incompatibility
with the POSIX platform when doing so. Even if such code `appeared' to work.
We added the warning to raise awareness as issues encountered by code doing
this are becoming more frequent. See the @ref{4b5,,os.fork()} documentation for
more details along with this discussion on fork being incompatible with threads@footnote{https://discuss.python.org/t/concerns-regarding-deprecation-of-fork-with-alive-threads/33555} for `why' we're now surfacing this
longstanding platform compatibility problem to developers.
@end itemize

When this warning appears due to usage of @ref{98,,multiprocessing} or
@ref{24,,concurrent.futures} the fix is to use a different
@ref{98,,multiprocessing} start method such as @code{"spawn"} or @code{"forkserver"}.

@item 
@ref{ca,,shutil}: The `onerror' argument of @ref{356,,shutil.rmtree()} is deprecated;
use `onexc' instead. (Contributed by Irit Katriel in gh-102828@footnote{https://github.com/python/cpython/issues/102828}.)

@item 
@ref{d4,,sqlite3}:


@itemize *

@item 
@ref{714,,default adapters and converters} are now deprecated.
Instead, use the @ref{715,,適合関数と変換関数のレシピ集}
and tailor them to your needs.
(Contributed by Erlend E. Aasland in gh-90016@footnote{https://github.com/python/cpython/issues/90016}.)

@item 
In @ref{5b0,,execute()}, @ref{1a3,,DeprecationWarning} is now emitted
when @ref{5b2,,named placeholders} are used together with
parameters supplied as a @ref{716,,sequence} instead of as a @ref{183,,dict}.
Starting from Python 3.14, using named placeholders with parameters supplied
as a sequence will raise a @ref{305,,ProgrammingError}.
(Contributed by Erlend E. Aasland in gh-101698@footnote{https://github.com/python/cpython/issues/101698}.)
@end itemize

@item 
@ref{df,,sys}: The @ref{6e6,,sys.last_type}, @ref{6e7,,sys.last_value} and @ref{6e8,,sys.last_traceback}
fields are deprecated. Use @ref{6e5,,sys.last_exc} instead.
(Contributed by Irit Katriel in gh-102778@footnote{https://github.com/python/cpython/issues/102778}.)

@item 
@ref{e4,,tarfile}: Extracting tar archives without specifying `filter' is deprecated until
Python 3.14, when @code{'data'} filter will become the default.
See @ref{697,,Extraction filters} for details.

@item 
@ref{10a,,typing}:


@itemize *

@item 
@ref{717,,typing.Hashable} and @ref{718,,typing.Sized}, aliases for
@ref{719,,collections.abc.Hashable} and @ref{71a,,collections.abc.Sized} respectively, are
deprecated. (gh-94309@footnote{https://github.com/python/cpython/issues/94309}.)

@item 
@ref{345,,typing.ByteString}, deprecated since Python 3.9, now causes a
@ref{1a3,,DeprecationWarning} to be emitted when it is used.
(Contributed by Alex Waygood in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize

@item 
@ref{12b,,xml.etree.ElementTree}: The module now emits @ref{1a3,,DeprecationWarning}
when testing the truth value of an @ref{363,,xml.etree.ElementTree.Element}.
Before, the Python implementation emitted @ref{659,,FutureWarning}, and the C
implementation emitted nothing.
(Contributed by Jacob Walls in gh-83122@footnote{https://github.com/python/cpython/issues/83122}.)

@item 
The 3-arg signatures (type, value, traceback) of @ref{71b,,coroutine throw()}, @ref{71c,,generator throw()} and
@ref{71d,,async generator throw()} are deprecated and
may be removed in a future version of Python. Use the single-arg versions
of these functions instead. (Contributed by Ofey Chan in gh-89874@footnote{https://github.com/python/cpython/issues/89874}.)

@item 
@ref{1a3,,DeprecationWarning} is now raised when @ref{323,,__package__} on a
module differs from
@ref{324,,__spec__.parent} (previously
it was @ref{71e,,ImportWarning}).
(Contributed by Brett Cannon in gh-65961@footnote{https://github.com/python/cpython/issues/65961}.)

@item 
Setting @ref{323,,__package__} or @ref{321,,__cached__} on a
module is deprecated, and will cease to be set or taken into consideration by
the import system in Python 3.14. (Contributed by Brett Cannon in gh-65961@footnote{https://github.com/python/cpython/issues/65961}.)

@item 
The bitwise inversion operator (@code{~}) on bool is deprecated. It will throw an
error in Python 3.16. Use @code{not} for logical negation of bools instead.
In the rare case that you really need the bitwise inversion of the underlying
@code{int}, convert to int explicitly: @code{~int(x)}. (Contributed by Tim Hoffmann
in gh-103487@footnote{https://github.com/python/cpython/issues/103487}.)

@item 
Accessing @ref{330,,co_lnotab} on code objects was deprecated in
Python 3.10 via 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/},
but it only got a proper @ref{1a3,,DeprecationWarning} in 3.12.
May be removed in 3.15.
(Contributed by Nikita Sobolev in gh-101866@footnote{https://github.com/python/cpython/issues/101866}.)
@end itemize

@menu
* Pending removal in Python 3.13: Pending removal in Python 3 13. 
* Pending removal in Python 3.14: Pending removal in Python 3 14<3>. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<5>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<5>. 
* Pending removal in Python 3.17: Pending removal in Python 3 17<3>. 
* Pending removal in future versions: Pending removal in future versions<5>. 

@end menu

@node Pending removal in Python 3 13,Pending removal in Python 3 14<3>,,非推奨<2>
@anchor{whatsnew/3 12 pending-removal-in-python-3-13}@anchor{71f}
@subsubsection Pending removal in Python 3.13


モジュール(
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} を参照):


@itemize *

@item 
@code{aifc}

@item 
@code{audioop}

@item 
@code{cgi}

@item 
@code{cgitb}

@item 
@code{chunk}

@item 
@code{crypt}

@item 
@code{imghdr}

@item 
@code{mailcap}

@item 
@code{msilib}

@item 
@code{nis}

@item 
@code{nntplib}

@item 
@code{ossaudiodev}

@item 
@code{pipes}

@item 
@code{sndhdr}

@item 
@code{spwd}

@item 
@code{sunau}

@item 
@code{telnetlib}

@item 
@code{uu}

@item 
@code{xdrlib}
@end itemize

その他のモジュール:


@itemize *

@item 
@code{lib2to3}, and the @code{2to3} program (gh-84540@footnote{https://github.com/python/cpython/issues/84540})
@end itemize

API


@itemize *

@item 
@code{configparser.LegacyInterpolation} (gh-90765@footnote{https://github.com/python/cpython/issues/90765})

@item 
@code{locale.resetlocale()} (gh-90817@footnote{https://github.com/python/cpython/issues/90817})

@item 
@code{turtle.RawTurtle.settiltangle()} (gh-50096@footnote{https://github.com/python/cpython/issues/50096})

@item 
@code{unittest.findTestCases()} (gh-50096@footnote{https://github.com/python/cpython/issues/50096})

@item 
@code{unittest.getTestCaseNames()} (gh-50096@footnote{https://github.com/python/cpython/issues/50096})

@item 
@code{unittest.makeSuite()} (gh-50096@footnote{https://github.com/python/cpython/issues/50096})

@item 
@code{unittest.TestProgram.usageExit()} (gh-67048@footnote{https://github.com/python/cpython/issues/67048})

@item 
@code{webbrowser.MacOSX} (gh-86421@footnote{https://github.com/python/cpython/issues/86421})

@item 
@ref{48e,,classmethod} descriptor chaining (gh-89519@footnote{https://github.com/python/cpython/issues/89519})
@end itemize

@node Pending removal in Python 3 14<3>,Pending removal in Python 3 15<5>,Pending removal in Python 3 13,非推奨<2>
@anchor{whatsnew/3 12 pending-removal-in-python-3-14}@anchor{720}
@subsubsection Pending removal in Python 3.14



@itemize *

@item 
@ref{7,,argparse}: The `type', `choices', and `metavar' parameters
of @code{argparse.BooleanOptionalAction} are deprecated
and will be removed in 3.14.
(Contributed by Nikita Sobolev in gh-92248@footnote{https://github.com/python/cpython/issues/92248}.)

@item 
@ref{9,,ast}: The following features have been deprecated in documentation
since Python 3.8, now cause a @ref{1a3,,DeprecationWarning} to be emitted at
runtime when they are accessed or used, and will be removed in Python 3.14:


@itemize *

@item 
@code{ast.Num}

@item 
@code{ast.Str}

@item 
@code{ast.Bytes}

@item 
@code{ast.NameConstant}

@item 
@code{ast.Ellipsis}
@end itemize

Use @ref{2ef,,ast.Constant} instead.
(Contributed by Serhiy Storchaka in gh-90953@footnote{https://github.com/python/cpython/issues/90953}.)

@item 
@ref{b,,asyncio}:


@itemize *

@item 
The child watcher classes @code{asyncio.MultiLoopChildWatcher},
@code{asyncio.FastChildWatcher}, @code{asyncio.AbstractChildWatcher}
and @code{asyncio.SafeChildWatcher} are deprecated and
will be removed in Python 3.14.
(Contributed by Kumar Aditya in gh-94597@footnote{https://github.com/python/cpython/issues/94597}.)

@item 
@code{asyncio.set_child_watcher()}, @code{asyncio.get_child_watcher()},
@code{asyncio.AbstractEventLoopPolicy.set_child_watcher()} and
@code{asyncio.AbstractEventLoopPolicy.get_child_watcher()} are deprecated
and will be removed in Python 3.14.
(Contributed by Kumar Aditya in gh-94597@footnote{https://github.com/python/cpython/issues/94597}.)

@item 
The @ref{2f2,,get_event_loop()} method of the
default event loop policy now emits a @ref{1a3,,DeprecationWarning} if there
is no current event loop set and it decides to create one.
(Contributed by Serhiy Storchaka and Guido van Rossum in gh-100160@footnote{https://github.com/python/cpython/issues/100160}.)
@end itemize

@item 
@ref{3f,,email}: Deprecated the `isdst' parameter in @ref{2f7,,email.utils.localtime()}.
(Contributed by Alan Williams in gh-72346@footnote{https://github.com/python/cpython/issues/72346}.)

@item 
@ref{7c,,importlib.abc} deprecated classes:


@itemize *

@item 
@code{importlib.abc.ResourceReader}

@item 
@code{importlib.abc.Traversable}

@item 
@code{importlib.abc.TraversableResources}
@end itemize

Use @ref{80,,importlib.resources.abc} classes instead:


@itemize *

@item 
@ref{2fa,,importlib.resources.abc.Traversable}

@item 
@ref{2f9,,importlib.resources.abc.TraversableResources}
@end itemize

(Contributed by Jason R. Coombs and Hugo van Kemenade in gh-93963@footnote{https://github.com/python/cpython/issues/93963}.)

@item 
@ref{85,,itertools} had undocumented, inefficient, historically buggy,
and inconsistent support for copy, deepcopy, and pickle operations.
This will be removed in 3.14 for a significant reduction in code
volume and maintenance burden.
(Contributed by Raymond Hettinger in gh-101588@footnote{https://github.com/python/cpython/issues/101588}.)

@item 
@ref{98,,multiprocessing}: The default start method will change to a safer one on
Linux, BSDs, and other non-macOS POSIX platforms where @code{'fork'} is currently
the default (gh-84559@footnote{https://github.com/python/cpython/issues/84559}). Adding a runtime warning about this was deemed too
disruptive as the majority of code is not expected to care. Use the
@ref{24a,,get_context()} or
@ref{24b,,set_start_method()} APIs to explicitly specify when
your code `requires' @code{'fork'}.  See @ref{1d5,,コンテキストと開始方式}.

@item 
@ref{a8,,pathlib}: @ref{2fe,,is_relative_to()} and
@ref{2fd,,relative_to()}: passing additional arguments is
deprecated.

@item 
@ref{ae,,pkgutil}: @code{pkgutil.find_loader()} and @code{pkgutil.get_loader()}
now raise @ref{1a3,,DeprecationWarning};
use @ref{5af,,importlib.util.find_spec()} instead.
(Contributed by Nikita Sobolev in gh-97850@footnote{https://github.com/python/cpython/issues/97850}.)

@item 
@ref{b6,,pty}:


@itemize *

@item 
@code{master_open()}: use @ref{301,,pty.openpty()}.

@item 
@code{slave_open()}: use @ref{301,,pty.openpty()}.
@end itemize

@item 
@ref{d4,,sqlite3}:


@itemize *

@item 
@code{version} and @code{version_info}.

@item 
@ref{5b0,,execute()} and @ref{5b1,,executemany()}
if @ref{5b2,,named placeholders} are used and
`parameters' is a sequence instead of a @ref{183,,dict}.
@end itemize

@item 
@ref{10e,,urllib}:
@code{urllib.parse.Quoter} is deprecated: it was not intended to be a
public API.
(Contributed by Gregory P. Smith in gh-88168@footnote{https://github.com/python/cpython/issues/88168}.)
@end itemize

@node Pending removal in Python 3 15<5>,Pending removal in Python 3 16<5>,Pending removal in Python 3 14<3>,非推奨<2>
@anchor{whatsnew/3 12 pending-removal-in-python-3-15}@anchor{721}
@subsubsection Pending removal in Python 3.15



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{321,,__cached__} on a module while
failing to set @ref{322,,__spec__.cached}
is deprecated. In Python 3.15, @code{__cached__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})

@item 
Setting @ref{323,,__package__} on a module while
failing to set @ref{324,,__spec__.parent}
is deprecated. In Python 3.15, @code{__package__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})
@end itemize

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
The undocumented @code{ctypes.SetPointerType()} function
has been deprecated since Python 3.13.
@end itemize

@item 
@ref{76,,http.server}:


@itemize *

@item 
The obsolete and rarely used @ref{325,,CGIHTTPRequestHandler}
has been deprecated since Python 3.13.
No direct replacement exists.
`Anything' is better than CGI to interface
a web server with a request handler.

@item 
The @code{--cgi} flag to the @code{python -m http.server}
command-line interface has been deprecated since Python 3.13.
@end itemize

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@code{load_module()} method: use @code{exec_module()} instead.
@end itemize

@item 
@ref{8a,,locale}:


@itemize *

@item 
The @ref{326,,getdefaultlocale()} function
has been deprecated since Python 3.11.
Its removal was originally planned for Python 3.13 (gh-90817@footnote{https://github.com/python/cpython/issues/90817}),
but has been postponed to Python 3.15.
Use @ref{327,,getlocale()}, @ref{328,,setlocale()},
and @ref{329,,getencoding()} instead.
(Contributed by Hugo van Kemenade in gh-111187@footnote{https://github.com/python/cpython/issues/111187}.)
@end itemize

@item 
@ref{a8,,pathlib}:


@itemize *

@item 
@ref{32a,,PurePath.is_reserved()}
has been deprecated since Python 3.13.
Use @ref{32b,,os.path.isreserved()} to detect reserved paths on Windows.
@end itemize

@item 
@ref{af,,platform}:


@itemize *

@item 
@ref{32c,,java_ver()} has been deprecated since Python 3.13.
This function is only useful for Jython support, has a confusing API,
and is largely untested.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The `check_home' argument of @ref{32d,,sysconfig.is_python_build()} has been
deprecated since Python 3.12.
@end itemize

@item 
@ref{f3,,threading}:


@itemize *

@item 
@ref{32e,,RLock()} will take no arguments in Python 3.15.
Passing any arguments has been deprecated since Python 3.14,
as the Python version does not permit any arguments,
but the C version allows any number of positional or keyword arguments,
ignoring every argument.
@end itemize

@item 
@ref{109,,types}:


@itemize *

@item 
@ref{32f,,types.CodeType}: Accessing @ref{330,,co_lnotab} was
deprecated in 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/}
since 3.10 and was planned to be removed in 3.12,
but it only got a proper @ref{1a3,,DeprecationWarning} in 3.12.
May be removed in 3.15.
(Contributed by Nikita Sobolev in gh-101866@footnote{https://github.com/python/cpython/issues/101866}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize *

@item 
The undocumented keyword argument syntax for creating
@ref{331,,NamedTuple} classes
(for example, @code{Point = NamedTuple("Point", x=int, y=int)})
has been deprecated since Python 3.13.
Use the class-based syntax or the functional syntax instead.

@item 
When using the functional syntax of @ref{332,,TypedDict}s, failing
to pass a value to the `fields' parameter (@code{TD = TypedDict("TD")}) or
passing @code{None} (@code{TD = TypedDict("TD", None)}) has been deprecated
since Python 3.13.
Use @code{class TD(TypedDict): pass} or @code{TD = TypedDict("TD", @{@})}
to create a TypedDict with zero field.

@item 
The @ref{333,,typing.no_type_check_decorator()} decorator function
has been deprecated since Python 3.13.
After eight years in the @ref{10a,,typing} module,
it has yet to be supported by any major type checker.
@end itemize

@item 
@ref{119,,wave}:


@itemize *

@item 
The @ref{334,,getmark()}, @code{setmark()},
and @ref{335,,getmarkers()} methods of
the @ref{336,,Wave_read} and @ref{337,,Wave_write} classes
have been deprecated since Python 3.13.
@end itemize

@item 
@ref{138,,zipimport}:


@itemize *

@item 
@ref{338,,load_module()} has been deprecated since
Python 3.10. Use @ref{339,,exec_module()} instead.
(Contributed by Jiahao Li in gh-125746@footnote{https://github.com/python/cpython/issues/125746}.)
@end itemize
@end itemize

@node Pending removal in Python 3 16<5>,Pending removal in Python 3 17<3>,Pending removal in Python 3 15<5>,非推奨<2>
@anchor{whatsnew/3 12 pending-removal-in-python-3-16}@anchor{722}
@subsubsection Pending removal in Python 3.16



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{33b,,__loader__} on a module while
failing to set @ref{33c,,__spec__.loader}
is deprecated. In Python 3.16, @code{__loader__} will cease to be set or
taken into consideration by the import system or the standard library.
@end itemize

@item 
@ref{8,,array}:


@itemize *

@item 
The @code{'u'} format code (@code{wchar_t})
has been deprecated in documentation since Python 3.3
and at runtime since Python 3.13.
Use the @code{'w'} format code (@ref{33d,,Py_UCS4})
for Unicode characters instead.
@end itemize

@item 
@ref{b,,asyncio}:


@itemize *

@item 
@code{asyncio.iscoroutinefunction()} is deprecated
and will be removed in Python 3.16;
use @ref{30d,,inspect.iscoroutinefunction()} instead.
(Contributed by Jiahao Li and Kumar Aditya in gh-122875@footnote{https://github.com/python/cpython/issues/122875}.)

@item 
@ref{b,,asyncio} policy system is deprecated and will be removed in Python 3.16.
In particular, the following classes and functions are deprecated:


@itemize *

@item 
@ref{30e,,asyncio.AbstractEventLoopPolicy}

@item 
@ref{30f,,asyncio.DefaultEventLoopPolicy}

@item 
@ref{310,,asyncio.WindowsSelectorEventLoopPolicy}

@item 
@ref{311,,asyncio.WindowsProactorEventLoopPolicy}

@item 
@ref{312,,asyncio.get_event_loop_policy()}

@item 
@ref{313,,asyncio.set_event_loop_policy()}
@end itemize

Users should use @ref{2f3,,asyncio.run()} or @ref{2f5,,asyncio.Runner} with
`loop_factory' to use the desired event loop implementation.

For example, to use @ref{314,,asyncio.SelectorEventLoop} on Windows:

@example
import asyncio

async def main():
    ...

asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
@end example

(Contributed by Kumar Aditya in gh-127949@footnote{https://github.com/python/cpython/issues/127949}.)
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Bitwise inversion on boolean types, @code{~True} or @code{~False}
has been deprecated since Python 3.12,
as it produces surprising and unintuitive results (@code{-2} and @code{-1}).
Use @code{not x} instead for the logical negation of a Boolean.
In the rare case that you need the bitwise inversion of
the underlying integer, convert to @code{int} explicitly (@code{~int(x)}).
@end itemize

@item 
@ref{63,,functools}:


@itemize *

@item 
Calling the Python implementation of @ref{21a,,functools.reduce()} with `function'
or `sequence' as keyword arguments has been deprecated since Python 3.14.
@end itemize

@item 
@ref{8b,,logging}:

Support for custom logging handlers with the `strm' argument is deprecated
and scheduled for removal in Python 3.16. Define handlers with the `stream'
argument instead. (Contributed by Mariusz Felisiak in gh-115032@footnote{https://github.com/python/cpython/issues/115032}.)

@item 
@ref{93,,mimetypes}:


@itemize *

@item 
Valid extensions start with a '.' or are empty for
@ref{319,,mimetypes.MimeTypes.add_type()}.
Undotted extensions are deprecated and will
raise a @ref{2ec,,ValueError} in Python 3.16.
(Contributed by Hugo van Kemenade in gh-75223@footnote{https://github.com/python/cpython/issues/75223}.)
@end itemize

@item 
@ref{ca,,shutil}:


@itemize *

@item 
The @code{ExecError} exception
has been deprecated since Python 3.14.
It has not been used by any function in @code{shutil} since Python 3.4,
and is now an alias of @ref{244,,RuntimeError}.
@end itemize

@item 
@ref{de,,symtable}:


@itemize *

@item 
The @ref{31d,,Class.get_methods} method
has been deprecated since Python 3.14.
@end itemize

@item 
@ref{df,,sys}:


@itemize *

@item 
The @ref{33e,,_enablelegacywindowsfsencoding()} function
has been deprecated since Python 3.13.
Use the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} environment variable instead.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The @code{sysconfig.expand_makefile_vars()} function
has been deprecated since Python 3.14.
Use the @code{vars} argument of @ref{340,,sysconfig.get_paths()} instead.
@end itemize

@item 
@ref{e4,,tarfile}:


@itemize *

@item 
The undocumented and unused @code{TarFile.tarfile} attribute
has been deprecated since Python 3.13.
@end itemize
@end itemize

@node Pending removal in Python 3 17<3>,Pending removal in future versions<5>,Pending removal in Python 3 16<5>,非推奨<2>
@anchor{whatsnew/3 12 pending-removal-in-python-3-17}@anchor{723}
@subsubsection Pending removal in Python 3.17



@itemize *

@item 
@ref{1f,,collections.abc}:


@itemize -

@item 
@ref{342,,collections.abc.ByteString} is scheduled for removal in Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize -

@item 
Before Python 3.14, old-style unions were implemented using the private class
@code{typing._UnionGenericAlias}. This class is no longer needed for the implementation,
but it has been retained for backward compatibility, with removal scheduled for Python
3.17. Users should use documented introspection helpers like @ref{2ab,,typing.get_origin()}
and @ref{2ac,,typing.get_args()} instead of relying on private implementation details.

@item 
@ref{345,,typing.ByteString}, deprecated since Python 3.9, is scheduled for removal in
Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize
@end itemize

@node Pending removal in future versions<5>,,Pending removal in Python 3 17<3>,非推奨<2>
@anchor{whatsnew/3 12 pending-removal-in-future-versions}@anchor{724}
@subsubsection Pending removal in future versions


The following APIs will be removed in the future,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{7,,argparse}:


@itemize *

@item 
Nesting argument groups and nesting mutually exclusive
groups are deprecated.

@item 
Passing the undocumented keyword argument `prefix_chars' to
@ref{2eb,,add_argument_group()} is now
deprecated.

@item 
The @ref{30c,,argparse.FileType} type converter is deprecated.
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Generators: @code{throw(type, exc, tb)} and @code{athrow(type, exc, tb)}
signature is deprecated: use @code{throw(exc)} and @code{athrow(exc)} instead,
the single argument signature.

@item 
Currently Python accepts numeric literals immediately followed by keywords,
for example @code{0in x}, @code{1or x}, @code{0if 1else 2}.  It allows confusing and
ambiguous expressions like @code{[0x1for x in y]} (which can be interpreted as
@code{[0x1 for x in y]} or @code{[0x1f or x in y]}).  A syntax warning is raised
if the numeric literal is immediately followed by one of keywords
@ref{349,,and}, @ref{17c,,else}, @ref{34a,,for}, @ref{181,,if},
@ref{34b,,in}, @ref{34c,,is} and @ref{34d,,or}.  In a future release it
will be changed to a syntax error. (gh-87999@footnote{https://github.com/python/cpython/issues/87999})

@item 
Support for @code{__index__()} and @code{__int__()} method returning non-int type:
these methods will be required to return an instance of a strict subclass of
@ref{19b,,int}.

@item 
Support for @code{__float__()} method returning a strict subclass of
@ref{196,,float}: these methods will be required to return an instance of
@ref{196,,float}.

@item 
Support for @code{__complex__()} method returning a strict subclass of
@ref{197,,complex}: these methods will be required to return an instance of
@ref{197,,complex}.

@item 
Passing a complex number as the `real' or `imag' argument in the
@ref{197,,complex()} constructor is now deprecated; it should only be passed
as a single positional argument.
(Contributed by Serhiy Storchaka in gh-109218@footnote{https://github.com/python/cpython/issues/109218}.)
@end itemize

@item 
@ref{15,,calendar}: @code{calendar.January} and @code{calendar.February} constants are
deprecated and replaced by @ref{34e,,calendar.JANUARY} and
@ref{34f,,calendar.FEBRUARY}.
(Contributed by Prince Roshan in gh-103636@footnote{https://github.com/python/cpython/issues/103636}.)

@item 
@ref{1c,,codecs}: use @ref{316,,open()} instead of @ref{315,,codecs.open()}. (gh-133038@footnote{https://github.com/python/cpython/issues/133038})

@item 
@ref{330,,codeobject.co_lnotab}: use the @ref{350,,codeobject.co_lines()} method
instead.

@item 
@ref{34,,datetime}:


@itemize *

@item 
@ref{351,,utcnow()}:
use @code{datetime.datetime.now(tz=datetime.UTC)}.

@item 
@ref{352,,utcfromtimestamp()}:
use @code{datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)}.
@end itemize

@item 
@ref{67,,gettext}: Plural value must be an integer.

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@ref{353,,cache_from_source()} `debug_override' parameter is
deprecated: use the `optimization' parameter instead.
@end itemize

@item 
@ref{7e,,importlib.metadata}:


@itemize *

@item 
@code{EntryPoints} tuple interface.

@item 
Implicit @code{None} on return values.
@end itemize

@item 
@ref{8b,,logging}: the @code{warn()} method has been deprecated
since Python 3.3, use @ref{354,,warning()} instead.

@item 
@ref{8f,,mailbox}: Use of StringIO input and text mode is deprecated, use
BytesIO and binary mode instead.

@item 
@ref{a5,,os}: Calling @ref{355,,os.register_at_fork()} in multi-threaded process.

@item 
@code{pydoc.ErrorDuringImport}: A tuple value for `exc_info' parameter is
deprecated, use an exception instance.

@item 
@ref{be,,re}: More strict rules are now applied for numerical group references
and group names in regular expressions.  Only sequence of ASCII digits is now
accepted as a numerical reference.  The group name in bytes patterns and
replacement strings can now only contain ASCII letters and digits and
underscore.
(Contributed by Serhiy Storchaka in gh-91760@footnote{https://github.com/python/cpython/issues/91760}.)

@item 
@code{sre_compile}, @code{sre_constants} and @code{sre_parse} modules.

@item 
@ref{ca,,shutil}: @ref{356,,rmtree()}'s `onerror' parameter is deprecated in
Python 3.12; use the `onexc' parameter instead.

@item 
@ref{d5,,ssl} options and protocols:


@itemize *

@item 
@ref{357,,ssl.SSLContext} without protocol argument is deprecated.

@item 
@ref{357,,ssl.SSLContext}: @ref{358,,set_npn_protocols()} and
@code{selected_npn_protocol()} are deprecated: use ALPN
instead.

@item 
@code{ssl.OP_NO_SSL*} options

@item 
@code{ssl.OP_NO_TLS*} options

@item 
@code{ssl.PROTOCOL_SSLv3}

@item 
@code{ssl.PROTOCOL_TLS}

@item 
@code{ssl.PROTOCOL_TLSv1}

@item 
@code{ssl.PROTOCOL_TLSv1_1}

@item 
@code{ssl.PROTOCOL_TLSv1_2}

@item 
@code{ssl.TLSVersion.SSLv3}

@item 
@code{ssl.TLSVersion.TLSv1}

@item 
@code{ssl.TLSVersion.TLSv1_1}
@end itemize

@item 
@ref{f3,,threading} methods:


@itemize *

@item 
@code{threading.Condition.notifyAll()}: use @ref{359,,notify_all()}.

@item 
@code{threading.Event.isSet()}: use @ref{35a,,is_set()}.

@item 
@code{threading.Thread.isDaemon()}, @ref{35b,,threading.Thread.setDaemon()}:
use @ref{35c,,threading.Thread.daemon} attribute.

@item 
@code{threading.Thread.getName()}, @ref{35d,,threading.Thread.setName()}:
use @ref{2a0,,threading.Thread.name} attribute.

@item 
@code{threading.currentThread()}: use @ref{35e,,threading.current_thread()}.

@item 
@code{threading.activeCount()}: use @ref{35f,,threading.active_count()}.
@end itemize

@item 
@ref{360,,typing.Text} (gh-92332@footnote{https://github.com/python/cpython/issues/92332}).

@item 
The internal class @code{typing._UnionGenericAlias} is no longer used to implement
@ref{2a8,,typing.Union}. To preserve compatibility with users using this private
class, a compatibility shim will be provided until at least Python 3.17. (Contributed by
Jelle Zijlstra in gh-105499@footnote{https://github.com/python/cpython/issues/105499}.)

@item 
@ref{361,,unittest.IsolatedAsyncioTestCase}: it is deprecated to return a value
that is not @code{None} from a test case.

@item 
@ref{110,,urllib.parse} deprecated functions: @ref{362,,urlparse()} instead


@itemize *

@item 
@code{splitattr()}

@item 
@code{splithost()}

@item 
@code{splitnport()}

@item 
@code{splitpasswd()}

@item 
@code{splitport()}

@item 
@code{splitquery()}

@item 
@code{splittag()}

@item 
@code{splittype()}

@item 
@code{splituser()}

@item 
@code{splitvalue()}

@item 
@code{to_bytes()}
@end itemize

@item 
@ref{11e,,wsgiref}: @code{SimpleHandler.stdout.write()} should not do partial
writes.

@item 
@ref{12b,,xml.etree.ElementTree}: Testing the truth value of an
@ref{363,,Element} is deprecated. In a future release it
will always return @code{True}. Prefer explicit @code{len(elem)} or
@code{elem is not None} tests instead.

@item 
@ref{292,,sys._clear_type_cache()} is deprecated:
use @ref{364,,sys._clear_internal_caches()} instead.
@end itemize

@node 削除<2>,Python 3 12 への移植,非推奨<2>,What's New In Python 3 12
@anchor{whatsnew/3 12 removed}@anchor{725}@anchor{whatsnew/3 12 whatsnew312-removed}@anchor{726}
@subsection 削除


@menu
* asynchat and asyncore:: 
* configparser: configparser<4>. 
* distutils:: 
* ensurepip:: 
* enum: enum<2>. 
* ftplib:: 
* gzip:: 
* hashlib:: 
* importlib: importlib<2>. 
* imp:: 
* io: io<4>. 
* locale: locale<2>. 
* smtpd:: 
* sqlite3: sqlite3<4>. 
* ssl: ssl<3>. 
* unittest: unittest<4>. 
* webbrowser: webbrowser<3>. 
* xml.etree.ElementTree: xml etree ElementTree. 
* zipimport: zipimport<2>. 
* その他:: 

@end menu

@node asynchat and asyncore,configparser<4>,,削除<2>
@anchor{whatsnew/3 12 asynchat-and-asyncore}@anchor{727}
@subsubsection asynchat and asyncore



@itemize *

@item 
These two modules have been removed
according to the schedule in 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/},
having been deprecated in Python 3.6.
Use @ref{b,,asyncio} instead.
(Contributed by Nikita Sobolev in gh-96580@footnote{https://github.com/python/cpython/issues/96580}.)
@end itemize

@node configparser<4>,distutils,asynchat and asyncore,削除<2>
@anchor{whatsnew/3 12 configparser}@anchor{728}
@subsubsection configparser



@itemize *

@item 
Several names deprecated in the @ref{26,,configparser} way back in 3.2 have
been removed per gh-89336@footnote{https://github.com/python/cpython/issues/89336}:


@itemize *

@item 
@ref{729,,configparser.ParsingError} no longer has a @code{filename} attribute
or argument. Use the @code{source} attribute and argument instead.

@item 
@ref{26,,configparser} no longer has a @code{SafeConfigParser} class. Use the
shorter @ref{4de,,ConfigParser} name instead.

@item 
@ref{4de,,configparser.ConfigParser} no longer has a @code{readfp} method.
Use @ref{72a,,read_file()} instead.
@end itemize
@end itemize

@node distutils,ensurepip,configparser<4>,削除<2>
@anchor{whatsnew/3 12 distutils}@anchor{72b}@anchor{whatsnew/3 12 whatsnew312-removed-distutils}@anchor{72c}
@subsubsection distutils



@itemize *

@item 
Remove the @code{distutils} package. It was deprecated in Python 3.10 by
@geindex Python Enhancement Proposals; PEP 632
PEP 632@footnote{https://peps.python.org/pep-0632/} "Deprecate distutils module". For projects still using
@code{distutils} and cannot be updated to something else, the @code{setuptools}
project can be installed: it still provides @code{distutils}.
(Contributed by Victor Stinner in gh-92584@footnote{https://github.com/python/cpython/issues/92584}.)
@end itemize

@node ensurepip,enum<2>,distutils,削除<2>
@anchor{whatsnew/3 12 ensurepip}@anchor{72d}
@subsubsection ensurepip



@itemize *

@item 
Remove the bundled setuptools wheel from @ref{59,,ensurepip},
and stop installing setuptools in environments created by @ref{117,,venv}.

@code{pip (>= 22.1)} does not require setuptools to be installed in the
environment. @code{setuptools}-based (and @code{distutils}-based) packages
can still be used with @code{pip install}, since pip will provide
@code{setuptools} in the build environment it uses for building a
package.

@code{easy_install}, @code{pkg_resources}, @code{setuptools} and @code{distutils}
are no longer provided by default in environments created with
@code{venv} or bootstrapped with @code{ensurepip}, since they are part of
the @code{setuptools} package. For projects relying on these at runtime,
the @code{setuptools} project should be declared as a dependency and
installed separately (typically, using pip).

(Contributed by Pradyun Gedam in gh-95299@footnote{https://github.com/python/cpython/issues/95299}.)
@end itemize

@node enum<2>,ftplib,ensurepip,削除<2>
@anchor{whatsnew/3 12 enum}@anchor{72e}
@subsubsection enum



@itemize *

@item 
Remove @ref{5a,,enum}'s @code{EnumMeta.__getattr__}, which is no longer needed for
enum attribute access.
(Contributed by Ethan Furman in gh-95083@footnote{https://github.com/python/cpython/issues/95083}.)
@end itemize

@node ftplib,gzip,enum<2>,削除<2>
@anchor{whatsnew/3 12 ftplib}@anchor{72f}
@subsubsection ftplib



@itemize *

@item 
Remove @ref{62,,ftplib}'s @code{FTP_TLS.ssl_version} class attribute: use the
`context' parameter instead.
(Contributed by Victor Stinner in gh-94172@footnote{https://github.com/python/cpython/issues/94172}.)
@end itemize

@node gzip,hashlib,ftplib,削除<2>
@anchor{whatsnew/3 12 gzip}@anchor{730}
@subsubsection gzip



@itemize *

@item 
Remove the @code{filename} attribute of @ref{6b,,gzip}'s @ref{65c,,gzip.GzipFile},
deprecated since Python 2.6, use the @ref{731,,name} attribute
instead. In write mode, the @code{filename} attribute added @code{'.gz'} file
extension if it was not present.
(Contributed by Victor Stinner in gh-94196@footnote{https://github.com/python/cpython/issues/94196}.)
@end itemize

@node hashlib,importlib<2>,gzip,削除<2>
@anchor{whatsnew/3 12 hashlib}@anchor{732}
@subsubsection hashlib



@itemize *

@item 
Remove the pure Python implementation of @ref{6c,,hashlib}'s
@ref{733,,hashlib.pbkdf2_hmac()}, deprecated in Python 3.10. Python 3.10 and
newer requires OpenSSL 1.1.1 (
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/}): this OpenSSL version provides
a C implementation of @ref{733,,pbkdf2_hmac()} which is faster.
(Contributed by Victor Stinner in gh-94199@footnote{https://github.com/python/cpython/issues/94199}.)
@end itemize

@node importlib<2>,imp,hashlib,削除<2>
@anchor{whatsnew/3 12 importlib}@anchor{734}
@subsubsection importlib



@itemize *

@item 
Many previously deprecated cleanups in @ref{7b,,importlib} have now been
completed:


@itemize *

@item 
References to, and support for @code{module_repr()} has been removed.
(Contributed by Barry Warsaw in gh-97850@footnote{https://github.com/python/cpython/issues/97850}.)

@item 
@code{importlib.util.set_package}, @code{importlib.util.set_loader} and
@code{importlib.util.module_for_loader} have all been removed. (Contributed by
Brett Cannon and Nikita Sobolev in gh-65961@footnote{https://github.com/python/cpython/issues/65961} and gh-97850@footnote{https://github.com/python/cpython/issues/97850}.)

@item 
Support for @code{find_loader()} and @code{find_module()} APIs have been
removed.  (Contributed by Barry Warsaw in gh-98040@footnote{https://github.com/python/cpython/issues/98040}.)

@item 
@code{importlib.abc.Finder}, @code{pkgutil.ImpImporter}, and @code{pkgutil.ImpLoader}
have been removed.  (Contributed by Barry Warsaw in gh-98040@footnote{https://github.com/python/cpython/issues/98040}.)
@end itemize
@end itemize

@node imp,io<4>,importlib<2>,削除<2>
@anchor{whatsnew/3 12 imp}@anchor{735}@anchor{whatsnew/3 12 whatsnew312-removed-imp}@anchor{736}
@subsubsection imp



@itemize *

@item 
The @code{imp} module has been removed.  (Contributed by Barry Warsaw in
gh-98040@footnote{https://github.com/python/cpython/issues/98040}.)

To migrate, consult the following correspondence table:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

imp

@tab

importlib

@item

@code{imp.NullImporter}

@tab

@code{sys.path_importer_cache} に @code{None} を挿入する

@item

@code{imp.cache_from_source()}

@tab

@ref{353,,importlib.util.cache_from_source()}

@item

@code{imp.find_module()}

@tab

@ref{5af,,importlib.util.find_spec()}

@item

@code{imp.get_magic()}

@tab

@ref{737,,importlib.util.MAGIC_NUMBER}

@item

@code{imp.get_suffixes()}

@tab

@ref{738,,importlib.machinery.SOURCE_SUFFIXES}, @ref{739,,importlib.machinery.EXTENSION_SUFFIXES}, and @ref{73a,,importlib.machinery.BYTECODE_SUFFIXES}

@item

@code{imp.get_tag()}

@tab

@ref{73b,,sys.implementation.cache_tag}

@item

@code{imp.load_module()}

@tab

@ref{73c,,importlib.import_module()}

@item

@code{imp.new_module(name)}

@tab

@code{types.ModuleType(name)}

@item

@code{imp.reload()}

@tab

@ref{73d,,importlib.reload()}

@item

@code{imp.source_from_cache()}

@tab

@ref{73e,,importlib.util.source_from_cache()}

@item

@code{imp.load_source()}

@tab

`See below'

@end multitable

@end quotation

Replace @code{imp.load_source()} with:

@example
import importlib.util
import importlib.machinery

def load_source(modname, filename):
    loader = importlib.machinery.SourceFileLoader(modname, filename)
    spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
    module = importlib.util.module_from_spec(spec)
    # The module is always executed and not cached in sys.modules.
    # Uncomment the following line to cache the module.
    # sys.modules[module.__name__] = module
    loader.exec_module(module)
    return module
@end example

@item 
Remove @code{imp} functions and attributes with no replacements:


@itemize *

@item 
ドキュメント化されていない関数:


@itemize *

@item 
@code{imp.init_builtin()}

@item 
@code{imp.load_compiled()}

@item 
@code{imp.load_dynamic()}

@item 
@code{imp.load_package()}
@end itemize

@item 
@code{imp.lock_held()}, @code{imp.acquire_lock()}, @code{imp.release_lock()}:
the locking scheme has changed in Python 3.3 to per-module locks.

@item 
@code{imp.find_module()} constants: @code{SEARCH_ERROR}, @code{PY_SOURCE},
@code{PY_COMPILED}, @code{C_EXTENSION}, @code{PY_RESOURCE}, @code{PKG_DIRECTORY},
@code{C_BUILTIN}, @code{PY_FROZEN}, @code{PY_CODERESOURCE}, @code{IMP_HOOK}.
@end itemize
@end itemize

@node io<4>,locale<2>,imp,削除<2>
@anchor{whatsnew/3 12 io}@anchor{73f}
@subsubsection io



@itemize *

@item 
Remove @ref{83,,io}'s @code{io.OpenWrapper} and @code{_pyio.OpenWrapper}, deprecated in Python
3.10: just use @ref{316,,open()} instead. The @ref{316,,open()} (@ref{740,,io.open()})
function is a built-in function. Since Python 3.10, @code{_pyio.open()} is
also a static method.
(Contributed by Victor Stinner in gh-94169@footnote{https://github.com/python/cpython/issues/94169}.)
@end itemize

@node locale<2>,smtpd,io<4>,削除<2>
@anchor{whatsnew/3 12 locale}@anchor{741}
@subsubsection locale



@itemize *

@item 
Remove @ref{8a,,locale}'s @code{locale.format()} function, deprecated in Python 3.7:
use @ref{742,,locale.format_string()} instead.
(Contributed by Victor Stinner in gh-94226@footnote{https://github.com/python/cpython/issues/94226}.)
@end itemize

@node smtpd,sqlite3<4>,locale<2>,削除<2>
@anchor{whatsnew/3 12 smtpd}@anchor{743}
@subsubsection smtpd



@itemize *

@item 
The @code{smtpd} module has been removed according to the schedule in 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/},
having been deprecated in Python 3.4.7 and 3.5.4.
Use the aiosmtpd@footnote{https://pypi.org/project/aiosmtpd/} PyPI module or any other
@ref{b,,asyncio}-based server instead.
(Contributed by Oleg Iarygin in gh-93243@footnote{https://github.com/python/cpython/issues/93243}.)
@end itemize

@node sqlite3<4>,ssl<3>,smtpd,削除<2>
@anchor{whatsnew/3 12 id2}@anchor{744}
@subsubsection sqlite3



@itemize *

@item 
The following undocumented @ref{d4,,sqlite3} features, deprecated in Python
3.10, are now removed:


@itemize *

@item 
@code{sqlite3.enable_shared_cache()}

@item 
@code{sqlite3.OptimizedUnicode}
@end itemize

If a shared cache must be used, open the database in URI mode using the
@code{cache=shared} query parameter.

The @code{sqlite3.OptimizedUnicode} text factory has been an alias for
@ref{169,,str} since Python 3.3. Code that previously set the text factory to
@code{OptimizedUnicode} can either use @code{str} explicitly, or rely on the
default value which is also @code{str}.

(Contributed by Erlend E. Aasland in gh-92548@footnote{https://github.com/python/cpython/issues/92548}.)
@end itemize

@node ssl<3>,unittest<4>,sqlite3<4>,削除<2>
@anchor{whatsnew/3 12 ssl}@anchor{745}
@subsubsection ssl



@itemize *

@item 
Remove @ref{d5,,ssl}'s @code{ssl.RAND_pseudo_bytes()} function, deprecated in Python 3.6:
use @ref{746,,os.urandom()} or @ref{747,,ssl.RAND_bytes()} instead.
(Contributed by Victor Stinner in gh-94199@footnote{https://github.com/python/cpython/issues/94199}.)

@item 
Remove the @code{ssl.match_hostname()} function.
It was deprecated in Python 3.7. OpenSSL performs
hostname matching since Python 3.7, Python no longer uses the
@code{ssl.match_hostname()} function.
(Contributed by Victor Stinner in gh-94199@footnote{https://github.com/python/cpython/issues/94199}.)

@item 
Remove the @code{ssl.wrap_socket()} function, deprecated in Python 3.7:
instead, create a @ref{357,,ssl.SSLContext} object and call its
@ref{748,,ssl.SSLContext.wrap_socket} method. Any package that still uses
@code{ssl.wrap_socket()} is broken and insecure. The function neither sends a
SNI TLS extension nor validates the server hostname. Code is subject to 
@geindex Common Weakness Enumeration; CWE 295
CWE 295@footnote{https://cwe.mitre.org/data/definitions/295.html}
(Improper Certificate Validation).
(Contributed by Victor Stinner in gh-94199@footnote{https://github.com/python/cpython/issues/94199}.)
@end itemize

@node unittest<4>,webbrowser<3>,ssl<3>,削除<2>
@anchor{whatsnew/3 12 id3}@anchor{749}
@subsubsection unittest



@itemize *

@item 
Remove many long-deprecated @ref{10c,,unittest} features:
@anchor{whatsnew/3 12 unittest-testcase-removed-aliases}@anchor{67f}

@itemize *

@item 
A number of @ref{2b3,,TestCase} method aliases:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

非推奨のエイリアス

@tab

メソッド名

@tab

非推奨となるバージョン

@item

@code{failUnless}

@tab

@ref{74a,,assertTrue()}

@tab

3.1

@item

@code{failIf}

@tab

@ref{74b,,assertFalse()}

@tab

3.1

@item

@code{failUnlessEqual}

@tab

@ref{74c,,assertEqual()}

@tab

3.1

@item

@code{failIfEqual}

@tab

@ref{74d,,assertNotEqual()}

@tab

3.1

@item

@code{failUnlessAlmostEqual}

@tab

@ref{74e,,assertAlmostEqual()}

@tab

3.1

@item

@code{failIfAlmostEqual}

@tab

@ref{74f,,assertNotAlmostEqual()}

@tab

3.1

@item

@code{failUnlessRaises}

@tab

@ref{750,,assertRaises()}

@tab

3.1

@item

@code{assert_}

@tab

@ref{74a,,assertTrue()}

@tab

3.2

@item

@code{assertEquals}

@tab

@ref{74c,,assertEqual()}

@tab

3.2

@item

@code{assertNotEquals}

@tab

@ref{74d,,assertNotEqual()}

@tab

3.2

@item

@code{assertAlmostEquals}

@tab

@ref{74e,,assertAlmostEqual()}

@tab

3.2

@item

@code{assertNotAlmostEquals}

@tab

@ref{74f,,assertNotAlmostEqual()}

@tab

3.2

@item

@code{assertRegexpMatches}

@tab

@ref{751,,assertRegex()}

@tab

3.2

@item

@code{assertRaisesRegexp}

@tab

@ref{752,,assertRaisesRegex()}

@tab

3.2

@item

@code{assertNotRegexpMatches}

@tab

@ref{753,,assertNotRegex()}

@tab

3.5

@end multitable


You can use @indicateurl{https://github.com/isidentical/teyit} to automatically modernise
your unit tests.

@item 
Undocumented and broken @ref{2b3,,TestCase} method
@code{assertDictContainsSubset} (deprecated in Python 3.2).

@item 
Undocumented @ref{594,,TestLoader.loadTestsFromModule} parameter `use_load_tests'
(deprecated and ignored since Python 3.5).

@item 
An alias of the @ref{754,,TextTestResult} class:
@code{_TextTestResult} (deprecated in Python 3.2).
@end itemize

(Contributed by Serhiy Storchaka in gh-89325@footnote{https://github.com/python/cpython/issues/89325}.)
@end itemize

@node webbrowser<3>,xml etree ElementTree,unittest<4>,削除<2>
@anchor{whatsnew/3 12 webbrowser}@anchor{755}
@subsubsection webbrowser



@itemize *

@item 
Remove support for obsolete browsers from @ref{11b,,webbrowser}.
The removed browsers include: Grail, Mosaic, Netscape, Galeon, Skipstone,
Iceape, Firebird, and Firefox versions 35 and below (gh-102871@footnote{https://github.com/python/cpython/issues/102871}).
@end itemize

@node xml etree ElementTree,zipimport<2>,webbrowser<3>,削除<2>
@anchor{whatsnew/3 12 xml-etree-elementtree}@anchor{756}
@subsubsection xml.etree.ElementTree



@itemize *

@item 
Remove the @code{ElementTree.Element.copy()} method of the
pure Python implementation, deprecated in Python 3.10, use the
@ref{757,,copy.copy()} function instead.  The C implementation of @ref{12b,,xml.etree.ElementTree}
has no @code{copy()} method, only a @code{__copy__()} method.
(Contributed by Victor Stinner in gh-94383@footnote{https://github.com/python/cpython/issues/94383}.)
@end itemize

@node zipimport<2>,その他,xml etree ElementTree,削除<2>
@anchor{whatsnew/3 12 zipimport}@anchor{758}
@subsubsection zipimport



@itemize *

@item 
Remove @ref{138,,zipimport}'s @code{find_loader()} and @code{find_module()} methods,
deprecated in Python 3.10: use the @code{find_spec()} method instead.  See
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/} for the rationale.
(Contributed by Victor Stinner in gh-94379@footnote{https://github.com/python/cpython/issues/94379}.)
@end itemize

@node その他,,zipimport<2>,削除<2>
@anchor{whatsnew/3 12 others}@anchor{759}
@subsubsection その他



@itemize *

@item 
Remove the @code{suspicious} rule from the documentation @code{Makefile} and
@code{Doc/tools/rstlint.py}, both in favor of sphinx-lint@footnote{https://github.com/sphinx-contrib/sphinx-lint}.
(Contributed by Julien Palard in gh-98179@footnote{https://github.com/python/cpython/issues/98179}.)

@item 
Remove the `keyfile' and `certfile' parameters from the
@ref{62,,ftplib}, @ref{78,,imaplib}, @ref{b1,,poplib} and @ref{cf,,smtplib} modules,
and the `key_file', `cert_file' and `check_hostname' parameters from the
@ref{73,,http.client} module,
all deprecated since Python 3.6. Use the `context' parameter
(`ssl_context' in @ref{78,,imaplib}) instead.
(Contributed by Victor Stinner in gh-94172@footnote{https://github.com/python/cpython/issues/94172}.)

@item 
Remove @code{Jython} compatibility hacks from several stdlib modules and tests.
(Contributed by Nikita Sobolev in gh-99482@footnote{https://github.com/python/cpython/issues/99482}.)

@item 
Remove @code{_use_broken_old_ctypes_structure_semantics_} flag
from @ref{2e,,ctypes} module.
(Contributed by Nikita Sobolev in gh-99285@footnote{https://github.com/python/cpython/issues/99285}.)
@end itemize

@node Python 3 12 への移植,Build Changes<2>,削除<2>,What's New In Python 3 12
@anchor{whatsnew/3 12 porting-to-python-3-12}@anchor{75a}@anchor{whatsnew/3 12 whatsnew312-porting-to-python312}@anchor{6f3}
@subsection Python 3.12 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python API の変更: Python API の変更<3>. 

@end menu

@node Python API の変更<3>,,,Python 3 12 への移植
@anchor{whatsnew/3 12 changes-in-the-python-api}@anchor{75b}
@subsubsection Python API の変更



@itemize *

@item 
More strict rules are now applied for numerical group references and
group names in regular expressions.
Only sequence of ASCII digits is now accepted as a numerical reference.
The group name in bytes patterns and replacement strings can now only
contain ASCII letters and digits and underscore.
(Contributed by Serhiy Storchaka in gh-91760@footnote{https://github.com/python/cpython/issues/91760}.)

@item 
Remove @code{randrange()} functionality deprecated since Python 3.10.  Formerly,
@code{randrange(10.0)} losslessly converted to @code{randrange(10)}. Now, it raises a
@ref{198,,TypeError}. Also, the exception raised for non-integer values such as
@code{randrange(10.5)} or @code{randrange('10')} has been changed from @ref{2ec,,ValueError} to
@ref{198,,TypeError}.  This also prevents bugs where @code{randrange(1e25)} would silently
select from a larger range than @code{randrange(10**25)}.
(Originally suggested by Serhiy Storchaka gh-86388@footnote{https://github.com/python/cpython/issues/86388}.)

@item 
@ref{1bd,,argparse.ArgumentParser} changed encoding and error handler
for reading arguments from file (e.g. @code{fromfile_prefix_chars} option)
from default text encoding (e.g. @ref{75c,,locale.getpreferredencoding(False)})
to @ref{75d,,filesystem encoding and error handler}.
Argument files should be encoded in UTF-8 instead of ANSI Codepage on Windows.

@item 
Remove the @code{asyncore}-based @code{smtpd} module deprecated in Python 3.4.7
and 3.5.4.  A recommended replacement is the
@ref{b,,asyncio}-based aiosmtpd@footnote{https://pypi.org/project/aiosmtpd/} PyPI module.

@item 
@ref{75e,,shlex.split()}: Passing @code{None} for `s' argument now raises an
exception, rather than reading @ref{75f,,sys.stdin}. The feature was deprecated
in Python 3.9.
(Contributed by Victor Stinner in gh-94352@footnote{https://github.com/python/cpython/issues/94352}.)

@item 
The @ref{a5,,os} module no longer accepts bytes-like paths, like
@ref{344,,bytearray} and @ref{165,,memoryview} types: only the exact
@ref{192,,bytes} type is accepted for bytes strings.
(Contributed by Victor Stinner in gh-98393@footnote{https://github.com/python/cpython/issues/98393}.)

@item 
@ref{760,,syslog.openlog()} and @ref{761,,syslog.closelog()} now fail if used in subinterpreters.
@ref{762,,syslog.syslog()} may still be used in subinterpreters,
but now only if @ref{760,,syslog.openlog()} has already been called in the main interpreter.
These new restrictions do not apply to the main interpreter,
so only a very small set of users might be affected.
This change helps with interpreter isolation.  Furthermore, @ref{e2,,syslog} is a wrapper
around process-global resources, which are best managed from the main interpreter.
(Contributed by Donghee Na in gh-99127@footnote{https://github.com/python/cpython/issues/99127}.)

@item 
The undocumented locking behavior of @ref{763,,cached_property()}
is removed, because it locked across all instances of the class, leading to high
lock contention. This means that a cached property getter function could now run
more than once for a single instance, if two threads race. For most simple
cached properties (e.g. those that are idempotent and simply calculate a value
based on other attributes of the instance) this will be fine.  If
synchronization is needed, implement locking within the cached property getter
function or around multi-threaded access points.

@item 
@ref{6e9,,sys._current_exceptions()} now returns a mapping from thread-id to an
exception instance, rather than to a @code{(typ, exc, tb)} tuple.
(Contributed by Irit Katriel in gh-103176@footnote{https://github.com/python/cpython/issues/103176}.)

@item 
When extracting tar files using @ref{e4,,tarfile} or
@ref{696,,shutil.unpack_archive()}, pass the `filter' argument to limit features
that may be surprising or dangerous.
See @ref{697,,Extraction filters} for details.

@item 
The output of the @ref{700,,tokenize.tokenize()} and @ref{701,,tokenize.generate_tokens()}
functions is now changed due to the changes introduced in 
@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/}. This
means that @code{STRING} tokens are not emitted any more for f-strings and the
tokens described in 
@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/} are now produced instead: @code{FSTRING_START},
@code{FSTRING_MIDDLE} and @code{FSTRING_END} are now emitted for f-string "string"
parts in addition to the appropriate tokens for the tokenization in the
expression components. For example for the f-string @code{f"start @{1+1@} end"}
the old version of the tokenizer emitted:

@example
1,0-1,18:           STRING         'f"start @{1+1@} end"'
@end example

while the new version emits:

@example
1,0-1,2:            FSTRING_START  'f"'
1,2-1,8:            FSTRING_MIDDLE 'start '
1,8-1,9:            OP             '@{'
1,9-1,10:           NUMBER         '1'
1,10-1,11:          OP             '+'
1,11-1,12:          NUMBER         '1'
1,12-1,13:          OP             '@}'
1,13-1,17:          FSTRING_MIDDLE ' end'
1,17-1,18:          FSTRING_END    '"'
@end example

Additionally, there may be some minor behavioral changes as a consequence of the
changes required to support 
@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/}. Some of these changes include:


@itemize *

@item 
The @code{type} attribute of the tokens emitted when tokenizing some invalid Python
characters such as @code{!} has changed from @code{ERRORTOKEN} to @code{OP}.

@item 
Incomplete single-line strings now also raise @ref{764,,tokenize.TokenError} as incomplete
multiline strings do.

@item 
Some incomplete or invalid Python code now raises @ref{764,,tokenize.TokenError} instead of
returning arbitrary @code{ERRORTOKEN} tokens when tokenizing it.

@item 
Mixing tabs and spaces as indentation in the same file is not supported anymore and will
raise a @ref{765,,TabError}.
@end itemize

@item 
The @ref{f3,,threading} module now expects the @code{_thread} module to have
an @code{_is_main_interpreter} attribute.  It is a function with no
arguments that returns @code{True} if the current interpreter is the
main interpreter.

Any library or application that provides a custom @code{_thread} module
should provide @code{_is_main_interpreter()}.
(See gh-112826@footnote{https://github.com/python/cpython/issues/112826}.)
@end itemize

@node Build Changes<2>,C API の変更<4>,Python 3 12 への移植,What's New In Python 3 12
@anchor{whatsnew/3 12 build-changes}@anchor{766}
@subsection Build Changes



@itemize *

@item 
Python no longer uses @code{setup.py} to build shared C extension modules.
Build parameters like headers and libraries are detected in @code{configure}
script. Extensions are built by @code{Makefile}. Most extensions use
@code{pkg-config} and fall back to manual detection.
(Contributed by Christian Heimes in gh-93939@footnote{https://github.com/python/cpython/issues/93939}.)

@item 
@code{va_start()} with two parameters, like @code{va_start(args, format),}
is now required to build Python.
@code{va_start()} is no longer called with a single parameter.
(Contributed by Kumar Aditya in gh-93207@footnote{https://github.com/python/cpython/issues/93207}.)

@item 
CPython now uses the ThinLTO option as the default link time optimization policy
if the Clang compiler accepts the flag.
(Contributed by Donghee Na in gh-89536@footnote{https://github.com/python/cpython/issues/89536}.)

@item 
Add @code{COMPILEALL_OPTS} variable in @code{Makefile} to override @ref{21,,compileall}
options (default: @code{-j0}) in @code{make install}. Also merged the 3
@code{compileall} commands into a single command to build .pyc files for all
optimization levels (0, 1, 2) at once.
(Contributed by Victor Stinner in gh-99289@footnote{https://github.com/python/cpython/issues/99289}.)

@item 
Add platform triplets for 64-bit LoongArch:


@itemize *

@item 
loongarch64-linux-gnusf

@item 
loongarch64-linux-gnuf32

@item 
loongarch64-linux-gnu
@end itemize

(Contributed by Zhang Na in gh-90656@footnote{https://github.com/python/cpython/issues/90656}.)

@item 
@code{PYTHON_FOR_REGEN} now require Python 3.10 or newer.

@item 
Autoconf 2.71 and aclocal 1.16.4 is now required to regenerate
@code{configure}.
(Contributed by Christian Heimes in gh-89886@footnote{https://github.com/python/cpython/issues/89886}.)

@item 
Windows builds and macOS installers from python.org now use OpenSSL 3.0.
@end itemize

@node C API の変更<4>,,Build Changes<2>,What's New In Python 3 12
@anchor{whatsnew/3 12 c-api-changes}@anchor{767}
@subsection C API の変更


@menu
* 新しい機能: 新しい機能<5>. 
* Python 3.12 への移植: Python 3 12 への移植<2>. 
* 非推奨: 非推奨<3>. 
* 削除: 削除<3>. 

@end menu

@node 新しい機能<5>,Python 3 12 への移植<2>,,C API の変更<4>
@anchor{whatsnew/3 12 id4}@anchor{768}
@subsubsection 新しい機能

@anchor{whatsnew/3 12 whatsnew312-pep697}@anchor{677}

@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 697
PEP 697@footnote{https://peps.python.org/pep-0697/}: Introduce the @ref{769,,Unstable C API tier},
intended for low-level tools like debuggers and JIT compilers.
This API may change in each minor release of CPython without deprecation
warnings.
Its contents are marked by the @code{PyUnstable_} prefix in names.

Code object constructors:


@itemize -

@item 
@code{PyUnstable_Code_New()} (renamed from @code{PyCode_New})

@item 
@code{PyUnstable_Code_NewWithPosOnlyArgs()} (renamed from @code{PyCode_NewWithPosOnlyArgs})
@end itemize

Extra storage for code objects (
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/}):


@itemize -

@item 
@code{PyUnstable_Eval_RequestCodeExtraIndex()} (renamed from @code{_PyEval_RequestCodeExtraIndex})

@item 
@code{PyUnstable_Code_GetExtra()} (renamed from @code{_PyCode_GetExtra})

@item 
@code{PyUnstable_Code_SetExtra()} (renamed from @code{_PyCode_SetExtra})
@end itemize

The original names will continue to be available until the respective
API changes.

(Contributed by Petr Viktorin in gh-101101@footnote{https://github.com/python/cpython/issues/101101}.)

@item 
@geindex Python Enhancement Proposals; PEP 697
PEP 697@footnote{https://peps.python.org/pep-0697/}: Add an API for extending types whose instance memory layout is
opaque:


@itemize -

@item 
@ref{76a,,PyType_Spec.basicsize} can be zero or negative to specify
inheriting or extending the base class size.

@item 
@ref{76b,,PyObject_GetTypeData()} and @ref{76c,,PyType_GetTypeDataSize()}
added to allow access to subclass-specific instance data.

@item 
@ref{76d,,Py_TPFLAGS_ITEMS_AT_END} and @ref{76e,,PyObject_GetItemData()}
added to allow safely extending certain variable-sized types, including
@ref{76f,,PyType_Type}.

@item 
@ref{770,,Py_RELATIVE_OFFSET} added to allow defining
@ref{771,,members} in terms of a subclass-specific struct.
@end itemize

(Contributed by Petr Viktorin in gh-103509@footnote{https://github.com/python/cpython/issues/103509}.)

@item 
Add the new @ref{637,,limited C API} function @ref{772,,PyType_FromMetaclass()},
which generalizes the existing @ref{773,,PyType_FromModuleAndSpec()} using
an additional metaclass argument.
(Contributed by Wenzel Jakob in gh-93012@footnote{https://github.com/python/cpython/issues/93012}.)

@item 
API for creating objects that can be called using
@ref{774,,the vectorcall protocol} was added to the
@ref{775,,Limited API}:


@itemize *

@item 
@ref{776,,Py_TPFLAGS_HAVE_VECTORCALL}

@item 
@ref{777,,PyVectorcall_NARGS()}

@item 
@ref{778,,PyVectorcall_Call()}

@item 
@ref{779,,vectorcallfunc}
@end itemize

The @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag is now removed from a class
when the class's @ref{77a,,__call__()} method is reassigned.
This makes vectorcall safe to use with mutable types (i.e. heap types
without the immutable flag, @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE}).
Mutable types that do not override @ref{77b,,tp_call} now
inherit the @code{Py_TPFLAGS_HAVE_VECTORCALL} flag.
(Contributed by Petr Viktorin in gh-93274@footnote{https://github.com/python/cpython/issues/93274}.)

The @ref{60f,,Py_TPFLAGS_MANAGED_DICT} and @ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF}
flags have been added. This allows extensions classes to support object
@ref{77d,,__dict__} and weakrefs with less bookkeeping,
using less memory and with faster access.

@item 
API for performing calls using
@ref{774,,the vectorcall protocol} was added to the
@ref{775,,Limited API}:


@itemize *

@item 
@ref{77e,,PyObject_Vectorcall()}

@item 
@ref{77f,,PyObject_VectorcallMethod()}

@item 
@ref{780,,PY_VECTORCALL_ARGUMENTS_OFFSET}
@end itemize

This means that both the incoming and outgoing ends of the vector call
protocol are now available in the @ref{775,,Limited API}. (Contributed
by Wenzel Jakob in gh-98586@footnote{https://github.com/python/cpython/issues/98586}.)

@item 
Add two new public functions,
@ref{781,,PyEval_SetProfileAllThreads()} and
@ref{664,,PyEval_SetTraceAllThreads()}, that allow to set tracing and profiling
functions in all running threads in addition to the calling one. (Contributed
by Pablo Galindo in gh-93503@footnote{https://github.com/python/cpython/issues/93503}.)

@item 
Add new function @ref{782,,PyFunction_SetVectorcall()} to the C API
which sets the vectorcall field of a given @ref{783,,PyFunctionObject}.
(Contributed by Andrew Frost in gh-92257@footnote{https://github.com/python/cpython/issues/92257}.)

@item 
The C API now permits registering callbacks via @ref{3d0,,PyDict_AddWatcher()},
@ref{784,,PyDict_Watch()} and related APIs to be called whenever a dictionary
is modified. This is intended for use by optimizing interpreters, JIT
compilers, or debuggers.
(Contributed by Carl Meyer in gh-91052@footnote{https://github.com/python/cpython/issues/91052}.)

@item 
Add @ref{785,,PyType_AddWatcher()} and @ref{786,,PyType_Watch()} API to register
callbacks to receive notification on changes to a type.
(Contributed by Carl Meyer in gh-91051@footnote{https://github.com/python/cpython/issues/91051}.)

@item 
Add @ref{787,,PyCode_AddWatcher()} and @ref{788,,PyCode_ClearWatcher()}
APIs to register callbacks to receive notification on creation and
destruction of code objects.
(Contributed by Itamar Oren in gh-91054@footnote{https://github.com/python/cpython/issues/91054}.)

@item 
Add @ref{789,,PyFrame_GetVar()} and @ref{78a,,PyFrame_GetVarString()} functions to
get a frame variable by its name.
(Contributed by Victor Stinner in gh-91248@footnote{https://github.com/python/cpython/issues/91248}.)

@item 
Add @ref{429,,PyErr_GetRaisedException()} and @ref{42c,,PyErr_SetRaisedException()}
for saving and restoring the current exception.
These functions return and accept a single exception object,
rather than the triple arguments of the now-deprecated
@ref{428,,PyErr_Fetch()} and @ref{42b,,PyErr_Restore()}.
This is less error prone and a bit more efficient.
(Contributed by Mark Shannon in gh-101578@footnote{https://github.com/python/cpython/issues/101578}.)

@item 
Add @code{_PyErr_ChainExceptions1}, which takes an exception instance,
to replace the legacy-API @code{_PyErr_ChainExceptions}, which is now
deprecated. (Contributed by Mark Shannon in gh-101578@footnote{https://github.com/python/cpython/issues/101578}.)

@item 
Add @ref{78b,,PyException_GetArgs()} and @ref{78c,,PyException_SetArgs()}
as convenience functions for retrieving and modifying
the @ref{78d,,args} passed to the exception's constructor.
(Contributed by Mark Shannon in gh-101578@footnote{https://github.com/python/cpython/issues/101578}.)

@item 
Add @ref{435,,PyErr_DisplayException()}, which takes an exception instance,
to replace the legacy-api @code{PyErr_Display()}. (Contributed by
Irit Katriel in gh-102755@footnote{https://github.com/python/cpython/issues/102755}).
@end itemize
@anchor{whatsnew/3 12 whatsnew312-pep683}@anchor{678}

@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 683
PEP 683@footnote{https://peps.python.org/pep-0683/}: Introduce `Immortal Objects', which allows objects
to bypass reference counts, and related changes to the C-API:


@itemize -

@item 

@table @asis

@item @code{_Py_IMMORTAL_REFCNT}: The reference count that defines an object

as immortal.
@end table

@item 
@code{_Py_IsImmortal} Checks if an object has the immortal reference count.

@item 

@table @asis

@item @code{PyObject_HEAD_INIT} This will now initialize reference count to

@code{_Py_IMMORTAL_REFCNT} when used with @code{Py_BUILD_CORE}.
@end table

@item 

@table @asis

@item @code{SSTATE_INTERNED_IMMORTAL} An identifier for interned unicode objects

that are immortal.
@end table

@item 

@table @asis

@item @code{SSTATE_INTERNED_IMMORTAL_STATIC} An identifier for interned unicode

objects that are immortal and static
@end table

@item 

@table @asis

@item @code{sys.getunicodeinternedsize} This returns the total number of unicode

objects that have been interned. This is now needed for @code{refleak.py} to
correctly track reference counts and allocated blocks
@end table
@end itemize

(Contributed by Eddie Elizondo in gh-84436@footnote{https://github.com/python/cpython/issues/84436}.)

@item 
@geindex Python Enhancement Proposals; PEP 684
PEP 684@footnote{https://peps.python.org/pep-0684/}: Add the new @ref{689,,Py_NewInterpreterFromConfig()}
function and @ref{78e,,PyInterpreterConfig}, which may be used
to create sub-interpreters with their own GILs.
(See @ref{670,,PEP 684; インタープリタごとの GIL} for more info.)
(Contributed by Eric Snow in gh-104110@footnote{https://github.com/python/cpython/issues/104110}.)

@item 
In the limited C API version 3.12, @ref{78f,,Py_INCREF()} and
@ref{790,,Py_DECREF()} functions are now implemented as opaque function calls to
hide implementation details.
(Contributed by Victor Stinner in gh-105387@footnote{https://github.com/python/cpython/issues/105387}.)
@end itemize

@node Python 3 12 への移植<2>,非推奨<3>,新しい機能<5>,C API の変更<4>
@anchor{whatsnew/3 12 id5}@anchor{791}
@subsubsection Python 3.12 への移植



@itemize *

@item 
Legacy Unicode APIs based on @code{Py_UNICODE*} representation has been removed.
Please migrate to APIs based on UTF-8 or @code{wchar_t*}.

@item 
Argument parsing functions like @ref{3c1,,PyArg_ParseTuple()} doesn't support
@code{Py_UNICODE*} based format (e.g. @code{u}, @code{Z}) anymore. Please migrate
to other formats for Unicode like @code{s}, @code{z}, @code{es}, and @code{U}.

@item 
@code{tp_weaklist} for all static builtin types is always @code{NULL}.
This is an internal-only field on @code{PyTypeObject}
but we're pointing out the change in case someone happens to be
accessing the field directly anyway.  To avoid breakage, consider
using the existing public C-API instead, or, if necessary, the
(internal-only) @code{_PyObject_GET_WEAKREFS_LISTPTR()} macro.

@item 
This internal-only @ref{792,,PyTypeObject.tp_subclasses} may now not be
a valid object pointer.  Its type was changed to void* to
reflect this.  We mention this in case someone happens to be accessing the
internal-only field directly.

To get a list of subclasses, call the Python method
@ref{793,,__subclasses__()} (using @ref{640,,PyObject_CallMethod()},
for example).

@item 
Add support of more formatting options (left aligning, octals, uppercase
hexadecimals, @code{intmax_t}, @code{ptrdiff_t}, @code{wchar_t} C
strings, variable width and precision) in @ref{62b,,PyUnicode_FromFormat()} and
@ref{794,,PyUnicode_FromFormatV()}.
(Contributed by Serhiy Storchaka in gh-98836@footnote{https://github.com/python/cpython/issues/98836}.)

@item 
An unrecognized format character in @ref{62b,,PyUnicode_FromFormat()} and
@ref{794,,PyUnicode_FromFormatV()} now sets a @ref{795,,SystemError}.
In previous versions it caused all the rest of the format string to be
copied as-is to the result string, and any extra arguments discarded.
(Contributed by Serhiy Storchaka in gh-95781@footnote{https://github.com/python/cpython/issues/95781}.)

@item 
Fix wrong sign placement in @ref{62b,,PyUnicode_FromFormat()} and
@ref{794,,PyUnicode_FromFormatV()}.
(Contributed by Philip Georgi in gh-95504@footnote{https://github.com/python/cpython/issues/95504}.)

@item 
Extension classes wanting to add a @ref{77d,,__dict__} or weak reference slot
should use @ref{60f,,Py_TPFLAGS_MANAGED_DICT} and
@ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF} instead of @code{tp_dictoffset} and
@code{tp_weaklistoffset}, respectively.
The use of @code{tp_dictoffset} and @code{tp_weaklistoffset} is still
supported, but does not fully support multiple inheritance
(gh-95589@footnote{https://github.com/python/cpython/issues/95589}), and performance may be worse.
Classes declaring @ref{60f,,Py_TPFLAGS_MANAGED_DICT} must call
@code{_PyObject_VisitManagedDict()} and @code{_PyObject_ClearManagedDict()}
to traverse and clear their instance's dictionaries.
To clear weakrefs, call @ref{796,,PyObject_ClearWeakRefs()}, as before.

@item 
The @ref{797,,PyUnicode_FSDecoder()} function no longer accepts bytes-like
paths, like @ref{344,,bytearray} and @ref{165,,memoryview} types: only the exact
@ref{192,,bytes} type is accepted for bytes strings.
(Contributed by Victor Stinner in gh-98393@footnote{https://github.com/python/cpython/issues/98393}.)

@item 
The @ref{798,,Py_CLEAR}, @ref{799,,Py_SETREF} and @ref{79a,,Py_XSETREF}
macros now only evaluate their arguments once. If an argument has side
effects, these side effects are no longer duplicated.
(Contributed by Victor Stinner in gh-98724@footnote{https://github.com/python/cpython/issues/98724}.)

@item 
The interpreter's error indicator is now always normalized. This means
that @ref{79b,,PyErr_SetObject()}, @ref{79c,,PyErr_SetString()} and the other
functions that set the error indicator now normalize the exception
before storing it. (Contributed by Mark Shannon in gh-101578@footnote{https://github.com/python/cpython/issues/101578}.)

@item 
@code{_Py_RefTotal} is no longer authoritative and only kept around
for ABI compatibility.  Note that it is an internal global and only
available on debug builds.  If you happen to be using it then you'll
need to start using @code{_Py_GetGlobalRefTotal()}.

@item 
The following functions now select an appropriate metaclass for the newly
created type:


@itemize *

@item 
@ref{79d,,PyType_FromSpec()}

@item 
@ref{79e,,PyType_FromSpecWithBases()}

@item 
@ref{773,,PyType_FromModuleAndSpec()}
@end itemize

Creating classes whose metaclass overrides @ref{79f,,tp_new}
is deprecated, and in Python 3.14+ it will be disallowed.
Note that these functions ignore @code{tp_new} of the metaclass, possibly
allowing incomplete initialization.

Note that @ref{772,,PyType_FromMetaclass()} (added in Python 3.12)
already disallows creating classes whose metaclass overrides @code{tp_new}
(@ref{7a0,,__new__()} in Python).

Since @code{tp_new} overrides almost everything @code{PyType_From*} functions do,
the two are incompatible with each other.
The existing behavior -- ignoring the metaclass for several steps
of type creation -- is unsafe in general, since (meta)classes assume that
@code{tp_new} was called.
There is no simple general workaround. One of the following may work for you:


@itemize -

@item 
If you control the metaclass, avoid using @code{tp_new} in it:


@itemize -

@item 
If initialization can be skipped, it can be done in
@ref{7a1,,tp_init} instead.

@item 
If the metaclass doesn't need to be instantiated from Python,
set its @code{tp_new} to @code{NULL} using
the @ref{7a2,,Py_TPFLAGS_DISALLOW_INSTANTIATION} flag.
This makes it acceptable for @code{PyType_From*} functions.
@end itemize

@item 
Avoid @code{PyType_From*} functions: if you don't need C-specific features
(slots or setting the instance size), create types by @ref{7a3,,calling}
the metaclass.

@item 
If you `know' the @code{tp_new} can be skipped safely, filter the deprecation
warning out using @ref{179,,warnings.catch_warnings()} from Python.
@end itemize

@item 
@ref{7a4,,PyOS_InputHook} and @ref{7a5,,PyOS_ReadlineFunctionPointer} are no
longer called in @ref{163,,subinterpreters}. This is
because clients generally rely on process-wide global state (since these
callbacks have no way of recovering extension module state).

This also avoids situations where extensions may find themselves running in a
subinterpreter that they don't support (or haven't yet been loaded in). See
gh-104668@footnote{https://github.com/python/cpython/issues/104668} for more info.

@item 
@ref{39e,,PyLongObject} has had its internals changed for better performance.
Although the internals of @ref{39e,,PyLongObject} are private, they are used
by some extension modules.
The internal fields should no longer be accessed directly, instead the API
functions beginning @code{PyLong_...} should be used instead.
Two new `unstable' API functions are provided for efficient access to the
value of @ref{39e,,PyLongObject}s which fit into a single machine word:


@itemize *

@item 
@ref{7a6,,PyUnstable_Long_IsCompact()}

@item 
@ref{7a7,,PyUnstable_Long_CompactValue()}
@end itemize

@item 
Custom allocators, set via @ref{7a8,,PyMem_SetAllocator()}, are now
required to be thread-safe, regardless of memory domain.  Allocators
that don't have their own state, including "hooks", are not affected.
If your custom allocator is not already thread-safe and you need
guidance then please create a new GitHub issue
and CC @code{@@ericsnowcurrently}.
@end itemize

@node 非推奨<3>,削除<3>,Python 3 12 への移植<2>,C API の変更<4>
@anchor{whatsnew/3 12 id6}@anchor{7a9}
@subsubsection 非推奨



@itemize *

@item 
In accordance with 
@geindex Python Enhancement Proposals; PEP 699
PEP 699@footnote{https://peps.python.org/pep-0699/}, the @code{ma_version_tag} field in @ref{64f,,PyDictObject}
is deprecated for extension modules. Accessing this field will generate a compiler
warning at compile time. This field will be removed in Python 3.14.
(Contributed by Ramvikrams and Kumar Aditya in gh-101193@footnote{https://github.com/python/cpython/issues/101193}. PEP by Ken Jin.)

@item 
Deprecate global configuration variable:


@itemize *

@item 
@ref{3f8,,Py_DebugFlag}: use @ref{3f9,,PyConfig.parser_debug}

@item 
@ref{3fa,,Py_VerboseFlag}: use @ref{3fb,,PyConfig.verbose}

@item 
@ref{3fc,,Py_QuietFlag}: use @ref{3fd,,PyConfig.quiet}

@item 
@ref{3fe,,Py_InteractiveFlag}: use @ref{3ff,,PyConfig.interactive}

@item 
@ref{400,,Py_InspectFlag}: use @ref{401,,PyConfig.inspect}

@item 
@ref{402,,Py_OptimizeFlag}: use @ref{403,,PyConfig.optimization_level}

@item 
@ref{404,,Py_NoSiteFlag}: use @ref{405,,PyConfig.site_import}

@item 
@ref{406,,Py_BytesWarningFlag}: use @ref{407,,PyConfig.bytes_warning}

@item 
@ref{408,,Py_FrozenFlag}: use @ref{409,,PyConfig.pathconfig_warnings}

@item 
@ref{40a,,Py_IgnoreEnvironmentFlag}: use @ref{40b,,PyConfig.use_environment}

@item 
@ref{40c,,Py_DontWriteBytecodeFlag}: use @ref{40d,,PyConfig.write_bytecode}

@item 
@ref{40e,,Py_NoUserSiteDirectory}: use @ref{40f,,PyConfig.user_site_directory}

@item 
@ref{410,,Py_UnbufferedStdioFlag}: use @ref{411,,PyConfig.buffered_stdio}

@item 
@ref{412,,Py_HashRandomizationFlag}: use @ref{413,,PyConfig.use_hash_seed}
and @ref{414,,PyConfig.hash_seed}

@item 
@ref{415,,Py_IsolatedFlag}: use @ref{416,,PyConfig.isolated}

@item 
@ref{417,,Py_LegacyWindowsFSEncodingFlag}: use @ref{418,,PyPreConfig.legacy_windows_fs_encoding}

@item 
@ref{419,,Py_LegacyWindowsStdioFlag}: use @ref{41a,,PyConfig.legacy_windows_stdio}

@item 
@code{Py_FileSystemDefaultEncoding}: use @ref{41b,,PyConfig.filesystem_encoding}

@item 
@code{Py_HasFileSystemDefaultEncoding}: use @ref{41b,,PyConfig.filesystem_encoding}

@item 
@code{Py_FileSystemDefaultEncodeErrors}: use @ref{41c,,PyConfig.filesystem_errors}

@item 
@code{Py_UTF8Mode}: use @ref{41d,,PyPreConfig.utf8_mode} (see @ref{41e,,Py_PreInitialize()})
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} instead.
(Contributed by Victor Stinner in gh-77782@footnote{https://github.com/python/cpython/issues/77782}.)

@item 
Creating @ref{3cf,,immutable types} with mutable
bases is deprecated and will be disabled in Python 3.14. (gh-95388@footnote{https://github.com/python/cpython/issues/95388})

@item 
The @code{structmember.h} header is deprecated, though it continues to be
available and there are no plans to remove it.

Its contents are now available just by including @code{Python.h},
with a @code{Py} prefix added if it was missing:


@itemize -

@item 
@ref{771,,PyMemberDef}, @ref{7aa,,PyMember_GetOne()} and
@ref{7ab,,PyMember_SetOne()}

@item 
Type macros like @ref{7ac,,Py_T_INT}, @ref{7ad,,Py_T_DOUBLE}, etc.
(previously @code{T_INT}, @code{T_DOUBLE}, etc.)

@item 
The flags @ref{7ae,,Py_READONLY} (previously @code{READONLY}) and
@ref{7af,,Py_AUDIT_READ} (previously all uppercase)
@end itemize

Several items are not exposed from @code{Python.h}:


@itemize -

@item 
@ref{7b0,,T_OBJECT} (use @ref{7b1,,Py_T_OBJECT_EX})

@item 
@ref{7b2,,T_NONE} (previously undocumented, and pretty quirky)

@item 
The macro @code{WRITE_RESTRICTED} which does nothing.

@item 
The macros @code{RESTRICTED} and @code{READ_RESTRICTED}, equivalents of
@ref{7af,,Py_AUDIT_READ}.

@item 
In some configurations, @code{<stddef.h>} is not included from @code{Python.h}.
It should be included manually when using @code{offsetof()}.
@end itemize

The deprecated header continues to provide its original
contents under the original names.
Your old code can stay unchanged, unless the extra include and non-namespaced
macros bother you greatly.

(Contributed in gh-47146@footnote{https://github.com/python/cpython/issues/47146} by Petr Viktorin, based on
earlier work by Alexander Belopolsky and Matthias Braun.)

@item 
@ref{428,,PyErr_Fetch()} and @ref{42b,,PyErr_Restore()} are deprecated.
Use @ref{429,,PyErr_GetRaisedException()} and
@ref{42c,,PyErr_SetRaisedException()} instead.
(Contributed by Mark Shannon in gh-101578@footnote{https://github.com/python/cpython/issues/101578}.)

@item 
@code{PyErr_Display()} is deprecated. Use @ref{435,,PyErr_DisplayException()}
instead. (Contributed by Irit Katriel in gh-102755@footnote{https://github.com/python/cpython/issues/102755}).

@item 
@code{_PyErr_ChainExceptions} is deprecated. Use @code{_PyErr_ChainExceptions1}
instead. (Contributed by Irit Katriel in gh-102192@footnote{https://github.com/python/cpython/issues/102192}.)

@item 
Using @ref{79d,,PyType_FromSpec()}, @ref{79e,,PyType_FromSpecWithBases()}
or @ref{773,,PyType_FromModuleAndSpec()} to create a class whose metaclass
overrides @ref{79f,,tp_new} is deprecated.
Call the metaclass instead.
@end itemize

@c Add deprecations above alphabetically, not here at the end.

@menu
* Pending removal in Python 3.14: Pending removal in Python 3 14<4>. 
* Pending removal in Python 3.15: Pending removal in Python 3 15<6>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<6>. 
* Pending removal in future versions: Pending removal in future versions<6>. 

@end menu

@node Pending removal in Python 3 14<4>,Pending removal in Python 3 15<6>,,非推奨<3>
@anchor{whatsnew/3 12 id7}@anchor{7b3}
@subsubsection Pending removal in Python 3.14



@itemize *

@item 
The @code{ma_version_tag} field in @ref{64f,,PyDictObject} for extension modules
(
@geindex Python Enhancement Proposals; PEP 699
PEP 699@footnote{https://peps.python.org/pep-0699/}; gh-101193@footnote{https://github.com/python/cpython/issues/101193}).

@item 
Creating @ref{3cf,,immutable types} with mutable
bases (gh-95388@footnote{https://github.com/python/cpython/issues/95388}).
@end itemize

@node Pending removal in Python 3 15<6>,Pending removal in Python 3 16<6>,Pending removal in Python 3 14<4>,非推奨<3>
@anchor{whatsnew/3 12 id8}@anchor{7b4}
@subsubsection Pending removal in Python 3.15



@itemize *

@item 
The @ref{3db,,PyImport_ImportModuleNoBlock()}:
Use @ref{3dc,,PyImport_ImportModule()} instead.

@item 
@ref{3dd,,PyWeakref_GetObject()} and @ref{3de,,PyWeakref_GET_OBJECT()}:
Use @ref{3df,,PyWeakref_GetRef()} instead. The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{3df,,PyWeakref_GetRef()} on Python 3.12 and older.

@item 
@ref{3e0,,Py_UNICODE} type and the @code{Py_UNICODE_WIDE} macro:
Use @code{wchar_t} instead.

@item 
@code{PyUnicode_AsDecodedObject()}:
Use @ref{3e1,,PyCodec_Decode()} instead.

@item 
@code{PyUnicode_AsDecodedUnicode()}:
Use @ref{3e1,,PyCodec_Decode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{169,,str}, such as @ref{192,,bytes}.

@item 
@code{PyUnicode_AsEncodedObject()}:
Use @ref{3e2,,PyCodec_Encode()} instead.

@item 
@code{PyUnicode_AsEncodedUnicode()}:
Use @ref{3e2,,PyCodec_Encode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{192,,bytes}, such as @ref{169,,str}.

@item 
Python initialization functions, deprecated in Python 3.13:


@itemize *

@item 
@ref{3e3,,Py_GetPath()}:
Use @ref{37c,,PyConfig_Get("module_search_paths")}
(@ref{3e4,,sys.path}) instead.

@item 
@ref{3e5,,Py_GetPrefix()}:
Use @ref{37c,,PyConfig_Get("base_prefix")}
(@ref{3e6,,sys.base_prefix}) instead. Use @ref{37c,,PyConfig_Get("prefix")} (@ref{3e7,,sys.prefix}) if @ref{3e8,,virtual environments} need to be handled.

@item 
@ref{3e9,,Py_GetExecPrefix()}:
Use @ref{37c,,PyConfig_Get("base_exec_prefix")}
(@ref{3ea,,sys.base_exec_prefix}) instead. Use
@ref{37c,,PyConfig_Get("exec_prefix")}
(@ref{3eb,,sys.exec_prefix}) if @ref{3e8,,virtual environments} need to
be handled.

@item 
@ref{3ec,,Py_GetProgramFullPath()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ee,,Py_GetProgramName()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ef,,Py_GetPythonHome()}:
Use @ref{37c,,PyConfig_Get("home")} or the
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable instead.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{37c,,PyConfig_Get()} on Python 3.13 and older.

@item 
Functions to configure Python's initialization, deprecated in Python 3.11:


@itemize *

@item 
@code{PySys_SetArgvEx()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{PySys_SetArgv()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{Py_SetProgramName()}:
Set @ref{3f2,,PyConfig.program_name} instead.

@item 
@code{Py_SetPythonHome()}:
Set @ref{3f3,,PyConfig.home} instead.

@item 
@ref{3f4,,PySys_ResetWarnOptions()}:
Clear @ref{3f5,,sys.warnoptions} and @code{warnings.filters} instead.
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} instead.

@item 
Global configuration variables:


@itemize *

@item 
@ref{3f8,,Py_DebugFlag}:
Use @ref{3f9,,PyConfig.parser_debug} or
@ref{37c,,PyConfig_Get("parser_debug")} instead.

@item 
@ref{3fa,,Py_VerboseFlag}:
Use @ref{3fb,,PyConfig.verbose} or
@ref{37c,,PyConfig_Get("verbose")} instead.

@item 
@ref{3fc,,Py_QuietFlag}:
Use @ref{3fd,,PyConfig.quiet} or
@ref{37c,,PyConfig_Get("quiet")} instead.

@item 
@ref{3fe,,Py_InteractiveFlag}:
Use @ref{3ff,,PyConfig.interactive} or
@ref{37c,,PyConfig_Get("interactive")} instead.

@item 
@ref{400,,Py_InspectFlag}:
Use @ref{401,,PyConfig.inspect} or
@ref{37c,,PyConfig_Get("inspect")} instead.

@item 
@ref{402,,Py_OptimizeFlag}:
Use @ref{403,,PyConfig.optimization_level} or
@ref{37c,,PyConfig_Get("optimization_level")} instead.

@item 
@ref{404,,Py_NoSiteFlag}:
Use @ref{405,,PyConfig.site_import} or
@ref{37c,,PyConfig_Get("site_import")} instead.

@item 
@ref{406,,Py_BytesWarningFlag}:
Use @ref{407,,PyConfig.bytes_warning} or
@ref{37c,,PyConfig_Get("bytes_warning")} instead.

@item 
@ref{408,,Py_FrozenFlag}:
Use @ref{409,,PyConfig.pathconfig_warnings} or
@ref{37c,,PyConfig_Get("pathconfig_warnings")} instead.

@item 
@ref{40a,,Py_IgnoreEnvironmentFlag}:
Use @ref{40b,,PyConfig.use_environment} or
@ref{37c,,PyConfig_Get("use_environment")} instead.

@item 
@ref{40c,,Py_DontWriteBytecodeFlag}:
Use @ref{40d,,PyConfig.write_bytecode} or
@ref{37c,,PyConfig_Get("write_bytecode")} instead.

@item 
@ref{40e,,Py_NoUserSiteDirectory}:
Use @ref{40f,,PyConfig.user_site_directory} or
@ref{37c,,PyConfig_Get("user_site_directory")} instead.

@item 
@ref{410,,Py_UnbufferedStdioFlag}:
Use @ref{411,,PyConfig.buffered_stdio} or
@ref{37c,,PyConfig_Get("buffered_stdio")} instead.

@item 
@ref{412,,Py_HashRandomizationFlag}:
Use @ref{413,,PyConfig.use_hash_seed}
and @ref{414,,PyConfig.hash_seed} or
@ref{37c,,PyConfig_Get("hash_seed")} instead.

@item 
@ref{415,,Py_IsolatedFlag}:
Use @ref{416,,PyConfig.isolated} or
@ref{37c,,PyConfig_Get("isolated")} instead.

@item 
@ref{417,,Py_LegacyWindowsFSEncodingFlag}:
Use @ref{418,,PyPreConfig.legacy_windows_fs_encoding} or
@ref{37c,,PyConfig_Get("legacy_windows_fs_encoding")} instead.

@item 
@ref{419,,Py_LegacyWindowsStdioFlag}:
Use @ref{41a,,PyConfig.legacy_windows_stdio} or
@ref{37c,,PyConfig_Get("legacy_windows_stdio")} instead.

@item 
@code{Py_FileSystemDefaultEncoding}, @code{Py_HasFileSystemDefaultEncoding}:
Use @ref{41b,,PyConfig.filesystem_encoding} or
@ref{37c,,PyConfig_Get("filesystem_encoding")} instead.

@item 
@code{Py_FileSystemDefaultEncodeErrors}:
Use @ref{41c,,PyConfig.filesystem_errors} or
@ref{37c,,PyConfig_Get("filesystem_errors")} instead.

@item 
@code{Py_UTF8Mode}:
Use @ref{41d,,PyPreConfig.utf8_mode} or
@ref{37c,,PyConfig_Get("utf8_mode")} instead.
(see @ref{41e,,Py_PreInitialize()})
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} to set these options. Or @ref{37c,,PyConfig_Get()} can be
used to get these options at runtime.
@end itemize

@node Pending removal in Python 3 16<6>,Pending removal in future versions<6>,Pending removal in Python 3 15<6>,非推奨<3>
@anchor{whatsnew/3 12 id9}@anchor{7b5}
@subsubsection Pending removal in Python 3.16



@itemize *

@item 
The bundled copy of @code{libmpdec}.
@end itemize

@node Pending removal in future versions<6>,,Pending removal in Python 3 16<6>,非推奨<3>
@anchor{whatsnew/3 12 id10}@anchor{7b6}
@subsubsection Pending removal in future versions


The following APIs are deprecated and will be removed,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{427,,Py_TPFLAGS_HAVE_FINALIZE}:
Unneeded since Python 3.8.

@item 
@ref{428,,PyErr_Fetch()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42a,,PyErr_NormalizeException()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42b,,PyErr_Restore()}:
Use @ref{42c,,PyErr_SetRaisedException()} instead.

@item 
@ref{42d,,PyModule_GetFilename()}:
Use @ref{42e,,PyModule_GetFilenameObject()} instead.

@item 
@ref{42f,,PyOS_AfterFork()}:
Use @ref{430,,PyOS_AfterFork_Child()} instead.

@item 
@ref{431,,PySlice_GetIndicesEx()}:
Use @ref{432,,PySlice_Unpack()} and @ref{433,,PySlice_AdjustIndices()} instead.

@item 
@ref{434,,PyUnicode_READY()}:
Unneeded since Python 3.12

@item 
@code{PyErr_Display()}:
Use @ref{435,,PyErr_DisplayException()} instead.

@item 
@code{_PyErr_ChainExceptions()}:
Use @code{_PyErr_ChainExceptions1()} instead.

@item 
@code{PyBytesObject.ob_shash} member:
call @ref{436,,PyObject_Hash()} instead.

@item 
Thread Local Storage (TLS) API:


@itemize *

@item 
@ref{437,,PyThread_create_key()}:
Use @ref{438,,PyThread_tss_alloc()} instead.

@item 
@ref{439,,PyThread_delete_key()}:
Use @ref{43a,,PyThread_tss_free()} instead.

@item 
@ref{43b,,PyThread_set_key_value()}:
Use @ref{43c,,PyThread_tss_set()} instead.

@item 
@ref{43d,,PyThread_get_key_value()}:
Use @ref{43e,,PyThread_tss_get()} instead.

@item 
@ref{43f,,PyThread_delete_key_value()}:
Use @ref{440,,PyThread_tss_delete()} instead.

@item 
@ref{441,,PyThread_ReInitTLS()}:
Unneeded since Python 3.7.
@end itemize
@end itemize

@node 削除<3>,,非推奨<3>,C API の変更<4>
@anchor{whatsnew/3 12 id11}@anchor{7b7}
@subsubsection 削除



@itemize *

@item 
Remove the @code{token.h} header file. There was never any public tokenizer C
API. The @code{token.h} header file was only designed to be used by Python
internals.
(Contributed by Victor Stinner in gh-92651@footnote{https://github.com/python/cpython/issues/92651}.)

@item 
Legacy Unicode APIs have been removed. See 
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/} for detail.


@itemize *

@item 
@code{PyUnicode_WCHAR_KIND}

@item 
@code{PyUnicode_AS_UNICODE()}

@item 
@code{PyUnicode_AsUnicode()}

@item 
@code{PyUnicode_AsUnicodeAndSize()}

@item 
@code{PyUnicode_AS_DATA()}

@item 
@code{PyUnicode_FromUnicode()}

@item 
@code{PyUnicode_GET_SIZE()}

@item 
@code{PyUnicode_GetSize()}

@item 
@code{PyUnicode_GET_DATA_SIZE()}
@end itemize

@item 
Remove the @code{PyUnicode_InternImmortal()} function macro.
(Contributed by Victor Stinner in gh-85858@footnote{https://github.com/python/cpython/issues/85858}.)
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 11,What's New In Python 3 10,What's New In Python 3 12,What's New in Python
@anchor{whatsnew/3 11 doc}@anchor{7b8}@anchor{whatsnew/3 11 translation-repo}@anchor{7b9}@anchor{whatsnew/3 11 what-s-new-in-python-3-11}@anchor{7ba}
@section What's New In Python 3.11


@*編集者: 
Pablo Galindo Salgado


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

この記事では Python 3.10 と比較した Python 3.11 の新機能を解説します。Python 3.11 は2022年10月24日にリリースされました。全詳細については @ref{142,,変更履歴} をご覧ください。

@menu
* 概要: 概要 -- リリースハイライト<4>. リリースハイライト
* 新しい機能: 新しい機能<6>. 
* 型ヒントに関連する新しい機能: 型ヒントに関連する新しい機能<2>. 
* その他の言語変更: その他の言語変更<3>. 
* その他の CPython の実装の変更:: 
* 新たなモジュール: 新たなモジュール<3>. 
* 改良されたモジュール: 改良されたモジュール<3>. 
* 最適化: 最適化<4>. 
* Faster CPython:: 
* CPython バイトコードの変更: CPython バイトコードの変更<3>. 
* 非推奨: 非推奨<4>. 
* Pending Removal in Python 3.12: Pending Removal in Python 3 12. 
* 削除: 削除<4>. 
* Porting to Python 3.11: Porting to Python 3 11. 
* Build Changes: Build Changes<3>. 
* C API の変更: C API の変更<5>. 
* Python 3.11.4での重要な変更点: Python 3 11 4での重要な変更点. 
* Python 3.11.5での重要な変更点: Python 3 11 5での重要な変更点. 

@end menu

@node 概要 -- リリースハイライト<4>,新しい機能<6>,,What's New In Python 3 11
@anchor{whatsnew/3 11 summary-release-highlights}@anchor{7bb}@anchor{whatsnew/3 11 whatsnew311-summary}@anchor{7bc}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.11.
@c Brevity is key.


@itemize *

@item 
Python 3.11 は Python 3.10 とくらべて 10-60% 高速です。平均的には、標準ベンチマークスイートでは 1.25倍の高速化を計測しました。詳細については @ref{7bd,,Faster CPython} を見てください。
@end itemize

@c PEP-sized items next.

新たな文法機能:


@itemize *

@item 
@ref{7be,,PEP 654; 例外グループと except*}
@end itemize

新たな組み込み機能:


@itemize *

@item 
@ref{7bf,,PEP 678; ノートによって例外を充実させる}
@end itemize

新しい標準ライブラリのモジュール：


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 680
PEP 680@footnote{https://peps.python.org/pep-0680/}: @ref{102,,tomllib} — TOML@footnote{https://toml.io/} のパースを標準ライブラリでサポート
@end itemize

インタープリタの改善:


@itemize *

@item 
@ref{7c0,,PEP 657; トレースバックのエラー位置の詳細化}

@item 
新しい @ref{7c1,,-P} コマンドライン引数と 
@geindex PYTHONSAFEPATH
@geindex 環境変数; PYTHONSAFEPATH
@ref{7c2,,PYTHONSAFEPATH} 環境変数により、 @ref{7c3,,安全でない可能性のあるパス} を @ref{3e4,,sys.path} に自動的に先頭に付加しないようにします。
@end itemize

新しい型ヒントの機能:


@itemize *

@item 
@ref{7c4,,PEP 646; Variadic generics}

@item 
@ref{7c5,,PEP 655; Marking individual TypedDict items as required or not-required}

@item 
@ref{7c6,,PEP 673; Self 型}

@item 
@ref{7c7,,PEP 675; Arbitrary literal string type}

@item 
@ref{7c8,,PEP 681; Data class transforms}
@end itemize

重要な非推奨化、削除と制限：


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: @ref{7c9,,たくさんのレガシーの標準ライブラリのモジュールが非推奨になり} Python 3.13 で削除されます

@item 
@geindex Python Enhancement Proposals; PEP 624
PEP 624@footnote{https://peps.python.org/pep-0624/}: @ref{7ca,,Py_UNICODE エンコーダー API は削除されました}

@item 
@geindex Python Enhancement Proposals; PEP 670
PEP 670@footnote{https://peps.python.org/pep-0670/}: @ref{7cb,,静的インライン関数に変換されたマクロ}
@end itemize

@node 新しい機能<6>,型ヒントに関連する新しい機能<2>,概要 -- リリースハイライト<4>,What's New In Python 3 11
@anchor{whatsnew/3 11 new-features}@anchor{7cc}@anchor{whatsnew/3 11 whatsnew311-features}@anchor{7cd}
@subsection 新しい機能


@menu
* PEP 657; トレースバックのエラー位置の詳細化: PEP 657 トレースバックのエラー位置の詳細化. 
* PEP 654; 例外グループと except*: PEP 654 例外グループと except*. 
* PEP 678; ノートによって例外を充実させる: PEP 678 ノートによって例外を充実させる. 
* Windows py.exe ランチャーの改善: Windows py exe ランチャーの改善. 

@end menu

@node PEP 657 トレースバックのエラー位置の詳細化,PEP 654 例外グループと except*,,新しい機能<6>
@anchor{whatsnew/3 11 pep-657-fine-grained-error-locations-in-tracebacks}@anchor{7ce}@anchor{whatsnew/3 11 whatsnew311-pep657}@anchor{7c0}
@subsubsection PEP 657: トレースバックのエラー位置の詳細化


トレースバックの出力時に、インタープリタはエラーを送出した行だけでなく正確な式を指し示すようになりました。たとえば:

@example
Traceback (most recent call last):
  File "distance.py", line 11, in <module>
    print(manhattan_distance(p1, p2))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "distance.py", line 6, in manhattan_distance
    return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
                           ^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'x'
@end example

以前のバージョンのインタープリタはその行だけを指していたため、どのオブジェクトが @code{None} であるかが曖昧でした。これらの強化されたエラーは、深くネストされた @ref{183,,dict} オブジェクトや複数の関数呼び出しを処理するときにも役立ちます:

@example
Traceback (most recent call last):
  File "query.py", line 37, in <module>
    magic_arithmetic('foo')
  File "query.py", line 18, in magic_arithmetic
    return add_counts(x) / 25
           ^^^^^^^^^^^^^
  File "query.py", line 24, in add_counts
    return 25 + query_user(user1) + query_user(user2)
                ^^^^^^^^^^^^^^^^^
  File "query.py", line 32, in query_user
    return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)
                               ~~~~~~~~~~~~~~~~~~^^^^^
TypeError: 'NoneType' object is not subscriptable
@end example

複雑な算術式と同様に:

@example
Traceback (most recent call last):
  File "calculation.py", line 54, in <module>
    result = (x / y / z) * (a / b / c)
              ~~~~~~^~~
ZeroDivisionError: division by zero
@end example

さらに、強化されたトレースバック機能で使用される情報は、一般的な API を介して利用可能になり、 @ref{4aa,,bytecode} @ref{7cf,,命令} とソースコードの場所を関連付けるために使用できます。この情報は次を使用して取得できます:


@itemize -

@item 
Python の @ref{7d0,,codeobject.co_positions()} メソッド。

@item 
C API の @ref{7d1,,PyCode_Addr2Location()} 関数。
@end itemize

詳細は 
@geindex Python Enhancement Proposals; PEP 657
PEP 657@footnote{https://peps.python.org/pep-0657/} を参照してください。(Pablo Galindo, Batuhan Taskaya, Ammar Askar の貢献による bpo-43950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43950})

@cartouche
@quotation 注釈 
この機能は @ref{7d2,,コードオブジェクト} に列の位置を保存する必要があり、その結果コンパイルされた Pthon ファイルのインタープリタのメモリ使用量とディスク使用量がわずかに増加する可能性があります。余分な情報を保存せず、余分なトレースバック情報を表示しないようにするには @ref{16f,,-X no_debug_ranges} コマンドライン引数または 
@geindex PYTHONNODEBUGRANGES
@geindex 環境変数; PYTHONNODEBUGRANGES
@ref{7d3,,PYTHONNODEBUGRANGES} 環境変数を使用してください。
@end quotation
@end cartouche

@node PEP 654 例外グループと except*,PEP 678 ノートによって例外を充実させる,PEP 657 トレースバックのエラー位置の詳細化,新しい機能<6>
@anchor{whatsnew/3 11 pep-654-exception-groups-and-except}@anchor{7d4}@anchor{whatsnew/3 11 whatsnew311-pep654}@anchor{7be}
@subsubsection PEP 654: 例外グループと @code{except*}


@geindex Python Enhancement Proposals; PEP 654
PEP 654@footnote{https://peps.python.org/pep-0654/} では、プログラムが無関係な複数の例外を同時に送出させて処理できるようにする言語機能が導入されています。組み込み型 @ref{4d2,,ExceptionGroup} と @ref{566,,BaseExceptionGroup} を使用すると、例外をグループ化して一緒に送出することができます。また、新しい @ref{1ac,,except*} 構文は、 @ref{1ab,,except} を例外グループのサブグループにマッチするように一般化したものです。

より詳しくは 
@geindex Python Enhancement Proposals; PEP 654
PEP 654@footnote{https://peps.python.org/pep-0654/} を参照してください。

(Irit Katriel の貢献による bpo-45292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45292}。PEP はIrit Katriel, Yury Selivanov, Guido van Rossum によって作成されました。)

@node PEP 678 ノートによって例外を充実させる,Windows py exe ランチャーの改善,PEP 654 例外グループと except*,新しい機能<6>
@anchor{whatsnew/3 11 pep-678-exceptions-can-be-enriched-with-notes}@anchor{7d5}@anchor{whatsnew/3 11 whatsnew311-pep678}@anchor{7bf}
@subsubsection PEP 678: ノートによって例外を充実させる


@ref{7d6,,BaseException} に @ref{7d7,,add_note()} メソッドが追加されました。これは例外が送出された時点では利用できないコンテキスト情報を例外に付与するために使用できます。追加された注釈はデフォルトのトレースバックに表示されます。

より詳しくは 
@geindex Python Enhancement Proposals; PEP 678
PEP 678@footnote{https://peps.python.org/pep-0678/} を参照してください。

(Irit Katriel の貢献による bpo-45607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45607}。PEP は Zac Hatfield-Dodds によって作成されました。)

@node Windows py exe ランチャーの改善,,PEP 678 ノートによって例外を充実させる,新しい機能<6>
@anchor{whatsnew/3 11 whatsnew311-windows-launcher}@anchor{7d8}@anchor{whatsnew/3 11 windows-py-exe-launcher-improvements}@anchor{7d9}
@subsubsection Windows @code{py.exe} ランチャーの改善


Python 3.11 に含まれる @ref{7da,,Python install manager} のコピーが大幅に更新されました。 
@geindex Python Enhancement Proposals; PEP 514
PEP 514@footnote{https://peps.python.org/pep-0514/} で定義されているように、制限付きの @code{-@var{<major>}.@var{<minor>}} の代わりに @code{-V:@var{<company>}/@var{<tag>}} 引数を使用した company/tag 構文をサポートするようになりました。これにより、 python.org@footnote{https://www.python.org} でホストされている @code{PythonCore} 以外のディストリビューションを起動できるようになります。

When using @code{-V:} selectors, either company or tag can be omitted, but all
installs will be searched. For example, @code{-V:OtherPython/} will select the
"best" tag registered for @code{OtherPython}, while @code{-V:3.11} or @code{-V:/3.11}
will select the "best" distribution with tag @code{3.11}.

When using the legacy @code{-@var{<major>}}, @code{-@var{<major>}.@var{<minor>}},
@code{-@var{<major>}-@var{<bitness>}} or @code{-@var{<major>}.@var{<minor>}-@var{<bitness>}} arguments,
all existing behaviour should be preserved from past versions,
and only releases from @code{PythonCore} will be selected.
However, the @code{-64} suffix now implies "not 32-bit" (not necessarily x86-64),
as there are multiple supported 64-bit platforms.
32-bit runtimes are detected by checking the runtime's tag for a @code{-32} suffix.
All releases of Python since 3.5 have included this in their 32-bit builds.
@anchor{whatsnew/3 11 new-feat-related-type-hints-311}@anchor{7db}
@node 型ヒントに関連する新しい機能<2>,その他の言語変更<3>,新しい機能<6>,What's New In Python 3 11
@anchor{whatsnew/3 11 new-features-related-to-type-hints}@anchor{7dc}@anchor{whatsnew/3 11 whatsnew311-typing-features}@anchor{7dd}
@subsection 型ヒントに関連する新しい機能


This section covers major changes affecting 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} type hints and
the @ref{10a,,typing} module.

@menu
* PEP 646; Variadic generics: PEP 646 Variadic generics. 
* PEP 655; Marking individual TypedDict items as required or not-required: PEP 655 Marking individual TypedDict items as required or not-required. 
* PEP 673; Self 型: PEP 673 Self 型. 
* PEP 675; Arbitrary literal string type: PEP 675 Arbitrary literal string type. 
* PEP 681; Data class transforms: PEP 681 Data class transforms. 
* PEP 563 may not be the future:: 

@end menu

@node PEP 646 Variadic generics,PEP 655 Marking individual TypedDict items as required or not-required,,型ヒントに関連する新しい機能<2>
@anchor{whatsnew/3 11 pep-646-variadic-generics}@anchor{7de}@anchor{whatsnew/3 11 whatsnew311-pep646}@anchor{7c4}
@subsubsection PEP 646: Variadic generics


@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} previously introduced @ref{486,,TypeVar}, enabling creation
of generics parameterised with a single type. 
@geindex Python Enhancement Proposals; PEP 646
PEP 646@footnote{https://peps.python.org/pep-0646/} adds
@ref{488,,TypeVarTuple}, enabling parameterisation
with an `arbitrary' number of types. In other words,
a @ref{488,,TypeVarTuple} is a `variadic' type variable,
enabling `variadic' generics.

This enables a wide variety of use cases.
In particular, it allows the type of array-like structures
in numerical computing libraries such as NumPy and TensorFlow to be
parameterised with the array `shape'. Static type checkers will now
be able to catch shape-related bugs in code that uses these libraries.

より詳しくは 
@geindex Python Enhancement Proposals; PEP 646
PEP 646@footnote{https://peps.python.org/pep-0646/} を参照してください。

(Contributed by Matthew Rahtz in bpo-43224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43224}, with contributions by
Serhiy Storchaka and Jelle Zijlstra. PEP written by Mark Mendoza, Matthew
Rahtz, Pradeep Kumar Srinivasan, and Vincent Siles.)

@node PEP 655 Marking individual TypedDict items as required or not-required,PEP 673 Self 型,PEP 646 Variadic generics,型ヒントに関連する新しい機能<2>
@anchor{whatsnew/3 11 pep-655-marking-individual-typeddict-items-as-required-or-not-required}@anchor{7df}@anchor{whatsnew/3 11 whatsnew311-pep655}@anchor{7c5}
@subsubsection PEP 655: Marking individual @code{TypedDict} items as required or not-required


@ref{7e0,,Required} and @ref{7e1,,NotRequired} provide a
straightforward way to mark whether individual items in a
@ref{332,,TypedDict} must be present. Previously, this was only possible
using inheritance.

All fields are still required by default,
unless the `total' parameter is set to @code{False},
in which case all fields are still not-required by default.
For example, the following specifies a @code{TypedDict}
with one required and one not-required key:

@example
class Movie(TypedDict):
   title: str
   year: NotRequired[int]

m1: Movie = @{"title": "Black Panther", "year": 2018@}  # OK
m2: Movie = @{"title": "Star Wars"@}  # OK (year is not required)
m3: Movie = @{"year": 2022@}  # ERROR (missing required field title)
@end example

The following definition is equivalent:

@example
class Movie(TypedDict, total=False):
   title: Required[str]
   year: int
@end example

より詳しくは 
@geindex Python Enhancement Proposals; PEP 655
PEP 655@footnote{https://peps.python.org/pep-0655/} を参照してください。

(Contributed by David Foster and Jelle Zijlstra in bpo-47087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47087}. PEP
written by David Foster.)

@node PEP 673 Self 型,PEP 675 Arbitrary literal string type,PEP 655 Marking individual TypedDict items as required or not-required,型ヒントに関連する新しい機能<2>
@anchor{whatsnew/3 11 pep-673-self-type}@anchor{7e2}@anchor{whatsnew/3 11 whatsnew311-pep673}@anchor{7c6}
@subsubsection PEP 673: @code{Self} 型


The new @ref{7e3,,Self} annotation provides a simple and intuitive
way to annotate methods that return an instance of their class. This
behaves the same as the @ref{486,,TypeVar}-based approach
@geindex Python Enhancement Proposals; PEP 484#annotating-instance-and-class-methods
specified in PEP 484@footnote{https://peps.python.org/pep-0484/#annotating-instance-and-class-methods},
but is more concise and easier to follow.

Common use cases include alternative constructors provided as
@ref{48e,,classmethod}s,
and @ref{7e4,,__enter__()} methods that return @code{self}:

@example
class MyLock:
    def __enter__(self) -> Self:
        self.lock()
        return self

    ...

class MyInt:
    @@classmethod
    def fromhex(cls, s: str) -> Self:
        return cls(int(s, 16))

    ...
@end example

@ref{7e3,,Self} can also be used to annotate method parameters
or attributes of the same type as their enclosing class.

より詳しくは 
@geindex Python Enhancement Proposals; PEP 673
PEP 673@footnote{https://peps.python.org/pep-0673/} を参照してください。

(Contributed by James Hilton-Balfe in bpo-46534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46534}. PEP written by
Pradeep Kumar Srinivasan and James Hilton-Balfe.)

@node PEP 675 Arbitrary literal string type,PEP 681 Data class transforms,PEP 673 Self 型,型ヒントに関連する新しい機能<2>
@anchor{whatsnew/3 11 pep-675-arbitrary-literal-string-type}@anchor{7e5}@anchor{whatsnew/3 11 whatsnew311-pep675}@anchor{7c7}
@subsubsection PEP 675: Arbitrary literal string type


The new @ref{7e6,,LiteralString} annotation may be used to indicate
that a function parameter can be of any literal string type. This allows
a function to accept arbitrary literal string types, as well as strings
created from other literal strings. Type checkers can then
enforce that sensitive functions, such as those that execute SQL
statements or shell commands, are called only with static arguments,
providing protection against injection attacks.

For example, a SQL query function could be annotated as follows:

@example
def run_query(sql: LiteralString) -> ...
    ...

def caller(
    arbitrary_string: str,
    query_string: LiteralString,
    table_name: LiteralString,
) -> None:
    run_query("SELECT * FROM students")       # ok
    run_query(query_string)                   # ok
    run_query("SELECT * FROM " + table_name)  # ok
    run_query(arbitrary_string)               # type checker error
    run_query(                                # type checker error
        f"SELECT * FROM students WHERE name = @{arbitrary_string@}"
    )
@end example

より詳しくは 
@geindex Python Enhancement Proposals; PEP 675
PEP 675@footnote{https://peps.python.org/pep-0675/} を参照してください。

(Contributed by Jelle Zijlstra in bpo-47088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47088}. PEP written by Pradeep
Kumar Srinivasan and Graham Bleaney.)

@node PEP 681 Data class transforms,PEP 563 may not be the future,PEP 675 Arbitrary literal string type,型ヒントに関連する新しい機能<2>
@anchor{whatsnew/3 11 pep-681-data-class-transforms}@anchor{7e7}@anchor{whatsnew/3 11 whatsnew311-pep681}@anchor{7c8}
@subsubsection PEP 681: Data class transforms


@ref{6fb,,dataclass_transform} may be used to
decorate a class, metaclass, or a function that is itself a decorator.
The presence of @code{@@dataclass_transform()} tells a static type checker that the
decorated object performs runtime "magic" that transforms a class,
giving it @ref{4e1,,dataclass}-like behaviors.

例えば:

@example
# The create_model decorator is defined by a library.
@@typing.dataclass_transform()
def create_model(cls: Type[T]) -> Type[T]:
    cls.__init__ = ...
    cls.__eq__ = ...
    cls.__ne__ = ...
    return cls

# The create_model decorator can now be used to create new model classes:
@@create_model
class CustomerModel:
    id: int
    name: str

c = CustomerModel(id=327, name="Eric Idle")
@end example

より詳しくは 
@geindex Python Enhancement Proposals; PEP 681
PEP 681@footnote{https://peps.python.org/pep-0681/} を参照してください。

(Contributed by Jelle Zijlstra in gh-91860@footnote{https://github.com/python/cpython/issues/91860}. PEP written by
Erik De Bonte and Eric Traut.)

@node PEP 563 may not be the future,,PEP 681 Data class transforms,型ヒントに関連する新しい機能<2>
@anchor{whatsnew/3 11 pep-563-may-not-be-the-future}@anchor{7e8}@anchor{whatsnew/3 11 whatsnew311-pep563-deferred}@anchor{7e9}
@subsubsection PEP 563 may not be the future


@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/} Postponed Evaluation of Annotations
(the @code{from __future__ import annotations} @ref{45d,,future statement})
that was originally planned for release in Python 3.10
has been put on hold indefinitely.
See this message from the Steering Council@footnote{https://mail.python.org/archives/list/python-dev@@python.org/message/VIZEBX5EYMSYIJNDBF6DMUMZOCWHARSO/}
for more information.

@node その他の言語変更<3>,その他の CPython の実装の変更,型ヒントに関連する新しい機能<2>,What's New In Python 3 11
@anchor{whatsnew/3 11 other-language-changes}@anchor{7ea}@anchor{whatsnew/3 11 whatsnew311-other-lang-changes}@anchor{7eb}
@subsection その他の言語変更



@itemize *

@item 
Starred unpacking expressions can now be used in @ref{34a,,for} statements.
(See bpo-46725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46725} for more details.)

@item 
Asynchronous @ref{7ec,,comprehensions} are now allowed
inside comprehensions in @ref{7ed,,asynchronous functions}.
Outer comprehensions implicitly become asynchronous in this case.
(Contributed by Serhiy Storchaka in bpo-33346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33346}.)

@item 
A @ref{198,,TypeError} is now raised instead of an @ref{5f0,,AttributeError} in
@ref{186,,with} statements and @ref{7ee,,contextlib.ExitStack.enter_context()}
for objects that do not support the @ref{1e1,,context manager} protocol,
and in @ref{185,,async with} statements and
@ref{7ef,,contextlib.AsyncExitStack.enter_async_context()}
for objects not supporting the @ref{7f0,,asynchronous context manager} protocol.
(Contributed by Serhiy Storchaka in bpo-12022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12022} and bpo-44471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44471}.)

@item 
Added @ref{7f1,,object.__getstate__()}, which provides the default
implementation of the @code{__getstate__()} method. @ref{29,,copy}ing
and @ref{ab,,pickle}ing instances of subclasses of builtin types
@ref{344,,bytearray}, @ref{184,,set}, @ref{7f2,,frozenset},
@ref{7f3,,collections.OrderedDict}, @ref{7f4,,collections.deque},
@ref{7f5,,weakref.WeakSet}, and @ref{7f6,,datetime.tzinfo} now copies and
pickles instance attributes implemented as @ref{7f7,,slots}.
This change has an unintended side effect: It trips up a small minority
of existing Python projects not expecting @ref{7f1,,object.__getstate__()} to
exist. See the later comments on gh-70766@footnote{https://github.com/python/cpython/issues/70766} for discussions of what
workarounds such code may need.
(Contributed by Serhiy Storchaka in bpo-26579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26579}.)
@end itemize
@anchor{whatsnew/3 11 whatsnew311-pythonsafepath}@anchor{7c3}

@itemize *

@item 
Added a @ref{7c1,,-P} command line option
and a 
@geindex PYTHONSAFEPATH
@geindex 環境変数; PYTHONSAFEPATH
@ref{7c2,,PYTHONSAFEPATH} environment variable,
which disable the automatic prepending to @ref{3e4,,sys.path}
of the script's directory when running a script,
or the current directory when using @ref{1a8,,-c} and @ref{23c,,-m}.
This ensures only stdlib and installed modules
are picked up by @ref{7f8,,import},
and avoids unintentionally or maliciously shadowing modules
with those in a local (and typically user-writable) directory.
(Contributed by Victor Stinner in gh-57684@footnote{https://github.com/python/cpython/issues/57684}.)

@item 
A @code{"z"} option was added to the @ref{4f9,,書式指定ミニ言語仕様} that
coerces negative to positive zero after rounding to the format precision.
See 
@geindex Python Enhancement Proposals; PEP 682
PEP 682@footnote{https://peps.python.org/pep-0682/} for more details.
(Contributed by John Belmonte in gh-90153@footnote{https://github.com/python/cpython/issues/90153}.)

@item 
Bytes are no longer accepted on @ref{3e4,,sys.path}.  Support broke sometime
between Python 3.2 and 3.6, with no one noticing until after Python 3.10.0
was released. In addition, bringing back support would be problematic due to
interactions between @ref{7f9,,-b} and @ref{7fa,,sys.path_importer_cache} when
there is a mixture of @ref{169,,str} and @ref{192,,bytes} keys.
(Contributed by Thomas Grainger in gh-91181@footnote{https://github.com/python/cpython/issues/91181}.)
@end itemize

@node その他の CPython の実装の変更,新たなモジュール<3>,その他の言語変更<3>,What's New In Python 3 11
@anchor{whatsnew/3 11 other-cpython-implementation-changes}@anchor{7fb}@anchor{whatsnew/3 11 whatsnew311-other-implementation-changes}@anchor{7fc}
@subsection その他の CPython の実装の変更



@itemize *

@item 
The special methods @ref{7fd,,__complex__()} for @ref{197,,complex}
and @ref{7fe,,__bytes__()} for @ref{192,,bytes} are implemented to support
the @ref{7ff,,typing.SupportsComplex} and @ref{800,,typing.SupportsBytes} protocols.
(Contributed by Mark Dickinson and Donghee Na in bpo-24234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24234}.)

@item 
@code{siphash13} is added as a new internal hashing algorithm.
It has similar security properties as @code{siphash24},
but it is slightly faster for long inputs.
@ref{169,,str}, @ref{192,,bytes}, and some other types
now use it as the default algorithm for @ref{801,,hash()}.
@geindex Python Enhancement Proposals; PEP 552
PEP 552@footnote{https://peps.python.org/pep-0552/} @ref{802,,hash-based .pyc files}
now use @code{siphash13} too.
(Contributed by Inada Naoki in bpo-29410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29410}.)

@item 
When an active exception is re-raised by a @ref{803,,raise} statement with no parameters,
the traceback attached to this exception is now always @code{sys.exc_info()[1].__traceback__}.
This means that changes made to the traceback in the current @ref{1ab,,except} clause are
reflected in the re-raised exception.
(Contributed by Irit Katriel in bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}.)

@item 
The interpreter state's representation of handled exceptions
(aka @code{exc_info} or @code{_PyErr_StackItem})
now only has the @code{exc_value} field; @code{exc_type} and @code{exc_traceback}
have been removed, as they can be derived from @code{exc_value}.
(Contributed by Irit Katriel in bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}.)

@item 
A new @ref{804,,command line option}, @code{AppendPath},
has been added for the Windows installer.
It behaves similarly to @code{PrependPath},
but appends the install and scripts directories instead of prepending them.
(Contributed by Bastian Neuburger in bpo-44934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44934}.)

@item 
The @ref{805,,PyConfig.module_search_paths_set} field must now be set to @code{1} for
initialization to use @ref{643,,PyConfig.module_search_paths} to initialize
@ref{3e4,,sys.path}. Otherwise, initialization will recalculate the path and replace
any values added to @code{module_search_paths}.

@item 
The output of the @ref{806,,--help} option now fits in 50 lines/80 columns.
Information about @ref{807,,Python environment variables}
and @ref{16f,,-X} options is now available using the respective
@ref{808,,--help-env} and @ref{809,,--help-xoptions} flags,
and with the new @ref{80a,,--help-all}.
(Contributed by Éric Araujo in bpo-46142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46142}.)

@item 
Converting between @ref{19b,,int} and @ref{169,,str} in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
now raises a @ref{2ec,,ValueError} if the number of digits in string form is
above a limit to avoid potential denial of service attacks due to the
algorithmic complexity. This is a mitigation for 
@geindex Common Vulnerabilities and Exposures; CVE 2020-10735
CVE 2020-10735@footnote{https://www.cve.org/CVERecord?id=CVE-2020-10735}.
This limit can be configured or disabled by environment variable, command
line flag, or @ref{df,,sys} APIs. See the @ref{80b,,integer string conversion length limitation} documentation.  The default limit
is 4300 digits in string form.
@end itemize

@node 新たなモジュール<3>,改良されたモジュール<3>,その他の CPython の実装の変更,What's New In Python 3 11
@anchor{whatsnew/3 11 new-modules}@anchor{80c}@anchor{whatsnew/3 11 whatsnew311-new-modules}@anchor{80d}
@subsection 新たなモジュール



@itemize *

@item 
@ref{102,,tomllib}: For parsing TOML@footnote{https://toml.io/}.
See 
@geindex Python Enhancement Proposals; PEP 680
PEP 680@footnote{https://peps.python.org/pep-0680/} for more details.
(Contributed by Taneli Hukkinen in bpo-40059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40059}.)

@item 
@ref{122,,wsgiref.types}:
@geindex Python Enhancement Proposals; PEP 3333
WSGI@footnote{https://peps.python.org/pep-3333/}-specific types for static type checking.
(Contributed by Sebastian Rittau in bpo-42012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42012}.)
@end itemize

@node 改良されたモジュール<3>,最適化<4>,新たなモジュール<3>,What's New In Python 3 11
@anchor{whatsnew/3 11 improved-modules}@anchor{80e}@anchor{whatsnew/3 11 whatsnew311-improved-modules}@anchor{80f}
@subsection 改良されたモジュール


@menu
* asyncio: asyncio<6>. 
* contextlib:: 
* データクラス:: 
* datetime: datetime<2>. 
* enum: enum<3>. 
* fcntl:: 
* fractions: fractions<4>. 
* functools: functools<2>. 
* gzip: gzip<2>. 
* hashlib: hashlib<2>. 
* IDLE と idelelib:: 
* inspect: inspect<3>. 
* locale: locale<3>. 
* logging:: 
* math: math<4>. 
* operator: operator<2>. 
* os: os<4>. 
* pathlib: pathlib<7>. 
* re: re<4>. 
* shutil: shutil<3>. 
* socket: socket<2>. 
* sqlite3: sqlite3<5>. 
* string:: 
* sys: sys<4>. 
* sysconfig: sysconfig<2>. 
* tempfile: tempfile<3>. 
* threading: threading<3>. 
* time: time<2>. 
* tkinter: tkinter<4>. 
* traceback: traceback<2>. 
* typing: typing<5>. 
* unicodedata: unicodedata<4>. 
* unittest: unittest<5>. 
* venv: venv<2>. 
* warnings: warnings<2>. 
* zipfile: zipfile<2>. 

@end menu

@node asyncio<6>,contextlib,,改良されたモジュール<3>
@anchor{whatsnew/3 11 asyncio}@anchor{810}@anchor{whatsnew/3 11 whatsnew311-asyncio}@anchor{811}
@subsubsection asyncio



@itemize *

@item 
Added the @ref{4d1,,TaskGroup} class,
an @ref{812,,asynchronous context manager}
holding a group of tasks that will wait for all of them upon exit.
For new code this is recommended over using
@ref{1c9,,create_task()} and @ref{813,,gather()} directly.
(Contributed by Yury Selivanov and others in gh-90908@footnote{https://github.com/python/cpython/issues/90908}.)

@item 
Added @ref{814,,timeout()}, an asynchronous context manager for
setting a timeout on asynchronous operations. For new code this is
recommended over using @ref{815,,wait_for()} directly.
(Contributed by Andrew Svetlov in gh-90927@footnote{https://github.com/python/cpython/issues/90927}.)

@item 
Added the @ref{2f5,,Runner} class, which exposes the machinery
used by @ref{2f3,,run()}.
(Contributed by Andrew Svetlov in gh-91218@footnote{https://github.com/python/cpython/issues/91218}.)

@item 
Added the @ref{816,,Barrier} class to the synchronization
primitives in the asyncio library, and the related
@ref{817,,BrokenBarrierError} exception.
(Contributed by Yves Duprat and Andrew Svetlov in gh-87518@footnote{https://github.com/python/cpython/issues/87518}.)

@item 
Added keyword argument `all_errors' to @ref{818,,asyncio.loop.create_connection()}
so that multiple connection errors can be raised as an @ref{4d2,,ExceptionGroup}.

@item 
Added the @ref{819,,asyncio.StreamWriter.start_tls()} method for
upgrading existing stream-based connections to TLS.
(Contributed by Ian Good in bpo-34975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34975}.)

@item 
Added raw datagram socket functions to the event loop:
@ref{81a,,sock_sendto()},
@ref{81b,,sock_recvfrom()} and
@ref{81c,,sock_recvfrom_into()}.
These have implementations in @ref{314,,SelectorEventLoop} and
@ref{81d,,ProactorEventLoop}.
(Contributed by Alex Grönholm in bpo-46805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46805}.)

@item 
Added @ref{4d5,,cancelling()} and
@ref{4d6,,uncancel()} methods to @ref{1c7,,Task}.
These are primarily intended for internal use,
notably by @ref{4d1,,TaskGroup}.
@end itemize

@node contextlib,データクラス,asyncio<6>,改良されたモジュール<3>
@anchor{whatsnew/3 11 contextlib}@anchor{81e}@anchor{whatsnew/3 11 whatsnew311-contextlib}@anchor{81f}
@subsubsection contextlib



@itemize *

@item 
Added non parallel-safe @ref{820,,chdir()} context manager to change
the current working directory and then restore it on exit. Simple wrapper
around @ref{821,,chdir()}. (Contributed by Filipe Laíns in bpo-25625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25625})
@end itemize

@node データクラス,datetime<2>,contextlib,改良されたモジュール<3>
@anchor{whatsnew/3 11 dataclasses}@anchor{822}@anchor{whatsnew/3 11 whatsnew311-dataclasses}@anchor{823}
@subsubsection データクラス



@itemize *

@item 
Change field default mutability check, allowing only defaults which are
@ref{824,,hashable} instead of any object which is not an instance of
@ref{183,,dict}, @ref{24d,,list} or @ref{184,,set}. (Contributed by Eric V. Smith in
bpo-44674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44674}.)
@end itemize

@node datetime<2>,enum<3>,データクラス,改良されたモジュール<3>
@anchor{whatsnew/3 11 datetime}@anchor{825}@anchor{whatsnew/3 11 whatsnew311-datetime}@anchor{826}
@subsubsection datetime



@itemize *

@item 
Add @ref{713,,datetime.UTC}, a convenience alias for
@ref{827,,datetime.timezone.utc}. (Contributed by Kabir Kwatra in gh-91973@footnote{https://github.com/python/cpython/issues/91973}.)

@item 
@ref{828,,datetime.date.fromisoformat()}, @ref{829,,datetime.time.fromisoformat()} and
@ref{82a,,datetime.datetime.fromisoformat()} can now be used to parse most ISO 8601
formats (barring only those that support fractional hours and minutes).
(Contributed by Paul Ganssle in gh-80010@footnote{https://github.com/python/cpython/issues/80010}.)
@end itemize

@node enum<3>,fcntl,datetime<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 enum}@anchor{82b}@anchor{whatsnew/3 11 whatsnew311-enum}@anchor{82c}
@subsubsection enum



@itemize *

@item 
Renamed @code{EnumMeta} to @ref{4f7,,EnumType}
(@code{EnumMeta} kept as an alias).

@item 
Added @ref{82d,,StrEnum},
with members that can be used as (and must be) strings.

@item 
Added @ref{82e,,ReprEnum},
which only modifies the @ref{82f,,__repr__()} of members
while returning their literal values (rather than names)
for @ref{830,,__str__()} and @ref{831,,__format__()}
(used by @ref{169,,str()}, @ref{199,,format()} and @ref{66b,,f-string}s).

@item 
Changed @ref{832,,Enum.__format__()} (the default for
@ref{199,,format()}, @ref{833,,str.format()} and @ref{66b,,f-string}s) to always produce
the same result as @ref{834,,Enum.__str__()}:  for enums inheriting from
@ref{82e,,ReprEnum} it will be the member's value; for all other enums
it will be the enum and member name (e.g. @code{Color.RED}).

@item 
Added a new `boundary' class parameter to @ref{835,,Flag} enums
and the @ref{836,,FlagBoundary} enum with its options,
to control how to handle out-of-range flag values.

@item 
Added the @ref{837,,verify()} enum decorator
and the @ref{838,,EnumCheck} enum with its options,
to check enum classes against several specific constraints.

@item 
Added the @ref{839,,member()} and @ref{83a,,nonmember()} decorators,
to ensure the decorated object is/is not converted to an enum member.

@item 
Added the @ref{83b,,property()} decorator,
which works like @ref{4b3,,property()} except for enums.
Use this instead of @ref{83c,,types.DynamicClassAttribute()}.

@item 
Added the @ref{83d,,global_enum()} enum decorator,
which adjusts @ref{82f,,__repr__()} and @ref{830,,__str__()}
to show values as members of their module rather than the enum class.
For example, @code{'re.ASCII'} for the @ref{83e,,ASCII} member
of @ref{83f,,re.RegexFlag} rather than @code{'RegexFlag.ASCII'}.

@item 
Enhanced @ref{835,,Flag} to support
@ref{840,,len()}, iteration and @ref{34b,,in}/@ref{841,,not in} on its members.
For example, the following now works:
@code{len(AFlag(3)) == 2 and list(AFlag(3)) == (AFlag.ONE, AFlag.TWO)}

@item 
Changed @ref{842,,Enum} and @ref{835,,Flag}
so that members are now defined
before @ref{843,,__init_subclass__()} is called;
@ref{844,,dir()} now includes methods, etc., from mixed-in data types.

@item 
Changed @ref{835,,Flag}
to only consider primary values (power of two) canonical
while composite values (@code{3}, @code{6}, @code{10}, etc.) are considered aliases;
inverted flags are coerced to their positive equivalent.
@end itemize

@node fcntl,fractions<4>,enum<3>,改良されたモジュール<3>
@anchor{whatsnew/3 11 fcntl}@anchor{845}@anchor{whatsnew/3 11 whatsnew311-fcntl}@anchor{846}
@subsubsection fcntl



@itemize *

@item 
On FreeBSD, the @code{F_DUP2FD} and @code{F_DUP2FD_CLOEXEC} flags respectively
are supported, the former equals to @code{dup2} usage while the latter set
the @code{FD_CLOEXEC} flag in addition.
@end itemize

@node fractions<4>,functools<2>,fcntl,改良されたモジュール<3>
@anchor{whatsnew/3 11 fractions}@anchor{847}@anchor{whatsnew/3 11 whatsnew311-fractions}@anchor{848}
@subsubsection fractions



@itemize *

@item 
Support 
@geindex Python Enhancement Proposals; PEP 515
PEP 515@footnote{https://peps.python.org/pep-0515/}-style initialization of @ref{213,,Fraction} from
string.  (Contributed by Sergey B Kirpichev in bpo-44258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44258}.)

@item 
@ref{213,,Fraction} now implements an @code{__int__} method, so
that an @code{isinstance(some_fraction, typing.SupportsInt)} check passes.
(Contributed by Mark Dickinson in bpo-44547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44547}.)
@end itemize

@node functools<2>,gzip<2>,fractions<4>,改良されたモジュール<3>
@anchor{whatsnew/3 11 functools}@anchor{849}@anchor{whatsnew/3 11 whatsnew311-functools}@anchor{84a}
@subsubsection functools



@itemize *

@item 
@ref{84b,,functools.singledispatch()} now supports @ref{2a7,,types.UnionType}
and @ref{2a8,,typing.Union} as annotations to the dispatch argument.:

@example
>>> from functools import singledispatch
>>> @@singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)
...
>>> @@fun.register
... def _(arg: int | float, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> from typing import Union
>>> @@fun.register
... def _(arg: Union[list, set], verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)
...
@end example

(Contributed by Yurii Karabas in bpo-46014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46014}.)
@end itemize

@node gzip<2>,hashlib<2>,functools<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 gzip}@anchor{84c}@anchor{whatsnew/3 11 whatsnew311-gzip}@anchor{84d}
@subsubsection gzip



@itemize *

@item 
The @ref{84e,,gzip.compress()} function is now faster when used with the
`mtime=0' argument as it delegates the compression entirely to a single
@ref{84f,,zlib.compress()} operation. There is one side effect of this change: The
gzip file header contains an "OS" byte in its header. That was traditionally
always set to a value of 255 representing "unknown" by the @ref{6b,,gzip}
module. Now, when using @ref{84e,,compress()} with `mtime=0', it may be
set to a different value by the underlying zlib C library Python was linked
against.
(See gh-112346@footnote{https://github.com/python/cpython/issues/112346} for details on the side effect.)
@end itemize

@node hashlib<2>,IDLE と idelelib,gzip<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 hashlib}@anchor{850}@anchor{whatsnew/3 11 whatsnew311-hashlib}@anchor{851}
@subsubsection hashlib



@itemize *

@item 
@ref{852,,hashlib.blake2b()} and @ref{853,,hashlib.blake2s()} now prefer libb2@footnote{https://www.blake2.net/}
over Python's vendored copy.
(Contributed by Christian Heimes in bpo-47095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47095}.)

@item 
The internal @code{_sha3} module with SHA3 and SHAKE algorithms now uses
`tiny_sha3' instead of the `Keccak Code Package' to reduce code and binary
size. The @ref{6c,,hashlib} module prefers optimized SHA3 and SHAKE
implementations from OpenSSL. The change affects only installations without
OpenSSL support.
(Contributed by Christian Heimes in bpo-47098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47098}.)

@item 
Add @ref{854,,hashlib.file_digest()}, a helper function for efficient hashing
of files or file-like objects.
(Contributed by Christian Heimes in gh-89313@footnote{https://github.com/python/cpython/issues/89313}.)
@end itemize

@node IDLE と idelelib,inspect<3>,hashlib<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 idle-and-idlelib}@anchor{855}@anchor{whatsnew/3 11 whatsnew311-idle}@anchor{856}
@subsubsection IDLE と idelelib



@itemize *

@item 
Apply syntax highlighting to @code{.pyi} files. (Contributed by Alex
Waygood and Terry Jan Reedy in bpo-45447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45447}.)

@item 
Include prompts when saving Shell with inputs and outputs.
(Contributed by Terry Jan Reedy in gh-95191@footnote{https://github.com/python/cpython/issues/95191}.)
@end itemize

@node inspect<3>,locale<3>,IDLE と idelelib,改良されたモジュール<3>
@anchor{whatsnew/3 11 inspect}@anchor{857}@anchor{whatsnew/3 11 whatsnew311-inspect}@anchor{858}
@subsubsection inspect



@itemize *

@item 
Add @ref{859,,getmembers_static()} to return all members without
triggering dynamic lookup via the descriptor protocol. (Contributed by
Weipeng Hong in bpo-30533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30533}.)

@item 
Add @ref{85a,,ismethodwrapper()}
for checking if the type of an object is a @ref{85b,,MethodWrapperType}.
(Contributed by Hakan Çelik in bpo-29418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29418}.)

@item 
Change the frame-related functions in the @ref{82,,inspect} module to return new
@ref{85c,,FrameInfo} and @ref{85d,,Traceback} class instances
(backwards compatible with the previous @ref{85e,,named tuple}-like interfaces)
that includes the extended 
@geindex Python Enhancement Proposals; PEP 657
PEP 657@footnote{https://peps.python.org/pep-0657/} position information (end
line number, column and end column). The affected functions are:


@itemize *

@item 
@ref{85f,,inspect.getframeinfo()}

@item 
@ref{860,,inspect.getouterframes()}

@item 
@ref{861,,inspect.getinnerframes()},

@item 
@ref{862,,inspect.stack()}

@item 
@ref{863,,inspect.trace()}
@end itemize

(Contributed by Pablo Galindo in gh-88116@footnote{https://github.com/python/cpython/issues/88116}.)
@end itemize

@node locale<3>,logging,inspect<3>,改良されたモジュール<3>
@anchor{whatsnew/3 11 locale}@anchor{864}@anchor{whatsnew/3 11 whatsnew311-locale}@anchor{865}
@subsubsection locale



@itemize *

@item 
Add @ref{329,,locale.getencoding()} to get the current locale encoding. It is similar to
@code{locale.getpreferredencoding(False)} but ignores the
@ref{866,,Python UTF-8 Mode}.
@end itemize

@node logging,math<4>,locale<3>,改良されたモジュール<3>
@anchor{whatsnew/3 11 logging}@anchor{867}@anchor{whatsnew/3 11 whatsnew311-logging}@anchor{868}
@subsubsection logging



@itemize *

@item 
Added @ref{869,,getLevelNamesMapping()}
to return a mapping from logging level names (e.g. @code{'CRITICAL'})
to the values of their corresponding @ref{86a,,ロギングレベル} (e.g. @code{50}, by default).
(Contributed by Andrei Kulakovin in gh-88024@footnote{https://github.com/python/cpython/issues/88024}.)

@item 
Added a @ref{86b,,createSocket()} method
to @ref{86c,,SysLogHandler}, to match
@ref{86d,,SocketHandler.createSocket()}.
It is called automatically during handler initialization
and when emitting an event, if there is no active socket.
(Contributed by Kirill Pinchuk in gh-88457@footnote{https://github.com/python/cpython/issues/88457}.)
@end itemize

@node math<4>,operator<2>,logging,改良されたモジュール<3>
@anchor{whatsnew/3 11 math}@anchor{86e}@anchor{whatsnew/3 11 whatsnew311-math}@anchor{86f}
@subsubsection math



@itemize *

@item 
Add @ref{870,,math.exp2()}: return 2 raised to the power of x.
(Contributed by Gideon Mitchell in bpo-45917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45917}.)

@item 
Add @ref{871,,math.cbrt()}: return the cube root of x.
(Contributed by Ajith Ramachandran in bpo-44357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44357}.)

@item 
The behaviour of two @ref{872,,math.pow()} corner cases was changed, for
consistency with the IEEE 754 specification. The operations
@code{math.pow(0.0, -math.inf)} and @code{math.pow(-0.0, -math.inf)} now return
@code{inf}. Previously they raised @ref{2ec,,ValueError}. (Contributed by Mark
Dickinson in bpo-44339@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44339}.)

@item 
The @ref{873,,math.nan} value is now always available.
(Contributed by Victor Stinner in bpo-46917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46917}.)
@end itemize

@node operator<2>,os<4>,math<4>,改良されたモジュール<3>
@anchor{whatsnew/3 11 operator}@anchor{874}@anchor{whatsnew/3 11 whatsnew311-operator}@anchor{875}
@subsubsection operator



@itemize *

@item 
A new function @code{operator.call} has been added, such that
@code{operator.call(obj, *args, **kwargs) == obj(*args, **kwargs)}.
(Contributed by Antony Lee in bpo-44019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44019}.)
@end itemize

@node os<4>,pathlib<7>,operator<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 os}@anchor{876}@anchor{whatsnew/3 11 whatsnew311-os}@anchor{877}
@subsubsection os



@itemize *

@item 
On Windows, @ref{746,,os.urandom()} now uses @code{BCryptGenRandom()},
instead of @code{CryptGenRandom()} which is deprecated.
(Contributed by Donghee Na in bpo-44611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44611}.)
@end itemize

@node pathlib<7>,re<4>,os<4>,改良されたモジュール<3>
@anchor{whatsnew/3 11 pathlib}@anchor{878}@anchor{whatsnew/3 11 whatsnew311-pathlib}@anchor{879}
@subsubsection pathlib



@itemize *

@item 
@ref{537,,glob()} and @ref{538,,rglob()} return only
directories if `pattern' ends with a pathname components separator:
@ref{87a,,sep} or @ref{87b,,altsep}.
(Contributed by Eisuke Kawasima in bpo-22276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22276} and bpo-33392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33392}.)
@end itemize

@node re<4>,shutil<3>,pathlib<7>,改良されたモジュール<3>
@anchor{whatsnew/3 11 re}@anchor{87c}@anchor{whatsnew/3 11 whatsnew311-re}@anchor{87d}
@subsubsection re



@itemize *

@item 
Atomic grouping (@code{(?>...)}) and possessive quantifiers (@code{*+}, @code{++},
@code{?+}, @code{@{m,n@}+}) are now supported in regular expressions.
(Contributed by Jeffrey C. Jacobs and Serhiy Storchaka in bpo-433030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=433030}.)
@end itemize

@node shutil<3>,socket<2>,re<4>,改良されたモジュール<3>
@anchor{whatsnew/3 11 shutil}@anchor{87e}@anchor{whatsnew/3 11 whatsnew311-shutil}@anchor{87f}
@subsubsection shutil



@itemize *

@item 
Add optional parameter `dir_fd' in @ref{356,,shutil.rmtree()}.
(Contributed by Serhiy Storchaka in bpo-46245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46245}.)
@end itemize

@node socket<2>,sqlite3<5>,shutil<3>,改良されたモジュール<3>
@anchor{whatsnew/3 11 socket}@anchor{880}@anchor{whatsnew/3 11 whatsnew311-socket}@anchor{881}
@subsubsection socket



@itemize *

@item 
Add CAN Socket support for NetBSD.
(Contributed by Thomas Klausner in bpo-30512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30512}.)

@item 
@ref{882,,create_connection()} has an option to raise, in case of
failure to connect, an @ref{4d2,,ExceptionGroup} containing all errors
instead of only raising the last error.
(Contributed by Irit Katriel in bpo-29980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29980}.)
@end itemize

@node sqlite3<5>,string,socket<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 sqlite3}@anchor{883}@anchor{whatsnew/3 11 whatsnew311-sqlite3}@anchor{884}
@subsubsection sqlite3



@itemize *

@item 
You can now disable the authorizer by passing @ref{885,,None} to
@ref{5a9,,set_authorizer()}.
(Contributed by Erlend E. Aasland in bpo-44491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44491}.)

@item 
Collation name @ref{886,,create_collation()} can now
contain any Unicode character.  Collation names with invalid characters
now raise @ref{887,,UnicodeEncodeError} instead of @ref{305,,sqlite3.ProgrammingError}.
(Contributed by Erlend E. Aasland in bpo-44688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44688}.)

@item 
@ref{d4,,sqlite3} exceptions now include the SQLite extended error code as
@ref{888,,sqlite_errorcode} and the SQLite error name as
@ref{889,,sqlite_errorname}.
(Contributed by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland in
bpo-16379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16379} and bpo-24139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24139}.)

@item 
Add @ref{88a,,setlimit()} and
@ref{88b,,getlimit()} to @ref{54d,,sqlite3.Connection} for
setting and getting SQLite limits by connection basis.
(Contributed by Erlend E. Aasland in bpo-45243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45243}.)

@item 
@ref{d4,,sqlite3} now sets @ref{88c,,sqlite3.threadsafety} based on the default
threading mode the underlying SQLite library has been compiled with.
(Contributed by Erlend E. Aasland in bpo-45613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45613}.)

@item 
@ref{d4,,sqlite3} C callbacks now use unraisable exceptions if callback
tracebacks are enabled. Users can now register an
@ref{507,,unraisable hook handler} to improve their debug
experience.
(Contributed by Erlend E. Aasland in bpo-45828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45828}.)

@item 
Fetch across rollback no longer raises @ref{88d,,InterfaceError}.
Instead we leave it to the SQLite library to handle these cases.
(Contributed by Erlend E. Aasland in bpo-44092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44092}.)

@item 
Add @ref{88e,,serialize()} and
@ref{88f,,deserialize()} to @ref{54d,,sqlite3.Connection} for
serializing and deserializing databases.
(Contributed by Erlend E. Aasland in bpo-41930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41930}.)

@item 
Add @ref{890,,create_window_function()} to
@ref{54d,,sqlite3.Connection} for creating aggregate window functions.
(Contributed by Erlend E. Aasland in bpo-34916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34916}.)

@item 
Add @ref{891,,blobopen()} to @ref{54d,,sqlite3.Connection}.
@ref{892,,sqlite3.Blob} allows incremental I/O operations on blobs.
(Contributed by Aviv Palivoda and Erlend E. Aasland in bpo-24905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24905}.)
@end itemize

@node string,sys<4>,sqlite3<5>,改良されたモジュール<3>
@anchor{whatsnew/3 11 string}@anchor{893}@anchor{whatsnew/3 11 whatsnew311-string}@anchor{894}
@subsubsection string



@itemize *

@item 
Add @ref{895,,get_identifiers()}
and @ref{896,,is_valid()} to @ref{897,,string.Template},
which respectively return all valid placeholders,
and whether any invalid placeholders are present.
(Contributed by Ben Kehoe in gh-90465@footnote{https://github.com/python/cpython/issues/90465}.)
@end itemize

@node sys<4>,sysconfig<2>,string,改良されたモジュール<3>
@anchor{whatsnew/3 11 sys}@anchor{898}@anchor{whatsnew/3 11 whatsnew311-sys}@anchor{899}
@subsubsection sys



@itemize *

@item 
@ref{89a,,sys.exc_info()} now derives the @code{type} and @code{traceback} fields
from the @code{value} (the exception instance), so when an exception is
modified while it is being handled, the changes are reflected in
the results of subsequent calls to @code{exc_info()}.
(Contributed by Irit Katriel in bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}.)

@item 
Add @ref{89b,,sys.exception()} which returns the active exception instance
(equivalent to @code{sys.exc_info()[1]}).
(Contributed by Irit Katriel in bpo-46328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46328}.)

@item 
Add the @ref{89c,,sys.flags.safe_path} flag.
(Contributed by Victor Stinner in gh-57684@footnote{https://github.com/python/cpython/issues/57684}.)
@end itemize

@node sysconfig<2>,tempfile<3>,sys<4>,改良されたモジュール<3>
@anchor{whatsnew/3 11 sysconfig}@anchor{89d}@anchor{whatsnew/3 11 whatsnew311-sysconfig}@anchor{89e}
@subsubsection sysconfig



@itemize *

@item 
Three new @ref{449,,installation schemes}
(`posix_venv', `nt_venv' and `venv') were added and are used when Python
creates new virtual environments or when it is running from a virtual
environment.
The first two schemes (`posix_venv' and `nt_venv') are OS-specific
for non-Windows and Windows, the `venv' is essentially an alias to one of
them according to the OS Python runs on.
This is useful for downstream distributors who modify
@ref{89f,,sysconfig.get_preferred_scheme()}.
Third party code that creates new virtual environments should use the new
`venv' installation scheme to determine the paths, as does @ref{117,,venv}.
(Contributed by Miro Hrončok in bpo-45413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45413}.)
@end itemize

@node tempfile<3>,threading<3>,sysconfig<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 tempfile}@anchor{8a0}@anchor{whatsnew/3 11 whatsnew311-tempfile}@anchor{8a1}
@subsubsection tempfile



@itemize *

@item 
@ref{8a2,,SpooledTemporaryFile} objects now fully implement the methods
of @ref{8a3,,io.BufferedIOBase} or @ref{8a4,,io.TextIOBase}
(depending on file mode).
This lets them work correctly with APIs that expect file-like objects,
such as compression modules.
(Contributed by Carey Metcalfe in gh-70363@footnote{https://github.com/python/cpython/issues/70363}.)
@end itemize

@node threading<3>,time<2>,tempfile<3>,改良されたモジュール<3>
@anchor{whatsnew/3 11 threading}@anchor{8a5}@anchor{whatsnew/3 11 whatsnew311-threading}@anchor{8a6}
@subsubsection threading



@itemize *

@item 
On Unix, if the @code{sem_clockwait()} function is available in the C library
(glibc 2.30 and newer), the @ref{8a7,,threading.Lock.acquire()} method now uses
the monotonic clock (@ref{8a8,,time.CLOCK_MONOTONIC}) for the timeout, rather
than using the system clock (@ref{8a9,,time.CLOCK_REALTIME}), to not be affected
by system clock changes.
(Contributed by Victor Stinner in bpo-41710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41710}.)
@end itemize

@node time<2>,tkinter<4>,threading<3>,改良されたモジュール<3>
@anchor{whatsnew/3 11 time}@anchor{8aa}@anchor{whatsnew/3 11 whatsnew311-time}@anchor{8ab}
@subsubsection time



@itemize *

@item 
On Unix, @ref{8ac,,time.sleep()} now uses the @code{clock_nanosleep()} or
@code{nanosleep()} function, if available, which has a resolution of 1 nanosecond
(10@w{^-9} seconds), rather than using @code{select()} which has a resolution
of 1 microsecond (10@w{^-6} seconds).
(Contributed by Benjamin Szőke and Victor Stinner in bpo-21302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21302}.)

@item 
On Windows 8.1 and newer, @ref{8ac,,time.sleep()} now uses a waitable timer based
on high-resolution timers@footnote{https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/high-resolution-timers}
which has a resolution of 100 nanoseconds (10@w{^-7} seconds). Previously,
it had a resolution of 1 millisecond (10@w{^-3} seconds).
(Contributed by Benjamin Szőke, Donghee Na, Eryk Sun and Victor Stinner in bpo-21302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21302} and bpo-45429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45429}.)
@end itemize

@node tkinter<4>,traceback<2>,time<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 tkinter}@anchor{8ad}@anchor{whatsnew/3 11 whatsnew311-tkinter}@anchor{8ae}
@subsubsection tkinter



@itemize *

@item 
Added method @code{info_patchlevel()} which returns the exact version of
the Tcl library as a named tuple similar to @ref{8af,,sys.version_info}.
(Contributed by Serhiy Storchaka in gh-91827@footnote{https://github.com/python/cpython/issues/91827}.)
@end itemize

@node traceback<2>,typing<5>,tkinter<4>,改良されたモジュール<3>
@anchor{whatsnew/3 11 traceback}@anchor{8b0}@anchor{whatsnew/3 11 whatsnew311-traceback}@anchor{8b1}
@subsubsection traceback



@itemize *

@item 
Add @ref{8b2,,traceback.StackSummary.format_frame_summary()} to allow users
to override which frames appear in the traceback, and how they are
formatted.
(Contributed by Ammar Askar in bpo-44569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44569}.)

@item 
Add @ref{8b3,,traceback.TracebackException.print()}, which prints the
formatted @ref{563,,TracebackException} instance to a file.
(Contributed by Irit Katriel in bpo-33809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33809}.)
@end itemize

@node typing<5>,unicodedata<4>,traceback<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 typing}@anchor{8b4}@anchor{whatsnew/3 11 whatsnew311-typing}@anchor{8b5}
@subsubsection typing


For major changes, see @ref{7db,,型ヒントに関連する新しい機能}.


@itemize *

@item 
Add @ref{8b6,,typing.assert_never()} and @ref{8b7,,typing.Never}.
@ref{8b6,,typing.assert_never()} is useful for asking a type checker to confirm
that a line of code is not reachable. At runtime, it raises an
@ref{8b8,,AssertionError}.
(Contributed by Jelle Zijlstra in gh-90633@footnote{https://github.com/python/cpython/issues/90633}.)

@item 
Add @ref{8b9,,typing.reveal_type()}. This is useful for asking a type checker
what type it has inferred for a given expression. At runtime it prints
the type of the received value.
(Contributed by Jelle Zijlstra in gh-90572@footnote{https://github.com/python/cpython/issues/90572}.)

@item 
Add @ref{8ba,,typing.assert_type()}. This is useful for asking a type checker
to confirm that the type it has inferred for a given expression matches
the given type. At runtime it simply returns the received value.
(Contributed by Jelle Zijlstra in gh-90638@footnote{https://github.com/python/cpython/issues/90638}.)

@item 
@ref{332,,typing.TypedDict} types can now be generic. (Contributed by
Samodya Abeysiriwardane in gh-89026@footnote{https://github.com/python/cpython/issues/89026}.)

@item 
@ref{331,,NamedTuple} types can now be generic.
(Contributed by Serhiy Storchaka in bpo-43923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43923}.)

@item 
Allow subclassing of @ref{8bb,,typing.Any}. This is useful for avoiding
type checker errors related to highly dynamic class, such as mocks.
(Contributed by Shantanu Jain in gh-91154@footnote{https://github.com/python/cpython/issues/91154}.)

@item 
The @ref{8bc,,typing.final()} decorator now sets the @code{__final__} attributed on
the decorated object.
(Contributed by Jelle Zijlstra in gh-90500@footnote{https://github.com/python/cpython/issues/90500}.)

@item 
The @ref{8bd,,typing.get_overloads()} function can be used for introspecting
the overloads of a function. @ref{8be,,typing.clear_overloads()} can be used
to clear all registered overloads of a function.
(Contributed by Jelle Zijlstra in gh-89263@footnote{https://github.com/python/cpython/issues/89263}.)

@item 
The @ref{8bf,,__init__()} method of @ref{56b,,Protocol} subclasses
is now preserved. (Contributed by Adrian Garcia Badarasco in gh-88970@footnote{https://github.com/python/cpython/issues/88970}.)

@item 
The representation of empty tuple types (@code{Tuple[()]}) is simplified.
This affects introspection, e.g. @code{get_args(Tuple[()])} now evaluates
to @code{()} instead of @code{((),)}.
(Contributed by Serhiy Storchaka in gh-91137@footnote{https://github.com/python/cpython/issues/91137}.)

@item 
Loosen runtime requirements for type annotations by removing the callable
check in the private @code{typing._type_check} function. (Contributed by
Gregory Beauregard in gh-90802@footnote{https://github.com/python/cpython/issues/90802}.)

@item 
@ref{8c0,,typing.get_type_hints()} now supports evaluating strings as forward
references in @ref{8c1,,PEP 585 generic aliases}.
(Contributed by Niklas Rosenstein in gh-85542@footnote{https://github.com/python/cpython/issues/85542}.)

@item 
@ref{8c0,,typing.get_type_hints()} no longer adds @ref{8c2,,Optional}
to parameters with @code{None} as a default. (Contributed by Nikita Sobolev
in gh-90353@footnote{https://github.com/python/cpython/issues/90353}.)

@item 
@ref{8c0,,typing.get_type_hints()} now supports evaluating bare stringified
@ref{56d,,ClassVar} annotations. (Contributed by Gregory Beauregard
in gh-90711@footnote{https://github.com/python/cpython/issues/90711}.)

@item 
@ref{8c3,,typing.no_type_check()} no longer modifies external classes and functions.
It also now correctly marks classmethods as not to be type checked. (Contributed
by Nikita Sobolev in gh-90729@footnote{https://github.com/python/cpython/issues/90729}.)
@end itemize

@node unicodedata<4>,unittest<5>,typing<5>,改良されたモジュール<3>
@anchor{whatsnew/3 11 unicodedata}@anchor{8c4}@anchor{whatsnew/3 11 whatsnew311-unicodedata}@anchor{8c5}
@subsubsection unicodedata



@itemize *

@item 
The Unicode database has been updated to version 14.0.0.
(Contributed by Benjamin Peterson in bpo-45190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45190}).
@end itemize

@node unittest<5>,venv<2>,unicodedata<4>,改良されたモジュール<3>
@anchor{whatsnew/3 11 unittest}@anchor{8c6}@anchor{whatsnew/3 11 whatsnew311-unittest}@anchor{8c7}
@subsubsection unittest



@itemize *

@item 
Added methods @ref{8c8,,enterContext()} and
@ref{8c9,,enterClassContext()} of class
@ref{2b3,,TestCase}, method
@ref{8ca,,enterAsyncContext()} of
class @ref{361,,IsolatedAsyncioTestCase} and function
@ref{8cb,,unittest.enterModuleContext()}.
(Contributed by Serhiy Storchaka in bpo-45046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45046}.)
@end itemize

@node venv<2>,warnings<2>,unittest<5>,改良されたモジュール<3>
@anchor{whatsnew/3 11 venv}@anchor{8cc}@anchor{whatsnew/3 11 whatsnew311-venv}@anchor{8cd}
@subsubsection venv



@itemize *

@item 
When new Python virtual environments are created, the `venv'
@ref{449,,sysconfig installation scheme} is used
to determine the paths inside the environment.
When Python runs in a virtual environment, the same installation scheme
is the default.
That means that downstream distributors can change the default sysconfig install
scheme without changing behavior of virtual environments.
Third party code that also creates new virtual environments should do the same.
(Contributed by Miro Hrončok in bpo-45413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45413}.)
@end itemize

@node warnings<2>,zipfile<2>,venv<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 warnings}@anchor{8ce}@anchor{whatsnew/3 11 whatsnew311-warnings}@anchor{8cf}
@subsubsection warnings



@itemize *

@item 
@ref{179,,warnings.catch_warnings()} now accepts arguments for @ref{8d0,,warnings.simplefilter()},
providing a more concise way to locally ignore warnings or convert them to errors.
(Contributed by Zac Hatfield-Dodds in bpo-47074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47074}.)
@end itemize

@node zipfile<2>,,warnings<2>,改良されたモジュール<3>
@anchor{whatsnew/3 11 whatsnew311-zipfile}@anchor{8d1}@anchor{whatsnew/3 11 zipfile}@anchor{8d2}
@subsubsection zipfile



@itemize *

@item 
Added support for specifying member name encoding for reading metadata
in a @ref{8d3,,ZipFile}'s directory and file headers.
(Contributed by Stephen J. Turnbull and Serhiy Storchaka in bpo-28080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28080}.)

@item 
Added @ref{8d4,,ZipFile.mkdir()}
for creating new directories inside ZIP archives.
(Contributed by Sam Ezeh in gh-49083@footnote{https://github.com/python/cpython/issues/49083}.)

@item 
Added @ref{8d5,,stem}, @ref{8d6,,suffix}
and @ref{8d7,,suffixes} to @ref{8d8,,zipfile.Path}.
(Contributed by Miguel Brito in gh-88261@footnote{https://github.com/python/cpython/issues/88261}.)
@end itemize

@node 最適化<4>,Faster CPython,改良されたモジュール<3>,What's New In Python 3 11
@anchor{whatsnew/3 11 optimizations}@anchor{8d9}@anchor{whatsnew/3 11 whatsnew311-optimizations}@anchor{8da}
@subsection 最適化


This section covers specific optimizations independent of the
@ref{7bd,,Faster CPython} project, which is covered in its own section.


@itemize *

@item 
The compiler now optimizes simple
@ref{8db,,printf-style % formatting} on string literals
containing only the format codes @code{%s}, @code{%r} and @code{%a} and makes it as
fast as a corresponding @ref{66b,,f-string} expression.
(Contributed by Serhiy Storchaka in bpo-28307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28307}.)

@item 
Integer division (@code{//}) is better tuned for optimization by compilers.
It is now around 20% faster on x86-64 when dividing an @ref{19b,,int}
by a value smaller than @code{2**30}.
(Contributed by Gregory P. Smith and Tim Peters in gh-90564@footnote{https://github.com/python/cpython/issues/90564}.)

@item 
@ref{695,,sum()} is now nearly 30% faster for integers smaller than @code{2**30}.
(Contributed by Stefan Behnel in gh-68264@footnote{https://github.com/python/cpython/issues/68264}.)

@item 
Resizing lists is streamlined for the common case,
speeding up @ref{8dc,,list.append()} by ≈15%
and simple @ref{8dd,,list comprehension}s by up to 20-30%
(Contributed by Dennis Sweeney in gh-91165@footnote{https://github.com/python/cpython/issues/91165}.)

@item 
Dictionaries don't store hash values when all keys are Unicode objects,
decreasing @ref{183,,dict} size.
For example, @code{sys.getsizeof(dict.fromkeys("abcdefg"))}
is reduced from 352 bytes to 272 bytes (23% smaller) on 64-bit platforms.
(Contributed by Inada Naoki in bpo-46845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46845}.)

@item 
Using @ref{8de,,asyncio.DatagramProtocol} is now orders of magnitude faster
when transferring large files over UDP,
with speeds over 100 times higher for a ≈60 MiB file.
(Contributed by msoxzw in gh-91487@footnote{https://github.com/python/cpython/issues/91487}.)

@item 
@ref{92,,math} functions @ref{8df,,comb()} and @ref{8e0,,perm()} are now
≈10 times faster for large arguments (with a larger speedup for larger `k').
(Contributed by Serhiy Storchaka in bpo-37295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37295}.)

@item 
The @ref{d7,,statistics} functions @ref{8e1,,mean()},
@ref{8e2,,variance()} and @ref{8e3,,stdev()} now consume
iterators in one pass rather than converting them to a @ref{24d,,list} first.
This is twice as fast and can save substantial memory.
(Contributed by Raymond Hettinger in gh-90415@footnote{https://github.com/python/cpython/issues/90415}.)

@item 
@ref{8e4,,unicodedata.normalize()}
now normalizes pure-ASCII strings in constant time.
(Contributed by Donghee Na in bpo-44987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44987}.)
@end itemize

@node Faster CPython,CPython バイトコードの変更<3>,最適化<4>,What's New In Python 3 11
@anchor{whatsnew/3 11 faster-cpython}@anchor{8e5}@anchor{whatsnew/3 11 whatsnew311-faster-cpython}@anchor{7bd}
@subsection Faster CPython


CPython 3.11 is an average of
25% faster@footnote{https://github.com/faster-cpython/ideas#published-results}
than CPython 3.10 as measured with the
pyperformance@footnote{https://github.com/python/pyperformance} benchmark suite,
when compiled with GCC on Ubuntu Linux.
Depending on your workload, the overall speedup could be 10-60%.

This project focuses on two major areas in Python:
@ref{8e6,,Faster Startup} and @ref{8e7,,Faster Runtime}.
Optimizations not covered by this project are listed separately under
@ref{8da,,最適化}.

@menu
* Faster Startup:: 
* Faster Runtime:: 
* Misc:: 
* FAQ:: 
* About:: 

@end menu

@node Faster Startup,Faster Runtime,,Faster CPython
@anchor{whatsnew/3 11 faster-startup}@anchor{8e8}@anchor{whatsnew/3 11 whatsnew311-faster-startup}@anchor{8e6}
@subsubsection Faster Startup


@menu
* Frozen imports / Static code objects:: 

@end menu

@node Frozen imports / Static code objects,,,Faster Startup
@anchor{whatsnew/3 11 frozen-imports-static-code-objects}@anchor{8e9}@anchor{whatsnew/3 11 whatsnew311-faster-imports}@anchor{8ea}
@subsubsection Frozen imports / Static code objects


Python caches @ref{4aa,,bytecode} in the @ref{8eb,,__pycache__}
directory to speed up module loading.

Previously in 3.10, Python module execution looked like this:

@example
Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate
@end example

In Python 3.11, the core modules essential for Python startup are "frozen".
This means that their @ref{7d2,,コードオブジェクト} (and bytecode)
are statically allocated by the interpreter.
This reduces the steps in module execution process to:

@example
Statically allocated code object -> Evaluate
@end example

Interpreter startup is now 10-15% faster in Python 3.11. This has a big
impact for short-running programs using Python.

(Contributed by Eric Snow, Guido van Rossum and Kumar Aditya in many issues.)

@node Faster Runtime,Misc,Faster Startup,Faster CPython
@anchor{whatsnew/3 11 faster-runtime}@anchor{8ec}@anchor{whatsnew/3 11 whatsnew311-faster-runtime}@anchor{8e7}
@subsubsection Faster Runtime


@menu
* Cheaper@comma{} lazy Python frames: Cheaper lazy Python frames. 
* Inlined Python function calls:: 
* PEP 659; Specializing Adaptive Interpreter: PEP 659 Specializing Adaptive Interpreter. 

@end menu

@node Cheaper lazy Python frames,Inlined Python function calls,,Faster Runtime
@anchor{whatsnew/3 11 cheaper-lazy-python-frames}@anchor{8ed}@anchor{whatsnew/3 11 whatsnew311-lazy-python-frames}@anchor{8ee}
@subsubsection Cheaper, lazy Python frames


Python frames, holding execution information,
are created whenever Python calls a Python function.
The following are new frame optimizations:


@itemize -

@item 
Streamlined the frame creation process.

@item 
Avoided memory allocation by generously re-using frame space on the C stack.

@item 
Streamlined the internal frame struct to contain only essential information.
Frames previously held extra debugging and memory management information.
@end itemize

Old-style @ref{8ef,,frame objects}
are now created only when requested by debuggers
or by Python introspection functions such as @ref{8f0,,sys._getframe()} and
@ref{8f1,,inspect.currentframe()}. For most user code, no frame objects are
created at all. As a result, nearly all Python functions calls have sped
up significantly. We measured a 3-7% speedup in pyperformance.

(Contributed by Mark Shannon in bpo-44590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44590}.)
@anchor{whatsnew/3 11 inline-calls}@anchor{8f2}
@node Inlined Python function calls,PEP 659 Specializing Adaptive Interpreter,Cheaper lazy Python frames,Faster Runtime
@anchor{whatsnew/3 11 inlined-python-function-calls}@anchor{8f3}@anchor{whatsnew/3 11 whatsnew311-inline-calls}@anchor{8f4}
@subsubsection Inlined Python function calls


During a Python function call, Python will call an evaluating C function to
interpret that function's code. This effectively limits pure Python recursion to
what's safe for the C stack.

In 3.11, when CPython detects Python code calling another Python function,
it sets up a new frame, and "jumps" to the new code inside the new frame. This
avoids calling the C interpreting function altogether.

Most Python function calls now consume no C stack space, speeding them up.
In simple recursive functions like fibonacci or
factorial, we observed a 1.7x speedup. This also means recursive functions
can recurse significantly deeper
(if the user increases the recursion limit with @ref{6ea,,sys.setrecursionlimit()}).
We measured a 1-3% improvement in pyperformance.

(Contributed by Pablo Galindo and Mark Shannon in bpo-45256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45256}.)

@node PEP 659 Specializing Adaptive Interpreter,,Inlined Python function calls,Faster Runtime
@anchor{whatsnew/3 11 pep-659-specializing-adaptive-interpreter}@anchor{8f5}@anchor{whatsnew/3 11 whatsnew311-pep659}@anchor{49f}
@subsubsection PEP 659: Specializing Adaptive Interpreter


@geindex Python Enhancement Proposals; PEP 659
PEP 659@footnote{https://peps.python.org/pep-0659/} is one of the key parts of the Faster CPython project. The general
idea is that while Python is a dynamic language, most code has regions where
objects and types rarely change. This concept is known as `type stability'.

At runtime, Python will try to look for common patterns and type stability
in the executing code. Python will then replace the current operation with a
more specialized one. This specialized operation uses fast paths available only
to those use cases/types, which generally outperform their generic
counterparts. This also brings in another concept called `inline caching', where
Python caches the results of expensive operations directly in the
@ref{4aa,,bytecode}.

The specializer will also combine certain common instruction pairs into one
superinstruction, reducing the overhead during execution.

Python will only specialize
when it sees code that is "hot" (executed multiple times). This prevents Python
from wasting time on run-once code. Python can also de-specialize when code is
too dynamic or when the use changes. Specialization is attempted periodically,
and specialization attempts are not too expensive,
allowing specialization to adapt to new circumstances.

(PEP written by Mark Shannon, with ideas inspired by Stefan Brunthaler.
See 
@geindex Python Enhancement Proposals; PEP 659
PEP 659@footnote{https://peps.python.org/pep-0659/} for more information. Implementation by Mark Shannon and Brandt
Bucher, with additional help from Irit Katriel and Dennis Sweeney.)

@c If I missed out anyone, please add them.


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

形式

@tab

Specialization

@tab

Operation speedup
(up to)

@tab

Contributor(s)

@item

Binary
operations

@tab

@code{x + x}

@code{x - x}

@code{x * x}

@tab

Binary add, multiply and subtract for common types
such as @ref{19b,,int}, @ref{196,,float} and @ref{169,,str}
take custom fast paths for their underlying types.

@tab

10%

@tab

Mark Shannon,
Donghee Na,
Brandt Bucher,
Dennis Sweeney

@item

Subscript

@tab

@code{a[i]}

@tab

Subscripting container types such as @ref{24d,,list},
@ref{614,,tuple} and @ref{183,,dict} directly index
the underlying data structures.

Subscripting custom @ref{588,,__getitem__()}
is also inlined similar to @ref{8f2,,Inlined Python function calls}.

@tab

10-25%

@tab

Irit Katriel,
Mark Shannon

@item

Store
subscript

@tab

@code{a[i] = z}

@tab

Similar to subscripting specialization above.

@tab

10-25%

@tab

Dennis Sweeney

@item

呼び出し (call)

@tab

@code{f(arg)}

@code{C(arg)}

@tab

Calls to common builtin (C) functions and types such
as @ref{840,,len()} and @ref{169,,str} directly call their
underlying C version. This avoids going through the
internal calling convention.

@tab

20%

@tab

Mark Shannon,
Ken Jin

@item

Load
global
variable

@tab

@code{print}

@code{len}

@tab

The object's index in the globals/builtins namespace
is cached. Loading globals and builtins require
zero namespace lookups.

@tab

@footnote{
A similar optimization already existed since Python 3.8.
3.11 specializes for more forms and reduces some overhead.
}

@tab

Mark Shannon

@item

Load
attribute

@tab

@code{o.attr}

@tab

Similar to loading global variables. The attribute's
index inside the class/object's namespace is cached.
In most cases, attribute loading will require zero
namespace lookups.

@tab

@footnote{
A similar optimization already existed since Python 3.10.
3.11 specializes for more forms. Furthermore, all attribute loads should
be sped up by @uref{https://bugs.python.org/issue?@@action=redirect&bpo=45947,bpo-45947}.
}

@tab

Mark Shannon

@item

Load
methods for
call

@tab

@code{o.meth()}

@tab

The actual address of the method is cached. Method
loading now has no namespace lookups -- even for
classes with long inheritance chains.

@tab

10-20%

@tab

Ken Jin,
Mark Shannon

@item

Store
attribute

@tab

@code{o.attr = z}

@tab

Similar to load attribute optimization.

@tab

2%
in pyperformance

@tab

Mark Shannon

@item

Unpack
Sequence

@tab

@code{*seq}

@tab

Specialized for common containers such as
@ref{24d,,list} and @ref{614,,tuple}.
Avoids internal calling convention.

@tab

8%

@tab

Brandt Bucher

@end multitable


@node Misc,FAQ,Faster Runtime,Faster CPython
@anchor{whatsnew/3 11 misc}@anchor{8f6}@anchor{whatsnew/3 11 whatsnew311-faster-cpython-misc}@anchor{8f7}
@subsubsection Misc



@itemize *

@item 
Objects now require less memory due to lazily created object namespaces.
Their namespace dictionaries now also share keys more freely.
(Contributed Mark Shannon in bpo-45340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45340} and bpo-40116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40116}.)

@item 
"Zero-cost" exceptions are implemented, eliminating the cost
of @ref{8f8,,try} statements when no exception is raised.
(Contributed by Mark Shannon in bpo-40222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40222}.)

@item 
A more concise representation of exceptions in the interpreter reduced the
time required for catching an exception by about 10%.
(Contributed by Irit Katriel in bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}.)

@item 
@ref{be,,re}'s regular expression matching engine has been partially refactored,
and now uses computed gotos (or "threaded code") on supported platforms. As a
result, Python 3.11 executes the pyperformance regular expression benchmarks@footnote{https://pyperformance.readthedocs.io/benchmarks.html#regex-dna} up to 10%
faster than Python 3.10.
(Contributed by Brandt Bucher in gh-91404@footnote{https://github.com/python/cpython/issues/91404}.)
@end itemize

@node FAQ,About,Misc,Faster CPython
@anchor{whatsnew/3 11 faq}@anchor{8f9}@anchor{whatsnew/3 11 whatsnew311-faster-cpython-faq}@anchor{8fa}
@subsubsection FAQ


@menu
* How should I write my code to utilize these speedups?:: 
* Will CPython 3.11 use more memory?: Will CPython 3 11 use more memory?. 
* I don't see any speedups in my workload. Why?: I don't see any speedups in my workload Why?. 
* Is there a JIT compiler?:: 

@end menu

@node How should I write my code to utilize these speedups?,Will CPython 3 11 use more memory?,,FAQ
@anchor{whatsnew/3 11 faster-cpython-faq-my-code}@anchor{8fb}@anchor{whatsnew/3 11 how-should-i-write-my-code-to-utilize-these-speedups}@anchor{8fc}
@subsubsection How should I write my code to utilize these speedups?


Write Pythonic code that follows common best practices;
you don't have to change your code.
The Faster CPython project optimizes for common code patterns we observe.

@node Will CPython 3 11 use more memory?,I don't see any speedups in my workload Why?,How should I write my code to utilize these speedups?,FAQ
@anchor{whatsnew/3 11 faster-cpython-faq-memory}@anchor{8fd}@anchor{whatsnew/3 11 will-cpython-3-11-use-more-memory}@anchor{8fe}
@subsubsection Will CPython 3.11 use more memory?


Maybe not; we don't expect memory use to exceed 20% higher than 3.10.
This is offset by memory optimizations for frame objects and object
dictionaries as mentioned above.

@node I don't see any speedups in my workload Why?,Is there a JIT compiler?,Will CPython 3 11 use more memory?,FAQ
@anchor{whatsnew/3 11 faster-cpython-ymmv}@anchor{8ff}@anchor{whatsnew/3 11 i-don-t-see-any-speedups-in-my-workload-why}@anchor{900}
@subsubsection I don't see any speedups in my workload. Why?


Certain code won't have noticeable benefits. If your code spends most of
its time on I/O operations, or already does most of its
computation in a C extension library like NumPy, there won't be significant
speedups. This project currently benefits pure-Python workloads the most.

Furthermore, the pyperformance figures are a geometric mean. Even within the
pyperformance benchmarks, certain benchmarks have slowed down slightly, while
others have sped up by nearly 2x!

@node Is there a JIT compiler?,,I don't see any speedups in my workload Why?,FAQ
@anchor{whatsnew/3 11 faster-cpython-jit}@anchor{901}@anchor{whatsnew/3 11 is-there-a-jit-compiler}@anchor{902}
@subsubsection Is there a JIT compiler?


No. We're still exploring other optimizations.

@node About,,FAQ,Faster CPython
@anchor{whatsnew/3 11 about}@anchor{903}@anchor{whatsnew/3 11 whatsnew311-faster-cpython-about}@anchor{904}
@subsubsection About


Faster CPython explores optimizations for @ref{905,,CPython}. The main team is
funded by Microsoft to work on this full-time. Pablo Galindo Salgado is also
funded by Bloomberg LP to work on the project part-time. Finally, many
contributors are volunteers from the community.

@node CPython バイトコードの変更<3>,非推奨<4>,Faster CPython,What's New In Python 3 11
@anchor{whatsnew/3 11 cpython-bytecode-changes}@anchor{906}@anchor{whatsnew/3 11 whatsnew311-bytecode-changes}@anchor{907}
@subsection CPython バイトコードの変更


The bytecode now contains inline cache entries,
which take the form of the newly-added @ref{908,,CACHE} instructions.
Many opcodes expect to be followed by an exact number of caches,
and instruct the interpreter to skip over them at runtime.
Populated caches can look like arbitrary instructions,
so great care should be taken when reading or modifying
raw, adaptive bytecode containing quickened data.

@menu
* New opcodes:: 
* Replaced opcodes:: 
* Changed/removed opcodes:: 

@end menu

@node New opcodes,Replaced opcodes,,CPython バイトコードの変更<3>
@anchor{whatsnew/3 11 new-opcodes}@anchor{909}@anchor{whatsnew/3 11 whatsnew311-added-opcodes}@anchor{90a}
@subsubsection New opcodes



@itemize *

@item 
@code{ASYNC_GEN_WRAP}, @ref{90b,,RETURN_GENERATOR} and @ref{90c,,SEND},
used in generators and co-routines.

@item 
@ref{90d,,COPY_FREE_VARS},
which avoids needing special caller-side code for closures.

@item 
@ref{90e,,JUMP_BACKWARD_NO_INTERRUPT},
for use in certain loops where handling interrupts is undesirable.

@item 
@ref{90f,,MAKE_CELL}, to create @ref{910,,セルオブジェクト (cell object)}.

@item 
@ref{911,,CHECK_EG_MATCH}  and  @code{PREP_RERAISE_STAR},
to handle the @ref{7be,,new exception groups and except*}
added in 
@geindex Python Enhancement Proposals; PEP 654
PEP 654@footnote{https://peps.python.org/pep-0654/}.

@item 
@ref{912,,PUSH_EXC_INFO}, for use in exception handlers.

@item 
@ref{5bb,,RESUME}, a no-op,
for internal tracing, debugging and optimization checks.
@end itemize

@node Replaced opcodes,Changed/removed opcodes,New opcodes,CPython バイトコードの変更<3>
@anchor{whatsnew/3 11 replaced-opcodes}@anchor{913}@anchor{whatsnew/3 11 whatsnew311-replaced-opcodes}@anchor{914}
@subsubsection Replaced opcodes



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Replaced Opcode(s)

@tab

New Opcode(s)

@tab

注釈

@item


@display
@code{BINARY_*}@w{ }
@code{INPLACE_*}@w{ }
@end display



@tab

@ref{366,,BINARY_OP}

@tab

Replaced all numeric binary/in-place
opcodes with a single opcode

@item


@display
@code{CALL_FUNCTION}@w{ }
@code{CALL_FUNCTION_KW}@w{ }
@code{CALL_METHOD}@w{ }
@end display



@tab


@display
@ref{915,,CALL}@w{ }
@code{KW_NAMES}@w{ }
@code{PRECALL}@w{ }
@ref{916,,PUSH_NULL}@w{ }
@end display



@tab

Decouples argument shifting for methods
from handling of keyword arguments;
allows better specialization of calls

@item


@display
@code{DUP_TOP}@w{ }
@code{DUP_TOP_TWO}@w{ }
@code{ROT_TWO}@w{ }
@code{ROT_THREE}@w{ }
@code{ROT_FOUR}@w{ }
@code{ROT_N}@w{ }
@end display



@tab


@display
@ref{917,,COPY}@w{ }
@ref{918,,SWAP}@w{ }
@end display



@tab

Stack manipulation instructions

@item


@display
@code{JUMP_IF_NOT_EXC_MATCH}@w{ }
@end display



@tab


@display
@ref{919,,CHECK_EXC_MATCH}@w{ }
@end display



@tab

Now performs check but doesn't jump

@item


@display
@code{JUMP_ABSOLUTE}@w{ }
@code{POP_JUMP_IF_FALSE}@w{ }
@code{POP_JUMP_IF_TRUE}@w{ }
@end display



@tab


@display
@ref{91a,,JUMP_BACKWARD}@w{ }
@code{POP_JUMP_BACKWARD_IF_*}@w{ }
@code{POP_JUMP_FORWARD_IF_*}@w{ }
@end display



@tab

See @footnote{
All jump opcodes are now relative, including the
existing @code{JUMP_IF_TRUE_OR_POP} and @code{JUMP_IF_FALSE_OR_POP}.
The argument is now an offset from the current instruction
rather than an absolute location.
};
@code{TRUE}, @code{FALSE},
@code{NONE} and @code{NOT_NONE} variants
for each direction

@item


@display
@code{SETUP_WITH}@w{ }
@code{SETUP_ASYNC_WITH}@w{ }
@end display



@tab

@code{BEFORE_WITH}

@tab

@ref{186,,with} block setup

@end multitable

@anchor{whatsnew/3 11 whatsnew311-changed-opcodes}@anchor{91b}@anchor{whatsnew/3 11 whatsnew311-removed-opcodes}@anchor{91c}
@node Changed/removed opcodes,,Replaced opcodes,CPython バイトコードの変更<3>
@anchor{whatsnew/3 11 changed-removed-opcodes}@anchor{91d}@anchor{whatsnew/3 11 whatsnew311-changed-removed-opcodes}@anchor{91e}
@subsubsection Changed/removed opcodes



@itemize *

@item 
Changed @ref{91f,,MATCH_CLASS} and @ref{920,,MATCH_KEYS}
to no longer push an additional boolean value to indicate success/failure.
Instead, @code{None} is pushed on failure
in place of the tuple of extracted values.

@item 
Changed opcodes that work with exceptions to reflect them
now being represented as one item on the stack instead of three
(see gh-89874@footnote{https://github.com/python/cpython/issues/89874}).

@item 
Removed @code{COPY_DICT_WITHOUT_KEYS}, @code{GEN_START},
@code{POP_BLOCK}, @code{SETUP_FINALLY} and @code{YIELD_FROM}.
@end itemize
@anchor{whatsnew/3 11 whatsnew311-deprecated}@anchor{921}
@node 非推奨<4>,Pending Removal in Python 3 12,CPython バイトコードの変更<3>,What's New In Python 3 11
@anchor{whatsnew/3 11 deprecated}@anchor{922}@anchor{whatsnew/3 11 whatsnew311-python-api-deprecated}@anchor{923}
@subsection 非推奨


This section lists Python APIs that have been deprecated in Python 3.11.

Deprecated C APIs are @ref{924,,listed separately}.
@anchor{whatsnew/3 11 whatsnew311-deprecated-language}@anchor{925}
@menu
* Language/Builtins:: 
* モジュール:: 
* Standard Library:: 

@end menu

@node Language/Builtins,モジュール,,非推奨<4>
@anchor{whatsnew/3 11 language-builtins}@anchor{926}@anchor{whatsnew/3 11 whatsnew311-deprecated-builtins}@anchor{927}
@subsubsection Language/Builtins



@itemize *

@item 
Chaining @ref{48e,,classmethod} descriptors (introduced in bpo-19072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19072})
is now deprecated.  It can no longer be used to wrap other descriptors
such as @ref{4b3,,property}.  The core design of this feature was flawed
and caused a number of downstream problems.  To "pass-through" a
@ref{48e,,classmethod}, consider using the @code{__wrapped__} attribute
that was added in Python 3.10.
(Contributed by Raymond Hettinger in gh-89519@footnote{https://github.com/python/cpython/issues/89519}.)

@item 
Octal escapes in string and bytes literals with values larger than @code{0o377}
(255 in decimal) now produce a @ref{1a3,,DeprecationWarning}.
In a future Python version, they will raise a @ref{1ae,,SyntaxWarning} and
eventually a @ref{18e,,SyntaxError}.
(Contributed by Serhiy Storchaka in gh-81548@footnote{https://github.com/python/cpython/issues/81548}.)

@item 
The delegation of @ref{19b,,int()} to @ref{19c,,__trunc__()} is now deprecated.
Calling @code{int(a)} when @code{type(a)} implements @code{__trunc__()} but not
@ref{19d,,__int__()} or @ref{19e,,__index__()} now raises
a @ref{1a3,,DeprecationWarning}.
(Contributed by Zackery Spytz in bpo-44977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44977}.)
@end itemize

@node モジュール,Standard Library,Language/Builtins,非推奨<4>
@anchor{whatsnew/3 11 modules}@anchor{928}@anchor{whatsnew/3 11 whatsnew311-deprecated-modules}@anchor{929}
@subsubsection モジュール

@anchor{whatsnew/3 11 whatsnew311-pep594}@anchor{7c9}

@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} led to the deprecations of the following modules
slated for removal in Python 3.13:


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{aifc}

@tab

@code{chunk}

@tab

@code{msilib}

@tab

@code{pipes}

@tab

@code{telnetlib}

@item

@code{audioop}

@tab

@code{crypt}

@tab

@code{nis}

@tab

@code{sndhdr}

@tab

@code{uu}

@item

@code{cgi}

@tab

@code{imghdr}

@tab

@code{nntplib}

@tab

@code{spwd}

@tab

@code{xdrlib}

@item

@code{cgitb}

@tab

@code{mailcap}

@tab

@code{ossaudiodev}

@tab

@code{sunau}

@tab

@end multitable


(Contributed by Brett Cannon in bpo-47061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47061} and Victor Stinner in
gh-68966@footnote{https://github.com/python/cpython/issues/68966}.)

@item 
The @code{asynchat}, @code{asyncore} and  @code{smtpd} modules have been
deprecated since at least Python 3.6. Their documentation and deprecation
warnings have now been updated to note they will be removed in Python 3.12.
(Contributed by Hugo van Kemenade in bpo-47022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47022}.)

@item 
The @code{lib2to3} package and @code{2to3} tool
are now deprecated and may not be able to parse Python 3.10 or newer.
See 
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/}, introducing the new PEG parser, for details.
(Contributed by Victor Stinner in bpo-40360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40360}.)

@item 
Undocumented modules @code{sre_compile}, @code{sre_constants}
and @code{sre_parse} are now deprecated.
(Contributed by Serhiy Storchaka in bpo-47152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47152}.)
@end itemize

@node Standard Library,,モジュール,非推奨<4>
@anchor{whatsnew/3 11 standard-library}@anchor{92a}@anchor{whatsnew/3 11 whatsnew311-deprecated-stdlib}@anchor{92b}
@subsubsection Standard Library



@itemize *

@item 
The following have been deprecated in @ref{26,,configparser} since Python 3.2.
Their deprecation warnings have now been updated to note they will be removed
in Python 3.12:


@itemize *

@item 
the @code{configparser.SafeConfigParser} class

@item 
the @code{configparser.ParsingError.filename} property

@item 
the @code{configparser.RawConfigParser.readfp()} method
@end itemize

(Contributed by Hugo van Kemenade in bpo-45173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45173}.)

@item 
@code{configparser.LegacyInterpolation} has been deprecated in the docstring
since Python 3.2, and is not listed in the @ref{26,,configparser} documentation.
It now emits a @ref{1a3,,DeprecationWarning} and will be removed
in Python 3.13. Use @ref{92c,,configparser.BasicInterpolation} or
@ref{92d,,configparser.ExtendedInterpolation} instead.
(Contributed by Hugo van Kemenade in bpo-46607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46607}.)

@item 
The older set of @ref{7f,,importlib.resources} functions were deprecated
in favor of the replacements added in Python 3.9
and will be removed in a future Python version,
due to not supporting resources located within package subdirectories:


@itemize *

@item 
@code{importlib.resources.contents()}

@item 
@code{importlib.resources.is_resource()}

@item 
@code{importlib.resources.open_binary()}

@item 
@code{importlib.resources.open_text()}

@item 
@code{importlib.resources.read_binary()}

@item 
@code{importlib.resources.read_text()}

@item 
@code{importlib.resources.path()}
@end itemize

@item 
The @ref{326,,locale.getdefaultlocale()} function is deprecated and will be
removed in Python 3.15. Use @ref{328,,locale.setlocale()},
@ref{75c,,locale.getpreferredencoding(False)} and
@ref{327,,locale.getlocale()} functions instead.
(Contributed by Victor Stinner in gh-90817@footnote{https://github.com/python/cpython/issues/90817}.)

@item 
The @code{locale.resetlocale()} function is deprecated and will be
removed in Python 3.13. Use @code{locale.setlocale(locale.LC_ALL, "")} instead.
(Contributed by Victor Stinner in gh-90817@footnote{https://github.com/python/cpython/issues/90817}.)

@item 
Stricter rules will now be applied for numerical group references
and group names in @ref{92e,,regular expressions}.
Only sequences of ASCII digits will now be accepted as a numerical reference,
and the group name in @ref{192,,bytes} patterns and replacement strings
can only contain ASCII letters, digits and underscores.
For now, a deprecation warning is raised for syntax violating these rules.
(Contributed by Serhiy Storchaka in gh-91760@footnote{https://github.com/python/cpython/issues/91760}.)

@item 
In the @ref{be,,re} module, the @code{re.template()} function
and the corresponding @code{re.TEMPLATE} and @code{re.T} flags
are deprecated, as they were undocumented and lacked an obvious purpose.
They will be removed in Python 3.13.
(Contributed by Serhiy Storchaka and Miro Hrončok in gh-92728@footnote{https://github.com/python/cpython/issues/92728}.)

@item 
@code{turtle.settiltangle()} has been deprecated since Python 3.1;
it now emits a deprecation warning and will be removed in Python 3.13. Use
@ref{92f,,turtle.tiltangle()} instead (it was earlier incorrectly marked
as deprecated, and its docstring is now corrected).
(Contributed by Hugo van Kemenade in bpo-45837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45837}.)

@item 
@ref{360,,typing.Text}, which exists solely to provide compatibility support
between Python 2 and Python 3 code, is now deprecated. Its removal is
currently unplanned, but users are encouraged to use @ref{169,,str} instead
wherever possible.
(Contributed by Alex Waygood in gh-92332@footnote{https://github.com/python/cpython/issues/92332}.)

@item 
The keyword argument syntax for constructing @ref{332,,typing.TypedDict} types
is now deprecated. Support will be removed in Python 3.13. (Contributed by
Jingchen Ye in gh-90224@footnote{https://github.com/python/cpython/issues/90224}.)

@item 
@code{webbrowser.MacOSX} is deprecated and will be removed in Python 3.13.
It is untested, undocumented, and not used by @ref{11b,,webbrowser} itself.
(Contributed by Donghee Na in bpo-42255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42255}.)

@item 
The behavior of returning a value from a @ref{2b3,,TestCase} and
@ref{361,,IsolatedAsyncioTestCase} test methods (other than the
default @code{None} value) is now deprecated.

@item 
Deprecated the following not-formally-documented @ref{10c,,unittest} functions,
scheduled for removal in Python 3.13:


@itemize *

@item 
@code{unittest.findTestCases()}

@item 
@code{unittest.makeSuite()}

@item 
@code{unittest.getTestCaseNames()}
@end itemize

Use @ref{593,,TestLoader} methods instead:


@itemize *

@item 
@ref{594,,unittest.TestLoader.loadTestsFromModule()}

@item 
@ref{595,,unittest.TestLoader.loadTestsFromTestCase()}

@item 
@ref{596,,unittest.TestLoader.getTestCaseNames()}
@end itemize

(Contributed by Erlend E. Aasland in bpo-5846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5846}.)

@item 
@code{unittest.TestProgram.usageExit()} is marked deprecated, to be removed
in 3.13.
(Contributed by Carlos Damázio in gh-67048@footnote{https://github.com/python/cpython/issues/67048}.)
@end itemize
@anchor{whatsnew/3 11 whatsnew311-pending-removal}@anchor{930}
@node Pending Removal in Python 3 12,削除<4>,非推奨<4>,What's New In Python 3 11
@anchor{whatsnew/3 11 pending-removal-in-python-3-12}@anchor{931}@anchor{whatsnew/3 11 whatsnew311-python-api-pending-removal}@anchor{932}
@subsection Pending Removal in Python 3.12


The following Python APIs have been deprecated in earlier Python releases,
and will be removed in Python 3.12.

C APIs pending removal are
@ref{933,,listed separately}.


@itemize *

@item 
The @code{asynchat} module

@item 
The @code{asyncore} module

@item 
The @ref{934,,entire distutils package}

@item 
The @code{imp} module

@item 
The @ref{238,,typing.io} namespace

@item 
The @ref{935,,typing.re} namespace

@item 
@code{cgi.log()}

@item 
@code{importlib.find_loader()}

@item 
@code{importlib.abc.Loader.module_repr()}

@item 
@code{importlib.abc.MetaPathFinder.find_module()}

@item 
@code{importlib.abc.PathEntryFinder.find_loader()}

@item 
@code{importlib.abc.PathEntryFinder.find_module()}

@item 
@code{importlib.machinery.BuiltinImporter.find_module()}

@item 
@code{importlib.machinery.BuiltinLoader.module_repr()}

@item 
@code{importlib.machinery.FileFinder.find_loader()}

@item 
@code{importlib.machinery.FileFinder.find_module()}

@item 
@code{importlib.machinery.FrozenImporter.find_module()}

@item 
@code{importlib.machinery.FrozenLoader.module_repr()}

@item 
@code{importlib.machinery.PathFinder.find_module()}

@item 
@code{importlib.machinery.WindowsRegistryFinder.find_module()}

@item 
@code{importlib.util.module_for_loader()}

@item 
@code{importlib.util.set_loader_wrapper()}

@item 
@code{importlib.util.set_package_wrapper()}

@item 
@code{pkgutil.ImpImporter}

@item 
@code{pkgutil.ImpLoader}

@item 
@code{pathlib.Path.link_to()}

@item 
@code{sqlite3.enable_shared_cache()}

@item 
@code{sqlite3.OptimizedUnicode()}

@item 
@code{PYTHONTHREADDEBUG} environment variable

@item 
The following deprecated aliases in @ref{10c,,unittest}:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

非推奨のエイリアス

@tab

メソッド名

@tab

非推奨となるバージョン

@item

@code{failUnless}

@tab

@ref{74a,,assertTrue()}

@tab

3.1

@item

@code{failIf}

@tab

@ref{74b,,assertFalse()}

@tab

3.1

@item

@code{failUnlessEqual}

@tab

@ref{74c,,assertEqual()}

@tab

3.1

@item

@code{failIfEqual}

@tab

@ref{74d,,assertNotEqual()}

@tab

3.1

@item

@code{failUnlessAlmostEqual}

@tab

@ref{74e,,assertAlmostEqual()}

@tab

3.1

@item

@code{failIfAlmostEqual}

@tab

@ref{74f,,assertNotAlmostEqual()}

@tab

3.1

@item

@code{failUnlessRaises}

@tab

@ref{750,,assertRaises()}

@tab

3.1

@item

@code{assert_}

@tab

@ref{74a,,assertTrue()}

@tab

3.2

@item

@code{assertEquals}

@tab

@ref{74c,,assertEqual()}

@tab

3.2

@item

@code{assertNotEquals}

@tab

@ref{74d,,assertNotEqual()}

@tab

3.2

@item

@code{assertAlmostEquals}

@tab

@ref{74e,,assertAlmostEqual()}

@tab

3.2

@item

@code{assertNotAlmostEquals}

@tab

@ref{74f,,assertNotAlmostEqual()}

@tab

3.2

@item

@code{assertRegexpMatches}

@tab

@ref{751,,assertRegex()}

@tab

3.2

@item

@code{assertRaisesRegexp}

@tab

@ref{752,,assertRaisesRegex()}

@tab

3.2

@item

@code{assertNotRegexpMatches}

@tab

@ref{753,,assertNotRegex()}

@tab

3.5

@end multitable

@end quotation
@end itemize
@anchor{whatsnew/3 11 whatsnew311-removed}@anchor{936}
@node 削除<4>,Porting to Python 3 11,Pending Removal in Python 3 12,What's New In Python 3 11
@anchor{whatsnew/3 11 removed}@anchor{937}@anchor{whatsnew/3 11 whatsnew311-python-api-removed}@anchor{938}
@subsection 削除


This section lists Python APIs that have been removed in Python 3.11.

Removed C APIs are @ref{939,,listed separately}.


@itemize *

@item 
Removed the @code{@@asyncio.coroutine()} @ref{93a,,decorator}
enabling legacy generator-based coroutines to be compatible with
@ref{93b,,async} / @ref{18d,,await} code.
The function has been deprecated since Python 3.8 and the removal was
initially scheduled for Python 3.10. Use @ref{7ed,,async def} instead.
(Contributed by Illia Volochii in bpo-43216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43216}.)

@item 
Removed @code{asyncio.coroutines.CoroWrapper} used for wrapping legacy
generator-based coroutine objects in the debug mode.
(Contributed by Illia Volochii in bpo-43216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43216}.)

@item 
Due to significant security concerns, the `reuse_address' parameter of
@ref{93c,,asyncio.loop.create_datagram_endpoint()}, disabled in Python 3.9, is
now entirely removed. This is because of the behavior of the socket option
@code{SO_REUSEADDR} in UDP.
(Contributed by Hugo van Kemenade in bpo-45129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45129}.)

@item 
Removed the @code{binhex} module, deprecated in Python 3.9.
Also removed the related, similarly-deprecated @ref{11,,binascii} functions:


@itemize *

@item 
@code{binascii.a2b_hqx()}

@item 
@code{binascii.b2a_hqx()}

@item 
@code{binascii.rlecode_hqx()}

@item 
@code{binascii.rldecode_hqx()}
@end itemize

The @ref{93d,,binascii.crc_hqx()} function remains available.

(Contributed by Victor Stinner in bpo-45085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45085}.)

@item 
Removed the @code{distutils} @code{bdist_msi} command deprecated in Python 3.9.
Use @code{bdist_wheel} (wheel packages) instead.
(Contributed by Hugo van Kemenade in bpo-45124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45124}.)

@item 
Removed the @ref{588,,__getitem__()} methods of
@ref{93e,,xml.dom.pulldom.DOMEventStream}, @ref{93f,,wsgiref.util.FileWrapper}
and @ref{940,,fileinput.FileInput}, deprecated since Python 3.9.
(Contributed by Hugo van Kemenade in bpo-45132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45132}.)

@item 
Removed the deprecated @ref{67,,gettext} functions
@code{lgettext()}, @code{ldgettext()},
@code{lngettext()} and @code{ldngettext()}.
Also removed the @code{bind_textdomain_codeset()} function,
the @code{NullTranslations.output_charset()} and
@code{NullTranslations.set_output_charset()} methods,
and the `codeset' parameter of @code{translation()} and @code{install()},
since they are only used for the @code{l*gettext()} functions.
(Contributed by Donghee Na and Serhiy Storchaka in bpo-44235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44235}.)

@item 
Removed from the @ref{82,,inspect} module:


@itemize *

@item 
The @code{getargspec()} function, deprecated since Python 3.0;
use @ref{22f,,inspect.signature()} or @ref{941,,inspect.getfullargspec()} instead.

@item 
The @code{formatargspec()} function, deprecated since Python 3.5;
use the @ref{22f,,inspect.signature()} function
or the @ref{4e3,,inspect.Signature} object directly.

@item 
The undocumented @code{Signature.from_builtin()}
and @code{Signature.from_function()} methods, deprecated since Python 3.5;
use the @ref{942,,Signature.from_callable()}
method instead.
@end itemize

(Contributed by Hugo van Kemenade in bpo-45320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45320}.)

@item 
Removed the @ref{943,,__class_getitem__()} method
from @ref{6cd,,pathlib.PurePath},
because it was not used and added by mistake in previous versions.
(Contributed by Nikita Sobolev in bpo-46483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46483}.)

@item 
Removed the @code{MailmanProxy} class in the @code{smtpd} module,
as it is unusable without the external @code{mailman} package.
(Contributed by Donghee Na in bpo-35800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35800}.)

@item 
Removed the deprecated @code{split()} method of @code{_tkinter.TkappType}.
(Contributed by Erlend E. Aasland in bpo-38371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38371}.)

@item 
Removed namespace package support from @ref{10c,,unittest} discovery.
It was introduced in Python 3.4 but has been broken since Python 3.7.
(Contributed by Inada Naoki in bpo-23882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23882}.)

@item 
Removed the undocumented private @code{float.__set_format__()} method,
previously known as @code{float.__setformat__()} in Python 3.7.
Its docstring said: "You probably don't want to use this function.
It exists mainly to be used in Python's test suite."
(Contributed by Victor Stinner in bpo-46852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46852}.)

@item 
The @code{--experimental-isolated-subinterpreters} configure flag
(and corresponding @code{EXPERIMENTAL_ISOLATED_SUBINTERPRETERS} macro)
have been removed.

@item 
Pynche@footnote{https://pypi.org/project/Pynche/}
--- The Pythonically Natural Color and Hue Editor --- has been moved out
of @code{Tools/scripts} and is being developed independently@footnote{https://gitlab.com/warsaw/pynche/-/tree/main} from the Python source tree.
@end itemize
@anchor{whatsnew/3 11 whatsnew311-porting}@anchor{944}
@node Porting to Python 3 11,Build Changes<3>,削除<4>,What's New In Python 3 11
@anchor{whatsnew/3 11 porting-to-python-3-11}@anchor{945}@anchor{whatsnew/3 11 whatsnew311-python-api-porting}@anchor{946}
@subsection Porting to Python 3.11


This section lists previously described changes and other bugfixes
in the Python API that may require changes to your Python code.

Porting notes for the C API are
@ref{947,,listed separately}.


@itemize *

@item 
@ref{316,,open()}, @ref{740,,io.open()}, @ref{315,,codecs.open()} and
@ref{940,,fileinput.FileInput} no longer accept @code{'U'} ("universal newline")
in the file mode. In Python 3, "universal newline" mode is used by default
whenever a file is opened in text mode,
and the @code{'U'} flag has been deprecated since Python 3.3.
The @ref{948,,newline parameter}
to these functions controls how universal newlines work.
(Contributed by Victor Stinner in bpo-37330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37330}.)

@item 
@ref{4c3,,ast.AST} node positions are now validated when provided to
@ref{4b1,,compile()} and other related functions. If invalid positions are detected,
a @ref{2ec,,ValueError} will be raised. (Contributed by Pablo Galindo in gh-93351@footnote{https://github.com/python/cpython/issues/93351})

@item 
Prohibited passing non-@ref{949,,concurrent.futures.ThreadPoolExecutor}
executors to @ref{94a,,asyncio.loop.set_default_executor()}
following a deprecation in Python 3.8.
(Contributed by Illia Volochii in bpo-43234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43234}.)

@item 
@ref{15,,calendar}: The @ref{94b,,calendar.LocaleTextCalendar} and
@ref{94c,,calendar.LocaleHTMLCalendar} classes now use
@ref{327,,locale.getlocale()}, instead of using @ref{326,,locale.getdefaultlocale()},
if no locale is specified.
(Contributed by Victor Stinner in bpo-46659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46659}.)

@item 
The @ref{aa,,pdb} module now reads the @code{.pdbrc} configuration file with
the @code{'UTF-8'} encoding.
(Contributed by Srinivas Reddy Thatiparthy (శ్రీనివాస్  రెడ్డి తాటిపర్తి) in bpo-41137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41137}.)

@item 
The `population' parameter of @ref{94d,,random.sample()} must be a sequence,
and automatic conversion of @ref{184,,set}s to @ref{24d,,list}s
is no longer supported. Also, if the sample size
is larger than the population size, a @ref{2ec,,ValueError} is raised.
(Contributed by Raymond Hettinger in bpo-40465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40465}.)

@item 
The `random' optional parameter of @ref{94e,,random.shuffle()} was removed.
It was previously an arbitrary random function to use for the shuffle;
now, @ref{94f,,random.random()} (its previous default) will always be used.

@item 
In @ref{be,,re} @ref{92e,,正規表現のシンタックス}, global inline flags (e.g. @code{(?i)})
can now only be used at the start of regular expressions.
Using them elsewhere has been deprecated since Python 3.6.
(Contributed by Serhiy Storchaka in bpo-47066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47066}.)

@item 
In the @ref{be,,re} module, several long-standing bugs where fixed that,
in rare cases, could cause capture groups to get the wrong result.
Therefore, this could change the captured output in these cases.
(Contributed by Ma Lin in bpo-35859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35859}.)
@end itemize

@node Build Changes<3>,C API の変更<5>,Porting to Python 3 11,What's New In Python 3 11
@anchor{whatsnew/3 11 build-changes}@anchor{950}@anchor{whatsnew/3 11 whatsnew311-build-changes}@anchor{951}
@subsection Build Changes



@itemize *

@item 
CPython now has 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} 
@geindex Python Enhancement Proposals; PEP 11#tier-3
Tier 3 support@footnote{https://peps.python.org/pep-0011/#tier-3} for
cross compiling to the WebAssembly@footnote{https://webassembly.org/} platforms
Emscripten@footnote{https://emscripten.org/}
(@code{wasm32-unknown-emscripten}, i.e. Python in the browser)
and WebAssembly System Interface (WASI)@footnote{https://wasi.dev/}
(@code{wasm32-unknown-wasi}).
The effort is inspired by previous work like Pyodide@footnote{https://pyodide.org/}.
These platforms provide a limited subset of POSIX APIs; Python standard
libraries features and modules related to networking, processes, threading,
signals, mmap, and users/groups are not available or don't work.
(Emscripten contributed by Christian Heimes and Ethan Smith in gh-84461@footnote{https://github.com/python/cpython/issues/84461}
and WASI contributed by Christian Heimes in gh-90473@footnote{https://github.com/python/cpython/issues/90473};
platforms promoted in gh-95085@footnote{https://github.com/python/cpython/issues/95085})

@item 
Building CPython now requires:


@itemize *

@item 
A C11@footnote{https://en.cppreference.com/w/c/11} compiler and standard library.
Optional C11 features@footnote{https://en.wikipedia.org/wiki/C11_(C_standard_revision)#Optional_features}
are not required.
(Contributed by Victor Stinner in bpo-46656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46656},
bpo-45440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45440} and bpo-46640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46640}.)

@item 
Support for IEEE 754@footnote{https://en.wikipedia.org/wiki/IEEE_754}
floating-point numbers.
(Contributed by Victor Stinner in bpo-46917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46917}.)
@end itemize

@item 
The @code{Py_NO_NAN} macro has been removed.
Since CPython now requires IEEE 754 floats, NaN values are always available.
(Contributed by Victor Stinner in bpo-46656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46656}.)

@item 
The @ref{f6,,tkinter} package now requires Tcl/Tk@footnote{https://www.tcl.tk}
version 8.5.12 or newer.
(Contributed by Serhiy Storchaka in bpo-46996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46996}.)

@item 
Build dependencies, compiler flags, and linker flags for most stdlib
extension modules are now detected by @code{configure}. libffi, libnsl,
libsqlite3, zlib, bzip2, liblzma, libcrypt, Tcl/Tk, and uuid flags
are detected by pkg-config@footnote{https://www.freedesktop.org/wiki/Software/pkg-config/} (when available).
@ref{f6,,tkinter} now requires a pkg-config command
to detect development settings for Tcl/Tk@footnote{https://www.tcl.tk} headers and libraries.
(Contributed by Christian Heimes and Erlend Egeberg Aasland in
bpo-45847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45847}, bpo-45747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45747}, and bpo-45763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45763}.)

@item 
libpython is no longer linked against libcrypt.
(Contributed by Mike Gilbert in bpo-45433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45433}.)

@item 
CPython can now be built with the
ThinLTO@footnote{https://clang.llvm.org/docs/ThinLTO.html} option
via passing @code{thin} to @ref{952,,--with-lto}, i.e. @code{--with-lto=thin}.
(Contributed by Donghee Na and Brett Holman in bpo-44340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44340}.)

@item 
Freelists for object structs can now be disabled. A new @code{configure}
option @code{--without-freelists} can be used to disable all freelists
except empty tuple singleton.
(Contributed by Christian Heimes in bpo-45522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45522}.)

@item 
@code{Modules/Setup} and @code{Modules/makesetup} have been improved and tied up.
Extension modules can now be built through @code{makesetup}. All except some
test modules can be linked statically into a main binary or library.
(Contributed by Brett Cannon and Christian Heimes in bpo-45548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45548},
bpo-45570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45570}, bpo-45571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45571}, and bpo-43974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43974}.)

@cartouche
@quotation 注釈 
Use the environment variables @code{TCLTK_CFLAGS} and
@code{TCLTK_LIBS} to manually specify the location of Tcl/Tk headers
and libraries. The @code{configure} options
@code{--with-tcltk-includes} and @code{--with-tcltk-libs}
have been removed.

On RHEL 7 and CentOS 7 the development packages do not provide @code{tcl.pc}
and @code{tk.pc}; use @code{TCLTK_LIBS="-ltk8.5 -ltkstub8.5 -ltcl8.5"}.
The directory @code{Misc/rhel7} contains @code{.pc} files and instructions
on how to build Python with RHEL 7's and CentOS 7's Tcl/Tk and OpenSSL.
@end quotation
@end cartouche

@item 
CPython will now use 30-bit digits by default for the Python @ref{19b,,int}
implementation. Previously, the default was to use 30-bit digits on platforms
with @code{SIZEOF_VOID_P >= 8}, and 15-bit digits otherwise. It's still possible
to explicitly request use of 15-bit digits via either the
@ref{953,,--enable-big-digits} option to the configure script
or (for Windows) the @code{PYLONG_BITS_IN_DIGIT} variable in @code{PC/pyconfig.h},
but this option may be removed at some point in the future.
(Contributed by Mark Dickinson in bpo-45569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45569}.)
@end itemize

@node C API の変更<5>,Python 3 11 4での重要な変更点,Build Changes<3>,What's New In Python 3 11
@anchor{whatsnew/3 11 c-api-changes}@anchor{954}@anchor{whatsnew/3 11 whatsnew311-c-api}@anchor{955}
@subsection C API の変更


@menu
* 新しい機能: 新しい機能<7>. 
* Porting to Python 3.11: Porting to Python 3 11<2>. 
* 非推奨: 非推奨<5>. 
* Pending Removal in Python 3.12: Pending Removal in Python 3 12<2>. 
* 削除: 削除<5>. 

@end menu

@node 新しい機能<7>,Porting to Python 3 11<2>,,C API の変更<5>
@anchor{whatsnew/3 11 id5}@anchor{956}@anchor{whatsnew/3 11 whatsnew311-c-api-new-features}@anchor{957}
@subsubsection 新しい機能



@itemize *

@item 
Add a new @ref{958,,PyType_GetName()} function to get type's short name.
(Contributed by Hai Shi in bpo-42035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42035}.)

@item 
Add a new @ref{959,,PyType_GetQualName()} function to get type's qualified name.
(Contributed by Hai Shi in bpo-42035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42035}.)

@item 
Add new @ref{95a,,PyThreadState_EnterTracing()} and
@ref{95b,,PyThreadState_LeaveTracing()} functions to the limited C API to
suspend and resume tracing and profiling.
(Contributed by Victor Stinner in bpo-43760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43760}.)

@item 
Added the @ref{381,,Py_Version} constant which bears the same value as
@ref{382,,PY_VERSION_HEX}.
(Contributed by  Gabriele N. Tornetta in bpo-43931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43931}.)

@item 
@ref{95c,,Py_buffer} and APIs are now part of the limited API and the stable
ABI:


@itemize *

@item 
@ref{639,,PyObject_CheckBuffer()}

@item 
@ref{63a,,PyObject_GetBuffer()}

@item 
@ref{95d,,PyBuffer_GetPointer()}

@item 
@ref{95e,,PyBuffer_SizeFromFormat()}

@item 
@ref{95f,,PyBuffer_ToContiguous()}

@item 
@ref{960,,PyBuffer_FromContiguous()}

@item 
@ref{961,,PyObject_CopyData()}

@item 
@ref{962,,PyBuffer_IsContiguous()}

@item 
@ref{963,,PyBuffer_FillContiguousStrides()}

@item 
@ref{964,,PyBuffer_FillInfo()}

@item 
@ref{63b,,PyBuffer_Release()}

@item 
@ref{965,,PyMemoryView_FromBuffer()}

@item 
@ref{966,,bf_getbuffer} and
@ref{967,,bf_releasebuffer} type slots
@end itemize

(Contributed by Christian Heimes in bpo-45459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45459}.)

@item 
Added the @ref{635,,PyType_GetModuleByDef()} function, used to get the module
in which a method was defined, in cases where this information is not
available directly (via @ref{968,,PyCMethod}).
(Contributed by Petr Viktorin in bpo-46613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46613}.)

@item 
Add new functions to pack and unpack C double (serialize and deserialize):
@ref{969,,PyFloat_Pack2()}, @ref{96a,,PyFloat_Pack4()}, @ref{96b,,PyFloat_Pack8()},
@ref{96c,,PyFloat_Unpack2()}, @ref{96d,,PyFloat_Unpack4()} and
@ref{96e,,PyFloat_Unpack8()}.
(Contributed by Victor Stinner in bpo-46906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46906}.)

@item 
Add new functions to get frame object attributes:
@ref{96f,,PyFrame_GetBuiltins()}, @ref{970,,PyFrame_GetGenerator()},
@ref{971,,PyFrame_GetGlobals()}, @ref{972,,PyFrame_GetLasti()}.

@item 
Added two new functions to get and set the active exception instance:
@ref{973,,PyErr_GetHandledException()} and @ref{974,,PyErr_SetHandledException()}.
These are alternatives to @ref{975,,PyErr_SetExcInfo()} and
@ref{976,,PyErr_GetExcInfo()} which work with the legacy 3-tuple
representation of exceptions.
(Contributed by Irit Katriel in bpo-46343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46343}.)

@item 
Added the @ref{977,,PyConfig.safe_path} member.
(Contributed by Victor Stinner in gh-57684@footnote{https://github.com/python/cpython/issues/57684}.)
@end itemize

@node Porting to Python 3 11<2>,非推奨<5>,新しい機能<7>,C API の変更<5>
@anchor{whatsnew/3 11 id6}@anchor{978}@anchor{whatsnew/3 11 whatsnew311-c-api-porting}@anchor{947}
@subsubsection Porting to Python 3.11

@anchor{whatsnew/3 11 whatsnew311-pep670}@anchor{7cb}

@itemize *

@item 
Some macros have been converted to static inline functions to avoid
macro pitfalls@footnote{https://gcc.gnu.org/onlinedocs/cpp/Macro-Pitfalls.html}.
The change should be mostly transparent to users,
as the replacement functions will cast their arguments to the expected types
to avoid compiler warnings due to static type checks.
However, when the limited C API is set to >=3.11,
these casts are not done,
and callers will need to cast arguments to their expected types.
See 
@geindex Python Enhancement Proposals; PEP 670
PEP 670@footnote{https://peps.python.org/pep-0670/} for more details.
(Contributed by Victor Stinner and Erlend E. Aasland in gh-89653@footnote{https://github.com/python/cpython/issues/89653}.)

@item 
@ref{975,,PyErr_SetExcInfo()} no longer uses the @code{type} and @code{traceback}
arguments, the interpreter now derives those values from the exception
instance (the @code{value} argument). The function still steals references
of all three arguments.
(Contributed by Irit Katriel in bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}.)

@item 
@ref{976,,PyErr_GetExcInfo()} now derives the @code{type} and @code{traceback}
fields of the result from the exception instance (the @code{value} field).
(Contributed by Irit Katriel in bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}.)

@item 
@ref{979,,_frozen} has a new @code{is_package} field to indicate whether
or not the frozen module is a package.  Previously, a negative value
in the @code{size} field was the indicator.  Now only non-negative values
be used for @code{size}.
(Contributed by Kumar Aditya in bpo-46608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46608}.)

@item 
@ref{97a,,_PyFrameEvalFunction()} now takes @code{_PyInterpreterFrame*}
as its second parameter, instead of @code{PyFrameObject*}.
See 
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/} for more details of how to use this function pointer type.

@item 
@code{PyCode_New()} and @code{PyCode_NewWithPosOnlyArgs()} now take
an additional @code{exception_table} argument.
Using these functions should be avoided, if at all possible.
To get a custom code object: create a code object using the compiler,
then get a modified version with the @code{replace} method.

@item 
@ref{97b,,PyCodeObject} no longer has the @code{co_code}, @code{co_varnames},
@code{co_cellvars} and @code{co_freevars} fields.  Instead, use
@ref{97c,,PyCode_GetCode()}, @ref{97d,,PyCode_GetVarnames()},
@ref{97e,,PyCode_GetCellvars()} and @ref{97f,,PyCode_GetFreevars()} respectively
to access them via the C API.
(Contributed by Brandt Bucher in bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841} and Ken Jin in gh-92154@footnote{https://github.com/python/cpython/issues/92154}
and gh-94936@footnote{https://github.com/python/cpython/issues/94936}.)

@item 
The old trashcan macros (@code{Py_TRASHCAN_SAFE_BEGIN}/@code{Py_TRASHCAN_SAFE_END})
are now deprecated. They should be replaced by the new macros
@code{Py_TRASHCAN_BEGIN} and @code{Py_TRASHCAN_END}.

A tp_dealloc function that has the old macros, such as:

@example
static void
mytype_dealloc(mytype *p)
@{
    PyObject_GC_UnTrack(p);
    Py_TRASHCAN_SAFE_BEGIN(p);
    ...
    Py_TRASHCAN_SAFE_END
@}
@end example

should migrate to the new macros as follows:

@example
static void
mytype_dealloc(mytype *p)
@{
    PyObject_GC_UnTrack(p);
    Py_TRASHCAN_BEGIN(p, mytype_dealloc)
    ...
    Py_TRASHCAN_END
@}
@end example

Note that @code{Py_TRASHCAN_BEGIN} has a second argument which
should be the deallocation function it is in.

To support older Python versions in the same codebase, you
can define the following macros and use them throughout
the code (credit: these were copied from the @code{mypy} codebase):

@example
#if PY_VERSION_HEX >= 0x03080000
#  define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc)
#  define CPy_TRASHCAN_END(op) Py_TRASHCAN_END
#else
#  define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_SAFE_BEGIN(op)
#  define CPy_TRASHCAN_END(op) Py_TRASHCAN_SAFE_END(op)
#endif
@end example

@item 
The @ref{980,,PyType_Ready()} function now raises an error if a type is defined
with the @ref{981,,Py_TPFLAGS_HAVE_GC} flag set but has no traverse function
(@ref{982,,PyTypeObject.tp_traverse}).
(Contributed by Victor Stinner in bpo-44263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44263}.)

@item 
Heap types with the @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} flag can now inherit
the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} vectorcall protocol.  Previously, this was only possible for
@ref{983,,static types}.
(Contributed by Erlend E. Aasland in bpo-43908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43908})

@item 
Since @ref{3c9,,Py_TYPE()} is changed to a inline static function,
@code{Py_TYPE(obj) = new_type} must be replaced with
@code{Py_SET_TYPE(obj, new_type)}: see the @ref{984,,Py_SET_TYPE()} function
(available since Python 3.9). For backward compatibility, this macro can be
used:

@example
#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE)
static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type)
@{ ob->ob_type = type; @}
#define Py_SET_TYPE(ob, type) _Py_SET_TYPE((PyObject*)(ob), type)
#endif
@end example

(Contributed by Victor Stinner in bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}.)

@item 
Since @ref{985,,Py_SIZE()} is changed to a inline static function,
@code{Py_SIZE(obj) = new_size} must be replaced with
@code{Py_SET_SIZE(obj, new_size)}: see the @ref{986,,Py_SET_SIZE()} function
(available since Python 3.9). For backward compatibility, this macro can be
used:

@example
#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE)
static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)
@{ ob->ob_size = size; @}
#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)
#endif
@end example

(Contributed by Victor Stinner in bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}.)

@item 
@code{<Python.h>} no longer includes the header files @code{<stdlib.h>},
@code{<stdio.h>}, @code{<errno.h>} and @code{<string.h>} when the @code{Py_LIMITED_API}
macro is set to @code{0x030b0000} (Python 3.11) or higher. C extensions should
explicitly include the header files after @code{#include <Python.h>}.
(Contributed by Victor Stinner in bpo-45434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45434}.)

@item 
The non-limited API files @code{cellobject.h}, @code{classobject.h}, @code{code.h}, @code{context.h},
@code{funcobject.h}, @code{genobject.h} and @code{longintrepr.h} have been moved to
the @code{Include/cpython} directory. Moreover, the @code{eval.h} header file was
removed. These files must not be included directly, as they are already
included in @code{Python.h}: @ref{987,,Include Files}. If they have
been included directly, consider including @code{Python.h} instead.
(Contributed by Victor Stinner in bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}.)

@item 
The @code{PyUnicode_CHECK_INTERNED()} macro has been excluded from the
limited C API. It was never usable there, because it used internal structures
which are not available in the limited C API.
(Contributed by Victor Stinner in bpo-46007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46007}.)

@item 
The following frame functions and type are now directly available with
@code{#include <Python.h>}, it's no longer needed to add
@code{#include <frameobject.h>}:


@itemize *

@item 
@ref{988,,PyFrame_Check()}

@item 
@ref{989,,PyFrame_GetBack()}

@item 
@ref{96f,,PyFrame_GetBuiltins()}

@item 
@ref{970,,PyFrame_GetGenerator()}

@item 
@ref{971,,PyFrame_GetGlobals()}

@item 
@ref{972,,PyFrame_GetLasti()}

@item 
@ref{661,,PyFrame_GetLocals()}

@item 
@ref{98a,,PyFrame_Type}
@end itemize

(Contributed by Victor Stinner in gh-93937@footnote{https://github.com/python/cpython/issues/93937}.)
@end itemize
@anchor{whatsnew/3 11 pyframeobject-3-11-hiding}@anchor{98b}

@itemize *

@item 
The @ref{98c,,PyFrameObject} structure members have been removed from the
public C API.

While the documentation notes that the @ref{98c,,PyFrameObject} fields are
subject to change at any time, they have been stable for a long time and were
used in several popular extensions.

In Python 3.11, the frame struct was reorganized to allow performance
optimizations. Some fields were removed entirely, as they were details of the
old implementation.

@ref{98c,,PyFrameObject} fields:


@itemize *

@item 
@code{f_back}: use @ref{989,,PyFrame_GetBack()}.

@item 
@code{f_blockstack}: removed.

@item 
@code{f_builtins}: use @ref{96f,,PyFrame_GetBuiltins()}.

@item 
@code{f_code}: use @ref{98d,,PyFrame_GetCode()}.

@item 
@code{f_gen}: use @ref{970,,PyFrame_GetGenerator()}.

@item 
@code{f_globals}: use @ref{971,,PyFrame_GetGlobals()}.

@item 
@code{f_iblock}: removed.

@item 
@code{f_lasti}: use @ref{972,,PyFrame_GetLasti()}.
Code using @code{f_lasti} with @code{PyCode_Addr2Line()} should use
@ref{98e,,PyFrame_GetLineNumber()} instead; it may be faster.

@item 
@code{f_lineno}: use @ref{98e,,PyFrame_GetLineNumber()}

@item 
@code{f_locals}: use @ref{661,,PyFrame_GetLocals()}.

@item 
@code{f_stackdepth}: removed.

@item 
@code{f_state}: no public API (renamed to @code{f_frame.f_state}).

@item 
@code{f_trace}: no public API.

@item 
@code{f_trace_lines}: use @code{PyObject_GetAttrString((PyObject*)frame, "f_trace_lines")}.

@item 
@code{f_trace_opcodes}: use @code{PyObject_GetAttrString((PyObject*)frame, "f_trace_opcodes")}.

@item 
@code{f_localsplus}: no public API (renamed to @code{f_frame.localsplus}).

@item 
@code{f_valuestack}: removed.
@end itemize

The Python frame object is now created lazily. A side effect is that the
@ref{98f,,f_back} member must not be accessed directly,
since its value is now also
computed lazily. The @ref{989,,PyFrame_GetBack()} function must be called
instead.

Debuggers that accessed the @ref{4a5,,f_locals} directly `must' call
@ref{661,,PyFrame_GetLocals()} instead. They no longer need to call
@code{PyFrame_FastToLocalsWithError()} or @code{PyFrame_LocalsToFast()},
in fact they should not call those functions. The necessary updating of the
frame is now managed by the virtual machine.

Code defining @code{PyFrame_GetCode()} on Python 3.8 and older:

@example
#if PY_VERSION_HEX < 0x030900B1
static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame)
@{
    Py_INCREF(frame->f_code);
    return frame->f_code;
@}
#endif
@end example

Code defining @code{PyFrame_GetBack()} on Python 3.8 and older:

@example
#if PY_VERSION_HEX < 0x030900B1
static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)
@{
    Py_XINCREF(frame->f_back);
    return frame->f_back;
@}
#endif
@end example

Or use the pythoncapi_compat project@footnote{https://github.com/python/pythoncapi-compat} to get these two
functions on older Python versions.

@item 
Changes of the @ref{990,,PyThreadState} structure members:


@itemize *

@item 
@code{frame}: removed, use @ref{991,,PyThreadState_GetFrame()} (function added
to Python 3.9 by bpo-40429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40429}).
Warning: the function returns a @ref{5e2,,strong reference}, need to call
@ref{992,,Py_XDECREF()}.

@item 
@code{tracing}: changed, use @ref{95a,,PyThreadState_EnterTracing()}
and @ref{95b,,PyThreadState_LeaveTracing()}
(functions added to Python 3.11 by bpo-43760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43760}).

@item 
@code{recursion_depth}: removed,
use @code{(tstate->recursion_limit - tstate->recursion_remaining)} instead.

@item 
@code{stackcheck_counter}: removed.
@end itemize

Code defining @code{PyThreadState_GetFrame()} on Python 3.8 and older:

@example
#if PY_VERSION_HEX < 0x030900B1
static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
@{
    Py_XINCREF(tstate->frame);
    return tstate->frame;
@}
#endif
@end example

Code defining @code{PyThreadState_EnterTracing()} and
@code{PyThreadState_LeaveTracing()} on Python 3.10 and older:

@example
#if PY_VERSION_HEX < 0x030B00A2
static inline void PyThreadState_EnterTracing(PyThreadState *tstate)
@{
    tstate->tracing++;
#if PY_VERSION_HEX >= 0x030A00A1
    tstate->cframe->use_tracing = 0;
#else
    tstate->use_tracing = 0;
#endif
@}

static inline void PyThreadState_LeaveTracing(PyThreadState *tstate)
@{
    int use_tracing = (tstate->c_tracefunc != NULL || tstate->c_profilefunc != NULL);
    tstate->tracing--;
#if PY_VERSION_HEX >= 0x030A00A1
    tstate->cframe->use_tracing = use_tracing;
#else
    tstate->use_tracing = use_tracing;
#endif
@}
#endif
@end example

Or use the pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat} to get these functions
on old Python functions.

@item 
Distributors are encouraged to build Python with the optimized Blake2
library libb2@footnote{https://www.blake2.net/}.

@item 
The @ref{805,,PyConfig.module_search_paths_set} field must now be set to 1 for
initialization to use @ref{643,,PyConfig.module_search_paths} to initialize
@ref{3e4,,sys.path}. Otherwise, initialization will recalculate the path and replace
any values added to @code{module_search_paths}.

@item 
@ref{993,,PyConfig_Read()} no longer calculates the initial search path, and will not
fill any values into @ref{643,,PyConfig.module_search_paths}. To calculate default
paths and then modify them, finish initialization and use @ref{62a,,PySys_GetObject()}
to retrieve @ref{3e4,,sys.path} as a Python list object and modify it directly.
@end itemize

@node 非推奨<5>,Pending Removal in Python 3 12<2>,Porting to Python 3 11<2>,C API の変更<5>
@anchor{whatsnew/3 11 id7}@anchor{994}@anchor{whatsnew/3 11 whatsnew311-c-api-deprecated}@anchor{924}
@subsubsection 非推奨



@itemize *

@item 
Deprecate the following functions to configure the Python initialization:


@itemize *

@item 
@code{PySys_AddWarnOptionUnicode()}

@item 
@code{PySys_AddWarnOption()}

@item 
@code{PySys_AddXOption()}

@item 
@code{PySys_HasWarnOptions()}

@item 
@code{PySys_SetArgvEx()}

@item 
@code{PySys_SetArgv()}

@item 
@code{PySys_SetPath()}

@item 
@code{Py_SetPath()}

@item 
@code{Py_SetProgramName()}

@item 
@code{Py_SetPythonHome()}

@item 
@code{Py_SetStandardStreamEncoding()}

@item 
@code{_Py_SetProgramFullPath()}
@end itemize

Use the new @ref{3f7,,PyConfig} API of the @ref{646,,Python Initialization Configuration} instead (
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/}).
(Contributed by Victor Stinner in gh-88279@footnote{https://github.com/python/cpython/issues/88279}.)

@item 
Deprecate the @code{ob_shash} member of the @ref{995,,PyBytesObject}. Use @ref{436,,PyObject_Hash()} instead.
(Contributed by Inada Naoki in bpo-46864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46864}.)
@end itemize

@node Pending Removal in Python 3 12<2>,削除<5>,非推奨<5>,C API の変更<5>
@anchor{whatsnew/3 11 id8}@anchor{996}@anchor{whatsnew/3 11 whatsnew311-c-api-pending-removal}@anchor{933}
@subsubsection Pending Removal in Python 3.12


The following C APIs have been deprecated in earlier Python releases,
and will be removed in Python 3.12.


@itemize *

@item 
@code{PyUnicode_AS_DATA()}

@item 
@code{PyUnicode_AS_UNICODE()}

@item 
@code{PyUnicode_AsUnicodeAndSize()}

@item 
@code{PyUnicode_AsUnicode()}

@item 
@code{PyUnicode_FromUnicode()}

@item 
@code{PyUnicode_GET_DATA_SIZE()}

@item 
@code{PyUnicode_GET_SIZE()}

@item 
@code{PyUnicode_GetSize()}

@item 
@code{PyUnicode_IS_COMPACT()}

@item 
@code{PyUnicode_IS_READY()}

@item 
@ref{434,,PyUnicode_READY()}

@item 
@code{PyUnicode_WSTR_LENGTH()}

@item 
@code{_PyUnicode_AsUnicode()}

@item 
@code{PyUnicode_WCHAR_KIND}

@item 
@ref{997,,PyUnicodeObject}

@item 
@code{PyUnicode_InternImmortal()}
@end itemize

@node 削除<5>,,Pending Removal in Python 3 12<2>,C API の変更<5>
@anchor{whatsnew/3 11 id9}@anchor{998}@anchor{whatsnew/3 11 whatsnew311-c-api-removed}@anchor{939}
@subsubsection 削除



@itemize *

@item 
@code{PyFrame_BlockSetup()} and @code{PyFrame_BlockPop()} have been
removed.
(Contributed by Mark Shannon in bpo-40222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40222}.)

@item 
Remove the following math macros using the @code{errno} variable:


@itemize *

@item 
@code{Py_ADJUST_ERANGE1()}

@item 
@code{Py_ADJUST_ERANGE2()}

@item 
@code{Py_OVERFLOWED()}

@item 
@code{Py_SET_ERANGE_IF_OVERFLOW()}

@item 
@code{Py_SET_ERRNO_ON_MATH_ERROR()}
@end itemize

(Victor Stinner の貢献による bpo-45412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45412})

@item 
Remove @code{Py_UNICODE_COPY()} and @code{Py_UNICODE_FILL()} macros, deprecated
since Python 3.3. Use @code{PyUnicode_CopyCharacters()} or @code{memcpy()}
(@code{wchar_t*} string), and @code{PyUnicode_Fill()} functions instead.
(Contributed by Victor Stinner in bpo-41123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41123}.)

@item 
Remove the @code{pystrhex.h} header file. It only contains private functions.
C extensions should only include the main @code{<Python.h>} header file.
(Contributed by Victor Stinner in bpo-45434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45434}.)

@item 
Remove the @code{Py_FORCE_DOUBLE()} macro. It was used by the
@code{Py_IS_INFINITY()} macro.
(Contributed by Victor Stinner in bpo-45440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45440}.)

@item 
The following items are no longer available when @ref{660,,Py_LIMITED_API}
is defined:


@itemize *

@item 
@ref{999,,PyMarshal_WriteLongToFile()}

@item 
@ref{99a,,PyMarshal_WriteObjectToFile()}

@item 
@ref{99b,,PyMarshal_ReadObjectFromString()}

@item 
@ref{99c,,PyMarshal_WriteObjectToString()}

@item 
@code{Py_MARSHAL_VERSION} マクロ
@end itemize

These are not part of the @ref{99d,,limited API}.

(Contributed by Victor Stinner in bpo-45474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45474}.)

@item 
Exclude @ref{3de,,PyWeakref_GET_OBJECT()} from the limited C API. It never
worked since the @code{PyWeakReference} structure is opaque in the
limited C API.
(Contributed by Victor Stinner in bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}.)

@item 
Remove the @code{PyHeapType_GET_MEMBERS()} macro. It was exposed in the
public C API by mistake, it must only be used by Python internally.
Use the @code{PyTypeObject.tp_members} member instead.
(Contributed by Victor Stinner in bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}.)

@item 
Remove the @code{HAVE_PY_SET_53BIT_PRECISION} macro (moved to the internal C
API).
(Contributed by Victor Stinner in bpo-45412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45412}.)
@end itemize
@anchor{whatsnew/3 11 whatsnew311-pep624}@anchor{7ca}

@itemize *

@item 
Remove the @ref{3e0,,Py_UNICODE} encoder APIs,
as they have been deprecated since Python 3.3,
are little used
and are inefficient relative to the recommended alternatives.

削除された関数は以下の通りです:


@itemize *

@item 
@code{PyUnicode_Encode()}

@item 
@code{PyUnicode_EncodeASCII()}

@item 
@code{PyUnicode_EncodeLatin1()}

@item 
@code{PyUnicode_EncodeUTF7()}

@item 
@code{PyUnicode_EncodeUTF8()}

@item 
@code{PyUnicode_EncodeUTF16()}

@item 
@code{PyUnicode_EncodeUTF32()}

@item 
@code{PyUnicode_EncodeUnicodeEscape()}

@item 
@code{PyUnicode_EncodeRawUnicodeEscape()}

@item 
@code{PyUnicode_EncodeCharmap()}

@item 
@code{PyUnicode_TranslateCharmap()}

@item 
@code{PyUnicode_EncodeDecimal()}

@item 
@code{PyUnicode_TransformDecimalToASCII()}
@end itemize

See 
@geindex Python Enhancement Proposals; PEP 624
PEP 624@footnote{https://peps.python.org/pep-0624/} for details and
@geindex Python Enhancement Proposals; PEP 624#alternative-apis
migration guidance@footnote{https://peps.python.org/pep-0624/#alternative-apis}.
(Contributed by Inada Naoki in bpo-44029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44029}.)
@end itemize

@node Python 3 11 4での重要な変更点,Python 3 11 5での重要な変更点,C API の変更<5>,What's New In Python 3 11
@anchor{whatsnew/3 11 notable-changes-in-3-11-4}@anchor{99e}
@subsection Python 3.11.4での重要な変更点


@menu
* tarfile: tarfile<2>. 

@end menu

@node tarfile<2>,,,Python 3 11 4での重要な変更点
@anchor{whatsnew/3 11 tarfile}@anchor{99f}
@subsubsection tarfile



@itemize *

@item 
The extraction methods in @ref{e4,,tarfile}, and @ref{696,,shutil.unpack_archive()},
have a new a `filter' argument that allows limiting tar features than may be
surprising or dangerous, such as creating files outside the destination
directory.
See @ref{697,,Extraction filters} for details.
In Python 3.12, use without the `filter' argument will show a
@ref{1a3,,DeprecationWarning}.
In Python 3.14, the default will switch to @code{'data'}.
(Contributed by Petr Viktorin in 
@geindex Python Enhancement Proposals; PEP 706
PEP 706@footnote{https://peps.python.org/pep-0706/}.)
@end itemize

@node Python 3 11 5での重要な変更点,,Python 3 11 4での重要な変更点,What's New In Python 3 11
@anchor{whatsnew/3 11 notable-changes-in-3-11-5}@anchor{9a0}
@subsection Python 3.11.5での重要な変更点


@menu
* OpenSSL:: 

@end menu

@node OpenSSL,,,Python 3 11 5での重要な変更点
@anchor{whatsnew/3 11 openssl}@anchor{9a1}
@subsubsection OpenSSL



@itemize *

@item 
Windows builds and macOS installers from python.org now use OpenSSL 3.0.
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 10,What's New In Python 3 9,What's New In Python 3 11,What's New in Python
@anchor{whatsnew/3 10 doc}@anchor{9a2}@anchor{whatsnew/3 10 translation-repo}@anchor{9a3}@anchor{whatsnew/3 10 what-s-new-in-python-3-10}@anchor{9a4}
@section What's New In Python 3.10


@*編集者: 
Pablo Galindo Salgado


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the git log
@c when researching a change.

この記事では Python 3.9 と比較した Python 3.10 の新機能を解説します。Python 3.10 は2021年10月4日にリリースされました。全詳細については @ref{142,,変更履歴} をご覧ください。

@menu
* 概要: 概要 -- リリースハイライト<5>. リリースハイライト
* 新しい機能: 新しい機能<8>. 
* 型ヒントに関連する新しい機能: 型ヒントに関連する新しい機能<3>. 
* その他の言語変更: その他の言語変更<4>. 
* 新たなモジュール: 新たなモジュール<4>. 
* 改良されたモジュール: 改良されたモジュール<4>. 
* 最適化: 最適化<5>. 
* 非推奨: 非推奨<6>. 
* 削除: 削除<6>. 
* Porting to Python 3.10: Porting to Python 3 10. 
* CPython バイトコードの変更: CPython バイトコードの変更<4>. 
* Build Changes: Build Changes<4>. 
* C API の変更: C API の変更<7>. 
* Notable security feature in 3.10.7: Notable security feature in 3 10 7. 
* Notable security feature in 3.10.8: Notable security feature in 3 10 8. 
* Notable changes in 3.10.12: Notable changes in 3 10 12. 

@end menu

@node 概要 -- リリースハイライト<5>,新しい機能<8>,,What's New In Python 3 10
@anchor{whatsnew/3 10 summary-release-highlights}@anchor{9a5}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.10.
@c Brevity is key.

@c PEP-sized items next.

新たな文法機能:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/}、構造的パターンマッチ: 仕様

@item 
@geindex Python Enhancement Proposals; PEP 635
PEP 635@footnote{https://peps.python.org/pep-0635/}、構造的パターンマッチ: モチベーションと原理

@item 
@geindex Python Enhancement Proposals; PEP 636
PEP 636@footnote{https://peps.python.org/pep-0636/}、構造的パターンマッチ: チュートリアル

@item 
bpo-12782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12782}、カッコ内のコンテキストマネージャーが正式にサポート
@end itemize

標準ライブラリの新機能:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 618
PEP 618@footnote{https://peps.python.org/pep-0618/}、zipに長さチェックのオプション引数が追加
@end itemize

インタプリタの改善:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/}, デバッグおよびその他のツール用の正確な行番号。
@end itemize

新しい型ヒントの機能:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 604
PEP 604@footnote{https://peps.python.org/pep-0604/}, Unionタイプの X | Y 形式での表示

@item 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/}, パラメータ指定変数

@item 
@geindex Python Enhancement Proposals; PEP 613
PEP 613@footnote{https://peps.python.org/pep-0613/}, 明示的型エイリアス

@item 
@geindex Python Enhancement Proposals; PEP 647
PEP 647@footnote{https://peps.python.org/pep-0647/}, ユーザ定義型ガード
@end itemize

重要な非推奨化、削除または制限:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/}, OpenSSL 1.1.1 以降の必須化

@item 
@geindex Python Enhancement Proposals; PEP 632
PEP 632@footnote{https://peps.python.org/pep-0632/}, distutilsモジュールが非推奨に

@item 
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/}, PyUnicodeObject の wstr メンバーの非推奨・削除への準備

@item 
@geindex Python Enhancement Proposals; PEP 624
PEP 624@footnote{https://peps.python.org/pep-0624/}, Py_UNICODE エンコーダAPIの削除

@item 
@geindex Python Enhancement Proposals; PEP 597
PEP 597@footnote{https://peps.python.org/pep-0597/}, 任意のEncodingWarningを追加
@end itemize

@node 新しい機能<8>,型ヒントに関連する新しい機能<3>,概要 -- リリースハイライト<5>,What's New In Python 3 10
@anchor{whatsnew/3 10 new-features}@anchor{9a6}
@subsection 新しい機能


@menu
* カッコ内のコンテキストマネージャー:: 
* エラーメッセージの改善: エラーメッセージの改善<4>. 
* PEP 626; デバッグおよびその他のツール用の正確な行番号。: PEP 626 デバッグおよびその他のツール用の正確な行番号。. 
* PEP 634; 構造的パターンマッチ: PEP 634 構造的パターンマッチ. 
* Optional EncodingWarning and encoding="locale" option:: 

@end menu

@node カッコ内のコンテキストマネージャー,エラーメッセージの改善<4>,,新しい機能<8>
@anchor{whatsnew/3 10 parenthesized-context-managers}@anchor{9a7}@anchor{whatsnew/3 10 whatsnew310-pep563}@anchor{9a8}
@subsubsection カッコ内のコンテキストマネージャー


コンテキストマネージャーを複数行で継続して記述する場合に、カッコで囲むことができるようになりました。複数行でたくさんのコンテキストマネージャーを記述するときに、従来のimport文と同じようにフォーマットできます。たとえば、以下のすべての例は有効です:

@example
with (CtxManager() as example):
    ...

with (
    CtxManager1(),
    CtxManager2()
):
    ...

with (CtxManager1() as example,
      CtxManager2()):
    ...

with (CtxManager1(),
      CtxManager2() as example):
    ...

with (
    CtxManager1() as example1,
    CtxManager2() as example2
):
    ...
@end example

カッコに囲まれたグループの最後の要素に対する、末尾のカンマも指定可能です。

@example
with (
    CtxManager1() as example1,
    CtxManager2() as example2,
    CtxManager3() as example3,
):
    ...
@end example

この新しい構文は、新パーサーによるLL(1)以外の能力を使用しています。詳細は 
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/} を参照してください。

(Guido van Rossum、Pablo Galindo、Lysandros Nikolaou の貢献による bpo-12782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12782}、bpo-40334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40334})

@node エラーメッセージの改善<4>,PEP 626 デバッグおよびその他のツール用の正確な行番号。,カッコ内のコンテキストマネージャー,新しい機能<8>
@anchor{whatsnew/3 10 better-error-messages}@anchor{9a9}
@subsubsection エラーメッセージの改善


@menu
* SyntaxErrors:: 
* IndentationErrors:: 
* AttributeErrors:: 
* NameErrors:: 

@end menu

@node SyntaxErrors,IndentationErrors,,エラーメッセージの改善<4>
@anchor{whatsnew/3 10 syntaxerrors}@anchor{9aa}
@subsubsection SyntaxErrors


閉じられていない括弧やブラケットを含むコードを解析する際、インタープリタはこれまでのように `SyntaxError: unexpected EOF while parsing' を表示したり、誤った位置を指したりするのではなく、未閉鎖の括弧やブラケットの位置を示すようになりました。たとえば、次のコードを考えてみましょう（未閉鎖の '@{' に注目してください）:

@example
expected = @{9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
            38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
some_other_code = foo()
@end example

以前のバージョンのインタープリタは、構文エラーの位置として混乱する場所を報告していました:

@example
File "example.py", line 3
    some_other_code = foo()
                    ^
SyntaxError: invalid syntax
@end example

しかしPython 3.10ではより有益なエラーが出力されます:

@example
File "example.py", line 1
    expected = @{9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
               ^
SyntaxError: '@{' was never closed
@end example

同様に、閉じられていない文字列リテラル（シングルクォートおよびトリプルクォート）に関するエラーも、これまでのように EOF/EOL を報告するのではなく、文字列の開始位置を指すようになりました。

これらの改善は PyPy インタプリタのこれまでの取組から着想を得ました。

(Pablo Galindoの貢献による bpo-42864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42864}、Batuhan Taskayaの貢献による bpo-40176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40176})

インタープリタによって発生する:exc:@cite{SyntaxError} 例外は、これまで問題が検出された箇所のみを強調表示していましたが、今後は構文エラーを構成する式全体の範囲を強調表示するようになりました。このため、（ Python 3.10 以前で）次のように表示されていたものが、

@example
>>> foo(x, z for z in range(10), t, w)
  File "<stdin>", line 1
    foo(x, z for z in range(10), t, w)
           ^
SyntaxError: Generator expression must be parenthesized
@end example

Python 3.10 では例外は次のように表示されるようになります:

@example
>>> foo(x, z for z in range(10), t, w)
  File "<stdin>", line 1
    foo(x, z for z in range(10), t, w)
           ^^^^^^^^^^^^^^^^^^^^
SyntaxError: Generator expression must be parenthesized
@end example

この改善は Pablo Galindo の貢献で実現しました bpo-43914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43914}。

多くの新しい種類の:exc:@cite{SyntaxError} 例外に対して、より具体的でわかりやすいエラーメッセージが追加されました。その中でも特に注目すべきものを以下に示します。


@itemize *

@item 
ブロックの前の @code{:} が存在しない:

@example
>>> if rocket.position > event_horizon
  File "<stdin>", line 1
    if rocket.position > event_horizon
                                      ^
SyntaxError: expected ':'
@end example

(Pablo Galindo の貢献による bpo-42997@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42997})

@item 
内包表記のターゲットにカッコのないタプルを使用:

@example
>>> @{x,y for x,y in zip('abcd', '1234')@}
  File "<stdin>", line 1
    @{x,y for x,y in zip('abcd', '1234')@}
     ^
SyntaxError: did you forget parentheses around the comprehension target?
@end example

(Pablo Galindo の貢献による bpo-43017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43017})

@item 
コレクションリテラルや式の間のカンマが存在しない:

@example
>>> items = @{
... x: 1,
... y: 2
... z: 3,
  File "<stdin>", line 3
    y: 2
       ^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
@end example

(Pablo Galindo の貢献による bpo-43822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43822})

@item 
複数の例外の型をカッコで囲んでいない:

@example
>>> try:
...     build_dyson_sphere()
... except NotEnoughScienceError, NotEnoughResourcesError:
  File "<stdin>", line 3
    except NotEnoughScienceError, NotEnoughResourcesError:
           ^
SyntaxError: multiple exception types must be parenthesized
@end example

(Pablo Galindo の貢献による bpo-43149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43149})

@item 
辞書のリテラルで @code{:} と値が存在しない:

@example
>>> values = @{
... x: 1,
... y: 2,
... z:
... @}
  File "<stdin>", line 4
    z:
     ^
SyntaxError: expression expected after dictionary key and ':'

>>> values = @{x:1, y:2, z w:3@}
  File "<stdin>", line 1
    values = @{x:1, y:2, z w:3@}
                        ^
SyntaxError: ':' expected after dictionary key
@end example

(Pablo Galindo の貢献による bpo-43823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43823})

@item 
@code{try} ブロックに @code{except} または @code{finally} ブロックが存在しない:

@example
>>> try:
...     x = 2
... something = 3
  File "<stdin>", line 3
    something  = 3
    ^^^^^^^^^
SyntaxError: expected 'except' or 'finally' block
@end example

(Pablo Galindo の貢献による bpo-44305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44305})

@item 
比較で @code{==} の代わりに @code{=} を使用している:

@example
>>> if rocket.position = event_horizon:
  File "<stdin>", line 1
    if rocket.position = event_horizon:
                       ^
SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
@end example

(Pablo Galindo の貢献による bpo-43797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43797})

@item 
f-stringで @code{*} を使用している:

@example
>>> f"Black holes @{*all_black_holes@} and revelations"
  File "<stdin>", line 1
    (*all_black_holes)
     ^
SyntaxError: f-string: cannot use starred expression here
@end example

(Pablo Galindo の貢献による bpo-41064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41064})
@end itemize

@node IndentationErrors,AttributeErrors,SyntaxErrors,エラーメッセージの改善<4>
@anchor{whatsnew/3 10 indentationerrors}@anchor{9ab}
@subsubsection IndentationErrors


多くの:exc:@cite{IndentationError} 例外において、どの種類のブロックでインデントが期待されていたのか、その文の位置に関する情報が追加されるようになりました。

@example
>>> def foo():
...    if lel:
...    x = 2
  File "<stdin>", line 3
    x = 2
    ^
IndentationError: expected an indented block after 'if' statement in line 2
@end example

@node AttributeErrors,NameErrors,IndentationErrors,エラーメッセージの改善<4>
@anchor{whatsnew/3 10 attributeerrors}@anchor{9ac}
@subsubsection AttributeErrors


When printing @ref{5f0,,AttributeError}, @code{PyErr_Display()} will offer
suggestions of similar attribute names in the object that the exception was
raised from:

@example
>>> collections.namedtoplo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?
@end example

(Pablo Galindo の貢献による bpo-38530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38530})

@cartouche
@quotation 警告 
Notice this won't work if @code{PyErr_Display()} is not called to display the error
which can happen if some other custom error display function is used. This is a common
scenario in some REPLs like IPython.
@end quotation
@end cartouche

@node NameErrors,,AttributeErrors,エラーメッセージの改善<4>
@anchor{whatsnew/3 10 nameerrors}@anchor{9ad}
@subsubsection NameErrors


When printing @ref{452,,NameError} raised by the interpreter, @code{PyErr_Display()}
will offer suggestions of similar variable names in the function that the exception
was raised from:

@example
>>> schwarzschild_black_hole = None
>>> schwarschild_black_hole
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole?
@end example

(Pablo Galindo の貢献による bpo-38530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38530})

@cartouche
@quotation 警告 
Notice this won't work if @code{PyErr_Display()} is not called to display the error,
which can happen if some other custom error display function is used. This is a common
scenario in some REPLs like IPython.
@end quotation
@end cartouche

@node PEP 626 デバッグおよびその他のツール用の正確な行番号。,PEP 634 構造的パターンマッチ,エラーメッセージの改善<4>,新しい機能<8>
@anchor{whatsnew/3 10 pep-626-precise-line-numbers-for-debugging-and-other-tools}@anchor{9ae}
@subsubsection PEP 626: デバッグおよびその他のツール用の正確な行番号。


PEP 626 brings more precise and reliable line numbers for debugging, profiling and coverage tools.
Tracing events, with the correct line number, are generated for all lines of code executed and only for lines of code that are executed.

The @ref{9af,,f_lineno} attribute of frame objects will always contain the
expected line number.

The @ref{330,,co_lnotab} attribute of
@ref{4e6,,code objects} is deprecated and
will be removed in 3.12.
Code that needs to convert from offset to line number should use the new
@ref{350,,co_lines()} method instead.

@node PEP 634 構造的パターンマッチ,Optional EncodingWarning and encoding="locale" option,PEP 626 デバッグおよびその他のツール用の正確な行番号。,新しい機能<8>
@anchor{whatsnew/3 10 pep-634-structural-pattern-matching}@anchor{9b0}
@subsubsection PEP 634: 構造的パターンマッチ


Structural pattern matching has been added in the form of a `match statement'
and `case statements' of patterns with associated actions. Patterns
consist of sequences, mappings, primitive data types as well as class instances.
Pattern matching enables programs to extract information from complex data types,
branch on the structure of data, and apply specific actions based on different
forms of data.

@menu
* 構文と演算:: 
* 宣言的なアプローチ:: 
* 単純パターン; リテラルとのマッチ: 単純パターン リテラルとのマッチ. 
* リテラルと変数を組み合わせたパターン:: 
* パターンとクラス:: 
* ネストしたパターン:: 
* 複雑なパターンとワイルドカード:: 
* ガード:: 
* その他の主要な機能:: 

@end menu

@node 構文と演算,宣言的なアプローチ,,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 syntax-and-operations}@anchor{9b1}
@subsubsection 構文と演算


パターンマッチングの一般的な構文は次のとおりです:

@example
match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>
@end example

match 文は式を取り、その値を 1 つ以上の case ブロックで指定されたパターンと順に比較します。具体的には、パターンマッチングは次の手順で動作します:


@enumerate 

@item 
型と構造を持つデータ（@code{subject}）を使用する

@item 
@code{match} 文内で @code{subject} を評価する

@item 
@code{case} 文の各パターンと上から順に比較し、一致が確認されるまで進める

@item 
一致が確認されたパターンに関連付けられた処理を実行する

@item 
完全一致するパターンがない場合、最後にワイルドカード @code{_} が指定されていれば、それが一致ケースとして使用されます。完全一致もワイルドカードも存在しない場合、 match ブロック全体は何も実行されません（no-op となります）。
@end enumerate

@node 宣言的なアプローチ,単純パターン リテラルとのマッチ,構文と演算,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 declarative-approach}@anchor{9b2}
@subsubsection 宣言的なアプローチ


読者の中には、C、Java、JavaScript（およびその他多くの言語）における switch 文を通じて、対象（データオブジェクト）をリテラル（パターン）と照合する単純な例として、パターンマッチングに馴染みがある方もいるでしょう。多くの場合、 switch 文はオブジェクトや式を、リテラルを含む複数の case 文と比較するために使用されます。

より強力なパターンマッチングの例は、Scala や Elixir のような言語で見られます。構造的パターンマッチングでは、アプローチは「宣言的」であり、データが一致するための条件（パターン）を明示的に記述します。

これに対して、「命令的」なアプローチでは、入れ子になった if 文を用いて構造的パターンマッチングと同様の処理を実現することも可能ですが、「宣言的」な方法ほど明確ではありません。宣言的アプローチでは、一致のために満たすべき条件を明示的なパターンとして記述するため、より読みやすくなります。構造的パターンマッチングは、最も単純な形では case 文で変数とリテラルを比較するものとして使用できますが、 Python における真の価値は、対象の型や構造を扱える点にあります。

@node 単純パターン リテラルとのマッチ,リテラルと変数を組み合わせたパターン,宣言的なアプローチ,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 simple-pattern-match-to-a-literal}@anchor{9b3}
@subsubsection 単純パターン: リテラルとのマッチ


最も基本的な形のパターンマッチングの例を見てみましょう。ここでは、値（＝対象、subject）が複数のリテラル、すなわちパターンと照合されます。以下の例では、@code{status} が match 文の対象です。
各 case 文のパターンは、リクエストのステータスコードを表すリテラルです。一致が見つかると、その case に対応する処理が実行されます。

@example
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"
@end example

上記の関数に @code{status} として 418 が渡された場合は、 "I'm a teapot" が返されます。一方、 500 が渡された場合には、ワイルドカードとして機能する @code{_} を使用した case 文が一致し、 "Something's wrong with the internet" が返されます。ここで、最後のブロックに注目してください。変数名 @code{_} はワイルドカードとして機能し、対象と必ず一致することを保証します。なお、 @code{_} の使用は任意です。

複数のリテラルを @code{|} ("or")を使用して組み合わせて1つのパターンにできます。

@example
case 401 | 403 | 404:
    return "Not allowed"
@end example

@menu
* ワイルドカードがないときの振る舞い:: 

@end menu

@node ワイルドカードがないときの振る舞い,,,単純パターン リテラルとのマッチ
@anchor{whatsnew/3 10 behavior-without-the-wildcard}@anchor{9b4}
@subsubsection ワイルドカードがないときの振る舞い


上記の例から最後の case ブロックを削除すると、次のようになります:

@example
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
@end example

case 文で @code{_} を使用しない場合、一致するパターンが存在しない可能性があります。一致するパターンがない場合、その処理は何も実行されずスキップされます。たとえば、 @code{status} に 500 が渡された場合、この例では何も起こりません。

@node リテラルと変数を組み合わせたパターン,パターンとクラス,単純パターン リテラルとのマッチ,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 patterns-with-a-literal-and-variable}@anchor{9b5}
@subsubsection リテラルと変数を組み合わせたパターン


パターンはアンパック代入のように記述することで、変数をバインドするために使用することもできます。次の例では、データポイントを展開して、その x 座標と y 座標を取得しています:

@example
# point は (x, y) のタプル
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y=@{y@}")
    case (x, 0):
        print(f"X=@{x@}")
    case (x, y):
        print(f"X=@{x@}, Y=@{y@}")
    case _:
        raise ValueError("Not a point")
@end example

最初のパターン @code{(0, 0)} は 2 つのリテラルから構成されており、上で示したリテラルパターン拡張と考えることができます。次の 2 つのパターンでは、リテラルと変数が組み合わされており、変数は対象（@code{point}）から値を取り出して変数にバインドします。4 番目のパターンは 2 つの値を同時に取得しており、これはアンパック代入 @code{(x, y) = point} と概念的に似ています。

@node パターンとクラス,ネストしたパターン,リテラルと変数を組み合わせたパターン,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 patterns-and-classes}@anchor{9b6}
@subsubsection パターンとクラス


データを構造化するためにクラスを使用している場合は、クラス名の後ろにコンストラクタのように引数リストを指定することで、クラスをパターンとして使用できます。このパターンでは、インスタンスの属性を変数にバインドすることが可能です:

@example
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def location(point):
    match point:
        case Point(x=0, y=0):
            print("原点")
        case Point(x=0, y=y):
            print(f"Y座標は @{y@} で点はY軸上にある")
        case Point(x=x, y=0):
            print(f"X座標は @{x@} で点はX軸上にある")
        case Point():
            print("点は平面上のそれ以外のどこかにある")
        case _:
            print("座標ではない")
@end example

@menu
* 位置パラメータを用いたパターン:: 

@end menu

@node 位置パラメータを用いたパターン,,,パターンとクラス
@anchor{whatsnew/3 10 patterns-with-positional-parameters}@anchor{9b7}
@subsubsection 位置パラメータを用いたパターン


いくつかの組み込みクラスでは位置引数が使用でき、属性の順番を提供します(例: データクラス)。クラスの @code{__match_args__} 特殊属性でによって、パターンの中で属性の明確な位置を定義することもできます。("x", "y")が設定された場合、以下のすべてのパターンは等価です(すべて属性 @code{y} が @code{var} 変数に関連づけられます):

@example
Point(1, var)
Point(1, y=var)
Point(x=1, y=var)
Point(y=var, x=1)
@end example

@node ネストしたパターン,複雑なパターンとワイルドカード,パターンとクラス,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 nested-patterns}@anchor{9b8}
@subsubsection ネストしたパターン


パターンは任意に入れ子にすることができます。たとえば、データが複数のポイントを含む短いリストである場合、次のようにマッチさせることができます:

@example
match points:
    case []:
        print("リストに座標がない")
    case [Point(0, 0)]:
        print("リスト中には原点が1つのみある")
    case [Point(x, y)]:
        print(f"リスト中に @{x@}, @{y@} の点が1つある")
    case [Point(0, y1), Point(0, y2)]:
        print(f"リスト中にY軸上の2つの点 @{y1@}、@{y2@} がある")
    case _:
        print("リスト中にそれ以外のデータが見つかった")
@end example

@node 複雑なパターンとワイルドカード,ガード,ネストしたパターン,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 complex-patterns-and-the-wildcard}@anchor{9b9}
@subsubsection 複雑なパターンとワイルドカード


ここまでの例では、最後の case 文で @code{_} を単独のワイルドカードとして使用してきました。しかし、ワイルドカードはより複雑なパターン内でも使用できます。たとえば、 @code{('error', code, _)} のように使用することができます。

@example
match test_variable:
    case ('warning', code, 40):
        print("警告を受け取った")
    case ('error', code, _):
        print(f"エラー @{code@} が発生した")
@end example

上記のケースでは、 @code{test_variable} は ('error', code, 100) と ('error', code, 800) にマッチします。

@node ガード,その他の主要な機能,複雑なパターンとワイルドカード,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 guard}@anchor{9ba}
@subsubsection ガード


パターンに @code{if} 節を追加できます。これは "ガード" と呼ばれます。ガードがfalseの場合、@code{match} は次のcaseブロックの処理に移動します。ガードを評価する前に値が取り出されることに注意してください:

@example
match point:
    case Point(x, y) if x == y:
        print(f"座標は対角線 Y=X 上の @{x@} の位置にある")
    case Point(x, y):
        print(f"座標の位置は対角線上ではない")
@end example

@node その他の主要な機能,,ガード,PEP 634 構造的パターンマッチ
@anchor{whatsnew/3 10 other-key-features}@anchor{9bb}
@subsubsection その他の主要な機能


その他のいくつかの主要な機能:


@itemize -

@item 
アンパック代入と同様に、タプルおよびリストのパターンはまったく同じ意味を持ち、任意のシーケンスにマッチします。技術的には、対象はシーケンスである必要があります。そのため、重要な例外として、パターンはイテレータにはマッチしません。また、よくある誤りを防ぐために、シーケンスパターンは文字列にもマッチしません。

@item 
シーケンスパターンではワイルドカードをサポートしています。たとえば、@code{[x, y, *rest]} や @code{(x, y, *rest)} は、アンパック代入におけるワイルドカードと同様に動作します。@code{*} の後の名前を @code{_} にすることもでき、@code{(x, y, *_)} は少なくとも 2 つの要素を持つシーケンスにマッチしますが、残りの要素は変数に束縛されません。

@item 
マッピングパターン: @code{@{"bandwidth": b, "latency": l@}} では、辞書から @code{"bandwidth"} と @code{"latency"} の値を取得します。シーケンスパターンとは異なり、余分なキーは無視されます。また、ワイルドカード @code{**rest} もサポートされています。（ただし、@code{**_} は冗長になるため使用できません。）

@item 
サブパターンでは @code{as} キーワードを使用して値を取り込みます:

@example
case (Point(x1, y1), Point(x2, y2) as p2): ...
@end example

このように書くと x1、y1、x2、y2 は @code{as} 節を使わないときと同様に、さらにp2に対象の2番目の要素全体がバインドされます。

@item 
ほとんどのリテラルは同一性を比較します。しかし、シングルトンの @code{True}、@code{False}、@code{None} では識別値を比較します。

@item 
名前を付けた定数をパターンに使用できます。名前を付けた定数を、値を取り込む変数として解釈することを防ぐために、ドット付きの変数名にする必要があります。

@example
from enum import Enum
class Color(Enum):
    RED = 0
    GREEN = 1
    BLUE = 2

color = Color.GREEN
match color:
    case Color.RED:
        print("I see red!")
    case Color.GREEN:
        print("Grass is green")
    case Color.BLUE:
        print("I'm feeling the blues :(")
@end example
@end itemize

完全な仕様については 
@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/} を参照してください。モチベーションと理論的根拠は 
@geindex Python Enhancement Proposals; PEP 635
PEP 635@footnote{https://peps.python.org/pep-0635/} に、より詳細なチュートリアルは 
@geindex Python Enhancement Proposals; PEP 636
PEP 636@footnote{https://peps.python.org/pep-0636/} にあります。

@node Optional EncodingWarning and encoding="locale" option,,PEP 634 構造的パターンマッチ,新しい機能<8>
@anchor{whatsnew/3 10 optional-encodingwarning-and-encoding-locale-option}@anchor{9bc}@anchor{whatsnew/3 10 whatsnew310-pep597}@anchor{9bd}
@subsubsection Optional @code{EncodingWarning} and @code{encoding="locale"} option


The default encoding of @ref{9be,,TextIOWrapper} and @ref{316,,open()} is
platform and locale dependent. Since UTF-8 is used on most Unix
platforms, omitting @code{encoding} option when opening UTF-8 files
(e.g. JSON, YAML, TOML, Markdown) is a very common bug. For example:

@example
# BUG: "rb" mode or encoding="utf-8" should be used.
with open("data.json") as f:
    data = json.load(f)
@end example

To find this type of bug, an optional @code{EncodingWarning} is added.
It is emitted when @ref{89c,,sys.flags.warn_default_encoding}
is true and locale-specific default encoding is used.

@code{-X warn_default_encoding} option and 
@geindex PYTHONWARNDEFAULTENCODING
@geindex 環境変数; PYTHONWARNDEFAULTENCODING
@ref{9bf,,PYTHONWARNDEFAULTENCODING}
are added to enable the warning.

See @ref{9c0,,Text Encoding} for more information.

@node 型ヒントに関連する新しい機能<3>,その他の言語変更<4>,新しい機能<8>,What's New In Python 3 10
@anchor{whatsnew/3 10 new-feat-related-type-hints}@anchor{9c1}@anchor{whatsnew/3 10 new-features-related-to-type-hints}@anchor{9c2}
@subsection 型ヒントに関連する新しい機能


This section covers major changes affecting 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} type hints and
the @ref{10a,,typing} module.

@menu
* PEP 604; New Type Union Operator: PEP 604 New Type Union Operator. 
* PEP 612; Parameter Specification Variables: PEP 612 Parameter Specification Variables. 
* PEP 613; TypeAlias: PEP 613 TypeAlias. 
* PEP 647; User-Defined Type Guards: PEP 647 User-Defined Type Guards. 

@end menu

@node PEP 604 New Type Union Operator,PEP 612 Parameter Specification Variables,,型ヒントに関連する新しい機能<3>
@anchor{whatsnew/3 10 pep-604-new-type-union-operator}@anchor{9c3}
@subsubsection PEP 604: New Type Union Operator


A new type union operator was introduced which enables the syntax @code{X | Y}.
This provides a cleaner way of expressing 'either type X or type Y' instead of
using @ref{2a8,,typing.Union}, especially in type hints.

In previous versions of Python, to apply a type hint for functions accepting
arguments of multiple types, @ref{2a8,,typing.Union} was used:

@example
def square(number: Union[int, float]) -> Union[int, float]:
    return number ** 2
@end example

Type hints can now be written in a more succinct manner:

@example
def square(number: int | float) -> int | float:
    return number ** 2
@end example

This new syntax is also accepted as the second argument to @ref{2ad,,isinstance()}
and @ref{9c4,,issubclass()}:

@example
>>> isinstance(1, int | str)
True
@end example

See @ref{9c5,,Union 型} and 
@geindex Python Enhancement Proposals; PEP 604
PEP 604@footnote{https://peps.python.org/pep-0604/} for more details.

(Contributed by Maggie Moss and Philippe Prados in bpo-41428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41428},
with additions by Yurii Karabas and Serhiy Storchaka in bpo-44490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44490}.)

@node PEP 612 Parameter Specification Variables,PEP 613 TypeAlias,PEP 604 New Type Union Operator,型ヒントに関連する新しい機能<3>
@anchor{whatsnew/3 10 pep-612-parameter-specification-variables}@anchor{9c6}
@subsubsection PEP 612: Parameter Specification Variables


Two new options to improve the information provided to static type checkers for
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/}'s @code{Callable} have been added to the @ref{10a,,typing} module.

The first is the parameter specification variable.  They are used to forward the
parameter types of one callable to another callable -- a pattern commonly
found in higher order functions and decorators.  Examples of usage can be found
in @ref{487,,typing.ParamSpec}. Previously, there was no easy way to type annotate
dependency of parameter types in such a precise manner.

The second option is the new @code{Concatenate} operator. It's used in conjunction
with parameter specification variables to type annotate a higher order callable
which adds or removes parameters of another callable.  Examples of usage can
be found in @ref{9c7,,typing.Concatenate}.

See @ref{9c8,,typing.Callable}, @ref{487,,typing.ParamSpec},
@ref{9c7,,typing.Concatenate}, @ref{9c9,,typing.ParamSpecArgs},
@ref{9ca,,typing.ParamSpecKwargs}, and 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} for more details.

(Contributed by Ken Jin in bpo-41559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41559}, with minor enhancements by Jelle
Zijlstra in bpo-43783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43783}.  PEP written by Mark Mendoza.)

@node PEP 613 TypeAlias,PEP 647 User-Defined Type Guards,PEP 612 Parameter Specification Variables,型ヒントに関連する新しい機能<3>
@anchor{whatsnew/3 10 pep-613-typealias}@anchor{9cb}
@subsubsection PEP 613: TypeAlias


@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} introduced the concept of type aliases, only requiring them to be
top-level unannotated assignments. This simplicity sometimes made it difficult
for type checkers to distinguish between type aliases and ordinary assignments,
especially when forward references or invalid types were involved. Compare:

@example
StrCache = 'Cache[str]'  # a type alias
LOG_PREFIX = 'LOG[DEBUG]'  # a module constant
@end example

Now the @ref{10a,,typing} module has a special value @ref{9cc,,TypeAlias}
which lets you declare type aliases more explicitly:

@example
StrCache: TypeAlias = 'Cache[str]'  # a type alias
LOG_PREFIX = 'LOG[DEBUG]'  # a module constant
@end example

より詳しくは、 
@geindex Python Enhancement Proposals; PEP 613
PEP 613@footnote{https://peps.python.org/pep-0613/} をご覧ください。

(Contributed by Mikhail Golubev in bpo-41923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41923}.)

@node PEP 647 User-Defined Type Guards,,PEP 613 TypeAlias,型ヒントに関連する新しい機能<3>
@anchor{whatsnew/3 10 pep-647-user-defined-type-guards}@anchor{9cd}
@subsubsection PEP 647: User-Defined Type Guards


@ref{48c,,TypeGuard} has been added to the @ref{10a,,typing} module to annotate
type guard functions and improve information provided to static type checkers
during type narrowing.  For more information, please see
@ref{48c,,TypeGuard}'s documentation, and 
@geindex Python Enhancement Proposals; PEP 647
PEP 647@footnote{https://peps.python.org/pep-0647/}.

(Contributed by Ken Jin and Guido van Rossum in bpo-43766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43766}.
PEP written by Eric Traut.)

@node その他の言語変更<4>,新たなモジュール<4>,型ヒントに関連する新しい機能<3>,What's New In Python 3 10
@anchor{whatsnew/3 10 other-language-changes}@anchor{9ce}
@subsection その他の言語変更



@itemize *

@item 
The @ref{19b,,int} type has a new method @ref{9cf,,int.bit_count()}, returning the
number of ones in the binary expansion of a given integer, also known
as the population count. (Contributed by Niklas Fiekas in bpo-29882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29882}.)

@item 
The views returned by @ref{9d0,,dict.keys()}, @ref{9d1,,dict.values()} and
@ref{9d2,,dict.items()} now all have a @code{mapping} attribute that gives a
@ref{698,,types.MappingProxyType} object wrapping the original
dictionary. (Contributed by Dennis Sweeney in bpo-40890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40890}.)

@item 
@geindex Python Enhancement Proposals; PEP 618
PEP 618@footnote{https://peps.python.org/pep-0618/}: The @ref{1a0,,zip()} function now has an optional @code{strict} flag, used
to require that all the iterables have an equal length.

@item 
Builtin and extension functions that take integer arguments no longer accept
@ref{1fe,,Decimal}s, @ref{213,,Fraction}s and other
objects that can be converted to integers only with a loss (e.g. that have
the @ref{19d,,__int__()} method but do not have the
@ref{19e,,__index__()} method).
(Contributed by Serhiy Storchaka in bpo-37999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37999}.)

@item 
If @ref{9d3,,object.__ipow__()} returns @ref{1a2,,NotImplemented}, the operator will
correctly fall back to @ref{9d4,,object.__pow__()} and @ref{1a5,,object.__rpow__()} as expected.
(Contributed by Alex Shkop in bpo-38302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38302}.)

@item 
Assignment expressions can now be used unparenthesized within set literals
and set comprehensions, as well as in sequence indexes (but not slices).

@item 
Functions have a new @code{__builtins__} attribute which is used to look for
builtin symbols when a function is executed, instead of looking into
@code{__globals__['__builtins__']}. The attribute is initialized from
@code{__globals__["__builtins__"]} if it exists, else from the current builtins.
(Contributed by Mark Shannon in bpo-42990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42990}.)

@item 
Two new builtin functions -- @ref{9d5,,aiter()} and @ref{9d6,,anext()} have been added
to provide asynchronous counterparts to @ref{9d7,,iter()} and @ref{9d8,,next()},
respectively.
(Contributed by Joshua Bronson, Daniel Pope, and Justin Wang in bpo-31861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31861}.)

@item 
Static methods (@ref{453,,@@staticmethod}) and class methods
(@ref{48e,,@@classmethod}) now inherit the method attributes
(@code{__module__}, @code{__name__}, @code{__qualname__}, @code{__doc__},
@code{__annotations__}) and have a new @code{__wrapped__} attribute.
Moreover, static methods are now callable as regular functions.
(Contributed by Victor Stinner in bpo-43682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43682}.)

@item 
Annotations for complex targets (everything beside @code{simple name} targets
defined by 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/}) no longer cause any runtime effects with @code{from __future__ import annotations}.
(Contributed by Batuhan Taskaya in bpo-42737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42737}.)

@item 
Class and module objects now lazy-create empty annotations dicts on demand.
The annotations dicts are stored in the object’s @code{__dict__} for
backwards compatibility.  This improves the best practices for working
with @code{__annotations__}; for more information, please see
@ref{9d9,,Annotations Best Practices}.
(Contributed by Larry Hastings in bpo-43901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43901}.)

@item 
Annotations consist of @code{yield}, @code{yield from}, @code{await} or named expressions
are now forbidden under @code{from __future__ import annotations} due to their side
effects.
(Contributed by Batuhan Taskaya in bpo-42725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42725}.)

@item 
Usage of unbound variables, @code{super()} and other expressions that might
alter the processing of symbol table as annotations are now rendered
effectless under @code{from __future__ import annotations}.
(Contributed by Batuhan Taskaya in bpo-42725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42725}.)

@item 
Hashes of NaN values of both @ref{196,,float} type and
@ref{1fe,,decimal.Decimal} type now depend on object identity. Formerly, they
always hashed to @code{0} even though NaN values are not equal to one another.
This caused potentially quadratic runtime behavior due to excessive hash
collisions when creating dictionaries and sets containing multiple NaNs.
(Contributed by Raymond Hettinger in bpo-43475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43475}.)

@item 
A @ref{18e,,SyntaxError} (instead of a @ref{452,,NameError}) will be raised when deleting
the @ref{9da,,__debug__} constant.  (Contributed by Donghee Na in bpo-45000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45000}.)

@item 
@ref{18e,,SyntaxError} exceptions now have @code{end_lineno} and
@code{end_offset} attributes.  They will be @code{None} if not determined.
(Contributed by Pablo Galindo in bpo-43914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43914}.)
@end itemize

@node 新たなモジュール<4>,改良されたモジュール<4>,その他の言語変更<4>,What's New In Python 3 10
@anchor{whatsnew/3 10 new-modules}@anchor{9db}
@subsection 新たなモジュール



@itemize *

@item 
None.
@end itemize

@node 改良されたモジュール<4>,最適化<5>,新たなモジュール<4>,What's New In Python 3 10
@anchor{whatsnew/3 10 improved-modules}@anchor{9dc}
@subsection 改良されたモジュール


@menu
* asyncio: asyncio<7>. 
* argparse: argparse<4>. 
* array: array<2>. 
* asynchat@comma{} asyncore@comma{} smtpd: asynchat asyncore smtpd. 
* base64: base64<3>. 
* bdb: bdb<2>. 
* bisect:: 
* codecs:: 
* collections.abc: collections abc. 
* contextlib: contextlib<2>. 
* curses: curses<2>. 
* データクラス: データクラス<2>. 
* distutils: distutils<2>. 
* doctest: doctest<2>. 
* エンコーディング:: 
* enum: enum<4>. 
* fileinput:: 
* faulthandler: faulthandler<2>. 
* gc: gc<2>. 
* glob: glob<2>. 
* hashlib: hashlib<3>. 
* hmac: hmac<2>. 
* IDLE と idelelib: IDLE と idelelib<2>. 
* importlib.metadata: importlib metadata<2>. 
* inspect: inspect<4>. 
* itertools: itertools<4>. 
* linecache: linecache<2>. 
* os: os<5>. 
* os.path: os path<4>. 
* pathlib: pathlib<8>. 
* プラットフォーム: プラットフォーム<3>. 
* pprint:: 
* py_compile:: 
* pyclbr:: 
* shelve:: 
* statistics: statistics<3>. 
* site: site<2>. 
* socket: socket<3>. 
* ssl: ssl<4>. 
* sqlite3: sqlite3<6>. 
* sys: sys<5>. 
* _thread:: 
* threading: threading<4>. 
* traceback: traceback<3>. 
* types: types<4>. 
* typing: typing<6>. 
* unittest: unittest<6>. 
* urllib.parse: urllib parse. 
* xml: xml<2>. 
* zipimport: zipimport<3>. 

@end menu

@node asyncio<7>,argparse<4>,,改良されたモジュール<4>
@anchor{whatsnew/3 10 asyncio}@anchor{9dd}
@subsubsection asyncio


Add missing @ref{9de,,connect_accepted_socket()}
method.
(Contributed by Alex Grönholm in bpo-41332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41332}.)

@node argparse<4>,array<2>,asyncio<7>,改良されたモジュール<4>
@anchor{whatsnew/3 10 argparse}@anchor{9df}
@subsubsection argparse


Misleading phrase "optional arguments" was replaced with "options" in argparse help. Some tests might require adaptation if they rely on exact output match.
(Contributed by Raymond Hettinger in bpo-9694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9694}.)

@node array<2>,asynchat asyncore smtpd,argparse<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 array}@anchor{9e0}
@subsubsection array


The @ref{9e1,,index()} method of @ref{4be,,array.array} now has
optional `start' and `stop' parameters.
(Contributed by Anders Lorentsen and Zackery Spytz in bpo-31956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31956}.)

@node asynchat asyncore smtpd,base64<3>,array<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 asynchat-asyncore-smtpd}@anchor{9e2}
@subsubsection asynchat, asyncore, smtpd


These modules have been marked as deprecated in their module documentation
since Python 3.6.  An import-time @ref{1a3,,DeprecationWarning} has now been
added to all three of these modules.

@node base64<3>,bdb<2>,asynchat asyncore smtpd,改良されたモジュール<4>
@anchor{whatsnew/3 10 base64}@anchor{9e3}
@subsubsection base64


Add @ref{9e4,,base64.b32hexencode()} and @ref{9e5,,base64.b32hexdecode()} to support the
Base32 Encoding with Extended Hex Alphabet.

@node bdb<2>,bisect,base64<3>,改良されたモジュール<4>
@anchor{whatsnew/3 10 bdb}@anchor{9e6}
@subsubsection bdb


Add @code{clearBreakpoints()} to reset all set breakpoints.
(Contributed by Irit Katriel in bpo-24160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24160}.)

@node bisect,codecs,bdb<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 bisect}@anchor{9e7}
@subsubsection bisect


Added the possibility of providing a `key' function to the APIs in the @ref{12,,bisect}
module. (Contributed by Raymond Hettinger in bpo-4356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4356}.)

@node codecs,collections abc,bisect,改良されたモジュール<4>
@anchor{whatsnew/3 10 codecs}@anchor{9e8}
@subsubsection codecs


Add a @ref{9e9,,codecs.unregister()} function to unregister a codec search function.
(Contributed by Hai Shi in bpo-41842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41842}.)

@node collections abc,contextlib<2>,codecs,改良されたモジュール<4>
@anchor{whatsnew/3 10 collections-abc}@anchor{9ea}
@subsubsection collections.abc


The @code{__args__} of the @ref{8c1,,parameterized generic} for
@ref{9eb,,collections.abc.Callable} are now consistent with @ref{9c8,,typing.Callable}.
@ref{9eb,,collections.abc.Callable} generic now flattens type parameters, similar
to what @ref{9c8,,typing.Callable} currently does.  This means that
@code{collections.abc.Callable[[int, str], str]} will have @code{__args__} of
@code{(int, str, str)}; previously this was @code{([int, str], str)}.  To allow this
change, @ref{9ec,,types.GenericAlias} can now be subclassed, and a subclass will
be returned when subscripting the @ref{9eb,,collections.abc.Callable} type.  Note
that a @ref{198,,TypeError} may be raised for invalid forms of parameterizing
@ref{9eb,,collections.abc.Callable} which may have passed silently in Python 3.9.
(Contributed by Ken Jin in bpo-42195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42195}.)

@node contextlib<2>,curses<2>,collections abc,改良されたモジュール<4>
@anchor{whatsnew/3 10 contextlib}@anchor{9ed}
@subsubsection contextlib


Add a @ref{9ee,,contextlib.aclosing()} context manager to safely close async generators
and objects representing asynchronously released resources.
(Contributed by Joongi Kim and John Belmonte in bpo-41229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41229}.)

Add asynchronous context manager support to @ref{9ef,,contextlib.nullcontext()}.
(Contributed by Tom Gringauz in bpo-41543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41543}.)

Add @ref{9f0,,AsyncContextDecorator}, for supporting usage of async
context managers as decorators.

@node curses<2>,データクラス<2>,contextlib<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 curses}@anchor{9f1}
@subsubsection curses


The extended color functions added in ncurses 6.1 will be used transparently
by @ref{9f2,,curses.color_content()}, @ref{9f3,,curses.init_color()},
@ref{9f4,,curses.init_pair()}, and @ref{9f5,,curses.pair_content()}. A new function,
@ref{9f6,,curses.has_extended_color_support()}, indicates whether extended color
support is provided by the underlying ncurses library.
(Contributed by Jeffrey Kintscher and Hans Petter Jansson in bpo-36982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36982}.)

The @code{BUTTON5_*} constants are now exposed in the @ref{2f,,curses} module if
they are provided by the underlying curses library.
(Contributed by Zackery Spytz in bpo-39273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39273}.)

@node データクラス<2>,distutils<2>,curses<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 dataclasses}@anchor{9f7}
@subsubsection データクラス


@menu
* __slots__:: 
* Keyword-only fields:: 

@end menu

@node __slots__,Keyword-only fields,,データクラス<2>
@anchor{whatsnew/3 10 slots}@anchor{9f8}
@subsubsection __slots__


Added @code{slots} parameter in @ref{4e1,,dataclasses.dataclass()} decorator.
(Contributed by Yurii Karabas in bpo-42269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42269})

@node Keyword-only fields,,__slots__,データクラス<2>
@anchor{whatsnew/3 10 keyword-only-fields}@anchor{9f9}
@subsubsection Keyword-only fields


dataclasses now supports fields that are keyword-only in the
generated __init__ method.  There are a number of ways of specifying
keyword-only fields.

You can say that every field is keyword-only:

@example
from dataclasses import dataclass

@@dataclass(kw_only=True)
class Birthday:
    name: str
    birthday: datetime.date
@end example

Both @code{name} and @code{birthday} are keyword-only parameters to the
generated __init__ method.

You can specify keyword-only on a per-field basis:

@example
from dataclasses import dataclass, field

@@dataclass
class Birthday:
    name: str
    birthday: datetime.date = field(kw_only=True)
@end example

Here only @code{birthday} is keyword-only.  If you set @code{kw_only} on
individual fields, be aware that there are rules about re-ordering
fields due to keyword-only fields needing to follow non-keyword-only
fields.  See the full dataclasses documentation for details.

You can also specify that all fields following a KW_ONLY marker are
keyword-only.  This will probably be the most common usage:

@example
from dataclasses import dataclass, KW_ONLY

@@dataclass
class Point:
    x: float
    y: float
    _: KW_ONLY
    z: float = 0.0
    t: float = 0.0
@end example

Here, @code{z} and @code{t} are keyword-only parameters, while @code{x} and
@code{y} are not.
(Contributed by Eric V. Smith in bpo-43532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43532}.)

@node distutils<2>,doctest<2>,データクラス<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 distutils}@anchor{9fa}@anchor{whatsnew/3 10 distutils-deprecated}@anchor{934}
@subsubsection distutils


The entire @code{distutils} package is deprecated, to be removed in Python
3.12. Its functionality for specifying package builds has already been
completely replaced by third-party packages @code{setuptools} and
@code{packaging}, and most other commonly used APIs are available elsewhere
in the standard library (such as @ref{af,,platform}, @ref{ca,,shutil},
@ref{dc,,subprocess} or @ref{e1,,sysconfig}). There are no plans to migrate
any other functionality from @code{distutils}, and applications that are
using other functions should plan to make private copies of the code.
Refer to 
@geindex Python Enhancement Proposals; PEP 632
PEP 632@footnote{https://peps.python.org/pep-0632/} for discussion.

The @code{bdist_wininst} command deprecated in Python 3.8 has been removed.
The @code{bdist_wheel} command is now recommended to distribute binary packages
on Windows.
(Contributed by Victor Stinner in bpo-42802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42802}.)

@node doctest<2>,エンコーディング,distutils<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 doctest}@anchor{9fb}
@subsubsection doctest


When a module does not define @code{__loader__}, fall back to @code{__spec__.loader}.
(Contributed by Brett Cannon in bpo-42133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42133}.)

@node エンコーディング,enum<4>,doctest<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 encodings}@anchor{9fc}
@subsubsection エンコーディング


@ref{9fd,,encodings.normalize_encoding()} now ignores non-ASCII characters.
(Contributed by Hai Shi in bpo-39337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39337}.)

@node enum<4>,fileinput,エンコーディング,改良されたモジュール<4>
@anchor{whatsnew/3 10 enum}@anchor{9fe}
@subsubsection enum


@ref{842,,Enum} @ref{82f,,__repr__()} now returns @code{enum_name.member_name} and
@ref{830,,__str__()} now returns @code{member_name}.  Stdlib enums available as
module constants have a @ref{1c1,,repr()} of @code{module_name.member_name}.
(Contributed by Ethan Furman in bpo-40066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40066}.)

Add @ref{82d,,enum.StrEnum} for enums where all members are strings.
(Contributed by Ethan Furman in bpo-41816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41816}.)

@node fileinput,faulthandler<2>,enum<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 fileinput}@anchor{9ff}
@subsubsection fileinput


Add `encoding' and `errors' parameters in @ref{a00,,fileinput.input()} and
@ref{940,,fileinput.FileInput}.
(Contributed by Inada Naoki in bpo-43712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43712}.)

@ref{a01,,fileinput.hook_compressed()} now returns @ref{9be,,TextIOWrapper} object
when `mode' is "r" and file is compressed, like uncompressed files.
(Contributed by Inada Naoki in bpo-5758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5758}.)

@node faulthandler<2>,gc<2>,fileinput,改良されたモジュール<4>
@anchor{whatsnew/3 10 faulthandler}@anchor{a02}
@subsubsection faulthandler


The @ref{5c,,faulthandler} module now detects if a fatal error occurs during a
garbage collector collection.
(Contributed by Victor Stinner in bpo-44466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44466}.)

@node gc<2>,glob<2>,faulthandler<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 gc}@anchor{a03}
@subsubsection gc


Add audit hooks for @ref{a04,,gc.get_objects()}, @ref{a05,,gc.get_referrers()} and
@ref{a06,,gc.get_referents()}. (Contributed by Pablo Galindo in bpo-43439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43439}.)

@node glob<2>,hashlib<3>,gc<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 glob}@anchor{a07}
@subsubsection glob


Add the `root_dir' and `dir_fd' parameters in @ref{5a0,,glob()} and
@ref{a08,,iglob()} which allow to specify the root directory for searching.
(Contributed by Serhiy Storchaka in bpo-38144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38144}.)

@node hashlib<3>,hmac<2>,glob<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 hashlib}@anchor{a09}
@subsubsection hashlib


The hashlib module requires OpenSSL 1.1.1 or newer.
(Contributed by Christian Heimes in 
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/} and bpo-43669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43669}.)

The hashlib module has preliminary support for OpenSSL 3.0.0.
(Contributed by Christian Heimes in bpo-38820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38820} and other issues.)

The pure-Python fallback of @ref{733,,pbkdf2_hmac()} is deprecated. In
the future PBKDF2-HMAC will only be available when Python has been built with
OpenSSL support.
(Contributed by Christian Heimes in bpo-43880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43880}.)

@node hmac<2>,IDLE と idelelib<2>,hashlib<3>,改良されたモジュール<4>
@anchor{whatsnew/3 10 hmac}@anchor{a0a}
@subsubsection hmac


The hmac module now uses OpenSSL's HMAC implementation internally.
(Contributed by Christian Heimes in bpo-40645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40645}.)

@node IDLE と idelelib<2>,importlib metadata<2>,hmac<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 idle-and-idlelib}@anchor{a0b}
@subsubsection IDLE と idelelib


Make IDLE invoke @ref{a0c,,sys.excepthook()} (when started without '-n').
User hooks were previously ignored.  (Contributed by Ken Hilton in
bpo-43008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43008}.)

Rearrange the settings dialog.  Split the 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.  (Contributed by Terry Jan
Reedy in bpo-40468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40468}.)  Move the indent space setting from the Font tab to
the new Windows tab.  (Contributed by Mark Roseman and Terry Jan Reedy in
bpo-33962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33962}.)

The changes above were backported to a 3.9 maintenance release.

Add a Shell sidebar.  Move the primary prompt ('>>>') to the sidebar.
Add secondary prompts ('...') to the sidebar.  Left click and optional
drag selects one or more lines of text, as with the editor
line number sidebar.  Right click after selecting text lines displays
a context menu with 'copy with prompts'.  This zips together prompts
from the sidebar with lines from the selected text.  This option also
appears on the context menu for the text.  (Contributed by Tal Einat
in bpo-37903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37903}.)

Use spaces instead of tabs to indent interactive code.  This makes
interactive code entries 'look right'.  Making this feasible was a
major motivation for adding the shell sidebar.  (Contributed by
Terry Jan Reedy in bpo-37892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37892}.)

Highlight the new @ref{a0d,,soft keywords} @ref{a0e,,match},
@ref{a0e,,case}, and @ref{a0f,,_} in
pattern-matching statements. However, this highlighting is not perfect
and will be incorrect in some rare cases, including some @code{_}-s in
@code{case} patterns.  (Contributed by Tal Einat in bpo-44010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44010}.)

New in 3.10 maintenance releases.

Apply syntax highlighting to @code{.pyi} files. (Contributed by Alex
Waygood and Terry Jan Reedy in bpo-45447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45447}.)

Include prompts when saving Shell with inputs and outputs.
(Contributed by Terry Jan Reedy in gh-95191@footnote{https://github.com/python/cpython/issues/95191}.)

@node importlib metadata<2>,inspect<4>,IDLE と idelelib<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 importlib-metadata}@anchor{a10}
@subsubsection importlib.metadata


Feature parity with @code{importlib_metadata} 4.6
(history@footnote{https://importlib-metadata.readthedocs.io/en/latest/history.html}).

@ref{589,,importlib.metadata entry points}
now provide a nicer experience
for selecting entry points by group and name through a new
@ref{589,,importlib.metadata.EntryPoints} class. See the Compatibility
Note in the docs for more info on the deprecation and usage.

Added @ref{a11,,importlib.metadata.packages_distributions()}
for resolving top-level Python modules and packages to their
@ref{a12,,importlib.metadata.Distribution}.

@node inspect<4>,itertools<4>,importlib metadata<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 inspect}@anchor{a13}
@subsubsection inspect


When a module does not define @code{__loader__}, fall back to @code{__spec__.loader}.
(Contributed by Brett Cannon in bpo-42133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42133}.)

Add @ref{a14,,inspect.get_annotations()}, which safely computes the annotations
defined on an object. It works around the quirks of accessing the annotations
on various types of objects, and makes very few assumptions about the object
it examines. @ref{a14,,inspect.get_annotations()} can also correctly un-stringize
stringized annotations.  @ref{a14,,inspect.get_annotations()} is now considered
best practice for accessing the annotations dict defined on any Python object;
for more information on best practices for working with annotations, please see
@ref{9d9,,Annotations Best Practices}.
Relatedly, @ref{22f,,inspect.signature()},
@ref{942,,inspect.Signature.from_callable()}, and @code{inspect.Signature.from_function()}
now call @ref{a14,,inspect.get_annotations()} to retrieve annotations. This means
@ref{22f,,inspect.signature()} and @ref{942,,inspect.Signature.from_callable()} can
also now un-stringize stringized annotations.
(Contributed by Larry Hastings in bpo-43817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43817}.)

@node itertools<4>,linecache<2>,inspect<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 itertools}@anchor{a15}
@subsubsection itertools


Add @ref{a16,,itertools.pairwise()}.
(Contributed by Raymond Hettinger in bpo-38200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38200}.)

@node linecache<2>,os<5>,itertools<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 linecache}@anchor{a17}
@subsubsection linecache


When a module does not define @code{__loader__}, fall back to @code{__spec__.loader}.
(Contributed by Brett Cannon in bpo-42133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42133}.)

@node os<5>,os path<4>,linecache<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 os}@anchor{a18}
@subsubsection os


Add @ref{4db,,os.cpu_count()} support for VxWorks RTOS.
(Contributed by Peixing Xin in bpo-41440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41440}.)

Add a new function @ref{a19,,os.eventfd()} and related helpers to wrap the
@code{eventfd2} syscall on Linux.
(Contributed by Christian Heimes in bpo-41001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41001}.)

Add @ref{a1a,,os.splice()} that allows to move data between two file
descriptors without copying between kernel address space and user
address space, where one of the file descriptors must refer to a
pipe. (Contributed by Pablo Galindo in bpo-41625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41625}.)

Add @ref{a1b,,O_EVTONLY}, @ref{a1c,,O_FSYNC}, @ref{a1d,,O_SYMLINK}
and @ref{a1e,,O_NOFOLLOW_ANY} for macOS.
(Contributed by Donghee Na in bpo-43106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43106}.)

@node os path<4>,pathlib<8>,os<5>,改良されたモジュール<4>
@anchor{whatsnew/3 10 os-path}@anchor{a1f}
@subsubsection os.path


@ref{262,,os.path.realpath()} now accepts a `strict' keyword-only argument. When set
to @code{True}, @ref{2c0,,OSError} is raised if a path doesn't exist or a symlink loop
is encountered.
(Contributed by Barney Gale in bpo-43757@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43757}.)

@node pathlib<8>,プラットフォーム<3>,os path<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 pathlib}@anchor{a20}
@subsubsection pathlib


Add slice support to @ref{a21,,PurePath.parents}.
(Contributed by Joshua Cannon in bpo-35498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35498}.)

Add negative indexing support to @ref{a21,,PurePath.parents}.
(Contributed by Yaroslav Pankovych in bpo-21041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21041}.)

Add @ref{a22,,Path.hardlink_to} method that
supersedes @code{link_to()}. The new method has the same argument
order as @ref{a23,,symlink_to()}.
(Contributed by Barney Gale in bpo-39950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39950}.)

@ref{a24,,pathlib.Path.stat()} and @ref{a25,,chmod()} now accept a
`follow_symlinks' keyword-only argument for consistency with corresponding
functions in the @ref{a5,,os} module.
(Contributed by Barney Gale in bpo-39906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39906}.)

@node プラットフォーム<3>,pprint,pathlib<8>,改良されたモジュール<4>
@anchor{whatsnew/3 10 platform}@anchor{a26}
@subsubsection プラットフォーム


Add @ref{a27,,platform.freedesktop_os_release()} to retrieve operation system
identification from freedesktop.org os-release@footnote{https://www.freedesktop.org/software/systemd/man/os-release.html} standard file.
(Contributed by Christian Heimes in bpo-28468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28468}.)

@node pprint,py_compile,プラットフォーム<3>,改良されたモジュール<4>
@anchor{whatsnew/3 10 pprint}@anchor{a28}
@subsubsection pprint


@ref{a29,,pprint.pprint()} now accepts a new @code{underscore_numbers} keyword argument.
(Contributed by sblondon in bpo-42914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42914}.)

@ref{b3,,pprint} can now pretty-print @ref{4e1,,dataclasses.dataclass} instances.
(Contributed by Lewis Gaul in bpo-43080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43080}.)

@node py_compile,pyclbr,pprint,改良されたモジュール<4>
@anchor{whatsnew/3 10 py-compile}@anchor{a2a}
@subsubsection py_compile


Add @code{--quiet} option to command-line interface of @ref{b8,,py_compile}.
(Contributed by Gregory Schevchenko in bpo-38731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38731}.)

@node pyclbr,shelve,py_compile,改良されたモジュール<4>
@anchor{whatsnew/3 10 pyclbr}@anchor{a2b}
@subsubsection pyclbr


Add an @code{end_lineno} attribute to the @code{Function} and @code{Class}
objects in the tree returned by @ref{a2c,,pyclbr.readmodule()} and
@ref{a2d,,pyclbr.readmodule_ex()}.  It matches the existing (start) @code{lineno}.
(Contributed by Aviral Srivastava in bpo-38307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38307}.)

@node shelve,statistics<3>,pyclbr,改良されたモジュール<4>
@anchor{whatsnew/3 10 shelve}@anchor{a2e}
@subsubsection shelve


The @ref{c8,,shelve} module now uses @ref{a2f,,pickle.DEFAULT_PROTOCOL} by default
instead of @ref{ab,,pickle} protocol @code{3} when creating shelves.
(Contributed by Zackery Spytz in bpo-34204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34204}.)

@node statistics<3>,site<2>,shelve,改良されたモジュール<4>
@anchor{whatsnew/3 10 statistics}@anchor{a30}
@subsubsection statistics


Add @ref{a31,,covariance()}, Pearson's
@ref{6e3,,correlation()}, and simple
@ref{a32,,linear_regression()} functions.
(Contributed by Tymoteusz Wołodźko in bpo-38490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38490}.)

@node site<2>,socket<3>,statistics<3>,改良されたモジュール<4>
@anchor{whatsnew/3 10 site}@anchor{a33}
@subsubsection site


When a module does not define @code{__loader__}, fall back to @code{__spec__.loader}.
(Contributed by Brett Cannon in bpo-42133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42133}.)

@node socket<3>,ssl<4>,site<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 socket}@anchor{a34}
@subsubsection socket


The exception @ref{a35,,socket.timeout} is now an alias of @ref{a36,,TimeoutError}.
(Contributed by Christian Heimes in bpo-42413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42413}.)

Add option to create MPTCP sockets with @code{IPPROTO_MPTCP}
(Contributed by Rui Cunha in bpo-43571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43571}.)

Add @code{IP_RECVTOS} option to receive the type of service (ToS) or DSCP/ECN fields
(Contributed by Georg Sauthoff in bpo-44077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44077}.)

@node ssl<4>,sqlite3<6>,socket<3>,改良されたモジュール<4>
@anchor{whatsnew/3 10 ssl}@anchor{a37}
@subsubsection ssl


The ssl module requires OpenSSL 1.1.1 or newer.
(Contributed by Christian Heimes in 
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/} and bpo-43669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43669}.)

The ssl module has preliminary support for OpenSSL 3.0.0 and new option
@ref{a38,,OP_IGNORE_UNEXPECTED_EOF}.
(Contributed by Christian Heimes in bpo-38820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38820}, bpo-43794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43794},
bpo-43788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43788}, bpo-43791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43791}, bpo-43799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43799}, bpo-43920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43920},
bpo-43789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43789}, and bpo-43811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43811}.)

Deprecated function and use of deprecated constants now result in
a @ref{1a3,,DeprecationWarning}. @ref{a39,,ssl.SSLContext.options} has
@ref{a3a,,OP_NO_SSLv2} and @ref{a3b,,OP_NO_SSLv3} set by default and
therefore cannot warn about setting the flag again. The
@ref{a3c,,deprecation section} has a list of deprecated
features.
(Contributed by Christian Heimes in bpo-43880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43880}.)

The ssl module now has more secure default settings. Ciphers without forward
secrecy or SHA-1 MAC are disabled by default. Security level 2 prohibits
weak RSA, DH, and ECC keys with less than 112 bits of security.
@ref{357,,SSLContext} defaults to minimum protocol version TLS 1.2.
Settings are based on Hynek Schlawack's research.
(Contributed by Christian Heimes in bpo-43998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43998}.)

The deprecated protocols SSL 3.0, TLS 1.0, and TLS 1.1 are no longer
officially supported. Python does not block them actively. However
OpenSSL build options, distro configurations, vendor patches, and cipher
suites may prevent a successful handshake.

Add a `timeout' parameter to the @ref{a3d,,ssl.get_server_certificate()} function.
(Contributed by Zackery Spytz in bpo-31870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31870}.)

The ssl module uses heap-types and multi-phase initialization.
(Contributed by Christian Heimes in bpo-42333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42333}.)

A new verify flag @ref{481,,VERIFY_X509_PARTIAL_CHAIN} has been added.
(Contributed by l0x in bpo-40849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40849}.)

@node sqlite3<6>,sys<5>,ssl<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 sqlite3}@anchor{a3e}
@subsubsection sqlite3


Add audit events for @ref{5a6,,connect()},
@ref{a3f,,enable_load_extension()}, and
@ref{6df,,load_extension()}.
(Contributed by Erlend E. Aasland in bpo-43762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43762}.)

@node sys<5>,_thread,sqlite3<6>,改良されたモジュール<4>
@anchor{whatsnew/3 10 sys}@anchor{a40}
@subsubsection sys


Add @ref{a41,,sys.orig_argv} attribute: the list of the original command line
arguments passed to the Python executable.
(Contributed by Victor Stinner in bpo-23427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23427}.)

Add @ref{a42,,sys.stdlib_module_names}, containing the list of the standard library
module names.
(Contributed by Victor Stinner in bpo-42955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42955}.)

@node _thread,threading<4>,sys<5>,改良されたモジュール<4>
@anchor{whatsnew/3 10 thread}@anchor{a43}
@subsubsection _thread


@ref{a44,,_thread.interrupt_main()} now takes an optional signal number to
simulate (the default is still @ref{253,,signal.SIGINT}).
(Contributed by Antoine Pitrou in bpo-43356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43356}.)

@node threading<4>,traceback<3>,_thread,改良されたモジュール<4>
@anchor{whatsnew/3 10 threading}@anchor{a45}
@subsubsection threading


Add @ref{a46,,threading.gettrace()} and @ref{a47,,threading.getprofile()} to
retrieve the functions set by @ref{a48,,threading.settrace()} and
@ref{a49,,threading.setprofile()} respectively.
(Contributed by Mario Corchero in bpo-42251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42251}.)

Add @ref{a4a,,threading.__excepthook__} to allow retrieving the original value
of @ref{a4b,,threading.excepthook()} in case it is set to a broken or a different
value.
(Contributed by Mario Corchero in bpo-42308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42308}.)

@node traceback<3>,types<4>,threading<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 traceback}@anchor{a4c}
@subsubsection traceback


The @ref{a4d,,format_exception()},
@ref{a4e,,format_exception_only()}, and
@ref{a4f,,print_exception()} functions can now take an exception object
as a positional-only argument.
(Contributed by Zackery Spytz and Matthias Bussonnier in bpo-26389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26389}.)

@node types<4>,typing<6>,traceback<3>,改良されたモジュール<4>
@anchor{whatsnew/3 10 types}@anchor{a50}
@subsubsection types


Reintroduce the @ref{a51,,types.EllipsisType}, @ref{a52,,types.NoneType}
and @ref{a53,,types.NotImplementedType} classes, providing a new set
of types readily interpretable by type checkers.
(Contributed by Bas van Beek in bpo-41810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41810}.)

@node typing<6>,unittest<6>,types<4>,改良されたモジュール<4>
@anchor{whatsnew/3 10 typing}@anchor{a54}
@subsubsection typing


For major changes, see @ref{9c1,,型ヒントに関連する新しい機能}.

The behavior of @ref{a55,,typing.Literal} was changed to conform with 
@geindex Python Enhancement Proposals; PEP 586
PEP 586@footnote{https://peps.python.org/pep-0586/}
and to match the behavior of static type checkers specified in the PEP.


@enumerate 

@item 
@code{Literal} now de-duplicates parameters.

@item 
Equality comparisons between @code{Literal} objects are now order independent.

@item 
@code{Literal} comparisons now respect types.  For example,
@code{Literal[0] == Literal[False]} previously evaluated to @code{True}.  It is
now @code{False}.  To support this change, the internally used type cache now
supports differentiating types.

@item 
@code{Literal} objects will now raise a @ref{198,,TypeError} exception during
equality comparisons if any of their parameters are not @ref{824,,hashable}.
Note that declaring @code{Literal} with unhashable parameters will not throw
an error:

@example
>>> from typing import Literal
>>> Literal[@{0@}]
>>> Literal[@{0@}] == Literal[@{False@}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
@end example
@end enumerate

(bpo-42345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42345} でのYurii Karabasの貢献による)

Add new function @ref{a56,,typing.is_typeddict()} to introspect if an annotation
is a @ref{332,,typing.TypedDict}.
(Contributed by Patrick Reader in bpo-41792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41792}.)

Subclasses of @code{typing.Protocol} which only have data variables declared
will now raise a @code{TypeError} when checked with @code{isinstance} unless they
are decorated with @ref{675,,runtime_checkable()}.  Previously, these checks
passed silently.  Users should decorate their
subclasses with the @code{runtime_checkable()} decorator
if they want runtime protocols.
(Contributed by Yurii Karabas in bpo-38908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38908}.)

Importing from the @code{typing.io} and @code{typing.re} submodules will now emit
@ref{1a3,,DeprecationWarning}.  These submodules have been deprecated since
Python 3.8 and will be removed in a future version of Python.  Anything
belonging to those submodules should be imported directly from
@ref{10a,,typing} instead.
(Contributed by Sebastian Rittau in bpo-38291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38291}.)

@node unittest<6>,urllib parse,typing<6>,改良されたモジュール<4>
@anchor{whatsnew/3 10 unittest}@anchor{a57}
@subsubsection unittest


Add new method @ref{a58,,assertNoLogs()} to complement the
existing @ref{a59,,assertLogs()}. (Contributed by Kit Yan Choi
in bpo-39385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39385}.)

@node urllib parse,xml<2>,unittest<6>,改良されたモジュール<4>
@anchor{whatsnew/3 10 urllib-parse}@anchor{a5a}
@subsubsection urllib.parse


Python versions earlier than Python 3.10 allowed using both @code{;} and @code{&} as
query parameter separators in @ref{31f,,urllib.parse.parse_qs()} and
@ref{31e,,urllib.parse.parse_qsl()}.  Due to security concerns, and to conform with
newer W3C recommendations, this has been changed to allow only a single
separator key, with @code{&} as the default.  This change also affects
@code{cgi.parse()} and @code{cgi.parse_multipart()} as they use the affected
functions internally.  For more details, please see their respective
documentation.
(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}.)

The presence of newline or tab characters in parts of a URL allows for some
forms of attacks. Following the WHATWG specification that updates 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html},
ASCII newline @code{\n}, @code{\r} and tab @code{\t} characters are stripped from the
URL by the parser in @ref{110,,urllib.parse} preventing such attacks. The removal
characters are controlled by a new module level variable
@code{urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE}. (See gh-88048@footnote{https://github.com/python/cpython/issues/88048})

@node xml<2>,zipimport<3>,urllib parse,改良されたモジュール<4>
@anchor{whatsnew/3 10 xml}@anchor{a5b}
@subsubsection xml


Add a @ref{a5c,,LexicalHandler} class to the
@ref{130,,xml.sax.handler} module.
(Contributed by Jonathan Gossage and Zackery Spytz in bpo-35018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35018}.)

@node zipimport<3>,,xml<2>,改良されたモジュール<4>
@anchor{whatsnew/3 10 zipimport}@anchor{a5d}
@subsubsection zipimport


Add methods related to 
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/}: @ref{a5e,,find_spec()},
@ref{a5f,,zipimport.zipimporter.create_module()}, and
@ref{339,,zipimport.zipimporter.exec_module()}.
(Contributed by Brett Cannon in bpo-42131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42131}.)

Add @ref{a60,,invalidate_caches()} method.
(Contributed by Desmond Cheong in bpo-14678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14678}.)

@node 最適化<5>,非推奨<6>,改良されたモジュール<4>,What's New In Python 3 10
@anchor{whatsnew/3 10 optimizations}@anchor{a61}
@subsection 最適化



@itemize *

@item 
Constructors @ref{169,,str()}, @ref{192,,bytes()} and @ref{344,,bytearray()} are now faster
(around 30--40% for small objects).
(Contributed by Serhiy Storchaka in bpo-41334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41334}.)

@item 
The @ref{c3,,runpy} module now imports fewer modules.
The @code{python3 -m module-name} command startup time is 1.4x faster in
average. On Linux, @code{python3 -I -m module-name} imports 69 modules on Python
3.9, whereas it only imports 51 modules (-18) on Python 3.10.
(Contributed by Victor Stinner in bpo-41006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41006} and bpo-41718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41718}.)

@item 
The @code{LOAD_ATTR} instruction now uses new "per opcode cache" mechanism.  It
is about 36% faster now for regular attributes and 44% faster for slots.
(Contributed by Pablo Galindo and Yury Selivanov in bpo-42093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42093} and Guido
van Rossum in bpo-42927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42927}, based on ideas implemented originally in PyPy
and MicroPython.)

@item 
When building Python with @ref{a62,,--enable-optimizations} now
@code{-fno-semantic-interposition} is added to both the compile and link line.
This speeds builds of the Python interpreter created with @ref{a63,,--enable-shared}
with @code{gcc} by up to 30%. See this article@footnote{https://developers.redhat.com/blog/2020/06/25/red-hat-enterprise-linux-8-2-brings-faster-python-3-8-run-speeds/}
for more details. (Contributed by Victor Stinner and Pablo Galindo in
bpo-38980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38980}.)

@item 
Use a new output buffer management code for @ref{14,,bz2} / @ref{8e,,lzma} /
@ref{139,,zlib} modules, and add @code{.readall()} function to
@code{_compression.DecompressReader} class. bz2 decompression is now 1.09x ~ 1.17x
faster, lzma decompression 1.20x ~ 1.32x faster, @code{GzipFile.read(-1)} 1.11x
~ 1.18x faster. (Contributed by Ma Lin, reviewed by Gregory P. Smith, in bpo-41486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41486})

@item 
When using stringized annotations, annotations dicts for functions are no longer
created when the function is created.  Instead, they are stored as a tuple of
strings, and the function object lazily converts this into the annotations dict
on demand.  This optimization cuts the CPU time needed to define an annotated
function by half.
(Contributed by Yurii Karabas and Inada Naoki in bpo-42202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42202}.)

@item 
Substring search functions such as @code{str1 in str2} and @code{str2.find(str1)}
now sometimes use Crochemore & Perrin's "Two-Way" string searching
algorithm to avoid quadratic behavior on long strings.  (Contributed
by Dennis Sweeney in bpo-41972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41972})

@item 
Add micro-optimizations to @code{_PyType_Lookup()} to improve type attribute cache lookup
performance in the common case of cache hits. This makes the interpreter 1.04 times faster
on average. (Contributed by Dino Viehland in bpo-43452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43452}.)

@item 
The following built-in functions now support the faster 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} vectorcall calling convention:
@ref{19f,,map()}, @ref{a64,,filter()}, @ref{a65,,reversed()}, @ref{3c3,,bool()} and @ref{196,,float()}.
(Contributed by Donghee Na and Jeroen Demeyer in bpo-43575@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43575}, bpo-43287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43287}, bpo-41922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41922}, bpo-41873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41873} and bpo-41870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41870}.)

@item 
@ref{a66,,BZ2File} performance is improved by removing internal @code{RLock}.
This makes @code{BZ2File} thread unsafe in the face of multiple simultaneous
readers or writers, just like its equivalent classes in @ref{6b,,gzip} and
@ref{8e,,lzma} have always been.  (Contributed by Inada Naoki in bpo-43785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43785}.)
@end itemize

@node 非推奨<6>,削除<6>,最適化<5>,What's New In Python 3 10
@anchor{whatsnew/3 10 deprecated}@anchor{a67}@anchor{whatsnew/3 10 whatsnew310-deprecated}@anchor{a3c}
@subsection 非推奨



@itemize *

@item 
Currently Python accepts numeric literals immediately followed by keywords,
for example @code{0in x}, @code{1or x}, @code{0if 1else 2}.  It allows confusing
and ambiguous expressions like @code{[0x1for x in y]} (which can be
interpreted as @code{[0x1 for x in y]} or @code{[0x1f or x in y]}).  Starting in
this release, a deprecation warning is raised if the numeric literal is
immediately followed by one of keywords @ref{349,,and}, @ref{17c,,else},
@ref{34a,,for}, @ref{181,,if}, @ref{34b,,in}, @ref{34c,,is} and @ref{34d,,or}.
In future releases it will be changed to syntax warning, and finally to
syntax error.
(Contributed by Serhiy Storchaka in bpo-43833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43833}.)

@item 
Starting in this release, there will be a concerted effort to begin
cleaning up old import semantics that were kept for Python 2.7
compatibility. Specifically,
@code{find_loader()}/@code{find_module()}
(superseded by @ref{a68,,find_spec()}),
@ref{a69,,load_module()}
(superseded by @ref{a6a,,exec_module()}),
@code{module_repr()} (which the import system
takes care of for you), the @code{__package__} attribute
(superseded by @code{__spec__.parent}), the @code{__loader__} attribute
(superseded by @code{__spec__.loader}), and the @code{__cached__} attribute
(superseded by @code{__spec__.cached}) will slowly be removed (as well
as other classes and methods in @ref{7b,,importlib}).
@ref{71e,,ImportWarning} and/or @ref{1a3,,DeprecationWarning} will be raised
as appropriate to help identify code which needs updating during
this transition.

@item 
The entire @code{distutils} namespace is deprecated, to be removed in
Python 3.12. Refer to the @ref{934,,module changes}
section for more information.

@item 
Non-integer arguments to @ref{a6b,,random.randrange()} are deprecated.
The @ref{2ec,,ValueError} is deprecated in favor of a @ref{198,,TypeError}.
(Contributed by Serhiy Storchaka and Raymond Hettinger in bpo-37319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37319}.)

@item 
The various @code{load_module()} methods of @ref{7b,,importlib} have been
documented as deprecated since Python 3.6, but will now also trigger
a @ref{1a3,,DeprecationWarning}. Use
@ref{a6a,,exec_module()} instead.
(Contributed by Brett Cannon in bpo-26131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26131}.)

@item 
@code{zimport.zipimporter.load_module()} has been deprecated in
preference for @ref{339,,exec_module()}.
(Contributed by Brett Cannon in bpo-26131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26131}.)

@item 
The use of @ref{a69,,load_module()} by the import
system now triggers an @ref{71e,,ImportWarning} as
@ref{a6a,,exec_module()} is preferred.
(Contributed by Brett Cannon in bpo-26131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26131}.)

@item 
The use of @code{importlib.abc.MetaPathFinder.find_module()} and
@code{importlib.abc.PathEntryFinder.find_module()} by the import system now
trigger an @ref{71e,,ImportWarning} as
@ref{a68,,importlib.abc.MetaPathFinder.find_spec()} and
@ref{a6c,,importlib.abc.PathEntryFinder.find_spec()}
are preferred, respectively. You can use
@ref{a6d,,importlib.util.spec_from_loader()} to help in porting.
(Contributed by Brett Cannon in bpo-42134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42134}.)

@item 
The use of @code{importlib.abc.PathEntryFinder.find_loader()} by the import
system now triggers an @ref{71e,,ImportWarning} as
@ref{a6c,,importlib.abc.PathEntryFinder.find_spec()} is preferred. You can use
@ref{a6d,,importlib.util.spec_from_loader()} to help in porting.
(Contributed by Brett Cannon in bpo-43672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43672}.)

@item 
The various implementations of
@code{importlib.abc.MetaPathFinder.find_module()} (
@code{importlib.machinery.BuiltinImporter.find_module()},
@code{importlib.machinery.FrozenImporter.find_module()},
@code{importlib.machinery.WindowsRegistryFinder.find_module()},
@code{importlib.machinery.PathFinder.find_module()},
@code{importlib.abc.MetaPathFinder.find_module()} ),
@code{importlib.abc.PathEntryFinder.find_module()} (
@code{importlib.machinery.FileFinder.find_module()} ), and
@code{importlib.abc.PathEntryFinder.find_loader()} (
@code{importlib.machinery.FileFinder.find_loader()} )
now raise @ref{1a3,,DeprecationWarning} and are slated for removal in
Python 3.12 (previously they were documented as deprecated in Python 3.4).
(Contributed by Brett Cannon in bpo-42135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42135}.)

@item 
@code{importlib.abc.Finder} is deprecated (including its sole method,
@code{find_module()}). Both
@ref{a6e,,importlib.abc.MetaPathFinder} and @ref{a6f,,importlib.abc.PathEntryFinder}
no longer inherit from the class. Users should inherit from one of these two
classes as appropriate instead.
(Contributed by Brett Cannon in bpo-42135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42135}.)

@item 
The deprecations of @code{imp}, @code{importlib.find_loader()},
@code{importlib.util.set_package_wrapper()},
@code{importlib.util.set_loader_wrapper()},
@code{importlib.util.module_for_loader()},
@code{pkgutil.ImpImporter}, and
@code{pkgutil.ImpLoader} have all been updated to list Python 3.12 as the
slated version of removal (they began raising @ref{1a3,,DeprecationWarning} in
previous versions of Python).
(Contributed by Brett Cannon in bpo-43720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43720}.)

@item 
The import system now uses the @code{__spec__} attribute on modules before
falling back on @code{module_repr()} for a module's
@code{__repr__()} method. Removal of the use of @code{module_repr()} is scheduled
for Python 3.12.
(Contributed by Brett Cannon in bpo-42137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42137}.)

@item 
@code{importlib.abc.Loader.module_repr()},
@code{importlib.machinery.FrozenLoader.module_repr()}, and
@code{importlib.machinery.BuiltinLoader.module_repr()} are deprecated and
slated for removal in Python 3.12.
(Contributed by Brett Cannon in bpo-42136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42136}.)

@item 
@code{sqlite3.OptimizedUnicode} has been undocumented and obsolete since Python
3.3, when it was made an alias to @ref{169,,str}.  It is now deprecated,
scheduled for removal in Python 3.12.
(Contributed by Erlend E. Aasland in bpo-42264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42264}.)

@item 
The undocumented built-in function @code{sqlite3.enable_shared_cache} is now
deprecated, scheduled for removal in Python 3.12.  Its use is strongly
discouraged by the SQLite3 documentation.  See the SQLite3 docs@footnote{https://sqlite.org/c3ref/enable_shared_cache.html} for more details.
If a shared cache must be used, open the database in URI mode using the
@code{cache=shared} query parameter.
(Contributed by Erlend E. Aasland in bpo-24464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24464}.)

@item 
以下の @code{threading} メソッドは非推奨になりました：


@itemize *

@item 
@code{threading.currentThread} => @ref{35e,,threading.current_thread()}

@item 
@code{threading.activeCount} => @ref{35f,,threading.active_count()}

@item 
@code{threading.Condition.notifyAll} =>
@ref{359,,threading.Condition.notify_all()}

@item 
@code{threading.Event.isSet} => @ref{35a,,threading.Event.is_set()}

@item 
@code{threading.Thread.setName} => @ref{2a0,,threading.Thread.name}

@item 
@code{threading.thread.getName} => @ref{2a0,,threading.Thread.name}

@item 
@code{threading.Thread.isDaemon} => @ref{35c,,threading.Thread.daemon}

@item 
@code{threading.Thread.setDaemon} => @ref{35c,,threading.Thread.daemon}
@end itemize

(Contributed by Jelle Zijlstra in gh-87889@footnote{https://github.com/python/cpython/issues/87889}.)

@item 
@code{pathlib.Path.link_to()} is deprecated and slated for removal in
Python 3.12. Use @ref{a22,,pathlib.Path.hardlink_to()} instead.
(Contributed by Barney Gale in bpo-39950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39950}.)

@item 
@code{cgi.log()} is deprecated and slated for removal in Python 3.12.
(Contributed by Inada Naoki in bpo-41139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41139}.)

@item 
The following @ref{d5,,ssl} features have been deprecated since Python 3.6,
Python 3.7, or OpenSSL 1.1.0 and will be removed in 3.11:


@itemize *

@item 
@code{OP_NO_SSLv2}, @code{OP_NO_SSLv3}, @code{OP_NO_TLSv1},
@code{OP_NO_TLSv1_1}, @code{OP_NO_TLSv1_2}, and
@code{OP_NO_TLSv1_3} are replaced by
@ref{a70,,minimum_version} and
@ref{a71,,maximum_version}.

@item 
@code{PROTOCOL_SSLv2}, @code{PROTOCOL_SSLv3},
@code{PROTOCOL_SSLv23}, @code{PROTOCOL_TLSv1},
@code{PROTOCOL_TLSv1_1}, @code{PROTOCOL_TLSv1_2}, and
@code{PROTOCOL_TLS} are deprecated in favor of
@ref{a72,,PROTOCOL_TLS_CLIENT} and @ref{a73,,PROTOCOL_TLS_SERVER}

@item 
@code{wrap_socket()} is replaced by @ref{748,,ssl.SSLContext.wrap_socket()}

@item 
@code{match_hostname()}

@item 
@code{RAND_pseudo_bytes()}, @code{RAND_egd()}

@item 
NPN features like @ref{a74,,ssl.SSLSocket.selected_npn_protocol()} and
@ref{358,,ssl.SSLContext.set_npn_protocols()} are replaced by ALPN.
@end itemize

@item 
The threading debug (@code{PYTHONTHREADDEBUG} environment variable) is
deprecated in Python 3.10 and will be removed in Python 3.12. This feature
requires a @ref{509,,debug build of Python}.
(Contributed by Victor Stinner in bpo-44584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44584}.)

@item 
Importing from the @code{typing.io} and @code{typing.re} submodules will now emit
@ref{1a3,,DeprecationWarning}.  These submodules will be removed in a future version
of Python.  Anything belonging to these submodules should be imported directly
from @ref{10a,,typing} instead.
(Contributed by Sebastian Rittau in bpo-38291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38291}.)
@end itemize

@node 削除<6>,Porting to Python 3 10,非推奨<6>,What's New In Python 3 10
@anchor{whatsnew/3 10 removed}@anchor{a75}@anchor{whatsnew/3 10 whatsnew310-removed}@anchor{a76}
@subsection 削除



@itemize *

@item 
Removed special methods @code{__int__}, @code{__float__}, @code{__floordiv__},
@code{__mod__}, @code{__divmod__}, @code{__rfloordiv__}, @code{__rmod__} and
@code{__rdivmod__} of the @ref{197,,complex} class.  They always raised
a @ref{198,,TypeError}.
(Contributed by Serhiy Storchaka in bpo-41974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41974}.)

@item 
The @code{ParserBase.error()} method from the private and undocumented @code{_markupbase}
module has been removed.  @ref{a77,,html.parser.HTMLParser} is the only subclass of
@code{ParserBase} and its @code{error()} implementation was already removed in
Python 3.5.
(Contributed by Berker Peksag in bpo-31844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31844}.)

@item 
Removed the @code{unicodedata.ucnhash_CAPI} attribute which was an internal
PyCapsule object. The related private @code{_PyUnicode_Name_CAPI} structure was
moved to the internal C API.
(Contributed by Victor Stinner in bpo-42157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42157}.)

@item 
Removed the @code{parser} module, which was deprecated in 3.9 due to the
switch to the new PEG parser, as well as all the C source and header files
that were only being used by the old parser, including @code{node.h}, @code{parser.h},
@code{graminit.h} and @code{grammar.h}.

@item 
Removed the Public C API functions @code{PyParser_SimpleParseStringFlags},
@code{PyParser_SimpleParseStringFlagsFilename},
@code{PyParser_SimpleParseFileFlags} and @code{PyNode_Compile}
that were deprecated in 3.9 due to the switch to the new PEG parser.

@item 
Removed the @code{formatter} module, which was deprecated in Python 3.4.
It is somewhat obsolete, little used, and not tested. It was originally
scheduled to be removed in Python 3.6, but such removals were delayed until
after Python 2.7 EOL. Existing users should copy whatever classes they use
into their code.
(Contributed by Donghee Na and Terry J. Reedy in bpo-42299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42299}.)

@item 
Removed the @code{PyModule_GetWarningsModule()} function that was useless
now due to the @code{_warnings} module was converted to a builtin module in 2.6.
(Contributed by Hai Shi in bpo-42599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42599}.)

@item 
Remove deprecated aliases to @ref{a78,,コレクション抽象基底クラス} from
the @ref{1e,,collections} module.
(Contributed by Victor Stinner in bpo-37324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37324}.)

@item 
The @code{loop} parameter has been removed from most of @ref{b,,asyncio}'s
@ref{a79,,high-level API} following deprecation
in Python 3.8.  The motivation behind this change is multifold:


@enumerate 

@item 
This simplifies the high-level API.

@item 
The functions in the high-level API have been implicitly getting the
current thread's running event loop since Python 3.7.  There isn't a need to
pass the event loop to the API in most normal use cases.

@item 
Event loop passing is error-prone especially when dealing with loops
running in different threads.
@end enumerate

Note that the low-level API will still accept @code{loop}.
See @ref{a7a,,Python API の変更} for examples of how to replace existing code.

(Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley
in bpo-42392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42392}.)
@end itemize

@node Porting to Python 3 10,CPython バイトコードの変更<4>,削除<6>,What's New In Python 3 10
@anchor{whatsnew/3 10 porting-to-python-3-10}@anchor{a7b}
@subsection Porting to Python 3.10


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Changes in the Python syntax:: 
* Python API の変更: Python API の変更<4>. 
* C API の変更: C API の変更<6>. 

@end menu

@node Changes in the Python syntax,Python API の変更<4>,,Porting to Python 3 10
@anchor{whatsnew/3 10 changes-in-the-python-syntax}@anchor{a7c}
@subsubsection Changes in the Python syntax



@itemize *

@item 
Deprecation warning is now emitted when compiling previously valid syntax
if the numeric literal is immediately followed by a keyword (like in @code{0in x}).
In future releases it will be changed to syntax warning, and finally to a
syntax error.  To get rid of the warning and make the code compatible with
future releases just add a space between the numeric literal and the
following keyword.
(Contributed by Serhiy Storchaka in bpo-43833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43833}.)
@end itemize

@node Python API の変更<4>,C API の変更<6>,Changes in the Python syntax,Porting to Python 3 10
@anchor{whatsnew/3 10 changes-in-the-python-api}@anchor{a7d}@anchor{whatsnew/3 10 changes-python-api}@anchor{a7a}
@subsubsection Python API の変更



@itemize *

@item 
The `etype' parameters of the @ref{a4d,,format_exception()},
@ref{a4e,,format_exception_only()}, and
@ref{a4f,,print_exception()} functions in the @ref{104,,traceback} module
have been renamed to `exc'.
(Contributed by Zackery Spytz and Matthias Bussonnier in bpo-26389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26389}.)

@item 
@ref{d,,atexit}: At Python exit, if a callback registered with
@ref{a7e,,atexit.register()} fails, its exception is now logged. Previously, only
some exceptions were logged, and the last exception was always silently
ignored.
(Contributed by Victor Stinner in bpo-42639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42639}.)

@item 
@ref{9eb,,collections.abc.Callable} generic now flattens type parameters, similar
to what @ref{9c8,,typing.Callable} currently does.  This means that
@code{collections.abc.Callable[[int, str], str]} will have @code{__args__} of
@code{(int, str, str)}; previously this was @code{([int, str], str)}.  Code which
accesses the arguments via @ref{2ac,,typing.get_args()} or @code{__args__} need to account
for this change.  Furthermore, @ref{198,,TypeError} may be raised for invalid forms
of parameterizing @ref{9eb,,collections.abc.Callable} which may have passed
silently in Python 3.9.
(Contributed by Ken Jin in bpo-42195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42195}.)

@item 
@ref{a7f,,socket.htons()} and @ref{a80,,socket.ntohs()} now raise @ref{a81,,OverflowError}
instead of @ref{1a3,,DeprecationWarning} if the given parameter will not fit in
a 16-bit unsigned integer.
(Contributed by Erlend E. Aasland in bpo-42393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42393}.)

@item 
The @code{loop} parameter has been removed from most of @ref{b,,asyncio}'s
@ref{a79,,high-level API} following deprecation
in Python 3.8.

A coroutine that currently looks like this:

@example
async def foo(loop):
    await asyncio.sleep(1, loop=loop)
@end example

Should be replaced with this:

@example
async def foo():
    await asyncio.sleep(1)
@end example

If @code{foo()} was specifically designed `not' to run in the current thread's
running event loop (e.g. running in another thread's event loop), consider
using @ref{a82,,asyncio.run_coroutine_threadsafe()} instead.

(Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley
in bpo-42392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42392}.)

@item 
The @ref{a83,,types.FunctionType} constructor now inherits the current builtins
if the `globals' dictionary has no @code{"__builtins__"} key, rather than using
@code{@{"None": None@}} as builtins: same behavior as @ref{4a3,,eval()} and
@ref{4a2,,exec()} functions.  Defining a function with @code{def function(...): ...}
in Python is not affected, globals cannot be overridden with this syntax: it
also inherits the current builtins.
(Contributed by Victor Stinner in bpo-42990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42990}.)
@end itemize

@node C API の変更<6>,,Python API の変更<4>,Porting to Python 3 10
@anchor{whatsnew/3 10 changes-in-the-c-api}@anchor{a84}
@subsubsection C API の変更



@itemize *

@item 
The C API functions @code{PyParser_SimpleParseStringFlags},
@code{PyParser_SimpleParseStringFlagsFilename},
@code{PyParser_SimpleParseFileFlags}, @code{PyNode_Compile} and the type
used by these functions, @code{struct _node}, were removed due to the switch
to the new PEG parser.

Source should be now be compiled directly to a code object using, for
example, @ref{a85,,Py_CompileString()}. The resulting code object can then be
evaluated using, for example, @ref{a86,,PyEval_EvalCode()}.

Specifically:


@itemize *

@item 
A call to @code{PyParser_SimpleParseStringFlags} followed by
@code{PyNode_Compile} can be replaced by calling @ref{a85,,Py_CompileString()}.

@item 
There is no direct replacement for @code{PyParser_SimpleParseFileFlags}.
To compile code from a @code{FILE *} argument, you will need to read
the file in C and pass the resulting buffer to @ref{a85,,Py_CompileString()}.

@item 
To compile a file given a @code{char *} filename, explicitly open the file, read
it and compile the result. One way to do this is using the @ref{83,,io}
module with @ref{3dc,,PyImport_ImportModule()}, @ref{640,,PyObject_CallMethod()},
@ref{a87,,PyBytes_AsString()} and @ref{a85,,Py_CompileString()},
as sketched below. (Declarations and error handling are omitted.)

@example
io_module = Import_ImportModule("io");
fileobject = PyObject_CallMethod(io_module, "open", "ss", filename, "rb");
source_bytes_object = PyObject_CallMethod(fileobject, "read", "");
result = PyObject_CallMethod(fileobject, "close", "");
source_buf = PyBytes_AsString(source_bytes_object);
code = Py_CompileString(source_buf, filename, Py_file_input);
@end example

@item 
For @code{FrameObject} objects, the @ref{a88,,f_lasti} member now represents a wordcode
offset instead of a simple offset into the bytecode string. This means that this
number needs to be multiplied by 2 to be used with APIs that expect a byte offset
instead (like @ref{a89,,PyCode_Addr2Line()} for example). Notice as well that the
@code{f_lasti} member of @code{FrameObject} objects is not considered stable: please
use @ref{98e,,PyFrame_GetLineNumber()} instead.
@end itemize
@end itemize

@node CPython バイトコードの変更<4>,Build Changes<4>,Porting to Python 3 10,What's New In Python 3 10
@anchor{whatsnew/3 10 cpython-bytecode-changes}@anchor{a8a}
@subsection CPython バイトコードの変更



@itemize *

@item 
The @code{MAKE_FUNCTION} instruction now accepts either a dict or a tuple of
strings as the function's annotations.
(Contributed by Yurii Karabas and Inada Naoki in bpo-42202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42202}.)
@end itemize

@node Build Changes<4>,C API の変更<7>,CPython バイトコードの変更<4>,What's New In Python 3 10
@anchor{whatsnew/3 10 build-changes}@anchor{a8b}
@subsection Build Changes



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/}: Python now requires OpenSSL 1.1.1 or newer. OpenSSL 1.0.2 is no
longer supported.
(Contributed by Christian Heimes in bpo-43669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43669}.)

@item 
The C99 functions @code{snprintf()} and @code{vsnprintf()} are now required
to build Python.
(Contributed by Victor Stinner in bpo-36020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36020}.)

@item 
@ref{d4,,sqlite3} requires SQLite 3.7.15 or higher. (Contributed by Sergey Fedoseev
and Erlend E. Aasland in bpo-40744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40744} and bpo-40810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40810}.)

@item 
The @ref{d,,atexit} module must now always be built as a built-in module.
(Contributed by Victor Stinner in bpo-42639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42639}.)

@item 
Add @ref{a8c,,--disable-test-modules} option to the @code{configure} script:
don't build nor install test modules.
(Contributed by Xavier de Gaye, Thomas Petazzoni and Peixing Xin in bpo-27640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27640}.)

@item 
Add @ref{a8d,,--with-wheel-pkg-dir=PATH option}
to the @code{./configure} script. If
specified, the @ref{59,,ensurepip} module looks for @code{setuptools} and @code{pip}
wheel packages in this directory: if both are present, these wheel packages
are used instead of ensurepip bundled wheel packages.

Some Linux distribution packaging policies recommend against bundling
dependencies. For example, Fedora installs wheel packages in the
@code{/usr/share/python-wheels/} directory and don't install the
@code{ensurepip._bundled} package.

(Contributed by Victor Stinner in bpo-42856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42856}.)

@item 
Add a new @ref{a8e,,configure --without-static-libpython option} to not build the @code{libpythonMAJOR.MINOR.a}
static library and not install the @code{python.o} object file.

(Contributed by Victor Stinner in bpo-43103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43103}.)

@item 
The @code{configure} script now uses the @code{pkg-config} utility, if available,
to detect the location of Tcl/Tk headers and libraries.  As before, those
locations can be explicitly specified with the @code{--with-tcltk-includes}
and @code{--with-tcltk-libs} configuration options.
(Contributed by Manolis Stamatogiannakis in bpo-42603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42603}.)

@item 
Add @ref{a8f,,--with-openssl-rpath} option to @code{configure} script. The option
simplifies building Python with a custom OpenSSL installation, e.g.
@code{./configure --with-openssl=/path/to/openssl --with-openssl-rpath=auto}.
(Contributed by Christian Heimes in bpo-43466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43466}.)
@end itemize

@node C API の変更<7>,Notable security feature in 3 10 7,Build Changes<4>,What's New In Python 3 10
@anchor{whatsnew/3 10 c-api-changes}@anchor{a90}
@subsection C API の変更


@menu
* PEP 652; Maintaining the Stable ABI: PEP 652 Maintaining the Stable ABI. 
* 新しい機能: 新しい機能<9>. 
* Porting to Python 3.10: Porting to Python 3 10<2>. 
* 非推奨: 非推奨<7>. 
* 削除: 削除<7>. 

@end menu

@node PEP 652 Maintaining the Stable ABI,新しい機能<9>,,C API の変更<7>
@anchor{whatsnew/3 10 pep-652-maintaining-the-stable-abi}@anchor{a91}
@subsubsection PEP 652: Maintaining the Stable ABI


The Stable ABI (Application Binary Interface) for extension modules or
embedding Python is now explicitly defined.
@ref{775,,C API の安定性} describes C API and ABI stability guarantees along with best
practices for using the Stable ABI.

(Contributed by Petr Viktorin in 
@geindex Python Enhancement Proposals; PEP 652
PEP 652@footnote{https://peps.python.org/pep-0652/} and bpo-43795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43795}.)

@node 新しい機能<9>,Porting to Python 3 10<2>,PEP 652 Maintaining the Stable ABI,C API の変更<7>
@anchor{whatsnew/3 10 id1}@anchor{a92}
@subsubsection 新しい機能



@itemize *

@item 
The result of @ref{a93,,PyNumber_Index()} now always has exact type @ref{19b,,int}.
Previously, the result could have been an instance of a subclass of @code{int}.
(Contributed by Serhiy Storchaka in bpo-40792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40792}.)

@item 
Add a new @ref{a94,,orig_argv} member to the @ref{3f7,,PyConfig}
structure: the list of the original command line arguments passed to the
Python executable.
(Contributed by Victor Stinner in bpo-23427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23427}.)

@item 
The @ref{a95,,PyDateTime_DATE_GET_TZINFO()} and
@ref{a96,,PyDateTime_TIME_GET_TZINFO()} macros have been added for accessing
the @code{tzinfo} attributes of @ref{4e2,,datetime.datetime} and
@ref{1fb,,datetime.time} objects.
(Contributed by Zackery Spytz in bpo-30155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30155}.)

@item 
Add a @ref{a97,,PyCodec_Unregister()} function to unregister a codec
search function.
(Contributed by Hai Shi in bpo-41842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41842}.)

@item 
The @ref{a98,,PyIter_Send()} function was added to allow
sending value into iterator without raising @code{StopIteration} exception.
(Contributed by Vladimir Matveev in bpo-41756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41756}.)

@item 
Add @ref{a99,,PyUnicode_AsUTF8AndSize()} to the limited C API.
(Contributed by Alex Gaynor in bpo-41784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41784}.)

@item 
Add @ref{60a,,PyModule_AddObjectRef()} function: similar to
@ref{60b,,PyModule_AddObject()} but don't steal a reference to the value on
success.
(Contributed by Victor Stinner in bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}.)

@item 
Add @ref{a9a,,Py_NewRef()} and @ref{a9b,,Py_XNewRef()} functions to increment the
reference count of an object and return the object.
(Contributed by Victor Stinner in bpo-42262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42262}.)

@item 
The @ref{79e,,PyType_FromSpecWithBases()} and @ref{773,,PyType_FromModuleAndSpec()}
functions now accept a single class as the `bases' argument.
(Contributed by Serhiy Storchaka in bpo-42423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42423}.)

@item 
The @ref{773,,PyType_FromModuleAndSpec()} function now accepts NULL @code{tp_doc}
slot.
(Contributed by Hai Shi in bpo-41832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41832}.)

@item 
The @ref{a9c,,PyType_GetSlot()} function can accept
@ref{983,,static types}.
(Contributed by Hai Shi and Petr Viktorin in bpo-41073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41073}.)

@item 
Add a new @ref{a9d,,PySet_CheckExact()} function to the C-API to check if an
object is an instance of @ref{184,,set} but not an instance of a subtype.
(Contributed by Pablo Galindo in bpo-43277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43277}.)

@item 
Add @ref{a9e,,PyErr_SetInterruptEx()} which allows passing a signal number
to simulate.
(Contributed by Antoine Pitrou in bpo-43356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43356}.)

@item 
The limited C API is now supported if @ref{509,,Python is built in debug mode} (if the @code{Py_DEBUG} macro is defined). In the limited C API,
the @ref{78f,,Py_INCREF()} and @ref{790,,Py_DECREF()} functions are now implemented
as opaque function
calls, rather than accessing directly the @ref{a9f,,PyObject.ob_refcnt}
member, if Python is built in debug mode and the @code{Py_LIMITED_API} macro
targets Python 3.10 or newer. It became possible to support the limited C API
in debug mode because the @ref{5df,,PyObject} structure is the same in release
and debug mode since Python 3.8 (see bpo-36465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36465}).

The limited C API is still not supported in the @ref{636,,--with-trace-refs}
special build (@code{Py_TRACE_REFS} macro).
(Contributed by Victor Stinner in bpo-43688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43688}.)

@item 
Add the @ref{aa0,,Py_Is(x@comma{} y)} function to test if the `x' object is
the `y' object, the same as @code{x is y} in Python. Add also the
@ref{aa1,,Py_IsNone()}, @ref{aa2,,Py_IsTrue()}, @ref{aa3,,Py_IsFalse()} functions to
test if an object is, respectively, the @code{None} singleton, the @code{True}
singleton or the @code{False} singleton.
(Contributed by Victor Stinner in bpo-43753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43753}.)

@item 
Add new functions to control the garbage collector from C code:
@ref{aa4,,PyGC_Enable()},
@ref{aa5,,PyGC_Disable()},
@ref{aa6,,PyGC_IsEnabled()}.
These functions allow to activate, deactivate and query the state of the garbage collector from C code without
having to import the @ref{64,,gc} module.

@item 
Add a new @ref{7a2,,Py_TPFLAGS_DISALLOW_INSTANTIATION} type flag to disallow
creating type instances.
(Contributed by Victor Stinner in bpo-43916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43916}.)

@item 
Add a new @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} type flag for creating immutable
type objects: type attributes cannot be set nor deleted.
(Contributed by Victor Stinner and Erlend E. Aasland in bpo-43908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43908}.)
@end itemize

@node Porting to Python 3 10<2>,非推奨<7>,新しい機能<9>,C API の変更<7>
@anchor{whatsnew/3 10 id2}@anchor{aa7}
@subsubsection Porting to Python 3.10



@itemize *

@item 
The @code{PY_SSIZE_T_CLEAN} macro must now be defined to use
@ref{3c1,,PyArg_ParseTuple()} and @ref{3c2,,Py_BuildValue()} formats which use
@code{#}: @code{es#}, @code{et#}, @code{s#}, @code{u#}, @code{y#}, @code{z#}, @code{U#} and @code{Z#}.
See @ref{3d5,,引数の解釈と値の構築} and 
@geindex Python Enhancement Proposals; PEP 353
PEP 353@footnote{https://peps.python.org/pep-0353/}.
(Contributed by Victor Stinner in bpo-40943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40943}.)

@item 
Since @ref{2cf,,Py_REFCNT()} is changed to the inline static function,
@code{Py_REFCNT(obj) = new_refcnt} must be replaced with @code{Py_SET_REFCNT(obj, new_refcnt)}:
see @ref{aa8,,Py_SET_REFCNT()} (available since Python 3.9). For backward
compatibility, this macro can be used:

@example
#if PY_VERSION_HEX < 0x030900A4
#  define Py_SET_REFCNT(obj, refcnt) ((Py_REFCNT(obj) = (refcnt)), (void)0)
#endif
@end example

(Contributed by Victor Stinner in bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}.)

@item 
Calling @ref{628,,PyDict_GetItem()} without @ref{164,,GIL} held had been allowed
for historical reason. It is no longer allowed.
(Contributed by Victor Stinner in bpo-40839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40839}.)

@item 
@code{PyUnicode_FromUnicode(NULL, size)} and @code{PyUnicode_FromStringAndSize(NULL, size)}
raise @code{DeprecationWarning} now.  Use @ref{aa9,,PyUnicode_New()} to allocate
Unicode object without initial data.
(Contributed by Inada Naoki in bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}.)

@item 
The private @code{_PyUnicode_Name_CAPI} structure of the PyCapsule API
@code{unicodedata.ucnhash_CAPI} has been moved to the internal C API.
(Contributed by Victor Stinner in bpo-42157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42157}.)

@item 
@ref{3e3,,Py_GetPath()}, @ref{3e5,,Py_GetPrefix()}, @ref{3e9,,Py_GetExecPrefix()},
@ref{3ec,,Py_GetProgramFullPath()}, @ref{3ef,,Py_GetPythonHome()} and
@ref{3ee,,Py_GetProgramName()} functions now return @code{NULL} if called before
@ref{460,,Py_Initialize()} (before Python is initialized). Use the new
@ref{646,,Python 初期化設定} API to get the @ref{aaa,,Python Path Configuration}.
(Contributed by Victor Stinner in bpo-42260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42260}.)

@item 
@ref{62f,,PyList_SET_ITEM()}, @ref{62e,,PyTuple_SET_ITEM()} and
@ref{aab,,PyCell_SET()} macros can no longer be used as l-value or r-value.
For example, @code{x = PyList_SET_ITEM(a, b, c)} and
@code{PyList_SET_ITEM(a, b, c) = x} now fail with a compiler error. It prevents
bugs like @code{if (PyList_SET_ITEM (a, b, c) < 0) ...} test.
(Contributed by Zackery Spytz and Victor Stinner in bpo-30459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30459}.)

@item 
The non-limited API files @code{odictobject.h}, @code{parser_interface.h},
@code{picklebufobject.h}, @code{pyarena.h}, @code{pyctype.h}, @code{pydebug.h},
@code{pyfpe.h}, and @code{pytime.h} have been moved to the @code{Include/cpython}
directory. These files must not be included directly, as they are already
included in @code{Python.h}; see @ref{987,,インクルードファイル}. If they have
been included directly, consider including @code{Python.h} instead.
(Contributed by Nicholas Sim in bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}.)

@item 
Use the @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} type flag to create immutable type
objects. Do not rely on @ref{aac,,Py_TPFLAGS_HEAPTYPE} to decide if a type
object is mutable or not; check if @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} is set
instead.
(Contributed by Victor Stinner and Erlend E. Aasland in bpo-43908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43908}.)

@item 
The undocumented function @code{Py_FrozenMain} has been removed from the
limited API. The function is mainly useful for custom builds of Python.
(Contributed by Petr Viktorin in bpo-26241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26241}.)
@end itemize

@node 非推奨<7>,削除<7>,Porting to Python 3 10<2>,C API の変更<7>
@anchor{whatsnew/3 10 id3}@anchor{aad}
@subsubsection 非推奨



@itemize *

@item 
The @code{PyUnicode_InternImmortal()} function is now deprecated
and will be removed in Python 3.12: use @ref{aae,,PyUnicode_InternInPlace()}
instead.
(Contributed by Victor Stinner in bpo-41692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41692}.)
@end itemize

@node 削除<7>,,非推奨<7>,C API の変更<7>
@anchor{whatsnew/3 10 id4}@anchor{aaf}
@subsubsection 削除



@itemize *

@item 
Removed @code{Py_UNICODE_str*} functions manipulating @code{Py_UNICODE*} strings.
(Contributed by Inada Naoki in bpo-41123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41123}.)


@itemize *

@item 
@code{Py_UNICODE_strlen}: use @ref{ab0,,PyUnicode_GetLength()} or
@ref{ab1,,PyUnicode_GET_LENGTH}

@item 
@code{Py_UNICODE_strcat}: use @ref{ab2,,PyUnicode_CopyCharacters()} or
@ref{62b,,PyUnicode_FromFormat()}

@item 
@code{Py_UNICODE_strcpy}, @code{Py_UNICODE_strncpy}: use
@ref{ab2,,PyUnicode_CopyCharacters()} or @ref{ab3,,PyUnicode_Substring()}

@item 
@code{Py_UNICODE_strcmp}: use @ref{ab4,,PyUnicode_Compare()}

@item 
@code{Py_UNICODE_strncmp}: use @ref{ab5,,PyUnicode_Tailmatch()}

@item 
@code{Py_UNICODE_strchr}, @code{Py_UNICODE_strrchr}: use
@ref{ab6,,PyUnicode_FindChar()}
@end itemize

@item 
Removed @code{PyUnicode_GetMax()}. Please migrate to new (
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/}) APIs.
(Contributed by Inada Naoki in bpo-41103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41103}.)

@item 
Removed @code{PyLong_FromUnicode()}. Please migrate to @ref{ab7,,PyLong_FromUnicodeObject()}.
(Contributed by Inada Naoki in bpo-41103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41103}.)

@item 
Removed @code{PyUnicode_AsUnicodeCopy()}. Please use @ref{ab8,,PyUnicode_AsUCS4Copy()} or
@ref{ab9,,PyUnicode_AsWideCharString()}
(Contributed by Inada Naoki in bpo-41103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41103}.)

@item 
Removed @code{_Py_CheckRecursionLimit} variable: it has been replaced by
@code{ceval.recursion_limit} of the @ref{aba,,PyInterpreterState} structure.
(Contributed by Victor Stinner in bpo-41834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41834}.)

@item 
Removed undocumented macros @code{Py_ALLOW_RECURSION} and
@code{Py_END_ALLOW_RECURSION} and the @code{recursion_critical} field of the
@ref{aba,,PyInterpreterState} structure.
(Contributed by Serhiy Storchaka in bpo-41936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41936}.)

@item 
Removed the undocumented @code{PyOS_InitInterrupts()} function. Initializing
Python already implicitly installs signal handlers: see
@ref{abb,,PyConfig.install_signal_handlers}.
(Contributed by Victor Stinner in bpo-41713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41713}.)

@item 
Remove the @code{PyAST_Validate()} function. It is no longer possible to build a
AST object (@code{mod_ty} type) with the public C API. The function was already
excluded from the limited C API (
@geindex Python Enhancement Proposals; PEP 384
PEP 384@footnote{https://peps.python.org/pep-0384/}).
(Contributed by Victor Stinner in bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}.)

@item 
Remove the @code{symtable.h} header file and the undocumented functions:


@itemize *

@item 
@code{PyST_GetScope()}

@item 
@code{PySymtable_Build()}

@item 
@code{PySymtable_BuildObject()}

@item 
@code{PySymtable_Free()}

@item 
@code{Py_SymtableString()}

@item 
@code{Py_SymtableStringObject()}
@end itemize

The @code{Py_SymtableString()} function was part the stable ABI by mistake but
it could not be used, because the @code{symtable.h} header file was excluded
from the limited C API.

Use Python @ref{de,,symtable} module instead.
(Contributed by Victor Stinner in bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}.)

@item 
Remove @ref{7a5,,PyOS_ReadlineFunctionPointer()} from the limited C API headers
and from @code{python3.dll}, the library that provides the stable ABI on
Windows. Since the function takes a @code{FILE*} argument, its ABI stability
cannot be guaranteed.
(Contributed by Petr Viktorin in bpo-43868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43868}.)

@item 
Remove @code{ast.h}, @code{asdl.h}, and @code{Python-ast.h} header files.
These functions were undocumented and excluded from the limited C API.
Most names defined by these header files were not prefixed by @code{Py} and so
could create names conflicts. For example, @code{Python-ast.h} defined a
@code{Yield} macro which was conflict with the @code{Yield} name used by the
Windows @code{<winbase.h>} header. Use the Python @ref{9,,ast} module instead.
(Contributed by Victor Stinner in bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}.)

@item 
Remove the compiler and parser functions using @code{struct _mod} type, because
the public AST C API was removed:


@itemize *

@item 
@code{PyAST_Compile()}

@item 
@code{PyAST_CompileEx()}

@item 
@code{PyAST_CompileObject()}

@item 
@code{PyFuture_FromAST()}

@item 
@code{PyFuture_FromASTObject()}

@item 
@code{PyParser_ASTFromFile()}

@item 
@code{PyParser_ASTFromFileObject()}

@item 
@code{PyParser_ASTFromFilename()}

@item 
@code{PyParser_ASTFromString()}

@item 
@code{PyParser_ASTFromStringObject()}
@end itemize

These functions were undocumented and excluded from the limited C API.
(Contributed by Victor Stinner in bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}.)

@item 
Remove the @code{pyarena.h} header file with functions:


@itemize *

@item 
@code{PyArena_New()}

@item 
@code{PyArena_Free()}

@item 
@code{PyArena_Malloc()}

@item 
@code{PyArena_AddPyObject()}
@end itemize

These functions were undocumented, excluded from the limited C API, and were
only used internally by the compiler.
(Contributed by Victor Stinner in bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}.)

@item 
The @code{PyThreadState.use_tracing} member has been removed to optimize Python.
(Contributed by Mark Shannon in bpo-43760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43760}.)
@end itemize

@node Notable security feature in 3 10 7,Notable security feature in 3 10 8,C API の変更<7>,What's New In Python 3 10
@anchor{whatsnew/3 10 notable-security-feature-in-3-10-7}
@subsection Notable security feature in 3.10.7


Converting between @ref{19b,,int} and @ref{169,,str} in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
now raises a @ref{2ec,,ValueError} if the number of digits in string form is
above a limit to avoid potential denial of service attacks due to the
algorithmic complexity. This is a mitigation for 
@geindex Common Vulnerabilities and Exposures; CVE 2020-10735
CVE 2020-10735@footnote{https://www.cve.org/CVERecord?id=CVE-2020-10735}.
This limit can be configured or disabled by environment variable, command
line flag, or @ref{df,,sys} APIs. See the @ref{80b,,integer string conversion length limitation} documentation.  The default limit
is 4300 digits in string form.

@node Notable security feature in 3 10 8,Notable changes in 3 10 12,Notable security feature in 3 10 7,What's New In Python 3 10
@anchor{whatsnew/3 10 notable-security-feature-in-3-10-8}@anchor{abd}
@subsection Notable security feature in 3.10.8


The deprecated @code{mailcap} module now refuses to inject unsafe text
(filenames, MIME types, parameters) into shell commands. Instead of using such
text, it will warn and act as if a match was not found (or for test commands,
as if the test failed).
(Contributed by Petr Viktorin in gh-98966@footnote{https://github.com/python/cpython/issues/98966}.)

@node Notable changes in 3 10 12,,Notable security feature in 3 10 8,What's New In Python 3 10
@anchor{whatsnew/3 10 notable-changes-in-3-10-12}@anchor{abe}
@subsection Notable changes in 3.10.12


@menu
* tarfile: tarfile<3>. 

@end menu

@node tarfile<3>,,,Notable changes in 3 10 12
@anchor{whatsnew/3 10 tarfile}@anchor{abf}
@subsubsection tarfile



@itemize *

@item 
The extraction methods in @ref{e4,,tarfile}, and @ref{696,,shutil.unpack_archive()},
have a new a `filter' argument that allows limiting tar features than may be
surprising or dangerous, such as creating files outside the destination
directory.
See @ref{697,,Extraction filters} for details.
In Python 3.12, use without the `filter' argument will show a
@ref{1a3,,DeprecationWarning}.
In Python 3.14, the default will switch to @code{'data'}.
(Contributed by Petr Viktorin in 
@geindex Python Enhancement Proposals; PEP 706
PEP 706@footnote{https://peps.python.org/pep-0706/}.)
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 9,What's New In Python 3 8,What's New In Python 3 10,What's New in Python
@anchor{whatsnew/3 9 doc}@anchor{ac0}@anchor{whatsnew/3 9 translation-repo}@anchor{ac1}@anchor{whatsnew/3 9 what-s-new-in-python-3-9}@anchor{ac2}
@section What's New In Python 3.9


@*編集者: 
Łukasz Langa


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Your text might get
@c rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes will be too small
@c or esoteric to include.  If such a change is added to the text,
@c it might get removed during final editing.
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

This article explains the new features in Python 3.9, compared to 3.8.
Python 3.9 was released on October 5, 2020.
For full details, see the @ref{142,,changelog}.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 596
PEP 596@footnote{https://peps.python.org/pep-0596/} - Python 3.9 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト<6>. リリースハイライト
* コード中の非推奨警告(DeprecationWarning)をチェックして下さい: コード中の非推奨警告 DeprecationWarning をチェックして下さい. 
* 新しい機能: 新しい機能<10>. 
* その他の言語変更: その他の言語変更<5>. 
* 新たなモジュール: 新たなモジュール<5>. 
* 改良されたモジュール: 改良されたモジュール<5>. 
* 最適化: 最適化<6>. 
* 非推奨: 非推奨<8>. 
* 削除: 削除<8>. 
* Python 3.9への移植: Python 3 9への移植. 
* Build Changes: Build Changes<5>. 
* C API の変更: C API の変更<9>. 
* Python 3.9.1 での重要な変更点: Python 3 9 1 での重要な変更点. 
* Python 3.9.2 での重要な変更点: Python 3 9 2 での重要な変更点. 
* Python 3.9.3 での重要な変更点: Python 3 9 3 での重要な変更点. 
* Python 3.9.5での重要な変更点: Python 3 9 5での重要な変更点. 
* Notable security feature in 3.9.14: Notable security feature in 3 9 14. 
* Notable changes in 3.9.17: Notable changes in 3 9 17. 

@end menu

@node 概要 -- リリースハイライト<6>,コード中の非推奨警告 DeprecationWarning をチェックして下さい,,What's New In Python 3 9
@anchor{whatsnew/3 9 summary-release-highlights}@anchor{ac3}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.9.
@c Brevity is key.

新たな文法機能:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/}、 @code{dict} に和集合の演算子が追加されました。

@item 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/}、標準コレクション型の型ヒントにおける総称型 (generics) の使用。

@item 
@geindex Python Enhancement Proposals; PEP 614
PEP 614@footnote{https://peps.python.org/pep-0614/}、デコレータの適用における文法的制約の緩和。
@end itemize

新たな組み込み機能:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 616
PEP 616@footnote{https://peps.python.org/pep-0616/}、prefixとsuffixを削除する文字列メソッド。
@end itemize

標準ライブラリの新機能:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 593
PEP 593@footnote{https://peps.python.org/pep-0593/}、より柔軟な変数・関数アノテーション (訳注: @code{Annotated} の導入)。

@item 
@ref{6a4,,os.pidfd_open()} が追加され、レースやシグナルを使わずにプロセス管理ができるようになりました。
@end itemize

インタプリタの改善:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 573
PEP 573@footnote{https://peps.python.org/pep-0573/}, fast access to module state from methods of C extension
types;

@item 
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/}、CPython における PEG (Parser Expression Grammar) ベースの新しい構文解析器の使用。

@item 
いくつかのPythonの組み込み型（range, tuple, set, frozenset, list, dict） を 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} vectorcall を用いて高速化しました。

@item 
garbage collection does not block on resurrected objects;

@item 
a number of Python modules (@code{_abc}, @code{audioop}, @code{_bz2},
@code{_codecs}, @code{_contextvars}, @code{_crypt}, @code{_functools},
@code{_json}, @code{_locale}, @ref{92,,math}, @ref{a3,,operator}, @ref{c1,,resource},
@ref{f4,,time}, @code{_weakref}) now use multiphase initialization as defined
by PEP 489;

@item 
a number of standard library modules (@code{audioop}, @ref{9,,ast}, @ref{6a,,grp},
@code{_hashlib}, @ref{b7,,pwd}, @code{_posixsubprocess}, @ref{bd,,random},
@ref{c6,,select}, @ref{db,,struct}, @ref{e7,,termios}, @ref{139,,zlib}) are now using
the stable ABI defined by PEP 384.
@end itemize

新たなライブラリモジュール:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 615
PEP 615@footnote{https://peps.python.org/pep-0615/}、IANAのTime Zone Databaseが標準ライブラリの @ref{13a,,zoneinfo} モジュールで提供されるようになりました。

@item 
an implementation of a topological sort of a graph is now provided in
the new @ref{69,,graphlib} module.
@end itemize

リリースプロセスの変更:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 602
PEP 602@footnote{https://peps.python.org/pep-0602/}、CPythonは年次のリリースサイクルを採用します。
@end itemize

@node コード中の非推奨警告 DeprecationWarning をチェックして下さい,新しい機能<10>,概要 -- リリースハイライト<6>,What's New In Python 3 9
@anchor{whatsnew/3 9 you-should-check-for-deprecationwarning-in-your-code}@anchor{ac4}
@subsection コード中の非推奨警告(DeprecationWarning)をチェックして下さい


Python 2.7がまだサポートされていた期間、Python 3の多くの機能はPython 2.7との後方互換性を保っていました。Python 2サポートの終了とともに、この後方互換性レイヤは除去されたか、間もなく除去されます。ここ数年で、それらの多くは警告 @ref{1a3,,DeprecationWarning} を出すようになりました。例えば、2012年にリリースされたPython 3.3以降、@code{collections.abc.Mapping} の代りに @code{collections.Mapping} を使うと、警告 @ref{1a3,,DeprecationWarning} が出ます。

警告 @ref{1a3,,DeprecationWarning} および @ref{ac5,,PendingDeprecationWarning} を確認するために、 @ref{ac6,,-W} @code{default} コマンドラインオプションを付けて、あなたのアプリケーションをテストして下さい。あるいは、@ref{ac6,,-W} @code{error} で警告をエラーとして扱うこともできます。サードパーティによるコードの警告を無視するには、@ref{1b1,,Warnings Filter} を使うことができます。

Python 3.9は、Python 2後方互換性レイヤを提供する最後のバージョンです。このレイヤは、Pythonプロジェクトの保守管理者に、Python 2サポートを止めてPython 3.9サポートを追加する時間的な余裕を与えるためのものです。

Aliases to @ref{a78,,Abstract Base Classes} in
the @ref{1e,,collections} module, like @code{collections.Mapping} alias to
@ref{ac7,,collections.abc.Mapping}, are kept for one last release for backward
compatibility. They will be removed from Python 3.10.

より一般的には、あなたのコードが次のバージョンのPythonと互換性を保てるよう、@ref{508,,Python Development Mode} でテストするようにしてください。

注釈: Pythonのこのバージョンで、既存の多くの非推奨機能が削除されました。詳しくは @ref{ac8,,削除} を見て下さい。

@node 新しい機能<10>,その他の言語変更<5>,コード中の非推奨警告 DeprecationWarning をチェックして下さい,What's New In Python 3 9
@anchor{whatsnew/3 9 new-features}@anchor{ac9}
@subsection 新しい機能


@menu
* 辞書のマージと更新演算子:: 
* prefixとsuffixを削除する新しい文字列メソッド:: 
* 標準コレクション型の型ヒントにおける総称型 (generics) の使用: 標準コレクション型の型ヒントにおける総称型 generics の使用. 
* 新しいパーサー:: 

@end menu

@node 辞書のマージと更新演算子,prefixとsuffixを削除する新しい文字列メソッド,,新しい機能<10>
@anchor{whatsnew/3 9 dictionary-merge-update-operators}@anchor{aca}
@subsubsection 辞書のマージと更新演算子


組み込みの @ref{183,,dict} クラスにマージ(@code{|})と更新(@code{|=})演算子が追加されました。この演算子は、辞書をマージする既存の方法 @code{dict.update} と @code{@{**d1, **d2@}} を補完します。

以下はプログラム例です:

@example
>>> x = @{"key1": "value1 from x", "key2": "value2 from x"@}
>>> y = @{"key2": "value2 from y", "key3": "value3 from y"@}
>>> x | y
@{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'@}
>>> y | x
@{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'@}
@end example

詳細は 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} を参照してください。(Brandt Bucher の貢献による bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144})

@node prefixとsuffixを削除する新しい文字列メソッド,標準コレクション型の型ヒントにおける総称型 generics の使用,辞書のマージと更新演算子,新しい機能<10>
@anchor{whatsnew/3 9 new-string-methods-to-remove-prefixes-and-suffixes}@anchor{acb}
@subsubsection prefixとsuffixを削除する新しい文字列メソッド


文字列から不要な prefix や suffix を簡単に削除する @ref{acc,,str.removeprefix(prefix)} と @ref{acd,,str.removesuffix(suffix)} が追加されました。 @code{bytes}, @code{bytearray}, @code{collections.UserString} にも同様のメソッドが追加されました。詳細は 
@geindex Python Enhancement Proposals; PEP 616
PEP 616@footnote{https://peps.python.org/pep-0616/} を参照してください。(Dennis Sweeney の貢献による bpo-39939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39939})

@node 標準コレクション型の型ヒントにおける総称型 generics の使用,新しいパーサー,prefixとsuffixを削除する新しい文字列メソッド,新しい機能<10>
@anchor{whatsnew/3 9 type-hinting-generics-in-standard-collections}@anchor{ace}
@subsubsection 標準コレクション型の型ヒントにおける総称型 (generics) の使用


型アノテーションで、@code{typing} モジュールからインポートしていた大文字の型（@code{List} や @code{Dict}）の代わりに、総称型（generics）で @code{list} や @code{dict} といった標準コレクション型が使用できるようになりました。いくつかの他の標準ライブラリの型（@code{queue.Queue} など）も総称型として使用できます。

例:

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

詳細は 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} を参照してください。(Guido van Rossum、Ethan Smith、Batuhan Taşkaya の貢献による bpo-39481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39481})

@node 新しいパーサー,,標準コレクション型の型ヒントにおける総称型 generics の使用,新しい機能<10>
@anchor{whatsnew/3 9 new-parser}@anchor{acf}
@subsubsection 新しいパーサー


Python 3.9は、 LL(1)@footnote{https://en.wikipedia.org/wiki/LL_parser} に代えて PEG@footnote{https://en.wikipedia.org/wiki/Parsing_expression_grammar} に基づく新しいパーサーを採用しています。新しいパーサーのパフォーマンスは古いパーサーとほぼ同程度ですが、新しい言語の機能を設計する際に、PEGの形式主義はより柔軟です。我々は、この柔軟性をPython 3.10以降に使い始める予定です。

@ref{9,,ast} モジュールは、新しいパーサーを使って古いパーサーと同じASTを生成します。

In Python 3.10, the old parser will be deleted and so will all
functionality that depends on it (primarily the @code{parser} module,
which has long been deprecated).  In Python 3.9 `only', you can switch
back to the LL(1) parser using a command line switch (@code{-X
oldparser}) or an environment variable (@code{PYTHONOLDPARSER=1}).

詳細は 
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/} を参照してください。(Guido van Rossum,、Pablo Galindo、およびLysandros Nikolaouの貢献による bpo-40334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40334})

@node その他の言語変更<5>,新たなモジュール<5>,新しい機能<10>,What's New In Python 3 9
@anchor{whatsnew/3 9 other-language-changes}@anchor{ad0}
@subsection その他の言語変更



@itemize *

@item 
@ref{ad1,,__import__()} now raises @ref{65b,,ImportError} instead of
@ref{2ec,,ValueError}, which used to occur when a relative import went past
its top-level package.
(Contributed by Ngalim Siregar in bpo-37444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37444}.)

@item 
Python now gets the absolute path of the script filename specified on
the command line (ex: @code{python3 script.py}): the @code{__file__} attribute of
the @ref{1,,__main__} module became an absolute path, rather than a relative
path. These paths now remain valid after the current directory is changed
by @ref{821,,os.chdir()}. As a side effect, the traceback also displays the
absolute path for @ref{1,,__main__} module frames in this case.
(Contributed by Victor Stinner in bpo-20443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20443}.)

@item 
In the @ref{508,,Python Development Mode} and in @ref{509,,debug build}, the
`encoding' and `errors' arguments are now checked for string encoding and
decoding operations. Examples: @ref{316,,open()}, @ref{ad2,,str.encode()} and
@ref{ad3,,bytes.decode()}.

By default, for best performance, the `errors' argument is only checked at
the first encoding/decoding error and the `encoding' argument is sometimes
ignored for empty strings.
(Contributed by Victor Stinner in bpo-37388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37388}.)

@item 
@code{"".replace("", s, n)} now returns @code{s} instead of an empty string for
all non-zero @code{n}.  It is now consistent with @code{"".replace("", s)}.
There are similar changes for @ref{192,,bytes} and @ref{344,,bytearray} objects.
(Contributed by Serhiy Storchaka in bpo-28029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28029}.)

@item 
Any valid expression can now be used as a @ref{93a,,decorator}.  Previously, the
grammar was much more restrictive.  See 
@geindex Python Enhancement Proposals; PEP 614
PEP 614@footnote{https://peps.python.org/pep-0614/} for details.
(Contributed by Brandt Bucher in bpo-39702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39702}.)

@item 
Improved help for the @ref{10a,,typing} module. Docstrings are now shown for
all special forms and special generic aliases (like @code{Union} and @code{List}).
Using @ref{ad4,,help()} with generic alias like @code{List[int]} will show the help
for the correspondent concrete type (@code{list} in this case).
(Contributed by Serhiy Storchaka in bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}.)

@item 
Parallel running of @ref{ad5,,aclose()} / @ref{ad6,,asend()} /
@ref{71d,,athrow()} is now prohibited, and @code{ag_running} now reflects
the actual running status of the async generator.
(Contributed by Yury Selivanov in bpo-30773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30773}.)

@item 
Unexpected errors in calling the @code{__iter__} method are no longer masked by
@code{TypeError} in the @ref{34b,,in} operator and functions
@ref{ad7,,contains()}, @ref{ad8,,indexOf()} and
@ref{ad9,,countOf()} of the @ref{a3,,operator} module.
(Contributed by Serhiy Storchaka in bpo-40824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40824}.)

@item 
Unparenthesized lambda expressions can no longer be the expression part in an
@code{if} clause in comprehensions and generator expressions. See bpo-41848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41848}
and bpo-43755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43755} for details.
@end itemize

@node 新たなモジュール<5>,改良されたモジュール<5>,その他の言語変更<5>,What's New In Python 3 9
@anchor{whatsnew/3 9 new-modules}@anchor{ada}
@subsection 新たなモジュール


@menu
* zoneinfo:: 
* graphlib: graphlib<2>. 

@end menu

@node zoneinfo,graphlib<2>,,新たなモジュール<5>
@anchor{whatsnew/3 9 zoneinfo}@anchor{adb}
@subsubsection zoneinfo


@ref{13a,,zoneinfo} モジュールにより標準ライブラリにIANAのタイムゾーンデータベースへのサポートを導入されます。@ref{adc,,zoneinfo.ZoneInfo} という、システムのタイムゾーンデータを背景とした具体的な @ref{7f6,,datetime.tzinfo} の実装が追加されます。

以下はプログラム例です:

@example
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta

>>> # Daylight saving time
>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00
>>> dt.tzname()
'PDT'

>>> # Standard time
>>> dt += timedelta(days=7)
>>> print(dt)
2020-11-07 12:00:00-08:00
>>> print(dt.tzname())
PST
@end example

As a fall-back source of data for platforms that don't ship the IANA database,
the tzdata@footnote{https://pypi.org/project/tzdata/} module was released as a first-party package -- distributed via
PyPI and maintained by the CPython core team.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 615

@item PEP 615@footnote{https://peps.python.org/pep-0615/} -- Support for the IANA Time Zone Database in the Standard Library

PEP作成と実装は Paul Ganssle による。
@end table


@node graphlib<2>,,zoneinfo,新たなモジュール<5>
@anchor{whatsnew/3 9 graphlib}@anchor{add}
@subsubsection graphlib


A new module, @ref{69,,graphlib}, was added that contains the
@ref{ade,,graphlib.TopologicalSorter} class to offer functionality to perform
topological sorting of graphs. (Contributed by Pablo Galindo, Tim Peters and
Larry Hastings in bpo-17005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17005}.)

@node 改良されたモジュール<5>,最適化<6>,新たなモジュール<5>,What's New In Python 3 9
@anchor{whatsnew/3 9 improved-modules}@anchor{adf}
@subsection 改良されたモジュール


@menu
* ast: ast<4>. 
* asyncio: asyncio<8>. 
* compileall: compileall<2>. 
* concurrent.futures: concurrent futures<3>. 
* curses: curses<3>. 
* datetime: datetime<3>. 
* distutils: distutils<3>. 
* fcntl: fcntl<2>. 
* ftplib: ftplib<2>. 
* gc: gc<3>. 
* hashlib: hashlib<4>. 
* http: http<2>. 
* IDLE と idelelib: IDLE と idelelib<3>. 
* imaplib: imaplib<2>. 
* importlib: importlib<3>. 
* inspect: inspect<5>. 
* ipaddress: ipaddress<2>. 
* math: math<5>. 
* multiprocessing: multiprocessing<3>. 
* nntplib:: 
* os: os<6>. 
* pathlib: pathlib<9>. 
* pdb: pdb<5>. 
* poplib:: 
* pprint: pprint<2>. 
* pydoc: pydoc<2>. 
* random: random<3>. 
* signal:: 
* smtplib:: 
* socket: socket<4>. 
* time: time<3>. 
* sys: sys<6>. 
* tracemalloc:: 
* typing: typing<7>. 
* unicodedata: unicodedata<5>. 
* venv: venv<3>. 
* xml: xml<3>. 

@end menu

@node ast<4>,asyncio<8>,,改良されたモジュール<5>
@anchor{whatsnew/3 9 ast}@anchor{ae0}
@subsubsection ast


Added the `indent' option to @ref{ae1,,dump()} which allows it to produce a
multiline indented output.
(Contributed by Serhiy Storchaka in bpo-37995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37995}.)

Added @ref{ae2,,ast.unparse()} as a function in the @ref{9,,ast} module that can
be used to unparse an @ref{4c3,,ast.AST} object and produce a string with code
that would produce an equivalent @ref{4c3,,ast.AST} object when parsed.
(Contributed by Pablo Galindo and Batuhan Taskaya in bpo-38870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38870}.)

Added docstrings to AST nodes that contains the ASDL signature used to
construct that node. (Contributed by Batuhan Taskaya in bpo-39638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39638}.)

@node asyncio<8>,compileall<2>,ast<4>,改良されたモジュール<5>
@anchor{whatsnew/3 9 asyncio}@anchor{ae3}
@subsubsection asyncio


セキュリティ上の重大な懸念により、@ref{93c,,asyncio.loop.create_datagram_endpoint()} での `reuse_address' 引数は無効になりました。これはソケットオプション @cite{SO_REUSEADDR`} のUDP における挙動が原因です。詳しくは、@code{loop.create_datagram_endpoint()} のドキュメントを参照してください。(Kyle Stanley, Antoine Pitrou, Yury Selivanov による貢献 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228})

Added a new @ref{6b9,,coroutine} @ref{ae4,,shutdown_default_executor()}
that schedules a shutdown for the default executor that waits on the
@ref{949,,ThreadPoolExecutor} to finish closing. Also,
@ref{2f3,,asyncio.run()} has been updated to use the new @ref{6b9,,coroutine}.
(Contributed by Kyle Stanley in bpo-34037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34037}.)

Added @code{asyncio.PidfdChildWatcher}, a Linux-specific child watcher
implementation that polls process file descriptors. (bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692})

Added a new @ref{6b9,,coroutine} @ref{ae5,,asyncio.to_thread()}. It is mainly used for
running IO-bound functions in a separate thread to avoid blocking the event
loop, and essentially works as a high-level version of
@ref{ae6,,run_in_executor()} that can directly take keyword arguments.
(Contributed by Kyle Stanley and Yury Selivanov in bpo-32309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32309}.)

When cancelling the task due to a timeout, @ref{815,,asyncio.wait_for()} will now
wait until the cancellation is complete also in the case when `timeout' is
<= 0, like it does with positive timeouts.
(Contributed by Elvis Pranskevichus in bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}.)

@ref{b,,asyncio} now raises @ref{198,,TypeError} when calling incompatible
methods with an @ref{ae7,,ssl.SSLSocket} socket.
(Contributed by Ido Michael in bpo-37404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37404}.)

@node compileall<2>,concurrent futures<3>,asyncio<8>,改良されたモジュール<5>
@anchor{whatsnew/3 9 compileall}@anchor{ae8}
@subsubsection compileall


Added new possibility to use hardlinks for duplicated @code{.pyc} files: `hardlink_dupes' parameter and --hardlink-dupes command line option.
(Contributed by  Lumír 'Frenzy' Balhar in bpo-40495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40495}.)

Added new options for path manipulation in resulting @code{.pyc} files: `stripdir', `prependdir', `limit_sl_dest' parameters and -s, -p, -e command line options.
Added the possibility to specify the option for an optimization level multiple times.
(Contributed by Lumír 'Frenzy' Balhar in bpo-38112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38112}.)

@node concurrent futures<3>,curses<3>,compileall<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 concurrent-futures}@anchor{ae9}
@subsubsection concurrent.futures


Added a new `cancel_futures' parameter to
@ref{aea,,concurrent.futures.Executor.shutdown()} that cancels all pending futures
which have not started running, instead of waiting for them to complete before
shutting down the executor.
(Contributed by Kyle Stanley in bpo-39349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39349}.)

Removed daemon threads from @ref{949,,ThreadPoolExecutor}
and @ref{1d6,,ProcessPoolExecutor}. This improves
compatibility with subinterpreters and predictability in their shutdown
processes. (Contributed by Kyle Stanley in bpo-39812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39812}.)

Workers in @ref{1d6,,ProcessPoolExecutor} are now spawned on
demand, only when there are no available idle workers to reuse. This optimizes
startup overhead and reduces the amount of lost CPU time to idle workers.
(Contributed by Kyle Stanley in bpo-39207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39207}.)

@node curses<3>,datetime<3>,concurrent futures<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 curses}@anchor{aeb}
@subsubsection curses


@ref{aec,,curses.get_escdelay()}, @ref{aed,,curses.set_escdelay()}, @ref{aee,,curses.get_tabsize()},  @ref{aef,,curses.set_tabsize()} の関数が追加されました。(Anthony Sottileによる bpo-38312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38312} でのコントリビュート。)

@node datetime<3>,distutils<3>,curses<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 datetime}@anchor{af0}
@subsubsection datetime


The @ref{af1,,isocalendar()} of @ref{1fa,,datetime.date}
and @ref{af2,,isocalendar()} of @ref{4e2,,datetime.datetime}
methods now returns a @ref{4e0,,namedtuple()} instead of a @ref{614,,tuple}.
(Contributed by Donghee Na in bpo-24416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24416}.)

@node distutils<3>,fcntl<2>,datetime<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 distutils}@anchor{af3}
@subsubsection distutils


The @code{upload} command now creates SHA2-256 and Blake2b-256 hash
digests. It skips MD5 on platforms that block MD5 digest.
(Contributed by Christian Heimes in bpo-40698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40698}.)

@node fcntl<2>,ftplib<2>,distutils<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 fcntl}@anchor{af4}
@subsubsection fcntl


Added constants @code{fcntl.F_OFD_GETLK}, @code{fcntl.F_OFD_SETLK}
and @code{fcntl.F_OFD_SETLKW}.
(Contributed by Donghee Na in bpo-38602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38602}.)

@node ftplib<2>,gc<3>,fcntl<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 ftplib}@anchor{af5}
@subsubsection ftplib


@ref{af6,,FTP} and @ref{af7,,FTP_TLS} now raise a @ref{2ec,,ValueError}
if the given timeout for their constructor is zero to prevent the creation of
a non-blocking socket. (Contributed by Donghee Na in bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}.)

@node gc<3>,hashlib<4>,ftplib<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 gc}@anchor{af8}
@subsubsection gc


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. (Contributed by Pablo Galindo and Tim Peters in bpo-38379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38379}.)

Added a new function @ref{af9,,gc.is_finalized()} to check if an object has been
finalized by the garbage collector. (Contributed by Pablo Galindo in
bpo-39322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39322}.)

@node hashlib<4>,http<2>,gc<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 hashlib}@anchor{afa}
@subsubsection hashlib


The @ref{6c,,hashlib} module can now use SHA3 hashes and SHAKE XOF from OpenSSL
when available.
(Contributed by Christian Heimes in bpo-37630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37630}.)

Builtin hash modules can now be disabled with
@code{./configure --without-builtin-hashlib-hashes} or selectively enabled with
e.g. @code{./configure --with-builtin-hashlib-hashes=sha3,blake2} to force use
of OpenSSL based implementation.
(Contributed by Christian Heimes in bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479})

@node http<2>,IDLE と idelelib<3>,hashlib<4>,改良されたモジュール<5>
@anchor{whatsnew/3 9 http}@anchor{afb}
@subsubsection http


HTTP status codes @code{103 EARLY_HINTS}, @code{418 IM_A_TEAPOT} and @code{425 TOO_EARLY} are added to
@ref{afc,,http.HTTPStatus}. (Contributed by Donghee Na in bpo-39509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39509} and Ross Rhodes in bpo-39507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39507}.)

@node IDLE と idelelib<3>,imaplib<2>,http<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 idle-and-idlelib}@anchor{afd}
@subsubsection IDLE と idelelib


Added option to toggle cursor blink off.  (Contributed by Zackery Spytz
in bpo-4603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4603}.)

Escape key now closes IDLE completion windows.  (Contributed by Johnny
Najera in bpo-38944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38944}.)

Added keywords to module name completion list.  (Contributed by Terry J.
Reedy in bpo-37765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37765}.)

New in 3.9 maintenance releases

Make IDLE invoke @ref{a0c,,sys.excepthook()} (when started without '-n').
User hooks were previously ignored.  (Contributed by Ken Hilton in
bpo-43008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43008}.)

The changes above have been backported to 3.8 maintenance releases.

Rearrange the settings dialog.  Split the 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.  (Contributed by Terry Jan
Reedy in bpo-40468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40468}.)  Move the indent space setting from the Font tab to
the new Windows tab.  (Contributed by Mark Roseman and Terry Jan Reedy in
bpo-33962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33962}.)

Apply syntax highlighting to @code{.pyi} files. (Contributed by Alex
Waygood and Terry Jan Reedy in bpo-45447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45447}.)

@node imaplib<2>,importlib<3>,IDLE と idelelib<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 imaplib}@anchor{afe}
@subsubsection imaplib


@ref{aff,,IMAP4} and @ref{b00,,IMAP4_SSL} now have
an optional `timeout' parameter for their constructors.
Also, the @ref{b01,,open()} method now has an optional `timeout' parameter
with this change. The overridden methods of @ref{b00,,IMAP4_SSL} and
@ref{b02,,IMAP4_stream} were applied to this change.
(Contributed by Donghee Na in bpo-38615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38615}.)

@ref{b03,,imaplib.IMAP4.unselect()} is added.
@ref{b03,,imaplib.IMAP4.unselect()} frees server's resources associated with the
selected mailbox and returns the server to the authenticated
state. This command performs the same actions as @ref{b04,,imaplib.IMAP4.close()}, except
that no messages are permanently removed from the currently
selected mailbox. (Contributed by Donghee Na in bpo-40375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40375}.)

@node importlib<3>,inspect<5>,imaplib<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 importlib}@anchor{b05}
@subsubsection importlib


To improve consistency with import statements, @ref{b06,,importlib.util.resolve_name()}
now raises @ref{65b,,ImportError} instead of @ref{2ec,,ValueError} for invalid relative
import attempts.
(Contributed by Ngalim Siregar in bpo-37444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37444}.)

Import loaders which publish immutable module objects can now publish
immutable packages in addition to individual modules.
(Contributed by Dino Viehland in bpo-39336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39336}.)

Added @ref{6b6,,importlib.resources.files()} function with support for
subdirectories in package data, matching backport in @code{importlib_resources}
version 1.5.
(Contributed by Jason R. Coombs in bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791}.)

Refreshed @code{importlib.metadata} from @code{importlib_metadata} version 1.6.1.

@node inspect<5>,ipaddress<2>,importlib<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 inspect}@anchor{b07}
@subsubsection inspect


@ref{b08,,inspect.BoundArguments.arguments} は @code{OrderedDict} から標準のdictに変更されました。(Inada Naoki の貢献による bpo-36350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36350}, bpo-39775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39775})

@node ipaddress<2>,math<5>,inspect<5>,改良されたモジュール<5>
@anchor{whatsnew/3 9 ipaddress}@anchor{b09}
@subsubsection ipaddress


@ref{84,,ipaddress} now supports IPv6 Scoped Addresses (IPv6 address with suffix @code{%<scope_id>}).

Scoped IPv6 addresses can be parsed using @ref{50d,,ipaddress.IPv6Address}.
If present, scope zone ID is available through the @ref{b0a,,scope_id} attribute.
(Contributed by Oleksandr Pavliuk in bpo-34788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34788}.)

Starting with Python 3.9.5 the @ref{84,,ipaddress} module no longer
accepts any leading zeros in IPv4 address strings.
(Contributed by Christian Heimes in bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384}).

@node math<5>,multiprocessing<3>,ipaddress<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 math}@anchor{b0b}
@subsubsection math


Expanded the @ref{b0c,,math.gcd()} function to handle multiple arguments.
Formerly, it only supported two arguments.
(Contributed by Serhiy Storchaka in bpo-39648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39648}.)

Added @ref{b0d,,math.lcm()}: return the least common multiple of specified arguments.
(Contributed by Mark Dickinson, Ananthakrishnan and Serhiy Storchaka in
bpo-39479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39479} and bpo-39648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39648}.)

Added @ref{6c0,,math.nextafter()}: return the next floating-point value after `x'
towards `y'.
(Contributed by Victor Stinner in bpo-39288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39288}.)

Added @ref{b0e,,math.ulp()}: return the value of the least significant bit
of a float.
(Contributed by Victor Stinner in bpo-39310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39310}.)

@node multiprocessing<3>,nntplib,math<5>,改良されたモジュール<5>
@anchor{whatsnew/3 9 multiprocessing}@anchor{b0f}
@subsubsection multiprocessing


The @ref{b10,,multiprocessing.SimpleQueue} class has a new
@ref{b11,,close()} method to explicitly close the
queue.
(Contributed by Victor Stinner in bpo-30966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30966}.)

@node nntplib,os<6>,multiprocessing<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 nntplib}@anchor{b12}
@subsubsection nntplib


@code{NNTP} and @code{NNTP_SSL} now raise a @ref{2ec,,ValueError}
if the given timeout for their constructor is zero to prevent the creation of
a non-blocking socket. (Contributed by Donghee Na in bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}.)

@node os<6>,pathlib<9>,nntplib,改良されたモジュール<5>
@anchor{whatsnew/3 9 os}@anchor{b13}
@subsubsection os


Added @ref{b14,,CLD_KILLED} and @ref{b15,,CLD_STOPPED} for @code{si_code}.
(Contributed by Donghee Na in bpo-38493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38493}.)

Exposed the Linux-specific @ref{6a4,,os.pidfd_open()} (bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}) and
@ref{b16,,os.P_PIDFD} (bpo-38713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38713}) for process management with file
descriptors.

@ref{25c,,os.unsetenv()} 関数が、Windowsでも使えるようになりました。(bpo-39413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39413} におけるVictor Stinnerの貢献による)

@ref{25b,,os.putenv()} と @ref{25c,,os.unsetenv()} 関数が、常に利用できるようになりました。(bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395} におけるVictor Stinnerの貢献による)

Added @ref{b17,,os.waitstatus_to_exitcode()} function:
convert a wait status to an exit code.
(Contributed by Victor Stinner in bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}.)

@node pathlib<9>,pdb<5>,os<6>,改良されたモジュール<5>
@anchor{whatsnew/3 9 pathlib}@anchor{b18}
@subsubsection pathlib


Added @ref{b19,,pathlib.Path.readlink()} which acts similarly to
@ref{b1a,,os.readlink()}.
(Contributed by Girts Folkmanis in bpo-30618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30618})

@node pdb<5>,poplib,pathlib<9>,改良されたモジュール<5>
@anchor{whatsnew/3 9 pdb}@anchor{b1b}
@subsubsection pdb


On Windows now @ref{273,,Pdb} supports @code{~/.pdbrc}.
(Contributed by Tim Hopper and Dan Lidral-Porter in bpo-20523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20523}.)

@node poplib,pprint<2>,pdb<5>,改良されたモジュール<5>
@anchor{whatsnew/3 9 poplib}@anchor{b1c}
@subsubsection poplib


@ref{b1d,,POP3} and @ref{b1e,,POP3_SSL} now raise a @ref{2ec,,ValueError}
if the given timeout for their constructor is zero to prevent the creation of
a non-blocking socket. (Contributed by Donghee Na in bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}.)

@node pprint<2>,pydoc<2>,poplib,改良されたモジュール<5>
@anchor{whatsnew/3 9 pprint}@anchor{b1f}
@subsubsection pprint


@ref{b3,,pprint} can now pretty-print @ref{4e5,,types.SimpleNamespace}.
(Contributed by Carl Bordum Hansen in bpo-37376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37376}.)

@node pydoc<2>,random<3>,pprint<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 pydoc}@anchor{b20}
@subsubsection pydoc


The documentation string is now shown not only for class, function,
method etc, but for any object that has its own @ref{b21,,__doc__}
attribute.
(Contributed by Serhiy Storchaka in bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}.)

@node random<3>,signal,pydoc<2>,改良されたモジュール<5>
@anchor{whatsnew/3 9 random}@anchor{b22}
@subsubsection random


Added a new @ref{b23,,random.Random.randbytes()} method: generate random bytes.
(Contributed by Victor Stinner in bpo-40286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40286}.)

@node signal,smtplib,random<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 signal}@anchor{b24}
@subsubsection signal


Exposed the Linux-specific @ref{b25,,signal.pidfd_send_signal()} for sending to
signals to a process using a file descriptor instead of a pid. (bpo-38712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38712})

@node smtplib,socket<4>,signal,改良されたモジュール<5>
@anchor{whatsnew/3 9 smtplib}@anchor{b26}
@subsubsection smtplib


@ref{b27,,SMTP} and @ref{b28,,SMTP_SSL} now raise a @ref{2ec,,ValueError}
if the given timeout for their constructor is zero to prevent the creation of
a non-blocking socket. (Contributed by Donghee Na in bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}.)

@ref{b29,,LMTP} constructor  now has an optional `timeout' parameter.
(Contributed by Donghee Na in bpo-39329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39329}.)

@node socket<4>,time<3>,smtplib,改良されたモジュール<5>
@anchor{whatsnew/3 9 socket}@anchor{b2a}
@subsubsection socket


The @ref{d1,,socket} module now exports the @ref{b2b,,CAN_RAW_JOIN_FILTERS}
constant on Linux 4.1 and greater.
(Contributed by Stefan Tatschner and Zackery Spytz in bpo-25780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25780}.)

The socket module now supports the @ref{b2c,,CAN_J1939} protocol on
platforms that support it.  (Contributed by Karl Ding in bpo-40291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40291}.)

The socket module now has the @ref{b2d,,socket.send_fds()} and
@ref{b2e,,socket.recv_fds()} functions. (Contributed by Joannah Nanjekye, Shinya
Okano and Victor Stinner in bpo-28724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28724}.)

@node time<3>,sys<6>,socket<4>,改良されたモジュール<5>
@anchor{whatsnew/3 9 time}@anchor{b2f}
@subsubsection time


On AIX, @ref{b30,,thread_time()} is now implemented with @code{thread_cputime()}
which has nanosecond resolution, rather than
@code{clock_gettime(CLOCK_THREAD_CPUTIME_ID)} which has a resolution of 10 milliseconds.
(Contributed by Batuhan Taskaya in bpo-40192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40192})

@node sys<6>,tracemalloc,time<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 sys}@anchor{b31}
@subsubsection sys


Added a new @ref{b32,,sys.platlibdir} attribute: name of the platform-specific
library directory. It is used to build the path of standard library and the
paths of installed extension modules. It is equal to @code{"lib"} on most
platforms.  On Fedora and SuSE, it is equal to @code{"lib64"} on 64-bit platforms.
(Contributed by Jan Matějek, Matěj Cepl, Charalampos Stratakis and Victor Stinner in bpo-1294959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1294959}.)

Previously, @ref{b33,,sys.stderr} was block-buffered when non-interactive. Now
@code{stderr} defaults to always being line-buffered.
(Contributed by Jendrik Seipp in bpo-13601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13601}.)

@node tracemalloc,typing<7>,sys<6>,改良されたモジュール<5>
@anchor{whatsnew/3 9 tracemalloc}@anchor{b34}
@subsubsection tracemalloc


Added @ref{b35,,tracemalloc.reset_peak()} to set the peak size of traced memory
blocks to the current size, to measure the peak of specific pieces of code.
(Contributed by Huon Wilson in bpo-40630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40630}.)

@node typing<7>,unicodedata<5>,tracemalloc,改良されたモジュール<5>
@anchor{whatsnew/3 9 typing}@anchor{b36}
@subsubsection typing


@geindex Python Enhancement Proposals; PEP 593
PEP 593@footnote{https://peps.python.org/pep-0593/} introduced an @ref{b37,,typing.Annotated} type to decorate existing
types with context-specific metadata and new @code{include_extras} parameter to
@ref{8c0,,typing.get_type_hints()} to access the metadata at runtime. (Contributed
by Till Varoquaux and Konstantin Kashin.)

@node unicodedata<5>,venv<3>,typing<7>,改良されたモジュール<5>
@anchor{whatsnew/3 9 unicodedata}@anchor{b38}
@subsubsection unicodedata


Unicode データベースが、バージョン 13.0.0 に更新されました。(bpo-39926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39926})

@node venv<3>,xml<3>,unicodedata<5>,改良されたモジュール<5>
@anchor{whatsnew/3 9 venv}@anchor{b39}
@subsubsection venv


The activation scripts provided by @ref{117,,venv} now all specify their prompt
customization consistently by always using the value specified by
@code{__VENV_PROMPT__}. Previously some scripts unconditionally used
@code{__VENV_PROMPT__}, others only if it happened to be set (which was the default
case), and one used @code{__VENV_NAME__} instead.
(Contributed by Brett Cannon in bpo-37663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37663}.)

@node xml<3>,,venv<3>,改良されたモジュール<5>
@anchor{whatsnew/3 9 xml}@anchor{b3a}
@subsubsection xml


White space characters within attributes are now preserved when serializing
@ref{12b,,xml.etree.ElementTree} to XML file. EOLNs are no longer normalized
to "n". This is the result of discussion about how to interpret
section 2.11 of XML spec.
(Contributed by Mefistotelis in bpo-39011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39011}.)

@node 最適化<6>,非推奨<8>,改良されたモジュール<5>,What's New In Python 3 9
@anchor{whatsnew/3 9 optimizations}@anchor{b3b}
@subsection 最適化



@itemize *

@item 
Optimized the idiom for assignment a temporary variable in comprehensions.
Now @code{for y in [expr]} in comprehensions is as fast as a simple assignment
@code{y = expr}.  For example:

@quotation

sums = [s for s in [0] for x in data for s in [s + x]]
@end quotation

Unlike the @code{:=} operator this idiom does not leak a variable to the
outer scope.

(Contributed by Serhiy Storchaka in bpo-32856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32856}.)

@item 
Optimized 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.
(Contributed by Victor Stinner in bpo-40010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40010}.)

@item 
Optimized the @ref{dc,,subprocess} module on FreeBSD using @code{closefrom()}.
(Contributed by Ed Maste, Conrad Meyer, Kyle Evans, Kubilay Kocak and Victor
Stinner in bpo-38061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38061}.)

@item 
@ref{b3c,,PyLong_FromDouble()} is now up to 1.87x faster for values that
fit into long.
(Contributed by Sergey Fedoseev in bpo-37986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37986}.)

@item 
A number of Python builtins (@ref{b3d,,range}, @ref{614,,tuple}, @ref{184,,set},
@ref{7f2,,frozenset}, @ref{24d,,list}, @ref{183,,dict}) are now sped up by using
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} vectorcall protocol.
(Contributed by Donghee Na, Mark Shannon, Jeroen Demeyer and Petr Viktorin in bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}.)

@item 
Optimized @code{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ù in bpo-8425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8425}.)

@item 
Python's small object allocator (@code{obmalloc.c}) now allows (no more than)
one empty arena to remain available for immediate reuse, without returning
it to the OS.  This prevents thrashing in simple loops where an arena could
be created and destroyed anew on each iteration.
(Contributed by Tim Peters in bpo-37257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37257}.)

@item 
@ref{b3e,,floor division} of float operation now has a better performance. Also
the message of @ref{b3f,,ZeroDivisionError} for this operation is updated.
(Contributed by Donghee Na in bpo-39434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39434}.)

@item 
Decoding short ASCII strings with UTF-8 and ascii codecs is now about
15% faster.  (Contributed by Inada Naoki in bpo-37348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37348}.)
@end itemize

Here's a summary of performance improvements from Python 3.4 through Python 3.9:

@example
Python version                       3.4     3.5     3.6     3.7     3.8    3.9
--------------                       ---     ---     ---     ---     ---    ---

Variable and attribute read access:
    read_local                       7.1     7.1     5.4     5.1     3.9    3.9
    read_nonlocal                    7.1     8.1     5.8     5.4     4.4    4.5
    read_global                     15.5    19.0    14.3    13.6     7.6    7.8
    read_builtin                    21.1    21.6    18.5    19.0     7.5    7.8
    read_classvar_from_class        25.6    26.5    20.7    19.5    18.4   17.9
    read_classvar_from_instance     22.8    23.5    18.8    17.1    16.4   16.9
    read_instancevar                32.4    33.1    28.0    26.3    25.4   25.3
    read_instancevar_slots          27.8    31.3    20.8    20.8    20.2   20.5
    read_namedtuple                 73.8    57.5    45.0    46.8    18.4   18.7
    read_boundmethod                37.6    37.9    29.6    26.9    27.7   41.1

Variable and attribute write access:
    write_local                      8.7     9.3     5.5     5.3     4.3    4.3
    write_nonlocal                  10.5    11.1     5.6     5.5     4.7    4.8
    write_global                    19.7    21.2    18.0    18.0    15.8   16.7
    write_classvar                  92.9    96.0   104.6   102.1    39.2   39.8
    write_instancevar               44.6    45.8    40.0    38.9    35.5   37.4
    write_instancevar_slots         35.6    36.1    27.3    26.6    25.7   25.8

Data structure read access:
    read_list                       24.2    24.5    20.8    20.8    19.0   19.5
    read_deque                      24.7    25.5    20.2    20.6    19.8   20.2
    read_dict                       24.3    25.7    22.3    23.0    21.0   22.4
    read_strdict                    22.6    24.3    19.5    21.2    18.9   21.5

Data structure write access:
    write_list                      27.1    28.5    22.5    21.6    20.0   20.0
    write_deque                     28.7    30.1    22.7    21.8    23.5   21.7
    write_dict                      31.4    33.3    29.3    29.2    24.7   25.4
    write_strdict                   28.4    29.9    27.5    25.2    23.1   24.5

Stack (or queue) operations:
    list_append_pop                 93.4   112.7    75.4    74.2    50.8   50.6
    deque_append_pop                43.5    57.0    49.4    49.2    42.5   44.2
    deque_append_popleft            43.7    57.3    49.7    49.7    42.8   46.4

Timing loop:
    loop_overhead                    0.5     0.6     0.4     0.3     0.3    0.3
@end example

These results were generated from the variable access benchmark script at:
@code{Tools/scripts/var_access_benchmark.py}. The benchmark script displays timings
in nanoseconds.  The benchmarks were measured on an
Intel® Core™ i7-4960HQ processor@footnote{https://ark.intel.com/content/www/us/en/ark/products/76088/intel-core-i7-4960hq-processor-6m-cache-up-to-3-80-ghz.html}
running the macOS 64-bit builds found at
python.org@footnote{https://www.python.org/downloads/macos/}.

@node 非推奨<8>,削除<8>,最適化<6>,What's New In Python 3 9
@anchor{whatsnew/3 9 deprecated}@anchor{b40}
@subsection 非推奨



@itemize *

@item 
distutilsの @code{bdist_msi} コマンドは、現在非推奨です。代わりに、@code{bdist_wheel} (wheelパッケージ)を使って下さい。 ( bpo-39586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39586} でのHugo van Kemenadeによる貢献による)

@item 
Currently @ref{b41,,math.factorial()} accepts @ref{196,,float} instances with
non-negative integer values (like @code{5.0}).  It raises a @ref{2ec,,ValueError}
for non-integral and negative floats.  It is now deprecated.  In future
Python versions it will raise a @ref{198,,TypeError} for all floats.
(Contributed by Serhiy Storchaka in bpo-37315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37315}.)

@item 
The @code{parser} and @code{symbol} modules are deprecated and will be
removed in future versions of Python. For the majority of use cases,
users can leverage the Abstract Syntax Tree (AST) generation and compilation
stage, using the @ref{9,,ast} module.

@item 
The Public C API functions @code{PyParser_SimpleParseStringFlags()},
@code{PyParser_SimpleParseStringFlagsFilename()},
@code{PyParser_SimpleParseFileFlags()} and @code{PyNode_Compile()}
are deprecated and will be removed in Python 3.10 together with the old parser.

@item 
Using @ref{1a2,,NotImplemented} in a boolean context has been deprecated,
as it is almost exclusively the result of incorrect rich comparator
implementations. It will be made a @ref{198,,TypeError} in a future version
of Python.
(Contributed by Josh Rosenberg in bpo-35712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35712}.)

@item 
The @ref{bd,,random} module currently accepts any hashable type as a
possible seed value.  Unfortunately, some of those types are not
guaranteed to have a deterministic hash value.  After Python 3.9,
the module will restrict its seeds to @ref{885,,None}, @ref{19b,,int},
@ref{196,,float}, @ref{169,,str}, @ref{192,,bytes}, and @ref{344,,bytearray}.

@item 
Opening the @ref{65c,,GzipFile} file for writing without specifying
the `mode' argument is deprecated.  In future Python versions it will always
be opened for reading by default.  Specify the `mode' argument for opening
it for writing and silencing a warning.
(Contributed by Serhiy Storchaka in bpo-28286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28286}.)

@item 
Deprecated the @code{split()} method of @code{_tkinter.TkappType} in
favour of the @code{splitlist()} method which has more consistent and
predictable behavior.
(Contributed by Serhiy Storchaka in bpo-38371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38371}.)

@item 
The explicit passing of coroutine objects to @ref{6a7,,asyncio.wait()} has been
deprecated and will be removed in version 3.11.
(Contributed by Yury Selivanov and Kyle Stanley in bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790}.)

@item 
binhex4 and hexbin4 standards are now deprecated. The @code{binhex} module
and the following @ref{11,,binascii} functions are now deprecated:


@itemize *

@item 
@code{b2a_hqx()}, @code{a2b_hqx()}

@item 
@code{rlecode_hqx()}, @code{rledecode_hqx()}
@end itemize

(Contributed by Victor Stinner in bpo-39353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39353}.)

@item 
@ref{9,,ast} classes @code{slice}, @code{Index} and @code{ExtSlice} are considered deprecated
and will be removed in future Python versions.  @code{value} itself should be
used instead of @code{Index(value)}.  @code{Tuple(slices, Load())} should be
used instead of @code{ExtSlice(slices)}.
(Contributed by Serhiy Storchaka in bpo-34822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34822}.)

@item 
@ref{9,,ast} classes @code{Suite}, @code{Param}, @code{AugLoad} and @code{AugStore}
are considered deprecated and will be removed in future Python versions.
They were not generated by the parser and not accepted by the code
generator in Python 3.
(Contributed by Batuhan Taskaya in bpo-39639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39639} and bpo-39969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39969}
and Serhiy Storchaka in bpo-39988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39988}.)

@item 
The @code{PyEval_InitThreads()} and @code{PyEval_ThreadsInitialized()}
functions are now deprecated and will be removed in Python 3.11. Calling
@code{PyEval_InitThreads()} now does nothing. The @ref{164,,GIL} is initialized
by @ref{460,,Py_Initialize()} since Python 3.7.
(Contributed by Victor Stinner in bpo-39877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39877}.)

@item 
Passing @code{None} as the first argument to the @ref{75e,,shlex.split()} function
has been deprecated.  (Contributed by Zackery Spytz in bpo-33262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33262}.)

@item 
@code{smtpd.MailmanProxy()} is now deprecated as it is unusable without
an external module, @code{mailman}.  (Contributed by Samuel Colvin in bpo-35800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35800}.)

@item 
The @code{lib2to3} module now emits a @ref{ac5,,PendingDeprecationWarning}.
Python 3.9 switched to a PEG parser (see 
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/}), and Python 3.10 may
include new language syntax that is not parsable by lib2to3's LL(1) parser.
The @code{lib2to3} module may be removed from the standard library in a future
Python version. Consider third-party alternatives such as LibCST@footnote{https://libcst.readthedocs.io/} or
parso@footnote{https://parso.readthedocs.io/}.
(Contributed by Carl Meyer in bpo-40360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40360}.)

@item 
@ref{94e,,random.shuffle()} の*random* パラメータは非推奨になりました。(Raymond Hettingerの貢献による bpo-40465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40465})
@end itemize

@node 削除<8>,Python 3 9への移植,非推奨<8>,What's New In Python 3 9
@anchor{whatsnew/3 9 removed}@anchor{b42}@anchor{whatsnew/3 9 removed-in-python-39}@anchor{ac8}
@subsection 削除



@itemize *

@item 
The erroneous version at @code{unittest.mock.__version__} has been removed.

@item 
@code{nntplib.NNTP}: @code{xpath()} and @code{xgtitle()} methods have been removed.
These methods are deprecated since Python 3.3. Generally, these extensions
are not supported or not enabled by NNTP server administrators.
For @code{xgtitle()}, please use @code{nntplib.NNTP.descriptions()} or
@code{nntplib.NNTP.description()} instead.
(Contributed by Donghee Na in bpo-39366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39366}.)

@item 
@ref{4be,,array.array}: @code{tostring()} and @code{fromstring()} methods have been
removed. They were aliases to @code{tobytes()} and @code{frombytes()}, deprecated
since Python 3.2.
(Contributed by Victor Stinner in bpo-38916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38916}.)

@item 
The undocumented @code{sys.callstats()} function has been removed. Since Python
3.7, it was deprecated and always returned @ref{885,,None}. It required a special
build option @code{CALL_PROFILE} which was already removed in Python 3.7.
(Contributed by Victor Stinner in bpo-37414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37414}.)

@item 
The @code{sys.getcheckinterval()} and @code{sys.setcheckinterval()} functions have
been removed. They were deprecated since Python 3.2. Use
@ref{b43,,sys.getswitchinterval()} and @ref{b44,,sys.setswitchinterval()} instead.
(Contributed by Victor Stinner in bpo-37392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37392}.)

@item 
The C function @code{PyImport_Cleanup()} has been removed. It was documented as:
"Empty the module table.  For internal use only."
(Contributed by Victor Stinner in bpo-36710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36710}.)

@item 
@code{_dummy_thread} and @code{dummy_threading} modules have been removed. These
modules were deprecated since Python 3.7 which requires threading support.
(Contributed by Victor Stinner in bpo-37312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37312}.)

@item 
@code{aifc.openfp()} alias to @code{aifc.open()}, @code{sunau.openfp()} alias to
@code{sunau.open()}, and @code{wave.openfp()} alias to @ref{b45,,wave.open()} have been
removed. They were deprecated since Python 3.7.
(Contributed by Victor Stinner in bpo-37320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37320}.)

@item 
The @code{isAlive()} method of @ref{176,,threading.Thread}
has been removed. It was deprecated since Python 3.8.
Use @ref{b46,,is_alive()} instead.
(Contributed by Donghee Na in bpo-37804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37804}.)

@item 
Methods @code{getchildren()} and @code{getiterator()} of classes
@ref{b47,,ElementTree} and
@ref{363,,Element} in the @ref{12b,,ElementTree}
module have been removed.  They were deprecated in Python 3.2.
Use @code{iter(x)} or @code{list(x)} instead of @code{x.getchildren()} and
@code{x.iter()} or @code{list(x.iter())} instead of @code{x.getiterator()}.
(Contributed by Serhiy Storchaka in bpo-36543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36543}.)

@item 
The old @ref{b0,,plistlib} API has been removed, it was deprecated since Python
3.4. Use the @ref{b48,,load()}, @ref{b49,,loads()}, @ref{b4a,,dump()}, and
@ref{b4b,,dumps()} functions. Additionally, the `use_builtin_types' parameter was
removed, standard @ref{192,,bytes} objects are always used instead.
(Contributed by Jon Janzen in bpo-36409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36409}.)

@item 
The C function @code{PyGen_NeedsFinalizing} has been removed. It was not
documented, tested, or used anywhere within CPython after the implementation
of 
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/}. Patch by Joannah Nanjekye.
(Contributed by Joannah Nanjekye in bpo-15088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15088})

@item 
@code{base64.encodestring()} and @code{base64.decodestring()}, aliases deprecated
since Python 3.1, have been removed: use @ref{b4c,,base64.encodebytes()} and
@ref{b4d,,base64.decodebytes()} instead.
(Contributed by Victor Stinner in bpo-39351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39351}.)

@item 
@code{fractions.gcd()} function has been removed, it was deprecated since Python
3.5 (bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486}): use @ref{b0c,,math.gcd()} instead.
(Contributed by Victor Stinner in bpo-39350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39350}.)

@item 
The `buffering' parameter of @ref{a66,,bz2.BZ2File} has been removed. Since
Python 3.0, it was ignored and using it emitted a @ref{1a3,,DeprecationWarning}.
Pass an open file object to control how the file is opened.
(Contributed by Victor Stinner in bpo-39357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39357}.)

@item 
The `encoding' parameter of @ref{b4e,,json.loads()} has been removed.
As of Python 3.1, it was deprecated and ignored; using it has emitted a
@ref{1a3,,DeprecationWarning} since Python 3.8.
(Contributed by Inada Naoki in bpo-39377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39377})

@item 
@code{with (await asyncio.lock):} and @code{with (yield from asyncio.lock):} statements are
not longer supported, use @code{async with lock} instead.  The same is correct for
@code{asyncio.Condition} and @code{asyncio.Semaphore}.
(Contributed by Andrew Svetlov in bpo-34793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34793}.)

@item 
The @code{sys.getcounts()} function, the @code{-X showalloccount} command line
option and the @code{show_alloc_count} field of the C structure
@ref{3f7,,PyConfig} have been removed. They required a special Python build by
defining @code{COUNT_ALLOCS} macro.
(Contributed by Victor Stinner in bpo-39489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39489}.)

@item 
The @code{_field_types} attribute of the @ref{331,,typing.NamedTuple} class
has been removed.  It was deprecated since Python 3.8.  Use
the @code{__annotations__} attribute instead.
(Contributed by Serhiy Storchaka in bpo-40182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40182}.)

@item 
The @code{symtable.SymbolTable.has_exec()} method has been removed. It was
deprecated since 2006, and only returning @code{False} when it's called.
(Contributed by Batuhan Taskaya in bpo-40208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40208})

@item 
The @code{asyncio.Task.current_task()} and @code{asyncio.Task.all_tasks()}
have been removed. They were deprecated since Python 3.7 and you can use
@ref{6a5,,asyncio.current_task()} and @ref{b4f,,asyncio.all_tasks()} instead.
(Contributed by Rémi Lapeyre in bpo-40967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40967})

@item 
The @code{unescape()} method in the @ref{a77,,html.parser.HTMLParser} class
has been removed (it was deprecated since Python 3.4).  @ref{b50,,html.unescape()}
should be used for converting character references to the corresponding
unicode characters.
@end itemize

@node Python 3 9への移植,Build Changes<5>,削除<8>,What's New In Python 3 9
@anchor{whatsnew/3 9 porting-to-python-3-9}@anchor{b51}
@subsection Python 3.9への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python API の変更: Python API の変更<5>. 
* C API の変更: C API の変更<8>. 
* CPython バイトコードの変更: CPython バイトコードの変更<5>. 

@end menu

@node Python API の変更<5>,C API の変更<8>,,Python 3 9への移植
@anchor{whatsnew/3 9 changes-in-the-python-api}@anchor{b52}
@subsubsection Python API の変更



@itemize *

@item 
@ref{ad1,,__import__()} and @ref{b06,,importlib.util.resolve_name()} now raise
@ref{65b,,ImportError} where it previously raised @ref{2ec,,ValueError}. Callers
catching the specific exception type and supporting both Python 3.9 and
earlier versions will need to catch both using @code{except (ImportError, ValueError):}.

@item 
The @ref{117,,venv} activation scripts no longer special-case when
@code{__VENV_PROMPT__} is set to @code{""}.

@item 
The @ref{b53,,select.epoll.unregister()} method no longer ignores the
@ref{b54,,EBADF} error.
(Contributed by Victor Stinner in bpo-39239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39239}.)

@item 
The `compresslevel' parameter of @ref{a66,,bz2.BZ2File} became keyword-only,
since the `buffering' parameter has been removed.
(Contributed by Victor Stinner in bpo-39357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39357}.)

@item 
Simplified AST for subscription. Simple indices will be represented by
their value, extended slices will be represented as tuples.
@code{Index(value)} will return a @code{value} itself, @code{ExtSlice(slices)}
will return @code{Tuple(slices, Load())}.
(Contributed by Serhiy Storchaka in bpo-34822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34822}.)

@item 
The @ref{7b,,importlib} module now ignores the 
@geindex PYTHONCASEOK
@geindex 環境変数; PYTHONCASEOK
@ref{b55,,PYTHONCASEOK}
environment variable when the @ref{b56,,-E} or @ref{b57,,-I} command line
options are being used.

@item 
The `encoding' parameter has been added to the classes @ref{af6,,ftplib.FTP} and
@ref{af7,,ftplib.FTP_TLS} as a keyword-only parameter, and the default encoding
is changed from Latin-1 to UTF-8 to follow 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://datatracker.ietf.org/doc/html/rfc2640.html}.

@item 
@ref{ae4,,asyncio.loop.shutdown_default_executor()} has been added to
@ref{b58,,AbstractEventLoop}, meaning alternative event loops that
inherit from it should have this method defined.
(Contributed by Kyle Stanley in bpo-34037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34037}.)

@item 
The constant values of future flags in the @ref{0,,__future__} module
is updated in order to prevent collision with compiler flags. Previously
@code{PyCF_ALLOW_TOP_LEVEL_AWAIT} was clashing with @code{CO_FUTURE_DIVISION}.
(Contributed by Batuhan Taskaya in bpo-39562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39562})

@item 
@code{array('u')} now uses @code{wchar_t} as C type instead of @code{Py_UNICODE}.
This change doesn't affect to its behavior because @code{Py_UNICODE} is alias
of @code{wchar_t} since Python 3.3.
(Contributed by Inada Naoki in bpo-34538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34538}.)

@item 
The @ref{b59,,logging.getLogger()} API now returns the root logger when passed
the name @code{'root'}, whereas previously it returned a non-root logger named
@code{'root'}. This could affect cases where user code explicitly wants a
non-root logger named @code{'root'}, or instantiates a logger using
@code{logging.getLogger(__name__)} in some top-level module called @code{'root.py'}.
(Contributed by Vinay Sajip in bpo-37742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37742}.)

@item 
Division handling of @ref{6cd,,PurePath} now returns @ref{1a2,,NotImplemented}
instead of raising a @ref{198,,TypeError} when passed something other than an
instance of @code{str} or @ref{6cd,,PurePath}.  This allows creating
compatible classes that don't inherit from those mentioned types.
(Contributed by Roger Aiudi in bpo-34775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34775}).

@item 
Starting with Python 3.9.5 the @ref{84,,ipaddress} module no longer
accepts any leading zeros in IPv4 address strings. Leading zeros are
ambiguous and interpreted as octal notation by some libraries. For example
the legacy function @ref{b5a,,socket.inet_aton()} treats leading zeros as octal
notatation. glibc implementation of modern @ref{b5b,,inet_pton()} does
not accept any leading zeros.
(Contributed by Christian Heimes in bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384}).

@item 
@ref{b5c,,codecs.lookup()} now normalizes the encoding name the same way as
@ref{9fd,,encodings.normalize_encoding()}, except that @ref{b5c,,codecs.lookup()} also
converts the name to lower case. For example, @code{"latex+latin1"} encoding
name is now normalized to @code{"latex_latin1"}.
(Contributed by Jordon Xu in bpo-37751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37751}.)
@end itemize

@node C API の変更<8>,CPython バイトコードの変更<5>,Python API の変更<5>,Python 3 9への移植
@anchor{whatsnew/3 9 changes-in-the-c-api}@anchor{b5d}
@subsubsection C API の変更



@itemize *

@item 
Instances of @ref{b5e,,heap-allocated types} (such as those created with
@ref{79d,,PyType_FromSpec()} and similar APIs) hold a reference to their type
object since Python 3.8. As indicated in the "Changes in the C API" of Python
3.8, for the vast majority of cases, there should be no side effect but for
types that have a custom @ref{982,,tp_traverse} function,
ensure that all custom @code{tp_traverse} functions of heap-allocated types
visit the object's type.

@quotation

例:

@example
int
foo_traverse(PyObject *self, visitproc visit, void *arg)
@{
// Rest of the traverse function
#if PY_VERSION_HEX >= 0x03090000
    // This was not needed before Python 3.9 (Python issue 35810 and 40217)
    Py_VISIT(Py_TYPE(self));
#endif
@}
@end example
@end quotation

If your traverse function delegates to @code{tp_traverse} of its base class
(or another type), ensure that @code{Py_TYPE(self)} is visited only once.
Note that only @ref{b5e,,heap type} are expected to visit the type
in @code{tp_traverse}.

@quotation

For example, if your @code{tp_traverse} function includes:

@example
base->tp_traverse(self, visit, arg)
@end example

then add:

@example
#if PY_VERSION_HEX >= 0x03090000
    // This was not needed before Python 3.9 (bpo-35810 and bpo-40217)
    if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) @{
        // a heap type's tp_traverse already visited Py_TYPE(self)
    @} else @{
        Py_VISIT(Py_TYPE(self));
    @}
#else
@end example
@end quotation

(See bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810} and bpo-40217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40217} for more information.)

@item 
The functions @code{PyEval_CallObject}, @code{PyEval_CallFunction},
@code{PyEval_CallMethod} and @code{PyEval_CallObjectWithKeywords} are deprecated.
Use @ref{63d,,PyObject_Call()} and its variants instead.
(See more details in bpo-29548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29548}.)
@end itemize

@node CPython バイトコードの変更<5>,,C API の変更<8>,Python 3 9への移植
@anchor{whatsnew/3 9 cpython-bytecode-changes}@anchor{b5f}
@subsubsection CPython バイトコードの変更



@itemize *

@item 
The @code{LOAD_ASSERTION_ERROR} opcode was added for handling the
@ref{b60,,assert} statement. Previously, the assert statement would not work
correctly if the @ref{8b8,,AssertionError} exception was being shadowed.
(Contributed by Zackery Spytz in bpo-34880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34880}.)

@item 
The @ref{b61,,COMPARE_OP} opcode was split into four distinct instructions:


@itemize *

@item 
@code{COMPARE_OP} for rich comparisons

@item 
@code{IS_OP} for 'is' and 'is not' tests

@item 
@code{CONTAINS_OP} for 'in' and 'not in' tests

@item 
@code{JUMP_IF_NOT_EXC_MATCH} for checking exceptions in 'try-except'
statements.
@end itemize

(Contributed by Mark Shannon in bpo-39156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39156}.)
@end itemize

@node Build Changes<5>,C API の変更<9>,Python 3 9への移植,What's New In Python 3 9
@anchor{whatsnew/3 9 build-changes}@anchor{b62}
@subsection Build Changes



@itemize *

@item 
Added @code{--with-platlibdir} option to the @code{configure} script: name of the
platform-specific library directory, stored in the new @ref{b32,,sys.platlibdir}
attribute. See @ref{b32,,sys.platlibdir} attribute for more information.
(Contributed by Jan Matějek, Matěj Cepl, Charalampos Stratakis
and Victor Stinner in bpo-1294959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1294959}.)

@item 
The @code{COUNT_ALLOCS} special build macro has been removed.
(Contributed by Victor Stinner in bpo-39489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39489}.)

@item 
On non-Windows platforms, the @code{setenv()} and @code{unsetenv()}
functions are now required to build Python.
(Contributed by Victor Stinner in bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395}.)

@item 
On non-Windows platforms, creating @code{bdist_wininst} installers is now
officially unsupported.  (See bpo-10945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10945} for more details.)

@item 
When building Python on macOS from source, @code{_tkinter} now links with
non-system Tcl and Tk frameworks if they are installed in
@code{/Library/Frameworks}, as had been the case on older releases
of macOS. If a macOS SDK is explicitly configured, by using
@ref{b63,,--enable-universalsdk} or @code{-isysroot}, only the SDK itself is
searched. The default behavior can still be overridden with
@code{--with-tcltk-includes} and @code{--with-tcltk-libs}.
(Contributed by Ned Deily in bpo-34956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34956}.)

@item 
Python can now be built for Windows 10 ARM64.
(Contributed by Steve Dower in bpo-33125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33125}.)

@item 
Some individual tests are now skipped when @code{--pgo} is used.  The tests
in question increased the PGO task time significantly and likely
didn't help improve optimization of the final executable. 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
@code{./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.
(See bpo-36044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36044} and bpo-37707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37707} for more details.)
@end itemize

@node C API の変更<9>,Python 3 9 1 での重要な変更点,Build Changes<5>,What's New In Python 3 9
@anchor{whatsnew/3 9 c-api-changes}@anchor{b64}
@subsection C API の変更


@menu
* 新しい機能: 新しい機能<11>. 
* Python 3.9への移植: Python 3 9への移植<2>. 
* 削除: 削除<9>. 

@end menu

@node 新しい機能<11>,Python 3 9への移植<2>,,C API の変更<9>
@anchor{whatsnew/3 9 id1}@anchor{b65}
@subsubsection 新しい機能



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 573
PEP 573@footnote{https://peps.python.org/pep-0573/}: Added @ref{773,,PyType_FromModuleAndSpec()} to associate
a module with a class; @ref{b66,,PyType_GetModule()} and
@ref{b67,,PyType_GetModuleState()} to retrieve the module and its state; and
@ref{968,,PyCMethod} and @ref{b68,,METH_METHOD} to allow a method to
access the class it was defined in.
(Contributed by Marcel Plch and Petr Viktorin in bpo-38787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38787}.)

@item 
Added @ref{98d,,PyFrame_GetCode()} function: get a frame code.
Added @ref{989,,PyFrame_GetBack()} function: get the frame next outer frame.
(Contributed by Victor Stinner in bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}.)

@item 
Added @ref{98e,,PyFrame_GetLineNumber()} to the limited C API.
(Contributed by Victor Stinner in bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}.)

@item 
Added @ref{b69,,PyThreadState_GetInterpreter()} and
@ref{64c,,PyInterpreterState_Get()} functions to get the interpreter.
Added @ref{991,,PyThreadState_GetFrame()} function to get the current frame of a
Python thread state.
Added @ref{b6a,,PyThreadState_GetID()} function: get the unique identifier of a
Python thread state.
(Contributed by Victor Stinner in bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}.)

@item 
Added a new public @ref{63c,,PyObject_CallNoArgs()} function to the C API, which
calls a callable Python object without any arguments. It is the most efficient
way to call a callable Python object without any argument.
(Contributed by Victor Stinner in bpo-37194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37194}.)

@item 
Changes in the limited C API (if @code{Py_LIMITED_API} macro is defined):


@itemize *

@item 
Provide @ref{3d2,,Py_EnterRecursiveCall()} and @ref{b6b,,Py_LeaveRecursiveCall()}
as regular functions for the limited API. Previously, there were defined as
macros, but these macros didn't compile with the limited C API which cannot
access @code{PyThreadState.recursion_depth} field (the structure is opaque in
the limited C API).

@item 
@code{PyObject_INIT()} and @code{PyObject_INIT_VAR()} become regular "opaque"
function to hide implementation details.
@end itemize

(Contributed by Victor Stinner in bpo-38644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38644} and bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}.)

@item 
The @ref{b6c,,PyModule_AddType()} function is added to help adding a type
to a module.
(Contributed by Donghee Na in bpo-40024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40024}.)

@item 
Added the functions @ref{b6d,,PyObject_GC_IsTracked()} and
@ref{b6e,,PyObject_GC_IsFinalized()} to the public API to allow to query if
Python objects are being currently tracked or have been already finalized by
the garbage collector respectively.
(Contributed by Pablo Galindo Salgado in bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241}.)

@item 
Added @code{_PyObject_FunctionStr()} to get a user-friendly string
representation of a function-like object.
(Patch by Jeroen Demeyer in bpo-37645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37645}.)

@item 
Added @ref{b6f,,PyObject_CallOneArg()} for calling an object with one
positional argument
(Patch by Jeroen Demeyer in bpo-37483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37483}.)
@end itemize

@node Python 3 9への移植<2>,削除<9>,新しい機能<11>,C API の変更<9>
@anchor{whatsnew/3 9 id2}@anchor{b70}
@subsubsection Python 3.9への移植



@itemize *

@item 
@code{PyInterpreterState.eval_frame} (
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/}) now requires a new mandatory
`tstate' parameter (@code{PyThreadState*}).
(Contributed by Victor Stinner in bpo-38500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38500}.)

@item 
Extension modules: @ref{b71,,m_traverse},
@ref{b72,,m_clear} and @ref{b73,,m_free}
functions of @ref{b74,,PyModuleDef} are no longer called if the module state
was requested but is not allocated yet. This is the case immediately after
the module is created and before the module is executed
(@ref{b75,,Py_mod_exec} function). More precisely, these functions are not called
if @ref{b76,,m_size} is greater than 0 and the module state (as
returned by @ref{b77,,PyModule_GetState()}) is @code{NULL}.

Extension modules without module state (@code{m_size <= 0}) are not affected.

@item 
If @ref{b78,,Py_AddPendingCall()} is called in a subinterpreter, the function is
now scheduled to be called from the subinterpreter, rather than being called
from the main interpreter. Each subinterpreter now has its own list of
scheduled calls.
(Contributed by Victor Stinner in bpo-39984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39984}.)

@item 
The Windows registry is no longer used to initialize @ref{3e4,,sys.path} when
the @code{-E} option is used (if @ref{40b,,PyConfig.use_environment} is set to
@code{0}). This is significant when embedding Python on Windows.
(Contributed by Zackery Spytz in bpo-8901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8901}.)

@item 
The global variable @ref{b79,,PyStructSequence_UnnamedField} is now a constant
and refers to a constant string.
(Contributed by Serhiy Storchaka in bpo-38650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38650}.)

@item 
The @code{PyGC_Head} structure is now opaque. It is only defined in the
internal C API (@code{pycore_gc.h}).
(Contributed by Victor Stinner in bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241}.)

@item 
The @code{Py_UNICODE_COPY}, @code{Py_UNICODE_FILL}, @code{PyUnicode_WSTR_LENGTH},
@code{PyUnicode_FromUnicode()}, @code{PyUnicode_AsUnicode()},
@code{_PyUnicode_AsUnicode}, and @code{PyUnicode_AsUnicodeAndSize()} are
marked as deprecated in C.  They have been deprecated by 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} since
Python 3.3.
(Contributed by Inada Naoki in bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}.)

@item 
The @ref{b7a,,Py_FatalError()} function is replaced with a macro which logs
automatically the name of the current function, unless the
@code{Py_LIMITED_API} macro is defined.
(Contributed by Victor Stinner in bpo-39882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39882}.)

@item 
The vectorcall protocol now requires that the caller passes only strings as
keyword names. (See bpo-37540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37540} for more information.)

@item 
Implementation details of a number of macros and functions are now hidden:


@itemize *

@item 
@ref{b7b,,PyObject_IS_GC()} macro was converted to a function.

@item 
The @code{PyObject_NEW()} macro becomes an alias to the
@ref{b7c,,PyObject_New} macro, and the @code{PyObject_NEW_VAR()} macro
becomes an alias to the @ref{b7d,,PyObject_NewVar} macro. They no longer
access directly the @ref{b7e,,PyTypeObject.tp_basicsize} member.

@item 
@code{PyObject_GET_WEAKREFS_LISTPTR()} macro was converted to a function:
the macro accessed directly the @ref{b7f,,PyTypeObject.tp_weaklistoffset}
member.

@item 
@ref{639,,PyObject_CheckBuffer()} macro was converted to a function: the macro
accessed directly the @ref{b80,,PyTypeObject.tp_as_buffer} member.

@item 
@ref{b81,,PyIndex_Check()} is now always declared as an opaque function to hide
implementation details: removed the @code{PyIndex_Check()} macro. The macro accessed
directly the @ref{b82,,PyTypeObject.tp_as_number} member.
@end itemize

(See bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170} for more details.)
@end itemize

@node 削除<9>,,Python 3 9への移植<2>,C API の変更<9>
@anchor{whatsnew/3 9 id3}@anchor{b83}
@subsubsection 削除



@itemize *

@item 
Excluded @code{PyFPE_START_PROTECT()} and @code{PyFPE_END_PROTECT()} macros of
@code{pyfpe.h} from the limited C API.
(Contributed by Victor Stinner in bpo-38835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38835}.)

@item 
The @code{tp_print} slot of @ref{b84,,PyTypeObject} has been removed.
It was used for printing objects to files in Python 2.7 and before. Since
Python 3.0, it has been ignored and unused.
(Contributed by Jeroen Demeyer in bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}.)

@item 
Changes in the limited C API (if @code{Py_LIMITED_API} macro is defined):


@itemize *

@item 
Excluded the following functions from the limited C API:


@itemize *

@item 
@code{PyThreadState_DeleteCurrent()}
(Contributed by Joannah Nanjekye in bpo-37878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37878}.)

@item 
@code{_Py_CheckRecursionLimit}

@item 
@code{_Py_NewReference()}

@item 
@code{_Py_ForgetReference()}

@item 
@code{_PyTraceMalloc_NewReference()}

@item 
@code{_Py_GetRefTotal()}

@item 
The trashcan mechanism which never worked in the limited C API.

@item 
@code{PyTrash_UNWIND_LEVEL}

@item 
@code{Py_TRASHCAN_BEGIN_CONDITION}

@item 
@code{Py_TRASHCAN_BEGIN}

@item 
@code{Py_TRASHCAN_END}

@item 
@code{Py_TRASHCAN_SAFE_BEGIN}

@item 
@code{Py_TRASHCAN_SAFE_END}
@end itemize

@item 
Moved following functions and definitions to the internal C API:


@itemize *

@item 
@code{_PyDebug_PrintTotalRefs()}

@item 
@code{_Py_PrintReferences()}

@item 
@code{_Py_PrintReferenceAddresses()}

@item 
@code{_Py_tracemalloc_config}

@item 
@code{_Py_AddToAllObjects()} (specific to @code{Py_TRACE_REFS} build)
@end itemize
@end itemize

(Contributed by Victor Stinner in bpo-38644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38644} and bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}.)

@item 
Removed @code{_PyRuntime.getframe} hook and removed @code{_PyThreadState_GetFrame}
macro which was an alias to @code{_PyRuntime.getframe}. They were only exposed
by the internal C API. Removed also @code{PyThreadFrameGetter} type.
(Contributed by Victor Stinner in bpo-39946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39946}.)

@item 
Removed the following functions from the C API. Call @ref{b85,,PyGC_Collect()}
explicitly to clear all free lists.
(Contributed by Inada Naoki and Victor Stinner in bpo-37340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37340},
bpo-38896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38896} and bpo-40428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40428}.)


@itemize *

@item 
@code{PyAsyncGen_ClearFreeLists()}

@item 
@code{PyContext_ClearFreeList()}

@item 
@code{PyDict_ClearFreeList()}

@item 
@code{PyFloat_ClearFreeList()}

@item 
@code{PyFrame_ClearFreeList()}

@item 
@code{PyList_ClearFreeList()}

@item 
@code{PyMethod_ClearFreeList()} and @code{PyCFunction_ClearFreeList()}:
the free lists of bound method objects have been removed.

@item 
@code{PySet_ClearFreeList()}: the set free list has been removed
in Python 3.4.

@item 
@code{PyTuple_ClearFreeList()}

@item 
@code{PyUnicode_ClearFreeList()}: the Unicode free list has been removed in
Python 3.3.
@end itemize

@item 
Removed @code{_PyUnicode_ClearStaticStrings()} function.
(Contributed by Victor Stinner in bpo-39465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39465}.)

@item 
Removed @code{Py_UNICODE_MATCH}. It has been deprecated by 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/}, and
broken since Python 3.3. The @ref{ab5,,PyUnicode_Tailmatch()} function can be
used instead.
(Contributed by Inada Naoki in bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}.)

@item 
Cleaned header files of interfaces defined but with no implementation.
The public API symbols being removed are:
@code{_PyBytes_InsertThousandsGroupingLocale},
@code{_PyBytes_InsertThousandsGrouping}, @code{_Py_InitializeFromArgs},
@code{_Py_InitializeFromWideArgs}, @code{_PyFloat_Repr}, @code{_PyFloat_Digits},
@code{_PyFloat_DigitsInit}, @code{PyFrame_ExtendStack}, @code{_PyAIterWrapper_Type},
@code{PyNullImporter_Type}, @code{PyCmpWrapper_Type}, @code{PySortWrapper_Type},
@code{PyNoArgsFunction}.
(Contributed by Pablo Galindo Salgado in bpo-39372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39372}.)
@end itemize

@node Python 3 9 1 での重要な変更点,Python 3 9 2 での重要な変更点,C API の変更<9>,What's New In Python 3 9
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-1}@anchor{b86}
@subsection Python 3.9.1 での重要な変更点


@menu
* typing: typing<8>. 
* macOS 11.0 (Big Sur) と Appleシリコンの Mac のサポート: macOS 11 0 Big Sur と Appleシリコンの Mac のサポート. 

@end menu

@node typing<8>,macOS 11 0 Big Sur と Appleシリコンの Mac のサポート,,Python 3 9 1 での重要な変更点
@anchor{whatsnew/3 9 id4}@anchor{b87}
@subsubsection typing


The behavior of @ref{a55,,typing.Literal} was changed to conform with 
@geindex Python Enhancement Proposals; PEP 586
PEP 586@footnote{https://peps.python.org/pep-0586/}
and to match the behavior of static type checkers specified in the PEP.


@enumerate 

@item 
@code{Literal} now de-duplicates parameters.

@item 
Equality comparisons between @code{Literal} objects are now order independent.

@item 
@code{Literal} comparisons now respect types.  For example,
@code{Literal[0] == Literal[False]} previously evaluated to @code{True}.  It is
now @code{False}.  To support this change, the internally used type cache now
supports differentiating types.

@item 
@code{Literal} objects will now raise a @ref{198,,TypeError} exception during
equality comparisons if any of their parameters are not @ref{824,,hashable}.
Note that declaring @code{Literal} with mutable parameters will not throw
an error:

@example
>>> from typing import Literal
>>> Literal[@{0@}]
>>> Literal[@{0@}] == Literal[@{False@}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
@end example
@end enumerate

(bpo-42345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42345} でのYurii Karabasの貢献による)

@node macOS 11 0 Big Sur と Appleシリコンの Mac のサポート,,typing<8>,Python 3 9 1 での重要な変更点
@anchor{whatsnew/3 9 macos-11-0-big-sur-and-apple-silicon-mac-support}@anchor{b88}
@subsubsection macOS 11.0 (Big Sur) と Appleシリコンの Mac のサポート


As of 3.9.1, Python now fully supports building and running on macOS 11.0
(Big Sur) and on Apple Silicon Macs (based on the @code{ARM64} architecture).
A new universal build variant, @code{universal2}, is now available to natively
support both @code{ARM64} and @code{Intel 64} in one set of executables. Binaries
can also now be built on current versions of macOS to be deployed on a range
of older macOS versions (tested to 10.9) while making some newer OS
functions and options conditionally available based on the operating system
version in use at runtime ("weaklinking").

(bpo-41100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41100} でのRonald OussorenとLawrence D'Annaの貢献による)

@node Python 3 9 2 での重要な変更点,Python 3 9 3 での重要な変更点,Python 3 9 1 での重要な変更点,What's New In Python 3 9
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-2}@anchor{b89}
@subsection Python 3.9.2 での重要な変更点


@menu
* collections.abc: collections abc<2>. 
* urllib.parse: urllib parse<2>. 

@end menu

@node collections abc<2>,urllib parse<2>,,Python 3 9 2 での重要な変更点
@anchor{whatsnew/3 9 collections-abc}@anchor{b8a}
@subsubsection collections.abc


@ref{9eb,,collections.abc.Callable} generic now flattens type parameters, similar
to what @ref{9c8,,typing.Callable} currently does.  This means that
@code{collections.abc.Callable[[int, str], str]} will have @code{__args__} of
@code{(int, str, str)}; previously this was @code{([int, str], str)}.  To allow this
change, @ref{9ec,,types.GenericAlias} can now be subclassed, and a subclass will
be returned when subscripting the @ref{9eb,,collections.abc.Callable} type.
Code which accesses the arguments via @ref{2ac,,typing.get_args()} or @code{__args__}
need to account for this change.  A @ref{1a3,,DeprecationWarning} may be emitted for
invalid forms of parameterizing @ref{9eb,,collections.abc.Callable} which may have
passed silently in Python 3.9.1.  This @ref{1a3,,DeprecationWarning} will
become a @ref{198,,TypeError} in Python 3.10.
(Contributed by Ken Jin in bpo-42195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42195}.)

@node urllib parse<2>,,collections abc<2>,Python 3 9 2 での重要な変更点
@anchor{whatsnew/3 9 urllib-parse}@anchor{b8b}
@subsubsection urllib.parse


Earlier Python versions allowed using both @code{;} and @code{&} as
query parameter separators in @ref{31f,,urllib.parse.parse_qs()} and
@ref{31e,,urllib.parse.parse_qsl()}.  Due to security concerns, and to conform with
newer W3C recommendations, this has been changed to allow only a single
separator key, with @code{&} as the default.  This change also affects
@code{cgi.parse()} and @code{cgi.parse_multipart()} as they use the affected
functions internally. For more details, please see their respective
documentation.
(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}.)

@node Python 3 9 3 での重要な変更点,Python 3 9 5での重要な変更点,Python 3 9 2 での重要な変更点,What's New In Python 3 9
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-3}@anchor{b8c}
@subsection Python 3.9.3 での重要な変更点


A security fix alters the @ref{af6,,ftplib.FTP} behavior to not trust the
IPv4 address sent from the remote server when setting up a passive data
channel.  We reuse the ftp server IP address instead.  For unusual code
requiring the old behavior, set a @code{trust_server_pasv_ipv4_address}
attribute on your FTP instance to @code{True}.  (See gh-87451@footnote{https://github.com/python/cpython/issues/87451})

@node Python 3 9 5での重要な変更点,Notable security feature in 3 9 14,Python 3 9 3 での重要な変更点,What's New In Python 3 9
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-5}@anchor{b8d}
@subsection Python 3.9.5での重要な変更点


@menu
* urllib.parse: urllib parse<3>. 

@end menu

@node urllib parse<3>,,,Python 3 9 5での重要な変更点
@anchor{whatsnew/3 9 id5}@anchor{b8e}
@subsubsection urllib.parse


The presence of newline or tab characters in parts of a URL allows for some
forms of attacks. Following the WHATWG specification that updates 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html},
ASCII newline @code{\n}, @code{\r} and tab @code{\t} characters are stripped from the
URL by the parser in @ref{110,,urllib.parse} preventing such attacks. The removal
characters are controlled by a new module level variable
@code{urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE}. (See gh-88048@footnote{https://github.com/python/cpython/issues/88048})

@node Notable security feature in 3 9 14,Notable changes in 3 9 17,Python 3 9 5での重要な変更点,What's New In Python 3 9
@anchor{whatsnew/3 9 notable-security-feature-in-3-9-14}@anchor{b8f}
@subsection Notable security feature in 3.9.14


Converting between @ref{19b,,int} and @ref{169,,str} in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
now raises a @ref{2ec,,ValueError} if the number of digits in string form is
above a limit to avoid potential denial of service attacks due to the
algorithmic complexity. This is a mitigation for 
@geindex Common Vulnerabilities and Exposures; CVE 2020-10735
CVE 2020-10735@footnote{https://www.cve.org/CVERecord?id=CVE-2020-10735}.
This limit can be configured or disabled by environment variable, command
line flag, or @ref{df,,sys} APIs. See the @ref{80b,,integer string conversion length limitation} documentation.  The default limit
is 4300 digits in string form.

@node Notable changes in 3 9 17,,Notable security feature in 3 9 14,What's New In Python 3 9
@anchor{whatsnew/3 9 notable-changes-in-3-9-17}@anchor{b90}
@subsection Notable changes in 3.9.17


@menu
* tarfile: tarfile<4>. 

@end menu

@node tarfile<4>,,,Notable changes in 3 9 17
@anchor{whatsnew/3 9 tarfile}@anchor{b91}
@subsubsection tarfile



@itemize *

@item 
The extraction methods in @ref{e4,,tarfile}, and @ref{696,,shutil.unpack_archive()},
have a new a `filter' argument that allows limiting tar features than may be
surprising or dangerous, such as creating files outside the destination
directory.
See @ref{697,,Extraction filters} for details.
In Python 3.12, use without the `filter' argument will show a
@ref{1a3,,DeprecationWarning}.
In Python 3.14, the default will switch to @code{'data'}.
(Contributed by Petr Viktorin in 
@geindex Python Enhancement Proposals; PEP 706
PEP 706@footnote{https://peps.python.org/pep-0706/}.)
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 8,What's New In Python 3 7,What's New In Python 3 9,What's New in Python
@anchor{whatsnew/3 8 doc}@anchor{b92}@anchor{whatsnew/3 8 translation-repo}@anchor{b93}@anchor{whatsnew/3 8 what-s-new-in-python-3-8}@anchor{b94}
@section What's New In Python 3.8


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Git log
@c when researching a change.

@*編集者: 
Raymond Hettinger


This article explains the new features in Python 3.8, compared to 3.7.
Python 3.8 was released on October 14, 2019.
For full details, see the @ref{142,,changelog}.

@c from datetime import date
@c from math import cos, radians
@c from unicodedata import normalize
@c import re
@c import math

@menu
* 概要: 概要 -- リリースハイライト<7>. リリースハイライト
* 新しい機能: 新しい機能<12>. 
* その他の言語変更: その他の言語変更<6>. 
* 新たなモジュール: 新たなモジュール<6>. 
* 改良されたモジュール: 改良されたモジュール<6>. 
* 最適化: 最適化<7>. 
* ビルドならびに C API の変更:: 
* 非推奨: 非推奨<9>. 
* API と機能の削除:: 
* Python 3.8 への移植: Python 3 8 への移植. 
* Python3.8.1 での重要な変更点: Python3 8 1 での重要な変更点. 
* Python3.8.2 での重要な変更点: Python3 8 2 での重要な変更点. 
* Notable changes in Python 3.8.3: Notable changes in Python 3 8 3. 
* Python3.8.8 での重要な変更点: Python3 8 8 での重要な変更点. 
* Notable changes in Python 3.8.9: Notable changes in Python 3 8 9. 
* Notable changes in Python 3.8.10: Notable changes in Python 3 8 10. 
* Notable changes in Python 3.8.10: Notable changes in Python 3 8 10<2>. 
* Notable changes in Python 3.8.12: Notable changes in Python 3 8 12. 
* Notable security feature in 3.8.14: Notable security feature in 3 8 14. 
* Notable changes in 3.8.17: Notable changes in 3 8 17. 

@end menu

@node 概要 -- リリースハイライト<7>,新しい機能<12>,,What's New In Python 3 8
@anchor{whatsnew/3 8 summary-release-highlights}@anchor{b95}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.8.
@c Brevity is key.

@c PEP-sized items next.

@node 新しい機能<12>,その他の言語変更<6>,概要 -- リリースハイライト<7>,What's New In Python 3 8
@anchor{whatsnew/3 8 new-features}@anchor{b96}
@subsection 新しい機能


@menu
* 代入式:: 
* 位置専用引数:: 
* コンパイル済みのバイトコードファイルのキャッシュを併存させるファイルシステム:: 
* デバッグビルドとリリースビルドのABI 共通化:: 
* f-string での = を用いたオブジェクトの表現:: 
* PEP 578; Pythonランタイムの監査フック: PEP 578 Pythonランタイムの監査フック. 
* PEP 587; Python 初期化設定: PEP 587 Python 初期化設定. 
* PEP 590; Vectorcall; a fast calling protocol for CPython: PEP 590 Vectorcall a fast calling protocol for CPython. 
* Pickle プロトコルバージョン 5 による帯域外データバッファ:: 

@end menu

@node 代入式,位置専用引数,,新しい機能<12>
@anchor{whatsnew/3 8 assignment-expressions}@anchor{b97}
@subsubsection 代入式


大きな構文の一部として、変数に値を割り当てる新しい構文 @code{:=} が追加されました。
この構文は セイウチの目と牙@footnote{https://en.wikipedia.org/wiki/Walrus#/media/File:Pacific_Walrus_-_Bull_(8247646168).jpg} に似ているため、「セイウチ演算子」の愛称で知られています。

以下の例では、代入式により @ref{840,,len()} 関数を二重に呼びだすことを回避しています:

@example
if (n := len(a)) > 10:
    print(f"List is too long (@{n@} elements, expected <= 10)")
@end example

同様の利点が、マッチがしたかどうかの判定とサブグループの取得とで2回マッチオブジェクトが必要になる、正規表現によるマッチでも、発揮されます:

@example
discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
    discount = float(mo.group(1)) / 100.0
@end example

この演算子は、生成した値をループ終了の判定とループ本体の両方で使用するような while 文においても、有用です:

@example
# Loop over fixed length blocks
while (block := f.read(256)) != '@w{'}:
    process(block)
@end example

動機となったもう 1 つのユースケースは、リスト内包表記においてフィルター条件の中で計算した値が式の本体でも必要になるところから出てきます:

@example
[clean_name.title() for name in names
 if (clean_name := normalize('NFC', name)) in allowed_names]
@end example

セイウチ演算子の使用は、複雑さを減らしたり可読性を向上させる綺麗なケースに限るよう努めてください。

完全な説明は 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/} を参照してください。

(Emily Morehouse の貢献による bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224})

@node 位置専用引数,コンパイル済みのバイトコードファイルのキャッシュを併存させるファイルシステム,代入式,新しい機能<12>
@anchor{whatsnew/3 8 positional-only-parameters}@anchor{b98}
@subsubsection 位置専用引数


There is a new function parameter syntax @code{/} to indicate that some
function parameters must be specified positionally and cannot be used as
keyword arguments.  This is the same notation shown by @code{help()} for C
functions annotated with Larry Hastings'
Argument Clinic@footnote{https://devguide.python.org/development-tools/clinic/} tool.

以下の例では、引数 `a' と `b' が位置専用、 `c' と `d' が位置引数でもキーワード引数でも可、`e' と `f' はキーワード引数専用です:

@example
def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)
@end example

以下は正しい関数呼び出しです:

@example
f(10, 20, 30, d=40, e=50, f=60)
@end example

一方、以下は不正です:

@example
f(10, b=20, c=30, d=40, e=50, f=60)   # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60)           # e must be a keyword argument
@end example

One use case for this notation is that it allows pure Python functions
to fully emulate behaviors of existing C coded functions.  For example,
the built-in @ref{b99,,divmod()} function does not accept keyword arguments:

@example
def divmod(a, b, /):
    "Emulate the built in divmod() function"
    return (a // b, a % b)
@end example

もう一つのユースケースは、引数名が有用ではない場合にキーワード引数としての利用を排除することです。例えば組み込み関数 @ref{840,,len()} は @code{len(obj, /)} というシグニチャです。これにより、以下のようなぎこちない呼び出しが排除されます:

@example
len(obj='hello')  # The "obj" keyword argument impairs readability
@end example

引数を位置専用とすることは、のちに引数名を変更する際に呼び出し側のコードを壊してしまう心配がないという利点があります。例えば、@ref{d7,,statistics} モジュールでは、`dist' という引数名が将来変更される可能性があります。これは、関数が以下のような定義だからこそ可能なことです:

@example
def quantiles(dist, /, *, n=4, method='exclusive')
    ...
@end example

Since the parameters to the left of @code{/} are not exposed as possible
keywords, the parameters names remain available for use in @code{**kwargs}:

@example
>>> def f(a, b, /, **kwargs):
...     print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 @{'a': 1, 'b': 2, 'c': 3@}
@end example

これにより、任意のキーワード引数を受け取る関数やメソッドを定義するのが、ぐんとシンプルになります。例えば、これは @ref{1e,,collections} モジュールから抜き出したコードです：

@example
class Counter(dict):

    def __init__(self, iterable=None, /, **kwds):
        # Note "iterable" is a possible keyword argument
@end example

詳細は 
@geindex Python Enhancement Proposals; PEP 570
PEP 570@footnote{https://peps.python.org/pep-0570/} を参照してください。

(Pablo Galindo の貢献による bpo-36540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36540}。)

@c TODO: Pablo will sprint on docs at PyCon US 2019.

@node コンパイル済みのバイトコードファイルのキャッシュを併存させるファイルシステム,デバッグビルドとリリースビルドのABI 共通化,位置専用引数,新しい機能<12>
@anchor{whatsnew/3 8 parallel-filesystem-cache-for-compiled-bytecode-files}@anchor{b9a}
@subsubsection コンパイル済みのバイトコードファイルのキャッシュを併存させるファイルシステム


暗黙のバイトコードキャッシュは、デフォルトでは各ソースコードのディレクトリ内の @code{__pycache__} サブディレクトリを使用しますが、新たに追加された環境変数 
@geindex PYTHONPYCACHEPREFIX
@geindex 環境変数; PYTHONPYCACHEPREFIX
@ref{b9b,,PYTHONPYCACHEPREFIX} （またはコマンドラインオプション @ref{16f,,-X} @code{pycache_prefix}) を指定すると、ソースコードと分離されたディレクトリツリーに格納されるようになります。

キャッシュの場所は @ref{b9c,,sys.pycache_prefix} で参照できます（@code{__pycache__} を使用する場合は @ref{885,,None} になります）。

（Carl Meyer の貢献による bpo-33499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33499}）

@node デバッグビルドとリリースビルドのABI 共通化,f-string での = を用いたオブジェクトの表現,コンパイル済みのバイトコードファイルのキャッシュを併存させるファイルシステム,新しい機能<12>
@anchor{whatsnew/3 8 debug-build-uses-the-same-abi-as-release-build}@anchor{b9d}
@subsubsection デバッグビルドとリリースビルドのABI 共通化


Python はリリースモード、デバッグモード両方のビルドにおいて、同じABI を用いるようになりました。Unix において、Python がデバッグモードでビルドされている場合、リリースモードで、あるいは安定ABI を用いて、ビルドされたC拡張モジュールを読み込むことができます。

Release builds and @ref{509,,debug builds} are now ABI compatible: defining the
@code{Py_DEBUG} macro no longer implies the @code{Py_TRACE_REFS} macro, which
introduces the only ABI incompatibility. The @code{Py_TRACE_REFS} macro, which
adds the @ref{28e,,sys.getobjects()} function and the 
@geindex PYTHONDUMPREFS
@geindex 環境変数; PYTHONDUMPREFS
@ref{b9e,,PYTHONDUMPREFS}
environment variable, can be set using the new @ref{636,,./configure --with-trace-refs} build option.
(Contributed by Victor Stinner in bpo-36465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36465}.)

Unix  においては、Android とCygwin  を除き、C拡張モジュールはlibpython にリンクされなくなりました。静的リンクされたPython は、Python 共有ライブラリを用いてビルドされたC拡張モジュールを読み込めます。(Victor Stinner の貢献による bpo-21536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21536}.)

Unix において、Python がデバッグモードでビルドされている場合、インポートは、リリースモードで、あるいは安定ABI を用いて、ビルドされたC拡張モジュールを探すようになりました。(Victor Stinner の貢献による bpo-36722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36722}.)

Python をアプリケーション内に組み込むためには、新しい @code{--embed} オプションを有効にして @code{python3-config --libs --embed} とすると、 @code{-lpython3.8} を有効にできます。(アプリケーションがlibpython にリンクされます) Python3.8 以前との互換性を保つためには、 @code{python3-config --libs --embed} をまず試みてから、失敗した場合 @code{python3-config --libs} (@code{--embed} なし) にフォールバックしてください。

Python をアプリケーションに組み込むために、@code{python-3.8-embed} pkg-config モジュールが追加されました: @code{pkg-config python-3.8-embed --libs} の出力は、@code{-lpython3.8} を含みます。 Python3.8 以前との互換性を保つためには、@code{pkg-config python-X.Y-embed --libs} をまず試みてから、失敗した場合 @code{pkg-config python-X.Y --libs} (@code{--embed} なし) にフォールバックしてください。(@code{X.Y} を使用するPython のバージョンに置き換えてください)

一方で、@code{pkg-config python3.8 --libs} は出力に @code{-lpython3.8} を含まなくなりました。C拡張モジュールは、libpython にリンクされるべきではありません。 (スクリプトによって処理される、Android とCygwin を除く) この変更では、意図的に後方互換性をなくしています。(Victor Stinner の貢献による bpo-36721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36721})

@node f-string での = を用いたオブジェクトの表現,PEP 578 Pythonランタイムの監査フック,デバッグビルドとリリースビルドのABI 共通化,新しい機能<12>
@anchor{whatsnew/3 8 bpo-36817-whatsnew}@anchor{b9f}@anchor{whatsnew/3 8 f-strings-support-for-self-documenting-expressions-and-debugging}@anchor{ba0}
@subsubsection `f-string' での @code{=} を用いたオブジェクトの表現


フォーマット済み文字列リテラル(@ref{66b,,f-string}) において @code{=} 指定子が有効になりました。@code{f'@{expr=@}'} のようなf-string は、f-string に書かれた式、イコール記号、式を評価されたものの文字列表現、の順で表示されます。例えば:

@example
>>> user = 'eric_idle'
>>> member_since = date(1975, 7, 31)
>>> f'@{user=@} @{member_since=@}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"
@end example

通常の @ref{19a,,f-string 書式指定子} を用いると、より柔軟に式の結果の表示方法を変えられます:

@example
>>> delta = date.today() - member_since
>>> f'@{user=!s@}  @{delta.days=:,d@}'
'user=eric_idle  delta.days=16,075'
@end example

@code{=} 指定子は式すべてを表示するので、次のような計算も表示できます:

@example
>>> print(f'@{theta=@}  @{cos(radians(theta))=:.3f@}')
theta=30  cos(radians(theta))=0.866
@end example

(Eric V. Smith, Larry Hastings の貢献による bpo-36817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36817})

@node PEP 578 Pythonランタイムの監査フック,PEP 587 Python 初期化設定,f-string での = を用いたオブジェクトの表現,新しい機能<12>
@anchor{whatsnew/3 8 pep-578-python-runtime-audit-hooks}@anchor{ba1}
@subsubsection PEP 578: Pythonランタイムの監査フック


このPEP は、監査用フックと信頼された Open のためのフックを追加します。これらは Python およびネイティブコードから利用できます。純粋に Python で書かれたフレームワークやアプリケーションはコードに関する追加情報を得ることができ、システム管理者や埋め込みでの利用者は Python のビルドを常に監査が有効な状態で利用できます。

詳細は 
@geindex Python Enhancement Proposals; PEP 578
PEP 578@footnote{https://peps.python.org/pep-0578/} を参照してください。

@node PEP 587 Python 初期化設定,PEP 590 Vectorcall a fast calling protocol for CPython,PEP 578 Pythonランタイムの監査フック,新しい機能<12>
@anchor{whatsnew/3 8 pep-587-python-initialization-configuration}@anchor{ba2}
@subsubsection PEP 587: Python 初期化設定


@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/} による C API  の改善により、Python 初期化時に、すべての初期化設定に対するより良い制御と改善されたエラー報告が得られます。

新たな構造体:


@itemize *

@item 
@ref{3f7,,PyConfig}

@item 
@ref{ba3,,PyPreConfig}

@item 
@ref{ba4,,PyStatus}

@item 
@ref{ba5,,PyWideStringList}
@end itemize

新たな関数:


@itemize *

@item 
@ref{ba6,,PyConfig_Clear()}

@item 
@ref{ba7,,PyConfig_InitIsolatedConfig()}

@item 
@ref{ba8,,PyConfig_InitPythonConfig()}

@item 
@ref{993,,PyConfig_Read()}

@item 
@ref{ba9,,PyConfig_SetArgv()}

@item 
@ref{baa,,PyConfig_SetBytesArgv()}

@item 
@ref{bab,,PyConfig_SetBytesString()}

@item 
@ref{bac,,PyConfig_SetString()}

@item 
@ref{bad,,PyPreConfig_InitIsolatedConfig()}

@item 
@ref{bae,,PyPreConfig_InitPythonConfig()}

@item 
@ref{baf,,PyStatus_Error()}

@item 
@ref{bb0,,PyStatus_Exception()}

@item 
@ref{bb1,,PyStatus_Exit()}

@item 
@ref{bb2,,PyStatus_IsError()}

@item 
@ref{bb3,,PyStatus_IsExit()}

@item 
@ref{bb4,,PyStatus_NoMemory()}

@item 
@ref{bb5,,PyStatus_Ok()}

@item 
@ref{bb6,,PyWideStringList_Append()}

@item 
@ref{bb7,,PyWideStringList_Insert()}

@item 
@ref{bb8,,Py_BytesMain()}

@item 
@ref{bb9,,Py_ExitStatusException()}

@item 
@ref{3f6,,Py_InitializeFromConfig()}

@item 
@ref{41e,,Py_PreInitialize()}

@item 
@ref{bba,,Py_PreInitializeFromArgs()}

@item 
@ref{bbb,,Py_PreInitializeFromBytesArgs()}

@item 
@ref{bbc,,Py_RunMain()}
@end itemize

このPEP は、@code{_PyRuntimeState.preconfig} (@ref{ba3,,PyPreConfig} 型) と @code{PyInterpreterState.config} (@ref{3f7,,PyConfig} 型) を内部構造体に加えます。@code{PyInterpreterState.config} は新たな参照設定となり、グローバル設定や他の内部変数を置き換えます。

@ref{646,,Python 初期化設定} も参照してください。

詳細は 
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/} を参照してください。

(Victor Stinner の貢献による bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763})

@node PEP 590 Vectorcall a fast calling protocol for CPython,Pickle プロトコルバージョン 5 による帯域外データバッファ,PEP 587 Python 初期化設定,新しい機能<12>
@anchor{whatsnew/3 8 pep-590-vectorcall-a-fast-calling-protocol-for-cpython}@anchor{bbd}
@subsubsection PEP 590: Vectorcall: a fast calling protocol for CPython


@ref{774,,The Vectorcall Protocol} is added to the Python/C API.
It is meant to formalize existing optimizations which were already done
for various classes.
Any @ref{983,,static type} implementing a callable can use this
protocol.

これは現在、暫定版です。Python3.9 から公開で使われることを目ざしています。

詳細は 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} を参照してください。

(Contributed by Jeroen Demeyer, Mark Shannon and Petr Viktorin in bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}.)

@node Pickle プロトコルバージョン 5 による帯域外データバッファ,,PEP 590 Vectorcall a fast calling protocol for CPython,新しい機能<12>
@anchor{whatsnew/3 8 pickle-protocol-5-with-out-of-band-data-buffers}@anchor{bbe}
@subsubsection Pickle プロトコルバージョン 5 による帯域外データバッファ


@ref{ab,,pickle} モジュールが Python のプロセス間での大容量データ転送でマルチコアないしマルチマシンでの利点を得るためには、メモリコピーの削減のほか、データ種別に応じた圧縮などの個別に合わせた最適化が重要です。

@ref{ab,,pickle} プロトコルバージョン5 は、
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} 互換であるようなデータが、メインのpickle ストリームとは別の独立した通信レイヤで転送されるような、帯域外バッファを提供します。

詳細は 
@geindex Python Enhancement Proposals; PEP 574
PEP 574@footnote{https://peps.python.org/pep-0574/} を参照してください。

(Antoine Pitrou の貢献による bpo-36785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36785})

@node その他の言語変更<6>,新たなモジュール<6>,新しい機能<12>,What's New In Python 3 8
@anchor{whatsnew/3 8 other-language-changes}@anchor{bbf}
@subsection その他の言語変更



@itemize *

@item 
実装上の問題により、@ref{1b0,,finally} 節での @ref{180,,continue} 文は不正でした。Python3.8 では、この制限は取り除かれています。
(Serhiy Storchaka の貢献による bpo-32489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32489})

@item 
@ref{3c3,,bool}, @ref{19b,,int}, @ref{213,,fractions.Fraction} タイプは、@ref{196,,float} や @ref{1fe,,decimal.Decimal} と同様の @ref{bc0,,as_integer_ratio()} メソッドを持つようになりました。このAPI の拡張によって、@code{numerator, denominator = x.as_integer_ratio()} のようなコードがより多くの数値型で動作します。
(Lisa Roach の貢献による bpo-33073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33073} および Raymond Hettinger の貢献による bpo-37819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37819})

@item 
@ref{19b,,int}, @ref{196,,float}, @ref{197,,complex} のコンストラクタは、可能ならば @ref{19e,,__index__()} 特殊メソッドを利用し、その場合は対応する @ref{19d,,__int__()}, @ref{bc1,,__float__()} や @ref{7fd,,__complex__()} は使用できません。(Serhiy Storchaka の貢献による bpo-20092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20092})

@item 
Added support of @code{\N@{@var{name}@}} escapes in @ref{be,,regular expressions}:

@example
>>> notice = 'Copyright © 2019'
>>> copyright_year_pattern = re.compile(r'\N@{copyright sign@}\s*(\d@{4@})')
>>> int(copyright_year_pattern.search(notice).group(1))
2019
@end example

(Jonathan Eunice, Serhiy Storchaka の貢献による bpo-30688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30688})

@item 
dict と dictview は、@ref{a65,,reversed()} を使って逆順でイテレートすることが可能になりました。(Rémi Lapeyre の貢献による bpo-33462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33462})

@item 
関数内でのキーワード名に関する構文の制限が強化されました。具体的には、@code{f((keyword)=arg)} の表現が許容されなくなりました。キーワード引数への代入の際、左側にキーワードそのまま以外の表現を許可する意図は、以前からありませんでした。
(Benjamin Peterson の貢献による bpo-34641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34641})

@item 
@ref{bc2,,yield} 文と @ref{1af,,return} 文における一般化されたイテラブルへの展開のために、全体を覆うかっこが不要になりました。これは `yield' と `return' の表現を、一般の展開と同様のわかりやすい形式にします:

@example
>>> def parse(family):
...     lastname, *members = family.split()
...     return lastname.upper(), *members
...
>>> parse('simpsons homer marge bart lisa maggie')
('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')
@end example

(David Cuthbert, Jordan Chapman の貢献による bpo-32117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32117})

@item 
@code{[(10, 20) (30, 40)]} のようなコードでコンマが無い場合、コンパイラは @ref{1ae,,SyntaxWarning} を、分かりやすい形式で表示します。これで、最初のタプルが呼び出し可能ではないことを @ref{198,,TypeError} で表示するよりもわかりやすくなります。(Serhiy Storchaka の貢献による bpo-15248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15248})

@item 
@ref{1fa,,datetime.date}, @ref{4e2,,datetime.datetime}, @ref{bc3,,datetime.timedelta} オブジェクトのサブクラス間の算術演算は、基底クラスではなくサブクラスのインスタンスを返すようになりました。この変更は、@ref{bc4,,astimezone()} のような、@ref{bc3,,datetime.timedelta} に対する算術演算を直接ないし間接的に使用する実装の戻り値の型に影響します。(Paul Ganssle の貢献による bpo-32417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32417})

@item 
Python インタープリタがCtrl-C (SIGINT) によって中断され、@ref{bc5,,KeyboardInterrupt} 例外の結果が捕捉されなかった場合、Python プロセスはSIGINT シグナルか、呼び出したプロセスが、Ctrl-C  によって終了したことを判別できるような適切な終了コードで終了するようになりました。　POSIX とWindows 上のシェルは、非対話セッション内でスクリプトの終了処理を適切に行うために、これを利用できます。(Gregory P. Smith を通してGoogle の貢献による bpo-1054041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1054041})

@item 
先進的なプログラミングにおいて、既存の関数の @ref{32f,,types.CodeType} オブジェクトを更新する必要が生じます。code オブジェクトはイミュータブルなので、既存のオブジェクトがあるにもかかわらず、新しい code オブジェクトを生成する必要がありました。パラメータが19もあるので、一から作成するのは非合理的です。新しい @code{replace()} メソッドを使えば、更新すべきパラメータを書くだけで、新しいクローンを作成することができます。

ここでは、@ref{8e1,,statistics.mean()} 関数がキーワード引数として `data' を使えないように変更する例を見てみましょう:

@example
>>> from statistics import mean
>>> mean(data=[10, 20, 90])
40
>>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)
>>> mean(data=[10, 20, 90])
Traceback (most recent call last):
  ...
TypeError: mean() got some positional-only arguments passed as keyword arguments: 'data'
@end example

(Victor Stinner の貢献による bpo-37032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37032})

@item 
For integers, the three-argument form of the @ref{1a4,,pow()} function now
permits the exponent to be negative in the case where the base is
relatively prime to the modulus. It then computes a modular inverse to
the base when the exponent is @code{-1}, and a suitable power of that
inverse for other negative exponents.  For example, to compute the
modular multiplicative inverse@footnote{https://en.wikipedia.org/wiki/Modular_multiplicative_inverse} of 38
modulo 137, write:

@example
>>> pow(38, -1, 137)
119
>>> 119 * 38 % 137
1
@end example

Modular inverses arise in the solution of linear Diophantine equations@footnote{https://en.wikipedia.org/wiki/Diophantine_equation}.
For example, to find integer solutions for @code{4258𝑥 + 147𝑦 = 369},
first rewrite as @code{4258𝑥 ≡ 369 (mod 147)} then solve:

@example
>>> x = 369 * pow(4258, -1, 147) % 147
>>> y = (4258 * x - 369) // -147
>>> 4258 * x + 147 * y
369
@end example

(Mark Dickinson の貢献による bpo-36027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36027})

@item 
辞書内包表現は辞書リテラルと同期されたため、まずキーが解釈され、次に値が解釈されます:

@example
>>> # Dict comprehension
>>> cast = @{input('role? '): input('actor? ') for i in range(2)@}
role? King Arthur
actor? Chapman
role? Black Knight
actor? Cleese

>>> # Dict literal
>>> cast = @{input('role? '): input('actor? ')@}
role? Sir Robin
actor? Eric Idle
@end example

この実行順の保証は代入式の役に立ち、キーの表現で代入されたものは、値の表現で使用することができます:

@example
>>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']
>>> @{(n := normalize('NFC', name)).casefold() : n for name in names@}
@{'martin von löwis': 'Martin von Löwis',
 'łukasz langa': 'Łukasz Langa',
 'walter dörwald': 'Walter Dörwald'@}
@end example

(Jörn Heissler の貢献による bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224})

@item 
The @ref{bc6,,object.__reduce__()} method can now return a tuple from two to
six elements long. Formerly, five was the limit.  The new, optional sixth
element is a callable with a @code{(obj, state)} signature.  This allows the
direct control over the state-updating behavior of a specific object.  If
not `None', this callable will have priority over the object's
@ref{bc7,,__setstate__()} method.
(Contributed by Pierre Glaser and Olivier Grisel in bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900}.)
@end itemize

@node 新たなモジュール<6>,改良されたモジュール<6>,その他の言語変更<6>,What's New In Python 3 8
@anchor{whatsnew/3 8 new-modules}@anchor{bc8}
@subsection 新たなモジュール



@itemize *

@item 
新しい @ref{7e,,importlib.metadata} モジュールは、サードパーティパッケージからのメタデータ読み込みをサポートします。これは暫定版です。例えば、インストールされたパッケージのバージョンを得たり、エントリーポイントの一覧を得たりできます:

@example
>>> # Note following example requires that the popular "requests"
>>> # package has been installed.
>>>
>>> from importlib.metadata import version, requires, files
>>> version('requests')
'2.22.0'
>>> list(requires('requests'))
['chardet (<3.1.0,>=3.0.2)']
>>> list(files('requests'))[:5]
[PackagePath('requests-2.22.0.dist-info/INSTALLER'),
 PackagePath('requests-2.22.0.dist-info/LICENSE'),
 PackagePath('requests-2.22.0.dist-info/METADATA'),
 PackagePath('requests-2.22.0.dist-info/RECORD'),
 PackagePath('requests-2.22.0.dist-info/WHEEL')]
@end example

(Barry Warsaw, Jason R. Coombs の貢献による bpo-34632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34632})
@end itemize

@node 改良されたモジュール<6>,最適化<7>,新たなモジュール<6>,What's New In Python 3 8
@anchor{whatsnew/3 8 improved-modules}@anchor{bc9}
@subsection 改良されたモジュール


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

@end menu

@node ast<5>,asyncio<9>,,改良されたモジュール<6>
@anchor{whatsnew/3 8 ast}@anchor{bca}
@subsubsection ast


AST ノードは @code{end_lineno} と @code{end_col_offset} の属性を持つようになりました。これは、正確なノードの終端位置を提供します。(これは、@code{lineno} と @code{col_offset} の属性を持つノードにのみ有効です)

新しい @ref{bcb,,ast.get_source_segment()} 関数は、特定の AST ノードのソースコードを返します。

(Ivan Levkivskyi の貢献による bpo-33416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33416})

@ref{1c2,,ast.parse()} 関数の新しいフラグが有効になりました:


@itemize *

@item 
@code{type_comments=True} は、そのAST ノードに関連する、
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} と 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} に規定されるような型コメントを返します;

@item 
@code{mode='func_type'} can be used to parse 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} "signature type
comments" (returned for function definition AST nodes);

@item 
@code{feature_version=(3, N)} を使うと、以前の Python 3 バージョンを指定できます。例えば、@code{feature_version=(3, 4)} とすると、@ref{93b,,async} と @ref{18d,,await} キーワードは、予約語ではないとして扱われます。
@end itemize

(Guido van Rossum の貢献による bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766})

@node asyncio<9>,builtins<2>,ast<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 asyncio}@anchor{bcc}
@subsubsection asyncio


@ref{2f3,,asyncio.run()} は暫定から安定API に移動しました。この関数は @ref{6b9,,coroutine} の実行と、イベントループを管理しながら自動的に結果を返すことに使用できます。例えば:

@example
import asyncio

async def main():
    await asyncio.sleep(0)
    return 42

asyncio.run(main())
@end example

これは、だいたい次と等価です

@example
import asyncio

async def main():
    await asyncio.sleep(0)
    return 42

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    asyncio.set_event_loop(None)
    loop.close()
@end example

実装はこれよりもずっと複雑なものになっています。ですが、 @ref{2f3,,asyncio.run()} は非同期IOプログラムを動かす際にまず選ぶべき選択肢です。

(Yury Selivanov の貢献による bpo-32314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32314})

@code{python -m asyncio} を実行すると、ネイティブ async 対話型インタプリタが起動します。高水準キーワード @ref{18d,,await} を使うコードの試験を簡単に行えます。すべての呼び出しに対して新しいイベントループを作る @code{asyncio.run()} を呼び出す必要はありません:

@example
$ python -m asyncio
asyncio REPL 3.8.0
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> await asyncio.sleep(10, result='hello')
hello
@end example

(Yury Selivanov の貢献による bpo-37028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37028})

The exception @ref{4d4,,asyncio.CancelledError} now inherits from
@ref{7d6,,BaseException} rather than @ref{bcd,,Exception} and no longer inherits
from @ref{bce,,concurrent.futures.CancelledError}.
(Contributed by Yury Selivanov in bpo-32528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32528}.)

Windows では、イベントループのデフォルトが @ref{81d,,ProactorEventLoop} になりました。(Victor Stinner の貢献による bpo-34687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34687})

@ref{81d,,ProactorEventLoop} はUDP もサポートするようになりました。(Adam Meily, Andrew Svetlov の貢献による bpo-29883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29883})

@ref{81d,,ProactorEventLoop} は @ref{bc5,,KeyboardInterrupt} ("CTRL+C") によって中断できるようになりました。(Vladimir Matveev の貢献による bpo-23057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23057})

@ref{1c7,,asyncio.Task} 内で、内包されたコルーチンを得られる @ref{bcf,,asyncio.Task.get_coro()} メソッドが追加されました。(Alex Grönholm の貢献による bpo-36999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36999})

@ref{1c9,,asyncio.create_task()} 関数か @ref{1ca,,create_task()} の @code{name} 引数を指定するか、もしくはタスクに対して @ref{bd0,,set_name()} メソッドを呼ぶことによって、asyncio タスクに名前をつけることができます。タスクの名前は、@ref{1c7,,asyncio.Task} の @code{repr()} 出力で、または @ref{bd1,,get_name()} メソッドで確認することができます。(Alex Grönholm の貢献による bpo-34270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34270})

@ref{818,,asyncio.loop.create_connection()} は、Happy Eyeballs@footnote{https://en.wikipedia.org/wiki/Happy_Eyeballs} をサポートするようになりました。挙動を定義するため、2つの新しいパラメータ: `happy_eyeballs_delay' と `interleave' が加えられます。Happy Eyeballs アルゴリズムは、アプリケーションが IPv4 と IPv6 をサポートする場合、その両方を使って接続を保つことによって、アプリケーションの応答性を向上させます。(twisteroid ambassador の貢献による bpo-33530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33530})

@node builtins<2>,collections,asyncio<9>,改良されたモジュール<6>
@anchor{whatsnew/3 8 builtins}@anchor{bd2}
@subsubsection builtins


組み込み関数 @ref{4b1,,compile()} が、@code{ast.PyCF_ALLOW_TOP_LEVEL_AWAIT} フラグを受け取るようになりました。このフラグが有効である場合、@ref{4b1,,compile()} は、一般には有効な公文ではない、トップレベルの @code{await}, @code{async for}, @code{async with} 構文が有効になります。この場合、@code{CO_COROUTINE} フラグを持つ非同期コードオブジェクトが返されるでしょう。(Matthias Bussonnier の貢献による bpo-34616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34616})

@node collections,cProfile,builtins<2>,改良されたモジュール<6>
@anchor{whatsnew/3 8 collections}@anchor{bd3}
@subsubsection collections


@ref{4e0,,collections.namedtuple()} の @ref{bd4,,_asdict()} メソッドは、@ref{7f3,,collections.OrderedDict} ではなく @ref{183,,dict} を返すようになりました。Python 3.7 からは一般に辞書の順番が保証されるため、このような変更が可能です。@code{OrderedDict} 特有の機能を使いたい場合は、結果を @code{OrderedDict(nt._asdict())} 型にキャストして使用することを推奨します。(Raymond Hettinger の貢献による bpo-35864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35864})

@node cProfile,csv<2>,collections,改良されたモジュール<6>
@anchor{whatsnew/3 8 cprofile}@anchor{bd5}
@subsubsection cProfile


@ref{bd6,,cProfile.Profile} クラスは、コンテキストマネージャとして使用できるようになりました。このようにしてコードブロックをプロファイルします:

@example
import cProfile

with cProfile.Profile() as profiler:
      # code to be profiled
      ...
@end example

(Scott Sanderson の貢献による bpo-29235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29235})

@node csv<2>,curses<4>,cProfile,改良されたモジュール<6>
@anchor{whatsnew/3 8 csv}@anchor{bd7}
@subsubsection csv


@ref{bd8,,csv.DictReader} は、@ref{7f3,,collections.OrderedDict} ではなく @ref{183,,dict} のインスタンスを返すようになりました。この変更によって、順序を保ちながら、より高速にかつメモリの使用量を減らして実行できます。(Michael Selik の貢献による bpo-34003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34003})

@node curses<4>,ctypes<3>,csv<2>,改良されたモジュール<6>
@anchor{whatsnew/3 8 curses}@anchor{bd9}
@subsubsection curses


ncurses ライブラリの、構造化されたバージョン情報を保持する変数を追加しました: @ref{bda,,ncurses_version}　 (Serhiy Storchaka の貢献による bpo-31680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31680})

@node ctypes<3>,datetime<4>,curses<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 ctypes}
@subsubsection ctypes


Windows では、@ref{bdc,,CDLL} とそのサブクラスが `winmode' 引数を受け取り、根底の @code{LoadLibraryEx} 呼び出しのフラグを指定できるようになりました。デフォルトでは、フラグは (フルパスか部分パスが初期DLL を読み込むのに使われていた場合) そのDLL が保存されている場所を含んだ信頼済みの場所と、@ref{bdd,,add_dll_directory()} によって加えられた場所からのみ、DLL を読み込むようになっています。(Steve Dower の貢献による bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085})

@node datetime<4>,functools<3>,ctypes<3>,改良されたモジュール<6>
@anchor{whatsnew/3 8 datetime}@anchor{bde}
@subsubsection datetime


Added new alternate constructors @ref{bdf,,datetime.date.fromisocalendar()} and
@ref{be0,,datetime.datetime.fromisocalendar()}, which construct @ref{1fa,,date} and
@ref{4e2,,datetime} objects respectively from ISO year, week number, and weekday;
these are the inverse of each class's @code{isocalendar} method.
(Contributed by Paul Ganssle in bpo-36004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36004}.)

@node functools<3>,gc<4>,datetime<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 functools}@anchor{be1}
@subsubsection functools


@ref{be2,,functools.lru_cache()} は、デコレータを返す関数としての使い方に加えて、デコレータそのものとしても使えるようになりました。両方の使い方ができます:

@example
@@lru_cache
def f(x):
    ...

@@lru_cache(maxsize=256)
def f(x):
    ...
@end example

(Raymond Hettinger の貢献による bpo-36772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36772})

インスタンスが存在する間、計算型プロパティをキャッシュする @ref{763,,functools.cached_property()} デコレータが追加されました:

@example
import functools
import statistics

class Dataset:
   def __init__(self, sequence_of_numbers):
      self.data = sequence_of_numbers

   @@functools.cached_property
   def variance(self):
      return statistics.variance(self.data)
@end example

(Carl Meyer の貢献による bpo-21145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21145})

@ref{be3,,single dispatch} を利用して、メソッドを @ref{be4,,ジェネリック関数} に変換する @ref{be5,,functools.singledispatchmethod()} デコレータが追加されました:

@example
from functools import singledispatchmethod
from contextlib import suppress

class TaskManager:

    def __init__(self, tasks):
        self.tasks = list(tasks)

    @@singledispatchmethod
    def discard(self, value):
        with suppress(ValueError):
            self.tasks.remove(value)

    @@discard.register(list)
    def _(self, tasks):
        targets = set(tasks)
        self.tasks = [x for x in self.tasks if x not in targets]
@end example

(Ethan Smith の貢献による bpo-32380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32380})

@node gc<4>,gettext,functools<3>,改良されたモジュール<6>
@anchor{whatsnew/3 8 gc}@anchor{be6}
@subsubsection gc


@ref{a04,,get_objects()} は、オブジェクトを得る世代を指定するオプションのパラメータ引数 `generation' を受け取るようになりました。(Pablo Galindo の貢献による bpo-36016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36016})

@node gettext,gzip<3>,gc<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 gettext}@anchor{be7}
@subsubsection gettext


@ref{be8,,pgettext()} を含む、類似のいくつかの関数が追加されました。 (Franz Glasner, Éric Araujo, Cheryl Sabella の貢献による bpo-2504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2504})

@node gzip<3>,IDLE と idelelib<4>,gettext,改良されたモジュール<6>
@anchor{whatsnew/3 8 gzip}@anchor{be9}
@subsubsection gzip


出力の再現性のために、@ref{84e,,gzip.compress()} に `mtime' パラメータが追加されました。 (Guo Ci Teo の貢献による bpo-34898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34898})

不正な、あるいは破損した gzip ファイルのうち、所定の種類のものについて、@ref{2c0,,OSError} にかわって @ref{bea,,BadGzipFile}  例外が送出されるようになりました。(Filip Gruszczyński, Michele Orrù, Zackery Spytz の貢献による bpo-6584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6584})

@node IDLE と idelelib<4>,inspect<6>,gzip<3>,改良されたモジュール<6>
@anchor{whatsnew/3 8 idle-and-idlelib}@anchor{beb}
@subsubsection IDLE と idelelib


Output over N lines (50 by default) is squeezed down to a button.
N can be changed in the PyShell section of the General page of the
Settings dialog.  Fewer, but possibly extra long, lines can be squeezed by
right clicking on the output.  Squeezed output can be expanded in place
by double-clicking the button or into the clipboard or a separate window
by right-clicking the button.  (Contributed by Tal Einat in bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353}.)

Add "Run Customized" to the Run menu to run a module with customized
settings. Any command line arguments entered are added to sys.argv.
They also re-appear in the box for the next customized run.  One can also
suppress the normal Shell main module restart.  (Contributed by Cheryl
Sabella, Terry Jan Reedy, and others in bpo-5680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5680} and bpo-37627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37627}.)

Added optional line numbers for IDLE editor windows. Windows
open without line numbers unless set otherwise in the General
tab of the configuration dialog.  Line numbers for an existing
window are shown and hidden in the Options menu.
(Contributed by Tal Einat and Saimadhav Heblikar in bpo-17535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17535}.)

OS native encoding is now used for converting between Python strings and Tcl
objects. This allows IDLE to work with emoji and other non-BMP characters.
These characters can be displayed or copied and pasted to or from the
clipboard.  Converting strings from Tcl to Python and back now never fails.
(Many people worked on this for eight years but the problem was finally
solved by Serhiy Storchaka in bpo-13153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13153}.)

New in 3.8.1:

Add option to toggle cursor blink off.  (Contributed by Zackery Spytz
in bpo-4603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4603}.)

Escape key now closes IDLE completion windows.  (Contributed by Johnny
Najera in bpo-38944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38944}.)

上で挙げた変更は 3.7 のメンテナンスリリースにバックポートされました。

Add keywords to module name completion list.  (Contributed by Terry J.
Reedy in bpo-37765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37765}.)

@node inspect<6>,io<5>,IDLE と idelelib<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 inspect}@anchor{bec}
@subsubsection inspect


@ref{bed,,inspect.getdoc()} 関数は、@code{__slots__} 属性に値が docstrings であるような @ref{183,,dict} がある場合、docstrings の内容を探索できるようになりました。これは、既に @ref{4b3,,property()}、@ref{48e,,classmethod()}、@ref{453,,staticmethod()} に現在あるような、ドキュメント生成の選択肢を提供します:

@example
class AudioClip:
    __slots__ = @{'bit_rate': 'expressed in kilohertz to one decimal place',
                 'duration': 'in seconds, rounded up to an integer'@}
    def __init__(self, bit_rate, duration):
        self.bit_rate = round(bit_rate / 1000.0, 1)
        self.duration = ceil(duration)
@end example

(Raymond Hettinger の貢献による bpo-36326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36326})

@node io<5>,itertools<5>,inspect<6>,改良されたモジュール<6>
@anchor{whatsnew/3 8 io}@anchor{bee}
@subsubsection io


In development mode (@ref{16f,,-X} @code{env}) and in @ref{509,,debug build}, the
@ref{505,,io.IOBase} finalizer now logs the exception if the @code{close()} method
fails. The exception is ignored silently by default in release build.
(Contributed by Victor Stinner in bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748}.)

@node itertools<5>,json tool,io<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 itertools}@anchor{bef}
@subsubsection itertools


@ref{bf0,,itertools.accumulate()} 関数に、初期値を定める、オプションの `initial' キーワード引数が追加されました:

@example
>>> from itertools import accumulate
>>> list(accumulate([10, 5, 30, 15], initial=1000))
[1000, 1010, 1015, 1045, 1060]
@end example

(Lisa Roach の貢献による bpo-34659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34659})

@node json tool,logging<2>,itertools<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 json-tool}@anchor{bf1}
@subsubsection json.tool


一行ごとに別々の JSON オブジェクトへ解析をする @code{--json-lines} オプションが追加されました。(Weipeng Hong の貢献による bpo-31553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31553})

@node logging<2>,math<6>,json tool,改良されたモジュール<6>
@anchor{whatsnew/3 8 logging}@anchor{bf2}
@subsubsection logging


Added a `force' keyword argument to @ref{bf3,,logging.basicConfig()}.
When set to true, any existing handlers attached
to the root logger are removed and closed before carrying out the
configuration specified by the other arguments.

This solves a long-standing problem.  Once a logger or `basicConfig()' had
been called, subsequent calls to `basicConfig()' were silently ignored.
This made it difficult to update, experiment with, or teach the various
logging configuration options using the interactive prompt or a Jupyter
notebook.

(Suggested by Raymond Hettinger, implemented by Donghee Na, and
reviewed by Vinay Sajip in bpo-33897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33897}.)

@node math<6>,mmap<2>,logging<2>,改良されたモジュール<6>
@anchor{whatsnew/3 8 math}@anchor{bf4}
@subsubsection math


二点間のユークリッド距離を計算する @ref{bf5,,math.dist()} 関数が追加されました。(Raymond Hettinger の貢献による bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089})

@ref{bf6,,math.hypot()} 関数は、3次元以上を扱えるように拡張されました。以前は、二次元の場合のみに対応していました。(Raymond Hettinger の貢献による bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089})

@ref{695,,sum()} に類似する関数として、初期値(デフォルトは1) に対してイテレート可能なオブジェクトの数を掛けていく @ref{bf7,,math.prod()} 関数が追加されました:

@example
>>> prior = 0.8
>>> likelihoods = [0.625, 0.84, 0.30]
>>> math.prod(likelihoods, start=prior)
0.126
@end example

(Pablo Galindo の貢献による bpo-35606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35606})

2つの組み合わせの関数 @ref{8e0,,math.perm()} と @ref{8df,,math.comb()} が追加されました:

@example
>>> math.perm(10, 3)    # Permutations of 10 things taken 3 at a time
720
>>> math.comb(10, 3)    # Combinations of 10 things taken 3 at a time
120
@end example

(Yash Aggarwal, Keller Fuchs, Serhiy Storchaka, Raymond Hettinger の貢献による bpo-37128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37128}, bpo-37178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37178}, bpo-35431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35431})

浮動小数点数を介することなく、正確な整数の二乗根を計算する関数 @ref{bf8,,math.isqrt()} が追加されました。この関数は、巨大な整数にも使用できます。@code{floor(sqrt(n))} より高速ですが、@ref{bf9,,math.sqrt()} より少し遅いです:

@example
>>> r = 650320427
>>> s = r ** 2
>>> isqrt(s - 1)         # correct
650320426
>>> floor(sqrt(s - 1))   # incorrect
650320427
@end example

(Mark Dickinson の貢献による bpo-36887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36887})

@ref{b41,,math.factorial()} 関数は、引数に int、またはそれに類似するもの以外を受け取らなくなりました。(Pablo Galindo の貢献による bpo-33083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33083})

@node mmap<2>,multiprocessing<4>,math<6>,改良されたモジュール<6>
@anchor{whatsnew/3 8 mmap}@anchor{bfa}
@subsubsection mmap


The @ref{519,,mmap.mmap} class now has an @ref{bfb,,madvise()} method to
access the @code{madvise()} system call.
(Contributed by Zackery Spytz in bpo-32941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32941}.)

@node multiprocessing<4>,os<7>,mmap<2>,改良されたモジュール<6>
@anchor{whatsnew/3 8 multiprocessing}@anchor{bfc}
@subsubsection multiprocessing


Added new @ref{9d,,multiprocessing.shared_memory} module.
(Contributed by Davin Potts in bpo-35813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35813}.)

On macOS, the `spawn' start method is now used by default.
(Contributed by Victor Stinner in bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725}.)

@node os<7>,os path<5>,multiprocessing<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 os}@anchor{bfd}
@subsubsection os


Added new function @ref{bdd,,add_dll_directory()} on Windows for providing
additional search paths for native dependencies when importing extension
modules or loading DLLs using @ref{2e,,ctypes}.
(Contributed by Steve Dower in bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085}.)

A new @ref{bfe,,os.memfd_create()} function was added to wrap the
@code{memfd_create()} syscall.
(Contributed by Zackery Spytz and Christian Heimes in bpo-26836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26836}.)

On Windows, much of the manual logic for handling reparse points (including
symlinks and directory junctions) has been delegated to the operating system.
Specifically, @ref{26d,,os.stat()} will now traverse anything supported by the
operating system, while @ref{6c8,,os.lstat()} will only open reparse points that
identify as "name surrogates" while others are opened as for @ref{26d,,os.stat()}.
In all cases, @ref{bff,,os.stat_result.st_mode} will only have @code{S_IFLNK} set for
symbolic links and not other kinds of reparse points. To identify other kinds
of reparse point, check the new @ref{c00,,os.stat_result.st_reparse_tag} attribute.

On Windows, @ref{b1a,,os.readlink()} is now able to read directory junctions. Note
that @ref{c01,,islink()} will return @code{False} for directory junctions,
and so code that checks @code{islink} first will continue to treat junctions as
directories, while code that handles errors from @ref{b1a,,os.readlink()} may now
treat junctions as links.

(Contributed by Steve Dower in bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834}.)

@node os path<5>,pathlib<10>,os<7>,改良されたモジュール<6>
@anchor{whatsnew/3 8 os-path}@anchor{c02}
@subsubsection os.path


@ref{a6,,os.path} functions that return a boolean result like
@ref{c03,,exists()}, @ref{c04,,lexists()}, @ref{c05,,isdir()},
@ref{c06,,isfile()}, @ref{c01,,islink()}, and @ref{c07,,ismount()}
now return @code{False} instead of raising @ref{2ec,,ValueError} or its subclasses
@ref{887,,UnicodeEncodeError} and @ref{c08,,UnicodeDecodeError} for paths that contain
characters or bytes unrepresentable at the OS level.
(Contributed by Serhiy Storchaka in bpo-33721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33721}.)

@ref{c09,,expanduser()} on Windows now prefers the 
@geindex USERPROFILE
@geindex 環境変数; USERPROFILE
@code{USERPROFILE}
environment variable and does not use 
@geindex HOME
@geindex 環境変数; HOME
@code{HOME}, which is not normally set
for regular user accounts.
(Contributed by Anthony Sottile in bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264}.)

@ref{c05,,isdir()} on Windows no longer returns @code{True} for a link to a
non-existent directory.

@ref{262,,realpath()} on Windows now resolves reparse points, including
symlinks and directory junctions.

(Contributed by Steve Dower in bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834}.)

@node pathlib<10>,pickle<2>,os path<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 pathlib}@anchor{c0a}
@subsubsection pathlib


@ref{266,,pathlib.Path} methods that return a boolean result like
@ref{c0b,,exists()}, @ref{53a,,is_dir()},
@ref{539,,is_file()}, @ref{c0c,,is_mount()},
@ref{c0d,,is_symlink()}, @ref{c0e,,is_block_device()},
@ref{c0f,,is_char_device()}, @ref{c10,,is_fifo()},
@ref{c11,,is_socket()} now return @code{False} instead of raising
@ref{2ec,,ValueError} or its subclass @ref{887,,UnicodeEncodeError} for paths that
contain characters unrepresentable at the OS level.
(Contributed by Serhiy Storchaka in bpo-33721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33721}.)

Added @code{pathlib.Path.link_to()} which creates a hard link pointing
to a path.
(Contributed by Joannah Nanjekye in bpo-26978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26978})
Note that @code{link_to} was deprecated in 3.10 and removed in 3.12 in
favor of a @code{hardlink_to} method added in 3.10 which matches the
semantics of the existing @code{symlink_to} method.

@node pickle<2>,plistlib,pathlib<10>,改良されたモジュール<6>
@anchor{whatsnew/3 8 pickle}@anchor{c12}
@subsubsection pickle


@ref{ab,,pickle} extensions subclassing the C-optimized @ref{c13,,Pickler}
can now override the pickling logic of functions and classes by defining the
special @ref{c14,,reducer_override()} method.
(Contributed by Pierre Glaser and Olivier Grisel in bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900}.)

@node plistlib,pprint<3>,pickle<2>,改良されたモジュール<6>
@anchor{whatsnew/3 8 plistlib}@anchor{c15}
@subsubsection plistlib


Added new @ref{c16,,plistlib.UID} and enabled support for reading and writing
NSKeyedArchiver-encoded binary plists.
(Contributed by Jon Janzen in bpo-26707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26707}.)

@node pprint<3>,py_compile<2>,plistlib,改良されたモジュール<6>
@anchor{whatsnew/3 8 pprint}@anchor{c17}
@subsubsection pprint


The @ref{b3,,pprint} module added a `sort_dicts' parameter to several functions.
By default, those functions continue to sort dictionaries before rendering or
printing.  However, if `sort_dicts' is set to false, the dictionaries retain
the order that keys were inserted.  This can be useful for comparison to JSON
inputs during debugging.

In addition, there is a convenience new function, @ref{c18,,pprint.pp()} that is
like @ref{a29,,pprint.pprint()} but with `sort_dicts' defaulting to @code{False}:

@example
>>> from pprint import pprint, pp
>>> d = dict(source='input.txt', operation='filter', destination='output.txt')
>>> pp(d, width=40)                  # Original order
@{'source': 'input.txt',
 'operation': 'filter',
 'destination': 'output.txt'@}
>>> pprint(d, width=40)              # Keys sorted alphabetically
@{'destination': 'output.txt',
 'operation': 'filter',
 'source': 'input.txt'@}
@end example

(Contributed by Rémi Lapeyre in bpo-30670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30670}.)

@node py_compile<2>,shlex,pprint<3>,改良されたモジュール<6>
@anchor{whatsnew/3 8 py-compile}@anchor{c19}
@subsubsection py_compile


@ref{c1a,,py_compile.compile()} now supports silent mode.
(Contributed by Joannah Nanjekye in bpo-22640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22640}.)

@node shlex,shutil<4>,py_compile<2>,改良されたモジュール<6>
@anchor{whatsnew/3 8 shlex}@anchor{c1b}
@subsubsection shlex


The new @ref{c1c,,shlex.join()} function acts as the inverse of @ref{75e,,shlex.split()}.
(Contributed by Bo Bayles in bpo-32102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32102}.)

@node shutil<4>,socket<5>,shlex,改良されたモジュール<6>
@anchor{whatsnew/3 8 shutil}@anchor{c1d}
@subsubsection shutil


@ref{c1e,,shutil.copytree()} now accepts a new @code{dirs_exist_ok} keyword argument.
(Contributed by Josh Bronson in bpo-20849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20849}.)

@ref{6da,,shutil.make_archive()} now defaults to the modern pax (POSIX.1-2001)
format for new archives to improve portability and standards conformance,
inherited from the corresponding change to the @ref{e4,,tarfile} module.
(Contributed by C.A.M. Gerlach in bpo-30661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30661}.)

@ref{356,,shutil.rmtree()} on Windows now removes directory junctions without
recursively removing their contents first.
(Contributed by Steve Dower in bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834}.)

@node socket<5>,ssl<5>,shutil<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 socket}@anchor{c1f}
@subsubsection socket


Added @ref{c20,,create_server()} and @ref{c21,,has_dualstack_ipv6()}
convenience functions to automate the necessary tasks usually involved when
creating a server socket, including accepting both IPv4 and IPv6 connections
on the same socket.  (Contributed by Giampaolo Rodolà in bpo-17561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17561}.)

The @ref{c22,,socket.if_nameindex()}, @ref{c23,,socket.if_nametoindex()}, and
@ref{c24,,socket.if_indextoname()} functions have been implemented on Windows.
(Contributed by Zackery Spytz in bpo-37007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37007}.)

@node ssl<5>,statistics<4>,socket<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 ssl}@anchor{c25}
@subsubsection ssl


Added @ref{c26,,post_handshake_auth} to enable and
@ref{c27,,verify_client_post_handshake()} to initiate TLS 1.3
post-handshake authentication.
(Contributed by Christian Heimes in bpo-34670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34670}.)

@node statistics<4>,sys<7>,ssl<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 statistics}@anchor{c28}
@subsubsection statistics


Added @ref{c29,,statistics.fmean()} as a faster, floating-point variant of
@ref{8e1,,statistics.mean()}.  (Contributed by Raymond Hettinger and
Steven D'Aprano in bpo-35904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35904}.)

Added @ref{c2a,,statistics.geometric_mean()}
(Contributed by Raymond Hettinger in bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}.)

Added @ref{c2b,,statistics.multimode()} that returns a list of the most
common values. (Contributed by Raymond Hettinger in bpo-35892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35892}.)

Added @ref{c2c,,statistics.quantiles()} that divides data or a distribution
in to equiprobable intervals (e.g. quartiles, deciles, or percentiles).
(Contributed by Raymond Hettinger in bpo-36546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36546}.)

Added @ref{c2d,,statistics.NormalDist}, a tool for creating
and manipulating normal distributions of a random variable.
(Contributed by Raymond Hettinger in bpo-36018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36018}.)

@example
>>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])
>>> temperature_feb.mean
6.0
>>> temperature_feb.stdev
6.356099432828281

>>> temperature_feb.cdf(3)            # Chance of being under 3 degrees
0.3184678262814532
>>> # Relative chance of being 7 degrees versus 10 degrees
>>> temperature_feb.pdf(7) / temperature_feb.pdf(10)
1.2039930378537762

>>> el_niño = NormalDist(4, 2.5)
>>> temperature_feb += el_niño        # Add in a climate effect
>>> temperature_feb
NormalDist(mu=10.0, sigma=6.830080526611674)

>>> temperature_feb * (9/5) + 32      # Convert to Fahrenheit
NormalDist(mu=50.0, sigma=12.294144947901014)
>>> temperature_feb.samples(3)        # Generate random samples
[7.672102882379219, 12.000027119750287, 4.647488369766392]
@end example

@node sys<7>,tarfile<5>,statistics<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 sys}@anchor{c2e}
@subsubsection sys


Add new @ref{507,,sys.unraisablehook()} function which can be overridden to control
how "unraisable exceptions" are handled. It is called when an exception has
occurred but there is no way for Python to handle it. For example, when a
destructor raises an exception or during garbage collection
(@ref{1b3,,gc.collect()}).
(Contributed by Victor Stinner in bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829}.)

@node tarfile<5>,threading<5>,sys<7>,改良されたモジュール<6>
@anchor{whatsnew/3 8 tarfile}@anchor{c2f}
@subsubsection tarfile


The @ref{e4,,tarfile} module now defaults to the modern pax (POSIX.1-2001)
format for new archives, instead of the previous GNU-specific one.
This improves cross-platform portability with a consistent encoding (UTF-8)
in a standardized and extensible format, and offers several other benefits.
(Contributed by C.A.M. Gerlach in bpo-36268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36268}.)

@node threading<5>,tokenize<2>,tarfile<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 threading}@anchor{c30}
@subsubsection threading


Add a new @ref{a4b,,threading.excepthook()} function which handles uncaught
@ref{c31,,threading.Thread.run()} exception. It can be overridden to control how
uncaught @ref{c31,,threading.Thread.run()} exceptions are handled.
(Contributed by Victor Stinner in bpo-1230540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1230540}.)

Add a new @ref{c32,,threading.get_native_id()} function and
a @ref{c33,,native_id}
attribute to the @ref{176,,threading.Thread} class. These return the native
integral Thread ID of the current thread assigned by the kernel.
This feature is only available on certain platforms, see
@ref{c32,,get_native_id} for more information.
(Contributed by Jake Tesler in bpo-36084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36084}.)

@node tokenize<2>,tkinter<5>,threading<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 tokenize}@anchor{c34}
@subsubsection tokenize


The @ref{101,,tokenize} module now implicitly emits a @code{NEWLINE} token when
provided with input that does not have a trailing new line.  This behavior
now matches what the C tokenizer does internally.
(Contributed by Ammar Askar in bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899}.)

@node tkinter<5>,time<4>,tokenize<2>,改良されたモジュール<6>
@anchor{whatsnew/3 8 tkinter}@anchor{c35}
@subsubsection tkinter


Added methods @code{selection_from()},
@code{selection_present()},
@code{selection_range()} and
@code{selection_to()}
in the @code{tkinter.Spinbox} class.
(Contributed by Juliette Monsel in bpo-34829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34829}.)

Added method @code{moveto()}
in the @code{tkinter.Canvas} class.
(Contributed by Juliette Monsel in bpo-23831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23831}.)

The @code{tkinter.PhotoImage} class now has
@code{transparency_get()} and
@code{transparency_set()} methods.  (Contributed by
Zackery Spytz in bpo-25451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25451}.)

@node time<4>,typing<9>,tkinter<5>,改良されたモジュール<6>
@anchor{whatsnew/3 8 time}@anchor{c36}
@subsubsection time


Added new clock @ref{c37,,CLOCK_UPTIME_RAW} for macOS 10.12.
(Contributed by Joannah Nanjekye in bpo-35702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35702}.)

@node typing<9>,unicodedata<6>,time<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 typing}@anchor{c38}
@subsubsection typing


The @ref{10a,,typing} module incorporates several new features:


@itemize *

@item 
A dictionary type with per-key types.  See 
@geindex Python Enhancement Proposals; PEP 589
PEP 589@footnote{https://peps.python.org/pep-0589/} and
@ref{332,,typing.TypedDict}.
TypedDict uses only string keys.  By default, every key is required
to be present. Specify "total=False" to allow keys to be optional:

@example
class Location(TypedDict, total=False):
    lat_long: tuple
    grid_square: str
    xy_coordinate: tuple
@end example

@item 
Literal types.  See 
@geindex Python Enhancement Proposals; PEP 586
PEP 586@footnote{https://peps.python.org/pep-0586/} and @ref{a55,,typing.Literal}.
Literal types indicate that a parameter or return value
is constrained to one or more specific literal values:

@example
def get_status(port: int) -> Literal['connected', 'disconnected']:
    ...
@end example

@item 
"Final" variables, functions, methods and classes.  See 
@geindex Python Enhancement Proposals; PEP 591
PEP 591@footnote{https://peps.python.org/pep-0591/},
@ref{56e,,typing.Final} and @ref{8bc,,typing.final()}.
The final qualifier instructs a static type checker to restrict
subclassing, overriding, or reassignment:

@example
pi: Final[float] = 3.1415926536
@end example

@item 
Protocol definitions.  See 
@geindex Python Enhancement Proposals; PEP 544
PEP 544@footnote{https://peps.python.org/pep-0544/}, @ref{56b,,typing.Protocol} and
@ref{675,,typing.runtime_checkable()}.  Simple ABCs like
@ref{c39,,typing.SupportsInt} are now @code{Protocol} subclasses.

@item 
New protocol class @ref{c3a,,typing.SupportsIndex}.

@item 
New functions @ref{2ab,,typing.get_origin()} and @ref{2ac,,typing.get_args()}.
@end itemize

@node unicodedata<6>,unittest<7>,typing<9>,改良されたモジュール<6>
@anchor{whatsnew/3 8 unicodedata}@anchor{c3b}
@subsubsection unicodedata


The @ref{10b,,unicodedata} module has been upgraded to use the Unicode 12.1.0@footnote{https://blog.unicode.org/2019/05/unicode-12-1-en.html} release.

New function @ref{c3c,,is_normalized()} can be used to verify a string
is in a specific normal form, often much faster than by actually normalizing
the string.  (Contributed by Max Belanger, David Euresti, and Greg Price in
bpo-32285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32285} and bpo-37966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37966}).

@node unittest<7>,venv<4>,unicodedata<6>,改良されたモジュール<6>
@anchor{whatsnew/3 8 unittest}@anchor{c3d}
@subsubsection unittest


Added @ref{c3e,,AsyncMock} to support an asynchronous version of
@ref{c3f,,Mock}.  Appropriate new assert functions for testing
have been added as well.
(Contributed by Lisa Roach in bpo-26467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26467}).

Added @ref{c40,,addModuleCleanup()} and
@ref{c41,,addClassCleanup()} to unittest to support
cleanups for @ref{c42,,setUpModule()} and
@ref{c43,,setUpClass()}.
(Contributed by Lisa Roach in bpo-24412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24412}.)

Several mock assert functions now also print a list of actual calls upon
failure. (Contributed by Petter Strandmark in bpo-35047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35047}.)

@ref{10c,,unittest} module gained support for coroutines to be used as test cases
with @ref{361,,unittest.IsolatedAsyncioTestCase}.
(Contributed by Andrew Svetlov in bpo-32972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32972}.)

以下はプログラム例です:

@example
import unittest


class TestRequest(unittest.IsolatedAsyncioTestCase):

    async def asyncSetUp(self):
        self.connection = await AsyncConnection()

    async def test_get(self):
        response = await self.connection.get("https://example.com")
        self.assertEqual(response.status_code, 200)

    async def asyncTearDown(self):
        await self.connection.close()


if __name__ == "__main__":
    unittest.main()
@end example

@node venv<4>,weakref,unittest<7>,改良されたモジュール<6>
@anchor{whatsnew/3 8 venv}@anchor{c44}
@subsubsection venv


@ref{117,,venv} now includes an @code{Activate.ps1} script on all platforms for
activating virtual environments under PowerShell Core 6.1.
(Contributed by Brett Cannon in bpo-32718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32718}.)

@node weakref,xml<4>,venv<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 weakref}@anchor{c45}
@subsubsection weakref


The proxy objects returned by @ref{c46,,weakref.proxy()} now support the matrix
multiplication operators @code{@@} and @code{@@=} in addition to the other
numeric operators. (Contributed by Mark Dickinson in bpo-36669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36669}.)

@node xml<4>,xmlrpc,weakref,改良されたモジュール<6>
@anchor{whatsnew/3 8 xml}@anchor{c47}
@subsubsection xml


As mitigation against DTD and external entity retrieval, the
@ref{128,,xml.dom.minidom} and @ref{12f,,xml.sax} modules no longer process
external entities by default.
(Contributed by Christian Heimes in bpo-17239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17239}.)

The @code{.find*()} methods in the @ref{12b,,xml.etree.ElementTree} module
support wildcard searches like @code{@{*@}tag} which ignores the namespace
and @code{@{namespace@}*} which returns all tags in the given namespace.
(Contributed by Stefan Behnel in bpo-28238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28238}.)

The @ref{12b,,xml.etree.ElementTree} module provides a new function
@ref{c48,,canonicalize()} that implements C14N 2.0.
(Contributed by Stefan Behnel in bpo-13611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13611}.)

The target object of @ref{c49,,xml.etree.ElementTree.XMLParser} can
receive namespace declaration events through the new callback methods
@code{start_ns()} and @code{end_ns()}.  Additionally, the
@ref{c4a,,xml.etree.ElementTree.TreeBuilder} target can be configured
to process events about comments and processing instructions to include
them in the generated tree.
(Contributed by Stefan Behnel in bpo-36676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36676} and bpo-36673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36673}.)

@node xmlrpc,,xml<4>,改良されたモジュール<6>
@anchor{whatsnew/3 8 xmlrpc}@anchor{c4b}
@subsubsection xmlrpc


@ref{c4c,,xmlrpc.client.ServerProxy} now supports an optional `headers' keyword
argument for a sequence of HTTP headers to be sent with each request.  Among
other things, this makes it possible to upgrade from default basic
authentication to faster session authentication.
(Contributed by Cédric Krier in bpo-35153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35153}.)

@node 最適化<7>,ビルドならびに C API の変更,改良されたモジュール<6>,What's New In Python 3 8
@anchor{whatsnew/3 8 optimizations}@anchor{c4d}
@subsection 最適化



@itemize *

@item 
The @ref{dc,,subprocess} module can now use the @ref{52e,,os.posix_spawn()} function
in some cases for better performance. Currently, it is only used on macOS
and Linux (using glibc 2.24 or newer) if all these conditions are met:


@itemize *

@item 
`close_fds' is false;

@item 
`preexec_fn', `pass_fds', `cwd' and `start_new_session' parameters
are not set;

@item 
the `executable' path contains a directory.
@end itemize

(Contributed by Joannah Nanjekye and Victor Stinner in bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}.)

@item 
@ref{c4e,,shutil.copyfile()}, @ref{c4f,,shutil.copy()}, @ref{c50,,shutil.copy2()},
@ref{c1e,,shutil.copytree()} and @ref{c51,,shutil.move()} use platform-specific
"fast-copy" syscalls on Linux and macOS in order to copy the file
more efficiently.
"fast-copy" means that the copying operation occurs within the kernel,
avoiding the use of userspace buffers in Python as in
"@code{outfd.write(infd.read())}".
On Windows @ref{c4e,,shutil.copyfile()} uses a bigger default buffer size (1 MiB
instead of 16 KiB) and a @ref{165,,memoryview()}-based variant of
@ref{c52,,shutil.copyfileobj()} is used.
The speedup for copying a 512 MiB file within the same partition is about
+26% on Linux, +50% on macOS and +40% on Windows. Also, much less CPU cycles
are consumed.
See @ref{c53,,プラットフォーム依存の効率的なコピー操作} section.
(Contributed by Giampaolo Rodolà in bpo-33671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33671}.)

@item 
@ref{c1e,,shutil.copytree()} uses @ref{c54,,os.scandir()} function and all copy
functions depending from it use cached @ref{26d,,os.stat()} values. The speedup
for copying a directory with 8000 files is around +9% on Linux, +20% on
Windows and +30% on a Windows SMB share. Also the number of @ref{26d,,os.stat()}
syscalls is reduced by 38% making @ref{c1e,,shutil.copytree()} especially faster
on network filesystems. (Contributed by Giampaolo Rodolà in bpo-33695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33695}.)

@item 
The default protocol in the @ref{ab,,pickle} module is now Protocol 4,
first introduced in Python 3.4.  It offers better performance and smaller
size compared to Protocol 3 available since Python 3.0.

@item 
Removed one @ref{c55,,Py_ssize_t} member from @code{PyGC_Head}.  All GC tracked
objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes.
(Contributed by Inada Naoki in bpo-33597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33597}.)

@item 
@ref{c56,,uuid.UUID} now uses @code{__slots__} to reduce its memory footprint.
(Contributed by Wouter Bolsterlee and Tal Einat in bpo-30977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30977})

@item 
Improved performance of @ref{c57,,operator.itemgetter()} by 33%.  Optimized
argument handling and added 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).  (Contributed by Raymond Hettinger in
bpo-35664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35664}.)

@item 
Sped-up field lookups in @ref{4e0,,collections.namedtuple()}.  They are now more
than two times faster, making them the fastest form of instance variable
lookup in Python. (Contributed by Raymond Hettinger, Pablo Galindo, and
Joe Jevnik, Serhiy Storchaka in bpo-32492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32492}.)

@item 
The @ref{24d,,list} constructor does not overallocate the internal item buffer
if the input iterable has a known length (the input implements @code{__len__}).
This makes the created list 12% smaller on average. (Contributed by
Raymond Hettinger and Pablo Galindo in bpo-33234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33234}.)

@item 
Doubled the speed of class variable writes.  When a non-dunder attribute
was updated, there was an unnecessary call to update slots.
(Contributed by Stefan Behnel, Pablo Galindo Salgado, Raymond Hettinger,
Neil Schemenauer, and Serhiy Storchaka in bpo-36012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36012}.)

@item 
Reduced an overhead of converting arguments passed to many builtin functions
and methods.  This sped up calling some simple builtin functions and
methods up to 20--50%.  (Contributed by Serhiy Storchaka in bpo-23867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23867},
bpo-35582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35582} and bpo-36127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36127}.)

@item 
@code{LOAD_GLOBAL} instruction now uses new "per opcode cache" mechanism.
It is about 40% faster now.  (Contributed by Yury Selivanov and Inada Naoki in
bpo-26219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26219}.)
@end itemize

@node ビルドならびに C API の変更,非推奨<9>,最適化<7>,What's New In Python 3 8
@anchor{whatsnew/3 8 build-and-c-api-changes}@anchor{c58}
@subsection ビルドならびに C API の変更



@itemize *

@item 
Default @ref{c59,,sys.abiflags} became an empty string: the @code{m} flag for
pymalloc became useless (builds with and without pymalloc are ABI compatible)
and so has been removed. (Contributed by Victor Stinner in bpo-36707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36707}.)

Example of changes:


@itemize *

@item 
Only @code{python3.8} program is installed, @code{python3.8m} program is gone.

@item 
Only @code{python3.8-config} script is installed, @code{python3.8m-config} script
is gone.

@item 
The @code{m} flag has been removed from the suffix of dynamic library
filenames: extension modules in the standard library as well as those
produced and installed by third-party packages, like those downloaded from
PyPI. On Linux, for example, the Python 3.7 suffix
@code{.cpython-37m-x86_64-linux-gnu.so} became
@code{.cpython-38-x86_64-linux-gnu.so} in Python 3.8.
@end itemize

@item 
The header files have been reorganized to better separate the different kinds
of APIs:


@itemize *

@item 
@code{Include/*.h} should be the portable public stable C API.

@item 
@code{Include/cpython/*.h} should be the unstable C API specific to CPython;
public API, with some private API prefixed by @code{_Py} or @code{_PY}.

@item 
@code{Include/internal/*.h} is the private internal C API very specific to
CPython. This API comes with no backward compatibility warranty and should
not be used outside CPython. It is only exposed for very specific needs
like debuggers and profiles which has to access to CPython internals
without calling functions. This API is now installed by @code{make install}.
@end itemize

(Contributed by Victor Stinner in bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134} and bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081},
work initiated by Eric Snow in Python 3.7.)

@item 
Some macros have been converted to static inline functions: parameter types
and return type are well defined, they don't have issues specific to macros,
variables have a local scopes. Examples:


@itemize *

@item 
@ref{78f,,Py_INCREF()}, @ref{790,,Py_DECREF()}

@item 
@ref{c5a,,Py_XINCREF()}, @ref{992,,Py_XDECREF()}

@item 
@code{PyObject_INIT}, @code{PyObject_INIT_VAR}

@item 
Private functions: @code{_PyObject_GC_TRACK()},
@code{_PyObject_GC_UNTRACK()}, @code{_Py_Dealloc()}
@end itemize

(Contributed by Victor Stinner in bpo-35059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35059}.)

@item 
The @code{PyByteArray_Init()} and @code{PyByteArray_Fini()} functions have
been removed. They did nothing since Python 2.7.4 and Python 3.2.0, were
excluded from the limited API (stable ABI), and were not documented.
(Contributed by Victor Stinner in bpo-35713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35713}.)

@item 
The result of @ref{c5b,,PyExceptionClass_Name()} is now of type
@code{const char *} rather of @code{char *}.
(Contributed by Serhiy Storchaka in bpo-33818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33818}.)

@item 
The duality of @code{Modules/Setup.dist} and @code{Modules/Setup} has been
removed.  Previously, when updating the CPython source tree, one had
to manually copy @code{Modules/Setup.dist} (inside the source tree) to
@code{Modules/Setup} (inside the build tree) in order to reflect any changes
upstream.  This was of a small benefit to packagers at the expense of
a frequent annoyance to developers following CPython development, as
forgetting to copy the file could produce build failures.

Now the build system always reads from @code{Modules/Setup} inside the source
tree.  People who want to customize that file are encouraged to maintain
their changes in a git fork of CPython or as patch files, as they would do
for any other change to the source tree.

(Contributed by Antoine Pitrou in bpo-32430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32430}.)

@item 
Functions that convert Python number to C integer like
@ref{605,,PyLong_AsLong()} and argument parsing functions like
@ref{3c1,,PyArg_ParseTuple()} with integer converting format units like @code{'i'}
will now use the @ref{19e,,__index__()} special method instead of
@ref{19d,,__int__()}, if available.  The deprecation warning will be
emitted for objects with the @code{__int__()} method but without the
@code{__index__()} method (like @ref{1fe,,Decimal} and
@ref{213,,Fraction}).  @ref{c5c,,PyNumber_Check()} will now return
@code{1} for objects implementing @code{__index__()}.
@ref{c5d,,PyNumber_Long()}, @ref{c5e,,PyNumber_Float()} and
@ref{c5f,,PyFloat_AsDouble()} also now use the @code{__index__()} method if
available.
(Contributed by Serhiy Storchaka in bpo-36048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36048} and bpo-20092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20092}.)

@item 
Heap-allocated type objects will now increase their reference count
in @ref{c60,,PyObject_Init()} (and its parallel macro @code{PyObject_INIT})
instead of in @ref{c61,,PyType_GenericAlloc()}. Types that modify instance
allocation or deallocation may need to be adjusted.
(Contributed by Eddie Elizondo in bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810}.)

@item 
The new function @code{PyCode_NewWithPosOnlyArgs()} allows to create
code objects like @code{PyCode_New()}, but with an extra `posonlyargcount'
parameter for indicating the number of positional-only arguments.
(Contributed by Pablo Galindo in bpo-37221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37221}.)

@item 
@code{Py_SetPath()} now sets @ref{3ed,,sys.executable} to the program full
path (@ref{3ec,,Py_GetProgramFullPath()}) rather than to the program name
(@ref{3ee,,Py_GetProgramName()}).
(Contributed by Victor Stinner in bpo-38234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38234}.)
@end itemize

@node 非推奨<9>,API と機能の削除,ビルドならびに C API の変更,What's New In Python 3 8
@anchor{whatsnew/3 8 deprecated}@anchor{c62}
@subsection 非推奨



@itemize *

@item 
The distutils @code{bdist_wininst} command is now deprecated, use
@code{bdist_wheel} (wheel packages) instead.
(Contributed by Victor Stinner in bpo-37481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37481}.)

@item 
Deprecated methods @code{getchildren()} and @code{getiterator()} in
the @ref{12b,,ElementTree} module now emit a
@ref{1a3,,DeprecationWarning} instead of @ref{ac5,,PendingDeprecationWarning}.
They will be removed in Python 3.9.
(Contributed by Serhiy Storchaka in bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209}.)

@item 
Passing an object that is not an instance of
@ref{949,,concurrent.futures.ThreadPoolExecutor} to
@ref{94a,,loop.set_default_executor()} is
deprecated and will be prohibited in Python 3.9.
(Contributed by Elvis Pranskevichus in bpo-34075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34075}.)

@item 
The @ref{588,,__getitem__()} methods of @ref{93e,,xml.dom.pulldom.DOMEventStream},
@ref{93f,,wsgiref.util.FileWrapper} and @ref{940,,fileinput.FileInput} have been
deprecated.

Implementations of these methods have been ignoring their `index' parameter,
and returning the next item instead.
(Contributed by Berker Peksag in bpo-9372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9372}.)

@item 
The @ref{331,,typing.NamedTuple} class has deprecated the @code{_field_types}
attribute in favor of the @code{__annotations__} attribute which has the same
information. (Contributed by Raymond Hettinger in bpo-36320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36320}.)

@item 
@ref{9,,ast} classes @code{Num}, @code{Str}, @code{Bytes}, @code{NameConstant} and
@code{Ellipsis} are considered deprecated and will be removed in future Python
versions. @ref{2ef,,Constant} should be used instead.
(Contributed by Serhiy Storchaka in bpo-32892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32892}.)

@item 
@ref{2f0,,ast.NodeVisitor} methods @code{visit_Num()}, @code{visit_Str()},
@code{visit_Bytes()}, @code{visit_NameConstant()} and @code{visit_Ellipsis()} are
deprecated now and will not be called in future Python versions.
Add the @ref{c63,,visit_Constant()} method to handle all
constant nodes.
(Contributed by Serhiy Storchaka in bpo-36917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36917}.)

@item 
The @code{@@asyncio.coroutine} @ref{93a,,decorator} is deprecated and will be
removed in version 3.10.  Instead of @code{@@asyncio.coroutine}, use
@ref{7ed,,async def} instead.
(Contributed by Andrew Svetlov in bpo-36921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36921}.)

@item 
In @ref{b,,asyncio}, the explicit passing of a `loop' argument has been
deprecated and will be removed in version 3.10 for the following:
@ref{c64,,asyncio.sleep()}, @ref{813,,asyncio.gather()}, @ref{c65,,asyncio.shield()},
@ref{815,,asyncio.wait_for()}, @ref{6a7,,asyncio.wait()}, @ref{4c6,,asyncio.as_completed()},
@ref{1c7,,asyncio.Task}, @ref{c66,,asyncio.Lock}, @ref{2f4,,asyncio.Event},
@ref{c67,,asyncio.Condition}, @ref{c68,,asyncio.Semaphore},
@ref{c69,,asyncio.BoundedSemaphore}, @ref{c6a,,asyncio.Queue},
@ref{c6b,,asyncio.create_subprocess_exec()}, and
@ref{c6c,,asyncio.create_subprocess_shell()}.

@item 
The explicit passing of coroutine objects to @ref{6a7,,asyncio.wait()} has been
deprecated and will be removed in version 3.11.
(Contributed by Yury Selivanov in bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790}.)

@item 
The following functions and methods are deprecated in the @ref{67,,gettext}
module: @code{lgettext()}, @code{ldgettext()},
@code{lngettext()} and @code{ldngettext()}.
They return encoded bytes, and it's possible that you will get unexpected
Unicode-related exceptions if there are encoding problems with the
translated strings. It's much better to use alternatives which return
Unicode strings in Python 3. These functions have been broken for a long time.

Function @code{bind_textdomain_codeset()}, methods
@code{NullTranslations.output_charset()} and
@code{NullTranslations.set_output_charset()}, and the `codeset'
parameter of functions @ref{c6d,,translation()} and
@ref{c6e,,install()} are also deprecated, since they are only used for
the @code{l*gettext()} functions.
(Contributed by Serhiy Storchaka in bpo-33710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33710}.)

@item 
The @code{isAlive()} method of @ref{176,,threading.Thread}
has been deprecated.
(Contributed by Donghee Na in bpo-35283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35283}.)

@item 
Many builtin and extension functions that take integer arguments will
now emit a deprecation warning for @ref{1fe,,Decimal}s,
@ref{213,,Fraction}s and any other objects that can be converted
to integers only with a loss (e.g. that have the @ref{19d,,__int__()}
method but do not have the @ref{19e,,__index__()} method).  In future
version they will be errors.
(Contributed by Serhiy Storchaka in bpo-36048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36048}.)

@item 
Deprecated passing the following arguments as keyword arguments:


@itemize -

@item 
`func' in @ref{218,,functools.partialmethod()}, @ref{c6f,,weakref.finalize()},
@ref{c70,,profile.Profile.runcall()}, @code{cProfile.Profile.runcall()},
@ref{c71,,bdb.Bdb.runcall()}, @ref{c72,,trace.Trace.runfunc()} and
@ref{c73,,curses.wrapper()}.

@item 
`function' in @ref{c74,,unittest.TestCase.addCleanup()}.

@item 
`fn' in the @ref{c75,,submit()} method of
@ref{949,,concurrent.futures.ThreadPoolExecutor} and
@ref{1d6,,concurrent.futures.ProcessPoolExecutor}.

@item 
`callback' in @ref{c76,,contextlib.ExitStack.callback()},
@code{contextlib.AsyncExitStack.callback()} and
@ref{c77,,contextlib.AsyncExitStack.push_async_callback()}.

@item 
`c' and `typeid' in the @code{create()}
method of @code{multiprocessing.managers.Server} and
@code{multiprocessing.managers.SharedMemoryServer}.

@item 
`obj' in @ref{c6f,,weakref.finalize()}.
@end itemize

In future releases of Python, they will be @ref{c78,,positional-only}.
(Contributed by Serhiy Storchaka in bpo-36492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36492}.)
@end itemize

@node API と機能の削除,Python 3 8 への移植,非推奨<9>,What's New In Python 3 8
@anchor{whatsnew/3 8 api-and-feature-removals}@anchor{c79}
@subsection API と機能の削除


The following features and APIs have been removed from Python 3.8:


@itemize *

@item 
Starting with Python 3.3, importing ABCs from @ref{1e,,collections} was
deprecated, and importing should be done from @ref{1f,,collections.abc}. Being
able to import from collections was marked for removal in 3.8, but has been
delayed to 3.9. (See gh-81134@footnote{https://github.com/python/cpython/issues/81134}.)

@item 
The @code{macpath} module, deprecated in Python 3.7, has been removed.
(Contributed by Victor Stinner in bpo-35471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35471}.)

@item 
The function @code{platform.popen()} has been removed, after having been
deprecated since Python 3.3: use @ref{31a,,os.popen()} instead.
(Contributed by Victor Stinner in bpo-35345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35345}.)

@item 
The function @code{time.clock()} has been removed, after having been
deprecated since Python 3.3: use @ref{c7a,,time.perf_counter()} or
@ref{c7b,,time.process_time()} instead, depending
on your requirements, to have well-defined behavior.
(Contributed by Matthias Bussonnier in bpo-36895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36895}.)

@item 
The @code{pyvenv} script has been removed in favor of @code{python3.8 -m venv}
to help eliminate confusion as to what Python interpreter the @code{pyvenv}
script is tied to. (Contributed by Brett Cannon in bpo-25427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25427}.)

@item 
@code{parse_qs}, @code{parse_qsl}, and @code{escape} are removed from the @code{cgi}
module.  They are deprecated in Python 3.2 or older. They should be imported
from the @code{urllib.parse} and @code{html} modules instead.

@item 
@code{filemode} function is removed from the @ref{e4,,tarfile} module.
It is not documented and deprecated since Python 3.3.

@item 
The @ref{c49,,XMLParser} constructor no longer accepts
the `html' argument.  It never had an effect and was deprecated in Python 3.4.
All other parameters are now @ref{5a5,,keyword-only}.
(Contributed by Serhiy Storchaka in bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209}.)

@item 
Removed the @code{doctype()} method of @ref{c49,,XMLParser}.
(Contributed by Serhiy Storchaka in bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209}.)

@item 
"unicode_internal" codec is removed.
(Contributed by Inada Naoki in bpo-36297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36297}.)

@item 
The @code{Cache} and @code{Statement} objects of the @ref{d4,,sqlite3} module are not
exposed to the user.
(Contributed by Aviv Palivoda in bpo-30262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30262}.)

@item 
The @code{bufsize} keyword argument of @ref{a00,,fileinput.input()} and
@ref{940,,fileinput.FileInput()} which was ignored and deprecated since Python 3.6
has been removed. bpo-36952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36952} (Contributed by Matthias Bussonnier.)

@item 
The functions @code{sys.set_coroutine_wrapper()} and
@code{sys.get_coroutine_wrapper()} deprecated in Python 3.7 have been removed;
bpo-36933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36933} (Contributed by Matthias Bussonnier.)
@end itemize

@node Python 3 8 への移植,Python3 8 1 での重要な変更点,API と機能の削除,What's New In Python 3 8
@anchor{whatsnew/3 8 porting-to-python-3-8}@anchor{c7c}
@subsection Python 3.8 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python の挙動の変更:: 
* Python API の変更: Python API の変更<6>. 
* C API の変更: C API の変更<10>. 
* CPython バイトコードの変更: CPython バイトコードの変更<6>. 
* Demos and Tools: Demos and Tools<2>. 

@end menu

@node Python の挙動の変更,Python API の変更<6>,,Python 3 8 への移植
@anchor{whatsnew/3 8 changes-in-python-behavior}@anchor{c7d}
@subsubsection Python の挙動の変更



@itemize *

@item 
Yield expressions (both @code{yield} and @code{yield from} clauses) are now disallowed
in comprehensions and generator expressions (aside from the iterable expression
in the leftmost @code{for} clause).
(Contributed by Serhiy Storchaka in bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544}.)

@item 
The compiler now produces a @ref{1ae,,SyntaxWarning} when identity checks
(@code{is} and @code{is not}) are used with certain types of literals
(e.g. strings, numbers).  These can often work by accident in CPython,
but are not guaranteed by the language spec.  The warning advises users
to use equality tests (@code{==} and @code{!=}) instead.
(Contributed by Serhiy Storchaka in bpo-34850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34850}.)

@item 
The CPython interpreter can swallow exceptions in some circumstances.
In Python 3.8 this happens in fewer cases.  In particular, exceptions
raised when getting the attribute from the type dictionary are no longer
ignored. (Contributed by Serhiy Storchaka in bpo-35459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35459}.)

@item 
Removed @code{__str__} implementations from builtin types @ref{3c3,,bool},
@ref{19b,,int}, @ref{196,,float}, @ref{197,,complex} and few classes from
the standard library.  They now inherit @code{__str__()} from @ref{c7e,,object}.
As result, defining the @code{__repr__()} method in the subclass of these
classes will affect their string representation.
(Contributed by Serhiy Storchaka in bpo-36793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36793}.)

@item 
On AIX, @ref{291,,sys.platform} doesn't contain the major version anymore.
It is always @code{'aix'}, instead of @code{'aix3'} .. @code{'aix7'}.  Since
older Python versions include the version number, so it is recommended to
always use @code{sys.platform.startswith('aix')}.
(Contributed by M. Felt in bpo-36588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36588}.)

@item 
@code{PyEval_AcquireLock()} and @code{PyEval_AcquireThread()} now
terminate the current thread if called while the interpreter is
finalizing, making them consistent with @ref{648,,PyEval_RestoreThread()},
@ref{c7f,,Py_END_ALLOW_THREADS()}, and @ref{64a,,PyGILState_Ensure()}. If this
behavior is not desired, guard the call by checking @code{_Py_IsFinalizing()}
or @ref{c80,,sys.is_finalizing()}.
(Contributed by Joannah Nanjekye in bpo-36475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36475}.)
@end itemize

@node Python API の変更<6>,C API の変更<10>,Python の挙動の変更,Python 3 8 への移植
@anchor{whatsnew/3 8 changes-in-the-python-api}@anchor{c81}
@subsubsection Python API の変更



@itemize *

@item 
The @ref{c82,,os.getcwdb()} function now uses the UTF-8 encoding on Windows,
rather than the ANSI code page: see 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} for the rationale. The
function is no longer deprecated on Windows.
(Contributed by Victor Stinner in bpo-37412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37412}.)

@item 
@ref{4b7,,subprocess.Popen} can now use @ref{52e,,os.posix_spawn()} in some cases
for better performance. On Windows Subsystem for Linux and QEMU User
Emulation, the @ref{4b7,,Popen} constructor using
@ref{52e,,os.posix_spawn()} no longer raises an exception on errors like
"missing program".  Instead the child process fails with a
non-zero @ref{c83,,returncode}.
(Contributed by Joannah Nanjekye and Victor Stinner in bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}.)

@item 
The `preexec_fn' argument of * @ref{4b7,,subprocess.Popen} is no longer
compatible with subinterpreters. The use of the parameter in a
subinterpreter now raises @ref{244,,RuntimeError}.
(Contributed by Eric Snow in bpo-34651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34651}, modified by Christian Heimes
in bpo-37951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37951}.)

@item 
The @ref{c84,,imaplib.IMAP4.logout()} method no longer silently ignores arbitrary
exceptions.
(Contributed by Victor Stinner in bpo-36348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36348}.)

@item 
The function @code{platform.popen()} has been removed, after having been deprecated since
Python 3.3: use @ref{31a,,os.popen()} instead.
(Contributed by Victor Stinner in bpo-35345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35345}.)

@item 
The @ref{c85,,statistics.mode()} function no longer raises an exception
when given multimodal data.  Instead, it returns the first mode
encountered in the input data.  (Contributed by Raymond Hettinger
in bpo-35892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35892}.)

@item 
The @ref{c86,,selection()} method of the
@ref{c87,,tkinter.ttk.Treeview} class no longer takes arguments.  Using it with
arguments for changing the selection was deprecated in Python 3.6.  Use
specialized methods like @ref{c88,,selection_set()} for
changing the selection.  (Contributed by Serhiy Storchaka in bpo-31508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31508}.)

@item 
The @ref{c89,,writexml()}, @ref{c8a,,toxml()}
and @ref{c8b,,toprettyxml()} methods of
@ref{128,,xml.dom.minidom} and the @ref{c8c,,write()}
method of @ref{12b,,xml.etree.ElementTree} now preserve the attribute order
specified by the user.
(Contributed by Diego Rojas and Raymond Hettinger in bpo-34160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34160}.)

@item 
A @ref{36,,dbm.dumb} database opened with flags @code{'r'} is now read-only.
@ref{c8d,,dbm.dumb.open()} with flags @code{'r'} and @code{'w'} no longer creates
a database if it does not exist.
(Contributed by Serhiy Storchaka in bpo-32749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32749}.)

@item 
The @code{doctype()} method defined in a subclass of
@ref{c49,,XMLParser} will no longer be called and will
emit a @ref{4d7,,RuntimeWarning} instead of a @ref{1a3,,DeprecationWarning}.
Define the @ref{c8e,,doctype()}
method on a target for handling an XML doctype declaration.
(Contributed by Serhiy Storchaka in bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209}.)

@item 
A @ref{244,,RuntimeError} is now raised when the custom metaclass doesn't
provide the @code{__classcell__} entry in the namespace passed to
@code{type.__new__}.  A @ref{1a3,,DeprecationWarning} was emitted in Python
3.6--3.7.  (Contributed by Serhiy Storchaka in bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}.)

@item 
The @ref{bd6,,cProfile.Profile} class can now be used as
a context manager. (Contributed by Scott Sanderson in bpo-29235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29235}.)

@item 
@ref{c4e,,shutil.copyfile()}, @ref{c4f,,shutil.copy()}, @ref{c50,,shutil.copy2()},
@ref{c1e,,shutil.copytree()} and @ref{c51,,shutil.move()} use platform-specific
"fast-copy" syscalls (see
@ref{c53,,プラットフォーム依存の効率的なコピー操作} section).

@item 
@ref{c4e,,shutil.copyfile()} default buffer size on Windows was changed from
16 KiB to 1 MiB.

@item 
The @code{PyGC_Head} struct has changed completely.  All code that touched the
struct member should be rewritten.  (See bpo-33597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33597}.)

@item 
The @ref{aba,,PyInterpreterState} struct has been moved into the "internal"
header files (specifically Include/internal/pycore_pystate.h).  An
opaque @code{PyInterpreterState} is still available as part of the public
API (and stable ABI).  The docs indicate that none of the struct's
fields are public, so we hope no one has been using them.  However,
if you do rely on one or more of those private fields and have no
alternative then please open a BPO issue.  We'll work on helping
you adjust (possibly including adding accessor functions to the
public API).  (See bpo-35886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35886}.)

@item 
The @ref{c8f,,mmap.flush()} method now returns @code{None} on
success and raises an exception on error under all platforms.  Previously,
its behavior was platform-dependent: a nonzero value was returned on success;
zero was returned on error under Windows.  A zero value was returned on
success; an exception was raised on error under Unix.
(Contributed by Berker Peksag in bpo-2122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2122}.)

@item 
@ref{128,,xml.dom.minidom} and @ref{12f,,xml.sax} modules no longer process
external entities by default.
(Contributed by Christian Heimes in bpo-17239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17239}.)

@item 
Deleting a key from a read-only @ref{35,,dbm} database (@ref{36,,dbm.dumb},
@ref{37,,dbm.gnu} or @ref{38,,dbm.ndbm}) raises @code{error} (@ref{c90,,dbm.dumb.error},
@ref{c91,,dbm.gnu.error} or @ref{c92,,dbm.ndbm.error}) instead of @ref{5e7,,KeyError}.
(Contributed by Xiang Zhang in bpo-33106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33106}.)

@item 
Simplified AST for literals.  All constants will be represented as
@ref{2ef,,ast.Constant} instances.  Instantiating old classes @code{Num},
@code{Str}, @code{Bytes}, @code{NameConstant} and @code{Ellipsis} will return
an instance of @code{Constant}.
(Contributed by Serhiy Storchaka in bpo-32892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32892}.)

@item 
@ref{c09,,expanduser()} on Windows now prefers the 
@geindex USERPROFILE
@geindex 環境変数; USERPROFILE
@code{USERPROFILE}
environment variable and does not use 
@geindex HOME
@geindex 環境変数; HOME
@code{HOME}, which is not normally
set for regular user accounts.
(Contributed by Anthony Sottile in bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264}.)

@item 
The exception @ref{4d4,,asyncio.CancelledError} now inherits from
@ref{7d6,,BaseException} rather than @ref{bcd,,Exception} and no longer inherits
from @ref{bce,,concurrent.futures.CancelledError}.
(Contributed by Yury Selivanov in bpo-32528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32528}.)

@item 
The function @ref{815,,asyncio.wait_for()} now correctly waits for cancellation
when using an instance of @ref{1c7,,asyncio.Task}. Previously, upon reaching
`timeout', it was cancelled and immediately returned.
(Contributed by Elvis Pranskevichus in bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}.)

@item 
The function @ref{c93,,asyncio.BaseTransport.get_extra_info()} now returns a safe
to use socket object when 'socket' is passed to the `name' parameter.
(Contributed by Yury Selivanov in bpo-37027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37027}.)

@item 
@ref{c94,,asyncio.BufferedProtocol} has graduated to the stable API.
@end itemize
@anchor{whatsnew/3 8 bpo-36085-whatsnew}@anchor{c95}

@itemize *

@item 
DLL dependencies for extension modules and DLLs loaded with @ref{2e,,ctypes} on
Windows are now resolved more securely. Only the system paths, the directory
containing the DLL or PYD file, and directories added with
@ref{bdd,,add_dll_directory()} are searched for load-time dependencies.
Specifically, 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} and the current working directory are no longer
used, and modifications to these will no longer have any effect on normal DLL
resolution. If your application relies on these mechanisms, you should check
for @ref{bdd,,add_dll_directory()} and if it exists, use it to add your DLLs
directory while loading your library. Note that Windows 7 users will need to
ensure that Windows Update KB2533623 has been installed (this is also verified
by the installer).
(Contributed by Steve Dower in bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085}.)

@item 
The header files and functions related to pgen have been removed after its
replacement by a pure Python implementation. (Contributed by Pablo Galindo
in bpo-36623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36623}.)

@item 
@ref{32f,,types.CodeType} has a new parameter in the second position of the
constructor (`posonlyargcount') to support positional-only arguments defined
in 
@geindex Python Enhancement Proposals; PEP 570
PEP 570@footnote{https://peps.python.org/pep-0570/}. The first argument (`argcount') now represents the total
number of positional arguments (including positional-only arguments). The new
@code{replace()} method of @ref{32f,,types.CodeType} can be used to make the code
future-proof.

@item 
The parameter @code{digestmod} for @ref{c96,,hmac.new()} no longer uses the MD5 digest
by default.
@end itemize

@node C API の変更<10>,CPython バイトコードの変更<6>,Python API の変更<6>,Python 3 8 への移植
@anchor{whatsnew/3 8 changes-in-the-c-api}@anchor{c97}
@subsubsection C API の変更



@itemize *

@item 
The @ref{c98,,PyCompilerFlags} structure got a new `cf_feature_version'
field. It should be initialized to @code{PY_MINOR_VERSION}. The field is ignored
by default, and is used if and only if @code{PyCF_ONLY_AST} flag is set in
`cf_flags'.
(Contributed by Guido van Rossum in bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766}.)

@item 
The @code{PyEval_ReInitThreads()} function has been removed from the C API.
It should not be called explicitly: use @ref{430,,PyOS_AfterFork_Child()}
instead.
(Contributed by Victor Stinner in bpo-36728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36728}.)

@item 
On Unix, C extensions are no longer linked to libpython except on Android
and Cygwin. When Python is embedded, @code{libpython} must not be loaded with
@code{RTLD_LOCAL}, but @code{RTLD_GLOBAL} instead. Previously, using
@code{RTLD_LOCAL}, it was already not possible to load C extensions which
were not linked to @code{libpython}, like C extensions of the standard
library built by the @code{*shared*} section of @code{Modules/Setup}.
(Contributed by Victor Stinner in bpo-21536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21536}.)

@item 
Use of @code{#} variants of formats in parsing or building value (e.g.
@ref{3c1,,PyArg_ParseTuple()}, @ref{3c2,,Py_BuildValue()}, @ref{63f,,PyObject_CallFunction()},
etc.) without @code{PY_SSIZE_T_CLEAN} defined raises @code{DeprecationWarning} now.
It will be removed in 3.10 or 4.0.  Read @ref{3d5,,引数の解釈と値の構築} for detail.
(Contributed by Inada Naoki in bpo-36381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36381}.)

@item 
Instances of heap-allocated types (such as those created with
@ref{79d,,PyType_FromSpec()}) hold a reference to their type object.
Increasing the reference count of these type objects has been moved from
@ref{c61,,PyType_GenericAlloc()} to the more low-level functions,
@ref{c60,,PyObject_Init()} and @code{PyObject_INIT}.
This makes types created through @ref{79d,,PyType_FromSpec()} behave like
other classes in managed code.

@ref{983,,Statically allocated types} are not affected.

For the vast majority of cases, there should be no side effect.
However, types that manually increase the reference count after allocating
an instance (perhaps to work around the bug) may now become immortal.
To avoid this, these classes need to call Py_DECREF on the type object
during instance deallocation.

To correctly port these types into 3.8, please apply the following
changes:


@itemize *

@item 
Remove @ref{78f,,Py_INCREF} on the type object after allocating an
instance - if any.
This may happen after calling @ref{b7c,,PyObject_New},
@ref{b7d,,PyObject_NewVar}, @ref{c99,,PyObject_GC_New()},
@ref{c9a,,PyObject_GC_NewVar()}, or any other custom allocator that uses
@ref{c60,,PyObject_Init()} or @code{PyObject_INIT}.

例:

@example
static foo_struct *
foo_new(PyObject *type) @{
    foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);
    if (foo == NULL)
        return NULL;
#if PY_VERSION_HEX < 0x03080000
    // Workaround for Python issue 35810; no longer necessary in Python 3.8
    PY_INCREF(type)
#endif
    return foo;
@}
@end example

@item 
Ensure that all custom @code{tp_dealloc} functions of heap-allocated types
decrease the type's reference count.

例:

@example
static void
foo_dealloc(foo_struct *instance) @{
    PyObject *type = Py_TYPE(instance);
    PyObject_GC_Del(instance);
#if PY_VERSION_HEX >= 0x03080000
    // This was not needed before Python 3.8 (Python issue 35810)
    Py_DECREF(type);
#endif
@}
@end example
@end itemize

(Contributed by Eddie Elizondo in bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810}.)

@item 
The @ref{c9b,,Py_DEPRECATED()} macro has been implemented for MSVC.
The macro now must be placed before the symbol name.

例:

@example
Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
@end example

(Contributed by Zackery Spytz in bpo-33407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33407}.)

@item 
The interpreter does not pretend to support binary compatibility of
extension types across feature releases, anymore.  A @ref{c9c,,PyTypeObject}
exported by a third-party extension module is supposed to have all the
slots expected in the current Python version, including
@ref{c9d,,tp_finalize} (@ref{427,,Py_TPFLAGS_HAVE_FINALIZE}
is not checked anymore before reading @ref{c9d,,tp_finalize}).

(Contributed by Antoine Pitrou in bpo-32388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32388}.)

@item 
The functions @code{PyNode_AddChild()} and @code{PyParser_AddToken()} now accept
two additional @code{int} arguments `end_lineno' and `end_col_offset'.

@item 
The @code{libpython38.a} file to allow MinGW tools to link directly against
@code{python38.dll} is no longer included in the regular Windows distribution.
If you require this file, it may be generated with the @code{gendef} and
@code{dlltool} tools, which are part of the MinGW binutils package:

@example
gendef - python38.dll > tmp.def
dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a
@end example

The location of an installed @code{pythonXY.dll} will depend on the
installation options and the version and language of Windows. See
@ref{c9e,,Windows で Python を使う} for more information. The resulting library should be
placed in the same directory as @code{pythonXY.lib}, which is generally the
@code{libs} directory under your Python installation.

(Contributed by Steve Dower in bpo-37351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37351}.)
@end itemize

@node CPython バイトコードの変更<6>,Demos and Tools<2>,C API の変更<10>,Python 3 8 への移植
@anchor{whatsnew/3 8 cpython-bytecode-changes}@anchor{c9f}
@subsubsection CPython バイトコードの変更



@itemize *

@item 
The interpreter loop  has been simplified by moving the logic of unrolling
the stack of blocks into the compiler.  The compiler emits now explicit
instructions for adjusting the stack of values and calling the
cleaning-up code for @ref{17f,,break}, @ref{180,,continue} and
@ref{1af,,return}.

Removed opcodes @code{BREAK_LOOP}, @code{CONTINUE_LOOP},
@code{SETUP_LOOP} and @code{SETUP_EXCEPT}.  Added new opcodes
@code{ROT_FOUR}, @code{BEGIN_FINALLY}, @code{CALL_FINALLY} and
@code{POP_FINALLY}.  Changed the behavior of @code{END_FINALLY}
and @code{WITH_CLEANUP_START}.

(Contributed by Mark Shannon, Antoine Pitrou and Serhiy Storchaka in
bpo-17611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17611}.)

@item 
Added new opcode @ref{ca0,,END_ASYNC_FOR} for handling exceptions raised
when awaiting a next item in an @ref{ca1,,async for} loop.
(Contributed by Serhiy Storchaka in bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}.)

@item 
The @ref{ca2,,MAP_ADD} now expects the value as the first element in the
stack and the key as the second element. This change was made so the key
is always evaluated before the value in dictionary comprehensions, as
proposed by 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/}. (Contributed by Jörn Heissler in bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224}.)
@end itemize

@node Demos and Tools<2>,,CPython バイトコードの変更<6>,Python 3 8 への移植
@anchor{whatsnew/3 8 demos-and-tools}@anchor{ca3}
@subsubsection Demos and Tools


Added a benchmark script for timing various ways to access variables:
@code{Tools/scripts/var_access_benchmark.py}.
(Contributed by Raymond Hettinger in bpo-35884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35884}.)

Here's a summary of performance improvements since Python 3.3:

@example
Python version                       3.3     3.4     3.5     3.6     3.7     3.8
--------------                       ---     ---     ---     ---     ---     ---

Variable and attribute read access:
    read_local                       4.0     7.1     7.1     5.4     5.1     3.9
    read_nonlocal                    5.3     7.1     8.1     5.8     5.4     4.4
    read_global                     13.3    15.5    19.0    14.3    13.6     7.6
    read_builtin                    20.0    21.1    21.6    18.5    19.0     7.5
    read_classvar_from_class        20.5    25.6    26.5    20.7    19.5    18.4
    read_classvar_from_instance     18.5    22.8    23.5    18.8    17.1    16.4
    read_instancevar                26.8    32.4    33.1    28.0    26.3    25.4
    read_instancevar_slots          23.7    27.8    31.3    20.8    20.8    20.2
    read_namedtuple                 68.5    73.8    57.5    45.0    46.8    18.4
    read_boundmethod                29.8    37.6    37.9    29.6    26.9    27.7

Variable and attribute write access:
    write_local                      4.6     8.7     9.3     5.5     5.3     4.3
    write_nonlocal                   7.3    10.5    11.1     5.6     5.5     4.7
    write_global                    15.9    19.7    21.2    18.0    18.0    15.8
    write_classvar                  81.9    92.9    96.0   104.6   102.1    39.2
    write_instancevar               36.4    44.6    45.8    40.0    38.9    35.5
    write_instancevar_slots         28.7    35.6    36.1    27.3    26.6    25.7

Data structure read access:
    read_list                       19.2    24.2    24.5    20.8    20.8    19.0
    read_deque                      19.9    24.7    25.5    20.2    20.6    19.8
    read_dict                       19.7    24.3    25.7    22.3    23.0    21.0
    read_strdict                    17.9    22.6    24.3    19.5    21.2    18.9

Data structure write access:
    write_list                      21.2    27.1    28.5    22.5    21.6    20.0
    write_deque                     23.8    28.7    30.1    22.7    21.8    23.5
    write_dict                      25.9    31.4    33.3    29.3    29.2    24.7
    write_strdict                   22.9    28.4    29.9    27.5    25.2    23.1

Stack (or queue) operations:
    list_append_pop                144.2    93.4   112.7    75.4    74.2    50.8
    deque_append_pop                30.4    43.5    57.0    49.4    49.2    42.5
    deque_append_popleft            30.8    43.7    57.3    49.7    49.7    42.8

Timing loop:
    loop_overhead                    0.3     0.5     0.6     0.4     0.3     0.3
@end example

The benchmarks were measured on an
Intel® Core™ i7-4960HQ processor@footnote{https://ark.intel.com/content/www/us/en/ark/products/76088/intel-core-i7-4960hq-processor-6m-cache-up-to-3-80-ghz.html}
running the macOS 64-bit builds found at
python.org@footnote{https://www.python.org/downloads/macos/}.
The benchmark script displays timings in nanoseconds.

@node Python3 8 1 での重要な変更点,Python3 8 2 での重要な変更点,Python 3 8 への移植,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-1}@anchor{ca4}
@subsection Python3.8.1 での重要な変更点


セキュリティ上の重大な懸念により、@ref{93c,,asyncio.loop.create_datagram_endpoint()} での `reuse_address' 引数は無効になりました。これはソケットオプション @cite{SO_REUSEADDR`} のUDP における挙動が原因です。詳しくは、@code{loop.create_datagram_endpoint()} のドキュメントを参照してください。(Kyle Stanley, Antoine Pitrou, Yury Selivanov による貢献 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228})

@node Python3 8 2 での重要な変更点,Notable changes in Python 3 8 3,Python3 8 1 での重要な変更点,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-2}@anchor{ca5}
@subsection Python3.8.2 での重要な変更点


Fixed a regression with the @code{ignore} callback of @ref{c1e,,shutil.copytree()}.
The argument types are now str and List[str] again.
(Contributed by Manuel Barkhau and Giampaolo Rodola in gh-83571@footnote{https://github.com/python/cpython/issues/83571}.)

@node Notable changes in Python 3 8 3,Python3 8 8 での重要な変更点,Python3 8 2 での重要な変更点,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-3}@anchor{ca6}
@subsection Notable changes in Python 3.8.3


The constant values of future flags in the @ref{0,,__future__} module
are updated in order to prevent collision with compiler flags. Previously
@code{PyCF_ALLOW_TOP_LEVEL_AWAIT} was clashing with @code{CO_FUTURE_DIVISION}.
(Contributed by Batuhan Taskaya in gh-83743@footnote{https://github.com/python/cpython/issues/83743})

@node Python3 8 8 での重要な変更点,Notable changes in Python 3 8 9,Notable changes in Python 3 8 3,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-8}@anchor{ca7}
@subsection Python3.8.8 での重要な変更点


Earlier Python versions allowed using both @code{;} and @code{&} as
query parameter separators in @ref{31f,,urllib.parse.parse_qs()} and
@ref{31e,,urllib.parse.parse_qsl()}.  Due to security concerns, and to conform with
newer W3C recommendations, this has been changed to allow only a single
separator key, with @code{&} as the default.  This change also affects
@code{cgi.parse()} and @code{cgi.parse_multipart()} as they use the affected
functions internally. For more details, please see their respective
documentation.
(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}.)

@node Notable changes in Python 3 8 9,Notable changes in Python 3 8 10,Python3 8 8 での重要な変更点,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-9}@anchor{ca8}
@subsection Notable changes in Python 3.8.9


A security fix alters the @ref{af6,,ftplib.FTP} behavior to not trust the
IPv4 address sent from the remote server when setting up a passive data
channel.  We reuse the ftp server IP address instead.  For unusual code
requiring the old behavior, set a @code{trust_server_pasv_ipv4_address}
attribute on your FTP instance to @code{True}.  (See gh-87451@footnote{https://github.com/python/cpython/issues/87451})

@node Notable changes in Python 3 8 10,Notable changes in Python 3 8 10<2>,Notable changes in Python 3 8 9,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-10}@anchor{ca9}
@subsection Notable changes in Python 3.8.10


@menu
* macOS 11.0 (Big Sur) と Appleシリコンの Mac のサポート: macOS 11 0 Big Sur と Appleシリコンの Mac のサポート<2>. 

@end menu

@node macOS 11 0 Big Sur と Appleシリコンの Mac のサポート<2>,,,Notable changes in Python 3 8 10
@anchor{whatsnew/3 8 macos-11-0-big-sur-and-apple-silicon-mac-support}@anchor{caa}
@subsubsection macOS 11.0 (Big Sur) と Appleシリコンの Mac のサポート


As of 3.8.10, Python now supports building and running on macOS 11
(Big Sur) and on Apple Silicon Macs (based on the @code{ARM64} architecture).
A new universal build variant, @code{universal2}, is now available to natively
support both @code{ARM64} and @code{Intel 64} in one set of executables.
Note that support for "weaklinking", building binaries targeted for newer
versions of macOS that will also run correctly on older versions by
testing at runtime for missing features, is not included in this backport
from Python 3.9; to support a range of macOS versions, continue to target
for and build on the oldest version in the range.

(Originally contributed by Ronald Oussoren and Lawrence D'Anna in gh-85272@footnote{https://github.com/python/cpython/issues/85272},
with fixes by FX Coudert and Eli Rykoff, and backported to 3.8 by Maxime Bélanger
and Ned Deily)

@node Notable changes in Python 3 8 10<2>,Notable changes in Python 3 8 12,Notable changes in Python 3 8 10,What's New In Python 3 8
@anchor{whatsnew/3 8 id1}@anchor{cab}
@subsection Notable changes in Python 3.8.10


@menu
* urllib.parse: urllib parse<4>. 

@end menu

@node urllib parse<4>,,,Notable changes in Python 3 8 10<2>
@anchor{whatsnew/3 8 urllib-parse}@anchor{cac}
@subsubsection urllib.parse


The presence of newline or tab characters in parts of a URL allows for some
forms of attacks. Following the WHATWG specification that updates 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html},
ASCII newline @code{\n}, @code{\r} and tab @code{\t} characters are stripped from the
URL by the parser in @ref{110,,urllib.parse} preventing such attacks. The removal
characters are controlled by a new module level variable
@code{urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE}. (See bpo-43882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43882})

@node Notable changes in Python 3 8 12,Notable security feature in 3 8 14,Notable changes in Python 3 8 10<2>,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-12}@anchor{cad}
@subsection Notable changes in Python 3.8.12


@menu
* Python API の変更: Python API の変更<7>. 

@end menu

@node Python API の変更<7>,,,Notable changes in Python 3 8 12
@anchor{whatsnew/3 8 id2}@anchor{cae}
@subsubsection Python API の変更


Starting with Python 3.8.12 the @ref{84,,ipaddress} module no longer accepts
any leading zeros in IPv4 address strings. Leading zeros are ambiguous and
interpreted as octal notation by some libraries. For example the legacy
function @ref{b5a,,socket.inet_aton()} treats leading zeros as octal notation.
glibc implementation of modern @ref{b5b,,inet_pton()} does not accept
any leading zeros.

(Originally contributed by Christian Heimes in bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384}, and backported
to 3.8 by Achraf Merzouki.)

@node Notable security feature in 3 8 14,Notable changes in 3 8 17,Notable changes in Python 3 8 12,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-security-feature-in-3-8-14}@anchor{caf}
@subsection Notable security feature in 3.8.14


Converting between @ref{19b,,int} and @ref{169,,str} in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
now raises a @ref{2ec,,ValueError} if the number of digits in string form is
above a limit to avoid potential denial of service attacks due to the
algorithmic complexity. This is a mitigation for 
@geindex Common Vulnerabilities and Exposures; CVE 2020-10735
CVE 2020-10735@footnote{https://www.cve.org/CVERecord?id=CVE-2020-10735}.
This limit can be configured or disabled by environment variable, command
line flag, or @ref{df,,sys} APIs. See the @ref{80b,,integer string conversion length limitation} documentation.  The default limit
is 4300 digits in string form.

@node Notable changes in 3 8 17,,Notable security feature in 3 8 14,What's New In Python 3 8
@anchor{whatsnew/3 8 notable-changes-in-3-8-17}@anchor{cb0}
@subsection Notable changes in 3.8.17


@menu
* tarfile: tarfile<6>. 

@end menu

@node tarfile<6>,,,Notable changes in 3 8 17
@anchor{whatsnew/3 8 id3}@anchor{cb1}
@subsubsection tarfile



@itemize *

@item 
The extraction methods in @ref{e4,,tarfile}, and @ref{696,,shutil.unpack_archive()},
have a new a `filter' argument that allows limiting tar features than may be
surprising or dangerous, such as creating files outside the destination
directory.
See @ref{697,,Extraction filters} for details.
In Python 3.12, use without the `filter' argument will show a
@ref{1a3,,DeprecationWarning}.
In Python 3.14, the default will switch to @code{'data'}.
(Contributed by Petr Viktorin in 
@geindex Python Enhancement Proposals; PEP 706
PEP 706@footnote{https://peps.python.org/pep-0706/}.)
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 7,What's New In Python 3 6,What's New In Python 3 8,What's New in Python
@anchor{whatsnew/3 7 doc}@anchor{cb2}@anchor{whatsnew/3 7 translation-repo}@anchor{cb3}@anchor{whatsnew/3 7 what-s-new-in-python-3-7}@anchor{cb4}
@section What's New In Python 3.7


@*編集者: 
Elvis Pranskevichus <@email{elvis@@magic.io}>


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Git log
@c when researching a change.

この記事では Python 3.6 と比較した Python 3.7 の新機能を解説します。Python 3.7 は2018年6月27日にリリースされました。全詳細については @ref{142,,変更履歴} をご覧ください。

@menu
* 概要: 概要 -- リリースハイライト<8>. リリースハイライト
* 新しい機能: 新しい機能<13>. 
* その他の言語変更: その他の言語変更<7>. 
* 新たなモジュール: 新たなモジュール<7>. 
* 改良されたモジュール: 改良されたモジュール<7>. 
* C API の変更: C API の変更<11>. 
* Build Changes: Build Changes<6>. 
* 最適化: 最適化<8>. 
* その他の CPython の実装の変更: その他の CPython の実装の変更<2>. 
* 非推奨の Python の挙動:: 
* 非推奨の Python モジュール、関数、メソッド:: 
* C API の非推奨の関数ならびに型:: 
* サポート対象プラットフォームからの除外:: 
* API と機能の削除: API と機能の削除<2>. 
* Module Removals:: 
* Windows-only Changes:: 
* 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 での重要な変更点. 
* Notable changes in Python 3.7.11: Notable changes in Python 3 7 11. 
* Notable security feature in 3.7.14: Notable security feature in 3 7 14. 

@end menu

@node 概要 -- リリースハイライト<8>,新しい機能<13>,,What's New In Python 3 7
@anchor{whatsnew/3 7 summary-release-highlights}@anchor{cb5}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.7.
@c Brevity is key.

新たな文法機能:


@itemize *

@item 
@ref{cb6,,PEP 563} 、型アノテーションの評価の遅延。
@end itemize

後方非互換な文法の変更:


@itemize *

@item 
@ref{93b,,async} と @ref{18d,,await} は予約されたキーワードになりました。
@end itemize

新たなライブラリモジュール:


@itemize *

@item 
@ref{28,,contextvars}: @ref{cb7,,PEP 567 -- コンテキスト変数}

@item 
@ref{33,,dataclasses}: @ref{cb8,,PEP 557 -- データクラス}

@item 
@ref{cb9,,importlib.resources}
@end itemize

新たな組み込み機能:


@itemize *

@item 
@ref{cba,,PEP 553} 、新しい @ref{271,,breakpoint()} 関数。
@end itemize

Python のデータモデルの改善:


@itemize *

@item 
@ref{cbb,,PEP 562} 、モジュール属性へのアクセスのカスタマイズ。

@item 
@ref{cbc,,PEP 560} 、typing モジュールとジェネリック型に対する言語コアによるサポート。

@item 
@ref{cbd,,dict}  オブジェクトの挿入順序を保存するという性質が、公式に Python 言語仕様の一部であると 宣言されました@footnote{hasbeendeclared} 。
@end itemize

標準ライブラリーの顕著な改善


@itemize *

@item 
@ref{b,,asyncio} モジュールに新しい機能が加わりました。
顕著な @ref{cbe,,使い勝手とパフォーマンスの改善} です。

@item 
@ref{f4,,time} モジュールが @ref{cbf,,ナノ秒単位の分解能を持つ関数} をサポートするようになりました。
@end itemize

CPython の実装の改善:


@itemize *

@item 
デフォルトのテキストエンコーディングとして ASCII を使わなくなりました:


@itemize *

@item 
@ref{cc0,,PEP 538} 、レガシーな C ロケールの抑圧

@item 
@ref{cc1,,PEP 540}, UTF-8 実行時モードの強制
@end itemize

@item 
@ref{cc2,,PEP 552} 、決定論的な .pyc

@item 
@ref{cc3,,New Python Development Mode}

@item 
@ref{cc4,,PEP 565} 、 @ref{1a3,,DeprecationWarning} の取り扱いの改善
@end itemize

C API の改善:


@itemize *

@item 
@ref{cc5,,PEP 539} 、スレッドローカルなストレージのための新しい C API
@end itemize

ドキュメントの改善:


@itemize *

@item 
@ref{cc6,,PEP 545} 、 Python ドキュメント翻訳

@item 
新しいドキュメント翻訳: 日本語@footnote{https://docs.python.org/ja/} 、 フランス語@footnote{https://docs.python.org/fr/} 、 韓国語@footnote{https://docs.python.org/ko/} 。
@end itemize

このリリースの特色は、多くの領域での特筆すべきパフォーマンスの改善です。
@ref{cc7,,最適化} 節に詳細な一覧があります。

1つ前にリリースされた Python との互換性に影響を持つ変更の一覧については、 @ref{cc8,,Python 3.7 への移植} 節を参照してください。

@node 新しい機能<13>,その他の言語変更<7>,概要 -- リリースハイライト<8>,What's New In Python 3 7
@anchor{whatsnew/3 7 new-features}@anchor{cc9}
@subsection 新しい機能


@menu
* PEP 563; アノテーションの遅延評価: 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; Show DeprecationWarning in __main__: PEP 565 Show DeprecationWarning in __main__. 
* PEP 560; typing モジュールとジェネリック型に対する言語コアによるサポート: PEP 560 typing モジュールとジェネリック型に対する言語コアによるサポート. 
* PEP 552; Hash-based .pyc Files: PEP 552 Hash-based pyc Files. 
* PEP 545; Python Documentation Translations: PEP 545 Python Documentation Translations. 
* Python Development Mode (-X dev): Python Development Mode -X dev. 

@end menu

@node PEP 563 アノテーションの遅延評価,PEP 538 レガシーな C ロケールの抑圧,,新しい機能<13>
@anchor{whatsnew/3 7 pep-563-postponed-evaluation-of-annotations}@anchor{cca}@anchor{whatsnew/3 7 whatsnew37-pep563}@anchor{cb6}
@subsubsection PEP 563: アノテーションの遅延評価


Python における型ヒントの到来により、 
@geindex Python Enhancement Proposals; PEP 3107
PEP 3107@footnote{https://peps.python.org/pep-3107/} で追加され 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} でさらに改善されたアノテーションの機能について、使い勝手に関する 2 つの明白な問題が明らかになりました:


@itemize *

@item 
アノテーションには現在のスコープで既に使える状態になっている名前しか使えない。言い換えれば、どんな種類の前方参照もサポートしない。

@item 
ソースコードに注釈を付けるのは Python プログラムの起動時間に好ましくない影響がある。
@end itemize

これらの問題はどちらもアノテーションの評価を遅延することで解決します。
アノテーションの定義時に、アノテーションに含まれる式を評価するコードをコンパイルする代わりに、コンパイラは当該の式の AST と同等な文字列形式でアノテーションを保存します。
必要であれば、 @ref{8c0,,typing.get_type_hints()} を使って実行時にアノテーションを解決できます。
たいていのケースではその必要は無く、(短い文字列はインタプリタによって格納されるので) アノテーションを保存するコストはより安くなり、起動時間がより速くなります。

使い勝手の点では、アノテーションは前方参照をサポートするようになり、次の文法が妥当なものになりました:

@example
class C:
    @@classmethod
    def from_string(cls, source: str) -> C:
        ...

    def validate_b(self, obj: B) -> bool:
        ...

class B:
    ...
@end example

この変更は後方互換性を壊してしまうので、新しい振る舞いは Python 3.7 では @ref{0,,__future__} インポートを使いモジュールごとに有効化する必要があります:

@example
from __future__ import annotations
@end example

この振る舞いは Python 3.10 でデフォルトになります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 563

@item PEP 563@footnote{https://peps.python.org/pep-0563/} -- アノテーションの遅延評価

PEP written and implemented by Łukasz Langa.
@end table


@node PEP 538 レガシーな C ロケールの抑圧,PEP 540 強制 UTF-8 実行モード,PEP 563 アノテーションの遅延評価,新しい機能<13>
@anchor{whatsnew/3 7 pep-538-legacy-c-locale-coercion}@anchor{ccb}@anchor{whatsnew/3 7 whatsnew37-pep538}@anchor{cc0}
@subsubsection PEP 538: レガシーな C ロケールの抑圧


Python 3 シリーズにおける継続中の課題の一つは、非 Windows プラットフォームではデフォルトの C ロケールつまり POSIX ロケールの使用から現在のところ必然的に導かれてしまう "7-bit ASCII" テキストエンコーディングの仮定を取り扱う賢明なデフォルトの方針を決定することです。

@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/} はインタープリタのデフォルトのコマンドラインインターフェースを更新し、新しく加わった 
@geindex PYTHONCOERCECLOCALE
@geindex 環境変数; PYTHONCOERCECLOCALE
@ref{ccc,,PYTHONCOERCECLOCALE} 環境変数のドキュメントにある通り、自動的にロケールを UTF-8 に基づいた利用可能なロケールへ強制します。
この方法で @code{LC_CTYPE} を自動的に設定すると、コアのインタープリタと (@ref{bf,,readline} などの) ロケールを考慮する C 拡張はデフォルトのテキストエンコーディングとして ASCII ではなく UTF-8 を使うことになります。

@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} にあるプラットフォームのサポート定義も、適切に設定された非 ASCII に基づくロケールだけにテキスト処理の完全なサポートを制限するよう更新されました。

この変更の一部として、強制対象として定義されたのロケール (現時点では @code{C.UTF-8}, @code{C.utf8}, @code{UTF-8}) を使っているときの @ref{75f,,stdin} と @ref{ccd,,stdout} のデフォルトのエラーハンドラは (@code{strict} ではなく) @code{surrogateescape} になります。
@ref{b33,,stderr} のデフォルトのエラーハンドラは、ロケールに関係無く引き続き @code{backslashreplace} です。

デフォルトではロケールの強制は暗黙に行われますが、ロケールが関係する結合における問題のデバッグを支援するために、 @code{PYTHONCOERCECLOCALE=warn} を設定することで (@ref{b33,,stderr} に直接出力される) 明示的な警告を要求できます。
この設定を有効にしていると、コアのインタプリタの初期化時にレガシーな C ロケールが有効なままの場合、 Python 実行器が警告を出力します。

@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/} のロケール強制には、(非 Python アプリケーションや古いバージョンの Python で動くのも含めた) 子プロセスに加え (GNU @code{readline} などの) 影響を受ける拡張モジュールにも利益がある一方、適切な対象ロケールが実行するシステムに存在することを要求するという負の面もあります。
(例えば、RHEL/CentOS 7 で起きているように) 適切な対象ロケールで利用可能なものが無いケースにきちんと対処するために、 Python 3.7 には @ref{cc1,,PEP 540; 強制 UTF-8 実行モード} も実装されています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 538

@item PEP 538@footnote{https://peps.python.org/pep-0538/} -- レガシーな C ロケールから UTF-8 ベースのロケールへの強制

PEP written and implemented by Nick Coghlan.
@end table


@node PEP 540 強制 UTF-8 実行モード,PEP 553 組み込みの breakpoint,PEP 538 レガシーな C ロケールの抑圧,新しい機能<13>
@anchor{whatsnew/3 7 pep-540-forced-utf-8-runtime-mode}@anchor{cce}@anchor{whatsnew/3 7 whatsnew37-pep540}@anchor{cc1}
@subsubsection PEP 540: 強制 UTF-8 実行モード


The new @ref{16f,,-X} @code{utf8} command line option and 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8}
environment variable can be used to enable the @ref{866,,Python UTF-8 Mode}.

When in UTF-8 mode, CPython ignores the locale settings, and uses the
UTF-8 encoding by default.  The error handlers for @ref{75f,,sys.stdin} and
@ref{ccd,,sys.stdout} streams are set to @code{surrogateescape}.

The forced UTF-8 mode can be used to change the text handling behavior in
an embedded Python interpreter without changing the locale settings of
an embedding application.

While 
@geindex Python Enhancement Proposals; PEP 540
PEP 540@footnote{https://peps.python.org/pep-0540/}'s UTF-8 mode has the benefit of working regardless of which
locales are available on the running system, it has the downside of having no
effect on extension modules (such as GNU @code{readline}), child processes running
non-Python applications, and child processes running older versions of Python.
To reduce the risk of corrupting text data when communicating with such
components, Python 3.7 also implements @ref{cc1,,PEP 540; 強制 UTF-8 実行モード}).

The UTF-8 mode is enabled by default when the locale is @code{C} or @code{POSIX}, and
the 
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/} locale coercion feature fails to change it to a UTF-8 based
alternative (whether that failure is due to @code{PYTHONCOERCECLOCALE=0} being set,
@code{LC_ALL} being set, or the lack of a suitable target locale).


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 540

@item PEP 540@footnote{https://peps.python.org/pep-0540/} -- 新しい UTF-8 モードの追加

PEP written and implemented by Victor Stinner
@end table


@node PEP 553 組み込みの breakpoint,PEP 539 スレッドローカルストレージのための新しい C API,PEP 540 強制 UTF-8 実行モード,新しい機能<13>
@anchor{whatsnew/3 7 pep-553-built-in-breakpoint}@anchor{cd0}@anchor{whatsnew/3 7 whatsnew37-pep553}@anchor{cba}
@subsubsection PEP 553: 組み込みの @code{breakpoint()}


Python 3.7 には、 Python デバッガへ入って行くための簡単で一貫した手段である、新しい組み込みの @ref{271,,breakpoint()} 関数があります。

Built-in @code{breakpoint()} calls @ref{cd1,,sys.breakpointhook()}.  By default, the
latter imports @ref{aa,,pdb} and then calls @code{pdb.set_trace()}, but by binding
@code{sys.breakpointhook()} to the function of your choosing, @code{breakpoint()} can
enter any debugger. Additionally, the environment variable
@geindex PYTHONBREAKPOINT
@geindex 環境変数; PYTHONBREAKPOINT
@ref{cd2,,PYTHONBREAKPOINT} can be set to the callable of your debugger of
choice.  Set @code{PYTHONBREAKPOINT=0} to completely disable built-in
@code{breakpoint()}.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 553

@item PEP 553@footnote{https://peps.python.org/pep-0553/} -- 組み込みの breakpoint()

PEP written and implemented by Barry Warsaw
@end table


@node PEP 539 スレッドローカルストレージのための新しい C API,PEP 562 モジュール属性へのアクセスのカスタマイズ,PEP 553 組み込みの breakpoint,新しい機能<13>
@anchor{whatsnew/3 7 pep-539-new-c-api-for-thread-local-storage}@anchor{cd3}@anchor{whatsnew/3 7 whatsnew37-pep539}@anchor{cc5}
@subsubsection PEP 539: スレッドローカルストレージのための新しい C API


While Python provides a C API for thread-local storage support; the existing
@ref{cd4,,Thread Local Storage (TLS) API} has used
int to represent TLS keys across all platforms.  This has not
generally been a problem for officially support platforms, but that is neither
POSIX-compliant, nor portable in any practical sense.

@geindex Python Enhancement Proposals; PEP 539
PEP 539@footnote{https://peps.python.org/pep-0539/} changes this by providing a new @ref{cd5,,Thread Specific Storage (TSS) API} to CPython which supersedes use of the
existing TLS API within the CPython interpreter, while deprecating the existing
API.  The TSS API uses a new type @ref{cd6,,Py_tss_t} instead of int
to represent TSS keys--an opaque type the definition of which may depend on
the underlying TLS implementation.  Therefore, this will allow to build CPython
on platforms where the native TLS key is defined in a way that cannot be safely
cast to int.

Note that on platforms where the native TLS key is defined in a way that cannot
be safely cast to int, all functions of the existing TLS API will be
no-op and immediately return failure. This indicates clearly that the old API
is not supported on platforms where it cannot be used reliably, and that no
effort will be made to add such support.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 539

@item PEP 539@footnote{https://peps.python.org/pep-0539/} -- A New C-API for Thread-Local Storage in CPython

PEP written by Erik M. Bray; implementation by Masayuki Yamamoto.
@end table


@node PEP 562 モジュール属性へのアクセスのカスタマイズ,PEP 564 ナノ秒単位の分解能を持つ新しい時間関数,PEP 539 スレッドローカルストレージのための新しい C API,新しい機能<13>
@anchor{whatsnew/3 7 pep-562-customization-of-access-to-module-attributes}@anchor{cd7}@anchor{whatsnew/3 7 whatsnew37-pep562}@anchor{cbb}
@subsubsection PEP 562: モジュール属性へのアクセスのカスタマイズ


Python 3.7 allows defining @ref{cd8,,__getattr__()} on modules and will call
it whenever a module attribute is otherwise not found.  Defining
@ref{cd9,,__dir__()} on modules is now also allowed.

この機能が役に立つ典型的な実例はモジュール属性の非推奨化と遅延読み込みです。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 562

@item PEP 562@footnote{https://peps.python.org/pep-0562/} -- モジュールの @code{__getattr__} と @code{__dir__}

PEP written and implemented by Ivan Levkivskyi
@end table


@node PEP 564 ナノ秒単位の分解能を持つ新しい時間関数,PEP 565 Show DeprecationWarning in __main__,PEP 562 モジュール属性へのアクセスのカスタマイズ,新しい機能<13>
@anchor{whatsnew/3 7 pep-564-new-time-functions-with-nanosecond-resolution}@anchor{cda}@anchor{whatsnew/3 7 whatsnew37-pep564}@anchor{cbf}
@subsubsection PEP 564: ナノ秒単位の分解能を持つ新しい時間関数


The resolution of clocks in modern systems can exceed the limited precision
of a floating-point number returned by the @ref{55d,,time.time()} function
and its variants.  To avoid loss of precision, 
@geindex Python Enhancement Proposals; PEP 564
PEP 564@footnote{https://peps.python.org/pep-0564/} adds six new
"nanosecond" variants of the existing timer functions to the @ref{f4,,time}
module:


@itemize *

@item 
@ref{cdb,,time.clock_gettime_ns()}

@item 
@ref{cdc,,time.clock_settime_ns()}

@item 
@ref{cdd,,time.monotonic_ns()}

@item 
@ref{cde,,time.perf_counter_ns()}

@item 
@ref{cdf,,time.process_time_ns()}

@item 
@ref{ce0,,time.time_ns()}
@end itemize

新しい関数は、整数値としてナノ秒単位の数値を返します。

@geindex Python Enhancement Proposals; PEP 0564#annex-clocks-resolution-in-python
Measurements@footnote{https://peps.python.org/pep-0564/#annex-clocks-resolution-in-python}
show that on Linux and Windows the resolution of @ref{ce0,,time.time_ns()} is
approximately 3 times better than that of @ref{55d,,time.time()}.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 564

@item PEP 564@footnote{https://peps.python.org/pep-0564/} -- ナノ秒単位の分解能を持つ新しい時間関数の追加

PEP written and implemented by Victor Stinner
@end table


@node PEP 565 Show DeprecationWarning in __main__,PEP 560 typing モジュールとジェネリック型に対する言語コアによるサポート,PEP 564 ナノ秒単位の分解能を持つ新しい時間関数,新しい機能<13>
@anchor{whatsnew/3 7 pep-565-show-deprecationwarning-in-main}@anchor{ce1}@anchor{whatsnew/3 7 whatsnew37-pep565}@anchor{cc4}
@subsubsection PEP 565: Show DeprecationWarning in @code{__main__}


The default handling of @ref{1a3,,DeprecationWarning} has been changed such that
these warnings are once more shown by default, but only when the code
triggering them is running directly in the @ref{1,,__main__} module.  As a result,
developers of single file scripts and those using Python interactively should
once again start seeing deprecation warnings for the APIs they use, but
deprecation warnings triggered by imported application, library and framework
modules will continue to be hidden by default.

As a result of this change, the standard library now allows developers to choose
between three different deprecation warning behaviours:


@itemize *

@item 
@ref{659,,FutureWarning}: always displayed by default, recommended for warnings
intended to be seen by application end users (e.g. for deprecated application
configuration settings).

@item 
@ref{1a3,,DeprecationWarning}: displayed by default only in @ref{1,,__main__} and when
running tests, recommended for warnings intended to be seen by other Python
developers where a version upgrade may result in changed behaviour or an
error.

@item 
@ref{ac5,,PendingDeprecationWarning}: displayed by default only when running
tests, intended for cases where a future version upgrade will change the
warning category to @ref{1a3,,DeprecationWarning} or @ref{659,,FutureWarning}.
@end itemize

Previously both @ref{1a3,,DeprecationWarning} and @ref{ac5,,PendingDeprecationWarning}
were only visible when running tests, which meant that developers primarily
writing single file scripts or using Python interactively could be surprised
by breaking changes in the APIs they used.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 565

@item PEP 565@footnote{https://peps.python.org/pep-0565/} -- Show DeprecationWarning in @code{__main__}

PEP written and implemented by Nick Coghlan
@end table


@node PEP 560 typing モジュールとジェネリック型に対する言語コアによるサポート,PEP 552 Hash-based pyc Files,PEP 565 Show DeprecationWarning in __main__,新しい機能<13>
@anchor{whatsnew/3 7 pep-560-core-support-for-typing-module-and-generic-types}@anchor{ce2}@anchor{whatsnew/3 7 whatsnew37-pep560}@anchor{cbc}
@subsubsection PEP 560: @code{typing} モジュールとジェネリック型に対する言語コアによるサポート


Initially 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} was designed in such way that it would not introduce `any'
changes to the core CPython interpreter. Now type hints and the @ref{10a,,typing}
module are extensively used by the community, so this restriction is removed.
The PEP introduces two special methods @ref{943,,__class_getitem__()} and
@ref{ce3,,__mro_entries__()}, these methods are now used by most classes and special
constructs in @ref{10a,,typing}. As a result, the speed of various operations
with types increased up to 7 times, the generic types can be used without
metaclass conflicts, and several long standing bugs in @ref{10a,,typing} module are
fixed.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 560

@item PEP 560@footnote{https://peps.python.org/pep-0560/} -- typing モジュールとジェネリック型に対する言語コアによるサポート

PEP written and implemented by Ivan Levkivskyi
@end table


@node PEP 552 Hash-based pyc Files,PEP 545 Python Documentation Translations,PEP 560 typing モジュールとジェネリック型に対する言語コアによるサポート,新しい機能<13>
@anchor{whatsnew/3 7 pep-552-hash-based-pyc-files}@anchor{ce4}@anchor{whatsnew/3 7 whatsnew37-pep552}@anchor{cc2}
@subsubsection PEP 552: Hash-based .pyc Files


Python has traditionally checked the up-to-dateness of bytecode cache files
(i.e., @code{.pyc} files) by comparing the source metadata (last-modified timestamp
and size) with source metadata saved in the cache file header when it was
generated. While effective, this invalidation method has its drawbacks.  When
filesystem timestamps are too coarse, Python can miss source updates, leading to
user confusion. Additionally, having a timestamp in the cache file is
problematic for build reproducibility@footnote{https://reproducible-builds.org/} and
content-based build systems.

@geindex Python Enhancement Proposals; PEP 552
PEP 552@footnote{https://peps.python.org/pep-0552/} extends the pyc format to allow the hash of the source file to be
used for invalidation instead of the source timestamp. Such @code{.pyc} files are
called "hash-based". By default, Python still uses timestamp-based invalidation
and does not generate hash-based @code{.pyc} files at runtime. Hash-based @code{.pyc}
files may be generated with @ref{b8,,py_compile} or @ref{21,,compileall}.

Hash-based @code{.pyc} files come in two variants: checked and unchecked. Python
validates checked hash-based @code{.pyc} files against the corresponding source
files at runtime but doesn't do so for unchecked hash-based pycs. Unchecked
hash-based @code{.pyc} files are a useful performance optimization for environments
where a system external to Python (e.g., the build system) is responsible for
keeping @code{.pyc} files up-to-date.

See @ref{802,,キャッシュされたバイトコードの無効化} for more information.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 552

@item PEP 552@footnote{https://peps.python.org/pep-0552/} -- Deterministic pycs

PEP written and implemented by Benjamin Peterson
@end table


@node PEP 545 Python Documentation Translations,Python Development Mode -X dev,PEP 552 Hash-based pyc Files,新しい機能<13>
@anchor{whatsnew/3 7 pep-545-python-documentation-translations}@anchor{ce5}@anchor{whatsnew/3 7 whatsnew37-pep545}@anchor{cc6}
@subsubsection PEP 545: Python Documentation Translations


@geindex Python Enhancement Proposals; PEP 545
PEP 545@footnote{https://peps.python.org/pep-0545/} describes the process of creating and maintaining Python
documentation translations.

Three new translations have been added:


@itemize -

@item 
日本語: @indicateurl{https://docs.python.org/ja/}

@item 
フランス語: @indicateurl{https://docs.python.org/fr/}

@item 
韓国語: @indicateurl{https://docs.python.org/ko/}
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 545

@item PEP 545@footnote{https://peps.python.org/pep-0545/} -- Python ドキュメント翻訳

PEP written and implemented by Julien Palard, Inada Naoki, and
Victor Stinner.
@end table


@node Python Development Mode -X dev,,PEP 545 Python Documentation Translations,新しい機能<13>
@anchor{whatsnew/3 7 python-development-mode-x-dev}@anchor{ce6}@anchor{whatsnew/3 7 whatsnew37-devmode}@anchor{cc3}
@subsubsection Python Development Mode (-X dev)


The new @ref{16f,,-X} @code{dev} command line option or the new
@geindex PYTHONDEVMODE
@geindex 環境変数; PYTHONDEVMODE
@ref{ce7,,PYTHONDEVMODE} environment variable can be used to enable
@ref{508,,Python Development Mode}.  When in development mode, Python performs
additional runtime checks that are too expensive to be enabled by default.
See @ref{508,,Python Development Mode} documentation for the full
description.

@node その他の言語変更<7>,新たなモジュール<7>,新しい機能<13>,What's New In Python 3 7
@anchor{whatsnew/3 7 other-language-changes}@anchor{ce8}
@subsection その他の言語変更



@itemize *

@item 
An @ref{18d,,await} expression and comprehensions containing an
@ref{ca1,,async for} clause were illegal in the expressions in
@ref{19a,,formatted string literals} due to a problem with the
implementation.  In Python 3.7 this restriction was lifted.

@item 
More than 255 arguments can now be passed to a function, and a function can
now have more than 255 parameters. (Contributed by Serhiy Storchaka in
bpo-12844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12844} and bpo-18896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18896}.)

@item 
@ref{190,,bytes.fromhex()} and @ref{191,,bytearray.fromhex()} now ignore all ASCII
whitespace, not only spaces. (Contributed by Robert Xiao in bpo-28927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28927}.)

@item 
@ref{169,,str}, @ref{192,,bytes}, and @ref{344,,bytearray} gained support for
the new @ref{ce9,,isascii()} method, which can be used to
test if a string or bytes contain only the ASCII characters.
(Contributed by INADA Naoki in bpo-32677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32677}.)

@item 
@ref{65b,,ImportError} now displays module name and module @code{__file__} path when
@code{from ... import ...} fails. (Contributed by Matthias Bussonnier in
bpo-29546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29546}.)

@item 
Circular imports involving absolute imports with binding a submodule to
a name are now supported.
(Contributed by Serhiy Storchaka in bpo-30024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30024}.)

@item 
@code{object.__format__(x, '@w{'})} is now equivalent to @code{str(x)} rather than
@code{format(str(self), '@w{'})}.
(Contributed by Serhiy Storchaka in bpo-28974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28974}.)

@item 
In order to better support dynamic creation of stack traces,
@ref{cea,,types.TracebackType} can now be instantiated from Python code, and
the @ref{ceb,,tb_next} attribute on
@ref{cec,,tracebacks} is now writable.
(Contributed by Nathaniel J. Smith in bpo-30579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30579}.)

@item 
When using the @ref{23c,,-m} switch, @code{sys.path[0]} is now eagerly expanded
to the full starting directory path, rather than being left as the empty
directory (which allows imports from the `current' working directory at the
time when an import occurs)
(Contributed by Nick Coghlan in bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053}.)

@item 
The new @ref{16f,,-X} @code{importtime} option or the
@geindex PYTHONPROFILEIMPORTTIME
@geindex 環境変数; PYTHONPROFILEIMPORTTIME
@ref{ced,,PYTHONPROFILEIMPORTTIME} environment variable can be used to show
the timing of each module import.
(Contributed by Inada Naoki in bpo-31415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31415}.)
@end itemize

@node 新たなモジュール<7>,改良されたモジュール<7>,その他の言語変更<7>,What's New In Python 3 7
@anchor{whatsnew/3 7 new-modules}@anchor{cee}
@subsection 新たなモジュール


@menu
* contextvars: contextvars<2>. 
* データクラス: データクラス<3>. 
* importlib.resources: importlib resources<2>. 

@end menu

@node contextvars<2>,データクラス<3>,,新たなモジュール<7>
@anchor{whatsnew/3 7 contextvars}@anchor{cef}@anchor{whatsnew/3 7 whatsnew37-pep567}@anchor{cb7}
@subsubsection contextvars


The new @ref{28,,contextvars} module and a set of
@ref{cf0,,new C APIs} introduce
support for `context variables'.  Context variables are conceptually
similar to thread-local variables.  Unlike TLS, context variables
support asynchronous code correctly.

The @ref{b,,asyncio} and @ref{3a,,decimal} modules have been updated to use
and support context variables out of the box.  Particularly the active
decimal context is now stored in a context variable, which allows
decimal operations to work with the correct context in asynchronous code.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 567

@item PEP 567@footnote{https://peps.python.org/pep-0567/} -- コンテキスト変数

PEP written and implemented by Yury Selivanov
@end table


@node データクラス<3>,importlib resources<2>,contextvars<2>,新たなモジュール<7>
@anchor{whatsnew/3 7 dataclasses}@anchor{cf1}@anchor{whatsnew/3 7 whatsnew37-pep557}@anchor{cb8}
@subsubsection データクラス


新しい @ref{4e1,,dataclass()} デコレータにより `データクラス' を宣言する方法が提供されます。
データクラスは属性を記述するのに、クラス変数アノテーションを使います。
コンストラクタや他の @ref{82f,,__repr__()}, @ref{cf2,,__eq__()}, @ref{cf3,,__hash__()} などのマジックメソッドは自動で生成されます。

以下はプログラム例です:

@example
@@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0

p = Point(1.5, 2.5)
print(p)   # produces "Point(x=1.5, y=2.5, z=0.0)"
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 557

@item PEP 557@footnote{https://peps.python.org/pep-0557/} -- データクラス

PEP written and implemented by Eric V. Smith
@end table


@node importlib resources<2>,,データクラス<3>,新たなモジュール<7>
@anchor{whatsnew/3 7 importlib-resources}@anchor{cf4}@anchor{whatsnew/3 7 whatsnew37-importlib-resources}@anchor{cb9}
@subsubsection importlib.resources


The new @ref{7f,,importlib.resources} module provides several new APIs and one
new ABC for access to, opening, and reading `resources' inside packages.
Resources are roughly similar to files inside packages, but they needn't
be actual files on the physical file system.  Module loaders can provide a
@code{get_resource_reader()} function which returns
a @code{importlib.abc.ResourceReader} instance to support this
new API.  Built-in file path loaders and zip file loaders both support this.

Contributed by Barry Warsaw and Brett Cannon in bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248}.


@subsubheading 参考


importlib_resources@footnote{https://importlib-resources.readthedocs.io/en/latest/}
-- a PyPI backport for earlier Python versions.


@node 改良されたモジュール<7>,C API の変更<11>,新たなモジュール<7>,What's New In Python 3 7
@anchor{whatsnew/3 7 improved-modules}@anchor{cf5}
@subsection 改良されたモジュール


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

@end menu

@node argparse<5>,asyncio<10>,,改良されたモジュール<7>
@anchor{whatsnew/3 7 argparse}@anchor{cf6}
@subsubsection argparse


The new @ref{cf7,,ArgumentParser.parse_intermixed_args()}
method allows intermixing options and positional arguments.
(Contributed by paul.j3 in bpo-14191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14191}.)

@node asyncio<10>,binascii,argparse<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 asyncio}@anchor{cf8}@anchor{whatsnew/3 7 whatsnew37-asyncio}@anchor{cbe}
@subsubsection asyncio


The @ref{b,,asyncio} module has received many new features, usability and
@ref{cf9,,performance improvements}.  Notable changes
include:


@itemize *

@item 
The new @ref{3d1,,provisional} @ref{2f3,,asyncio.run()} function can
be used to run a coroutine from synchronous code by automatically creating and
destroying the event loop.
(Contributed by Yury Selivanov in bpo-32314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32314}.)

@item 
asyncio gained support for @ref{28,,contextvars}.
@ref{cfa,,loop.call_soon()},
@ref{cfb,,loop.call_soon_threadsafe()},
@ref{cfc,,loop.call_later()},
@ref{cfd,,loop.call_at()}, and
@ref{cfe,,Future.add_done_callback()}
have a new optional keyword-only `context' parameter.
@ref{1c7,,Tasks} now track their context automatically.
See 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} for more details.
(Contributed by Yury Selivanov in bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}.)

@item 
The new @ref{1c9,,asyncio.create_task()} function has been added as a shortcut
to @code{asyncio.get_event_loop().create_task()}.
(Contributed by Andrew Svetlov in bpo-32311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32311}.)

@item 
The new @ref{cff,,loop.start_tls()}
method can be used to upgrade an existing connection to TLS.
(Contributed by Yury Selivanov in bpo-23749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23749}.)

@item 
The new @ref{d00,,loop.sock_recv_into()}
method allows reading data from a socket directly into a provided buffer making
it possible to reduce data copies.
(Contributed by Antoine Pitrou in bpo-31819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31819}.)

@item 
The new @ref{6a5,,asyncio.current_task()} function returns the currently running
@ref{1c7,,Task} instance, and the new @ref{b4f,,asyncio.all_tasks()}
function returns a set of all existing @code{Task} instances in a given loop.
The @code{Task.current_task()} and
@code{Task.all_tasks()} methods have been deprecated.
(Contributed by Andrew Svetlov in bpo-32250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32250}.)

@item 
The new `provisional' @ref{c94,,BufferedProtocol} class allows
implementing streaming protocols with manual control over the receive buffer.
(Contributed by Yury Selivanov in bpo-32251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32251}.)

@item 
The new @ref{d01,,asyncio.get_running_loop()} function returns the currently
running loop, and raises a @ref{244,,RuntimeError} if no loop is running.
This is in contrast with @ref{2f2,,asyncio.get_event_loop()}, which will `create'
a new event loop if none is running.
(Contributed by Yury Selivanov in bpo-32269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32269}.)

@item 
The new @ref{d02,,StreamWriter.wait_closed()}
coroutine method allows waiting until the stream writer is closed.  The new
@ref{d03,,StreamWriter.is_closing()} method
can be used to determine if the writer is closing.
(Contributed by Andrew Svetlov in bpo-32391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32391}.)

@item 
The new @ref{d04,,loop.sock_sendfile()}
coroutine method allows sending files using @ref{d05,,os.sendfile} when possible.
(Contributed by Andrew Svetlov in bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410}.)

@item 
The new @ref{d06,,Future.get_loop()} and
@code{Task.get_loop()} methods return the instance of the loop on which a task or
a future were created.
@ref{d07,,Server.get_loop()} allows doing the same for
@ref{d08,,asyncio.Server} objects.
(Contributed by Yury Selivanov in bpo-32415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32415} and
Srinivas Reddy Thatiparthy in bpo-32418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32418}.)

@item 
It is now possible to control how instances of @ref{d08,,asyncio.Server} begin
serving.  Previously, the server would start serving immediately when created.
The new `start_serving' keyword argument to
@ref{d09,,loop.create_server()} and
@ref{4ca,,loop.create_unix_server()},
as well as @ref{d0a,,Server.start_serving()}, and
@ref{d0b,,Server.serve_forever()}
can be used to decouple server instantiation and serving.  The new
@ref{d0c,,Server.is_serving()} method returns @code{True}
if the server is serving.  @ref{d08,,Server} objects are now
asynchronous context managers:

@example
srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
@end example

(Contributed by Yury Selivanov in bpo-32662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32662}.)

@item 
Callback objects returned by
@ref{cfc,,loop.call_later()}
gained the new @ref{d0d,,when()} method which
returns an absolute scheduled callback timestamp.
(Contributed by Andrew Svetlov in bpo-32741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32741}.)

@item 
The @ref{93c,,loop.create_datagram_endpoint()} method
gained support for Unix sockets.
(Contributed by Quentin Dawans in bpo-31245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31245}.)

@item 
The @ref{d0e,,asyncio.open_connection()}, @ref{d0f,,asyncio.start_server()} functions,
@ref{818,,loop.create_connection()},
@ref{d09,,loop.create_server()},
@ref{9de,,loop.create_accepted_socket()}
methods and their corresponding UNIX socket variants now accept the
`ssl_handshake_timeout' keyword argument.
(Contributed by Neil Aspinall in bpo-29970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29970}.)

@item 
The new @ref{d10,,Handle.cancelled()} method returns
@code{True} if the callback was cancelled.
(Contributed by Marat Sharafutdinov in bpo-31943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31943}.)

@item 
The asyncio source has been converted to use the
@ref{93b,,async}/@ref{18d,,await} syntax.
(Contributed by Andrew Svetlov in bpo-32193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32193}.)

@item 
The new @ref{d11,,ReadTransport.is_reading()}
method can be used to determine the reading state of the transport.
Additionally, calls to
@ref{d12,,ReadTransport.resume_reading()}
and @ref{d13,,ReadTransport.pause_reading()}
are now idempotent.
(Contributed by Yury Selivanov in bpo-32356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32356}.)

@item 
Loop methods which accept socket paths now support passing
@ref{5a1,,path-like objects}.
(Contributed by Yury Selivanov in bpo-32066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32066}.)

@item 
In @ref{b,,asyncio} TCP sockets on Linux are now created with @code{TCP_NODELAY}
flag set by default.
(Contributed by Yury Selivanov and Victor Stinner in bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}.)

@item 
Exceptions occurring in cancelled tasks are no longer logged.
(Contributed by Yury Selivanov in bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508}.)

@item 
New @code{WindowsSelectorEventLoopPolicy} and
@code{WindowsProactorEventLoopPolicy} classes.
(Contributed by Yury Selivanov in bpo-33792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33792}.)
@end itemize

Several @code{asyncio} APIs have been
@ref{d14,,deprecated}.

@node binascii,calendar<3>,asyncio<10>,改良されたモジュール<7>
@anchor{whatsnew/3 7 binascii}@anchor{d15}
@subsubsection binascii


The @ref{d16,,b2a_uu()} function now accepts an optional `backtick'
keyword argument.  When it's true, zeros are represented by @code{'`'}
instead of spaces.  (Contributed by Xiang Zhang in bpo-30103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30103}.)

@node calendar<3>,collections<2>,binascii,改良されたモジュール<7>
@anchor{whatsnew/3 7 calendar}@anchor{d17}
@subsubsection calendar


@ref{d18,,HTMLCalendar} クラスに、作成された HTML カレンダーの CSS クラスのカスタマイズを容易にするクラス属性が新しく加わりました。
(Contributed by Oz Tiram in bpo-30095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30095}.)

@node collections<2>,compileall<3>,calendar<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 collections}@anchor{d19}
@subsubsection collections


@code{collections.namedtuple()} がデフォルト値をサポートするようになりました。
(Contributed by Raymond Hettinger in bpo-32320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32320}.)

@node compileall<3>,concurrent futures<4>,collections<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 compileall}@anchor{d1a}
@subsubsection compileall


@ref{d1b,,compileall.compile_dir()} learned the new `invalidation_mode' parameter,
which can be used to enable
@ref{cc2,,hash-based .pyc invalidation}.  The invalidation
mode can also be specified on the command line using the new
@code{--invalidation-mode} argument.
(Contributed by Benjamin Peterson in bpo-31650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31650}.)

@node concurrent futures<4>,contextlib<3>,compileall<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 concurrent-futures}@anchor{d1c}
@subsubsection concurrent.futures


@ref{1d6,,ProcessPoolExecutor} と @ref{949,,ThreadPoolExecutor} が新しいコンストラクタ引数 `initializer' と `initargs' をサポートするようになりました。
(Contributed by Antoine Pitrou in bpo-21423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21423}.)

@ref{1d6,,ProcessPoolExecutor} が新しい `mp_context' 引数を通して multiprocessing の context を受け取れるようになりました。
(Contributed by Thomas Moreau in bpo-31540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31540}.)

@node contextlib<3>,cProfile<2>,concurrent futures<4>,改良されたモジュール<7>
@anchor{whatsnew/3 7 contextlib}@anchor{d1d}
@subsubsection contextlib


The new @ref{9ef,,nullcontext()} is a simpler and faster no-op
context manager than @ref{d1e,,ExitStack}.
(Contributed by Jesse-Bakker in bpo-10049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10049}.)

The new @ref{d1f,,asynccontextmanager()},
@ref{d20,,AbstractAsyncContextManager}, and
@ref{d21,,AsyncExitStack} have been added to
complement their synchronous counterparts.  (Contributed
by Jelle Zijlstra in bpo-29679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29679} and bpo-30241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30241},
and by Alexander Mohr and Ilya Kulakov in bpo-29302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29302}.)

@node cProfile<2>,crypt,contextlib<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 cprofile}@anchor{d22}
@subsubsection cProfile


The @ref{2b,,cProfile} command line now accepts @code{-m module_name} as an
alternative to script path.  (Contributed by Sanyam Khurana in bpo-21862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21862}.)

@node crypt,datetime<5>,cProfile<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 crypt}@anchor{d23}
@subsubsection crypt


The @code{crypt} module now supports the Blowfish hashing method.
(Contributed by Serhiy Storchaka in bpo-31664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31664}.)

The @code{mksalt()} function now allows specifying the number of rounds
for hashing.  (Contributed by Serhiy Storchaka in bpo-31702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31702}.)

@node datetime<5>,dbm<2>,crypt,改良されたモジュール<7>
@anchor{whatsnew/3 7 datetime}@anchor{d24}
@subsubsection datetime


The new @ref{82a,,datetime.fromisoformat()}
method constructs a @ref{4e2,,datetime} object from a string
in one of the formats output by
@ref{d25,,datetime.isoformat()}.
(Contributed by Paul Ganssle in bpo-15873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15873}.)

The @ref{7f6,,tzinfo} class now supports sub-minute offsets.
(Contributed by Alexander Belopolsky in bpo-5288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5288}.)

@node dbm<2>,decimal<2>,datetime<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 dbm}@anchor{d26}
@subsubsection dbm


@ref{36,,dbm.dumb} now supports reading read-only files and no longer writes the
index file when it is not changed.

@node decimal<2>,dis<4>,dbm<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 decimal}@anchor{d27}
@subsubsection decimal


The @ref{3a,,decimal} module now uses @ref{cb7,,context variables}
to store the decimal context.
(Contributed by Yury Selivanov in bpo-32630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32630}.)

@node dis<4>,distutils<4>,decimal<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 dis}@anchor{d28}
@subsubsection dis


The @ref{205,,dis()} function is now able to
disassemble nested code objects (the code of comprehensions, generator
expressions and nested functions, and the code used for building nested
classes).  The maximum depth of disassembly recursion is controlled by
the new `depth' parameter.
(Contributed by Serhiy Storchaka in bpo-11822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11822}.)

@node distutils<4>,enum<5>,dis<4>,改良されたモジュール<7>
@anchor{whatsnew/3 7 distutils}@anchor{d29}
@subsubsection distutils


@code{README.rst} is now included in the list of distutils standard READMEs and
therefore included in source distributions.
(Contributed by Ryan Gonzalez in bpo-11913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11913}.)

@node enum<5>,functools<4>,distutils<4>,改良されたモジュール<7>
@anchor{whatsnew/3 7 enum}@anchor{d2a}
@subsubsection enum


The @ref{842,,Enum} learned the new @code{_ignore_} class property,
which allows listing the names of properties which should not become
enum members.
(Contributed by Ethan Furman in bpo-31801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31801}.)

In Python 3.8, attempting to check for non-Enum objects in @ref{842,,Enum}
classes will raise a @ref{198,,TypeError} (e.g. @code{1 in Color}); similarly,
attempting to check for non-Flag objects in a @ref{835,,Flag} member will
raise @ref{198,,TypeError} (e.g. @code{1 in Perm.RW}); currently, both operations
return @ref{d2b,,False} instead and are deprecated.
(Contributed by Ethan Furman in bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217}.)

@node functools<4>,gc<5>,enum<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 functools}@anchor{d2c}
@subsubsection functools


@ref{84b,,functools.singledispatch()} now supports registering implementations
using type annotations.
(Contributed by Łukasz Langa in bpo-32227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32227}.)

@node gc<5>,hmac<3>,functools<4>,改良されたモジュール<7>
@anchor{whatsnew/3 7 gc}@anchor{d2d}
@subsubsection gc


The new @ref{d2e,,gc.freeze()} function allows freezing all objects tracked
by the garbage collector and excluding them from future collections.
This can be used before a POSIX @code{fork()} call to make the GC copy-on-write
friendly or to speed up collection.  The new @ref{d2f,,gc.unfreeze()} functions
reverses this operation.  Additionally, @ref{d30,,gc.get_freeze_count()} can
be used to obtain the number of frozen objects.
(Contributed by Li Zekun in bpo-31558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31558}.)

@node hmac<3>,http client,gc<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 hmac}@anchor{d31}
@subsubsection hmac


The @ref{6e,,hmac} module now has an optimized one-shot @ref{d32,,digest()}
function, which is up to three times faster than @ref{d33,,HMAC()}.
(Contributed by Christian Heimes in bpo-32433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32433}.)

@node http client,http server,hmac<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 http-client}@anchor{d34}
@subsubsection http.client


@ref{d35,,HTTPConnection} and @ref{d36,,HTTPSConnection}
now support the new `blocksize' argument for improved upload throughput.
(Contributed by Nir Soffer in bpo-31945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31945}.)

@node http server,idlelib と IDLE,http client,改良されたモジュール<7>
@anchor{whatsnew/3 7 http-server}@anchor{d37}
@subsubsection http.server


@ref{d38,,SimpleHTTPRequestHandler} now supports the HTTP
@code{If-Modified-Since} header.  The server returns the 304 response status if
the target file was not modified after the time specified in the header.
(Contributed by Pierre Quentel in bpo-29654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29654}.)

@ref{d38,,SimpleHTTPRequestHandler} accepts the new `directory'
argument, in addition to the new @code{--directory} command line argument.
With this parameter, the server serves the specified directory, by default it
uses the current working directory.
(Contributed by Stéphane Wirtel and Julien Palard in bpo-28707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28707}.)

The new @ref{d39,,ThreadingHTTPServer} class
uses threads to handle requests using @ref{d3a,,ThreadingMixIn}.
It is used when @code{http.server} is run with @code{-m}.
(Contributed by Julien Palard in bpo-31639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31639}.)

@node idlelib と IDLE,importlib<4>,http server,改良されたモジュール<7>
@anchor{whatsnew/3 7 idlelib-and-idle}@anchor{d3b}
@subsubsection idlelib と IDLE


自動補完におけるいくつもの修正。
(Contributed by Louie Lu in bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786}.)

Module Browser (on the File menu, formerly called Class Browser),
now displays nested functions and classes in addition to top-level
functions and classes.
(Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy
in bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262}.)

The Settings dialog (Options, Configure IDLE) has been partly rewritten
to improve both appearance and function.
(Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)

The font sample now includes a selection of non-Latin characters so that
users can better see the effect of selecting a particular font.
(Contributed by Terry Jan Reedy in bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802}.)
The sample can be edited to include other characters.
(Contributed by Serhiy Storchaka in bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860}.)

The IDLE features formerly implemented as extensions have been reimplemented
as normal features.  Their settings have been moved from the Extensions tab
to other dialog tabs.
(Contributed by Charles Wohlganger and Terry Jan Reedy in bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099}.)

Editor code context option revised.  Box displays all context lines up to
maxlines.  Clicking on a context line jumps the editor to that line.  Context
colors for custom themes is added to Highlights tab of Settings dialog.
(Contributed by Cheryl Sabella and Terry Jan Reedy in bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642},
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}, and bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}.)

On Windows, a new API call tells Windows 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.
(Contributed by Terry Jan Reedy in bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}.)

New in 3.7.1:

Output over N lines (50 by default) is squeezed down to a button.
N can be changed in the PyShell section of the General page of the
Settings dialog.  Fewer, but possibly extra long, lines can be squeezed by
right clicking on the output.  Squeezed output can be expanded in place
by double-clicking the button or into the clipboard or a separate window
by right-clicking the button.  (Contributed by Tal Einat in bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353}.)

上で挙げた変更は 3.6 のメンテナンスリリースにバックポートされました。

NEW in 3.7.4:

Add "Run Customized" to the Run menu to run a module with customized
settings. Any command line arguments entered are added to sys.argv.
They re-appear in the box for the next customized run.  One can also
suppress the normal Shell main module restart.  (Contributed by Cheryl
Sabella, Terry Jan Reedy, and others in bpo-5680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5680} and bpo-37627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37627}.)

New in 3.7.5:

Add optional line numbers for IDLE editor windows. Windows
open without line numbers unless set otherwise in the General
tab of the configuration dialog.  Line numbers for an existing
window are shown and hidden in the Options menu.
(Contributed by Tal Einat and Saimadhav Heblikar in bpo-17535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17535}.)

@node importlib<4>,io<6>,idlelib と IDLE,改良されたモジュール<7>
@anchor{whatsnew/3 7 importlib}@anchor{d3c}
@subsubsection importlib


The @code{importlib.abc.ResourceReader} ABC was introduced to
support the loading of resources from packages.  See also
@ref{cb9,,importlib.resources}.
(Contributed by Barry Warsaw, Brett Cannon in bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248}.)

@ref{73d,,importlib.reload()} now raises @ref{d3d,,ModuleNotFoundError} if the module
lacks a spec.
(Contributed by Garvit Khatri in bpo-29851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29851}.)

@ref{5af,,importlib.util.find_spec()} now raises @ref{d3d,,ModuleNotFoundError} instead of
@ref{5f0,,AttributeError} if the specified parent module is not a package (i.e.
lacks a @code{__path__} attribute).
(Contributed by Milan Oberkirch in bpo-30436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30436}.)

The new @ref{d3e,,importlib.util.source_hash()} can be used to compute the hash of
the passed source.  A @ref{cc2,,hash-based .pyc file}
embeds the value returned by this function.

@node io<6>,ipaddress<3>,importlib<4>,改良されたモジュール<7>
@anchor{whatsnew/3 7 io}@anchor{d3f}
@subsubsection io


The new @ref{d40,,TextIOWrapper.reconfigure()}
method can be used to reconfigure the text stream with the new settings.
(Contributed by Antoine Pitrou in bpo-30526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30526} and
INADA Naoki in bpo-15216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15216}.)

@node ipaddress<3>,itertools<6>,io<6>,改良されたモジュール<7>
@anchor{whatsnew/3 7 ipaddress}@anchor{d41}
@subsubsection ipaddress


The new @code{subnet_of()} and @code{supernet_of()} methods of
@ref{50f,,ipaddress.IPv6Network} and @ref{50e,,ipaddress.IPv4Network} can
be used for network containment tests.
(Contributed by Michel Albert and Cheryl Sabella in bpo-20825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20825}.)

@node itertools<6>,locale<4>,ipaddress<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 itertools}@anchor{d42}
@subsubsection itertools


@ref{d43,,itertools.islice()} now accepts
@ref{19e,,integer-like objects} as start, stop,
and slice arguments.
(Contributed by Will Roberts in bpo-30537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30537}.)

@node locale<4>,logging<3>,itertools<6>,改良されたモジュール<7>
@anchor{whatsnew/3 7 locale}@anchor{d44}
@subsubsection locale


The new `monetary' argument to @ref{742,,locale.format_string()} can be used
to make the conversion use monetary thousands separators and
grouping strings.  (Contributed by Garvit in bpo-10379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10379}.)

The @ref{75c,,locale.getpreferredencoding()} function now always returns @code{'UTF-8'}
on Android or when in the @ref{cc1,,forced UTF-8 mode}.

@node logging<3>,math<7>,locale<4>,改良されたモジュール<7>
@anchor{whatsnew/3 7 logging}@anchor{d45}
@subsubsection logging


@ref{d46,,Logger} インスタンスが pickle 化できるようになりました。
(Contributed by Vinay Sajip in bpo-30520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30520}.)

The new @ref{d47,,StreamHandler.setStream()}
method can be used to replace the logger stream after handler creation.
(Contributed by Vinay Sajip in bpo-30522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30522}.)

It is now possible to specify keyword arguments to handler constructors in
configuration passed to @ref{d48,,logging.config.fileConfig()}.
(Contributed by Preston Landers in bpo-31080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31080}.)

@node math<7>,mimetypes<3>,logging<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 math}@anchor{d49}
@subsubsection math


新しい @ref{d4a,,math.remainder()} 関数が IEEE 754 方式の剰余演算で実装されています。
Contributed by Mark Dickinson in bpo-29962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29962}.)

@node mimetypes<3>,msilib,math<7>,改良されたモジュール<7>
@anchor{whatsnew/3 7 mimetypes}@anchor{d4b}
@subsubsection mimetypes


The MIME type of .bmp has been changed from @code{'image/x-ms-bmp'} to
@code{'image/bmp'}.
(Contributed by Nitish Chandra in bpo-22589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22589}.)

@node msilib,multiprocessing<5>,mimetypes<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 msilib}@anchor{d4c}
@subsubsection msilib


The new @code{Database.Close()} method can be used
to close the @abbr{MSI} database.
(Contributed by Berker Peksag in bpo-20486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20486}.)

@node multiprocessing<5>,os<8>,msilib,改良されたモジュール<7>
@anchor{whatsnew/3 7 multiprocessing}@anchor{d4d}
@subsubsection multiprocessing


The new @ref{d4e,,Process.close()} method
explicitly closes the process object and releases all resources associated
with it.  @ref{2ec,,ValueError} is raised if the underlying process is still
running.
(Contributed by Antoine Pitrou in bpo-30596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30596}.)

The new @ref{d4f,,Process.kill()} method can
be used to terminate the process using the @ref{d50,,SIGKILL} signal on Unix.
(Contributed by Vitor Pereira in bpo-30794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30794}.)

Non-daemonic threads created by @ref{252,,Process} are now
joined on process exit.
(Contributed by Antoine Pitrou in bpo-18966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18966}.)

@node os<8>,pathlib<11>,multiprocessing<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 os}@anchor{d51}
@subsubsection os


@ref{d52,,os.fwalk()} now accepts the `path' argument as @ref{192,,bytes}.
(Contributed by Serhiy Storchaka in bpo-28682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28682}.)

@ref{c54,,os.scandir()} gained support for @ref{d53,,file descriptors}.
(Contributed by Serhiy Storchaka in bpo-25996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25996}.)

The new @ref{355,,register_at_fork()} function allows registering Python
callbacks to be executed at process fork.
(Contributed by Antoine Pitrou in bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500}.)

Added @ref{d54,,os.preadv()} (combine the functionality of @ref{d55,,os.readv()} and
@ref{d56,,os.pread()}) and @ref{d57,,os.pwritev()} functions (combine the functionality
of @ref{d58,,os.writev()} and @ref{d59,,os.pwrite()}). (Contributed by Pablo Galindo in
bpo-31368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31368}.)

The mode argument of @ref{52c,,os.makedirs()} no longer affects the file
permission bits of newly created intermediate-level directories.
(Contributed by Serhiy Storchaka in bpo-19930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19930}.)

@ref{d5a,,os.dup2()} now returns the new file descriptor.  Previously, @code{None}
was always returned.
(Contributed by Benjamin Peterson in bpo-32441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32441}.)

The structure returned by @ref{26d,,os.stat()} now contains the
@ref{d5b,,st_fstype} attribute on Solaris and its derivatives.
(Contributed by Jesús Cea Avión in bpo-32659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32659}.)

@node pathlib<11>,pdb<6>,os<8>,改良されたモジュール<7>
@anchor{whatsnew/3 7 pathlib}@anchor{d5c}
@subsubsection pathlib


The new @ref{c0c,,Path.is_mount()} method is now available
on POSIX systems and can be used to determine whether a path is a mount point.
(Contributed by Cooper Ry Lees in bpo-30897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30897}.)

@node pdb<6>,py_compile<3>,pathlib<11>,改良されたモジュール<7>
@anchor{whatsnew/3 7 pdb}@anchor{d5d}
@subsubsection pdb


@ref{272,,pdb.set_trace()} now takes an optional `header' keyword-only
argument.  If given, it is printed to the console just before debugging
begins.  (Contributed by Barry Warsaw in bpo-31389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31389}.)

@ref{aa,,pdb} command line now accepts @code{-m module_name} as an alternative to
script file.  (Contributed by Mario Corchero in bpo-32206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32206}.)

@node py_compile<3>,pydoc<3>,pdb<6>,改良されたモジュール<7>
@anchor{whatsnew/3 7 py-compile}@anchor{d5e}
@subsubsection py_compile


@ref{c1a,,py_compile.compile()} -- and by extension, @ref{21,,compileall} -- now
respects the 
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable by
unconditionally creating @code{.pyc} files for hash-based validation.
This allows for guaranteeing
reproducible builds@footnote{https://reproducible-builds.org/} of @code{.pyc}
files when they are created eagerly. (Contributed by Bernhard M. Wiedemann
in bpo-29708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29708}.)

@node pydoc<3>,queue<2>,py_compile<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 pydoc}@anchor{d5f}
@subsubsection pydoc


The pydoc server can now bind to an arbitrary hostname specified by the
new @code{-n} command-line argument.
(Contributed by Feanil Patel in bpo-31128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31128}.)

@node queue<2>,re<5>,pydoc<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 queue}@anchor{d60}
@subsubsection queue


The new @ref{d61,,SimpleQueue} class is an unbounded @abbr{FIFO} queue.
(Contributed by Antoine Pitrou in bpo-14976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14976}.)

@node re<5>,signal<2>,queue<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 re}@anchor{d62}
@subsubsection re


The flags @ref{83e,,re.ASCII}, @ref{d63,,re.LOCALE} and @ref{d64,,re.UNICODE}
can be set within the scope of a group.
(Contributed by Serhiy Storchaka in bpo-31690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31690}.)

@ref{5a2,,re.split()} now supports splitting on a pattern like @code{r'\b'},
@code{'^$'} or @code{(?=-)} that matches an empty string.
(Contributed by Serhiy Storchaka in bpo-25054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25054}.)

Regular expressions compiled with the @ref{d63,,re.LOCALE} flag no longer
depend on the locale at compile time.  Locale settings are applied only
when the compiled regular expression is used.
(Contributed by Serhiy Storchaka in bpo-30215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30215}.)

@ref{659,,FutureWarning} is now emitted if a regular expression contains
character set constructs that will change semantically in the future,
such as nested sets and set operations.
(Contributed by Serhiy Storchaka in bpo-30349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30349}.)

Compiled regular expression and match objects can now be copied
using @ref{757,,copy.copy()} and @ref{d65,,copy.deepcopy()}.
(Contributed by Serhiy Storchaka in bpo-10076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10076}.)

@node signal<2>,socket<6>,re<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 signal}@anchor{d66}
@subsubsection signal


The new `warn_on_full_buffer' argument to the @ref{d67,,signal.set_wakeup_fd()}
function makes it possible to specify whether Python prints a warning on
stderr when the wakeup buffer overflows.
(Contributed by Nathaniel J. Smith in bpo-30050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30050}.)

@node socket<6>,socketserver,signal<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 socket}@anchor{d68}
@subsubsection socket


The new @ref{d69,,socket.getblocking()} method
returns @code{True} if the socket is in blocking mode and @code{False} otherwise.
(Contributed by Yury Selivanov in bpo-32373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32373}.)

The new @ref{d6a,,socket.close()} function closes the passed socket file descriptor.
This function should be used instead of @ref{d6b,,os.close()} for better
compatibility across platforms.
(Contributed by Christian Heimes in bpo-32454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32454}.)

The @ref{d1,,socket} module now exposes the @ref{d6c,,socket.TCP_CONGESTION} (Linux 2.6.13), @ref{d6c,,socket.TCP_USER_TIMEOUT} (Linux 2.6.37), and @ref{d6c,,socket.TCP_NOTSENT_LOWAT} (Linux 3.12) constants.
(Contributed by Omar Sandoval in bpo-26273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26273} and
Nathaniel J. Smith in bpo-29728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29728}.)

Support for @ref{d6d,,socket.AF_VSOCK} sockets has been added to allow
communication between virtual machines and their hosts.
(Contributed by Cathy Avery in bpo-27584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27584}.)

Sockets now auto-detect family, type and protocol from file descriptor
by default.
(Contributed by Christian Heimes in bpo-28134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28134}.)

@node socketserver,sqlite3<7>,socket<6>,改良されたモジュール<7>
@anchor{whatsnew/3 7 socketserver}@anchor{d6e}
@subsubsection socketserver


@ref{d6f,,socketserver.ThreadingMixIn.server_close} now waits until all non-daemon
threads complete. @ref{d6f,,socketserver.ForkingMixIn.server_close} now waits
until all child processes complete.

Add a new @ref{d70,,socketserver.ForkingMixIn.block_on_close} class attribute to
@ref{d71,,socketserver.ForkingMixIn} and @ref{d3a,,socketserver.ThreadingMixIn}
classes. Set the class attribute to @code{False} to get the pre-3.7 behaviour.

@node sqlite3<7>,ssl<6>,socketserver,改良されたモジュール<7>
@anchor{whatsnew/3 7 sqlite3}@anchor{d72}
@subsubsection sqlite3


@ref{54d,,sqlite3.Connection} now exposes the @ref{d73,,backup()}
method when the underlying SQLite library is at version 3.6.11 or higher.
(Contributed by Lele Gaifax in bpo-27645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27645}.)

The `database' argument of @ref{5a6,,sqlite3.connect()} now accepts any
@ref{5a1,,path-like object}, instead of just a string.
(Contributed by Anders Lorentsen in bpo-31843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31843}.)

@node ssl<6>,string<2>,sqlite3<7>,改良されたモジュール<7>
@anchor{whatsnew/3 7 ssl}@anchor{d74}
@subsubsection ssl


The @ref{d5,,ssl} module now uses OpenSSL's builtin API instead of
@code{match_hostname()} to check a host name or an IP address.  Values
are validated during TLS handshake.  Any certificate validation error
including failing the host name check now raises
@ref{d75,,SSLCertVerificationError} and aborts the handshake with a proper
TLS Alert message.  The new exception contains additional information.
Host name validation can be customized with
@ref{d76,,SSLContext.hostname_checks_common_name}.
(Contributed by Christian Heimes in bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399}.)

@cartouche
@quotation 注釈 
The improved host name check requires a `libssl' implementation compatible
with OpenSSL 1.0.2 or 1.1.  Consequently, OpenSSL 0.9.8 and 1.0.1 are no
longer supported (see @ref{d77,,サポート対象プラットフォームからの除外} for more details).
The ssl module is mostly compatible with LibreSSL 2.7.2 and newer.
@end quotation
@end cartouche

The @code{ssl} module no longer sends IP addresses in SNI TLS extension.
(Contributed by Christian Heimes in bpo-32185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32185}.)

@code{match_hostname()} no longer supports partial wildcards like
@code{www*.example.org}.
(Contributed by Mandeep Singh in bpo-23033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23033} and Christian Heimes in
bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399}.)

The default cipher suite selection of the @code{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 updates.  Default cipher
suite selection can be configured at compile time.
(Contributed by Christian Heimes in bpo-31429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31429}.)

Validation of server certificates containing internationalized domain names
(IDNs) is now supported.  As part of this change, the
@ref{d78,,SSLSocket.server_hostname} attribute
now stores the expected hostname in A-label form (@code{"xn--pythn-mua.org"}),
rather than the U-label form (@code{"pythön.org"}).  (Contributed by
Nathaniel J. Smith and Christian Heimes in bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414}.)

The @code{ssl} module has preliminary and experimental support for TLS 1.3 and
OpenSSL 1.1.1.  At the time of Python 3.7.0 release, OpenSSL 1.1.1 is still
under development and TLS 1.3 hasn't been finalized yet.  The TLS 1.3
handshake and protocol behaves slightly differently than TLS 1.2 and earlier,
see @ref{d79,,TLS 1.3}.
(Contributed by Christian Heimes in bpo-32947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32947}, bpo-20995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20995},
bpo-29136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29136}, bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622} and bpo-33618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33618})

@ref{ae7,,SSLSocket} and @ref{d7a,,SSLObject} no longer have a public
constructor.  Direct instantiation was never a documented and supported
feature.  Instances must be created with @ref{357,,SSLContext} methods
@ref{748,,wrap_socket()} and @ref{d7b,,wrap_bio()}.
(Contributed by Christian Heimes in bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951})

OpenSSL 1.1 APIs for setting the minimum and maximum TLS protocol version are
available as @ref{a70,,SSLContext.minimum_version}
and @ref{a71,,SSLContext.maximum_version}.
Supported protocols are indicated by several new flags, such as
@ref{d7c,,HAS_TLSv1_1}.
(Contributed by Christian Heimes in bpo-32609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32609}.)

Added @ref{c26,,ssl.SSLContext.post_handshake_auth} to enable and
@ref{c27,,ssl.SSLSocket.verify_client_post_handshake()} to initiate TLS 1.3
post-handshake authentication.
(Contributed by Christian Heimes in gh-78851@footnote{https://github.com/python/cpython/issues/78851}.)

@node string<2>,subprocess<2>,ssl<6>,改良されたモジュール<7>
@anchor{whatsnew/3 7 string}@anchor{d7d}
@subsubsection string


@ref{897,,string.Template} now lets you to optionally modify the regular
expression pattern for braced placeholders and non-braced placeholders
separately.  (Contributed by Barry Warsaw in bpo-1198569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1198569}.)

@node subprocess<2>,sys<8>,string<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 subprocess}@anchor{d7e}
@subsubsection subprocess


The @ref{d7f,,subprocess.run()} function accepts the new `capture_output'
keyword argument.  When true, stdout and stderr will be captured.
This is equivalent to passing @ref{d80,,subprocess.PIPE} as `stdout' and
`stderr' arguments.
(Contributed by Bo Bayles in bpo-32102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32102}.)

The @code{subprocess.run} function and the @ref{4b7,,subprocess.Popen} constructor
now accept the `text' keyword argument as an alias
to `universal_newlines'.
(Contributed by Andrew Clegg in bpo-31756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31756}.)

On Windows the default for `close_fds' was changed from @code{False} to
@code{True} when redirecting the standard handles.  It's now possible to set
`close_fds' to true when redirecting the standard handles.  See
@ref{4b7,,subprocess.Popen}.  This means that `close_fds' now defaults to
@code{True} on all supported platforms.
(Contributed by Segev Finer in bpo-19764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19764}.)

The subprocess module is now more graceful when handling
@ref{bc5,,KeyboardInterrupt} during @ref{d81,,subprocess.call()},
@ref{d7f,,subprocess.run()}, or in a @ref{4b7,,Popen}
context manager.  It now waits a short amount of time for the child
to exit, before continuing the handling of the @code{KeyboardInterrupt}
exception.
(Contributed by Gregory P. Smith in bpo-25942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25942}.)

@node sys<8>,time<5>,subprocess<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 sys}@anchor{d82}
@subsubsection sys


The new @ref{cd1,,sys.breakpointhook()} hook function is called by the
built-in @ref{271,,breakpoint()}.
(Contributed by Barry Warsaw in bpo-31353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31353}.)

On Android, the new @ref{d83,,sys.getandroidapilevel()} returns the build-time
Android API version.
(Contributed by Victor Stinner in bpo-28740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28740}.)

The new @ref{d84,,sys.get_coroutine_origin_tracking_depth()} function returns
the current coroutine origin tracking depth, as set by
the new @ref{d85,,sys.set_coroutine_origin_tracking_depth()}.  @ref{b,,asyncio}
has been converted to use this new API instead of
the deprecated @code{sys.set_coroutine_wrapper()}.
(Contributed by Nathaniel J. Smith in bpo-32591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32591}.)

@node time<5>,tkinter<6>,sys<8>,改良されたモジュール<7>
@anchor{whatsnew/3 7 time}@anchor{d86}
@subsubsection time


@geindex Python Enhancement Proposals; PEP 564
PEP 564@footnote{https://peps.python.org/pep-0564/} adds six new functions with nanosecond resolution to the
@ref{f4,,time} module:


@itemize *

@item 
@ref{cdb,,time.clock_gettime_ns()}

@item 
@ref{cdc,,time.clock_settime_ns()}

@item 
@ref{cdd,,time.monotonic_ns()}

@item 
@ref{cde,,time.perf_counter_ns()}

@item 
@ref{cdf,,time.process_time_ns()}

@item 
@ref{ce0,,time.time_ns()}
@end itemize

New clock identifiers have been added:


@itemize *

@item 
@ref{d87,,time.CLOCK_BOOTTIME} (Linux): Identical to
@ref{8a8,,time.CLOCK_MONOTONIC}, except it also includes any time that the
system is suspended.

@item 
@ref{d88,,time.CLOCK_PROF} (FreeBSD, NetBSD and OpenBSD): High-resolution
per-process CPU timer.

@item 
@ref{d89,,time.CLOCK_UPTIME} (FreeBSD, OpenBSD): Time whose absolute value is
the time the system has been running and not suspended, providing accurate
uptime measurement.
@end itemize

The new @ref{b30,,time.thread_time()} and @ref{d8a,,time.thread_time_ns()} functions
can be used to get per-thread CPU time measurements.
(Contributed by Antoine Pitrou in bpo-32025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32025}.)

The new @ref{d8b,,time.pthread_getcpuclockid()} function returns the clock ID
of the thread-specific CPU-time clock.

@node tkinter<6>,tracemalloc<2>,time<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 tkinter}@anchor{d8c}
@subsubsection tkinter


The new @ref{d8d,,tkinter.ttk.Spinbox} class is now available.
(Contributed by Alan Moore in bpo-32585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32585}.)

@node tracemalloc<2>,types<5>,tkinter<6>,改良されたモジュール<7>
@anchor{whatsnew/3 7 tracemalloc}@anchor{d8e}
@subsubsection tracemalloc


@ref{d8f,,tracemalloc.Traceback} behaves more like regular tracebacks,
sorting the frames from oldest to most recent.
@ref{d90,,Traceback.format()}
now accepts negative `limit', truncating the result to the
@code{abs(limit)} oldest frames.  To get the old behaviour, use
the new `most_recent_first' argument to @code{Traceback.format()}.
(Contributed by Jesse Bakker in bpo-32121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32121}.)

@node types<5>,unicodedata<7>,tracemalloc<2>,改良されたモジュール<7>
@anchor{whatsnew/3 7 types}@anchor{d91}
@subsubsection types


The new @ref{d92,,WrapperDescriptorType},
@ref{85b,,MethodWrapperType}, @ref{d93,,MethodDescriptorType},
and @ref{d94,,ClassMethodDescriptorType} classes are now available.
(Contributed by Manuel Krebber and Guido van Rossum in bpo-29377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29377},
and Serhiy Storchaka in bpo-32265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32265}.)

The new @ref{d95,,types.resolve_bases()} function resolves MRO entries
dynamically as specified by 
@geindex Python Enhancement Proposals; PEP 560
PEP 560@footnote{https://peps.python.org/pep-0560/}.
(Contributed by Ivan Levkivskyi in bpo-32717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32717}.)

@node unicodedata<7>,unittest<8>,types<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 unicodedata}@anchor{d96}
@subsubsection unicodedata


The internal @ref{10b,,unicodedata} database has been upgraded to use Unicode 11@footnote{https://www.unicode.org/versions/Unicode11.0.0/}. (Contributed by Benjamin
Peterson.)

@node unittest<8>,unittest mock,unicodedata<7>,改良されたモジュール<7>
@anchor{whatsnew/3 7 unittest}@anchor{d97}
@subsubsection unittest


The new @code{-k} command-line option allows filtering tests by a name
substring or a Unix shell-like pattern.
For example, @code{python -m unittest -k foo} runs
@code{foo_tests.SomeTest.test_something}, @code{bar_tests.SomeTest.test_foo},
but not @code{bar_tests.FooTest.test_something}.
(Contributed by Jonas Haag in bpo-32071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32071}.)

@node unittest mock,urllib parse<5>,unittest<8>,改良されたモジュール<7>
@anchor{whatsnew/3 7 unittest-mock}@anchor{d98}
@subsubsection unittest.mock


The @ref{d99,,sentinel} attributes now preserve their identity
when they are @ref{29,,copied} or @ref{ab,,pickled}. (Contributed by
Serhiy Storchaka in bpo-20804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20804}.)

The new @ref{d9a,,seal()} function allows sealing
@ref{c3f,,Mock} instances, which will disallow further creation
of attribute mocks.  The seal is applied recursively to all attributes that
are themselves mocks.
(Contributed by Mario Corchero in bpo-30541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30541}.)

@node urllib parse<5>,uu,unittest mock,改良されたモジュール<7>
@anchor{whatsnew/3 7 urllib-parse}@anchor{d9b}
@subsubsection urllib.parse


@ref{d9c,,urllib.parse.quote()} has been updated from 
@geindex RFC; RFC 2396
RFC 2396@footnote{https://datatracker.ietf.org/doc/html/rfc2396.html} to 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html},
adding @code{~} to the set of characters that are never quoted by default.
(Contributed by Christian Theune and Ratnadeep Debnath in bpo-16285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16285}.)

@node uu,uuid<4>,urllib parse<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 uu}@anchor{d9d}
@subsubsection uu


The @code{uu.encode()} function now accepts an optional `backtick'
keyword argument.  When it's true, zeros are represented by @code{'`'}
instead of spaces.  (Contributed by Xiang Zhang in bpo-30103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30103}.)

@node uuid<4>,warnings<3>,uu,改良されたモジュール<7>
@anchor{whatsnew/3 7 uuid}@anchor{d9e}
@subsubsection uuid


The new @ref{d9f,,UUID.is_safe} attribute relays information
from the platform about whether generated UUIDs are generated with a
multiprocessing-safe method.
(Contributed by Barry Warsaw in bpo-22807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22807}.)

@ref{da0,,uuid.getnode()} now prefers universally administered
MAC addresses over locally administered MAC addresses.
This makes a better guarantee for global uniqueness of UUIDs returned
from @ref{da1,,uuid.uuid1()}.  If only locally administered MAC addresses are
available, the first such one found is returned.
(Contributed by Barry Warsaw in bpo-32107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32107}.)

@node warnings<3>,xml<5>,uuid<4>,改良されたモジュール<7>
@anchor{whatsnew/3 7 warnings}@anchor{da2}
@subsubsection warnings


The initialization of the default warnings filters has changed as follows:


@itemize *

@item 
warnings enabled via command line options (including those for @ref{7f9,,-b}
and the new CPython-specific @ref{16f,,-X} @code{dev} option) are always passed
to the warnings machinery via the @ref{3f5,,sys.warnoptions} attribute.

@item 
warnings filters enabled via the command line or the environment now have the
following order of precedence:


@itemize *

@item 
the @code{BytesWarning} filter for @ref{7f9,,-b} (or @code{-bb})

@item 
any filters specified with the @ref{ac6,,-W} option

@item 
any filters specified with the 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} environment
variable

@item 
any other CPython specific filters (e.g. the @code{default} filter added
for the new @code{-X dev} mode)

@item 
any implicit filters defined directly by the warnings machinery
@end itemize

@item 
in @ref{509,,CPython debug builds}, all warnings are now displayed
by default (the implicit filter list is empty)
@end itemize

(Contributed by Nick Coghlan and Victor Stinner in bpo-20361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20361},
bpo-32043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32043}, and bpo-32230@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32230}.)

Deprecation warnings are once again shown by default in single-file scripts and
at the interactive prompt.  See @ref{cc4,,PEP 565; Show DeprecationWarning in __main__} for details.
(Contributed by Nick Coghlan in bpo-31975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31975}.)

@node xml<5>,xml etree,warnings<3>,改良されたモジュール<7>
@anchor{whatsnew/3 7 xml}@anchor{da4}
@subsubsection xml


As mitigation against DTD and external entity retrieval, the
@ref{128,,xml.dom.minidom} and @ref{12f,,xml.sax} modules no longer process
external entities by default.
(Contributed by Christian Heimes in gh-61441@footnote{https://github.com/python/cpython/issues/61441}.)

@node xml etree,xmlrpc server,xml<5>,改良されたモジュール<7>
@anchor{whatsnew/3 7 xml-etree}@anchor{da5}
@subsubsection xml.etree


@ref{da6,,ElementPath} predicates in the @code{find()}
methods can now compare text of the current node with @code{[. = "text"]},
not only text in children.  Predicates also allow adding spaces for
better readability.  (Contributed by Stefan Behnel in bpo-31648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31648}.)

@node xmlrpc server,zipapp,xml etree,改良されたモジュール<7>
@anchor{whatsnew/3 7 xmlrpc-server}@anchor{da7}
@subsubsection xmlrpc.server


@code{SimpleXMLRPCDispatcher.register_function()}
can now be used as a decorator.  (Contributed by Xiang Zhang in
bpo-7769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7769}.)

@node zipapp,zipfile<3>,xmlrpc server,改良されたモジュール<7>
@anchor{whatsnew/3 7 zipapp}@anchor{da8}
@subsubsection zipapp


Function @ref{da9,,create_archive()} now accepts an optional `filter'
argument to allow the user to select which files should be included in the
archive.  (Contributed by Irmen de Jong in bpo-31072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31072}.)

Function @ref{da9,,create_archive()} now accepts an optional `compressed'
argument to generate a compressed archive.  A command line option
@code{--compress} has also been added to support compression.
(Contributed by Zhiming Wang in bpo-31638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31638}.)

@node zipfile<3>,,zipapp,改良されたモジュール<7>
@anchor{whatsnew/3 7 zipfile}@anchor{daa}
@subsubsection zipfile


@ref{8d3,,ZipFile} now accepts the new `compresslevel' parameter to
control the compression level.
(Contributed by Bo Bayles in bpo-21417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21417}.)

Subdirectories in archives created by @code{ZipFile} are now stored in
alphabetical order.
(Contributed by Bernhard M. Wiedemann in bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}.)

@node C API の変更<11>,Build Changes<6>,改良されたモジュール<7>,What's New In Python 3 7
@anchor{whatsnew/3 7 c-api-changes}@anchor{dab}
@subsection C API の変更


A new API for thread-local storage has been implemented.  See
@ref{cc5,,PEP 539; スレッドローカルストレージのための新しい C API} for an overview and
@ref{cd5,,スレッド固有ストレージ (Thread Specific Storage@comma{} TSS) API} for a complete reference.
(Contributed by Masayuki Yamamoto in bpo-25658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25658}.)

The new @ref{cb7,,context variables} functionality
exposes a number of @ref{cf0,,new C APIs}.

The new @ref{dac,,PyImport_GetModule()} function returns the previously
imported module with the given name.
(Contributed by Eric Snow in bpo-28411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28411}.)

The new @ref{dad,,Py_RETURN_RICHCOMPARE} macro eases writing rich
comparison functions.
(Contributed by Petr Victorin in bpo-23699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23699}.)

The new @ref{dae,,Py_UNREACHABLE} macro can be used to mark unreachable
code paths.
(Contributed by Barry Warsaw in bpo-31338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31338}.)

The @ref{105,,tracemalloc} now exposes a C API through the new
@ref{daf,,PyTraceMalloc_Track()} and @ref{db0,,PyTraceMalloc_Untrack()}
functions.
(Contributed by Victor Stinner in bpo-30054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30054}.)

The new @ref{db1,,import__find__load__start} and
@ref{db1,,import__find__load__done} static markers can be used
to trace module imports.
(Contributed by Christian Heimes in bpo-31574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31574}.)

The fields @code{name} and @code{doc} of structures
@ref{771,,PyMemberDef}, @ref{db2,,PyGetSetDef},
@ref{db3,,PyStructSequence_Field}, @ref{db4,,PyStructSequence_Desc},
and @code{wrapperbase} are now of type @code{const char *} rather of
@code{char *}.  (Contributed by Serhiy Storchaka in bpo-28761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28761}.)

The result of @ref{a99,,PyUnicode_AsUTF8AndSize()} and @ref{424,,PyUnicode_AsUTF8()}
is now of type @code{const char *} rather of @code{char *}. (Contributed by Serhiy
Storchaka in bpo-28769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28769}.)

The result of @ref{db5,,PyMapping_Keys()}, @ref{db6,,PyMapping_Values()} and
@ref{db7,,PyMapping_Items()} is now always a list, rather than a list or a
tuple. (Contributed by Oren Milman in bpo-28280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28280}.)

Added functions @ref{432,,PySlice_Unpack()} and @ref{433,,PySlice_AdjustIndices()}.
(Contributed by Serhiy Storchaka in bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}.)

@ref{42f,,PyOS_AfterFork()} is deprecated in favour of the new functions
@ref{db8,,PyOS_BeforeFork()}, @ref{db9,,PyOS_AfterFork_Parent()} and
@ref{430,,PyOS_AfterFork_Child()}.  (Contributed by Antoine Pitrou in
bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500}.)

The @code{PyExc_RecursionErrorInst} singleton that was part of the public API
has been removed as its members being never cleared may cause a segfault
during finalization of the interpreter. Contributed by Xavier de Gaye in
bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898} and bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697}.

Added C API support for timezones with timezone constructors
@ref{dba,,PyTimeZone_FromOffset()} and @ref{dbb,,PyTimeZone_FromOffsetAndName()},
and access to the UTC singleton with @ref{dbc,,PyDateTime_TimeZone_UTC}.
Contributed by Paul Ganssle in bpo-10381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10381}.

The type of results of @code{PyThread_start_new_thread()} and
@code{PyThread_get_thread_ident()}, and the `id' parameter of
@ref{dbd,,PyThreadState_SetAsyncExc()} changed from long to
unsigned long.
(Contributed by Serhiy Storchaka in bpo-6532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6532}.)

@ref{ab9,,PyUnicode_AsWideCharString()} now raises a @ref{2ec,,ValueError} if the
second argument is @code{NULL} and the wchar_t* string contains null
characters.  (Contributed by Serhiy Storchaka in bpo-30708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30708}.)

Changes to the startup sequence and the management of dynamic memory
allocators mean that the long documented requirement to call
@ref{460,,Py_Initialize()} before calling most C API functions is now
relied on more heavily, and failing to abide by it may lead to segfaults in
embedding applications. See the @ref{cc8,,Python 3.7 への移植} section in this
document and the @ref{dbe,,Python 初期化以前} section in the C API documentation
for more details.

The new @ref{dbf,,PyInterpreterState_GetID()} returns the unique ID for a
given interpreter.
(Contributed by Eric Snow in bpo-29102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29102}.)

@ref{dc0,,Py_DecodeLocale()}, @ref{dc1,,Py_EncodeLocale()} now use the UTF-8
encoding when the @ref{cc1,,UTF-8 mode} is enabled.
(Contributed by Victor Stinner in bpo-29240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29240}.)

@ref{dc2,,PyUnicode_DecodeLocaleAndSize()} and @ref{dc3,,PyUnicode_EncodeLocale()}
now use the current locale encoding for @code{surrogateescape} error handler.
(Contributed by Victor Stinner in bpo-29240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29240}.)

The `start' and `end' parameters of @ref{ab6,,PyUnicode_FindChar()} are
now adjusted to behave like string slices.
(Contributed by Xiang Zhang in bpo-28822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28822}.)

@node Build Changes<6>,最適化<8>,C API の変更<11>,What's New In Python 3 7
@anchor{whatsnew/3 7 build-changes}@anchor{dc4}
@subsection Build Changes


Support for building @code{--without-threads} has been removed.  The
@ref{f3,,threading} module is now always available.
(Contributed by Antoine Pitrou in bpo-31370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31370}.).

A full copy of libffi is no longer bundled for use when building the
@ref{2e,,_ctypes} module on non-OSX UNIX platforms.  An installed copy
of libffi is now required when building @code{_ctypes} on such platforms.
(Contributed by Zachary Ware in bpo-27979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27979}.)

The Windows build process no longer depends on Subversion to pull in external
sources, a Python script is used to download zipfiles from GitHub instead.
If Python 3.6 is not found on the system (via @code{py -3.6}), NuGet is used to
download a copy of 32-bit Python for this purpose.  (Contributed by Zachary
Ware in bpo-30450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30450}.)

The @ref{d5,,ssl} module requires OpenSSL 1.0.2 or 1.1 compatible libssl.
OpenSSL 1.0.1 has reached end of lifetime on 2016-12-31 and is no longer
supported. LibreSSL is temporarily not supported as well. LibreSSL releases
up to version 2.6.4 are missing required OpenSSL 1.0.2 APIs.

@node 最適化<8>,その他の CPython の実装の変更<2>,Build Changes<6>,What's New In Python 3 7
@anchor{whatsnew/3 7 optimizations}@anchor{dc5}@anchor{whatsnew/3 7 whatsnew37-perf}@anchor{cc7}
@subsection 最適化


The overhead of calling many methods of various standard library classes
implemented in C has been significantly reduced by porting more code
to use the @code{METH_FASTCALL} convention.
(Contributed by Victor Stinner in bpo-29300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29300}, bpo-29507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29507},
bpo-29452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29452}, and bpo-29286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29286}.)

Various optimizations have reduced Python startup time by 10% on Linux and
up to 30% on macOS.
(Contributed by Victor Stinner, INADA Naoki in bpo-29585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29585}, and
Ivan Levkivskyi in bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333}.)

Method calls are now up to 20% faster due to the bytecode changes which
avoid creating bound method instances.
(Contributed by Yury Selivanov and INADA Naoki in bpo-26110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26110}.)
@anchor{whatsnew/3 7 whatsnew37-asyncio-perf}@anchor{cf9}
The @ref{b,,asyncio} module received a number of notable optimizations for
commonly used functions:


@itemize *

@item 
The @ref{2f2,,asyncio.get_event_loop()} function has been reimplemented in C to
make it up to 15 times faster.
(Contributed by Yury Selivanov in bpo-32296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32296}.)

@item 
@ref{dc6,,asyncio.Future} callback management has been optimized.
(Contributed by Yury Selivanov in bpo-32348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32348}.)

@item 
@ref{813,,asyncio.gather()} is now up to 15% faster.
(Contributed by Yury Selivanov in bpo-32355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32355}.)

@item 
@ref{c64,,asyncio.sleep()} is now up to 2 times faster when the `delay'
argument is zero or negative.
(Contributed by Andrew Svetlov in bpo-32351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32351}.)

@item 
The performance overhead of asyncio debug mode has been reduced.
(Contributed by Antoine Pitrou in bpo-31970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31970}.)
@end itemize

As a result of @ref{cbc,,PEP 560 work}, the import time
of @ref{10a,,typing} has been reduced by a factor of 7, and many typing operations
are now faster.
(Contributed by Ivan Levkivskyi in bpo-32226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32226}.)

@ref{dc7,,sorted()} and @ref{dc8,,list.sort()} have been optimized for common cases
to be up to 40-75% faster.
(Contributed by Elliot Gorokhovsky in bpo-28685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28685}.)

@ref{dc9,,dict.copy()} is now up to 5.5 times faster.
(Contributed by Yury Selivanov in bpo-31179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31179}.)

@ref{6f9,,hasattr()} and @ref{dca,,getattr()} are now about 4 times faster when
`name' is not found and `obj' does not override @ref{6fa,,object.__getattr__()}
or @ref{dcb,,object.__getattribute__()}.
(Contributed by INADA Naoki in bpo-32544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32544}.)

Searching for certain Unicode characters (like Ukrainian capital "Є")
in a string was up to 25 times slower than searching for other characters.
It is now only 3 times slower in the worst case.
(Contributed by Serhiy Storchaka in bpo-24821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24821}.)

The @ref{4e0,,collections.namedtuple()} factory has been reimplemented to
make the creation of named tuples 4 to 6 times faster.
(Contributed by Jelle Zijlstra with further improvements by INADA Naoki,
Serhiy Storchaka, and Raymond Hettinger in bpo-28638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28638}.)

@ref{dcc,,datetime.date.fromordinal()} and @ref{dcd,,datetime.date.fromtimestamp()}
are now up to 30% faster in the common case.
(Contributed by Paul Ganssle in bpo-32403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32403}.)

The @ref{d52,,os.fwalk()} function is now up to 2 times faster thanks to
the use of @ref{c54,,os.scandir()}.
(Contributed by Serhiy Storchaka in bpo-25996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25996}.)

The speed of the @ref{356,,shutil.rmtree()} function has been improved by
20--40% thanks to the use of the @ref{c54,,os.scandir()} function.
(Contributed by Serhiy Storchaka in bpo-28564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28564}.)

Optimized case-insensitive matching and searching of @ref{be,,regular expressions}.  Searching some patterns can now be up to 20 times faster.
(Contributed by Serhiy Storchaka in bpo-30285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30285}.)

@ref{dce,,re.compile()} now converts @code{flags} parameter to int object if
it is @code{RegexFlag}.  It is now as fast as Python 3.5, and faster than
Python 3.6 by about 10% depending on the pattern.
(Contributed by INADA Naoki in bpo-31671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31671}.)

The @ref{dcf,,modify()} methods of classes
@ref{dd0,,selectors.EpollSelector}, @ref{dd1,,selectors.PollSelector}
and @ref{dd2,,selectors.DevpollSelector} may be around 10% faster under
heavy loads.  (Contributed by Giampaolo Rodola' in bpo-30014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30014})

Constant folding has been moved from the peephole optimizer to the new AST
optimizer, which is able perform optimizations more consistently.
(Contributed by Eugene Toder and INADA Naoki in bpo-29469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29469} and
bpo-11549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11549}.)

Most functions and methods in @ref{4,,abc} have been rewritten in C.
This makes creation of abstract base classes, and calling @ref{2ad,,isinstance()}
and @ref{9c4,,issubclass()} on them 1.5x faster.  This also reduces Python
start-up time by up to 10%. (Contributed by Ivan Levkivskyi and INADA Naoki
in bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333})

Significant speed improvements to alternate constructors for
@ref{1fa,,datetime.date} and @ref{4e2,,datetime.datetime} by using fast-path
constructors when not constructing subclasses. (Contributed by Paul Ganssle
in bpo-32403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32403})

The speed of comparison of @ref{4be,,array.array} instances has been
improved considerably in certain cases.  It is now from 10x to 70x faster
when comparing arrays holding values of the same integer type.
(Contributed by Adrian Wielgosik in bpo-24700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24700}.)

The @ref{dd3,,math.erf()} and @ref{dd4,,math.erfc()} functions now use the (faster)
C library implementation on most platforms.
(Contributed by Serhiy Storchaka in bpo-26121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26121}.)

@node その他の CPython の実装の変更<2>,非推奨の Python の挙動,最適化<8>,What's New In Python 3 7
@anchor{whatsnew/3 7 other-cpython-implementation-changes}@anchor{dd5}
@subsection その他の CPython の実装の変更



@itemize *

@item 
Trace hooks may now opt out of receiving the @code{line} and opt into receiving
the @code{opcode} events from the interpreter by setting the corresponding new
@ref{dd6,,f_trace_lines} and @ref{dd7,,f_trace_opcodes} attributes on the
frame being traced. (Contributed by Nick Coghlan in bpo-31344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31344}.)

@item 
Fixed some consistency problems with namespace package module attributes.
Namespace module objects now have an @code{__file__} that is set to @code{None}
(previously unset), and their @code{__spec__.origin} is also set to @code{None}
(previously the string @code{"namespace"}).  See bpo-32305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32305}.  Also, the
namespace module object's @code{__spec__.loader} is set to the same value as
@code{__loader__} (previously, the former was set to @code{None}).  See
bpo-32303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32303}.

@item 
The @ref{46f,,locals()} dictionary now displays in the lexical order that
variables were defined.  Previously, the order was undefined.
(Contributed by Raymond Hettinger in bpo-32690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32690}.)

@item 
The @code{distutils} @code{upload} command no longer tries to change CR
end-of-line characters to CRLF.  This fixes a corruption issue with sdists
that ended with a byte equivalent to CR.
(Contributed by Bo Bayles in bpo-32304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32304}.)
@end itemize

@node 非推奨の Python の挙動,非推奨の Python モジュール、関数、メソッド,その他の CPython の実装の変更<2>,What's New In Python 3 7
@anchor{whatsnew/3 7 deprecated-python-behavior}@anchor{dd8}
@subsection 非推奨の Python の挙動


Yield expressions (both @code{yield} and @code{yield from} clauses) are now deprecated
in comprehensions and generator expressions (aside from the iterable expression
in the leftmost @code{for} clause). This ensures that comprehensions
always immediately return a container of the appropriate type (rather than
potentially returning a @ref{dd9,,generator iterator} object), while generator
expressions won't attempt to interleave their implicit output with the output
from any explicit yield expressions.  In Python 3.7, such expressions emit
@ref{1a3,,DeprecationWarning} when compiled, in Python 3.8 this will be a
@ref{18e,,SyntaxError}.
(Contributed by Serhiy Storchaka in bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544}.)

Returning a subclass of @ref{197,,complex} from @ref{7fd,,object.__complex__()} is
deprecated and will be an error in future Python versions.  This makes
@code{__complex__()} consistent with @ref{19d,,object.__int__()} and
@ref{bc1,,object.__float__()}.
(Contributed by Serhiy Storchaka in bpo-28894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28894}.)

@node 非推奨の Python モジュール、関数、メソッド,C API の非推奨の関数ならびに型,非推奨の Python の挙動,What's New In Python 3 7
@anchor{whatsnew/3 7 deprecated-python-modules-functions-and-methods}@anchor{dda}
@subsection 非推奨の Python モジュール、関数、メソッド


@menu
* aifc:: 
* asyncio: asyncio<11>. 
* collections: collections<3>. 
* dbm: dbm<3>. 
* enum: enum<6>. 
* gettext: gettext<2>. 
* importlib: importlib<5>. 
* locale: locale<5>. 
* macpath:: 
* threading: threading<6>. 
* socket: socket<7>. 
* ssl: ssl<7>. 
* sunau:: 
* sys: sys<9>. 
* wave:: 

@end menu

@node aifc,asyncio<11>,,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 aifc}@anchor{ddb}
@subsubsection aifc


@code{aifc.openfp()} has been deprecated and will be removed in Python 3.9.
Use @code{aifc.open()} instead.
(Contributed by Brian Curtin in bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985}.)

@node asyncio<11>,collections<3>,aifc,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id2}@anchor{ddc}@anchor{whatsnew/3 7 whatsnew37-asyncio-deprecated}@anchor{d14}
@subsubsection asyncio


Support for directly @code{await}-ing instances of @ref{c66,,asyncio.Lock} and
other asyncio synchronization primitives has been deprecated.  An
asynchronous context manager must be used in order to acquire and release
the synchronization resource.
(Contributed by Andrew Svetlov in bpo-32253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32253}.)

The @code{asyncio.Task.current_task()} and @code{asyncio.Task.all_tasks()}
methods have been deprecated.
(Contributed by Andrew Svetlov in bpo-32250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32250}.)

@node collections<3>,dbm<3>,asyncio<11>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id3}@anchor{ddd}
@subsubsection collections


In Python 3.8, the abstract base classes in @ref{1f,,collections.abc} will no
longer be exposed in the regular @ref{1e,,collections} module.  This will help
create a clearer distinction between the concrete classes and the abstract
base classes.
(Contributed by Serhiy Storchaka in bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}.)

@node dbm<3>,enum<6>,collections<3>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id4}@anchor{dde}
@subsubsection dbm


@ref{36,,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 missing and recreated in the @code{'r'} and @code{'w'}
modes (this will be an error in future Python releases).
(Contributed by Serhiy Storchaka in bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847}.)

@node enum<6>,gettext<2>,dbm<3>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id5}@anchor{ddf}
@subsubsection enum


In Python 3.8, attempting to check for non-Enum objects in @ref{842,,Enum}
classes will raise a @ref{198,,TypeError} (e.g. @code{1 in Color}); similarly,
attempting to check for non-Flag objects in a @ref{835,,Flag} member will
raise @ref{198,,TypeError} (e.g. @code{1 in Perm.RW}); currently, both operations
return @ref{d2b,,False} instead.
(Contributed by Ethan Furman in bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217}.)

@node gettext<2>,importlib<5>,enum<6>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 gettext}@anchor{de0}
@subsubsection gettext


Using non-integer value for selecting a plural form in @ref{67,,gettext} is
now deprecated.  It never correctly worked. (Contributed by Serhiy Storchaka
in bpo-28692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28692}.)

@node importlib<5>,locale<5>,gettext<2>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id6}@anchor{de1}
@subsubsection importlib


Methods
@code{MetaPathFinder.find_module()}
(replaced by
@ref{a68,,MetaPathFinder.find_spec()})
and
@code{PathEntryFinder.find_loader()}
(replaced by
@ref{a6c,,PathEntryFinder.find_spec()})
both deprecated in Python 3.4 now emit @ref{1a3,,DeprecationWarning}.
(Contributed by Matthias Bussonnier in bpo-29576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29576}.)

The @ref{de2,,importlib.abc.ResourceLoader} ABC has been deprecated in
favour of @code{importlib.abc.ResourceReader}.

@node locale<5>,macpath,importlib<5>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id7}@anchor{de3}
@subsubsection locale


@code{locale.format()} has been deprecated, use @ref{742,,locale.format_string()}
instead.  (Contributed by Garvit in bpo-10379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10379}.)

@node macpath,threading<6>,locale<5>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 macpath}@anchor{de4}
@subsubsection macpath


The @code{macpath} is now deprecated and will be removed in Python 3.8.
(Contributed by Chi Hsuan Yen in bpo-9850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9850}.)

@node threading<6>,socket<7>,macpath,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 threading}@anchor{de5}
@subsubsection threading


@code{dummy_threading} and @code{_dummy_thread} have been deprecated.  It is
no longer possible to build Python with threading disabled.
Use @ref{f3,,threading} instead.
(Contributed by Antoine Pitrou in bpo-31370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31370}.)

@node socket<7>,ssl<7>,threading<6>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id8}@anchor{de6}
@subsubsection socket


The silent argument value truncation in @ref{a7f,,socket.htons()} and
@ref{a80,,socket.ntohs()} has been deprecated.  In future versions of Python,
if the passed argument is larger than 16 bits, an exception will be raised.
(Contributed by Oren Milman in bpo-28332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28332}.)

@node ssl<7>,sunau,socket<7>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id9}@anchor{de7}
@subsubsection ssl


@code{ssl.wrap_socket()} is deprecated.  Use
@ref{748,,ssl.SSLContext.wrap_socket()} instead.
(Contributed by Christian Heimes in bpo-28124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28124}.)

@node sunau,sys<9>,ssl<7>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 sunau}@anchor{de8}
@subsubsection sunau


@code{sunau.openfp()} has been deprecated and will be removed in Python 3.9.
Use @code{sunau.open()} instead.
(Contributed by Brian Curtin in bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985}.)

@node sys<9>,wave,sunau,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 id10}@anchor{de9}
@subsubsection sys


Deprecated @code{sys.set_coroutine_wrapper()} and
@code{sys.get_coroutine_wrapper()}.

The undocumented @code{sys.callstats()} function has been deprecated and
will be removed in a future Python version.
(Contributed by Victor Stinner in bpo-28799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28799}.)

@node wave,,sys<9>,非推奨の Python モジュール、関数、メソッド
@anchor{whatsnew/3 7 wave}@anchor{dea}
@subsubsection wave


@code{wave.openfp()} has been deprecated and will be removed in Python 3.9.
Use @ref{b45,,wave.open()} instead.
(Contributed by Brian Curtin in bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985}.)

@node C API の非推奨の関数ならびに型,サポート対象プラットフォームからの除外,非推奨の Python モジュール、関数、メソッド,What's New In Python 3 7
@anchor{whatsnew/3 7 deprecated-functions-and-types-of-the-c-api}@anchor{deb}
@subsection C API の非推奨の関数ならびに型


Function @ref{431,,PySlice_GetIndicesEx()} is deprecated and replaced with
a macro if @code{Py_LIMITED_API} is not set or set to a value in the range
between @code{0x03050400} and @code{0x03060000} (not inclusive), or is @code{0x03060100}
or higher.  (Contributed by Serhiy Storchaka in bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}.)

@ref{42f,,PyOS_AfterFork()} has been deprecated.  Use @ref{db8,,PyOS_BeforeFork()},
@ref{db9,,PyOS_AfterFork_Parent()} or @ref{430,,PyOS_AfterFork_Child()} instead.
(Contributed by Antoine Pitrou in bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500}.)

@node サポート対象プラットフォームからの除外,API と機能の削除<2>,C API の非推奨の関数ならびに型,What's New In Python 3 7
@anchor{whatsnew/3 7 id11}@anchor{dec}@anchor{whatsnew/3 7 platform-support-removals}@anchor{d77}
@subsection サポート対象プラットフォームからの除外



@itemize *

@item 
FreeBSD 9 とそれ以前のバージョンは公式にはサポートされなくなりました。

@item 
For full Unicode support, including within extension modules, *nix platforms
are now expected to provide at least one of @code{C.UTF-8} (full locale),
@code{C.utf8} (full locale) or @code{UTF-8} (@code{LC_CTYPE}-only locale) as an
alternative to the legacy @code{ASCII}-based @code{C} locale.

@item 
OpenSSL 0.9.8 and 1.0.1 are no longer supported, which means building CPython
3.7 with SSL/TLS support on older platforms still using these versions
requires custom build options that link to a more recent version of OpenSSL.

Notably, this issue affects the Debian 8 (aka "jessie") and Ubuntu 14.04
(aka "Trusty") LTS Linux distributions, as they still use OpenSSL 1.0.1 by
default.

Debian 9 ("stretch") and Ubuntu 16.04 ("xenial"), as well as recent releases
of other LTS Linux releases (e.g. RHEL/CentOS 7.5, SLES 12-SP3), use OpenSSL
1.0.2 or later, and remain supported in the default build configuration.

CPython's own CI configuration file@footnote{https://github.com/python/cpython/blob/v3.7.13/.travis.yml} provides an
example of using the SSL
compatibility testing infrastructure@footnote{https://github.com/python/cpython/tree/3.14/Tools/ssl/multissltests.py} in
CPython's test suite to build and link against OpenSSL 1.1.0 rather than an
outdated system provided OpenSSL.
@end itemize

@node API と機能の削除<2>,Module Removals,サポート対象プラットフォームからの除外,What's New In Python 3 7
@anchor{whatsnew/3 7 api-and-feature-removals}@anchor{ded}
@subsection API と機能の削除


The following features and APIs have been removed from Python 3.7:


@itemize *

@item 
The @code{os.stat_float_times()} function has been removed. It was introduced in
Python 2.3 for backward compatibility with Python 2.2, and was deprecated
since Python 3.1.

@item 
Unknown escapes consisting of @code{'\'} and an ASCII letter in replacement
templates for @ref{5a3,,re.sub()} were deprecated in Python 3.5, and will now
cause an error.

@item 
Removed support of the `exclude' argument in @ref{dee,,tarfile.TarFile.add()}.
It was deprecated in Python 2.7 and 3.2.  Use the `filter' argument instead.

@item 
The @code{ntpath.splitunc()} function was deprecated in
Python 3.1, and has now been removed.  Use @ref{def,,splitdrive()}
instead.

@item 
@ref{4e0,,collections.namedtuple()} no longer supports the `verbose' parameter
or @code{_source} attribute which showed the generated source code for the
named tuple class.  This was part of an optimization designed to speed-up
class creation.  (Contributed by Jelle Zijlstra with further improvements
by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger in bpo-28638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28638}.)

@item 
Functions @ref{3c3,,bool()}, @ref{196,,float()}, @ref{24d,,list()} and @ref{614,,tuple()} no
longer take keyword arguments.  The first argument of @ref{19b,,int()} can now
be passed only as positional argument.

@item 
Removed previously deprecated in Python 2.4 classes @code{Plist}, @code{Dict} and
@code{_InternalDict} in the @ref{b0,,plistlib} module.  Dict values in the result
of functions @code{readPlist()} and
@code{readPlistFromBytes()} are now normal dicts.  You no longer
can use attribute access to access items of these dictionaries.

@item 
The @code{asyncio.windows_utils.socketpair()} function has been
removed.  Use the @ref{df0,,socket.socketpair()} function instead,
it is available on all platforms since Python 3.5.
@code{asyncio.windows_utils.socketpair} was just an alias to
@code{socket.socketpair} on Python 3.5 and newer.

@item 
@ref{b,,asyncio} no longer exports the @ref{c7,,selectors} and
@code{_overlapped} modules as @code{asyncio.selectors} and
@code{asyncio._overlapped}. Replace @code{from asyncio import selectors} with
@code{import selectors}.

@item 
Direct instantiation of @ref{ae7,,ssl.SSLSocket} and @ref{d7a,,ssl.SSLObject}
objects is now prohibited. The constructors were never documented, tested,
or designed as public constructors.  Users were supposed to use
@code{ssl.wrap_socket()} or @ref{357,,ssl.SSLContext}.
(Contributed by Christian Heimes in bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951}.)

@item 
The unused @code{distutils} @code{install_misc} command has been removed.
(Contributed by Eric N. Vander Weele in bpo-29218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29218}.)
@end itemize

@node Module Removals,Windows-only Changes,API と機能の削除<2>,What's New In Python 3 7
@anchor{whatsnew/3 7 module-removals}@anchor{df1}
@subsection Module Removals


The @code{fpectl} module 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.
(Contributed by Nathaniel J. Smith in bpo-29137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29137}.)

@node Windows-only Changes,Python 3 7 への移植,Module Removals,What's New In Python 3 7
@anchor{whatsnew/3 7 windows-only-changes}@anchor{df2}
@subsection Windows-only Changes


The python launcher, (py.exe), can accept 32 & 64 bit specifiers `without'
having to specify a minor version as well. So @code{py -3-32} and @code{py -3-64}
become valid as well as @code{py -3.7-32}, also the -`m'-64 and -`m.n'-64 forms
are now accepted to force 64 bit python even if 32 bit would have otherwise
been used. If the specified version is not available py.exe will error exit.
(Contributed by Steve Barnes in bpo-30291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30291}.)

The launcher can be run as @code{py -0} to produce a list of the installed pythons,
`with default marked with an asterisk'. Running @code{py -0p} will include the paths.
If py is run with a version specifier that cannot be matched it will also print
the `short form' list of available specifiers.
(Contributed by Steve Barnes in bpo-30362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30362}.)

@node Python 3 7 への移植,Python 3 7 1 での重要な変更点,Windows-only Changes,What's New In Python 3 7
@anchor{whatsnew/3 7 porting-to-python-3-7}@anchor{df3}@anchor{whatsnew/3 7 porting-to-python-37}@anchor{cc8}
@subsection Python 3.7 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python の挙動の変更: Python の挙動の変更<2>. 
* Python API の変更: Python API の変更<8>. 
* C API の変更: C API の変更<12>. 
* CPython バイトコードの変更: CPython バイトコードの変更<7>. 
* Windows-only Changes: Windows-only Changes<2>. 
* その他の CPython の実装の変更: その他の CPython の実装の変更<3>. 

@end menu

@node Python の挙動の変更<2>,Python API の変更<8>,,Python 3 7 への移植
@anchor{whatsnew/3 7 changes-in-python-behavior}@anchor{df4}
@subsubsection Python の挙動の変更



@itemize *

@item 
@ref{93b,,async} and @ref{18d,,await} names are now reserved keywords.
Code using these names as identifiers will now raise a @ref{18e,,SyntaxError}.
(Contributed by Jelle Zijlstra in bpo-30406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30406}.)

@item 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/} is enabled for all code in Python 3.7, meaning that
@ref{df5,,StopIteration} exceptions raised directly or indirectly in
coroutines and generators are transformed into @ref{244,,RuntimeError}
exceptions.
(Contributed by Yury Selivanov in bpo-32670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32670}.)

@item 
@ref{df6,,object.__aiter__()} methods can no longer be declared as
asynchronous.  (Contributed by Yury Selivanov in bpo-31709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31709}.)

@item 
以前のバージョンの Python で、誤って以下の構文を許容してしまっていました:

@example
f(1 for x in [1],)

class C(1 for x in [1]):
    pass
@end example

Python 3.7 now correctly raises a @ref{18e,,SyntaxError}, as a generator
expression always needs to be directly inside a set of parentheses
and cannot have a comma on either side, and the duplication of the
parentheses can be omitted only on calls.
(Contributed by Serhiy Storchaka in bpo-32012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32012} and bpo-32023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32023}.)

@item 
When using the @ref{23c,,-m} switch, the initial working directory is now added
to @ref{3e4,,sys.path}, rather than an empty string (which dynamically denoted
the current working directory at the time of each import). Any programs that
are checking for the empty string, or otherwise relying on the previous
behaviour, will need to be updated accordingly (e.g. by also checking for
@code{os.getcwd()} or @code{os.path.dirname(__main__.__file__)}, depending on why
the code was checking for the empty string in the first place).
@end itemize

@node Python API の変更<8>,C API の変更<12>,Python の挙動の変更<2>,Python 3 7 への移植
@anchor{whatsnew/3 7 changes-in-the-python-api}@anchor{df7}
@subsubsection Python API の変更



@itemize *

@item 
@ref{d6f,,socketserver.ThreadingMixIn.server_close} now waits until all
non-daemon threads complete.  Set the new
@ref{d70,,socketserver.ThreadingMixIn.block_on_close} class attribute to
@code{False} to get the pre-3.7 behaviour.
(Contributed by Victor Stinner in bpo-31233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31233} and bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540}.)

@item 
@ref{d6f,,socketserver.ForkingMixIn.server_close} now waits until all
child processes complete. Set the new
@ref{d70,,socketserver.ForkingMixIn.block_on_close} class attribute to @code{False}
to get the pre-3.7 behaviour.
(Contributed by Victor Stinner in bpo-31151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31151} and bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540}.)

@item 
The @ref{df8,,locale.localeconv()} function now temporarily sets the @code{LC_CTYPE}
locale to the value of @code{LC_NUMERIC} in some cases.
(Contributed by Victor Stinner in bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900}.)

@item 
@ref{df9,,pkgutil.walk_packages()} now raises a @ref{2ec,,ValueError} if `path' is
a string.  Previously an empty list was returned.
(Contributed by Sanyam Khurana in bpo-24744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24744}.)

@item 
A format string argument for @ref{dfa,,string.Formatter.format()}
is now @ref{c78,,positional-only}.
Passing it as a keyword argument was deprecated in Python 3.5. (Contributed
by Serhiy Storchaka in bpo-29193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29193}.)

@item 
Attributes @ref{dfb,,key},
@ref{dfc,,value} and
@ref{dfd,,coded_value} of class
@ref{dfe,,http.cookies.Morsel} are now read-only.
Assigning to them was deprecated in Python 3.5.
Use the @ref{dff,,set()} method for setting them.
(Contributed by Serhiy Storchaka in bpo-29192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29192}.)

@item 
The `mode' argument of @ref{52c,,os.makedirs()} no longer affects the file
permission bits of newly created intermediate-level directories.
To set their file permission bits you can set the umask before invoking
@code{makedirs()}.
(Contributed by Serhiy Storchaka in bpo-19930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19930}.)

@item 
The @ref{e00,,struct.Struct.format} type is now @ref{169,,str} instead of
@ref{192,,bytes}. (Contributed by Victor Stinner in bpo-21071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21071}.)

@item 
@code{cgi.parse_multipart()} now accepts the `encoding' and `errors'
arguments and returns the same results as
@code{FieldStorage}: for non-file fields, the value associated to a key
is a list of strings, not bytes.
(Contributed by Pierre Quentel in bpo-29979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29979}.)

@item 
Due to internal changes in @ref{d1,,socket}, calling @ref{e01,,socket.fromshare()}
on a socket created by @ref{e02,,socket.share} in older
Python versions is not supported.

@item 
@code{repr} for @ref{7d6,,BaseException} has changed to not include the trailing
comma.  Most exceptions are affected by this change.
(Contributed by Serhiy Storchaka in bpo-30399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30399}.)

@item 
@code{repr} for @ref{bc3,,datetime.timedelta} has changed to include the keyword
arguments in the output. (Contributed by Utkarsh Upadhyay in bpo-30302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30302}.)

@item 
Because @ref{356,,shutil.rmtree()} is now implemented using the @ref{c54,,os.scandir()}
function, the user specified handler `onerror' is now called with the first
argument @code{os.scandir} instead of @code{os.listdir} when listing the directory
is failed.

@item 
Support for nested sets and set operations in regular expressions as in
Unicode Technical Standard #18@footnote{https://unicode.org/reports/tr18/} might be added in the future.  This would
change the syntax.  To facilitate this future change a @ref{659,,FutureWarning}
will be raised in ambiguous cases for the time being.
That include sets starting with a literal @code{'['} or containing literal
character sequences @code{'--'}, @code{'&&'}, @code{'~~'}, and @code{'||'}.  To
avoid a warning, escape them with a backslash.
(Contributed by Serhiy Storchaka in bpo-30349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30349}.)

@item 
The result of splitting a string on a @ref{be,,regular expression}
that could match an empty string has been changed.  For example
splitting on @code{r'\s*'} will now split not only on whitespaces as it
did previously, but also on empty strings before all non-whitespace
characters and just before the end of the string.
The previous behavior can be restored by changing the pattern
to @code{r'\s+'}.  A @ref{659,,FutureWarning} was emitted for such patterns since
Python 3.5.

For patterns that match both empty and non-empty strings, the result of
searching for all matches may also be changed in other cases.  For example
in the string @code{'a\n\n'}, the pattern @code{r'(?m)^\s*?$'} will not only
match empty strings at positions 2 and 3, but also the string @code{'\n'} at
positions 2--3.  To match only blank lines, the pattern should be rewritten
as @code{r'(?m)^[^\S\n]*$'}.

@ref{5a3,,re.sub()} now replaces empty matches adjacent to a previous
non-empty match.  For example @code{re.sub('x*', '-', 'abxd')} returns now
@code{'-a-b--d-'} instead of @code{'-a-b-d-'} (the first minus between 'b' and
'd' replaces 'x', and the second minus replaces an empty string between
'x' and 'd').

(Contributed by Serhiy Storchaka in bpo-25054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25054} and bpo-32308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32308}.)

@item 
Change @ref{e03,,re.escape()} to only escape regex special characters instead
of escaping all characters other than ASCII letters, numbers, and @code{'_'}.
(Contributed by Serhiy Storchaka in bpo-29995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29995}.)

@item 
@ref{d8f,,tracemalloc.Traceback} frames are now sorted from oldest to most
recent to be more consistent with @ref{104,,traceback}.
(Contributed by Jesse Bakker in bpo-32121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32121}.)

@item 
On OSes that support @ref{e04,,socket.SOCK_NONBLOCK} or
@ref{e05,,socket.SOCK_CLOEXEC} bit flags, the
@ref{e06,,socket.type} no longer has them applied.
Therefore, checks like @code{if sock.type == socket.SOCK_STREAM}
work as expected on all platforms.
(Contributed by Yury Selivanov in bpo-32331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32331}.)

@item 
On Windows the default for the `close_fds' argument of
@ref{4b7,,subprocess.Popen} was changed from @ref{d2b,,False} to @ref{e07,,True}
when redirecting the standard handles. If you previously depended on handles
being inherited when using @ref{4b7,,subprocess.Popen} with standard io
redirection, you will have to pass @code{close_fds=False} to preserve the
previous behaviour, or use
@ref{e08,,STARTUPINFO.lpAttributeList}.

@item 
@ref{e09,,importlib.machinery.PathFinder.invalidate_caches()} -- which implicitly
affects @ref{e0a,,importlib.invalidate_caches()} -- now deletes entries
in @ref{7fa,,sys.path_importer_cache} which are set to @code{None}.
(Contributed by Brett Cannon in bpo-33169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33169}.)

@item 
In @ref{b,,asyncio},
@ref{e0b,,loop.sock_recv()},
@ref{e0c,,loop.sock_sendall()},
@ref{e0d,,loop.sock_accept()},
@ref{e0e,,loop.getaddrinfo()},
@ref{e0f,,loop.getnameinfo()}
have been changed to be proper coroutine methods to match their
documentation.  Previously, these methods returned @ref{dc6,,asyncio.Future}
instances.
(Contributed by Yury Selivanov in bpo-32327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32327}.)

@item 
@ref{e10,,asyncio.Server.sockets} now returns a copy of the internal list
of server sockets, instead of returning it directly.
(Contributed by Yury Selivanov in bpo-32662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32662}.)

@item 
@ref{e00,,Struct.format} is now a @ref{169,,str} instance
instead of a @ref{192,,bytes} instance.
(Contributed by Victor Stinner in bpo-21071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21071}.)

@item 
@ref{7,,argparse} subparsers can now be made mandatory by passing @code{required=True}
to @ref{e11,,ArgumentParser.add_subparsers()}.
(Contributed by Anthony Sottile in bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510}.)

@item 
@ref{e12,,ast.literal_eval()} is now stricter.  Addition and subtraction of
arbitrary numbers are no longer allowed.
(Contributed by Serhiy Storchaka in bpo-31778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31778}.)

@item 
@ref{e13,,Calendar.itermonthdates}
will now consistently raise an exception when a date falls outside of the
@code{0001-01-01} through @code{9999-12-31} range.  To support applications that
cannot tolerate such exceptions, the new
@ref{e14,,Calendar.itermonthdays3} and
@ref{e15,,Calendar.itermonthdays4} can be used.
The new methods return tuples and are not restricted by the range supported by
@ref{1fa,,datetime.date}.
(Contributed by Alexander Belopolsky in bpo-28292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28292}.)

@item 
@ref{e16,,collections.ChainMap} now preserves the order of the underlying
mappings.  (Contributed by Raymond Hettinger in bpo-32792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32792}.)

@item 
The @code{submit()} method of @ref{949,,concurrent.futures.ThreadPoolExecutor}
and @ref{1d6,,concurrent.futures.ProcessPoolExecutor} now raises
a @ref{244,,RuntimeError} if called during interpreter shutdown.
(Contributed by Mark Nemec in bpo-33097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33097}.)

@item 
The @ref{4de,,configparser.ConfigParser} constructor now uses @code{read_dict()}
to process the default values, 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.
(Contributed by James Tocknell in bpo-23835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23835}.)

@item 
Several undocumented internal imports were removed.
One example is that @code{os.errno} is no longer available; use @code{import errno}
directly instead.
Note that such undocumented internal imports may be removed any time without
notice, even in micro version releases.
@end itemize

@node C API の変更<12>,CPython バイトコードの変更<7>,Python API の変更<8>,Python 3 7 への移植
@anchor{whatsnew/3 7 changes-in-the-c-api}@anchor{e17}
@subsubsection C API の変更


The function @ref{431,,PySlice_GetIndicesEx()} is considered unsafe for
resizable sequences.  If the slice indices are not instances of @ref{19b,,int},
but objects that implement the @code{__index__()} method, the sequence can be
resized after passing its length to @code{PySlice_GetIndicesEx()}.  This
can lead to returning indices out of the length of the sequence.  For
avoiding possible problems use new functions @ref{432,,PySlice_Unpack()} and
@ref{433,,PySlice_AdjustIndices()}.
(Contributed by Serhiy Storchaka in bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}.)

@node CPython バイトコードの変更<7>,Windows-only Changes<2>,C API の変更<12>,Python 3 7 への移植
@anchor{whatsnew/3 7 cpython-bytecode-changes}@anchor{e18}
@subsubsection CPython バイトコードの変更


There are two new opcodes: @code{LOAD_METHOD} and @code{CALL_METHOD}.
(Contributed by Yury Selivanov and INADA Naoki in bpo-26110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26110}.)

The @code{STORE_ANNOTATION} opcode has been removed.
(Contributed by Mark Shannon in bpo-32550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32550}.)

@node Windows-only Changes<2>,その他の CPython の実装の変更<3>,CPython バイトコードの変更<7>,Python 3 7 への移植
@anchor{whatsnew/3 7 id12}@anchor{e19}
@subsubsection Windows-only Changes


The file used to override @ref{3e4,,sys.path} is now called
@code{<python-executable>._pth} instead of @code{'sys.path'}.
See @ref{e1a,,モジュールの検索} for more information.
(Contributed by Steve Dower in bpo-28137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28137}.)

@node その他の CPython の実装の変更<3>,,Windows-only Changes<2>,Python 3 7 への移植
@anchor{whatsnew/3 7 id13}@anchor{e1b}
@subsubsection その他の CPython の実装の変更


In preparation for potential future changes to the public CPython runtime
initialization API (see 
@geindex Python Enhancement Proposals; PEP 432
PEP 432@footnote{https://peps.python.org/pep-0432/} for an initial, but somewhat outdated,
draft), CPython's internal startup
and configuration management logic has been significantly refactored. While
these updates are intended to be entirely transparent to both embedding
applications and users of the regular CPython CLI, they're being mentioned
here as the refactoring changes the internal order of various operations
during interpreter startup, and hence may uncover previously latent defects,
either in embedding applications, or in CPython itself.
(Initially contributed by Nick Coghlan and Eric Snow as part of
bpo-22257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22257}, and further updated by Nick, Eric, and Victor Stinner in a
number of other issues). Some known details affected:


@itemize *

@item 
@code{PySys_AddWarnOptionUnicode()} is not currently usable by embedding
applications due to the requirement to create a Unicode object prior to
calling @code{Py_Initialize}. Use @code{PySys_AddWarnOption()} instead.

@item 
warnings filters added by an embedding application with
@code{PySys_AddWarnOption()} should now more consistently take precedence
over the default filters set by the interpreter
@end itemize

Due to changes in the way the default warnings filters are configured,
setting @ref{406,,Py_BytesWarningFlag} to a value greater than one is no longer
sufficient to both emit @ref{e1c,,BytesWarning} messages and have them converted
to exceptions.  Instead, the flag must be set (to cause the warnings to be
emitted in the first place), and an explicit @code{error::BytesWarning}
warnings filter added to convert them to exceptions.

Due to a change in the way docstrings are handled by the compiler, the
implicit @code{return None} in a function body consisting solely of a docstring
is now marked as occurring on the same line as the docstring, not on the
function's header line.

The current exception state has been moved from the frame object to the co-routine.
This simplified the interpreter and fixed a couple of obscure bugs caused by
having swap exception state when entering or exiting a generator.
(Contributed by Mark Shannon in bpo-25612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25612}.)

@node Python 3 7 1 での重要な変更点,Python 3 7 2 での重要な変更点,Python 3 7 への移植,What's New In Python 3 7
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-1}@anchor{e1d}
@subsection Python 3.7.1 での重要な変更点


Starting in 3.7.1, @ref{460,,Py_Initialize()} now consistently reads and respects
all of the same environment settings as @ref{e1e,,Py_Main()} (in earlier Python
versions, it respected an ill-defined subset of those environment variables,
while in Python 3.7.0 it didn't read any of them due to bpo-34247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34247}). If
this behavior is unwanted, set @ref{40a,,Py_IgnoreEnvironmentFlag} to 1 before
calling @ref{460,,Py_Initialize()}.

In 3.7.1 the C API for Context Variables
@ref{e1f,,was updated} to use
@ref{5df,,PyObject} pointers.  See also bpo-34762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34762}.

In 3.7.1 the @ref{101,,tokenize} module now implicitly emits a @code{NEWLINE} token
when provided with input that does not have a trailing new line.  This behavior
now matches what the C tokenizer does internally.
(Contributed by Ammar Askar in bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899}.)

@node Python 3 7 2 での重要な変更点,Python 3 7 6 での重要な変更点,Python 3 7 1 での重要な変更点,What's New In Python 3 7
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-2}@anchor{e20}
@subsection Python 3.7.2 での重要な変更点


In 3.7.2, @ref{117,,venv} on Windows no longer copies the original binaries, but
creates redirector scripts named @code{python.exe} and @code{pythonw.exe} instead.
This resolves a long standing issue where all virtual environments would have
to be upgraded or recreated with each Python update. However, note that this
release will still require recreation of virtual environments in order to get
the new scripts.

@node Python 3 7 6 での重要な変更点,Python 3 7 10 での重要な変更点,Python 3 7 2 での重要な変更点,What's New In Python 3 7
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-6}@anchor{e21}
@subsection Python 3.7.6 での重要な変更点


セキュリティ上の重大な懸念により、@ref{93c,,asyncio.loop.create_datagram_endpoint()} での `reuse_address' 引数は無効になりました。これはソケットオプション @cite{SO_REUSEADDR`} のUDP における挙動が原因です。詳しくは、@code{loop.create_datagram_endpoint()} のドキュメントを参照してください。(Kyle Stanley, Antoine Pitrou, Yury Selivanov による貢献 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228})

@node Python 3 7 10 での重要な変更点,Notable changes in Python 3 7 11,Python 3 7 6 での重要な変更点,What's New In Python 3 7
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-10}@anchor{e22}
@subsection Python 3.7.10 での重要な変更点


Earlier Python versions allowed using both @code{;} and @code{&} as
query parameter separators in @ref{31f,,urllib.parse.parse_qs()} and
@ref{31e,,urllib.parse.parse_qsl()}.  Due to security concerns, and to conform with
newer W3C recommendations, this has been changed to allow only a single
separator key, with @code{&} as the default.  This change also affects
@code{cgi.parse()} and @code{cgi.parse_multipart()} as they use the affected
functions internally. For more details, please see their respective
documentation.
(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}.)

@node Notable changes in Python 3 7 11,Notable security feature in 3 7 14,Python 3 7 10 での重要な変更点,What's New In Python 3 7
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-11}@anchor{e23}
@subsection Notable changes in Python 3.7.11


A security fix alters the @ref{af6,,ftplib.FTP} behavior to not trust the
IPv4 address sent from the remote server when setting up a passive data
channel.  We reuse the ftp server IP address instead.  For unusual code
requiring the old behavior, set a @code{trust_server_pasv_ipv4_address}
attribute on your FTP instance to @code{True}.  (See gh-87451@footnote{https://github.com/python/cpython/issues/87451})

The presence of newline or tab characters in parts of a URL allows for some
forms of attacks. Following the WHATWG specification that updates RFC 3986,
ASCII newline @code{\n}, @code{\r} and tab @code{\t} characters are stripped from the
URL by the parser @ref{110,,urllib.parse()} preventing such attacks. The removal
characters are controlled by a new module level variable
@code{urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE}. (See gh-88048@footnote{https://github.com/python/cpython/issues/88048})

@node Notable security feature in 3 7 14,,Notable changes in Python 3 7 11,What's New In Python 3 7
@anchor{whatsnew/3 7 notable-security-feature-in-3-7-14}@anchor{e24}
@subsection Notable security feature in 3.7.14


Converting between @ref{19b,,int} and @ref{169,,str} in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
now raises a @ref{2ec,,ValueError} if the number of digits in string form is
above a limit to avoid potential denial of service attacks due to the
algorithmic complexity. This is a mitigation for 
@geindex Common Vulnerabilities and Exposures; CVE 2020-10735
CVE 2020-10735@footnote{https://www.cve.org/CVERecord?id=CVE-2020-10735}.
This limit can be configured or disabled by environment variable, command
line flag, or @ref{df,,sys} APIs. See the @ref{80b,,integer string conversion length limitation} documentation.  The default limit
is 4300 digits in string form.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 6,What's New In Python 3 5,What's New In Python 3 7,What's New in Python
@anchor{whatsnew/3 6 doc}@anchor{e25}@anchor{whatsnew/3 6 translation-repo}@anchor{e26}@anchor{whatsnew/3 6 what-s-new-in-python-3-6}@anchor{e27}
@section What's New In Python 3.6


@*エディタ: 
Elvis Pranskevichus <@email{elvis@@magic.io}>, Yury Selivanov <@email{yury@@magic.io}>


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

This article explains the new features in Python 3.6, compared to 3.5.
Python 3.6 was released on December 23, 2016.  See the
changelog@footnote{https://docs.python.org/3.6/whatsnew/changelog.html} for a full
list of changes.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 494
PEP 494@footnote{https://peps.python.org/pep-0494/} - Python 3.6 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト<9>. リリースハイライト
* 新しい機能: 新しい機能<14>. 
* その他の言語変更: その他の言語変更<8>. 
* 新たなモジュール: 新たなモジュール<8>. 
* 改良されたモジュール: 改良されたモジュール<8>. 
* 最適化: 最適化<9>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<2>. 
* その他の改善:: 
* 非推奨: 非推奨<10>. 
* 削除: 削除<10>. 
* Python 3.6 への移植: Python 3 6 への移植. 
* Notable changes in Python 3.6.2: Notable changes in Python 3 6 2. 
* Notable changes in Python 3.6.4: Notable changes in Python 3 6 4. 
* Notable changes in Python 3.6.5: Notable changes in Python 3 6 5. 
* Notable changes in Python 3.6.7: Notable changes in Python 3 6 7. 
* Notable changes in Python 3.6.10: Notable changes in Python 3 6 10. 
* Notable changes in Python 3.6.13: Notable changes in Python 3 6 13. 
* Notable changes in Python 3.6.14: Notable changes in Python 3 6 14. 

@end menu

@node 概要 -- リリースハイライト<9>,新しい機能<14>,,What's New In Python 3 6
@anchor{whatsnew/3 6 summary-release-highlights}@anchor{e28}
@subsection 概要 -- リリースハイライト


新たな文法機能:


@itemize *

@item 
@ref{e29,,PEP 498}、フォーマット済み文字列リテラル。

@item 
@ref{e2a,,PEP 515}、数値リテラル内のアンダースコア。

@item 
@ref{e2b,,PEP 526}、変数アノテーションの文法。

@item 
@ref{e2c,,PEP 525}、非同期ジェネレータ。

@item 
@ref{e2d,,PEP 530}: 非同期内包表記
@end itemize

新たなライブラリモジュール:


@itemize *

@item 
@ref{c5,,secrets}: @ref{e2e,,PEP 506 -- 標準ライブラリーに Secrets モジュールを追加}.
@end itemize

CPython の実装の改善:


@itemize *

@item 
@ref{cbd,,dict} 型は、 Raymond Hettinger@footnote{https://mail.python.org/pipermail/python-dev/2012-December/123028.html} の提案に基づき、 PyPy dict implementation@footnote{https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html} と同様の @ref{e2f,,よりコンパクトな表現} を使うように再実装されました。
その結果、 Python 3.5 と比較して辞書が使うメモリ 20% から 25% 減少しました。

@item 
@ref{e30,,新しいプロトコル} により、クラス生成のカスタマイズがより簡単になりました。

@item 
クラス属性の定義の順番が @ref{e31,,保持されるようになりました}。

@item 
@code{**kwargs} の要素の順序が、キーワード引数が関数に渡されたときの @ref{e32,,順序に一致した} ものになりました。

@item 
DTrace と SystemTap の @ref{e33,,プローブのサポート} が追加されました。

@item 
新しい @ref{e34,,PYTHONMALLOC}  環境変数が、インタープリタのメモリ確保とメモリアクセスエラーのデバッグに使えるようになりました。
@end itemize

標準ライブラリーの顕著な改善


@itemize *

@item 
The @ref{b,,asyncio} module has received new features, significant
usability and performance improvements, and a fair amount of bug fixes.
Starting with Python 3.6 the @code{asyncio} module is no longer provisional
and its API is considered stable.

@item 
A new @ref{e35,,file system path protocol} has been
implemented to support @ref{5a1,,path-like objects}.
All standard library functions operating on paths have been updated to
work with the new protocol.

@item 
@ref{34,,datetime} モジュールで @ref{e36,,地域時間の曖昧さ回避} がサポートされました。

@item 
@ref{10a,,typing} モジュールに数多くの @ref{e37,,改善} がなされました。

@item 
@ref{105,,tracemalloc} モジュールが大幅に書き直され、改善されたメモリ割り当てエラーの診断プログラムの提供だけでなく、 @ref{54c,,ResourceWarning} の出力メッセージも改善されています。
より詳しいことは @ref{e34,,PYTHONMALLOC 節} を参照してください。
@end itemize

セキュリティの改善:


@itemize *

@item 
The new @ref{c5,,secrets} module has been added to simplify the generation of
cryptographically strong pseudo-random numbers suitable for
managing secrets such as account authentication, tokens, and similar.

@item 
On Linux, @ref{746,,os.urandom()} now blocks until the system urandom entropy
pool is initialized to increase the security. See the 
@geindex Python Enhancement Proposals; PEP 524
PEP 524@footnote{https://peps.python.org/pep-0524/} for the
rationale.

@item 
@ref{6c,,hashlib} および @ref{d5,,ssl} モジュールは OpenSSL 1.1.0 をサポートしました。

@item 
@ref{d5,,ssl} モジュールのデフォルトの設定と機能群が改善されました。

@item 
@ref{6c,,hashlib} モジュールで BLAKE2, SHA-3, SHAKE ハッシュアルゴリズムと @ref{e38,,scrypt()} キー導出関数がサポートされるようになりました。
@end itemize

Windows の改善:


@itemize *

@item 
@ref{e39,,PEP 528} および @ref{e3a,,PEP 529}、 Windows のファイルシステムとコンソールのエンコーディングを UTF-8 に変更しました。

@item 
@code{py.exe} ランチャーを対話的に使うときに、 (コマンドライン引数や設定ファイルで) バージョンを指定しないと Python 3 よりも Python 2 を選択するということはなくなりました。
シェバン行の扱いは以前のままで、 "python" とあった場合は Python 2 を指しています。

@item 
@code{python.exe} and @code{pythonw.exe} have been marked as long-path aware,
which means that the 260 character path limit may no longer apply.
See @ref{e3b,,removing the MAX_PATH limitation} for details.

@item 
A @code{._pth} file can be added to force isolated mode and fully specify
all search paths to avoid registry and environment lookup. See
@ref{e1a,,the documentation} for more information.

@item 
A @code{python36.zip} file now works as a landmark to infer
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME}. See @ref{e1a,,the documentation} for
more information.
@end itemize

@node 新しい機能<14>,その他の言語変更<8>,概要 -- リリースハイライト<9>,What's New In Python 3 6
@anchor{whatsnew/3 6 new-features}@anchor{e3c}@anchor{whatsnew/3 6 pypy-dict-implementation}@anchor{e3d}
@subsection 新しい機能


@menu
* PEP 498; フォーマット済み文字列リテラル: PEP 498 フォーマット済み文字列リテラル. 
* PEP 526; 変数アノテーションの文法: PEP 526 変数アノテーションの文法. 
* PEP 515; 数値リテラル内のアンダースコア: PEP 515 数値リテラル内のアンダースコア. 
* PEP 525; 非同期ジェネレータ: PEP 525 非同期ジェネレータ. 
* PEP 530; 非同期内包表記: PEP 530 非同期内包表記. 
* PEP 487; Simpler customization of class creation: PEP 487 Simpler customization of class creation. 
* 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 and SystemTap probing support:: 

@end menu

@node PEP 498 フォーマット済み文字列リテラル,PEP 526 変数アノテーションの文法,,新しい機能<14>
@anchor{whatsnew/3 6 pep-498-formatted-string-literals}@anchor{e3e}@anchor{whatsnew/3 6 whatsnew36-pep498}@anchor{e29}
@subsubsection PEP 498: フォーマット済み文字列リテラル


@geindex Python Enhancement Proposals; PEP 498
PEP 498@footnote{https://peps.python.org/pep-0498/} は新たな種類の文字列リテラル、すなわち `f-strings'、 @ref{19a,,フォーマット済み文字列リテラル} を導入しました。

フォーマット済み文字列リテラルはプレフィックスに @code{'f'} をとり @ref{833,,str.format()} による書式文字列に似ています。これらには中括弧で囲まれた置換フィールドがあります。置換フィールドは実行時に評価される式で、 @ref{199,,format()} プロトコルによってフォーマットされます:

@example
>>> name = "Fred"
>>> f"He said his name is @{name@}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: @{value:@{width@}.@{precision@}@}"  # nested fields
'result:      12.35'
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 498

@item PEP 498@footnote{https://peps.python.org/pep-0498/} -- Literal String Interpolation.

PEP written and implemented by Eric V. Smith.
@end table

@ref{19a,,Feature documentation}.


@node PEP 526 変数アノテーションの文法,PEP 515 数値リテラル内のアンダースコア,PEP 498 フォーマット済み文字列リテラル,新しい機能<14>
@anchor{whatsnew/3 6 pep-526-syntax-for-variable-annotations}@anchor{e3f}@anchor{whatsnew/3 6 whatsnew36-pep526}@anchor{e2b}
@subsubsection PEP 526: 変数アノテーションの文法


@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} は関数の仮引数の型アノテーションの標準(別名型ヒント)を導入しました。この PEP は Python に、クラス変数およびインスタンス変数を含む変数の型アノテーションの構文を追加しました:

@example
primes: List[int] = []

captain: str  # Note: no initial value!

class Starship:
    stats: Dict[str, int] = @{@}
@end example

関数アノテーションと同様に、Python インタープリタは変数アノテーションに特定の意味を付加せず、クラスやモジュールの @code{__annotations__} 属性に保存するだけです。

静的型付け言語の変数定義とは対照的に、アノテーションシンタックスの目的は抽象構文木および @code{__annotations__} 属性を通じて、サードパーティツールやライブラリーに型の構造化されたメタデータを指定する簡単な方法を提供することです。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 526

@item PEP 526@footnote{https://peps.python.org/pep-0526/} -- Syntax for variable annotations

PEP written by Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach,
and Guido van Rossum. Implemented by Ivan Levkivskyi.
@end table

新構文を使用あるいは使用予定のツール: mypy@footnote{https://www.mypy-lang.org/}, pytype@footnote{https://github.com/google/pytype}, PyCharm などなど。


@node PEP 515 数値リテラル内のアンダースコア,PEP 525 非同期ジェネレータ,PEP 526 変数アノテーションの文法,新しい機能<14>
@anchor{whatsnew/3 6 pep-515-underscores-in-numeric-literals}@anchor{e40}@anchor{whatsnew/3 6 whatsnew36-pep515}@anchor{e2a}
@subsubsection PEP 515: 数値リテラル内のアンダースコア


@geindex Python Enhancement Proposals; PEP 515
PEP 515@footnote{https://peps.python.org/pep-0515/} により、可読性向上のために数値リテラル内でアンダースコアを使えるようになりました。例えば:

@example
>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295
@end example

単一のアンダースコアは数字の間と基数指定子の後で許されます。先頭、末尾、あるいは複数のアンダースコアを列内で使用することはできません。

The @ref{4f9,,string formatting} language also now has support
for the @code{'_'} option to signal the use of an underscore for a thousands
separator for floating-point presentation types and for integer
presentation type @code{'d'}.  For integer presentation types @code{'b'},
@code{'o'}, @code{'x'}, and @code{'X'}, underscores will be inserted every 4
digits:

@example
>>> '@{:_@}'.format(1000000)
'1_000_000'
>>> '@{:_x@}'.format(0xFFFFFFFF)
'ffff_ffff'
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 515

@item PEP 515@footnote{https://peps.python.org/pep-0515/} -- 数値リテラル内のアンダースコア

PEP written by Georg Brandl and Serhiy Storchaka.
@end table


@node PEP 525 非同期ジェネレータ,PEP 530 非同期内包表記,PEP 515 数値リテラル内のアンダースコア,新しい機能<14>
@anchor{whatsnew/3 6 pep-525-asynchronous-generators}@anchor{e41}@anchor{whatsnew/3 6 whatsnew36-pep525}@anchor{e2c}
@subsubsection PEP 525: 非同期ジェネレータ


@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} で Python 3.5 はネイティブなコルーチンならびに @code{async} / @code{await} 構文をサポートしました。Python 3.5 実装における大きな制約は同一の関数実体内で @code{await} と @code{yield} を使えないことでした。Python 3.6 ではこの制約はなくなり、 `非同期ジェネレータ' を定義できるようになりました:

@example
async def ticker(delay, to):
    """Yield numbers from 0 to *to* every *delay* seconds."""
    for i in range(to):
        yield i
        await asyncio.sleep(delay)
@end example

新たな構文のおかげでより速く、より簡潔にコードを書くことができます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 525

@item PEP 525@footnote{https://peps.python.org/pep-0525/} -- 非同期ジェネレータ

PEP written and implemented by Yury Selivanov.
@end table


@node PEP 530 非同期内包表記,PEP 487 Simpler customization of class creation,PEP 525 非同期ジェネレータ,新しい機能<14>
@anchor{whatsnew/3 6 pep-530-asynchronous-comprehensions}@anchor{e42}@anchor{whatsnew/3 6 whatsnew36-pep530}@anchor{e2d}
@subsubsection PEP 530: 非同期内包表記


@geindex Python Enhancement Proposals; PEP 530
PEP 530@footnote{https://peps.python.org/pep-0530/} によりリスト、セット、辞書内包表記ならびにジェネレータ式内での @code{async for} の使用がサポートされました:

@example
result = [i async for i in aiter() if i % 2]
@end example

加えて、 @code{await} 式が全ての内包表記でサポートされました:

@example
result = [await fun() for fun in funcs if await condition()]
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 530

@item PEP 530@footnote{https://peps.python.org/pep-0530/} -- 非同期内包表記

PEP written and implemented by Yury Selivanov.
@end table


@node PEP 487 Simpler customization of class creation,PEP 487 記述子プロトコルの改善,PEP 530 非同期内包表記,新しい機能<14>
@anchor{whatsnew/3 6 pep-487-simpler-customization-of-class-creation}@anchor{e43}@anchor{whatsnew/3 6 whatsnew36-pep487}@anchor{e30}
@subsubsection PEP 487: Simpler customization of class creation


It is now possible to customize subclass creation without using a metaclass.
The new @code{__init_subclass__} classmethod will be called on the base class
whenever a new subclass is created:

@example
class PluginBase:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)

class Plugin1(PluginBase):
    pass

class Plugin2(PluginBase):
    pass
@end example

In order to allow zero-argument @ref{1a6,,super()} calls to work correctly from
@ref{843,,__init_subclass__()} implementations, custom metaclasses must
ensure that the new @code{__classcell__} namespace entry is propagated to
@code{type.__new__} (as described in @ref{e44,,クラスオブジェクトの作成}).


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 487

@item PEP 487@footnote{https://peps.python.org/pep-0487/} -- Simpler customization of class creation

PEP 著と実装 Martin Teichmann.
@end table

@ref{e45,,Feature documentation}


@node PEP 487 記述子プロトコルの改善,PEP 519 ファイルシステムパスプロトコルの追加,PEP 487 Simpler customization of class creation,新しい機能<14>
@anchor{whatsnew/3 6 pep-487-descriptor-protocol-enhancements}@anchor{e46}@anchor{whatsnew/3 6 whatsnew36-pep487-descriptors}@anchor{e47}
@subsubsection PEP 487: 記述子プロトコルの改善


@geindex Python Enhancement Proposals; PEP 487
PEP 487@footnote{https://peps.python.org/pep-0487/} extends the descriptor protocol to include the new optional
@ref{e48,,__set_name__()} method.  Whenever a new class is defined, the new
method will be called on all descriptors included in the definition, providing
them with a reference to the class being defined and the name given to the
descriptor within the class namespace.  In other words, instances of
descriptors can now know the attribute name of the descriptor in the
owner class:

@example
class IntField:
    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise ValueError(f'expecting integer in @{self.name@}')
        instance.__dict__[self.name] = value

    # this is the new initializer:
    def __set_name__(self, owner, name):
        self.name = name

class Model:
    int_field = IntField()
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 487

@item PEP 487@footnote{https://peps.python.org/pep-0487/} -- Simpler customization of class creation

PEP 著と実装 Martin Teichmann.
@end table

@ref{e49,,Feature documentation}


@node PEP 519 ファイルシステムパスプロトコルの追加,PEP 495 地域時間の曖昧さ回避,PEP 487 記述子プロトコルの改善,新しい機能<14>
@anchor{whatsnew/3 6 pep-519-adding-a-file-system-path-protocol}@anchor{e4a}@anchor{whatsnew/3 6 whatsnew36-pep519}@anchor{e35}
@subsubsection PEP 519: ファイルシステムパスプロトコルの追加


File system paths have historically been represented as @ref{169,,str}
or @ref{192,,bytes} objects. This has led to people who write code which
operate on file system paths to assume that such objects are only one
of those two types (an @ref{19b,,int} representing a file descriptor
does not count as that is not a file path). Unfortunately that
assumption prevents alternative object representations of file system
paths like @ref{a8,,pathlib} from working with pre-existing code,
including Python's standard library.

To fix this situation, a new interface represented by
@ref{e4b,,os.PathLike} has been defined. By implementing the
@ref{e4c,,__fspath__()} method, an object signals that it
represents a path. An object can then provide a low-level
representation of a file system path as a @ref{169,,str} or
@ref{192,,bytes} object. This means an object is considered
@ref{5a1,,path-like} if it implements
@ref{e4b,,os.PathLike} or is a @ref{169,,str} or @ref{192,,bytes} object
which represents a file system path. Code can use @ref{e4d,,os.fspath()},
@ref{e4e,,os.fsdecode()}, or @ref{e4f,,os.fsencode()} to explicitly get a
@ref{169,,str} and/or @ref{192,,bytes} representation of a path-like
object.

The built-in @ref{316,,open()} function has been updated to accept
@ref{e4b,,os.PathLike} objects, as have all relevant functions in the
@ref{a5,,os} and @ref{a6,,os.path} modules, and most other functions and
classes in the standard library.  The @ref{6c3,,os.DirEntry} class
and relevant classes in @ref{a8,,pathlib} have also been updated to
implement @ref{e4b,,os.PathLike}.

The hope is that updating the fundamental functions for operating
on file system paths will lead to third-party code to implicitly
support all @ref{5a1,,path-like objects} without any
code changes, or at least very minimal ones (e.g. calling
@ref{e4d,,os.fspath()} at the beginning of code before operating on a
path-like object).

Here are some examples of how the new interface allows for
@ref{266,,pathlib.Path} to be used more easily and transparently with
pre-existing code:

@example
>>> import pathlib
>>> with open(pathlib.Path("README")) as f:
...     contents = f.read()
...
>>> import os.path
>>> os.path.splitext(pathlib.Path("some_file.txt"))
('some_file', '.txt')
>>> os.path.join("/a/b", pathlib.Path("c"))
'/a/b/c'
>>> import os
>>> os.fspath(pathlib.Path("some_file.txt"))
'some_file.txt'
@end example

(Implemented by Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle Zijlstra.)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 519

@item PEP 519@footnote{https://peps.python.org/pep-0519/} -- ファイルシステムパスプロトコルの追加

PEP written by Brett Cannon and Koos Zevenhoven.
@end table


@node PEP 495 地域時間の曖昧さ回避,PEP 529 Windows ファイルシステムのエンコーディングを UTF-8 に変更,PEP 519 ファイルシステムパスプロトコルの追加,新しい機能<14>
@anchor{whatsnew/3 6 pep-495-local-time-disambiguation}@anchor{e50}@anchor{whatsnew/3 6 whatsnew36-pep495}@anchor{e36}
@subsubsection PEP 495: 地域時間の曖昧さ回避


世界の大抵の場所で、地域時計が1日繰り下げられることがこれまでありましたし、これからもあるでしょう。そういった時に、同じ日に同じ時間を指す区間があります。そういった状況では地域時計が表示する (あるいは Python の datetime インスタンスが格納する) 情報では、時間内の特定の瞬間を識別することはできません。

@geindex Python Enhancement Proposals; PEP 495
PEP 495@footnote{https://peps.python.org/pep-0495/} は時間内の地域時間が同じ二つの瞬間を区別するために、新たな `fold' 属性を @ref{4e2,,datetime.datetime} インスタンスならびに @ref{1fb,,datetime.time} クラスに追加しました。

@example
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
@end example

@ref{e51,,fold} 属性の値は、曖昧な場合に時間内の二番目の (年代的) 瞬間を表しているものを除く全てのインスタンスで @code{0} です。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 495

@item PEP 495@footnote{https://peps.python.org/pep-0495/} -- 地域時間の曖昧さ回避

PEP written by Alexander Belopolsky and Tim Peters, implementation
by Alexander Belopolsky.
@end table


@node PEP 529 Windows ファイルシステムのエンコーディングを UTF-8 に変更,PEP 528 Windows コンソールのエンコーディングを UTF-8 に変更,PEP 495 地域時間の曖昧さ回避,新しい機能<14>
@anchor{whatsnew/3 6 pep-529-change-windows-filesystem-encoding-to-utf-8}@anchor{e52}@anchor{whatsnew/3 6 whatsnew36-pep529}@anchor{e3a}
@subsubsection PEP 529: Windows ファイルシステムのエンコーディングを UTF-8 に変更


Representing filesystem paths is best performed with str (Unicode) rather than
bytes. However, there are some situations where using bytes is sufficient and
correct.

Prior to Python 3.6, data loss could result when using bytes paths on Windows.
With this change, using bytes to represent paths is now supported on Windows,
provided those bytes are encoded with the encoding returned by
@ref{e53,,sys.getfilesystemencoding()}, which now defaults to @code{'utf-8'}.

Applications that do not use str to represent paths should use
@ref{e4f,,os.fsencode()} and @ref{e4e,,os.fsdecode()} to ensure their bytes are
correctly encoded. To revert to the previous behaviour, set
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} or call
@ref{33e,,sys._enablelegacywindowsfsencoding()}.

See 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} for more information and discussion of code modifications that
may be required.

@node PEP 528 Windows コンソールのエンコーディングを UTF-8 に変更,PEP 520 クラス属性の定義の順番を保持,PEP 529 Windows ファイルシステムのエンコーディングを UTF-8 に変更,新しい機能<14>
@anchor{whatsnew/3 6 pep-528-change-windows-console-encoding-to-utf-8}@anchor{e54}@anchor{whatsnew/3 6 whatsnew36-pep528}@anchor{e39}
@subsubsection PEP 528: Windows コンソールのエンコーディングを UTF-8 に変更


The default console on Windows will now accept all Unicode characters and
provide correctly read str objects to Python code. @code{sys.stdin},
@code{sys.stdout} and @code{sys.stderr} now default to utf-8 encoding.

This change only applies when using an interactive console, and not when
redirecting files or pipes. To revert to the previous behaviour for interactive
console use, set 
@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 環境変数; PYTHONLEGACYWINDOWSSTDIO
@ref{e55,,PYTHONLEGACYWINDOWSSTDIO}.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 528

@item PEP 528@footnote{https://peps.python.org/pep-0528/} -- Windows コンソールのエンコーディングを UTF-8 に変更

PEP written and implemented by Steve Dower.
@end table


@node PEP 520 クラス属性の定義の順番を保持,PEP 468 キーワード引数の順番の保持,PEP 528 Windows コンソールのエンコーディングを UTF-8 に変更,新しい機能<14>
@anchor{whatsnew/3 6 pep-520-preserving-class-attribute-definition-order}@anchor{e56}@anchor{whatsnew/3 6 whatsnew36-pep520}@anchor{e31}
@subsubsection PEP 520: クラス属性の定義の順番を保持


Attributes in a class definition body have a natural ordering: the same
order in which the names appear in the source.  This order is now
preserved in the new class's @ref{e57,,__dict__} attribute.

Also, the effective default class `execution' namespace (returned from
@ref{e58,,type.__prepare__()}) is now an insertion-order-preserving
mapping.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 520

@item PEP 520@footnote{https://peps.python.org/pep-0520/} -- クラス属性の定義の順番を保持

PEP written and implemented by Eric Snow.
@end table


@node PEP 468 キーワード引数の順番の保持,新たな dict 実装,PEP 520 クラス属性の定義の順番を保持,新しい機能<14>
@anchor{whatsnew/3 6 pep-468-preserving-keyword-argument-order}@anchor{e59}@anchor{whatsnew/3 6 whatsnew36-pep468}@anchor{e32}
@subsubsection PEP 468: キーワード引数の順番の保持


関数シグニチャにおける @code{**kwargs} は挿入順序を保存するマッピングであることが保証されるようになりました。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 468

@item PEP 468@footnote{https://peps.python.org/pep-0468/} -- キーワード引数の順番の保持

PEP written and implemented by Eric Snow.
@end table


@node 新たな dict 実装,PEP 523 CPython にフレーム評価 API を追加,PEP 468 キーワード引数の順番の保持,新しい機能<14>
@anchor{whatsnew/3 6 new-dict-implementation}@anchor{e5a}@anchor{whatsnew/3 6 whatsnew36-compactdict}@anchor{e2f}
@subsubsection 新たな dict 実装


The @ref{cbd,,dict} type now uses a "compact" representation
based on a proposal by Raymond Hettinger@footnote{https://mail.python.org/pipermail/python-dev/2012-December/123028.html}
which was first implemented by PyPy@footnote{https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html}.
The memory usage of the new @ref{183,,dict()} is between 20% and 25% smaller
compared to Python 3.5.

The order-preserving aspect of this new implementation is considered an
implementation detail and should not be relied upon (this may change in
the future, but it is desired to have this new dict implementation in
the language for a few releases before changing the language spec to mandate
order-preserving semantics for all current and future Python
implementations; this also helps preserve backwards-compatibility
with older versions of the language where random iteration order is
still in effect, e.g. Python 3.5).

(Contributed by INADA Naoki in bpo-27350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27350}. Idea
originally suggested by Raymond Hettinger@footnote{https://mail.python.org/pipermail/python-dev/2012-December/123028.html}.)

@node PEP 523 CPython にフレーム評価 API を追加,PYTHONMALLOC 環境変数,新たな dict 実装,新しい機能<14>
@anchor{whatsnew/3 6 pep-523-adding-a-frame-evaluation-api-to-cpython}@anchor{e5b}@anchor{whatsnew/3 6 whatsnew36-pep523}@anchor{e5c}
@subsubsection PEP 523: CPython にフレーム評価 API を追加


While Python provides extensive support to customize how code
executes, one place it has not done so is in the evaluation of frame
objects.  If you wanted some way to intercept frame evaluation in
Python there really wasn't any way without directly manipulating
function pointers for defined functions.

@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/} changes this by providing an API to make frame
evaluation pluggable at the C level. This will allow for tools such
as debuggers and JITs to intercept frame evaluation before the
execution of Python code begins. This enables the use of alternative
evaluation implementations for Python code, tracking frame
evaluation, etc.

This API is not part of the limited C API and is marked as private to
signal that usage of this API is expected to be limited and only
applicable to very select, low-level use-cases. Semantics of the
API will change with Python as necessary.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 523

@item PEP 523@footnote{https://peps.python.org/pep-0523/} -- Adding a frame evaluation API to CPython

PEP written by Brett Cannon and Dino Viehland.
@end table


@node PYTHONMALLOC 環境変数,DTrace and SystemTap probing support,PEP 523 CPython にフレーム評価 API を追加,新しい機能<14>
@anchor{whatsnew/3 6 pythonmalloc-environment-variable}@anchor{e5d}@anchor{whatsnew/3 6 whatsnew36-pythonmalloc}@anchor{e34}
@subsubsection PYTHONMALLOC 環境変数


新たな環境変数 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} により Python メモリアロケータの設定とデバッグフックの導入ができます。

@code{PYTHONMALLOC=debug} を使用してリリースモードでコンパイルされた Python で、Python メモリアロケータにデバッグフックを導入できるようになりました。デバッグフックの効果は:


@itemize *

@item 
新たに割り当てられたメモリを @code{0xCB} バイトで埋めます

@item 
解放されたメモリを @code{0xDB} バイトで埋めます

@item 
Python メモリアロケータ API の違反を検知します。例えば @ref{e5f,,PyMem_Malloc()} で割り当てられたメモリブロックに @ref{e60,,PyObject_Free()} を呼ぶこと。

@item 
バッファ開始前の書き込み (バッファアンダーフロー) を検知します

@item 
バッファ終端後の書き込み (バッファオーバーフロー) を検知します

@item 
Check that the @ref{474,,GIL} is held when allocator
functions of @ref{e61,,PYMEM_DOMAIN_OBJ} (ex: @ref{e62,,PyObject_Malloc()}) and
@ref{e63,,PYMEM_DOMAIN_MEM} (ex: @ref{e5f,,PyMem_Malloc()}) domains are called.
@end itemize

Checking if the GIL is held is also a new feature of Python 3.6.

See the @ref{e64,,PyMem_SetupDebugHooks()} function for debug hooks on Python
memory allocators.

It is now also possible to force the usage of the @code{malloc()} allocator of
the C library for all Python memory allocations using @code{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
@ref{105,,tracemalloc} module to get the traceback where a memory block was
allocated.

Example of fatal error on buffer overflow using
@code{python3.6 -X tracemalloc=5} (store 5 frames in traces):

@example
Debug memory block at address p=0x7fbcd41666f8: API 'o'
    4 bytes originally requested
    The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
    The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
        at tail+0: 0x02 *** OUCH
        at tail+1: 0xfb
        at tail+2: 0xfb
        at tail+3: 0xfb
        at tail+4: 0xfb
        at tail+5: 0xfb
        at tail+6: 0xfb
        at tail+7: 0xfb
    The block was made by call #1233329 to debug malloc/realloc.
    Data at p: 1a 2b 30 00

Memory block allocated at (most recent call first):
  File "test/test_bytes.py", line 323
  File "unittest/case.py", line 600
  File "unittest/case.py", line 648
  File "unittest/suite.py", line 122
  File "unittest/suite.py", line 84

Fatal Python error: bad trailing pad byte

Current thread 0x00007fbcdbd32700 (most recent call first):
  File "test/test_bytes.py", line 323 in test_hex
  File "unittest/case.py", line 600 in run
  File "unittest/case.py", line 648 in __call__
  File "unittest/suite.py", line 122 in run
  File "unittest/suite.py", line 84 in __call__
  File "unittest/suite.py", line 122 in run
  File "unittest/suite.py", line 84 in __call__
  ...
@end example

(Contributed by Victor Stinner in bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516} and bpo-26564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26564}.)

@node DTrace and SystemTap probing support,,PYTHONMALLOC 環境変数,新しい機能<14>
@anchor{whatsnew/3 6 dtrace-and-systemtap-probing-support}@anchor{e65}@anchor{whatsnew/3 6 whatsnew36-tracing}@anchor{e33}
@subsubsection DTrace and SystemTap probing support


Python can now be built @code{--with-dtrace} which enables static markers
for the following events in the interpreter:


@itemize *

@item 
関数の呼び出し/復帰

@item 
ガベージコレクションの開始/終了

@item 
実行されたコードの行。
@end itemize

This can be used to instrument running interpreters in production,
without the need to recompile specific @ref{509,,debug builds} or
providing application-specific profiling/debugging code.

詳細については @ref{e66,,DTrace と SystemTap で CPython を測定する} を参照してください。

The current implementation is tested on Linux and macOS.  Additional
markers may be added in the future.

(Contributed by Łukasz Langa in bpo-21590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21590}, based on patches by
Jesús Cea Avión, David Malcolm, and Nikhil Benesch.)

@node その他の言語変更<8>,新たなモジュール<8>,新しい機能<14>,What's New In Python 3 6
@anchor{whatsnew/3 6 other-language-changes}@anchor{e67}
@subsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
A @code{global} or @code{nonlocal} statement must now textually appear
before the first use of the affected name in the same scope.
Previously this was a @ref{1ae,,SyntaxWarning}.

@item 
It is now possible to set a @ref{e68,,special method} to
@code{None} to indicate that the corresponding operation is not available.
For example, if a class sets @ref{e69,,__iter__()} to @code{None}, the class
is not iterable.
(Contributed by Andrew Barnert and Ivan Levkivskyi in bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}.)

@item 
Long sequences of repeated traceback lines are now abbreviated as
@code{"[Previous line repeated @{count@} more times]"} (see
@ref{e6a,,traceback} for an example).
(Contributed by Emanuel Barry in bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}.)

@item 
Import now raises the new exception @ref{d3d,,ModuleNotFoundError}
(subclass of @ref{65b,,ImportError}) when it cannot find a module.  Code
that currently checks for ImportError (in try-except) will still work.
(Contributed by Eric Snow in bpo-15767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15767}.)

@item 
Class methods relying on zero-argument @code{super()} will now work correctly
when called from metaclass methods during class creation.
(Contributed by Martin Teichmann in bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}.)
@end itemize

@node 新たなモジュール<8>,改良されたモジュール<8>,その他の言語変更<8>,What's New In Python 3 6
@anchor{whatsnew/3 6 new-modules}@anchor{e6b}
@subsection 新たなモジュール


@menu
* secrets:: 

@end menu

@node secrets,,,新たなモジュール<8>
@anchor{whatsnew/3 6 secrets}@anchor{e6c}@anchor{whatsnew/3 6 whatsnew36-pep506}@anchor{e2e}
@subsubsection secrets


The main purpose of the new @ref{c5,,secrets} module is to provide an obvious way
to reliably generate cryptographically strong pseudo-random values suitable
for managing secrets, such as account authentication, tokens, and similar.

@cartouche
@quotation 警告 
Note that the pseudo-random generators in the @ref{bd,,random} module
should `NOT' be used for security purposes.  Use @ref{c5,,secrets}
on Python 3.6+ and @ref{746,,os.urandom()} on Python 3.5 and earlier.
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 506

@item PEP 506@footnote{https://peps.python.org/pep-0506/} -- Adding A Secrets Module To The Standard Library

PEP written and implemented by Steven D'Aprano.
@end table


@node 改良されたモジュール<8>,最適化<9>,新たなモジュール<8>,What's New In Python 3 6
@anchor{whatsnew/3 6 improved-modules}@anchor{e6d}
@subsection 改良されたモジュール


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

@end menu

@node array<3>,ast<6>,,改良されたモジュール<8>
@anchor{whatsnew/3 6 array}@anchor{e6e}
@subsubsection array


Exhausted iterators of @ref{4be,,array.array} will now stay exhausted even
if the iterated array is extended.  This is consistent with the behavior
of other mutable sequences.

Contributed by Serhiy Storchaka in bpo-26492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26492}.

@node ast<6>,asyncio<12>,array<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 ast}@anchor{e6f}
@subsubsection ast


The new @ref{2ef,,ast.Constant} AST node has been added.  It can be used
by external AST optimizers for the purposes of constant folding.

Contributed by Victor Stinner in bpo-26146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26146}.

@node asyncio<12>,binascii<2>,ast<6>,改良されたモジュール<8>
@anchor{whatsnew/3 6 asyncio}@anchor{e70}
@subsubsection asyncio


Starting with Python 3.6 the @code{asyncio} module is no longer provisional and its
API is considered stable.

Notable changes in the @ref{b,,asyncio} module since Python 3.5.0
(all backported to 3.5.x due to the provisional status):


@itemize *

@item 
The @ref{2f2,,get_event_loop()} function has been changed to
always return the currently running loop when called from coroutines
and callbacks.
(Contributed by Yury Selivanov in bpo-28613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28613}.)

@item 
The @ref{e71,,ensure_future()} function and all functions that
use it, such as @ref{e72,,loop.run_until_complete()},
now accept all kinds of @ref{4c9,,awaitable objects}.
(Contributed by Yury Selivanov.)

@item 
他のスレッドからコルーチンをイベントループに送信するための新たな @ref{a82,,run_coroutine_threadsafe()} 関数。
(Contributed by Vincent Michel.)

@item 
New @ref{e73,,Transport.is_closing()}
method to check if the transport is closing or closed.
(Contributed by Yury Selivanov.)

@item 
The @ref{d09,,loop.create_server()}
method can now accept a list of hosts.
(Contributed by Yann Sionneau.)

@item 
New @ref{e74,,loop.create_future()}
method to create Future objects.  This allows alternative event
loop implementations, such as
uvloop@footnote{https://github.com/MagicStack/uvloop}, to provide a faster
@ref{dc6,,asyncio.Future} implementation.
(Contributed by Yury Selivanov in bpo-27041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27041}.)

@item 
New @ref{e75,,loop.get_exception_handler()}
method to get the current exception handler.
(Contributed by Yury Selivanov in bpo-27040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27040}.)

@item 
新しい @ref{4d0,,StreamReader.readuntil()} メソッドで、区切りとなるバイトの並びが出てくるまでストリームからデータを読み取れるようになりました。
(Contributed by Mark Korenberg.)

@item 
The performance of @ref{e76,,StreamReader.readexactly()}
has been improved.
(Contributed by Mark Korenberg in bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}.)

@item 
The @ref{e0e,,loop.getaddrinfo()}
method is optimized to avoid calling the system @code{getaddrinfo}
function if the address is already resolved.
(Contributed by A. Jesse Jiryu Davis.)

@item 
The @ref{e77,,loop.stop()}
method has been changed to stop the loop immediately after
the current iteration.  Any new callbacks scheduled as a result
of the last iteration will be discarded.
(Contributed by Guido van Rossum in bpo-25593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25593}.)

@item 
@ref{e78,,Future.set_exception}
will now raise @ref{198,,TypeError} when passed an instance of
the @ref{df5,,StopIteration} exception.
(Contributed by Chris Angelico in bpo-26221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26221}.)

@item 
New @ref{9de,,loop.connect_accepted_socket()}
method to be used by servers that accept connections outside of asyncio,
but that use asyncio to handle them.
(Contributed by Jim Fulton in bpo-27392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27392}.)

@item 
@code{TCP_NODELAY} flag is now set for all TCP transports by default.
(Contributed by Yury Selivanov in bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}.)

@item 
New @ref{e79,,loop.shutdown_asyncgens()}
to properly close pending asynchronous generators before closing the
loop.
(Contributed by Yury Selivanov in bpo-28003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28003}.)

@item 
@ref{dc6,,Future} and @ref{1c7,,Task}
classes now have an optimized C implementation which makes asyncio
code up to 30% faster.
(Contributed by Yury Selivanov and INADA Naoki in bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}
and bpo-28544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28544}.)
@end itemize

@node binascii<2>,cmath,asyncio<12>,改良されたモジュール<8>
@anchor{whatsnew/3 6 binascii}@anchor{e7a}
@subsubsection binascii


The @ref{e7b,,b2a_base64()} 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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25357}.)

@node cmath,collections<4>,binascii<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 cmath}@anchor{e7c}
@subsubsection cmath


The new @ref{e7d,,cmath.tau} (`τ') constant has been added.
(Contributed by Lisa Roach in bpo-12345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12345}, see 
@geindex Python Enhancement Proposals; PEP 628
PEP 628@footnote{https://peps.python.org/pep-0628/} for details.)

新たに定数が追加されました。 @ref{e7e,,math.inf} と @ref{873,,math.nan} に対応する @ref{e7f,,cmath.inf} と @ref{e80,,cmath.nan}。複素数の repr が使用する書式に対応する @ref{e81,,cmath.infj} と @ref{e82,,cmath.nanj}。
(Contributed by Mark Dickinson in bpo-23229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23229}.)

@node collections<4>,concurrent futures<5>,cmath,改良されたモジュール<8>
@anchor{whatsnew/3 6 collections}@anchor{e83}
@subsubsection collections


The new @ref{e84,,Collection} abstract base class has been
added to represent sized iterable container classes.
(Contributed by Ivan Levkivskyi, docs by Neil Girdhar in bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}.)

The new @ref{e85,,Reversible} abstract base class represents
iterable classes that also provide the @ref{e86,,__reversed__()} method.
(Contributed by Ivan Levkivskyi in bpo-25987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25987}.)

The new @ref{e87,,AsyncGenerator} abstract base class represents
asynchronous generators.
(Contributed by Yury Selivanov in bpo-28720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28720}.)

The @ref{4e0,,namedtuple()} function now accepts an optional
keyword argument `module', which, when specified, is used for
the @ref{617,,__module__} attribute of the returned named tuple class.
(Contributed by Raymond Hettinger in bpo-17941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17941}.)

The `verbose' and `rename' arguments for
@ref{4e0,,namedtuple()} are now keyword-only.
(Contributed by Raymond Hettinger in bpo-25628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25628}.)

Recursive @ref{7f4,,collections.deque} instances can now be pickled.
(Contributed by Serhiy Storchaka in bpo-26482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26482}.)

@node concurrent futures<5>,contextlib<4>,collections<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 concurrent-futures}@anchor{e88}
@subsubsection concurrent.futures


The @ref{949,,ThreadPoolExecutor}
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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27664}.)

@node contextlib<4>,datetime<6>,concurrent futures<5>,改良されたモジュール<8>
@anchor{whatsnew/3 6 contextlib}@anchor{e89}
@subsubsection contextlib


The @ref{e8a,,contextlib.AbstractContextManager} class has been added to
provide an abstract base class for context managers.  It provides a
sensible default implementation for @code{__enter__()} which returns
@code{self} and leaves @code{__exit__()} an abstract method.  A matching
class has been added to the @ref{10a,,typing} module as
@ref{e8b,,typing.ContextManager}.
(Contributed by Brett Cannon in bpo-25609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25609}.)

@node datetime<6>,decimal<3>,contextlib<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 datetime}@anchor{e8c}
@subsubsection datetime


The @ref{4e2,,datetime} and @ref{1fb,,time} classes have
the new @ref{e8d,,fold} attribute used to disambiguate local time
when necessary.  Many functions in the @ref{34,,datetime} have been
updated to support local time disambiguation.
See @ref{e36,,Local Time Disambiguation} section for more
information.
(Contributed by Alexander Belopolsky in bpo-24773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24773}.)

The @ref{e8e,,datetime.strftime()} and
@ref{e8f,,date.strftime()} methods now support
ISO 8601 date directives @code{%G}, @code{%u} and @code{%V}.
(Contributed by Ashley Anderson in bpo-12006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12006}.)

The @ref{d25,,datetime.isoformat()} 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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19475}.)

The @ref{e90,,datetime.combine()} now
accepts an optional `tzinfo' argument.
(Contributed by Alexander Belopolsky in bpo-27661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27661}.)

@node decimal<3>,distutils<5>,datetime<6>,改良されたモジュール<8>
@anchor{whatsnew/3 6 decimal}@anchor{e91}
@subsubsection decimal


New @ref{e92,,Decimal.as_integer_ratio()}
method that returns a pair @code{(n, d)} of integers that represent the given
@ref{1fe,,Decimal} instance as a fraction, in lowest terms and
with a positive denominator:

@example
>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)
@end example

(Contributed by Stefan Krah amd Mark Dickinson in bpo-25928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25928}.)

@node distutils<5>,email<3>,decimal<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 distutils}@anchor{e93}
@subsubsection distutils


The @code{default_format} attribute has been removed from
@code{distutils.command.sdist.sdist} and the @code{formats}
attribute defaults to @code{['gztar']}. Although not anticipated,
any code relying on the presence of @code{default_format} may
need to be adapted. See bpo-27819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27819} for more details.

@node email<3>,エンコーディング<2>,distutils<5>,改良されたモジュール<8>
@anchor{whatsnew/3 6 email}@anchor{e94}
@subsubsection email


The new email API, enabled via the `policy' keyword to various constructors, is
no longer provisional.  The @ref{3f,,email} documentation has been reorganized and
rewritten to focus on the new API, while retaining the old documentation for
the legacy API.  (Contributed by R. David Murray in bpo-24277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24277}.)

The @ref{49,,email.mime} classes now all accept an optional `policy' keyword.
(Contributed by Berker Peksag in bpo-27331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27331}.)

The @ref{e95,,DecodedGenerator} now supports the `policy'
keyword.

There is a new @ref{53,,policy} attribute,
@ref{e96,,message_factory}, that controls what class is used
by default when the parser creates new message objects.  For the
@ref{e97,,email.policy.compat32} policy this is @ref{581,,Message},
for the new policies it is @ref{580,,EmailMessage}.
(Contributed by R. David Murray in bpo-20476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20476}.)

@node エンコーディング<2>,enum<7>,email<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 encodings}@anchor{e98}
@subsubsection エンコーディング


On Windows, added the @code{'oem'} encoding to use @code{CP_OEMCP}, and the @code{'ansi'}
alias for the existing @code{'mbcs'} encoding, which uses the @code{CP_ACP} code page.
(Contributed by Steve Dower in bpo-27959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27959}.)

@node enum<7>,faulthandler<3>,エンコーディング<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 enum}@anchor{e99}
@subsubsection enum


Two new enumeration base classes have been added to the @ref{5a,,enum} module:
@ref{835,,Flag} and @ref{e9a,,IntFlag}.  Both are used to define
constants that can be combined using the bitwise operators.
(Contributed by Ethan Furman in bpo-23591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23591}.)

Many standard library modules have been updated to use the
@ref{e9a,,IntFlag} class for their constants.

The new @ref{e9b,,enum.auto} value can be used to assign values to enum
members automatically:

@example
>>> from enum import Enum, auto
>>> class Color(Enum):
...     red = auto()
...     blue = auto()
...     green = auto()
...
>>> list(Color)
[<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]
@end example

@node faulthandler<3>,fileinput<2>,enum<7>,改良されたモジュール<8>
@anchor{whatsnew/3 6 faulthandler}@anchor{e9c}
@subsubsection faulthandler


On Windows, the @ref{5c,,faulthandler} module now installs a handler for Windows
exceptions: see @ref{20f,,faulthandler.enable()}. (Contributed by Victor Stinner in
bpo-23848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23848}.)

@node fileinput<2>,hashlib<5>,faulthandler<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 fileinput}@anchor{e9d}
@subsubsection fileinput


@ref{e9e,,hook_encoded()} now supports the `errors' argument.
(Contributed by Joseph Hackman in bpo-25788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25788}.)

@node hashlib<5>,http client<2>,fileinput<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 hashlib}@anchor{e9f}
@subsubsection hashlib


@ref{6c,,hashlib} supports OpenSSL 1.1.0.  The minimum recommend version is 1.0.2.
(Contributed by Christian Heimes in bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}.)

BLAKE2 hash functions were added to the module. @ref{852,,blake2b()}
and @ref{853,,blake2s()} are always available and support the full
feature set of BLAKE2.
(Contributed by Christian Heimes in bpo-26798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26798} based on code by
Dmitry Chestnykh and Samuel Neves. Documentation written by Dmitry Chestnykh.)

The SHA-3 hash functions @ref{ea0,,sha3_224()}, @ref{ea1,,sha3_256()},
@ref{ea2,,sha3_384()}, @ref{ea3,,sha3_512()}, and SHAKE hash functions
@ref{ea4,,shake_128()} and @ref{ea5,,shake_256()} were added.
(Contributed by Christian Heimes in bpo-16113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16113}. Keccak Code Package
by Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van Assche, and
Ronny Van Keer.)

The password-based key derivation function @ref{e38,,scrypt()} is now
available with OpenSSL 1.1.0 and newer.
(Contributed by Christian Heimes in bpo-27928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27928}.)

@node http client<2>,idlelib と IDLE<2>,hashlib<5>,改良されたモジュール<8>
@anchor{whatsnew/3 6 http-client}@anchor{ea6}
@subsubsection http.client


@ref{ea7,,HTTPConnection.request()} and
@ref{ea8,,endheaders()} both now support
chunked encoding request bodies.
(Contributed by Demian Brecht and Rolf Krahl in bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}.)

@node idlelib と IDLE<2>,importlib<6>,http client<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 idlelib-and-idle}@anchor{ea9}
@subsubsection idlelib と IDLE


The idlelib package is being modernized and refactored to make IDLE look and
work better and to make the code easier to understand, test, and improve. Part
of making IDLE look better, especially on Linux and Mac, is using ttk widgets,
mostly in the dialogs.  As a result, IDLE no longer runs with tcl/tk 8.4.  It
now requires tcl/tk 8.5 or 8.6.  We recommend running the latest release of
either.

'Modernizing' includes renaming and consolidation of idlelib modules. The
renaming of files with partial uppercase names is similar to the renaming of,
for instance, Tkinter and TkFont to tkinter and tkinter.font in 3.0.  As a
result, imports of idlelib files that worked in 3.5 will usually not work in
3.6.  At least a module name change will be needed (see idlelib/README.txt),
sometimes more.  (Name changes contributed by Al Swiegart and Terry Reedy in
bpo-24225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24225}.  Most idlelib patches since have been and will be part of the
process.)

In compensation, the eventual result with be that some idlelib classes will be
easier to use, with better APIs and docstrings explaining them.  Additional
useful information will be added to idlelib when available.

New in 3.6.2:

自動補完におけるいくつもの修正。
(Contributed by Louie Lu in bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786}.)

New in 3.6.3:

Module Browser (on the File menu, formerly called Class Browser),
now displays nested functions and classes in addition to top-level
functions and classes.
(Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy
in bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262}.)

The IDLE features formerly implemented as extensions have been reimplemented
as normal features.  Their settings have been moved from the Extensions tab
to other dialog tabs.
(Contributed by Charles Wohlganger and Terry Jan Reedy in bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099}.)

The Settings dialog (Options, Configure IDLE) has been partly rewritten
to improve both appearance and function.
(Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)

New in 3.6.4:

The font sample now includes a selection of non-Latin characters so that
users can better see the effect of selecting a particular font.
(Contributed by Terry Jan Reedy in bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802}.)
The sample can be edited to include other characters.
(Contributed by Serhiy Storchaka in bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860}.)

New in 3.6.6:

Editor code context option revised.  Box displays all context lines up to
maxlines.  Clicking on a context line jumps the editor to that line.  Context
colors for custom themes is added to Highlights tab of Settings dialog.
(Contributed by Cheryl Sabella and Terry Jan Reedy in bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642},
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}, and bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}.)

On Windows, a new API call tells Windows 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.
(Contributed by Terry Jan Reedy in bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}.)

New in 3.6.7:

Output over N lines (50 by default) is squeezed down to a button.
N can be changed in the PyShell section of the General page of the
Settings dialog.  Fewer, but possibly extra long, lines can be squeezed by
right clicking on the output.  Squeezed output can be expanded in place
by double-clicking the button or into the clipboard or a separate window
by right-clicking the button.  (Contributed by Tal Einat in bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353}.)

@node importlib<6>,inspect<7>,idlelib と IDLE<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 importlib}@anchor{eaa}
@subsubsection importlib


Import now raises the new exception @ref{d3d,,ModuleNotFoundError}
(subclass of @ref{65b,,ImportError}) when it cannot find a module.  Code
that current checks for @code{ImportError} (in try-except) will still work.
(Contributed by Eric Snow in bpo-15767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15767}.)

@ref{eab,,importlib.util.LazyLoader} now calls
@ref{eac,,create_module()} on the wrapped loader, removing the
restriction that @ref{ead,,importlib.machinery.BuiltinImporter} and
@ref{eae,,importlib.machinery.ExtensionFileLoader} couldn't be used with
@ref{eab,,importlib.util.LazyLoader}.

@ref{353,,importlib.util.cache_from_source()},
@ref{73e,,importlib.util.source_from_cache()}, and
@ref{eaf,,importlib.util.spec_from_file_location()} now accept a
@ref{5a1,,path-like object}.

@node inspect<7>,json<2>,importlib<6>,改良されたモジュール<8>
@anchor{whatsnew/3 6 inspect}@anchor{eb0}
@subsubsection inspect


The @ref{22f,,inspect.signature()} function now reports the
implicit @code{.0} parameters generated by the compiler for comprehension and
generator expression scopes as if they were positional-only parameters called
@code{implicit0}. (Contributed by Jelle Zijlstra in bpo-19611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19611}.)

To reduce code churn when upgrading from Python 2.7 and the legacy
@code{inspect.getargspec()} API, the previously documented deprecation of
@ref{941,,inspect.getfullargspec()} has been reversed. While this function is
convenient for single/source Python 2/3 code bases, the richer
@ref{22f,,inspect.signature()} interface remains the recommended approach for new
code. (Contributed by Nick Coghlan in bpo-27172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27172})

@node json<2>,logging<4>,inspect<7>,改良されたモジュール<8>
@anchor{whatsnew/3 6 json}@anchor{eb1}
@subsubsection json


@ref{eb2,,json.load()} と @ref{b4e,,json.loads()} は、バイナリ入力をサポートしました。エンコード済みのJSON は、 UTF-8, UTF-16, UTF-32のいずれかを返すべきです。 (Contributed by Serhiy Storchaka in bpo-17909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17909}.)

@node logging<4>,math<8>,json<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 logging}@anchor{eb3}
@subsubsection logging


新しく @ref{eb4,,WatchedFileHandler.reopenIfNeeded()} メソッドが追加され、ログファイルを再オープンする必要があるかどうかをチェックする機能が追加れました。(Contributed by Marian Horban in bpo-24884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24884}.)

@node math<8>,multiprocessing<6>,logging<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 math}@anchor{eb5}
@subsubsection math


The tau (`τ') constant has been added to the @ref{92,,math} and @ref{19,,cmath}
modules.
(Contributed by Lisa Roach in bpo-12345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12345}, see 
@geindex Python Enhancement Proposals; PEP 628
PEP 628@footnote{https://peps.python.org/pep-0628/} for details.)

@node multiprocessing<6>,os<9>,math<8>,改良されたモジュール<8>
@anchor{whatsnew/3 6 multiprocessing}@anchor{eb6}
@subsubsection multiprocessing


@ref{24c,,Proxy Objects} returned by
@ref{250,,multiprocessing.Manager()} can now be nested.
(Contributed by Davin Potts in bpo-6766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6766}.)

@node os<9>,pathlib<12>,multiprocessing<6>,改良されたモジュール<8>
@anchor{whatsnew/3 6 os}@anchor{eb7}
@subsubsection os


See the summary of @ref{e35,,PEP 519} for details on how the
@ref{a5,,os} and @ref{a6,,os.path} modules now support
@ref{5a1,,path-like objects}.

@ref{c54,,scandir()} now supports @ref{192,,bytes} paths on Windows.

A new @ref{eb8,,close()} method allows explicitly closing a
@ref{c54,,scandir()} iterator.  The @ref{c54,,scandir()} iterator now
supports the @ref{1e1,,context manager} protocol.  If a @code{scandir()}
iterator is neither exhausted nor explicitly closed a @ref{54c,,ResourceWarning}
will be emitted in its destructor.
(Contributed by Serhiy Storchaka in bpo-25994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25994}.)

On Linux, @ref{746,,os.urandom()} now blocks until the system urandom entropy pool
is initialized to increase the security. See the 
@geindex Python Enhancement Proposals; PEP 524
PEP 524@footnote{https://peps.python.org/pep-0524/} for the rationale.

The Linux @code{getrandom()} syscall (get random bytes) is now exposed as the new
@ref{eb9,,os.getrandom()} function.
(Contributed by Victor Stinner, part of the 
@geindex Python Enhancement Proposals; PEP 524
PEP 524@footnote{https://peps.python.org/pep-0524/})

@node pathlib<12>,pdb<7>,os<9>,改良されたモジュール<8>
@anchor{whatsnew/3 6 pathlib}@anchor{eba}
@subsubsection pathlib


@ref{a8,,pathlib} は @ref{5a1,,path-like objects} をサポートしました。 (Contributed by Brett Cannon in bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}.)

詳細は、 @ref{e35,,PEP 519} の要約を参照してください。

@node pdb<7>,pickle<3>,pathlib<12>,改良されたモジュール<8>
@anchor{whatsnew/3 6 pdb}@anchor{ebb}
@subsubsection pdb


@ref{273,,Pdb} クラスのコンストラクタに、新しくオプション引数 `readrc' が増えました。この引数は、 @code{.pdbrc} ファイルを読み込むかどうかを指定します。

@node pickle<3>,pickletools,pdb<7>,改良されたモジュール<8>
@anchor{whatsnew/3 6 pickle}@anchor{ebc}
@subsubsection pickle


Objects that need @code{__new__} called with keyword arguments can now be pickled
using @ref{27b,,pickle protocols} older than protocol version 4.
Protocol version 4 already supports this case.  (Contributed by Serhiy
Storchaka in bpo-24164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24164}.)

@node pickletools,pydoc<4>,pickle<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 pickletools}@anchor{ebd}
@subsubsection pickletools


@ref{ebe,,pickletools.dis()} now outputs the implicit memo index for the
@code{MEMOIZE} opcode.
(Contributed by Serhiy Storchaka in bpo-25382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25382}.)

@node pydoc<4>,random<4>,pickletools,改良されたモジュール<8>
@anchor{whatsnew/3 6 pydoc}@anchor{ebf}
@subsubsection pydoc


The @ref{ba,,pydoc} module has learned to respect the @code{MANPAGER}
environment variable.
(Contributed by Matthias Klose in bpo-8637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8637}.)

@ref{ad4,,help()} and @ref{ba,,pydoc} can now list named tuple fields in the
order they were defined rather than alphabetically.
(Contributed by Raymond Hettinger in bpo-24879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24879}.)

@node random<4>,re<6>,pydoc<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 random}@anchor{ec0}
@subsubsection random


The new @ref{ec1,,choices()} function returns a list of elements of
specified size from the given population with optional weights.
(Contributed by Raymond Hettinger in bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}.)

@node re<6>,readline,random<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 re}@anchor{ec2}
@subsubsection re


Added support of modifier spans in regular expressions.  Examples:
@code{'(?i:p)ython'} matches @code{'python'} and @code{'Python'}, but not @code{'PYTHON'};
@code{'(?i)g(?-i:v)r'} matches @code{'GvR'} and @code{'gvr'}, but not @code{'GVR'}.
(Contributed by Serhiy Storchaka in bpo-433028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=433028}.)

Match object groups can be accessed by @code{__getitem__}, which is
equivalent to @code{group()}.  So @code{mo['name']} is now equivalent to
@code{mo.group('name')}.  (Contributed by Eric Smith in bpo-24454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24454}.)

@ref{ec3,,Match} objects now support
@ref{19e,,index-like objects} as group
indices.
(Contributed by Jeroen Demeyer and Xiang Zhang in bpo-27177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27177}.)

@node readline,rlcompleter,re<6>,改良されたモジュール<8>
@anchor{whatsnew/3 6 readline}@anchor{ec4}
@subsubsection readline


Added @ref{ec5,,set_auto_history()} to enable or disable
automatic addition of input to the history list.  (Contributed by
Tyler Crompton in bpo-26870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26870}.)

@node rlcompleter,shlex<2>,readline,改良されたモジュール<8>
@anchor{whatsnew/3 6 rlcompleter}@anchor{ec6}
@subsubsection rlcompleter


Private and special attribute names now are omitted unless the prefix starts
with underscores.  A space or a colon is added after some completed keywords.
(Contributed by Serhiy Storchaka in bpo-25011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25011} and bpo-25209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25209}.)

@node shlex<2>,site<3>,rlcompleter,改良されたモジュール<8>
@anchor{whatsnew/3 6 shlex}@anchor{ec7}
@subsubsection shlex


The @ref{ec8,,shlex} has much
@ref{ec9,,improved shell compatibility}
through the new `punctuation_chars' argument to control which characters
are treated as punctuation.
(Contributed by Vinay Sajip in bpo-1521950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1521950}.)

@node site<3>,sqlite3<8>,shlex<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 site}@anchor{eca}
@subsubsection site


When specifying paths to add to @ref{3e4,,sys.path} in a @code{.pth} file,
you may now specify file paths on top of directories (e.g. zip files).
(Contributed by Wolfgang Langner in bpo-26587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26587}).

@node sqlite3<8>,socket<8>,site<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 sqlite3}@anchor{ecb}
@subsubsection sqlite3


@ref{ecc,,sqlite3.Cursor.lastrowid} は、 @code{REPLACE} 文をサポートしました。 (Contributed by Alex LordThorsen in bpo-16864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16864}.)

@node socket<8>,socketserver<2>,sqlite3<8>,改良されたモジュール<8>
@anchor{whatsnew/3 6 socket}@anchor{ecd}
@subsubsection socket


The @ref{ece,,ioctl()} function now supports the
@ref{ecf,,SIO_LOOPBACK_FAST_PATH} control code.
(Contributed by Daniel Stokes in bpo-26536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26536}.)

The @ref{ed0,,getsockopt()} constants @code{SO_DOMAIN},
@code{SO_PROTOCOL}, @code{SO_PEERSEC}, and @code{SO_PASSSEC} are now supported.
(Contributed by Christian Heimes in bpo-26907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26907}.)

The @ref{ed1,,setsockopt()} now supports the
@code{setsockopt(level, optname, None, optlen: int)} form.
(Contributed by Christian Heimes in bpo-27744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27744}.)

The socket module now supports the address family
@ref{ed2,,AF_ALG} to interface with Linux Kernel crypto API. @code{ALG_*},
@code{SOL_ALG} and @ref{ed3,,sendmsg_afalg()} were added.
(Contributed by Christian Heimes in bpo-27744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27744} with support from
Victor Stinner.)

New Linux constants @code{TCP_USER_TIMEOUT} and @code{TCP_CONGESTION} were added.
(Contributed by Omar Sandoval, bpo-26273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26273}).

@node socketserver<2>,ssl<8>,socket<8>,改良されたモジュール<8>
@anchor{whatsnew/3 6 socketserver}@anchor{ed4}
@subsubsection socketserver


Servers based on the @ref{d2,,socketserver} module, including those
defined in @ref{76,,http.server}, @ref{135,,xmlrpc.server} and
@ref{121,,wsgiref.simple_server}, now support the @ref{1e1,,context manager}
protocol.
(Contributed by Aviv Palivoda in bpo-26404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26404}.)

The @ref{ed5,,wfile} attribute of
@ref{ed6,,StreamRequestHandler} classes now implements
the @ref{8a3,,io.BufferedIOBase} writable interface.  In particular,
calling @ref{ed7,,write()} is now guaranteed to send the
data in full.  (Contributed by Martin Panter in bpo-26721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26721}.)

@node ssl<8>,statistics<5>,socketserver<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 ssl}@anchor{ed8}
@subsubsection ssl


@ref{d5,,ssl} supports OpenSSL 1.1.0.  The minimum recommend version is 1.0.2.
(Contributed by Christian Heimes in bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}.)

3DES has been removed from the default cipher suites and ChaCha20 Poly1305
cipher suites have been added.
(Contributed by Christian Heimes in bpo-27850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27850} and bpo-27766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27766}.)

@ref{357,,SSLContext} has better default configuration for options
and ciphers.
(Contributed by Christian Heimes in bpo-28043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28043}.)

SSL session can be copied from one client-side connection to another
with the new @ref{ed9,,SSLSession} class.  TLS session resumption can
speed up the initial handshake, reduce latency and improve performance
(Contributed by Christian Heimes in bpo-19500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19500} based on a draft by
Alex Warhawk.)

The new @ref{eda,,get_ciphers()} method can be used to
get a list of enabled ciphers in order of cipher priority.

All constants and flags have been converted to @ref{edb,,IntEnum} and
@ref{e9a,,IntFlag}.
(Contributed by Christian Heimes in bpo-28025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28025}.)

Server and client-side specific TLS protocols for @ref{357,,SSLContext}
were added.
(Contributed by Christian Heimes in bpo-28085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28085}.)

Added @ref{c26,,ssl.SSLContext.post_handshake_auth} to enable and
@ref{c27,,ssl.SSLSocket.verify_client_post_handshake()} to initiate TLS 1.3
post-handshake authentication.
(Contributed by Christian Heimes in gh-78851@footnote{https://github.com/python/cpython/issues/78851}.)

@node statistics<5>,struct<2>,ssl<8>,改良されたモジュール<8>
@anchor{whatsnew/3 6 statistics}@anchor{edc}
@subsubsection statistics


A new @ref{edd,,harmonic_mean()} function has been added.
(Contributed by Steven D'Aprano in bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}.)

@node struct<2>,subprocess<3>,statistics<5>,改良されたモジュール<8>
@anchor{whatsnew/3 6 struct}@anchor{ede}
@subsubsection struct


@ref{db,,struct} now supports IEEE 754 half-precision floats via the @code{'e'}
format specifier.
(Contributed by Eli Stevens, Mark Dickinson in bpo-11734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11734}.)

@node subprocess<3>,sys<10>,struct<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 subprocess}@anchor{edf}
@subsubsection subprocess


@ref{4b7,,subprocess.Popen} destructor now emits a @ref{54c,,ResourceWarning} warning
if the child process is still running. Use the context manager protocol (@code{with
proc: ...}) or explicitly call the @ref{ee0,,wait()} method to
read the exit status of the child process. (Contributed by Victor Stinner in
bpo-26741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26741}.)

The @ref{4b7,,subprocess.Popen} 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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6135}.)

@node sys<10>,telnetlib,subprocess<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 sys}@anchor{ee1}
@subsubsection sys


The new @ref{ee2,,getfilesystemencodeerrors()} function returns the name of
the error mode used to convert between Unicode filenames and bytes filenames.
(Contributed by Steve Dower in bpo-27781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27781}.)

On Windows the return value of the @ref{ee3,,getwindowsversion()} 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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}.)

@node telnetlib,time<6>,sys<10>,改良されたモジュール<8>
@anchor{whatsnew/3 6 telnetlib}@anchor{ee4}
@subsubsection telnetlib


@code{telnetlib.Telnet} is now a context manager (contributed by
Stéphane Wirtel in bpo-25485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25485}).

@node time<6>,timeit,telnetlib,改良されたモジュール<8>
@anchor{whatsnew/3 6 time}@anchor{ee5}
@subsubsection time


The @ref{ee6,,struct_time} attributes @code{tm_gmtoff} and
@code{tm_zone} are now available on all platforms.

@node timeit,tkinter<7>,time<6>,改良されたモジュール<8>
@anchor{whatsnew/3 6 timeit}@anchor{ee7}
@subsubsection timeit


The new @ref{ee8,,Timer.autorange()} convenience
method has been added to call @ref{ee9,,Timer.timeit()}
repeatedly so that the total run time is greater or equal to 200 milliseconds.
(Contributed by Steven D'Aprano in bpo-6422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6422}.)

@ref{f5,,timeit} now warns when there is substantial (4x) variance
between best and worst times.
(Contributed by Serhiy Storchaka in bpo-23552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23552}.)

@node tkinter<7>,traceback<4>,timeit,改良されたモジュール<8>
@anchor{whatsnew/3 6 tkinter}@anchor{eea}
@subsubsection tkinter


Added methods @code{Variable.trace_add()},
@code{Variable.trace_remove()} and @code{trace_info()}
in the @code{tkinter.Variable} class.  They replace old methods
@code{trace_variable()}, @code{trace()},
@code{trace_vdelete()} and
@code{trace_vinfo()} that use obsolete Tcl commands and might
not work in future versions of Tcl.
(Contributed by Serhiy Storchaka in bpo-22115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22115}).

@node traceback<4>,tracemalloc<3>,tkinter<7>,改良されたモジュール<8>
@anchor{whatsnew/3 6 traceback}@anchor{eeb}@anchor{whatsnew/3 6 whatsnew36-traceback}@anchor{e6a}
@subsubsection traceback


Both the traceback module and the interpreter's builtin exception display now
abbreviate long sequences of repeated lines in tracebacks as shown in the
following example:

@example
>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
@end example

(Contributed by Emanuel Barry in bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}.)

@node tracemalloc<3>,typing<10>,traceback<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 tracemalloc}@anchor{eec}
@subsubsection tracemalloc


The @ref{105,,tracemalloc} module now supports tracing memory allocations in
multiple different address spaces.

The new @ref{eed,,DomainFilter} filter class has been added
to filter block traces by their address space (domain).

(Contributed by Victor Stinner in bpo-26588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26588}.)

@node typing<10>,unicodedata<8>,tracemalloc<3>,改良されたモジュール<8>
@anchor{whatsnew/3 6 typing}@anchor{eee}@anchor{whatsnew/3 6 whatsnew36-typing}@anchor{e37}
@subsubsection typing


Since the @ref{10a,,typing} module is @ref{3d1,,provisional},
all changes introduced in Python 3.6 have also been
backported to Python 3.5.x.

The @ref{10a,,typing} module has a much improved support for generic type
aliases.  For example @code{Dict[str, Tuple[S, T]]} is now a valid
type annotation.
(Contributed by Guido van Rossum in Github #195@footnote{https://github.com/python/typing/pull/195}.)

The @ref{e8b,,typing.ContextManager} class has been added for
representing @ref{e8a,,contextlib.AbstractContextManager}.
(Contributed by Brett Cannon in bpo-25609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25609}.)

The @ref{eef,,typing.Collection} class has been added for
representing @ref{e84,,collections.abc.Collection}.
(Contributed by Ivan Levkivskyi in bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}.)

The @ref{56d,,typing.ClassVar} type construct has been added to
mark class variables.  As introduced in 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/}, a variable annotation
wrapped in ClassVar indicates that a given attribute is intended to be used as
a class variable and should not be set on instances of that class.
(Contributed by Ivan Levkivskyi in Github #280@footnote{https://github.com/python/typing/pull/280}.)

A new @ref{ef0,,TYPE_CHECKING} constant that is assumed to be
@code{True} by the static type checkers, but is @code{False} at runtime.
(Contributed by Guido van Rossum in Github #230@footnote{https://github.com/python/typing/issues/230}.)

A new @ref{ef1,,NewType()} helper function has been added to create
lightweight distinct types for annotations:

@example
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
@end example

The static type checker will treat the new type as if it were a subclass
of the original type.  (Contributed by Ivan Levkivskyi in Github #189@footnote{https://github.com/python/typing/issues/189}.)

@node unicodedata<8>,unittest mock<2>,typing<10>,改良されたモジュール<8>
@anchor{whatsnew/3 6 unicodedata}@anchor{ef2}
@subsubsection unicodedata


The @ref{10b,,unicodedata} module now uses data from Unicode 9.0.0@footnote{https://unicode.org/versions/Unicode9.0.0/}.
(Contributed by Benjamin Peterson.)

@node unittest mock<2>,urllib request,unicodedata<8>,改良されたモジュール<8>
@anchor{whatsnew/3 6 unittest-mock}@anchor{ef3}
@subsubsection unittest.mock


@ref{c3f,,Mock} クラスは、次の改善が行われました。


@itemize *

@item 
@ref{ef4,,Mock.assert_called()} と @ref{ef5,,Mock.assert_called_once()} は、mockオブジェクトが呼ばれたかどうかを確認します。 (Contributed by Amit Saha in bpo-26323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26323}.)

@item 
The @ref{ef6,,Mock.reset_mock()} method
now has two optional keyword only arguments: `return_value' and
`side_effect'.
(Contributed by Kushal Das in bpo-21271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21271}.)
@end itemize

@node urllib request,urllib robotparser,unittest mock<2>,改良されたモジュール<8>
@anchor{whatsnew/3 6 urllib-request}@anchor{ef7}
@subsubsection urllib.request


If a HTTP request has a file or iterable body (other than a
bytes object) but no @code{Content-Length} header, rather than
throwing an error, @ref{ef8,,AbstractHTTPHandler}
now falls back to use chunked transfer encoding.
(Contributed by Demian Brecht and Rolf Krahl in bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}.)

@node urllib robotparser,venv<5>,urllib request,改良されたモジュール<8>
@anchor{whatsnew/3 6 urllib-robotparser}@anchor{ef9}
@subsubsection urllib.robotparser


@ref{efa,,RobotFileParser} now supports the @code{Crawl-delay} and
@code{Request-rate} extensions.
(Contributed by Nikolay Bogoychev in bpo-16099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16099}.)

@node venv<5>,warnings<4>,urllib robotparser,改良されたモジュール<8>
@anchor{whatsnew/3 6 venv}@anchor{efb}
@subsubsection venv


@code{venv は、新しいパラメータ `}--prompt`@w{`} を受け入れました。このパラメータは、 仮想環境を表すプリフィックスを指定します。 (Proposed by Łukasz Balcerzak and ported to 3.6 by Stéphane Wirtel in bpo-22829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22829}.)

@node warnings<4>,winreg,venv<5>,改良されたモジュール<8>
@anchor{whatsnew/3 6 warnings}@anchor{efc}
@subsubsection warnings


A new optional `source' parameter has been added to the
@ref{efd,,warnings.warn_explicit()} function: the destroyed object which emitted a
@ref{54c,,ResourceWarning}. A `source' attribute has also been added to
@code{warnings.WarningMessage} (contributed by Victor Stinner in
bpo-26568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26568} and bpo-26567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26567}).

When a @ref{54c,,ResourceWarning} warning is logged, the @ref{105,,tracemalloc} module is now
used to try to retrieve the traceback where the destroyed object was allocated.

スクリプト @code{example.py} での例:

@example
import warnings

def func():
    return open(__file__)

f = func()
f = None
@end example

Output of the command @code{python3.6 -Wd -X tracemalloc=5 example.py}:

@example
example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
  f = None
Object allocated at (most recent call first):
  File "example.py", lineno 4
    return open(__file__)
  File "example.py", lineno 6
    f = func()
@end example

The "Object allocated at" traceback is new and is only displayed if
@ref{105,,tracemalloc} is tracing Python memory allocations and if the
@ref{118,,warnings} module was already imported.

@node winreg,winsound,warnings<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 winreg}@anchor{efe}
@subsubsection winreg


Added the 64-bit integer type @ref{eff,,REG_QWORD}.
(Contributed by Clement Rouault in bpo-23026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23026}.)

@node winsound,xmlrpc client,winreg,改良されたモジュール<8>
@anchor{whatsnew/3 6 winsound}@anchor{f00}
@subsubsection winsound


Allowed keyword arguments to be passed to @ref{f01,,Beep},
@ref{f02,,MessageBeep}, and @ref{f03,,PlaySound} (bpo-27982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27982}).

@node xmlrpc client,zipfile<4>,winsound,改良されたモジュール<8>
@anchor{whatsnew/3 6 xmlrpc-client}@anchor{f04}
@subsubsection xmlrpc.client


The @ref{134,,xmlrpc.client} module now supports unmarshalling
additional data types used by the Apache XML-RPC implementation
for numerics and @code{None}.
(Contributed by Serhiy Storchaka in bpo-26885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26885}.)

@node zipfile<4>,zlib<2>,xmlrpc client,改良されたモジュール<8>
@anchor{whatsnew/3 6 zipfile}@anchor{f05}
@subsubsection zipfile


A new @ref{f06,,ZipInfo.from_file()} class method
allows making a @ref{2cb,,ZipInfo} instance from a filesystem file.
A new @ref{f07,,ZipInfo.is_dir()} method can be used
to check if the @ref{2cb,,ZipInfo} instance represents a directory.
(Contributed by Thomas Kluyver in bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}.)

The @ref{65d,,ZipFile.open()} method can now be used to
write data into a ZIP file, as well as for extracting data.
(Contributed by Thomas Kluyver in bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}.)

@node zlib<2>,,zipfile<4>,改良されたモジュール<8>
@anchor{whatsnew/3 6 zlib}@anchor{f08}
@subsubsection zlib


The @ref{84f,,compress()} and @ref{f09,,decompress()} functions now accept
keyword arguments.
(Contributed by Aviv Palivoda in bpo-26243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26243} and
Xiang Zhang in bpo-16764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16764} respectively.)

@node 最適化<9>,ビルドならびに C API の変更<2>,改良されたモジュール<8>,What's New In Python 3 6
@anchor{whatsnew/3 6 optimizations}@anchor{f0a}
@subsection 最適化



@itemize *

@item 
The Python interpreter now uses a 16-bit wordcode instead of bytecode which
made a number of opcode optimizations possible.
(Contributed by Demur Rumed with input and reviews from
Serhiy Storchaka and Victor Stinner in bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647} and bpo-28050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28050}.)

@item 
The @ref{dc6,,asyncio.Future} class now has an optimized C implementation.
(Contributed by Yury Selivanov and INADA Naoki in bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}.)

@item 
The @ref{1c7,,asyncio.Task} class now has an optimized
C implementation. (Contributed by Yury Selivanov in bpo-28544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28544}.)

@item 
Various implementation improvements in the @ref{10a,,typing} module
(such as caching of generic types) allow up to 30 times performance
improvements and reduced memory footprint.

@item 
The ASCII decoder is now up to 60 times as fast for error handlers
@code{surrogateescape}, @code{ignore} and @code{replace} (Contributed
by Victor Stinner in bpo-24870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24870}).

@item 
The ASCII and the Latin1 encoders are now up to 3 times as fast for the
error handler @code{surrogateescape}
(Contributed by Victor Stinner in bpo-25227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25227}).

@item 
The UTF-8 encoder is now up to 75 times as fast for error handlers
@code{ignore}, @code{replace}, @code{surrogateescape}, @code{surrogatepass} (Contributed
by Victor Stinner in bpo-25267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25267}).

@item 
The UTF-8 decoder is now up to 15 times as fast for error handlers
@code{ignore}, @code{replace} and @code{surrogateescape} (Contributed
by Victor Stinner in bpo-25301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25301}).

@item 
@code{bytes % args} is now up to 2 times faster. (Contributed by Victor Stinner
in bpo-25349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25349}).

@item 
@code{bytearray % args} is now between 2.5 and 5 times faster. (Contributed by
Victor Stinner in bpo-25399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25399}).

@item 
Optimize @ref{190,,bytes.fromhex()} and @ref{191,,bytearray.fromhex()}: they are now
between 2x and 3.5x faster. (Contributed by Victor Stinner in bpo-25401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25401}).

@item 
Optimize @code{bytes.replace(b'@w{'}, b'.')} and @code{bytearray.replace(b'@w{'}, b'.')}:
up to 80% faster. (Contributed by Josh Snider in bpo-26574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26574}).

@item 
Allocator functions of the @ref{e5f,,PyMem_Malloc()} domain
(@ref{e63,,PYMEM_DOMAIN_MEM}) now use the @ref{f0b,,pymalloc memory allocator} instead of @code{malloc()} function of the C library. The
pymalloc allocator is optimized for objects smaller or equal to 512 bytes
with a short lifetime, and use @code{malloc()} for larger memory blocks.
(Contributed by Victor Stinner in bpo-26249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26249}).

@item 
@ref{f0c,,pickle.load()} and @ref{f0d,,pickle.loads()} are now up to 10% faster when
deserializing many small objects (Contributed by Victor Stinner in
bpo-27056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27056}).

@item 
Passing @ref{f0e,,keyword arguments} to a function has an
overhead in comparison with passing @ref{f0f,,positional arguments}.  Now in extension functions implemented with using
Argument Clinic this overhead is significantly decreased.
(Contributed by Serhiy Storchaka in bpo-27574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27574}).

@item 
Optimized @ref{5a0,,glob()} and @ref{a08,,iglob()} functions in the
@ref{68,,glob} module; they are now about 3--6 times faster.
(Contributed by Serhiy Storchaka in bpo-25596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25596}).

@item 
Optimized globbing in @ref{a8,,pathlib} by using @ref{c54,,os.scandir()};
it is now about 1.5--4 times faster.
(Contributed by Serhiy Storchaka in bpo-26032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26032}).

@item 
@ref{12b,,xml.etree.ElementTree} parsing, iteration and deepcopy performance
has been significantly improved.
(Contributed by Serhiy Storchaka in bpo-25638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25638}, bpo-25873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25873},
and bpo-25869@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25869}.)

@item 
Creation of @ref{213,,fractions.Fraction} instances from floats and
decimals is now 2 to 3 times faster.
(Contributed by Serhiy Storchaka in bpo-25971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25971}.)
@end itemize

@node ビルドならびに C API の変更<2>,その他の改善,最適化<9>,What's New In Python 3 6
@anchor{whatsnew/3 6 build-and-c-api-changes}@anchor{f10}
@subsection ビルドならびに C API の変更



@itemize *

@item 
Python now requires some C99 support in the toolchain to build.
Most notably, Python now uses standard integer types and macros in
place of custom macros like @code{PY_LONG_LONG}.
For more information, see 
@geindex Python Enhancement Proposals; PEP 7
PEP 7@footnote{https://peps.python.org/pep-0007/} and bpo-17884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17884}.

@item 
Cross-compiling CPython with the Android NDK and the Android API level set to
21 (Android 5.0 Lollipop) or greater runs successfully. While Android is not
yet a supported platform, the Python test suite runs on the Android emulator
with only about 16 tests failures. See the Android meta-issue bpo-26865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26865}.

@item 
The @code{--enable-optimizations} configure flag has been added. Turning it on
will activate expensive optimizations like PGO.
(Original patch by Alecsandru Patrascu of Intel in bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}.)

@item 
The @ref{474,,GIL} must now be held when allocator
functions of @ref{e61,,PYMEM_DOMAIN_OBJ} (ex: @ref{e62,,PyObject_Malloc()}) and
@ref{e63,,PYMEM_DOMAIN_MEM} (ex: @ref{e5f,,PyMem_Malloc()}) domains are called.

@item 
New @ref{f11,,Py_FinalizeEx()} API which indicates if flushing buffered data
failed.
(Contributed by Martin Panter in bpo-5319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5319}.)

@item 
@ref{624,,PyArg_ParseTupleAndKeywords()} now supports @ref{c78,,positional-only parameters}.  Positional-only parameters are
defined by empty names.
(Contributed by Serhiy Storchaka in bpo-26282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26282}).

@item 
@code{PyTraceback_Print} method now abbreviates long sequences of repeated lines
as @code{"[Previous line repeated @{count@} more times]"}.
(Contributed by Emanuel Barry in bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}.)

@item 
The new @ref{f12,,PyErr_SetImportErrorSubclass()} function allows for
specifying a subclass of @ref{65b,,ImportError} to raise.
(Contributed by Eric Snow in bpo-15767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15767}.)

@item 
The new @ref{f13,,PyErr_ResourceWarning()} function can be used to generate
a @ref{54c,,ResourceWarning} providing the source of the resource allocation.
(Contributed by Victor Stinner in bpo-26567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26567}.)

@item 
The new @ref{f14,,PyOS_FSPath()} function returns the file system
representation of a @ref{5a1,,path-like object}.
(Contributed by Brett Cannon in bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}.)

@item 
The @ref{f15,,PyUnicode_FSConverter()} and @ref{797,,PyUnicode_FSDecoder()}
functions will now accept @ref{5a1,,path-like objects}.
@end itemize

@node その他の改善,非推奨<10>,ビルドならびに C API の変更<2>,What's New In Python 3 6
@anchor{whatsnew/3 6 other-improvements}@anchor{f16}
@subsection その他の改善



@itemize *

@item 
@ref{f17,,--version} (短縮系: @ref{49b,,-V}) が2回与えられた場合、Python は @ref{49c,,sys.version} で詳細な情報を出力します。

@example
$ ./python -VV
Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]
@end example
@end itemize

@node 非推奨<10>,削除<10>,その他の改善,What's New In Python 3 6
@anchor{whatsnew/3 6 deprecated}@anchor{f18}
@subsection 非推奨


@menu
* 新たなキーワード:: 
* 非推奨の Python 挙動:: 
* 非推奨の Python モジュール、関数、メソッド: 非推奨の Python モジュール、関数、メソッド<2>. 
* xml: xml<6>. 
* C API の非推奨の関数ならびに型: C API の非推奨の関数ならびに型<2>. 
* 非推奨のビルドオプション:: 

@end menu

@node 新たなキーワード,非推奨の Python 挙動,,非推奨<10>
@anchor{whatsnew/3 6 new-keywords}@anchor{f19}
@subsubsection 新たなキーワード


@code{async} および @code{await} を変数、クラス、関数、モジュール名として使用することは推奨されません。@code{async} と @code{await} は Python 3.5 で 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} により導入され、Python 3.7 で正式にキーワードとなります。Python 3.6 から @code{async} や @code{await} を変数名に使用すると @ref{1a3,,DeprecationWarning} が出ます。

@node 非推奨の Python 挙動,非推奨の Python モジュール、関数、メソッド<2>,新たなキーワード,非推奨<10>
@anchor{whatsnew/3 6 deprecated-python-behavior}@anchor{f1a}
@subsubsection 非推奨の Python 挙動


Raising the @ref{df5,,StopIteration} exception inside a generator will now
generate a @ref{1a3,,DeprecationWarning}, and will trigger a @ref{244,,RuntimeError}
in Python 3.7.  See @ref{f1b,,PEP 479; ジェネレータ内の StopIteration の処理の変更} for details.

The @ref{df6,,__aiter__()} method is now expected to return an asynchronous
iterator directly instead of returning an awaitable as previously.
Doing the former will trigger a @ref{1a3,,DeprecationWarning}.  Backward
compatibility will be removed in Python 3.7.
(Contributed by Yury Selivanov in bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}.)

A backslash-character pair that is not a valid escape sequence now generates
a @ref{1a3,,DeprecationWarning}.  Although this will eventually become a
@ref{18e,,SyntaxError}, that will not be for several Python releases.
(Contributed by Emanuel Barry in bpo-27364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27364}.)

When performing a relative import, falling back on @code{__name__} and
@code{__path__} from the calling module when @code{__spec__} or
@code{__package__} are not defined now raises an @ref{71e,,ImportWarning}.
(Contributed by Rose Ames in bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791}.)

@node 非推奨の Python モジュール、関数、メソッド<2>,xml<6>,非推奨の Python 挙動,非推奨<10>
@anchor{whatsnew/3 6 deprecated-python-modules-functions-and-methods}@anchor{f1c}
@subsubsection 非推奨の Python モジュール、関数、メソッド


@menu
* asynchat:: 
* asyncore:: 
* dbm: dbm<4>. 
* distutils: distutils<6>. 
* grp:: 
* importlib: importlib<7>. 
* os: os<10>. 
* re: re<7>. 
* ssl: ssl<9>. 
* tkinter: tkinter<8>. 
* venv: venv<6>. 

@end menu

@node asynchat,asyncore,,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 asynchat}@anchor{f1d}
@subsubsection asynchat


The @code{asynchat} has been deprecated in favor of @ref{b,,asyncio}.
(Contributed by Mariatta in bpo-25002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25002}.)

@node asyncore,dbm<4>,asynchat,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 asyncore}@anchor{f1e}
@subsubsection asyncore


The @code{asyncore} has been deprecated in favor of @ref{b,,asyncio}.
(Contributed by Mariatta in bpo-25002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25002}.)

@node dbm<4>,distutils<6>,asyncore,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 dbm}@anchor{f1f}
@subsubsection dbm


Unlike other @ref{35,,dbm} implementations, the @ref{36,,dbm.dumb} module
creates databases with the @code{'rw'} mode and allows modifying the database
opened with the @code{'r'} mode.  This behavior is now deprecated and will
be removed in 3.8.
(Contributed by Serhiy Storchaka in bpo-21708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21708}.)

@node distutils<6>,grp,dbm<4>,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 id2}@anchor{f20}
@subsubsection distutils


The undocumented @code{extra_path} argument to the
@code{distutils.Distribution} constructor is now considered deprecated
and will raise a warning if set.   Support for this parameter will be
removed in a future Python release.  See bpo-27919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27919} for details.

@node grp,importlib<7>,distutils<6>,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 grp}@anchor{f21}
@subsubsection grp


@ref{f22,,getgrgid()} の非整数の引数のサポートは非推奨になりました。 (Contributed by Serhiy Storchaka in bpo-26129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26129}.)

@node importlib<7>,os<10>,grp,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 id3}@anchor{f23}
@subsubsection importlib


The @ref{f24,,importlib.machinery.SourceFileLoader.load_module()} and
@ref{f25,,importlib.machinery.SourcelessFileLoader.load_module()} methods
are now deprecated. They were the only remaining implementations of
@ref{a69,,importlib.abc.Loader.load_module()} in @ref{7b,,importlib} that had not
been deprecated in previous versions of Python in favour of
@ref{a6a,,importlib.abc.Loader.exec_module()}.

The @ref{f26,,importlib.machinery.WindowsRegistryFinder} class is now
deprecated. As of 3.6.0, it is still added to @ref{f27,,sys.meta_path} by
default (on Windows), but this may change in future releases.

@node os<10>,re<7>,importlib<7>,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 id4}@anchor{f28}
@subsubsection os


Undocumented support of general @ref{193,,bytes-like objects}
as paths in @ref{a5,,os} functions, @ref{4b1,,compile()} and similar functions is
now deprecated.
(Contributed by Serhiy Storchaka in bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791} and bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}.)

@node re<7>,ssl<9>,os<10>,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 id5}@anchor{f29}
@subsubsection re


Support for inline flags @code{(?letters)} in the middle of the regular
expression has been deprecated and will be removed in a future Python
version.  Flags at the start of a regular expression are still allowed.
(Contributed by Serhiy Storchaka in bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}.)

@node ssl<9>,tkinter<8>,re<7>,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 id6}@anchor{f2a}
@subsubsection ssl


OpenSSLの0.9.8, 1.0.0 ,1.0.1 は非推奨となっており、長い間サポートされていません。将来的に @ref{d5,,ssl} モジュールは、OpenSSLの1.0.2 もしくは1.1.0が必須になります。

SSL-related arguments like @code{certfile}, @code{keyfile} and @code{check_hostname}
in @ref{62,,ftplib}, @ref{73,,http.client}, @ref{78,,imaplib}, @ref{b1,,poplib},
and @ref{cf,,smtplib} have been deprecated in favor of @code{context}.
(Contributed by Christian Heimes in bpo-28022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28022}.)

A couple of protocols and functions of the @ref{d5,,ssl} module are now
deprecated. Some features will no longer be available in future versions
of OpenSSL. Other features are deprecated in favor of a different API.
(Contributed by Christian Heimes in bpo-28022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28022} and bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}.)

@node tkinter<8>,venv<6>,ssl<9>,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 id7}@anchor{f2b}
@subsubsection tkinter


The @code{tkinter.tix} module is now deprecated.  @ref{f6,,tkinter} users
should use @ref{ff,,tkinter.ttk} instead.

@node venv<6>,,tkinter<8>,非推奨の Python モジュール、関数、メソッド<2>
@anchor{whatsnew/3 6 id8}@anchor{f2c}@anchor{whatsnew/3 6 whatsnew36-venv}@anchor{f2d}
@subsubsection venv


The @code{pyvenv} script has been deprecated in favour of @code{python3 -m venv}.
This prevents confusion as to what Python interpreter @code{pyvenv} is
connected to and thus what Python interpreter will be used by the virtual
environment.  (Contributed by Brett Cannon in bpo-25154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25154}.)

@node xml<6>,C API の非推奨の関数ならびに型<2>,非推奨の Python モジュール、関数、メソッド<2>,非推奨<10>
@anchor{whatsnew/3 6 xml}@anchor{f2e}
@subsubsection xml



@itemize *

@item 
As mitigation against DTD and external entity retrieval, the
@ref{128,,xml.dom.minidom} and @ref{12f,,xml.sax} modules no longer process
external entities by default.
(Contributed by Christian Heimes in gh-61441@footnote{https://github.com/python/cpython/issues/61441}.)
@end itemize

@node C API の非推奨の関数ならびに型<2>,非推奨のビルドオプション,xml<6>,非推奨<10>
@anchor{whatsnew/3 6 deprecated-functions-and-types-of-the-c-api}@anchor{f2f}
@subsubsection C API の非推奨の関数ならびに型


Undocumented functions @code{PyUnicode_AsEncodedObject()},
@code{PyUnicode_AsDecodedObject()}, @code{PyUnicode_AsEncodedUnicode()}
and @code{PyUnicode_AsDecodedUnicode()} are deprecated now.
Use the @ref{f30,,generic codec based API} instead.

@node 非推奨のビルドオプション,,C API の非推奨の関数ならびに型<2>,非推奨<10>
@anchor{whatsnew/3 6 deprecated-build-options}@anchor{f31}
@subsubsection 非推奨のビルドオプション


The @code{--with-system-ffi} configure flag is now on by default on non-macOS
UNIX platforms.  It may be disabled by using @code{--without-system-ffi}, but
using the flag is deprecated and will not be accepted in Python 3.7.
macOS is unaffected by this change.  Note that many OS distributors already
use the @code{--with-system-ffi} flag when building their system Python.

@node 削除<10>,Python 3 6 への移植,非推奨<10>,What's New In Python 3 6
@anchor{whatsnew/3 6 removed}@anchor{f32}
@subsection 削除


@menu
* API と機能の削除: API と機能の削除<3>. 

@end menu

@node API と機能の削除<3>,,,削除<10>
@anchor{whatsnew/3 6 api-and-feature-removals}@anchor{f33}
@subsubsection API と機能の削除



@itemize *

@item 
Unknown escapes consisting of @code{'\'} and an ASCII letter in
regular expressions will now cause an error.  In replacement templates for
@ref{5a3,,re.sub()} they are still allowed, but deprecated.
The @ref{d63,,re.LOCALE} flag can now only be used with binary patterns.

@item 
@code{inspect.getmoduleinfo()} was removed (was deprecated since CPython 3.3).
@ref{f34,,inspect.getmodulename()} should be used for obtaining the module
name for a given path.
(Contributed by Yury Selivanov in bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}.)

@item 
@code{traceback.Ignore} class and @code{traceback.usage}, @code{traceback.modname},
@code{traceback.fullmodname}, @code{traceback.find_lines_from_code},
@code{traceback.find_lines}, @code{traceback.find_strings},
@code{traceback.find_executable_lines} methods were removed from the
@ref{104,,traceback} module. They were undocumented methods deprecated since
Python 3.2 and equivalent functionality is available from private methods.

@item 
The @code{tk_menuBar()} and @code{tk_bindForTraversal()} dummy methods in
@ref{f6,,tkinter} widget classes were removed (corresponding Tk commands
were obsolete since Tk 4.0).

@item 
The @ref{65d,,open()} method of the @ref{8d3,,zipfile.ZipFile}
class no longer supports the @code{'U'} mode (was deprecated since Python 3.4).
Use @ref{9be,,io.TextIOWrapper} for reading compressed text files in
@ref{f35,,universal newlines} mode.

@item 
The undocumented @code{IN}, @code{CDROM}, @code{DLFCN}, @code{TYPES}, @code{CDIO}, and
@code{STROPTS} modules have been removed.  They had been available in the
platform specific @code{Lib/plat-*/} directories, but were chronically out of
date, inconsistently available across platforms, and unmaintained.  The
script that created these modules is still available in the source
distribution at Tools/scripts/h2py.py@footnote{https://github.com/python/cpython/blob/v3.6.15/Tools/scripts/h2py.py}.

@item 
非推奨の @code{asynchat.fifo} クラスは削除されました。
@end itemize

@node Python 3 6 への移植,Notable changes in Python 3 6 2,削除<10>,What's New In Python 3 6
@anchor{whatsnew/3 6 porting-to-python-3-6}@anchor{f36}
@subsection Python 3.6 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* 'python' コマンドの挙動の変更:: 
* Python API の変更: Python API の変更<9>. 
* C API の変更: C API の変更<13>. 
* CPython バイトコードの変更: CPython バイトコードの変更<8>. 

@end menu

@node 'python' コマンドの挙動の変更,Python API の変更<9>,,Python 3 6 への移植
@anchor{whatsnew/3 6 changes-in-python-command-behavior}@anchor{f37}
@subsubsection 'python' コマンドの挙動の変更



@itemize *

@item 
The output of a special Python build with defined @code{COUNT_ALLOCS},
@code{SHOW_ALLOC_COUNT} or @code{SHOW_TRACK_COUNT} macros is now off by
default.  It can be re-enabled using the @code{-X showalloccount} option.
It now outputs to @code{stderr} instead of @code{stdout}.
(Contributed by Serhiy Storchaka in bpo-23034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23034}.)
@end itemize

@node Python API の変更<9>,C API の変更<13>,'python' コマンドの挙動の変更,Python 3 6 への移植
@anchor{whatsnew/3 6 changes-in-the-python-api}@anchor{f38}
@subsubsection Python API の変更



@itemize *

@item 
@ref{316,,open()} will no longer allow combining the @code{'U'} mode flag
with @code{'+'}.
(Contributed by Jeff Balogh and John O'Connor in bpo-2091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2091}.)

@item 
@ref{d4,,sqlite3} no longer implicitly commits an open transaction before DDL
statements.

@item 
On Linux, @ref{746,,os.urandom()} now blocks until the system urandom entropy pool
is initialized to increase the security.

@item 
When @ref{a6a,,importlib.abc.Loader.exec_module()} is defined,
@ref{eac,,importlib.abc.Loader.create_module()} must also be defined.

@item 
@ref{f39,,PyErr_SetImportError()} now sets @ref{198,,TypeError} when its `msg'
argument is not set. Previously only @code{NULL} was returned.

@item 
The format of the @ref{330,,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 @ref{9af,,frame.f_lineno},
@code{PyFrame_GetLineNumber()} or @code{PyCode_Addr2Line()} are not affected.
Functions directly decoding @code{co_lnotab} should be updated to use a signed
8-bit integer type for the line number delta, but this is only required to
support applications using a negative line number delta. See
@code{Objects/lnotab_notes.txt} for the @code{co_lnotab} format and how to decode
it, and see the 
@geindex Python Enhancement Proposals; PEP 511
PEP 511@footnote{https://peps.python.org/pep-0511/} for the rationale.

@item 
The functions in the @ref{21,,compileall} module now return booleans instead
of @code{1} or @code{0} to represent success or failure, respectively. Thanks to
booleans being a subclass of integers, this should only be an issue if you
were doing identity checks for @code{1} or @code{0}. See bpo-25768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25768}.

@item 
Reading the @code{port} attribute of
@ref{f3a,,urllib.parse.urlsplit()} and @ref{362,,urlparse()} results
now raises @ref{2ec,,ValueError} for out-of-range values, rather than
returning @ref{885,,None}.  See bpo-20059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20059}.

@item 
The @code{imp} module now raises a @ref{1a3,,DeprecationWarning} instead of
@ref{ac5,,PendingDeprecationWarning}.

@item 
The following modules have had missing APIs added to their
@ref{f3b,,__all__} attributes to match the documented APIs:
@ref{15,,calendar}, @code{cgi}, @ref{2d,,csv},
@ref{12b,,ElementTree}, @ref{5a,,enum},
@ref{5f,,fileinput}, @ref{62,,ftplib}, @ref{8b,,logging}, @ref{8f,,mailbox},
@ref{93,,mimetypes}, @ref{a4,,optparse}, @ref{b0,,plistlib}, @code{smtpd},
@ref{dc,,subprocess}, @ref{e4,,tarfile}, @ref{f3,,threading} and
@ref{119,,wave}.  This means they will export new symbols when @code{import *}
is used.
(Contributed by Joel Taddei and Jacek Kołodziej in bpo-23883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23883}.)

@item 
When performing a relative import, if @code{__package__} does not compare equal
to @code{__spec__.parent} then @ref{71e,,ImportWarning} is raised.
(Contributed by Brett Cannon in bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791}.)

@item 
When a relative import is performed and no parent package is known, then
@ref{65b,,ImportError} will be raised. Previously, @ref{795,,SystemError} could be
raised. (Contributed by Brett Cannon in bpo-18018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18018}.)

@item 
Servers based on the @ref{d2,,socketserver} module, including those
defined in @ref{76,,http.server}, @ref{135,,xmlrpc.server} and
@ref{121,,wsgiref.simple_server}, now only catch exceptions derived
from @ref{bcd,,Exception}. Therefore if a request handler raises
an exception like @ref{f3c,,SystemExit} or @ref{bc5,,KeyboardInterrupt},
@ref{f3d,,handle_error()} is no longer called, and
the exception will stop a single-threaded server. (Contributed by
Martin Panter in bpo-23430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23430}.)

@item 
@code{spwd.getspnam()} now raises a @ref{f3e,,PermissionError} instead of
@ref{5e7,,KeyError} if the user doesn't have privileges.

@item 
The @ref{f3f,,socket.socket.close()} method now raises an exception if
an error (e.g. @code{EBADF}) was reported by the underlying system call.
(Contributed by Martin Panter in bpo-26685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26685}.)

@item 
The `decode_data' argument for the @code{smtpd.SMTPChannel} and
@code{smtpd.SMTPServer} constructors is now @code{False} by default.
This means that the argument passed to
@code{process_message()} is now a bytes object by
default, and @code{process_message()} will be passed keyword arguments.
Code that has already been updated in accordance with the deprecation
warning generated by 3.5 will not be affected.

@item 
All optional arguments of the @ref{f40,,dump()}, @ref{f41,,dumps()},
@ref{eb2,,load()} and @ref{b4e,,loads()} functions and
@ref{f42,,JSONEncoder} and @ref{f43,,JSONDecoder} class
constructors in the @ref{86,,json} module are now @ref{5a5,,keyword-only}.
(Contributed by Serhiy Storchaka in bpo-18726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18726}.)

@item 
@code{type.__new__} をオーバーライドしていない @ref{f44,,type} のサブクラスは、オブジェクトの型を得るのに１引数形式を利用することができません。

@item 
As part of 
@geindex Python Enhancement Proposals; PEP 487
PEP 487@footnote{https://peps.python.org/pep-0487/}, the handling of keyword arguments passed to
@ref{f44,,type} (other than the metaclass hint, @code{metaclass}) is now
consistently delegated to @ref{843,,object.__init_subclass__()}. This means that
@ref{7a0,,type.__new__} and @ref{8bf,,type.__init__} both now accept arbitrary keyword arguments,
but @ref{843,,object.__init_subclass__()} (which is called from
@ref{7a0,,type.__new__}) will reject them by default.
Custom metaclasses accepting additional keyword arguments will need to adjust
their calls to @ref{7a0,,type.__new__}
(whether direct or via @ref{1a6,,super}) accordingly.

@item 
In @code{distutils.command.sdist.sdist}, the @code{default_format}
attribute has been removed and is no longer honored. Instead, the
gzipped tarfile format is the default on all platforms and no
platform-specific selection is made.
In environments where distributions are
built on Windows and zip distributions are required, configure
the project with a @code{setup.cfg} file containing the following:

@example
[sdist]
formats=zip
@end example

この挙動は Setuptools 26.0.0 により以前の Python バージョンにバックポートされました。

@item 
In the @ref{111,,urllib.request} module and the
@ref{ea7,,http.client.HTTPConnection.request()} method, if no Content-Length
header field has been specified and the request body is a file object,
it is now sent with HTTP 1.1 chunked encoding. If a file object has to
be sent to a HTTP 1.0 server, the Content-Length value now has to be
specified by the caller.
(Contributed by Demian Brecht and Rolf Krahl with tweaks from
Martin Panter in bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}.)

@item 
The @ref{bd8,,DictReader} now returns rows of type
@ref{7f3,,OrderedDict}.
(Contributed by Steve Holden in bpo-27842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27842}.)

@item 
The @code{crypt.METHOD_CRYPT} will no longer be added to @code{crypt.methods}
if unsupported by the platform.
(Contributed by Victor Stinner in bpo-25287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25287}.)

@item 
The `verbose' and `rename' arguments for
@ref{4e0,,namedtuple()} are now keyword-only.
(Contributed by Raymond Hettinger in bpo-25628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25628}.)

@item 
On Linux, @ref{f45,,ctypes.util.find_library()} now looks in
@code{LD_LIBRARY_PATH} for shared libraries.
(Contributed by Vinay Sajip in bpo-9998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9998}.)

@item 
The @ref{aff,,imaplib.IMAP4} class now handles flags containing the
@code{']'} character in messages sent from the server to improve
real-world compatibility.
(Contributed by Lita Cho in bpo-21815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21815}.)

@item 
The @ref{f46,,mmap.mmap.write()} function now returns the number
of bytes written like other write methods.
(Contributed by Jakub Stasiak in bpo-26335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26335}.)

@item 
The @ref{f47,,pkgutil.iter_modules()} and @ref{df9,,pkgutil.walk_packages()}
functions now return @ref{f48,,ModuleInfo} named tuples.
(Contributed by Ramchandra Apte in bpo-17211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17211}.)

@item 
@ref{5a3,,re.sub()} now raises an error for invalid numerical group
references in replacement templates even if the pattern is not
found in the string.  The error message for invalid group references
now includes the group index and the position of the reference.
(Contributed by SilentGhost, Serhiy Storchaka in bpo-25953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25953}.)

@item 
@ref{8d3,,zipfile.ZipFile} will now raise @ref{36b,,NotImplementedError} for
unrecognized compression values.  Previously a plain @ref{244,,RuntimeError}
was raised.  Additionally, calling @ref{8d3,,ZipFile} methods
on a closed ZipFile or calling the @ref{f49,,write()} method
on a ZipFile created with mode @code{'r'} will raise a @ref{2ec,,ValueError}.
Previously, a @ref{244,,RuntimeError} was raised in those scenarios.

@item 
when custom metaclasses are combined with zero-argument @ref{1a6,,super()} or
direct references from methods to the implicit @code{__class__} closure
variable, the implicit @code{__classcell__} namespace entry must now be passed
up to @code{type.__new__} for initialisation. Failing to do so will result in
a @ref{1a3,,DeprecationWarning} in Python 3.6 and a @ref{244,,RuntimeError} in
Python 3.8.

@item 
With the introduction of @ref{d3d,,ModuleNotFoundError}, import system consumers
may start expecting import system replacements to raise that more specific
exception when appropriate, rather than the less-specific @ref{65b,,ImportError}.
To provide future compatibility with such consumers, implementers of
alternative import systems that completely replace @ref{ad1,,__import__()} will
need to update their implementations to raise the new subclass when a module
can't be found at all. Implementers of compliant plugins to the default
import system shouldn't need to make any changes, as the default import
system will raise the new subclass when appropriate.
@end itemize

@node C API の変更<13>,CPython バイトコードの変更<8>,Python API の変更<9>,Python 3 6 への移植
@anchor{whatsnew/3 6 changes-in-the-c-api}@anchor{f4a}
@subsubsection C API の変更



@itemize *

@item 
The @ref{e5f,,PyMem_Malloc()} allocator family now uses the @ref{f0b,,pymalloc allocator} rather than the system @code{malloc()}. Applications calling
@ref{e5f,,PyMem_Malloc()} without holding the GIL can now crash. Set the
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable to @code{debug} to validate the
usage of memory allocators in your application. See bpo-26249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26249}.

@item 
@ref{f4b,,Py_Exit()} (and the main interpreter) now override the exit status
with 120 if flushing buffered data failed.  See bpo-5319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5319}.
@end itemize

@node CPython バイトコードの変更<8>,,C API の変更<13>,Python 3 6 への移植
@anchor{whatsnew/3 6 cpython-bytecode-changes}@anchor{f4c}
@subsubsection CPython バイトコードの変更


There have been several major changes to the @ref{4aa,,bytecode} in Python 3.6.


@itemize *

@item 
The Python interpreter now uses a 16-bit wordcode instead of bytecode.
(Contributed by Demur Rumed with input and reviews from
Serhiy Storchaka and Victor Stinner in bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647} and bpo-28050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28050}.)

@item 
The new @code{FORMAT_VALUE} and @ref{f4d,,BUILD_STRING} opcodes as part
of the  @ref{e29,,formatted string literal} implementation.
(Contributed by Eric Smith in bpo-25483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25483} and
Serhiy Storchaka in bpo-27078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27078}.)

@item 
The new @code{BUILD_CONST_KEY_MAP} opcode to optimize the creation
of dictionaries with constant keys.
(Contributed by Serhiy Storchaka in bpo-27140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27140}.)

@item 
The function call opcodes have been heavily reworked for better performance
and simpler implementation.
The @ref{f4e,,MAKE_FUNCTION}, @code{CALL_FUNCTION},
@code{CALL_FUNCTION_KW} and @code{BUILD_MAP_UNPACK_WITH_CALL} opcodes
have been modified, the new @ref{f4f,,CALL_FUNCTION_EX} and
@code{BUILD_TUPLE_UNPACK_WITH_CALL} have been added, and
@code{CALL_FUNCTION_VAR}, @code{CALL_FUNCTION_VAR_KW} and @code{MAKE_CLOSURE} opcodes
have been removed.
(Contributed by Demur Rumed in bpo-27095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27095}, and Serhiy Storchaka in
bpo-27213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27213}, bpo-28257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28257}.)

@item 
The new @ref{f50,,SETUP_ANNOTATIONS} and @code{STORE_ANNOTATION} opcodes
have been added to support the new @ref{f51,,variable annotation} syntax.
(Contributed by Ivan Levkivskyi in bpo-27985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27985}.)
@end itemize

@node Notable changes in Python 3 6 2,Notable changes in Python 3 6 4,Python 3 6 への移植,What's New In Python 3 6
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-2}@anchor{f52}
@subsection Notable changes in Python 3.6.2


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

@end menu

@node New make regen-all build target,Removal of make touch build target,,Notable changes in Python 3 6 2
@anchor{whatsnew/3 6 new-make-regen-all-build-target}@anchor{f53}
@subsubsection New @code{make regen-all} build target


To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.

Instead, a new @code{make regen-all} command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in@footnote{https://github.com/python/cpython/tree/3.14/Makefile.pre.in} for details.

(Victor Stinner の貢献による bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404})


Added in version 3.6.2.


@node Removal of make touch build target,,New make regen-all build target,Notable changes in Python 3 6 2
@anchor{whatsnew/3 6 removal-of-make-touch-build-target}@anchor{f54}
@subsubsection Removal of @code{make touch} build target


The @code{make touch} build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.

It has been replaced by the new @code{make regen-all} target.

(Victor Stinner の貢献による bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404})


バージョン 3.6.2 で変更.


@node Notable changes in Python 3 6 4,Notable changes in Python 3 6 5,Notable changes in Python 3 6 2,What's New In Python 3 6
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-4}@anchor{f55}
@subsection Notable changes in Python 3.6.4


The @code{PyExc_RecursionErrorInst} singleton that was part of the public API
has been removed as its members being never cleared may cause a segfault
during finalization of the interpreter.
(Contributed by Xavier de Gaye in bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898} and bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697}.)

@node Notable changes in Python 3 6 5,Notable changes in Python 3 6 7,Notable changes in Python 3 6 4,What's New In Python 3 6
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-5}@anchor{f56}
@subsection Notable changes in Python 3.6.5


The @ref{df8,,locale.localeconv()} function now sets temporarily the @code{LC_CTYPE}
locale to the @code{LC_NUMERIC} locale in some cases.
(Contributed by Victor Stinner in bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900}.)

@node Notable changes in Python 3 6 7,Notable changes in Python 3 6 10,Notable changes in Python 3 6 5,What's New In Python 3 6
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-7}@anchor{f57}
@subsection Notable changes in Python 3.6.7


@ref{128,,xml.dom.minidom} and @ref{12f,,xml.sax} modules no longer process
external entities by default. See also gh-61441@footnote{https://github.com/python/cpython/issues/61441}.

In 3.6.7 the @ref{101,,tokenize} module now implicitly emits a @code{NEWLINE} token
when provided with input that does not have a trailing new line.  This behavior
now matches what the C tokenizer does internally.
(Contributed by Ammar Askar in bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899}.)

@node Notable changes in Python 3 6 10,Notable changes in Python 3 6 13,Notable changes in Python 3 6 7,What's New In Python 3 6
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-10}@anchor{f58}
@subsection Notable changes in Python 3.6.10


セキュリティ上の重大な懸念により、@ref{93c,,asyncio.loop.create_datagram_endpoint()} での `reuse_address' 引数は無効になりました。これはソケットオプション @cite{SO_REUSEADDR`} のUDP における挙動が原因です。詳しくは、@code{loop.create_datagram_endpoint()} のドキュメントを参照してください。(Kyle Stanley, Antoine Pitrou, Yury Selivanov による貢献 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228})

@node Notable changes in Python 3 6 13,Notable changes in Python 3 6 14,Notable changes in Python 3 6 10,What's New In Python 3 6
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-13}@anchor{f59}
@subsection Notable changes in Python 3.6.13


Earlier Python versions allowed using both @code{;} and @code{&} as
query parameter separators in @ref{31f,,urllib.parse.parse_qs()} and
@ref{31e,,urllib.parse.parse_qsl()}.  Due to security concerns, and to conform with
newer W3C recommendations, this has been changed to allow only a single
separator key, with @code{&} as the default.  This change also affects
@code{cgi.parse()} and @code{cgi.parse_multipart()} as they use the affected
functions internally. For more details, please see their respective
documentation.
(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}.)

@node Notable changes in Python 3 6 14,,Notable changes in Python 3 6 13,What's New In Python 3 6
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-14}@anchor{f5a}
@subsection Notable changes in Python 3.6.14


A security fix alters the @ref{af6,,ftplib.FTP} behavior to not trust the
IPv4 address sent from the remote server when setting up a passive data
channel.  We reuse the ftp server IP address instead.  For unusual code
requiring the old behavior, set a @code{trust_server_pasv_ipv4_address}
attribute on your FTP instance to @code{True}.  (See gh-87451@footnote{https://github.com/python/cpython/issues/87451})

The presence of newline or tab characters in parts of a URL allows for some
forms of attacks. Following the WHATWG specification that updates RFC 3986,
ASCII newline @code{\n}, @code{\r} and tab @code{\t} characters are stripped from the
URL by the parser @ref{110,,urllib.parse()} preventing such attacks. The removal
characters are controlled by a new module level variable
@code{urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE}. (See gh-88048@footnote{https://github.com/python/cpython/issues/88048})

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 5,What's New In Python 3 4,What's New In Python 3 6,What's New in Python
@anchor{whatsnew/3 5 doc}@anchor{f5b}@anchor{whatsnew/3 5 translation-repo}@anchor{f5c}@anchor{whatsnew/3 5 what-s-new-in-python-3-5}@anchor{f5d}
@section What's New In Python 3.5


@*エディタ: 
Elvis Pranskevichus <@email{elvis@@magic.io}>, Yury Selivanov <@email{yury@@magic.io}>


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

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@footnote{https://docs.python.org/3.5/whatsnew/changelog.html} for a full
list of changes.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 478
PEP 478@footnote{https://peps.python.org/pep-0478/} - Python 3.5 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト<10>. リリースハイライト
* 新しい機能: 新しい機能<15>. 
* その他の言語変更: その他の言語変更<9>. 
* 新たなモジュール: 新たなモジュール<9>. 
* 改良されたモジュール: 改良されたモジュール<9>. 
* その他のモジュールレベルの変更:: 
* 最適化: 最適化<10>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<3>. 
* 非推奨: 非推奨<11>. 
* 削除: 削除<11>. 
* Python 3.5 への移植: Python 3 5 への移植. 
* Notable changes in Python 3.5.4: Notable changes in Python 3 5 4. 

@end menu

@node 概要 -- リリースハイライト<10>,新しい機能<15>,,What's New In Python 3 5
@anchor{whatsnew/3 5 summary-release-highlights}@anchor{f5e}
@subsection 概要 -- リリースハイライト


新たな文法機能:


@itemize *

@item 
@ref{f5f,,PEP 492}、コルーチン、async 構文と await 構文。

@item 
@ref{f60,,PEP 465}、新たな行列乗算演算子 @code{a @@ b}。

@item 
@ref{f61,,PEP 448}、追加可能なアンパックへの一般化。
@end itemize

新たなライブラリモジュール:


@itemize *

@item 
@ref{10a,,typing}: @ref{f62,,PEP 484 -- 型ヒント}。

@item 
@ref{136,,zipapp}: @ref{f63,,PEP 441 Python ZIP アプリケーションのサポートの改善}。
@end itemize

新たな組み込み機能:


@itemize *

@item 
@code{bytes % args}, @code{bytearray % args}: @ref{f64,,PEP 461} -- bytes と bytearray に @code{%} 書式化を追加。

@item 
新たな @ref{f65,,bytes.hex()}, @ref{f66,,bytearray.hex()} @ref{f67,,memoryview.hex()} メソッド。 (Contributed by Arnon Yaari in bpo-9951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9951}.)

@item 
@ref{165,,memoryview} クラスが、(複数次元の場合を含んだ) タプルの添字をサポートするようになりました。
(bpo-23632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23632} におけるAntoine Pitrouによる貢献です。)

@item 
ジェネレータに @code{gi_yieldfrom} 属性が新しく追加され、これは @code{yield from} 式で反復処理されるオブジェクトを返します。
(Contributed by Benno Leslie and Yury Selivanov in bpo-24450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24450}.)

@item 
新たな例外 @ref{f68,,RecursionError} が最長再帰深度に到達した際に送出されるようになりました。   (Contributed by Georg Brandl in bpo-19235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19235}.)
@end itemize

CPython の実装の改善:


@itemize *

@item 
@code{LC_TYPE} ロケールが POSIX ロケール (@code{C} ロケール) のとき、 @ref{75f,,sys.stdin} および @ref{ccd,,sys.stdout} は @code{strict} エラーハンドラではなく @code{surrogateescape} を使うようになりました。 (Contributed by Victor Stinner in bpo-19977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19977}.)

@item 
@code{.pyo} ファイルは使われなくなり、@code{.pyc} ファイル名に最適化レベルが明示される、より柔軟な仕組みに置き換えられました。(@ref{f69,,PEP 488 の概要} を参照してください。)

@item 
組み込みおよび拡張モジュールが多段階で初期化されるようになりました。これは Python モジュールのロード方法と同じです。 (@ref{f6a,,PEP 489 の概要} を参照してください。)
@end itemize

標準ライブラリーの顕著な改善


@itemize *

@item 
@ref{7f3,,collections.OrderedDict} が @ref{f6b,,C で実装されました}。
これにより 4 倍から 100 倍高速になりました。

@item 
@ref{d5,,ssl} モジュールに @ref{f6c,,メモリ BIO サポート} が追加されました。これにより SSL プロトコルの処理と ネットワーク IO が分離されました。

@item 
新たな関数 @ref{c54,,os.scandir()} はディレクトリー走査の @ref{f6d,,改良され非常に速い方法} を提供します。

@item 
@ref{be2,,functools.lru_cache()} の大部分が @ref{f6e,,C で再実装} され、性能が大幅に向上しました。

@item 
新たな関数 @ref{d7f,,subprocess.run()} は @ref{f6f,,サブプロセスを実行する合理的な方法} を提供します。

@item 
@ref{104,,traceback} モジュールは性能と開発者の利便性が向上し、大いに @ref{f70,,強化され} ました。
@end itemize

セキュリティの改善:


@itemize *

@item 
SSLv3 が標準ライブラリ全体を通じて無効化されました。ただし @ref{357,,ssl.SSLContext} を手動でインスタンス化することによってなら今でも有効には出来ます。  (詳細に関しては bpo-22638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22638} を参照してください。この変更は CPython 3.4 と 2.7 にもバックポートされました。)

@item 
潜在的なインジェクション攻撃からの防御のために、HTTP クッキーの解析がより厳密に行われるようになりました。 (Contributed by Antoine Pitrou in bpo-22796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22796}.)
@end itemize

Windows の改善:


@itemize *

@item 
Windows のインストーラが新しくなり古い MSI を置き換えました。さらに詳しい情報は @ref{c9e,,Windows で Python を使う} をご覧ください。

@item 
Windows のビルドに Microsoft Visual C++ 14.0 を使うようになっています。拡張モジュールも同じものを使うべきです。
@end itemize

以降は、たくさんのほかの小さな改善、CPython での最適化、非推奨リスト、潜在的な移植性問題を含む、ユーザ向けの変更の包括的なリストになっています。

@node 新しい機能<15>,その他の言語変更<9>,概要 -- リリースハイライト<10>,What's New In Python 3 5
@anchor{whatsnew/3 5 new-features}@anchor{f71}
@subsection 新しい機能


@menu
* PEP 492 - コルーチン、 async と await 構文:: 
* PEP 465 - 行列の乗算専用の中置演算子:: 
* PEP 448 - 追加可能なアンパックへの一般化:: 
* PEP 461 - bytes および bytearray のパーセント書式化サポート:: 
* PEP 484 - 型ヒント:: 
* PEP 471 - os.scandir() 関数: PEP 471 - os scandir 関数 -- より良く、速いディレクトリイテレータ. より良く、速いディレクトリイテレータ
* PEP 475; EINTR で失敗したシステムコールの再試行: PEP 475 EINTR で失敗したシステムコールの再試行. 
* PEP 479; ジェネレータ内の StopIteration の処理の変更: PEP 479 ジェネレータ内の StopIteration の処理の変更. 
* PEP 485; 近似的に等しいことを調べる関数: PEP 485 近似的に等しいことを調べる関数. 
* PEP 486; Python ランチャーが仮想環境を認識する: PEP 486 Python ランチャーが仮想環境を認識する. 
* PEP 488; PYO ファイルの廃止: PEP 488 PYO ファイルの廃止. 
* PEP 489; 拡張モジュールの多段階初期化: PEP 489 拡張モジュールの多段階初期化. 

@end menu

@node PEP 492 - コルーチン、 async と await 構文,PEP 465 - 行列の乗算専用の中置演算子,,新しい機能<15>
@anchor{whatsnew/3 5 pep-492-coroutines-with-async-and-await-syntax}@anchor{f72}@anchor{whatsnew/3 5 whatsnew-pep-492}@anchor{f5f}
@subsubsection PEP 492 - コルーチン、 async と await 構文


@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} で @ref{4c9,,待機可能オブジェクト}、@ref{f73,,コルーチン関数}、@ref{f74,,非同期イテレーション}、@ref{7f0,,非同期コンテキストマネージャ} が追加され、Python における非同期プログラミングを大幅に向上しました。

コルーチン関数は新たな構文 @ref{7ed,,async def} を用いて定義されます:

@example
>>> async def coro():
...     return 'spam'
@end example

Inside a coroutine function, the new @ref{18d,,await} expression can be used
to suspend coroutine execution until the result is available.  Any object
can be `awaited', as long as it implements the @ref{4c9,,awaitable} protocol by
defining the @ref{f75,,__await__()} method.

PEP 492 により @ref{ca1,,async for} 文も追加されました。非同期イテラブルを反復するのに便利です。

新たな構文を用いた初歩的な HTTP クライアントの例です:

@example
import asyncio

async def http_get(domain):
    reader, writer = await asyncio.open_connection(domain, 80)

    writer.write(b'\r\n'.join([
        b'GET / HTTP/1.1',
        b'Host: %b' % domain.encode('latin-1'),
        b'Connection: close',
        b'@w{'}, b'@w{'}
    ]))

    async for line in reader:
        print('>>>', line)

    writer.close()

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(http_get('example.com'))
finally:
    loop.close()
@end example

非同期イテレーションと同様に、非同期なコンテキストマネージャの新たな構文があります。以下のスクリプト:

@example
import asyncio

async def coro(name, lock):
    print('coro @{@}: waiting for lock'.format(name))
    async with lock:
        print('coro @{@}: holding the lock'.format(name))
        await asyncio.sleep(1)
        print('coro @{@}: releasing the lock'.format(name))

loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
    loop.run_until_complete(coros)
finally:
    loop.close()
@end example

の出力は:

@example
coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock
@end example

@ref{ca1,,async for} と @ref{185,,async with} は両方とも、 @ref{7ed,,async def} で宣言されたコルーチン関数内でのみ使えることに注意してください。

コルーチン関数は @ref{f76,,asyncio loop} のような適したイベントループ内で実行させるためのものです。

@cartouche
@quotation 注釈 

バージョン 3.5.2 で変更: CPython 3.5.2 以降では、 @code{__aiter__} は @ref{4c7,,非同期イテレータ} を直接返せます。
@ref{4c9,,awaitable} オブジェクトを返すと @ref{ac5,,PendingDeprecationWarning} が送出されます。

より詳細なことはドキュメントの @ref{f77,,非同期イテレータ (Asynchronous Iterator)} 節を参照してください。

@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 492

@item PEP 492@footnote{https://peps.python.org/pep-0492/} -- コルーチン、 async 構文と await 構文

PEP written and implemented by Yury Selivanov.
@end table


@node PEP 465 - 行列の乗算専用の中置演算子,PEP 448 - 追加可能なアンパックへの一般化,PEP 492 - コルーチン、 async と await 構文,新しい機能<15>
@anchor{whatsnew/3 5 pep-465-a-dedicated-infix-operator-for-matrix-multiplication}@anchor{f78}@anchor{whatsnew/3 5 whatsnew-pep-465}@anchor{f60}
@subsubsection PEP 465 - 行列の乗算専用の中置演算子


@geindex Python Enhancement Proposals; PEP 465
PEP 465@footnote{https://peps.python.org/pep-0465/} adds the @code{@@} infix operator for matrix multiplication.
Currently, no builtin Python types implement the new operator, however, it
can be implemented by defining @ref{f79,,__matmul__()},
@ref{f7a,,__rmatmul__()}, and @ref{f7b,,__imatmul__()} for regular,
reflected, and in-place matrix multiplication.
The semantics of these methods is similar to that of
methods defining other infix arithmetic operators.

行列の乗算は数学、科学、工学の多くの分野では非常に一般的です。
@code{@@} の追加によりコードをより綺麗に書くことが出来ます:

@example
S = (H @@ beta - r).T @@ inv(H @@ V @@ H.T) @@ (H @@ beta - r)
@end example

これはたとえば NumPy を使っても、以下のように書く必要がありました:

@example
S = dot((dot(H, beta) - r).T,
        dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))
@end example

NumPy 1.10 はこの新たな演算子をサポートしています:

@example
>>> import numpy

>>> x = numpy.ones(3)
>>> x
array([ 1., 1., 1.])

>>> m = numpy.eye(3)
>>> m
array([[ 1., 0., 0.],
       [ 0., 1., 0.],
       [ 0., 0., 1.]])

>>> x @@ m
array([ 1., 1., 1.])
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 465

@item PEP 465@footnote{https://peps.python.org/pep-0465/} -- 行列乗算専用の中置演算子

PEP written by Nathaniel J. Smith; implemented by Benjamin Peterson.
@end table


@node PEP 448 - 追加可能なアンパックへの一般化,PEP 461 - bytes および bytearray のパーセント書式化サポート,PEP 465 - 行列の乗算専用の中置演算子,新しい機能<15>
@anchor{whatsnew/3 5 pep-448-additional-unpacking-generalizations}@anchor{f7c}@anchor{whatsnew/3 5 whatsnew-pep-448}@anchor{f61}
@subsubsection PEP 448 - 追加可能なアンパックへの一般化


@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} によって、 @code{*} イテラブルアンパック演算子と @code{**} 辞書アンパック演算子の利用方法が拡張されました。
@ref{f7d,,関数呼び出し} で任意の数のアンパックで使えるようになりました:

@example
>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5

>>> def fn(a, b, c, d):
...     print(a, b, c, d)
...

>>> fn(**@{'a': 1, 'c': 3@}, **@{'b': 2, 'd': 4@})
1 2 3 4
@end example

同様に、タプル、リスト、集合、辞書表現でも複数のアンパックが使えます (@ref{f7e,,式のリスト} および @ref{f7f,,辞書表示} を参照してください):

@example
>>> *range(4), 4
(0, 1, 2, 3, 4)

>>> [*range(4), 4]
[0, 1, 2, 3, 4]

>>> @{*range(4), 4, *(5, 6, 7)@}
@{0, 1, 2, 3, 4, 5, 6, 7@}

>>> @{'x': 1, **@{'y': 2@}@}
@{'x': 1, 'y': 2@}
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 448

@item PEP 448@footnote{https://peps.python.org/pep-0448/} -- 追加可能なアンパックへの一般化

PEP written by Joshua Landau; implemented by Neil Girdhar,
Thomas Wouters, and Joshua Landau.
@end table


@node PEP 461 - bytes および bytearray のパーセント書式化サポート,PEP 484 - 型ヒント,PEP 448 - 追加可能なアンパックへの一般化,新しい機能<15>
@anchor{whatsnew/3 5 pep-461-percent-formatting-support-for-bytes-and-bytearray}@anchor{f80}@anchor{whatsnew/3 5 whatsnew-pep-461}@anchor{f64}
@subsubsection PEP 461 - bytes および bytearray のパーセント書式化サポート


@geindex Python Enhancement Proposals; PEP 461
PEP 461@footnote{https://peps.python.org/pep-0461/} によって、 @ref{192,,bytes} と @ref{344,,bytearray} に @code{%} @ref{f81,,補間演算子} のサポートが追加されます。

補間は通常は文字列演算だと考えられていますが、 @code{bytes} や @code{bytearrays} 上の補間が意味を持つ場合もあって、この機能が無いと余計な作業が必要になりコードの全体の可読性が損なわれます。
この問題は特にワイヤフォーマットプロトコルの取り扱いにおいて重要で、バイナリとASCII互換のテキストが入り交じったものがよく出てきます。

例:

@example
>>> b'Hello %b!' % b'World'
b'Hello World!'

>>> b'x=%i y=%f' % (1, 2.5)
b'x=1 y=2.500000'
@end example

Unicode に対して @code{%b} は使えませんが、 @code{%a} であれば使えます (@code{repr(obj).encode('ascii', 'backslashreplace')} と同等):

@example
>>> b'Hello %b!' % 'World'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'

>>> b'price: %a' % '10€'
b"price: '10\\u20ac'"
@end example

@code{%s} および @code{%r} 変換型はサポートはされますが、 Python 2 との互換性を持たせる必要のあるコードベースでのみ使われるべきだということに注意してください。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 461

@item PEP 461@footnote{https://peps.python.org/pep-0461/} -- bytes と bytearray への % 書式化の追加

PEP written by Ethan Furman; implemented by Neil Schemenauer and
Ethan Furman.
@end table


@node PEP 484 - 型ヒント,PEP 471 - os scandir 関数 -- より良く、速いディレクトリイテレータ,PEP 461 - bytes および bytearray のパーセント書式化サポート,新しい機能<15>
@anchor{whatsnew/3 5 pep-484-type-hints}@anchor{f82}@anchor{whatsnew/3 5 whatsnew-pep-484}@anchor{f62}
@subsubsection PEP 484 - 型ヒント


関数アノテーション構文はバージョン 3.0 (
@geindex Python Enhancement Proposals; PEP 3107
PEP 3107@footnote{https://peps.python.org/pep-3107/}) から Python の仕様になりましたが、アノテーションのセマンティクスは未定義のままでした。

経験的に、関数アノテーションの使用の大半は関数の引数と返り値の型ヒントを提供するためのものです。
標準ライブラリーが型アノテーションの基本的な定義とツールを持てば、Python ユーザに有益であることは明白となりました。

@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} introduces a @ref{3d1,,provisional module} to
provide these standard definitions and tools, along with some conventions
for situations where annotations are not available.

例えば、こちらは引数と返り値の型がアノテーションで定義されている簡単な関数です:

@example
def greeting(name: str) -> str:
    return 'Hello ' + name
@end example

While these annotations are available at runtime through the usual
@ref{458,,__annotations__} attribute, `no automatic type checking happens
at runtime'.  Instead, it is assumed that a separate off-line type checker
(e.g. mypy@footnote{https://mypy-lang.org}) will be used for on-demand
source code analysis.

型システムはユニオン、一般型、そして @ref{8bb,,Any} という全ての型と互換な (すなわち代入可能) 特殊型をサポートしています。


@subsubheading 参考



@itemize *

@item 
@ref{10a,,typing} モジュールのドキュメント

@item 

@table @asis

@geindex Python Enhancement Proposals; PEP 484

@item PEP 484@footnote{https://peps.python.org/pep-0484/} -- 型ヒント

PEP 著 Guido van Rossum, Jukka Lehtosalo, Łukasz Langa; 実装 Guido van Rossum。
@end table

@item 

@table @asis

@geindex Python Enhancement Proposals; PEP 483

@item PEP 483@footnote{https://peps.python.org/pep-0483/} -- 型ヒントの理論

PEP written by Guido van Rossum
@end table
@end itemize


@node PEP 471 - os scandir 関数 -- より良く、速いディレクトリイテレータ,PEP 475 EINTR で失敗したシステムコールの再試行,PEP 484 - 型ヒント,新しい機能<15>
@anchor{whatsnew/3 5 pep-471-os-scandir-function-a-better-and-faster-directory-iterator}@anchor{f83}@anchor{whatsnew/3 5 whatsnew-pep-471}@anchor{f6d}
@subsubsection PEP 471 - os.scandir() 関数 -- より良く、速いディレクトリイテレータ


@geindex Python Enhancement Proposals; PEP 471
PEP 471@footnote{https://peps.python.org/pep-0471/} により新しいディレクトリ反復関数 @ref{c54,,os.scandir()} が標準ライブラリへ追加されました。
さらに、 @code{scandir} を使い @ref{6d0,,os.walk()} が実装され、 POSIX システムで3倍から5倍、 Windows システムで7倍から20倍高速になりました。
これは主に、ディレクトリツリーを走査するのに必要な @ref{26d,,os.stat()} の呼び出し回数をかなり減らしたことによるものです。

これの他にも、  @code{scandir}  ファイル名のリストではなくイテレータを返すようになり、非常に大きなディレクトリ群の走査をするときのメモリ効率が改善されました。

次の例では、 @ref{c54,,os.scandir()} を使用して、与えられた `path' 内の先頭が @code{'.'} でないすべてのファイル (ディレクトリを除く) を表示します。 @ref{f84,,entry.is_file()} を呼び出しても、通常は追加のシステムコールは行われません:

@example
for entry in os.scandir(path):
    if not entry.name.startswith('.') and entry.is_file():
        print(entry.name)
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 471

@item PEP 471@footnote{https://peps.python.org/pep-0471/} -- os.scandir() 関数 -- より良く、速いディレクトリイテレータ

PEP 著・実装 Ben Hoyt 補佐 Victor Stinner。
@end table


@node PEP 475 EINTR で失敗したシステムコールの再試行,PEP 479 ジェネレータ内の StopIteration の処理の変更,PEP 471 - os scandir 関数 -- より良く、速いディレクトリイテレータ,新しい機能<15>
@anchor{whatsnew/3 5 pep-475-retry-system-calls-failing-with-eintr}@anchor{f85}@anchor{whatsnew/3 5 whatsnew-pep-475}@anchor{f86}
@subsubsection PEP 475: EINTR で失敗したシステムコールの再試行


An @ref{f87,,errno.EINTR} error code is returned whenever a system call, that
is waiting for I/O, is interrupted by a signal.  Previously, Python would
raise @ref{f88,,InterruptedError} in such cases.  This meant that, when writing a
Python application, the developer had two choices:


@enumerate 

@item 
@code{InterruptedError} を無視する。

@item 
呼び出し箇所の全てで @code{InterruptedError} を処理し、中断されたシステムコールの再開を試みる。
@end enumerate

最初の選択肢では、アプリケーションは断続的に失敗します。
二つ目の選択肢では、定型処理を大量に追加せねばならず、コードの可読性が著しく下がります。
次の2つを比べてみてください:

@example
print("Hello World")
@end example

および:

@example
while True:
    try:
        print("Hello World")
        break
    except InterruptedError:
        continue
@end example

@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} は @code{EINTR} を受けた場合のシステムコールの自動再試行を実装しています。
これはほとんどの場合ユーザコードでの @code{EINTR} や @ref{f88,,InterruptedError} を扱う負担をなくし、標準ライブラリを含む Python プログラムをより堅牢にします。
シグナルハンドラが例外を投げない場合にのみシステムコールを再試行することに注意してください。

下記は、シグナルで中断された際に再試行をするようになった関数のリストです:


@itemize *

@item 
@ref{316,,open()} および @ref{740,,io.open()};

@item 
@ref{5c,,faulthandler} モジュールの関数;

@item 
@ref{a5,,os} モジュールの関数: @ref{f89,,fchdir()}, @ref{52a,,fchmod()}, @ref{f8a,,fchown()}, @ref{f8b,,fdatasync()}, @ref{f8c,,fstat()}, @ref{f8d,,fstatvfs()}, @ref{f8e,,fsync()}, @ref{f8f,,ftruncate()}, @ref{f90,,mkfifo()}, @ref{f91,,mknod()}, @ref{f92,,open()}, @ref{f93,,posix_fadvise()}, @ref{f94,,posix_fallocate()}, @ref{d56,,pread()}, @ref{d59,,pwrite()}, @ref{f95,,read()}, @ref{d55,,readv()}, @ref{d05,,sendfile()}, @ref{f96,,wait3()}, @ref{f97,,wait4()}, @ref{f98,,wait()}, @ref{f99,,waitid()}, @ref{f9a,,waitpid()}, @ref{f9b,,write()}, @ref{d58,,writev()};

@item 
special cases: @ref{d6b,,os.close()} and @ref{d5a,,os.dup2()} now ignore
@ref{f87,,EINTR} errors; the syscall is not retried (see the PEP
for the rationale);

@item 
@ref{c6,,select} モジュール関数: @ref{f9c,,devpoll.poll()}, @ref{f9d,,epoll.poll()}, @ref{f9e,,kqueue.control()}, @ref{f9f,,poll.poll()}, @ref{fa0,,select()};

@item 
@ref{fa1,,socket} クラスのメソッド: @ref{fa2,,accept()}, @ref{fa3,,connect()} (ノンブロッキングソケットを除く), @ref{fa4,,recv()}, @ref{fa5,,recvfrom()}, @ref{fa6,,recvmsg()}, @ref{fa7,,send()}, @ref{fa8,,sendall()}, @ref{6a1,,sendmsg()}, @ref{fa9,,sendto()};

@item 
@ref{faa,,signal.sigtimedwait()} および @ref{fab,,signal.sigwaitinfo()};

@item 
@ref{8ac,,time.sleep()}.
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 475

@item PEP 475@footnote{https://peps.python.org/pep-0475/} -- EINTR で失敗したシステムコールの再試行

Antoine Pitrou の協力のもと、 PEP および実装は Charles-François Natali と Victor Stinner によって書かれました (『フレンチ・コネクション』)。
@end table


@node PEP 479 ジェネレータ内の StopIteration の処理の変更,PEP 485 近似的に等しいことを調べる関数,PEP 475 EINTR で失敗したシステムコールの再試行,新しい機能<15>
@anchor{whatsnew/3 5 pep-479-change-stopiteration-handling-inside-generators}@anchor{fac}@anchor{whatsnew/3 5 whatsnew-pep-479}@anchor{f1b}
@subsubsection PEP 479: ジェネレータ内の StopIteration の処理の変更


Python 3.4 以前では、ジェネレータと @ref{df5,,StopIteration} の組み合わせが驚くような動作をし、分かりづらいバグを隠すことがありました。
以前は、ジェネレータ関数内でうっかり @code{StopIteration} が送出されると、そのジェネレータの反復処理をしているループ構造が終端に達したと解釈されていました。

@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/} によってジェネレータのこの振る舞いが変更されました:
ジェネレータ内部で @code{StopIteration} 例外が送出されたときは、ジェネレータのフレームを抜ける前に @ref{244,,RuntimeError} に置き換えられます。
この変更の一番の目的は、保護されていない @ref{9d8,,next()} の呼び出しが @code{StopIteration} を送出し、ジェネレータを回している反復処理が黙って終了してしまうような状況で、デバッグをしやすくすることです。
これは @code{yield from} 構造と組み合わさったとき特に有害になります。

これは後方互換性の無い変更ですので、この新しい振る舞いを有効にするには @ref{fad,,__future__} のインポートが必要です:

@example
>>> from __future__ import generator_stop

>>> def gen():
...     next(iter([]))
...     yield
...
>>> next(gen())
Traceback (most recent call last):
  File "<stdin>", line 2, in gen
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
@end example

@code{__future__} をインポートしておらず、ジェネレータの内部で @ref{df5,,StopIteration} 例外が送出されたときには @ref{ac5,,PendingDeprecationWarning} が送出されます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 479

@item PEP 479@footnote{https://peps.python.org/pep-0479/} -- ジェネレータ内の StopIteration の処理の変更

PEP written by Chris Angelico and Guido van Rossum. Implemented by
Chris Angelico, Yury Selivanov and Nick Coghlan.
@end table


@node PEP 485 近似的に等しいことを調べる関数,PEP 486 Python ランチャーが仮想環境を認識する,PEP 479 ジェネレータ内の StopIteration の処理の変更,新しい機能<15>
@anchor{whatsnew/3 5 pep-485-a-function-for-testing-approximate-equality}@anchor{fae}@anchor{whatsnew/3 5 whatsnew-pep-485}@anchor{faf}
@subsubsection PEP 485: 近似的に等しいことを調べる関数


@geindex Python Enhancement Proposals; PEP 485
PEP 485@footnote{https://peps.python.org/pep-0485/} により、2値が互いに近似的に等しいか "近い" ことを調べる関数 @ref{fb0,,math.isclose()} 及び @ref{fb1,,cmath.isclose()} が追加されました。
2値が近いと判断されるかどうかは与えられた絶対及び相対許容差で決まります。
相対許容差は @code{isclose} 引数間で許される、絶対値の大きい方に対する最大の差です:

@example
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, rel_tol=1e-5)
True
>>> math.isclose(a, b, rel_tol=1e-6)
False
@end example

2値を絶対許容差で比較することも出来ます。絶対許容差は非負数でなければなりません:

@example
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, abs_tol=0.00003)
True
>>> math.isclose(a, b, abs_tol=0.00001)
False
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 485

@item PEP 485@footnote{https://peps.python.org/pep-0485/} -- A function for testing approximate equality

PEP written by Christopher Barker; implemented by Chris Barker and
Tal Einat.
@end table


@node PEP 486 Python ランチャーが仮想環境を認識する,PEP 488 PYO ファイルの廃止,PEP 485 近似的に等しいことを調べる関数,新しい機能<15>
@anchor{whatsnew/3 5 pep-486-make-the-python-launcher-aware-of-virtual-environments}@anchor{fb2}@anchor{whatsnew/3 5 whatsnew-pep-486}@anchor{fb3}
@subsubsection PEP 486: Python ランチャーが仮想環境を認識する


@geindex Python Enhancement Proposals; PEP 486
PEP 486@footnote{https://peps.python.org/pep-0486/} により、 Windows ランチャー (
@geindex Python Enhancement Proposals; PEP 397
PEP 397@footnote{https://peps.python.org/pep-0397/} を参照してください) が有効になっている仮想環境を認識するようになりました。
デフォルトのインタプリタを使っていて、 @code{VIRTUAL_ENV} 環境変数が設定されているときは、仮想環境のインタプリタが使われます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 486

@item PEP 486@footnote{https://peps.python.org/pep-0486/} -- Python ランチャーが仮想環境を認識する

PEP written and implemented by Paul Moore.
@end table


@node PEP 488 PYO ファイルの廃止,PEP 489 拡張モジュールの多段階初期化,PEP 486 Python ランチャーが仮想環境を認識する,新しい機能<15>
@anchor{whatsnew/3 5 pep-488-elimination-of-pyo-files}@anchor{fb4}@anchor{whatsnew/3 5 whatsnew-pep-488}@anchor{f69}
@subsubsection PEP 488: PYO ファイルの廃止


@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} は @code{.pyo} ファイルという概念を廃止しました。
つまり、@code{.pyc} ファイルは最適化されていないバイトコードと最適化されたバイトコードの両方を指すということです。
バイトコードファイルを何度も再生成する必要がないよう、バイトコードが最適化されたときは @code{.pyc} ファイルは任意の @code{opt-} タグを名前に持つようになりました。
この副作用で、@ref{18c,,-O} と @ref{fb5,,-OO} のいずれかで実行した場合でも、バイトコードのファイル名が衝突しないようになりました。
それにより、@ref{18c,,-O} および @ref{fb5,,-OO} で生成したバイトコードは同時に存在できるようになりました。
@ref{353,,importlib.util.cache_from_source()} にの API は更新され、この変更に役立ちます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 488

@item PEP 488@footnote{https://peps.python.org/pep-0488/} -- PYO ファイルの廃止

PEP written and implemented by Brett Cannon.
@end table


@node PEP 489 拡張モジュールの多段階初期化,,PEP 488 PYO ファイルの廃止,新しい機能<15>
@anchor{whatsnew/3 5 pep-489-multi-phase-extension-module-initialization}@anchor{fb6}@anchor{whatsnew/3 5 whatsnew-pep-489}@anchor{f6a}
@subsubsection PEP 489: 拡張モジュールの多段階初期化


@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} により拡張モジュールの初期化方式が更新され、 Python 3.4 で 
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/} によって導入された2段階でモジュールを読み込む仕組みが活用できるようになりました。

この変更によって、新しい仕組みを使うことを選択した拡張モジュールのインポートの動作が、 Python のソースコードやバイトコードでできたモジュールにかなり近くなり、これまで ASCII に制限されていたモジュール名に任意の識別子が使えるようになりました。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 489

@item PEP 489@footnote{https://peps.python.org/pep-0489/} -- 拡張モジュールの多段階初期化

PEP 著 Petr Viktorin, Stefan Behnel, Nick Coghlan; 実装 Petr Viktorin.
@end table


@node その他の言語変更<9>,新たなモジュール<9>,新しい機能<15>,What's New In Python 3 5
@anchor{whatsnew/3 5 other-language-changes}@anchor{fb7}
@subsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
@code{"namereplace"} エラーハンドラが追加されました。@code{"backslashreplace"} エラーハンドラはデコードと変換で動くようになりました。 (Contributed by Serhiy Storchaka in bpo-19676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19676} and bpo-22286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22286}.)

@item 
@ref{7f9,,-b} オプションが @ref{192,,bytes} と @ref{19b,,int} の比較に影響するようになりました。 (Contributed by Serhiy Storchaka in bpo-23681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23681}.)

@item 
新たなカザフ語 @code{kz1048} 及びタジク語 @code{koi8_t} @ref{fb8,,コーデックス}。 (Contributed by Serhiy Storchaka in bpo-22682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22682} and bpo-22681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22681}.)

@item 
プロパティのドキュメンテーション文字列が書き込み可能になりました。これは特に @ref{4e0,,collections.namedtuple()} のドキュメンテーション文字列で有用です。 (Contributed by Berker Peksag in bpo-24064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24064}.)

@item 
相対インポートに関する循環インポートがサポートされました。(Contributed by Brett Cannon and Antoine Pitrou in bpo-17636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17636}.)
@end itemize

@node 新たなモジュール<9>,改良されたモジュール<9>,その他の言語変更<9>,What's New In Python 3 5
@anchor{whatsnew/3 5 new-modules}@anchor{fb9}
@subsection 新たなモジュール


@menu
* typing: typing<11>. 
* zipapp: zipapp<2>. 

@end menu

@node typing<11>,zipapp<2>,,新たなモジュール<9>
@anchor{whatsnew/3 5 typing}@anchor{fba}
@subsubsection typing


The new @ref{10a,,typing} @ref{3d1,,provisional} module
provides standard definitions and tools for function type annotations.
See @ref{f62,,Type Hints} for more information.

@node zipapp<2>,,typing<11>,新たなモジュール<9>
@anchor{whatsnew/3 5 whatsnew-zipapp}@anchor{f63}@anchor{whatsnew/3 5 zipapp}@anchor{fbb}
@subsubsection zipapp


新たな @ref{136,,zipapp} モジュール (
@geindex Python Enhancement Proposals; PEP 441
PEP 441@footnote{https://peps.python.org/pep-0441/} で仕様定義) は実行可能な Python Zip アプリケーションを作成するための API とコマンドラインツールを提供します。
Python Zip アプリケーションは Python 2.6 の bpo-1739468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739468} で導入されましたが、それ以降もあまり知られていませんでした。

この新しいモジュールを使ったアプリケーションのバンドル方法は単純で、 @code{__main__.py} ファイルを含む全てのファイルをディレクトリ @code{myapp} に置き、次のように実行します:

@example
$ python -m zipapp myapp
$ python myapp.pyz
@end example

モジュールの実装は bpo-23491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23491} の Paul Moore による貢献です。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 441
PEP 441@footnote{https://peps.python.org/pep-0441/} -- Python ZIP アプリケーションのサポートの改善 <whatsnew-zipapp>`


@node 改良されたモジュール<9>,その他のモジュールレベルの変更,新たなモジュール<9>,What's New In Python 3 5
@anchor{whatsnew/3 5 improved-modules}@anchor{fbc}
@subsection 改良されたモジュール


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

@end menu

@node argparse<6>,asyncio<13>,,改良されたモジュール<9>
@anchor{whatsnew/3 5 argparse}@anchor{fbd}
@subsubsection argparse


@ref{1bd,,ArgumentParser} クラスは、@ref{fbe,,allow_abbrev} を @code{False} に設定することでロングオプションの @ref{fbf,,短縮使用} を無効化できるようになりました。 (Contributed by Jonathan Paugh, Steven Bethard, paul j3 and Daniel Eriksson in bpo-14910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14910}.)

@node asyncio<13>,bz2,argparse<6>,改良されたモジュール<9>
@anchor{whatsnew/3 5 asyncio}@anchor{fc0}
@subsubsection asyncio


Since the @ref{b,,asyncio} module is @ref{3d1,,provisional},
all changes introduced in Python 3.5 have also been backported to Python 3.4.x.

Python 3.4.0 以後の @ref{b,,asyncio} モジュールの重要な変更点:


@itemize *

@item 
新たなデバッグ API: @ref{fc1,,loop.set_debug()} と @ref{fc2,,loop.get_debug()} メソッド。 (Contributed by Victor Stinner.)

@item 
proactor イベントループが SSL をサポートしました。 (Contributed by Antoine Pitrou and Victor Stinner in bpo-22560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22560}.)

@item 
イベントループが閉じているかどうか調べる新たな @ref{fc3,,loop.is_closed()} メソッド。 (Contributed by Victor Stinner in bpo-21326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21326}.)

@item 
コルーチンの新しい @ref{1c7,,Task} を便利に作成しスケジュールするための新たな @ref{1ca,,loop.create_task()}。
@code{create_task} メソッドは
コルーチンをタスクにラップする全ての asyncio 関数、たとえば @ref{6a7,,asyncio.wait()}, @ref{813,,asyncio.gather()}、にも使われます。 (Contributed by Victor Stinner.)

@item 
A new @ref{fc4,,transport.get_write_buffer_limits()}
method to inquire for `high-' and `low-' water limits of the flow
control.
(Contributed by Victor Stinner.)

@item 
The @code{async()} function is deprecated in favor of
@ref{e71,,ensure_future()}.
(Contributed by Yury Selivanov.)

@item 
@ref{1ca,,loop.create_task()} メソッドが使うタスクファクトリーをカスタマイズするための新たな @ref{1c8,,loop.set_task_factory()} メソッドと @ref{fc5,,loop.get_task_factory()} メソッド。 (Yury Selivanovによる貢献。)

@item 
新たな @ref{fc6,,Queue.join()} および @ref{fc7,,Queue.task_done()} キューメソッド。(Contributed by Victor Stinner.)

@item 
@code{JoinableQueue} クラスは @ref{c6a,,asyncio.Queue} クラスにより削除されました。 (Contributed by Victor Stinner.)
@end itemize

3.5.1 での変更:


@itemize *

@item 
The @ref{e71,,ensure_future()} function and all functions that
use it, such as @ref{e72,,loop.run_until_complete()},
now accept all kinds of @ref{4c9,,awaitable objects}.
(Contributed by Yury Selivanov.)

@item 
他のスレッドからコルーチンをイベントループに送信するための新たな @ref{a82,,run_coroutine_threadsafe()} 関数。
(Contributed by Vincent Michel.)

@item 
New @ref{e73,,Transport.is_closing()}
method to check if the transport is closing or closed.
(Contributed by Yury Selivanov.)

@item 
The @ref{d09,,loop.create_server()}
method can now accept a list of hosts.
(Contributed by Yann Sionneau.)
@end itemize

3.5.2 での変更:


@itemize *

@item 
New @ref{e74,,loop.create_future()}
method to create Future objects.  This allows alternative event
loop implementations, such as
uvloop@footnote{https://github.com/MagicStack/uvloop}, to provide a faster
@ref{dc6,,asyncio.Future} implementation.
(Contributed by Yury Selivanov.)

@item 
New @ref{e75,,loop.get_exception_handler()}
method to get the current exception handler.
(Contributed by Yury Selivanov.)

@item 
新しい @ref{4d0,,StreamReader.readuntil()} メソッドで、区切りとなるバイトの並びが出てくるまでストリームからデータを読み取れるようになりました。
(Contributed by Mark Korenberg.)

@item 
The @ref{818,,loop.create_connection()}
and @ref{d09,,loop.create_server()}
methods are optimized to avoid calling the system @code{getaddrinfo}
function if the address is already resolved.
(Contributed by A. Jesse Jiryu Davis.)

@item 
The @ref{fc8,,loop.sock_connect(sock@comma{} address)}
no longer requires the `address' to be resolved prior to the call.
(Contributed by A. Jesse Jiryu Davis.)
@end itemize

@node bz2,cgi,asyncio<13>,改良されたモジュール<9>
@anchor{whatsnew/3 5 bz2}@anchor{fc9}
@subsubsection bz2


@ref{fca,,BZ2Decompressor.decompress} メソッドがオプション引数 `max_length' を取れるようになり、展開されたデータの最大サイズが制限できるようになりました。
(Contributed by Nikolaus Rath in bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}.)

@node cgi,cmath<2>,bz2,改良されたモジュール<9>
@anchor{whatsnew/3 5 cgi}@anchor{fcb}
@subsubsection cgi


The @code{FieldStorage} class now supports the @ref{1e1,,context manager}
protocol.  (Contributed by Berker Peksag in bpo-20289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20289}.)

@node cmath<2>,コード,cgi,改良されたモジュール<9>
@anchor{whatsnew/3 5 cmath}@anchor{fcc}
@subsubsection cmath


新たな関数 @ref{fb1,,isclose()} は近似的に等しいかどうかを判断する方法を提供します。
(Contributed by Chris Barker and Tal Einat in bpo-24270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24270}.)

@node コード,collections<5>,cmath<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 code}@anchor{fcd}
@subsubsection コード


@ref{fce,,InteractiveInterpreter.showtraceback()} メソッドが、対話的インタープリタのように連なったスタックトレース全体を表示するようになりました。
(Contributed by Claudiu Popa in bpo-17442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17442}.)

@node collections<5>,collections abc<3>,コード,改良されたモジュール<9>
@anchor{whatsnew/3 5 collections}@anchor{fcf}
@subsubsection collections

@anchor{whatsnew/3 5 whatsnew-ordereddict}@anchor{f6b}
@ref{7f3,,collections.OrderedDict} が C で実装されました。
これにより 4倍 から 100 倍高速になりました。
(Contributed by Eric Snow in bpo-16991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16991}.)

@code{OrderedDict.items()}, @code{OrderedDict.keys()},
and @code{OrderedDict.values()} views now support @ref{a65,,reversed()} iteration.
(Contributed by Serhiy Storchaka in bpo-19505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19505}.)

@ref{7f4,,deque} クラスが @ref{fd0,,index()}、 @ref{fd1,,insert()}、 @ref{fd2,,copy()} を定義し、@code{+} と @code{*} 演算をサポートしました。
これにより deque インスタンスは @ref{4bf,,MutableSequence} と認識され、list との代替性が向上しました。
(Contributed by Raymond Hettinger in bpo-23704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23704}.)

@ref{4e0,,namedtuple()} で生成されたドキュメンテーション文字列が更新可能となりました:

@example
Point = namedtuple('Point', ['x', 'y'])
Point.__doc__ += ': Cartesian coordinate'
Point.x.__doc__ = 'abscissa'
Point.y.__doc__ = 'ordinate'
@end example

(Contributed by Berker Peksag in bpo-24064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24064}.)

The @ref{fd3,,UserString} class now implements the
@ref{fd4,,__getnewargs__()}, @ref{fd5,,__rmod__()}, @ref{fd6,,casefold()},
@ref{fd7,,format_map()}, @ref{fd8,,isprintable()}, and @ref{fd9,,maketrans()}
methods to match the corresponding methods of @ref{169,,str}.
(Contributed by Joe Jevnik in bpo-22189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22189}.)

@node collections abc<3>,compileall<4>,collections<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 collections-abc}@anchor{fda}
@subsubsection collections.abc


The @code{Sequence.index()} method now
accepts `start' and `stop' arguments to match the corresponding methods
of @ref{614,,tuple}, @ref{24d,,list}, etc.
(Contributed by Devin Jeanpierre in bpo-23086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23086}.)

新たに @ref{fdb,,Generator} 抽象基底クラスが追加されました。
(Contributed by Stefan Behnel in bpo-24018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24018}.)

新たに @ref{fdc,,Awaitable}, @ref{fdd,,Coroutine}, @ref{fde,,AsyncIterator}, @ref{fdf,,AsyncIterable} 抽象基底クラスが追加されました。
(Contributed by Yury Selivanov in bpo-24184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24184}.)

For earlier Python versions, a backport of the new ABCs is available in an
external PyPI package@footnote{https://pypi.org/project/backports_abc/}.

@node compileall<4>,concurrent futures<6>,collections abc<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 compileall}@anchor{fe0}
@subsubsection compileall


A new @ref{21,,compileall} option, @code{-j @var{N}}, allows running `N' workers
simultaneously to perform parallel bytecode compilation.
The @ref{d1b,,compile_dir()} function has a corresponding @code{workers}
parameter.  (Contributed by Claudiu Popa in bpo-16104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16104}.)

Another new option, @code{-r}, allows controlling the maximum recursion
level for subdirectories.  (Contributed by Claudiu Popa in bpo-19628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19628}.)

The @code{-q} command line option can now be specified more than once, in
which case all output, including errors, will be suppressed.  The corresponding
@code{quiet} parameter in @ref{d1b,,compile_dir()},
@ref{fe1,,compile_file()}, and @ref{fe2,,compile_path()} can now
accept an integer value indicating the level of output suppression.
(Contributed by Thomas Kluyver in bpo-21338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21338}.)

@node concurrent futures<6>,configparser<5>,compileall<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 concurrent-futures}@anchor{fe3}
@subsubsection concurrent.futures


The @ref{1dc,,Executor.map()} method now accepts a
`chunksize' argument to allow batching of tasks to improve performance when
@ref{1d6,,ProcessPoolExecutor()} is used.
(Contributed by Dan O'Reilly in bpo-11271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11271}.)

The number of workers in the @ref{949,,ThreadPoolExecutor}
constructor is optional now.  The default value is 5 times the number of CPUs.
(Contributed by Claudiu Popa in bpo-21527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21527}.)

@node configparser<5>,contextlib<5>,concurrent futures<6>,改良されたモジュール<9>
@anchor{whatsnew/3 5 configparser}@anchor{fe4}
@subsubsection configparser


@ref{26,,configparser} now provides a way to customize the conversion
of values by specifying a dictionary of converters in the
@ref{4de,,ConfigParser} constructor, or by defining them
as methods in @code{ConfigParser} subclasses.  Converters defined in
a parser instance are inherited by its section proxies.

以下はプログラム例です:

@example
>>> import configparser
>>> conv = @{@}
>>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]
>>> cfg = configparser.ConfigParser(converters=conv)
>>> cfg.read_string("""
... [s]
... list = a b c d e f g
... """)
>>> cfg.get('s', 'list')
'a b c d e f g'
>>> cfg.getlist('s', 'list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> section = cfg['s']
>>> section.getlist('list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
@end example

(Contributed by Łukasz Langa in bpo-18159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18159}.)

@node contextlib<5>,csv<3>,configparser<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 contextlib}@anchor{fe5}
@subsubsection contextlib


新規 @ref{1e1,,context manager} の @ref{fe6,,contextlib.redirect_stderr()} は、ユーティリティスクリプトにて、その出力を @ref{b33,,sys.stderr} に書き出す一方でその向き先を変えれない頑固な API の扱いを簡単にしてくれます  (@ref{fe7,,redirect_stdout()} と対となるものです)。:

@example
>>> import contextlib, io, logging
>>> f = io.StringIO()
>>> with contextlib.redirect_stderr(f):
...     logging.warning('warning')
...
>>> f.getvalue()
'WARNING:root:warning\n'
@end example

(Contributed by Berker Peksag in bpo-22389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22389}.)

@node csv<3>,curses<5>,contextlib<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 csv}@anchor{fe8}
@subsubsection csv


@ref{fe9,,writerow()} メソッドは、シーケンスだけでなく、 任意のイテラブルをサポートしました。(Contributed by Serhiy Storchaka in bpo-23171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23171}.)

@node curses<5>,dbm<5>,csv<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 curses}@anchor{fea}
@subsubsection curses


The new @ref{feb,,update_lines_cols()} function updates the @ref{fec,,LINES}
and @ref{fed,,COLS} module variables.  This is useful for detecting
manual screen resizing.  (Contributed by Arnon Yaari in bpo-4254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4254}.)

@node dbm<5>,difflib<3>,curses<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 dbm}@anchor{fee}
@subsubsection dbm


@ref{c8d,,dumb.open} always creates a new database when the flag
has the value @code{"n"}.  (Contributed by Claudiu Popa in bpo-18039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18039}.)

@node difflib<3>,distutils<7>,dbm<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 difflib}@anchor{fef}
@subsubsection difflib


The charset of HTML documents generated by
@ref{ff0,,HtmlDiff.make_file()}
can now be customized by using a new `charset' keyword-only argument.
The default charset of HTML document changed from @code{"ISO-8859-1"}
to @code{"utf-8"}.
(Contributed by Berker Peksag in bpo-2052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2052}.)

The @ref{ff1,,diff_bytes()} function can now compare lists of byte
strings.  This fixes a regression from Python 2.
(Contributed by Terry J. Reedy and Greg Ward in bpo-17445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17445}.)

@node distutils<7>,doctest<3>,difflib<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 distutils}@anchor{ff2}
@subsubsection distutils


Both the @code{build} and @code{build_ext} commands now accept a @code{-j} option to
enable parallel building of extension modules.
(Contributed by Antoine Pitrou in bpo-5309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5309}.)

The @code{distutils} module now supports @code{xz} compression, and can be
enabled by passing @code{xztar} as an argument to @code{bdist --format}.
(Contributed by Serhiy Storchaka in bpo-16314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16314}.)

@node doctest<3>,email<4>,distutils<7>,改良されたモジュール<9>
@anchor{whatsnew/3 5 doctest}@anchor{ff3}
@subsubsection doctest


@ref{ff4,,DocTestSuite()} 関数が、 `module' がドキュメンテーション文字列(docstrings)を含まない場合に @ref{2ec,,ValueError} を送出するのではなく空の @ref{ff5,,unittest.TestSuite} を返すようになりました。 (Contributed by Glenn Jones in bpo-15916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15916}.)

@node email<4>,enum<8>,doctest<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 email}@anchor{ff6}
@subsubsection email


A new policy option @ref{ff7,,Policy.mangle_from_}
controls whether or not lines that start with @code{"From "} in email bodies are
prefixed with a @code{">"} character by generators.  The default is @code{True} for
@ref{e97,,compat32} and @code{False} for all other policies.
(Contributed by Milan Oberkirch in bpo-20098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20098}.)

A new
@ref{ff8,,Message.get_content_disposition()}
method provides easy access to a canonical value for the
@code{Content-Disposition} header.
(Contributed by Abhilash Raj in bpo-21083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21083}.)

A new policy option @ref{ff9,,EmailPolicy.utf8}
can be set to @code{True} to encode email headers using the UTF-8 charset instead
of using encoded words.  This allows @code{Messages} to be formatted according to
@geindex RFC; RFC 6532
RFC 6532@footnote{https://datatracker.ietf.org/doc/html/rfc6532.html} and used with an SMTP server that supports the 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://datatracker.ietf.org/doc/html/rfc6531.html}
@code{SMTPUTF8} extension.  (Contributed by R. David Murray in
bpo-24211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24211}.)

The @ref{ffa,,mime.text.MIMEText} constructor now
accepts a @ref{ffb,,charset.Charset} instance.
(Contributed by Claude Paroz and Berker Peksag in bpo-16324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16324}.)

@node enum<8>,faulthandler<4>,email<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 enum}@anchor{ffc}
@subsubsection enum


@ref{842,,Enum} 呼び出し可能オブジェクトは、`names' のみが与えられた場合に enum 値の初期値を指定する新たな引数 `start' を持ちます:

@example
>>> Animal = enum.Enum('Animal', 'cat dog', start=10)
>>> Animal.cat
<Animal.cat: 10>
>>> Animal.dog
<Animal.dog: 11>
@end example

(Contributed by Ethan Furman in bpo-21706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21706}.)

@node faulthandler<4>,functools<5>,enum<8>,改良されたモジュール<9>
@anchor{whatsnew/3 5 faulthandler}@anchor{ffd}
@subsubsection faulthandler


関数 @ref{20f,,enable()}, @ref{ffe,,register()}, @ref{fff,,dump_traceback()}, @ref{1000,,dump_traceback_later()} が、ファイル様オブジェクトだけでなくファイル記述子を受け取るようになりました。 (Contributed by Wei Wu in bpo-23566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23566}.)

@node functools<5>,glob<3>,faulthandler<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 functools}@anchor{1001}
@subsubsection functools

@anchor{whatsnew/3 5 whatsnew-lrucache}@anchor{f6e}
@ref{be2,,lru_cache()} 機構の多くが C で実装されました。これにより速度が大幅に向上しました。 (Contributed by Matt Joiner, Alexey Kachayev, and Serhiy Storchaka in bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}.)

@node glob<3>,gzip<4>,functools<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 glob}@anchor{1002}
@subsubsection glob


@ref{a08,,iglob()} 関数と @ref{5a0,,glob()} 関数は、 @code{"**"} パターンを使ったサブディレクトリの再帰的な検索をサポートしました。(Contributed by Serhiy Storchaka in bpo-13968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13968}.)

@node gzip<4>,heapq<2>,glob<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 gzip}@anchor{1003}
@subsubsection gzip


@ref{65c,,GzipFile} コンストラクタの `mode' 引数が排他的作成を要求する @code{"x"}  を受け取るようになりました。 (Contributed by Tim Heaney in bpo-19222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19222}.)

@node heapq<2>,http<3>,gzip<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 heapq}@anchor{1004}
@subsubsection heapq


Element comparison in @ref{1005,,merge()} can now be customized by
passing a @ref{1006,,key function} in a new optional `key' keyword argument,
and a new optional `reverse' keyword argument can be used to reverse element
comparison:

@example
>>> import heapq
>>> a = ['9', '777', '55555']
>>> b = ['88', '6666']
>>> list(heapq.merge(a, b, key=len))
['9', '88', '777', '6666', '55555']
>>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))
['55555', '6666', '777', '88', '9']
@end example

(Contributed by Raymond Hettinger in bpo-13742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13742}.)

@node http<3>,http client<3>,heapq<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 http}@anchor{1007}
@subsubsection http


新しい @ref{afc,,HTTPStatus} のenum は、HTTPステータスコードのセットで、その理由句と詳細な説明は、英語で記載されています。(Contributed by Demian Brecht in bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}.)

@node http client<3>,idlelib と IDLE<3>,http<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 http-client}@anchor{1008}
@subsubsection http.client


@ref{1009,,HTTPConnection.getresponse()}
now raises a @ref{100a,,RemoteDisconnected} exception when a
remote server connection is closed unexpectedly.  Additionally, if a
@ref{100b,,ConnectionError} (of which @code{RemoteDisconnected}
is a subclass) is raised, the client socket is now closed automatically,
and will reconnect on the next request:

@example
import http.client
conn = http.client.HTTPConnection('www.python.org')
for retries in range(3):
    try:
        conn.request('GET', '/')
        resp = conn.getresponse()
    except http.client.RemoteDisconnected:
        pass
@end example

(Contributed by Martin Panter in bpo-3566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3566}.)

@node idlelib と IDLE<3>,imaplib<3>,http client<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 idlelib-and-idle}@anchor{100c}
@subsubsection idlelib と IDLE


idlelib は IDLE シェルとエディタを実装するものであってほかのプログラムからインポートされることを意図してはいないので、改善は毎度のリリースごとに行われます。3.4.0 から始まり、また将来の 3.5.x リリースになされる累積的な変更リストは @code{Lib/idlelib/NEWS.txt} で読むことが出来ます。このファイルは IDLE で Help ‣ About IDLE からも辿り着けます。

@node imaplib<3>,imghdr,idlelib と IDLE<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 imaplib}@anchor{100d}
@subsubsection imaplib


@ref{aff,,IMAP4} クラスが @ref{1e1,,context manager} プロトコルをサポートするようになりました。 @ref{186,,with} 文とともに使うと、 IMAP4 @code{LOGOUT} コマンドがブロックの終了時に自動的に呼び出されます。 (Contributed by Tarek Ziadé and Serhiy Storchaka in bpo-4972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4972}.)

The @ref{78,,imaplib} module now supports 
@geindex RFC; RFC 5161
RFC 5161@footnote{https://datatracker.ietf.org/doc/html/rfc5161.html} (ENABLE Extension)
and 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://datatracker.ietf.org/doc/html/rfc6855.html} (UTF-8 Support) via the @ref{100e,,IMAP4.enable()}
method.  A new @ref{100f,,IMAP4.utf8_enabled}
attribute tracks whether or not 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://datatracker.ietf.org/doc/html/rfc6855.html} support is enabled.
(Contributed by Milan Oberkirch, R. David Murray, and Maciej Szulik in
bpo-21800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21800}.)

The @ref{78,,imaplib} module now automatically encodes non-ASCII string usernames
and passwords using UTF-8, as recommended by the RFCs.  (Contributed by Milan
Oberkirch in bpo-21800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21800}.)

@node imghdr,importlib<8>,imaplib<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 imghdr}@anchor{1010}
@subsubsection imghdr


The @code{what()} function now recognizes the
OpenEXR@footnote{https://www.openexr.com} format
(contributed by Martin Vignali and Claudiu Popa in bpo-20295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20295}),
and the WebP@footnote{https://en.wikipedia.org/wiki/WebP} format
(contributed by Fabrice Aneche and Claudiu Popa in bpo-20197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20197}.)

@node importlib<8>,inspect<8>,imghdr,改良されたモジュール<9>
@anchor{whatsnew/3 5 importlib}@anchor{1011}
@subsubsection importlib


The @ref{eab,,util.LazyLoader} class allows for
lazy loading of modules in applications where startup time is important.
(Contributed by Brett Cannon in bpo-17621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17621}.)

The @ref{1012,,abc.InspectLoader.source_to_code()}
method is now a static method.  This makes it easier to initialize a module
object with code compiled from a string by running
@code{exec(code, module.__dict__)}.
(Contributed by Brett Cannon in bpo-21156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21156}.)

The new @ref{1013,,util.module_from_spec()}
function is now the preferred way to create a new module.  As opposed to
creating a @ref{1014,,types.ModuleType} instance directly, this new function
will set the various import-controlled attributes based on the passed-in
spec object.  (Contributed by Brett Cannon in bpo-20383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20383}.)

@node inspect<8>,io<7>,importlib<8>,改良されたモジュール<9>
@anchor{whatsnew/3 5 inspect}@anchor{1015}
@subsubsection inspect


Both the @ref{4e3,,Signature} and @ref{4e4,,Parameter} classes are
now picklable and hashable.  (Contributed by Yury Selivanov in bpo-20726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20726}
and bpo-20334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20334}.)

A new
@ref{1016,,BoundArguments.apply_defaults()}
method provides a way to set default values for missing arguments:

@example
>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
@end example

(Contributed by Yury Selivanov in bpo-24190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24190}.)

A new class method
@ref{942,,Signature.from_callable()} makes
subclassing of @ref{4e3,,Signature} easier.  (Contributed
by Yury Selivanov and Eric Snow in bpo-17373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17373}.)

The @ref{22f,,signature()} function now accepts a `follow_wrapped'
optional keyword argument, which, when set to @code{False}, disables automatic
following of @code{__wrapped__} links.
(Contributed by Yury Selivanov in bpo-20691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20691}.)

A set of new functions to inspect
@ref{f73,,coroutine functions} and
@ref{6b9,,coroutine objects} has been added:
@ref{1017,,iscoroutine()}, @ref{30d,,iscoroutinefunction()},
@ref{1018,,isawaitable()}, @ref{1019,,getcoroutinelocals()},
and @ref{101a,,getcoroutinestate()}.
(Contributed by Yury Selivanov in bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017} and bpo-24400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24400}.)

The @ref{862,,stack()}, @ref{863,,trace()},
@ref{860,,getouterframes()}, and @ref{861,,getinnerframes()}
functions now return a list of named tuples.
(Contributed by Daniel Shahaf in bpo-16808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16808}.)

@node io<7>,ipaddress<4>,inspect<8>,改良されたモジュール<9>
@anchor{whatsnew/3 5 io}@anchor{101b}
@subsubsection io


A new @ref{101c,,BufferedIOBase.readinto1()}
method, that uses at most one call to the underlying raw stream's
@ref{101d,,RawIOBase.read()} or
@ref{101e,,RawIOBase.readinto()} methods.
(Contributed by Nikolaus Rath in bpo-20578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20578}.)

@node ipaddress<4>,json<3>,io<7>,改良されたモジュール<9>
@anchor{whatsnew/3 5 ipaddress}@anchor{101f}
@subsubsection ipaddress


Both the @ref{50e,,IPv4Network} and @ref{50f,,IPv6Network} classes
now accept an @code{(address, netmask)} tuple argument, so as to easily construct
network objects from existing addresses:

@example
>>> import ipaddress
>>> ipaddress.IPv4Network(('127.0.0.0', 8))
IPv4Network('127.0.0.0/8')
>>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))
IPv4Network('127.0.0.0/8')
@end example

(Contributed by Peter Moody and Antoine Pitrou in bpo-16531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16531}.)

A new @ref{1020,,reverse_pointer} attribute for the
@ref{50c,,IPv4Address} and @ref{50d,,IPv6Address} classes
returns the name of the reverse DNS PTR record:

@example
>>> import ipaddress
>>> addr = ipaddress.IPv4Address('127.0.0.1')
>>> addr.reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> addr6 = ipaddress.IPv6Address('::1')
>>> addr6.reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'
@end example

(Contributed by Leon Weber in bpo-20480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20480}.)

@node json<3>,linecache<3>,ipaddress<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 json}@anchor{1021}
@subsubsection json


The @ref{87,,json.tool} command line interface now preserves the order of keys in
JSON objects passed in input.  The new @code{--sort-keys} option can be used
to sort the keys alphabetically. (Contributed by Berker Peksag
in bpo-21650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21650}.)

JSON decoder now raises @ref{1022,,JSONDecodeError} instead of
@ref{2ec,,ValueError} to provide better context information about the error.
(Contributed by Serhiy Storchaka in bpo-19361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19361}.)

@node linecache<3>,locale<6>,json<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 linecache}@anchor{1023}
@subsubsection linecache


A new @ref{1024,,lazycache()} function can be used to capture information
about a non-file-based module to permit getting its lines later via
@ref{240,,getline()}. This avoids doing I/O until a line is actually
needed, without having to carry the module globals around indefinitely.
(Contributed by Robert Collins in bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}.)

@node locale<6>,logging<5>,linecache<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 locale}@anchor{1025}
@subsubsection locale


A new @ref{1026,,delocalize()} function can be used to convert a string into
a normalized number string, taking the @code{LC_NUMERIC} settings into account:

@example
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
'de_DE.UTF-8'
>>> locale.delocalize('1.234,56')
'1234.56'
>>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.delocalize('1,234.56')
'1234.56'
@end example

(Contributed by Cédric Krier in bpo-13918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13918}.)

@node logging<5>,lzma,locale<6>,改良されたモジュール<9>
@anchor{whatsnew/3 5 logging}@anchor{1027}
@subsubsection logging


All logging methods (@ref{d46,,Logger} @ref{1028,,log()},
@ref{1029,,exception()}, @ref{102a,,critical()},
@ref{102b,,debug()}, etc.), now accept exception instances
as an `exc_info' argument, in addition to boolean values and exception
tuples:

@example
>>> import logging
>>> try:
...     1/0
... except ZeroDivisionError as ex:
...     logging.error('exception', exc_info=ex)
ERROR:root:exception
@end example

(Contributed by Yury Selivanov in bpo-20537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20537}.)

The @ref{102c,,handlers.HTTPHandler} class now
accepts an optional @ref{357,,ssl.SSLContext} instance to configure SSL
settings used in an HTTP connection.
(Contributed by Alex Gaynor in bpo-22788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22788}.)

The @ref{242,,handlers.QueueListener} class now
takes a `respect_handler_level' keyword argument which, if set to @code{True},
will pass messages to handlers taking handler levels into account.
(Contributed by Vinay Sajip.)

@node lzma,math<9>,logging<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 lzma}@anchor{102d}
@subsubsection lzma


The @ref{102e,,LZMADecompressor.decompress()}
method now accepts an optional `max_length' argument to limit the maximum
size of decompressed data.
(Contributed by Martin Panter in bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}.)

@node math<9>,multiprocessing<7>,lzma,改良されたモジュール<9>
@anchor{whatsnew/3 5 math}@anchor{102f}
@subsubsection math


@ref{92,,math} モジュールに定数 @ref{e7e,,inf} および @ref{873,,nan} が追加されました。
(Contributed by Mark Dickinson in bpo-23185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23185}.)

新たな関数 @ref{fb0,,isclose()} は近似的に等しいことを調べる方法を提供します。
(Contributed by Chris Barker and Tal Einat in bpo-24270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24270}.)

A new @ref{b0c,,gcd()} function has been added.  The @code{fractions.gcd()}
function is now deprecated. (Contributed by Mark Dickinson and Serhiy
Storchaka in bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486}.)

@node multiprocessing<7>,operator<3>,math<9>,改良されたモジュール<9>
@anchor{whatsnew/3 5 multiprocessing}@anchor{1030}
@subsubsection multiprocessing


@ref{1031,,sharedctypes.synchronized()} オブジェクトが @ref{1e1,,コンテキストマネージャ} プロトコルをサポートするようになりました。 (Contributed by Charles-François Natali in bpo-21565@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21565}.)

@node operator<3>,os<11>,multiprocessing<7>,改良されたモジュール<9>
@anchor{whatsnew/3 5 operator}@anchor{1032}
@subsubsection operator


@ref{1033,,attrgetter()}, @ref{c57,,itemgetter()},
and @ref{1034,,methodcaller()} objects now support pickling.
(Contributed by Josh Rosenberg and Serhiy Storchaka in bpo-22955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22955}.)

行列乗算を行う @ref{1035,,matmul()} 関数と @ref{1036,,imatmul()} 関数が新しく追加されました。
(Contributed by Benjamin Peterson in bpo-21176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21176}.)

@node os<11>,pathlib<13>,operator<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 os}@anchor{1037}
@subsubsection os


The new @ref{c54,,scandir()} function returning an iterator of
@ref{6c3,,DirEntry} objects has been added.  If possible, @ref{c54,,scandir()}
extracts file attributes while scanning a directory, removing the need to
perform subsequent system calls to determine file type or attributes, which may
significantly improve performance.  (Contributed by Ben Hoyt with the help
of Victor Stinner in bpo-22524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22524}.)

Windows において、新たに @ref{1038,,stat_result.st_file_attributes} 属性が利用可能です。これは Windows API の @code{GetFileInformationByHandle()} から返る @code{BY_HANDLE_FILE_INFORMATION} 構造体のメンバ @code{dwFileAttributes} に対応します。 (Contributed by Ben Hoyt in bpo-21719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21719}.)

@ref{746,,urandom()} 関数が、Linux 3.17 以降ではシステムコール @code{getrandom()} を、OpenBSD 5.6 以降ではシステムコール @code{getentropy()} を使うようになりました。これは @code{/dev/urandom} を使う必要性をなくし、潜在的には起こり得たファイル記述子を使い果たすことによる失敗を避けることに繋がります。 (Contributed by Victor Stinner in bpo-22181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22181}.)

New @ref{1039,,get_blocking()} and @ref{103a,,set_blocking()} functions allow
getting and setting a file descriptor's blocking mode (@ref{103b,,O_NONBLOCK}.)
(Contributed by Victor Stinner in bpo-22054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22054}.)

@ref{103c,,truncate()} と @ref{f8f,,ftruncate()} が Windows でサポートされるようになりました。 (Contributed by Steve Dower in bpo-23668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23668}.)

There is a new @ref{103d,,os.path.commonpath()} function returning the longest
common sub-path of each passed pathname.  Unlike the
@ref{103e,,os.path.commonprefix()} function, it always returns a valid
path:

@example
>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'
@end example

(Contributed by Rafik Draoui and Serhiy Storchaka in bpo-10395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10395}.)

@node pathlib<13>,pickle<4>,os<11>,改良されたモジュール<9>
@anchor{whatsnew/3 5 pathlib}@anchor{103f}
@subsubsection pathlib


The new @ref{1040,,Path.samefile()} method can be used
to check whether the path points to the same file as another path, which can
be either another @ref{266,,Path} object, or a string:

@example
>>> import pathlib
>>> p1 = pathlib.Path('/etc/hosts')
>>> p2 = pathlib.Path('/etc/../etc/hosts')
>>> p1.samefile(p2)
True
@end example

(Contributed by Vajrasky Kok and Antoine Pitrou in bpo-19775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19775}.)

The @ref{1041,,Path.mkdir()} method now accepts a new optional
`exist_ok' argument to match @code{mkdir -p} and @ref{52c,,os.makedirs()}
functionality.  (Contributed by Berker Peksag in bpo-21539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21539}.)

There is a new @ref{1042,,Path.expanduser()} method to
expand @code{~} and @code{~user} prefixes.  (Contributed by Serhiy Storchaka and
Claudiu Popa in bpo-19776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19776}.)

A new @ref{1043,,Path.home()} class method can be used to get
a @ref{266,,Path} instance representing the user’s home
directory.
(Contributed by Victor Salgado and Mayank Tripathi in bpo-19777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19777}.)

New @ref{1044,,Path.write_text()},
@ref{1045,,Path.read_text()},
@ref{1046,,Path.write_bytes()},
@ref{2df,,Path.read_bytes()} methods to simplify
read/write operations on files.

The following code snippet will create or rewrite existing file
@code{~/spam42}:

@example
>>> import pathlib
>>> p = pathlib.Path('~/spam42')
>>> p.expanduser().write_text('ham')
3
@end example

(Contributed by Christopher Welborn in bpo-20218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20218}.)

@node pickle<4>,poplib<2>,pathlib<13>,改良されたモジュール<9>
@anchor{whatsnew/3 5 pickle}@anchor{1047}
@subsubsection pickle


Nested objects, such as unbound methods or nested classes, can now be pickled
using @ref{27b,,pickle protocols} older than protocol version 4.
Protocol version 4 already supports these cases.  (Contributed by Serhiy
Storchaka in bpo-23611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23611}.)

@node poplib<2>,re<8>,pickle<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 poplib}@anchor{1048}
@subsubsection poplib


A new @ref{1049,,POP3.utf8()} command enables 
@geindex RFC; RFC 6856
RFC 6856@footnote{https://datatracker.ietf.org/doc/html/rfc6856.html}
(Internationalized Email) support, if a POP server supports it.
(Contributed by Milan OberKirch in bpo-21804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21804}.)

@node re<8>,readline<2>,poplib<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 re}@anchor{104a}
@subsubsection re


References and conditional references to groups with fixed length are now
allowed in lookbehind assertions:

@example
>>> import re
>>> pat = re.compile(r'(a|b).(?<=\1)c')
>>> pat.match('aac')
<_sre.SRE_Match object; span=(0, 3), match='aac'>
>>> pat.match('bbc')
<_sre.SRE_Match object; span=(0, 3), match='bbc'>
@end example

(Contributed by Serhiy Storchaka in bpo-9179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9179}.)

The number of capturing groups in regular expressions is no longer limited to
100.  (Contributed by Serhiy Storchaka in bpo-22437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22437}.)

The @ref{5a3,,sub()} and @ref{5a4,,subn()} functions now replace unmatched
groups with empty strings instead of raising an exception.
(Contributed by Serhiy Storchaka in bpo-1519638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1519638}.)

The @ref{546,,re.error} exceptions have new attributes,
@ref{104b,,msg}, @ref{104c,,pattern},
@ref{104d,,pos}, @ref{104e,,lineno},
and @ref{104f,,colno}, that provide better context
information about the error:

@example
>>> re.compile("""
...     (?x)
...     .++
... """)
Traceback (most recent call last):
   ...
sre_constants.error: multiple repeat at position 16 (line 3, column 7)
@end example

(Contributed by Serhiy Storchaka in bpo-22578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22578}.)

@node readline<2>,selectors,re<8>,改良されたモジュール<9>
@anchor{whatsnew/3 5 readline}@anchor{1050}
@subsubsection readline


A new @ref{1051,,append_history_file()} function can be used to append
the specified number of trailing elements in history to the given file.
(Contributed by Bruno Cauet in bpo-22940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22940}.)

@node selectors,shutil<5>,readline<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 selectors}@anchor{1052}
@subsubsection selectors


The new @ref{dd2,,DevpollSelector} supports efficient
@code{/dev/poll} polling on Solaris.
(Contributed by Giampaolo Rodola' in bpo-18931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18931}.)

@node shutil<5>,signal<3>,selectors,改良されたモジュール<9>
@anchor{whatsnew/3 5 shutil}@anchor{1053}
@subsubsection shutil


The @ref{c51,,move()} function now accepts a `copy_function' argument,
allowing, for example, the @ref{c4f,,copy()} function to be used instead of
the default @ref{c50,,copy2()} if there is a need to ignore file metadata
when moving.
(Contributed by Claudiu Popa in bpo-19840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19840}.)

The @ref{6da,,make_archive()} function now supports the `xztar' format.
(Contributed by Serhiy Storchaka in bpo-5411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5411}.)

@node signal<3>,smtpd<2>,shutil<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 signal}@anchor{1054}
@subsubsection signal


Windows において、 @ref{d67,,set_wakeup_fd()} 関数がソケットハンドルもサポートするようになりました。  (Contributed by Victor Stinner in bpo-22018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22018}.)

Various @code{SIG*} constants in the @ref{cb,,signal} module have been converted into
@ref{5a,,Enums}.  This allows meaningful names to be printed
during debugging, instead of integer "magic numbers".
(Contributed by Giampaolo Rodola' in bpo-21076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21076}.)

@node smtpd<2>,smtplib<2>,signal<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 smtpd}@anchor{1055}
@subsubsection smtpd


Both the @code{SMTPServer} and @code{SMTPChannel} classes now
accept a `decode_data' keyword argument to determine if the @code{DATA} portion of
the SMTP transaction is decoded using the @code{"utf-8"} codec or is instead
provided to the
@code{SMTPServer.process_message()}
method as a byte string.  The default is @code{True} for backward compatibility
reasons, but will change to @code{False} in Python 3.6.  If `decode_data' is set
to @code{False}, the @code{process_message} method must be prepared to accept keyword
arguments.
(Contributed by Maciej Szulik in bpo-19662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19662}.)

The @code{SMTPServer} class now advertises the @code{8BITMIME} extension
(
@geindex RFC; RFC 6152
RFC 6152@footnote{https://datatracker.ietf.org/doc/html/rfc6152.html}) if `decode_data' has been set @code{True}.  If the client
specifies @code{BODY=8BITMIME} on the @code{MAIL} command, it is passed to
@code{SMTPServer.process_message()}
via the `mail_options' keyword.
(Contributed by Milan Oberkirch and R.  David Murray in bpo-21795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21795}.)

The @code{SMTPServer} class now also supports the @code{SMTPUTF8}
extension (
@geindex RFC; RFC 6531
RFC 6531@footnote{https://datatracker.ietf.org/doc/html/rfc6531.html}: Internationalized Email).  If the client specified
@code{SMTPUTF8 BODY=8BITMIME} on the @code{MAIL} command, they are passed to
@code{SMTPServer.process_message()}
via the `mail_options' keyword.  It is the responsibility of the
@code{process_message} method to correctly handle the @code{SMTPUTF8} data.
(Contributed by Milan Oberkirch in bpo-21725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21725}.)

It is now possible to provide, directly or via name resolution, IPv6
addresses in the @code{SMTPServer} constructor, and have it
successfully connect.  (Contributed by Milan Oberkirch in bpo-14758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14758}.)

@node smtplib<2>,sndhdr,smtpd<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 smtplib}@anchor{1056}
@subsubsection smtplib


A new @ref{1057,,SMTP.auth()} method provides a convenient way to
implement custom authentication mechanisms. (Contributed by Milan
Oberkirch in bpo-15014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15014}.)

The @ref{1058,,SMTP.set_debuglevel()} method now
accepts an additional debuglevel (2), which enables timestamps in debug
messages. (Contributed by Gavin Chappell and Maciej Szulik in bpo-16914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16914}.)

Both the @ref{1059,,SMTP.sendmail()} and
@ref{105a,,SMTP.send_message()} methods now
support 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://datatracker.ietf.org/doc/html/rfc6531.html} (SMTPUTF8).
(Contributed by Milan Oberkirch and R. David Murray in bpo-22027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22027}.)

@node sndhdr,socket<9>,smtplib<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 sndhdr}@anchor{105b}
@subsubsection sndhdr


The @code{what()} and @code{whathdr()} functions  now return
a @ref{4e0,,namedtuple()}.  (Contributed by Claudiu Popa in
bpo-18615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18615}.)

@node socket<9>,ssl<10>,sndhdr,改良されたモジュール<9>
@anchor{whatsnew/3 5 socket}@anchor{105c}
@subsubsection socket


Functions with timeouts now use a monotonic clock, instead of a system clock.
(Contributed by Victor Stinner in bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}.)

A new @ref{105d,,socket.sendfile()} method allows
sending a file over a socket by using the high-performance @ref{d05,,os.sendfile()}
function on UNIX, resulting in uploads being from 2 to 3 times faster than when
using plain @ref{fa7,,socket.send()}.
(Contributed by Giampaolo Rodola' in bpo-17552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17552}.)

The @ref{fa8,,socket.sendall()} method no longer resets the
socket timeout every time bytes are received or sent.  The socket timeout is
now the maximum total duration to send all data.
(Contributed by Victor Stinner in bpo-23853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23853}.)

The `backlog' argument of the @ref{105e,,socket.listen()}
method is now optional.  By default it is set to
@ref{105f,,SOMAXCONN} or to @code{128}, whichever is less.
(Contributed by Charles-François Natali in bpo-21455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21455}.)

@node ssl<10>,sqlite3<9>,socket<9>,改良されたモジュール<9>
@anchor{whatsnew/3 5 ssl}@anchor{1060}
@subsubsection ssl


@menu
* メモリ BIO サポート:: 
* Application-Layer Protocol Negotiation Support:: 
* その他の変更:: 

@end menu

@node メモリ BIO サポート,Application-Layer Protocol Negotiation Support,,ssl<10>
@anchor{whatsnew/3 5 memory-bio-support}@anchor{1061}@anchor{whatsnew/3 5 whatsnew-sslmemorybio}@anchor{f6c}
@subsubsection メモリ BIO サポート


(Contributed by Geert Jansen in bpo-21965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21965}.)

The new @ref{d7a,,SSLObject} class has been added to provide SSL protocol
support for cases when the network I/O capabilities of @ref{ae7,,SSLSocket}
are not necessary or are suboptimal.  @code{SSLObject} represents
an SSL protocol instance, but does not implement any network I/O methods, and
instead provides a memory buffer interface.  The new @ref{1062,,MemoryBIO}
class can be used to pass data between Python and an SSL protocol instance.

The memory BIO SSL support is primarily intended to be used in frameworks
implementing asynchronous I/O for which @ref{ae7,,SSLSocket}'s readiness
model ("select/poll") is inefficient.

A new @ref{d7b,,SSLContext.wrap_bio()} method can be used
to create a new @code{SSLObject} instance.

@node Application-Layer Protocol Negotiation Support,その他の変更,メモリ BIO サポート,ssl<10>
@anchor{whatsnew/3 5 application-layer-protocol-negotiation-support}@anchor{1063}
@subsubsection Application-Layer Protocol Negotiation Support


(Contributed by Benjamin Peterson in bpo-20188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20188}.)

Where OpenSSL support is present, the @ref{d5,,ssl} module now implements
the `Application-Layer Protocol Negotiation' TLS extension as described
in 
@geindex RFC; RFC 7301
RFC 7301@footnote{https://datatracker.ietf.org/doc/html/rfc7301.html}.

The new @ref{1064,,SSLContext.set_alpn_protocols()}
can be used to specify which protocols a socket should advertise during
the TLS handshake.

The new
@ref{1065,,SSLSocket.selected_alpn_protocol()}
returns the protocol that was selected during the TLS handshake.
The @ref{1066,,HAS_ALPN} flag indicates whether ALPN support is present.

@node その他の変更,,Application-Layer Protocol Negotiation Support,ssl<10>
@anchor{whatsnew/3 5 other-changes}@anchor{1067}
@subsubsection その他の変更


There is a new @ref{1068,,SSLSocket.version()} method to
query the actual protocol version in use.
(Contributed by Antoine Pitrou in bpo-20421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20421}.)

The @ref{ae7,,SSLSocket} class now implements
a @code{SSLSocket.sendfile()} method.
(Contributed by Giampaolo Rodola' in bpo-17552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17552}.)

The @code{SSLSocket.send()} method now raises either
the @ref{1069,,ssl.SSLWantReadError} or @ref{106a,,ssl.SSLWantWriteError} exception on a
non-blocking socket if the operation would block. Previously, it would return
@code{0}.  (Contributed by Nikolaus Rath in bpo-20951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20951}.)

The @ref{106b,,cert_time_to_seconds()} function now interprets the input time
as UTC and not as local time, per 
@geindex RFC; RFC 5280
RFC 5280@footnote{https://datatracker.ietf.org/doc/html/rfc5280.html}.  Additionally, the return
value is always an @ref{19b,,int}. (Contributed by Akira Li in bpo-19940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19940}.)

New @code{SSLObject.shared_ciphers()} and
@ref{106c,,SSLSocket.shared_ciphers()} methods return
the list of ciphers sent by the client during the handshake.
(Contributed by Benjamin Peterson in bpo-23186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23186}.)

The @ref{106d,,SSLSocket.do_handshake()},
@ref{106e,,SSLSocket.read()},
@code{SSLSocket.shutdown()}, and
@ref{106f,,SSLSocket.write()} methods of the @ref{ae7,,SSLSocket}
class no longer reset the socket timeout every time bytes are received or sent.
The socket timeout is now the maximum total duration of the method.
(Contributed by Victor Stinner in bpo-23853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23853}.)

The @code{match_hostname()} function now supports matching of IP addresses.
(Contributed by Antoine Pitrou in bpo-23239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23239}.)

@node sqlite3<9>,subprocess<4>,ssl<10>,改良されたモジュール<9>
@anchor{whatsnew/3 5 sqlite3}@anchor{1070}
@subsubsection sqlite3


The @ref{1071,,Row} class now fully supports the sequence protocol,
in particular @ref{a65,,reversed()} iteration and slice indexing.
(Contributed by Claudiu Popa in bpo-10203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10203}; by Lucas Sinclair,
Jessica McKellar, and  Serhiy Storchaka in bpo-13583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13583}.)

@node subprocess<4>,sys<11>,sqlite3<9>,改良されたモジュール<9>
@anchor{whatsnew/3 5 subprocess}@anchor{1072}@anchor{whatsnew/3 5 whatsnew-subprocess}@anchor{f6f}
@subsubsection subprocess


新たに @ref{d7f,,run()} 関数が追加されました。
これは指定されたコマンドを実行し @ref{1073,,CompletedProcess} オブジェクトを返します。
オブジェクトは終了したプロセスを記述します。
新たな API はより一貫的で、古いバージョンとの互換性を必要としない Python コードでサブプロセスを起動するのに推奨される方法です。
(Contributed by Thomas Kluyver in bpo-23342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23342}.)

例:

@example
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
@end example

@node sys<11>,sysconfig<3>,subprocess<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 sys}@anchor{1074}
@subsubsection sys


A new @code{set_coroutine_wrapper()} function allows setting a global
hook that will be called whenever a @ref{6b9,,coroutine object}
is created by an @ref{7ed,,async def} function.  A corresponding
@code{get_coroutine_wrapper()} can be used to obtain a currently set
wrapper.  Both functions are @ref{3d1,,provisional},
and are intended for debugging purposes only.  (Contributed by Yury Selivanov
in bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017}.)

A new @ref{c80,,is_finalizing()} function can be used to check if the Python
interpreter is @ref{479,,shutting down}.
(Contributed by Antoine Pitrou in bpo-22696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22696}.)

@node sysconfig<3>,tarfile<7>,sys<11>,改良されたモジュール<9>
@anchor{whatsnew/3 5 sysconfig}@anchor{1075}
@subsubsection sysconfig


The name of the user scripts directory on Windows now includes the first
two components of the Python version. (Contributed by Paul Moore
in bpo-23437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23437}.)

@node tarfile<7>,threading<7>,sysconfig<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 tarfile}@anchor{1076}
@subsubsection tarfile


@ref{1077,,open()} 関数の `mode' 引数が排他的作成を要求する @code{"x"}  を受け取るようになりました。 (Contributed by Berker Peksag in bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}.)

The @ref{29b,,TarFile.extractall()} and
@ref{29c,,TarFile.extract()} methods now take a keyword
argument `numeric_owner'.  If set to @code{True}, the extracted files and
directories will be owned by the numeric @code{uid} and @code{gid} from the tarfile.
If set to @code{False} (the default, and the behavior in versions prior to 3.5),
they will be owned by the named user and group in the tarfile.
(Contributed by Michael Vogt and Eric Smith in bpo-23193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23193}.)

The @ref{1078,,TarFile.list()} now accepts an optional
`members' keyword argument that can be set to a subset of the list returned
by @ref{1079,,TarFile.getmembers()}.
(Contributed by Serhiy Storchaka in bpo-21549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21549}.)

@node threading<7>,time<7>,tarfile<7>,改良されたモジュール<9>
@anchor{whatsnew/3 5 threading}@anchor{107a}
@subsubsection threading


@ref{8a7,,Lock.acquire()} と @ref{107b,,RLock.acquire()} の両メソッドがタイムアウトの管理に単調時計を使用するようになりました。
(Contributed by Victor Stinner in bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}.)

@node time<7>,timeit<2>,threading<7>,改良されたモジュール<9>
@anchor{whatsnew/3 5 time}@anchor{107c}
@subsubsection time


@ref{55c,,monotonic()} 関数が常に利用出来るようになりました。
(Contributed by Victor Stinner in bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}.)

@node timeit<2>,tkinter<9>,time<7>,改良されたモジュール<9>
@anchor{whatsnew/3 5 timeit}@anchor{107d}
@subsubsection timeit


新たなコマンドラインオプション @code{-u} 又は @code{--unit=@var{U}} を使用してタイマーの出力の単位を指定できます。
サポートされたオプションは @code{usec}, @code{msec},  @code{sec} です。
(Contributed by Julian Gindi in bpo-18983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18983}.)

@ref{107e,,timeit()} 関数に引数 `globals' が追加されました。
これによりコードが実行される名前空間を指定します。
(Contributed by Ben Roberts in bpo-2527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2527}.)

@node tkinter<9>,traceback<5>,timeit<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 tkinter}@anchor{107f}
@subsubsection tkinter


The @code{tkinter._fix} module used for setting up the Tcl/Tk environment
on Windows has been replaced by a private function in the @code{_tkinter}
module which makes no permanent changes to environment variables.
(Contributed by Zachary Ware in bpo-20035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20035}.)

@node traceback<5>,types<6>,tkinter<9>,改良されたモジュール<9>
@anchor{whatsnew/3 5 traceback}@anchor{1080}@anchor{whatsnew/3 5 whatsnew-traceback}@anchor{f70}
@subsubsection traceback


New @ref{1081,,walk_stack()} and @ref{1082,,walk_tb()}
functions to conveniently traverse frame and
@ref{cec,,traceback objects}.
(Contributed by Robert Collins in bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}.)

New lightweight classes: @ref{563,,TracebackException},
@ref{1083,,StackSummary}, and @ref{1084,,FrameSummary}.
(Contributed by Robert Collins in bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}.)

Both the @ref{1085,,print_tb()} and @ref{1086,,print_stack()} functions
now support negative values for the `limit' argument.
(Contributed by Dmitry Kazakov in bpo-22619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22619}.)

@node types<6>,unicodedata<9>,traceback<5>,改良されたモジュール<9>
@anchor{whatsnew/3 5 types}@anchor{1087}
@subsubsection types


新たに @ref{1088,,coroutine()} 関数が追加されました。
@ref{dd9,,ジェネレータ} と @ref{fdb,,ジェネレータ様} オブジェクトを @ref{4c9,,awaitable} に変換します。
(Contributed by Yury Selivanov in bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017}.)

新たに型 @ref{1089,,CoroutineType} が追加されました。
@ref{7ed,,async def} 関数で作られた @ref{6b9,,coroutine} オブジェクトに使われます。 (Contributed by Yury Selivanov in bpo-24400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24400}.)

@node unicodedata<9>,unittest<9>,types<6>,改良されたモジュール<9>
@anchor{whatsnew/3 5 unicodedata}@anchor{108a}
@subsubsection unicodedata


The @ref{10b,,unicodedata} module now uses data from Unicode 8.0.0@footnote{https://unicode.org/versions/Unicode8.0.0/}.

@node unittest<9>,unittest mock<3>,unicodedata<9>,改良されたモジュール<9>
@anchor{whatsnew/3 5 unittest}@anchor{108b}
@subsubsection unittest


The @ref{594,,TestLoader.loadTestsFromModule()}
method now accepts a keyword-only argument `pattern' which is passed to
@code{load_tests} as the third argument.  Found packages are now checked for
@code{load_tests} regardless of whether their path matches `pattern', because it
is impossible for a package name to match the default pattern.
(Contributed by Robert Collins and Barry A. Warsaw in bpo-16662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16662}.)

Unittest discovery errors now are exposed in the
@ref{108c,,TestLoader.errors} attribute of the
@ref{593,,TestLoader} instance.
(Contributed by Robert Collins in bpo-19746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19746}.)

A new command line option @code{--locals} to show local variables in
tracebacks.  (Contributed by Robert Collins in bpo-22936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22936}.)

@node unittest mock<3>,urllib<4>,unittest<9>,改良されたモジュール<9>
@anchor{whatsnew/3 5 unittest-mock}@anchor{108d}
@subsubsection unittest.mock


@ref{c3f,,Mock} クラスは、次の改善が行われました。


@itemize *

@item 
The class constructor has a new `unsafe' parameter, which causes mock
objects to raise @ref{5f0,,AttributeError} on attribute names starting
with @code{"assert"}.
(Contributed by Kushal Das in bpo-21238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21238}.)

@item 
A new @ref{108e,,Mock.assert_not_called()}
method to check if the mock object was called.
(Contributed by Kushal Das in bpo-21262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21262}.)
@end itemize

The @ref{108f,,MagicMock} class now supports
@ref{1090,,__truediv__()}, @ref{1091,,__divmod__()}
and @ref{f79,,__matmul__()} operators.
(Contributed by Johannes Baiter in bpo-20968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20968}, and Håkan Lövdahl
in bpo-23581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23581} and bpo-23568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23568}.)

It is no longer necessary to explicitly pass @code{create=True} to the
@ref{1092,,patch()} function when patching builtin names.
(Contributed by Kushal Das in bpo-17660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17660}.)

@node urllib<4>,wsgiref,unittest mock<3>,改良されたモジュール<9>
@anchor{whatsnew/3 5 urllib}@anchor{1093}
@subsubsection urllib


A new
@ref{1094,,request.HTTPPasswordMgrWithPriorAuth}
class allows HTTP Basic Authentication credentials to be managed so as to
eliminate unnecessary @code{401} response handling, or to unconditionally send
credentials on the first request in order to communicate with servers that
return a @code{404} response instead of a @code{401} if the @code{Authorization} header
is not sent. (Contributed by Matej Cepl in bpo-19494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19494} and Akshit Khurana in
bpo-7159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7159}.)

A new `quote_via' argument for the
@ref{1095,,parse.urlencode()}
function provides a way to control the encoding of query parts if needed.
(Contributed by Samwyse and Arnon Yaari in bpo-13866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13866}.)

The @ref{307,,request.urlopen()} function accepts an
@ref{357,,ssl.SSLContext} object as a `context' argument, which will be used for
the HTTPS connection.  (Contributed by Alex Gaynor in bpo-22366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22366}.)

The @ref{1096,,parse.urljoin()} was updated to use the
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html} semantics for the resolution of relative URLs, rather than
@geindex RFC; RFC 1808
RFC 1808@footnote{https://datatracker.ietf.org/doc/html/rfc1808.html} and 
@geindex RFC; RFC 2396
RFC 2396@footnote{https://datatracker.ietf.org/doc/html/rfc2396.html}.
(Contributed by Demian Brecht and Senthil Kumaran in bpo-22118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22118}.)

@node wsgiref,xmlrpc<2>,urllib<4>,改良されたモジュール<9>
@anchor{whatsnew/3 5 wsgiref}@anchor{1097}
@subsubsection wsgiref


The `headers' argument of the @ref{1098,,headers.Headers}
class constructor is now optional.
(Contributed by Pablo Torres Navarrete and SilentGhost in bpo-5800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5800}.)

@node xmlrpc<2>,xml sax,wsgiref,改良されたモジュール<9>
@anchor{whatsnew/3 5 xmlrpc}@anchor{1099}
@subsubsection xmlrpc


@ref{c4c,,client.ServerProxy} クラスが @ref{1e1,,コンテキストマネージャ} プロトコルをサポートするようになりました。 (Contributed by Claudiu Popa in bpo-20627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20627}.)

@ref{c4c,,client.ServerProxy} コンストラクタは任意の @ref{357,,ssl.SSLContext} インスタンスを受け取るようになりました。 (Contributed by Alex Gaynor in bpo-22960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22960}.)

@node xml sax,zipfile<5>,xmlrpc<2>,改良されたモジュール<9>
@anchor{whatsnew/3 5 xml-sax}@anchor{109a}
@subsubsection xml.sax


SAX パーサは @ref{109b,,xmlreader.InputSource} オブジェクトの文字ストリームをサポートしました。
(Contributed by Serhiy Storchaka in bpo-2175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2175}.)

@ref{109c,,parseString()} が @ref{169,,str} インスタンスを受け取るようになりました。
(Contributed by Serhiy Storchaka in bpo-10590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10590}.)

@node zipfile<5>,,xml sax,改良されたモジュール<9>
@anchor{whatsnew/3 5 zipfile}@anchor{109d}
@subsubsection zipfile


ZIP output can now be written to unseekable streams.
(Contributed by Serhiy Storchaka in bpo-23252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23252}.)

@ref{65d,,ZipFile.open()} メソッドの `mode' 引数が排他的作成を要求する @code{"x"}  を受け取るようになりました。 (Contributed by Serhiy Storchaka in bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}.)

@node その他のモジュールレベルの変更,最適化<10>,改良されたモジュール<9>,What's New In Python 3 5
@anchor{whatsnew/3 5 other-module-level-changes}@anchor{109e}
@subsection その他のモジュールレベルの変更


Many functions in the @ref{94,,mmap}, @code{ossaudiodev}, @ref{d1,,socket},
@ref{d5,,ssl}, and @ref{1c,,codecs} modules now accept writable
@ref{193,,bytes-like objects}.
(Contributed by Serhiy Storchaka in bpo-23001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23001}.)

@node 最適化<10>,ビルドならびに C API の変更<3>,その他のモジュールレベルの変更,What's New In Python 3 5
@anchor{whatsnew/3 5 optimizations}@anchor{109f}
@subsection 最適化


The @ref{6d0,,os.walk()} function has been sped up by 3 to 5 times on POSIX systems,
and by 7 to 20 times on Windows.  This was done using the new @ref{c54,,os.scandir()}
function, which exposes file information from the underlying @code{readdir} or
@code{FindFirstFile}/@code{FindNextFile} system calls.  (Contributed by
Ben Hoyt with help from Victor Stinner in bpo-23605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23605}.)

Construction of @code{bytes(int)} (filled by zero bytes) is faster and uses less
memory for large objects. @code{calloc()} is used instead of @code{malloc()} to
allocate memory for these objects.
(Contributed by Victor Stinner in bpo-21233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21233}.)

Some operations on @ref{84,,ipaddress} @ref{50e,,IPv4Network} and
@ref{50f,,IPv6Network} have been massively sped up, such as
@ref{10a0,,subnets()}, @ref{10a1,,supernet()},
@ref{10a2,,summarize_address_range()}, @ref{10a3,,collapse_addresses()}.
The speed up can range from 3 to 15 times.
(Contributed by Antoine Pitrou, Michel Albert, and Markus in
bpo-21486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21486}, bpo-21487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21487}, bpo-20826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20826}, bpo-23266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23266}.)

Pickling of @ref{84,,ipaddress} objects was optimized to produce significantly
smaller output.  (Contributed by Serhiy Storchaka in bpo-23133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23133}.)

@ref{10a4,,io.BytesIO} の多くの操作が 50% から 100% 速くなりました。 (Contributed by Serhiy Storchaka in bpo-15381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15381} and David Wilson in bpo-22003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22003}.)

The @ref{10a5,,marshal.dumps()} function is now faster: 65--85% with versions 3
and 4, 20--25% with versions 0 to 2 on typical data, and up to 5 times in
best cases.
(Contributed by Serhiy Storchaka in bpo-20416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20416} and bpo-23344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23344}.)

UTF-32 エンコーダが 3 から 7 倍速くなりました。 (Contributed by Serhiy Storchaka in bpo-15027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15027}.)

正規表現のパースが最高で 10% 速くなりました。 (Contributed by Serhiy Storchaka in bpo-19380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19380}.)

The @ref{f41,,json.dumps()} function was optimized to run with
@code{ensure_ascii=False} as fast as with @code{ensure_ascii=True}.
(Contributed by Naoki Inada in bpo-23206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23206}.)

The @ref{10a6,,PyObject_IsInstance()} and @ref{10a7,,PyObject_IsSubclass()}
functions have been sped up in the common case that the second argument
has @ref{f44,,type} as its metaclass.
(Contributed Georg Brandl by in bpo-22540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22540}.)

メソッドのキャッシュが少し改良されました。ベンチマークによっては性能が最高で 5% 向上しました。 (Contributed by Antoine Pitrou in bpo-22847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22847}.)

@ref{bd,,random} モジュールのオブジェクトのメモリ使用量が 64-bit ビルドで 50% 減少しました。 (Contributed by Serhiy Storchaka in bpo-23488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23488}.)

@ref{4b3,,property()} ゲッタの呼び出しが最高で 25% 速くなりました。 (Contributed by Joe Jevnik in bpo-23910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23910}.)

@ref{213,,fractions.Fraction} のインスタンス化が最高で 30% 速くなりました。 (Contributed by Stefan Behnel in bpo-22464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22464}.)

String methods @ref{10a8,,find()}, @ref{10a9,,rfind()}, @ref{10aa,,split()},
@ref{10ab,,partition()} and the @ref{34b,,in} string operator are now significantly
faster for searching 1-character substrings.
(Contributed by Serhiy Storchaka in bpo-23573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23573}.)

@node ビルドならびに C API の変更<3>,非推奨<11>,最適化<10>,What's New In Python 3 5
@anchor{whatsnew/3 5 build-and-c-api-changes}@anchor{10ac}
@subsection ビルドならびに C API の変更


新たな @code{calloc} 関数が追加されました:


@itemize *

@item 
@ref{632,,PyMem_RawCalloc()},

@item 
@ref{10ad,,PyMem_Calloc()},

@item 
@ref{10ae,,PyObject_Calloc()}.
@end itemize

(Contributed by Victor Stinner in bpo-21233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21233}.)

新たなエンコーディング/デコーディングヘルパ関数:


@itemize *

@item 
@ref{dc0,,Py_DecodeLocale()} (@code{_Py_char2wchar()} の代わり),

@item 
@ref{dc1,,Py_EncodeLocale()} (@code{_Py_wchar2char()} の代わり).
@end itemize

(Contributed by Victor Stinner in bpo-18395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18395}.)

A new @ref{10af,,PyCodec_NameReplaceErrors()} function to replace the unicode
encode error with @code{\N@{...@}} escapes.
(Contributed by Serhiy Storchaka in bpo-19676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19676}.)

A new @ref{10b0,,PyErr_FormatV()} function similar to @ref{10b1,,PyErr_Format()},
but accepts a @code{va_list} argument.
(Contributed by Antoine Pitrou in bpo-18711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18711}.)

A new @ref{10b2,,PyExc_RecursionError} exception.
(Contributed by Georg Brandl in bpo-19235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19235}.)

New @ref{10b3,,PyModule_FromDefAndSpec()}, @ref{10b4,,PyModule_FromDefAndSpec2()},
and @ref{10b5,,PyModule_ExecDef()} functions introduced by 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} --
multi-phase extension module initialization.
(Contributed by Petr Viktorin in bpo-24268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24268}.)

New @ref{10b6,,PyNumber_MatrixMultiply()} and
@ref{10b7,,PyNumber_InPlaceMatrixMultiply()} functions to perform matrix
multiplication.
(Contributed by Benjamin Peterson in bpo-21176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21176}.  See also 
@geindex Python Enhancement Proposals; PEP 465
PEP 465@footnote{https://peps.python.org/pep-0465/}
for details.)

The @ref{c9d,,PyTypeObject.tp_finalize} slot is now part of the stable ABI.

Windows builds now require Microsoft Visual C++ 14.0, which
is available as part of Visual Studio 2015@footnote{https://visualstudio.microsoft.com/en/vs/older-downloads/#visual-studio-2015-and-other-products}.

いくつかのプラットフォームにおいて、拡張モジュールのファイル名にプラットフォームについての情報をタグとして含むようになりました (タグはオプショナルであり、CPython は、タグが含まれていて実行しようとしているプラットフォームとミスマッチな場合にその拡張をロードしようとしない一方で、拡張をそれが含まれていなくてもインポートします):


@itemize *

@item 
Linux では拡張モジュールのファイル名は @code{.cpython-<major><minor>m-<architecture>-<os>.pyd} で終わります:


@itemize *

@item 
@code{<major>} は Python バージョンのメジャー番号です。Python 3.5 では @code{3} です。

@item 
@code{<minor>} は Python バージョンのマイナー番号です。Python 3.5 では @code{5} です。

@item 
@code{<architecture>} は拡張モジュールがどのハードウェアアーキテクチャ向けに動作するようビルドされたのかを表します。32-bit Intel プラットフォーム向けの @code{i386} か 64-bit Intel (及び AMD) プラットフォーム向けの @code{x86_64} がもっとも一般的です。

@item 
@code{<os>} は原則として @code{linux-gnu} ですが、64-bit プラットフォームにおいて 32-bit ABI で動作するようビルドされた拡張モジュールの場合は @code{linux-gnu32} になります (この場合 @code{<architecture>} は @code{x86_64} となるでしょう)。
@end itemize

@item 
Windows では拡張モジュールのファイル名は @code{<debug>.cp<major><minor>-<platform>.pyd} で終わります:


@itemize *

@item 
@code{<major>} は Python バージョンのメジャー番号です。Python 3.5 では @code{3} です。

@item 
@code{<minor>} は Python バージョンのマイナー番号です。Python 3.5 では @code{5} です。

@item 
@code{<platform>} は拡張モジュールがどのプラットフォーム向けにビルドされたものなのかを表し、 Win32 用の @code{win32} , Win64 用の @code{win_amd64} , Windows Itanium 64 用の @code{win_ia64} , Windows on ARM 用の @code{win_arm} のいずれかです。

@item 
デバッグモードでビルドされた場合は @code{<debug>} は @code{_d} となり、それ以外の場合はブランクです。
@end itemize

@item 
OS X プラットフォームでは拡張モジュールのファイル名は @code{-darwin.so} で終わります。

@item 
他のすべてのプラットフォームでは、拡張モジュールのファイル名は Python 3.4 でのものと同じです。
@end itemize

@node 非推奨<11>,削除<11>,ビルドならびに C API の変更<3>,What's New In Python 3 5
@anchor{whatsnew/3 5 deprecated}@anchor{10b8}
@subsection 非推奨


@menu
* 新たなキーワード: 新たなキーワード<2>. 
* 非推奨の Python の挙動: 非推奨の Python の挙動<2>. 
* サポートされないオペレーティングシステム:: 
* 非推奨の Python モジュール、関数、メソッド: 非推奨の Python モジュール、関数、メソッド<3>. 

@end menu

@node 新たなキーワード<2>,非推奨の Python の挙動<2>,,非推奨<11>
@anchor{whatsnew/3 5 new-keywords}@anchor{10b9}
@subsubsection 新たなキーワード


@code{async} および @code{await} を変数、クラス、関数、ならびにモジュールの名前に使用することは推奨されません。
それらは Python 3.5 で 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} により導入され、Python 3.7 で正式にキーワードになります。

@node 非推奨の Python の挙動<2>,サポートされないオペレーティングシステム,新たなキーワード<2>,非推奨<11>
@anchor{whatsnew/3 5 deprecated-python-behavior}@anchor{10ba}
@subsubsection 非推奨の Python の挙動


ジェネレータ内で @ref{df5,,StopIteration} 例外を送出すると現在は静かな @ref{ac5,,PendingDeprecationWarning} が発生します。
これは、Python 3.6 では静かでない非推奨の警告となり、Python 3.7 では @ref{244,,RuntimeError} を起こします。
詳細は @ref{f1b,,PEP 479; Change StopIteration handling inside generators} を参照してください。

@node サポートされないオペレーティングシステム,非推奨の Python モジュール、関数、メソッド<3>,非推奨の Python の挙動<2>,非推奨<11>
@anchor{whatsnew/3 5 unsupported-operating-systems}@anchor{10bb}
@subsubsection サポートされないオペレーティングシステム


Windows XP は Microsoft によって既にサポートされていません。このため 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} により、CPython 3.5 ではこの OS をもはや公式にはサポートしません。

@node 非推奨の Python モジュール、関数、メソッド<3>,,サポートされないオペレーティングシステム,非推奨<11>
@anchor{whatsnew/3 5 deprecated-python-modules-functions-and-methods}@anchor{10bc}
@subsubsection 非推奨の Python モジュール、関数、メソッド


The @code{formatter} module has now graduated to full deprecation and is still
slated for removal in Python 3.6.

The @code{asyncio.async()} function is deprecated in favor of
@ref{e71,,ensure_future()}.

The @code{smtpd} module has in the past always decoded the DATA portion of
email messages using the @code{utf-8} codec.  This can now be controlled by the
new `decode_data' keyword to @code{SMTPServer}.  The default value is
@code{True}, but this default is deprecated.  Specify the `decode_data' keyword
with an appropriate value to avoid the deprecation warning.

@ref{dfe,,http.cookies.Morsel} オブジェクトの @ref{dfb,,key}, @ref{dfc,,value}, @ref{dfd,,coded_value} に対して直接代入することは非推奨です。 @ref{dff,,set()} メソッドを使うようにしてください。また、 @ref{dff,,set()} のドキュメントされていなかった `LegalChars' パラメータは非推奨となり、無視されます。

@ref{10bd,,string.Formatter} クラスの @ref{dfa,,format()} メソッドに対し、キーワード引数 `format_string' としてフォーマット文字列を渡すことは非推奨となりました。 (Contributed by Serhiy Storchaka in bpo-23671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23671}.)

The @code{platform.dist()} and @code{platform.linux_distribution()} functions
are now deprecated.  Linux distributions use too many different ways of
describing themselves, so the functionality is left to a package.
(Contributed by Vajrasky Kok and Berker Peksag in bpo-1322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1322}.)

@ref{4e3,,inspect.Signature} の、以前からドキュメントされていなかったメソッド @code{from_function} と @code{from_builtin} は非推奨です。新しい @ref{942,,Signature.from_callable()} を代わりに使ってください。 (Contributed by Yury Selivanov in bpo-24248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24248}.)

The @code{inspect.getargspec()} function is deprecated and scheduled to be
removed in Python 3.6.  (See bpo-20438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20438} for details.)

The @ref{82,,inspect} @ref{941,,getfullargspec()},
@ref{10be,,getcallargs()}, and @code{formatargspec()} functions are
deprecated in favor of the @ref{22f,,inspect.signature()} API. (Contributed by Yury
Selivanov in bpo-20438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20438}.)

@ref{10bf,,getargvalues()} and @ref{10c0,,formatargvalues()} functions
were inadvertently marked as deprecated with the release of Python 3.5.0.

str のパターンとともに @ref{d63,,re.LOCALE} や @ref{83e,,re.ASCII} フラグを使用することは非推奨となりました。  (Contributed by Serhiy Storchaka in bpo-22407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22407}.)

@code{'\'} と ASCII 文字からなる認識出来ない特殊シーケンスが正規表現内と置き換えパターン内で使われた場合に、非推奨警告を出すようになりました。Python 3.6 では禁止されるようになります。 (Contributed by Serhiy Storchaka in bpo-23622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23622}.)

@ref{594,,unittest.TestLoader.loadTestsFromModule()} メソッドのドキュメントされておらず非公式の `use_load_tests' デフォルト引数は非推奨となり、無視されます。 (Contributed by Robert Collins and Barry A. Warsaw in bpo-16662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16662}.)

@node 削除<11>,Python 3 5 への移植,非推奨<11>,What's New In Python 3 5
@anchor{whatsnew/3 5 removed}@anchor{10c1}
@subsection 削除


@menu
* API と機能の削除: API と機能の削除<4>. 

@end menu

@node API と機能の削除<4>,,,削除<11>
@anchor{whatsnew/3 5 api-and-feature-removals}@anchor{10c2}
@subsubsection API と機能の削除


時代遅れとなり、以前に既に非推奨となった以下の API と機能が削除されました:


@itemize *

@item 
email パッケージの @code{__version__} 属性は削除されました。email パッケージが標準ライブラリとは別々にリリースされていたのは遥か昔の話であり、ここのところ何回かのリリースにいたっては @code{__version__} 文字列が更新されていませんでした。

@item 
3.4 で非推奨となっていた @ref{62,,ftplib} モジュール内の内部クラス @code{Netrc} が削除されました。 (Contributed by Matt Chaput in bpo-6623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6623}.)

@item 
@code{.pyo} ファイルのコンセプトは削除されました。

@item 
暫定 @ref{b,,asyncio} モジュールで 3.4.4 で非推奨となった JoinableQueue は削除されました。 (Contributed by A. Jesse Jiryu Davis in bpo-23464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23464}.)
@end itemize

@node Python 3 5 への移植,Notable changes in Python 3 5 4,削除<11>,What's New In Python 3 5
@anchor{whatsnew/3 5 porting-to-python-3-5}@anchor{10c3}
@subsection Python 3.5 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python の挙動の変更: Python の挙動の変更<3>. 
* Python API の変更: Python API の変更<10>. 
* C API の変更: C API の変更<14>. 

@end menu

@node Python の挙動の変更<3>,Python API の変更<10>,,Python 3 5 への移植
@anchor{whatsnew/3 5 changes-in-python-behavior}@anchor{10c4}
@subsubsection Python の挙動の変更



@itemize *

@item 
以前のバージョンの Python で、誤って以下の構文を許容してしまっていました:

@example
f(1 for x in [1], *args)
f(1 for x in [1], **kwargs)
@end example

Python 3.5 は正しく @ref{18e,,SyntaxError} を投げます。ジェネレータ式は関数への唯一の引数でない場合には、括弧で囲まなければならないのです。(---訳注: 一応。3.5 以前も @code{ff(str(i) for i in range(5), "5")} は SyntaxError です。上の例の通り @code{gg(str(i) for i in range(5), *["1", "2"])} や @code{hh(str(i) for i in range(5), **@{"k1": "1", "k2": "2"@})} が SytaxError ではなかった、という話です。---)
@end itemize

@node Python API の変更<10>,C API の変更<14>,Python の挙動の変更<3>,Python 3 5 への移植
@anchor{whatsnew/3 5 changes-in-the-python-api}@anchor{10c5}
@subsubsection Python API の変更



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/}: Python シグナルハンドラが例外を送出しなければ、システムコールがシグナルに中断された場合に、 @ref{f88,,InterruptedError} を送出せずにシステムコールを再試行するようになりました。

@item 
Python 3.5 以前は、 @ref{1fb,,time} オブジェクトは UTC で深夜を表すときに偽とみなされていました。
この挙動は分かりにくく、エラーの元となると考えられ、Python 3.5 で削除されました。
全詳細については bpo-13936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13936} を参照してください。

@item 
The @code{ssl.SSLSocket.send()} method now raises either
@ref{1069,,ssl.SSLWantReadError} or @ref{106a,,ssl.SSLWantWriteError}
on a non-blocking socket if the operation would block.  Previously,
it would return @code{0}.  (Contributed by Nikolaus Rath in bpo-20951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20951}.)

@item 
ジェネレータの @code{__name__} 属性の値として、以前は code オブジェクトの名前から取っていましたが、関数名からセットされるようになりました。code の方が所望の場合は @code{gen.gi_code.co_name} から取得してください。ジェネレータは新たに @code{__qualname__} 属性も持つようになりました。これはジェネレータの正規名であり、ジェネレータの表現をする際 (@code{repr(gen)}) にこれを用いるようになりました。 (Contributed by Victor Stinner in bpo-21205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21205}.)

@item 
The deprecated "strict" mode and argument of @ref{a77,,HTMLParser},
@code{HTMLParser.error()}, and the @code{HTMLParserError} exception have been
removed.  (Contributed by Ezio Melotti in bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}.)
The `convert_charrefs' argument of @ref{a77,,HTMLParser} is
now @code{True} by default.  (Contributed by Berker Peksag in bpo-21047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21047}.)

@item 
API の公式な部分とは言えないものの、移植性への考慮のために (つまりテストの修正) に、エラーメッセージの変更に注意を払っておいてください。かつて "'sometype' does not support the buffer protocol" の形だったものが、いまでは "a @ref{193,,bytes-like object} is required, not 'sometype'" の形になっています。 (Contributed by Ezio Melotti in bpo-16518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16518}.)

@item 
既に存在していないディレクトリをカレントディレクトリとして指していた場合に、 @ref{10c6,,find_spec()} は以前は @ref{264,,FileNotFoundError} 例外を送出していましたが、そうではなく @code{None} を返却するようになりました。この際 @ref{7fa,,sys.path_importer_cache} に @code{None} を `キャッシュはしません' 。これは典型的なケースとは違います(訳注: msg231477@footnote{https://bugs.python.org/issue22834#msg231477})。 (bpo-22834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22834})

@item 
@ref{73,,http.client} モジュールと @ref{76,,http.server} モジュールに散らばっていた HTTP ステータスコードと対応するメッセージを、共通の @ref{afc,,HTTPStatus} enum としてまとめ直しました。@ref{73,,http.client} 、 @ref{76,,http.server} にあったもとの値も後方互換性のために残してあります。 (Contributed by Demian Brecht in bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}.)

@item 
When an import loader defines @ref{a6a,,exec_module()}
it is now expected to also define
@ref{eac,,create_module()} (raises a
@ref{1a3,,DeprecationWarning} now, will be an error in Python 3.6). If the loader
inherits from @ref{10c7,,importlib.abc.Loader} then there is nothing to do, else
simply define @ref{eac,,create_module()} to return
@code{None}.  (Contributed by Brett Cannon in bpo-23014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23014}.)

@item 
@ref{5a2,,re.split()} 関数は常に空のパターンマッチを無視してきました。ですからパターン @code{"x*"} はパターン @code{"x+"} と同じように動作し、パターン @code{"\b"} は決して動作しませんでした。今後は @ref{5a2,,re.split()} はパターンが空文字列に合致しうる場合に警告を出します。互換性のためには空文字列とはマッチしえないパターンを使ってください(たとえば @code{"x*"} ではなく @code{"x+"} を使ってください)。空文字列としかマッチしえないパターン(例えば @code{"\b"})はエラーとなります。 (Contributed by Serhiy Storchaka in bpo-22818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22818}.)

@item 
@ref{dfe,,http.cookies.Morsel} 辞書風インターフェイスのそれ自身での一貫性を持たせるようにしました: morsel の比較に @ref{dfb,,key} と @ref{dfc,,value} を考慮するようにし、 @ref{10c8,,copy()} は @ref{183,,dict} を返さずに @ref{dfe,,Morsel} インスタンスを返すようにし、 @ref{10c9,,update()} は更新する辞書内のいずれかのキーが不正(訳注: 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} として不正なキーのことで、update 以外のインターフェイスでは変更前も拒絶される)であれば例外を投げるようにしています。加えて、ドキュメントされていない @ref{dff,,set()} の `LegalChars' パラメータは非推奨となり、また指定しても無視されます。 (Contributed by Demian Brecht in bpo-2211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2211}.)

@item 
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} has removed @code{.pyo} files from Python and introduced the optional
@code{opt-} tag in @code{.pyc} file names. The
@ref{353,,importlib.util.cache_from_source()} has gained an `optimization'
parameter to help control the @code{opt-} tag. Because of this, the
`debug_override' parameter of the function is now deprecated. @code{.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 @code{.pyo} files from previous versions of Python are
invalid regardless of this PEP.

@item 
The @ref{d1,,socket} module now exports the @ref{10ca,,CAN_RAW_FD_FRAMES}
constant on linux 3.6 and greater.

@item 
@geindex RFC; RFC 5280
RFC 5280@footnote{https://datatracker.ietf.org/doc/html/rfc5280.html} に基づき、 @ref{106b,,ssl.cert_time_to_seconds()} 関数が入力の時刻をローカル時刻ではなく UTC として解釈するようになりました。また、戻り値は常に @ref{19b,,int} となります。 (Contributed by Akira Li in bpo-19940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19940}.)

@item 
@code{pygettext.py} ツールが POT-Creation-Date ヘッダ内のタイムゾーン形式として、標準の +NNNN 形式を使うようになりました。

@item 
The @ref{cf,,smtplib} module now uses @ref{b33,,sys.stderr} instead of the previous
module-level @code{stderr} variable for debug output.  If your (test)
program depends on patching the module-level variable to capture the debug
output, you will need to update it to capture sys.stderr instead.

@item 
@ref{10cb,,str.startswith()} と @ref{10cc,,str.endswith()} メソッドは空文字列を見つけた場合と完全に範囲外のインデクスが渡された場合に @code{True} を返すことはしなくなりました。  (Contributed by Serhiy Storchaka in bpo-24284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24284}.)

@item 
@ref{bed,,inspect.getdoc()} 関数が基底クラスから継承したドキュメンテーション文字列を返すようになりました。その継承したドキュメンテーション文字列が相応しいのであれば、もはやそれを繰り返して記述する必要はありません。継承されたそれを抑制するには、空の文字列を記述しなければなりません(もしくは然るべきドキュメンテーションを埋めれば良いです)。この変更は @ref{ba,,pydoc} モジュールと @ref{ad4,,help()} 関数の出力に影響します。 (Contributed by Serhiy Storchaka in bpo-15582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15582}.)

@item 
ネストされた @ref{217,,functools.partial()} 呼び出しは平坦化されるようになりました。以前の振る舞いに依存していたのであれば @ref{217,,functools.partial()} オブジェクトに属性を追加するか、または @ref{217,,functools.partial()} をサブクラス化することで出来ます。 (--訳注: 後半が意味がある内容を言ってるようには思えません。「以前の振る舞い」とはおそらく @code{partial} オブジェクトの @code{func} 属性が functools.partial そのものになることを指していて、「似たことをしたければ @code{partial} オブジェクトに別の属性を付ければりゃいんじゃね?」程度の無責任な代替案を言ってるだけのような気がします。そもそも後者の「サブクラス化」は出来ないと思いますし。 --)  (Contributed by Alexander Belopolsky in bpo-7830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7830}.)
@end itemize

@node C API の変更<14>,,Python API の変更<10>,Python 3 5 への移植
@anchor{whatsnew/3 5 changes-in-the-c-api}@anchor{10cd}
@subsubsection C API の変更



@itemize *

@item 
The undocumented @code{format} member of the
(non-public) @code{PyMemoryViewObject} structure has been removed.
All extensions relying on the relevant parts in @code{memoryobject.h}
must be rebuilt.

@item 
The @code{PyMemAllocator} structure was renamed to
@ref{10ce,,PyMemAllocatorEx} and a new @code{calloc} field was added.

@item 
Removed non-documented macro @code{PyObject_REPR()} which leaked references.
Use format character @code{%R} in @ref{62b,,PyUnicode_FromFormat()}-like functions
to format the @ref{1c1,,repr()} of the object.
(Contributed by Serhiy Storchaka in bpo-22453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22453}.)

@item 
Because the lack of the @ref{617,,__module__} attribute breaks pickling and
introspection, a deprecation warning is now raised for builtin types without
the @ref{617,,__module__} attribute.  This will be an @ref{5f0,,AttributeError} in
the future.
(Contributed by Serhiy Storchaka in bpo-20204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20204}.)

@item 
As part of the 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} implementation, the @code{tp_reserved} slot of
@ref{c9c,,PyTypeObject} was replaced with a
@ref{10cf,,tp_as_async} slot.  Refer to @ref{10d0,,コルーチンオブジェクト} for
new types, structures and functions.
@end itemize

@node Notable changes in Python 3 5 4,,Python 3 5 への移植,What's New In Python 3 5
@anchor{whatsnew/3 5 notable-changes-in-python-3-5-4}@anchor{10d1}
@subsection Notable changes in Python 3.5.4


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

@end menu

@node New make regen-all build target<2>,Removal of make touch build target<2>,,Notable changes in Python 3 5 4
@anchor{whatsnew/3 5 new-make-regen-all-build-target}@anchor{10d2}
@subsubsection New @code{make regen-all} build target


To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.

Instead, a new @code{make regen-all} command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in@footnote{https://github.com/python/cpython/tree/3.14/Makefile.pre.in} for details.

(Victor Stinner の貢献による bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404})


Added in version 3.5.4.


@node Removal of make touch build target<2>,,New make regen-all build target<2>,Notable changes in Python 3 5 4
@anchor{whatsnew/3 5 removal-of-make-touch-build-target}@anchor{10d3}
@subsubsection Removal of @code{make touch} build target


The @code{make touch} build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.

It has been replaced by the new @code{make regen-all} target.

(Victor Stinner の貢献による bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404})


バージョン 3.5.4 で変更.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 4,What's New In Python 3 3,What's New In Python 3 5,What's New in Python
@anchor{whatsnew/3 4 doc}@anchor{10d4}@anchor{whatsnew/3 4 translation-repo}@anchor{10d5}@anchor{whatsnew/3 4 what-s-new-in-python-3-4}@anchor{10d6}
@section What's New In Python 3.4


@*著者: 
R. David Murray <@email{rdmurray@@bitdance.com}> (Editor)


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document, but the maintainer reserves the
@c right to rewrite any additions. In particular, for obscure or esoteric
@c features, the maintainer may reduce any addition to a simple reference to
@c the new documentation rather than explaining the feature inline.
@c 
@c * While the maintainer will periodically go through Misc/NEWS
@c and add changes, it's best not to rely on this. We know from experience
@c that any changes that aren't in the What's New documentation around the
@c time of the original release will remain largely unknown to the community
@c for years, even if they're added later. We also know from experience that
@c other priorities can arise, and the maintainer will run out of time to do
@c updates -- in such cases, end users will be much better served by partial
@c notifications that at least give a hint about new features to
@c investigate.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS. The What's New should focus on changes that
@c are visible to Python *users* and that *require* a feature release (i.e.
@c most bug fixes should only be recorded in Misc/NEWS)
@c 
@c * PEPs should not be marked Final until they have an entry in What's New.
@c A placeholder entry that is just a section header and a link to the PEP
@c (e.g ":pep:`397` has been implemented") is acceptable. If a PEP has been
@c implemented and noted in What's New, don't forget to mark it as Final!
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to add just a very brief note about a change.  For
@c example: "The :ref:`~socket.transmogrify()` function was added to the
@c :mod:`socket` module."  The maintainer will research the change and
@c write the necessary text (if appropriate). The advantage of doing this
@c is that even if no more descriptive text is ever added, readers will at
@c least have a notification that the new feature exists and a link to the
@c relevant documentation.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c The :ref:`~socket.transmogrify()` function was added to the
@c :mod:`socket` module.  (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.
@c 
@c * Cross referencing tip: :ref:`mod.attr` will display as ``mod.attr``,
@c while :ref:`~mod.attr` will display as ``attr``.

この記事では 3.3 と比較した Python 3.4 の新機能を解説します。 Python 3.4 は2014年3月16日にリリースされました。全詳細については 変更履歴@footnote{https://docs.python.jp/3.4/whatsnew/changelog.html} をご覧ください。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 429
PEP 429@footnote{https://peps.python.org/pep-0429/} -- Python 3.4 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト<11>. リリースハイライト
* 新しい機能: 新しい機能<16>. 
* 新たなモジュール: 新たなモジュール<10>. 
* 改良されたモジュール: 改良されたモジュール<10>. 
* CPython の実装の変更:: 
* 非推奨: 非推奨<12>. 
* 削除: 削除<12>. 
* Python 3.4 への移植: Python 3 4 への移植. 
* 3.4.3 の変更: 3 4 3 の変更. 

@end menu

@node 概要 -- リリースハイライト<11>,新しい機能<16>,,What's New In Python 3 4
@anchor{whatsnew/3 4 summary-release-highlights}@anchor{10d7}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.4.
@c Brevity is key.

新たな文法機能:


@itemize *

@item 
Python 3.4 に追加された新しい文法機能はありません。
@end itemize

その他の新しい機能:


@itemize *

@item 
@ref{10d8,,pip が常に利用可能であることが保障されるようになりました} (
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/})。

@item 
@ref{10d9,,新しく作成されたファイル記述子が継承不可能 （non-inheritable） になりました} (
@geindex Python Enhancement Proposals; PEP 446
PEP 446@footnote{https://peps.python.org/pep-0446/})。

@item 
@ref{10da,,隔離モード (isolated mode)} の為のコマンドラインオプション (bpo-16499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16499})。

@item 
非テキストエンコーディングでの @ref{10db,,Codec 処理の改良}  (複数の issue に関係).

@item 
インポートシステムのための @ref{10dc,,ModuleSpec 型}  (
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/}).  (インポーターの作者に影響します)

@item 
@ref{91,,marshal} フォーマットが @ref{10dd,,よりコンパクトで効率的に} なりました  (bpo-16475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16475})。
@end itemize

新たなライブラリモジュール:


@itemize *

@item 
@ref{b,,asyncio}: @ref{10de,,非同期 IO のための新たな暫定 API} (
@geindex Python Enhancement Proposals; PEP 3156
PEP 3156@footnote{https://peps.python.org/pep-3156/})。

@item 
@ref{59,,ensurepip}: @ref{10df,,pip インストーラのブートストラップ} (
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/})。

@item 
@ref{5a,,enum}: @ref{10e0,,列挙型のサポート} (
@geindex Python Enhancement Proposals; PEP 435
PEP 435@footnote{https://peps.python.org/pep-0435/})。

@item 
@ref{a8,,pathlib}: @ref{10e1,,オブジェクト指向のファイルシステムパス} (
@geindex Python Enhancement Proposals; PEP 428
PEP 428@footnote{https://peps.python.org/pep-0428/})。

@item 
@ref{c7,,selectors}: @ref{10e2,,高水準で効率的な I/O の多重化}、@ref{c6,,select} モジュールプリミティブを基にしています (
@geindex Python Enhancement Proposals; PEP 3156
PEP 3156@footnote{https://peps.python.org/pep-3156/} の一部)。

@item 
@ref{d7,,statistics}: 基礎的な @ref{10e3,,数値的に安定な統計ライブラリ} (
@geindex Python Enhancement Proposals; PEP 450
PEP 450@footnote{https://peps.python.org/pep-0450/})。

@item 
@ref{105,,tracemalloc}: @ref{10e4,,Python のメモリ割り当てのトレース} (
@geindex Python Enhancement Proposals; PEP 454
PEP 454@footnote{https://peps.python.org/pep-0454/})。
@end itemize

大幅に改善されたライブラリモジュール:


@itemize *

@item 
@ref{63,,functools} の @ref{10e5,,シングルディスパッチジェネリック関数} (
@geindex Python Enhancement Proposals; PEP 443
PEP 443@footnote{https://peps.python.org/pep-0443/})。

@item 
@ref{ab,,pickle} の新しい @ref{10e6,,プロトコル 4} (
@geindex Python Enhancement Proposals; PEP 3154
PEP 3154@footnote{https://peps.python.org/pep-3154/}).

@item 
@ref{98,,multiprocessing} が @ref{10e7,,Unix で os.fork の使用を避けるオプションを持つようになりました} (bpo-8713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8713})。

@item 
@ref{3f,,email} has a new submodule, @ref{41,,contentmanager}, and
a new @ref{581,,Message} subclass
(@ref{580,,EmailMessage}) that @ref{10e8,,simplify MIME handling} (bpo-18891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18891}).

@item 
@ref{82,,inspect} と @ref{ba,,pydoc} が以前よりも遥かに幅広い種類の callable オブジェクトを正しくイントロスペクション出来るようになり、これは Python @ref{ad4,,help()} システムを改善することになりました。

@item 
@ref{84,,ipaddress} モジュール API は安定だと宣言されました。
@end itemize

セキュリティの改善:


@itemize *

@item 
@ref{10e9,,安全で取り替え可能なハッシュアルゴリズム} (
@geindex Python Enhancement Proposals; PEP 456
PEP 456@footnote{https://peps.python.org/pep-0456/})。

@item 
ファイル記述子が子プロセスにリークするのを防ぐために @ref{10d9,,新しく作成されたファイル記述子が継承不可になりました} (
@geindex Python Enhancement Proposals; PEP 446
PEP 446@footnote{https://peps.python.org/pep-0446/})。

@item 
@ref{10da,,隔離モード (isolated mode)} のための新たなコマンドラインオプション (bpo-16499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16499})。

@item 
@ref{98,,multiprocessing} が @ref{10e7,,Unix で os.fork の使用を避けるオプション} を持つようになりました。
子プロセスとのデータ共有を避けるため `spawn' と `forkserver' はより安全です。

@item 
Windows での @ref{98,,multiprocessing} 子プロセスはもはや、必要なものを除いて親の継承可能なハンドルを継承しません。

@item 
新たな関数 @ref{733,,hashlib.pbkdf2_hmac()} は PKCS#5 パスワードベースの鍵導出関数２@footnote{https://en.wikipedia.org/wiki/PBKDF2} を提供します。

@item 
@ref{d5,,ssl} での @ref{10ea,,TLSv1.1、 TLSv1.2 サポート} の追加。

@item 
@ref{d5,,ssl} での @ref{10eb,,Windows のシステム証明書ストアよりの証明書抽出サポート} の追加。

@item 
@ref{d5,,ssl} での @ref{10ec,,サーバサイド SNI (Server Name Indication) サポート} の追加。

@item 
@ref{357,,ssl.SSLContext} クラスに @ref{10ed,,多数の改善} がなされました。

@item 
All modules in the standard library that support SSL now support server
certificate verification, including hostname matching
(@code{ssl.match_hostname()}) and CRLs (Certificate Revocation lists, see
@ref{10ee,,ssl.SSLContext.load_verify_locations()}).
@end itemize

CPython の実装の改善:


@itemize *

@item 
@ref{10ef,,オブジェクトの安全なファイナライゼーション} (
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/})。

@item 
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/} を活用することで、ほとんどのケースで @ref{10ef,,モジュールのグローバルがファイナライゼーション中に None がセットされることはなくなりました}  (bpo-18214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18214})。

@item 
@ref{10f0,,設定可能なメモリアロケータ} (
@geindex Python Enhancement Proposals; PEP 445
PEP 445@footnote{https://peps.python.org/pep-0445/})。

@item 
@ref{10f1,,Argument Clinic} (
@geindex Python Enhancement Proposals; PEP 436
PEP 436@footnote{https://peps.python.org/pep-0436/})。
@end itemize

以降は、たくさんのほかの小さな改善、CPython での最適化、非推奨リスト、潜在的な移植性問題を含む、ユーザ向けの変更の包括的なリストになっています。

@node 新しい機能<16>,新たなモジュール<10>,概要 -- リリースハイライト<11>,What's New In Python 3 4
@anchor{whatsnew/3 4 new-features}@anchor{10f2}
@subsection 新しい機能


@menu
* PEP 453; Python インストール時の PIP の明示的なブートストラッピング: PEP 453 Python インストール時の PIP の明示的なブートストラッピング. 
* PEP 446; 新規作成されたファイル記述子は継承不可: PEP 446 新規作成されたファイル記述子は継承不可. 
* Codec 処理の改良:: 
* PEP 451; インポートシステムのための ModuleSpec 型: PEP 451 インポートシステムのための ModuleSpec 型. 
* その他の言語変更: その他の言語変更<10>. 

@end menu

@node PEP 453 Python インストール時の PIP の明示的なブートストラッピング,PEP 446 新規作成されたファイル記述子は継承不可,,新しい機能<16>
@anchor{whatsnew/3 4 pep-453-explicit-bootstrapping-of-pip-in-python-installations}@anchor{10f3}@anchor{whatsnew/3 4 whatsnew-pep-453}@anchor{10d8}
@subsubsection PEP 453: Python インストール時の PIP の明示的なブートストラッピング


@menu
* デフォルトでの pip のブートストラッピング:: 
* ドキュメントの変更:: 

@end menu

@node デフォルトでの pip のブートストラッピング,ドキュメントの変更,,PEP 453 Python インストール時の PIP の明示的なブートストラッピング
@anchor{whatsnew/3 4 bootstrapping-pip-by-default}@anchor{10f4}
@subsubsection デフォルトでの pip のブートストラッピング


新しい @ref{59,,ensurepip} モジュール(
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/} で定義されています)は標準のクロスプラットフォームのメカニズムで、Python インストールと仮想環境に pip インストーラをブートストラップします。Python 3.4.0 に含まれる @code{pip} のバージョンは @code{pip} 1.5.4 で、将来の 3.4.x メンテナンスリリースでは Python のリリース候補の作成時点で入手出来る最新バージョンの @code{pip} がバンドルされる予定です。

デフォルトでは @code{pipX} , @code{pipX.Y} コマンドが全てのプラットフォームに、Python パッケージ @code{pip} とその依存物とともにインストールされます(X. Y はインストールされる Python のバージョン)。Windows 実環境と全てのプラットフォームの仮想環境には、バージョンが名前に付与されない @code{pip} コマンドもインストールされます。ほかのプラットフォームでは、システムワイドでバージョンが名前に付与されない @code{pip} コマンドは、典型的には Python 2 を別途インストールした際のものを指しています。

@code{pyvenv} コマンドラインユーティリティと @ref{117,,venv} モジュールは、仮想環境で @code{pip} が使えるようにするために @ref{59,,ensurepip} モジュールを使います。
コマンドラインユーティリティを使う際は @code{pip} はデフォルトでインストールされます。
@ref{117,,venv} モジュールの @ref{10f5,,API} を使う際は、 @code{pip} のインストールは明示的に要求しなければなりません。

CPython の @ref{10f6,,source builds on POSIX systems} では @code{make install}, @code{make altinstall} コマンドはデフォルトで @code{pip} ブートストラップを行います。この振る舞いは configure のオプションを変更して Makefile を作ることで変更できます。

Windows と Mac OS X では CPython インストーラはそれ自身と一緒に @code{pip} をデフォルトでインストールするようになっています(ユーザはインストールプロセスで除外するかもしれませんが)。Windows ユーザは @code{pip} がコマンドラインからデフォルトで利用可能なように @code{PATH} の自動修正するかの選択を求められます。そうしない場合でも Windows のための Python ランチャで @code{py -m pip} のようにすれば良いです。

As 
@geindex Python Enhancement Proposals; PEP 0453#recommendations-for-downstream-distributors
discussed in the PEP@footnote{https://peps.python.org/pep-0453/#recommendations-for-downstream-distributors}
platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear and
simple directions on how to install them on that platform (usually using
the system package manager).

@cartouche
@quotation 注釈 
Python 2 と Python 3 の共存インストールでの衝突を避けるために、 @code{ensurepip} を直接呼び出した場合のデフォルトでは、バージョン付けされた @code{pip3}, @code{pip3.4} コマンドだけがインストールされます。バージョン付けのない @code{pip} コマンドもインストールしたければ、 @code{--default-pip} オプションが必要です。 @code{pyvenv} と Windows インストーラは修飾のない @code{pip} コマンドがそれら環境で利用可能となるように保障しますし、また、複数の Python がインストールされたシステムで曖昧さを避けようと直接コマンドを呼び出す代わりに、 @code{pip} は @code{-m} スイッチ経由でいつでも呼び出せます。
@end quotation
@end cartouche

@node ドキュメントの変更,,デフォルトでの pip のブートストラッピング,PEP 453 Python インストール時の PIP の明示的なブートストラッピング
@anchor{whatsnew/3 4 documentation-changes}@anchor{10f7}
@subsubsection ドキュメントの変更


この変更の一部は、 @ref{10f8,,Python モジュールのインストール} と distributing-index セクションがより手短な始め方として完全にデザインし直されたことと、FAQ ドキュメントです。ほとんどのパッケージングについてのドキュメンテーションは Python Packaging User Guide@footnote{https://packaging.python.org}  が保守している Python Packaging Authority に移動されて、独立したプロジェクトのドキュメンテーションになっています。

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as @ref{10f9,,setuptools による C および C++ 拡張のビルド}
and @ref{10fa,,setuptools による C および C++ 拡張のビルド}.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 453

@item PEP 453@footnote{https://peps.python.org/pep-0453/} -- Python インストールの際の明示的なpipのブートストラッピング

PEP は Donald Stufft と Nick Coghlan によって書かれ、Donald Stufft, Nick Coghlan, Martin von Löwis, Ned Deily により実装されました。
@end table


@node PEP 446 新規作成されたファイル記述子は継承不可,Codec 処理の改良,PEP 453 Python インストール時の PIP の明示的なブートストラッピング,新しい機能<16>
@anchor{whatsnew/3 4 pep-446-newly-created-file-descriptors-are-non-inheritable}@anchor{10fb}@anchor{whatsnew/3 4 whatsnew-pep-446}@anchor{10d9}
@subsubsection PEP 446: 新規作成されたファイル記述子は継承不可


@geindex Python Enhancement Proposals; PEP 446
PEP 446@footnote{https://peps.python.org/pep-0446/} により、新規作成するファイル記述子は @ref{10fc,,継承不可 (non-inheritable)} となります。一般的にはこれこそがアプリケーションが望む振る舞いです。新たにプロセスを生成する際に、現在開いているファイルを起こした子プロセスでも開くことは、検出が困難なあらゆるバグや潜在的なセキュリティ問題を引き起こしかねません。

そうはいっても継承することが望ましい場合もあります。それらのケースをサポートするために、以下の新規関数とメソッドが利用出来ます:


@itemize *

@item 
@ref{10fd,,os.get_inheritable()}, @ref{10fe,,os.set_inheritable()}

@item 
@ref{10ff,,os.get_handle_inheritable()}, @ref{1100,,os.set_handle_inheritable()}

@item 
@ref{1101,,socket.socket.get_inheritable()}, @ref{1102,,socket.socket.set_inheritable()}
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 446

@item PEP 446@footnote{https://peps.python.org/pep-0446/} -- 新規作成されたファイル記述子を継承不可にする

PEP written and implemented by Victor Stinner.
@end table


@node Codec 処理の改良,PEP 451 インポートシステムのための ModuleSpec 型,PEP 446 新規作成されたファイル記述子は継承不可,新しい機能<16>
@anchor{whatsnew/3 4 codec-handling-improvements}@anchor{10db}@anchor{whatsnew/3 4 improvements-to-codec-handling}@anchor{1103}
@subsubsection Codec 処理の改良


その最初の導入からずっと、 @ref{1c,,codecs} モジュールとはいつなんどきも、型に中立で動的なエンコーディング・デコーディングシステムとして働くものであったのです。そうなのですがその Python テキストモデルとの密接な結合、特に組み込み型 @ref{169,,str}, @ref{192,,bytes}, @ref{344,,bytearray} にある型に制限があるコンビニエンスメソッドのおかげで、歴史的にその本来の意図を曖昧にしてきたのでした。

そんな状況を清く正しくするための重要な一歩として、今ではコンビニエンス関数 @ref{1104,,codecs.encode()}, @ref{1105,,codecs.decode()} が Python 2.7、3.3、3.4 で適切にドキュメントされました。これら関数は @ref{1c,,codecs} モジュールに Python 2.4 からずっと存在している (うえに回帰テストスイートでもずっと網羅してきた) のですが、以前はドキュメントされていなかったわけなので、実行時イントロスペクションでようやく見つけられるというものだったわけです。

@ref{169,,str}, @ref{192,,bytes}, @ref{344,,bytearray} でのコンビニエンスメソッドが Python 3 では Unicode テキストエンコーディングに制限され、Python 2 では @code{basestring} <-> @code{basestring} 変換に制限されるのとは違うのです。 @ref{1c,,codecs} のコンビニエンス関数は Python 2 と Python 3 の両方で任意のコーデックをサポートするのです。

Python 3.4 では、インタプリタは標準ライブラリで提供している非テキストエンコーディングについて知っています。そして以下のように適宜、それら汎用目的のコンビニエンス関数へユーザを誘導します:

@example
>>> b"abcdef".decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

>>> "hello".encode("rot13")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs

>>> open("foo.txt", encoding="hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs
@end example

関連する変更で、後方互換性を壊すことなくそれが相応しい場合にはいつでも、エンコーディング・デコーディング操作中に起こる例外は、同じ例外型でありエラーを発生させることになった原因コーデックの名前に言及する連鎖例外内に包まれます:

@example
>>> import codecs

>>> codecs.decode(b"abcdefgh", "hex")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
    return (binascii.a2b_hex(input), len(input))
binascii.Error: Non-hexadecimal digit found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

>>> codecs.encode("hello", "bz2")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
    return (bz2.compress(input), len(input))
  File "/usr/lib/python3.4/bz2.py", line 498, in compress
    return comp.compress(data) + comp.flush()
TypeError: 'str' does not support the buffer interface

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)
@end example

そしてついに、ここまで実例で見てきたような的確な誘導による改善が、それ自体は Python 3.2 で復活していた非 Unicode コーデックへのコンビニエンスのエイリアスの復活を可能にしました。(---訳注: Python 3.0 で一度非 Unicode エンコーディングは消滅し、3.2 でそれらコーデックそのものは復活したものの、 Lib/encodings/aliases.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/encodings/aliases.py} のマッピングからは除外されたままだった。---) つまり、バイナリデータの 16 進表現エンコードとそのデコード (たとえば、です) は、今ではこう書けるということです:

@example
>>> from codecs import encode, decode
>>> encode(b"hello", "hex")
b'68656c6c6f'
>>> decode(b"68656c6c6f", "hex")
b'hello'
@end example

標準ライブラリで提供されるバイナリ変換とテキスト変換は、 @ref{1106,,バイナリ変換 (Binary Transforms)} と @ref{1107,,テキスト変換 (Text Transforms)} に詳細記述されました。

(Contributed by Nick Coghlan in bpo-7475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7475}, bpo-17827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17827},
bpo-17828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17828} and bpo-19619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19619}.)

@node PEP 451 インポートシステムのための ModuleSpec 型,その他の言語変更<10>,Codec 処理の改良,新しい機能<16>
@anchor{whatsnew/3 4 pep-451-a-modulespec-type-for-the-import-system}@anchor{1108}@anchor{whatsnew/3 4 whatsnew-pep-451}@anchor{10dc}
@subsubsection PEP 451: インポートシステムのための ModuleSpec 型


@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/} は、インポート機構がロードに使うモジュールに関する情報 (つまりモジュールの仕様) のカプセル化を提供します。これはインポートの実装とインポート関連 API の両方を単純化するのに役立ちます。この変更は、 いくつかの将来のインポート関連の改善@footnote{https://mail.python.org/pipermail/python-dev/2013-November/130111.html} の足掛かりでもあります。

この PEP による公な側面での変化は完全に後方互換です。さらにそれらは、インポーターの作者以外にとっては透過的であるはずです。鍵となるファインダとローダのメソッドはまだ動作し続けますが非推奨となりました。新しいインポータは PEP に記述された新メソッドを使うべきです。既存のインポータは新メソッドを実装するように更新すべきです。置き換えられるべきメソッドとその代わりとなるメソッドのリストについては @ref{1109,,非推奨} を参照してください。

@node その他の言語変更<10>,,PEP 451 インポートシステムのための ModuleSpec 型,新しい機能<16>
@anchor{whatsnew/3 4 other-language-changes}@anchor{110a}
@subsubsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
Unicode データベースを UCD バージョン 6.3 にアップグレードしました。

@item 
@ref{110b,,min()} と @ref{110c,,max()} にキーワード専用引数 `default' が追加されました。これにはイテラブルが要素なしであると評価される場合に返す値を指定出来ます。 (Contributed by Julian Berman in bpo-18111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18111}.)

@item 
Module objects are now @ref{110d,,weakly referenceable}.

@item 
モジュールの @code{__file__} 属性 (と関連する値) にはデフォルトでは常に絶対パスを含むようになりました。ただし、スクリプトがコマンドラインから相対パスを使って直接実行された際の @code{__main__.__file__} は唯一の例外です。 (Contributed by Brett Cannon in bpo-18416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18416}.)

@item 
UTF-16 デコーダ (妥当なサロゲートペアを受け付ける) と UTF-16 エンコーダ (非 BMP 文字のエンコードでサロゲートペアを生成) 以外の、(UTF-7 を除く) 全ての UTF-* コーデックが、エラーハンドラ @code{surrogatepass} を使わない限りはエンコーディングとデコーディングの両方でサロゲートペアを拒絶するようになりました。(Contributed by Victor Stinner, Kang-Hao (Kenny) Lu and Serhiy Storchaka in bpo-12892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12892}.)

@item 
新規ドイツ語 EBCDIC @ref{fb8,,codec} @code{cp273}.  (Contributed by Michael Bierenfeld and Andrew Kuchling in bpo-1097797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1097797}.)

@item 
新規ウクライナ語 @ref{fb8,,codec} @code{cp1125}.  (Contributed by Serhiy Storchaka in bpo-19668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19668}.)

@item 
@ref{192,,bytes}.join() と @ref{344,,bytearray}.join() が引数として任意のバッファオブジェクトを受け取れるようになりました。 (Contributed by Antoine Pitrou in bpo-15958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15958}.)

@item 
@ref{19b,,int} コンストラクタの `base' 引数に、 @code{__index__} メソッドを持つ任意のオブジェクトを渡せるようになりました。(Contributed by Mark Dickinson in bpo-16772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16772}.) (---訳注: @ref{110e,,Python API の変更} に同じ bpo-16772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16772} を発端とする変更が書かれているのでそちらも参照して下さい。 ---)

@item 
フレームオブジェクトに、ローカル変数への全ての参照をフレームからクリアするメソッド @ref{585,,clear()} が追加されました。(Contributed by Antoine Pitrou in bpo-17934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17934}.)

@item 
@ref{165,,memoryview} が @ref{1f,,Sequence} として登録され、また、組み込み関数 @ref{a65,,reversed()} をサポートするようになりました。 (Contributed by Nick Coghlan and Claudiu Popa in bpo-18690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18690} and bpo-19078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19078}.)

@item 
Argument Clinic の導入、 @ref{82,,inspect} と @ref{ba,,pydoc} になされた他の変更の結果、多くの場合で @ref{ad4,,help()} が報告するシグニチャが修正・改善されました。

@item 
@ref{110f,,__length_hint__()} が、公式な言語仕様の一部になりました (see 
@geindex Python Enhancement Proposals; PEP 424
PEP 424@footnote{https://peps.python.org/pep-0424/})。 (Contributed by Armin Ronacher in bpo-16148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16148}.)
@end itemize

@node 新たなモジュール<10>,改良されたモジュール<10>,新しい機能<16>,What's New In Python 3 4
@anchor{whatsnew/3 4 new-modules}@anchor{1110}
@subsection 新たなモジュール


@menu
* asyncio: asyncio<14>. 
* ensurepip: ensurepip<2>. 
* enum: enum<9>. 
* pathlib: pathlib<14>. 
* selectors: selectors<2>. 
* statistics: statistics<6>. 
* tracemalloc: tracemalloc<4>. 

@end menu

@node asyncio<14>,ensurepip<2>,,新たなモジュール<10>
@anchor{whatsnew/3 4 asyncio}@anchor{1111}@anchor{whatsnew/3 4 whatsnew-asyncio}@anchor{10de}
@subsubsection asyncio


@ref{b,,asyncio} モジュールが追加されました (
@geindex Python Enhancement Proposals; PEP 3156
PEP 3156@footnote{https://peps.python.org/pep-3156/} で定義されています)。これは Python のための標準的で抜き挿し可能なイベントループモデルを、標準ライブラリに信頼出来る非同期 I/O サポートを追加することで提供し、また、ほかのイベントループ実装を標準ライブラリと相互運用することを容易にします。

Python 3.4 では、このモジュールは @ref{3d1,,暫定 API} であるとみなされています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3156

@item PEP 3156@footnote{https://peps.python.org/pep-3156/} -- 非同期 IO サポートの再起動: "asyncio" モジュール

PEP written and implementation led by Guido van Rossum. (訳注: PEP タイトルの「Asynchronous IO Support Rebooted: the "asyncio" Module」は 
@geindex Python Enhancement Proposals; PEP 3153
PEP 3153@footnote{https://peps.python.org/pep-3153/} の焼き直しのため。)
@end table


@node ensurepip<2>,enum<9>,asyncio<14>,新たなモジュール<10>
@anchor{whatsnew/3 4 ensurepip}@anchor{1112}@anchor{whatsnew/3 4 whatsnew-ensurepip}@anchor{10df}
@subsubsection ensurepip


新規の @ref{59,,ensurepip} モジュールは 
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/} 実装のための本質的な基盤です。通常はエンドユーザはこのモジュールを弄ぶ必要はありません。ですが、 @code{pip} のインストレーションや仮想環境に対する自動ブートストラップを拒否していた場合には、手動でそれをブートストラップするのに使えます。

@ref{59,,ensurepip} は @code{pip} のバンドルされたコピーを含んでいて、これは CPython リリースの最初のリリース候補時点での最新です (このことはメンテナンスリリース、feature リリースの両方に適用されます)。 @code{ensurepip} 自身はインターネットアクセスしません。依存パッケージ解決のためのインターネットアクセスを要するならばそれは @code{ensurepip} 実行の後の @code{pip} で行いますし、 @code{pip} そのもののアップグレードも @code{pip} 自身で行います。(そのようなアップグレード版 @code{pip} は個別のインストールパッケージとみなされて、Python がアンインストールされても削除されないことを付記しておきます。)

このモジュールが「 `ensure (保障する)' 」を名前に冠するのは、 @code{pip} がインストール済みならば何もしないからです。このモジュールは @code{--upgrade} オプションを持ちますが、これは既存のインストール版 @code{pip} がこのモジュールにバンドルされたコピーよりも古い場合に、バンドルされたコピー版 @code{pip} をインストールします。

@node enum<9>,pathlib<14>,ensurepip<2>,新たなモジュール<10>
@anchor{whatsnew/3 4 enum}@anchor{1113}@anchor{whatsnew/3 4 whatsnew-enum}@anchor{10e0}
@subsubsection enum


@ref{5a,,enum} モジュール (
@geindex Python Enhancement Proposals; PEP 435
PEP 435@footnote{https://peps.python.org/pep-0435/} にて定義) は標準の列挙型実装を提供します。これにより (@ref{d1,,socket} のような) ほかのモジュールが、不透明な整数定数を後方互換を保ったまま列挙値に置き換えることによって、より情報に富むエラーメッセージを提供したり、より良いデバッグサポートを行えるようになります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 435

@item PEP 435@footnote{https://peps.python.org/pep-0435/} -- Python 標準ライブラリに enum 型を追加

PEP written by Barry Warsaw, Eli Bendersky and Ethan Furman,
implemented by Ethan Furman.
@end table


@node pathlib<14>,selectors<2>,enum<9>,新たなモジュール<10>
@anchor{whatsnew/3 4 pathlib}@anchor{1114}@anchor{whatsnew/3 4 whatsnew-pathlib}@anchor{10e1}
@subsubsection pathlib


新規モジュール @ref{a8,,pathlib} は、異なるオペレーティングシステムごとに適切な意味付けでファイルシステムパスを表現するクラス群を提供しています。パスのクラス群は `純粋パス' と `具象パス' に分離されています。前者は I/O を伴わない純粋なパス計算操作を提供するもので、後者は純粋パスを派生しますが I/O 操作も提供します。

Python 3.4 では、このモジュールは @ref{3d1,,暫定 API} であるとみなされています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 428

@item PEP 428@footnote{https://peps.python.org/pep-0428/} -- pathlib モジュール -- オブジェクト指向のファイルシステムパス

PEP written and implemented by Antoine Pitrou.
@end table


@node selectors<2>,statistics<6>,pathlib<14>,新たなモジュール<10>
@anchor{whatsnew/3 4 selectors}@anchor{1115}@anchor{whatsnew/3 4 whatsnew-selectors}@anchor{10e2}
@subsubsection selectors


新規モジュール @ref{c7,,selectors} (
@geindex Python Enhancement Proposals; PEP 3156
PEP 3156@footnote{https://peps.python.org/pep-3156/} の一部として作成されました)　は、高水準で効率的な I/O の多重化を行います。これは @ref{c6,,select} モジュールプリミティブに基いています。

@node statistics<6>,tracemalloc<4>,selectors<2>,新たなモジュール<10>
@anchor{whatsnew/3 4 statistics}@anchor{1116}@anchor{whatsnew/3 4 whatsnew-statistics}@anchor{10e3}
@subsubsection statistics


新規モジュール @ref{d7,,statistics} (
@geindex Python Enhancement Proposals; PEP 450
PEP 450@footnote{https://peps.python.org/pep-0450/} で定義) は統計を扱う中核機能のいくつかを標準ライブラリで直接提供します。このモジュールはデータ系列の平均、中央値、最頻値、分散、標準偏差の計算をサポートします。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 450

@item PEP 450@footnote{https://peps.python.org/pep-0450/} -- 標準ライブラリに統計モジュールを追加

PEP written and implemented by Steven D'Aprano
@end table


@node tracemalloc<4>,,statistics<6>,新たなモジュール<10>
@anchor{whatsnew/3 4 tracemalloc}@anchor{1117}@anchor{whatsnew/3 4 whatsnew-tracemalloc}@anchor{10e4}
@subsubsection tracemalloc


新たな @ref{105,,tracemalloc} モジュール (
@geindex Python Enhancement Proposals; PEP 454
PEP 454@footnote{https://peps.python.org/pep-0454/} で定義) は Python が割り当てたメモリブロックをトレースするためのデバッグツールです。
以下の情報を提供します:


@itemize *

@item 
オブジェクトが割り当てられた場所をトレースする

@item 
ファイル名ごと、及び行ごとに割り当てられたメモリブロックの以下の統計を取ります：総サイズ、ブロック数、割り当てられたブロックの平均サイズ

@item 
メモリリークを検出するために2つのスナップショットの差を計算します。
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 454

@item PEP 454@footnote{https://peps.python.org/pep-0454/} -- Python メモリ割り当てをトレースするための tracemalloc モジュールの追加

PEP written and implemented by Victor Stinner
@end table


@node 改良されたモジュール<10>,CPython の実装の変更,新たなモジュール<10>,What's New In Python 3 4
@anchor{whatsnew/3 4 improved-modules}@anchor{1118}
@subsection 改良されたモジュール


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

@end menu

@node abc,aifc<2>,,改良されたモジュール<10>
@anchor{whatsnew/3 4 abc}@anchor{1119}
@subsubsection abc


新規関数 @ref{111a,,abc.get_cache_token()} は、オブジェクトグラフ内での変化の影響を受けるキャッシュをいつ無効化すれば良いかを知るために使えます。 (Contributed by Łukasz Langa in bpo-16832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16832}.)

新規クラス @ref{111b,,ABC} はそのメタクラスとして @ref{111c,,ABCMeta} を持ちます。この @code{ABC} を基底クラスとして使うことは @code{metaclass=abc.ABCMeta} を指定するのと本質的に同じ効果を持ちますが、少ないタイプ数で単純に書ける上に読みやすいものになります。(Contributed by Bruno Dupuis in bpo-16049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16049}.)

@node aifc<2>,argparse<7>,abc,改良されたモジュール<10>
@anchor{whatsnew/3 4 aifc}@anchor{111d}
@subsubsection aifc


The @code{getparams()} method now returns a namedtuple rather than a
plain tuple.  (Contributed by Claudiu Popa in bpo-17818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17818}.)

@code{aifc.open()} now supports the context management protocol: when used in a
@ref{186,,with} block, the @code{close()} method of the returned
object will be called automatically at the end of the block.  (Contributed by
Serhiy Storchacha in bpo-16486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16486}.)

The @code{writeframesraw()} and @code{writeframes()}
methods now accept any @ref{193,,bytes-like object}.  (Contributed by Serhiy
Storchaka in bpo-8311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8311}.)

@node argparse<7>,audioop,aifc<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 argparse}@anchor{111e}
@subsubsection argparse


@ref{30c,,FileType} クラスが `encoding' 引数、 `errors' 引数を受け付けるようになりました。これは @ref{316,,open()} にそのまま渡されます。 (Contributed by Lucas Maystre in bpo-11175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11175}.)

@node audioop,base64<4>,argparse<7>,改良されたモジュール<10>
@anchor{whatsnew/3 4 audioop}@anchor{111f}
@subsubsection audioop


@code{audioop} now supports 24-bit samples.  (Contributed by Serhiy Storchaka
in bpo-12866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12866}.)

New @code{byteswap()} function converts big-endian samples to
little-endian and vice versa.  (Contributed by Serhiy Storchaka in
bpo-19641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19641}.)

All @code{audioop} functions now accept any @ref{193,,bytes-like object}.  Strings
are not accepted: they didn't work before, now they raise an error right away.
(Contributed by Serhiy Storchaka in bpo-16685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16685}.)

@node base64<4>,collections<6>,audioop,改良されたモジュール<10>
@anchor{whatsnew/3 4 base64}@anchor{1120}
@subsubsection base64


@ref{f,,base64} のエンコード・デコード関数が任意の @ref{193,,bytes-like object} オブジェクトを受け取れるようになりました。以前は @ref{192,,bytes} または @ref{344,,bytearray} インスタンスである必要がありました。 (Contributed by Nick Coghlan in bpo-17839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17839}.)

新規関数 @ref{1121,,a85encode()}, @ref{1122,,a85decode()} は @code{Ascii85} フォーマットの、 @ref{1123,,b85encode()}, @ref{1124,,b85decode()} は git/mercurial の @code{Base85} フォーマットの、バイナリデータのエンコード・バイナリデータへのデコードを提供します。 @code{a85} 関数は、Abobe 方言を含む @code{Ascii85} エンコーディングの変種と互換性を持たせるためのオプションを持っています。(Contributed by Martin Morrison, the Mercurial project, Serhiy Storchaka, and Antoine Pitrou in bpo-17618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17618}.)

@node collections<6>,colorsys,base64<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 collections}@anchor{1125}
@subsubsection collections


@ref{1126,,ChainMap.new_child()} メソッドが、チェーンに追加する子マップを指定する `m' 引数を取るようになりました。これにより、以前は組み込み辞書が必ず maps の先頭になっていましたが、カスタムマッピング型も使えるようになります。(Contributed by Vinay Sajip in bpo-16613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16613}.)

@node colorsys,contextlib<6>,collections<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 colorsys}@anchor{1127}
@subsubsection colorsys


RGB --- YIQ 変換の係数の桁数が FCC NTSC version@footnote{https://en.wikipedia.org/wiki/YIQ#FCC_version_of_NTSC_standard} に合うように広げられました。結果としての変化は 1% 未満のはずで、また、ほかの処理系での結果とより合致するでしょう。 (Contributed by Brian Landers and Serhiy Storchaka in bpo-14323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14323}.)

@node contextlib<6>,dbm<6>,colorsys,改良されたモジュール<10>
@anchor{whatsnew/3 4 contextlib}@anchor{1128}
@subsubsection contextlib


新規コンテキストマネージャ @ref{1129,,contextlib.suppress} によって、意図して単独ステートメントからの例外を抑制しているというコードの意図をはっきりと読み手に伝えることが出来ます。 (Contributed by Raymond Hettinger in bpo-15806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15806} and Zero Piraeus in bpo-19266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19266}.)

新規コンテキストマネージャ @ref{fe7,,contextlib.redirect_stdout()} は、ユーティリティスクリプトにて、その出力を @ref{ccd,,sys.stdout} に書き出す一方でその向き先を変えれない頑固な API の扱いを簡単にしてくれます。これを使うと、 @ref{ccd,,sys.stdout} 出力をなにかほかのストリームに振り替えたり、あるいは @ref{112a,,io.StringIO} と組み合わせて文字列化したり出来ます。後者などは特に便利で、たとえば元々はコマンドラインインターフェイスとして実装された関数からの出力を取り込む、などということが出来ます。このコンテキストマネージャはユーティリティスクリプト以外では使わない方が肝要です。というのもこれは @ref{ccd,,sys.stdout} の大域的な状態に影響を与えてしまうからです。 (Contributed by Raymond Hettinger in bpo-15805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15805}.)

@ref{27,,contextlib} ドキュメントにも改善が行われ、コンテキストマネージャを単独で使うのと再利用したり再入可能(リエントラント)するのとの違いについての @ref{112b,,議論} が追加されました。

@node dbm<6>,dis<5>,contextlib<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 dbm}@anchor{112c}
@subsubsection dbm


@ref{112d,,dbm.open()} がコンテキスト管理プロトコルをサポートするようになりました: @ref{186,,with} ブロックで使うとデータベースオブジェクトの @code{close} メソッドがブロックの終了時に自動的に呼び出されます。 (Contributed by Claudiu Popa and Nick Coghlan in bpo-19282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19282}.)

@node dis<5>,doctest<4>,dbm<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 dis}@anchor{112e}
@subsubsection dis


関数 @ref{112f,,show_code()}, @ref{205,,dis()}, @ref{206,,distb()}, @ref{207,,disassemble()} が新たにキーワード専用引数 `file' を受け取ります。これは出力先を制御します。

@ref{3c,,dis} モジュールはいまでは @ref{203,,Instruction} クラスを中心に据えて構築されています。これは個々のバイトコード操作の詳細に対し、オブジェクト指向的なアクセスを提供するクラスです。

新規メソッド @ref{4ec,,get_instructions()} が、与えた Python コード片についての命令 (インストラクション) ストリームを発行するイテレータを提供します。これを使えば、@ref{3c,,dis} モジュール自身が提供しているのとは違った方法で、バイトコードオブジェクトを調べたり加工するようなプログラムを書くことが出来ます。例えばこのように書けます:

@example
>>> import dis
>>> for instr in dis.get_instructions(lambda x: x + 1):
...     print(instr.opname)
LOAD_FAST
LOAD_CONST
BINARY_ADD
RETURN_VALUE
@end example

@ref{3c,,dis} モジュールにある色々な表示ツールが、これらの新しい構成要素でもって書き直されました。

In addition, a new application-friendly class @ref{204,,Bytecode} provides
an object-oriented API for inspecting bytecode in both in human-readable form
and for iterating over instructions.  The @ref{204,,Bytecode} constructor
takes the same arguments that @ref{4ec,,get_instructions()} does (plus an
optional `current_offset'), and the resulting object can be iterated to produce
@ref{203,,Instruction} objects.  But it also has a @ref{1130,,dis}
method, equivalent to calling @ref{205,,dis} on the constructor argument, but
returned as a multi-line string:

@example
>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
>>> for instr in bytecode:
...     print('@{@} (@{@})'.format(instr.opname, instr.opcode))
LOAD_FAST (124)
LOAD_CONST (100)
BINARY_ADD (23)
RETURN_VALUE (83)
>>> bytecode.dis().splitlines()
['  1           0 LOAD_FAST                0 (x)',
 '      -->     3 LOAD_CONST               1 (1)',
 '              6 BINARY_ADD',
 '              7 RETURN_VALUE']
@end example

@ref{204,,Bytecode} にはクラスメソッド @ref{1131,,from_traceback()} もあります。トレースバックから @ref{204,,Bytecode} を構築します。(@code{print(Bytecode.from_traceback(tb).dis())} は @ref{206,,distb()} を使って @code{distb(tb)} とするのと同じです。)

(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in bpo-11816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11816}
and Claudiu Popa in bpo-17916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17916}.)

新規関数 @ref{1132,,stack_effect()} は与えられた opcode (命令コード) と引数の Python スタックへの effect を計算します。この情報は他からは得られません。 (Contributed by Larry Hastings in bpo-19722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19722}.) (---訳注: @code{PyCompile_OpcodeStackEffect} として C API として曝した上で Python からアクセス出来るようにしたものらしいです。 stackdepth_walk での使用箇所@footnote{https://hg.python.org/cpython/file/5fe72b9ed48e/Python/compile.c#l3838} 参照。---)

@node doctest<4>,email<5>,dis<5>,改良されたモジュール<10>
@anchor{whatsnew/3 4 doctest}@anchor{1133}
@subsubsection doctest


A new @ref{1134,,option flag}, @ref{1135,,FAIL_FAST}, halts
test running as soon as the first failure is detected.  (Contributed by R.
David Murray and Daniel Urban in bpo-16522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16522}.)

@ref{3e,,doctest} コマンドラインインターフェイスは @ref{7,,argparse} を使うようになりました。2 つの新オプション @code{-o} と @code{-f} が追加されています。 @code{-o} によりコマンドラインから @ref{1134,,doctest オプション} を指定することが出来ます。 @code{-f} は @code{-o FAIL_FAST} の速記法です (@ref{10c,,unittest} CLI でサポートされる似たオプション @ref{1136,,サポートされる同じオプション} に似せるためです)。 (Contributed by R. David Murray in bpo-11390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11390}.)

@ref{3e,,doctest} はいまや、拡張モジュールの @code{__doc__} 文字列から doctest を見つけることが出来ます。 (Contributed by Zachary Ware in bpo-3158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3158}.)

@node email<5>,filecmp,doctest<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 email}@anchor{1137}
@subsubsection email


@ref{1138,,as_string()} メソッドが、その文字列表現を生成するのに使うデフォルトポリシーを上書き出来る `policy' 引数を取るようになりました。つまり @ref{581,,Message} を作り直したり @code{flattern} メソッドの書式化パラメータのためだけに @ref{44,,generator} を使うことなしに、 @code{as_string} をより多くの状況で使えるということになります。(Contributed by R. David Murray in bpo-18600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18600}.)

@ref{1139,,as_bytes()} メソッドが追加されました。これは @code{as_string} が文字列表現を生成するのと似たやり方で、メッセージの bytes 表現を生成します。これは `maxheaderlen' 引数を取りませんが、 `unixfrom' 引数と `policy' 引数を取ります。 @ref{581,,Message} の @ref{113a,,__bytes__()} がこれを呼び出すようにしたので、 @code{bytes(mymsg)} は今や直感に反しない結果、つまり完全にフォーマットされたメッセージを生成します。(Contributed by R. David Murray in bpo-18600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18600}.)

@ref{113b,,Message.set_param()} メソッドにキーワード引数 `replace' が追加されました。真を渡すとヘッダリスト内のその位置を変更せずに関連ヘッダを更新します。後方互換のためにデフォルトは @code{False} です。 (Contributed by R. David Murray in bpo-18891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18891}.)
@anchor{whatsnew/3 4 whatsnew-email-contentmanager}@anchor{10e8}
サブモジュール @ref{41,,contentmanager} と @ref{53,,policy} 属性の @ref{113c,,content_manager} の追加と併せて、 @ref{581,,Message} の対となる二つのサブクラス (@ref{580,,EmailMessage} と @ref{113d,,MIMEPart}) が追加されました。
全てのドキュメントは、 email の新規 @ref{3d1,,暫定 API} の構成要素として追加されたこの新しいモジュールにあります。
これらのクラスは、 email メッセージからの内容抽出や挿入を遥かに簡単に行える、数多くの新規メソッドを提供しています。
詳細は @ref{41,,contentmanager} のドキュメントと @ref{113e,,email; 使用例} を参照してください。
これらの API の追加作業により email6 プロジェクトの一部として計画されていた作業は、その大部分が完了しました。
現在のところ、暫定 API 状態は Python 3.5 で最後となる予定です (可能性としてはエラー処理あたりのゾーンでは少々の些細な追加は残るかもしれません)。 (Contributed by R. David Murray in bpo-18891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18891}.)

@node filecmp,functools<6>,email<5>,改良されたモジュール<10>
@anchor{whatsnew/3 4 filecmp}@anchor{113f}
@subsubsection filecmp


@ref{1140,,clear_cache()} 関数が追加されました。 @ref{5e,,filecmp} は @ref{26d,,os.stat()} 情報をキャッシュして最後の比較時点からのファイルの変化をみていますが、このキャッシュをクリアします。これはたとえば、ファイルシステムのタイムスタンプフィールドの解像度未満の時間差で再比較したい場合に使えるでしょう。(Contributed by Mark Levitt in bpo-18149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18149}.)

New module attribute @ref{1141,,DEFAULT_IGNORES} provides the list of
directories that are used as the default value for the `ignore' parameter of
the @ref{1142,,dircmp()} function.  (Contributed by Eli Bendersky in
bpo-15442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15442}.)

@node functools<6>,gc<6>,filecmp,改良されたモジュール<10>
@anchor{whatsnew/3 4 functools}@anchor{1143}
@subsubsection functools


新たな @ref{218,,partialmethod()} デスクリプタは、ちょうど普通の callable に対して @ref{217,,partial()} がするように、デスクリプタへの引数部分適用を可能にします。この新しいデスクリプタをクラス定義内で使うと、簡単に (@ref{217,,partial()} インスタンスを含む) 任意の callable を普通のインスタンスメソッドのように振舞わせることも出来ます。(Contributed by Alon Horev and Nick Coghlan in bpo-4331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4331}.)
@anchor{whatsnew/3 4 whatsnew-singledispatch}@anchor{10e5}
新たな @ref{84b,,singledispatch()} デコレータは、Python 標準ライブラリにシングルディスパッチのジェネリック関数のサポートを追加します。オブジェクト指向プログラミングは共通データ集合についての複数操作をまとめあげてクラスに押し込めようとしますが、ジェネリック関数は `異なった' 種類のデータに対して動作させたい操作の複数実装をひとつにまとめあげる考え方です。(---訳注: ここで「ジェネリック関数」と呼んでいるものを他の言語との類推で理解しようとすると、「呼び出す側目線」では同じで、「呼び出される側」目線では違うかもしれません。例えば C++ ユーザは「template の特殊化」もしくは「型ごとのオーバロード」との類推で理解してください。---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 443

@item PEP 443@footnote{https://peps.python.org/pep-0443/} -- シングルディスパッチのジェネリック関数

PEP written and implemented by Łukasz Langa.
@end table


@ref{1144,,total_ordering()} now supports a return value of
@ref{1a2,,NotImplemented} from the underlying comparison function.  (Contributed
by Katie Miller in bpo-10042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10042}.)

@ref{217,,partial()} 関数のピュア Python 版が標準ライブラリに追加されました。CPython の場合は C による高速版で置き換えられますが、ほかの Python 実装で利用出来ます。 (Contributed by Brian Thorne in bpo-12428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12428}.)

@node gc<6>,glob<4>,functools<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 gc}@anchor{1145}
@subsubsection gc


新規関数 @ref{2dc,,get_stats()} は、インタプリタが開始してからの、世代ごと回収統計を持つ辞書の、3 世代ぶんのリストを返します。(Contributed by Antoine Pitrou in bpo-16351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16351}.)

@node glob<4>,hashlib<6>,gc<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 glob}@anchor{1146}
@subsubsection glob


新規関数 @ref{1147,,escape()} は、glob 的な展開がなされないようにして字句通りの合致をするように、ファイル名に含まれる特殊文字をエスケープする手段となります。(Contributed by Serhiy Storchaka in bpo-8402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8402}.)

@node hashlib<6>,hmac<4>,glob<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 hashlib}@anchor{1148}
@subsubsection hashlib


新たな関数 @ref{733,,hashlib.pbkdf2_hmac()} は PKCS#5 パスワードベースの鍵導出関数２@footnote{https://en.wikipedia.org/wiki/PBKDF2} を提供します。 (Contributed by Christian Heimes in bpo-18582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18582}.)

@ref{6c,,hashlib} のハッシュオブジェクトの @ref{1149,,name} 属性が、公式にサポートされるインターフェイスになりました。これは CPython の @ref{6c,,hashlib} には以前から存在していました (ただしサポートされるハッシュの名前を必ずしも小文字で返してはいませんでした) が、公開インターフェイスとしていなかったために、ほかのいくつかの Python 実装では以前はサポートされていませんでした。(Contributed by Jason R. Coombs in bpo-18532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18532}.)

@node hmac<4>,html,hashlib<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 hmac}@anchor{114a}
@subsubsection hmac


@ref{6e,,hmac} は、 @ref{c96,,new()} の `key' 引数として @code{bytearray} と @code{bytes} を許容するようになり、また、 @ref{c96,,new()} 関数と @ref{114b,,update()} メソッドの両方への `msg' パラメータとして、 @ref{6c,,hashlib} モジュールがサポートする任意の型を許容するようになりました。(Contributed by Jonas Borgström in bpo-18240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18240}.)

@ref{c96,,hmac.new()} 関数への `digestmod' 引数には、@ref{6c,,hashlib} が認識する任意のハッシュダイジェスト名を渡せるようになりました。これとともに、 `digestmod' のデフォルトとして @code{MD5} を使う現在の振る舞いは非推奨です。将来のバージョンの Python ではこれのデフォルト値はなくなり、指定が必須になります。 (Contributed by Christian Heimes in bpo-17276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17276}.)

@ref{114c,,block_size} 属性と @ref{114d,,name} 属性 (と @ref{114e,,digest_size} 属性の公式ドキュメント) の追加をもって、 @ref{6e,,hmac} モジュールは完全に 
@geindex Python Enhancement Proposals; PEP 247
PEP 247@footnote{https://peps.python.org/pep-0247/} API を遵守するものとなりました。 (Contributed by Christian Heimes in bpo-18775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18775}.)

@node html,http<4>,hmac<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 html}@anchor{114f}
@subsubsection html


新規関数 @ref{b50,,unescape()} は HTML5 文字参照を対応する Unicode 文字に変換します。 (Contributed by Ezio Melotti in bpo-2927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2927}.)

@ref{a77,,HTMLParser} が新規キーワード引数 `convert_charrefs' を受け取ります。これが @code{True} の場合に、全ての文字参照が自動的に変換されます。後方互換性の問題から今はこのデフォルトを @code{False} にしてありますが、将来バージョンの Python でこれを @code{True} に変えます。ですから値は明示的にセットしてこの新しい機能を使うように更新しておくと良いです。(Contributed by Ezio Melotti in bpo-13633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13633}.)

@ref{a77,,HTMLParser} の `strict' 引数が非推奨となりました。 (Contributed by Ezio Melotti in bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}.)

@node http<4>,idlelib と IDLE<4>,html,改良されたモジュール<10>
@anchor{whatsnew/3 4 http}@anchor{1150}
@subsubsection http


@ref{1151,,send_error()} 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
@ref{1152,,error_message_format} attribute
and sent as the body of the error response.
(Contributed by Karl Cow in bpo-12921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12921}.)

@ref{76,,http.server} の @ref{1153,,コマンドラインインターフェイス} に @code{-b/--bind} オプションが追加されました。これは特定のアドレスで listen することを指示します。 (Contributed by Malte Swart in bpo-17764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17764}.) (---訳注: ネットワークプログラミングに詳しい人ほど混乱しそうなので一応。 @code{--bind} というオプション名が示すとおり、より正確に表現するなら「ユーザ指定のネットワークインターフェイスに bind」。コミットログの表現「Expose --bind argument for http.server, enable http.server to bind to a user specified network interface.」の方がわかりやすいかと。  ---)

@node idlelib と IDLE<4>,importlib<9>,http<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 idlelib-and-idle}@anchor{1154}
@subsubsection idlelib と IDLE


idlelib は IDLE シェルとエディタを実装するものであってほかのプログラムからインポートされることを意図してはいないので、改善は毎度のリリースごとに行われます。3.3.0 から始まり、また将来の 3.4.x リリースになされる累積的な変更リストは @code{Lib/idlelib/NEWS.txt} で読むことが出来ます。このファイルは IDLE で Help ‣ About IDLE からも辿り着けます。

@node importlib<9>,inspect<9>,idlelib と IDLE<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 importlib}@anchor{1155}
@subsubsection importlib


@ref{1156,,InspectLoader} ABC に新規メソッド @ref{1012,,source_to_code()} が追加されました。ソースデータとパスを受け取り、コードオブジェクトを返します。これのデフォルト実装は @code{compile(data, path, 'exec', dont_inherit=True)} と同じです。 (Contributed by Eric Snow and Brett Cannon in bpo-15627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15627}.)

@ref{1156,,InspectLoader} では @ref{1157,,get_code()} メソッドへのデフォルト実装追加も行われました。とはいえ性能面の理由より、通常はデフォルト実装をオーバライドすることが望ましいです。 (Contributed by Brett Cannon in bpo-18072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18072}.)

The @ref{73d,,reload()} function has been moved from @code{imp} to
@ref{7b,,importlib} as part of the @code{imp} module deprecation.  (Contributed by
Berker Peksag in bpo-18193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18193}.)

@ref{81,,importlib.util} now has a @ref{737,,MAGIC_NUMBER} attribute
providing access to the bytecode version number.  This replaces the
@code{get_magic()} function in the deprecated @code{imp} module.
(Contributed by Brett Cannon in bpo-18192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18192}.)

New @ref{81,,importlib.util} functions @ref{353,,cache_from_source()}
and @ref{73e,,source_from_cache()} replace the same-named functions
in the deprecated @code{imp} module.  (Contributed by Brett Cannon in
bpo-18194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18194}.)

@ref{7b,,importlib} ブートストラップ @ref{1158,,NamespaceLoader} が @ref{1156,,InspectLoader} ABC に従うようになりました。つまりこれにより @code{runpy} と @code{python -m} が名前空間パッケージに対して使えるようになりました。(Contributed by Brett Cannon in bpo-18058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18058}.)  (訳注: 3.3 以降の名前空間パッケージについては What's New In Python 3.3 (
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/}) 参照。)

@ref{81,,importlib.util} に @ref{1159,,decode_source()} 関数が追加されました。 @ref{f35,,universal newlines} 処理を使って bytes からソースをデコードします。 @ref{115a,,InspectLoader.get_source()} メソッドを実装するのに便利です。

@ref{eae,,importlib.machinery.ExtensionFileLoader} に @ref{115b,,get_filename()} メソッドが追加されました。これは本来実装されるべきものでしたが見落とされていました。(Contributed by Eric Snow in bpo-19152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19152}.)

@node inspect<9>,ipaddress<5>,importlib<9>,改良されたモジュール<10>
@anchor{whatsnew/3 4 inspect}@anchor{115c}
@subsubsection inspect


@ref{82,,inspect} モジュールに、ソースコードおよびモジュール・クラス・関数についてのその他情報を手早く表示するための、基礎的な @ref{115d,,コマンドラインインターフェイス} が追加されました。  (Contributed by Claudiu Popa and Nick Coghlan in bpo-18626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18626}.)

新規の @ref{115e,,unwrap()} で、 @ref{115f,,functools.wraps()} (やラッパー関数に @code{__wrapped__} 属性をセットするその他 API) で作られたラッパー関数のチェインを、簡単にほどくことが出来ます。 (Contributed by Daniel Urban, Aaron Iles and Nick Coghlan in bpo-13266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13266}.) (---訳注: 「簡単に」の意味するところについて、 @ref{110e,,Python API の変更} に記述されている @code{functools.update_wrapper()} と @code{functools.wraps()} の変更も参照して下さい。---)

新規 @ref{5a,,enum} モジュールが実装されたことを受け @ref{82,,inspect} モジュールは、カスタム @code{__dir__} メソッドに対する、またメタクラスを介して提供される動的クラス属性に対する、ずっと良いサポートを提供出来るようになりました。 (Contributed by Ethan Furman in bpo-18929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18929} and bpo-19030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19030}.)

@ref{941,,getfullargspec()} and @code{getargspec()}
now use the @ref{22f,,signature()} API. This allows them to
support a much broader range of callables, including those with
@code{__signature__} attributes, those with metadata provided by argument
clinic, @ref{217,,functools.partial()} objects and more. Note that, unlike
@ref{22f,,signature()}, these functions still ignore @code{__wrapped__}
attributes, and report the already bound first argument for bound methods,
so it is still necessary to update your code to use
@ref{22f,,signature()} directly if those features are desired.
(Contributed by Yury Selivanov in bpo-17481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17481}.)

@ref{22f,,signature()} が CPython 関数のダックタイプをサポートするようになりました。これは Cython でコンパイルされた関数をサポートすることになります。 (Contributed by Stefan Behnel and Yury Selivanov in bpo-17159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17159}.) (---訳注: duck type はここでは「 @code{types.FunctionType} であることを要求しない」の意味。 _signature_is_functionlike@footnote{https://hg.python.org/cpython/file/32a660a52aae/Lib/inspect.py#l1604} 参照。 ---)

@node ipaddress<5>,logging<6>,inspect<9>,改良されたモジュール<10>
@anchor{whatsnew/3 4 ipaddress}@anchor{1160}
@subsubsection ipaddress


@ref{84,,ipaddress} は Python 3.3 で標準ライブラリに @ref{3d1,,暫定 API} として追加されました。Python 3.4 リリースで、この但し書きは削除されました: @ref{84,,ipaddress} は今や安定 API とみなされ、今後は通常の標準ライブラリの後方互換性維持要件に従います。

新規のプロパティ @ref{1161,,is_global} は、アドレスが routeable である場合に @code{True} を返します。 (Contributed by Peter Moody in bpo-17400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17400}.) (---訳注: リファレンスマニュアルでは routeable という表現ではなく「アドレスがパブリックネットワークに割り当てられている場合」。---)

@node logging<6>,marshal<2>,ipaddress<5>,改良されたモジュール<10>
@anchor{whatsnew/3 4 logging}@anchor{1162}
@subsubsection logging


@ref{1163,,TimedRotatingFileHandler} に `atTime' パラメータが追加されました。ロールオーバ対象となる日付での時刻を指定します。 (Contributed by Ronald Oussoren in bpo-9556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9556}.)

@ref{1164,,SocketHandler} と @ref{1165,,DatagramHandler} が Unix ドメインソケットをサポートするようになりました (`port' に @code{None} をセットすることで)。 (Contributed by Vinay Sajip in commit ce46195b56a9@footnote{https://hg.python.org/cpython/rev/ce46195b56a9} .)

@ref{d48,,fileConfig()} が `fname' パラメータとして @ref{1166,,configparser.RawConfigParser} のサブクラスを許容するようになりました。これはロギングの設定がアプリケーション全体の設定の一部に過ぎない場合や、 @ref{d48,,fileConfig()} に渡す前にアプリケーションが設定を修正するような場合でも設定ファイルを使用することを容易にします。(Contributed by Vinay Sajip in bpo-16110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16110}.)

@ref{1167,,logging.config.listen()} 関数経由でソケットから受信したロギング設定データを、処理前に検証出来るようになりました。新規のキーワード引数 `verify' に検証関数を渡すことで可能です。(Contributed by Vinay Sajip in bpo-15452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15452}.)

@node marshal<2>,mmap<3>,logging<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 marshal}@anchor{1168}@anchor{whatsnew/3 4 whatsnew-marshal-3}@anchor{10dd}
@subsubsection marshal


@ref{91,,marshal} のバージョンが 3 に上げられました。新バージョンを実装しているコードは、intern された文字列をただ一つのコピーだけ記録しておきデシリアライズでその intern を維持するという Python 2 での振舞いを復活させつつ、「ただ一つのコピー」を文字列型のみならず任意のオブジェクト型に (再帰参照の処理も含め) 拡張しています。これは @code{.pyc} ファイルのサイズを削減し、また、 @code{.pyc} (または @code{.pyo}) ファイルからロードされる際にモジュールが占めるメモリ量を削減します。(Contributed by Kristján Valur Jónsson in bpo-16475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16475}, with additional speedups by Antoine Pitrou in bpo-19219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19219}.)

@node mmap<3>,multiprocessing<8>,marshal<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 mmap}@anchor{1169}
@subsubsection mmap


mmap objects are now @ref{110d,,weakly referenceable}.
(Contributed by Valerie Lambert in bpo-4885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4885}.)

@node multiprocessing<8>,operator<4>,mmap<3>,改良されたモジュール<10>
@anchor{whatsnew/3 4 multiprocessing}@anchor{116a}
@subsubsection multiprocessing

@anchor{whatsnew/3 4 whatsnew-multiprocessing-no-fork}@anchor{10e7}
@ref{98,,multiprocessing} を使ってプロセスを開始する @ref{1d5,,開始方式} として、Unix において 2 つ、 @code{spawn} と @code{forkserver} が追加されました。これらはスレッドとプロセスのミックスをより堅牢にし、また、 @code{spawn} は multiprocessing が以前から常に Windows で使ってきたセマンティクスと一致します。新規関数の、 @ref{116b,,get_all_start_methods()} はプラットフォームで利用出来るすべての開始方式を報告し、 @ref{116c,,get_start_method()} は現在設定されている開始方式を報告し、 @ref{24b,,set_start_method()} は開始方式を設定します。(Contributed by Richard Oudkerk in bpo-8713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8713}.)

@ref{98,,multiprocessing} には、子プロセスがどのように作られるかを決定する @code{context} のコンセプトが追加されています。新規関数 @ref{24a,,get_context()} は指定した開始方式を使うコンテキストを返します。コンテキストは @ref{98,,multiprocessing} モジュール自身と同じ API を持っているので、コンテキスト内で操作する @ref{116d,,Pool} や他のオブジェクトを、それを使って作成することが出来ます。コンテキストによって、フレームワークとアプリケーションあるいは同じアプリケーションの別の部分が相互に干渉しあわないようにして multiprocessing を使うことが出来ます。(Contributed by Richard Oudkerk in bpo-18999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18999}.)

昔からの `fork' 開始方式を除き、子プロセスはもはや必要のないハンドル・ファイル記述子をその親から継承しません。 (part of bpo-8713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8713}).

@ref{98,,multiprocessing} が開始方式に @code{spawn} または @code{forkserver} を使う場合に、子プロセスで適切に @code{__main__} を初期化するために @ref{c3,,runpy} (これが @code{-m} スイッチを実装しています) に頼るようになりました。これは、 multiprocessing と @code{-m} コマンドラインスイッチ・明示的な相対インポートを組み合わせると子プロセスが不可解に失敗していたような、いくつかの際どい問題を解決します。 (Contributed by Nick Coghlan in bpo-19946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19946}.)

@node operator<4>,os<12>,multiprocessing<8>,改良されたモジュール<10>
@anchor{whatsnew/3 4 operator}@anchor{116e}
@subsubsection operator


新規関数 @ref{116f,,length_hint()} は、言語仕様となった特殊メソッド @ref{110f,,__length_hint__()} の 
@geindex Python Enhancement Proposals; PEP 424
PEP 424@footnote{https://peps.python.org/pep-0424/} 公式仕様の一環として、それがどのように使われるのかについて詳述する実装を提供します。(Contributed by Armin Ronacher in bpo-16148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16148}.)

参照実装として、また Python 実装の代替として用いることが出来る、 @ref{a3,,operator} モジュールのピュア Python 版が書かれました。 (Contributed by Zachary Ware in bpo-16694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16694}.)

@node os<12>,pdb<8>,operator<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 os}@anchor{1170}
@subsubsection os


新規関数により @ref{10fc,,継承可能フラグ} を制御出来るようになりました。ファイル記述子には @ref{10fd,,os.get_inheritable()}, @ref{10fe,,os.set_inheritable()} を、Windows のハンドルには @ref{10ff,,os.get_handle_inheritable()}, @ref{1100,,os.set_handle_inheritable()} を使います。

関数 @ref{4db,,cpu_count()} が追加されました。これは Python を実行しているプラットフォームで利用可能な CPU 数を返します (決定できない場合は @code{None} を返します)。既存の @ref{1171,,multiprocessing.cpu_count()} はこの関数の値を返すようになりました。(Contributed by Trent Nelson, Yogesh Chaudhari, Victor Stinner, and Charles-François Natali in bpo-17914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17914}.)

@ref{1172,,os.path.samestat()} が Windows プラットフォームでも動作するようになりました (また、 @ref{1173,,os.path.samefile()} の実装は Unix と Windows で共有されました)。 (Contributed by Brian Curtin in bpo-11939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11939}.)

@ref{c07,,os.path.ismount()} が Windows において、ドライブルートよりも下にあるマウントポイントを認識するようになりました。  (Contributed by Tim Golden in bpo-9035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9035}.)

@ref{f92,,os.open()} supports two new flags on platforms that provide them,
@ref{1174,,O_PATH} (un-opened file descriptor), and @ref{1175,,O_TMPFILE}
(unnamed temporary file; as of 3.4.0 release available only on Linux systems
with a kernel version of 3.11 or newer that have uapi headers).  (Contributed
by Christian Heimes in bpo-18673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18673} and Benjamin Peterson, respectively.)

@node pdb<8>,pickle<5>,os<12>,改良されたモジュール<10>
@anchor{whatsnew/3 4 pdb}@anchor{1176}
@subsubsection pdb


@ref{aa,,pdb} が、ジェネレータ、 @ref{bc2,,yield} 、 @code{yield from} をより価値ある方法で処理するように強化されました。これは @ref{b,,asyncio} ベースのプログラムをデバッグする際にとりわけ助けとなります。 (Contributed by Andrew Svetlov and Xavier de Gaye in bpo-16596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16596}.)

@ref{aa,,pdb} から @code{print} コマンドは削除され、pdb コマンドラインからの Python @ref{1177,,print()} 関数へのアクセスを取り戻しました。 Python 2 の @code{pdb} には @code{print} コマンドはなく @code{print} の入力は Python 2 の @code{print} 文を実行していました。 Python 3 で pdb の @ref{1178,,p} コマンドへのエイリアスとして @code{print} を作ったのが間違いでした。 @code{p} はその引数の @code{repr} を表示するのであって、Python 2 での @code{print} コマンドがしていた @code{str} を表示するのではありません。さらに悪いことに、Python 3 の @code{pdb print} コマンドは Python 3 の @code{print} 関数を隠してしまい、 @code{pdb} プロンプトからのアクセスを出来なくしていたのでした。 (Contributed by Connor Osborn in bpo-18764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18764}.)

@node pickle<5>,plistlib<2>,pdb<8>,改良されたモジュール<10>
@anchor{whatsnew/3 4 pickle}@anchor{1179}@anchor{whatsnew/3 4 whatsnew-protocol-4}@anchor{10e6}
@subsubsection pickle


@ref{ab,,pickle} now supports (but does not use by default) a new pickle protocol,
protocol 4.  This new protocol addresses a number of issues that were present
in previous protocols, such as the serialization of nested classes, very large
strings and containers, and classes whose @ref{7a0,,__new__()} method takes
keyword-only arguments.  It also provides some efficiency improvements.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3154

@item PEP 3154@footnote{https://peps.python.org/pep-3154/} -- Pickle プロトコル 4

PEP written by Antoine Pitrou and implemented by Alexandre Vassalotti.
@end table


@node plistlib<2>,poplib<3>,pickle<5>,改良されたモジュール<10>
@anchor{whatsnew/3 4 plistlib}@anchor{117a}
@subsubsection plistlib


@ref{b0,,plistlib} now has an API that is similar to the standard pattern for
stdlib serialization protocols, with new @ref{b48,,load()},
@ref{b4a,,dump()}, @ref{b49,,loads()}, and @ref{b4b,,dumps()}
functions.  (The older API is now deprecated.)  In addition to the already
supported XML plist format (@ref{117b,,FMT_XML}), it also now supports
the binary plist format (@ref{117c,,FMT_BINARY}).  (Contributed by Ronald
Oussoren and others in bpo-14455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14455}.)

@node poplib<3>,pprint<4>,plistlib<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 poplib}@anchor{117d}
@subsubsection poplib


@ref{b1,,poplib} に 2 つの新規メソッドが追加されました。 @ref{117e,,capa()} は POP サーバにより公表された機能リストを返します。 @ref{117f,,stls()} は平文 POP3 セッションを、POP サーバがサポートしていれば暗号化された POP3 セッションに切り替えます。 (Contributed by Lorenzo Catucci in bpo-4473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4473}.)

@node pprint<4>,pty<2>,poplib<3>,改良されたモジュール<10>
@anchor{whatsnew/3 4 pprint}@anchor{1180}
@subsubsection pprint


@ref{b3,,pprint} モジュールの、 @ref{1181,,PrettyPrinter} クラス、 @ref{1182,,pformat()} 関数、 @ref{a29,,pprint()} 関数に、新規オプション `compact' が追加されました。これは出力方法を制御するもので、今のところのこれの @code{True} での振舞いは、個々の (インデントされた) 行を `width' 幅で出来るだけ多くのシーケンスの要素が収まるように出力します。 (Contributed by Serhiy Storchaka in bpo-19132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19132}.)

長い文字列が Python の普通の行継続構文で折り返されるようになりました。 (Contributed by Antoine Pitrou in bpo-17150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17150}.)

@node pty<2>,pydoc<5>,pprint<4>,改良されたモジュール<10>
@anchor{whatsnew/3 4 pty}@anchor{1183}
@subsubsection pty


@ref{1184,,pty.spawn()} が @code{None} ではなく @ref{f9a,,os.waitpid()} からの戻り値から取ったステータス値を返すようになりました。 (Contributed by Gregory P. Smith.)

@node pydoc<5>,re<9>,pty<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 pydoc}@anchor{1185}
@subsubsection pydoc


@ref{ba,,pydoc} モジュールがイントロスペクション API @ref{22f,,inspect.signature()} に直接基くようになりました。これによりより幅広く callable オブジェクトのシグニチャ情報を提供出来るようになりました。この変更は、ヘルプ情報表示の際に @code{__wrapped__} 属性も考慮に入れられることも意味しています。(Contributed by Larry Hastings in bpo-19674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19674}.)

@ref{ba,,pydoc} モジュールはもはや既に束縛済みのメソッドでは @code{self} パラメータを表示しません。それよりも、与えられた callable の正確な現在のシグニチャを常に表示しようとします。 (Contributed by Larry Hastings in bpo-20710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20710}.)

@ref{ba,,pydoc} に直接なされた変更に加え、背後の @ref{82,,inspect} モジュールの改善が、カスタム @code{__dir__} メソッドやさまざまなデスクリプタの扱いについての振る舞いの大幅な改善に寄与しました。

組み込み @ref{ad4,,help()} は @ref{ba,,pydoc} モジュールに基いているので、上記変更は @ref{ad4,,help()} の振る舞いにも影響します。

@node re<9>,resource,pydoc<5>,改良されたモジュール<10>
@anchor{whatsnew/3 4 re}@anchor{1186}
@subsubsection re


New @ref{1187,,fullmatch()} function and @ref{1188,,Pattern.fullmatch()} method anchor
the pattern at both ends of the string to match.  This provides a way to be
explicit about the goal of the match, which avoids a class of subtle bugs where
@code{$} characters get lost during code changes or the addition of alternatives
to an existing regular expression.  (Contributed by Matthew Barnett in
bpo-16203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16203}.)

@ref{1189,,正規表現オブジェクト} の repr にパターンとフラグを含めるようになりました。 @ref{118a,,match オブジェクト} の repr に start、end と合致した部分文字列を含むようになりました。 (Contributed by Hugo Lopes Tavares and Serhiy Storchaka in bpo-13592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13592} and bpo-17087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17087}.)

@node resource,select,re<9>,改良されたモジュール<10>
@anchor{whatsnew/3 4 resource}@anchor{118b}
@subsubsection resource


新規関数 @ref{118c,,prlimit()} は、指定プロセスのリソースリミットの問い合わせとセットを、一度の呼び出しで行えます。カーネルバージョン 2.6.36 以降で glibc 2.13 以降の Linux プラットフォームで利用可能です。 (Contributed by Christian Heimes in bpo-16595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16595}.)

On Linux kernel version 2.6.36 or later, there are also some new
Linux specific constants: @ref{118d,,RLIMIT_MSGQUEUE},
@ref{118e,,RLIMIT_NICE}, @ref{118f,,RLIMIT_RTPRIO},
@ref{1190,,RLIMIT_RTTIME}, and @ref{1191,,RLIMIT_SIGPENDING}.
(Contributed by Christian Heimes in bpo-19324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19324}.)

On FreeBSD version 9 and later, there some new FreeBSD specific constants:
@ref{1192,,RLIMIT_SBSIZE}, @ref{1193,,RLIMIT_SWAP}, and
@ref{1194,,RLIMIT_NPTS}.  (Contributed by Claudiu Popa in
bpo-19343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19343}.)

@node select,shelve<2>,resource,改良されたモジュール<10>
@anchor{whatsnew/3 4 select}@anchor{1195}
@subsubsection select


@ref{1196,,epoll} がコンテキスト管理プロトコルをサポートするようになりました: @ref{186,,with} ブロックで使うと  @ref{1197,,close()} メソッドがブロックの終了時に自動的に呼び出されます。 (Contributed by Serhiy Storchaka in bpo-16488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16488}.)

@ref{1198,,devpoll} オブジェクトに、メソッド @ref{1199,,fileno()} とメソッド @ref{119a,,close()} 、それに属性 @ref{119b,,closed} が追加されました。 (Contributed by Victor Stinner in bpo-18794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18794}.)

@node shelve<2>,shutil<6>,select,改良されたモジュール<10>
@anchor{whatsnew/3 4 shelve}@anchor{119c}
@subsubsection shelve


@ref{119d,,Shelf} がコンテキスト管理プロトコルをサポートするようになりました: @code{with} ブロックで使うとブロックの終了時に自動的にクローズされます。 (Contributed by Filip Gruszczyński in bpo-13896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13896}.)

@node shutil<6>,smtpd<3>,shelve<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 shutil}@anchor{119e}
@subsubsection shutil


@ref{c4e,,copyfile()} が、コピー元とコピー先が同じファイルの場合に @ref{119f,,Error} の限定されたサブクラスである @ref{11a0,,SameFileError} を投げるようになりました。これにより、アプリケーションはこの特定のエラーでそれに相応しいアクションを取れます。 (Contributed by Atsuo Ishimoto and Hynek Schlawack in bpo-1492704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1492704}.)

@node smtpd<3>,smtplib<3>,shutil<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 smtpd}@anchor{11a1}
@subsubsection smtpd


The @code{SMTPServer} and @code{SMTPChannel} classes now
accept a `map' keyword argument which, if specified, is passed in to
@code{asynchat.async_chat} as its `map' argument.  This allows an application
to avoid affecting the global socket map.  (Contributed by Vinay Sajip in
bpo-11959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11959}.)

@node smtplib<3>,socket<10>,smtpd<3>,改良されたモジュール<10>
@anchor{whatsnew/3 4 smtplib}@anchor{11a2}
@subsubsection smtplib


@ref{11a3,,SMTPException} が @ref{2c0,,OSError} のサブクラスになりました。これによって、とにかくエラーが起こったのだということにしか関心がないコードが、ソケット階層でのエラーと SMTP プロトコル階層の両エラーを一撃の try/except 文で捕捉出来るようになりました。 (Contributed by Ned Jackson Lovely in bpo-2118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2118}.)

@node socket<10>,sqlite3<10>,smtplib<3>,改良されたモジュール<10>
@anchor{whatsnew/3 4 socket}@anchor{11a4}
@subsubsection socket


The socket module now supports the @ref{11a5,,CAN_BCM} protocol on
platforms that support it.  (Contributed by Brian Thorne in bpo-15359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15359}.)

ソケットオブジェクトで @ref{10fc,,継承可能フラグ} を制御出来るようになりました。 @ref{1101,,get_inheritable()} で取得し、 @ref{1102,,set_inheritable()} でセットします。

定数値の @code{socket.AF_*} と @code{socket.SOCK_*} が、新規の @ref{5a,,enum} モジュールを使った列挙値になりました。つまりデバッグなどで魑魅魍魎な整数ではなく徳高い名前で表示されるということです。

The @ref{11a6,,AF_LINK} constant is now available on BSD and OSX.

@ref{b5b,,inet_pton()} と @ref{11a7,,inet_ntop()} が Windows でサポートされるようになりました。 (Contributed by Atsuo Ishimoto in bpo-7171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7171}.)

@node sqlite3<10>,ssl<11>,socket<10>,改良されたモジュール<10>
@anchor{whatsnew/3 4 sqlite3}@anchor{11a8}
@subsubsection sqlite3


@ref{5a6,,connect()} 関数に新規の真偽値パラメータ `uri' が追加されました。これを真にセットすると `database' パラメータを URI として解釈させることが出来ます。 (SQLite の URI のドキュメント@footnote{https://www.sqlite.org/uri.html} を参照してください)。 (Contributed by poq in bpo-13773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13773}.)

@node ssl<11>,stat,sqlite3<10>,改良されたモジュール<10>
@anchor{whatsnew/3 4 ssl}@anchor{11a9}
@subsubsection ssl

@anchor{whatsnew/3 4 whatsnew-tls-11-12}@anchor{10ea}
@ref{11aa,,PROTOCOL_TLSv1_1} と @ref{11ab,,PROTOCOL_TLSv1_2} (TLSv1.1 と TLSv1.2 のサポート) が追加されました。これらプロトコルのサポートは Python が OpenSSL 1.0.1 以降とリンクしている場合にのみ利用可能です。 (Contributed by Michele Orrù and Antoine Pitrou in bpo-16692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16692}.)
@anchor{whatsnew/3 4 whatsnew34-sslcontext}@anchor{10ed}
新規関数 @ref{480,,create_default_context()} は、互換性とセキュリティの間の程よいバランスとなるよう調整された @ref{357,,SSLContext} を得るための標準手段として追加されました。それらの設定は @ref{357,,SSLContext} コンストラクタが与えるデフォルトよりも厳しく、そして将来的にセキュリティにおけるベストプラクティスによる要請が変化すれば、事前予告なしで調整されるかもしれません。SSL をサポートする標準ライブラリの使用においての新しいベストプラクティスとして、 @ref{357,,SSLContext} を得るのには @ref{480,,create_default_context()} を使うことが推奨です。必要に応じ、対応する標準ライブラリ API の `context' 引数に渡すためにそれを使うよう修正してください。(Contributed by Christian Heimes in bpo-19689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19689}.)

@ref{357,,SSLContext} のメソッド @ref{10ee,,load_verify_locations()} にオプショナル引数 `cadata' が追加されました。これには PEM あるいは DER エンコードの証明書を直接指定できます。前者の場合は文字列で、後者では @ref{193,,bytes-like object} で指定します。(Contributed by Christian Heimes in bpo-18138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18138}.)

関数 @ref{11ac,,get_default_verify_paths()} が追加されました。これは @ref{11ad,,set_default_verify_paths()} メソッドが OpenSSL デフォルトの @code{cafile} と @code{capath} をセットするのに使うパスと環境変数から成る名前付きタプルを返します。デフォルトの検証にまつわる問題をデバッグするのに使えるでしょう。(Contributed by Christian Heimes in bpo-18143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18143}.)

@ref{357,,SSLContext} の新規メソッド @ref{11ae,,cert_store_stats()} はロードされた @code{X.509} 証明書、 @code{X.509 CA} 証明書、証明書失効リスト (@code{crl}) を報告し、また、新規メソッド @ref{11af,,get_ca_certs()} はロードされた @code{CA} 証明書のリストを返します。(Contributed by Christian Heimes in bpo-18147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18147}.)

If OpenSSL 0.9.8 or later is available, @ref{357,,SSLContext} has a new
attribute @ref{11b0,,verify_flags} that can be used to control the
certificate verification process by setting it to some combination of the new
constants @ref{11b1,,VERIFY_DEFAULT}, @ref{11b2,,VERIFY_CRL_CHECK_LEAF},
@ref{11b3,,VERIFY_CRL_CHECK_CHAIN}, or @ref{551,,VERIFY_X509_STRICT}.
OpenSSL does not do any CRL verification by default.  (Contributed by
Christien Heimes in bpo-8813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8813}.)

@ref{357,,SSLContext} の新規メソッド @ref{11b4,,load_default_certs()} は、プラットフォームによって異なるデフォルトの場所から “認証局” (CA=certification authority) 証明書ファイル一式をロードします。クライアントがサーバを検証するための TLS web サーバ証明の証明書をロード (@code{purpose=}@ref{11b5,,SERVER_AUTH}) することも、サーバがクライアント証明書を検証するのに用いる証明書をロード (@code{purpose=}@ref{11b6,,CLIENT_AUTH}) することも出来ます。(Contributed by Christian Heimes in bpo-19292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19292}.)
@anchor{whatsnew/3 4 whatsnew34-win-cert-store}@anchor{10eb}
Windows だけで利用出来る関数が 2 つ追加されました。 @ref{11b7,,enum_certificates()} と @ref{11b8,,enum_crls()} で Windows のシステム証明書ストアから、証明書、証明書の情報、CRLs (certification revocation=証明書失効リスト) を抽出出来ます。(Contributed by Christian Heimes in bpo-17134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17134}.)
@anchor{whatsnew/3 4 whatsnew34-sni}@anchor{10ec}
新規メソッド @ref{11b9,,ssl.SSLContext.set_servername_callback()} によるサーバサイド SNI (Server Name Indication) サポートが追加されました。 (Contributed by Daniel Black in bpo-8109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8109}.)

@ref{11ba,,SSLSocket.getpeercert()} が返す辞書に @code{X509v3} 拡張アイテムを含むようになりました: @code{crlDistributionPoints}, @code{caIssuers}, @code{OCSP} URI。 (Contributed by Christian Heimes in bpo-18379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18379}.)

@node stat,struct<3>,ssl<11>,改良されたモジュール<10>
@anchor{whatsnew/3 4 stat}@anchor{11bb}
@subsubsection stat


The @ref{d6,,stat} module is now backed by a C implementation in @code{_stat}. A C
implementation is required as most of the values aren't standardized and
are platform-dependent.  (Contributed by Christian Heimes in bpo-11016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11016}.)

The module supports new @ref{11bc,,ST_MODE} flags, @ref{11bd,,S_IFDOOR},
@ref{11be,,S_IFPORT}, and @ref{11bf,,S_IFWHT}.  (Contributed by
Christian Hiemes in bpo-11016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11016}.)

@node struct<3>,subprocess<5>,stat,改良されたモジュール<10>
@anchor{whatsnew/3 4 struct}@anchor{11c0}
@subsubsection struct


関数 @ref{11c1,,iter_unpack} と、コンパイル済フォーマットでのメソッド @ref{11c2,,struct.Struct.iter_unpack()} が追加されました。これは、与えられたデータフォーマットの繰り返しインスタンスを含むバッファを逐次的にアンパックします。 (Contributed by Antoine Pitrou in bpo-17804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17804}.)

@node subprocess<5>,sunau<2>,struct<3>,改良されたモジュール<10>
@anchor{whatsnew/3 4 subprocess}@anchor{11c3}
@subsubsection subprocess


@ref{11c4,,check_output()} が `input' 引数を受け付けるようになりました。これは実行するコマンドにとっての @code{stdin} を供給するのに使われます (訳注: @ref{d7f,,run()} のドキュメント参照)。 (Contributed by Zack Weinberg in bpo-16624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16624}.)

@ref{11c5,,getoutput()} and @ref{11c6,,getstatusoutput()} now
work on Windows.  This change was actually inadvertently made in 3.3.4.
(Contributed by Tim Golden in bpo-10197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10197}.)

@node sunau<2>,sys<12>,subprocess<5>,改良されたモジュール<10>
@anchor{whatsnew/3 4 sunau}@anchor{11c7}
@subsubsection sunau


The @code{getparams()} method now returns a namedtuple rather than a
plain tuple.  (Contributed by Claudiu Popa in bpo-18901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18901}.)

@code{sunau.open()} now supports the context management protocol: when used in a
@ref{186,,with} block, the @code{close} method of the returned object will be
called automatically at the end of the block.  (Contributed by Serhiy Storchaka
in bpo-18878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18878}.)

@code{AU_write.setsampwidth()} now supports 24 bit samples, thus adding
support for writing 24 sample using the module.  (Contributed by
Serhiy Storchaka in bpo-19261@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19261}.)

The @code{writeframesraw()} and
@code{writeframes()} methods now accept any @ref{193,,bytes-like object}.  (Contributed by Serhiy Storchaka in bpo-8311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8311}.)

@node sys<12>,tarfile<8>,sunau<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 sys}@anchor{11c8}
@subsubsection sys


新規関数 @ref{11c9,,sys.getallocatedblocks()} は、現在インタプリタによりアロケートされているブロック数を返します (デフォルトの @code{--with-pymalloc} 設定での CPython では、これは @ref{e62,,PyObject_Malloc()} API によるアロケーションです)。これはメモリリークの追跡に、とりわけテストスイートで自動化されている場合はなおさら有用です。 (Contributed by Antoine Pitrou in bpo-13390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13390}.)

Python インタプリタが @ref{443,,対話モード} で開始する際に @ref{df,,sys} モジュールの属性 @ref{11ca,,__interactivehook__} をチェックするようになりました。この属性があると、対話モード開始直前にその設定値が引数なしで呼び出されます。このチェックは 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} ファイルが読み込まれたあとで行われるので、そのファイル内でセット出来ます。 @ref{cc,,site} モジュールは @ref{bf,,readline} をサポートするプラットフォームではタブ補完と (@code{~/.python-history} への) 履歴保存を有効にする関数を @ref{11cb,,__interactivehook__ にセットします} 。この (新たな) 振る舞いがお気に召さなければ、 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP}, @ref{cd,,sitecustomize}, @ref{114,,usercustomize} のいずれかで @ref{df,,sys} からこの属性を削除 (あるいはほかのなにか callable をセット) してください。 (Contributed by Éric Araujo and Antoine Pitrou in bpo-5845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5845}.)

@node tarfile<8>,textwrap<2>,sys<12>,改良されたモジュール<10>
@anchor{whatsnew/3 4 tarfile}@anchor{11cc}
@subsubsection tarfile


@ref{e4,,tarfile} モジュールはスクリプトや直接 @code{-m} で呼ばれた場合、簡単な @ref{11cd,,コマンドラインインターフェイス} をサポートするようになりました。
これにより tar ファイルアーカイブの作成や解凍が可能です。
(Contributed by Berker Peksag in bpo-13477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13477}.)

@node textwrap<2>,threading<8>,tarfile<8>,改良されたモジュール<10>
@anchor{whatsnew/3 4 textwrap}@anchor{11ce}
@subsubsection textwrap


@ref{11cf,,TextWrapper} に 2 つ新しい制御変数が追加されていて、これらは属性値であり、コンストラクタ引数に渡せます。それぞれ @ref{11d0,,max_lines} が最大出力行数、 @ref{11d1,,placeholder} が `max_lines' により切り詰める場合に出力の最終行に置くテキストです。これら機能を使った新規のコンビニエンス関数 @ref{11d2,,shorten()} が追加されています。これは入力に含まれる全ての空白文字を単一の空白に置き換え、また幅 `width' に収めて、切り詰める場合は末尾を `placeholder' (デフォルトで @code{[...]}) で置き換えて、単一行で返します。(Contributed by Antoine Pitrou and Serhiy Storchaka in bpo-18585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18585} and bpo-18725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18725}.)

@node threading<8>,traceback<6>,textwrap<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 threading}@anchor{11d3}
@subsubsection threading


メインスレッドを表現する @ref{176,,Thread} オブジェクトを、新規関数 @ref{11d4,,main_thread()} で得られるようになりました。通常の条件であればこれは Python インタプリタを開始したスレッドになります。 (Contributed by Andrew Svetlov in bpo-18882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18882}.)

@node traceback<6>,types<7>,threading<8>,改良されたモジュール<10>
@anchor{whatsnew/3 4 traceback}@anchor{11d5}
@subsubsection traceback


新規関数 @ref{11d6,,traceback.clear_frames()} は、トレースバックオブジェクトを受け取って、それが参照している全てのフレーム内のローカル変数をクリアすることで、メモリ消費量を削減します。 (Contributed by Andrew Kuchling in bpo-1565525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1565525}.)

@node types<7>,urllib<5>,traceback<6>,改良されたモジュール<10>
@anchor{whatsnew/3 4 types}@anchor{11d7}
@subsubsection types


A new @ref{83c,,DynamicClassAttribute()} descriptor provides a way to define
an attribute that acts normally when looked up through an instance object, but
which is routed to the `class' @code{__getattr__} when looked up through the
class.  This allows one to have properties active on a class, and have virtual
attributes on the class with the same name (see @ref{5a,,enum} for an example).
(Contributed by Ethan Furman in bpo-19030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19030}.)

@node urllib<5>,unittest<10>,types<7>,改良されたモジュール<10>
@anchor{whatsnew/3 4 urllib}@anchor{11d8}
@subsubsection urllib


@ref{111,,urllib.request} が新規クラス @ref{11d9,,DataHandler} を介して @code{data:} URL をサポートするようになりました。 (Contributed by Mathias Panzenböck in bpo-16423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16423}.)

@ref{11da,,Request} クラスで使われる HTTP メソッドを、サブクラスで @ref{11db,,method} 属性をセットすることにより指定出来るようになりました。 (Contributed by Jason R Coombs in bpo-18978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18978}.) (---訳注: @ref{11db,,method} は 3.3 で追加されたが、コンストラクタに渡されたものが設定されるだけだった。---)

@ref{11da,,Request} オブジェクトは今では再利用可能です: @ref{11dc,,full_url} あるいは @ref{11dd,,data} 属性などが変更されると、関連する全ての内部プロパティが更新されます。このことによって今や、例えば、 @ref{11da,,Request} オブジェクトを、異なる `data' 引数での @ref{11de,,OpenerDirector.open()} の複数回呼び出し内で使ったり、あるいは、まっさらから作り直すのではなく @ref{11da,,Request} の @code{url} を書き換えて使ったり出来ます。新たに @ref{11df,,remove_header()} メソッドも追加されていて、これは @ref{11da,,Request} からヘッダを取り除きます。 (Contributed by Alexey Kachayev in bpo-16464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16464}, Daniel Wozniak in bpo-17485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17485}, and Damien Brecht and Senthil Kumaran in bpo-17272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17272}.)

@ref{11e0,,HTTPError} オブジェクトに、エラーに関係する HTTP レスポンスヘッダへのアクセスを提供する @ref{11e1,,headers} 属性が追加されました。 (Contributed by Berker Peksag in bpo-15701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15701}.)

@node unittest<10>,venv<7>,urllib<5>,改良されたモジュール<10>
@anchor{whatsnew/3 4 unittest}@anchor{11e2}
@subsubsection unittest


The @ref{2b3,,TestCase} class has a new method,
@ref{11e3,,subTest()}, that produces a context manager whose
@ref{186,,with} block becomes a "sub-test".  This context manager allows a test
method to dynamically generate subtests  by, say, calling the @code{subTest}
context manager inside a loop.  A single test method can thereby produce an
indefinite number of separately identified and separately counted tests, all of
which will run even if one or more of them fail.  For example:

@example
class NumbersTest(unittest.TestCase):
    def test_even(self):
        for i in range(6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)
@end example

これは 6 つのサブテストとなり、それぞれは unittest 内の冗長出力において、変数名 @code{i} とその変数への個々の値 (@code{i=0}, @code{i=1}, など) からなるラベルで識別されます。この例の完全なバージョンが @ref{11e4,,サブテストを利用して繰り返しテストの区別を付ける} にあります。 (Contributed by Antoine Pitrou in bpo-16997@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16997}.)

@ref{11e5,,unittest.main()} の `defaultTest' に、テスト名からなるイテラブルを渡せるようになりました。以前は文字列で単一のテスト名を渡せるだけでした。 (Contributed by Jyrki Pulliainen in bpo-15132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15132}.)

テストディスカバリ最中に発生する @ref{11e6,,SkipTest} (これはテストファイル内のモジュールレベルで起こせます) を、エラーとしてではなくスキップとして報告するようになりました。 (Contributed by Zach Ware in bpo-16935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16935}.)

@ref{11e7,,discover()} が発見したファイルをソートするようになったので、一貫したテスト順でテスト出来ます。  (Contributed by Martin Melin and Jeff Ramnani in bpo-16709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16709}.)

@ref{ff5,,TestSuite} がその実行完了次第すぐに、テスト成功していれば、テストへの参照を取り除くようになりました。ガーベージコレクションを行う Python インタプリタ上ではこの振る舞いによって、テストへの参照を保持しているものが他にない場合のテストのガーベージコレクトを可能にします。この振る舞いは @ref{ff5,,TestSuite} をサブクラス化して何もしない @code{_removeTestAtIndex} を定義することで上書き出来ます。 (Contributed by Tom Wardill, Matt McClure, and Andrew Svetlov in bpo-11798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11798}.)

テストアサーションの新規コンテキストマネージャ @ref{a59,,assertLogs()} が追加されました。これはコードブロックが @ref{8b,,logging} を使ってログメッセージを発行しているか確認します。デフォルトでは任意のロガーからの @code{INFO} 以上のプライオリティを持つメッセージを取れますが、ロガー名と最小プライオリティの両方とも指定可能です。コンテキストマネージャからの戻りオブジェクトに対して、ログされた @ref{11e8,,LogRecord} とフォーマットされたメッセージの両方あるいはどちらかを問い合わせることが出来ます。 (Contributed by Antoine Pitrou in bpo-18937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18937}.)

テストディスカバリが名前空間パッケージで動作するようになりました。 (Contributed by Claudiu Popa in bpo-17457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17457}.)

@ref{10d,,unittest.mock} オブジェクトが、呼び出しが合致する際に仕様としてのシグニチャを検査するようになりました。これはつまり、以前は位置引数だけの合致だったものが、位置引数と名前の両方で合致できるようになったということです。(Contributed by Antoine Pitrou in bpo-17015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17015}.)

@ref{11e9,,mock_open()} objects now have @code{readline} and @code{readlines}
methods.  (Contributed by Toshio Kuratomi in bpo-17467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17467}.)

@node venv<7>,wave<2>,unittest<10>,改良されたモジュール<10>
@anchor{whatsnew/3 4 venv}@anchor{11ea}
@subsubsection venv


@ref{117,,venv} に @code{csh} と @code{fish} シェルの有効化スクリプトが追加されました。 (Contributed by Andrew Svetlov in bpo-15417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15417}.)

@ref{571,,EnvBuilder} クラスとコンビニエンス関数 @ref{572,,create()} が新規キーワード引数 `with_pip' を取るようになりました。デフォルトは @code{False} です。これは @ref{571,,EnvBuilder} が仮想環境に @code{pip} がインストールされていることを保証するかどうかを制御します。(Contributed by Nick Coghlan in bpo-19552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19552} as part of the 
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/} implementation.)

@node wave<2>,weakref<2>,venv<7>,改良されたモジュール<10>
@anchor{whatsnew/3 4 wave}@anchor{11eb}
@subsubsection wave


The @ref{11ec,,getparams()} method now returns a namedtuple rather
than a plain tuple.  (Contributed by Claudiu Popa in bpo-17487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17487}.)

@ref{b45,,wave.open()} がコンテキスト管理プロトコルをサポートするようになりました。 (Contributed by Claudiu Popa in bpo-17616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17616}.)

@ref{119,,wave} は @ref{11ed,,シーク不能なファイルへの書き出しが出来るように} なりました。 (Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka in bpo-5202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5202}.)

@ref{11ee,,writeframesraw()} メソッドと @ref{11ef,,writeframes()} メソッドが @ref{193,,bytes-like object} を受け付けるようになりました。 (Contributed by Serhiy Storchaka in bpo-8311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8311}.)

@node weakref<2>,xml etree<2>,wave<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 weakref}@anchor{11f0}
@subsubsection weakref


新規 @ref{11f1,,WeakMethod} クラスは、インスタンスメソッドへの弱参照をシミュレートします。 (Contributed by Antoine Pitrou in bpo-14631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14631}.)

新規クラス @ref{c6f,,finalize} は、弱参照自身のライフサイクルを注意深く管理する必要性なしに、オブジェクトがガーベージコレクトされる際に呼び出されるコールバックを登録することを可能にします。 (Contributed by Richard Oudkerk in bpo-15528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15528}.)

@ref{11f2,,ref} に関連付いたコールバック (あれば) を、新規属性 @ref{11f3,,__callback__} で取得出来るようになりました。(Contributed by Mark Dickinson in bpo-17643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17643}.)

@node xml etree<2>,zipfile<6>,weakref<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 xml-etree}@anchor{11f4}
@subsubsection xml.etree


ノンブロッキングなアプリケーションでの XML ドキュメントの解析に、新規パーサ @ref{11f5,,XMLPullParser} を利用出来ます。実例は @ref{11f6,,非ブロックパースのためのプル API} をみてください。 (Contributed by Antoine Pitrou in bpo-17741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17741}.)

@ref{12b,,xml.etree.ElementTree} の関数 @ref{11f7,,tostring()} 、@ref{11f8,,tostringlist()} と、 @ref{b47,,ElementTree} クラスの @ref{c8c,,write()} メソッドに、 @ref{5a5,,キーワード専用引数} の `short_empty_elements' が追加されました。これはコンテンツを持たない要素を省略形 (@code{<tag />}) で書き出すか展開された形 (@code{<tag></tag>}) で書き出すかを制御します。(Contributed by Ariel Poliak and Serhiy Storchaka in bpo-14377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14377}.)

@node zipfile<6>,,xml etree<2>,改良されたモジュール<10>
@anchor{whatsnew/3 4 zipfile}@anchor{11f9}
@subsubsection zipfile


@ref{11fa,,PyZipFile} クラスの @ref{11fb,,writepy()} メソッドに `filterfunc' オプションが追加されました。これはアーカイブにどのディレクトリ・ファイルを加えるのかをコントロールするのに使うことが出来ます。例えばテスト用ファイルをアーカイブから除外する、などということが出来ます。(Contributed by Christian Tismer in bpo-19274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19274}.)

The `allowZip64' parameter to @ref{8d3,,ZipFile} and
@ref{11fa,,PyZipFile} is now @code{True} by default.  (Contributed by
William Mallard in bpo-17201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17201}.)

@node CPython の実装の変更,非推奨<12>,改良されたモジュール<10>,What's New In Python 3 4
@anchor{whatsnew/3 4 cpython-implementation-changes}@anchor{11fc}
@subsection CPython の実装の変更


@menu
* PEP 445; CPython のメモリアロケータのカスタマイズ: PEP 445 CPython のメモリアロケータのカスタマイズ. 
* PEP 442; オブジェクトの安全なファイナライゼーション: PEP 442 オブジェクトの安全なファイナライゼーション. 
* PEP 456; 安全で取り換え可能なハッシュアルゴリズム: PEP 456 安全で取り換え可能なハッシュアルゴリズム. 
* PEP 436; Argument Clinic: PEP 436 Argument Clinic. 
* その他のビルド並びに C API の変更:: 
* その他の改善: その他の改善<2>. 
* 大幅な最適化:: 

@end menu

@node PEP 445 CPython のメモリアロケータのカスタマイズ,PEP 442 オブジェクトの安全なファイナライゼーション,,CPython の実装の変更
@anchor{whatsnew/3 4 pep-445-customization-of-cpython-memory-allocators}@anchor{11fd}@anchor{whatsnew/3 4 whatsnew-pep-445}@anchor{10f0}
@subsubsection PEP 445: CPython のメモリアロケータのカスタマイズ


@geindex Python Enhancement Proposals; PEP 445
PEP 445@footnote{https://peps.python.org/pep-0445/} は、CPython インタープリタのメモリ割り当てをカスタマイズするために新たな C 水準のインターフェイスを追加しました。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 445

@item PEP 445@footnote{https://peps.python.org/pep-0445/} -- Python メモリアロケータをカスタマイズするための新 API 追加

PEP written and implemented by Victor Stinner.
@end table


@node PEP 442 オブジェクトの安全なファイナライゼーション,PEP 456 安全で取り換え可能なハッシュアルゴリズム,PEP 445 CPython のメモリアロケータのカスタマイズ,CPython の実装の変更
@anchor{whatsnew/3 4 pep-442-safe-object-finalization}@anchor{11fe}@anchor{whatsnew/3 4 whatsnew-pep-442}@anchor{10ef}
@subsubsection PEP 442: オブジェクトの安全なファイナライゼーション


@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/} removes the current limitations and quirks of object finalization
in CPython. With it, objects with @ref{11ff,,__del__()} methods, as well as
generators with @ref{1b0,,finally} clauses, can be finalized when they are
part of a reference cycle.

この変更の一環で、モジュールのグローバルは、ほとんどのケースではインタプリタのシャットダウン中に強制的に @ref{885,,None} がセットされることはなくなり、代わりに循環ガーベージコレクタの通常のオペレーションに委ねます。このことは、循環 GC が最初に導入されて以来悩みの種だった、普通 @code{__del__} メソッドを巻き込んだ「インタプリタシャットダウン時エラーの類」全体を回避します。(---訳注: bpo-18214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18214} (superseder for bpo-812369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=812369}), changeset 84936:79e2f5bbc30c@footnote{https://hg.python.org/cpython/rev/79e2f5bbc30c/} ---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 442

@item PEP 442@footnote{https://peps.python.org/pep-0442/} -- オブジェクトの安全なファイナライゼーション

PEP written and implemented by Antoine Pitrou.
@end table


@node PEP 456 安全で取り換え可能なハッシュアルゴリズム,PEP 436 Argument Clinic,PEP 442 オブジェクトの安全なファイナライゼーション,CPython の実装の変更
@anchor{whatsnew/3 4 pep-456-secure-and-interchangeable-hash-algorithm}@anchor{1200}@anchor{whatsnew/3 4 whatsnew-pep-456}@anchor{10e9}
@subsubsection PEP 456: 安全で取り換え可能なハッシュアルゴリズム


@geindex Python Enhancement Proposals; PEP 456
PEP 456@footnote{https://peps.python.org/pep-0456/} は、Python のハッシュアルゴリズムで行われた以前のセキュリティ修正作業 --- これは公に曝されている辞書検索に裏打ちされた API が標的になるかもしれない、特定の DOS 攻撃に対処するものです ---  に追従するものです (この改善の現在ラウンドの事の起こりについては bpo-14621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14621} を見てください)。この PEP では、 CPython のハッシュのコードをパッケージャが異なるハッシュアルゴリズムへの差し替えを容易にするために一元化し、そして Python のデフォルト実装としては 64 ビットデータ型を持つプラットフォームで SipHash に乗り換えます。以前の FNV アルゴリズムと比較したどんなパフォーマンスの差異も、些細なものです。

The PEP adds additional fields to the @ref{1201,,sys.hash_info} named tuple to
describe the hash algorithm in use by the currently executing binary.  Otherwise,
the PEP does not alter any existing CPython APIs.

@node PEP 436 Argument Clinic,その他のビルド並びに C API の変更,PEP 456 安全で取り換え可能なハッシュアルゴリズム,CPython の実装の変更
@anchor{whatsnew/3 4 pep-436-argument-clinic}@anchor{1202}@anchor{whatsnew/3 4 whatsnew-pep-436}@anchor{10f1}
@subsubsection PEP 436: Argument Clinic


「Argument Clinic」(
@geindex Python Enhancement Proposals; PEP 436
PEP 436@footnote{https://peps.python.org/pep-0436/}) は CPython ビルドプロセスの新たな鍋の具です。ビルトインと標準ライブラリの拡張モジュールが C で実装されるにあたって、正確なシグニチャを定義し保守管理するプロセスを単純化するのに使えます。

Python 3.4 では既にいくつかの標準ライブラリ拡張モジュールが Argument Clinic を使うように変換されていて、またこれの結果として @ref{ba,,pydoc} と @ref{82,,inspect} が更新されました。

Python 3.4 メンテナンスリリースでの更新の一部として C で実装されている callable に対して、プログラム的なイントロスペクションのためのシグニチャメタデータの追加が、さらに追加で行われることが期待されています。

@cartouche
@quotation 注釈 
Argument Clinic の PEP は、実装されている状態に対して完全には最新のものとはなっていません。Argument Clinic は Python 3.4 ではサードパーティに向けた公開 API として利用可能とする予定ではないので、このケースではリリース管理者とコア開発チームによって許容出来るとみなされました。
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 436

@item PEP 436@footnote{https://peps.python.org/pep-0436/} -- The Argument Clinic DSL (訳注: DSL=Domain-Specific Language)

PEP written and implemented by Larry Hastings.
@end table


@node その他のビルド並びに C API の変更,その他の改善<2>,PEP 436 Argument Clinic,CPython の実装の変更
@anchor{whatsnew/3 4 other-build-and-c-api-changes}@anchor{1203}
@subsubsection その他のビルド並びに C API の変更



@itemize *

@item 
@ref{a9c,,PyType_GetSlot()} 関数が、安定 ABI に追加されました。これにより、制限 API を使う際に名前の付いた型のスロットから関数ポインタを取り出すことが出来ます。(Contributed by Martin von Löwis in bpo-17162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17162}.) (---訳注: 安定 ABI, 制限 API については What's New In Python 3.2 (
@geindex Python Enhancement Proposals; PEP 384
PEP 384@footnote{https://peps.python.org/pep-0384/}) を参照。---)

@item 
The new @code{Py_SetStandardStreamEncoding()} pre-initialization API
allows applications embedding the CPython interpreter to reliably force
a particular encoding and error handler for the standard streams.
(Contributed by Bastien Montagne and Nick Coghlan in bpo-16129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16129}.)

@item 
文字列引数を変更することのない Python C API のほとんどが、 @code{char *} ではなく適切に @code{const char *} として宣言されました。 (Contributed by Serhiy Storchaka in bpo-1772673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1772673}.)

@item 
Python インタプリタが利用出来ない場合 (例えばクロスコンパイルのシナリオ) であっても使える、シェルで書き直したバージョンの @code{python-config} が追加されました。

@item 
@ref{62b,,PyUnicode_FromFormat()} が @code{%s}, @code{%A}, @code{%U}, @code{%V}, @code{%S}, @code{%R} についての幅と精度の指定をサポートするようになりました。 (Contributed by Ysj Ray and Victor Stinner in bpo-7330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7330}.)

@item 
既存の @ref{1204,,PyStructSequence_InitType()} 関数を補うものとして、 @ref{1205,,PyStructSequence_InitType2()} が追加されました。違いは、これは成功時に @code{0} 、失敗時に @code{-1} を返すことです。

@item 
CPython のソースを、最近の GCC と clang のアドレスサニティチェック機能を使ってコンパイル出来るようにしました: 小さなオブジェクト用アロケータで起こっていた偽の警報を黙らせました。 (Contributed by Dhiru Kholia in bpo-18596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18596}.)

@item 
Windows ビルドに アドレス空間配置のランダム化@footnote{https://en.wikipedia.org/wiki/Address_space_layout_randomization} と データ実行防止@footnote{https://en.wikipedia.org/wiki/Data_Execution_Prevention} を使うようにしました。 (Contributed by Christian Heimes in bpo-16632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16632}.)

@item 
@ref{116f,,operator.length_hint()} と等価な C API 関数 @ref{1206,,PyObject_LengthHint()} が追加されました。 (Contributed by Armin Ronacher in bpo-16148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16148}.)
@end itemize

@node その他の改善<2>,大幅な最適化,その他のビルド並びに C API の変更,CPython の実装の変更
@anchor{whatsnew/3 4 other-improvements}@anchor{1207}@anchor{whatsnew/3 4 other-improvements-3-4}@anchor{1208}
@subsubsection その他の改善

@anchor{whatsnew/3 4 whatsnew-isolated-mode}@anchor{10da}

@itemize *

@item 
The @ref{1209,,python} command has a new @ref{120a,,option}, @code{-I}, which causes it to run in "isolated mode",
which means that @ref{3e4,,sys.path} contains neither the script's directory nor
the user's @code{site-packages} directory, and all @code{PYTHON*} environment
variables are ignored (it implies both @code{-s} and @code{-E}).  Other
restrictions may also be applied in the future, with the goal being to
isolate the execution of a script from the user's environment.  This is
appropriate, for example, when Python is used to run a system script.  On
most POSIX systems it can and should be used in the @code{#!} line of system
scripts.  (Contributed by Christian Heimes in bpo-16499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16499}.)

@item 
@ref{bf,,readline} をサポートするプラットフォームで、対話インタプリタでの @code{Tab} キーでの補完がデフォルトで有効になりました。履歴もデフォルトで有効となり、 @code{~/.python-history} に書き込まれ (そしてそこから読み込まれ) ます。 (Contributed by Antoine Pitrou and Éric Araujo in bpo-5845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5845}.)

@item 
Python インタプリタの @code{--version} での起動時、標準エラーではなく標準出力にバージョン情報を出力するようになりました (bpo-18338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18338})。同じ変更は @ref{7,,argparse} モジュールに対して (bpo-18920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18920})、また、スクリプトとして呼び出せる機能を持つモジュールに対して (bpo-18922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18922}) も行われました。

@item 
CPython の Windows インストーラが、拡張子を登録する際に 
@geindex PATHEXT
@geindex 環境変数; PATHEXT
@code{PATHEXT} に @code{.py} を追加するようになりました。これをするとユーザは、 Windows コマンドプロンプトから Python スクリプトを、 @code{.py} 拡張子なしでその名前だけタイプして実行出来ます。 (Contributed by Paul Moore in bpo-18569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18569}.)

@item 
A new @code{make} target coverage-report@footnote{https://devguide.python.org/coverage/#measuring-coverage-of-c-code-with-gcov-and-lcov}
will build python, run the test suite, and generate an HTML coverage report
for the C codebase using @code{gcov} and lcov@footnote{https://github.com/linux-test-project/lcov}.

@item 
The @code{-R} option to the @ref{120b,,python regression test suite} now
also checks for memory allocation leaks, using
@ref{11c9,,sys.getallocatedblocks()}.  (Contributed by Antoine Pitrou in
bpo-13390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13390}.)

@item 
@code{python -m} が名前空間パッケージで動くようになりました。

@item 
@ref{d6,,stat} モジュールが C で実装されました。これは以前問題であった Python モジュール内で値をハードコードすることなく、定数を C ヘッダファイルから取りこめることを意味しています。(---訳注: bpo-11016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11016} 、特に msg127114@footnote{https://bugs.python.org/issue11016#msg127114} 以降参照。---)

@item 
単一の OS モジュール (POSIX の @code{.so} と Windows の @code{.dll}) からの複数 Python モジュールのロードを正しく行えるようになりました (以前は黙ってファイル内の最初のモジュールだけが返されていました)。  (Contributed by Václav Šmilauer in bpo-16421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16421}.)

@item 
A new opcode, @code{LOAD_CLASSDEREF}, has been added to fix a bug in the
loading of free variables in class bodies that could be triggered by certain
uses of @ref{e58,,__prepare__}.  (Contributed by Benjamin Peterson in
bpo-17853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17853}.)

@item 
Victor Stinner が、彼の 
@geindex Python Enhancement Proposals; PEP 445
PEP 445@footnote{https://peps.python.org/pep-0445/} ベースの @code{pyfailmalloc} ツールを用いて数多くのメモリエラー関連のクラッシュを特定し、そして修正しました。 (bpo-18408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18408}, bpo-18520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18520})

@item 
@code{pyvenv} コマンドに、シンボリックリンクがデフォルトのシステムでもそうせずにコピーを使うようにするための @code{--copies} オプションが追加されました。 (Contributed by Vinay Sajip in bpo-18807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18807}.)

@item 
@code{pyvenv} コマンドにはさらに、そうしなければ自動的に仮想環境に pip がブートストラップされてしまうのを抑制するための、 @code{--without-pip} オプションが追加されました。(Contributed by Nick Coghlan in bpo-19552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19552} as part of the 
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/} implementation.)

@item 
環境変数 
@geindex PYTHONIOENCODING
@geindex 環境変数; PYTHONIOENCODING
@ref{120c,,PYTHONIOENCODING} の値内で、エンコーディング名を省略出来るようになりました。つまり、デフォルトエンコーディングを変更することなしにエラーハンドラだけをセット出来ます。 (Contributed by Serhiy Storchaka in bpo-18818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18818}.)

@item 
@ref{14,,bz2}、@ref{8e,,lzma}、@ref{6b,,gzip} モジュールの @code{open} 関数が @code{x} (排他的作成) モードをサポートするようになりました。 (Contributed by Tim Heaney and Vajrasky Kok in bpo-19201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19201}, bpo-19222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19222}, and bpo-19223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19223}.)
@end itemize

@node 大幅な最適化,,その他の改善<2>,CPython の実装の変更
@anchor{whatsnew/3 4 significant-optimizations}@anchor{120d}
@subsubsection 大幅な最適化



@itemize *

@item 
UTF-32 デコーダが3-4倍速くなりました。 (Contributed by Serhiy Storchaka in bpo-14625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14625}.)

@item 
集合に対するハッシュ衝突のコストが削減されました。ハッシュテーブルの個々の検査 (probe) で、ハッシュテーブル全体を通したランダムな検査を行う前に、連続する隣接したキー/ハッシュペアをチェックするようになりました。これは、キャッシュ局所性を利用して衝突解決のコストを減らします。この衝突解決戦略は、リニア検査とオープンアドレッシング法のハイブリッドとして説明できます。追加的なリニア検査の数はデフォルトでは 9 です。この値は、コンパイル時に LINEAR_PROBES を定義することで任意の値に変更できます。リニア検査を完全に無効にするには LINEAR_PROBES=0 を設定してください。 (Contributed by Raymond Hettinger in bpo-18771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18771}.)

@item 
インタプリタの起動が約 30% 高速化されました。この速度向上は、いくつかの手段によってもたらされました。インタプリタは起動時により少数のモジュールをロードするようになりました。例えば @ref{be,,re}, @ref{1e,,collections}, @ref{8a,,locale} モジュール、およびそれらの依存モジュールは、デフォルトではインポートされません。 marshal モジュールは、コンパイルされた Python コードをより高速にロードできるように改善されました。 (Contributed by Antoine Pitrou, Christian Heimes and Victor Stinner in bpo-19219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19219}, bpo-19218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19218}, bpo-19209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19209}, bpo-19205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19205} and bpo-9548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9548}.)

@item 
@ref{a66,,bz2.BZ2File} が大半の場合 Python2 のバージョン以上に速くなりました。@ref{120e,,lzma.LZMAFile} も最適化されました。(Contributed by Serhiy Storchaka and Nadeem Vawda in bpo-16034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16034}.)

@item 
@ref{120f,,random.getrandbits()} が (通常使用される) 小さな整数に対して20%-40% 早くなりました。 (Contributed by Serhiy Storchaka in bpo-16674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16674}.)

@item 
文字列のストレージ形式を変更したことにより、文字列のピックル化は非常に速くなりました。(Contributed by Victor Stinner and Antoine Pitrou in bpo-15596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15596}.)

@item 
A performance issue in @code{io.FileIO.readall()} has been solved.  This
particularly affects Windows, and significantly speeds up the case of piping
significant amounts of data through @ref{dc,,subprocess}.  (Contributed
by Richard Oudkerk in bpo-15758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15758}.)

@item 
@ref{1210,,html.escape()} が10倍速くなりました。(Contributed by Matt Bryant in bpo-18020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18020}.)

@item 
Windows において、 @code{obmalloc} で CRT の @code{malloc} の代わりにネイティブの @code{VirtualAlloc} を使うようになりました。人工的なベンチマーク結果は、メモリー消費が 3% 減ったことを示しています。

@item 
@ref{746,,os.urandom()} now uses a lazily opened persistent file descriptor
so as to avoid using many file descriptors when run in parallel from
multiple threads.  (Contributed by Antoine Pitrou in bpo-18756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18756}.)
@end itemize

@node 非推奨<12>,削除<12>,CPython の実装の変更,What's New In Python 3 4
@anchor{whatsnew/3 4 deprecated}@anchor{1211}@anchor{whatsnew/3 4 deprecated-3-4}@anchor{1109}
@subsection 非推奨


このセクションでは、Python 3.4 で非推奨となり Python 3.5 以降で削除予定となる、様々な API とその他機能性についてをカバーします。(全てではありませんが) ほとんどのケースで、非推奨に対する警告を (たとえば @code{-Wd} を使って) 有効にしたインタプリタ起動時、非推奨 API を使うと @ref{1a3,,DeprecationWarning} を励起します。

@menu
* Python API の非推奨項目:: 
* 非推奨の機能:: 

@end menu

@node Python API の非推奨項目,非推奨の機能,,非推奨<12>
@anchor{whatsnew/3 4 deprecations-in-the-python-api}@anchor{1212}
@subsubsection Python API の非推奨項目



@itemize *

@item 
As mentioned in @ref{10dc,,PEP 451; インポートシステムのための ModuleSpec 型}, a number of @ref{7b,,importlib}
methods and functions are deprecated: @code{importlib.find_loader()} is
replaced by @ref{5af,,importlib.util.find_spec()};
@code{importlib.machinery.PathFinder.find_module()} is replaced by
@ref{1213,,importlib.machinery.PathFinder.find_spec()};
@code{importlib.abc.MetaPathFinder.find_module()} is replaced by
@ref{a68,,importlib.abc.MetaPathFinder.find_spec()};
@code{importlib.abc.PathEntryFinder.find_loader()} and
@code{find_module()} are replaced by
@ref{a6c,,importlib.abc.PathEntryFinder.find_spec()}; all of the @code{@var{xxx}Loader} ABC
@code{load_module} methods (@code{importlib.abc.Loader.load_module()},
@code{importlib.abc.InspectLoader.load_module()},
@code{importlib.abc.FileLoader.load_module()},
@code{importlib.abc.SourceLoader.load_module()}) should no longer be
implemented, instead loaders should implement an
@code{exec_module} method
(@ref{a6a,,importlib.abc.Loader.exec_module()},
@ref{1214,,importlib.abc.InspectLoader.exec_module()}
@ref{1215,,importlib.abc.SourceLoader.exec_module()}) and let the import system
take care of the rest; and
@code{importlib.abc.Loader.module_repr()},
@code{importlib.util.module_for_loader()}, @code{importlib.util.set_loader()},
and @code{importlib.util.set_package()} are no longer needed because their
functions are now handled automatically by the import system.

@item 
The @code{imp} module is pending deprecation. To keep compatibility with
Python 2/3 code bases, the module's removal is currently not scheduled.

@item 
The @code{formatter} module is pending deprecation and is slated for removal
in Python 3.6.

@item 
@ref{c96,,hmac.new()} 関数の `digestmod' がデフォルトで暗黙に @code{MD5} を使う仕様は撤廃されます。Python 3.6 では `digestmod' 引数には明示的にダイジェスト名かコンストラクタを渡すことが求められます。

@item 
@ref{62,,ftplib} モジュール内の内部クラス @code{Netrc} はずっと長いことそのドキュメンテーション文字列内で非推奨であることを謳ってきました。これは今や @ref{1a3,,DeprecationWarning} を発行します。Python 3.5 ではこのクラスは完全に削除されます。

@item 
@ref{ee0,,subprocess.Popen.wait()} の文書化されていない引数 `endtime' は本来曝してはいけないものでしたので、使用されていないことを願っています。これは非推奨ですし、確実に Python 3.5 では削除されるのではないでしょうか。(---訳注: 3.5 では削除はされませんでしたが、もちろん使用しないでください。これは内部用です。---)

@item 
@ref{a77,,HTMLParser} の `strict' 引数は非推奨です。

@item 
The @ref{b0,,plistlib} @code{readPlist()},
@code{writePlist()}, @code{readPlistFromBytes()}, and
@code{writePlistToBytes()} functions are deprecated in favor of the
corresponding new functions @ref{b48,,load()}, @ref{b4a,,dump()},
@ref{b49,,loads()}, and @ref{b4b,,dumps()}.  @code{Data()}
is deprecated in favor of just using the @ref{192,,bytes} constructor.

@item 
@ref{e1,,sysconfig} のキー @code{SO} は非推奨です。これは @code{EXT_SUFFIX} に取って代わられました。

@item 
種々の @code{open} 関数で受け付けられていた @code{U} モードは非推奨となりました。Python 3 ではこれは何も役に立つことはしません。 @ref{9be,,io.TextIOWrapper} (必要ならば)、 `newline' 引数を適切に使うことによって置き換えられるはずです。

@item 
@ref{57a,,xml.etree.ElementTree.iterparse()} の `parser' 引数と @ref{c49,,XMLParser()} の `html' 引数が非推奨となりました。後者は (訳注: 第一引数のため) 削除に備えて @code{XMLParser} への全ての引数はキーワード引数として渡すようにしてください。
@end itemize

@node 非推奨の機能,,Python API の非推奨項目,非推奨<12>
@anchor{whatsnew/3 4 deprecated-features}@anchor{1216}
@subsubsection 非推奨の機能



@itemize *

@item 
@ref{1217,,IDLE --- Python のエディタとシェル} の @code{-n} フラグでの実行 (サブプロセスを起こさない) は非推奨となりました。ただし、この機能は bpo-18823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18823} が解決するまでは削除はされません。

@item 
@ref{cc,,site} モジュールは "site-python" ディレクトリが存在すればこれを sys.path に加えていましたが、これは非推奨となりました。 (bpo-19375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19375})
@end itemize

@node 削除<12>,Python 3 4 への移植,非推奨<12>,What's New In Python 3 4
@anchor{whatsnew/3 4 removed}@anchor{1218}
@subsection 削除


@menu
* サポートされなくなったオペレーティングシステム:: 
* API と機能の削除: API と機能の削除<5>. 
* コードの整理:: 

@end menu

@node サポートされなくなったオペレーティングシステム,API と機能の削除<5>,,削除<12>
@anchor{whatsnew/3 4 operating-systems-no-longer-supported}@anchor{1219}
@subsubsection サポートされなくなったオペレーティングシステム


以下の OS 向けのソースとビルドツールは削除されました。


@itemize *

@item 
OS/2 (bpo-16135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16135})。

@item 
Windows 2000 (changeset e52df05b496a@footnote{https://hg.python.org/cpython/rev/e52df05b496a})。

@item 
@code{COMSPEC} が @code{command.com} を指している Windows システム (bpo-14470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14470}).

@item 
VMS (bpo-16136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16136})。
@end itemize

@node API と機能の削除<5>,コードの整理,サポートされなくなったオペレーティングシステム,削除<12>
@anchor{whatsnew/3 4 api-and-feature-removals}@anchor{121a}
@subsubsection API と機能の削除


時代遅れとなり、以前に既に非推奨となった以下の API と機能が削除されました:


@itemize *

@item 
保守されていなかった @code{Misc/TextMate} と @code{Misc/vim} ディレクトリは削除されました (代わりに何が使えるかの提案は devguide@footnote{https://devguide.python.org} をみてください --- 訳注: おそらく Additional Resources@footnote{https://devguide.python.org/#additional-resources} に挙げられている wiki@footnote{https://wiki.python.org/moin/PythonEditors} を指している ---)。

@item 
makefile のマクロ @code{SO}  は削除されました (これは @code{SHLIB_SUFFIX} マクロと @code{EXT_SUFFIX} マクロで置き換えられました) (bpo-16754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16754})。

@item 
@code{PyThreadState.tick_counter} フィールドは削除されました。これは Python 3.2 で「新しい GIL」が導入された際に意味をなくしていました。 (bpo-19199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19199}).

@item 
@code{PyLoader} と @code{PyPycLoader} が @ref{7b,,importlib} から削除されました。 (Contributed by Taras Lyapun in bpo-15641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15641}.)

@item 
@ref{d35,,HTTPConnection} と @ref{d36,,HTTPSConnection} の `strict' 引数は削除されました。 HTTP 0.9 スタイルの 「Simple Responses」はもはやサポートされません。

@item 
@ref{11da,,urllib.request.Request} の非推奨となっていた getter/setter メソッドの @code{add_data}, @code{has_data}, @code{get_data}, @code{get_type}, @code{get_host}, @code{get_selector}, @code{set_proxy}, @code{get_origin_req_host}, @code{is_unverifiable} は削除されました (代わりに属性アクセスを直接使ってください)。

@item 
非推奨の @code{TYPE_INT64} ロードのサポートが @ref{91,,marshal} から削除されました。  (Contributed by Dan Riti in bpo-15480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15480}.)

@item 
@ref{4e3,,inspect.Signature}: 位置専用パラメータを示すのに今では正当な名前が必要です。

@item 
object 自身の @ref{831,,object.__format__()} はもはや空でないフォーマット文字列を受け付けず、 @ref{198,,TypeError} を投げます。空でない文字列を渡すことは既に Python 3.2 で非推奨となっていました。この変更は以前は動作した (そして正しくない) コードが、オブジェクトが __format__ メソッドを得ることで処理に失敗し始めていた状況を防ぐ目的でなされました。この変更が意味することはあなたのコードにとって、それを処理する __format__ メソッドを持たないオブジェクトに @code{s} フォーマットコードを使うと @ref{198,,TypeError} を起こしうるようになった、ということです。背景については bpo-7994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7994} を参照して下さい。 (---訳注: このパラグラフの中盤が非常にわかりにくい表現で訳者も意味を取りきれていませんが、おそらく Python 2.6/3.0 で動作していた例えば @code{format(1+1j, '10s')} が Python 2.7/3.1 で動作しなくなったことを指しているのだと思います。問題にされているのは動作しなくなったことではなくてむしろ動作していたことで、そして object.__format__ が return str(self).__format__(fmt) で実現されていること。このコードでは fmt は何らの意味も持っていませんので、これは一貫性に欠ける要因である、とのことで、「わかりやすく拒絶する」ことが真意であるようです ---)

@item 
@code{difflib.SequenceMatcher.isbjunk()} and
@code{difflib.SequenceMatcher.isbpopular()} were deprecated in 3.2, and have
now been removed: use @code{x in sm.bjunk} and
@code{x in sm.bpopular}, where `sm' is a @ref{121b,,SequenceMatcher} object
(bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}).
@end itemize

@node コードの整理,,API と機能の削除<5>,削除<12>
@anchor{whatsnew/3 4 code-cleanups}@anchor{121c}
@subsubsection コードの整理



@itemize *

@item 
@ref{ba,,pydoc} モジュールで、使用されておらず文書化もされていなかった内部的な @code{Scanner} クラスが削除されました。

@item 
ひどく壊れていた OSX システムで呼ばれる可能性があるのみだった @ref{af,,platform} モジュールの非公開関数 @code{_mac_ver_lookup}, @code{_mac_ver_gstalt}, @code{_bcd2str} とあわせて、非公開かつ実質的に未使用だった @code{_gestalt} モジュールが削除されました。 (see bpo-18393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18393})

@item 
@ref{e4,,tarfile} モジュールの名前空間内に @ref{d6,,stat} 定数群がハードコードでコピーされていましたが、これは削除されました。
@end itemize

@node Python 3 4 への移植,3 4 3 の変更,削除<12>,What's New In Python 3 4
@anchor{whatsnew/3 4 porting-to-python-3-4}@anchor{121d}
@subsection Python 3.4 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* 'python' コマンドの挙動の変更: 'python' コマンドの挙動の変更<2>. 
* Python API の変更: Python API の変更<11>. 
* C API の変更: C API の変更<15>. 

@end menu

@node 'python' コマンドの挙動の変更<2>,Python API の変更<11>,,Python 3 4 への移植
@anchor{whatsnew/3 4 changes-in-python-command-behavior}@anchor{121e}
@subsubsection 'python' コマンドの挙動の変更



@itemize *

@item 
POSIX シェルでは、環境変数 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} に空の値をセットすることは、何もセットしないことと同じです。ところが 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} に空の値をセットすることは、何もセットしないことと `まったく同じではありませんでした': 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} に空の値をセットすると、 @code{.} をセットしたのと同じ意味になっていて、これは 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} での振舞いから類推しようとすると混乱を招くものでした。この振る舞いは 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} での POSIX の慣習に従うように改められました。

@item 
CPython インタプリタのデバッグビルド (@code{--with-pydebug}) での出力 [X refs, Y blocks] がデフォルトではオフになりました。 @code{-X showrefcount} オプション起動で再度有効に出来ます。 (Contributed by Ezio Melotti in bpo-17323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17323}.)

@item 
@code{python} コマンドとほとんどの標準ライブラリスクリプト (また @ref{7,,argparse} も) において、 @code{--version} が情報出力を @code{stderr} ではなく @code{stdout} に行うようになりました (issue へのリンクは @ref{1208,,その他の改善} セクション内参照)。
@end itemize

@node Python API の変更<11>,C API の変更<15>,'python' コマンドの挙動の変更<2>,Python 3 4 への移植
@anchor{whatsnew/3 4 changes-in-the-python-api}@anchor{110e}
@subsubsection Python API の変更



@itemize *

@item 
@ref{7c,,importlib.abc} 内に定義されている ABC は、無分別に @ref{36b,,NotImplementedError} を投げるのではなく、相応しい例外を投げるかデフォルト値を返すかのどちらかになりました。このことは @ref{1a6,,super()} を呼び出して ABC がするがままに任せているコードにのみ影響します。互換性のために、必要であれば @ref{36b,,NotImplementedError} とその投げられる新たな例外の両方を捕捉してください。

@item 
The module type now initializes the @ref{323,,__package__} and
@ref{33b,,__loader__}
attributes to @code{None} by default. To determine if these attributes were set
in a backwards-compatible fashion, use e.g.
@code{getattr(module, '__loader__', None) is not None}.  (bpo-17115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17115}.)

@item 
@code{importlib.util.module_for_loader()} now sets @code{__loader__} and
@code{__package__} unconditionally to properly support reloading. If this is not
desired then you will need to set these attributes manually. You can use
@code{importlib.util.module_to_load()} for module management.

@item 
インポートがリロードの際に無条件に関連属性 (例えば @code{__name__}, @code{__loader__}, @code{__package__}, @code{__file__}, @code{__cached__}) をリセットするようになりました。これは、3.3 以前のリロードの際にモジュールを再発見する振る舞いと同じものを復元するものであるということを注記しておきます。 (bpo-19413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19413})

@item 
凍結パッケージ (frozen package) はもはや @code{__path__} にパッケージ名を含むリストをセットせず、空リストをセットします。この以前の振る舞いは、凍結パッケージと同じ名前を持つディレクトリが存在する場合のサブモジュールのインポートで、インポートシステムが間違ったことを起こしうるものでした。モジュールがパッケージなのかそうでないのかを決める正しい方法は、 @code{hasattr(module, '__path__')} を使うことです。 (bpo-18065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18065})

@item 
Frozen modules no longer define a @code{__file__} attribute. It's semantically
incorrect for frozen modules to set the attribute as they are not loaded from
any explicit location. If you must know that a module comes from frozen code
then you can see if the module's @code{__spec__.location} is set to @code{'frozen'},
check if the loader is a subclass of
@ref{1220,,importlib.machinery.FrozenImporter},
or if Python 2 compatibility is necessary you can use @code{imp.is_frozen()}.

@item 
@ref{c1a,,py_compile.compile()} が書き込み先ファイルパスがシンボリックリンクか非レギュラーファイルの場合に @ref{1221,,FileExistsError} を投げるようになりました。これは、警告の役割を果たすためです、インポートがファイルパスの元のファイルタイプが何かによらずに、それらファイルをレギュラーファイルで上書きすることの。

@item 
ソースコードをロードしようとして @ref{18e,,SyntaxError} かもしくは @ref{c08,,UnicodeDecodeError} を引き起こした場合に、 @ref{1222,,importlib.abc.SourceLoader.get_source()} はそれを @ref{65b,,ImportError} に読み替えて投げることをしなくなりました。 @ref{65b,,ImportError} はそうあるべきなのに見つからない場合にのみ投げられるべきなので、ソースコードが見つかったけれども正しくない構造である場合の意味にまで及ぶのは、手を伸ばし過ぎで過負荷です。ImportError を捕捉していたコードで今後とも構文エラーとデコーディングの問題を無視したいと望むならば、これら 3 つ全ての例外を捕捉するようにしてください。 (訳注: changeset 84172:e353f64dfd95@footnote{https://hg.python.org/cpython/rev/e353f64dfd95} )

@item 
@ref{1223,,functools.update_wrapper()} と @ref{115f,,functools.wraps()} が、たとえその関数も @code{__wrapped__} を持っていたとしても正しくその関数が包まれるように @code{__wrapped__} 属性値をセットするようになりました。つまり @code{__wrapped__} 属性は、以前のようにチェイン内の全ての @code{__wrapped__} 属性が最も内側の関数を参照するのではなく、デコレートされた関数の積み上げを正しくリンクするようになったということです。以前の振る舞いが意図されたものであると思い込んでいたイントロスペクションライブラリの作者は、チェインの中の最初の関数 (@code{__wrapped__} 属性を持たない) にアクセスするのに @ref{115e,,inspect.unwrap()} を使えます。(---訳注: bpo-17482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17482}. わかりにくいので実例で。中で適切に @@wrap を使うデコレータ @@deco1、@@deco2 があるとして、my_func をこの両方でデコレートするとします。この場合に、Python 3.3 までは @code{my_func.__wrapped__.__wrapped__} が AttributeError になります。今回のこの修正で @code{my_func.__wrapped__.__wrapped__} は期待通りに振舞います。 ---)

@item 
@ref{941,,inspect.getfullargspec()} は、 @ref{22f,,inspect.signature()} を前提とした再実装がなされました。これにより、かつて扱えていたよりも遥かに広い種類の呼び出し可能 (callable) を扱うようになりました (訳注: 例えば @ref{316,,open()} などは Python 3.3 までは扱えなかった)。Python 3.4 系列の経過のなかで、追加で組み込みや拡張モジュールの callable がシグニチャのメタデータを持つことが期待されています。 @ref{941,,inspect.getfullargspec()} が非 Python callable で失敗することを前提としたコードは、適宜調整の必要があるかもしれません。

@item 
@ref{1224,,importlib.machinery.PathFinder} は @ref{1225,,sys.path_hooks} 内のオブジェクトに、空文字列の場合は現在作業ディレクトリを渡すようになりました。結果の @ref{7fa,,sys.path_importer_cache} が決して @code{'@w{'}} を含まないことになるので、 @ref{3e4,,sys.path} に基いて @ref{7fa,,sys.path_importer_cache} を巡回しても全てのキーを見つけられません。インタプリタを @code{-m} で起動した場合も含め、現在作業ディレクトリ内でインポートされた際のモジュールの @code{__file__} も絶対パスで持つようになりました (ただしスクリプトがコマンドラインから相対パスを使って直接実行された際の @code{__main__.__file__} を除きます (Contributed by Brett Cannon in bpo-18416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18416}))。 (bpo-18416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18416})

@item 
@ref{d35,,HTTPConnection} と @ref{d36,,HTTPSConnection} から `strict' 引数が削除されたことは、残りの引数をキーワード引数としてではなく位置引数として使っていたなら意味が変わってしまいます。非推奨警告に注意を払ってきたのであれば、あなたのコードは既に全てのオプショナル引数をキーワードで渡しているはずです。

@item 
@code{from __future__ import ...} ステートメントの間に文字列が含まれる場合に `常に' @ref{18e,,SyntaxError} となるようになりました。以前はモジュールの docstring が先頭にある場合とない場合で振る舞いが違っていて、ない場合にこのエラーが意図せず無視される場合がありました。この修正は CPython を言語仕様に準拠させるものです。Jython と PyPy では既にこれが行われています。 (bpo-17434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17434})

@item 
@ref{11ba,,ssl.SSLSocket.getpeercert()} と @ref{106d,,ssl.SSLSocket.do_handshake()} は、 @code{SSLSocket} が未接続時に以前は @ref{5f0,,AttributeError} を投げていましたが、 @code{ENOTCONN} を持った @ref{2c0,,OSError} を投げるように改められました。加えて @ref{11ba,,getpeercert()} はハンドシェイクが未実施の場合に @ref{2ec,,ValueError} を投げるようになりました。

@item 
@ref{1226,,base64.b32decode()} が入力文字列が非 b32 文字を含む場合に @ref{198,,TypeError} ではなく @ref{1227,,binascii.Error} を投げるようになりました。今回のこの @ref{198,,TypeError} はほか (訳注: if the input is incorrectly padded のとき) の @ref{198,,TypeError} が置き換えられた際に置き換え忘れられたものでした。 (Contributed by Serhiy Storchaka in bpo-18011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18011}.) 注意: この修正は後方互換性を保てないので本来メンテナンスリリースの Python 3.3 には入るべきではなかったのですが、不注意で Python 3.3.3 にも行われてしまいました。

@item 
The @code{file} attribute is now automatically closed when
the creating @code{cgi.FieldStorage} instance is garbage collected. If you
were pulling the file object out separately from the @code{cgi.FieldStorage}
instance and not keeping the instance alive, then you should either store the
entire @code{cgi.FieldStorage} instance or read the contents of the file
before the @code{cgi.FieldStorage} instance is garbage collected.

@item 
クローズ済みの SSL ソケットに対する @code{read} や @code{write} 呼び出しで、以前のようなミステリアスな @ref{5f0,,AttributeError} ではなく、役に立つ @ref{2ec,,ValueError} を投げるようになりました。 (bpo-9177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9177})

@item 
@ref{1228,,slice.indices()} が巨大な値で @ref{a81,,OverflowError} を起こすことはなくなりました。この修正からの流れで @ref{1228,,slice.indices()} は負の値に対して @ref{2ec,,ValueError} を投げるようになっています。以前はこれは馬鹿げた値を返していました。 (bpo-14794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14794})

@item 
特殊メソッド @code{__complex__} が複素数ではなく @ref{196,,float} を返す実装をしているオブジェクトを渡すと @ref{19,,cmath} 関数ではエラーとなり、 @ref{197,,complex} コンストラクタでは受け容れられていましたが、これはいずれも @ref{198,,TypeError} となるように改められました。(bpo-16290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16290}.)

@item 
3.2 と 3.3 での @ref{19b,,int} コンストラクタが `base' パラメータとして誤って @ref{196,,float} を許容してしまっていました。それをわざわざやっているとも思えないですが、そうしていたなら今後は @ref{198,,TypeError} になります。 (bpo-16772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16772})

@item 
キーワード専用引数へのデフォルト値が、通常のキーワード引数へのデフォルト値評価の `あとで' 評価されるようになりました。前ではなく。望むらくは誰一人以前のバギーな振る舞いに頼っちゃうおバカなコードを書いていませんように。願います。 (bpo-16967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16967})

@item 
古いスレッド状態が @ref{4b5,,fork()} 後にクリアされるようになりました。これにより、以前は不適切に永遠に生き残ってしまっていたいくつかのシステムリソース (たとえば、スレッドローカル記憶内に維持されたデータベース接続) が解放されるようになります。 (bpo-17094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17094}.)

@item 
Parameter names in @code{__annotations__} dicts are now mangled properly,
similarly to @ref{1229,,__kwdefaults__}.
(Contributed by Yury Selivanov in bpo-20625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20625}.)

@item 
@ref{1149,,hashlib.hash.name} が識別子を常に小文字で返すようになりました。以前はいくつかの組み込みハッシュが大文字名を持っていましたが、公式インターフェイスであることから、命名に一貫性を持たせるようにしました。 (bpo-18532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18532})

@item 
Because @ref{ff5,,unittest.TestSuite} now drops references to tests after they
are run, test harnesses that reuse a @ref{ff5,,TestSuite} to re-run
a set of tests may fail.   Test suites should not be re-used in this fashion
since it means state is retained between test runs, breaking the test
isolation that @ref{10c,,unittest} is designed to provide.  However, if the lack
of isolation is considered acceptable, the old behavior can be restored by
creating a @ref{ff5,,TestSuite} subclass that defines a
@code{_removeTestAtIndex} method that does nothing (see
@ref{122a,,TestSuite.__iter__()}) (bpo-11798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11798}).

@item 
@ref{10c,,unittest} がコマンドライン解析に @ref{7,,argparse} を使うようになりました。このことで、以前は動作していた不当なコマンド形式で許されなくなったものがあります。理屈から言えばこれは後方互換性の問題ではないはずです。許されなくなったコマンド形式は意味をなしていなかったものですから、使われていたとは思えません。

@item 
The @ref{5a2,,re.split()}, @ref{122b,,re.findall()}, and @ref{5a3,,re.sub()} functions, and
the @ref{122c,,group()} and @ref{122d,,groups()} methods of
@code{match} objects now always return a `bytes' object when the string
to be matched is a @ref{193,,bytes-like object}.  Previously the return type
matched the input type, so if your code was depending on the return value
being, say, a @code{bytearray}, you will need to change your code.

@item 
@code{audioop} functions now raise an error immediately if passed string
input, instead of failing randomly later on (bpo-16685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16685}).

@item 
@ref{a77,,HTMLParser} の新規引数 `convert_charrefs' は現在は後方互換性維持のために @code{False} をデフォルトとしていますが、最終的には @code{True} がデフォルトになります。あなたのコードでは @ref{a77,,HTMLParser} の全ての呼び出しでこれをキーワード引数として明示することをお勧めします。 (bpo-13633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13633})

@item 
@ref{c96,,hmac.new()} 関数の `digestmod' 引数からデフォルト値が消える予定です。ので、 @ref{c96,,hmac.new()} 呼び出しは常に `digestmod' を明示するように修正すべきです。 (bpo-17276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17276})

@item 
@ref{174,,sysconfig.get_config_var()} にキー @code{SO} を渡すことと @ref{298,,sysconfig.get_config_vars()} の呼び出し結果から @code{SO} キーを探すことは非推奨です。このキーは文脈依存の @code{EXT_SUFFIX} または @code{SHLIB_SUFFIX} で置き換えられるべきです。 (bpo-19555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19555})

@item 
@code{open} 系関数にモード @code{U} を使っていたコードは修正すべきです。 @code{U} は Python 3 では無力であり、いずれはこれの使用は例外を投げるようになる予定です。使う関数に依存しますが、 `newline' 引数を使うか、あるいは必要であればストリームを @ref{9be,,TextIOWrapper} でラップしてその `newline' 引数を使うことで、その古い Python 2 の振る舞いと同等なものを実現出来ます。 (bpo-15204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15204})

@item 
スクリプト内から @code{pyvenv} を使っていて、pip がインストール `されない' ことを望むならば、コマンド呼び出しに @code{--without-pip} を追加しなければなりません。

@item 
indent を明示した場合の @ref{f40,,json.dump()} と @ref{f41,,json.dumps()} のデフォルトの振る舞いが変更されました。要素を区切るカンマが行末に来る場合の後ろに、空白を追加しなくなりました。これはその出力のテストを空白に繊細な比較をすることで行っている場合にだけ問題になります。 (bpo-16333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16333})

@item 
@ref{3e,,doctest} が拡張モジュールの @code{__doc__} 文字列から doctest を見つけるようになったので、doctest のテストディスカバリが拡張モジュールを含んでいてその中で doctest のようにみえるものが含まれていると、テスト実行時にこれまで見かけたことのないテスト失敗を目にするかもしれません。 (bpo-3158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3158})

@item 
@ref{1f,,collections.abc} モジュールが、Python スタートアップの改善の一環で少々リファクタリングが行われました。これの結果として @ref{1e,,collections} は自動で @ref{1f,,collections.abc} をインポートしなくなりました。もしもこの (文書化されていなかった) 暗黙でのインポートに依存していたのであれば、 @code{import collections.abc} として明示的にインポートを追加する必要があります。 (bpo-20784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20784})
@end itemize

@node C API の変更<15>,,Python API の変更<11>,Python 3 4 への移植
@anchor{whatsnew/3 4 changes-in-the-c-api}@anchor{122e}
@subsubsection C API の変更



@itemize *

@item 
いくつかの内部 C API とともに @ref{122f,,PyEval_EvalFrameEx()}, @ref{1230,,PyObject_Repr()}, @ref{1231,,PyObject_Str()} に、現在アクティブな例外を黙殺する状況で使われていないことを確かにするためのデバッグアサーションが仕込まれました。アクティブな例外を捨てることが期待されて望ましいケース (たとえば、既にローカルに @ref{428,,PyErr_Fetch()} で保存済みであるとか、異なる例外に置き換えることが意図である場合) は、アサーション有効でコンパイルされている Python バージョンで実行して、(直接的・間接的によらず) それら操作呼び出しがそのアサーションを発行するのを、明示的に @ref{1232,,PyErr_Clear()} 呼び出しをすることで潰してください。

@item 
@ref{f39,,PyErr_SetImportError()} が `msg' がセットされていない場合に @ref{198,,TypeError} をセットするようになりました。以前は例外をセットすることなく @code{NULL} を返すだけでした。

@item 
@ref{7a5,,PyOS_ReadlineFunctionPointer} コールバックは、エラー時に @code{NULL} を返すか @ref{631,,PyMem_RawMalloc()} または @ref{633,,PyMem_RawRealloc()} でアロケートした文字列を返さなければなりません。 @ref{e5f,,PyMem_Malloc()} や @ref{1233,,PyMem_Realloc()} でアロケートした文字列はダメです。 (bpo-16742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16742})

@item 
@ref{43b,,PyThread_set_key_value()} が必ず値をセットするようになりました。Python 3.3 ではこの関数はキーが既存 (で現在値が @code{NULL} ポインタでない) の場合には何もしませんでした。

@item 
@ref{98c,,PyFrameObject} 構造体のフィールド @code{f_tstate} (thread state) が、バグをフィックスするために削除されました: 論拠については bpo-14432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14432} を参照してください。
@end itemize

@node 3 4 3 の変更,,Python 3 4 への移植,What's New In Python 3 4
@anchor{whatsnew/3 4 changed-in-3-4-3}@anchor{1234}
@subsection 3.4.3 の変更


@menu
* PEP 476; stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化: PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化. 

@end menu

@node PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化,,,3 4 3 の変更
@anchor{whatsnew/3 4 pep-476}@anchor{1235}@anchor{whatsnew/3 4 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients}@anchor{1236}
@subsubsection PEP 476: stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化


@ref{73,,http.client} とこのモジュールを使っている例えば @ref{111,,urllib.request} や @ref{134,,xmlrpc.client}  が、サーバをプラットフォームが持つ信頼ストアにある CA により署名された証明書で検証し、そのホスト名がリクエストされたホスト名かどうかのチェックをデフォルトで行うようになりました。これは多くのアプリケーションにとって大幅なセキュリティ改善になります。

以前の古い振る舞いが必要なアプリケーションでは、代わりとなるコンテキストを渡せます:

@example
import urllib.request
import ssl

# This disables all verification
context = ssl._create_unverified_context()

# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib.request.urlopen("https://invalid-cert", context=context)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 3,What's New In Python 3 2,What's New In Python 3 4,What's New in Python
@anchor{whatsnew/3 3 doc}@anchor{1237}@anchor{whatsnew/3 3 translation-repo}@anchor{1238}@anchor{whatsnew/3 3 what-s-new-in-python-3-3}@anchor{1239}
@section What's New In Python 3.3


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

この記事では 3.2 と比較した Python 3.3 の新機能を解説します。 Python 3.3 は2012年9月29日にリリースされました。全詳細については 変更履歴@footnote{https://docs.python.jp/3.3/whatsnew/changelog.html} をご覧ください。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 398
PEP 398@footnote{https://peps.python.org/pep-0398/} - Python 3.3 リリーススケジュール


@menu
* 概要: 概要 -- リリースハイライト<12>. リリースハイライト
* 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; 明示的なユニコードリテラル: PEP 414 明示的なユニコードリテラル. 
* PEP 3155; クラスと関数の正規名: PEP 3155 クラスと関数の正規名. 
* PEP 412; キー共有辞書: PEP 412 キー共有辞書. 
* PEP 362; 関数シグニチャオブジェクト: PEP 362 関数シグニチャオブジェクト. 
* PEP 421; sys.implementation の追加: PEP 421 sys implementation の追加. 
* インポート実装としての importlib の使用:: 
* その他の言語変更: その他の言語変更<11>. 
* 細粒度のインポートロック:: 
* 組み込みの関数と型:: 
* 新たなモジュール: 新たなモジュール<11>. 
* 改良されたモジュール: 改良されたモジュール<11>. 
* 最適化: 最適化<11>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<4>. 
* 非推奨: 非推奨<13>. 
* Python 3.3 への移植: Python 3 3 への移植. 

@end menu

@node 概要 -- リリースハイライト<12>,PEP 405 仮想環境,,What's New In Python 3 3
@anchor{whatsnew/3 3 summary-release-highlights}@anchor{123a}
@subsection 概要 -- リリースハイライト


@c This section singles out the most important changes in Python 3.3.
@c Brevity is key.

新たな文法機能:


@itemize *

@item 
@ref{123b,,ジェネレータの委譲}. のための新しい @code{yield from} 式

@item 
@ref{169,,str} オブジェクト向けの @code{u'unicode'} 文法の再適用
@end itemize

新たなライブラリモジュール:


@itemize *

@item 
@ref{5c,,faulthandler} (低水準のクラッシュのデバッグを補助する)

@item 
@ref{84,,ipaddress} (IPアドレスとマスクを表す高水準オブジェクト)

@item 
@ref{8e,,lzma} (XZ / LZMA アルゴリズムを使用したデータ圧縮)

@item 
@ref{10d,,unittest.mock} (テスト向けにシステムの一部をモックオブジェクトで置き換える)

@item 
@ref{117,,venv} (人気の @code{virtualenv} パッケージのような、Python @ref{123c,,virtual environments})
@end itemize

新たな組み込み機能:


@itemize *

@item 
@ref{123d,,I/O 例外階層} の手直し
@end itemize

実装の改善:


@itemize *

@item 
@ref{123e,,インポート機構} を、 @ref{7b,,importlib} を元に書き換え

@item 
よりコンパクトな @ref{123f,,ユニコード文字列}.

@item 
よりコンパクトな @ref{1240,,属性辞書}.
@end itemize

ライブラリモジュールの大幅な改善:


@itemize *

@item 
@ref{1241,,decimal} モジュールのCによる高速化

@item 
@ref{1242,,email} モジュールでのより良いユニコード処理 (@ref{1243,,暫定版})
@end itemize

セキュリティの改善:


@itemize *

@item 
ハッシュのランダム化がデフォルトで有効になりました。
@end itemize

以降はユーザ向けの変更の包括的なリストになっています。

@node PEP 405 仮想環境,PEP 420 暗黙的な名前空間パッケージ,概要 -- リリースハイライト<12>,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-405}@anchor{123c}@anchor{whatsnew/3 3 pep-405-virtual-environments}@anchor{1244}
@subsection PEP 405: 仮想環境


仮想環境 (virtual environment) は隔離されたPython環境を作成する手助けをします。
一方で保守を容易にするために、システム全体のインストールを共有します。
仮想環境はそれ自身の site packages (つまりローカルにインストールされたライブラリ) を持ちつつ、任意でシステム全体の site packages と分離できます。
このコンセプトと実装は、人気のサードパーティパッケージである @code{virtualenv} を元にしていますが、インタプリタコアとの統合による恩恵を受けています。

この PEP はプログラムからのアクセス用の @ref{117,,venv} モジュールと、コマンドラインからのアクセスと管理向けの @code{pyvenv} スクリプトを追加します。Pythonインタプリタは仮想環境のディレクトリツリーの存在を示す @code{pyvenv.cfg} をチェックします。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 405

@item PEP 405@footnote{https://peps.python.org/pep-0405/} - Python Virtual Environments

PEP written by Carl Meyer; implementation by Carl Meyer and Vinay Sajip
@end table


@node PEP 420 暗黙的な名前空間パッケージ,PEP 3118 新たなメモリビューの実装とバッファプロトコルのドキュメント,PEP 405 仮想環境,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-420-implicit-namespace-packages}@anchor{1245}
@subsection PEP 420: 暗黙的な名前空間パッケージ


@code{__init__.py} マーカーファイルを必要としないパッケージディレクトリと、複数のモジュールパスをネイティブでサポートします(
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} に記載された様々なサードパーティでの名前空間のアプローチに影響されています)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 420

@item PEP 420@footnote{https://peps.python.org/pep-0420/} - Implicit Namespace Packages

PEP written by Eric V. Smith; implementation by Eric V. Smith
and Barry Warsaw
@end table


@node PEP 3118 新たなメモリビューの実装とバッファプロトコルのドキュメント,PEP 393 文字列の柔軟な表現,PEP 420 暗黙的な名前空間パッケージ,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-3118-new-memoryview-implementation-and-buffer-protocol-documentation}@anchor{1246}@anchor{whatsnew/3 3 pep-3118-update}@anchor{1247}
@subsection PEP 3118: 新たなメモリビューの実装とバッファプロトコルのドキュメント


@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} の実装が大幅に改善されました。

新しい memoryview 実装が、Py_buffer 構造体内にフィールドを動的にアロケートする際に多数のクラッシュの報告をもたらしていた全ての所有権問題、ライフタイム問題を包括的に解決しました。加えて、不連続もしくは多次元の入力に対してクラッシュしたり誤った結果を返していた多数の関数が修正されました。

memoryview オブジェクトに、 PEP-3118 準拠の getbufferproc() が追加されています
(訳注: @ref{1248,,バッファオブジェクト構造体 (buffer object structure)} 参照)。これはコンシューマの要求型をチェックします。多くの新機能が追加されており、これらのほとんどが不連続配列とサブオフセットを持つ配列に完全な一般化をもたらすものです。

@ref{260,,ドキュメント} が更新され、エキスポータ(提供側)とコンシューマ(利用側)両方についての責務をより明確に詳細化しています。 @ref{1249,,バッファ要求のフラグ} が、基本フラグと組合せフラグでグループ分けされています。不連続配列と多次元の NumPy スタイル行列のメモリレイアウトについて説明されています。

@menu
* フィーチャー:: 
* API の変更:: 

@end menu

@node フィーチャー,API の変更,,PEP 3118 新たなメモリビューの実装とバッファプロトコルのドキュメント
@anchor{whatsnew/3 3 features}@anchor{124a}
@subsubsection フィーチャー



@itemize *

@item 
struct モジュールの構文の全ての native @ref{124b,,書式指定文字} をサポートするようになりました ('@@' プレフィクスが付いていても良いです)。 (訳注: @ref{124c,,format} 参照。)

@item 
いくつかの制限はありますが、 @ref{124d,,cast()} メソッドでフォーマット変更と C-@ref{124e,,contiguous} 配列の形状 (shape) の変更を行うことが出来ます。

@item 
任意の配列型で多次元のリスト表現がサポートされるようになっています。

@item 
任意の配列型で多次元の比較がサポートされるようになっています。

@item 
'B', 'b', 'c' いずれかのフォーマットの @ref{824,,hashable} な (読み出し専用の) 型の1次元メモリビューもまた、 hashable です。 (Contributed by Antoine Pitrou in bpo-13411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13411}.)

@item 
Arbitrary slicing of any 1-D arrays type is supported. For example, it
is now possible to reverse a memoryview in `O'(1) by using a negative step.
@end itemize

@node API の変更,,フィーチャー,PEP 3118 新たなメモリビューの実装とバッファプロトコルのドキュメント
@anchor{whatsnew/3 3 api-changes}@anchor{124f}
@subsubsection API の変更



@itemize *

@item 
最大 @ref{1250,,次元} は公式に 64 に制限されています。

@item 
空の @ref{1251,,shape}, 空の @ref{1252,,strides}, 空の @ref{1253,,suboffsets} を表現するのに以前は @code{None} を用いていましたが今ではこれは空のタプルです。

@item 
フォーマット 'B' (unsigned bytes) での memoryview 要素へのアクセスは整数を返すようになりました (struct モジュールでの構文に従っています)。bytes オブジェクトが欲しければまずビューを 'c' で @ref{124d,,cast()} しなければなりません。

@item 
memoryview どうしの比較は被演算対象の論理構造を使って行うようになり、また、全ての配列要素は値で比較されます。struct モジュールの構文の全てのフォーマット文字でサポートされます。認識出来ないフォーマット文字でのビューは今でも許されていますが、ビューの指す中身によらずこれは常に等しくないとされます。

@item 
ほかの変更については、 @ref{1254,,ビルドならびに C API の変更} と @ref{1255,,C コードの移植} を参照してください。
@end itemize

(Contributed by Stefan Krah in bpo-10181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10181}.)


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} - Revising the Buffer Protocol


@node PEP 393 文字列の柔軟な表現,PEP 397 Windows の Python ランチャ,PEP 3118 新たなメモリビューの実装とバッファプロトコルのドキュメント,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-393}@anchor{123f}@anchor{whatsnew/3 3 pep-393-flexible-string-representation}@anchor{1256}
@subsection PEP 393: 文字列の柔軟な表現


Unicode 文字列型が、複数の内部表現 (1、2 または 4 バイトで表現される Unicode 序数(ordinal) の最大値依存) を、表現される文字列内でサポートするように変更されました (訳注: 以前までは Python のビルド時に固定で決めていました)。このことは全てのシステムにおいて、一般のケースでは空間効率の良い表現をしながらも UCS-4 へのフルアクセスを与えます。既存の API との互換性のために複数の表現が並行で存在することになりますが、徐々にこの互換性はなくされていくはずです。

Python 側にはこの変更による不都合は何もないはずです。

C API 側では 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} は完全に後方互換です。レガシーな API は最低 5 年は残されるはずです。レガシー API を使うアプリケーションはメモリ削減の効能が完全には得られないか、あるいは最悪の場合には少し余計なメモリを使うかもしれません。これは Python がそれぞれの文字列の二つのバージョン (レガシーなフォーマットと新しい効率的な格納方法) を維持する必要があるかもしれないからです

@menu
* 機能性:: 
* 性能およびリソース使用量:: 

@end menu

@node 機能性,性能およびリソース使用量,,PEP 393 文字列の柔軟な表現
@anchor{whatsnew/3 3 functionality}@anchor{1257}
@subsubsection 機能性


@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} でなされた変更は以下の通りです:


@itemize *

@item 
Python は今や非 BMP 面の文字を含む Unicode コードポイントの完全な範囲 (つまり @code{U+0000} から @code{U+10FFFF} まで) を常にサポートします。narrow ビルド / wide ビルドという区別は今では存在していないため、Python は今ではいつでもかつての wide ビルドのように振る舞い、Windows でもこれは例外ではありません。

@item 
narrow ビルドとの決別は、それに付き物だった問題も解決しました。例えば:


@itemize *

@item 
@ref{840,,len()} は今では非 BMP 面文字について必ず 1 を返します。つまり @code{len('\U0010FFFF') == 1} です;

@item 
サロゲートペアが文字列リテラル内で再結合されることはありません。つまり @code{'\uDBFF\uDFFF' != '\U0010FFFF'} です;

@item 
非 BMP 面文字を指すインデクスやスライスは期待通りの値を返します。つまり @code{'\U0010FFFF'[0]} は今では @code{'\uDBFF'} ではなく @code{'\U0010FFFF'} を返します;

@item 
ほかの全ての標準ライブラリ関数が今では正しく非 BMP コードポイントを処理します。
@end itemize

@item 
@ref{1258,,sys.maxunicode} の値は今やいつでも @code{1114111} (十六進で @code{0x10FFFF}) です。後方互換性のために C API の @code{PyUnicode_GetMax()} 関数は今でも @code{0xFFFF} か @code{0x10FFFF} のどちらかを返すようになってはいますが、新しい Unicode API とともには使ってはいけません (see bpo-13054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13054})。

@item 
@code{./configure} スクリプトのフラグ @code{--with-wide-unicode} は削除されました。
@end itemize

@node 性能およびリソース使用量,,機能性,PEP 393 文字列の柔軟な表現
@anchor{whatsnew/3 3 performance-and-resource-usage}@anchor{1259}
@subsubsection 性能およびリソース使用量


Unicode 文字列の記憶域サイズが文字列内のコードポイント最大値に依存するようになったということです:


@itemize *

@item 
純粋な ASCII と Latin1 文字列 (@code{U+0000-U+00FF}) はコードポイントごとに 1 バイトを占めます;

@item 
BMP 文字列 (@code{U+0000-U+FFFF}) はコードポイントごとに 2 バイトを占めます;

@item 
非 BMP 文字列 (@code{U+10000-U+10FFFF}) はコードポイントごとに 4 バイトを占めます。
@end itemize

結局のところほとんどのアプリケーションにとってのこれの効能は、文字列記憶のためのメモリ使用量が激減することで、これは以前の wide unicode ビルドと比較して顕著です。これは多くの場合、インターナショナルな文脈であってもなお純粋な ASCII が使われるであろうことに関係があります。(というのも多くの文字列が人間向けでない言語として格納されるからです。例えば XML フラグメンツや HTTP ヘッダ、JSON エンコードされたデータ、などなど。)同じ理由から、大きなアプリケーションで CPU キャッシュ活用効率を高めるであろうことも期待出来ます。Python 3.3 のメモリ使用は Python 3.2 の 2 倍から 3 倍小さく、また、Python 2.7 よりも少し良いことが Django ベンチマークでわかっています (詳細は PEP をみてください)。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 393

@item PEP 393@footnote{https://peps.python.org/pep-0393/} - 文字列の柔軟な表現 (Flexible String Representation)

PEP written by Martin von Löwis; implementation by Torsten Becker
and Martin von Löwis.
@end table


@node PEP 397 Windows の Python ランチャ,PEP 3151 OS および IO 例外階層の手直し,PEP 393 文字列の柔軟な表現,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-397}@anchor{125a}@anchor{whatsnew/3 3 pep-397-python-launcher-for-windows}@anchor{125b}
@subsection PEP 397: Windows の Python ランチャ


Python 3.3 の Windows インストーラが、ランチャアプリケーションの @code{py} をインストールするようになりました。これは Python をバージョンに依存しない方法で起動するのに使われます。

ランチャは @code{*.py} ファイルをダブルクリックすると暗黙のうちに呼び出されます。システムにインストールされているのが単一の Python バージョンであれば、そのバージョンがファイルの実行に使われます。複数バージョンがインストールされていればデフォルトでは最新バージョンが使われますが、Python スクリプト内で Unix スタイルの「shebang 行 ( @code{#!} )」を含めることでオーバライド出来ます。

ランチャは明示的にコマンドラインから @code{py} アプリケーションとして使うことも出来ます。 @code{py} の実行は暗黙にスクリプトを起動するバージョン選択のルールに従いますが、与えるコマンドライン引数により狙ったバージョンを選択出来ます (たとえば @code{-3} は Python 2 もインストールされている際に Python 3 を要求し、 @code{-2.6} はもっと新しいバージョンがインストールされている場合に特定の古いバージョンを要求します)。

ランチャに加え、Windows インストーラには新しくインストールする Python をシステムの PATH に追加するオプションが含まれるようになりました。 (Contributed by Brian Curtin in bpo-3561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3561}.)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 397

@item PEP 397@footnote{https://peps.python.org/pep-0397/} - Python Launcher for Windows

PEP written by Mark Hammond and Martin v. Löwis; implementation by
Vinay Sajip.
@end table

ランチャのドキュメント: @ref{7da,,Python install manager}

インストーラ PATH の調整: @ref{125c,,Python install manager}


@node PEP 3151 OS および IO 例外階層の手直し,PEP 380 サブジェネレータへの委譲構文,PEP 397 Windows の Python ランチャ,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-3151}@anchor{123d}@anchor{whatsnew/3 3 pep-3151-reworking-the-os-and-io-exception-hierarchy}@anchor{125d}
@subsection PEP 3151: OS および IO 例外階層の手直し


OS エラーが送出する例外の階層が単純化され、粒度が下げられました。

You don't have to worry anymore about choosing the appropriate exception
type between @ref{2c0,,OSError}, @ref{125e,,IOError}, @ref{125f,,EnvironmentError},
@ref{1260,,WindowsError}, @code{mmap.error}, @ref{1261,,socket.error} or
@ref{1262,,select.error}.  All these exception types are now only one:
@ref{2c0,,OSError}.  The other names are kept as aliases for compatibility
reasons.

また、特定のエラー条件を捕捉するのが容易になりました。
@code{errno} 属性 (または @code{args[0]}) の特定の定数を @ref{5b,,errno} モジュールから調べる代わりに、適切な @ref{2c0,,OSError} 派生クラスを捕捉することが出来ます。
利用可能な派生クラスは以下の通りです:


@itemize *

@item 
@ref{235,,BlockingIOError}

@item 
@ref{1263,,ChildProcessError}

@item 
@ref{100b,,ConnectionError}

@item 
@ref{1221,,FileExistsError}

@item 
@ref{264,,FileNotFoundError}

@item 
@ref{f88,,InterruptedError}

@item 
@ref{1264,,IsADirectoryError}

@item 
@ref{1265,,NotADirectoryError}

@item 
@ref{f3e,,PermissionError}

@item 
@ref{1266,,ProcessLookupError}

@item 
@ref{a36,,TimeoutError}
@end itemize

@ref{100b,,ConnectionError} 自身には細かな派生クラスがあります:


@itemize *

@item 
@ref{1267,,BrokenPipeError}

@item 
@ref{1268,,ConnectionAbortedError}

@item 
@ref{1269,,ConnectionRefusedError}

@item 
@ref{126a,,ConnectionResetError}
@end itemize

新たな例外のおかげで @ref{5b,,errno} の一般的な使い方を避けることが出来ます。
例えば、Python 3.2 向けに書かれた以下のコード:

@example
from errno import ENOENT, EACCES, EPERM

try:
    with open("document.txt") as f:
        content = f.read()
except IOError as err:
    if err.errno == ENOENT:
        print("document.txt file is missing")
    elif err.errno in (EACCES, EPERM):
        print("You are not allowed to read document.txt")
    else:
        raise
@end example

は @ref{5b,,errno} をインポートしたり手動で例外属性を調べたりせずに書くことが出来ます:

@example
try:
    with open("document.txt") as f:
        content = f.read()
except FileNotFoundError:
    print("document.txt file is missing")
except PermissionError:
    print("You are not allowed to read document.txt")
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3151

@item PEP 3151@footnote{https://peps.python.org/pep-3151/} - Reworking the OS and IO Exception Hierarchy

PEP written and implemented by Antoine Pitrou
@end table


@geindex yield;yield from (in What's New)

@node PEP 380 サブジェネレータへの委譲構文,PEP 409 例外コンテキストの抑制,PEP 3151 OS および IO 例外階層の手直し,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-380}@anchor{123b}@anchor{whatsnew/3 3 pep-380-syntax-for-delegating-to-a-subgenerator}@anchor{126b}
@subsection PEP 380: サブジェネレータへの委譲構文


PEP 380 は @code{yield from} 式を追加します。これは @ref{126c,,ジェネレータ} に、その操作の一部をほかのジェネレータに委譲するための式です。これによって @ref{bc2,,yield} を含んでいるコードのセクションをほかのジェネレータに移動出来るでしょう。加えてサブジェネレータは値を伴って戻ることが出来、その戻り値は委譲した側のジェネレータで使えます。

@code{yield from} 式がデザインされた主たる動機はサブジェネレータへの委譲として使うことではありますが、実際には任意のサブイテレータに委譲することも出来ます。

単純なイテレータに対して、 @code{yield from iterable} は本質的には @code{for item in iterable: yield item} への単なる速記法です:

@example
>>> def g(x):
...     yield from range(x, 0, -1)
...     yield from range(x)
...
>>> list(g(5))
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
@end example

ですが普通のループとは違って @code{yield from} ではサブジェネレータは、呼び出し側スコープから @ref{126d,,send()} されたり @ref{71c,,throw()} された値を直接受け取ることができ、また、外側のジェネレータに最終的な値を返せます:

@example
>>> def accumulate():
...     tally = 0
...     while 1:
...         next = yield
...         if next is None:
...             return tally
...         tally += next
...
>>> def gather_tallies(tallies):
...     while 1:
...         tally = yield from accumulate()
...         tallies.append(tally)
...
>>> tallies = []
>>> acc = gather_tallies(tallies)
>>> next(acc)  # Ensure the accumulator is ready to accept values
>>> for i in range(4):
...     acc.send(i)
...
>>> acc.send(None)  # Finish the first tally
>>> for i in range(5):
...     acc.send(i)
...
>>> acc.send(None)  # Finish the second tally
>>> tallies
[6, 10]
@end example

この変更を推し進める一番本質にあったものは、たとえ @code{send} メソッドや @code{throw} メソッドとともに使われることを前提に設計されたジェネレータであっても、大きな関数を複数のサブ関数に分割するのと同じくらいに、ジェネレータを簡単に複数のサブジェネレータに分割出来るようにすることでした。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 380

@item PEP 380@footnote{https://peps.python.org/pep-0380/} - サブジェネレータへの委譲構文

PEP written by Greg Ewing; implementation by Greg Ewing, integrated into
3.3 by Renaud Blanch, Ryan Kelly and Nick Coghlan; documentation by
Zbigniew Jędrzejewski-Szmek and Nick Coghlan
@end table


@node PEP 409 例外コンテキストの抑制,PEP 414 明示的なユニコードリテラル,PEP 380 サブジェネレータへの委譲構文,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-409-suppressing-exception-context}@anchor{126e}
@subsection PEP 409: 例外コンテキストの抑制


PEP 409 は、チェインされた例外コンテキストの表示を無効にするための新構文を導入します。これを使えば例外翻訳して投げ直すようなアプリケーションで、エラーメッセージをわかりやすくすることが出来ます:

@example
>>> class D:
...     def __init__(self, extra):
...         self._extra_attributes = extra
...     def __getattr__(self, attr):
...         try:
...             return self._extra_attributes[attr]
...         except KeyError:
...             raise AttributeError(attr) from None
...
>>> D(@{@}).x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __getattr__
AttributeError: x
@end example

元となる要因例外を抑制する @code{from None} を後置しなければ、もとの例外はデフォルトで表示されます:

@example
>>> class C:
...     def __init__(self, extra):
...         self._extra_attributes = extra
...     def __getattr__(self, attr):
...         try:
...             return self._extra_attributes[attr]
...         except KeyError:
...             raise AttributeError(attr)
...
>>> C(@{@}).x
Traceback (most recent call last):
  File "<stdin>", line 6, in __getattr__
KeyError: 'x'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __getattr__
AttributeError: x
@end example

抑制することでデバッグ能力が失われるというわけではなくて、元々の例外コンテキストは利用可能なままです。(例えば介在するライブラリが有益な背後の詳細を不適切に隠してしまっているなど、必要な場合はあるでしょう。)

@example
>>> try:
...     D(@{@}).x
... except AttributeError as exc:
...     print(repr(exc.__context__))
...
KeyError('x',)
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 409

@item PEP 409@footnote{https://peps.python.org/pep-0409/} - 例外コンテキストの抑制

PEP written by Ethan Furman; implemented by Ethan Furman and Nick
Coghlan.
@end table


@node PEP 414 明示的なユニコードリテラル,PEP 3155 クラスと関数の正規名,PEP 409 例外コンテキストの抑制,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-414-explicit-unicode-literals}@anchor{126f}
@subsection PEP 414: 明示的なユニコードリテラル


Unicode を意識する Python アプリケーションが Python 2 で Unicode リテラルを多用しているとしても Python 3 への移行を容易にするために、Python 3.3 では文字列リテラルへの "@code{u}" 前置を再びサポートすることにしました。この前置は Python 3 自身では何らの意味も持ちはせず、Python 3 への移行において純粋な機械的変更を要する事項を単に減らすためだけのために提供されます。開発者はもっと重要な意味的変更 (たとえばバイナリとテキストの厳密な区別) に集中すべきなのです。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 414

@item PEP 414@footnote{https://peps.python.org/pep-0414/} - 明示的なユニコードリテラル

PEP written by Armin Ronacher.
@end table


@node PEP 3155 クラスと関数の正規名,PEP 412 キー共有辞書,PEP 414 明示的なユニコードリテラル,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-3155-qualified-name-for-classes-and-functions}@anchor{1270}
@subsection PEP 3155: クラスと関数の正規名


Functions and class objects have a new @ref{1271,,__qualname__}
attribute representing
the "path" from the module top-level to their definition.  For global functions
and classes, this is the same as @ref{1272,,__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
>>> class C:
...     def meth(self):
...         pass
...
>>> C.meth.__name__
'meth'
>>> C.meth.__qualname__
'C.meth'
@end example

入れ子のクラスでの例:

@example
>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.D.__name__
'D'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__name__
'meth'
>>> C.D.meth.__qualname__
'C.D.meth'
@end example

入れ子の関数の例:

@example
>>> def outer():
...     def inner():
...         pass
...     return inner
...
>>> outer().__name__
'inner'
>>> outer().__qualname__
'outer.<locals>.inner'
@end example

それらオブジェクトの文字列表現も、この新しくてより正確な情報を含むように変更されています:

@example
>>> str(C.D)
"<class '__main__.C.D'>"
>>> str(C.D.meth)
'<function C.D.meth at 0x7f46b9fe31e0>'
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3155

@item PEP 3155@footnote{https://peps.python.org/pep-3155/} - クラスと関数の正規名 (qualified name)

PEP written and implemented by Antoine Pitrou.
@end table


@node PEP 412 キー共有辞書,PEP 362 関数シグニチャオブジェクト,PEP 3155 クラスと関数の正規名,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-412}@anchor{1240}@anchor{whatsnew/3 3 pep-412-key-sharing-dictionary}@anchor{1273}
@subsection PEP 412: キー共有辞書


オブジェクト属性を記憶するのに使われる辞書が、内部記憶域の一部 (キーとそれに対応するハッシュ値) を互いに共有出来るようになりました。これにより、組み込みでない型のインスタンスをたくさん作るプログラムのメモリ消費が少なくなります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 412

@item PEP 412@footnote{https://peps.python.org/pep-0412/} - キー共有辞書

PEP written and implemented by Mark Shannon.
@end table


@node PEP 362 関数シグニチャオブジェクト,PEP 421 sys implementation の追加,PEP 412 キー共有辞書,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-362-function-signature-object}@anchor{1274}
@subsection PEP 362: 関数シグニチャオブジェクト


新たに追加された関数 @ref{22f,,inspect.signature()} は、Python 呼び出し可能オブジェクト (callable) を調べることを簡単で直接的なものにしてくれます。幅広い callable をサポートしています:デコレートされているかどうかによらず関数、クラス、 @ref{217,,functools.partial()} オブジェクト。新たに追加されたクラス群 @ref{4e3,,inspect.Signature}, @ref{4e4,,inspect.Parameter}, @ref{1275,,inspect.BoundArguments} は、アノテーション、デフォルト値、パラメータの種類、束縛されている引数などのような呼び出しシグニチャについての情報を保持し、これによって、デコレータを書いたりあるいは呼び出しシグニチャや引数を検証したり改訂したりするコードを書くことが、非常に単純になります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 362

@item PEP 362@footnote{https://peps.python.org/pep-0362/}: - 関数シグニチャオブジェクト

PEP written by Brett Cannon, Yury Selivanov, Larry Hastings, Jiwon Seo;
implemented by Yury Selivanov.
@end table


@node PEP 421 sys implementation の追加,インポート実装としての importlib の使用,PEP 362 関数シグニチャオブジェクト,What's New In Python 3 3
@anchor{whatsnew/3 3 pep-421-adding-sys-implementation}@anchor{1276}
@subsection PEP 421: sys.implementation の追加


@ref{df,,sys} モジュールに新規属性が追加され、これは現在動作中のインタープリタ実装に固有の詳細を公開します。その @ref{73b,,sys.implementation} 属性の手始めの集合として、 @code{name}, @code{version}, @code{hexversion}, @code{cache_tag} が定義されています。

@code{sys.implementation} の真意は、標準ライブラリによって利用される実装固有の情報を一つの名前空間で一元管理することにあります。このことにより異なる Python 実装が単一の標準ライブラリのコードベースを共有することが、もっとずっと簡単になります。今時点での初期状態では @code{sys.implementation} は実装固有データのごく一部を保持しているだけです。標準ライブラリの移植性がもっと高くなるように、徐々にこの比率が変わっていくでしょう。

標準ライブラリの移植性を改善した一例が @code{cache_tag} です。Python 3.3 以降は @code{sys.implementation.cache_tag} が 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} をサポートするために @ref{7b,,importlib} により使われます。組み込みのインポートシステムのために @code{importlib} を使う全ての Python 実装が、モジュールのキャッシュの振る舞いを制御するのに @code{cache_tag} を利用できます。

@menu
* SimpleNamespace:: 

@end menu

@node SimpleNamespace,,,PEP 421 sys implementation の追加
@anchor{whatsnew/3 3 simplenamespace}@anchor{1277}
@subsubsection SimpleNamespace


@code{sys.implementation} の実現に伴って Python に新たな型 @ref{4e5,,types.SimpleNamespace} が導入されることとなりました。 @ref{183,,dict} のようなマッピングベースの名前空間とは対照的に、 @code{SimpleNamespace} は @ref{c7e,,object} のような属性ベースです。ですが @code{object} とは違って @code{SimpleNamespace} インスタンスは書き込み可能です。つまり普通の属性アクセスを通じて名前空間に追加したり削除したり修正したりできます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 421

@item PEP 421@footnote{https://peps.python.org/pep-0421/} - sys.implementation の追加

PEP written and implemented by Eric Snow.
@end table


@node インポート実装としての importlib の使用,その他の言語変更<11>,PEP 421 sys implementation の追加,What's New In Python 3 3
@anchor{whatsnew/3 3 importlib}@anchor{123e}@anchor{whatsnew/3 3 using-importlib-as-the-implementation-of-import}@anchor{1278}
@subsection インポート実装としての importlib の使用


bpo-2377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2377} - Replace __import__ w/ importlib.__import__
bpo-13959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13959} - Re-implement parts of @code{imp} in pure Python
bpo-14605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14605} - Make import machinery explicit
bpo-14646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14646} - Require loaders set __loader__ and __package__

@ref{ad1,,__import__()} 関数を @ref{1279,,importlib.__import__()} によって実現するようにしました。これは 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} の「第二段階」を完了させるものです。この変更には複数の恩恵があります。まず最初にこれはインポートの機構を、C コードの奥深くで暗黙に秘密裏に行うのではなく、より透明化します。このことで、Python 3.3 をサポートする全ての Python VM で単一の実装を用いることが出来るようになり、インポートのセマンティクスにおける VM 固有の逸脱と決別する助けともなります。そしてこれはインポート機構の保守をより容易とし、将来起こりうる進化を促します。

一般のユーザにとっては、セマンティクスにおいて目に見える変化はないはずです。今時点でインポートを操作したりインポート呼び出しをプログラム的に行っている場合は、このドキュメントの @ref{127a,,Python コードの移植} でカバーしているコードの修正が必要になるかもしれません。

@menu
* 新たな API:: 
* 目に見える変化:: 

@end menu

@node 新たな API,目に見える変化,,インポート実装としての importlib の使用
@anchor{whatsnew/3 3 new-apis}@anchor{127b}
@subsubsection 新たな API


この変更による一番大きな恩恵の一つは、インポート文の動作に何が介在するのかについて露になったことです。つまりかつては様々なインポータが暗黙で行っていたことが、今では完全に @ref{7b,,importlib} パッケージの一部として公開されています。

The abstract base classes defined in @ref{7c,,importlib.abc} have been expanded
to properly delineate between @ref{127c,,meta path finders}
and @ref{127d,,path entry finders} by introducing
@ref{a6e,,importlib.abc.MetaPathFinder} and
@ref{a6f,,importlib.abc.PathEntryFinder}, respectively. The old ABC of
@code{importlib.abc.Finder} is now only provided for backwards-compatibility
and does not enforce any method requirements.

In terms of finders, @ref{127e,,importlib.machinery.FileFinder} exposes the
mechanism used to search for source and bytecode files of a module. Previously
this class was an implicit member of @ref{1225,,sys.path_hooks}.

ローダ (loader) については、新規の抽象基底クラス @ref{127f,,importlib.abc.FileLoader} が、モジュールのコードを格納する機構としてのファイルシステムを使うローダを書く助けとなります。ソースファイルのローダ (@ref{1280,,importlib.machinery.SourceFileLoader})、ソースを持たないバイトコードのためのローダ (@ref{1281,,importlib.machinery.SourcelessFileLoader})、そして拡張モジュールのためのローダ (@ref{eae,,importlib.machinery.ExtensionFileLoader}) が今では直接的に利用出来ます。

@ref{65b,,ImportError} には属性 @code{name} と @code{path} が追加されて、これには提供すべき関連データがある場合にセットされます。インポート失敗時のメッセージも、これまでのようにモジュール名の末尾だけを与えるのではなく、モジュールの完全名を提供するようになりました。

The @ref{e0a,,importlib.invalidate_caches()} function will now call the method with
the same name on all finders cached in @ref{7fa,,sys.path_importer_cache} to help
clean up any stored state as necessary.

@node 目に見える変化,,新たな API,インポート実装としての importlib の使用
@anchor{whatsnew/3 3 visible-changes}@anchor{1282}
@subsubsection 目に見える変化


潜在的に必要となるかもしれないコード修正については、 @ref{127a,,Python コードの移植} セクションを参照してください。

@ref{7b,,importlib} によって公開されるものが拡がったことによる、インポートについてのほかの目に見える変化があります。最大の変化は @ref{f27,,sys.meta_path} と @ref{1225,,sys.path_hooks} が、インポートで使われる meta path finder と path entry hook の全てを格納するようになったことです。以前はファインダは直接的に公開されるのではなく、インポートの C コード内に暗黙のものとして隠されていました。このことによって、今では望めば要件に合うようファインダを取り除いたり順序を変えたりといったことが簡単に行えるようになっています。

もう一つの変化は、モジュール生成時に使われたローダを格納する @code{__loader__} 属性を、全てのモジュールが持つようになったことです。 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} はローダの実装においてこの属性をセットすることを必須とするよう更新されました。ですので今後サードパーティのローダが更新されれば、この属性の存在に依存出来るようになります。ですがそのときが来るまでは、インポート処理がモジュールのロードの後処理としてセットします。

さらにローダが 
@geindex Python Enhancement Proposals; PEP 366
PEP 366@footnote{https://peps.python.org/pep-0366/} よりの @code{__package__} 属性を設定することも期待出来るようになりました。繰り返しになりますがインポート処理自身が既にこれを全てのローダで @ref{7b,,importlib} より行っていて、また、インポート処理自身がこの属性をロードの後処理としてセットしています。

@code{None} is now inserted into @ref{7fa,,sys.path_importer_cache} when no finder
can be found on @ref{1225,,sys.path_hooks}. Since @code{imp.NullImporter} is not
directly exposed on @ref{1225,,sys.path_hooks} it could no longer be relied upon to
always be available to use as a value representing no finder found.

全てのほかの変更は、Python 3.3 へのコードの更新の際に考慮すべきセマンティクスの変更に関係しています。ですのでそららについて、このドキュメントの @ref{127a,,Python コードの移植} セクションを読むべきです。

(Implementation by Brett Cannon)

@node その他の言語変更<11>,細粒度のインポートロック,インポート実装としての importlib の使用,What's New In Python 3 3
@anchor{whatsnew/3 3 other-language-changes}@anchor{1283}
@subsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
Added support for Unicode name aliases and named sequences.
Both @ref{1284,,unicodedata.lookup()} and @code{'\N@{...@}'} now resolve name aliases,
and @ref{1284,,unicodedata.lookup()} resolves named sequences too.

(Contributed by Ezio Melotti in bpo-12753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12753}.)

@item 
Unicode データベースを UCD バージョン 6.1.0 にアップグレードしました。

@item 
@ref{b3d,,range()} オブジェクトどうしの等値性比較が、それぞれの range オブジェクトによって生成されるシーケンスの等値性を反映して行われるようになりました (bpo-13201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13201})。

@item 
@ref{192,,bytes} と @ref{344,,bytearray} オブジェクトのメソッド @code{count()}, @code{find()}, @code{rfind()}, @code{index()}, @code{rindex()} が、第一引数に 0 から 255 の整数を受け付けるようになりました。

(Contributed by Petri Lehtinen in bpo-12170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12170}.)

@item 
@ref{192,,bytes} と @ref{344,,bytearray} オブジェクトのメソッド @code{rjust()}, @code{ljust()}, @code{center()} が、 @code{fill} 引数として @ref{344,,bytearray} を受け付けるようになりました  (Contributed by Petri Lehtinen in bpo-12380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12380}.)。

@item 
New methods have been added to @ref{24d,,list} and @ref{344,,bytearray}:
@code{copy()} and @code{clear()} (bpo-10516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10516}).  Consequently,
@ref{4bf,,MutableSequence} now also defines a
@code{clear()} method (bpo-11388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11388}).

@item 
raw bytes リテラルとして @code{br"..."} だけでなく  @code{rb"..."} とも書けるようになりました。

(Contributed by Antoine Pitrou in bpo-13748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13748}.)

@item 
@ref{1285,,dict.setdefault()} が与えられたキーのルックアップを一度しか行わないようになったので、組み込み型でのこれの使用はアトミックになります。(訳注: 外部観察可能な変化で説明すると、以前はこの呼び出しが、キーの2回の __hash__、__eq__ 呼び出しを引き起こしていたものが、1回になった。)

(Contributed by Filip Gruszczyński in bpo-13521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13521}.)

@item 
関数呼び出しが関数シグニチャに合致しない場合のエラーメッセージがかなり改善されました。

(Contributed by Benjamin Peterson.)
@end itemize

@node 細粒度のインポートロック,組み込みの関数と型,その他の言語変更<11>,What's New In Python 3 3
@anchor{whatsnew/3 3 a-finer-grained-import-lock}@anchor{1286}
@subsection 細粒度のインポートロック


以前のバージョンの CPython では、常に大域的なインポートロックを当てにしていました。このことは意図せず頭痛の種を持ち込むこと繋がっていました。たとえば、モジュールをインポートすることで副作用として異なるスレッドでのコード実行を引き起こす際に起こる、デッドロックといったことです。不恰好な回避策がときどき採用されてきました。C API 関数 @ref{3db,,PyImport_ImportModuleNoBlock()} などです。

Python 3.3 ではモジュールのインポートでは、モジュール単位でのロックを採用しています。このことによって複数スレッドからの指定モジュールのインポートは (モジュールが不完全な初期化のまま曝されるのを防いで) 正しく直列化されて、前述の頭痛の種は取り除かれています。

(Contributed by Antoine Pitrou in bpo-9260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9260}.)

@node 組み込みの関数と型,新たなモジュール<11>,細粒度のインポートロック,What's New In Python 3 3
@anchor{whatsnew/3 3 builtin-functions-and-types}@anchor{1287}
@subsection 組み込みの関数と型



@itemize *

@item 
@ref{316,,open()} 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 @ref{1288,,os.O_CLOEXEC} for
example. The @code{'x'} mode was added: open for exclusive creation, failing if
the file already exists.

@item 
@ref{1177,,print()}: `flush' キーワード引数が追加されました。`flush' キーワード引数が真の場合ストリームは強制的にフラッシュされます。

@item 
@ref{801,,hash()}: ハッシュのランダム化がデフォルトで有効になりました。 @ref{cf3,,object.__hash__()} と環境変数 
@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} を参照してください。

@item 
@ref{169,,str} 型に @ref{fd6,,casefold()} メソッドが追加されました。文字列の casefold されたコピーを返します。casefold された文字列は、大文字小文字に関係ないマッチに使えます。例えば @code{'ß'.casefold()} は @code{'ss'} を返します。

@item 
シーケンスについてのドキュメントを大幅に書き換えました。バイナリのシーケンスとテキストのシーケンスについての区別についてより良い説明を加え、また、個々の組み込みシーケンスに関して個別のドキュメントを提供しています (bpo-4966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4966})。
@end itemize

@node 新たなモジュール<11>,改良されたモジュール<11>,組み込みの関数と型,What's New In Python 3 3
@anchor{whatsnew/3 3 new-modules}@anchor{128a}
@subsection 新たなモジュール


@menu
* faulthandler: faulthandler<5>. 
* ipaddress: ipaddress<6>. 
* lzma: lzma<2>. 

@end menu

@node faulthandler<5>,ipaddress<6>,,新たなモジュール<11>
@anchor{whatsnew/3 3 faulthandler}@anchor{128b}
@subsubsection faulthandler


This new debug module @ref{5c,,faulthandler} contains functions to dump Python tracebacks explicitly,
on a fault (a crash like a segmentation fault), after a timeout, or on a user
signal. Call @ref{20f,,faulthandler.enable()} to install fault handlers for the
@ref{128c,,SIGSEGV}, @ref{128d,,SIGFPE}, @ref{128e,,SIGABRT},
@ref{128f,,SIGBUS}, and @ref{1290,,SIGILL} signals.
You can also enable them at startup by setting the 
@geindex PYTHONFAULTHANDLER
@geindex 環境変数; PYTHONFAULTHANDLER
@ref{1291,,PYTHONFAULTHANDLER}
environment variable or by using @ref{16f,,-X} @code{faulthandler} command line option.

Linuxでのセグメンテーションフォールト時の例:

@example
$ python -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault

Current thread 0x00007fb899f39700:
  File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
  File "<stdin>", line 1 in <module>
Segmentation fault
@end example

@node ipaddress<6>,lzma<2>,faulthandler<5>,新たなモジュール<11>
@anchor{whatsnew/3 3 ipaddress}@anchor{1292}
@subsubsection ipaddress


新規モジュール @ref{84,,ipaddress} は、IPv4/IPv6 アドレス、ネットワーク、インターフェース (すなわち固有の IP サブネットで関連付けられる IP アドレス) を表現するオブジェクトを生成したり加工したりするための道具立てを提供します。

(Contributed by Google and Peter Moody in 
@geindex Python Enhancement Proposals; PEP 3144
PEP 3144@footnote{https://peps.python.org/pep-3144/}.)

@node lzma<2>,,ipaddress<6>,新たなモジュール<11>
@anchor{whatsnew/3 3 lzma}@anchor{1293}
@subsubsection lzma


The newly added @ref{8e,,lzma} module provides data compression and decompression
using the LZMA algorithm, including support for the @code{.xz} and @code{.lzma}
file formats.

(Contributed by Nadeem Vawda and Per Øyvind Karlsen in bpo-6715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6715}.)

@node 改良されたモジュール<11>,最適化<11>,新たなモジュール<11>,What's New In Python 3 3
@anchor{whatsnew/3 3 improved-modules}@anchor{1294}
@subsection 改良されたモジュール


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

@end menu

@node abc<2>,array<4>,,改良されたモジュール<11>
@anchor{whatsnew/3 3 abc}@anchor{1295}
@subsubsection abc


Improved support for abstract base classes containing descriptors composed with
abstract methods. The recommended approach to declaring abstract descriptors is
now to provide @code{__isabstractmethod__} as a dynamically updated
property. The built-in descriptors have been updated accordingly.


@itemize *

@item 
@ref{1296,,abc.abstractproperty} は非推奨となりました。代わりに @ref{1297,,abc.abstractmethod()} に @ref{4b3,,property} を渡して使ってください。

@item 
@ref{1298,,abc.abstractclassmethod} は非推奨となりました。代わりに @ref{1297,,abc.abstractmethod()} に @ref{48e,,classmethod} を渡して使ってください。

@item 
@ref{1299,,abc.abstractstaticmethod} は非推奨となりました。代わりに @ref{1297,,abc.abstractmethod()} に @ref{453,,staticmethod} を渡して使ってください。
@end itemize

(Contributed by Darren Dale in bpo-11610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11610}.)

@ref{129a,,abc.ABCMeta.register()} が登録されたサブクラスを返すようになりました。つまりクラスデコレータとして使うことができるようになったということです (bpo-10868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10868})。

@node array<4>,base64<5>,abc<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 array}@anchor{129b}
@subsubsection array


The @ref{8,,array} module supports the long long type using @code{q} and
@code{Q} type codes.

(Contributed by Oren Tirosh and Hirokazu Yamamoto in bpo-1172711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1172711}.)

@node base64<5>,binascii<3>,array<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 base64}@anchor{129c}
@subsubsection base64


@ref{f,,base64} モジュールのモダンなインターフェイスのほうのデコード関数が、ASCII 文字のみで構成された Unicode 文字列を受け付けるようになりました。たとえば @code{base64.b64decode('YWJj')} は @code{b'abc'} を返します。 (Contributed by Catalin Iacob in bpo-13641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13641}.)

@node binascii<3>,bz2<2>,base64<5>,改良されたモジュール<11>
@anchor{whatsnew/3 3 binascii}@anchor{129d}
@subsubsection binascii


@code{a2b_} 関数が、バイナリオブジェクトだけでなく ASCII 文字のみで構成された Unicode 文字列を入力として受け付けるようになりました。 (Contributed by Antoine Pitrou in bpo-13637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13637}.)

@node bz2<2>,codecs<2>,binascii<3>,改良されたモジュール<11>
@anchor{whatsnew/3 3 bz2}@anchor{129e}
@subsubsection bz2


@ref{14,,bz2} モジュールが最初から書き直されました。その過程で新機能がいくつか追加されました。


@itemize *

@item 
新たな @ref{129f,,bz2.open()} 関数: bzip2 で圧縮されたファイルをバイナリかテキストモードで開きます。

@item 
@ref{a66,,bz2.BZ2File} が、コンストラクタの `fileobj' 引数で、任意のファイル様オブジェクトの読み書きが出来るようになりました。

(Contributed by Nadeem Vawda in bpo-5863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5863}.)

@item 
@ref{a66,,bz2.BZ2File} と @ref{12a0,,bz2.decompress()} が (@code{pbzip2} ツールで生成されたような) マルチストリームの入力を展開出来るようになりました。同時に @ref{a66,,bz2.BZ2File} は、 @code{'a'} (追記) モードを使ってこのタイプの圧縮ファイルを作るのに使えるようになりました。

(Contributed by Nir Aides in bpo-1625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1625}.)

@item 
@ref{a66,,bz2.BZ2File} now implements all of the @ref{8a3,,io.BufferedIOBase} API,
except for the @code{detach()} and @code{truncate()} methods.
@end itemize

@node codecs<2>,collections<7>,bz2<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 codecs}@anchor{12a1}
@subsubsection codecs


@ref{57,,mbcs} コーデックが、全ての Windows バージョンでエラーハンドラ @code{replace} と @code{ignore} を正しく処理するように書き換えられました。 @ref{57,,mbcs} コーデックは以前は、エンコードでは @code{replace} のみ、デコードでは @code{ignore} のみでしたが、これにより全てのエラーハンドラがサポートされます。

新たに Windows のみ用のコーデック @code{cp65001} が追加されました (bpo-13216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13216})。これは Windows コードページ 65001 (Windows UTF-8, @code{CP_UTF8}) です。例えばこれはコンソール出力のコードページが (例えば @code{chcp 65001} コマンドを使って)  cp65001 にセットされている場合に @code{sys.stdout} で使われます。

マルチバイト CJK デコーダの再同期が高速になりました。これは不正なバイトシーケンスが最初のバイトであれば無視するだけです。例えば @code{b'\xff\n'.decode('gb2312', 'replace')} は文字置き換えののちに @code{\n} を返すようになっています。

(bpo-12016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12016})

漸増的 CJK コーデックのエンコーダは以前は encode() メソッド呼び出しのたびにリセットしていましたが、リセットしなくなりました。例えば:

@example
>>> import codecs
>>> encoder = codecs.getincrementalencoder('hz')('strict')
>>> b'@w{'}.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
b'~@{NpJ)l6HK!#~@} Bye.'
@end example

この例の場合は以前の Python では @code{b'~@{Np~@}~@{J)~@}~@{l6~@}~@{HK~@}~@{!#~@} Bye.'} となっていました。

(bpo-12100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12100})

@code{unicode_internal} コーデックは非推奨となりました。

@node collections<7>,contextlib<7>,codecs<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 collections}@anchor{12a2}
@subsubsection collections


新たに追加されたクラス @ref{e16,,ChainMap} は、複数のマッピングをひとまとまりに扱えるようにします。 (Written by Raymond Hettinger for bpo-11089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11089}, made public in bpo-11297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11297}.)

抽象基底クラス群は新しいモジュール @ref{1f,,collections.abc} に移動しました。抽象コレクションと具象コレクションを識別しやすくするためです。これをインポートしている既存のコードを維持するために、 ABC の別名群が @ref{1e,,collections} モジュール内に残されています。 (bpo-11085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11085})

@c XXX addition of __slots__ to ABCs not recorded here: internal detail

@ref{12a3,,Counter} クラスが、単項 @code{+} 演算子、単項 @code{-} 演算子、インプレイス演算子の @code{+=}, @code{-=}, @code{|=}, @code{&=} をサポートするようになりました。(Contributed by Raymond Hettinger in bpo-13121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13121}.)

@node contextlib<7>,crypt<2>,collections<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 contextlib}@anchor{12a4}
@subsubsection contextlib


コンテキストマネージャをプログラム的に操作することと、これと類似のクリーンアップの機能性について、@ref{d1e,,ExitStack} が今後は確かな基礎を提供します。かつての (非推奨となり削除された) @code{contextlib.nested} API とは違って、この新しい API は、コンテキストマネージャがリソースを (たとえばファイルオブジェクトなどを) @code{__init__} メソッドで獲得したのか、あるいは (たとえば @ref{f3,,threading} モジュールからの同期オブジェクトを) @code{__enter__} メソッドで獲得したのかとは無関係に正しく動作するように設計されました。

(bpo-13585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13585})

@node crypt<2>,curses<6>,contextlib<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 crypt}@anchor{12a5}
@subsubsection crypt


Addition of salt and modular crypt format (hashing method) and the @code{mksalt()}
function to the @code{crypt} module.

(bpo-10924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10924})

@node curses<6>,datetime<7>,crypt<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 curses}@anchor{12a6}
@subsubsection curses



@itemize *

@item 
If the @ref{2f,,curses} module is linked to the ncursesw library, use Unicode
functions when Unicode strings or characters are passed (e.g.
@code{waddwstr()}), and bytes functions otherwise (e.g. @code{waddstr()}).

@item 
Unicode 文字列をエンコードするのに @code{utf-8} ではなく locale のエンコーディングを使うようになりました。(---訳注:  bpo-12567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12567} に対応した説明と思います。とすればこれは `ワイド文字を受け取らない C 関数に渡す' 際に Unicode をエンコードする際の話。このときに以前は暗黙で @code{utf-8} でエンコードしていたのは「誤りである」ということのようです。 ---)

@item 
@ref{12a7,,curses.window} クラスに属性 @ref{12a8,,curses.window.encoding} が追加されました。

@item 
@ref{12a7,,curses.window} クラスに @ref{12a9,,get_wch()} メソッドが追加されました。これはワイド文字を一つ取得します。

@item 
@ref{2f,,curses} モジュールに関数 @ref{12aa,,unget_wch()} が追加されました。これはワイド文字をプッシュし、次に @ref{12a9,,get_wch()} を呼び出した時にその値が返るようにします。
@end itemize

(Contributed by Iñigo Serna in bpo-6755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6755}.)
(---訳注: 最初の2つはおそらく bpo-12567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12567} --)

@node datetime<7>,decimal<4>,curses<6>,改良されたモジュール<11>
@anchor{whatsnew/3 3 datetime}@anchor{12ab}
@subsubsection datetime



@itemize *

@item 
naive な @ref{4e2,,datetime} インスタンスと aware な @ref{4e2,,datetime} インスタンスの等価比較で、 @ref{198,,TypeError} を投げずに @ref{d2b,,False} を返すようになりました。 (bpo-15006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15006}).

@item 
新規メソッド @ref{12ac,,datetime.datetime.timestamp()}: @ref{4e2,,datetime} インスタンスに対応する POSIX タイムスタンプを返します。

@item 
@ref{e8e,,datetime.datetime.strftime()} メソッドが 1000 年よりも前の書式化をサポートしました。(---訳注: What's New in Python 3.2 での変更も参照してみてください。---)

@item 
@ref{bc4,,datetime.datetime.astimezone()} メソッドを引数なしで呼び出せるようになりました。これは datetime インスタンスをシステムのタイムゾーンに変換します。
@end itemize

@node decimal<4>,email<6>,datetime<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 decimal}@anchor{12ad}@anchor{whatsnew/3 3 new-decimal}@anchor{1241}
@subsubsection decimal



@table @asis

@item bpo-7652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7652} - decimal 算術演算の、高速なネイティブ 実装の統合

C-module and libmpdec written by Stefan Krah.
@end table

The new C version of the decimal module integrates the high speed libmpdec
library for arbitrary precision correctly rounded decimal floating-point
arithmetic. libmpdec conforms to IBM's General Decimal Arithmetic Specification.

Performance gains range from 10x for database applications to 100x for
numerically intensive applications. These numbers are expected gains
for standard precisions used in decimal floating-point arithmetic. Since
the precision is user configurable, the exact figures may vary. For example,
in integer bignum arithmetic the differences can be significantly higher.

The following table is meant as an illustration. Benchmarks are available
at @indicateurl{https://www.bytereef.org/mpdecimal/quickstart.html}.

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} 
@headitem

@tab

decimal.py

@tab

_decimal

@tab

speedup

@item

pi

@tab

42.02s

@tab

0.345s

@tab

120x

@item

telco

@tab

172.19s

@tab

5.68s

@tab

30x

@item

psycopg

@tab

3.57s

@tab

0.29s

@tab

12x

@end multitable

@end quotation

@menu
* フィーチャー: フィーチャー<2>. 
* API の変更: API の変更<2>. 

@end menu

@node フィーチャー<2>,API の変更<2>,,decimal<4>
@anchor{whatsnew/3 3 id1}@anchor{12ae}
@subsubsection フィーチャー



@itemize *

@item 
@ref{12af,,FloatOperation} @ref{12b0,,シグナル} により、float と Decimal の混合の厳密なセマンティクスを有効に出来ます。(---訳注: 使用例が @ref{12b1,,Quick-start tutorial} にあります。---)

@item 
If Python is compiled without threads, the C version automatically
disables the expensive thread local context machinery. In this case,
the variable @ref{12b2,,HAVE_THREADS} is set to @code{False}.
@end itemize

@node API の変更<2>,,フィーチャー<2>,decimal<4>
@anchor{whatsnew/3 3 id2}@anchor{12b3}
@subsubsection API の変更



@itemize *

@item 
C モジュールはマシンアーキテクチャに依存する以下のコンテキストの制限を持ちます:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@tab

32-bit

@tab

64-bit

@item

@ref{12b4,,MAX_PREC}

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@ref{12b5,,MAX_EMAX}

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@ref{12b6,,MIN_EMIN}

@tab

@code{-425000000}

@tab

@code{-999999999999999999}

@end multitable

@end quotation

@item 
In the context templates (@ref{12b7,,DefaultContext},
@ref{12b8,,BasicContext} and @ref{12b9,,ExtendedContext})
the magnitude of @ref{12ba,,Emax} and
@ref{12bb,,Emin} has changed to @code{999999}.

@item 
decimal.py の @ref{1fe,,Decimal} コンストラクタは上記のコンテキスト制限に無知で、任意の指数や精度で正確に変換しようとします。C 版は内部の制限を持っていますので、次の規則が使われます: 可能ならば値は正確に変換され、そうでない場合 @ref{12bc,,InvalidOperation} が送出されて結果が NaN となります。後者のケースは丸めあるいは不正確な値を得るために @ref{12bd,,create_decimal()} を使うことでいつでも可能です。(---訳注: わかりにくい表現ですがコンテキストで InvalidOperation をトラップしていれば結果が NaN で受け取れて(そうでなければ InvalidOperation が投げられて)、その制御は create_decimal で明示的に行える、ということを言っています。---)

@item 
The power function in decimal.py is always correctly rounded. In the
C version, it is defined in terms of the correctly rounded
@ref{12be,,exp()} and @ref{12bf,,ln()} functions,
but the final result is only "almost always correctly rounded".

@item 
C 版ではシグナルを含む辞書は @ref{12c0,,MutableMapping} です。速度的な理由により @ref{12c1,,flags} と @ref{12c2,,traps} はコンテキストが初期化された時点での @ref{12c0,,MutableMapping} を参照し続けます。新たなシグナル辞書を @ref{12c1,,flags} に @ref{12c2,,traps} 割り当てれば新しい値で更新はされるものの、コンテキストはそれら右辺の辞書を参照しません。

@item 
@ref{12c3,,Context} を pickle 化するとこれまでとは異なる出力をします。これは Python 版と C 版で共通の交換フォーマットを実現するためです。

@item 
@ref{12c3,,Context} コンストタクタの引数順が @ref{1c1,,repr()} での表示順に合うように改められました。

@item 
@ref{12c4,,quantize()} メソッドの @code{watchexp} パラメータが非推奨となりました。
@end itemize

@node email<6>,ftplib<3>,decimal<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 email}@anchor{12c5}@anchor{whatsnew/3 3 new-email}@anchor{1242}
@subsubsection email


@menu
* ポリシーフレームワーク:: 
* 新規ヘッダ API を伴った暫定ポリシー:: 
* その他のAPIの変更:: 

@end menu

@node ポリシーフレームワーク,新規ヘッダ API を伴った暫定ポリシー,,email<6>
@anchor{whatsnew/3 3 policy-framework}@anchor{12c6}
@subsubsection ポリシーフレームワーク


email パッケージに @ref{53,,policy} フレームワークが追加されました。 @ref{12c7,,Policy} は、 email パッケージがどのように振舞うのかを制御するための多数のメソッドとプロパティを持つオブジェクトです。Python 3.3 のための最初のポリシーは @ref{12c8,,Compat32} で、これは Python 3.2 の email パッケージとの後方互換性を提供します。 @code{policy} は、 @ref{52,,parser} によって email メッセージが解析される際、あるいは @ref{581,,Message} オブジェクトを生成する際、あるいは @ref{44,,generator} を用いて email がシリアライズする際に指定出来ます。オーバライドしない限りは、 @code{parser} に渡されたポリシーは全ての @code{Message} オブジェクトと @code{parser} が生成したサブオブジェクトに引き継がれます。デフォルトでは @code{generator} は、シリアライズしようとする @code{Message} オブジェクトのポリシーを使います。デフォルトのポリシーは @ref{e97,,compat32} です。

すべての @code{policy} オブジェクトで実装される制御の最小限のセットは以下です:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

max_line_length

@tab

@code{Message} がシリアライズされる際に各行が持ちうる、linesep 文字(列)を含まない最大の行幅です。デフォルトでは 78 です。

@item

linesep

@tab

@code{Message} がシリアライズされる際に各行を分割するのに使われる文字です。デフォルトは @code{\n} です。

@item

cte_type

@tab

@code{7bit} または @code{8bit} 。 @code{8bit} は @code{Bytes} @code{generator} に対してのみ適用され、プロトコルが許す場所 (あるいはオリジナルの入力に含まれる場所) には非 ASCII が使われうることを示します。

@item

raise_on_defect

@tab

@code{parser} が異常を検出した場合に、 @code{Message} オブジェクトの @code{defects} リストに追加するのではなく例外を送出するようにします。

@end multitable


新たな設定値を持つ新しいポリシーインスタンスは、ポリシーオブジェクトの @ref{12c9,,clone()} メソッドを使って作られます。 @code{clone} は任意の上記制御値をキーワード引数として受け取ります。この呼び出しで指定されない制御はデフォルトのまま残されます。ですので linesep 文字列として @code{\r\n} を使うポリシーをこのようにして作れます:

@example
mypolicy = compat32.clone(linesep='\r\n')
@end example

ポリシーは、あなたのアプリケーションが必要とするフォーマットでメッセージを生成するのを簡単にしてくれます。 @code{generator} を呼び出す全ての場所で @code{linesep='\r\n'} を指定するのを忘れないようにする代わりに、あなたのプログラムが @code{Message} オブジェクトを作成するために使う @code{parser} あるいは @code{Message} がポリシーを要求する一箇所だけで指定すれば良いのです。もちろん一方ではメッセージを複数の形式で生成する必要があれば、 @code{generator} 呼び出しのたびにパラメータで指定する必要があります。もしくは、あなた固有のケースのためにカスタムなポリシーを作って、 @code{generator} 作成の際にそれを渡すことも出来ます。

@node 新規ヘッダ API を伴った暫定ポリシー,その他のAPIの変更,ポリシーフレームワーク,email<6>
@anchor{whatsnew/3 3 provisional-policy-with-new-header-api}@anchor{12ca}
@subsubsection 新規ヘッダ API を伴った暫定ポリシー


ポリシーフレームワーク単品でもまったくもって価値があるものではありますが、その導入の主たる動機は、それを使わないコードに対しての後方互換を壊さないやり方で、email パッケージに新機能を実現する新しいポリシーを作れるようにすることでした。その新しいポリシーは新規 API を導入するものなので、私たちはそれらを Python 3.3 での @ref{1243,,暫定ポリシー} としてリリースしました。コア開発者が必要と判断すれば、後方互換性を破壊する (コードの破棄さえも含む) 変更が起こりえます。

その新規ポリシーは @ref{12cb,,EmailPolicy} のインスタンス (訳注: @ref{12cc,,email.policy.default} や @ref{12cd,,email.policy.SMTP} など) です。これには以下の制御が追加されています:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

refold_source

@tab

@ref{52,,parser} により解析されたヘッダを、 @ref{44,,generator} が折り返しし直す (refold) かどうかを制御します。 @code{none}, @code{long}, @code{all} のいずれかを指定します。デフォルトは @code{long} で、ソースのヘッダで @code{max_line_length} よりも長い行を refold します。 @code{none} はどの行も refold しません。 @code{all} は全ての行を refold します。

@item

header_factory

@tab

@code{name} と @code{value} を引数に取り、カスタムなヘッダオブジェクトを生成する呼び出し可能 (callable) です。

@end multitable


@code{header_factory} が、この新規ポリシーにより提供される新機能の要です。この新規ポリシーの一つが使われると、 @code{Message} オブジェクトから抽出されたすべてのヘッダは @code{header_factory} で生成されるオブジェクトであり、また、 @code{Message} にヘッダをセットする場合のいつでも、それは @code{header_factory} で生成されるオブジェクトになります。すべてのその種のヘッダオブジェクトは、ヘッダ名と同名の @code{name} 属性を持ちます。アドレスヘッダと日付ヘッダは、ヘッダの解析済み日付にアクセス出来るよう、追加の属性群を持ちます。以下のように使えます:

@example
>>> m = Message(policy=SMTP)
>>> m['To'] = 'Éric <foo@@example.com>'
>>> m['to']
'Éric <foo@@example.com>'
>>> m['to'].addresses
(Address(display_name='Éric', username='foo', domain='example.com'),)
>>> m['to'].addresses[0].username
'foo'
>>> m['to'].addresses[0].display_name
'Éric'
>>> m['Date'] = email.utils.localtime()
>>> m['Date'].datetime
datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))
>>> m['Date']
'Fri, 25 May 2012 21:44:27 -0400'
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400
@end example

Unicode の display name が、メッセージがシリアライズされる際に自動的に @code{utf-8} (訳注: 実行例の場合は「の MIME ヘッダエンコード」) でエンコードされ、ヘッダに直接アクセスすると Unicode で返ることに気付くと思います。つまり @ref{45,,email.header} の @ref{12ce,,decode_header()} 関数や @ref{12cf,,make_header()} 関数を取り扱う必要性を取り除いてくれています。

アドレスを部品から組み立てることも出来ます:

@example
>>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),
...                           Address('Sally', 'sally', 'example.com')]),
...            Address('Bonzo', addr_spec='bonz@@laugh.com')]
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400
cc: pals: Bob <bob@@example.com>, Sally <sally@@example.com>;, Bonzo <bonz@@laugh.com>
@end example

Unicode へデコードするのは自動で行われます:

@example
>>> m2 = message_from_string(str(m))
>>> m2['to']
'Éric <foo@@example.com>'
@end example

メッセージ解析の際、グループと個々のアドレスにアクセスするのにヘッダオブジェクトの @code{addresses} 属性と @code{groups} 属性を使えます:

@example
>>> m2['cc'].addresses
(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com'), Address(display_name='Bonzo', username='bonz', domain='laugh.com'))
>>> m2['cc'].groups
(Group(display_name='pals', addresses=(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com')), Group(display_name=None, addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh.com'),))
@end example

要するに新規ポリシーのどれか一つを使うことは、ヘッダ操作をこのようなものにしてくれるということです: あなたのアプリケーションは Unicode 文字列でお仕事をし、email パッケージは Unicode のエンコード/デコードを透過的に行って RFC 標準 Content Transfer Encoding との相互変換をやってのける、と。

@node その他のAPIの変更,,新規ヘッダ API を伴った暫定ポリシー,email<6>
@anchor{whatsnew/3 3 other-api-changes}@anchor{12d0}
@subsubsection その他のAPIの変更


@ref{12d1,,BytesHeaderParser} が @ref{52,,parser} モジュールに追加されました。これは @ref{12d2,,HeaderParser} を補足するものであり、また、 bytes API を完全にする (訳注: What's New in Python 3.2 での email の変更内容参照) ものです。

新しいユーティリティ関数:


@itemize *

@item 
@ref{12d3,,format_datetime()}: @ref{4e2,,datetime} を与えると email ヘッダで使われる書式でフォーマットした文字列を生成します。

@item 
@ref{12d4,,parsedate_to_datetime()}: email ヘッダからの日付文字列を渡すと、 aware な、または naive な @ref{4e2,,datetime} に変換します。オフセットが @code{-0000} の場合に naive で返します。

@item 
@ref{2f7,,localtime()}: 引数なしで呼び出すと、ローカル @ref{12d5,,timezone} を使った aware な @ref{4e2,,datetime} として現在ローカル時間を返します。aware な @ref{4e2,,datetime} を渡して呼び出すと、ローカル @ref{12d5,,timezone} を使った aware な @ref{4e2,,datetime} に変換します。
@end itemize

@node ftplib<3>,functools<7>,email<6>,改良されたモジュール<11>
@anchor{whatsnew/3 3 ftplib}@anchor{12d6}
@subsubsection ftplib



@itemize *

@item 
@ref{af6,,ftplib.FTP} に新しいキーワード引数 @code{source_address} が追加されました。 @code{(host, port)} の形で指定し、これは外に向かうソケットを作成する際に @ref{12d7,,bind()} 呼び出し内でのソースアドレスとして用いられます。 (Contributed by Giampaolo Rodolà in bpo-8594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8594}.)

@item 
@ref{af7,,FTP_TLS} クラスに、制御チャネルを平文に戻すための @ref{12d8,,ccc()} 関数が追加されました。これは、固定ポートで開くことなく非セキュア FTP で NAT を処理する方法を知っているファイアウォールを利用するのに有用となりえます。(Contributed by Giampaolo Rodolà in bpo-12139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12139}.)

@item 
新規メソッド @ref{12d9,,ftplib.FTP.mlsd()} は機械で読めるディレクトリリスティングのフォーマットを提供し、 @ref{12da,,ftplib.FTP.nlst()} と @ref{12db,,ftplib.FTP.dir()} に取って代わるものとなりました。(Contributed by Giampaolo Rodolà in bpo-11072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11072}.)
@end itemize

@node functools<7>,gc<7>,ftplib<3>,改良されたモジュール<11>
@anchor{whatsnew/3 3 functools}@anchor{12dc}
@subsubsection functools


@ref{be2,,functools.lru_cache()} デコレータにキーワード引数 @code{typed} を指定出来るようになりました (デフォルトは @code{False} です)。これは異なった型の等値比較のキャッシュ値を別々のキャッシュスロットに置くかどうかを決めます。(Contributed by Raymond Hettinger in bpo-13227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13227}.)

@node gc<7>,hmac<5>,functools<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 gc}@anchor{12dd}
@subsubsection gc


ガーベージコレクタが回収前後に呼び出すコールバックを登録出来るようになりました。新規属性 @ref{12de,,callbacks} リストに登録します。

@node hmac<5>,http<5>,gc<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 hmac}@anchor{12df}
@subsubsection hmac


タイミング解析によるダイジェストに対する サイドチャンネル攻撃@footnote{https://en.wikipedia.org/wiki/Side-channel_attack} からの防御のために、 @ref{12e0,,compare_digest()} 関数が追加されました。(Contributed by Nick Coghlan and Christian Heimes in bpo-15061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15061}.)

@node http<5>,html<2>,hmac<5>,改良されたモジュール<11>
@anchor{whatsnew/3 3 http}@anchor{12e1}
@subsubsection http


@ref{12e2,,http.server.BaseHTTPRequestHandler} がヘッダをバッファするようになり、 @ref{12e3,,end_headers()} 呼び出し時に一度に全てをまとめて書き出すようになりました。新規のメソッド @ref{12e4,,flush_headers()} は、集積したヘッダを送信する場合の管理に直接使うことが出来ます。(Contributed by Andrew Schaaf in bpo-3709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3709}.)

@ref{76,,http.server} が正当な @code{HTML 4.01 strict} 出力を生成するようになりました。 (Contributed by Ezio Melotti in bpo-13295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13295}.)

@ref{12e5,,http.client.HTTPResponse} にメソッド @ref{12e6,,readinto()} が追加されました。つまりこのクラスを @ref{12e7,,io.RawIOBase} のように扱えるということです。 (Contributed by John Kuhn in bpo-13464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13464}.)

@node html<2>,imaplib<4>,http<5>,改良されたモジュール<11>
@anchor{whatsnew/3 3 html}@anchor{12e8}
@subsubsection html


@ref{a77,,html.parser.HTMLParser} is now able to parse broken markup without
raising errors, therefore the `strict' argument of the constructor and the
@code{HTMLParseError} exception are now deprecated.
The ability to parse broken markup is the result of a number of bug fixes that
are also available on the latest bug fix releases of Python 2.7/3.2.
(Contributed by Ezio Melotti in bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}, and bpo-14538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14538},
bpo-13993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13993}, bpo-13960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13960}, bpo-13358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13358}, bpo-1745761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1745761},
bpo-755670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=755670}, bpo-13357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13357}, bpo-12629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12629}, bpo-1200313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1200313},
bpo-670664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=670664}, bpo-13273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13273}, bpo-12888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12888}, bpo-7311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7311}.)

@ref{70,,html.entities} モジュールに、HTML5 名前付き文字参照と Unicode 文字(列) とを対応付ける @ref{12e9,,html5} 辞書が追加されました (例: @code{html5['gt;'] == '>'})。この辞書は既に @ref{a77,,HTMLParser} が使っています。 (Contributed by Ezio Melotti in bpo-11113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11113} and bpo-15156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15156}.)

@node imaplib<4>,inspect<10>,html<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 imaplib}@anchor{12ea}
@subsubsection imaplib


@ref{b00,,IMAP4_SSL} コンストラクタが SSLContext パラメータを受け取るようになりました。これはセキュアなチャネルのパラメータを制御します。

(Contributed by Sijin Joseph in bpo-8808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8808}.)

@node inspect<10>,io<8>,imaplib<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 inspect}@anchor{12eb}
@subsubsection inspect


@ref{12ec,,getclosurevars()} 関数が追加されました。この関数は、指定した関数の関数本体から参照されている現在束縛されている全ての名前と、それら名前が解決された場所 (訳注: globals, builtins など) を報告します。これにより、ステートフルなクロージャに依存するコードをテストするのに、正しい内部状態を検証するのが容易になります。

(Contributed by Meador Inge and Nick Coghlan in bpo-13062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13062}.)

@ref{12ed,,getgeneratorlocals()} 関数が追加されました。この関数は、指定したジェネレータのスタックフレーム内のローカル変数の、現在束縛されているものを報告します。これにより、ジェネレータをテストするのに、正しい内部状態を検証するのが容易になります。

(Contributed by Meador Inge in bpo-15153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15153}.)

@node io<8>,itertools<7>,inspect<10>,改良されたモジュール<11>
@anchor{whatsnew/3 3 io}@anchor{12ee}
@subsubsection io


@ref{740,,open()} 関数に排他的作成に使用する新たな @code{'x'} モードが追加されました。ファイルが既に存在する場合は @ref{1221,,FileExistsError} を送出します。
C11 fopen() の 'x' モードに基づいています。

(Contributed by David Townshend in bpo-12760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12760}.)

The constructor of the @ref{9be,,TextIOWrapper} class has a new
`write_through' optional argument. If `write_through' is @code{True}, calls to
@code{write()} are guaranteed not to be buffered: any data
written on the @ref{9be,,TextIOWrapper} object is immediately handled to its
underlying binary buffer.

@node itertools<7>,logging<7>,io<8>,改良されたモジュール<11>
@anchor{whatsnew/3 3 itertools}@anchor{12ef}
@subsubsection itertools


@ref{bf0,,accumulate()} がユーザ提供二項関数を渡すためのオプショナル引数 @code{func} を受け付けるようになりました。

@node logging<7>,math<10>,itertools<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 logging}@anchor{12f0}
@subsubsection logging


@ref{bf3,,basicConfig()} 関数がオプショナルな @code{handlers} 引数をサポートするようになりました。これはルートロガーに追加するハンドラ群の @ref{12f1,,イテラブル} です。

A class level attribute @code{append_nul} has
been added to @ref{86c,,SysLogHandler} to allow control of the
appending of the @code{NUL} (@code{\000}) byte to syslog records, since for some
daemons it is required while for others it is passed through to the log.

@node math<10>,mmap<4>,logging<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 math}@anchor{12f2}
@subsubsection math


@ref{92,,math} モジュールに新たな関数 @ref{12f3,,log2()} が追加されました。`x' の 2 を底とする対数を返します。

(Written by Mark Dickinson in bpo-11888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11888}.)

@node mmap<4>,multiprocessing<9>,math<10>,改良されたモジュール<11>
@anchor{whatsnew/3 3 mmap}@anchor{12f4}
@subsubsection mmap


@ref{12f5,,read()} メソッドの他のファイルライクなオブジェクトとの互換性が増しました。引数が省略されるか @code{None} の場合に、ファイルの現在位置からマッピングの末尾までのバイト列を返すようになっています。(Contributed by Petri Lehtinen in bpo-12021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12021}.)

@node multiprocessing<9>,nntplib<2>,mmap<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 multiprocessing}@anchor{12f6}
@subsubsection multiprocessing


関数 @ref{12f7,,multiprocessing.connection.wait()} が追加されました。これは複数の (接続やソケット、パイプのような) オブジェクトをタイムアウト付きでポーリングします。(Contributed by Richard Oudkerk in bpo-12328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12328}.)

@ref{12f8,,multiprocessing.connection.Connection} objects can now be transferred
over multiprocessing connections.
(Contributed by Richard Oudkerk in bpo-4892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4892}.)

@ref{252,,multiprocessing.Process} がキーワード引数 @code{daemon} を取るようになりました。これは親プロセスから @code{daemon} フラグを継承するデフォルトの振る舞いをオーバライドします (bpo-6064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6064})。

属性 @ref{12f9,,multiprocessing.Process.sentinel} が追加されました。これを用いることで、ふさわしい OS プリミティブ (例えば POSIX システムでの @ref{c6,,select}) を使った一括での複数 @ref{252,,Process} オブジェクト待ちが可能です。

@ref{19f,,map()} と @ref{12fa,,itertools.starmap()} との関係と同じ、既存の @ref{12fb,,multiprocessing.pool.Pool.map()} と @ref{12fc,,map_async()} に対応する @ref{12fd,,multiprocessing.pool.Pool.starmap()} と @ref{12fe,,starmap_async()} が追加されました。 (Contributed by Hynek Schlawack in bpo-12708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12708}.)

@node nntplib<2>,os<13>,multiprocessing<9>,改良されたモジュール<11>
@anchor{whatsnew/3 3 nntplib}@anchor{12ff}
@subsubsection nntplib


The @code{nntplib.NNTP} class now supports the context management protocol to
unconditionally consume @ref{1261,,socket.error} exceptions and to close the NNTP
connection when done:

@example
>>> from nntplib import NNTP
>>> with NNTP('news.gmane.org') as n:
...     n.group('gmane.comp.python.committers')
...
('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
>>>
@end example

(Contributed by Giampaolo Rodolà in bpo-9795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9795}.)

@node os<13>,pdb<9>,nntplib<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 os}@anchor{1300}
@subsubsection os



@itemize *

@item 
The @ref{a5,,os} module has a new @ref{1301,,pipe2()} function that makes it
possible to create a pipe with @ref{1288,,O_CLOEXEC} or
@ref{103b,,O_NONBLOCK} flags set atomically. This is especially useful to
avoid race conditions in multi-threaded programs.

@item 
@ref{a5,,os} モジュールに @ref{d05,,sendfile()} 関数が追加されました。これはあるファイル (またはソケット) 記述子からのコピーを、効率的な「ゼロコピー」で行います。「ゼロコピー」という言い回しは、これは二つの記述子間でのデータのコピー全てが完全にカーネルによって行われる、という事実について指しています。データコピーにユーザ空間のバッファは使われません。 @ref{d05,,sendfile()} は例えばファイルのダウンロードのような、ディスク上のファイルとネットワークソケット間での効率的なデータコピーに使うことが出来ます。

(Patch submitted by Ross Lagerwall and Giampaolo Rodolà in bpo-10882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10882}.)

@item 
シンボリックリンク攻撃や一時ファイル、一時ディレクトリにまつわる問題のような競合状態を避けるには、ファイル名の代わりにファイル記述子を操作することがより信頼出来ます (そして高速でもあります)。 Python 3.3 はファイル記述子で動作するよう既存関数の強化と新規関数の追加を行ないました。 (bpo-4761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4761}, bpo-10755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10755} and bpo-14626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14626})


@itemize -

@item 
@ref{a5,,os} モジュールの新規関数 @ref{d52,,fwalk()} は @ref{6d0,,walk()} と似ていますが、これは訪問するディレクトリを指すファイル記述子も yield します。これは特にシンボリックリンクの競合を避けるために有用です。

@item 
The following functions get new optional `dir_fd' (@ref{1302,,paths relative to directory descriptors}) and/or `follow_symlinks' (@ref{1303,,not following symlinks}):
@ref{1304,,access()}, @ref{1305,,chflags()}, @ref{529,,chmod()}, @ref{1306,,chown()},
@ref{1307,,link()}, @ref{6c8,,lstat()}, @ref{52b,,mkdir()}, @ref{f90,,mkfifo()},
@ref{f91,,mknod()}, @ref{f92,,open()}, @ref{b1a,,readlink()}, @ref{1308,,remove()},
@ref{1309,,rename()}, @ref{130a,,replace()}, @ref{130b,,rmdir()}, @ref{26d,,stat()},
@ref{130c,,symlink()}, @ref{130d,,unlink()}, @ref{130e,,utime()}.  Platform
support for using these parameters can be checked via the sets
@ref{130f,,os.supports_dir_fd} and @ref{1310,,os.supports_follow_symlinks}.

@item 
関数 @ref{821,,chdir()}, @ref{529,,chmod()}, @ref{1306,,chown()}, @ref{1311,,execve()}, @ref{1312,,listdir()}, @ref{1313,,pathconf()}, @ref{c03,,exists()}, @ref{26d,,stat()}, @ref{1314,,statvfs()}, @ref{130e,,utime()} が、パス引数としてファイル記述子をサポートするようになりました。これをプラットフォームがサポートするかどうかは @ref{1315,,os.supports_fd} を調べることでわかります。
@end itemize

@item 
@ref{1304,,access()} がキーワード引数 @code{effective_ids} を受け取るようになりました。これは実 uid/gid の代わりに実効 uid/gid を使ってアクセスチェックを行うように振る舞いを変更します。これをプラットフォームがサポートするかどうかは @ref{1316,,supports_effective_ids} を調べることでわかります。

@item 
@ref{a5,,os} モジュールに 2 つの関数が追加されました。 @ref{1317,,getpriority()} と @ref{1318,,setpriority()} です。これらはプロセスのナイス値/優先度 (niceness/priority) を @ref{1319,,os.nice()} と似た方法で取得・設定しますが、現在プロセスだけのものだけではなく全てのプロセスに対して使えるよう拡張されています。

(Patch submitted by Giampaolo Rodolà in bpo-10784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10784}.)

@item 
新規関数 @ref{130a,,os.replace()} は変更先の上書きにおいてクロスプラットフォームな方法でファイル名変更を行えます。既存の @ref{1309,,os.rename()} では、変更先が既存のファイルの場合に POSIX では上書き、Windows ではエラーとなります。(Contributed by Antoine Pitrou in bpo-8828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8828}.)

@item 
stat 系関数 (@ref{26d,,stat()}, @ref{f8c,,fstat()}, @ref{6c8,,lstat()}) がファイルのタイムスタンプのナノ秒精度を読み取れるようになりました。これと対となる @ref{130e,,utime()} もファイルのタイムスタンプをナノ秒精度で書き出せるようになりました。 (Contributed by Larry Hastings in bpo-14127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14127}.)

@item 
新規関数 @ref{131a,,os.get_terminal_size()} はファイル記述子が接続しているターミナルウィンドウのサイズを取得します。 @ref{131b,,shutil.get_terminal_size()} も参照して下さい。 (Contributed by Zbigniew Jędrzejewski-Szmek in bpo-13609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13609}.)
@end itemize

@c XXX sort out this mess after beta1


@itemize *

@item 
Linux 拡張属性をサポートするための新たな関数 (bpo-12720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12720}): @ref{131c,,getxattr()}, @ref{131d,,listxattr()}, @ref{131e,,removexattr()}, @ref{131f,,setxattr()}.

@item 
スケジューラに対する新たなインターフェイス。これら関数はプロセスに対する OS による CPU 時間割り当てを制御します。新規関数: @ref{1320,,sched_get_priority_max()}, @ref{1321,,sched_get_priority_min()}, @ref{1322,,sched_getaffinity()}, @ref{1323,,sched_getparam()}, @ref{1324,,sched_getscheduler()}, @ref{1325,,sched_rr_get_interval()}, @ref{1326,,sched_setaffinity()}, @ref{1327,,sched_setparam()}, @ref{1328,,sched_setscheduler()}, @ref{1329,,sched_yield()},

@item 
ファイルシステムを制御する新たな関数:


@itemize *

@item 
@ref{f93,,posix_fadvise()}: データへアクセスする意思を、パターンを指定して宣言します。これによりカーネルが最適化を行えるようになります。

@item 
@ref{f94,,posix_fallocate()}: ファイルを割り当てるに十分なディスクスペースを確保します。

@item 
@ref{132a,,sync()}: ディスクへの全ての書き込みを強制します。
@end itemize

@item 
追加された新たな POSIX 関数:


@itemize *

@item 
@ref{132b,,lockf()}: オープンされたファイル記述子に対して、POSIX ロックの適用、テスト、解除を行います。

@item 
@ref{d56,,pread()}: ファイル記述子の指定オフセット位置から読み込みます。ファイルオフセットは変化しません。

@item 
@ref{d59,,pwrite()}: ファイル記述子に対し、指定オフセット位置から書き出します。ファイルオフセットは変化しません。

@item 
@ref{d55,,readv()}: ファイル記述子からデータを読みこんで複数の書き込み可能なバッファに書き込みます。

@item 
@ref{103c,,truncate()}: `path' に対応するファイルを、サイズが最大で `length' バイトになるよう切り詰めます。

@item 
@ref{f99,,waitid()}: 一つ以上の子プロセスの完了を待ちます。

@item 
@ref{d58,,writev()}: `buffers' の内容をファイル記述子へ書き出します。 `buffer' は任意のバッファのシーケンスです。

@item 
@ref{132c,,getgrouplist()} (bpo-9344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9344}): 指定したユーザが属するグループ ID のリストを返します。
@end itemize

@item 
@ref{132d,,times()} および @ref{132e,,uname()}: 戻り値の型がタプルから属性名のついたタプルライクオブジェクトに変更されました。

@item 
いくつかのプラットフォームにおいて、 @ref{132f,,lseek()} 関数で使う追加の定数をサポートするようになりました。 @code{os.SEEK_HOLE} や @code{os.SEEK_DATA} などです。

@item 
New constants @ref{1330,,RTLD_LAZY}, @ref{1331,,RTLD_NOW},
@ref{1332,,RTLD_GLOBAL}, @ref{1333,,RTLD_LOCAL}, @ref{1334,,RTLD_NODELETE},
@ref{1335,,RTLD_NOLOAD}, and @ref{1336,,RTLD_DEEPBIND} are available on
platforms that support them.   These are for use with the
@ref{1337,,sys.setdlopenflags()} function, and supersede the similar constants
defined in @ref{2e,,ctypes} and @code{DLFCN}.  (Contributed by Victor Stinner
in bpo-13226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13226}.)

@item 
クロスプラットフォームのサポートを簡単にするために、非 Windows 環境でも @ref{130c,,os.symlink()} がキーワード引数 @code{target_is_directory} を受け付けるようになりました (単に無視します)。
@end itemize

@node pdb<9>,pickle<6>,os<13>,改良されたモジュール<11>
@anchor{whatsnew/3 3 pdb}@anchor{1338}
@subsubsection pdb


@code{Tab} キーでの補完がコマンド名だけでなくその引数に対しても使えるようになりました。例えば @code{break} コマンドに対しては、関数、ファイル名が補完されます。

(Contributed by Georg Brandl in bpo-14210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14210})

@node pickle<6>,pydoc<6>,pdb<9>,改良されたモジュール<11>
@anchor{whatsnew/3 3 pickle}@anchor{1339}
@subsubsection pickle


@ref{c13,,pickle.Pickler} オブジェクトに pickler ごとのリダクション関数を設定する、オプショナルな @ref{133a,,dispatch_table} 属性が追加されました。

(Contributed by Richard Oudkerk in bpo-14166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14166}.)

@node pydoc<6>,re<10>,pickle<6>,改良されたモジュール<11>
@anchor{whatsnew/3 3 pydoc}@anchor{133b}
@subsubsection pydoc


The Tk GUI and the @code{serve()} function have been removed from the
@ref{ba,,pydoc} module: @code{pydoc -g} and @code{serve()} have been deprecated
in Python 3.2.

@node re<10>,sched,pydoc<6>,改良されたモジュール<11>
@anchor{whatsnew/3 3 re}@anchor{133c}
@subsubsection re


@ref{169,,str} 正規表現が @code{\u} および @code{\U} エスケープをサポートしました。

(Contributed by Serhiy Storchaka in bpo-3665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3665}.)

@node sched,select<2>,re<10>,改良されたモジュール<11>
@anchor{whatsnew/3 3 sched}@anchor{133d}
@subsubsection sched



@itemize *

@item 
@ref{133e,,run()} が `blocking' パラメータを取るようになりました。
これを偽にセットすると、このメソッドは既に実行予定時間になっているイベント (もしあれば) を実行してすぐに戻ります。
これは @ref{133f,,scheduler} を非ブロッキングなアプリケーションで使いたい場合に有用です。
(Contributed by Giampaolo Rodolà in bpo-13449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13449}.)
(---訳注: 原文の表現がわかりにくいですが、これは @code{blocking=False} 時はスケジュールされた時間になっているタスクがあれば通常は `delayfunc' を呼び出すところをそうせずに、一番早く次の予定時間に達するタスクの予定時間までの時間差を返します。---)

@item 
@ref{133f,,scheduler} クラスをマルチスレッド環境で安全に使えるようになりました。 (Contributed by Josiah Carlson and Giampaolo Rodolà in bpo-8684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8684}.)

@item 
@ref{133f,,scheduler} クラスのコンストラクタでのパラメータ `timefunc' と `delayfunc' が省略可能になりました。それぞれデフォルトで順に @ref{55d,,time.time()}, @ref{8ac,,time.sleep()} が使われます。 (Contributed by Chris Clark in bpo-13245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13245}.)

@item 
@ref{1340,,enter()} と @ref{1341,,enterabs()} の `argument' パラメータが省略可能になりました。  (Contributed by Chris Clark in bpo-13245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13245}.)

@item 
@ref{1340,,enter()} と @ref{1341,,enterabs()} が `kwargs' パラメータを受け付けるようになりました。  (Contributed by Chris Clark in bpo-13245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13245}.)
@end itemize

@node select<2>,shlex<3>,sched,改良されたモジュール<11>
@anchor{whatsnew/3 3 select}@anchor{1342}
@subsubsection select


Solaris とその派生プラットフォームにおいて、新規クラス @ref{1198,,select.devpoll} が追加されました。これはハイパフォーマンスな非同期ソケットを @code{/dev/poll} 経由で提供するものです。 (Contributed by Jesús Cea Avión in bpo-6397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6397}.)

@node shlex<3>,shutil<7>,select<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 shlex}@anchor{1343}
@subsubsection shlex


The previously undocumented helper function @code{quote} from the
@code{pipes} modules has been moved to the @ref{c9,,shlex} module and
documented.  @ref{582,,quote()} properly escapes all characters in a string
that might be otherwise given special meaning by the shell.

@node shutil<7>,signal<4>,shlex<3>,改良されたモジュール<11>
@anchor{whatsnew/3 3 shutil}@anchor{1344}
@subsubsection shutil



@itemize *

@item 
新たな関数:


@itemize *

@item 
@ref{1345,,disk_usage()}: ディスクの利用状況について、トータル、使用中、空きの容量を返します。 (Contributed by Giampaolo Rodolà in bpo-12442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12442}.)

@item 
@ref{548,,chown()}: 指定された path のユーザ、グループの両方あるいは一方を変更します。ユーザ、グループは名前もしくは数値での ID (uid, gid) で指定します。(Contributed by Sandro Tosi in bpo-12191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12191}.)

@item 
@ref{131b,,shutil.get_terminal_size()}: インタプリタが接続しているターミナルウィンドウのサイズを取得します。 (Contributed by Zbigniew Jędrzejewski-Szmek in bpo-13609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13609}.)
@end itemize

@item 
@ref{c50,,copy2()} と @ref{1346,,copystat()} がファイルのタイムスタンプを、それをサポートするプラットフォームではナノ秒精度も維持するようになりました。また、Linux ではこれらは「拡張属性 (extended attributes)」もコピーするようになりました。 (Contributed by Larry Hastings in bpo-14127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14127} and bpo-15238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15238}.)

@item 
いくつかの関数がオプショナルな @code{symlinks} 引数を取るようになりました。これが真の場合、シンボリックリンクの指す先を解決するのではなくシンボリックそのものに対しての操作をします (そうすることが必要であればシンボリックリンク作成もします)。(Contributed by Hynek Schlawack in bpo-12715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12715}.)

@item 
ファイルシステムをまたがったファイルのコピーの際に、 @ref{c51,,move()} がシンボリックリンクを POSIX の @code{move} コマンドが行うのと同じやり方で扱うようになりました。つまりターゲットのファイルの中身をコピーするのではなくシンボリックリンクを再作成します。(Contributed by Jonathan Niehof in bpo-9993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9993}.) また、 @ref{c51,,move()} は @code{dst} 引数を戻り値として返すようになりました。

@item 
@ref{f92,,os.open()} と @ref{130d,,os.unlink()} が新パラメータ @code{dir_fd} をサポートしているプラットフォームでは、 @ref{356,,rmtree()} は今では シンボリックリンク攻撃に耐性を持ちます。 (Contributed by Martin von Löwis and Hynek Schlawack in bpo-4489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4489}.)
@end itemize

@node signal<4>,smtpd<4>,shutil<7>,改良されたモジュール<11>
@anchor{whatsnew/3 3 signal}@anchor{1347}
@subsubsection signal



@itemize *

@item 
@ref{cb,,signal} モジュールに新規関数が追加されました:


@itemize *

@item 
@ref{1348,,pthread_sigmask()}: これを呼び出すスレッドにセットされているシグナルマスクを取り出したり変更したりします (Contributed by Jean-Paul Calderone in bpo-8407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8407});

@item 
@ref{1349,,pthread_kill()}: スレッドにシグナルを送ります;

@item 
@ref{134a,,sigpending()}: 保留中のシグナルを調べます;

@item 
@ref{134b,,sigwait()}: シグナルを待ちます;

@item 
@ref{fab,,sigwaitinfo()}: シグナルを待ちますが、それについての詳細情報を返します;

@item 
@ref{faa,,sigtimedwait()}: @ref{fab,,sigwaitinfo()} と似ていますがタイムアウト指定できます。
@end itemize

@item 
シグナルハンドラは wakeup ファイル記述子に以前は @code{\0} を書き込んでいましたが、シグナル番号を 1 バイト整数として書き込むようにしました。これにより、一つ以上のシグナルを待った上でどのシグナルが発生したのかあとから調べるといったことが出来ます。

@item 
@ref{134c,,signal.signal()} と @ref{134d,,signal.siginterrupt()} は RuntimeError ではなく @ref{2c0,,OSError} を投げるようになりました: OSError は errno 属性を持っています。
@end itemize

@node smtpd<4>,smtplib<4>,signal<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 smtpd}@anchor{134e}
@subsubsection smtpd


The @code{smtpd} module now supports 
@geindex RFC; RFC 5321
RFC 5321@footnote{https://datatracker.ietf.org/doc/html/rfc5321.html} (extended SMTP) and 
@geindex RFC; RFC 1870
RFC 1870@footnote{https://datatracker.ietf.org/doc/html/rfc1870.html}
(size extension).  Per the standard, these extensions are enabled if and only
if the client initiates the session with an @code{EHLO} command.

(Initial @code{ELHO} support by Alberto Trevino.  Size extension by Juhana
Jauhiainen.  Substantial additional work on the patch contributed by Michele
Orrù and Dan Boswell.  bpo-8739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8739})

@node smtplib<4>,socket<11>,smtpd<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 smtplib}@anchor{134f}
@subsubsection smtplib


クラス @ref{b27,,SMTP}, @ref{b28,,SMTP_SSL}, @ref{b29,,LMTP} に新しいキーワード引数 @code{source_address} が追加されました。 @code{(host, port)} の形で指定し、これは外に向かうソケットを作成する際に @ref{12d7,,bind()} 呼び出し内でのソースアドレスとして用いられます。(Contributed by Paulo Scardine in bpo-11281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11281}.)

@ref{b27,,SMTP} がコンテキスト管理プロトコルをサポートするようになったので @code{SMTP} のインスタンスを @code{with} 文で使えます。  (Contributed by Giampaolo Rodolà in bpo-11289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11289}.)

@ref{b28,,SMTP_SSL} コンストラクタと @ref{1350,,starttls()} メソッドが SSLContext パラメータを受け取るようになりました。これはセキュアなチャネルのパラメータを制御します。 (Contributed by Kasun Herath in bpo-8809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8809}.)

@node socket<11>,socketserver<3>,smtplib<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 socket}@anchor{1351}
@subsubsection socket



@itemize *

@item 
@ref{fa1,,socket} クラスが、前提となるプラットフォームがサポートしていれば従属的なデータを処理する追加のメソッドを公開しました:


@itemize *

@item 
@ref{6a1,,sendmsg()}

@item 
@ref{fa6,,recvmsg()}

@item 
@ref{1352,,recvmsg_into()}
@end itemize

(Contributed by David Watson in bpo-6560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6560}, based on an earlier patch by
Heiko Wundram)

@item 
@ref{fa1,,socket} クラスが Linux で (@indicateurl{https://lwn.net/Articles/253425}) PF_CAN プロトコルファミリ (@indicateurl{https://en.wikipedia.org/wiki/Socketcan}) をサポートしました。

(Contributed by Matthias Fuchs, updated by Tiago Gonçalves in bpo-10141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10141}.)

@item 
The @ref{fa1,,socket} class now supports the PF_RDS protocol family
(@indicateurl{https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets} and
https://oss.oracle.com/projects/rds@footnote{https://web.archive.org/web/20130115155505/https://oss.oracle.com/projects/rds/}).

@item 
@ref{fa1,,socket} クラスが OS X で @code{PF_SYSTEM} プロトコルファミリをサポートするようになりました。 (Contributed by Michael Goderbauer in bpo-13777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13777}.)

@item 
New function @ref{1353,,sethostname()} allows the hostname to be set
on Unix systems if the calling process has sufficient privileges.
(Contributed by Ross Lagerwall in bpo-10866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10866}.)
@end itemize

@node socketserver<3>,sqlite3<11>,socket<11>,改良されたモジュール<11>
@anchor{whatsnew/3 3 socketserver}@anchor{1354}
@subsubsection socketserver


@ref{1355,,BaseServer} がオーバライド可能な @ref{1356,,service_actions()} メソッドを持つようになり、これは @ref{1357,,serve_forever()} によりサービスループ内で呼び出されます。 @ref{d71,,ForkingMixIn} がこれをゾンビ化した子プロセスのクリーンアップに使っています。 (Contributed by Justin Warkentin in bpo-11109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11109}.)

@node sqlite3<11>,ssl<12>,socketserver<3>,改良されたモジュール<11>
@anchor{whatsnew/3 3 sqlite3}@anchor{1358}
@subsubsection sqlite3


@ref{54d,,sqlite3.Connection} の新規のメソッド @ref{5ab,,set_trace_callback()} を使うと sqlite3 により処理されるすべての sql コマンドの足跡 (トレース) をキャプチャ出来ます。(Contributed by Torsten Landschoff in bpo-11688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11688}.)

@node ssl<12>,stat<2>,sqlite3<11>,改良されたモジュール<11>
@anchor{whatsnew/3 3 ssl}@anchor{1359}
@subsubsection ssl



@itemize *

@item 
@ref{d5,,ssl} モジュールに新たに 2 つの乱数生成関数が追加されました:


@itemize *

@item 
@ref{747,,RAND_bytes()}: 暗号学的に強固な擬似乱数バイト列を生成します。

@item 
@code{RAND_pseudo_bytes()}: generate pseudo-random bytes.
@end itemize

(Contributed by Victor Stinner in bpo-12049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12049}.)

@item 
@ref{d5,,ssl} モジュールがより粒度の細かい例外階層を公開するようになり、これにより様々な種類のエラーを調べることが容易になります。 (Contributed by Antoine Pitrou in bpo-11183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11183}.)

@item 
@ref{598,,load_cert_chain()} が `password' 引数を受け付けるようになりました。これは秘密鍵が暗号化されている場合に使われます。 (Contributed by Adam Simpkins in bpo-12803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12803}.)

@item 
ディフィー・ヘルマン鍵共有の、通常のものと楕円曲線ベースのもの両方が @ref{135a,,load_dh_params()} メソッドと @ref{135b,,set_ecdh_curve()} メソッドを通じてサポートされるようになりました。(Contributed by Antoine Pitrou in bpo-13626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13626} and bpo-13627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13627}.)

@item 
SSL ソケットに新規メソッド @ref{135c,,get_channel_binding()} が追加されました。これは SCRAM-SHA-1-PLUS (訳注: 
@geindex RFC; RFC 5802
RFC 5802@footnote{https://datatracker.ietf.org/doc/html/rfc5802.html} など参照) のようなある種の認証メカニズムの実装で拡張されることを想定したものです。(Contributed by Jacek Konieczny in bpo-12551@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12551}.)

@item 
You can query the SSL compression algorithm used by an SSL socket, thanks
to its new @ref{135d,,compression()} method.  The new attribute
@ref{135e,,OP_NO_COMPRESSION} can be used to disable compression.
(Contributed by Antoine Pitrou in bpo-13634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13634}.)

@item 
@ref{358,,ssl.SSLContext.set_npn_protocols()} による Next Protocol Negotiation 拡張のサポートが追加されました。
(Contributed by Colin Marc in bpo-14204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14204}.)

@item 
属性 @ref{135f,,library} と @ref{1360,,reason} が追加されたので、SSL のエラーは以前よりもっと簡単に調べることが出来るようになりました。(Contributed by Antoine Pitrou in bpo-14837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14837}.)

@item 
@ref{a3d,,get_server_certificate()} 関数が IPv6 をサポートするようになりました。 (Contributed by Charles-François Natali in bpo-11811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11811}.)

@item 
New attribute @ref{1361,,OP_CIPHER_SERVER_PREFERENCE} allows setting
SSLv3 server sockets to use the server's cipher ordering preference rather
than the client's (bpo-13635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13635}).
@end itemize

@node stat<2>,struct<4>,ssl<12>,改良されたモジュール<11>
@anchor{whatsnew/3 3 stat}@anchor{1362}
@subsubsection stat


ドキュメントされていなかった @code{tarfile.filemode} 関数が @ref{1363,,stat.filemode()} に移動されました。これはファイルモードを '-rwxrwxrwx' 形式の文字列に変換するのに使えます。

(Contributed by Giampaolo Rodolà in bpo-14807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14807}.)

@node struct<4>,subprocess<6>,stat<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 struct}@anchor{1364}
@subsubsection struct


The @ref{db,,struct} module now supports @code{ssize_t} and @code{size_t} via the
new codes @code{n} and @code{N}, respectively.  (Contributed by Antoine Pitrou
in bpo-3163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3163}.)

@node subprocess<6>,sys<13>,struct<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 subprocess}@anchor{1365}
@subsubsection subprocess


POSIX プラットフォームにおいて、コマンド文字列として bytes オブジェクトを渡せるようになりました。 (Contributed by Victor Stinner in bpo-8513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8513}.)

A new constant @ref{1366,,DEVNULL} allows suppressing output in a
platform-independent fashion.  (Contributed by Ross Lagerwall in
bpo-5870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5870}.)

@node sys<13>,tarfile<9>,subprocess<6>,改良されたモジュール<11>
@anchor{whatsnew/3 3 sys}@anchor{1367}
@subsubsection sys


@ref{df,,sys} モジュールに、スレッドの実装に関する情報が格納された @ref{85e,,名前付きタプル} を保持する @ref{1368,,thread_info} が追加されました。 (bpo-11223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11223})

@node tarfile<9>,tempfile<4>,sys<13>,改良されたモジュール<11>
@anchor{whatsnew/3 3 tarfile}@anchor{1369}
@subsubsection tarfile


@ref{e4,,tarfile} が @ref{8e,,lzma} モジュールにより @code{lzma} エンコーディングをサポートするようになりました (Contributed by Lars Gustäbel in bpo-5689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5689}.)。

@node tempfile<4>,textwrap<3>,tarfile<9>,改良されたモジュール<11>
@anchor{whatsnew/3 3 tempfile}@anchor{136a}
@subsubsection tempfile


@ref{8a2,,tempfile.SpooledTemporaryFile}'s @code{truncate()} method now accepts
a @code{size} parameter.  (Contributed by Ryan Kelly in bpo-9957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9957}.)

@node textwrap<3>,threading<9>,tempfile<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 textwrap}@anchor{136b}
@subsubsection textwrap


@ref{f2,,textwrap} モジュールに @ref{57d,,indent()} が追加されました。これはテキストのブロック内の選択行に共通のプレフィクスを追加する簡単な方法になります。(bpo-13857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13857})

@node threading<9>,time<8>,textwrap<3>,改良されたモジュール<11>
@anchor{whatsnew/3 3 threading}@anchor{136c}
@subsubsection threading


いずれもかつてインスタンスを返すファクトリ関数であった @ref{136d,,threading.Condition}, @ref{136e,,threading.Semaphore}, @ref{136f,,threading.BoundedSemaphore}, @ref{1370,,threading.Event}, @ref{1371,,threading.Timer} がクラスになったので、サブクラス化出来るようになりました。 (Contributed by Éric Araujo in bpo-10968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10968}.)

@ref{176,,threading.Thread} コンストラクタがキーワード引数 @code{daemon} を取るようになりました。これは親スレッドから @code{daemon} フラグを継承するデフォルトの振る舞いをオーバライドします (bpo-6064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6064})。

かつての非公開関数 @code{_thread.get_ident} が公開関数 @ref{1372,,threading.get_ident()} として利用可能となっています。これは標準ライブラリにおいて多数の @code{_thread} モジュールへの直接アクセスを取り除く結果になりました。 @code{_thread.get_ident} を使っているサードパーティのコードも同じように、新しく公開化されたインターフェイスに乗り換えるべきです。

@node time<8>,types<8>,threading<9>,改良されたモジュール<11>
@anchor{whatsnew/3 3 time}@anchor{1373}
@subsubsection time


@geindex Python Enhancement Proposals; PEP 418
PEP 418@footnote{https://peps.python.org/pep-0418/} が @ref{f4,,time} モジュールに新たな関数を追加しました:


@itemize *

@item 
@ref{1374,,get_clock_info()}: クロックの情報を取得します。

@item 
@ref{55c,,monotonic()}: 単調なクロック (逆行しない)、システムクロックの更新の影響を受けません。

@item 
@ref{c7a,,perf_counter()}: 短期間の計測のために利用可能な最高の解像度を持つパフォーマンスカウンタです。

@item 
@ref{c7b,,process_time()}: 現在のプロセスの system と user CPU 時間の和です。
@end itemize

その他の新たな関数:


@itemize *

@item 
@ref{1375,,clock_getres()}, @ref{1376,,clock_gettime()} and
@ref{1377,,clock_settime()} functions with @code{CLOCK_@var{xxx}} constants.
(Contributed by Victor Stinner in bpo-10278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10278}.)
@end itemize

クロスプラットフォーム間での一貫性を改善するために、 @ref{8ac,,sleep()} が負の値を渡すと @ref{2ec,,ValueError} を投げるように変更されています。以前から POSIX システムではエラーでしたが、Windows の場合に無限に sleep していました。

@node types<8>,unittest<11>,time<8>,改良されたモジュール<11>
@anchor{whatsnew/3 3 types}@anchor{1378}
@subsubsection types


新規クラス @ref{698,,types.MappingProxyType} の追加: 読み出し専用のマッピングのプロキシです。 (bpo-14386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14386})

新規関数 @ref{1379,,types.new_class()} と @ref{137a,,types.prepare_class()} は 
@geindex Python Enhancement Proposals; PEP 3115
PEP 3115@footnote{https://peps.python.org/pep-3115/} 準拠の動的な型の生成サポートを提供します。(bpo-14588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14588})

@node unittest<11>,urllib<6>,types<8>,改良されたモジュール<11>
@anchor{whatsnew/3 3 unittest}@anchor{137b}
@subsubsection unittest


メソッド @ref{750,,assertRaises()}, @ref{752,,assertRaisesRegex()}, @ref{137c,,assertWarns()}, @ref{137d,,assertWarnsRegex()} が、コンテキストマネージャとして使われる際にキーワード引数 `msg' を受け付けるようになりました。 (Contributed by Ezio Melotti and Winston Ewert in bpo-10775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10775}.)

@ref{137e,,unittest.TestCase.run()} が @ref{137f,,TestResult} オブジェクトを返すようになりました。

@node urllib<6>,webbrowser<4>,unittest<11>,改良されたモジュール<11>
@anchor{whatsnew/3 3 urllib}@anchor{1380}
@subsubsection urllib


@ref{11da,,Request} クラスが @ref{1381,,get_method()} で使われる `method' 引数を受け付けるようになりました。これはどの HTTP メソッドが使われるべきかを指定します。例えば以下は @code{'HEAD'} リクエストを送信します:

@example
>>> urlopen(Request('https://www.python.org', method='HEAD'))
@end example

(bpo-1673007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1673007})

@node webbrowser<4>,xml etree ElementTree<2>,urllib<6>,改良されたモジュール<11>
@anchor{whatsnew/3 3 webbrowser}@anchor{1382}
@subsubsection webbrowser


@ref{11b,,webbrowser} モジュールがさらに多くの "browsers" をサポートしました: Google Chrome (バージョンと OS 依存で名前が @code{chrome}, @code{chromium}, @code{chrome-browser}, あるいは @code{chromium-browser}) と、汎用のランチャ @code{xdg-open} (FreeDesktop.org プロジェクトのもの) と @code{gvfs-open} (GNOME 3 のデフォルト URI ハンドラ)。 (The former contributed by Arnaud Calmettes in bpo-13620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13620}, the latter by Matthias Klose in bpo-14493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14493}.)

@node xml etree ElementTree<2>,zlib<3>,webbrowser<4>,改良されたモジュール<11>
@anchor{whatsnew/3 3 xml-etree-elementtree}@anchor{1383}
@subsubsection xml.etree.ElementTree


The @ref{12b,,xml.etree.ElementTree} module now imports its C accelerator by
default; there is no longer a need to explicitly import
@code{xml.etree.cElementTree} (this module stays for backwards compatibility,
but is now deprecated).  In addition,  the @code{iter} family of methods of
@ref{363,,Element} has been optimized (rewritten in C).
The module's documentation has also been greatly improved with added examples
and a more detailed reference.

@node zlib<3>,,xml etree ElementTree<2>,改良されたモジュール<11>
@anchor{whatsnew/3 3 zlib}@anchor{1384}
@subsubsection zlib


New attribute @ref{1385,,zlib.Decompress.eof} makes it possible to distinguish
between a properly formed compressed stream and an incomplete or truncated one.
(Contributed by Nadeem Vawda in bpo-12646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12646}.)

New attribute @ref{1386,,zlib.ZLIB_RUNTIME_VERSION} reports the version string of
the underlying @code{zlib} library that is loaded at runtime.  (Contributed by
Torsten Landschoff in bpo-12306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12306}.)

@node 最適化<11>,ビルドならびに C API の変更<4>,改良されたモジュール<11>,What's New In Python 3 3
@anchor{whatsnew/3 3 optimizations}@anchor{1387}
@subsection 最適化


大きな性能向上がありました:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} により、Unicode 文字列に対する操作が最適化されました:


@itemize *

@item 
メモリフットプリントはテキストに依存して 1/2 から 1/4 になりました

@item 
ASCII 文字列を UTF-8 にエンコードするのに文字をエンコードする必要はなくなりました、UTF-8 表現は ASCII 表現と共有されます

@item 
UTF-8 エンコーダが最適化されました

@item 
単一の ASCII 文字を繰り返して ASCII 文字列の部分列を得るのは 4 倍速くなりました
@end itemize

@item 
UTF-8 が2倍から4倍速くなりました。UTF-16 のエンコーディングが最大で10倍速くなりました。

(Contributed by Serhiy Storchaka, bpo-14624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14624}, bpo-14738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14738} and
bpo-15026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15026}.)
@end itemize

@node ビルドならびに C API の変更<4>,非推奨<13>,最適化<11>,What's New In Python 3 3
@anchor{whatsnew/3 3 build-and-c-api-changes}@anchor{1254}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
新しい 
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} 関連の関数:


@itemize *

@item 
@ref{1388,,PyMemoryView_FromMemory()}
@end itemize

@item 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} により追加された新たな Unicode 型、マクロ、関数:


@itemize *

@item 
高水準 API:


@itemize *

@item 
@ref{ab2,,PyUnicode_CopyCharacters()}

@item 
@ref{ab6,,PyUnicode_FindChar()}

@item 
@ref{ab0,,PyUnicode_GetLength()}, @ref{ab1,,PyUnicode_GET_LENGTH}

@item 
@ref{aa9,,PyUnicode_New()}

@item 
@ref{ab3,,PyUnicode_Substring()}

@item 
@ref{1389,,PyUnicode_ReadChar()}, @ref{138a,,PyUnicode_WriteChar()}
@end itemize

@item 
低水準 API:


@itemize *

@item 
型 @ref{138b,,Py_UCS1}, @ref{138c,,Py_UCS2}, @ref{33d,,Py_UCS4}

@item 
構造体 @ref{138d,,PyASCIIObject} と @ref{138e,,PyCompactUnicodeObject}

@item 
@ref{434,,PyUnicode_READY}

@item 
@ref{138f,,PyUnicode_FromKindAndData()}

@item 
@ref{1390,,PyUnicode_AsUCS4()}, @ref{ab8,,PyUnicode_AsUCS4Copy()}

@item 
@ref{1391,,PyUnicode_DATA}, @ref{1392,,PyUnicode_1BYTE_DATA},
@ref{1393,,PyUnicode_2BYTE_DATA}, @ref{1394,,PyUnicode_4BYTE_DATA}

@item 
@ref{1395,,PyUnicode_KIND} with @code{PyUnicode_Kind} enum:
@code{PyUnicode_WCHAR_KIND}, @ref{1396,,PyUnicode_1BYTE_KIND},
@ref{1397,,PyUnicode_2BYTE_KIND}, @ref{1398,,PyUnicode_4BYTE_KIND}

@item 
@ref{1399,,PyUnicode_READ}, @ref{139a,,PyUnicode_READ_CHAR}, @ref{139b,,PyUnicode_WRITE}

@item 
@ref{139c,,PyUnicode_MAX_CHAR_VALUE}
@end itemize
@end itemize

@item 
@ref{3c1,,PyArg_ParseTuple} が @code{c} フォーマットとして @ref{344,,bytearray} を許容するようになりました (bpo-12380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12380})。
@end itemize

@node 非推奨<13>,Python 3 3 への移植,ビルドならびに C API の変更<4>,What's New In Python 3 3
@anchor{whatsnew/3 3 deprecated}@anchor{139d}
@subsection 非推奨


@menu
* サポートされないオペレーティングシステム: サポートされないオペレーティングシステム<2>. 
* 非推奨の Python モジュール、関数、メソッド: 非推奨の Python モジュール、関数、メソッド<4>. 
* C API の非推奨の関数ならびに型: C API の非推奨の関数ならびに型<3>. 
* 非推奨の機能: 非推奨の機能<2>. 

@end menu

@node サポートされないオペレーティングシステム<2>,非推奨の Python モジュール、関数、メソッド<4>,,非推奨<13>
@anchor{whatsnew/3 3 unsupported-operating-systems}@anchor{139e}
@subsubsection サポートされないオペレーティングシステム


保守する者がいないため OS/2 ならびに VMS はもはやサポートされません。

保守の負担のため WIndows 2000 および @code{COMSPEC} を @code{command.com} に設定している Windows プラットフォームはもはやサポートされません。

3.2 で非推奨だった OSF のサポートが完全に削除されました。

@node 非推奨の Python モジュール、関数、メソッド<4>,C API の非推奨の関数ならびに型<3>,サポートされないオペレーティングシステム<2>,非推奨<13>
@anchor{whatsnew/3 3 deprecated-python-modules-functions-and-methods}@anchor{139f}
@subsubsection 非推奨の Python モジュール、関数、メソッド



@itemize *

@item 
object 型そのものの @code{object.__format__()} に空でない文字列が渡すことは非推奨となりました。Python 3.4 ではこれは @ref{198,,TypeError} となります (bpo-9856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9856})。

@item 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} により、 @code{unicode_internal} コーデックは非推奨となりました。UTF-8, UTF-16 (@code{utf-16-le} または @code{utf-16-be}), あるいは UTF-32 (@code{utf-32-le} または @code{utf-32-be}) を使ってください。

@item 
@ref{12da,,ftplib.FTP.nlst()} および @ref{12db,,ftplib.FTP.dir()}: @ref{12d9,,ftplib.FTP.mlsd()} を使ってください

@item 
@code{platform.popen()}: use the @ref{dc,,subprocess} module. Check especially
the @ref{13a0,,Replacing Older Functions with the subprocess Module} section (bpo-11377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11377}).

@item 
bpo-13374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13374}: @ref{a5,,os} モジュールにある Windows のバイト列 API は非推奨となりました。ANSI コードページに依存しないようにしてあらゆるファイル名をサポートするために、バイト列文字列のファイル名ではなく Unicode ファイル名を使ってください。

@item 
bpo-13988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13988}: The @code{xml.etree.cElementTree} module is deprecated.  The
accelerator is used automatically whenever available.

@item 
The behaviour of @code{time.clock()} depends on the platform: use the new
@ref{c7a,,time.perf_counter()} or @ref{c7b,,time.process_time()} function instead,
depending on your requirements, to have a well defined behaviour.

@item 
The @code{os.stat_float_times()} function is deprecated.

@item 
@ref{4,,abc} モジュール:


@itemize *

@item 
@ref{1296,,abc.abstractproperty} は非推奨となりました。代わりに @ref{1297,,abc.abstractmethod()} に @ref{4b3,,property} を渡して使ってください。

@item 
@ref{1298,,abc.abstractclassmethod} は非推奨となりました。代わりに @ref{1297,,abc.abstractmethod()} に @ref{48e,,classmethod} を渡して使ってください。

@item 
@ref{1299,,abc.abstractstaticmethod} は非推奨となりました。代わりに @ref{1297,,abc.abstractmethod()} に @ref{453,,staticmethod} を渡して使ってください。
@end itemize

@item 
@ref{7b,,importlib} パッケージ:


@itemize *

@item 
バイトコードファイルとしての @ref{13a1,,importlib.abc.SourceLoader.path_stats()} によりコンパイル時点の修正時刻とソースファイルサイズの両方を格納するようになったので、 @ref{13a2,,importlib.abc.SourceLoader.path_mtime()} は非推奨となりました。
@end itemize
@end itemize

@node C API の非推奨の関数ならびに型<3>,非推奨の機能<2>,非推奨の Python モジュール、関数、メソッド<4>,非推奨<13>
@anchor{whatsnew/3 3 deprecated-functions-and-types-of-the-c-api}@anchor{13a3}
@subsubsection C API の非推奨の関数ならびに型


@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} で @ref{3e0,,Py_UNICODE} は非推奨になり、Python 4 で削除されます。この型を使用している全ての関数は非推奨です。

Unicode functions and methods using @ref{3e0,,Py_UNICODE} and
@ref{3e0,,Py_UNICODE}* types:


@itemize *

@item 
@code{PyUnicode_FromUnicode}: use @ref{13a4,,PyUnicode_FromWideChar()} or
@ref{138f,,PyUnicode_FromKindAndData()}

@item 
@code{PyUnicode_AS_UNICODE}, @code{PyUnicode_AsUnicode()},
@code{PyUnicode_AsUnicodeAndSize()}: use @ref{ab9,,PyUnicode_AsWideCharString()}

@item 
@code{PyUnicode_AS_DATA}: use @ref{1391,,PyUnicode_DATA} with
@ref{1399,,PyUnicode_READ} and @ref{139b,,PyUnicode_WRITE}

@item 
@code{PyUnicode_GET_SIZE}, @code{PyUnicode_GetSize()}: use
@ref{ab1,,PyUnicode_GET_LENGTH} or @ref{ab0,,PyUnicode_GetLength()}

@item 
@code{PyUnicode_GET_DATA_SIZE}: use
@code{PyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str)} (only work on ready
strings)

@item 
@code{PyUnicode_AsUnicodeCopy()}: use @ref{ab8,,PyUnicode_AsUCS4Copy()} or
@ref{ab9,,PyUnicode_AsWideCharString()}

@item 
@code{PyUnicode_GetMax()}
@end itemize

Py_UNICODE* 文字列を操作する関数ならびにマクロ:


@itemize *

@item 
@code{Py_UNICODE_strlen()}: use @ref{ab0,,PyUnicode_GetLength()} or
@ref{ab1,,PyUnicode_GET_LENGTH}

@item 
@code{Py_UNICODE_strcat()}: use @ref{ab2,,PyUnicode_CopyCharacters()} or
@ref{62b,,PyUnicode_FromFormat()}

@item 
@code{Py_UNICODE_strcpy()}, @code{Py_UNICODE_strncpy()},
@code{Py_UNICODE_COPY()}: use @ref{ab2,,PyUnicode_CopyCharacters()} or
@ref{ab3,,PyUnicode_Substring()}

@item 
@code{Py_UNICODE_strcmp()}: use @ref{ab4,,PyUnicode_Compare()}

@item 
@code{Py_UNICODE_strncmp()}: use @ref{ab5,,PyUnicode_Tailmatch()}

@item 
@code{Py_UNICODE_strchr()}, @code{Py_UNICODE_strrchr()}: use
@ref{ab6,,PyUnicode_FindChar()}

@item 
@code{Py_UNICODE_FILL()}: use @ref{13a5,,PyUnicode_Fill()}

@item 
@code{Py_UNICODE_MATCH}
@end itemize

エンコーダ:


@itemize *

@item 
@code{PyUnicode_Encode()}: use @code{PyUnicode_AsEncodedObject()}

@item 
@code{PyUnicode_EncodeUTF7()}

@item 
@code{PyUnicode_EncodeUTF8()}: use @ref{424,,PyUnicode_AsUTF8()} or
@ref{13a6,,PyUnicode_AsUTF8String()}

@item 
@code{PyUnicode_EncodeUTF32()}

@item 
@code{PyUnicode_EncodeUTF16()}

@item 
@code{PyUnicode_EncodeUnicodeEscape()} use
@ref{13a7,,PyUnicode_AsUnicodeEscapeString()}

@item 
@code{PyUnicode_EncodeRawUnicodeEscape()} use
@ref{13a8,,PyUnicode_AsRawUnicodeEscapeString()}

@item 
@code{PyUnicode_EncodeLatin1()}: use @ref{13a9,,PyUnicode_AsLatin1String()}

@item 
@code{PyUnicode_EncodeASCII()}: use @ref{13aa,,PyUnicode_AsASCIIString()}

@item 
@code{PyUnicode_EncodeCharmap()}

@item 
@code{PyUnicode_TranslateCharmap()}

@item 
@code{PyUnicode_EncodeMBCS()}: use @ref{13ab,,PyUnicode_AsMBCSString()} or
@ref{13ac,,PyUnicode_EncodeCodePage()} (with @code{CP_ACP} code_page)

@item 
@code{PyUnicode_EncodeDecimal()},
@code{PyUnicode_TransformDecimalToASCII()}
@end itemize

@node 非推奨の機能<2>,,C API の非推奨の関数ならびに型<3>,非推奨<13>
@anchor{whatsnew/3 3 deprecated-features}@anchor{13ad}
@subsubsection 非推奨の機能


@ref{8,,array} モジュールの @code{'u'} 書式化コードは非推奨となりました。Python 4 ではほかの (@ref{3e0,,Py_UNICODE}) API と一緒に削除されるでしょう。

@node Python 3 3 への移植,,非推奨<13>,What's New In Python 3 3
@anchor{whatsnew/3 3 porting-to-python-3-3}@anchor{13ae}
@subsection Python 3.3 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:

@menu
* Python コードの移植:: 
* C コードの移植:: 
* C 拡張のビルド:: 
* コマンドラインスイッチの変更:: 

@end menu

@node Python コードの移植,C コードの移植,,Python 3 3 への移植
@anchor{whatsnew/3 3 porting-python-code}@anchor{127a}@anchor{whatsnew/3 3 portingpythoncode}@anchor{13af}
@subsubsection Python コードの移植



@itemize *

@item 
ハッシュのランダム化がデフォルトで有効になりました。これを無効にするには環境変数 
@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} を @code{0} にセットして下さい。 @ref{cf3,,object.__hash__()} メソッドも参照して下さい。

@item 
bpo-12326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12326}: Linux では、 @ref{291,,sys.platform} はもはやメジャーバージョン番号を含みません。 これは今では常に 'linux' です。以前はこれは Python のビルドに使われた Linux バージョンに依存した @code{'linux2'} や @code{'linux3'} でした。 @code{sys.platform == 'linux2'} などとするのではなく、 @code{sys.platform.startswith('linux')} とするか、古い Python バージョンのサポートが不要であれば直接的に @code{sys.platform == 'linux'} として下さい。

@item 
bpo-13847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13847}, bpo-14180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14180}: @ref{f4,,time} および @ref{34,,datetime}: タイムスタンプが範囲外の場合に、 @ref{2ec,,ValueError} ではなく @ref{a81,,OverflowError} を送出するようになりました。また、C 関数の @code{gmtime()} あるいは @code{localtime()} が失敗した場合には @ref{2c0,,OSError} を送出するようになりました。

@item 
インポートで使われるデフォルトのファインダが、特定のディレクトリに何が含まれるのかについてのキャッシュを利用するようになっています。実行中に Python ソースファイルやバイトコードファイルを作ったら、キャッシュをクリアしてファインダが新しく作られたファイルに気付けるように、 @ref{e0a,,importlib.invalidate_caches()} を呼ぶ必要があることに注意してください。

@item 
@ref{65b,,ImportError} がインポートを試みたモジュール名として完全名を使うようになっています。ImportError のメッセージをチェックする doctest は、モジュール名をその末尾の名前ではなく完全な名前を使うように更新する必要があります。

@item 
@ref{ad1,,__import__()} の引数 `index' のデフォルトが -1 ではなく 0 となり、また、もはや負の値はサポートされません。デフォルト値が -1 で残されたのは(訳注: つまり絶対、相対インポートの両方を試みるようにしたのは) 
@geindex Python Enhancement Proposals; PEP 328
PEP 328@footnote{https://peps.python.org/pep-0328/} を実装した際の過失でした。絶対インポートに先立って相対インポートを実行する振る舞いがまだ必要なのであれば、index を 1 にして相対インポートを実行して、その後で index 0 のインポートをするようにしてください。そうなのですが、 @ref{ad1,,__import__()} を直接呼び出すのではなく、 @ref{73c,,importlib.import_module()} を使うことが望ましいやり方です。

@item 
@ref{ad1,,__import__()} の index に、トップレベルモジュールに対して 0 でなく 1 を与えることは今では許されません。例えば @code{__import__('sys', level=1)} はエラーです。

@item 
Because @ref{f27,,sys.meta_path} and @ref{1225,,sys.path_hooks} now have finders on
them by default, you will most likely want to use @ref{13b0,,list.insert()} instead
of @ref{8dc,,list.append()} to add to those lists.

@item 
Because @code{None} is now inserted into @ref{7fa,,sys.path_importer_cache}, if you
are clearing out entries in the dictionary of paths that do not have a
finder, you will need to remove keys paired with values of @code{None} `and'
@code{imp.NullImporter} to be backwards-compatible. This will lead to extra
overhead on older versions of Python that re-insert @code{None} into
@ref{7fa,,sys.path_importer_cache} where it represents the use of implicit
finders, but semantically it should not change anything.

@item 
@code{importlib.abc.Finder} no longer specifies a @code{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 @code{find_loader()} first, though, in the
case of working with @ref{127d,,path entry finders}.

@item 
@ref{ae,,pkgutil} は、内部的に @ref{7b,,importlib} を使うように変更されました。このことは、 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} インポートエミュレーションの古い振る舞いが本物のインポートシステムの振る舞いに合わせるのに失敗していた数多くの特殊ケースの問題を取り除きます。インポートエミュレーションそのものはまだ存在しますが、今では非推奨です。 @ref{13b1,,pkgutil.iter_importers()} 関数と @ref{df9,,pkgutil.walk_packages()} 関数は標準インポートフックを特別に扱うので、ファインダの @code{iter_modules()} メソッドは標準ではないにも関わらず、まだサポートされます。

@item 
@ref{12ce,,email.header.decode_header()} によってなされる解析に長い間存在していた RFC 非準拠のバグ (bpo-1079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1079}) が修正されました。エンコードされたヘッダを Unicode に変換するための標準的なイディオム (@code{str(make_header(decode_header(h))}) を使うコードからは変化はみえません。ですが、 decode_header から返される個々のタプル要素を見ているコードでは、 @code{ASCII} セクションの前後の空白が @code{ASCII} 内に含まれるようになったことがわかります。 @code{make_header} は入力文字列に既に存在していなければ @code{ASCII} 非 @code{ASCII} セクション間に以前と同じく空白を追加するので、 @code{make_header} を使ってヘッダを構築するコードは変更なしで動作するはずです。

@item 
@ref{13b2,,email.utils.formataddr()} は非 ASCII の display name に対し正しい content transfer encoding の扱いをするようになっています。かつての、フォーマット後文字列内に非 ASCII Unicode を維持してしまう誤った振る舞いに依存するすべてのコードは、変更の必要があります。 (bpo-1690608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1690608})

@item 
@ref{13b3,,poplib.POP3.quit()} メソッドもほかの全ての @code{poplib} のメソッドと同じく、今ではプロトコルエラーを送出し得ます。 @code{quit} が @ref{13b4,,poplib.error_proto} エラーを送出しないことをあてにしていたコードは、 @code{quit} でのエラーが特定のアプリケーションにとって問題となるようであれば、修正の必要があるかもしれません (bpo-11291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11291})。

@item 
Python 2.4 から非推奨となっていた、 @ref{13b5,,email.parser.Parser} への @code{strict} 引数はついに削除されました。

@item 
非推奨となっていたメソッド @code{unittest.TestCase.assertSameElements} は削除されました。

@item 
非推奨となっていた変数 @code{time.accept2dyear} は削除されました。

@item 
非推奨となっていた @code{Context._clamp} 属性が @ref{3a,,decimal} モジュールから削除されました。以前に既にこれは公開属性 @ref{13b6,,clamp} に置き換えられていました (bpo-8540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8540} 参照)。

@item 
文書化されていなかった内部ヘルパクラス @code{SSLFakeFile} が @ref{cf,,smtplib} モジュールより削除されました。この機能はずっと以前から @ref{13b7,,socket.socket.makefile()} によって直接的に提供されています。

@item 
Windows では @ref{8ac,,time.sleep()} に負値を与えた場合に無限に眠っていましたが、今ではこれは例外を送出します。POSIX ではこれは以前より常に例外です。

@item 
The @code{ast.__version__} constant has been removed.  If you need to
make decisions affected by the AST version, use @ref{8af,,sys.version_info}
to make the decision.

@item 
@ref{f3,,threading} モジュールの、非公開クラスをサブクラス化するファクトリ関数を迂回していたコードは、今では公開クラスになったので修正の必要があります。

@item 
threading モジュール内の文書化されていなかったデバッグ機構を削除してコードを単純化しました。このことが製品コードに影響することがあってはなりませんが、これと連携していたアプリケーションデバッグフレームワークのケースがありうるので、言及しておきます (bpo-13550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13550})。
@end itemize

@node C コードの移植,C 拡張のビルド,Python コードの移植,Python 3 3 への移植
@anchor{whatsnew/3 3 porting-c-code}@anchor{1255}
@subsubsection C コードの移植



@itemize *

@item 
In the course of changes to the buffer API the undocumented
@code{smalltable} member of the
@ref{95c,,Py_buffer} structure has been removed and the
layout of the @code{PyMemoryViewObject} has changed.

@code{memoryobject.h} あるいは @code{object.h} での関係する部分に依存する全ての拡張は、再ビルドが必要です。

@item 
@ref{123f,,PEP 393} により、 @ref{3e0,,Py_UNICODE} 型とこの型を使う全ての関数は非推奨となりました (ただし最低 5 年は利用可能なまま保たれます)。Unicode オブジェクトの構築とアクセスに低水準 Unicode API をこれまで使っていて、 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} によって提供されるメモリフットプリント削減の恩恵を受けたければ、新しい @ref{13b8,,Unicode API} に乗り換える必要があります。

一方で @ref{13b9,,PyUnicode_Concat()} 、 @ref{13ba,,PyUnicode_Join()} あるいは @ref{62b,,PyUnicode_FromFormat()} といった高水準関数のみを使ってきたのであれば、あなたのコードは自動的に新しい Unicode 表現に便乗できます。

@item 
@ref{13bb,,PyImport_GetMagicNumber()} は失敗時に @code{-1} を返すようになりました。

@item 
@ref{ad1,,__import__()} の `level' 引数に負値を渡すことはもはや有効ではないので、対応する @ref{13bc,,PyImport_ImportModuleLevel()} でも同じです。このことは @ref{13bd,,PyImport_ImportModuleEx()} に使われる `level' の値が @code{-1} ではなく @code{0} を使うようになったことも意味しています。
@end itemize

@node C 拡張のビルド,コマンドラインスイッチの変更,C コードの移植,Python 3 3 への移植
@anchor{whatsnew/3 3 building-c-extensions}@anchor{13be}
@subsubsection C 拡張のビルド



@itemize *

@item 
C 拡張のファイル名として認められる範囲が狭められました。滅多に使われてこなかった命名は取りやめられました: POSIX では、 @code{xxxmodule.so}, @code{xxxmodule.abi3.so}, @code{xxxmodule.cpython-*.so} 命名は今後 @code{xxx} モジュールの実装とは認識されません。これまでそのようなファイルを作ってきたのであれば、別の命名に乗り換えてください (つまり @code{module} 文字列をファイル名から取り除いてください)。

(implemented in bpo-14040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14040}.)
@end itemize

@node コマンドラインスイッチの変更,,C 拡張のビルド,Python 3 3 への移植
@anchor{whatsnew/3 3 command-line-switch-changes}@anchor{13bf}
@subsubsection コマンドラインスイッチの変更



@itemize *

@item 
@code{-Q} コマンドラインスイッチとそれに関係するものは削除されました。 @code{sys.flags.division_warning} をチェックしているコードは修正する必要があります。

(bpo-10998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10998}, contributed by Éric Araujo.)

@item 
@ref{13c0,,-S} スイッチ付きで @code{python} を開始すると、 @code{import site} がモジュール検索パスにサイト固有のパスを追加しなくなります。以前のバージョンではそれをしていました。

(bpo-11591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11591}, contributed by Carl Meyer with editions by Éric Araujo.)
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 2,What's New In Python 3 1,What's New In Python 3 3,What's New in Python
@anchor{whatsnew/3 2 doc}@anchor{13c1}@anchor{whatsnew/3 2 translation-repo}@anchor{13c2}@anchor{whatsnew/3 2 what-s-new-in-python-3-2}@anchor{13c3}
@section What's New In Python 3.2


@*著者: 
Raymond Hettinger


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten.  (Note, during release candidate phase or just before
@c a beta release, please use the tracker instead -- this helps avoid
@c merge conflicts.   If you must add a suggested entry directly,
@c please put it in an XXX comment and the maintainer will take notice).
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.  It's helpful to
@c add the issue number:
@c 
@c   XXX Describe the transmogrify() function added to the socket
@c   module.
@c 
@c   (Contributed by P.Y. Developer; :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the SVN log
@c when researching a change.

This article explains the new features in Python 3.2 as compared to 3.1.
Python 3.2 was released on February 20, 2011. It
focuses on a few highlights and gives a few examples.  For full details, see the
Misc/NEWS@footnote{https://github.com/python/cpython/blob/076ca6c3c8df3030307e548d9be792ce3c1c6eea/Misc/NEWS}
file.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 392
PEP 392@footnote{https://peps.python.org/pep-0392/} - Python 3.2 リリーススケジュール


@menu
* PEP 384; 安定 ABI の定義: PEP 384 安定 ABI の定義. 
* PEP 389; argparse コマンドライン解析モジュール: PEP 389 argparse コマンドライン解析モジュール. 
* PEP 391; logging の辞書ベースの設定: PEP 391 logging の辞書ベースの設定. 
* PEP 3148; concurrent.futures モジュール: PEP 3148 concurrent futures モジュール. 
* PEP 3147; PYC リポジトリーディレクトリ: PEP 3147 PYC リポジトリーディレクトリ. 
* PEP 3149; ABI バージョンでタグ付けされた .so ファイル: PEP 3149 ABI バージョンでタグ付けされた so ファイル. 
* PEP 3333; Python Web Server Gateway Interface v1.0.1: PEP 3333 Python Web Server Gateway Interface v1 0 1. 
* その他の言語変更: その他の言語変更<12>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール:: 
* マルチスレッディング:: 
* 最適化: 最適化<12>. 
* Unicode 文字列型:: 
* Codecs:: 
* ドキュメント:: 
* IDLE:: 
* コードリポジトリ:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<5>. 
* Python 3.2 への移植: Python 3 2 への移植. 

@end menu

@node PEP 384 安定 ABI の定義,PEP 389 argparse コマンドライン解析モジュール,,What's New In Python 3 2
@anchor{whatsnew/3 2 pep-384-defining-a-stable-abi}@anchor{13c4}
@subsection PEP 384: 安定 ABI の定義


かつて、ある Python バージョンでビルドされた拡張モジュールは、ほかの Python バージョンでは使えないことがありました。特に Windows では、全ての Python 公式リリースごとに、使いたい全ての拡張モジュールを再ビルドする必要がありました。これは、拡張モジュールが Python インタプリタの内部実装に自由にアクセス出来たことからの結果でした。

Python 3.2 より、このことに関する別のアプローチが利用可能になりました。(@ref{660,,Py_LIMITED_API} を定義することで) 制限された API のみ使うようにする拡張モジュールは、数多くの内部実装を利用出来ない代わりに将来のいくつものリリースで安定であることを約束された API 集合だけ使うことになります。結果として、このモードで 3.2 のためにビルドされた拡張モジュールは 3.3、3.4、…でも動作するでしょう。なお、メモリ構造の詳細を曝すような拡張モジュールでは、相変わらず全ての Python 公式リリースごとに再ビルドする必要があるでしょう。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 384

@item PEP 384@footnote{https://peps.python.org/pep-0384/} - 安定 ABI の定義

PEP written by Martin von Löwis.
@end table


@node PEP 389 argparse コマンドライン解析モジュール,PEP 391 logging の辞書ベースの設定,PEP 384 安定 ABI の定義,What's New In Python 3 2
@anchor{whatsnew/3 2 pep-389-argparse-command-line-parsing-module}@anchor{13c5}
@subsection PEP 389: argparse コマンドライン解析モジュール


コマンドライン解析のために、新たに @ref{7,,argparse} モジュールが @ref{a4,,optparse} の制限を克服するものとして導入されました。optparse には (オプションだけでなく) 位置引数のサポートはなく、サブコマンドも作れず、必須のオプションやその他オプション指定と検証に共通するパターンについてのサポートもありませんでした。

このモジュールはコミュニティにおいて既に広く行き渡っていたサードパーティのモジュールでした。その先駆者たちよりももっと完全な機能性を持ったことで、 @ref{7,,argparse} モジュールは今ではコマンドライン解析での推奨モジュールとなりました。古いモジュールは、それに依存しているレガシーなコードが大量にあるため、今後も利用可能なまま保たれます。

以下に注釈付きで示したパーサは、有限個の選択肢から選ばせ、 `metavar' でヘルプ表示を指定し、一つ以上の位置引数があるかを検証し、必須オプションを設けている実例になっています:

@example
import argparse
parser = argparse.ArgumentParser(
            description = 'Manage servers',         # main description for help
            epilog = 'Tested on Solaris and Linux') # displayed after help
parser.add_argument('action',                       # argument name
            choices = ['deploy', 'start', 'stop'],  # three allowed values
            help = 'action on each target')         # help msg
parser.add_argument('targets',
            metavar = 'HOSTNAME',                   # var name used in help msg
            nargs = '+',                            # require one or more targets
            help = 'url for target machines')       # help msg explanation
parser.add_argument('-u', '--user',                 # -u or --user option
            required = True,                        # make it a required argument
            help = 'login as user')
@end example

コマンド文字列とともにこのパーサを呼び出してみます:

@example
>>> cmd = 'deploy sneezy.example.com sleepy.example.com -u skycaptain'
>>> result = parser.parse_args(cmd.split())
>>> result.action
'deploy'
>>> result.targets
['sneezy.example.com', 'sleepy.example.com']
>>> result.user
'skycaptain'
@end example

このパーサが自動的に作り出したヘルプはこのようになります:

@example
>>> parser.parse_args('-h'.split())

usage: manage_cloud.py [-h] -u USER
                       @{deploy,start,stop@} HOSTNAME [HOSTNAME ...]

Manage servers

positional arguments:
  @{deploy,start,stop@}   action on each target
  HOSTNAME              url for target machines

optional arguments:
  -h, --help            show this help message and exit
  -u USER, --user USER  login as user

Tested on Solaris and Linux
@end example

@ref{7,,argparse} 機能でとりわけ素晴らしいのはサブパーサを定義出来ることです。それらはそれぞれ自身固有の引数パターンを持ち、ヘルプ表示をします:

@example
import argparse
parser = argparse.ArgumentParser(prog='HELM')
subparsers = parser.add_subparsers()

parser_l = subparsers.add_parser('launch', help='Launch Control')   # first subgroup
parser_l.add_argument('-m', '--missiles', action='store_true')
parser_l.add_argument('-t', '--torpedos', action='store_true')

parser_m = subparsers.add_parser('move', help='Move Vessel',        # second subgroup
                                 aliases=('steer', 'turn'))         # equivalent names
parser_m.add_argument('-c', '--course', type=int, required=True)
parser_m.add_argument('-s', '--speed', type=int, default=0)
@end example

@example
$ ./helm.py --help                         # top level help (launch and move)
$ ./helm.py launch --help                  # help for launch options
$ ./helm.py launch --missiles              # set missiles=True and torpedos=False
$ ./helm.py steer --course 180 --speed 5   # set movement parameters
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 389

@item PEP 389@footnote{https://peps.python.org/pep-0389/} - 新しいコマンドライン解析モジュール

PEP written by Steven Bethard.
@end table

@ref{13c6,,Migrating optparse code to argparse} に @ref{a4,,optparse} との違いが詳しく書かれています。


@node PEP 391 logging の辞書ベースの設定,PEP 3148 concurrent futures モジュール,PEP 389 argparse コマンドライン解析モジュール,What's New In Python 3 2
@anchor{whatsnew/3 2 pep-391-dictionary-based-configuration-for-logging}@anchor{13c7}
@subsection PEP 391:  logging の辞書ベースの設定


The @ref{8b,,logging} module provided two kinds of configuration, one style with
function calls for each option or another style driven by an external file saved
in a @ref{26,,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.

もっと柔軟な設定をサポートするために、新たに @ref{13c8,,logging.config.dictConfig()} が追加されました。これはロギングの設定を通常の Python 辞書で指定します。設定オプションにはフォーマッタ、ハンドラ、フィルタ、そしてロガーが含まれます。以下は設定辞書の動作する実例です:

@example
@{"version": 1,
 "formatters": @{"brief": @{"format": "%(levelname)-8s: %(name)-15s: %(message)s"@},
                "full": @{"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"@}
                @},
 "handlers": @{"console": @{
                   "class": "logging.StreamHandler",
                   "formatter": "brief",
                   "level": "INFO",
                   "stream": "ext://sys.stdout"@},
              "console_priority": @{
                   "class": "logging.StreamHandler",
                   "formatter": "full",
                   "level": "ERROR",
                   "stream": "ext://sys.stderr"@}
              @},
 "root": @{"level": "DEBUG", "handlers": ["console", "console_priority"]@}@}
@end example

その辞書が @code{conf.json} ファイルに格納されているのであれば、コードからこのように呼び出してロード出来ます:

@example
>>> import json, logging.config
>>> with open('conf.json') as f:
...     conf = json.load(f)
...
>>> logging.config.dictConfig(conf)
>>> logging.info("Transaction completed normally")
INFO    : root           : Transaction completed normally
>>> logging.critical("Abnormal termination")
2011-02-17 11:14:36,694 root            CRITICAL Abnormal termination
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 391

@item PEP 391@footnote{https://peps.python.org/pep-0391/} - logging の辞書ベースの設定

PEP written by Vinay Sajip.
@end table


@node PEP 3148 concurrent futures モジュール,PEP 3147 PYC リポジトリーディレクトリ,PEP 391 logging の辞書ベースの設定,What's New In Python 3 2
@anchor{whatsnew/3 2 pep-3148-the-concurrent-futures-module}@anchor{13c9}
@subsection PEP 3148:  @code{concurrent.futures} モジュール


同時並行性 (concurrency) を生成・管理するコードはトップレベルの新しい名前空間 `concurrent' に集められることになりました。その最初のメンバーが `futures' パッケージです。これはスレッドとプロセス管理の統一的な高水準インターフェイスを提供します。

@ref{24,,concurrent.futures} の設計は Java の `java.util.concurrent' パッケージに触発されました。そのモデルでは、実行する呼び出しとその結果は @ref{13ca,,Future} オブジェクトで表現され、これはスレッド、プロセス、遠隔手続呼び出しの共通的な側面を抽象化しています。そのオブジェクトはステータスのチェック (実行中あるいは完了かどうか)、タイムアウト、キャンセル、コールバックの追加、そして結果や例外へのアクセスをサポートします。

この新モジュールで提供される最も基本となるのが、呼び出しの実行と管理のための 2 つの executor クラスです。これら executor の目標は、これまでにもあった道具立てでの並列呼び出しを、もっと簡単にすることです。リソースプールをお膳立てしたり呼び出しを実行したり、結果のキューを作ったり、あるいはタイムアウトのハンドラを追加したり、スレッドやプロセスや遠隔手続呼び出しの総数を制限したり、といったことを、これらを使えば、その労力を小さく出来ます。

理想的にはそれぞれのアプリケーションは、プロセスとスレッドの制限が確実に管理されるように、複数コンポーネントをまたがって単一の executor を共有すべきです。そうしておけば、個々のコンポーネントがリソース管理についての競合する戦略を持つ場合に起こる設計の難題は解決出来ます。

どちらの executor クラスとも 3 つのメソッドを持つ共通インターフェイスを持ちます。 @ref{c75,,submit()} メソッドは呼び出し可能オブジェクトをスケジュールし、 @ref{13ca,,Future} オブジェクトを返します。 @ref{1dc,,map()} メソッドは一気に複数の非同期呼び出しをスケジュールします。 @ref{aea,,shutdown()} メソッドはリソースを解放します。これらクラスは @ref{1e1,,context manager} なので @ref{186,,with} 文とともに使うことが出来、現時点で保留中の future が実行を終えた際にリソースが自動的に解放されることを保障出来ます。

以下はファイルコピーを行う 4 つの並列スレッドを実行する、 @ref{949,,ThreadPoolExecutor} の単純な使用例です:

@example
import concurrent.futures, shutil
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest4.txt')
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3148

@item PEP 3148@footnote{https://peps.python.org/pep-3148/} - Futures -- 計算の非同期な実行

PEP written by Brian Quinlan.
@end table

@ref{13cb,,ThreadPoolExecutor の例} はスレッド並列でウェブページを取得する実例コードです。

@ref{1d6,,ProcessPoolExecutor} の実例を @ref{13cc,,並列で素数計算するコード例} として挙げています。


@node PEP 3147 PYC リポジトリーディレクトリ,PEP 3149 ABI バージョンでタグ付けされた so ファイル,PEP 3148 concurrent futures モジュール,What's New In Python 3 2
@anchor{whatsnew/3 2 pep-3147-pyc-repository-directories}@anchor{13cd}
@subsection PEP 3147:  PYC リポジトリーディレクトリ


バイトコードを `.pyc' ファイルとしてキャッシュする Python の方法は、複数の Python インタプリタ環境ではうまく働きませんでした。一つのインタプリタがもう一つのインタプリタによって作られたキャッシュファイルに出会うと、そのインタプリタはソースを再コンパイルしてキャッシュファイルを上書きするわけですから、これではキャッシュの価値は台無しです。

「pyc ファイト」問題は、複数バージョンの Python を載せる Linux ディストリビューションにありふれたこととなったよりももっと表立って来ました。これら衝突は Unladen Swallow@footnote{https://en.wikipedia.org/wiki/Unladen_Swallow#Project_activity} のような CPython 以外の実装でも起こります。

この問題を解決するために、Python のインポート機構はそれぞれのインタプリタごとに区別された名前を使うように拡張されました。Python 3.2、Python 3.3、 Unladen Swallow でそれぞれ競合するファイル名 "mymodule.pyc" を使うのではなく、それぞれ "mymodule.cpython-32.pyc", "mymodule.cpython-33.pyc", "mymodule.unladen10.pyc" を使うようになりました。同時にこれらの新しいファイルがソースディレクトリを散らかすのを防ぐために、 `pyc' ファイルはパッケージディレクトリの下の "__pycache__" ディレクトリに収集するようになりました。

ファイル名と格納先ディレクトリは別にして、この新方式にはプログラマ目線での目に見える変化が少しあります:


@itemize *

@item 
Imported modules now have a @ref{321,,__cached__} attribute which stores
the name of the actual file that was imported:

@example
>>> import collections
>>> collections.__cached__
'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
@end example

@item 
The tag that is unique to each interpreter is accessible from the @code{imp}
module:

@example
>>> import imp
>>> imp.get_tag()
'cpython-32'
@end example

@item 
Scripts that try to deduce source filename from the imported file now need to
be smarter.  It is no longer sufficient to simply strip the "c" from a ".pyc"
filename.  Instead, use the new functions in the @code{imp} module:

@example
>>> imp.source_from_cache('c:/py32/lib/__pycache__/collections.cpython-32.pyc')
'c:/py32/lib/collections.py'
>>> imp.cache_from_source('c:/py32/lib/collections.py')
'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
@end example

@item 
@ref{b8,,py_compile} と @ref{21,,compileall} モジュールはこの新命名規則とターゲットディレクトリを反映するよう更新されました。 `compileall' のコマンドラインからの起動には新しいオプションが追加されました。 @code{-i} はコンパイルするファイルとディレクトリのリストを指定します。 @code{-b} はバイトコードファイルを `__pycache__' ではなく伝統的な場所に書き出します。

@item 
The @ref{7c,,importlib.abc} module has been updated with new @ref{13ce,,abstract base classes} for loading bytecode files.  The obsolete
ABCs, @code{PyLoader} and
@code{PyPycLoader}, have been deprecated (instructions on how
to stay Python 3.1 compatible are included with the documentation).
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3147

@item PEP 3147@footnote{https://peps.python.org/pep-3147/} - PYC リポジトリーディレクトリー

PEP written by Barry Warsaw.
@end table


@node PEP 3149 ABI バージョンでタグ付けされた so ファイル,PEP 3333 Python Web Server Gateway Interface v1 0 1,PEP 3147 PYC リポジトリーディレクトリ,What's New In Python 3 2
@anchor{whatsnew/3 2 pep-3149-abi-version-tagged-so-files}@anchor{13cf}
@subsection PEP 3149: ABI バージョンでタグ付けされた .so ファイル


PYC レポジトリーディレクトリでは複数バイトコードのキャッシュファイルを共存できます。この PEP は共有オブジェクトについての同じようなメカニズムを実装します。それには共通のディレクトリを使い、個々のバージョンごとの名前の区別をします。

共通ディレクトリは "pyshared" です。また、ファイル名は Python 実装 (例えば CPython、PyPy、Jython など)、メジャー・マイナーバージョン番号やオプショナルなビルドフラグ (例えばデバッグビルドでの "d"、 pymalloc ビルドの "m"、ワイド幅 Unicode の "u") を特定することで区別するように命名されます。任意のパッケージ "foo" について、配布パッケージがインストールされるとこれらファイルは例えばこのような具合でしょう:

@example
/usr/share/pyshared/foo.cpython-32m.so
/usr/share/pyshared/foo.cpython-33md.so
@end example

Python 自身からこのタグに、 @ref{e1,,sysconfig} モジュールにある関数でアクセス出来ます:

@example
>>> import sysconfig
>>> sysconfig.get_config_var('SOABI')       # find the version tag
'cpython-32mu'
>>> sysconfig.get_config_var('EXT_SUFFIX')  # find the full filename extension
'.cpython-32mu.so'
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3149

@item PEP 3149@footnote{https://peps.python.org/pep-3149/} - ABI バージョンでタグ付けされた .so ファイル

PEP written by Barry Warsaw.
@end table


@node PEP 3333 Python Web Server Gateway Interface v1 0 1,その他の言語変更<12>,PEP 3149 ABI バージョンでタグ付けされた so ファイル,What's New In Python 3 2
@anchor{whatsnew/3 2 pep-3333-python-web-server-gateway-interface-v1-0-1}@anchor{13d0}
@subsection PEP 3333: Python Web Server Gateway Interface v1.0.1


この情報 PEP は、 WSGI プロトコルによってどのようにバイト列/テキストの問題が処理されるべきかを明確化しています。HTTP プロトコルそのものはバイト列指向であっても、Python 3 にあってほとんど @ref{169,,str} 型で便利に文字列処理出来るようにすることが挑戦でした。

この PEP では、リクエスト/レスポンスヘッダとメタデータに使われるいわゆる `ネイティブ文字列(native strings)' と、リクエストとレスポンスのボディに使われる `バイト列文字列(byte strings)' を区別します。

The `native strings' are always of type @ref{169,,str} 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
@code{start_response()} function.  They must follow 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} with respect to
encoding. That is, they must either be `ISO-8859-1' characters or use
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} MIME encoding.

WSGI アプリケーションを Python 2 から移植する開発者は、とりわけ以下に注意してください:


@itemize *

@item 
Python 2 でヘッダとしてネイティブ文字列を既に使っているアプリケーションは変更の必要はありません。(---訳注: 原文は「If the app already used strings for headers ...」。native strings としないと意味が通りません。 ---)

@item 
そうではなくアプリケーションが出力ヘッダをエンコードしていたり、入力ヘッダをデコードしていたのであれば、ヘッダは Latin-1 に再エンコードする必要があります。たとえば @code{h.encode('utf-8')} により utf-8 でエンコードされた出力ヘッダは、バイト列からネイティブ文字列に @code{h.encode('utf-8').decode('latin-1')} で変換する必要があります。(---訳注: この原文は h が元々 latin-1 で表現出来る文字セットであることを暗黙で仮定しているようです。---)

@item 
Values yielded by an application or sent using the @code{write()} method
must be byte strings.  The @code{start_response()} function and environ
must use native strings.  The two cannot be mixed.
@end itemize

For server implementers writing CGI-to-WSGI pathways or other CGI-style
protocols, the users must to be able access the environment using native strings
even though the underlying platform may have a different convention.  To bridge
this gap, the @ref{11e,,wsgiref} module has a new function,
@ref{13d1,,wsgiref.handlers.read_environ()} for transcoding CGI variables from
@ref{259,,os.environ} into native strings and returning a new dictionary.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3333

@item PEP 3333@footnote{https://peps.python.org/pep-3333/} - Python Web Server Gateway Interface v1.0.1

PEP written by Phillip Eby.
@end table


@node その他の言語変更<12>,新たなモジュール、改良されたモジュール、非推奨のモジュール,PEP 3333 Python Web Server Gateway Interface v1 0 1,What's New In Python 3 2
@anchor{whatsnew/3 2 other-language-changes}@anchor{13d2}
@subsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
@ref{199,,format()} と @ref{833,,str.format()} のフォーマット文字 `#' が拡張されました。以前から二進、八進、十六進整数に対して順にそれぞれ '0b', '0o', '0x' を冠する出力をしていましたが、これは浮動小数点数、複素数、 Decimal に対しても処理するようになり、これはあとに続く桁がなくても必ず小数点を出力します。

@example
>>> format(20, '#o')
'0o24'
>>> format(12.34, '#5.0f')
'  12.'
@end example

(Suggested by Mark Dickinson and implemented by Eric Smith in bpo-7094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7094}.)

@item 
There is also a new @ref{fd7,,str.format_map()} method that extends the
capabilities of the existing @ref{833,,str.format()} method by accepting arbitrary
@ref{13d3,,mapping} objects.  This new method makes it possible to use string
formatting with any of Python's many dictionary-like objects such as
@ref{13d4,,defaultdict}, @ref{119d,,Shelf},
@ref{4de,,ConfigParser}, or @ref{35,,dbm}.  It is also useful with
custom @ref{183,,dict} subclasses that normalize keys before look-up or that
supply a @ref{13d5,,__missing__()} method for unknown keys:

@example
>>> import shelve
>>> d = shelve.open('tmp.shl')
>>> 'The @{project_name@} status is @{status@} as of @{date@}'.format_map(d)
'The testing project status is green as of February 15, 2011'

>>> class LowerCasedDict(dict):
...     def __getitem__(self, key):
...         return dict.__getitem__(self, key.lower())
...
>>> lcd = LowerCasedDict(part='widgets', quantity=10)
>>> 'There are @{QUANTITY@} @{Part@} in stock'.format_map(lcd)
'There are 10 widgets in stock'

>>> class PlaceholderDict(dict):
...     def __missing__(self, key):
...         return '<@{@}>'.format(key)
...
>>> 'Hello @{name@}, welcome to @{location@}'.format_map(PlaceholderDict())
'Hello <name>, welcome to <location>'
@end example
@end itemize

@quotation

(Suggested by Raymond Hettinger and implemented by Eric Smith in
bpo-6081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6081}.)
@end quotation


@itemize *

@item 
The interpreter can now be started with a quiet option, @code{-q}, to prevent
the copyright and version information from being displayed in the interactive
mode.  The option can be introspected using the @ref{89c,,sys.flags} attribute:

@example
$ python -q
>>> sys.flags
sys.flags(debug=0, division_warning=0, inspect=0, interactive=0,
optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,
ignore_environment=0, verbose=0, bytes_warning=0, quiet=1)
@end example

(Contributed by Marcin Wojdyr in bpo-1772833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1772833}).

@item 
The @ref{6f9,,hasattr()} function works by calling @ref{dca,,getattr()} and detecting
whether an exception is raised.  This technique allows it to detect methods
created dynamically by @ref{6fa,,__getattr__()} or @ref{dcb,,__getattribute__()} 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 @ref{5f0,,AttributeError} and let other
exceptions pass through:

@example
>>> class A:
...     @@property
...     def f(self):
...         return 1 // 0
...
>>> a = A()
>>> hasattr(a, 'f')
Traceback (most recent call last):
  ...
ZeroDivisionError: integer division or modulo by zero
@end example

(Discovered by Yury Selivanov and fixed by Benjamin Peterson; bpo-9666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9666}.)

@item 
浮動小数点数または複素数に対する @ref{169,,str()} は @ref{1c1,,repr()} 表現と同じになりました。以前は @ref{169,,str()} 形式のほうが短い表現になっていましたがこれは単に困惑させるものでした。 @ref{1c1,,repr()} がデフォルトで可能ななかでの一番短い表現をするようになったので、 @ref{169,,str()} があえて短い表現を取ろうとする必要性がなくなりました。

@example
>>> import math
>>> repr(math.pi)
'3.141592653589793'
>>> str(math.pi)
'3.141592653589793'
@end example

(Proposed and implemented by Mark Dickinson; bpo-9337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9337}.)

@item 
@ref{165,,memoryview} objects now have a @ref{13d6,,release()} method
and they also now support the context management protocol.  This allows timely
release of any resources that were acquired when requesting a buffer from the
original object.

@example
>>> with memoryview(b'abcdefgh') as v:
...     print(v.tolist())
[97, 98, 99, 100, 101, 102, 103, 104]
@end example

(Added by Antoine Pitrou; bpo-9757@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9757}.)

@item 
以前は、入れ子になったブロック内である名前が自由変数として現れる場合、局所名前空間からその名前を削除することは不正でした。

@example
def outer(x):
    def inner():
        return x
    inner()
    del x
@end example

これは可能になりました。
@ref{1ab,,except} 節の対象が消去されることを思い出せば、
Python 2.6 では動き、Python 3.1 では @ref{18e,,SyntaxError} を送出するこのコードは再び動きます:

@example
def f():
    def print_error():
        print(e)
    try:
        something
    except Exception as e:
        print_error()
        # implicit "del e" here
@end example

(bpo-4617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4617} を参照してください。)

@item 
@ref{13d7,,Struct sequence types} are now subclasses of tuple.
This means that C structures like those returned by @ref{26d,,os.stat()},
@ref{13d8,,time.gmtime()}, and @ref{8af,,sys.version_info} now work like a
@ref{85e,,named tuple} and now work with functions and methods that
expect a tuple as an argument.  This is a big step forward in making the C
structures as flexible as their pure Python counterparts:

@example
>>> import sys
>>> isinstance(sys.version_info, tuple)
True
>>> 'Version %d.%d.%d %s(%d)' % sys.version_info
'Version 3.2.0 final(0)'
@end example

(Suggested by Arfrever Frehtes Taifersar Arahesis and implemented
by Benjamin Peterson in bpo-8413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8413}.)

@item 
警告の制御を以前より簡単に出来るようになりました。環境変数 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} を使えば、コマンドラインで @code{-W} を使うより簡単です:

@example
$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'
@end example

(Suggested by Barry Warsaw and implemented by Philip Jenvey in bpo-7301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7301}.)

@item 
新たな警告カテゴリ @ref{54c,,ResourceWarning} が追加されました。これはリソース消費やクリーンアップについての潜在的な問題が検出されると発行されます。これは通常のリリースビルドではデフォルトでは黙殺しますが、 @ref{118,,warnings} モジュールで意味付けを変更 (訳注: @ref{1b1,,警告フィルタ} 参照) するかコマンドラインオプションで有効に出来ます。

A @ref{54c,,ResourceWarning} is issued at interpreter shutdown if the
@ref{13d9,,gc.garbage} list isn't empty, and if @ref{13da,,gc.DEBUG_UNCOLLECTABLE} is
set, all uncollectable objects are printed.  This is meant to make the
programmer aware that their code contains object finalization issues.

@ref{54c,,ResourceWarning} は明示的にクローズされなかった @ref{13db,,file object} が破壊される際にも発行されます。そのようなオブジェクトのデアロケータは背後の OS リソース (大抵はファイル記述子) を閉じることを保障はしますが、オブジェクトのデアロケートの遅れは様々な問題を産み落とし、とりわけ Windows でこれは顕著です。コマンドラインからこの警告を有効にするには例えばこのようにします:

@example
$ python -q -Wdefault
>>> f = open("foo", "wb")
>>> del f
__main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>
@end example

(Added by Antoine Pitrou and Georg Brandl in bpo-10093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10093} and bpo-477863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=477863}.)

@item 
@ref{b3d,,range} objects now support `index' and `count' methods. This is part
of an effort to make more objects fully implement the
@ref{13dc,,collections.Sequence} @ref{13ce,,abstract base class}.  As a result, the
language will have a more uniform API.  In addition, @ref{b3d,,range} objects
now support slicing and negative indices, even with values larger than
@ref{13dd,,sys.maxsize}.  This makes `range' more interoperable with lists:

@example
>>> range(0, 100, 2).count(10)
1
>>> range(0, 100, 2).index(10)
5
>>> range(0, 100, 2)[5]
10
>>> range(0, 100, 2)[0:5]
range(0, 10, 2)
@end example

(Contributed by Daniel Stutzbach in bpo-9213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9213}, by Alexander Belopolsky
in bpo-2690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2690}, and by Nick Coghlan in bpo-10889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10889}.)

@item 
Py2.x から @ref{13de,,callable()} 組み込み関数が復活しました。
この関数は @code{isinstance(x, collections.Callable)} のように式内で @ref{13ce,,抽象基底クラス} を使用するよりも、簡潔で可読性の高い手段を提供します:

@example
>>> callable(max)
True
>>> callable(20)
False
@end example

(bpo-10518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10518} を参照してください。)

@item 
Python のインポート機構が、パス名に非 ASCII 文字を含むディレクトリにインストールされたモジュールをロードできるようになりました。これはユーザ名に非 ASCII 文字を含むユーザにとっての、ホームディレクトリにまつわる腹立たしい問題を解決しました。
@end itemize

@quotation

(Required extensive work by Victor Stinner in bpo-9425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9425}.)
@end quotation

@node 新たなモジュール、改良されたモジュール、非推奨のモジュール,マルチスレッディング,その他の言語変更<12>,What's New In Python 3 2
@anchor{whatsnew/3 2 new-improved-and-deprecated-modules}@anchor{13df}
@subsection 新たなモジュール、改良されたモジュール、非推奨のモジュール


Python の標準ライブラリは保守の努力と質の向上を大きく受けています。

The biggest news for Python 3.2 is that the @ref{3f,,email} package, @ref{8f,,mailbox}
module, and @code{nntplib} modules now work correctly with the bytes/text model
in Python 3.  For the first time, there is correct handling of messages with
mixed encodings.

標準ライブラリ全体を通じて、エンコーディング問題とテキスト対バイト列問題に関してより注意深い配慮がなされました。とりわけオペレーティングシステムとの連携では、Windows の MBCS エンコーディングやロケールに配慮するエンコーディング、あるいは UTF-8 を使う非 ASCII のデータ交換はより良く行えるようになりました。

もうひとつの目覚しい勝利は、 `SSL' 接続とセキュリティ証明書サポートの大幅な改善です。

さらに、以前よりももっと多くのクラスが今では @ref{1e1,,context manager} を実装し、 @ref{186,,with} 文を使った便利で信頼出来るリソースのクリーンアップをサポートしています。

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

@end menu

@node email<7>,elementtree,,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 email}@anchor{13e0}
@subsubsection email


The usability of the @ref{3f,,email} package in Python 3 has been mostly fixed by
the extensive efforts of R. David Murray.  The problem was that emails are
typically read and stored in the form of @ref{192,,bytes} rather than @ref{169,,str}
text, and they may contain multiple encodings within a single email.  So, the
email package had to be extended to parse and generate email messages in bytes
format.


@itemize *

@item 
新規関数 @ref{13e1,,message_from_bytes()}, @ref{13e2,,message_from_binary_file()} 、それに新規クラス @ref{13e3,,BytesFeedParser}, @ref{13e4,,BytesParser} が、バイナリメッセージデータをパースしてモデルオブジェクトに読み込みます。

@item 
bytes の入力をモデルに与えると @ref{13e5,,get_payload()} は、デフォルトでは `8 ビット' の @code{Content-Transfer-Encoding} MIME ヘッダをもったメッセージボディをそのヘッダで指定された文字セットを使い、デコードして結果文字列を返します。

@item 
bytes の入力をモデルに与えると @ref{13e6,,Generator} は、 `8 ビット' の @code{Content-Transfer-Encoding} MIME ヘッダをもったメッセージボディを、 `7 ビット' の @code{Content-Transfer-Encoding} を持つものに変換します。

エンコードされていない非 ASCII バイト列を持つヘッダは `未知の 8 ビット' 文字セットを使った 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} エンコードであると見做されます。

@item 
新規クラス @ref{13e7,,BytesGenerator} は出力としてバイト列を生成します。これはモデルを構築するのに使った入力にあった非 ASCII データをそのままにし、 `8ビットの' @code{Content-Transfer-Encoding} を持つメッセージボディに含めます。

@item 
@ref{cf,,smtplib} モジュールの @ref{b27,,SMTP} クラスが @ref{1059,,sendmail()} メソッドの `msg' 引数としてバイト列文字列を受け付けるようになりました。新しく追加されたメソッド @ref{105a,,send_message()} は `msg' 引数に @ref{581,,Message} オブジェクトを受け付けます。このメソッドは `msg' にあたえたオブジェクトから `from_addr' アドレスと `to_addrs' アドレスを直接取ることが出来ます。
@end itemize

(Proposed and implemented by R. David Murray, bpo-4661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4661} and bpo-10321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10321}.)

@node elementtree,functools<8>,email<7>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 elementtree}@anchor{13e8}
@subsubsection elementtree


The @ref{12b,,xml.etree.ElementTree} package and its @code{xml.etree.cElementTree}
counterpart have been updated to version 1.3.

有用な関数とメソッドが幾つか新たに追加されました:


@itemize *

@item 
@ref{13e9,,xml.etree.ElementTree.fromstringlist()}、断片のシーケンスから XML 文書を組み立てます

@item 
@ref{13ea,,xml.etree.ElementTree.register_namespace()}、大域名前空間接頭辞を登録するのに使用します

@item 
@ref{11f8,,xml.etree.ElementTree.tostringlist()}、全サブリストを含めた文字列表記に使用します

@item 
@ref{13eb,,xml.etree.ElementTree.Element.extend()}、ゼロ以上の要素のシークエンスを追加するのに使用します

@item 
@ref{13ec,,xml.etree.ElementTree.Element.iterfind()}、要素と子要素を検索します

@item 
@ref{13ed,,xml.etree.ElementTree.Element.itertext()}、要素と子要素を走るテキストイテレータを作成します

@item 
@ref{13ee,,xml.etree.ElementTree.TreeBuilder.end()}、現在の要素を閉じます

@item 
@ref{c8e,,xml.etree.ElementTree.TreeBuilder.doctype()}、doctype 定義を処理します
@end itemize

2つのメソッドが非推奨になりました:


@itemize *

@item 
@code{xml.etree.ElementTree.getchildren()} use @code{list(elem)} instead.

@item 
@code{xml.etree.ElementTree.getiterator()} use @code{Element.iter} instead.
@end itemize

For details of the update, see Introducing ElementTree@footnote{https://web.archive.org/web/20200703234532/http://effbot.org/zone/elementtree-13-intro.htm}
on Fredrik Lundh's website.

(Contributed by Florent Xicluna and Fredrik Lundh, bpo-6472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6472}.)

@node functools<8>,itertools<8>,elementtree,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 functools}@anchor{13ef}
@subsubsection functools



@itemize *

@item 
@ref{63,,functools} モジュールに関数呼び出しをキャッシュするデコレータが追加されています。 @ref{be2,,functools.lru_cache()} を使うと、同じ結果が期待される場合の外部リソースへの問い合わせ繰り返しを防ぐことができます。

たとえばデータベース問い合わせ関数をキャッシュするデコレータで修飾すれば、人気の検索のデータベースアクセスを省けます:

@example
>>> import functools
>>> @@functools.lru_cache(maxsize=300)
... def get_phone_number(name):
...     c = conn.cursor()
...     c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
...     return c.fetchone()[0]
@end example

@example
>>> for name in user_requests:
...     get_phone_number(name)        # cached lookup
@end example

効果的なキャッシュサイズを選択する助けとなるよう、ラップされた関数はキャッシュの統計を追跡する道具にもなっています:

@example
>>> get_phone_number.cache_info()
CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)
@end example

テーブル phonelist が更新されたのであれば、内容が古くなったキャッシュをクリアできます:

@example
>>> get_phone_number.cache_clear()
@end example

(Contributed by Raymond Hettinger and incorporating design ideas from Jim
Baker, Miki Tebeka, and Nick Coghlan; see recipe 498245@footnote{https://code.activestate.com/recipes/498245-lru-and-lfu-cache-decorators/}, recipe 577479@footnote{https://code.activestate.com/recipes/577479-simple-caching-decorator/}, bpo-10586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10586}, and
bpo-10593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10593}.)

@item 
The @ref{115f,,functools.wraps()} decorator now adds a @code{__wrapped__} attribute
pointing to the original callable function.  This allows wrapped functions to
be introspected.  It also copies @ref{13f0,,__annotations__} if
defined.  And now it also gracefully skips over missing attributes such as
@ref{13f1,,__doc__} which
might not be defined for the wrapped callable.

上の例の場合、キャッシュは元の関数を復元することで削除できます:

@example
>>> get_phone_number = get_phone_number.__wrapped__    # uncached function
@end example

(By Nick Coghlan and Terrence Cole; bpo-9567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9567}, bpo-3445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3445}, and
bpo-8814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8814}.)

@item 
拡張比較 (rich comparison) メソッドを持つクラスを書く助けとなるよう、新たなデコレータ @ref{1144,,functools.total_ordering()} が追加されました。これは既存の等式と不等式メソッドを使って残りのメソッドを埋めます。

例えば `__eq__' と `__lt__' を与えると、 @ref{1144,,total_ordering()} は `__le__', `__gt__', `__ge__' を補います:

@example
@@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))

    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
@end example

`total_ordering' デコレータが残りの比較メソッドを自動的に補います。

(Contributed by Raymond Hettinger.)

@item 
Python 2 からのプログラムの移植のために使える、 @ref{13f2,,functools.cmp_to_key()} 関数が追加されました。これは旧式の比較関数をモダンな @ref{1006,,key function} に変換します:

@example
>>> # locale-aware sort order
>>> sorted(iterable, key=cmp_to_key(locale.strcoll))
@end example

ソートの例と簡単なチュートリアルは @ref{13f3,,ソートのテクニック} を参照して下さい。

(Contributed by Raymond Hettinger.)
@end itemize

@node itertools<8>,collections<8>,functools<8>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 itertools}@anchor{13f4}
@subsubsection itertools



@itemize *

@item 
@ref{85,,itertools} モジュールに、 APL@footnote{https://ja.wikipedia.org/wiki/APL} の `scan' 演算子や NumPy@footnote{http://www.numpy.org/} の `accumulate' 関数をモデルにした @ref{bf0,,accumulate()} が新しく追加されました:

@example
>>> from itertools import accumulate
>>> list(accumulate([8, 2, 50]))
[8, 10, 60]
@end example

@example
>>> prob_dist = [0.1, 0.4, 0.2, 0.3]
>>> list(accumulate(prob_dist))      # cumulative probability distribution
[0.1, 0.5, 0.7, 1.0]
@end example

@ref{bf0,,accumulate()} の使用例が @ref{13f5,,examples for the random module} にあります。

(Contributed by Raymond Hettinger and incorporating design suggestions
from Mark Dickinson.)
@end itemize

@node collections<8>,threading<10>,itertools<8>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 collections}@anchor{13f6}
@subsubsection collections



@itemize *

@item 
@ref{12a3,,collections.Counter} クラスに 2 つの形式のインプレイス減算が追加されました。 saturating subtraction@footnote{https://en.wikipedia.org/wiki/Saturation_arithmetic} (訳注: 結果を [min, max] に収める演算) を行う既存の `-=' 演算子に加え、新しく追加された @ref{13f7,,subtract()} メソッドは通常の減算を行います。前者は要素数に正しか持たない 多重集合@footnote{https://ja.wikipedia.org/wiki/%E5%A4%9A%E9%87%8D%E9%9B%86%E5%90%88} に用いるのに適していて、後者は要素数に負を許容するユースケースにより適しています。

@example
>>> from collections import Counter
>>> tally = Counter(dogs=5, cats=3)
>>> tally -= Counter(dogs=2, cats=8)    # saturating subtraction
>>> tally
Counter(@{'dogs': 3@})
@end example

@example
>>> tally = Counter(dogs=5, cats=3)
>>> tally.subtract(dogs=2, cats=8)      # regular subtraction
>>> tally
Counter(@{'dogs': 3, 'cats': -5@})
@end example

(Contributed by Raymond Hettinger.)

@item 
@ref{7f3,,collections.OrderedDict} クラスに @ref{13f8,,move_to_end()} メソッド (訳注: 「end」は「端」) が追加されました。これは既存のキーを受け取って、順序付けされたシーケンスの最初の位置か最後の位置に移動します。

デフォルトでは要素は最後の位置に移動します。これはエントリを @code{od[k] = od.pop(k)} で入れ替えるのと同じです。

高速な端への移動操作はエントリの並べなおしに便利です。例えば、最も最近使った順序でエントリを年齢付けすることによってアクセス順を追跡するのに、順序付けされた辞書を使えます。

@example
>>> from collections import OrderedDict
>>> d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e'])
>>> list(d)
['a', 'b', 'X', 'd', 'e']
>>> d.move_to_end('X')
>>> list(d)
['a', 'b', 'd', 'e', 'X']
@end example

(Contributed by Raymond Hettinger.)

@item 
@ref{7f4,,collections.deque} クラスに 2 つのメソッド @ref{13f9,,count()} と @ref{13fa,,reverse()} が追加されました。これでさらに @ref{24d,,list} との置換可能性が増しました:

@example
>>> from collections import deque
>>> d = deque('simsalabim')
>>> d.count('s')
2
>>> d.reverse()
>>> d
deque(['m', 'i', 'b', 'a', 'l', 'a', 's', 'm', 'i', 's'])
@end example

(Contributed by Raymond Hettinger.)
@end itemize

@node threading<10>,datetime と time,collections<8>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 threading}@anchor{13fb}
@subsubsection threading


@ref{f3,,threading} モジュールに新たに同期クラス @ref{13fc,,Barrier} が追加されました。これは多重のスレッドに、それら全てが共通のバリアポイントに到達するまで待たせます。バリアは、複数の事前条件を持ったタスクを、その前任タスクの全てが完了するまで走らせたくない場合に有用です。

バリアは任意の数のスレッドに対して使えます。これは Rendezvous@footnote{https://en.wikipedia.org/wiki/Synchronous_rendezvous} を一般化したもので、それは 2 つのスレッドに対してのみに定義されていました。

二段階の周期バリアとしての実装なので、 @ref{13fc,,Barrier} オブジェクトはループ内での利用に適しています。分けられた `filling (満杯にする)' 段階と `draining (排出する)' 段階は、スレッドのどれか一つが元に戻ってバリアに再び入る前に、全てのスレッドが解放 (排出) されることを保障します。バリアはそれぞれの周期のあとに完全にリセットされます。

バリアは例えばこのように使います:

@example
from threading import Barrier, Thread

def get_votes(site):
    ballots = conduct_election(site)
    all_polls_closed.wait()        # do not count until all polls are closed
    totals = summarize(ballots)
    publish(site, totals)

all_polls_closed = Barrier(len(sites))
for site in sites:
    Thread(target=get_votes, args=(site,)).start()
@end example

この例ではバリアは、全ての投票所が閉じるまではどの投票サイトでも得票を数えないルールを強制しています。バリアを使ったソリューションが @ref{13fd,,threading.Thread.join()} でのそれといかに似ているか気付くと思います。ですがバリアポイントを通過した後に、スレッドは生き続けて (投票を集計する (summarizing ballots) という) 仕事を続けます。

いずれかの前任タスクがハングしたり遅延したりしうるのであれば、バリアを `timeout' 付きで作ることができます。全ての前任タスクがバリアポイントに到達する前にタイムアウトの期間が経過すると、全ての待機スレッドは解放されて @ref{13fe,,BrokenBarrierError} 例外が発生します:

@example
def get_votes(site):
    ballots = conduct_election(site)
    try:
        all_polls_closed.wait(timeout=midnight - time.now())
    except BrokenBarrierError:
        lockbox = seal_ballots(ballots)
        queue.put(lockbox)
    else:
        totals = summarize(ballots)
        publish(site, totals)
@end example

この例ではバリアは、もっと手堅いルールを強制しています。選挙サイトのどれかが午前零時前に終了しなかった場合バリアがタイムアウトし、投票用紙は密封されて後の処理のためのキューに預けられます。

See Barrier Synchronization Patterns@footnote{https://osl.cs.illinois.edu/media/papers/karmani-2009-barrier_synchronization_pattern.pdf}
for more examples of how barriers can be used in parallel computing.  Also, there is
a simple but thorough explanation of barriers in The Little Book of Semaphores@footnote{https://greenteapress.com/semaphores/LittleBookOfSemaphores.pdf}, `section 3.6'.

(Contributed by Kristján Valur Jónsson with an API review by Jeffrey Yasskin in
bpo-8777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8777}.)

@node datetime と time,math<11>,threading<10>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 datetime-and-time}@anchor{13ff}
@subsubsection datetime と time



@itemize *

@item 
@ref{34,,datetime} モジュールに新たに @ref{12d5,,timezone} 型が追加されています。これは @ref{7f6,,tzinfo} インターフェイスを実装し、UTC からの固定オフセットとタイムゾーン名を返します。これによりタイムゾーンを意識する (timezone-aware な) datetime オブジェクトを容易に作れます:

@example
>>> from datetime import datetime, timezone

>>> datetime.now(timezone.utc)
datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone.utc)

>>> datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)
@end example

@item 
さらに、 @ref{bc3,,timedelta} オブジェクトは今では @ref{196,,float} を掛けることができ、 @ref{196,,float} や @ref{19b,,int} で割ることができます。また、 @ref{bc3,,timedelta} オブジェクトは別の @ref{bc3,,timedelta} で割ることが出来ます。

@item 
@ref{e8f,,datetime.date.strftime()} メソッドにはもう 1900 年以降という制限はありません。新しくサポートされる年の範囲は 1000 以上 9999 以下です。

@item 
Whenever a two-digit year is used in a time tuple, the interpretation has been
governed by @code{time.accept2dyear}.  The default is @code{True} which means that
for a two-digit year, the century is guessed according to the POSIX rules
governing the @code{%y} strptime format.

Starting with Py3.2, use of the century guessing heuristic will emit a
@ref{1a3,,DeprecationWarning}.  Instead, it is recommended that
@code{time.accept2dyear} be set to @code{False} so that large date ranges
can be used without guesswork:

@example
>>> import time, warnings
>>> warnings.resetwarnings()      # remove the default warning filters

>>> time.accept2dyear = True      # guess whether 11 means 11 or 2011
>>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
Warning (from warnings module):
  ...
DeprecationWarning: Century info guessed for a 2-digit year.
'Fri Jan  1 12:34:56 2011'

>>> time.accept2dyear = False     # use the full range of allowable dates
>>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
'Fri Jan  1 12:34:56 11'
@end example

Several functions now have significantly expanded date ranges.  When
@code{time.accept2dyear} is false, the @ref{1400,,time.asctime()} function will
accept any year that fits in a C int, while the @ref{1401,,time.mktime()} and
@ref{1402,,time.strftime()} functions will accept the full range supported by the
corresponding operating system functions.
@end itemize

(Contributed by Alexander Belopolsky and Victor Stinner in bpo-1289118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1289118},
bpo-5094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5094}, bpo-6641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6641}, bpo-2706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2706}, bpo-1777412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1777412}, bpo-8013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8013},
and bpo-10827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10827}.)

@c XXX https://bugs.python.org/issue?%40search_text=datetime&%40sort=-activity

@node math<11>,abc<3>,datetime と time,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 math}@anchor{1403}
@subsubsection math


@ref{92,,math} モジュールがアップデートされ、C99 標準に触発されて6つの新たな関数が追加されました。

@ref{1404,,isfinite()} 関数は特殊値を確実に、かつ高速に検出する方法を提供します。通常の数には @code{True} を、`Nan' や `Infinity' には @code{False} を返します:

@example
>>> from math import isfinite
>>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))]
[True, True, False, False]
@end example

@ref{1405,,expm1()} 関数は小さな `x' に対しても精度を失うこと (訳注: 桁落ち) なく @code{e**x-1} を計算します。
通常、桁落ちは非常に近い数の引き算で起こります。

@example
>>> from math import expm1
>>> expm1(0.013671875)   # more accurate way to compute e**x-1 for a small x
0.013765762467652909
@end example

@ref{dd3,,erf()} 関数は確率積分、すなわち 誤差関数@footnote{https://ja.wikipedia.org/wiki/%E8%AA%A4%E5%B7%AE%E9%96%A2%E6%95%B0} を返します。 相補誤差関数 @ref{dd4,,erfc()} は @code{1 - erf(x)} です:

@example
>>> from math import erf, erfc, sqrt
>>> erf(1.0/sqrt(2.0))   # portion of normal distribution within 1 standard deviation
0.682689492137086
>>> erfc(1.0/sqrt(2.0))  # portion of normal distribution outside 1 standard deviation
0.31731050786291404
>>> erf(1.0/sqrt(2.0)) + erfc(1.0/sqrt(2.0))
1.0
@end example

@ref{1406,,gamma()} 関数は階乗を連続的に拡張したものです。詳細は ガンマ関数@footnote{https://ja.wikipedia.org/wiki/%E3%82%AC%E3%83%B3%E3%83%9E%E9%96%A2%E6%95%B0}  を参照してください。ガンマ関数は階乗に関係しているため、小さな  `x' でも大きくなります。そのため、ガンマ関数の自然対数を計算する @ref{1407,,lgamma()} 関数があります。

@example
>>> from math import gamma, lgamma
>>> gamma(7.0)           # six factorial
720.0
>>> lgamma(801.0)        # log(800 factorial)
4551.950730698041
@end example

(Contributed by Mark Dickinson.)

@node abc<3>,io<9>,math<11>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 abc}@anchor{1408}
@subsubsection abc


@ref{4,,abc} モジュールは @ref{1298,,abstractclassmethod()} と @ref{1299,,abstractstaticmethod()} をサポートしました。

これらのツールによって特定の @ref{48e,,classmethod()} や @ref{453,,staticmethod()} を実装する必要のある @ref{13ce,,抽象基底クラス} を定義することが出来ます。

@example
class Temperature(metaclass=abc.ABCMeta):
    @@abc.abstractclassmethod
    def from_fahrenheit(cls, t):
        ...
    @@abc.abstractclassmethod
    def from_celsius(cls, t):
        ...
@end example

(Patch submitted by Daniel Urban; bpo-5867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5867}.)

@node io<9>,reprlib,abc<3>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 io}@anchor{1409}
@subsubsection io


@ref{10a4,,io.BytesIO} に @ref{165,,memoryview()} と同様の機能を提供する新たなメソッド @ref{140a,,getbuffer()} が追加されました。
このメソッドはコピーせずにデータの編集可能なビューを作成します。
バッファのランダムアクセスとスライス記法のサポートはインプレースな編集に適しています:

@example
>>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11

>>> def change_location(buffer, record_number, location):
...     start = record_number * REC_LEN + LOC_START
...     buffer[start: start+LOC_LEN] = location

>>> import io

>>> byte_stream = io.BytesIO(
...     b'G3805  storeroom  Main chassis    '
...     b'X7899  shipping   Reserve cog     '
...     b'L6988  receiving  Primary sprocket'
... )
>>> buffer = byte_stream.getbuffer()
>>> change_location(buffer, 1, b'warehouse  ')
>>> change_location(buffer, 0, b'showroom   ')
>>> print(byte_stream.getvalue())
b'G3805  showroom   Main chassis    '
b'X7899  warehouse  Reserve cog     '
b'L6988  receiving  Primary sprocket'
@end example

(Contributed by Antoine Pitrou in bpo-5506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5506}.)

@node reprlib,logging<8>,io<9>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 reprlib}@anchor{140b}
@subsubsection reprlib


When writing a @ref{82f,,__repr__()} method for a custom container, it is easy to
forget to handle the case where a member refers back to the container itself.
Python's builtin objects such as @ref{24d,,list} and @ref{184,,set} handle
self-reference by displaying "..." in the recursive part of the representation
string.

To help write such @ref{82f,,__repr__()} methods, the @ref{c0,,reprlib} module has a new
decorator, @ref{140c,,recursive_repr()}, for detecting recursive calls to
@code{__repr__()} and substituting a placeholder string instead:

@example
>>> class MyList(list):
...     @@recursive_repr()
...     def __repr__(self):
...         return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
@end example

(Contributed by Raymond Hettinger in bpo-9826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9826} and bpo-9840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9840}.)

@node logging<8>,csv<4>,reprlib,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 logging}@anchor{140d}
@subsubsection logging


上記の辞書ベースの設定に加え、@ref{8b,,logging} パッケージには他にも多くの改良があります。

ロギングのドキュメントは @ref{140e,,基本チュートリアル}  、 @ref{140f,,上級チュートリアル}  、 @ref{1410,,クックブック} により増強されてきました。ロギングについて学習するにはこれらのドキュメントが最速の方法です。

セットアップ関数 @ref{bf3,,logging.basicConfig()} に `style' 引数が追加され、これにより異なる 3 つのタイプの文字列書式化がサポートされます。デフォルトは伝統的な % 書式化を使う "%" で、 @ref{833,,str.format()} スタイルの "@{" 、 @ref{897,,string.Template} で提供されるシェルスタイルの "$" をセット出来ます。以下の 3 つの設定は等価です:

@example
>>> from logging import basicConfig
>>> basicConfig(style='%', format="%(name)s -> %(levelname)s: %(message)s")
>>> basicConfig(style='@{', format="@{name@} -> @{levelname@} @{message@}")
>>> basicConfig(style='$', format="$name -> $levelname: $message")
@end example

If no configuration is set-up before a logging event occurs, there is now a
default configuration using a @ref{1411,,StreamHandler} directed to
@ref{b33,,sys.stderr} for events of @code{WARNING} level or higher.  Formerly, an
event occurring before a configuration was set-up would either raise an
exception or silently drop the event depending on the value of
@ref{1412,,logging.raiseExceptions}.  The new default handler is stored in
@ref{1413,,logging.lastResort}.

フィルタの利用は単純になりました。 @ref{1414,,Filter} オブジェクトを作る代わりに、 @code{True} か @code{False} を返す任意の Python 呼び出し可能オブジェクトを述語 (predicate) として利用出来ます。

ほかにも柔軟性を高め、設定を単純化する数多くの改善がありました。Python 3.2 での全ての変更についてはモジュールのドキュメントを参照してください。

@node csv<4>,contextlib<8>,logging<8>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 csv}@anchor{1415}
@subsubsection csv


@ref{2d,,csv} モジュールは新たな方言 @ref{1416,,unix_dialect} をサポートしました。
この方言は全フィールドをクォートし、行末を伝統的な Unix 形式の @code{'\n'} にします。
登録された方言名は @code{unix} です。

@ref{1417,,csv.DictWriter} に新たなメソッド @ref{1418,,writeheader()} が追加されました。
最初の列をドキュメントのフィールド名に書き出すのに使用します:

@example
>>> import csv, sys
>>> w = csv.DictWriter(sys.stdout, ['name', 'dept'], dialect='unix')
>>> w.writeheader()
"name","dept"
>>> w.writerows([
...     @{'name': 'tom', 'dept': 'accounting'@},
...     @{'name': 'susan', 'dept': 'Salesl'@}])
"tom","accounting"
"susan","sales"
@end example

(New dialect suggested by Jay Talbot in bpo-5975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5975}, and the new method
suggested by Ed Abraham in bpo-1537721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1537721}.)

@node contextlib<8>,decimal と fractions,csv<4>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 contextlib}@anchor{1419}
@subsubsection contextlib


新しく追加され、そして少しばかりハートを揺さぶるツール @ref{141a,,ContextDecorator} は、関数デコレータとしての任務も果たす @ref{1e1,,context manager} を作るのに役立つものです。

利便性のためにこの新機能は @ref{141b,,contextmanager()} で使われているので、両方の役割をサポートするのにことさら労力は要しません。

基本的なアイディアは、コンテキストマネージャも関数デコレータも、ともに事前アクション・事後アクションラッパーとして使うことが出来るというものです。コンテキストマネージャは @ref{186,,with} 文を使ったステートメント (文) のグループを包みますし、関数デコレータは関数に取り囲まれたステートメントのグループを包みます。そうです、どちらかの役割で使える事前アクションあるいは事後アクションラッパーを書く必要性は、しばしば起こることです。

たとえば関数やステートメントのグループをロガーで包んで、開始時刻と終了時刻を追跡できるようにするとしばしば便利です。このタスクをこなすために関数デコレータとコンテキストマネージャの両方を書く代わりに、 @ref{141b,,contextmanager()} が単一の定義に両方の能力をもたらしてくれます:

@example
from contextlib import contextmanager
import logging

logging.basicConfig(level=logging.INFO)

@@contextmanager
def track_entry_and_exit(name):
    logging.info('Entering: %s', name)
    yield
    logging.info('Exiting: %s', name)
@end example

ContextDecorator が使われる前の 3.1 までの @ref{141b,,contextmanager()} では、これはコンテキストマネージャとして使えるだけでした:

@example
with track_entry_and_exit('widget loader'):
    print('Some time consuming activity goes here')
    load_widget()
@end example

今ではこれはデコレータとしても使えます:

@example
@@track_entry_and_exit('widget loader')
def activity():
    print('Some time consuming activity goes here')
    load_widget()
@end example

一つの場所に二重の責務を持たせることには普通ある種の制約を持ち込みます。コンテキストマネージャには普通は @ref{186,,with} 文で使える値を返せる柔軟性を持ちますが、関数デコレータにはそれに匹敵するものはありません。

上の例の場合は、`track_entry_and_exit' コンテキストマネージャが、取り囲まれたステートメント本体で使えるロギングのインスタンスを返す綺麗な方法はありません。

(Contributed by Michael Foord in bpo-9110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9110}.)

@node decimal と fractions,ftp,contextlib<8>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 decimal-and-fractions}@anchor{141c}
@subsubsection decimal と fractions


Mark Dickinson は、異なる数値データの型が実際の値が等しい場合は常に同じハッシュ値を持つことを保証する、エレガントで効率的なスキームを作り上げました (bpo-8188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8188}):

@example
assert hash(Fraction(3, 2)) == hash(1.5) == \
       hash(Decimal("1.5")) == hash(complex(1.5, 0))
@end example

Some of the hashing details are exposed through a new attribute,
@ref{1201,,sys.hash_info}, 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:

@example
>>> sys.hash_info
sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)
@end example

An early decision to limit the interoperability of various numeric types has
been relaxed.  It is still unsupported (and ill-advised) to have implicit
mixing in arithmetic expressions such as @code{Decimal('1.1') + float('1.1')}
because the latter loses information in the process of constructing the binary
float.  However, since existing floating-point value can be converted losslessly
to either a decimal or rational representation, it makes sense to add them to
the constructor and to support mixed-type comparisons.


@itemize *

@item 
@ref{1fe,,decimal.Decimal} コンストラクタに @ref{196,,float} オブジェクトを直接渡せるようになりました。これにより @ref{141d,,from_float()} メソッドを使う必要はなくなりました (bpo-8257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8257})。

@item 
型違いの比較はいまでは完全にサポートされたので、 @ref{1fe,,Decimal} オブジェクトを直接 @ref{196,,float} や @ref{213,,fractions.Fraction} と比較出来ます (bpo-2531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2531} and bpo-8188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8188})。
@end itemize

Similar changes were made to @ref{213,,fractions.Fraction} so that the
@ref{141e,,from_float()} and @ref{141f,,from_decimal()}
methods are no longer needed (bpo-8294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8294}):

@example
>>> from decimal import Decimal
>>> from fractions import Fraction
>>> Decimal(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
@end example

Another useful change for the @ref{3a,,decimal} module is that the
@ref{13b6,,Context.clamp} attribute is now public.  This is useful in creating
contexts that correspond to the decimal interchange formats specified in IEEE
754 (see bpo-8540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8540}).

(Contributed by Mark Dickinson and Raymond Hettinger.)

@node ftp,popen,decimal と fractions,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 ftp}@anchor{1420}
@subsubsection ftp


@ref{af6,,ftplib.FTP} クラスがコンテキスト管理プロトコルをサポートするようになりました。with ブロックを抜ける際に無条件に FTP 接続をクローズします (クローズ処理で発生する @ref{1261,,socket.error} は無視されます)。:

@example
>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
        ftp.login()
        ftp.dir()

'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
@end example

ちなみに @ref{519,,mmap.mmap} や @ref{a00,,fileinput.input()}  のようなほかのファイルライクなオブジェクトも自動クローズするコンテキスト管理プロトコルをサポートするようになっていたりします:

@example
with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
    for line in f:
        process(line)
@end example

(Contributed by Tarek Ziadé and Giampaolo Rodolà in bpo-4972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4972}, and
by Georg Brandl in bpo-8046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8046} and bpo-1286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1286}.)

@ref{af7,,FTP_TLS} クラスが `context' パラメータを受け取れるようになりました。これには @ref{357,,ssl.SSLContext} オブジェクトを渡します。これは SSL コンフィグレーションオプション、証明書、秘密鍵を単一の (たぶん長生きの) 構造にまとめあげてくれるものです。

(Contributed by Giampaolo Rodolà; bpo-8806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8806}.)

@node popen,select<3>,ftp,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 popen}@anchor{1421}
@subsubsection popen


@ref{31a,,os.popen()} ならびに @ref{4b7,,subprocess.Popen()} 関数が自動的にファイル記述子を閉じる @ref{186,,with} 文をサポートしました。

(Contributed by Antoine Pitrou and Brian Curtin in bpo-7461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7461} and
bpo-10554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10554}.)

@node select<3>,gzip と zipfile,popen,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 select}@anchor{1422}
@subsubsection select


The @ref{c6,,select} module now exposes a new, constant attribute,
@ref{1423,,PIPE_BUF}, which gives the minimum number of bytes which are
guaranteed not to block when @ref{fa0,,select.select()} says a pipe is ready
for writing.

@example
>>> import select
>>> select.PIPE_BUF
512
@end example

(Available on Unix systems. Patch by Sébastien Sablé in bpo-9862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9862})

@node gzip と zipfile,tarfile<10>,select<3>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 gzip-and-zipfile}@anchor{1424}
@subsubsection gzip と zipfile


@ref{65c,,gzip.GzipFile} が @ref{8a3,,io.BufferedIOBase} @ref{13ce,,抽象基底クラス} を継承しました (@code{truncate()} をのぞく)。
@ref{1425,,peek()} メソッドが追加され、シーク不能なファイルオブジェクトならびにゼロ埋めされたファイルオブジェクトをサポートしました。

また、@ref{6b,,gzip} モジュールにより簡便でインメモリな圧縮および解凍を行う  @ref{84e,,compress()} ならびに @ref{1426,,decompress()} 関数が追加されました。
圧縮や解凍の前に @ref{192,,bytes} としてエンコードしなければならない点に注意してください:

@example
>>> import gzip
>>> s = 'Three shall be the number thou shalt count, '
>>> s += 'and the number of the counting shall be three'
>>> b = s.encode()                        # convert to utf-8
>>> len(b)
89
>>> c = gzip.compress(b)
>>> len(c)
77
>>> gzip.decompress(c).decode()[:42]      # decompress and convert to text
'Three shall be the number thou shalt count'
@end example

(Contributed by Anand B. Pillai in bpo-3488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3488}; and by Antoine Pitrou, Nir
Aides and Brian Curtin in bpo-9962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9962}, bpo-1675951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1675951}, bpo-7471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7471} and
bpo-2846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2846}.)

Also, the @ref{65d,,zipfile.ZipExtFile} class was reworked internally to represent
files stored inside an archive.  The new implementation is significantly faster
and can be wrapped in an @ref{1427,,io.BufferedReader} 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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7610}.)

@node tarfile<10>,hashlib<7>,gzip と zipfile,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 tarfile}@anchor{1428}
@subsubsection tarfile


@ref{1429,,TarFile} クラスは今ではコンテキストマネージャとして使えます。加えて、その @ref{dee,,add()} メソッドに新しいオプション `filter' が追加されました。これはファイルをアーカイブに追加するかどうかを制御し、また、ファイルのメタデータを編集するのにも使えます。

`filter' オプションは古くて柔軟性に欠ける `exclude' パラメータを置き換えるものであり、 `exclude' は非推奨となりました。 `filter' を指定する場合は @ref{f0e,,keyword argument} として渡さなければなりません。ユーザ指定の filter 関数は @ref{142a,,TarInfo} オブジェクトを受け取り、更新した @ref{142a,,TarInfo} オブジェクトを返すか、あるいはアーカイブから除外したければ @code{None} を返してください。

@example
>>> import tarfile, glob

>>> def myfilter(tarinfo):
...     if tarinfo.isfile():             # only save real files
...         tarinfo.uname = 'monty'      # redact the user name
...         return tarinfo

>>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:
...     for filename in glob.glob('*.txt'):
...         tf.add(filename, filter=myfilter)
...     tf.list()
-rw-r--r-- monty/501        902 2011-01-26 17:59:11 annotations.txt
-rw-r--r-- monty/501        123 2011-01-26 17:59:11 general_questions.txt
-rw-r--r-- monty/501       3514 2011-01-26 17:59:11 prion.txt
-rw-r--r-- monty/501        124 2011-01-26 17:59:11 py_todo.txt
-rw-r--r-- monty/501       1399 2011-01-26 17:59:11 semaphore_notes.txt
@end example

(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in bpo-6856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6856}.)

@node hashlib<7>,ast<7>,tarfile<10>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 hashlib}@anchor{142b}
@subsubsection hashlib


@ref{6c,,hashlib} モジュールに、2 つの定数属性が追加されました。全ての実装で利用可能であることが保障されているハッシュアルゴリズムのリストと、現在の実装で利用可能なそれらリストの 2 つです:

@example
>>> import hashlib

>>> hashlib.algorithms_guaranteed
@{'sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'@}

>>> hashlib.algorithms_available
@{'md2', 'SHA256', 'SHA512', 'dsaWithSHA', 'mdc2', 'SHA224', 'MD4', 'sha256',
'sha512', 'ripemd160', 'SHA1', 'MDC2', 'SHA', 'SHA384', 'MD2',
'ecdsa-with-SHA1','md4', 'md5', 'sha1', 'DSA-SHA', 'sha224',
'dsaEncryption', 'DSA', 'RIPEMD160', 'sha', 'MD5', 'sha384'@}
@end example

(Suggested by Carl Chenet in bpo-7418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7418}.)

@node ast<7>,os<14>,hashlib<7>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 ast}@anchor{142c}
@subsubsection ast


@ref{9,,ast} モジュールには、Python リテラル構文を使った式文字列を安全に評価できる、汎用目的の素晴らしい道具が含まれています。その @ref{e12,,ast.literal_eval()} 関数は、悪用されやすい組み込み関数 @ref{4a3,,eval()} の安全な代替品として働いてくれます。Python 3.2 はこれのサポート型に @ref{192,,bytes} と @ref{184,,set} を加えました。結果サポートする型は全部でこれらになりました: 文字列型、バイト列文字列型、数値型、タプル型、リスト型、辞書型、集合型、真偽値型、@code{None}。

@example
>>> from ast import literal_eval

>>> request = "@{'req': 3, 'func': 'pow', 'args': (2, 0.5)@}"
>>> literal_eval(request)
@{'args': (2, 0.5), 'req': 3, 'func': 'pow'@}

>>> request = "os.system('do something harmful')"
>>> literal_eval(request)
Traceback (most recent call last):
  ...
ValueError: malformed node or string: <_ast.Call object at 0x101739a10>
@end example

(Implemented by Benjamin Peterson and Georg Brandl.)

@node os<14>,shutil<8>,ast<7>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 os}@anchor{142d}
@subsubsection os


ファイル名と環境変数に使われるエンコーディングは OS ごとに様々です。 @ref{a5,,os} モジュールは新たに 2 つの関数 @ref{e4f,,fsencode()} と @ref{e4e,,fsdecode()} を追加しました。それぞれファイル名のエンコード、デコードを行います:

@example
>>> import os
>>> filename = 'Sehenswürdigkeiten'
>>> os.fsencode(filename)
b'Sehensw\xc3\xbcrdigkeiten'
@end example

Some operating systems allow direct access to encoded bytes in the
environment.  If so, the @ref{142e,,os.supports_bytes_environ} constant will be
true.

エンコードされた環境変数への直接アクセス (可能な場合) には、新規関数 @ref{142f,,os.getenvb()} または @ref{25a,,os.environb} を使ってください。これは @ref{259,,os.environ} のバイト列バージョンです。

(Contributed by Victor Stinner.)

@node shutil<8>,sqlite3<12>,os<14>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 shutil}@anchor{1430}
@subsubsection shutil


@ref{c1e,,shutil.copytree()} 関数に新たに 2 つのオプションが追加されました:


@itemize *

@item 
`ignore_dangling_symlinks': @code{symlinks=False} とするとこの関数は、ファイルがシンボリックリンクだった場合にリンクそのものではなくそれが指しているファイルをコピーします。 `ignore_dangling_symlinks' を真にすると、そのファイルが存在しない場合のエラーを無視します。

@item 
`copy_function': これはファイルをコピーするのに使われる呼び出し可能オブジェクトです。デフォルトでは @ref{c50,,shutil.copy2()} が使われます。
@end itemize

(Contributed by Tarek Ziadé.)

これらに加え、 @ref{ca,,shutil} モジュールは ZIP ファイル、未圧縮の tar ファイル、gzip 圧縮の tar、 bzip 圧縮の tar のための @ref{1431,,archiving operations} を新たにサポートします。また、追加のアーカイブファイルフォーマットを登録する関数もあります (例えば xz 圧縮の tar やカスタムフォーマット)。

そのメインとなるのが @ref{6da,,make_archive()} と @ref{696,,unpack_archive()} です。デフォルトではカレントディレクトリ (@ref{821,,os.chdir()} で変えれます) とそのサブディレクトリの両方を処理します。アーカイブファイル名はフルパス名で指定しなければなりません(訳注: これの真偽不明。リファレンスに対応する記述なし)。アーカイブするステップは非破壊的です (つまりオリジナルのファイルは変更されずにそのままにされます)。

@example
>>> import shutil, pprint

>>> os.chdir('mydata')  # change to the source directory
>>> f = shutil.make_archive('/var/backup/mydata',
...                         'zip')      # archive the current directory
>>> f                                   # show the name of archive
'/var/backup/mydata.zip'
>>> os.chdir('tmp')                     # change to an unpacking
>>> shutil.unpack_archive('/var/backup/mydata.zip')  # recover the data

>>> pprint.pprint(shutil.get_archive_formats())  # display known formats
[('bztar', "bzip2'ed tar-file"),
 ('gztar', "gzip'ed tar-file"),
 ('tar', 'uncompressed tar file'),
 ('zip', 'ZIP file')]

>>> shutil.register_archive_format(     # register a new archive format
...     name='xz',
...     function=xz.compress,           # callable archiving function
...     extra_args=[('level', 8)],      # arguments to the function
...     description='xz compression'
... )
@end example

(Contributed by Tarek Ziadé.)

@node sqlite3<12>,html<3>,shutil<8>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 sqlite3}@anchor{1432}
@subsubsection sqlite3


@ref{d4,,sqlite3} モジュールが pysqlite バージョン 2.6.0 に更新されました。これには 2 つの新機能があります。


@itemize *

@item 
The @code{sqlite3.Connection.in_transit} attribute is true if there is an
active transaction for uncommitted changes.

@item 
@ref{a3f,,sqlite3.Connection.enable_load_extension()} メソッドと @ref{6df,,sqlite3.Connection.load_extension()} メソッドにより ".so" ファイルから SQLite 拡張をロードできます。良く知られた拡張の一つとして、SQLite と一緒に配布されている全文検索拡張があります。
@end itemize

(Contributed by R. David Murray and Shashwat Anand; bpo-8845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8845}.)

@node html<3>,socket<12>,sqlite3<12>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 html}@anchor{1433}
@subsubsection html


ただ一つの関数 @ref{1210,,escape()} が提供される、新しい @ref{6f,,html} モジュールが導入されました。これは HTML マークアップから予約されている文字をエスケープするのに使います:

@example
>>> import html
>>> html.escape('x > 2 && x < 7')
'x &gt; 2 &amp;&amp; x &lt; 7'
@end example

@node socket<12>,ssl<13>,html<3>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 socket}@anchor{1434}
@subsubsection socket


@ref{d1,,socket} モジュールに新たに二つの改善がありました。


@itemize *

@item 
Socket objects now have a @ref{1435,,detach()} method which puts
the socket into closed state without actually closing the underlying file
descriptor.  The latter can then be reused for other purposes.
(Added by Antoine Pitrou; bpo-8524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8524}.)

@item 
@ref{882,,socket.create_connection()} がコンテキスト管理プロトコルをサポートするようになりました。with ブロックを抜ける際に無条件にソケットをクローズします (クローズ処理で発生する @ref{1261,,socket.error} は無視されます)。 (Contributed by Giampaolo Rodolà; bpo-9794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9794}.) (---訳注: リファレンスもそうなのですが、「 @ref{882,,socket.create_connection()} が with をサポート」というのは実態とは違うんじゃないかと思います(この関数のユーザからは同じにみえたとしても)。実際には @ref{fa1,,socket.socket} がコンテキストマネージャをサポートしています。 socket.py@footnote{https://hg.python.org/cpython/file/3.2/Lib/socket.py} 参照。--)
@end itemize

@node ssl<13>,nntp,socket<12>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 ssl}@anchor{1436}
@subsubsection ssl


@ref{d5,,ssl} モジュールは、セキュアな (暗号化され、認証された) インターネット接続のために共通の要求を満足するための数多くの機能を追加しています:


@itemize *

@item 
新規クラス @ref{357,,SSLContext} は、プロトコル設定や証明書、秘密鍵やそのた色々なオプションのような、永続的 SSL データの容器として働きます。その中のメソッド @ref{748,,wrap_socket()} を使うと、 SSL コンテキストから SSL ソケットを作れます。

@item 
A new function, @code{ssl.match_hostname()}, supports server identity
verification for higher-level protocols by implementing the rules of HTTPS
(from 
@geindex RFC; RFC 2818
RFC 2818@footnote{https://datatracker.ietf.org/doc/html/rfc2818.html}) which are also suitable for other protocols.

@item 
The @ref{748,,ssl.wrap_socket()} constructor function now takes a `ciphers'
argument.  The `ciphers' string lists the allowed encryption algorithms using
the format described in the OpenSSL documentation@footnote{https://docs.openssl.org/1.0.2/man1/ciphers/#cipher-list-format}.

@item 
最新版の OpenSSL にリンクしていれば、 @ref{d5,,ssl} モジュールは TLS プロトコルに対する Server Name Indication 拡張 (訳注: SNI, 
@geindex RFC; RFC 4366
RFC 4366@footnote{https://datatracker.ietf.org/doc/html/rfc4366.html}) をサポートします。これは単一の IP ポートで異なった証明書を使った複数「バーチャルホスト」をもたらすものです。この拡張はクライアントモードでのみサポートされ、 @ref{748,,ssl.SSLContext.wrap_socket()} の `server_hostname' を渡すことで活性化されます。

@item 
@ref{d5,,ssl} モジュールに色々オプションが追加されました。例えば @ref{a3a,,OP_NO_SSLv2} は安全でなく時代遅れの SSLv2 を無効にします。

@item 
拡張はOpenSSL の全ての暗号とメッセージダイジェストアルゴリズムをロードします。SSL 証明書の中に検証できないものがある場合、"unknown algorithm" エラーを報告します。

@item 
The version of OpenSSL being used is now accessible using the module
attributes @ref{1437,,ssl.OPENSSL_VERSION} (a string),
@ref{1438,,ssl.OPENSSL_VERSION_INFO} (a 5-tuple), and
@ref{1439,,ssl.OPENSSL_VERSION_NUMBER} (an integer).
@end itemize

(Contributed by Antoine Pitrou in bpo-8850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8850}, bpo-1589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1589}, bpo-8322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8322},
bpo-5639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5639}, bpo-4870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4870}, bpo-8484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8484}, and bpo-8321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8321}.)

@node nntp,certificates,ssl<13>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 nntp}@anchor{143a}
@subsubsection nntp


The @code{nntplib} module has a revamped implementation with better bytes and
text semantics as well as more practical APIs.  These improvements break
compatibility with the nntplib version in Python 3.1, which was partly
dysfunctional in itself.

Support for secure connections through both implicit (using
@code{nntplib.NNTP_SSL}) and explicit (using @code{nntplib.NNTP.starttls()})
TLS has also been added.

(Contributed by Antoine Pitrou in bpo-9360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9360} and Andrew Vant in bpo-1926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1926}.)

@node certificates,imaplib<5>,nntp,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 certificates}@anchor{143b}
@subsubsection certificates


@ref{d36,,http.client.HTTPSConnection}, @ref{143c,,urllib.request.HTTPSHandler} @ref{307,,urllib.request.urlopen()} はサーバ証明書を証明書認証局 (Certification Authority (CA)) セットと照合するためのオプショナル引数を取るようになりました。これは HTTPS の公共利用で推奨されるものです。(---訳注: これは `check_hostname' パラメータのことを指していますが、3.4.3 でこれの扱いが変わっているのでリファレンスを注意深く読んで下さい。--)

(Added by Antoine Pitrou, bpo-9003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9003}.)

@node imaplib<5>,http client<4>,certificates,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 imaplib}@anchor{143d}
@subsubsection imaplib


標準 IMAP4 接続での明示的な TLS 使用を新規メソッド @ref{143e,,imaplib.IMAP4.starttls} で出来るようになりました。

(Contributed by Lorenzo M. Catucci and Antoine Pitrou, bpo-4471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4471}.)

@node http client<4>,unittest<12>,imaplib<5>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 http-client}@anchor{143f}
@subsubsection http.client


@ref{73,,http.client} モジュールに数多くの小さな API 改善がなされています。旧式 HTTP 0.9 の単純な応答 (HTTP 0.9 simple responses) はもうサポートされず、また、 `strict' パラメータは全てのクラスで非推奨となりました。

@ref{d35,,HTTPConnection} クラスと @ref{d36,,HTTPSConnection} クラスが `source_address' パラメータを取るようになりました。これには HTTP(S) 接続の接続元を表す (host, port) のタプルを渡します。

@ref{d36,,HTTPSConnection} に、証明書検証と HTTPS バーチャルホストのサポートが追加されました。

接続オブジェクトの @ref{ea7,,request()} メソッドのオプショナルな `body' 引数には、リクエストのコンテンツを与えるために @ref{13db,,file object} を渡すことが出来ました。便利のためにこれに @ref{12f1,,iterable} も渡すことが出来るようになりました。ただしこの場合は明示的に @code{Content-Length} ヘッダを加えなければなりません。この拡張されたインターフェイスは以前よりも遥かに柔軟です。

プロキシサーバ経由で HTTPS 接続を確立するために、新規メソッド @ref{1440,,set_tunnel()} が追加されています。これにより HTTP 接続トンネリングのためのホストとポートをセットします。

@ref{76,,http.server} の振る舞いと合わせ、HTTP クライアントライブラリもヘッダを ISO-8859-1 (Latin-1) エンコーディングでエンコードするようになりました。これは既に incoming (外から来る方) ヘッダに対して行われていますが、今ではこの振る舞いは incoming、outgoing (外へ向かう方) トラフィックの両方で一貫しています (bpo-10980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10980} 内の Armin Ronacher による仕事を参照)。

@node unittest<12>,random<5>,http client<4>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 unittest}@anchor{1441}
@subsubsection unittest


unittest モジュールに数多くの改善がありました。パッケージに対する test discovery のサポートが追加され、対話プロンプトから実験しやすくなり、新しいメソッドが追加され、テスト失敗時の診断メッセージが改善され、そしてメソッド名がより良いものになりました。


@itemize *

@item 
The command-line call @code{python -m unittest} can now accept file paths
instead of module names for running specific tests (bpo-10620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10620}).  The new
test discovery can find tests within packages, locating any test importable
from the top-level directory.  The top-level directory can be specified with
the @code{-t} option, a pattern for matching files with @code{-p}, and a directory to
start discovery with @code{-s}:

@example
$ python -m unittest discover -s my_proj_dir -p _test.py
@end example

(Contributed by Michael Foord.)

@item 
Experimentation at the interactive prompt is now easier because the
@ref{2b3,,unittest.TestCase} class can now be instantiated without
arguments:

@example
>>> from unittest import TestCase
>>> TestCase().assertEqual(pow(2, 3), 8)
@end example

(Contributed by Michael Foord.)

@item 
@ref{10c,,unittest} モジュールは 2 つの新メソッド @ref{137c,,assertWarns()} と @ref{137d,,assertWarnsRegex()} を持ちます。これらはテストのもとでコードによって所与の警告が発行されるかどうかを検証します:

@example
with self.assertWarns(DeprecationWarning):
    legacy_function('XYZ')
@end example

(Contributed by Antoine Pitrou, bpo-9754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9754}.)

もう一つの新メソッド @ref{1442,,assertCountEqual()} は 2 つのイテラブルを比較して、要素の出現回数が同じか (順序に関わらず同じ要素が同じ数だけ出現するかどうか) をテストします:

@example
def test_anagram(self):
    self.assertCountEqual('algorithm', 'logarithm')
@end example

(Contributed by Raymond Hettinger.)

@item 
unittest モジュールの大事な特長は、テスト失敗時の有意義な診断を生成するよう腐心してくれることです。可能ならば失敗は期待値と実際の出力との差分と一緒に記録されます。これは失敗したテスト実行の解析に特に役に立ちますが、差分は時々とてつもなく大きくもなりますので、新たに追加した属性 @ref{1443,,maxDiff} に差分の最大長をセットすることで表示を制御できるようになりました。

@item 
さらにモジュールのメソッド名に数多くのクリーンアップを行いました。

For example, @ref{751,,assertRegex()} is the new name for
@code{assertRegexpMatches()} which was misnamed because the
test uses @ref{1444,,re.search()}, not @ref{1445,,re.match()}.  Other methods using
regular expressions are now named using short form "Regex" in preference to
"Regexp" -- this matches the names used in other unittest implementations,
matches Python's old name for the @ref{be,,re} module, and it has unambiguous
camel-casing.

(Contributed by Raymond Hettinger and implemented by Ezio Melotti.)

@item 
一貫性を向上させるために、長年使用されたメソッドエイリアスが推奨名に対し非推奨になりました:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

以前の名前

@tab

推奨名

@item

@code{assert_()}

@tab

@ref{74a,,assertTrue()}

@item

@code{assertEquals()}

@tab

@ref{74c,,assertEqual()}

@item

@code{assertNotEquals()}

@tab

@ref{74d,,assertNotEqual()}

@item

@code{assertAlmostEquals()}

@tab

@ref{74e,,assertAlmostEqual()}

@item

@code{assertNotAlmostEquals()}

@tab

@ref{74f,,assertNotAlmostEqual()}

@end multitable

@end quotation

Likewise, the @code{TestCase.fail*} methods deprecated in Python 3.1 are expected
to be removed in Python 3.3.

(Contributed by Ezio Melotti; bpo-9424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9424}.)

@item 
The @code{assertDictContainsSubset()} method was deprecated
because it was misimplemented with the arguments in the wrong order.  This
created hard-to-debug optical illusions where tests like
@code{TestCase().assertDictContainsSubset(@{'a':1, 'b':2@}, @{'a':1@})} would fail.

(Contributed by Raymond Hettinger.)
@end itemize

@node random<5>,poplib<4>,unittest<12>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 random}@anchor{1446}
@subsubsection random


@ref{bd,,random} モジュールの整数メソッドの一様分布の生成が改善されました。
以前は @code{int(n*random())} を計算していました。
この方法では `n' が2の冪乗でない限り僅かにバイアスがあります。
現在の方法では次の2の冪乗の範囲まで複数の選択肢を作成し、@code{0 <= x < n} の範囲に入ったもののみを保持します。
影響を受ける関数やメソッドは @ref{a6b,,randrange()}、@ref{1447,,randint()}、@ref{1448,,choice()}、@ref{94e,,shuffle()} ならびに @ref{94d,,sample()} です。

(Contributed by Raymond Hettinger; bpo-9025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9025}.)

@node poplib<4>,asyncore<2>,random<5>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 poplib}@anchor{1449}
@subsubsection poplib


@ref{b1e,,POP3_SSL} クラスが `context' パラメータを受け取れるようになりました。これには @ref{357,,ssl.SSLContext} オブジェクトを渡します。これは SSL コンフィグレーションオプション、証明書、秘密鍵を単一の (たぶん長生きの) 構造にまとめあげてくれるものです。

(Contributed by Giampaolo Rodolà; bpo-8807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8807}.)

@node asyncore<2>,tempfile<5>,poplib<4>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 asyncore}@anchor{144a}
@subsubsection asyncore


@code{asyncore.dispatcher} now provides a
@code{handle_accepted()} method
returning a @code{(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 @code{handle_accept()} and avoids
the user  to call @code{accept()} directly.

(Contributed by Giampaolo Rodolà; bpo-6706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6706}.)

@node tempfile<5>,inspect<11>,asyncore<2>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 tempfile}@anchor{144b}
@subsubsection tempfile


@ref{e6,,tempfile} モジュールに新たなコンテキストマネージャ @ref{144c,,TemporaryDirectory} が追加されました。一時ディレクトリの確実な後片付けを容易に行えます:

@example
with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary dir:', tmpdirname)
@end example

(Contributed by Neil Schemenauer and Nick Coghlan; bpo-5178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5178}.)

@node inspect<11>,pydoc<7>,tempfile<5>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 inspect}@anchor{144d}
@subsubsection inspect



@itemize *

@item 
@ref{82,,inspect} モジュールに新たな関数 @ref{144e,,getgeneratorstate()} が追加されました。これで簡単にジェネレータイテレータの現在状態を識別出来ます (---訳注: generator-iterator という用語を使っている箇所は Python ドキュメント全体通して多くはないのですが 2.x の @ref{bc2,,yield 文} 説明中に登場します。ジェネレータと同じ意味です。なお getgeneratorstate はジェネレータでないイテレータには使えません。---):

@example
>>> from inspect import getgeneratorstate
>>> def gen():
...     yield 'demo'
...
>>> g = gen()
>>> getgeneratorstate(g)
'GEN_CREATED'
>>> next(g)
'demo'
>>> getgeneratorstate(g)
'GEN_SUSPENDED'
>>> next(g, None)
>>> getgeneratorstate(g)
'GEN_CLOSED'
@end example

(Contributed by Rodolpho Eckhardt and Nick Coghlan, bpo-10220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10220}.)

@item 
動的な属性を活性化することなく検索するのをサポートするために、 @ref{82,,inspect} モジュールに @ref{6bc,,getattr_static()} 関数が追加されました。 @ref{6f9,,hasattr()} とは違ってこれは本当に読み出しのみの検索であり、検索中に状態変更しないことが保障されています:

@example
>>> class A:
...     @@property
...     def f(self):
...         print('Running')
...         return 10
...
>>> a = A()
>>> getattr(a, 'f')
Running
10
>>> inspect.getattr_static(a, 'f')
<property object at 0x1022bd788>
@end example
@end itemize

@quotation

(Contributed by Michael Foord.)
@end quotation

@node pydoc<7>,dis<6>,inspect<11>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 pydoc}@anchor{144f}
@subsubsection pydoc


The @ref{ba,,pydoc} module now provides a much-improved web server interface, as
well as a new command-line option @code{-b} to automatically open a browser window
to display that server:

@example
$ pydoc3.2 -b
@end example

(Contributed by Ron Adam; bpo-2001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2001}.)

@node dis<6>,dbm<7>,pydoc<7>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 dis}@anchor{1450}
@subsubsection dis


@ref{3c,,dis} モジュールに、コードを調べるための 2 つの新しい関数 @ref{1451,,code_info()} と @ref{112f,,show_code()} が追加されました。ともに、与えられた関数、メソッド、ソースコード文字列、コードオブジェクトについての詳細なコードオブジェクト情報を提供します。前者はそれを文字列で返し、後者は印字します:

@example
>>> import dis, random
>>> dis.show_code(random.choice)
Name:              choice
Filename:          /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/random.py
Argument count:    2
Kw-only arguments: 0
Number of locals:  3
Stack size:        11
Flags:             OPTIMIZED, NEWLOCALS, NOFREE
Constants:
   0: 'Choose a random element from a non-empty sequence.'
   1: 'Cannot choose from an empty sequence'
Names:
   0: _randbelow
   1: len
   2: ValueError
   3: IndexError
Variable names:
   0: self
   1: seq
   2: i
@end example

また、 @ref{205,,dis()} 関数が文字列引数を取れるようになり、これによって、よくあるイディオム @code{dis(compile(s, '@w{'}, 'eval'))} は @code{dis(s)} で一撃です:

@example
>>> dis('3*x+1 if x%2==1 else x//2')
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (2)
              6 BINARY_MODULO
              7 LOAD_CONST               1 (1)
             10 COMPARE_OP               2 (==)
             13 POP_JUMP_IF_FALSE       28
             16 LOAD_CONST               2 (3)
             19 LOAD_NAME                0 (x)
             22 BINARY_MULTIPLY
             23 LOAD_CONST               1 (1)
             26 BINARY_ADD
             27 RETURN_VALUE
        >>   28 LOAD_NAME                0 (x)
             31 LOAD_CONST               0 (2)
             34 BINARY_FLOOR_DIVIDE
             35 RETURN_VALUE
@end example

要はこれらによって、CPython がどう実装されているか探索してみたり、言語構文が裏方で何をするのか見てみたりすることがより簡単になったということです。

(Contributed by Nick Coghlan in bpo-9147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9147}.)

@node dbm<7>,ctypes<4>,dis<6>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 dbm}@anchor{1452}
@subsubsection dbm


All database modules now support the @code{get()} and @code{setdefault()} methods.

(Suggested by Ray Allen in bpo-9523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9523}.)

@node ctypes<4>,site<4>,dbm<7>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 ctypes}@anchor{1453}
@subsubsection ctypes


C @code{ssize_t} データ型を表現する新たな型 @ref{1454,,ctypes.c_ssize_t} が追加されました。

@node site<4>,sysconfig<4>,ctypes<4>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 site}@anchor{1455}
@subsubsection site


@ref{cc,,site} モジュールに、Python インストレーションの詳細を報告するのに有益な3つの新たな関数が追加されました。


@itemize *

@item 
@ref{1456,,getsitepackages()} は全てのグローバルな site-packages ディレクトリを一覧します。

@item 
@ref{1457,,getuserbase()} は、ユーザのデータを格納できるベースディレクトリを報告します。

@item 
@ref{1458,,getusersitepackages()} はユーザ固有の site-packages ディレクトリのパスを明らかにします。
@end itemize

@example
>>> import site
>>> site.getsitepackages()
['/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.2/lib/site-python',
 '/Library/Python/3.2/site-packages']
>>> site.getuserbase()
'/Users/raymondhettinger/Library/Python/3.2'
>>> site.getusersitepackages()
'/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'
@end example

便宜のために、いくつかの site の機能はコマンドラインから直接アクセス可能です:

@example
$ python -m site --user-base
/Users/raymondhettinger/.local
$ python -m site --user-site
/Users/raymondhettinger/.local/lib/python3.2/site-packages
@end example

(Contributed by Tarek Ziadé in bpo-6693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6693}.)

@node sysconfig<4>,pdb<10>,site<4>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 sysconfig}@anchor{1459}
@subsubsection sysconfig


新しい @ref{e1,,sysconfig} モジュールは、プラットフォームやインストレーションごとに変わるインストールパスや環境設定変数への、直接的なアクセスを提供します。

このモジュールはプラットフォームとバージョンの情報へのシンプルなアクセス関数を持っています:


@itemize *

@item 
@ref{145a,,get_platform()} は `linux-i586' や `macosx-10.6-ppc' といった値を返します。

@item 
@ref{145b,,get_python_version()} は Python バージョンを文字列で "3.2" のように返します。
@end itemize

It also provides access to the paths and variables corresponding to one of
seven named schemes used by @code{distutils}.  Those include `posix_prefix',
`posix_home', `posix_user', `nt', `nt_user', `os2', `os2_home':


@itemize *

@item 
@ref{340,,get_paths()} は現在のインストールスキームに関するインストールパスを含むディレクトリ名を作ります。

@item 
@ref{298,,get_config_vars()} はプラットフォーム依存変数の辞書を返します。
@end itemize

便利なコマンドラインインターフェースもあります:

@example
C:\Python32>python -m sysconfig
Platform: "win32"
Python version: "3.2"
Current installation scheme: "nt"

Paths:
        data = "C:\Python32"
        include = "C:\Python32\Include"
        platinclude = "C:\Python32\Include"
        platlib = "C:\Python32\Lib\site-packages"
        platstdlib = "C:\Python32\Lib"
        purelib = "C:\Python32\Lib\site-packages"
        scripts = "C:\Python32\Scripts"
        stdlib = "C:\Python32\Lib"

Variables:
        BINDIR = "C:\Python32"
        BINLIBDEST = "C:\Python32\Lib"
        EXE = ".exe"
        INCLUDEPY = "C:\Python32\Include"
        LIBDEST = "C:\Python32\Lib"
        SO = ".pyd"
        VERSION = "32"
        abiflags = ""
        base = "C:\Python32"
        exec_prefix = "C:\Python32"
        platbase = "C:\Python32"
        prefix = "C:\Python32"
        projectbase = "C:\Python32"
        py_version = "3.2"
        py_version_nodot = "32"
        py_version_short = "3.2"
        srcdir = "C:\Python32"
        userbase = "C:\Documents and Settings\Raymond\Application Data\Python"
@end example

(Moved out of Distutils by Tarek Ziadé.)

@node pdb<10>,configparser<6>,sysconfig<4>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 pdb}@anchor{145c}
@subsubsection pdb


@ref{aa,,pdb} デバッガモジュールに数多くのユーザビリティの改善がなされました:


@itemize *

@item 
@code{pdb.py} は @code{-c} オプションで指定した @code{.pdbrc} スクリプトファイルを実行できるようになっています。

@item 
@code{.pdbrc} スクリプトファイルにはデバッグを継続する @code{continue} コマンドと @code{next} コマンドを含むことができます。

@item 
The @ref{273,,Pdb} class constructor now accepts a `nosigint' argument.

@item 
新コマンド: @code{l(list)}, @code{ll(long list)}, @code{source} はソースコードを出力します。

@item 
新コマンド:  @code{display}, @code{undisplay} は、変更があった場合の式の値の表示/非表示を切り替えます。

@item 
新コマンド: @code{interact} は現在のスコープで見つかったグローバルおよびローカル名を含む対話型インタプリタを開始します。

@item 
ブレイクポイントをブレイクポイント番号指定でクリア出来ます。
@end itemize

(Contributed by Georg Brandl, Antonio Cuni and Ilya Sandler.)

@node configparser<6>,urllib parse<6>,pdb<10>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 configparser}@anchor{145d}
@subsubsection configparser


The @ref{26,,configparser} module was modified to improve usability and
predictability of the default parser and its supported INI syntax.  The old
@code{ConfigParser} class was removed in favor of @code{SafeConfigParser}
which has in turn been renamed to @ref{4de,,ConfigParser}. Support
for inline comments is now turned off by default and section or option
duplicates are not allowed in a single configuration source.

Config parsers はマッピングプロトコルにもとづく新しい API を獲得しました:

@example
>>> parser = ConfigParser()
>>> parser.read_string("""
... [DEFAULT]
... location = upper left
... visible = yes
... editable = no
... color = blue
...
... [main]
... title = Main Menu
... color = green
...
... [options]
... title = Options
... """)
>>> parser['main']['color']
'green'
>>> parser['main']['editable']
'no'
>>> section = parser['options']
>>> section['title']
'Options'
>>> section['title'] = 'Options (editable: %(editable)s)'
>>> section['title']
'Options (editable: no)'
@end example

新しい API は旧式 API の上に実装されているので、カスタムなパーサーサブクラスは変更なしで使えるはずです。

config parser によって受け付けられる INI ファイルの構造は今ではカスタマイズ出来ます。ユーザは、オプションと値を区切る代替のデリミタやコメントのプレフィクスを指定でき、 `DEFAULT' セクションの名前を変えることができ、あるいは補間の構文を切り替えられます。

抜き挿し可能 (pluggable) な補間サポートがあって、これには追加の補間ハンドラ @ref{92d,,ExtendedInterpolation} が含まれています:

@example
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> parser.read_dict(@{'buildout': @{'directory': '/home/ambv/zope9'@},
...                   'custom': @{'prefix': '/usr/local'@}@})
>>> parser.read_string("""
... [buildout]
... parts =
...   zope9
...   instance
... find-links =
...   $@{buildout:directory@}/downloads/dist
...
... [zope9]
... recipe = plone.recipe.zope9install
... location = /opt/zope
...
... [instance]
... recipe = plone.recipe.zope9instance
... zope9-location = $@{zope9:location@}
... zope-conf = $@{custom:prefix@}/etc/zope.conf
... """)
>>> parser['buildout']['find-links']
'\n/home/ambv/zope9/downloads/dist'
>>> parser['instance']['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance = parser['instance']
>>> instance['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance['zope9-location']
'/opt/zope'
@end example

小さな機能もたくさん導入されています。例えば読み込み操作内でのエンコーディング指定のサポート、取得関数でのフォールバック値の指定、あるいは辞書や文字列から直接的に読むことなどです。

(All changes contributed by Łukasz Langa.)

@c XXX consider showing a difflib example

@node urllib parse<6>,mailbox,configparser<6>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 urllib-parse}@anchor{145e}
@subsubsection urllib.parse


数多くのユーザビリティーの改善が @ref{110,,urllib.parse} モジュールになされました。

@ref{362,,urlparse()} 関数が 
@geindex RFC; RFC 2732
RFC 2732@footnote{https://datatracker.ietf.org/doc/html/rfc2732.html} にて記述されている IPv6@footnote{https://ja.wikipedia.org/wiki/IPv6} アドレスをサポートするようになりました:

@example
>>> import urllib.parse
>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
ParseResult(scheme='http',
            netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',
            path='/foo/',
            params='@w{'},
            query='@w{'},
            fragment='@w{'})
@end example

@ref{145f,,urldefrag()} 関数は、今や @ref{85e,,named tuple} を返します:

@example
>>> r = urllib.parse.urldefrag('http://python.org/about/#target')
>>> r
DefragResult(url='http://python.org/about/', fragment='target')
>>> r[0]
'http://python.org/about/'
>>> r.fragment
'target'
@end example

また、  @ref{1095,,urlencode()} 関数はさらに柔軟になり、 `query' 引数としては文字列とバイト列のどちらも受け付けます。文字列で渡した場合、パラメータ  `safe', `encoding', `error' がエンコードのために @ref{1460,,quote_plus()} に送られます:

@example
>>> urllib.parse.urlencode([
...      ('type', 'telenovela'),
...      ('name', '¿Dónde Está Elisa?')],
...      encoding='latin-1')
'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'
@end example

@ref{1461,,ASCII エンコードバイト列の解析} に詳細に書きましたが、全ての @ref{110,,urllib.parse} 関数は今では ASCII エンコードされたバイト文字列を (通常の文字列と混ぜない限り) 入力として受け付けます。ASCII エンコードされたバイト文字列がパラメータとして与えられると、戻り値の型も ASCII エンコードされたバイト文字列になります:

@example
>>> urllib.parse.urlparse(b'http://www.python.org:80/about/')
ParseResultBytes(scheme=b'http', netloc=b'www.python.org:80',
                 path=b'/about/', params=b'@w{'}, query=b'@w{'}, fragment=b'@w{'})
@end example

(Work by Nick Coghlan, Dan Mahn, and Senthil Kumaran in bpo-2987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2987},
bpo-5468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5468}, and bpo-9873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9873}.)

@node mailbox,turtledemo,urllib parse<6>,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 mailbox}@anchor{1462}
@subsubsection mailbox


Thanks to a concerted effort by R. David Murray, the @ref{8f,,mailbox} module has
been fixed for Python 3.2.  The challenge was that mailbox had been originally
designed with a text interface, but email messages are best represented with
@ref{192,,bytes} because various parts of a message may have different encodings.

解決のためには任意の email メッセージをパースするために、 @ref{3f,,email} パッケージのバイナリサポートが利用されました (---訳注: @ref{13e7,,BytesGenerator} や @ref{13e1,,message_from_bytes()} など)。また、API の変更も必要となりました。

@ref{1463,,mailbox.Mailbox} オブジェクトの @ref{1464,,add()} メソッドは、今や期待通りにバイナリ入力を受け付けます。

@ref{112a,,StringIO} とテキストファイルでの入力は非推奨となりました。また、文字列での入力は、非 ASCII 文字が使用されていると早々に失敗します。以前は後のほうのステップで email が処理される際にようやく失敗していました。

バイナリ出力のサポートもあります。 @ref{1465,,get_file()} メソッドは今ではバイナリモードのファイルを返します (これまでは不適切にテキストモードが使われていました)。また、新しい @ref{1466,,get_bytes()} メソッドは、指定した `key' に対応するメッセージの @ref{192,,bytes} 表現を返します。

今でも古い API の @ref{1467,,get_string()} を使って非バイナリ出力は可能ですが、そのアプローチはあまり役に立ちません。そうではなく @ref{1468,,Message} オブジェクトからメッセージを抽出するか、それらをバイナリ入力からロードするのが最善です。

(Contributed by R. David Murray, with efforts from Steffen Daode Nurpmeso and an
initial patch by Victor Stinner in bpo-9124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9124}.)

@node turtledemo,,mailbox,新たなモジュール、改良されたモジュール、非推奨のモジュール
@anchor{whatsnew/3 2 turtledemo}@anchor{1469}
@subsubsection turtledemo


The demonstration code for the @ref{107,,turtle} module was moved from the `Demo'
directory to main library.  It includes over a dozen sample scripts with
lively displays.  Being on @ref{3e4,,sys.path}, it can now be run directly
from the command-line:

@example
$ python -m turtledemo
@end example

(Moved from the Demo directory by Alexander Belopolsky in bpo-10199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10199}.)

@node マルチスレッディング,最適化<12>,新たなモジュール、改良されたモジュール、非推奨のモジュール,What's New In Python 3 2
@anchor{whatsnew/3 2 multi-threading}@anchor{146a}
@subsection マルチスレッディング



@itemize *

@item 
The mechanism for serializing execution of concurrently running Python threads
(generally known as the @ref{164,,GIL} or Global Interpreter Lock) has
been rewritten.  Among the objectives were more predictable switching
intervals and reduced overhead due to lock contention and the number of
ensuing system calls.  The notion of a "check interval" to allow thread
switches has been abandoned and replaced by an absolute duration expressed in
seconds.  This parameter is tunable through @ref{b44,,sys.setswitchinterval()}.
It currently defaults to 5 milliseconds.

この実装に関するさらなる詳細は python-dev mailing-list message@footnote{https://mail.python.org/pipermail/python-dev/2009-October/093321.html} で読むことが出来ます (ただしこのメッセージで言っている "priority requests" は含められませんでした)。

(Contributed by Antoine Pitrou.)

@item 
通常のロックと再帰的なロックが、@ref{8a7,,acquire()} メソッドでオプションで `timeout' 引数を受け取るようになりました。
(Contributed by Antoine Pitrou; bpo-7316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7316}.)

@item 
同様に、@ref{146b,,threading.Semaphore.acquire()} にも `timeout' 引数が追加されました。
(Contributed by Torsten Landschoff; bpo-850728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=850728}.)

@item 
通常のロックと再帰的なロックの獲得に、 Pthreads を使用するプラットフォームでシグナルが割り込めるようになりました。これでロック獲得時にデッドロックしていた Python プログラムは、プロセスに SIGINT (ほとんどのシェルでは @code{Ctrl}+@code{C} で) を繰り返し送ることで殺せます。(Contributed by Reid Kleckner; bpo-8844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8844}.)
@end itemize

@node 最適化<12>,Unicode 文字列型,マルチスレッディング,What's New In Python 3 2
@anchor{whatsnew/3 2 optimizations}@anchor{146c}
@subsection 最適化


小さな性能向上が多く追加されました:


@itemize *

@item 
Python's peephole optimizer now recognizes patterns such @code{x in @{1, 2, 3@}} as
being a test for membership in a set of constants.  The optimizer recasts the
@ref{184,,set} as a @ref{7f2,,frozenset} and stores the pre-built constant.

Now that the speed penalty is gone, it is practical to start writing
membership tests using set-notation.  This style is both semantically clear
and operationally fast:

@example
extension = name.rpartition('.')[2]
if extension in @{'xml', 'html', 'xhtml', 'css'@}:
    handle(name)
@end example

(Patch and additional tests contributed by Dave Malcolm; bpo-6690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6690}).

@item 
@ref{ab,,pickle} モジュールを用いたデータのシリアライズ・デシリアライズが数倍速くなりました。

(Contributed by Alexandre Vassalotti, Antoine Pitrou
and the Unladen Swallow team in bpo-9410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9410} and bpo-3873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3873}.)

@item 
The Timsort algorithm@footnote{https://en.wikipedia.org/wiki/Timsort} used in
@ref{dc8,,list.sort()} and @ref{dc7,,sorted()} now runs faster and uses less memory
when called with a @ref{1006,,key function}.  Previously, every element of
a list was wrapped with a temporary object that remembered the key value
associated with each element.  Now, two arrays of keys and values are
sorted in parallel.  This saves the memory consumed by the sort wrappers,
and it saves time lost to delegating comparisons.

(Patch by Daniel Stutzbach in bpo-9915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9915}.)

@item 
JSON decoding performance is improved and memory consumption is reduced
whenever the same string is repeated for multiple keys.  Also, JSON encoding
now uses the C speedups when the @code{sort_keys} argument is true.

(Contributed by Antoine Pitrou in bpo-7451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7451} and by Raymond Hettinger and
Antoine Pitrou in bpo-10314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10314}.)

@item 
再帰的ロック (@ref{32e,,threading.RLock()} API により生成) は C で実装されたことにより、以前の純粋な Python 実装より10から15倍速くなり、通常のロックと同じくらいになりました。

(Contributed by Antoine Pitrou; bpo-3001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3001}.)

@item 
The fast-search algorithm in stringlib is now used by the @ref{10aa,,split()},
@ref{146d,,rsplit()}, @ref{146e,,splitlines()} and @ref{4b8,,replace()} methods on
@ref{192,,bytes}, @ref{344,,bytearray} and @ref{169,,str} objects. Likewise, the
algorithm is also used by @ref{10a9,,rfind()}, @ref{146f,,rindex()}, @ref{146d,,rsplit()} and
@ref{1470,,rpartition()}.

(Patch by Florent Xicluna in bpo-7622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7622} and bpo-7462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7462}.)

@item 
Integer to string conversions now work two "digits" at a time, reducing the
number of division and modulo operations.

(bpo-6713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6713} by Gawain Bolton, Mark Dickinson, and Victor Stinner.)
@end itemize

There were several other minor optimizations. Set differencing now runs faster
when one operand is much larger than the other (patch by Andress Bennetts in
bpo-8685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8685}).  The @code{array.repeat()} method has a faster implementation
(bpo-1569291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1569291} by Alexander Belopolsky). The @ref{12e2,,BaseHTTPRequestHandler}
has more efficient buffering (bpo-3709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3709} by Andrew Schaaf).  The
@ref{1033,,operator.attrgetter()} function has been sped-up (bpo-10160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10160} by
Christos Georgiou).  And @ref{4de,,ConfigParser} loads multi-line arguments a bit
faster (bpo-7113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7113} by Łukasz Langa).

@node Unicode 文字列型,Codecs,最適化<12>,What's New In Python 3 2
@anchor{whatsnew/3 2 unicode}@anchor{1471}
@subsection Unicode 文字列型


Python has been updated to Unicode 6.0.0@footnote{https://unicode.org/versions/Unicode6.0.0/}.  The update to the standard adds
over 2,000 new characters including emoji@footnote{https://en.wikipedia.org/wiki/Emoji}
symbols which are important for mobile phones.

In addition, the updated standard has altered the character properties for two
Kannada characters (U+0CF1, U+0CF2) and one New Tai Lue numeric character
(U+19DA), making the former eligible for use in identifiers while disqualifying
the latter.  For more information, see Unicode Character Database Changes@footnote{https://www.unicode.org/versions/Unicode6.0.0/#Database_Changes}.

@node Codecs,ドキュメント,Unicode 文字列型,What's New In Python 3 2
@anchor{whatsnew/3 2 codecs}@anchor{1472}
@subsection Codecs


`cp720' アラビア DOS エンコードがサポートされました (bpo-1616979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1616979})。

MBCS エンコーディングはもうエラーハンドラ引数を無視することはありません。デフォルトの strict モードでは、デコード出来ないバイト列に対して @ref{c08,,UnicodeDecodeError} を、エンコードできない文字に対して @ref{887,,UnicodeEncodeError} を投げます。

MBCS コーデックはエラーハンドラとして、デコードでの @code{'strict'} と @code{'ignore'} 、エンコードでの @code{'strict'} と @code{'replace'} をサポートします。

Python 3.1 での MBCS エンコーディングを模擬したければデコードでは @code{'ignore'} ハンドラを、エンコードでは @code{'replace'} ハンドラを選んでください。

Mac OS X では Python は、コマンドライン引数をロケールのエンコーディングではなく @code{'utf-8'} でデコードします。

@ref{e4,,tarfile} はデフォルトで、Windows では (@code{'mbcs'} ではなく) @code{'utf-8'} エンコーディングを使い、また、全ての OS でエラーハンドラ @code{'surrogateescape'} を使います。

@node ドキュメント,IDLE,Codecs,What's New In Python 3 2
@anchor{whatsnew/3 2 documentation}@anchor{1473}
@subsection ドキュメント


ドキュメントの改善が引き続き行われています。


@itemize *

@item 
@ref{1474,,組み込み関数} のような長大なセクションには先頭にクイックリンクの表が追加されました。 @ref{85,,itertools} のようなケースでは cheatsheet@footnote{https://en.wikipedia.org/wiki/Cheat_sheet} スタイルの表からリンクが張られていて、これで要約がわかりますし、ドキュメント全体を読む必要なく記憶を呼び覚ますことが出来ます。

@item 
ある種のケースではピュア Python のソースコードが文書化の助手として便利に働いてくれますので、今では多くのモジュールがソースコードの最新バージョンへのクイックリンクを客演させています。例えば @ref{63,,functools} モジュールのドキュメントは先頭にこのようにクイックリンクを置いています:

@quotation

`ソースコード' Lib/functools.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/functools.py}.
@end quotation

(Contributed by Raymond Hettinger; see
rationale@footnote{https://rhettinger.wordpress.com/2011/01/28/open-your-source-more/}.)

@item 
ドキュメントには今ではもっと実例とレシピが含まれています。特に @ref{be,,re} モジュールのものには大掛かりなセクション @ref{1475,,正規表現の例} があります。同じように @ref{85,,itertools} では新しい @ref{1476,,Itertools レシピ} で更新され続けます。

@item 
@ref{34,,datetime} モジュールは今ではピュア Python による補助実装を持っています。機能に違いはありません。これは読みやすい代替の実装を提供するだけのものです。

(Contributed by Alexander Belopolsky in bpo-9528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9528}.)

@item 
保守されていなかった @code{Demo} ディレクトリは削除されました。いくつかのデモはドキュメントに統合され、いくつかは @code{Tools/demo} ディレクトリに移動し、ほかのものは一緒に削除されました。

(Contributed by Georg Brandl in bpo-7962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7962}.)
@end itemize

@node IDLE,コードリポジトリ,ドキュメント,What's New In Python 3 2
@anchor{whatsnew/3 2 idle}@anchor{1477}
@subsection IDLE



@itemize *

@item 
IDLE のフォーマットメニューに、ソースコードから末尾の空白を取り除くことが出来るオプションが追加されました。

(Contributed by Raymond Hettinger; bpo-5150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5150}.)

@item 
Mac OS X 上の IDLE が Carbon AquaTk と Cocoa AquaTk の両方で動くようになりました。

(Contributed by Kevin Walzer, Ned Deily, and Ronald Oussoren; bpo-6075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6075}.)
@end itemize

@node コードリポジトリ,ビルドならびに C API の変更<5>,IDLE,What's New In Python 3 2
@anchor{whatsnew/3 2 code-repository}@anchor{1478}
@subsection コードリポジトリ


In addition to the existing Subversion code repository at @indicateurl{https://svn.python.org}
there is now a Mercurial@footnote{https://www.mercurial-scm.org/} repository at
@indicateurl{https://hg.python.org/}.

3.2 のリリース後に、主要なリポジトリを Mercurial に移行する計画があります。
この分散バージョン管理システムによってコミュニティメンバが容易に外部 changeset を作成したり共有したりすることが出来ます。
詳細は 
@geindex Python Enhancement Proposals; PEP 385
PEP 385@footnote{https://peps.python.org/pep-0385/} を参照してください。

To learn to use the new version control system, see the Quick Start@footnote{https://www.mercurial-scm.org/wiki/QuickStart} or the Guide to Mercurial Workflows@footnote{https://www.mercurial-scm.org/guide}.

@node ビルドならびに C API の変更<5>,Python 3 2 への移植,コードリポジトリ,What's New In Python 3 2
@anchor{whatsnew/3 2 build-and-c-api-changes}@anchor{1479}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
スクリプト `idle', `pydoc', `2to3' が @code{make altinstall} 時にバージョン固有のサフィックスを付けてインストールされるようになりました (bpo-10679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10679})。

@item 
Unicode データベースにアクセスする関数 (Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, ほか) が、たとえ narrow Unicode ビルドであっても full Unicode 範囲を受け付け、返すようになりました。Python から目に見える違いとしては、大きなコードポイントについて @ref{147a,,unicodedata.numeric()} が正しい値を返し、 @ref{1c1,,repr()} はより多くの文字を表示可能と考えるようになりました。

(Reported by Bupjoe Lee and fixed by Amaury Forgeot D'Arc; bpo-5127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5127}.)

@item 
Computed gotos are now enabled by default on supported compilers (which are
detected by the configure script).  They can still be disabled selectively by
specifying @code{--without-computed-gotos}.

(Contributed by Antoine Pitrou; bpo-9203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9203}.)

@item 
オプション @code{--with-wctype-functions} は削除されました。今では組み込みの Unicode データベースが全ての関数のために使われます。

(Contributed by Amaury Forgeot D'Arc; bpo-9210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9210}.)

@item 
ハッシュ値として新しい型 @ref{147b,,Py_hash_t} を使うようになりました。これはポインタと同じサイズになるように定義されています。以前は long 型を使っていましたが、これはいくつかの 64 ビット OS でも 32 ビット長のままでした。この修正の結果、64 ビットポインタでビルドすれば @ref{184,,set} と @ref{183,,dict} が @code{2**32} 以上のエントリを持てるようになりました (以前もそのサイズを入れることは出来ましたが、悲劇的なパフォーマンス低下を起こしていました)。

(Suggested by Raymond Hettinger and implemented by Benjamin Peterson;
bpo-9778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9778}.)

@item 
A new macro @code{Py_VA_COPY} copies the state of the variable argument
list.  It is equivalent to C99 `va_copy' but available on all Python platforms
(bpo-2443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2443}).

@item 
A new C API function @code{PySys_SetArgvEx()} allows an embedded interpreter
to set @ref{147c,,sys.argv} without also modifying @ref{3e4,,sys.path}
(bpo-5753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5753}).

@item 
@code{PyEval_CallObject()} is now only available in macro form.  The
function declaration, which was kept for backwards compatibility reasons, is
now removed -- the macro was introduced in 1997 (bpo-8276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8276}).

@item 
@ref{147d,,PyLong_AsLongAndOverflow()} の姉妹品の @ref{147e,,PyLong_AsLongLongAndOverflow()} 関数が追加されました。両方とも Python @ref{19b,,int} を C ネイティブの固定幅型に変換しますが、変換が幅に合わないことを検出します (bpo-7767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7767})。

@item 
@ref{147f,,PyUnicode_CompareWithASCIIString()} 関数が、Python 文字列が `NUL' 終端である場合に「 `等しくない' 」を返すようになりました。

@item 
新しい関数 @ref{1480,,PyErr_NewExceptionWithDoc()} は @ref{1481,,PyErr_NewException()} と似ていますが、ドキュメンテーション文字列を受け付けます。これは C 拡張に、対応するピュア Python と同じ自己文書化 (self-documenting) 能力を与えます (bpo-7033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7033})。

@item 
@code{--with-valgrind} オプションとともにコンパイル時、 Valgrind のもとでの実行時に自動的に pymalloc アロケータが無効になるようになりました。ほかの状況では pymalloc は有利ですが、Valgrind 配下での実行時のメモリリーク検出では無効化したほうが良い結果が得られます (bpo-2422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2422})。

@item 
`PyArg_Parse' 関数から書式文字列 @code{O?} が削除されました。これはもう使われていませんし、今まで一度も文書化されたことはありません (bpo-8837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8837})。
@end itemize

There were a number of other small changes to the C-API.  See the
Misc/NEWS@footnote{https://github.com/python/cpython/blob/v3.2.6/Misc/NEWS}
file for a complete list.

Also, there were a number of updates to the Mac OS X build, see
Mac/BuildScript/README.txt@footnote{https://github.com/python/cpython/blob/v3.2.6/Mac/BuildScript/README.txt}
for details.  For users running a 32/64-bit
build, there is a known problem with the default Tcl/Tk on Mac OS X 10.6.
Accordingly, we recommend installing an updated alternative such as
ActiveState Tcl/Tk 8.5.9@footnote{https://web.archive.org/web/20101208191259/https://www.activestate.com/activetcl/downloads}.
See @indicateurl{https://www.python.org/download/mac/tcltk/} for additional details.

@node Python 3 2 への移植,,ビルドならびに C API の変更<5>,What's New In Python 3 2
@anchor{whatsnew/3 2 porting-to-python-3-2}@anchor{1482}
@subsection Python 3.2 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:


@itemize *

@item 
The @ref{26,,configparser} module has a number of clean-ups.  The major change is
to replace the old @code{ConfigParser} class with long-standing preferred
alternative @code{SafeConfigParser}.  In addition there are a number of
smaller incompatibilities:


@itemize *

@item 
補間 (interpolation) の構文は今では @ref{1483,,get()} と @ref{1484,,set()} の操作で検証されます。デフォルトの補間スキームでは、パーセント記号を使ったただ二つのトークンのみが正当です: @code{%(name)s} と @code{%%} 、後者はエスケープされたパーセント記号自身。

@item 
@ref{1484,,set()} メソッドと @ref{1485,,add_section()} メソッドは今ではその値が実際に文字列かどうかを検証します。以前はサポートされない型が意図せず持ち込まれる可能性がありました。

@item 
単一ソースからのセクションまたはオプションの複製 (重複) に対し、今では @ref{1486,,DuplicateSectionError} もしくは @ref{1487,,DuplicateOptionError} を投げます。以前は重複は黙って以前のエントリを上書きしていました。

@item 
インラインコメントは今ではデフォルトで無効なので、 `;' 文字を安全に値のなかで使えます。

@item 
コメントを字下げ出来るようになっています。このことにより、値が継続行となる場合の後続行の字下げ開始位置に `;' または `#' を置くには、補間を使う必要があります。こうすればコメントのプレフィクス文字が値内に現れて誤ってコメントと解釈されるのを防げます。

@item 
@code{""} は今では合法な値なので、もはや自動的に空文字列に変換されることはありません。空文字列のためには行内で @code{"option ="} と書いてください。
@end itemize

@item 
The @code{nntplib} module was reworked extensively, meaning that its APIs
are often incompatible with the 3.1 APIs.

@item 
@ref{344,,bytearray} オブジェクトはもうファイル名には使えません。代わりに @ref{192,,bytes} に変換しなければいけません。

@item 
The @code{array.tostring()} and @code{array.fromstring()} have been renamed to
@ref{1488,,array.tobytes()} and
@ref{1489,,array.frombytes()} for clarity.  The old names
have been deprecated. (See bpo-8990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8990}.)

@item 
@code{PyArg_Parse*()} 系関数:


@itemize *

@item 
書式文字列 "t#" の削除: 代わりに "s#" もしくは "s*" を使ってください。

@item 
書式文字列 "w" および "w#" の削除: 代わりに "w*" を使ってください。
@end itemize

@item 
The @code{PyCObject} type, deprecated in 3.1, has been removed.  To wrap
opaque C pointers in Python objects, the @ref{148a,,PyCapsule} API should be used
instead; the new type has a well-defined interface for passing typing safety
information and a less complicated signature for calling a destructor.

@item 
The @code{sys.setfilesystemencoding()} function was removed because
it had a flawed design.

@item 
@ref{148b,,random.seed()} 関数とメソッドが、salt に文字列やバイト列を与えた場合に内部で sha512 ハッシュ関数を使うようになりました。Python 3.1 シーケンスを再現するのに以前のバージョンの `seed' が必要であれば、 `version' 引数を `1' にしてください。 @code{random.seed(s, version=1)} のように。

@item 
The previously deprecated @code{string.maketrans()} function has been removed
in favor of the static methods @ref{148c,,bytes.maketrans()} and
@ref{148d,,bytearray.maketrans()}.  This change solves the confusion around which
types were supported by the @ref{d8,,string} module.  Now, @ref{169,,str},
@ref{192,,bytes}, and @ref{344,,bytearray} each have their own `maketrans' and
`translate' methods with intermediate translation tables of the appropriate
type.

(Contributed by Georg Brandl; bpo-5675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5675}.)

@item 
The previously deprecated @code{contextlib.nested()} function has been removed
in favor of a plain @ref{186,,with} statement which can accept multiple
context managers.  The latter technique is faster (because it is built-in),
and it does a better job finalizing multiple context managers when one of them
raises an exception:

@example
with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
    for line in infile:
        if '<critical>' in line:
            outfile.write(line)
@end example

(Georg Brandl と Mattias Brändström の貢献; appspot issue 53094@footnote{https://codereview.appspot.com/53094}.)

@item 
@ref{148e,,struct.pack()} は、文字列パックコード @code{s} で bytes のみを許容するようになりました。以前はテキスト引数を受け取って暗黙に UTF-8 でエンコードして bytes に変換していました。特定のエンコーディングを前提にするのは間違っていますし、可変長のエンコーディングは構造体の固定長セグメントへの書き込みで失敗しうるので、これは問題でした。

例えば @code{struct.pack('<6sHHBBB', 'GIF87a', x, y)} としているならば、テキストではなく bytes を使うように @code{struct.pack('<6sHHBBB', b'GIF87a', x, y)} と書き換えなければなりません。

(Discovered by David Beazley and fixed by Victor Stinner; bpo-10783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10783}.)

@item 
パース失敗時に @ref{12b,,xml.etree.ElementTree} クラスが @ref{148f,,xml.etree.ElementTree.ParseError} を投げるようになりました。以前は @ref{1490,,xml.parsers.expat.ExpatError} を投げていました。

@item 
浮動小数点数と複素数に対する @ref{169,,str()} が以前より長い表現をするようになったことで、古いフォーマットに依存する doctest は壊れるかもしれません。

@item 
@ref{4b7,,subprocess.Popen} の `close_fds' のデフォルトが、Unix では @code{True} になりました。Windows では 3 つの標準ストリームに @code{None} がセットされている場合には @code{True} 、以外の場合は @code{False} になりました。以前は `close_fds' のデフォルトはいつでも @code{False} でした。これは開いているファイル記述子が子プロセスに漏れた場合に解決が難しいバグや競合状態を生み出していました。

@item 
レガシーな HTTP 0.9 のサポートが @ref{111,,urllib.request} と @ref{73,,http.client} から削除されました。このサポートはサーバサイドではまだ健在です (@ref{76,,http.server} 内)。

(Contributed by Antoine Pitrou, bpo-10711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10711}.)

@item 
タイムアウトモード時の SSL ソケットでタイムアウトした場合に、汎用の @ref{1491,,SSLError} ではなく @ref{a35,,socket.timeout} を投げるようになりました。

(Contributed by Antoine Pitrou, bpo-10272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10272}.)

@item 
The misleading functions @code{PyEval_AcquireLock()} and
@code{PyEval_ReleaseLock()} have been officially deprecated.  The
thread-state aware APIs (such as @ref{647,,PyEval_SaveThread()}
and @ref{648,,PyEval_RestoreThread()}) should be used instead.

@item 
Due to security risks, @code{asyncore.handle_accept()} has been deprecated, and
a new function, @code{asyncore.handle_accepted()}, was added to replace it.

(Contributed by Giampaolo Rodola in bpo-6706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6706}.)

@item 
Due to the new @ref{164,,GIL} implementation, @code{PyEval_InitThreads()}
cannot be called before @ref{460,,Py_Initialize()} anymore.
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 1,What's New In Python 3 0,What's New In Python 3 2,What's New in Python
@anchor{whatsnew/3 1 doc}@anchor{1492}@anchor{whatsnew/3 1 translation-repo}@anchor{1493}@anchor{whatsnew/3 1 what-s-new-in-python-3-1}@anchor{1494}
@section What's New In Python 3.1


@*著者: 
Raymond Hettinger


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c % Patch 12345
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer.)
@c 
@c This saves the maintainer the effort of going through the SVN log
@c when researching a change.

This article explains the new features in Python 3.1, compared to 3.0.
Python 3.1 was released on June 27, 2009.

@menu
* PEP 372; 順序付き辞書: PEP 372 順序付き辞書. 
* PEP 378; 1000区切りのための書式指定子: PEP 378 1000区切りのための書式指定子. 
* その他の言語変更: その他の言語変更<13>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール: 新たなモジュール、改良されたモジュール、非推奨のモジュール<2>. 
* 最適化: 最適化<13>. 
* IDLE: IDLE<2>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<6>. 
* Python 3.1 への移植: Python 3 1 への移植. 

@end menu

@node PEP 372 順序付き辞書,PEP 378 1000区切りのための書式指定子,,What's New In Python 3 1
@anchor{whatsnew/3 1 pep-372-ordered-dictionaries}@anchor{1495}
@subsection PEP 372: 順序付き辞書


通常の Python 辞書は、 key/value ペアを不定の順序でイテレートします。何年にもわたり、いろいろな人が key の挿入順を保存する辞書の別実装を書いてきました。その経験に基づき、新しい @ref{7f3,,OrderedDict} クラスが導入されました。

OrderedDict API は通常の辞書と同じインターフェースを提供していますが、 key/value をイテレートするときに key が最初に挿入された順番になることが保証されています。新しいエントリが既存のエントリを上書きした場合は、元の挿入順序が保持されます。エントリを削除して再挿入すると、順序は一番最後に移動します。

標準ライブラリのいくつかのモジュールで、順序付き辞書の利用がサポートされています。@ref{26,,configparser} モジュールはデフォルトで順序付き辞書を使います。設定ファイルを読み込み、編集した後、元の順序で書きなおすことができます。@ref{4e0,,collections.namedtuple()} の `_asdict()' メソッドは、タプルの順序と同じ順序の順序付き辞書を返すようになりました。@ref{86,,json} モジュールのデコーダーが OrderedDict をビルドするのをサポートするために、 @ref{f43,,JSONDecoder} クラスのコンストラクタに `object_pairs_hook' 引数が追加されました。 PyYAML@footnote{https://pyyaml.org/} などの外部のライブラリでもサポートされています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 372

@item PEP 372@footnote{https://peps.python.org/pep-0372/} - 順序付き辞書

PEP written by Armin Ronacher and Raymond Hettinger.  Implementation
written by Raymond Hettinger.
@end table


順序付き辞書は挿入順序を記憶するので、ソートと組み合わせて使うことで、ソートされた辞書を作れます:

@example
>>> # regular unsorted dictionary
>>> d = @{'banana': 3, 'apple':4, 'pear': 1, 'orange': 2@}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
@end example

この新しい順序付き辞書は、項目が削除されてもソートされた順序を保持します。しかし、キーが追加されるとき、そのキーは最後に追加され、ソートは保持されません。

@node PEP 378 1000区切りのための書式指定子,その他の言語変更<13>,PEP 372 順序付き辞書,What's New In Python 3 1
@anchor{whatsnew/3 1 pep-378-format-specifier-for-thousands-separator}@anchor{1496}
@subsection PEP 378: 1000区切りのための書式指定子


組み込みの @ref{199,,format()} 関数と @ref{833,,str.format()} メソッドが使うミニ言語に、単純でロケールに依存しない 1000 区切りカンマの書式化が追加されました。これによって簡単にプログラムの出力を、その玄人ちっくな見た目を改善してひとさまにとって読みやすいものに出来ます:

@example
>>> format(1234567, ',d')
'1,234,567'
>>> format(1234567.89, ',.2f')
'1,234,567.89'
>>> format(12345.6 + 8901234.12j, ',f')
'12,345.600000+8,901,234.120000j'
>>> format(Decimal('1234567.89'), ',f')
'1,234,567.89'
@end example

これをサポートする型は @ref{19b,,int}, @ref{196,,float}, @ref{197,,complex} , @ref{1fe,,decimal.Decimal} です。

ドットやら空白やらアポストロフィやらあるいはアンダースコアなどの他のセパレータをどうやって指定するかの議論は水面下にありますが、ロケールに従う必要があるアプリケーションは、1000区切りセパレータについていくつかのサポートを既に持っている既存の `n' 指定子を使うべきです。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 378

@item PEP 378@footnote{https://peps.python.org/pep-0378/} - 1000区切りのための書式指定子

PEP written by Raymond Hettinger and implemented by Eric Smith and
Mark Dickinson.
@end table


@node その他の言語変更<13>,新たなモジュール、改良されたモジュール、非推奨のモジュール<2>,PEP 378 1000区切りのための書式指定子,What's New In Python 3 1
@anchor{whatsnew/3 1 other-language-changes}@anchor{1497}
@subsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
@code{__main__.py} を含むディレクトと zip アーカイブを、その名前をインタプリタに渡すことで直接実行出来るようになりました。そのディレクトリと zip ファイルは自動的に sys.path エントリの先頭に挿入されます。(Suggestion and initial patch by Andy Chu; revised patch by Phillip J. Eby and Nick Coghlan; bpo-1739468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739468}.)

@item 
@ref{19b,,int()} 型に @code{bit_length} メソッドが追加されました。
このメソッドはその値を二進数で表現するのに必要なビット数を返します:

@example
>>> n = 37
>>> bin(37)
'0b100101'
>>> n.bit_length()
6
>>> n = 2**123-1
>>> n.bit_length()
123
>>> (n+1).bit_length()
124
@end example

(Contributed by Fredrik Johansson, Victor Stinner, Raymond Hettinger,
and Mark Dickinson; bpo-3439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3439}.)

@item 
@ref{199,,format()} 文字列のフィールドに自動的に番号が振られるようになりました:

@example
>>> 'Sir @{@} of @{@}'.format('Gallahad', 'Camelot')
'Sir Gallahad of Camelot'
@end example

以前は、文字列は @code{'Sir @{0@} of @{1@}'} のようにフィールドに番号を振らなければなりませんでした。

(Contributed by Eric Smith; bpo-5237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5237}.)

@item 
The @code{string.maketrans()} function is deprecated and is replaced by new
static methods, @ref{148c,,bytes.maketrans()} and @ref{148d,,bytearray.maketrans()}.
This change solves the confusion around which types were supported by the
@ref{d8,,string} module. Now, @ref{169,,str}, @ref{192,,bytes}, and
@ref{344,,bytearray} each have their own `maketrans' and `translate'
methods with intermediate translation tables of the appropriate type.

(Contributed by Georg Brandl; bpo-5675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5675}.)

@item 
@ref{186,,with} 文のシンタックスは一つの文で複数のコンテキストマネージャを使えるようになりました:

@example
>>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
...     for line in infile:
...         if '<critical>' in line:
...             outfile.write(line)
@end example

With the new syntax, the @code{contextlib.nested()} function is no longer
needed and is now deprecated.

(Georg Brandl と Mattias Brändström の貢献; appspot issue 53094@footnote{https://codereview.appspot.com/53094}.)

@item 
@code{round(x, n)} は `x' が整数の場合、整数を返すようになりました。以前は浮動小数点を返していました:

@example
>>> round(1123, -2)
1100
@end example

(Contributed by Mark Dickinson; bpo-4707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4707}.)

@item 
Python now uses David Gay's algorithm for finding the shortest floating-point
representation that doesn't change its value.  This should help
mitigate some of the confusion surrounding binary floating-point
numbers.

The significance is easily seen with a number like @code{1.1} which does not
have an exact equivalent in binary floating point.  Since there is no exact
equivalent, an expression like @code{float('1.1')} evaluates to the nearest
representable value which is @code{0x1.199999999999ap+0} in hex or
@code{1.100000000000000088817841970012523233890533447265625} in decimal. That
nearest value was and still is used in subsequent floating-point
calculations.

What is new is how the number gets displayed.  Formerly, Python used a
simple approach.  The value of @code{repr(1.1)} was computed as @code{format(1.1,
'.17g')} which evaluated to @code{'1.1000000000000001'}. The advantage of
using 17 digits was that it relied on IEEE-754 guarantees to assure that
@code{eval(repr(1.1))} would round-trip exactly to its original value.  The
disadvantage is that many people found the output to be confusing (mistaking
intrinsic limitations of binary floating-point representation as being a
problem with Python itself).

新しいアルゴリズムでは @code{repr(1.1)} はより賢明で @code{'1.1'} を返します。実際的には、これは全ての等価な文字列表現 (前提となる同じ浮動小数点数に戻るもの) を探し、そして一番短い表現を返します。

新アルゴリズムは、可能な限りよりわかりやすい表現を生み出す傾向がありますが、元の値を変更しません。ですから @code{1.1 + 2.2 != 3.3} は表示がどうであれ、今でも問題です。

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.

(Contributed by Eric Smith and Mark Dickinson; bpo-1580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1580})
@end itemize

@node 新たなモジュール、改良されたモジュール、非推奨のモジュール<2>,最適化<13>,その他の言語変更<13>,What's New In Python 3 1
@anchor{whatsnew/3 1 new-improved-and-deprecated-modules}@anchor{1498}
@subsection 新たなモジュール、改良されたモジュール、非推奨のモジュール



@itemize *

@item 
シーケンスまたはイテラブル内にある一意な要素を数え上げるのに便利な @ref{12a3,,collections.Counter} クラスが追加されました:

@example
>>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
Counter(@{'blue': 3, 'red': 2, 'green': 1@})
@end example

(Contributed by Raymond Hettinger; bpo-1696199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1696199}.)

@item 
Tk のテーマ付きウィジェットへのアクセスを提供する、新しい @ref{ff,,tkinter.ttk} モジュールが追加されました。 @ref{ff,,tkinter.ttk} の基本的なアイディアは、拡張可能性のためにウィジェットの動作を実装するコードと見た目を記述するコードを分離することです。

(Contributed by Guilherme Polo; bpo-2983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2983}.)

@item 
@ref{65c,,gzip.GzipFile} と @ref{a66,,bz2.BZ2File} クラスはコンテキストマネジメントプロトコルをサポートするようになりました:

@example
>>> # Automatically close file after writing
>>> with gzip.GzipFile(filename, "wb") as f:
...     f.write(b"xxx")
@end example

(Contributed by Antoine Pitrou.)

@item 
@ref{3a,,decimal} モジュールが二進 @ref{196,,float} から decimal オブジェクトを生成するメソッドをサポートしました。
変換は正確ですが時に意外なことがあります:

@example
>>> Decimal.from_float(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
@end example

長い十進の結果が、 `1.1' を記憶するための現実の二進での端数を表しています。 `1.1' は二進数で正確に表現出来ないので、端数は十進表現でとても多くの桁数になっています。

(Contributed by Raymond Hettinger and Mark Dickinson.)

@item 
@ref{85,,itertools} に 2 つの関数が追加されました。 @ref{1499,,itertools.combinations_with_replacement()} 関数は、置換 (順列, permutation) や直積 (Cartesian product) を含む組合せ論の 4 つの生成関数のうちの 1 つです。 @ref{149a,,itertools.compress()} 関数は APL@footnote{https://ja.wikipedia.org/wiki/APL} の同名機能の模倣品です。また、既存の @ref{149b,,itertools.count()} 関数は新たにオプショナルな `step' 引数を取るようになり、そして数え方に @ref{213,,fractions.Fraction} や @ref{1fe,,decimal.Decimal} を含む任意の数値型を使えるようになりました。

@example
>>> [p+q for p,q in combinations_with_replacement('LOVE', 2)]
['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']

>>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0]))
[2, 3, 5, 7]

>>> c = count(start=Fraction(1,2), step=Fraction(1,6))
>>> [next(c), next(c), next(c), next(c)]
[Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)]
@end example

(Contributed by Raymond Hettinger.)

@item 
@ref{4e0,,collections.namedtuple()} が新たにキーワード引数 `rename' をサポートし、これにより不正なフィールド名を自動で _0, _1, ... といった位置による名前に変換することが出来ます。これはフィールド名が何か外部ソースに基いて作られる場合に有用です。例えば CSV のヘッダ、SQL のフィールドリスト、あるいはユーザ入力などです:

@example
>>> query = input()
SELECT region, dept, count(*) FROM main GROUPBY region, dept

>>> cursor.execute(query)
>>> query_fields = [desc[0] for desc in cursor.description]
>>> UserQuery = namedtuple('UserQuery', query_fields, rename=True)
>>> pprint.pprint([UserQuery(*row) for row in cursor])
[UserQuery(region='South', dept='Shipping', _2=185),
 UserQuery(region='North', dept='Accounting', _2=37),
 UserQuery(region='West', dept='Sales', _2=419)]
@end example

(Contributed by Raymond Hettinger; bpo-1818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1818}.)

@item 
@ref{5a3,,re.sub()}、@ref{5a4,,re.subn()} および @ref{5a2,,re.split()} 関数は flags 引数を受け取るようになりました。

(Contributed by Gregory Smith.)

@item 
logging を自身では使わずとも使用ライブラリがそうしているようなアプリケーションのために、 @ref{8b,,logging} モジュールが単純な @ref{149c,,logging.NullHandler} を実装しました。null ハンドラをセットアップすることは、 "No handlers could be found for logger foo" のような警告を抑制します。

@example
>>> h = logging.NullHandler()
>>> logging.getLogger("foo").addHandler(h)
@end example

(Contributed by Vinay Sajip; bpo-4384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4384}).

@item 
コマンドラインスイッチ @code{-m} をサポートしている @ref{c3,,runpy} がパッケージの実行をサポートするようになりました。パッケージ名が与えられると @code{__main__} サブモジュールを探し出して実行します。

(Contributed by Andi Vajda; bpo-4195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4195}.)

@item 
@ref{aa,,pdb} モジュールが @ref{138,,zipimport} (あるいはなにかほかの 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} 準拠ローダ) でロードされたモジュールのソースコードにアクセスでき、表示できるようになりました。

(Contributed by Alexander Belopolsky; bpo-4201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4201}.)

@item 
@ref{217,,functools.partial} オブジェクトが pickle 化出来るようになりました。
@end itemize

@quotation

(Suggested by Antoine Pitrou and Jesse Noller.  Implemented by
Jack Diederich; bpo-5228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5228}.)
@end quotation


@itemize *

@item 
シンボルのための @ref{ba,,pydoc} ヘルプトピックが追加されました。これで対話環境で @code{help('@@')} などが期待通りの働きをします (---訳注: 実装としては pydoc_data パッケージのこと。 @code{pydoc_data/topics.py} に docstring からは生成出来ない、シンボルについてのドキュメントが収められています  ---)。

(Contributed by David Laban; bpo-4739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4739}.)

@item 
@ref{10c,,unittest} に特定のテストメソッドやテストクラス全体をスキップする仕組みのサポートが追加されました。さらに、この機能はテスト結果を「意図的な失敗」とすることができ、テストが失敗しても @code{TestResult} の失敗数にはカウントされなくなります:

@example
class TestGizmo(unittest.TestCase):

    @@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_gizmo_on_windows(self):
        ...

    @@unittest.expectedFailure
    def test_gimzo_without_required_library(self):
        ...
@end example

また例外についてのテストが、 @ref{186,,with} 文で使えるコンテキストマネージャとして増強されました:

@example
def test_division_by_zero(self):
    with self.assertRaises(ZeroDivisionError):
        x / 0
@end example

In addition, several new assertion methods were added including
@ref{149d,,assertSetEqual()},
@ref{149e,,assertDictEqual()},
@code{assertDictContainsSubset()},
@ref{149f,,assertListEqual()},
@ref{14a0,,assertTupleEqual()},
@ref{14a1,,assertSequenceEqual()},
@ref{752,,assertRaisesRegexp()},
@ref{14a2,,assertIsNone()},
and @ref{14a3,,assertIsNotNone()}.

(Contributed by Benjamin Peterson and Antoine Pitrou.)

@item 
The @ref{83,,io} module has three new constants for the @ref{14a4,,seek()}
method: @ref{14a5,,SEEK_SET}, @ref{14a6,,SEEK_CUR}, and @ref{14a7,,SEEK_END}.

@item 
@ref{8af,,sys.version_info} タプルが名前付きタプルになりました。

@example
>>> sys.version_info
sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)
@end example

(Contributed by Ross Light; bpo-4285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4285}.)

@item 
The @code{nntplib} and @ref{78,,imaplib} modules now support IPv6.

(Contributed by Derek Morr; bpo-1655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1655} and bpo-1664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1664}.)

@item 
@ref{ab,,pickle} を、プロトコル 2 以下を使う際に Python 2.x との相互運用に順応するようにしました。標準ライブラリの再編成はたくさんのオブジェクトへの公式な参照を変えました。例えば Python 2 の @code{__builtin__.set} は Python 3 では @code{builtins.set} です。この変化は異なる Python バージョン間でのデータ共有の取り組みを複雑にしました。ですが今回のこの修正により、プロトコル 2 以下を選んだ場合は pickler は自動的にロード時もダンプ時も古い Python 2 命名を使うようになります。この再マッピングはデフォルトで有効になりますが、 `fix_imports' オプションで無効に出来ます:

@example
>>> s = @{1, 2, 3@}
>>> pickle.dumps(s, protocol=0)
b'c__builtin__\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
>>> pickle.dumps(s, protocol=0, fix_imports=False)
b'cbuiltins\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
@end example

不幸にも、そして避けられないこの変更による副作用は、Python 3.1 によって生成されたプロトコル 2 pickle が Python 3.0 で読めなくなるであろうことです。Python 2.x との互換性を維持するつもりがないのであれば、Python 3.x 実装間でのデータ移行では最新 pickle プロトコルバージョン 3 を使うべきです。

(Contributed by Alexandre Vassalotti and Antoine Pitrou, bpo-6137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6137}.)

@item 
新規モジュール @ref{7b,,importlib} が追加されました。 @ref{7f8,,import} 文とその相棒の @ref{ad1,,__import__()} 関数の、完全で移植性が高いピュア Python 参照実装を提供しています。これはインポートで行う動作の文書化と定義における、確かな前進です。

(Contributed by Brett Cannon.)
@end itemize

@node 最適化<13>,IDLE<2>,新たなモジュール、改良されたモジュール、非推奨のモジュール<2>,What's New In Python 3 1
@anchor{whatsnew/3 1 optimizations}@anchor{14a8}
@subsection 最適化


大きな性能向上がありました:


@itemize *

@item 
The new I/O library (as defined in 
@geindex Python Enhancement Proposals; PEP 3116
PEP 3116@footnote{https://peps.python.org/pep-3116/}) was mostly written in
Python and quickly proved to be a problematic bottleneck in Python 3.0.
In Python 3.1, the I/O library has been entirely rewritten in C and is
2 to 20 times faster depending on the task at hand. The pure Python
version is still available for experimentation purposes through
the @code{_pyio} module.

(Contributed by Amaury Forgeot d'Arc and Antoine Pitrou.)

@item 
Added a heuristic so that tuples and dicts containing only untrackable objects
are not tracked by the garbage collector. This can reduce the size of
collections and therefore the garbage collection overhead on long-running
programs, depending on their particular use of datatypes.

(Contributed by Antoine Pitrou, bpo-4688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4688}.)

@item 
Enabling a configure option named @code{--with-computed-gotos}
on compilers that support it (notably: gcc, SunPro, icc), the bytecode
evaluation loop is compiled with a new dispatch mechanism which gives
speedups of up to 20%, depending on the system, the compiler, and
the benchmark.

(Contributed by Antoine Pitrou along with a number of other participants,
bpo-4753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4753}).

@item 
UTF-8, UTF-16 ならびに LATIN-1 のデコーディングが2から4倍速くなりました。

(Antoine Pitrou と Amaury Forgeot d'Arc の貢献, bpo-4868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4868}.)

@item 
The @ref{86,,json} module now has a C extension to substantially improve
its performance.  In addition, the API was modified so that json works
only with @ref{169,,str}, not with @ref{192,,bytes}.  That change makes the
module closely match the JSON specification@footnote{https://json.org/}
which is defined in terms of Unicode.

(Contributed by Bob Ippolito and converted to Py3.1 by Antoine Pitrou
and Benjamin Peterson; bpo-4136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4136}.)

@item 
Unpickling now interns the attribute names of pickled objects.  This saves
memory and allows pickles to be smaller.

(Contributed by Jake McGuire and Antoine Pitrou; bpo-5084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5084}.)
@end itemize

@node IDLE<2>,ビルドならびに C API の変更<6>,最適化<13>,What's New In Python 3 1
@anchor{whatsnew/3 1 idle}@anchor{14a9}
@subsection IDLE



@itemize *

@item 
IDLE のフォーマットメニューに、ソースコードから末尾の空白を取り除くことが出来るオプションが追加されました。

(Contributed by Roger D. Serwy; bpo-5150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5150}.)
@end itemize

@node ビルドならびに C API の変更<6>,Python 3 1 への移植,IDLE<2>,What's New In Python 3 1
@anchor{whatsnew/3 1 build-and-c-api-changes}@anchor{14aa}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
整数の内部格納方式が @code{2**15} ベースと @code{2**30} ベースのいずれかになりました。
これはビルド時に決定されます。
以前は常に @code{2**15} ベースで格納されていました。
@code{2**30} ベースにすると 64 bit マシンでは性能が有意に向上しますが、 32 bit マシンでのベンチマーク結果には向上も低下もあります。
そのため、デフォルトでは 64 bit マシンで @code{2**30} ベースを、 32 bit マシンで @code{2**15} ベースを使用します。
Unix では新たな configure オプション @code{--enable-big-digits} が追加されました。
これにより上記のデフォルトを上書き出来ます。

この変更は性能向上以外ではエンドユーザには分からないはずですが、例外が1つあります。
テストおよびデバッグ目的で内部形式の情報を提供する @ref{14ab,,sys.int_info} が追加されましたが、これにより数字あたりのビット数と各数字の格納に使われる C の型のバイトサイズが分かります:

@example
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
@end example

(Contributed by Mark Dickinson; bpo-4258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4258}.)

@item 
@ref{14ac,,PyLong_AsUnsignedLongLong()} 関数は負の `pylong' に対し @ref{198,,TypeError} ではなく @ref{a81,,OverflowError} を送出するようになりました。

(Contributed by Mark Dickinson and Lisandro Dalcrin; bpo-5175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5175}.)

@item 
@code{PyNumber_Int()} が非推奨になりました。代わりに @ref{c5d,,PyNumber_Long()} を使用してください。

(Contributed by Mark Dickinson; bpo-4910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4910}.)

@item 
非推奨の関数 @code{PyOS_ascii_strtod()} および @code{PyOS_ascii_atof()} を置き換えるために新しく @ref{14ad,,PyOS_string_to_double()} 関数が追加されました。

(Contributed by Mark Dickinson; bpo-5914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5914}.)

@item 
@code{PyCObject} API を置き換えるものとして、 @ref{148a,,PyCapsule} が追加されました。主な違いとしては、新しい型は、型安全に情報を渡すための良く定義されたインターフェースを持ち、また、デストラクタの呼び出しのシグネチャの複雑さが小さくなっています。古い型は問題のある API で、今では非推奨です。

(Contributed by Larry Hastings; bpo-5630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5630}.)
@end itemize

@node Python 3 1 への移植,,ビルドならびに C API の変更<6>,What's New In Python 3 1
@anchor{whatsnew/3 1 porting-to-python-3-1}@anchor{14ae}
@subsection Python 3.1 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:


@itemize *

@item 
The new floating-point string representations can break existing doctests.
For example:

@example
def e():
    '@w{'}'Compute the base of natural logarithms.

    >>> e()
    2.7182818284590451

    '@w{'}'
    return sum(1/math.factorial(x) for x in reversed(range(30)))

doctest.testmod()

**********************************************************************
Failed example:
    e()
Expected:
    2.7182818284590451
Got:
    2.718281828459045
**********************************************************************
@end example

@item 
pickle モジュールがプロトコルバージョン 2 以下で自動的に名前の再対応付けを行うので、Python 3.1 で pickle 化すると Python 3.0 で読めなくなります。一つの解決策はプロトコル 3 を使うことです。もう一つは `fix_imports' オプションを @code{False} にセットすることです。上述の議論を参照してください。
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New In Python 3 0,What's New in Python 2 7,What's New In Python 3 1,What's New in Python
@anchor{whatsnew/3 0 doc}@anchor{14af}@anchor{whatsnew/3 0 translation-repo}@anchor{14b0}@anchor{whatsnew/3 0 what-s-new-in-python-3-0}@anchor{14b1}
@section What's New In Python 3.0


@c XXX Add trademark info for Apple, Microsoft.

@*著者: 
Guido van Rossum


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.  (Note: I didn't get to this for 3.0.
@c GvR.)
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.  (Due to time
@c constraints I haven't managed to do this for 3.0.  GvR.)
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c % Patch 12345
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer.)
@c 
@c This saves the maintainer the effort of going through the SVN log
@c when researching a change.  (Again, I didn't get to this for 3.0.
@c GvR.)

この記事では 2.6 と比較した Python 3.0 での新機能を解説します。
Python 3.0、あるいは "Python 3000"、 "Py3K" は初めて `意図的に後方非互換にした' Python のリリースです。
Python 3.0 は2008年12月3日にリリースされました。
通常のリリースよりも多くの変更があり、全ての Python ユーザにとって重要です。
しかし、変更について理解したら Python に実際にはそれほど変更がないことが分かるでしょう。
全体的に見れば、よく知られた悩みの種が概ね解決され、昔の粗雑なものが取り除かれています。

この記事は全ての新機能を完璧な仕様を示そうとはしませんが、便利な概要については説明しようとしています。
全詳細については Python 3.0 のドキュメントや、本編で引かれている多くの PEP を参照してください。
特定の機能の実装や設計原理について完全に理解したいなら、通常のドキュメントよりも詳しいことが書いてある PEP を見るとよいでしょう。
しかし、一旦機能が完全に実装されると、普通 PEP は最新の状態に保たれないことに注意してください。

この文書で全項目に触れるべきなのですが、時間の制約のためそうではありません。
いつもの新リリースのように、 ソース配布の @cite{Misc/NEWS} には些細な変更についても詳細な情報があります。

@c Compare with previous release in 2 - 3 sentences here.

@c add hyperlink when the documentation becomes available online.

@c ======================================================================

@c Large, PEP-level features and changes should be described here.

@c Should there be a new section here for 3k migration?

@c Or perhaps a more general section describing module changes/deprecation?

@c sets module deprecated

@c ======================================================================

@menu
* よくある悩みの種:: 
* 構文の変更の概要:: 
* Python 2.6 で既にあった変更: Python 2 6 で既にあった変更. 
* ライブラリの変更:: 
* PEP 3101; 文字列整形の新たなアプローチ: PEP 3101 文字列整形の新たなアプローチ. 
* 例外に関する変更:: 
* その他の変更: その他の変更<2>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<7>. 
* 性能:: 
* Python 3.0 への移植: Python 3 0 への移植. 

@end menu

@node よくある悩みの種,構文の変更の概要,,What's New In Python 3 0
@anchor{whatsnew/3 0 common-stumbling-blocks}@anchor{14b2}
@subsection よくある悩みの種


このセクションは Python 2.5 に慣れていたら躓いてしまいそうな少数の変更の一覧です。

@menu
* print関数:: 
* リストからビューおよびイテレータへ:: 
* 順序比較:: 
* 整数:: 
* Unicode 対 8 ビット、ではなく、テキスト対データに:: 

@end menu

@node print関数,リストからビューおよびイテレータへ,,よくある悩みの種
@anchor{whatsnew/3 0 print-is-a-function}@anchor{14b3}
@subsubsection print関数


@code{print} 文は @ref{1177,,print()} 関数に置き換えられ、古い @code{print} 文の特殊な文法の殆どがキーワード引数で置き換えられています (
@geindex Python Enhancement Proposals; PEP 3105
PEP 3105@footnote{https://peps.python.org/pep-3105/})。 例:

@example
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!
@end example

項目間の区切りをカスタマイズすることもできます。例:

@example
print("There are <", 2**32, "> possibilities!", sep="")
@end example

これは以下を出力します :

@example
There are <4294967296> possibilities!
@end example

注釈:


@itemize *

@item 
@ref{1177,,print()} 関数は、古い @code{print} 文の "ソフトスペース" 機能をサポートしません。例えば Python 2.x では、 @code{print "A\n", "B"} は @code{"A\nB\n"} を出力していましたが、 Python 3.0 では、 @code{print("A\n", "B")} は @code{"A\n B\n"} を出力します。

@item 
最初は、対話モードで古い @code{print x} を何回もタイプしてしまうでしょう。代わりに @code{print(x)} とタイプするよう再教育してください。

@item 
@code{2to3} ソース変換ツールを使うと、すべての @code{print} 文が @ref{1177,,print()} 関数呼び出しに自動的に置換されるので、大きなプロジェクトでもさほど問題にならないでしょう。
@end itemize

@node リストからビューおよびイテレータへ,順序比較,print関数,よくある悩みの種
@anchor{whatsnew/3 0 views-and-iterators-instead-of-lists}@anchor{14b4}
@subsubsection リストからビューおよびイテレータへ


いくつかの良く使われている API はもはやリストを返しません:


@itemize *

@item 
@ref{183,,dict} の @ref{9d0,,dict.keys()}, @ref{9d2,,dict.items()} そして @ref{9d1,,dict.values()} メソッドはリストの代わりに "views" を返します。 例えば: @code{k = d.keys(); k.sort()} は上手く動きません。 代わりに @code{k = sorted(d)} を使ってください (これは Python 2.5 でも動作し、効率的です)。

@item 
Also, the @code{dict.iterkeys()}, @code{dict.iteritems()} and
@code{dict.itervalues()} methods are no longer supported.

@item 
@ref{19f,,map()} と @ref{a64,,filter()} はイテレータを返します。もしも本物のリストが必要で、全ての入力シーケンスが同じ長さの場合であれば、簡単に直すなら @ref{19f,,map()} を @ref{24d,,list()} で包みます。例えば @code{list(map(...))} という具合。ですがより良いのは、大抵はリスト内包を使うことです (特に元々のコードが @ref{14b5,,lambda} を使っている場合)。あるいはコードを、リストを全く必要としないように書き換えましょう。とりわけトリッキーなのは、関数に副作用を起こさせるために呼び出される @ref{19f,,map()} です; この場合確実な変換は普通に @ref{34a,,for} ループを使うことです (そもそもリストを作ること自体が無駄遣いでしょう)。

入力シーケンスの長さが同じとは限らないならば、 @ref{19f,,map()} は最も短いシーケンスが消費されつくすと処理をやめます。Python 2.x での @ref{19f,,map()} 用法と全く互換にするにはシーケンスを @ref{14b6,,itertools.zip_longest()} で包んでください。例えば @code{map(func, *sequences)} を @code{list(map(func, itertools.zip_longest(*sequences)))} とします。

@item 
@ref{b3d,,range()} now behaves like @code{xrange()} used to behave, except
it works with values of arbitrary size.  The latter no longer
exists.

@item 
@ref{1a0,,zip()} はイテレータを返します。
@end itemize

@node 順序比較,整数,リストからビューおよびイテレータへ,よくある悩みの種
@anchor{whatsnew/3 0 ordering-comparisons}@anchor{14b7}
@subsubsection 順序比較


Python 3.0 で順序比較のルールが簡単になりました。


@itemize *

@item 
順序比較演算子 (@code{<}, @code{<=}, @code{>=}, @code{>})  は、そのオペランドが自然な順序づけを持たない場合 TypeError 例外を送出します。  @code{1 < '@w{'}}, @code{0 > None} または @code{len <= len} のような式は無効になり、 @code{None < None} は @code{False} を返す代わりに @ref{198,,TypeError} を送出します。その結果、 不均一なリスト（訳注：比較不能な型からなる要素が混在するリスト）のソートは意味がなくなりました。 -- 全ての要素は互いに比較できなければなりません。これは @code{==} と @code{!=} 演算子には適用されないことに注意してください: 別々の比較不可能な型のオブジェクトを比較すると常に、互いに等しくないと評価されます。

@item 
@ref{dc7,,sorted()} and @ref{dc8,,list.sort()} 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".

@item 
The @code{cmp()} function should be treated as gone, and the @code{__cmp__()}
special method is no longer supported.  Use @ref{14b8,,__lt__()} for sorting,
@ref{cf2,,__eq__()} with @ref{cf3,,__hash__()}, and other rich comparisons as needed.
(If you really need the @code{cmp()} functionality, you could use the
expression @code{(a > b) - (a < b)} as the equivalent for @code{cmp(a, b)}.)
@end itemize

@node 整数,Unicode 対 8 ビット、ではなく、テキスト対データに,順序比較,よくある悩みの種
@anchor{whatsnew/3 0 integers}@anchor{14b9}
@subsubsection 整数



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 237
PEP 237@footnote{https://peps.python.org/pep-0237/}: Essentially, @code{long} renamed to @ref{19b,,int}.
That is, there is only one built-in integral type, named
@ref{19b,,int}; but it behaves mostly like the old @code{long} type.

@item 
@geindex Python Enhancement Proposals; PEP 238
PEP 238@footnote{https://peps.python.org/pep-0238/}: An expression like @code{1/2} returns a float.  Use
@code{1//2} to get the truncating behavior.  (The latter syntax has
existed for years, at least since Python 2.2.)

@item 
The @code{sys.maxint} constant was removed, since there is no
longer a limit to the value of integers.  However, @ref{13dd,,sys.maxsize}
can be used as an integer larger than any practical list or string
index.  It conforms to the implementation's "natural" integer size
and is typically the same as @code{sys.maxint} in previous releases
on the same platform (assuming the same build options).

@item 
long 整数の @ref{1c1,,repr()} はもはや末尾に @code{L} を持ちません。そのため、無条件に "L" を取り除くコードは代わりに最後の数字を取り除いてしまうでしょう。 (代わりに @ref{169,,str()} を使用してください。)

@item 
8進数リテラルが @code{0720} の形でなくなりました。代わりに @code{0o720} を使ってください。
@end itemize

@node Unicode 対 8 ビット、ではなく、テキスト対データに,,整数,よくある悩みの種
@anchor{whatsnew/3 0 text-vs-data-instead-of-unicode-vs-8-bit}@anchor{14ba}
@subsubsection Unicode 対 8 ビット、ではなく、テキスト対データに


バイナリと Unicode について知っていると思っている全てが変わりました。


@itemize *

@item 
Python 3.0 でのコンセプトは、Unicode 文字列と 8 ビット文字列、という対比ではなくて、 `テキスト' と (バイナリ) `データ' の違いと考える、というものです。全てのテキストは Unicode です; 一方で `エンコードされた' Unicode はバイナリデータとして表現されます。テキストを保持するのに使われる型は @ref{169,,str} で、データには @ref{192,,bytes} を使います。2.x での状況との最大の違いは、Python 3.0 でテキストとデータを混ぜようとすれば @ref{198,,TypeError} となることです。Python 2.x では Unicode と 8 ビット文字列を混ぜたとすれば、8 ビット文字列がたまたま 7 ビット (ASCII) バイトだけから出来ていれば動くし非 ASCII バイトがあれば @ref{c08,,UnicodeDecodeError} となっていたでしょう。この、データ値に依存した振る舞いが、何年にも渡って夥しい数の悲劇を生み出していました。

@item 
As a consequence of this change in philosophy, pretty much all code
that uses Unicode, encodings or binary data most likely has to
change.  The change is for the better, as in the 2.x world there
were numerous bugs having to do with mixing encoded and unencoded
text.  To be prepared in Python 2.x, start using @code{unicode}
for all unencoded text, and @ref{169,,str} for binary or encoded data
only.  Then the @code{2to3} tool will do most of the work for you.

@item 
Unicode テキストのリテラルに @code{u"..."} を使うことはもはやできません。しかし、バイナリーデータのリテラルには @code{b"..."} を使わなければなりません。(---訳注: この @code{u"..."} は Python 3.3 で再び使えるようになりました。 ---)

@item 
@ref{169,,str} 型と @ref{192,,bytes} 型を混ぜて使うことは出来ませんから、それらはいつでも明示的に変換しなければいけません。 @ref{169,,str} から @ref{192,,bytes} にするには @ref{ad2,,str.encode()} を使ってください。そして @ref{192,,bytes} から @ref{169,,str} にするには @ref{ad3,,bytes.decode()} を使います。それぞれ @code{bytes(s, encoding=...)} 、 @code{str(b, encoding=...)} を使うことも出来ます。

@item 
Like @ref{169,,str}, the @ref{192,,bytes} type is immutable.  There is a
separate `mutable' type to hold buffered binary data,
@ref{344,,bytearray}.  Nearly all APIs that accept @ref{192,,bytes} also
accept @ref{344,,bytearray}.  The mutable API is based on
@ref{4bf,,collections.MutableSequence}.

@item 
raw 文字列リテラル内にある全てのバックスラッシュが「字句通り」に解釈されます。つまり @code{'\U'} も @code{'\u'} も、 raw 文字列内にあっては何ら特別に扱われないということです。例えば @code{r'\u20ac'} は Python 3.0 では 6 文字の文字列です。Python 2.x では @code{ur'\u20ac'} が単一の「ユーロ」文字であったのにです。(無論この変更は raw 文字列リテラルについてだけのもので、ユーロ文字は Python 3.0 で @code{'\u20ac'} です。)

@item 
The built-in @code{basestring} abstract type was removed.  Use
@ref{169,,str} instead.  The @ref{169,,str} and @ref{192,,bytes} types
don't have functionality enough in common to warrant a shared base
class.  The @code{2to3} tool (see below) replaces every occurrence of
@code{basestring} with @ref{169,,str}.

@item 
テキストファイルとして開かれたファイル (これは従来どおり @ref{316,,open()} でのデフォルトのモード) は、 (メモリ内の) 文字列と (ディスクでの) バイト列との写像をするのに、常にエンコーディングを使います。バイナリファイル (モードに @code{b} を付けて開いたもの) はメモリ内では常にバイト列を使います。このことで、もしもファイルが誤ったモードやエンコーディングで開かれようとすると、I/O はきっと口やかましく失敗します。こっそり正しくないデータを生み出すのではなく。それに加えて、ファイルを開く際には Unix ユーザでさえもこれからは、 (テキストかバイナリかの) 正しいモードを選択する必要があるということです。プラットフォームにはそれ特有のデフォルトエンコーディングがあります。Unix 的プラットフォームではこれは環境変数 @code{LANG} にセットされているかもしれません (あるいは時々ほかのプラットフォーム特有の、ロケールに関係した環境変数にもセットされています)。全てとは言いませんが多くの場合は、システムのデフォルトは UTF-8 です; ですが決してこのデフォルトを当てにすべきではありません。純粋な ASCII テキスト以上のものを読み書きするどんなアプリケーションも、きっとエンコーディングをオーバライド出来る手段を持つべきです。 @ref{1c,,codecs} 内にあるエンコーディングを熟知したストリームを使うことは、今ではもう必要なくなりました。

@item 
@ref{75f,,sys.stdin}, @ref{ccd,,sys.stdout}, @ref{b33,,sys.stderr} の初期値はいまでは Unicode のみのテキストファイルです (つまりそれらは @ref{8a4,,io.TextIOBase} のインスタンスです)。バイト列データをそれらのストリームで読み書きするには、 @ref{14bb,,io.TextIOBase.buffer} 属性を使う必要があります。

@item 
ファイル名は、API へは (Unicode) 文字列を渡し、 (Unicode) 文字列が返ります。これにはプラットフォーム特有の問題があるかもしれません。というのも、いくつかのプラットフォームではファイル名は任意のバイト文字列だからです。(他方では、Windows ではファイル名はネイティブに Unicode で格納されています。) 次善策として、ほとんどの API (たとえば @ref{316,,open()} と @ref{a5,,os} モジュール内の多くの関数) はファイル名として、文字列だけでなく @ref{192,,bytes} を受け付け、そして少しの API は @ref{192,,bytes} を返すかどうかを要求出来る手段を持っています。それゆえに @ref{1312,,os.listdir()} は引数が @ref{192,,bytes} インスタンスであれば @ref{192,,bytes} のリストで返し、 @ref{c82,,os.getcwdb()} はカレントディレクトリを @ref{192,,bytes} で返します。 @ref{1312,,os.listdir()} が文字列のリストで返す際、適切にデコード出来ないファイル名は @ref{462,,UnicodeError} とはせずに無視されることにご注意ください。

@item 
@ref{259,,os.environ} や @ref{147c,,sys.argv} のようないくつかのシステム API にも問題がありえます。システムにより利用可能とされるべきバイト列がデフォルトエンコーディングで解釈不能な場合です。環境変数 @code{LANG} をセットしてプログラムを再実行することが、おそらく最善のアプローチです。

@item 
@geindex Python Enhancement Proposals; PEP 3138
PEP 3138@footnote{https://peps.python.org/pep-3138/}: 文字列への @ref{1c1,,repr()} はもう非 ASCII 文字をエスケープしません。ただし、制御文字、Unicode 標準で印字不可状態のコードポイントは今でもエスケープされます。

@item 
@geindex Python Enhancement Proposals; PEP 3120
PEP 3120@footnote{https://peps.python.org/pep-3120/}: ソースのエンコードのデフォルトが UTF-8 になりました。

@item 
@geindex Python Enhancement Proposals; PEP 3131
PEP 3131@footnote{https://peps.python.org/pep-3131/}: 非 ASCII 文字を識別子として使用することが出来るようになりました。 (そうはいっても標準ライブラリは、コメント内での貢献者の名前以外では ASCII だけのままです。)

@item 
@code{StringIO} および @code{cStringIO} モジュールは廃止されました。その代わり @ref{83,,io} モジュールをインポートして、テキストやデータには @ref{112a,,io.StringIO} や @ref{10a4,,io.BytesIO} を使用してください。

@item 
@ref{14bc,,Unicode HOWTO} を参照してください。Python 3.0 向けに更新されました。
@end itemize

@node 構文の変更の概要,Python 2 6 で既にあった変更,よくある悩みの種,What's New In Python 3 0
@anchor{whatsnew/3 0 overview-of-syntax-changes}@anchor{14bd}
@subsection 構文の変更の概要


このセクションは Python 3.0 における全ての `構文の' 変更についての簡単な概要です。

@menu
* 新たな構文:: 
* 変更された構文:: 
* 削除された操作:: 

@end menu

@node 新たな構文,変更された構文,,構文の変更の概要
@anchor{whatsnew/3 0 new-syntax}@anchor{14be}
@subsubsection 新たな構文



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 3107
PEP 3107@footnote{https://peps.python.org/pep-3107/}: Function argument and return value annotations.  This
provides a standardized way of annotating a function's parameters
and return value.  There are no semantics attached to such
annotations except that they can be introspected at runtime using
the @ref{458,,__annotations__} attribute.  The intent is to
encourage experimentation through metaclasses, decorators or frameworks.

@item 
@geindex Python Enhancement Proposals; PEP 3102
PEP 3102@footnote{https://peps.python.org/pep-3102/}: キーワード専用引数。
パラメータリスト中で @code{*args} のあとに現れる名前付きパラメータは、呼び出す際には `必ず' キーワード引数の構文を使う必要があります (---訳注: @code{def fun(*a, kw):} という定義で @code{fun(1, 2, 3)} は NG で @code{fun(1, 2, kw=3)} としなければならない。ここまでは 2.x と同じ ---)。
この PEP により、可変引数リストを受け取らずにキーワード専用引数だけを許したい場合にそれを主張するために剥き出しの @code{*} をパラメータリスト内に書けるようになりました (---訳注: @code{def fun(*, kw):} と定義出来る。この定義では @code{fun(kw=1)} としてしか呼び出せない。 @code{fun(1)} はダメ。---)。

@item 
クラス定義内で、基底クラスのリストのあとでキーワード引数が許されるようになりました。これは metaclass を指定するための新しい規約 (次セクション参照) に使われるものですが、 metaclass サポートだけのためだけでなく他の目的に使うことも出来ます。

@item 
@geindex Python Enhancement Proposals; PEP 3104
PEP 3104@footnote{https://peps.python.org/pep-3104/}: @ref{14bf,,nonlocal} 文。 @code{nonlocal x} を使うと外側の (ただしグローバルでない) スコープから、直接変数を代入することが出来るようになります。 @code{nonlocal} は新しく予約語になりました。

@item 
@geindex Python Enhancement Proposals; PEP 3132
PEP 3132@footnote{https://peps.python.org/pep-3132/}: 拡張されたイテレータのアンパック。 @code{a, b, *rest = some_sequence} のようなことを書けるようになりました。 @code{*rest, a = stuff} も出来ます。 @code{rest} オブジェクトは常に (空かもしれなくても) リストです; 右辺には任意のイテラブルを置けます。例えば:

@example
(a, *rest, b) = range(5)
@end example

これは `a' に @code{0} を、 `b' に @code{4} を、そして `rest' に @code{[1, 2, 3]} をセットします。

@item 
辞書内包表記: @code{@{k: v for k, v in stuff@}} は @code{dict(stuff)} と同じ意味ですが、より柔軟です。 (これは 
@geindex Python Enhancement Proposals; PEP 274
PEP 274@footnote{https://peps.python.org/pep-0274/} で支持されています。)

@item 
セットリテラル、例えば @code{@{1, 2@}}。@code{@{@}} は空の辞書であることに注意してください。空のセットには @code{set()} を使用してください。セットの内包表記もサポートされました。例えば @code{@{x for x in stuff@}} は @code{set(stuff)} と同じ意味ですが、より柔軟です。

@item 
新たな8進数リテラル、e.g. @code{0o720} (2.6 で既にありました)。古い8進数リテラル (@code{0720}) は廃止されました。

@item 
新たなバイナリリテラル、e.g. @code{0b1010} (2.6 で既にありました) と、関連する新しい組み込み関数 @ref{14c0,,bin()} が導入されました。

@item 
@code{b} または @code{B} で始まるバイトリテラルと、関連する新しい組み込み関数 @ref{192,,bytes()} が導入されました。
@end itemize

@node 変更された構文,削除された操作,新たな構文,構文の変更の概要
@anchor{whatsnew/3 0 changed-syntax}@anchor{14c1}
@subsubsection 変更された構文



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 3109
PEP 3109@footnote{https://peps.python.org/pep-3109/} と 
@geindex Python Enhancement Proposals; PEP 3134
PEP 3134@footnote{https://peps.python.org/pep-3134/}: 新たな @ref{803,,raise} 文のシンタックス: @code{raise [@var{expr} [from @var{expr}]]}。以下を参照してください。

@item 
@code{as} と @ref{186,,with} は予約語になりました。 (実際には 2.6 から)

@item 
@code{True}、@code{False}、および @code{None} が予約語になりました。(2.6 では既に @code{None} が部分的に制限されていました)

@item 
Change from @ref{1ab,,except} `exc', `var' to
@code{except} `exc' @code{as} `var'.  See 
@geindex Python Enhancement Proposals; PEP 3110
PEP 3110@footnote{https://peps.python.org/pep-3110/}.

@item 
@geindex Python Enhancement Proposals; PEP 3115
PEP 3115@footnote{https://peps.python.org/pep-3115/}: 新たなメタクラスのシンタックス．以下の;

@example
class C:
    __metaclass__ = M
    ...
@end example

代わりに次のようにしてください:

@example
class C(metaclass=M):
    ...
@end example

The module-global @code{__metaclass__} variable is no longer
supported.  (It was a crutch to make it easier to default to
new-style classes without deriving every class from
@ref{c7e,,object}.)

@item 
リスト内包表記はもう @code{[... for @var{var} in @var{item1}, @var{item2}, ...]} という構文形をサポートしません。代わりに @code{[... for @var{var} in (@var{item1}, @var{item2}, ...)]} を使用してください。また、リスト内包表記は異なるセマンティクスを持つことに注意してください。リスト内包表記は @ref{24d,,list()} コンストラクタ内のジェネレータ式の糖衣構文に近く、特にループの制御変数はスコープ外ではもう使用することができません。

@item 
`ellipsis' (@code{...}) はどこででも原子的な式として使うことが出来ます。
(以前はスライス内でのみ許されていました。)
また、@code{...} と書かなければ `ならなく' なりました。
(以前は文法の些細な偶然により @code{. . .} と書くことも出来ました。)
@end itemize

@node 削除された操作,,変更された構文,構文の変更の概要
@anchor{whatsnew/3 0 removed-syntax}@anchor{14c2}
@subsubsection 削除された操作



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 3113
PEP 3113@footnote{https://peps.python.org/pep-3113/}: タプル引数のアンパックが削除されました.  @code{def foo(a, (b, c)): ...} のように書くことはできません。かわりに @code{def foo(a, b_c): b, c = b_c} を使用してください。

@item 
バッククオートが削除されました (代わりに @ref{1c1,,repr()} を使用してください)。

@item 
@code{<>} が削除されました (代わりに @code{!=} を使用してください)。

@item 
削除されたキーワード: @ref{4a2,,exec()} はキーワードでなくなりましたが、関数として残りました。 (幸運にも関数のシンタックスは 2.x でも許容されています。)  また、 @ref{4a2,,exec()} はストリーム引数を受け取らなくなりました。@code{exec(f)} の代わりに @code{exec(f.read())} を使うことができます。

@item 
@code{l} または @code{L} で終わる整数リテラルはサポートされません。

@item 
@code{u} or @code{U} で始まる文字列リテラルはサポートされません。(---訳注: この @code{u"..."} は Python 3.3 で再び使えるようになりました。 ---)

@item 
@ref{14c3,,from} `module' @ref{7f8,,import} @code{*} はモジュールレベルでのみ許され、関数内での使用は許されません。

@item 
相対インポートに許される構文は @code{from .[@var{module}] import @var{name}} のみです。
@code{.} で始まらない形の全ての @ref{7f8,,import} は絶対インポートと解釈されます。 (
@geindex Python Enhancement Proposals; PEP 328
PEP 328@footnote{https://peps.python.org/pep-0328/})

@item 
古い形式のクラスはサポートされません。
@end itemize

@node Python 2 6 で既にあった変更,ライブラリの変更,構文の変更の概要,What's New In Python 3 0
@anchor{whatsnew/3 0 changes-already-present-in-python-2-6}@anchor{14c4}
@subsection Python 2.6 で既にあった変更


おそらく多くのユーザが一足飛びに Python 2.5 から Python 3.0 に移行しようとするでしょうから、このセクションでは、もともとは Python 3.0 のためにデザインされたものの Python 2.6 にバックポートされた新機能について、読者に思い出してもらいましょう。 @ref{14c5,,What's New in Python 2.6} 内の対応するセクションにはもっと長い説明が書かれています。


@itemize *

@item 
@ref{14c6,,PEP 343; "with" ステートメント}. @ref{186,,with} 文は今では標準機能となったので、 @ref{0,,__future__} からインポートする必要はもうありません。 @ref{14c7,,コンテキストマネージャを書く} と @ref{14c8,,contextlib モジュール} も見てください。

@item 
@ref{14c9,,PEP 366; メインモジュールからの明示的相対インポート}. @ref{23c,,-m} オプションの有用性を強化します。パッケージ内にあるモジュールを参照している際に関係します。

@item 
@ref{14ca,,PEP 370; ユーザごとの site-packages ディレクトリ}.

@item 
@ref{14cb,,PEP 371; multiprocessing パッケージ}.

@item 
@ref{14cc,,PEP 3101; 進化版文字列フォーマッティング}. 注意: 2.6 の記述では @ref{199,,format()} メソッドが 8 ビット文字列と Unicode 文字列両方について述べていますが、3.0 では @ref{169,,str} 型 (Unicode サポートを持ったテキスト文字列) だけがこのメソッドをサポートしています。 @ref{192,,bytes} 型にはありません。計画では最終的にはこれだけが唯一の文字列フォーマットの API になり、Python 3.1 では @code{%} 演算子は非推奨扱いを開始する予定です。(--- 訳注: @code{%} 演算子の撤廃は影響が大き過ぎるからか、現実には (ドキュメントでの軽い記述を除き) 実行時に特別に非推奨扱いされることは 3.5 になってさえもいまだありません。 ---)

@item 
@ref{14cd,,PEP 3105; print を関数にする}. これはもはや標準機能となったので、 @ref{0,,__future__} からインポートする必要はありません。詳細はこのドキュメントの上の方に書いてあります。

@item 
@ref{14ce,,PEP 3110; 例外処理の変更}.  The @ref{1ab,,except} `exc' @code{as} `var'
syntax is now standard and @code{except} `exc', `var' is no
longer supported.  (Of course, the @code{as} `var' part is still
optional.)

@item 
@ref{14cf,,PEP 3112; バイトリテラル}. 文字列リテラル @code{b"..."} 表記 (とそのお仲間 @code{b'...'}, @code{b"""..."""}, @code{br"..."} など) は今では @ref{192,,bytes} 型です。

@item 
@ref{14d0,,PEP 3116; 新しい I/O ライブラリ}.  The @ref{83,,io} module is now the standard way of
doing file I/O.  The built-in @ref{316,,open()} function is now an
alias for @ref{740,,io.open()} and has additional keyword arguments
`encoding', `errors', `newline' and `closefd'.  Also note that an
invalid `mode' argument now raises @ref{2ec,,ValueError}, not
@ref{125e,,IOError}.  The binary file object underlying a text file
object can be accessed as @code{f.buffer} (but beware that the
text object maintains a buffer of itself in order to speed up
the encoding and decoding operations).

@item 
@ref{14d1,,PEP 3118; 改訂版バッファプロトコル}.  The old builtin @code{buffer()} is now really gone;
the new builtin @ref{165,,memoryview()} provides (mostly) similar
functionality.

@item 
@ref{14d2,,PEP 3119; 抽象基底クラス}.  The @ref{4,,abc} module and the ABCs defined in the
@ref{1e,,collections} module plays a somewhat more prominent role in
the language now, and built-in collection types like @ref{183,,dict}
and @ref{24d,,list} conform to the @ref{12c0,,collections.MutableMapping}
and @ref{4bf,,collections.MutableSequence} ABCs, respectively.

@item 
@ref{14d3,,PEP 3127; 整数リテラルのサポートと文法}. 上述のとおり、新しい 8 進数リテラル表現だけが唯一の 8 進数リテラル表現となり、また、バイナリリテラルが追加されました。

@item 
@ref{14d4,,PEP 3129; クラスデコレータ}.

@item 
@ref{14d5,,PEP 3141; 数値の型階層}. @ref{a2,,numbers} が、もう一つの新しく ABC を使うモジュールで、Python の「数値塔 (numeric tower)」を定義しています。新しい @ref{61,,fractions} モジュールが @ref{14d6,,numbers.Rational} を実装していることにも注目してください。
@end itemize

@node ライブラリの変更,PEP 3101 文字列整形の新たなアプローチ,Python 2 6 で既にあった変更,What's New In Python 3 0
@anchor{whatsnew/3 0 library-changes}@anchor{14d7}
@subsection ライブラリの変更


時間の制約により、この文書は標準ライブラリの非常に幅広い変更について徹底的に取り上げてはいません。
ライブラリの大きな変更については 
@geindex Python Enhancement Proposals; PEP 3108
PEP 3108@footnote{https://peps.python.org/pep-3108/} を参照してください。
ここでは要約を示します:


@itemize *

@item 
多くの古いモジュールは削除されました。
@code{gopherlib} (もう使われません) や @code{md5} (@ref{6c,,hashlib} に代替されました) 等のいくつかのモジュールは 
@geindex Python Enhancement Proposals; PEP 4
PEP 4@footnote{https://peps.python.org/pep-0004/} で既に廃止予定でした。
他のモジュールは、Irix、BeOS ならびに Mac OS 9 等のプラットフォームでのサポートが打ち切られた (
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} 参照) ために削除されました。
いくつかのモジュールは使われなかったり、より良い代用品があるため Python 3.0 で削除されました
網羅的なリストは 
@geindex Python Enhancement Proposals; PEP 3108
PEP 3108@footnote{https://peps.python.org/pep-3108/} を参照してください。

@item 
The @code{bsddb3} package was removed because its presence in the
core standard library has proved over time to be a particular burden
for the core developers due to testing instability and Berkeley DB's
release schedule.  However, the package is alive and well,
externally maintained at @indicateurl{https://www.jcea.es/programacion/pybsddb.htm}.

@item 
いくつかのモジュールは 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} に従っていないか、その他の理由により名前が変更されました:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

以前の名前

@tab

新しい名前

@item

_winreg

@tab

winreg

@item

ConfigParser

@tab

configparser

@item

copy_reg

@tab

copyreg

@item

Queue

@tab

queue

@item

SocketServer

@tab

socketserver

@item

markupbase

@tab

_markupbase

@item

repr

@tab

reprlib

@item

test.test_support

@tab

test.support

@end multitable


@item 
A common pattern in Python 2.x is to have one version of a module
implemented in pure Python, with an optional accelerated version
implemented as a C extension; for example, @ref{ab,,pickle} and
@code{cPickle}.  This places the burden of importing the accelerated
version and falling back on the pure Python version on each user of
these modules.  In Python 3.0, the accelerated versions are
considered implementation details of the pure Python versions.
Users should always import the standard version, which attempts to
import the accelerated version and falls back to the pure Python
version.  The @ref{ab,,pickle} / @code{cPickle} pair received this
treatment.  The @ref{b4,,profile} module is on the list for 3.1.  The
@code{StringIO} module has been turned into a class in the @ref{83,,io}
module.

@item 
関連のあるモジュールのいくつかはパッケージにまとめられ、ふつうサブモジュール名は単純化されました。結果として以下のようなパッケージが出来ました:


@itemize *

@item 
@ref{35,,dbm} (@code{anydbm}, @code{dbhash}, @code{dbm},
@code{dumbdbm}, @code{gdbm}, @code{whichdb}).

@item 
@ref{6f,,html} (@code{HTMLParser}, @code{htmlentitydefs}).

@item 
@ref{72,,http} (@code{httplib}, @code{BaseHTTPServer},
@code{CGIHTTPServer}, @code{SimpleHTTPServer}, @code{Cookie},
@code{cookielib}).

@item 
@ref{f6,,tkinter} (all @code{Tkinter}-related modules except
@ref{107,,turtle}).  The target audience of @ref{107,,turtle} doesn't
really care about @ref{f6,,tkinter}.  Also note that as of Python
2.6, the functionality of @ref{107,,turtle} has been greatly enhanced.

@item 
@ref{10e,,urllib} (@code{urllib}, @code{urllib2}, @code{urlparse},
@code{robotparse}).

@item 
@ref{133,,xmlrpc} (@code{xmlrpclib}, @code{DocXMLRPCServer},
@code{SimpleXMLRPCServer}).
@end itemize
@end itemize

@geindex Python Enhancement Proposals; PEP 3108
PEP 3108@footnote{https://peps.python.org/pep-3108/} で取り上げられていない標準ライブラリーの他の変更:


@itemize *

@item 
Killed @code{sets}.  Use the built-in @ref{184,,set()} class.

@item 
Cleanup of the @ref{df,,sys} module: removed @code{sys.exitfunc()},
@code{sys.exc_clear()}, @code{sys.exc_type}, @code{sys.exc_value},
@code{sys.exc_traceback}.  (Note that @ref{6e6,,sys.last_type}
etc. remain.)

@item 
Cleanup of the @ref{4be,,array.array} type: the @code{read()} and
@code{write()} methods are gone; use @ref{14d8,,fromfile()} and
@ref{14d9,,tofile()} instead.  Also, the @code{'c'} typecode for array is
gone -- use either @code{'b'} for bytes or @code{'u'} for Unicode
characters.

@item 
Cleanup of the @ref{a3,,operator} module: removed
@code{sequenceIncludes()} and @code{isCallable()}.

@item 
Cleanup of the @code{thread} module: @code{acquire_lock()} and
@code{release_lock()} are gone; use @ref{8a7,,acquire()} and
@ref{14da,,release()} instead.

@item 
Cleanup of the @ref{bd,,random} module: removed the @code{jumpahead()} API.

@item 
The @code{new} module is gone.

@item 
The functions @code{os.tmpnam()}, @code{os.tempnam()} and
@code{os.tmpfile()} have been removed in favor of the @ref{e6,,tempfile}
module.

@item 
@ref{101,,tokenize} モジュールはバイトでも機能するように変更されました。メインのエントリポイントは generate_tokens から @ref{700,,tokenize.tokenize()} になりました。

@item 
@code{string.letters} and its friends (@code{string.lowercase} and
@code{string.uppercase}) are gone.  Use
@ref{14db,,string.ascii_letters} etc. instead.  (The reason for the
removal is that @code{string.letters} and friends had
locale-specific behavior, which is a bad idea for such
attractively named global "constants".)

@item 
Renamed module @code{__builtin__} to @ref{13,,builtins} (removing the
underscores, adding an 's').  The @code{__builtins__} variable
found in most global namespaces is unchanged.  To modify a builtin,
you should use @ref{13,,builtins}, not @code{__builtins__}!
@end itemize

@node PEP 3101 文字列整形の新たなアプローチ,例外に関する変更,ライブラリの変更,What's New In Python 3 0
@anchor{whatsnew/3 0 pep-3101-a-new-approach-to-string-formatting}@anchor{14dc}
@subsection 
@geindex Python Enhancement Proposals; PEP 3101
`PEP 3101': 文字列整形の新たなアプローチ



@itemize *

@item 
組み込みの新しい文字列書式化操作で、文字列の @code{%} 演算子を置き換えるものです。(しかしながら @code{%} 演算子はまだサポートされます; Python 3.1 で非推奨となり、将来のいつかの時点で削除されます。) 完全な詳細は 
@geindex Python Enhancement Proposals; PEP 3101
PEP 3101@footnote{https://peps.python.org/pep-3101/} をお読み下さい。 (--- 訳注: @ref{14c4,,Python 2.6 で既にあった変更} での対応する記述に書いた訳注を参照。---)
@end itemize

@node 例外に関する変更,その他の変更<2>,PEP 3101 文字列整形の新たなアプローチ,What's New In Python 3 0
@anchor{whatsnew/3 0 changes-to-exceptions}@anchor{14dd}
@subsection 例外に関する変更


例外の送出や捕捉を行う API は整理され、 強力な新機能が追加されました:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 352
PEP 352@footnote{https://peps.python.org/pep-0352/}: 全ての例外は (直接的にまたは間接的に) @ref{7d6,,BaseException} を継承しなければなりません。
@ref{7d6,,BaseException} は例外階層の根です。
これは勧告としては新しくありませんが、@ref{7d6,,BaseException} 継承の `要求' は新しいです。
(Python 2.6 は依然として昔のクラスを送出するのを許容しており、捕捉するものについての制限はありません。)
結果として文字列例外は終に本当の意味で、完全になくなりました。

@item 
ほとんど全ての例外は、実際は @ref{bcd,,Exception} を継承すべきです。 @ref{7d6,,BaseException} は最上位で扱われるべき例外、例えば @ref{f3c,,SystemExit} や @ref{bc5,,KeyboardInterrupt} の基底クラスとしてのみ使われるべきでしす。上記カテゴリーを除く全ての例外を処理するのに推奨されるイディオムは @ref{1ab,,except} @ref{bcd,,Exception} です。

@item 
@code{StandardError} was removed.

@item 
Exceptions no longer behave as sequences.  Use the @ref{78d,,args}
attribute instead.

@item 
@geindex Python Enhancement Proposals; PEP 3109
PEP 3109@footnote{https://peps.python.org/pep-3109/}: Raising exceptions.  You must now use @code{raise
@var{Exception}(@var{args})} instead of @code{raise @var{Exception}, @var{args}}.
Additionally, you can no longer explicitly specify a traceback;
instead, if you `have' to do this, you can assign directly to the
@ref{14de,,__traceback__} attribute (see below).

@item 
@geindex Python Enhancement Proposals; PEP 3110
PEP 3110@footnote{https://peps.python.org/pep-3110/}: 例外の捕捉。
@code{except @var{SomeException}, @var{variable}} ではなく @code{except @var{SomeException} as @var{variable}} としなければなりません。
その上 @ref{1ab,,except} ブロックがある場合 `variable' は明示的に削除されます。

@item 
@geindex Python Enhancement Proposals; PEP 3134
PEP 3134@footnote{https://peps.python.org/pep-3134/}: Exception chaining.  There are two cases: implicit
chaining and explicit chaining.  Implicit chaining happens when an
exception is raised in an @ref{1ab,,except} or @ref{1b0,,finally}
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
@ref{14df,,__context__} attribute of the secondary exception.
Explicit chaining is invoked with this syntax:

@example
raise SecondaryException() from primary_exception
@end example

(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
@ref{14e0,,__cause__} attribute of the secondary exception.  The
traceback printed when an unhandled exception occurs walks the chain
of @code{__cause__} and @ref{14df,,__context__} attributes and
prints a
separate traceback for each component of the chain, with the primary
exception at the top.  (Java users may recognize this behavior.)

@item 
@geindex Python Enhancement Proposals; PEP 3134
PEP 3134@footnote{https://peps.python.org/pep-3134/}: Exception objects now store their traceback as the
@ref{14de,,__traceback__} attribute.  This means that an exception
object now contains all the information pertaining to an exception,
and there are fewer reasons to use @ref{89a,,sys.exc_info()} (though the
latter is not removed).

@item 
Windows が拡張モジュールのロードに失敗したときの例外メッセージが少し改善しました。
例えば、@code{error code 193} は @code{%1 is not a valid Win32 application} になりました。
文字列は英語でないロケールを扱えるようになりました。
@end itemize

@node その他の変更<2>,ビルドならびに C API の変更<7>,例外に関する変更,What's New In Python 3 0
@anchor{whatsnew/3 0 miscellaneous-other-changes}@anchor{14e1}
@subsection その他の変更


@menu
* 演算子と特殊メソッド:: 
* 組み込み:: 

@end menu

@node 演算子と特殊メソッド,組み込み,,その他の変更<2>
@anchor{whatsnew/3 0 operators-and-special-methods}@anchor{14e2}
@subsubsection 演算子と特殊メソッド



@itemize *

@item 
@code{!=} は @code{==} と逆の結果をかえします（@code{==} が @ref{1a2,,NotImplemented} を返さなければ）。

@item 
「非束縛メソッド (unbound methods)」という概念は言語から削除されました。クラス属性としてのメソッドを参照しても今では普通の関数オブジェクトが得られます。

@item 
@code{__getslice__()}, @code{__setslice__()} and @code{__delslice__()}
were killed.  The syntax @code{a[i:j]} now translates to
@code{a.__getitem__(slice(i, j))} (or @ref{14e3,,__setitem__()} or
@ref{14e4,,__delitem__()}, when used as an assignment or deletion target,
respectively).

@item 
@geindex Python Enhancement Proposals; PEP 3114
PEP 3114@footnote{https://peps.python.org/pep-3114/}:  @ref{9d8,,next()} 標準メソッドは @ref{14e5,,__next__()} に改名されました。

@item 
The @code{__oct__()} and @code{__hex__()} special methods are removed
-- @ref{14e6,,oct()} and @ref{14e7,,hex()} use @ref{19e,,__index__()} now to convert
the argument to an integer.

@item 
Removed support for @code{__members__} and @code{__methods__}.

@item 
The function attributes named @code{func_X} have been renamed to
use the @code{__X__} form, freeing up these names in the function
attribute namespace for user-defined attributes.  To wit,
@code{func_closure}, @code{func_code}, @code{func_defaults},
@code{func_dict}, @code{func_doc}, @code{func_globals},
@code{func_name} were renamed to @ref{14e8,,__closure__},
@ref{59d,,__code__}, @ref{14e9,,__defaults__},
@ref{14ea,,__dict__}, @ref{13f1,,__doc__},
@ref{14eb,,__globals__}, @ref{14ec,,__name__},
respectively.

@item 
@code{__nonzero__()} is now @ref{14ed,,__bool__()}.
@end itemize

@node 組み込み,,演算子と特殊メソッド,その他の変更<2>
@anchor{whatsnew/3 0 builtins}@anchor{14ee}
@subsubsection 組み込み



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 3135
PEP 3135@footnote{https://peps.python.org/pep-3135/}: 新しくなった @ref{1a6,,super()} 。今では @ref{1a6,,super()} は引数なしで呼び出せます。(これが @ref{14ef,,class} 内で定義される通常のインスタンスメソッド内であると仮定して) 正しいクラスとインスタンスが自動的に選択されます。引数ありの場合の @ref{1a6,,super()} の振る舞いには変更はありません。

@item 
@geindex Python Enhancement Proposals; PEP 3111
PEP 3111@footnote{https://peps.python.org/pep-3111/}: @code{raw_input()} was renamed to @ref{14f0,,input()}.  That
is, the new @ref{14f0,,input()} function reads a line from
@ref{75f,,sys.stdin} and returns it with the trailing newline stripped.
It raises @ref{14f1,,EOFError} if the input is terminated prematurely.
To get the old behavior of @ref{14f0,,input()}, use @code{eval(input())}.

@item 
新しい組み込み関数 @ref{9d8,,next()} が追加されました。 オブジェクトの @ref{14e5,,__next__()} メソッドを呼び出します。

@item 
@ref{14f2,,round()} 関数の丸めの戦略と戻り値の型が変更されました。ど真ん中の場合に、四捨五入ではなく最近接偶数への丸めをするようになりました。(例えば @code{round(2.5)} は今では @code{2} を返します。 @code{3} ではなく。) (---訳注: 丸めモードについては Wikipedia@footnote{https://en.wikipedia.org/wiki/Rounding#Tie-breaking} 参照。---) @code{round(x[, n])} は常に浮動小数点数の結果を返す代わりに、 @code{x.__round__([n])} に処理を委譲するようになりました。これは一般的に、単一引数で呼ばれた際に整数を返し、二つの引数で呼ばれた場合は @code{x} と同じ型の値として返します。

@item 
Moved @code{intern()} to @ref{14f3,,sys.intern()}.

@item 
Removed: @code{apply()}.  Instead of @code{apply(f, args)} use
@code{f(*args)}.

@item 
Removed @ref{13de,,callable()}.  Instead of @code{callable(f)} you can use
@code{isinstance(f, collections.Callable)}.  The @code{operator.isCallable()}
function is also gone.

@item 
Removed @code{coerce()}.  This function no longer serves a purpose
now that classic classes are gone.

@item 
Removed @code{execfile()}.  Instead of @code{execfile(fn)} use
@code{exec(open(fn).read())}.

@item 
Removed the @code{file} type.  Use @ref{316,,open()}.  There are now several
different kinds of streams that open can return in the @ref{83,,io} module.

@item 
Removed @code{reduce()}.  Use @ref{21a,,functools.reduce()} if you really
need it; however, 99 percent of the time an explicit @ref{34a,,for}
loop is more readable.

@item 
Removed @code{reload()}.  Use @code{imp.reload()}.

@item 
Removed. @code{dict.has_key()} -- use the @ref{34b,,in} operator
instead.
@end itemize

@c ======================================================================

@node ビルドならびに C API の変更<7>,性能,その他の変更<2>,What's New In Python 3 0
@anchor{whatsnew/3 0 build-and-c-api-changes}@anchor{14f4}
@subsection ビルドならびに C API の変更


時間がないため、以下のC APIへの変更点のリストは `かなり' 不完全です。


@itemize *

@item 
Mac OS 9, BeOS, RISCOS, Irix, Tru64 に限らず、いくつものプラットフォームのサポートが打ち切られました。

@item 
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/}: 新たなバッファ API。

@item 
@geindex Python Enhancement Proposals; PEP 3121
PEP 3121@footnote{https://peps.python.org/pep-3121/}: 例外モジュールの初期化と最終化

@item 
@geindex Python Enhancement Proposals; PEP 3123
PEP 3123@footnote{https://peps.python.org/pep-3123/}: @ref{14f5,,PyObject_HEAD} を標準的な C に一致。

@item 
制限付き実行 の C API サポートはこれ以上されません。

@item 
@code{PyNumber_Coerce()}, @code{PyNumber_CoerceEx()},
@code{PyMember_Get()}, and @code{PyMember_Set()} C APIs are removed.

@item 
新たな C API @ref{3db,,PyImport_ImportModuleNoBlock()}、@ref{3dc,,PyImport_ImportModule()} のように動きますが、インポートロックでブロックしません (代わりにエラーを返します)。

@item 
ブール変換の C 水準のスロットとメソッドがリネームされました: @code{nb_nonzero} が @code{nb_bool} になりました。

@item 
Removed @code{METH_OLDARGS} and @code{WITH_CYCLE_GC} from the C API.
@end itemize

@c ======================================================================

@node 性能,Python 3 0 への移植,ビルドならびに C API の変更<7>,What's New In Python 3 0
@anchor{whatsnew/3 0 performance}@anchor{14f6}
@subsection 性能


3.0 の可搬化 (generalization) による正味の結果は、Python 3.0 を pystone ベンチマークすると Python 2.5 より 10% 遅くなる、というものでした。これはどうやら小さい整数についての特殊処理を削除したことに一番大きな要因があるようです。これには改善の余地がありますが、それは 3.0 リリース以降でしょう!

@c ======================================================================

@node Python 3 0 への移植,,性能,What's New In Python 3 0
@anchor{whatsnew/3 0 porting-to-python-3-0}@anchor{14f7}
@subsection Python 3.0 への移植


(---訳注: 今では独立したクックブック pyporting-howto があるのでそちらをご覧下さい。---) 既存の Python 2.5 や 2.6 のソースコードを Python 3.0 に移植する最良の策は以下の通りです:


@enumerate 0

@item 
(必須:) 優秀なテストカバレッジから始めてください。

@item 
Python 2.6 に移植します。Python 2.x を Python 2.(x+1) に移植する普通の作業以上のことをしてはいけません。確実に全てのテストを通してください。

@item 
(まだ 2.6 を使います:) コマンドラインに @code{-3} オプションを渡します。これは 3.0 で削除された (または変更された) 機能についての警告発行を有効にします。再びテストスイートを実行して、そして警告が出たコードをそれがなくなるまで修正し、全てのテストをパスさせます。

@item 
Run the @code{2to3} source-to-source translator over your source code
tree.  Run the
result of the translation under Python 3.0.  Manually fix up any
remaining issues, fixing problems until all tests pass again.
@end enumerate

Python 2.6 と 3.0 両方で変更なしに動作するコードを書こうとすることはお奨め出来ません; それをするととても捻じ曲がったコーディングスタイルを使う必要があるでしょう。例えば @code{print} やメタクラスを避けたりとかそんな。Python 2.6 と 3.0 両バージョンともに対するサポートを必要とするライブラリを保守しているのであれば、最良のアプローチは上記スリーステップを修正して、2.6 版のソースコードを編集して @code{2to3} する、を繰り返すことです。これは 3.0 版のソースコードを編集するより良いです。(---訳注: ここで言っていることは正論なのですが、 @code{2to3} は「Python 3 では動くが Python 2 では動かない (かもしれない)」ものを生成します。2016 時点でも Python 2.7 はかなり元気 (予定では 2020 年までは公式にサポートされる) ですので両バージョン (ただし今だと 2.7 と 3.2 以降) で変更なしで動作するものを必要とすることは、残念ながらまだ多いでしょう (あなたが作っているのがライブラリであるならば)。これについては pyporting-howto に少し書かれています。 ---)

C 拡張を Python 3.0 に移植するには、 @ref{14f8,,Python 3 への拡張モジュール移植} を参照してください。

@c ======================================================================

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 7,What's New in Python 2 6,What's New In Python 3 0,What's New in Python
@anchor{whatsnew/2 7 doc}@anchor{14f9}@anchor{whatsnew/2 7 translation-repo}@anchor{14fa}@anchor{whatsnew/2 7 what-s-new-in-python-2-7}@anchor{14fb}
@section What's New in Python 2.7


@*著者: 
A.M. Kuchling (amk at amk.ca)


@c hyperlink all the methods & functions.

@c T_STRING_INPLACE not described in main docs

@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.  Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number in a parenthetical comment.
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer; :issue:`12345`.)
@c 
@c This saves the maintainer some effort going through the SVN logs
@c when researching a change.

この文書は Python 2.7 の新機能について解説します。Python 2.7 は 2010 年 7 月 3 日にリリースされました。

数値周りの扱いが、浮動小数点数でも @ref{1fe,,Decimal} クラスでもいろいろな点で改良されました、標準ライブラリにいくつかの有用な追加が行われました。 @ref{10c,,unittest} モジュールが大幅に改良され、コマンドラインオプション解析の @ref{7,,argparse} モジュールが追加され、 @ref{1e,,collections} モジュールに便利な @ref{7f3,,OrderedDict} と @ref{12a3,,Counter} が追加され、他にもたくさんの改良が行われています。

Python 2.7 は 2.x の最終リリースになることが予定されているので、私たちはこのリリースを長期にわたって良いものになるように努力してきました。Python 3 への移植を助けるため、いくつかの新機能が Python 3.x から Python 2.7 に取り込まれています。

このドキュメントは新機能の完全な詳細を提供するのではなくて、簡易な概要を提供することを目的にしています。完全な詳細が知りたければ、 @indicateurl{https://docs.python.org} の Python 2.7 のドキュメントを参照してください。設計と実装の根拠を理解したい場合は、新機能に関する PEP を参照するか、 @indicateurl{https://bugs.python.org} に議論したい機能について登録してください。可能な限り、 "What's New in Python" は各変更の bug や patch に対してリンクしています。

@menu
* Python 2.x の今後: Python 2 x の今後. 
* Deprecation Warnings の扱いの変更:: 
* Python 3.1 の機能: Python 3 1 の機能. 
* PEP 372; collections に順序付き辞書を追加: PEP 372 collections に順序付き辞書を追加. 
* PEP 378; 1000区切りのための書式指定子: PEP 378 1000区切りのための書式指定子<2>. 
* PEP 389; コマンドライン解析のための argparse モジュール: PEP 389 コマンドライン解析のための argparse モジュール. 
* PEP 391; logging の辞書ベースの設定: PEP 391 logging の辞書ベースの設定<2>. 
* PEP 3106; 辞書 View: PEP 3106 辞書 View. 
* PEP 3137; memoryview オブジェクト: PEP 3137 memoryview オブジェクト. 
* その他の言語変更: その他の言語変更<14>. 
* 新しいモジュールと改良されたモジュール:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<8>. 
* その他の変更と修正:: 
* Python 2.7 への移植: Python 2 7 への移植. 
* Python 2.7 メンテナンスリリースで追加された新機能: Python 2 7 メンテナンスリリースで追加された新機能. 
* 謝辞:: 

@end menu

@node Python 2 x の今後,Deprecation Warnings の扱いの変更,,What's New in Python 2 7
@anchor{whatsnew/2 7 the-future-for-python-2-x}@anchor{14fc}@anchor{whatsnew/2 7 whatsnew27-python31}@anchor{14fd}
@subsection Python 2.x の今後


Python 2.7 は 2.x シリーズの最後のメジャーリリースになります。Python のメンテナは既に Python 3.x シリーズへの新機能の開発に焦点をシフトしています。Python 2 は今後もバグフィックスを受け容れ、新しいハードウェアやサポートしている OS のバージョンでのビルドが出来るように保つ一方で、言語や標準ライブラリの新しい完全な機能のリリースは行いません。

しかしながら、Python 2.7 と Python 3 の間の共通の大きなサブセットがあって、その共通サブセットあるいは直接的に Python 3 のものへの移行に伴う多くの変更が安全に自動的に行える一方で、その他の変更(Unicode の扱いに関係するものに顕著ですが)入念な検討を必要とし、移行を有効に行うためには堅牢な回帰テストスイートが望まれることでしょう。

これは Python 2.7 が長期間に渡って依然として有効であり、安定性と、Python 3 がいまだに移植されていないような製品システムのベースプラットフォームのサポートを提供し続けることを意味しています。Python 2.7 シリーズに望まれているライフサイクルについての完全な詳細は、 
@geindex Python Enhancement Proposals; PEP 373
PEP 373@footnote{https://peps.python.org/pep-0373/} に記述されています。

2.7 が長期的に重要なリリースになるので、いくつかの結論があります:


@itemize *

@item 
上述のように、 2.7 リリースは以前の 2.x バージョンに較べて遥かに長期間のメンテナンスとなります。Python 2.7 は現在では、最低でも 2020 年までコア開発チームによって(セキュリティアップデートやほかのバグフィックスの)サポートがなされ続けることが求められています(最初のリリースから 10 年後です。普通であれば 18--24 ヶ月なのに)。

@item 
Python 2.7 標準ライブラリが年老いていくに従い、(直接であれ再配布であれ) Python Package Index の効果的な利用が Python 2 ユーザにとってますます重要になっています。さまざまなタスクをこなすありとあらゆるサードパーティパッケージに加え、Python 2 互換の、Python 3 標準ライブラリからバックポートした新しいモジュールや機能を含むパッケージ、Python 3 への移行を容易にするための様々なツールやライブラリが入手出来ます。Python Packaging User Guide@footnote{https://packaging.python.org} は Python Package Index からソフトウェアをダウンロード・インストールする際のガイダンスです。

@item 
Python 2 を拡張するための望ましいアプローチは現在では Python Package Index に新しいパッケージを公開することである一方で、このアプローチが全てのケースで求められるわけではありません。特にそれがネットワークセキュリティに関係している場合には。PyPI に新規もしくは更新パッケージを公開することでは十分ではない例外的なケースにおいては、Python 2 標準ライブラリに直接新機能を追加するために Python Enhancement Proposal プロセスが使われるでしょう。そのような追加の全てと、それらが追加されたメンテナンスリリースは、下の方の @ref{14fe,,Python 2.7 メンテナンスリリースで追加された新機能} セクションで言及されます。
@end itemize

Python 2 から Python 3 へ乗り換えたいと望むプロジェクトあるいはPython 2 と Python 3 両方のユーザをサポートしたいと願うライブラリやフレームワークの開発者向けに、さまざまなツールやガイドがあります。これらは、相応しいアプローチを決めたりある種複雑な技術的詳細の管理をする手助けとなるでしょう。まず手始めには pyporting-howto HOWTO ガイドをご覧になることをお奨めします。

@node Deprecation Warnings の扱いの変更,Python 3 1 の機能,Python 2 x の今後,What's New in Python 2 7
@anchor{whatsnew/2 7 changes-to-the-handling-of-deprecation-warnings}@anchor{14ff}
@subsection Deprecation Warnings の扱いの変更


Python 2.7 では開発者向けの警告をデフォルトで抑止するポリシーが取られました。 @ref{1a3,,DeprecationWarning} とそれを継承した警告は、指定されない限りは無視され、アプリケーションのユーザーがその警告を見ないですむようになりました。この変更は Python 3.2 ブランチにも適用されました。 (stdlib-sig で討議され、 bpo-7319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7319} になりました)

以前のリリースでは、 @ref{1a3,,DeprecationWarning} メッセージはデフォルトで有効になっており、 Python 開発者に、将来のバージョンの Python でそのコードのどこが動かなくなるかを明確に知らせていました。

しかし、 Python で開発されたアプリケーションの利用者であって開発には携わっていない人がどんどん増えてきました。 @ref{1a3,,DeprecationWarning} メッセージはそれらのユーザーには無関係で、彼らをアプリケーションが本当に正しく動いているのか不安にさせ、ユーザーの質問に応えるための開発者の負担も増やしていました。

@ref{1a3,,DeprecationWarning} メッセージの表示を有効にするには、 @ref{ac6,,-Wdefault} (短い形式: @ref{ac6,,-Wd}) スイッチか、Python を実行する前に 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} 環境変数を @code{"default"}  (か、 @code{"d"})に設定します。 Python コードから有効にする場合は @code{warnings.simplefilter('default')} とします。

@code{unittest} モジュールもテスト実行時に自動的に deprecation warnings を有効にします。

@node Python 3 1 の機能,PEP 372 collections に順序付き辞書を追加,Deprecation Warnings の扱いの変更,What's New in Python 2 7
@anchor{whatsnew/2 7 python-3-1-features}@anchor{1500}
@subsection Python 3.1 の機能


Python 2.6 は Python 3.0 から多くの機能を取り込み、Python 2.7 は Python 3.1 の新しい機能のいくつかを取り込みました。2.x シリーズは 3.x シリーズへの移行のためのツールを提供し続けています。

Python 2.7 に取り込まれた 3.1 の機能の不完全なリスト:


@itemize *

@item 
集合のリテラル文法 (@code{@{1,2,3@}} は mutable set になります)

@item 
辞書と集合の内包表記 (@code{@{i: i*2 for i in range(3)@}}).

@item 
1つの @ref{186,,with} 文で複数のコンテキストマネージャを扱えるように。

@item 
@ref{83,,io} ライブラリの新バージョン。パフォーマンスのためにC言語で描き直されています。

@item 
@ref{1501,,PEP 372; collections に順序付き辞書を追加} で解説されている順序付き辞書

@item 
@ref{1502,,PEP 378; 1000区切りのための書式指定子} で解説されている新しい @code{","} フォーマット指定子

@item 
@ref{165,,memoryview} オブジェクト

@item 
@ref{7b,,importlib} モジュールの小さいサブセット。 @ref{1503,,下に説明があります}

@item 
float @code{x} の @ref{1c1,,repr()} が多くの場合に短くなりました。これは @code{x} に戻せることが保証される最小の10進文字列です。以前のバージョンの Python では、 @code{float(repr(x))} が @code{x} になることだけが保証されていました。

@item 
float から文字列、文字列から float への変換が正しく丸められるようになりました。 @ref{14f2,,round()} 関数も正しく丸めるようになりました。

@item 
拡張モジュールが C API を提供するための、 @ref{148a,,PyCapsule} 型

@item 
@ref{147d,,PyLong_AsLongAndOverflow()} C API 関数
@end itemize

新しい Python3 モード Warning:


@itemize *

@item 
@code{operator.isCallable()} と @code{operator.sequenceIncludes()} は 3.x ではサポートされず、警告が表示されます。

@item 
@code{-3} スイッチは、整数または長整数での古い除算方式を使用した場合に警告を出力するようになる @code{-Qwarn} スイッチを有効にするようになりました。
@end itemize

@c ========================================================================

@c Large, PEP-level features and changes should be described here.

@c ========================================================================

@node PEP 372 collections に順序付き辞書を追加,PEP 378 1000区切りのための書式指定子<2>,Python 3 1 の機能,What's New in Python 2 7
@anchor{whatsnew/2 7 pep-0372}@anchor{1501}@anchor{whatsnew/2 7 pep-372-adding-an-ordered-dictionary-to-collections}@anchor{1504}
@subsection PEP 372: collections に順序付き辞書を追加


通常の Python 辞書は、 key/value ペアを不定の順序でイテレートします。何年にもわたり、いろいろな人が key の挿入順を保存する辞書の別実装を書いてきました。その経験に基づき、 2.7 は @ref{1e,,collections} モジュールに新しい @ref{7f3,,OrderedDict} クラスを追加しました。

@ref{7f3,,OrderedDict} API は通常の辞書と同じインターフェースを提供していますが、 key/value をイテレートするときに key が最初に挿入された順番になることが保証されています。

@example
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
...                  ('second', 2),
...                  ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
@end example

新しいエントリが既存のエントリを上書きした場合は、元の挿入順序が保持されます。:

@example
>>> d['second'] = 4
>>> d.items()
[('first', 1), ('second', 4), ('third', 3)]
@end example

エントリを削除して再挿入すると、順序は一番最後に移動します。:

@example
>>> del d['second']
>>> d['second'] = 5
>>> d.items()
[('first', 1), ('third', 3), ('second', 5)]
@end example

@ref{1505,,popitem()} メソッドは、オプションの `last' 引数を持ち、でフォルトで @code{True} になっています。 `last' が真の場合、一番最近に追加された key が返され、削除されます。偽の場合、最も古い key が選ばれます:

@example
>>> od = OrderedDict([(x,0) for x in range(20)])
>>> od.popitem()
(19, 0)
>>> od.popitem()
(18, 0)
>>> od.popitem(last=False)
(0, 0)
>>> od.popitem(last=False)
(1, 0)
@end example

2つの順序付き辞書を比較するときは、key/value だけでなく、挿入順も比較されます。:

@example
>>> od1 = OrderedDict([('first', 1),
...                    ('second', 2),
...                    ('third', 3)])
>>> od2 = OrderedDict([('third', 3),
...                    ('first', 1),
...                    ('second', 2)])
>>> od1 == od2
False
>>> # Move 'third' key to the end
>>> del od2['third']; od2['third'] = 3
>>> od1 == od2
True
@end example

@ref{7f3,,OrderedDict} を通常の辞書と比較すると、挿入順は無視されて単に key/value だけが比較されます。

How does the @ref{7f3,,OrderedDict} work?  It maintains a
doubly linked list of keys, appending new keys to the list as they're inserted.
A secondary dictionary maps keys to their corresponding list node, so
deletion doesn't have to traverse the entire linked list and therefore
remains `O'(1).

標準ライブラリのいくつかのモジュールで、順序付き辞書の利用がサポートされています。


@itemize *

@item 
The @ref{26,,ConfigParser} module uses them by default, meaning that
configuration files can now be read, modified, and then written back
in their original order.

@item 
The @ref{bd4,,_asdict()} method for
@ref{4e0,,collections.namedtuple()} now returns an ordered dictionary with the
values appearing in the same order as the underlying tuple indices.

@item 
The @ref{86,,json} module's @ref{f43,,JSONDecoder} class
constructor was extended with an `object_pairs_hook' parameter to
allow @code{OrderedDict} instances to be built by the decoder.
Support was also added for third-party tools like
PyYAML@footnote{https://pyyaml.org/}.
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 372

@item PEP 372@footnote{https://peps.python.org/pep-0372/} - collections に順序付き辞書を追加

PEP written by Armin Ronacher and Raymond Hettinger;
implemented by Raymond Hettinger.
@end table


@node PEP 378 1000区切りのための書式指定子<2>,PEP 389 コマンドライン解析のための argparse モジュール,PEP 372 collections に順序付き辞書を追加,What's New in Python 2 7
@anchor{whatsnew/2 7 pep-0378}@anchor{1502}@anchor{whatsnew/2 7 pep-378-format-specifier-for-thousands-separator}@anchor{1506}
@subsection PEP 378: 1000区切りのための書式指定子


大きい数値に区切り文字を追加して、18446744073709551616 の代わりに 18,446,744,073,709,551,616 と出力すると、プログラムの出力を読みやすくできます。

これを行う一般的な方法は @ref{8a,,locale} モジュールを使うことで、複数の区切り文字 (北米では "," で、ヨーロッパでは ".") を使ったり、複数のグループの大きさを使うことができます。しかし、 @ref{8a,,locale} の利用方法は複雑ですし、スレッドごとに異なるロケールの出力を行うプログラムでは利用することができません。

そのため、シンプルなカンマによるグループ化機構が @ref{833,,str.format()} メソッドのミニ言語に追加されました。浮動小数点数をフォーマットする場合、シンプルにカンマを幅と精度の間に置きます。

@example
>>> '@{:20,.2f@}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'
@end example

整数をフォーマットする場合は、幅の後にカンマを追加します。

@example
>>> '@{:20,d@}'.format(18446744073709551616)
'18,446,744,073,709,551,616'
@end example

この機構は全く柔軟性を持っていません。区切り文字は常にカンマですし、グループは常に数字3つになります。カンマ書式機構は @ref{8a,,locale} ほど汎用ではありませんが、手軽に使うことができます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 378

@item PEP 378@footnote{https://peps.python.org/pep-0378/} - 1000区切りのための書式指定子

PEP written by Raymond Hettinger; implemented by Eric Smith.
@end table


@node PEP 389 コマンドライン解析のための argparse モジュール,PEP 391 logging の辞書ベースの設定<2>,PEP 378 1000区切りのための書式指定子<2>,What's New in Python 2 7
@anchor{whatsnew/2 7 pep-389-the-argparse-module-for-parsing-command-lines}@anchor{1507}
@subsection PEP 389: コマンドライン解析のための argparse モジュール


コマンドライン引数の解析のための @ref{7,,argparse} モジュールが、 @ref{a4,,optparse} モジュールのより強力な代替として追加されました。

This means Python now supports three different modules for parsing
command-line arguments: @ref{65,,getopt}, @ref{a4,,optparse}, and
@ref{7,,argparse}.  The @ref{65,,getopt} module closely resembles the C
library's @code{getopt()} function, so it remains useful if you're writing a
Python prototype that will eventually be rewritten in C.
@ref{a4,,optparse} becomes redundant, but there are no plans to remove it
because there are many scripts still using it, and there's no
automated way to update these scripts.  (Making the @ref{7,,argparse}
API consistent with @ref{a4,,optparse}'s interface was discussed but
rejected as too messy and difficult.)

古いバージョンの Python との互換性を気にすること無く新しいスクリプトを書く時は、 @ref{a4,,optparse} の代わりに @ref{7,,argparse} を使ってください。

以下はこの使用例です:

@example
import argparse

parser = argparse.ArgumentParser(description='Command-line example.')

# Add optional switches
parser.add_argument('-v', action='store_true', dest='is_verbose',
                    help='produce verbose output')
parser.add_argument('-o', action='store', dest='output',
                    metavar='FILE',
                    help='direct output to FILE instead of stdout')
parser.add_argument('-C', action='store', type=int, dest='context',
                    metavar='NUM', default=0,
                    help='display NUM lines of added context')

# Allow any number of additional arguments.
parser.add_argument(nargs='*', action='store', dest='inputs',
                    help='input filenames (default is stdin)')

args = parser.parse_args()
print args.__dict__
@end example

オーバーライドしない限り、 @code{-h} と @code{--help} スイッチが自動的に追加され、綺麗にフォーマットした出力を生成します。

@example
-> ./python.exe argparse-example.py --help
usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]

Command-line example.

positional arguments:
  inputs      input filenames (default is stdin)

optional arguments:
  -h, --help  show this help message and exit
  -v          produce verbose output
  -o FILE     direct output to FILE instead of stdout
  -C NUM      display NUM lines of added context
@end example

@ref{a4,,optparse} と同じく、コマンドラインスイッチと引数は、 `dest' 引数の名前の属性をもったオブジェクトとして返されます。

@example
-> ./python.exe argparse-example.py -v
@{'output': None,
 'is_verbose': True,
 'context': 0,
 'inputs': []@}

-> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
@{'output': '/tmp/output',
 'is_verbose': True,
 'context': 4,
 'inputs': ['file1', 'file2']@}
@end example

@ref{7,,argparse} は @ref{a4,,optparse} よりも多くの便利なバリデーションを持っています。引数の正確な数を整数で指定したり、 @code{'*'} で0以上の数を指定したり、 @code{'+'} で1以上の数を指定したり、 @code{'?'} でオプションにしたりできます。トップレベルのパーサーはサブパーサーを持つことができ、 @code{svn commit}, @code{svn checkout} のように異なるオプションを持ったサブコマンドを定義できます。引数のタイプに @ref{30c,,FileType} を指定することで、自動でファイルを開き、 @code{'-'} が指定されたときに標準入出力だと判断することができます。


@subsubheading 参考



@table @asis

@item @ref{7,,argparse} のドキュメント

argparse モジュールのドキュメント

@item @ref{13c6,,Migrating optparse code to argparse}

@ref{a4,,optparse} を使うコードを変換する方法を説明した Python のドキュメントの一部

@geindex Python Enhancement Proposals; PEP 389

@item PEP 389@footnote{https://peps.python.org/pep-0389/} - argparse コマンドライン解析モジュール

PEP written and implemented by Steven Bethard.
@end table


@node PEP 391 logging の辞書ベースの設定<2>,PEP 3106 辞書 View,PEP 389 コマンドライン解析のための argparse モジュール,What's New in Python 2 7
@anchor{whatsnew/2 7 pep-391-dictionary-based-configuration-for-logging}@anchor{1508}
@subsection PEP 391: logging の辞書ベースの設定


@ref{8b,,logging} モジュールは非常に柔軟です。アプリケーションは logging のサブシステムのツリーを定義できます。このツリーの各ロガーはいくつかのメッセージをフィルターし、異なるフォーマットを行い、メッセージを沢山の種類のハンドラーに渡します。

All this flexibility can require a lot of configuration.  You can
write Python statements to create objects and set their properties,
but a complex set-up requires verbose but boring code.
@ref{8b,,logging} also supports a @ref{d48,,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 @ref{13c8,,dictConfig()} function that
uses a dictionary to configure logging.  There are many ways to
produce a dictionary from different sources: construct one with code;
parse a file containing JSON; or use a YAML parsing library if one is
installed.  For more information see @ref{1509,,環境設定のための関数}.

以下は、2つのロガー、 root logger と "network" という名前の logger を設定する例です。root logger に送られたメッセージは syslog プロトコルを利用してシステムログに送られ、 "network" logger に送られたメッセージは 1 MB ごとにローテートされる
@code{network.log} ファイルに書きこまれます。

@example
import logging
import logging.config

configdict = @{
 'version': 1,    # Configuration schema in use; must be 1 for now
 'formatters': @{
     'standard': @{
         'format': ('%(asctime)s %(name)-15s '
                    '%(levelname)-8s %(message)s')@}@},

 'handlers': @{'netlog': @{'backupCount': 10,
                     'class': 'logging.handlers.RotatingFileHandler',
                     'filename': '/logs/network.log',
                     'formatter': 'standard',
                     'level': 'INFO',
                     'maxBytes': 1000000@},
              'syslog': @{'class': 'logging.handlers.SysLogHandler',
                         'formatter': 'standard',
                         'level': 'ERROR'@}@},

 # Specify all the subordinate loggers
 'loggers': @{
             'network': @{
                         'handlers': ['netlog']
             @}
 @},
 # Specify properties of the root logger
 'root': @{
          'handlers': ['syslog']
 @},
@}

# Set up configuration
logging.config.dictConfig(configdict)

# As an example, log two error messages
logger = logging.getLogger('/')
logger.error('Database not found')

netlogger = logging.getLogger('network')
netlogger.error('Connection failed')
@end example

他にも、 @ref{8b,,logging} モジュールには Vinary Sajip によって実装された 3 つの改良があります。

@c rev79293


@itemize *

@item 
@ref{86c,,SysLogHandler} クラスは TCP 経由の syslog をサポートします。コンストラクタの `socktype' 引数は使用するソケットの種類として、 UDP を使う @ref{150a,,socket.SOCK_DGRAM} と TCP を使う @ref{150b,,socket.SOCK_STREAM} のどちらかを取ります。デフォルトはUDPのままです。

@item 
@ref{d46,,Logger} インスタンスに @ref{150c,,getChild()}  メソッドが追加されました。これは、相対パスで下位の logger を返します。 例えば、 @code{log = getLogger('app')} として logger を取得した後、  @code{log.getChild('network.listen')} は @code{getLogger('app.network.listen')} と同じになります。

@item 
The @ref{150d,,LoggerAdapter} class gained an
@ref{150e,,isEnabledFor()} method that takes a
`level' and returns whether the underlying logger would
process a message of that level of importance.
@end itemize

@c XXX: Logger objects don't have a class declaration so the link don't work


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 391

@item PEP 391@footnote{https://peps.python.org/pep-0391/} - logging の辞書ベースの設定

PEP written and implemented by Vinay Sajip.
@end table


@node PEP 3106 辞書 View,PEP 3137 memoryview オブジェクト,PEP 391 logging の辞書ベースの設定<2>,What's New in Python 2 7
@anchor{whatsnew/2 7 pep-3106-dictionary-views}@anchor{150f}
@subsection PEP 3106: 辞書 View


辞書の @ref{9d0,,keys()}, @ref{9d1,,values()}, @ref{9d2,,items()} メソッドは Python 3.x では動作が代わり、完全に実体化されたリストの代わりに、 `view' と呼ばれるオブジェクトを返すようになりました。

It's not possible to change the return values of @ref{9d0,,keys()},
@ref{9d1,,values()}, and @ref{9d2,,items()} in Python 2.7 because
too much code would break.  Instead the 3.x versions were added
under the new names @code{viewkeys()}, @code{viewvalues()},
and @code{viewitems()}.

@example
>>> d = dict((i*10, chr(65+i)) for i in range(26))
>>> d
@{0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'@}
>>> d.viewkeys()
dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
@end example

View はイテレートするだけでなく、set と似た利用をすることもできます。@code{&} 演算子で共通部分集合を、@code{|} 演算子で話集合を取ることができます。

@example
>>> d1 = dict((i*10, chr(65+i)) for i in range(26))
>>> d2 = dict((i**.5, i) for i in range(1000))
>>> d1.viewkeys() & d2.viewkeys()
set([0.0, 10.0, 20.0, 30.0])
>>> d1.viewkeys() | range(0, 30)
set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
@end example

view は辞書とその辞書の変化に追随しています。:

@example
>>> vk = d.viewkeys()
>>> vk
dict_keys([0, 130, 10, ..., 250])
>>> d[260] = '&'
>>> vk
dict_keys([0, 130, 260, 10, ..., 250])
@end example

ただし、view をイテレートしている間に key の追加や削除ができないことに気を付けてください。:

@example
>>> for k in vk:
...     d[k*2] = k
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
@end example

Python 2.x で view メソッドを利用すると、 2to3 が自動的にそれを通常の @ref{9d0,,keys()}, @ref{9d1,,values()}, @ref{9d2,,items()} メソッドに書き換えてくれます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3106

@item PEP 3106@footnote{https://peps.python.org/pep-3106/} - Revamping dict.keys(), .values() and .items()

PEP written by Guido van Rossum.
Backported to 2.7 by Alexandre Vassalotti; bpo-1967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1967}.
@end table


@node PEP 3137 memoryview オブジェクト,その他の言語変更<14>,PEP 3106 辞書 View,What's New in Python 2 7
@anchor{whatsnew/2 7 pep-3137-the-memoryview-object}@anchor{1510}
@subsection PEP 3137: memoryview オブジェクト


@ref{165,,memoryview} オブジェクトは、他のオブジェクトのメモリの内容に対する @ref{192,,bytes} 型のインターフェースに合わせた view を提供します。

@example
>>> import string
>>> m = memoryview(string.letters)
>>> m
<memory at 0x37f850>
>>> len(m)           # Returns length of underlying object
52
>>> m[0], m[25], m[26]   # Indexing returns one byte
('a', 'z', 'A')
>>> m2 = m[0:26]         # Slicing returns another memoryview
>>> m2
<memory at 0x37f080>
@end example

view の内容は bytes 型の文字列か整数のリストに変換することができます。

@example
>>> m2.tobytes()
'abcdefghijklmnopqrstuvwxyz'
>>> m2.tolist()
[97, 98, 99, 100, 101, 102, 103, ... 121, 122]
>>>
@end example

@ref{165,,memoryview} オブジェクトは、対象となる背後のオブジェクトが変更可能 (mutable) な場合は、その変更を許可しています。

@example
>>> m2[0] = 75
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot modify read-only memory
>>> b = bytearray(string.letters)  # Creating a mutable object
>>> b
bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> mb = memoryview(b)
>>> mb[0] = '*'         # Assign to view, changing the bytearray.
>>> b[0:5]              # The bytearray has been changed.
bytearray(b'*bcde')
>>>
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3137

@item PEP 3137@footnote{https://peps.python.org/pep-3137/} - Immutable Bytes and Mutable Buffer

PEP written by Guido van Rossum.
Implemented by Travis Oliphant, Antoine Pitrou and others.
Backported to 2.7 by Antoine Pitrou; bpo-2396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2396}.
@end table


@node その他の言語変更<14>,新しいモジュールと改良されたモジュール,PEP 3137 memoryview オブジェクト,What's New in Python 2 7
@anchor{whatsnew/2 7 other-language-changes}@anchor{1511}
@subsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
set リテラルのためのシンタックスが Python 3.x からバックポートされました。内容を波括弧で囲うと mutable set になります。dict リテラルとの区別は、コロンと value が存在しないことで行われます。なので、@code{@{@}} は引き続き空の dict になります。空の set を作るときには @code{set()} を使ってください。

@example
>>> @{1, 2, 3, 4, 5@}
set([1, 2, 3, 4, 5])
>>> set() # empty set
set([])
>>> @{@}    # empty dict
@{@}
@end example

Backported by Alexandre Vassalotti; bpo-2335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2335}.

@item 
dict と set の内包表記も Python 3.x からバックポートされました。list と generator の内包表記を set と dict にも使えるように一般化させています。

@example
>>> @{x: x*x for x in range(6)@}
@{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25@}
>>> @{('a'*x) for x in range(6)@}
set(['@w{'}, 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
@end example

Backported by Alexandre Vassalotti; bpo-2333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2333}.

@item 
@ref{186,,with} 文が1つの文で複数のコンテキストマネージャーを使えるようになりました。コンテキストマネージャーは左から右へ処理され、それぞれが新しい @code{with} 文の開始となるように扱われます。つまり:

@example
with A() as a, B() as b:
    ... suite of statements ...
@end example

は、以下と同じです

@example
with A() as a:
    with B() as b:
        ... suite of statements ...
@end example

The @code{contextlib.nested()} function provides a very similar
function, so it's no longer necessary and has been deprecated.

(Proposed in @indicateurl{https://codereview.appspot.com/53094}; implemented by
Georg Brandl.)

@item 
浮動小数点数と文字列の間の変換がほとんどのプラットフォームで正しく丸められるようになりました。この変換はいろいろな場面で発生します: float 型や complex 型に対する @ref{169,,str()} 関数の適用、 @ref{196,,float} や @ref{197,,complex} コンストラクタ、数値フォーマット、 @ref{91,,marshal}, @ref{ab,,pickle}, @ref{86,,json} モジュールを使ってのシリアライズとデシリアライズ、 Python コード中の float や imaginary リテラルの解析、 @ref{1fe,,Decimal} から float への変換などです。

これに関連して、浮動小数点数 `x' の @ref{1c1,,repr()} は、 (round-half-to-even 丸めモードで)正しく丸め処理をした場合に元の `x' に戻せる最小の 10進文字列になりました。以前は `x' を17桁の10進文字列に丸めていました。

@c maybe add an example?

丸めライブラリが、この改善が Windows や gcc, icc, suncc を使った Unix 環境で動かす役目をおっています。このライブラリの正確な動作が保証できない少しの環境があるので、そういったシステムではこのライブラリは利用されません。 @ref{1512,,sys.float_repr_style} が @code{short} なら新しいコードが利用されていて、 @code{legacy} なら利用されていません。

Implemented by Eric Smith and Mark Dickinson, using David Gay's
@code{dtoa.c} library; bpo-7117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7117}.

@item 
多倍長整数や通常の整数から浮動小数点への変換でも丸め処理が変更され、元の数に一番近い浮動小数点値が返されるようになりました。これは浮動小数点へ完全に変換できる小さい整数では問題になりませんが、桁数に対して精度がどうしても足りない場合に関係します。Python 2.7 はより正確に近似するようになりました。例えば、Python 2.6 では次のように計算されていました:

@example
>>> n = 295147905179352891391
>>> float(n)
2.9514790517935283e+20
>>> n - long(float(n))
65535L
@end example

Python 2.7 の浮動小数点への変換結果は元の数値より大きくなりますが、元の値により近くなっています:

@example
>>> n = 295147905179352891391
>>> float(n)
2.9514790517935289e+20
>>> n - long(float(n))
-1L
@end example

(Implemented by Mark Dickinson; bpo-3166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3166}.)

この丸めの動作により、整数同士の true division (@code{from __future__ import division}) の結果もより正確になりました。 (Also implemented by Mark Dickinson; bpo-1811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1811}.)

@item 
Implicit coercion for complex numbers has been removed; the interpreter
will no longer ever attempt to call a @code{__coerce__()} method on complex
objects.  (Removed by Meador Inge and Mark Dickinson; bpo-5211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5211}.)

@item 
@ref{833,,str.format()} メソッドは置換フィールドに対する自動ナンバリングをサポートするようになりました。これにより @ref{833,,str.format()} をより @code{%s} と同じように使えるようになりました。

@example
>>> '@{@}:@{@}:@{@}'.format(2009, 04, 'Sunday')
'2009:4:Sunday'
>>> '@{@}:@{@}:@{day@}'.format(2009, 4, day='Sunday')
'2009:4:Sunday'
@end example

自動ナンバリングは左のフィールドから右のフィールドへと行われるので、最初の @code{@{...@}} 指定は @ref{833,,str.format()} メソッドの最初の引数を利用し、次の指定は次の引数を利用します。自動ナンバリングと明示的なナンバリングを混ぜて使うことはできず、全ての置換指定に手動でナンバリングするか、全てを自動ナンバリングに任せなければなりません。ただし、上の例の2つめのように、自動ナンバリングと名前フィールドを混ぜて使うことは可能です。 (Contributed by Eric Smith; bpo-5237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5237}.)

複素数が @ref{199,,format()} をサポートするようになりました。デフォルトでは右寄せになります。精度やカンマ区切りの指定は、実部と虚部のそれぞれに対して適用されます。アラインの指定は @code{1.5+3j} のような複素数全体に対して適用されます。 (Contributed by Eric Smith; bpo-1588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1588} and bpo-7988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7988}.)

'F' 書式符号は常に大文字を使って出力するようになり、 'INF' や 'NAN' が出力されるようになりました。 (Contributed by Eric Smith; bpo-3382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3382}.)

A low-level change: the @ref{831,,object.__format__()} method now triggers
a @ref{ac5,,PendingDeprecationWarning} if it's passed a format string,
because the @code{__format__()} method for @ref{c7e,,object} converts
the object to a string representation and formats that.  Previously
the method silently applied the format string to the string
representation, but that could hide mistakes in Python code.  If
you're supplying formatting information such as an alignment or
precision, presumably you're expecting the formatting to be applied
in some object-specific way.  (Fixed by Eric Smith; bpo-7994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7994}.)

@item 
The @ref{19b,,int()} and @code{long()} types gained a @code{bit_length}
method that returns the number of bits necessary to represent
its argument in binary:

@example
>>> n = 37
>>> bin(n)
'0b100101'
>>> n.bit_length()
6
>>> n = 2**123-1
>>> n.bit_length()
123
>>> (n+1).bit_length()
124
@end example

(Contributed by Fredrik Johansson and Victor Stinner; bpo-3439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3439}.)

@item 
@ref{7f8,,import} 文が、絶対インポート (例: @code{from .os import sep})が失敗したときに相対インポートを試さなくなりました。これはバグ修正ですが、いままでたまたま動いていただけの @code{import}  文を動かなくしてしまう可能性があります。(Fixed by Meador Inge; bpo-7902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7902}.)

@item 
It's now possible for a subclass of the built-in @code{unicode} type
to override the @code{__unicode__()} method.  (Implemented by
Victor Stinner; bpo-1583863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1583863}.)

@item 
@ref{344,,bytearray} 型の @ref{1513,,translate()} メソッドが第一引数に @code{None} を受け入れるようになりました。 (Fixed by Georg Brandl; bpo-4759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4759}.)

@c XXX bytearray doesn't seem to be documented

@item 
When using @ref{48e,,@@classmethod} and
@ref{453,,@@staticmethod} to wrap
methods as class or static methods, the wrapper object now
exposes the wrapped function as their @ref{1514,,__func__}
attribute.
(Contributed by Amaury Forgeot d'Arc, after a suggestion by
George Sakkis; bpo-5982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5982}.)

@item 
@code{__slots__} を利用して属性を制限した場合に、設定されていない属性を del したときに @ref{5f0,,AttributeError} にならなかったのを修正しました。 (Fixed by Benjamin Peterson; bpo-7604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7604}.)

@item 
2つの新しいエンコーディングが追加されました: "cp720" は主にアラビア文字に使われます。 "cp858" は cp850 の一種ですが、ユーロ記号を追加しています。 (CP720 contributed by Alexander Belchenko and Amaury Forgeot d'Arc in bpo-1616979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1616979}; CP858 contributed by Tim Hatch in bpo-8016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8016}.)

@item 
The @code{file} object will now set the @code{filename} attribute
on the @ref{125e,,IOError} exception when trying to open a directory
on POSIX platforms (noted by Jan Kaliszewski; bpo-4764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4764}), and
now explicitly checks for and forbids writing to read-only file objects
instead of trusting the C library to catch and report the error
(fixed by Stefan Krah; bpo-5677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5677}).

@item 
Python の字句解析機は改行をそれ自身に変換するようになりました。それにより、組み込みの @ref{4b1,,compile()} 関数がどの改行コードを利用したコードでも受け付けるようになりました。また、コードの終端の改行も不要になりました。

@item 
関数宣言中の余分な丸括弧は Python 3.x では不正になりました。つまり、 @code{def f((x)): pass} はsyntax errorになります。 Python3 警告モードでは、 Python 2.7 はこの利用方法について警告を出すようになりました。 (Noted by James Lingard; bpo-7362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7362}.)

@item 
古いスタイルのクラスのオブジェクトに対して弱参照を作れるようになりました。新スタイルクラスには以前から弱参照を利用できます。(Fixed by Antoine Pitrou; bpo-8268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8268}.)

@item 
モジュールオブジェクトがGCされたとき、モジュールの辞書は、他にその辞書への参照を持っているものがない場合にのみクリアされるようになりました。(bpo-7140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7140}).
@end itemize

@c ======================================================================

@menu
* インタプリタの変更:: 
* 最適化: 最適化<14>. 

@end menu

@node インタプリタの変更,最適化<14>,,その他の言語変更<14>
@anchor{whatsnew/2 7 interpreter-changes}@anchor{1515}@anchor{whatsnew/2 7 new-27-interpreter}@anchor{1516}
@subsubsection インタプリタの変更


新しい環境変数 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} を使って警告を制御できるようになりました。この環境変数には、 @ref{ac6,,-W} スイッチに使われる警告の設定を、カンマ区切りの文字列として指定します。 (Contributed by Brian Curtin; bpo-7301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7301}.)

For example, the following setting will print warnings every time
they occur, but turn warnings from the @ref{75,,Cookie} module into an
error.  (The exact syntax for setting an environment variable varies
across operating systems and shells.)

@example
export PYTHONWARNINGS=all,error:::Cookie:0
@end example

@c ======================================================================

@node 最適化<14>,,インタプリタの変更,その他の言語変更<14>
@anchor{whatsnew/2 7 optimizations}@anchor{1517}
@subsubsection 最適化


いくつかの場面でパフォーマンスが向上しています。


@itemize *

@item 
A new opcode was added to perform the initial setup for
@ref{186,,with} statements, looking up the @ref{7e4,,__enter__()} and
@ref{1518,,__exit__()} methods.  (Contributed by Benjamin Peterson.)

@item 
たくさんのオブジェクトを開放せずに確保していくという、よくある使い方の 1つにおいて、GCのパフォーマンスが向上しました。以前はこの場合にGCにかかる時間はオブジェクトの数の2乗に比例していました。現在はフルGCの数は増えたヒープ上のオブジェクトの数に比例しています。新しい方式では、3世代中2世代目に対するGCが10回実行されたうえで、 2世代目から3世代目に移ったオブジェクトの数が3世代目のオブジェクトの数の 10%を超えたときにフルGCが発生します。(Suggested by Martin von Löwis and implemented by Antoine Pitrou; bpo-4074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4074}.)

@item 
GCが循環参照になりえないシンプルなコンテナ型の追跡を避けるようになりました。 Python 2.7 では、アトミックな型(整数、文字列など)のみを含むタプルと辞書は追跡されません。推移的に、アトミックな型のみを含むタプルを含む辞書も、同じく追跡されません。これにより、GCによって巡回されチェックされるオブジェクトの数が減るので、 GCのコストを減らすことができます。 (Contributed by Antoine Pitrou; bpo-4688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4688}.)

@item 
Long integers are now stored internally either in base @code{2**15} or in base
@code{2**30}, the base being determined at build time.  Previously, they
were always stored in base @code{2**15}.  Using base @code{2**30} gives
significant performance improvements on 64-bit machines, but
benchmark results on 32-bit machines have been mixed.  Therefore,
the default is to use base @code{2**30} on 64-bit machines and base @code{2**15}
on 32-bit machines; on Unix, there's a new configure option
@code{--enable-big-digits} that can be used to override this default.

Apart from the performance improvements this change should be
invisible to end users, with one exception: for testing and
debugging purposes there's a new structseq @code{sys.long_info} that
provides information about the internal format, giving the number of
bits per digit and the size in bytes of the C type used to store
each digit:

@example
>>> import sys
>>> sys.long_info
sys.long_info(bits_per_digit=30, sizeof_digit=4)
@end example

(Contributed by Mark Dickinson; bpo-4258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4258}.)

その他の変更により、多倍長整数オブジェクトのサイズは数バイト小さくなりました。 32bit システムでは 2byte, 64bit システムでは 6byte 小さくなりました。 (Contributed by Mark Dickinson; bpo-5260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5260}.)

@item 
多倍長整数の除算アルゴリズムが、内部のループの軽量化や乗算からシフト演算への置き換え、不要なイテレーションの削除により高速化されました。いくつかのベンチマークによると、多倍長整数の剰余演算は 50% から 150% 高速化されています。 (Contributed by Mark Dickinson; bpo-5512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5512}.) ビット演算も高速化されています。(initial patch by Gregory Smith; bpo-1087418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1087418})

@item 
@code{%} の実装が、左側のオペランドが文字列型かどうかをチェックしてその場合の処理を特殊化しました。これにより文字列に対して @code{%} を頻繁に使う、テンプレートライブラリなどのアプリケーションのパフォーマンスが1--3%向上します。 (Implemented by Collin Winter; bpo-5176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5176}.)

@item 
@code{if} 条件付きのリスト内包表記がより高速なバイトコードにコンパイルされるようになりました。(Patch by Antoine Pitrou, back-ported to 2.7 by Jeffrey Yasskin; bpo-4715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4715}.)

@item 
整数や多倍長整数から10進文字列への変換を、任意の基数をサポートした汎用の変換関数を使う代わりに10進数に特殊化した処理を行うことで高速化しました。 (Patch by Gawain Bolton; bpo-6713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6713}.)

@item 
The @code{split()}, @code{replace()}, @code{rindex()},
@code{rpartition()}, and @code{rsplit()} methods of string-like types
(strings, Unicode strings, and @ref{344,,bytearray} objects) now use a
fast reverse-search algorithm instead of a character-by-character
scan.  This is sometimes faster by a factor of 10.  (Added by
Florent Xicluna; bpo-7462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7462} and bpo-7622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7622}.)

@item 
The @ref{ab,,pickle} and @code{cPickle} modules now automatically
intern the strings used for attribute names, reducing memory usage
of the objects resulting from unpickling.  (Contributed by Jake
McGuire; bpo-5084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5084}.)

@item 
The @code{cPickle} module now special-cases dictionaries,
nearly halving the time required to pickle them.
(Contributed by Collin Winter; bpo-5670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5670}.)
@end itemize

@c ======================================================================

@node 新しいモジュールと改良されたモジュール,ビルドならびに C API の変更<8>,その他の言語変更<14>,What's New in Python 2 7
@anchor{whatsnew/2 7 new-and-improved-modules}@anchor{1519}
@subsection 新しいモジュールと改良されたモジュール


全てのリリースに置いて、 Python の標準ライブラリはたくさんの改良とバグ修正がされてきました。ここでは一部の注目に値する変更を、モジュール名で辞書順ソートしてリストアップしています。もっと完全な変更リストが見たければ、ソースツリー内の @code{Misc/NEWS} ファイルか、全ての完全な詳細が入っている Subversion のログを参照してください。


@itemize *

@item 
@ref{10,,bdb} モジュールの基底デバッガクラス @ref{2d5,,Bdb} に、モジュールをスキップする機能が追加されました。コンストラクタは @code{django.*} のような glob スタイルのパターンをもった iterable を引数として受け取ります。デバッガはパターンのどれかにマッチするスタックフレームにステップインしません。 (Contributed by Maru Newby after a suggestion by Senthil Kumaran; bpo-5142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5142}.)

@item 
@ref{11,,binascii} モジュールが buffer API をサポートするようになり、 @ref{165,,memoryview} インスタンスやその他のバッファオブジェクトともに利用できるようになりました。 (Backported from 3.x by Florent Xicluna; bpo-7703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7703}.)

@item 
Updated module: the @code{bsddb} module has been updated from 4.7.2devel9
to version 4.8.4 of
the pybsddb package@footnote{https://www.jcea.es/programacion/pybsddb.htm}.
The new version features better Python 3.x compatibility, various bug fixes,
and adds several new BerkeleyDB flags and methods.
(Updated by Jesús Cea Avión; bpo-8156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8156}.  The pybsddb
changelog can be read at @indicateurl{https://hg.jcea.es/pybsddb/file/tip/ChangeLog}.)

@item 
@ref{14,,bz2} モジュールの @ref{a66,,BZ2File} がコンテキストマネージャープロトコルをサポートするようになりました。これにより、 @code{with bz2.BZ2File(...) as f:} といった書き方ができます。 (Contributed by Hagen Fürstenau; bpo-3860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3860}.)

@item 
@ref{1e,,collections} モジュールの新しい @ref{12a3,,Counter} クラスは、データの数え上げをするときに便利です。 @ref{12a3,,Counter} インスタンスは辞書のように振る舞いますが、キーが存在しなかったときに @ref{5e7,,KeyError} 例外を発生させる代わりに 0 を返します。

@example
>>> from collections import Counter
>>> c = Counter()
>>> for letter in 'here is a sample of english text':
...   c[letter] += 1
...
>>> c
Counter(@{' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
'p': 1, 'r': 1, 'x': 1@})
>>> c['e']
5
>>> c['z']
0
@end example

@ref{12a3,,Counter} には追加の3つのメソッドがあります。 @ref{151a,,most_common()} はカウントが最も多い N 要素とそのカウントを返します。 @ref{151b,,elements()} はカウントしている要素を、そのカウント数だけ繰り返すイテレータを返します。 @ref{13f7,,subtract()} はイテレート可能型を受け取り、その各要素を足すのではなく引いて行きます。引数が辞書か他の @code{Counter} だった場合は、そのカウントが引かれます。

@example
>>> c.most_common(5)
[(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
>>> c.elements() ->
   'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
   'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
   'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
   's', 's', 'r', 't', 't', 'x'
>>> c['e']
5
>>> c.subtract('very heavy on the letter e')
>>> c['e']    # Count is now lower
-1
@end example

Contributed by Raymond Hettinger; bpo-1696199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1696199}.

@c revision 79660

新しいクラス @ref{7f3,,OrderedDict} はすでに @ref{1501,,PEP 372; collections に順序付き辞書を追加} で紹介しました。

メソッドが追加されました。@ref{7f4,,deque}  データ型の @ref{13f9,,count()}  メソッドは、引数で指定された `x' と等しい要素が何個入っているかを返します。 @ref{13fa,,reverse()} メソッドは deque 内の要素をインプレースで逆順にします。 @ref{7f4,,deque} はまた、最大長を返す読み出し専用の属性 @ref{151c,,maxlen} を持ちます。 (Both features added by Raymond Hettinger.)

@ref{4e0,,namedtuple} クラスにオプションの `rename' 引数が追加されました。 `rename' が真のとき、複数回現れたり Python の識別子として許可されないために無効なフィールド名があったとき、フィールドのリスト内での場所に基づく有効なフィールド名に置き換えられます。

@example
>>> from collections import namedtuple
>>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
>>> T._fields
('field1', '_1', '_2', 'field2')
@end example

(Added by Raymond Hettinger; bpo-1818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1818}.)

Finally, the @ref{ac7,,Mapping} abstract base class now
returns @ref{1a2,,NotImplemented} if a mapping is compared to
another type that isn't a @code{Mapping}.
(Fixed by Daniel Stutzbach; bpo-8729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8729}.)

@item 
Constructors for the parsing classes in the @ref{26,,ConfigParser} module now
take an `allow_no_value' parameter, defaulting to false; if true,
options without values will be allowed.  For example:

@example
>>> import ConfigParser, StringIO
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-bdb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(StringIO.StringIO(sample_config))
>>> config.get('mysqld', 'user')
'mysql'
>>> print config.get('mysqld', 'skip-bdb')
None
>>> print config.get('mysqld', 'unknown')
Traceback (most recent call last):
  ...
NoOptionError: No option 'unknown' in section: 'mysqld'
@end example

(Contributed by Mats Kindahl; bpo-7005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7005}.)

@item 
Deprecated function: @code{contextlib.nested()}, which allows
handling more than one context manager with a single @ref{186,,with}
statement, has been deprecated, because the @code{with} statement
now supports multiple context managers.

@item 
The @ref{74,,cookielib} module now ignores cookies that have an invalid
version field, one that doesn't contain an integer value.  (Fixed by
John J. Lee; bpo-3924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3924}.)

@item 
@ref{29,,copy} モジュールの @ref{d65,,deepcopy()} 関数が、束縛ずみインスタンスメソッドを正しくコピーするようになりました。(Implemented by Robert Collins; bpo-1515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1515}.)

@item 
@ref{2e,,ctypes} モジュールが、ポインタとして宣言された引数に対して @code{None} が渡された場合常に C の @code{NULL} ポインタに変換するようになりました。(Changed by Thomas Heller; bpo-4606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4606}.) 根底の、 libffi ライブラリ@footnote{https://sourceware.org/libffi/} がバージョン 3.0.9 にアップデートされ、いくつかのプラットフォームにおけるいろいろな問題が修正されました。(Updated by Matthias Klose; bpo-8142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8142}.)

@item 
新しいメソッド: @ref{34,,datetime} モジュールの @ref{bc3,,timedelta} クラスに @ref{151d,,total_seconds()} メソッドが追加されました。これはその期間の秒数を返します。(Contributed by Brian Quinlan; bpo-5788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5788}.)

@item 
New method: the @ref{1fe,,Decimal} class gained a
@ref{141d,,from_float()} class method that performs an exact
conversion of a floating-point number to a @code{Decimal}.
This exact conversion strives for the
closest decimal approximation to the floating-point representation's value;
the resulting decimal value will therefore still include the inaccuracy,
if any.
For example, @code{Decimal.from_float(0.1)} returns
@code{Decimal('0.1000000000000000055511151231257827021181583404541015625')}.
(Implemented by Raymond Hettinger; bpo-4796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4796}.)

Comparing instances of @ref{1fe,,Decimal} with floating-point
numbers now produces sensible results based on the numeric values
of the operands.  Previously such comparisons would fall back to
Python's default rules for comparing objects, which produced arbitrary
results based on their type.  Note that you still cannot combine
@code{Decimal} and floating point in other operations such as addition,
since you should be explicitly choosing how to convert between float and
@code{Decimal}.  (Fixed by Mark Dickinson; bpo-2531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2531}.)

@ref{1fe,,Decimal} のコンストラクタが浮動小数点数を受け入れるようになりました。 (added by Raymond Hettinger; bpo-8257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8257}) また、アラビア・インド数字などの、ヨーロッパ以外の Unicode 文字も受け入れるようになりました。 (contributed by Mark Dickinson; bpo-6595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6595}).

@ref{12c3,,Context} クラスのほとんどのメソッドが @ref{1fe,,Decimal} インスタンスと同じく整数を受け入れるようになりました。例外は @ref{151e,,canonical()} と @ref{151f,,is_canonical()} メソッドだけです。 (Patch by Juan José Conti; bpo-7633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7633}.)

@ref{1fe,,Decimal} インスタンスを文字列の @ref{833,,format()} メソッドで利用した場合、デフォルトのアライメントが左揃えから、数値型に適した右揃えに変更されました。  (Changed by Mark Dickinson; bpo-6857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6857}.)

signaling NaN (あるいは @code{sNAN}) との比較は、暗黙に比較演算に応じて真偽値を返すのではなく、 @ref{12bc,,InvalidOperation} 例外を発生させるようになりました。 Quiet NaN (あるいは @code{NAN}) はハッシュ可能になりました。 (Fixed by Mark Dickinson; bpo-7279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7279}.)

@item 
@ref{3b,,difflib} モジュールの出力が、ファイル名を含むヘッダのセパレータにスペースではなくタブ文字を使うようになり、最近の @code{diff}/@code{patch} ツールとの互換性が高くなりました。(Fixed by Anatoly Techtonik; bpo-7585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7585}.)

@item 
Distutils @code{sdist} コマンドが、 @code{MANIFEST.in} や @code{setup.py} ファイルが変更されていなくても、ユーザーが作成したかもしれない新しいファイルが含まれるようにするために、毎回 @code{MANIFEST} ファイルを再生成するようになりました。 (Fixed by Tarek Ziadé; bpo-8688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8688}.)

@item 
The @ref{3e,,doctest} module's @ref{1520,,IGNORE_EXCEPTION_DETAIL} flag
will now ignore the name of the module containing the exception
being tested.  (Patch by Lennart Regebro; bpo-7490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7490}.)

@item 
The @ref{3f,,email} module's @ref{581,,Message} class will
now accept a Unicode-valued payload, automatically converting the
payload to the encoding specified by @code{output_charset}.
(Added by R. David Murray; bpo-1368247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1368247}.)

@item 
@ref{213,,Fraction} クラスが、コンストラクタの引数として、 1つの float 値、 @ref{1fe,,Decimal} インスタンス、 2つの有理数を受け入れるようになりました。(Implemented by Mark Dickinson; rationals added in bpo-5812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5812}, and float/decimal in bpo-8294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8294}.)

fraction と complex 数の間の順序比較演算 (@code{<}, @code{<=}, @code{>}, @code{>=})が @ref{198,,TypeError} 例外を発生させるようになりました。これは過失を修正し、 @ref{213,,Fraction} を他の数値型とマッチさせます。

@c revision 79455

@item 
新しいクラス: @ref{af7,,FTP_TLS} が @ref{62,,ftplib} に追加されました。認証とその後の制御・データ転送をTLSカプセル化することでセキュアなFTP接続を提供します。 (Contributed by Giampaolo Rodola; bpo-2054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2054}.)

バイナリデータのアップロードを行う @ref{1521,,storbinary()} に `rest' 引数が追加され、アップロードのリスタートができるようになりました。 (patch by Pablo Mouzo; bpo-6845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6845}.)

@item 
New class decorator: @ref{1144,,total_ordering()} in the @ref{63,,functools}
module takes a class that defines an @ref{cf2,,__eq__()} method and one of
@ref{14b8,,__lt__()}, @ref{1522,,__le__()}, @ref{1523,,__gt__()}, or @ref{1524,,__ge__()},
and generates the missing comparison methods.  Since the
@code{__cmp__()} method is being deprecated in Python 3.x,
this decorator makes it easier to define ordered classes.
(Added by Raymond Hettinger; bpo-5479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5479}.)

新しい関数: @ref{13f2,,cmp_to_key()} 関数は、古いスタイルの2引数を受け取る比較関数を受け取り、 @ref{dc7,,sorted()}, @ref{110b,,min()}, @ref{110c,,max()} などの `key' 引数に利用できる呼び出し可能オブジェクトを返します。この関数の主な目的は、古いコードを Python 3.x へ対応させるのを手助けすることです。(Added by Raymond Hettinger.)

@item 
新しい関数: @ref{64,,gc} モジュールに @ref{1525,,is_tracked()} 関数が追加されました。渡されたオブジェクトがGCに追跡されている場合に True を、そうでない場合に False を返します。 (Contributed by Antoine Pitrou; bpo-4688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4688}.)

@item 
@ref{6b,,gzip} モジュールの @ref{65c,,GzipFile} がコンテキストマネージャープロトコルをサポートしました。 @code{with gzip.GzipFile(...) as f:} と書くことができます。(contributed by Hagen Fürstenau; bpo-3860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3860} また、 @ref{8a3,,io.BufferedIOBase} ABC を実装しています。なので、より高速な処理のために @ref{1427,,io.BufferedReader} でラップすることができます。 (contributed by Nir Aides; bpo-7471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7471}). さらに、コンストラクタにオプションのタイムスタンプを指定することで、 gzip ファイル内の変更時間レコードをオーバーライドすることができるようになりました。  (Contributed by Jacques Frechet; bpo-4272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4272}.)

gzip ファイルフォーマットのファイルは最後にゼロバイトによるパディングができるようになりました。 @ref{6b,,gzip} モジュールは末尾のゼロバイトを消費します。(Fixed by Tadek Pietraszek and Brian Curtin; bpo-2846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2846}.)

@item 
New attribute: the @ref{6c,,hashlib} module now has an @code{algorithms}
attribute containing a tuple naming the supported algorithms.
In Python 2.7, @code{hashlib.algorithms} contains
@code{('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')}.
(Contributed by Carl Chenet; bpo-7418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7418}.)

@item 
The default @ref{12e5,,HTTPResponse} class used by the @ref{72,,httplib} module now
supports buffering, resulting in much faster reading of HTTP responses.
(Contributed by Kristján Valur Jónsson; bpo-4879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4879}.)

The @ref{d35,,HTTPConnection} and @ref{d36,,HTTPSConnection} classes
now support a `source_address' parameter, a @code{(host, port)} 2-tuple
giving the source address that will be used for the connection.
(Contributed by Eldon Ziegler; bpo-3972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3972}.)

@item 
The @code{ihooks} module now supports relative imports.  Note that
@code{ihooks} is an older module for customizing imports,
superseded by the @code{imputil} module added in Python 2.0.
(Relative import support added by Neil Schemenauer.)

@c revision 75423

@item 
@ref{78,,imaplib} モジュールが IPv6 アドレスをサポートするようになりました。 (Contributed by Derek Morr; bpo-1655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1655}.)

@item 
@ref{82,,inspect} モジュールに @ref{10be,,getcallargs()} 関数が追加されました。 callable とその位置引数、キーワード引数を受け取り、 callable のどの仮引数がどの実引数を受け取るかを計算し、引数名から値へマップする辞書を返します。例えば:

@example
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
...     pass
...
>>> getcallargs(f, 1, 2, 3)
@{'a': 1, 'b': 2, 'pos': (3,), 'named': @{@}@}
>>> getcallargs(f, a=2, x=4)
@{'a': 2, 'b': 1, 'pos': (), 'named': @{'x': 4@}@}
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() takes at least 1 argument (0 given)
@end example

Contributed by George Sakkis; bpo-3135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3135}.

@item 
Updated module: The @ref{83,,io} library has been upgraded to the version shipped with
Python 3.1.  For 3.1, the I/O library was entirely rewritten in C
and is 2 to 20 times faster depending on the task being performed.  The
original Python version was renamed to the @code{_pyio} module.

One minor resulting change: the @ref{8a4,,io.TextIOBase} class now
has an @ref{1526,,errors} attribute giving the error setting
used for encoding and decoding errors (one of @code{'strict'}, @code{'replace'},
@code{'ignore'}).

@ref{1527,,io.FileIO} クラスは、無効なファイルディスクリプタを渡されたときに @ref{2c0,,OSError} を送出するようになりました。(Implemented by Benjamin Peterson; bpo-4991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4991}.) @ref{1528,,truncate()} メソッドは、ファイル位置を保存するようになりました。以前は、ファイル位置を新しいファイルの末尾に変更しました。(Fixed by Pascal Chambon; bpo-6939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6939}.)

@item 
新しい関数: @code{itertools.compress(data, selectors)} は、2 つのイテレータを取ります。`data' の要素は、`selectors' の対応する値が真であれば返されます:

@example
itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F
@end example

@c maybe here is better to use >>> list(itertools.compress(...)) instead

新しい関数: @code{itertools.combinations_with_replacement(iter, r)} は、 `iter' から、すべての可能な長さ `r' の要素の組合せを返します。 @ref{1529,,combinations()} とは異なり、生成された組合せに個別の要素が繰り返し出現できます:

@example
itertools.combinations_with_replacement('abc', 2) =>
  ('a', 'a'), ('a', 'b'), ('a', 'c'),
  ('b', 'b'), ('b', 'c'), ('c', 'c')
@end example

なお要素は、実際の値ではなく、その入力内での位置に依って一意であるとみなされます。

@ref{149b,,itertools.count()} 関数は、1 以外の値を増分できるように、 `step' 引数を追加しました。 @ref{149b,,count()} はまた、キーワード引数に対応し、さらに浮動小数点数や @ref{1fe,,Decimal} インスタンスのような、非整数の値を使えるようになりました。(Implemented by Raymond Hettinger; bpo-5032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5032}.)

@ref{1529,,itertools.combinations()} および @ref{152a,,itertools.product()} は、以前は入力のイテレート可能オブジェクトより大きい `r' に @ref{2ec,,ValueError} を返していました。これは仕様エラーと認められ、空のイテレータを返すようになりました。(Fixed by Raymond Hettinger; bpo-4816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4816}.)

@item 
更新されたモジュール: @ref{86,,json} モジュールが、エンコーディングやデコーディングを高速化する C 拡張を含んだ、 simplejson パッケージのバージョン 2.0.9 にアップグレードされました。 (Contributed by Bob Ippolito; bpo-4136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4136}.)

新しい @ref{7f3,,collections.OrderedDict} 型をサポートするために、 @ref{eb2,,json.load()} はオプションとして、任意のオブジェクトリテラルに対して呼び出され、ペアのリストにデコードする `object_pairs_hook' パラメタを追加しました。(Contributed by Raymond Hettinger; bpo-5381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5381}.)

@item 
@ref{8f,,mailbox} モジュールの @ref{65e,,Maildir} クラスは、読み込むディレクトリのタイムスタンプを記録し、その後に更新時刻が変わった場合にのみ再読み込みするようになりました。これは不必要なディレクトリ走査を避けることでパフォーマンスを向上させます。(Fixed by A.M. Kuchling and Antoine Pitrou; bpo-1607951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1607951}, bpo-6896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6896}.)

@item 
新しい関数: @ref{92,,math} モジュールは、誤差関数と相補誤差関数 @ref{dd3,,erf()} および @ref{dd4,,erfc()} 、 @code{e**x - 1} を @ref{152b,,exp()} から 1 を引くのよりも高い精度で計算する @ref{1405,,expm1()} 、ガンマ関数 @ref{1406,,gamma()} 、そしてガンマ関数の自然対数 @ref{1407,,lgamma()} を追加しました。 (Contributed by Mark Dickinson and nirinA raseliarison; bpo-3366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3366}.)

@item 
The @ref{98,,multiprocessing} module's @code{Manager*} classes
can now be passed a callable that will be called whenever
a subprocess is started, along with a set of arguments that will be
passed to the callable.
(Contributed by lekma; bpo-5585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5585}.)

The @ref{116d,,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
@code{Pool} to start a new worker.  This is useful if tasks may leak
memory or other resources, or if some tasks will cause the worker to
become very large.
(Contributed by Charles Cazabon; bpo-6963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6963}.)

@item 
The @code{nntplib} module now supports IPv6 addresses.
(Contributed by Derek Morr; bpo-1664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1664}.)

@item 
新しい関数: @ref{a5,,os} モジュールは、以下の POSIX システムコールをラップします: real, effective, および saved GID と UID を返す、 @ref{152c,,getresgid()} と @ref{152d,,getresuid()} 、 real, effective, および saved GID と UID を新しく設定する、 @ref{152e,,setresgid()} と @ref{152f,,setresuid()} 、現在のプロセスにグループアクセスリストを初期化する @ref{1530,,initgroups()}  。 (GID/UID functions contributed by Travis H.; bpo-6508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6508}. Support for initgroups added by Jean-Paul Calderone; bpo-7333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7333}.)

@ref{4b5,,os.fork()} 関数は、子プロセス中で import ロックを再初期化するようになりました。これは、Solaris における @ref{4b5,,fork()} がスレッドから呼び出された時の問題を修正します。(Fixed by Zsolt Cserna; bpo-7242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7242}.)

@item 
@ref{a6,,os.path} モジュールの、 @ref{1531,,normpath()} および @ref{1532,,abspath()} 関数は、Unicode を保存するようになりました。入力パスが Unicode なら、戻り値も Unicode 文字列になります。 (@ref{1531,,normpath()} fixed by Matt Giuca in bpo-5827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5827}; @ref{1532,,abspath()} fixed by Ezio Melotti in bpo-3426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3426}.)

@item 
@ref{ba,,pydoc} モジュールは、Python が使う様々なシンボルのヘルプを追加しました。例えば、 @code{help('<<')} や @code{help('@@')} とできるようになりました。(Contributed by David Laban; bpo-4739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4739}.)

@item 
@ref{be,,re} モジュールの @ref{5a2,,split()}, @ref{5a3,,sub()}, および @ref{5a4,,subn()} は、モジュールの他の関数との一貫性のため、オプションの `flags' 引数を受け付けるようになりました。 (Added by Gregory P. Smith.)

@item 
新しい関数: @ref{c3,,runpy} モジュールの @ref{4a4,,run_path()} は、与えられた `path' 引数のコードを実行します。 `path' は Python ソースファイルのパス (@code{example.py})、コンパイル済みバイトコードファイル (@code{example.pyc})、ディレクトリ (@code{./package/})、または zip アーカイブ (@code{example.zip}) にできます。ディレクトリか zip パスが与えられると、それが @code{sys.path} の最初に加えられ、モジュール @ref{1,,__main__} が import されます。これは、ディレクトリや zip が @code{__main__.py} を含むことを期待します。なければ、他の @code{__main__.py} が @code{sys.path} の後の部分から import されることがあります。これにより、Python のコマンドラインが明示的なパス名を処理する方法を真似たいようなスクリプトに、 @ref{c3,,runpy} のより多くの機構が利用できるようになります。 (Added by Nick Coghlan; bpo-6816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6816}.)

@item 
新しい関数: @ref{ca,,shutil} モジュールの @ref{6da,,make_archive()} は、ファイル名、アーカイブ型 (zip または tar-format)、およびディレクトリパスを取って、そのディレクトリの内容を含むアーカイブを生成します。(Added by Tarek Ziadé.)

@ref{ca,,shutil} の @ref{c4e,,copyfile()} および @ref{c1e,,copytree()} 関数は、名前付きパイプのコピーを求められたときに @ref{1533,,SpecialFileError} 例外を送出する様になりました。以前は、コードは、名前付きパイプを、通常のファイルのように読み込み用に開いて扱い、いつまでもブロックしていました。 (Fixed by Antoine Pitrou; bpo-3002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3002}.)

@item 
@ref{cb,,signal} モジュールは、シグナルハンドラを本当に必要でない限り再インストールしなくなりました。これで、EINTR シグナルを確実に捕えられないバグが修正されました。(Fixed by Charles-Francois Natali; bpo-8354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8354}.)

@item 
新しい関数: @ref{cc,,site} モジュールの、新しい関数群は様々なサイトおよびユーザに特有のパスを返します。 @ref{1456,,getsitepackages()} は、全てのグローバル site-packages ディレクトリを含むリストを返します。 @ref{1458,,getusersitepackages()} は、ユーザの site-packages ディレクトリのパスを返します。そして、 @ref{1457,,getuserbase()} は、データの保存に使えるディレクトリへのパスを与える、 @ref{1534,,USER_BASE} 環境変数の値を返します。 (Contributed by Tarek Ziadé; bpo-6693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6693}.)

@ref{cc,,site} モジュールは @ref{cd,,sitecustomize} モジュールが import されたときに例外を報告するようになり、 @ref{bc5,,KeyboardInterrupt} 例外が捕捉されて飲み込まれることはなくなりました。 (Fixed by Victor Stinner; bpo-3137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3137}.)

@item 
@ref{882,,create_connection()} 関数は、接続に使われるソースアドレスを与える @code{(host, port)} の 2-タプル、 `source_address' パラメタを追加しました。 (Contributed by Eldon Ziegler; bpo-3972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3972}.)

@ref{1535,,recv_into()} および @ref{1536,,recvfrom_into()} メソッドは、バッファ API をサポートするオブジェクト、最も便利なのは @ref{344,,bytearray} や @ref{165,,memoryview} 、に書きこむようになりました。 (Implemented by Antoine Pitrou; bpo-8104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8104}.)

@item 
The @ref{d2,,SocketServer} module's @ref{1537,,TCPServer} class now
supports socket timeouts and disabling the Nagle algorithm.
The @code{disable_nagle_algorithm} class attribute
defaults to @code{False}; if overridden to be true,
new request connections will have the TCP_NODELAY option set to
prevent buffering many small sends into a single TCP packet.
The @ref{1538,,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, @ref{1539,,handle_timeout()}
will be called and @ref{153a,,handle_request()} will return.
(Contributed by Kristján Valur Jónsson; bpo-6192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6192} and bpo-6267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6267}.)

@item 
更新されたモジュール: @ref{d4,,sqlite3} モジュールが pysqlite パッケージ@footnote{https://github.com/ghaering/pysqlite} のバージョン 2.6.0 にアップデートされました。バージョン 2.6.0 はいくつかのバグ修正を含み、共有ライブラリから SQLite 拡張をロードできるようになりました。拡張を有効にするには @code{enable_load_extension(True)} メソッドを呼び出し、そして特定の共有ライブラリをロードするには @ref{6df,,load_extension()} を呼び出してください。 (Updated by Gerhard Häring.)

@item 
The @ref{d5,,ssl} module's @ref{ae7,,SSLSocket} objects now support the
buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
bpo-7133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7133}) and automatically set
OpenSSL's @code{SSL_MODE_AUTO_RETRY}, which will prevent an error
code being returned from @code{recv()} operations that trigger an SSL
renegotiation (fix by Antoine Pitrou; bpo-8222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8222}).

The @ref{748,,wrap_socket()} 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@footnote{https://docs.openssl.org/1.0.2/man1/ciphers/}.
(Added by Antoine Pitrou; bpo-8322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8322}.)

その他の変更により、拡張はOpenSSL の全ての暗号とメッセージダイジェストアルゴリズムをロードし、それらすべてが利用できるようにします。SSL 証明書の中には検証できないものもあり、"unknown algorithm" エラーを報告します。 (Reported by Beda Kosata, and fixed by Antoine Pitrou; bpo-8484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8484}.)

The version of OpenSSL being used is now available as the module
attributes @ref{1437,,ssl.OPENSSL_VERSION} (a string),
@ref{1438,,ssl.OPENSSL_VERSION_INFO} (a 5-tuple), and
@ref{1439,,ssl.OPENSSL_VERSION_NUMBER} (an integer).  (Added by Antoine
Pitrou; bpo-8321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8321}.)

@item 
The @ref{db,,struct} module will no longer silently ignore overflow
errors when a value is too large for a particular integer format
code (one of @code{bBhHiIlLqQ}); it now always raises a
@ref{153b,,struct.error} exception.  (Changed by Mark Dickinson;
bpo-1523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1523}.)  The @ref{148e,,pack()} function will also
attempt to use @ref{19e,,__index__()} to convert and pack non-integers
before trying the @ref{19d,,__int__()} method or reporting an error.
(Changed by Mark Dickinson; bpo-8300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8300}.)

@item 
新しい関数: @ref{dc,,subprocess} モジュールの @ref{11c4,,check_output()} は、指定された引数群でコマンドを実行し、コマンドがエラーを起こさずに実行したらコマンドの出力を文字列として返し、そうでなければ @ref{153c,,CalledProcessError} 例外を送出します。

@example
>>> subprocess.check_output(['df', '-h', '.'])
'Filesystem     Size   Used  Avail Capacity  Mounted on\n
/dev/disk0s2    52G    49G   3.0G    94%    /\n'

>>> subprocess.check_output(['df', '-h', '/bogus'])
  ...
subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
@end example

(Contributed by Gregory P. Smith.)

The @ref{dc,,subprocess} module will now retry its internal system calls
on receiving an @ref{f87,,EINTR} signal.  (Reported by several people; final
patch by Gregory P. Smith in bpo-1068268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1068268}.)

@item 
新しい関数: @ref{de,,symtable} モジュールの @ref{153d,,is_declared_global()} は、明示的に global と宣言された引数には真、暗示的に global である引数には偽を返します。(Contributed by Jeremy Hylton.)

@item 
@ref{e2,,syslog} モジュールは、識別子として、以前デフォルトであった @code{'python'} の値ではなく、 @code{sys.argv[0]} の値を使うようになりました。 (Changed by Sean Reifschneider; bpo-8451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8451}.)

@item 
The @ref{8af,,sys.version_info} value is now a named tuple, with attributes
named @code{major}, @code{minor}, @code{micro},
@code{releaselevel}, and @code{serial}.  (Contributed by Ross
Light; bpo-4285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4285}.)

@ref{ee3,,sys.getwindowsversion()} also returns a named tuple,
with attributes named @code{major}, @code{minor}, @code{build},
@code{platform}, @code{service_pack}, @code{service_pack_major},
@code{service_pack_minor}, @code{suite_mask}, and
@code{product_type}.  (Contributed by Brian Curtin; bpo-7766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7766}.)

@item 
@ref{e4,,tarfile} モジュールのデフォルトエラー処理が変更され、致命的なエラーを抑制しないようになりました。デフォルトのエラーレベルは以前は 0 で、エラーはメッセージとしてデバッグログに書き込まれるだけでしたが、デバッグログはデフォルトでは活性化されていないため、エラーは顧みられませんでした。デフォルトのエラーレベルは 1 になり、エラーがあれば例外が送出されます。 (Changed by Lars Gustäbel; bpo-7357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7357}.)

@ref{e4,,tarfile} は、tar ファイルに追加される @ref{142a,,TarInfo} オブジェクトのフィルタリングをサポートするようになりました。 @ref{dee,,add()} を呼び出したとき、オプションの呼び出し可能オブジェクトである `filter' 引数を与えることができます。 `filter' オブジェクトには、ファイルが追加される度に @ref{142a,,TarInfo} を渡され、これを変形して返せます。このオブジェクトが @code{None} を返したら、そのファイルは結果のアーカイブから除かれます。これは既存の `exclude' 引数より強力で、それゆえこれは非推奨となります。(Added by Lars Gustäbel; bpo-6856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6856}.) @ref{1429,,TarFile} クラスはまた、コンテキストマネージャプロトコルもサポートするようになりました。(Added by Lars Gustäbel; bpo-7232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7232}.)

@item 
@ref{1370,,threading.Event} クラスの @ref{153e,,wait()} メソッドは、終了時に内部フラグを返すようになりました。 @ref{153e,,wait()} は内部フラグが真になるまでブロックすることを想定されているため、この関数は通常真を返すことになります。この戻り値は、タイムアウトが与えられ、オペレーションがタイムアウトした時のみ偽になります。 (Contributed by Tim Lesher; bpo-1674032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1674032}.)

@item 
@ref{10b,,unicodedata} モジュールに提供される Unicode データベースは、どの文字が数字や空白文字か、または改行を表すかを決定するために、内部で使われるようになりました。このデータベースはまた、 @code{Unihan.txt} データファイルからの情報も含みます (patch by Anders Chrigström and Amaury Forgeot d'Arc; bpo-1571184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1571184})。また、バージョン 5.2.0 にアップデートされました (updated by Florent Xicluna; bpo-8024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8024})。

@item 
The @ref{110,,urlparse} module's @ref{f3a,,urlsplit()} now handles
unknown URL schemes in a fashion compliant with 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html}: if the
URL is of the form @code{"<something>://..."}, the text before the
@code{://} is treated as the scheme, even if it's a made-up scheme that
the module doesn't know about.  This change may break code that
worked around the old behaviour.  For example, Python 2.6.4 or 2.5
will return the following:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', '@w{'}, '//host/filename?query', '@w{'}, '@w{'})
@end example

Python 2.7 (や Python 2.6.5) は以下を返します:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', 'host', '/filename?query', '@w{'}, '@w{'})
@end example

(Python 2.7 では、これは普通のタプルではなく名前付きタプルを返すので、実際は微妙に異なる出力をします。)

The @ref{110,,urlparse} module also supports IPv6 literal addresses as defined by
@geindex RFC; RFC 2732
RFC 2732@footnote{https://datatracker.ietf.org/doc/html/rfc2732.html} (contributed by Senthil Kumaran; bpo-2987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2987}).

@example
>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
            path='/foo', params='@w{'}, query='@w{'}, fragment='@w{'})
@end example

@item 
新しいクラス: @ref{11a,,weakref} モジュールの @ref{7f5,,WeakSet} クラスは、その要素の弱参照だけを保持する集合です。要素は、それを指す参照がなくなり次第除去されます。 (Originally implemented in Python 3.x by Raymond Hettinger, and backported to 2.7 by Michael Foord.)

@item 
The @ref{12b,,xml.etree.ElementTree} library, no longer escapes
ampersands and angle brackets when outputting an XML processing
instruction (which looks like @code{<?xml-stylesheet href="#style1"?>})
or comment (which looks like @code{<!-- comment -->}).
(Patch by Neil Muller; bpo-2746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2746}.)

@item 
The XML-RPC client and server, provided by the @ref{134,,xmlrpclib} and
@ref{135,,SimpleXMLRPCServer} modules, have improved performance by
supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
to compress the XML being exchanged.  The gzip compression is
controlled by the @code{encode_threshold} attribute of
@ref{153f,,SimpleXMLRPCRequestHandler}, which contains a size in bytes;
responses larger than this will be compressed.
(Contributed by Kristján Valur Jónsson; bpo-6267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6267}.)

@item 
@ref{137,,zipfile} モジュールの @ref{8d3,,ZipFile} は、コンテキストマネジメントプロトコルをサポートし、 @code{with zipfile.ZipFile(...) as f:} と書けるようになりました。 (Contributed by Brian Curtin; bpo-5511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5511}.)

@ref{137,,zipfile} now also supports archiving empty directories and
extracts them correctly.  (Fixed by Kuba Wieczorek; bpo-4710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4710}.)
Reading files out of an archive is faster, and interleaving
@ref{1540,,read()} and
@ref{1541,,readline()} now works correctly.
(Contributed by Nir Aides; bpo-7610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7610}.)

@ref{1542,,is_zipfile()} 関数は、以前受け付けられていたパス名に加え、ファイルオブジェクトも受け付けるようになりました。 (Contributed by Gabriel Genellina; bpo-4756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4756}.)

@ref{2cc,,writestr()} メソッドは、 @ref{8d3,,ZipFile} コンストラクタで指定されたデフォルトの圧縮メソッドをオーバライドする、オプションの `compress_type' パラメタを追加しました。 (Contributed by Ronald Oussoren; bpo-6003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6003}.)
@end itemize

@c ======================================================================

@c whole new modules get described in subsections here

@menu
* 新しいモジュール; importlib: 新しいモジュール importlib. 
* 新しいモジュール; sysconfig: 新しいモジュール sysconfig. 
* ttk; Tk のテーマ付きウィジェット: ttk Tk のテーマ付きウィジェット. 
* 更新されたモジュール; unittest: 更新されたモジュール unittest. 
* 更新されたモジュール; ElementTree 1.3: 更新されたモジュール ElementTree 1 3. 

@end menu

@node 新しいモジュール importlib,新しいモジュール sysconfig,,新しいモジュールと改良されたモジュール
@anchor{whatsnew/2 7 importlib-section}@anchor{1503}@anchor{whatsnew/2 7 new-module-importlib}@anchor{1543}
@subsubsection 新しいモジュール: importlib


Python 3.1 includes the @ref{7b,,importlib} package, a re-implementation
of the logic underlying Python's @ref{7f8,,import} statement.
@ref{7b,,importlib} is useful for implementers of Python interpreters and
to users who wish to write new importers that can participate in the
import process.  Python 2.7 doesn't contain the complete
@ref{7b,,importlib} package, but instead has a tiny subset that contains
a single function, @ref{73c,,import_module()}.

@code{import_module(name, package=None)} はモジュールを import します。 `name' はモジュールまたはパッケージの名前を含む文字列です。 @code{..utils.errors} のように @code{.} 文字で始まる文字列を与えることで、相対 import も可能です。相対 import では、 `package' 引数は必ず与えられなければならず、相対 import のアンカーとして使われるパッケージの名前でなければなりません。 @ref{73c,,import_module()} は、 import されたモジュールを @code{sys.modules} に挿入し、モジュールオブジェクトを返すこともします。

ここに例があります:

@example
>>> from importlib import import_module
>>> anydbm = import_module('anydbm')  # Standard absolute import
>>> anydbm
<module 'anydbm' from '/p/python/Lib/anydbm.py'>
>>> # Relative import
>>> file_util = import_module('..file_util', 'distutils.command')
>>> file_util
<module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
@end example

@ref{7b,,importlib} は、Brett Cannon によって実装され、 Python 3.1 に導入されました。

@node 新しいモジュール sysconfig,ttk Tk のテーマ付きウィジェット,新しいモジュール importlib,新しいモジュールと改良されたモジュール
@anchor{whatsnew/2 7 new-module-sysconfig}@anchor{1544}
@subsubsection 新しいモジュール: sysconfig


@ref{e1,,sysconfig} モジュールが Distutils パッケージから引き抜かれ、新しいトップレベルモジュールになりました。 @ref{e1,,sysconfig} は、Python のビルドプロセスについての以下の情報を得るための関数群を提供しています。コンパイラスイッチ、インストレーションパス、プラットフォーム名、そして Python がソースディレクトリから実行されているかどうかです。

モジュールの関数のいくつかを紹介すると:


@itemize *

@item 
@ref{174,,get_config_var()} は、Python の Makefile と @code{pyconfig.h} ファイルから変数を返します。

@item 
@ref{298,,get_config_vars()} は、すべての環境設定変数を含む辞書を返します。

@item 
@ref{1545,,get_path()} は、特定のタイプのモジュール、つまり標準ライブラリ、サイト特有のモジュール、プラットフォーム特有のライブフラリなど、への設定されたパスを返します。

@item 
@ref{32d,,is_python_build()} は、Python ソースツリーからバイナリを起動していれば真を、そうでなければ偽を返します。
@end itemize

詳細と関数の完全な一覧は @ref{e1,,sysconfig} ドキュメントを参照してください。

Distutils パッケージと @ref{e1,,sysconfig} は Tarek Ziadé によってメンテナンスされていて、彼は Distutils の新世代版を開発するために Distutils2 パッケージ (source repository at @indicateurl{https://hg.python.org/distutils2/}) も開始しました。

@node ttk Tk のテーマ付きウィジェット,更新されたモジュール unittest,新しいモジュール sysconfig,新しいモジュールと改良されたモジュール
@anchor{whatsnew/2 7 ttk-themed-widgets-for-tk}@anchor{1546}
@subsubsection ttk: Tk のテーマ付きウィジェット


Tcl/Tk 8.5 は、基本的な Tk ウィジェットを最実装しながらより自由な外観のカスタマイズが広がり、よりネイティブなプラットフォームのウィジェットに似たテーマ付きウィジェット群を含みます。このウィジェット群は、元は Tile と呼ばれていましたが、Tcl/Tck リリース 8.5 への追加の際に ("themed Tk" を略して) Ttk に改名されました。

To learn more, read the @ref{ff,,ttk} module documentation.  You may also
wish to read the Tcl/Tk manual page describing the
Ttk theme engine, available at
@indicateurl{https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.html}. Some
screenshots of the Python/Ttk code in use are at
@indicateurl{https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki}.

The @ref{ff,,tkinter.ttk} module was written by Guilherme Polo and added in
bpo-2983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2983}.  An alternate version called @code{Tile.py}, written by
Martin Franklin and maintained by Kevin Walzer, was proposed for
inclusion in bpo-2618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2618}, but the authors argued that Guilherme
Polo's work was more comprehensive.

@node 更新されたモジュール unittest,更新されたモジュール ElementTree 1 3,ttk Tk のテーマ付きウィジェット,新しいモジュールと改良されたモジュール
@anchor{whatsnew/2 7 unittest-section}@anchor{1547}@anchor{whatsnew/2 7 updated-module-unittest}@anchor{1548}
@subsubsection 更新されたモジュール: unittest


The @ref{10c,,unittest} module was greatly enhanced; many
new features were added.  Most of these features were implemented
by Michael Foord, unless otherwise noted.  The enhanced version of
the module is downloadable separately for use with Python versions 2.4 to 2.6,
packaged as the @code{unittest2} package, from unittest2@footnote{https://pypi.org/project/unittest2/}.

When used from the command line, the module can automatically discover
tests.  It's not as fancy as py.test@footnote{https://pytest.org} or
nose@footnote{https://nose.readthedocs.io/}, but provides a
simple way to run tests kept within a set of package directories.  For example,
the following command will search the @code{test/} subdirectory for
any importable test files named @code{test*.py}:

@example
python -m unittest discover -s test
@end example

詳細は、 @ref{10c,,unittest} モジュールのドキュメントを参照してください。 (Developed in bpo-6001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6001}.)

@ref{11e5,,main()} 関数は、その他幾つかの新しいオプションを提供します:


@itemize *

@item 
@ref{1549,,-b} や @code{--buffer} は、標準出力や標準エラーストリームをそれぞれのテストの間バッファに入れます。テストが通れば、結果の出力は全て捨てられます。失敗したら、バッファに入れられた出力が表示されます。

@item 
@ref{154a,,-c} や @code{--catch} は、control-C による中断をより上品にします。テストプロセスを即座に中断するのではなく、現在実行中のテストは完了させ、中断までの部分的な結果は報告されます。待ちきれなければ、control-C をもう一度押せば、即座に中断されます。

この control-C ハンドラは、コードがテストされているときや、実行されているテストが独自のシグナルハンドラを定義したとき、シグナルハンドラがすでに設定されていてそして呼び出されたということを知らせることで、問題を起こさないようにします。これがまずいなら、 @ref{154b,,removeHandler()} デコレータを使って、テストが control-C ハンドリングを無効にするべきであると示せます。

@item 
@ref{154c,,-f} や @code{--failfast} は、テストが失敗したとき、他のテストを続けるのではなく、テストの実行を即座に停止します。 (Suggested by Cliff Dyer and implemented by Michael Foord; bpo-8074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8074}.)
@end itemize

進捗メッセージは、verbose モードで実行したとき、期待された失敗に 'x' を、期待されない成功に 'u' を表示するようになりました。(Contributed by Benjamin Peterson.)

テストケースは、テストをスキップするために @ref{11e6,,SkipTest} 例外を送出します。(bpo-1034053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1034053}).

@ref{74c,,assertEqual()}, @ref{74a,,assertTrue()}, および @ref{74b,,assertFalse()} 失敗のメッセージは、提供する情報量が増えました。 @ref{2b3,,TestCase} クラスの @ref{154d,,longMessage} 属性を真に設定すると、失敗時に、標準のエラーメッセージと追加して提供したメッセージの両方が表示されます。(Added by Michael Foord; bpo-5663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5663}.)

@ref{750,,assertRaises()} メソッドは、実行する呼び出し可能オブジェクトを与えずに呼び出されたとき、コンテキストハンドラを返すようになりました。例えば、こう書くことができます:

@example
with self.assertRaises(KeyError):
    @{@}['foo']
@end example

(Implemented by Antoine Pitrou; bpo-4444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4444}.)

@c rev 78774

モジュールレベルおよびクラスレベルの設定と、ティアダウンフィクスチャがサポートされました。モジュールは、 @ref{c42,,setUpModule()} および @ref{154e,,tearDownModule()} 関数を含むことができます。クラスは @ref{c43,,setUpClass()} および @ref{154f,,tearDownClass()} メソッドを含むことができ、これらは (@code{@@classmethod} や透過なものを使って) クラスメソッドとして定義しなければなりません。これらの関数とメソッドは、テストランナーが別のモジュールやクラスのテストケースに切り替えるときに呼び出されます。

メソッド @ref{c74,,addCleanup()} および @ref{1550,,doCleanups()} が追加されました。 @ref{c74,,addCleanup()} で、無条件に呼び出されるクリーンアップ関数を (@ref{1551,,setUp()} が失敗したら @ref{1551,,setUp()} の後に、そうでなければ @ref{1552,,tearDown()} の後に) 追加できるようにします。これにより、テスト中のリソースの配置と解放が簡潔になります。(bpo-5679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5679}).

より特化したテストを提供するメソッドがいくつか追加されました。これらのメソッドの多くは、Google のエンジニアたちによってそのテストスイートのために書かれました。Gregory P. Smith, Michael Foord, and GvR が、これを @ref{10c,,unittest} の Python 版にマージしました。


@itemize *

@item 
@ref{14a2,,assertIsNone()} および @ref{14a3,,assertIsNotNone()} はひとつの式を取り、その結果が @code{None} であるか、またはないかを確かめます。

@item 
@ref{1553,,assertIs()} および @ref{1554,,assertIsNot()} は、2 つの値を取り、その評価が同一のオブジェクトであるか、またはないかを確かめます。 (Added by Michael Foord; bpo-2578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2578}.)

@item 
@ref{1555,,assertIsInstance()} および @ref{1556,,assertNotIsInstance()} は、結果のオブジェクトが特定のクラス、またはタプルにあるクラスのいずれかのインスタンスであるかを調べます。(Added by Georg Brandl; bpo-7031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7031}.)

@item 
@ref{1557,,assertGreater()}, @ref{1558,,assertGreaterEqual()}, @ref{1559,,assertLess()}, および @ref{155a,,assertLessEqual()} は、二つの量を比較します。

@item 
@ref{155b,,assertMultiLineEqual()} は 2 つの文字列を比較し、等しくなければ、2 文字列の差分をハイライトする有益な比較を表示します。この比較は、Unicode 文字列が @ref{74c,,assertEqual()} で比較されるときのデフォルトに使われるようになりました。

@item 
@ref{751,,assertRegexpMatches()} and
@ref{753,,assertNotRegexpMatches()} checks whether the
first argument is a string matching or not matching the regular
expression provided as the second argument (bpo-8038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8038}).

@item 
@ref{752,,assertRaisesRegexp()} checks
whether a particular exception
is raised, and then also checks that the string representation of
the exception matches the provided regular expression.

@item 
@ref{155c,,assertIn()} および @ref{155d,,assertNotIn()} は、 `first' が `second' に属するか、または属さないかを調べます。

@item 
@ref{1442,,assertItemsEqual()} tests whether two provided sequences
contain the same elements.

@item 
@ref{149d,,assertSetEqual()} は、2 つの集合が等しいか比較し、エラーの場合のみ、集合間の差分を報告します。

@item 
同様に、 @ref{149f,,assertListEqual()} および @ref{14a0,,assertTupleEqual()} は、指定された型を比較し、差分を説明しますが、完全な値を表示するとはかぎりません。これらのメソッドは、リストやタプルを @ref{74c,,assertEqual()} で比較するときにデフォルトで使われるようになりました。より一般的には、 @ref{14a1,,assertSequenceEqual()} は 2 つのシーケンスを比較し、必要なら両方のシーケンスが特定の型であるかを調べます。

@item 
@ref{149e,,assertDictEqual()} compares two dictionaries and reports the
differences; it's now used by default when you compare two dictionaries
using @ref{74c,,assertEqual()}.  @code{assertDictContainsSubset()} checks whether
all of the key/value pairs in `first' are found in `second'.

@item 
@ref{74e,,assertAlmostEqual()} and @ref{74f,,assertNotAlmostEqual()} 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.

@item 
@ref{155e,,loadTestsFromName()} は、 @ref{593,,TestLoader} の @ref{155f,,suiteClass} 属性を適切に受け入れます。(Fixed by Mark Roddy; bpo-6866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6866}.)

@item 
新しいフックにより、 @ref{74c,,assertEqual()} メソッドを拡張して新しいデータ型を扱わせられます。 @ref{1560,,addTypeEqualityFunc()} メソッドは型オブジェクトと関数を取ります。この関数は、比較される両方のオブジェクトが特定の型であるときに使われます。この関数は、2 つのオブジェクトを比較し、マッチしなければ例外を送出するべきです。この関数が、新しいシーケンス比較メソッドがするように、2 つのオブジェクトがなぜマッチしないのかについて追加の情報を提供するのがいいアイデアです。
@end itemize

@ref{11e5,,unittest.main()} はオプションの @code{exit} 引数を取るようになりました。偽の場合、 @ref{11e5,,main()} は @ref{277,,sys.exit()} を呼び出さず、これにより対話型インタプリタから @ref{11e5,,main()} が使えるようになります。(Contributed by J. Pablo Fernández; bpo-3379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3379}.)

@ref{137f,,TestResult} に、テストランの直前と直後に呼び出される @ref{1561,,startTestRun()} および @ref{1562,,stopTestRun()} が追加されました。 (Contributed by Robert Collins; bpo-5728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5728}.)

これら一連の変更により、 @code{unittest.py} は無様に大きくなったので、モジュールはパッケージとなり、コードは複数のファイルに分割されました (by Benjamin Peterson)。これは、モジュールをインポートして使う方法には影響しません。


@subsubheading 参考



@table @asis

@item @indicateurl{https://web.archive.org/web/20210619163128/http://www.voidspace.org.uk/python/articles/unittest2.shtml}

Describes the new features, how to use them, and the
rationale for various design decisions.  (By Michael Foord.)
@end table


@node 更新されたモジュール ElementTree 1 3,,更新されたモジュール unittest,新しいモジュールと改良されたモジュール
@anchor{whatsnew/2 7 elementtree-section}@anchor{1563}@anchor{whatsnew/2 7 updated-module-elementtree-1-3}@anchor{1564}
@subsubsection 更新されたモジュール: ElementTree 1.3


Python に同梱される ElementTree ライブラリのバージョンが、バージョン 1.3 にアップデートされました。新機能の一部は:


@itemize *

@item 
様々な解析関数が、使われる @ref{c49,,XMLParser} インスタンスを与える `parser' キーワード引数を取るようになりました。これにより、ファイルの内部エンコーディングをオーバーライドできるようになりました:

@example
p = ET.XMLParser(encoding='utf-8')
t = ET.XML("""<root/>""", parser=p)
@end example

Errors in parsing XML now raise a @ref{148f,,ParseError} exception, whose
instances have a @code{position} attribute
containing a (`line', `column') tuple giving the location of the problem.

@item 
ElementTree's code for converting trees to a string has been
significantly reworked, making it roughly twice as fast in many
cases.  The @ref{c8c,,ElementTree.write()}
and @code{Element.write()} methods now have a `method' parameter that can be
"xml" (the default), "html", or "text".  HTML mode will output empty
elements as @code{<empty></empty>} instead of @code{<empty/>}, and text
mode will skip over elements and only output the text chunks.  If
you set the @ref{1565,,tag} attribute of an
element to @code{None} but
leave its children in place, the element will be omitted when the
tree is written out, so you don't need to do more extensive rearrangement
to remove a single element.

Namespace handling has also been improved.  All @code{xmlns:<whatever>}
declarations are now output on the root element, not scattered throughout
the resulting XML.  You can set the default namespace for a tree
by setting the @code{default_namespace} attribute and can
register new prefixes with @ref{13ea,,register_namespace()}.  In XML mode,
you can use the true/false `xml_declaration' parameter to suppress the
XML declaration.

@item 
新しい @ref{363,,Element}  メソッド: @ref{13eb,,extend()}  はシーケンスから項目の子に要素を追加します。要素それ自体はシーケンスのように振る舞うので、子をある要素から別の要素に移すのが簡単です:

@example
from xml.etree import ElementTree as ET

t = ET.XML("""<list>
  <item>1</item> <item>2</item>  <item>3</item>
</list>""")
new = ET.XML('<root/>')
new.extend(t)

# Outputs <root><item>1</item>...</root>
print ET.tostring(new)
@end example

@item 
New @ref{363,,Element} method:
@ref{1566,,iter()} yields the children of the
element as a generator.  It's also possible to write @code{for child in
elem:} to loop over an element's children.  The existing method
@code{getiterator()} is now deprecated, as is @code{getchildren()}
which constructs and returns a list of children.

@item 
New @ref{363,,Element} method:
@ref{13ed,,itertext()} yields all chunks of
text that are descendants of the element.  For example:

@example
t = ET.XML("""<list>
  <item>1</item> <item>2</item>  <item>3</item>
</list>""")

# Outputs ['\n  ', '1', ' ', '2', '  ', '3', '\n']
print list(t.itertext())
@end example

@item 
非推奨: 要素をブール値として使う (すなわち、 @code{if elem:}) と、要素が子を持てば真を、子を持たなければ偽を返します。この振る舞いは紛らわしいです -- @code{None} は偽、では子を持たない要素は? -- ですから、 @ref{659,,FutureWarning} を引き起こすようになりました。コードでは、明示するべきです。子の数に興味があるなら @code{len(elem) != 0} と、または @code{elem is not None} と書いてください。
@end itemize

Fredrik Lundh develops ElementTree and produced the 1.3 version;
you can read his article describing 1.3 at
@indicateurl{https://web.archive.org/web/20200703234532/http://effbot.org/zone/elementtree-13-intro.htm}.
Florent Xicluna updated the version included with
Python, after discussions on python-dev and in bpo-6472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6472}.)

@c ======================================================================

@node ビルドならびに C API の変更<8>,その他の変更と修正,新しいモジュールと改良されたモジュール,What's New in Python 2 7
@anchor{whatsnew/2 7 build-and-c-api-changes}@anchor{1567}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
The latest release of the GNU Debugger, GDB 7, can be scripted using Python@footnote{https://web.archive.org/web/20110715084810/http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html}.
When you begin debugging an executable program P, GDB will look for
a file named @code{P-gdb.py} and automatically read it.  Dave Malcolm
contributed a @code{python-gdb.py} that adds a number of
commands useful when debugging Python itself.  For example,
@code{py-up} and @code{py-down} go up or down one Python stack frame,
which usually corresponds to several C stack frames.  @code{py-print}
prints the value of a Python variable, and @code{py-bt} prints the
Python stack trace.  (Added as a result of bpo-8032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8032}.)

@item 
Python に備え付けの @code{.gdbinit} ファイルを使うと、デバッグされているスレッドが GIL をほじしていないとき、2.7 バージョンの "pyo" マクロが正常に動くようになりました。このマクロは、表示の前にこれを取得するようになりました。 (Contributed by Victor Stinner; bpo-3632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3632}.)

@item 
@ref{b78,,Py_AddPendingCall()} はスレッドセーフになり、ワーカスレッドがメイン Python スレッドに通知を投入することができるようになりました。これは特に、非同時性の IO 処理に便利です。(Contributed by Kristján Valur Jónsson; bpo-4293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4293}.)

@item 
New function: @ref{1568,,PyCode_NewEmpty()} creates an empty code object;
only the filename, function name, and first line number are required.
This is useful for extension modules that are attempting to
construct a more useful traceback stack.  Previously such
extensions needed to call @code{PyCode_New()}, which had many
more arguments.  (Added by Jeffrey Yasskin.)

@item 
新しい関数: @ref{1480,,PyErr_NewExceptionWithDoc()} は、既存の @ref{1481,,PyErr_NewException()} と同じように新しい例外クラスを生成しますが、新しい例外クラスの docstring を含む、追加の @code{char *} 引数を取ります。(Added by 'lekma' on the Python bug tracker; bpo-7033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7033}.)

@item 
新しい関数: @ref{98e,,PyFrame_GetLineNumber()} はフレームオブジェクトを取り、そのフレームが現在実行している行番号を返します。以前は、コードは現在実行しているバイトコード命令のインデクスを得て、それからそのアドレスに対応する行番号を探索する必要がありました。(Added by Jeffrey Yasskin.)

@item 
New functions: @ref{147d,,PyLong_AsLongAndOverflow()} and
@ref{147e,,PyLong_AsLongLongAndOverflow()}  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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7528} and bpo-7767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7767}.)

@item 
New function: stemming from the rewrite of string-to-float conversion,
a new @ref{14ad,,PyOS_string_to_double()} function was added.  The old
@code{PyOS_ascii_strtod()} and @code{PyOS_ascii_atof()} functions
are now deprecated.

@item 
New function: @code{PySys_SetArgvEx()} sets the value of
@code{sys.argv} and can optionally update @code{sys.path} to include the
directory containing the script named by @code{sys.argv[0]} depending
on the value of an `updatepath' parameter.

This function was added to close a security hole for applications
that embed Python.  The old function, @code{PySys_SetArgv()}, would
always update @code{sys.path}, and sometimes it would add the current
directory.  This meant that, if you ran an application embedding
Python in a directory controlled by someone else, attackers could
put a Trojan-horse module in the directory (say, a file named
@code{os.py}) that your application would then import and run.

If you maintain a C/C++ application that embeds Python, check
whether you're calling @code{PySys_SetArgv()} and carefully consider
whether the application should be using @code{PySys_SetArgvEx()}
with `updatepath' set to false.

Security issue reported as 
@geindex Common Vulnerabilities and Exposures; CVE 2008-5983
CVE 2008-5983@footnote{https://www.cve.org/CVERecord?id=CVE-2008-5983};
discussed in bpo-5753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5753}, and fixed by Antoine Pitrou.

@item 
新しいマクロ: Python ヘッダファイルは、以下のマクロを定義しました: @ref{1569,,Py_ISALNUM}, @ref{156a,,Py_ISALPHA}, @ref{156b,,Py_ISDIGIT}, @ref{156c,,Py_ISLOWER}, @ref{156d,,Py_ISSPACE}, @ref{156e,,Py_ISUPPER}, @ref{156f,,Py_ISXDIGIT}, @ref{1570,,Py_TOLOWER}, および @ref{1571,,Py_TOUPPER} 。これらすべての関数は、文字を分類する C の標準マクロと類似ですが、Python は文字をロケールに依らず文字を分析したいときがあるため、現在のロケール設定を無視します。(Added by Eric Smith; bpo-5793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5793}.)

@item 
Removed function: @code{PyEval_CallObject()} is now only available
as a macro.  A function version was being kept around to preserve
ABI linking compatibility, but that was in 1997; it can certainly be
deleted by now.  (Removed by Antoine Pitrou; bpo-8276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8276}.)

@item 
New format codes: the @code{PyString_FromFormat()},
@code{PyString_FromFormatV()}, and @ref{10b1,,PyErr_Format()} functions now
accept @code{%lld} and @code{%llu} format codes for displaying
C's long long types.
(Contributed by Mark Dickinson; bpo-7228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7228}.)

@item 
スレッドとプロセスのフォークの間の複雑な相互関係が変更されました。以前は、 @ref{4b5,,os.fork()} によって生成された子プロセスは失敗していました。これは、子は動作しているスレッド 1 つだけで生成され、そのスレッドが @ref{4b5,,os.fork()} を処理するからです。他のスレッドが、Python のインポートロックのような、ロックを保持していたら、フォークが実行されたとき、ロックは新しいプロセスでも "held" としてマークされたままです。しかし、子プロセスでは、他のスレッドは複製されないため、ロックを解放するものは何もないので、子プロセスは import の実行を続けることができません。

Python 2.7 は、 @ref{4b5,,os.fork()} を実行する前に import ロックを取得し、また @ref{f3,,threading} モジュールを使って生成された全てのロックをクリーンアップします。内部ロックを持っていたり、自身で @code{fork()} を呼び出したりするような C 拡張モジュールは、このクリーンアップの恩恵を受けません。

(Fixed by Thomas Wouters; bpo-1590864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1590864}.)

@item 
The @ref{45f,,Py_Finalize()} function now calls the internal
@code{threading._shutdown()} function; this prevents some exceptions from
being raised when an interpreter shuts down.
(Patch by Adam Olsen; bpo-1722344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1722344}.)

@item 
When using the @ref{771,,PyMemberDef} structure to define attributes
of a type, Python will no longer let you try to delete or set a
@code{T_STRING_INPLACE} attribute.

@c rev 79644

@item 
@ref{2e,,ctypes} によって定義されたグローバルシンボルには、 @code{Py} または @code{_ctypes} が接頭されるようになりました。(Implemented by Thomas Heller; bpo-3102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3102}.)

@item 
New configure option: the @code{--with-system-expat} switch allows
building the @ref{12c,,pyexpat} module to use the system Expat library.
(Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-7609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7609}.)

@item 
新しい設定オプション: @code{--with-valgrind} オプションは、 Valgrind メモリエラー検出器が正しく分析するのが難しい pymalloc アロケータを無効にするようになりました。ですから Valgrind は、メモリリークやオーバーランをより検出できます。 (Contributed by James Henstridge; bpo-2422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2422}.)

@item 
新しい設定オプション: @code{--with-dbmliborder=} に空の文字列を与えて様々な DBM モジュールを全て無効にできます。 (Added by Arfrever Frehtes Taifersar Arahesis; bpo-6491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6491}.)

@item 
The @code{configure} script now checks for floating-point rounding bugs
on certain 32-bit Intel chips and defines a @code{X87_DOUBLE_ROUNDING}
preprocessor definition.  No code currently uses this definition,
but it's available if anyone wishes to use it.
(Added by Mark Dickinson; bpo-2937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2937}.)

@code{configure} also now sets a @code{LDCXXSHARED} Makefile
variable for supporting C++ linking.  (Contributed by Arfrever
Frehtes Taifersar Arahesis; bpo-1222585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1222585}.)

@item 
ビルドプロセスは、pkg-config サポートに必要なファイルを生成するようになりました。(Contributed by Clinton Roy; bpo-3585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3585}.)

@item 
ビルドプロセスは、Subversion 1.7 をサポートするようになりました。 (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-6094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6094}.)
@end itemize

@menu
* カプセル:: 
* ポート特有の変更; Windows: ポート特有の変更 Windows. 
* ポート特有の変更; Mac OS X: ポート特有の変更 Mac OS X. 
* ポート特有の変更; FreeBSD: ポート特有の変更 FreeBSD. 

@end menu

@node カプセル,ポート特有の変更 Windows,,ビルドならびに C API の変更<8>
@anchor{whatsnew/2 7 capsules}@anchor{1572}@anchor{whatsnew/2 7 whatsnew27-capsules}@anchor{1573}
@subsubsection カプセル


Python 3.1 は、拡張モジュールに C API を提供する新しい C データ型 @ref{148a,,PyCapsule} を追加しました。カプセルは、本質的には C の @code{void *} ポインタのホルダであり、モジュール属性として利用できるようになります。例えば、 @ref{d1,,socket} モジュールの API は @code{socket.CAPI} として公開されていて、 @ref{10b,,unicodedata} は @code{ucnhash_CAPI} を公開しています。その他の拡張はモジュールを import し、辞書にアクセスしてカプセルオブジェクトを取得し、そしてモジュールの様々な API 関数へのポインタの配列を指す @code{void *} ポインタを取得できます。

There is an existing data type already used for this,
@code{PyCObject}, but it doesn't provide type safety.  Evil code
written in pure Python could cause a segmentation fault by taking a
@code{PyCObject} from module A and somehow substituting it for the
@code{PyCObject} in module B.   Capsules know their own name,
and getting the pointer requires providing the name:

@example
void *vtable;

if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") @{
        PyErr_SetString(PyExc_ValueError, "argument type invalid");
        return NULL;
@}

vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
@end example

@code{vtable} が期待どおりのものを指すことが保証されます。異なるカプセルが渡されたら、 @ref{1574,,PyCapsule_IsValid()} は不適合な名前を検知し、偽を返します。これらのオブジェクトの使用について、より詳しい情報は、 @ref{1575,,拡張モジュールに C API を提供する} を参照してください。

Python 2.7 now uses capsules internally to provide various
extension-module APIs, but the @code{PyCObject_AsVoidPtr()} was
modified to handle capsules, preserving compile-time compatibility
with the @code{PyCObject} interface.  Use of
@code{PyCObject_AsVoidPtr()} will signal a
@ref{ac5,,PendingDeprecationWarning}, which is silent by default.

Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
discussed in bpo-5630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5630}.

@c ======================================================================

@node ポート特有の変更 Windows,ポート特有の変更 Mac OS X,カプセル,ビルドならびに C API の変更<8>
@anchor{whatsnew/2 7 port-specific-changes-windows}@anchor{1576}
@subsubsection ポート特有の変更: Windows



@itemize *

@item 
The @ref{97,,msvcrt} module now contains some constants from
the @code{crtassem.h} header file:
@ref{1577,,CRT_ASSEMBLY_VERSION},
@ref{1578,,VC_ASSEMBLY_PUBLICKEYTOKEN},
and @ref{1579,,LIBRARIES_ASSEMBLY_NAME_PREFIX}.
(Contributed by David Cournapeau; bpo-4365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4365}.)

@item 
The @ref{11c,,_winreg} module for accessing the registry now implements
the @ref{157a,,CreateKeyEx()} and @ref{157b,,DeleteKeyEx()}
functions, extended versions of previously supported functions that
take several extra arguments.  The @ref{157c,,DisableReflectionKey()},
@ref{157d,,EnableReflectionKey()}, and @ref{157e,,QueryReflectionKey()}
were also tested and documented.
(Implemented by Brian Curtin: bpo-7347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7347}.)

@item 
The new @code{_beginthreadex()} API is used to start threads, and
the native thread-local storage functions are now used.
(Contributed by Kristján Valur Jónsson; bpo-3582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3582}.)

@item 
The @ref{157f,,os.kill()} function now works on Windows.  The signal value
can be the constants @ref{1580,,CTRL_C_EVENT},
@ref{1581,,CTRL_BREAK_EVENT}, or any integer.  The first two constants
will send @code{Control}-@code{C} and @code{Control}-@code{Break} keystroke events to
subprocesses; any other value will use the @code{TerminateProcess()}
API.  (Contributed by Miki Tebeka; bpo-1220212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1220212}.)

@item 
@ref{1312,,os.listdir()} 関数は、空のパスに対してちゃんと失敗するようになりました。 (Fixed by Hirokazu Yamamoto; bpo-5913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5913}.)

@item 
The @ref{93,,mimetypes} module will now read the MIME database from
the Windows registry when initializing.
(Patch by Gabriel Genellina; bpo-4969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4969}.)
@end itemize

@c ======================================================================

@node ポート特有の変更 Mac OS X,ポート特有の変更 FreeBSD,ポート特有の変更 Windows,ビルドならびに C API の変更<8>
@anchor{whatsnew/2 7 port-specific-changes-mac-os-x}@anchor{1582}
@subsubsection ポート特有の変更: Mac OS X



@itemize *

@item 
追加されたパッケージを、システムインストレーションとユーザがインストールした同じバージョンのコピーで共有するために、 @code{sys.path} に @code{/Library/Python/2.7/site-packages} が追加されました。 (Changed by Ronald Oussoren; bpo-4865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4865}.)


バージョン 2.7.13 で変更: As of 2.7.13, this change was removed.
@code{/Library/Python/2.7/site-packages}, the site-packages directory
used by the Apple-supplied system Python 2.7 is no longer appended to
@code{sys.path} for user-installed Pythons such as from the python.org
installers.  As of macOS 10.12, Apple changed how the system
site-packages directory is configured, which could cause installation
of pip components, like setuptools, to fail.  Packages installed for
the system Python will no longer be shared with user-installed
Pythons. (bpo-28440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28440})

@end itemize

@node ポート特有の変更 FreeBSD,,ポート特有の変更 Mac OS X,ビルドならびに C API の変更<8>
@anchor{whatsnew/2 7 port-specific-changes-freebsd}@anchor{1583}
@subsubsection ポート特有の変更: FreeBSD



@itemize *

@item 
FreeBSD 7.1's @code{SO_SETFIB} constant, used with the @ref{fa1,,socket()} methods
@ref{ed0,,getsockopt()}/@ref{ed1,,setsockopt()} to select an
alternate routing table, is now available in the @ref{d1,,socket}
module.  (Added by Kyle VanderBeek; bpo-8235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8235}.)
@end itemize

@node その他の変更と修正,Python 2 7 への移植,ビルドならびに C API の変更<8>,What's New in Python 2 7
@anchor{whatsnew/2 7 other-changes-and-fixes}@anchor{1584}
@subsection その他の変更と修正



@itemize *

@item 
ベンチマークスクリプトの 2 つ、 @code{iobench} および @code{ccbench}, が @code{Tools} ディレクトリに追加されました。 @code{iobench} は、様々な演算を実行している間 @ref{316,,open()} によって返された組み込みファイル I/O オブジェクトの速度を計測し、 @code{ccbench} は、変化する数のスレッドを使っていくつかのタスクを処理するときの計算スループット、スレッド切り替えレイテンシ、IO 処理バンド幅の計測を試みる同時実行ベンチマークです。

@item 
@code{Tools/i18n/msgfmt.py} スクリプトは、複数の形式の @code{.po} ファイルを理解できるようになりました。(Fixed by Martin von Löwis; bpo-5464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5464}.)

@item 
When importing a module from a @code{.pyc} or @code{.pyo} file
with an existing @code{.py} counterpart, the @ref{1585,,co_filename}
attributes of the resulting code objects are overwritten when the
original filename is obsolete.  This can happen if the file has been
renamed, moved, or is accessed through different paths.  (Patch by
Ziga Seilnacht and Jean-Paul Calderone; bpo-1180193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1180193}.)

@item 
@code{regrtest.py} スクリプトは、テストを乱順に実行する @code{-r} オプションの、ランダムシードに使われる整数を取る @code{--randseed=} スイッチを取るようになりました。 @code{-r} オプションは、使われたシードも報告します。 (Added by Collin Winter.)

@item 
もう一つの @code{regrtest.py} スイッチは @code{-j} で、いくつのテストを並行して実行するかを指定する整数です。これにより、マルチコア機での合計実行時間を短縮できます。このオプションは、実行時間を長くすることで知られている @code{-R} スイッチなど、いくつかの他のオプションと互換です。 (Added by Antoine Pitrou, bpo-6152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6152}.) これはまた、選ばれたテストを失敗するまでループして実行する @code{-F} スイッチとも同時に使えます。(Added by Antoine Pitrou; bpo-7312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7312}.)

@item 
スクリプトとして実行されるとき、 @code{py_compile.py} モジュールは標準入力を読み込んでコンパイルするファイル名のリストとする @code{'-'} を引数として受け付けるようになりました。(Contributed by Piotr Ożarowski; bpo-8233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8233}.)
@end itemize

@c ======================================================================

@node Python 2 7 への移植,Python 2 7 メンテナンスリリースで追加された新機能,その他の変更と修正,What's New in Python 2 7
@anchor{whatsnew/2 7 porting-to-python-2-7}@anchor{1586}
@subsection Python 2.7 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:


@itemize *

@item 
The @ref{b3d,,range()} function processes its arguments more
consistently; it will now call @ref{19d,,__int__()} on non-float,
non-integer arguments that are supplied to it.  (Fixed by Alexander
Belopolsky; bpo-1533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1533}.)

@item 
文字列 @ref{199,,format()} メソッドは浮動小数点数および複素数に使われるデフォルトの精度を、 @ref{169,,str()} で使われる精度に合わせ、小数第 6 位から 12 位に変更しました。 (Changed by Eric Smith; bpo-5920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5920}.)

@item 
Because of an optimization for the @ref{186,,with} statement, the special
methods @ref{7e4,,__enter__()} and @ref{1518,,__exit__()} must belong to the object's
type, and cannot be directly attached to the object's instance.  This
affects new-style classes (derived from @ref{c7e,,object}) and C extension
types.  (bpo-6101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6101}.)

@item 
Due to a bug in Python 2.6, the `exc_value' parameter to
@ref{1518,,__exit__()} 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@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7853}.)

@item 
@code{__slots__} を利用して属性を制限した場合に、設定されていない属性を del したときに @ref{5f0,,AttributeError} にならなかったのを修正しました。 (Fixed by Benjamin Peterson; bpo-7604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7604}.)
@end itemize

標準ライブラリでは:


@itemize *

@item 
年がサポートされている範囲外にはみ出るような @ref{4e2,,datetime} インスタンスの演算が、 @ref{a81,,OverflowError} を送出しないことがありました。このようなエラーはより注意深く調べられ、例外を送出するようになりました。(Reported by Mark Leander, patch by Anand B. Pillai and Alexander Belopolsky; bpo-7150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7150}.)

@item 
@ref{1fe,,Decimal} インスタンスを文字列の @ref{199,,format()} メソッドに使うとき、デフォルトの揃えは以前は左揃えでした。これは右揃えに変更され、プログラムの出力が変わるかもしれません。(Changed by Mark Dickinson; bpo-6857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6857}.)

signaling NaN (あるいは @code{sNAN}) との比較は、暗黙に比較演算に応じて真偽値を返すのではなく、 @ref{12bc,,InvalidOperation} 例外を発生させるようになりました。 Quiet NaN (あるいは @code{NAN}) はハッシュ可能になりました。 (Fixed by Mark Dickinson; bpo-7279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7279}.)

@item 
The @ref{12b,,xml.etree.ElementTree} library no longer escapes
ampersands and angle brackets when outputting an XML processing
instruction (which looks like @code{<?xml-stylesheet href="#style1"?>})
or comment (which looks like @code{<!-- comment -->}).
(Patch by Neil Muller; bpo-2746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2746}.)

@item 
The @code{readline()} method of @ref{112a,,StringIO} objects now does
nothing when a negative length is requested, as other file-like
objects do.  (bpo-7348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7348}).

@item 
@ref{e2,,syslog} モジュールは、識別子として、以前デフォルトであった @code{'python'} の値ではなく、 @code{sys.argv[0]} の値を使うようになりました。 (Changed by Sean Reifschneider; bpo-8451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8451}.)

@item 
@ref{e4,,tarfile} モジュールのデフォルトエラー処理が変更され、致命的なエラーを抑制しないようになりました。デフォルトのエラーレベルは以前は 0 で、エラーはメッセージとしてデバッグログに書き込まれるだけでしたが、デバッグログはデフォルトでは活性化されていないため、エラーは顧みられませんでした。デフォルトのエラーレベルは 1 になり、エラーがあれば例外が送出されます。 (Changed by Lars Gustäbel; bpo-7357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7357}.)

@item 
The @ref{110,,urlparse} module's @ref{f3a,,urlsplit()} now handles
unknown URL schemes in a fashion compliant with 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html}: if the
URL is of the form @code{"<something>://..."}, the text before the
@code{://} is treated as the scheme, even if it's a made-up scheme that
the module doesn't know about.  This change may break code that
worked around the old behaviour.  For example, Python 2.6.4 or 2.5
will return the following:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', '@w{'}, '//host/filename?query', '@w{'}, '@w{'})
@end example

Python 2.7 (や Python 2.6.5) は以下を返します:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', 'host', '/filename?query', '@w{'}, '@w{'})
@end example

(Python 2.7 では、これは普通のタプルではなく名前付きタプルを返すので、実際は微妙に異なる出力をします。)
@end itemize

C 拡張では:


@itemize *

@item 
@code{PyArg_Parse*} 系統の関数で整数フォーマットコードを使う C 拡張は、 @ref{1a3,,DeprecationWarning} を引き起こすのではなく、 @ref{198,,TypeError} 例外を送出するようになりました。(bpo-5080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5080})

@item 
Use the new @ref{14ad,,PyOS_string_to_double()} function instead of the old
@code{PyOS_ascii_strtod()} and @code{PyOS_ascii_atof()} functions,
which are now deprecated.
@end itemize

Python を埋め込んだアプリケーションでは:


@itemize *

@item 
The @code{PySys_SetArgvEx()} function was added, letting
applications close a security hole when the existing
@code{PySys_SetArgv()} function was used.  Check whether you're
calling @code{PySys_SetArgv()} and carefully consider whether the
application should be using @code{PySys_SetArgvEx()} with
`updatepath' set to false.
@end itemize

@c ======================================================================

@node Python 2 7 メンテナンスリリースで追加された新機能,謝辞,Python 2 7 への移植,What's New in Python 2 7
@anchor{whatsnew/2 7 new-features-added-to-python-2-7-maintenance-releases}@anchor{1587}@anchor{whatsnew/2 7 py27-maintenance-enhancements}@anchor{14fe}
@subsection Python 2.7 メンテナンスリリースで追加された新機能


Python 2.7 メンテナンスリリースでは、正真正銘それが求められる状況では、新しい機能が追加される場合があります。そのような追加のどんなものでも Python Enhancement Proposal プロセスを通過しなければなりません。Python 3 だけに新しい機能を追加することによっても Python Package Index に公開することによってもいずれでも十分ではないと言えるだけのやむにやまれない理由付けが必要です。

個別の提案は以下にリストしますが、全ての Python 2.7 メンテナンスリリースに追加される新しい @code{-3} 警告は除いています。

@menu
* デバッグモード用の2つの新しい環境変数:: 
* PEP 434; IDLE 拡張についての全てのブランチにおける例外的な扱い: PEP 434 IDLE 拡張についての全てのブランチにおける例外的な扱い. 
* PEP 466; Python 2.7 のためのネットワークセキュリティ拡張: PEP 466 Python 2 7 のためのネットワークセキュリティ拡張. 
* PEP 477; Python 2.7 への ensurepip (PEP 453) バックポート: PEP 477 Python 2 7 への ensurepip PEP 453 バックポート. 
* PEP 476; stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化: PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化<2>. 
* PEP 493; HTTPS verification migration tools for Python 2.7: PEP 493 HTTPS verification migration tools for Python 2 7. 
* New make regen-all build target: New make regen-all build target<3>. 
* Removal of make touch build target: Removal of make touch build target<3>. 

@end menu

@node デバッグモード用の2つの新しい環境変数,PEP 434 IDLE 拡張についての全てのブランチにおける例外的な扱い,,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 two-new-environment-variables-for-debug-mode}@anchor{1588}
@subsubsection デバッグモード用の2つの新しい環境変数


In debug mode, the @code{[xxx refs]} statistic is not written by default, the
@code{PYTHONSHOWREFCOUNT} environment variable now must also be set.
(Contributed by Victor Stinner; bpo-31733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31733}.)

When Python is compiled with @code{COUNT_ALLOC} defined, allocation counts are no
longer dumped by default anymore: the @code{PYTHONSHOWALLOCCOUNT} environment
variable must now also be set. Moreover, allocation counts are now dumped into
stderr, rather than stdout. (Contributed by Victor Stinner; bpo-31692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31692}.)


Added in version 2.7.15.


@node PEP 434 IDLE 拡張についての全てのブランチにおける例外的な扱い,PEP 466 Python 2 7 のためのネットワークセキュリティ拡張,デバッグモード用の2つの新しい環境変数,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 pep-434-idle-enhancement-exception-for-all-branches}@anchor{1589}
@subsubsection PEP 434: IDLE 拡張についての全てのブランチにおける例外的な扱い


@geindex Python Enhancement Proposals; PEP 434
PEP 434@footnote{https://peps.python.org/pep-0434/} は、Pythonと一緒に出荷されるIDLE開発環境に変更を加えるための一般的な免除事項を説明します。これは、IDLE の開発者 が Python 2 と 3 のすべてのサポートされているバージョン間でより一貫したユーザーエクスペリエンスを提供するためのものです。

全ての IDLE の変更についての詳細は、個別のリリースについてのNEWS ファイルを参照してください。

@node PEP 466 Python 2 7 のためのネットワークセキュリティ拡張,PEP 477 Python 2 7 への ensurepip PEP 453 バックポート,PEP 434 IDLE 拡張についての全てのブランチにおける例外的な扱い,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 pep-466-network-security-enhancements-for-python-2-7}@anchor{158a}
@subsubsection PEP 466: Python 2.7 のためのネットワークセキュリティ拡張


@geindex Python Enhancement Proposals; PEP 466
PEP 466@footnote{https://peps.python.org/pep-0466/} は、 Python 2.7 メンテナンスリリースに含めることを認められた数多くのネットワークセキュリティ強化についての提案を記述しています。それら変更の最初のものは Python 2.7.7 に初めて登場しました。

Python 2.7.7 に 
@geindex Python Enhancement Proposals; PEP 466
PEP 466@footnote{https://peps.python.org/pep-0466/} 関連で追加された機能:


@itemize *

@item 
@ref{12e0,,hmac.compare_digest()} が Python 3 からバックポートされました。これにより Python 2 アプリケーションで  timing attack resistant comparison operation が利用可能になります (Contributed by Alex Gaynor; bpo-21306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21306}.)

@item 
python.org で公開される公式 Windows インストーラのビルドに使う OpenSSL が 1.0.1g にアップグレードされました . (Contributed by Zachary Ware; bpo-21462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21462}.)
@end itemize

Python 2.7.8 に 
@geindex Python Enhancement Proposals; PEP 466
PEP 466@footnote{https://peps.python.org/pep-0466/} 関連で追加された機能:


@itemize *

@item 
@ref{733,,hashlib.pbkdf2_hmac()} が Python 3 からバックポートされました。これにより Python 2 アプリケーションでも、安全なパスワード格納に広範に使うのに相応しいハッシュアルゴリズムが利用できます (Contributed by Alex Gaynor; bpo-21304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21304}.)

@item 
OpenSSL 1.0.1h was upgraded for the official Windows installers published on
python.org. (Contributed by Zachary Ware in bpo-21671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21671} for 
@geindex Common Vulnerabilities and Exposures; CVE 2014-0224
CVE 2014-0224@footnote{https://www.cve.org/CVERecord?id=CVE-2014-0224}.)
@end itemize

Python 2.7.9 に 
@geindex Python Enhancement Proposals; PEP 466
PEP 466@footnote{https://peps.python.org/pep-0466/} 関連で追加された機能:


@itemize *

@item 
Python 3.4 の @ref{d5,,ssl} モジュールのほとんどがバックポートされました。つまり @ref{d5,,ssl} は今や、Server Name Indication, TLS1.x 設定, platform certificate store へのアクセス, @ref{357,,SSLContext} クラス, その他機能が使えます (Contributed by Alex Gaynor and David Reid; bpo-21308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21308}.)

個別の詳細については、モジュールのドキュメンテーション内の "バージョン 2.7.9 で追加" の注釈を参照してください。

@item 
@ref{746,,os.urandom()} は、呼び出しのたびに @code{/dev/urandom} を開きなおす代わりに @code{/dev/urandom} のファイル記述子をキャッシュするように変更されました。(Contributed by Alex Gaynor; bpo-21305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21305}.)

@item 
@ref{158b,,hashlib.algorithms_guaranteed} と @ref{158c,,hashlib.algorithms_available} が Python 3 からバックポートされました。これにより Python 2 アプリケーションが可能な限り最強のハッシュアルゴリズムを選択するのが容易になります (Contributed by Alex Gaynor in bpo-21307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21307})
@end itemize

@node PEP 477 Python 2 7 への ensurepip PEP 453 バックポート,PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化<2>,PEP 466 Python 2 7 のためのネットワークセキュリティ拡張,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 pep-477-backport-ensurepip-pep-453-to-python-2-7}@anchor{158d}
@subsubsection PEP 477: Python 2.7 への ensurepip (PEP 453) バックポート


@geindex Python Enhancement Proposals; PEP 477
PEP 477@footnote{https://peps.python.org/pep-0477/} が Python 2.7 メンテナンスリリースに 
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/} ensurepip モジュール, それによって可能になるドキュメンテーションの改善を含めることを認め、Python 2.7.9 リリースではじめてお披露目されました。

@menu
* デフォルトでの pip のブートストラッピング: デフォルトでの pip のブートストラッピング<2>. 
* ドキュメントの変更: ドキュメントの変更<2>. 

@end menu

@node デフォルトでの pip のブートストラッピング<2>,ドキュメントの変更<2>,,PEP 477 Python 2 7 への ensurepip PEP 453 バックポート
@anchor{whatsnew/2 7 bootstrapping-pip-by-default}@anchor{158e}
@subsubsection デフォルトでの pip のブートストラッピング


新しい @ref{59,,ensurepip} モジュール(
@geindex Python Enhancement Proposals; PEP 453
PEP 453@footnote{https://peps.python.org/pep-0453/} で定義されています)は標準のクロスプラットフォームのメカニズムで、Python インストールに pip インストーラをブートストラップします。Python 2.7.9 に含まれる @code{pip} のバージョンは @code{pip} 1.5.6 で、将来の 2.7.x メンテナンスリリースでは Python のリリース候補の作成時点で入手出来る最新バージョンの @code{pip} がバンドルされる予定です。

デフォルトでは @code{pip} , @code{pipX} , @code{pipX.Y} コマンドが全てのプラットフォームに、Python パッケージ @code{pip} とその依存物とともにインストールされます(X. Y はインストールされる Python のバージョン)。

CPython の @ref{10f6,,source builds on POSIX systems} では @code{make install}, @code{make altinstall} コマンドはデフォルトでは @code{pip} ブートストラップを行いません。この振る舞いは configure のオプションを変更して Makefile を作ることで変更できます。

Windows と Mac OS X では CPython インストーラはそれ自身と一緒に @code{pip} をデフォルトでインストールするようになっています(ユーザはインストールプロセスで除外するかもしれませんが)。Windows ユーザは @code{pip} がコマンドラインからデフォルトで利用可能なように @code{PATH} の自動修正するかの選択を求められます。そうしない場合でも Windows のための Python ランチャで @code{py -m pip} のようにすれば良いです。

As 
@geindex Python Enhancement Proposals; PEP 0477#disabling-ensurepip-by-downstream-distributors
discussed in the PEP@footnote{https://peps.python.org/pep-0477/#disabling-ensurepip-by-downstream-distributors},
platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear and
simple directions on how to install them on that platform (usually using
the system package manager).

@node ドキュメントの変更<2>,,デフォルトでの pip のブートストラッピング<2>,PEP 477 Python 2 7 への ensurepip PEP 453 バックポート
@anchor{whatsnew/2 7 documentation-changes}@anchor{158f}
@subsubsection ドキュメントの変更


この変更の一部は、 @ref{10f8,,Python モジュールのインストール} と distributing-index セクションがより手短な始め方として完全にデザインし直されたことと、FAQ ドキュメントです。ほとんどのパッケージングについてのドキュメンテーションは Python Packaging User Guide@footnote{https://packaging.python.org}  が保守している Python Packaging Authority に移動されて、独立したプロジェクトのドキュメンテーションになっています。

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as @ref{10f9,,setuptools による C および C++ 拡張のビルド}
and @ref{10fa,,setuptools による C および C++ 拡張のビルド}.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 453

@item PEP 453@footnote{https://peps.python.org/pep-0453/} -- Python インストールの際の明示的なpipのブートストラッピング

PEP は Donald Stufft と Nick Coghlan によって書かれ、Donald Stufft, Nick Coghlan, Martin von Löwis, Ned Deily により実装されました。
@end table


@node PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化<2>,PEP 493 HTTPS verification migration tools for Python 2 7,PEP 477 Python 2 7 への ensurepip PEP 453 バックポート,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients}@anchor{1590}
@subsubsection PEP 476: stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化


@geindex Python Enhancement Proposals; PEP 476
PEP 476@footnote{https://peps.python.org/pep-0476/} updated @ref{72,,httplib} and modules which use it, such as
@ref{111,,urllib2} and @ref{134,,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.

以前の古い振る舞いが必要なアプリケーションでは、代わりとなるコンテキストを渡せます:

@example
import urllib2
import ssl

# This disables all verification
context = ssl._create_unverified_context()

# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib2.urlopen("https://invalid-cert", context=context)
@end example

@node PEP 493 HTTPS verification migration tools for Python 2 7,New make regen-all build target<3>,PEP 476 stdlib http クライアントが証明書の検証を行うのをデフォルトで有効化<2>,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 pep-493-https-verification-migration-tools-for-python-2-7}@anchor{1591}
@subsubsection PEP 493: HTTPS verification migration tools for Python 2.7


@geindex Python Enhancement Proposals; PEP 493
PEP 493@footnote{https://peps.python.org/pep-0493/} provides additional migration tools to support a more incremental
infrastructure upgrade process for environments containing applications and
services relying on the historically permissive processing of server
certificates when establishing client HTTPS connections.  These additions were
made in the Python 2.7.12 release.

These tools are intended for use in cases where affected applications and
services can't be modified to explicitly pass a more permissive SSL context
when establishing the connection.

For applications and services which can't be modified at all, the new
@code{PYTHONHTTPSVERIFY} environment variable may be set to @code{0} to revert an
entire Python process back to the default permissive behaviour of Python 2.7.8
and earlier.

For cases where the connection establishment code can't be modified, but the
overall application can be, the new @code{ssl._https_verify_certificates()}
function can be used to adjust the default behaviour at runtime.

@node New make regen-all build target<3>,Removal of make touch build target<3>,PEP 493 HTTPS verification migration tools for Python 2 7,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 new-make-regen-all-build-target}@anchor{1592}
@subsubsection New @code{make regen-all} build target


To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.

Instead, a new @code{make regen-all} command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in@footnote{https://github.com/python/cpython/tree/3.14/Makefile.pre.in} for details.

(Victor Stinner の貢献による bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404})


Added in version 2.7.14.


@node Removal of make touch build target<3>,,New make regen-all build target<3>,Python 2 7 メンテナンスリリースで追加された新機能
@anchor{whatsnew/2 7 removal-of-make-touch-build-target}@anchor{1593}
@subsubsection Removal of @code{make touch} build target


The @code{make touch} build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.

It has been replaced by the new @code{make regen-all} target.

(Victor Stinner の貢献による bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404})


バージョン 2.7.14 で変更.


@c ======================================================================

@node 謝辞,,Python 2 7 メンテナンスリリースで追加された新機能,What's New in Python 2 7
@anchor{whatsnew/2 7 acknowledgements}@anchor{1594}@anchor{whatsnew/2 7 acks27}@anchor{1595}
@subsection 謝辞


著者は、以下の方々がこの記事の多くの草稿に提案、修正、そして助力を差し伸べてくださったことに感謝の意を表したいと思います: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray, Hugh Secker-Walker.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 6,What's New in Python 2 5,What's New in Python 2 7,What's New in Python
@anchor{whatsnew/2 6 doc}@anchor{1596}@anchor{whatsnew/2 6 translation-repo}@anchor{1597}@anchor{whatsnew/2 6 what-s-new-in-python-2-6}@anchor{1598}@anchor{whatsnew/2 6 whats-new-in-2-6}@anchor{14c5}
@section What's New in Python 2.6


@*著者: 
A.M. Kuchling (amk at amk.ca)


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number in a parenthetical comment.
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer; :issue:`12345`.)
@c 
@c This saves the maintainer some effort going through the SVN logs
@c when researching a change.

This article explains the new features in Python 2.6, released on October 1,
2008.  The release schedule is described in 
@geindex Python Enhancement Proposals; PEP 361
PEP 361@footnote{https://peps.python.org/pep-0361/}.

The major theme of Python 2.6 is preparing the migration path to
Python 3.0, a major redesign of the language.  Whenever possible,
Python 2.6 incorporates new features and syntax from 3.0 while
remaining compatible with existing code by not removing older features
or syntax.  When it's not possible to do that, Python 2.6 tries to do
what it can, adding compatibility functions in a
@code{future_builtins} module and a @code{-3} switch to warn about
usages that will become unsupported in 3.0.

@ref{98,,multiprocessing} や @ref{86,,json} といった、いくつか重要な新しいパッケージが標準ライブラリに追加されましたが、Python 3.0 に何らかも関係しない新機能はあまり多くはありません。

Python 2.6 ではさらに、たくさんの改善とバグフィックスがソースコードのありとあらゆる場所に見られます。Python 2.5 から 2.6 の変更ログを手繰ってみると、低く見積もっても、適用されたパッチは 259、フィックスされたバグは 612 にのぼります。

このドキュメントは新機能の完全な詳細を提供するのではなくて、簡易な概要を提供することを目的にしています。完全な詳細が知りたければ、 Python 2.6 のドキュメントを参照してください。設計と実装の根拠を理解したい場合は、新機能に関する PEP を参照してください。可能な限り、 "What’s New in Python" は各変更の bug や patch に対してリンクしています。

@c Compare with previous release in 2 - 3 sentences here.
@c add hyperlink when the documentation becomes available online.

@c ========================================================================

@c Large, PEP-level features and changes should be described here.

@c ========================================================================

@menu
* Python 3.0: Python 3 0. 
* 開発プロセスに関する変更:: 
* PEP 343; "with" ステートメント: PEP 343 "with" ステートメント. 
* PEP 366; メインモジュールからの明示的相対インポート: PEP 366 メインモジュールからの明示的相対インポート. 
* PEP 370; ユーザごとの site-packages ディレクトリ: PEP 370 ユーザごとの site-packages ディレクトリ. 
* PEP 371; multiprocessing パッケージ: PEP 371 multiprocessing パッケージ. 
* 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; 数値の型階層: PEP 3141 数値の型階層. 
* その他の言語変更: その他の言語変更<15>. 
* 新しいモジュールと改良されたモジュール: 新しいモジュールと改良されたモジュール<2>. 
* 非推奨と削除:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<9>. 
* Python 2.6 への移植: Python 2 6 への移植. 
* 謝辞: 謝辞<2>. 

@end menu

@node Python 3 0,開発プロセスに関する変更,,What's New in Python 2 6
@anchor{whatsnew/2 6 python-3-0}@anchor{1599}
@subsection Python 3.0


Python 2.6 と 3.0 の開発サイクルは同期していました。両バージョンのアルファ、ベータリリースは同じ日にリリースされています。3.0 の開発は 2.6 の多くの機能に影響を与えました。

Python 3.0 は、2.x シリーズとの互換性を破壊する、広範囲な再設計です。これは、Python 3.0 で動作させるためには既存のコードに何らかの変換が必要なことを意味しています。しかしながら、必ずしも全ての 3.0 での変更が互換性を破壊するわけではありません。新機能が既存のコードの破壊を引き起こさないケースにおいては、それらは 2.6 にバックポートされました。これらについてはこのドキュメントの適切な場所に記載しています。3.0 由来の機能の一部としては以下があります:


@itemize *

@item 
オブジェクトを複素数(虚数)に変換する @code{__complex__()} メソッド。

@item 
例外の捕捉の、これまでとは別の文法の追加: @code{except TypeError as exc} 。

@item 
組み込み関数 @code{reduce()} への別名としての @ref{21a,,functools.reduce()} の追加。
@end itemize

Python 3.0 adds several new built-in functions and changes the
semantics of some existing builtins.  Functions that are new in 3.0
such as @ref{14c0,,bin()} have simply been added to Python 2.6, but existing
builtins haven't been changed; instead, the @code{future_builtins}
module has versions with the new 3.0 semantics.  Code written to be
compatible with 3.0 can do @code{from future_builtins import hex, map} as
necessary.

A new command-line switch, @code{-3}, enables warnings
about features that will be removed in Python 3.0.  You can run code
with this switch to see how much work will be necessary to port
code to 3.0.  The value of this switch is available
to Python code as the boolean variable @code{sys.py3kwarning},
and to C extension code as @code{Py_Py3kWarningFlag}.


@subsubheading 参考


The 3`xxx' series of PEPs, which contains proposals for Python 3.0.
@geindex Python Enhancement Proposals; PEP 3000
PEP 3000@footnote{https://peps.python.org/pep-3000/} describes the development process for Python 3.0.
Start with 
@geindex Python Enhancement Proposals; PEP 3100
PEP 3100@footnote{https://peps.python.org/pep-3100/} that describes the general goals for Python
3.0, and then explore the higher-numbered PEPs that propose
specific features.


@node 開発プロセスに関する変更,PEP 343 "with" ステートメント,Python 3 0,What's New in Python 2 6
@anchor{whatsnew/2 6 changes-to-the-development-process}@anchor{159a}
@subsection 開発プロセスに関する変更


2.6 の開発の間で、Python 開発プロセスは 2 つの重要な変更を経験しました: SourceForge の課題トラッカーから、カスタイマイズした Roundup インストレーションに乗り換えました。また、ドキュメントは LaTeX から reStructuredText に変換しました。

@menu
* 新しい課題トラッカー; Roundup: 新しい課題トラッカー Roundup. 
* 新しいドキュメンテーションフォーマット; Sphinx を使っての reStructuredText: 新しいドキュメンテーションフォーマット Sphinx を使っての reStructuredText. 

@end menu

@node 新しい課題トラッカー Roundup,新しいドキュメンテーションフォーマット Sphinx を使っての reStructuredText,,開発プロセスに関する変更
@anchor{whatsnew/2 6 new-issue-tracker-roundup}@anchor{159b}
@subsubsection 新しい課題トラッカー: Roundup


もう随分長いこと Python 開発者たちは、SourceForge のバグトラッカーにイライラを高め続けてきました。SourceForge がホストするソリューションには全くカスタマイズの余地がなく、たとえば課題のライフサイクルをカスタマイズ出来ませんでした。

The infrastructure committee of the Python Software Foundation
therefore posted a call for issue trackers, asking volunteers to set
up different products and import some of the bugs and patches from
SourceForge.  Four different trackers were examined: Jira@footnote{https://www.atlassian.com/software/jira/},
Launchpad@footnote{https://launchpad.net/},
Roundup@footnote{https://roundup.sourceforge.io/}, and
Trac@footnote{https://trac.edgewall.org/}.
The committee eventually settled on Jira
and Roundup as the two candidates.  Jira is a commercial product that
offers no-cost hosted instances to free-software projects; Roundup
is an open-source project that requires volunteers
to administer it and a server to host it.

ボランティアへの呼び掛けののち、新しい Roundup インストレーションが @indicateurl{https://bugs.python.org} にセットアップされました。Roundup の一つのインストレーションは複数のトラッカーをホスト出来るため、このサーバは今では Jython と Python ウェブサイトのための課題トラッカーもホストしています。間違いなく将来はほかのものもホストするでしょう。可能な場所では、"What's New in Python" のこのエディションでは、それぞれの変更についてのバグ/パッチの Roundup アイテムにリンクします。

Hosting of the Python bug tracker is kindly provided by
Upfront Systems@footnote{https://upfrontsoftware.co.za}
of Stellenbosch, South Africa.  Martin von Löwis put a
lot of effort into importing existing bugs and patches from
SourceForge; his scripts for this import operation are at
@code{https://svn.python.org/view/tracker/importer/} and may be useful to
other projects wishing to move from SourceForge to Roundup.


@subsubheading 参考



@table @asis

@item @indicateurl{https://bugs.python.org}

Python のバグトラッカー。

@item @indicateurl{https://bugs.jython.org}:

Jython のバグトラッカー。

@item @indicateurl{https://roundup.sourceforge.io/}

Roundup のダウンロードとドキュメント。

@item @indicateurl{https://svn.python.org/view/tracker/importer/}

Martin von Löwis の変換スクリプト。
@end table


@node 新しいドキュメンテーションフォーマット Sphinx を使っての reStructuredText,,新しい課題トラッカー Roundup,開発プロセスに関する変更
@anchor{whatsnew/2 6 new-documentation-format-restructuredtext-using-sphinx}@anchor{159c}
@subsubsection 新しいドキュメンテーションフォーマット: Sphinx を使っての reStructuredText


Python のドキュメンテーションは、そのプロジェクトの開始した 1989 年頃より LaTeX を使って書かれてきました。1980 年代と 1990 年代初期は、ほとんどのドキュメンテーションはあとで学習するために印刷されるもので、オンラインで見るものではありませんでした。LaTeX はとても魅惑的な印刷をしてくれるものですから、非常に大変広く広く使われていましたが、一方では、学んだマークアップの基礎的なルールで直裁的に、書いたらそれっきり、というものでもありました。

こんにちにおいてもなお、印刷を命題とする出版において LaTeX は健在といえど、プログラミングの道具立ての風景は変わりました。わたしたちはもはやドキュメンテーションの紙束をプリントアウトはしません。代わりにオンラインでブラウズします。ですから HTML は、サポートすべき最も重要なフォーマットになりました。悲しいかな、 LaTeX から HTML への変換は気が狂うほどに複雑で、Fred L. Drake Jr.、彼は長らく Python ドキュメンテーションのエディターを務めていますが、彼はその変換処理の保守に多大な時間を浪費していたのです。ときおり人々はドキュメンテーションを SGML に変換して、それから XML にすればいいでしょ、と持ちかけるのですが、良い変換を達成することにとらわれて、誰一人として仕事を完遂させようと時間を捧げることはしませんでした。

During the 2.6 development cycle, Georg Brandl put a lot of effort
into building a new toolchain for processing the documentation.  The
resulting package is called Sphinx, and is available from
@indicateurl{https://www.sphinx-doc.org/}.

Sphinx は HTML 出力に集中し、人を惹きつけるスタイルでモダンな HTML を生成します。印刷出力は LaTeX への変換を経由することで健在です。入力のフォーマットは reStructuredText です。これはカスタムな拡張とディレクティブをサポートしているマークアップ文法で、Python コミュニティでは広く使われています。

Sphinx は執筆に使えるスタンドアロンのパッケージです。そして 2 ダースに届かんばかりのプロジェクト (Sphinx ウェブサイトのリスト@footnote{https://www.sphinx-doc.org/en/master/examples.html}) が Sphinx をドキュメンテーションツールとして採用しました。


@subsubheading 参考



@table @asis

@item Documenting Python@footnote{https://devguide.python.org/documenting/}

Python ドキュメントの書き方について書いています。

@item Sphinx@footnote{https://www.sphinx-doc.org/}

Sphinx ツールチェインのドキュメントとコードです。

@item Docutils@footnote{https://docutils.sourceforge.io}

縁の下の力持ちになっている reStructuredText のパーサとツールセットです。
@end table


@node PEP 343 "with" ステートメント,PEP 366 メインモジュールからの明示的相対インポート,開発プロセスに関する変更,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-0343}@anchor{14c6}@anchor{whatsnew/2 6 pep-343-the-with-statement}@anchor{159d}
@subsection PEP 343: "with" ステートメント


Python 2.5 では、  '@ref{186,,with}' 文が @code{from __future__ import with_statement} ディレクティブで有効に出来るオプションの機能として追加されました。2.6 では '@code{with}' 文は特別に有効化する必要なく、もういつでもそこにあります。このセクションの残りの部分は "What's New in Python 2.5" の対応するセクションからの丸々コピーですので、2.5 で '@code{with}' 文に馴染んでいるなら読み飛ばしてもらって結構です。

'@ref{186,,with}' ステートメントは、以前なら後片付けが実行されるのを確実にするために @code{try...finally} ブロックを使ったであろうようなコードを、より単純明快にします。このセクションでは、このステートメントの普通の使い方を説明します。続くセクションでは実装の詳細を調べ、このステートメントとともに使うためにオブジェクトをどうやって書けば良いかをお見せします。

'@ref{186,,with}' ステートメントは基本構造が以下となる制御フロー構造です:

@example
with expression [as variable]:
    with-block
@end example

The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has @ref{7e4,,__enter__()} and @ref{1518,,__exit__()}
methods).

The object's @ref{7e4,,__enter__()} 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 @ref{1518,,__exit__()}
method is called, even if the block raised an exception, and can therefore run
clean-up code.

いくつかの Python 標準オブジェクトが既にコンテキスト管理プロトコルをサポートしていて、 '@ref{186,,with}' とともに使えます。ファイルオブジェクトがその一例です:

@example
with open('/etc/passwd', 'r') as f:
    for line in f:
        print line
        ... more processing code ...
@end example

このステートメントが実行し終わったあかつきには、 `f' のファイルオブジェクトは、たとえ @ref{34a,,for} ループが道半ばにして例外と成り果てても、自動的にクローズされます。

@cartouche
@quotation 注釈 
In this case, `f' is the same object created by @ref{316,,open()}, because
@ref{7e4,,__enter__()} returns `self'.
@end quotation
@end cartouche

@ref{f3,,threading} モジュールのロック・条件変数でも '@ref{186,,with}' ステートメントの恩恵にあずかれます:

@example
lock = threading.Lock()
with lock:
    # Critical section of code
    ...
@end example

ブロックが実行される前にロックが獲得されて、ブロックが完了するやいなや必ず解放されます。

The @ref{159e,,localcontext()} function in the @ref{3a,,decimal} module makes
it easy to save and restore the current decimal context, which encapsulates
the desired precision and rounding characteristics for computations:

@example
from decimal import Decimal, Context, localcontext

# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # All code in this block uses a precision of 16 digits.
    # The original context is restored on exiting the block.
    print v.sqrt()
@end example

@menu
* コンテキストマネージャを書く:: 
* contextlib モジュール:: 

@end menu

@node コンテキストマネージャを書く,contextlib モジュール,,PEP 343 "with" ステートメント
@anchor{whatsnew/2 6 new-26-context-managers}@anchor{14c7}@anchor{whatsnew/2 6 writing-context-managers}@anchor{159f}
@subsubsection コンテキストマネージャを書く


中身を紐解いてみれば、 '@ref{186,,with}' ステートメントはけっこう入り組んでいます。ほとんどの人にとっては、既存のオブジェクトを '@code{with}' とともに使うだけのことでその詳細を知る必要は無いので、それで良いならこのセクションの残りの部分は読み飛ばして結構です。新しいオブジェクトの作者は基礎となる実装の詳細について知る必要があるので、このまま読み進めるべきです。

コンテキスト管理プロトコルの高度な説明はこんなです:


@itemize *

@item 
The expression is evaluated and should result in an object called a "context
manager".  The context manager must have @ref{7e4,,__enter__()} and
@ref{1518,,__exit__()} methods.

@item 
The context manager's @ref{7e4,,__enter__()} method is called.  The value
returned is assigned to `VAR'.  If no @code{as VAR} clause is present, the
value is simply discarded.

@item 
`BLOCK' 内のコードが実行されます。

@item 
If `BLOCK' raises an exception, the context manager's @ref{1518,,__exit__()} method
is called with three arguments, the exception details (@code{type, value, traceback},
the same values returned by @ref{89a,,sys.exc_info()}, which can also be @code{None}
if no exception occurred).  The method's return value controls whether an exception
is re-raised: any false value re-raises the exception, and @code{True} will result
in suppressing it.  You'll only rarely want to suppress the exception, because
if you do the author of the code containing the '@ref{186,,with}' statement will
never realize anything went wrong.

@item 
If `BLOCK' didn't raise an exception,  the @ref{1518,,__exit__()} method is still
called, but `type', `value', and `traceback' are all @code{None}.
@end itemize

例を通じて考えましょう。枝葉末節を含んだ完璧なコードを提示しようとは思いませんが、データベースのためにトランザクションをサポートするのに必要となるメソッドの書き方についてスケッチしてみようと思います。

(データベース用語に不慣れな方へ:データベースへの変更のセットは、トランザクションという単位でグループ化されています。トランザクションは「コミット」される、その意味は、全ての変更がデータベースに書き込まれることです、もしくは「ロールバック」される、この場合全ての変更が捨てられてデータベースが変更されません、この 2 つのいずれかになりえます。詳しくはなにかデータベースの著述を読んで下さい。)

データベース接続を表現するオブジェクトがあると仮定しましょう。私たちの目標は、そのオブジェクトのユーザがこのように書けるようになることです:

@example
db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...
@end example

The transaction should be committed if the code in the block runs flawlessly or
rolled back if there's an exception. Here's the basic interface for
@code{DatabaseConnection} that I'll assume:

@example
class DatabaseConnection:
    # Database interface
    def cursor(self):
        "Returns a cursor object and starts a new transaction"
    def commit(self):
        "Commits current transaction"
    def rollback(self):
        "Rolls back current transaction"
@end example

The @ref{7e4,,__enter__()} method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add @code{as cursor} to
their '@ref{186,,with}' statement to bind the cursor to a variable name.

@example
class DatabaseConnection:
    ...
    def __enter__(self):
        # Code to start a new transaction
        cursor = self.cursor()
        return cursor
@end example

The @ref{1518,,__exit__()} method is the most complicated because it's where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.

下記のコード内では実行がメソッドの末尾まで落ちていって、なのでデフォルトの @code{None} 返却になります。 @code{None} は偽なので、例外は自動的に再送出されます。望むならもっと明示的に、コメントでマークした部分で @ref{1af,,return} 文を書いてもよろしいです:

@example
class DatabaseConnection:
    ...
    def __exit__(self, type, value, tb):
        if tb is None:
            # No exception, so commit
            self.commit()
        else:
            # Exception occurred, so rollback.
            self.rollback()
            # return False
@end example

@node contextlib モジュール,,コンテキストマネージャを書く,PEP 343 "with" ステートメント
@anchor{whatsnew/2 6 new-module-contextlib}@anchor{14c8}@anchor{whatsnew/2 6 the-contextlib-module}@anchor{15a0}
@subsubsection contextlib モジュール


@ref{27,,contextlib} モジュールは、 '@ref{186,,with}' ステートメントで使えるオブジェクトを書く際に便利ないくつかの関数とデコレータを提供しています。

The decorator is called @ref{141b,,contextmanager()}, and lets you write
a single generator function instead of defining a new class.  The generator
should yield exactly one value.  The code up to the @ref{bc2,,yield} will be
executed as the @ref{7e4,,__enter__()} method, and the value yielded will
be the method's return value that will get bound to the variable in the
'@ref{186,,with}' statement's @code{as} clause, if any.  The code after
the @code{yield} will be executed in the @ref{1518,,__exit__()} method.
Any exception raised in the block will be raised by the @code{yield}
statement.

このデコレータを使って、前セクションの私たちのデータベースの例はこのように書けます:

@example
from contextlib import contextmanager

@@contextmanager
def db_transaction(connection):
    cursor = connection.cursor()
    try:
        yield cursor
    except:
        connection.rollback()
        raise
    else:
        connection.commit()

db = DatabaseConnection()
with db_transaction(db) as cursor:
    ...
@end example

@ref{27,,contextlib} モジュールには @code{nested(mgr1, mgr2, ...)} 関数もあり、この関数はたくさんのコンテキストマネージャを組み合わせることができて、入れ子の '@ref{186,,with}' を書く必要性をなくしてくれます。この例では、単一の '@code{with}' でデータベーストランザクション開始とスレッドのロック獲得の両方をやってのけています:

@example
lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
    ...
@end example

Finally, the @ref{15a1,,closing()} function returns its argument so that it can be
bound to a variable, and calls the argument's @code{.close()} method at the end
of the block.

@example
import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 343

@item PEP 343@footnote{https://peps.python.org/pep-0343/} - "with" ステートメント

PEP は Guido van Rossum と Nick Coghlan によって書かれ、Mike Bland、 Guido van Rossum、Neal Norwitz により実装されました。この PEP は '@ref{186,,with}' ステートメントによって生成されるコードを見せてくれるので、このステートメントがどうやって動作するのかを知るのに役立ちます。
@end table

@ref{27,,contextlib} モジュールについてのドキュメント。


@c ======================================================================

@node PEP 366 メインモジュールからの明示的相対インポート,PEP 370 ユーザごとの site-packages ディレクトリ,PEP 343 "with" ステートメント,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-0366}@anchor{14c9}@anchor{whatsnew/2 6 pep-366-explicit-relative-imports-from-a-main-module}@anchor{15a2}
@subsection PEP 366: メインモジュールからの明示的相対インポート


Python のオプション @ref{23c,,-m} で、モジュールをスクリプトとして実行出来ます。パッケージ内のモジュールを実行する際に、相対インポートが正しく動作していませんでした。

The fix for Python 2.6 adds a @ref{323,,module.__package__} attribute.
When this attribute is present, relative imports will be
relative to the value of this attribute instead of the
@ref{15a3,,__name__} attribute.

PEP 302-style importers can then set @ref{323,,__package__} as necessary.
The @ref{c3,,runpy} module that implements the @ref{23c,,-m} switch now
does this, so relative imports will now work correctly in scripts
running from inside a package.

@c ======================================================================

@node PEP 370 ユーザごとの site-packages ディレクトリ,PEP 371 multiprocessing パッケージ,PEP 366 メインモジュールからの明示的相対インポート,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-0370}@anchor{14ca}@anchor{whatsnew/2 6 pep-370-per-user-site-packages-directory}@anchor{15a4}
@subsection PEP 370: ユーザごとの @code{site-packages} ディレクトリ


When you run Python, the module search path @code{sys.path} usually
includes a directory whose path ends in @code{"site-packages"}.  This
directory is intended to hold locally installed packages available to
all users using a machine or a particular site installation.

Python 2.6 ではユーザ固有のサイトディレクトリのための決まりを導入しました。ディレクトリはプラットフォームに依存して変わります。


@itemize *

@item 
Unix と Mac OS X: @code{~/.local/}

@item 
Windows: @code{%APPDATA%/Python}
@end itemize

このディレクトリ内にはバージョン固有のサブディレクトリが入ります。Unix/Mac OS では  @code{lib/python2.6/site-packages}  のように、Windows では @code{Python26/site-packages}  のように。

If you don't like the default directory, it can be overridden by an
environment variable.  
@geindex PYTHONUSERBASE
@geindex 環境変数; PYTHONUSERBASE
@ref{15a5,,PYTHONUSERBASE} sets the root
directory used for all Python versions supporting this feature.  On
Windows, the directory for application-specific data can be changed by
setting the @code{APPDATA} environment variable.  You can also
modify the @code{site.py} file for your Python installation.

この機能は Python 起動時に @ref{15a6,,-s} オプションを付けるか、環境変数 
@geindex PYTHONNOUSERSITE
@geindex 環境変数; PYTHONNOUSERSITE
@ref{15a7,,PYTHONNOUSERSITE} をセットすることで完全に無効に出来ます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 370

@item PEP 370@footnote{https://peps.python.org/pep-0370/} - ユーザごとの @code{site-packages} ディレクトリ

PEP 著と実装 Christian Heimes.
@end table


@c ======================================================================

@node PEP 371 multiprocessing パッケージ,PEP 3101 進化版文字列フォーマッティング,PEP 370 ユーザごとの site-packages ディレクトリ,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-0371}@anchor{14cb}@anchor{whatsnew/2 6 pep-371-the-multiprocessing-package}@anchor{15a8}
@subsection PEP 371: @code{multiprocessing} パッケージ


新しい @ref{98,,multiprocessing} により、Python プログラムが新たなプロセスを作成して何か計算を実行させて結果を返させることが出来ます。親と子のプロセスはキューとパイプを使って通信し、ロックとセマフォを使って同期し、単純なデータの配列を共有出来ます。

The @ref{98,,multiprocessing} module started out as an exact emulation of
the @ref{f3,,threading} module using processes instead of threads.  That
goal was discarded along the path to Python 2.6, but the general
approach of the module is still similar.  The fundamental class
is the @ref{252,,Process}, which is passed a callable object and
a collection of arguments.  The @ref{15a9,,start()} method
sets the callable running in a subprocess, after which you can call
the @ref{15aa,,is_alive()} method to check whether the
subprocess is still running and the @ref{15ab,,join()}
method to wait for the process to exit.

ここに、サブプロセスが階乗を計算する例を示します。その計算をする関数はヘンテコリンに書かれていて、入力が 4 の倍数だととっても時間がかかるように仕組んであります。

@example
import time
from multiprocessing import Process, Queue


def factorial(queue, N):
    "Compute a factorial."
    # If N is a multiple of 4, this function will take much longer.
    if (N % 4) == 0:
        time.sleep(.05 * N/4)

    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Put the result on the queue
    queue.put(fact)

if __name__ == '__main__':
    queue = Queue()

    N = 5

    p = Process(target=factorial, args=(queue, N))
    p.start()
    p.join()

    result = queue.get()
    print 'Factorial', N, '=', result
@end example

@ref{15ac,,Queue} が factorial の結果を通信して返すのに使われています。 @ref{15ac,,Queue} オブジェクトはグローバル変数に格納されています。子プロセスは、子プロセスが作成された時点のその変数の値を使うことになります; @ref{15ac,,Queue} なので、親子はそのオブジェクトを通信のために使うことが出来ます。(プロセス作成後に親がグローバル変数 queue を差し替えても、子の値は左右されませんし、逆もしかりです。)

Two other classes, @ref{116d,,Pool} and
@ref{250,,Manager}, provide higher-level interfaces.
@ref{116d,,Pool} will create a fixed number of worker
processes, and requests can then be distributed to the workers by calling
@ref{15ad,,apply()} or
@ref{15ae,,apply_async()} to add a single request, and
@ref{12fb,,map()} or
@ref{12fc,,map_async()} to add a number of
requests.  The following code uses a @ref{116d,,Pool} to
spread requests across 5 worker processes and retrieve a list of results:

@example
from multiprocessing import Pool

def factorial(N, dictionary):
    "Compute a factorial."
    ...
p = Pool(5)
result = p.map(factorial, range(1, 1000, 10))
for v in result:
    print v
@end example

これは以下のような出力をします:

@example
1
39916800
51090942171709440000
8222838654177922817725562880000000
33452526613163807108170062053440751665152000000000
...
@end example

The other high-level interface, the @ref{250,,Manager} class,
creates a separate server process that can hold master copies of Python data
structures.  Other processes can then access and modify these data
structures using proxy objects.  The following example creates a
shared dictionary by calling the @ref{183,,dict()} method; the worker
processes then insert values into the dictionary.  (Locking is not
done for you automatically, which doesn't matter in this example.
@ref{250,,Manager}'s methods also include
@ref{15af,,Lock()},
@ref{15b0,,RLock()},
and @ref{15b1,,Semaphore()} to create
shared locks.)

@example
import time
from multiprocessing import Pool, Manager

def factorial(N, dictionary):
    "Compute a factorial."
    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Store result in dictionary
    dictionary[N] = fact

if __name__ == '__main__':
    p = Pool(5)
    mgr = Manager()
    d = mgr.dict()         # Create shared dictionary

    # Run tasks using the pool
    for N in range(1, 1000, 10):
        p.apply_async(factorial, (N, d))

    # Mark pool as closed -- no more tasks can be added.
    p.close()

    # Wait for tasks to exit
    p.join()

    # Output results
    for k, v in sorted(d.items()):
        print k, v
@end example

これはこんな出力をするでしょう:

@example
1 1
11 39916800
21 51090942171709440000
31 8222838654177922817725562880000000
41 33452526613163807108170062053440751665152000000000
51 15511187532873822802242430164693032110632597200169861120000...
@end example


@subsubheading 参考


@ref{98,,multiprocessing} モジュールについてのドキュメント。


@table @asis

@geindex Python Enhancement Proposals; PEP 371

@item PEP 371@footnote{https://peps.python.org/pep-0371/} - multiprocessing パッケージの追加

PEP 著 Jesse Noller と Richard Oudkerk; 実装 Richard Oudkerk と Jesse Noller.
@end table


@c ======================================================================

@node PEP 3101 進化版文字列フォーマッティング,PEP 3105 print を関数にする,PEP 371 multiprocessing パッケージ,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3101}@anchor{14cc}@anchor{whatsnew/2 6 pep-3101-advanced-string-formatting}@anchor{15b2}
@subsection 
@geindex Python Enhancement Proposals; PEP 3101
`PEP 3101': 進化版文字列フォーマッティング


In Python 3.0, the @code{%} operator is supplemented by a more powerful string
formatting method, @ref{199,,format()}.  Support for the @ref{833,,str.format()} method
has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a @code{.format()} method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (@code{@{}, @code{@}}) as special characters:

@example
>>> # Substitute positional argument 0 into the string.
>>> "User ID: @{0@}".format("root")
'User ID: root'
>>> # Use the named keyword arguments
>>> "User ID: @{uid@}   Last seen: @{last_login@}".format(
...    uid="root",
...    last_login = "5 Mar 2008 07:20")
'User ID: root   Last seen: 5 Mar 2008 07:20'
@end example

波括弧自身は二重に書くことでエスケープ出来ます:

@example
>>> "Empty dict: @{@{@}@}".format()
"Empty dict: @{@}"
@end example

フィールド名は、位置引数に対応する整数による @code{@{0@}}, @code{@{1@}}, …、またはキーワード引数に対応する名前です。属性を読み出したり辞書のキーにアクセスするような合成フィールド名(compound field names)も与えることが出来ます:

@example
>>> import sys
>>> print 'Platform: @{0.platform@}\nPython version: @{0.version@}'.format(sys)
Platform: darwin
Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]'

>>> import mimetypes
>>> 'Content-type: @{0[.mp4]@}'.format(mimetypes.types_map)
'Content-type: video/mp4'
@end example

@code{[.mp4]} のように辞書スタイルの記法を使う際は文字列の周りを引用符で囲む必要はありません; @code{.mp4} をキーに値のルックアップされます。数値で始まる文字列は整数に変換されます。フォーマット文字列内でこれ以上複雑な表現は書けません。

ここまでは、結果文字列に置き換えられるフィールドを指定する方法について見てきました。フォーマッティングではさらに、コロンに続けて書式指定子を追加することでコントロール可能です。例えば:

@example
>>> # Field 0: left justify, pad to 15 characters
>>> # Field 1: right justify, pad to 6 characters
>>> fmt = '@{0:15@} $@{1:>6@}'
>>> fmt.format('Registration', 35)
'Registration    $    35'
>>> fmt.format('Tutorial', 50)
'Tutorial        $    50'
>>> fmt.format('Banquet', 125)
'Banquet         $   125'
@end example

書式指定子として、ネストによる他フィールド参照が使えます:

@example
>>> fmt = '@{0:@{1@}@}'
>>> width = 15
>>> fmt.format('Invoice #1234', width)
'Invoice #1234  '
>>> width = 35
>>> fmt.format('Invoice #1234', width)
'Invoice #1234                      '
@end example

望みの幅内でのフィールドの整列を指定可能です:


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文字

@tab

効果

@item

< (デフォルト)

@tab

左寄せ

@item

>

@tab

右寄せ

@item

^

@tab

中央寄せ

@item

=

@tab

(数値型についてのみ) 符号のあとにパディング

@end multitable


書式指定子には体裁のタイプも含めることが出来ます。値をどのようにフォーマットするかです。たとえば浮動小数点数は普通の数値に、あるいは指数形式でフォーマット出来ます:

@example
>>> '@{0:g@}'.format(3.75)
'3.75'
>>> '@{0:e@}'.format(3.75)
'3.750000e+00'
@end example

たくさんの体裁のタイプを利用出来ます。2.6 ドキュメントの @ref{15b3,,complete list} を調べてみてください。以下はその一部です:


@multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{b}

@tab

2進数。出力される数値は2を基数とします。

@item

@code{c}

@tab

文字。数値を対応するユニコード文字に変換します。

@item

@code{d}

@tab

10進数。出力される数値は10を基数とします。

@item

@code{o}

@tab

8進数。出力される数値は8を基数とします。

@item

@code{x}

@tab

16進数。出力される数値は16を基数とします。 10進で9を超える数字には小文字が使われます。

@item

@code{e}

@tab

指数表現です。指数を示す 'e'  を使った科学的記数法で表示します。

@item

@code{g}

@tab

汎用フォーマット。数値が大き過ぎない限りは固定小数点表現をしますが、大きい値では 'e' 指数表現に切り替えます。

@item

@code{n}

@tab

数値です。現在のロケールに合わせて、数値分割文字が挿入されることを除き、 @code{'g'} (浮動小数点数の場合) または 'd' (整数の場合) と同じです。

@item

@code{%}

@tab

パーセンテージです。数値は 100 倍され、固定小数点数フォーマット (@code{'f'}) でパーセント記号付きで表示されます。

@end multitable


Classes and types can define a @ref{831,,__format__()} method to control how they're
formatted.  It receives a single argument, the format specifier:

@example
def __format__(self, format_spec):
    if isinstance(format_spec, unicode):
        return unicode(str(self))
    else:
        return str(self)
@end example

There's also a @ref{199,,format()} builtin that will format a single
value.  It calls the type's @ref{831,,__format__()} method with the
provided specifier:

@example
>>> format(75.6564, '.2f')
'75.66'
@end example


@subsubheading 参考



@table @asis

@item @ref{15b3,,書式指定文字列の文法}

リファレンスドキュメント。

@geindex Python Enhancement Proposals; PEP 3101

@item PEP 3101@footnote{https://peps.python.org/pep-3101/}: 進化版文字列フォーマッティング

PEP 著 Talin; 実装 Eric Smith。
@end table


@c ======================================================================

@node PEP 3105 print を関数にする,PEP 3110 例外処理の変更,PEP 3101 進化版文字列フォーマッティング,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3105}@anchor{14cd}@anchor{whatsnew/2 6 pep-3105-print-as-a-function}@anchor{15b4}
@subsection PEP 3105: @code{print} を関数にする


@code{print} 文は Python 3.0 では @ref{1177,,print()} 関数になります。 @ref{1177,,print()} が関数になることで、 @code{def print(...)} やなにかほかの場所からの新しい関数をインポートするなどの方法で置き換え可能になります。

Python 2.6 では @code{__future__} インポートで 言語構文としての @code{print} を取り除き、関数形式のものを代わりに使えるように出来ます。たとえば:

@example
>>> from __future__ import print_function
>>> print('# of entries', len(dictionary), file=sys.stderr)
@end example

この新しい関数のシグネチャは以下の通りです:

@example
def print(*args, sep=' ', end='\n', file=None)
@end example

パラメータは以下のとおりです:


@itemize *

@item 
`args': 出力される値を指定する位置引数リスト。

@item 
`sep': 引数リスト `args' を出力するのに使われる区切り文字。

@item 
`end': 引数リスト `args'  を全て出力したあとに出力するテキスト。

@item 
`file': 出力が送られるファイルオブジェクト。
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3105

@item PEP 3105@footnote{https://peps.python.org/pep-3105/} - print を関数にする

Georg Brandl 著の PEP。
@end table


@c ======================================================================

@node PEP 3110 例外処理の変更,PEP 3112 バイトリテラル,PEP 3105 print を関数にする,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3110}@anchor{14ce}@anchor{whatsnew/2 6 pep-3110-exception-handling-changes}@anchor{15b5}
@subsection PEP 3110: 例外処理の変更


Python プログラマが時折やらかしてしまう誤りの一つにこんなのがあります:

@example
try:
    ...
except TypeError, ValueError:  # Wrong!
    ...
@end example

このコードの作者はきっと @ref{198,,TypeError} 例外と @ref{2ec,,ValueError} 例外の両方とっつかまえてやろうと思ったのでしょうが、このコードは実際にはちょっと違ったことをします: @ref{198,,TypeError} を捕捉したらこれを @code{"ValueError"} というローカル名の例外オブジェクトに束縛します…。 @ref{2ec,,ValueError} 例外は決して捕捉されません。正しくは、例外のタプルで指定します:

@example
try:
    ...
except (TypeError, ValueError):
    ...
@end example

こんなことが起こってしまうのは、ここではカンマの使用が曖昧だからです: それ、解析木内で 2 つのノードを示すのかな、タプルな単一ノードかしら?

Python 3.0 はカンマからワード "as" に置き換えてこの曖昧さをなくします。例外を捕捉して例外オブジェクトを @code{exc} に記憶するには、こう書かなければなりません:

@example
try:
    ...
except TypeError as exc:
    ...
@end example

Python 3.0 は "as" の使用のみをサポートするようになるので、最初の例は 2 つの異なる例外を捕捉するものとして翻訳されます。Python 2.6 ではカンマも "as" もサポートするので、既存のコードはそのまま動作します。新たに 2.6 で実行される Python コードを書くならば、 "as" の使用を勧めます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3110

@item PEP 3110@footnote{https://peps.python.org/pep-3110/} - Python 3000 での例外の捕捉

PEP 著と実装 Collin Winter.
@end table


@c ======================================================================

@node PEP 3112 バイトリテラル,PEP 3116 新しい I/O ライブラリ,PEP 3110 例外処理の変更,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3112}@anchor{14cf}@anchor{whatsnew/2 6 pep-3112-byte-literals}@anchor{15b6}
@subsection PEP 3112: バイトリテラル


Python 3.0 は Unicode を言語の基本文字列型として採用し、8 ビットリテラルは異なった記法で指示します。それには @code{b'string'} とするか、 @ref{192,,bytes} のコンストラクタを用います。前方互換のために、Python 2.6 は @ref{169,,str} 型に対する別名として @ref{192,,bytes} を追加のうえで、 @code{b'@w{'}} 記法もサポートします。

2.6 の @ref{169,,str} 型は 3.0 の @ref{192,,bytes} 型とは色んな意味で違います; 一番顕著なのは、コンストラクタがまったく異なることです。3.0 での @code{bytes([65, 66, 67])} は 3 つのバイトで @code{ABC} を構築しますが、2.6 での @code{bytes([65, 66, 67])} は引数のリストを @ref{169,,str()} で文字列化した 12 バイト文字列を返します。

2.6 での @ref{192,,bytes} の主な使いみちはオブジェクトの型のテストに @code{isinstance(x, bytes)} とすることでしょう。またこれは、 2.x コードが文字列として ASCII 文字と 8 ビットバイトのどちらを意図しているのか知ることが出来ない 2to3 コンバータの助けになります; あなたは今や @ref{192,,bytes} と @ref{169,,str} の区別を、あなたの意図を正確に表現するのに使えます。そして結果のコードは Python 3.0 で正しいものに修正されるでしょう。

全ての文字列リテラルを Unicode 文字列としてしまう @code{__future__} インポートもあります。これは Unicode 文字を含むのに @code{\u} エスケープシーケンスを使えることを意味します。

@example
from __future__ import unicode_literals

s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
     '\u3081\u3000\u751f\u305f\u307e\u3054')

print len(s)               # 12 Unicode characters
@end example

At the C level, Python 3.0 will rename the existing 8-bit
string type, called @code{PyStringObject} in Python 2.x,
to @ref{995,,PyBytesObject}.  Python 2.6 uses @code{#define}
to support using the names @ref{995,,PyBytesObject()},
@ref{15b7,,PyBytes_Check()}, @ref{15b8,,PyBytes_FromStringAndSize()},
and all the other functions and macros used with strings.

@ref{192,,bytes} 型のインスタンスは単に文字列と同じで @ref{15b9,,immutable} です。 @ref{344,,bytearray} 型が、バイト列を @ref{15ba,,mutable} シーケンスとして格納するものとして新しく追加されました:

@example
>>> bytearray([65, 66, 67])
bytearray(b'ABC')
>>> b = bytearray(u'\u21ef\u3244', 'utf-8')
>>> b
bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
>>> b[0] = '\xe3'
>>> b
bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
>>> unicode(str(b), 'utf-8')
u'\u31ef \u3244'
@end example

Byte arrays support most of the methods of string types, such as
@ref{15bb,,startswith()}/@ref{15bc,,endswith()},
@ref{15bd,,find()}/@ref{15be,,rfind()},
and some of the methods of lists, such as @ref{15bf,,append()},
@ref{15c0,,pop()},  and @ref{15c1,,reverse()}.

@example
>>> b = bytearray('ABC')
>>> b.append('d')
>>> b.append(ord('e'))
>>> b
bytearray(b'ABCde')
@end example

対応する C API もあります。 @ref{15c2,,PyByteArray_FromObject()}, @ref{15c3,,PyByteArray_FromStringAndSize()} や色々その他関数です。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3112

@item PEP 3112@footnote{https://peps.python.org/pep-3112/} - Python 3000 でのバイトリテラル

PEP 著 Jason Orendorff; 2.6 へのバックポート Christian Heimes.
@end table


@c ======================================================================

@node PEP 3116 新しい I/O ライブラリ,PEP 3118 改訂版バッファプロトコル,PEP 3112 バイトリテラル,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3116}@anchor{14d0}@anchor{whatsnew/2 6 pep-3116-new-i-o-library}@anchor{15c4}
@subsection PEP 3116: 新しい I/O ライブラリ


Python's built-in file objects support a number of methods, but
file-like objects don't necessarily support all of them.  Objects that
imitate files usually support @code{read()} and
@code{write()}, but they may not support @code{readline()},
for example.  Python 3.0 introduces a layered I/O library in the @ref{83,,io}
module that separates buffering and text-handling features from the
fundamental read and write operations.

@ref{83,,io} モジュールによって提供される抽象基底クラスには 3 つのレベルがあります:


@itemize *

@item 
@ref{12e7,,RawIOBase} defines raw I/O operations: @ref{101d,,read()},
@ref{101e,,readinto()}, @ref{15c5,,write()},
@ref{14a4,,seek()}, @ref{15c6,,tell()}, @ref{1528,,truncate()},
and @ref{506,,close()}.
Most of the methods of this class will often map to a single system call.
There are also @ref{15c7,,readable()}, @ref{15c8,,writable()},
and @ref{15c9,,seekable()} methods for determining what operations a
given object will allow.

Python 3.0 はこのクラスのファイルとソケットに対する具象実装を持っていますが、Python 2.6 はファイル、ソケットオブジェクトのこの方法での再構築はしていません。

@item 
@ref{8a3,,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 @ref{12e7,,RawIOBase},
and adds a @ref{15ca,,raw} attribute holding the underlying
raw object.

There are five concrete classes implementing this ABC.
@ref{15cb,,BufferedWriter} and @ref{1427,,BufferedReader} are for objects
that support write-only or read-only usage that have a @ref{14a4,,seek()}
method for random access.  @ref{15cc,,BufferedRandom} objects support
read and write access upon the same underlying stream, and
@ref{15cd,,BufferedRWPair} is for objects such as TTYs that have both
read and write operations acting upon unconnected streams of data.
The @ref{10a4,,BytesIO} class supports reading, writing, and seeking
over an in-memory buffer.

@geindex universal newlines;What's new

@item 
@ref{8a4,,TextIOBase}: Provides functions for reading and writing
strings (remember, strings will be Unicode in Python 3.0),
and supporting @ref{f35,,universal newlines}.  @ref{8a4,,TextIOBase} defines
the @ref{bf,,readline()} method and supports iteration upon
objects.

There are two concrete implementations.  @ref{9be,,TextIOWrapper}
wraps a buffered I/O object, supporting all of the methods for
text I/O and adding a @ref{14bb,,buffer} attribute for access
to the underlying object.  @ref{112a,,StringIO} simply buffers
everything in memory without ever writing anything to disk.

(In Python 2.6, @ref{112a,,io.StringIO} is implemented in
pure Python, so it's pretty slow.   You should therefore stick with the
existing @code{StringIO} module or @code{cStringIO} for now.  At some
point Python 3.0's @ref{83,,io} module will be rewritten into C for speed,
and perhaps the C implementation will be  backported to the 2.x releases.)
@end itemize

Python 2.6 では根底にある実装が @ref{83,,io} モジュールのクラスの上に組み立てられるようには再構築されていません (訳注: Python HowTo の移植ガイドにも触れられている通り、2.7 も同じです)。このモジュールは 3.0 への前方互換のコードを書くのを容易にするために、また、開発者たちがバッファリング I/O とテキスト I/O を自身で書く労力を省くために提供されています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3116

@item PEP 3116@footnote{https://peps.python.org/pep-3116/} - 新しい I/O

PEP 著: Daniel Stutzbach, Mike Verdone, Guido van Rossum. 実装: Guido van Rossum, Georg Brandl, Walter Doerwald, Jeremy Hylton, Martin von Loewis, Tony Löwis, ほか.
@end table


@c ======================================================================

@node PEP 3118 改訂版バッファプロトコル,PEP 3119 抽象基底クラス,PEP 3116 新しい I/O ライブラリ,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3118}@anchor{14d1}@anchor{whatsnew/2 6 pep-3118-revised-buffer-protocol}@anchor{15ce}
@subsection PEP 3118: 改訂版バッファプロトコル


バッファプロトコルは Python 型にその内部表現へのポインタをやりとりさせる、C レベル API です。例えば、メモリマップドファイルは文字のバッファとして見ることが出来ます。そしてこれは @ref{be,,re} のようなほかのモジュールが、それを文字列として扱って検索するようなことを許します。

バッファプロトコルの主なユーザは NumPy のような数値演算パッケージで、それらは呼び出し元がより遅い API を経由することなく直接的に行列にデータを書き込むことが出来るように、行列の内部表現を曝しています。この PEP は NumPy 開発の経験を踏まえてバッファプロトコルを更新するもので、行列の形状を表明したり、メモリ領域をロックしたりするような多数の新機能を追加します。

最重要の新規 C API 関数は @code{PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)} で、これはオブジェクトを受け取って、フラグをセットし、 @code{Py_buffer} 構造体にオブジェクトのメモリ表現についての情報を埋めます。オブジェクトはこの操作を、外部の呼び出し元がその内容を修正している間所定のメモリをロックするのに使えます。ですので対応する操作 @code{PyBuffer_Release(Py_buffer *view)} があり、これで外部呼出し元が処理を終えたことを表明します。

@ref{63a,,PyObject_GetBuffer()} への `flags' 引数は返されるメモリについての制約条件を指定します。いくつかの例として:


@itemize *

@item 
@ref{15cf,,PyBUF_WRITABLE} indicates that the memory must be writable.

@item 
@code{PyBUF_LOCK} requests a read-only or exclusive lock on the memory.

@item 
@ref{15d0,,PyBUF_C_CONTIGUOUS} and @ref{15d1,,PyBUF_F_CONTIGUOUS}
requests a C-contiguous (last dimension varies the fastest) or
Fortran-contiguous (first dimension varies the fastest) array layout.
@end itemize

@ref{3c1,,PyArg_ParseTuple()} のための 2 つの新しい書式化コード @code{s*} と @code{z*} は、パラメータとしてロックされたバッファオブジェクトを返します。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3118

@item PEP 3118@footnote{https://peps.python.org/pep-3118/} - 改訂版バッファプロトコル

PEP 著: Travis Oliphant, Carl Banks; 実装: Travis Oliphant.
@end table


@c ======================================================================

@node PEP 3119 抽象基底クラス,PEP 3127 整数リテラルのサポートと文法,PEP 3118 改訂版バッファプロトコル,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3119}@anchor{14d2}@anchor{whatsnew/2 6 pep-3119-abstract-base-classes}@anchor{15d2}
@subsection PEP 3119: 抽象基底クラス


Some object-oriented languages such as Java support interfaces,
declaring that a class has a given set of methods or supports a given
access protocol.  Abstract Base Classes (or ABCs) are an equivalent
feature for Python. The ABC support consists of an @ref{4,,abc} module
containing a metaclass called @ref{111c,,ABCMeta}, special handling of
this metaclass by the @ref{2ad,,isinstance()} and @ref{9c4,,issubclass()}
builtins, and a collection of basic ABCs that the Python developers
think will be widely useful.  Future versions of Python will probably
add more ABCs.

Let's say you have a particular class and wish to know whether it supports
dictionary-style access.  The phrase "dictionary-style" is vague, however.
It probably means that accessing items with @code{obj[1]} works.
Does it imply that setting items with @code{obj[2] = value} works?
Or that the object will have @code{keys()}, @code{values()}, and @code{items()}
methods?  What about the iterative variants  such as @code{iterkeys()}?
@code{copy`and :meth:()}!update`?  Iterating over the object with @code{iter()}?

The Python 2.6 @ref{1e,,collections} module includes a number of
different ABCs that represent these distinctions.  @code{Iterable}
indicates that a class defines @ref{e69,,__iter__()}, and
@code{Container} means the class defines a @ref{15d3,,__contains__()}
method and therefore supports @code{x in y} expressions.  The basic
dictionary interface of getting items, setting items, and
@code{keys()}, @code{values()}, and @code{items()}, is defined by the
@code{MutableMapping} ABC.

あなた自身のクラスを特定の ABC から派生して、ABC のインターフェイスをサポートすることを示せます:

@example
import collections

class Storage(collections.MutableMapping):
    ...
@end example

Alternatively, you could write the class without deriving from
the desired ABC and instead register the class by
calling the ABC's @ref{129a,,register()} method:

@example
import collections

class Storage:
    ...

collections.MutableMapping.register(Storage)
@end example

For classes that you write, deriving from the ABC is probably clearer.
The @ref{129a,,register()}  method is useful when you've written a new
ABC that can describe an existing type or class, or if you want
to declare that some third-party class implements an ABC.
For example, if you defined a @code{PrintableType} ABC,
it's legal to do:

@example
# Register Python's types
PrintableType.register(int)
PrintableType.register(float)
PrintableType.register(str)
@end example

クラスは ABC が規定するセマンティクスに従うべきですが、Python はそれをチェックは出来ません；その ABC の要求を理解してコードを適切に実装するのはクラスの作者任せです。

オブジェクトが特定のインターフェイスをサポートするかどうかをチェックするのには、今やこう書けます:

@example
def func(d):
    if not isinstance(d, collections.MutableMapping):
        raise ValueError("Mapping object expected, not %r" % d)
@end example

これからはたくさんのこのようなチェックをしなければならないのだ、この例のように、などとは思わないように。Python は至極ダックタイピングな流儀なのであって明示的な型チェックは決してされませんし、コードは単純にオブジェクトのメソッドを、それらメソッドがそこにあるはずで、なければ例外になるのを信じて呼ぶだけです。ABC についてのチェックには分別を持ち、それが絶対的に必要な場合にだけそうするようにしましょう。

あなた自身の ABCs を書くには、クラス定義内のメタクラスとして @code{abc.ABCMeta} を使います:

@example
from abc import ABCMeta, abstractmethod

class Drawable():
    __metaclass__ = ABCMeta

    @@abstractmethod
    def draw(self, x, y, scale=1.0):
        pass

    def draw_doubled(self, x, y):
        self.draw(x, y, scale=2.0)


class Square(Drawable):
    def draw(self, x, y, scale):
        ...
@end example

In the @code{Drawable} ABC above, the @code{draw_doubled()} method
renders the object at twice its size and can be implemented in terms
of other methods described in @code{Drawable}.  Classes implementing
this ABC therefore don't need to provide their own implementation
of @code{draw_doubled()}, though they can do so.  An implementation
of @code{draw()} is necessary, though; the ABC can't provide
a useful generic implementation.

You can apply the @ref{1297,,@@~abc.abstractmethod} decorator to methods such as
@code{draw()} that must be implemented; Python will then raise an
exception for classes that don't define the method.
Note that the exception is only raised when you actually
try to create an instance of a subclass lacking the method:

@example
>>> class Circle(Drawable):
...     pass
...
>>> c = Circle()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Circle with abstract methods draw
>>>
@end example

抽象データ属性を @code{@@abstractproperty} を使って宣言出来ます:

@example
from abc import abstractproperty
...

@@abstractproperty
def readonly(self):
   return self._x
@end example

Subclasses must then define a @code{readonly} property.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3119

@item PEP 3119@footnote{https://peps.python.org/pep-3119/} - 抽象基底クラスの導入

PEP は Guido van Rossum と Talin によって著され、Guido van Rossum により実装されています。Python 2.6 へのバックポートは Benjamin Aranguren と Alex Martelli により行われました。
@end table


@c ======================================================================

@node PEP 3127 整数リテラルのサポートと文法,PEP 3129 クラスデコレータ,PEP 3119 抽象基底クラス,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3127}@anchor{14d3}@anchor{whatsnew/2 6 pep-3127-integer-literal-support-and-syntax}@anchor{15d4}
@subsection PEP 3127: 整数リテラルのサポートと文法


Python 3.0 は octal (基数 8: 8 進数) 整数リテラルの構文を変更し、先行するゼロの代わりに "0o" または "0O" (「ゼロオー」)としています。また、 binary (基数 2: 2 進数) 整数リテラルのサポートを追加し、これは "0b" または "0B" で指示します。

Python 2.6 は先行するゼロの形式での 8 進数サポートをやめませんが、 "0o" と "0b" は追加サポートします:

@example
>>> 0o21, 2*8 + 1
(17, 17)
>>> 0b101111
47
@end example

ビルトイン関数 @ref{14e6,,oct()} はまだ先行ゼロ形式での表現を返します。新しいビルトイン関数 @ref{14c0,,bin()} は数値の 2 進数表現を返します:

@example
>>> oct(42)
'052'
>>> future_builtins.oct(42)
'0o52'
>>> bin(173)
'0b10101101'
@end example

ビルトイン @ref{19b,,int()}, @code{long()} が、基数 8 か 0 を要求された場合の "0o" プレフィクス、基数 2 か 0 を要求された場合の "0b" プレフィクスをそれぞれ許容するようになりました(基数 `base' = 0 は文字列から基数を決めるべきであることを指示します):

@example
>>> int ('0o52', 0)
42
>>> int('1101', 2)
13
>>> int('0b1101', 2)
13
>>> int('0b1101', 0)
13
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3127

@item PEP 3127@footnote{https://peps.python.org/pep-3127/} - 整数リテラルのサポートと文法

PEP 著 Patrick Maupin、2.6 へのバックポートは Eric Smith による。
@end table


@c ======================================================================

@node PEP 3129 クラスデコレータ,PEP 3141 数値の型階層,PEP 3127 整数リテラルのサポートと文法,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3129}@anchor{14d4}@anchor{whatsnew/2 6 pep-3129-class-decorators}@anchor{15d5}
@subsection PEP 3129: クラスデコレータ


デコレータが拡張されて関数だけでなクラスにも使えるようになりました。今やこのように書くのは合法です:

@example
@@foo
@@bar
class A:
  pass
@end example

これは次と等価です:

@example
class A:
  pass

A = foo(bar(A))
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3129

@item PEP 3129@footnote{https://peps.python.org/pep-3129/} - クラスデコレータ

PEP 著 Collin Winter.
@end table


@c ======================================================================

@node PEP 3141 数値の型階層,その他の言語変更<15>,PEP 3129 クラスデコレータ,What's New in Python 2 6
@anchor{whatsnew/2 6 pep-3141}@anchor{14d5}@anchor{whatsnew/2 6 pep-3141-a-type-hierarchy-for-numbers}@anchor{15d6}
@subsection PEP 3141: 数値の型階層


Python 3.0 では Scheme の numeric tower に触発された、いくつかの数値型のための抽象基底クラスを追加しています。これらのクラスは @ref{a2,,numbers} モジュール として 2.6 にバックポートされています。

一番てっぺんの汎用 ABC が @code{Number} です。これには何の演算も含まれず、オブジェクトがなんらか数値であることをチェックするためだけにあります。 @code{isinstance(obj, Number)} として使えます。

@code{Complex} は @code{Number} のサブクラスです。複素数は基礎的な追加の演算の加算、減算、積算、除算、累乗に耐えるとともに、実数部と虚数部の抽出と共役数の取得が出来ます。Python のビルトインの complex 型は @code{Complex} を実装しています。

@code{Real} は @code{Complex} から更に派生し、実数のみで動作する演算を追加しています: @code{floor()}, @code{trunc()}, 丸め, divmod, floor division, 比較、です。

@code{Rational} 数は @code{Real} からの派生で、プロパティ @code{numerator}, @code{denominator} を持ち、浮動小数点数への変換が出来ます。Python 2.6 は単純な有理数クラス @code{Fraction} を @ref{61,,fractions} モジュールに追加しています。(@code{Rational} ではなく @code{Fraction} なのは、 @ref{14d6,,numbers.Rational} と名前が衝突するのを避けるためです。)

@code{Integral} 数は @code{Rational} からの派生で、シフト演算 @code{<<}, @code{>>} が出来て、 @code{&} や @code{|} のようなビット演算で混ぜ合わせることができて、また、配列のインデクスとスライスの境界として使えます。

Python 3.0 では、その PEP は少し既存のビルトイン @ref{14f2,,round()}, @ref{15d7,,math.floor()}, @ref{15d8,,math.ceil()} を再定義していて、また、Python 2.6 にバックポートされている新しい @ref{15d9,,math.trunc()} を追加しています。 @ref{15d9,,math.trunc()} はゼロに向かう方向の丸めで、引数とゼロの間で一番近い @code{Integral} を返します。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3141

@item PEP 3141@footnote{https://peps.python.org/pep-3141/} - 数値の型階層

PEP 著: Jeffrey Yasskin.
@end table

Guile マニュアルの Scheme's numerical tower@footnote{https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower} 。

Scheme's number datatypes@footnote{https://conservatory.scheme.org/schemers/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2} from the R5RS Scheme specification.


@menu
* fractions モジュール:: 

@end menu

@node fractions モジュール,,,PEP 3141 数値の型階層
@anchor{whatsnew/2 6 the-fractions-module}@anchor{15da}
@subsubsection @code{fractions} モジュール


数値型階層を埋めるべく、 @ref{61,,fractions} モジュールが有理数クラスを提供しています。有理数は分子(numerator)と分母(denominator)で構成される分数としてその値を格納し、浮動小数点数では近似しか出来ない @code{2/3} のような数を正確に表現出来ます。

@code{Fraction} のコンストラクタは 2 つの @code{Integral} 値を取り、それらはそれぞれ結果の分数の分子と分母になります。:

@example
>>> from fractions import Fraction
>>> a = Fraction(2, 3)
>>> b = Fraction(2, 5)
>>> float(a), float(b)
(0.66666666666666663, 0.40000000000000002)
>>> a+b
Fraction(16, 15)
>>> a/b
Fraction(5, 3)
@end example

For converting floating-point numbers to rationals,
the float type now has an @code{as_integer_ratio()} method that returns
the numerator and denominator for a fraction that evaluates to the same
floating-point value:

@example
>>> (2.5) .as_integer_ratio()
(5, 2)
>>> (3.1415) .as_integer_ratio()
(7074029114692207L, 2251799813685248L)
>>> (1./3) .as_integer_ratio()
(6004799503160661L, 18014398509481984L)
@end example

1./3 のような浮動小数点数で近似にしかならない値は、近似して単純化されたりはしないことに注意してください; その分数は浮動小数点数に `正確に' 合うように試みられます。

@ref{61,,fractions} モジュールは、ずっと長い間 Python の @code{Demo/classes/} ディレクトリにいた Sjoerd Mullender による実装に基いています。この実装が Jeffrey Yasskin によって大幅に更新されました。

@node その他の言語変更<15>,新しいモジュールと改良されたモジュール<2>,PEP 3141 数値の型階層,What's New in Python 2 6
@anchor{whatsnew/2 6 other-language-changes}@anchor{15db}
@subsection その他の言語変更


Python 言語コアに小さな変更がいくつか行われました:


@itemize *

@item 
@code{__main__.py} を含んだディレクトリ名と zip アーカイブ名をインタプリタに渡して直接実行出来るようになりました。そのディレクトリと zip アーカイブは自動的に sys.path エントリの先頭に追加されます。(Suggestion and initial patch by Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan; bpo-1739468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739468}.)

@item 
@ref{6f9,,hasattr()} 関数は @code{__getattr__()} メソッドが例外を起こすと何か失敗したのだと仮定して、全て捕捉して無視して @code{False} を返していました。ですがそのロジックは @ref{bc5,,KeyboardInterrupt} と @ref{f3c,,SystemExit} まで捕まえるべきではなかったのです。Python 2.6 では @ref{6f9,,hasattr()} はもはやそれら例外に出会ってもそれを捨てません。 (Fixed by Benjamin Peterson; bpo-2196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2196}.)

@item 
@code{**} 構文を使ってキーワード引数を許容する関数を呼び出すのに、もう Python 辞書を使う必要はありません; 任意のマッピングプロトコルをサポートするオブジェクトで今では動作します:

@example
>>> def f(**kw):
...    print sorted(kw)
...
>>> ud=UserDict.UserDict()
>>> ud['a'] = 1
>>> ud['b'] = 'string'
>>> f(**ud)
['a', 'b']
@end example

(Contributed by Alexander Belopolsky; bpo-1686487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1686487}.)

同時に、 @code{*args} 引数のあとでキーワード引数を与える関数呼び出しも今では合法です。:

@example
>>> def f(*args, **kw):
...     print args, kw
...
>>> f(1,2,3, *(4,5,6), keyword=13)
(1, 2, 3, 4, 5, 6) @{'keyword': 13@}
@end example

以前はこれは構文エラーになっていました。 (Contributed by Amaury Forgeot d'Arc; bpo-3473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3473}.)

@item 
新しいビルトイン @code{next(iterator, [default])} は指定したイテレータより次のアイテムを返します。 `iterator' が使い果たされている場合、 `default' 引数が与えられていれがこれを、そうでなければ @ref{df5,,StopIteration} 例外を起こします。 (Backported in bpo-2719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2719}.)

@item 
Tuples now have @ref{15dc,,index()} and @ref{15dd,,count()} methods
matching the list type's @ref{15de,,index()} and @ref{15df,,count()} methods:

@example
>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.count(0)
2
@end example

(Contributed by Raymond Hettinger)

@item 
ビルトイン型が拡張スライス構文をサポートするために改善されています。色々な @code{(start, stop, step)} 組み合わせを受け付けます。以前はこれのサポートは限定的で、ものによっては動作しませんでした。 (Implemented by Thomas Wouters.)

@c Revision 57619

@item 
property に @code{getter}, @code{setter}, @code{deleter} が追加されています。取得関数(getter)、設定関数(setter)、削除関数(deleter)を既存のプロパティに追加するための便利なショートカットとして使えるデコレータです。これらはこのように使えます:

@example
class C(object):
    @@property
    def x(self):
        return self._x

    @@x.setter
    def x(self, value):
        self._x = value

    @@x.deleter
    def x(self):
        del self._x

class D(C):
    @@C.x.getter
    def x(self):
        return self._x * 2

    @@x.setter
    def x(self, value):
        self._x = value / 2
@end example

@item 
ビルトインの set 型のいくつかのメソッドが複数イテラブルを受け付けるようになっています: @code{intersection()}, @code{intersection_update()}, @code{union()}, @code{update()}, @code{difference()}, @code{difference_update()} です。

@example
>>> s=set('1234567890')
>>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
set(['2'])
>>> s.difference('246', '789')
set(['1', '0', '3', '5'])
@end example

(Contributed by Raymond Hettinger.)

@item 
たくさんの浮動小数点数機能が追加されました。 @ref{196,,float()} 関数は文字列 @code{nan} を IEEE 754 非数 (Not A Number) 値に変換し、 @code{+inf} と @code{-inf} は正あるいは負の無限大に変換します。これは IEEE 754 セマンティクスのあらゆるプラットフォームで動作します。 (Contributed by Christian Heimes; bpo-1635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635}.)

ほか @ref{92,,math} モジュールに @code{isinf()} と @code{isnan()} が追加されています; 浮動小数点数が、前者は無限大ならば、後者は非数ならばそれぞれ真を返します。 (bpo-1640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1640})

浮動小数点数を 16 進表記文字列に変換する変換関数が追加されています (bpo-3008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3008})。これら関数は 10 進と 2 進との間の変換で起こる丸め誤差を持ち込まずに浮動小数点数と文字列表現の相互変換をします。浮動小数点数は文字列表現を返す @ref{14e7,,hex()} メソッドを持ち、また、 @code{float.fromhex()} メソッドが文字列から浮動小数点数に戻します:

@example
>>> a = 3.75
>>> a.hex()
'0x1.e000000000000p+1'
>>> float.fromhex('0x1.e000000000000p+1')
3.75
>>> b=1./3
>>> b.hex()
'0x1.5555555555555p-2'
@end example

@item 
数に関する繊細さ: 符号付ゼロ (-0 と +0) をサポートするシステムで 2 つの浮動小数点数から複素数を作る際に、 @ref{197,,complex()} コンストラクタがゼロの符号を維持するようになりました。 (Fixed by Mark T. Dickinson; bpo-1507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1507}.)

@item 
@code{__hash__()} メソッドを親クラスから継承するクラスは、ハッシュ出来ないことを示すのに @code{__hash__ = None} をセット出来ます。これにより @code{hash(obj)} は @ref{198,,TypeError} を起こし、そのクラスは @code{Hashable} ABC を実装していないことを示します。

@code{__cmp__()} か @code{__eq__()} を定義するのにその比較にオブジェクトの身元ではなくその値を使ったならば、あなたはこれをすべきです。全てのオブジェクトはその値として @code{id(obj)} を使うデフォルトのハッシュ化メソッドを持っています。親クラスから継承した @code{__hash__()} を削除する整理された方法はありません。ですのでオーバライドとしての @code{None} の代入が実装されました。 C API のレベルでは、拡張は @code{tp_hash} に @ref{15e0,,PyObject_HashNotImplemented()} をセット出来ます。 (Fixed by Nick Coghlan and Amaury Forgeot d'Arc; bpo-2235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2235}.)

@item 
@ref{15e1,,GeneratorExit} 例外が @ref{bcd,,Exception} ではなく @ref{7d6,,BaseException} のサブクラスになっています。 @code{except Exception:} をする例外ハンドラが意図せず @ref{15e1,,GeneratorExit} 捕捉してしまうことがなくなります。 (Contributed by Chad Austin; bpo-1537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1537}.)

@item 
ジェネレータオブジェクトが、そのジェネレータを返すオリジナルのコードオブジェクトを参照する @code{gi_code} 属性を持つようになりました。 (Contributed by Collin Winter; bpo-1473257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1473257}.)

@item 
ビルトイン関数 @ref{4b1,,compile()} が位置引数だけでなくキーワード引数も受け付けるようになりました。  (Contributed by Thomas Wouters; bpo-1444529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1444529}.)

@item 
@ref{197,,complex()} コンストラクタが括弧で囲まれた複素数表現文字列を受け付けるようになっています。 @code{complex(repr(cplx))} で元に戻せるということです。例えば @code{complex('(3+4j)')} は今では値 @code{(3+4j)} を返します。 (bpo-1491866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1491866})

@item 
文字列の @code{translate()} メソッドが変形テーブルパラメータとして @code{None} を受け付けるようになりました。そのまま同じものを返す変形として扱われます。これにより文字を削除する操作を実行するのが簡単になります。 (Contributed by Bengt Richter and implemented by Raymond Hettinger; bpo-1193128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1193128}.)

@item 
ビルトインの @ref{844,,dir()} 関数が、受け取ったオブジェクトの @code{__dir__()} メソッドをチェックするようになりました。このメソッドはそのオブジェクトで妥当な属性名を含む文字列のリストを返さなければなりません。これにより @ref{844,,dir()} が生成する値を制御出来ます。 @code{__getattr__()} や @code{__getattribute__()} メソッドを使うオブジェクトはこれを使うことで、約束するつもりの擬似属性を公表出来ます。 (bpo-1591665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1591665})

@item 
Instance method objects have new attributes for the object and function
comprising the method; the new synonym for @code{im_self} is
@ref{15e2,,__self__}, and @code{im_func} is also available as
@ref{1514,,__func__}.
The old names are still supported in Python 2.6, but are gone in 3.0.

@item 
目立たない変更: @ref{46f,,locals()} 関数を @ref{14ef,,class} ステートメント内で使う際、結果の辞書はもはや自由変数を返しません。(この場合、自由変数は @code{class} ステートメント内で参照される変数で、クラスの属性ではありません。)
@end itemize

@c ======================================================================

@menu
* 最適化: 最適化<15>. 
* インタプリタの変更: インタプリタの変更<2>. 

@end menu

@node 最適化<15>,インタプリタの変更<2>,,その他の言語変更<15>
@anchor{whatsnew/2 6 optimizations}@anchor{15e3}
@subsubsection 最適化



@itemize *

@item 
@ref{118,,warnings} モジュールが C で書き直されました。これにより警告をパーサから発行出来、また、インタプリタの起動が高速化しています。 (Contributed by Neal Norwitz and Brett Cannon; bpo-1631171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1631171}.)

@item 
型オブジェクトがメソッドのキャッシュを持つようになっています。これは個別のクラスについての正しいメソッド実装を見つけるのに必要な仕事を減らします。いったんキャッシュされれば、インタプリタは呼び出さなければならない正しいメソッドを知るために基底クラス群を横断しなくてもよくなります。基底クラスやクラス自身が修正されれば、Python の動的な振る舞いの面においても正しくあり続けなければならないので、キャッシュはクリアされます。 (Original optimization implemented by Armin Rigo, updated for Python 2.6 by Kevin Jacobs; bpo-1700288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1700288}.)

デフォルトではこの変更は、Python コアに含まれる型のみに適用されます。拡張モジュールは必ずしもこのキャッシュに互換ではなく、拡張モジュールはメソッドキャッシュを有効にするために、モジュールの @code{tp_flags} フィールドに明示的に @code{Py_TPFLAGS_HAVE_VERSION_TAG} を追加しなければなりません。(このメソッドキャッシュに対して互換であるためには、拡張モジュールのコードは、それが実装するどんな型についても @code{tp_dict} メンバに直接アクセスしたり修正したりしてはなりません。ほとんどのモジュールはこれをしていませんが、Python インタプリタがそれを検知することは出来ません。 bpo-1878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1878} にいくらかの議論がありますので参照してください。)

@item 
キーワード引数を使う関数呼び出しが、素早くポインタで比較することで顕著に高速化しています。これは常に文字列丸ごとを比較する時間を省きます。 (Contributed by Raymond Hettinger, after an initial implementation by Antoine Pitrou; bpo-1819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1819}.)

@item 
@ref{db,,struct} モジュールの全ての関数が C で書き換えられました。「Need For Speed スプリント」での作業の成果です。 (Contributed by Raymond Hettinger.)

@item 
いくつかの標準ビルトイン型が、その型オブジェクトにビットをセットするようになりました。これは、オブジェクトがそれら型のサブクラスの一つであるかどうかのチェックするのを高速化します。 (Contributed by Neal Norwitz.)

@item 
Unicode 文字列が、空白文字と改行を検出するためのコードにより高速な実装を使うようになりました; @code{split()} メソッドでおよそ 25% の速度向上、 @code{splitlines()} メソッドでは 35% です。(Contributed by Antoine Pitrou.) Unicode 文字列データのために pymalloc を使うことでメモリ使用が減りました。

@item 
The @code{with} statement now stores the @ref{1518,,__exit__()} method on the stack,
producing a small speedup.  (Implemented by Jeffrey Yasskin.)

@item 
メモリ使用を減らすために、一番作られたオブジェクトをガーベージコレクトする際に、ガーベージコレクタが内部のフリーリストをクリアするようになりました。これはオペレーティングシステムにすぐに返されます。
@end itemize

@c ======================================================================

@node インタプリタの変更<2>,,最適化<15>,その他の言語変更<15>
@anchor{whatsnew/2 6 interpreter-changes}@anchor{15e4}@anchor{whatsnew/2 6 new-26-interpreter}@anchor{15e5}
@subsubsection インタプリタの変更


Two command-line options have been reserved for use by other Python
implementations.  The @code{-J} switch has been reserved for use by
Jython for Jython-specific options, such as switches that are passed to
the underlying JVM.  @ref{16f,,-X} has been reserved for options
specific to a particular implementation of Python such as CPython,
Jython, or IronPython.  If either option is used with Python 2.6, the
interpreter will report that the option isn't currently used.

Python インタプリタに @ref{15e6,,-B} スイッチを渡すか、インタプリタ実行前に環境変数 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@ref{15e7,,PYTHONDONTWRITEBYTECODE} をセットするかのどちらかで、 @code{.pyc} や @code{.pyo} が作られないようにすることが出来るようになりました。この設定は Python プログラムから @code{sys.dont_write_bytecode} 変数として利用可能で、Python コードはこの変数を変更してインタプリタの振る舞いを変えることが出来ます。 (Contributed by Neal Norwitz and Georg Brandl.)

標準入力、標準出力、標準エラー出力に使うエンコーディングを、インタプリタ起動前に環境変数 
@geindex PYTHONIOENCODING
@geindex 環境変数; PYTHONIOENCODING
@ref{120c,,PYTHONIOENCODING} を設定することで指定出来るようになりました。値は @code{<encoding>} または @code{<encoding>:<errorhandler>} 形式の文字列でなければなりません。 `encoding' 部分はエンコーディングの名前で、例えば @code{utf-8} や @code{latin-1} です; 省略可能な `errorhandler' 部分はエンコーディングによって処理出来ない文字に対して何をするのかを指定するもので、 "error", "ignore", "replace" のどれかです。 (Contributed by Martin von Löwis.)

@c ======================================================================

@node 新しいモジュールと改良されたモジュール<2>,非推奨と削除,その他の言語変更<15>,What's New in Python 2 6
@anchor{whatsnew/2 6 new-and-improved-modules}@anchor{15e8}
@subsection 新しいモジュールと改良されたモジュール


全てのリリースに置いて、 Python の標準ライブラリはたくさんの改良とバグ修正がされてきました。ここでは一部の注目に値する変更を、モジュール名で辞書順ソートしてリストアップしています。もっと完全な変更リストが見たければ、ソースツリー内の @code{Misc/NEWS} ファイルか、全ての完全な詳細が入っている Subversion のログを参照してください。


@itemize *

@item 
The @code{asyncore} and @code{asynchat} modules are
being actively maintained again, and a number of patches and bugfixes
were applied.  (Maintained by Josiah Carlson; see bpo-1736190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1736190} for
one patch.)

@item 
@code{bsddb} モジュールは新しいメンテナ Jesús Cea Avión を得て、パッケージは今ではスタンドアロンのパッケージとして入手可能です。パッケージのウェブページは www.jcea.es/programacion/pybsddb.htm@footnote{https://www.jcea.es/programacion/pybsddb.htm} です。このモジュールは Python 3.0 では標準ライブラリからは削除される予定です。というのも、これの更新ペースは Python のそれよりも遥かに頻繁だからです。

@code{bsddb.dbshelve} モジュールは pickle 化で、プロトコル 1 に制限するのではなく利用出来る一番高いプロトコルバージョンを使うようになりました。(Contributed by W. Barnes.)

@item 
The @code{cgi} module will now read variables from the query string
of an HTTP POST request.  This makes it possible to use form actions
with URLs that include query strings such as
"/cgi-bin/add.py?category=1".  (Contributed by Alexandre Fiori and
Nubis; bpo-1817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1817}.)

The @code{parse_qs()} and @code{parse_qsl()} functions have been
relocated from the @code{cgi} module to the @ref{110,,urlparse} module.
The versions still available in the @code{cgi} module will
trigger @ref{ac5,,PendingDeprecationWarning} messages in 2.6
(bpo-600362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=600362}).

@item 
@ref{19,,cmath} モジュールに大掛かりな改訂が行われました。Mark Dickinson と Christian Heimes による貢献です。5 つの新しい関数が追加されました:


@itemize *

@item 
@code{polar()} は複素数を極形式 (polar form) に変換し、複素数の絶対値 (modulus) と偏角 (argument) を返します。

@item 
@code{rect()} はその逆で、絶対値と偏角から対応する複素数に戻します。

@item 
@code{phase()} は複素数の偏角 (angle とも呼ばれています) を返します。

@item 
@code{isnan()} はその引数の実数部か虚数部のどちらかが NaN であれば真を返します。

@item 
@code{isinf()} はその引数の実数部か虚数部のどちらかが無限大であれば真を返します。
@end itemize

その改訂では、 @ref{19,,cmath} モジュールの数値的安定性も改善されました。全ての関数で、結果の実数部、虚数部は最小精度単位で少しの範囲内で、可能な限り正確です。詳細は bpo-1381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1381} を見てください。 @code{asinh()}, @code{atanh()}:, @code{atan()} に対する分岐截線 (branch cut) も修正されています。(--- 訳注: units of least precision に対する枯れた訳語はないようなので最小精度単位としていますが仮数部の最下位ビットのことです。ので、within a few ulps は下位数ビットという意味。分岐截線 (branch cut) は一般的な訳語かどうかはわかりませんが、wikipedia から採りました。---)

そのモジュールのテストは大変拡大しました; およそ 2000 の新たなテストケースが数学関数群を鍛え上げます。

IEEE 754 プラットフォームでは @ref{19,,cmath} モジュールは、IEEE 754 の特殊値と浮動小数点例外を、C99 標準の付録 'G' での一貫性のある方法で処理するようになりました。

@item 
A new data type in the @ref{1e,,collections} module: @code{namedtuple(typename, fieldnames)}
is a factory function that creates subclasses of the standard tuple
whose fields are accessible by name as well as index.  For example:

@example
>>> var_type = collections.namedtuple('variable',
...             'id name type size')
>>> # Names are separated by spaces or commas.
>>> # 'id, name, type, size' would also work.
>>> var_type._fields
('id', 'name', 'type', 'size')

>>> var = var_type(1, 'frequency', 'int', 4)
>>> print var[0], var.id    # Equivalent
1 1
>>> print var[2], var.type  # Equivalent
int int
>>> var._asdict()
@{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'@}
>>> v2 = var._replace(name='amplitude')
>>> v2
variable(id=1, name='amplitude', type='int', size=4)
@end example

Several places in the standard library that returned tuples have
been modified to return @code{namedtuple()} instances.  For example,
the @code{Decimal.as_tuple()} method now returns a named tuple with
@code{sign}, @code{digits}, and @code{exponent} fields.

(Contributed by Raymond Hettinger.)

@item 
@ref{1e,,collections} モジュールのもう一つの変更は、 @code{deque} 型が省略可能な `maxlen' パラメータをサポートするようになったことです; 与えられると、 deque のサイズが要素数 `maxlen' を超えないように制限されます。お腹いっぱいの deque にさらに要素を追加すると、古いものから捨てられます。

@example
>>> from collections import deque
>>> dq=deque(maxlen=3)
>>> dq
deque([], maxlen=3)
>>> dq.append(1); dq.append(2); dq.append(3)
>>> dq
deque([1, 2, 3], maxlen=3)
>>> dq.append(4)
>>> dq
deque([2, 3, 4], maxlen=3)
@end example

(Contributed by Raymond Hettinger.)

@item 
The @ref{75,,Cookie} module's @ref{dfe,,Morsel} objects now support an
@ref{15e9,,httponly} attribute.  In some browsers. cookies with this attribute
set cannot be accessed or manipulated by JavaScript code.
(Contributed by Arvin Schnell; bpo-1638033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1638033}.)

@item 
@ref{2f,,curses} モジュールの新しい window メソッド @code{chgat()} は、一行での指定数ぶん文字の表示属性を変更します。 (Contributed by Fabian Kreutz.)

@example
# Boldface text starting at y=0,x=21
# and affecting the rest of the line.
stdscr.chgat(0, 21, curses.A_BOLD)
@end example

@ref{32,,curses.textpad} モジュールの @code{Textbox} クラスが上書きモードのほかに挿入モード編集をサポートするようになりました。挿入モードは @code{Textbox} インスタンス構築時に `insert_mode' パラメータを真にすることで有効になります。

@item 
@ref{34,,datetime} モジュールの @code{strftime()} メソッドが @code{%f} 書式化コードをサポートするようになりました。これはオブジェクトのマイクロ秒をミリ秒としてゼロ埋めで 6 桁で展開します。 (---訳注: 言葉だけだとどうしても伝わりにくいですが、フィールドとしてミリ秒を持たずにマイクロ秒を持っている datetime で「秒.ミリ秒」という表記をするのにマイクロ秒精度まで表示するのが目的です。ですので 654 ミリ秒が「654000」と書式化されますし、32 ミリ秒は「032000」です。---) (Contributed by Skip Montanaro; bpo-1158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1158}.)

@item 
The @ref{3a,,decimal} module was updated to version 1.66 of
the General Decimal Specification@footnote{https://speleotrove.com/decimal/decarith.html}.  New features
include some methods for some basic mathematical functions such as
@code{exp()} and @code{log10()}:

@example
>>> Decimal(1).exp()
Decimal("2.718281828459045235360287471")
>>> Decimal("2.7182818").ln()
Decimal("0.9999999895305022877376682436")
>>> Decimal(1000).log10()
Decimal("3")
@end example

@code{Decimal} クラスの @code{as_tuple()} メソッドが @code{sign}, @code{digits}, @code{exponent} フィールドを持った名前付きタプルを返すようになりました。

(Implemented by Facundo Batista and Mark Dickinson.  Named tuple
support added by Raymond Hettinger.)

@item 
@ref{3b,,difflib} モジュールの @code{SequenceMatcher} クラスが、マッチを @code{a}, @code{b}, @code{size} 属性を持つ名前付きタプルで返すようになりました。 (Contributed by Raymond Hettinger.)

@item 
@ref{af6,,ftplib.FTP} クラスのコンストラクタと @code{connect()} メソッドに省略可能 @code{timeout} パラメータが追加されました。タイムアウトを秒で指定します。(Added by Facundo Batista.) また、 @code{FTP} クラスの @code{storbinary()} と @code{storlines()} メソッドが `callback' パラメータを新たに受け取ります。これはデータが送信されたあとでデータの各ブロックごとに呼び出されます。 (Contributed by Phil Schwartz; bpo-1221598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1221598}.)

@item 
ビルトイン関数の @code{reduce()} が @ref{63,,functools} モジュールでも利用可能です。Python 3.0 ではビルトイン関数は削除されて @ref{63,,functools} のものだけが使えます; 現在のところ 2.x シリーズでビルトイン版を削除する計画はありません。 (Patched by Christian Heimes; bpo-1739906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739906}.) (---訳注: 2.7 でも削除されていません。使用を検出するには @code{-3} オプションなどで警告をチェックしてください。 ---)

@item 
可能な場合には、 @ref{66,,getpass} モジュールはプロンプトメッセージ出力とパスワードの読み取りに @code{/dev/tty} を使うようになりました。利用出来ない場合は標準エラー出力と標準入力が使われます。端末に入力パスワードがエコーされるかもしれない場合、プロンプト表示の前に警告が出力されます。 (Contributed by Gregory P. Smith.)

@item 
@ref{5a0,,glob.glob()} 関数が、Unicode パスが使われるかディレクトリ内に Unicode ファイル名がマッチすると Unicode ファイル名を返すようになりました。 (bpo-1001604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1001604})

@item 
@ref{6d,,heapq} モジュールの新しい関数 @code{merge(iter1, iter2, ...)} は、任意の数のソートされたデータを返すイテラブルを取り、全てのイテラブルの内容をソートされた順に返す新しいジェネレータを返します (---訳注: 誤解を招く表現なので補足しておきますが、入力のイテレータはソート済みであることを「仮定」し、出力のジェネレータは「入力が主張している」順序に従うだけです。入力がソートされていなくても並べ替えられるわけではありません。リファレンスにはここはきちんと書かれています。---)。例えば:

@example
>>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
[1, 2, 3, 5, 8, 9, 16]
@end example

もう一つの新たな関数 @code{heappushpop(heap, item)} は、 `item' を `heap' に push した後、pop を行って `heap' から最初の要素を返します。この一続きの動作を @code{heappush()} に引き続いて @code{heappop()} を別々に呼び出すよりも効率的に実行します。

@ref{6d,,heapq} は以前使っていた「以下(@code{<=})」比較ではなく「より小さい(@code{<})」比較だけを使って実装されています。これにより @ref{6d,,heapq} に格納する型の要件が @ref{dc8,,list.sort()} メソッドに合致します。 (Contributed by Raymond Hettinger.)

@item 
An optional @code{timeout} parameter, specifying a timeout measured in
seconds, was added to the @ref{d35,,httplib.HTTPConnection} and
@ref{d36,,HTTPSConnection} class constructors.  (Added by Facundo
Batista.)

@item 
@code{getmoduleinfo()} や @code{getargs()} のようなほとんどの @ref{82,,inspect} モジュール関数が、名前付きタプルを返すようになりました。タプルのように振る舞うだけでなく、属性でアクセスすることも出来ます。 (Contributed by Raymond Hettinger.)

モジュールには @code{isgenerator()}, @code{isgeneratorfunction()}, @code{isabstract()} を含むいくつかの新しい関数が追加されています。

@item 
@ref{85,,itertools} モジュールにいくつかの関数が追加されています。

@code{izip_longest(iter1, iter2, ...[, fillvalue])} はそれぞれの要素群からタプルを生成します; イテラブルの要素数がほかのものより短ければ欠落値として `fillvalue' が埋められます。例えば:

@example
>>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))
@end example

@code{product(iter1, iter2, ..., [repeat=N])} は与えたイテラブルの直積 (Cartesian product)、つまりそれぞれのイテラブルから返るその要素たちの全てのありうる組み合わせを含むタプルの集合を返します。:

@example
>>> list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
 (2, 4), (2, 5), (2, 6),
 (3, 4), (3, 5), (3, 6)]
@end example

省略可能 `repeat' キーワード引数が与えられると、イテラブルが一つであればこれが `N' 個、複数あればそのセットが `N' 回与えられたとみなします。単一のイテラブルに対しては `N' 要素タプルのリストで返ります:

@example
>>> list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
@end example

2 つのイテラブルであれば `2N' 要素タプルのリストで返ります:

@example
>>> list(itertools.product([1,2], [3,4], repeat=2))
[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
@end example

@code{combinations(iterable, r)}  は、入力 `iterable' の要素からなる長さ `r' の部分列を返します (---訳注: 数学の初等組み合わせ論の「組合せ (combination)」 ---):

@example
>>> list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]
>>> list(itertools.combinations('123', 3))
[('1', '2', '3')]
>>> list(itertools.combinations('1234', 3))
[('1', '2', '3'), ('1', '2', '4'),
 ('1', '3', '4'), ('2', '3', '4')]
@end example

@code{permutations(iter[, r])} は入力 `iterable' の長さ `r' の順列を返します。 `r' が指定されなければ、イテラブルが生成する全要素数がデフォルトで使われます (---訳注: 数学の初等組み合わせ論の「順列 (sequence without repetition)」または群論や組合せ論の「置換 (permutation)」。リファレンスでは訳出で置換も順列も両方出てきていますが、高校教育で習う用語で「順列」が伝わりやすいのでここでは「順列」としています。 ---):

@example
>>> list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
 (2, 1), (2, 3), (2, 4),
 (3, 1), (3, 2), (3, 4),
 (4, 1), (4, 2), (4, 3)]
@end example

@code{itertools.chain(*iterables)} は @ref{85,,itertools} に元々いたものですが、新しい構築方法が出来ました。Python 2.6 では、 @code{itertools.chain.from_iterable(iterable)} でほかのイテラブルを返す単一のイテラブルを取り、 @code{chain()} は、最初のイテラブルからの全要素、次のイテラブルからの全要素、…、のように返します:

@example
>>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
[1, 2, 3, 4, 5, 6]
@end example

(All contributed by Raymond Hettinger.)

@item 
@ref{8b,,logging} モジュールの @code{FileHandler} クラスとそのサブクラスの @code{WatchedFileHandler}, @code{RotatingFileHandler}, @code{TimedRotatingFileHandler} がそのコンストラクタで省略可能 `delay' パラメータを受け取るようになりました。 `delay' が真の場合、ログファイルのオープンは最初の @code{emit()} が呼び出されるまで延期されます。 (Contributed by Vinay Sajip.)

@code{TimedRotatingFileHandler} ではコンストラクタに `utc' パラメータも取るようになっています。これが真の場合、 @code{when='midnight'} などの切り替え時刻判定とその生成ファイル名に UTC が使われます。

@item 
いくつかの新しい関数が @ref{92,,math} モジュールに追加されました:


@itemize *

@item 
@ref{15ea,,isinf()} と @ref{15eb,,isnan()} は与えられた浮動小数点数が、順に、(正または負の) 無限大であるかどうか、非数 (NaN=Not a Number) であるかどうかを返します。

@item 
@ref{15ec,,copysign()} は IEEE 754 数の符号ビットをコピーします。 `x' の絶対値と `y' の符号ビットを組み合わせたものを返します。例えば @code{math.copysign(1, -0.0)} は -1.0 を返します。 (Contributed by Christian Heimes.)

@item 
@ref{b41,,factorial()} は階乗を計算します。 (Contributed by Raymond Hettinger; bpo-2138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2138}.)

@item 
@ref{15ed,,fsum()} はイテラブルからの数列を、部分和の計算を通じて精度の損失を避けながら積み上げた合計の計算をします。 (Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson; bpo-2819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2819}.)

@item 
@ref{15ee,,acosh()}, @ref{15ef,,asinh()}, @ref{15f0,,atanh()} は逆双曲線関数を計算します。

@item 
@ref{15f1,,log1p()} は `1+x'  の自然対数 (底 `e' の対数) を返します。

@item 
@code{trunc()} はゼロに向かう方向に丸めを行い、与えられた引数とゼロに最も近い @code{Integral} を返します。これは @ref{14d5,,PEP 3141; 数値の型階層} のバックポートの一部として追加されました。
@end itemize

@item 
@ref{92,,math} モジュールは、特に浮動小数点例外と IEEE 754 の特殊値の処理において、プラットフォーム間に渡る振る舞いの一貫性をさらに高めるように改善されました。

可能な場合にはいつでもこのモジュールは 754 の特殊値について、C99 標準の勧告に従います。例えば、 @code{sqrt(-1.)} は今ではほとんど全てのプラットフォームで @ref{2ec,,ValueError} となるはずで、 @code{sqrt(float('NaN'))} は全ての IEEE 754 プラットフォームで NaN を返すはずです。C99 標準の付録 'F' で 'divide-by-zero' または 'invalid' を伝えることを勧告している箇所では Python は @ref{2ec,,ValueError} を投げます。C99 標準の付録 'F' で 'overflow' を伝えることを勧告している箇所では Python は @ref{a81,,OverflowError} を投げます。 (See bpo-711019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=711019} and bpo-1640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1640}.)

(Contributed by Christian Heimes and Mark Dickinson.)

@item 
@ref{519,,mmap} オブジェクトに @code{rfind()} メソッドが追加されています。部分文字列の検索を、末尾から後ろ向きに検索します。 @code{find()} には新しい引数 `end' パラメータが追加されていて、検索対象の終了位置を指定することが出来ます。 (Contributed by John Lenton.)

@item 
@ref{a3,,operator} モジュールに @code{methodcaller()} 関数が追加されています。名前と省略可能な引数を与えると、渡したその任意の引数でその名前の関数を呼び出す呼び出し可能オブジェクトを返します。例えば:

@example
>>> # Equivalent to lambda s: s.replace('old', 'new')
>>> replacer = operator.methodcaller('replace', 'old', 'new')
>>> replacer('old wine in old bottles')
'new wine in new bottles'
@end example

(Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)

@code{attrgetter()} 関数がドット付きの名前を受け付け、対応する属性ルックアップをするようになりました:

@example
>>> inst_name = operator.attrgetter(
...        '__class__.__name__')
>>> inst_name('@w{'})
'str'
>>> inst_name(help)
'_Helper'
@end example

(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)

@item 
@ref{a5,,os} モジュールがいくつか新しくシステムコールをラップしています。開いたファイルについて、 @code{fchmod(fd, mode)} はモードを変更し、 @code{fchown(fd, uid, gid)} は所有権を変更し、 @code{lchmod(path, mode)} はシンボリックリンクのモードを変更します。 (Contributed by Georg Brandl and Christian Heimes.)

@code{chflags()} と @code{lchflags()} は対応するシステムコール (利用可能であれば) へのラッパーで、ファイルのフラグを変更します。そのフラグ値についての定数が @ref{d6,,stat} モジュールに定義されています; いくつかの取りうる値には、ファイルが変更されるべきではないことを伝える @code{UF_IMMUTABLE} 、ファイルにはデータの追記のみが可能であることを伝える @code{UF_APPEND} 、があります。 (Contributed by M. Levinson.)

@code{os.closerange(low, high)} は効率よく全ての `low' から `high' のファイルデスクリプタをクローズします。全てのエラーは無視されます。それと `high' はクローズ対象ではないです。この関数は既に @ref{dc,,subprocess} モジュールがプロセスを開始するのを高速化するために使われています。 (Contributed by Georg Brandl; bpo-1663329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1663329}.)

@item 
@code{os.environ} オブジェクトの @code{clear()} メソッドが、オブジェクトのキーから取り除くだけでなく @ref{25c,,os.unsetenv()} を使って環境変数を未設定にするようになりました。  (Contributed by Martin Horcicka; bpo-1181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1181}.)

@item 
@ref{6d0,,os.walk()} 関数に @code{followlinks} パラメータが追加されています。これを真にすると、シンボリックリンクが指す相手のディレクトリを渡り歩くようになります。後方互換のためにこのパラメータのデフォルトは偽です。なお、親ディレクトリを指すシンボリックリンクなど参照が循環していると、無限再帰に陥りますので注意してください。 (bpo-1273829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1273829})

@item 
@ref{a6,,os.path} モジュールの @code{splitext()} 関数が、先行するピリオドで分割しないように変更されています。これにより Unix のドットファイルの処理結果がよくなります。例えば @code{os.path.splitext('.ipython')} は @code{('@w{'}, '.ipython')} ではなく @code{('.ipython', '@w{'})} を返すようになっています。 (bpo-1115886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1115886})

新規関数 @code{os.path.relpath(path, start='.')} は、与えられれば @code{start} からの、与えられなければカレントディレクトリからの、目的地 @code{path} への相対パスを返します。 (Contributed by Richard Barran; bpo-1339796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1339796}.)

Windows において、 @ref{15f2,,os.path.expandvars()} が "%var%" 形式の記述に環境変数を展開し、 "~user" にユーザのホームディレクトリのパスを展開するようになりました。 (Contributed by Josiah Carlson; bpo-957650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=957650}.) (---訳注: "~user" は実在した仕様かわかりません。2.7 に該当する実装もコメントも docstring もリファレンスもありませんし、当然この振る舞いは現在実在していません。---)

@item 
@ref{aa,,pdb} モジュールで提供される Python デバッガに新たなコマンドが追加されました: "run" はデバッグ対象の Python プログラムを再起動します。またオプションとして、対象プログラムに与えるコマンドライン引数を渡せます。 (Contributed by Rocky Bernstein; bpo-1393667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1393667}.)

@item 
トレースバックのデバッグを開始するのに使われる @ref{15f3,,pdb.post_mortem()} が、トレースバックが与えられない場合に @ref{89a,,sys.exc_info()} からの戻り値のトレースバックを使うようになりました。 (Contributed by Facundo Batista; bpo-1106316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1106316}.)

@item 
@ref{ac,,pickletools} モジュールに @code{optimize()} 関数が追加されました。これは pickle を含んだ文字列を受け取って、未使用 opcode を削除の上で同じデータ構造を含んだより小さい pickle を返します。 (Contributed by Raymond Hettinger.)

@item 
@ref{ae,,pkgutil} モジュールに @code{get_data()} 関数が追加されました。これはインストールされている Python パッケージに含まれるリソースファイルの内容を返します。例えば:

@example
>>> import pkgutil
>>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
 ...
@end example

(Contributed by Paul Moore; bpo-2439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2439}.)

@item 
@code{pyexpat} モジュールの @code{Parser} オブジェクトで、 @code{buffer_size} 属性の設定により文字データの保持に使うバッファのサイズを変更出来るようになりました。 (Contributed by Achim Gaedke; bpo-1137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1137}.)

@item 
@code{Queue} モジュールが、エントリを違った順序で取り出すような queue の変種をサポートするようになっています。 @code{PriorityQueue} クラスはキューアイテムをヒープで格納し、それを優先順で取り出します。 @code{LifoQueue} クラスは、最後にエントリに追加されたものを最初に取り出します。つまり stack のように振舞うということです。 (Contributed by Raymond Hettinger.)

@item 
@ref{bd,,random} モジュールの @code{Random} が、今では 32 ビットシステムで pickle 出来、64 ビットシステムで unpickle 出来、逆も出来ます。残念ながらこの変更は Python 2.6 の @code{Random} オブジェクトを以前の Python で正しく unpickle 出来ないことを意味します。 (Contributed by Shawn Ligocki; bpo-1727780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1727780}.)

新たな @code{triangular(low, high, mode)} は、三角分布 (triangular distribution) に従う乱数を生成します。 `mode' は分布内の最頻値で、返却値は `high' を含まない `low' と `high' の間です。 (Contributed by Wladmir van der Laan and Raymond Hettinger; bpo-1681432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1681432}.)

@item 
@ref{be,,re} モジュールによって実行される長い正規表現検索が届けられるシグナルをチェックするようになり、これにより多大な時間を要する検索を中断出来るようになります。 (Contributed by Josh Hoyt and Ralf Schmitt; bpo-846388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=846388}.) (---訳注: 原文を忠実に訳すとわかりにくいですが、単に C のレベルでシグナルハンドラを仕掛けたので Python が割り込める、というのがここで言っていることです。本質的には「長い」や「時間のかかる」はあまり関係ないです。---)

正規表現モジュールは、小さな正規表現固有仮想マシン用のバイトコードをコンパイルすることで実装されています。信頼出来ないコードにより、悪意あるバイトコード文字列を直接作って破滅させることが出来ます。ですので、2.6 では正規表現バイトコードの検証をするようにしてあります。(Contributed by Guido van Rossum from work for Google App Engine; bpo-3487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3487}.)

@item 
The @ref{c2,,rlcompleter} module's @code{Completer.complete()} method
will now ignore exceptions triggered while evaluating a name.
(Fixed by Lorenz Quack; bpo-2250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2250}.)

@item 
@ref{c4,,sched} モジュールの @code{scheduler} インスタンスが読み出し専用の @ref{bb,,queue} 属性を持つようになりました。これはスケジューラのキュー内容を名前付きタプル @code{(time, priority, action, argument)} で返します。 (Contributed by Raymond Hettinger; bpo-1861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1861}.)

@item 
The @ref{c6,,select} module now has wrapper functions
for the Linux @code{epoll()} and BSD @code{kqueue()} system calls.
@code{modify()} method was added to the existing @code{poll}
objects; @code{pollobj.modify(fd, eventmask)} takes a file descriptor
or file object and an event mask, modifying the recorded event mask
for that file.
(Contributed by Christian Heimes; bpo-1657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1657}.)

@item 
@ref{c1e,,shutil.copytree()} が省略可能引数 `ignore' を取るようになっています。呼び出し可能オブジェクトを渡します。この呼び出し可能オブジェクトはそれぞれのディレクトリパスとその内容リストを受け取って、コピーせずに無視したい名前のリストを返します。

@ref{ca,,shutil} モジュールでは同時に、この新たなパラメータのために使える @code{ignore_patterns()} も提供しています。 @code{ignore_patterns()} は任意の数の glob スタイルのパターンを取り、これらパターンに合致する任意のファイルとディレクトリを無視する呼び出し可能オブジェクトを返します。以下は、 @code{.svn} ディレクトリと '~' で終わるファイル名を持つ Emacs のバックアップファイルをスキップしてディレクトリコピーをする例です:

@example
shutil.copytree('Doc/library', '/tmp/library',
                ignore=shutil.ignore_patterns('*~', '.svn'))
@end example

(Contributed by Tarek Ziadé; bpo-2663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2663}.)

@item 
Tkinter や GTK+ などのような場所で、シグナルハンドリングと GUI 処理のイベントループを組み合わせることは、長い間悩みの種でした; ほとんどのソフトウェアはポーリングを行って、わずかばかりの時間で起き上がっては GUI イベントが起きていないかチェックするハメになっています。 @ref{cb,,signal} モジュールが、これをより効率的に行えるようにしました。 @code{signal.set_wakeup_fd(fd)} でファイルデスクリプタをセットすると、イベント受信時にファイルデスクリプタにバイトが書き込まれます。 C レベルの関数 @ref{15f4,,PySignal_SetWakeupFd()} もあります。同じくファイルデスクリプタを渡します。

Event loops will use this by opening a pipe to create two descriptors,
one for reading and one for writing.  The writable descriptor
will be passed to @code{set_wakeup_fd()}, and the readable descriptor
will be added to the list of descriptors monitored by the event loop via
@code{select()} or @code{poll()}.
On receiving a signal, a byte will be written and the main event loop
will be woken up, avoiding the need to poll.

(Contributed by Adam Olsen; bpo-1583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1583}.)

@code{siginterrupt()} 関数が Python コードから利用可能になりました。対象シグナルがシステムコールを中断出来るかどうかを変更出来ます。 (Contributed by Ralf Schmitt.)

@code{setitimer()}, @code{getitimer()} 関数も追加されています (利用可能であれば)。 @code{setitimer()} は、指定時間経過後に処理にシグナルを届けます。時間は「壁時計時間 (wall-clock time)」(訳注: リファレンスでは「実時間」と表現している)、「プロセスの実行時間 (consumed process time)」、またはプロセス + システム時間の組合せで指定します。(Contributed by Guilherme Polo; bpo-2240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2240}.)

@item 
@ref{cf,,smtplib} モジュールが、 @code{SMTP_SSL} クラスの追加によって SMTP over SSL をサポートするようになっています。このクラスは既存の @code{SMTP} と同じインターフェイスです。(Contributed by Monty Taylor.)   両方のクラスのコンストラクタでは新たに省略可能な @code{timeout} パラメータを取ります。最初に接続を試みる際のタイムアウト値を秒で指定します。(Contributed by Facundo Batista.)

LMTP プロトコル (
@geindex RFC; RFC 2033
RFC 2033@footnote{https://datatracker.ietf.org/doc/html/rfc2033.html}) 実装もモジュールに追加されています。LMTP はメールキューを管理しないエージェント間で e-mail を転送する際に、SMTP の代わりに使われます。(LMTP implemented by Leif Hedstrom; bpo-957003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=957003}.)

@code{SMTP.starttls()} は今や 
@geindex RFC; RFC 3207
RFC 3207@footnote{https://datatracker.ietf.org/doc/html/rfc3207.html} 遵守であり、TLS ネゴシエーション自身で得たのでないサーバから得られるいかなる知識も記憶しません。(Patch contributed by Bill Fenner; bpo-829951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=829951}.)

@item 
The @ref{d1,,socket} module now supports TIPC (@indicateurl{https://tipc.sourceforge.net/}),
a high-performance non-IP-based protocol designed for use in clustered
environments.  TIPC addresses are 4- or 5-tuples.
(Contributed by Alberto Bertogli; bpo-1646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1646}.)

新規の @code{create_connection()} 関数はアドレスを取り、省略可能なタイムアウト値を使って接続を行い、接続されたソケットオブジェクトを返します。この関数は同時に、アドレスのタイプを調べて IPv4 と IPv6 の相応しい方を使って接続します。あなたのコードが @code{socket(socket.AF_INET, ...)} を使う代わりに @code{create_connection()} に乗り換えることは、それが IPv6 対応で必要なこと全て、となるでしょう。

@item 
The base classes in the @ref{d2,,SocketServer} module now support
calling a @ref{1539,,handle_timeout()} method after a span of inactivity
specified by the server's @ref{1538,,timeout} attribute.  (Contributed
by Michael Pomraning.)  The @ref{1357,,serve_forever()} method
now takes an optional poll interval measured in seconds,
controlling how often the server will check for a shutdown request.
(Contributed by Pedro Werneck and Jeffrey Yasskin;
bpo-742598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=742598}, bpo-1193577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1193577}.)

@item 
Gerhard Häring により保守されている @ref{d4,,sqlite3} モジュールが、Python 2.5 時のバージョン 2.3.2 からバージョン 2.4.1 に更新されました。

@item 
The @ref{db,,struct} module now supports the C99 _Bool type,
using the format character @code{'?'}.
(Contributed by David Remahl.)

@item 
The @ref{4b7,,Popen} objects provided by the @ref{dc,,subprocess} module
now have @ref{15f5,,terminate()}, @ref{15f6,,kill()}, and @ref{15f7,,send_signal()} methods.
On Windows, @code{send_signal()} only supports the @ref{15f8,,SIGTERM}
signal, and all these methods are aliases for the Win32 API function
@code{TerminateProcess()}.
(Contributed by Christian Heimes.)

@item 
@ref{df,,sys} モジュールに新たに追加された変数 @code{float_info} は、 @code{float.h} に由来するプラットフォームの浮動小数点数サポートについての情報を含んだオブジェクトです。このオブジェクトの属性としては、 @code{mant_dig} (仮数部の桁数)、 @code{epsilon} (1.0 と、それより大きい表現可能な最小値との差)などがあります。 (Contributed by Christian Heimes; bpo-1534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1534}.)

もう一つの新たな変数 @code{dont_write_bytecode} は Python がモジュールインポート時に @code{.pyc} や @code{.pyo} を作るかどうかを制御します。この変数が真ならば、コンパイル済みファイルは作られません。この変数は Python インタプリタを @ref{15e6,,-B} スイッチ付きで起動するか環境変数 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@ref{15e7,,PYTHONDONTWRITEBYTECODE} をセットすることで初期設定されます。Python コードはこのあとでこの変数の値を変更することで、バイトコードファイルを作るかどうかを制御出来ます。 (Contributed by Neal Norwitz and Georg Brandl.)

Python インタプリタに与えられたコマンドライン引数についての情報を、 @code{sys.flags} として利用可能な名前付きタプルで知ることが出来ます。例えば Python が冗長モードで起動された場合は @code{verbose} 属性は真となり、デバッグモードでは @code{debug} 属性が真、などです。これら属性は全て読み出し専用です。 (Contributed by Christian Heimes.)

新しい関数 @code{getsizeof()} が追加されました。 Python オブジェクトを受け取り、そのオブジェクトが利用しているメモリサイズをバイト単位で返します。
ビルトインオブジェクトは正確な結果を返しますが、サードパーティの拡張は正確な値を返さないかもしれません。
その場合 @code{__sizeof__()} メソッドを定義してオブジェクトのサイズを返すことができます。 (Robert Schuppenies による貢献. bpo-2898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2898})

現在動作中のプロファイラとトレーサーを、 @ref{15f9,,sys.getprofile()} と @ref{15fa,,sys.gettrace()} で知ることが出来るようになりました。 (Contributed by Georg Brandl; bpo-1648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1648}.)

@item 
@ref{e4,,tarfile} モジュールが、既にサポートされている POSIX.1-1988 (ustar) と GNU tar フォーマットに加えて、POSIX.1-2001 (pax) をサポートするようになりました。デフォルトは GNU tar です; これと違うフォーマットでファイルを開くには @code{format} パラメータで指定します:

@example
tar = tarfile.open("output.tar", "w",
                   format=tarfile.PAX_FORMAT)
@end example

新しい @code{encoding} と @code{errors} パラメータはエンコーディングと文字変換のエラー処理方法を指定します。 @code{'strict'}, @code{'ignore'},  @code{'replace'} は Python の 3 つの標準エラー処理です; @code{'utf-8'} は特殊で、不正な文字を、それの UTF-8 表現に置き換えます。(文字変換は、PAX フォーマットが Unicode ファイル名をサポートするために現れ、デフォルトは UTF-8 エンコーディングです。)

The @code{TarFile.add()} method now accepts an @code{exclude} argument that's
a function that can be used to exclude certain filenames from
an archive.
The function must take a filename and return true if the file
should be excluded or false if it should be archived.
The function is applied to both the name initially passed to @code{add()}
and to the names of files in recursively added directories.

(All changes contributed by Lars Gustäbel).

@item 
An optional @code{timeout} parameter was added to the
@code{telnetlib.Telnet} class constructor, specifying a timeout
measured in seconds.  (Added by Facundo Batista.)

@item 
@ref{6ed,,tempfile.NamedTemporaryFile} クラスは普通はこれが作った一時ファイルを、ファイルクローズ時に削除します。この振る舞いを、コンストラクタのパラメータに @code{delete=False} を渡すことで変更出来るようになりました。 (Contributed by Damien Miller; bpo-1537850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1537850}.)

新しいクラス @code{SpooledTemporaryFile} は一時ファイルのように振舞いますが、そのデータは最大サイズを超えるまではメモリ内に格納されます。その制限を超えると、その内容がディスク上の一時ファイルに書き込まれます。 (Contributed by Dustin J. Mitchell.)

@code{NamedTemporaryFile} と @code{SpooledTemporaryFile} のともにコンテキストマネージャとして動作しますので、 @code{with tempfile.NamedTemporaryFile() as tmp: ...} のように書くことが出来ます。 (Contributed by Alexander Belopolsky; bpo-2021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2021}.)

@item 
The @ref{ea,,test.test_support} module gained a number
of context managers useful for writing tests.
@ref{15fb,,EnvironmentVarGuard()} is a
context manager that temporarily changes environment variables and
automatically restores them to their old values.

もう一つのコンテキストマネージャ @code{TransientResource} は、利用出来るかもしれないし出来ないかもしれないリソースの呼び出しを包むことが出来ます; 指定した例外リストを捕捉して無視します(---訳注: この紹介、良くないと思うのと、多分著者が誤解してます。確かに属性名/属性値を特定してこれに一致する場合にだけ例外を受け取るためのものなので、一致しないものは無視、という事実には反しませんが、「狙った例外は受け取る(ResourceDenied)」でもあるはずです。「期待した例外が発生する」ことをテストしたいでしょう、「期待しない例外はテストには関係ない」であるとともに。それとリファレンスと docstring によれば「指定した例外と属性に合致する場合に ResourceDenied」と言っているので、やはり事実とは反しています。---)。例えば、ネットワークのテストでは外部のウェブサイトとの接続時の特定の失敗を無視するでしょう:

@example
with test_support.TransientResource(IOError,
                                errno=errno.ETIMEDOUT):
    f = urllib.urlopen('https://sf.net')
    ...
@end example

最後に、 @code{check_warnings()} は @code{warning} モジュールの警告フィルタをリセットして、全ての引き起こされる警告メッセージを記録するオブジェクトを返します (bpo-3781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3781}):

@example
with test_support.check_warnings() as wrec:
    warnings.simplefilter("always")
    # ... code that triggers a warning ...
    assert str(wrec.message) == "function is outdated"
    assert len(wrec.warnings) == 1, "Multiple warnings raised"
@end example

(Contributed by Brett Cannon.)

@item 
The @ref{f2,,textwrap} module can now preserve existing whitespace
at the beginnings and ends of the newly created lines
by specifying @code{drop_whitespace=False}
as an argument:

@example
>>> S = """This  sentence  has a bunch   of
...   extra   whitespace."""
>>> print textwrap.fill(S, width=15)
This  sentence
has a bunch
of    extra
whitespace.
>>> print textwrap.fill(S, drop_whitespace=False, width=15)
This  sentence
  has a bunch
   of    extra
   whitespace.
>>>
@end example

(Contributed by Dwayne Bailey; bpo-1581073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1581073}.)

@item 
@ref{f3,,threading} モジュールの API が、 @code{setDaemon()}, @code{isDaemon()} メソッドではなく @code{daemon} のようにプロパティを使うように変更中です。また、いくつかのメソッドはキャメルケースではなくアンダースコアスタイルに名前変更されています; 例えば @code{activeCount()} メソッドは @code{active_count()} にリネームされます。2.6 と 3.0 の両バージョンのモジュールは同じプロパティとリネームされたメソッドをサポートしますが、古いメソッドは削除されません。古い API が Python 3.x で撤廃するのがいつになるのかは未定です; 2.x バージョンでは削除されないでしょう。 (Carried out by several people, most notably Benjamin Peterson.) (--- 訳注: 3.5 でもこの状態は続いたままです。今でもキャメルケーススタイルのメソッドが使えます。ですが、もちろん新しい名前を使うべきです。---)

@ref{f3,,threading} モジュールの @code{Thread} オブジェクトに @code{ident} プロパティが追加されています。スレッドの識別子を非ゼロの整数で返します。 (Contributed by Gregory P. Smith; bpo-2871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2871}.)

@item 
@ref{f5,,timeit} モジュールが、計測されるステートメントとセットアップコードとして、文字列だけでなく呼び出し可能オブジェクトを渡せるようになりました。 @code{Timer} インスタンスを作成する 2 つの便利関数が追加されています: @code{repeat(stmt, setup, time, repeat, number)} と @code{timeit(stmt, setup, time, number)} で、インスタンスを作成して対応するメソッドを呼びます。 (Contributed by Erik Demaine; bpo-1533909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1533909}.)

@item 
@code{Tkinter} モジュールが、オプションとしてリストとタプルを受け付けるようになっています。Tcl/Tk へは空白区切りの文字列にして渡されます。 (Contributed by Guilherme Polo; bpo-2906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2906}.)

@item 
タートルグラフィックスのための @ref{107,,turtle} モジュールが Gregor Lingl により大幅に拡張されました。
モジュールの新しい機能は次の通りです:


@itemize *

@item 
亀の移動と回転のアニメーションの改善。

@item 
新しい @code{delay()} メソッド、 @code{tracer()} メソッド、 @code{speed()} メソッドを使って亀の動きをコントロールできるようになりました。

@item 
亀に新しい姿を設定できたり、新しい座標系を定義できるようになりました。

@item 
Turtles now have an @code{undo()} method that can roll back actions.

@item 
マウスやキーボードからの入力イベントに反応するための簡易なサポートが入り、簡単なゲームを書けるようになりました。

@item 
@code{turtle.cfg} を使って、turtle の画面の起動時の見た目をカスタマイズできるようになりました。

@item 
モジュールの docstring が、他の言語に翻訳された docstring に置き換えられるようになりました。
@end itemize

(bpo-1513695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1513695})

@item 
An optional @code{timeout} parameter was added to the
@ref{307,,urllib.urlopen} function and the
@code{urllib.ftpwrapper} class constructor, as well as the
@ref{307,,urllib2.urlopen} function.  The parameter specifies a timeout
measured in seconds.   For example:

@example
>>> u = urllib2.urlopen("http://slow.example.com",
                        timeout=3)
Traceback (most recent call last):
  ...
urllib2.URLError: <urlopen error timed out>
>>>
@end example

(Added by Facundo Batista.)

@item 
@ref{10b,,unicodedata} モジュールで提供される Unicode データベースが、バージョン 5.1.0 に更新されました。 (Updated by Martin von Löwis; bpo-3811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3811}.)

@item 
@ref{118,,warnings} モジュールの @code{formatwarning()} と @code{showwarning()} に省略可能な `line' 引数が追加されました。ソースコードの行番号を与えることが出来ます。 (Added as part of bpo-1631171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1631171}, which re-implemented part of the @ref{118,,warnings} module in C code.)

新しい関数 @code{catch_warnings()} はコンテキストマネージャで、テスト目的で警告フィルタを一時的に変更して元に戻すのに使えます。 (bpo-3781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3781}).

@item 
The XML-RPC @ref{135,,SimpleXMLRPCServer} and @ref{135,,DocXMLRPCServer}
classes can now be prevented from immediately opening and binding to
their socket by passing @code{False} as the `bind_and_activate'
constructor parameter.  This can be used to modify the instance's
@code{allow_reuse_address} attribute before calling the
@code{server_bind()} and @code{server_activate()} methods to
open the socket and begin listening for connections.
(Contributed by Peter Parente; bpo-1599845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1599845}.)

@code{SimpleXMLRPCServer} はさらに @code{_send_traceback_header} 属性を持つようになりました。真の場合、例外とフォーマットされたトレースバックが HTTP ヘッダ "X-Exception" と "X-Traceback" として返ります。この機能はデバッグのみに使い、製品のサーバには使ってはなりません。トレースバックには剥き出しのパスワードが含まれるかもしれず、あるいはほかの何か企業秘密だったり国家秘密だったりするような繊細な情報満載かもしれないのです。 (Contributed by Alan McIntyre as part of his project for Google's Summer of Code 2007.)

@item 
The @ref{134,,xmlrpclib} module no longer automatically converts
@ref{1fa,,datetime.date} and @ref{1fb,,datetime.time} to the
@ref{15fc,,xmlrpclib.DateTime} type; the conversion semantics were
not necessarily correct for all applications.  Code using
@code{xmlrpclib} should convert @code{date} and @ref{1fb,,time}
instances. (bpo-1330538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1330538})  The code can also handle
dates before 1900 (contributed by Ralf Schmitt; bpo-2014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2014})
and 64-bit integers represented by using @code{<i8>} in XML-RPC responses
(contributed by Riku Lindblad; bpo-2985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2985}).

@item 
@ref{137,,zipfile} モジュールの @code{ZipFile} クラスに @code{extract()} メソッドと @code{extractall()} メソッドが追加されました。アーカイブ内の、それぞれ単一ファイル、全てのファイルを、カレントディレクトリか指定のディレクトリに展開します:

@example
z = zipfile.ZipFile('python-251.zip')

# Unpack a single file, writing it relative
# to the /tmp directory.
z.extract('Python/sysmodule.c', '/tmp')

# Unpack all the files in the archive.
z.extractall()
@end example

(Contributed by Alan McIntyre; bpo-467924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=467924}.)

@ref{316,,open()}, @code{read()}, @code{extract()} メソッドはファイル名か @code{ZipInfo} オブジェクトのどちらかを受け取れるようになっています。これは誤って重複したファイル名を含んでいるアーカイブで有用でしょう。 (Contributed by Graham Horler; bpo-1775025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1775025}.)

最後に、 @ref{137,,zipfile} がアーカイブするファイルのファイル名として Unicode の使用をサポートするようになりました。  (Contributed by Alexey Borzenkov; bpo-1734346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1734346}.)  (---訳注: リファレンスに注意事項として書かれていますが、zip ファイルのファイル名標準は存在しないのでこれは問題を起こすことがあります。---)
@end itemize

@c ======================================================================

@c whole new modules get described in subsections here

@menu
* ast モジュール:: 
* The future_builtins module:: 
* json モジュール; JavaScript オブジェクト記法: json モジュール JavaScript オブジェクト記法. 
* plistlib モジュール; プロパティリストパーサ: plistlib モジュール プロパティリストパーサ. 
* ctypes の強化:: 
* SSL サポートの改善:: 

@end menu

@node ast モジュール,The future_builtins module,,新しいモジュールと改良されたモジュール<2>
@anchor{whatsnew/2 6 the-ast-module}@anchor{15fd}
@subsubsection @code{ast} モジュール


@ref{9,,ast} モジュールは Python コードの抽象構文木 (Abstract Syntax Tree) 表現を提供します。また、Armin Ronacher は共通タスクを実行するさまざまなヘルパー関数を寄稿しました。これらは HTML テンプレートパッケージであるとか、コードアナライザ、などなどの、Python コードを処理するツールで有用となるでしょう。

@code{parse()} 関数は式を受け取り AST を返します。 @code{dump()} 関数はツリー表現をデバッギングに相応しい出力をします:

@example
import ast

t = ast.parse("""
d = @{@}
for i in 'abcdefghijklm':
    d[i + i] = ord(i) - ord('a') + 1
print d
""")
print ast.dump(t)
@end example

これの出力は深くネストされたツリーです:

@example
Module(body=[
  Assign(targets=[
    Name(id='d', ctx=Store())
   ], value=Dict(keys=[], values=[]))
  For(target=Name(id='i', ctx=Store()),
      iter=Str(s='abcdefghijklm'), body=[
    Assign(targets=[
      Subscript(value=
        Name(id='d', ctx=Load()),
          slice=
          Index(value=
            BinOp(left=Name(id='i', ctx=Load()), op=Add(),
             right=Name(id='i', ctx=Load()))), ctx=Store())
     ], value=
     BinOp(left=
      BinOp(left=
       Call(func=
        Name(id='ord', ctx=Load()), args=[
          Name(id='i', ctx=Load())
         ], keywords=[], starargs=None, kwargs=None),
       op=Sub(), right=Call(func=
        Name(id='ord', ctx=Load()), args=[
          Str(s='a')
         ], keywords=[], starargs=None, kwargs=None)),
       op=Add(), right=Num(n=1)))
    ], orelse=[])
   Print(dest=None, values=[
     Name(id='d', ctx=Load())
   ], nl=True)
 ])
@end example

@code{literal_eval()} メソッドは、文字列またはリテラル式を表現する AST を受け取り解析と評価を行い、結果の値を返します。リテラル式は、文字列、数値、辞書などのみを含む Python 式で、文や関数呼び出しを含みません。もしもあなたに式を評価する必要があって、だけれども @ref{4a3,,eval()} を呼び出すことによるセキュリティリスクを許容出来ないということであれば、 @code{literal_eval()} がそれを安全に処理してくれます:

@example
>>> literal = '("a", "b", @{2:4, 3:8, 1:2@})'
>>> print ast.literal_eval(literal)
('a', 'b', @{1: 2, 2: 4, 3: 8@})
>>> print ast.literal_eval('"a" + "b"')
Traceback (most recent call last):
  ...
ValueError: malformed string
@end example

モジュールには、AST を横断し、修正するための @code{NodeVisitor} と @code{NodeTransformer} クラス、例えば行番号の変更などの共通的な変形を行う関数群が含まれています。

@c ======================================================================

@node The future_builtins module,json モジュール JavaScript オブジェクト記法,ast モジュール,新しいモジュールと改良されたモジュール<2>
@anchor{whatsnew/2 6 the-future-builtins-module}@anchor{15fe}
@subsubsection The @code{future_builtins} module


Python 3.0 makes many changes to the repertoire of built-in
functions, and most of the changes can't be introduced in the Python
2.x series because they would break compatibility.
The @code{future_builtins} module provides versions
of these built-in functions that can be imported when writing
3.0-compatible code.

このモジュールに今のところ含まれるのは:


@itemize *

@item 
@code{ascii(obj)}: 2.x の @ref{1c1,,repr()} と同じことをします。Python 3.0 では @ref{1c1,,repr()} は Unicode 文字列を返すようになっていて、一方 @ref{15ff,,ascii()} は純粋な ASCII バイト文字列を返します。

@item 
@code{filter(predicate, iterable)}, @code{map(func, iterable1, ...)}: 3.0 と同じようにイテレータを返し、これは 2.x のビルトインがリストで返すのとは違っています。

@item 
@code{hex(value)}, @code{oct(value)}: @code{__hex__()} と @code{__oct__()} メソッドを呼び出すのではなく、 @code{__index__()} メソッドを呼び出した結果を hexadecimal または octal に変換します。こちらのバージョンの @ref{14e6,,oct()} は新しい @code{0o} 記法で返却します。
@end itemize

@c ======================================================================

@node json モジュール JavaScript オブジェクト記法,plistlib モジュール プロパティリストパーサ,The future_builtins module,新しいモジュールと改良されたモジュール<2>
@anchor{whatsnew/2 6 the-json-module-javascript-object-notation}@anchor{1600}
@subsubsection @code{json} モジュール: JavaScript オブジェクト記法


新しい @ref{86,,json} モジュールは、JSON (Javascript Object Notation) と Python 型のエンコーディング、デコーディングをサポートします。JSON は軽量なデータ交換フォーマットで、頻繁にウェブアプリケーションで使われます。JSON の詳細情報は @indicateurl{http://www.json.org} にあります。

@ref{86,,json} モジュールはほとんどのビルトイン型のデコーディングとエンコーディングサポートを備えています。以下の例は辞書のエンコードとデコードをしています:

@example
>>> import json
>>> data = @{"spam": "foo", "parrot": 42@}
>>> in_json = json.dumps(data) # Encode the data
>>> in_json
'@{"parrot": 42, "spam": "foo"@}'
>>> json.loads(in_json) # Decode into a Python object
@{"spam": "foo", "parrot": 42@}
@end example

ほかの何か型をサポートするのに独自のエンコーダ、デコーダを書くことも出来ます。JSON 文字列の pretty-printing もサポートされています。

@ref{86,,json} (もともと simplejson と呼ばれていました) は Bob Ippolito によって書かれました。

@c ======================================================================

@node plistlib モジュール プロパティリストパーサ,ctypes の強化,json モジュール JavaScript オブジェクト記法,新しいモジュールと改良されたモジュール<2>
@anchor{whatsnew/2 6 the-plistlib-module-a-property-list-parser}@anchor{1601}
@subsubsection @code{plistlib} モジュール: プロパティリストパーサ


@code{.plist} フォーマットは Mac OS X で一般的に使われ、基本的なデータ型(数値、文字列、リスト、辞書)を XML ベースのフォーマットにシリアライズして格納します。データ型の XML-RPC シリアライズに似ています。

Mac OS X で主に使われるとはいえ、そのフォーマットはまったく Mac 固有ではなくその Python 実装は Python がサポートするあらゆるプラットフォームで動作するので、@ref{b0,,plistlib} は標準ライブラリに昇格しました。

モジュールを使うのは単純です:

@example
import sys
import plistlib
import datetime

# Create data structure
data_struct = dict(lastAccessed=datetime.datetime.now(),
                   version=1,
                   categories=('Personal','Shared','Private'))

# Create string containing XML.
plist_str = plistlib.writePlistToString(data_struct)
new_struct = plistlib.readPlistFromString(plist_str)
print data_struct
print new_struct

# Write data structure to a file and read it back.
plistlib.writePlist(data_struct, '/tmp/customizations.plist')
new_struct = plistlib.readPlist('/tmp/customizations.plist')

# read/writePlist accepts file-like objects as well as paths.
plistlib.writePlist(data_struct, sys.stdout)
@end example

@c ======================================================================

@node ctypes の強化,SSL サポートの改善,plistlib モジュール プロパティリストパーサ,新しいモジュールと改良されたモジュール<2>
@anchor{whatsnew/2 6 ctypes-enhancements}@anchor{1602}
@subsubsection ctypes の強化


Thomas Heller は @ref{2e,,ctypes} モジュールの保守と拡張を続けました。

@ref{2e,,ctypes} は今では C99 @code{bool} 型を表す @code{c_bool} データ型をサポートします。  (Contributed by David Remahl; bpo-1649190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1649190}.)

@ref{2e,,ctypes} の string, buffer, array 型が拡張スライスインデクス構文をサポートするように改善され、 @code{(start, stop, step)} の色々な組み合わせが使えます。 (Implemented by Thomas Wouters.)

@c Revision 57769

全ての @ref{2e,,ctypes} データ型が @code{from_buffer()}, @code{from_buffer_copy()} メソッドをサポートするようになりました。これは与えられた buffer オブジェクトに基く ctypes インスタンスを作ります。 @code{from_buffer_copy()} はそのオブジェクトの内容をコピーし、 @code{from_buffer()} はその同じメモリ領域を共有します。

新しい呼び出しの慣例は、 @ref{2e,,ctypes} にそれぞれのラップされた呼び出しの発生時に @code{errno} あるいは Win32 LastError 変数をクリアすることを伝えることです。 (Implemented by Thomas Heller; bpo-1798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1798}.)

Unix @code{errno} 変数を関数呼び出し後に抽出できるようになっています。ラップされた関数を作る際、 @code{use_errno=True} を @code{DLL()} 関数へのキーワード引数として渡すことが出来、それによりモジュールレベル関数の @code{set_errno()} と @code{get_errno()} を、 errno 値を設定・取得するのに呼び出せます。

Win32 LastError は @code{DLL()}, @code{OleDLL()}, @code{WinDLL()} 関数で同じようにサポートされています。同じように @code{use_last_error=True} を与え、モジュールレベル関数 @code{set_last_error()} と @code{get_last_error()} を使います。

ctypes インスタンスへのポインタを抽出にするのに使われる @code{byref()} 関数が、省略可能な `offset' パラメータを受け取るようになりました。これは返されるポインタに追加されるバイト数です。

@c ======================================================================

@node SSL サポートの改善,,ctypes の強化,新しいモジュールと改良されたモジュール<2>
@anchor{whatsnew/2 6 improved-ssl-support}@anchor{1603}
@subsubsection SSL サポートの改善


Bill Janssen は Python 2.6 の Secure Sockets Layer サポートを大掛かりに改善しました。行われたのは新モジュール @ref{d5,,ssl} の追加です。これは OpenSSL@footnote{https://www.openssl.org/} ライブラリの上に構築されています。この新しいモジュールはプロトコルのネゴシエイトのさらなる制御、X.509 証明書の使用、そして SSL サーバ (クライアントの対語としての) を Python で書くためのより良いサポートを提供しています。既存の @ref{d1,,socket} モジュールにある SSL サポートは削除されずにそのまま使えますが、Python 3.0 では削除されます。

この新たなモジュールを使うには、まず最初にいつものやり方で TCP コネクションを作らなければなりません。そしてその上でそれを @code{ssl.wrap_socket()} 関数に渡します (---訳注: 2.7.9 ではさらに進化した @code{SSLContext.wrap_socket} が使えます ---)。証明書が必要かどうかを指定することが出来、証明書の情報を @code{getpeercert()} メソッドで取得することも出来ます。


@subsubheading 参考


@ref{d5,,ssl} モジュールについてのドキュメント。


@c ======================================================================

@node 非推奨と削除,ビルドならびに C API の変更<9>,新しいモジュールと改良されたモジュール<2>,What's New in Python 2 6
@anchor{whatsnew/2 6 deprecations-and-removals}@anchor{1604}
@subsection 非推奨と削除



@itemize *

@item 
文字列を例外として送出することは出来なくなりました。これをすると @ref{198,,TypeError} を起こします。

@item 
Changes to the @ref{bcd,,Exception} interface
as dictated by 
@geindex Python Enhancement Proposals; PEP 352
PEP 352@footnote{https://peps.python.org/pep-0352/} continue to be made.  For 2.6,
the @code{message} attribute is being deprecated in favor of the
@ref{78d,,args} attribute.

@item 
(3.0 警告モード) Python 3.0 はたくさんの時代遅れのモジュールを削除し、ほかのものも名前変更するような標準ライブラリの再編成が特色となります。Python 2.6 を 3.0 警告モードで動かすと、それらがインポートされる際に警告が励起されます。

The list of deprecated modules is:
@code{audiodev},
@code{bgenlocations},
@code{buildtools},
@code{bundlebuilder},
@code{Canvas},
@code{compiler},
@code{dircache},
@code{dl},
@code{fpformat},
@code{gensuitemodule},
@code{ihooks},
@code{imageop},
@code{imgfile},
@code{linuxaudiodev},
@code{mhlib},
@code{mimetools},
@code{multifile},
@code{new},
@code{pure},
@code{statvfs},
@code{sunaudiodev},
@code{test.testall}, and
@code{toaiff}.

@item 
The @code{gopherlib} module has been removed.

@item 
The @code{MimeWriter} module and @code{mimify} module
have been deprecated; use the @ref{3f,,email}
package instead.

@item 
The @code{md5} module has been deprecated; use the @ref{6c,,hashlib} module
instead.

@item 
The @code{posixfile} module has been deprecated; @ref{1605,,fcntl.lockf()}
provides better locking.

@item 
The @code{popen2} module has been deprecated; use the @ref{dc,,subprocess}
module.

@item 
The @code{rgbimg} module has been removed.

@item 
The @code{sets} module has been deprecated; it's better to
use the built-in @ref{184,,set} and @ref{7f2,,frozenset} types.

@item 
The @code{sha} module has been deprecated; use the @ref{6c,,hashlib} module
instead.
@end itemize

@c ======================================================================

@node ビルドならびに C API の変更<9>,Python 2 6 への移植,非推奨と削除,What's New in Python 2 6
@anchor{whatsnew/2 6 build-and-c-api-changes}@anchor{1606}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
Python now must be compiled with C89 compilers (after 19
years!).  This means that the Python source tree has dropped its
own implementations of @code{memmove()} and @code{strerror()}, which
are in the C89 standard library.

@item 
Python 2.6 は Microsoft Visual Studio 2008 (version 9.0) でビルド出来ます。そしてこれが新しいデフォルトコンパイラです。 @code{PCbuild} ディレクトリのビルドファイルを参照して下さい。 (Implemented by Christian Heimes.)

@item 
Mac OS X では、Python 2.6 は 4 種類のユニバーサルビルドでコンパイル出来ます。 @code{configure} スクリプトは @code{--with-universal-archs=[32-bit|64-bit|all]} スイッチを取って、32-bit アーキテクチャ (x86, PowerPC), 64-bit (x86-64 and PPC-64), あるいは両方のバイナリをビルド出来ます。 (Contributed by Ronald Oussoren.)

@item 
A new function added in Python 2.6.6, @code{PySys_SetArgvEx()}, sets
the value of @code{sys.argv} and can optionally update @code{sys.path} to
include the directory containing the script named by @code{sys.argv[0]}
depending on the value of an `updatepath' parameter.

This function was added to close a security hole for applications
that embed Python.  The old function, @code{PySys_SetArgv()}, would
always update @code{sys.path}, and sometimes it would add the current
directory.  This meant that, if you ran an application embedding
Python in a directory controlled by someone else, attackers could
put a Trojan-horse module in the directory (say, a file named
@code{os.py}) that your application would then import and run.

If you maintain a C/C++ application that embeds Python, check
whether you're calling @code{PySys_SetArgv()} and carefully consider
whether the application should be using @code{PySys_SetArgvEx()}
with `updatepath' set to false.  Note that using this function will
break compatibility with Python versions 2.6.5 and earlier; if you
have to continue working with earlier versions, you can leave
the call to @code{PySys_SetArgv()} alone and call
@code{PyRun_SimpleString("sys.path.pop(0)\n")} afterwards to discard
the first @code{sys.path} component.

Security issue reported as 
@geindex Common Vulnerabilities and Exposures; CVE 2008-5983
CVE 2008-5983@footnote{https://www.cve.org/CVERecord?id=CVE-2008-5983};
discussed in gh-50003@footnote{https://github.com/python/cpython/issues/50003}, and fixed by Antoine Pitrou.

@item 
BerkeleyDB モジュールが C API オブジェクトを公開しています。 @code{bsddb.db.api} として利用可能です。このモジュールは @code{bsddb} モジュールを自身の独自の目的で使いたいほかの C 拡張で使えます。 (Contributed by Duncan Grisby.)

@item 
@ref{15ce,,PEP 3118 改訂版バッファプロトコル} で前述の新しいバッファインターフェイスのために、 @ref{63a,,PyObject_GetBuffer()} と @ref{63b,,PyBuffer_Release()} とほか少しの関数が追加されました。

@item 
Python's use of the C stdio library is now thread-safe, or at least
as thread-safe as the underlying library is.  A long-standing potential
bug occurred if one thread closed a file object while another thread
was reading from or writing to the object.  In 2.6 file objects
have a reference count, manipulated by the
@code{PyFile_IncUseCount()} and @code{PyFile_DecUseCount()}
functions.  File objects can't be closed unless the reference count
is zero.  @code{PyFile_IncUseCount()} should be called while the GIL
is still held, before carrying out an I/O operation using the
@code{FILE *} pointer, and @code{PyFile_DecUseCount()} should be called
immediately after the GIL is re-acquired.
(Contributed by Antoine Pitrou and Gregory P. Smith.)

@item 
異なるスレッドから同時にモジュールをインポートすることでデッドロックが発生することはなくなりました; 今では @ref{65b,,ImportError} になります。新たな API 関数 @ref{3db,,PyImport_ImportModuleNoBlock()} は最初に @code{sys.modules} を探し、インポートロック獲得後にインポートしようと試みます。インポートロックが他のスレッドにより獲得されていれば @ref{65b,,ImportError} が発生します。(Contributed by Christian Heimes.)

@item 
Several functions return information about the platform's
floating-point support.  @ref{1607,,PyFloat_GetMax()} returns
the maximum representable floating-point value,
and @ref{1608,,PyFloat_GetMin()} returns the minimum
positive value.  @ref{1609,,PyFloat_GetInfo()} returns an object
containing more information from the @code{float.h} file, such as
@code{"mant_dig"} (number of digits in the mantissa), @code{"epsilon"}
(smallest difference between 1.0 and the next largest value
representable), and several others.
(Contributed by Christian Heimes; bpo-1534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1534}.)

@item 
@ref{160a,,PyComplex_AsCComplex()} を使う C 関数とメソッドが @code{__complex__()} メソッドを持つ引数を受け付けるようになっています。特に、 @ref{19,,cmath} モジュールにある関数は、このメソッドを持つオブジェクトを受け付けます。これは Python 3.0 での変更のバックポートです。 (Contributed by Mark Dickinson; bpo-1675423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1675423}.)

@item 
Python C API に 2 つの大文字小文字を区別しない文字列比較関数 @code{PyOS_stricmp(char*, char*)} と @code{PyOS_strnicmp(char*, char*, Py_ssize_t)} が追加されました。 (Contributed by Christian Heimes; bpo-1635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635}.)

@item 
多くの C 拡張が、 @code{init*} 関数内でモジュール辞書に整数と文字列定数を追加するために独自の小さなマクロを定義しています。 Python 2.6 ではついにモジュールに値を追加する標準マクロを定義しました。 @ref{160b,,PyModule_AddStringMacro} と @ref{160c,,PyModule_AddIntMacro()} です。 (Contributed by Christian Heimes.)

@item 
Some macros were renamed in both 3.0 and 2.6 to make it clearer that
they are macros,
not functions.  @code{Py_Size()} became @ref{985,,Py_SIZE()},
@code{Py_Type()} became @ref{3c9,,Py_TYPE()}, and
@code{Py_Refcnt()} became @ref{2cf,,Py_REFCNT()}.
The mixed-case macros are still available
in Python 2.6 for backward compatibility.
(bpo-1629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1629})

@item 
Distutils は C 拡張を、デバッグバージョンの Python 実行時に別のディレクトリにビルドするようになりました。 (Contributed by Collin Winter; bpo-1530959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1530959}.)

@item 
いくつかの基本データ型、例えば数値や文字列型は、あとで再利用されるオブジェクトのフリーリスト(---訳注: メモリ管理での alloc/free の free。---)を内部的に管理しています。それらデータ構造はこのフリーリストに関して、命名規約に従うようにしました; その変数名は常に @code{free_list} 、カウンタは常に @code{numfree} 、そしてマクロ @code{Py<typename>_MAXFREELIST} が必ず定義されます。

@item 
新たに追加された Makefile のターゲット "make patchcheck" は、Python ソースツリーに対してパッチを作る準備をします: 修正された @code{.py} ファイル全てに含まれる末尾の余分な空白を取り除き、ドキュメンテーションが変更されているかをチェックし、そして @code{Misc/ACKS} と @code{Misc/NEWS} が更新されているかどうかを報告します。 (Contributed by Brett Cannon.)

もう一つの新しいターゲット "make profile-opt" は、GCC の profile-guided 最適化を使った Python バイナリをビルドします。これは Python をプロファイリングを有効にしてビルドし、プロファイル結果のセットを得るためのテストスイートを実施し、そして最適化のためにそれら結果を使ってビルドします。 (Contributed by Gregory P. Smith.)
@end itemize

@c ======================================================================

@menu
* ポート特有の変更; Windows: ポート特有の変更 Windows<2>. 
* ポート特有の変更; Mac OS X: ポート特有の変更 Mac OS X<2>. 
* ポート特有の変更; IRIX: ポート特有の変更 IRIX. 

@end menu

@node ポート特有の変更 Windows<2>,ポート特有の変更 Mac OS X<2>,,ビルドならびに C API の変更<9>
@anchor{whatsnew/2 6 port-specific-changes-windows}@anchor{160d}
@subsubsection ポート特有の変更: Windows



@itemize *

@item 
Windows 95, 98, ME, NT4 のサポートはとりやめられました。 Python 2.6 は最低でも Windows 2000 SP4 が必要です。

@item 
Windows での新しいデフォルトコンパイラが Visual Studio 2008 (version 9.0) になっています。Visual Studio 2003 (version 7.1) と 2005 (version 8.0) のビルドディレクトリは PC/ に移動しました。新しい @code{PCbuild} ディレクトリは X64, デバッグビルド、Profile Guided Optimization (PGO) をサポートしています。PGO ビルドは通常ビルドに較べておよそ 10% 高速化になります。 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and Martin von Löwis.)

@item 
The @ref{97,,msvcrt} module now supports
both the normal and wide char variants of the console I/O
API.  The @ref{160e,,getwch()} function reads a keypress and returns a Unicode
value, as does the @ref{160f,,getwche()} function.  The @ref{1610,,putwch()} function
takes a Unicode character and writes it to the console.
(Contributed by Christian Heimes.)

@item 
@ref{15f2,,os.path.expandvars()} は "%var%" 形式を環境変数で置換し、 "~user" をユーザのホームディレクトリパスに置換します(---訳注: 上のほうの訳注参照。---)。 (Contributed by Josiah Carlson; bpo-957650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=957650}.)

@item 
The @ref{d1,,socket} module's socket objects now have an
@ref{ece,,ioctl()} method that provides a limited interface to the
@code{WSAIoctl()} system interface.

@item 
The @ref{11c,,_winreg} module now has a function,
@ref{1611,,ExpandEnvironmentStrings()},
that expands environment variable references such as @code{%NAME%}
in an input string.  The handle objects provided by this
module now support the context protocol, so they can be used
in @ref{186,,with} statements. (Contributed by Christian Heimes.)

@ref{11c,,_winreg} also has better support for x64 systems,
exposing the @ref{157c,,DisableReflectionKey()}, @ref{157d,,EnableReflectionKey()},
and @ref{157e,,QueryReflectionKey()} functions, which enable and disable
registry reflection for 32-bit processes running on 64-bit systems.
(bpo-1753245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1753245})

@item 
The @code{msilib} module's @code{Record} object
gained @code{GetInteger()} and @code{GetString()} methods that
return field values as an integer or a string.
(Contributed by Floris Bruynooghe; bpo-2125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2125}.)
@end itemize

@c ======================================================================

@node ポート特有の変更 Mac OS X<2>,ポート特有の変更 IRIX,ポート特有の変更 Windows<2>,ビルドならびに C API の変更<9>
@anchor{whatsnew/2 6 port-specific-changes-mac-os-x}@anchor{1612}
@subsubsection ポート特有の変更: Mac OS X



@itemize *

@item 
Python をフレームワークビルドでコンパイルする際に、 @code{configure} スクリプトに @code{--with-framework-name} オプションでフレームワーク名を指定出来るようになりました。

@item 
The @code{macfs} module has been removed.  This in turn required the
@code{macostools.touched()} function to be removed because it depended on the
@code{macfs} module.  (bpo-1490190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1490190})

@item 
Many other Mac OS modules have been deprecated and will be removed in
Python 3.0:
@code{_builtinSuites},
@code{aepack},
@code{aetools},
@code{aetypes},
@code{applesingle},
@code{appletrawmain},
@code{appletrunner},
@code{argvemulator},
@code{Audio_mac},
@code{autoGIL},
@code{Carbon},
@code{cfmfile},
@code{CodeWarrior},
@code{ColorPicker},
@code{EasyDialogs},
@code{Explorer},
@code{Finder},
@code{FrameWork},
@code{findertools},
@code{ic},
@code{icglue},
@code{icopen},
@code{macerrors},
@code{MacOS},
@code{macfs},
@code{macostools},
@code{macresource},
@code{MiniAEFrame},
@code{Nav},
@code{Netscape},
@code{OSATerminology},
@code{pimp},
@code{PixMapWrapper},
@code{StdSuites},
@code{SystemEvents},
@code{Terminal}, and
@code{terminalcommand}.
@end itemize

@c ======================================================================

@node ポート特有の変更 IRIX,,ポート特有の変更 Mac OS X<2>,ビルドならびに C API の変更<9>
@anchor{whatsnew/2 6 port-specific-changes-irix}@anchor{1613}
@subsubsection ポート特有の変更: IRIX


A number of old IRIX-specific modules were deprecated and will
be removed in Python 3.0:
@code{al} and @code{AL},
@code{cd},
@code{cddb},
@code{cdplayer},
@code{CL} and @code{cl},
@code{DEVICE},
@code{ERRNO},
@code{FILE},
@code{FL} and @code{fl},
@code{flp},
@code{fm},
@code{GET},
@code{GLWS},
@code{GL} and @code{gl},
@code{IN},
@code{IOCTL},
@code{jpeg},
@code{panelparser},
@code{readcd},
@code{SV} and @code{sv},
@code{torgb},
@code{videoreader}, and
@code{WAIT}.

@c ======================================================================

@node Python 2 6 への移植,謝辞<2>,ビルドならびに C API の変更<9>,What's New in Python 2 6
@anchor{whatsnew/2 6 porting-to-python-2-6}@anchor{1614}
@subsection Python 2.6 への移植


このセクションでは前述の変更とバグフィックスにより必要となるかもしれないコードの変更を列挙します:


@itemize *

@item 
ハッシュ化をサポートしないクラスはその定義内でその事実を示すために、  @code{__hash__ = None} をセットすべきです。

@item 
文字列を例外として送出することは出来なくなりました。これをすると @ref{198,,TypeError} を起こします。

@item 
@ref{7f4,,collections.deque} の @code{__init__()} メソッドが、イテラブルから要素を追加する前に全ての deque の既存の内容をクリアするようになっています。この変更は @code{list.__init__()} の振る舞いと一致します(---訳注: 当たり前のことにしか思えないのですが詳細がわかりません。これ以前のバージョンでは deque はシングルトンのように振舞っていたのでしょうか。---)。

@item 
@ref{8bf,,object.__init__()} は以前は任意の引数とキーワード引数を受け取り、そして無視していました。Python 2.6 ではもうこれは許されません。 @ref{198,,TypeError} を起こします。これは結果的に @ref{c7e,,object} の対応するメソッドを呼ぶ(おそらく @ref{1a6,,super()} を介して) @code{__init__()} メソッドに影響します。 bpo-1683368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1683368} の議論を参照して下さい。

@item 
@code{Decimal} のコンストラクタは今では先頭と末尾の空白が含まれる文字列を許容します。以前は @code{InvalidOperation} となっていました。他方で、 @code{Context} オブジェクトの @code{create_decimal()} メソッドは余分な空白を明示的に拒絶するようになり、 @code{ConversionSyntax} を投げます。

@item 
実装上の誤り(事故)で、ビルトインの @ref{ad1,,__import__()} 関数にファイルパスを渡すと指定したファイルをインポート出来ていました。しかしながらこれは決して意図した振る舞いではありませんでした。実装は今ではこのケースを明示的にチェックし、 @ref{65b,,ImportError} を起こします。

@item 
C API: @ref{1615,,PyImport_Import()} と @ref{3dc,,PyImport_ImportModule()} 関数がデフォルトで、相対インポートではなく絶対インポートをするようになっています。これはほかのモジュールをインポートする C 拡張に影響します。

@item 
C API: ハッシュされるべきではない拡張データ型は、 @code{tp_hash} スロットを @ref{15e0,,PyObject_HashNotImplemented()} と定義すべきです。

@item 
@ref{d1,,socket} モジュールの例外 @ref{1261,,socket.error} が @ref{125e,,IOError} 派生になっています。以前は @code{StandardError} のサブクラスではありませんでしたが今は @ref{125e,,IOError} を通じてそれのサブクラスです。 (Implemented by Gregory P. Smith; bpo-1706815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1706815}.)

@item 
The @ref{134,,xmlrpclib} module no longer automatically converts
@ref{1fa,,datetime.date} and @ref{1fb,,datetime.time} to the
@ref{15fc,,xmlrpclib.DateTime} type; the conversion semantics were
not necessarily correct for all applications.  Code using
@code{xmlrpclib} should convert @code{date} and @ref{1fb,,time}
instances. (bpo-1330538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1330538})

@item 
(3.0 警告モード) @ref{bcd,,Exception} クラスはスライスやインデクスアクセスで警告を出します; @ref{bcd,,Exception} のタプルのような振る舞いはのちに取り除かれます。

@item 
(3.0 警告モード) 2 つの辞書や 2 つの比較メソッドを実装しないオブジェクトの不等号比較は警告されます。 @code{dict1 == dict2} はまだ動作しますが、 @code{dict1 < dict2} はのちに取り除かれます。

Python のスコープルールの実装の詳細であるセル間の比較も、警告を引き起こします。なぜならこれは、3.0 ではそのような比較は完全に禁止されているからです。
@end itemize

Python を埋め込んだアプリケーションでは:


@itemize *

@item 
The @code{PySys_SetArgvEx()} function was added in Python 2.6.6,
letting applications close a security hole when the existing
@code{PySys_SetArgv()} function was used.  Check whether you're
calling @code{PySys_SetArgv()} and carefully consider whether the
application should be using @code{PySys_SetArgvEx()} with
`updatepath' set to false.
@end itemize

@c ======================================================================

@node 謝辞<2>,,Python 2 6 への移植,What's New in Python 2 6
@anchor{whatsnew/2 6 acknowledgements}@anchor{1616}@anchor{whatsnew/2 6 acks}@anchor{1617}
@subsection 謝辞


著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の人々に感謝します:  Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, Antoine Pitrou, Brian Warner.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 5,What's New in Python 2 4,What's New in Python 2 6,What's New in Python
@anchor{whatsnew/2 5 doc}@anchor{1618}@anchor{whatsnew/2 5 translation-repo}@anchor{1619}@anchor{whatsnew/2 5 what-s-new-in-python-2-5}@anchor{161a}
@section What's New in Python 2.5


@*著者: 
A.M. Kuchling


@c $Id: whatsnew25.tex 56611 2007-07-29 08:26:10Z georg.brandl $

@c Fix XXX comments

This article explains the new features in Python 2.5.  The final release of
Python 2.5 is scheduled for August 2006; 
@geindex Python Enhancement Proposals; PEP 356
PEP 356@footnote{https://peps.python.org/pep-0356/} describes the planned
release schedule.  Python 2.5 was released on September 19, 2006.

The changes in Python 2.5 are an interesting mix of language and library
improvements. The library enhancements will be more important to Python's user
community, I think, because several widely useful packages were added.  New
modules include ElementTree for XML processing (@code{xml.etree}),
the SQLite database module (@code{sqlite}), and the @ref{2e,,ctypes}
module for calling C functions.

言語の変更の意義は、中程度のものです。いくつかの心地よい機能が入りましたが、そのほとんどの機能は毎日使うというものでもありません。条件式(conditional expressions)がついに言語に追加されました。ちょっと変わった文法です。 @ref{161b,,PEP 308; 条件式 (Conditional Expressions)} のセクションを参照してください。新しい '@ref{186,,with}' 文は後始末のコードを書くのを簡単にします(@ref{161c,,PEP 343; "with" ステートメント} セクション)。ジェネレータに値を返すことが出来るようになりました(@ref{161d,,PEP 342; ジェネレータの新機能} セクション)。インポートが、絶対パス、相対パスのどちらかで可視に出来るようになりました(@ref{161e,,PEP 328; 絶対インポート、相対インポート} セクション)。例外ハンドリングのいくつかの境界のケースで、より良いハンドリングを行えるようになりました(@ref{161f,,PEP 341; try/except/finally の一体化} セクション)。これらのどの改善も価値が高いですが、それらは言語機能を限定的に改善するものであって、いずれも Python のセマンティクスを広範に修正するものではありません。

言語とライブラリの追加と同様に、ほかの改善とバグフィックスもソースツリー全体に渡っています。SVN 変更ログを検索すると、Python 2.4 から 2.5 の間で適用されたパッチは 353、フィックスされたバグは 458 ありました(ともに少なく見積もってです)。

このドキュメントは新機能の完全な詳細を提供するのではなくて、変更について、役に立つ実例を使った簡易な概要を提供することを目的にしています。完全な詳細が知りたければ常に、 @indicateurl{https://docs.python.org} の Python 2.6 のドキュメントを参照すべきです。設計と実装の根拠を理解したい場合は、新機能に関する PEP を参照してください。可能な限り、 "What’s New in Python" は各変更の bug や patch に対してリンクしています。

このドキュメントについてのコメント、提案と誤りの報告は歓迎です。著者に電子メールを送るか、または Python バグトラッカーにバグをあげてください。

@c ======================================================================

@menu
* PEP 308; 条件式 (Conditional Expressions): PEP 308 条件式 Conditional Expressions. 
* PEP 309; 関数の部分適用: PEP 309 関数の部分適用. 
* PEP 314; Metadata for Python Software Packages v1.1: PEP 314 Metadata for Python Software Packages v1 1. 
* PEP 328; 絶対インポート、相対インポート: PEP 328 絶対インポート、相対インポート. 
* 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__' メソッド. 
* その他の言語変更: その他の言語変更<16>. 
* 新たなモジュール、改良されたモジュール、削除されたモジュール:: 
* ビルドならびに C API の変更: ビルドならびに C API の変更<10>. 
* Python 2.5 への移植: Python 2 5 への移植. 
* 謝辞: 謝辞<3>. 

@end menu

@node PEP 308 条件式 Conditional Expressions,PEP 309 関数の部分適用,,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-308}@anchor{161b}@anchor{whatsnew/2 5 pep-308-conditional-expressions}@anchor{1620}
@subsection PEP 308: 条件式 (Conditional Expressions)


もう長いことずっと、人々は条件式を書くための手段を要望し続けてきました。それは Boolean 値が真か偽かによって値 A または B を返す式です。条件式により以下と同じ効果を持つ単一行代入式を書くことが出来ます:

@example
if condition:
    x = true_value
else:
    x = false_value
@end example

構文についての退屈で終わりのない議論が python-dev と comp.lang.python の両方で続いてきました。投票では、大半は何らかの形で条件式を望んでいることを示していましたが、明らかな過半数によって支持される構文はありませんでした。候補には C の @code{cond ? true_v : false_v} や @code{if cond then true_v else false_v} を含む、ほか 16 のバリエーションがありました。

Guido van Rossum は結果として意外な構文を選択しました:

@example
x = true_value if condition else false_value
@end example

評価はこれでも既存の Boolean 式のように遅延的であり、評価順は少々前後します。真ん中の `condition' はまさに最初に評価されるのであって、 `true_value' 式はその `condition' が真の場合にのみ評価されます。同じように `false_value' は `condition' が偽の場合にのみ評価されるのです。

この構文は奇妙で退行しているようにも思えます; どうして condition が `真ん中' にあって C の @code{c ? x : y} のように前にないのでしょう? この決定は、標準ライブラリ内のモジュールにその新構文を適用し、結果のコードをどう読むかを見ることでチェックされました。条件式が使われる多くの場合で、一つの値はどうやら「一般の場合」で一つの値は「例外的な場合」のようで、条件を満たさないことが稀な場合にのみ使われていました。条件の構文はこのパターンで少しばかり明快さを増します:

@example
contents = ((doc + '\n') if doc else '@w{'})
@end example

私には上記ステートメントはこう読めます。「 `contents' は普通は @code{doc+'\n'} の値に代入される。ただし時々 `doc' が空になる。その特別な場合には空の値が代入されるのだ」。私は普通と普通でないのが明らかでない場合に頻繁に条件式を使うとは思いません。

言語が条件式に括弧を必要とすべきかどうかに関していくつか議論がありました。決定は Python 言語文法として括弧は `必要ない' とされましたが、スタイルの問題としては私は常に括弧を付けるべきと思います。以下 2 つの例を考えてみてください:

@example
# First version -- no parens
level = 1 if logging else 0

# Second version -- with parens
level = (1 if logging else 0)
@end example

最初の版の場合、私は読者の目はおそらくステートメントを「level = 1」「if logging」「else 0」にグループ化すると思います。そして condition は `level' への代入が行われるのかどうかを決めるのだ、と考えるであろうと。後者の版は読みやすいです、少なくとも私の意見では。代入はいつでも行われることも、選択が 2 つの値の間で起こることもはっきりしますから。

括弧を含めるもう一つの理由があります: 少し奇妙なリスト内包とラムダの組合せが、不完全な条件式になることがあります。 
@geindex Python Enhancement Proposals; PEP 308
PEP 308@footnote{https://peps.python.org/pep-0308/} にいくつかの例があるので見てください。条件式の周りをいつでも括弧で囲むなら、このケースにぶち当たることもありません。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 308

@item PEP 308@footnote{https://peps.python.org/pep-0308/} - 条件式 (Conditional Expressions)

PEP 著 Guido van Rossum と Raymond D. Hettinger; 実装 Thomas Wouters.
@end table


@c ======================================================================

@node PEP 309 関数の部分適用,PEP 314 Metadata for Python Software Packages v1 1,PEP 308 条件式 Conditional Expressions,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-309}@anchor{1621}@anchor{whatsnew/2 5 pep-309-partial-function-application}@anchor{1622}
@subsection PEP 309: 関数の部分適用


@ref{63,,functools} モジュールは、関数型スタイルのプログラミングのためのツールを含むことを意図したものです。

このモジュールには一つの有用なツールとして、 @code{partial()} 関数があります。関数型スタイルでプログラムを書くのに、あなたはときおり、いくつかのパラメータを持つ関数に一部パラメータを埋めたものを作りたくなります。Python 関数 @code{f(a, b, c)} を考えてみましょう; @code{f(1, b, c)} と等価な @code{g(b, c)} を作れたら、と思うわけです。これは「関数の部分適用」と呼ばれています。

@code{partial()} は @code{(function, arg1, arg2, ... kwarg1=value1, kwarg2=value2)} という引数を取ります。できあがったオブジェクトは呼び出し可能オブジェクトですので、それを呼べば、引数の埋まった `function' を実行したのと同じことになります。

以下にあるのは、小さいけれども現実的な一つの例です:

@example
import functools

def log (message, subsystem):
    "Write the contents of 'message' to the specified subsystem."
    print '%s: %s' % (subsystem, message)
    ...

server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')
@end example

もうひとつ、PyGTK を使うプログラムからの例をみてみましょう。いま、「コンテキスト依存」のポップアップメニューを動的に構築しようとしています。そのメニューオプションから提供されるコールバックは、 @code{open_item()} メソッドの部分適用版で、その最初の引数が適用済みです:

@example
...
class Application:
    def open_item(self, path):
       ...
    def init (self):
        open_func = functools.partial(self.open_item, item_path)
        popup_menu.append( ("Open", open_func, 1) )
@end example

@ref{63,,functools} モジュールのもう一つの関数は @code{update_wrapper(wrapper, wrapped)} で、より良く振舞うデコレータを書くのに役立ちます。 @code{update_wrapper()} は包まれるほうの名前、モジュール、ドキュメンテーション文字列属性をラッパー関数にコピーすることで、トレースバックを理解しやすくします。たとえばこう書けます:

@example
def my_decorator(f):
    def wrapper(*args, **kwds):
        print 'Calling decorated function'
        return f(*args, **kwds)
    functools.update_wrapper(wrapper, f)
    return wrapper
@end example

@code{wraps()} は、ラップされる関数についての情報をコピーするために、あなた自身のデコレータ内で使えるデコレータです。先の例はこのようにも書けます:

@example
def my_decorator(f):
    @@functools.wraps(f)
    def wrapper(*args, **kwds):
        print 'Calling decorated function'
        return f(*args, **kwds)
    return wrapper
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 309

@item PEP 309@footnote{https://peps.python.org/pep-0309/} - 関数の部分適用

PEP の提案と著:  Peter Harris; 実装: Hye-Shik Chang と Nick Coghlan, また、適応物が Raymond Hettinger により。 (---訳注: この PEP のタイトルに違和感を憶える人は多いと思います。functools のテリトリが「関数型スタイルのサポート」にあるのに。部分引数サポートのためのパッチが最終的に関数型スタイルに行き着いた (正確には、「partial のような高階関数を置く場所として functools という場所を使いましょう、partial から始めましょう」というのが提案の趣旨)、という経緯がこのタイトルに反映しています。---)
@end table


@c ======================================================================

@node PEP 314 Metadata for Python Software Packages v1 1,PEP 328 絶対インポート、相対インポート,PEP 309 関数の部分適用,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-314}@anchor{1623}@anchor{whatsnew/2 5 pep-314-metadata-for-python-software-packages-v1-1}@anchor{1624}
@subsection PEP 314: Metadata for Python Software Packages v1.1


Distutils にいくつかの単純な依存性解決サポートが追加されました。 @code{setup()} 関数に @code{requires}, @code{provides},  @code{obsoletes} キーワードパラメータが追加されています。 @code{sdist} コマンドでソース配布物をビルドする際に、依存性についての情報が @code{PKG-INFO} ファイルに記録されます。

もう一つ追加されたキーワードパラメータ @code{download_url} は、パッケージのソースコードの URL をセットします。これによりパッケージインデクス内のエントリを探し出すことが出来、パッケージの依存性を決めることが出来、必要パッケージをダウンロード出来ます:

@example
VERSION = '1.0'
setup(name='PyPackage',
      version=VERSION,
      requires=['numarray', 'zlib (>=1.1.4)'],
      obsoletes=['OldPackage']
      download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
                    % VERSION),
     )
@end example

Python Package Index (@indicateurl{https://pypi.org}) へのもう一つの新たな拡張は、パッケージについてのソースコードとバイナリアーカイブの保存についてです。新たな Distutils コマンド @code{upload} は、レポジトリへパッケージをアップロードします。

パッケージがアップロードされる前には、Distutils @code{sdist} コマンドを使って配布物をビルド可能でなければなりません。それさえ出来ていれば、 @code{python setup.py upload} がパッケージを PyPI アーカイブに追加してくれます。追加で、パッケージに GPG 署名出来ます。これには @code{--sign} オプションと @code{--identity} オプションを使います。

パッケージのアップロードは Martin von Löwis と Richard Jones により実装されました。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 314

@item PEP 314@footnote{https://peps.python.org/pep-0314/} - Metadata for Python Software Packages v1.1

PEP 提案と著 A.M. Kuchling、 Richard Jones、 Fred Drake; 実装 Richard Jones と Fred Drake.
@end table


@c ======================================================================

@node PEP 328 絶対インポート、相対インポート,PEP 338 - モジュールをスクリプトとして実行する,PEP 314 Metadata for Python Software Packages v1 1,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-328}@anchor{161e}@anchor{whatsnew/2 5 pep-328-absolute-and-relative-imports}@anchor{1625}
@subsection PEP 328: 絶対インポート、相対インポート


The simpler part of 
@geindex Python Enhancement Proposals; PEP 328
PEP 328@footnote{https://peps.python.org/pep-0328/} was implemented in Python 2.4: parentheses could now
be used to enclose the names imported from a module using the @code{from ... import
...} statement, making it easier to import many different names.

より複雑なほうは Python 2.5 で実装されました: モジュールのインポートにおいて、それが絶対インポートなのかパッケージ相対のインポートなのかを指定出来るようにする、というものです。将来のバージョンの Python では絶対インポートをデフォルトにする方向に向かう予定です。

いま、あなたは以下のようなパッケージディレクトリを持っているとします:

@example
pkg/
pkg/__init__.py
pkg/main.py
pkg/string.py
@end example

@code{pkg} パッケージがモジュール @code{pkg.main} とサブモジュール @code{pkg.string} を持っています。

@code{main.py} のなかの人、になってみましょう。 @code{import string} 文を実行すると、何が起こるでしょうか? Python 2.4 とそれ以前のバージョンでは、相対インポートとして実行するためにパッケージのディレクトリ内のものを最初に探し、 @code{pkg/string.py} を発見してそのファイル内容を @code{pkg.string} モジュールであるとしてインポートし、そのモジュールは @code{pkg.main} モジュール内の名前空間で、名前 @code{string} に束縛されます。

よろしいでしょう。欲しいものが @code{pkg.string} であるならば。ですが欲しいのは Python 標準ライブラリモジュールの @ref{d8,,string} なのだとしたら? @code{pkg.string} を無視して標準モジュールを探す綺麗な方法はありません; 一般的に、 @code{sys.modules} の中身から探す必要がありました。これはちょっとばかり美しくありません。Holger Krekel の @code{py.std} パッケージは標準ライブラリからモジュールをインポートするのに @code{import py; py.std.string.join()} と、よりこぎれいな方法を与えてくれますが、そのパッケージは全ての Python インストレーションでの利用が可能にはなっていません。

相対インポートに頼ったコードを読むことは、より不明瞭でもあります。読者は @ref{d8,,string} と @code{pkg.string} のどちらを使おうとしているのかについて、混乱するだろうからです。Python ユーザはすぐに、彼らのパッケージのサブモジュール名が標準ライブラリモジュールの名前と被らないようにすることを学びますが、あなたのサブモジュール名が将来のバージョンの Python に追加される新しいモジュールで使われる名前にならないようにすることは出来ません。

Python 2.5 では @ref{7f8,,import} の振る舞いを、 @code{from __future__ import absolute_import} ディレクティブを使うことによって絶対インポートに切り替えられます。この絶対インポートの振る舞いは将来バージョンの Python でデフォルトになります(おそらく Python 2.7 で)。(訳注: ご承知のとおり Python 2.7 でもこれはデフォルトとはなっていません。Python 3.x への移行のためにも 2.5 - 2.7 では @code{from __future__ import absolute_import} を使うべきです。) 絶対インポートをデフォルトにしてしまえば、 @code{import string} はいつでも標準ライブラリ版を見つけます。ユーザは可能な限り絶対インポートを使い始めるべきで、あなたのコードでは @code{from pkg import string} と書き始めることが望まれます。

相対インポートは、 @code{from ... import} 形式を使う際にモジュール名の前にピリオドを付ければまだ可能です:

@example
# Import names from pkg.string
from .string import name1, name2
# Import pkg.string
from . import string
@end example

これは現在のパッケージからの相対で @ref{d8,,string} モジュールをインポートしますので、 @code{pkg.main} 内ではこれは、 `name1' と `name2' を @code{pkg.string} からインポートするでしょう。加えて、先行する複数ピリオドは、現在のパッケージの親からの相対インポートを実行します。例えば、 @code{A.B.C} モジュール内のコードはこのように出来ます:

@example
from . import D                 # Imports A.B.D
from .. import E                # Imports A.E
from ..F import G               # Imports A.F.G
@end example

このピリオドによる書き方は @code{import modname} 形式のインポート文では使えず、 @code{from ... import} 形式でのみ使えます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 328

@item PEP 328@footnote{https://peps.python.org/pep-0328/} - マルチラインインポートと、絶対/相対インポート

PEP 著 Aahz; 実装 Thomas Wouters。

@item @indicateurl{https://pylib.readthedocs.io/}

Holger Krekel による py ライブラリで、 @code{py.std} パッケージを含みます。
@end table


@c ======================================================================

@node PEP 338 - モジュールをスクリプトとして実行する,PEP 341 try/except/finally の一体化,PEP 328 絶対インポート、相対インポート,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-338}@anchor{1626}@anchor{whatsnew/2 5 pep-338-executing-modules-as-scripts}@anchor{1627}
@subsection PEP 338 - モジュールをスクリプトとして実行する


Python 2.4 で追加されたモジュールをスクリプトとして実行するための @ref{23c,,-m} スイッチが、少し能力を高めました。Python インタプリタ内での C 実装に代わり、これの実現には新しいモジュール @ref{c3,,runpy} を使うようになっています。

@ref{c3,,runpy} モジュールはインポートのメカニズムをより洗練された方法で実装しているので、今では @code{pychecker.checker} のようにパッケージ内のモジュールも実行出来ます。このモジュールは異なるインポートメカニズム、例えば @ref{138,,zipimport} モジュールもサポートします。このことにより、 @code{sys.path} に .zip アーカイブのパスを追加して、 @ref{23c,,-m} スイッチでアーカイブ内のコードを実行する、といったことも出来ます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 338

@item PEP 338@footnote{https://peps.python.org/pep-0338/} - モジュールをスクリプトとして実行する

PEP 著と実装 Nick Coghlan.
@end table


@c ======================================================================

@node PEP 341 try/except/finally の一体化,PEP 342 ジェネレータの新機能,PEP 338 - モジュールをスクリプトとして実行する,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-341}@anchor{161f}@anchor{whatsnew/2 5 pep-341-unified-try-except-finally}@anchor{1628}
@subsection PEP 341: try/except/finally の一体化


Until Python 2.5, the @ref{8f8,,try} statement came in two flavours. You could
use a @ref{1b0,,finally} block to ensure that code is always executed, or one or
more @ref{1ab,,except} blocks to catch  specific exceptions.  You couldn't
combine both @code{except} blocks and a @code{finally} block, because
generating the right bytecode for the combined version was complicated and it
wasn't clear what the semantics of the combined statement should be.

Guido van Rossum はいくらかの時間 Java での作業に時間を割きました。それは @ref{1ab,,except} ブロックと @ref{1b0,,finally} ブロックを組み合わせるのと等価なものをサポートしています。そしてこの作業が、このステートメントがどういう意味であるべきかを明らかにしたのです。Python 2.5 では、あなたは今ではこう書くことが出来ます:

@example
try:
    block-1 ...
except Exception1:
    handler-1 ...
except Exception2:
    handler-2 ...
else:
    else-block
finally:
    final-block
@end example

`block-1' 内のコードが実行されます。そのコードが例外を投げた場合、個々の @ref{1ab,,except} ブロックがテストされます: その例外が @code{Exception1} クラスであれば、 `handler-1' が実行されます; そうでない場合で @code{Exception2} クラスであれば、 `handler-2' が実行されます、以下同文。例外が起こらなければ、 `else-block' が実行されます。

以前に何が起こったのかに拠らず、コードブロック完了時やどれかの例外が処理されれば `final-block' が実行されます。例外ハンドラ内や `else-block' でエラーが起こったり、 新しく例外を投げる場合でさえ、 `final-block' 内のコードはそれでも実行されます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 341

@item PEP 341@footnote{https://peps.python.org/pep-0341/} - try-except と try-finally を一体化する

PEP 著 Georg Brandl; 実装 Thomas Lee。
@end table


@c ======================================================================

@node PEP 342 ジェネレータの新機能,PEP 343 "with" ステートメント<2>,PEP 341 try/except/finally の一体化,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-342}@anchor{161d}@anchor{whatsnew/2 5 pep-342-new-generator-features}@anchor{1629}
@subsection PEP 342: ジェネレータの新機能


Python 2.5 は、ジェネレータ `に向けて' 値を渡すための単純な手段を追加しました。Python 2.3 でジェネレータが導入された時点ではジェネレータが出来たのは出力だけでした。いったんジェネレータのコードが呼び出されてイテレータが作られたあとは、新しい情報をそのジェネレータ関数の再開位置に渡す手段はありませんでした。ヤクザな解決法としては、ジェネレータがグローバル変数を見るようにしたり、ミュータブルなオブジェクトを渡しておいて呼び出し元であとからそれを変更したり、といったものがありました。

基本的なジェネレータについて思い出してもらいましょう、単純な例はこんなです:

@example
def counter (maximum):
    i = 0
    while i < maximum:
        yield i
        i += 1
@end example

When you call @code{counter(10)}, the result is an iterator that returns the values
from 0 up to 9.  On encountering the @ref{bc2,,yield} statement, the iterator
returns the provided value and suspends the function's execution, preserving the
local variables. Execution resumes on the following call to the iterator's
@ref{9d8,,next()} method, picking up after the @code{yield} statement.

In Python 2.3, @ref{bc2,,yield} was a statement; it didn't return any value.  In
2.5, @code{yield} is now an expression, returning a value that can be
assigned to a variable or otherwise operated on:

@example
val = (yield i)
@end example

戻り値に何かする際は、 @ref{bc2,,yield} 式の周りには括弧は付けておいたほうがいいと思います、この例でのように。括弧はべつに必要はないのですが、どんな場合に必要かを憶えるよりは、いつでも付けるのが簡単でしょう。

(
@geindex Python Enhancement Proposals; PEP 342
PEP 342@footnote{https://peps.python.org/pep-0342/} がその規則を正確に説明していますが、それによると @ref{bc2,,yield} 式は、代入式で右辺のトップレベルにあるとき以外はいつも括弧を付ける必要があります。つまり @code{val = yield i} とは書けますが、 @code{val = (yield i) + 12} のように演算子があるときは括弧を使わなくてはいけません。)

Values are sent into a generator by calling its @code{send(value)} method.  The
generator's code is then resumed and the @ref{bc2,,yield} expression returns the
specified `value'.  If the regular @ref{9d8,,next()} method is called, the
@code{yield} returns @ref{885,,None}.

以下は前のと同じ例ですが、内部カウンタの値の変更を許す修正をしました:

@example
def counter (maximum):
    i = 0
    while i < maximum:
        val = (yield i)
        # If value provided, change counter
        if val is not None:
            i = val
        else:
            i += 1
@end example

そしてカウンタ変更の例がこちらです:

@example
>>> it = counter(10)
>>> print it.next()
0
>>> print it.next()
1
>>> print it.send(8)
8
>>> print it.next()
9
>>> print it.next()
Traceback (most recent call last):
  File "t.py", line 15, in ?
    print it.next()
StopIteration
@end example

@ref{bc2,,yield} が @ref{885,,None} を返すことはよくあるのですから、そうなっていないかどうか必ずチェックしておくべきです。ジェネレータ関数を再開するために使うメソッドが @code{send()} しかないのだと確信してるのでない限り、式の値をそのまま使ってはいけません。

ジェネレータには、 @code{send()} のほかにも新しいメソッドが二つあります


@itemize *

@item 
@code{throw(type, value=None, traceback=None)} はジェネレータ内で例外を投げるために使います; その例外はジェネレータの実行が停止したところの @ref{bc2,,yield} 式によって投げられます。

@item 
@code{close()} はジェネレータ内で @ref{15e1,,GeneratorExit} 例外を投げてイテレートを終了させます。この例外を受け取ったジェネレータのコードは @ref{15e1,,GeneratorExit} か @ref{df5,,StopIteration} を投げなくてはいけません; この例外を捕捉して何かほかのことをしようとするのは規則違反であり、 @ref{244,,RuntimeError} を引き起こします; 関数が何かほかの例外を投げると、その例外は呼び出し元に伝播します。 @code{close()} はジェネレータのガーベージコレクトによっても呼ばれます。

@ref{15e1,,GeneratorExit} が起こったときにクリーンアップ作業をする必要があるなら、 @ref{15e1,,GeneratorExit} を捕捉するのではなく @code{try: ... finaly:} するようお勧めします。
@end itemize

これらの変更の合わせ技で、ジェネレータは情報の一方的な生産者から、生産者かつ消費者という存在に変貌を遂げたのです。

ジェネレータは `コルーチン' という、より一般化された形式のサブルーチンにもなります。サブルーチンは一カ所 (関数の冒頭) から入って別の一カ所 (@ref{1af,,return} 文) から出るだけですが、コルーチンはいろいろな場所 (@ref{bc2,,yield} 文) から入ったり出たり再開したりできるのです。わたしたちは Python でコルーチンを効果的に使うためのパターンを理解する必要があります。

The addition of the @code{close()} method has one side effect that isn't obvious.
@code{close()} is called when a generator is garbage-collected, so this means the
generator's code gets one last chance to run before the generator is destroyed.
This last chance means that @code{try...finally} statements in generators can now
be guaranteed to work; the @ref{1b0,,finally} clause will now always get a
chance to run.  The syntactic restriction that you couldn't mix @ref{bc2,,yield}
statements with a @code{try...finally} suite has therefore been removed.  This
seems like a minor bit of language trivia, but using generators and
@code{try...finally} is actually necessary in order to implement the
@ref{186,,with} statement described by 
@geindex Python Enhancement Proposals; PEP 343
PEP 343@footnote{https://peps.python.org/pep-0343/}.  I'll look at this new statement
in the following  section.

もう一つさらに深遠なこの変更の効果: 以前はジェネレータの @code{gi_frame} 属性は常にフレームオブジェクトでした。今では @code{gi_frame} は、ジェネレータが使い果たされた場合に @code{None} になります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 342

@item PEP 342@footnote{https://peps.python.org/pep-0342/} - 拡張されたジェネレータを用いたコルーチン

PEP は Guido van Rossum と Phillip J. Eby によって書かれ、Phillip J. Eby によって実装されました。コルーチンとしてのジェネレータの用法のいくつかの手が込んだ例が含まれています。

この機能の初期バージョンは Raymond Hettinger による 
@geindex Python Enhancement Proposals; PEP 288
PEP 288@footnote{https://peps.python.org/pep-0288/} と Samuele Pedroni による 
@geindex Python Enhancement Proposals; PEP 325
PEP 325@footnote{https://peps.python.org/pep-0325/} で提案されました。

@item @indicateurl{https://en.wikipedia.org/wiki/Coroutine}

コルーチンに関する WikiPedia エントリ。

@item @indicateurl{https://web.archive.org/web/20160321211320/http://www.sidhe.org/~dan/blog/archives/000178.html}

Dan Sugalski による、Perl の視点からみたコルーチンの説明です。
@end table


@c ======================================================================

@node PEP 343 "with" ステートメント<2>,PEP 352 例外の新スタイルクラス化,PEP 342 ジェネレータの新機能,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-343}@anchor{161c}@anchor{whatsnew/2 5 pep-343-the-with-statement}@anchor{162a}
@subsection PEP 343: "with" ステートメント


'@ref{186,,with}' ステートメントは、以前なら後片付けが実行されるのを確実にするために @code{try...finally} ブロックを使ったであろうようなコードを、より単純明快にします。このセクションでは、このステートメントの普通の使い方を説明します。続くセクションでは実装の詳細を調べ、このステートメントとともに使うためにオブジェクトをどうやって書けば良いかをお見せします。

'@ref{186,,with}' ステートメントは基本構造が以下となる新しい制御フロー構造です:

@example
with expression [as variable]:
    with-block
@end example

The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has @ref{7e4,,__enter__()} and @ref{1518,,__exit__()}
methods.

The object's @ref{7e4,,__enter__()} 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 @ref{1518,,__exit__()}
method is called, even if the block raised an exception, and can therefore run
clean-up code.

Python 2.5 でこのステートメントを有効にするには、以下のディレクティブをあなたのモジュールに追加する必要があります:

@example
from __future__ import with_statement
@end example

Python 2.6 ではこれは常に有効になります。

いくつかの Python 標準オブジェクトが既にコンテキスト管理プロトコルをサポートしていて、 '@ref{186,,with}' とともに使えます。ファイルオブジェクトがその一例です:

@example
with open('/etc/passwd', 'r') as f:
    for line in f:
        print line
        ... more processing code ...
@end example

このステートメントが実行し終わったあかつきには、 `f' のファイルオブジェクトは、たとえ @ref{34a,,for} ループが道半ばにして例外と成り果てても、自動的にクローズされます。

@cartouche
@quotation 注釈 
In this case, `f' is the same object created by @ref{316,,open()}, because
@ref{7e4,,__enter__()} returns `self'.
@end quotation
@end cartouche

@ref{f3,,threading} モジュールのロック・条件変数でも '@ref{186,,with}' ステートメントの恩恵にあずかれます:

@example
lock = threading.Lock()
with lock:
    # Critical section of code
    ...
@end example

ブロックが実行される前にロックが獲得されて、ブロックが完了するやいなや必ず解放されます。

@ref{3a,,decimal} モジュール内の新しい @code{localcontext()} 関数は現在の decimal のコンテキスト (計算の望みの精度と丸め特性をカプセル化しています) を保存しておいてあとで元に戻すのを簡単にしてくれます:

@example
from decimal import Decimal, Context, localcontext

# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # All code in this block uses a precision of 16 digits.
    # The original context is restored on exiting the block.
    print v.sqrt()
@end example

@menu
* コンテキストマネージャを書く: コンテキストマネージャを書く<2>. 
* contextlib モジュール: contextlib モジュール<2>. 

@end menu

@node コンテキストマネージャを書く<2>,contextlib モジュール<2>,,PEP 343 "with" ステートメント<2>
@anchor{whatsnew/2 5 new-25-context-managers}@anchor{162b}@anchor{whatsnew/2 5 writing-context-managers}@anchor{162c}
@subsubsection コンテキストマネージャを書く


中身を紐解いてみれば、 '@ref{186,,with}' ステートメントはけっこう入り組んでいます。ほとんどの人にとっては、既存のオブジェクトを '@code{with}' とともに使うだけのことでその詳細を知る必要は無いので、それで良いならこのセクションの残りの部分は読み飛ばして結構です。新しいオブジェクトの作者は基礎となる実装の詳細について知る必要があるので、このまま読み進めるべきです。

コンテキスト管理プロトコルの高度な説明はこんなです:


@itemize *

@item 
The expression is evaluated and should result in an object called a "context
manager".  The context manager must have @ref{7e4,,__enter__()} and @ref{1518,,__exit__()}
methods.

@item 
The context manager's @ref{7e4,,__enter__()} method is called.  The value returned
is assigned to `VAR'.  If no @code{'as VAR'} clause is present, the value is simply
discarded.

@item 
`BLOCK' 内のコードが実行されます。

@item 
`BLOCK' が例外を起こした場合、コンテキストマネージャの @code{__exit__} メソッドが 3 つの引数とともに呼び出されます。これは例外の詳細です (@code{type, value, traceback}, これは @ref{89a,,sys.exc_info()} が返す値と同じで、例外が起こらなければ @code{None} です)。そのメソッドの戻り値は例外を再送出するかどうかを制御します: 全ての偽の値ではその例外が再送出され、 @code{True} では揉み消します。例外を揉み消すなど滅多なことでは欲しいと思わないでしょう。もしそうしてしまったら、 '@ref{186,,with}' ステートメントを含んだコードの作者は何か間違ったことが起こったことに決して気付かないですから。

@item 
If `BLOCK' didn't raise an exception,  the @ref{1518,,__exit__()} method is still
called, but `type', `value', and `traceback' are all @code{None}.
@end itemize

例を通じて考えましょう。枝葉末節を含んだ完璧なコードを提示しようとは思いませんが、データベースのためにトランザクションをサポートするのに必要となるメソッドの書き方についてスケッチしてみようと思います。

(データベース用語に不慣れな方へ:データベースへの変更のセットは、トランザクションという単位でグループ化されています。トランザクションは「コミット」される、その意味は、全ての変更がデータベースに書き込まれることです、もしくは「ロールバック」される、この場合全ての変更が捨てられてデータベースが変更されません、この 2 つのいずれかになりえます。詳しくはなにかデータベースの著述を読んで下さい。)

データベース接続を表現するオブジェクトがあると仮定しましょう。私たちの目標は、そのオブジェクトのユーザがこのように書けるようになることです:

@example
db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...
@end example

トランザクションはブロック内のコードがつつがなく終了すればコミットし、例外が発生すればロールバックすべきです。私が思い描いている @code{DatabaseConnection} の基本的なインターフェイスはこんなです:

@example
class DatabaseConnection:
    # Database interface
    def cursor (self):
        "Returns a cursor object and starts a new transaction"
    def commit (self):
        "Commits current transaction"
    def rollback (self):
        "Rolls back current transaction"
@end example

The @ref{7e4,,__enter__()} method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add @code{as cursor} to
their '@ref{186,,with}' statement to bind the cursor to a variable name.

@example
class DatabaseConnection:
    ...
    def __enter__ (self):
        # Code to start a new transaction
        cursor = self.cursor()
        return cursor
@end example

The @ref{1518,,__exit__()} method is the most complicated because it's where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.

下記のコード内では実行がメソッドの末尾まで落ちていって、なのでデフォルトの @code{None} 返却になります。 @code{None} は偽なので、例外は自動的に再送出されます。望むならもっと明示的に、コメントでマークした部分で @ref{1af,,return} 文を書いてもよろしいです:

@example
class DatabaseConnection:
    ...
    def __exit__ (self, type, value, tb):
        if tb is None:
            # No exception, so commit
            self.commit()
        else:
            # Exception occurred, so rollback.
            self.rollback()
            # return False
@end example

@node contextlib モジュール<2>,,コンテキストマネージャを書く<2>,PEP 343 "with" ステートメント<2>
@anchor{whatsnew/2 5 contextlibmod}@anchor{162d}@anchor{whatsnew/2 5 the-contextlib-module}@anchor{162e}
@subsubsection contextlib モジュール


新しい @ref{27,,contextlib} モジュールは、 '@ref{186,,with}' ステートメントで使えるオブジェクトを書く際に便利ないくつかの関数とデコレータを提供しています。

The decorator is called @code{contextmanager()}, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the @ref{bc2,,yield} will be executed as the
@ref{7e4,,__enter__()} method, and the value yielded will be the method's return
value that will get bound to the variable in the '@ref{186,,with}' statement's
@code{as} clause, if any.  The code after the @ref{bc2,,yield} will be
executed in the @ref{1518,,__exit__()} method.  Any exception raised in the block will
be raised by the @code{yield} statement.

このデコレータを使って、前セクションの私たちのデータベースの例はこのように書けます:

@example
from contextlib import contextmanager

@@contextmanager
def db_transaction (connection):
    cursor = connection.cursor()
    try:
        yield cursor
    except:
        connection.rollback()
        raise
    else:
        connection.commit()

db = DatabaseConnection()
with db_transaction(db) as cursor:
    ...
@end example

@ref{27,,contextlib} モジュールには @code{nested(mgr1, mgr2, ...)} 関数もあり、この関数はたくさんのコンテキストマネージャを組み合わせることができて、入れ子の '@ref{186,,with}' を書く必要性をなくしてくれます。この例では、単一の '@code{with}' でデータベーストランザクション開始とスレッドのロック獲得の両方をやってのけています:

@example
lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
    ...
@end example

最後になりますが、 @code{closing(object)} 関数は `object' をそのまま返して変数に束縛出来るようにし、かつブロックの終了で、与えた引数が持つ @code{object.close} を呼び出します:

@example
import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 343

@item PEP 343@footnote{https://peps.python.org/pep-0343/} - "with" ステートメント

PEP は Guido van Rossum と Nick Coghlan によって書かれ、Mike Bland、 Guido van Rossum、Neal Norwitz により実装されました。この PEP は '@ref{186,,with}' ステートメントによって生成されるコードを見せてくれるので、このステートメントがどうやって動作するのかを知るのに役立ちます。
@end table

@ref{27,,contextlib} モジュールについてのドキュメント。


@c ======================================================================

@node PEP 352 例外の新スタイルクラス化,PEP 353 添え字型に ssize_t を使う,PEP 343 "with" ステートメント<2>,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-352}@anchor{162f}@anchor{whatsnew/2 5 pep-352-exceptions-as-new-style-classes}@anchor{1630}
@subsection PEP 352: 例外の新スタイルクラス化


例外クラスは、今では旧スタイルクラスだけではなく新スタイルクラスになれます。組み込みの @ref{bcd,,Exception} クラスと全ての標準組み込み例外 (@ref{452,,NameError}, @ref{2ec,,ValueError}, など) が今では新スタイルクラスです。

例外の継承階層が少し再編成されました。2.5 では継承関係はこのようになっています (---訳注: 2.6 ではさらに GeneratorExit が Exception ではなく BaseExceotion の直接の子になり、これは 3.x でも引き継がれています。---):

@example
BaseException       # New in Python 2.5
|- KeyboardInterrupt
|- SystemExit
|- Exception
   |- (all other current built-in exceptions)
@end example

この再編成が行われたのは、人々がしばしばプログラムのエラーを示す例外すべてを捕捉したがるからです。 @ref{bc5,,KeyboardInterrupt} と @ref{f3c,,SystemExit} はエラーではありませんが、普通は @code{Control}-@code{C} をユーザが叩いたか、コードが @ref{277,,sys.exit()} を呼び出したかのような明示的なアクションを表します。剥き出しの @code{except:} はまさに全ての例外を捕捉しますから、一般に、再送出のために @ref{bc5,,KeyboardInterrupt} と @ref{f3c,,SystemExit} はリストする必要があります。お決まりのパターンはこんなです:

@example
try:
    ...
except (KeyboardInterrupt, SystemExit):
    raise
except:
    # Log error...
    # Continue running program...
@end example

Python 2.5 では同じ結果を得るのにもう @code{except Exception} と書いても良いです。これは普通はエラーを示す例外全てを捕捉しつつも @ref{bc5,,KeyboardInterrupt} と @ref{f3c,,SystemExit} は置き去りにします。無論かつてまでのバージョン同様、剥き身の @code{except:} は全例外を捕捉します。

Python 3.0 での目標は、例外として raise される全てのクラスが @ref{7d6,,BaseException} からの、もしくは @ref{7d6,,BaseException}  のある子孫であることを要求することであり、Python 2.x シリーズの将来のリリースにおいてはこの制約の強制を始めるかもしれません。ですからあなたの全ての例外は、今からすぐに @ref{bcd,,Exception} 派生にするのが肝要です。捕捉例外を特定しない @code{except:} は Python 3.0 から取り除かれるべきであることが提案されていますが、Guido van Rossum はこれをどうするかまだ決めていません。 (---訳注: 2.7 では raise は「新スタイルクラスであれば」 @ref{7d6,,BaseException} 派生であることを要求されますが、旧スタイルクラスであればなんでも許されてしまう点ではあまり変わっていません。これについての警告は @code{-3} などで受けることが出来ます。Python 3.0 でようやく全ての例外が @ref{7d6,,BaseException} 派生であることが強制されるようになりました。 また、 @code{except:} は 3.4 でも残っています。---)

例外として文字列を @code{raise "Error occurred"} として raise することは Python 2.5 では非推奨であり警告を引き起こします。その目的は、あと少しのリリースで文字列例外を削除することです。 (---訳注: 2.6 以降の What's New では明示的に書かれてはいませんが、2.7 では警告ではなくエラーです。---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 352

@item PEP 352@footnote{https://peps.python.org/pep-0352/} - 例外のためのスーパークラス

PEP 著: Brett Cannon と Guido van Rossum; 実装: Brett Cannon.
@end table


@c ======================================================================

@node PEP 353 添え字型に ssize_t を使う,PEP 357 '__index__' メソッド,PEP 352 例外の新スタイルクラス化,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-353}@anchor{1631}@anchor{whatsnew/2 5 pep-353-using-ssize-t-as-the-index-type}@anchor{1632}
@subsection PEP 353: 添え字型に ssize_t を使う


A wide-ranging change to Python's C API, using a new  @ref{c55,,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
@code{2**31 - 1} = 2147483647 items. (There are actually a few different
programming models that 64-bit C compilers can use -- see
@indicateurl{https://unix.org/version2/whatsnew/lp64_wp.html} for a discussion -- but the
most commonly available model leaves int as 32 bits.)

2147483647 に要素数が制限されることは 32 ビットプラットフォームではあまり重大でもありません。その長さ制限を喰らう前にメモリを使い果たすでしょうから。それぞれのリストアイテムは、ポインタのための領域 (4 バイト) をアイテムを表現する @ref{5df,,PyObject} に余分に必要とします。2147483647*4 は既に 32 ビットのアドレス空間が含められるバイト数を超えています。(---訳注: 意味不明。何か誤解があるような…? 4 バイトは 2147483647 (符号付きとして 2^31 - 1) でしょう。4 を掛ける説明なんかここでまったくされていない。なぜ掛ける? それと要素のインデクシングとアイテムの必要領域は議論には無関係なのでは?---)

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

この変更は C 拡張モジュールの著者に大変大きく影響します。Python 文字列とリストやタプルのようなコンテナ型は、そのサイズを表すのに @ref{c55,,Py_ssize_t} を使うようになっています。 @ref{1633,,PyList_Size()} のような関数は @ref{c55,,Py_ssize_t} を返します。拡張モジュール内のコードでは、ですので、ある程度の変数の @ref{c55,,Py_ssize_t} への変更が必要でしょう。

The @ref{3c1,,PyArg_ParseTuple()} and @ref{3c2,,Py_BuildValue()} functions have a new
conversion code, @code{n}, for @ref{c55,,Py_ssize_t}.   @ref{3c1,,PyArg_ParseTuple()}'s
@code{s#} and @code{t#} still output int by default, but you can define the
macro  @code{PY_SSIZE_T_CLEAN} before including @code{Python.h}  to make
them return @ref{c55,,Py_ssize_t}.

@geindex Python Enhancement Proposals; PEP 353
PEP 353@footnote{https://peps.python.org/pep-0353/} には、拡張の著者が読んで学ぶべき 64 ビットプラットフォームサポートについてのセクションがあります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 353

@item PEP 353@footnote{https://peps.python.org/pep-0353/} - 添え字型に ssize_t を使う

PEP 著と実装 Martin von Löwis.
@end table


@c ======================================================================

@node PEP 357 '__index__' メソッド,その他の言語変更<16>,PEP 353 添え字型に ssize_t を使う,What's New in Python 2 5
@anchor{whatsnew/2 5 pep-357}@anchor{1634}@anchor{whatsnew/2 5 pep-357-the-index-method}@anchor{1635}
@subsection PEP 357: '__index__' メソッド


NumPy 開発者たちは、新しい特殊メソッド、 @code{__index__()} を追加することによってしか解決できない問題を抱えていました。スライスの表現 @code{[start:stop:step]} を使う際、 `start', `stop', `step' は全て整数か長整数でなければなりません。NumPy は様々な特殊化された整数型を持っていて、符号なし、符号付きの 8、16、32、64 ビットに対応していますが、それらをスライスの添え字に使う手段はありませんでした。

スライシングに既存の @code{__int__()} メソッドをそのまま使うことは出来ません。それらは整数への型変換を実装するのにも使われるからです。スライシングが @code{__int__()} を使ったとすれば、浮動小数点数でさえスライスの添え字として使うことが合法になりますが、それは明らかに望む振る舞いではありません。

その代わりに新しい特殊メソッド @code{__index__()} が追加されました。これは引数を取らずに、スライスの添え字として使われる整数を返します。例えば:

@example
class C:
    def __index__ (self):
        return self.value
@end example

戻り値は Python 整数または長整数でなければなりません。インタプリタは戻り値が正しいかどうかをチェックし、要求に合わない場合に @ref{198,,TypeError} を送出します。

A corresponding @ref{1636,,nb_index} slot was added to the C-level
@ref{1637,,PyNumberMethods} structure to let C extensions implement this protocol.
@code{PyNumber_Index(obj)} can be used in extension code to call the
@code{__index__()} function and retrieve its result.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 357

@item PEP 357@footnote{https://peps.python.org/pep-0357/} - スライシングのために任意のオブジェクトを使えるようにする

PEP 著と実装 Travis Oliphant.
@end table


@c ======================================================================

@node その他の言語変更<16>,新たなモジュール、改良されたモジュール、削除されたモジュール,PEP 357 '__index__' メソッド,What's New in Python 2 5
@anchor{whatsnew/2 5 other-lang}@anchor{1638}@anchor{whatsnew/2 5 other-language-changes}@anchor{1639}
@subsection その他の言語変更


以下が、Python 2.5 言語コアに加えられた全ての変更点です。


@itemize *

@item 
@ref{183,,dict} 型に新たなフックが追加されています。サブクラスが、辞書に含まれないキーに対してデフォルトを提供出来るようにするものです。キーが見つからない場合、辞書の @code{__missing__(key)} メソッドが呼ばれます。このフックは @ref{1e,,collections} モジュール内の新しいクラス @code{defaultdict} で使われています。続く例は存在しないキーに対してゼロを返す辞書を定義しています:

@example
class zerodict (dict):
    def __missing__ (self, key):
        return 0

d = zerodict(@{1:1, 2:2@})
print d[1], d[2]   # Prints 1, 2
print d[3], d[4]   # Prints 0, 0
@end example

@item 
8 ビット文字列、Unicode ともに、ありがちなユースケースを単純化する  @code{partition(sep)} と @code{rpartition(sep)} が追加されました。

文字列のスライスに使うために @code{find(S)} メソッドを使ってインデクスを得るのだけれども、やりたいのはそのセパレータ(S)の前後の部分文字列を得ることだ、といったことはしょっちゅう必要になります。@code{partition(sep)} はこのパターンのコードを、一撃、に圧縮してくれます。これはセパレータ前の部分文字列、セパレータ自身、セパレータ後の部分文字列の 3 要素タプルを返します。セパレータが含まれない場合は、返却値の最初の要素に文字列全体が、残り2つは空文字列で返ります。@code{rpartition(sep)} もほぼ同じことをしますがセパレータの検索をお尻から始めます。 @code{r} は逆順('reverse')を表します。

いくつかの例です:

@example
>>> ('http://www.python.org').partition('://')
('http', '://', 'www.python.org')
>>> ('file:/usr/share/doc/index.html').partition('://')
('file:/usr/share/doc/index.html', '@w{'}, '@w{'})
>>> (u'Subject: a quick question').partition(':')
(u'Subject', u':', u' a quick question')
>>> 'www.python.org'.rpartition('.')
('www.python', '.', 'org')
>>> 'www.python.org'.rpartition(':')
('@w{'}, '@w{'}, 'www.python.org')
@end example

(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)

@item 
文字列型の @code{startswith()} と @code{endswith()} メソッドが、チェックされる文字列のタプルを受け容れるようになりました:

@example
def is_image_file (filename):
    return filename.endswith(('.gif', '.jpg', '.tiff'))
@end example

(Implemented by Georg Brandl following a suggestion by Tom Lynn.)

@c RFE #1491485

@item 
ビルトイン関数 @ref{110b,,min()} と @ref{110c,,max()} に、 @code{sort()} における @code{key} に似たキーワード引数 @code{key} が追加されました。このパラメータには関数を与えます。これは一つの引数を取り、リスト内の全ての値に対して呼び出されます; @ref{110b,,min()}/@ref{110c,,max()} はこの関数を全要素に適用したもののなかでの最小値/最大値を返します。例えば、リスト中の最長の文字列を探すにはこのように出来ます:

@example
L = ['medium', 'longest', 'short']
# Prints 'longest'
print max(L, key=len)
# Prints 'short', because lexicographically 'short' has the largest value
print max(L)
@end example

(Contributed by Steven Bethard and Raymond Hettinger.)

@item 
2 つの新たなビルトイン関数 @ref{163a,,any()} と @ref{163b,,all()} は、イテレータがいくつか真を含むかどうかを評価します。 @ref{163a,,any()} はイテレータのいずれかが返す値が真と評価される場合に @ref{e07,,True} を返し、そうでなければ @ref{d2b,,False} を返します。 @ref{163b,,all()} はイテレータが返す値の評価が真のみの場合に @ref{e07,,True} を返します。 (Suggested by Guido van Rossum, and implemented by Raymond Hettinger.)

@item 
クラスの @code{__hash__()} メソッドが返す値として、長整数と整数のどちらでも良くなりました。長整数が返されれば、その値のハッシュから取られます。以前のバージョンではこれは普通の整数であることが要求されていましたが、2.5 ではビルトイン関数 @ref{163c,,id()} が変更されて常に非負数が返り、ユーザはしばしば @code{__hash__()} 内で @code{id(self)} を使うようです (これはお奨めしませんが)。 (---訳注: 不思議な論法で意味がわかりません。id が非負を返すとなぜユーザは __hash__ の実装に使おうとするのか? ユーザがそれをしてしまうのは単にデフォルト実装がそうだから、というだけではないかと思います。__cmp__, __eq__ が「身元」以外の意味を使って比較を行うならば、 __cmp__ で id を使うのはシンプルに「ダメ」でしょう。--)

@c Bug #1536021

@item 
モジュールのデフォルトエンコーディングが ASCII になりました(訳注: Python 3 からはデフォルトは utf-8 (PEP 3120))。8 ビット文字を含んでいるのにエンコーディング宣言がないモジュールが構文エラーになるようになりました。Python 2.4 では構文エラーとはならず警告でした。モジュールのエンコーディングをする方法については 
@geindex Python Enhancement Proposals; PEP 263
PEP 263@footnote{https://peps.python.org/pep-0263/} を参照してください; 例えば、ソースコードの先頭付近にこのような行を追加することで出来ます:

@example
# -*- coding: latin1 -*-
@end example

@item 
Unicode 文字列とデフォルトの ASCII エンコーディングで Unicode に変換出来ない 8 ビット文字列との比較を試みると、新しい警告 @ref{163d,,UnicodeWarning} が引き起こされるようになっています。比較結果は偽です:

@example
>>> chr(128) == unichr(128)   # Can't convert chr(128) to Unicode
__main__:1: UnicodeWarning: Unicode equal comparison failed
  to convert both arguments to Unicode - interpreting them
  as being unequal
False
>>> chr(127) == unichr(127)   # chr(127) can be converted
True
@end example

以前はこれは @ref{c08,,UnicodeDecodeError} を起こしていましたので、2.5 でのこれは辞書のアクセス時に悩ましい問題をもたらしました。キーとして使われている @code{unichr(128)} や @code{chr(128)} を探そうとすると @ref{c08,,UnicodeDecodeError} 例外が起こっていたでしょう。2.5 での、 辞書を実装している @code{dictobject.c} のほかの変更により、これは揉み消すのではなく、引き続き例外を起こします(訳注: 原文では this exception といっているので @ref{c08,,UnicodeDecodeError} が起こるように読めるのですが、2.5 時点での振る舞いは確認出来ていませんが 2.7 では @ref{163d,,UnicodeWarning} とともに @ref{5e7,,KeyError} が発生する、のようになるはずです。2.6 以降の What's New でのこれに関する言及はありませんが変更があったのかもしれません)。

この種の比較で例外を起こすのは完全に正しいことではあるものの、その変更はコードを破壊するかもしれないので、必要に応じて警告に出来るよう導入されたのが @ref{163d,,UnicodeWarning} です。

(Implemented by Marc-André Lemburg.)

@item 
Python プログラマがよくしでかす間違いとして、パッケージディレクトリに @code{__init__.py} を入れ忘れる、というものがあります。この間違いのデバッグはややこしく、大抵 Python を @ref{163e,,-v} スイッチ付きで起動して、パス検索全てをログ出力するハメになります。Python 2.5 ではパッケージディレクトリに @code{__init__.py} がないことが検出されると新たに @ref{71e,,ImportWarning} 警告を出すようになりました。デフォルトではこの警告は黙って無視されます; これを出したければ、 @ref{ac6,,-Wd} スイッチをつけて Python を起動してください。(Implemented by Thomas Wouters.)

@item 
クラス定義において、基底クラスのリストを空リストに出来るようになっています(訳注: object を派生しないので結果として旧スタイルクラスになります)。例えば以下は今や合法です:

@example
class C():
    pass
@end example

(Implemented by Brett Cannon.)
@end itemize

@c ======================================================================

@menu
* 対話的なインタプリタの変更:: 
* 最適化: 最適化<16>. 

@end menu

@node 対話的なインタプリタの変更,最適化<16>,,その他の言語変更<16>
@anchor{whatsnew/2 5 interactive}@anchor{163f}@anchor{whatsnew/2 5 interactive-interpreter-changes}@anchor{1640}
@subsubsection 対話的なインタプリタの変更


対話的なインタプリタ内では、 @code{quit} と @code{exit}  はずっと、立ち去ろうと(quit しようと)試みてそうタイプしてしまうユーザにとってある種有用な文字列になっていました:

@example
>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
@end example

Python 2.5 でも @code{quit} と @code{exit} はそれ自身そのような文字列を生成はしますが、同時に「呼び出す」ことが出来るオブジェクトになっています。初心者が思わず @code{quit()} や @code{exit()} してしまった場合、今では彼らが期待する通りにインタプリタが終了します。  (Implemented by Georg Brandl.)

Python 実行形式ファイルが標準的な長い形式の @ref{806,,--help} と @ref{f17,,--version} を受け付けるようになりました。Windows の場合はヘルプメッセージを出力するのに @ref{1641,,/?} オプションも受け付けます。(Implemented by Georg Brandl.)

@c ======================================================================

@node 最適化<16>,,対話的なインタプリタの変更,その他の言語変更<16>
@anchor{whatsnew/2 5 optimizations}@anchor{1642}@anchor{whatsnew/2 5 opts}@anchor{1643}
@subsubsection 最適化


この最適化のいくつかは、2006年5月21日から28日にかけてアイスランドのレイキャビクで開催されたイベント、NeedForSpeed sprintで開発されました。このスプリントはCPythonの実装のスピードアップに焦点を当て、EWT LLCが資金を提供し、CCP Gamesが現地でサポートしました。 このスプリントで追加された最適化については、以下のリストで特別にマークしています。


@itemize *

@item 
Python 2.4 が導入されたとき、組み込みの @ref{184,,set} と @ref{7f2,,frozenset} 型は Python の辞書型の上に構築されたものでした。 Python 2.5 では、内部データ構造がセットを実装するためにカスタマイズされ、その結果、セットのメモリ使用量は3分の1になり、多少高速化されました。(Raymond Hettinger による実装。)

@item 
部分文字列の検索、文字列の分割、文字マップのエンコードとデコードなど、いくつかの Unicode 操作の速度が改善されました。 (部分文字列の検索と分割は、NeedForSpeed スプリントで Fredrik Lundh と Andrew Dalke が追加しました。部分文字列の検索と分割の改良は、NeedForSpeed sprintでFredrik LundhとAndrew Dalkeによって追加されました。文字マップは Walter Dörwald と Martin von Löwis によって改善されました。)

@c Patch 1313939, 1359618

@item 
The @code{long(str, base)} function is now faster on long digit strings
because fewer intermediate results are calculated.  The peak is for strings of
around 800--1000 digits where  the function is 6 times faster. (Contributed by
Alan McIntyre and committed at the NeedForSpeed sprint.)

@c Patch 1442927

@item 
It's now illegal to mix iterating over a file  with @code{for line in file} and
calling  the file object's @code{read()}/@ref{bf,,readline()}/@code{readlines()}
methods.  Iteration uses an internal buffer and the  @code{read*()} methods
don't use that buffer.   Instead they would return the data following the
buffer, causing the data to appear out of order.  Mixing iteration and these
methods will now trigger a @ref{2ec,,ValueError} from the @code{read*()} method.
(Implemented by Thomas Wouters.)

@c Patch 1397960

@item 
The @ref{db,,struct} module now compiles structure format  strings into an
internal representation and caches this representation, yielding a 20% speedup.
(Contributed by Bob Ippolito at the NeedForSpeed sprint.)

@item 
@ref{be,,re} モジュールは、システムの @code{malloc()} と @code{free()} の代わりに Python のアロケータ関数に切り替えることで、1～2%のスピードアップを達成しました。(NeedForSpeed sprintにてJack Diederichによるコントリビュート)

@item 
コードジェネレータの peephole オプティマイザは式の中で簡単な定数の折りたたみを実行するようになりました。 @code{a = 2+3} のように書くと、コードジェネレータは算術演算を行い、 @code{a = 5} に対応するコードを生成します。 (Raymond Hettinger による提案と実装。)

@item 
Function calls are now faster because code objects now keep  the most recently
finished frame (a "zombie frame") in an internal field of the code object,
reusing it the next time the code object is invoked.  (Original patch by Michael
Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed
sprint.)  Frame objects are also slightly smaller, which may improve cache
locality and reduce memory usage a bit.  (Contributed by Neal Norwitz.)

@c Patch 876206

@c Patch 1337051

@item 
Python's built-in exceptions are now new-style classes, a change that speeds
up instantiation considerably.  Exception handling in Python 2.5 is therefore
about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and
Sean Reifschneider at the NeedForSpeed sprint.)

@item 
Importing now caches the paths tried, recording whether  they exist or not so
that the interpreter makes fewer  @code{open()} and @code{stat()} calls on
startup. (Contributed by Martin von Löwis and Georg Brandl.)

@c Patch 921466
@end itemize

@c ======================================================================

@node 新たなモジュール、改良されたモジュール、削除されたモジュール,ビルドならびに C API の変更<10>,その他の言語変更<16>,What's New in Python 2 5
@anchor{whatsnew/2 5 modules}@anchor{1644}@anchor{whatsnew/2 5 new-improved-and-removed-modules}@anchor{1645}
@subsection 新たなモジュール、改良されたモジュール、削除されたモジュール


標準ライブラリは Python 2.5 で数多くの拡張とバグフィックスを行っています。ここでは注目に値する変更をモジュール名の辞書順で列挙します。変更についてのもっと完全なリストが見たければソースツリーの @code{Misc/NEWS} を調べるか、全ての詳細について SVN ログに目を通してみてください。


@itemize *

@item 
The @code{audioop} module now supports the a-LAW encoding, and the code for
u-LAW encoding has been improved.  (Contributed by Lars Immisch.)

@item 
@ref{1c,,codecs} モジュールに漸増的コーデックのサポートが追加されています。 @code{codec.lookup()} 関数がタプルではなく @code{CodecInfo} を返すようになっています。 @code{CodecInfo} のインスタンスは後方互換性を維持するために 4 要素タプルのように振舞うだけでなく、属性 @code{encode}, @code{decode}, @code{incrementalencoder}, @code{incrementaldecoder}, @code{streamwriter}, @code{streamreader} を持ちます。漸増的コーデックは入力を受け取って出力するのを複数チャンクに分けて行えます; 出力は非漸増的コーデックに一回で入力全体を渡したものと同じになります。詳細は @ref{1c,,codecs} モジュールのドキュメントを参照して下さい。 (Designed and implemented by Walter Dörwald.)

@c Patch  1436130

@item 
@ref{1e,,collections} モジュールに新たに追加された @code{defaultdict} 型は、標準 @ref{183,,dict} のサブクラスです。この新しい型はほとんど辞書と同じに振る舞い、ただし、キーを要求された際にそのキーが存在していなかった場合に、自動的に辞書にデフォルト値を追加します。

@code{defaultdict} のコンストラクタの最初の引数は、キーが要求されて存在しない場合に呼び出されるファクトリ関数です。ファクトリ関数は引数を取りません。つまりこれに該当する @ref{24d,,list()} や @ref{19b,,int()} のようなビルトイン型のコンストラクタも使えます。例えば、その頭文字を基準に語の索引をこのように作ることが出来ます:

@example
words = """Nel mezzo del cammin di nostra vita
mi ritrovai per una selva oscura
che la diritta via era smarrita""".lower().split()

index = defaultdict(list)

for w in words:
    init_letter = w[0]
    index[init_letter].append(w)
@end example

@code{index} を出力するとこんな具合です:

@example
defaultdict(<type 'list'>, @{'c': ['cammin', 'che'], 'e': ['era'],
        'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
        'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
        'p': ['per'], 's': ['selva', 'smarrita'],
        'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']@}
@end example

(Contributed by Guido van Rossum.)

@item 
@ref{1e,,collections} モジュールで提供されている両端キュー (double-ended queue) 型 @code{deque} に、キュー内で最初に現れる `value' を削除するメソッド @code{remove(value)} メソッドが追加されています。 `value' が見つからなければ @ref{2ec,,ValueError} が送出されます。 (Contributed by Raymond Hettinger.)

@item 
新規モジュール: @ref{27,,contextlib} モジュールには '@ref{186,,with}' ステートメントで使えるヘルパ関数が含まれています。詳細は @ref{162d,,contextlib モジュール} をみてください。

@item 
新規モジュール: @ref{2b,,cProfile} モジュールは既存の @ref{b4,,profile} モジュールの C 実装で、遥かに小さなオーバヘッドで実行出来ます。モジュールのインターフェイスは @ref{b4,,profile} と同じです: 関数をプロファイルするのには @code{cProfile.run('main()')} と実行し、プロファイル結果をファイルに書き出すなど出来ます。これは Hotshot プロファイラとして知られるものではないですが (これも C で書かれてますが @ref{b4,,profile} モジュールのインターフェイスとは別物です)、将来バージョンの Python で保守が続けられる予定です。(Contributed by Armin Rigo.)

また、プロファイラによる計測データの解析のための @ref{b5,,pstats} モジュールが、 @code{Stats} コンストラクタの `stream' 引数による直接ファイル出力に対応しました。 (Contributed by Skip Montanaro.)

@item 
The @ref{2d,,csv} module, which parses files in comma-separated value format,
received several enhancements and a number of bugfixes.  You can now set the
maximum size in bytes of a field by calling the
@code{csv.field_size_limit(new_limit)} function; omitting the `new_limit'
argument will return the currently set limit.  The @code{reader} class now has
a @code{line_num} attribute that counts the number of physical lines read from
the source; records can span multiple physical lines, so @code{line_num} is not
the same as the number of records read.

CSV パーサは引用符内のマルチラインをより厳密に扱うようになっています。以前は、引用符で囲まれたフィールドが改行文字(newline)で終了することなく終端すると、改行文字が返却フィールドに追加されていました。この振る舞いはフィールドに復帰文字(carriage return)を含んだファイルを読み込む際に問題だったため、改行文字を挿入することなくフィールドを返すように変更されました。このことにより、フィールド内に埋め込まれた改行文字が重要な場合、入力は改行文字が保存される方法で行分割されるはずです。(---訳注: リファレンスも含めこの説明の表現がわかりにくいです。行指向で読み込む場合改行コードのモード(NL, CR NL, CR)依存で「物理行が終了した」とみなされるわけですが、このモード依存(CR 時)の振る舞いがなくなった、ということです。---)

(Contributed by Skip Montanaro and Andrew McNamara.)

@item 
The @ref{4e2,,datetime} class in the @ref{34,,datetime}  module now has a
@code{strptime(string, format)}  method for parsing date strings, contributed
by Josh Spoerri. It uses the same format characters as @ref{1646,,time.strptime()} and
@ref{1402,,time.strftime()}:

@example
from datetime import datetime

ts = datetime.strptime('10:13:15 2006-03-07',
                       '%H:%M:%S %Y-%m-%d')
@end example

@item 
@ref{3b,,difflib} モジュールのメソッド @code{SequenceMatcher.get_matching_blocks()} が、合致するサブシーケンスを記述するブロックについて、最小範囲リストを返すよう保障するようになりました。以前は時折 2 つのリストエントリに合致要素ブロックが分割されることがありました。(Enhancement by Tim Peters.)

@item 
@ref{3e,,doctest} モジュールに、実行されるべきものから例を守る @code{SKIP} オプションが追加されています。これは、読者のための使用例として意図しているけれども実際のテストケースとして意図していないようなコードスニペットのために用意されました。

@code{testfile()} 関数と @code{DocFileSuite} にファイルのエンコーディングを指定するための `encoding' パラメータが追加されました。これにより docstring 内に非 ASCII 文字列を含むテストが簡単になります。(Contributed by Bjorn Tillenius.)

@c Patch 1080727

@item 
@ref{3f,,email} パッケージがバージョン 4.0 にアップデートされました (Contributed by Barry Warsaw.)

@c XXX need to provide some more detail here

@geindex universal newlines;What's new

@item 
The @ref{5f,,fileinput} module was made more flexible. Unicode filenames are now
supported, and a `mode' parameter that defaults to @code{"r"} was added to the
@ref{14f0,,input()} function to allow opening files in binary or @ref{f35,,universal newlines} mode.  Another new parameter, `openhook', lets you use a function
other than @ref{316,,open()}  to open the input files.  Once you're iterating over
the set of files, the @code{FileInput} object's new @ref{1647,,fileno()} returns
the file descriptor for the currently opened file. (Contributed by Georg
Brandl.)

@item 
@ref{64,,gc} モジュールに、新しい関数 @code{get_count()} が追加されています。これは GC 3 世代についての現在の検出を含む 3 要素タプルを返します。これはガーベージコレクタの決算情報です; これらの数が指定された閾値に到達すると、ガーベージコレクトのスイープが起こります。既存の @ref{1b3,,gc.collect()} 関数は省略可能な `generation' 引数を取るようになっていて、これはどの世代を検出するかを指定する 0、1、2 です。 (Contributed by Barry Warsaw.)

@item 
@ref{6d,,heapq} モジュールの @code{nsmallest()} 関数と @code{nlargest()} 関数がキーワードパラメータ @code{key} をサポートするようになっています。これは @ref{110b,,min()}/@ref{110c,,max()} 関数と @code{sort()} メソッドで提供されているものと似たものです。例えば:

@example
>>> import heapq
>>> L = ["short", 'medium', 'longest', 'longer still']
>>> heapq.nsmallest(2, L)  # Return two lowest elements, lexicographically
['longer still', 'longest']
>>> heapq.nsmallest(2, L, key=len)   # Return two shortest elements
['short', 'medium']
@end example

(Contributed by Raymond Hettinger.)

@item 
@ref{d43,,itertools.islice()} 関数が start と step として @code{None} を受け付けるようになっています。これは slice オブジェクトとの互換性を高めるもので、つまり以下のように書くことが出来ます:

@example
s = slice(5)     # Create slice object
itertools.islice(iterable, s.start, s.stop, s.step)
@end example

(Contributed by Raymond Hettinger.)

@item 
@ref{8a,,locale} モジュールの @ref{199,,format()} 関数が更新され、2 つの関数 @code{format_string()} と @code{currency()} が追加されました。

@ref{199,,format()} 関数の `val' パラメータは以前は一つ以上の %文字指定子が現れる文字列が許されていました; 今はこのパラメータは正確に一つの %文字指定子を含む、周りに囲むテキストのない文字列でなければなりません。省略可能な `monetary' パラメータも追加されています。これが @code{True} の場合、通貨の書式化の 3 桁ごとに区切るセパレータに、ロケールのルールを使います。

複数 %文字指定子を含む文字列をフォーマットするには、 @ref{199,,format()} のように働き、任意のテキストと %文字指定子を混ぜた文字列をサポートする新しい @code{format_string()} 関数を使ってください。

現在ロケール設定に関連した数字を書式化する @code{currency()} 関数も追加されています。

(Contributed by Georg Brandl.)

@c Patch 1180296

@item 
@ref{8f,,mailbox} モジュールでは、メールボックスについてそれを読むことに加えて修正出来る能力を追加するための、大々的な書き換えが行われています。 @code{mbox}, @code{MH}, @code{Maildir} を含む新しいクラス群はメールボックス読み込みに使われますが、メッセージ追加のための @code{add(message)} 、削除の @code{remove(key)} 、ロック/アンロックのための @code{lock()}/@code{unlock()} も持っています。続く例は maildir 形式から mbox 形式に変換する例です:

@example
import mailbox

# 'factory=None' uses email.Message.Message as the class representing
# individual messages.
src = mailbox.Maildir('maildir', factory=None)
dest = mailbox.mbox('/tmp/mbox')

for msg in src:
    dest.add(msg)
@end example

(Contributed by Gregory K. Johnson.  Funding was provided by Google's 2005
Summer of Code.)

@item 
New module: the @code{msilib} module allows creating Microsoft Installer
@code{.msi} files and CAB files.  Some support for reading the @code{.msi}
database is also included. (Contributed by Martin von Löwis.)

@item 
The @code{nis} module now supports accessing domains other than the system
default domain by supplying a `domain' argument to the @code{nis.match()} and
@code{nis.maps()} functions. (Contributed by Ben Bell.)

@item 
@ref{a3,,operator} モジュールの @code{itemgetter()} 関数と @code{attrgetter()} 関数が複数フィールドをサポートするようになりました。 @code{operator.attrgetter('a', 'b')} のように呼び出すと、 @code{a} と @code{b} 属性を取り出す関数を返します。この新機能と @code{sort()} メソッドの @code{key} パラメータを組み合わせると、複数フィールドでのリストのソートが簡単になります。

@item 
@ref{a4,,optparse} モジュールが Optik ライブラリのバージョン 1.5.1 に更新されました。 @code{OptionParser} クラスに @code{epilog} 属性と @code{destroy()} メソッドが追加されています。前者はヘルプメッセージのあとに出力される文字列です。後者はオブジェクトによって作られた循環参照を破棄します。 (Contributed by Greg Ward.)

@item 
@ref{a5,,os} モジュールに多数の変更がありました。 @code{stat_float_times} 値のデフォルトが真となっていて、これはつまり @ref{26d,,os.stat()} が時刻の値を浮動小数点数で返すということです。(ただし必ずしも @ref{26d,,os.stat()} が秒の端数が正確な値を返すという意味ではありません; 全てのシステムがそのような精度をサポートしてはいません。)

Constants named @ref{14a5,,os.SEEK_SET}, @ref{14a6,,os.SEEK_CUR}, and
@ref{14a7,,os.SEEK_END} have been added; these are the parameters to the
@ref{132f,,os.lseek()} function.  Two new constants for locking are
@ref{1648,,os.O_SHLOCK} and @ref{1649,,os.O_EXLOCK}.

2 つの新しい関数 @code{wait3()} と @code{wait4()} が追加されています。これらは @code{waitpid()} 関数に似ています。これは子プロセスが終了するのを待ってプロセス ID とその終了コードを返しますが、 @code{wait3()} と @code{wait4()} は追加の情報を返します。 @code{wait3()} はプロセス ID を入力に取りませんので任意の子プロセス終了を待ち、 @ref{164a,,resource.getrusage()} 関数から返る `process-id', `exit-status', `resource-usage' の 3 要素タプルを返します。 @code{wait4(pid)} はプロセス ID を取ります。 (Contributed by Chad J. Schroeder.)

FreeBSD では、 @ref{26d,,os.stat()} 関数がナノ秒精度の時刻を返し、また、返却オブジェクトが @code{st_gen} と @code{st_birthtime} を持つようになっています。 @code{st_flags} 属性も、プラットフォームがサポートされている場合には利用可能です。 (Contributed by Antti Louko and Diego Pettenò.)

@c (Patch 1180695, 1212117)

@item 
@ref{aa,,pdb} モジュールで提供される Python デバッガが、ブレイクポイントに到達して実行が停止する際に実行するコマンドのリストを記憶するようになりました。ブレイクポイント #1 を作ったら、 @code{commands 1} を入力し、実行するコマンド群を入力し、 @code{end} でリストを終えます。コマンドリストには @code{continue} や @code{next} のような実行再開コマンドを含めることが出来ます。 (Contributed by Grégoire Dooms.)

@c Patch 790710

@item 
The @ref{ab,,pickle} and @code{cPickle} modules no longer accept a return value
of @code{None} from the @ref{bc6,,__reduce__()} method; the method must return a tuple
of arguments instead.  The ability to return @code{None} was deprecated in Python
2.4, so this completes the removal of the feature.

@item 
The @ref{ae,,pkgutil} module, containing various utility functions for finding
packages, was enhanced to support 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/}'s import hooks and now also works for
packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.)

@item 
Marc-André Lemburg による pybench ベンチマークスイートが @code{Tools/pybench} ディレクトリに含まれるようになりました。pybench スイートは、広く使われている @code{pystone.py} プログラムの改善版で、インタプリタの速度についてのより詳しい計測を行います。 @code{pystone.py} のように多くの異なる演算を実行したり単独の数字に縮退する代わりに、これは関数コール、タプルのスライス、メソッドの検索、数値演算のような特定の演算を計測します。 (---訳注: Tools についての言及すべてに共通することですが、原則として Tools は「全て」を入手する手段はソースコード配布を利用することだけです。インストールされるものはプラットフォーム依存や linux であればディストリビュータによっても変わります。顕著なのは Windows で、Tools 配下のものはごく限られたものだけがインストールされます。pybench もソースコード配布物にのみ含まれ、Windows 公式インストーラではインストールされません。なお、 @code{pystone.py} は Lib/test 内にあります。---)

@item 
@code{pyexpat} モジュールが使う Expat パーサをバージョン 2.0 にしました。 (Contributed by Trent Mick.)

@item 
The @ref{15ac,,Queue} class provided by the @code{Queue} module gained two new
methods.  @code{join()} blocks until all items in the queue have been retrieved
and all processing work on the items  have been completed.  Worker threads call
the other new method,  @code{task_done()}, to signal that processing for an item
has been completed.  (Contributed by Raymond Hettinger.)

@item 
古い @code{regex}, @code{regsub} モジュール、これは Python 2.0 からずっと非推奨になっていましたが、ついに削除されました。ほかにも、 @code{statcache}, @code{tzparse}, @code{whrandom} が削除されています。

@item 
@code{dircmp} や @code{ni} といった石器時代のモジュールを大事にしまっていた @code{lib-old} ディレクトリも削除されました。  @code{lib-old} がデフォルトで @code{sys.path} に含まれることはなかったので、あなたが明示的にそれを @code{sys.path} に入れてこなかった限り、この削除はあなたには関係ないでしょう。

@item 
@ref{c2,,rlcompleter} モジュールが @ref{bf,,readline} モジュールのインポートに依存しないようになりました。これにより非 Unix プラットフォームで動作するようになりました。 (Patch from Robert Kiendl.)

@c Patch #1472854

@item 
The @ref{135,,SimpleXMLRPCServer} and @ref{135,,DocXMLRPCServer}  classes now have a
@code{rpc_paths} attribute that constrains XML-RPC operations to a limited set
of URL paths; the default is to allow only @code{'/'} and @code{'/RPC2'}.  Setting
@code{rpc_paths} to @code{None} or an empty tuple disables  this path checking.

@c Bug #1473048

@item 
The @ref{d1,,socket} module now supports @code{AF_NETLINK} sockets on Linux,
thanks to a patch from Philippe Biondi.   Netlink sockets are a Linux-specific
mechanism for communications between a user-space process and kernel code; an
introductory  article about them is at @indicateurl{https://www.linuxjournal.com/article/7356}.
In Python code, netlink addresses are represented as a tuple of 2 integers,
@code{(pid, group_mask)}.

ソケットオブジェクトの 2 つの新たなメソッド、 @code{recv_into(buffer)}, @code{recvfrom_into(buffer)} は、受信データを、文字列データとして返す代わりにバッファプロトコルをサポートするオブジェクトに書き込みます。このことにより、受信データを直接 array やメモリマップドファイルに置けます。

ソケットオブジェクトには @code{getfamily()}, @code{gettype()}, @code{getproto()} アクセッサメソッドも追加されています。それぞれソケットについてのアドレスファミリ、タイプ、プロトコルを取得します。

@item 
New module: the @code{spwd} module provides functions for accessing the shadow
password database on systems that support  shadow passwords.

@item 
@code{pack()}, @code{unpack()} メソッドでフォーマット文字列を @code{Struct} オブジェクトにコンパイルすることで、 @ref{db,,struct} がより高速になっています。これは @ref{be,,re} モジュールでコンパイル済み正規表現オブジェクトを作れるのに似ています。モジュールレベルの @code{pack()}, @code{unpack()} 関数もそのまま使えます; それらは @code{Struct} オブジェクトを作ってキャッシュします。あるいは @code{Struct} インスタンスを直接使えます:

@example
s = struct.Struct('ih3s')

data = s.pack(1972, 187, 'abc')
year, number, name = s.unpack(data)
@end example

You can also pack and unpack data to and from buffer objects directly using the
@code{pack_into(buffer, offset, v1, v2, ...)} and @code{unpack_from(buffer,
offset)} methods.  This lets you store data directly into an array or a
memory-mapped file.

(@code{Struct} objects were implemented by Bob Ippolito at the NeedForSpeed
sprint.  Support for buffer objects was added by Martin Blais, also at the
NeedForSpeed sprint.)

@item 
Python デベロッパは 2.5 開発プロセスの間で CVS から Subversion に移行しました。ビルドバージョンについての正確な情報は @code{sys.subversion} により取得可能で、これは 3 要素タプル @code{(interpreter-name, branch-name, revision-range)} です。例えば執筆時点では 2.5 で @code{('CPython', 'trunk', '45313:45315')} を返します。 (---訳注: Python 3.2 から 3.3 にかけて、開発が Mercurial に移行していて、これは 2.7 メンテナンスリリースの間にあたります。今(3.6 dev 時点)では全て Mercurial に移行しており、 @code{sys.subversion} は今では意味のある値は返しません。3.3 からは既に @code{sys.subversion} は削除されています。---)

この情報は C 拡張から @ref{164b,,Py_GetBuildInfo()} 関数を使っても得ることが出来ます。これはビルド情報についての文字列を返し、例えば @code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"} のような値です。 (Contributed by Barry Warsaw.)

@item 
もう一つの新規関数 @ref{164c,,sys._current_frames()} は、実行スレッドについての現在スタックフレームを、各スレッドの識別子がキーの辞書として返します。辞書の値は、関数が呼ばれた時点のそのスレッドで現在アクティブになっているスタックフレームの一番上です。(Contributed by Tim Peters.)

@item 
@ref{e4,,tarfile} モジュールの @code{TarFile} クラスに @code{extractall()} メソッドが追加されました。アーカイブから全てのメンバをカレントディレクトリに抽出します。抽出ターゲットとして別のディレクトリも指定できますし、アーカイブメンバのサブセットのみ解凍することも出来ます。

ストリームモードで開く tarfile に使われる圧縮を、モード @code{'r|*'} を使って自動で検出出来るようになっています。 (Contributed by Lars Gustäbel.)

@c patch 918101

@item 
@ref{f3,,threading} モジュールで、新しいスレッドを作る際に使われるスタックサイズを設定出来るようになりました。 @code{stack_size([*size*])} 関数は現在構成されているスタックサイズを返し、省略可能引数 `size' パラメータを与えると新しい値を設定します。全てのプラットフォームがスタックサイズ変更をサポートしているわけではなく、Windows、POSIX スレッド、OS/2 で可能です。 (Contributed by Andrew MacIntyre.)

@c Patch 1454481

@item 
The @ref{10b,,unicodedata} module has been updated to use version 4.1.0 of the
Unicode character database.  Version 3.2.0 is required  by some specifications,
so it's still available as  @ref{164d,,unicodedata.ucd_3_2_0}.

@item 
新モジュール: @ref{116,,uuid} モジュールは 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://datatracker.ietf.org/doc/html/rfc4122.html} による UUID (universally unique identifiers) を生成します。その RFC ではいくつかの異なる UUID のバージョンを定義しており、文字列から生成するもの、システム特性から生成するもの、純粋に乱数から生成するものがあります。このモジュールでは @code{UUID} クラスと @code{uuid1()}, @code{uuid3()}, @code{uuid4()}, @code{uuid5()} 関数を持っていて、それら異なったバージョンの UUID を生成します。(UUID バージョン 2 は 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://datatracker.ietf.org/doc/html/rfc4122.html} にありませんのでこのモジュールにもないです)

@example
>>> import uuid
>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
@end example

(Contributed by Ka-Ping Yee.)

@item 
@ref{11a,,weakref} モジュールの @code{WeakKeyDictionary} 型と @code{WeakValueDictionary} 型に、辞書内に含まれる弱参照を巡回する新たなメソッドが追加されています。 @code{iterkeyrefs()} と @code{keyrefs()} が @code{WeakKeyDictionary} に追加され、 @code{itervaluerefs()} と @code{valuerefs()} が @code{WeakValueDictionary} に追加されました。(Contributed by Fred L. Drake, Jr.)

@item 
The @ref{11b,,webbrowser} module received a number of enhancements. It's now
usable as a script with @code{python -m webbrowser}, taking a URL as the argument;
there are a number of switches  to control the behaviour (@code{-n} for a new
browser window,  @code{-t} for a new tab).  New module-level functions,
@code{open_new()} and @code{open_new_tab()}, were added  to support this.  The
module's @ref{316,,open()} 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.)

@c Patch #754022

@item 
The @ref{134,,xmlrpclib} module now supports returning  @ref{4e2,,datetime} objects
for the XML-RPC date type.  Supply  @code{use_datetime=True} to the @ref{164e,,loads()}
function or the @code{Unmarshaller} class to enable this feature. (Contributed
by Skip Montanaro.)

@c Patch 1120353

@item 
@ref{137,,zipfile} モジュールが ZIP64 バージョンのフォーマットをサポートしました。これで 4GiB を超える zip 書庫を作れ、4GiB を超えるファイルを書庫に含めることが出来ます。 (Contributed by Ronald Oussoren.)

@c Patch 1446489

@item 
@ref{139,,zlib} モジュールの @code{Compress} , @code{Decompress} オブジェクトが @ref{29,,copy()} メソッドをサポートするようになりました。オブジェクトの内部状態を複製して新しい @code{Compress} あるいは @code{Decompress} オブジェクトを返します。 (Contributed by Chris AtLee.)

@c Patch 1435422
@end itemize

@c ======================================================================

@menu
* ctypes パッケージ:: 
* ElementTree パッケージ:: 
* hashlib パッケージ:: 
* sqlite3 パッケージ:: 
* wsgiref パッケージ:: 

@end menu

@node ctypes パッケージ,ElementTree パッケージ,,新たなモジュール、改良されたモジュール、削除されたモジュール
@anchor{whatsnew/2 5 module-ctypes}@anchor{164f}@anchor{whatsnew/2 5 the-ctypes-package}@anchor{1650}
@subsubsection ctypes パッケージ


The @ref{2e,,ctypes} package, written by Thomas Heller, has been added  to the
standard library.  @ref{2e,,ctypes} lets you call arbitrary functions  in shared
libraries or DLLs.  Long-time users may remember the @code{dl} module, which
provides functions for loading shared libraries and calling functions in them.
The @ref{2e,,ctypes} package is much fancier.

シェアドライブラリや DLL をロードするには、 @code{CDLL} クラスのインスタンスを、その名前かパスを渡して構築します。構築したら、 @code{CDLL} オブジェクトの属性にアクセスすることで任意の関数呼び出しが出来ます:

@example
import ctypes

libc = ctypes.CDLL('libc.so.6')
result = libc.printf("Line of output\n")
@end example

Type constructors for the various C types are provided: @code{c_int()},
@code{c_float()}, @code{c_double()}, @code{c_char_p()} (equivalent to char*), and so forth.  Unlike Python's types, the C versions are all mutable; you
can assign to their @code{value} attribute to change the wrapped value.  Python
integers and strings will be automatically converted to the corresponding C
types, but for other types you  must call the correct type constructor.  (And I
mean `must';  getting it wrong will often result in the interpreter crashing
with a segmentation fault.)

C 関数がメモリ領域を更新するものである場合、Python 文字列に @code{c_char_p()} を使うべきではありません。 Python 文字列は @ref{15b9,,immutable} であることを前提としているからです; この規則を犯すことは頭を掻き毟るバグを引き起こすでしょう。更新可能なメモリ領域が必要な場合は @code{create_string_buffer()} を使います:

@example
s = "this is a string"
buf = ctypes.create_string_buffer(s)
libc.strfry(buf)
@end example

C 関数はデフォルトでは整数を返すと仮定されますが、関数オブジェクトの @code{restype} 属性をセットすることでこれを変更出来ます:

@example
>>> libc.atof('2.71828')
-1783957616
>>> libc.atof.restype = ctypes.c_double
>>> libc.atof('2.71828')
2.71828
@end example

@ref{2e,,ctypes} also provides a wrapper for Python's C API  as the
@code{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 @ref{1f3,,py_object} type
constructor that will create a  @ref{5df,,PyObject}* pointer.  A simple usage:

@example
import ctypes

d = @{@}
ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
          ctypes.py_object("abc"),  ctypes.py_object(1))
# d is now @{'abc', 1@}.
@end example

Don't forget to use @ref{1f3,,py_object()}; if it's omitted you end  up with a
segmentation fault.

@ref{2e,,ctypes} が周辺ライブラリとして登場してしばらく経ちますが、@ref{2e,,ctypes} が存在していることに依存できないとなれば人々はまだハードコードされた拡張モジュールを書いて配布します。 @ref{2e,,ctypes} が Python 中核に含められた今、おそらく開発者たちは、拡張モジュールの代わりに @ref{2e,,ctypes} を介してアクセスするライブラリの上に Python ラッパーを書き始めるでしょう,


@subsubheading 参考



@table @asis

@item @indicateurl{https://web.archive.org/web/20180410025338/http://starship.python.net/crew/theller/ctypes/}

The pre-stdlib ctypes web page, with a tutorial, reference, and FAQ.
@end table

@ref{2e,,ctypes} モジュールについてのドキュメント。


@c ======================================================================

@node ElementTree パッケージ,hashlib パッケージ,ctypes パッケージ,新たなモジュール、改良されたモジュール、削除されたモジュール
@anchor{whatsnew/2 5 module-etree}@anchor{1651}@anchor{whatsnew/2 5 the-elementtree-package}@anchor{1652}
@subsubsection ElementTree パッケージ


XML 処理のための、Fredrik Lundh の ElementTree ライブラリのサブセットが、標準ライブラリに @code{xml.etree} として追加されました。利用可能なモジュールは ElementTree 1.2.6 よりの @code{ElementTree}, @code{ElementPath}, @code{ElementInclude} です。 C 実装 @code{cElementTree} モジュールも含まれています。

The rest of this section will provide a brief overview of using ElementTree.
Full documentation for ElementTree is available at
@indicateurl{https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm}.

ElementTree は XML ドキュメントを、要素ノードのツリーとして表現します。ドキュメントのテキストコンテントは @code{text} 属性と @code{tail} 属性に格納されます (これが ElementTree と Document Object Model (DOM) との一番大きな違いです; DOM 内ではノードの数多くの型があります。 @code{TextNode} はその一つです。)

最も一般的に使う解析関数は @code{parse()} です。これは (ファイル名が含まれるとみなされる) 文字列またはファイルのようなオブジェクトを受け取って、 @code{ElementTree} インスタンスを返します:

@example
from xml.etree import ElementTree as ET

tree = ET.parse('ex-1.xml')

feed = urllib.urlopen(
          'http://planet.python.org/rss10.xml')
tree = ET.parse(feed)
@end example

@code{ElementTree} インスタンスを手にしてしまえば、あとはルートの @code{Element} ノードを得るために @code{getroot()} を呼び出せます。

文字列リテラルを受け取って (@code{ElementTree} ではなく) @code{Element} ノードを返す @code{XML()} 関数 もあります。この関数を使えば、簡単に XML リテラルを使って XML 断片からツリーを組み上げることが綺麗に出来ます:

@example
svg = ET.XML("""<svg width="10px" version="1.0">
             </svg>""")
svg.set('height', '320px')
svg.append(elem1)
@end example

個々の XML 要素はいくつかの辞書のような、いくつかのリストのようなメソッドをサポートしています。辞書的な操作は属性値のアクセスに使い、リスト的な操作は子ノードのアクセスに使います。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@item

@code{elem[n]}

@tab

n 番目の子要素を返す。

@item

@code{elem[m:n]}

@tab

m 番目から n 番目までの子要素を返す(---訳注: n は含まない---)。

@item

@code{len(elem)}

@tab

子要素数を返す。

@item

@code{list(elem)}

@tab

子要素のリストを返す。

@item

@code{elem.append(elem2)}

@tab

`elem2' を子として追加する。

@item

@code{elem.insert(index, elem2)}

@tab

指定された位置に `elem2' を挿入する。

@item

@code{del elem[n]}

@tab

n 番目の子要素を削除する。

@item

@code{elem.keys()}

@tab

属性名のリストを返す。

@item

@code{elem.get(name)}

@tab

属性 `name' の値を返す。

@item

@code{elem.set(name, value)}

@tab

属性 `name' に新しい値をセットする。

@item

@code{elem.attrib}

@tab

属性を含んだ辞書を取り出す。

@item

@code{del elem.attrib[name]}

@tab

属性 `name' を削除する。

@end multitable


コメントと処理命令 (processing instruction=PI) も、 @code{Element} ノードで表現されます。ノードがコメントあるいは処理命令であるかをチェックするにはこのようにします:

@example
if elem.tag is ET.Comment:
    ...
elif elem.tag is ET.ProcessingInstruction:
    ...
@end example

XML 出力を生成するには @code{ElementTree.write()} メソッドを呼び出す必要があります。 @code{parse()} のように、文字列もしくはファイルのようなオブジェクトを渡せます:

@example
# Encoding is US-ASCII
tree.write('output.xml')

# Encoding is UTF-8
f = open('output.xml', 'w')
tree.write(f, encoding='utf-8')
@end example

(警告: 出力に使われるデフォルトエンコーディングは ASCII です。一般的な XML での作業では要素名に任意の Unicode 文字を含められるので、ASCII エンコーディングはあまり役に立ちません。要素名に 127 より大きなどんな文字が含まれても例外となりますので。ですから任意の Unicode 文字を扱うために UTF-8 のようなエンコーディングを指定するのが吉です。)

このセクションでは  ElementTree インターフェイスのほんの一部しか記載していません。さらに詳しい情報については、パッケージの公式ドキュメントを参照して下さい。


@subsubheading 参考



@table @asis

@item @indicateurl{https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm}

ElementTree の公式ドキュメント
@end table


@c ======================================================================

@node hashlib パッケージ,sqlite3 パッケージ,ElementTree パッケージ,新たなモジュール、改良されたモジュール、削除されたモジュール
@anchor{whatsnew/2 5 module-hashlib}@anchor{1653}@anchor{whatsnew/2 5 the-hashlib-package}@anchor{1654}
@subsubsection hashlib パッケージ


A new @ref{6c,,hashlib} module, written by Gregory P. Smith,  has been added to
replace the @code{md5} and @code{sha} modules.  @ref{6c,,hashlib} adds support for
additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When
available, the module uses OpenSSL for fast platform optimized implementations
of algorithms.

The old @code{md5} and @code{sha} modules still exist as wrappers around hashlib
to preserve backwards compatibility.  The new module's interface is very close
to that of the old modules, but not identical. The most significant difference
is that the constructor functions for creating new hashing objects are named
differently.

@example
# Old versions
h = md5.md5()
h = md5.new()

# New version
h = hashlib.md5()

# Old versions
h = sha.sha()
h = sha.new()

# New version
h = hashlib.sha1()

# Hash that weren't previously available
h = hashlib.sha224()
h = hashlib.sha256()
h = hashlib.sha384()
h = hashlib.sha512()

# Alternative form
h = hashlib.new('md5')          # Provide algorithm as a string
@end example

ハッシュオブジェクトを作ってしまえばあとはそのメソッドは以前と同じです: @code{update(string)} は指定された文字列を現在のダイジェスト状態にハッシュ更新し、 @code{digest()} と @code{hexdigest()} は結果のダイジェスト値をバイナリ文字列・16進数表記文字列として返し、 @ref{29,,copy()} はダイジェスト状態を複製して新たなハッシュオブジェクトを作ります。


@subsubheading 参考


@ref{6c,,hashlib} モジュールについてのドキュメント。


@c ======================================================================

@node sqlite3 パッケージ,wsgiref パッケージ,hashlib パッケージ,新たなモジュール、改良されたモジュール、削除されたモジュール
@anchor{whatsnew/2 5 module-sqlite}@anchor{1655}@anchor{whatsnew/2 5 the-sqlite3-package}@anchor{1656}
@subsubsection sqlite3 パッケージ


The pysqlite module (@indicateurl{https://www.pysqlite.org}), a wrapper for the SQLite embedded
database, has been added to the standard library under the package name
@ref{d4,,sqlite3}.

SQLite は、軽量なディスク上のデータベースを提供する C ライブラリです。別のサーバプロセスを用意する必要なく、 SQL クエリー言語の非標準的な一種を使用してデータベースにアクセスできます。一部のアプリケーションは内部データ保存に SQLite を使えます。また、SQLite を使ってアプリケーションのプロトタイプを作り、その後そのコードを PostgreSQL や Oracle のような大規模データベースに移植するということも可能です。

pysqlite  は Gerhard Häring によって書かれ、 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} に記述された DB-API 2.0 仕様に準拠した SQL インターフェースを提供するものです。

ソースコードから Python をビルドする場合は注意してください。Python ソースツリーは SQLite コードを含まずラッパーモジュールのみを含んでいます。Python ビルド前に SQLite ライブラリとヘッダをインストールする必要があります。必要ヘッダが利用可能となっていればモジュールはビルドされます。

このモジュールを使うには、最初にデータベースを表す @code{Connection} オブジェクトを作ります。ここではデータはファイル @code{/tmp/example} に格納されているものとします。

@example
conn = sqlite3.connect('/tmp/example')
@end example

特別な名前である @code{:memory:} を使うと RAM 上にデータベースを作ることもできます。

@code{Connection} があれば、 @code{Cursor} オブジェクトを作りその @code{execute()} メソッドを呼んで SQL コマンドを実行することができます:

@example
c = conn.cursor()

# Create table
c.execute('@w{'}'create table stocks
(date text, trans text, symbol text,
 qty real, price real)'@w{'}')

# Insert a row of data
c.execute("""insert into stocks
          values ('2006-01-05','BUY','RHAT',100,35.14)""")
@end example

たいてい、SQL 操作は Python 変数の値を使う必要があります。この時、クエリーを Python の文字列操作を使って構築することは、安全とは言えないので、すべきではありません。そのようなことをするとプログラムが SQL インジェクション攻撃に対し脆弱になりかねません。

代わりに、DB-API のパラメータ割り当てを使います。 @code{?} を変数の値を使いたいところに埋めておきます。その上で、値のタプルをカーソルの @code{execute()} メソッドの第2引数として引き渡します。(他のデータベースモジュールでは変数の場所を示すのに @code{%s} や @code{:1} などの異なった表記を用いることがあります。) 例を示します:

@example
# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)

# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)

# Larger example
for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ):
    c.execute('insert into stocks values (?,?,?,?,?)', t)
@end example

SELECT 文を実行した後データを取得する方法は3つありどれを使っても構いません。一つはカーソルをイテレータ (@ref{4c8,,iterator}) として扱う、一つはカーソルの @code{fetchone()} メソッドを呼んで一致した内の一行を取得する、もう一つは @code{fetchall()} メソッドを呼んで一致した全ての行のリストとして受け取る、という3つです。

以下の例ではイテレータの形を使います:

@example
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
>>> for row in c:
...    print row
...
(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
>>>
@end example

SQLite でサポートされる SQL 方言についてもっと詳しく知りたければ、 @indicateurl{http://www.sqlite.org} を参照して下さい。


@subsubheading 参考



@table @asis

@item @indicateurl{https://www.pysqlite.org}

pysqlite のウェブページ。

@item @indicateurl{https://www.sqlite.org}

SQLite のウェブページ。ここの文書ではサポートされる SQL 方言の文法と使えるデータ型を説明しています。
@end table

@ref{d4,,sqlite3} モジュールについてのドキュメント。


@table @asis

@geindex Python Enhancement Proposals; PEP 249

@item PEP 249@footnote{https://peps.python.org/pep-0249/} - Database API Specification 2.0

Marc-Andre Lemburg により書かれた PEP。
@end table


@c ======================================================================

@node wsgiref パッケージ,,sqlite3 パッケージ,新たなモジュール、改良されたモジュール、削除されたモジュール
@anchor{whatsnew/2 5 module-wsgiref}@anchor{1657}@anchor{whatsnew/2 5 the-wsgiref-package}@anchor{1658}
@subsubsection wsgiref パッケージ


Web Server Gateway Interface (WSGI) v1.0 は、 Web サーバと Python で記述された Web アプリケーションとの標準インターフェースであり、 
@geindex Python Enhancement Proposals; PEP 333
PEP 333@footnote{https://peps.python.org/pep-0333/} で定義されています。  @ref{11e,,wsgiref} パッケージは WSGI 仕様のリファレンス実装です。

@c XXX should this be in a :pep:`333` section instead?

パッケージには WSGI アプリケーションとして動作する基礎的な HTTP サーバが含まれています; このサーバは製品ユースではないデバッグ目的に有用です。サーバをセットアップするには僅か数行で済みます:

@example
from wsgiref import simple_server

wsgi_app = ...

host = '@w{'}
port = 8000
httpd = simple_server.make_server(host, port, wsgi_app)
httpd.serve_forever()
@end example

@c XXX discuss structure of WSGI applications?

@c XXX provide an example using Django or some other framework?


@subsubheading 参考



@table @asis

@item @indicateurl{https://web.archive.org/web/20160331090247/http://wsgi.readthedocs.org/en/latest/}

WSGI 関連のリソースについて集約しているウェブサイト。

@geindex Python Enhancement Proposals; PEP 333

@item PEP 333@footnote{https://peps.python.org/pep-0333/} - Python Web Server Gateway Interface v1.0

PEP 著 Phillip J. Eby.
@end table


@c ======================================================================

@node ビルドならびに C API の変更<10>,Python 2 5 への移植,新たなモジュール、改良されたモジュール、削除されたモジュール,What's New in Python 2 5
@anchor{whatsnew/2 5 build-and-c-api-changes}@anchor{1659}@anchor{whatsnew/2 5 build-api}@anchor{165a}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
Python ソースツリーは CVS から Subversion に変換されました。この複雑な移行手続きは Martin von Löwis によって指揮されつつがなく遂行されました。この手続きは 
@geindex Python Enhancement Proposals; PEP 347
PEP 347@footnote{https://peps.python.org/pep-0347/} にて開発されました。

@item 
Coverity, a company that markets a source code analysis tool called Prevent,
provided the results of their examination of the Python source code.  The
analysis found about 60 bugs that  were quickly fixed.  Many of the bugs were
refcounting problems, often occurring in error-handling code.  See
@indicateurl{https://scan.coverity.com} for the statistics.

@item 
The largest change to the C API came from 
@geindex Python Enhancement Proposals; PEP 353
PEP 353@footnote{https://peps.python.org/pep-0353/}, which modifies the
interpreter to use a @ref{c55,,Py_ssize_t} type definition instead of
int.  See the earlier section @ref{1631,,PEP 353; 添え字型に ssize_t を使う} for a discussion of this
change.

@item 
The design of the bytecode compiler has changed a great deal,  no longer
generating bytecode by traversing the parse tree.  Instead the parse tree is
converted to an abstract syntax tree (or AST), and it is  the abstract syntax
tree that's traversed to produce the bytecode.

It's possible for Python code to obtain AST objects by using the
@ref{4b1,,compile()} built-in and specifying @code{_ast.PyCF_ONLY_AST} as the value of
the  `flags' parameter:

@example
from _ast import PyCF_ONLY_AST
ast = compile("""a=0
for i in range(10):
    a += i
""", "<string>", 'exec', PyCF_ONLY_AST)

assignment = ast.body[0]
for_loop = ast.body[1]
@end example

No official documentation has been written for the AST code yet, but 
@geindex Python Enhancement Proposals; PEP 339
PEP 339@footnote{https://peps.python.org/pep-0339/}
discusses the design.  To start learning about the code, read the definition of
the various AST nodes in @code{Parser/Python.asdl}.  A Python script reads this
file and generates a set of C structure definitions in
@code{Include/Python-ast.h}.  The @code{PyParser_ASTFromString()} and
@code{PyParser_ASTFromFile()}, defined in @code{Include/pythonrun.h}, take
Python source as input and return the root of an AST representing the contents.
This AST can then be turned into a code object by @code{PyAST_Compile()}.  For
more information, read the source code, and then ask questions on python-dev.

The AST code was developed under Jeremy Hylton's management, and implemented by
(in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John
Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil
Schemenauer, plus the participants in a number of AST sprints at conferences
such as PyCon.

@c List of names taken from Jeremy's python-dev post at

@c https://mail.python.org/pipermail/python-dev/2005-October/057500.html

@item 
Evan Jones's patch to obmalloc, first described in a talk at PyCon DC 2005,
was applied.  Python 2.4 allocated small objects in 256K-sized arenas, but never
freed arenas.  With this patch, Python will free arenas when they're empty.  The
net effect is that on some platforms, when you allocate many objects, Python's
memory usage may actually drop when you delete them and the memory may be
returned to the operating system.  (Implemented by Evan Jones, and reworked by
Tim Peters.)

Note that this change means extension modules must be more careful when
allocating memory.  Python's API has many different functions for allocating
memory that are grouped into families.  For example, @ref{e5f,,PyMem_Malloc()},
@ref{1233,,PyMem_Realloc()}, and @ref{165b,,PyMem_Free()} are one family that allocates
raw memory, while @ref{e62,,PyObject_Malloc()}, @ref{165c,,PyObject_Realloc()}, and
@ref{e60,,PyObject_Free()} are another family that's supposed to be used for
creating Python objects.

Previously these different families all reduced to the platform's
@code{malloc()} and @code{free()} functions.  This meant  it didn't matter if
you got things wrong and allocated memory with the @code{PyMem} function but
freed it with the @code{PyObject} function.  With 2.5's changes to obmalloc,
these families now do different things and mismatches will probably result in a
segfault.  You should carefully test your C extension modules with Python 2.5.

@item 
ビルトインの集合型のために公式の C API が作られました。新しく作るのには @ref{165d,,PySet_New()} か @ref{165e,,PyFrozenSet_New()} を、要素の追加には @ref{165f,,PySet_Add()} 、削除には @ref{1660,,PySet_Discard()} 、 @ref{1661,,PySet_Contains()} と @ref{1662,,PySet_Size()} で集合オブジェクトの状態を調べます。 (Contributed by Raymond Hettinger.)

@item 
C コードから Python インタプリタの正確なリビジョンについての情報を取得出来るようになりました。 @ref{164b,,Py_GetBuildInfo()} 関数を呼び出すことでビルド情報についての文字列が @code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"} のように返ります。 (Contributed by Barry Warsaw.)

@item 
Two new macros can be used to indicate C functions that are local to the
current file so that a faster calling convention can be used.
@ref{1663,,Py_LOCAL} declares the function as returning a value of the
specified `type' and uses a fast-calling qualifier.
@ref{1664,,Py_LOCAL_INLINE} does the same thing and also requests the
function be inlined.  If macro @code{PY_LOCAL_AGGRESSIVE} is defined before
@code{python.h} is included, a set of more aggressive optimizations are enabled
for the module; you should benchmark the results to find out if these
optimizations actually make the code faster.  (Contributed by Fredrik Lundh at
the NeedForSpeed sprint.)

@item 
@code{PyErr_NewException(name, base, dict)} が `base' 引数としてベースクラスのタプルを受け付けるようになりました。 (Contributed by Georg Brandl.)

@item 
The @code{PyErr_Warn()} function for issuing warnings is now deprecated in
favour of @code{PyErr_WarnEx(category, message, stacklevel)} which lets you
specify the number of stack frames separating this function and the caller.  A
`stacklevel' of 1 is the function calling @ref{1665,,PyErr_WarnEx()}, 2 is the
function above that, and so forth.  (Added by Neal Norwitz.)

@item 
CPython は今でも C で書かれていますが、コードは C++ コンパイラでもエラーなしでコンパイル出来るようになりました。   (Implemented by Anthony Baxter, Martin von Löwis, Skip Montanaro.)

@item 
The @code{PyRange_New()} function was removed.  It was never documented, never
used in the core code, and had dangerously lax error checking.  In the unlikely
case that your extensions were using it, you can replace it by something like
the following:

@example
range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
                              start, stop, step);
@end example
@end itemize

@c ======================================================================

@menu
* ポート特有の変更:: 

@end menu

@node ポート特有の変更,,,ビルドならびに C API の変更<10>
@anchor{whatsnew/2 5 port-specific-changes}@anchor{1666}@anchor{whatsnew/2 5 ports}@anchor{1667}
@subsubsection ポート特有の変更



@itemize *

@item 
MacOS X (10.3 以上): モジュールの動的ロードに、MacOS 固有の関数ではなく @code{dlopen()} 関数を使うようになりました。

@item 
MacOS X: an @code{--enable-universalsdk} switch was added to the
@code{configure} script that compiles the interpreter as a universal binary
able to run on both PowerPC and Intel processors. (Contributed by Ronald
Oussoren; bpo-2573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2573}.)

@item 
Windows: @code{.dll} はもはや拡張モジュールのファイル拡張子としてはサポートされません。これからは @code{.pyd} だけが拡張モジュールとして検索されるファイル拡張子です。
@end itemize

@c ======================================================================

@node Python 2 5 への移植,謝辞<3>,ビルドならびに C API の変更<10>,What's New in Python 2 5
@anchor{whatsnew/2 5 porting}@anchor{1668}@anchor{whatsnew/2 5 porting-to-python-2-5}@anchor{1669}
@subsection Python 2.5 への移植


このセクションでは前述の変更により必要となるかもしれないコードの変更を列挙します:


@itemize *

@item 
ASCII がモジュールのデフォルトエンコーディングになっています(訳注: Python 3 からはデフォルトは utf-8 (PEP 3120))。8 ビット文字を含んでいるのにエンコーディング宣言がないモジュールが構文エラーになるようになりました。Python 2.4 では構文エラーとはならず警告でした。

@item 
以前はジェネレータの @code{gi_frame} 属性は常にフレームオブジェクトでしたが、 @ref{161d,,PEP 342; ジェネレータの新機能} で説明した 
@geindex Python Enhancement Proposals; PEP 342
PEP 342@footnote{https://peps.python.org/pep-0342/} での変更により、 @code{gi_frame} は @code{None} になりえます。

@item 
Unicode 文字列とデフォルトの ASCII エンコーディングで Unicode に変換出来ない 8 ビット文字列との比較を試みると、新しい警告 @ref{163d,,UnicodeWarning} が引き起こされるようになっています。以前はそのような比較では @ref{c08,,UnicodeDecodeError} 例外を起こしていました。

@item 
ライブラリ: @ref{2d,,csv} モジュールは引用符内のマルチラインをより厳密に扱うようになっています。フィールド内に改行を埋め込んでいるファイルがある場合は、その入力は改行文字を残すやり方で行分解されるはずです。

@item 
ライブラリ: @ref{8a,,locale} モジュールの @ref{199,,format()} 関数は、以前は %文字指定子が一つを超えてさえいなければ任意の文字列を受け付けていたかもしれませんが、Python 2.5 からは正確に一つの、ほかに周りをテキストで囲まれていない %文字指定子でなければなりません。

@item 
Library: The @ref{ab,,pickle} and @code{cPickle} modules no longer accept a
return value of @code{None} from the @ref{bc6,,__reduce__()} method; the method must
return a tuple of arguments instead.  The modules also no longer accept the
deprecated `bin' keyword parameter.

@item 
Library: The @ref{135,,SimpleXMLRPCServer} and @ref{135,,DocXMLRPCServer}  classes now
have a @code{rpc_paths} attribute that constrains XML-RPC operations to a
limited set of URL paths; the default is to allow only @code{'/'} and @code{'/RPC2'}.
Setting  @code{rpc_paths} to @code{None} or an empty tuple disables  this path
checking.

@item 
C API: Many functions now use @ref{c55,,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 @ref{1631,,PEP 353; 添え字型に ssize_t を使う} for a discussion of this change.

@item 
C API:  The obmalloc changes mean that  you must be careful to not mix usage
of the @code{PyMem_*} and @code{PyObject_*} families of functions. Memory
allocated with  one family's @code{*_Malloc} must be  freed with the
corresponding family's @code{*_Free} function.
@end itemize

@c ======================================================================

@node 謝辞<3>,,Python 2 5 への移植,What's New in Python 2 5
@anchor{whatsnew/2 5 acknowledgements}@anchor{166a}
@subsection 謝辞


The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: 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.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 4,What's New in Python 2 3,What's New in Python 2 5,What's New in Python
@anchor{whatsnew/2 4 doc}@anchor{166b}@anchor{whatsnew/2 4 translation-repo}@anchor{166c}@anchor{whatsnew/2 4 what-s-new-in-python-2-4}@anchor{166d}
@section What's New in Python 2.4


@*著者: 
A.M. Kuchling


@c $Id: whatsnew24.tex 54632 2007-03-31 11:59:54Z georg.brandl $

@c Don't write extensive text for new sections; I'll do that.

@c Feel free to add commented-out reminders of things that need

@c to be covered.  --amk

この文書は 2005 年 3 月 30 日にリリースされた Python 2.4.1 の新機能について解説します。

Python 2.4 は、真ん中サイズ、のリリースです。急進的だった Python 2.2 ほどには多くの変更をしていませんが、保守的だった 2.3 よりは多くの機能を導入しています。新しい言語機能で最も重要なのが、関数デコレータとジェネレータ式です。ほかのほとんどの変更は標準ライブラリに対するものです。

Python 2.3 から 2.4 の CVS 変更ログによれば、適用されたパッチは 481、フィックスされたバグは 502 ありました。ともに、少なく見積もって、です。

このドキュメントは個々の新機能の完全な詳細を提供するのではなくて、簡易な概要を提供することを目的にしています。完全な詳細が知りたければ、 Python ライブラリリファレンス、Python リファレンスマニュアルのような Python 2.4 のドキュメントを参照してください。多くの場合個別の新機能についての実装の説明やデザインの根拠については PEP に託されています。

@c ======================================================================

@menu
* PEP 218; ビルトインの集合オブジェクト: PEP 218 ビルトインの集合オブジェクト. 
* PEP 237; 長整数と整数を一体化していく: PEP 237 長整数と整数を一体化していく. 
* PEP 289; ジェネレータ式: PEP 289 ジェネレータ式. 
* PEP 292; より単純な文字列置換 (string substitution): PEP 292 より単純な文字列置換 string substitution. 
* PEP 318; 関数とメソッドのためのデコレータ: PEP 318 関数とメソッドのためのデコレータ. 
* PEP 322; 逆順のイテレーション: PEP 322 逆順のイテレーション. 
* PEP 324; 新しい subprocess モジュール: PEP 324 新しい subprocess モジュール. 
* PEP 327; Decimal データ型: PEP 327 Decimal データ型. 
* PEP 328; マルチラインインポート: PEP 328 マルチラインインポート. 
* PEP 331; Locale に依存しない Float/String 変換: PEP 331 Locale に依存しない Float/String 変換. 
* その他の言語変更: その他の言語変更<17>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール: 新たなモジュール、改良されたモジュール、非推奨のモジュール<3>. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<11>. 
* Python 2.4 への移植: Python 2 4 への移植. 
* 謝辞: 謝辞<4>. 

@end menu

@node PEP 218 ビルトインの集合オブジェクト,PEP 237 長整数と整数を一体化していく,,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-218-built-in-set-objects}@anchor{166e}
@subsection PEP 218: ビルトインの集合オブジェクト


Python 2.3 では @code{sets} モジュールを導入しました。集合データ型の C 実装が Python コアに新たに、2 つの新しいビルトイン型 @code{set(iterable)} と @code{frozenset(iterable)} として追加されています。これらは要素が集合に属しているかのメンバシップテスト、シーケンスからの重複の削除、それに和集合 (union)、共通集合 (intersection)、 差 (difference)、対称差 (symmetric difference) といった数学演算を高速に行います:

@example
>>> a = set('abracadabra')              # form a set from a string
>>> 'z' in a                            # fast membership testing
False
>>> a                                   # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> '@w{'}.join(a)                          # convert back into a string
'arbcd'

>>> b = set('alacazam')                 # form a second set
>>> a - b                               # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                               # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                               # letters in both a and b
set(['a', 'c'])
>>> a ^ b                               # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

>>> a.add('z')                          # add a new element
>>> a.update('wxy')                     # add multiple new elements
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
>>> a.remove('x')                       # take one element out
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
@end example

@ref{7f2,,frozenset()} 型は @ref{184,,set()} の @ref{15b9,,immutable} 版です。 immutable かつハッシュ可能なので、辞書のキーやほかの set のメンバとして使えるでしょう。

2.3 で追加された @code{sets} モジュールは標準ライブラリに残されていて、 @code{Set} や @code{ImmutableSet} をサブクラス化したければ便利かもしれません。今のところこれを撤廃する予定はありません。(---訳注: @code{sets} モジュールは 2.6 で非推奨となっています。---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 218

@item PEP 218@footnote{https://peps.python.org/pep-0218/} - 集合オブジェクト型をビルトインに追加する

元々は Greg Wilson によって提案され、完全な実装は Raymond Hettinger によってなされました。
@end table


@c ======================================================================

@node PEP 237 長整数と整数を一体化していく,PEP 289 ジェネレータ式,PEP 218 ビルトインの集合オブジェクト,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-237-unifying-long-integers-and-integers}@anchor{166f}
@subsection PEP 237: 長整数と整数を一体化していく


この PEP の非常に長期に渡る移行は Python 2.2 に始まり、Python 2.4 でさらにもう一歩前進しています。2.3 では int/long の一体化後に異なる振る舞いをする整数演算をすると @ref{659,,FutureWarning} 警告を出して、結果の値は (プラットフォーム依存で) 32 ビットまたは 64 ビットに制限していました。2.4 ではこれらの式はもう警告は出さず、代わりにいつでも(2.3 とは違った)長整数となる結果をはじき出します。

問題を起こしうる式は主として左シフトで、そして長い 16 進リテラルと 8 進リテラルです。例えば @code{2 << 32} は 2.3 では警告とともに 32 ビットプラットフォームでは結果は 0 になります。Python 2.4 ではこの式は正しい答えの 8589934592 になります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 237

@item PEP 237@footnote{https://peps.python.org/pep-0237/} - 長整数と整数を一体化していく

オリジナルの PEP は Moshe Zadka と GvR (Guido van Rossum) によって書かれました。.2.4 での変更については Kalle Svensson によって実装されました。
@end table


@c ======================================================================

@node PEP 289 ジェネレータ式,PEP 292 より単純な文字列置換 string substitution,PEP 237 長整数と整数を一体化していく,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-289-generator-expressions}@anchor{1670}
@subsection PEP 289: ジェネレータ式


The iterator feature introduced in Python 2.2 and the @ref{85,,itertools} module
make it easier to write programs that loop through large data sets without
having the entire data set in memory at one time.  List comprehensions don't fit
into this picture very well because they produce a Python list object containing
all of the items.  This unavoidably pulls all of the objects into memory, which
can be a problem if your data set is very large.  When trying to write a
functionally styled program, it would be natural to write something like:

@example
links = [link for link in get_all_links() if not link.followed]
for link in links:
    ...
@end example

こうではなく

@example
for link in get_all_links():
    if link.followed:
        continue
    ...
@end example

最初の形の方が簡潔でおそらく読みやすいですが、扱っているのがとても多くのリンクオブジェクトであるならば、全てのリンクオブジェクトが一気にメモリに載らないように二つ目の形で書く必要がありました。

ジェネレータ式はリスト内包と似た動作をしますが、リスト全体を実体化しません; 代わりにそれは、要素を一つずつ返すジェネレータを返します。上述の例はこう書けます:

@example
links = (link for link in get_all_links() if not link.followed)
for link in links:
    ...
@end example

上の例でのように、ジェネレータ式は常に括弧の中に書かなければなりません。関数呼び出しを囲む括弧もそれに含まれるので、関数にそのまま渡すイテレータを作りたければこれで良いです:

@example
print sum(obj.count for obj in list_all_objects())
@end example

ジェネレータ式はリスト内包とは色々小さい点で違います。最も顕著なのはループ変数 (上の例での `obj') がジェネレータ式の外からアクセス不能なことです。リスト内包はループの制御変数が最後に代入された値で残ります; 将来のバージョンの Python では、この振る舞いはリスト内包がこの点でジェネレータ式と同じになるように変更されます。 (---訳注: Python 2.7 でもリスト内包のこの振る舞いは変わっておらず、警告ともなりません。制御変数が内包のスコープ外で可視でなくなったのは Python 3.0 からです。---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 289

@item PEP 289@footnote{https://peps.python.org/pep-0289/} - ジェネレータ式

Raymond Hettinger によって提案され、Hye-Shik Chang に導かれた早期の尽力によって Jiwon Seo により実装されました。
@end table


@c ======================================================================

@node PEP 292 より単純な文字列置換 string substitution,PEP 318 関数とメソッドのためのデコレータ,PEP 289 ジェネレータ式,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-292-simpler-string-substitutions}@anchor{1671}
@subsection PEP 292: より単純な文字列置換 (string substitution)


標準ライブラリに、文字列を変数で置換するための代替メカニズムをもたらす新しいくつかのクラスが追加されました; この置換のスタイルは、訓練されていないユーザがテンプレートを編集する必要があるようなアプリケーションにとって、より良いものでしょう。

変数置換を名前で行うためのいつもの方法は @code{%} 演算子です:

@example
>>> '%(page)i: %(title)s' % @{'page':2, 'title': 'The Best of Times'@}
'2: The Best of Times'
@end example

テンプレート文字列を書くのに、閉じ括弧のあとの @code{i} や @code{s} を忘れやすいです。これはそのテンプレートが Python モジュール内にあるなら大問題でもありません。コードを実行し、「サポートされないフォーマット文字 (unsupported format character)」な @ref{2ec,,ValueError} を喰らい、問題を直すだけのことです。ですが、例えば Mailman のようなアプリケーションを考えてみてください。テンプレート文字列や翻訳は、Python 言語について承知していないユーザが編集するのです。フォーマット文字列の構文はそのようなユーザに説明するには複雑で、彼らが間違いをやらかした場合には、親切なフィードバックを彼らに与えるのは難しいのです。

PEP 292 は @ref{d8,,string} モジュールに @code{Template} クラスを追加します。これは置換を指示するのに @code{$} を使います:

@example
>>> import string
>>> t = string.Template('$page: $title')
>>> t.substitute(@{'page':2, 'title': 'The Best of Times'@})
'2: The Best of Times'
@end example

辞書にキーが見つからない場合、 @code{substitute()} メソッドは @ref{5e7,,KeyError} を送出します。 @code{safe_substitute()} メソッドもあり、これはキー不在を無視します:

@example
>>> t = string.Template('$page: $title')
>>> t.safe_substitute(@{'page':3@})
'3: $title'
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 292

@item PEP 292@footnote{https://peps.python.org/pep-0292/} - より単純な文字列置換 (string substitution)

Barry Warsaw 著、実装
@end table


@c ======================================================================

@node PEP 318 関数とメソッドのためのデコレータ,PEP 322 逆順のイテレーション,PEP 292 より単純な文字列置換 string substitution,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-318-decorators-for-functions-and-methods}@anchor{1672}
@subsection PEP 318: 関数とメソッドのためのデコレータ


Python 2.2 は Python オブジェクトモデルを静的メソッド、クラスメソッドを追加することで拡張はしましたが、それらを定義する新たな手段を提供するような Python 構文の拡張はしませんでした。このため、 @ref{1673,,def} でメソッドは普通に書いたのち、新型メソッドとしての関数へ仕立て上げる @ref{453,,staticmethod()} または @ref{48e,,classmethod()} にその結果のメソッドを渡す、という手順を取る必要がありました。このような具合でした:

@example
class C:
   def meth (cls):
       ...

   meth = classmethod(meth)   # Rebind name to wrapped-up class method
@end example

メソッドがとても長かったりすると、関数のボディの後ろの @ref{48e,,classmethod()} 呼び出しは見失ったり忘れたりしやすいものでした。

そのような定義をもっと読みやすくするために何か構文を追加する、という意図は常にありましたが、2.2 のリリース時点では良い構文は明らかではありませんでした。本日時点でさえ `いまだ' 明らかとは言えませんが、ユーザは静的メソッドとクラスメソッドを簡単に手にする手段を注文し続けています; 新たな構文的機能はこの要求に合うように追加されました。

この新たな機能は「関数デコレータ (function decorators)」と呼ばれます。この名前は @ref{48e,,classmethod()}, @ref{453,,staticmethod()}, とその仲間たちが関数オブジェクトに追加的な情報を保存することから着想を得たものです; それらは関数をより多くの詳細で `デコレート (修飾) している' というわけです。

記法は Java より拝借して @code{'@@'} 文字を指示子として使います。この新たな構文を使うと、上記の例はこのように書けます:

@example
class C:

   @@classmethod
   def meth (cls):
       ...
@end example

@code{@@classmethod} は @code{meth=classmethod(meth)} 代入の速記法です。より一般的には、このように書けば…:

@example
@@A
@@B
@@C
def f ():
    ...
@end example

これはデコレータ前史の以下コードと等価です:

@example
def f(): ...
f = A(B(C(f)))
@end example

デコレータは関数定義の前になければなりません。一行ごとに一つのデコレータです。 def ステートメントと同じ行にあってはダメです。つまり @code{@@A def f(): ...} は不正です。モジュールレベルかクラス内の関数定義のみをデコレート出来ます; クラス定義はデコレート出来ません。(--- 訳注: クラス定義のデコレータは Python 2.6 で追加されました (PEP 3129) 。---)

デコレータはただの関数です。引数としてデコレートされる関数を取り、同じ関数か何か新しいオブジェクトを返すだけの。結果がほかのデコレータ適用されるの出ない限りは、デコレータの戻り値は呼び出し可能である必要はありません (普通はそうですが)。あなた自身のデコレータを書くのは簡単です。続く単純な例は、関数オブジェクトに単に属性をセットするだけのものです:

@example
>>> def deco(func):
...    func.attr = 'decorated'
...    return func
...
>>> @@deco
... def f(): pass
...
>>> f
<function f at 0x402ef0d4>
>>> f.attr
'decorated'
>>>
@end example

もう少しだけ現実的な例として、続く例ではデコレータに、与えられた引数が整数かどうかチェックさせてみます:

@example
def require_int (func):
    def wrapper (arg):
        assert isinstance(arg, int)
        return func(arg)

    return wrapper

@@require_int
def p1 (arg):
    print arg

@@require_int
def p2(arg):
    print arg*2
@end example

@geindex Python Enhancement Proposals; PEP 318
PEP 318@footnote{https://peps.python.org/pep-0318/} にある例はこのアイディアのもっと凝った版が含まれていて、それは要求型の指定と戻り値のチェックの両方が出来ます。

デコレータ関数は引数を取ることが出来ます。引数が与えられた場合、あなたのデコレータ関数はそれら引数のみで呼び出され、そして新しいデコレータを返さなければなりません; この関数は単一の関数を取らなければならず、前述のように関数を返さなければなりません。言い換えると、 @code{@@A @@B @@C(args)} はこうなります:

@example
def f(): ...
_deco = C(args)
f = A(B(_deco(f)))
@end example

これが正しいと理解するには少しばかり頭をひねる必要がありますが、難しすぎることはありません。

A small related change makes the @ref{14ec,,func_name}
attribute of functions
writable.  This attribute is used to display function names in tracebacks, so
decorators should change the name of any new function that's constructed and
returned.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 318

@item PEP 318@footnote{https://peps.python.org/pep-0318/} - 関数、メソッド、クラスのためのデコレータ

Kevin D. Smith, Jim Jewett, Skip Montanaro により著されました。数多くの人々が関数デコレータ実装のパッチを書きましたが、実際にチェックインされたものは Mark Russell が書いた #979728 でした。

@item @indicateurl{https://wiki.python.org/moin/PythonDecoratorLibrary}

数多くのデコレータ例を含む Wiki ページ。
@end table


@c ======================================================================

@node PEP 322 逆順のイテレーション,PEP 324 新しい subprocess モジュール,PEP 318 関数とメソッドのためのデコレータ,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-322-reverse-iteration}@anchor{1674}
@subsection PEP 322: 逆順のイテレーション


新しいビルトイン関数 @code{reversed(seq)} は、シーケンスを受け取って、シーケンスの要素を逆順にループするイテレータを返します:

@example
>>> for i in reversed(xrange(1,4)):
...    print i
...
3
2
1
@end example

@code{range(1,4)[::-1]} のようにする拡張スライスでのやり方に比較して @ref{a65,,reversed()} は読みやすく、実行が高速で、大体の場合はメモリ使用が少なく済みます。

@ref{a65,,reversed()} は任意のイテレータは受け付けず、シーケンスのみ受け付けることに注意してください。イテレータを逆順にしたければ、最初に @ref{24d,,list()} でリストに変換してください:

@example
>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
...
root:*:0:0:System Administrator:/var/root:/bin/tcsh
  ...
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 322

@item PEP 322@footnote{https://peps.python.org/pep-0322/}  - 逆順のイテレーション

Raymond Hettinger 著、実装.
@end table


@c ======================================================================

@node PEP 324 新しい subprocess モジュール,PEP 327 Decimal データ型,PEP 322 逆順のイテレーション,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-324-new-subprocess-module}@anchor{1675}
@subsection PEP 324: 新しい subprocess モジュール


The standard library provides a number of ways to execute a subprocess, offering
different features and different levels of complexity.
@code{os.system(command)} is easy to use, but slow (it runs a shell process
which executes the command) and dangerous (you have to be careful about escaping
the shell's metacharacters).  The @code{popen2} module offers classes that can
capture standard output and standard error from the subprocess, but the naming
is confusing.  The @ref{dc,,subprocess} module cleans  this up, providing a unified
interface that offers all the features you might need.

Instead of @code{popen2}'s collection of classes, @ref{dc,,subprocess} contains a
single class called @ref{4b7,,subprocess.Popen}  whose constructor supports a number of
different keyword arguments.

@example
class Popen(args, bufsize=0, executable=None,
            stdin=None, stdout=None, stderr=None,
            preexec_fn=None, close_fds=False, shell=False,
            cwd=None, env=None, universal_newlines=False,
            startupinfo=None, creationflags=0):
@end example

`args' は普通は文字列のシーケンスで、サブプロセスとして実行するプログラムへの引数群となります。 (`shell' 引数が真の場合は `args' はシェルに解釈を任せるために渡す文字列に出来、つまりこの場合 @ref{1676,,os.system()} と同じことをします。)

`stdin', `stdout', `stderr' はサブプロセスの入力・出力・エラーのストリームを指定します。ファイルオブジェクトかファイル記述子を渡すことが出来ます。あるいは定数 @code{subprocess.PIPE} を渡してサブプロセスと親とのパイプを作成することが出来ます。

@geindex universal newlines;What's new

コンストラクタには多くの便利なオプションがあります:


@itemize *

@item 
`close_fds' はサブプロセス実行前に全てのファイル記述子をクローズすることを要求します。

@item 
`cwd' はサブプロセスを実行する作業ディレクトリを指定します (デフォルトは親の作業ディレクトリです)。

@item 
`env' は環境変数を指定する辞書です。

@item 
`preexec_fn' は子が開始する前に呼び出される関数です。

@item 
`universal_newlines' で、子の入出力を、Python の @ref{f35,,universal newlines} 機能で開きます。
@end itemize

@code{Popen} インスタンスを作ってしまえば、あとはサブプロセスが終了するまで停止するために @code{wait()} メソッド呼び出すことが出来、停止することなく終了をチェックするのに @code{poll()} メソッドを呼び出すことが出来、あるいは @code{communicate(data)} を呼び出して、子の標準入力に `data' を送信することが出来ます。 @code{communicate(data)} はサブプロセスが送信する標準出力と標準エラー出力を読み込み、タプル @code{(stdout_data, stderr_data)} を返します。

@code{call()} は @code{Popen} コンストラクタにその引数を流し込むショートカットで、コマンドが終了するまで待ち、サブプロセスの終了コードを返します。これは @ref{1676,,os.system()} に対する安全な置き換えとなりえます:

@example
sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
if sts == 0:
    # Success
    ...
else:
    # dpkg returned an error
    ...
@end example

コマンドはシェルを使うことなく呼び出されます。もしシェルを本当に使いたいのであればキーワード引数として @code{shell=True} を与えた上でシーケンスの代わりに文字列を与えることが出来ます:

@example
sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)
@end example

PEP にはシェルと Python コードの様々な例が採られていて、シェルスクリプトをいかにして @ref{dc,,subprocess} を用いて Python コードに変換するかを示しています。PEP のこのセクションを読むことを強くお勧めします。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 324

@item PEP 324@footnote{https://peps.python.org/pep-0324/} - subprocess - プロセスのための新たなモジュール

Fredrik Lundh 他によるサポートによって、Peter Åstrand により PEP 著と実装が行われました。
@end table


@c ======================================================================

@node PEP 327 Decimal データ型,PEP 328 マルチラインインポート,PEP 324 新しい subprocess モジュール,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-327-decimal-data-type}@anchor{1677}
@subsection PEP 327: Decimal データ型


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 @code{Decimal} type can represent these fractions
accurately, up to a user-specified precision limit.

@menu
* なぜ Decimal が必要なのか?:: 
* Decimal 型:: 
* Context 型:: 

@end menu

@node なぜ Decimal が必要なのか?,Decimal 型,,PEP 327 Decimal データ型
@anchor{whatsnew/2 4 why-is-decimal-needed}@anchor{1678}
@subsubsection なぜ Decimal が必要なのか?


浮動小数点数が使う表現方法に起因する制約があります。浮動小数点数は 3 つの構成要素から成ります:


@itemize *

@item 
符号(sign)。正または負。

@item 
仮数部(mantissa)。一桁の 2 進値に端数部が続きます。例えば 2 進数で @code{1.01} は @code{1 + 0/2 + 1/4} で 10 進表記で 1.25 です。

@item 
指数部(exponent)。小数点がその数値のどこに位置するかを表します。
@end itemize

例えば 1.25 は、正の符号を持ち、仮数部の値は (2 進数で) 1.01 で、指数部は 0 です (小数点は移動の必要がありません)。5 は同じ符号と仮数部を持ち、指数部は、仮数部が 4 倍なので 2 (2 を底とする 2 の 冪乗) です; 1.25 * 4 は 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 @code{1.0001100110011 ...}; .1 = 1/16 + 1/32 +
1/256 plus an infinite number of additional terms.  IEEE 754 has to chop off
that infinitely repeated decimal after 52 digits, so the representation is
slightly inaccurate.

ときどきあなたはこの不正確さを、数値を表示する際に目にするでしょう:

@example
>>> 1.1
1.1000000000000001
@end example

この不正確さは数値を表示する際にいつでも目に見えるわけではありません。浮動小数点数から文字列への変換が C ライブラリによって提供されていて、C ライブラリのほとんどが賢明な出力を生成しようと頑張っているからです。それが表示されないにしても、不正確さはそれでも存在していて、後続の計算への誤差が大きくなりえます。

多くのアプリケーションではこれは重要ではありません。モニタにプロットして表示するのに 1.1 と 1.1000000000000001 の差は小さすぎて見えません。大抵は出力を一定の桁位置までに制限して出力するものですし、2 やら 3 やら 8 桁などの位置で丸めたりすれば誤差は決して露わにはなりません。ですがそれが重要なアプリケーションにとっては、あなた自身のカスタム数学ルーチンのための実装作業は膨大になります。

こうして @code{Decimal} 型が作られました。

@node Decimal 型,Context 型,なぜ Decimal が必要なのか?,PEP 327 Decimal データ型
@anchor{whatsnew/2 4 the-decimal-type}@anchor{1679}
@subsubsection @code{Decimal} 型


新しいモジュール @ref{3a,,decimal} が Python 標準ライブラリに追加されました。これには 2 つのクラス @code{Decimal}, @code{Context} を含みます。 @code{Decimal} インスタンスは数値を表現し、 @code{Context} インスタンスは、精度やデフォルトの丸めモードなどのさまざまな設定をまとめるのに使われます。

@code{Decimal} のインスタンスは普通の Python 整数や浮動小数点数のように @ref{15b9,,immutable} です。 @code{Decimal} のインスタンスは整数や文字列から構築出来ます:

@example
>>> import decimal
>>> decimal.Decimal(1972)
Decimal("1972")
>>> decimal.Decimal("1.1")
Decimal("1.1")
@end example

符号(sign)、10進数値のタプルで表した仮数部(mantissa)、指数部(exponent)を含んだタプルを渡すことも出来ます:

@example
>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
Decimal("-14.75")
@end example

注意: 符号ビットは負符号の有無なので、 0 が正、1  が負です。

浮動小数点数からの変換は少々問題です: 1.1 を表現する浮動小数点数は 10 進数値の正確な 1.1 に変換すべきでしょうか、それとも 1.1 が持つどんな不正確さもそのまま持ち込むべきでしょうか? 決定は、問題をはぐらかして、その種の変換を API の範疇外とする、というものでした。代わりにあなたは浮動小数点数を望みの精度で文字列に変換して、その文字列を @code{Decimal} コンストラクタに渡す必要があります:

@example
>>> f = 1.1
>>> decimal.Decimal(str(f))
Decimal("1.1")
>>> decimal.Decimal('%.12f' % f)
Decimal("1.100000000000")
@end example

いったん @code{Decimal} を手にしてしまえばあとは普通の数学演算が使えます。制約の一つ: べき乗には整数の指数しか使えません:

@example
>>> a = decimal.Decimal('35.72')
>>> b = decimal.Decimal('1.73')
>>> a+b
Decimal("37.45")
>>> a-b
Decimal("33.99")
>>> a*b
Decimal("61.7956")
>>> a/b
Decimal("20.64739884393063583815028902")
>>> a ** 2
Decimal("1275.9184")
>>> a**b
Traceback (most recent call last):
  ...
decimal.InvalidOperation: x ** (non-integer)
@end example

@code{Decimal} インスタンスと整数は混ぜて使えますが、浮動小数点数とは出来ません:

@example
>>> a + 4
Decimal("39.72")
>>> a + 4.5
Traceback (most recent call last):
  ...
TypeError: You can interact Decimal only with int, long or Decimal data types.
>>>
@end example

@code{Decimal} 数を @ref{92,,math}, @ref{19,,cmath} モジュールで使うことは出来ますが、演算実行前にその場で浮動小数点数に変換されて、結果精度と正確性を失う可能性があります。戻り値は普通の浮動小数点数であって @code{Decimal} ではありません:

@example
>>> import math, cmath
>>> d = decimal.Decimal('123456789012.345')
>>> math.sqrt(d)
351364.18288201344
>>> cmath.sqrt(-d)
351364.18288201344j
@end example

@code{Decimal} インスタンスは @code{Decimal} インスタンスを返す @code{sqrt()} メソッドを持っていますが、三角関数のようななにかほかのことが必要な場合は、それらを実装する必要があるでしょう。:

@example
>>> d.sqrt()
Decimal("351364.1828820134592177245001")
@end example

@node Context 型,,Decimal 型,PEP 327 Decimal データ型
@anchor{whatsnew/2 4 the-context-type}@anchor{167a}
@subsubsection @code{Context} 型


@code{Context} クラスのインスタンスは decimal 演算についてのいくつかの設定をカプセル化しています:


@itemize *

@item 
@code{prec} は精度で、小数桁数です。

@item 
@code{rounding} は丸めのモードを指定します。 @ref{3a,,decimal} にはこの値に渡せる定数が定義されています: @code{ROUND_DOWN}, @code{ROUND_CEILING}, @code{ROUND_HALF_EVEN}, それに色々。

@item 
@code{traps} は特定のエラー状態に出会った場合に何が起こるべきかを指定する辞書です: 例外を発生させるか値を返すかどちらかです。いくつかのエラー状態の例としては、ゼロ除算、精度損失、オーバーフローがあります。
@end itemize

スレッドローカルなデフォルトのコンテキストを、 @code{getcontext()} を呼び出すことで利用出来ます; デフォルトの精度、丸めモード、トラップ処理に代えてこのコンテキストのプロパティを変更出来ます。続く例はデフォルトコンテキストの精度を変更する効果についてお見せします:

@example
>>> decimal.getcontext().prec
28
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.1428571428571428571428571429")
>>> decimal.getcontext().prec = 9
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.142857143")
@end example

エラー状態の場合のデフォルトアクションを選択出来ます; モジュールは無限大(infinity)あるいは非数(not-a-number: NaN)を返すか、例外を投げるかです:

@example
>>> decimal.Decimal(1) / decimal.Decimal(0)
Traceback (most recent call last):
  ...
decimal.DivisionByZero: x / 0
>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
>>> decimal.Decimal(1) / decimal.Decimal(0)
Decimal("Infinity")
>>>
@end example

@code{Context} インスタンスは @code{to_eng_string()}, @code{to_sci_string()} のような、数値の書式化のための色々なメソッドも持っています。

さらに詳しく知りたければ @ref{3a,,decimal} モジュールのドキュメントを読んで下さい。これには簡単に始められるチュートリアルとリファレンスが入っています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 327

@item PEP 327@footnote{https://peps.python.org/pep-0327/} - Decimal データ型

Facundo Batista によって著され、Facundo Batista, Eric Price, Raymond Hettinger, Aahz,  Tim Peters らによって実装されました。

@item http://www.lahey.com/float.htm@footnote{https://web.archive.org/web/20230604072523/http://www.lahey.com/float.htm}

この記事は浮動小数点数の不正確さが起こりうるたくさんの問題について、Fortran コードを使って解説しています。

@item @indicateurl{https://speleotrove.com/decimal/}

10 進数ベースの表現についての記述です(訳注: decimal-based は小数ベースとも 10 進数ベースとも取れるのですが、後者にしておきました)。この表現方法は標準として提案されていて、この Python の decimal 型の基礎になっています。この題材の多くが Rexx 言語設計者である Mike Cowlishaw によって著されました。
@end table


@c ======================================================================

@node PEP 328 マルチラインインポート,PEP 331 Locale に依存しない Float/String 変換,PEP 327 Decimal データ型,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-328-multi-line-imports}@anchor{167b}
@subsection PEP 328: マルチラインインポート


言語の変更の一つは小さな文法的な微調整で、モジュールからたくさんの名前をインポートするのを簡単にするためのものです。 @code{from module import names} 文において、 `names' はカンマ区切りのシーケンスです。シーケンスがとても長くなった場合、同じモジュールからのインポート文を何度も書くか、行末をバックスラッシュでエスケープするかするでしょう、このように:

@example
from SimpleXMLRPCServer import SimpleXMLRPCServer,\
            SimpleXMLRPCRequestHandler,\
            CGIXMLRPCRequestHandler,\
            resolve_dotted_attribute
@end example

Python 2.4 での文法的な変更は、単純に names を丸括弧で囲んでも良い、とするだけのものです。Python は丸括弧内の改行を無視しますので、バックスラッシュはもう必要ありません:

@example
from SimpleXMLRPCServer import (SimpleXMLRPCServer,
                                SimpleXMLRPCRequestHandler,
                                CGIXMLRPCRequestHandler,
                                resolve_dotted_attribute)
@end example

その PEP は、全ての @ref{7f8,,import} 文が絶対インポートであること、相対インポートであることを示すには @code{.} 文字で開始すること、の提案もしています。PEP のこの部分は Python 2.4 では実装されていませんが、 Python 2.5 向けには完了しています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 328

@item PEP 328@footnote{https://peps.python.org/pep-0328/} - マルチラインインポートと、絶対/相対インポート

Aahz 著.  Multi-line imports は Dima Dorfman により実装。
@end table


@c ======================================================================

@node PEP 331 Locale に依存しない Float/String 変換,その他の言語変更<17>,PEP 328 マルチラインインポート,What's New in Python 2 4
@anchor{whatsnew/2 4 pep-331-locale-independent-float-string-conversions}@anchor{167c}
@subsection PEP 331: Locale に依存しない Float/String 変換


@ref{8a,,locale} モジュールにより、Python ソフトウェアは特定の国や言語の地域化をする色々な変換や表示の変換を選択出来ます。ところがこのモジュールは、数値ロケールを変更しないように気を配らなければなりませんでした。というのも Python 内の色んな関数実装が、数値ロケールが @code{'C'} ロケールにセットされたままであることを必要としていたからです。しばしばこれは、コードが C ライブラリの @code{atof()} 関数を使っていることに原因がありました。

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.

この PEP に記述された解法は、ロケール設定を無視して ASCII のみの変換を実施する 3 つの新しい Python API 関数を追加することです:


@itemize *

@item 
@code{PyOS_ascii_strtod(str, ptr)}  and @code{PyOS_ascii_atof(str, ptr)}
both convert a string to a C double.

@item 
@code{PyOS_ascii_formatd(buffer, buf_len, format, d)} converts a
double to an ASCII string.
@end itemize

The code for these functions came from the GLib library
(https://developer-old.gnome.org/glib/2.26/@footnote{http://web.archive.org/web/20210306104320/https://developer.gnome.org/glib/2.26/}), whose developers kindly
relicensed the relevant functions and donated them to the Python Software
Foundation.  The @ref{8a,,locale} module  can now change the numeric locale,
letting extensions such as GTK+  produce the correct results.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 331

@item PEP 331@footnote{https://peps.python.org/pep-0331/} - Locale に依存しない Float/String 変換

Christian R. Reis 著, 実装 Gustavo Carneiro.
@end table


@c ======================================================================

@node その他の言語変更<17>,新たなモジュール、改良されたモジュール、非推奨のモジュール<3>,PEP 331 Locale に依存しない Float/String 変換,What's New in Python 2 4
@anchor{whatsnew/2 4 other-language-changes}@anchor{167d}
@subsection その他の言語変更


以下が、Python 2.4 言語コアに加えられた全ての変更点です。


@itemize *

@item 
関数とメソッドのためのデコレータが追加されました。 (
@geindex Python Enhancement Proposals; PEP 318
PEP 318@footnote{https://peps.python.org/pep-0318/}).

@item 
ビルトインの @ref{184,,set()} 型と @ref{7f2,,frozenset()} 型が追加されました (
@geindex Python Enhancement Proposals; PEP 218
PEP 218@footnote{https://peps.python.org/pep-0218/})。ほか新たなビルトイン関数 @code{reversed(seq)} 関数が追加されました (
@geindex Python Enhancement Proposals; PEP 322
PEP 322@footnote{https://peps.python.org/pep-0322/})。

@item 
ジェネレータ式が追加されました (
@geindex Python Enhancement Proposals; PEP 289
PEP 289@footnote{https://peps.python.org/pep-0289/}).

@item 
いくらかの数値式は、もう 32 ビットや 64 ビットに制限されません (
@geindex Python Enhancement Proposals; PEP 237
PEP 237@footnote{https://peps.python.org/pep-0237/}).

@item 
@code{from module import names} ステートメントにおいて、 `names' を括弧で囲むことが出来るようになりました (
@geindex Python Enhancement Proposals; PEP 328
PEP 328@footnote{https://peps.python.org/pep-0328/}).

@item 
@ref{167e,,dict.update()} メソッドが @ref{183,,dict} コンストラクタと同じ形式の引数を取れるようになりました。これには任意のマッピング、キー/値ペアのイテラブルとキーワード引数を含みます。 (Contributed by Raymond Hettinger.)

@item 
文字列の @code{ljust()}, @code{rjust()}, @code{center()} メソッドで空白以外の埋め文字を省略可能引数で指定出来るようになりました。 (Contributed by Raymond Hettinger.)

@item 
ほかに、文字列には @code{rsplit()} メソッドも追加されています。これは @code{split()} メソッドと似た動きをしますが、後ろから順に分割します (Contributed by Sean Reifschneider.)

@example
>>> 'www.python.org'.split('.', 1)
['www', 'python.org']
'www.python.org'.rsplit('.', 1)
['www.python', 'org']
@end example

@item 
リストの @code{sort()} メソッドに 3 つのキーワード引数 `cmp', `key', `reverse' が追加されています。これらパラメータは @code{sort()} のある種の用法を単純にします。これらは全て省略可能です。

`cmp' パラメータには比較関数を渡します。これは 2 つのパラメータを取り、パラメータの比較結果に応じて -1, 0, +1 のいずれかを返します。この関数はリストのソートに使われます。これまでの @code{sort()} に唯一許されていたのがこの `cmp' パラメータでした。

`key' には単一パラメータ関数を渡します。これはリスト要素を受け取り、要素の比較キーを返す関数です。リストはその比較キーを使ってソートされます。続く例はリストを大文字小文字区別なく並び替えます:

@example
>>> L = ['A', 'b', 'c', 'D']
>>> L.sort()                 # Case-sensitive sort
>>> L
['A', 'D', 'b', 'c']
>>> # Using 'key' parameter to sort list
>>> L.sort(key=lambda x: x.lower())
>>> L
['A', 'b', 'c', 'D']
>>> # Old-fashioned way
>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
>>> L
['A', 'b', 'c', 'D']
@end example

例の最後のものは `cmp' パラメータを使っています。これが大文字小文字区別のない並び替えの昔ながらの方法です。むろん動きます。が、 `key' パラメータでのやり方より遅いです。 `cmp' では @code{lower()} メソッド呼び出しが比較ごとなので要素ごとに 2 回呼び出すことになりますが、 `key' だと呼び出しはそれぞれの要素ごとに @code{lower()} 呼び出しを一回だけで済ませられます。

単純なキー関数や比較関数には、しばしば @ref{14b5,,lambda} 関数を避けて非束縛メソッドを使えます。例えば上記の大文字小文字によらない並べ替えはこのように書くのが最善です:

@example
>>> L.sort(key=str.lower)
>>> L
['A', 'b', 'c', 'D']
@end example

最後の `reverse' パラメータはブーリアン値を取ります。真ならばリストは逆順にソートされます。 @code{L.sort(); L.reverse()} と書く代わりにこれからは @code{L.sort(reverse=True)} と書けます。

ソートの結果がステーブル(安定)であることが保障されるようになりました。つまり 2 つの要素が同列である場合、入力と同じ順序が保たれます。例えば人物リストを名前でソートしたのちに年齢でソートすると結果は、年齢でソートされていますが同年齢の人物は名前順です。

(All changes to @code{sort()} contributed by Raymond Hettinger.)

@item 
新たに追加されたビルトイン関数 @code{sorted(iterable)} はインプレイスなメソッド @ref{dc8,,list.sort()} と似た振る舞いをしますが、式内で使えます。違いは:

@item 
入力には任意のイテラブルを取れます;

@item 
新しく構築されたコピーをソートし、オリジナルは無傷のままにします; そして

@item 
式として新しいソート済みコピーを返します。

@example
>>> L = [9,7,8,3,2,4,1,6,5]
>>> [10+i for i in sorted(L)]       # usable in a list comprehension
[11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> L                               # original is left unchanged
[9,7,8,3,2,4,1,6,5]
>>> sorted('Monty Python')          # any iterable may be an input
[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']

>>> # List the contents of a dict sorted by key values
>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
>>> for k, v in sorted(colormap.iteritems()):
...     print k, v
...
black 4
blue 2
green 3
red 1
yellow 5
@end example

(Contributed by Raymond Hettinger.)

@item 
整数演算はもはや @code{OverflowWarning} は引き起こしません。 @code{OverflowWarning} 警告は Python 2.5 で撤廃されます。

@item 
インタプリタに新たに @ref{23c,,-m} スイッチが加わりました。これは名前を取り、 @code{sys.path} にある対応するモジュールを検索し、そしてそのモジュールをスクリプトとして実行します。たとえば Python プロファイラを @code{python -m profile} で起動することが出来るようになりました。 (Contributed by Nick Coghlan.)

@item 
@code{eval(expr, globals, locals)} 関数と @code{execfile(filename, globals, locals)} 関数、 @code{exec} 文が `locals' パラメータに任意のマッピング型を受け取れるようになりました。以前は正規の Python 辞書である必要がありました。 (Contributed by Raymond Hettinger.)

@item 
ビルトイン関数の @ref{1a0,,zip()} と @code{itertools.izip()} が引数なしで呼ばれた場合に空リストを返すようになりました。以前は @ref{198,,TypeError} 例外でした。これにより可変引数リストをこなしやすくなります:

@example
>>> def transpose(array):
...    return zip(*array)
...
>>> transpose([(1,2,3), (4,5,6)])
[(1, 4), (2, 5), (3, 6)]
>>> transpose([])
[]
@end example

(Contributed by Raymond Hettinger.)

@item 
Encountering a failure while importing a module no longer leaves a partially initialized
module object in @code{sys.modules}.  The incomplete module object left
behind would fool further imports of the same module into succeeding, leading to
confusing errors.   (Fixed by Tim Peters.)

@item 
@ref{885,,None} が定数になっています。 @code{None} という名前に新しい値を割り当てようとするコードは、今では構文エラーになります。 (Contributed by Raymond Hettinger.)
@end itemize

@c ======================================================================

@menu
* 最適化: 最適化<17>. 

@end menu

@node 最適化<17>,,,その他の言語変更<17>
@anchor{whatsnew/2 4 optimizations}@anchor{167f}
@subsubsection 最適化



@itemize *

@item 
The inner loops for list and tuple slicing were optimized and now run about
one-third faster.  The inner loops for dictionaries were also optimized,
resulting in performance boosts for @code{keys()}, @code{values()}, @code{items()},
@code{iterkeys()}, @code{itervalues()}, and @code{iteritems()}. (Contributed by
Raymond Hettinger.)

@item 
The machinery for growing and shrinking lists was optimized for speed and for
space efficiency.  Appending and popping from lists now runs faster due to more
efficient code paths and less frequent use of the underlying system
@code{realloc()}.  List comprehensions also benefit.   @ref{602,,list.extend()} was
also optimized and no longer converts its argument into a temporary list before
extending the base list.  (Contributed by Raymond Hettinger.)

@item 
@ref{24d,,list()}, @ref{614,,tuple()}, @ref{19f,,map()}, @ref{a64,,filter()}, and @ref{1a0,,zip()} now
run several times faster with non-sequence arguments that supply a
@code{__len__()} method.  (Contributed by Raymond Hettinger.)

@item 
The methods @code{list.__getitem__()}, @code{dict.__getitem__()}, and
@code{dict.__contains__()} are now implemented as @code{method_descriptor}
objects rather than @code{wrapper_descriptor} objects.  This form of  access
doubles their performance and makes them more suitable for use as arguments to
functionals: @code{map(mydict.__getitem__, keylist)}. (Contributed by Raymond
Hettinger.)

@item 
Added a new opcode, @code{LIST_APPEND}, that simplifies the generated bytecode
for list comprehensions and speeds them up by about a third.  (Contributed by
Raymond Hettinger.)

@item 
The peephole bytecode optimizer has been improved to  produce shorter, faster
bytecode; remarkably, the resulting bytecode is  more readable.  (Enhanced by
Raymond Hettinger.)

@item 
String concatenations in statements of the form @code{s = s + "abc"} and @code{s +=
"abc"} are now performed more efficiently in certain circumstances.  This
optimization won't be present in other Python implementations such as Jython, so
you shouldn't rely on it; using the @code{join()} method of strings is still
recommended when you want to efficiently glue a large number of strings
together. (Contributed by Armin Rigo.)
@end itemize

The net result of the 2.4 optimizations is that Python 2.4 runs the pystone
benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2.
(pystone is not a particularly good benchmark, but it's the most commonly used
measurement of Python's performance.  Your own applications may show greater or
smaller benefits from Python 2.4.)

@c pystone is almost useless for comparing different versions of Python;
@c instead, it excels at predicting relative Python performance on different
@c machines.  So, this section would be more informative if it used other tools
@c such as pybench and parrotbench.  For a more application oriented benchmark,
@c try comparing the timings of test_decimal.py under 2.3 and 2.4.

@c ======================================================================

@node 新たなモジュール、改良されたモジュール、非推奨のモジュール<3>,ビルドならびに C API の変更<11>,その他の言語変更<17>,What's New in Python 2 4
@anchor{whatsnew/2 4 new-improved-and-deprecated-modules}@anchor{1680}
@subsection 新たなモジュール、改良されたモジュール、非推奨のモジュール


いつものように、Python の標準ライブラリには数多くの拡張とバグ修正がありました。ここでは最も注目に値する変更について、モジュールの辞書順に列挙します。変更の完全なリストについてはソースツリーの @code{Misc/NEWS} を調べるか、あるいは全ての詳細について CVS ログに目を通してみてください。


@itemize *

@item 
The @code{asyncore} module's @code{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.

@item 
The @ref{f,,base64} module now has more complete 
@geindex RFC; RFC 3548
RFC 3548@footnote{https://datatracker.ietf.org/doc/html/rfc3548.html} support for Base64,
Base32, and Base16 encoding and decoding, including optional case folding and
optional alternative alphabets. (Contributed by Barry Warsaw.)

@item 
@ref{12,,bisect} モジュールが性能改善のために C 実装を使うようになりました。 (Contributed by Dmitry Vasiliev.)

@item 
Hye-Shik Chang によって保守されている東アジアのコーデックの CJKCodecs コレクションが Python 2.4 に統合されました。新たなエンコーディングは:

@item 
Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz

@item 
Chinese (ROC): big5, cp950

@item 

@table @asis

@item Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,

iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
shift-jis, shift-jisx0213, shift-jis-2004
@end table

@item 
Korean: cp949, euc-kr, johab, iso-2022-kr

@item 
ほか、新たなエンコーディングが追加されています: HP Roman8,  ISO_8859-11, ISO_8859-16, PCTP-154, TIS-620.

@item 
UTF-8, UTF-16 コーデックが部分的な入力を受け取った場合により上手に処理するようになりました。以前は @code{StreamReader} クラスは不足データを読み出そうと試みるために、それがストリームからデコード処理を再開することを不可能にしていました。 @code{read()} メソッドは今ではそのとき読めているデータを返し、次の呼び出しで以前の読み残しのデコード処理から再開します。(Implemented by Walter Dörwald.)

@item 
There is a new @ref{1e,,collections} module for  various specialized collection
datatypes.  Currently it contains just one type, @code{deque}, a double-ended
queue that supports efficiently adding and removing elements from either
end:

@example
>>> from collections import deque
>>> d = deque('ghi')        # make a new deque with three items
>>> d.append('j')           # add a new entry to the right side
>>> d.appendleft('f')       # add a new entry to the left side
>>> d                       # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop()                 # return and remove the rightmost item
'j'
>>> d.popleft()             # return and remove the leftmost item
'f'
>>> list(d)                 # list the contents of the deque
['g', 'h', 'i']
>>> 'h' in d                # search the deque
True
@end example

@code{Queue} や @ref{f3,,threading} のようないくつかのモジュールで、 @ref{7f4,,collections.deque} を生かして性能改善を成し遂げています。 (Contributed by Raymond Hettinger.)

@item 
The @ref{26,,ConfigParser} classes have been enhanced slightly. The @ref{1681,,read()}
method now returns a list of the files that were successfully parsed, and the
@ref{1484,,set()} method raises @ref{198,,TypeError} if passed a `value' argument that
isn't a string.   (Contributed by John Belmonte and David Goodger.)

@item 
@ref{2f,,curses} モジュールが ncurses 拡張の @code{use_default_colors()} をサポートするようになりました。透明性をサポートするターミナルを持つプラットフォームならば、このことで透明背景に出来ます。 (Contributed by Jörg Lehmann.)

@item 
@ref{3b,,difflib} モジュールに @code{HtmlDiff} クラスが追加されています。これは対象テキストをサイドバイサイドで視覚化する HTML テーブルを作ります。 (Contributed by Dan Gass.)

@item 
@ref{3f,,email} パッケージがバージョン 3.0 に更新されています。多くの非推奨だった API が削除され、Python 2.3 以前のバージョンへのサポートが削除されています。パッケージのバージョン 3.0 は MIME メッセージについての漸増的な新パーサを使います。これは @code{email.FeedParser} モジュールで利用可能です。この新パーサはメモリ内に全てのメッセージを読み込んでおく必要がなく、メッセージが不正であっても例外は投げません; 代わりにメッセージの全ての問題についてを @code{defect} 属性に記録します。 (Developed by Anthony Baxter, Barry Warsaw, Thomas Wouters, and others.)

@item 
@ref{6d,,heapq} モジュールは C に変換されました。性能改善は 10 倍となり、モジュールはより大きなデータを扱うのに相応しいものになりました。加えて、モジュールには新しく 2 つの関数が追加されました。それは @code{nlargest()} と @code{nsmallest()} で、データセット内の大きいものから N 番目まで、小さいものから N 番目までを、高価な完全なソートを要することなく取り出すのに使います。(Contributed by Raymond Hettinger.)

@item 
The @ref{72,,httplib} module now contains constants for HTTP status codes defined
in various HTTP-related RFC documents.  Constants have names such as
@code{OK}, @code{CREATED}, @code{CONTINUE}, and
@code{MOVED_PERMANENTLY}; use pydoc to get a full list.  (Contributed by
Andrew Eland.)

@item 
@ref{78,,imaplib} モジュールが IMAP の THREAD コマンドをサポートするようになりました。 (contributed by Yves Dionne) また、 @code{deleteacl()} メソッドと @code{myrights()} メソッドが追加されました。 (contributed by Arnaud Mazin).

@item 
@ref{85,,itertools} モジュールに @code{groupby(iterable[, *func*])} 関数が追加されました。 `iterable' は何か要素のストリームを返すものをイテレート出来るもので、省略可能な `func' パラメータは要素を取ってキー値を返す関数です。省略されればキーは要素自身です。 @code{groupby()} は要素群をキー値の合致ごとサブシーケンスにグループ化して、キー値とサブシーケンスに対するイテレータを組とする 2 要素タプルのシリーズを返します。

例をお見せするのが早いでしょう。ここでは `key' 関数は単に数値が偶数か奇数かを返すだけです。 @code{groupby()} の結果は偶数または奇数の一連の流れを返します:

@example
>>> import itertools
>>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
...    print key_val, list(it)
...
0 [2, 4, 6]
1 [7]
0 [8]
1 [9, 11]
0 [12, 14]
>>>
@end example

@code{groupby()} は典型的にはソート済み入力に使います。 @code{groupby()} のロジックは除外、数え上げ、重複要素の特定を手軽に行う Unix の @code{uniq} フィルタに似ています:

@example
>>> word = 'abracadabra'
>>> letters = sorted(word)   # Turn string into a sorted list of letters
>>> letters
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
>>> for k, g in itertools.groupby(letters):
...    print k, list(g)
...
a ['a', 'a', 'a', 'a', 'a']
b ['b', 'b']
c ['c']
d ['d']
r ['r', 'r']
>>> # List unique letters
>>> [k for k, g in groupby(letters)]
['a', 'b', 'c', 'd', 'r']
>>> # Count letter occurrences
>>> [(k, len(list(g))) for k, g in groupby(letters)]
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
@end example

(Contributed by Hye-Shik Chang.)

@item 
@ref{85,,itertools} には @code{tee(iterator, N)} という新たな関数も追加されています。これは `iterator' の、独立した `N' 個の複製イテレータを返します。 `N' は省略されればデフォルトは 2 です。:

@example
>>> L = [1,2,3]
>>> i1, i2 = itertools.tee(L)
>>> i1,i2
(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
>>> list(i1)               # Run the first iterator to exhaustion
[1, 2, 3]
>>> list(i2)               # Run the second iterator to exhaustion
[1, 2, 3]
@end example

@code{tee()} がイテレータから返される値のコピーを維持する必要があることに注意してください。最悪の場合はそれら全てを維持する必要があるかもしれません。ですのでこれは長丁場の入力に対して、先行するイテレータが後続のイテレータの遥か先を突っ走れる場合には注意深く使わなければなりません。その分断が大きいようであれば、 @ref{24d,,list()} を代わりに使うほうが良いかもしれません。イテレータたちが相互に近い場所を追跡する場合は @code{tee()} は理想的です。ブックマーク、ウィンドウ処理、あるいは先読みイテレータといったものに適用出来るのではないでしょうか。 (Contributed by Raymond Hettinger.)

@item 
A number of functions were added to the @ref{8a,,locale}  module, such as
@code{bind_textdomain_codeset()} to specify a particular encoding and a family of
@code{l*gettext()} functions that return messages in the chosen encoding.
(Contributed by Gustavo Niemeyer.)

@item 
@ref{8b,,logging} パッケージの @code{basicConfig()} 関数に、ログ設定を簡単にするいくつかのキーワード引数が追加されました。デフォルトの振る舞いはログメッセージを標準エラー出力に出力することですが、様々なキーワード引数でログを特定のファイルに書いたり、ログのフォーマットを変えたり、ロギングのレベルを変えたり出来ます。例えば:

@example
import logging
logging.basicConfig(filename='/var/log/application.log',
    level=0,  # Log all messages
    format='%(levelname):%(process):%(thread):%(message)')
@end example

ほかの @ref{8b,,logging} パッケージへの追加としては、 便利メソッド @code{log(level, msg)} や、ログファイルを時間間隔でローテートするクラス @code{TimedRotatingFileHandler} などがあります。モジュールには元々 @code{RotatingFileHandler} が含まれており、こちらはファイルが特定のサイズを超過した場合にローテートするものです。両クラスとも新しく導出された @code{BaseRotatingHandler} 基底クラスから派生していて、これはまた別のローテートするハンドラを実装するのに使えます。

(Changes implemented by Vinay Sajip.)

@item 
@ref{91,,marshal} モジュールが、データ構造のアンパックで内部化した文字列を共有するようになりました。これはある種の pickle 文字列のサイズを切り詰めるでしょうが、主要な効能は @code{.pyc} ファイルが顕著に小さくなることです。(Contributed by Martin von Löwis.)

@item 
The @code{nntplib} module's @code{NNTP} class gained @code{description()} and
@code{descriptions()} methods to retrieve  newsgroup descriptions for a single
group or for a range of groups. (Contributed by Jürgen A. Erhard.)

@item 
@ref{a3,,operator} モジュールに 2 つの関数 @code{attrgetter(attr)} と @code{itemgetter(index)} が追加されています。両関数ともに、単一引数を取ってそれに対応する属性かアイテムを返す呼び出し可能オブジェクトを返します。これら呼び出し可能オブジェクトは @ref{19f,,map()} や @ref{dc7,,sorted()} とともに使う際の優れたデータ抽出器になります。例えば:

@example
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
>>> map(operator.itemgetter(1), L)
[2, 1, 4, 3]
>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
@end example

(Contributed by Raymond Hettinger.)

@item 
@ref{a4,,optparse} モジュールが色々更新されました。モジュールはメッセージを @ref{1682,,gettext.gettext()} を通して Optik のヘルプとエラーメッセージを国際化するのを可能にしています。オプションのヘルプメッセージは文字列 @code{'%default'} を含めることが出来るようになっており、これはオプションのデフォルト値に置換されます。(Contributed by Greg Ward.)

@item 
The long-term plan is to deprecate the @code{rfc822} module in some future
Python release in favor of the @ref{3f,,email} package. To this end, the
@ref{1683,,email.Utils.formatdate} function has been changed to make it usable as a
replacement for @code{rfc822.formatdate()}.  You may want to write new e-mail
processing code with this in mind.  (Change implemented by Anthony Baxter.)

@item 
@ref{a5,,os} モジュールに @code{urandom(n)} が追加されました。これは `n' バイトの乱数データを含む文字列を返します。この関数はプラットフォーム固有の乱数発生源にアクセスします。例えば Linux での @code{/dev/urandom} や Windows での CryptoAPI です。 (Contributed by Trevor Perrin.)

@item 
もう一つの新規関数 @code{os.path.lexists(path)} は `path' によって指定されたファイルがそれがシンボリックリンクかどうかによらず、存在している場合に真を返します。これは、既存の @code{os.path.exists(path)} 関数が `path' がシンボリックリンクでその指し先が存在しない場合に偽を返すのとは異なります。 (Contributed by Beni Cherniavsky.)

@item 
@ref{a5,,os} モジュールの下層にある @ref{b2,,posix} モジュールに @code{getsid()} 関数が追加されました。 (Contributed by J. Raynor.)

@item 
@ref{b1,,poplib} モジュールが  POP over SSL をサポートするようになりました.  (Contributed by Hector Urtubia.)

@item 
@ref{b4,,profile} モジュールが C 拡張の関数をプロファイル出来るようになりました。 (Contributed by Nick Bastin.)

@item 
@ref{bd,,random} モジュールに、 @code{getrandbits(N)} 関数が追加されました。 `N' ビット長の長整数を返します。既存の @code{randrange()} メソッドは @code{getrandbits()} を適切な場所で使うようになり、任意の大きな乱数値生成をより効果的にしています。 (Contributed by Raymond Hettinger.)

@item 
@ref{be,,re} モジュールの正規表現言語が拡張されて、単純な条件式 @code{(?(group)A|B)} を書けるようになっています。 `group' は数値グループ ID か正規表現内で @code{(?P<group>...)} で定義したグループ名のどちらかです。指定したグループが合致した場合は、正規表現パターン `A' が文字列に対してテストされ、そうでなければパターン `B' が代わりに試されます。(Contributed by Gustavo Niemeyer.)

@item 
@ref{be,,re} モジュールはもう再帰をすることはありません。Gustavo Niemeyer による膨大な量の仕事のおかげです。再帰する正規表現エンジンでは、ある種のパターンでは大量の C スタック空間を消費し、スタックのオーバーフローを起こすことがありました。例えば表現 @code{(a|b)+} が文字 @code{a} から成る 3 万バイトの文字列に対してマッチすると、一文字ごとに一つのスタックフレームを消費していました。Python 2.3 ではスタックオーバーフローのチェックを試みて @ref{244,,RuntimeError} を投げようとしましたが、ある種のパターンではチェックをすり抜けてしまって、運が悪いとセグメンテーション違反を起こしていました。Python 2.4 の正規表現エンジンではこのパターンと問題を起こすことなくマッチ出来ます。

@item 
@ref{cb,,signal} モジュールで、 @ref{134c,,signal.signal()} へのパラメータのエラーチェックを厳しくしています。例えば @code{SIGKILL} シグナルへのハンドラはセット出来ません。以前のバージョンの Python ではこれを黙って受け容れていましたが、2.4 では @ref{244,,RuntimeError} を投げます。

@item 
@ref{d1,,socket} モジュールに 2 つ新しい関数が追加されています。 @code{socketpair()} 関数は接続したソケットのペアを返し、 @code{getservbyport(port)} は与えたポート番号からサービス名を探して返します。(Contributed by Dave Cole and Barry Warsaw.)

@item 
@code{sys.exitfunc()} 関数は非推奨となりました。コードは既存の @ref{d,,atexit} モジュールを使うべきです。これは複数の終了関数呼び出しを正しく処理出来ます。結果的には @code{sys.exitfunc()} は純粋に @ref{d,,atexit} のみから使われる内部インターフェイスとなるでしょう。

@item 
@ref{e4,,tarfile} モジュールがデフォルトで GNU フォーマットを生成するようになっています。 (Contributed by Lars Gustäbel.)

@item 
@ref{f3,,threading} モジュールで、スレッドローカルなデータのサポートについて、品の良い単純な方法でサポート出来ました。モジュールは @code{local} クラスを持っており、その属性値は異なるスレッドごとにローカルになります:

@example
import threading

data = threading.local()
data.number = 42
data.url = ('www.python.org', 80)
@end example

この場合他のスレッドは @code{number} 属性、 @code{url} 属性に自身の値を代入、抽出出来ます。 @code{local} クラスは属性初期化であるとかメソッドの追加のためにサブクラス化することも出来ます。 (Contributed by Jim Fulton.)

@item 
@ref{f5,,timeit} モジュールはループを計測中は周期的なガーベージコレクションを自動で無効化するようになりました。この変更により、繰り返しの計測の比較がやりやすくなります。 (Contributed by Raymond Hettinger.)

@item 
@ref{11a,,weakref} モジュールがサポートするオブジェクトが非常に幅広くなりました。これには Python 関数、クラスインスタンス, set, frozenset, deque, array と正規表現パターンオブジェクトが含まれます。(Contributed by Raymond Hettinger.)

@item 
The @ref{134,,xmlrpclib} module now supports a multi-call extension for
transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by
Brian Quinlan.)

@item 
@code{mpz}, @code{rotor},  @code{xreadlines}  モジュールは削除されました。
@end itemize

@c ======================================================================

@c whole new modules get described in subsections here

@c =====================

@menu
* cookielib:: 
* doctest: doctest<5>. 

@end menu

@node cookielib,doctest<5>,,新たなモジュール、改良されたモジュール、非推奨のモジュール<3>
@anchor{whatsnew/2 4 cookielib}@anchor{1684}
@subsubsection cookielib


The @ref{74,,cookielib} library supports client-side handling for HTTP cookies,
mirroring the @ref{75,,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.

セッションを跨いでクッキーを記憶するために、2 つのクッキー瓶実装が提供されています。一つは Netscape フォーマットでクッキーを記憶するのでアプリケーションは Mozilla か Lynx のクッキーファイルを使え、もう一つは Perl の libwww ライブラリと同じフォーマットでクッキーを記憶します。

@ref{111,,urllib2} has been changed to interact with @ref{74,,cookielib}:
@code{HTTPCookieProcessor} manages a cookie jar that is used when accessing
URLs.

このモジュールは John J. Lee により寄稿されました。

@c ==================

@node doctest<5>,,cookielib,新たなモジュール、改良されたモジュール、非推奨のモジュール<3>
@anchor{whatsnew/2 4 doctest}@anchor{1685}
@subsubsection doctest


Edward Loper と Tim Peters のおかげにより、 @ref{3e,,doctest} モジュールに注目に値するリファクタリングが入りました。テストはこれまで通り単純に @ref{1686,,doctest.testmod()} を実行するすることで行えますが、リファクタリングはモジュールの操作をカスタマイズする色々な手段を提供してくれます。

新規クラス @code{DocTestFinder} は指定したオブジェクトの docstring からテストを抽出します:

@example
def f (x, y):
    """>>> f(2,2)
4
>>> f(3,2)
6
    """
    return x*y

finder = doctest.DocTestFinder()

# Get list of DocTest instances
tests = finder.find(f)
@end example

新規クラス @code{DocTestRunner} はテストを個々に実行し、結果の要約を生成出来ます:

@example
runner = doctest.DocTestRunner()
for t in tests:
    tried, failed = runner.run(t)

runner.summarize(verbose=1)
@end example

上の例はこのような出力を生成します:

@example
1 items passed all tests:
   2 tests in f
2 tests in 1 items.
2 passed and 0 failed.
Test passed.
@end example

@code{DocTestRunner} は実際の出力と結果の期待値の比較に、 @code{OutputChecker} のインスタンスを使います。このクラスはその振る舞いをカスタマイズする色々なフラグを取ります。意欲的なユーザであれば @code{OutputChecker} の完全な新しいサブクラスも書けます。

デフォルトの出力チェッカーは多くのお手軽機能を持っています。例えば @ref{1687,,doctest.ELLIPSIS} オプションフラグは、出力の期待値内での省略記号 (@code{...}) と任意文字列を一致するとみなし、瑣末な部分が変化するような出力に簡単に適合するように出来ます:

@example
def o (n):
    """>>> o(1)
<__main__.C instance at 0x...>
>>>
"""
@end example

もう一つの特殊文字列 @code{<BLANKLINE>} は空行に合致します:

@example
def p (n):
    """>>> p(1)
<BLANKLINE>
>>>
"""
@end example

もう一つの新機能は出力の diff スタイル出力で、オプションフラグに @ref{1688,,doctest.REPORT_UDIFF} (unified diffs), @ref{1689,,doctest.REPORT_CDIFF} (context diffs), @ref{168a,,doctest.REPORT_NDIFF} (delta-style) を指定することで利用出来ます。例えば以下があるとして:

@example
def g (n):
    """>>> g(4)
here
is
a
lengthy
>>>"""
    L = 'here is a rather lengthy list of words'.split()
    for word in L[:n]:
        print word
@end example

Running the above function's tests with @ref{1688,,doctest.REPORT_UDIFF} specified,
you get the following output:

@example
**********************************************************************
File "t.py", line 15, in g
Failed example:
    g(4)
Differences (unified diff with -expected +actual):
    @@@@ -2,3 +2,3 @@@@
     is
     a
    -lengthy
    +rather
**********************************************************************
@end example

@c ======================================================================

@node ビルドならびに C API の変更<11>,Python 2 4 への移植,新たなモジュール、改良されたモジュール、非推奨のモジュール<3>,What's New in Python 2 4
@anchor{whatsnew/2 4 build-and-c-api-changes}@anchor{168b}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
拡張関数からの戻り値として一般的に使うための 3 つの便利なマクロが追加されています: @ref{168c,,Py_RETURN_NONE}, @ref{168d,,Py_RETURN_TRUE}, @ref{168e,,Py_RETURN_FALSE} (Contributed by Brett Cannon.)

@item 
Another new macro, @ref{798,,Py_CLEAR},  decreases the reference count of
`obj' and sets `obj' to the null pointer.  (Contributed by Jim Fulton.)

@item 
新規関数 @code{PyTuple_Pack(N, obj1, obj2, ..., objN)} は Python オブジェクトの可変長引数リストからタプルを構築します。 (Contributed by Raymond Hettinger.)

@item 
新規関数 @code{PyDict_Contains(d, k)} は、処理内で起こる例外のマスキングなしでの高速なルックアップを実装しています。 (Contributed by Raymond Hettinger.)

@item 
The @ref{168f,,Py_IS_NAN}(X) macro returns 1 if  its float or double argument
`X' is a NaN.   (Contributed by Tim Peters.)

@item 
C code can avoid unnecessary locking by using the new
@code{PyEval_ThreadsInitialized()} function to tell  if any thread operations
have been performed.  If this function  returns false, no lock operations are
needed. (Contributed by Nick Coghlan.)

@item 
新規関数 @ref{625,,PyArg_VaParseTupleAndKeywords()} は @ref{624,,PyArg_ParseTupleAndKeywords()} と同じですが、たくさんの引数の代わりに @code{va_list} を取ることだけが違います。(Contributed by Greg Chapman.)

@item 
A new method flag, @ref{1690,,METH_COEXIST}, allows a function defined in slots
to co-exist with a @ref{1691,,PyCFunction} having the same name.  This can halve
the access time for a method such as @code{set.__contains__()}.  (Contributed by
Raymond Hettinger.)

@item 
Python can now be built with additional profiling for the interpreter itself,
intended as an aid to people developing the Python core.  Providing
@code{--enable-profiling} to the @code{configure} script will let you
profile the interpreter with @code{gprof}, and providing the
@code{--with-tsc} switch enables profiling using the Pentium's
Time-Stamp-Counter register.  Note that the @code{--with-tsc} switch is slightly
misnamed, because the profiling feature also works on the PowerPC platform,
though that processor architecture doesn't call that register "the TSC
register".  (Contributed by Jeremy Hylton.)

@item 
The @code{tracebackobject} type has been renamed to
@code{PyTracebackObject}.
@end itemize

@c ======================================================================

@menu
* ポート特有の変更: ポート特有の変更<2>. 

@end menu

@node ポート特有の変更<2>,,,ビルドならびに C API の変更<11>
@anchor{whatsnew/2 4 port-specific-changes}@anchor{1692}
@subsubsection ポート特有の変更



@itemize *

@item 
Windows ポートは MSVC++ 6 と 7.1 でビルド出来ます。 (Contributed by Martin von Löwis.)
@end itemize

@c ======================================================================

@node Python 2 4 への移植,謝辞<4>,ビルドならびに C API の変更<11>,What's New in Python 2 4
@anchor{whatsnew/2 4 porting-to-python-2-4}@anchor{1693}
@subsection Python 2.4 への移植


このセクションでは前述の変更により必要となるかもしれないコードの変更を列挙します:


@itemize *

@item 
大き過ぎる値を持つ左シフトと 16 進/ 8 進定数が @ref{659,,FutureWarning} を引き起こした上で 32 ビットまたは 64 ビットに制限される、という振る舞いはもうしません。代わりに長整数を返します。

@item 
整数演算はもはや @code{OverflowWarning} は引き起こしません。 @code{OverflowWarning} 警告は Python 2.5 で撤廃されます。

@item 
ビルトイン関数の @ref{1a0,,zip()} と @code{itertools.izip()} が引数なしで呼ばれた場合に、 @ref{198,,TypeError} 例外を起こすのではなく空リストを返すようになりました。

@item 
You can no longer compare the @code{date} and @ref{4e2,,datetime} instances
provided by the @ref{34,,datetime} module.  Two  instances of different classes
will now always be unequal, and  relative comparisons (@code{<}, @code{>}) will raise
a @ref{198,,TypeError}.

@item 
@code{dircache.listdir()} now passes exceptions to the caller instead of
returning empty lists.

@item 
@code{LexicalHandler.startDTD()} はパブリックでシステムの ID を間違った順序で受け取っていました。これは修正されました; この間違った順序に依存したアプリケーションは修正しなければなりません。

@item 
@ref{1694,,fcntl.ioctl()} は `mutate_flag' 引数が省略されて問題に関係がある場合は警告を出します。

@item 
@ref{e4,,tarfile} モジュールがデフォルトで GNU フォーマットを生成するようになっています。

@item 
Encountering a failure while importing a module no longer leaves a
partially initialized module object in @code{sys.modules}.

@item 
@ref{885,,None} が定数になっています。 @code{None} という名前に新しい値を割り当てようとするコードは、今では構文エラーになります。

@item 
@code{signals.signal()} 関数は、ある種の不正な値では @ref{244,,RuntimeError} を投げるようになっています。以前はこれらエラーは黙って通していました。例えばもう @code{SIGKILL} へはハンドラは渡せません。
@end itemize

@c ======================================================================

@node 謝辞<4>,,Python 2 4 への移植,What's New in Python 2 4
@anchor{whatsnew/2 4 acknowledgements}@anchor{1695}@anchor{whatsnew/2 4 acks}@anchor{1696}
@subsection 謝辞


著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の人々に感謝します: Koray Can, Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson, Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 3,What's New in Python 2 2,What's New in Python 2 4,What's New in Python
@anchor{whatsnew/2 3 doc}@anchor{1697}@anchor{whatsnew/2 3 translation-repo}@anchor{1698}@anchor{whatsnew/2 3 what-s-new-in-python-2-3}@anchor{1699}
@section What's New in Python 2.3


@*著者: 
A.M. Kuchling


@c $Id: whatsnew23.tex 54631 2007-03-31 11:58:36Z georg.brandl $

この文書は Python 2.3 の新機能について解説します。Python 2.3 は 2003 年 7 月 29 日にリリースされました。

Python 2.3 の主要なテーマは、2.2 で追加されたいくつかの機能を磨くこと、言語中核に小さいながらも有用な種々の拡張をすること、そして標準ライブラリの拡充です。ひとつ前のバージョンで導入された新しいオブジェクトモデルは、18 ヶ月に渡るバグフィックスと新スタイルクラスの性能改善をもたらした最適化の努力の恩恵を受けました。 @ref{695,,sum()}, @ref{169a,,enumerate()} のような、新たなビルトイン関数が少し追加されました。 @ref{34b,,in} 演算子がサブストリングの検索に使えるようになりました (例えば @code{"ab" in "abc"} は @ref{e07,,True} を返します)。

たくさんのライブラリ新機能…、Boolean、 set、 heap、 日付/時刻データ型、ZIP 形式アーカイブからのモジュールインポート、待ち望まれていた Python カタログのためのメタデータサポート、更新されたバージョンの IDLE、ロギングメッセージのためのモジュール、テキストの折り返し、CSV ファイルの解析、コマンドラインオプションの処理、BerkeleyDB データベースの使用…、新機能、強化機能のリストは長大になります。

このドキュメントは個々の新機能の完全な詳細を提供するのではなくて、簡易な概要を提供することを目的にしています。完全な詳細が知りたければ、 Python ライブラリリファレンス、Python リファレンスマニュアルのような Python 2.4 のドキュメントを参照してください。設計と実装の根拠を理解したい場合は、新機能に関する PEP を参照してください。

@c ======================================================================

@menu
* PEP 218; 標準の集合データ型: PEP 218 標準の集合データ型. 
* PEP 255; 単純なジェネレータ: PEP 255 単純なジェネレータ. 
* PEP 263; ソースコードのエンコーディング: PEP 263 ソースコードのエンコーディング. 
* PEP 273; Zip アーカイブからモジュールをインポートする: PEP 273 Zip アーカイブからモジュールをインポートする. 
* PEP 277; Windows NT での Unicode ファイル名サポート: PEP 277 Windows NT での Unicode ファイル名サポート. 
* PEP 278; Universal Newline サポート: PEP 278 Universal Newline サポート. 
* PEP 279; enumerate(): PEP 279 enumerate. 
* PEP 282; ロギングパッケージ: PEP 282 ロギングパッケージ. 
* PEP 285; Boolean 型: PEP 285 Boolean 型. 
* PEP 293; コーデックエラーを処理するコールバック: PEP 293 コーデックエラーを処理するコールバック. 
* PEP 301; パッケージインデクスと、 Distutils のためのメタデータ: PEP 301 パッケージインデクスと、 Distutils のためのメタデータ. 
* PEP 302; 新たなインポートフック: PEP 302 新たなインポートフック. 
* PEP 305; カンマ区切り形式ファイル: PEP 305 カンマ区切り形式ファイル. 
* PEP 307; Pickle の機能拡張: PEP 307 Pickle の機能拡張. 
* 拡張スライス:: 
* その他の言語変更: その他の言語変更<18>. 
* 新たなモジュール、改良されたモジュール、非推奨のモジュール: 新たなモジュール、改良されたモジュール、非推奨のモジュール<4>. 
* Pymalloc; 特殊化されたオブジェクトアロケータ: Pymalloc 特殊化されたオブジェクトアロケータ. 
* ビルドならびに C API の変更: ビルドならびに C API の変更<12>. 
* その他の変更と修正: その他の変更と修正<2>. 
* Python 2.3 への移植: Python 2 3 への移植. 
* 謝辞: 謝辞<5>. 

@end menu

@node PEP 218 標準の集合データ型,PEP 255 単純なジェネレータ,,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-218-a-standard-set-datatype}@anchor{169b}
@subsection PEP 218: 標準の集合データ型


(---訳注: イキナリですが、あなたが今これを「Python の歴史を知る」もしくは「初登場時の熱量高い紹介」を読みたくて読んでいるのでない限りは、もしくは本当に今 2.3 を使う必要があれば別ですが、このモジュールは 2.4 で既にビルトインで置き換えられ、2.6 では非推奨となり、3.0 では削除されています。ので、集合型について知りたければここよりも 2.4 のビルトインの方から読んだ方が良いです。---) --- 新しいモジュール @code{sets} には、集合データ型の実装が含まれています。 @code{Set} クラスは @ref{15ba,,mutable} の集合のためのクラスで、メンバの追加と削除が出来ます。 @code{ImmutableSet} は変更できない集合のためのクラスなので、@code{ImmutableSet} のインスタンスを辞書のキーとして利用出来ます。集合型は辞書の上に構築されているので、集合内の要素はハッシュ可能でなければなりません。

単純な使用例です:

@example
>>> import sets
>>> S = sets.Set([1,2,3])
>>> S
Set([1, 2, 3])
>>> 1 in S
True
>>> 0 in S
False
>>> S.add(5)
>>> S.remove(3)
>>> S
Set([1, 2, 5])
>>>
@end example

The union and intersection of sets can be computed with the @ref{169c,,union()} and
@ref{169d,,intersection()} methods; an alternative notation uses the bitwise operators
@code{&} and @code{|}. Mutable sets also have in-place versions of these methods,
@code{union_update()} and @ref{169e,,intersection_update()}.

@example
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([4,5,6])
>>> S1.union(S2)
Set([1, 2, 3, 4, 5, 6])
>>> S1 | S2                  # Alternative notation
Set([1, 2, 3, 4, 5, 6])
>>> S1.intersection(S2)
Set([])
>>> S1 & S2                  # Alternative notation
Set([])
>>> S1.union_update(S2)
>>> S1
Set([1, 2, 3, 4, 5, 6])
>>>
@end example

It's also possible to take the symmetric difference of two sets.  This is the
set of all elements in the union that aren't in the intersection.  Another way
of putting it is that the symmetric difference contains all elements that are in
exactly one set.  Again, there's an alternative notation (@code{^}), and an
in-place version with the ungainly name @ref{169f,,symmetric_difference_update()}.

@example
>>> S1 = sets.Set([1,2,3,4])
>>> S2 = sets.Set([3,4,5,6])
>>> S1.symmetric_difference(S2)
Set([1, 2, 5, 6])
>>> S1 ^ S2
Set([1, 2, 5, 6])
>>>
@end example

@code{issubset()} と @code{issuperset()} メソッドも使えます。これはある集合が部分集合、上位集合であるかとうかをチェックします:

@example
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([2,3])
>>> S2.issubset(S1)
True
>>> S1.issubset(S2)
False
>>> S1.issuperset(S2)
True
>>>
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 218

@item PEP 218@footnote{https://peps.python.org/pep-0218/} - 集合オブジェクト型をビルトインに追加する

PEP 著 Greg V. Wilson. 実装: Greg V. Wilson, Alex Martelli, GvR. (---訳注: PEPそのものは 2.4 のビルトイン型 set, frozenset の追加と同じものですが、2.3 ではモジュールとして追加され、2.4 でビルトイン版が追加され、2.6 でモジュール版が非推奨となった、という流れです。---)
@end table


@c ======================================================================

@node PEP 255 単純なジェネレータ,PEP 263 ソースコードのエンコーディング,PEP 218 標準の集合データ型,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-255-simple-generators}@anchor{16a0}@anchor{whatsnew/2 3 section-generators}@anchor{16a1}
@subsection PEP 255: 単純なジェネレータ


Python 2.2 では、ジェネレータが @code{from __future__ import generators} ディレクティブで有効に出来るオプションの機能として追加されました。2.3 ではジェネレータは特別に有効化する必要なく、もうキーワード @ref{bc2,,yield} として、いつでもそこにあります。このセクションの残りの部分は "What's New in Python 2.2" のジェネレータの記述からの丸々コピーですので、2.2 のときに読んだなら読み飛ばしてもらって結構です。

Python や C の標準的な関数コールについては、よくご存じに違いありません。関数を呼ぶと、ローカル変数を作るプライベートな名前空間ができますね。その関数が @ref{1af,,return} 文まで来ると、ローカル変数が破壊されてから、返り値が呼び出し元に返ります。次に同じ関数をもう一度呼ぶと、新しいプライベート名前空間に新規のローカル変数が作られるのです。しかし、関数を出るときにローカル変数を捨てなければどうなるでしょうか。その出ていったところから関数を続行できたとしたら、どうでしょう。これこそジェネレータが提供する機能です; すなわち、ジェネレータは続行できる関数と考えることができます。

ジェネレータ関数の最も単純な例です:

@example
def generate_ints(N):
    for i in range(N):
        yield i
@end example

新しいキーワード @ref{bc2,,yield} がジェネレータのために導入されました。 @code{yield} ステートメントを含むどんな関数もジェネレータ関数です; Python バイトコードコンパイラはこれを検知し、関数が特別に扱われるように翻訳します。 (---訳注: Python 2.5 の PEP 342 も参照して下さい。この 2.2 で導入時点の @code{yield} はステートメントではなく式に変更されています。---)

ジェネレータ関数を呼び出すと、単一の値の代わりにイテレータプロトコルに対応したオブジェクトを返します。上の例で @code{yield} を実行したとき、ジェネレータは @code{return} 文のようにして @code{i} の値を生成します。 @code{yield} と @code{return} 文の大きな違いは、 @code{yield} に到達した段階でジェネレータの実行状態が一時停止になって、ローカル変数が保存される点です。次回そのジェネレータの @code{.next()} メソッドを呼ぶと、 @code{yield} の直後から関数が実行を再開します。(複雑な理由により、 @code{yield} は @code{try}...@ref{1b0,,finally} の @code{try} ブロック内に含めることは許されていません; 
@geindex Python Enhancement Proposals; PEP 255
PEP 255@footnote{https://peps.python.org/pep-0255/} に @code{yield} と例外の相互作用についての詳細説明がありますので参照して下さい。) --- (---訳注: Python 2.5 の PEP 342 で @ref{8f8,,try}...@ref{1b0,,finally} 内に置けないという制約はなくなりました。また、 @ref{8f8,,try}...@ref{1b0,,finally} の @ref{8f8,,try} 、とここであえて特定しているのは、同じく 2.5 の PEP 341 によって try/except/finally の一体化されるまでは、 @code{finally} の @code{try} と @code{except} の @code{try} が別物だったからです。---)

上記の @code{generate_ints()} ジェネレータはこんな具合に使います:

@example
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
  File "stdin", line 1, in ?
  File "stdin", line 2, in generate_ints
StopIteration
@end example

同じく @code{for i in generate_ints(5)} や @code{a,b,c = generate_ints(3)} といった書き方もできます。

ジェネレータ関数内で @ref{1af,,return} 文は、引数を付けずに、処理の終わりを知らせるためにだけ使うことができます; @code{return} を実行したあとは、もうそのジェネレータが値を返すことはできません。ジェネレータ関数の中では、 @code{return 5} などと値を付けた @code{return} は構文エラーです。ジェネレータの出力が終わったことを示すには、ほかにも、手動で @ref{df5,,StopIteration}  を投げてもいいですし、関数の最後まで実行するだけでも同じことになります。(---訳注: Python 2.7 まではジェネレータ内での戻り値のある @code{return 5} は構文エラーになりますが、少なくとも Python 3.4 で構文エラーとはなりません。単に無視されます。リファレンスに言及されていない振舞いなので、何かの事故かもしれません。いずれにせよジェネレータ内では Python 3 でも @code{return} で値は戻せません。---)

自分でクラスを書いて、ジェネレータで言うところのローカル変数をインスタンス変数として全部保管しておけば、同じ効果を得ることは可能です。たとえば整数のリストを返すのは、 @code{self.count} を 0 にして、 @ref{9d8,,next()} メソッドが @code{self.count} をインクリメントして返すようにすればできます。しかしながら、ある程度複雑なジェネレータになってくると、同じことをするクラスを書くのは格段にややこしいことになります。 @code{Lib/test/test_generators.py} にはもっと面白い例がたくさん含まれています。一番単純な一つは、ジェネレータを再帰的に使ってツリーを順繰りに横断する実装をするこれです (---訳注: ジェネレータは現在の最新 3.5 までの間に 2 度大きな機能強化が行われているのですが、一つが 2.5 での PEP 342 でこれは yield 「に」値を戻せるようにするものです。もう一つが 3.3 での PEP 380 で、これはサブジェネレータへの委譲 @code{yield from <subgen>} の追加でした。ですのでこの 3.3 からの @code{yield from} を使うと下記例はもっとスッキリ書けます。---):

@example
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x
@end example

ほかにも @code{Lib/test/test_generators.py} には、N-Queens 問題 (N×N コマのチェス盤に、互いに攻撃できないような配置で N 個のクイーンを置く) やナイト・ツアー (N×N 盤の全コマをナイトが一度ずつ通るような経路を探す) の解を出す例が入っています。

ジェネレータの発想はほかのプログラミング言語、特に Icon (@indicateurl{https://www2.cs.arizona.edu/icon/}) から着想しています。Icon ではジェネレータが言語の中枢になっています。Icon では、あらゆる式と関数がジェネレータのように振舞います。 @indicateurl{https://www2.cs.arizona.edu/icon/docs/ipd266.htm} の "Icon プログラミング言語の概要" の一つの例が、これがどのようなものであるのかを教えてくれます:

@example
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
@end example

Icon では @code{find()} 関数は部分文字列 "or" が見つかる位置 3, 23, 33 を返します。 @ref{181,,if} 文内では @code{i} には最初 3 が代入されますが、これは 3 より小さいので比較は失敗し、Icon は次の値 23 を取り出します。 23 は 5 より大きいので比較は成功し、コードは 23 をスクリーンに表示します。

Python では Icon がそうするほどにはジェネレータを中心的概念に置きません。ジェネレータは Python 言語中核の新たな一面ではありますが、それらを学ぶのも使うのも誰しも行うべきだというものでもなく、そしてこれで解決できない何か問題があれば、忘れてしまっても良いものです。Icon と比較した特筆すべき Python インターフェイスの機能はジェネレータの状態が具象オブジェクト (イテレータ) で表現されることであり、それは他の関数に渡せますし、データ構造に記憶しておくことも出来ます。(---訳注: ジェネレータについてかなり控えめなのは、この時点で著者は将来の拡張を既に見据えていたから? かもしれませんね。PEP 342 と PEP 380 により今やジェネレータはこの頃より遥かに高機能になっており、今ではきっと「こんなものなくても困らない」なんて Python 使いはいないでしょう。---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 255

@item PEP 255@footnote{https://peps.python.org/pep-0255/} - 単純なジェネレータ

Neil Schemenauer, Tim Peters, Magnus Lie Hetland により著されました。実装のほとんどは Neil Schemenauer と Tim Peters により行われ、 Python Labs クルーにより他の修正が行われました。
@end table


@c ======================================================================

@node PEP 263 ソースコードのエンコーディング,PEP 273 Zip アーカイブからモジュールをインポートする,PEP 255 単純なジェネレータ,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-263-source-code-encodings}@anchor{16a2}@anchor{whatsnew/2 3 section-encodings}@anchor{16a3}
@subsection PEP 263: ソースコードのエンコーディング


Python ソースファイルで、異なる文字セットエンコーディングを宣言出来るようになりました。エンコーディングはソースコードの 1 行目か 2 行目に特殊形式のコメントを含めることで宣言出来ます。 UTF-8 ファイルであればこのように宣言出来ます:

@example
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
@end example

このエンコーディング宣言がなければ、デフォルトの 7 ビット ASCII エンコーディングが使われます(訳注: Python 3 からはデフォルトは utf-8 (PEP 3120))。8 ビット文字を含んでいるのにエンコーディング宣言がないモジュールの実行やインポートを行うと、 Python 2.3 では @ref{1a3,,DeprecationWarning} を引き起こします; 2.4 ではこれは構文エラーになる予定です(訳注: 実際には 2.4 ではこれは実現せず、2.5 から)。

エンコーディング宣言は Unicode 文字列リテラルにのみ影響します。それらは指定したエンコーディングで Unicode 文字列に変換されます。Python 識別子は今でも ASCII 文字列に制限されていることに注意してください。ですから普通の英数字範囲外の文字を変数名に使うことは出来ません。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 263

@item PEP 263@footnote{https://peps.python.org/pep-0263/} - Python ソースコードのエンコーディングを定義する

Marc-André Lemburg、 Martin von Löwis 著; Suzuki Hisao、 Martin von Löwis 実装.
@end table


@c ======================================================================

@node PEP 273 Zip アーカイブからモジュールをインポートする,PEP 277 Windows NT での Unicode ファイル名サポート,PEP 263 ソースコードのエンコーディング,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-273-importing-modules-from-zip-archives}@anchor{16a4}
@subsection PEP 273: Zip アーカイブからモジュールをインポートする


新たなモジュール @ref{138,,zipimport} が、ZIP フォーマットの書庫からモジュールのインポートをサポートします。 @ref{138,,zipimport} を明示的にインポートする必要はありません; @code{sys.path} に ZIP 形式書庫が追加されるとそれは自動的にインポートされます。例えば:

@example
amk@@nyman:~/src/python$ unzip -l /tmp/example.zip
Archive:  /tmp/example.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
amk@@nyman:~/src/python$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'
>>>
@end example

@code{sys.path} には今や ZIP 書庫のファイル名も入れることが出来ます。ZIP アーカイブ内にはどんなファイルを置いてもかまいませんが、import できるのは @code{*.py}, @code{*.pyc}, @code{*.pyo} だけです。書庫に @code{*.py} だけが含まれる場合には、Python は書庫を修正して対応する @code{*.pyc} を作るなどということはしないので、 @code{*.pyc} ファイルを含まない ZIP 書庫からのインポートはやや遅いかもしれません。

書庫内のパスをサブディレクトリ以下のみインポートするように指定出来ます; 例えば、パス @code{/tmp/example.zip/lib/} はその書庫内の @code{lib/} サブディレクトリだけからインポートします。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 273

@item PEP 273@footnote{https://peps.python.org/pep-0273/} - Zip アーカイブからモジュールをインポートする

このモジュールの実装も行った、James C. Ahlstrom による PEP です。 Python 2.3 は  
@geindex Python Enhancement Proposals; PEP 273
PEP 273@footnote{https://peps.python.org/pep-0273/} の仕様に従っていますが、 Just van Rossum の書いた、 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} に記述されているインポートフックによる実装を使っています。その新しいインポートフックについては  @ref{16a5,,PEP 302; 新たなインポートフック}  をみてください。
@end table


@c ======================================================================

@node PEP 277 Windows NT での Unicode ファイル名サポート,PEP 278 Universal Newline サポート,PEP 273 Zip アーカイブからモジュールをインポートする,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-277-unicode-file-name-support-for-windows-nt}@anchor{16a6}
@subsection PEP 277: Windows NT での Unicode ファイル名サポート


Windows NT, 2000, XP では、ファイルシステムはファイル名として Unicode 文字列を使います。伝統的に Python はファイル名をバイト文字列として表現してきましたが、それはアクセス出来ないファイル名を表してしまう場合があって、不十分でした。

Python はいまや (ファイルシステムの制約の範囲内での) 任意の Unicode 文字列を @ref{316,,open()} 組み込み関数をはじめとするファイル名が期待される全ての関数で許容します。 @ref{1312,,os.listdir()} に Unicode 文字列が渡されれば、Python は今では Unicode 文字列のリストを返します。新しい関数 @code{os.getcwdu()} は Unicode 文字列でカレントディレクトリを返します(訳注: ちなみに Python 3 での Unicode 周りの大改造に伴いこの関数はなくなり、代わりに「あえてバイト列のほうを返す」  が追加されています(@code{os.getcwdu()} がもはや Unicode を返すので)。)。

ファイル名のバイト文字列はいまでも動きます。Windows 版 Python は透過的にそれらを Unicode に @code{mbcs} エンコーディングを使って変換します。

Other systems also allow Unicode strings as file names but convert them to byte
strings before passing them to the system, which can cause a @ref{462,,UnicodeError}
to be raised. Applications can test whether arbitrary Unicode strings are
supported as file names by checking @ref{16a7,,os.path.supports_unicode_filenames},
a Boolean value.

MacOS では、 @ref{1312,,os.listdir()} は Unicode ファイル名を返すようになっているでしょう。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 277

@item PEP 277@footnote{https://peps.python.org/pep-0277/} - Windows NT での Unicode ファイル名サポート

Neil Hodgson 著; 実装 Neil Hodgson, Martin von Löwis, Mark Hammond。
@end table


@c ======================================================================

@geindex universal newlines;What's new

@node PEP 278 Universal Newline サポート,PEP 279 enumerate,PEP 277 Windows NT での Unicode ファイル名サポート,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-278-universal-newline-support}@anchor{16a8}
@subsection PEP 278: Universal Newline サポート


今日では 3 つの主要なオペレーティングシステムが使われています。 Microsoft Windows, Apple の Macintosh OS, さまざまな Unix 派生系です。テキストファイルの行終端マークに使う文字がこれら 3 つ全てでそれぞれ違っていることが、クロスプラットフォームのための仕事における小さな苛立ちです。  Unix が使うのはラインフィード (ASCII 文字 10), MacOS が使うのはキャリッジリターン (ASCII 文字 13),  Windows に至ってはキャリッジリターンとラインフィード 2 文字のシーケンスを使います。

Python のファイルオブジェクトが、動作しているプラットフォームに従わない行終端変換をサポートするようになりました。ファイルのオープンにモード @code{'U'} や @code{'rU'} を使うと、 @ref{f35,,universal newlines} モードを使った読み込みとしてファイルを開きます。これで @code{read()}, @code{readline()} などのファイルメソッドが、 3 つどの行終端でも @code{'\n'} という文字列に翻訳して返すようになります。

universal newline サポートはモジュールのインポートと @code{execfile()} 関数でのファイル実行にも使われます。これで 3 つ全てのオペレーティングシステム間で行終端変換の必要なく Python モジュールを共有出来ます。

この機能は Python をソースからビルドする際に @code{configure} スクリプトに @code{--without-universal-newlines} スイッチ を付けることで無効に出来ます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 278

@item PEP 278@footnote{https://peps.python.org/pep-0278/} : Universal Newline サポート

Jack Jansen 著、実装
@end table


@c ======================================================================

@node PEP 279 enumerate,PEP 282 ロギングパッケージ,PEP 278 Universal Newline サポート,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-279-enumerate}@anchor{16a9}@anchor{whatsnew/2 3 section-enumerate}@anchor{16aa}
@subsection PEP 279: enumerate()


新たな組み込み関数 @ref{169a,,enumerate()} はある種のループ処理を少し簡潔にするものです。 `thing' がイテレータかシーケンスだとして、 @code{enumerate(thing)} は @code{(0, thing[0])}, @code{(1, thing[1])}, @code{(2, thing[2])}, … を生成するイテレータを返します。

リストの全てを変更するためのよくあるイディオムはこのようなものでしょう:

@example
for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result
@end example

これは @ref{169a,,enumerate()} を使ってこのように書き換えることが出来ます:

@example
for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 279

@item PEP 279@footnote{https://peps.python.org/pep-0279/} - 組み込み関数 enumerate()

Raymond D. Hettinger 著、実装.
@end table


@c ======================================================================

@node PEP 282 ロギングパッケージ,PEP 285 Boolean 型,PEP 279 enumerate,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-282-the-logging-package}@anchor{16ab}
@subsection PEP 282: ロギングパッケージ


ログ記録のための標準パッケージ @ref{8b,,logging} が Python 2.3 に追加されています。それはログ出力生成の強力で柔軟なメカニズムを提供し、フィルタと加工を色々な方法で行えます。標準フォーマットで書く設定ファイルで、プログラムのロギングの振る舞いを制御出来ます。ログレコードを標準エラー出力やファイルやソケット、システムログへの送信、あるいは e-mail 送信するようなハンドラが Python に含まれています。もちろん、あなた自身のハンドラクラスを書くことも出来ます。

@ref{d46,,Logger} が最も重要なクラスです。ほとんどのアプリケーションコードは一つかそれ以上の @ref{d46,,Logger} オブジェクトを扱い、それぞれ一つはそのアプリケーションの特定のサブシステムで使われるでしょう。それぞれの @ref{d46,,Logger} は名前で識別され、名前は @code{.} をコンポーネントのセパレータとして使う階層で体系化されます。例えば、 @code{server}, @code{server.auth}, @code{server.network} といった名前の @ref{d46,,Logger} インスタンスを持つといった具合です。この例の後ろ 2 つは階層で @code{server} の下にあります。 @code{server} への冗長性を見つけた場合や @code{server} メッセージを直接異なるハンドラに向けた場合、変更は @code{server.auth} と @code{server.network} へのログ記録にも適用されるということです。全てのほかのロガーの親となる、ルート @ref{d46,,Logger} もあります。

単純な用法のために、 @ref{8b,,logging} パッケージはいくつかの便利関数を含んでいて、これは常にルートログを使います:

@example
import logging

logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
@end example

これは以下のような出力をします:

@example
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
@end example

In the default configuration, informational and debugging messages are
suppressed and the output is sent to standard error.  You can enable the display
of informational and debugging messages by calling the @ref{16ac,,setLevel()} method
on the root logger.

Notice the @ref{354,,warning()} call's use of string formatting operators; all of the
functions for logging messages take the arguments @code{(msg, arg1, arg2, ...)} and
log the string resulting from @code{msg % (arg1, arg2, ...)}.

There's also an @ref{16ad,,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'.

@example
def f():
    try:    1/0
    except: logging.exception('Problem recorded')

f()
@end example

これは以下のような出力をします:

@example
ERROR:root:Problem recorded
Traceback (most recent call last):
  File "t.py", line 6, in f
    1/0
ZeroDivisionError: integer division or modulo by zero
@end example

多少なりとも高度なプログラムでは、ルートロガー以上のロガーを使うでしょう。 @code{getLogger(name)} 関数は特定のロガーを取得するのに使います。その時点で存在していなければ、作成されます。 @code{getLogger(None)} はルートロガーを返します。:

@example
log = logging.getLogger('server')
 ...
log.info('Listening on port %i', port)
 ...
log.critical('Disk full')
 ...
@end example

Log records are usually propagated up the hierarchy, so a message logged to
@code{server.auth} is also seen by @code{server} and @code{root}, but a @ref{d46,,Logger}
can prevent this by setting its @ref{16ae,,propagate} attribute to @ref{d2b,,False}.

There are more classes provided by the @ref{8b,,logging} package that can be
customized.  When a @ref{d46,,Logger} instance is told to log a message, it
creates a @ref{11e8,,LogRecord} instance that is sent to any number of different
@ref{16af,,Handler} instances.  Loggers and handlers can also have an attached list
of filters, and each filter can cause the @ref{11e8,,LogRecord} to be ignored or
can modify the record before passing it along.  When they're finally output,
@ref{11e8,,LogRecord} instances are converted to text by a @ref{16b0,,Formatter}
class.  All of these classes can be replaced by your own specially written
classes.

これら全ての機能で @ref{8b,,logging} パッケージは最も複雑なアプリケーションでさえ、十分な柔軟性を提供しているはずです。ここではそれら機能の不完全な概要しか示しませんでしたので、全ての詳細はパッケージのドキュメントを参照してください。 
@geindex Python Enhancement Proposals; PEP 282
PEP 282@footnote{https://peps.python.org/pep-0282/} を読むことも助けになるでしょう。(---訳注: 今ではクックブックもあるのでそちらもどうぞ。---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 282

@item PEP 282@footnote{https://peps.python.org/pep-0282/} - ログシステム

PEP 著: Vinay Sajip と Trent Mick; 実装: Vinay Sajip.
@end table


@c ======================================================================

@node PEP 285 Boolean 型,PEP 293 コーデックエラーを処理するコールバック,PEP 282 ロギングパッケージ,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-285-a-boolean-type}@anchor{16b1}@anchor{whatsnew/2 3 section-bool}@anchor{16b2}
@subsection PEP 285: Boolean 型


A Boolean type was added to Python 2.3.  Two new constants were added to the
@code{__builtin__} module, @ref{e07,,True} and @ref{d2b,,False}.  (@ref{e07,,True} and
@ref{d2b,,False} constants were added to the built-ins in Python 2.2.1, but the
2.2.1 versions are simply set to integer values of 1 and 0 and aren't a
different type.)

この新しい型の型オブジェクトの名前は @ref{3c3,,bool} です; これのコンストラクタは任意の Python 値を取り、 @ref{e07,,True} または @ref{d2b,,False} に変換します:

@example
>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool( (1,) )
True
@end example

標準ライブラリモジュールとビルトイン関数のほとんどが、そうすべきときには Boolean を返すように変更されました:

@example
>>> obj = []
>>> hasattr(obj, 'append')
True
>>> isinstance(obj, list)
True
>>> isinstance(obj, tuple)
False
@end example

Python の Boolean はコードを明快にすることを主たる目標として追加されました。例えばあなたがコードを読んでいて @code{return 1} に出くわした場合、あなたは考えるはずです。この @code{1} は、真偽としての真値なのであろうか、それともインデクスだろうか、はたまた何かほかの数量に掛ける係数だろうか、と。 @code{return True} であればその意味するところはかなり明らかです。

Python の Boolean は、厳格な型チェックを目的として追加された `のではありません' 。Pascal のようなとても厳格な言語では、Boolean の数学演算も阻むでしょうし、 @ref{181,,if} ステートメントの式が必ず Boolean の結果に評価されなければならないことを要求するでしょう。 Python はこの厳しさを今持ちませんし、 
@geindex Python Enhancement Proposals; PEP 285
PEP 285@footnote{https://peps.python.org/pep-0285/} が名言するように、未来永劫持つことはありません。このことは、 @code{if} ステートメントにこれからも任意の式を書けることを意味しますし、リストやらタプルやら何かほかのデタラメなオブジェクトに評価されるものでも良いことを意味します。Boolean 型は @ref{19b,,int} クラスのサブクラスであって、Boolean の算術演算はこれからも動作します:

@example
>>> True + 1
2
>>> False + 1
1
>>> False * 75
0
>>> True * 75
75
@end example

@ref{e07,,True} と @ref{d2b,,False} はぶっちゃけて言えば…: これらは整数値 1 と 0 の別名だけれども唯一異なるのは @ref{169,,str()} と @ref{1c1,,repr()} が @code{'1'} と @code{'0'} ではなく @code{'True'} と @code{'False'} を返すことだけである。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 285

@item PEP 285@footnote{https://peps.python.org/pep-0285/} - 真偽値型の追加

Guido van Rossum 著、実装
@end table


@c ======================================================================

@node PEP 293 コーデックエラーを処理するコールバック,PEP 301 パッケージインデクスと、 Distutils のためのメタデータ,PEP 285 Boolean 型,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-293-codec-error-handling-callbacks}@anchor{16b3}
@subsection PEP 293: コーデックエラーを処理するコールバック


Unicode 文字列をバイト文字列にエンコードする際には、エンコード出来ない文字に出会うことがあります。いまのところ Python は、そのエラー処理として "strict" (@ref{462,,UnicodeError} を発生させる)、  "ignore" (その文字をスキップする)、 "replace" (出力文字列ではクエッションマークに置換する)、のいずれか一つを指定出来て、 "strict" がデフォルトの振る舞いになっています。その種のエラーのために、ほかの代わりとなる処理が望ましいかもしれません。例えば XML や HTML の実体参照に置き換えるなどの。

Python は今や、異なる処理戦略を追加する柔軟なフレームワークを手にしました。新しいエラーハンドラを @ref{16b4,,codecs.register_error()} で追加出来、コーデックは @ref{16b5,,codecs.lookup_error()} を使ってそのエラーハンドラにアクセス出来ます。等価な C API も C で書かれたコーデックのために追加されています。エラーハンドラは、変換すべき文字列、そのエラーが検出されたその文字列内での位置、ターゲットエンコーディングのような必要な状態情報を受け取ります。ハンドラは例外を投げるか、置換文字列を返せます。

このフレームワークを使って 2 つのエラーハンドラが実装されました: "backslashreplace" はエンコード出来ない文字をバックスラッシュで引用し、 "xmlcharrefreplace" は XML 文字参照を発行します。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 293

@item PEP 293@footnote{https://peps.python.org/pep-0293/} - コーデックエラーを処理するコールバック

Walter Dörwald 著、実装
@end table


@c ======================================================================

@node PEP 301 パッケージインデクスと、 Distutils のためのメタデータ,PEP 302 新たなインポートフック,PEP 293 コーデックエラーを処理するコールバック,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-301-package-index-and-metadata-for-distutils}@anchor{16b6}@anchor{whatsnew/2 3 section-pep301}@anchor{16b7}
@subsection PEP 301: パッケージインデクスと、 Distutils のためのメタデータ


長い間要望されてきた Python カタログのサポートが 2.3 で初登場です。

カタログの心臓部は Distutils の新コマンド @code{register} です。 @code{python setup.py register} を実行すると、名前、バージョン、メンテナ、説明、ライセンスのようなパッケージ記述のメタデータを収集して、中央カタログサーバに送信します。結果のカタログは @indicateurl{https://pypi.org} で利用可能です。

To make the catalog a bit more useful, a new optional `classifiers' keyword
argument has been added to the Distutils @code{setup()} function.  A list of
Trove@footnote{http://catb.org/~esr/trove/}-style strings can be supplied to help
classify the software.

以下は @code{setup.py} に分類指定子 (classifier) を記述する例です。 Distutils の古いバージョンと互換になるように書いています。:

@example
from distutils import core
kw = @{'name': "Quixote",
      'version': "0.5.1",
      'description': "A highly Pythonic Web application framework",
      # ...
      @}

if (hasattr(core, 'setup_keywords') and
    'classifiers' in core.setup_keywords):
    kw['classifiers'] = \
        ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
         'Environment :: No Input/Output (Daemon)',
         'Intended Audience :: Developers'],

core.setup(**kw)
@end example

classifier の完全なリストは @code{python setup.py register --list-classifiers} と実行することで得ることが出来ます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 301

@item PEP 301@footnote{https://peps.python.org/pep-0301/} - パッケージインデクスと、 Distutils のためのメタデータ

Richard Jones 著、実装
@end table


@c ======================================================================

@node PEP 302 新たなインポートフック,PEP 305 カンマ区切り形式ファイル,PEP 301 パッケージインデクスと、 Distutils のためのメタデータ,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-302-new-import-hooks}@anchor{16b8}@anchor{whatsnew/2 3 section-pep302}@anchor{16a5}
@subsection PEP 302: 新たなインポートフック


カスタムなインポートフックを書くことは、Python 1.3 で @code{ihooks} モジュールが導入されたその日からずっと可能でした。それでも本当のところそれで幸せになった人は誰一人いません。それで新しいインポートフックを書くのが難しくてとっ散らかっていたからです。 @code{imputil} と @code{iu} モジュール のような代わりとなる色々な提案がありましたが、そのいずれも多くの賛同を得ることが出来たものはありませんし、そのいずれもが簡単に C コードから使うことが出来ませんでした。

@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} はその先駆者、特に Gordon McMillan の @code{iu} モジュールからアイディアを借りています。3 つの新たなアイテムが @ref{df,,sys} モジュールに追加されています:


@itemize *

@item 
@code{sys.path_hooks} は呼び出し可能オブジェクトのリストです。ほとんどの場合クラスになるでしょう。それぞれの呼び出し可能オブジェクトは、パスを含む文字列を受け取って、このパスからインポートを処理するインポーターオブジェクトを返すか、このパスを処理出来なければ @ref{65b,,ImportError} を送出します。

@item 
@code{sys.path_importer_cache} はそれぞれのパスごとのインポーターオブジェクトをキャッシュしますので、 @code{sys.path_hooks} は個々のパスを一回だけ横断すれば良いことになります。

@item 
@code{sys.meta_path} は @code{sys.path} がチェックされる前に横断させるインポーターオブジェクトのリストです(訳注: ここだけ読むとわかりにくいですがライブラリリファレンスを読めばわかります)。このリストは初期状態で空ですが、ユーザコードがオブジェクトをそれに追加出来ます。追加のビルトインと凍結モジュールを、このリストにオブジェクトを追加することによってインポートさせることが出来ます。
@end itemize

インポーターオブジェクトは一つのメソッド @code{find_module(fullname, path=None)} を持たなければなりません。 `fullname' はモジュールかパッケージの名前です。例えば @code{string} や @code{distutils.core} です。 @code{find_module()} メソッドは一つのメソッド @code{load_module(fullname)} を持つローダーオブジェクトを返さなければなりません。 @code{load_module(fullname)} では対応するモジュールオブジェクトを生成して返します。

Python の新しいインポートのロジックは、なので、擬似コードで示すとだいたいこんな感じです (少し単純化しています; 完全な詳細は 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} 参照):

@example
for mp in sys.meta_path:
    loader = mp(fullname)
    if loader is not None:
        <module> = loader.load_module(fullname)

for path in sys.path:
    for hook in sys.path_hooks:
        try:
            importer = hook(path)
        except ImportError:
            # ImportError, so try the other path hooks
            pass
        else:
            loader = importer.find_module(fullname)
            <module> = loader.load_module(fullname)

# Not found!
raise ImportError
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 302

@item PEP 302@footnote{https://peps.python.org/pep-0302/} - 新たなインポートフック

Just van Rossum、Paul Moore 著、実装 Just van Rossum。
@end table


@c ======================================================================

@node PEP 305 カンマ区切り形式ファイル,PEP 307 Pickle の機能拡張,PEP 302 新たなインポートフック,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-305-comma-separated-files}@anchor{16b9}@anchor{whatsnew/2 3 section-pep305}@anchor{16ba}
@subsection PEP 305: カンマ区切り形式ファイル


カンマ区切りファイルは、データベースやスプレッドシートからのエキスポートのために頻繁に使われるフォーマットです。Python 2.3 はカンマ区切りファイルのパーサを追加しました。

カンマ区切りフォーマットは、ぱっと見で、簡単そうに見えます:

@example
Costs,150,200,3.95
@end example

行を読んで @code{line.split(',')}: これほどに簡単なものはあるだろうか、って? ですが、文字列データ内にカンマを含んだりすると、コトは複雑になります:

@example
"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
@end example

デカくて醜い正規表現でこれをパース出来るでしょうが、新登場の @ref{2d,,csv} を使えば遥かに単純になります:

@example
import csv

input = open('datafile', 'rb')
reader = csv.reader(input)
for line in reader:
    print line
@end example

The @ref{6ae,,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.

カンマ区切りファイルの異なった方言を定義して登録出来ます。今のところ 2 つの方言があって、両者とも Microsoft Excel で使われるものです。独立している @ref{6af,,csv.writer} はタプルやリストの連続から、デリミタを含む文字列は引用符で囲みつつカンマ区切りファイルを生成します。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 305

@item PEP 305@footnote{https://peps.python.org/pep-0305/} - CSV File API

PEP 著と実装: Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.
@end table


@c ======================================================================

@node PEP 307 Pickle の機能拡張,拡張スライス,PEP 305 カンマ区切り形式ファイル,What's New in Python 2 3
@anchor{whatsnew/2 3 pep-307-pickle-enhancements}@anchor{16bb}@anchor{whatsnew/2 3 section-pep307}@anchor{16bc}
@subsection PEP 307: Pickle の機能拡張


The @ref{ab,,pickle} and @code{cPickle} modules received some attention during the
2.3 development cycle.  In 2.2, new-style classes could be pickled without
difficulty, but they weren't pickled very compactly; 
@geindex Python Enhancement Proposals; PEP 307
PEP 307@footnote{https://peps.python.org/pep-0307/} quotes a trivial
example where a new-style class results in a pickled string three times longer
than that for a classic class.

解決方法として、新しい pickle プロトコルが発明されました。 @ref{16bd,,pickle.dumps()} 関数はずっと長い間、テキストとするのかバイナリとするのかについてはサポートしていました。2.3 ではこのフラグは Boolean から整数に再定義されました: 0 は旧式のテキストモード pickle フォーマット、1 が同じく旧式のバイナリフォーマット、そして 2 が今回の 2.3 から特有のフォーマットです。新しく追加された定数 @ref{16be,,pickle.HIGHEST_PROTOCOL} を指定すると、最も望ましいものが選択されます。

Unpickling is no longer considered a safe operation.  2.2's @ref{ab,,pickle}
provided hooks for trying to prevent unsafe classes from being unpickled
(specifically, a @code{__safe_for_unpickling__} attribute), but none of this
code was ever audited and therefore it's all been ripped out in 2.3.  You should
not unpickle untrusted data in any version of Python.

To reduce the pickling overhead for new-style classes, a new interface for
customizing pickling was added using three special methods:
@ref{7f1,,__getstate__()}, @ref{bc7,,__setstate__()}, and @ref{fd4,,__getnewargs__()}.  Consult
@geindex Python Enhancement Proposals; PEP 307
PEP 307@footnote{https://peps.python.org/pep-0307/} for the full semantics  of these methods.

pickle をもっとさらに圧縮する方法として、pickle されるクラスの身元特定のために長い文字列を使う代わりに整数コードを使えるようになっています。Python Software Foundation は標準コードのリストを保守しています; プライベート使用のためのコード範囲もあります。現在のところ指定されているコードはありません。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 307

@item PEP 307@footnote{https://peps.python.org/pep-0307/} - pickle プロトコルの拡張

著、実装: Guido van Rossum と Tim Peters
@end table


@c ======================================================================

@node 拡張スライス,その他の言語変更<18>,PEP 307 Pickle の機能拡張,What's New in Python 2 3
@anchor{whatsnew/2 3 extended-slices}@anchor{16bf}@anchor{whatsnew/2 3 section-slices}@anchor{16c0}
@subsection 拡張スライス


Python 1.4 以来ずっと、スライシングの構文は省略可能な 3 つ目の引数 "step" またの名を "stride" 、をサポートしていたのです。例えばこれらは全て合法な Python 構文です: @code{L[1:10:2]}, @code{L[:-1:1]}, @code{L[::-1]} 。これはこの 3 つ目の引数を大々的に使う Numerical Python 開発者によって要望されたことで Python に追加されたものですが、Python ビルトインのリスト、タプル、文字列といったシーケンス型がこの機能をサポートすることはなく、これを試みると @ref{198,,TypeError} を起こしていました。Michael Hudson がこの不徹底を修正するパッチを寄稿しました。

例えば、今やリストの偶数番目要素を簡単に取り出せます:

@example
>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
@end example

負の値では、同じリストの逆順コピーを作るように動作します:

@example
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
@end example

これはタプル、配列、文字列に対しても使えます:

@example
>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'
@end example

リストや配列のような @ref{15ba,,mutable} なシーケンスに対して、拡張スライスを代入や削除に使えますが、拡張スライスと普通のスライスではいくつかの違いがあります。普通のスライスで代入を行えば、シーケンスの長さを変更出来ます (---訳注: 念のため。Python 3 の range は list を直接返す関数ではなくジェネレータなので、以下例は @code{a = list(range(3))} などとしないと動作しません。続く例でも同じです。---):

@example
>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]
@end example

拡張スライスにはこの柔軟性はありません。拡張スライスを代入に使う際は、ステートメントの右辺のリストは、置換されるスライスとしての要素数と同数でなければなりません:

@example
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
@end example

削除はもっと素直です:

@example
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]
@end example

One can also now pass slice objects to the @ref{588,,__getitem__()} methods of the
built-in sequences:

@example
>>> range(10).__getitem__(slice(0, 5, 2))
[0, 2, 4]
@end example

あるいは直接 slice オブジェクトを添え字に使えます:

@example
>>> range(10)[slice(0, 5, 2)]
[0, 2, 4]
@end example

To simplify implementing sequences that support extended slicing, slice objects
now have a method @code{indices(length)} which, given the length of a sequence,
returns a @code{(start, stop, step)} tuple that can be passed directly to
@ref{b3d,,range()}. @code{indices()} handles omitted and out-of-bounds indices in a
manner consistent with regular slices (and this innocuous phrase hides a welter
of confusing details!).  The method is intended to be used like this:

@example
class FakeSeq:
    ...
    def calc_item(self, i):
        ...
    def __getitem__(self, item):
        if isinstance(item, slice):
            indices = item.indices(len(self))
            return FakeSeq([self.calc_item(i) for i in range(*indices)])
        else:
            return self.calc_item(i)
@end example

ところでこの例からは、ビルトインの @ref{694,,slice} オブジェクトが今では slice 型という型オブジェクトで、もう関数ではないことがわかるでしょう。これは、Python 2.2 で @ref{19b,,int}, @ref{169,,str} などに対して行われた同じ目的の修正と一貫しています。

@c ======================================================================

@node その他の言語変更<18>,新たなモジュール、改良されたモジュール、非推奨のモジュール<4>,拡張スライス,What's New in Python 2 3
@anchor{whatsnew/2 3 other-language-changes}@anchor{16c1}
@subsection その他の言語変更


以下が、Python 2.3 言語コアに加えられた全ての変更点です。


@itemize *

@item 
@ref{bc2,,yield} 文がこのドキュメントの @ref{16a1,,PEP 255; 単純なジェネレータ} で述べた通り、キーワードになっています。

@item 
新たな組み込み関数 @ref{169a,,enumerate()} が追加されました。このドキュメントの @ref{16aa,,PEP 279; enumerate()} で述べた通りです。

@item 
新たな定数 @ref{e07,,True},  @ref{d2b,,False} がビルトイン @ref{3c3,,bool} 型の追加に伴い追加されました。このドキュメントの @ref{16b2,,PEP 285; Boolean 型} で述べた通りです。

@item 
@ref{19b,,int()} 型コンストラクタは、文字列や浮動小数点数を整数に収める際、それがとても大き場合に  @ref{a81,,OverflowError} を投げるのではなく長整数を返すようになっています。これは @code{isinstance(int(expression), int)} が偽を返すかもしれないという逆説的な結果をもたらし得ますが、これが実際に問題を起こすとはあまり思えません。

@item 
ビルトイン型が拡張スライス構文をサポートするようになりました。このドキュメントの @ref{16c0,,拡張スライス} で述べた通りです。

@item 
新規組み込み関数 @code{sum(iterable, start=0)} はイテラブル オブジェクト内の数値アイテムを足し込んで総和を返します。 @ref{695,,sum()} は数値しか受け付けませんので、文字列群を連結するのには使えません。 (Contributed by Alex Martelli.)

@item 
@code{list.insert(pos, value)} で `value' を先頭に追加するのに `pos' に負数が使われてきました。この振る舞いはスライスのインデクシングとの一貫性のために変更されました。つまり `pos' が -1 の場合は最終要素の前への追加、などとなります。

@item 
@code{list.index(value)} はリスト内から `value' を探してそのインデクスを返しますが、オプショナルな `start' と `stop' 引数を取って、リストの部分列からの検索が可能になりました。

@item 
辞書の新たなメソッド @code{pop(key[, *default*])} は、 `key' に対応する値を返して辞書からそのキー/値ペアを取り除きます。辞書内にそのキーが不在であれば、 `default' が指定されていればそれを、そうでなければ @ref{5e7,,KeyError} を投げます。:

@example
>>> d = @{1:2@}
>>> d
@{1: 2@}
>>> d.pop(4)
Traceback (most recent call last):
  File "stdin", line 1, in ?
KeyError: 4
>>> d.pop(1)
2
>>> d.pop(1)
Traceback (most recent call last):
  File "stdin", line 1, in ?
KeyError: 'pop(): dictionary is empty'
>>> d
@{@}
>>>
@end example

また、新しいメソッド @code{dict.fromkeys(iterable, value)} は、与えられたイテレータ `iterable' からキーを取り出しつつ全ての値を `value' にセットすることで構築します。 `value' のデフォルトは @code{None} です。

(Patches contributed by Raymond Hettinger.)

また、 @ref{183,,dict()} コンストラクタは小さな辞書を簡単に構築出来るよう、キーワード引数を受け付けるようになりました:

@example
>>> dict(red=1, blue=2, green=3, black=4)
@{'blue': 2, 'black': 4, 'green': 3, 'red': 1@}
@end example

(Contributed by Just van Rossum.)

@item 
@ref{b60,,assert} ステートメントが @code{__debug__} フラグをチェックすることはもうありません。このため、 @code{__debug__} に代入することによってアサーションを無効にすることは出来ません。Python を @ref{18c,,-O} スイッチで起動により全てのアサーションが実行されない点は、以前と変わりません。

@item 
ほとんどの型オブジェクトが今では呼び出し可能であり、なので関数、クラス、モジュールのようなオブジェクトを新たに構築するのにそれを使えます。 (@code{new} モジュールはこれにより将来のバージョンの Python で撤廃される可能性があります。 @ref{109,,types} モジュール内の型オブジェクトが使えるからです。 ---訳注: 2.6 で実際に撤廃されています。---) 例えば、新規モジュールオブジェクトは以下コードで構築出来ます:

@example
>>> import types
>>> m = types.ModuleType('abc','docstring')
>>> m
<module 'abc' (built-in)>
>>> m.__doc__
'docstring'
@end example

@item 
新たな警告 @ref{ac5,,PendingDeprecationWarning} が、将来廃止される予定のある機能であることを示すために追加されました。この警告はデフォルトで `出力されません' 。将来において廃止される予定の機能の使用をチェックするにはコマンドラインから @ref{ac6,,-Walways;;PendingDeprecationWarning;;} を与えるか、 @ref{16c2,,warnings.filterwarnings()} を使います。

@item 
文字列ベースの例外、例えば @code{raise "Error occurred"} のようなもの、これは廃止のための過程を開始しています。文字列を例外として投げると @ref{ac5,,PendingDeprecationWarning} が発行されます。

@item 
@code{None} を変数名に使うと @ref{1ae,,SyntaxWarning} 警告を出すようになっています。将来バージョンの Python では @code{None} はキーワードになります。

@item 
The @code{xreadlines()} method of file objects, introduced in Python 2.1, is no
longer necessary because files now behave as their own iterator.
@code{xreadlines()} was originally introduced as a faster way to loop over all
the lines in a file, but now you can simply write @code{for line in file_obj}.
File objects also have a new read-only @code{encoding} attribute that gives the
encoding used by the file; Unicode strings written to the file will be
automatically  converted to bytes using the given encoding.

@item 
The method resolution order used by new-style classes has changed, though
you'll only notice the difference if you have a really complicated inheritance
hierarchy.  Classic classes are unaffected by this change.  Python 2.2
originally used a topological sort of a class's ancestors, but 2.3 now uses the
C3 algorithm as described in the paper "A Monotonic Superclass Linearization for Dylan"@footnote{https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910}. To
understand the motivation for this change,  read Michele Simionato's article
@ref{16c3,,The Python 2.3 Method Resolution Order}, or
read the thread on python-dev starting with the message at
@indicateurl{https://mail.python.org/pipermail/python-dev/2002-October/029035.html}. Samuele
Pedroni first pointed out the problem and also implemented the fix by coding the
C3 algorithm.

@item 
Python runs multithreaded programs by switching between threads after
executing N bytecodes.  The default value for N has been increased from 10 to
100 bytecodes, speeding up single-threaded applications by reducing the
switching overhead.  Some multithreaded applications may suffer slower response
time, but that's easily fixed by setting the limit back to a lower number using
@code{sys.setcheckinterval(N)}. The limit can be retrieved with the new
@code{sys.getcheckinterval()} function.

@item 
マイナーですが広範囲に渡る変更として、拡張型の名前の変更があります。Python と一緒に含まれるモジュールで定義される拡張型の名前が、モジュール名と @code{'.'} が型名に前置されるようになりました。例えば、Python 2.2 ではソケットオブジェクトを作って @code{__class__} を出力すると、このような出力だったでしょう:

@example
>>> s = socket.socket()
>>> s.__class__
<type 'socket'>
@end example

2.3 ではこうなります:

@example
>>> s.__class__
<type '_socket.socket'>
@end example

@item 
One of the noted incompatibilities between old- and new-style classes has been
removed: you can now assign to the @ref{16c4,,__name__} and @ref{16c5,,__bases__}
attributes of new-style classes.  There are some restrictions on what can be
assigned to @code{__bases__} along the lines of those relating to assigning to
an instance's @ref{16c6,,__class__} attribute.
@end itemize

@c ======================================================================

@menu
* 文字列に関する変更:: 
* 最適化: 最適化<18>. 

@end menu

@node 文字列に関する変更,最適化<18>,,その他の言語変更<18>
@anchor{whatsnew/2 3 string-changes}@anchor{16c7}
@subsubsection 文字列に関する変更



@itemize *

@item 
@ref{34b,,in} 演算子が文字列に対して違った振る舞いをするようになりました。以前は `X' と `Y' が文字列の場合の @code{X in Y} は、 `X' は単一文字でなければなりませんでした。これが `X' はどんな長さでも良くなり、 @code{X in Y} は `X' が `Y' のサブストリングであれば @ref{e07,,True} を返すように変更されました。 `X' が空文字列の場合は結果は常に @ref{e07,,True} になります。

@example
>>> 'ab' in 'abcd'
True
>>> 'ad' in 'abcd'
False
>>> '@w{'} in 'abcd'
True
@end example

これはサブストリングの開始位置を教えてくれるわけではないので、その情報が必要であれば @ref{10a8,,find()} 文字列メソッドを使ってください。

@item 
@ref{16c8,,strip()}, @ref{16c9,,lstrip()}, @ref{16ca,,rstrip()} に、剥ぎ取る文字を指定する省略可能な引数が追加されています。デフォルトは従来通り全ての空白文字を削除します。:

@example
>>> '   abc '.strip()
'abc'
>>> '><><abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n'.strip('<>')
'abc<><><>\n'
>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
u'\u4001abc'
>>>
@end example

(Suggested by Simon Brunning and implemented by Walter Dörwald.)

@item 
The @ref{10cb,,startswith()} and @ref{10cc,,endswith()} string methods now accept negative
numbers for the `start' and `end' parameters.

@item 
Another new string method is @ref{16cb,,zfill()}, originally a function in the
@ref{d8,,string} module.  @ref{16cb,,zfill()} pads a numeric string with zeros on the
left until it's the specified width. Note that the @code{%} operator is still more
flexible and powerful than @ref{16cb,,zfill()}.

@example
>>> '45'.zfill(4)
'0045'
>>> '12345'.zfill(4)
'12345'
>>> 'goofy'.zfill(6)
'0goofy'
@end example

(Contributed by Walter Dörwald.)

@item 
A new type object, @code{basestring}, has been added. Both 8-bit strings and
Unicode strings inherit from this type, so @code{isinstance(obj, basestring)} will
return @ref{e07,,True} for either kind of string.  It's a completely abstract
type, so you can't create @code{basestring} instances.

@item 
内部化した文字列はもう不死身ではないので、内部辞書からの参照が、参照している唯一のものとなれば、普通にガーベージコレクト対象となります。 (Implemented by Oren Tirosh.)
@end itemize

@c ======================================================================

@node 最適化<18>,,文字列に関する変更,その他の言語変更<18>
@anchor{whatsnew/2 3 optimizations}@anchor{16cc}
@subsubsection 最適化



@itemize *

@item 
The creation of new-style class instances has been made much faster; they're
now faster than classic classes!

@item 
The @ref{dc8,,sort()} method of list objects has been extensively rewritten by Tim
Peters, and the implementation is significantly faster.

@item 
Multiplication of large long integers is now much faster thanks to an
implementation of Karatsuba multiplication, an algorithm that scales better than
the `O'(`n'@w{^2}) required for the grade-school multiplication algorithm.  (Original
patch by Christopher A. Craig, and significantly reworked by Tim Peters.)

@item 
The @code{SET_LINENO} opcode is now gone.  This may provide a small speed
increase, depending on your compiler's idiosyncrasies. See section
@ref{16cd,,その他の変更と修正} for a longer explanation. (Removed by Michael Hudson.)

@item 
@code{xrange()} objects now have their own iterator, making @code{for i in
xrange(n)} slightly faster than @code{for i in range(n)}.  (Patch by Raymond
Hettinger.)

@item 
A number of small rearrangements have been made in various hotspots to improve
performance, such as inlining a function or removing some code.  (Implemented
mostly by GvR, but lots of people have contributed single changes.)
@end itemize

The net result of the 2.3 optimizations is that Python 2.3 runs the  pystone
benchmark around 25% faster than Python 2.2.

@c ======================================================================

@node 新たなモジュール、改良されたモジュール、非推奨のモジュール<4>,Pymalloc 特殊化されたオブジェクトアロケータ,その他の言語変更<18>,What's New in Python 2 3
@anchor{whatsnew/2 3 new-improved-and-deprecated-modules}@anchor{16ce}
@subsection 新たなモジュール、改良されたモジュール、非推奨のモジュール


いつものように、Python の標準ライブラリには数多くの拡張とバグ修正がありました。ここでは最も注目に値する変更について、モジュールの辞書順に列挙します。変更の完全なリストについてはソースツリーの @code{Misc/NEWS} を調べるか、あるいは全ての詳細について CVS ログに目を通してみてください。


@itemize *

@item 
@ref{8,,array} モジュールが @code{'u'} フォーマット文字を使った Unicode 文字の配列をサポートするようになっています。配列はまた、 @code{+=} 代入演算子を使ってほかの配列内容を加算すること、 @code{*=} 演算子を使って配列を繰り返すことが可能になっています。(Contributed by Jason Orendorff.)

@item 
@code{bsddb} モジュールが PyBSDDB@footnote{https://pybsddb.sourceforge.net} バージョン 4.1.6 によって置き換えられています。これは BerkeleyDB のトランザクションの機能へのより完全なインターフェースを提供します。

古いバージョンのモジュールは @code{bsddb185} にリネームされて、自動的にはビルドされません。有効にするには @code{Modules/Setup} を編集する必要があります。新しい @code{bsddb} パッケージは古いモジュールと互換となるように意図されていますので、何か非互換を見つけたらファイルのバグを確認してください。Python 2.3 へのアップグレードの際、前提となる BerkeleyDB ライブラリの新バージョンでインタープリタがコンパイルされるならば、ほぼ確実にあなたのデータベースは新バージョンに変換しなければならないでしょう。ソース配布物の @code{Tools/scripts} ディレクトリの @code{db2pickle.py} と @code{pickle2db.py} スクリプトを使って、これをかなり簡単に行うことが出来ます。もし既に PyBSDDB パッケージを使っていて @code{bsddb3} としてインポートしているならば、 @code{bsddb} をインポートするように @code{import} 文を変更する必要があります。

@item 
新規の @ref{14,,bz2} モジュールは bz2 データ圧縮ライブラリへのインターフェイスです。bz2 圧縮データは普通 @ref{139,,zlib} 圧縮データよりも小さくなります。 (Contributed by Gustavo Niemeyer.)

@item 
標準の日付時刻型が @ref{34,,datetime} モジュールとして追加されています。詳細はこのドキュメントの下の方に記述してありますのでそちらを参照して下さい。

@item 
The Distutils @code{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 @code{sampmodule.c} includes the header
file @code{sample.h}, you would create the @code{Extension} object like
this:

@example
ext = Extension("samp",
                sources=["sampmodule.c"],
                depends=["sample.h"])
@end example

@code{sample.h} を修正するとモジュールは再コンパイルされます。 (Contributed by Jeremy Hylton.)

@item 
Other minor changes to Distutils: it now checks for the 
@geindex CC
@geindex 環境変数; CC
@ref{16cf,,CC},
@geindex CFLAGS
@geindex 環境変数; CFLAGS
@ref{16d0,,CFLAGS}, @code{CPP}, 
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS}, and 
@geindex CPPFLAGS
@geindex 環境変数; CPPFLAGS
@ref{16d2,,CPPFLAGS}
environment variables, using them to override the settings in Python's
configuration (contributed by Robert Weber).

@item 
Previously the @ref{3e,,doctest} module would only search the docstrings of
public methods and functions for test cases, but it now also examines private
ones as well.  The @ref{ff4,,DocTestSuite()} function creates a
@ref{ff5,,unittest.TestSuite} object from a set of @ref{3e,,doctest} tests.

@item 
新しい関数 @code{gc.get_referents(object)} は `object' により参照されている全てのオブジェクトのリストを返します。

@item 
The @ref{65,,getopt} module gained a new function, @ref{16d3,,gnu_getopt()}, that
supports the same arguments as the existing @ref{16d4,,getopt()} function but uses
GNU-style scanning mode. The existing @ref{16d4,,getopt()} stops processing options as
soon as a non-option argument is encountered, but in GNU-style mode processing
continues, meaning that options and arguments can be mixed.  For example:

@example
>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename')], ['output', '-v'])
>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename'), ('-v', '@w{'})], ['output'])
@end example

(Contributed by Peter Åstrand.)

@item 
モジュール @ref{6a,,grp}, @ref{b7,,pwd}, @ref{c1,,resource} では拡張されたタプルを返すようになりました:

@example
>>> import grp
>>> g = grp.getgrnam('amk')
>>> g.gr_name, g.gr_gid
('amk', 500)
@end example

@item 
@ref{6b,,gzip} モジュールが 2 GiB を超えるファイルを扱えるようになっています。

@item 
The new @ref{6d,,heapq} module contains an implementation of a heap queue
algorithm.  A heap is an array-like data structure that keeps items in a
partially sorted order such that, for every index `k', @code{heap[k] <=
heap[2*k+1]} and @code{heap[k] <= heap[2*k+2]}.  This makes it quick to remove the
smallest item, and inserting a new item while maintaining the heap property is
`O'(log `n').  (See @indicateurl{https://xlinux.nist.gov/dads//HTML/priorityque.html} for more
information about the priority queue data structure.)

The @ref{6d,,heapq} module provides @ref{16d5,,heappush()} and @ref{16d6,,heappop()} functions
for adding and removing items while maintaining the heap property on top of some
other mutable Python sequence type.  Here's an example that uses a Python list:

@example
>>> import heapq
>>> heap = []
>>> for item in [3, 7, 5, 11, 1]:
...    heapq.heappush(heap, item)
...
>>> heap
[1, 3, 5, 11, 7]
>>> heapq.heappop(heap)
1
>>> heapq.heappop(heap)
3
>>> heap
[5, 7, 11]
@end example

(Contributed by Kevin O'Connor.)

@item 
The IDLE integrated development environment has been updated using the code
from the IDLEfork project (@indicateurl{https://idlefork.sourceforge.net}).  The most notable feature is
that the code being developed is now executed in a subprocess, meaning that
there's no longer any need for manual @code{reload()} operations. IDLE's core code
has been incorporated into the standard library as the @ref{77,,idlelib} package.

@item 
@ref{78,,imaplib} モジュールが  IMAP over SSL をサポートするようになりました. (Contributed by Piers Lauder and Tino Lange.)

@item 
The @ref{85,,itertools} contains a number of useful functions for use with
iterators, inspired by various functions provided by the ML and Haskell
languages.  For example, @code{itertools.ifilter(predicate, iterator)} returns all
elements in the iterator for which the function @code{predicate()} returns
@ref{e07,,True}, and @code{itertools.repeat(obj, N)} returns @code{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.)

@item 
@ref{92,,math} module の 2 つの新規関数 @code{degrees(rads)} と @code{radians(degs)} は、ラジアンと度の間の変換を行います。 @ref{92,,math} モジュールの @ref{16d7,,math.sin()} や @ref{16d8,,math.cos()} などは常にラジアンでの入力が必要です。 @ref{16d9,,math.log()} 関数には底を指定するオプショナルの `base' 引数が追加されていて、 @code{e} と @code{10} でない底の対数を計算するのが簡単になりました。 (Contributed by Raymond Hettinger.)

@item 
Several new POSIX functions (@code{getpgid()}, @code{killpg()}, @code{lchown()},
@code{loadavg()}, @code{major()}, @code{makedev()}, @code{minor()}, and
@code{mknod()}) were added to the @ref{b2,,posix} module that underlies the
@ref{a5,,os} module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
Otkidach.)

@item 
In the @ref{a5,,os} module, the @code{*stat()} family of functions can now report
fractions of a second in a timestamp.  Such time stamps are represented as
floats, similar to the value returned by @ref{55d,,time.time()}.

During testing, it was found that some applications will break if time stamps
are floats.  For compatibility, when using the tuple interface of the
@ref{16da,,stat_result} time stamps will be represented as integers. When using
named fields (a feature first introduced in Python 2.2), time stamps are still
represented as integers, unless @code{os.stat_float_times()} is invoked to enable
float return values:

@example
>>> os.stat("/tmp").st_mtime
1034791200
>>> os.stat_float_times(True)
>>> os.stat("/tmp").st_mtime
1034791200.6335014
@end example

Python 2.4 では、浮動小数点数を返すのがデフォルトとなります。

Application developers should enable this feature only if all their libraries
work properly when confronted with floating-point time stamps, or if they use
the tuple API. If used, the feature should be activated on an application level
instead of trying to enable it on a per-use basis.

@item 
@ref{a4,,optparse} モジュールに新たなコマンドライン引数パーサが追加されました。これはオプション値を特定の Python 型に変換することが出来、また、自動的に使用例メッセージを生成します。詳細はこのドキュメントの続くセクションを参照して下さい。

@item 
The old and never-documented @code{linuxaudiodev} module has been deprecated,
and a new version named @code{ossaudiodev} has been added.  The module was
renamed because the OSS sound drivers can be used on platforms other than Linux,
and the interface has also been tidied and brought up to date in various ways.
(Contributed by Greg Ward and Nicholas FitzRoy-Dale.)

@item 
実行中のプラットフォームについての色々な特性を決定する数多くの関数を含む、新規 @ref{af,,platform} モジュールが追加されました。アーキテクチャ、CPU タイプ、Windows の OS バージョンや Linux ディストリビューションのバージョンなどを取得できます。(Contributed by Marc-André Lemburg.)

@item 
The parser objects provided by the @ref{12c,,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
@ref{16db,,buffer_text} attribute to @ref{e07,,True} will enable buffering.

@item 
The @code{sample(population, k)} function was added to the @ref{bd,,random}
module.  `population' is a sequence or @code{xrange} object containing the
elements of a population, and @ref{94d,,sample()} chooses `k' elements from the
population without replacing chosen elements.  `k' can be any value up to
@code{len(population)}. For example:

@example
>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
>>> random.sample(days, 3)      # Choose 3 elements
['St', 'Sn', 'Th']
>>> random.sample(days, 7)      # Choose 7 elements
['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
>>> random.sample(days, 7)      # Choose 7 again
['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
>>> random.sample(days, 8)      # Can't choose eight
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "random.py", line 414, in sample
      raise ValueError, "sample larger than population"
ValueError: sample larger than population
>>> random.sample(xrange(1,10000,2), 10)   # Choose ten odd nos. under 10000
[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
@end example

@ref{bd,,random} が C で実装された新しいアルゴリズムのメルセンヌ・ツイスタを使うようになりました。これは以前のアルゴリズムよりも高速で、より広く研究されています。

(All changes contributed by Raymond Hettinger.)

@item 
The @ref{bf,,readline} module also gained a number of new functions:
@ref{16dc,,get_history_item()}, @ref{16dd,,get_current_history_length()}, and
@ref{16de,,redisplay()}.

@item 
The @code{rexec} and @code{Bastion} modules have been declared dead, and
attempts to import them will fail with a @ref{244,,RuntimeError}.  New-style classes
provide new ways to break out of the restricted execution environment provided
by @code{rexec}, and no one has interest in fixing them or time to do so.  If
you have applications using @code{rexec}, rewrite them to use something else.

(Sticking with Python 2.2 or 2.1 will not make your applications any safer
because there are known bugs in the @code{rexec} module in those versions.  To
repeat: if you're using @code{rexec}, stop using it immediately.)

@item 
The @code{rotor} module has been deprecated because the  algorithm it uses for
encryption is not believed to be secure.  If you need encryption, use one of the
several AES Python modules that are available separately.

@item 
@ref{ca,,shutil} モジュールに @code{move(src, dest)} が追加されており、これはファイルまたはディレクトリを新しい場所へ再帰的に移動します。

@item 
Support for more advanced POSIX signal handling was added to the @ref{cb,,signal}
but then removed again as it proved impossible to make it work reliably across
platforms.

@item 
@ref{d1,,socket} モジュールがタイムアウトをサポートするようになりました。ソケットオブジェクトの @code{settimeout(t)} メソッドに `t' 秒を与えることで行えます。これに続くソケット操作が `t' 秒を超えて完了しない場合には操作は中断し、 @ref{a35,,socket.timeout} 例外を投げます。

オリジナルのタイムアウト実装は Tim O'Malley によりなされました。Michael Gilfix がこれを Python @ref{d1,,socket} モジュールに統合し、長い長いレビューに導きました。コードがチェックインされたのち、Guido van Rossum はそれを部分的に書き換えました。(これは協調的開発プロセスの好例です。)

@item 
Windows での @ref{d1,,socket} モジュールの Secure  Sockets Layer (SSL) サポートが始まりました。

@item 
The value of the C @code{PYTHON_API_VERSION} macro is now exposed at the
Python level as @code{sys.api_version}.  The current exception can be cleared by
calling the new @code{sys.exc_clear()} function.

@item 
新モジュール @ref{e4,,tarfile} で @code{tar} 形式のアーカイブファイルの読み書きが出来ます。 (Contributed by Lars Gustäbel.)

@item 
The new @ref{f2,,textwrap} module contains functions for wrapping strings
containing paragraphs of text.  The @code{wrap(text, width)} function takes a
string and returns a list containing the text split into lines of no more than
the chosen width.  The @code{fill(text, width)} function returns a single
string, reformatted to fit into lines no longer than the chosen width. (As you
can guess, @ref{16df,,fill()} is built on top of @ref{16e0,,wrap()}.  For example:

@example
>>> import textwrap
>>> paragraph = "Not a whit, we defy augury: ... more text ..."
>>> textwrap.wrap(paragraph, 60)
["Not a whit, we defy augury: there's a special providence in",
 "the fall of a sparrow. If it be now, 'tis not to come; if it",
 ...]
>>> print textwrap.fill(paragraph, 35)
Not a whit, we defy augury: there's
a special providence in the fall of
a sparrow. If it be now, 'tis not
to come; if it be not to come, it
will be now; if it be not now, yet
it will come: the readiness is all.
>>>
@end example

The module also contains a @ref{11cf,,TextWrapper} class that actually implements
the text wrapping strategy.   Both the @ref{11cf,,TextWrapper} class and the
@ref{16e0,,wrap()} and @ref{16df,,fill()} functions support a number of additional keyword
arguments for fine-tuning the formatting; consult the module's documentation
for details. (Contributed by Greg Ward.)

@item 
The @code{thread} and @ref{f3,,threading} modules now have companion modules,
@code{dummy_thread} and @code{dummy_threading}, that provide a do-nothing
implementation of the @code{thread} module's interface for platforms where
threads are not supported.  The intention is to simplify thread-aware modules
(ones that `don't' rely on threads to run) by putting the following code at the
top:

@example
try:
    import threading as _threading
except ImportError:
    import dummy_threading as _threading
@end example

In this example, @code{_threading} is used as the module name to make it clear
that the module being used is not necessarily the actual @ref{f3,,threading}
module. Code can call functions and use classes in @code{_threading} whether or
not threads are supported, avoiding an @ref{181,,if} statement and making the
code slightly clearer.  This module will not magically make multithreaded code
run without threads; code that waits for another thread to return or to do
something will simply hang forever.

@item 
@ref{f4,,time} モジュールの @ref{1646,,strptime()} 関数は長いこと混乱の元でした。それがプラットフォームの C 関数 @ref{1646,,strptime()} を使い、異なったプラットフォームごとに時折おかしなバグを持っていたからです。Brett Cannon は pure Python で、全てのプラットフォームで全く同じに振舞うように書き直した実装を寄稿しました。

@item 
新規モジュール @ref{f5,,timeit} は、Python コードの断片 (スニペット) を実行するのにかかる時間を計測します。ファイル @code{timeit.py} は直接コマンドラインから実行出来ますし、モジュールの @ref{16e1,,Timer} クラスをインポートして直接使うことも出来ます。以下に、空の Unicode 文字列を追加することによって 8 ビット文字列を Unicode に変換するのと @code{unicode()} 関数を使うのとでいずれが高速なのかを把握するための短い例をお見せします:

@example
import timeit

timer1 = timeit.Timer('unicode("abc")')
timer2 = timeit.Timer('"abc" + u""')

# Run three trials
print timer1.repeat(repeat=3, number=100000)
print timer2.repeat(repeat=3, number=100000)

# On my laptop this outputs:
# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
@end example

@item 
@code{Tix} モジュールに色々バグ修正がなされ、Tix パッケージの現在バージョンに更新されました。

@item 
@code{Tkinter} モジュールがスレッドを有効化した Tcl で動作するようになりました。Tcl のスレッドモデルは、ウィジットはそれが作られたスレッドからのみアクセスされることを必要とします。ほかのスレッドからのアクセスは Tcl を混乱させます。ある特定の Tcl インターフェイスでは、 @code{Tkinter} はウィジットがコマンドの纏め上げによって異なるスレッドからアクセスされる際に、正しいスレッドに向けて結果を待つことで自動的にこれを避けるようになりました。それ以外のインターフェイスでは自動で処理は出来ませんが、 @code{Tkinter} はそのようなアクセス時に最低でもそれが問題とわかるよう例外を送出するようになっています。この変更についての詳細な説明は @indicateurl{https://mail.python.org/pipermail/python-dev/2002-December/031107.html} をみてください。(Implemented by Martin von Löwis.)

@item 
@code{_tkinter} を介した Tcl メソッド呼び出しは今では文字列だけを返すのではありません。代わりに Tcl は対応する Python の等価なオブジェクトに変換されたオブジェクトを返します。Python に等価なものがなければ @code{_tkinter.Tcl_Obj} で包んで返します。この振る舞いは @code{tkapp} オブジェクトの @code{wantobjects()} メソッドで制御出来ます。

(ほとんどの Tkinter アプリケーションがそうするように) @code{Tkinter} モジュールを通して @code{_tkinter} を使う際、この機能は常に有効になります。これは互換性の問題を引き起こさないはずです。 Tkinter は可能な場合には文字列を Python 型に常に変換していたからです。

何か非互換性を見つけたら古い振る舞いに戻せます。最初の @code{tkapp} オブジェクトを生成する前に @code{Tkinter} モジュールの @code{wantobjects} 変数に偽をセットしてください:

@example
import Tkinter
Tkinter.wantobjects = 0
@end example

ここで説明した変更によって何かアプリケーションの破壊があれば、バグとして報告してください。

@item 
@code{UserDict} モジュールに新しく @code{DictMixin} クラスが追加されました。既に最小限のマッピングインターフェースを持っているクラスのために、全ての辞書メソッドを定義します。これは、 @ref{c8,,shelve} モジュール内のクラスのような、辞書に置換可能である必要があるクラスの記述を大幅に単純化します。

クラスがメソッド @ref{588,,__getitem__()}, @ref{14e3,,__setitem__()}, @ref{14e4,,__delitem__()}, @code{keys()} を定義している場合にはいつでも、スーパークラスとして mix-in を追加すると完全な辞書インターフェースになります。例えば:

@example
>>> import UserDict
>>> class SeqDict(UserDict.DictMixin):
...     """Dictionary lookalike implemented with lists."""
...     def __init__(self):
...         self.keylist = []
...         self.valuelist = []
...     def __getitem__(self, key):
...         try:
...             i = self.keylist.index(key)
...         except ValueError:
...             raise KeyError
...         return self.valuelist[i]
...     def __setitem__(self, key, value):
...         try:
...             i = self.keylist.index(key)
...             self.valuelist[i] = value
...         except ValueError:
...             self.keylist.append(key)
...             self.valuelist.append(value)
...     def __delitem__(self, key):
...         try:
...             i = self.keylist.index(key)
...         except ValueError:
...             raise KeyError
...         self.keylist.pop(i)
...         self.valuelist.pop(i)
...     def keys(self):
...         return list(self.keylist)
...
>>> s = SeqDict()
>>> dir(s)      # See that other dictionary methods are implemented
['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
 '__init__', '__iter__', '__len__', '__module__', '__repr__',
 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
 'setdefault', 'update', 'valuelist', 'values']
@end example

(Contributed by Raymond Hettinger.)

@item 
The DOM implementation in @ref{128,,xml.dom.minidom} can now generate XML output
in a particular encoding by providing an optional encoding argument to the
@ref{c8a,,toxml()} and @ref{c8b,,toprettyxml()} methods of DOM nodes.

@item 
@code{xmlrpclib} モジュールが、 Python の @code{None} のような nil データを処理するための XML-RPC 拡張をサポートするようになりました。 nil 値は XML-RPC 応答のアンマーシャルでいつでもサポートされます。 @code{None} を含んだリクエストを生成するためには、 @code{Marshaller} のインスタンスを生成する際に `allow_none' パラメータに真を与えなければなりません。

@item 
新規モジュール @code{DocXMLRPCServer} は、セルフ-ドキュメンティング XML-RPC サーバを書くのに使えます。実際のところをみるためにはデモモード (つまりプログラムとして) 実行してみてください。ウェブブラウザを RPC サーバに向ければ pydoc スタイルのドキュメントを生成します。xmlrpclib をサーバに向ければ実際のメソッドを呼び出せます。(Contributed by Brian Quinlan.)

@item 
internationalized domain names (RFC 3454, 3490, 3491, 3492) のサポートが追加されました。Unicode ドメイン名とその名前の ASCII 互換エンコーディング (ACE=ASCII-compatible encoding) の間の変換をするのに "idna" エンコーディングを使用出来ます:

@example
>@{@}>@{@}> u"www.Alliancefrançaise.nu".encode("idna")
'www.xn--alliancefranaise-npb.nu'
@end example

@ref{d1,,socket} モジュールも、C ライブラリに渡す前に Unicode ホスト名を ACE バージョンに透過的に変換するように拡張されています。 @code{httplib} や @ref{62,,ftplib} のようなホスト名を扱うモジュールも Unicode ホスト名をサポートしています; @code{httplib} は HTTP @code{Host} ヘッダをドメイン名の ACE 版を使って送信します。 @ref{10e,,urllib} は URL の @code{path} 部分が ASCII のみである限り、非 ASCII ホスト名を持つ Unicode URL をサポートします

この変更の実装のために、 @ref{da,,stringprep} モジュール、 @code{mkstringprep} ツール、 @code{punycode} エンコーディングが追加されました。
@end itemize

@c ======================================================================

@menu
* 日付時刻型:: 
* optparse モジュール:: 

@end menu

@node 日付時刻型,optparse モジュール,,新たなモジュール、改良されたモジュール、非推奨のモジュール<4>
@anchor{whatsnew/2 3 date-time-type}@anchor{16e2}
@subsubsection 日付時刻型


タイムスタンプとして使うのに相応しい日付と時刻の型が @ref{34,,datetime} モジュールとして追加されました。これら型は異なるカレンダであるとか多くの洒落た機能をサポートはせずに、時刻表現の基礎だけに集中するものです。

3 つの基礎となるクラスがあり、 @ref{1fa,,date} は年・月・日を表現し、 @ref{1fb,,time} は時・分・秒を、 @ref{4e2,,datetime} が @ref{1fa,,date} と @ref{1fb,,time} の両方の属性すべてを持ちます。また、 @ref{bc3,,timedelta} は 2 つの時刻の差を表現し、タイムゾーンのロジックは抽象クラス @ref{7f6,,tzinfo} から派生したクラスにより実装されます。

You can create instances of @ref{1fa,,date} and @ref{1fb,,time} by either supplying
keyword arguments to the appropriate constructor, e.g.
@code{datetime.date(year=1972, month=10, day=15)}, or by using one of a number of
class methods.  For example, the @ref{16e3,,today()} class method returns the
current local date.

構築後の日付時刻クラスのインスタンスは全て @ref{15b9,,immutable} です。オブジェクトから書式文字列を生成する数多くのメソッドがあります:

@example
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.isoformat()
'2002-12-30T21:27:03.994956'
>>> now.ctime()  # Only available on date, datetime
'Mon Dec 30 21:27:03 2002'
>>> now.strftime('%Y %d %b')
'2002 30 Dec'
@end example

The @ref{16e4,,replace()} method allows modifying one or more fields  of a
@ref{1fa,,date} or @ref{4e2,,datetime} instance, returning a new instance:

@example
>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
>>> d.replace(year=2001, hour = 12)
datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
>>>
@end example

インスタンスは比較可能で、ハッシュ出来、文字列に変換出来ます (結果は @ref{d25,,isoformat()} メソッドのものと同じです)。  と @ref{4e2,,datetime} はお互いに減算演算が可能で、 @ref{bc3,,timedelta} インスタンスを加算することも出来ます。最も大きな不足機能としては、文字列を解析して @ref{1fa,,date} や @ref{4e2,,datetime} へ戻すための標準ライブラリサポートはありません。(---訳注: 2 点。「比較可能」の意味は 2.3 から 2.4 で意味が変わっています。2.4 で @ref{1fa,,date} と @ref{4e2,,datetime} の比較は出来なくなりました。2.3 では出来ていました。文字列からの @ref{4e2,,datetime} 構築は 2.5 で @code{strptime()} が追加されています。---)

さらに詳しい情報については、モジュールのリファレンスドキュメントを参照してください。 (Contributed by Tim Peters.)

@c ======================================================================

@node optparse モジュール,,日付時刻型,新たなモジュール、改良されたモジュール、非推奨のモジュール<4>
@anchor{whatsnew/2 3 the-optparse-module}@anchor{16e5}
@subsubsection optparse モジュール


@ref{65,,getopt} モジュールはコマンドライン引数の単純な解析を提供しています。新規に追加された @ref{a4,,optparse} モジュール (元々 Optik と呼ばれていたものです) は Unix の慣習に従ったもっと念入りなコマンドライン解析を行い、自動的に @code{--help} のための出力をし、異なったオプションに対して異なったアクションを実行出来ます。 (---訳注: 2.7 以降は @ref{a4,,optparse} よりも新しい @ref{7,,argparse} を使ってください。---)

@ref{16e6,,OptionParser} インスタンスを作ることから始め、プログラムのオプションがどんなであるかそれに対して教えてやります:

@example
import sys
from optparse import OptionParser

op = OptionParser()
op.add_option('-i', '--input',
              action='store', type='string', dest='input',
              help='set input filename')
op.add_option('-l', '--length',
              action='store', type='int', dest='length',
              help='set maximum length of output')
@end example

コマンドラインの解析は @ref{16e7,,parse_args()} メソッドを呼び出すことで行います

@example
options, args = op.parse_args(sys.argv[1:])
print options
print args
@end example

これは、全てのオプションの値を含んだオブジェクトと残った引数を含む文字列リストを返します。

色々な引数でこのスクリプトを実行すれば、あなたの期待するように動きます。この例での `length' 引数が自動的に整数に変換されることに注目してください。

@example
$ ./python opt.py -i data arg1
<Values at 0x400cad4c: @{'input': 'data', 'length': None@}>
['arg1']
$ ./python opt.py --input=data --length=4
<Values at 0x400cad2c: @{'input': 'data', 'length': 4@}>
[]
$
@end example

ヘルプメッセージはあなたのために自動生成されます:

@example
$ ./python opt.py --help
usage: opt.py [options]

options:
  -h, --help            show this help message and exit
  -iINPUT, --input=INPUT
                        set input filename
  -lLENGTH, --length=LENGTH
                        set maximum length of output
$
@end example

さらに詳しいことはモジュールのドキュメントを参照して下さい。

Optik は Getopt SIG の読者からの示唆を受けてGreg Ward により書かれました。

@c ======================================================================

@node Pymalloc 特殊化されたオブジェクトアロケータ,ビルドならびに C API の変更<12>,新たなモジュール、改良されたモジュール、非推奨のモジュール<4>,What's New in Python 2 3
@anchor{whatsnew/2 3 pymalloc-a-specialized-object-allocator}@anchor{16e8}@anchor{whatsnew/2 3 section-pymalloc}@anchor{16e9}
@subsection Pymalloc: 特殊化されたオブジェクトアロケータ


Pymalloc は Vladimir Marangozov により書かれ Python 2.1 で追加された、特殊化されたオブジェクトアロケータです。Pymalloc は典型的な Python プログラムでのアロケーションのパターンにおいて、システムの @code{malloc()} よりも高速で省メモリであることを意図したものです。このアロケータは C の @code{malloc()} 関数を大きなメモリプールを得るのに使い、それより小さなメモリ要求はこれらプールで実現しています。

2.1 と 2.2 ではこの機能は実験的な位置付けでありデフォルトでは有効ではありませんでした。これを有効にするには Python コンパイル時に @code{configure} スクリプトに @code{--with-pymalloc} オプションを明示的に与える必要がありました。2.3 では pymalloc はさらに拡張され、また、デフォルトで有効になりました。逆にこれを無効にするのに @code{--without-pymalloc} を与える必要があります。

この変更は Python で書いたコードからは見えませんが、 pymalloc は C 拡張内のバグを露にするかもしれません。C 拡張の著者は pymalloc を有効にしてテストすべきです。というのも、ある種の正しくないコードが実行時にコアダンプしうるからです。

問題を起こすとりわけ一般的な誤りが一つあります。Python の C API 内には数多くのメモリアロケーション関数がありますが、これは以前は単に C ライブラリの @code{malloc()} と @code{free()} への別名であり、何かの間違いでミスマッチな関数呼び出しをしても、誤りは気付かれないものでした。今回のこのオブジェクトアロケータを有効化すると、これら関数は @code{malloc()} と @code{free()} への別名ではまったくなくて、メモリ解放に誤った関数を呼び出すとコアダンプし得ます。例えば @ref{e62,,PyObject_Malloc()} を使って獲得したメモリは @code{free()} ではなく @ref{e60,,PyObject_Free()} を使って解放する必要があります。Python に含まれるいくつかのモジュールがまさにこれに抵触し、修正の必要がありました。間違いなく多くのサードパーティモジュールが同じ問題を抱えているでしょう。

この変更の一環として、メモリアロケーションのためのこんがらかった複数インターフェイスが統合されて 2 つの API ファミリになりました。一方のファミリで獲得されたメモリは他方の関数で操作されることは許されません。一方のファミリはメモリの塊を獲得するためのもので、もう一方は Python オブジェクトの獲得に特殊化されたものです。


@itemize *

@item 
何某かの区別のないメモリの塊を獲得・解放するのには「生メモリ」ファミリを使います: @ref{e5f,,PyMem_Malloc()}, @ref{1233,,PyMem_Realloc()}, @ref{165b,,PyMem_Free()}.

@item 
「オブジェクトメモリ」ファミリは上述の pymalloc 機構へのインターフェイスであり、多数の「小さな」獲得をするための特化がされています: @ref{e62,,PyObject_Malloc()}, @ref{165c,,PyObject_Realloc()}, @ref{e60,,PyObject_Free()}.

@item 
Python オブジェクトの獲得と解放には「オブジェクト」ファミリ @ref{b7c,,PyObject_New}, @ref{b7d,,PyObject_NewVar}, @ref{16ea,,PyObject_Del()} を使います。
@end itemize

Tim Peters による多大な仕事のおかげで、 2.3 の pymalloc はデバッグ機能も提供しています。これはメモリの上書き、二重解放に関して、拡張モジュールとインタプリタ自身について検出出来ます。このサポートを有効にするには @code{configure} スクリプトにオプション @code{--with-pydebug} を与えて Python インタプリタをデバッグバージョンとしてコンパイルしてください。

拡張の著者のために、Python 2.3 のソースとともにヘッダファイル @code{Misc/pymemcompat.h} が配布されています。これは Python 拡張に 2.3 インターフェイスでのメモリ獲得を使えるようにするもので、1.5.2 以降の全てのバージョンに対してコンパイル可能です。Python のソース配布物からファイルをコピーして、あなたの拡張ソースにバンドル出来ます。


@subsubheading 参考



@table @asis

@item @indicateurl{https://hg.python.org/cpython/file/default/Objects/obmalloc.c}

pymalloc 実装に関する完全な詳細については Python ソースコード内の @code{Objects/obmalloc.c} ファイルの先頭のコメントを参照してください。上のファイルへのリンクは python.org の SVN ブラウザを指しています。
@end table


@c ======================================================================

@node ビルドならびに C API の変更<12>,その他の変更と修正<2>,Pymalloc 特殊化されたオブジェクトアロケータ,What's New in Python 2 3
@anchor{whatsnew/2 3 build-and-c-api-changes}@anchor{16eb}
@subsection ビルドならびに C API の変更


Python のビルド過程と C API の変更は以下の通りです:


@itemize *

@item 
ガーベージコレクションで使われている循環の検出実装が安定であることがわかったため、必須とすることになりました。Python をこれなしでコンパイルすることはもう出来ません。 @code{configure} スクリプトの @code{--with-cycle-gc} スイッチは削除されました。

@item 
Python がオプショナルでシェアドライブラリ (@code{libpython2.3.so}) としてビルド可能になりました。Python の @code{configure} スクリプトに @code{--enable-shared} オプションを与えることで可能です。 (Contributed by Ondrej Palkovsky.)

@item 
マクロ @code{DL_EXPORT} と @code{DL_IMPORT} が非推奨となっています。Python コアが一般的にマクロ @code{PyAPI_FUNC} と @code{PyAPI_DATA} を使うのに対し、Python 拡張モジュールの初期化関数が新規マクロ @ref{16ec,,PyMODINIT_FUNC} を使って宣言されなければならなくなりました。

@item 
@code{configure} スクリプトに @code{--without-doc-strings} オプションを与えることで、ビルトイン関数とモジュールが docstring を持たないインタプリタとしてコンパイル出来るようになりました。これは Python の実行形式ファイルを 10% 小さくしますが、もちろん Python ビルトインのヘルプが取得できないことにもなります。 (Contributed by Gustavo Niemeyer.)

@item 
@code{PyArg_NoArgs()} マクロが非推奨となったので、これを使っているコードは修正しなければなりません。Python 2.2 以降ではメソッド定義テーブルでは引数を持たず、引数チェックを省けることを示すのに @ref{16ed,,METH_NOARGS} フラグが使えます。2.2 以前の Python バージョンとの互換性が重要な場合には @code{PyArg_ParseTuple(args, "")} を代わりに使えますが、 @ref{16ed,,METH_NOARGS} を使うより遅いです。

@item 
@ref{3c1,,PyArg_ParseTuple()} に符号なし整数の色々なサイズのためのフォーマット文字が追加されました: unsigned char のための @code{B}, unsigned short int のための @code{H}, unsigned int のための @code{I}, unsigned long long のための @code{K}。

@item 
新規関数 @code{PyObject_DelItemString(mapping, char *key)} が @code{PyObject_DelItem(mapping, PyString_New(key))} の速記法として追加されました。

@item 
ファイルオブジェクトの内部文字列バッファの管理が変更されて、必要な場合には指数関数的に増やすようになりました。 @code{Lib/test/test_bufio.py} 内のベンチマークテストの結果での速度向上は大幅なものです (ある一つの計測では 57 秒から 1.7 秒になりました)。

@item 
It's now possible to define class and static methods for a C extension type by
setting either the @ref{16ee,,METH_CLASS} or @ref{16ef,,METH_STATIC} flags in a
method's @ref{16f0,,PyMethodDef} structure.

@item 
Python は Expat XML パーサのソースコードのコピーを丸抱えするようになり、これにより Expat のシステムのバージョンやローカルにインストールされたものへの依存がなくなっています。

@item 
If you dynamically allocate type objects in your extension, you should be
aware of a change in the rules relating to the @ref{617,,__module__} and
@ref{16c4,,__name__} attributes.  In summary, you will want to ensure the type's
dictionary contains a @code{'__module__'} key; making the module name the part of
the type name leading up to the final period will no longer have the desired
effect.  For more detail, read the API reference documentation or the  source.
@end itemize

@c ======================================================================

@menu
* ポート特有の変更: ポート特有の変更<3>. 

@end menu

@node ポート特有の変更<3>,,,ビルドならびに C API の変更<12>
@anchor{whatsnew/2 3 port-specific-changes}@anchor{16f1}
@subsubsection ポート特有の変更


Support for a port to IBM's OS/2 using the EMX runtime environment was merged
into the main Python source tree.  EMX is a POSIX emulation layer over the OS/2
system APIs.  The Python port for EMX tries to support all the POSIX-like
capability exposed by the EMX runtime, and mostly succeeds; @code{fork()} and
@ref{5d,,fcntl()} are restricted by the limitations of the underlying emulation
layer.  The standard OS/2 port, which uses IBM's Visual Age compiler, also
gained support for case-sensitive import semantics as part of the integration of
the EMX port into CVS.  (Contributed by Andrew MacIntyre.)

On MacOS, most toolbox modules have been weaklinked to improve backward
compatibility.  This means that modules will no longer fail to load if a single
routine is missing on the current OS version. Instead calling the missing
routine will raise an exception. (Contributed by Jack Jansen.)

The RPM spec files, found in the @code{Misc/RPM/} directory in the Python
source distribution, were updated for 2.3.  (Contributed by Sean Reifschneider.)

Other new platforms now supported by Python include AtheOS
(@indicateurl{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS.

@c ======================================================================

@node その他の変更と修正<2>,Python 2 3 への移植,ビルドならびに C API の変更<12>,What's New in Python 2 3
@anchor{whatsnew/2 3 other-changes-and-fixes}@anchor{16f2}@anchor{whatsnew/2 3 section-other}@anchor{16cd}
@subsection その他の変更と修正


いつものように、たくさんのほかの改善とバグフィックスがソースツリー全体に渡って散らばっています。CVS 変更ログを検索すると、Python 2.2 から 2.3 にかけて適用されたパッチは 523、バグ修正は 514 ありました。いずれも少なく見積もって、です。

ほかの、さらに特筆すべき変更のいくつかを挙げます:


@itemize *

@item 
環境変数 
@geindex PYTHONINSPECT
@geindex 環境変数; PYTHONINSPECT
@ref{16f3,,PYTHONINSPECT} をセットしておくと、Python インタプリタが Python プログラム実行後に対話モードに入ります。これは Python を @ref{16f4,,-i} で起動するのと同じです。環境変数は Python インタプリタ実行前にセットするか、Python プログラムのその実行の一部としてセットすることが出来ます。

@item 
@code{regrtest.py} スクリプトで「`foo' を除く全てのリソース」とする手段が出来ました。 @code{-u} オプションにリソース名を渡すのにハイフン (@code{'-'}) を前置すると「このリソースを除く」ことを意味します。例えば '@code{-uall,-bsddb}' は @code{bsddb} を除く全てのリソースを有効にするのに使えます。

@item 
ドキュメントのビルドに使われるツールは今では Unix 同様に Cygwin でも動作します。

@item 
@code{SET_LINENO} 命令コード (opcode) は削除されました。彼方の昔に戻れば、この命令コードはトレースバック内で行番号を生成し、トレース関数をサポートするのに必要でした (例えば @ref{aa,,pdb} のために)。Python 1.5 より、トレースバック内の行番号は "python -O" で働くための異なったメカニズムを用いて計算で求められてきました。2.3 のためには Michael Hudson がトレース関数を呼ぶのに決定する似た方法を実装しましたので、 @code{SET_LINENO} の必要性は完全になくなりました。

Python コードから何か異なる結果を見つけるのは、 @ref{18c,,-O} なしで Python を実行する際のわずかなスピードアップを別とすれば、困難かもしれません。

フレームオブジェクトの @ref{9af,,f_lineno} フィールドにアクセスしている C 拡張は、代わりに @code{PyCode_Addr2Line(f->f_code, f->f_lasti)} を呼び出すべきです。これは以前の Python バージョンでも "python -O" のもとでコードが動作するのにも望ましい効果を持つでしょう。

気の利いた新機能としては、トレース関数は、今ではフレームオブジェクトの @ref{9af,,f_lineno} 属性を、次に実行される行に変更してセットします。 @ref{aa,,pdb} デバッガにはこの新機能の恩恵を受けて @code{jump} コマンドが追加されています。 (Implemented by Richie Hindle.)
@end itemize

@c ======================================================================

@node Python 2 3 への移植,謝辞<5>,その他の変更と修正<2>,What's New in Python 2 3
@anchor{whatsnew/2 3 porting-to-python-2-3}@anchor{16f5}
@subsection Python 2.3 への移植


このセクションでは前述の変更により必要となるかもしれないコードの変更を列挙します:


@itemize *

@item 
@ref{bc2,,yield} は今では常にキーワードです。変数名として使っていたならば、別の名前を選ぶ必要があります。

@item 
文字列 `X' と `Y' について、 @code{X in Y} は `X' が一文字以上の場合でも動作するようになりました。

@item 
@ref{19b,,int()} 型コンストラクタは、文字列や浮動小数点数を整数に収める際、それがとても大き場合に  @ref{a81,,OverflowError} を投げるのではなく長整数を返すようになっています。

@item 
8 ビット文字を含んだ Unicode 文字列をソースコードに埋め込む場合、ファイルのエンコーディング (UTF-8, Latin-1, あるいはほか何か) を、ファイルの先頭のコメントに宣言しなければなりません。 @ref{16a3,,PEP 263; ソースコードのエンコーディング} を参照してください。

@item 
@code{_tkinter} を介した Tcl メソッド呼び出しは今では文字列だけを返すのではありません。代わりに Tcl は対応する Python の等価なオブジェクトに変換されたオブジェクトを返します。Python に等価なものがなければ @code{_tkinter.Tcl_Obj} で包んで返します。

@item 
@code{0xffffffff} のような大きな値の 8 進、16 進リテラルで @ref{659,,FutureWarning} が発行されます。2.3 ではこれは 32 ビットの値に格納されて結果は負の値になりますが、Python 2.4 ではこれは正の長整数になります。

この警告の修正をする方法が少しだけあります。本当に正の値が欲しいのであれば @code{L} をリテラルの最後に付けて下さい。32 ビット分だけの下位ビットセットで 32 ビット整数を取り出したいのであれば、また、 @code{~(1 << 31)} のような式を使ってきたのであれば、おそらく全ビットをセットすることから始めて上位ビットをクリアするのが最も簡明です。例えば最上位ビット (ビット 31) を単にクリアするには @code{0xffffffffL &~(1L<<31)} と書けます。(---訳注: 2 点。Python 3 サポートを検討するならば @code{L} は付けないように。2.4 以降は警告もなしに長整数になりますし。もう一点はこのパラグラフ全体について。根本的に警告への対処の話をしてるようで後半はほとんど本質でない話をしているので意味不明な文章になっています。本当に 2.3 を使わなければならないのでない限り、この文章を真面目に理解しようとしなくとも良いと思います(本質的な措置は @code{L} を付けることしかない、2.3 では)。---)

@item 
@code{__debug__} に代入することでアサーションを無効にすることは出来なくなりました。

@item 
Distutils の @code{setup()} 関数に `depends' のような色々な新しいキーワード引数が追加されています。Distutils の古いバージョンでは未知のキーワードを渡すと処理を中断してしまいます。新旧で動作させなければならないのであれば、 @code{setup.py} 内で @code{get_distutil_options()} 関数の有無をチェックし、それらをサポートするバージョンの Distutils でのみ新しいキーワード引数を使うようにしてください:

@example
from distutils import core

kw = @{'sources': 'foo.c', ...@}
if hasattr(core, 'get_distutil_options'):
    kw['depends'] = ['foo.h']
ext = Extension(**kw)
@end example

@item 
@code{None} を変数名に使うと @ref{1ae,,SyntaxWarning} 警告を出すようになっています。

@item 
Python と一緒に含まれるモジュールで定義される拡張型の名前にモジュール名と @code{'.'} が型名の頭に付くようになっています。
@end itemize

@c ======================================================================

@node 謝辞<5>,,Python 2 3 への移植,What's New in Python 2 3
@anchor{whatsnew/2 3 acknowledgements}@anchor{16f6}@anchor{whatsnew/2 3 acks}@anchor{16f7}
@subsection 謝辞


著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の人々に感謝します:  Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David Daniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler, Just van Rossum.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 2,What's New in Python 2 1,What's New in Python 2 3,What's New in Python
@anchor{whatsnew/2 2 doc}@anchor{16f8}@anchor{whatsnew/2 2 translation-repo}@anchor{16f9}@anchor{whatsnew/2 2 what-s-new-in-python-2-2}@anchor{16fa}
@section What's New in Python 2.2


@*著者: 
A.M. Kuchling


@c $Id: whatsnew22.tex 37315 2004-09-10 19:33:00Z akuchling $

@menu
* はじめに:: 
* PEP 252 と PEP 253; 型とクラスについての変更: PEP 252 と PEP 253 型とクラスについての変更. 
* PEP 234; イテレータ: PEP 234 イテレータ. 
* PEP 255; 単純なジェネレータ: PEP 255 単純なジェネレータ<2>. 
* PEP 237; 長整数と整数を一体化していく: PEP 237 長整数と整数を一体化していく<2>. 
* PEP 238; 除算演算子を変更していく: PEP 238 除算演算子を変更していく. 
* Unicode の変更:: 
* PEP 227; 入れ子状のスコープ: PEP 227 入れ子状のスコープ. 
* 新しいモジュールと改良されたモジュール: 新しいモジュールと改良されたモジュール<3>. 
* インタプリタの変更と修正:: 
* その他の変更と修正: その他の変更と修正<3>. 
* 謝辞: 謝辞<6>. 

@end menu

@node はじめに,PEP 252 と PEP 253 型とクラスについての変更,,What's New in Python 2 2
@anchor{whatsnew/2 2 introduction}@anchor{16fb}
@subsection はじめに


この文書は 2002 年 10 月 14 日にリリースされた Python 2.2.2 の新機能について解説します。Python 2.2.2 は 2001 年 12 月 21 日にリリースされた Python 2.2 のバグフィックスリリースです。

Python 2.2 は「クリーンアップリリース」と考えることが出来ます。ジェネレータやイテレータのように、完全に書き直されたいくつかの機能があります。ほとんどのその変更は著しくて以前とはかけ離れたものとなりましたが、これは言語設計の不品行と暗黒面を綺麗に掃除することを目的としています。

このドキュメントは個々の新機能の完全な詳細を提供するのではなくて、簡易な概要を提供することを目的にしています。完全な詳細が知りたければ、Python ライブラリリファレンス@footnote{https://docs.python.org/2.2/lib/lib.html} 、Python リファレンスマニュアル@footnote{https://docs.python.org/2.2/ref/ref.html} のような Python 2.2 のドキュメントを参照すべきです。設計と実装の根拠を理解したい場合は、新機能に関する PEP を参照してください。

@c see also, now defunct
@c 
@c http://www.unixreview.com/documents/s=1356/urm0109h/0109h.htm
@c    "What's So Special About Python 2.2?" is also about the new 2.2 features, and
@c    was written by Cameron Laird and Kathryn Soraiz.

@c ======================================================================

@node PEP 252 と PEP 253 型とクラスについての変更,PEP 234 イテレータ,はじめに,What's New in Python 2 2
@anchor{whatsnew/2 2 peps-252-and-253-type-and-class-changes}@anchor{16fc}
@subsection PEP 252 と PEP 253: 型とクラスについての変更


最大にして広範に影響が及ぶ Python 2.2 の変更は、 オブジェクトとクラスの Python モデルについてのものです。変更は後方互換であるはずなので、あなたのコードは変更なしで動きそうです。ですがその変更は、いくつかの素晴らしい能力を発揮させます。この、本記事中において最も長くて複雑なセクションについて始める前に、変更の概要を提供し、いくつかの所感を提示しておこうと思います。

A long time ago I wrote a web page listing flaws in Python's design.  One of the
most significant flaws was that it's impossible to subclass Python types
implemented in C.  In particular, it's not possible to subclass built-in types,
so you can't just subclass, say, lists in order to add a single useful method to
them. The @code{UserList} module provides a class that supports all of the
methods of lists and that can be subclassed further, but there's lots of C code
that expects a regular Python list and won't accept a @ref{16fd,,UserList}
instance.

Python 2.2 はこれを修正し、また、その過程においていくつかの心躍る新機能を追加しました。簡単に要約します:


@itemize *

@item 
あなたはリストのような組み込み型をサブクラス化出来ます。整数でさえ出来ます。そしてあなたのサブクラスは、元の型を要求している全ての場所で動作します。

@item 
以前より使えたインスタンスメソッド加え、静的メソッド、クラスメソッドを今や定義出来ます。

@item 
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 @ref{6fa,,__getattr__()} can be rewritten to use properties instead, making the
resulting code simpler and faster.  As a small side benefit, attributes can now
have docstrings, too.

@item 
`slots' を使って、インスタンスの適正な属性を特定の集合に制限できます。これはタイプミスに対する安全装置にも出来ますし、将来のバージョンの Python では今よりも最適化される可能性があります。
@end itemize

一部のユーザはこれら全ての変更に懸念を表明しました。そうだね、彼らは言います、新しい機能はかっこいいし昔の Python では出来なかった全ての芸当の役に立つさ、だけどさ、それって言語をより複雑にするよなぁ。一部の人々はずっと常に、Python が単純さを保つことを提言してきました。そして彼らはその単純さが失われると感じたのです。

個人的に私は、それらは心配には及ばない、と思っています。多くのそれら新機能は随分と秘伝的で、あなたはそれらに気付く必要もないままたくさんの Python コードを書けます。単純なクラスを書くことはかつてよりも難しいということはなく、実際にそれを必要としない限りは、秘伝をわざわざ学習することも教育することも必要ありません。以前ならば C 言語からでしか可能でなかったようなある種の複雑なタスクは、いまやピュアな python から出来て、私には何もかもが良い方向に思えます。

この記事では全てのショーケースの品を陳列しようとはしませんし、将来の拡張のために必要な小さな変更は説明しません。代わりにこのセクションではおおまかなアウトラインを描きます。Python 2.2 の新しいオブジェクトモデルの追加的な情報源については、 @ref{16fe,,関連リンク} を参照してください。

@menu
* 旧と新クラス:: 
* デスクリプタ:: 
* 多重継承; ダイヤモンドルール: 多重継承 ダイヤモンドルール. 
* 属性アクセス:: 
* 関連リンク:: 

@end menu

@node 旧と新クラス,デスクリプタ,,PEP 252 と PEP 253 型とクラスについての変更
@anchor{whatsnew/2 2 old-and-new-classes}@anchor{16ff}
@subsubsection 旧と新クラス


まず、 Python 2.2 は本当に 2 種類のクラスを持っているのだ、ということを知る必要があります: クラシック、あるいは旧スタイルクラス、と、新スタイルクラスです。旧スタイルクラスのモデルは、以前のバージョンのクラスモデルと完全に同じものです。このセクションに記述する全ての新機能は、全て新スタイルクラスだけに適用されるものです。この逸脱が未来永劫続くことは望まれていません; 最終的には旧スタイルクラスは撤廃されます。たぶん Python 3.0 で。

では、新スタイルクラスは、どうやって定義すればいいのでしょう? 答えは、既存の新スタイルクラスをサブクラス化することです。たとえば整数、リスト、辞書やファイルでさえも、ほとんどの Python 組み込み型は今では新スタイルクラスです。 @ref{c7e,,object} という名の新スタイルクラスは全ての組み込み型の基底クラスとして既に追加されていて、相応しい組み込み型がなければ単に @ref{c7e,,object} をサブクラス化すれば良いです:

@example
class C(object):
    def __init__ (self):
        ...
    ...
@end example

This means that @ref{14ef,,class} statements that don't have any base classes are
always classic classes in Python 2.2.  (Actually you can also change this by
setting a module-level variable named @code{__metaclass__} --- see 
@geindex Python Enhancement Proposals; PEP 253
PEP 253@footnote{https://peps.python.org/pep-0253/}
for the details --- but it's easier to just subclass @ref{c7e,,object}.)

組み込み型(ビルトイン型)のための型オブジェクトは、クレバーなトリックを使って名付けられた組み込み(ビルトイン)として利用可能です。Python は既に組み込み関数 @ref{19b,,int()}, @ref{196,,float()}, @ref{169,,str()} を持っていました。2.2 にはその関数はなくなり、型オブジェクトは呼び出されるとファクトリとして振舞います:

@example
>>> int
<type 'int'>
>>> int('123')
123
@end example

To make the set of types complete, new type objects such as @ref{183,,dict()} and
@code{file()} have been added.  Here's a more interesting example, adding a
@code{lock()} method to file objects:

@example
class LockableFile(file):
    def lock (self, operation, length=0, start=0, whence=0):
        import fcntl
        return fcntl.lockf(self.fileno(), operation,
                           length, start, whence)
@end example

The now-obsolete @code{posixfile} module contained a class that emulated all of
a file object's methods and also added a @code{lock()} method, but this class
couldn't be passed to internal functions that expected a built-in file,
something which is possible with our new @code{LockableFile}.

@node デスクリプタ,多重継承 ダイヤモンドルール,旧と新クラス,PEP 252 と PEP 253 型とクラスについての変更
@anchor{whatsnew/2 2 descriptors}@anchor{1700}
@subsubsection デスクリプタ


In previous versions of Python, there was no consistent way to discover what
attributes and methods were supported by an object. There were some informal
conventions, such as defining @code{__members__} and @code{__methods__}
attributes that were lists of names, but often the author of an extension type
or a class wouldn't bother to define them.  You could fall back on inspecting
the @ref{77d,,__dict__} of an object, but when class inheritance or an arbitrary
@code{__getattr__()} hook were in use this could still be inaccurate.

その新しいクラスモデルの根底にあったひとつの大きな着想は、 `descriptors' を使ったオブジェクトの属性を記述する API を正式なものにしてしまうことです。デスクリプタは属性の値を記述し、それがメソッドなのかフィールドなのかを伝えます。デスククリプタ API によって、静的メソッドとクラスメソッドが、より風変わりなコンストラクタとともに可能となりました。

属性デスクリプタはクラスオブジェクト内部に棲息するオブジェクトで、それ自身のいくつかの属性を持っています:


@itemize *

@item 
@ref{1272,,__name__} は属性の名前です。

@item 
@ref{b21,,__doc__} is the attribute's docstring.

@item 
@code{__get__(object)} は `object' から属性値を取り出すメソッドです。

@item 
@code{__set__(object, value)} は `object' の属性に  `value' をセットするメソッドです。

@item 
@code{__delete__(object, value)} は `object' の `value'  属性を削除します。
@end itemize

例えば、あなたが @code{obj.x} と書いたときに Python が実際に行うことは以下です:

@example
descriptor = obj.__class__.x
descriptor.__get__(obj)
@end example

For methods, @ref{1701,,descriptor.__get__} returns a temporary
object that's
callable, and wraps up the instance and the method to be called on it. This is
also why static methods and class methods are now possible; they have
descriptors that wrap up just the method, or the method and the class.  As a
brief explanation of these new kinds of methods, static methods aren't passed
the instance, and therefore resemble regular functions.  Class methods are
passed the class of the object, but not the object itself.  Static and class
methods are defined like this:

@example
class C(object):
    def f(arg1, arg2):
        ...
    f = staticmethod(f)

    def g(cls, arg1, arg2):
        ...
    g = classmethod(g)
@end example

The @ref{453,,staticmethod()} function takes the function @code{f()}, and returns it
wrapped up in a descriptor so it can be stored in the class object.  You might
expect there to be special syntax for creating such methods (@code{def static f},
@code{defstatic f()}, or something like that) but no such syntax has been defined
yet; that's been left for future versions of Python.

スロットとプロパティのような新機能がさらに新種のデスクリプタとして実装され、また、何か奇抜なデスクリプタクラスを書くことは難しくはありません。例えば、Eiffel 言語スタイルのメソッドに対する事前条件・事後条件を書くことを可能とするデスクリプタクラスを書けるかもしれません。それを使ったクラスはきっとこう定義出来るでしょう:

@example
from eiffel import eiffelmethod

class C(object):
    def f(self, arg1, arg2):
        # The actual function
        ...
    def pre_f(self):
        # Check preconditions
        ...
    def post_f(self):
        # Check postconditions
        ...

    f = eiffelmethod(f, pre_f, post_f)
@end example

Note that a person using the new @code{eiffelmethod()} doesn't have to understand
anything about descriptors.  This is why I think the new features don't increase
the basic complexity of the language. There will be a few wizards who need to
know about it in order to write @code{eiffelmethod()} or the ZODB or whatever,
but most users will just write code on top of the resulting libraries and ignore
the implementation details.

@node 多重継承 ダイヤモンドルール,属性アクセス,デスクリプタ,PEP 252 と PEP 253 型とクラスについての変更
@anchor{whatsnew/2 2 multiple-inheritance-the-diamond-rule}@anchor{1702}
@subsubsection 多重継承: ダイヤモンドルール


多重継承は名前解決のルールの変更を経てより有用なものになっています。クラスのこのようなセットを考えてみましょう (ダイアグラムは Guido van Rossum による 
@geindex Python Enhancement Proposals; PEP 253
PEP 253@footnote{https://peps.python.org/pep-0253/} より):

@example
      class A:
        ^ ^  def save(self): ...
       /   \
      /     \
     /       \
    /         \
class B     class C:
    ^         ^  def save(self): ...
     \       /
      \     /
       \   /
        \ /
      class D
@end example

The lookup rule for classic classes is simple but not very smart; the base
classes are searched depth-first, going from left to right.  A reference to
@code{D.save()} will search the classes @code{D}, @code{B}, and then
@code{A}, where @code{save()} would be found and returned.  @code{C.save()}
would never be found at all.  This is bad, because if @code{C}'s @code{save()}
method is saving some internal state specific to @code{C}, not calling it will
result in that state never getting saved.

新スタイルクラスはちょっと説明するのに複雑な違ったアルゴリズムを使い、この状況では正しいことをします(Python 2.3 ではこのアルゴリズムはさらに変更されて、ほとんどのケースで同じ結果となり、本当に複雑な継承グラフの場合にもっと有用な結果となりました)。


@enumerate 

@item 
List all the base classes, following the classic lookup rule and include a
class multiple times if it's visited repeatedly.  In the above example, the list
of visited classes is [@code{D}, @code{B}, @code{A}, @code{C},
@code{A}].

@item 
Scan the list for duplicated classes.  If any are found, remove all but one
occurrence, leaving the `last' one in the list.  In the above example, the list
becomes [@code{D}, @code{B}, @code{C}, @code{A}] after dropping
duplicates.
@end enumerate

Following this rule, referring to @code{D.save()} will return @code{C.save()},
which is the behaviour we're after.  This lookup rule is the same as the one
followed by Common Lisp.  A new built-in function, @ref{1a6,,super()}, provides a way
to get at a class's superclasses without having to reimplement Python's
algorithm. The most commonly used form will be  @code{super(class, obj)}, which
returns  a bound superclass object (not the actual class object).  This form
will be used in methods to call a method in the superclass; for example,
@code{D}'s @code{save()} method would look like this:

@example
class D (B,C):
    def save (self):
        # Call superclass .save()
        super(D, self).save()
        # Save D's private information here
        ...
@end example

@ref{1a6,,super()} は @code{super(class)} や @code{super(class1, class2)} のように呼ばれれば非束縛のスーパークラスオブジェクトも返せますが、これはあまり役には立たないでしょう。

@node 属性アクセス,関連リンク,多重継承 ダイヤモンドルール,PEP 252 と PEP 253 型とクラスについての変更
@anchor{whatsnew/2 2 attribute-access}@anchor{1703}
@subsubsection 属性アクセス


A fair number of sophisticated Python classes define hooks for attribute access
using @ref{6fa,,__getattr__()}; most commonly this is done for convenience, to make
code more readable by automatically mapping an attribute access such as
@code{obj.parent} into a method call such as @code{obj.get_parent}.  Python 2.2 adds
some new ways of controlling attribute access.

まず、 @code{__getattr__(attr_name)} は新スタイルクラスにおいてもなおサポートされ、変更はありません。これまで同様に、 @code{obj.foo} アクセスが試みられて、インスタンスの辞書に @code{foo} 名の属性が見つからなければ呼び出されます。

New-style classes also support a new method,
@code{__getattribute__(attr_name)}.  The difference between the two methods is
that @ref{dcb,,__getattribute__()} is `always' called whenever any attribute is
accessed, while the old @ref{6fa,,__getattr__()} is only called if @code{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 @code{__getattr__()} method is
complicated because to avoid recursion you can't use regular attribute accesses
inside them, and instead have to mess around with the contents of
@ref{77d,,__dict__}. @ref{6fa,,__getattr__()} methods also end up being called by Python
when it checks for other methods such as @ref{82f,,__repr__()} or @code{__coerce__()},
and so have to be written with this in mind. Finally, calling a function on
every attribute access results in a sizable performance loss.

@ref{4b3,,property} is a new built-in type that packages up three functions that
get, set, or delete an attribute, and a docstring.  For example, if you want to
define a @code{size} attribute that's computed, but also settable, you could
write:

@example
class C(object):
    def get_size (self):
        result = ... computation ...
        return result
    def set_size (self, size):
        ... compute something based on the size
        and set internal state appropriately ...

    # Define a property.  The 'delete this attribute'
    # method is defined as None, so the attribute
    # can't be deleted.
    size = property(get_size, set_size,
                    None,
                    "Storage size of this instance")
@end example

That is certainly clearer and easier to write than a pair of
@code{__getattr__()}/@code{__setattr__()} methods that check for the @code{size}
attribute and handle it specially while retrieving all other attributes from the
instance's @ref{77d,,__dict__}.  Accesses to @code{size} are also the only ones
which have to perform the work of calling a function, so references to other
attributes run at their usual speed.

もう一つ最後、新しいクラス属性 @ref{1704,,__slots__} を使うと、オブジェクトで参照出来る属性リストを制約することが出来ます。Python オブジェクトは普通非常に動的で、どんなときにもインスタンスに対して単に @code{obj.new_attr=1} とするだけで新しい属性を定義出来ます。新スタイルクラスは @ref{1704,,__slots__} という名前のクラス属性を定義出来、これにより適正な属性名集合を特定の集合に制限出来ます。実例をみるのが早いです:

@example
>>> class C(object):
...     __slots__ = ('template', 'name')
...
>>> obj = C()
>>> print obj.template
None
>>> obj.template = 'Test'
>>> print obj.template
Test
>>> obj.newattr = None
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'newattr'
@end example

@ref{1704,,__slots__} リストに含めなかった属性への代入を試みて @ref{5f0,,AttributeError} になっていることに注目してください。

@node 関連リンク,,属性アクセス,PEP 252 と PEP 253 型とクラスについての変更
@anchor{whatsnew/2 2 related-links}@anchor{1705}@anchor{whatsnew/2 2 sect-rellinks}@anchor{16fe}
@subsubsection 関連リンク


このセクションは新機能について、あなたがプログラミングを始める説明としては十分な簡単な概要だけ示しました。ですが、多くの詳細は、単純化したり無視しています。もっと完全な光景を眺めたければ、どこに行けば良いでしょうか?

The @ref{1706,,デスクリプタ ガイド} 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.

次です。2 つの関連する PEP、 
@geindex Python Enhancement Proposals; PEP 252
PEP 252@footnote{https://peps.python.org/pep-0252/}, 
@geindex Python Enhancement Proposals; PEP 253
PEP 253@footnote{https://peps.python.org/pep-0253/} があります。 
@geindex Python Enhancement Proposals; PEP 252
PEP 252@footnote{https://peps.python.org/pep-0252/} は "型をもっとクラスに似せる(Making Types Look More Like Classes)" というタイトルで、デスクリプタ API についてカバーしています。 
@geindex Python Enhancement Proposals; PEP 253
PEP 253@footnote{https://peps.python.org/pep-0253/} は "組み込み型のサブタイプ化(Subtyping Built-in Types)" というタイトルで、組み込み型のサブタイプを可能とするための型オブジェクトの変更について記述しています。 
@geindex Python Enhancement Proposals; PEP 253
PEP 253@footnote{https://peps.python.org/pep-0253/} は 252 よりも複雑な PEP で、型とメタ型で必要な説明のいくつかのポイントでは、あなたの脳味噌は爆発するかもしれないです。どちらの PEP も、著・実装ともに、Zope Corp. チームの残りのメンバーからのかなりの支援を受けて、Guido van Rossum によって書かれました。

最後ですが、究極の権威があります: ソースコードです。型ハンドリングのほとんどの機構は @code{Objects/typeobject.c} 内にあります。ただしこれに頼るのは、python-list や python-dev へ質問を投稿することを含むほかの全ての手段を使い果たしたのちの最後の手段にしてください。

@c ======================================================================

@node PEP 234 イテレータ,PEP 255 単純なジェネレータ<2>,PEP 252 と PEP 253 型とクラスについての変更,What's New in Python 2 2
@anchor{whatsnew/2 2 pep-234-iterators}@anchor{1707}
@subsection PEP 234: イテレータ


2.2 でのもう一つの重要な追加は、C と Python レベル両方に対するイテレーションインターフェイスです。オブジェクトが呼び出し元からどのように反復されるのか定義出来ます。

In Python versions up to 2.1, the usual way to make @code{for item in obj} work is
to define a @ref{588,,__getitem__()} method that looks something like this:

@example
def __getitem__(self, index):
    return <next item>
@end example

@ref{588,,__getitem__()} is more properly used to define an indexing operation on an
object so that you can write @code{obj[5]} to retrieve the sixth element.  It's a
bit misleading when you're using this only to support @ref{34a,,for} 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 @ref{588,,__getitem__()} calls will be made with `index' incrementing by
one each time.  In other words, the presence of the @ref{588,,__getitem__()} method
doesn't mean that using @code{file[5]}  to randomly access the sixth element will
work, though it really should.

In Python 2.2, iteration can be implemented separately, and @ref{588,,__getitem__()}
methods can be limited to classes that really do support random access.  The
basic idea of iterators is  simple.  A new built-in function, @code{iter(obj)}
or @code{iter(C, sentinel)}, is used to get an iterator. @code{iter(obj)} returns
an iterator for the object `obj', while @code{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 @code{__iter__()} method, which should create and
return a new iterator for the object; if the object is its own iterator, this
method can just return @code{self}.  In particular, iterators will usually be their
own iterators.  Extension types implemented in C can implement a @ref{1708,,tp_iter}
function in order to return an iterator, and extension types that want to behave
as iterators can define a @ref{1709,,tp_iternext} function.

それでは、結局のところイテレータは実際どんなでしょうか? これに必要なメソッドは一つ、 @ref{9d8,,next()} です (---訳注: Python 3 で @code{__next__} に変更されています---)。これは引数を取らず、次の値を返します。返すべき値がなくなったら、 @ref{9d8,,next()} 呼び出しは @ref{df5,,StopIteration} 例外を送出しなければなりません:

@example
>>> L = [1,2,3]
>>> i = iter(L)
>>> print i
<iterator object at 0x8116870>
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>>
@end example

In 2.2, Python's @ref{34a,,for} statement no longer expects a sequence; it
expects something for which @ref{9d7,,iter()} will return an iterator. For backward
compatibility and convenience, an iterator is automatically constructed for
sequences that don't implement @code{__iter__()} or a @ref{1708,,tp_iter} slot, so
@code{for i in [1,2,3]} will still work.  Wherever the Python interpreter loops
over a sequence, it's been changed to use the iterator protocol.  This means you
can do things like this:

@example
>>> L = [1,2,3]
>>> i = iter(L)
>>> a,b,c = i
>>> a,b,c
(1, 2, 3)
@end example

いくつかの Python の基礎型には既にイテレータのサポートが追加されています。辞書に対して @ref{9d7,,iter()} を呼び出すと、キーの反復をするイテレータが返ります:

@example
>>> m = @{'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12@}
>>> for key in m: print key, m[key]
...
Mar 3
Feb 2
Aug 8
Sep 9
May 5
Jun 6
Jul 7
Jan 1
Apr 4
Nov 11
Dec 12
Oct 10
@end example

That's just the default behaviour.  If you want to iterate over keys, values, or
key/value pairs, you can explicitly call the @code{iterkeys()},
@code{itervalues()}, or @code{iteritems()} methods to get an appropriate iterator.
In a minor related change, the @ref{34b,,in} operator now works on dictionaries,
so @code{key in dict} is now equivalent to @code{dict.has_key(key)}.

ファイルもイテレータを提供しています。これはファイルに読むべき行がなくなるまで @ref{bf,,readline()} を呼び出すもので、つまりファイルを行ごとに読み出すのにこのように書けるわけです:

@example
for line in file:
    # do something for each line
    ...
@end example

イテレータは前進しか出来ないことに注意してください; 前の要素を取り出す手段もなければ、イテレータをリセットしたりコピーしたりといったことも出来ません。イテレータオブジェクトにそのような追加の能力を持たせることは出来ますが、イテレータプロトコルが規定するのは @ref{9d8,,next()} メソッドのみです。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 234

@item PEP 234@footnote{https://peps.python.org/pep-0234/}: イテレータ

著: Ka-Ping Yee と GvR (Guido van Rossum); 実装: Python Labs クルー, 主に GvR と Tim Peters.
@end table


@c ======================================================================

@node PEP 255 単純なジェネレータ<2>,PEP 237 長整数と整数を一体化していく<2>,PEP 234 イテレータ,What's New in Python 2 2
@anchor{whatsnew/2 2 pep-255-simple-generators}@anchor{170a}
@subsection PEP 255: 単純なジェネレータ


ジェネレータはもう一つの新機能で、これはイテレータの導入と連携するものです。

Python や C の標準的な関数コールについては、よくご存じに違いありません。関数を呼ぶと、ローカル変数を作るプライベートな名前空間ができますね。その関数が @ref{1af,,return} 文まで来ると、ローカル変数が破壊されてから、返り値が呼び出し元に返ります。次に同じ関数をもう一度呼ぶと、新しいプライベート名前空間に新規のローカル変数が作られるのです。しかし、関数を出るときにローカル変数を捨てなければどうなるでしょうか。その出ていったところから関数を続行できたとしたら、どうでしょう。これこそジェネレータが提供する機能です; すなわち、ジェネレータは続行できる関数と考えることができます。

ジェネレータ関数の最も単純な例です:

@example
def generate_ints(N):
    for i in range(N):
        yield i
@end example

新しいキーワード @ref{bc2,,yield} がジェネレータのために導入されました。 @code{yield} ステートメントを含むどんな関数もジェネレータ関数です; Python バイトコードコンパイラはこれを検知し、関数が特別に扱われるように翻訳します。新たなキーワードの導入なので、ジェネレータを使えるようにするには @code{from __future__ import generators} ステートメントをモジュールソースコードの先頭付近に含めなければなりません。Python 2.3 ではこのステートメントは不要になります。(---訳注: Python 2.5 の PEP 342 も参照して下さい。この 2.2 で導入時点の @code{yield} はステートメントではなく式に変更されています。---)

ジェネレータ関数を呼び出すと、単一の値の代わりにイテレータプロトコルに対応したオブジェクトを返します。上の例で @code{yield} を実行したとき、ジェネレータは @code{return} 文のようにして @code{i} の値を生成します。 @code{yield} と @code{return} 文の大きな違いは、 @code{yield} に到達した段階でジェネレータの実行状態が一時停止になって、ローカル変数が保存される点です。次回そのジェネレータの @code{.next()} メソッドを呼ぶと、 @code{yield} の直後から関数が実行を再開します。(複雑な理由により、 @code{yield} は @code{try}...@ref{1b0,,finally} の @code{try} ブロック内に含めることは許されていません; 
@geindex Python Enhancement Proposals; PEP 255
PEP 255@footnote{https://peps.python.org/pep-0255/} に @code{yield} と例外の相互作用についての詳細説明がありますので参照して下さい。) --- (---訳注: Python 2.5 の PEP 342 で @ref{8f8,,try}...@ref{1b0,,finally} 内に置けないという制約はなくなりました。また、 @ref{8f8,,try}...@ref{1b0,,finally} の @ref{8f8,,try} 、とここであえて特定しているのは、同じく 2.5 の PEP 341 によって try/except/finally の一体化されるまでは、 @code{finally} の @code{try} と @code{except} の @code{try} が別物だったからです。---)

上記の @code{generate_ints()} ジェネレータはこんな具合に使います:

@example
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in generate_ints
StopIteration
@end example

同じく @code{for i in generate_ints(5)} や @code{a,b,c = generate_ints(3)} といった書き方もできます。

ジェネレータ関数内で @ref{1af,,return} 文は、引数を付けずに、処理の終わりを知らせるためにだけ使うことができます; @code{return} を実行したあとは、もうそのジェネレータが値を返すことはできません。ジェネレータ関数の中では、 @code{return 5} などと値を付けた @code{return} は構文エラーです。ジェネレータの出力が終わったことを示すには、ほかにも、手動で @ref{df5,,StopIteration}  を投げてもいいですし、関数の最後まで実行するだけでも同じことになります。(---訳注: Python 2.7 まではジェネレータ内での戻り値のある @code{return 5} は構文エラーになりますが、少なくとも Python 3.4 で構文エラーとはなりません。単に無視されます。リファレンスに言及されていない振舞いなので、何かの事故かもしれません。いずれにせよジェネレータ内では Python 3 でも @code{return} で値は戻せません。---)

自分でクラスを書いて、ジェネレータで言うところのローカル変数をインスタンス変数として全部保管しておけば、同じ効果を得ることは可能です。たとえば整数のリストを返すのは、 @code{self.count} を 0 にして、 @ref{9d8,,next()} メソッドが @code{self.count} をインクリメントして返すようにすればできます。しかしながら、ある程度複雑なジェネレータになってくると、同じことをするクラスを書くのは格段にややこしいことになります。 @code{Lib/test/test_generators.py} にはもっと面白い例がたくさん含まれています。一番単純な一つは、ジェネレータを再帰的に使ってツリーを順繰りに横断する実装をするこれです (---訳注: ジェネレータは現在の最新 3.5 までの間に 2 度大きな機能強化が行われているのですが、一つが 2.5 での PEP 342 でこれは yield 「に」値を戻せるようにするものです。もう一つが 3.3 での PEP 380 で、これはサブジェネレータへの委譲 @code{yield from <subgen>} の追加でした。ですのでこの 3.3 からの @code{yield from} を使うと下記例はもっとスッキリ書けます。---):

@example
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x
@end example

ほかにも @code{Lib/test/test_generators.py} には、N-Queens 問題 (N×N コマのチェス盤に、互いに攻撃できないような配置で N 個のクイーンを置く) やナイト・ツアー (N×N 盤の全コマをナイトが一度ずつ通るような経路を探す) の解を出す例が入っています。

ジェネレータの発想はほかのプログラミング言語、特に Icon (@indicateurl{https://www2.cs.arizona.edu/icon/}) から着想しています。Icon ではジェネレータが言語の中枢になっています。Icon では、あらゆる式と関数がジェネレータのように振舞います。 @indicateurl{https://www2.cs.arizona.edu/icon/docs/ipd266.htm} の "Icon プログラミング言語の概要" の一つの例が、これがどのようなものであるのかを教えてくれます:

@example
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
@end example

Icon では @code{find()} 関数は部分文字列 "or" が見つかる位置 3, 23, 33 を返します。 @ref{181,,if} 文内では @code{i} には最初 3 が代入されますが、これは 3 より小さいので比較は失敗し、Icon は次の値 23 を取り出します。 23 は 5 より大きいので比較は成功し、コードは 23 をスクリーンに表示します。

Python では Icon がそうするほどにはジェネレータを中心的概念に置きません。ジェネレータは Python 言語中核の新たな一面ではありますが、それらを学ぶのも使うのも誰しも行うべきだというものでもなく、そしてこれで解決できない何か問題があれば、忘れてしまっても良いものです。Icon と比較した特筆すべき Python インターフェイスの機能はジェネレータの状態が具象オブジェクト (イテレータ) で表現されることであり、それは他の関数に渡せますし、データ構造に記憶しておくことも出来ます。(---訳注: ジェネレータについてかなり控えめなのは、この時点で著者は将来の拡張を既に見据えていたから? かもしれませんね。PEP 342 と PEP 380 により今やジェネレータはこの頃より遥かに高機能になっており、今ではきっと「こんなものなくても困らない」なんて Python 使いはいないでしょう。---)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 255

@item PEP 255@footnote{https://peps.python.org/pep-0255/} - 単純なジェネレータ

Neil Schemenauer, Tim Peters, Magnus Lie Hetland により著されました。実装のほとんどは Neil Schemenauer と Tim Peters により行われ、 Python Labs クルーにより他の修正が行われました。
@end table


@c ======================================================================

@node PEP 237 長整数と整数を一体化していく<2>,PEP 238 除算演算子を変更していく,PEP 255 単純なジェネレータ<2>,What's New in Python 2 2
@anchor{whatsnew/2 2 pep-237-unifying-long-integers-and-integers}@anchor{170b}
@subsection PEP 237: 長整数と整数を一体化していく


In recent versions, the distinction between regular integers, which are 32-bit
values on most machines, and long integers, which can be of arbitrary size, was
becoming an annoyance.  For example, on platforms that support files larger than
@code{2**32} bytes, the @code{tell()} method of file objects has to return a long
integer. However, there were various bits of Python that expected plain integers
and would raise an error if a long integer was provided instead.  For example,
in Python 1.5, only regular integers could be used as a slice index, and
@code{'abc'[1L:]} would raise a @ref{198,,TypeError} exception with the message 'slice
index must be int'.

Python 2.2 は必要に応じて short 整数を長整数に値をシフトします。 'L' サフィックスは長整数リテラルを示すのにはもはや不要です。今ではコンパイラは相応しい型を選べます。('L' サフィックスは将来の Python 2.x では非推奨となり、Python 2.4 では警告となり、おそらく Python 3.0 では削除されます。 --- 訳注: Python 3 で 'L' が廃止されて、付けると構文エラーになるようになったのは事実です。ですが少なくとも Python 2.7 では @code{-3} でも @code{-Qwarnall} でも警告とならないので注意してください。Python 2 系を使っていて Python 3 との互換性を持ちたいならば、 2.2 以降では 'L' は付けるべきではありません。 --- ) かつて @ref{a81,,OverflowError} となっていたような多くの演算が、今ではその結果として長整数を返します。例えば:

@example
>>> 1234567890123
1234567890123L
>>> 2 ** 64
18446744073709551616L
@end example

ほとんどのケースで、今や整数と長整数は同じものとして扱われるでしょう。 @ref{f44,,type()} ビルトインで今でも区別出来ますが、ほとんど必要ないでしょう (--- 訳注: Python 3 では本当にこの2つの区別がなくなったので、当然区別出来ません。Python 3 系への移行を考えている Python 2 コードは、両者の区別に頼らないようにするべきです。 ---)。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 237

@item PEP 237@footnote{https://peps.python.org/pep-0237/} - 長整数と整数を一体化していく

Moshe Zadka と Guido van Rossum 著、実装 (ほぼ) Guido van Rossum.。
@end table


@c ======================================================================

@node PEP 238 除算演算子を変更していく,Unicode の変更,PEP 237 長整数と整数を一体化していく<2>,What's New in Python 2 2
@anchor{whatsnew/2 2 pep-238-changing-the-division-operator}@anchor{170c}
@subsection PEP 238: 除算演算子を変更していく


Python 2.2 の変更で最も物議を醸すものが、Python 誕生時からずっとそうであり続けた古い設計の欠陥、これを修正するための取り組み開始の予兆です。現在の Python の除算演算子 @code{/} は 2 つの整数引数に対して C 言語の除算演算子のように振舞います: 端数部があれば切り捨てて整数を結果として返します。例えば @code{3/2} は 1.5 ではなく 1 で、 @code{(-1)/2} は -0.5 ではなく -1 です。Python の動的型付けにより演算対象の型がなんなのかを容易には決定できないくせに 2 つの演算対象の型に依存するので、除算の結果は予想に反したものとなりうるのです。

(議論の的となるのはこれが `本当の' 設計の欠陥なのかどうかと、果たしてこれを修正することで既存のコードを破壊する価値はあるのかどうかです。それは python-dev での終わりのない議論を巻き起こし、2001 年 7 月には @code{comp.lang.python} への辛辣な投稿の嵐に突入しました。私はここではどちらかの側に立って説きつけるつもりはなく、Python 2.2 で何が実現したのかを記述することだけに専念します。
@geindex Python Enhancement Proposals; PEP 238
PEP 238@footnote{https://peps.python.org/pep-0238/} にはその主張と反対意見の要約が書かれていますので、そちらをお読みください。)

この変更がコードを破壊しうるために、導入は大変ゆっくり少しずつ進められていきます。Python 2.2 が移行を始めますが、切り替えは Python 3.0 になるまで達成させられることはありません。

まず最初に、いくつか 
@geindex Python Enhancement Proposals; PEP 238
PEP 238@footnote{https://peps.python.org/pep-0238/} から用語を借りることにします。
"真の除算 (True division)" とは、プログラマでない人々が一番馴染みのある除算です。
3/2 は 1.5、1/4 は 0.25、などなど。
"切り捨て除算 (Floor division)" は、整数の被演算子が与えられたときの Python の @code{/} 演算子が現在やっていることで、結果は真の除算の結果の値の小数点以下を小さくなる方向へ丸めたものです。
"クラシック除算 (Classic division)" は現在の @code{/} の混合した振る舞いを指します。演算対象が整数同士であれば切り捨て除算の結果となり、一方が浮動小数点数であれば真の除算の結果となる振る舞いです。

以下が 2.2 で導入される変更です:


@itemize *

@item 
新しい演算子 @code{//} が floor division の演算子です。(いえーい、これって C++ コメントのシンボルに似てるね、なんてことは私たちは知っています。) @code{//} は演算対象の型がなんであれ `いつでも' floor division を実行しますので、 @code{1 // 2} は 0、 @code{1.0 // 2.0} も 0.0 です。

@code{//} は Python 2.2 でいつでも使えます; @code{__future__} を使って有効化するなんてことは必要ないです。

@item 
@code{from __future__ import division} をモジュールに import することで、 @code{/} 演算子が真の除算 (true division) の結果を返すように変更されるので、 @code{1/2} は 0.5 になります。 @code{__future__} 文なしでは @code{/} はクラシック除算 (classic division) のままです。 @code{/} が持つデフォルトの意味は Python 3.0 になるまで変更されません。

@item 
Classes can define methods called @ref{1090,,__truediv__()} and @ref{170d,,__floordiv__()}
to overload the two division operators.  At the C level, there are also slots in
the @ref{1637,,PyNumberMethods} structure so extension types can define the two
operators.

@item 
Python 2.2 は、コードが変更後の除算セマンティクスで動作するかどうかをテストするコマンドライン引数をサポートします。 @code{-Q warn} で python を実行すると、除算が二つの整数に適用されている箇所全てで警告します。除算の意味変更の影響を受ける箇所の特定と修正に使えるでしょう。デフォルトでは、Python 2.2 は警告なしで単純に classic division を実行します; その警告がデフォルトになるのは Python 2.3 からです。
@end itemize


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 238

@item PEP 238@footnote{https://peps.python.org/pep-0238/} - 除算演算子を変更していく

Moshe Zadka と Guido van Rossum 著、実装 Guido van Rossum.。
@end table


@c ======================================================================

@node Unicode の変更,PEP 227 入れ子状のスコープ,PEP 238 除算演算子を変更していく,What's New in Python 2 2
@anchor{whatsnew/2 2 unicode-changes}@anchor{170e}
@subsection Unicode の変更


Python の Unicode サポートが 2.2 で少し拡張されています。Unicode 文字列は普通は 16 ビット符号なし整数としての UCS-2 で格納されます。Python 2.2 は内部エンコーディングとして 32 ビット符号なし整数の UCS-4 を使うようにもコンパイル出来ます。これは @code{configure} スクリプトに @code{--enable-unicode=ucs4} オプションを与えることで行います。(@code{--disable-unicode} を与えることで完全に Unicode サポートを無効にすることも出来ます。)

When built to use UCS-4 (a "wide Python"), the interpreter can natively handle
Unicode characters from U+000000 to U+110000, so the range of legal values for
the @code{unichr()} function is expanded accordingly.  Using an interpreter
compiled to use UCS-2 (a "narrow Python"), values greater than 65535 will still
cause @code{unichr()} to raise a @ref{2ec,,ValueError} exception. This is all
described in 
@geindex Python Enhancement Proposals; PEP 261
PEP 261@footnote{https://peps.python.org/pep-0261/}, "Support for 'wide' Unicode characters"; consult it for
further details.

Another change is simpler to explain. Since their introduction, Unicode strings
have supported an @code{encode()} method to convert the string to a selected
encoding such as UTF-8 or Latin-1.  A symmetric @code{decode([*encoding*])}
method has been added to 8-bit strings (though not to Unicode strings) in 2.2.
@code{decode()} assumes that the string is in the specified encoding and decodes
it, returning whatever is returned by the codec.

この新たなインターフェイスに相乗りする形で、 Unicode には無関係のタスクのためのコーデックが追加されました。例えば uu エンコーディング、 MIME の base64 エンコーディング、 @ref{139,,zlib} モジュールでの圧縮のためのエンコーディングが追加されています:

@example
>>> s = """Here is a lengthy piece of redundant, overly verbose,
... and repetitive text.
... """
>>> data = s.encode('zlib')
>>> data
'x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...'
>>> data.decode('zlib')
'Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n'
>>> print s.encode('uu')
begin 666 <data>
M2&5R92!I<R!A(&QE;F=T:'D@@<&EE8V4@@;V8@@<F5D=6YD86YT+"!O=F5R;'D@@
>=F5R8F]S92P*86YD(')E<&5T:71I=F4@@=&5X="X*

end
>>> "sheesh".encode('rot-13')
'furrfu'
@end example

To convert a class instance to Unicode, a @code{__unicode__()} method can be
defined by a class, analogous to @code{__str__()}.

@code{encode()}, @code{decode()}, and @code{__unicode__()} were implemented by
Marc-André Lemburg.  The changes to support using UCS-4 internally were
implemented by Fredrik Lundh and Martin von Löwis.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 261

@item PEP 261@footnote{https://peps.python.org/pep-0261/} - 'wide' Unicode 文字のサポート

Paul Prescod 著。 (---訳注: この What's New セクションと PEP 内容は 2.x ではずっと有効ですが、3.x で大幅に変わっていて逐一補足出来ないほど大きく違っています。変更の概要についてはクックブックの「Python 2 から Python 3 への移植」がわかりやすいと思います。---)
@end table


@c ======================================================================

@node PEP 227 入れ子状のスコープ,新しいモジュールと改良されたモジュール<3>,Unicode の変更,What's New in Python 2 2
@anchor{whatsnew/2 2 pep-227-nested-scopes}@anchor{170f}
@subsection PEP 227: 入れ子状のスコープ


Python 2.1 では、静的にネストされたスコープが @code{from __future__ import nested_scopes} ディレクティブで有効に出来るオプションの機能として追加されました。2.2 では入れ子のスコープには特別に有効化する必要なく、もういつでもそこにあります。このセクションの残りの部分は "What's New in Python 2.1" の入れ子のスコープの記述からの丸々コピーですので、2.1 のときに読んだなら読み飛ばしてもらって結構です。

Python2.1 で導入され、2.2 で完成した最も大きな変更点は Python のスコープルールです。Python2.0では、ある指定された時点である変数の名前を検索するために多くても3つの名前空間、つまりローカル、モジュールレベル、ビルトイン名前空間しか使われませんでした。このことは直感的な期待と一致せずしばしば人々を驚かせました。例えば、入れ子になった再帰関数の定義は動きません:

@example
def f():
    ...
    def g(value):
        ...
        return g(value-1) + 1
    ...
@end example

The function @code{g()} will always raise a @ref{452,,NameError} exception, because
the binding of the name @code{g} isn't in either its local namespace or in the
module-level namespace.  This isn't much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the @ref{14b5,,lambda} expression clumsier, and this was a problem in practice.
In code which uses @code{lambda} you can often find local variables being
copied by passing them as the default values of arguments.

@example
def find(self, name):
    "Return list of any entries equal to 'name'"
    L = filter(lambda x, name=name: x == name,
               self.list_attribute)
    return L
@end example

過度な関数型スタイルで書かれた Python コードの可読性は、結果的にはひどく苦痛を感じるものですね。

Python 2.2 の最も重要な変更点は、この問題を解決するために静的なスコープが追加されたことです。最初の効果として、 @code{name=name} という例ではデフォルトの引数は必要ありません。簡単に言えば、指定された引数名が関数内の値に割り当てられない場合(@ref{1673,,def} 、 @ref{14ef,,class} または @ref{7f8,,import} ステートメントの割り当てによって)、変数の参照は外側のスコープのローカル名前空間で検索されます。ルールや実装の詳細は PEP で参照できます。

この変更は、同じ変数名がモジュールレベルと関数の定義が含まれている関数内のローカルの両方で変数名として使用されているコードで、互換性の問題を引き起こす可能性があります。ですがむしろ気にしなくてよいでしょう。そのようなコードはそもそも最初から相当こんがらかっているので。

この変更の副作用の一つは、 @code{from module import *} と @code{exec} の両ステートメントが特定の条件下の関数スコープ内で不正となることです。 Python のリファレンスマニュアルははじめからずっと @code{from module import *} はトップレベルモジュールでのみ合法であると言ってきましたが、以前の CPython インタプリタはこれを一度も強制していませんでした。入れ子になったスコープ実装の一環として、Python のソースをバイトコードに変換するコンパイラは、内包されたスコープ内の変数にアクセスするために別のコードを生成する必要があります。 @code{from module import *}, @code{exec} はコンパイラにこれを理解することを不可能にしてしまいます。なぜならそれらはコンパイル時にはわからないローカル名前空間に名前を追加するからです。それゆえ、もし関数が関数定義を含んだり自由な変数に @ref{14b5,,lambda} の語句を含んだりする場合、コンパイラは @ref{18e,,SyntaxError} 例外を上げて知らせます。

前述した説明を少し明確にするため、例を挙げます:

@example
x = 1
def f():
    # The next line is a syntax error
    exec 'x=2'
    def g():
        return x
@end example

Line 4 containing the @code{exec} statement is a syntax error, since
@code{exec} would define a new local variable named @code{x} whose value should
be accessed by @code{g()}.

これは実際には大した制約でもないはずです。 @code{exec} が Python コードで使われるのは稀です(使われているとしたら大抵どこか貧弱な設計であることの証)。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 227

@item PEP 227@footnote{https://peps.python.org/pep-0227/} - 静的に入れ子になったスコープ

Jeremy Hylton著、実装
@end table


@c ======================================================================

@node 新しいモジュールと改良されたモジュール<3>,インタプリタの変更と修正,PEP 227 入れ子状のスコープ,What's New in Python 2 2
@anchor{whatsnew/2 2 new-and-improved-modules}@anchor{1710}
@subsection 新しいモジュールと改良されたモジュール



@itemize *

@item 
The @ref{134,,xmlrpclib} module was contributed to the standard library by Fredrik
Lundh, providing support for writing XML-RPC clients.  XML-RPC is a simple
remote procedure call protocol built on top of HTTP and XML. For example, the
following snippet retrieves a list of RSS channels from the O'Reilly Network,
and then  lists the recent headlines for one channel:

@example
import xmlrpclib
s = xmlrpclib.Server(
      'http://www.oreillynet.com/meerkat/xml-rpc/server.php')
channels = s.meerkat.getChannels()
# channels is a list of dictionaries, like this:
# [@{'id': 4, 'title': 'Freshmeat Daily News'@}
#  @{'id': 190, 'title': '32Bits Online'@},
#  @{'id': 4549, 'title': '3DGamers'@}, ... ]

# Get the items for one channel
items = s.meerkat.getItems( @{'channel': 4@} )

# 'items' is another list of dictionaries, like this:
# [@{'link': 'http://freshmeat.net/releases/52719/',
#   'description': 'A utility which converts HTML to XSL FO.',
#   'title': 'html2fo 0.3 (Default)'@}, ... ]
@end example

The @ref{135,,SimpleXMLRPCServer} module makes it easy to create straightforward
XML-RPC servers.  See @indicateurl{http://xmlrpc.scripting.com/} for more information about XML-RPC.

@item 
新しい @ref{6e,,hmac} モジュールは、 
@geindex RFC; RFC 2104
RFC 2104@footnote{https://datatracker.ietf.org/doc/html/rfc2104.html} で記述される HMAC アルゴリズムを実装します 。 (Contributed by Gerhard Häring.)

@item 
Several functions that originally returned lengthy tuples now return
pseudo-sequences that still behave like tuples but also have mnemonic attributes such
as @code{memberst_mtime} or @ref{1711,,tm_year}. The enhanced functions include
@ref{26d,,stat()}, @ref{f8c,,fstat()}, @ref{1314,,statvfs()}, and @ref{f8d,,fstatvfs()} in the
@ref{a5,,os} module, and @ref{1712,,localtime()}, @ref{13d8,,gmtime()}, and @ref{1646,,strptime()} in
the @ref{f4,,time} module.

例えば旧式のタプルでファイルサイズを得るには @code{file_size = os.stat(filename)[stat.ST_SIZE]} のように書くしかありませんでしたが、今ではもっとわかりやすい @code{file_size = os.stat(filename).st_size} のように書くことが出来ます。

この機能のオリジナルのパッチは Nick Mathewson により寄稿されました。

@item 
Python プロファイラが大幅に改造されて、出力の色々な間違いが修正されました。 (Contributed by Fred L. Drake, Jr. and Tim Peters.)

@item 
@ref{d1,,socket} モジュールを IPv6 サポート付きでコンパイル可能になりました。Python の @code{configure} スクリプトに @code{--enable-ipv6} オプションを与えてください。(Contributed by Jun-ichiro "itojun" Hagino.)

@item 
Two new format characters were added to the @ref{db,,struct} module for 64-bit
integers on platforms that support the C long long type.  @code{q} is for
a signed 64-bit integer, and @code{Q} is for an unsigned one.  The value is
returned in Python's long integer type.  (Contributed by Tim Peters.)

@item 
インタプリタの対話モードに新たに @ref{ad4,,help()} ビルトインが追加されています。これは Python 2.1 で導入された @ref{ba,,pydoc} モジュールを用いて対話的なヘルプを提供します。 @code{help(object)} で `object' について手に入る任意のヘルプを表示します。 @ref{ad4,,help()} を引数なしで起動するとオンラインのヘルプユーティリティに入ります。ここから関数名やクラス名、モジュール名をタイプすることで、それらのヘルプテキストを読むことが出来ます。 (Contributed by Guido van Rossum, using Ka-Ping Yee's @ref{ba,,pydoc} module.)

@item 
Various bugfixes and performance improvements have been made to the SRE engine
underlying the @ref{be,,re} module.  For example, the @ref{5a3,,re.sub()} and
@ref{5a2,,re.split()} functions have been rewritten in C.  Another contributed patch
speeds up certain Unicode character ranges by a factor of two, and a new
@ref{1713,,finditer()}  method that returns an iterator over all the non-overlapping
matches in  a given string.  (SRE is maintained by Fredrik Lundh.  The
BIGCHARSET patch was contributed by Martin von Löwis.)

@item 
@ref{cf,,smtplib} モジュールに 
@geindex RFC; RFC 2487
RFC 2487@footnote{https://datatracker.ietf.org/doc/html/rfc2487.html} 「Secure SMTP over TLS」のサポートが追加されました。これにより Python プログラムとメール転送エージェント間でのメッセージの暗号化された SMTP トラフィックが可能になりました。 @ref{cf,,smtplib} は SMTP 認証もサポートしています。 (Contributed by Gerhard Häring.)

@item 
Piers Lauder によって保守されている @ref{78,,imaplib} モジュールに新たに多くの拡張のサポートが追加されました: 
@geindex RFC; RFC 2342
RFC 2342@footnote{https://datatracker.ietf.org/doc/html/rfc2342.html} で定義されている NAMESPACE 拡張、 SORT、 GETACL、 SETACL。(Contributed by Anthony Baxter and Michel Pelletier.)

@item 
The @code{rfc822} module's parsing of email addresses is now compliant with
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html}, an update to 
@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html}.  (The module's name is `not' going to be
changed to @code{rfc2822}.)  A new package, @ref{3f,,email}, has also been added for
parsing and generating e-mail messages.  (Contributed by Barry Warsaw, and
arising out of his work on Mailman.)

@item 
The @ref{3b,,difflib} module now contains a new @code{Differ} class for
producing human-readable lists of changes (a "delta") between two sequences of
lines of text.  There are also two generator functions, @code{ndiff()} and
@code{restore()}, which respectively return a delta from two sequences, or one of
the original sequences from a delta. (Grunt work contributed by David Goodger,
from ndiff.py code by Tim Peters who then did the generatorization.)

@item 
New constants @code{ascii_letters}, @code{ascii_lowercase}, and
@code{ascii_uppercase} were added to the @ref{d8,,string} module.  There were
several modules in the standard library that used @code{string.letters} to
mean the ranges A-Za-z, but that assumption is incorrect when locales are in
use, because @code{string.letters} varies depending on the set of legal
characters defined by the current locale.  The buggy modules have all been fixed
to use @code{ascii_letters} instead. (Reported by an unknown person; fixed by
Fred L. Drake, Jr.)

@item 
The @ref{93,,mimetypes} module now makes it easier to use alternative MIME-type
databases by the addition of a @ref{1714,,MimeTypes} class, which takes a list of
filenames to be parsed.  (Contributed by Fred L. Drake, Jr.)

@item 
A @ref{1371,,Timer} class was added to the @ref{f3,,threading} module that allows
scheduling an activity to happen at some future time.  (Contributed by Itamar
Shtull-Trauring.)
@end itemize

@c ======================================================================

@node インタプリタの変更と修正,その他の変更と修正<3>,新しいモジュールと改良されたモジュール<3>,What's New in Python 2 2
@anchor{whatsnew/2 2 interpreter-changes-and-fixes}@anchor{1715}
@subsection インタプリタの変更と修正


Python 拡張モジュールを書いたり、インタプリタの埋め込みをしたり、あるいは単にインタプリタそのものをハックしたりするために C レベルでインタプリタを扱う人々以外には影響しないいくつかの変更があります。Python コードを書くだけであればここに記述する変更は、あなたに関係するものは全くありません。


@itemize *

@item 
プロファイルとトレースの関数が C で実装されました。Python ベースのものと比較して圧倒的に高速に操作出来、プロファイルとトレースのオーバヘッドを削減するはずです。これは Python の開発環境の著者に朗報でしょう。2 つの C 関数、 @ref{1716,,PyEval_SetProfile()} と @ref{663,,PyEval_SetTrace()} が Python API に追加されました。既存の @ref{1717,,sys.setprofile()} 関数、 @ref{2e1,,sys.settrace()} 関数はそのまま存在し、単純に新規 C レベル関数を使うように修正されました。 (Contributed by Fred L. Drake, Jr.)

@item 
Another low-level API, primarily of interest to implementers of Python
debuggers and development tools, was added. @ref{1718,,PyInterpreterState_Head()} and
@ref{1719,,PyInterpreterState_Next()} let a caller walk through all the existing
interpreter objects; @ref{171a,,PyInterpreterState_ThreadHead()} and
@ref{171b,,PyThreadState_Next()} allow looping over all the thread states for a given
interpreter.  (Contributed by David Beazley.)

@item 
ガーベージコレクタの C レベルインターフェイスが変更されています。これはガーベージコレクションをサポートする拡張型を書いたり、関数の利用誤りのデバッグをするのを簡単にします。多数の関数が少々これまでとは異なったセマンティクスを持つので、関数群がリネームされました。旧 API を使う拡張はこれまで通りコンパイルは出来ますが、ガーベージコレクションには参加 `出来ません' 。このため 2.2 のためにはかなり高優先度で更新を検討すべきです。

拡張モジュールを新 API でアップグレードするには、以下のステップを実施してください:

@item 
Rename @code{Py_TPFLAGS_GC} to @ref{981,,Py_TPFLAGS_HAVE_GC}.

@item 

@table @asis

@item オブジェクトのアロケートには @ref{c99,,PyObject_GC_New()} または @ref{c9a,,PyObject_GC_NewVar()} を使ってください。

そしてオブジェクトのデアロケートには @ref{171c,,PyObject_GC_Del()} を使ってください。
@end table

@item 
Rename @code{PyObject_GC_Init()} to @ref{171d,,PyObject_GC_Track()} and
@code{PyObject_GC_Fini()} to @ref{171e,,PyObject_GC_UnTrack()}.

@item 
Remove @code{PyGC_HEAD_SIZE} from object size calculations.

@item 
Remove calls to @code{PyObject_AS_GC()} and @code{PyObject_FROM_GC()}.

@item 
@ref{3c1,,PyArg_ParseTuple()} に新たな書式化シーケンス @code{et} が追加されました。 @code{et} はパラメータとエンコーディング名の両方を取りパラメータを与えられたエンコーディングで変換しますが、パラメータが Unicode である場合には変換し、8 ビット文字列である場合にはこれが既に望みのものであることと仮定してそのままにします。このことは @code{es} 書式化文字が 8 ビット文字列は Python デフォルトの ASCII エンコーディングであると仮定して新たに与えられたエンコーディングで変換するのとは違っています。 (Contributed by M.-A. Lemburg, and used for the MBCS support on Windows described in the following section.)

@item 
A different argument parsing function, @ref{171f,,PyArg_UnpackTuple()}, has been
added that's simpler and presumably faster.  Instead of specifying a format
string, the caller simply gives the minimum and maximum number of arguments
expected, and a set of pointers to @ref{5df,,PyObject}* variables that will be
filled in with argument values.

@item 
Two new flags @ref{16ed,,METH_NOARGS} and @ref{1720,,METH_O} are available in method
definition tables to simplify implementation of methods with no arguments or a
single untyped argument. Calling such methods is more efficient than calling a
corresponding method that uses @ref{1721,,METH_VARARGS}.  Also, the old
@code{METH_OLDARGS} style of writing C methods is  now officially deprecated.

@item 
Two new wrapper functions, @ref{1722,,PyOS_snprintf()} and @ref{1723,,PyOS_vsnprintf()}
were added to provide  cross-platform implementations for the relatively new
@code{snprintf()} and @code{vsnprintf()} C lib APIs. In contrast to the standard
@code{sprintf()} and @code{vsprintf()} functions, the Python versions check the
bounds of the buffer used to protect against buffer overruns. (Contributed by
M.-A. Lemburg.)

@item 
@ref{1724,,_PyTuple_Resize()} 関数の未使用パラメータを取り除いたので、今後は 3 つではなく 2 つのパラメータを取ります。3 つ目の引数は一度も使われることはなかったため、Python 2.2 以前のコードからの移植時には単純に捨てることが出来ます。
@end itemize

@c ======================================================================

@node その他の変更と修正<3>,謝辞<6>,インタプリタの変更と修正,What's New in Python 2 2
@anchor{whatsnew/2 2 other-changes-and-fixes}@anchor{1725}
@subsection その他の変更と修正


いつものように、たくさんのほかの改善とバグフィックスがソースツリー全体に渡って散らばっています。CVS 変更ログを検索すると、Python 2.1 から 2.2 にかけて適用されたパッチは 527、バグ修正は 683、2.2.1 で適用されたパッチは 139、バグ修正は 143、2.2.2 で適用されたパッチは 106、バグ修正は 82。いずれも少なく見積もって、です。

ほかの、さらに特筆すべき変更のいくつかを挙げます:


@itemize *

@item 
The code for the MacOS port for Python, maintained by Jack Jansen, is now kept
in the main Python CVS tree, and many changes have been made to support MacOS X.

The most significant change is the ability to build Python as a framework,
enabled by supplying the @code{--enable-framework} option to the configure
script when compiling Python.  According to Jack Jansen, "This installs a
self-contained Python installation plus the OS X framework "glue" into
@code{/Library/Frameworks/Python.framework} (or another location of choice).
For now there is little immediate added benefit to this (actually, there is the
disadvantage that you have to change your PATH to be able to find Python), but
it is the basis for creating a full-blown Python application, porting the
MacPython IDE, possibly using Python as a standard OSA scripting language and
much more."

Most of the MacPython toolbox modules, which interface to MacOS APIs such as
windowing, QuickTime, scripting, etc. have been ported to OS X, but they've been
left commented out in @code{setup.py}.  People who want to experiment with
these modules can uncomment them manually.

@c Jack's original comments:
@c The main change is the possibility to build Python as a
@c framework. This installs a self-contained Python installation plus the
@c OSX framework "glue" into /Library/Frameworks/Python.framework (or
@c another location of choice). For now there is little immediate added
@c benefit to this (actually, there is the disadvantage that you have to
@c change your PATH to be able to find Python), but it is the basis for
@c creating a fullblown Python application, porting the MacPython IDE,
@c possibly using Python as a standard OSA scripting language and much
@c more. You enable this with "configure --enable-framework".
@c The other change is that most MacPython toolbox modules, which
@c interface to all the MacOS APIs such as windowing, quicktime,
@c scripting, etc. have been ported. Again, most of these are not of
@c immediate use, as they need a full application to be really useful, so
@c they have been commented out in setup.py. People wanting to experiment
@c can uncomment them. Gestalt and Internet Config modules are enabled by
@c default.

@item 
キーワード引数を取らないビルトイン関数にそれを渡すと、メッセージ "`function' takes no keyword arguments" を伴う @ref{198,,TypeError} 例外を励起するようになりました。

@item 
Python 2.1 で拡張モジュールとして追加された弱参照は、今では Python 中核の一部です。これは新スタイルクラスの実装のために使われるからです。このため @ref{11a,,weakref} モジュールにいた @ref{1726,,ReferenceError} 例外をビルトイン例外に移動しました。

@item 
Tim Peters による新しいスクリプト @code{Tools/scripts/cleanfuture.py} は、Python ソースコードから自動的に廃止された @code{__future__} 文を削除します。

@item 
ビルトイン関数 @ref{4b1,,compile()} に `flags' 引数が追加され、これにより @code{__future__} ステートメントの振る舞いが、IDLE 内やほかの開発環境内にある模擬的なシェル内で正しく準拠するようになりました。この変更は 
@geindex Python Enhancement Proposals; PEP 264
PEP 264@footnote{https://peps.python.org/pep-0264/} に記述されています。 (Contributed by Michael Hudson.)

@item 
Python 1.6 で導入された新ライセンスは GPL 互換ではありませんでした。2.2 ライセンスのためにいくつか小さな字句的修正によりこれをフィックスし、GPL プログラム内に Python を埋め込むことが再び合法になりました。Python そのものは GPL ではなく、かつても今後も BSD ライセンスに本質的に等価なものであることに注意してください。このライセンスの変更は Python 2.0.1 リリース、2.1.1 リリースにも適用されました。

@item 
Windows において Unicode ファイル名がある場合に、Python はそれを Microsoft ファイル API を使うことで MBCS 文字列に変換するようになりました。MBCS はそのファイル API によって明示的に使われるので、デフォルトのエンコーディングとして Python が ASCII を選択するのは苛立たしいことがわかりました。Unix においては @code{locale.nl_langinfo(CODESET)} が利用可能であればロケールの文字セットが使われます。 (Windows support was contributed by Mark Hammond with assistance from Marc-André Lemburg. Unix support was added by Martin von Löwis.)

@item 
Windows でのラージファイルのサポートが有効になりました。  (Contributed by Tim Peters.)

@item 
@code{Tools/scripts/ftpmirror.py} スクリプトが、もしあれば、 @code{.netrc} ファイルを読むようになりました。 (Contributed by Mike Romberg.)

@item 
Some features of the object returned by the @code{xrange()} function are now
deprecated, and trigger warnings when they're accessed; they'll disappear in
Python 2.3. @code{xrange} objects tried to pretend they were full sequence
types by supporting slicing, sequence multiplication, and the @ref{34b,,in}
operator, but these features were rarely used and therefore buggy.  The
@code{tolist()} method and the @code{start}, @code{stop}, and @code{step}
attributes are also being deprecated.  At the C level, the fourth argument to
the @code{PyRange_New()} function, @code{repeat}, has also been deprecated.

@item 
辞書実装に対するパッチの束がありました。ほとんどが、辞書にこっそりとそのハッシュ値を変更するオブジェクトを含んでいたり、それが含まれる辞書を変更する場合に潜在的にコアダンプしていたことに対する修正です。Michael Hudson がコアダンプするケースを見つけて python-dev に穏やかなリズムで報告している間に Tim Peters がバグをフィックスし、 Michael がまた別のケースを見つけ、ということを繰り返しました。

@item 
On Windows, Python can now be compiled with Borland C thanks to a number of
patches contributed by Stephen Hansen, though the result isn't fully functional
yet.  (But this `is' progress...)

@item 
Another Windows enhancement: Wise Solutions generously offered PythonLabs use
of their InstallerMaster 8.1 system.  Earlier PythonLabs Windows installers used
Wise 5.0a, which was beginning to show its age.  (Packaged up by Tim Peters.)

@item 
ファイル名が @code{.pyw} で終わるものが Windows でインポート出来るようになりました。 @code{.pyw} は Windows のみのものであり、スクリプトが PYTHON.EXE ではなく PYTHONW.EXE を使って実行されることを示すのに使われます。これは出力のために DOS コンソールがポップアップしてしまうのを避けるのに使われます。このパッチはそのようなスクリプトを、それがモジュールとしても利用可能であるケースでインポート出来るようにします。 (Implemented by David Bolen.)

@item 
Python が C の @code{dlopen()} 関数を拡張モジュールのロードに用いるプラットフォームにおいて、 @code{dlopen()} で使われるフラグを @ref{1727,,sys.getdlopenflags()} 関数と @ref{1337,,sys.setdlopenflags()} 関数でセット出来るようになりました。 (Contributed by Bram Stolk.)

@item 
The @ref{1a4,,pow()} built-in function no longer supports 3 arguments when
floating-point numbers are supplied. @code{pow(x, y, z)} returns @code{(x**y) % z},
but this is never useful for floating-point numbers, and the final result varies
unpredictably depending on the platform.  A call such as @code{pow(2.0, 8.0, 7.0)}
will now raise a @ref{198,,TypeError} exception.
@end itemize

@c ======================================================================

@node 謝辞<6>,,その他の変更と修正<3>,What's New in Python 2 2
@anchor{whatsnew/2 2 acknowledgements}@anchor{1728}
@subsection 謝辞


著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の人々に感謝します:  Fred Bremmer, Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David Goodger, Mark Hammond, Stephen Hansen, Michael Hudson, Jack Jansen, Marc-André Lemburg, Martin von Löwis, Fredrik Lundh, Michael McLay, Nick Mathewson, Paul Moore, Gustavo Niemeyer, Don O'Donnell, Joonas Paalasma, Tim Peters, Jens Quade, Tom Reinhardt, Neil Schemenauer, Guido van Rossum, Greg Ward, Edward Welbourne.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 1,What's New in Python 2 0,What's New in Python 2 2,What's New in Python
@anchor{whatsnew/2 1 doc}@anchor{1729}@anchor{whatsnew/2 1 translation-repo}@anchor{172a}@anchor{whatsnew/2 1 what-s-new-in-python-2-1}@anchor{172b}
@section What's New in Python 2.1


@*著者: 
A.M. Kuchling


@c $Id: whatsnew21.tex 50964 2006-07-30 03:03:43Z fred.drake $

@menu
* はじめに: はじめに<2>. 
* PEP 227; 入れ子状のスコープ: PEP 227 入れ子状のスコープ<2>. 
* PEP 236; __future__ 指示文: PEP 236 __future__ 指示文. 
* PEP 207; 拡張比較: PEP 207 拡張比較. 
* PEP 230; 警告フレームワーク: PEP 230 警告フレームワーク. 
* PEP 229; 新しいビルドシステム: PEP 229 新しいビルドシステム. 
* PEP 205; 弱参照: PEP 205 弱参照. 
* PEP 232; 関数の属性: PEP 232 関数の属性. 
* PEP 235; 大文字小文字を区別しないプラットフォームでのモジュールの読み込み: PEP 235 大文字小文字を区別しないプラットフォームでのモジュールの読み込み. 
* PEP 217; 対話モード用 Display Hook: PEP 217 対話モード用 Display Hook. 
* PEP 208; 新しい型強制モデル: PEP 208 新しい型強制モデル. 
* PEP 241; Pythonソフトウェアパッケージのためのメタデータ: PEP 241 Pythonソフトウェアパッケージのためのメタデータ. 
* 新しいモジュールと改良されたモジュール: 新しいモジュールと改良されたモジュール<4>. 
* その他の変更と修正: その他の変更と修正<4>. 
* 謝辞: 謝辞<7>. 

@end menu

@node はじめに<2>,PEP 227 入れ子状のスコープ<2>,,What's New in Python 2 1
@anchor{whatsnew/2 1 introduction}@anchor{172c}
@subsection はじめに


この記事はPython 2.1の新機能について説明します。Python 2.1には Python 2.0ほど多くの変更点はありませんが、楽しい驚きがあります。2.1はPythonの拡張計画（PEP）を使い動かす最初のリリースであり、大きい変更点のほとんどは、より詳細なドキュメントや変更のための設計原理を提供するPEPに付随しています。この記事は新機能について網羅していませんが、Pythonプログラマのための新機能について概要を示します。特に興味のある任意の新機能の詳細については、Python 2.1ドキュメントか特定のPEPを参照してください。

Python開発チームの最近の目標の一つとして新しいリリースのペースを上げており、一つのリリースにつき6～9ヶ月ごとにリリースしています。2.1はこの速いペースになって出てきた最初のリリースで、初のアルファ版は、2.0の最終版がリリースされた3ヶ月後の1月に登場しました。

Python 2.1の最終版は2001年4月17日に作成されました。

@c ======================================================================

@node PEP 227 入れ子状のスコープ<2>,PEP 236 __future__ 指示文,はじめに<2>,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-227-nested-scopes}@anchor{172d}
@subsection PEP 227: 入れ子状のスコープ


Python2.1における最も大きな変更点はPythonのスコープルールです。Python2.0では、ある指定された時点である変数の名前を検索するために多くても3つの名前空間、つまりローカル、モジュールレベル、ビルトイン名前空間しか使われませんでした。このことは直感的な期待と一致せずしばしば人々を驚かせました。例えば、入れ子になった再帰関数の定義は動きません:

@example
def f():
    ...
    def g(value):
        ...
        return g(value-1) + 1
    ...
@end example

The function @code{g()} will always raise a @ref{452,,NameError} exception, because
the binding of the name @code{g} isn't in either its local namespace or in the
module-level namespace.  This isn't much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the @ref{14b5,,lambda} expression clumsier, and this was a problem in practice.
In code which uses @ref{14b5,,lambda} you can often find local variables being
copied by passing them as the default values of arguments.

@example
def find(self, name):
    "Return list of any entries equal to 'name'"
    L = filter(lambda x, name=name: x == name,
               self.list_attribute)
    return L
@end example

過度な関数型スタイルで書かれた Python コードの可読性は、結果的にはひどく苦痛を感じるものですね。

Python 2.1の最も重要な変更点は、この問題を解決するために静的なスコープが追加されたことです。最初の効果として、@code{name=name} という例ではデフォルトの引数は必要ありません。簡単に言えば、指定された引数名が関数内の値に割り当てられない場合(@ref{1673,,def}、@ref{14ef,,class} または @ref{7f8,,import} ステートメントの割り当てによって)、変数の参照は外側のスコープのローカル名前空間で検索されます。ルールや実装の詳細はPEPで参照できます。

この変更は、同じ変数名がモジュールレベルと関数の定義が含まれている関数内のローカルの両方で変数名として使用されているコードで、互換性の問題を引き起こす可能性があります。ですがむしろ気にしなくてよいでしょう。そのようなコードはそもそも最初から相当こんがらかっているので。

この変更の副作用の一つは、 @code{from module import *} と @code{exec} の両ステートメントが特定の条件下の関数スコープ内で不正となることです。 Python のリファレンスマニュアルははじめからずっと @code{from module import *} はトップレベルモジュールでのみ合法であると言ってきましたが、以前の CPython インタプリタはこれを一度も強制していませんでした。入れ子になったスコープ実装の一環として、Python のソースをバイトコードに変換するコンパイラは、内包されたスコープ内の変数にアクセスするために別のコードを生成する必要があります。 @code{from module import *}, @code{exec} はコンパイラにこれを理解することを不可能にしてしまいます。なぜならそれらはコンパイル時にはわからないローカル名前空間に名前を追加するからです。それゆえ、もし関数が関数定義を含んだり自由な変数に @ref{14b5,,lambda} の語句を含んだりする場合、コンパイラは @ref{18e,,SyntaxError} 例外を上げて知らせます。

前述した説明を少し明確にするため、例を挙げます:

@example
x = 1
def f():
    # The next line is a syntax error
    exec 'x=2'
    def g():
        return x
@end example

Line 4 containing the @code{exec} statement is a syntax error, since
@code{exec} would define a new local variable named @code{x} whose value should
be accessed by @code{g()}.

これは実際には大した制約でもないはずです。 @code{exec} が Python コードで使われるのは稀です(使われているとしたら大抵どこか貧弱な設計であることの証)。

互換性の問題が考慮されて、入れ子のスコープは段階的導入につながりました; Python 2.1 ではそれらはデフォルトで有効になっていませんが、 
@geindex Python Enhancement Proposals; PEP 236
PEP 236@footnote{https://peps.python.org/pep-0236/} に記載されているように、future 文を使用してモジュール内でオンにすることができます。(
@geindex Python Enhancement Proposals; PEP 236
PEP 236@footnote{https://peps.python.org/pep-0236/} の更なる議論について、続くセクションを参照してください。) Python 2.2では入れ子になったスコープがデフォルトになり、それをオフにする方法はありませんが、ユーザは 2.1 の全ライフタイムを通して、導入の結果起きるあらゆる破損を修正し続けるでしょう。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 227

@item PEP 227@footnote{https://peps.python.org/pep-0227/} - 静的に入れ子になったスコープ

Jeremy Hylton著、実装
@end table


@c ======================================================================

@node PEP 236 __future__ 指示文,PEP 207 拡張比較,PEP 227 入れ子状のスコープ<2>,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-236-future-directives}@anchor{172e}
@subsection PEP 236: __future__ 指示文


ネストされたスコープへのこの対応は、リリース 2.1 ではコードを壊すことの危険性について広く懸念されており、  Pythoneer 達に保守的なアプローチを選ばせるには十分でした。このアプローチは、必須とするリリース N+1 に対する、 リリース N でのオプション機能として有効化という序奏、というものです。

この構文は @ref{0,,__future__} という名の予約モジュールを使う @code{from...import} ステートメントを使用します。ネストしたスコープは以下のステートメントで有効にできます。

@example
from __future__ import nested_scopes
@end example

普通 の @ref{7f8,,import} ステートメントに見えますが、実は違います; このような未来のステートメントが置かれる場所には厳格なルールがあります。これらはモジュールの冒頭にしか置けませんし、必ず何らかのPythonコードや正規の @code{import} ステートメントの前になければなりません。それと言うのもこのようなステートメントは、Pythonのバイトコードコンパイラがコードを解析し、バイトコードを生成する方法に影響しますので、生成されるバイトコードとなるステートメントの前になくてはならないのです。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 236

@item PEP 236@footnote{https://peps.python.org/pep-0236/} - バック・トゥ・ザ・ @ref{0,,__future__}

Tim Peter著、Jeremy Hylton主実装
@end table


@c ======================================================================

@node PEP 207 拡張比較,PEP 230 警告フレームワーク,PEP 236 __future__ 指示文,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-207-rich-comparisons}@anchor{172f}
@subsection PEP 207: 拡張比較


In earlier versions, Python's support for implementing comparisons on user-defined
classes and extension types was quite simple. Classes could implement a
@code{__cmp__()} method that was given two instances of a class, and could only
return 0 if they were equal or +1 or -1 if they weren't; the method couldn't
raise an exception or return anything other than a Boolean value.  Users of
Numeric Python often found this model too weak and restrictive, because in the
number-crunching programs that numeric Python is used for, it would be more
useful to be able to perform elementwise comparisons of two matrices, returning
a matrix containing the results of a given comparison for each element.  If the
two matrices are of different sizes, then the compare has to be able to raise an
exception to signal the error.

Python2.1で、このニーズを満たすために拡張比較が追加されました。Pythonのクラスは、@code{<}、@code{<=}、@code{>}、@code{>=}、@code{==}、@code{!=} の各演算を個別にオーバーロードできます。この新しい特殊メソッドの名前は:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

メソッド名

@item

@code{<}

@tab

@ref{14b8,,__lt__()}

@item

@code{<=}

@tab

@ref{1522,,__le__()}

@item

@code{>}

@tab

@ref{1523,,__gt__()}

@item

@code{>=}

@tab

@ref{1524,,__ge__()}

@item

@code{==}

@tab

@ref{cf2,,__eq__()}

@item

@code{!=}

@tab

@ref{1730,,__ne__()}

@end multitable


(特殊メソッドはFortranの @code{.LT.} や @code{.LE.} 等々の演算子にちなんで命名されています。プログラマはほぼ確実にこれらの名前を熟知していますので、覚えやすいでしょう。)

これらの特殊メソッドは @code{method(self, other)} の形式になっており、@code{self} が演算子の左辺、@code{other} が右辺のオブジェクトになります。例えば、式 @code{A < B} は @code{A.__lt__(B)} を呼び出します。

これらの特殊メソッドは何でも、つまり真偽値や行列、リストや他のPython オブジェクトを返せます。もし比較が不可能であったり、矛盾していたり、意味がない場合は、代わりに例外を上げることができます。

The built-in @code{cmp(A,B)} function can use the rich comparison machinery,
and now accepts an optional argument specifying which comparison operation to
use; this is given as one of the strings @code{"<"}, @code{"<="}, @code{">"}, @code{">="},
@code{"=="}, or @code{"!="}.  If called without the optional third argument,
@code{cmp()} will only return -1, 0, or +1 as in previous versions of Python;
otherwise it will call the appropriate method and can return any Python object.

C プログラマにとって興味深い関連する変更があります。型オブジェクトに新しい @code{tp_richcmp} スロットと、この拡張された比較を行うAPIが追加されました。ここではC APIについて言及しませんが、あながた関連する関数のリストを見たければ、 
@geindex Python Enhancement Proposals; PEP 207
PEP 207@footnote{https://peps.python.org/pep-0207/} かバージョン2.1のC APIドキュメントを参照してください。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 207

@item PEP 207@footnote{https://peps.python.org/pep-0207/}: 拡張比較

David Ascher によるかつての仕事に大きく拠りますが  Guido van Rossum によって著され、実装されました。
@end table


@c ======================================================================

@node PEP 230 警告フレームワーク,PEP 229 新しいビルドシステム,PEP 207 拡張比較,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-230-warning-framework}@anchor{1731}
@subsection PEP 230: 警告フレームワーク


10 年の間に、Python は途中で廃止されたモジュールと機能の特定の番号を蓄積してきました。どれだけのコードが活用されているか知る術はないので、機能を削除して問題ないか把握することは困難です。その機能に依存するプログラムは一つもないかもしれませんし、たくさんあるかもしれません。より構造化された方法で古い機能を削除できるようにするために、警告のフレームワークが追加されました。Python の開発者がある機能を取り除きたいときは、まずは Python の次のバージョンで警告を引き起こします。続く Python バージョンで開発者はその機能を削除出来、ユーザは古い機能の使用を取り除くために Python リリースサイクル一つ丸々使えます。

Python 2.1 はこのスキームで使われる警告フレームワークを追加します。また、警告の表示機能や表示させたくない警告を除外する機能を提供する、 @ref{118,,warnings} モジュールを追加します。サードパーティーのモジュールはまた、彼らがサポート対象外にしたい古い機能を非推奨と知らしめるのにこのフレームワークを利用できます。

For example, in Python 2.1 the @code{regex} module is deprecated, so importing
it causes a warning to be printed:

@example
>>> import regex
__main__:1: DeprecationWarning: the regex module
         is deprecated; please use the re module
>>>
@end example

警告は @ref{1732,,warnings.warn()} 関数を呼び出すことで発行できます:

@example
warnings.warn("feature X no longer supported")
@end example

最初のパラメータは警告メッセージです。任意追加のパラメータは、特定の警告カテゴリを指定するために利用することができます。

Filters can be added to disable certain warnings; a regular expression pattern
can be applied to the message or to the module name in order to suppress a
warning.  For example, you may have a program that uses the @code{regex} module
and not want to spare the time to convert it to use the @ref{be,,re} module right
now.  The warning can be suppressed by calling

@example
import warnings
warnings.filterwarnings(action = 'ignore',
                        message='.*regex module is deprecated',
                        category=DeprecationWarning,
                        module = '__main__')
@end example

This adds a filter that will apply only to warnings of the class
@ref{1a3,,DeprecationWarning} triggered in the @ref{1,,__main__} module, and applies
a regular expression to only match the message about the @code{regex} module
being deprecated, and will cause such warnings to be ignored.  Warnings can also
be printed only once, printed every time the offending code is executed, or
turned into exceptions that will cause the program to stop (unless the
exceptions are caught in the usual way, of course).

関数は、警告を発行するための Python の C API にも追加されました。詳細については PEP 230 または Python の API ドキュメントを参照してください。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 5

@item PEP 5@footnote{https://peps.python.org/pep-0005/} - 言語の進化のためのガイドライン

Python から古い機能を削除する時に従うべき手順を示すため、 Paul Prescod により書かれました。当 PEP に記載された方針は正式に採用されていませんが、最終的な方針も Prescod の提案とおそらくさほど違いはないでしょう。

@geindex Python Enhancement Proposals; PEP 230

@item PEP 230@footnote{https://peps.python.org/pep-0230/} - 警告フレームワーク

Guido van Rossum 著、実装
@end table


@c ======================================================================

@node PEP 229 新しいビルドシステム,PEP 205 弱参照,PEP 230 警告フレームワーク,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-229-new-build-system}@anchor{1733}
@subsection PEP 229: 新しいビルドシステム


Python のコンパイル時、ユーザはソースツリーの中に入って、様々な追加モジュールを有効にするために @code{Modules/Setup} ファイルを編集しなければなりませんでした; デフォルトのセットは比較的小さくて、ほとんどの Unix プラットフォームで、コンパイルするモジュールを制限しています。これは、特に Linux に顕著ですが、たくさんの追加機能を持った Unix プラットフォームでは、Python インストレーションはしばしば、そう出来るのに有用なモジュールを全く含まない、といったことが起こることを意味しています。

Python 2.0 は、配布と拡張のインストールをするためのモジュールのセットである Distutils を追加しました。Python 2.1 では Distutils を、たくさんの拡張モジュールの標準ライブラリを、サポートする機器かどうかを自動検出してコンパイルするのに使っています。これが Python インストレーションをより簡単に、より機能的とするものであることが期待されています。

モジュールを有効化するために @code{Modules/Setup} を編集する必要性の代わりに、Python ソースツリーのトップレベルディレクトリにある @code{setup.py} スクリプトがビルド時に実行され、システムのモジュールとヘッダファイルを調べることによって、どのモジュールが有効に出来るのかを検出しようと試みます。モジュールが @code{Modules/Setup} 内でそう構成されていれば、 @code{setup.py} スクリプトはそのモジュールをコンパイルしようとはせずに @code{Modules/Setup} ファイル内容に従います。これは特定のプラットフォームで必要となるヘンチクリンなコマンドラインフラグやライブラリフラグを特定する手段も与えてくれます。

もう一つの大きなビルド機構の変更点は Neil Schemenauer による再構成で、今や Python は、トップディレクトリと @code{Python/}, @code{Parser/}, @code{Objects/}, @code{Modules/} サブディレクトリにあった別々の Makefile が再帰的にビルドする代わりに、再帰をしないトップレベルの単一 makefile を使うようになっています。このことで Python のビルドは速くなり、 Makefile をもてあそぶのが単純明快になっています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 229

@item PEP 229@footnote{https://peps.python.org/pep-0229/} - Distutils を使った Python のビルド

A.M. Kuchling 著、実装
@end table


@c ======================================================================

@node PEP 205 弱参照,PEP 232 関数の属性,PEP 229 新しいビルドシステム,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-205-weak-references}@anchor{1734}
@subsection PEP 205: 弱参照


@ref{11a,,weakref} モジュールを通して利用出来る弱参照(weak references)は、ささやかですが有用な、Python プログラマの道具箱に新たに加わったデータ型です。

オブジェクトへの参照(辞書内やリスト内を思い浮かべてください)を記憶しておくということは、オブジェクトを生き永らえさせるという副作用を持っています。少しばかりの、この振る舞いが望ましくない特殊なケースがあります。オブジェクトのキャッシュがその最もありがちな一つで、もう一つはツリーのようなデータ構造での循環参照です。

例えば、他の関数 @code{f(x)} の結果を、その関数の引数と結果を辞書に格納することでキャッシュするメモライジング関数を考えてみましょう。

@example
_cache = @{@}
def memoize(x):
    if _cache.has_key(x):
        return _cache[x]

    retval = f(x)

    # Cache the returned object
    _cache[x] = retval

    return retval
@end example

This version works for simple things such as integers, but it has a side effect;
the @code{_cache} dictionary holds a reference to the return values, so they'll
never be deallocated until the Python process exits and cleans up. This isn't
very noticeable for integers, but if @code{f()} returns an object, or a data
structure that takes up a lot of memory, this can be a problem.

弱参照は、オブジェクトをその時間を超えて生き永らえさせたくないキャッシュの実装のための手段を提供します。オブジェクトがアクセス出来るのが弱参照からのみである場合、そのオブジェクトは解放されて、その弱参照は参照しているそのオブジェクトがもはや存在しないことを表明します。オブジェクト `obj' への弱参照を作るには、 @code{wr = weakref.ref(obj)} とします。参照されているオブジェクトは、それがあたかも関数であったかのように弱参照を「コール」することで得ます: @code{wr()} 。それは参照されたオブジェクトを返すか、もう存在していないのであれば @code{None} を返します。

This makes it possible to write a @code{memoize()} function whose cache doesn't
keep objects alive, by storing weak references in the cache.

@example
_cache = @{@}
def memoize(x):
    if _cache.has_key(x):
        obj = _cache[x]()
        # If weak reference object still exists,
        # return it
        if obj is not None: return obj

    retval = f(x)

    # Cache a weak reference
    _cache[x] = weakref.ref(retval)

    return retval
@end example

The @ref{11a,,weakref} module also allows creating proxy objects which behave like
weak references --- an object referenced only by proxy objects is deallocated --
but instead of requiring an explicit call to retrieve the object, the proxy
transparently forwards all operations to the object as long as the object still
exists.  If the object is deallocated, attempting to use a proxy will cause a
@code{weakref.ReferenceError} exception to be raised.

@example
proxy = weakref.proxy(obj)
proxy.attr   # Equivalent to obj.attr
proxy.meth() # Equivalent to obj.meth()
del obj
proxy.attr   # raises weakref.ReferenceError
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 205

@item PEP 205@footnote{https://peps.python.org/pep-0205/} - 弱参照

Fred L. Drake, Jr. 著、実装
@end table


@c ======================================================================

@node PEP 232 関数の属性,PEP 235 大文字小文字を区別しないプラットフォームでのモジュールの読み込み,PEP 205 弱参照,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-232-function-attributes}@anchor{1735}
@subsection PEP 232: 関数の属性


In Python 2.1, functions can now have arbitrary information attached to them.
People were often using docstrings to hold information about functions and
methods, because the @ref{13f1,,__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.

ついに関数に、任意の属性をセットし、取り出すことが出来るようになりました。普通の Python 構文で出来ます:

@example
def f(): pass

f.publish = 1
f.secure = 1
f.grammar = "A ::= B (C D)*"
@end example

The dictionary containing attributes can be accessed as the function's
@ref{14ea,,__dict__}. Unlike the @ref{e57,,__dict__} attribute of class instances, in
functions you can actually assign a new dictionary to @ref{14ea,,__dict__}, though
the new value is restricted to a regular Python dictionary; you `can't' be
tricky and set it to a @code{UserDict} instance, or any other random object
that behaves like a mapping.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 232

@item PEP 232@footnote{https://peps.python.org/pep-0232/} - 関数の属性

Barry Warsaw 著、実装
@end table


@c ======================================================================

@node PEP 235 大文字小文字を区別しないプラットフォームでのモジュールの読み込み,PEP 217 対話モード用 Display Hook,PEP 232 関数の属性,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-235-importing-modules-on-case-insensitive-platforms}@anchor{1736}
@subsection PEP 235: 大文字小文字を区別しないプラットフォームでのモジュールの読み込み


いくつかのオペレーティングシステムは、大小文字区別に無関心なファイルシステムを持っています。MacOS と Windows がその代表例です。それらシステムにおいてはファイル名 @code{FILE.PY} と @code{file.py} の区別が出来ません。たとえそれが元のファイル名を尊重して格納出来たとしてもです(それらは大小文字維持、でもあります)。

Python 2.1 では @ref{7f8,,import} 文が、case-insensitive (大小文字に無関心)なプラットフォームで case-sensitivity (大小文字への繊細さ)をシミュレートして動作します。Python は今や、まずはデフォルトで case-sensitive なマッチによる検索をし、それで見つからなければ @ref{65b,,ImportError} を投げます。ですから @code{import file} は @code{FILE.PY} をインポートしません。case-insensitive マッチングは Python インタプリタ開始前に環境変数 
@geindex PYTHONCASEOK
@geindex 環境変数; PYTHONCASEOK
@ref{b55,,PYTHONCASEOK} をセットすることで要求出来ます。

@c ======================================================================

@node PEP 217 対話モード用 Display Hook,PEP 208 新しい型強制モデル,PEP 235 大文字小文字を区別しないプラットフォームでのモジュールの読み込み,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-217-interactive-display-hook}@anchor{1737}
@subsection PEP 217: 対話モード用 Display Hook


Python インタプリタを対話的に使う際には、コマンドの出力結果表示にはビルトインの @ref{1c1,,repr()} 関数が使われます。Python 2.1 ではこの @ref{1c1,,repr()} の代わりに呼び出される呼び出し可能オブジェクトを、 @ref{1738,,sys.displayhook()} 変数にセット出来ます。たとえば特別な pretty- printing 関数をセット出来ます:

@example
>>> # Create a recursive data structure
... L = [1,2,3]
>>> L.append(L)
>>> L # Show Python's default output
[1, 2, 3, [...]]
>>> # Use pprint.pprint() as the display function
... import sys, pprint
>>> sys.displayhook = pprint.pprint
>>> L
[1, 2, 3,  <Recursion on list with id=135143996>]
>>>
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 217

@item PEP 217@footnote{https://peps.python.org/pep-0217/} - Display Hook の対話的な使用

Moshe Zadka 著、実装
@end table


@c ======================================================================

@node PEP 208 新しい型強制モデル,PEP 241 Pythonソフトウェアパッケージのためのメタデータ,PEP 217 対話モード用 Display Hook,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-208-new-coercion-model}@anchor{1739}
@subsection PEP 208: 新しい型強制モデル


数値強制が C レベルでどのようになされるかについての修正は、とても大きなものでした。これは Python の C 拡張の著者にのみ影響し、数値操作をサポートする拡張型を書くのをより柔軟にするものです。

拡張型はその @code{PyTypeObject} 構造体に、新しい型強制モデルをサポートすることを示すために @code{Py_TPFLAGS_CHECKTYPES} フラグをセット出来るようになりました。そのような拡張型内では、数値的スロット関数は 2 つの引数が同じ型であることを仮定しなくなります。代わりに、2 つの引数が異なる型を渡せて、内部的に型変換を実行出来ます。スロット関数にそれが処理出来ない型が渡された場合は、それが失敗であることを表すために @code{Py_NotImplemented} シングルトン値への参照を返せます。この場合他の数値関数が試されて、おそらく操作を実行出来ます。それでも @code{Py_NotImplemented} を返すなら @ref{198,,TypeError} が送出されます。Python で書かれた数値メソッドも @code{Py_NotImplemented} を返せます。この場合インタプリタはメソッドが存在しないものとして振舞います。 (おそらく @ref{198,,TypeError} が投げられたり、オブジェクトのほかの数値メソッドが試されます。)


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 208

@item PEP 208@footnote{https://peps.python.org/pep-0208/} - 型強制モデルの手直し

Neil Schemenauer により著され、実装されましたが、大変多くを Marc-André Lemburg による以前の仕事に拠っています。C レベルで今では数値操作がどのように処理されるようになったかの細かい点を理解したければ、これを読んで下さい。
@end table


@c ======================================================================

@node PEP 241 Pythonソフトウェアパッケージのためのメタデータ,新しいモジュールと改良されたモジュール<4>,PEP 208 新しい型強制モデル,What's New in Python 2 1
@anchor{whatsnew/2 1 pep-241-metadata-in-python-packages}@anchor{173a}
@subsection PEP 241: Pythonソフトウェアパッケージのためのメタデータ


Python ユーザーからのよくある苦情としては、存在するすべての Python モジュールの一覧がないということです。T. Middleton's の @code{www.vex.net/parnassus/} にあった Vaults of Parnassus (2009年2月に停止、Internet Archive Wayback Machine <@indicateurl{https://web.archive.org/web/20090130140102/http://www.vex.net/parnassus/}>`_ で閲覧可) が最大のものでしたが、ソフトウェアの登録は任意だったため、多くの人は登録しませんでした。

この問題をどうにかするための最初の小さな一歩として、Distutils の @code{sdist} コマンドを使ってパッケージ化する Python ソフトウェアに @code{PKG-INFO} と名付けられたファイルを含むようにしました。これには名前、バージョン、著者 (カタログ化の用語ではメタデータ) のような情報を含んでいます。 
@geindex Python Enhancement Proposals; PEP 241
PEP 241@footnote{https://peps.python.org/pep-0241/} が @code{PKG-INFO} ファイルに持てるフィールドの完全なリストを記述しています。Python 2.1 を使ったソフトウェアをパッケージ化し始めた人々によってパッケージがどんどんメタデータを含み、自動的なカタログ化システムを構築し、それを実験することが出来るようになります。その結果の経験により、おそらく本当に良いカタログを設計出来、Python 2.2 でそのサポートを構築出来るでしょう。例えば Distutils の @code{sdist} コマンドと @code{bdist_*} コマンド群はあなたのパッケージをカタログサーバに自動的にアップロードする @code{upload} オプションをサポート出来るでしょう。

@code{PKG-INFO} を含んだパッケージの作成は Python 2.1 を使っていなくても開始することが出来ます。Distutils の新しいリリースが以前のバージョンの Python ユーザ向けにも作られているからです。Distutils のバージョン 1.0.2 が、多数のバグフィックスや拡張とともに、 
@geindex Python Enhancement Proposals; PEP 241
PEP 241@footnote{https://peps.python.org/pep-0241/} の変更を含んでいます。これは @indicateurl{https://www.python.org/community/sigs/current/distutils-sig/} にある Distutils SIG から入手可能です。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 241

@item PEP 241@footnote{https://peps.python.org/pep-0241/} - Pythonソフトウェアパッケージのためのメタデータ

A.M. Kuchling 著、実装

@geindex Python Enhancement Proposals; PEP 243

@item PEP 243@footnote{https://peps.python.org/pep-0243/} - レポジトリアップロードモジュールのメカニズム

Sean Reifschneider により著されました。このドラフト PEP は中央サーバに Python パッケージをアップロードする機構について提案しています。
@end table


@c ======================================================================

@node 新しいモジュールと改良されたモジュール<4>,その他の変更と修正<4>,PEP 241 Pythonソフトウェアパッケージのためのメタデータ,What's New in Python 2 1
@anchor{whatsnew/2 1 new-and-improved-modules}@anchor{173b}
@subsection 新しいモジュールと改良されたモジュール



@itemize *

@item 
Ka-Ping Yee contributed two new modules: @code{inspect.py}, a module for
getting information about live Python code, and @code{pydoc.py}, a module for
interactively converting docstrings to HTML or text.  As a bonus,
@code{Tools/scripts/pydoc}, which is now automatically installed, uses
@code{pydoc.py} to display documentation given a Python module, package, or
class name.  For example, @code{pydoc xml.dom} displays the following:

@example
Python Library Documentation: package xml.dom in xml

NAME
    xml.dom - W3C Document Object Model implementation for Python.

FILE
    /usr/local/lib/python2.1/xml/dom/__init__.pyc

DESCRIPTION
    The Python mapping of the Document Object Model is documented in the
    Python Library Reference in the section on the xml.dom package.

    This package contains the following modules:
      ...
@end example

@code{pydoc} には TK ベースの対話的ヘルプブラウザも含まれています。 @code{pydoc} はすぐに病みつきになります。お試しあれ。

@item 
Two different modules for unit testing were added to the standard library.
The @ref{3e,,doctest} module, contributed by Tim Peters, provides a testing
framework based on running embedded examples in docstrings and comparing the
results against the expected output.  PyUnit, contributed by Steve Purcell, is a
unit testing framework inspired by JUnit, which was in turn an adaptation of
Kent Beck's Smalltalk testing framework.  See @indicateurl{https://pyunit.sourceforge.net/} for
more information about PyUnit.

@item 
The @ref{3b,,difflib} module contains a class, @ref{121b,,SequenceMatcher}, which
compares two sequences and computes the changes required to transform one
sequence into the other.  For example, this module can be used to write a tool
similar to the Unix @code{diff} program, and in fact the sample program
@code{Tools/scripts/ndiff.py} demonstrates how to write such a script.

@item 
@ref{31,,curses.panel} はパネルライブラリへのラッパーであり、ncurses と SYSV curses の一部であり、 Thomas Gellekum により寄稿されました。パネルライブラリは深さ(depth)の追加機能を持つウィンドウを提供しています。ウィンドウは深さ順での高い方、低い方に移動出来、パネルライブラリはパネルがどこで重なるか、区域のどちらが可視かを理解します。

@item 
The PyXML package has gone through a few releases since Python 2.0, and Python
2.1 includes an updated version of the @ref{126,,xml} package.  Some of the
noteworthy changes include support for Expat 1.2 and later versions, the ability
for Expat parsers to handle files in any encoding supported by Python, and
various bugfixes for SAX, DOM, and the @code{minidom} module.

@item 
Ka-Ping Yee は未捕捉の例外を処理するもうひとつのフックも寄稿しました。 @ref{a0c,,sys.excepthook()} には呼び出し可能オブジェクトをセット出来ます。例外がどの @ref{8f8,,try}...@ref{1ab,,except} にも捕捉されない場合に、例外は @ref{a0c,,sys.excepthook()} に通されて、そこで好きなことを何でも出来ます。9 回目の Python カンファレンスにおいて、Ping はこのフックを使ったアプリケーションのデモを行いました。そこでは、スタックフレームを列挙するだけでなくそれぞれのフレームでの関数の引数とローカル変数の列挙も行う拡張トレースバックの表示をしていました。

@item 
Various functions in the @ref{f4,,time} module, such as @ref{1400,,asctime()} and
@ref{1712,,localtime()}, require a floating-point argument containing the time in
seconds since the epoch.  The most common use of these functions is to work with
the current time, so the floating-point argument has been made optional; when a
value isn't provided, the current time will be used.  For example, log file
entries usually need a string containing the current time; in Python 2.1,
@code{time.asctime()} can be used, instead of the lengthier
@code{time.asctime(time.localtime(time.time()))} that was previously required.

この変更は Thomas Wouters により提案され、実装されました。

@item 
@ref{62,,ftplib} モジュールがデフォルトでパッシブモードでファイルを取得するようになりました。これはパッシブモードがファイアウォール配下ではより良く動作するようだからです。この要望は Debian のバグトラッキングシステムから起こりました。ほかの Debian パッケージがファイル取得に @ref{62,,ftplib} を使い、ファイアウォールの元で動作しなかったのです。このことが誰かの問題になるとは思えません。Netscape のデフォルトがパッシブモードですし、苦情を言う人々も稀でした。ですがもしもパッシブモードがあなたのアプリケーションやネットワーク構成にとって不適切である場合には、FTP オブジェクトの @code{set_pasv(0)} を呼び出して、パッシブモードを無効にしてください。

@item 
@ref{d1,,socket} モジュールに、Grant Edwards により寄稿された、生のソケットへのアクセスのサポートが追加されました。

@item 
@ref{b5,,pstats} モジュールに、Python プログラムの時間計測プロファイルを表示する単純な対話的統計ブラウザが含まれるようになり、これはモジュールがスクリプトとして実行された場合に呼び出されます。Eric S. Raymond によって寄稿されました。

@item 
実装依存の関数ですが @code{sys._getframe([depth])} が、現在の呼び出しスタックより、指定したフレームオブジェクトを返すものとして追加されました。 @ref{8f0,,sys._getframe()} は呼び出しスタックの一番上のフレームを返します。オプショナルな整数引数 `depth' を与えると、関数はスタックの一番上から下 `depth' ぶんの呼び出しのフレームを返します。例えば @code{sys._getframe(1)} は呼び出し元のフレームオブジェクトを返します。

この関数は CPython のみに含まれ、 Jython や .NET 実装にはありません。デバッグのためだけに用い、製品コード内にこれを書いてしまう誘惑に打ち克ってください。
@end itemize

@c ======================================================================

@node その他の変更と修正<4>,謝辞<7>,新しいモジュールと改良されたモジュール<4>,What's New in Python 2 1
@anchor{whatsnew/2 1 other-changes-and-fixes}@anchor{173c}
@subsection その他の変更と修正


短めのリリースサイクルだったため Python 2.1 では比較的少ない変更でした。CVS 変更ログの検索では 117 のパッチ適用と 136 のバグフィックスが見つかります。ともに少なく見積もっています。いくつかの注目に値する変更を紹介します:


@itemize *

@item 
A specialized object allocator is now optionally available, that should be
faster than the system @code{malloc()} and have less memory overhead.  The
allocator uses C's @code{malloc()} function to get large pools of memory, and
then fulfills smaller memory requests from these pools.  It can be enabled by
providing the @code{--with-pymalloc} option to the @code{configure}
script; see @code{Objects/obmalloc.c} for the implementation details.

Authors of C extension modules should test their code with the object allocator
enabled, because some incorrect code may break, causing core dumps at runtime.
There are a bunch of memory allocation functions in Python's C API that have
previously been just aliases for the C library's @code{malloc()} and
@code{free()}, meaning that if you accidentally called mismatched functions, the
error wouldn't be noticeable.  When the object allocator is enabled, these
functions aren't aliases of @code{malloc()} and @code{free()} any more, and
calling the wrong function to free memory will get you a core dump.  For
example, if memory was allocated using @ref{173d,,PyMem_New}, it has to be freed
using @ref{173e,,PyMem_Del()}, not @code{free()}.  A few modules included with Python
fell afoul of this and had to be fixed; doubtless there are more third-party
modules that will have the same problem.

オブジェクトアロケータは Vladimir Marangozov により寄稿されました。

@item 
The speed of line-oriented file I/O has been improved because people often
complain about its lack of speed, and because it's often been used as a naïve
benchmark.  The @ref{bf,,readline()} method of file objects has therefore been
rewritten to be much faster.  The exact amount of the speedup will vary from
platform to platform depending on how slow the C library's @code{getc()} was, but
is around 66%, and potentially much faster on some particular operating systems.
Tim Peters did much of the benchmarking and coding for this change, motivated by
a discussion in comp.lang.python.

A new module and method for file objects was also added, contributed by Jeff
Epler. The new method, @code{xreadlines()}, is similar to the existing
@code{xrange()} built-in.  @code{xreadlines()} returns an opaque sequence object
that only supports being iterated over, reading a line on every iteration but
not reading the entire file into memory as the existing @code{readlines()} method
does. You'd use it like this:

@example
for line in sys.stdin.xreadlines():
    # ... do something for each line ...
    ...
@end example

ライン I/O の変更についての詳しい説明は、 @indicateurl{https://mail.python.org/pipermail/python-dev/2001-January/} にある 2001 年 1 月 1--15 日の python-dev のまとめをご覧ください。

@item 
A new method, @ref{173f,,popitem()}, was added to dictionaries to enable
destructively iterating through the contents of a dictionary; this can be faster
for large dictionaries because there's no need to construct a list containing
all the keys or values. @code{D.popitem()} removes a random @code{(key, value)} pair
from the dictionary @code{D} and returns it as a 2-tuple.  This was implemented
mostly by Tim Peters and Guido van Rossum, after a suggestion and preliminary
patch by Moshe Zadka.

@item 
@code{from module import *} を使ってインポートする際にインポートされる名前を制御出来るようになりました。インポートされるべき名前のリストを含む @code{__all__} 属性を定義することでこれを行えます。一つのよくある不平が、 @ref{df,,sys} や @ref{d8,,string} のように、ほかのモジュールをモジュールがインポートする場合に、 @code{from module import *} がインポートしているモジュールの名前空間内にそれらを追加することです。これをフィックスするには、 @code{__all__} に公開名を単に列挙します:

@example
# List public names
__all__ = ['Database', 'open']
@end example

このパッチのより厳密な版が最初に示唆されて Ben Wolfson により実装されましたが、python-dev でのいくつかの議論を経てからより弱い最終版がチェックインされました。

@item 
文字列に @ref{1c1,,repr()} を適用するとこれまでは表示出来ない文字について、8 進エスケープが使われていました。例えば改行コードは @code{'\012'} でした。これは Python の起源である C に追従した名残ですが、こんにちでは普段使いで 8 進エスケープが使われることは非常に少なくなりました。Ka-Ping Yee が 8 進の代わりに 16 進を使いつつ相応の文字には @code{\n}, @code{\t}, @code{\r} などのエスケープを使うよう示唆し、この新しい書式化を実装しました。

@item 
コンパイル時点で検出される構文エラーがエラーとなったファイル名と行番号を含む例外を送出できるようになり、またこれによりコンパイラの再編成という喜ばしい副作用がありました。Jeremy Hylton により達成されました。

@item 
C extensions which import other modules have been changed to use
@ref{3dc,,PyImport_ImportModule()}, which means that they will use any import hooks
that have been installed.  This is also encouraged for third-party extensions
that need to import some other module from C code.

@item 
Unicode 文字データベースのサイズが Fredrik Lundh のおかげでさらに 340K だけ小さくなりました。

@item 
いくつかの新たなポートの寄与: MacOS X (by Steven Majewski), Cygwin (by Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware 7  (by Billy G. Allie).
@end itemize

そしてよくあるマイナーなバグフィックス、マイナーなメモリリーク、ドキュメンテーション文字列の編集やほかの微調整があり、全てを列挙するには長過ぎます。もし見たいのであれば、CVS ログで完全な詳細を読んで下さい。

@c ======================================================================

@node 謝辞<7>,,その他の変更と修正<4>,What's New in Python 2 1
@anchor{whatsnew/2 1 acknowledgements}@anchor{1740}
@subsection 謝辞


著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の人々に感謝します:  Graeme Cross, David Goodger, Jay Graves, Michael Hudson, Marc-André Lemburg, Fredrik Lundh, Neil Schemenauer, Thomas Wouters.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node What's New in Python 2 0,変更履歴,What's New in Python 2 1,What's New in Python
@anchor{whatsnew/2 0 doc}@anchor{1741}@anchor{whatsnew/2 0 translation-repo}@anchor{1742}@anchor{whatsnew/2 0 what-s-new-in-python-2-0}@anchor{1743}
@section What's New in Python 2.0


@*著者: 
A.M. Kuchling and Moshe Zadka


@c $Id: whatsnew20.tex 50964 2006-07-30 03:03:43Z fred.drake $

@menu
* はじめに: はじめに<3>. 
* Python 1.6 はいかがですか?: Python 1 6 はいかがですか?. 
* 新しい開発プロセス:: 
* Unicode 文字列型: Unicode 文字列型<2>. 
* リストの内包表記:: 
* 累算代入 (Augmented Assignment): 累算代入 Augmented Assignment. 
* 文字列メソッド:: 
* 循環参照のガベージコレクション:: 
* その他の言語コアの変更:: 
* Python 2.0 への移植: Python 2 0 への移植. 
* 拡張と埋め込みについての変更:: 
* Distutils; モジュールの簡単インストール: Distutils モジュールの簡単インストール. 
* XML モジュール:: 
* 更新されたモジュール:: 
* 新しいモジュール: 新しいモジュール<2>. 
* IDLE の改善:: 
* 削除されたモジュール、非推奨となったモジュール:: 
* 謝辞: 謝辞<8>. 

@end menu

@node はじめに<3>,Python 1 6 はいかがですか?,,What's New in Python 2 0
@anchor{whatsnew/2 0 introduction}@anchor{1744}
@subsection はじめに


新 Python リリース、バージョン 2.0 は、2000 年 10 月 16 日にリリースされました。この記事では 2.0 のエキサイティングな新機能をカバーし、いくつかの有用な変更点をハイライトし、少しの、コードの書き換えを要する互換性のない変更点について指摘します。

Python の開発は、リリースとリリースの間で止まることはなく、バグフィックスと改善はとめどなく、日夜提出されます。多くのマイナーフィックス、少しの最適化、ドキュメンテーション文字列の追加、より良いエラーメッセージが 2.0 に仲間入りしました。これら全てを列挙するのは不可能ですが、それは確かに大事でしょう、全てのリストを見たければ、公に入手可能な CVS ログを調べてください。この前進は、今やバグ修正に日々を費やすことで報酬を受け取って PythonLabs のために働く 5 人の開発者、それと SourceForge に移行した結果改善されたコミュニケーションのおかげです。

@c ======================================================================

@node Python 1 6 はいかがですか?,新しい開発プロセス,はじめに<3>,What's New in Python 2 0
@anchor{whatsnew/2 0 what-about-python-1-6}@anchor{1745}
@subsection Python 1.6 はいかがですか?


Python 1.6 は「推定的義務」の Python リリースと考えることが出来ます。2000 年 5 月にコア開発チームが CNRI を離れたあと、CNRI は Python にかかる作業全てが CNRI で実施されることを含む 1.6 リリースが作成されることをリクエストしました。それゆえ Python 1.6 は、最も重要な新機能としての Unicode サポートを含む、2000 年 5 月の CVS ツリーの状態と同等です。開発はもちろん 5 月以降も継続されましたので、1.6 ツリーは Python 2.0 との前方互換を保障するために少しの修正を受け取りました。1.6 はですから、Python の進化の一部であり、側枝ではありません。

では、あなたは Python 1.6 に興味を示すべきでしょうか? おそらく答えはノーです。1.6final と 2.0beta1 のリリースは同じ日に行われ (2000 年 9 月 5 日)、Python 2.0 のファイナライズはその一ヶ月かそこらで行われるよう計画されました。もしあなたが保守すべきアプリケーションを持っているならば、1.6 への移行には少しばかりコードの破壊を伴うようです。つまりその修正を行い、一ヶ月の間に 2.0 への移行による別の破壊ラウンドがやってきます。直接 2.0 に移行したほうが良いでしょう。このドキュメントに記載する、ほとんどの面白い機能は 2.0 のみのものであり、なぜならほとんどの作業は、5 月から 9 月の間に行われたからなのです。

@c ======================================================================

@node 新しい開発プロセス,Unicode 文字列型<2>,Python 1 6 はいかがですか?,What's New in Python 2 0
@anchor{whatsnew/2 0 new-development-process}@anchor{1746}
@subsection 新しい開発プロセス


Python 2.0 における最も重要な変化はコードに対するものではまったくなくて、Python がどのように開発されるのかについてでしょう: 2000 年 5 月に Python 開発者たちは、ソースコード格納、バグ報告の追跡、パッチ提出の待ち行列管理のための SourceForge によって利用出来るようになったツールの使用を始めました。Python 2.0 ではバグ報告やパッチの提出には、Python プロジェクトページで利用可能なバグトラッキングとパッチ管理ツールを使ってください。 @indicateurl{https://sourceforge.net/projects/python/} にあります(訳注: 2015 年現在の状況は What's New in Python 2.6 参照)。

SourceForge で現在ホストされているサービスの中で最も重要なのは Python CVS ツリーで、Python のソースコードを含む、バージョンコントロールされたレポジトリです。以前までは、CVS ツリーへの書き込み許可を持つ人々が 7 人ほどいて、全てのパッチはその中の一人が精査とチェックをする必要がありました。明らかにこれはスケーラブルではありませんでした。CVS ツリーを SourceForge に移動することで、より多くの人々に書き込み許可を与えることが可能になりました; 2000 年 9 月時点で、27 人の人々が変更をチェックイン出来るようになっていました。これは 4 倍の増加です。これは大規模な変更、これまでであれば小さなコア開発グループによるフィルタを経由しなければならないために試みられなかったような、大規模な変更を可能にしています。例えばある日 Peter Schneider-Kamp は K&R C 互換を落としてしまうことを思い立ち、Python の C ソースを ANSI C に変換しました。python-dev メーリングリストでの承認を得たのち、彼は立て続けにチェックインを開始しておよそ一週間ほどで終わらせ、ほかの開発者たちも手助けに参加し、そして作業は完了しました。書き込み許可が 5 人だけだったならば、おそらくそのタスクはこう見做されたでしょう:「素晴らしい。けれども時間と労力に見合わない」。そして決して実現することはなかったことでしょう。

SourceForge のサービスを使うことへのシフトは、開発の目覚しいスピードアップをもたらしました。パッチはいまや、提出され、コメントされ、提出者以外の別人によって改定されて戻ってきて、などなどが、パッチがチェックインの価値があると判断されるまで行われています。バグは唯一つの中央保管庫で追跡され、修正には特定の誰かを割り当てることが出来、そして私たちはオープンバグを進捗の指標として考えることが出来ます。これは代償なしでは達成しませんでした; 開発者には今や以前よりもたくさんの処理すべき電子メールがあり、より多くメーリングリストに追従しなければならず、そして新しい環境のための特別なツールを要しました。例えば、SourceForge はデフォルトでパッチ提出とバグ報告を電子メールで通知しますが、これは全く助けにならないもので、Ka-Ping Yee はもっと有用なメッセージを送信するための HTML スクリーンスクレイパを書きました。

簡単にコードを追加出来るようになったことは、当初少し苦痛を大きくしました。例えばコードが不十分なままだったり、開発グループからのはっきりとした承諾のないままチェックインされたりするといったことです。浮上してきた承認プロセスは、Apache グループが使っているようなものにいくらか似たものです。開発者たちは +1, +0, -0, -1 というふうにパッチに投票できます; +1 と -1 は承諾、却下を表し、+0 と -0 は、開発者は変更にほとんど興味がないけれどもやや肯定、否定の傾向であることを意味します。Apache モデルからの最も大きな違いは、投票行為は本質的に助言であって、優しい終身独裁者 Guido van Rossum 侯に大衆の民意を伝えるものであることです。彼は投票結果をそれでも無視出来ますし、コミュニティが異論を唱えようが変更を承認したり却下したり出来ます。

実際のパッチの作成は新機能の追加での最後のステップであり、通常、良いデザインを工面する前のタスクと容易に比較出来ます。一方で新機能についての議論はしばしばメーリングリストでの長大なスレッドを巻き起こし、議論に追いつくのが大変になり、そして誰も python-dev の投稿全てを読めません。それゆえに、Python 拡張提案 (Python Enhancement Proposals: PEPs)を書く、相対的に形式ばったプロセスが、始動しました。インターネットの RFC をモデルにしたものです。PEPs は新機能提案を記述した草案文書であり、コミュニティの合意として提案が承認されるか却下されるまで継続的に改定されます。 
@geindex Python Enhancement Proposals; PEP 1
PEP 1@footnote{https://peps.python.org/pep-0001/} の導入部、"PEP の目的とガイドライン" から引用します:

@quotation

PEP は Python Enhancement Proposal を意味します。PEP は、Python コミュニティに対して情報を提供する、あるいは Python の新機能について記述する設計文書です。PEP は、機能についての技術的な仕様とその機能の論拠(理論)を簡潔に伝えるべきです。

私たちは PEP が新機能提案にかかる、コミュニティによる問題提起の集積と Python になされる設計決断の文書化のための最上位の機構となることを意図しています。PEP の著者にはコミュニティ内の合意形成を行うこと、反対意見を文書化することの責務があります。
@end quotation

PEP の編集に関するプロセス、様式、体裁についての詳細が  
@geindex Python Enhancement Proposals; PEP 1
PEP 1@footnote{https://peps.python.org/pep-0001/} の残りの部分に書かれています。PEPs は SourceForge 上の Python CVS ツリーで営まれますが Python 2.0 配布物の一部ではなく、 @indicateurl{https://peps.python.org/} で HTML 形式で利用可能です。2000 年 9 月時点で  
@geindex Python Enhancement Proposals; PEP 201
PEP 201@footnote{https://peps.python.org/pep-0201/} の "Lockstep Iteration" から PEP 225 の "Elementwise/Objectwise Operators" までの 25 の PEP があります。

@c ======================================================================

@node Unicode 文字列型<2>,リストの内包表記,新しい開発プロセス,What's New in Python 2 0
@anchor{whatsnew/2 0 unicode}@anchor{1747}
@subsection Unicode 文字列型


Python 2.0 での最大の新機能は新しい基礎データ型、Unicode 文字列です。Unicode は文字を表現するのに ASCII で使用される 8 ビット数の代わりに 16 ビットを使います。これによって 65,536 の個別の文字がサポート出来ます。(---訳注: Unicode の扱いはまず Python 2.2 で UCS4 が使えるように拡張され(つまり 32 ビットに拡張)、Python 3 では Unicode が唯一の文字列型に変更されています。後者の変更点は非常に大きいですが、クックブックの「Python 2 から Python 3 への移植」に比較的よくまとめられています。---)

最終的な Unicode サポートに関するインターフェイスは、python-dev メーリングリストにおける数え切れない、時として嵐のような議論を経て、Fredrik Lundh によって実装された Unicode 文字列型に基づいて、ほとんどが Marc-André Lemburg によって実装されました。インターフェイスについての詳細な説明は 
@geindex Python Enhancement Proposals; PEP 100
PEP 100@footnote{https://peps.python.org/pep-0100/} 「Python Unicode の統合」に記述されました。今ここでは、Unicode インターフェイスについて、一番重要な点を単純にカバーするだけにしましょう。

Python ソースコード内では Unicode 文字列は @code{u"string"} のように書きます。任意の Unicode 文字は新しく追加されたエスケープシーケンスで書きます。 @code{\u@var{HHHH}} のように書き、 `HHHH' は 0000 から FFFF までの 4 桁の 16 進表記数です。以前からあるエスケープシーケンス @code{\x@var{HH}} も使えますし、8 進表記も、 @code{\777} で表現される U+01FF までの文字に使えます。

Unicode 文字列は普通の文字列と全く似ていて、 @ref{15b9,,immutable} なシーケンス型です。添え字でアクセス出来、スライス出来ますが、インプレイスに変更することは出来ません。Unicode 文字列は @code{encode( [encoding] )} メソッドを持っていて、これは望みのエンコーディングでエンコードした 8 ビット文字列を返します。エンコーディングは文字列で名前付けられていて、例えば @code{'ascii'}, @code{'utf-8'}, @code{'iso-8859-1'} のようなものです。コーデック API は、新しいエンコーディングを実装し、Python プログラム全体を通して利用可能となるよう登録するために定義されています。エンコーディングが指定されない場合はデフォルトのエンコーディングは普通 7 ビット ASCII ですが、Python インストレーションにおいて、 @code{site.py} のカスタマイズ版内で @code{sys.setdefaultencoding(encoding)} を呼び出すことで変更出来ます。

8 ビット文字列と Unicode 文字列を結合すると常に、デフォルトの ASCII エンコーディングを使って Unicode に型変換されます。 @code{'a' + u'bc'} の結果は @code{u'abc'} になります。

新たなビルトイン関数が追加され、既存のビルトイン関数も Unicode サポートのために修正されました:


@itemize *

@item 
@code{unichr(ch)} は Unicode におけるコードが整数 `ch' になるような文字 1 文字からなる Unicode 文字列を返します。

@item 
`u' が 1 文字の通常文字あるいは Unicode 文字として、 @code{ord(u)} はコードを整数で返します。

@item 
@code{unicode(string [, encoding] [, errors] )} は、8 ビット文字列から Unicode 文字列を作ります。 @code{encoding} は使用するエンコーディング名の文字列です。 @code{errors} パラメータは、現在エンコーディングにおいて不正な文字の扱いを指示します; これに値として @code{'strict'} を渡すと全てのエンコーディングエラーに対し、例外を引き起こします。 @code{'ignore'} を渡すとエラーは黙って無視されます。 @code{'replace'} を渡すと、全ての問題ケースで、公式な置き換え文字である U+FFFD に置き換えます。

@item 
@code{exec} 文や　@code{eval()}, @code{getattr()}, @code{setattr()} のような色々なビルトインも、普通の文字列同様に Unicode 文字列を受け付けるようになりました。(この修正をするプロセスをいくつかのビルトインで忘れている可能性もあります。文字列を受け取るものが Unicode を全く受け取らないビルトインを見つけたら、バグとして報告してください。)
@end itemize

新規モジュール @ref{10b,,unicodedata} は、Unicode 文字の特性へのインターフェイスを提供します。例えば @code{unicodedata.category(u'A')} は 2 文字の文字列 'Lu' を返しますが、これは、 'L' が letter を、 'u' が uppercase を表します。 @code{unicodedata.bidirectional(u'\u0660')} は 'AN' を返し、これは U+0660 が Arabic Number であることを表します。

@ref{1c,,codecs} モジュールには、既存のエンコーディングをルックアップする関数、新しいエンコーディングを登録する関数が含まれます。新しいエンコーディングを実装したいと思うのでない限りは、一番使うことになるのは @code{codecs.lookup(encoding)} でしょう。これは 4 要素のタプルを返します: @code{(encode_func, decode_func, stream_reader, stream_writer)} 。


@itemize *

@item 
`encode_func' は、Unicode 文字列を受け取って 2 要素タプル @code{(string, length)} を返す関数です。 `string' は、与えられたエンコーディングで Unicode 文字列を変換した部分 (おそらく全体) を含む 8 ビット文字列で、 `length' は何文字の Unicode 文字列が変換されたかを伝えます。

@item 
`decode_func' は `encode_func' の対となる関数で、8 ビット文字列を受け取って、2 要素のタプル @code{(ustring, length)} を返します。 `ustring' が結果の Unicode 文字列で、整数 `length' が、8 ビット文字列何文字が消費されたかを表します。

@item 
`stream_reader' is a class that supports decoding input from a stream.
`stream_reader(file_obj)' returns an object that supports the @code{read()},
@code{readline()}, and @code{readlines()} methods.  These methods will all
translate from the given encoding and return Unicode strings.

@item 
`stream_writer', similarly, is a class that supports encoding output to a
stream.  `stream_writer(file_obj)' returns an object that supports the
@code{write()} and @code{writelines()} methods.  These methods expect Unicode
strings, translating them to the given encoding on output.
@end itemize

例えば以下のコードは Unicode 文字列を UTF-8 でエンコーディングしてファイルに書きます:

@example
import codecs

unistr = u'\u0660\u2000ab ...'

(UTF8_encode, UTF8_decode,
 UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')

output = UTF8_streamwriter( open( '/tmp/output', 'wb') )
output.write( unistr )
output.close()
@end example

そして以下コードではファイルから UTF-8 で読めます:

@example
input = UTF8_streamreader( open( '/tmp/output', 'rb') )
print repr(input.read())
input.close()
@end example

@ref{be,,re} モジュールでは Unicode 対応した正規表現が利用可能で、これは新しい根底となる SRE なる実装から成り、Secret Labs AB の Fredrik Lundh によって書かれました。

Python コンパイラに全ての文字列リテラルを Unicode 文字列として解釈させるための @code{-U} コマンドラインオプションが追加されました。これはあなたの Python コードのテストと将来の保障を意図しています。というのも、将来の Python バージョンでは 8 ビット文字列のサポートがなくなって、Unicode 文字列だけとなる予定だからです。 (---訳注: ここで言っている将来バージョンとは、結果的には Python 3 になりました。What's New での明記はないのですが @code{-U} オプションは Python 2.7 時点では存在していません。ですが同じことは 2.6 以降では @code{from __future__ import unicode_literals} で出来ます。 ---)

@c ======================================================================

@node リストの内包表記,累算代入 Augmented Assignment,Unicode 文字列型<2>,What's New in Python 2 0
@anchor{whatsnew/2 0 list-comprehensions}@anchor{1748}
@subsection リストの内包表記


リストというのは Python の主要なデータ型で、多くのプログラムがリストをいつかは操るものです。リストの操作での 2 つのよくある操作は、それらについてループし、あるいは特定の基準に合致したものを取り出すか個々の要素にある関数を適用するかする、といったものです。例えば文字列のリストが与えられた場合、特定の部分文字列を含む全ての文字列を引き抜いたり、あるいは各行から末尾の空白を取り除いたりしたいでしょう。

既にあった @ref{19f,,map()} 関数、 @ref{a64,,filter()} 関数がこの目的のためには使えますが、それらにはその引数の一つに関数が必要です。何か既存のビルトイン関数で直接渡せるものがあればよいのですが、これがない場合その必要とされる仕事をする小さな関数を作る必要があって、また、Python のスコープ規則によって、その小さな関数が何かほかの情報を必要とする場合に醜いものになります。前パラグラフでの最初の例を考えましょう。指定の部分文字列を含む文字列リストから全てを探す例です。このように書けるでしょう:

@example
# Given the list L, make a list of all strings
# containing the substring S.
sublist = filter( lambda s, substring=S:
                     string.find(s, substring) != -1,
                  L)
@end example

Python のスコープ規則のために、 @ref{14b5,,lambda} 式で作っている匿名関数にデフォルト引数を使い、これに検索対象の部分文字列を渡しています。リスト内包表記はこれを明快にします:

@example
sublist = [ s for s in L if string.find(s, S) != -1 ]
@end example

リスト内包表記は以下の形式を持ちます:

@example
[ expression for expr in sequence1
             for expr2 in sequence2 ...
             for exprN in sequenceN
             if condition ]
@end example

@code{for}...@code{in} 節はイテレートするシーケンスを含みます。シーケンス群は同じ長さである必要はありません。それらは並列でイテレートされる `のではなく' 左から右の順で周ります。続くパラグラフでもっとわかりやすく説明します。生成されるリストの要素は一連の `expression' の値となります。最後の @ref{181,,if} 節はオプショナルです。これがあれば `expression' は `condition' が真の場合にのみ評価・追加されます。

セマンティクスについてとてもわかりやすく説明しておきましょう。リスト内包は以下の Python コードと等価です:

@example
for expr1 in sequence1:
    for expr2 in sequence2:
    ...
        for exprN in sequenceN:
             if (condition):
                  # Append the value of
                  # the expression to the
                  # resulting list.
@end example

つまり、複数の @code{for}...@code{in} 節があって @code{if} がないときの最終出力は、長さが各シーケンス長の積に等しくなるということです。長さ 3 のリスト二つなら、出力リストの長さは 9 要素です:

@example
seq1 = 'abc'
seq2 = (1,2,3)
>>> [ (x,y) for x in seq1 for y in seq2]
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),
('c', 2), ('c', 3)]
@end example

Python の文法に曖昧さを紛れ込ませないように、`expression' でタプルを作るなら括弧で囲わなくてはなりません。下にあるリスト内包表記で、最初のは構文エラーですが、二番目は有効です:

@example
# Syntax error
[ x,y for x in seq1 for y in seq2]
# Correct
[ (x,y) for x in seq1 for y in seq2]
@end example

リスト内包表記のアイディアは、もともとは関数型プログラミング言語 Haskell (@indicateurl{https://www.haskell.org}) に由来しています。Greg Ewing が Python にこれを追加することを最も実際的に主張し、彼が最初のリスト内包のパッチを書きました。それは傍目には終わりのない議論が python-dev メーリングリストにて続き、Skip Montanaro によって最新に保たれました。

@c ======================================================================

@node 累算代入 Augmented Assignment,文字列メソッド,リストの内包表記,What's New in Python 2 0
@anchor{whatsnew/2 0 augmented-assignment}@anchor{1749}
@subsection 累算代入 (Augmented Assignment)


累算代入はもう一つの長らく待ち望まれた機能であり、Python 2.0 に追加されました。累算代入演算子には  @code{+=}, @code{-=}, @code{*=} などがあります。例えばステートメント @code{a += 2} は変数 @code{a} に 2 を加算し、これはちょっとだけ長い記述 @code{a = a + 2} と同じです。

The full list of supported assignment operators is @code{+=}, @code{-=}, @code{*=},
@code{/=}, @code{%=}, @code{**=}, @code{&=}, @code{|=}, @code{^=}, @code{>>=}, and @code{<<=}.  Python
classes can override the augmented assignment operators by defining methods
named @code{__iadd__()}, @code{__isub__()}, etc.  For example, the following
@code{Number} class stores a number and supports using += to create a new
instance with an incremented value.

@c The empty groups below prevent conversion to guillemets.

@example
class Number:
    def __init__(self, value):
        self.value = value
    def __iadd__(self, increment):
        return Number( self.value + increment)

n = Number(5)
n += 3
print n.value
@end example

The @code{__iadd__()} special method is called with the value of the increment,
and should return a new instance with an appropriately modified value; this
return value is bound as the new value of the variable on the left-hand side.

累算代入演算子は最初に C 言語で導入されて、 @code{awk}, C++, Java, Perl, PHP といった C から派生した言語のほとんどでサポートされています。累算代入のパッチは Thomas Wouters により実装されました。

@c ======================================================================

@node 文字列メソッド,循環参照のガベージコレクション,累算代入 Augmented Assignment,What's New in Python 2 0
@anchor{whatsnew/2 0 string-methods}@anchor{174a}
@subsection 文字列メソッド


Until now string-manipulation functionality was in the @ref{d8,,string} module,
which was usually a front-end for the @code{strop} module written in C.  The
addition of Unicode posed a difficulty for the @code{strop} module, because the
functions would all need to be rewritten in order to accept either 8-bit or
Unicode strings.  For functions such as @code{string.replace()}, which takes 3
string arguments, that means eight possible permutations, and correspondingly
complicated code.

代わりに、Python 2.0 は問題を文字列型に押し込み、文字列操作機能が 8 ビット文字列と Unicode 文字列の両方のメソッドを通じて利用可能としました。

@example
>>> 'andrew'.capitalize()
'Andrew'
>>> 'hostname'.replace('os', 'linux')
'hlinuxtname'
>>> 'moshe'.find('sh')
2
@end example

変わらない一つのこと、華やかなエイプリルフールのジョークではありませんが、それは Python 文字列が @ref{15b9,,immutable} だということです。ですので文字列メソッドは新しい文字列を返し、それが操作する文字列を変更しません。

古い @ref{d8,,string} モジュールはまだ後方互換性のために残されますが、それはほとんど新たな文字列メソッドへのフロントエンドとして振舞います。

Two methods which have no parallel in pre-2.0 versions, although they did exist
in JPython for quite some time, are @code{startswith()} and @code{endswith()}.
@code{s.startswith(t)} is equivalent to @code{s[:len(t)] == t}, while
@code{s.endswith(t)} is equivalent to @code{s[-len(t):] == t}.

One other method which deserves special mention is @code{join()}.  The
@code{join()} method of a string receives one parameter, a sequence of strings,
and is equivalent to the @code{string.join()} function from the old @ref{d8,,string}
module, with the arguments reversed. In other words, @code{s.join(seq)} is
equivalent to the old @code{string.join(seq, s)}.

@c ======================================================================

@node 循環参照のガベージコレクション,その他の言語コアの変更,文字列メソッド,What's New in Python 2 0
@anchor{whatsnew/2 0 garbage-collection-of-cycles}@anchor{174b}
@subsection 循環参照のガベージコレクション


Python の C 実装は、ガーベージコレクションの実装に参照カウントを使っています。全ての Python オブジェクトは自身を参照している数を維持していて、参照が作成されたり破壊されたりするカウントを調整しています。参照カウントがゼロになればそのオブジェクトにはもはや到達可能ではありません。あなたはそれにアクセスするためのオブジェクトへの参照を持つ必要がありますが、カウントがゼロならば参照はもはや存在しないということです。

参照カウントはある種望ましい特徴を持っています。それは理解しやすく、実装しやすく、結果としての実装の移植性は高く、かなり高速であり、そして、独自のメモリ処理方式を実装しているようなほかのライブラリと共にでも良く振舞います。参照カウントの主要な問題点は、それが時々、オブジェクトにはもう到達不能であることに気付かないので、結果としてメモリリークを引き起こすことです。これは参照の循環がある場合に発生します。

最も単純な循環について考えてみます。クラスインスタンスが自身への参照を持つ場合です:

@example
instance = SomeClass()
instance.myself = instance
@end example

上の例の 2 行のコードが実行された後では、 @code{instance} の参照カウントは 2 です。参照の一つ目は @code{'instance'} と名付けられた変数からのもので、もう一つの参照は、インスタンスの @code{myself} 属性から来るものです。

このあとに続くコードが @code{del instance} だとしたら、何が起こるでしょうか? @code{instance} の参照カウントは 1 減るので参照カウントは 1 になります。 @code{myself} 属性内の参照はいまだ存在します。けれどもインスタンスはもう Python コードからは到達不能ですから、本来削除出来るはずです。お互いを参照しあうならばいくつものオブジェクトが循環に参加しえるので、結果それら全てのオブジェクトはリークしてしまいます。

Python 2.0 はこの問題を、循環検出アルゴリズムを周期的に実行することによりフィックスします。そのアルゴリズムは、到達不能な循環を探して関係するオブジェクトを削除します。新しく追加された @ref{64,,gc} モジュールは、ガーベージコレクションを実行する関数、デバッグのための統計情報を取得する関数、コレクタのパラメータを調整する関数を提供します。

循環検出アルゴリズムの実行はいくらかの時間がかかるので、結果として多少の追加的なオーバヘッドがかかるでしょう。2.0 を使って循環のコレクションの経験を積んだのちに、 Python 2.1 では注意深い調整によりオーバヘッドを最小に出来ることが望まれています。今のところパフォーマンスの損失がいかほどなのかは明らかではありません。これはこれのベンチマークがトリッキーであり、プログラムがどれだけの頻度でオブジェクトを構築・破棄するのかに大きく依存するからです。循環の検出は Python コンパイル時に無効に出来ます。もしもあなたが小さな速度のペナルティでさえも許容出来ないであるとか、あるいは循環のコレクションがバギーであることを疑うのであれば、 @code{configure} スクリプト実行時に @code{--without-cycle-gc} スイッチを与えることでそうすることが出来ます。 (---訳注: Python 2.3 でこの循環参照の GC は必須となり、 @code{--without-cycle-gc} 、 @code{--with-cycle-gc} での有無効化は撤廃されました。---)

何人かの人々がこの問題に体当たりで取り組み、解決に対する貢献をしました。循環検出アプローチの初期の実装は、Toby Kelsey により書かれました。現在のアルゴリズムは CNRI を訪れている間に Eric Tiedemann によって提案されて、Guido van Rossum と Neil Schemenauer が別々の 2 つの実装を書いて、あとで Neil によって統合されたものです。そこに至るまでにもほかの数多くの人々によって提案がなされました。python-dev メーリングリストの 2000 年 3 月のアーカイブに、これに関するほとんどの議論が含まれています。特にタイトルが "Reference cycle collection for Python" と "Finalization again" のスレッドです。

@c ======================================================================

@node その他の言語コアの変更,Python 2 0 への移植,循環参照のガベージコレクション,What's New in Python 2 0
@anchor{whatsnew/2 0 other-core-changes}@anchor{174c}
@subsection その他の言語コアの変更


Python 文法とビルトイン関数について、色々マイナーな変更がなされました。影響が広範囲に及ぶものは一つもありませんが、手軽で便利なものです。

@menu
* 言語のマイナー変更:: 
* ビルトイン関数の変更:: 

@end menu

@node 言語のマイナー変更,ビルトイン関数の変更,,その他の言語コアの変更
@anchor{whatsnew/2 0 minor-language-changes}@anchor{174d}
@subsubsection 言語のマイナー変更


A new syntax makes it more convenient to call a given function with a tuple of
arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier,
you'd use the @code{apply()} built-in function: @code{apply(f, args, kw)} calls the
function @code{f()} with the argument tuple `args' and the keyword arguments in
the dictionary `kw'.  @code{apply()}  is the same in 2.0, but thanks to a patch
from Greg Ewing, @code{f(*args, **kw)} is a shorter and clearer way to achieve the
same effect.  This syntax is symmetrical with the syntax for defining
functions:

@example
def f(*args, **kw):
    # args is a tuple of positional args,
    # kw is a dictionary of keyword args
    ...
@end example

The @code{print} statement can now have its output directed to a file-like
object by following the @code{print} with  @code{>> file}, similar to the
redirection operator in Unix shells. Previously you'd either have to use the
@code{write()} method of the file-like object, which lacks the convenience and
simplicity of @code{print}, or you could assign a new value to
@code{sys.stdout} and then restore the old value.  For sending output to standard
error, it's much easier to write this:

@example
print >> sys.stderr, "Warning: action field not supplied"
@end example

@code{import module as name} または @code{from module import name as othername} という構文を使って、インポートするモジュールの名前をリネーム出来るようになりました。パッチは Thomas Wouters が投稿しました。

@code{%} 演算子を使う際に新しい書式化スタイルが利用可能です; '%r' はその引数の @ref{1c1,,repr()} を挿入します。これは対称性の検討からも考えられました。今の場合は既存の '%s' が引数の @ref{169,,str()} を挿入することに呼応するものです。例えば @code{'%r %s' % ('abc', 'abc')} は文字列 @code{'abc' abc} を返します。

Previously there was no way to implement a class that overrode Python's built-in
@ref{34b,,in} operator and implemented a custom version.  @code{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
@ref{174e,,IndexError} is encountered.  Moshe Zadka contributed a patch which adds a
@code{__contains__()} magic method for providing a custom implementation for
@code{in}. Additionally, new built-in objects written in C can define what
@code{in} means for them via a new slot in the sequence protocol.

以前のバージョンの Python では、オブジェクトの削除に再帰するアルゴリズムを使っていました。データ構造が深くネストしている場合、インタプリタが C のスタックを使い果たしてクラッシュしていました。Christian Tismer はこの問題をフィックスする削除ロジックに書き直しました。これに関係する注目すべきものとしては、再帰するオブジェクトの比較が無限再帰してクラッシュしていたのを、Jeremy Hylton が書き直してクラッシュしないようにして、有用な結果を生成するようにしたことです。例えば以下コード:

@example
a = []
b = []
a.append(a)
b.append(b)
@end example

The comparison @code{a==b} returns true, because the two recursive data structures
are isomorphic. See the thread "trashcan and PR#7" in the April 2000 archives of
the python-dev mailing list for the discussion leading up to this
implementation, and some useful relevant links.    Note that comparisons can now
also raise exceptions. In earlier versions of Python, a comparison operation
such as @code{cmp(a,b)} would always produce an answer, even if a user-defined
@code{__cmp__()} method encountered an error, since the resulting exception would
simply be silently swallowed.

@c Starting URL:

@c https://www.python.org/pipermail/python-dev/2000-April/004834.html

Work has been done on porting Python to 64-bit Windows on the Itanium processor,
mostly by Trent Mick of ActiveState.  (Confusingly, @code{sys.platform} is still
@code{'win32'} on Win64 because it seems that for ease of porting, MS Visual C++
treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the
Python CE page at @indicateurl{https://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.

変数に値が割り当てられる前にローカル変数を参照するコードにおいて、 @ref{452,,NameError} 例外はよく混乱するものであり、この欠点を軽減する試みがなされました。例えば下に挙げるコードは @code{print} 文で 1.5.2 と 2.0 の両方で例外が発生しますが、1.5.2 は @ref{452,,NameError} 例外が、2.0 では新規の例外 @ref{174f,,UnboundLocalError} が投げられます。 @ref{174f,,UnboundLocalError} は @ref{452,,NameError} のサブクラスですので @ref{452,,NameError} が投げられることを想定する既存のコードはそのまま動作するはずです。:

@example
def f():
    print "i=",i
    i = i + 1
f()
@end example

2 つの新規例外 @ref{765,,TabError} と @ref{1750,,IndentationError} が導入されました。これらはともに @ref{18e,,SyntaxError} のサブクラスで、Python コードに不適切なインデントが見つかると送出されます。

@node ビルトイン関数の変更,,言語のマイナー変更,その他の言語コアの変更
@anchor{whatsnew/2 0 changes-to-built-in-functions}@anchor{1751}
@subsubsection ビルトイン関数の変更


新しいビルトイン関数 @code{zip(seq1, seq2, ...)} が追加されました。 @ref{1a0,,zip()} はタプルのリストを返します。それぞれは、引数のシーケンスのそれぞれの i 番目要素たちを含むタプルです。 @ref{1a0,,zip()} と @code{map(None, seq1, seq2)} の違いは、 @ref{19f,,map()} はシーケンスが同じ長さを持たない場合に @code{None} が埋められるのに対し、 @ref{1a0,,zip()} は返すリストの長さを、引数のシーケンスの最も短い長さに切り詰めます。

The @ref{19b,,int()} and @code{long()} functions now accept an optional "base"
parameter when the first argument is a string. @code{int('123', 10)} returns 123,
while @code{int('123', 16)} returns 291.  @code{int(123, 16)} raises a
@ref{198,,TypeError} exception with the message "can't convert non-string with
explicit base".

@ref{df,,sys} モジュールに、これまでより詳細なバージョン情報を持つ変数が追加されました。 @code{sys.version_info} はタプル @code{(major, minor, micro, level, serial)} です。例えば仮に 2.0.1beta1 というバージョンだったとすれば、 @code{sys.version_info} は @code{(2, 0, 1, 'beta', 1)} となるでしょう。 `level' は @code{"alpha"} や @code{"beta"} といった文字列で、最終リリースでは @code{"final"} です。(---訳注: Python 2.7 で名前付きタプルになっています。また、その属性名では level ではなく releaselevel です。---)

Dictionaries have an odd new method, @code{setdefault(key, default)}, which
behaves similarly to the existing @code{get()} method.  However, if the key is
missing, @code{setdefault()} both returns the value of `default' as @code{get()}
would do, and also inserts it into the dictionary as the value for `key'.  Thus,
the following lines of code:

@example
if dict.has_key( key ): return dict[key]
else:
    dict[key] = []
    return dict[key]
@end example

は、単一の @code{return dict.setdefault(key, [])} ステートメントだけで書けます。

再帰の暴走を C のスタックが埋め尽くされてコアダンプしたり GPF (訳注: General Protection Fault) する前に捕捉するために、インタプリタは最大の再帰の深さをセットします。以前まではこの制限は Python コンパイル時点で決めてしまっていましたが、2.0 では最大の再帰の深さは @ref{6eb,,sys.getrecursionlimit()} と @ref{6ea,,sys.setrecursionlimit()} を使って読み取れ、修正出来ます。このデフォルトは 1000 です。また、当該プラットフォームでのおよその最大値は、新たに追加されたスクリプト @code{Misc/find_recursionlimit.py} を実行することで知ることが出来ます。

@c ======================================================================

@node Python 2 0 への移植,拡張と埋め込みについての変更,その他の言語コアの変更,What's New in Python 2 0
@anchor{whatsnew/2 0 porting-to-2-0}@anchor{1752}
@subsection Python 2.0 への移植


新しい Python リリースは以前のリリースとの互換性を保つために苦心していますし、その記録はかなり良くなされてきました。ですがいくつかの変更に関しては、大抵は大きな誤りであると判明した初期デザインを修正するという理由で、後方互換性を破壊することを必ずしも回避せずに有用性が検討されています。このセクションでは Python 2.0 において、古い Python コードを破壊するかもしれない変更点について列挙します。

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
@ref{8dc,,append()} and @ref{13b0,,insert()}.
In earlier versions of Python, if @code{L} is
a list, @code{L.append( 1,2 )} appends the tuple @code{(1,2)} to the list.  In Python
2.0 this causes a @ref{198,,TypeError} exception to be raised, with the message:
'append requires exactly 1 argument; 2 given'.  The fix is to simply add an
extra set of parentheses to pass both values as a tuple:  @code{L.append( (1,2) )}.

The earlier versions of these methods were more forgiving because they used an
old function in Python's C interface to parse their arguments; 2.0 modernizes
them to use @ref{3c1,,PyArg_ParseTuple()}, the current argument parsing function,
which provides more helpful error messages and treats multi-argument calls as
errors.  If you absolutely must use 2.0 but can't fix your code, you can edit
@code{Objects/listobject.c} and define the preprocessor symbol
@code{NO_STRICT_LIST_APPEND} to preserve the old behaviour; this isn't recommended.

@ref{d1,,socket} モジュールのいくつかの関数についてはまだこの方法が許されています。例えば、 @code{socket.connect( ('hostname', 25) )} が正しい形式なのですが、 @code{socket.connect('hostname', 25)} も動作します。@ref{1753,,socket.connect_ex} と @ref{12d7,,socket.bind} も同じようにおおらかです。2.0alpha1 がそれら関数を厳しくしたのですが、ドキュメントが実際には複数引数を取る形式で誤って書かれたために、多くの人々がその厳しくなったチェックに違反してしまうコードを書いてしまいました。GvR はその変更を、市民たちの反応を受けて元に戻し、 @ref{d1,,socket} モジュールについてはドキュメントは修正されて、複数引数形式は非推奨としてマークするに留められました。将来バージョンの Python においてこれはもう一度厳しく `なります' 。 (---訳注: What's New からは読み取れませんが少なくとも 2.7 では単一引数でしか渡せません。つまり明示的にタプルにして渡す必要があります。---)

文字列リテラル内の @code{\x} エスケープは、正確に 2 桁の 16 進表記文字になりました。以前は 'x' に続く 16 進表記文字全てを消費して最後の 8 ビットを使っていたため、 @code{\x123456} は @code{\x56} と同じでした。

例外 @ref{5f0,,AttributeError} と @ref{452,,NameError} がよりフレンドリなエラーメッセージを持つようになっています。それらのテキストは @code{'Spam' instance has no attribute 'eggs'} や @code{name 'eggs' is not defined} のようなものになります。以前まではエラーメッセージは存在しない属性名 @code{eggs} だけでしたので、この事実に便乗して書かれたコードは 2.0 では壊れます。

Some work has been done to make integers and long integers a bit more
interchangeable.  In 1.5.2, large-file support was added for Solaris, to allow
reading files larger than 2 GiB; this made the @code{tell()} method of file
objects return a long integer instead of a regular integer.  Some code would
subtract two file offsets and attempt to use the result to multiply a sequence
or slice a string, but this raised a @ref{198,,TypeError}.  In 2.0, long integers
can be used to multiply or slice a sequence, and it'll behave as you'd
intuitively expect it to; @code{3L * 'abc'} produces 'abcabcabc', and
@code{(0,1,2,3)[2L:4L]} produces (2,3). Long integers can also be used in various
contexts where previously only integers were accepted, such as in the
@code{seek()} method of file objects, and in the formats supported by the @code{%}
operator (@code{%d}, @code{%i}, @code{%x}, etc.).  For example, @code{"%d" % 2L**64} will
produce the string @code{18446744073709551616}.

一番微妙な長整数についての変更は、長整数を @ref{169,,str()} してももはや末尾の 'L' 文字が付かないことです。 @ref{1c1,,repr()} では今でも付くのにも関わらずです。 'L' は長整数を普通の整数と全く同じように印字したい多くの人々を悩ませてきました。それを各々自分なりの手段で取り除く必要があったからです。これはもう 2.0 では問題でなくなりましたが、 'L' が付くことをあてにして @code{str(longval)[:-1]} とするコードが今度は数値の最後の桁を失ってしまいます。

Taking the @ref{1c1,,repr()} of a float now uses a different formatting precision
than @ref{169,,str()}.  @ref{1c1,,repr()} uses @code{%.17g} format string for C's
@code{sprintf()}, while @ref{169,,str()} uses @code{%.12g} as before.  The effect is that
@ref{1c1,,repr()} may occasionally show more decimal places than  @ref{169,,str()}, for
certain numbers.  For example, the number 8.1 can't be represented exactly in
binary, so @code{repr(8.1)} is @code{'8.0999999999999996'}, while str(8.1) is
@code{'8.1'}.

The @code{-X} command-line option, which turned all standard exceptions into
strings instead of classes, has been removed; the standard exceptions will now
always be classes.  The @code{exceptions} module containing the standard
exceptions was translated from Python to a built-in C module, written by Barry
Warsaw and Fredrik Lundh.

@c Commented out for now -- I don't think anyone will care.
@c The pattern and match objects provided by SRE are C types, not Python
@c class instances as in 1.5.  This means you can no longer inherit from
@c \class{RegexObject} or \class{MatchObject}, but that shouldn't be much
@c of a problem since no one should have been doing that in the first
@c place.

@c ======================================================================

@node 拡張と埋め込みについての変更,Distutils モジュールの簡単インストール,Python 2 0 への移植,What's New in Python 2 0
@anchor{whatsnew/2 0 extending-embedding-changes}@anchor{1754}
@subsection 拡張と埋め込みについての変更


いくつかの変更点については覆いが被されていて、C 拡張モジュールや大きなアプリケーションでの Python インタプリタの埋め込みを書く人々からしか見えないものです。Python C API を扱う必要がないのであれば、このセクションは読み飛ばして差し支えありません。

Python C API のバージョン番号がインクリメントされたので、1.5.2 でコンパイルされた C 拡張は 2.0 で動作させるために再コンパイルしなければなりません。Windows では Python 1.5.x でビルドされたサードパーティ拡張を Python 2.0 でインポートすることは、Windows の DLL の仕組みのために、出来ません。その場合 Python は例外を投げ、インポートは失敗します。(---訳注: この文章、おかしなことを言っているので一応…。おそらく「Windows の一般市民は C コンパイラを持っていない」ことが著者の頭にあって、手が滑っているのだと思います。DLL の動作の仕組みが問題となるのは事実ですが、本質的には Windows 云々はあまり関係ないです。API が変わるか ABI が変わるならプラットフォームに関係なくリコンパイルは常に必要です。 ---)

Users of Jim Fulton's ExtensionClass module will be pleased to find out that
hooks have been added so that ExtensionClasses are now supported by
@ref{2ad,,isinstance()} and @ref{9c4,,issubclass()}. This means you no longer have to
remember to write code such as @code{if type(obj) == myExtensionClass}, but can use
the more natural @code{if isinstance(obj, myExtensionClass)}.

@code{Python/importdl.c} ファイルが多くの異なるプラットフォームの動的ロードをサポートするのに大量の #ifdef だらけになっていたのを、Greg Stein が掃除して再編成しました。 @code{importdl.c} は今ではとても小さくなり、プラットフォーム依存のコードは @code{Python/dynload_*.c} ファイル群の束にそれぞれ移動しました。もう一つの掃除。include/ ディレクトリ内で色々な移植性のためのハックを施すためのたくさんの @code{my*.h} ファイルたちが、単一の @code{Include/pyport.h} にマージされました。

Vladimir Marangozov の手による、待ち望まれた malloc の再編成が完了しました。これは Python インタプリタが C 標準の @code{malloc()} の代わりにカスタムアロケータを使うことを容易にするものです。ドキュメントについては @code{Include/pymem.h} と @code{Include/objimpl.h} のコメントを読んで下さい。インターフェイスが決着するまでの間の長い長い議論については python.org の 'patches' と 'python-dev' リストのウェブアーカイブをみてください。(---訳注: この件についての続きの話が  What's New in Python 2.3 に Pymalloc として少しわかりやすく記述されています。---)

MacOS の GUSI 開発環境の最近のバージョンは POSIX スレッドをサポートしています。ですので Python の POSIX スレッディングのサポートは今では Macintosh で動作します。ユーザ空間での GNU @code{pth} ライブラリを使ったスレッディングサポートも寄稿されました。

Windows でのスレッディングサポートも拡張されました。Windows は、競合があるケースでのみカーネルオブジェクトを使うスレッドロックをサポートしています。競合がない普通のケースではそれらはより単純な関数を使い、これは段違いに高速です。NT での Python 1.5.2 版でスレッド化すると、非スレッド版の 2 倍遅くなりますが、2.0 に変えるとその差はたった 10% です。これらの改善は Yakov Markovitch の貢献によるものです。

Python 2.0 のソースが ANSI C プロトタイプだけを使うようになったので、Python のコンパイルには ANSI C コンパイラが必須になりました。K&R C しかサポートしないコンパイラではもうコンパイル出来ません。

Previously the Python virtual machine used 16-bit numbers in its bytecode,
limiting the size of source files.  In particular, this affected the maximum
size of literal lists and dictionaries in Python source; occasionally people who
are generating Python code would run into this limit.  A patch by Charles G.
Waldman raises the limit from @code{2**16} to @code{2**32}.

Three new convenience functions intended for adding constants to a module's
dictionary at module initialization time were added: @ref{60b,,PyModule_AddObject()},
@ref{1755,,PyModule_AddIntConstant()}, and @ref{1756,,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.

Unix スタイルのシグナルハンドラへのラッパーAPIが追加されました。 @ref{1757,,PyOS_getsig()} でシグナルハンドラを取得し、 @ref{1758,,PyOS_setsig()} で新しいハンドラをセットします。

@c ======================================================================

@node Distutils モジュールの簡単インストール,XML モジュール,拡張と埋め込みについての変更,What's New in Python 2 0
@anchor{whatsnew/2 0 distutils-making-modules-easy-to-install}@anchor{1759}
@subsection Distutils: モジュールの簡単インストール


Python 2.0 以前は、モジュールのインストールは退屈な作業でした -- Python がどこにインストールされているかや拡張モジュールのコンパイルに必要なオプションを自動的に知る方法はありませんでした。ソフトウェアの作者は Makefile と設定ファイル群の編集という大変な労力を要する儀式を通過しなければならないのに、それは実際には Unix だけのためであって Windows と MacOS のサポートを置き去りにするものでした。Python ユーザは全く異なったインストール命令に直面していました。それは拡張パッケージごとに異なり、Python インストールをある種つまらない作業としていました。

The SIG for distribution utilities, shepherded by Greg Ward, has created the
Distutils, a system to make package installation much easier.  They form the
@code{distutils} package, a new part of Python's standard library. In the best
case, installing a Python module from source will require the same steps: first
you simply mean unpack the tarball or zip archive, and the run "@code{python
setup.py install}".  The platform will be automatically detected, the compiler
will be recognized, C extension modules will be compiled, and the distribution
installed into the proper directory.  Optional command-line arguments provide
more control over the installation process, the distutils package offers many
places to override defaults -- separating the build from the install, building
or installing in non-default directories, and more.

Distutils を使うには @code{setup.py} スクリプトを書く必要があります。単純なケースでは、ソフトウェアが .py ファイルだけを含む場合、最小限の @code{setup.py} は数行足らずで書けます:

@example
from distutils.core import setup
setup (name = "foo", version = "1.0",
       py_modules = ["module1", "module2"])
@end example

@code{setup.py} ファイルは、ソフトウェアが少しのパッケージで構成される場合はこれより大きく複雑になることはありません:

@example
from distutils.core import setup
setup (name = "foo", version = "1.0",
       packages = ["package", "package.subpackage"])
@end example

C 拡張が最も複雑なケースになりえます。以下は PyXML パッケージからもってきた例です:

@example
from distutils.core import setup, Extension

expat_extension = Extension('xml.parsers.pyexpat',
     define_macros = [('XML_NS', None)],
     include_dirs = [ 'extensions/expat/xmltok',
                      'extensions/expat/xmlparse' ],
     sources = [ 'extensions/pyexpat.c',
                 'extensions/expat/xmltok/xmltok.c',
                 'extensions/expat/xmltok/xmlrole.c', ]
       )
setup (name = "PyXML", version = "0.5.4",
       ext_modules =[ expat_extension ] )
@end example

Distutils ではソース配布物、バイナリ配布物の作成の面倒もみてくれます。 "sdist" コマンドは "@code{python setup.py sdist}" を実行することで起動し、これは @code{foo-1.0.tar.gz} のようなソース配布物を作ります。新しいコマンドを作るのは難しくありません。コマンド "bdist_rpm" と "bdist_wininst" が既に寄稿されていて、各々 RPM 配布物の作成、Windows インストーラの作成を行います。Debian パッケージや Solaris の @code{.pkg} のようなほかの配布フォーマットを作成するコマンドについての開発ステージは様々です。

これら全ては、 Python ドキュメントの基本的なセットとして追加されたマニュアル `Python モジュールの配布' にドキュメントされています。

@c ======================================================================

@node XML モジュール,更新されたモジュール,Distutils モジュールの簡単インストール,What's New in Python 2 0
@anchor{whatsnew/2 0 xml-modules}@anchor{175a}
@subsection XML モジュール


Python 1.5.2 included a simple XML parser in the form of the @code{xmllib}
module, contributed by Sjoerd Mullender.  Since 1.5.2's release, two different
interfaces for processing XML have become common: SAX2 (version 2 of the Simple
API for XML) provides an event-driven interface with some similarities to
@code{xmllib}, and the DOM (Document Object Model) provides a tree-based
interface, transforming an XML document into a tree of nodes that can be
traversed and modified.  Python 2.0 includes a SAX2 interface and a stripped-down
DOM interface as part of the @ref{126,,xml} package. Here we will give a brief
overview of these new interfaces; consult the Python documentation or the source
code for complete details. The Python XML SIG is also working on improved
documentation.

@menu
* SAX2 サポート:: 
* DOM サポート:: 
* PyXML との関係:: 

@end menu

@node SAX2 サポート,DOM サポート,,XML モジュール
@anchor{whatsnew/2 0 sax2-support}@anchor{175b}
@subsubsection SAX2 サポート


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 @ref{175c,,startElement()} and @ref{175d,,endElement()}
methods are called for every starting and end tag encountered by the parser, the
@ref{175e,,characters()} method is called for every chunk of character data, and so
forth.

イベントドリブンのアプローチはドキュメント全体をいっときにメモリに持たなくて良い点で有利であり、ドキュメントが本当に巨大であるものを処理する際にはこれは重要です。ですが SAX ハンドラクラスを記述することは、ドキュメント構造を変更しようとする場合にはある種入り組んだものとなって、とても複雑になりえます。

以下の小さな実例プログラムでは、全ての開始・終了タグでメッセージを印字するハンドラを定義して、ファイル @code{hamlet.xml} をそのハンドラを使ってパースしています:

@example
from xml import sax

class SimpleHandler(sax.ContentHandler):
    def startElement(self, name, attrs):
        print 'Start of element:', name, attrs.keys()

    def endElement(self, name):
        print 'End of element:', name

# Create a parser object
parser = sax.make_parser()

# Tell it what handler to use
handler = SimpleHandler()
parser.setContentHandler( handler )

# Parse a file!
parser.parse( 'hamlet.xml' )
@end example

For more information, consult the Python documentation, or the XML HOWTO at
@indicateurl{https://pyxml.sourceforge.net/topics/howto/xml-howto.html}.

@node DOM サポート,PyXML との関係,SAX2 サポート,XML モジュール
@anchor{whatsnew/2 0 dom-support}@anchor{175f}
@subsubsection DOM サポート


The Document Object Model is a tree-based representation for an XML document.  A
top-level @code{Document} instance is the root of the tree, and has a single
child which is the top-level @code{Element} instance. This @code{Element}
has children nodes representing character data and any sub-elements, which may
have further children of their own, and so forth.  Using the DOM you can
traverse the resulting tree any way you like, access element and attribute
values, insert and delete nodes, and convert the tree back into XML.

DOM は XML ドキュメントを修正するのに有用です。というのも DOM ツリーは作成出来、新規ノードを追加したりサブツリーを再編成したりすることで修正出来、出力として新たな XML ドキュメントを生成出来るからです。DOM ツリーを手動で構築して XML に変換することも出来ます。これにより単純に @code{<tag1>}...@code{</tag1>} をファイルに書くよりも柔軟性の高い方法で XML 出力を生成出来ます。

The DOM implementation included with Python lives in the @ref{128,,xml.dom.minidom}
module.  It's a lightweight implementation of the Level 1 DOM with support for
XML namespaces.  The  @code{parse()} and @code{parseString()} convenience
functions are provided for generating a DOM tree:

@example
from xml.dom import minidom
doc = minidom.parse('hamlet.xml')
@end example

@code{doc} is a @code{Document} instance.  @code{Document}, like all the other
DOM classes such as @code{Element} and @code{Text}, is a subclass of the
@code{Node} base class.  All the nodes in a DOM tree therefore support certain
common methods, such as @code{toxml()} which returns a string containing the XML
representation of the node and its children.  Each class also has special
methods of its own; for example, @code{Element} and @code{Document}
instances have a method to find all child elements with a given tag name.
Continuing from the previous 2-line example:

@example
perslist = doc.getElementsByTagName( 'PERSONA' )
print perslist[0].toxml()
print perslist[1].toxml()
@end example

`Hamlet' XML ファイルに対して上の例は以下のような出力をします:

@example
<PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
<PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>
@end example

ドキュメントのルートエレメントは @code{doc.documentElement} として取得出来、その子は簡単に、ノードを削除したり追加したりすることで修正出来ます:

@example
root = doc.documentElement

# Remove the first child
root.removeChild( root.childNodes[0] )

# Move the new first child to the end
root.appendChild( root.childNodes[0] )

# Insert the new first child (originally,
# the third child) before the 20th child.
root.insertBefore( root.childNodes[0], root.childNodes[20] )
@end example

Again, I will refer you to the Python documentation for a complete listing of
the different @code{Node} classes and their various methods.

@node PyXML との関係,,DOM サポート,XML モジュール
@anchor{whatsnew/2 0 relationship-to-pyxml}@anchor{1760}
@subsubsection PyXML との関係


The XML Special Interest Group has been working on XML-related Python code for a
while.  Its code distribution, called PyXML, is available from the SIG's web
pages at @indicateurl{https://www.python.org/community/sigs/current/xml-sig}. The PyXML distribution also used
the package name @code{xml}.  If you've written programs that used PyXML, you're
probably wondering about its compatibility with the 2.0 @ref{126,,xml} package.

結論として、Python 2.0 の @ref{126,,xml} パッケージは PyXML と互換性がありません。ですが、直近バージョンの PyXML をインストールすることで互換性を持たせることができます。 多くのアプリケーションは Python 2.0 に含まれる XML サポートで十分ですが、より複雑なアプリケーションは完全なPyXML パッケージをインストールする必要があります。 インストールされた PyXML バージョン 0.6.0 以上は、Python に同梱されている @ref{126,,xml} パッケージを置き換え、標準パッケージの厳密なスーパーセットとなり、多くの追加機能が追加されます。 PyXML の追加機能には次のようなものがあります。


@itemize *

@item 
4DOM, a full DOM implementation from FourThought, Inc.

@item 
The xmlproc validating parser, written by Lars Marius Garshol.

@item 
The @code{sgmlop} parser accelerator module, written by Fredrik Lundh.
@end itemize

@c ======================================================================

@node 更新されたモジュール,新しいモジュール<2>,XML モジュール,What's New in Python 2 0
@anchor{whatsnew/2 0 module-changes}@anchor{1761}
@subsection 更新されたモジュール


Lots of improvements and bugfixes were made to Python's extensive standard
library; some of the affected modules include @ref{bf,,readline},
@ref{26,,ConfigParser}, @code{cgi}, @ref{15,,calendar}, @ref{b2,,posix}, @ref{bf,,readline},
@code{xmllib}, @code{aifc}, @code{chunk}, @ref{119,,wave}, @ref{bd,,random}, @ref{c8,,shelve},
and @code{nntplib}.  Consult the CVS logs for the exact patch-by-patch details.

Brian Gallew contributed OpenSSL support for the @ref{d1,,socket} module.  OpenSSL
is an implementation of the Secure Socket Layer, which encrypts the data being
sent over a socket.  When compiling Python, you can edit @code{Modules/Setup}
to include SSL support, which adds an additional function to the @ref{d1,,socket}
module: @code{socket.ssl(socket, keyfile, certfile)}, which takes a socket
object and returns an SSL socket.  The @ref{72,,httplib} and @ref{10e,,urllib} modules
were also changed to support @code{https://} URLs, though no one has implemented
FTP or SMTP over SSL.

The @ref{72,,httplib} module has been rewritten by Greg Stein to support HTTP/1.1.

Backward compatibility with the 1.5 version of @code{httplib} is provided,
though using HTTP/1.1 features such as pipelining will require rewriting code to
use a different set of interfaces.

The @code{Tkinter} module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and
support for the older 7.x versions has been dropped.  The Tkinter module now
supports displaying Unicode strings in Tk widgets. Also, Fredrik Lundh
contributed an optimization which makes operations like @code{create_line} and
@code{create_polygon} much faster, especially when using lots of coordinates.

@ref{2f,,curses} モジュールが、Oliver Andrich による拡張版をもとに大規模に拡張され、ncurses と SYSV curses からの多くの追加機能、例えば色付きの表示、別の文字集合サポート、パッド、マウスサポートなどをサポートするようになりました。このことは、モジュールが BSD curses だけしか持っていない OS とは互換性が無いことを意味しますが、現在メンテナンスされている OS でそういう類のものは無さそうです。

2.0 の Unicode サポートについて前述したように、 @ref{be,,re} モジュールで提供される正規表現の根底となる実装が変更されました。SRE は新しい正規表現エンジンで、Fredrik Lundh によって書かれ、部分的に Hewlett Packard 社により寄贈されました。これは 8 ビット文字列と Unicode 文字列両方に合致するようサポートされています。

@c ======================================================================

@node 新しいモジュール<2>,IDLE の改善,更新されたモジュール,What's New in Python 2 0
@anchor{whatsnew/2 0 new-modules}@anchor{1762}
@subsection 新しいモジュール


数多くのモジュールが新しく追加されました。ここではそれらを短い説明とともに列挙するだけにします。特定のモジュールの詳細は 2.0 のドキュメントを調べてください。


@itemize *

@item 
@ref{d,,atexit}: Python インタプリタが終了する前に呼び出す関数を登録します。これまで @code{sys.exitfunc} に直接セットしてきたコードは  @ref{d,,atexit} モジュールを代わりに用いるように修正してください。 @ref{d,,atexit} をインポートし、 @ref{a7e,,atexit.register()} で終了時に呼び出す関数を登録します。(Contributed by Skip Montanaro.)

@item 
@ref{1c,,codecs}, @code{encodings}, @ref{10b,,unicodedata}:  Added as part of the new
Unicode support.

@item 
@ref{5e,,filecmp}: Supersedes the old @code{cmp}, @code{cmpcache} and
@code{dircmp} modules, which have now become deprecated. (Contributed by Gordon
MacMillan and Moshe Zadka.)

@item 
@ref{67,,gettext}: このモジュールは Python プログラムに、GNU gettext メッセージカタログライブラリへのインターフェイスを提供することで国際化 (I18N=internationalization) と地域化 (L10N=localization) サポートをもたらします。 (Integrated by Barry Warsaw, from separate contributions by Martin von Löwis, Peter Funk, and James Henstridge.)

@item 
@code{linuxaudiodev}: Support for the @code{/dev/audio} device on Linux, a
twin to the existing @code{sunaudiodev} module. (Contributed by Peter Bosch,
with fixes by Jeremy Hylton.)

@item 
@ref{94,,mmap}: Windows、Unix 両方でのメモリマップドファイルへのインターフェイスです。ファイル内容をメモリに直接マッピング出来、それは @ref{15ba,,mutable} な文字列であるかのように振る舞い、これにより読み書き出来ます。それらは例えば @ref{be,,re} モジュールのような普通は文字列を期待するような関数にさえも渡せます。(Contributed by Sam Rushing, with some extensions by A.M. Kuchling.)

@item 
@code{pyexpat}: An interface to the Expat XML parser. (Contributed by Paul
Prescod.)

@item 
@ref{113,,robotparser}: Parse a @code{robots.txt} file, which is used for writing
web spiders that politely avoid certain areas of a web site.  The parser accepts
the contents of a @code{robots.txt} file, builds a set of rules from it, and
can then answer questions about the fetchability of a given URL.  (Contributed
by Skip Montanaro.)

@item 
@ref{e3,,tabnanny}: Python ソースコードが曖昧なインデントになっていないかをチェックするモジュール/スクリプトです。 (Contributed by Tim Peters.)

@item 
@code{UserString}: A base class useful for deriving objects that behave like
strings.

@item 
@ref{11b,,webbrowser}: 指定した URL で、プラットフォームに依存しない方法でウェブブラウザを起動するモジュールです。個々のプラットフォームにおいて様々なブラウザが特定の順序で試されます。ユーザはどのブラウザを起動するかを環境変数 `BROWSER' をセットすることで変更出来ます。(元々は Eric S. Raymond による @ref{10e,,urllib} への、同じ機能追加をするパッチに触発されましたが、最終的なモジュールは Fred Drake が元々 @code{Tools/idle/BrowserControl.py} として実装したものに由来し、Fred が標準ライブラリに適合させました。)

@item 
@ref{11c,,_winreg}: An interface to the Windows registry.  @code{_winreg} is an
adaptation of functions that have been part of PythonWin since 1995, but has now
been added to the core  distribution, and enhanced to support Unicode.
@code{_winreg} was written by Bill Tutt and Mark Hammond.

@item 
@ref{137,,zipfile}: ZIP 形式アーカイブの読み書きのためのモジュールです。DOS/Windows での @code{PKZIP} や Unix での @code{zip} により生成されるアーカイブで、 @code{gzip} 形式とは混同しないで下さい (こちらは @ref{6b,,gzip} モジュールによってサポートされています)。(Contributed by James C. Ahlstrom.)

@item 
@code{imputil}: A module that provides a simpler way for writing customized
import hooks, in comparison to the existing @code{ihooks} module.  (Implemented
by Greg Stein, with much discussion on python-dev along the way.)
@end itemize

@c ======================================================================

@node IDLE の改善,削除されたモジュール、非推奨となったモジュール,新しいモジュール<2>,What's New in Python 2 0
@anchor{whatsnew/2 0 idle-improvements}@anchor{1763}
@subsection IDLE の改善


IDLE は公式の Python のクロスプラットフォームな IDE で、 Tkinter を使って書かれています。Python 2.0 では IDLE 0.6 を含めました。これは多くの新機能追加と改善がなされています。以下はその一部です:


@itemize *

@item 
UI の、特にシンタックスハイライトと自動インデントの領域において、改善と最適化がなされました。

@item 
クラスブラウザで、例えばモジュール内のトップレベル関数のような、より多くの情報をみることが出来るようになりました。

@item 
タブ幅をユーザ制御出来るようになりました。既存の Python ファイルを操作する際には、IDLE は自動的にインデントの慣習を検知してそれに合わせます。

@item 
色々なプラットフォームでブラウザの呼び出しがサポートされています。これを使って、ブラウザで Python ドキュメントを開きます。

@item 
IDLE がコマンドラインを持つようになりました。これは普通の Python インタプリタに大きく似せてあります。

@item 
色々な場所でコンテキストヘルプが出るようになっています。

@item 
IDLE は今ではパッケージとしてインストール出来ます。

@item 
エディタウィンドウ内では、下部に行/桁を表示するようになっています。

@item 
新たな 3 つのキーストロークコマンド: モジュールのチェック (@code{Alt}-@code{F5})、モジュールのインポート (@code{F5})、スクリプト実行 (@code{Ctrl}-@code{F5}).
@end itemize

@c ======================================================================

@node 削除されたモジュール、非推奨となったモジュール,謝辞<8>,IDLE の改善,What's New in Python 2 0
@anchor{whatsnew/2 0 deleted-and-deprecated-modules}@anchor{1764}
@subsection 削除されたモジュール、非推奨となったモジュール


A few modules have been dropped because they're obsolete, or because there are
now better ways to do the same thing.  The @code{stdwin} module is gone; it was
for a platform-independent windowing toolkit that's no longer developed.

A number of modules have been moved to the @code{lib-old} subdirectory:
@code{cmp}, @code{cmpcache}, @code{dircmp}, @code{dump},  @code{find},
@code{grep}, @code{packmail},  @code{poly}, @code{util}, @code{whatsound},
@code{zmod}.  If you have code which relies on a module  that's been moved to
@code{lib-old}, you can simply add that directory to @code{sys.path}   to get them
back, but you're encouraged to update any code that uses these modules.

@node 謝辞<8>,,削除されたモジュール、非推奨となったモジュール,What's New in Python 2 0
@anchor{whatsnew/2 0 acknowledgements}@anchor{1765}
@subsection 謝辞


著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の人々に感謝します:  David Bolen, Mark Hammond, Gregg Hauser, Jeremy Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch, Skip Montanaro, Vladimir Marangozov, Tobias Polzin, Guido van Rossum, Neil Schemenauer, and Russ Schmidt.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

"変更履歴" は、 Misc/NEWS.d@footnote{https://github.com/python/cpython/tree/3.14/Misc/NEWS.d} ディレクトリ以下の内容から ビルドされたファイル@footnote{https://pypi.org/project/blurb/} の HTML 版で、現在のバージョンの Python への `すべての' 重要な変更が載っています。

@node 変更履歴,,What's New in Python 2 0,What's New in Python
@anchor{whatsnew/changelog doc}@anchor{1766}@anchor{whatsnew/changelog changelog}@anchor{142}@anchor{whatsnew/changelog id1}@anchor{1767}@anchor{whatsnew/changelog translation-repo}@anchor{1768}
@section 変更履歴


@menu
* Python next:: 
* Python 3.14.3 final: Python 3 14 3 final. 
* Python 3.14.2 final: Python 3 14 2 final. 
* Python 3.14.1 final: Python 3 14 1 final. 
* Python 3.14.0 final: Python 3 14 0 final. 
* Python 3.14.0 release candidate 3: Python 3 14 0 release candidate 3. 
* Python 3.14.0 release candidate 2: Python 3 14 0 release candidate 2. 
* Python 3.14.0 release candidate 1: Python 3 14 0 release candidate 1. 
* Python 3.14.0 beta 4: Python 3 14 0 beta 4. 
* Python 3.14.0 beta 3: Python 3 14 0 beta 3. 
* Python 3.14.0 beta 2: Python 3 14 0 beta 2. 
* Python 3.14.0 beta 1: Python 3 14 0 beta 1. 
* Python 3.14.0 alpha 7: Python 3 14 0 alpha 7. 
* Python 3.14.0 alpha 6: Python 3 14 0 alpha 6. 
* Python 3.14.0 alpha 5: Python 3 14 0 alpha 5. 
* Python 3.14.0 alpha 4: Python 3 14 0 alpha 4. 
* Python 3.14.0 alpha 3: Python 3 14 0 alpha 3. 
* Python 3.14.0 alpha 2: Python 3 14 0 alpha 2. 
* Python 3.14.0 alpha 1: Python 3 14 0 alpha 1. 
* Python 3.13.0 beta 1: Python 3 13 0 beta 1. 
* Python 3.13.0 alpha 6: Python 3 13 0 alpha 6. 
* Python 3.13.0 alpha 5: Python 3 13 0 alpha 5. 
* Python 3.13.0 alpha 4: Python 3 13 0 alpha 4. 
* Python 3.13.0 alpha 3: Python 3 13 0 alpha 3. 
* Python 3.13.0 alpha 2: Python 3 13 0 alpha 2. 
* Python 3.13.0 alpha 1: Python 3 13 0 alpha 1. 
* Python 3.12.0 beta 1: Python 3 12 0 beta 1. 
* Python 3.12.0 alpha 7: Python 3 12 0 alpha 7. 
* Python 3.12.0 alpha 6: Python 3 12 0 alpha 6. 
* Python 3.12.0 alpha 5: Python 3 12 0 alpha 5. 
* Python 3.12.0 alpha 4: Python 3 12 0 alpha 4. 
* Python 3.12.0 alpha 3: Python 3 12 0 alpha 3. 
* Python 3.12.0 alpha 2: Python 3 12 0 alpha 2. 
* Python 3.12.0 alpha 1: Python 3 12 0 alpha 1. 
* Python 3.11.0 beta 1: Python 3 11 0 beta 1. 
* Python 3.11.0 alpha 7: Python 3 11 0 alpha 7. 
* Python 3.11.0 alpha 6: Python 3 11 0 alpha 6. 
* Python 3.11.0 alpha 5: Python 3 11 0 alpha 5. 
* Python 3.11.0 alpha 4: Python 3 11 0 alpha 4. 
* Python 3.11.0 alpha 3: Python 3 11 0 alpha 3. 
* Python 3.11.0 alpha 2: Python 3 11 0 alpha 2. 
* Python 3.11.0 alpha 1: Python 3 11 0 alpha 1. 
* Python 3.10.0 beta 1: Python 3 10 0 beta 1. 
* Python 3.10.0 alpha 7: Python 3 10 0 alpha 7. 
* Python 3.10.0 alpha 6: Python 3 10 0 alpha 6. 
* Python 3.10.0 alpha 5: Python 3 10 0 alpha 5. 
* Python 3.10.0 alpha 4: Python 3 10 0 alpha 4. 
* Python 3.10.0 alpha 3: Python 3 10 0 alpha 3. 
* Python 3.10.0 alpha 2: Python 3 10 0 alpha 2. 
* Python 3.10.0 alpha 1: Python 3 10 0 alpha 1. 
* Python 3.9.0 beta 1: Python 3 9 0 beta 1. 
* Python 3.9.0 alpha 6: Python 3 9 0 alpha 6. 
* Python 3.9.0 alpha 5: Python 3 9 0 alpha 5. 
* Python 3.9.0 alpha 4: Python 3 9 0 alpha 4. 
* Python 3.9.0 alpha 3: Python 3 9 0 alpha 3. 
* Python 3.9.0 alpha 2: Python 3 9 0 alpha 2. 
* Python 3.9.0 alpha 1: Python 3 9 0 alpha 1. 
* Python 3.8.0 beta 1: Python 3 8 0 beta 1. 
* Python 3.8.0 alpha 4: Python 3 8 0 alpha 4. 
* Python 3.8.0 alpha 3: Python 3 8 0 alpha 3. 
* Python 3.8.0 alpha 2: Python 3 8 0 alpha 2. 
* Python 3.8.0 alpha 1: Python 3 8 0 alpha 1. 
* Python 3.7.0 final: Python 3 7 0 final. 
* Python 3.7.0 release candidate 1: Python 3 7 0 release candidate 1. 
* Python 3.7.0 beta 5: Python 3 7 0 beta 5. 
* Python 3.7.0 beta 4: Python 3 7 0 beta 4. 
* Python 3.7.0 beta 3: Python 3 7 0 beta 3. 
* Python 3.7.0 beta 2: Python 3 7 0 beta 2. 
* Python 3.7.0 beta 1: Python 3 7 0 beta 1. 
* Python 3.7.0 alpha 4: Python 3 7 0 alpha 4. 
* Python 3.7.0 alpha 3: Python 3 7 0 alpha 3. 
* Python 3.7.0 alpha 2: Python 3 7 0 alpha 2. 
* Python 3.7.0 alpha 1: Python 3 7 0 alpha 1. 
* Python 3.6.6 final: Python 3 6 6 final. 
* Python 3.6.6 release candidate 1: Python 3 6 6 release candidate 1. 
* Python 3.6.5 final: Python 3 6 5 final. 
* Python 3.6.5 release candidate 1: Python 3 6 5 release candidate 1. 
* Python 3.6.4 final: Python 3 6 4 final. 
* Python 3.6.4 release candidate 1: Python 3 6 4 release candidate 1. 
* Python 3.6.3 final: Python 3 6 3 final. 
* Python 3.6.3 release candidate 1: Python 3 6 3 release candidate 1. 
* Python 3.6.2 final: Python 3 6 2 final. 
* Python 3.6.2 release candidate 2: Python 3 6 2 release candidate 2. 
* Python 3.6.2 release candidate 1: Python 3 6 2 release candidate 1. 
* Python 3.6.1 final: Python 3 6 1 final. 
* Python 3.6.1 release candidate 1: Python 3 6 1 release candidate 1. 
* Python 3.6.0 final: Python 3 6 0 final. 
* Python 3.6.0 release candidate 2: Python 3 6 0 release candidate 2. 
* Python 3.6.0 release candidate 1: Python 3 6 0 release candidate 1. 
* Python 3.6.0 beta 4: Python 3 6 0 beta 4. 
* Python 3.6.0 beta 3: Python 3 6 0 beta 3. 
* Python 3.6.0 beta 2: Python 3 6 0 beta 2. 
* Python 3.6.0 beta 1: Python 3 6 0 beta 1. 
* Python 3.6.0 alpha 4: Python 3 6 0 alpha 4. 
* Python 3.6.0 alpha 3: Python 3 6 0 alpha 3. 
* Python 3.6.0 alpha 2: Python 3 6 0 alpha 2. 
* Python 3.6.0 alpha 1: Python 3 6 0 alpha 1. 
* Python 3.5.5 final: Python 3 5 5 final. 
* Python 3.5.5 release candidate 1: Python 3 5 5 release candidate 1. 
* Python 3.5.4 final: Python 3 5 4 final. 
* Python 3.5.4 release candidate 1: Python 3 5 4 release candidate 1. 
* Python 3.5.3 final: Python 3 5 3 final. 
* Python 3.5.3 release candidate 1: Python 3 5 3 release candidate 1. 
* Python 3.5.2 final: Python 3 5 2 final. 
* Python 3.5.2 release candidate 1: Python 3 5 2 release candidate 1. 
* Python 3.5.1 final: Python 3 5 1 final. 
* Python 3.5.1 release candidate 1: Python 3 5 1 release candidate 1. 
* Python 3.5.0 final: Python 3 5 0 final. 
* Python 3.5.0 release candidate 4: Python 3 5 0 release candidate 4. 
* Python 3.5.0 release candidate 3: Python 3 5 0 release candidate 3. 
* Python 3.5.0 release candidate 2: Python 3 5 0 release candidate 2. 
* Python 3.5.0 release candidate 1: Python 3 5 0 release candidate 1. 
* Python 3.5.0 beta 4: Python 3 5 0 beta 4. 
* Python 3.5.0 beta 3: Python 3 5 0 beta 3. 
* Python 3.5.0 beta 2: Python 3 5 0 beta 2. 
* Python 3.5.0 beta 1: Python 3 5 0 beta 1. 
* Python 3.5.0 alpha 4: Python 3 5 0 alpha 4. 
* Python 3.5.0 alpha 3: Python 3 5 0 alpha 3. 
* Python 3.5.0 alpha 2: Python 3 5 0 alpha 2. 
* Python 3.5.0 alpha 1: Python 3 5 0 alpha 1. 

@end menu

@node Python next,Python 3 14 3 final,,変更履歴
@anchor{whatsnew/changelog python-next}@anchor{1769}
@subsection Python next


`Release date: XXXX-XX-XX'

@menu
* macOS:: 
* Windows:: 
* ライブラリ:: 
* ドキュメント: ドキュメント<2>. 
* Core and Builtins:: 

@end menu

@node macOS,Windows,,Python next
@anchor{whatsnew/changelog macos}@anchor{176a}
@subsubsection macOS



@itemize -

@item 
gh-144551@footnote{https://github.com/python/cpython/issues/144551}: Update macOS installer to use OpenSSL 3.0.19.
@end itemize

@node Windows,ライブラリ,macOS,Python next
@anchor{whatsnew/changelog windows}@anchor{176b}
@subsubsection Windows



@itemize -

@item 
gh-144551@footnote{https://github.com/python/cpython/issues/144551}: Updated bundled version of OpenSSL to 3.0.19.
@end itemize

@node ライブラリ,ドキュメント<2>,Windows,Python next
@anchor{whatsnew/changelog library}@anchor{176c}
@subsubsection ライブラリ



@itemize -

@item 
gh-144833@footnote{https://github.com/python/cpython/issues/144833}: Fixed a use-after-free in @ref{d5,,ssl} when @code{SSL_new()} returns
NULL in @code{newPySSLSocket()}. The error was reported via a dangling
pointer after the object had already been freed.

@item 
gh-144782@footnote{https://github.com/python/cpython/issues/144782}: Fix @ref{1bd,,argparse.ArgumentParser} to be @ref{ab,,pickleable}.

@item 
gh-144538@footnote{https://github.com/python/cpython/issues/144538}: Bump the version of pip bundled in ensurepip to version 26.0.1

@item 
gh-144494@footnote{https://github.com/python/cpython/issues/144494}: Fix performance regression in @ref{b4f,,asyncio.all_tasks()} on
@ref{176d,,free-threaded builds}. Patch by Kumar Aditya.

@item 
gh-144363@footnote{https://github.com/python/cpython/issues/144363}: Update bundled libexpat@footnote{https://libexpat.github.io/} to
2.7.4

@item 
gh-143637@footnote{https://github.com/python/cpython/issues/143637}: Fixed a crash in socket.sendmsg() that could occur if ancillary
data is mutated re-entrantly during argument parsing.

@item 
gh-143543@footnote{https://github.com/python/cpython/issues/143543}: Fix a crash in itertools.groupby that could occur when a
user-defined @ref{cf2,,__eq__()} method re-enters the iterator during
key comparison.

@item 
gh-140652@footnote{https://github.com/python/cpython/issues/140652}: Fix a crash in @code{_interpchannels.list_all()} after closing
a channel.

@item 
gh-80667@footnote{https://github.com/python/cpython/issues/80667}: Support lookup for Tangut Ideographs in @ref{10b,,unicodedata}.

@item 
bpo-40243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40243}: Fix @code{unicodedata.ucd_3_2_0.numeric()} for non-decimal
values.
@end itemize

@node ドキュメント<2>,Core and Builtins,ライブラリ,Python next
@anchor{whatsnew/changelog documentation}@anchor{176e}
@subsubsection ドキュメント



@itemize -

@item 
gh-136246@footnote{https://github.com/python/cpython/issues/136246}: A new "Improve this page" link is available in the left-hand
sidebar of the docs, offering links to create GitHub issues, discussion
forum posts, or pull requests.
@end itemize

@node Core and Builtins,,ドキュメント<2>,Python next
@anchor{whatsnew/changelog core-and-builtins}@anchor{176f}
@subsubsection Core and Builtins



@itemize -

@item 
gh-144766@footnote{https://github.com/python/cpython/issues/144766}: Fix a crash in fork child process when perf support is enabled.

@item 
gh-144759@footnote{https://github.com/python/cpython/issues/144759}: Fix undefined behavior in the lexer when @code{start} and
@code{multi_line_start} pointers are @code{NULL} in
@code{_PyLexer_remember_fstring_buffers()} and
@code{_PyLexer_restore_fstring_buffers()}. The @code{NULL} pointer arithmetic
(@code{NULL - valid_pointer}) is now guarded with explicit @code{NULL} checks.

@item 
gh-144563@footnote{https://github.com/python/cpython/issues/144563}: Fix interaction of the Tachyon profiler and @ref{2e,,ctypes} and
other modules that load the Python shared library (if present) in an
independent map as this was causing the mechanism that loads the binary
information to be confused. Patch by Pablo Galindo

@item 
gh-144601@footnote{https://github.com/python/cpython/issues/144601}: Fix crash when importing a module whose @code{PyInit} function
raises an exception from a subinterpreter.

@item 
gh-144446@footnote{https://github.com/python/cpython/issues/144446}: Fix data races in the free-threaded build when reading frame
object attributes while another thread is executing the frame.

@item 
gh-143650@footnote{https://github.com/python/cpython/issues/143650}: Fix race condition in @ref{7b,,importlib} where a thread could
receive a stale module reference when another thread's import fails.

@item 
gh-80667@footnote{https://github.com/python/cpython/issues/80667}: Literals using the @code{\N@{name@}} escape syntax can now construct
CJK ideographs and Hangul syllables using case-insensitive names.
@end itemize

@node Python 3 14 3 final,Python 3 14 2 final,Python next,変更履歴
@anchor{whatsnew/changelog python-3-14-3-final}@anchor{1770}
@subsection Python 3.14.3 final


`Release date: 2026-02-03'

@menu
* Windows: Windows<2>. 
* Tools/Demos:: 
* テスト:: 
* セキュリティ:: 
* ライブラリ: ライブラリ<2>. 
* IDLE: IDLE<3>. 
* ドキュメント: ドキュメント<3>. 
* Core and Builtins: Core and Builtins<2>. 
* C API:: 
* ビルド:: 

@end menu

@node Windows<2>,Tools/Demos,,Python 3 14 3 final
@anchor{whatsnew/changelog id2}@anchor{1771}
@subsubsection Windows



@itemize -

@item 
gh-128067@footnote{https://github.com/python/cpython/issues/128067}: Fix a bug in PyREPL on Windows where output without a trailing
newline was overwritten by the next prompt.
@end itemize

@node Tools/Demos,テスト,Windows<2>,Python 3 14 3 final
@anchor{whatsnew/changelog tools-demos}@anchor{1772}
@subsubsection Tools/Demos



@itemize -

@item 
gh-142095@footnote{https://github.com/python/cpython/issues/142095}: Make gdb 'py-bt' command use frame from thread local state when
available. Patch by Sam Gross and Victor Stinner.
@end itemize

@node テスト,セキュリティ,Tools/Demos,Python 3 14 3 final
@anchor{whatsnew/changelog tests}@anchor{1773}
@subsubsection テスト



@itemize -

@item 
gh-144415@footnote{https://github.com/python/cpython/issues/144415}: The Android testbed now distinguishes between stdout/stderr
messages which were triggered by a newline, and those triggered by a
manual call to @code{flush}. This fixes logging of progress indicators and
similar content.

@item 
gh-143460@footnote{https://github.com/python/cpython/issues/143460}: Skip tests relying on infinite recusion if stack size is
unlimited.

@item 
gh-65784@footnote{https://github.com/python/cpython/issues/65784}: Add support for parametrized resource @code{wantobjects} in
regrtests, which allows to run Tkinter tests with the specified value of
@code{tkinter.wantobjects}, for example @code{-u wantobjects=0}.

@item 
gh-143553@footnote{https://github.com/python/cpython/issues/143553}: Add support for parametrized resources, such as @code{-u
xpickle=2.7}.

@item 
gh-142836@footnote{https://github.com/python/cpython/issues/142836}: Accommodated Solaris in
@code{test_pdb.test_script_target_anonymous_pipe}.

@item 
bpo-31391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31391}: Forward-port test_xpickle from Python 2 to Python 3 and add the
resource back to test's command line.
@end itemize

@node セキュリティ,ライブラリ<2>,テスト,Python 3 14 3 final
@anchor{whatsnew/changelog security}@anchor{1774}
@subsubsection セキュリティ



@itemize -

@item 
gh-144125@footnote{https://github.com/python/cpython/issues/144125}: @ref{13e7,,BytesGenerator} will now refuse to
serialize (write) headers that are unsafely folded or delimited; see
@ref{4f2,,verify_generated_headers}. (Contributed by Bas
Bloemsaat and Petr Viktorin in gh-121650@footnote{https://github.com/python/cpython/issues/121650}).

@item 
gh-143935@footnote{https://github.com/python/cpython/issues/143935}: Fixed a bug in the folding of comments when flattening an email
message using a modern email policy. Comments consisting of a very long
sequence of non-foldable characters could trigger a forced line wrap that
omitted the required leading space on the continuation line, causing the
remainder of the comment to be interpreted as a new header field. This
enabled header injection with carefully crafted inputs.

@item 
gh-143925@footnote{https://github.com/python/cpython/issues/143925}: Reject control characters in @code{data:} URL media types.

@item 
gh-143919@footnote{https://github.com/python/cpython/issues/143919}: Reject control characters in @ref{dfe,,http.cookies.Morsel}
fields and values.

@item 
gh-143916@footnote{https://github.com/python/cpython/issues/143916}: Reject C0 control characters within wsgiref.headers.Headers
fields, values, and parameters.
@end itemize

@node ライブラリ<2>,IDLE<3>,セキュリティ,Python 3 14 3 final
@anchor{whatsnew/changelog id3}@anchor{1775}
@subsubsection ライブラリ



@itemize -

@item 
gh-144380@footnote{https://github.com/python/cpython/issues/144380}: Improve performance of @ref{1427,,io.BufferedReader} line
iteration by ~49%.

@item 
gh-144169@footnote{https://github.com/python/cpython/issues/144169}: Fix three crashes when non-string keyword arguments are
supplied to objects in the @ref{9,,ast} module.

@item 
gh-144100@footnote{https://github.com/python/cpython/issues/144100}: Fixed a crash in ctypes when using a deprecated
@code{POINTER(str)} type in @code{argtypes}. Instead of aborting, ctypes now
raises a proper Python exception when the pointer target type is
unresolved.

@item 
gh-144050@footnote{https://github.com/python/cpython/issues/144050}: Fix @ref{1363,,stat.filemode()} in the pure-Python implementation to
avoid misclassifying invalid mode values as block devices.

@item 
gh-144023@footnote{https://github.com/python/cpython/issues/144023}: Fixed validation of file descriptor 0 in posix functions when
used with follow_symlinks parameter.

@item 
gh-143999@footnote{https://github.com/python/cpython/issues/143999}: Fix an issue where @ref{144e,,inspect.getgeneratorstate()} and
@ref{101a,,inspect.getcoroutinestate()} could fail for generators wrapped by
@ref{1088,,types.coroutine()} in the suspended state.

@item 
gh-143831@footnote{https://github.com/python/cpython/issues/143831}: @ref{1776,,annotationlib.ForwardRef} objects are now hashable when
created from annotation scopes with closures. Previously, hashing such
objects would throw an exception. Patch by Bartosz Sławecki.

@item 
gh-143874@footnote{https://github.com/python/cpython/issues/143874}: Fixed a bug in @ref{aa,,pdb} where expression results were not
sent back to remote client.

@item 
gh-143880@footnote{https://github.com/python/cpython/issues/143880}: Fix data race in @ref{217,,functools.partial()} in the @ref{1f4,,free threading} build.

@item 
gh-143706@footnote{https://github.com/python/cpython/issues/143706}: Fix @ref{98,,multiprocessing} forkserver so that @ref{147c,,sys.argv}
is correctly set before @code{__main__} is preloaded. Previously,
@ref{147c,,sys.argv} was empty during main module import in forkserver child
processes. This fixes a regression introduced in 3.13.8 and 3.14.1. Root
caused by Aaron Wieczorek, test provided by Thomas Watson, thanks!

@item 
gh-143638@footnote{https://github.com/python/cpython/issues/143638}: Forbid reentrant calls of the @ref{c13,,pickle.Pickler} and
@ref{1777,,pickle.Unpickler} methods for the C implementation. Previously,
this could cause crash or data corruption, now concurrent calls of methods
of the same object raise @ref{244,,RuntimeError}.

@item 
gh-78724@footnote{https://github.com/python/cpython/issues/78724}: Raise @ref{244,,RuntimeError}'s when user attempts to call methods
on half-initialized @ref{1778,,Struct} objects, For example, created
by @code{Struct.__new__(Struct)}.  Patch by Sergey B Kirpichev.

@item 
gh-143196@footnote{https://github.com/python/cpython/issues/143196}: Fix crash when the internal encoder object returned by
undocumented function @code{json.encoder.c_make_encoder()} was called with
non-zero second (`_current_indent_level') argument.

@item 
gh-143191@footnote{https://github.com/python/cpython/issues/143191}: @ref{1779,,_thread.stack_size()} now raises @ref{2ec,,ValueError} if the
stack size is too small. Patch by Victor Stinner.

@item 
gh-143602@footnote{https://github.com/python/cpython/issues/143602}: Fix a inconsistency issue in @ref{15c5,,write()} that
leads to unexpected buffer overwrite by deduplicating the buffer exports.

@item 
gh-143547@footnote{https://github.com/python/cpython/issues/143547}: Fix @ref{507,,sys.unraisablehook()} when the hook raises an
exception and changes @ref{507,,sys.unraisablehook()}: hold a strong reference
to the old hook. Patch by Victor Stinner.

@item 
gh-143517@footnote{https://github.com/python/cpython/issues/143517}: @ref{459,,annotationlib.get_annotations()} no longer raises a
@ref{18e,,SyntaxError} when evaluating a stringified starred annotation that
starts with one or more whitespace characters followed by a @code{*}. Patch
by Bartosz Sławecki.

@item 
gh-143378@footnote{https://github.com/python/cpython/issues/143378}: Fix use-after-free crashes when a @ref{10a4,,BytesIO} object
is concurrently mutated during @ref{15c5,,write()} or
@ref{177a,,writelines()}.

@item 
gh-143346@footnote{https://github.com/python/cpython/issues/143346}: Fix incorrect wrapping of the Base64 data in
@code{plistlib._PlistWriter} when the indent contains a mix of tabs and
spaces.

@item 
gh-143310@footnote{https://github.com/python/cpython/issues/143310}: @ref{f6,,tkinter}: fix a crash when a Python @ref{24d,,list} is
mutated during the conversion to a Tcl object (e.g., when setting a Tcl
variable). Patch by Bénédikt Tran.

@item 
gh-143309@footnote{https://github.com/python/cpython/issues/143309}: Fix a crash in @ref{1311,,os.execve()} on non-Windows platforms when
given a custom environment mapping which is then mutated during parsing.
Patch by Bénédikt Tran.

@item 
gh-143308@footnote{https://github.com/python/cpython/issues/143308}: @ref{ab,,pickle}: fix use-after-free crashes when a
@ref{177b,,PickleBuffer} is concurrently mutated by a custom buffer
callback during pickling. Patch by Bénédikt Tran and Aaron Wieczorek.

@item 
gh-143237@footnote{https://github.com/python/cpython/issues/143237}: Fix support of named pipes in the rotating @ref{8b,,logging}
handlers.

@item 
gh-143249@footnote{https://github.com/python/cpython/issues/143249}: Fix possible buffer leaks in Windows overlapped I/O on error
handling.

@item 
gh-143241@footnote{https://github.com/python/cpython/issues/143241}: @ref{13a,,zoneinfo}: fix infinite loop in @ref{177c,,ZoneInfo.from_file} when parsing a malformed TZif file. Patch
by Fatih Celik.

@item 
gh-142830@footnote{https://github.com/python/cpython/issues/142830}: @ref{d4,,sqlite3}: fix use-after-free crashes when the
connection's callbacks are mutated during a callback execution. Patch by
Bénédikt Tran.

@item 
gh-143200@footnote{https://github.com/python/cpython/issues/143200}: @ref{12b,,xml.etree.ElementTree}: fix use-after-free crashes in
@ref{588,,__getitem__()} and @ref{14e3,,__setitem__()} methods of
@ref{363,,Element} when the element is concurrently
mutated. Patch by Bénédikt Tran.

@item 
gh-142195@footnote{https://github.com/python/cpython/issues/142195}: Updated timeout evaluation logic in @ref{dc,,subprocess} to be
compatible with deterministic environments like Shadow where time moves
exactly as requested.

@item 
gh-142164@footnote{https://github.com/python/cpython/issues/142164}: Fix the ctypes bitfield overflow error message to report the
correct offset and size calculation.

@item 
gh-143145@footnote{https://github.com/python/cpython/issues/143145}: Fixed a possible reference leak in ctypes when constructing
results with multiple output parameters on error.

@item 
gh-122431@footnote{https://github.com/python/cpython/issues/122431}: Corrected the error message in
@ref{1051,,readline.append_history_file()} to state that @code{nelements} must be
non-negative instead of positive.

@item 
gh-143004@footnote{https://github.com/python/cpython/issues/143004}: Fix a potential use-after-free in
@ref{177d,,collections.Counter.update()} when user code mutates the Counter
during an update.

@item 
gh-143046@footnote{https://github.com/python/cpython/issues/143046}: The @ref{b,,asyncio} REPL no longer prints copyright and version
messages in the quiet mode (@ref{177e,,-q}). Patch by Bartosz Sławecki.

@item 
gh-140648@footnote{https://github.com/python/cpython/issues/140648}: The @ref{b,,asyncio} REPL now respects the @ref{b57,,-I} flag
(isolated mode). Previously, it would load and execute
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} even if the flag was set. Contributed by Bartosz
Sławecki.

@item 
gh-142991@footnote{https://github.com/python/cpython/issues/142991}: Fixed socket operations such as recvfrom() and sendto() for
FreeBSD divert(4) socket.

@item 
gh-143010@footnote{https://github.com/python/cpython/issues/143010}: Fixed a bug in @ref{8f,,mailbox} where the precise timing of an
external event could result in the library opening an existing file
instead of a file it expected to create.

@item 
gh-142881@footnote{https://github.com/python/cpython/issues/142881}: Fix concurrent and reentrant call of @ref{177f,,atexit.unregister()}.

@item 
gh-112127@footnote{https://github.com/python/cpython/issues/112127}: Fix possible use-after-free in @ref{177f,,atexit.unregister()} when
the callback is unregistered during comparison.

@item 
gh-142783@footnote{https://github.com/python/cpython/issues/142783}: Fix zoneinfo use-after-free with descriptor _weak_cache. a
descriptor as _weak_cache could cause crashes during object creation. The
fix ensures proper reference counting for descriptor-provided objects.

@item 
gh-142754@footnote{https://github.com/python/cpython/issues/142754}: Add the `ownerDocument' attribute to @ref{128,,xml.dom.minidom}
elements and attributes created by directly instantiating the @code{Element}
or @code{Attr} class. Note that this way of creating nodes is not supported;
creator functions like @ref{1780,,xml.dom.Document.documentElement()} should
be used instead.

@item 
gh-142784@footnote{https://github.com/python/cpython/issues/142784}: The @ref{b,,asyncio} REPL now properly closes the loop upon the
end of interactive session. Previously, it could cause surprising
warnings. Contributed by Bartosz Sławecki.

@item 
gh-142555@footnote{https://github.com/python/cpython/issues/142555}: @ref{8,,array}: fix a crash in @code{a[i] = v} when converting `i'
to an index via @ref{19e,,i.__index__} or
@ref{bc1,,i.__float__} mutates the array.

@item 
gh-142594@footnote{https://github.com/python/cpython/issues/142594}: Fix crash in @code{TextIOWrapper.close()} when the underlying
buffer's @code{closed} property calls @ref{1781,,detach()}.

@item 
gh-142451@footnote{https://github.com/python/cpython/issues/142451}: @ref{6e,,hmac}: Ensure that the @ref{114c,,HMAC.block_size} attribute is correctly copied by @ref{1782,,HMAC.copy}. Patch by Bénédikt Tran.

@item 
gh-142495@footnote{https://github.com/python/cpython/issues/142495}: @ref{13d4,,collections.defaultdict} now prioritizes
@ref{14e3,,__setitem__()} when inserting default values from
@code{default_factory}. This prevents race conditions where a default value
would overwrite a value set before @code{default_factory} returns.

@item 
gh-142651@footnote{https://github.com/python/cpython/issues/142651}: @ref{10d,,unittest.mock}: fix a thread safety issue where
@ref{1783,,Mock.call_count} may return
inaccurate values when the mock is called concurrently from multiple
threads.

@item 
gh-142595@footnote{https://github.com/python/cpython/issues/142595}: Added type check during initialization of the @ref{3a,,decimal}
module to prevent a crash in case of broken stdlib.  Patch by Sergey B
Kirpichev.

@item 
gh-142556@footnote{https://github.com/python/cpython/issues/142556}: Fix crash when a task gets re-registered during finalization in
@ref{b,,asyncio}. Patch by Kumar Aditya.

@item 
gh-123241@footnote{https://github.com/python/cpython/issues/123241}: Avoid reference count operations in garbage collection of
@ref{2e,,ctypes} objects.

@item 
gh-142517@footnote{https://github.com/python/cpython/issues/142517}: The non-@code{compat32} @ref{3f,,email} policies now correctly handle
refolding encoded words that contain bytes that can not be decoded in
their specified character set.  Previously this resulted in an encoding
exception during folding.

@item 
gh-112527@footnote{https://github.com/python/cpython/issues/112527}: The help text for required options in @ref{7,,argparse} no longer
extended with " (default: None)".

@item 
gh-142346@footnote{https://github.com/python/cpython/issues/142346}: Fix usage formatting for mutually exclusive groups in
@ref{7,,argparse} when they are preceded by positional arguments or followed
or intermixed with other optional arguments.

@item 
gh-142315@footnote{https://github.com/python/cpython/issues/142315}: Pdb can now run scripts from anonymous pipes used in process
substitution. Patch by Bartosz Sławecki.

@item 
gh-142332@footnote{https://github.com/python/cpython/issues/142332}: Fix usage formatting for positional arguments in mutually
exclusive groups in @ref{7,,argparse}. in @ref{7,,argparse}.

@item 
gh-142282@footnote{https://github.com/python/cpython/issues/142282}: Fix @ref{1784,,winreg.QueryValueEx()} to not accidentally read
garbage buffer under race condition.

@item 
gh-75949@footnote{https://github.com/python/cpython/issues/75949}: Fix @ref{7,,argparse} to preserve @code{|} separators in mutually
exclusive groups when the usage line wraps due to length.

@item 
gh-142267@footnote{https://github.com/python/cpython/issues/142267}: Improve @ref{7,,argparse} performance by caching the formatter
used for argument validation.

@item 
gh-68552@footnote{https://github.com/python/cpython/issues/68552}: @code{MisplacedEnvelopeHeaderDefect} and @code{Missing header name}
defects are now correctly passed to the @code{handle_defect} method of
@code{policy} in @ref{1785,,FeedParser}.

@item 
gh-142006@footnote{https://github.com/python/cpython/issues/142006}: Fix a bug in the @ref{12cc,,email.policy.default} folding algorithm
which incorrectly resulted in a doubled newline when a line ending at
exactly max_line_length was followed by an unfoldable token.

@item 
gh-105836@footnote{https://github.com/python/cpython/issues/105836}: Fix @ref{a82,,asyncio.run_coroutine_threadsafe()} leaving underlying
cancelled asyncio task running.

@item 
gh-139971@footnote{https://github.com/python/cpython/issues/139971}: @ref{ba,,pydoc}: Ensure that the link to the online documentation
of a @ref{1786,,stdlib} module is correct.

@item 
gh-139262@footnote{https://github.com/python/cpython/issues/139262}: Some keystrokes can be swallowed in the new @code{PyREPL} on
Windows, especially when used together with the ALT key. Fix by Chris
Eibl.

@item 
gh-138897@footnote{https://github.com/python/cpython/issues/138897}: Improved @ref{1787,,license}/@ref{1788,,copyright}/@ref{1789,,credits}
display in the @ref{491,,REPL}: now uses a pager.

@item 
gh-79986@footnote{https://github.com/python/cpython/issues/79986}: Add parsing for @code{References} and @code{In-Reply-To} headers to
the @ref{3f,,email} library that parses the header content as lists of
message id tokens.  This prevents them from being folded incorrectly.

@item 
gh-136282@footnote{https://github.com/python/cpython/issues/136282}: Add support for @ref{178a,,UNNAMED_SECTION} when
creating a section via the mapping protocol access

@item 
gh-109263@footnote{https://github.com/python/cpython/issues/109263}: Starting a process from spawn context in @ref{98,,multiprocessing}
no longer sets the start method globally.

@item 
gh-133253@footnote{https://github.com/python/cpython/issues/133253}: Fix thread-safety issues in @ref{89,,linecache}.

@item 
gh-132715@footnote{https://github.com/python/cpython/issues/132715}: Skip writing objects during marshalling once a failure has
occurred.
@end itemize

@node IDLE<3>,ドキュメント<3>,ライブラリ<2>,Python 3 14 3 final
@anchor{whatsnew/changelog idle}@anchor{178b}
@subsubsection IDLE



@itemize -

@item 
gh-143774@footnote{https://github.com/python/cpython/issues/143774}: Better explain the operation of Format / Format Paragraph.
@end itemize

@node ドキュメント<3>,Core and Builtins<2>,IDLE<3>,Python 3 14 3 final
@anchor{whatsnew/changelog id4}@anchor{178c}
@subsubsection ドキュメント



@itemize -

@item 
gh-140806@footnote{https://github.com/python/cpython/issues/140806}: Add documentation for @ref{178d,,enum.bin()}.
@end itemize

@node Core and Builtins<2>,C API,ドキュメント<3>,Python 3 14 3 final
@anchor{whatsnew/changelog id5}@anchor{178e}
@subsubsection Core and Builtins



@itemize -

@item 
gh-144307@footnote{https://github.com/python/cpython/issues/144307}: Prevent a reference leak in module teardown at interpreter
finalization.

@item 
gh-144194@footnote{https://github.com/python/cpython/issues/144194}: Fix error handling in perf jitdump initialization on memory
allocation failure.

@item 
gh-144012@footnote{https://github.com/python/cpython/issues/144012}: Check if the result is @code{NULL} in @code{BINARY_OP_EXTENT} opcode.

@item 
gh-141805@footnote{https://github.com/python/cpython/issues/141805}: Fix crash in @ref{184,,set} when objects with the same hash are
concurrently added to the set after removing an element with the same hash
while the set still contains elements with the same hash.

@item 
gh-143670@footnote{https://github.com/python/cpython/issues/143670}: Fixes a crash in @code{ga_repr_items_list} function.

@item 
gh-143377@footnote{https://github.com/python/cpython/issues/143377}: Fix a crash in @code{_interpreters.capture_exception()} when
the exception is incorrectly formatted. Patch by Bénédikt Tran.

@item 
gh-136924@footnote{https://github.com/python/cpython/issues/136924}: The interactive help mode in the @ref{491,,REPL} no longer
incorrectly syntax highlights text input as Python code. Contributed by
Olga Matoula.

@item 
gh-143189@footnote{https://github.com/python/cpython/issues/143189}: Fix crash when inserting a non-@ref{169,,str} key into a split
table dictionary when the key matches an existing key in the split table
but has no corresponding value in the dict.

@item 
gh-143228@footnote{https://github.com/python/cpython/issues/143228}: Fix use-after-free in perf trampoline when toggling profiling
while threads are running or during interpreter finalization with daemon
threads active. The fix uses reference counting to ensure trampolines are
not freed while any code object could still reference them. Pach by Pablo
Galindo

@item 
gh-142664@footnote{https://github.com/python/cpython/issues/142664}: Fix a use-after-free crash in @ref{cf3,,memoryview.__hash__} when the @code{__hash__} method of the referenced object
mutates that object or the view. Patch by Bénédikt Tran.

@item 
gh-142557@footnote{https://github.com/python/cpython/issues/142557}: Fix a use-after-free crash in @ref{f81,,bytearray.__mod__} when the @code{bytearray} is mutated while
formatting the @code{%}-style arguments. Patch by Bénédikt Tran.

@item 
gh-143195@footnote{https://github.com/python/cpython/issues/143195}: Fix use-after-free crashes in @ref{f66,,bytearray.hex()} and
@ref{f67,,memoryview.hex()} when the separator's @ref{178f,,__len__()}
mutates the original object. Patch by Bénédikt Tran.

@item 
gh-142975@footnote{https://github.com/python/cpython/issues/142975}: Fix crash after unfreezing all objects tracked by the garbage
collector on the @ref{1f4,,free threaded} build.

@item 
gh-143135@footnote{https://github.com/python/cpython/issues/143135}: Set @ref{1790,,sys.flags.inspect} to @code{1} when
@geindex PYTHONINSPECT
@geindex 環境変数; PYTHONINSPECT
@ref{16f3,,PYTHONINSPECT} is @code{0}. Previously, it was set to @code{0} in this
case.

@item 
gh-143003@footnote{https://github.com/python/cpython/issues/143003}: Fix an overflow of the shared empty buffer in
@ref{1791,,bytearray.extend()} when @code{__length_hint__()} returns 0 for
non-empty iterator.

@item 
gh-143006@footnote{https://github.com/python/cpython/issues/143006}: Fix a possible assertion error when comparing negative
non-integer @code{float} and @code{int} with the same number of bits in the
integer part.

@item 
gh-143057@footnote{https://github.com/python/cpython/issues/143057}: Avoid locking in @ref{daf,,PyTraceMalloc_Track()} and
@ref{db0,,PyTraceMalloc_Untrack()} when @ref{105,,tracemalloc} is not enabled.

@item 
gh-142776@footnote{https://github.com/python/cpython/issues/142776}: Fix a file descriptor leak in import.c

@item 
gh-142829@footnote{https://github.com/python/cpython/issues/142829}: Fix a use-after-free crash in @ref{177,,contextvars.Context}
comparison when a custom @code{__eq__} method modifies the context via
@ref{1792,,set()}.

@item 
gh-142766@footnote{https://github.com/python/cpython/issues/142766}: Clear the frame of a generator when @ref{1793,,generator.close()} is
called.

@item 
gh-142737@footnote{https://github.com/python/cpython/issues/142737}: Tracebacks will be displayed in fallback mode even if
@ref{740,,io.open()} is lost. Previously, this would crash the interpreter.
Patch by Bartosz Sławecki.

@item 
gh-142554@footnote{https://github.com/python/cpython/issues/142554}: Fix a crash in @ref{b99,,divmod()} when @code{_pylong.int_divmod()}
does not return a tuple of length two exactly. Patch by Bénédikt Tran.

@item 
gh-142560@footnote{https://github.com/python/cpython/issues/142560}: Fix use-after-free in @ref{344,,bytearray} search-like methods
(@ref{15bd,,find()}, @ref{1794,,count()},
@ref{1795,,index()}, @ref{1796,,rindex()}, and
@ref{15be,,rfind()}) by marking the storage as exported which causes
reallocation attempts to raise @ref{1797,,BufferError}. For
@ref{ad7,,contains()}, @ref{1798,,split()}, and
@ref{1799,,rsplit()} the @ref{260,,buffer protocol} is
used for this.

@item 
gh-142531@footnote{https://github.com/python/cpython/issues/142531}: Fix a free-threaded GC performance regression.  If there are
many untracked tuples, the GC will run too often, resulting in poor
performance.  The fix is to include untracked tuples in the "long lived"
object count. The number of frozen objects is also now included since the
free-threaded GC must scan those too.

@item 
gh-142402@footnote{https://github.com/python/cpython/issues/142402}: Fix reference counting when adjacent literal parts are merged
while constructing @ref{16a,,string.templatelib.Template}, preventing the
displaced string object from leaking.

@item 
gh-133932@footnote{https://github.com/python/cpython/issues/133932}: Fix crash in the free threading build when clearing frames that
hold tagged integers.

@item 
gh-142343@footnote{https://github.com/python/cpython/issues/142343}: Fix SIGILL crash on m68k due to incorrect assembly constraint.

@item 
gh-100964@footnote{https://github.com/python/cpython/issues/100964}: Fix reference cycle in exhausted generator frames. Patch by
Savannah Ostrowski.

@item 
gh-69605@footnote{https://github.com/python/cpython/issues/69605}: Fix edge-cases around already imported modules in the
@ref{491,,REPL} auto-completion of imports.

@item 
gh-138568@footnote{https://github.com/python/cpython/issues/138568}: Adjusted the built-in @ref{ad4,,help()} function so that empty
inputs are ignored in interactive mode.

@item 
gh-137007@footnote{https://github.com/python/cpython/issues/137007}: Fix a bug during JIT compilation failure which caused garbage
collection debug assertions to fail.
@end itemize

@node C API,ビルド,Core and Builtins<2>,Python 3 14 3 final
@anchor{whatsnew/changelog c-api}@anchor{179a}
@subsubsection C API



@itemize -

@item 
gh-142589@footnote{https://github.com/python/cpython/issues/142589}: Fix @ref{3c7,,PyUnstable_Object_IsUniqueReferencedTemporary()}
handling of tagged ints on the interpreter stack.

@item 
gh-142571@footnote{https://github.com/python/cpython/issues/142571}: @code{PyUnstable_CopyPerfMapFile()} now checks that opening
the file succeeded before flushing.
@end itemize

@node ビルド,,C API,Python 3 14 3 final
@anchor{whatsnew/changelog build}@anchor{179b}
@subsubsection ビルド



@itemize -

@item 
gh-142454@footnote{https://github.com/python/cpython/issues/142454}: When calculating the digest of the JIT stencils input, sort the
hashed files by filenames before adding their content to the hasher. This
ensures deterministic hash input and hence deterministic hash, independent
on filesystem order.

@item 
gh-141808@footnote{https://github.com/python/cpython/issues/141808}: When running @code{make clean-retain-profile}, keep the generated
JIT stencils. That way, the stencils are not generated twice when
Profile-guided optimization (PGO) is used. It also allows distributors to
supply their own pre-built JIT stencils.

@item 
gh-138061@footnote{https://github.com/python/cpython/issues/138061}: Ensure reproducible builds by making JIT stencil header
generation deterministic.
@end itemize

@node Python 3 14 2 final,Python 3 14 1 final,Python 3 14 3 final,変更履歴
@anchor{whatsnew/changelog python-3-14-2-final}@anchor{179c}
@subsection Python 3.14.2 final


`Release date: 2025-12-05'

@menu
* セキュリティ: セキュリティ<2>. 
* ライブラリ: ライブラリ<3>. 
* Core and Builtins: Core and Builtins<3>. 
* ライブラリ: ライブラリ<4>. 

@end menu

@node セキュリティ<2>,ライブラリ<3>,,Python 3 14 2 final
@anchor{whatsnew/changelog id6}@anchor{179d}
@subsubsection セキュリティ



@itemize -

@item 
gh-142145@footnote{https://github.com/python/cpython/issues/142145}: Remove quadratic behavior in @code{xml.minidom} node ID cache
clearing.

@item 
gh-119452@footnote{https://github.com/python/cpython/issues/119452}: Fix a potential memory denial of service in the
@ref{76,,http.server} module. When a malicious user is connected to the CGI
server on Windows, it could cause an arbitrary amount of memory to be
allocated. This could have led to symptoms including a @ref{179e,,MemoryError},
swapping, out of memory (OOM) killed processes or containers, or even
system crashes.
@end itemize

@node ライブラリ<3>,Core and Builtins<3>,セキュリティ<2>,Python 3 14 2 final
@anchor{whatsnew/changelog id7}@anchor{179f}
@subsubsection ライブラリ



@itemize -

@item 
gh-140797@footnote{https://github.com/python/cpython/issues/140797}: Revert changes to the undocumented @code{re.Scanner} class.
Capturing groups are still allowed for backward compatibility, although
using them can lead to incorrect result. They will be forbidden in future
Python versions.

@item 
gh-142206@footnote{https://github.com/python/cpython/issues/142206}: The resource tracker in the @ref{98,,multiprocessing} module now
uses the original communication protocol, as in Python 3.14.0 and below,
by default. This avoids issues with upgrading Python while it is running.
(Note that such 'in-place' upgrades are not tested.) The tracker remains
compatible with subprocesses that use new protocol (that is, subprocesses
using Python 3.13.10, 3.14.1 and 3.15).

@item 
gh-142214@footnote{https://github.com/python/cpython/issues/142214}: Fix two regressions in @ref{33,,dataclasses} in Python 3.14.1
related to annotations.


@itemize *

@item 
An exception is no longer raised if @code{slots=True} is used and the
@code{__init__} method does not have an @code{__annotate__} attribute
(likely because @code{init=False} was used).

@item 
An exception is no longer raised if annotations are requested on the
@code{__init__} method and one of the fields is not present in the class
annotations. This can occur in certain dynamic scenarios.
@end itemize

Patch by Jelle Zijlstra.
@end itemize

@node Core and Builtins<3>,ライブラリ<4>,ライブラリ<3>,Python 3 14 2 final
@anchor{whatsnew/changelog id8}@anchor{17a0}
@subsubsection Core and Builtins



@itemize -

@item 
gh-142218@footnote{https://github.com/python/cpython/issues/142218}: Fix crash when inserting into a split table dictionary with a
non @ref{169,,str} key that matches an existing key.
@end itemize

@node ライブラリ<4>,,Core and Builtins<3>,Python 3 14 2 final
@anchor{whatsnew/changelog id9}@anchor{17a1}
@subsubsection ライブラリ



@itemize -

@item 
gh-116738@footnote{https://github.com/python/cpython/issues/116738}: Fix @ref{19,,cmath} data race when initializing trigonometric
tables with subinterpreters.
@end itemize

@node Python 3 14 1 final,Python 3 14 0 final,Python 3 14 2 final,変更履歴
@anchor{whatsnew/changelog python-3-14-1-final}@anchor{17a2}
@subsection Python 3.14.1 final


`Release date: 2025-12-02'

@menu
* Windows: Windows<3>. 
* Tools/Demos: Tools/Demos<2>. 
* テスト: テスト<2>. 
* セキュリティ: セキュリティ<3>. 
* ライブラリ: ライブラリ<5>. 
* IDLE: IDLE<4>. 
* ドキュメント: ドキュメント<4>. 
* Core and Builtins: Core and Builtins<4>. 
* ライブラリ: ライブラリ<6>. 
* Core and Builtins: Core and Builtins<5>. 
* ライブラリ: ライブラリ<7>. 
* Core and Builtins: Core and Builtins<6>. 
* ライブラリ: ライブラリ<8>. 
* Core and Builtins: Core and Builtins<7>. 
* ライブラリ: ライブラリ<9>. 
* Core and Builtins: Core and Builtins<8>. 
* ライブラリ: ライブラリ<10>. 
* Core and Builtins: Core and Builtins<9>. 
* ライブラリ: ライブラリ<11>. 
* Core and Builtins: Core and Builtins<10>. 
* C API: C API<2>. 
* ビルド: ビルド<2>. 

@end menu

@node Windows<3>,Tools/Demos<2>,,Python 3 14 1 final
@anchor{whatsnew/changelog id10}@anchor{17a3}
@subsubsection Windows



@itemize -

@item 
gh-139810@footnote{https://github.com/python/cpython/issues/139810}: Installing with @code{py install 3[.x]-dev} will now select final
versions as well as prereleases.
@end itemize

@node Tools/Demos<2>,テスト<2>,Windows<3>,Python 3 14 1 final
@anchor{whatsnew/changelog id11}@anchor{17a4}
@subsubsection Tools/Demos



@itemize -

@item 
gh-141692@footnote{https://github.com/python/cpython/issues/141692}: Each slice of an iOS XCframework now contains a @code{lib} folder
that contains a symlink to the libpython dylib. This allows binary modules
to be compiled for iOS using dynamic libreary linking, rather than
Framework linking.

@item 
gh-141442@footnote{https://github.com/python/cpython/issues/141442}: The iOS testbed now correctly handles test arguments that
contain spaces.

@item 
gh-140702@footnote{https://github.com/python/cpython/issues/140702}: The iOS testbed app will now expose the @code{GITHUB_ACTIONS}
environment variable to iOS apps being tested.

@item 
gh-137484@footnote{https://github.com/python/cpython/issues/137484}: Have @code{Tools/wasm/wasi} put the build Python into a directory
named after the build triple instead of "build".

@item 
gh-137248@footnote{https://github.com/python/cpython/issues/137248}: Add a @code{--logdir} option to @code{Tools/wasm/wasi} for specifying
where to write log files.

@item 
gh-137243@footnote{https://github.com/python/cpython/issues/137243}: Have Tools/wasm/wasi detect a WASI SDK install in /opt when it
was directly extracted from a release tarball.
@end itemize

@node テスト<2>,セキュリティ<3>,Tools/Demos<2>,Python 3 14 1 final
@anchor{whatsnew/changelog id12}@anchor{17a5}
@subsubsection テスト



@itemize -

@item 
gh-140482@footnote{https://github.com/python/cpython/issues/140482}: Preserve and restore the state of @code{stty echo} as part of the
test environment.

@item 
gh-140082@footnote{https://github.com/python/cpython/issues/140082}: Update @code{python -m test} to set @code{FORCE_COLOR=1} when being
run with color enabled so that @ref{10c,,unittest} which is run by it with
redirected output will output in color.

@item 
gh-139208@footnote{https://github.com/python/cpython/issues/139208}: Fix regrtest @code{--fast-ci --verbose}: don't ignore the
@code{--verbose} option anymore. Patch by Victor Stinner.

@item 
gh-136442@footnote{https://github.com/python/cpython/issues/136442}: Use exitcode @code{1} instead of @code{5} if
@ref{c43,,unittest.TestCase.setUpClass()} raises an exception
@end itemize

@node セキュリティ<3>,ライブラリ<5>,テスト<2>,Python 3 14 1 final
@anchor{whatsnew/changelog id13}@anchor{17a6}
@subsubsection セキュリティ



@itemize -

@item 
gh-139700@footnote{https://github.com/python/cpython/issues/139700}: Check consistency of the zip64 end of central directory record.
Support records with "zip64 extensible data" if there are no bytes
prepended to the ZIP file.

@item 
gh-139283@footnote{https://github.com/python/cpython/issues/139283}: @ref{d4,,sqlite3}: correctly handle maximum number of rows to
fetch in @ref{17a7,,Cursor.fetchmany} and reject
negative values for @ref{17a8,,Cursor.arraysize}.
Patch by Bénédikt Tran.

@item 
gh-137836@footnote{https://github.com/python/cpython/issues/137836}: Add support of the "plaintext" element, RAWTEXT elements "xmp",
"iframe", "noembed" and "noframes", and optionally RAWTEXT element
"noscript" in @ref{a77,,html.parser.HTMLParser}.

@item 
gh-136063@footnote{https://github.com/python/cpython/issues/136063}: @ref{48,,email.message}: ensure linear complexity for legacy HTTP
parameters parsing. Patch by Bénédikt Tran.

@item 
gh-136065@footnote{https://github.com/python/cpython/issues/136065}: Fix quadratic complexity in @ref{15f2,,os.path.expandvars()}.

@item 
gh-119451@footnote{https://github.com/python/cpython/issues/119451}: Fix a potential memory denial of service in the
@ref{73,,http.client} module. When connecting to a malicious server, it could
cause an arbitrary amount of memory to be allocated. This could have led
to symptoms including a @ref{179e,,MemoryError}, swapping, out of memory (OOM)
killed processes or containers, or even system crashes.

@item 
gh-119342@footnote{https://github.com/python/cpython/issues/119342}: Fix a potential memory denial of service in the @ref{b0,,plistlib}
module. When reading a Plist file received from untrusted source, it could
cause an arbitrary amount of memory to be allocated. This could have led
to symptoms including a @ref{179e,,MemoryError}, swapping, out of memory (OOM)
killed processes or containers, or even system crashes.
@end itemize

@node ライブラリ<5>,IDLE<4>,セキュリティ<3>,Python 3 14 1 final
@anchor{whatsnew/changelog id14}@anchor{17a9}
@subsubsection ライブラリ



@itemize -

@item 
gh-74389@footnote{https://github.com/python/cpython/issues/74389}: When the stdin being used by a @ref{4b7,,subprocess.Popen}
instance is closed, this is now ignored in
@ref{17aa,,subprocess.Popen.communicate()} instead of leaving the class in an
inconsistent state.

@item 
gh-87512@footnote{https://github.com/python/cpython/issues/87512}: Fix @ref{17aa,,subprocess.Popen.communicate()} timeout handling on
Windows when writing large input. Previously, the timeout was ignored
during stdin writing, causing the method to block indefinitely if the
child process did not consume input quickly. The stdin write is now
performed in a background thread, allowing the timeout to be properly
enforced.

@item 
gh-141473@footnote{https://github.com/python/cpython/issues/141473}: When @ref{17aa,,subprocess.Popen.communicate()} was called with
`input' and a `timeout' and is called for a second time after a
@ref{17ab,,TimeoutExpired} exception before the process has died,
it should no longer hang.

@item 
gh-59000@footnote{https://github.com/python/cpython/issues/59000}: Fix @ref{aa,,pdb} breakpoint resolution for class methods when the
module defining the class is not imported.

@item 
gh-141570@footnote{https://github.com/python/cpython/issues/141570}: Support @ref{17ac,,file-like object} raising @ref{2c0,,OSError} from
@ref{17ad,,fileno()} in color detection
(@code{_colorize.can_colorize()}). This can occur when @code{sys.stdout} is
redirected.

@item 
gh-141659@footnote{https://github.com/python/cpython/issues/141659}: Fix bad file descriptor errors from @code{_posixsubprocess} on
AIX.

@item 
gh-141600@footnote{https://github.com/python/cpython/issues/141600}: Fix musl version detection on Void Linux.

@item 
gh-141497@footnote{https://github.com/python/cpython/issues/141497}: @ref{84,,ipaddress}: ensure that the methods
@ref{17ae,,IPv4Network.hosts()} and
@ref{17af,,IPv6Network.hosts()} always return an
iterator.

@item 
gh-140938@footnote{https://github.com/python/cpython/issues/140938}: The @ref{8e3,,statistics.stdev()} and @ref{17b0,,statistics.pstdev()}
functions now raise a @ref{2ec,,ValueError} when the input contains an
infinity or a NaN.

@item 
gh-124111@footnote{https://github.com/python/cpython/issues/124111}: Updated Tcl threading configuration in @ref{3,,_tkinter} to
assume that threads are always available in Tcl 9 and later.

@item 
gh-137109@footnote{https://github.com/python/cpython/issues/137109}: The @ref{4b5,,os.fork} and related forking APIs will no longer warn
in the common case where Linux or macOS platform APIs return the number of
threads in a process and find the answer to be 1 even when a
@ref{355,,os.register_at_fork()} @code{after_in_parent=} callback (re)starts a
thread.

@item 
gh-141314@footnote{https://github.com/python/cpython/issues/141314}: Fix assertion failure in @ref{17b1,,io.TextIOWrapper.tell()} when
reading files with standalone carriage return (@code{\r}) line endings.

@item 
gh-141311@footnote{https://github.com/python/cpython/issues/141311}: Fix assertion failure in @code{io.BytesIO.readinto()} and
undefined behavior arising when read position is above capcity in
@ref{10a4,,io.BytesIO}.

@item 
gh-141141@footnote{https://github.com/python/cpython/issues/141141}: Fix a thread safety issue with @ref{1124,,base64.b85decode()}.
Contributed by Benel Tayar.

@item 
gh-137969@footnote{https://github.com/python/cpython/issues/137969}: Fix @ref{17b2,,annotationlib.ForwardRef.evaluate()} returning
@ref{1776,,ForwardRef} objects which don't update with new
globals.

@item 
gh-140911@footnote{https://github.com/python/cpython/issues/140911}: @ref{1e,,collections}: Ensure that the methods
@code{UserString.rindex()} and @code{UserString.index()} accept
@ref{fd3,,collections.UserString} instances as the sub argument.

@item 
gh-140797@footnote{https://github.com/python/cpython/issues/140797}: The undocumented @code{re.Scanner} class now forbids regular
expressions containing capturing groups in its lexicon patterns. Patterns
using capturing groups could previously lead to crashes with segmentation
fault. Use non-capturing groups (?:...) instead.

@item 
gh-125115@footnote{https://github.com/python/cpython/issues/125115}: Refactor the @ref{aa,,pdb} parsing issue so positional arguments
can pass through intuitively.

@item 
gh-140815@footnote{https://github.com/python/cpython/issues/140815}: @ref{5c,,faulthandler} now detects if a frame or a code object is
invalid or freed. Patch by Victor Stinner.

@item 
gh-100218@footnote{https://github.com/python/cpython/issues/100218}: Correctly set @ref{17b3,,errno} when
@ref{c23,,socket.if_nametoindex()} or @ref{c24,,socket.if_indextoname()} raise an
@ref{2c0,,OSError}. Patch by Bénédikt Tran.

@item 
gh-140875@footnote{https://github.com/python/cpython/issues/140875}: Fix handling of unclosed character references (named and
numerical) followed by the end of file in @ref{a77,,html.parser.HTMLParser}
with @code{convert_charrefs=False}.

@item 
gh-140734@footnote{https://github.com/python/cpython/issues/140734}: @ref{98,,multiprocessing}: fix off-by-one error when checking the
length of a temporary socket file path. Patch by Bénédikt Tran.

@item 
gh-140874@footnote{https://github.com/python/cpython/issues/140874}: Bump the version of pip bundled in ensurepip to version 25.3

@item 
gh-140691@footnote{https://github.com/python/cpython/issues/140691}: In @ref{111,,urllib.request}, when opening a FTP URL fails because
a data connection cannot be made, the control connection's socket is now
closed to avoid a @ref{54c,,ResourceWarning}.

@item 
gh-103847@footnote{https://github.com/python/cpython/issues/103847}: Fix hang when cancelling process created by
@ref{c6b,,asyncio.create_subprocess_exec()} or
@ref{c6c,,asyncio.create_subprocess_shell()}. Patch by Kumar Aditya.

@item 
gh-120057@footnote{https://github.com/python/cpython/issues/120057}: Add @ref{258,,os.reload_environ()} to @code{os.__all__}.

@item 
gh-140228@footnote{https://github.com/python/cpython/issues/140228}: Avoid making unnecessary filesystem calls for frozen modules in
@ref{89,,linecache} when the global module cache is not present.

@item 
gh-140590@footnote{https://github.com/python/cpython/issues/140590}: Fix arguments checking for the
@code{functools.partial.__setstate__()} that may lead to internal state
corruption and crash. Patch by Sergey Miryanov.

@item 
gh-125434@footnote{https://github.com/python/cpython/issues/125434}: Display thread name in @ref{5c,,faulthandler} on Windows. Patch by
Victor Stinner.

@item 
gh-140634@footnote{https://github.com/python/cpython/issues/140634}: Fix a reference counting bug in
@code{os.sched_param.__reduce__()}.

@item 
gh-140633@footnote{https://github.com/python/cpython/issues/140633}: Ignore @ref{5f0,,AttributeError} when setting a module's
@code{__file__} attribute when loading an extension module packaged as Apple
Framework.

@item 
gh-140593@footnote{https://github.com/python/cpython/issues/140593}: @ref{12c,,xml.parsers.expat}: Fix a memory leak that could affect
users with @ref{17b4,,ElementDeclHandler()} set to
a custom element declaration handler. Patch by Sebastian Pipping.

@item 
gh-140607@footnote{https://github.com/python/cpython/issues/140607}: Inside @ref{101d,,io.RawIOBase.read()}, validate that the count of
bytes returned by @ref{101e,,io.RawIOBase.readinto()} is valid (inside the
provided buffer).

@item 
gh-138162@footnote{https://github.com/python/cpython/issues/138162}: Fix @ref{150d,,logging.LoggerAdapter} with @code{merge_extra=True}
and without the `extra' argument.

@item 
gh-138774@footnote{https://github.com/python/cpython/issues/138774}: @ref{ae2,,ast.unparse()} now generates full source code when
handling @ref{17b5,,ast.Interpolation} nodes that do not have a specified
source.

@item 
gh-140474@footnote{https://github.com/python/cpython/issues/140474}: Fix memory leak in @ref{4be,,array.array} when creating arrays
from an empty @ref{169,,str} and the @code{u} type code.

@item 
gh-137530@footnote{https://github.com/python/cpython/issues/137530}: @ref{33,,dataclasses} Fix annotations for generated @code{__init__}
methods by replacing the annotations that were in-line in the generated
source code with @code{__annotate__} functions attached to the methods.

@item 
gh-140348@footnote{https://github.com/python/cpython/issues/140348}: Fix regression in Python 3.14.0 where using the @code{|} operator
on a @ref{2a8,,typing.Union} object combined with an object that is not a
type would raise an error.

@item 
gh-140272@footnote{https://github.com/python/cpython/issues/140272}: Fix memory leak in the @code{clear()} method of the
@ref{37,,dbm.gnu} database.

@item 
gh-140041@footnote{https://github.com/python/cpython/issues/140041}: Fix import of @ref{2e,,ctypes} on Android and Cygwin when ABI
flags are present.

@item 
gh-140120@footnote{https://github.com/python/cpython/issues/140120}: Fixed a memory leak in @ref{6e,,hmac} when it was using the
hacl-star backend. Discovered by @code{@@ashm-dev} using AddressSanitizer.

@item 
gh-139905@footnote{https://github.com/python/cpython/issues/139905}: Add suggestion to error message for @ref{17b6,,typing.Generic}
subclasses when @code{cls.__parameters__} is missing due to a parent class
failing to call @ref{843,,super().__init_subclass__()} in its @code{__init_subclass__}.

@item 
gh-139894@footnote{https://github.com/python/cpython/issues/139894}: Fix incorrect sharing of current task with the child process
while forking in @ref{b,,asyncio}. Patch by Kumar Aditya.

@item 
gh-139845@footnote{https://github.com/python/cpython/issues/139845}: Fix to not print KeyboardInterrupt twice in default asyncio
REPL.

@item 
gh-139783@footnote{https://github.com/python/cpython/issues/139783}: Fix @ref{17b7,,inspect.getsourcelines()} for the case when a
decorator is followed by a comment or an empty line.

@item 
gh-139809@footnote{https://github.com/python/cpython/issues/139809}: Prevent premature colorization of subparser @code{prog} in
@ref{e11,,argparse.ArgumentParser.add_subparsers()} to respect color
environment variable changes after parser creation.

@item 
gh-139736@footnote{https://github.com/python/cpython/issues/139736}: Fix excessive indentation in the default @ref{7,,argparse}
@code{HelpFormatter}. Patch by Alexander Edland.

@item 
gh-70765@footnote{https://github.com/python/cpython/issues/70765}: @ref{76,,http.server}: fix default handling of HTTP/0.9 requests in
@ref{12e2,,BaseHTTPRequestHandler}. Previously,
@code{BaseHTTPRequestHandler.parse_request()} incorrectly waited for
headers in the request although those are not supported in HTTP/0.9. Patch
by Bénédikt Tran.

@item 
gh-63161@footnote{https://github.com/python/cpython/issues/63161}: Fix @ref{17b8,,tokenize.detect_encoding()}. Support non-UTF-8 shebang
and comments if non-UTF-8 encoding is specified. Detect decoding error for
non-UTF-8 encoding. Detect null bytes in source code.

@item 
gh-139391@footnote{https://github.com/python/cpython/issues/139391}: Fix an issue when, on non-Windows platforms, it was not
possible to gracefully exit a @code{python -m asyncio} process suspended by
Ctrl+Z and later resumed by @code{fg@footnote{https://manpages.debian.org/fg}} other than with @code{kill@footnote{https://manpages.debian.org/kill}}.

@item 
gh-101828@footnote{https://github.com/python/cpython/issues/101828}: Fix @code{'shift_jisx0213'}, @code{'shift_jis_2004'},
@code{'euc_jisx0213'} and @code{'euc_jis_2004'} codecs truncating null chars as
they were treated as part of multi-character sequences.

@item 
gh-139289@footnote{https://github.com/python/cpython/issues/139289}: Do a real lazy-import on @ref{c2,,rlcompleter} in @ref{aa,,pdb} and
restore the existing completer after importing @ref{c2,,rlcompleter}.

@item 
gh-139246@footnote{https://github.com/python/cpython/issues/139246}: fix: paste zero-width in default repl width is wrong.

@item 
gh-90949@footnote{https://github.com/python/cpython/issues/90949}: Add
@ref{17b9,,SetAllocTrackerActivationThreshold()}
and
@ref{17ba,,SetAllocTrackerMaximumAmplification()}
to @ref{17bb,,xmlparser} objects to prevent use of
disproportional amounts of dynamic memory from within an Expat parser.
Patch by Bénédikt Tran.

@item 
gh-139210@footnote{https://github.com/python/cpython/issues/139210}: Fix use-after-free when reporting unknown event in
@ref{57a,,xml.etree.ElementTree.iterparse()}. Patch by Ken Jin.

@item 
gh-138860@footnote{https://github.com/python/cpython/issues/138860}: Lazy import @ref{c2,,rlcompleter} in @ref{aa,,pdb} to avoid deadlock
in subprocess.

@item 
gh-112729@footnote{https://github.com/python/cpython/issues/112729}: Fix crash when calling @ref{17bc,,concurrent.interpreters.create()}
when the process is out of memory.

@item 
gh-135729@footnote{https://github.com/python/cpython/issues/135729}: Fix unraisable exception during finalization when using
@ref{25,,concurrent.interpreters} in the REPL.

@item 
gh-139076@footnote{https://github.com/python/cpython/issues/139076}: Fix a bug in the @ref{ba,,pydoc} module that was hiding functions
in a Python module if they were implemented in an extension module and the
module did not have @code{__all__}.

@item 
gh-139065@footnote{https://github.com/python/cpython/issues/139065}: Fix trailing space before a wrapped long word if the line
length is exactly `width' in @ref{f2,,textwrap}.

@item 
gh-139001@footnote{https://github.com/python/cpython/issues/139001}: Fix race condition in @ref{266,,pathlib.Path} on the internal
@code{_raw_paths} field.

@item 
gh-138813@footnote{https://github.com/python/cpython/issues/138813}: @code{multiprocessing.BaseProcess} defaults @code{kwargs} to
@code{None} instead of a shared dictionary.

@item 
gh-138993@footnote{https://github.com/python/cpython/issues/138993}: Dedent @ref{1789,,credits} text.

@item 
gh-138891@footnote{https://github.com/python/cpython/issues/138891}: Fix @code{SyntaxError} when @code{inspect.get_annotations(f,
eval_str=True)} is called on a function annotated with a 
@geindex Python Enhancement Proposals; PEP 646
PEP 646@footnote{https://peps.python.org/pep-0646/}
@code{star_expression}

@item 
gh-130567@footnote{https://github.com/python/cpython/issues/130567}: Fix possible crash in @ref{17bd,,locale.strxfrm()} due to a platform
bug on macOS.

@item 
gh-138859@footnote{https://github.com/python/cpython/issues/138859}: Fix generic type parameterization raising a @ref{198,,TypeError}
when omitting a @code{ParamSpec} that has a default which is not a list
of types.

@item 
gh-138764@footnote{https://github.com/python/cpython/issues/138764}: Prevent @ref{17be,,annotationlib.call_annotate_function()} from
calling @code{__annotate__} functions that don't support
@code{VALUE_WITH_FAKE_GLOBALS} in a fake globals namespace with empty
globals.

Make @code{FORWARDREF} and @code{STRING} annotations fall back to using
@code{VALUE} annotations in the case that neither their own format, nor
@code{VALUE_WITH_FAKE_GLOBALS} are supported.

@item 
gh-138775@footnote{https://github.com/python/cpython/issues/138775}: Use of @code{python -m} with @ref{f,,base64} has been fixed to
detect input from a terminal so that it properly notices EOF.

@item 
gh-138779@footnote{https://github.com/python/cpython/issues/138779}: Support device numbers larger than @code{2**63-1} for the
@ref{17bf,,st_rdev} field of the @ref{16da,,os.stat_result}
structure.

@item 
gh-137706@footnote{https://github.com/python/cpython/issues/137706}: Fix the partial evaluation of annotations that use
@code{typing.Annotated[T, x]} where @code{T} is a forward reference.

@item 
gh-88375@footnote{https://github.com/python/cpython/issues/88375}: Fix normalization of the @code{robots.txt} rules and URLs in the
@ref{113,,urllib.robotparser} module. No longer ignore trailing @code{?}.
Distinguish raw special characters @code{?}, @code{=} and @code{&} from the
percent-encoded ones.

@item 
gh-111788@footnote{https://github.com/python/cpython/issues/111788}: Fix parsing errors in the @ref{113,,urllib.robotparser} module.
Don't fail trying to parse weird paths. Don't fail trying to decode
non-UTF-8 @code{robots.txt} files.

@item 
gh-98896@footnote{https://github.com/python/cpython/issues/98896}: Fix a failure in multiprocessing resource_tracker when
SharedMemory names contain colons. Patch by Rani Pinchuk.

@item 
gh-138425@footnote{https://github.com/python/cpython/issues/138425}: Fix partial evaluation of @ref{1776,,annotationlib.ForwardRef}
objects which rely on names defined as globals.

@item 
gh-138432@footnote{https://github.com/python/cpython/issues/138432}: @ref{17c0,,zoneinfo.reset_tzpath()} will now convert any
@ref{e4b,,os.PathLike} objects it receives into strings before adding them
to @code{TZPATH}. It will raise @code{TypeError} if anything other than a string
is found after this conversion. If given an @ref{e4b,,os.PathLike} object
that represents a relative path, it will now raise @code{ValueError} instead
of @code{TypeError}, and present a more informative error message.

@item 
gh-138008@footnote{https://github.com/python/cpython/issues/138008}: Fix segmentation faults in the @ref{2e,,ctypes} module due to
invalid @ref{17c1,,argtypes}. Patch by Dung Nguyen.

@item 
gh-60462@footnote{https://github.com/python/cpython/issues/60462}: Fix @ref{17bd,,locale.strxfrm()} on Solaris (and possibly other
platforms).

@item 
gh-138239@footnote{https://github.com/python/cpython/issues/138239}: The REPL now highlights @ref{66d,,type} as a soft keyword in
@ref{66d,,type statements}.

@item 
gh-138204@footnote{https://github.com/python/cpython/issues/138204}: Forbid expansion of shared anonymous @ref{94,,memory maps}
on Linux, which caused a bus error.

@item 
gh-138010@footnote{https://github.com/python/cpython/issues/138010}: Fix an issue where defining a class with an
@ref{489,,@@warnings.deprecated}-decorated base class
may not invoke the correct @ref{843,,__init_subclass__()} method in
cases involving multiple inheritance. Patch by Brian Schubert.

@item 
gh-138151@footnote{https://github.com/python/cpython/issues/138151}: In @ref{6,,annotationlib}, improve evaluation of forward
references to nonlocal variables that are not yet defined when the
annotations are initially evaluated.

@item 
gh-137317@footnote{https://github.com/python/cpython/issues/137317}: @ref{22f,,inspect.signature()} now correctly handles classes that
use a descriptor on a wrapped @code{__init__()} or @code{__new__()}
method. Contributed by Yongyu Yan.

@item 
gh-137754@footnote{https://github.com/python/cpython/issues/137754}: Fix import of the @ref{13a,,zoneinfo} module if the C
implementation of the @ref{34,,datetime} module is not available.

@item 
gh-137490@footnote{https://github.com/python/cpython/issues/137490}: Handle @ref{17c2,,ECANCELED} in the same way as
@ref{f87,,EINTR} in @ref{fab,,signal.sigwaitinfo()} on NetBSD.

@item 
gh-137477@footnote{https://github.com/python/cpython/issues/137477}: Fix @code{inspect.getblock()}, @ref{17b7,,inspect.getsourcelines()}
and @ref{17c3,,inspect.getsource()} for generator expressions.

@item 
gh-137044@footnote{https://github.com/python/cpython/issues/137044}: Return large limit values as positive integers instead of
negative integers in @ref{17c4,,resource.getrlimit()}. Accept large values and
reject negative values (except @ref{17c5,,RLIM_INFINITY}) for limits
in @ref{17c6,,resource.setrlimit()}.

@item 
gh-75989@footnote{https://github.com/python/cpython/issues/75989}: @ref{29b,,tarfile.TarFile.extractall()} and
@ref{29c,,tarfile.TarFile.extract()} now overwrite symlinks when extracting
hardlinks. (Contributed by Alexander Enrique Urieles Nieto in
gh-75989@footnote{https://github.com/python/cpython/issues/75989}.)

@item 
gh-137017@footnote{https://github.com/python/cpython/issues/137017}: Fix @ref{b46,,threading.Thread.is_alive} to remain @code{True} until
the underlying OS thread is fully cleaned up. This avoids false negatives
in edge cases involving thread monitoring or premature
@ref{b46,,threading.Thread.is_alive} calls.

@item 
gh-137273@footnote{https://github.com/python/cpython/issues/137273}: Fix debug assertion failure in @ref{328,,locale.setlocale()} on
Windows.

@item 
gh-137239@footnote{https://github.com/python/cpython/issues/137239}: @ref{6d,,heapq}: Update @code{heapq.__all__} with @code{*_max}
functions.

@item 
gh-81325@footnote{https://github.com/python/cpython/issues/81325}: @ref{1429,,tarfile.TarFile} now accepts a @ref{5a1,,path-like} when working on a tar archive. (Contributed by
Alexander Enrique Urieles Nieto in gh-81325@footnote{https://github.com/python/cpython/issues/81325}.)

@item 
gh-137185@footnote{https://github.com/python/cpython/issues/137185}: Fix a potential async-signal-safety issue in
@ref{5c,,faulthandler} when printing C stack traces.

@item 
gh-136914@footnote{https://github.com/python/cpython/issues/136914}: Fix retrieval of @ref{17c7,,doctest.DocTest.lineno} for objects
decorated with @ref{17c8,,functools.cache()} or
@ref{763,,functools.cached_property}.

@item 
gh-136912@footnote{https://github.com/python/cpython/issues/136912}: @ref{d32,,hmac.digest()} now properly handles large keys and
messages by falling back to the pure Python implementation when necessary.
Patch by Bénédikt Tran.

@item 
gh-83424@footnote{https://github.com/python/cpython/issues/83424}: Allows creating a @ref{bdc,,ctypes.CDLL} without name when passing
a handle as an argument.

@item 
gh-136234@footnote{https://github.com/python/cpython/issues/136234}: Fix @ref{17c9,,asyncio.WriteTransport.writelines()} to be robust to
connection failure, by using the same behavior as
@ref{17ca,,write()}.

@item 
gh-136507@footnote{https://github.com/python/cpython/issues/136507}: Fix mimetypes CLI to handle multiple file parameters.

@item 
gh-136057@footnote{https://github.com/python/cpython/issues/136057}: Fixed the bug in @ref{aa,,pdb} and @ref{10,,bdb} where @code{next} and
@code{step} can't go over the line if a loop exists in the line.

@item 
gh-135386@footnote{https://github.com/python/cpython/issues/135386}: Fix opening a @ref{39,,dbm.sqlite3} database for reading from
read-only file or directory.

@item 
gh-135444@footnote{https://github.com/python/cpython/issues/135444}: Fix @ref{4cb,,asyncio.DatagramTransport.sendto()} to account for
datagram header size when data cannot be sent.

@item 
gh-126631@footnote{https://github.com/python/cpython/issues/126631}: Fix @ref{98,,multiprocessing} @code{forkserver} bug which prevented
@code{__main__} from being preloaded.

@item 
gh-135307@footnote{https://github.com/python/cpython/issues/135307}: @ref{3f,,email}: Fix exception in @code{set_content()} when encoding
text and max_line_length is set to @code{0} or @code{None} (unlimited).

@item 
gh-134453@footnote{https://github.com/python/cpython/issues/134453}: Fixed @ref{17aa,,subprocess.Popen.communicate()} @code{input=} handling
of @ref{165,,memoryview} instances that were non-byte shaped on POSIX
platforms. Those are now properly cast to a byte shaped view instead of
truncating the input.  Windows platforms did not have this bug.

@item 
gh-134698@footnote{https://github.com/python/cpython/issues/134698}: Fix a crash when calling methods of @ref{357,,ssl.SSLContext} or
@ref{ae7,,ssl.SSLSocket} across multiple threads.

@item 
gh-125996@footnote{https://github.com/python/cpython/issues/125996}: Fix thread safety of @ref{7f3,,collections.OrderedDict}. Patch by
Kumar Aditya.

@item 
gh-133789@footnote{https://github.com/python/cpython/issues/133789}: Fix unpickling of @ref{a8,,pathlib} objects that were pickled in
Python 3.13.

@item 
gh-127081@footnote{https://github.com/python/cpython/issues/127081}: Fix libc thread safety issues with @ref{35,,dbm} by performing
stateful operations in critical sections.

@item 
gh-132551@footnote{https://github.com/python/cpython/issues/132551}: Make @ref{10a4,,io.BytesIO} safe in @ref{1f4,,free-threaded} build.

@item 
gh-131788@footnote{https://github.com/python/cpython/issues/131788}: Make @code{ResourceTracker.send} from @ref{98,,multiprocessing}
re-entrant safe

@item 
gh-118981@footnote{https://github.com/python/cpython/issues/118981}: Fix potential hang in @code{multiprocessing.popen_spawn_posix}
that can happen when the child proc dies early by closing the child fds
right away.

@item 
gh-102431@footnote{https://github.com/python/cpython/issues/102431}: Clarify constraints for "logical" arguments in methods of
@ref{12c3,,decimal.Context}.

@item 
gh-78319@footnote{https://github.com/python/cpython/issues/78319}: UTF8 support for the IMAP APPEND command has been made RFC
compliant.

@item 
bpo-38735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38735}: Fix failure when importing a module from the root directory on
unix-like platforms with sys.pycache_prefix set.

@item 
bpo-41839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41839}: Allow negative priority values from
@ref{1321,,os.sched_get_priority_min()} and @ref{1320,,os.sched_get_priority_max()}
functions.
@end itemize

@node IDLE<4>,ドキュメント<4>,ライブラリ<5>,Python 3 14 1 final
@anchor{whatsnew/changelog id15}@anchor{17cb}
@subsubsection IDLE



@itemize -

@item 
gh-96491@footnote{https://github.com/python/cpython/issues/96491}: Deduplicate version number in IDLE shell title bar after saving
to a file.

@item 
gh-139742@footnote{https://github.com/python/cpython/issues/139742}: Colorize t-string prefixes for template strings in IDLE, as
done for f-string prefixes.
@end itemize

@node ドキュメント<4>,Core and Builtins<4>,IDLE<4>,Python 3 14 1 final
@anchor{whatsnew/changelog id16}@anchor{17cc}
@subsubsection ドキュメント



@itemize -

@item 
gh-141994@footnote{https://github.com/python/cpython/issues/141994}: @ref{130,,xml.sax.handler}: Make Documentation of
@ref{17cd,,xml.sax.handler.feature_external_ges} warn of opening up to
external entity attacks@footnote{https://en.wikipedia.org/wiki/XML_external_entity_attack}. Patch by
Sebastian Pipping.

@item 
gh-140578@footnote{https://github.com/python/cpython/issues/140578}: Remove outdated sencence in the documentation for
@ref{98,,multiprocessing}, that implied that
@ref{949,,concurrent.futures.ThreadPoolExecutor} did not exist.
@end itemize

@node Core and Builtins<4>,ライブラリ<6>,ドキュメント<4>,Python 3 14 1 final
@anchor{whatsnew/changelog id17}@anchor{17ce}
@subsubsection Core and Builtins



@itemize -

@item 
gh-142048@footnote{https://github.com/python/cpython/issues/142048}: Fix quadratically increasing garbage collection delays in
free-threaded build.
@end itemize

@node ライブラリ<6>,Core and Builtins<5>,Core and Builtins<4>,Python 3 14 1 final
@anchor{whatsnew/changelog id18}@anchor{17cf}
@subsubsection ライブラリ



@itemize -

@item 
gh-116738@footnote{https://github.com/python/cpython/issues/116738}: Fix thread safety issue with @ref{be,,re} scanner objects in
free-threaded builds.
@end itemize

@node Core and Builtins<5>,ライブラリ<7>,ライブラリ<6>,Python 3 14 1 final
@anchor{whatsnew/changelog id19}@anchor{17d0}
@subsubsection Core and Builtins



@itemize -

@item 
gh-141930@footnote{https://github.com/python/cpython/issues/141930}: When importing a module, use Python's regular file object to
ensure that writes to @code{.pyc} files are complete or an appropriate error
is raised.

@item 
gh-120158@footnote{https://github.com/python/cpython/issues/120158}: Fix inconsistent state when enabling or disabling monitoring
events too many times.

@item 
gh-139653@footnote{https://github.com/python/cpython/issues/139653}: Only raise a @code{RecursionError} or trigger a fatal error if the
stack pointer is both below the limit pointer `and' above the stack base.
If outside of these bounds assume that it is OK. This prevents false
positives when user-space threads swap stacks.

@item 
gh-139103@footnote{https://github.com/python/cpython/issues/139103}: Improve multithreaded scaling of dataclasses on the
free-threaded build.

@item 
gh-141579@footnote{https://github.com/python/cpython/issues/141579}: Fix @ref{69a,,sys.activate_stack_trampoline()} to properly support
the @code{perf_jit} backend. Patch by Pablo Galindo.

@item 
gh-114203@footnote{https://github.com/python/cpython/issues/114203}: Skip locking if object is already locked by two-mutex critical
section.

@item 
gh-141528@footnote{https://github.com/python/cpython/issues/141528}: Suggest using @ref{17d1,,concurrent.interpreters.Interpreter.close()}
instead of the private @code{_interpreters.destroy} function when warning
about remaining subinterpreters. Patch by Sergey Miryanov.

@item 
gh-141312@footnote{https://github.com/python/cpython/issues/141312}: Fix the assertion failure in the @code{__setstate__} method of the
range iterator when a non-integer argument is passed. Patch by Sergey
Miryanov.
@end itemize

@node ライブラリ<7>,Core and Builtins<6>,Core and Builtins<5>,Python 3 14 1 final
@anchor{whatsnew/changelog id20}@anchor{17d2}
@subsubsection ライブラリ



@itemize -

@item 
gh-116738@footnote{https://github.com/python/cpython/issues/116738}: Make csv module thread-safe on the @ref{1f4,,free threaded} build.
@end itemize

@node Core and Builtins<6>,ライブラリ<8>,ライブラリ<7>,Python 3 14 1 final
@anchor{whatsnew/changelog id21}@anchor{17d3}
@subsubsection Core and Builtins



@itemize -

@item 
gh-140939@footnote{https://github.com/python/cpython/issues/140939}: Fix memory leak when @ref{344,,bytearray} or @ref{192,,bytes} is
formated with the @code{%*b} format with a large width that results in a
@ref{179e,,MemoryError}.
@end itemize

@node ライブラリ<8>,Core and Builtins<7>,Core and Builtins<6>,Python 3 14 1 final
@anchor{whatsnew/changelog id22}@anchor{17d4}
@subsubsection ライブラリ



@itemize -

@item 
gh-140260@footnote{https://github.com/python/cpython/issues/140260}: Fix @ref{db,,struct} data race in endian table initialization with
subinterpreters. Patch by Shamil Abdulaev.
@end itemize

@node Core and Builtins<7>,ライブラリ<9>,ライブラリ<8>,Python 3 14 1 final
@anchor{whatsnew/changelog id23}@anchor{17d5}
@subsubsection Core and Builtins



@itemize -

@item 
gh-140530@footnote{https://github.com/python/cpython/issues/140530}: Fix a reference leak when @code{raise exc from cause} fails. Patch
by Bénédikt Tran.

@item 
gh-140373@footnote{https://github.com/python/cpython/issues/140373}: Correctly emit @code{PY_UNWIND} event when generator object is
closed. Patch by Mikhail Efimov.

@item 
gh-140576@footnote{https://github.com/python/cpython/issues/140576}: Fixed crash in @ref{701,,tokenize.generate_tokens()} in case of
specific incorrect input. Patch by Mikhail Efimov.

@item 
gh-140551@footnote{https://github.com/python/cpython/issues/140551}: Fixed crash in @ref{183,,dict} if @ref{17d6,,dict.clear()} is called at
the lookup stage. Patch by Mikhail Efimov and Inada Naoki.

@item 
gh-140517@footnote{https://github.com/python/cpython/issues/140517}: Fixed a reference leak when iterating over the result of
@ref{19f,,map()} with @code{strict=True} when the input iterables have different
lengths. Patch by Mikhail Efimov.

@item 
gh-140471@footnote{https://github.com/python/cpython/issues/140471}: Fix potential buffer overflow in @ref{4c3,,ast.AST} node
initialization when encountering malformed @ref{17d7,,_fields}
containing non-@ref{169,,str}.

@item 
gh-140431@footnote{https://github.com/python/cpython/issues/140431}: Fix a crash in Python's @ref{17d8,,garbage collector} due to partially initialized @ref{6b9,,coroutine} objects when
coroutine origin tracking depth is enabled
(@ref{d85,,sys.set_coroutine_origin_tracking_depth()}).
@end itemize

@node ライブラリ<9>,Core and Builtins<8>,Core and Builtins<7>,Python 3 14 1 final
@anchor{whatsnew/changelog id24}@anchor{17d9}
@subsubsection ライブラリ



@itemize -

@item 
gh-140398@footnote{https://github.com/python/cpython/issues/140398}: Fix memory leaks in @ref{bf,,readline} functions
@ref{17da,,read_init_file()}, @ref{17db,,read_history_file()},
@ref{17dc,,write_history_file()}, and
@ref{1051,,append_history_file()} when @ref{613,,PySys_Audit()} fails.
@end itemize

@node Core and Builtins<8>,ライブラリ<10>,ライブラリ<9>,Python 3 14 1 final
@anchor{whatsnew/changelog id25}@anchor{17dd}
@subsubsection Core and Builtins



@itemize -

@item 
gh-140406@footnote{https://github.com/python/cpython/issues/140406}: Fix memory leak when an object's @ref{cf3,,__hash__()}
method returns an object that isn't an @ref{19b,,int}.

@item 
gh-140358@footnote{https://github.com/python/cpython/issues/140358}: Restore elapsed time and unreachable object count in GC debug
output. These were inadvertently removed during a refactor of @code{gc.c}.
The debug log now again reports elapsed collection time and the number of
unreachable objects. Contributed by Pål Grønås Drange.

@item 
gh-140306@footnote{https://github.com/python/cpython/issues/140306}: Fix memory leaks in cross-interpreter channel operations and
shared namespace handling.

@item 
gh-140301@footnote{https://github.com/python/cpython/issues/140301}: Fix memory leak of @code{PyConfig} in subinterpreters.

@item 
gh-140257@footnote{https://github.com/python/cpython/issues/140257}: Fix data race between interpreter_clear() and take_gil() on
eval_breaker during finalization with daemon threads.

@item 
gh-139951@footnote{https://github.com/python/cpython/issues/139951}: Fixes a regression in GC performance for a growing heap
composed mostly of small tuples.


@itemize *

@item 
Counts number of actually tracked objects, instead of trackable objects.
This ensures that untracking tuples has the desired effect of reducing GC overhead.

@item 
Does not track most untrackable tuples during creation.
This prevents large numbers of small tuples causing excessive GCs.
@end itemize

@item 
gh-140104@footnote{https://github.com/python/cpython/issues/140104}: Fix a bug with exception handling in the JIT. Patch by Ken Jin.
Bug reported by Daniel Diniz.

@item 
gh-140061@footnote{https://github.com/python/cpython/issues/140061}: Fixing the checking of whether an object is uniquely referenced
to ensure free-threaded compatibility. Patch by Sergey Miryanov.

@item 
gh-140067@footnote{https://github.com/python/cpython/issues/140067}: Fix memory leak in sub-interpreter creation.

@item 
gh-140000@footnote{https://github.com/python/cpython/issues/140000}: Fix potential memory leak when a reference cycle exists between
an instance of @ref{2ae,,typing.TypeAliasType}, @ref{486,,typing.TypeVar},
@ref{487,,typing.ParamSpec}, or @ref{488,,typing.TypeVarTuple} and its
@code{__name__} attribute. Patch by Mikhail Efimov.

@item 
gh-139914@footnote{https://github.com/python/cpython/issues/139914}: Restore support for HP PA-RISC, which has an upwards-growing
stack.

@item 
gh-139988@footnote{https://github.com/python/cpython/issues/139988}: Fix a memory leak when failing to create a
@ref{2a8,,Union} type. Patch by Bénédikt Tran.

@item 
gh-139748@footnote{https://github.com/python/cpython/issues/139748}: Fix reference leaks in error branches of functions accepting
path strings or bytes such as @ref{4b1,,compile()} and @ref{1676,,os.system()}. Patch
by Bénédikt Tran.

@item 
gh-139516@footnote{https://github.com/python/cpython/issues/139516}: Fix lambda colon erroneously start format spec in f-string in
tokenizer.

@item 
gh-139640@footnote{https://github.com/python/cpython/issues/139640}: @ref{1c2,,ast.parse()} no longer emits syntax warnings for
@code{return}/@code{break}/@code{continue} in @code{finally} (see 
@geindex Python Enhancement Proposals; PEP 765
PEP 765@footnote{https://peps.python.org/pep-0765/}) -- they
are only emitted during compilation.

@item 
gh-139640@footnote{https://github.com/python/cpython/issues/139640}: Fix swallowing some syntax warnings in different modules if
they accidentally have the same message and are emitted from the same
line. Fix duplicated warnings in the @code{finally} block.

@item 
gh-63161@footnote{https://github.com/python/cpython/issues/63161}: Support non-UTF-8 shebang and comments in Python source files if
non-UTF-8 encoding is specified. Detect decoding error in comments for
default (UTF-8) encoding. Show the line and position of decoding error for
default encoding in a traceback. Show the line containing the coding
cookie when it conflicts with the BOM in a traceback.
@end itemize

@node ライブラリ<10>,Core and Builtins<9>,Core and Builtins<8>,Python 3 14 1 final
@anchor{whatsnew/changelog id26}@anchor{17de}
@subsubsection ライブラリ



@itemize -

@item 
gh-116738@footnote{https://github.com/python/cpython/issues/116738}: Make @ref{94,,mmap} thread-safe on the @ref{1f4,,free threaded} build.
@end itemize

@node Core and Builtins<9>,ライブラリ<11>,ライブラリ<10>,Python 3 14 1 final
@anchor{whatsnew/changelog id27}@anchor{17df}
@subsubsection Core and Builtins



@itemize -

@item 
gh-138558@footnote{https://github.com/python/cpython/issues/138558}: Fix handling of unusual t-string annotations in annotationlib.
Patch by Dave Peck.

@item 
gh-134466@footnote{https://github.com/python/cpython/issues/134466}: Don't run PyREPL in a degraded environment where setting
termios attributes is not allowed.

@item 
gh-138944@footnote{https://github.com/python/cpython/issues/138944}: Fix @ref{18e,,SyntaxError} message when invalid syntax appears on
the same line as a valid @code{import ... as ...} or @code{from ... import ... as
...} statement. Patch by Brian Schubert.

@item 
gh-105487@footnote{https://github.com/python/cpython/issues/105487}: Remove non-existent @ref{17e0,,__copy__()},
@ref{17e1,,__deepcopy__()}, and @ref{16c5,,__bases__} from the
@ref{17e2,,__dir__()} entries of @ref{9ec,,types.GenericAlias}.

@item 
gh-69605@footnote{https://github.com/python/cpython/issues/69605}: Fix some standard library submodules missing from the
@ref{491,,REPL} auto-completion of imports.
@end itemize

@node ライブラリ<11>,Core and Builtins<10>,Core and Builtins<9>,Python 3 14 1 final
@anchor{whatsnew/changelog id28}@anchor{17e3}
@subsubsection ライブラリ



@itemize -

@item 
gh-116738@footnote{https://github.com/python/cpython/issues/116738}: Make @ref{2b,,cProfile} thread-safe on the @ref{1f4,,free threaded} build.

@item 
gh-138004@footnote{https://github.com/python/cpython/issues/138004}: On Solaris/Illumos platforms, thread names are now encoded as
ASCII to avoid errors on systems (e.g. OpenIndiana) that don't support
non-ASCII names.
@end itemize

@node Core and Builtins<10>,C API<2>,ライブラリ<11>,Python 3 14 1 final
@anchor{whatsnew/changelog id29}@anchor{17e4}
@subsubsection Core and Builtins



@itemize -

@item 
gh-137433@footnote{https://github.com/python/cpython/issues/137433}: Fix a potential deadlock in the @ref{1f4,,free threading} build
when daemon threads enable or disable profiling or tracing while the main
thread is shutting down the interpreter.

@item 
gh-137400@footnote{https://github.com/python/cpython/issues/137400}: Fix a crash in the @ref{1f4,,free threading} build when disabling
profiling or tracing across all threads with
@ref{781,,PyEval_SetProfileAllThreads()} or
@ref{664,,PyEval_SetTraceAllThreads()} or their Python equivalents
@ref{6ef,,threading.settrace_all_threads()} and
@ref{6f0,,threading.setprofile_all_threads()}.

@item 
gh-58124@footnote{https://github.com/python/cpython/issues/58124}: Fix name of the Python encoding in Unicode errors of the code
page codec: use "cp65000" and "cp65001" instead of "CP_UTF7" and "CP_UTF8"
which are not valid Python code names. Patch by Victor Stinner.

@item 
gh-132657@footnote{https://github.com/python/cpython/issues/132657}: Improve performance of @ref{7f2,,frozenset} by removing locks in
the free-threading build.

@item 
gh-133400@footnote{https://github.com/python/cpython/issues/133400}: Fixed Ctrl+D (^D) behavior in _pyrepl module to match old
pre-3.13 REPL behavior.

@item 
gh-128640@footnote{https://github.com/python/cpython/issues/128640}: Fix a crash when using threads inside of a subinterpreter.
@end itemize

@node C API<2>,ビルド<2>,Core and Builtins<10>,Python 3 14 1 final
@anchor{whatsnew/changelog id30}@anchor{17e5}
@subsubsection C API



@itemize -

@item 
gh-137422@footnote{https://github.com/python/cpython/issues/137422}: Fix @ref{1f4,,free threading} race condition in
@ref{5fb,,PyImport_AddModuleRef()}. It was previously possible for two calls
to the function return two different objects, only one of which was stored
in @ref{17e6,,sys.modules}.

@item 
gh-140042@footnote{https://github.com/python/cpython/issues/140042}: Removed the sqlite3_shutdown call that could cause closing
connections for sqlite when used with multiple sub interpreters.

@item 
gh-141042@footnote{https://github.com/python/cpython/issues/141042}: Make qNaN in @ref{969,,PyFloat_Pack2()} and
@ref{96a,,PyFloat_Pack4()}, if while conversion to a narrower precision
floating-point format --- the remaining after truncation payload will be
zero.  Patch by Sergey B Kirpichev.

@item 
gh-140487@footnote{https://github.com/python/cpython/issues/140487}: Fix @ref{17e7,,Py_RETURN_NOTIMPLEMENTED} in limited C API 3.11
and older: don't treat @code{Py_NotImplemented} as immortal. Patch by Victor
Stinner.

@item 
gh-140153@footnote{https://github.com/python/cpython/issues/140153}: Fix @ref{2cf,,Py_REFCNT()} definition on limited C API 3.11-3.13.
Patch by Victor Stinner.

@item 
gh-139653@footnote{https://github.com/python/cpython/issues/139653}: Add @ref{466,,PyUnstable_ThreadState_SetStackProtection()} and
@ref{467,,PyUnstable_ThreadState_ResetStackProtection()} functions to set the
stack protection base address and stack protection size of a Python thread
state. Patch by Victor Stinner.
@end itemize

@node ビルド<2>,,C API<2>,Python 3 14 1 final
@anchor{whatsnew/changelog id31}@anchor{17e8}
@subsubsection ビルド



@itemize -

@item 
gh-141808@footnote{https://github.com/python/cpython/issues/141808}: Do not generate the jit stencils twice in case of PGO builds on
Windows.

@item 
gh-141784@footnote{https://github.com/python/cpython/issues/141784}: Fix @code{_remote_debugging_module.c} compilation on 32-bit Linux.
Include Python.h before system headers to make sure that
@code{_remote_debugging_module.c} uses the same types (ABI) than Python.
Patch by Victor Stinner.

@item 
gh-140768@footnote{https://github.com/python/cpython/issues/140768}: Warn when the WASI SDK version doesn't match what's supported.

@item 
gh-140513@footnote{https://github.com/python/cpython/issues/140513}: Generate a clear compilation error when
@code{_Py_TAIL_CALL_INTERP} is enabled but either @code{preserve_none} or
@code{musttail} is not supported.

@item 
gh-140189@footnote{https://github.com/python/cpython/issues/140189}: iOS builds were added to CI.

@item 
gh-138489@footnote{https://github.com/python/cpython/issues/138489}: When cross-compiling for WASI by @code{build_wasm} or
@code{build_emscripten}, the @code{build-details.json} step is now included in
the build process, just like with native builds.

This fixes the @code{libinstall} task which requires the
@code{build-details.json} file during the process.

@item 
gh-137618@footnote{https://github.com/python/cpython/issues/137618}: @code{PYTHON_FOR_REGEN} now requires Python 3.10 to Python 3.15.
Patch by Adam Turner.

@item 
gh-123681@footnote{https://github.com/python/cpython/issues/123681}: Check the @code{strftime()} behavior at runtime instead of at the
compile time to support cross-compiling. Remove the internal macro
@code{_Py_NORMALIZE_CENTURY}.
@end itemize

@node Python 3 14 0 final,Python 3 14 0 release candidate 3,Python 3 14 1 final,変更履歴
@anchor{whatsnew/changelog python-3-14-0-final}@anchor{17e9}
@subsection Python 3.14.0 final


`Release date: 2025-10-07'

@menu
* macOS: macOS<2>. 
* Windows: Windows<4>. 
* Tools/Demos: Tools/Demos<3>. 
* セキュリティ: セキュリティ<4>. 
* ライブラリ: ライブラリ<12>. 

@end menu

@node macOS<2>,Windows<4>,,Python 3 14 0 final
@anchor{whatsnew/changelog id32}@anchor{17ea}
@subsubsection macOS



@itemize -

@item 
gh-124111@footnote{https://github.com/python/cpython/issues/124111}: Update macOS installer to use Tcl/Tk 8.6.17.

@item 
gh-139573@footnote{https://github.com/python/cpython/issues/139573}: Updated bundled version of OpenSSL to 3.0.18.
@end itemize

@node Windows<4>,Tools/Demos<3>,macOS<2>,Python 3 14 0 final
@anchor{whatsnew/changelog id33}@anchor{17eb}
@subsubsection Windows



@itemize -

@item 
gh-139573@footnote{https://github.com/python/cpython/issues/139573}: Updated bundled version of OpenSSL to 3.0.18.
@end itemize

@node Tools/Demos<3>,セキュリティ<4>,Windows<4>,Python 3 14 0 final
@anchor{whatsnew/changelog id34}@anchor{17ec}
@subsubsection Tools/Demos



@itemize -

@item 
gh-139330@footnote{https://github.com/python/cpython/issues/139330}: SBOM generation tool didn't cross-check the version and
checksum values against the @code{Modules/expat/refresh.sh} script, leading
to the values becoming out-of-date during routine updates.

@item 
gh-132006@footnote{https://github.com/python/cpython/issues/132006}: XCframeworks now include privacy manifests to satisfy Apple App
Store submission requirements.

@item 
gh-138171@footnote{https://github.com/python/cpython/issues/138171}: A script for building an iOS XCframework was added. As part of
this change, the top level @code{iOS} folder has been moved to be a
subdirectory of the @code{Apple} folder.
@end itemize

@node セキュリティ<4>,ライブラリ<12>,Tools/Demos<3>,Python 3 14 0 final
@anchor{whatsnew/changelog id35}@anchor{17ed}
@subsubsection セキュリティ



@itemize -

@item 
gh-139400@footnote{https://github.com/python/cpython/issues/139400}: @ref{12c,,xml.parsers.expat}: Make sure that parent Expat parsers
are only garbage-collected once they are no longer referenced by
subparsers created by
@ref{17ee,,ExternalEntityParserCreate()}. Patch by
Sebastian Pipping.
@end itemize

@node ライブラリ<12>,,セキュリティ<4>,Python 3 14 0 final
@anchor{whatsnew/changelog id36}@anchor{17ef}
@subsubsection ライブラリ



@itemize -

@item 
gh-139312@footnote{https://github.com/python/cpython/issues/139312}: Upgrade bundled libexpat to 2.7.3
@end itemize

@node Python 3 14 0 release candidate 3,Python 3 14 0 release candidate 2,Python 3 14 0 final,変更履歴
@anchor{whatsnew/changelog python-3-14-0-release-candidate-3}@anchor{17f0}
@subsection Python 3.14.0 release candidate 3


`Release date: 2025-09-18'

@menu
* Windows: Windows<5>. 
* Tools/Demos: Tools/Demos<4>. 
* セキュリティ: セキュリティ<5>. 
* ライブラリ: ライブラリ<13>. 
* Core and Builtins: Core and Builtins<11>. 

@end menu

@node Windows<5>,Tools/Demos<4>,,Python 3 14 0 release candidate 3
@anchor{whatsnew/changelog id37}@anchor{17f1}
@subsubsection Windows



@itemize -

@item 
gh-138896@footnote{https://github.com/python/cpython/issues/138896}: Fix error installing C runtime on non-updated Windows machines
@end itemize

@node Tools/Demos<4>,セキュリティ<5>,Windows<5>,Python 3 14 0 release candidate 3
@anchor{whatsnew/changelog id38}@anchor{17f2}
@subsubsection Tools/Demos



@itemize -

@item 
gh-137873@footnote{https://github.com/python/cpython/issues/137873}: The iOS test runner has been simplified, resolving some issues
that have been observed using the runner in GitHub Actions and Azure
Pipelines test environments.
@end itemize

@node セキュリティ<5>,ライブラリ<13>,Tools/Demos<4>,Python 3 14 0 release candidate 3
@anchor{whatsnew/changelog id39}@anchor{17f3}
@subsubsection セキュリティ



@itemize -

@item 
gh-135661@footnote{https://github.com/python/cpython/issues/135661}: Fix CDATA section parsing in @ref{a77,,html.parser.HTMLParser}
according to the HTML5 standard: @code{] ]>} and @code{]] >} no longer end the
CDATA section. Add private method @code{_set_support_cdata()} which can be
used to specify how to parse @code{<[CDATA[} --- as a CDATA section in
foreign content (SVG or MathML) or as a bogus comment in the HTML
namespace.
@end itemize

@node ライブラリ<13>,Core and Builtins<11>,セキュリティ<5>,Python 3 14 0 release candidate 3
@anchor{whatsnew/changelog id40}@anchor{17f4}
@subsubsection ライブラリ



@itemize -

@item 
gh-138998@footnote{https://github.com/python/cpython/issues/138998}: Update bundled libexpat to 2.7.2

@item 
gh-118803@footnote{https://github.com/python/cpython/issues/118803}: Add back @ref{342,,collections.abc.ByteString} and
@ref{345,,typing.ByteString}. Both had been removed in prior alpha, beta and
release candidates for Python 3.14, but their removal has now been
postponed to Python 3.17.

@item 
gh-137226@footnote{https://github.com/python/cpython/issues/137226}: Fix @ref{8c0,,typing.get_type_hints()} calls on generic
@ref{332,,typing.TypedDict} classes defined with string annotations.

@item 
gh-138804@footnote{https://github.com/python/cpython/issues/138804}: Raise @ref{198,,TypeError} instead of @ref{5f0,,AttributeError} when an
argument of incorrect type is passed to @ref{582,,shlex.quote()}. This restores
the behavior of the function prior to 3.14.

@item 
gh-128636@footnote{https://github.com/python/cpython/issues/128636}: Fix crash in PyREPL when os.environ is overwritten with an
invalid value for mac

@item 
gh-138514@footnote{https://github.com/python/cpython/issues/138514}: Raise @ref{2ec,,ValueError} when a multi-character string is passed
to the `echo_char' parameter of @ref{21d,,getpass.getpass()}. Patch by Benjamin
Johnson.

@item 
gh-138515@footnote{https://github.com/python/cpython/issues/138515}: @ref{3f,,email} is added to Emscripten build.

@item 
gh-99948@footnote{https://github.com/python/cpython/issues/99948}: @ref{f45,,ctypes.util.find_library()} now works in Emscripten build.

@item 
gh-138253@footnote{https://github.com/python/cpython/issues/138253}: Add the `block' parameter in the @code{put()} and @code{get()}
methods of the @ref{25,,concurrent.interpreters} queues for compatibility
with the @ref{15ac,,queue.Queue} interface.

@item 
gh-138133@footnote{https://github.com/python/cpython/issues/138133}: Prevent infinite traceback loop when sending CTRL^C to Python
through @code{strace}.

@item 
gh-134869@footnote{https://github.com/python/cpython/issues/134869}: Fix an issue where pressing Ctrl+C during tab completion in the
REPL would leave the autocompletion menu in a corrupted state.

@item 
gh-90548@footnote{https://github.com/python/cpython/issues/90548}: Fix @code{musl} detection for @ref{17f5,,platform.libc_ver()} on Alpine
Linux if compiled with --strip-all.

@item 
gh-136134@footnote{https://github.com/python/cpython/issues/136134}: @code{SMTP.auth_cram_md5()} now raises an
@ref{11a3,,SMTPException} instead of a @ref{2ec,,ValueError} if Python has
been built without MD5 support. In particular, @ref{b27,,SMTP}
clients will not attempt to use this method even if the remote server is
assumed to support it. Patch by Bénédikt Tran.

@item 
gh-136134@footnote{https://github.com/python/cpython/issues/136134}: @ref{17f6,,IMAP4.login_cram_md5} now
raises an @ref{17f7,,IMAP4.error} if CRAM-MD5
authentication is not supported. Patch by Bénédikt Tran.

@item 
gh-134953@footnote{https://github.com/python/cpython/issues/134953}: Expand @code{_colorize} theme with @code{keyword_constant} and
implement in @ref{491,,repl}.
@end itemize

@node Core and Builtins<11>,,ライブラリ<13>,Python 3 14 0 release candidate 3
@anchor{whatsnew/changelog id41}@anchor{17f8}
@subsubsection Core and Builtins



@itemize -

@item 
gh-71810@footnote{https://github.com/python/cpython/issues/71810}: Raise @ref{a81,,OverflowError} for @code{(-1).to_bytes()} for signed
conversions when bytes count is zero.  Patch by Sergey B Kirpichev.

@item 
gh-138192@footnote{https://github.com/python/cpython/issues/138192}: Fix @ref{28,,contextvars} initialization so that all
subinterpreters are assigned the @ref{17f9,,MISSING} value.

@item 
gh-138479@footnote{https://github.com/python/cpython/issues/138479}: Fix a crash when a generic object's @code{__typing_subst__}
returns an object that isn't a @ref{614,,tuple}.

@item 
gh-138372@footnote{https://github.com/python/cpython/issues/138372}: Fix @ref{1ae,,SyntaxWarning} emitted for erroneous subscript
expressions involving @ref{17fa,,template string literals}. Patch
by Brian Schubert.

@item 
gh-138318@footnote{https://github.com/python/cpython/issues/138318}: The default REPL now avoids highlighting built-in names (for
instance @ref{184,,set} or @ref{199,,format()}) when they are used as attribute
names (for instance in @code{value.set} or @code{text.format}).

@item 
gh-138349@footnote{https://github.com/python/cpython/issues/138349}: Fix crash in certain cases where a module contains both a
module-level annotation and a comprehension.

@item 
gh-137384@footnote{https://github.com/python/cpython/issues/137384}: Fix a crash when using the @ref{118,,warnings} module in a
finalizer at shutdown. Patch by Kumar Aditya.

@item 
gh-137883@footnote{https://github.com/python/cpython/issues/137883}: Fix runaway recursion when calling a function with keyword
arguments.

@item 
gh-137079@footnote{https://github.com/python/cpython/issues/137079}: Fix keyword typo recognition when parsing files. Patch by Pablo
Galindo.

@item 
gh-137728@footnote{https://github.com/python/cpython/issues/137728}: Fix the JIT's handling of many local variables. This previously
caused a segfault.

@item 
gh-137576@footnote{https://github.com/python/cpython/issues/137576}: Fix for incorrect source code being shown in tracebacks from
the Basic REPL when 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} is given. Patch by Adam Hartz.
@end itemize

@node Python 3 14 0 release candidate 2,Python 3 14 0 release candidate 1,Python 3 14 0 release candidate 3,変更履歴
@anchor{whatsnew/changelog python-3-14-0-release-candidate-2}@anchor{17fb}
@subsection Python 3.14.0 release candidate 2


`Release date: 2025-08-14'

@menu
* macOS: macOS<3>. 
* Windows: Windows<6>. 
* ライブラリ: ライブラリ<14>. 
* ドキュメント: ドキュメント<5>. 
* Core and Builtins: Core and Builtins<12>. 
* C API: C API<3>. 
* ビルド: ビルド<3>. 

@end menu

@node macOS<3>,Windows<6>,,Python 3 14 0 release candidate 2
@anchor{whatsnew/changelog id42}@anchor{17fc}
@subsubsection macOS



@itemize -

@item 
gh-137450@footnote{https://github.com/python/cpython/issues/137450}: macOS installer shell path management improvements: separate
the installer @code{Shell profile updater} postinstall script from the
@code{Update Shell Profile.command} to enable more robust error handling.

@item 
gh-137134@footnote{https://github.com/python/cpython/issues/137134}: Update macOS installer to ship with SQLite version 3.50.4.
@end itemize

@node Windows<6>,ライブラリ<14>,macOS<3>,Python 3 14 0 release candidate 2
@anchor{whatsnew/changelog id43}@anchor{17fd}
@subsubsection Windows



@itemize -

@item 
gh-137134@footnote{https://github.com/python/cpython/issues/137134}: Update Windows installer to ship with SQLite 3.50.4.
@end itemize

@node ライブラリ<14>,ドキュメント<5>,Windows<6>,Python 3 14 0 release candidate 2
@anchor{whatsnew/changelog id44}@anchor{17fe}
@subsubsection ライブラリ



@itemize -

@item 
gh-137426@footnote{https://github.com/python/cpython/issues/137426}: Remove the code deprecation of
@code{importlib.abc.ResourceLoader}. It is documented as deprecated, but left
for backwards compatibility with other classes in @code{importlib.abc}.

@item 
gh-137282@footnote{https://github.com/python/cpython/issues/137282}: Fix tab completion and @ref{844,,dir()} on
@ref{24,,concurrent.futures}.

@item 
gh-137257@footnote{https://github.com/python/cpython/issues/137257}: Bump the version of pip bundled in ensurepip to version 25.2

@item 
gh-137226@footnote{https://github.com/python/cpython/issues/137226}: Fix behavior of @ref{17b2,,annotationlib.ForwardRef.evaluate()} when
the `type_params' parameter is passed and the name of a type param is also
present in an enclosing scope.

@item 
gh-130522@footnote{https://github.com/python/cpython/issues/130522}: Fix unraisable @ref{198,,TypeError} raised during
@ref{479,,interpreter shutdown} in the @ref{f3,,threading} module.

@item 
gh-137059@footnote{https://github.com/python/cpython/issues/137059}: Fix handling of file URLs with a Windows drive letter in the
URL authority by @ref{2bd,,urllib.request.url2pathname()}. This fixes a
regression in earlier pre-releases of Python 3.14.

@item 
gh-130577@footnote{https://github.com/python/cpython/issues/130577}: @ref{e4,,tarfile} now validates archives to ensure member offsets
are non-negative.  (Contributed by Alexander Enrique Urieles Nieto in
gh-130577@footnote{https://github.com/python/cpython/issues/130577}.)

@item 
gh-135228@footnote{https://github.com/python/cpython/issues/135228}: When @ref{33,,dataclasses} replaces a class with a slotted
dataclass, the original class can now be garbage collected again. Earlier
changes in Python 3.14 caused this class to always remain in existence
together with the replacement class synthesized by @ref{33,,dataclasses}.
@end itemize

@node ドキュメント<5>,Core and Builtins<12>,ライブラリ<14>,Python 3 14 0 release candidate 2
@anchor{whatsnew/changelog id45}@anchor{17ff}
@subsubsection ドキュメント



@itemize -

@item 
gh-136155@footnote{https://github.com/python/cpython/issues/136155}: We are now checking for fatal errors in EPUB builds in CI.
@end itemize

@node Core and Builtins<12>,C API<3>,ドキュメント<5>,Python 3 14 0 release candidate 2
@anchor{whatsnew/changelog id46}@anchor{1800}
@subsubsection Core and Builtins



@itemize -

@item 
gh-137400@footnote{https://github.com/python/cpython/issues/137400}: Fix a crash in the @ref{1f4,,free threading} build when disabling
profiling or tracing across all threads with
@ref{781,,PyEval_SetProfileAllThreads()} or
@ref{664,,PyEval_SetTraceAllThreads()} or their Python equivalents
@ref{6ef,,threading.settrace_all_threads()} and
@ref{6f0,,threading.setprofile_all_threads()}.

@item 
gh-137314@footnote{https://github.com/python/cpython/issues/137314}: Fixed a regression where raw f-strings incorrectly interpreted
escape sequences in format specifications. Raw f-strings now properly
preserve literal backslashes in format specs, matching the behavior from
Python 3.11. For example, @code{rf"@{obj:\xFF@}"} now correctly produces
@code{'\\xFF'} instead of @code{'ÿ'}. Patch by Pablo Galindo.

@item 
gh-137308@footnote{https://github.com/python/cpython/issues/137308}: A standalone docstring in a node body is optimized as a
@ref{17e,,pass} statement to ensure that the node's body is never empty.
There was a @ref{2ec,,ValueError} in @ref{4b1,,compile()} otherwise.

@item 
gh-137288@footnote{https://github.com/python/cpython/issues/137288}: Fix bug where some bytecode instructions of a boolean
expression are not associated with the correct exception handler.

@item 
gh-134291@footnote{https://github.com/python/cpython/issues/134291}: Remove some newer macOS API usage from the JIT compiler in
order to restore compatibility with older OSX 10.15 deployment targets.

@item 
gh-131338@footnote{https://github.com/python/cpython/issues/131338}: Disable computed stack limit checks on non-glibc linux
platforms to fix crashes on deep recursion.

@item 
gh-136870@footnote{https://github.com/python/cpython/issues/136870}: Fix data races while de-instrumenting bytecode of code objects
running concurrently in threads.
@end itemize

@node C API<3>,ビルド<3>,Core and Builtins<12>,Python 3 14 0 release candidate 2
@anchor{whatsnew/changelog id47}@anchor{1801}
@subsubsection C API



@itemize -

@item 
gh-137573@footnote{https://github.com/python/cpython/issues/137573}: Mark @code{_PyOptimizer_Optimize} as @ref{1802,,Py_NO_INLINE} to
prevent stack overflow crashes on macOS.
@end itemize

@node ビルド<3>,,C API<3>,Python 3 14 0 release candidate 2
@anchor{whatsnew/changelog id48}@anchor{1803}
@subsubsection ビルド



@itemize -

@item 
gh-132339@footnote{https://github.com/python/cpython/issues/132339}: Add support for OpenSSL 3.5.
@end itemize

@node Python 3 14 0 release candidate 1,Python 3 14 0 beta 4,Python 3 14 0 release candidate 2,変更履歴
@anchor{whatsnew/changelog python-3-14-0-release-candidate-1}@anchor{1804}
@subsection Python 3.14.0 release candidate 1


`Release date: 2025-07-22'

@menu
* Tools/Demos: Tools/Demos<5>. 
* セキュリティ: セキュリティ<6>. 
* ライブラリ: ライブラリ<15>. 
* Core and Builtins: Core and Builtins<13>. 
* ライブラリ: ライブラリ<16>. 
* Core and Builtins: Core and Builtins<14>. 
* ライブラリ: ライブラリ<17>. 
* Core and Builtins: Core and Builtins<15>. 
* C API: C API<4>. 
* ビルド: ビルド<4>. 

@end menu

@node Tools/Demos<5>,セキュリティ<6>,,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id49}@anchor{1805}
@subsubsection Tools/Demos



@itemize -

@item 
gh-136251@footnote{https://github.com/python/cpython/issues/136251}: Fixes and usability improvements for
@code{Tools/wasm/emscripten/web_example}
@end itemize

@node セキュリティ<6>,ライブラリ<15>,Tools/Demos<5>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id50}@anchor{1806}
@subsubsection セキュリティ



@itemize -

@item 
gh-135661@footnote{https://github.com/python/cpython/issues/135661}: Fix parsing attributes with whitespaces around the @code{=}
separator in @ref{a77,,html.parser.HTMLParser} according to the HTML5
standard.

@item 
gh-118350@footnote{https://github.com/python/cpython/issues/118350}: Fix support of escapable raw text mode (elements "textarea" and
"title") in @ref{a77,,html.parser.HTMLParser}.
@end itemize

@node ライブラリ<15>,Core and Builtins<13>,セキュリティ<6>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id51}@anchor{1807}
@subsubsection ライブラリ



@itemize -

@item 
gh-136170@footnote{https://github.com/python/cpython/issues/136170}: Removed the unreleased @code{zipfile.ZipFile.data_offset} property
added in 3.14.0a7 as it wasn't fully clear which behavior it should have
in some situations so the result was not always what a user might expect.

@item 
gh-124621@footnote{https://github.com/python/cpython/issues/124621}: pyrepl now works in Emscripten.

@item 
gh-136874@footnote{https://github.com/python/cpython/issues/136874}: Discard URL query and fragment in
@ref{2bd,,urllib.request.url2pathname()}.

@item 
gh-130645@footnote{https://github.com/python/cpython/issues/130645}: Enable color help by default in @ref{7,,argparse}.

@item 
gh-136549@footnote{https://github.com/python/cpython/issues/136549}: Fix signature of @ref{a4b,,threading.excepthook()}.

@item 
gh-136523@footnote{https://github.com/python/cpython/issues/136523}: Fix @ref{337,,wave.Wave_write} emitting an unraisable when open
raises.

@item 
gh-52876@footnote{https://github.com/python/cpython/issues/52876}: Add missing @code{keepends} (default @code{True}) parameter to
@code{codecs.StreamReaderWriter.readline()} and
@code{codecs.StreamReaderWriter.readlines()}.

@item 
gh-136470@footnote{https://github.com/python/cpython/issues/136470}: Correct @ref{1d2,,concurrent.futures.InterpreterPoolExecutor}'s
default thread name.

@item 
gh-136476@footnote{https://github.com/python/cpython/issues/136476}: Fix a bug that was causing the @code{get_async_stack_trace}
function to miss some frames in the stack trace.

@item 
gh-136434@footnote{https://github.com/python/cpython/issues/136434}: Fix docs generation of @code{UnboundItem} in
@ref{25,,concurrent.interpreters} when running with @ref{fb5,,-OO}.

@item 
gh-136380@footnote{https://github.com/python/cpython/issues/136380}: Raises @ref{5f0,,AttributeError} when accessing
@ref{1d2,,concurrent.futures.InterpreterPoolExecutor} and subinterpreters
are not available.

@item 
gh-134759@footnote{https://github.com/python/cpython/issues/134759}: Fix @ref{174f,,UnboundLocalError} in
@ref{13e5,,email.message.Message.get_payload()} when the payload to decode is a
@ref{192,,bytes} object. Patch by Kliment Lamonov.

@item 
gh-134657@footnote{https://github.com/python/cpython/issues/134657}: @ref{b,,asyncio}: Remove some private names from
@code{asyncio.__all__}.
@end itemize

@node Core and Builtins<13>,ライブラリ<16>,ライブラリ<15>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id52}@anchor{1808}
@subsubsection Core and Builtins



@itemize -

@item 
gh-136801@footnote{https://github.com/python/cpython/issues/136801}: Fix PyREPL syntax highlighting on match cases after multi-line
case. Contributed by Olga Matoula.
@end itemize

@node ライブラリ<16>,Core and Builtins<14>,Core and Builtins<13>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id53}@anchor{1809}
@subsubsection ライブラリ



@itemize -

@item 
gh-136421@footnote{https://github.com/python/cpython/issues/136421}: Fix crash when initializing @ref{34,,datetime} concurrently.
@end itemize

@node Core and Builtins<14>,ライブラリ<17>,ライブラリ<16>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id54}@anchor{180a}
@subsubsection Core and Builtins



@itemize -

@item 
gh-136541@footnote{https://github.com/python/cpython/issues/136541}: Fix some issues with the perf trampolines on x86-64 and
aarch64.  The trampolines were not being generated correctly for some
cases, which could lead to the perf integration not working correctly.
Patch by Pablo Galindo.

@item 
gh-136517@footnote{https://github.com/python/cpython/issues/136517}: Fixed a typo that prevented printing of uncollectable objects
when the @ref{13da,,gc.DEBUG_UNCOLLECTABLE} mode was set.

@item 
gh-136525@footnote{https://github.com/python/cpython/issues/136525}: Fix issue where per-thread bytecode was not instrumented for
newly created threads.

@item 
gh-132661@footnote{https://github.com/python/cpython/issues/132661}: @code{Interpolation.expression} now has a default, the empty
string.

@item 
gh-132661@footnote{https://github.com/python/cpython/issues/132661}: Reflect recent 
@geindex Python Enhancement Proposals; PEP 750
PEP 750@footnote{https://peps.python.org/pep-0750/} change.

Disallow concatenation of @code{string.templatelib.Template} and
@ref{169,,str}. Also, disallow implicit concatenation of t-string literals
with string or f-string literals.
@end itemize

@node ライブラリ<17>,Core and Builtins<15>,Core and Builtins<14>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id55}@anchor{180b}
@subsubsection ライブラリ



@itemize -

@item 
gh-116738@footnote{https://github.com/python/cpython/issues/116738}: Make functions in @ref{6a,,grp} thread-safe on the @ref{1f4,,free threaded} build.
@end itemize

@node Core and Builtins<15>,C API<4>,ライブラリ<17>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id56}@anchor{180c}
@subsubsection Core and Builtins



@itemize -

@item 
gh-135148@footnote{https://github.com/python/cpython/issues/135148}: Fixed a bug where f-string debug expressions (using =) would
incorrectly strip out parts of strings containing escaped quotes and #
characters. Patch by Pablo Galindo.

@item 
gh-133136@footnote{https://github.com/python/cpython/issues/133136}: Limit excess memory usage in the @ref{1f4,,free threading} build
when a large dictionary or list is resized and accessed by multiple
threads.

@item 
gh-91153@footnote{https://github.com/python/cpython/issues/91153}: Fix a crash when a @ref{344,,bytearray} is concurrently mutated
during item assignment.

@item 
gh-127971@footnote{https://github.com/python/cpython/issues/127971}: Fix off-by-one read beyond the end of a string in string
search.
@end itemize

@node C API<4>,ビルド<4>,Core and Builtins<15>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id57}@anchor{180d}
@subsubsection C API



@itemize -

@item 
gh-112068@footnote{https://github.com/python/cpython/issues/112068}: Revert support of nullable arguments in @ref{180e,,PyArg_Parse()}.

@item 
gh-133296@footnote{https://github.com/python/cpython/issues/133296}: New variants for the critical section API that accept one or
two @ref{484,,PyMutex} pointers rather than @ref{5df,,PyObject} instances
are now public in the non-limited C API.

@item 
gh-134009@footnote{https://github.com/python/cpython/issues/134009}: Expose @ref{463,,PyMutex_IsLocked()} as part of the public C API.
@end itemize

@node ビルド<4>,,C API<4>,Python 3 14 0 release candidate 1
@anchor{whatsnew/changelog id58}@anchor{180f}
@subsubsection ビルド



@itemize -

@item 
gh-135621@footnote{https://github.com/python/cpython/issues/135621}: PyREPL no longer depends on the @ref{2f,,curses} standard library.
Contributed by Łukasz Langa.
@end itemize

@node Python 3 14 0 beta 4,Python 3 14 0 beta 3,Python 3 14 0 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-14-0-beta-4}@anchor{1810}
@subsection Python 3.14.0 beta 4


`Release date: 2025-07-08'

@menu
* Tools/Demos: Tools/Demos<6>. 
* テスト: テスト<3>. 
* セキュリティ: セキュリティ<7>. 
* ライブラリ: ライブラリ<18>. 
* ドキュメント: ドキュメント<6>. 
* Core and Builtins: Core and Builtins<16>. 
* C API: C API<5>. 
* ビルド: ビルド<5>. 

@end menu

@node Tools/Demos<6>,テスト<3>,,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id59}@anchor{1811}
@subsubsection Tools/Demos



@itemize -

@item 
gh-135968@footnote{https://github.com/python/cpython/issues/135968}: Stubs for @code{strip} are now provided as part of an iOS install.

@item 
gh-133600@footnote{https://github.com/python/cpython/issues/133600}: Backport file reorganization for Tools/wasm/wasi.

This should make backporting future code changes easier. It also
simplifies instructions around how to do WASI builds in the devguide.
@end itemize

@node テスト<3>,セキュリティ<7>,Tools/Demos<6>,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id60}@anchor{1812}
@subsubsection テスト



@itemize -

@item 
gh-135966@footnote{https://github.com/python/cpython/issues/135966}: The iOS testbed now handles the @code{app_packages} folder as a
site directory.

@item 
gh-135494@footnote{https://github.com/python/cpython/issues/135494}: Fix regrtest to support excluding tests from @code{--pgo} tests.
Patch by Victor Stinner.
@end itemize

@node セキュリティ<7>,ライブラリ<18>,テスト<3>,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id61}@anchor{1813}
@subsubsection セキュリティ



@itemize -

@item 
gh-136053@footnote{https://github.com/python/cpython/issues/136053}: @ref{91,,marshal}: fix a possible crash when deserializing
@ref{694,,slice} objects.

@item 
gh-135661@footnote{https://github.com/python/cpython/issues/135661}: Fix parsing start and end tags in
@ref{a77,,html.parser.HTMLParser} according to the HTML5 standard.


@itemize *

@item 
Whitespaces no longer accepted between @code{</} and the tag name.
E.g. @code{</ script>} does not end the script section.

@item 
Vertical tabulation (@code{\v}) and non-ASCII whitespaces no longer recognized
as whitespaces. The only whitespaces are @code{\t\n\r\f} and space.

@item 
Null character (U+0000) no longer ends the tag name.

@item 
Attributes and slashes after the tag name in end tags are now ignored,
instead of terminating after the first @code{>} in quoted attribute value.
E.g. @code{</script/foo=">"/>}.

@item 
Multiple slashes and whitespaces between the last attribute and closing @code{>}
are now ignored in both start and end tags. E.g. @code{<a foo=bar/ //>}.

@item 
Multiple @code{=} between attribute name and value are no longer collapsed.
E.g. @code{<a foo==bar>} produces attribute "foo" with value "=bar".

@item 
[Reverted in gh-136927@footnote{https://github.com/python/cpython/issues/136927}] Whitespaces between the @code{=} separator and attribute name or value are no
longer ignored. E.g. @code{<a foo =bar>} produces two attributes "foo" and
"=bar", both with value None; @code{<a foo= bar>} produces two attributes:
"foo" with value "" and "bar" with value None.
@end itemize

@item 
gh-102555@footnote{https://github.com/python/cpython/issues/102555}: Fix comment parsing in @ref{a77,,html.parser.HTMLParser}
according to the HTML5 standard. @code{--!>} now ends the comment. @code{-- >}
no longer ends the comment. Support abnormally ended empty comments
@code{<-->} and @code{<--->}.
@end itemize

@node ライブラリ<18>,ドキュメント<6>,セキュリティ<7>,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id62}@anchor{1814}
@subsubsection ライブラリ



@itemize -

@item 
gh-136286@footnote{https://github.com/python/cpython/issues/136286}: Fix pickling failures for protocols 0 and 1 for many objects
realted to subinterpreters.

@item 
gh-136316@footnote{https://github.com/python/cpython/issues/136316}: Improve support for evaluating nested forward references in
@ref{1815,,typing.evaluate_forward_ref()}.

@item 
gh-85702@footnote{https://github.com/python/cpython/issues/85702}: If @code{zoneinfo._common.load_tzdata} is given a package without a
resource a @ref{1816,,zoneinfo.ZoneInfoNotFoundError} is raised rather than a
@ref{f3e,,PermissionError}. Patch by Victor Stinner.

@item 
gh-136028@footnote{https://github.com/python/cpython/issues/136028}: Fix parsing month names containing "İ" (U+0130, LATIN CAPITAL
LETTER I WITH DOT ABOVE) in @ref{1646,,time.strptime()}. This affects locales
az_AZ, ber_DZ, ber_MA and crh_UA.

@item 
gh-135995@footnote{https://github.com/python/cpython/issues/135995}: In the palmos encoding, make byte @code{0x9b} decode to @code{›}
(U+203A - SINGLE RIGHT-POINTING ANGLE QUOTATION MARK).

@item 
gh-53203@footnote{https://github.com/python/cpython/issues/53203}: Fix @ref{1646,,time.strptime()} for @code{%c} and @code{%x} formats on
locales byn_ER, wal_ET and lzh_TW, and for @code{%X} format on locales ar_SA,
bg_BG and lzh_TW.

@item 
gh-91555@footnote{https://github.com/python/cpython/issues/91555}: An earlier change, which was introduced in 3.14.0b2, has been
reverted. It disabled logging for a logger during handling of log messages
for that logger. Since the reversion, the behaviour should be as it was
before 3.14.0b2.

@item 
gh-135878@footnote{https://github.com/python/cpython/issues/135878}: Fixes a crash of @ref{4e5,,types.SimpleNamespace} on @ref{1f4,,free threading} builds, when several threads were calling its
@ref{82f,,__repr__()} method at the same time.

@item 
gh-135836@footnote{https://github.com/python/cpython/issues/135836}: Fix @ref{174e,,IndexError} in @ref{818,,asyncio.loop.create_connection()}
that could occur when non-@ref{2c0,,OSError} exception is raised during
connection and socket's @code{close()} raises @code{OSError}.

@item 
gh-135836@footnote{https://github.com/python/cpython/issues/135836}: Fix @ref{174e,,IndexError} in @ref{818,,asyncio.loop.create_connection()}
that could occur when the Happy Eyeballs algorithm resulted in an empty
exceptions list during connection attempts.

@item 
gh-135855@footnote{https://github.com/python/cpython/issues/135855}: Raise @ref{198,,TypeError} instead of @ref{795,,SystemError} when
@code{_interpreters.set___main___attrs()} is passed a non-dict object.
Patch by Brian Schubert.

@item 
gh-135815@footnote{https://github.com/python/cpython/issues/135815}: @ref{9f,,netrc}: skip security checks if @ref{1817,,os.getuid()} is
missing. Patch by Bénédikt Tran.

@item 
gh-135640@footnote{https://github.com/python/cpython/issues/135640}: Address bug where it was possible to call
@ref{c8c,,xml.etree.ElementTree.ElementTree.write()} on an ElementTree object
with an invalid root element. This behavior blanked the file passed to
@code{write} if it already existed.

@item 
gh-135645@footnote{https://github.com/python/cpython/issues/135645}: Added @code{supports_isolated_interpreters} field to
@ref{73b,,sys.implementation}.

@item 
gh-135646@footnote{https://github.com/python/cpython/issues/135646}: Raise consistent @ref{452,,NameError} exceptions in
@ref{17b2,,annotationlib.ForwardRef.evaluate()}

@item 
gh-135557@footnote{https://github.com/python/cpython/issues/135557}: Fix races on @ref{6d,,heapq} updates and @ref{24d,,list} reads on
the @ref{1f4,,free threaded} build.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: Only fetch globals and locals if necessary in
@ref{459,,annotationlib.get_annotations()}

@item 
gh-135561@footnote{https://github.com/python/cpython/issues/135561}: Fix a crash on DEBUG builds when an HACL* HMAC routine fails.
Patch by Bénédikt Tran.

@item 
gh-135487@footnote{https://github.com/python/cpython/issues/135487}: Fix @code{reprlib.Repr.repr_int()} when given integers with
more than @ref{1818,,sys.get_int_max_str_digits()} digits. Patch by Bénédikt
Tran.

@item 
gh-135335@footnote{https://github.com/python/cpython/issues/135335}: @ref{98,,multiprocessing}: Flush @code{stdout} and @code{stderr} after
preloading modules in the @code{forkserver}.

@item 
gh-135069@footnote{https://github.com/python/cpython/issues/135069}: Fix the "Invalid error handling" exception in
@code{encodings.idna.IncrementalDecoder} to correctly replace the
'errors' parameter.

@item 
gh-130662@footnote{https://github.com/python/cpython/issues/130662}: +Accept leading zeros in precision and width fields for
+:class:@ref{1fe,,Decimal} formatting, for example @code{format(Decimal(1.25),
'.016f')}.

@item 
gh-130662@footnote{https://github.com/python/cpython/issues/130662}: Accept leading zeros in precision and width fields for
@ref{213,,Fraction} formatting, for example @code{format(Fraction(1,
3), '.016f')}.

@item 
gh-87790@footnote{https://github.com/python/cpython/issues/87790}: Support underscore and comma as thousands separators in the
fractional part for @ref{213,,Fraction}'s formatting.  Patch by
Sergey B Kirpichev.

@item 
gh-87790@footnote{https://github.com/python/cpython/issues/87790}: Support underscore and comma as thousands separators in the
fractional part for @ref{1fe,,Decimal}'s formatting.  Patch by
Sergey B Kirpichev.

@item 
gh-130664@footnote{https://github.com/python/cpython/issues/130664}: Handle corner-case for @ref{213,,Fraction}'s
formatting: treat zero-padding (preceding the width field by a zero
(@code{'0'}) character) as an equivalent to a fill character of @code{'0'} with
an alignment type of @code{'='}, just as in case of @ref{196,,float}'s.
@end itemize

@node ドキュメント<6>,Core and Builtins<16>,ライブラリ<18>,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id63}@anchor{1819}
@subsubsection ドキュメント



@itemize -

@item 
gh-136155@footnote{https://github.com/python/cpython/issues/136155}: EPUB builds are fixed by excluding non-XHTML-compatible tags.
@end itemize

@node Core and Builtins<16>,C API<5>,ドキュメント<6>,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id64}@anchor{181a}
@subsubsection Core and Builtins



@itemize -

@item 
gh-109700@footnote{https://github.com/python/cpython/issues/109700}: Fix memory error handling in @ref{5e4,,PyDict_SetDefault()}.

@item 
gh-78465@footnote{https://github.com/python/cpython/issues/78465}: Fix error message for @code{cls.__new__(cls, ...)} where @code{cls} is
not instantiable builtin or extension type (with @code{tp_new} set to
@code{NULL}).

@item 
gh-129958@footnote{https://github.com/python/cpython/issues/129958}: Differentiate between t-strings and f-strings in syntax error
for newlines in format specifiers of single-quoted interpolated strings.

@item 
gh-135871@footnote{https://github.com/python/cpython/issues/135871}: Non-blocking mutex lock attempts now return immediately when
the lock is busy instead of briefly spinning in the @ref{1f4,,free threading}
build.

@item 
gh-135106@footnote{https://github.com/python/cpython/issues/135106}: Restrict the trashcan mechanism to GC'ed objects and untrack
them while in the trashcan to prevent the GC and trashcan mechanisms
conflicting.

@item 
gh-135607@footnote{https://github.com/python/cpython/issues/135607}: Fix potential @ref{11a,,weakref} races in an object's destructor on
the @ref{1f4,,free threaded} build.

@item 
gh-135608@footnote{https://github.com/python/cpython/issues/135608}: Fix a crash in the JIT involving attributes of modules.

@item 
gh-135543@footnote{https://github.com/python/cpython/issues/135543}: Emit @code{sys.remote_exec} audit event when
@ref{16d,,sys.remote_exec()} is called and migrate @code{remote_debugger_script}
to @code{cpython.remote_debugger_script}.

@item 
gh-134280@footnote{https://github.com/python/cpython/issues/134280}: Disable constant folding for @code{~} with a boolean argument.
This moves the deprecation warning from compile time to runtime.
@end itemize

@node C API<5>,ビルド<5>,Core and Builtins<16>,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id65}@anchor{181b}
@subsubsection C API



@itemize -

@item 
gh-135906@footnote{https://github.com/python/cpython/issues/135906}: Fix compilation errors when compiling the internal headers with
a C++ compiler.
@end itemize

@node ビルド<5>,,C API<5>,Python 3 14 0 beta 4
@anchor{whatsnew/changelog id66}@anchor{181c}
@subsubsection ビルド



@itemize -

@item 
gh-134273@footnote{https://github.com/python/cpython/issues/134273}: Add support for configuring compiler flags for the JIT with
@code{CFLAGS_JIT}
@end itemize

@node Python 3 14 0 beta 3,Python 3 14 0 beta 2,Python 3 14 0 beta 4,変更履歴
@anchor{whatsnew/changelog python-3-14-0-beta-3}@anchor{181d}
@subsection Python 3.14.0 beta 3


`Release date: 2025-06-17'

@menu
* Windows: Windows<7>. 
* テスト: テスト<4>. 
* セキュリティ: セキュリティ<8>. 
* ライブラリ: ライブラリ<19>. 
* ドキュメント: ドキュメント<7>. 
* Core and Builtins: Core and Builtins<17>. 
* ライブラリ: ライブラリ<20>. 
* Core and Builtins: Core and Builtins<18>. 
* ライブラリ: ライブラリ<21>. 
* Core and Builtins: Core and Builtins<19>. 
* ライブラリ: ライブラリ<22>. 
* Core and Builtins: Core and Builtins<20>. 
* C API: C API<6>. 
* ビルド: ビルド<6>. 

@end menu

@node Windows<7>,テスト<4>,,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id67}@anchor{181e}
@subsubsection Windows



@itemize -

@item 
gh-135099@footnote{https://github.com/python/cpython/issues/135099}: Fix a crash that could occur on Windows when a background
thread waits on a @ref{484,,PyMutex} while the main thread is shutting down
the interpreter.
@end itemize

@node テスト<4>,セキュリティ<8>,Windows<7>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id68}@anchor{181f}
@subsubsection テスト



@itemize -

@item 
gh-132815@footnote{https://github.com/python/cpython/issues/132815}: Fix test__opcode: add @code{JUMP_BACKWARD} to specialization
stats.

@item 
gh-135489@footnote{https://github.com/python/cpython/issues/135489}: Show verbose output for failing tests during PGO profiling step
with --enable-optimizations.

@item 
gh-135120@footnote{https://github.com/python/cpython/issues/135120}: Add @code{test.support.subTests()}.
@end itemize

@node セキュリティ<8>,ライブラリ<19>,テスト<4>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id69}@anchor{1820}
@subsubsection セキュリティ



@itemize -

@item 
gh-135462@footnote{https://github.com/python/cpython/issues/135462}: Fix quadratic complexity in processing specially crafted input
in @ref{a77,,html.parser.HTMLParser}. End-of-file errors are now handled
according to the HTML5 specs -- comments and declarations are
automatically closed, tags are ignored.

@item 
gh-135034@footnote{https://github.com/python/cpython/issues/135034}: Fixes multiple issues that allowed @code{tarfile} extraction
filters (@code{filter="data"} and @code{filter="tar"}) to be bypassed using
crafted symlinks and hard links.

Addresses 
@geindex Common Vulnerabilities and Exposures; CVE 2024-12718
CVE 2024-12718@footnote{https://www.cve.org/CVERecord?id=CVE-2024-12718}, 
@geindex Common Vulnerabilities and Exposures; CVE 2025-4138
CVE 2025-4138@footnote{https://www.cve.org/CVERecord?id=CVE-2025-4138}, 
@geindex Common Vulnerabilities and Exposures; CVE 2025-4330
CVE 2025-4330@footnote{https://www.cve.org/CVERecord?id=CVE-2025-4330}, and
@geindex Common Vulnerabilities and Exposures; CVE 2025-4517
CVE 2025-4517@footnote{https://www.cve.org/CVERecord?id=CVE-2025-4517}.
@end itemize

@node ライブラリ<19>,ドキュメント<7>,セキュリティ<8>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id70}@anchor{1821}
@subsubsection ライブラリ



@itemize -

@item 
gh-65697@footnote{https://github.com/python/cpython/issues/65697}: @ref{26,,configparser}'s error message when attempting to write
an invalid key is now more helpful.

@item 
gh-135497@footnote{https://github.com/python/cpython/issues/135497}: Fix @ref{1822,,os.getlogin()} failing for longer usernames on
BSD-based platforms.

@item 
gh-135429@footnote{https://github.com/python/cpython/issues/135429}: Fix the argument mismatch in @code{_lsprof} for @code{PY_THROW}
event.

@item 
gh-135368@footnote{https://github.com/python/cpython/issues/135368}: Fix @ref{c3f,,unittest.mock.Mock} generation on
@ref{4e1,,dataclasses.dataclass()} objects. Now all special attributes are set
as it was before gh-124429@footnote{https://github.com/python/cpython/issues/124429}.

@item 
gh-133967@footnote{https://github.com/python/cpython/issues/133967}: Do not normalize @ref{8a,,locale} name 'C.UTF-8' to 'en_US.UTF-8'.

@item 
gh-135321@footnote{https://github.com/python/cpython/issues/135321}: Raise a correct exception for values greater than 0x7fffffff
for the @code{BINSTRING} opcode in the C implementation of @ref{ab,,pickle}.

@item 
gh-135276@footnote{https://github.com/python/cpython/issues/135276}: Backported bugfixes in zipfile.Path from zipp 3.23. Fixed
@code{.name}, @code{.stem} and other basename-based properties on Windows when
working with a zipfile on disk.

@item 
gh-135244@footnote{https://github.com/python/cpython/issues/135244}: @ref{116,,uuid}: when the MAC address cannot be determined, the
48-bit node ID is now generated with a cryptographically-secure
pseudo-random number generator (CSPRNG) as per 
@geindex RFC; RFC 9562 Section 6.10-3
RFC 9562@comma{} §6.10.3@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-6.10-3}. This affects @ref{da1,,uuid1()} and
@ref{2c2,,uuid6()}.

@item 
gh-134970@footnote{https://github.com/python/cpython/issues/134970}: Fix the "unknown action" exception in
@ref{2eb,,argparse.ArgumentParser.add_argument_group()} to correctly replace
the action class.

@item 
gh-134718@footnote{https://github.com/python/cpython/issues/134718}: @ref{ae1,,ast.dump()} now only omits @code{None} and @code{[]} values if
they are default values.

@item 
gh-134939@footnote{https://github.com/python/cpython/issues/134939}: Add the @ref{25,,concurrent.interpreters} module.  See 
@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}.

@item 
gh-134885@footnote{https://github.com/python/cpython/issues/134885}: Fix possible crash in the @ref{23,,compression.zstd} module
related to setting parameter types. Patch by Jelle Zijlstra.

@item 
gh-134857@footnote{https://github.com/python/cpython/issues/134857}: Improve error report for @ref{3e,,doctest}s run with
@ref{10c,,unittest}. Remove @code{doctest} module frames from tracebacks and
redundant newline character from a failure message.

@item 
gh-128840@footnote{https://github.com/python/cpython/issues/128840}: Fix parsing long IPv6 addresses with embedded IPv4 address.

@item 
gh-134637@footnote{https://github.com/python/cpython/issues/134637}: Fix performance regression in calling a @ref{2e,,ctypes} function
pointer in @ref{1f4,,free threading}.

@item 
gh-134696@footnote{https://github.com/python/cpython/issues/134696}: Built-in HACL* and OpenSSL implementations of hash function
constructors now correctly accept the same `documented' named arguments.
For instance, @ref{1823,,md5()} could be previously invoked as
@code{md5(data=data)} or @code{md5(string=string)} depending on the underlying
implementation but these calls were not compatible. Patch by Bénédikt
Tran.

@item 
gh-134151@footnote{https://github.com/python/cpython/issues/134151}: @ref{3f,,email}: Fix @ref{198,,TypeError} in
@ref{1824,,email.utils.decode_params()} when sorting 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} continuations
that contain an unnumbered section.

@item 
gh-134210@footnote{https://github.com/python/cpython/issues/134210}: @ref{1825,,curses.window.getch()} now correctly handles signals.
Patch by Bénédikt Tran.

@item 
gh-134152@footnote{https://github.com/python/cpython/issues/134152}: @ref{3f,,email}: Fix parsing of email message ID with invalid
domain.

@item 
gh-133489@footnote{https://github.com/python/cpython/issues/133489}: @ref{120f,,random.getrandbits()} can now generate more that 2@w{^31} bits. @ref{1826,,random.randbytes()} can now generate more that 256
MiB.

@item 
gh-132813@footnote{https://github.com/python/cpython/issues/132813}: Improve error messages for incorrect types and values of
@ref{1827,,csv.Dialect} attributes.

@item 
gh-132969@footnote{https://github.com/python/cpython/issues/132969}: Prevent the @ref{1d6,,ProcessPoolExecutor}
executor thread, which remains running when @ref{aea,,shutdown(wait=False)}, from attempting to adjust the
pool's worker processes after the object state has already been reset
during shutdown. A combination of conditions, including a worker process
having terminated abormally, resulted in an exception and a potential hang
when the still-running executor thread attempted to replace dead workers
within the pool.

@item 
gh-127081@footnote{https://github.com/python/cpython/issues/127081}: Fix libc thread safety issues with @ref{a5,,os} by replacing
@code{getlogin} with @code{getlogin_r} re-entrant version.

@item 
gh-131884@footnote{https://github.com/python/cpython/issues/131884}: Fix formatting issues in @ref{f40,,json.dump()} when both `indent'
and `skipkeys' are used.

@item 
gh-130999@footnote{https://github.com/python/cpython/issues/130999}: Avoid exiting the new REPL and offer suggestions even if there
are non-string candidates when errors occur.
@end itemize

@node ドキュメント<7>,Core and Builtins<17>,ライブラリ<19>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id71}@anchor{1828}
@subsubsection ドキュメント



@itemize -

@item 
gh-135171@footnote{https://github.com/python/cpython/issues/135171}: Document that the @ref{4c8,,iterator} for the leftmost
@code{for} clause in the generator expression is created immediately.

@item 
bpo-45210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45210}: Document that error indicator may be set in tp_dealloc, and how
to avoid clobbering it.
@end itemize

@node Core and Builtins<17>,ライブラリ<20>,ドキュメント<7>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id72}@anchor{1829}
@subsubsection Core and Builtins



@itemize -

@item 
gh-135496@footnote{https://github.com/python/cpython/issues/135496}: Fix typo in the f-string conversion type error ("exclamanation"
-> "exclamation").

@item 
gh-135371@footnote{https://github.com/python/cpython/issues/135371}: Fixed @ref{b,,asyncio} debugging tools to properly display
internal coroutine call stacks alongside external task dependencies. The
@code{python -m asyncio ps} and @code{python -m asyncio pstree} commands now
show complete execution context. Patch by Pablo Galindo.
@end itemize

@node ライブラリ<20>,Core and Builtins<18>,Core and Builtins<17>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id73}@anchor{182a}
@subsubsection ライブラリ



@itemize -

@item 
gh-127319@footnote{https://github.com/python/cpython/issues/127319}: Set the @code{allow_reuse_port} class variable to @code{False} on the
XMLRPC, logging, and HTTP servers. This matches the behavior in prior
Python releases, which is to not allow port reuse.
@end itemize

@node Core and Builtins<18>,ライブラリ<21>,ライブラリ<20>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id74}@anchor{182b}
@subsubsection Core and Builtins



@itemize -

@item 
gh-135171@footnote{https://github.com/python/cpython/issues/135171}: Reverts the behavior of async generator expressions when
created with object w/o __aiter__ method to the pre-3.13 behavior of
raising a TypeError.

@item 
gh-130077@footnote{https://github.com/python/cpython/issues/130077}: Properly raise custom syntax errors when incorrect syntax
containing names that are prefixes of soft keywords is encountered.  Patch
by Pablo Galindo.

@item 
gh-135171@footnote{https://github.com/python/cpython/issues/135171}: Reverts the behavior of generator expressions when created with
a non-iterable to the pre-3.13 behavior of raising a TypeError. It is no
longer possible to cause a crash in the debugger by altering the generator
expression's local variables. This is achieved by moving the @code{GET_ITER}
instruction back to the creation of the generator expression and adding an
additional check to @code{FOR_ITER}.
@end itemize

@node ライブラリ<21>,Core and Builtins<19>,Core and Builtins<18>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id75}@anchor{182c}
@subsubsection ライブラリ



@itemize -

@item 
gh-116738@footnote{https://github.com/python/cpython/issues/116738}: Make methods in @ref{6d,,heapq} thread-safe on the @ref{1f4,,free threaded} build.
@end itemize

@node Core and Builtins<19>,ライブラリ<22>,ライブラリ<21>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id76}@anchor{182d}
@subsubsection Core and Builtins



@itemize -

@item 
gh-134876@footnote{https://github.com/python/cpython/issues/134876}: Add support to 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/} remote debugging for Linux kernels
which don't have CONFIG_CROSS_MEMORY_ATTACH configured.

@item 
gh-134889@footnote{https://github.com/python/cpython/issues/134889}: Fix handling of a few opcodes that leave operands on the stack
when optimizing @code{LOAD_FAST}.
@end itemize

@node ライブラリ<22>,Core and Builtins<20>,Core and Builtins<19>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id77}@anchor{182e}
@subsubsection ライブラリ



@itemize -

@item 
gh-134908@footnote{https://github.com/python/cpython/issues/134908}: Fix crash when iterating over lines in a text file on the
@ref{1f4,,free threaded} build.
@end itemize

@node Core and Builtins<20>,C API<6>,ライブラリ<22>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id78}@anchor{182f}
@subsubsection Core and Builtins



@itemize -

@item 
gh-132617@footnote{https://github.com/python/cpython/issues/132617}: Fix @ref{167e,,dict.update()} modification check that could
incorrectly raise a "dict mutated during update" error when a different
dictionary was modified that happens to share the same underlying keys
object.

@item 
gh-134679@footnote{https://github.com/python/cpython/issues/134679}: Fix crash in the @ref{1f4,,free threading} build's QSBR code that
could occur when changing an object's @code{__dict__} attribute.

@item 
gh-127682@footnote{https://github.com/python/cpython/issues/127682}: No longer call @code{__iter__} twice in list comprehensions. This
brings the behavior of list comprehensions in line with other forms of
iteration

@item 
gh-133912@footnote{https://github.com/python/cpython/issues/133912}: Fix the C API function @code{PyObject_GenericSetDict} to handle
extension classes with inline values.
@end itemize

@node C API<6>,ビルド<6>,Core and Builtins<20>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id79}@anchor{1830}
@subsubsection C API



@itemize -

@item 
gh-134989@footnote{https://github.com/python/cpython/issues/134989}: Fix @code{Py_RETURN_NONE}, @code{Py_RETURN_TRUE} and
@code{Py_RETURN_FALSE} macros in the limited C API 3.11 and older: don't
treat @code{Py_None}, @code{Py_True} and @code{Py_False} as immortal. Patch by
Victor Stinner.

@item 
gh-134989@footnote{https://github.com/python/cpython/issues/134989}: Implement @ref{1831,,PyObject_DelAttr()} and
@ref{1832,,PyObject_DelAttrString()} as macros in the limited C API 3.12 and
older. Patch by Victor Stinner.

@item 
gh-133968@footnote{https://github.com/python/cpython/issues/133968}: Add @ref{3b9,,PyUnicodeWriter_WriteASCII()} function to write an
ASCII string into a @ref{3b3,,PyUnicodeWriter}. The function is faster than
@ref{3bf,,PyUnicodeWriter_WriteUTF8()}, but has an undefined behavior if the
input string contains non-ASCII characters. Patch by Victor Stinner.
@end itemize

@node ビルド<6>,,C API<6>,Python 3 14 0 beta 3
@anchor{whatsnew/changelog id80}@anchor{1833}
@subsubsection ビルド



@itemize -

@item 
gh-119132@footnote{https://github.com/python/cpython/issues/119132}: Remove "experimental" tag from the CPython free-threading
build.

@item 
gh-135497@footnote{https://github.com/python/cpython/issues/135497}: Fix the detection of @code{MAXLOGNAME} in the @code{configure.ac}
script.

@item 
gh-134923@footnote{https://github.com/python/cpython/issues/134923}: Windows builds with profile-guided optimization enabled now use
@code{/GENPROFILE} and @code{/USEPROFILE} instead of deprecated @code{/LTCG:}
options.

@item 
gh-134774@footnote{https://github.com/python/cpython/issues/134774}: Fix @ref{1834,,Py_DEBUG} macro redefinition warnings on Windows
debug builds. Patch by Chris Eibl.

@item 
gh-134632@footnote{https://github.com/python/cpython/issues/134632}: Fixed @code{build-details.json} generation to use @code{INCLUDEPY},
in order to reference the @code{pythonX.Y} subdirectory of the include
directory, as required in 
@geindex Python Enhancement Proposals; PEP 739
PEP 739@footnote{https://peps.python.org/pep-0739/}, instead of the top-level include
directory.
@end itemize

@node Python 3 14 0 beta 2,Python 3 14 0 beta 1,Python 3 14 0 beta 3,変更履歴
@anchor{whatsnew/changelog python-3-14-0-beta-2}@anchor{1835}
@subsection Python 3.14.0 beta 2


`Release date: 2025-05-26'

@menu
* Windows: Windows<8>. 
* Tools/Demos: Tools/Demos<7>. 
* テスト: テスト<5>. 
* セキュリティ: セキュリティ<9>. 
* ライブラリ: ライブラリ<23>. 
* Core and Builtins: Core and Builtins<21>. 
* C API: C API<7>. 
* ビルド: ビルド<7>. 

@end menu

@node Windows<8>,Tools/Demos<7>,,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id81}@anchor{1836}
@subsubsection Windows



@itemize -

@item 
gh-130727@footnote{https://github.com/python/cpython/issues/130727}: Fix a race in internal calls into WMI that can result in an
"invalid handle" exception under high load. Patch by Chris Eibl.

@item 
gh-76023@footnote{https://github.com/python/cpython/issues/76023}: Make @ref{262,,os.path.realpath()} ignore Windows error 1005 when in
non-strict mode.

@item 
gh-133779@footnote{https://github.com/python/cpython/issues/133779}: Reverts the change to generate different @code{pyconfig.h}
files based on compiler settings, as it was frequently causing extension
builds to break. In particular, the @code{Py_GIL_DISABLED} preprocessor
variable must now always be defined explicitly when compiling for the
experimental free-threaded runtime. The @ref{174,,sysconfig.get_config_var()}
function can be used to determine whether the current runtime was compiled
with that flag or not.

@item 
gh-133626@footnote{https://github.com/python/cpython/issues/133626}: Ensures packages are not accidentally bundled into the
traditional installer.
@end itemize

@node Tools/Demos<7>,テスト<5>,Windows<8>,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id82}@anchor{1837}
@subsubsection Tools/Demos



@itemize -

@item 
gh-134215@footnote{https://github.com/python/cpython/issues/134215}: @ref{491,,REPL} import autocomplete only suggests private modules
when explicitly specified.
@end itemize

@node テスト<5>,セキュリティ<9>,Tools/Demos<7>,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id83}@anchor{1838}
@subsubsection テスト



@itemize -

@item 
gh-133744@footnote{https://github.com/python/cpython/issues/133744}: Fix multiprocessing interrupt test. Add an event to synchronize
the parent process with the child process: wait until the child process
starts sleeping. Patch by Victor Stinner.

@item 
gh-133682@footnote{https://github.com/python/cpython/issues/133682}: Fixed test case
@code{test.test_annotationlib.TestStringFormat.test_displays} which ensures
proper handling of complex data structures (lists, sets, dictionaries, and
tuples) in string annotations.

@item 
gh-133639@footnote{https://github.com/python/cpython/issues/133639}: Fix @code{TestPyReplAutoindent.test_auto_indent_default()} doesn't
run @code{input_code}.
@end itemize

@node セキュリティ<9>,ライブラリ<23>,テスト<5>,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id84}@anchor{1839}
@subsubsection セキュリティ



@itemize -

@item 
gh-133767@footnote{https://github.com/python/cpython/issues/133767}: Fix use-after-free in the "unicode-escape" decoder with a
non-"strict" error handler.

@item 
gh-128840@footnote{https://github.com/python/cpython/issues/128840}: Short-circuit the processing of long IPv6 addresses early in
@ref{84,,ipaddress} to prevent excessive memory consumption and a minor
denial-of-service.
@end itemize

@node ライブラリ<23>,Core and Builtins<21>,セキュリティ<9>,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id85}@anchor{183a}
@subsubsection ライブラリ



@itemize -

@item 
gh-132710@footnote{https://github.com/python/cpython/issues/132710}: If possible, ensure that @ref{da0,,uuid.getnode()} returns the same
result even across different processes. Previously, the result was
constant only within the same process. Patch by Bénédikt Tran.

@item 
gh-80334@footnote{https://github.com/python/cpython/issues/80334}: @ref{183b,,multiprocessing.freeze_support()} now checks for work on
any "spawn" start method platform rather than only on Windows.

@item 
gh-134582@footnote{https://github.com/python/cpython/issues/134582}: Fix tokenize.untokenize() round-trip errors related to
t-strings braces escaping

@item 
gh-134546@footnote{https://github.com/python/cpython/issues/134546}: Ensure @ref{aa,,pdb} remote debugging script is readable by remote
Python process.

@item 
gh-134451@footnote{https://github.com/python/cpython/issues/134451}: Converted @code{asyncio.tools.CycleFoundException} from dataclass
to a regular exception type.

@item 
gh-114177@footnote{https://github.com/python/cpython/issues/114177}: Fix @ref{b,,asyncio} to not close subprocess pipes which would
otherwise error out when the event loop is already closed.

@item 
gh-90871@footnote{https://github.com/python/cpython/issues/90871}: Fixed an off by one error concerning the backlog parameter in
@ref{4ca,,create_unix_server()}. Contributed by Christian
Harries.

@item 
gh-134323@footnote{https://github.com/python/cpython/issues/134323}: Fix the @ref{183c,,threading.RLock.locked()} method.

@item 
gh-86802@footnote{https://github.com/python/cpython/issues/86802}: Fixed asyncio memory leak in cancelled shield tasks. For
shielded tasks where the shield was cancelled, log potential exceptions
through the exception handler. Contributed by Christian Harries.

@item 
gh-134209@footnote{https://github.com/python/cpython/issues/134209}: @ref{2f,,curses}: The @ref{183d,,curses.window.instr()} and
@ref{183e,,curses.window.getstr()} methods now allocate their internal buffer on
the heap instead of the stack; in addition, the max buffer size is
increased from 1023 to 2047.

@item 
gh-134235@footnote{https://github.com/python/cpython/issues/134235}: Updated tab completion on REPL to include builtin modules.
Contributed by Tom Wang, Hunter Young

@item 
gh-134152@footnote{https://github.com/python/cpython/issues/134152}: Fixed @ref{174f,,UnboundLocalError} that could occur during
@ref{3f,,email} header parsing if an expected trailing delimiter is missing
in some contexts.

@item 
gh-134168@footnote{https://github.com/python/cpython/issues/134168}: @ref{76,,http.server}: Fix IPv6 address binding and
@ref{183f,,--directory} handling when using HTTPS.

@item 
gh-62184@footnote{https://github.com/python/cpython/issues/62184}: Remove import of C implementation of @ref{1527,,io.FileIO} from
Python implementation which has its own implementation

@item 
gh-133982@footnote{https://github.com/python/cpython/issues/133982}: Emit @ref{4d7,,RuntimeWarning} in the Python implementation of
@ref{83,,io} when the @ref{13db,,file-like object} is not closed
explicitly in the presence of multiple I/O layers.

@item 
gh-133890@footnote{https://github.com/python/cpython/issues/133890}: The @ref{e4,,tarfile} module now handles @ref{887,,UnicodeEncodeError}
in the same way as @ref{2c0,,OSError} when cannot extract a member.

@item 
gh-134097@footnote{https://github.com/python/cpython/issues/134097}: Fix interaction of the new @ref{491,,REPL} and @ref{16f,,-X showrefcount} command line option.

@item 
gh-133889@footnote{https://github.com/python/cpython/issues/133889}: The generated directory listing page in
@ref{d38,,http.server.SimpleHTTPRequestHandler} now only shows the decoded
path component of the requested URL, and not the query and fragment.

@item 
gh-134098@footnote{https://github.com/python/cpython/issues/134098}: Fix handling paths that end with a percent-encoded slash
(@code{%2f} or @code{%2F}) in @ref{d38,,http.server.SimpleHTTPRequestHandler}.

@item 
gh-132124@footnote{https://github.com/python/cpython/issues/132124}: On POSIX-compliant systems,
@code{multiprocessing.util.get_temp_dir()} now ignores 
@geindex TMPDIR
@geindex 環境変数; TMPDIR
@code{TMPDIR}
(and similar environment variables) if the path length of @code{AF_UNIX}
socket files exceeds the platform-specific maximum length when using the
@ref{1d4,,forkserver} start method.
Patch by Bénédikt Tran.

@item 
gh-134062@footnote{https://github.com/python/cpython/issues/134062}: @ref{84,,ipaddress}: fix collisions in @ref{cf3,,__hash__()}
for @ref{50e,,IPv4Network} and @ref{50f,,IPv6Network}
objects.

@item 
gh-133970@footnote{https://github.com/python/cpython/issues/133970}: Make @code{string.templatelib.Template} and
@code{string.templatelib.Interpolation} generic.

@item 
gh-71253@footnote{https://github.com/python/cpython/issues/71253}: Raise @ref{2ec,,ValueError} in @ref{316,,open()} if `opener' returns a
negative file-descriptor in the Python implementation of @ref{83,,io} to
match the C implementation.

@item 
gh-133960@footnote{https://github.com/python/cpython/issues/133960}: Simplify and improve @ref{1815,,typing.evaluate_forward_ref()}. It
now no longer raises errors on certain invalid types. In several
situations, it is now able to evaluate forward references that were
previously unsupported.

@item 
gh-133925@footnote{https://github.com/python/cpython/issues/133925}: Make the private class @code{typing._UnionGenericAlias} hashable.

@item 
gh-133653@footnote{https://github.com/python/cpython/issues/133653}: Fix @ref{1bd,,argparse.ArgumentParser} with the `formatter_class'
argument. Fix TypeError when `formatter_class' is a custom subclass of
@code{HelpFormatter}. Fix TypeError when `formatter_class' is not a
subclass of @code{HelpFormatter} and non-standard `prefix_char' is
used. Fix support of colorizing when `formatter_class' is not a subclass
of @code{HelpFormatter}.

@item 
gh-132641@footnote{https://github.com/python/cpython/issues/132641}: Fixed a race in @ref{be2,,functools.lru_cache()} under
free-threading.

@item 
gh-133783@footnote{https://github.com/python/cpython/issues/133783}: Fix bug with applying @ref{1c0,,copy.replace()} to @ref{9,,ast}
objects. Attributes that default to @code{None} were incorrectly treated as
required for manually created AST nodes.

@item 
gh-133684@footnote{https://github.com/python/cpython/issues/133684}: Fix bug where @ref{459,,annotationlib.get_annotations()} would
return the wrong result for certain classes that are part of a class
hierarchy where @code{from __future__ import annotations} is used.

@item 
gh-77057@footnote{https://github.com/python/cpython/issues/77057}: Fix handling of invalid markup declarations in
@ref{a77,,html.parser.HTMLParser}.

@item 
gh-130328@footnote{https://github.com/python/cpython/issues/130328}: Speedup pasting in @code{PyREPL} on Windows in a legacy console.
Patch by Chris Eibl.

@item 
gh-133701@footnote{https://github.com/python/cpython/issues/133701}: Fix bug where @ref{332,,typing.TypedDict} classes defined under
@code{from __future__ import annotations} and inheriting from another
@code{TypedDict} had an incorrect @code{__annotations__} attribute.

@item 
gh-133581@footnote{https://github.com/python/cpython/issues/133581}: Improve unparsing of t-strings in @ref{ae2,,ast.unparse()} and
@code{from __future__ import annotations}. Empty t-strings now round-trip
correctly and formatting in interpolations is preserved. Patch by Jelle
Zijlstra.

@item 
gh-133551@footnote{https://github.com/python/cpython/issues/133551}: Support t-strings (
@geindex Python Enhancement Proposals; PEP 750
PEP 750@footnote{https://peps.python.org/pep-0750/}) in @ref{6,,annotationlib}. Patch
by Jelle Zijlstra.

@item 
gh-133439@footnote{https://github.com/python/cpython/issues/133439}: Fix dot commands with trailing spaces are mistaken for
multi-line SQL statements in the sqlite3 command-line interface.

@item 
gh-132493@footnote{https://github.com/python/cpython/issues/132493}: Avoid accessing @code{__annotations__} unnecessarily in
@ref{22f,,inspect.signature()}.

@item 
gh-132876@footnote{https://github.com/python/cpython/issues/132876}: @code{ldexp()} on Windows doesn't round subnormal results before
Windows 11, but should.  Python's @ref{1840,,math.ldexp()} wrapper now does
round them, so results may change slightly, in rare cases of very small
results, on Windows versions before 11.

@item 
gh-133009@footnote{https://github.com/python/cpython/issues/133009}: @ref{12b,,xml.etree.ElementTree}: Fix a crash in
@ref{17e1,,Element.__deepcopy__} when the element is
concurrently mutated. Patch by Bénédikt Tran.

@item 
gh-91555@footnote{https://github.com/python/cpython/issues/91555}: Ignore log messages generated during handling of log messages,
to avoid deadlock or infinite recursion. [NOTE: This change has since been
reverted.]

@item 
gh-125028@footnote{https://github.com/python/cpython/issues/125028}: @ref{216,,functools.Placeholder} cannot be passed to
@ref{217,,functools.partial()} as a keyword argument.

@item 
gh-62824@footnote{https://github.com/python/cpython/issues/62824}: Fix aliases for @code{iso8859_8} encoding. Patch by Dave Goncalves.

@item 
gh-86155@footnote{https://github.com/python/cpython/issues/86155}: @ref{1841,,html.parser.HTMLParser.close()} no longer loses data when
the @code{<script>} tag is not closed. Patch by Waylan Limberg.

@item 
gh-69426@footnote{https://github.com/python/cpython/issues/69426}: Fix @ref{a77,,html.parser.HTMLParser} to not unescape character
entities in attribute values if they are followed by an ASCII alphanumeric
or an equals sign.

@item 
bpo-28494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28494}: Improve Zip file validation false positive rate in
@ref{1542,,zipfile.is_zipfile()}.

@item 
gh-134381@footnote{https://github.com/python/cpython/issues/134381}: Fix @ref{244,,RuntimeError} when using a not-started
@ref{176,,threading.Thread} after calling @ref{4b5,,os.fork()}
@end itemize

@node Core and Builtins<21>,C API<7>,ライブラリ<23>,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id86}@anchor{1842}
@subsubsection Core and Builtins



@itemize -

@item 
gh-127960@footnote{https://github.com/python/cpython/issues/127960}: PyREPL interactive shell no longer starts with @code{__package__}
and @code{__file__} global names set to @code{_pyrepl} package internals.
Contributed by Yuichiro Tachibana.

@item 
gh-130397@footnote{https://github.com/python/cpython/issues/130397}: Remove special-casing for C stack depth limits for WASI. Due to
WebAssembly's built-in stack protection this does not pose a security
concern.

@item 
gh-128066@footnote{https://github.com/python/cpython/issues/128066}: Fixes an edge case where PyREPL improperly threw an error when
Python is invoked on a read only filesystem while trying to write history
file entries.

@item 
gh-69605@footnote{https://github.com/python/cpython/issues/69605}: When auto-completing an import in the @ref{491,,REPL}, finding no
candidates now issues no suggestion, rather than suggestions from the
current namespace.

@item 
gh-134158@footnote{https://github.com/python/cpython/issues/134158}: Fix coloring of double braces in f-strings and t-strings in the
@ref{491,,REPL}.

@item 
gh-134119@footnote{https://github.com/python/cpython/issues/134119}: Fix crash when calling @ref{9d8,,next()} on an exhausted template
string iterator. Patch by Jelle Zijlstra.

@item 
gh-134100@footnote{https://github.com/python/cpython/issues/134100}: Fix a use-after-free bug that occurs when an imported module
isn't in @ref{17e6,,sys.modules} after its initial import. Patch by
Nico-Posada.

@item 
gh-133999@footnote{https://github.com/python/cpython/issues/133999}: Fix @ref{18e,,SyntaxError} regression in @ref{1ab,,except} parsing
after gh-123440@footnote{https://github.com/python/cpython/issues/123440}.

@item 
gh-133886@footnote{https://github.com/python/cpython/issues/133886}: Fix @ref{16d,,sys.remote_exec()} for non-ASCII paths in non-UTF-8
locales and non-UTF-8 paths in UTF-8 locales.

@item 
gh-133703@footnote{https://github.com/python/cpython/issues/133703}: Fix hashtable in dict can be bigger than intended in some
situations.

@item 
gh-133778@footnote{https://github.com/python/cpython/issues/133778}: Fix bug where assigning to the @ref{1843,,__annotations__}
attributes of classes defined under @code{from __future__ import annotations}
had no effect.

@item 
gh-132762@footnote{https://github.com/python/cpython/issues/132762}: @ref{24e,,fromkeys()} no longer loops forever when adding a
small set of keys to a large base dict. Patch by Angela Liss.

@item 
gh-133541@footnote{https://github.com/python/cpython/issues/133541}: Inconsistent indentation in user input crashed the new REPL
when syntax highlighting was active. This is now fixed.

@item 
gh-133516@footnote{https://github.com/python/cpython/issues/133516}: Raise @ref{2ec,,ValueError} when constants @code{True}, @code{False} or
@code{None} are used as an identifier after NFKC normalization.

@item 
gh-132542@footnote{https://github.com/python/cpython/issues/132542}: Update @ref{c33,,Thread.native_id}
after @code{fork(2)@footnote{https://manpages.debian.org/fork(2)}} to ensure accuracy. Patch by Noam Cohen.
@end itemize

@node C API<7>,ビルド<7>,Core and Builtins<21>,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id87}@anchor{1844}
@subsubsection C API



@itemize -

@item 
gh-134144@footnote{https://github.com/python/cpython/issues/134144}: Fix crash when calling @ref{1845,,Py_EndInterpreter()} with a
@ref{1846,,thread state} that isn't the initial thread for the interpreter.
@end itemize

@node ビルド<7>,,C API<7>,Python 3 14 0 beta 2
@anchor{whatsnew/changelog id88}@anchor{1847}
@subsubsection ビルド



@itemize -

@item 
gh-134455@footnote{https://github.com/python/cpython/issues/134455}: Fixed @code{build-details.json} generation to use the correct
@code{c_api.headers} as defined in 
@geindex Python Enhancement Proposals; PEP 739
PEP 739@footnote{https://peps.python.org/pep-0739/}, instead of @code{c_api.include}.

@item 
gh-131769@footnote{https://github.com/python/cpython/issues/131769}: Fix detecting when the build Python in a cross-build is a
pydebug build.

@item 
gh-117088@footnote{https://github.com/python/cpython/issues/117088}: AIX linker don't support -h option, so avoid it through
platform check
@end itemize

@node Python 3 14 0 beta 1,Python 3 14 0 alpha 7,Python 3 14 0 beta 2,変更履歴
@anchor{whatsnew/changelog python-3-14-0-beta-1}@anchor{1848}
@subsection Python 3.14.0 beta 1


`Release date: 2025-05-06'

@menu
* Windows: Windows<9>. 
* Tools/Demos: Tools/Demos<8>. 
* テスト: テスト<6>. 
* セキュリティ: セキュリティ<10>. 
* ライブラリ: ライブラリ<24>. 
* IDLE: IDLE<5>. 
* ドキュメント: ドキュメント<8>. 
* Core and Builtins: Core and Builtins<22>. 
* ライブラリ: ライブラリ<25>. 
* Core and Builtins: Core and Builtins<23>. 
* ライブラリ: ライブラリ<26>. 
* Core and Builtins: Core and Builtins<24>. 
* ライブラリ: ライブラリ<27>. 
* C API: C API<8>. 
* ビルド: ビルド<8>. 

@end menu

@node Windows<9>,Tools/Demos<8>,,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id89}@anchor{1849}
@subsubsection Windows



@itemize -

@item 
gh-132930@footnote{https://github.com/python/cpython/issues/132930}: Marks the installer for Windows as deprecated and updates
documentation to cover the new Python install manager.

@item 
gh-127405@footnote{https://github.com/python/cpython/issues/127405}: Add @code{ABIFLAGS} to @ref{298,,sysconfig.get_config_vars()} on
Windows. Patch by Xuehai Pan.
@end itemize

@node Tools/Demos<8>,テスト<6>,Windows<9>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id90}@anchor{184a}
@subsubsection Tools/Demos



@itemize -

@item 
gh-130453@footnote{https://github.com/python/cpython/issues/130453}: Allow passing multiple keyword arguments with the same function
name in @code{pygettext}.

@item 
gh-130195@footnote{https://github.com/python/cpython/issues/130195}: Add warning messages when @code{pygettext} unimplemented
@code{-a/--extract-all} option is called.
@end itemize

@node テスト<6>,セキュリティ<10>,Tools/Demos<8>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id91}@anchor{184b}
@subsubsection テスト



@itemize -

@item 
gh-133131@footnote{https://github.com/python/cpython/issues/133131}: The iOS testbed will now select the most recently released
"SE-class" device for testing if a device isn't explicitly specified.

@item 
gh-91048@footnote{https://github.com/python/cpython/issues/91048}: Add ability to externally inspect all pending asyncio tasks,
even if no task is currently entered on the event loop.

@item 
gh-109981@footnote{https://github.com/python/cpython/issues/109981}: The test helper that counts the list of open file descriptors
now uses the optimised @code{/dev/fd} approach on all Apple platforms, not
just macOS. This avoids crashes caused by guarded file descriptors.

@item 
gh-132678@footnote{https://github.com/python/cpython/issues/132678}: Add @code{--prioritize} to @code{-m test}. This option allows the
user to specify which selected tests should execute first, even if the
order is otherwise randomized. This is particularly useful for tests that
run the longest.

@item 
gh-131290@footnote{https://github.com/python/cpython/issues/131290}: Tests in @code{Lib/test} can now be correctly executed as
standalone scripts.
@end itemize

@node セキュリティ<10>,ライブラリ<24>,テスト<6>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id92}@anchor{184c}
@subsubsection セキュリティ



@itemize -

@item 
gh-115322@footnote{https://github.com/python/cpython/issues/115322}: The underlying extension modules behind @ref{bf,,readline}:,
@ref{dc,,subprocess}, and @ref{2e,,ctypes} now raise audit events on previously
uncovered code paths that could lead to file system access related to C
function calling and external binary execution.  The
@code{ctypes.call_function} audit hook has also been fixed to use an unsigned
value for its @code{function pointer}.
@end itemize

@node ライブラリ<24>,IDLE<5>,セキュリティ<10>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id93}@anchor{184d}
@subsubsection ライブラリ



@itemize -

@item 
gh-133490@footnote{https://github.com/python/cpython/issues/133490}: Add color support to PDB in remote mode.

@item 
gh-132493@footnote{https://github.com/python/cpython/issues/132493}: Avoid eagerly evaluating annotations in functions decorated
with @ref{140c,,reprlib.recursive_repr()}.

@item 
gh-130645@footnote{https://github.com/python/cpython/issues/130645}: Add color to stdlib argparse CLIs. Patch by Hugo van Kemenade.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: Make @ref{459,,annotationlib.get_annotations()} succeed with the
@code{FORWARDREF} format if evaluating the annotations throws an exception
other than @ref{452,,NameError} or @ref{5f0,,AttributeError}.

@item 
gh-133351@footnote{https://github.com/python/cpython/issues/133351}: Fix remote PDB to correctly request tab completions for Python
expressions from the server when completing a continuation line of a
multi-line Python block.

@item 
gh-133367@footnote{https://github.com/python/cpython/issues/133367}: Add the @code{--feature-version}, @code{--optimize}, and
@code{--show-empty} options to the @ref{9,,ast} command-line interface. Patch
by Semyon Moroz.

@item 
gh-133363@footnote{https://github.com/python/cpython/issues/133363}: The @ref{184e,,cmd.Cmd} class has been fixed to reliably call the
@code{completedefault} method whenever the @code{do_shell} method is not defined
and tab completion is requested for a line beginning with @code{!}.

@item 
gh-113081@footnote{https://github.com/python/cpython/issues/113081}: Highlight syntax on source code in @ref{aa,,pdb}.

@item 
gh-133349@footnote{https://github.com/python/cpython/issues/133349}: Introduced auto-indent in @ref{aa,,pdb} multi-line input.

@item 
gh-133306@footnote{https://github.com/python/cpython/issues/133306}: Use @code{\z} instead of @code{\Z} in @ref{184f,,fnmatch.translate()} and
@ref{4fb,,glob.translate()}.

@item 
gh-133306@footnote{https://github.com/python/cpython/issues/133306}: Support @code{\z} as a synonym for @code{\Z} in @ref{be,,regular expressions}.

@item 
gh-133300@footnote{https://github.com/python/cpython/issues/133300}: Make @ref{1bd,,argparse.ArgumentParser}'s @code{suggest_on_error} a
keyword-only parameter. Patch by Hugo van Kemenade.

@item 
gh-133290@footnote{https://github.com/python/cpython/issues/133290}: Fix attribute caching issue when setting
@ref{1850,,ctypes._Pointer._type_} in the undocumented and deprecated
@code{ctypes.SetPointerType()} function and the undocumented
@code{set_type()} method.

@item 
gh-133223@footnote{https://github.com/python/cpython/issues/133223}: When PDB is attached to a remote process, do a better job of
intercepting Ctrl+C and forwarding it to the remote process.

@item 
gh-133153@footnote{https://github.com/python/cpython/issues/133153}: Do not complete @ref{aa,,pdb} commands in @code{interact} mode of
@ref{aa,,pdb}.

@item 
gh-133139@footnote{https://github.com/python/cpython/issues/133139}: Add the @ref{1f6,,curses.assume_default_colors()} function, a
refinement of the @ref{1f7,,curses.use_default_colors()} function which allows
to change the color pair @code{0}.

@item 
gh-133089@footnote{https://github.com/python/cpython/issues/133089}: Use original timeout value for @ref{17ab,,subprocess.TimeoutExpired}
when the func @ref{d7f,,subprocess.run()} is called with a timeout instead of
sometimes a confusing partial remaining time out value used internally on
the final @code{wait()}.

@item 
gh-133036@footnote{https://github.com/python/cpython/issues/133036}: @ref{315,,codecs.open()} is now deprecated. Use @ref{316,,open()}
instead. Contributed by Inada Naoki.

@item 
gh-132987@footnote{https://github.com/python/cpython/issues/132987}: Many builtin and extension functions which accept an unsigned
integer argument, now use @ref{19e,,__index__()} if available.

@item 
gh-124703@footnote{https://github.com/python/cpython/issues/124703}: Set return code to @code{1} when aborting process from @ref{aa,,pdb}.

@item 
gh-133005@footnote{https://github.com/python/cpython/issues/133005}: Support passing @code{preset} option to @ref{1077,,tarfile.open()} when
using @code{'w|xz'} mode.

@item 
gh-115032@footnote{https://github.com/python/cpython/issues/115032}: Support for custom logging handlers with the `strm' argument is
deprecated and scheduled for removal in Python 3.16. Define handlers with
the `stream' argument instead. Patch by Mariusz Felisiak.

@item 
gh-132991@footnote{https://github.com/python/cpython/issues/132991}: Add @code{socket.IP_FREEBIND} constant on Linux 2.4 and
later.

@item 
gh-132995@footnote{https://github.com/python/cpython/issues/132995}: Bump the version of pip bundled in ensurepip to version 25.1.1

@item 
gh-132933@footnote{https://github.com/python/cpython/issues/132933}: The zipapp module now applies the filter when creating the list
of files to add, rather than waiting until the file is being added to the
archive.

@item 
gh-121249@footnote{https://github.com/python/cpython/issues/121249}: Always support the float complex and double complex C types in the @ref{db,,struct} module.  Patch by Sergey B
Kirpichev.

@item 
gh-132915@footnote{https://github.com/python/cpython/issues/132915}: @ref{1851,,fcntl.fcntl()} and @ref{1694,,fcntl.ioctl()} can now detect a
buffer overflow and raise @ref{795,,SystemError}. The stack and memory can be
corrupted in such case, so treat this error as fatal.

@item 
gh-132017@footnote{https://github.com/python/cpython/issues/132017}: Fix error when @code{pyrepl} is suspended, then resumed and
terminated.

@item 
gh-132893@footnote{https://github.com/python/cpython/issues/132893}: Improved @ref{1852,,statistics.NormalDist.cdf()} accuracy for inputs
smaller than the mean.

@item 
gh-130328@footnote{https://github.com/python/cpython/issues/130328}: Speedup pasting in @code{PyREPL} on Windows. Fix by Chris Eibl.

@item 
gh-132882@footnote{https://github.com/python/cpython/issues/132882}: Fix copying of @ref{2a8,,typing.Union} objects containing objects
that do not support the @code{|} operator.

@item 
gh-93696@footnote{https://github.com/python/cpython/issues/93696}: Fixed the breakpoint display error for frozen modules in
@ref{aa,,pdb}.

@item 
gh-129965@footnote{https://github.com/python/cpython/issues/129965}: Add MIME types for @code{.7z}, @code{.apk}, @code{.deb}, @code{.glb},
@code{.gltf}, @code{.gz}, @code{.m4v}, @code{.php}, @code{.rar}, @code{.rpm}, @code{.stl} and
@code{.wmv}. Patch by Hugo van Kemenade.

@item 
gh-132742@footnote{https://github.com/python/cpython/issues/132742}: @ref{1851,,fcntl.fcntl()} now supports arbitrary @ref{193,,bytes-like objects}, not only @ref{192,,bytes}. @ref{1694,,fcntl.ioctl()}
now automatically retries system calls failing with EINTR and releases the
GIL during a system call even for large bytes-like object.

@item 
gh-132451@footnote{https://github.com/python/cpython/issues/132451}: The CLI for the PDB debugger now accepts a @code{-p PID} argument
to allow attaching to a running process. The process must be running the
same version of Python as the one running PDB.

@item 
gh-125618@footnote{https://github.com/python/cpython/issues/125618}: Add a `format' parameter to
@ref{17b2,,annotationlib.ForwardRef.evaluate()}. Evaluating annotations in the
@code{FORWARDREF} format now succeeds in more cases that would previously
have raised an exception.

@item 
gh-132805@footnote{https://github.com/python/cpython/issues/132805}: Fix incorrect handling of nested non-constant values in the
FORWARDREF format in @ref{6,,annotationlib}.

@item 
gh-132734@footnote{https://github.com/python/cpython/issues/132734}: Add new constants for Bluetooth @ref{d1,,sockets}.

@item 
gh-132673@footnote{https://github.com/python/cpython/issues/132673}: Fix @ref{8b8,,AssertionError} raised on @ref{1e5,,ctypes.Structure}
with @code{_align_ = 0} and @code{_fields_ = []}.

@item 
gh-132578@footnote{https://github.com/python/cpython/issues/132578}: Rename the @code{threading.Thread._handle} field to avoid
shadowing methods defined on subclasses of @code{threading.Thread}.

@item 
gh-132561@footnote{https://github.com/python/cpython/issues/132561}: Fix the public @code{locked} method of @code{multiprocessing.SemLock}
class. Also adding 2 tests for the derivated @ref{1853,,multiprocessing.Lock}
and @ref{1854,,multiprocessing.RLock} classes.

@item 
gh-121468@footnote{https://github.com/python/cpython/issues/121468}: Add @ref{279,,pdb.set_trace_async()} function to support
@ref{18d,,await} statements in @ref{aa,,pdb}.

@item 
gh-132493@footnote{https://github.com/python/cpython/issues/132493}: @ref{56b,,typing.Protocol} now uses
@ref{459,,annotationlib.get_annotations()} when checking whether or not an
instance implements the protocol with @ref{2ad,,isinstance()}. This enables
support for @code{isinstance} checks against classes with deferred
annotations.

@item 
gh-132536@footnote{https://github.com/python/cpython/issues/132536}: Do not disable @ref{1855,,PY_THROW} event in @ref{10,,bdb}
because it can't be disabled.

@item 
gh-132527@footnote{https://github.com/python/cpython/issues/132527}: Include the valid typecode 'w' in the error message when an
invalid typecode is passed to @ref{4be,,array.array}.

@item 
gh-132099@footnote{https://github.com/python/cpython/issues/132099}: The Bluetooth socket with the @ref{281,,BTPROTO_HCI}
protocol on Linux now accepts an address in the format of an integer
@code{device_id}, not only a tuple  @code{(device_id,)}.

@item 
gh-81793@footnote{https://github.com/python/cpython/issues/81793}: Fix @ref{1307,,os.link()} on platforms (like Linux) where the system
@code{link()} function does not follow symlinks. On Linux, it now
follows symlinks by default or if @code{follow_symlinks=True} is specified.
On Windows, it now raises an error if @code{follow_symlinks=True} is passed.
On macOS, it now raises an error if @code{follow_symlinks=False} is passed
and the system @code{linkat()} function is not available at runtime.

@item 
gh-132493@footnote{https://github.com/python/cpython/issues/132493}: Support creation of @ref{56b,,typing.Protocol} classes with
annotations that cannot be resolved at class creation time.

@item 
gh-132491@footnote{https://github.com/python/cpython/issues/132491}: Rename @code{annotationlib.value_to_string} to
@ref{1856,,annotationlib.type_repr()} and provide better handling for function
objects.

@item 
gh-132426@footnote{https://github.com/python/cpython/issues/132426}: Add @ref{45b,,annotationlib.get_annotate_from_class_namespace()} as
a helper for accessing annotations in metaclasses, and remove
@code{annotationlib.get_annotate_function}.

@item 
gh-70145@footnote{https://github.com/python/cpython/issues/70145}: Add support for channels in Bluetooth HCI protocol
(@ref{281,,BTPROTO_HCI}).

@item 
gh-131913@footnote{https://github.com/python/cpython/issues/131913}: Add a shortcut function
@ref{251,,multiprocessing.Process.interrupt()} alongside the existing
@ref{1857,,multiprocessing.Process.terminate()} and
@ref{d4f,,multiprocessing.Process.kill()} for an improved control over child
process termination.

@item 
gh-132439@footnote{https://github.com/python/cpython/issues/132439}: Fix @code{PyREPL} on Windows: characters entered via AltGr are
swallowed. Patch by Chris Eibl.

@item 
gh-132429@footnote{https://github.com/python/cpython/issues/132429}: Fix support of Bluetooth sockets on NetBSD and DragonFly BSD.
Add support for `cid' and `bdaddr_type' in the BTPROTO_L2CAP address on
FreeBSD. Return `cid' in @code{getsockname()} for BTPROTO_L2CAP if it is not
zero.

@item 
gh-132106@footnote{https://github.com/python/cpython/issues/132106}: @ref{243,,QueueListener.start} now raises a @ref{244,,RuntimeError}
if the listener is already started.

@item 
gh-132417@footnote{https://github.com/python/cpython/issues/132417}: Fix a @code{NULL} pointer dereference when a C function called
using @ref{2e,,ctypes} with @code{restype} @ref{1f3,,py_object} returns
@code{NULL}.

@item 
gh-132385@footnote{https://github.com/python/cpython/issues/132385}: Fix instance error suggestions trigger potential exceptions in
@ref{6fa,,object.__getattr__()} in @ref{104,,traceback}.

@item 
gh-125866@footnote{https://github.com/python/cpython/issues/125866}: Add optional `add_scheme' argument to
@ref{2bf,,urllib.request.pathname2url()}; when set to true, a complete URL is
returned. Likewise add optional `require_scheme' argument to
@ref{2bd,,url2pathname()}; when set to true, a complete URL is
accepted.

@item 
gh-132308@footnote{https://github.com/python/cpython/issues/132308}: A @ref{563,,traceback.TracebackException} now correctly renders
the @code{__context__} and @code{__cause__} attributes from @ref{1858,,falsey} @ref{bcd,,Exception}, and the @code{exceptions} attribute from falsey
@ref{4d2,,ExceptionGroup}.

@item 
gh-130645@footnote{https://github.com/python/cpython/issues/130645}: Add colour to @ref{7,,argparse} help output. Patch by Hugo van
Kemenade.

@item 
gh-127495@footnote{https://github.com/python/cpython/issues/127495}: In PyREPL, append a new entry to the @code{PYTHON_HISTORY} file
`after' every statement.  This should preserve command-line history after
interpreter is terminated.  Patch by Sergey B Kirpichev.

@item 
gh-129463@footnote{https://github.com/python/cpython/issues/129463}: Comparison of @ref{1776,,annotationlib.ForwardRef} objects no
longer uses the internal @code{__code__} and @code{__ast_node__} attributes,
which are used as caches.

@item 
gh-132250@footnote{https://github.com/python/cpython/issues/132250}: Fixed the @ref{795,,SystemError} in @ref{2b,,cProfile} when locating
the actual C function of a method raises an exception.

@item 
gh-132064@footnote{https://github.com/python/cpython/issues/132064}: @ref{459,,annotationlib.get_annotations()} now uses the
@code{__annotate__} attribute if it is present, even if @code{__annotations__}
is not present. Additionally, the function now raises a
@ref{198,,TypeError} if it is passed an object that does not have any
annotatins.

@item 
gh-130664@footnote{https://github.com/python/cpython/issues/130664}: Support the @code{'_'} digit separator in formatting of the
integral part of @ref{1fe,,Decimal}'s.  Patch by Sergey B
Kirpichev.

@item 
gh-131952@footnote{https://github.com/python/cpython/issues/131952}: Add color output to the @code{json} CLI. Patch by Tomas
Roun.

@item 
gh-132063@footnote{https://github.com/python/cpython/issues/132063}: Prevent exceptions that evaluate as falsey (namely, when their
@code{__bool__} method returns @code{False} or their @code{__len__} method returns
0) from being ignored by @ref{1d6,,concurrent.futures.ProcessPoolExecutor}
and @ref{949,,concurrent.futures.ThreadPoolExecutor}.

@item 
gh-132106@footnote{https://github.com/python/cpython/issues/132106}: @ref{242,,logging.handlers.QueueListener} now implements the
context manager protocol, allowing it to be used in a @ref{186,,with}
statement.

@item 
gh-132054@footnote{https://github.com/python/cpython/issues/132054}: The @code{application/yaml} mime type (
@geindex RFC; RFC 9512
RFC 9512@footnote{https://datatracker.ietf.org/doc/html/rfc9512.html}) is now
supported by @ref{93,,mimetypes}. Patch by Sasha "Nelie" Chernykh and Hugo
van Kemenade.

@item 
gh-119605@footnote{https://github.com/python/cpython/issues/119605}: Respect @code{follow_wrapped} for @code{__init__()} and
@code{__new__()} methods when getting the class signature for a class with
@ref{22f,,inspect.signature()}. Preserve class signature after wrapping with
@ref{489,,warnings.deprecated()}. Patch by Xuehai Pan.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import times by up to 33x for the @ref{c9,,shlex} module,
and improve the performance of @ref{582,,shlex.quote()} by up to 12x. Patch by
Adam Turner.

@item 
gh-85302@footnote{https://github.com/python/cpython/issues/85302}: Add support for @ref{282,,BTPROTO_SCO} in sockets on
FreeBSD.

@item 
gh-131757@footnote{https://github.com/python/cpython/issues/131757}: Make @ref{be2,,functools.lru_cache()} call the cached function
unlocked to allow concurrency.

@item 
gh-131423@footnote{https://github.com/python/cpython/issues/131423}: @ref{d5,,ssl} can show descriptions for errors added in OpenSSL
3.4.1. Patch by Bénédikt Tran.

@item 
gh-131434@footnote{https://github.com/python/cpython/issues/131434}: Improve error reporting for incorrect format in
@ref{1646,,time.strptime()}.

@item 
gh-131524@footnote{https://github.com/python/cpython/issues/131524}: Add help message to @ref{af,,platform} command-line interface.
Contributed by Harry Lees.

@item 
gh-100926@footnote{https://github.com/python/cpython/issues/100926}: Move @ref{1f1,,ctypes.POINTER()} types cache from a global internal
cache (@code{_pointer_type_cache}) to the
@ref{1f2,,ctypes._CData.__pointer_type__} attribute of the corresponding
@ref{2e,,ctypes} types. This will stop the cache from growing without limits
in some situations.

@item 
gh-85702@footnote{https://github.com/python/cpython/issues/85702}: If @code{zoneinfo._common.load_tzdata} is given a package without a
resource a @code{ZoneInfoNotFoundError} is raised rather than a
@ref{1264,,IsADirectoryError}.

@item 
gh-123471@footnote{https://github.com/python/cpython/issues/123471}: Make concurrent iterations over @ref{1859,,itertools.repeat} safe
under free-threading.

@item 
gh-131127@footnote{https://github.com/python/cpython/issues/131127}: Systems using LibreSSL now successfully build.

@item 
gh-89157@footnote{https://github.com/python/cpython/issues/89157}: Make the pure Python implementation of
@ref{828,,datetime.date.fromisoformat()}, only accept ASCII strings for
consistency with the C implementation.

@item 
gh-130941@footnote{https://github.com/python/cpython/issues/130941}: Fix @ref{4de,,configparser.ConfigParser} parsing empty
interpolation with @code{allow_no_value} set to @code{True}.

@item 
gh-110067@footnote{https://github.com/python/cpython/issues/110067}: Make @ref{6d,,heapq} max-heap functions @ref{221,,heapq.heapify_max()},
@ref{222,,heapq.heappush_max()}, @ref{223,,heapq.heappop_max()}, and
@ref{224,,heapq.heapreplace_max()} public. Previous underscored naming is kept
for backwards compatibility. Additionally, the missing function
@ref{225,,heapq.heappushpop_max()} has been added to both the C and Python
implementations.

@item 
gh-129098@footnote{https://github.com/python/cpython/issues/129098}: Fix REPL traceback reporting when using @ref{4b1,,compile()} with an
inexisting file. Patch by Bénédikt Tran.

@item 
gh-130631@footnote{https://github.com/python/cpython/issues/130631}: @code{http.cookiejar.join_header_words()} is now more similar
to the original Perl version. It now quotes the same set of characters and
always quote values that end with @code{"\n"}.

@item 
gh-130482@footnote{https://github.com/python/cpython/issues/130482}: Add ability to specify name for @code{tkinter.OptionMenu}
and @code{tkinter.ttk.OptionMenu}.

@item 
gh-77065@footnote{https://github.com/python/cpython/issues/77065}: Add keyword-only optional argument `echo_char' for
@ref{21d,,getpass.getpass()} for optional visual keyboard feedback support.
Patch by Semyon Moroz.

@item 
gh-130317@footnote{https://github.com/python/cpython/issues/130317}: Fix @ref{969,,PyFloat_Pack2()} and @ref{96c,,PyFloat_Unpack2()} for
NaN's with payload.  This corrects round-trip for @ref{185a,,struct.unpack()}
and @ref{148e,,struct.pack()} in case of the IEEE 754 binary16 "half precision"
type. Patch by Sergey B Kirpichev.

@item 
gh-130402@footnote{https://github.com/python/cpython/issues/130402}: Joining running daemon threads during interpreter shutdown now
raises @ref{47a,,PythonFinalizationError}.

@item 
gh-130167@footnote{https://github.com/python/cpython/issues/130167}: Improve speed of @ref{2d7,,difflib.IS_LINE_JUNK()}. Patch by Semyon
Moroz.

@item 
gh-101410@footnote{https://github.com/python/cpython/issues/101410}: Added more detailed messages for domain errors in the
@ref{92,,math} module.

@item 
gh-128384@footnote{https://github.com/python/cpython/issues/128384}: Make @ref{179,,warnings.catch_warnings} use a context variable
for holding the warning filtering state if the
@ref{18a,,sys.flags.context_aware_warnings} flag is set to true.  This makes
using the context manager thread-safe in multi-threaded programs.  The
flag is true by default in free-threaded builds and is otherwise false.
The value of the flag can be overridden by the the @ref{16f,,-X context_aware_warnings} command-line option or by the
@geindex PYTHON_CONTEXT_AWARE_WARNINGS
@geindex 環境変数; PYTHON_CONTEXT_AWARE_WARNINGS
@ref{185b,,PYTHON_CONTEXT_AWARE_WARNINGS} environment variable.

@item 
gh-129719@footnote{https://github.com/python/cpython/issues/129719}: Fix missing @code{socket.CAN_RAW_ERR_FILTER} constant in the
socket module on Linux systems. It was missing since Python 3.11.

@item 
gh-129027@footnote{https://github.com/python/cpython/issues/129027}: Raise @ref{1a3,,DeprecationWarning} for
@ref{292,,sys._clear_type_cache()}. This function was deprecated in Python 3.13
but it didn't raise a runtime warning.

@item 
gh-128307@footnote{https://github.com/python/cpython/issues/128307}: Add @code{eager_start} keyword argument to
@ref{1ca,,asyncio.loop.create_task()}

@item 
gh-127604@footnote{https://github.com/python/cpython/issues/127604}: Add support for printing the C stack trace on systems that
support it via @ref{20e,,faulthandler.dump_c_stack()} or via the `c_stack'
argument in @ref{20f,,faulthandler.enable()}.

@item 
gh-127385@footnote{https://github.com/python/cpython/issues/127385}: Add the @code{F_DUPFD_QUERY} constant to the @ref{5d,,fcntl} module.

@item 
gh-126838@footnote{https://github.com/python/cpython/issues/126838}: Add `resolve_host' keyword-only parameter to
@ref{2bd,,urllib.request.url2pathname()}, and fix handling of file URLs with
authorities.

@item 
gh-82129@footnote{https://github.com/python/cpython/issues/82129}: Fix @ref{452,,NameError} when calling @ref{8c0,,typing.get_type_hints()}
on a @ref{4e1,,dataclasses.dataclass()} created by
@ref{185c,,dataclasses.make_dataclass()} with un-annotated fields.

@item 
gh-122559@footnote{https://github.com/python/cpython/issues/122559}: Remove @code{__reduce__()} and @code{__reduce_ex__()} methods
that always raise @ref{198,,TypeError} in the C implementation of
@ref{1527,,io.FileIO}, @ref{1427,,io.BufferedReader}, @ref{15cb,,io.BufferedWriter}
and @ref{15cc,,io.BufferedRandom} and replace them with default
@code{__getstate__()} methods that raise @code{TypeError}. This restores
fine details of behavior of Python 3.11 and older versions.

@item 
gh-122179@footnote{https://github.com/python/cpython/issues/122179}: @ref{854,,hashlib.file_digest()} now raises @ref{235,,BlockingIOError}
when no data is available during non-blocking I/O. Before, it added
spurious null bytes to the digest.

@item 
gh-53032@footnote{https://github.com/python/cpython/issues/53032}: Expose @ref{1ff,,decimal.IEEEContext()} to support creation of
contexts corresponding to the IEEE 754 (2008) decimal interchange formats.
Patch by Sergey B Kirpichev.

@item 
gh-120220@footnote{https://github.com/python/cpython/issues/120220}: Deprecate the @code{tkinter.Variable} methods
@code{trace_variable()}, @code{trace_vdelete()} and @code{trace_vinfo()}.
Methods @code{trace_add()}, @code{trace_remove()} and @code{trace_info()}
can be used instead.

@item 
gh-113539@footnote{https://github.com/python/cpython/issues/113539}: @ref{11b,,webbrowser}: Names in the 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} environment
variable can now refer to already registered web browsers, instead of
always generating a new browser command.

This makes it possible to set 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} to the value of one of the
supported browsers on macOS.

@item 
bpo-44172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44172}: Keep a reference to original @ref{2f,,curses} windows in
subwindows so that the original window does not get deleted before
subwindows.

@item 
gh-75223@footnote{https://github.com/python/cpython/issues/75223}: Deprecate undotted extensions in
@ref{319,,mimetypes.MimeTypes.add_type()}. Patch by Hugo van Kemenade.
@end itemize

@node IDLE<5>,ドキュメント<8>,ライブラリ<24>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id94}@anchor{185d}
@subsubsection IDLE



@itemize -

@item 
gh-112936@footnote{https://github.com/python/cpython/issues/112936}: fix IDLE: no Shell menu item in single-process mode.
@end itemize

@node ドキュメント<8>,Core and Builtins<22>,IDLE<5>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id95}@anchor{185e}
@subsubsection ドキュメント



@itemize -

@item 
gh-107006@footnote{https://github.com/python/cpython/issues/107006}: Move documentation and example code for
@ref{185f,,threading.local} from its docstring to the official docs.

@item 
gh-125142@footnote{https://github.com/python/cpython/issues/125142}: As part of the builtin help intro text, show the keyboard
shortcuts for the new, non-basic REPL (F1, F2, and F3).
@end itemize

@node Core and Builtins<22>,ライブラリ<25>,ドキュメント<8>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id96}@anchor{1860}
@subsubsection Core and Builtins



@itemize -

@item 
gh-133336@footnote{https://github.com/python/cpython/issues/133336}: @code{-J} is no longer reserved for use by Jython. Patch by
Adam Turner.

@item 
gh-133261@footnote{https://github.com/python/cpython/issues/133261}: Fix bug where the cycle GC could untrack objects in the
trashcan because they looked like they were immortal. When objects are
added to the trashcan, we take care to ensure they keep a mortal reference
count.

@item 
gh-133346@footnote{https://github.com/python/cpython/issues/133346}: Added experimental color theming support to the @code{_colorize}
module.

@item 
gh-132917@footnote{https://github.com/python/cpython/issues/132917}: For the free-threaded build, check the process memory usage
increase before triggering a full automatic garbage collection.  If the
memory used has not increased 10% since the last collection then defer it.

@item 
gh-91048@footnote{https://github.com/python/cpython/issues/91048}: Add a new @code{python -m asyncio ps PID} command-line interface to
inspect asyncio tasks in a running Python process. Displays a flat table
of await relationships. A variant showing a tree view is also available as
@code{python -m asyncio pstree PID}. Both are useful for debugging async
code. Patch by Pablo Galindo, Łukasz Langa, Yury Selivanov, and Marta
Gomez Macias.

@item 
gh-133304@footnote{https://github.com/python/cpython/issues/133304}: Workaround NaN's "canonicalization" in @ref{96a,,PyFloat_Pack4()}
and @ref{96d,,PyFloat_Unpack4()} on RISC-V.

@item 
gh-133197@footnote{https://github.com/python/cpython/issues/133197}: Improve @ref{18e,,SyntaxError} error messages for incompatible
string / bytes prefixes.

@item 
gh-133231@footnote{https://github.com/python/cpython/issues/133231}: Add new utilities of observing JIT compilation:
@ref{44f,,sys._jit.is_available()}, @ref{450,,sys._jit.is_enabled()}, and
@ref{1861,,sys._jit.is_active()}.
@end itemize

@node ライブラリ<25>,Core and Builtins<23>,Core and Builtins<22>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id97}@anchor{1862}
@subsubsection ライブラリ



@itemize -

@item 
gh-133194@footnote{https://github.com/python/cpython/issues/133194}: @ref{1c2,,ast.parse()} will no longer parse new 
@geindex Python Enhancement Proposals; PEP 758
PEP 758@footnote{https://peps.python.org/pep-0758/} syntax
with older `feature_version' passed.
@end itemize

@node Core and Builtins<23>,ライブラリ<26>,ライブラリ<25>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id98}@anchor{1863}
@subsubsection Core and Builtins



@itemize -

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Split @code{CALL_LEN} into several uops allowing the JIT to remove
them when optimizing. Patch by Diego Russo.

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Use @code{sym_new_type} instead of @code{sym_new_not_null} for
_BUILD_STRING, _BUILD_SET

@item 
gh-132942@footnote{https://github.com/python/cpython/issues/132942}: Fix two races in the type lookup cache.  This affected the
free-threaded build and could cause crashes (apparently quite difficult to
trigger).

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Propagate the return type of @code{_BINARY_OP_SUBSCR_TUPLE_INT} in
JIT. Patch by Tomas Roun

@item 
gh-132952@footnote{https://github.com/python/cpython/issues/132952}: Speed up startup with the @code{-S} argument by importing the
private @code{_io} module instead of @ref{83,,io}. This fixes a performance
regression introduced earlier in Python 3.14 development and restores
performance to the level of Python 3.13.

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Allow the JIT to remove int guards after @code{_CALL_LEN} by
setting the return type to int. Patch by Diego Russo

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Split @code{CALL_TUPLE_1} into several uops allowing the JIT to
remove some of them. Patch by Tomas Roun

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Split @code{CALL_STR_1} into several uops allowing the JIT to
remove some of them. Patch by Tomas Roun

@item 
gh-132825@footnote{https://github.com/python/cpython/issues/132825}: Enhance unhashable key/element error messages for @ref{183,,dict}
and @ref{184,,set}. Patch by Victor Stinner.

@item 
gh-131591@footnote{https://github.com/python/cpython/issues/131591}: Reset any 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/} remote debugging pending call in children
after @ref{4b5,,os.fork()} calls.

@item 
gh-132713@footnote{https://github.com/python/cpython/issues/132713}: Fix @code{repr(list)} race condition: hold a strong reference to
the item while calling @code{repr(item)}. Patch by Victor Stinner.

@item 
gh-132661@footnote{https://github.com/python/cpython/issues/132661}: Implement 
@geindex Python Enhancement Proposals; PEP 750
PEP 750@footnote{https://peps.python.org/pep-0750/} (Template Strings). Add new syntax for
t-strings and implement new internal @code{string.templatelib.Template}
and @code{string.templatelib.Interpolation} types.

@item 
gh-132479@footnote{https://github.com/python/cpython/issues/132479}: Fix compiler crash in certain circumstances where multiple
module-level annotations include comprehensions and other nested scopes.

@item 
gh-132747@footnote{https://github.com/python/cpython/issues/132747}: Fix a crash when calling @ref{1701,,__get__()} of a
@ref{1864,,method} with a @ref{885,,None} second argument.

@item 
gh-132744@footnote{https://github.com/python/cpython/issues/132744}: Certain calls now check for runaway recursion and respect the
system recursion limit.

@item 
gh-132449@footnote{https://github.com/python/cpython/issues/132449}: Syntax errors that look like misspellings of Python keywords
now provide a helpful fix suggestion for the typo.  Contributed by Pablo
Galindo Salgado.
@end itemize

@node ライブラリ<26>,Core and Builtins<24>,Core and Builtins<23>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id99}@anchor{1865}
@subsubsection ライブラリ



@itemize -

@item 
gh-132737@footnote{https://github.com/python/cpython/issues/132737}: Support profiling code that requires @code{__main__}, such as
@ref{ab,,pickle}.
@end itemize

@node Core and Builtins<24>,ライブラリ<27>,ライブラリ<26>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id100}@anchor{1866}
@subsubsection Core and Builtins



@itemize -

@item 
gh-132639@footnote{https://github.com/python/cpython/issues/132639}: Added @ref{606,,PyLong_AsNativeBytes()},
@ref{607,,PyLong_FromNativeBytes()} and
@ref{608,,PyLong_FromUnsignedNativeBytes()} to the limited C API.

@item 
gh-100239@footnote{https://github.com/python/cpython/issues/100239}: Add specialisation for @code{BINARY_OP/SUBSCR} on list and slice.

@item 
gh-132508@footnote{https://github.com/python/cpython/issues/132508}: Uses tagged integers on the evaluation stack to represent the
instruction offsets when reraising an exception. This avoids the need to
box the integer which could fail in low memory conditions.

@item 
gh-124476@footnote{https://github.com/python/cpython/issues/124476}: Fix decoding from the locale encoding in the C.UTF-8 locale.

@item 
gh-131927@footnote{https://github.com/python/cpython/issues/131927}: Compiler warnings originating from the same module and line
number are now only emitted once, matching the behaviour of warnings
emitted from user code. This can also be configured with @ref{118,,warnings}
filters.

@item 
gh-132457@footnote{https://github.com/python/cpython/issues/132457}: Make @ref{453,,staticmethod()} and @ref{48e,,classmethod()} generic.

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Use @code{sym_new_type} instead of @code{sym_new_not_null} for
_BUILD_LIST, _BUILD_SET, _BUILD_MAP

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Split @code{CALL_TYPE_1} into several uops allowing the JIT to
remove some of them.

@item 
gh-132386@footnote{https://github.com/python/cpython/issues/132386}: Fix crash when passing a dict subclass as the @code{globals}
parameter to @ref{4a2,,exec()}.

@item 
gh-127682@footnote{https://github.com/python/cpython/issues/127682}: No longer call @code{__iter__} twice when creating and executing a
generator expression. Creating a generator expression from a non-interable
will raise only when the generator expression is executed. This brings the
behavior of generator expressions in line with other generators.

@item 
gh-132261@footnote{https://github.com/python/cpython/issues/132261}: The internal storage for annotations and annotate functions on
classes now uses different keys in the class dictionary. This eliminates
various edge cases where access to the @code{__annotate__} and
@code{__annotations__} attributes would behave unpredictably.

@item 
gh-132284@footnote{https://github.com/python/cpython/issues/132284}: Don't wrap base @code{PyCFunction} slots on class creation if not
overridden.

@item 
gh-130415@footnote{https://github.com/python/cpython/issues/130415}: Improve the JIT's ability to remove unused constant and local
variable loads, and fix an issue where deallocating unused values could
cause JIT code to crash or behave incorrectly.

@item 
gh-126703@footnote{https://github.com/python/cpython/issues/126703}: Fix possible use after free in cases where a method's
definition has the same lifetime as its @code{self}.

@item 
gh-132286@footnote{https://github.com/python/cpython/issues/132286}: Fix that @ref{1867,,type.__annotate__} was not deleted, when
@ref{1843,,type.__annotations__} was deleted.

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Allow the JIT to remove an extra @code{_TO_BOOL_BOOL} instruction
after @code{_CONTAINS_OP_DICT} by setting the return type to bool.

@item 
gh-124715@footnote{https://github.com/python/cpython/issues/124715}: Prevents against stack overflows when calling
@ref{790,,Py_DECREF()}. Third-party extension objects no longer need to use
the "trashcan" mechanism, as protection is now built into the
@ref{790,,Py_DECREF()} macro.

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Allow the JIT compiler to remove some type checks for
operations on lists, tuples, dictionaries, and sets.

@item 
gh-128398@footnote{https://github.com/python/cpython/issues/128398}: Improve error message when an object supporting the synchronous
(resp. asynchronous) context manager protocol is entered using
@ref{185,,async with} (resp. @ref{186,,with}) instead of @ref{186,,with}
(resp. @ref{185,,async with}). Patch by Bénédikt Tran.

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Allow the JIT to remove unicode guards after
@code{_BINARY_OP_SUBSCR_STR_INT} by setting the return type to string.

@item 
gh-131878@footnote{https://github.com/python/cpython/issues/131878}: Handle uncaught exceptions in the main input loop for the new
REPL.

@item 
gh-131878@footnote{https://github.com/python/cpython/issues/131878}: Fix support of unicode characters with two or more codepoints
on Windows in the new REPL.

@item 
gh-126835@footnote{https://github.com/python/cpython/issues/126835}: Move constant folding to the peephole optimizer. Rename AST
optimization related files (Python/ast_opt.c -> Python/ast_preprocess.c),
structs (_PyASTOptimizeState -> _PyASTPreprocessState) and functions
(_PyAST_Optimize -> _PyAST_Preprocess, _PyCompile_AstOptimize ->
_PyCompile_AstPreprocess).

@item 
gh-114809@footnote{https://github.com/python/cpython/issues/114809}: Add support for macOS multi-arch builds with the JIT enabled

@item 
gh-131507@footnote{https://github.com/python/cpython/issues/131507}: PyREPL now supports syntax highlighting. Contributed by Łukasz
Langa.

@item 
gh-130907@footnote{https://github.com/python/cpython/issues/130907}: If the @code{__annotations__} of a module object are accessed
while the module is executing, return the annotations that have been
defined so far, without caching them.

@item 
gh-130104@footnote{https://github.com/python/cpython/issues/130104}: Three-argument @ref{1a4,,pow()} now try calling
@ref{1a5,,__rpow__()} if necessary. Previously it was only called in
two-argument @code{pow()} and the binary power operator.

@item 
gh-130070@footnote{https://github.com/python/cpython/issues/130070}: Fixed an assertion error for @ref{4a2,,exec()} passed a string
@code{source} and a non-@code{None} @code{closure}. Patch by Bartosz Sławecki.

@item 
gh-129958@footnote{https://github.com/python/cpython/issues/129958}: Fix a bug that was allowing newlines inconsistently in format
specifiers for single-quoted f-strings. Patch by Pablo Galindo.

@item 
gh-129858@footnote{https://github.com/python/cpython/issues/129858}: @code{elif} statements that follow an @code{else} block now have a
specific error message.

@item 
gh-69605@footnote{https://github.com/python/cpython/issues/69605}: Add module autocomplete to PyREPL.

@item 
gh-128555@footnote{https://github.com/python/cpython/issues/128555}: Add the @ref{175,,sys.flags.thread_inherit_context} flag.


@itemize *

@item 
This flag is set to true by default on the free-threaded build
and false otherwise.  If the flag is true, starting a new thread using
@ref{176,,threading.Thread} will, by default, use a copy of the
@ref{177,,contextvars.Context} from the caller of
@ref{178,,threading.Thread.start()} rather than using an empty context.

@item 
Add the @ref{16f,,-X thread_inherit_context} command-line option and
@geindex PYTHON_THREAD_INHERIT_CONTEXT
@geindex 環境変数; PYTHON_THREAD_INHERIT_CONTEXT
@ref{1868,,PYTHON_THREAD_INHERIT_CONTEXT} environment variable, which set the
@ref{175,,thread_inherit_context} flag.

@item 
Add the @code{context} keyword parameter to @ref{176,,Thread}.  It can
be used to explicitly pass a context value to be used by a new thread.

@item 
Make the @code{_contextvars} module built-in.
@end itemize

@item 
gh-123539@footnote{https://github.com/python/cpython/issues/123539}: Improve @ref{18e,,SyntaxError} message for using @code{import ... as}
and @code{from ... import ... as} with not a name.

@item 
gh-102567@footnote{https://github.com/python/cpython/issues/102567}: @ref{16f,,-X importtime} now accepts value @code{2}, which
indicates that an @code{importtime} entry should also be printed if an
imported module has already been loaded. Patch by Noah Kim and Adam
Turner.

@item 
gh-116436@footnote{https://github.com/python/cpython/issues/116436}: Improve error message when @ref{198,,TypeError} occurs during
@ref{167e,,dict.update()}

@item 
gh-103997@footnote{https://github.com/python/cpython/issues/103997}: String arguments passed to "-c" are now automatically dedented
as if by @ref{1a9,,textwrap.dedent()}. This allows "python -c" invocations to
be indented in shell scripts without causing indentation errors. (Patch by
Jon Crall and Steven Sun)
@end itemize

@node ライブラリ<27>,C API<8>,Core and Builtins<24>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id101}@anchor{1869}
@subsubsection ライブラリ



@itemize -

@item 
gh-89562@footnote{https://github.com/python/cpython/issues/89562}: Remove @code{hostflags} member from @code{PySSLContext} struct.
@end itemize

@node C API<8>,ビルド<8>,ライブラリ<27>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id102}@anchor{186a}
@subsubsection C API



@itemize -

@item 
gh-133166@footnote{https://github.com/python/cpython/issues/133166}: Fix regression where @ref{635,,PyType_GetModuleByDef()} returns
NULL without setting @ref{198,,TypeError} when a static type is passed.

@item 
gh-133164@footnote{https://github.com/python/cpython/issues/133164}: Add @ref{3c7,,PyUnstable_Object_IsUniqueReferencedTemporary()}
function for determining if an object exists as a unique temporary
variable on the interpreter's stack.  This is a replacement for some cases
where checking that @ref{2cf,,Py_REFCNT()} is one is no longer sufficient to
determine if it's safe to modify a Python object in-place with no visible
side effects.

@item 
gh-133140@footnote{https://github.com/python/cpython/issues/133140}: Add @ref{3c6,,PyUnstable_Object_IsUniquelyReferenced()} as a
replacement for @code{Py_REFNCT(op) == 1} on @ref{1f4,,free threaded} builds of Python.

@item 
gh-131747@footnote{https://github.com/python/cpython/issues/131747}: On non-Windows platforms, deprecate using
@ref{317,,ctypes.Structure._pack_} to use a Windows-compatible layout on
non-Windows platforms. The layout should be specified explicitly by
setting @ref{1e7,,ctypes.Structure._layout_} to @code{'ms'}.

@item 
gh-128972@footnote{https://github.com/python/cpython/issues/128972}: For non-free-threaded builds, the memory layout of
@ref{138d,,PyASCIIObject} is reverted to match Python 3.13. (Note that the
structure is not part of stable ABI and so its memory layout is
`guaranteed' to remain stable.)

@item 
gh-133079@footnote{https://github.com/python/cpython/issues/133079}: The undocumented APIs @code{Py_C_RECURSION_LIMIT} and
@code{PyThreadState.c_recursion_remaining}, added in 3.13, are
removed without a deprecation period.

@item 
gh-132987@footnote{https://github.com/python/cpython/issues/132987}: The @code{k} and @code{K} formats in @ref{180e,,PyArg_Parse()} now
support the @ref{19e,,__index__()} special method, like all other
integer formats.

@item 
gh-132909@footnote{https://github.com/python/cpython/issues/132909}: Fix an overflow when handling the @ref{186b,,K} format in @ref{3c2,,Py_BuildValue()}. Patch by
Bénédikt Tran.

@item 
gh-132798@footnote{https://github.com/python/cpython/issues/132798}: Deprecated and undocumented functions
@code{PyUnicode_AsEncodedObject()},
@code{PyUnicode_AsDecodedObject()},
@code{PyUnicode_AsEncodedUnicode()} and
@code{PyUnicode_AsDecodedUnicode()} are scheduled for removal in 3.15.

@item 
gh-132470@footnote{https://github.com/python/cpython/issues/132470}: Creating a @ref{1e8,,ctypes.CField} with a `byte_size' that does
not match the actual type size now raises a @ref{2ec,,ValueError} instead of
crashing the interpreter.

@item 
gh-112068@footnote{https://github.com/python/cpython/issues/112068}: [Reverted in gh-136991@footnote{https://github.com/python/cpython/issues/136991}] Add support of nullable arguments in
@ref{180e,,PyArg_Parse()} and similar functions. Adding @code{?} after any format
unit makes @code{None} be accepted as a value.

@item 
gh-50333@footnote{https://github.com/python/cpython/issues/50333}: Non-tuple sequences are deprecated as argument for the
@code{(items)} format unit in @ref{3c1,,PyArg_ParseTuple()} and other
@ref{3d5,,argument parsing} functions if `items' contains format
units which store a @ref{3d6,,borrowed buffer} or a
@ref{3d7,,borrowed reference}.
@end itemize

@node ビルド<8>,,C API<8>,Python 3 14 0 beta 1
@anchor{whatsnew/changelog id103}@anchor{186c}
@subsubsection ビルド



@itemize -

@item 
gh-113464@footnote{https://github.com/python/cpython/issues/113464}: Use the cpython-bin-deps "externals" repository for Windows
LLVM dependency management. Installing LLVM manually is no longer
necessary for Windows JIT builds.

@item 
gh-133183@footnote{https://github.com/python/cpython/issues/133183}: iOS compiler shims now include @code{IPHONEOS_DEPLOYMENT_TARGET}
in target triples, ensuring that SDK version minimums are honored.

@item 
gh-133167@footnote{https://github.com/python/cpython/issues/133167}: Fix compilation process with @code{--enable-optimizations} and
@code{--without-docstrings}.

@item 
gh-133171@footnote{https://github.com/python/cpython/issues/133171}: Since free-threaded builds do not support the experimental JIT
compiler, prevent these configurations from being combined.

@item 
gh-132758@footnote{https://github.com/python/cpython/issues/132758}: Fix building with tail call interpreter and pystats.

@item 
gh-132649@footnote{https://github.com/python/cpython/issues/132649}: The @code{PClayout} script now allows passing
@code{--include-tcltk} on Windows ARM64.

@item 
gh-132257@footnote{https://github.com/python/cpython/issues/132257}: Change the default LTO flags on GCC to not pass
@code{-flto-partition=none}, and allow parallelization of LTO. For newer GNU
makes and GCC, this has a multiple factor speedup for LTO build times,
with no noticeable loss in performance.

@item 
gh-132026@footnote{https://github.com/python/cpython/issues/132026}: Fix use of undefined identifiers in platform triplet detection
on MIPS Linux platforms.
@end itemize

@node Python 3 14 0 alpha 7,Python 3 14 0 alpha 6,Python 3 14 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-14-0-alpha-7}@anchor{186d}
@subsection Python 3.14.0 alpha 7


`リリース日: 2025-04-08'

@menu
* macOS: macOS<4>. 
* Windows: Windows<10>. 
* Tools/Demos: Tools/Demos<9>. 
* テスト: テスト<7>. 
* セキュリティ: セキュリティ<11>. 
* ライブラリ: ライブラリ<28>. 
* ドキュメント: ドキュメント<9>. 
* Core and Builtins: Core and Builtins<25>. 
* ライブラリ: ライブラリ<29>. 
* Core and Builtins: Core and Builtins<26>. 
* C API: C API<9>. 
* ビルド: ビルド<9>. 

@end menu

@node macOS<4>,Windows<10>,,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id104}@anchor{186e}
@subsubsection macOS



@itemize -

@item 
gh-124111@footnote{https://github.com/python/cpython/issues/124111}: Update macOS installer to use Tcl/Tk 8.6.16.

@item 
gh-131423@footnote{https://github.com/python/cpython/issues/131423}: Update macOS installer to use OpenSSL 3.0.16. Patch by Bénédikt
Tran.

@item 
gh-131025@footnote{https://github.com/python/cpython/issues/131025}: Update macOS installer to ship with SQLite 3.49.1.
@end itemize

@node Windows<10>,Tools/Demos<9>,macOS<4>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id105}@anchor{186f}
@subsubsection Windows



@itemize -

@item 
gh-131423@footnote{https://github.com/python/cpython/issues/131423}: Update bundled version of OpenSSL to 3.0.16. The new build also
disables uplink support, which may be relevant to embedders but has no
impact on normal use.

@item 
gh-131453@footnote{https://github.com/python/cpython/issues/131453}: Some @code{SND_*} and @code{MB_*} constants are added to
@ref{11d,,winsound}.

@item 
gh-91349@footnote{https://github.com/python/cpython/issues/91349}: Replaces our copy of @code{zlib} with @code{zlib-ng}, for performance
improvements in @ref{139,,zlib}.

@item 
gh-131025@footnote{https://github.com/python/cpython/issues/131025}: Update Windows installer to ship with SQLite 3.49.1.
@end itemize

@node Tools/Demos<9>,テスト<7>,Windows<10>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id106}@anchor{1870}
@subsubsection Tools/Demos



@itemize -

@item 
gh-132121@footnote{https://github.com/python/cpython/issues/132121}: Always escape non-printable Unicode characters in
@code{pygettext}.

@item 
gh-131852@footnote{https://github.com/python/cpython/issues/131852}: @code{msgfmt} no longer adds the @code{POT-Creation-Date} to
generated @code{.mo} files for consistency with GNU @code{msgfmt}.
@end itemize

@node テスト<7>,セキュリティ<11>,Tools/Demos<9>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id107}@anchor{1871}
@subsubsection テスト



@itemize -

@item 
gh-131277@footnote{https://github.com/python/cpython/issues/131277}: Allow to unset one or more environment variables at once via
@ref{1872,,EnvironmentVarGuard.unset()}. Patch by Bénédikt
Tran.

@item 
gh-131050@footnote{https://github.com/python/cpython/issues/131050}: @code{test_ssl.test_dh_params} is skipped if the underlying TLS
library does not support finite-field ephemeral Diffie-Hellman.
@end itemize

@node セキュリティ<11>,ライブラリ<28>,テスト<7>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id108}@anchor{1873}
@subsubsection セキュリティ



@itemize -

@item 
gh-131809@footnote{https://github.com/python/cpython/issues/131809}: Update bundled libexpat to 2.7.1

@item 
gh-131261@footnote{https://github.com/python/cpython/issues/131261}: Upgrade to libexpat 2.7.0

@item 
gh-121284@footnote{https://github.com/python/cpython/issues/121284}: Fix bug in the folding of rfc2047 encoded-words when flattening
an email message using a modern email policy. Previously when an
encoded-word was too long for a line, it would be decoded, split across
lines, and re-encoded. But commas and other special characters in the
original text could be left unencoded and unquoted. This could
theoretically be used to spoof header lines using a carefully constructed
encoded-word if the resulting rendered email was transmitted or re-parsed.
@end itemize

@node ライブラリ<28>,ドキュメント<9>,セキュリティ<11>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id109}@anchor{1874}
@subsubsection ライブラリ



@itemize -

@item 
gh-132174@footnote{https://github.com/python/cpython/issues/132174}: Fix function name in error message of
@code{_interpreters.run_string}.

@item 
gh-132171@footnote{https://github.com/python/cpython/issues/132171}: Fix crash of @code{_interpreters.run_string} on string subclasses.

@item 
gh-129204@footnote{https://github.com/python/cpython/issues/129204}: Introduce new @code{_PYTHON_SUBPROCESS_USE_POSIX_SPAWN}
environment variable knob in @ref{dc,,subprocess} to control the use of
@ref{52e,,os.posix_spawn()}.

@item 
gh-132159@footnote{https://github.com/python/cpython/issues/132159}: Do not shadow user arguments in generated @code{__new__()} by
decorator @ref{489,,warnings.deprecated}. Patch by Xuehai Pan.

@item 
gh-132168@footnote{https://github.com/python/cpython/issues/132168}: The @ref{1f3,,ctypes.py_object} type now supports subscription,
making it a @ref{1a1,,generic type}.

@item 
gh-84481@footnote{https://github.com/python/cpython/issues/84481}: Add the @code{zipfile.ZipFile.data_offset} attribute, which
stores the offset to the beginning of ZIP data in a file when available.
When the @ref{8d3,,zipfile.ZipFile} is opened in either mode @code{'w'} or
@code{'x'} and the underlying file does not support @code{tell()}, the value
will be @code{None} instead.

@item 
gh-132075@footnote{https://github.com/python/cpython/issues/132075}: Fix possible use of @ref{d1,,socket} address structures with
uninitialized members. Now all structure members are initialized with
zeroes by default.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import times by up to 27x for the @ref{d8,,string} module.
Patch by Adam Turner.

@item 
gh-125434@footnote{https://github.com/python/cpython/issues/125434}: Display thread name in @ref{5c,,faulthandler}. Patch by Victor
Stinner.

@item 
gh-132002@footnote{https://github.com/python/cpython/issues/132002}: Fix crash when deallocating @ref{1875,,contextvars.ContextVar}
with weird unahashable string names.

@item 
gh-131938@footnote{https://github.com/python/cpython/issues/131938}: @ref{12b,,xml.etree.ElementTree}: update the error message when an
element to remove via @ref{1876,,Element.remove} is not found. Patch by Bénédikt
Tran.

@item 
gh-115942@footnote{https://github.com/python/cpython/issues/115942}: Add @ref{183c,,threading.RLock.locked()},
@ref{1877,,multiprocessing.Lock.locked()}, @ref{1878,,multiprocessing.RLock.locked()},
and allow @ref{15af,,multiprocessing.managers.SyncManager.Lock()} and
@ref{15b0,,multiprocessing.managers.SyncManager.RLock()} to proxy @code{locked()}
call.

@item 
gh-131974@footnote{https://github.com/python/cpython/issues/131974}: Fix several thread-safety issues in @ref{2e,,ctypes} on the
@ref{1f4,,free threaded} build.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve the import time of the @ref{9,,ast} module by extracting
the @ref{ae2,,unparse()} function to a helper module.

@item 
gh-107369@footnote{https://github.com/python/cpython/issues/107369}: Improved performance of @ref{57d,,textwrap.indent()} by an average
of ~1.3x. Patch by Adam Turner.

@item 
gh-131792@footnote{https://github.com/python/cpython/issues/131792}: Improved performance of @ref{1a9,,textwrap.dedent()} by an average
of ~2.4x, (with improvements of up to 4x for large inputs), and fixed a
bug where blank lines with whitespace characters other than space or
horizontal tab were not normalised to the newline. Patch by Adam Turner,
Marius Juston, and Pieter Eendebak.

@item 
gh-131668@footnote{https://github.com/python/cpython/issues/131668}: @ref{d1,,socket}: Fix code parsing AF_BLUETOOTH socket addresses.

@item 
gh-60115@footnote{https://github.com/python/cpython/issues/60115}: Support frozen modules for @ref{240,,linecache.getline()}.

@item 
gh-131492@footnote{https://github.com/python/cpython/issues/131492}: Fix a resource leak when constructing a @ref{65c,,gzip.GzipFile}
with a filename fails, for example when passing an invalid
@code{compresslevel}.

@item 
gh-131435@footnote{https://github.com/python/cpython/issues/131435}: 10-20% performance improvement of @ref{1447,,random.randint()}.

@item 
gh-131461@footnote{https://github.com/python/cpython/issues/131461}: Fix @ref{54c,,ResourceWarning} when constructing a
@ref{65c,,gzip.GzipFile} in write mode with a broken file object.

@item 
gh-125866@footnote{https://github.com/python/cpython/issues/125866}: Deprecate the @code{nturl2path} module. Call
@ref{2bd,,urllib.request.url2pathname()} and
@ref{2bf,,pathname2url()} instead.

@item 
gh-126367@footnote{https://github.com/python/cpython/issues/126367}: Fix issue where @ref{2bd,,urllib.request.url2pathname()} raised
@ref{2c0,,OSError} when given a Windows URI containing a colon character not
following a drive letter, such as before an NTFS alternate data stream.

@item 
gh-120144@footnote{https://github.com/python/cpython/issues/120144}: Disable @code{CALL} event in @ref{10,,bdb} in @code{monitoring} backend
when we don't need any new events on the code object to get a better
performance.

@item 
gh-131358@footnote{https://github.com/python/cpython/issues/131358}: Register @code{cseuckr} as an encoding alias for @code{euc_kr}.

@item 
gh-131325@footnote{https://github.com/python/cpython/issues/131325}: Fix sendfile fallback implementation to drain data after
writing to transport in @ref{b,,asyncio}.

@item 
gh-90548@footnote{https://github.com/python/cpython/issues/90548}: @ref{17f5,,platform.libc_ver()} can now detect and report the version
of @code{musl} on Alpine Linux.

@item 
gh-129843@footnote{https://github.com/python/cpython/issues/129843}: Fix incorrect argument passing in
@ref{efd,,warnings.warn_explicit()}.

@item 
gh-70647@footnote{https://github.com/python/cpython/issues/70647}: When creating a @ref{34,,datetime} object with an out of range date
a more informative error is raised.

@item 
gh-130914@footnote{https://github.com/python/cpython/issues/130914}: Allow @ref{21f,,graphlib.TopologicalSorter.prepare()} to be called
more than once as long as sorting has not started. Patch by Daniel Pope.

@item 
gh-131236@footnote{https://github.com/python/cpython/issues/131236}: Allow to generate multiple UUIDs at once via @ref{2c7,,python -m uuid --count}.

@item 
gh-126895@footnote{https://github.com/python/cpython/issues/126895}: Fix @ref{bf,,readline} in @ref{1f4,,free-threaded}
build.

@item 
gh-121468@footnote{https://github.com/python/cpython/issues/121468}: @code{$_asynctask} is added as a @ref{aa,,pdb} convenience variable
to access the current asyncio task if applicable.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import time of @ref{8a,,locale} using lazy import @code{re}.
Patch by Semyon Moroz.

@item 
gh-129598@footnote{https://github.com/python/cpython/issues/129598}: Fix @ref{ae2,,ast.unparse()} when @ref{1879,,ast.Interactive} contains
multiple statements.

@item 
gh-85162@footnote{https://github.com/python/cpython/issues/85162}: The @ref{76,,http.server} module now includes built-in support for
HTTPS servers exposed by @ref{228,,http.server.HTTPSServer}. This
functionality is exposed by the command-line interface (@code{python -m
http.server}) through the @code{--tls-cert}, @code{--tls-key} and
@code{--tls-password-file} options. Patch by Semyon Moroz.

@item 
gh-129463@footnote{https://github.com/python/cpython/issues/129463}: The implementations of equality and hashing for
@ref{1776,,annotationlib.ForwardRef} now use all attributes on the object.
Two @code{ForwardRef} objects are equal only if all attributes are
equal.

@item 
gh-128593@footnote{https://github.com/python/cpython/issues/128593}: @ref{1776,,annotationlib.ForwardRef} objects no longer cache their
value when they are successfully evaluated. Successive calls to
@ref{17b2,,annotationlib.ForwardRef.evaluate()} may return different values.

@item 
gh-117779@footnote{https://github.com/python/cpython/issues/117779}: Fix reading duplicated entries in @ref{137,,zipfile} by name.
Reading duplicated entries (except the last one) by @code{ZipInfo} now emits
a warning instead of raising an exception.

@item 
gh-128715@footnote{https://github.com/python/cpython/issues/128715}: The class of @ref{1e5,,Structure}/@ref{1e6,,Union}
field descriptors is now available as @ref{1e8,,CField}, and has new
attributes to aid debugging and introspection.

@item 
gh-128055@footnote{https://github.com/python/cpython/issues/128055}: Fix @code{test.test_sysconfig.test_sysconfigdata_json} when
running outside the build directory (eg. after installing).

@item 
gh-126037@footnote{https://github.com/python/cpython/issues/126037}: @ref{12b,,xml.etree.ElementTree}: Fix a crash in
@ref{187a,,Element.find},
@ref{187b,,Element.findtext} and
@ref{187c,,Element.findall} when the
tag to find implements an @ref{cf2,,__eq__()} method mutating the
element being queried. Patch by Bénédikt Tran.

@item 
gh-127794@footnote{https://github.com/python/cpython/issues/127794}: When headers are added to @ref{581,,email.message.Message}
objects, either through @ref{187d,,email.message.Message.__setitem__()} or
@ref{187e,,email.message.Message.add_header()}, the field name is now validated
according to 
@geindex RFC; RFC 5322 Section 2.2
RFC 5322@comma{} Section 2.2@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html#section-2.2} and a
@ref{2ec,,ValueError} is raised if the field name contains any invalid
characters.

@item 
gh-123599@footnote{https://github.com/python/cpython/issues/123599}: Deprecate @code{pathlib.PurePath.as_uri()}; use
@ref{31c,,pathlib.Path.as_uri()} instead.

@item 
gh-126033@footnote{https://github.com/python/cpython/issues/126033}: @ref{12b,,xml.etree.ElementTree}: Fix a crash in
@ref{1876,,Element.remove} when the
element is concurrently mutated. Patch by Bénédikt Tran.

@item 
gh-120144@footnote{https://github.com/python/cpython/issues/120144}: Add the optional backend of @code{sys.monitoring} to @ref{10,,bdb}
and use it for @ref{aa,,pdb}.

@item 
gh-74598@footnote{https://github.com/python/cpython/issues/74598}: Add @ref{211,,fnmatch.filterfalse()} for excluding names matching a
pattern. Patch by Bénédikt Tran.

@item 
gh-114917@footnote{https://github.com/python/cpython/issues/114917}: Add support for AI_NUMERICSERV in getaddrinfo emulation

@item 
bpo-17254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17254}: Added aliases for Thai Language using Microsoft Code Pages.
@end itemize

@node ドキュメント<9>,Core and Builtins<25>,ライブラリ<28>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id110}@anchor{187f}
@subsubsection ドキュメント



@itemize -

@item 
gh-131417@footnote{https://github.com/python/cpython/issues/131417}: Mention @ref{dc6,,asyncio.Future} and @ref{1c7,,asyncio.Task} in
generic classes list.
@end itemize

@node Core and Builtins<25>,ライブラリ<29>,ドキュメント<9>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id111}@anchor{1880}
@subsubsection Core and Builtins



@itemize -

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Allow the JIT to remove an extra @code{_TO_BOOL_BOOL} instruction
after @code{_CONTAINS_OP_SET} by setting the return type to bool.

@item 
gh-132011@footnote{https://github.com/python/cpython/issues/132011}: Fix crash when calling @ref{8dc,,list.append()} as an unbound
method.

@item 
gh-131998@footnote{https://github.com/python/cpython/issues/131998}: Fix a crash when using an unbound method @ref{1881,,descriptor}
object in a function where a bound method descriptor was used.

@item 
gh-131591@footnote{https://github.com/python/cpython/issues/131591}: Implement 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/} (Safe external debugger interface for
CPython). Add a new @ref{16d,,sys.remote_exec()} function to the @ref{df,,sys}
module. This function schedules the execution of a Python file in a
separate process. Patch by Pablo Galindo, Matt Wozniski and Ivona
Stojanovic.

@item 
gh-131798@footnote{https://github.com/python/cpython/issues/131798}: Allow JIT to omit str guard in truthiness test when str type is
known.

@item 
gh-131833@footnote{https://github.com/python/cpython/issues/131833}: Add support for optionally dropping grouping parentheses when
using multiple exception types as per 
@geindex Python Enhancement Proposals; PEP 758
PEP 758@footnote{https://peps.python.org/pep-0758/}. Patch by Pablo Galindo

@item 
gh-130924@footnote{https://github.com/python/cpython/issues/130924}: Usage of a name in a function-scope annotation no longer
triggers creation of a cell for that variable. This fixes a regression in
earlier alphas of Python 3.14.

@item 
gh-131800@footnote{https://github.com/python/cpython/issues/131800}: Improve the experimental JIT's ability to remove type checks
for certain subscripting operations.

@item 
gh-131738@footnote{https://github.com/python/cpython/issues/131738}: Compiler emits optimized code for builtin any/all/tuple calls
over a generator expression.

@item 
gh-131719@footnote{https://github.com/python/cpython/issues/131719}: Fix missing NULL check in @code{_PyMem_FreeDelayed} in
@ref{1f4,,free-threaded} build.

@item 
gh-131670@footnote{https://github.com/python/cpython/issues/131670}: Fix @ref{9d6,,anext()} failing on sync @ref{1882,,__anext__()}
raising an exception.

@item 
gh-131666@footnote{https://github.com/python/cpython/issues/131666}: Fix signature of @code{anext_awaitable.close} objects. Patch by
Bénédikt Tran.

@item 
gh-130415@footnote{https://github.com/python/cpython/issues/130415}: Optimize comparison of two constants in JIT builds

@item 
gh-129149@footnote{https://github.com/python/cpython/issues/129149}: Add fast path for small and medium-size integers in
@ref{3a3,,PyLong_FromInt32()}, @ref{3a5,,PyLong_FromUInt32()},
@ref{3a4,,PyLong_FromInt64()} and @ref{3a6,,PyLong_FromUInt64()}. Patch by Chris
Eibl.

@item 
gh-130887@footnote{https://github.com/python/cpython/issues/130887}: Optimize the AArch64 code generation for the JIT. Patch by
Diego Russo

@item 
gh-130956@footnote{https://github.com/python/cpython/issues/130956}: Optimize the AArch64 code generation for the JIT. Patch by
Diego Russo

@item 
gh-130928@footnote{https://github.com/python/cpython/issues/130928}: Fix error message when formatting bytes using the @code{'i'} flag.
Patch by Maxim Ageev.

@item 
gh-130935@footnote{https://github.com/python/cpython/issues/130935}: Annotations at the class and module level that are
conditionally defined are now only reflected in @code{__annotations__} if the
block they are in is executed. Patch by Jelle Zijlstra.

@item 
gh-130775@footnote{https://github.com/python/cpython/issues/130775}: Do not crash on negative @code{column} and @code{end_column} in
@ref{9,,ast} locations.

@item 
gh-130704@footnote{https://github.com/python/cpython/issues/130704}: Optimize @code{LOAD_FAST} and its superinstruction form to reduce
reference counting overhead. These instructions are replaced with faster
variants that load borrowed references onto the operand stack when we can
prove that the reference in the frame outlives the reference loaded onto
the stack.

@item 
gh-88887@footnote{https://github.com/python/cpython/issues/88887}: Fixing multiprocessing Resource Tracker process leaking, usually
observed when running Python as PID 1.

@item 
gh-130115@footnote{https://github.com/python/cpython/issues/130115}: Fix an issue with thread identifiers being sign-extended on
some platforms.
@end itemize

@node ライブラリ<29>,Core and Builtins<26>,Core and Builtins<25>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id112}@anchor{1883}
@subsubsection ライブラリ



@itemize -

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Add support for built-in implementation of HMAC (
@geindex RFC; RFC 2104
RFC 2104@footnote{https://datatracker.ietf.org/doc/html/rfc2104.html})
based on HACL*. Patch by Bénédikt Tran.
@end itemize

@node Core and Builtins<26>,C API<9>,ライブラリ<29>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id113}@anchor{1884}
@subsubsection Core and Builtins



@itemize -

@item 
gh-130080@footnote{https://github.com/python/cpython/issues/130080}: Implement PEP 765: Disallow return/break/continue that exit a
finally block.

@item 
gh-129900@footnote{https://github.com/python/cpython/issues/129900}: Fix return codes inside @ref{f3c,,SystemExit} not getting returned
by the REPL.

@item 
gh-128632@footnote{https://github.com/python/cpython/issues/128632}: Disallow @code{__classdict__} as the name of a type parameter.
Using this name would previously crash the interpreter in some
circumstances.

@item 
gh-126703@footnote{https://github.com/python/cpython/issues/126703}: Improve performance of builtin methods by using a freelist.

@item 
gh-126703@footnote{https://github.com/python/cpython/issues/126703}: Improve performance of  @ref{b3d,,range} by using a freelist.
@end itemize

@node C API<9>,ビルド<9>,Core and Builtins<26>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id114}@anchor{1885}
@subsubsection C API



@itemize -

@item 
gh-131740@footnote{https://github.com/python/cpython/issues/131740}: Update PyUnstable_GC_VisitObjects to traverse perm gen.

@item 
gh-131525@footnote{https://github.com/python/cpython/issues/131525}: The PyTupleObject now caches the computed hash value in the new
field ob_hash.
@end itemize

@node ビルド<9>,,C API<9>,Python 3 14 0 alpha 7
@anchor{whatsnew/changelog id115}@anchor{1886}
@subsubsection ビルド



@itemize -

@item 
gh-131865@footnote{https://github.com/python/cpython/issues/131865}: The DTrace build now properly passes the @code{CC} and @code{CFLAGS}
variables to the @code{dtrace} command when utilizing SystemTap on Linux.

@item 
gh-131675@footnote{https://github.com/python/cpython/issues/131675}: Fix mimalloc library builds for 32-bit ARM targets.

@item 
gh-131691@footnote{https://github.com/python/cpython/issues/131691}: clang-cl on Windows needs option @code{/EHa} to support SEH
(structured exception handling) correctly. Fix by Chris Eibl.

@item 
gh-131278@footnote{https://github.com/python/cpython/issues/131278}: Add optimizing flag @code{WITH_COMPUTED_GOTOS} to Windows builds
for when using a compiler that supports it (currently clang-cl). Patch by
Chris Eibl.

@item 
gh-130213@footnote{https://github.com/python/cpython/issues/130213}: Update the vendored HACL* library to fix build issues with
older clang compilers.

@item 
gh-130673@footnote{https://github.com/python/cpython/issues/130673}: Fix potential @code{KeyError} when handling object sections during
JIT building process.
@end itemize

@node Python 3 14 0 alpha 6,Python 3 14 0 alpha 5,Python 3 14 0 alpha 7,変更履歴
@anchor{whatsnew/changelog python-3-14-0-alpha-6}@anchor{1887}
@subsection Python 3.14.0 alpha 6


`Release date: 2025-03-14'

@menu
* macOS: macOS<5>. 
* Windows: Windows<11>. 
* Tools/Demos: Tools/Demos<10>. 
* テスト: テスト<8>. 
* セキュリティ: セキュリティ<12>. 
* ライブラリ: ライブラリ<30>. 
* ドキュメント: ドキュメント<10>. 
* Core and Builtins: Core and Builtins<27>. 
* ライブラリ: ライブラリ<31>. 
* Core and Builtins: Core and Builtins<28>. 
* ライブラリ: ライブラリ<32>. 
* Core and Builtins: Core and Builtins<29>. 
* C API: C API<10>. 
* ビルド: ビルド<10>. 

@end menu

@node macOS<5>,Windows<11>,,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id116}@anchor{1888}
@subsubsection macOS



@itemize -

@item 
gh-128540@footnote{https://github.com/python/cpython/issues/128540}: Ensure web browser is launched by @ref{1889,,webbrowser.open()} on
macOS, even for @code{file://} URLs.
@end itemize

@node Windows<11>,Tools/Demos<10>,macOS<5>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id117}@anchor{188a}
@subsubsection Windows



@itemize -

@item 
gh-131020@footnote{https://github.com/python/cpython/issues/131020}: pylauncher@footnote{https://github.com/python/cpython/tree/3.14/PC/launcher2.c} correctly detects a BOM
when searching for the shebang. Fix by Chris Eibl.
@end itemize

@node Tools/Demos<10>,テスト<8>,Windows<11>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id118}@anchor{188b}
@subsubsection Tools/Demos



@itemize -

@item 
gh-130453@footnote{https://github.com/python/cpython/issues/130453}: Make it possible to override default keywords in
@code{pygettext}.

@item 
gh-85012@footnote{https://github.com/python/cpython/issues/85012}: Correctly reset @code{msgctxt} when compiling messages in
@code{msgfmt}.

@item 
gh-130453@footnote{https://github.com/python/cpython/issues/130453}: Extend support for specifying custom keywords in
@code{pygettext}.

@item 
gh-130195@footnote{https://github.com/python/cpython/issues/130195}: Add warning messages when @code{pygettext} unimplemented
@code{-a/--extract-all} option is called.

@item 
gh-130057@footnote{https://github.com/python/cpython/issues/130057}: Add support for translator comments in @code{pygettext.py}.

@item 
gh-130025@footnote{https://github.com/python/cpython/issues/130025}: The iOS testbed now correctly handles symlinks used as Python
framework references.

@item 
gh-129911@footnote{https://github.com/python/cpython/issues/129911}: Fix the keyword entry in the help output of
@code{pygettext}.
@end itemize

@node テスト<8>,セキュリティ<12>,Tools/Demos<10>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id119}@anchor{188c}
@subsubsection テスト



@itemize -

@item 
gh-129200@footnote{https://github.com/python/cpython/issues/129200}: Multiple iOS testbed runners can now be started at the same
time without introducing an ambiguity over simulator ownership.

@item 
gh-130292@footnote{https://github.com/python/cpython/issues/130292}: The iOS testbed will now run successfully on a machine that has
not previously run Xcode tests (such as CI configurations).

@item 
gh-130293@footnote{https://github.com/python/cpython/issues/130293}: The tests of terminal colorization are no longer sensitive to
the value of the @code{TERM} variable in the testing environment.

@item 
gh-129401@footnote{https://github.com/python/cpython/issues/129401}: Fix a flaky test in @code{test_repr_rlock} that checks the
representation of @ref{1854,,multiprocessing.RLock}.

@item 
gh-126332@footnote{https://github.com/python/cpython/issues/126332}: Add unit tests for pyrepl.
@end itemize

@node セキュリティ<12>,ライブラリ<30>,テスト<8>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id120}@anchor{188d}
@subsubsection セキュリティ



@itemize -

@item 
gh-127371@footnote{https://github.com/python/cpython/issues/127371}: Avoid unbounded buffering for
@code{tempfile.SpooledTemporaryFile.writelines()}. Previously, disk
spillover was only checked after the lines iterator had been exhausted.
This is now done after each line is written.
@end itemize

@node ライブラリ<30>,ドキュメント<10>,セキュリティ<12>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id121}@anchor{188e}
@subsubsection ライブラリ



@itemize -

@item 
gh-131204@footnote{https://github.com/python/cpython/issues/131204}: Use monospace font from System Font Stack for cross-platform
support in @ref{201,,difflib.HtmlDiff}.

@item 
gh-131196@footnote{https://github.com/python/cpython/issues/131196}: Improve performance of @ref{188f,,uuid.UUID.hex} and
@ref{830,,uuid.UUID.__str__}.

@item 
gh-130940@footnote{https://github.com/python/cpython/issues/130940}: The behavior of @code{PyConfig.use_system_logger} was modified to
be enabled by default on iOS. It remains disabled by default on macOS.

@item 
gh-131123@footnote{https://github.com/python/cpython/issues/131123}: Supported completions for attributes of convenience variables
in @ref{aa,,pdb}.

@item 
gh-93096@footnote{https://github.com/python/cpython/issues/93096}: Removed undocumented CLI @code{python -m difflib}. Use @code{python -m
doctest Lib/difflib.py -v} instead. Patch by Semyon Moroz.

@item 
gh-93096@footnote{https://github.com/python/cpython/issues/93096}: Removed undocumented @code{-t} and @code{-v} arguments of @code{python -m
pickle}. Use @code{python -m doctest Lib/pickle.py -v} instead. Patch by
Semyon Moroz.

@item 
gh-81267@footnote{https://github.com/python/cpython/issues/81267}: Correct @ref{8ac,,time.sleep()} error message when an object that
cannot be interpreted as an integer or float is provided.

@item 
gh-93096@footnote{https://github.com/python/cpython/issues/93096}: Removed undocumented @code{-t} and @code{-v} arguments of @code{python -m
pickletools}. Use @code{python -m doctest Lib/pickletools.py -v} instead.
Patch by Semyon Moroz.

@item 
gh-131045@footnote{https://github.com/python/cpython/issues/131045}: Fix issue with @code{__contains__}, values, and pseudo-members for
@ref{835,,enum.Flag}.

@item 
gh-130959@footnote{https://github.com/python/cpython/issues/130959}: Fix pure-Python implementation of
@ref{829,,datetime.time.fromisoformat()} to reject times with spaces in
fractional part (for example, @code{12:34:56.400 +02:00}), matching the C
implementation. Patch by Michał Gorny.

@item 
gh-130806@footnote{https://github.com/python/cpython/issues/130806}: Deleting @ref{65c,,gzip.GzipFile} before it is closed now emits a
@ref{54c,,ResourceWarning}.

@item 
gh-130637@footnote{https://github.com/python/cpython/issues/130637}: Add validation for numeric response data in poplib.POP3.stat()
method

@item 
gh-130665@footnote{https://github.com/python/cpython/issues/130665}: Only apply locale to @ref{1d0,,calendar CLI} when
set via @code{--locale} and not via @code{LANG} environment variable.

@item 
gh-130660@footnote{https://github.com/python/cpython/issues/130660}: @code{sys.ps1} and @code{sys.ps2} are now restored after
@ref{1890,,code.interact()} call.

@item 
gh-130608@footnote{https://github.com/python/cpython/issues/130608}: Remove `dirs_exist_ok' argument from @ref{267,,pathlib.Path.copy()}
and @ref{268,,copy_into()}. These methods are new in Python 3.14.

@item 
gh-130461@footnote{https://github.com/python/cpython/issues/130461}: Remove @code{.. index::} directives from the @ref{116,,uuid} module
documentation. These directives previously created entries in the general
index for @ref{da0,,getnode()} as well as the @ref{da1,,uuid1()},
@ref{2e5,,uuid3()}, @ref{2e7,,uuid4()}, @ref{2e6,,uuid5()}, and
@ref{2c4,,uuid8()} constructor functions.

@item 
gh-130379@footnote{https://github.com/python/cpython/issues/130379}: The zipapp module now calculates the list of files to be added
to the archive before creating the archive. This avoids accidentally
including the target when it is being created in the source directory.

@item 
gh-82987@footnote{https://github.com/python/cpython/issues/82987}: Inline breakpoints like @ref{271,,breakpoint()} or
@ref{272,,pdb.set_trace()} will always stop the program at calling frame,
ignoring the @code{skip} pattern (if any).

@item 
gh-125377@footnote{https://github.com/python/cpython/issues/125377}: @code{<tab>} at the beginning of the line in @ref{aa,,pdb} multi-line
input will fill in a 4-space indentation now, instead of inserting a
@code{\t} character.

@item 
gh-125413@footnote{https://github.com/python/cpython/issues/125413}: Ensure the path returned from @ref{267,,pathlib.Path.copy()} or
@ref{269,,move()} has fresh @ref{26b,,info}.

@item 
gh-65697@footnote{https://github.com/python/cpython/issues/65697}: stdlib configparser will now attempt to validate that keys it
writes will not result in file corruption (creating a file unable to be
accurately parsed by a future read() call from the same parser).
Attempting a corrupting write() will raise an InvalidWriteError.

@item 
gh-125413@footnote{https://github.com/python/cpython/issues/125413}: Speed up @ref{267,,Path.copy} by making better
use of @ref{26b,,info} internally.

@item 
gh-130285@footnote{https://github.com/python/cpython/issues/130285}: Fix corner case for @ref{94d,,random.sample()} allowing the `counts'
parameter to specify an empty population. So now, @code{sample([], 0,
counts=[])} and @code{sample('abc', k=0, counts=[0, 0, 0])} both give the
same result as @code{sample([], 0)}.

@item 
gh-124703@footnote{https://github.com/python/cpython/issues/124703}: Executing @code{quit} command in @ref{aa,,pdb} will raise
@ref{278,,bdb.BdbQuit} when @ref{aa,,pdb} is started from an interactive console
using @ref{271,,breakpoint()} or @ref{272,,pdb.set_trace()}.

@item 
gh-107773@footnote{https://github.com/python/cpython/issues/107773}: Make @ref{34,,datetime} subclass @ref{82f,,__repr__()}
consistent both implementations. Patch by Semyon Moroz.

@item 
gh-130250@footnote{https://github.com/python/cpython/issues/130250}: Fix regression in @code{traceback.print_last()}.

@item 
gh-123471@footnote{https://github.com/python/cpython/issues/123471}: Make concurrent iterations over @ref{511,,itertools.batched} safe
under free-threading.

@item 
gh-57537@footnote{https://github.com/python/cpython/issues/57537}: Support breakpoints for @ref{138,,zipimport} modules on @ref{aa,,pdb}

@item 
gh-130230@footnote{https://github.com/python/cpython/issues/130230}: Fix crash in @ref{1a4,,pow()} with only @ref{1fe,,Decimal}
third argument.

@item 
gh-126944@footnote{https://github.com/python/cpython/issues/126944}: Show explicit errors when required arguments of @ref{aa,,pdb}
commands are missing

@item 
gh-127750@footnote{https://github.com/python/cpython/issues/127750}: Improve repr of @ref{be5,,functools.singledispatchmethod} methods
and descriptors.

@item 
gh-128520@footnote{https://github.com/python/cpython/issues/128520}: Apply type conversion consistently in @ref{6cd,,pathlib.PurePath}
and @ref{266,,Path} methods can accept a path object as an
argument, such as @ref{6d3,,match()} and
@ref{1891,,rename()}. The argument is now converted to path object
if it lacks a @ref{6ce,,with_segments()} attribute, and not
otherwise.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Reverts a change in the previous release attempting to make
some stdlib imports used within the @ref{dc,,subprocess} module lazy as this
was causing errors during @code{__del__} finalizers calling methods such as
@code{terminate}, or @code{kill}, or @code{send_signal}.

@item 
gh-130164@footnote{https://github.com/python/cpython/issues/130164}: Fixed failure to raise @ref{198,,TypeError} in
@ref{1892,,inspect.Signature.bind()} for positional-only arguments provided by
keyword when a variadic keyword argument (e.g. @code{**kwargs}) is present.

@item 
gh-130151@footnote{https://github.com/python/cpython/issues/130151}: Fix reference leaks in @code{_hashlib.hmac_new()} and
@code{_hashlib.hmac_digest()}. Patch by Bénédikt Tran.

@item 
gh-130145@footnote{https://github.com/python/cpython/issues/130145}: Fix @code{asyncio.AbstractEventloop.run_forever()} when another
loop is already running.

@item 
gh-130139@footnote{https://github.com/python/cpython/issues/130139}: Fix bug where @ref{1c2,,ast.parse()} did not error on AST input
which is not of the correct type, when called with optimize=False.

@item 
gh-127260@footnote{https://github.com/python/cpython/issues/127260}: Forbid the use of colon (":") as a fractional component
separator and other improvements to the consistency of error raising
between the C and Python implementations of
@ref{829,,datetime.time.fromisoformat()} and
@ref{82a,,datetime.datetime.fromisoformat()}. Patch by Semyon Moroz.

@item 
gh-85795@footnote{https://github.com/python/cpython/issues/85795}: Using @ref{1a6,,super()} and @code{__class__} @ref{1893,,closure variable}
in user-defined methods of @ref{331,,typing.NamedTuple} subclasses is now
explicitly prohibited at runtime. Contributed by Bartosz Sławecki in
gh-130082@footnote{https://github.com/python/cpython/issues/130082}.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import time of @ref{1a,,cmd} by lazy importing
@ref{82,,inspect} and removing @ref{d8,,string}. Patch by Semyon Moroz.

@item 
gh-129726@footnote{https://github.com/python/cpython/issues/129726}: Fix @ref{65c,,gzip.GzipFile} raising an unraisable exception
during garbage collection when referring to a temporary object by breaking
the reference loop with @ref{11a,,weakref}.

@item 
gh-127750@footnote{https://github.com/python/cpython/issues/127750}: Remove broken @ref{be5,,functools.singledispatchmethod()} caching
introduced in gh-85160@footnote{https://github.com/python/cpython/issues/85160}. Achieve the same performance using different
optimization.

@item 
gh-129948@footnote{https://github.com/python/cpython/issues/129948}: Add support for shared @ref{184,,set} to
@ref{1894,,multiprocessing.managers.SyncManager} via @ref{24f,,SyncManager.set()}.

@item 
gh-129965@footnote{https://github.com/python/cpython/issues/129965}: Update MIME types for @code{.avi} and @code{.wav}. Add MIME types for
@code{.docx}, @code{.pptx}, @code{.xlsx}, @code{.epub}, @code{.flac}, @code{.m4a}, @code{.odg},
@code{.odp}, @code{.ods}, @code{.odt}, @code{.oga}, @code{.ogg}, @code{.ogx} and @code{.weba}.
Patch by Hugo van Kemenade.

@item 
gh-129889@footnote{https://github.com/python/cpython/issues/129889}: Support context manager protocol by @ref{1e2,,contextvars.Token}.
Patch by Andrew Svetlov.

@item 
gh-97850@footnote{https://github.com/python/cpython/issues/97850}: Update the deprecation warning of
@ref{a69,,importlib.abc.Loader.load_module()}.

@item 
gh-129678@footnote{https://github.com/python/cpython/issues/129678}: @ref{4de,,configparser.ConfigParser}: do not write an empty
unnamed section

@item 
gh-128641@footnote{https://github.com/python/cpython/issues/128641}: Restore @ref{1681,,configparser.ConfigParser.read()} performance.

@item 
gh-129569@footnote{https://github.com/python/cpython/issues/129569}: Fix @ref{8e4,,unicodedata.normalize()} to always return a built-in
@ref{169,,str} object when given an input of a @ref{169,,str} subclass,
regardless of whether the string is already normalized.

@item 
gh-128231@footnote{https://github.com/python/cpython/issues/128231}: Execution of multiple statements in the new REPL now stops
immediately upon the first exception encountered. Patch by Bartosz
Sławecki.

@item 
gh-96092@footnote{https://github.com/python/cpython/issues/96092}: Fix bug in @ref{1081,,traceback.walk_stack()} called with None where
it was skipping more frames than in prior versions. This bug fix also
changes walk_stack to walk the stack in the frame where it was called
rather than where it first gets used.

@item 
gh-129288@footnote{https://github.com/python/cpython/issues/129288}: Add optional @code{l2_cid} and @code{l2_bdaddr_type} fields to
@ref{d1,,socket} @code{BTPROTO_L2CAP} sockaddr tuple.

@item 
gh-128703@footnote{https://github.com/python/cpython/issues/128703}: Fix @ref{517,,mimetypes.guess_type()} to use default mapping for
empty @code{Content-Type} in registry.

@item 
gh-128647@footnote{https://github.com/python/cpython/issues/128647}: Eagerly write to buffers passed to @ref{65c,,gzip.GzipFile}'s
@ref{1895,,readinto()} and
@ref{101c,,readinto1()} implementations, avoiding unnecessary
allocations. Patch by Chris Markiewicz.

@item 
gh-128184@footnote{https://github.com/python/cpython/issues/128184}: Improve display of @ref{1776,,annotationlib.ForwardRef} object
within @ref{4e3,,inspect.Signature} representations. This also fixes a
@ref{452,,NameError} that was raised when using @ref{4e1,,dataclasses.dataclass()}
on classes with unresolvable forward references.

@item 
gh-128041@footnote{https://github.com/python/cpython/issues/128041}: Add
@ref{1da,,concurrent.futures.ProcessPoolExecutor.terminate_workers()} and
@ref{1db,,concurrent.futures.ProcessPoolExecutor.kill_workers()} as ways to
terminate or kill all living worker processes in the given pool.
(Contributed by Charles Machalow in gh-130849@footnote{https://github.com/python/cpython/issues/130849}.)

@item 
gh-127647@footnote{https://github.com/python/cpython/issues/127647}: Add protocols @ref{236,,io.Reader} and @ref{237,,io.Writer} as
alternatives to @ref{238,,typing.IO}, @ref{239,,typing.TextIO}, and
@ref{23a,,typing.BinaryIO}.

@item 
gh-109798@footnote{https://github.com/python/cpython/issues/109798}: Added additional information into error messages in
@ref{34,,datetime}, and made the messages more consistent between the C and
Python implementations. Patch by Semyon Moroz.

@item 
gh-125746@footnote{https://github.com/python/cpython/issues/125746}: Delay deprecated @ref{338,,zipimport.zipimporter.load_module()}
removal time to 3.15. Use @ref{339,,zipimport.zipimporter.exec_module()}
instead.

@item 
gh-74028@footnote{https://github.com/python/cpython/issues/74028}: Add the optional @code{buffersize} parameter to
@ref{1dc,,concurrent.futures.Executor.map()} to limit the number of submitted
tasks whose results have not yet been yielded. If the buffer is full,
iteration over the `iterables' pauses until a result is yielded from the
buffer.

@item 
gh-124927@footnote{https://github.com/python/cpython/issues/124927}: Non-printing characters are now properly handled in the new
REPL.

@item 
gh-124096@footnote{https://github.com/python/cpython/issues/124096}: Turn on virtual terminal mode and enable bracketed paste in
REPL on Windows console. (If the terminal does not support bracketed
paste, enabling it does nothing.)

@item 
gh-89083@footnote{https://github.com/python/cpython/issues/89083}: Add @ref{2c3,,uuid.uuid7()} for generating UUIDv7 objects as
specified in 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}. Patch by Bénédikt Tran.

@item 
gh-89083@footnote{https://github.com/python/cpython/issues/89083}: Add @ref{2c2,,uuid.uuid6()} for generating UUIDv6 objects as
specified in 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}. Patch by Bénédikt Tran.

@item 
gh-117151@footnote{https://github.com/python/cpython/issues/117151}: Increase @code{io.DEFAULT_BUFFER_SIZE} from 8k to 128k and adjust
@ref{316,,open()} on platforms where @ref{f8c,,os.fstat()} provides a @code{st_blksize}
field (such as Linux) to use @code{max(min(blocksize, 8 MiB),
io.DEFAULT_BUFFER_SIZE)} rather than always using the device block size.
This should improve I/O performance. Patch by Romain Morotti.

@item 
gh-105499@footnote{https://github.com/python/cpython/issues/105499}: Make @ref{2a7,,types.UnionType} an alias for
@ref{2a8,,typing.Union}. Both @code{int | str} and @code{Union[int, str]} now
create instances of the same type. Patch by Jelle Zijlstra.

@item 
gh-93096@footnote{https://github.com/python/cpython/issues/93096}: Document the command-line for @ref{93,,mimetypes}. It now exits
with @code{1} on failure instead of @code{0} and @code{2} on incorrect command-line
parameters instead of @code{1}. Also, errors are printed to stderr instead of
stdout and their text is made tighter. Patch by Oleg Iarygin and Hugo van
Kemenade.
@end itemize

@node ドキュメント<10>,Core and Builtins<27>,ライブラリ<30>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id122}@anchor{1896}
@subsubsection ドキュメント



@itemize -

@item 
gh-125722@footnote{https://github.com/python/cpython/issues/125722}: Require Sphinx 8.2.0 or later to build the Python
documentation. Patch by Adam Turner.

@item 
gh-129712@footnote{https://github.com/python/cpython/issues/129712}: The wheel tags supported by each macOS universal SDK option are
now documented.

@item 
gh-46236@footnote{https://github.com/python/cpython/issues/46236}: C API: Document @ref{1897,,PyUnicode_RSplit()},
@ref{1898,,PyUnicode_Partition()} and @ref{1899,,PyUnicode_RPartition()}.
@end itemize

@node Core and Builtins<27>,ライブラリ<31>,ドキュメント<10>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id123}@anchor{189a}
@subsubsection Core and Builtins



@itemize -

@item 
gh-131141@footnote{https://github.com/python/cpython/issues/131141}: Fix data race in @ref{e0,,sys.monitoring} instrumentation while
registering callback.

@item 
gh-130804@footnote{https://github.com/python/cpython/issues/130804}: Fix support of unicode characters on Windows in the new REPL.

@item 
gh-130932@footnote{https://github.com/python/cpython/issues/130932}: Fix incorrect exception handling in
@code{_PyModule_IsPossiblyShadowing}

@item 
gh-122029@footnote{https://github.com/python/cpython/issues/122029}: @ref{1717,,sys.setprofile()} and @ref{2e1,,sys.settrace()} will not
generate a @code{c_call} event for @code{INSTRUMENTED_CALL_FUNCTION_EX} if the
callable is a method with a C function wrapped, because we do not generate
@code{c_return} event in such case.

@item 
gh-129964@footnote{https://github.com/python/cpython/issues/129964}: Fix JIT crash on Windows on Arm. Patch by Diego Russo and
Brandt Bucher.

@item 
gh-130851@footnote{https://github.com/python/cpython/issues/130851}: Fix a crash in the @ref{1f4,,free threading} build when
constructing a @ref{1b,,code} object with @ref{189b,,co_consts}
that contains instances of types that are not otherwise generated by the
bytecode compiler.

@item 
gh-128534@footnote{https://github.com/python/cpython/issues/128534}: Ensure that both left and right branches have the same source
for @code{async for} loops. Add these branches to the @code{co_branches()}
iterator.

@item 
gh-130794@footnote{https://github.com/python/cpython/issues/130794}: Fix memory leak in the @ref{1f4,,free threaded}
build when resizing a shared list or dictionary from multiple short-lived
threads.

@item 
gh-130415@footnote{https://github.com/python/cpython/issues/130415}: Improve JIT understanding of integers in boolean context.

@item 
gh-130382@footnote{https://github.com/python/cpython/issues/130382}: Fix @code{PyRefTracer_DESTROY} not being sent from
@code{Python/ceval.c} @code{Py_DECREF()}.

@item 
gh-130574@footnote{https://github.com/python/cpython/issues/130574}: Renumber @ref{5bb,,RESUME} from 149 to 128.

@item 
gh-124878@footnote{https://github.com/python/cpython/issues/124878}: Fix race conditions during runtime finalization that could lead
to accessing freed memory.

@item 
gh-130415@footnote{https://github.com/python/cpython/issues/130415}: Improve the experimental JIT's ability to narrow boolean values
based on the results of truthiness tests.

@item 
gh-130618@footnote{https://github.com/python/cpython/issues/130618}: Fix a bug that was causing @code{UnicodeDecodeError} or
@code{SystemError} to be raised when using f-strings with @code{lambda}
expressions with non-ASCII characters. Patch by Pablo Galindo

@item 
gh-123044@footnote{https://github.com/python/cpython/issues/123044}: Make sure that the location of branch targets in @code{match}
cases is in the body, not the pattern.

@item 
gh-128534@footnote{https://github.com/python/cpython/issues/128534}: Add branch monitoring (@code{BRANCH_LEFT} and @code{BRANCH_RIGHT}
events) for @code{async for} loops.

@item 
gh-130163@footnote{https://github.com/python/cpython/issues/130163}: Fix possible crashes related to concurrent change and use of
the @ref{df,,sys} module attributes.

@item 
gh-122029@footnote{https://github.com/python/cpython/issues/122029}: @code{INSTRUMENTED_CALL_KW} will expand the method before
monitoring to reflect the actual behavior more accurately.

@item 
gh-130415@footnote{https://github.com/python/cpython/issues/130415}: Improve JIT's ability to optimize strings in boolean contexts.

@item 
gh-130396@footnote{https://github.com/python/cpython/issues/130396}: Use actual stack limits (from
@code{pthread_getattr_np(3)@footnote{https://manpages.debian.org/pthread_getattr_np(3)}}) for linux, and other systems with
@code{_GNU_SOURCE} defined, when determining limits for C stack protection.

@item 
gh-128396@footnote{https://github.com/python/cpython/issues/128396}: Fix a crash that occurs when calling @ref{46f,,locals()} inside an
inline comprehension that uses the same local variable as the outer frame
scope where the variable is a free or cell var.

@item 
gh-129107@footnote{https://github.com/python/cpython/issues/129107}: Fix two more @ref{344,,bytearray} functions for @ref{1f4,,free threading}.

@item 
gh-127705@footnote{https://github.com/python/cpython/issues/127705}: Use tagged references (@code{_PyStackRef}) for the default build
as well as for the free-threading build. This has a small negative
performance impact short-term but will enable larger speedups in the
future and significantly reduce maintenance costs by allowing a single
implementation of tagged references in the future.

@item 
gh-130094@footnote{https://github.com/python/cpython/issues/130094}: Fix two race conditions involving concurrent imports that could
lead to spurious failures with @ref{d3d,,ModuleNotFoundError}.

@item 
gh-129107@footnote{https://github.com/python/cpython/issues/129107}: Make @ref{344,,bytearray} iterator safe under @ref{1f4,,free threading}.

@item 
gh-115802@footnote{https://github.com/python/cpython/issues/115802}: Use the more efficient "medium" code model for JIT-compiled
code on supported platforms.

@item 
gh-107956@footnote{https://github.com/python/cpython/issues/107956}: A @code{build-details.json} file is now install in the
platform-independent standard library directory (
@geindex Python Enhancement Proposals; PEP 739
PEP 739@footnote{https://peps.python.org/pep-0739/}
implementation).

@item 
gh-116042@footnote{https://github.com/python/cpython/issues/116042}: Fix location for SyntaxErrors of invalid escapes in the
tokenizer. Patch by Pablo Galindo

@item 
gh-91079@footnote{https://github.com/python/cpython/issues/91079}: Change C stack overflow protection to consider the amount of
stack consumed, rather than a counter. This allows deeper recursion in
many cases, but remains safe.

@item 
gh-129715@footnote{https://github.com/python/cpython/issues/129715}: Improve the experimental JIT's handling of returns to unknown
callers.
@end itemize

@node ライブラリ<31>,Core and Builtins<28>,Core and Builtins<27>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id124}@anchor{189c}
@subsubsection ライブラリ



@itemize -

@item 
gh-129983@footnote{https://github.com/python/cpython/issues/129983}: Fix data race in compile_template in @code{sre.c}.
@end itemize

@node Core and Builtins<28>,ライブラリ<32>,ライブラリ<31>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id125}@anchor{189d}
@subsubsection Core and Builtins



@itemize -

@item 
gh-129967@footnote{https://github.com/python/cpython/issues/129967}: Fix a race condition in the @ref{1f4,,free threading} build when
@code{repr(set)} is called concurrently with @code{set.clear()}.

@item 
gh-129953@footnote{https://github.com/python/cpython/issues/129953}: The internal (evaluation) stack is now spilled to memory
whenever execution escapes from the interpreter or JIT compiled code. This
should have no observable effect in either Python or builtin extensions,
but will allow various important optimizations in the future.

@item 
gh-129515@footnote{https://github.com/python/cpython/issues/129515}: Clarify syntax error messages for conditional expressions when
a statement is specified before an @ref{181,,if} or after an
@ref{17c,,else} keyword.

@item 
gh-129349@footnote{https://github.com/python/cpython/issues/129349}: @ref{190,,bytes.fromhex()} and @ref{191,,bytearray.fromhex()} now accepts
ASCII @ref{192,,bytes} and @ref{193,,bytes-like objects}.

@item 
gh-129149@footnote{https://github.com/python/cpython/issues/129149}: Add fast path for medium-size integers in
@ref{189e,,PyLong_FromSsize_t()}. Patch by Chris Eibl.

@item 
gh-129107@footnote{https://github.com/python/cpython/issues/129107}: Make the @ref{344,,bytearray} safe under @ref{1f4,,free threading}.

@item 
gh-128974@footnote{https://github.com/python/cpython/issues/128974}: Fix a crash in @ref{830,,UnicodeError.__str__}
when custom attributes implement @ref{830,,__str__()} with
side-effects. Patch by Bénédikt Tran.

@item 
gh-126085@footnote{https://github.com/python/cpython/issues/126085}: @ref{2ae,,typing.TypeAliasType} now supports star unpacking.

@item 
gh-125331@footnote{https://github.com/python/cpython/issues/125331}: @code{from __future__ import barry_as_FLUFL} now works in more
contexts, including when it is used in files, with the @code{-c} flag, and in
the REPL when there are multiple statements on the same line. Previously,
it worked only on subsequent lines in the REPL, and when the appropriate
flags were passed directly to @ref{4b1,,compile()}. Patch by Pablo Galindo.

@item 
gh-121464@footnote{https://github.com/python/cpython/issues/121464}: Make concurrent iterations over the same @ref{169a,,enumerate()}
iterator safe under free-threading. See Strategy for Iterators in Free Threading@footnote{https://github.com/python/cpython/issues/124397}.

@item 
gh-87790@footnote{https://github.com/python/cpython/issues/87790}: Support underscore and comma as thousands separators in the
fractional part for floating-point presentation types of the new-style
string formatting (with @ref{199,,format()} or @ref{19a,,f-strings}).  Patch by
Sergey B Kirpichev.

@item 
gh-124445@footnote{https://github.com/python/cpython/issues/124445}: Fix specialization of generic aliases that are generic over a
@ref{487,,typing.ParamSpec} and have been specialized with a nested type
variable.

@item 
gh-120608@footnote{https://github.com/python/cpython/issues/120608}: Adapt @ref{a65,,reversed()} for use in the free-threading build. The
@ref{a65,,reversed()} is still not thread-safe in the sense that concurrent
iterations may see the same object, but they will not corrupt the
interpreter state.
@end itemize

@node ライブラリ<32>,Core and Builtins<29>,Core and Builtins<28>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id126}@anchor{189f}
@subsubsection ライブラリ



@itemize -

@item 
gh-100388@footnote{https://github.com/python/cpython/issues/100388}: Fix the @code{platform._sys_version()} method when @code{__DATE__} is
undefined at buildtime by changing default buildtime datetime string to
the UNIX epoch.
@end itemize

@node Core and Builtins<29>,C API<10>,ライブラリ<32>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id127}@anchor{18a0}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44369}: Improve syntax errors for incorrectly closed strings. Patch by
Pablo Galindo
@end itemize

@node C API<10>,ビルド<10>,Core and Builtins<29>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id128}@anchor{18a1}
@subsubsection C API



@itemize -

@item 
gh-111178@footnote{https://github.com/python/cpython/issues/111178}: Fix @ref{968,,PyCMethod} API: replace @code{size_t nargs} with
@code{Py_ssize_t nargs} in @ref{968,,PyCMethod}. Patch by Victor Stinner.

@item 
gh-130947@footnote{https://github.com/python/cpython/issues/130947}: Add again @ref{18a2,,PySequence_Fast()} to the limited C API. Patch
by Victor Stinner.

@item 
gh-128863@footnote{https://github.com/python/cpython/issues/128863}: The following private functions are deprecated and planned for
removal in Python 3.18:


@itemize *

@item 
@code{_PyUnicodeWriter_Init()}:
replace @code{_PyUnicodeWriter_Init(&writer)} with
@ref{3b4,,writer = PyUnicodeWriter_Create(0)}.

@item 
@code{_PyUnicodeWriter_Finish()}:
replace @code{_PyUnicodeWriter_Finish(&writer)} with
@ref{3b7,,PyUnicodeWriter_Finish(writer)}.

@item 
@code{_PyUnicodeWriter_Dealloc()}:
replace @code{_PyUnicodeWriter_Dealloc(&writer)} with
@ref{3b6,,PyUnicodeWriter_Discard(writer)}.

@item 
@code{_PyUnicodeWriter_WriteChar()}:
replace @code{_PyUnicodeWriter_WriteChar(&writer, ch)} with
@ref{3ba,,PyUnicodeWriter_WriteChar(writer@comma{} ch)}.

@item 
@code{_PyUnicodeWriter_WriteStr()}:
replace @code{_PyUnicodeWriter_WriteStr(&writer, str)} with
@ref{3bc,,PyUnicodeWriter_WriteStr(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteSubstring()}:
replace @code{_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)} with
@ref{3bd,,PyUnicodeWriter_WriteSubstring(writer@comma{} str@comma{} start@comma{} end)}.

@item 
@code{_PyUnicodeWriter_WriteASCIIString()}:
replace @code{_PyUnicodeWriter_WriteASCIIString(&writer, str)} with
@ref{3bf,,PyUnicodeWriter_WriteUTF8(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteLatin1String()}:
replace @code{_PyUnicodeWriter_WriteLatin1String(&writer, str)} with
@ref{3bf,,PyUnicodeWriter_WriteUTF8(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_Prepare()}: (no replacement).

@item 
@code{_PyUnicodeWriter_PrepareKind()}: (no replacement).
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get these
new public functions on Python 3.13 and older.

Patch by Victor Stinner.

@item 
gh-45325@footnote{https://github.com/python/cpython/issues/45325}: Add a new @code{p} format parameter to @ref{3c2,,Py_BuildValue()} that
allows to take a C integer and produce a Python @ref{3c3,,bool} object.
Patch by Pablo Galindo.
@end itemize

@node ビルド<10>,,C API<10>,Python 3 14 0 alpha 6
@anchor{whatsnew/changelog id129}@anchor{18a3}
@subsubsection ビルド



@itemize -

@item 
gh-131035@footnote{https://github.com/python/cpython/issues/131035}: Use @code{-flto=thin} for faster build times using clang-cl on
Windows. Patch by Chris Eibl.

@item 
gh-130740@footnote{https://github.com/python/cpython/issues/130740}: Ensure that @code{Python.h} is included before @code{stdbool.h}
unless @code{pyconfig.h} is included before or in some platform-specific
contexts.

@item 
gh-130090@footnote{https://github.com/python/cpython/issues/130090}: Building with @code{PlatformToolset=ClangCL} on Windows now
supports PGO (profile guided optimization). Patch by Chris Eibl with
invaluable support from Steve Dover.

@item 
gh-129819@footnote{https://github.com/python/cpython/issues/129819}: Allow building the JIT with the tailcall interpreter.

@item 
gh-129989@footnote{https://github.com/python/cpython/issues/129989}: Fix a bug where the tailcall interpreter was enabled when
@code{--without-tail-call-interp} was provided to the configure script.

@item 
gh-129838@footnote{https://github.com/python/cpython/issues/129838}: Don't redefine @code{_Py_NO_SANITIZE_UNDEFINED} when compiling
with a recent GCC version and undefined sanitizer enabled.

@item 
gh-82909@footnote{https://github.com/python/cpython/issues/82909}: @code{#pragma}-based linking with @code{python3*.lib} can now be
switched off with @ref{444,,Py_NO_LINK_LIB}. Patch by Jean-Christophe
Fillion-Robin.
@end itemize

@node Python 3 14 0 alpha 5,Python 3 14 0 alpha 4,Python 3 14 0 alpha 6,変更履歴
@anchor{whatsnew/changelog python-3-14-0-alpha-5}@anchor{18a4}
@subsection Python 3.14.0 alpha 5


`Release date: 2025-02-11'

@menu
* macOS: macOS<6>. 
* Tools/Demos: Tools/Demos<11>. 
* テスト: テスト<9>. 
* セキュリティ: セキュリティ<13>. 
* ライブラリ: ライブラリ<33>. 
* IDLE: IDLE<6>. 
* ドキュメント: ドキュメント<11>. 
* Core and Builtins: Core and Builtins<30>. 
* ライブラリ: ライブラリ<34>. 
* Core and Builtins: Core and Builtins<31>. 
* ライブラリ: ライブラリ<35>. 
* Core and Builtins: Core and Builtins<32>. 
* ライブラリ: ライブラリ<36>. 
* C API: C API<11>. 
* ビルド: ビルド<11>. 

@end menu

@node macOS<6>,Tools/Demos<11>,,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id130}@anchor{18a5}
@subsubsection macOS



@itemize -

@item 
gh-91132@footnote{https://github.com/python/cpython/issues/91132}: Update macOS installer to use ncurses 6.5.
@end itemize

@node Tools/Demos<11>,テスト<9>,macOS<6>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id131}@anchor{18a6}
@subsubsection Tools/Demos



@itemize -

@item 
gh-129248@footnote{https://github.com/python/cpython/issues/129248}: The iOS test runner now strips the log prefix from each line
output by the test suite.

@item 
gh-104400@footnote{https://github.com/python/cpython/issues/104400}: Fix several bugs in extraction by switching to an AST parser in
@code{pygettext}.
@end itemize

@node テスト<9>,セキュリティ<13>,Tools/Demos<11>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id132}@anchor{18a7}
@subsubsection テスト



@itemize -

@item 
gh-129386@footnote{https://github.com/python/cpython/issues/129386}: Add @code{test.support.reset_code}, which can be used to reset
various bytecode-level optimizations and local instrumentation for a
function.

@item 
gh-128474@footnote{https://github.com/python/cpython/issues/128474}: Disable @code{test_embed} test cases that segfault on BOLT
instrument binaries. The tests are only disabled when BOLT is enabled.

@item 
gh-128003@footnote{https://github.com/python/cpython/issues/128003}: Add an option @code{--parallel-threads=N} to the regression test
runner that runs individual tests in multiple threads in parallel in order
to find concurrency bugs.  Note that most of the test suite is not yet
reviewed for thread-safety or annotated with @code{@@thread_unsafe} when
necessary.
@end itemize

@node セキュリティ<13>,ライブラリ<33>,テスト<9>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id133}@anchor{18a8}
@subsubsection セキュリティ



@itemize -

@item 
gh-105704@footnote{https://github.com/python/cpython/issues/105704}: When using @ref{f3a,,urllib.parse.urlsplit()} and
@ref{362,,urllib.parse.urlparse()} host parsing would not reject domain names
containing square brackets (@code{[} and @code{]}). Square brackets are only
valid for IPv6 and IPvFuture hosts according to RFC 3986 Section 3.2.2@footnote{https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2}.

@item 
gh-126108@footnote{https://github.com/python/cpython/issues/126108}: Fix a possible @code{NULL} pointer dereference in
@code{PySys_AddWarnOptionUnicode()}.

@item 
gh-80222@footnote{https://github.com/python/cpython/issues/80222}: Fix bug in the folding of quoted strings when flattening an
email message using a modern email policy. Previously when a quoted string
was folded so that it spanned more than one line, the surrounding quotes
and internal escapes would be omitted. This could theoretically be used to
spoof header lines using a carefully constructed quoted string if the
resulting rendered email was transmitted or re-parsed.

@item 
gh-119511@footnote{https://github.com/python/cpython/issues/119511}: Fix a potential denial of service in the @ref{78,,imaplib} module.
When connecting to a malicious server, it could cause an arbitrary amount
of memory to be allocated. On many systems this is harmless as unused
virtual memory is only a mapping, but if this hit a virtual address size
limit it could lead to a @ref{179e,,MemoryError} or other process crash. On
unusual systems or builds where all allocated memory is touched and backed
by actual ram or storage it could've consumed resources doing so until
similarly crashing.
@end itemize

@node ライブラリ<33>,IDLE<6>,セキュリティ<13>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id134}@anchor{18a9}
@subsubsection ライブラリ



@itemize -

@item 
gh-129939@footnote{https://github.com/python/cpython/issues/129939}: Comparison pages with highlighted changes generated by the
@ref{201,,difflib.HtmlDiff} class now support dark mode.

@item 
gh-129928@footnote{https://github.com/python/cpython/issues/129928}: Raise @ref{305,,sqlite3.ProgrammingError} if a user-defined SQL
function with invalid number of parameters is created. Patch by Erlend
Aasland.

@item 
gh-129583@footnote{https://github.com/python/cpython/issues/129583}: Update bundled pip to 25.0.1

@item 
gh-129766@footnote{https://github.com/python/cpython/issues/129766}: Fix crash in @ref{118,,warnings}, when calling @code{_release_lock()}
with no existing lock.

@item 
gh-129005@footnote{https://github.com/python/cpython/issues/129005}: @code{_pyio.FileIO.readall()} now allocates, resizes, and fills a
data buffer using the same algorithm @code{_io.FileIO.readall()} uses.

@item 
gh-129646@footnote{https://github.com/python/cpython/issues/129646}: Update the locale alias mapping in the @ref{8a,,locale} module to
match the latest X Org locale alias mapping and support new locales in
Glibc 2.41.

@item 
gh-128317@footnote{https://github.com/python/cpython/issues/128317}: Put CLI calendar highlighting in private class, removing
@code{highlight_day} from public @ref{18aa,,calendar.TextCalendar} API. Patch by
Hugo van Kemenade.

@item 
gh-129603@footnote{https://github.com/python/cpython/issues/129603}: Fix bugs where @ref{1071,,sqlite3.Row} objects could segfault if
their inherited @ref{18ab,,description} was set to @code{None}.
Patch by Erlend Aasland.

@item 
gh-129559@footnote{https://github.com/python/cpython/issues/129559}: Add @ref{18ac,,bytearray.resize()} method so @ref{344,,bytearray} can
be efficiently resized in place.

@item 
gh-129502@footnote{https://github.com/python/cpython/issues/129502}: Unlikely errors in preparing arguments for @ref{2e,,ctypes}
callback are now handled in the same way as errors raised in the callback
of in converting the result of the callback -- using
@ref{507,,sys.unraisablehook()} instead of @ref{a0c,,sys.excepthook()} and not
setting @ref{6e5,,sys.last_exc} and other variables.

@item 
gh-129403@footnote{https://github.com/python/cpython/issues/129403}: Corrected @ref{2ec,,ValueError} message for
@ref{816,,asyncio.Barrier} and @ref{13fc,,threading.Barrier}.

@item 
gh-129409@footnote{https://github.com/python/cpython/issues/129409}: Fix an integer overflow in the @ref{2d,,csv} module when writing a
data field larger than 2GB.

@item 
gh-126400@footnote{https://github.com/python/cpython/issues/126400}: Add a socket `timeout' keyword argument to
@ref{86c,,logging.handlers.SysLogHandler}.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Always lazy import @code{warnings} in @ref{f3,,threading}. Patch by
Taneli Hukkinen.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import time of @ref{dc,,subprocess} by lazy importing
@code{locale} and @code{signal}. Patch by Taneli Hukkinen.

@item 
gh-129346@footnote{https://github.com/python/cpython/issues/129346}: In @ref{d4,,sqlite3}, handle out-of-memory when creating
user-defined SQL functions.

@item 
gh-129005@footnote{https://github.com/python/cpython/issues/129005}: Optimize @code{_pyio.FileIO.readinto} by avoiding unnecessary
objects and copies using @ref{25f,,os.readinto()}.

@item 
gh-129195@footnote{https://github.com/python/cpython/issues/129195}: Support reporting call graph information from
@code{asyncio.staggered.staggered_race()}.

@item 
gh-129205@footnote{https://github.com/python/cpython/issues/129205}: Add @ref{25f,,os.readinto()} to read into a @ref{260,,buffer object} from a file descriptor.

@item 
gh-128772@footnote{https://github.com/python/cpython/issues/128772}: Fix @ref{ba,,pydoc} for methods with the @code{__module__} attribute
equal to @code{None}.

@item 
gh-129061@footnote{https://github.com/python/cpython/issues/129061}: Fix FORCE_COLOR and NO_COLOR when empty strings. Patch by Hugo
van Kemenade.

@item 
gh-92897@footnote{https://github.com/python/cpython/issues/92897}: Scheduled the deprecation of the @code{check_home} argument of
@ref{32d,,sysconfig.is_python_build()} to Python 3.15.

@item 
gh-129064@footnote{https://github.com/python/cpython/issues/129064}: Deprecate @code{sysconfig.expand_makefile_vars()}, in favor of
using @ref{340,,sysconfig.get_paths()} with the @code{vars} argument.

@item 
gh-128550@footnote{https://github.com/python/cpython/issues/128550}: Removed an incorrect optimization relating to eager tasks in
@ref{4d1,,asyncio.TaskGroup} that resulted in cancellations being missed.

@item 
gh-128991@footnote{https://github.com/python/cpython/issues/128991}: Release the enter frame reference within @ref{10,,bdb} callback

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Reduce import time of @ref{b5,,pstats} and @ref{137,,zipfile} by up to
20%, by removing unnecessary imports to @ref{10a,,typing}. Patch by Bénédikt
Tran.

@item 
gh-128978@footnote{https://github.com/python/cpython/issues/128978}: Fix a @ref{452,,NameError} in
@code{sysconfig.expand_makefile_vars()}. Patch by Bénédikt Tran.

@item 
gh-128961@footnote{https://github.com/python/cpython/issues/128961}: Fix a crash when setting state on an exhausted
@ref{4be,,array.array} iterator.

@item 
gh-128894@footnote{https://github.com/python/cpython/issues/128894}: Fix @code{traceback.TracebackException._format_syntax_error} not
to fail on exceptions with custom metadata.

@item 
gh-128916@footnote{https://github.com/python/cpython/issues/128916}: Do not attempt to set @code{SO_REUSEPORT} on sockets of address
families other than @code{AF_INET} and @code{AF_INET6}, as it is meaningless
with these address families, and the call with fail with Linux kernel
6.12.9 and newer.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import time of @ref{102,,tomllib} by removing @code{typing},
@code{string}, and @code{tomllib._types} imports. Patch by Taneli Hukkinen.

@item 
gh-128679@footnote{https://github.com/python/cpython/issues/128679}: @ref{105,,tracemalloc}: Fix race conditions when
@ref{18ad,,tracemalloc.stop()} is called by a thread, while other threads are
tracing memory allocations. Patch by Victor Stinner.

@item 
gh-128891@footnote{https://github.com/python/cpython/issues/128891}: Add specialized opcodes to @code{opcode.opname}.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Reduce import time of @ref{67,,gettext} by up to ten times, by
importing @ref{be,,re} on demand. In particular, @code{re} is no longer
implicitly exposed as @code{gettext.re}. Patch by Eli Schwartz.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Reduce the import time of @ref{a4,,optparse} when no help text is
printed. Patch by Eli Schwartz.

@item 
gh-128657@footnote{https://github.com/python/cpython/issues/128657}: Fix possible extra reference when using objects returned by
@ref{18ae,,hashlib.sha256()} under @ref{1f4,,free threading}.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Reduce the import time of @ref{2d,,csv} by up to five times, by
importing @ref{be,,re} on demand. In particular, @code{re} is no more implicitly
exposed as @code{csv.re}. Patch by Bénédikt Tran.

@item 
gh-128308@footnote{https://github.com/python/cpython/issues/128308}: Support the `name' keyword argument for eager tasks in
@ref{1ca,,asyncio.loop.create_task()},  @ref{1c9,,asyncio.create_task()} and
@ref{1cb,,asyncio.TaskGroup.create_task()}, by passing on all `kwargs' to the
task factory set by @ref{1c8,,asyncio.loop.set_task_factory()}.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve the performance of @ref{2d3,,base64.b16decode()} by up to
ten times by more efficiently checking the byte-string for hexadecimal
digits. Reduce the import time of @ref{f,,base64} by up to six times, by no
longer importing @ref{be,,re}. Patch by Bénédikt Tran, Chris Markiewicz, and
Adam Turner.

@item 
gh-128156@footnote{https://github.com/python/cpython/issues/128156}: When using macOS system @code{libffi}, support for complex types
in @ref{2e,,ctypes} is now checked at runtime (macOS 10.15 or newer). The
types must also be available at build time.

@item 
gh-128636@footnote{https://github.com/python/cpython/issues/128636}: Fix PyREPL failure when @ref{259,,os.environ} is overwritten with
an invalid value.

@item 
gh-128498@footnote{https://github.com/python/cpython/issues/128498}: Default to stdout isatty for color detection instead of stderr.
Patch by Hugo van Kemenade.

@item 
gh-128384@footnote{https://github.com/python/cpython/issues/128384}: Add locking to @ref{118,,warnings} to avoid some data races when
free-threading is used.  Change @code{_warnings_runtime_state.mutex} to be a
recursive mutex and expose it to @ref{118,,warnings}, via the
@code{_acquire_lock()} and @code{_release_lock()} functions. The lock is
held when @code{filters} and @code{_filters_version} are updated.

@item 
gh-128509@footnote{https://github.com/python/cpython/issues/128509}: Add @ref{28f,,sys._is_immortal()} for identifying @ref{290,,immortal}
objects at runtime.

@item 
gh-128479@footnote{https://github.com/python/cpython/issues/128479}: Fix @code{asyncio.staggered.staggered_race()} leaking tasks and
issuing an unhandled exception.

@item 
gh-128427@footnote{https://github.com/python/cpython/issues/128427}: @ref{2c5,,uuid.NIL} and @ref{2c6,,uuid.MAX} are now available to
represent the Nil and Max UUID formats as defined by 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}.

@item 
gh-91279@footnote{https://github.com/python/cpython/issues/91279}: @ref{2cc,,zipfile.ZipFile.writestr()} now respect
@code{SOURCE_DATE_EPOCH} that distributions can set centrally and have build
tools consume this in order to produce reproducible output.

@item 
gh-112064@footnote{https://github.com/python/cpython/issues/112064}: Fix incorrect handling of negative read sizes in
@ref{18af,,HTTPResponse.read}. Patch by Yury
Manushkin.

@item 
gh-58956@footnote{https://github.com/python/cpython/issues/58956}: Fixed a frame reference leak in @ref{10,,bdb}.

@item 
gh-128131@footnote{https://github.com/python/cpython/issues/128131}: Completely support random access of uncompressed unencrypted
read-only zip files obtained by @ref{65d,,ZipFile.open}.

@item 
gh-127975@footnote{https://github.com/python/cpython/issues/127975}: Avoid reusing quote types in @ref{ae2,,ast.unparse()} if not needed.

@item 
gh-115514@footnote{https://github.com/python/cpython/issues/115514}: Fix exceptions and incomplete writes after
@code{asyncio._SelectorTransport} is closed before writes are
completed.

@item 
gh-121604@footnote{https://github.com/python/cpython/issues/121604}: Add missing Deprecation warnings for
@ref{18b0,,importlib.machinery.DEBUG_BYTECODE_SUFFIXES},
@ref{18b1,,importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES},
@ref{f26,,importlib.machinery.WindowsRegistryFinder},
@ref{de2,,importlib.abc.ResourceLoader},
@ref{13a2,,importlib.abc.SourceLoader.path_mtime()}.

@item 
gh-127873@footnote{https://github.com/python/cpython/issues/127873}: When @code{-E} is set, only ignore @code{PYTHON_COLORS} and not
@code{FORCE_COLOR}/@code{NO_COLOR}/@code{TERM} when colourising output. Patch by
Hugo van Kemenade.

@item 
gh-125413@footnote{https://github.com/python/cpython/issues/125413}: Add @ref{26b,,pathlib.Path.info} attribute, which stores an object
implementing the @ref{26c,,pathlib.types.PathInfo} protocol (also new). The
object supports querying the file type and internally caching
@ref{26d,,stat()} results. Path objects generated by
@ref{26e,,iterdir()} are initialized with file type information
gleaned from scanning the parent directory.

@item 
gh-127712@footnote{https://github.com/python/cpython/issues/127712}: Fix handling of the @code{secure} argument of
@ref{18b2,,logging.handlers.SMTPHandler}.

@item 
gh-127096@footnote{https://github.com/python/cpython/issues/127096}: Do not recreate unnamed section on every read in
@ref{4de,,configparser.ConfigParser}. Patch by Andrey Efremov.

@item 
gh-124369@footnote{https://github.com/python/cpython/issues/124369}: Deprecate @code{pdb.Pdb.curframe_locals}

@item 
gh-126332@footnote{https://github.com/python/cpython/issues/126332}: Fix _pyrepl crash when entering a double CTRL-Z on an
overflowing line.

@item 
gh-125553@footnote{https://github.com/python/cpython/issues/125553}: Fix round-trip invariance for backslash continuations in
@ref{18b3,,tokenize.untokenize()}.

@item 
gh-91048@footnote{https://github.com/python/cpython/issues/91048}: Add @ref{1cc,,asyncio.capture_call_graph()} and
@ref{1cd,,asyncio.print_call_graph()} functions.

@item 
gh-124703@footnote{https://github.com/python/cpython/issues/124703}: Quitting @ref{aa,,pdb} in @code{inline} mode will emit a confirmation
prompt and exit gracefully now, instead of printing an exception
traceback.

@item 
gh-123987@footnote{https://github.com/python/cpython/issues/123987}: Fixed issue in NamespaceReader where a non-path item in a
namespace path, such as a sentinel added by an editable installer, would
break resource loading.

@item 
gh-119349@footnote{https://github.com/python/cpython/issues/119349}: Add the @ref{1f0,,ctypes.util.dllist()} function to list the loaded
shared libraries for the current process.

@item 
gh-55454@footnote{https://github.com/python/cpython/issues/55454}: Add IMAP4 @code{IDLE} support to the @ref{78,,imaplib} module.  Patch
by Forest.

@item 
gh-119257@footnote{https://github.com/python/cpython/issues/119257}: Show tab completions menu below the current line, which results
in less janky behaviour, and fixes a cursor movement bug. Patch by Daniel
Hollas

@item 
gh-101410@footnote{https://github.com/python/cpython/issues/101410}: Support custom messages for domain errors in the @ref{92,,math}
module (@ref{bf9,,math.sqrt()}, @ref{16d9,,math.log()} and @ref{15f0,,math.atanh()} were
modified as examples).  Patch by Charlie Zhao and Sergey B Kirpichev.

@item 
gh-81340@footnote{https://github.com/python/cpython/issues/81340}: Use @ref{18b4,,os.copy_file_range()} in @ref{c4f,,shutil.copy()},
@ref{c50,,shutil.copy2()}, and @ref{c4e,,shutil.copyfile()} functions by default. An
underlying Linux system call gives filesystems an opportunity to implement
the use of copy-on-write (in case of btrfs and XFS) or server-side copy
(in the case of NFS.) Patch by Illia Volochii.

@item 
bpo-27307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27307}: Add attribute and item access support to
@ref{10bd,,string.Formatter} in auto-numbering mode, which allows format
strings like '@{.name@}' and '@{[1]@}'.
@end itemize

@node IDLE<6>,ドキュメント<11>,ライブラリ<33>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id135}@anchor{18b5}
@subsubsection IDLE



@itemize -

@item 
gh-129873@footnote{https://github.com/python/cpython/issues/129873}: Simplify displaying the IDLE doc by only copying the text
section of idle.html to idlelib/help.html. Patch by Stan Ulbrych.
@end itemize

@node ドキュメント<11>,Core and Builtins<30>,IDLE<6>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id136}@anchor{18b6}
@subsubsection ドキュメント



@itemize -

@item 
gh-125722@footnote{https://github.com/python/cpython/issues/125722}: Require Sphinx 8.1.3 or later to build the Python
documentation. Patch by Adam Turner.

@item 
gh-67206@footnote{https://github.com/python/cpython/issues/67206}: Document that @ref{18b7,,string.printable} is not printable in the
POSIX sense. In particular, @ref{fd8,,string.printable.isprintable()} returns @ref{d2b,,False}. Patch by Bénédikt Tran.
@end itemize

@node Core and Builtins<30>,ライブラリ<34>,ドキュメント<11>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id137}@anchor{18b8}
@subsubsection Core and Builtins



@itemize -

@item 
gh-100239@footnote{https://github.com/python/cpython/issues/100239}: Replace the opcode BINARY_SUBSCR and its family by BINARY_OP
with oparg NB_SUBSCR.

@item 
gh-129732@footnote{https://github.com/python/cpython/issues/129732}: Fixed a race in @code{_Py_qsbr_reserve} in the free threading
build.

@item 
gh-129763@footnote{https://github.com/python/cpython/issues/129763}: Remove the internal @code{LLTRACE} macro (use @ref{1834,,Py_DEBUG}
instead).

@item 
gh-129715@footnote{https://github.com/python/cpython/issues/129715}: Improve JIT performance for generators.

@item 
gh-129643@footnote{https://github.com/python/cpython/issues/129643}: Fix thread safety of @ref{18b9,,PyList_Insert()} in free-threading
builds.

@item 
gh-129668@footnote{https://github.com/python/cpython/issues/129668}: Fix race condition when raising @ref{179e,,MemoryError} in the free
threaded build.

@item 
gh-129643@footnote{https://github.com/python/cpython/issues/129643}: Fix thread safety of @ref{18ba,,PyList_SetItem()} in free-threading
builds. Patch by Kumar Aditya.

@item 
gh-128563@footnote{https://github.com/python/cpython/issues/128563}: Fix an issue where the "lltrace" debug feature could have been
incorrectly enabled for some frames.

@item 
gh-129393@footnote{https://github.com/python/cpython/issues/129393}: On FreeBSD, @ref{291,,sys.platform} doesn't contain the major
version anymore. It is always @code{'freebsd'}, instead of @code{'freebsd13'} or
@code{'freebsd14'}.
@end itemize

@node ライブラリ<34>,Core and Builtins<31>,Core and Builtins<30>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id138}@anchor{18bb}
@subsubsection ライブラリ



@itemize -

@item 
gh-129345@footnote{https://github.com/python/cpython/issues/129345}: Fix null pointer dereference in @ref{760,,syslog.openlog()} when an
audit hook raises an exception.
@end itemize

@node Core and Builtins<31>,ライブラリ<35>,ライブラリ<34>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id139}@anchor{18bc}
@subsubsection Core and Builtins



@itemize -

@item 
gh-129231@footnote{https://github.com/python/cpython/issues/129231}: Improve memory layout of JIT traces. Patch by Diego Russo

@item 
gh-129149@footnote{https://github.com/python/cpython/issues/129149}: Add fast path for medium-size integers in
@ref{18bd,,PyLong_FromUnsignedLong()}, @ref{18be,,PyLong_FromUnsignedLongLong()}
and @ref{18bf,,PyLong_FromSize_t()}.

@item 
gh-129201@footnote{https://github.com/python/cpython/issues/129201}: The free-threaded version of the cyclic garbage collector has
been optimized to conditionally use CPU prefetch instructions during the
collection.  This can reduce collection times by making it more likely
that data is in the CPU cache when it is needed.  The prefetch
instructions are enabled if the number of long-lived objects (objects
surviving a full collection) exceeds a threshold.

@item 
gh-129093@footnote{https://github.com/python/cpython/issues/129093}: Fix f-strings such as @code{f'@{expr=@}'} sometimes not displaying
the full expression when the expression contains @code{!=}.

@item 
gh-124363@footnote{https://github.com/python/cpython/issues/124363}: Treat debug expressions in f-string as raw strings. Patch by
Pablo Galindo

@item 
gh-128714@footnote{https://github.com/python/cpython/issues/128714}: Fix the potential races in get/set dunder methods
@code{__annotations__}, @code{__annotate__} and @code{__type_params__} for function
object, and add related tests.

@item 
gh-128799@footnote{https://github.com/python/cpython/issues/128799}: Add frame of @code{except*} to traceback when it wraps a naked
exception.

@item 
gh-128842@footnote{https://github.com/python/cpython/issues/128842}: Collect JIT memory stats using pystats. Patch by Diego Russo.

@item 
gh-100239@footnote{https://github.com/python/cpython/issues/100239}: Specialize @code{BINARY_OP} for bitwise logical operations on
compact ints.

@item 
gh-128910@footnote{https://github.com/python/cpython/issues/128910}: Undocumented and unused private C-API functions
@code{_PyTrash_begin} and @code{_PyTrash_end} are removed.

@item 
gh-128807@footnote{https://github.com/python/cpython/issues/128807}: Add a marking phase to the free-threaded GC.  This is similar
to what was done in gh-126491@footnote{https://github.com/python/cpython/issues/126491}.  Since the free-threaded GC does not have
generations and is not incremental, the marking phase looks for all
objects reachable from known roots.  The roots are objects known to not be
garbage, like the module dictionary for @ref{df,,sys}.  For most programs,
this marking phase should make the GC a bit faster since typically less
work is done per object.

@item 
gh-100239@footnote{https://github.com/python/cpython/issues/100239}: Add opcode @code{BINARY_OP_EXTEND} which executes a pair of
functions (guard and specialization functions) accessed from the inline
cache.

@item 
gh-128563@footnote{https://github.com/python/cpython/issues/128563}: A new type of interpreter has been added to CPython. This
interpreter uses tail calls for its instruction handlers. Preliminary
benchmark results suggest 7-11% geometric mean faster on pyperformance
(depending on platform), and up to 30% faster on Python-intensive
workloads. This interpreter currently only works on newer compilers, such
as @code{clang-19}. Other compilers will continue using the old interpreter.
Patch by Ken Jin, with ideas on how to implement this in CPython by Mark
Shannon, Garret Gu, Haoran Xu, and Josh Haberman.

@item 
gh-126703@footnote{https://github.com/python/cpython/issues/126703}: Improve performance of iterating over lists and tuples by using
a freelist for the iterator objects.

@item 
gh-127953@footnote{https://github.com/python/cpython/issues/127953}: The time to handle a @code{LINE} event in sys.monitoring (and
sys.settrace) is now independent of the number of lines in the code
object.

@item 
gh-128330@footnote{https://github.com/python/cpython/issues/128330}: Restore terminal control characters on REPL exit.

@item 
gh-128016@footnote{https://github.com/python/cpython/issues/128016}: Improved the @code{SyntaxWarning} message for invalid escape
sequences to clarify that such sequences will raise a @code{SyntaxError} in
future Python releases. The new message also suggests a potential fix,
i.e., @code{Did you mean "\\e"?}.

@item 
gh-126004@footnote{https://github.com/python/cpython/issues/126004}: Fix handling of @ref{18c0,,UnicodeError.start} and
@ref{18c1,,UnicodeError.end} values in the @ref{18c2,,codecs.replace_errors()} error
handler. Patch by Bénédikt Tran.

@item 
gh-126004@footnote{https://github.com/python/cpython/issues/126004}: Fix handling of @ref{18c0,,UnicodeError.start} and
@ref{18c1,,UnicodeError.end} values in the
@ref{18c3,,codecs.backslashreplace_errors()} error handler. Patch by Bénédikt
Tran.

@item 
gh-126004@footnote{https://github.com/python/cpython/issues/126004}: Fix handling of @ref{18c0,,UnicodeError.start} and
@ref{18c1,,UnicodeError.end} values in the
@ref{18c4,,codecs.xmlcharrefreplace_errors()} error handler. Patch by Bénédikt
Tran.

@item 
gh-127119@footnote{https://github.com/python/cpython/issues/127119}: Slightly optimize the @ref{19b,,int} deallocator.

@item 
gh-127349@footnote{https://github.com/python/cpython/issues/127349}: Fixed the error when resizing terminal in Python REPL. Patch by
Semyon Moroz.

@item 
gh-125723@footnote{https://github.com/python/cpython/issues/125723}: Fix crash with @code{gi_frame.f_locals} when generator frames
outlive their generator. Patch by Mikhail Efimov.
@end itemize

@node ライブラリ<35>,Core and Builtins<32>,Core and Builtins<31>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id140}@anchor{18c5}
@subsubsection ライブラリ



@itemize -

@item 
gh-126349@footnote{https://github.com/python/cpython/issues/126349}: Add @ref{2a3,,turtle.fill()}, @ref{2a4,,turtle.poly()} and
@ref{2a5,,turtle.no_animation()} context managers. Patch by Marie Roald and
Yngve Mardal Moe.
@end itemize

@node Core and Builtins<32>,ライブラリ<36>,ライブラリ<35>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id141}@anchor{18c6}
@subsubsection Core and Builtins



@itemize -

@item 
gh-115911@footnote{https://github.com/python/cpython/issues/115911}: If the current working directory cannot be determined due to
permissions, then import will no longer raise @ref{f3e,,PermissionError}.
Patch by Alex Willmer.
@end itemize

@node ライブラリ<36>,C API<11>,Core and Builtins<32>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id142}@anchor{18c7}
@subsubsection ライブラリ



@itemize -

@item 
gh-112713@footnote{https://github.com/python/cpython/issues/112713}: Added support for the @code{Partitioned} cookie flag in
@ref{75,,http.cookies}.
@end itemize

@node C API<11>,ビルド<11>,ライブラリ<36>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id143}@anchor{18c8}
@subsubsection C API



@itemize -

@item 
gh-129533@footnote{https://github.com/python/cpython/issues/129533}: Update @ref{aa4,,PyGC_Enable()}, @ref{aa5,,PyGC_Disable()},
@ref{aa6,,PyGC_IsEnabled()} to use atomic operation for thread-safety at
free-threading build. Patch by Donghee Na.

@item 
gh-89188@footnote{https://github.com/python/cpython/issues/89188}: Implement @ref{1395,,PyUnicode_KIND()} and @ref{1391,,PyUnicode_DATA()}
as function, in addition to the macros with the same names. The macros
rely on C bit fields which have compiler-specific layout. Patch by Victor
Stinner.

@item 
gh-91417@footnote{https://github.com/python/cpython/issues/91417}: Remove @ref{18a2,,PySequence_Fast()} from the limited C API, since
this function has to be used with @ref{3cb,,PySequence_Fast_GET_ITEM}
which never worked in the limited C API. Patch by Victor Stinner.

@item 
gh-128509@footnote{https://github.com/python/cpython/issues/128509}: Add @ref{3c4,,PyUnstable_IsImmortal()} for determining whether an
object is @ref{290,,immortal}.

@item 
gh-129033@footnote{https://github.com/python/cpython/issues/129033}: Remove @code{_PyInterpreterState_GetConfigCopy()} and
@code{_PyInterpreterState_SetConfig()} private functions. Use instead
@ref{37c,,PyConfig_Get()} and @ref{37d,,PyConfig_Set()}, public C API added by
@geindex Python Enhancement Proposals; PEP 741
PEP 741@footnote{https://peps.python.org/pep-0741/} "Python Configuration C API". Patch by Victor Stinner.

@item 
gh-129033@footnote{https://github.com/python/cpython/issues/129033}: Remove the private @code{_Py_InitializeMain()} function. It was a
@ref{3d1,,provisional API} added to Python 3.8 by 
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/}. Patch by Victor
Stinner.

@item 
gh-128844@footnote{https://github.com/python/cpython/issues/128844}: Add @ref{18c9,,PyUnstable_TryIncRef()} and
@ref{18ca,,PyUnstable_EnableTryIncRef()} unstable APIs.  These are helpers for
dealing with unowned references in a thread-safe way, particularly in the
free threading build.

@item 
gh-128911@footnote{https://github.com/python/cpython/issues/128911}: Add @ref{396,,PyImport_ImportModuleAttr()} and
@ref{397,,PyImport_ImportModuleAttrString()} helper functions to import a
module and get an attribute of the module. Patch by Victor Stinner.

@item 
gh-128863@footnote{https://github.com/python/cpython/issues/128863}: The following private functions are deprecated and planned for
removal in Python 3.18:


@itemize *

@item 
@code{_PyBytes_Join()}: use @ref{383,,PyBytes_Join()}.

@item 
@code{_PyDict_GetItemStringWithError()}: use @ref{421,,PyDict_GetItemStringRef()}.

@item 
@code{_PyDict_Pop()}: use @ref{422,,PyDict_Pop()}.

@item 
@code{_PyLong_Sign()}: use @ref{39a,,PyLong_GetSign()}.

@item 
@code{_PyLong_FromDigits()} and @code{_PyLong_New()}:
use @ref{3aa,,PyLongWriter_Create()}.

@item 
@code{_PyThreadState_UncheckedGet()}: use @ref{423,,PyThreadState_GetUnchecked()}.

@item 
@code{_PyUnicode_AsString()}: use @ref{424,,PyUnicode_AsUTF8()}.

@item 
@code{_Py_HashPointer()}: use @ref{425,,Py_HashPointer()}.

@item 
@code{_Py_fopen_obj()}: use @ref{393,,Py_fopen()}.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get these
new public functions on Python 3.13 and older.

Patch by Victor Stinner.

@item 
gh-126599@footnote{https://github.com/python/cpython/issues/126599}: Remove some internal test APIs for the experimental JIT
compiler.

@item 
gh-127925@footnote{https://github.com/python/cpython/issues/127925}: Convert the @ref{3a,,decimal} module to use 
@geindex Python Enhancement Proposals; PEP 757
PEP 757@footnote{https://peps.python.org/pep-0757/} C API
(export-import integers), offering some speed-up if the integer part of
the @ref{1fe,,Decimal} instance is small.  Patch by Sergey B
Kirpichev.
@end itemize

@node ビルド<11>,,C API<11>,Python 3 14 0 alpha 5
@anchor{whatsnew/changelog id144}@anchor{18cb}
@subsubsection ビルド



@itemize -

@item 
gh-129660@footnote{https://github.com/python/cpython/issues/129660}: Drop @code{test_embed} from PGO training, whose contribution in
recent versions is considered to be ignorable.

@item 
gh-128902@footnote{https://github.com/python/cpython/issues/128902}: Fix compile errors with Clang 9 and older due to lack of
@code{__attribute__((fallthrough))} support.
@end itemize

@node Python 3 14 0 alpha 4,Python 3 14 0 alpha 3,Python 3 14 0 alpha 5,変更履歴
@anchor{whatsnew/changelog python-3-14-0-alpha-4}@anchor{18cc}
@subsection Python 3.14.0 alpha 4


`Release date: 2025-01-14'

@menu
* macOS: macOS<7>. 
* Tools/Demos: Tools/Demos<12>. 
* テスト: テスト<10>. 
* ライブラリ: ライブラリ<37>. 
* Core and Builtins: Core and Builtins<33>. 
* ライブラリ: ライブラリ<38>. 
* Core and Builtins: Core and Builtins<34>. 
* ライブラリ: ライブラリ<39>. 
* Core and Builtins: Core and Builtins<35>. 
* C API: C API<12>. 
* ビルド: ビルド<12>. 

@end menu

@node macOS<7>,Tools/Demos<12>,,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id145}@anchor{18cd}
@subsubsection macOS



@itemize -

@item 
gh-127592@footnote{https://github.com/python/cpython/issues/127592}: Usage of the unified Apple System Log APIs was disabled when
the minimum macOS version is earlier than 10.12.
@end itemize

@node Tools/Demos<12>,テスト<10>,macOS<7>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id146}@anchor{18ce}
@subsubsection Tools/Demos



@itemize -

@item 
gh-128152@footnote{https://github.com/python/cpython/issues/128152}: Fix a bug where Argument Clinic's C pre-processor parser tried
to parse pre-processor directives inside C comments. Patch by Erlend
Aasland.
@end itemize

@node テスト<10>,ライブラリ<37>,Tools/Demos<12>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id147}@anchor{18cf}
@subsubsection テスト



@itemize -

@item 
gh-128690@footnote{https://github.com/python/cpython/issues/128690}: Temporarily do not use test_embed in PGO profile builds until
the problem with test_init_pyvenv_cfg failing in some configurations is
resolved.
@end itemize

@node ライブラリ<37>,Core and Builtins<33>,テスト<10>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id148}@anchor{18d0}
@subsubsection ライブラリ



@itemize -

@item 
gh-128731@footnote{https://github.com/python/cpython/issues/128731}: Fix @ref{54c,,ResourceWarning} in
@ref{18d1,,urllib.robotparser.RobotFileParser.read()}.

@item 
gh-71339@footnote{https://github.com/python/cpython/issues/71339}: Add new assertion methods for @ref{10c,,unittest}:
@ref{2b4,,assertHasAttr()},
@ref{2b5,,assertNotHasAttr()},
@ref{2b6,,assertIsSubclass()},
@ref{2b7,,assertNotIsSubclass()}
@ref{2b8,,assertStartsWith()},
@ref{2b9,,assertNotStartsWith()},
@ref{2ba,,assertEndsWith()} and
@ref{2bb,,assertNotEndsWith()}.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import time of @ref{ab,,pickle} by 25% by removing an
unnecessary regular expression. As such, @ref{be,,re} is no more implicitly
available as @code{pickle.re}. Patch by Bénédikt Tran.

@item 
gh-128661@footnote{https://github.com/python/cpython/issues/128661}: Fixes @ref{1815,,typing.evaluate_forward_ref()} not showing
deprecation when @code{type_params} arg is not passed.

@item 
gh-128562@footnote{https://github.com/python/cpython/issues/128562}: Fix possible conflicts in generated @ref{f6,,tkinter} widget names
if the widget class name ends with a digit.

@item 
gh-128559@footnote{https://github.com/python/cpython/issues/128559}: Improved import time of @ref{b,,asyncio}.

@item 
gh-128552@footnote{https://github.com/python/cpython/issues/128552}: Fix cyclic garbage introduced by
@ref{1ca,,asyncio.loop.create_task()} and @ref{1cb,,asyncio.TaskGroup.create_task()}
holding a reference to the created task if it is eager.

@item 
gh-128340@footnote{https://github.com/python/cpython/issues/128340}: Add internal thread safe handle to be used in
@ref{cfb,,asyncio.loop.call_soon_threadsafe()} for thread safe cancellation.

@item 
gh-128182@footnote{https://github.com/python/cpython/issues/128182}: Fix crash when using @ref{2e,,ctypes} pointers concurrently on the
@ref{1f4,,free threaded} build.

@item 
gh-128400@footnote{https://github.com/python/cpython/issues/128400}: Only show the current thread in @ref{5c,,faulthandler} on the
@ref{1f4,,free threaded} build to prevent races.

@item 
gh-128400@footnote{https://github.com/python/cpython/issues/128400}: Fix crash when using @ref{fff,,faulthandler.dump_traceback()} while
other threads are active on the @ref{1f4,,free threaded}
build.

@item 
gh-128388@footnote{https://github.com/python/cpython/issues/128388}: Fix @code{PyREPL} on Windows to support more keybindings, like the
@code{Control}-@code{←} and @code{Control}-@code{→} word-skipping keybindings and those
with meta (i.e. @code{Alt}), e.g. @code{Alt}-@code{d} to @code{kill-word} or
@code{Alt}-@code{Backspace} @code{backward-kill-word}.

@item 
gh-88834@footnote{https://github.com/python/cpython/issues/88834}: Unify the instance check for @ref{2a8,,typing.Union} and
@ref{2a7,,types.UnionType}: @code{Union} now uses the instance checks
against its parameters instead of the subclass checks.

@item 
gh-128302@footnote{https://github.com/python/cpython/issues/128302}: Fix
@code{xml.dom.xmlbuilder.DOMEntityResolver.resolveEntity()}, which was
broken by the Python 3.0 transition.

@item 
gh-128317@footnote{https://github.com/python/cpython/issues/128317}: Highlight today in colour in @ref{15,,calendar}'s CLI output.
Patch by Hugo van Kemenade.

@item 
gh-128302@footnote{https://github.com/python/cpython/issues/128302}: Allow @code{xml.dom.xmlbuilder.DOMParser.parse()} to correctly
handle @code{xml.dom.xmlbuilder.DOMInputSource} instances that only
have a @code{systemId} attribute set.

@item 
gh-128151@footnote{https://github.com/python/cpython/issues/128151}: Improve generation of @ref{c56,,UUID} objects version 3, 4,
5, and 8 via their dedicated functions by 30%. Patch by Bénédikt Tran.

@item 
gh-128118@footnote{https://github.com/python/cpython/issues/128118}: Improve performance of @ref{757,,copy.copy()} by 30% via a fast path
for atomic types and container types.

@item 
gh-127946@footnote{https://github.com/python/cpython/issues/127946}: Fix crash when modifying @ref{18d2,,ctypes._CFuncPtr} objects
concurrently on the @ref{1f4,,free threaded} build.

@item 
gh-128062@footnote{https://github.com/python/cpython/issues/128062}: Revert the font of @ref{108,,turtledemo}'s menu bar to its default
value and display the shortcut keys in the correct position.

@item 
gh-128014@footnote{https://github.com/python/cpython/issues/128014}: Fix resetting the default window icon by passing @code{default='@w{'}}
to the @ref{f6,,tkinter} method @code{wm_iconbitmap()}.

@item 
gh-41872@footnote{https://github.com/python/cpython/issues/41872}: Fix quick extraction of module docstrings from a file in
@ref{ba,,pydoc}. It now supports docstrings with single quotes, escape
sequences, raw string literals, and other Python syntax.

@item 
gh-127060@footnote{https://github.com/python/cpython/issues/127060}: Set TERM environment variable to "dumb" to disable traceback
colors in IDLE, since IDLE doesn't understand ANSI escape sequences. Patch
by Victor Stinner.

@item 
gh-126742@footnote{https://github.com/python/cpython/issues/126742}: Fix support of localized error messages reported by
@code{dlerror(3)@footnote{https://manpages.debian.org/dlerror(3)}} and @code{gdbm_strerror@footnote{https://manpages.debian.org/gdbm(3)}} in
@ref{2e,,ctypes} and @ref{37,,dbm.gnu} functions respectively. Patch by Bénédikt
Tran.

@item 
gh-122548@footnote{https://github.com/python/cpython/issues/122548}: Adds two new local events to sys.monitoring, @code{BRANCH_LEFT}
and @code{BRANCH_RIGHT}. This allows the two arms of the branch to be
disabled independently, which should hugely improve performance of
branch-level coverage tools. The old branch event, @code{BRANCH} is now
deprecated.

@item 
gh-127847@footnote{https://github.com/python/cpython/issues/127847}: Fix the position when doing interleaved seeks and reads in
uncompressed, unencrypted zip files returned by
@ref{65d,,zipfile.ZipFile.open()}.

@item 
gh-127688@footnote{https://github.com/python/cpython/issues/127688}: Add the @ref{25d,,SCHED_DEADLINE} and @ref{25e,,SCHED_NORMAL}
constants to the @ref{a5,,os} module.

@item 
gh-83662@footnote{https://github.com/python/cpython/issues/83662}: Add missing @code{__class_getitem__} method to the Python
implementation of @ref{217,,functools.partial()}, to make it compatible with
the C version. This is mainly relevant for alternative Python
implementations like PyPy and GraalPy, because CPython will usually use
the C-implementation of that function.

@item 
gh-127586@footnote{https://github.com/python/cpython/issues/127586}: @ref{116d,,multiprocessing.pool.Pool} now properly restores
blocked signal handlers of the parent thread when creating processes via
either `spawn' or `forkserver'.

@item 
gh-98188@footnote{https://github.com/python/cpython/issues/98188}: Fix an issue in @ref{13e5,,email.message.Message.get_payload()} where
data cannot be decoded if the Content Transfer Encoding mechanism contains
trailing whitespaces or additional junk text. Patch by Hui Liu.

@item 
gh-127529@footnote{https://github.com/python/cpython/issues/127529}: Correct behavior of
@code{asyncio.selector_events.BaseSelectorEventLoop._accept_connection()}
in handling @ref{1268,,ConnectionAbortedError} in a loop. This improves
performance on OpenBSD.

@item 
gh-127360@footnote{https://github.com/python/cpython/issues/127360}: When a descriptive error message cannot be provided for an
@ref{1491,,ssl.SSLError}, the "unknown error" message now shows the internal
error code (as retrieved by @code{ERR_get_error} and similar OpenSSL
functions).

@item 
gh-127196@footnote{https://github.com/python/cpython/issues/127196}: Fix crash when dict with keys in invalid encoding were passed
to several functions in @code{_interpreters} module.

@item 
gh-124130@footnote{https://github.com/python/cpython/issues/124130}: Fix a bug in matching regular expression @code{\B} in empty input
string. Now it is always the opposite of @code{\b}. To get an old behavior,
use @code{(?!\A\Z)\B}. To get a new behavior in old Python versions, use
@code{(?!\b)}.

@item 
gh-126639@footnote{https://github.com/python/cpython/issues/126639}: @ref{6ed,,tempfile.NamedTemporaryFile} will now issue a
@ref{54c,,ResourceWarning} when it is finalized by the garbage collector
without being explicitly closed.

@item 
gh-126624@footnote{https://github.com/python/cpython/issues/126624}: Expose error code
@ref{18d3,,XML_ERROR_NOT_STARTED} of Expat >=2.6.4
in @ref{12d,,xml.parsers.expat.errors}.

@item 
gh-126225@footnote{https://github.com/python/cpython/issues/126225}: @ref{65,,getopt} and @ref{a4,,optparse} are no longer marked as
deprecated. There are legitimate reasons to use one of these modules in
preference to @ref{7,,argparse}, and none of these modules are at risk of
being removed from the standard library. Of the three, @code{argparse}
remains the recommended default choice, `unless' one of the concerns noted
at the top of the @code{optparse} module documentation applies.

@item 
gh-124761@footnote{https://github.com/python/cpython/issues/124761}: Add @ref{18d4,,SO_REUSEPORT_LB} constant to @ref{d1,,socket}
for FreeBSD.

@item 
gh-121720@footnote{https://github.com/python/cpython/issues/121720}: @ref{4f6,,enum.EnumDict} can now be used without resorting to
private API.

@item 
gh-123424@footnote{https://github.com/python/cpython/issues/123424}: Add @ref{2ca,,zipfile.ZipInfo._for_archive()} setting default
properties on @ref{2cb,,ZipInfo} objects. Patch by Bénédikt Tran
and Jason R. Coombs.

@item 
gh-121676@footnote{https://github.com/python/cpython/issues/121676}: Deprecate calling the Python implementation of
@ref{21a,,functools.reduce()} with a @code{function} or @code{sequence} as a
@ref{f0e,,keyword argument}. This will be forbidden in Python 3.16 in order
to match the C implementation.

@item 
gh-112015@footnote{https://github.com/python/cpython/issues/112015}: @ref{1eb,,ctypes.memoryview_at()} now exists to create a
@ref{165,,memoryview} object that refers to the supplied pointer and length.
This works like @ref{1ec,,ctypes.string_at()} except it avoids a buffer copy,
and is typically useful when implementing pure Python callback functions
that are passed dynamically-sized buffers.

@item 
gh-95371@footnote{https://github.com/python/cpython/issues/95371}: Added support for other image formats (PNG, PGM, and PPM) to the
turtle module. Patch by Shin-myoung-serp.
@end itemize

@node Core and Builtins<33>,ライブラリ<38>,ライブラリ<37>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id149}@anchor{18d5}
@subsubsection Core and Builtins



@itemize -

@item 
gh-128078@footnote{https://github.com/python/cpython/issues/128078}: Fix a @ref{795,,SystemError} when using @ref{9d6,,anext()} with a
default tuple value. Patch by Bénédikt Tran.

@item 
gh-128717@footnote{https://github.com/python/cpython/issues/128717}: Fix a crash when setting the recursion limit while other
threads are active on the @ref{1f4,,free threaded} build.

@item 
gh-124483@footnote{https://github.com/python/cpython/issues/124483}: Treat @code{Py_DECREF} and variants as escaping when generating
opcode and uop metadata. This prevents the possibility of a @code{__del__}
method causing the JIT to behave incorrectly.

@item 
gh-126703@footnote{https://github.com/python/cpython/issues/126703}: Improve performance of class methods by using a freelist.

@item 
gh-128137@footnote{https://github.com/python/cpython/issues/128137}: Update @ref{138d,,PyASCIIObject} layout to handle interned field
with the atomic operation. Patch by Donghee Na.
@end itemize

@node ライブラリ<38>,Core and Builtins<34>,Core and Builtins<33>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id150}@anchor{18d6}
@subsubsection ライブラリ



@itemize -

@item 
gh-128192@footnote{https://github.com/python/cpython/issues/128192}: Upgrade HTTP digest authentication algorithm for
@ref{111,,urllib.request} by supporting SHA-256 digest authentication as
specified in 
@geindex RFC; RFC 7616
RFC 7616@footnote{https://datatracker.ietf.org/doc/html/rfc7616.html}.
@end itemize

@node Core and Builtins<34>,ライブラリ<39>,ライブラリ<38>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id151}@anchor{18d7}
@subsubsection Core and Builtins



@itemize -

@item 
gh-126868@footnote{https://github.com/python/cpython/issues/126868}: Increase usage of freelist for @ref{19b,,int} allocation.

@item 
gh-114203@footnote{https://github.com/python/cpython/issues/114203}: Optimize @code{Py_BEGIN_CRITICAL_SECTION} for simple recursive
calls.

@item 
gh-127705@footnote{https://github.com/python/cpython/issues/127705}: Adds stackref debugging when @code{Py_STACKREF_DEBUG} is set.
Finds all double-closes and leaks, logging the origin and last borrow.

Inspired by HPy's debug mode.
@indicateurl{https://docs.hpyproject.org/en/latest/debug-mode.html}

@item 
gh-128079@footnote{https://github.com/python/cpython/issues/128079}: Fix a bug where @ref{1ac,,except*} does not
properly check the return value of an @ref{4d2,,ExceptionGroup}'s
@ref{18d8,,split()} function, leading to a crash in some
cases. Now when @ref{18d8,,split()} returns an invalid
object, @ref{1ac,,except*} raises a @ref{198,,TypeError} with
the original raised @ref{4d2,,ExceptionGroup} object chained to it.

@item 
gh-128030@footnote{https://github.com/python/cpython/issues/128030}: Avoid error from calling @code{PyModule_GetFilenameObject} on a
non-module object when importing a non-existent symbol from a non-module
object.
@end itemize

@node ライブラリ<39>,Core and Builtins<35>,Core and Builtins<34>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id152}@anchor{18d9}
@subsubsection ライブラリ



@itemize -

@item 
gh-128035@footnote{https://github.com/python/cpython/issues/128035}: Indicate through @ref{286,,ssl.HAS_PHA} whether the @ref{d5,,ssl}
module supports TLSv1.3 post-handshake client authentication (PHA). Patch
by Will Childs-Klein.
@end itemize

@node Core and Builtins<35>,C API<12>,ライブラリ<39>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id153}@anchor{18da}
@subsubsection Core and Builtins



@itemize -

@item 
gh-127274@footnote{https://github.com/python/cpython/issues/127274}: Add a new flag, @code{CO_METHOD}, to @ref{18db,,co_flags}
that indicates whether the code object belongs to a function defined in
class scope.

@item 
gh-66409@footnote{https://github.com/python/cpython/issues/66409}: During the @ref{18dc,,path initialization}, we now
check if @code{base_exec_prefix} is the same as @code{base_prefix} before
falling back to searching the Python interpreter directory.

@item 
gh-127970@footnote{https://github.com/python/cpython/issues/127970}: We now use the location of the @code{libpython} runtime library
used in the current process to determine @ref{3e6,,sys.base_prefix} on all
platforms implementing the dladdr@footnote{https://pubs.opengroup.org/onlinepubs/9799919799/functions/dladdr.html}
function defined by the UNIX standard — this includes Linux, Android,
macOS, iOS, FreeBSD, etc. This was already the case on Windows and macOS
Framework builds.

@item 
gh-127773@footnote{https://github.com/python/cpython/issues/127773}: Do not use the type attribute cache for types with incompatible
@ref{18dd,,MRO}.

@item 
gh-127903@footnote{https://github.com/python/cpython/issues/127903}: @code{Objects/unicodeobject.c}: fix a crash on DEBUG builds in
@code{_copy_characters} when there is nothing to copy.

@item 
gh-127809@footnote{https://github.com/python/cpython/issues/127809}: Fix an issue where the experimental JIT may infer an incorrect
result type for exponentiation (@code{**} and @code{**=}), leading to bugs or
crashes.

@item 
gh-126862@footnote{https://github.com/python/cpython/issues/126862}: Fix a possible overflow when a class inherits from an absurd
number of super-classes. Reported by Valery Fedorenko. Patch by Bénédikt
Tran.
@end itemize

@node C API<12>,ビルド<12>,Core and Builtins<35>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id154}@anchor{18de}
@subsubsection C API



@itemize -

@item 
gh-128400@footnote{https://github.com/python/cpython/issues/128400}: @ref{b7a,,Py_FatalError()} no longer shows all threads on the
@ref{1f4,,free threaded} build to prevent crashes.

@item 
gh-128629@footnote{https://github.com/python/cpython/issues/128629}: Add macros @ref{37f,,Py_PACK_VERSION()} and
@ref{380,,Py_PACK_FULL_VERSION()} for bit-packing Python version numbers.

@item 
gh-128008@footnote{https://github.com/python/cpython/issues/128008}: Add @ref{18df,,PyWeakref_IsDead()} function, which tests if a weak
reference is dead.

@item 
gh-127350@footnote{https://github.com/python/cpython/issues/127350}: Add @ref{393,,Py_fopen()} function to open a file. Similar to the
@code{fopen()} function, but the `path' parameter is a Python object and
an exception is set on error. Add also @ref{394,,Py_fclose()} function to
close a file, function needed for Windows support. Patch by Victor
Stinner.
@end itemize

@node ビルド<12>,,C API<12>,Python 3 14 0 alpha 4
@anchor{whatsnew/changelog id155}@anchor{18e0}
@subsubsection ビルド



@itemize -

@item 
gh-128627@footnote{https://github.com/python/cpython/issues/128627}: For Emscripten builds the function pointer cast call trampoline
now uses the wasm-gc ref.test instruction if it's available instead of
Wasm JS type reflection.

@item 
gh-128472@footnote{https://github.com/python/cpython/issues/128472}: Skip BOLT optimization of functions using computed gotos,
fixing errors on build with LLVM 19.

@item 
gh-115765@footnote{https://github.com/python/cpython/issues/115765}: GNU Autoconf 2.72 is now required to generate
@code{configure}. Patch by Erlend Aasland.

@item 
gh-123925@footnote{https://github.com/python/cpython/issues/123925}: Fix building the @ref{2f,,curses} module on platforms with
libncurses but without libncursesw.

@item 
gh-90905@footnote{https://github.com/python/cpython/issues/90905}: Add support for cross-compiling to x86_64 on aarch64/arm64
macOS.

@item 
gh-128321@footnote{https://github.com/python/cpython/issues/128321}: Set @code{LIBS} instead of @code{LDFLAGS} when checking if
@ref{d4,,sqlite3} library functions are available. This fixes the ordering of
linked libraries during checks, which was incorrect when using a
statically linked @code{libsqlite3}.

@item 
gh-100384@footnote{https://github.com/python/cpython/issues/100384}: Error on @code{unguarded-availability} in macOS builds, preventing
invalid use of symbols that are not available in older versions of the OS.

@item 
gh-128104@footnote{https://github.com/python/cpython/issues/128104}: Remove @code{Py_STRFTIME_C99_SUPPORT} conditions in favor of
requiring C99 @code{strftime(3)@footnote{https://manpages.debian.org/strftime(3)}} specifier support at build time. When
cross-compiling, there is no build time check and support is assumed.

@item 
gh-127951@footnote{https://github.com/python/cpython/issues/127951}: Add option @code{--pystats} to the Windows build to enable
performance statistics collection.
@end itemize

@node Python 3 14 0 alpha 3,Python 3 14 0 alpha 2,Python 3 14 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-14-0-alpha-3}@anchor{18e1}
@subsection Python 3.14.0 alpha 3


`Release date: 2024-12-17'

@menu
* Windows: Windows<12>. 
* Tools/Demos: Tools/Demos<13>. 
* テスト: テスト<11>. 
* セキュリティ: セキュリティ<14>. 
* ライブラリ: ライブラリ<40>. 
* ドキュメント: ドキュメント<12>. 
* Core and Builtins: Core and Builtins<36>. 
* ライブラリ: ライブラリ<41>. 
* Core and Builtins: Core and Builtins<37>. 
* C API: C API<13>. 
* ビルド: ビルド<13>. 

@end menu

@node Windows<12>,Tools/Demos<13>,,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id156}@anchor{18e2}
@subsubsection Windows



@itemize -

@item 
gh-127353@footnote{https://github.com/python/cpython/issues/127353}: Allow to force color output on Windows using environment
variables. Patch by Andrey Efremov.

@item 
gh-125729@footnote{https://github.com/python/cpython/issues/125729}: Makes the presence of the @ref{107,,turtle} module dependent on the
Tcl/Tk installer option. Previously, the module was always installed but
would be unusable without Tcl/Tk.
@end itemize

@node Tools/Demos<13>,テスト<11>,Windows<12>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id157}@anchor{18e3}
@subsubsection Tools/Demos



@itemize -

@item 
gh-126700@footnote{https://github.com/python/cpython/issues/126700}: Add support for multi-argument @ref{67,,gettext} functions in
@code{pygettext.py}.
@end itemize

@node テスト<11>,セキュリティ<14>,Tools/Demos<13>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id158}@anchor{18e4}
@subsubsection テスト



@itemize -

@item 
gh-127906@footnote{https://github.com/python/cpython/issues/127906}: Test the limited C API in test_cppext. Patch by Victor Stinner.

@item 
gh-127637@footnote{https://github.com/python/cpython/issues/127637}: Add tests for the @ref{3c,,dis} command-line interface. Patch by
Bénédikt Tran.

@item 
gh-126925@footnote{https://github.com/python/cpython/issues/126925}: iOS test results are now streamed during test execution, and
the deprecated xcresulttool is no longer used.

@item 
gh-127076@footnote{https://github.com/python/cpython/issues/127076}: Disable strace based system call tests when LD_PRELOAD is set.

@item 
gh-127076@footnote{https://github.com/python/cpython/issues/127076}: Filter out memory-related @code{mmap}, @code{munmap}, and
@code{mprotect}  calls from file-related ones when testing @ref{83,,io} behavior
using strace.
@end itemize

@node セキュリティ<14>,ライブラリ<40>,テスト<11>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id159}@anchor{18e5}
@subsubsection セキュリティ



@itemize -

@item 
gh-127655@footnote{https://github.com/python/cpython/issues/127655}: Fixed the
@code{asyncio.selector_events._SelectorSocketTransport} transport not
pausing writes for the protocol when the buffer reaches the high water
mark when using @ref{17c9,,asyncio.WriteTransport.writelines()}.
@end itemize

@node ライブラリ<40>,ドキュメント<12>,セキュリティ<14>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id160}@anchor{18e6}
@subsubsection ライブラリ



@itemize -

@item 
gh-126907@footnote{https://github.com/python/cpython/issues/126907}: Fix crash when using @ref{d,,atexit} concurrently on the
@ref{1f4,,free-threaded} build.

@item 
gh-127870@footnote{https://github.com/python/cpython/issues/127870}: Detect recursive calls in ctypes @code{_as_parameter_} handling.
Patch by Victor Stinner.

@item 
gh-127732@footnote{https://github.com/python/cpython/issues/127732}: The @ref{af,,platform} module now correctly detects Windows Server
2025.

@item 
gh-126789@footnote{https://github.com/python/cpython/issues/126789}: Fixed @ref{298,,sysconfig.get_config_vars()},
@ref{340,,sysconfig.get_paths()}, and siblings, returning outdated cached data
if the value  of @ref{3e7,,sys.prefix} or @ref{3eb,,sys.exec_prefix} changes.
Overwriting @ref{3e7,,sys.prefix} or @ref{3eb,,sys.exec_prefix} still is
discouraged, as that might break other parts of the code.

@item 
gh-127718@footnote{https://github.com/python/cpython/issues/127718}: Add colour to @ref{e9,,test.regrtest} output. Patch by Hugo van
Kemenade.

@item 
gh-127610@footnote{https://github.com/python/cpython/issues/127610}: Added validation for more than one var-positional or
var-keyword parameters in @ref{4e3,,inspect.Signature}. Patch by Maxim
Ageev.

@item 
gh-127627@footnote{https://github.com/python/cpython/issues/127627}: Added @code{posix._emscripten_debugger()} to help with debugging
the test suite on the Emscripten target.

@item 
gh-126821@footnote{https://github.com/python/cpython/issues/126821}: macOS and iOS apps can now choose to redirect stdout and stderr
to the system log during interpreter configuration.

@item 
gh-93312@footnote{https://github.com/python/cpython/issues/93312}: Include @code{<sys/pidfd.h>} to get @code{os.PIDFD_NONBLOCK} constant.
Patch by Victor Stinner.

@item 
gh-127481@footnote{https://github.com/python/cpython/issues/127481}: Add the @code{EPOLLWAKEUP} constant to the @ref{c6,,select} module.

@item 
gh-127065@footnote{https://github.com/python/cpython/issues/127065}: Make @ref{1034,,operator.methodcaller()} thread-safe and re-entrant
safe.

@item 
gh-127321@footnote{https://github.com/python/cpython/issues/127321}: @ref{272,,pdb.set_trace()} will not stop at an opcode that does not
have an associated line number anymore.

@item 
gh-127429@footnote{https://github.com/python/cpython/issues/127429}: Fixed bug where, on cross-builds, the @ref{e1,,sysconfig} POSIX
data was being generated with the host Python's @code{Makefile}. The data is
now generated from current build's @code{Makefile}.

@item 
gh-127413@footnote{https://github.com/python/cpython/issues/127413}: Add the @ref{209,,dis --specialized} command-line option to show
specialized bytecode. Patch by Bénédikt Tran.

@item 
gh-125413@footnote{https://github.com/python/cpython/issues/125413}: Revert addition of @code{pathlib.Path.scandir()}. This method
was added in 3.14.0a2. The optimizations remain for file system paths, but
other subclasses should only have to implement
@ref{26e,,pathlib.Path.iterdir()}.

@item 
gh-127257@footnote{https://github.com/python/cpython/issues/127257}: In @ref{d5,,ssl}, system call failures that OpenSSL reports using
@code{ERR_LIB_SYS} are now raised as @ref{2c0,,OSError}.

@item 
gh-59705@footnote{https://github.com/python/cpython/issues/59705}: On Linux, @ref{176,,threading.Thread} now sets the thread name to
the operating system. Patch by Victor Stinner.

@item 
gh-127303@footnote{https://github.com/python/cpython/issues/127303}: Publicly expose @ref{18e7,,EXACT_TOKEN_TYPES} in
@code{token.__all__}.

@item 
gh-127331@footnote{https://github.com/python/cpython/issues/127331}: @ref{d5,,ssl} can show descriptions for errors added in OpenSSL
3.4.

@item 
gh-123967@footnote{https://github.com/python/cpython/issues/123967}: Fix faulthandler for trampoline frames. If the top-most frame
is a trampoline frame, skip it. Patch by Victor Stinner.

@item 
gh-127178@footnote{https://github.com/python/cpython/issues/127178}: A @code{_sysconfig_vars_(...).json} file is now shipped in the
standard library directory. It contains the output of
@ref{298,,sysconfig.get_config_vars()} on the default environment encoded as
JSON data. This is an implementation detail, and may change at any time.

@item 
gh-127072@footnote{https://github.com/python/cpython/issues/127072}: Remove outdated @code{socket.NETLINK_*} constants not present in
Linux kernels beyond 2.6.17.

@item 
gh-127255@footnote{https://github.com/python/cpython/issues/127255}: The @ref{1ea,,CopyComPointer()} function is now public.
Previously, this was private and only available in @code{_ctypes}.

@item 
gh-127182@footnote{https://github.com/python/cpython/issues/127182}: Fix @code{io.StringIO.__setstate__()} crash, when @ref{885,,None}
was passed as the first value.

@item 
gh-127217@footnote{https://github.com/python/cpython/issues/127217}: Fix @ref{2bf,,urllib.request.pathname2url()} for paths starting with
multiple slashes on Posix.

@item 
gh-125866@footnote{https://github.com/python/cpython/issues/125866}: @ref{2bf,,urllib.request.pathname2url()} now adds an empty authority
when generating a URL for a path that begins with exactly one slash. For
example, the path @code{/etc/hosts} is converted to the scheme-less URL
@code{///etc/hosts}. As a result of this change, URLs without authorities are
only generated for relative paths.

@item 
gh-127221@footnote{https://github.com/python/cpython/issues/127221}: Add colour to @ref{10c,,unittest} output. Patch by Hugo van
Kemenade.

@item 
gh-127035@footnote{https://github.com/python/cpython/issues/127035}: Fix @ref{6db,,shutil.which} on Windows. Now it looks at direct
match if and only if the command ends with a PATHEXT extension or X_OK is
not in mode. Support extensionless files if "." is in PATHEXT. Support
PATHEXT extensions that end with a dot.

@item 
gh-122273@footnote{https://github.com/python/cpython/issues/122273}: Support PyREPL history on Windows. Patch by devdanzin and
Victor Stinner.

@item 
gh-125866@footnote{https://github.com/python/cpython/issues/125866}: @ref{2bf,,urllib.request.pathname2url()} and
@ref{2bd,,url2pathname()} no longer convert Windows drive
letters to uppercase.

@item 
gh-127078@footnote{https://github.com/python/cpython/issues/127078}: Fix issue where @ref{2bd,,urllib.request.url2pathname()} failed to
discard an extra slash before a UNC drive in the URL path on Windows.

@item 
gh-126766@footnote{https://github.com/python/cpython/issues/126766}: Fix issue where @ref{2bd,,urllib.request.url2pathname()} failed to
discard any 'localhost' authority present in the URL.

@item 
gh-127065@footnote{https://github.com/python/cpython/issues/127065}: Fix crash when calling a @ref{1034,,operator.methodcaller()} instance
from multiple threads in the free threading build.

@item 
gh-127090@footnote{https://github.com/python/cpython/issues/127090}: Fix value of @ref{18e8,,urllib.response.addinfourl.url} for
@code{file:} URLs that express relative paths and absolute Windows paths. The
canonical URL generated by @ref{2bf,,urllib.request.pathname2url()} is now
used.

@item 
gh-126992@footnote{https://github.com/python/cpython/issues/126992}: Fix LONG and INT opcodes to only use base 10 for string to
integer conversion in @ref{ab,,pickle}.

@item 
gh-126997@footnote{https://github.com/python/cpython/issues/126997}: Fix support of STRING and GLOBAL opcodes with non-ASCII
arguments in @ref{ac,,pickletools}. @ref{ebe,,pickletools.dis()} now outputs
non-ASCII bytes in STRING, BINSTRING and SHORT_BINSTRING arguments as
escaped (@code{\xXX}).

@item 
gh-126316@footnote{https://github.com/python/cpython/issues/126316}: @ref{6a,,grp}: Make @ref{18e9,,grp.getgrall()} thread-safe by adding a
mutex. Patch by Victor Stinner.

@item 
gh-126618@footnote{https://github.com/python/cpython/issues/126618}: Fix the representation of @ref{149b,,itertools.count} objects when
the count value is @ref{13dd,,sys.maxsize}.

@item 
gh-126615@footnote{https://github.com/python/cpython/issues/126615}: The @ref{1e9,,COMError} exception is now public.
Previously, this was private and only available in @code{_ctypes}.

@item 
gh-126985@footnote{https://github.com/python/cpython/issues/126985}: When running under a virtual environment with the @ref{cc,,site}
disabled (see @ref{13c0,,-S}), @ref{3e7,,sys.prefix} and
@ref{3e6,,sys.base_prefix} will now point to the virtual environment, instead
of the base installation.

@item 
gh-112192@footnote{https://github.com/python/cpython/issues/112192}: In the @ref{103,,trace} module, increase the coverage precision
(@code{cov%}) to one decimal.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import time of @ref{93,,mimetypes} by around 11-16 times.
Patch by Hugo van Kemenade.

@item 
gh-126947@footnote{https://github.com/python/cpython/issues/126947}: Raise @ref{198,,TypeError} in
@code{_pydatetime.timedelta.__new__()} if the passed arguments are not
@ref{19b,,int} or @ref{196,,float}, so that the Python implementation is in
line with the C implementation.

@item 
gh-126946@footnote{https://github.com/python/cpython/issues/126946}: Improve the @ref{18ea,,GetoptError} error message when a
long option prefix matches multiple accepted options in
@ref{16d4,,getopt.getopt()} and @ref{16d3,,getopt.gnu_getopt()}.

@item 
gh-126899@footnote{https://github.com/python/cpython/issues/126899}: Make tkinter widget methods @code{after()} and
@code{after_idle()} accept arguments passed by keyword.

@item 
gh-85168@footnote{https://github.com/python/cpython/issues/85168}: Fix issue where @ref{2bd,,urllib.request.url2pathname()} and
@ref{2bf,,pathname2url()} always used UTF-8 when quoting and
unquoting file URIs. They now use the @ref{75d,,filesystem encoding and error handler}.

@item 
gh-126780@footnote{https://github.com/python/cpython/issues/126780}: Fix @ref{1531,,os.path.normpath()} for drive-relative paths on
Windows.

@item 
gh-126775@footnote{https://github.com/python/cpython/issues/126775}: Make @ref{18eb,,linecache.checkcache()} thread safe and GC
re-entrancy safe.

@item 
gh-126601@footnote{https://github.com/python/cpython/issues/126601}: Fix issue where @ref{2bf,,urllib.request.pathname2url()} raised
@ref{2c0,,OSError} when given a Windows path containing a colon character not
following a drive letter, such as before an NTFS alternate data stream.

@item 
gh-126727@footnote{https://github.com/python/cpython/issues/126727}: @code{locale.nl_langinfo(locale.ERA)} now returns multiple era
description segments separated by semicolons. Previously it only returned
the first segment on platforms with Glibc.

@item 
gh-85046@footnote{https://github.com/python/cpython/issues/85046}: Add @ref{20b,,EHWPOISON} error code to @ref{5b,,errno}.

@item 
gh-118201@footnote{https://github.com/python/cpython/issues/118201}: Fixed intermittent failures of @ref{18ec,,os.confstr},
@ref{1313,,os.pathconf} and @ref{18ed,,os.sysconf} on iOS and Android.

@item 
gh-86463@footnote{https://github.com/python/cpython/issues/86463}: The @code{usage} parameter of @ref{1bd,,argparse.ArgumentParser} no
longer affects the default value of the @code{prog} parameter in subparsers.

@item 
gh-124008@footnote{https://github.com/python/cpython/issues/124008}: Fix possible crash (in debug build), incorrect output or
returning incorrect value from raw binary @code{write()} when writing to
console on Windows.

@item 
gh-123401@footnote{https://github.com/python/cpython/issues/123401}: The @ref{75,,http.cookies} module now supports parsing obsolete
@geindex RFC; RFC 850
RFC 850@footnote{https://datatracker.ietf.org/doc/html/rfc850.html} date formats, in accordance with 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html} requirements.
Patch by Nano Zheng.

@item 
gh-122431@footnote{https://github.com/python/cpython/issues/122431}: @ref{1051,,readline.append_history_file()} now raises a
@ref{2ec,,ValueError} when given a negative value.

@item 
gh-122356@footnote{https://github.com/python/cpython/issues/122356}: Guarantee that the position of a file-like object passed to
@ref{1542,,zipfile.is_zipfile()} is left untouched after the call. Patch by
Bénédikt Tran.

@item 
gh-122288@footnote{https://github.com/python/cpython/issues/122288}: Improve the performances of @ref{184f,,fnmatch.translate()} by a
factor 1.7. Patch by Bénédikt Tran.

@item 
gh-88110@footnote{https://github.com/python/cpython/issues/88110}: Fixed @ref{252,,multiprocessing.Process} reporting a @code{.exitcode}
of 1 even on success when using the @code{"fork"} start method while using a
@ref{949,,concurrent.futures.ThreadPoolExecutor}.

@item 
gh-97514@footnote{https://github.com/python/cpython/issues/97514}: Authentication was added to the @ref{98,,multiprocessing}
forkserver start method control socket so that only processes with the
authentication key generated by the process that spawned the forkserver
can control it.  This is an enhancement over the other gh-97514@footnote{https://github.com/python/cpython/issues/97514} fixes
so that access is no longer limited only by filesystem permissions.

The file descriptor exchange of control pipes with the forked worker
process now requires an explicit acknowledgement byte to be sent over the
socket after the exchange on all forkserver supporting platforms. That
makes testing the above much easier.
@end itemize

@node ドキュメント<12>,Core and Builtins<36>,ライブラリ<40>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id161}@anchor{18ee}
@subsubsection ドキュメント



@itemize -

@item 
gh-127347@footnote{https://github.com/python/cpython/issues/127347}: Publicly expose @ref{18ef,,traceback.print_list()} in
@code{traceback.__all__}.
@end itemize

@node Core and Builtins<36>,ライブラリ<41>,ドキュメント<12>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id162}@anchor{18f0}
@subsubsection Core and Builtins



@itemize -

@item 
gh-127740@footnote{https://github.com/python/cpython/issues/127740}: Fix error message in @ref{190,,bytes.fromhex()} when given an odd
number of digits to properly indicate that an even number of hexadecimal
digits is required.

@item 
gh-127058@footnote{https://github.com/python/cpython/issues/127058}: @code{PySequence_Tuple} now creates the resulting tuple
atomically, preventing partially created tuples being visible to the
garbage collector or through @code{gc.get_referrers()}

@item 
gh-127599@footnote{https://github.com/python/cpython/issues/127599}: Fix statistics for increments of object reference counts (in
particular, when a reference count was increased by more than 1 in a
single operation).

@item 
gh-127651@footnote{https://github.com/python/cpython/issues/127651}: When raising @ref{65b,,ImportError} for missing symbols in @code{from}
imports, use @code{__file__} in the error message if @code{__spec__.origin} is
not a location

@item 
gh-127582@footnote{https://github.com/python/cpython/issues/127582}: Fix non-thread-safe object resurrection when calling finalizers
and watcher callbacks in the free threading build.

@item 
gh-127434@footnote{https://github.com/python/cpython/issues/127434}: The iOS compiler shims can now accept arguments with spaces.

@item 
gh-127536@footnote{https://github.com/python/cpython/issues/127536}: Add missing locks around some list assignment operations in the
free threading build.

@item 
gh-127085@footnote{https://github.com/python/cpython/issues/127085}: Fix race when exporting a buffer from a @ref{165,,memoryview}
object on the @ref{1f4,,free-threaded} build.

@item 
gh-127238@footnote{https://github.com/python/cpython/issues/127238}: Correct error message for @ref{18f1,,sys.set_int_max_str_digits()}.

@item 
gh-113841@footnote{https://github.com/python/cpython/issues/113841}: Fix possible undefined behavior division by zero in
@ref{197,,complex}'s @ref{18f2,,_Py_c_pow()}.
@end itemize

@node ライブラリ<41>,Core and Builtins<37>,Core and Builtins<36>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id163}@anchor{18f3}
@subsubsection ライブラリ



@itemize -

@item 
gh-127133@footnote{https://github.com/python/cpython/issues/127133}: Calling @ref{2eb,,argparse.ArgumentParser.add_argument_group()} on
an argument group, and calling
@ref{2eb,,argparse.ArgumentParser.add_argument_group()} or
@ref{2ed,,argparse.ArgumentParser.add_mutually_exclusive_group()} on a mutually
exclusive group now raise exceptions. This nesting was never supported,
often failed to work correctly, and was unintentionally exposed through
inheritance. This functionality has been deprecated since Python 3.11.
@end itemize

@node Core and Builtins<37>,C API<13>,ライブラリ<41>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id164}@anchor{18f4}
@subsubsection Core and Builtins



@itemize -

@item 
gh-126491@footnote{https://github.com/python/cpython/issues/126491}: Add a marking phase to the GC. All objects that can be
transitively reached from builtin modules or the stacks are marked as
reachable before cycle detection. This reduces the amount of work done by
the GC by approximately half.

@item 
gh-127020@footnote{https://github.com/python/cpython/issues/127020}: Fix a crash in the free threading build when
@ref{97c,,PyCode_GetCode()}, @ref{97d,,PyCode_GetVarnames()},
@ref{97e,,PyCode_GetCellvars()}, or @ref{97f,,PyCode_GetFreevars()} were called
from multiple threads at the same time.

@item 
gh-127010@footnote{https://github.com/python/cpython/issues/127010}: Simplify GC tracking of dictionaries. All dictionaries are
tracked when created, rather than being lazily tracked when a trackable
object was added to them. This simplifies the code considerably and
results in a slight speedup.

@item 
gh-126980@footnote{https://github.com/python/cpython/issues/126980}: Fix @ref{68c,,__buffer__()} of @ref{344,,bytearray} crashing
when @ref{18f5,,READ} or
@ref{18f6,,WRITE} are passed as flags.

@item 
gh-126937@footnote{https://github.com/python/cpython/issues/126937}: Fix @ref{198,,TypeError} when a @ref{1e5,,ctypes.Structure} has a
field size that doesn't fit into an unsigned 16-bit integer. Instead, the
maximum number of `bits' is @ref{13dd,,sys.maxsize}.

@item 
gh-126868@footnote{https://github.com/python/cpython/issues/126868}: Increase performance of @ref{19b,,int} by adding a freelist for
compact ints.

@item 
gh-126881@footnote{https://github.com/python/cpython/issues/126881}: Fix crash in finalization of dtoa state. Patch by Kumar Aditya.

@item 
gh-126892@footnote{https://github.com/python/cpython/issues/126892}: Require cold or invalidated code to "warm up" before being JIT
compiled again.

@item 
gh-126091@footnote{https://github.com/python/cpython/issues/126091}: Ensure stack traces are complete when throwing into a generator
chain that ends in a custom generator.

@item 
gh-126024@footnote{https://github.com/python/cpython/issues/126024}: Optimize decoding of short UTF-8 sequences containing non-ASCII
characters by approximately 15%.

@item 
gh-125420@footnote{https://github.com/python/cpython/issues/125420}: Add @ref{18f7,,memoryview.index()} to @ref{165,,memoryview} objects.
Patch by Bénédikt Tran.

@item 
gh-125420@footnote{https://github.com/python/cpython/issues/125420}: Add @ref{18f8,,memoryview.count()} to @ref{165,,memoryview} objects.
Patch by Bénédikt Tran.

@item 
gh-124470@footnote{https://github.com/python/cpython/issues/124470}: Fix crash in free-threaded builds when replacing object
dictionary while reading attribute on another thread

@item 
gh-69639@footnote{https://github.com/python/cpython/issues/69639}: Implement mixed-mode arithmetic rules combining real and complex
numbers as specified by C standards since C99.  Patch by Sergey B
Kirpichev.

@item 
gh-120010@footnote{https://github.com/python/cpython/issues/120010}: Correct invalid corner cases which resulted in @code{(nan+nanj)}
output in complex multiplication, e.g., @code{(1e300+1j)*(nan+infj)}.  Patch
by Sergey B Kirpichev.

@item 
gh-109746@footnote{https://github.com/python/cpython/issues/109746}: If @code{_thread.start_new_thread()} fails to start a new
thread, it deletes its state from interpreter and thus avoids its repeated
cleanup on finalization.
@end itemize

@node C API<13>,ビルド<13>,Core and Builtins<37>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id165}@anchor{18f9}
@subsubsection C API



@itemize -

@item 
gh-127896@footnote{https://github.com/python/cpython/issues/127896}: The previously undocumented function @ref{3d8,,PySequence_In()} is
@ref{23d,,soft deprecated}. Use @ref{3d9,,PySequence_Contains()} instead.

@item 
gh-127791@footnote{https://github.com/python/cpython/issues/127791}: Fix loss of callbacks after more than one call to
@ref{18fa,,PyUnstable_AtExit()}.

@item 
gh-127691@footnote{https://github.com/python/cpython/issues/127691}: The @ref{461,,Unicode Exception Objects} C API
now raises a @ref{198,,TypeError} if its exception argument is not a
@ref{462,,UnicodeError} object. Patch by Bénédikt Tran.

@item 
gh-123378@footnote{https://github.com/python/cpython/issues/123378}: Ensure that the value of @ref{18c1,,UnicodeEncodeError.end} retrieved by @ref{18fb,,PyUnicodeEncodeError_GetEnd()}
lies in @code{[min(1, objlen), max(min(1, objlen), objlen)]} where `objlen'
is the length of @ref{18fc,,UnicodeEncodeError.object}.
Similar arguments apply to @ref{c08,,UnicodeDecodeError} and
@ref{18fd,,UnicodeTranslateError} and their corresponding C interface. Patch by
Bénédikt Tran.

@item 
gh-127314@footnote{https://github.com/python/cpython/issues/127314}: Improve error message when calling the C API without an active
thread state on the @ref{1f4,,free-threaded} build.

@item 
gh-123378@footnote{https://github.com/python/cpython/issues/123378}: Ensure that the value of @ref{18c0,,UnicodeEncodeError.start} retrieved by @ref{18fe,,PyUnicodeEncodeError_GetStart()}
lies in @code{[0, max(0, objlen - 1)]} where `objlen' is the length of
@ref{18fc,,UnicodeEncodeError.object}. Similar arguments
apply to @ref{c08,,UnicodeDecodeError} and @ref{18fd,,UnicodeTranslateError} and
their corresponding C interface. Patch by Bénédikt Tran.

@item 
gh-109523@footnote{https://github.com/python/cpython/issues/109523}: Reading text from a non-blocking stream with @code{read} may now
raise a @ref{235,,BlockingIOError} if the operation cannot immediately return
bytes.

@item 
gh-102471@footnote{https://github.com/python/cpython/issues/102471}: Add a new import and export API for Python @ref{19b,,int} objects
(
@geindex Python Enhancement Proposals; PEP 757
PEP 757@footnote{https://peps.python.org/pep-0757/}):


@itemize *

@item 
@ref{3a7,,PyLong_GetNativeLayout()};

@item 
@ref{3a8,,PyLong_Export()};

@item 
@ref{3a9,,PyLong_FreeExport()};

@item 
@ref{3aa,,PyLongWriter_Create()};

@item 
@ref{3ab,,PyLongWriter_Finish()};

@item 
@ref{3ac,,PyLongWriter_Discard()}.
@end itemize

Patch by Victor Stinner.

@item 
gh-121058@footnote{https://github.com/python/cpython/issues/121058}: @code{PyThreadState_Clear()} now warns (and calls
@code{sys.excepthook}) if the thread state still has an active exception.
@end itemize

@node ビルド<13>,,C API<13>,Python 3 14 0 alpha 3
@anchor{whatsnew/changelog id166}@anchor{18ff}
@subsubsection ビルド



@itemize -

@item 
gh-127865@footnote{https://github.com/python/cpython/issues/127865}: Fix build failure on systems without thread-locals support.

@item 
gh-127629@footnote{https://github.com/python/cpython/issues/127629}: Emscripten builds now include ctypes support.

@item 
gh-127111@footnote{https://github.com/python/cpython/issues/127111}: Updated the Emscripten web example to use ES6 modules and be
built into a distinct @code{web_example} subfolder.

@item 
gh-115869@footnote{https://github.com/python/cpython/issues/115869}: Make @code{jit_stencils.h} (which is produced during JIT builds)
reproducible.

@item 
gh-126898@footnote{https://github.com/python/cpython/issues/126898}: The Emscripten build of Python is now based on ES6 modules.
@end itemize

@node Python 3 14 0 alpha 2,Python 3 14 0 alpha 1,Python 3 14 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-14-0-alpha-2}@anchor{1900}
@subsection Python 3.14.0 alpha 2


`Release date: 2024-11-19'

@menu
* Windows: Windows<13>. 
* Tools/Demos: Tools/Demos<14>. 
* テスト: テスト<12>. 
* セキュリティ: セキュリティ<15>. 
* ライブラリ: ライブラリ<42>. 
* ドキュメント: ドキュメント<13>. 
* Core and Builtins: Core and Builtins<38>. 
* ライブラリ: ライブラリ<43>. 
* Core and Builtins: Core and Builtins<39>. 
* ライブラリ: ライブラリ<44>. 
* Core and Builtins: Core and Builtins<40>. 
* ライブラリ: ライブラリ<45>. 
* C API: C API<14>. 
* ビルド: ビルド<14>. 

@end menu

@node Windows<13>,Tools/Demos<14>,,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id167}@anchor{1901}
@subsubsection Windows



@itemize -

@item 
gh-126911@footnote{https://github.com/python/cpython/issues/126911}: Update credits command output.

@item 
gh-118973@footnote{https://github.com/python/cpython/issues/118973}: Ensures the experimental free-threaded install includes the
@code{_tkinter} module. The optional Tcl/Tk component must also be installed
in order for the module to work.

@item 
gh-126497@footnote{https://github.com/python/cpython/issues/126497}: Fixes venv failure due to missing redirector executables in
experimental free-threaded installs.

@item 
gh-126074@footnote{https://github.com/python/cpython/issues/126074}: Removed unnecessary DLLs from Windows embeddable package

@item 
gh-125315@footnote{https://github.com/python/cpython/issues/125315}: Avoid crashing in @ref{af,,platform} due to slow WMI calls on some
Windows machines.

@item 
gh-126084@footnote{https://github.com/python/cpython/issues/126084}: Fix venvwlauncher to launch pythonw instead of python so no
extra console window is created.

@item 
gh-125842@footnote{https://github.com/python/cpython/issues/125842}: Fix a @ref{795,,SystemError} when @ref{277,,sys.exit()} is called with
@code{0xffffffff} on Windows.

@item 
gh-125550@footnote{https://github.com/python/cpython/issues/125550}: Enable the @ref{7da,,Python install manager} to detect Python 3.14 installs from
the Windows Store.

@item 
gh-123803@footnote{https://github.com/python/cpython/issues/123803}: All Windows code pages are now supported as "cpXXX" codecs on
Windows.
@end itemize

@node Tools/Demos<14>,テスト<12>,Windows<13>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id168}@anchor{1902}
@subsubsection Tools/Demos



@itemize -

@item 
gh-126807@footnote{https://github.com/python/cpython/issues/126807}: Fix extraction warnings in @code{pygettext.py} caused by
mistaking function definitions for function calls.

@item 
gh-126167@footnote{https://github.com/python/cpython/issues/126167}: The iOS testbed was modified so that it can be used by
third-party projects for testing purposes.
@end itemize

@node テスト<12>,セキュリティ<15>,Tools/Demos<14>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id169}@anchor{1903}
@subsubsection テスト



@itemize -

@item 
gh-126909@footnote{https://github.com/python/cpython/issues/126909}: Fix test_os extended attribute tests to work on filesystems
with 1 KiB xattr size limit.

@item 
gh-125730@footnote{https://github.com/python/cpython/issues/125730}: Change @code{make test} to not run GUI tests by default. Use
@code{make ci} to run tests with GUI tests instead.

@item 
gh-124295@footnote{https://github.com/python/cpython/issues/124295}: Add translation tests to the @ref{7,,argparse} module.
@end itemize

@node セキュリティ<15>,ライブラリ<42>,テスト<12>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id170}@anchor{1904}
@subsubsection セキュリティ



@itemize -

@item 
gh-126623@footnote{https://github.com/python/cpython/issues/126623}: Upgrade libexpat to 2.6.4
@end itemize

@node ライブラリ<42>,ドキュメント<13>,セキュリティ<15>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id171}@anchor{1905}
@subsubsection ライブラリ



@itemize -

@item 
gh-85957@footnote{https://github.com/python/cpython/issues/85957}: Add missing MIME types for images with RFCs: emf, fits, g3fax,
jp2, jpm, jpx, t38, tiff-fx and wmf. Patch by Hugo van Kemenade.

@item 
gh-126920@footnote{https://github.com/python/cpython/issues/126920}: Fix the @code{prefix} and @code{exec_prefix} keys from
@ref{298,,sysconfig.get_config_vars()} incorrectly having the same value as
@ref{3e6,,sys.base_prefix} and @ref{3ea,,sys.base_exec_prefix},
respectively, inside virtual environments. They now accurately reflect
@ref{3e7,,sys.prefix} and @ref{3eb,,sys.exec_prefix}.

@item 
gh-67877@footnote{https://github.com/python/cpython/issues/67877}: Fix memory leaks when @ref{be,,regular expression} matching
terminates abruptly, either because of a signal or because memory
allocation fails.

@item 
gh-125063@footnote{https://github.com/python/cpython/issues/125063}: @ref{91,,marshal} now supports @ref{694,,slice} objects. The marshal
format version was increased to 5.

@item 
gh-126789@footnote{https://github.com/python/cpython/issues/126789}: Fixed the values of @ref{298,,sysconfig.get_config_vars()},
@ref{340,,sysconfig.get_paths()}, and their siblings when the @ref{cc,,site}
initialization happens after @ref{e1,,sysconfig} has built a cache for
@ref{298,,sysconfig.get_config_vars()}.

@item 
gh-126188@footnote{https://github.com/python/cpython/issues/126188}: Update bundled pip to 24.3.1

@item 
gh-126766@footnote{https://github.com/python/cpython/issues/126766}: Fix issue where @ref{2bd,,urllib.request.url2pathname()} failed to
discard two leading slashes introducing an empty authority section.

@item 
gh-126705@footnote{https://github.com/python/cpython/issues/126705}: Allow @ref{e4b,,os.PathLike} to be a base for Protocols.

@item 
gh-126699@footnote{https://github.com/python/cpython/issues/126699}: Allow @ref{fde,,collections.abc.AsyncIterator} to be a base for
Protocols.

@item 
gh-126654@footnote{https://github.com/python/cpython/issues/126654}: Fix crash when non-dict was passed to several functions in
@code{_interpreters} module.

@item 
gh-104745@footnote{https://github.com/python/cpython/issues/104745}: Limit starting a patcher (from @ref{1092,,unittest.mock.patch()} or
@ref{1906,,unittest.mock.patch.object()}) more than once without stopping it

@item 
gh-126595@footnote{https://github.com/python/cpython/issues/126595}: Fix a crash when instantiating @ref{149b,,itertools.count} with an
initial count of @ref{13dd,,sys.maxsize} on debug builds. Patch by Bénédikt
Tran.

@item 
gh-120423@footnote{https://github.com/python/cpython/issues/120423}: Fix issue where @ref{2bf,,urllib.request.pathname2url()} mishandled
Windows paths with embedded forward slashes.

@item 
gh-126565@footnote{https://github.com/python/cpython/issues/126565}: Improve performances of @ref{1907,,zipfile.Path.open()} for
non-reading modes.

@item 
gh-126505@footnote{https://github.com/python/cpython/issues/126505}: Fix bugs in compiling case-insensitive @ref{be,,regular expressions} with character classes containing non-BMP characters:
upper-case non-BMP character did was ignored and the ASCII flag was
ignored when matching a character range whose upper bound is beyond the
BMP region.

@item 
gh-117378@footnote{https://github.com/python/cpython/issues/117378}: Fixed the @ref{98,,multiprocessing} @code{"forkserver"} start method
forkserver process to correctly inherit the parent's @ref{3e4,,sys.path}
during the importing of @ref{1908,,multiprocessing.set_forkserver_preload()}
modules in the same manner as @ref{3e4,,sys.path} is configured in workers
before executing work items.

This bug caused some forkserver module preloading to silently fail to
preload. This manifested as a performance degradation in child processes
when the @code{sys.path} was required due to additional repeated work in
every worker.

It could also have a side effect of @code{""} remaining in @ref{3e4,,sys.path}
during forkserver preload imports instead of the absolute path from
@ref{1909,,os.getcwd()} at multiprocessing import time used in the worker
@code{sys.path}.

The @code{sys.path} differences between phases in the child process could
potentially have caused preload to import incorrect things from the wrong
location.  We are unaware of that actually having happened in practice.

@item 
gh-125679@footnote{https://github.com/python/cpython/issues/125679}: The @ref{1853,,multiprocessing.Lock} and
@ref{1854,,multiprocessing.RLock} @code{repr} values no longer say "unknown" on
macOS.

@item 
gh-126476@footnote{https://github.com/python/cpython/issues/126476}: Raise @ref{190a,,calendar.IllegalMonthError} (now a subclass of
@ref{174e,,IndexError}) for @ref{190b,,calendar.month()} when the input month is
not correct.

@item 
gh-126489@footnote{https://github.com/python/cpython/issues/126489}: The Python implementation of @ref{ab,,pickle} no longer calls
@ref{190c,,pickle.Pickler.persistent_id()} for the result of
@code{persistent_id()}.

@item 
gh-126451@footnote{https://github.com/python/cpython/issues/126451}: Register the @ref{177,,contextvars.Context} type to
@ref{ac7,,collections.abc.Mapping}.

@item 
gh-126175@footnote{https://github.com/python/cpython/issues/126175}: Add @code{msg}, @code{doc}, @code{pos}, @code{lineno} and @code{colno}
attributes to @ref{190d,,tomllib.TOMLDecodeError}. Deprecate instantiating with
free-form arguments.

@item 
gh-89416@footnote{https://github.com/python/cpython/issues/89416}: Add 
@geindex RFC; RFC 9559
RFC 9559@footnote{https://datatracker.ietf.org/doc/html/rfc9559.html} MIME types for Matroska audiovisual container
formats. Patch by Hugo van Kemenade.

@item 
gh-126417@footnote{https://github.com/python/cpython/issues/126417}: Register the @code{multiprocessing.managers.DictProxy} and
@code{multiprocessing.managers.ListProxy} types in
@ref{9b,,multiprocessing.managers} to @ref{12c0,,collections.abc.MutableMapping}
and @ref{4bf,,collections.abc.MutableSequence}, respectively.

@item 
gh-126390@footnote{https://github.com/python/cpython/issues/126390}: Add support for returning intermixed options and non-option
arguments in order in @ref{16d3,,getopt.gnu_getopt()}.

@item 
gh-126374@footnote{https://github.com/python/cpython/issues/126374}: Add support for options with optional arguments in the
@ref{65,,getopt} module.

@item 
gh-126363@footnote{https://github.com/python/cpython/issues/126363}: Speed up pattern parsing in @ref{537,,pathlib.Path.glob()} by
skipping creation of a @ref{266,,pathlib.Path} object for the pattern.

@item 
gh-126353@footnote{https://github.com/python/cpython/issues/126353}: @ref{2f2,,asyncio.get_event_loop()} now does not implicitly creates
an event loop. It now raises a @ref{244,,RuntimeError} if there is no set
event loop. Patch by Kumar Aditya.

@item 
gh-126313@footnote{https://github.com/python/cpython/issues/126313}: Fix an issue in @ref{190e,,curses.napms()} when
@ref{190f,,curses.initscr()} has not yet been called. Patch by Bénédikt Tran.

@item 
gh-126303@footnote{https://github.com/python/cpython/issues/126303}: Fix pickling and copying of @ref{1910,,os.sched_param} objects.

@item 
gh-126138@footnote{https://github.com/python/cpython/issues/126138}: Fix a use-after-free crash on @ref{1c7,,asyncio.Task} objects
whose underlying coroutine yields an object that implements an evil
@ref{dcb,,__getattribute__()}. Patch by Nico Posada.

@item 
gh-120057@footnote{https://github.com/python/cpython/issues/120057}: Replace the @code{os.environ.refresh()} method with a new
@ref{258,,os.reload_environ()} function. Patch by Victor Stinner.

@item 
gh-126220@footnote{https://github.com/python/cpython/issues/126220}: Fix crash in @code{cProfile.Profile} and
@code{_lsprof.Profiler} when their callbacks were directly called with
0 arguments.

@item 
gh-126212@footnote{https://github.com/python/cpython/issues/126212}: Fix issue where @ref{2bf,,urllib.request.pathname2url()} and
@ref{2bd,,url2pathname()} removed slashes from Windows DOS
drive paths and URLs.

@item 
gh-126223@footnote{https://github.com/python/cpython/issues/126223}: Raise a @ref{887,,UnicodeEncodeError} instead of a
@ref{795,,SystemError} upon calling @code{_interpreters.create()} with an
invalid Unicode character.

@item 
gh-126205@footnote{https://github.com/python/cpython/issues/126205}: Fix issue where @ref{2bf,,urllib.request.pathname2url()} generated
URLs beginning with four slashes (rather than two) when given a Windows
UNC path.

@item 
gh-126156@footnote{https://github.com/python/cpython/issues/126156}: Improved performances of creating
@ref{dfe,,Morsel} objects by a factor of 3.8x.

@item 
gh-126105@footnote{https://github.com/python/cpython/issues/126105}: Fix a crash in @ref{9,,ast} when the @ref{17d7,,ast.AST._fields}
attribute is deleted.

@item 
gh-126106@footnote{https://github.com/python/cpython/issues/126106}: Fixes a possible @code{NULL} pointer dereference in @ref{d5,,ssl}.

@item 
gh-126080@footnote{https://github.com/python/cpython/issues/126080}: Fix a use-after-free crash on @ref{1c7,,asyncio.Task} objects for
which the underlying event loop implements an evil
@ref{dcb,,__getattribute__()}. Reported by Nico-Posada. Patch by
Bénédikt Tran.

@item 
gh-125322@footnote{https://github.com/python/cpython/issues/125322}: Correct detection of complex numbers support in libffi.

@item 
gh-126083@footnote{https://github.com/python/cpython/issues/126083}: Fixed a reference leak in @ref{1c7,,asyncio.Task} objects when
reinitializing the same object with a non-@code{None} context. Patch by Nico
Posada.

@item 
gh-126068@footnote{https://github.com/python/cpython/issues/126068}: Fix exceptions in the @ref{7,,argparse} module so that only error
messages for ArgumentError and ArgumentTypeError are now translated.
ArgumentError is now only used for command line errors, not for logical
errors in the program. TypeError is now raised instead of ValueError for
some logical errors.

@item 
gh-125413@footnote{https://github.com/python/cpython/issues/125413}: Add @code{pathlib.Path.scandir()} method to efficiently fetch
directory children and their file attributes. This is a trivial wrapper of
@ref{c54,,os.scandir()}.

@item 
gh-125984@footnote{https://github.com/python/cpython/issues/125984}: Fix use-after-free crashes on @ref{dc6,,asyncio.Future} objects
for which the underlying event loop implements an evil
@ref{dcb,,__getattribute__()}. Reported by Nico-Posada. Patch by
Bénédikt Tran.

@item 
gh-125926@footnote{https://github.com/python/cpython/issues/125926}: Fix @ref{1096,,urllib.parse.urljoin()} for base URI with undefined
authority. Although 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html} only specify reference resolution for
absolute base URI, @code{urljoin()} should continue to return sensible
result for relative base URI.

@item 
gh-125969@footnote{https://github.com/python/cpython/issues/125969}: Fix an out-of-bounds crash when an evil
@ref{cfa,,asyncio.loop.call_soon()} mutates the length of the internal
callbacks list. Patch by Bénédikt Tran.

@item 
gh-125966@footnote{https://github.com/python/cpython/issues/125966}: Fix a use-after-free crash in
@ref{1911,,asyncio.Future.remove_done_callback()}. Patch by Bénédikt Tran.

@item 
gh-125789@footnote{https://github.com/python/cpython/issues/125789}: Fix possible crash when mutating list of callbacks returned by
@code{asyncio.Future._callbacks}. It now always returns a new copy in C
implementation @code{_asyncio}. Patch by Kumar Aditya.

@item 
gh-126916@footnote{https://github.com/python/cpython/issues/126916}: Allow the `initial' parameter of @ref{21a,,functools.reduce()} to be
passed as a keyword argument. Patch by Sayandip Dutta.

@item 
gh-124452@footnote{https://github.com/python/cpython/issues/124452}: Fix an issue in
@ref{1912,,email.policy.EmailPolicy.header_source_parse()} and
@ref{1913,,email.policy.Compat32.header_source_parse()} that introduced spurious
leading whitespaces into header values when the header includes a newline
character after the header name delimiter (@code{:}) and before the value.

@item 
gh-117941@footnote{https://github.com/python/cpython/issues/117941}: @code{argparse.BooleanOptionalAction} now rejects option
names starting with @code{--no-}.

@item 
gh-125884@footnote{https://github.com/python/cpython/issues/125884}: Fixed the bug for @ref{aa,,pdb} where it can't set breakpoints on
functions with certain annotations.

@item 
gh-125355@footnote{https://github.com/python/cpython/issues/125355}: Fix several bugs in
@ref{cf7,,argparse.ArgumentParser.parse_intermixed_args()}.


@itemize *

@item 
The parser no longer changes temporarily during parsing.

@item 
Default values are not processed twice.

@item 
Required mutually exclusive groups containing positional arguments are now supported.

@item 
The missing arguments report now includes the names of all required optional and positional arguments.

@item 
Unknown options can be intermixed with positional arguments in parse_known_intermixed_args().
@end itemize

@item 
gh-125767@footnote{https://github.com/python/cpython/issues/125767}: @ref{1a6,,super} objects are now @ref{ab,,pickleable} and
@ref{29,,copyable}.

@item 
gh-124969@footnote{https://github.com/python/cpython/issues/124969}: @code{locale.nl_langinfo(locale.ALT_DIGITS)} now returns a string
again. The returned value consists of up to 100 semicolon-separated
symbols.

@item 
gh-84850@footnote{https://github.com/python/cpython/issues/84850}: Remove @code{URLopener} and @code{FancyURLopener} classes
from @ref{111,,urllib.request}. They had previously raised
@ref{1a3,,DeprecationWarning} since Python 3.3.

@item 
gh-125666@footnote{https://github.com/python/cpython/issues/125666}: Avoid the exiting the interpreter if a null byte is given as
input in the new REPL.

@item 
gh-125710@footnote{https://github.com/python/cpython/issues/125710}: [Enum] fix hashable<->nonhashable comparisons for member values

@item 
gh-125631@footnote{https://github.com/python/cpython/issues/125631}: Restore ability to set @ref{190c,,persistent_id}
and @ref{1914,,persistent_load} attributes of instances of
the @code{Pickler} and @code{Unpickler} classes in the @ref{ab,,pickle}
module.

@item 
gh-125378@footnote{https://github.com/python/cpython/issues/125378}: Fixed the bug in @ref{aa,,pdb} where after a multi-line command,
an empty line repeats the first line of the multi-line command, instead of
the full command.

@item 
gh-125682@footnote{https://github.com/python/cpython/issues/125682}: Reject non-ASCII digits in the Python implementation of
@ref{b4e,,json.loads()} conforming to the JSON specification.

@item 
gh-125660@footnote{https://github.com/python/cpython/issues/125660}: Reject invalid unicode escapes for Python implementation of
@ref{b4e,,json.loads()}.

@item 
gh-52551@footnote{https://github.com/python/cpython/issues/52551}: Use @code{wcsftime()} to implement @ref{1402,,time.strftime()} on
Windows.

@item 
gh-125259@footnote{https://github.com/python/cpython/issues/125259}: Fix the notes removal logic for errors thrown in enum
initialization.

@item 
gh-125633@footnote{https://github.com/python/cpython/issues/125633}: Add function @ref{232,,inspect.ispackage()} to determine whether an
object is a @ref{233,,package} or not.

@item 
gh-125614@footnote{https://github.com/python/cpython/issues/125614}: In the @ref{15f,,FORWARDREF} format of
@ref{6,,annotationlib}, fix bug where nested expressions were not returned
as @ref{1776,,annotationlib.ForwardRef} format.

@item 
gh-125590@footnote{https://github.com/python/cpython/issues/125590}: Allow @code{FrameLocalsProxy} to delete and pop if the key is not
a fast variable.

@item 
gh-125600@footnote{https://github.com/python/cpython/issues/125600}: Only show stale code warning in @ref{aa,,pdb} when we display
source code.

@item 
gh-125542@footnote{https://github.com/python/cpython/issues/125542}: Deprecate passing keyword-only `prefix_chars' argument to
@ref{2eb,,argparse.ArgumentParser.add_argument_group()}.

@item 
gh-125541@footnote{https://github.com/python/cpython/issues/125541}: Pressing @code{Ctrl}-@code{C} while blocked in
@ref{8a7,,threading.Lock.acquire()}, @ref{107b,,threading.RLock.acquire()}, and
@ref{13fd,,threading.Thread.join()} now interrupts the function call and raises
a @ref{bc5,,KeyboardInterrupt} exception on Windows, similar to how those
functions behave on macOS and Linux.

@item 
gh-125519@footnote{https://github.com/python/cpython/issues/125519}: Improve traceback if @ref{73d,,importlib.reload()} is called with an
object that is not a module. Patch by Alex Waygood.

@item 
gh-125451@footnote{https://github.com/python/cpython/issues/125451}: Fix deadlock when
@ref{1d6,,concurrent.futures.ProcessPoolExecutor} shuts down concurrently
with an error when feeding a job to a worker process.

@item 
gh-125115@footnote{https://github.com/python/cpython/issues/125115}: Fixed a bug in @ref{aa,,pdb} where arguments starting with @code{-}
can't be passed to the debugged script.

@item 
gh-125398@footnote{https://github.com/python/cpython/issues/125398}: Fix the conversion of the @code{VIRTUAL_ENV} path in the
activate script in @ref{117,,venv} when running in Git Bash for Windows.

@item 
gh-125245@footnote{https://github.com/python/cpython/issues/125245}: Fix race condition when importing @ref{1f,,collections.abc}, which
could incorrectly return an empty module.

@item 
gh-52551@footnote{https://github.com/python/cpython/issues/52551}: Fix encoding issues in @ref{1402,,time.strftime()}, the
@ref{e8e,,strftime()} method of the @ref{34,,datetime} classes
@ref{4e2,,datetime}, @ref{1fa,,date} and
@ref{1fb,,time} and formatting of these classes. Characters not
encodable in the current locale are now acceptable in the format string.
Surrogate pairs and sequence of surrogatescape-encoded bytes are no longer
recombinated. Embedded null character no longer terminates the format
string.

@item 
gh-124984@footnote{https://github.com/python/cpython/issues/124984}: Fixed thread safety in @ref{d5,,ssl} in the free-threaded build.
OpenSSL operations are now protected by a per-object lock.

@item 
gh-124651@footnote{https://github.com/python/cpython/issues/124651}: Properly quote template strings in @ref{117,,venv} activation
scripts.

@item 
gh-124694@footnote{https://github.com/python/cpython/issues/124694}: We've added
@ref{1d2,,concurrent.futures.InterpreterPoolExecutor}, which allows you to
run code in multiple isolated interpreters.  This allows you to circumvent
the limitations of CPU-bound threads (due to the GIL). Patch by Eric Snow.

This addition is unrelated to 
@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}.

@item 
gh-58032@footnote{https://github.com/python/cpython/issues/58032}: Deprecate the @ref{30c,,argparse.FileType} type converter.

@item 
gh-99749@footnote{https://github.com/python/cpython/issues/99749}: Adds a feature to optionally enable suggestions for argument
choices and subparser names if mistyped by the user.

@item 
gh-58956@footnote{https://github.com/python/cpython/issues/58956}: Fixed a bug in @ref{aa,,pdb} where sometimes the breakpoint won't
trigger if it was set on a function which is already in the call stack.

@item 
gh-124111@footnote{https://github.com/python/cpython/issues/124111}: The tkinter module can now be built to use either the new
version 9.0.0 of Tcl/Tk or the latest release 8.6.15 of Tcl/Tk 8.  Tcl/Tk
9 includes many improvements, both to the Tcl language and to the
appearance and utility of the graphical user interface provided by Tk.

@item 
gh-80958@footnote{https://github.com/python/cpython/issues/80958}: unittest discovery supports PEP 420 namespace packages as start
directory again.

@item 
gh-123370@footnote{https://github.com/python/cpython/issues/123370}: Fix the canvas not clearing after running turtledemo clock.

@item 
gh-89083@footnote{https://github.com/python/cpython/issues/89083}: Add @ref{2c4,,uuid.uuid8()} for generating UUIDv8 objects as
specified in 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}. Patch by Bénédikt Tran

@item 
gh-122549@footnote{https://github.com/python/cpython/issues/122549}: Add @ref{27d,,platform.invalidate_caches()} to invalidate cached
results.

@item 
gh-120754@footnote{https://github.com/python/cpython/issues/120754}: Update unbounded @code{read} calls in @ref{137,,zipfile} to specify an
explicit @code{size} putting a limit on how much data they may read. This
also updates handling around ZIP max comment size to match the standard
instead of reading comments that are one byte too long.

@item 
gh-121267@footnote{https://github.com/python/cpython/issues/121267}: Improve the performance of @ref{e4,,tarfile} when writing files,
by caching user names and group names.

@item 
gh-70764@footnote{https://github.com/python/cpython/issues/70764}: Fixed an issue where @ref{12ec,,inspect.getclosurevars()} would
incorrectly classify an attribute name as a global variable when the name
exists both as an attribute name and a global variable.

@item 
gh-118289@footnote{https://github.com/python/cpython/issues/118289}: @code{posixpath.realpath()} now raises
@ref{1265,,NotADirectoryError} when `strict' mode is enabled and a
non-directory path with a trailing slash is supplied.

@item 
gh-119826@footnote{https://github.com/python/cpython/issues/119826}: Always return an absolute path for @ref{1532,,os.path.abspath()} on
Windows.

@item 
gh-97850@footnote{https://github.com/python/cpython/issues/97850}: Remove deprecated @code{pkgutil.get_loader()} and
@code{pkgutil.find_loader()}.

@item 
gh-118986@footnote{https://github.com/python/cpython/issues/118986}: Add @code{socket.IPV6_RECVERR} constant (available since
Linux 2.2).

@item 
gh-116897@footnote{https://github.com/python/cpython/issues/116897}: Accepting objects with false values (like @code{0} and @code{[]})
except empty strings, byte-like objects and @code{None} in
@ref{110,,urllib.parse} functions @ref{31e,,parse_qsl()} and
@ref{31f,,parse_qs()} is now deprecated.

@item 
gh-101955@footnote{https://github.com/python/cpython/issues/101955}: Fix SystemError when match regular expression pattern
containing some combination of possessive quantifier, alternative and
capture group.

@item 
gh-71936@footnote{https://github.com/python/cpython/issues/71936}: Fix a race condition in @ref{116d,,multiprocessing.pool.Pool}.

@item 
bpo-46128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46128}: Strip @ref{361,,unittest.IsolatedAsyncioTestCase} stack frames
from reported stacktraces.

@item 
gh-84852@footnote{https://github.com/python/cpython/issues/84852}: Add MIME types for MS Embedded OpenType, OpenType Layout,
TrueType, WOFF 1.0 and 2.0 fonts. Patch by Sahil Prajapati and Hugo van
Kemenade.
@end itemize

@node ドキュメント<13>,Core and Builtins<38>,ライブラリ<42>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id172}@anchor{1915}
@subsubsection ドキュメント



@itemize -

@item 
gh-126622@footnote{https://github.com/python/cpython/issues/126622}: Added stub pages for removed modules explaining their removal,
where to find replacements, and linking to the last Python version that
supported them. Contributed by Ned Batchelder.

@item 
gh-125277@footnote{https://github.com/python/cpython/issues/125277}: Require Sphinx 7.2.6 or later to build the Python
documentation. Patch by Adam Turner.

@item 
gh-60712@footnote{https://github.com/python/cpython/issues/60712}: Include the @ref{c7e,,object} type in the lists of documented
types. Change by Furkan Onder and Martin Panter.
@end itemize

@node Core and Builtins<38>,ライブラリ<43>,ドキュメント<13>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id173}@anchor{1916}
@subsubsection Core and Builtins



@itemize -

@item 
gh-126795@footnote{https://github.com/python/cpython/issues/126795}: Increase the threshold for JIT code warmup. Depending on
platform and workload, this can result in performance gains of 1-9% and
memory savings of 3-5%.

@item 
gh-126341@footnote{https://github.com/python/cpython/issues/126341}: Now @ref{2ec,,ValueError} is raised instead of @ref{795,,SystemError}
when trying to iterate over a released @ref{165,,memoryview} object.

@item 
gh-126688@footnote{https://github.com/python/cpython/issues/126688}: Fix a crash when calling @ref{4b5,,os.fork()} on some operating
systems, including SerenityOS.
@end itemize

@node ライブラリ<43>,Core and Builtins<39>,Core and Builtins<38>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id174}@anchor{1917}
@subsubsection ライブラリ



@itemize -

@item 
gh-126066@footnote{https://github.com/python/cpython/issues/126066}: Fix @ref{7b,,importlib} to not write an incomplete .pyc files when
a ulimit or some other operating system mechanism is preventing the write
to go through fully.
@end itemize

@node Core and Builtins<39>,ライブラリ<44>,ライブラリ<43>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id175}@anchor{1918}
@subsubsection Core and Builtins



@itemize -

@item 
gh-126222@footnote{https://github.com/python/cpython/issues/126222}: Do not include count of "peek" items in @code{_PyUop_num_popped}.
This ensures that the correct number of items are popped from the stack
when a micro-op exits with an error.

@item 
gh-126366@footnote{https://github.com/python/cpython/issues/126366}: Fix crash when using @code{yield from} on an object that raises an
exception in its @code{__iter__}.
@end itemize

@node ライブラリ<44>,Core and Builtins<40>,Core and Builtins<39>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id176}@anchor{1919}
@subsubsection ライブラリ



@itemize -

@item 
gh-126209@footnote{https://github.com/python/cpython/issues/126209}: Fix an issue with @code{skip_file_prefixes} parameter which
resulted in an inconsistent behaviour between the C and Python
implementations of @ref{1732,,warnings.warn()}. Patch by Daehee Kim.
@end itemize

@node Core and Builtins<40>,ライブラリ<45>,ライブラリ<44>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id177}@anchor{191a}
@subsubsection Core and Builtins



@itemize -

@item 
gh-126312@footnote{https://github.com/python/cpython/issues/126312}: Fix crash during garbage collection on an object frozen by
@ref{d2e,,gc.freeze()} on the free-threaded build.

@item 
gh-103951@footnote{https://github.com/python/cpython/issues/103951}: Relax optimization requirements to allow fast attribute access
to module subclasses.

@item 
gh-126072@footnote{https://github.com/python/cpython/issues/126072}: Following gh-126101@footnote{https://github.com/python/cpython/issues/126101}, for @ref{7d2,,コードオブジェクト} like lambda,
annotation and type alias, we no longer  add @code{None} to its
@ref{189b,,co_consts}.

@item 
gh-126195@footnote{https://github.com/python/cpython/issues/126195}: Improve JIT performance by 1.4% on macOS Apple Silicon by using
platform-specific memory protection APIs. Patch by Diego Russo.

@item 
gh-126139@footnote{https://github.com/python/cpython/issues/126139}: Provide better error location when attempting to use a
@ref{fad,,future statement} with an unknown future feature.

@item 
gh-126072@footnote{https://github.com/python/cpython/issues/126072}: Add a new attribute in @ref{18db,,co_flags} to indicate
whether the first item in @ref{189b,,co_consts} is the docstring.
If a code object has no docstring, @code{None} will `NOT' be inserted.

@item 
gh-126076@footnote{https://github.com/python/cpython/issues/126076}: Relocated objects such as @code{tuple}, @code{bytes} and @code{str}
objects are properly tracked by @ref{105,,tracemalloc} and its associated
hooks. Patch by Pablo Galindo.

@item 
gh-90370@footnote{https://github.com/python/cpython/issues/90370}: Avoid temporary tuple creation for vararg in argument passing
with Argument Clinic generated code (if arguments either vararg or
positional-only).

@item 
gh-126018@footnote{https://github.com/python/cpython/issues/126018}: Fix a crash in @ref{191b,,sys.audit()} when passing a non-string as
first argument and Python was compiled in debug mode.

@item 
gh-126012@footnote{https://github.com/python/cpython/issues/126012}: The @ref{165,,memoryview} type now supports subscription, making
it a @ref{1a1,,generic type}.

@item 
gh-125837@footnote{https://github.com/python/cpython/issues/125837}: Adds @ref{36e,,LOAD_SMALL_INT} and @ref{375,,LOAD_CONST_IMMORTAL}
instructions. @code{LOAD_SMALL_INT} pushes a small integer equal to the
@code{oparg} to the stack. @code{LOAD_CONST_IMMORTAL} does the same as
@code{LOAD_CONST} but is more efficient for immortal objects. Removes
@code{RETURN_CONST}  instruction.

@item 
gh-125942@footnote{https://github.com/python/cpython/issues/125942}: On Android, the @code{errors} setting of @ref{ccd,,sys.stdout} was
changed from @code{surrogateescape} to @code{backslashreplace}.

@item 
gh-125859@footnote{https://github.com/python/cpython/issues/125859}: Fix a crash in the free threading build when
@ref{a04,,gc.get_objects()} or @ref{a05,,gc.get_referrers()} is called during an
in-progress garbage collection.

@item 
gh-125868@footnote{https://github.com/python/cpython/issues/125868}: It was possible in 3.14.0a1 only for attribute lookup to give
the wrong value. This was due to an incorrect specialization in very
specific circumstances. This is fixed in 3.14.0a2.

@item 
gh-125498@footnote{https://github.com/python/cpython/issues/125498}: The JIT has been updated to leverage Clang 19’s new
@code{preserve_none} attribute, which supports more platforms and is more
useful than LLVM's existing @code{ghccc} calling convention. This also
removes the need to manually patch the calling convention in LLVM IR,
simplifying the JIT compilation process.

@item 
gh-125703@footnote{https://github.com/python/cpython/issues/125703}: Correctly honour @ref{105,,tracemalloc} hooks in specialized
@code{Py_DECREF} paths. Patch by Pablo Galindo

@item 
gh-125593@footnote{https://github.com/python/cpython/issues/125593}: Use color to highlight error locations in traceback from
exception group

@item 
gh-125017@footnote{https://github.com/python/cpython/issues/125017}: Fix crash on certain accesses to the @code{__annotations__} of
@ref{453,,staticmethod} and @ref{48e,,classmethod} objects.

@item 
gh-125588@footnote{https://github.com/python/cpython/issues/125588}: The Python PEG generator can now use f-strings in the grammar
actions. Patch by Pablo Galindo

@item 
gh-125444@footnote{https://github.com/python/cpython/issues/125444}: Fix illegal instruction for older Arm architectures. Patch by
Diego Russo, testing by Ross Burton.

@item 
gh-118423@footnote{https://github.com/python/cpython/issues/118423}: Add a new @code{INSTRUCTION_SIZE} macro to the cases generator
which returns the current instruction size.

@item 
gh-125038@footnote{https://github.com/python/cpython/issues/125038}: Fix crash when iterating over a generator expression after
direct changes on @code{gi_frame.f_locals}. Patch by Mikhail Efimov.

@item 
gh-124855@footnote{https://github.com/python/cpython/issues/124855}: Don't allow the JIT and perf support to be active at the same
time. Patch by Pablo Galindo

@item 
gh-123714@footnote{https://github.com/python/cpython/issues/123714}: Update JIT compilation to use LLVM 19

@item 
gh-123930@footnote{https://github.com/python/cpython/issues/123930}: Improve the error message when a script shadowing a module from
the standard library causes @ref{65b,,ImportError} to be raised during a
"from" import. Similarly, improve the error message when a script
shadowing a third party module attempts to "from" import an attribute from
that third party module while still initialising.

@item 
gh-119793@footnote{https://github.com/python/cpython/issues/119793}: The @ref{19f,,map()} built-in now has an optional keyword-only
`strict' flag like @ref{1a0,,zip()} to check that all the iterables are of
equal length. Patch by Wannes Boeykens.
@end itemize

@node ライブラリ<45>,C API<14>,Core and Builtins<40>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id178}@anchor{191c}
@subsubsection ライブラリ



@itemize -

@item 
gh-118950@footnote{https://github.com/python/cpython/issues/118950}: Fix bug where SSLProtocol.connection_lost wasn't getting called
when OSError was thrown on writing to socket.

@item 
gh-113570@footnote{https://github.com/python/cpython/issues/113570}: Fixed a bug in @code{reprlib.repr} where it incorrectly called the
repr method on shadowed Python built-in types.
@end itemize

@node C API<14>,ビルド<14>,ライブラリ<45>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id179}@anchor{191d}
@subsubsection C API



@itemize -

@item 
gh-126554@footnote{https://github.com/python/cpython/issues/126554}: Fix error handling in @ref{bdc,,ctypes.CDLL} objects which could
result in a crash in rare situations.

@item 
gh-126061@footnote{https://github.com/python/cpython/issues/126061}: Add @ref{39b,,PyLong_IsPositive()}, @ref{39c,,PyLong_IsNegative()}
and @ref{39d,,PyLong_IsZero()} for checking if a @ref{39e,,PyLongObject} is
positive, negative, or zero, respectively.

@item 
gh-125608@footnote{https://github.com/python/cpython/issues/125608}: Fix a bug where dictionary watchers (e.g.,
@ref{784,,PyDict_Watch()}) on an object's attribute dictionary
(@ref{77d,,__dict__}) were not triggered when the object's attributes
were modified.

@item 
gh-123619@footnote{https://github.com/python/cpython/issues/123619}: Added the @ref{3c5,,PyUnstable_Object_EnableDeferredRefcount()}
function for enabling 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/} deferred reference counting.

@item 
gh-121654@footnote{https://github.com/python/cpython/issues/121654}: Add @ref{3af,,PyType_Freeze()} function to make a type immutable.
Patch by Victor Stinner.

@item 
gh-120026@footnote{https://github.com/python/cpython/issues/120026}: The @code{Py_HUGE_VAL} macro is @ref{23d,,soft deprecated}.
@end itemize

@node ビルド<14>,,C API<14>,Python 3 14 0 alpha 2
@anchor{whatsnew/changelog id180}@anchor{191e}
@subsubsection ビルド



@itemize -

@item 
gh-126691@footnote{https://github.com/python/cpython/issues/126691}: Removed the @code{--with-emscripten-target} configure flag. We
unified the @code{node} and @code{browser} options and the same build can now be
used, independent of target runtime.

@item 
gh-123877@footnote{https://github.com/python/cpython/issues/123877}: Use @code{wasm32-wasip1} as the target triple for WASI instead of
@code{wasm32-wasi}. The latter will eventually be reclaimed for WASI 1.0
while CPython currently only supports WASI preview1.

@item 
gh-126458@footnote{https://github.com/python/cpython/issues/126458}: Disable SIMD support for HACL under WASI.

@item 
gh-89640@footnote{https://github.com/python/cpython/issues/89640}: Hard-code float word ordering as little endian on WASM.

@item 
gh-126206@footnote{https://github.com/python/cpython/issues/126206}: @code{make clinic} now runs Argument Clinic using the @code{--force}
option, thus forcefully regenerating generated code.

@item 
gh-126187@footnote{https://github.com/python/cpython/issues/126187}: Introduced @code{Tools/wasm/emscripten.py} to simplify doing
Emscripten builds.

@item 
gh-124932@footnote{https://github.com/python/cpython/issues/124932}: For cross builds, there is now support for having a different
install @code{prefix} than the @code{host_prefix} used by @code{getpath.py}. This
is set to @code{/} by default for Emscripten, on other platforms the default
behavior is the same as before.

@item 
gh-125946@footnote{https://github.com/python/cpython/issues/125946}: The minimum supported Android version is now 7.0 (API level
24).

@item 
gh-125940@footnote{https://github.com/python/cpython/issues/125940}: The Android build now supports 16 KB page sizes@footnote{https://developer.android.com/guide/practices/page-sizes}.

@item 
gh-89640@footnote{https://github.com/python/cpython/issues/89640}: Improve detection of float word ordering on Linux when link-time
optimizations are enabled.

@item 
gh-124928@footnote{https://github.com/python/cpython/issues/124928}: Emscripten builds now require node >= 18.

@item 
gh-115382@footnote{https://github.com/python/cpython/issues/115382}: Fix cross compile failures when the host and target SOABIs
match.
@end itemize

@node Python 3 14 0 alpha 1,Python 3 13 0 beta 1,Python 3 14 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-14-0-alpha-1}@anchor{191f}
@subsection Python 3.14.0 alpha 1


`Release date: 2024-10-15'

@menu
* macOS: macOS<8>. 
* Windows: Windows<14>. 
* Tools/Demos: Tools/Demos<15>. 
* テスト: テスト<13>. 
* セキュリティ: セキュリティ<16>. 
* ライブラリ: ライブラリ<46>. 
* IDLE: IDLE<7>. 
* ドキュメント: ドキュメント<14>. 
* Core and Builtins: Core and Builtins<41>. 
* ライブラリ: ライブラリ<47>. 
* Core and Builtins: Core and Builtins<42>. 
* ライブラリ: ライブラリ<48>. 
* Core and Builtins: Core and Builtins<43>. 
* ライブラリ: ライブラリ<49>. 
* Core and Builtins: Core and Builtins<44>. 
* ライブラリ: ライブラリ<50>. 
* Core and Builtins: Core and Builtins<45>. 
* ライブラリ: ライブラリ<51>. 
* Core and Builtins: Core and Builtins<46>. 
* ライブラリ: ライブラリ<52>. 
* Core and Builtins: Core and Builtins<47>. 
* ライブラリ: ライブラリ<53>. 
* Core and Builtins: Core and Builtins<48>. 
* C API: C API<15>. 
* ビルド: ビルド<15>. 

@end menu

@node macOS<8>,Windows<14>,,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id181}@anchor{1920}
@subsubsection macOS



@itemize -

@item 
gh-124448@footnote{https://github.com/python/cpython/issues/124448}: Update bundled Tcl/Tk in macOS installer to 8.6.15.

@item 
gh-123797@footnote{https://github.com/python/cpython/issues/123797}: Check for runtime availability of @code{ptsname_r} function on
macos.

@item 
gh-123418@footnote{https://github.com/python/cpython/issues/123418}: Updated macOS installer build to use OpenSSL 3.0.15.
@end itemize

@node Windows<14>,Tools/Demos<15>,macOS<8>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id182}@anchor{1921}
@subsubsection Windows



@itemize -

@item 
gh-124487@footnote{https://github.com/python/cpython/issues/124487}: Increases Windows required OS and API level to Windows 10.

@item 
gh-124609@footnote{https://github.com/python/cpython/issues/124609}: Fix @code{_Py_ThreadId} for Windows builds using MinGW. Patch by
Tony Roberts.

@item 
gh-124448@footnote{https://github.com/python/cpython/issues/124448}: Updated bundled Tcl/Tk to 8.6.15.

@item 
gh-124254@footnote{https://github.com/python/cpython/issues/124254}: Ensures experimental free-threaded binaries remain installed
when updating.

@item 
gh-123915@footnote{https://github.com/python/cpython/issues/123915}: Ensure that @code{Tools\msi\buildrelease.bat} uses different
directories for AMD64 and ARM64 builds.

@item 
gh-123418@footnote{https://github.com/python/cpython/issues/123418}: Updated Windows build to use OpenSSL 3.0.15.

@item 
gh-123476@footnote{https://github.com/python/cpython/issues/123476}: Add support for @code{socket.TCP_QUICKACK} on Windows platforms.

@item 
gh-122573@footnote{https://github.com/python/cpython/issues/122573}: The Windows build of CPython now requires 3.10 or newer.

@item 
gh-100256@footnote{https://github.com/python/cpython/issues/100256}: @ref{93,,mimetypes} no longer fails when it encounters an
inaccessible registry key.

@item 
gh-119679@footnote{https://github.com/python/cpython/issues/119679}: Ensures correct import libraries are included in Windows
installs.

@item 
gh-119690@footnote{https://github.com/python/cpython/issues/119690}: Adds Unicode support and fixes audit events for
@code{_winapi.CreateNamedPipe}.

@item 
gh-111201@footnote{https://github.com/python/cpython/issues/111201}: Add support for new pyrepl on Windows

@item 
gh-119070@footnote{https://github.com/python/cpython/issues/119070}: Fixes @code{py.exe} handling of shebangs like @code{/usr/bin/env
python3.12}, which were previously interpreted as @code{python3.exe} instead
of @code{python3.12.exe}.

@item 
gh-117505@footnote{https://github.com/python/cpython/issues/117505}: Fixes an issue with the Windows installer not running ensurepip
in a fully isolated environment. This could cause unexpected interactions
with the user site-packages.

@item 
gh-118209@footnote{https://github.com/python/cpython/issues/118209}: Avoid crashing in @ref{94,,mmap} on Windows when the mapped memory
is inaccessible due to file system errors or access violations.

@item 
gh-79846@footnote{https://github.com/python/cpython/issues/79846}: Makes @code{ssl.create_default_context()} ignore invalid
certificates in the Windows certificate store
@end itemize

@node Tools/Demos<15>,テスト<13>,Windows<14>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id183}@anchor{1922}
@subsubsection Tools/Demos



@itemize -

@item 
gh-123418@footnote{https://github.com/python/cpython/issues/123418}: Update GitHub CI workflows to use OpenSSL 3.0.15 and
multissltests to use 3.0.15, 3.1.7, and 3.2.3.
@end itemize

@node テスト<13>,セキュリティ<16>,Tools/Demos<15>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id184}@anchor{1923}
@subsubsection テスト



@itemize -

@item 
gh-125041@footnote{https://github.com/python/cpython/issues/125041}: Re-enable skipped tests for @ref{139,,zlib} on the s390x
architecture: only skip checks of the compressed bytes, which can be
different between zlib's software implementation and the
hardware-accelerated implementation.

@item 
gh-124378@footnote{https://github.com/python/cpython/issues/124378}: Updated @code{test_ttk} to pass with Tcl/Tk 8.6.15.

@item 
gh-124213@footnote{https://github.com/python/cpython/issues/124213}: Detect whether the test suite is running inside a
systemd-nspawn container with @code{--suppress-sync=true} option, and skip
the @code{test_os} and @code{test_mmap} tests that are failing in this scenario.

@item 
gh-124190@footnote{https://github.com/python/cpython/issues/124190}: Add capability to ignore entire files or directories in check
warning CI tool

@item 
gh-121921@footnote{https://github.com/python/cpython/issues/121921}: Update @code{Lib/test/crashers/bogus_code_obj.py} so that it
crashes properly again.

@item 
gh-112301@footnote{https://github.com/python/cpython/issues/112301}: Add tooling to check for changes in compiler warnings. Patch by
Nate Ohlson.

@item 
gh-59022@footnote{https://github.com/python/cpython/issues/59022}: Add tests for @ref{1924,,pkgutil.extend_path()}. Patch by Andreas
Stocker.

@item 
gh-99242@footnote{https://github.com/python/cpython/issues/99242}: @ref{1925,,os.getloadavg()} may throw @ref{2c0,,OSError} when running
regression tests under certain conditions (e.g. chroot). This error is now
caught and ignored, since reporting load average is optional.

@item 
gh-121084@footnote{https://github.com/python/cpython/issues/121084}: Fix test_typing random leaks. Clear typing ABC caches when
running tests for refleaks (@code{-R} option): call @code{_abc_caches_clear()}
on typing abstract classes and their subclasses. Patch by Victor Stinner.

@item 
gh-121160@footnote{https://github.com/python/cpython/issues/121160}: Add a test for @ref{1926,,readline.set_history_length()}. Note that
this test may fail on readline libraries.

@item 
gh-121200@footnote{https://github.com/python/cpython/issues/121200}: Fix @code{test_expanduser_pwd2()} of @code{test_posixpath}.  Call
@code{getpwnam()} to get @code{pw_dir}, since it can be different than
@code{getpwall()} @code{pw_dir}. Patch by Victor Stinner.

@item 
gh-121188@footnote{https://github.com/python/cpython/issues/121188}: When creating the JUnit XML file, regrtest now escapes
characters which are invalid in XML, such as the chr(27) control character
used in ANSI escape sequences. Patch by Victor Stinner.

@item 
gh-120801@footnote{https://github.com/python/cpython/issues/120801}: Cleaned up fixtures for importlib.metadata tests and
consolidated behavior with 'test.support.os_helper'.

@item 
gh-119727@footnote{https://github.com/python/cpython/issues/119727}: Add @code{--single-process} command line option to Python test
runner (regrtest). Patch by Victor Stinner.

@item 
gh-119273@footnote{https://github.com/python/cpython/issues/119273}: Python test runner no longer runs tests using TTY (ex:
test_ioctl) in a process group (using @code{setsid()}). Previously, tests
using TTY were skipped. Patch by Victor Stinner.

@item 
gh-119050@footnote{https://github.com/python/cpython/issues/119050}: regrtest test runner: Add XML support to the refleak checker
(-R option). Patch by Victor Stinner.

@item 
gh-101525@footnote{https://github.com/python/cpython/issues/101525}: Skip @code{test_gdb} if the binary is relocated by BOLT. Patch by
Donghee Na.

@item 
gh-107562@footnote{https://github.com/python/cpython/issues/107562}: Test certificates have been updated to expire far in the
future. This allows testing Y2038 with system time set to after that, so
that actual Y2038 issues can be exposed, and not masked by expired
certificate errors.
@end itemize

@node セキュリティ<16>,ライブラリ<46>,テスト<13>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id185}@anchor{1927}
@subsubsection セキュリティ



@itemize -

@item 
gh-125140@footnote{https://github.com/python/cpython/issues/125140}: Remove the current directory from @code{sys.path} when using
PyREPL.

@item 
gh-123678@footnote{https://github.com/python/cpython/issues/123678}: Upgrade libexpat to 2.6.3

@item 
gh-112301@footnote{https://github.com/python/cpython/issues/112301}: Enable compiler options that warn of potential security
vulnerabilities.

@item 
gh-122792@footnote{https://github.com/python/cpython/issues/122792}: Changed IPv4-mapped @code{ipaddress.IPv6Address} to consistently
use the mapped IPv4 address value for deciding properties. Properties
which have their behavior fixed are @code{is_multicast}, @code{is_reserved},
@code{is_link_local}, @code{is_global}, and @code{is_unspecified}.

@item 
gh-112301@footnote{https://github.com/python/cpython/issues/112301}: Add ability to ignore warnings per file with warning count in
warning checking tooling. Patch by Nate Ohlson.

@item 
gh-112301@footnote{https://github.com/python/cpython/issues/112301}: Add macOS warning tracking to warning check tooling. Patch by
Nate Ohlson.

@item 
gh-122133@footnote{https://github.com/python/cpython/issues/122133}: Authenticate the socket connection for the
@code{socket.socketpair()} fallback on platforms where @code{AF_UNIX} is not
available like Windows.

Patch by Gregory P. Smith <@email{greg@@krypto.org}> and Seth Larson
<@email{seth@@python.org}>. Reported by Ellie <@email{el@@horse64.org}>

@item 
gh-121957@footnote{https://github.com/python/cpython/issues/121957}: Fixed missing audit events around interactive use of Python,
now also properly firing for @code{python -i}, as well as for @code{python -m
asyncio}. The events in question are @code{cpython.run_stdin} and
@code{cpython.run_startup}.

@item 
gh-112301@footnote{https://github.com/python/cpython/issues/112301}: Enable runtime protections for glibc to abort execution when
unsafe behavior is encountered, for all platforms except Windows.

@item 
gh-121285@footnote{https://github.com/python/cpython/issues/121285}: Remove backtracking from tarfile header parsing for
@code{hdrcharset}, PAX, and GNU sparse headers.

@item 
gh-112301@footnote{https://github.com/python/cpython/issues/112301}: Add default compiler options to improve security. Enable
-Wimplicit-fallthrough, -fstack-protector-strong, -Wtrampolines.

@item 
gh-118773@footnote{https://github.com/python/cpython/issues/118773}: Fixes creation of ACLs in @ref{52b,,os.mkdir()} on Windows to work
correctly on non-English machines.

@item 
gh-118486@footnote{https://github.com/python/cpython/issues/118486}: @ref{52b,,os.mkdir()} on Windows now accepts `mode' of @code{0o700} to
restrict the new directory to the current user. This fixes
@geindex Common Vulnerabilities and Exposures; CVE 2024-4030
CVE 2024-4030@footnote{https://www.cve.org/CVERecord?id=CVE-2024-4030} affecting @ref{52d,,tempfile.mkdtemp()} in scenarios where the
base temporary directory is more permissive than the default.
@end itemize

@node ライブラリ<46>,IDLE<7>,セキュリティ<16>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id186}@anchor{1928}
@subsubsection ライブラリ



@itemize -

@item 
gh-125422@footnote{https://github.com/python/cpython/issues/125422}: Fixed the bug where @ref{aa,,pdb} and @ref{10,,bdb} can step into the
bottom caller frame.

@item 
gh-100141@footnote{https://github.com/python/cpython/issues/100141}: Fixed the bug where @ref{aa,,pdb} will be stuck in an infinite
loop when debugging an empty file.

@item 
gh-53203@footnote{https://github.com/python/cpython/issues/53203}: Fix @ref{1646,,time.strptime()} for @code{%c}, @code{%x} and @code{%X} formats
in many locales that use non-ASCII digits, like Persian, Burmese, Odia and
Shan.

@item 
gh-125206@footnote{https://github.com/python/cpython/issues/125206}: Workaround for old libffi versions is added. Module ctypes
supports double complex only with libffi >= 3.3.0. Patch by
Mikhail Efimov.

@item 
gh-89967@footnote{https://github.com/python/cpython/issues/89967}: Make @ref{1929,,WeakKeyDictionary} and
@ref{192a,,WeakValueDictionary} safe against concurrent mutations
from other threads. Patch by Kumar Aditya.

@item 
gh-125260@footnote{https://github.com/python/cpython/issues/125260}: The @ref{84e,,gzip.compress()} `mtime' parameter now defaults to 0
for reproducible output. Patch by Bernhard M. Wiedemann and Adam Turner.

@item 
gh-125243@footnote{https://github.com/python/cpython/issues/125243}: Fix data race when creating @ref{adc,,zoneinfo.ZoneInfo} objects
in the free threading build.

@item 
gh-125254@footnote{https://github.com/python/cpython/issues/125254}: Fix a bug where ArgumentError includes the incorrect ambiguous
option in @ref{7,,argparse}.

@item 
gh-125235@footnote{https://github.com/python/cpython/issues/125235}: Keep @ref{f6,,tkinter} TCL paths in venv pointing to base
installation on Windows.

@item 
gh-61011@footnote{https://github.com/python/cpython/issues/61011}: Fix inheritance of nested mutually exclusive groups from parent
parser in @ref{1bd,,argparse.ArgumentParser}. Previously, all nested
mutually exclusive groups lost their connection to the group containing
them and were displayed as belonging directly to the parser.

@item 
gh-125118@footnote{https://github.com/python/cpython/issues/125118}: Don't copy arbitrary values to _Bool in the
@ref{db,,struct} module.

@item 
gh-125069@footnote{https://github.com/python/cpython/issues/125069}: Fix an issue where providing a @ref{6cd,,pathlib.PurePath} object
as an initializer argument to a second @ref{6cd,,PurePath} object
with a different @ref{536,,parser} resulted in arguments to
the former object's initializer being joined by the latter object's
parser.

@item 
gh-125096@footnote{https://github.com/python/cpython/issues/125096}: If the 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL} environment variable is set,
the @ref{cc,,site} module no longer imports the @code{_pyrepl} module.
Moreover, the @ref{cc,,site} module now respects @ref{b56,,-E} and
@ref{b57,,-I} command line options: ignore 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL} in
this case. Patch by Victor Stinner.

@item 
gh-124969@footnote{https://github.com/python/cpython/issues/124969}: Fix @code{locale.nl_langinfo(locale.ALT_DIGITS)}. Now it returns a
tuple of up to 100 strings (an empty tuple on most locales). Previously it
returned the first item of that tuple or an empty string.

@item 
gh-124960@footnote{https://github.com/python/cpython/issues/124960}: Fix support for the @code{barry_as_FLUFL} future flag in the new
REPL.

@item 
gh-69998@footnote{https://github.com/python/cpython/issues/69998}: Fix @ref{454,,locale.nl_langinfo()} in case when different categories
have different locales. The function now sets temporarily the @code{LC_CTYPE}
locale in some cases. This temporary change affects other threads.

@item 
gh-124958@footnote{https://github.com/python/cpython/issues/124958}: Fix refcycles in exceptions raised from
@ref{4d1,,asyncio.TaskGroup} and the python implementation of
@ref{dc6,,asyncio.Future}

@item 
gh-53203@footnote{https://github.com/python/cpython/issues/53203}: Fix @ref{1646,,time.strptime()} for @code{%c} and @code{%x} formats in many
locales: Arabic, Bislama, Breton, Bodo, Kashubian, Chuvash, Estonian,
French, Irish, Ge'ez, Gurajati, Manx Gaelic, Hebrew, Hindi, Chhattisgarhi,
Haitian Kreyol, Japanese, Kannada, Korean, Marathi, Malay, Norwegian,
Nynorsk, Punjabi, Rajasthani, Tok Pisin, Yoruba, Yue Chinese, Yau/Nungon
and Chinese.

@item 
gh-123961@footnote{https://github.com/python/cpython/issues/123961}: Convert @ref{2f,,curses} to multi-phase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}), thereby fixing reference leaks at interpreter shutdown.
Patch by Bénédikt Tran.

@item 
gh-124944@footnote{https://github.com/python/cpython/issues/124944}: Add @code{SO_ORIGINAL_DST} to the @ref{d1,,socket} module.

@item 
gh-117151@footnote{https://github.com/python/cpython/issues/117151}: The default buffer size used by @ref{c52,,shutil.copyfileobj()} has
been increased from 64k to 256k on non-Windows platforms. It was already
larger on Windows.

@item 
gh-90102@footnote{https://github.com/python/cpython/issues/90102}: Skip the @code{isatty} system call during open() when the file is
known to not be a character device. This provides a slight performance
improvement when reading whole files.

@item 
gh-124917@footnote{https://github.com/python/cpython/issues/124917}: Allow calling @ref{c03,,os.path.exists()} and
@ref{c04,,os.path.lexists()} with keyword arguments on Windows. Fixes a
regression in 3.13.0.

@item 
gh-65865@footnote{https://github.com/python/cpython/issues/65865}: @ref{7,,argparse} now raises early error for invalid @code{help}
arguments to @ref{4bc,,add_argument()},
@ref{e11,,add_subparsers()} and @code{add_parser()}.

@item 
gh-124653@footnote{https://github.com/python/cpython/issues/124653}: Fix detection of the minimal Queue API needed by the
@ref{8b,,logging} module. Patch by Bénédikt Tran.

@item 
gh-91818@footnote{https://github.com/python/cpython/issues/91818}: The CLI of many modules (@ref{9,,ast}, @ref{59,,ensurepip},
@ref{86,,json}, @ref{aa,,pdb}, @ref{d4,,sqlite3}, @ref{101,,tokenize}, @ref{117,,venv}) now
uses the actual executable name instead of simply "python" to display in
the usage message.

@item 
gh-124858@footnote{https://github.com/python/cpython/issues/124858}: Fix reference cycles left in tracebacks in
@ref{d0e,,asyncio.open_connection()} when used with @code{happy_eyeballs_delay}

@item 
gh-124390@footnote{https://github.com/python/cpython/issues/124390}: Fixed @ref{8b8,,AssertionError} when using
@code{asyncio.staggered.staggered_race()} with
@ref{6a2,,asyncio.eager_task_factory}.

@item 
gh-85935@footnote{https://github.com/python/cpython/issues/85935}: @ref{4bc,,argparse.ArgumentParser.add_argument()} now raises an
exception if an @ref{192b,,action} that does not consume arguments (like
'store_const' or 'store_true') or explicit @code{nargs=0} are specified for
positional arguments.

@item 
gh-124835@footnote{https://github.com/python/cpython/issues/124835}: Make @ref{192c,,tomllib.loads()} raise @ref{198,,TypeError} not
@ref{5f0,,AttributeError} on bad input types that do not have the @code{replace}
attribute. Improve error message when @ref{192,,bytes} is received.

@item 
gh-124693@footnote{https://github.com/python/cpython/issues/124693}: Fix a bug where @ref{7,,argparse} doesn't recognize negative
complex numbers or negative numbers using scientific notation.

@item 
gh-124787@footnote{https://github.com/python/cpython/issues/124787}: Fix @ref{2ae,,typing.TypeAliasType} with incorrect
@code{type_params} argument. Now it raises a @ref{198,,TypeError} when a type
parameter without a default follows one with a default, and when an entry
in the @code{type_params} tuple is not a type parameter object.

@item 
gh-66436@footnote{https://github.com/python/cpython/issues/66436}: Improved @ref{1bc,,prog} default value for
@ref{1bd,,argparse.ArgumentParser}. It will now include the name of the
Python executable along with the module or package name, or the path to a
directory, ZIP file, or directory within a ZIP file if the code was run
that way.

@item 
gh-116850@footnote{https://github.com/python/cpython/issues/116850}: Fix @ref{7,,argparse} for namespaces with not directly writable
dict (e.g. classes).

@item 
gh-101552@footnote{https://github.com/python/cpython/issues/101552}: Add an `annoation_format' parameter to
@ref{22f,,inspect.signature()}. Add an `quote_annotation_strings' parameter to
@ref{231,,inspect.Signature.format()}. Use the new functionality to improve the
display of annotations in signatures in @ref{ba,,pydoc}. Patch by Jelle
Zijlstra.

@item 
gh-58573@footnote{https://github.com/python/cpython/issues/58573}: Fix conflicts between abbreviated long options in the parent
parser and subparsers in @ref{7,,argparse}.

@item 
gh-124594@footnote{https://github.com/python/cpython/issues/124594}: All @ref{b,,asyncio} REPL prompts run in the same @ref{177,,context}. Contributed by Bartosz Sławecki.

@item 
gh-61181@footnote{https://github.com/python/cpython/issues/61181}: Fix support of @ref{192d,,choices} with string value in
@ref{7,,argparse}. Substrings of the specified string no longer considered
valid values.

@item 
gh-116750@footnote{https://github.com/python/cpython/issues/116750}: Provide @ref{192e,,sys.monitoring.clear_tool_id()} to unregister all
events and callbacks set by the tool.

@item 
gh-124552@footnote{https://github.com/python/cpython/issues/124552}: Improve the accuracy of @ref{10,,bdb}'s check for the possibility
of breakpoint in a frame. This makes it possible to disable unnecessary
events in functions.

@item 
gh-124538@footnote{https://github.com/python/cpython/issues/124538}: Fixed crash when using @ref{a06,,gc.get_referents()} on a capsule
object.

@item 
gh-80259@footnote{https://github.com/python/cpython/issues/80259}: Fix @ref{7,,argparse} support of positional arguments with
@code{nargs='?'}, @code{default=argparse.SUPPRESS} and specified @code{type}.

@item 
gh-120378@footnote{https://github.com/python/cpython/issues/120378}: Fix a crash related to an integer overflow in
@ref{192f,,curses.resizeterm()} and @ref{1930,,curses.resize_term()}.

@item 
gh-124498@footnote{https://github.com/python/cpython/issues/124498}: Fix @ref{2ae,,typing.TypeAliasType} not to be generic, when
@code{type_params} is an empty tuple.

@item 
gh-53834@footnote{https://github.com/python/cpython/issues/53834}: Fix support of arguments with @ref{192d,,choices} in @ref{7,,argparse}.
Positional arguments with @ref{1931,,nargs} equal to @code{'?'} or @code{'*'} no
longer check @ref{1932,,default} against @code{choices}. Optional arguments with
@code{nargs} equal to @code{'?'} no longer check @ref{1933,,const} against
@code{choices}.

@item 
gh-123884@footnote{https://github.com/python/cpython/issues/123884}: Fixed bug in itertools.tee() handling of other tee inputs (a
tee in a tee). The output now has the promised `n' independent new
iterators.  Formerly, the first iterator was identical (not independent)
to the input iterator. This would sometimes give surprising results.

@item 
gh-123017@footnote{https://github.com/python/cpython/issues/123017}: Due to unreliable results on some devices,
@ref{1402,,time.strftime()} no longer accepts negative years on Android.

@item 
gh-123014@footnote{https://github.com/python/cpython/issues/123014}: @ref{6a4,,os.pidfd_open()} and @ref{b25,,signal.pidfd_send_signal()} are
now unavailable when building against Android API levels older than 31,
since the underlying system calls may cause a crash.

@item 
gh-124176@footnote{https://github.com/python/cpython/issues/124176}: Add support for @ref{4e1,,dataclasses.dataclass()} in
@ref{1934,,unittest.mock.create_autospec()}. Now @code{create_autospec} will check
for potential dataclasses and use @ref{1935,,dataclasses.fields()} function to
retrieve the spec information.

@item 
gh-124345@footnote{https://github.com/python/cpython/issues/124345}: @ref{7,,argparse} supports abbreviated single-dash long options
separated by @code{=} from its value.

@item 
gh-124400@footnote{https://github.com/python/cpython/issues/124400}: Fixed a @ref{aa,,pdb} bug where @code{until} has no effect when it
appears in a @code{commands} sequence. Also avoid printing the frame
information at a breakpoint that has a command list containing a command
that resumes execution.

@item 
gh-90562@footnote{https://github.com/python/cpython/issues/90562}: Modify dataclasses to support zero-argument super() when
@code{slots=True} is specified.  This works by modifying all references to
@code{__class__} to point to the newly created class.

@item 
gh-104860@footnote{https://github.com/python/cpython/issues/104860}: Fix disallowing abbreviation of single-dash long options in
@ref{7,,argparse} with @code{allow_abbrev=False}.

@item 
gh-63143@footnote{https://github.com/python/cpython/issues/63143}: Fix parsing mutually exclusive arguments in @ref{7,,argparse}.
Arguments with the value identical to the default value (e.g. booleans,
small integers, empty or 1-character strings) are no longer considered
"not present".

@item 
gh-72795@footnote{https://github.com/python/cpython/issues/72795}: Positional arguments with @ref{1931,,nargs} equal to @code{'*'} or
@code{argparse.REMAINDER} are no longer required. This allows to use
positional argument with @code{nargs='*'} and without @code{default} in mutually
exclusive group and improves error message about required arguments.

@item 
gh-59317@footnote{https://github.com/python/cpython/issues/59317}: Fix parsing positional argument with @ref{1931,,nargs} equal to
@code{'?'} or @code{'*'} if it is preceded by an option and another positional
argument.

@item 
gh-100980@footnote{https://github.com/python/cpython/issues/100980}: The @ref{1936,,_fields_} attribute of
@ref{1e5,,ctypes.Structure} and @ref{1e6,,Union} is no longer set if
the setattr operation raises an error.

@item 
gh-53780@footnote{https://github.com/python/cpython/issues/53780}: @ref{7,,argparse} now ignores the first @code{"--"} (double dash)
between an option and command.

@item 
gh-124217@footnote{https://github.com/python/cpython/issues/124217}: Add RFC 9637 reserved IPv6 block @code{3fff::/20} in
@ref{84,,ipaddress} module.

@item 
gh-111513@footnote{https://github.com/python/cpython/issues/111513}: Improve the error message that may be raised by
@ref{dcd,,datetime.date.fromtimestamp()}.

@item 
gh-124248@footnote{https://github.com/python/cpython/issues/124248}: Fixed potential crash when using @ref{db,,struct} to process
zero-width 'Pascal string' fields (@code{0p}).

@item 
gh-81691@footnote{https://github.com/python/cpython/issues/81691}: Fix handling of multiple @code{"--"} (double dashes) in
@ref{7,,argparse}. Only the first one has now been removed, all subsequent
ones are now taken literally.

@item 
gh-87041@footnote{https://github.com/python/cpython/issues/87041}: Fix a bug in @ref{7,,argparse} where lengthy subparser argument
help is incorrectly indented.

@item 
gh-84559@footnote{https://github.com/python/cpython/issues/84559}: The default @ref{98,,multiprocessing} start method on Linux and
other POSIX systems has been changed away from often unsafe @code{"fork"} to
@code{"forkserver"} (when the platform supports sending file handles over
pipes as most do) or @code{"spawn"}.  Mac and Windows are unchanged as they
already default to @code{"spawn"}.

@item 
gh-124212@footnote{https://github.com/python/cpython/issues/124212}: Fix invalid variable in @ref{117,,venv} handling of failed symlink
on Windows

@item 
gh-124171@footnote{https://github.com/python/cpython/issues/124171}: Add workaround for broken @code{fmod()} implementations on
Windows, that loose zero sign (e.g. @code{fmod(-10, 1)} returns @code{0.0}).
Patch by Sergey B Kirpichev.

@item 
gh-123978@footnote{https://github.com/python/cpython/issues/123978}: Remove broken @ref{b30,,time.thread_time()} and
@ref{d8a,,time.thread_time_ns()} on NetBSD.

@item 
gh-123934@footnote{https://github.com/python/cpython/issues/123934}: Fix @ref{108f,,unittest.mock.MagicMock} resetting magic methods
return values after @code{.reset_mock(return_value=True)} was called.

@item 
gh-124016@footnote{https://github.com/python/cpython/issues/124016}: Update @ref{10b,,unicodedata} database to Unicode 16.0.0.

@item 
gh-123968@footnote{https://github.com/python/cpython/issues/123968}: Fix the command-line interface for the @ref{bd,,random} module to
select floats between 0 and N, not 1 and N.

@item 
gh-123945@footnote{https://github.com/python/cpython/issues/123945}: Fix a bug where @ref{7,,argparse} doesn't recognize negative
numbers with underscores

@item 
gh-123935@footnote{https://github.com/python/cpython/issues/123935}: Fix parent slots detection for dataclasses that inherit from
classes with @code{__dictoffset__}.

@item 
gh-123892@footnote{https://github.com/python/cpython/issues/123892}: Add @code{"_wmi"} to @ref{a42,,sys.stdlib_module_names}. Patch by
Victor Stinner.

@item 
gh-84808@footnote{https://github.com/python/cpython/issues/84808}: Fix error handling in @ref{fa1,,socket} method
@ref{1753,,connect_ex()} on platforms where @code{errno}
can be negative.

@item 
gh-123756@footnote{https://github.com/python/cpython/issues/123756}: Added a new argument @code{mode} to @ref{273,,pdb.Pdb}. Only allow
@ref{aa,,pdb} from command line to use @code{restart} command.

@item 
gh-122765@footnote{https://github.com/python/cpython/issues/122765}: Fix unbalanced quote errors occurring when activate.csh in
@ref{117,,venv} was sourced with a custom prompt containing unpaired quotes or
newlines.

@item 
gh-123657@footnote{https://github.com/python/cpython/issues/123657}: Fix crash and memory leak in @ref{1937,,decimal.getcontext()}. It
crashed when using a thread-local context by
@code{--with-decimal-contextvar=no}.

@item 
gh-123339@footnote{https://github.com/python/cpython/issues/123339}: Fix @ref{17c3,,inspect.getsource()} for classes in
@ref{1f,,collections.abc} and @ref{3a,,decimal} (for pure Python implementation)
modules. @ref{1938,,inspect.getcomments()} now raises OSError instead of
IndexError if the @code{__firstlineno__} value for a class is out of bound.

@item 
gh-123374@footnote{https://github.com/python/cpython/issues/123374}: Remove check for redefined memo entry in
@ref{ebe,,pickletools.dis()}.

@item 
gh-123504@footnote{https://github.com/python/cpython/issues/123504}: Fixed reference leak in the finalization of @ref{f6,,tkinter}.

@item 
gh-123430@footnote{https://github.com/python/cpython/issues/123430}: Pages generated by the @ref{76,,http.server} module allow the
browser to apply its default dark mode.

@item 
gh-123446@footnote{https://github.com/python/cpython/issues/123446}: Fix empty function name in @ref{198,,TypeError} when
@ref{6ae,,csv.reader()}, @ref{6af,,csv.writer()}, or @ref{1939,,csv.register_dialect()}
are used without the required args.

@item 
gh-123448@footnote{https://github.com/python/cpython/issues/123448}: Fixed memory leak of @ref{569,,typing.NoDefault} by moving it to
the static types array.

@item 
gh-123409@footnote{https://github.com/python/cpython/issues/123409}: Fix @ref{193a,,ipaddress.IPv6Address.reverse_pointer} output
according to 
@geindex RFC; RFC 3596 Section 2.5
RFC 3596@comma{} §2.5@footnote{https://datatracker.ietf.org/doc/html/rfc3596.html#section-2.5}.  Patch by Bénédikt
Tran.

@item 
gh-123089@footnote{https://github.com/python/cpython/issues/123089}: Make @ref{7f5,,weakref.WeakSet} safe against concurrent mutations
while it is being iterated. Patch by Kumar Aditya.

@item 
gh-123363@footnote{https://github.com/python/cpython/issues/123363}: Show string value of @ref{193b,,CONTAINS_OP} oparg in @ref{3c,,dis}
output. Patch by Alexandr153.

@item 
gh-123341@footnote{https://github.com/python/cpython/issues/123341}: Add @ref{943,,__class_getitem__()} to
@code{tkinter.Event} for type subscript support at runtime. Patch by
Adonis Rakateli.

@item 
gh-123340@footnote{https://github.com/python/cpython/issues/123340}: Show string value of @ref{193c,,IS_OP} oparg in @ref{3c,,dis}
output.

@item 
gh-119518@footnote{https://github.com/python/cpython/issues/119518}: Speed up normalization of @ref{6cd,,pathlib.PurePath} and
@ref{266,,Path} objects by not interning string parts.

@item 
gh-123270@footnote{https://github.com/python/cpython/issues/123270}: Applied a more surgical fix for malformed payloads in
@ref{8d8,,zipfile.Path} causing infinite loops (gh-122905@footnote{https://github.com/python/cpython/issues/122905}) without breaking
contents using legitimate characters.

@item 
gh-73991@footnote{https://github.com/python/cpython/issues/73991}: Add @ref{268,,pathlib.Path.copy_into()} and
@ref{26a,,move_into()}, which copy and move files and directories
into `existing' directories.

@item 
gh-123228@footnote{https://github.com/python/cpython/issues/123228}: Fix return type for
@code{_pyrepl.readline._ReadlineWrapper.get_line_buffer()} to be
@ref{169,,str()}.  Patch by Sergey B Kirpichev.

@item 
gh-123240@footnote{https://github.com/python/cpython/issues/123240}: Raise audit events for the @ref{14f0,,input()} in the new REPL.

@item 
gh-76960@footnote{https://github.com/python/cpython/issues/76960}: Fix @ref{1096,,urllib.parse.urljoin()} and
@ref{145f,,urllib.parse.urldefrag()} for URIs containing empty components. For
example, @code{urljoin()} with relative reference "?" now sets empty query
and removes fragment. Preserve empty components (authority, params, query,
fragment) in @code{urljoin()}. Preserve empty components (authority,
params, query) in @code{urldefrag()}.

@item 
gh-116810@footnote{https://github.com/python/cpython/issues/116810}: Resolve a memory leak introduced in CPython 3.10's @ref{d5,,ssl}
when the @ref{193d,,ssl.SSLSocket.session} property was accessed.  Speeds up
read and write access to said property by no longer unnecessarily cloning
session objects via serialization.

@item 
gh-123243@footnote{https://github.com/python/cpython/issues/123243}: Fix memory leak in @code{_decimal}.

@item 
gh-122546@footnote{https://github.com/python/cpython/issues/122546}: Consistently use same file name for different exceptions in the
new repl. Patch by Sergey B Kirpichev.

@item 
gh-123213@footnote{https://github.com/python/cpython/issues/123213}: @ref{13eb,,xml.etree.ElementTree.Element.extend()} and
@ref{363,,Element} assignment no longer hide the
internal exception if an erroneous generator is passed. Patch by Bar
Harel.

@item 
gh-85110@footnote{https://github.com/python/cpython/issues/85110}: Preserve relative path in URL without netloc in
@ref{193e,,urllib.parse.urlunsplit()} and @ref{193f,,urllib.parse.urlunparse()}.

@item 
gh-123165@footnote{https://github.com/python/cpython/issues/123165}: Add support for rendering @ref{1940,,Positions} in
@ref{3c,,dis}.

@item 
gh-122909@footnote{https://github.com/python/cpython/issues/122909}: In urllib.request when URLError is raised opening an ftp URL,
the exception argument is now consistently a string. Earlier versions
passed either a string or an ftplib exception instance as the argument to
URLError.

@item 
gh-123084@footnote{https://github.com/python/cpython/issues/123084}: Deprecate @code{shutil.ExecError}, which hasn't been raised
by any @ref{ca,,shutil} function since Python 3.4. It's now an alias for
@ref{244,,RuntimeError}.

@item 
gh-123085@footnote{https://github.com/python/cpython/issues/123085}: In a bare call to @ref{6b6,,importlib.resources.files()}, ensure the
caller's frame is properly detected when @code{importlib.resources} is itself
available as a compiled module only (no source).

@item 
gh-123067@footnote{https://github.com/python/cpython/issues/123067}: Fix quadratic complexity in parsing @code{"}-quoted cookie values
with backslashes by @ref{75,,http.cookies}.

@item 
gh-123049@footnote{https://github.com/python/cpython/issues/123049}: Add support for @ref{178a,,UNNAMED_SECTION} in
@ref{1485,,configparser.ConfigParser.add_section()}.

@item 
gh-121735@footnote{https://github.com/python/cpython/issues/121735}: When working with zip archives, importlib.resources now
properly honors module-adjacent references (e.g. @code{files(pkg.mod)} and
not just @code{files(pkg)}).

@item 
gh-122981@footnote{https://github.com/python/cpython/issues/122981}: Fix @ref{17c3,,inspect.getsource()} for generated classes with Python
base classes (e.g. enums).

@item 
gh-122903@footnote{https://github.com/python/cpython/issues/122903}: @code{zipfile.Path.glob} now correctly matches directories instead
of silently omitting them.

@item 
gh-122905@footnote{https://github.com/python/cpython/issues/122905}: @ref{8d8,,zipfile.Path} objects now sanitize names from the
zipfile.

@item 
gh-122873@footnote{https://github.com/python/cpython/issues/122873}: Enable @ref{86,,json} module to work as a script using the
@ref{23c,,-m} switch: @code{python -m json}. See the @ref{23e,,JSON command-line interface} documentation. Patch by Trey Hunner.

@item 
gh-122858@footnote{https://github.com/python/cpython/issues/122858}: Deprecate @code{asyncio.iscoroutinefunction()} in favor of
@ref{30d,,inspect.iscoroutinefunction()}.

@item 
gh-116263@footnote{https://github.com/python/cpython/issues/116263}: @ref{1941,,logging.handlers.RotatingFileHandler} no longer rolls
over empty log files.

@item 
gh-105376@footnote{https://github.com/python/cpython/issues/105376}: Restore the deprecated @ref{8b,,logging} @code{warn()} method. It was
removed in Python 3.13 alpha 1. Keep the deprecated @code{warn()} method in
Python 3.13. Patch by Victor Stinner.

@item 
gh-122311@footnote{https://github.com/python/cpython/issues/122311}: Improve errors in the @ref{ab,,pickle} module.
@ref{1942,,PicklingError} is now raised more often instead of
@ref{887,,UnicodeEncodeError}, @ref{2ec,,ValueError} and @ref{5f0,,AttributeError},
and the original exception is chained to it. Improve and unify error
messages in Python and C implementations.

@item 
gh-122744@footnote{https://github.com/python/cpython/issues/122744}: Bump the version of pip bundled in ensurepip to version 24.2.

@item 
gh-118761@footnote{https://github.com/python/cpython/issues/118761}: Improve import time of @ref{b3,,pprint} by around seven times.
Patch by Hugo van Kemenade.

@item 
gh-118974@footnote{https://github.com/python/cpython/issues/118974}: Add @code{decorator} parameter to
@ref{185c,,dataclasses.make_dataclass()} to customize the functional creation of
dataclasses.

@item 
gh-118814@footnote{https://github.com/python/cpython/issues/118814}: Fix the @ref{486,,typing.TypeVar} constructor when name is passed
by keyword.

@item 
gh-122637@footnote{https://github.com/python/cpython/issues/122637}: Adjust @code{cmath.tanh(nanj)} and @code{cmath.tanh(infj)} for recent
C standards.

@item 
gh-122478@footnote{https://github.com/python/cpython/issues/122478}: Remove internal frames from tracebacks shown in
@ref{1943,,code.InteractiveInterpreter} with non-default
@ref{a0c,,sys.excepthook()}. Save correct tracebacks in
@ref{6e8,,sys.last_traceback} and update @code{__traceback__} attribute of
@ref{6e7,,sys.last_value} and @ref{6e5,,sys.last_exc}.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: On Android, the @code{FICLONE} and @code{FICLONERANGE} constants are
no longer exposed by @ref{5d,,fcntl}, as these ioctls are blocked by SELinux.

@item 
gh-82378@footnote{https://github.com/python/cpython/issues/82378}: Make sure that the new @ref{491,,REPL} interprets
@ref{1944,,sys.tracebacklimit} in the same way that the classic REPL did.

@item 
gh-122334@footnote{https://github.com/python/cpython/issues/122334}: Fix crash when importing @ref{d5,,ssl} after the main interpreter
restarts.

@item 
gh-122459@footnote{https://github.com/python/cpython/issues/122459}: Optimize @ref{ab,,pickling} by name objects without the
@code{__module__} attribute.

@item 
gh-87320@footnote{https://github.com/python/cpython/issues/87320}: In @ref{1943,,code.InteractiveInterpreter}, handle exceptions
caused by calling a non-default @ref{a0c,,sys.excepthook()}. Before, the
exception bubbled up to the caller, ending the @ref{491,,REPL}.

@item 
gh-122272@footnote{https://github.com/python/cpython/issues/122272}: On some platforms such as Linux, year with century was not
0-padded when formatted by @ref{e8e,,strftime()} with C99-specific
specifiers @code{'%C'} or @code{'%F'}. The 0-padding behavior is now guaranteed
when the format specifiers @code{'%C'} and @code{'%F'} are supported by the C
library. Patch by Ben Hsing

@item 
gh-122400@footnote{https://github.com/python/cpython/issues/122400}: Handle @ref{2ec,,ValueError}s raised by @ref{26d,,os.stat()} in
@ref{1142,,filecmp.dircmp} and @ref{1945,,filecmp.cmpfiles()}. Patch by Bénédikt
Tran.

@item 
gh-122311@footnote{https://github.com/python/cpython/issues/122311}: Fix some error messages in @ref{ab,,pickle}.

@item 
gh-121650@footnote{https://github.com/python/cpython/issues/121650}: @ref{3f,,email} headers with embedded newlines are now quoted on
output. The @ref{44,,generator} will now refuse to serialize (write)
headers that are unsafely folded or delimited; see
@ref{4f2,,verify_generated_headers}. (Contributed by Bas
Bloemsaat and Petr Viktorin in gh-121650@footnote{https://github.com/python/cpython/issues/121650}.)

@item 
gh-122332@footnote{https://github.com/python/cpython/issues/122332}: Fixed segfault with @ref{bcf,,asyncio.Task.get_coro()} when using an
eager task factory.

@item 
gh-105733@footnote{https://github.com/python/cpython/issues/105733}: @ref{59e,,ctypes.ARRAY()} is now @ref{23d,,soft deprecated}: it no
longer emits deprecation warnings and is not scheduled for removal.

@item 
gh-122213@footnote{https://github.com/python/cpython/issues/122213}: Add notes for pickle serialization errors that allow to
identify the source of the error.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: As part of 
@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/}, add the following attributes for
customizing evaluation of annotation scopes:


@itemize *

@item 
@code{evaluate_value} on @ref{2ae,,typing.TypeAliasType}

@item 
@code{evaluate_bound}, @code{evaluate_constraints}, and @code{evaluate_default} on @ref{486,,typing.TypeVar}

@item 
@code{evaluate_default} on @ref{487,,typing.ParamSpec}

@item 
@code{evaluate_default} on @ref{488,,typing.TypeVarTuple}
@end itemize

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: Fix handling of classes with custom metaclasses in
@code{annotationlib.get_annotations}.

@item 
gh-122170@footnote{https://github.com/python/cpython/issues/122170}: Handle @ref{2ec,,ValueError}s raised by @ref{26d,,os.stat()} in
@ref{89,,linecache}. Patch by Bénédikt Tran.

@item 
gh-122163@footnote{https://github.com/python/cpython/issues/122163}: Add notes for JSON serialization errors that allow to identify
the source of the error.

@item 
gh-122129@footnote{https://github.com/python/cpython/issues/122129}: Improve support of method descriptors and wrappers in the help
title.

@item 
gh-122145@footnote{https://github.com/python/cpython/issues/122145}: Fix an issue when reporting tracebacks corresponding to Python
code emitting an empty AST body. Patch by Nikita Sobolev and Bénédikt
Tran.

@item 
gh-121723@footnote{https://github.com/python/cpython/issues/121723}: Make @ref{13c8,,logging.config.dictConfig()} accept any object
implementing the Queue public API. See the @ref{1946,,queue configuration} section for details. Patch by Bénédikt Tran.

@item 
gh-82951@footnote{https://github.com/python/cpython/issues/82951}: Serializing objects with complex @code{__qualname__} (such as
unbound methods and nested classes) by name no longer involves serializing
parent objects by value in pickle protocols < 4.

@item 
gh-120754@footnote{https://github.com/python/cpython/issues/120754}: @code{Pathlib.read_bytes} no longer opens the file in Python's
buffered I/O mode. This reduces overheads as the code reads a file in
whole leading to a modest speedup.

@item 
gh-113785@footnote{https://github.com/python/cpython/issues/113785}: @ref{2d,,csv} now correctly parses numeric fields (when used with
@ref{1947,,csv.QUOTE_NONNUMERIC} or @ref{6ad,,csv.QUOTE_STRINGS}) which start
with an escape character.

@item 
gh-122088@footnote{https://github.com/python/cpython/issues/122088}: @ref{489,,@@warnings.deprecated} now copies the coroutine status of
functions and methods so that @ref{30d,,inspect.iscoroutinefunction()} returns
the correct result.

@item 
gh-122081@footnote{https://github.com/python/cpython/issues/122081}: Fix a crash in the @code{decimal.IEEEContext()} optional
function available via the @code{EXTRA_FUNCTIONALITY} configuration flag.

@item 
gh-73991@footnote{https://github.com/python/cpython/issues/73991}: Add @ref{269,,pathlib.Path.move()}, which moves a file or directory
tree.

@item 
gh-121268@footnote{https://github.com/python/cpython/issues/121268}: Remove workarounds for non-IEEE 754 systems in @ref{19,,cmath}.

@item 
gh-119698@footnote{https://github.com/python/cpython/issues/119698}: Due to the lack of interest for
@ref{31d,,symtable.Class.get_methods()}, the method is marked as deprecated and
will be removed in Python 3.16. Patch by Bénédikt Tran.

@item 
gh-121889@footnote{https://github.com/python/cpython/issues/121889}: Adjusts @code{cmath.acosh(complex('0+nanj'))} for recent C
standards.

@item 
gh-121804@footnote{https://github.com/python/cpython/issues/121804}: Correctly show error locations, when @ref{18e,,SyntaxError} raised
in new repl. Patch by Sergey B Kirpichev.

@item 
gh-121797@footnote{https://github.com/python/cpython/issues/121797}: Add alternative @ref{213,,Fraction} constructor
@ref{214,,Fraction.from_number()}.

@item 
gh-121798@footnote{https://github.com/python/cpython/issues/121798}: Add alternative @ref{1fe,,Decimal} constructor
@ref{1fd,,Decimal.from_number()}.

@item 
gh-120930@footnote{https://github.com/python/cpython/issues/120930}: Fixed a bug introduced by gh-92081@footnote{https://github.com/python/cpython/issues/92081} that added an incorrect
extra blank to encoded words occurring in wrapped headers.

@item 
gh-57141@footnote{https://github.com/python/cpython/issues/57141}: The `shallow' argument to @ref{1142,,filecmp.dircmp} (new in Python
3.13) is now keyword-only.

@item 
gh-121245@footnote{https://github.com/python/cpython/issues/121245}: Simplify handling of the history file in
@code{site.register_readline()} helper. The @code{CAN_USE_PYREPL} variable now
will be initialized, when imported.  Patch by Sergey B Kirpichev.

@item 
gh-121249@footnote{https://github.com/python/cpython/issues/121249}: Support the float complex and double complex C types in the @ref{db,,struct} module if the compiler has C11
complex arithmetic.  Patch by Sergey B Kirpichev.

@item 
gh-121486@footnote{https://github.com/python/cpython/issues/121486}: @ref{92,,math} functions @ref{bf8,,isqrt()}, @ref{16d9,,log()},
@ref{12f3,,log2()} and @ref{1948,,log10()} now support integers larger
than @code{2**2**32} on 32-bit platforms.

@item 
gh-121474@footnote{https://github.com/python/cpython/issues/121474}: Fix missing sanity check for @code{parties} arg in
@ref{13fc,,threading.Barrier} constructor. Patch by Clinton Christian
(pygeek).

@item 
gh-121450@footnote{https://github.com/python/cpython/issues/121450}: Hard-coded breakpoints (@ref{271,,breakpoint()} and
@ref{272,,pdb.set_trace()}) now reuse the most recent @code{Pdb} instance that
calls @code{Pdb.set_trace()}, instead of creating a new one each time. As a
result, all the instance specific data like @code{display} and @code{commands}
are preserved across Hard-coded breakpoints.

@item 
gh-119169@footnote{https://github.com/python/cpython/issues/119169}: Slightly speed up @ref{6d0,,os.walk()} by simplifying exception
handling.

@item 
gh-121423@footnote{https://github.com/python/cpython/issues/121423}: Improve import time of @ref{d1,,socket} by lazy importing modules
and writing @code{socket.errorTab} as a constant.

@item 
gh-59110@footnote{https://github.com/python/cpython/issues/59110}: @ref{138,,zipimport} supports now namespace packages when no
directory entry exists.

@item 
gh-119004@footnote{https://github.com/python/cpython/issues/119004}: Fix a crash in @ref{1949,,OrderedDict.__eq__} when operands are mutated during the
check. Patch by Bénédikt Tran.

@item 
gh-121313@footnote{https://github.com/python/cpython/issues/121313}: Limit the reading size in the
@ref{12f8,,multiprocessing.connection.Connection} class to 64 KiB to prevent
memory overallocation and unnecessary memory management system calls.

@item 
gh-121332@footnote{https://github.com/python/cpython/issues/121332}: Fix constructor of @ref{9,,ast} nodes with custom
@code{_attributes}. Previously, passing custom attributes would raise a
@ref{1a3,,DeprecationWarning}. Passing arguments to the constructor that
are not in @code{_fields} or @code{_attributes} remains deprecated. Patch by
Jelle Zijlstra.

@item 
gh-121245@footnote{https://github.com/python/cpython/issues/121245}: Fix a bug in the handling of the command history of the new
@ref{491,,REPL} that caused the history file to be wiped at REPL exit.

@item 
gh-121210@footnote{https://github.com/python/cpython/issues/121210}: Handle AST nodes with missing runtime fields or attributes in
@ref{1bf,,ast.compare()}. Patch by Bénédikt Tran.

@item 
gh-121163@footnote{https://github.com/python/cpython/issues/121163}: Add support for @code{all} as an valid @code{action} for
@ref{8d0,,warnings.simplefilter()} and @ref{16c2,,warnings.filterwarnings()}.

@item 
gh-121151@footnote{https://github.com/python/cpython/issues/121151}: Fix wrapping of long usage text of arguments inside a mutually
exclusive group in @ref{7,,argparse}.

@item 
gh-121141@footnote{https://github.com/python/cpython/issues/121141}: Add support for @ref{1c0,,copy.replace()} to AST nodes. Patch by
Bénédikt Tran.

@item 
gh-87744@footnote{https://github.com/python/cpython/issues/87744}: Fix waitpid race while calling
@ref{194a,,send_signal()} in asyncio. Patch by Kumar
Aditya.

@item 
gh-121027@footnote{https://github.com/python/cpython/issues/121027}: Add a future warning in @code{functools.partial.__get__()}. In
future Python versions @ref{217,,functools.partial} will be a method
descriptor.

@item 
gh-121027@footnote{https://github.com/python/cpython/issues/121027}: Make the @ref{217,,functools.partial} object a method descriptor.

@item 
gh-117784@footnote{https://github.com/python/cpython/issues/117784}: CPython now detects whether its linked TLS library supports
TLSv1.3 post-handshake authentication and disables that feature if support
is lacking.

@item 
gh-121025@footnote{https://github.com/python/cpython/issues/121025}: Improve the @ref{82f,,__repr__()} of
@ref{218,,functools.partialmethod}. Patch by Bénédikt Tran.

@item 
gh-121018@footnote{https://github.com/python/cpython/issues/121018}: Fixed issues where @code{argparse.ArgumentParser.parse_args()}
did not honor @code{exit_on_error=False}. Based on patch by Ben Hsing.

@item 
gh-119614@footnote{https://github.com/python/cpython/issues/119614}: Fix truncation of strings with embedded null characters in some
internal operations in @ref{f6,,tkinter}.

@item 
gh-120910@footnote{https://github.com/python/cpython/issues/120910}: When reading installed files from an egg, use
@code{relative_to(walk_up=True)} to honor files installed outside of the
installation root.

@item 
gh-61103@footnote{https://github.com/python/cpython/issues/61103}: Support float complex, double complex and
long double complex C types in @ref{2e,,ctypes} as
@ref{1ed,,c_float_complex}, @ref{1ee,,c_double_complex} and
@ref{1ef,,c_longdouble_complex} if the compiler has C11 complex
arithmetic. Patch by Sergey B Kirpichev.

@item 
gh-120888@footnote{https://github.com/python/cpython/issues/120888}: Upgrade pip wheel bundled with ensurepip (pip 24.1.1)

@item 
gh-101830@footnote{https://github.com/python/cpython/issues/101830}: Accessing the @ref{f6,,tkinter} object's string representation no
longer converts the underlying Tcl object to a string on Windows.

@item 
gh-120678@footnote{https://github.com/python/cpython/issues/120678}: Fix regression in the new REPL that meant that globals from
files passed using the @code{-i} argument would not be included in the REPL's
global namespace. Patch by Alex Waygood.

@item 
gh-120811@footnote{https://github.com/python/cpython/issues/120811}: Fix possible memory leak in @ref{194b,,contextvars.Context.run()}.

@item 
gh-120782@footnote{https://github.com/python/cpython/issues/120782}: Fix wrong references of the @ref{34,,datetime} types after
reloading the module.

@item 
gh-120713@footnote{https://github.com/python/cpython/issues/120713}: @ref{e8e,,datetime.datetime.strftime()} now 0-pads years with less
than four digits for the format specifiers @code{%Y} and @code{%G} on Linux.
Patch by Ben Hsing

@item 
gh-120769@footnote{https://github.com/python/cpython/issues/120769}: Make empty line in @ref{aa,,pdb} repeats the last command even
when the command is from @code{cmdqueue}.

@item 
gh-120780@footnote{https://github.com/python/cpython/issues/120780}: Show string value of LOAD_SPECIAL oparg in @ref{3c,,dis} output.

@item 
gh-41431@footnote{https://github.com/python/cpython/issues/41431}: Add @ref{194c,,datetime.time.strptime()} and
@ref{1f9,,datetime.date.strptime()}. Contributed by Wannes Boeykens.

@item 
gh-120743@footnote{https://github.com/python/cpython/issues/120743}: @ref{23d,,Soft deprecate} @ref{31a,,os.popen()} and
@ref{31b,,os.spawn*} functions. They should no longer be used to
write new code. The @ref{dc,,subprocess} module is recommended instead. Patch
by Victor Stinner.

@item 
gh-120732@footnote{https://github.com/python/cpython/issues/120732}: Fix @code{name} passing to @ref{c3f,,unittest.mock.Mock} object when
using @ref{1934,,unittest.mock.create_autospec()}.

@item 
gh-111259@footnote{https://github.com/python/cpython/issues/111259}: @ref{be,,re} now handles patterns like @code{"[\s\S]"} or @code{"\s|\S"}
which match any character as effectively as a dot with the @code{DOTALL}
modifier (@code{"(?s:.)"}).

@item 
gh-120683@footnote{https://github.com/python/cpython/issues/120683}: Fix an error in @ref{11e8,,logging.LogRecord}, when the integer
part of the timestamp is rounded up, while the millisecond calculation
truncates, causing the log timestamp to be wrong by up to 999 ms (affected
roughly 1 in 8 million timestamps).

@item 
gh-118710@footnote{https://github.com/python/cpython/issues/118710}: @ref{50c,,ipaddress.IPv4Address} and
@ref{50d,,ipaddress.IPv6Address} attributes @code{version} and
@code{max_prefixlen} are now available on the class.

@item 
gh-120633@footnote{https://github.com/python/cpython/issues/120633}: Move scrollbar and remove tear-off menus in turtledemo.

@item 
gh-120606@footnote{https://github.com/python/cpython/issues/120606}: Allow users to use EOF to exit @code{commands} definition in
@ref{aa,,pdb}

@item 
gh-120284@footnote{https://github.com/python/cpython/issues/120284}: Allow @ref{194d,,asyncio.Runner.run()} to accept @ref{4c9,,awaitable}
objects instead of simply @ref{6b9,,coroutine}s.

@item 
gh-120541@footnote{https://github.com/python/cpython/issues/120541}: Improve the prompt in the "less" pager when @ref{ad4,,help()} is
called with non-string argument.

@item 
gh-120495@footnote{https://github.com/python/cpython/issues/120495}: Fix incorrect exception handling in Tab Nanny. Patch by
Wulian233.

@item 
gh-120388@footnote{https://github.com/python/cpython/issues/120388}: Improve a warning message when a test method in @ref{10c,,unittest}
returns something other than @code{None}. Now we show the returned object
type and optional asyncio-related tip.

@item 
gh-120381@footnote{https://github.com/python/cpython/issues/120381}: Correct @ref{194e,,inspect.ismethoddescriptor()} to check also for
the lack of @ref{194f,,__delete__()}.  Patch by Jan Kaliszewski.

@item 
gh-90425@footnote{https://github.com/python/cpython/issues/90425}: The OS byte in gzip headers is now always set to 255 when using
@ref{84e,,gzip.compress()}.

@item 
gh-120343@footnote{https://github.com/python/cpython/issues/120343}: Fix column offset reporting for tokens that come after
multiline f-strings in the @ref{101,,tokenize} module.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: As part of implementing 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} and 
@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/}, add a new
module @code{annotationlib}. Add support for unresolved forward references in
annotations to @ref{33,,dataclasses}, @ref{332,,typing.TypedDict}, and
@ref{331,,typing.NamedTuple}.

@item 
gh-119600@footnote{https://github.com/python/cpython/issues/119600}: Fix @ref{1092,,unittest.mock.patch()} to not read attributes of the
target when @code{new_callable} is set. Patch by Robert Collins.

@item 
gh-120289@footnote{https://github.com/python/cpython/issues/120289}: Fixed the use-after-free issue in @ref{2b,,cProfile} by
disallowing @code{disable()} and @code{clear()} in external timers.

@item 
gh-82017@footnote{https://github.com/python/cpython/issues/82017}: Added support for converting any objects that have the
@code{as_integer_ratio()} method to a @ref{213,,Fraction}.

@item 
gh-114053@footnote{https://github.com/python/cpython/issues/114053}: Fix edge-case bug where @ref{8c0,,typing.get_type_hints()} would
produce incorrect results if type parameters in a class scope were
overridden by assignments in a class scope and @code{from __future__ import
annotations} semantics were enabled. Patch by Alex Waygood.

@item 
gh-114053@footnote{https://github.com/python/cpython/issues/114053}: Fix erroneous @ref{452,,NameError} when calling
@ref{a14,,inspect.get_annotations()} with @code{eval_str=True`} on a class that
made use of 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} type parameters in a module that had @code{from
__future__ import annotations} at the top of the file. Patch by Alex
Waygood.

@item 
gh-120268@footnote{https://github.com/python/cpython/issues/120268}: Prohibit passing @code{None} to pure-Python
@ref{dcd,,datetime.date.fromtimestamp()} to achieve consistency with
C-extension implementation.

@item 
gh-120244@footnote{https://github.com/python/cpython/issues/120244}: Fix memory leak in @ref{5a3,,re.sub()} when the replacement string
contains backreferences.

@item 
gh-120254@footnote{https://github.com/python/cpython/issues/120254}: Added @code{commands} argument to @ref{272,,pdb.set_trace()} which
allows users to send debugger commands from the source file.

@item 
gh-120211@footnote{https://github.com/python/cpython/issues/120211}: Fix @ref{ff,,tkinter.ttk} with Tcl/Tk 9.0.

@item 
gh-71587@footnote{https://github.com/python/cpython/issues/71587}: Fix crash in C version of @ref{1950,,datetime.datetime.strptime()}
when called again on the restarted interpreter.

@item 
gh-117983@footnote{https://github.com/python/cpython/issues/117983}: Defer the @code{threading} import in @code{importlib.util} until lazy
loading is used.

@item 
gh-120157@footnote{https://github.com/python/cpython/issues/120157}: Remove unused constant
@code{concurrent.futures._base._FUTURE_STATES} in @ref{24,,concurrent.futures}.
Patch by Clinton Christian (pygeek).

@item 
gh-120161@footnote{https://github.com/python/cpython/issues/120161}: @ref{34,,datetime} no longer crashes in certain complex reference
cycle situations.

@item 
gh-119698@footnote{https://github.com/python/cpython/issues/119698}: Fix @ref{31d,,symtable.Class.get_methods()} and document its
behaviour. Patch by Bénédikt Tran.

@item 
gh-120121@footnote{https://github.com/python/cpython/issues/120121}: Add @ref{1951,,concurrent.futures.InvalidStateError} to module's
@code{__all__}.

@item 
gh-119933@footnote{https://github.com/python/cpython/issues/119933}: Add the @ref{1952,,symtable.SymbolTableType} enumeration to
represent the possible outputs of the
@ref{1953,,symtable.SymbolTable.get_type} method. Patch by Bénédikt Tran.

@item 
gh-120029@footnote{https://github.com/python/cpython/issues/120029}: Expose @ref{289,,symtable.Symbol} methods
@ref{28c,,is_free_class()},
@ref{28b,,is_comp_iter()} and
@ref{28a,,is_comp_cell()}. Patch by Bénédikt Tran.

@item 
gh-120108@footnote{https://github.com/python/cpython/issues/120108}: Fix calling @ref{d65,,copy.deepcopy()} on @ref{9,,ast} trees that have
been modified to have references to parent nodes. Patch by Jelle Zijlstra.

@item 
gh-120056@footnote{https://github.com/python/cpython/issues/120056}: Add @code{socket.IP_RECVERR} and @code{socket.IP_RECVTTL}
constants (both available since Linux 2.2). And
@code{socket.IP_RECVORIGDSTADDR} constant (available since Linux
2.6.29).

@item 
gh-112672@footnote{https://github.com/python/cpython/issues/112672}: Support building @ref{f6,,tkinter} with Tcl 9.0.

@item 
gh-120057@footnote{https://github.com/python/cpython/issues/120057}: Added the @ref{259,,os.environ.refresh()} method to
update @ref{259,,os.environ} with changes to the environment made by
@ref{25b,,os.putenv()}, by @ref{25c,,os.unsetenv()}, or made outside Python in the
same process. Patch by Victor Stinner.

@item 
gh-120029@footnote{https://github.com/python/cpython/issues/120029}: Expose @ref{1954,,symtable.Symbol.is_type_parameter()} in the
@ref{de,,symtable} module. Patch by Bénédikt Tran.

@item 
gh-119819@footnote{https://github.com/python/cpython/issues/119819}: Fix regression to allow logging configuration with
multiprocessing queue types.

@item 
gh-65454@footnote{https://github.com/python/cpython/issues/65454}: @ref{1955,,unittest.mock.Mock.attach_mock()} no longer triggers a call
to a @code{PropertyMock} being attached.

@item 
gh-117142@footnote{https://github.com/python/cpython/issues/117142}: The @ref{2e,,ctypes} module may now be imported in all
subinterpreters, including those that have their own GIL.

@item 
gh-118835@footnote{https://github.com/python/cpython/issues/118835}: Fix _pyrepl crash when using custom prompt with ANSI escape
codes.

@item 
gh-81936@footnote{https://github.com/python/cpython/issues/81936}: @code{help()} and @code{showtopic()} methods now respect a
configured `output' argument to @code{pydoc.Helper} and not use the
pager in such cases. Patch by Enrico Tröger.

@item 
gh-117398@footnote{https://github.com/python/cpython/issues/117398}: The @code{_datetime} module (C implementation for @ref{34,,datetime})
now supports being imported in multiple interpreters.

@item 
gh-119824@footnote{https://github.com/python/cpython/issues/119824}: Print stack entry in @ref{aa,,pdb} when and only when user input
is needed.

@item 
gh-119838@footnote{https://github.com/python/cpython/issues/119838}: In mixed arithmetic operations with
@ref{213,,Fraction} and complex, the fraction is now converted to
@ref{196,,float} instead of @ref{197,,complex}.

@item 
gh-119770@footnote{https://github.com/python/cpython/issues/119770}: Make @ref{e7,,termios} @code{ioctl()} constants positive. Patch by
Victor Stinner.

@item 
gh-89727@footnote{https://github.com/python/cpython/issues/89727}: Fix issue with @ref{356,,shutil.rmtree()} where a
@ref{f68,,RecursionError} is raised on deep directory trees.

@item 
gh-119577@footnote{https://github.com/python/cpython/issues/119577}: The @ref{1a3,,DeprecationWarning} emitted when testing the truth
value of an @ref{363,,xml.etree.ElementTree.Element} now describes
unconditionally returning @code{True} in a future version rather than raising
an exception in Python 3.14.

@item 
gh-89727@footnote{https://github.com/python/cpython/issues/89727}: Partially fix issue with @ref{356,,shutil.rmtree()} where a
@ref{f68,,RecursionError} is raised on deep directory trees. A recursion error
is no longer raised when @code{rmtree.avoids_symlink_attacks} is false.

@item 
gh-93963@footnote{https://github.com/python/cpython/issues/93963}: Remove deprecated names from @code{importlib.abc} as found in
@code{importlib.resources.abc}.

@item 
gh-119118@footnote{https://github.com/python/cpython/issues/119118}: Fix performance regression in the @ref{101,,tokenize} module by
caching the @code{line} token attribute and calculating the column offset
more efficiently.

@item 
gh-89727@footnote{https://github.com/python/cpython/issues/89727}: Fix issue with @ref{d52,,os.fwalk()} where a @ref{f68,,RecursionError}
was raised on deep directory trees by adjusting the implementation to be
iterative instead of recursive.

@item 
gh-119594@footnote{https://github.com/python/cpython/issues/119594}: If one calls pow(fractions.Fraction, x, module) with modulo not
None, the error message now says that the types are incompatible rather
than saying pow only takes 2 arguments. Patch by Wim Jeantine-Glenn and
Mark Dickinson.

@item 
gh-119588@footnote{https://github.com/python/cpython/issues/119588}: @code{zipfile.Path.is_symlink} now assesses if the given path is a
symlink.

@item 
gh-119562@footnote{https://github.com/python/cpython/issues/119562}: Remove @code{ast.Num}, @code{ast.Str},
@code{ast.Bytes}, @code{ast.NameConstant} and
@code{ast.Ellipsis}. They had all emitted deprecation warnings since
Python 3.12. Patch by Alex Waygood.

@item 
gh-119555@footnote{https://github.com/python/cpython/issues/119555}: Catch @ref{18e,,SyntaxError} from @ref{4b1,,compile()} in the
runsource() method of the InteractiveColoredConsole.  Patch by Sergey B
Kirpichev.

@item 
gh-118908@footnote{https://github.com/python/cpython/issues/118908}: Limit exposed globals from internal imports and definitions on
new REPL startup. Patch by Eugene Triguba and Pablo Galindo.

@item 
gh-117865@footnote{https://github.com/python/cpython/issues/117865}: Improve the import time of the @ref{9,,ast} module by deferring
the import of @ref{be,,re}. Patch by Jelle Zijlstra.

@item 
gh-119127@footnote{https://github.com/python/cpython/issues/119127}: Positional arguments of @ref{217,,functools.partial()} objects now
support placeholders via @ref{216,,functools.Placeholder}.

@item 
gh-113892@footnote{https://github.com/python/cpython/issues/113892}: Now, the method @code{sock_connect} of
@ref{81d,,asyncio.ProactorEventLoop} raises a @ref{2ec,,ValueError} if given
socket is not in non-blocking mode, as well as in other loop
implementations.

@item 
gh-119506@footnote{https://github.com/python/cpython/issues/119506}: Fix @code{io.TextIOWrapper.write()} method breaks internal
buffer when the method is called again during flushing internal buffer.

@item 
gh-69214@footnote{https://github.com/python/cpython/issues/69214}: Fix @code{fcntl.ioctl()} `request' parameter: use an @code{unsigned
long} instead of an @code{unsigned int} for the `request' parameter of
@ref{1694,,fcntl.ioctl()} to support requests larger than @code{UINT_MAX}. Patch by
Victor Stinner.

@item 
gh-119105@footnote{https://github.com/python/cpython/issues/119105}: @code{difflib}'s @code{DIffer.compare()} (and so also @code{ndiff}) can
no longer be provoked into cubic-time behavior, or into unbounded
recursion, and should generally be faster in ordinary cases too. Results
may change in some cases, although that should be rare. Correctness of
diffs is not affected. Some similar lines far apart may be reported as
deleting one and adding the other, where before they were displayed on
adjacent output lines with markup showing the intraline differences.

@item 
gh-119443@footnote{https://github.com/python/cpython/issues/119443}: The interactive REPL no longer runs with @code{from __future__
import annotations} enabled. Patch by Jelle Zijlstra.

@item 
gh-119461@footnote{https://github.com/python/cpython/issues/119461}: Add @code{socket.VMADDR_CID_LOCAL} constant. Patch by Victor
Stinner.

@item 
gh-117398@footnote{https://github.com/python/cpython/issues/117398}: Objects in the datetime C-API are now all statically allocated,
which means better memory safety, especially when the module is reloaded.
This should be transparent to users.

@item 
gh-118894@footnote{https://github.com/python/cpython/issues/118894}: @ref{b,,asyncio} REPL now has the same capabilities as PyREPL.

@item 
gh-118830@footnote{https://github.com/python/cpython/issues/118830}: Bump @ref{ab,,pickle} default protocol to @code{5}.

@item 
gh-118911@footnote{https://github.com/python/cpython/issues/118911}: In PyREPL, updated @code{maybe-accept}'s logic so that if the user
hits @code{Enter} twice, they are able to terminate the block even if
there's trailing whitespace. Also, now when the user hits arrow up, the
cursor is on the last functional line. This matches IPython's behavior.
Patch by Aya Elsayed.

@item 
gh-115225@footnote{https://github.com/python/cpython/issues/115225}: Raise error on certain technically valid but pathological ISO
8601 strings passed to @ref{829,,datetime.time.fromisoformat()} that were
previously parsed incorrectly.

@item 
gh-111201@footnote{https://github.com/python/cpython/issues/111201}: Remove dependency to @ref{bf,,readline} from the new Python REPL.

@item 
gh-119189@footnote{https://github.com/python/cpython/issues/119189}: When using the @code{**} operator or @ref{1a4,,pow()} with
@ref{213,,Fraction} as the base and an exponent that is not
rational, a float, or a complex, the fraction is no longer converted to a
float.

@item 
gh-119174@footnote{https://github.com/python/cpython/issues/119174}: Fix high DPI causes turtledemo(turtle-graphics examples)
windows blurry Patch by Wulian233 and Terry Jan Reedy

@item 
gh-119121@footnote{https://github.com/python/cpython/issues/119121}: Fix a NameError happening in
@code{asyncio.staggered.staggered_race}. This function is now tested.

@item 
gh-119105@footnote{https://github.com/python/cpython/issues/119105}: @code{difflib.Differ} is much faster for some cases of diffs where
many pairs of lines are equally similar.

@item 
gh-119113@footnote{https://github.com/python/cpython/issues/119113}: Fix issue where @ref{1956,,pathlib.PurePath.with_suffix()} didn't
raise @ref{198,,TypeError} when given @code{None} as a suffix.

@item 
gh-118643@footnote{https://github.com/python/cpython/issues/118643}: Fix an AttributeError in the @ref{3f,,email} module when re-fold a
long address list. Also fix more cases of incorrect encoding of the
address separator in the address list.

@item 
gh-73991@footnote{https://github.com/python/cpython/issues/73991}: Add @ref{267,,pathlib.Path.copy()}, which copies a file or directory
to another.

@item 
gh-58933@footnote{https://github.com/python/cpython/issues/58933}: Make @ref{aa,,pdb} return to caller frame correctly when
@code{f_trace} of the caller frame is not set

@item 
gh-82805@footnote{https://github.com/python/cpython/issues/82805}: Support single-dot file extensions in
@ref{1957,,pathlib.PurePath.suffix} and related attributes and methods. For
example, the @ref{1958,,suffixes} of
@code{PurePath('foo.bar.')} are now @code{['.bar', '.']} rather than @code{[]}.
This brings file extension splitting in line with
@ref{1959,,os.path.splitext()}.

@item 
gh-118924@footnote{https://github.com/python/cpython/issues/118924}: Remove @code{version} and @code{version_info} from
@ref{d4,,sqlite3}. Patch by Hugo van Kemenade.

@item 
gh-118928@footnote{https://github.com/python/cpython/issues/118928}: Disallow using a sequence of parameters with named placeholders
in @ref{d4,,sqlite3} queries. Patch by Erlend E. Aasland.

@item 
gh-118895@footnote{https://github.com/python/cpython/issues/118895}: Setting attributes on @ref{569,,typing.NoDefault} now raises
@ref{5f0,,AttributeError} instead of @ref{198,,TypeError}.

@item 
gh-118868@footnote{https://github.com/python/cpython/issues/118868}: Fixed issue where kwargs were no longer passed to the logging
handler QueueHandler

@item 
gh-118827@footnote{https://github.com/python/cpython/issues/118827}: Remove deprecated @code{Quoter} class from
@ref{110,,urllib.parse}. It had previously raised a @ref{1a3,,DeprecationWarning}
since Python 3.11. Patch by Nikita Sobolev.

@item 
gh-118824@footnote{https://github.com/python/cpython/issues/118824}: Remove deprecated @code{pty.master_open()} and
@code{pty.slave_open()}. Use @ref{301,,pty.openpty()} instead. Patch by Nikita
Sobolev.

@item 
gh-118851@footnote{https://github.com/python/cpython/issues/118851}: @code{ctx} arguments to the constructors of @ref{9,,ast} node
classes now default to @ref{4c2,,ast.Load()}. Patch by Jelle
Zijlstra.

@item 
gh-101588@footnote{https://github.com/python/cpython/issues/101588}: Remove copy, deepcopy, and pickle from itertools. These had
previously raised a DeprecationWarning since Python 3.12.

@item 
gh-118805@footnote{https://github.com/python/cpython/issues/118805}: Remove `type', `choices', and `metavar' parameters of
@code{argparse.BooleanOptionalAction}. They were deprecated since
Python 3.12.

@item 
gh-118803@footnote{https://github.com/python/cpython/issues/118803}: @code{typing.ByteString} and
@code{collections.abc.ByteString} are removed. They had previously
raised a @ref{1a3,,DeprecationWarning} since Python 3.12.

@item 
gh-118798@footnote{https://github.com/python/cpython/issues/118798}: The `isdst' parameter has been removed from
@ref{2f7,,email.utils.localtime()}. Patch by Hugo van Kemenade.

@item 
gh-118760@footnote{https://github.com/python/cpython/issues/118760}: Restore the default value of @code{tkiter.wantobjects} to @code{1}.

@item 
gh-118760@footnote{https://github.com/python/cpython/issues/118760}: Fix errors in calling Tkinter bindings on Windows.

@item 
gh-74033@footnote{https://github.com/python/cpython/issues/74033}: Drop support for passing keyword arguments to
@ref{266,,pathlib.Path}.

@item 
gh-101357@footnote{https://github.com/python/cpython/issues/101357}: Suppress all @ref{2c0,,OSError} exceptions from
@ref{c0b,,pathlib.Path.exists()} and @code{is_*()} methods, rather than a
selection of more common errors. The new behaviour is consistent with
@ref{c03,,os.path.exists()}, @ref{c05,,os.path.isdir()}, etc. Use
@ref{a24,,pathlib.Path.stat()} to retrieve the file status without suppressing
exceptions.

@item 
gh-78707@footnote{https://github.com/python/cpython/issues/78707}: Drop support for passing additional positional arguments to
@ref{2fd,,pathlib.PurePath.relative_to()} and
@ref{2fe,,is_relative_to()}.

@item 
gh-118507@footnote{https://github.com/python/cpython/issues/118507}: Fix @ref{c06,,os.path.isfile()} on Windows for pipes. Speedup
@ref{6ca,,os.path.isjunction()} and @ref{c04,,os.path.lexists()} on Windows with a
native implementation.

@item 
gh-118772@footnote{https://github.com/python/cpython/issues/118772}: Allow @ref{486,,typing.TypeVar} instances without a default to
follow instances without a default in some cases. Patch by Jelle Zijlstra.

@item 
gh-118714@footnote{https://github.com/python/cpython/issues/118714}: Allow @code{restart} in post-mortem debugging of @ref{aa,,pdb}.
Removed restart message when the user quits pdb from post-mortem mode.

@item 
gh-118673@footnote{https://github.com/python/cpython/issues/118673}: Removed executable bits and shebang from stdlib modules.

@item 
gh-110863@footnote{https://github.com/python/cpython/issues/110863}: @ref{262,,os.path.realpath()} now suppresses any @ref{2c0,,OSError} from
@ref{b1a,,os.readlink()} when `strict' mode is disabled (the default).

@item 
gh-118263@footnote{https://github.com/python/cpython/issues/118263}: Speed up @ref{6cb,,os.path.splitroot()} & @ref{1531,,os.path.normpath()}
with a direct C call.

@item 
gh-110190@footnote{https://github.com/python/cpython/issues/110190}: Fix ctypes structs with array on SPARC by setting
@code{MAX_STRUCT_SIZE} to 32 in stgdict. Patch by Jakub Kulik

@item 
gh-118033@footnote{https://github.com/python/cpython/issues/118033}: Fix @ref{4e1,,dataclasses.dataclass()} not creating a
@code{__weakref__} slot when subclassing @ref{17b6,,typing.Generic}.

@item 
gh-117766@footnote{https://github.com/python/cpython/issues/117766}: Always use @ref{169,,str()} to print @code{choices} in @ref{7,,argparse}.

@item 
gh-106531@footnote{https://github.com/python/cpython/issues/106531}: In @ref{7f,,importlib.resources}, sync with importlib_resources 6.3.2@footnote{https://importlib-resources.readthedocs.io/en/latest/history.html#v6-3-2},
including: @code{MultiplexedPath} now expects @code{Traversable} paths,
deprecating string arguments to @code{MultiplexedPath}; Enabled support for
resources in namespace packages in zip files; Fixed @code{NotADirectoryError}
when calling files on a subdirectory of a namespace package.

@item 
gh-115937@footnote{https://github.com/python/cpython/issues/115937}: Removed extra preprocessing for the @code{__signature__}
attribute: the code just check if it's a @ref{4e3,,inspect.Signature}
instance.  Patch by Sergey B Kirpichev.

@item 
gh-115808@footnote{https://github.com/python/cpython/issues/115808}: Add @ref{255,,operator.is_none()} and @ref{256,,operator.is_not_none()}
functions.

@item 
gh-114264@footnote{https://github.com/python/cpython/issues/114264}: Improve performance of @ref{d65,,copy.deepcopy()} by adding a fast
path for atomic types.

@item 
gh-113878@footnote{https://github.com/python/cpython/issues/113878}: Add `doc' parameter to @ref{195a,,dataclasses.field()}, so it can be
stored and shown as a documentation / metadata. If
@code{@@dataclass(slots=True)} is used, then the supplied string is available
in the @ref{1704,,__slots__} dict. Otherwise, the supplied string is
only available in the corresponding @ref{195b,,dataclasses.Field} object.

In order to support this feature we are changing the @code{__slots__} format
in dataclasses from @ref{614,,tuple} to @ref{183,,dict} when documentation /
metadata is present.

@item 
gh-113978@footnote{https://github.com/python/cpython/issues/113978}: Ignore warnings on text completion inside REPL.

@item 
gh-113008@footnote{https://github.com/python/cpython/issues/113008}: Correct argparse usage output for required, mutually exclusive
groups containing a positional argument

@item 
gh-108172@footnote{https://github.com/python/cpython/issues/108172}: @code{webbrowser} honors OS preferred browser on Linux when its
desktop entry name contains the text of a known browser name.

@item 
gh-109109@footnote{https://github.com/python/cpython/issues/109109}: You can now get the raw TLS certificate chains from TLS
connections via @ref{195c,,ssl.SSLSocket.get_verified_chain()} and
@ref{195d,,ssl.SSLSocket.get_unverified_chain()} methods.

Contributed by Mateusz Nowak.

@item 
gh-105623@footnote{https://github.com/python/cpython/issues/105623}: Fix performance degradation in
@ref{1941,,logging.handlers.RotatingFileHandler}. Patch by Craig Robson.

@item 
gh-102450@footnote{https://github.com/python/cpython/issues/102450}: Add missing ISO-8601 24:00 alternative to midnight of next day
to @ref{82a,,datetime.datetime.fromisoformat()} and
@ref{829,,datetime.time.fromisoformat()}. Patch by Izan "TizzySaurus" Robinson
(@email{tizzysaurus@@gmail.com})

@item 
gh-103956@footnote{https://github.com/python/cpython/issues/103956}: Fix lack of newline characters in @ref{103,,trace} module output
when line tracing is enabled but source code line for current frame is not
available.

@item 
gh-92081@footnote{https://github.com/python/cpython/issues/92081}: Fix missing spaces in email headers when the spaces are mixed
with encoded 8-bit characters.

@item 
gh-103194@footnote{https://github.com/python/cpython/issues/103194}: Prepare Tkinter for C API changes in Tcl 8.7/9.0 to avoid
@code{_tkinter.Tcl_Obj} being unexpectedly returned instead of
@ref{3c3,,bool}, @ref{169,,str}, @ref{344,,bytearray}, or @ref{19b,,int}.

@item 
gh-87106@footnote{https://github.com/python/cpython/issues/87106}: Fixed handling in @ref{1892,,inspect.Signature.bind()} of keyword
arguments having the same name as positional-only arguments when a
variadic keyword argument (e.g. @code{**kwargs}) is present.

@item 
gh-103134@footnote{https://github.com/python/cpython/issues/103134}: Add additional methods to @ref{24c,,proxy objects} in the @code{multiprocessing} module:


@itemize *

@item 
@code{clear()} and @code{copy()} for proxies of @ref{24d,,list}

@item 
@ref{24e,,fromkeys()}, @code{reversed(d)}, @code{d | @{@}}, @code{@{@} | d},
@code{d |= @{'b': 2@}} for proxies of @ref{183,,dict}
@end itemize

@item 
bpo-45767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45767}: Fix integer conversion in @ref{195e,,os.major()}, @ref{195f,,os.minor()},
and @ref{1960,,os.makedev()}. Support device numbers larger than @code{2**63-1}.
Support non-existent device number (@code{NODEV}).

@item 
bpo-44864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44864}: Do not translate user-provided strings in
@ref{1bd,,argparse.ArgumentParser}.

@item 
bpo-41843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41843}: Solaris now uses @ref{d05,,os.sendfile()} fast-copy syscall for more
efficient @ref{ca,,shutil} file copy related functions.

@item 
bpo-15987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15987}: Implemented @ref{1bf,,ast.compare()} for comparing two ASTs. Patch
by Batuhan Taskaya with some help from Jeremy Hylton.

@item 
gh-67693@footnote{https://github.com/python/cpython/issues/67693}: Fix @ref{193f,,urllib.parse.urlunparse()} and
@ref{193e,,urllib.parse.urlunsplit()} for URIs with path starting with multiple
slashes and no authority. Based on patch by Ashwin Ramaswami.

@item 
bpo-14074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14074}: Fix @ref{7,,argparse} metavar processing to allow positional
arguments to have a tuple metavar.
@end itemize

@node IDLE<7>,ドキュメント<14>,ライブラリ<46>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id187}@anchor{1961}
@subsubsection IDLE



@itemize -

@item 
gh-122392@footnote{https://github.com/python/cpython/issues/122392}: Increase currently inadequate vertical spacing for the IDLE
browsers (path, module, and stack) on high-resolution monitors.

@item 
gh-112938@footnote{https://github.com/python/cpython/issues/112938}: Fix uninteruptable hang when Shell gets rapid continuous
output.

@item 
gh-122482@footnote{https://github.com/python/cpython/issues/122482}: Change About IDLE to direct users to discuss.python.org instead
of the now unused idle-dev email and mailing list.

@item 
gh-78889@footnote{https://github.com/python/cpython/issues/78889}: Stop Shell freezes by blocking user access to non-method
sys.stdout.shell attributes, which are all private.

@item 
gh-120083@footnote{https://github.com/python/cpython/issues/120083}: Add explicit black IDLE Hovertip foreground color needed for
recent macOS. Fixes Sonoma showing unreadable white on pale yellow.  Patch
by John Riggles.

@item 
gh-120104@footnote{https://github.com/python/cpython/issues/120104}: Fix padding in config and search dialog windows in IDLE.
@end itemize

@node ドキュメント<14>,Core and Builtins<41>,IDLE<7>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id188}@anchor{1962}
@subsubsection ドキュメント



@itemize -

@item 
gh-124872@footnote{https://github.com/python/cpython/issues/124872}: Added definitions for @ref{1963,,context}, @ref{1964,,current context},
and @ref{1965,,context management protocol}, updated related definitions to be
consistent, and expanded the documentation for
@ref{177,,contextvars.Context}.

@item 
gh-125018@footnote{https://github.com/python/cpython/issues/125018}: The @ref{7e,,importlib.metadata} documentation now includes
semantic cross-reference targets for the significant documented APIs. This
means intersphinx references like @ref{1966,,importlib.metadata.version()} will
now work as expected.

@item 
gh-124720@footnote{https://github.com/python/cpython/issues/124720}: Update "Using Python on a Mac" section of the "Python Setup and
Usage" document and include information on installing free-threading
support.

@item 
gh-124457@footnote{https://github.com/python/cpython/issues/124457}: Remove coverity scan from the CPython repo. It has not been
used since 2020 and is currently unmaintained.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: Add an Android platform guide, and flag modules not available
on Android.

@item 
gh-123976@footnote{https://github.com/python/cpython/issues/123976}: Refresh docs around custom providers.

@item 
gh-70870@footnote{https://github.com/python/cpython/issues/70870}: Clarified the dual usage of the term "free variable" (both the
formal meaning of any reference to names defined outside the local scope,
and the narrower pragmatic meaning of nonlocal variables named in
@code{co_freevars}).

@item 
gh-121277@footnote{https://github.com/python/cpython/issues/121277}: Writers of CPython's documentation can now use @code{next} as the
version for the @code{versionchanged}, @code{versionadded}, @code{deprecated}
directives.

@item 
gh-117765@footnote{https://github.com/python/cpython/issues/117765}: Improved documentation for @ref{1967,,unittest.mock.patch.dict()}

@item 
gh-121749@footnote{https://github.com/python/cpython/issues/121749}: Fix documentation for @ref{60a,,PyModule_AddObjectRef()}.

@item 
gh-120012@footnote{https://github.com/python/cpython/issues/120012}: Clarify the behaviours of @ref{1968,,multiprocessing.Queue.empty()}
and @ref{1969,,multiprocessing.SimpleQueue.empty()} on closed queues. Patch by
Bénédikt Tran.

@item 
gh-119574@footnote{https://github.com/python/cpython/issues/119574}: Added some missing environment variables to the output of
@ref{808,,--help-env}.

@item 
bpo-34008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34008}: The @ref{e1e,,Py_Main()} documentation moved from the "Very High
Level API" section to the "Initialization and Finalization" section.

Also make it explicit that we expect @code{Py_Main} to typically be called
instead of @code{Py_Initialize} rather than after it (since @code{Py_Main} makes
its own call to @code{Py_Initialize}). Document that calling both is
supported but is version dependent on which settings will be applied
correctly.
@end itemize

@node Core and Builtins<41>,ライブラリ<47>,ドキュメント<14>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id189}@anchor{196a}
@subsubsection Core and Builtins



@itemize -

@item 
gh-124375@footnote{https://github.com/python/cpython/issues/124375}: Fix a crash in the free threading build when the GC runs
concurrently with a new thread starting.

@item 
gh-125221@footnote{https://github.com/python/cpython/issues/125221}: Fix possible race condition when calling
@ref{196b,,__reduce_ex__()} for the first time in the free threading
build.

@item 
gh-125174@footnote{https://github.com/python/cpython/issues/125174}: Make the handling of reference counts of immortal objects more
robust. Immortal objects with reference counts that deviate from their
original reference count by up to a billion (half a billion on 32 bit
builds) are still counted as immortal.

@item 
gh-125039@footnote{https://github.com/python/cpython/issues/125039}: Make @code{this_instr} and @code{prev_instr} const in cases
generator.
@end itemize

@node ライブラリ<47>,Core and Builtins<42>,Core and Builtins<41>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id190}@anchor{196c}
@subsubsection ライブラリ



@itemize -

@item 
gh-125008@footnote{https://github.com/python/cpython/issues/125008}: Fix @ref{18b3,,tokenize.untokenize()} producing invalid syntax for
double braces preceded by certain escape characters.
@end itemize

@node Core and Builtins<42>,ライブラリ<48>,ライブラリ<47>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id191}@anchor{196d}
@subsubsection Core and Builtins



@itemize -

@item 
gh-124871@footnote{https://github.com/python/cpython/issues/124871}: Fix compiler bug (in some versions of 3.13) where an assertion
fails during reachability analysis.

@item 
gh-123378@footnote{https://github.com/python/cpython/issues/123378}: Fix a crash in the @ref{830,,__str__()} method of
@ref{462,,UnicodeError} objects when the @ref{18c0,,UnicodeError.start} and
@ref{18c1,,UnicodeError.end} values are invalid or out-of-range. Patch by
Bénédikt Tran.

@item 
gh-118093@footnote{https://github.com/python/cpython/issues/118093}: Improve the experimental JIT compiler's ability to stay "on
trace" when encountering highly-biased branches.

@item 
gh-124642@footnote{https://github.com/python/cpython/issues/124642}: Fixed scalability issue in free-threaded builds for lock-free
reads from dictionaries in multi-threaded scenarios

@item 
gh-116510@footnote{https://github.com/python/cpython/issues/116510}: Fix a crash caused by immortal interned strings being shared
between sub-interpreters that use basic single-phase init.  In that case,
the string can be used by an interpreter that outlives the interpreter
that created and interned it.  For interpreters that share obmalloc state,
also share the interned dict with the main interpreter.

@item 
gh-116510@footnote{https://github.com/python/cpython/issues/116510}: Fix a bug that can cause a crash when sub-interpreters use
"basic" single-phase extension modules.  Shared objects could refer to
PyGC_Head nodes that had been freed as part of interpreter cleanup.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: The @code{__main__} module no longer always contains an
@code{__annotations__} dictionary in its global namespace.

@item 
gh-124547@footnote{https://github.com/python/cpython/issues/124547}: When deallocating an object with inline values whose
@code{__dict__} is still live: if memory allocation for the inline values
fails, clear the dictionary. Prevents an interpreter crash.

@item 
gh-124513@footnote{https://github.com/python/cpython/issues/124513}: Fix a crash in FrameLocalsProxy constructor: check the number
of arguments. Patch by Victor Stinner.

@item 
gh-124442@footnote{https://github.com/python/cpython/issues/124442}: Fix nondeterminism in compilation by sorting the value of
@ref{477,,__static_attributes__}. Patch by kp2pml30.

@item 
gh-124285@footnote{https://github.com/python/cpython/issues/124285}: Fix bug where @code{bool(a)} can be invoked more than once during
the evaluation of a compound boolean expression.

@item 
gh-123856@footnote{https://github.com/python/cpython/issues/123856}: Fix PyREPL failure when a keyboard interrupt is triggered after
using a history search

@item 
gh-65961@footnote{https://github.com/python/cpython/issues/65961}: Deprecate the setting and using @code{__package__} and
@code{__cached__}.

@item 
gh-119726@footnote{https://github.com/python/cpython/issues/119726}: The JIT now generates more efficient code for calls to C
functions resulting in up to 0.8% memory savings and 1.5% speed
improvement on AArch64. Patch by Diego Russo.

@item 
gh-122878@footnote{https://github.com/python/cpython/issues/122878}: Use the @code{pager} binary, if available (e.g. on Debian and
derivatives), to display REPL @code{help()}.

@item 
gh-124188@footnote{https://github.com/python/cpython/issues/124188}: Fix reading and decoding a line from the source file with
non-UTF-8 encoding for syntax errors raised in the compiler.

@item 
gh-124027@footnote{https://github.com/python/cpython/issues/124027}: Support @code{<page up>}, @code{<page down>}, and @code{<delete>} keys
in the Python REPL when @code{$TERM} is set to @code{vt100}.

@item 
gh-124022@footnote{https://github.com/python/cpython/issues/124022}: Fix bug where docstring is removed from classes in interactive
mode.

@item 
gh-123958@footnote{https://github.com/python/cpython/issues/123958}: docstrings are now removed from the optimized AST in
optimization level 2.

@item 
gh-123923@footnote{https://github.com/python/cpython/issues/123923}: The @code{f_executable} field in the internal
@ref{196e,,_PyInterpreterFrame} struct now uses a tagged pointer.
Profilers and debuggers that uses this field should clear the least
significant bit to recover the @ref{5df,,PyObject}* pointer.

@item 
gh-77894@footnote{https://github.com/python/cpython/issues/77894}: Fix possible crash in the garbage collector when it tries to
break a reference loop containing a @ref{165,,memoryview} object. Now a
@code{memoryview} object can only be cleared if there are no buffers
that refer it.

@item 
gh-120221@footnote{https://github.com/python/cpython/issues/120221}: asyncio REPL is now again properly recognizing
KeyboardInterrupts. Display of exceptions raised in secondary threads is
fixed.

@item 
gh-119310@footnote{https://github.com/python/cpython/issues/119310}: Allow the new interactive shell to read history files written
with the editline library that use unicode-escaped entries.  Patch by
aorcajo and Łukasz Langa.

@item 
gh-123572@footnote{https://github.com/python/cpython/issues/123572}: Fix key mappings for various F-keys in Windows for the new
REPL. Patch by devdanzin
@end itemize

@node ライブラリ<48>,Core and Builtins<43>,Core and Builtins<42>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id192}@anchor{196f}
@subsubsection ライブラリ



@itemize -

@item 
gh-123614@footnote{https://github.com/python/cpython/issues/123614}: Add @ref{1970,,turtle.save()} to easily save Turtle drawings as
PostScript files. Patch by Marie Roald and Yngve Mardal Moe.
@end itemize

@node Core and Builtins<43>,ライブラリ<49>,ライブラリ<48>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id193}@anchor{1971}
@subsubsection Core and Builtins



@itemize -

@item 
gh-123339@footnote{https://github.com/python/cpython/issues/123339}: Setting the @code{__module__} attribute for a class now
removes the @code{__firstlineno__} item from the type's dict, so they will no
longer be inconsistent.

@item 
gh-119034@footnote{https://github.com/python/cpython/issues/119034}: Change @code{<page up>} and @code{<page down>} keys of the Python
REPL to history search forward/backward. Patch by Victor Stinner.

@item 
gh-123562@footnote{https://github.com/python/cpython/issues/123562}: Improve @ref{18e,,SyntaxError} message for using @code{case ... as
...} with not a name.

@item 
gh-123545@footnote{https://github.com/python/cpython/issues/123545}: Fix a double decref in rare cases on experimental JIT builds.

@item 
gh-123484@footnote{https://github.com/python/cpython/issues/123484}: Fix @code{_Py_DebugOffsets} for long objects to be relative to the
start of the object rather than the start of a subobject.

@item 
gh-123446@footnote{https://github.com/python/cpython/issues/123446}: Fix empty function name in @ref{198,,TypeError} when builtin magic
methods are used without the required args.

@item 
gh-123440@footnote{https://github.com/python/cpython/issues/123440}: Improve @ref{18e,,SyntaxError} message for using @code{except as} with
not a name.

@item 
gh-116017@footnote{https://github.com/python/cpython/issues/116017}: Improved JIT memory consumption by periodically freeing memory
used by infrequently-executed code. This change is especially likely to
improve the memory footprint of long-running programs.

@item 
gh-123344@footnote{https://github.com/python/cpython/issues/123344}: Add AST optimizations for type parameter defaults.

@item 
gh-123321@footnote{https://github.com/python/cpython/issues/123321}: Prevent Parser/myreadline race condition from segfaulting on
multi-threaded use. Patch by Bar Harel and Amit Wienner.

@item 
gh-123177@footnote{https://github.com/python/cpython/issues/123177}: Fix a bug causing stray prompts to appear in the middle of
wrapped lines in the new REPL.

@item 
gh-122982@footnote{https://github.com/python/cpython/issues/122982}: Extend the deprecation period for bool inversion (@code{~}) by two
years.

@item 
gh-123271@footnote{https://github.com/python/cpython/issues/123271}: Make concurrent iterations over the same @ref{1a0,,zip()} iterator
safe under free-threading.

@item 
gh-123275@footnote{https://github.com/python/cpython/issues/123275}: Support @ref{16f,,-X gil=1} and 
@geindex PYTHON_GIL
@geindex 環境変数; PYTHON_GIL
@ref{49a,,PYTHON_GIL=1} on non-free-threaded builds.

@item 
gh-123177@footnote{https://github.com/python/cpython/issues/123177}: Deactivate line wrap in the Apple Terminal via a ANSI escape
code. Patch by Pablo Galindo

@item 
gh-123229@footnote{https://github.com/python/cpython/issues/123229}: Fix valgrind warning by initializing the f-string buffers to 0
in the tokenizer. Patch by Pablo Galindo

@item 
gh-122298@footnote{https://github.com/python/cpython/issues/122298}: Restore printout of GC stats when
@code{gc.set_debug(gc.DEBUG_STATS)} is called. This feature was accidentally
removed when implementing incremental GC.

@item 
gh-121804@footnote{https://github.com/python/cpython/issues/121804}: Correctly show error locations when a @ref{18e,,SyntaxError} is
raised in the basic REPL. Patch by Sergey B Kirpichev.

@item 
gh-115776@footnote{https://github.com/python/cpython/issues/115776}: Enables inline values (Python's equivalent of hidden classes)
on any class who's instances are of a fixed size.

@item 
gh-123142@footnote{https://github.com/python/cpython/issues/123142}: Fix too-wide source location in exception tracebacks coming
from broken iterables in comprehensions.

@item 
gh-123048@footnote{https://github.com/python/cpython/issues/123048}: Fix a bug where pattern matching code could emit a
@ref{1972,,JUMP_FORWARD} with no source location.

@item 
gh-118093@footnote{https://github.com/python/cpython/issues/118093}: Break up @code{CALL_ALLOC_AND_ENTER_INIT} into micro-ops and relax
requirement for exact args, in order to increase the amount of code
supported by tier 2.

@item 
gh-123123@footnote{https://github.com/python/cpython/issues/123123}: Fix displaying @ref{18e,,SyntaxError} exceptions covering multiple
lines. Patch by Pablo Galindo

@item 
gh-123083@footnote{https://github.com/python/cpython/issues/123083}: Fix a potential use-after-free in @code{STORE_ATTR_WITH_HINT}.

@item 
gh-123022@footnote{https://github.com/python/cpython/issues/123022}: Fix crash in free-threaded build when calling
@ref{460,,Py_Initialize()} from a non-main thread.

@item 
gh-118093@footnote{https://github.com/python/cpython/issues/118093}: Add three specializations for @ref{372,,CALL_KW}:


@itemize *

@item 
@code{CALL_KW_PY} for calls to Python functions

@item 
@code{CALL_KW_BOUND_METHOD} for calls to bound methods

@item 
@code{CALL_KW_NON_PY} for all other calls
@end itemize

@item 
gh-122821@footnote{https://github.com/python/cpython/issues/122821}: Make sure that branches in @ref{1973,,while} statements have
consistent offsets for @ref{e0,,sys.monitoring}. @code{while} statements
are now compiled with a simple jump at the end of the body, instead of
duplicating the test.

@item 
gh-122907@footnote{https://github.com/python/cpython/issues/122907}: Building with @code{HAVE_DYNAMIC_LOADING} now works as well as it
did in 3.12. Existing deficiences will be addressed separately. (See
@indicateurl{https://github.com/python/cpython/issues/122950}.)

@item 
gh-122888@footnote{https://github.com/python/cpython/issues/122888}: Fix crash on certain calls to @code{str()} with positional
arguments of the wrong type. Patch by Jelle Zijlstra.

@item 
gh-118093@footnote{https://github.com/python/cpython/issues/118093}: Improve the experimental JIT's handling of polymorphic code.

@item 
gh-122697@footnote{https://github.com/python/cpython/issues/122697}: Fixed memory leaks at interpreter shutdown in the free-threaded
build, and also reporting of leaked memory blocks via @ref{16f,,-X showrefcount}.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: Fix Android stdout and stderr messages being truncated or lost.

@item 
gh-122527@footnote{https://github.com/python/cpython/issues/122527}: Fix a crash that occurred when a @code{PyStructSequence} was
deallocated after its type's dictionary was cleared by the GC.  The type's
@ref{b7e,,tp_basicsize} now accounts for non-sequence
fields that aren't included in the @ref{985,,Py_SIZE} of the sequence.

@item 
gh-122445@footnote{https://github.com/python/cpython/issues/122445}: Add only fields which are modified via self.* to
@ref{477,,__static_attributes__}.

@item 
gh-122417@footnote{https://github.com/python/cpython/issues/122417}: In the free-threaded build, the reference counts for heap type
objects are now partially stored in a distributed manner in per-thread
arrays.  This reduces contention on the heap type's reference count fields
when creating or destroying instances of the same type from multiple
threads concurrently.

@item 
gh-116090@footnote{https://github.com/python/cpython/issues/116090}: Fix an issue in JIT builds that prevented some @ref{34a,,for}
loops from correctly firing @ref{1974,,RAISE} monitoring events.

@item 
gh-122300@footnote{https://github.com/python/cpython/issues/122300}: Preserve AST nodes for f-string with single-element format
specifiers. Patch by Pablo Galindo

@item 
gh-120906@footnote{https://github.com/python/cpython/issues/120906}: @ref{4a5,,frame.f_locals} now supports arbitrary hashable objects
as keys.

@item 
gh-122239@footnote{https://github.com/python/cpython/issues/122239}: When a @ref{24d,,list}, @ref{614,,tuple} or @ref{183,,dict} with too
many elements is unpacked, show the actual length in the error message.

@item 
gh-122245@footnote{https://github.com/python/cpython/issues/122245}: Detection of writes to @code{__debug__} is moved from the
compiler's codegen stage to the symtable. This means that these errors are
now detected even in code that is optimized away before codegen (such as
assertions with the @ref{18c,,-O} command line option).

@item 
gh-122234@footnote{https://github.com/python/cpython/issues/122234}: Specializations for sums with float and complex inputs in
@ref{695,,sum()} now always use compensated summation.  Also, for integer items
in above specializations: @ref{1975,,PyLong_AsDouble()} is used, instead of
@ref{147d,,PyLong_AsLongAndOverflow()}.  Patch by Sergey B Kirpichev.

@item 
gh-122208@footnote{https://github.com/python/cpython/issues/122208}: Dictionary watchers now only deliver the PyDict_EVENT_ADDED
event when the insertion is in a known good state to succeed.

@item 
gh-122160@footnote{https://github.com/python/cpython/issues/122160}: Remove the @code{BUILD_CONST_KEY_MAP} opcode. Use
@ref{369,,BUILD_MAP} instead.

@item 
gh-122029@footnote{https://github.com/python/cpython/issues/122029}: Emit @code{c_call} events in @ref{1717,,sys.setprofile()} when a
@code{PyMethodObject} pointing to a @code{PyCFunction} is called.

@item 
gh-122026@footnote{https://github.com/python/cpython/issues/122026}: Fix a bug that caused the tokenizer to not correctly identify
mismatched parentheses inside f-strings in some situations. Patch by Pablo
Galindo

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Python's hashlib now unconditionally uses the vendored HACL*
library for Blake2. Python no longer accepts libb2 as an optional
dependency for Blake2.

We refreshed HACL* to the latest version, and now vendor HACL*'s 128-bit
and 256-bit wide vector implementations for Blake2, which are used on
x86/x64 toolchains when the required CPU features are available at
runtime.

HACL*'s 128-bit wide vector implementation of Blake2 can also run on ARM
NEON and Power8, but lacking evidence of a performance gain, these are not
enabled (yet).
@end itemize

@node ライブラリ<49>,Core and Builtins<44>,Core and Builtins<43>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id194}@anchor{1976}
@subsubsection ライブラリ



@itemize -

@item 
gh-121999@footnote{https://github.com/python/cpython/issues/121999}: The default extraction filter for the @ref{e4,,tarfile} module is
now set to @ref{29a,,'data'}.
@end itemize

@node Core and Builtins<44>,ライブラリ<50>,ライブラリ<49>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id195}@anchor{1977}
@subsubsection Core and Builtins



@itemize -

@item 
gh-121860@footnote{https://github.com/python/cpython/issues/121860}: Fix crash when rematerializing a managed dictionary after it
was deleted.

@item 
gh-121795@footnote{https://github.com/python/cpython/issues/121795}: Improve performance of set membership testing, @code{set.remove()}
and @code{set.discard()} when the argument is a set.

@item 
gh-121814@footnote{https://github.com/python/cpython/issues/121814}: Fixed the SegFault when @ref{663,,PyEval_SetTrace()} is used with
no Python frame on stack.

@item 
gh-121295@footnote{https://github.com/python/cpython/issues/121295}: Fix PyREPL console getting into a blocked state after
interrupting a long paste

@item 
gh-121794@footnote{https://github.com/python/cpython/issues/121794}: Fix bug in free-threaded Python where a resurrected object
could lead to a negative ref count assertion failure.

@item 
gh-121657@footnote{https://github.com/python/cpython/issues/121657}: Improve the @ref{18e,,SyntaxError} message if the user tries to use
@ref{bc2,,yield from} outside a function.

@item 
gh-121609@footnote{https://github.com/python/cpython/issues/121609}: Fix pasting of characters containing unicode character joiners
in the new REPL. Patch by Marta Gomez Macias

@item 
gh-121297@footnote{https://github.com/python/cpython/issues/121297}: Previously, incorrect usage of @ref{18d,,await} or asynchronous
comprehensions in code removed by the @ref{18c,,-O} option was not flagged
by the Python compiler. Now, such code raises @ref{18e,,SyntaxError}. Patch by
Jelle Zijlstra.

@item 
gh-117482@footnote{https://github.com/python/cpython/issues/117482}: Unexpected slot wrappers are no longer created for builtin
static types in subinterpreters.

@item 
gh-121562@footnote{https://github.com/python/cpython/issues/121562}: Optimized performance of hex_from_char by replacing switch-case
with a lookup table

@item 
gh-121499@footnote{https://github.com/python/cpython/issues/121499}: Fix a bug affecting how multi-line history was being rendered
in the new REPL after interacting with the new screen cache. Patch by
Pablo Galindo

@item 
gh-121497@footnote{https://github.com/python/cpython/issues/121497}: Fix a bug that was preventing the REPL to correctly respect the
history when an input hook was set. Patch by Pablo Galindo

@item 
gh-121012@footnote{https://github.com/python/cpython/issues/121012}: Tier 2 execution now ensures that list iterators remain
exhausted, once they become exhausted.

@item 
gh-121439@footnote{https://github.com/python/cpython/issues/121439}: Allow tuples of length 20 in the freelist to be reused.

@item 
gh-121288@footnote{https://github.com/python/cpython/issues/121288}: @ref{2ec,,ValueError} messages for @ref{15de,,list.index()},
@ref{1978,,range.index()}, @code{deque.index()}, @code{deque.remove()} and
@code{ShareableList.index()} no longer contain the repr of the searched
value (which can be arbitrary large) and are consistent with error
messages for other @ref{1979,,index()} and @ref{197a,,remove()}
methods.

@item 
gh-121368@footnote{https://github.com/python/cpython/issues/121368}: Fix race condition in @code{_PyType_Lookup} in the free-threaded
build due to a missing memory fence.  This could lead to
@code{_PyType_Lookup} returning incorrect results on arm64.

@item 
gh-121149@footnote{https://github.com/python/cpython/issues/121149}: Added specialization for summation of complexes, this also
improves accuracy of builtin @ref{695,,sum()} for such inputs.  Patch by Sergey
B Kirpichev.

@item 
gh-121130@footnote{https://github.com/python/cpython/issues/121130}: Fix f-strings with debug expressions in format specifiers.
Patch by Pablo Galindo
@end itemize

@node ライブラリ<50>,Core and Builtins<45>,Core and Builtins<44>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id196}@anchor{197b}
@subsubsection ライブラリ



@itemize -

@item 
gh-121381@footnote{https://github.com/python/cpython/issues/121381}: Remove @code{subprocess._USE_VFORK} escape hatch code and
documentation. It was added just in case, and doesn't have any known cases
that require it.
@end itemize

@node Core and Builtins<45>,ライブラリ<51>,ライブラリ<50>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id197}@anchor{197c}
@subsubsection Core and Builtins



@itemize -

@item 
gh-119726@footnote{https://github.com/python/cpython/issues/119726}: Optimize code layout for calls to C functions from the JIT on
AArch64. Patch by Diego Russo.

@item 
gh-121115@footnote{https://github.com/python/cpython/issues/121115}: @ref{606,,PyLong_AsNativeBytes()} no longer uses
@ref{19e,,__index__()} methods by default. The
@code{Py_ASNATIVEBYTES_ALLOW_INDEX} flag has been added to allow it.

@item 
gh-120838@footnote{https://github.com/python/cpython/issues/120838}: @ref{45f,,Py_Finalize()} and @ref{f11,,Py_FinalizeEx()} now
always run with the main interpreter active.

@item 
gh-113433@footnote{https://github.com/python/cpython/issues/113433}: Subinterpreters now get cleaned up automatically during runtime
finalization.

@item 
gh-119726@footnote{https://github.com/python/cpython/issues/119726}: Improve the speed and memory use of C function calls from JIT
code on AArch64. Patch by Diego Russo

@item 
gh-116017@footnote{https://github.com/python/cpython/issues/116017}: Simplify the warmup mechanism used for "side exits" in JIT
code, resulting in slightly better performance and slightly lower memory
usage for most platforms.

@item 
gh-98442@footnote{https://github.com/python/cpython/issues/98442}: Fix too wide source locations of the cleanup instructions of a
with statement.

@item 
gh-120754@footnote{https://github.com/python/cpython/issues/120754}: Reduce the number of system calls invoked when reading a whole
file (ex. @code{open('a.txt').read()}). For a sample program that reads the
contents of the 400+ @code{.rst} files in the cpython repository @code{Doc}
folder, there is an over 10% reduction in system call count.

@item 
gh-119462@footnote{https://github.com/python/cpython/issues/119462}: Make sure that invariants of type versioning are maintained: *
Superclasses always have their version number assigned before subclasses *
The version tag is always zero if the tag is not valid. * The version tag
is always non-if the tag is valid.

@item 
gh-120437@footnote{https://github.com/python/cpython/issues/120437}: Fix @code{_CHECK_STACK_SPACE} optimization problems introduced in
gh-118322@footnote{https://github.com/python/cpython/issues/118322}.

@item 
gh-120722@footnote{https://github.com/python/cpython/issues/120722}: Correctly set the bytecode position on return instructions
within lambdas. Patch by Jelle Zijlstra.

@item 
gh-120367@footnote{https://github.com/python/cpython/issues/120367}: Fix bug where compiler creates a redundant jump during
pseudo-op replacement. Can only happen with a synthetic AST that has a try
on the same line as the instruction following the exception handler.

@item 
gh-120507@footnote{https://github.com/python/cpython/issues/120507}: Remove the @code{BEFORE_WITH} and @code{BEFORE_ASYNC_WITH}
instructions. Add the new @ref{36f,,LOAD_SPECIAL} instruction. Generate
code for @code{with} and @code{async with} statements using the new instruction.

@item 
gh-113993@footnote{https://github.com/python/cpython/issues/113993}: Strings interned with @ref{14f3,,sys.intern()} are again
garbage-collected when no longer used, as per the documentation. Strings
interned with the C function @ref{aae,,PyUnicode_InternInPlace()} are still
immortal. Internals of the string interning mechanism have been changed.
This may affect performance and identities of @ref{169,,str} objects.
@end itemize

@node ライブラリ<51>,Core and Builtins<46>,Core and Builtins<45>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id198}@anchor{197d}
@subsubsection ライブラリ



@itemize -

@item 
gh-120485@footnote{https://github.com/python/cpython/issues/120485}: Add an override of @code{allow_reuse_port} on classes subclassing
@code{socketserver.TCPServer} where @code{allow_reuse_address} is also
overridden.
@end itemize

@node Core and Builtins<46>,ライブラリ<52>,ライブラリ<51>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id199}@anchor{197e}
@subsubsection Core and Builtins



@itemize -

@item 
gh-120384@footnote{https://github.com/python/cpython/issues/120384}: Fix an array out of bounds crash in @code{list_ass_subscript},
which could be invoked via some specifically tailored input: including
concurrent modification of a list object, where one thread assigns a slice
and another clears it.

@item 
gh-120367@footnote{https://github.com/python/cpython/issues/120367}: Fix crash in compiler on code with redundant NOPs and JUMPs
which show up after exception handlers are moved to the end of the code.
@end itemize

@node ライブラリ<52>,Core and Builtins<47>,Core and Builtins<46>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id200}@anchor{197f}
@subsubsection ライブラリ



@itemize -

@item 
gh-120380@footnote{https://github.com/python/cpython/issues/120380}: Fix Python implementation of @ref{c13,,pickle.Pickler} for
@ref{192,,bytes} and @ref{344,,bytearray} objects when using protocol version
5. Patch by Bénédikt Tran.
@end itemize

@node Core and Builtins<47>,ライブラリ<53>,ライブラリ<52>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id201}@anchor{1980}
@subsubsection Core and Builtins



@itemize -

@item 
gh-120397@footnote{https://github.com/python/cpython/issues/120397}: Improve the throughput by up to two times for the
@ref{1981,,str.count()}, @ref{1982,,bytes.count()} and @ref{1794,,bytearray.count()} methods
for counting single characters.

@item 
gh-120221@footnote{https://github.com/python/cpython/issues/120221}: Deliver real signals on Ctrl-C and Ctrl-Z in the new REPL.
Patch by Pablo Galindo

@item 
gh-120346@footnote{https://github.com/python/cpython/issues/120346}: Respect 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL} when running in interactive
inspect mode (@code{python -i}). Patch by Pablo Galindo

@item 
gh-93691@footnote{https://github.com/python/cpython/issues/93691}: Fix source locations of instructions generated for the iterator
of a for statement.

@item 
gh-120198@footnote{https://github.com/python/cpython/issues/120198}: Fix a crash when multiple threads read and write to the same
@code{__class__} of an object concurrently.

@item 
gh-120298@footnote{https://github.com/python/cpython/issues/120298}: Fix use-after free in @code{list_richcompare_impl} which can be
invoked via some specifically tailored evil input.

@item 
gh-119666@footnote{https://github.com/python/cpython/issues/119666}: Fix a compiler crash in the case where two comprehensions in
class scope both reference @code{__class__}.

@item 
gh-119726@footnote{https://github.com/python/cpython/issues/119726}: JIT: Re-use trampolines on AArch64 when creating stencils.
Patch by Diego Russo

@item 
gh-120225@footnote{https://github.com/python/cpython/issues/120225}: Fix crash in compiler on empty block at end of exception
handler.

@item 
gh-93691@footnote{https://github.com/python/cpython/issues/93691}: Fix source locations of instructions generated for with
statements.

@item 
gh-120097@footnote{https://github.com/python/cpython/issues/120097}: @code{FrameLocalsProxy} now subclasses @code{collections.abc.Mapping}
and can be matched as a mapping in @code{match} statements

@item 
gh-120080@footnote{https://github.com/python/cpython/issues/120080}: Direct call to the @code{int.__round__()} now accepts @code{None}
as a valid argument.

@item 
gh-119933@footnote{https://github.com/python/cpython/issues/119933}: Improve @ref{18e,,SyntaxError} messages for invalid expressions in
a type parameters bound, a type parameter constraint tuple or a default
type parameter. Patch by Bénédikt Tran.

@item 
gh-119724@footnote{https://github.com/python/cpython/issues/119724}: Reverted improvements to error messages for @code{elif}/@code{else}
statements not matching any valid statements, which made in hard to locate
the syntax errors inside those @code{elif}/@code{else} blocks.

@item 
gh-119879@footnote{https://github.com/python/cpython/issues/119879}: String search is now slightly faster for certain cases. It now
utilizes last character gap (good suffix rule) for two-way periodic
needles.

@item 
gh-119842@footnote{https://github.com/python/cpython/issues/119842}: Honor @ref{7a4,,PyOS_InputHook()} in the new REPL. Patch by Pablo
Galindo

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: @ref{48e,,classmethod()} and @ref{453,,staticmethod()} now wrap the
@ref{458,,__annotations__} and @ref{1983,,__annotate__}
attributes of their underlying callable lazily. See 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}. Patch by
Jelle Zijlstra.

@item 
gh-119821@footnote{https://github.com/python/cpython/issues/119821}: Fix execution of @ref{4ab,,annotation scopes}
within classes when @code{globals} is set to a non-dict. Patch by Jelle
Zijlstra.

@item 
gh-118934@footnote{https://github.com/python/cpython/issues/118934}: Make @code{PyEval_GetLocals} return borrowed reference

@item 
gh-119740@footnote{https://github.com/python/cpython/issues/119740}: Remove the previously-deprecated delegation of @ref{19b,,int()} to
@ref{19c,,__trunc__()}.

@item 
gh-119689@footnote{https://github.com/python/cpython/issues/119689}: Generate stack effect metadata for pseudo instructions from
bytecodes.c.

@item 
gh-109218@footnote{https://github.com/python/cpython/issues/109218}: @ref{197,,complex()} accepts now a string only as a positional
argument. Passing a complex number as the "real" or "imag" argument is
deprecated; it should only be passed as a single positional argument.

@item 
gh-119548@footnote{https://github.com/python/cpython/issues/119548}: Add a @code{clear} command to the REPL. Patch by Pablo Galindo

@item 
gh-111999@footnote{https://github.com/python/cpython/issues/111999}: Fix the signature of @ref{fd7,,str.format_map()}.

@item 
gh-119560@footnote{https://github.com/python/cpython/issues/119560}: An invalid assert in beta 1 has been removed.  The assert would
fail if @code{PyState_FindModule()} was used in an extension module's init
function before the module def had been initialized.

@item 
gh-119369@footnote{https://github.com/python/cpython/issues/119369}: Fix deadlock during thread deletion in free-threaded build,
which could occur when the GIL was enabled at runtime.

@item 
gh-119525@footnote{https://github.com/python/cpython/issues/119525}: Fix deadlock involving @code{_PyType_Lookup()} cache in the
free-threaded build when the GIL is dynamically enabled at runtime.

@item 
gh-119258@footnote{https://github.com/python/cpython/issues/119258}: Eliminate type version guards in the tier two interpreter.

Note that setting the @code{tp_version_tag} manually (which has never been
supported) may result in crashes.

@item 
gh-119311@footnote{https://github.com/python/cpython/issues/119311}: Fix bug where names are unexpectedly mangled in the bases of
generic classes.

@item 
gh-119395@footnote{https://github.com/python/cpython/issues/119395}: Fix bug where names appearing after a generic class are mangled
as if they are in the generic class.

@item 
gh-119372@footnote{https://github.com/python/cpython/issues/119372}: Correct invalid corner cases in complex division (resulted in
@code{(nan+nanj)} output), e.g.  @code{1/complex('(inf+infj)')}.  Patch by
Sergey B Kirpichev.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: Evaluation of annotations is now deferred. See 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} for
details.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: Replace @code{LOAD_ASSERTION_ERROR} opcode with
@ref{36a,,LOAD_COMMON_CONSTANT} and add support for
@ref{36b,,NotImplementedError}.

@item 
gh-119213@footnote{https://github.com/python/cpython/issues/119213}: Non-builtin modules built with argument clinic were crashing if
used in a subinterpreter before the main interpreter.  The objects that
were causing the problem by leaking between interpreters carelessly have
been fixed.

@item 
gh-119011@footnote{https://github.com/python/cpython/issues/119011}: Fixes @code{type.__type_params__} to return an empty tuple instead
of a descriptor.

@item 
gh-118692@footnote{https://github.com/python/cpython/issues/118692}: Avoid creating unnecessary @ref{df5,,StopIteration} instances for
monitoring.

@item 
gh-119180@footnote{https://github.com/python/cpython/issues/119180}: Add an @code{__annotate__} attribute to functions, classes, and
modules as part of 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}. Patch by Jelle Zijlstra.

@item 
gh-119049@footnote{https://github.com/python/cpython/issues/119049}: Fix displaying the source line for warnings created by the C
API if the @ref{118,,warnings} module had not yet been imported.

@item 
gh-119057@footnote{https://github.com/python/cpython/issues/119057}: Improve @ref{b3f,,ZeroDivisionError} error message. Now, all error
messages are harmonized: all @code{/}, @code{//}, and @code{%} operations just use
"division by zero" message. And @code{0 ** -1} operation uses "zero to a
negative power".

@item 
gh-118844@footnote{https://github.com/python/cpython/issues/118844}: Fix build failures when configuring with both @code{--disable-gil}
and @code{--enable-experimental-jit}.

@item 
gh-118921@footnote{https://github.com/python/cpython/issues/118921}: Add @code{copy()} method for @code{FrameLocalsProxy} which returns a
snapshot @code{dict} for local variables.

@item 
gh-117657@footnote{https://github.com/python/cpython/issues/117657}: Fix data races on the field that stores a pointer to the
interpreter's main thread that occur in free-threaded builds.

@item 
gh-118750@footnote{https://github.com/python/cpython/issues/118750}: If the C version of the @code{decimal} module is available,
@code{int(str)} now uses it to supply an asymptotically much faster
conversion. However, this only applies if the string contains over about 2
million digits.

@item 
gh-118767@footnote{https://github.com/python/cpython/issues/118767}: Using @ref{1a2,,NotImplemented} in a boolean context now raises
@ref{198,,TypeError}. Contributed by Jelle Zijlstra.

@item 
gh-118561@footnote{https://github.com/python/cpython/issues/118561}: Fix race condition in free-threaded build where
@ref{602,,list.extend()} could expose uninitialised memory to concurrent
readers.

@item 
gh-117139@footnote{https://github.com/python/cpython/issues/117139}: Convert the Python evaluation stack to use internal stack
references. The purpose is to support tagged pointers. In 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}, this
will allow for its form of deferred reference counting. For both the
default and free-threaded builds, this sets up the infrastructure for
unboxed integers in the future.
@end itemize

@node ライブラリ<53>,Core and Builtins<48>,Core and Builtins<47>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id202}@anchor{1984}
@subsubsection ライブラリ



@itemize -

@item 
gh-115801@footnote{https://github.com/python/cpython/issues/115801}: Raise @code{TypeError} when passing a string to
@ref{1985,,difflib.unified_diff()} and @ref{1986,,difflib.context_diff()}.
@end itemize

@node Core and Builtins<48>,C API<15>,ライブラリ<53>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id203}@anchor{1987}
@subsubsection Core and Builtins



@itemize -

@item 
gh-117558@footnote{https://github.com/python/cpython/issues/117558}: Improve error messages when a string, bytes or bytearray object
of length 1 is expected.

@item 
gh-117195@footnote{https://github.com/python/cpython/issues/117195}: Avoid assertion failure for debug builds when calling
@code{object.__sizeof__(1)}

@item 
gh-116022@footnote{https://github.com/python/cpython/issues/116022}: Improve the @ref{82f,,__repr__()} output of
@ref{4c3,,AST} nodes.

@item 
gh-114091@footnote{https://github.com/python/cpython/issues/114091}: Changed the error message for awaiting something that can't be
awaited from "object <type> can't be used in an await expression" to
"'<type>' object can't be awaited".

@item 
gh-113190@footnote{https://github.com/python/cpython/issues/113190}: @ref{45f,,Py_Finalize()} now deletes all interned strings.

@item 
gh-84978@footnote{https://github.com/python/cpython/issues/84978}: Add class methods @ref{194,,float.from_number()} and
@ref{195,,complex.from_number()}.

@item 
gh-95144@footnote{https://github.com/python/cpython/issues/95144}: Improve the error message from @code{a in b} when @code{b} is not a
container to mention the term "container".

@item 
bpo-24766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24766}: Fix handling of @code{doc} argument to subclasses of @code{property}.
@end itemize

@node C API<15>,ビルド<15>,Core and Builtins<48>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id204}@anchor{1988}
@subsubsection C API



@itemize -

@item 
gh-123961@footnote{https://github.com/python/cpython/issues/123961}: Convert the @ref{1989,,curses.window} static
type exposed by the @code{PyCursesWindow_Type} macro in
@code{Include/py_curses.h} to a @ref{b5e,,heap type}. Patch by
Bénédikt Tran.

@item 
gh-124502@footnote{https://github.com/python/cpython/issues/124502}: Add @ref{3b2,,PyUnicode_Equal()} function to the limited C API:
test if two strings are equal. Patch by Victor Stinner.

@item 
gh-124296@footnote{https://github.com/python/cpython/issues/124296}: @ref{64f,,PyDictObject} no longer maintains a private version
tag field @code{ma_version_tag} per 
@geindex Python Enhancement Proposals; PEP 699
PEP 699@footnote{https://peps.python.org/pep-0699/}.  This field was originally
added in Python 3.6 (
@geindex Python Enhancement Proposals; PEP 509
PEP 509@footnote{https://peps.python.org/pep-0509/}) and deprecated in Python 3.12.

@item 
gh-124160@footnote{https://github.com/python/cpython/issues/124160}: Fix crash when importing modules containing state and
single-phase initialization in a subinterpreter.

@item 
gh-124153@footnote{https://github.com/python/cpython/issues/124153}: Add @ref{3b0,,PyType_GetBaseByToken()} and @ref{3b1,,Py_tp_token}
slot for easier type checking, related to 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} and 
@geindex Python Enhancement Proposals; PEP 630
PEP 630@footnote{https://peps.python.org/pep-0630/}.

@item 
gh-124127@footnote{https://github.com/python/cpython/issues/124127}: In the limited C API 3.14 and newer, @ref{2cf,,Py_REFCNT()} is now
implemented as an opaque function call to hide implementation details.
Patch by Victor Stinner.

@item 
gh-123880@footnote{https://github.com/python/cpython/issues/123880}: Fixed a bug that prevented circular imports of extension
modules that use single-phase initialization.

@item 
gh-123909@footnote{https://github.com/python/cpython/issues/123909}: @ref{79d,,PyType_FromSpec()}, @ref{79e,,PyType_FromSpecWithBases()}
and @ref{773,,PyType_FromModuleAndSpec()} will now fail if the metaclass of
the new type has custom @ref{79f,,tp_new}.

@item 
gh-107954@footnote{https://github.com/python/cpython/issues/107954}: Add functions to configure the Python initialization
(
@geindex Python Enhancement Proposals; PEP 741
PEP 741@footnote{https://peps.python.org/pep-0741/}):


@itemize *

@item 
@ref{387,,PyInitConfig_Create()}

@item 
@ref{388,,PyInitConfig_Free()}

@item 
@ref{38a,,PyInitConfig_GetError()}

@item 
@ref{38b,,PyInitConfig_GetExitCode()}

@item 
@ref{38f,,PyInitConfig_HasOption()}

@item 
@ref{38c,,PyInitConfig_GetInt()}

@item 
@ref{38d,,PyInitConfig_GetStr()}

@item 
@ref{38e,,PyInitConfig_GetStrList()}

@item 
@ref{389,,PyInitConfig_FreeStrList()}

@item 
@ref{390,,PyInitConfig_SetInt()}

@item 
@ref{391,,PyInitConfig_SetStr()}

@item 
@ref{392,,PyInitConfig_SetStrList()}

@item 
@ref{37b,,PyInitConfig_AddModule()}

@item 
@ref{386,,Py_InitializeFromInitConfig()}
@end itemize

Patch by Victor Stinner.

@item 
gh-107954@footnote{https://github.com/python/cpython/issues/107954}: Add functions to get and set the current runtime Python
configuration:


@itemize *

@item 
@ref{37c,,PyConfig_Get()}

@item 
@ref{384,,PyConfig_GetInt()}

@item 
@ref{37d,,PyConfig_Set()}

@item 
@ref{385,,PyConfig_Names()}
@end itemize

Patch by Victor Stinner.

@item 
gh-123465@footnote{https://github.com/python/cpython/issues/123465}: @ref{770,,Py_RELATIVE_OFFSET} is now allowed in
@ref{771,,PyMemberDef} for the special offset member
@code{"__vectorcalloffset__"}, as well as the discouraged special offset
members @code{"__dictoffset__"} and @code{"__weaklistoffset__"}

@item 
gh-100554@footnote{https://github.com/python/cpython/issues/100554}: Added a slot @code{Py_tp_vectorcall} to set
@ref{198a,,tp_vectorcall} via the @ref{79d,,PyType_FromSpec()}
function family. Limited API extensions can use this feature to provide
more efficient vector call-based implementation of @code{__new__} and
@code{__init__}.

@item 
gh-122854@footnote{https://github.com/python/cpython/issues/122854}: Add @ref{395,,Py_HashBuffer()} to compute and return the hash
value of a buffer. Patch by Antoine Pitrou and Victor Stinner.

@item 
gh-122728@footnote{https://github.com/python/cpython/issues/122728}: Fix @ref{5f8,,PyEval_GetLocals()} to avoid @ref{795,,SystemError}
("bad argument to internal function"). Patch by Victor Stinner.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: Make @ref{198b,,PyObject_Print} work around a bug in Android and
OpenBSD which prevented it from throwing an exception when trying to write
to a read-only stream.

@item 
gh-105201@footnote{https://github.com/python/cpython/issues/105201}: Add @ref{398,,PyIter_NextItem()} to replace @ref{399,,PyIter_Next()},
which has an ambiguous return value. Patch by Irit Katriel and Erlend
Aasland.

@item 
gh-121489@footnote{https://github.com/python/cpython/issues/121489}: Export private @code{_PyBytes_Join()} again.

@item 
gh-121645@footnote{https://github.com/python/cpython/issues/121645}: Add @ref{383,,PyBytes_Join(sep@comma{} iterable)}
function, similar to @code{sep.join(iterable)} in Python. Patch by Victor
Stinner.

@item 
gh-89364@footnote{https://github.com/python/cpython/issues/89364}: Export the @ref{15f4,,PySignal_SetWakeupFd()} function. Previously,
the function was documented but it couldn't be used in 3rd party code.
Patch by Victor Stinner.

@item 
gh-113993@footnote{https://github.com/python/cpython/issues/113993}: @ref{aae,,PyUnicode_InternInPlace()} no longer prevents its
argument from being garbage collected.

Several functions that take @code{char *} are now documented as possibly
preventing string objects from being garbage collected; refer to their
documentation for details: @ref{198c,,PyUnicode_InternFromString()},
@ref{198d,,PyDict_SetItemString()}, @ref{198e,,PyObject_SetAttrString()},
@ref{1832,,PyObject_DelAttrString()}, @ref{198c,,PyUnicode_InternFromString()},
and @code{PyModule_Add*} convenience functions.

@item 
gh-113601@footnote{https://github.com/python/cpython/issues/113601}: Removed debug build assertions related to interning strings,
which were falsely triggered by stable ABI extensions.

@item 
gh-112136@footnote{https://github.com/python/cpython/issues/112136}: Restore the private @code{_PyArg_Parser} structure and the private
@code{_PyArg_ParseTupleAndKeywordsFast()} function, previously removed in
Python 3.13 alpha 1. Patch by Victor Stinner.

@item 
gh-120642@footnote{https://github.com/python/cpython/issues/120642}: Remove the private @code{_Py_CODEUNIT} type from the public C API.
The internal @code{pycore_code.h} header should now be used to get this
internal type. Patch by Victor Stinner.

@item 
gh-120858@footnote{https://github.com/python/cpython/issues/120858}: @ref{198f,,PyDict_Next()} no longer locks the dictionary in the
free-threaded build.  The locking needs to be done by the caller around
the entire iteration loop.

@item 
gh-120642@footnote{https://github.com/python/cpython/issues/120642}: Remove the following unstable functions:


@itemize *

@item 
@code{PyUnstable_Replace_Executor()}

@item 
@code{PyUnstable_SetOptimizer()}

@item 
@code{PyUnstable_GetOptimizer()}

@item 
@code{PyUnstable_GetExecutor()}

@item 
@code{PyUnstable_Optimizer_NewCounter()}

@item 
@code{PyUnstable_Optimizer_NewUOpOptimizer()}
@end itemize

Patch by Victor Stinner.

@item 
gh-120389@footnote{https://github.com/python/cpython/issues/120389}: Add new functions to convert C @code{<stdint.h>} numbers from/to
Python @ref{19b,,int}:


@itemize *

@item 
@ref{3a3,,PyLong_FromInt32()}

@item 
@ref{3a5,,PyLong_FromUInt32()}

@item 
@ref{3a4,,PyLong_FromInt64()}

@item 
@ref{3a6,,PyLong_FromUInt64()}

@item 
@ref{39f,,PyLong_AsInt32()}

@item 
@ref{3a1,,PyLong_AsUInt32()}

@item 
@ref{3a0,,PyLong_AsInt64()}

@item 
@ref{3a2,,PyLong_AsUInt64()}
@end itemize

Patch by Victor Stinner.

@item 
gh-120600@footnote{https://github.com/python/cpython/issues/120600}: In the limited C API 3.14 and newer, @ref{3c9,,Py_TYPE()} is now
implemented as an opaque function call to hide implementation details.
Patch by Victor Stinner.

@item 
gh-70278@footnote{https://github.com/python/cpython/issues/70278}: @ref{62b,,PyUnicode_FromFormat()} no longer produces the ending
@code{\ufffd} character for truncated C string when use precision with @code{%s}
and @code{%V}. It now truncates the string before the start of truncated
multibyte sequences.

@item 
gh-119771@footnote{https://github.com/python/cpython/issues/119771}: Set @ref{5b,,errno} in @ref{18f2,,_Py_c_pow()} on overflows.  Patch
by Sergey B Kirpichev.

@item 
gh-119182@footnote{https://github.com/python/cpython/issues/119182}: Add a new @ref{3b3,,PyUnicodeWriter} API to create a Python
@ref{169,,str} object:


@itemize *

@item 
@ref{3b4,,PyUnicodeWriter_Create()}.

@item 
@ref{3b6,,PyUnicodeWriter_Discard()}.

@item 
@ref{3b7,,PyUnicodeWriter_Finish()}.

@item 
@ref{3ba,,PyUnicodeWriter_WriteChar()}.

@item 
@ref{3bf,,PyUnicodeWriter_WriteUTF8()}.

@item 
@ref{3be,,PyUnicodeWriter_WriteUCS4()}.

@item 
@ref{3c0,,PyUnicodeWriter_WriteWideChar()}.

@item 
@ref{3bc,,PyUnicodeWriter_WriteStr()}.

@item 
@ref{3bb,,PyUnicodeWriter_WriteRepr()}.

@item 
@ref{3bd,,PyUnicodeWriter_WriteSubstring()}.

@item 
@ref{3b8,,PyUnicodeWriter_Format()}.

@item 
@ref{3b5,,PyUnicodeWriter_DecodeUTF8Stateful()}.
@end itemize

Patch by Victor Stinner.

@item 
gh-119613@footnote{https://github.com/python/cpython/issues/119613}: Soft deprecate the @ref{1990,,Py_MEMCPY} macro: use directly
@code{memcpy()} instead.  Patch by Victor Stinner.

@item 
gh-119775@footnote{https://github.com/python/cpython/issues/119775}: Creating @ref{3cf,,immutable types}
with mutable bases was deprecated since 3.12 and now raises a
@ref{198,,TypeError}.

@item 
gh-119585@footnote{https://github.com/python/cpython/issues/119585}: Fix crash when a thread state that was created by
@ref{64a,,PyGILState_Ensure()} calls a destructor that during
@ref{1991,,PyThreadState_Clear()} that calls back into
@ref{64a,,PyGILState_Ensure()} and @ref{64b,,PyGILState_Release()}. This might
occur when in the free-threaded build or when using thread-local variables
whose destructors call @ref{64a,,PyGILState_Ensure()}.

@item 
gh-119613@footnote{https://github.com/python/cpython/issues/119613}: Macros @code{Py_IS_NAN}, @code{Py_IS_INFINITY} and @code{Py_IS_FINITE}
are @ref{23d,,soft deprecated}.

@item 
gh-119336@footnote{https://github.com/python/cpython/issues/119336}: Restore the removed @code{_PyLong_NumBits()} function. It is used
by the pywin32 project. Patch by Ethan Smith

@item 
gh-119344@footnote{https://github.com/python/cpython/issues/119344}: The critical section API is now public as part of the
non-limited C API.

@item 
gh-119333@footnote{https://github.com/python/cpython/issues/119333}: Add @ref{1992,,PyContext_AddWatcher()} and
@ref{1993,,PyContext_ClearWatcher()} APIs to register callbacks to receive
notification on enter and exit of context objects.

@item 
gh-119247@footnote{https://github.com/python/cpython/issues/119247}: Added @code{Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST} and
@code{Py_END_CRITICAL_SECTION_SEQUENCE_FAST} macros to make it possible to
use PySequence_Fast APIs safely when free-threaded, and update str.join to
work without the GIL using them.

@item 
gh-111389@footnote{https://github.com/python/cpython/issues/111389}: Add @ref{1994,,PyHASH_MULTIPLIER} constant: prime multiplier
used in string and various other hashes. Patch by Victor Stinner.

@item 
gh-118771@footnote{https://github.com/python/cpython/issues/118771}: Several C declarations with names that didn't start with the
@code{Py} or @code{_Py} prefixes, which were added by mistake in 3.13 alpha and
beta releases, were moved to internal headers.

@item 
gh-116984@footnote{https://github.com/python/cpython/issues/116984}: Make mimalloc includes relative to the current file to avoid
embedders or extensions needing to include @code{Internal/mimalloc} if they
are already including internal CPython headers.

@item 
gh-118789@footnote{https://github.com/python/cpython/issues/118789}: Add @ref{1995,,PyUnstable_Object_ClearWeakRefsNoCallbacks()}, which
clears weakrefs without calling their callbacks.

@item 
gh-118789@footnote{https://github.com/python/cpython/issues/118789}: Restore @code{_PyWeakref_ClearRef} that was previously removed in
Python 3.13 alpha 1.

@item 
gh-117511@footnote{https://github.com/python/cpython/issues/117511}: Make the @ref{484,,PyMutex} public in the non-limited C API.

@item 
gh-116560@footnote{https://github.com/python/cpython/issues/116560}: Add @ref{39a,,PyLong_GetSign()} function.  Patch by Sergey B
Kirpichev.

@item 
gh-97588@footnote{https://github.com/python/cpython/issues/97588}: Fix creating bitfields in @ref{2e,,ctypes} structures and unions.
Fields no longer overlap.

@item 
gh-87135@footnote{https://github.com/python/cpython/issues/87135}: Attempting to acquire the GIL after runtime finalization has
begun in a different thread now causes the thread to hang rather than
terminate, which avoids potential crashes or memory corruption caused by
attempting to terminate a thread that is running code not specifically
designed to support termination. In most cases this hanging is harmless
since the process will soon exit anyway.

The @code{PyThread_exit_thread} function is now deprecated.  Its behavior is
inconsistent across platforms, and it can only be used safely in the
unlikely case that every function in the entire call stack has been
designed to support the platform-dependent termination mechanism.  It is
recommended that users of this function change their design to not require
thread termination.  In the unlikely case that thread termination is
needed and can be done safely, users may migrate to calling
platform-specific APIs such as @code{pthread_exit} (POSIX) or
@code{_endthreadex} (Windows) directly.

@item 
bpo-34008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34008}: Added @code{Py_IsInitialized} to the list of APIs that are safe to
call before the interpreter is initialized, and updated the embedding
tests to cover it.
@end itemize

@node ビルド<15>,,C API<15>,Python 3 14 0 alpha 1
@anchor{whatsnew/changelog id205}@anchor{1996}
@subsubsection ビルド



@itemize -

@item 
gh-125269@footnote{https://github.com/python/cpython/issues/125269}: Fix detection of whether @code{-latomic} is needed when
cross-compiling CPython using the configure script.

@item 
gh-123990@footnote{https://github.com/python/cpython/issues/123990}: Remove @code{WITH_FREELISTS} macro and @code{--without-freelists}
build configuration

@item 
gh-124102@footnote{https://github.com/python/cpython/issues/124102}: Update internal documentation under PCbuild, so it now
correctly states that Windows requires VS2017 or later and Python 3.10 or
later

@item 
gh-124043@footnote{https://github.com/python/cpython/issues/124043}: Building using @ref{636,,--with-trace-refs} is (temporarily)
disallowed when the GIL is disabled.

@item 
gh-123418@footnote{https://github.com/python/cpython/issues/123418}: Updated Android build to use OpenSSL 3.0.15.

@item 
gh-123297@footnote{https://github.com/python/cpython/issues/123297}: Propagate the value of @code{LDFLAGS} to @code{LDCXXSHARED} in
@ref{e1,,sysconfig}. Patch by Pablo Galindo

@item 
gh-121634@footnote{https://github.com/python/cpython/issues/121634}: Allow for specifying the target compile triple for WASI.

@item 
gh-122578@footnote{https://github.com/python/cpython/issues/122578}: Use WASI SDK 24 for testing.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: Rename build variable @code{MODULE_LDFLAGS} back to @code{LIBPYTHON},
as it's used by package build systems (e.g. Meson).

@item 
gh-118943@footnote{https://github.com/python/cpython/issues/118943}: Fix an issue where the experimental JIT could be built several
times by the @code{make regen-all} target, leading to possible race
conditions on heavily parallelized builds.

@item 
gh-121996@footnote{https://github.com/python/cpython/issues/121996}: Introduce ./configure --disable-safety and
--enable-slower-safety options. Patch by Donghee Na.

@item 
gh-120522@footnote{https://github.com/python/cpython/issues/120522}: Added a @ref{1997,,--with-app-store-compliance} option to patch
out known issues with macOS/iOS App Store review processes.

@item 
gh-120371@footnote{https://github.com/python/cpython/issues/120371}: Support WASI SDK 22 by explicitly skipping functions that are
just stubs in wasi-libc.

@item 
gh-121731@footnote{https://github.com/python/cpython/issues/121731}: Fix mimalloc compile error on GNU/Hurd

@item 
gh-121487@footnote{https://github.com/python/cpython/issues/121487}: Fix deprecation warning for ATOMIC_VAR_INIT in mimalloc.

@item 
gh-121467@footnote{https://github.com/python/cpython/issues/121467}: Fix a Makefile bug that prevented mimalloc header files from
being installed.

@item 
gh-121103@footnote{https://github.com/python/cpython/issues/121103}: On POSIX systems, excluding macOS framework installs, the lib
directory for the free-threaded build now includes a "t" suffix to avoid
conflicts with a co-located default build installation.

@item 
gh-120831@footnote{https://github.com/python/cpython/issues/120831}: The default minimum iOS version was increased to 13.0.

@item 
gh-121082@footnote{https://github.com/python/cpython/issues/121082}: Fix build failure when the developer use @code{--enable-pystats}
arguments in configuration command after #118450.

@item 
gh-120671@footnote{https://github.com/python/cpython/issues/120671}: Fix failing configure tests due to a missing space when
appending to CFLAGS.

@item 
gh-120602@footnote{https://github.com/python/cpython/issues/120602}: Correctly handle LLVM installs with @code{LLVM_VERSION_SUFFIX}
when building with @code{--enable-experimental-jit}.

@item 
gh-120688@footnote{https://github.com/python/cpython/issues/120688}: On WASI in debug mode, Python is now built with compiler flag
@code{-O3} instead of @code{-Og}, to support more recursive calls. Patch by
Victor Stinner.

@item 
gh-118943@footnote{https://github.com/python/cpython/issues/118943}: Fix a possible race condition affecting parallel builds
configured with @code{--enable-experimental-jit}, in which
@ref{264,,FileNotFoundError} could be caused by another process already moving
@code{jit_stencils.h.new} to @code{jit_stencils.h}.

@item 
gh-120326@footnote{https://github.com/python/cpython/issues/120326}: On Windows, fix build error when @code{--disable-gil} and
@code{--experimental-jit} options are combined.

@item 
gh-120291@footnote{https://github.com/python/cpython/issues/120291}: Make the @code{python-config} shell script compatible with
non-bash shells.

@item 
gh-113565@footnote{https://github.com/python/cpython/issues/113565}: Improve @ref{2f,,curses} and @ref{31,,curses.panel} dependency checks
in @code{configure}.

@item 
gh-119729@footnote{https://github.com/python/cpython/issues/119729}: On POSIX systems, the pkg-config (@code{.pc}) filenames now
include the ABI flags, which may include debug ("d") and free-threaded
("t").  For example: * @code{python-3.14.pc} (default, non-debug build) *
@code{python-3.14d.pc} (default, debug build) * @code{python-3.14t.pc}
(free-threaded build)

@item 
gh-119400@footnote{https://github.com/python/cpython/issues/119400}: @code{make_ssl_certs}, the script that prepares certificate data
for the test suite, now allows specifying expiration dates.

@item 
gh-115119@footnote{https://github.com/python/cpython/issues/115119}: Fall back to the bundled libmpdec if a system version cannot be
found.

@item 
gh-119132@footnote{https://github.com/python/cpython/issues/119132}: Update @ref{49c,,sys.version} to identify whether the build is
default build or free-threading build. Patch By Donghee Na.

@item 
gh-118836@footnote{https://github.com/python/cpython/issues/118836}: Fix an @code{AssertionError} when building with
@code{--enable-experimental-jit} and the compiler emits a @code{SHT_NOTE}
section.

@item 
gh-118943@footnote{https://github.com/python/cpython/issues/118943}: Fix a possible race condition affecting parallel builds
configured with @code{--enable-experimental-jit}, in which compilation errors
could be caused by an incompletely-generated header file.
@end itemize

@node Python 3 13 0 beta 1,Python 3 13 0 alpha 6,Python 3 14 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-13-0-beta-1}@anchor{1998}
@subsection Python 3.13.0 beta 1


`Release date: 2024-05-08'

@menu
* セキュリティ: セキュリティ<17>. 
* Core and Builtins: Core and Builtins<49>. 
* ライブラリ: ライブラリ<54>. 
* Core and Builtins: Core and Builtins<50>. 
* ライブラリ: ライブラリ<55>. 
* ドキュメント: ドキュメント<15>. 
* ビルド: ビルド<16>. 
* Windows: Windows<15>. 
* macOS: macOS<9>. 
* IDLE: IDLE<8>. 
* C API: C API<16>. 

@end menu

@node セキュリティ<17>,Core and Builtins<49>,,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id206}@anchor{1999}
@subsubsection セキュリティ



@itemize -

@item 
gh-116741@footnote{https://github.com/python/cpython/issues/116741}: Update bundled libexpat to 2.6.2

@item 
gh-117233@footnote{https://github.com/python/cpython/issues/117233}: Detect BLAKE2, SHA3, Shake, & truncated SHA512 support in the
OpenSSL-ish libcrypto library at build time.  This allows @ref{6c,,hashlib}
to be used with libraries that do not to support every algorithm that
upstream OpenSSL does.
@end itemize

@node Core and Builtins<49>,ライブラリ<54>,セキュリティ<17>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id207}@anchor{199a}
@subsubsection Core and Builtins



@itemize -

@item 
gh-118414@footnote{https://github.com/python/cpython/issues/118414}: Add instrumented opcodes to YIELD_VALUE assertion for tracing
cases.

@item 
gh-117953@footnote{https://github.com/python/cpython/issues/117953}: When a builtin or extension module is imported for the first
time, while a subinterpreter is active, the module's init function is now
run by the main interpreter first before import continues in the
subinterpreter. Consequently, single-phase init modules now fail in an
isolated subinterpreter without the init function running under that
interpreter, whereas before it would run under the subinterpreter `before'
failing, potentially leaving behind global state and callbacks and
otherwise leaving the module in an inconsistent state.

@item 
gh-117549@footnote{https://github.com/python/cpython/issues/117549}: Don't use designated initializer syntax in inline functions in
internal headers. They cause problems for C++ or MSVC users who aren't yet
using the latest C++ standard (C++20). While internal, pycore_backoff.h,
is included (indirectly, via pycore_code.h) by some key 3rd party software
that does so for speed.
@end itemize

@node ライブラリ<54>,Core and Builtins<50>,Core and Builtins<49>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id208}@anchor{199b}
@subsubsection ライブラリ



@itemize -

@item 
gh-95382@footnote{https://github.com/python/cpython/issues/95382}: Improve performance of @ref{f41,,json.dumps()} and @ref{f40,,json.dump()}
when using the argument `indent'. Depending on the data the encoding using
@ref{f41,,json.dumps()} with `indent' can be up to 2 to 3 times faster.
@end itemize

@node Core and Builtins<50>,ライブラリ<55>,ライブラリ<54>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id209}@anchor{199c}
@subsubsection Core and Builtins



@itemize -

@item 
gh-116322@footnote{https://github.com/python/cpython/issues/116322}: In @code{--disable-gil} builds, the GIL will be enabled while
loading C extension modules. If the module indicates that it supports
running without the GIL, the GIL will be disabled once loading is
complete. Otherwise, the GIL will remain enabled for the remainder of the
interpreter's lifetime. This behavior does not apply if the GIL has been
explicitly enabled or disabled with @code{PYTHON_GIL} or @code{-Xgil}.

@item 
gh-118513@footnote{https://github.com/python/cpython/issues/118513}: Fix incorrect @ref{174f,,UnboundLocalError} when two comprehensions
in the same function both reference the same name, and in one
comprehension the name is bound while in the other it's an implicit
global.

@item 
gh-118518@footnote{https://github.com/python/cpython/issues/118518}: Allow the Linux perf support to work without frame pointers
using perf's advanced JIT support. The feature is activated when using the
@code{PYTHON_PERF_JIT_SUPPORT} environment variable or when running Python
with @code{-Xperf_jit}. Patch by Pablo Galindo.

@item 
gh-117514@footnote{https://github.com/python/cpython/issues/117514}: Add @code{sys._is_gil_enabled()} function that returns whether the
GIL is currently enabled.  In the default build it always returns @code{True}
because the GIL is always enabled.  In the free-threaded build, it may
return @code{True} or @code{False}.

@item 
gh-118164@footnote{https://github.com/python/cpython/issues/118164}: Break a loop between the Python implementation of the
@ref{3a,,decimal} module and the Python code for integer to string
conversion. Also optimize integer to string conversion for values in the
range from 9_000 to 135_000 decimal digits.

@item 
gh-118473@footnote{https://github.com/python/cpython/issues/118473}: Fix @ref{199d,,sys.set_asyncgen_hooks()} not to be partially set when
raising @ref{198,,TypeError}.

@item 
gh-118465@footnote{https://github.com/python/cpython/issues/118465}: Compiler populates the new @code{__firstlineno__} field on a class
with the line number of the first line of the class definition.

@item 
gh-118492@footnote{https://github.com/python/cpython/issues/118492}: Fix an issue where the type cache can expose a previously
accessed attribute when a finalizer is run.

@item 
gh-117714@footnote{https://github.com/python/cpython/issues/117714}: update @code{async_generator.athrow().close()} and
@code{async_generator.asend().close()} to close their section of the
underlying async generator

@item 
gh-111201@footnote{https://github.com/python/cpython/issues/111201}: The @ref{1b5,,interactive} interpreter is now implemented in
Python, which allows for a number of new features like colors, multiline
input, history viewing, and paste mode. Contributed by Pablo Galindo,
Łukasz Langa and Lysandros Nikolaou based on code from the PyPy project.

@item 
gh-74929@footnote{https://github.com/python/cpython/issues/74929}: Implement PEP 667: converted @ref{4a5,,FrameType.f_locals} and @ref{661,,PyFrame_GetLocals()} to return a
write-through proxy object when the frame refers to a function or
comprehension.

@item 
gh-116767@footnote{https://github.com/python/cpython/issues/116767}: Fix crash in compiler on 'async with' that has many context
managers.

@item 
gh-118335@footnote{https://github.com/python/cpython/issues/118335}: Change how to use the tier 2 interpreter. Instead of running
Python with @code{-X uops} or setting the environment variable
@code{PYTHON_UOPS=1}, this choice is now made at build time by configuring
with @code{--enable-experimental-jit=interpreter}.

`Beware!' This changes the environment variable to enable or disable
micro-ops to @code{PYTHON_JIT}. The old @code{PYTHON_UOPS} is no longer used.

@item 
gh-118306@footnote{https://github.com/python/cpython/issues/118306}: Update JIT compilation to use LLVM 18

@item 
gh-118160@footnote{https://github.com/python/cpython/issues/118160}: @ref{4ab,,Annotation scopes} within classes can
now contain comprehensions. However, such comprehensions are not inlined
into their parent scope at runtime. Patch by Jelle Zijlstra.

@item 
gh-118272@footnote{https://github.com/python/cpython/issues/118272}: Fix bug where @code{generator.close} does not free the generator
frame's locals.

@item 
gh-118216@footnote{https://github.com/python/cpython/issues/118216}: Don't consider @ref{0,,__future__} imports with dots before the
module name.

@item 
gh-118074@footnote{https://github.com/python/cpython/issues/118074}: Make sure that the Executor objects in the COLD_EXITS array
aren't assumed to be GC-able (which would access bytes outside the
object).

@item 
gh-107674@footnote{https://github.com/python/cpython/issues/107674}: Lazy load frame line number to improve performance of tracing

@item 
gh-118082@footnote{https://github.com/python/cpython/issues/118082}: Improve @ref{18e,,SyntaxError} message for imports without names,
like in @code{from x import} and @code{import} cases. It now points out to users
that @ref{7f8,,import} expects at least one name after it.

@item 
gh-118090@footnote{https://github.com/python/cpython/issues/118090}: Improve @ref{18e,,SyntaxError} message for empty type param
brackets.

@item 
gh-117958@footnote{https://github.com/python/cpython/issues/117958}: Added a @code{get_jit_code()} method to access JIT compiled
machine code from the UOp Executor when the experimental JIT is enabled.
Patch by Anthony Shaw.

@item 
gh-117901@footnote{https://github.com/python/cpython/issues/117901}: Add option for compiler's codegen to save nested instruction
sequences for introspection.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: Redirect stdout and stderr to system log when embedded in an
Android app.

@item 
gh-109118@footnote{https://github.com/python/cpython/issues/109118}: @ref{4ab,,annotation scope} within class scopes
can now contain lambdas.

@item 
gh-117894@footnote{https://github.com/python/cpython/issues/117894}: Prevent @code{agen.aclose()} objects being re-used after
@code{.throw()}.

@item 
gh-117881@footnote{https://github.com/python/cpython/issues/117881}: prevent concurrent access to an async generator via
athrow().throw() or asend().throw()

@item 
gh-117536@footnote{https://github.com/python/cpython/issues/117536}: Fix a @ref{4d7,,RuntimeWarning} when calling
@code{agen.aclose().throw(Exception)}.

@item 
gh-117755@footnote{https://github.com/python/cpython/issues/117755}: Fix mimalloc allocator for huge memory allocation (around
8,589,934,592 GiB) on s390x. Patch by Victor Stinner.

@item 
gh-117750@footnote{https://github.com/python/cpython/issues/117750}: Fix issue where an object's dict would get out of sync with the
object's internal values when being cleared. @code{obj.__dict__.clear()} now
clears the internal values, but leaves the dict attached to the object.

@item 
gh-117431@footnote{https://github.com/python/cpython/issues/117431}: Improve the performance of the following @ref{192,,bytes} and
@ref{344,,bytearray} methods by adapting them to the
@ref{199e,,METH_FASTCALL} calling convention:


@itemize *

@item 
@code{count()}

@item 
@code{find()}

@item 
@code{index()}

@item 
@code{rfind()}

@item 
@code{rindex()}
@end itemize

@item 
gh-117709@footnote{https://github.com/python/cpython/issues/117709}: Speed up calls to @ref{169,,str()} with positional-only argument, by
using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} @code{vectorcall} calling convention. Patch by Erlend
Aasland.

@item 
gh-117680@footnote{https://github.com/python/cpython/issues/117680}: Give @code{_PyInstructionSequence} a Python interface and use it
in tests.

@item 
gh-115776@footnote{https://github.com/python/cpython/issues/115776}: Statically allocated objects are, by definition, immortal so
must be marked as such regardless of whether they are in extension modules
or not.

@item 
gh-117385@footnote{https://github.com/python/cpython/issues/117385}: Remove unhandled @code{PY_MONITORING_EVENT_BRANCH} and
@code{PY_MONITORING_EVENT_EXCEPTION_HANDLED} events from
@ref{2e1,,sys.settrace()}.

@item 
gh-116322@footnote{https://github.com/python/cpython/issues/116322}: Extension modules may indicate to the runtime that they can run
without the GIL. Multi-phase init modules do so by calling providing
@code{Py_MOD_GIL_NOT_USED} for the @code{Py_mod_gil} slot, while single-phase
init modules call @code{PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED)}
from their init function.

@item 
gh-116129@footnote{https://github.com/python/cpython/issues/116129}: Implement 
@geindex Python Enhancement Proposals; PEP 696
PEP 696@footnote{https://peps.python.org/pep-0696/}, adding support for defaults on type
parameters. Patch by Jelle Zijlstra.

@item 
gh-93502@footnote{https://github.com/python/cpython/issues/93502}: Add two new functions to the C-API,
@ref{610,,PyRefTracer_SetTracer()} and @ref{611,,PyRefTracer_GetTracer()}, that
allows to track object creation and destruction the same way the
@ref{105,,tracemalloc} module does. Patch by Pablo Galindo

@item 
gh-107674@footnote{https://github.com/python/cpython/issues/107674}: Improved the performance of @ref{2e1,,sys.settrace()} significantly

@item 
gh-95754@footnote{https://github.com/python/cpython/issues/95754}: Improve the error message when a script shadowing a module from
the standard library causes @ref{5f0,,AttributeError} to be raised. Similarly,
improve the error message when a script shadowing a third party module
attempts to access an attribute from that third party module while still
initialising.

@item 
gh-99180@footnote{https://github.com/python/cpython/issues/99180}: Elide uninformative traceback indicators in @code{return} and
simple @code{assignment} statements. Patch by Pablo Galindo.

@item 
gh-105879@footnote{https://github.com/python/cpython/issues/105879}: Allow the `globals' and `locals' arguments to @ref{4a2,,exec()} and
@ref{4a3,,eval()} to be passed as keywords.
@end itemize

@node ライブラリ<55>,ドキュメント<15>,Core and Builtins<50>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id210}@anchor{199f}
@subsubsection ライブラリ



@itemize -

@item 
gh-118418@footnote{https://github.com/python/cpython/issues/118418}: A @ref{1a3,,DeprecationWarning} is now emitted if you fail to pass
a value to the new `type_params' parameter of @code{typing._eval_type()} or
@code{typing.ForwardRef._evaluate()}. (Using either of these private and
undocumented functions is discouraged to begin with, but failing to pass a
value to the @code{type_params} parameter may lead to incorrect behaviour on
Python 3.12 or newer.)

@item 
gh-118660@footnote{https://github.com/python/cpython/issues/118660}: Add an optional second type parameter to
@ref{e8b,,typing.ContextManager} and @ref{19a0,,typing.AsyncContextManager},
representing the return types of @ref{1518,,__exit__()} and
@ref{19a1,,__aexit__()} respectively. This parameter defaults to @code{bool
| None}.

@item 
gh-118650@footnote{https://github.com/python/cpython/issues/118650}: The @code{enum} module allows method named @code{_repr_*} to be
defined on @code{Enum} types.

@item 
gh-118648@footnote{https://github.com/python/cpython/issues/118648}: Add type parameter defaults to @ref{19a2,,typing.Generator} and
@ref{19a3,,typing.AsyncGenerator}.

@item 
gh-101137@footnote{https://github.com/python/cpython/issues/101137}: Mime type @code{text/x-rst} is now supported by @ref{93,,mimetypes}.

@item 
gh-118164@footnote{https://github.com/python/cpython/issues/118164}: The Python implementation of the @code{decimal} module could
appear to hang in relatively small power cases (like @code{2**117}) if
context precision was set to a very high value. A different method to
check for exactly representable results is used now that doesn't rely on
computing @code{10**precision} (which could be effectively too large to
compute).

@item 
gh-111744@footnote{https://github.com/python/cpython/issues/111744}: @code{breakpoint()} and @code{pdb.set_trace()} now enter the debugger
immediately after the call rather than before the next line is executed.

@item 
gh-118500@footnote{https://github.com/python/cpython/issues/118500}: Add @ref{aa,,pdb} support for zipapps

@item 
gh-118406@footnote{https://github.com/python/cpython/issues/118406}: Add signature for @ref{54d,,sqlite3.Connection} objects.

@item 
gh-101732@footnote{https://github.com/python/cpython/issues/101732}: Use a Y2038 compatible openssl time function when available.

@item 
gh-118404@footnote{https://github.com/python/cpython/issues/118404}: Fix @ref{22f,,inspect.signature()} for non-comparable callables.

@item 
gh-118402@footnote{https://github.com/python/cpython/issues/118402}: Fix @ref{22f,,inspect.signature()} for the result of the
@ref{13f2,,functools.cmp_to_key()} call.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: On Android, @ref{145a,,sysconfig.get_platform} now returns the
format specified by 
@geindex Python Enhancement Proposals; PEP 738
PEP 738@footnote{https://peps.python.org/pep-0738/}.

@item 
gh-118285@footnote{https://github.com/python/cpython/issues/118285}: Allow to specify the signature of custom callable instances of
extension type by the @code{__text_signature__} attribute. Specify signatures
of @ref{1033,,operator.attrgetter}, @ref{c57,,operator.itemgetter}, and
@ref{1034,,operator.methodcaller} instances.

@item 
gh-118314@footnote{https://github.com/python/cpython/issues/118314}: Fix an edge case in @ref{19a4,,binascii.a2b_base64()} strict mode,
where excessive padding is not detected when no padding is necessary.

@item 
gh-118271@footnote{https://github.com/python/cpython/issues/118271}: Add the @code{PhotoImage} methods @code{read()} to read an
image from a file and @code{data()} to get the image data. Add
`background' and `grayscale' parameters to @code{PhotoImage} method
@code{write()}.

@item 
gh-118225@footnote{https://github.com/python/cpython/issues/118225}: Add the @code{PhotoImage} method @code{copy_replace()} to
copy a region from one image to other image, possibly with pixel zooming
and/or subsampling. Add `from_coords' parameter to @code{PhotoImage}
methods @code{copy()}, @code{zoom()} and @code{subsample()}. Add `zoom'
and `subsample' parameters to @code{PhotoImage} method @code{copy()}.

@item 
gh-118221@footnote{https://github.com/python/cpython/issues/118221}: Fix a bug where @ref{54f,,sqlite3.Connection.iterdump()} could fail
if a custom @ref{19a5,,row factory} was used.
Patch by Erlend Aasland.

@item 
gh-118013@footnote{https://github.com/python/cpython/issues/118013}: Fix regression introduced in gh-103193@footnote{https://github.com/python/cpython/issues/103193} that meant that calling
@ref{6bc,,inspect.getattr_static()} on an instance would cause a strong
reference to that instance's class to persist in an internal cache in the
@ref{82,,inspect} module. This caused unexpected memory consumption if the
class was dynamically created, the class held strong references to other
objects which took up a significant amount of memory, and the cache
contained the sole strong reference to the class. The fix for the
regression leads to a slowdown in @code{getattr_static()}, but the
function should still be significantly faster than it was in Python 3.11.
Patch by Alex Waygood.

@item 
gh-118218@footnote{https://github.com/python/cpython/issues/118218}: Speed up @ref{a16,,itertools.pairwise()} in the common case by up to
1.8x.

@item 
gh-117486@footnote{https://github.com/python/cpython/issues/117486}: Improve the behavior of user-defined subclasses of
@ref{4c3,,ast.AST}. Such classes will now require no changes in the usual
case to conform with the behavior changes of the @ref{9,,ast} module in
Python 3.13. Patch by Jelle Zijlstra.

@item 
gh-90848@footnote{https://github.com/python/cpython/issues/90848}: Fixed @ref{1934,,unittest.mock.create_autospec()} to configure parent
mock with keyword arguments.

@item 
gh-118168@footnote{https://github.com/python/cpython/issues/118168}: Fix incorrect argument substitution when @ref{19a6,,typing.Unpack}
is used with the builtin @ref{614,,tuple}. @code{typing.Unpack} now raises
@ref{198,,TypeError} when used with certain invalid types. Patch by Jelle
Zijlstra.

@item 
gh-118131@footnote{https://github.com/python/cpython/issues/118131}: Add command-line interface for the @ref{bd,,random} module. Patch
by Hugo van Kemenade.

@item 
gh-118107@footnote{https://github.com/python/cpython/issues/118107}: Fix @ref{138,,zipimport} reading of ZIP64 files with file entries
that are too big or offset too far.

@item 
gh-102511@footnote{https://github.com/python/cpython/issues/102511}: Fix @ref{1531,,os.path.normpath()} for UNC paths on Windows. Speed up
@ref{6cb,,os.path.splitroot()} with a native implementation.

@item 
gh-117535@footnote{https://github.com/python/cpython/issues/117535}: Change the unknown filename of @ref{118,,warnings} from @code{sys} to
@code{<sys>} to clarify that it's not a real filename.

@item 
gh-114053@footnote{https://github.com/python/cpython/issues/114053}: Fix erroneous @ref{452,,NameError} when calling
@ref{8c0,,typing.get_type_hints()} on a class that made use of 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} type
parameters in a module that had @code{from __future__ import annotations} at
the top of the file. Patch by Alex Waygood.

@item 
gh-116931@footnote{https://github.com/python/cpython/issues/116931}: Add parameter `fileobj' check for
@ref{19a7,,tarfile.TarFile.addfile()}

@item 
gh-117995@footnote{https://github.com/python/cpython/issues/117995}: Don't raise @ref{1a3,,DeprecationWarning} when a @ref{716,,sequence}
of parameters is used to bind indexed, nameless placeholders. See also
gh-100668@footnote{https://github.com/python/cpython/issues/100668}.

@item 
gh-80361@footnote{https://github.com/python/cpython/issues/80361}: Fix TypeError in @ref{13e5,,email.message.Message.get_payload()} when
the charset is 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} encoded.

@item 
gh-86650@footnote{https://github.com/python/cpython/issues/86650}: Fix IndexError when parse some emails with invalid Message-ID
(including one-off addresses generated by Microsoft Outlook).

@item 
gh-117691@footnote{https://github.com/python/cpython/issues/117691}: Improve the error messages emitted by @ref{e4,,tarfile}
deprecation warnings relating to PEP 706. If a @code{filter} argument is not
provided to @code{extract()} or @code{extractall}, the deprecation warning now
points to the line in the user's code where the relevant function was
called. Patch by Alex Waygood.

@item 
gh-115874@footnote{https://github.com/python/cpython/issues/115874}: Fixed a possible segfault during garbage collection of
@code{_asyncio.FutureIter} objects. Patch by Savannah Ostrowski.

@item 
gh-115060@footnote{https://github.com/python/cpython/issues/115060}: Speed up @ref{537,,pathlib.Path.glob()} by omitting an initial
@ref{53a,,is_dir()} call. As a result of this change,
@ref{537,,glob()} can no longer raise @ref{2c0,,OSError}.

@item 
gh-77102@footnote{https://github.com/python/cpython/issues/77102}: @ref{cc,,site} module now parses @code{.pth} file with UTF-8 first,
and @ref{54a,,locale encoding} if @code{UnicodeDecodeError} happened. It
supported only locale encoding before.

@item 
gh-76785@footnote{https://github.com/python/cpython/issues/76785}: We've exposed the low-level @code{_interpreters} module for the
sake of the PyPI implementation of 
@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}.  It was sometimes available
as the @code{_xxsubinterpreters} module and was formerly used only for
testing. For the most part, it should be considered an internal module,
like @code{_thread} and @code{_imp}. See
@indicateurl{https://discuss.python.org/t/pep-734-multiple-interpreters-in-the-stdlib/41147/26}.

@item 
gh-115060@footnote{https://github.com/python/cpython/issues/115060}: Speed up @ref{537,,pathlib.Path.glob()} by not scanning directories
for non-wildcard pattern segments.

@item 
gh-117727@footnote{https://github.com/python/cpython/issues/117727}: Speed up @ref{26e,,pathlib.Path.iterdir()} by using
@ref{c54,,os.scandir()} internally.

@item 
gh-117586@footnote{https://github.com/python/cpython/issues/117586}: Speed up @ref{6cf,,pathlib.Path.walk()} by working with strings
internally.

@item 
gh-117722@footnote{https://github.com/python/cpython/issues/117722}: Change the new multi-separator support in
@ref{4d0,,asyncio.StreamReader.readuntil()} to only accept tuples of separators
rather than arbitrary iterables.

@item 
gh-117692@footnote{https://github.com/python/cpython/issues/117692}: Fixes a bug when @ref{19a8,,doctest.DocTestFinder} was failing on
wrapped @code{builtin_function_or_method}.

@item 
gh-117348@footnote{https://github.com/python/cpython/issues/117348}: Largely restored import time performance of configparser by
avoiding dataclasses.

@item 
gh-117641@footnote{https://github.com/python/cpython/issues/117641}: Speedup @ref{103d,,os.path.commonpath()} on Unix.

@item 
gh-117663@footnote{https://github.com/python/cpython/issues/117663}: Fix @code{_simple_enum} to detect aliases when multiple arguments
are present but only one is the member value.

@item 
gh-117636@footnote{https://github.com/python/cpython/issues/117636}: Speedup @ref{19a9,,os.path.join()}.

@item 
gh-117618@footnote{https://github.com/python/cpython/issues/117618}: Support @code{package.module} as @code{filename} for @code{break}
command of @ref{aa,,pdb}

@item 
gh-102247@footnote{https://github.com/python/cpython/issues/102247}: the status codes enum with constants in http.HTTPStatus are
updated to include the names from RFC9110. This RFC includes some HTTP
statuses previously only used for WEBDAV and assigns more generic names to
them.

The old constants are preserved for backwards compatibility.

@item 
gh-117607@footnote{https://github.com/python/cpython/issues/117607}: Speedup @ref{6d1,,os.path.relpath()}.

@item 
gh-117586@footnote{https://github.com/python/cpython/issues/117586}: Speed up @ref{537,,pathlib.Path.glob()} by working with strings
internally.

@item 
gh-117225@footnote{https://github.com/python/cpython/issues/117225}: Add colour to doctest output. Patch by Hugo van Kemenade.

@item 
gh-117566@footnote{https://github.com/python/cpython/issues/117566}: @ref{19aa,,ipaddress.IPv6Address.is_loopback()} will now return
@code{True} for IPv4-mapped loopback addresses, i.e. addresses in the
@code{::ffff:127.0.0.0/104} address space.

@item 
gh-117546@footnote{https://github.com/python/cpython/issues/117546}: Fix issue where @ref{262,,os.path.realpath()} stopped resolving
symlinks after encountering a symlink loop on POSIX.

@item 
gh-116720@footnote{https://github.com/python/cpython/issues/116720}: Improved behavior of @ref{4d1,,asyncio.TaskGroup} when an
external cancellation collides with an internal cancellation. For example,
when two task groups are nested and both experience an exception in a
child task simultaneously, it was possible that the outer task group would
misbehave, because its internal cancellation was swallowed by the inner
task group.

In the case where a task group is cancelled externally and also must raise
an @ref{4d2,,ExceptionGroup}, it will now call the parent task's
@ref{4d3,,cancel()} method. This ensures that a
@ref{4d4,,asyncio.CancelledError} will be raised at the next @ref{18d,,await},
so the cancellation is not lost.

An added benefit of these changes is that task groups now preserve the
cancellation count (@ref{4d5,,asyncio.Task.cancelling()}).

In order to handle some corner cases, @ref{4d6,,asyncio.Task.uncancel()} may
now reset the undocumented @code{_must_cancel} flag when the cancellation
count reaches zero.

@item 
gh-117516@footnote{https://github.com/python/cpython/issues/117516}: Add @ref{48b,,typing.TypeIs}, implementing 
@geindex Python Enhancement Proposals; PEP 742
PEP 742@footnote{https://peps.python.org/pep-0742/}. Patch by
Jelle Zijlstra.

@item 
gh-117503@footnote{https://github.com/python/cpython/issues/117503}: Fix support of non-ASCII user names in bytes paths in
@ref{c09,,os.path.expanduser()} on Posix.

@item 
gh-117394@footnote{https://github.com/python/cpython/issues/117394}: @ref{c07,,os.path.ismount()} is now 2-3 times faster if the user has
permissions.

@item 
gh-117313@footnote{https://github.com/python/cpython/issues/117313}: Only treat @code{'\n'}, @code{'\r'} and @code{'\r\n'} as line separators
in re-folding the @ref{3f,,email} messages. Preserve control characters
@code{'\v'}, @code{'\f'}, @code{'\x1c'}, @code{'\x1d'} and @code{'\x1e'} and Unicode line
separators @code{'\x85'}, @code{'\u2028'} and @code{'\u2029'} as is.

@item 
gh-117142@footnote{https://github.com/python/cpython/issues/117142}: Convert @code{_ctypes} to multi-phase initialisation
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
gh-66543@footnote{https://github.com/python/cpython/issues/66543}: Add the @ref{516,,mimetypes.guess_file_type()} function which works
with file path. Passing file path instead of URL in
@ref{517,,guess_type()} is @ref{23d,,soft deprecated}.

@item 
gh-68583@footnote{https://github.com/python/cpython/issues/68583}: webbrowser CLI: replace getopt with argparse, add long options.
Patch by Hugo van Kemenade.

@item 
gh-116871@footnote{https://github.com/python/cpython/issues/116871}: Name suggestions for @ref{5f0,,AttributeError} and
@ref{65b,,ImportError} now only include underscored names if the original name
was underscored.

@item 
gh-116023@footnote{https://github.com/python/cpython/issues/116023}: Don't show empty fields (value @code{None} or @code{[]}) in
@ref{ae1,,ast.dump()} by default. Add @code{show_empty=False} parameter to
optionally show them.

@item 
gh-115961@footnote{https://github.com/python/cpython/issues/115961}: Added @code{name} and @code{mode} attributes for compressed
and archived file-like objects in modules @ref{14,,bz2}, @ref{8e,,lzma},
@ref{e4,,tarfile} and @ref{137,,zipfile}. The value of the @code{mode}
attribute of @ref{65c,,gzip.GzipFile} was changed from integer (@code{1} or
@code{2}) to string (@code{'rb'} or @code{'wb'}). The value of the @code{mode}
attribute of the readable file-like object returned by
@ref{65d,,zipfile.ZipFile.open()} was changed from @code{'r'} to @code{'rb'}.

@item 
gh-82062@footnote{https://github.com/python/cpython/issues/82062}: Fix @ref{22f,,inspect.signature()} to correctly handle parameter
defaults on methods in extension modules that use names defined in the
module namespace.

@item 
gh-83856@footnote{https://github.com/python/cpython/issues/83856}: Honor @ref{d,,atexit} for all @ref{98,,multiprocessing} start methods

@item 
gh-113081@footnote{https://github.com/python/cpython/issues/113081}: Print colorized exception just like built-in traceback in
@ref{aa,,pdb}

@item 
gh-112855@footnote{https://github.com/python/cpython/issues/112855}: Speed up pickling of @ref{6cd,,pathlib.PurePath} objects. Patch
by Barney Gale.

@item 
gh-111744@footnote{https://github.com/python/cpython/issues/111744}: Support opcode events in @ref{10,,bdb}

@item 
gh-109617@footnote{https://github.com/python/cpython/issues/109617}: @code{ncurses}: fixed a crash that could occur on macOS 13 or
earlier when Python was built with Apple Xcode 15's SDK.

@item 
gh-83151@footnote{https://github.com/python/cpython/issues/83151}: Enabled arbitrary statements and evaluations in @ref{aa,,pdb} shell
to access the local variables of the current frame, which made it possible
for multi-scope code like generators or nested function to work.

@item 
gh-110209@footnote{https://github.com/python/cpython/issues/110209}: Add @ref{943,,__class_getitem__()} to
@ref{19ab,,types.GeneratorType} and @ref{1089,,types.CoroutineType} for type
hinting purposes. Patch by James Hilton-Balfe.

@item 
gh-108191@footnote{https://github.com/python/cpython/issues/108191}: The @ref{4e5,,types.SimpleNamespace} now accepts an optional
positional argument which specifies initial values of attributes as a dict
or an iterable of key-value pairs.

@item 
gh-62090@footnote{https://github.com/python/cpython/issues/62090}: Fix assertion errors caused by whitespace in metavars or
@code{SUPPRESS}-ed groups in @ref{7,,argparse} by simplifying usage formatting.
Patch by Ali Hamdan.

@item 
gh-102402@footnote{https://github.com/python/cpython/issues/102402}: Adjust @code{logging.LogRecord} to use @code{time.time_ns()} and fix
minor bug related to floating-point math.

@item 
gh-100242@footnote{https://github.com/python/cpython/issues/100242}: Bring pure Python implementation @code{functools.partial.__new__}
more in line with the C-implementation by not just always checking for the
presence of the attribute @code{'func'} on the first argument of @code{partial}.
Instead, both the Python version and the C version perform an
@code{isinstance(func, partial)} check on the first argument of @code{partial}.

@item 
gh-99730@footnote{https://github.com/python/cpython/issues/99730}: HEAD requests are no longer upgraded to GET request during
redirects in urllib.

@item 
gh-66410@footnote{https://github.com/python/cpython/issues/66410}: Setting the @code{tkinter} module global @code{wantobjects}
to @code{2} before creating the @ref{19ac,,Tk} object or call the
@code{wantobjects()} method of the @code{Tk} object with argument @code{2}
makes now arguments to callbacks registered in the @ref{f6,,tkinter} module
to be passed as various Python objects (@code{int}, @code{float}, @code{bytes},
@code{tuple}), depending on their internal representation in Tcl, instead of
always @code{str}. @code{tkinter.wantobjects} is now set to @code{2} by
default.

@item 
bpo-40943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40943}: Fix several IndexError when parse emails with truncated
Message-ID, address, routes, etc, e.g. @code{example@@}.

@item 
bpo-39324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39324}: Add mime type mapping for .md <-> text/markdown

@item 
bpo-18108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18108}: @ref{548,,shutil.chown()} now supports `dir_fd' and
`follow_symlinks' keyword arguments.

@item 
bpo-30988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30988}: Fix parsing of emails with invalid address headers having a
leading or trailing dot. Patch by tsufeki.

@item 
bpo-32839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32839}: Add the @code{after_info()} method for Tkinter widgets.
@end itemize

@node ドキュメント<15>,ビルド<16>,ライブラリ<55>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id211}@anchor{19ad}
@subsubsection ドキュメント



@itemize -

@item 
gh-117928@footnote{https://github.com/python/cpython/issues/117928}: The minimum Sphinx version required for the documentation is
now 6.2.1.
@end itemize

@node ビルド<16>,Windows<15>,ドキュメント<15>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id212}@anchor{19ae}
@subsubsection ビルド



@itemize -

@item 
gh-118734@footnote{https://github.com/python/cpython/issues/118734}: Fixes Windows build when invoked directly (not through the
@code{build.bat} script) without specifying a value for @code{UseTIER2}.

@item 
gh-115119@footnote{https://github.com/python/cpython/issues/115119}: The @code{configure} option @ref{657,,--with-system-libmpdec}
now defaults to @code{yes}. The bundled copy of @code{libmpdecimal} will be
removed in Python 3.15.

@item 
gh-117845@footnote{https://github.com/python/cpython/issues/117845}: Fix building against recent libedit versions by detecting
readline hook signatures in @code{configure}.

@item 
gh-116622@footnote{https://github.com/python/cpython/issues/116622}: A testbed project was added to run the test suite on Android.

@item 
gh-117645@footnote{https://github.com/python/cpython/issues/117645}: Increase WASI stack size from 512 KiB to 8 MiB and the initial
memory from 10 MiB to 20 MiB. Patch by Victor Stinner.

@item 
gh-115119@footnote{https://github.com/python/cpython/issues/115119}: @code{configure} now uses @code{pkg-config} to detect
@ref{3a,,decimal} dependencies if the @ref{657,,--with-system-libmpdec} option
is given.
@end itemize

@node Windows<15>,macOS<9>,ビルド<16>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id213}@anchor{19af}
@subsubsection Windows



@itemize -

@item 
gh-115119@footnote{https://github.com/python/cpython/issues/115119}: Update Windows installer to use libmpdecimal 4.0.0.

@item 
gh-118486@footnote{https://github.com/python/cpython/issues/118486}: @ref{52b,,os.mkdir()} now accepts `mode' of @code{0o700} to restrict
the new directory to the current user.

@item 
gh-118347@footnote{https://github.com/python/cpython/issues/118347}: Fixes launcher updates not being installed.

@item 
gh-118293@footnote{https://github.com/python/cpython/issues/118293}: The @code{multiprocessing} module now passes the
@code{STARTF_FORCEOFFFEEDBACK} flag when spawning processes to tell Windows
not to change the mouse cursor.

@item 
gh-115009@footnote{https://github.com/python/cpython/issues/115009}: Update Windows installer to use SQLite 3.45.3.

@item 
gh-90329@footnote{https://github.com/python/cpython/issues/90329}: Suppress the warning displayed on virtual environment creation
when the requested and created paths differ only by a short (8.3 style)
name. Warnings will continue to be shown if a junction or symlink in the
path caused the venv to be created in a different location than originally
requested.

@item 
gh-117786@footnote{https://github.com/python/cpython/issues/117786}: Fixes virtual environments not correctly launching when created
from a Store install.
@end itemize

@node macOS<9>,IDLE<8>,Windows<15>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id214}@anchor{19b0}
@subsubsection macOS



@itemize -

@item 
gh-115119@footnote{https://github.com/python/cpython/issues/115119}: Update macOS installer to use libmpdecimal 4.0.0.

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: iOS preprocessor symbol usage was made compatible with older
macOS SDKs.

@item 
gh-115009@footnote{https://github.com/python/cpython/issues/115009}: Update macOS installer to use SQLite 3.45.3.

@item 
gh-91629@footnote{https://github.com/python/cpython/issues/91629}: Use @code{~/.config/fish/conf.d} configs and
@code{fish_add_path} to set 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} when installing for the
Fish shell.
@end itemize

@node IDLE<8>,C API<16>,macOS<9>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id215}@anchor{19b1}
@subsubsection IDLE



@itemize -

@item 
bpo-34774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34774}: Use user-selected color theme for Help => IDLE Doc.
@end itemize

@node C API<16>,,IDLE<8>,Python 3 13 0 beta 1
@anchor{whatsnew/changelog id216}@anchor{19b2}
@subsubsection C API



@itemize -

@item 
gh-118124@footnote{https://github.com/python/cpython/issues/118124}: Fix @ref{19b3,,Py_BUILD_ASSERT} and
@ref{19b4,,Py_BUILD_ASSERT_EXPR} for non-constant expressions: use
@code{static_assert()} on C11 and newer. Patch by Victor Stinner.

@item 
gh-110850@footnote{https://github.com/python/cpython/issues/110850}: Add "Raw" variant of PyTime functions


@itemize *

@item 
@ref{5d8,,PyTime_MonotonicRaw()}

@item 
@ref{5da,,PyTime_PerfCounterRaw()}

@item 
@ref{5dc,,PyTime_TimeRaw()}
@end itemize

Patch by Victor Stinner.

@item 
gh-117987@footnote{https://github.com/python/cpython/issues/117987}: Restore functions removed in Python 3.13 alpha 1:


@itemize *

@item 
@ref{19b5,,Py_SetPythonHome()}

@item 
@ref{19b6,,Py_SetProgramName()}

@item 
@ref{19b7,,PySys_SetArgvEx()}

@item 
@ref{19b8,,PySys_SetArgv()}
@end itemize

Patch by Victor Stinner.

@item 
gh-117929@footnote{https://github.com/python/cpython/issues/117929}: Restore removed @ref{19b9,,PyEval_InitThreads()} function. Patch by
Victor Stinner.

@item 
gh-117534@footnote{https://github.com/python/cpython/issues/117534}: Improve validation logic in the C implementation of
@ref{82a,,datetime.datetime.fromisoformat()} to better handle invalid years.
Patch by Vlad Efanov.

@item 
gh-68114@footnote{https://github.com/python/cpython/issues/68114}: Fixed skipitem()'s handling of the old 'w' and 'w#' formatters.
These are no longer supported and now raise an exception if used.

@item 
gh-111997@footnote{https://github.com/python/cpython/issues/111997}: Add a C-API for firing monitoring events.
@end itemize

@node Python 3 13 0 alpha 6,Python 3 13 0 alpha 5,Python 3 13 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-13-0-alpha-6}@anchor{19ba}
@subsection Python 3.13.0 alpha 6


`Release date: 2024-04-09'

@menu
* Core and Builtins: Core and Builtins<51>. 
* ライブラリ: ライブラリ<56>. 
* Core and Builtins: Core and Builtins<52>. 
* ライブラリ: ライブラリ<57>. 
* ドキュメント: ドキュメント<16>. 
* テスト: テスト<14>. 
* ビルド: ビルド<17>. 
* Windows: Windows<16>. 
* C API: C API<17>. 

@end menu

@node Core and Builtins<51>,ライブラリ<56>,,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id217}@anchor{19bb}
@subsubsection Core and Builtins



@itemize -

@item 
gh-117494@footnote{https://github.com/python/cpython/issues/117494}: Refactored the instruction sequence data structure out of
compile.c into instruction_sequence.c.

@item 
gh-116968@footnote{https://github.com/python/cpython/issues/116968}: Introduce a unified 16-bit backoff counter type
(@code{_Py_BackoffCounter}), shared between the Tier 1 adaptive specializer
and the Tier 2 optimizer. The API used for adaptive specialization
counters is changed but the behavior is (supposed to be) identical.

The behavior of the Tier 2 counters is changed:


@itemize *

@item 
There are no longer dynamic thresholds (we never varied these).

@item 
All counters now use the same exponential backoff.

@item 
The counter for @code{JUMP_BACKWARD} starts counting down from 16.

@item 
The @code{temperature} in side exits starts counting down from 64.
@end itemize

@item 
gh-117431@footnote{https://github.com/python/cpython/issues/117431}: Improve the performance of the following @ref{192,,bytes} and
@ref{344,,bytearray} methods by adapting them to the
@ref{199e,,METH_FASTCALL} calling convention:


@itemize *

@item 
@code{endswith()}

@item 
@code{startswith()}
@end itemize

@item 
gh-117431@footnote{https://github.com/python/cpython/issues/117431}: Improve the performance of the following @ref{169,,str} methods
by adapting them to the @ref{199e,,METH_FASTCALL} calling convention:


@itemize *

@item 
@ref{1981,,count()}

@item 
@ref{10cc,,endswith()}

@item 
@ref{10a8,,find()}

@item 
@ref{19bc,,index()}

@item 
@ref{10a9,,rfind()}

@item 
@ref{146f,,rindex()}

@item 
@ref{10cb,,startswith()}
@end itemize

@item 
gh-117411@footnote{https://github.com/python/cpython/issues/117411}: Move @code{PyFutureFeatures} to an internal header and make it
private.

@item 
gh-109120@footnote{https://github.com/python/cpython/issues/109120}: Added handle of incorrect star expressions, e.g @code{f(3, *)}.
Patch by Grigoryev Semyon

@item 
gh-117266@footnote{https://github.com/python/cpython/issues/117266}: Fix crashes for certain user-created subclasses of
@ref{4c3,,ast.AST}. Such classes are now expected to set the
@code{_field_types} attribute.

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Updated the @ref{6c,,hashlib} built-in HACL* project@footnote{https://github.com/hacl-star/hacl-star} C code
from upstream that we use for many implementations when they are not
present via OpenSSL in a given build.  This also avoids the rare potential
for a C symbol name one definition rule linking issue.

@item 
gh-117108@footnote{https://github.com/python/cpython/issues/117108}: Change the old space bit of objects in the young generation
from 0 to gcstate->visited, so that any objects created during GC will
have the old bit set correctly if they get moved into the old generation.

@item 
gh-117108@footnote{https://github.com/python/cpython/issues/117108}: The cycle GC now chooses the size of increments based on the
total heap size, instead of the rate of object creation. This ensures that
it can keep up with growing heaps.

@item 
gh-116735@footnote{https://github.com/python/cpython/issues/116735}: For @code{INSTRUMENTED_CALL_FUNCTION_EX}, set @code{arg0} to
@code{sys.monitoring.MISSING} instead of @code{None} for
@ref{19bd,,CALL} event.

@item 
gh-113964@footnote{https://github.com/python/cpython/issues/113964}: Starting new threads and process creation through
@ref{4b5,,os.fork()} are now only prevented once all non-daemon threads exit.

@item 
gh-116626@footnote{https://github.com/python/cpython/issues/116626}: Ensure @code{INSTRUMENTED_CALL_FUNCTION_EX} always emits
@ref{19bd,,CALL}

@item 
gh-116554@footnote{https://github.com/python/cpython/issues/116554}: @code{list.sort()} now exploits more cases of partial ordering,
particularly those with long descending runs with sub-runs of equal
values. Those are recognized as single runs now (previously, each block of
repeated values caused a new run to be created).

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: Added a Loader that can discover extension modules in an
iOS-style Frameworks folder.

@item 
gh-115775@footnote{https://github.com/python/cpython/issues/115775}: Compiler populates the new @code{__static_attributes__} field on a
class with the names of attributes of this class which are accessed
through self.X from any function in its body.

@item 
gh-115776@footnote{https://github.com/python/cpython/issues/115776}: The array of values, the @code{PyDictValues} struct is now
embedded in the object during allocation. This provides better performance
in the common case, and does not degrade as much when the object's
@code{__dict__} is materialized.

@item 
gh-108362@footnote{https://github.com/python/cpython/issues/108362}: Implement an incremental cyclic garbage collector. By
collecting the old generation in increments, there is no need for a full
heap scan. This can hugely reduce maximum pause time for programs with
large heaps.

Reduce the number of generations from three to two. The old generation is
split into two spaces, "visited" and "pending".

Collection happens in two steps:: * An increment is formed from the young
generation and a small part of the pending space. * This increment is
scanned and the survivors moved to the end of the visited space.

When the collecting space becomes empty, the two spaces are swapped.
@end itemize

@node ライブラリ<56>,Core and Builtins<52>,Core and Builtins<51>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id218}@anchor{19be}
@subsubsection ライブラリ



@itemize -

@item 
gh-109870@footnote{https://github.com/python/cpython/issues/109870}: Dataclasses now calls @ref{4a2,,exec()} once per dataclass, instead
of once per method being added.  This can speed up dataclass creation by
up to 20%.

@item 
gh-97901@footnote{https://github.com/python/cpython/issues/97901}: Mime type @code{text/rtf} is now supported by @ref{93,,mimetypes}.
@end itemize

@node Core and Builtins<52>,ライブラリ<57>,ライブラリ<56>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id219}@anchor{19bf}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24612}: Improve the @ref{18e,,SyntaxError} that happens when 'not' appears
after an operator. Patch by Pablo Galindo
@end itemize

@node ライブラリ<57>,ドキュメント<16>,Core and Builtins<52>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id220}@anchor{19c0}
@subsubsection ライブラリ



@itemize -

@item 
gh-117648@footnote{https://github.com/python/cpython/issues/117648}: Improve performance of @ref{19a9,,os.path.join()} and
@ref{c09,,os.path.expanduser()}.

@item 
gh-117584@footnote{https://github.com/python/cpython/issues/117584}: Raise @ref{198,,TypeError} for non-paths in
@ref{6d1,,posixpath.relpath}.

@item 
gh-117467@footnote{https://github.com/python/cpython/issues/117467}: Preserve mailbox ownership when rewriting in
@ref{19c1,,mailbox.mbox.flush}. Patch by Tony
Mountifield.

@item 
gh-114848@footnote{https://github.com/python/cpython/issues/114848}: Raise @ref{264,,FileNotFoundError} when @code{getcwd()} returns
'(unreachable)', which can happen on Linux >= 2.6.36 with glibc < 2.27.

@item 
gh-117459@footnote{https://github.com/python/cpython/issues/117459}: @code{asyncio.asyncio.run_coroutine_threadsafe()} now keeps the
traceback of @code{CancelledError}, @ref{a36,,TimeoutError} and
@code{InvalidStateError} which are raised in the coroutine.

@item 
gh-117381@footnote{https://github.com/python/cpython/issues/117381}: Fix error message for @code{ntpath.commonpath()}.

@item 
gh-117337@footnote{https://github.com/python/cpython/issues/117337}: Deprecate undocumented @code{glob.glob0()} and
@code{glob.glob1()} functions. Use @ref{5a0,,glob.glob()} and pass a directory
to its `root_dir' argument instead.

@item 
gh-117349@footnote{https://github.com/python/cpython/issues/117349}: Optimise several functions in @ref{a6,,os.path}.

@item 
gh-117348@footnote{https://github.com/python/cpython/issues/117348}: Refactored @code{configparser.RawConfigParser._read()} to reduce
cyclometric complexity and improve comprehensibility.

@item 
gh-117335@footnote{https://github.com/python/cpython/issues/117335}: Raise TypeError for non-sequences for
@code{ntpath.commonpath()}.

@item 
gh-66449@footnote{https://github.com/python/cpython/issues/66449}: @ref{4de,,configparser.ConfigParser} now accepts unnamed sections
before named ones, if configured to do so.

@item 
gh-88014@footnote{https://github.com/python/cpython/issues/88014}: In documentation of @ref{65c,,gzip.GzipFile} in module gzip,
explain data type of optional constructor argument `mtime', and recommend
@code{mtime = 0} for generating deterministic streams.

@item 
gh-117310@footnote{https://github.com/python/cpython/issues/117310}: Fixed an unlikely early & extra @code{Py_DECREF} triggered crash
in @ref{d5,,ssl} when creating a new @code{_ssl._SSLContext} if CPython was
built implausibly such that the default cipher list is empty `or' the
SSL library it was linked against reports a failure from its C
@code{SSL_CTX_set_cipher_list()} API.

@item 
gh-117294@footnote{https://github.com/python/cpython/issues/117294}: A @code{DocTestCase} now reports as skipped if all examples in the
doctest are skipped.

@item 
gh-98966@footnote{https://github.com/python/cpython/issues/98966}: In @ref{dc,,subprocess}, raise a more informative message when
@code{stdout=STDOUT}.

@item 
gh-117225@footnote{https://github.com/python/cpython/issues/117225}: doctest: only print "and X failed" when non-zero, don't
pluralise "1 items". Patch by Hugo van Kemenade.

@item 
gh-117205@footnote{https://github.com/python/cpython/issues/117205}: Speed up @ref{d1b,,compileall.compile_dir()} by 20% when using
multiprocessing by increasing @code{chunksize}.

@item 
gh-117178@footnote{https://github.com/python/cpython/issues/117178}: Fix regression in lazy loading of self-referential modules,
introduced in gh-114781@footnote{https://github.com/python/cpython/issues/114781}.

@item 
gh-112383@footnote{https://github.com/python/cpython/issues/112383}: Fix @ref{3c,,dis} module's handling of @code{ENTER_EXECUTOR}
instructions.

@item 
gh-117182@footnote{https://github.com/python/cpython/issues/117182}: Lazy-loading of modules that modify their own @code{__class__} no
longer reverts the @code{__class__} to @ref{1014,,types.ModuleType}.

@item 
gh-117084@footnote{https://github.com/python/cpython/issues/117084}: Fix @ref{137,,zipfile} extraction for directory entries with the
name containing backslashes on Windows.

@item 
gh-117114@footnote{https://github.com/python/cpython/issues/117114}: Make @ref{19c2,,os.path.isdevdrive()} available on all platforms. For
those that do not offer Dev Drives, it will always return @code{False}.

@item 
gh-117110@footnote{https://github.com/python/cpython/issues/117110}: Fix a bug that prevents subclasses of @ref{8bb,,typing.Any} to be
instantiated with arguments. Patch by Chris Fu.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Deferred select imports in importlib.metadata and
importlib.resources for a 14% speedup.

@item 
gh-70647@footnote{https://github.com/python/cpython/issues/70647}: Start the deprecation period for the current behavior of
@ref{1950,,datetime.datetime.strptime()} and @ref{1646,,time.strptime()} which always
fails to parse a date string with a @ref{2ec,,ValueError} involving a day of
month such as @code{strptime("02-29", "%m-%d")} when a year is `not'
specified and the date happen to be February 29th.  This should help avoid
users finding new bugs every four years due to a natural mistaken
assumption about the API when parsing partial date values.

@item 
gh-116987@footnote{https://github.com/python/cpython/issues/116987}: Fixed @code{inspect.findsource()} for class code objects.

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: Modify standard library to allow for iOS platform differences.

@item 
gh-90872@footnote{https://github.com/python/cpython/issues/90872}: On Windows, @ref{ee0,,subprocess.Popen.wait()} no longer calls
@code{WaitForSingleObject()} with a negative timeout: pass @code{0} ms if the
timeout is negative. Patch by Victor Stinner.

@item 
gh-116957@footnote{https://github.com/python/cpython/issues/116957}: configparser: Don't leave ConfigParser values in an invalid
state (stored as a list instead of a str) after an earlier read raised
DuplicateSectionError or DuplicateOptionError.

@item 
gh-115538@footnote{https://github.com/python/cpython/issues/115538}: @code{_io.WindowsConsoleIO} now emit a warning if a boolean
value is passed as a filedescriptor argument.

@item 
gh-90095@footnote{https://github.com/python/cpython/issues/90095}: Ignore empty lines and comments in @code{.pdbrc}

@item 
gh-106531@footnote{https://github.com/python/cpython/issues/106531}: Refreshed zipfile._path from zipp 3.18@footnote{https://zipp.readthedocs.io/en/latest/history.html#v3-18-0}, providing
better compatibility for PyPy, better glob performance for deeply nested
zipfiles, and providing internal access to @code{CompleteDirs.inject} for use
in other tests (like importlib.resources).

@item 
gh-63207@footnote{https://github.com/python/cpython/issues/63207}: On Windows, @ref{55d,,time.time()} now uses the
@code{GetSystemTimePreciseAsFileTime()} clock to have a resolution better
than 1 us, instead of the @code{GetSystemTimeAsFileTime()} clock which has a
resolution of 15.6 ms. Patch by Victor Stinner.

@item 
gh-116764@footnote{https://github.com/python/cpython/issues/116764}: Restore support of @code{None} and other false values in
@ref{110,,urllib.parse} functions @ref{31f,,parse_qs()} and
@ref{31e,,parse_qsl()}. Also, they now raise a TypeError for
non-zero integers and non-empty sequences.

@item 
gh-116811@footnote{https://github.com/python/cpython/issues/116811}: In @code{PathFinder.invalidate_caches}, delegate to
@code{MetadataPathFinder.invalidate_caches}.

@item 
gh-116647@footnote{https://github.com/python/cpython/issues/116647}: Fix recursive child in dataclasses

@item 
gh-113171@footnote{https://github.com/python/cpython/issues/113171}: Fixed various false positives and false negatives in


@itemize *

@item 
@ref{19c3,,ipaddress.IPv4Address.is_private} (see these docs for details)

@item 
@ref{1161,,ipaddress.IPv4Address.is_global}

@item 
@ref{19c4,,ipaddress.IPv6Address.is_private}

@item 
@ref{19c5,,ipaddress.IPv6Address.is_global}
@end itemize

Also in the corresponding @ref{50e,,ipaddress.IPv4Network} and
@ref{50f,,ipaddress.IPv6Network} attributes.

@item 
gh-63283@footnote{https://github.com/python/cpython/issues/63283}: In @ref{56,,encodings.idna}, any capitalization of the ACE prefix
(@code{xn--}) is now acceptable. Patch by Pepijn de Vos and Zackery Spytz.

@item 
gh-71042@footnote{https://github.com/python/cpython/issues/71042}: Add @ref{19c6,,platform.android_ver()}, which provides device and OS
information on Android.

@item 
gh-73468@footnote{https://github.com/python/cpython/issues/73468}: Added new @ref{514,,math.fma()} function, wrapping C99's @code{fma()}
operation: fused multiply-add function. Patch by Mark Dickinson and Victor
Stinner.

@item 
gh-116608@footnote{https://github.com/python/cpython/issues/116608}: The @ref{7f,,importlib.resources} functions
@ref{4fd,,is_resource()},
@ref{4fe,,open_binary()},
@ref{4ff,,open_text()}, @ref{500,,path()},
@ref{501,,read_binary()}, and
@ref{502,,read_text()} are un-deprecated, and support
subdirectories via multiple positional arguments. The
@ref{503,,contents()} function also allows subdirectories,
but remains deprecated.

@item 
gh-116484@footnote{https://github.com/python/cpython/issues/116484}: Change automatically generated @code{tkinter.Checkbutton}
widget names to avoid collisions with automatically generated
@code{tkinter.ttk.Checkbutton} widget names within the same parent
widget.

@item 
gh-114314@footnote{https://github.com/python/cpython/issues/114314}: In @ref{2e,,ctypes}, ctype data is now stored in type objects
directly rather than in a dict subclass. This is an internal change that
should not affect usage.

@item 
gh-116401@footnote{https://github.com/python/cpython/issues/116401}: Fix blocking @ref{d52,,os.fwalk()} and @ref{356,,shutil.rmtree()} on
opening named pipe.

@item 
gh-71052@footnote{https://github.com/python/cpython/issues/71052}: Implement @ref{f45,,ctypes.util.find_library()} on Android.

@item 
gh-90535@footnote{https://github.com/python/cpython/issues/90535}: Fix support of `interval' values > 1 in
@code{logging.TimedRotatingFileHandler} for @code{when='MIDNIGHT'} and
@code{when='Wx'}.

@item 
gh-113308@footnote{https://github.com/python/cpython/issues/113308}: Remove some internal protected parts from @ref{116,,uuid}:
@code{_has_uuid_generate_time_safe}, @code{_netbios_getnode},
@code{_ipconfig_getnode}, and @code{_load_system_functions}. They were unused.

@item 
gh-115627@footnote{https://github.com/python/cpython/issues/115627}: Fix the @ref{d5,,ssl} module error handling of connection
terminate by peer. It now throws an OSError with the appropriate error
code instead of an EOFError.

@item 
gh-114847@footnote{https://github.com/python/cpython/issues/114847}: Speed up @ref{262,,os.path.realpath()} on non-Windows platforms.

@item 
gh-114271@footnote{https://github.com/python/cpython/issues/114271}: Fix a race in @code{threading.Thread.join()}.

@code{threading._MainThread} now always represents the main thread of the
main interpreter.

@code{PyThreadState.on_delete} and @code{PyThreadState.on_delete_data} have been
removed.

@item 
gh-113538@footnote{https://github.com/python/cpython/issues/113538}: Add @ref{4ce,,asyncio.Server.close_clients()} and
@ref{4cf,,asyncio.Server.abort_clients()} methods which allow to more
forcefully close an asyncio server.

@item 
gh-85287@footnote{https://github.com/python/cpython/issues/85287}: Changes Unicode codecs to return UnicodeEncodeError or
UnicodeDecodeError, rather than just UnicodeError.

@item 
gh-113548@footnote{https://github.com/python/cpython/issues/113548}: @ref{aa,,pdb} now allows CLI arguments to @code{pdb -m}.

@item 
gh-112948@footnote{https://github.com/python/cpython/issues/112948}: Make completion of @ref{aa,,pdb} similar to Python REPL

@item 
gh-105866@footnote{https://github.com/python/cpython/issues/105866}: Fixed @code{_get_slots} bug which caused error when defining
dataclasses with slots and a weakref_slot.

@item 
gh-96471@footnote{https://github.com/python/cpython/issues/96471}: Add @ref{c6a,,asyncio.Queue} termination with
@ref{4cc,,shutdown()} method.

@item 
gh-89739@footnote{https://github.com/python/cpython/issues/89739}: The @ref{138,,zipimport} module can now read ZIP64 files.

@item 
bpo-33533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33533}: @ref{4c6,,asyncio.as_completed()} now returns an object that is both
an asynchronous iterator and plain iterator. The new asynchronous
iteration pattern allows for easier correlation between prior tasks and
their completed results. This is a closer match to
@ref{19c7,,concurrent.futures.as_completed()}'s iteration pattern. Patch by
Justin Arthur.

@item 
bpo-27578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27578}: @ref{17c3,,inspect.getsource()} (and related functions) work with
empty module files, returning @code{'\n'} (or reasonable equivalent) instead
of raising @code{OSError}. Patch by Kernc.

@item 
bpo-37141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37141}: Accept an iterable of separators in
@ref{4d0,,asyncio.StreamReader.readuntil()}, stopping when one of them is
encountered.

@item 
gh-66543@footnote{https://github.com/python/cpython/issues/66543}: Make @ref{517,,mimetypes.guess_type()} properly parsing of URLs with
only a host name, URLs containing fragment or query, and filenames with
only a UNC sharepoint on Windows. Based on patch by Dong-hee Na.

@item 
bpo-15010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15010}: @ref{11e7,,unittest.TestLoader.discover()} now saves the original
value of @code{unittest.TestLoader._top_level_dir} and restores it at the end
of the call.
@end itemize

@node ドキュメント<16>,テスト<14>,ライブラリ<57>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id221}@anchor{19c8}
@subsubsection ドキュメント



@itemize -

@item 
gh-115977@footnote{https://github.com/python/cpython/issues/115977}: Remove compatibility references to Emscripten.

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: Add an iOS platform guide, and flag modules not available on
iOS.

@item 
gh-91565@footnote{https://github.com/python/cpython/issues/91565}: Changes to documentation files and config outputs to reflect the
new location for reporting bugs - i.e. GitHub rather than bugs.python.org.
@end itemize

@node テスト<14>,ビルド<17>,ドキュメント<16>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id222}@anchor{19c9}
@subsubsection テスト



@itemize -

@item 
gh-83434@footnote{https://github.com/python/cpython/issues/83434}: Disable JUnit XML output (@code{--junit-xml=FILE} command line
option) in regrtest when hunting for reference leaks (@code{-R} option).
Patch by Victor Stinner.

@item 
gh-117187@footnote{https://github.com/python/cpython/issues/117187}: Fix XML tests for vanilla Expat <2.6.0.

@item 
gh-116333@footnote{https://github.com/python/cpython/issues/116333}: Tests of TLS related things (error codes, etc) were updated to
be more lenient about specific error message strings and behaviors as seen
in the BoringSSL and AWS-LC forks of OpenSSL.

@item 
gh-117089@footnote{https://github.com/python/cpython/issues/117089}: Consolidated tests for importlib.metadata in their own
@code{metadata} package.

@item 
gh-115979@footnote{https://github.com/python/cpython/issues/115979}: Update test_importlib so that it passes under WASI SDK 21.

@item 
gh-112536@footnote{https://github.com/python/cpython/issues/112536}: Add --tsan to test.regrtest for running TSAN tests in
reasonable execution times. Patch by Donghee Na.

@item 
gh-116307@footnote{https://github.com/python/cpython/issues/116307}: Added import helper @code{isolated_modules} as @code{CleanImport}
does not remove modules imported during the context. Use it in
importlib.resources tests to avoid leaving @code{mod} around to impede
importlib.metadata tests.
@end itemize

@node ビルド<17>,Windows<16>,テスト<14>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id223}@anchor{19ca}
@subsubsection ビルド



@itemize -

@item 
gh-114736@footnote{https://github.com/python/cpython/issues/114736}: Have WASI builds use WASI SDK 21.

@item 
gh-115983@footnote{https://github.com/python/cpython/issues/115983}: Skip building test modules that must be built as shared under
WASI.

@item 
gh-71052@footnote{https://github.com/python/cpython/issues/71052}: Add Android build script and instructions.
@end itemize

@node Windows<16>,C API<17>,ビルド<17>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id224}@anchor{19cb}
@subsubsection Windows



@itemize -

@item 
gh-117267@footnote{https://github.com/python/cpython/issues/117267}: Ensure @code{DirEntry.stat().st_ctime} behaves consistently with
@ref{26d,,os.stat()} during the deprecation period of @code{st_ctime} by
containing the same value as @code{st_birthtime}. After the deprecation
period, @code{st_ctime} will be the metadata change time (or unavailable
through @code{DirEntry}), and only @code{st_birthtime} will contain the creation
time.

@item 
gh-116195@footnote{https://github.com/python/cpython/issues/116195}: Improves performance of @ref{19cc,,os.getppid()} by using an
alternate system API when available. Contributed by vxiiduu.

@item 
gh-88494@footnote{https://github.com/python/cpython/issues/88494}: On Windows, @ref{55c,,time.monotonic()} now uses the
@code{QueryPerformanceCounter()} clock to have a resolution better than 1 us,
instead of the @code{GetTickCount64()} clock which has a resolution of 15.6
ms. Patch by Victor Stinner.

@item 
gh-116773@footnote{https://github.com/python/cpython/issues/116773}: Fix instances of @code{<_overlapped.Overlapped object at 0xXXX>
still has pending operation at deallocation, the process may crash}.

@item 
gh-91227@footnote{https://github.com/python/cpython/issues/91227}: Fix the asyncio ProactorEventLoop implementation so that sending
a datagram to an address that is not listening does not prevent receiving
any more datagrams.

@item 
gh-115119@footnote{https://github.com/python/cpython/issues/115119}: Switched from vendored @code{libmpdecimal} code to a
separately-hosted external package in the @code{cpython-source-deps}
repository when building the @code{_decimal} module.
@end itemize

@node C API<17>,,Windows<16>,Python 3 13 0 alpha 6
@anchor{whatsnew/changelog id225}@anchor{19cd}
@subsubsection C API



@itemize -

@item 
gh-117642@footnote{https://github.com/python/cpython/issues/117642}: Fix 
@geindex Python Enhancement Proposals; PEP 737
PEP 737@footnote{https://peps.python.org/pep-0737/} implementation for @code{%#T} and @code{%#N}.

@item 
gh-87193@footnote{https://github.com/python/cpython/issues/87193}: @ref{19ce,,_PyBytes_Resize()} can now be called for bytes objects
with reference count > 1, including 1-byte bytes objects. It creates a new
bytes object and destroys the old one if it has reference count > 1.

@item 
gh-117021@footnote{https://github.com/python/cpython/issues/117021}: Fix integer overflow in @ref{19cf,,PyLong_AsPid()} on non-Windows
64-bit platforms.

@item 
gh-115756@footnote{https://github.com/python/cpython/issues/115756}: @code{PyCode_GetFirstFree()} is an ustable API now and has
been renamed to @ref{627,,PyUnstable_Code_GetFirstFree()}. (Contributed by
Bogdan Romanyuk in gh-115781@footnote{https://github.com/python/cpython/issues/115781})

@item 
gh-116869@footnote{https://github.com/python/cpython/issues/116869}: Add @code{test_cext} test: build a C extension to check if the
Python C API emits C compiler warnings. Patch by Victor Stinner.

@item 
gh-116869@footnote{https://github.com/python/cpython/issues/116869}: Make the C API compatible with
@code{-Werror=declaration-after-statement} compiler flag again. Patch by
Victor Stinner.

@item 
gh-116936@footnote{https://github.com/python/cpython/issues/116936}: Add @ref{635,,PyType_GetModuleByDef()} to the limited C API. Patch
by Victor Stinner.

@item 
gh-116809@footnote{https://github.com/python/cpython/issues/116809}: Restore removed private @code{_PyErr_ChainExceptions1()} function.
Patch by Victor Stinner.

@item 
gh-115754@footnote{https://github.com/python/cpython/issues/115754}: In the limited C API version 3.13, getting @code{Py_None},
@code{Py_False}, @code{Py_True}, @code{Py_Ellipsis} and @code{Py_NotImplemented}
singletons is now implemented as function calls at the stable ABI level to
hide implementation details. Getting these constants still return borrowed
references. Patch by Victor Stinner.

@item 
gh-115754@footnote{https://github.com/python/cpython/issues/115754}: Add @ref{5f9,,Py_GetConstant()} and
@ref{5fa,,Py_GetConstantBorrowed()} functions to get constants. For example,
@code{Py_GetConstant(Py_CONSTANT_ZERO)} returns a @ref{5e2,,strong reference} to
the constant zero. Patch by Victor Stinner.

@item 
gh-111696@footnote{https://github.com/python/cpython/issues/111696}: Add support for @code{%T}, @code{%T#}, @code{%N} and @code{%N#} formats to
@ref{62b,,PyUnicode_FromFormat()}: format the fully qualified name of an
object type and of a type: call @ref{618,,PyType_GetModuleName()}. See
@geindex Python Enhancement Proposals; PEP 737
PEP 737@footnote{https://peps.python.org/pep-0737/} for more information. Patch by Victor Stinner.

@item 
gh-111696@footnote{https://github.com/python/cpython/issues/111696}: Add @ref{618,,PyType_GetModuleName()} function to get the type's
module name. Equivalent to getting the @code{type.__module__} attribute.
Patch by Eric Snow and Victor Stinner.

@item 
gh-111696@footnote{https://github.com/python/cpython/issues/111696}: Add @ref{616,,PyType_GetFullyQualifiedName()} function to get the
type's fully qualified name. Equivalent to
@code{f"@{type.__module__@}.@{type.__qualname__@}"}, or @code{type.__qualname__} if
@code{type.__module__} is not a string or is equal to @code{"builtins"}. Patch
by Victor Stinner.

@item 
gh-85283@footnote{https://github.com/python/cpython/issues/85283}: The @code{fcntl}, @code{grp}, @code{pwd}, @code{termios}, @code{_statistics}
and @code{_testconsole} C extensions are now built with the @ref{637,,limited C API}. Patch by Victor Stinner.

@item 
gh-111140@footnote{https://github.com/python/cpython/issues/111140}: Add additional flags to @ref{606,,PyLong_AsNativeBytes()} and
@ref{607,,PyLong_FromNativeBytes()} to allow the caller to determine how to
handle edge cases around values that fill the entire buffer.

@item 
gh-113024@footnote{https://github.com/python/cpython/issues/113024}: Add @ref{60c,,PyObject_GenericHash()} function.
@end itemize

@node Python 3 13 0 alpha 5,Python 3 13 0 alpha 4,Python 3 13 0 alpha 6,変更履歴
@anchor{whatsnew/changelog python-3-13-0-alpha-5}@anchor{19d0}
@subsection Python 3.13.0 alpha 5


`Release date: 2024-03-12'

@menu
* セキュリティ: セキュリティ<18>. 
* Core and Builtins: Core and Builtins<53>. 
* ライブラリ: ライブラリ<58>. 
* Core and Builtins: Core and Builtins<54>. 
* ライブラリ: ライブラリ<59>. 
* Core and Builtins: Core and Builtins<55>. 
* ライブラリ: ライブラリ<60>. 
* ドキュメント: ドキュメント<17>. 
* テスト: テスト<15>. 
* ビルド: ビルド<18>. 
* Windows: Windows<17>. 
* macOS: macOS<10>. 
* IDLE: IDLE<9>. 
* Tools/Demos: Tools/Demos<16>. 
* C API: C API<18>. 

@end menu

@node セキュリティ<18>,Core and Builtins<53>,,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id226}@anchor{19d1}
@subsubsection セキュリティ



@itemize -

@item 
gh-115398@footnote{https://github.com/python/cpython/issues/115398}: Allow controlling Expat >=2.6.0 reparse deferral
(
@geindex Common Vulnerabilities and Exposures; CVE 2023-52425
CVE 2023-52425@footnote{https://www.cve.org/CVERecord?id=CVE-2023-52425}) by adding five new methods:


@itemize *

@item 
@ref{576,,xml.etree.ElementTree.XMLParser.flush()}

@item 
@ref{577,,xml.etree.ElementTree.XMLPullParser.flush()}

@item 
@ref{578,,xml.parsers.expat.xmlparser.GetReparseDeferralEnabled()}

@item 
@ref{579,,xml.parsers.expat.xmlparser.SetReparseDeferralEnabled()}

@item 
@code{xml.sax.expatreader.ExpatParser.flush()}
@end itemize

@item 
gh-114572@footnote{https://github.com/python/cpython/issues/114572}: @ref{11ae,,ssl.SSLContext.cert_store_stats()} and
@ref{11af,,ssl.SSLContext.get_ca_certs()} now correctly lock access to the
certificate store, when the @ref{357,,ssl.SSLContext} is shared across
multiple threads.
@end itemize

@node Core and Builtins<53>,ライブラリ<58>,セキュリティ<18>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id227}@anchor{19d2}
@subsubsection Core and Builtins



@itemize -

@item 
gh-116604@footnote{https://github.com/python/cpython/issues/116604}: Respect the status of the garbage collector when indirect calls
are made via @ref{693,,PyErr_CheckSignals()} and the evaluation breaker.
Patch by Pablo Galindo

@item 
gh-112087@footnote{https://github.com/python/cpython/issues/112087}: @ref{24d,,list} is now compatible with the implementation of
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}.

@item 
gh-116381@footnote{https://github.com/python/cpython/issues/116381}: Add specialization for @code{CONTAINS_OP}.

@item 
gh-116296@footnote{https://github.com/python/cpython/issues/116296}: Fix possible refleak in @code{object.__reduce__()} internal
error handling.

@item 
gh-115823@footnote{https://github.com/python/cpython/issues/115823}: Properly calculate error ranges in the parser when raising
@ref{18e,,SyntaxError} exceptions caused by invalid byte sequences. Patch by
Pablo Galindo

@item 
gh-115778@footnote{https://github.com/python/cpython/issues/115778}: Add @code{tierN} annotation for instruction definition in
interpreter DSL.

@item 
gh-115733@footnote{https://github.com/python/cpython/issues/115733}: Fix crash when calling @code{next()} on exhausted list iterators.

@item 
gh-115700@footnote{https://github.com/python/cpython/issues/115700}: The regen-cases build stage now works on Windows.

@item 
gh-115347@footnote{https://github.com/python/cpython/issues/115347}: Fix bug where docstring was replaced by a redundant NOP when
Python is run with @code{-OO}.

@item 
gh-115323@footnote{https://github.com/python/cpython/issues/115323}: Make error message more meaningful for when
@ref{1791,,bytearray.extend()} is called with a @ref{169,,str} object.

@item 
gh-112175@footnote{https://github.com/python/cpython/issues/112175}: Every @code{PyThreadState} now has its own @code{eval_breaker},
allowing specific threads to be interrupted.
@end itemize

@node ライブラリ<58>,Core and Builtins<54>,Core and Builtins<53>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id228}@anchor{19d3}
@subsubsection ライブラリ



@itemize -

@item 
gh-115154@footnote{https://github.com/python/cpython/issues/115154}: Fix a bug that was causing the @ref{18b3,,tokenize.untokenize()}
function to handle unicode named literals incorrectly. Patch by Pablo
Galindo
@end itemize

@node Core and Builtins<54>,ライブラリ<59>,ライブラリ<58>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id229}@anchor{19d4}
@subsubsection Core and Builtins



@itemize -

@item 
gh-112433@footnote{https://github.com/python/cpython/issues/112433}: Add ability to force alignment of @ref{1e5,,ctypes.Structure} by
way of the new @code{_align_} attribute on the class.
@end itemize

@node ライブラリ<59>,Core and Builtins<55>,Core and Builtins<54>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id230}@anchor{19d5}
@subsubsection ライブラリ



@itemize -

@item 
gh-104090@footnote{https://github.com/python/cpython/issues/104090}: The multiprocessing resource tracker now exits with non-zero
status code if a resource leak was detected. It still exits with status
code 0 otherwise.
@end itemize

@node Core and Builtins<55>,ライブラリ<60>,ライブラリ<59>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id231}@anchor{19d6}
@subsubsection Core and Builtins



@itemize -

@item 
gh-105858@footnote{https://github.com/python/cpython/issues/105858}: Improve the constructors for @ref{9,,ast} nodes. Arguments of
list types now default to an empty list if omitted, and optional fields
default to @code{None}. AST nodes now have an @code{__annotations__} attribute
with the expected types of their attributes. Passing unrecognized extra
arguments to AST nodes is deprecated and will become an error in Python
3.15. Omitting a required argument to an AST node is deprecated and will
become an error in Python 3.15. Patch by Jelle Zijlstra.

@item 
gh-101860@footnote{https://github.com/python/cpython/issues/101860}: Expose @code{__name__} attribute on property.

@item 
gh-96497@footnote{https://github.com/python/cpython/issues/96497}: Fix incorrect resolution of mangled class variables used in
assignment expressions in comprehensions.
@end itemize

@node ライブラリ<60>,ドキュメント<17>,Core and Builtins<55>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id232}@anchor{19d7}
@subsubsection ライブラリ



@itemize -

@item 
gh-116600@footnote{https://github.com/python/cpython/issues/116600}: Fix @ref{1c1,,repr()} for global @ref{835,,Flag} members.

@item 
gh-116349@footnote{https://github.com/python/cpython/issues/116349}: @ref{32c,,platform.java_ver()} is deprecated and will be removed in
3.15. It was largely untested, had a confusing API, and was only useful
for Jython support.

@item 
gh-116143@footnote{https://github.com/python/cpython/issues/116143}: Fix a race in pydoc @code{_start_server}, eliminating a window in
which @code{_start_server} can return a thread that is "serving" but without
a @code{docserver} set.

@item 
gh-116127@footnote{https://github.com/python/cpython/issues/116127}: @ref{10a,,typing}: implement 
@geindex Python Enhancement Proposals; PEP 705
PEP 705@footnote{https://peps.python.org/pep-0705/} which adds
@ref{48a,,typing.ReadOnly} support to @ref{332,,typing.TypedDict}.

@item 
gh-116325@footnote{https://github.com/python/cpython/issues/116325}: @ref{10a,,typing}: raise @ref{18e,,SyntaxError} instead of
@ref{5f0,,AttributeError} on forward references as empty strings.

@item 
gh-115957@footnote{https://github.com/python/cpython/issues/115957}: When @code{asyncio.TaskGroup.create_task} is called on an inactive
@code{asyncio.TaskGroup}, the given coroutine will be closed (which prevents
a @code{RuntimeWarning}).

@item 
gh-115978@footnote{https://github.com/python/cpython/issues/115978}: Disable preadv(), readv(), pwritev(), and writev() on WASI.

Under wasmtime for WASI 0.2, these functions don't pass test_posix
(@indicateurl{https://github.com/bytecodealliance/wasmtime/issues/7830}).

@item 
gh-88352@footnote{https://github.com/python/cpython/issues/88352}: Fix the computation of the next rollover time in the
@code{logging.TimedRotatingFileHandler} handler.
@code{computeRollover()} now always returns a timestamp larger than the
specified time and works correctly during the DST change.
@code{doRollover()} no longer overwrite the already rolled over file,
saving from data loss when run at midnight or during repeated time at the
DST change.

@item 
gh-87115@footnote{https://github.com/python/cpython/issues/87115}: Set @code{__main__.__spec__} to @code{None} when running a script with
@ref{aa,,pdb}

@item 
gh-76511@footnote{https://github.com/python/cpython/issues/76511}: Fix UnicodeEncodeError in @code{email.Message.as_string()} that
results when a message that claims to be in the ascii character set
actually has non-ascii characters. Non-ascii characters are now replaced
with the U+FFFD replacement character, like in the @code{replace} error
handler.

@item 
gh-89547@footnote{https://github.com/python/cpython/issues/89547}: Add support for nested typing special forms like
Final[ClassVar[int]].

@item 
gh-65824@footnote{https://github.com/python/cpython/issues/65824}: Improve the @code{less} prompt in @ref{ba,,pydoc}.

@item 
gh-116040@footnote{https://github.com/python/cpython/issues/116040}: [Enum] fix by-value calls when second value is falsey; e.g.
Cardinal(1, 0)

@item 
gh-115821@footnote{https://github.com/python/cpython/issues/115821}: [Enum] Improve error message when calling super().__new__() in
custom __new__.

@item 
gh-85644@footnote{https://github.com/python/cpython/issues/85644}: Use the @code{XDG_CURRENT_DESKTOP} environment variable in
@ref{11b,,webbrowser} to check desktop. Prefer it to the deprecated
@code{GNOME_DESKTOP_SESSION_ID} for GNOME detection.

@item 
gh-75988@footnote{https://github.com/python/cpython/issues/75988}: Fixed @ref{1934,,unittest.mock.create_autospec()} to pass the call
through to the wrapped object to return the real result.

@item 
gh-115881@footnote{https://github.com/python/cpython/issues/115881}: Fix issue where @ref{1c2,,ast.parse()} would incorrectly flag
conditional context managers (such as @code{with (x() if y else z()): ...})
as invalid syntax if @code{feature_version=(3, 8)} was passed. This reverts
changes to the grammar made as part of gh-94949@footnote{https://github.com/python/cpython/issues/94949}.

@item 
gh-115886@footnote{https://github.com/python/cpython/issues/115886}: Fix silent truncation of the name with an embedded null
character in @ref{19d8,,multiprocessing.shared_memory.SharedMemory}.

@item 
gh-115532@footnote{https://github.com/python/cpython/issues/115532}: Add kernel density estimation to the statistics module.

@item 
gh-115714@footnote{https://github.com/python/cpython/issues/115714}: On WASI, the @ref{f4,,time} module no longer get process time
using @code{times()} or @code{CLOCK_PROCESS_CPUTIME_ID}, system API is that is
unreliable and is likely to be removed from WASI. The affected clock
functions fall back to calling @code{clock()}.

@item 
gh-115809@footnote{https://github.com/python/cpython/issues/115809}: Improve algorithm for computing which rolled-over log files to
delete in @code{logging.TimedRotatingFileHandler}. It is now reliable
for handlers without @code{namer} and with arbitrary deterministic @code{namer}
that leaves the datetime part in the file name unmodified.

@item 
gh-74668@footnote{https://github.com/python/cpython/issues/74668}: @ref{110,,urllib.parse} functions @ref{31f,,parse_qs()} and
@ref{31e,,parse_qsl()} now support bytes arguments containing raw
and percent-encoded non-ASCII data.

@item 
gh-67044@footnote{https://github.com/python/cpython/issues/67044}: @ref{6af,,csv.writer()} now always quotes or escapes @code{'\r'} and
@code{'\n'}, regardless of `lineterminator' value.

@item 
gh-115712@footnote{https://github.com/python/cpython/issues/115712}: Restore support of space delimiter with
@code{skipinitialspace=True} in @ref{2d,,csv}. @ref{6af,,csv.writer()} now quotes
empty fields if delimiter is a space and skipinitialspace is true and
raises exception if quoting is not possible.

@item 
gh-112364@footnote{https://github.com/python/cpython/issues/112364}: Fixed @ref{ae2,,ast.unparse()} to handle format_spec with @code{"},
@code{'} or @code{\\}. Patched by Frank Hoffmann.

@item 
gh-112997@footnote{https://github.com/python/cpython/issues/112997}: Stop logging potentially sensitive callback arguments in
@ref{b,,asyncio} unless debug mode is active.

@item 
gh-114914@footnote{https://github.com/python/cpython/issues/114914}: Fix an issue where an abandoned @code{StreamWriter} would not
be garbage collected.

@item 
gh-111358@footnote{https://github.com/python/cpython/issues/111358}: Fix a bug in
@code{asyncio.BaseEventLoop.shutdown_default_executor()} to ensure the
timeout passed to the coroutine behaves as expected.

@item 
gh-115618@footnote{https://github.com/python/cpython/issues/115618}: Fix improper decreasing the reference count for @code{None}
argument in @ref{4b3,,property} methods @ref{19d9,,getter()},
@ref{19da,,setter()} and @ref{19db,,deleter()}.

@item 
gh-112720@footnote{https://github.com/python/cpython/issues/112720}: Refactor @code{dis.ArgResolver} to make it possible to
subclass and change the way jump args are interpreted.

@item 
gh-112006@footnote{https://github.com/python/cpython/issues/112006}: Fix @ref{115e,,inspect.unwrap()} for types with the @code{__wrapper__}
data descriptor. Fix @ref{942,,inspect.Signature.from_callable()} for builtins
@ref{48e,,classmethod()} and @ref{453,,staticmethod()}.

@item 
gh-101293@footnote{https://github.com/python/cpython/issues/101293}: Support callables with the @code{__call__()} method and types with
@code{__new__()} and @code{__init__()} methods set to class methods, static
methods, bound methods, partial functions, and other types of methods and
descriptors in @ref{942,,inspect.Signature.from_callable()}.

@item 
gh-103092@footnote{https://github.com/python/cpython/issues/103092}: Isolate @code{_lsprof} (apply 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}).

@item 
gh-113942@footnote{https://github.com/python/cpython/issues/113942}: @ref{ba,,pydoc} no longer skips global functions implemented as
builtin methods, such as @code{MethodDescriptorType} and
@code{WrapperDescriptorType}.

@item 
gh-115256@footnote{https://github.com/python/cpython/issues/115256}: Added DeprecationWarning when accessing the tarfile attribute
of TarInfo objects. The attribute is never used internally and is only
attached to TarInfos when the tarfile is opened in write-mode, not
read-mode. The attribute creates an unnecessary reference cycle which may
cause corruption when not closing the handle after writing a tarfile.

@item 
gh-115197@footnote{https://github.com/python/cpython/issues/115197}: @code{urllib.request} no longer resolves the hostname before
checking it against the system's proxy bypass list on macOS and Windows.

@item 
gh-113812@footnote{https://github.com/python/cpython/issues/113812}: @code{DatagramTransport.sendto()} will now send zero-length
datagrams if called with an empty bytes object. The transport flow control
also now accounts for the datagram header when calculating the buffer
size.

@item 
gh-114763@footnote{https://github.com/python/cpython/issues/114763}: Protect modules loaded with @ref{eab,,importlib.util.LazyLoader}
from race conditions when multiple threads try to access attributes before
the loading is complete.

@item 
gh-114709@footnote{https://github.com/python/cpython/issues/114709}: @code{posixpath.commonpath()} now raises a @ref{2ec,,ValueError}
exception when passed an empty iterable. Previously, @ref{174e,,IndexError} was
raised.

@code{posixpath.commonpath()} now raises a @ref{198,,TypeError} exception when
passed @code{None}. Previously, @ref{2ec,,ValueError} was raised.

@item 
gh-114610@footnote{https://github.com/python/cpython/issues/114610}: Fix bug where @ref{19dc,,pathlib.PurePath.with_stem()} converted a
non-empty path suffix to a stem when given an empty `stem' argument. It
now raises @ref{2ec,,ValueError}, just like
@ref{1956,,pathlib.PurePath.with_suffix()} does when called on a path with an
empty stem, given a non-empty `suffix' argument.

@item 
gh-107361@footnote{https://github.com/python/cpython/issues/107361}: Add @ref{481,,ssl.VERIFY_X509_PARTIAL_CHAIN} and
@code{VERIFY_X509_STRICT} to the default SSL context created with
@ref{480,,ssl.create_default_context()}.

@item 
gh-112281@footnote{https://github.com/python/cpython/issues/112281}: Allow creating @ref{9c5,,union of types} for
@ref{b37,,typing.Annotated} with unhashable metadata.

@item 
gh-111775@footnote{https://github.com/python/cpython/issues/111775}: Fix @code{importlib.resources.simple.ResourceHandle.open()} for
text mode, added missed @code{stream} argument.

@item 
gh-90095@footnote{https://github.com/python/cpython/issues/90095}: Make .pdbrc and -c work with any valid pdb commands.

@item 
gh-107625@footnote{https://github.com/python/cpython/issues/107625}: Raise @ref{729,,configparser.ParsingError} from
@ref{1681,,read()} and
@ref{72a,,read_file()} methods of
@ref{4de,,configparser.ConfigParser} if a key without a corresponding value
is continued (that is, followed by an indented line).

@item 
gh-107155@footnote{https://github.com/python/cpython/issues/107155}: Fix incorrect output of @code{help(x)} where @code{x} is a
@ref{14b5,,lambda} function, which has an @code{__annotations__} dictionary
attribute with a @code{"return"} key.

@item 
gh-57141@footnote{https://github.com/python/cpython/issues/57141}: Add option for `non-shallow' comparisons to
@ref{1142,,filecmp.dircmp} like @ref{19dd,,filecmp.cmp()}. Original patch by Steven
Ward. Enhanced by Tobias Rautenkranz

@item 
gh-69990@footnote{https://github.com/python/cpython/issues/69990}: @code{Profile.print_stats()} has been improved to accept multiple
sort arguments. Patched by Chiu-Hsiang Hsu and Furkan Onder.

@item 
gh-104061@footnote{https://github.com/python/cpython/issues/104061}: Add @code{socket.SO_BINDTOIFINDEX} constant.

@item 
gh-60346@footnote{https://github.com/python/cpython/issues/60346}: Fix ArgumentParser inconsistent with parse_known_args.

@item 
gh-102389@footnote{https://github.com/python/cpython/issues/102389}: Add @code{windows_31j} to aliases for @code{cp932} codec

@item 
gh-72249@footnote{https://github.com/python/cpython/issues/72249}: Always include the @ref{19de,,module} name in the @ref{1c1,,repr()} of
@ref{217,,functools.partial()} objects.  Patch by Furkan Onder and Anilyka
Barry.

@item 
gh-100985@footnote{https://github.com/python/cpython/issues/100985}: Update HTTPSConnection to consistently wrap IPv6 Addresses when
using a proxy.

@item 
gh-100884@footnote{https://github.com/python/cpython/issues/100884}: email: fix misfolding of comma in address-lists over multiple
lines in combination with unicode encoding.

@item 
gh-95782@footnote{https://github.com/python/cpython/issues/95782}: Fix @code{io.BufferedReader.tell()},
@code{io.BufferedReader.seek()}, @code{_pyio.BufferedReader.tell()},
@code{io.BufferedRandom.tell()}, @code{io.BufferedRandom.seek()} and
@code{_pyio.BufferedRandom.tell()} being able to return negative offsets.

@item 
gh-96310@footnote{https://github.com/python/cpython/issues/96310}: Fix a traceback in @ref{7,,argparse} when all options in a
mutually exclusive group are suppressed.

@item 
gh-93205@footnote{https://github.com/python/cpython/issues/93205}: Fixed a bug in
@ref{1163,,logging.handlers.TimedRotatingFileHandler} where multiple rotating
handler instances pointing to files with the same name but different
extensions would conflict and not delete the correct files.

@item 
bpo-31116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31116}: Add Z85 encoding to @code{base64}.

@item 
bpo-44865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44865}: Add missing call to localization function in @ref{7,,argparse}.

@item 
bpo-43952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43952}: Fix @ref{19df,,multiprocessing.connection.Listener.accept()} to
accept empty bytes as authkey. Not accepting empty bytes as key causes it
to hang indefinitely.

@item 
bpo-42125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42125}: linecache: get module name from @code{__spec__} if available. This
allows getting source code for the @code{__main__} module when a custom
loader is used.

@item 
bpo-41122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41122}: Failing to pass arguments properly to
@ref{be5,,functools.singledispatchmethod()} now throws a TypeError instead of
hitting an index out of bounds internally.

@item 
bpo-40818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40818}: The asyncio REPL now runs @ref{11ca,,sys.__interactivehook__} on
startup. The default implementation of @ref{11ca,,sys.__interactivehook__}
provides auto-completion to the asyncio REPL. Patch contributed by Rémi
Lapeyre.

@item 
bpo-33775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33775}: Add 'default' and 'version' help text for localization in
argparse.
@end itemize

@node ドキュメント<17>,テスト<15>,ライブラリ<60>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id233}@anchor{19e0}
@subsubsection ドキュメント



@itemize -

@item 
gh-115399@footnote{https://github.com/python/cpython/issues/115399}: Document 
@geindex Common Vulnerabilities and Exposures; CVE 2023-52425
CVE 2023-52425@footnote{https://www.cve.org/CVERecord?id=CVE-2023-52425} of Expat <2.6.0 under "XML
vulnerabilities".

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Improve import time of @ref{116,,uuid} on Linux.
@end itemize

@node テスト<15>,ビルド<18>,ドキュメント<17>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id234}@anchor{19e1}
@subsubsection テスト



@itemize -

@item 
gh-71052@footnote{https://github.com/python/cpython/issues/71052}: Add test exclusions to support running the test suite on
Android.

@item 
gh-71052@footnote{https://github.com/python/cpython/issues/71052}: Enable @code{test_concurrent_futures} on platforms that support
threading but not multiprocessing.

@item 
gh-115796@footnote{https://github.com/python/cpython/issues/115796}: Make '_testinternalcapi.assemble_code_object' construct the
exception table for the code object.

@item 
gh-115720@footnote{https://github.com/python/cpython/issues/115720}: Leak tests (@code{-R}, @code{--huntrleaks}) now show a summary of the
number of leaks found in each iteration.

@item 
gh-115122@footnote{https://github.com/python/cpython/issues/115122}: Add @code{--bisect} option to regrtest test runner: run failed
tests with @code{test.bisect_cmd} to identify failing tests. Patch by Victor
Stinner.

@item 
gh-115596@footnote{https://github.com/python/cpython/issues/115596}: Fix @code{ProgramPriorityTests} in @code{test_os} permanently
changing the process priority.

@item 
gh-115556@footnote{https://github.com/python/cpython/issues/115556}: On Windows, commas passed in arguments to
@code{Tools\buildbot\test.bat} and @code{PCbuild\\rt.bat} are now properly
handled.

@item 
gh-115420@footnote{https://github.com/python/cpython/issues/115420}: Fix translation of exception handler targets by
@code{_testinternalcapi.optimize_cfg}.

@item 
gh-115376@footnote{https://github.com/python/cpython/issues/115376}: Fix segfault in @code{_testinternalcapi.compiler_codegen} on bad
input.
@end itemize

@node ビルド<18>,Windows<17>,テスト<15>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id235}@anchor{19e2}
@subsubsection ビルド



@itemize -

@item 
gh-116313@footnote{https://github.com/python/cpython/issues/116313}: Get WASI builds to work under wasmtime 18 w/ WASI 0.2/preview2
primitives.

@item 
gh-71052@footnote{https://github.com/python/cpython/issues/71052}: Change Android's @ref{291,,sys.platform} from @code{"linux"} to
@code{"android"}.

@item 
gh-116117@footnote{https://github.com/python/cpython/issues/116117}: Backport @code{libb2}'s PR #42 to fix compiling CPython on 32-bit
Windows with @code{clang-cl}.

@item 
gh-71052@footnote{https://github.com/python/cpython/issues/71052}: Fix several Android build issues

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: A testbed project was added to run the test suite on iOS.

@item 
gh-115350@footnote{https://github.com/python/cpython/issues/115350}: Fix building ctypes module with -DWIN32_LEAN_AND_MEAN defined

@item 
gh-111225@footnote{https://github.com/python/cpython/issues/111225}: Link extension modules against libpython on Android.

@item 
gh-115737@footnote{https://github.com/python/cpython/issues/115737}: The install name for libPython is now correctly set for
non-framework macOS builds.

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: Makefile targets were added to support compiling an
iOS-compatible framework build.
@end itemize

@node Windows<17>,macOS<10>,ビルド<18>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id236}@anchor{19e3}
@subsubsection Windows



@itemize -

@item 
gh-116012@footnote{https://github.com/python/cpython/issues/116012}: Ensure the value of @code{GetLastError()} is preserved across GIL
operations.

@item 
gh-115582@footnote{https://github.com/python/cpython/issues/115582}: Building extensions intended for free-threaded builds of
CPython now require compiling with @code{/DPy_GIL_DISABLED} manually when
using a regular install. This is expected to change in future releases.

@item 
gh-115554@footnote{https://github.com/python/cpython/issues/115554}: The installer now has more strict rules about updating the
@ref{7da,,Python install manager}. In general, most users only have a single launcher
installed and will see no difference. When multiple launchers have been
installed, the option to install the launcher is disabled until all but
one have been removed. Downgrading the launcher (which was never allowed)
is now more obviously blocked.

@item 
gh-115543@footnote{https://github.com/python/cpython/issues/115543}: @ref{7da,,Python install manager} can now detect Python 3.13 when installed from
the Microsoft Store, and will install Python 3.12 by default when
@geindex PYLAUNCHER_ALLOW_INSTALL
@geindex 環境変数; PYLAUNCHER_ALLOW_INSTALL
@code{PYLAUNCHER_ALLOW_INSTALL} is set.
@end itemize

@node macOS<10>,IDLE<9>,Windows<17>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id237}@anchor{19e4}
@subsubsection macOS



@itemize -

@item 
gh-116145@footnote{https://github.com/python/cpython/issues/116145}: Update macOS installer to Tcl/Tk 8.6.14.
@end itemize

@node IDLE<9>,Tools/Demos<16>,macOS<10>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id238}@anchor{19e5}
@subsubsection IDLE



@itemize -

@item 
gh-88516@footnote{https://github.com/python/cpython/issues/88516}: On macOS show a proxy icon in the title bar of editor windows to
match platform behaviour.
@end itemize

@node Tools/Demos<16>,C API<18>,IDLE<9>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id239}@anchor{19e6}
@subsubsection Tools/Demos



@itemize -

@item 
gh-100176@footnote{https://github.com/python/cpython/issues/100176}: Remove outdated Tools/@{io,cc,string@}bench

@item 
bpo-45101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45101}: Add consistency in usage message IO between 2 versions of
python-config.
@end itemize

@node C API<18>,,Tools/Demos<16>,Python 3 13 0 alpha 5
@anchor{whatsnew/changelog id240}@anchor{19e7}
@subsubsection C API



@itemize -

@item 
gh-114626@footnote{https://github.com/python/cpython/issues/114626}: Add again @code{_PyCFunctionFastWithKeywords} name, removed in
Python 3.13 alpha 4 by mistake.  Keep the old private
@code{_PyCFunctionFastWithKeywords} name (Python 3.7) as an alias to the new
public name @code{PyCFunctionFastWithKeywords} (Python 3.13a4). Patch by
Victor Stinner.

@item 
gh-111418@footnote{https://github.com/python/cpython/issues/111418}: Add @ref{19e8,,PyHASH_MODULUS}, @ref{19e9,,PyHASH_BITS},
@ref{19ea,,PyHASH_INF} and @ref{19eb,,PyHASH_IMAG} C macros.  Patch by
Sergey B Kirpichev.
@end itemize

@node Python 3 13 0 alpha 4,Python 3 13 0 alpha 3,Python 3 13 0 alpha 5,変更履歴
@anchor{whatsnew/changelog python-3-13-0-alpha-4}@anchor{19ec}
@subsection Python 3.13.0 alpha 4


`Release date: 2024-02-15'

@menu
* セキュリティ: セキュリティ<19>. 
* Core and Builtins: Core and Builtins<56>. 
* ライブラリ: ライブラリ<61>. 
* ドキュメント: ドキュメント<18>. 
* テスト: テスト<16>. 
* ビルド: ビルド<19>. 
* Windows: Windows<18>. 
* macOS: macOS<11>. 
* IDLE: IDLE<10>. 
* Tools/Demos: Tools/Demos<17>. 
* C API: C API<19>. 

@end menu

@node セキュリティ<19>,Core and Builtins<56>,,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id241}@anchor{19ed}
@subsubsection セキュリティ



@itemize -

@item 
gh-115399@footnote{https://github.com/python/cpython/issues/115399}: Update bundled libexpat to 2.6.0

@item 
gh-115243@footnote{https://github.com/python/cpython/issues/115243}: Fix possible crashes in @ref{fd0,,collections.deque.index()} when
the deque is concurrently modified.
@end itemize

@node Core and Builtins<56>,ライブラリ<61>,セキュリティ<19>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id242}@anchor{19ee}
@subsubsection Core and Builtins



@itemize -

@item 
gh-112087@footnote{https://github.com/python/cpython/issues/112087}: For an empty reverse iterator for list will be reduced to
@ref{a65,,reversed()}. Patch by Donghee Na

@item 
gh-114570@footnote{https://github.com/python/cpython/issues/114570}: Add @ref{47a,,PythonFinalizationError} exception. This exception
derived from @ref{244,,RuntimeError} is raised when an operation is blocked
during the @ref{479,,Python finalization}. Patch by
Victor Stinner.

@item 
gh-114695@footnote{https://github.com/python/cpython/issues/114695}: Add @ref{364,,sys._clear_internal_caches()}, which clears all
internal performance-related caches (and deprecate the less-general
@ref{292,,sys._clear_type_cache()} function).

@item 
gh-114828@footnote{https://github.com/python/cpython/issues/114828}: Fix compilation crashes in uncommon code examples using
@ref{1a6,,super()} inside a comprehension in a class body.

@item 
gh-112069@footnote{https://github.com/python/cpython/issues/112069}: Adapt @ref{184,,set} and @ref{7f2,,frozenset} methods to Argument
Clinic.

@item 
gh-115011@footnote{https://github.com/python/cpython/issues/115011}: Setters for members with an unsigned integer type now support
the same range of valid values for objects that has a
@ref{19e,,__index__()} method as for @ref{19b,,int}.

@item 
gh-114887@footnote{https://github.com/python/cpython/issues/114887}: Changed socket type validation in
@ref{93c,,create_datagram_endpoint()} to accept all non-stream
sockets. This fixes a regression in compatibility with raw sockets.

@item 
gh-114944@footnote{https://github.com/python/cpython/issues/114944}: Fixes a race between @code{PyParkingLot_Park} and
@code{_PyParkingLot_UnparkAll}.

@item 
gh-113462@footnote{https://github.com/python/cpython/issues/113462}: Limit the number of versions that a single class can use.
Prevents a few wayward classes using up all the version numbers.

@item 
gh-76763@footnote{https://github.com/python/cpython/issues/76763}: The @ref{19ef,,chr()} builtin function now always raises
@ref{2ec,,ValueError} for values outside the valid range. Previously it raised
@ref{a81,,OverflowError} for very large or small values.

@item 
gh-114806@footnote{https://github.com/python/cpython/issues/114806}: No longer specialize calls to classes, if those classes have
metaclasses. Fixes bug where the @code{__call__} method of the metaclass was
not being called.

@item 
gh-107944@footnote{https://github.com/python/cpython/issues/107944}: Improve error message for function calls with bad keyword
arguments via getargs

@item 
gh-112529@footnote{https://github.com/python/cpython/issues/112529}: The free-threaded build no longer allocates space for the
@code{PyGC_Head} structure in objects that support cyclic garbage collection.
A number of other fields and data structures are used as replacements,
including @code{ob_gc_bits}, @code{ob_tid}, and mimalloc internal data
structures.

@item 
gh-114456@footnote{https://github.com/python/cpython/issues/114456}: Lower the recursion limit under a debug build of WASI.

@item 
gh-114083@footnote{https://github.com/python/cpython/issues/114083}: Compiler applies folding of LOAD_CONST with following
instruction in a separate pass before other optimisations. This enables
jump threading in certain circumstances.

@item 
gh-114388@footnote{https://github.com/python/cpython/issues/114388}: Fix a @ref{4d7,,RuntimeWarning} emitted when assign an integer-like
value that is not an instance of @ref{19b,,int} to an attribute that
corresponds to a C struct member of @ref{19f0,,type} T_UINT
and T_ULONG. Fix a double @ref{4d7,,RuntimeWarning} emitted when assign a
negative integer value to an attribute that corresponds to a C struct
member of type T_UINT.

@item 
gh-114265@footnote{https://github.com/python/cpython/issues/114265}: Compiler propagates line numbers before optimization, leading
to more optimization opportunities and removing the need for the
@code{guarantee_lineno_for_exits} hack.

@item 
gh-112529@footnote{https://github.com/python/cpython/issues/112529}: The free-threaded build now has its own thread-safe GC
implementation that uses mimalloc to find GC tracked objects. It is
non-generational, unlike the existing GC implementation.

@item 
gh-114050@footnote{https://github.com/python/cpython/issues/114050}: Fix segmentation fault caused by an incorrect format string in
@code{TypeError} exception when more than two arguments are passed to
@code{int}.

@item 
gh-112354@footnote{https://github.com/python/cpython/issues/112354}: The @code{END_FOR} instruction now pops only one value. This is to
better support side exits in loops.

@item 
gh-113884@footnote{https://github.com/python/cpython/issues/113884}: Make @ref{d61,,queue.SimpleQueue} thread safe when the GIL is
disabled.

@item 
gh-114058@footnote{https://github.com/python/cpython/issues/114058}: Implement the foundations of the Tier 2 redundancy eliminator.

@item 
gh-113939@footnote{https://github.com/python/cpython/issues/113939}: frame.clear(): Clear frame.f_locals as well, and not only the
fast locals. This is relevant once frame.f_locals was accessed, which
would contain also references to all the locals.

@item 
gh-112050@footnote{https://github.com/python/cpython/issues/112050}: Convert @ref{7f4,,collections.deque} to use Argument Clinic.

@item 
gh-112050@footnote{https://github.com/python/cpython/issues/112050}: Make methods on @ref{7f4,,collections.deque} thread-safe when the
GIL is disabled.

@item 
gh-113464@footnote{https://github.com/python/cpython/issues/113464}: Add an option (@code{--enable-experimental-jit} for
@code{configure}-based builds or @code{--experimental-jit} for @code{PCbuild}-based
ones) to build an `experimental' just-in-time compiler, based on
copy-and-patch@footnote{https://fredrikbk.com/publications/copy-and-patch.pdf}

@item 
gh-113055@footnote{https://github.com/python/cpython/issues/113055}: Make interp->obmalloc a pointer. For interpreters that share
state with the main interpreter, this points to the same static memory
structure. For interpreters with their own obmalloc state, it is heap
allocated. Add free_obmalloc_arenas() which will free the obmalloc arenas
and radix tree structures for interpreters with their own obmalloc state.

@item 
gh-55664@footnote{https://github.com/python/cpython/issues/55664}: Add warning when creating @ref{f44,,type} using a namespace
dictionary with non-string keys. Patched by Daniel Urban and Furkan Onder.

@item 
gh-104530@footnote{https://github.com/python/cpython/issues/104530}: Use native Win32 condition variables.
@end itemize

@node ライブラリ<61>,ドキュメント<18>,Core and Builtins<56>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id243}@anchor{19f1}
@subsubsection ライブラリ



@itemize -

@item 
gh-115392@footnote{https://github.com/python/cpython/issues/115392}: Fix a bug in @ref{3e,,doctest} where incorrect line numbers would
be reported for decorated functions.

@item 
gh-114563@footnote{https://github.com/python/cpython/issues/114563}: Fix several @ref{199,,format()} bugs when using the C implementation
of @ref{1fe,,Decimal}: * memory leak in some rare cases when using
the @code{z} format option (coerce negative 0) * incorrect output when
applying the @code{z} format option to type @code{F} (fixed-point with capital
@code{NAN} / @code{INF}) * incorrect output when applying the @code{#} format
option (alternate form)

@item 
gh-102840@footnote{https://github.com/python/cpython/issues/102840}: Fix confused traceback when floordiv, mod, or divmod operations
happens between instances of @ref{213,,fractions.Fraction} and
@ref{197,,complex}.

@item 
gh-115165@footnote{https://github.com/python/cpython/issues/115165}: Most exceptions are now ignored when attempting to set the
@code{__orig_class__} attribute on objects returned when calling
@ref{10a,,typing} generic aliases (including generic aliases created using
@ref{b37,,typing.Annotated}). Previously only @ref{5f0,,AttributeError} was
ignored. Patch by Dave Shawley.

@item 
gh-112903@footnote{https://github.com/python/cpython/issues/112903}: Fix "issubclass() arg 1 must be a class" errors in certain
cases of multiple inheritance with generic aliases (regression in early
3.13 alpha releases).

@item 
gh-115133@footnote{https://github.com/python/cpython/issues/115133}: Fix tests for @ref{11f5,,XMLPullParser}
with Expat 2.6.0.

@item 
gh-115059@footnote{https://github.com/python/cpython/issues/115059}: @code{io.BufferedRandom.read1()} now flushes the underlying
write buffer.

@item 
gh-79382@footnote{https://github.com/python/cpython/issues/79382}: Trailing @code{**} no longer allows to match files and non-existing
paths in recursive @ref{5a0,,glob()}.

@item 
gh-67837@footnote{https://github.com/python/cpython/issues/67837}: Avoid race conditions in the creation of directories during
concurrent extraction in @ref{e4,,tarfile} and @ref{137,,zipfile}.

@item 
gh-115060@footnote{https://github.com/python/cpython/issues/115060}: Speed up @ref{537,,pathlib.Path.glob()} by removing redundant regex
matching.

@item 
gh-97928@footnote{https://github.com/python/cpython/issues/97928}: Partially revert the behavior of @code{tkinter.Text.count()}. By
default it preserves the behavior of older Python versions, except that
setting @code{wantobjects} to 0 no longer has effect. Add a new parameter
`return_ints': specifying @code{return_ints=True} makes @code{Text.count()}
always returning the single count as an integer instead of a 1-tuple or
@code{None}.

@item 
gh-114628@footnote{https://github.com/python/cpython/issues/114628}: When csv.Error is raised when handling TypeError, do not print
the TypeError traceback.

@item 
gh-85984@footnote{https://github.com/python/cpython/issues/85984}: Added @code{_POSIX_VDISABLE} from C's @code{<unistd.h>} to
@ref{e7,,termios}.

@item 
gh-114965@footnote{https://github.com/python/cpython/issues/114965}: Update bundled pip to 24.0

@item 
gh-114959@footnote{https://github.com/python/cpython/issues/114959}: @ref{e4,,tarfile} no longer ignores errors when trying to extract
a directory on top of a file.

@item 
gh-114894@footnote{https://github.com/python/cpython/issues/114894}: Add @ref{4c0,,array.array.clear()}.

@item 
gh-114071@footnote{https://github.com/python/cpython/issues/114071}: Support tuple subclasses using auto() for enum member value.

@item 
gh-109475@footnote{https://github.com/python/cpython/issues/109475}: Fix support of explicit option value "--" in @ref{7,,argparse}
(e.g. @code{--option=--}).

@item 
gh-49766@footnote{https://github.com/python/cpython/issues/49766}: Fix @ref{1fa,,date}-@ref{4e2,,datetime}
comparison. Now the special comparison methods like @code{__eq__} and
@code{__lt__} return @ref{1a2,,NotImplemented} if one of comparands is
@code{date} and other is @code{datetime} instead of ignoring the
time part and the time zone or forcefully return "not equal" or raise
@ref{198,,TypeError}. It makes comparison of @code{date} and
@code{datetime} subclasses more symmetric and allows to change the
default behavior by overriding the special comparison methods in
subclasses.

@item 
gh-110190@footnote{https://github.com/python/cpython/issues/110190}: Fix ctypes structs with array on Windows ARM64 platform by
setting @code{MAX_STRUCT_SIZE} to 32 in stgdict. Patch by Diego Russo

@item 
gh-114678@footnote{https://github.com/python/cpython/issues/114678}: Ensure that deprecation warning for 'N' specifier in
@ref{1fe,,Decimal} format is not raised for cases where 'N' appears
in other places in the format specifier. Based on patch by Stefan Krah.

@item 
gh-70303@footnote{https://github.com/python/cpython/issues/70303}: Return both files and directories from @ref{537,,pathlib.Path.glob()}
if a pattern ends with "@code{**}". Previously only directories were
returned.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Improve import time of @ref{7e,,importlib.metadata} and
@ref{54,,email.utils}.

@item 
gh-113280@footnote{https://github.com/python/cpython/issues/113280}: Fix a leak of open socket in rare cases when error occurred in
@ref{ae7,,ssl.SSLSocket} creation.

@item 
gh-77749@footnote{https://github.com/python/cpython/issues/77749}: @ref{19f2,,email.policy.EmailPolicy.fold()} now always encodes
non-ASCII characters in headers if @ref{ff9,,utf8}
is false.

@item 
gh-83383@footnote{https://github.com/python/cpython/issues/83383}: Synchronization of the @ref{36,,dbm.dumb} database is now no-op if
there was no modification since opening or last synchronization. The
directory file for a newly created empty @ref{36,,dbm.dumb} database is now
created immediately after opening instead of deferring this until
synchronizing or closing.

@item 
gh-91602@footnote{https://github.com/python/cpython/issues/91602}: Add `filter' keyword-only parameter to
@ref{54f,,sqlite3.Connection.iterdump()} for filtering database objects to
dump. Patch by Mariusz Felisiak.

@item 
gh-112451@footnote{https://github.com/python/cpython/issues/112451}: Prohibit subclassing pure-Python @ref{12d5,,datetime.timezone}.
This is consistent with C-extension implementation. Patch by Mariusz
Felisiak.

@item 
gh-69893@footnote{https://github.com/python/cpython/issues/69893}: Add the @code{close()} method for the iterator returned by
@ref{57a,,xml.etree.ElementTree.iterparse()}.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Reduce the import time of @ref{f3,,threading} module by ~50%.
Patch by Daniel Hollas.

@item 
gh-114492@footnote{https://github.com/python/cpython/issues/114492}: Make the result of @ref{19f3,,termios.tcgetattr()} reproducible on
Alpine Linux. Previously it could leave a random garbage in some fields.

@item 
gh-114315@footnote{https://github.com/python/cpython/issues/114315}: Make @ref{19f4,,threading.Lock} a real class, not a factory
function. Add @code{__new__} to @code{_thread.lock} type.

@item 
gh-100414@footnote{https://github.com/python/cpython/issues/100414}: Add @ref{39,,dbm.sqlite3} as a backend to @ref{35,,dbm}, and make it
the new default @code{dbm} backend. Patch by Raymond Hettinger and Erlend
E. Aasland.

@item 
gh-113267@footnote{https://github.com/python/cpython/issues/113267}: Revert changes in gh-106584@footnote{https://github.com/python/cpython/issues/106584} which made calls of
@code{TestResult} methods @code{startTest()} and @code{stopTest()} unbalanced.

@item 
gh-75128@footnote{https://github.com/python/cpython/issues/75128}: Ignore an @ref{2c0,,OSError} in
@code{asyncio.BaseEventLoop.create_server()} when IPv6 is available but the
interface cannot actually support it.

@item 
gh-114423@footnote{https://github.com/python/cpython/issues/114423}: @code{_DummyThread} entries in @code{threading._active} are now
automatically removed when the related thread dies.

@item 
gh-114257@footnote{https://github.com/python/cpython/issues/114257}: Dismiss the @code{FileNotFound} error in
@ref{f45,,ctypes.util.find_library()} and just return @code{None} on Linux.

@item 
gh-114321@footnote{https://github.com/python/cpython/issues/114321}: Expose more platform specific constants in the @ref{5d,,fcntl}
module on Linux, macOS, FreeBSD and NetBSD.

@item 
gh-114328@footnote{https://github.com/python/cpython/issues/114328}: The @ref{19f5,,tty.setcbreak()} and new @ref{19f6,,tty.cfmakecbreak()} no
longer clears the terminal input ICRLF flag. This fixes a regression
introduced in 3.12 that no longer matched how OSes define cbreak mode in
their @code{stty(1)} manual pages.

@item 
gh-114281@footnote{https://github.com/python/cpython/issues/114281}: Remove type hints from @code{Lib/asyncio/staggered.py}. The
annotations in the typeshed@footnote{https://github.com/python/typeshed}
project should be used instead.

@item 
gh-101438@footnote{https://github.com/python/cpython/issues/101438}: Avoid reference cycle in ElementTree.iterparse. The iterator
returned by @code{ElementTree.iterparse} may hold on to a file descriptor.
The reference cycle prevented prompt clean-up of the file descriptor if
the returned iterator was not exhausted.

@item 
gh-114198@footnote{https://github.com/python/cpython/issues/114198}: The signature for the @code{__replace__} method on
@ref{33,,dataclasses} now has the first argument named @code{self}, rather than
@code{obj}.

@item 
gh-104522@footnote{https://github.com/python/cpython/issues/104522}: @ref{2c0,,OSError} raised when run a subprocess now only has
`filename' attribute set to `cwd' if the error was caused by a failed
attempt to change the current directory.

@item 
gh-114149@footnote{https://github.com/python/cpython/issues/114149}: Enum: correctly handle tuple subclasses in custom @code{__new__}.

@item 
gh-83648@footnote{https://github.com/python/cpython/issues/83648}: Support deprecation of options, positional arguments and
subcommands in @ref{7,,argparse}.

@item 
gh-114087@footnote{https://github.com/python/cpython/issues/114087}: Speed up @code{dataclasses.asdict} up to 1.35x.

@item 
gh-109534@footnote{https://github.com/python/cpython/issues/109534}: Fix a reference leak in
@code{asyncio.selector_events.BaseSelectorEventLoop} when SSL handshakes
fail. Patch contributed by Jamie Phan.

@item 
gh-79634@footnote{https://github.com/python/cpython/issues/79634}: Accept @ref{5a1,,path-like objects} as patterns
in @ref{537,,pathlib.Path.glob()} and @ref{538,,rglob()}.

@item 
gh-112202@footnote{https://github.com/python/cpython/issues/112202}: Ensure that a @ref{19f7,,asyncio.Condition.notify()} call does not
get lost if the awakened @code{Task} is simultaneously cancelled or
encounters any other error.

@item 
gh-113951@footnote{https://github.com/python/cpython/issues/113951}: Fix the behavior of @code{tag_unbind()} methods of
@code{tkinter.Text} and @code{tkinter.Canvas} classes with three
arguments. Previously, @code{widget.tag_unbind(tag, sequence, funcid)}
destroyed the current binding for `sequence', leaving `sequence' unbound,
and deleted the `funcid' command. Now it removes only `funcid' from the
binding for `sequence', keeping other commands, and deletes the `funcid'
command. It leaves `sequence' unbound only if `funcid' was the last bound
command.

@item 
gh-97959@footnote{https://github.com/python/cpython/issues/97959}: Fix rendering class methods, bound methods, method and function
aliases in @ref{ba,,pydoc}. Class methods no longer have "method of
builtins.type instance" note. Corresponding notes are now added for class
and unbound methods. Method and function aliases now have references to
the module or the class where the origin was defined if it differs from
the current. Bound methods are now listed in the static methods section.
Methods of builtin classes are now supported as well as methods of Python
classes.

@item 
gh-113796@footnote{https://github.com/python/cpython/issues/113796}: Add more validation checks in the @ref{1827,,csv.Dialect}
constructor. @ref{2ec,,ValueError} is now raised if the same character is used
in different roles.

@item 
gh-113732@footnote{https://github.com/python/cpython/issues/113732}: Fix support of @ref{6ac,,QUOTE_NOTNULL} and
@ref{6ad,,QUOTE_STRINGS} in @ref{6ae,,csv.reader()}.

@item 
gh-113225@footnote{https://github.com/python/cpython/issues/113225}: Speed up @ref{6cf,,pathlib.Path.walk()} by using
@ref{19f8,,os.DirEntry.path} where possible.

@item 
gh-89039@footnote{https://github.com/python/cpython/issues/89039}: When replace() method is called on a subclass of datetime, date
or time, properly call derived constructor. Previously, only the base
class's constructor was called.

Also, make sure to pass non-zero fold values when creating subclasses in
various methods. Previously, fold was silently ignored.

@item 
gh-112919@footnote{https://github.com/python/cpython/issues/112919}: Speed-up @ref{16e4,,datetime.datetime.replace()},
@ref{19f9,,datetime.date.replace()} and @ref{19fa,,datetime.time.replace()}.

@item 
gh-59013@footnote{https://github.com/python/cpython/issues/59013}: Set breakpoint on the first executable line of the function,
instead of the line of function definition when the user do @code{break func}
using @ref{aa,,pdb}

@item 
gh-112343@footnote{https://github.com/python/cpython/issues/112343}: Improve handling of pdb convenience variables to avoid
replacing string contents.

@item 
gh-112240@footnote{https://github.com/python/cpython/issues/112240}: Add option to calendar module CLI to specify the weekday to
start each week. Patch by Steven Ward.

@item 
gh-111741@footnote{https://github.com/python/cpython/issues/111741}: Recognise @code{image/webp} as a standard format in the
@ref{93,,mimetypes} module.

@item 
gh-43457@footnote{https://github.com/python/cpython/issues/43457}: Fix the @ref{f6,,tkinter} widget method @code{wm_attributes()}. It
now accepts the attribute name without the minus prefix to get window
attributes and allows to specify attributes and values to set as keyword
arguments. Add new optional keyword argument `return_python_dict': calling
@code{w.wm_attributes(return_python_dict=True)} returns the attributes as a
dict instead of a tuple. Calling @code{w.wm_attributes()} now returns a tuple
instead of string if `wantobjects' was set to 0.

@item 
gh-82626@footnote{https://github.com/python/cpython/issues/82626}: Many functions now emit a warning if a boolean value is passed
as a file descriptor argument.

@item 
gh-111051@footnote{https://github.com/python/cpython/issues/111051}: Added check for file modification during debugging with
@ref{aa,,pdb}

@item 
gh-110345@footnote{https://github.com/python/cpython/issues/110345}: Show the Tcl/Tk patchlevel (rather than version) in
@code{tkinter._test()}.

@item 
gh-38807@footnote{https://github.com/python/cpython/issues/38807}: Fix race condition in @ref{103,,trace}. Instead of checking if a
directory exists and creating it, directly call @ref{52c,,os.makedirs()} with
the kwarg @code{exist_ok=True}.

@item 
gh-75705@footnote{https://github.com/python/cpython/issues/75705}: Set unixfrom envelope in @ref{19fb,,mailbox.mbox} and
@ref{19fc,,mailbox.MMDF}.

@item 
gh-106233@footnote{https://github.com/python/cpython/issues/106233}: Fix stacklevel in @code{InvalidTZPathWarning} during
@ref{13a,,zoneinfo} module import.

@item 
gh-105102@footnote{https://github.com/python/cpython/issues/105102}: Allow @ref{1e6,,ctypes.Union} to be nested in
@ref{1e5,,ctypes.Structure} when the system endianness is the opposite of
the classes.

@item 
gh-104282@footnote{https://github.com/python/cpython/issues/104282}: Fix null pointer dereference in
@code{lzma._decode_filter_properties()} due to improper handling of BCJ
filters with properties of zero length. Patch by Radislav Chugunov.

@item 
gh-96471@footnote{https://github.com/python/cpython/issues/96471}: Add @ref{15ac,,queue.Queue} termination with
@ref{542,,shutdown()}.

@item 
gh-101599@footnote{https://github.com/python/cpython/issues/101599}: Changed argparse flag options formatting to remove redundancy.

@item 
gh-85984@footnote{https://github.com/python/cpython/issues/85984}: Add POSIX pseudo-terminal functions @ref{19fd,,os.posix_openpt()},
@ref{19fe,,os.grantpt()}, @ref{19ff,,os.unlockpt()}, and @ref{1a00,,os.ptsname()}.

@item 
gh-102512@footnote{https://github.com/python/cpython/issues/102512}: When @ref{4b5,,os.fork()} is called from a foreign thread (aka
@code{_DummyThread}), the type of the thread in a child process is changed to
@code{_MainThread}. Also changed its name and daemonic status, it can be now
joined.

@item 
gh-88569@footnote{https://github.com/python/cpython/issues/88569}: Add @ref{32b,,os.path.isreserved()}, which identifies reserved
pathnames such as "NUL", "AUX" and "CON". This function is only available
on Windows.

Deprecate @ref{32a,,pathlib.PurePath.is_reserved()}.

@item 
bpo-38364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38364}: The @code{inspect} functions @code{isgeneratorfunction},
@code{iscoroutinefunction}, @code{isasyncgenfunction} now support
@code{functools.partialmethod} wrapped functions the same way they support
@code{functools.partial}.
@end itemize

@node ドキュメント<18>,テスト<16>,ライブラリ<61>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id244}@anchor{1a01}
@subsubsection ドキュメント



@itemize -

@item 
gh-115233@footnote{https://github.com/python/cpython/issues/115233}: Fix an example for @ref{150d,,LoggerAdapter} in the
Logging Cookbook.

@item 
gh-114123@footnote{https://github.com/python/cpython/issues/114123}: Move the @ref{2d,,csv} module docstring to the @code{csv} module
instead of reexporting it from the internal @code{_csv} module, and
remove @code{__doc__} from @code{csv.__all__}.

Move @code{csv.__version__} to the @code{csv} module instead of
reexporting it from the internal @code{_csv} module, and remove
@code{__version__} from @code{csv.__all__}.
@end itemize

@node テスト<16>,ビルド<19>,ドキュメント<18>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id245}@anchor{1a02}
@subsubsection テスト



@itemize -

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: Added test exclusions required to run the test suite on iOS.

@item 
gh-105089@footnote{https://github.com/python/cpython/issues/105089}: Fix
@code{test.test_zipfile.test_core.TestWithDirectory.test_create_directory_with_write}
test in AIX by doing a bitwise AND of 0xFFFF on mode , so that it will be
in sync with @code{zinfo.external_attr}
@end itemize

@node ビルド<19>,Windows<18>,テスト<16>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id246}@anchor{1a03}
@subsubsection ビルド



@itemize -

@item 
gh-115167@footnote{https://github.com/python/cpython/issues/115167}: Avoid vendoring @code{vcruntime140_threads.dll} when building with
Visual Studio 2022 version 17.8.

@item 
gh-113632@footnote{https://github.com/python/cpython/issues/113632}: Promote WASI to a tier 2 platform and drop Emscripten from tier
3 in configure.ac.

@item 
gh-114099@footnote{https://github.com/python/cpython/issues/114099}: configure and Makefile were refactored to accommodate framework
builds on Apple platforms other than macOS.

@item 
gh-114875@footnote{https://github.com/python/cpython/issues/114875}: Add @code{getgrent()} as a prerequisite for building the
@ref{6a,,grp} module.
@end itemize

@node Windows<18>,macOS<11>,ビルド<19>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id247}@anchor{1a04}
@subsubsection Windows



@itemize -

@item 
gh-115049@footnote{https://github.com/python/cpython/issues/115049}: Fixes @code{py.exe} launcher failing when run as users without
user profiles.

@item 
gh-115009@footnote{https://github.com/python/cpython/issues/115009}: Update Windows installer to use SQLite 3.45.1.

@item 
gh-109991@footnote{https://github.com/python/cpython/issues/109991}: Update Windows build to use OpenSSL 3.0.13.

@item 
gh-111239@footnote{https://github.com/python/cpython/issues/111239}: Update Windows builds to use zlib v1.3.1.

@item 
gh-100107@footnote{https://github.com/python/cpython/issues/100107}: The @code{py.exe} launcher will no longer attempt to run the
Microsoft Store redirector when launching a script containing a
@code{/usr/bin/env} shebang

@item 
gh-112984@footnote{https://github.com/python/cpython/issues/112984}: Adds free-threaded binaries to Windows installer as an optional
component.

@item 
gh-89240@footnote{https://github.com/python/cpython/issues/89240}: Allows @ref{98,,multiprocessing} to create pools of greater than 62
processes.
@end itemize

@node macOS<11>,IDLE<10>,Windows<18>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id248}@anchor{1a05}
@subsubsection macOS



@itemize -

@item 
gh-115009@footnote{https://github.com/python/cpython/issues/115009}: Update macOS installer to use SQLite 3.45.1.

@item 
gh-109991@footnote{https://github.com/python/cpython/issues/109991}: Update macOS installer to use OpenSSL 3.0.13.

@item 
gh-114490@footnote{https://github.com/python/cpython/issues/114490}: Add Mach-O linkage support for @ref{1a06,,platform.architecture()}.

@item 
gh-87804@footnote{https://github.com/python/cpython/issues/87804}: On macOS the result of @code{os.statvfs} and @code{os.fstatvfs} now
correctly report the size of very large disks, in previous versions the
reported number of blocks was wrong for disks with at least 2**32 blocks.
@end itemize

@node IDLE<10>,Tools/Demos<17>,macOS<11>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id249}@anchor{1a07}
@subsubsection IDLE



@itemize -

@item 
gh-96905@footnote{https://github.com/python/cpython/issues/96905}: In idlelib code, stop redefining built-ins 'dict' and 'object'.

@item 
gh-103820@footnote{https://github.com/python/cpython/issues/103820}: Revise IDLE bindings so that events from mouse button 4/5 on
non-X11 windowing systems (i.e. Win32 and Aqua) are not mistaken for
scrolling.
@end itemize

@node Tools/Demos<17>,C API<19>,IDLE<10>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id250}@anchor{1a08}
@subsubsection Tools/Demos



@itemize -

@item 
gh-113516@footnote{https://github.com/python/cpython/issues/113516}: Don't set @code{LDSHARED} when building for WASI.

@item 
gh-109991@footnote{https://github.com/python/cpython/issues/109991}: Update GitHub CI workflows to use OpenSSL 3.0.13 and
multissltests to use 1.1.1w, 3.0.13, 3.1.5, and 3.2.1.

@item 
gh-115015@footnote{https://github.com/python/cpython/issues/115015}: Fix a bug in Argument Clinic that generated incorrect code for
methods with no parameters that use the @ref{1a09,,METH_METHOD | METH_FASTCALL | METH_KEYWORDS} calling
convention. Only the positional parameter count was checked; any keyword
argument passed would be silently accepted.
@end itemize

@node C API<19>,,Tools/Demos<17>,Python 3 13 0 alpha 4
@anchor{whatsnew/changelog id251}@anchor{1a0a}
@subsubsection C API



@itemize -

@item 
gh-111140@footnote{https://github.com/python/cpython/issues/111140}: Adds @ref{606,,PyLong_AsNativeBytes()},
@ref{607,,PyLong_FromNativeBytes()} and
@ref{608,,PyLong_FromUnsignedNativeBytes()} functions.

@item 
gh-114685@footnote{https://github.com/python/cpython/issues/114685}: @ref{964,,PyBuffer_FillInfo()} now raises a @ref{795,,SystemError} if
called with @ref{1a0b,,PyBUF_READ} or @ref{1a0c,,PyBUF_WRITE} as flags.
These flags should only be used with the @code{PyMemoryView_*} C API.

@item 
gh-114685@footnote{https://github.com/python/cpython/issues/114685}: @ref{63a,,PyObject_GetBuffer()} now raises a @ref{795,,SystemError} if
called with @ref{1a0b,,PyBUF_READ} or @ref{1a0c,,PyBUF_WRITE} as flags.
These flags should only be used with the @code{PyMemoryView_*} C API.

@item 
gh-114626@footnote{https://github.com/python/cpython/issues/114626}: Add @code{PyCFunctionFast} and @code{PyCFunctionFastWithKeywords}
typedefs (identical to the existing @code{_PyCFunctionFast} and
@code{_PyCFunctionFastWithKeywords} typedefs, just without a leading @code{_}
prefix).

@item 
gh-114329@footnote{https://github.com/python/cpython/issues/114329}: Add @ref{5fe,,PyList_GetItemRef()}, which is similar to
@ref{5ff,,PyList_GetItem()} but returns a @ref{5e2,,strong reference} instead of
a @ref{3d7,,borrowed reference}.

@item 
gh-110850@footnote{https://github.com/python/cpython/issues/110850}: Add PyTime C API:


@itemize *

@item 
@ref{5d3,,PyTime_t} type.

@item 
@ref{5d4,,PyTime_MIN} and @ref{5d5,,PyTime_MAX} constants.

@item 
@ref{5d6,,PyTime_AsSecondsDouble()},
@ref{5d7,,PyTime_Monotonic()}, @ref{5d9,,PyTime_PerfCounter()}, and
@ref{5db,,PyTime_Time()} functions.
@end itemize

Patch by Victor Stinner.

@item 
gh-112066@footnote{https://github.com/python/cpython/issues/112066}: Add @ref{5e3,,PyDict_SetDefaultRef()}: insert a key and value into
a dictionary if the key is not already present. This is similar to
@ref{1285,,dict.setdefault()}, but returns an integer value indicating if the
key was already present. It is also similar to
@ref{5e4,,PyDict_SetDefault()}, but returns a strong reference instead of a
borrowed reference.
@end itemize

@node Python 3 13 0 alpha 3,Python 3 13 0 alpha 2,Python 3 13 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-13-0-alpha-3}@anchor{1a0d}
@subsection Python 3.13.0 alpha 3


`Release date: 2024-01-17'

@menu
* セキュリティ: セキュリティ<20>. 
* Core and Builtins: Core and Builtins<57>. 
* ライブラリ: ライブラリ<62>. 
* ドキュメント: ドキュメント<19>. 
* テスト: テスト<17>. 
* ビルド: ビルド<20>. 
* Windows: Windows<19>. 
* macOS: macOS<12>. 
* IDLE: IDLE<11>. 
* C API: C API<20>. 

@end menu

@node セキュリティ<20>,Core and Builtins<57>,,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id252}@anchor{1a0e}
@subsubsection セキュリティ



@itemize -

@item 
gh-113659@footnote{https://github.com/python/cpython/issues/113659}: Skip @code{.pth} files with names starting with a dot or hidden
file attribute.

@item 
gh-112302@footnote{https://github.com/python/cpython/issues/112302}: Created a Software Bill-of-Materials document and tooling for
tracking dependencies.
@end itemize

@node Core and Builtins<57>,ライブラリ<62>,セキュリティ<20>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id253}@anchor{1a0f}
@subsubsection Core and Builtins



@itemize -

@item 
gh-107901@footnote{https://github.com/python/cpython/issues/107901}: Compiler duplicates basic blocks that have an eval breaker
check, no line number, and multiple predecessors.

@item 
gh-107901@footnote{https://github.com/python/cpython/issues/107901}: A jump leaving an exception handler back to normal code no
longer checks the eval breaker.

@item 
gh-113655@footnote{https://github.com/python/cpython/issues/113655}: Set the C recursion limit to 4000 on Windows, and 10000 on
Linux/OSX. This seems to be near the sweet spot to maintain safety, but
not compromise backwards compatibility.

@item 
gh-113710@footnote{https://github.com/python/cpython/issues/113710}: Add typed stack effects to the interpreter DSL, along with
various instruction annotations.

@item 
gh-77046@footnote{https://github.com/python/cpython/issues/77046}: On Windows, file descriptors wrapping Windows handles are now
created non inheritable by default (
@geindex Python Enhancement Proposals; PEP 446
PEP 446@footnote{https://peps.python.org/pep-0446/}). Patch by Zackery Spytz
and Victor Stinner.

@item 
gh-113853@footnote{https://github.com/python/cpython/issues/113853}: Guarantee that all executors make progress. This then
guarantees that tier 2 execution always makes progress.

@item 
gh-113753@footnote{https://github.com/python/cpython/issues/113753}: Fix an issue where the finalizer of @code{PyAsyncGenASend} objects
might not be called if they were allocated from a free list.

@item 
gh-107901@footnote{https://github.com/python/cpython/issues/107901}: Compiler changed so that synthetic jumps which are not at loop
end no longer check the eval breaker.

@item 
gh-113703@footnote{https://github.com/python/cpython/issues/113703}: Fix a regression in the @ref{1d,,codeop} module that was causing
it to incorrectly identify incomplete f-strings. Patch by Pablo Galindo

@item 
gh-89811@footnote{https://github.com/python/cpython/issues/89811}: Check for a valid @code{tp_version_tag} before performing bytecode
specializations that rely on this value being usable.

@item 
gh-111488@footnote{https://github.com/python/cpython/issues/111488}: Changed error message in case of no 'in' keyword after 'for' in
list comprehensions

@item 
gh-113657@footnote{https://github.com/python/cpython/issues/113657}: Fix an issue that caused important instruction pointer updates
to be optimized out of tier two traces.

@item 
gh-113603@footnote{https://github.com/python/cpython/issues/113603}: Fixed bug where a redundant NOP is not removed, causing an
assertion to fail in the compiler in debug mode.

@item 
gh-113602@footnote{https://github.com/python/cpython/issues/113602}: Fix an error that was causing the parser to try to overwrite
existing errors and crashing in the process. Patch by Pablo Galindo

@item 
gh-113486@footnote{https://github.com/python/cpython/issues/113486}: No longer issue spurious @code{PY_UNWIND} events for optimized
calls to classes.

@item 
gh-113297@footnote{https://github.com/python/cpython/issues/113297}: Fix segfault in the compiler on with statement with 19 context
managers.

@item 
gh-113212@footnote{https://github.com/python/cpython/issues/113212}: Improve @ref{1a6,,super} error messages.

@item 
gh-111375@footnote{https://github.com/python/cpython/issues/111375}: Only use @code{NULL} in the exception stack to indicate an
exception was handled. Patch by Carey Metcalfe.

@item 
gh-112215@footnote{https://github.com/python/cpython/issues/112215}: Increase the C recursion limit by a factor of 3 for non-debug
builds, except for webassembly and s390 platforms which are unchanged.
This mitigates some regressions in 3.12 with deep recursion mixing builtin
(C) and Python code.

@item 
gh-113054@footnote{https://github.com/python/cpython/issues/113054}: Fixed bug where a redundant NOP is not removed, causing an
assertion to fail in the compiler in debug mode.

@item 
gh-106905@footnote{https://github.com/python/cpython/issues/106905}: Use per AST-parser state rather than global state to track
recursion depth within the AST parser to prevent potential race condition
due to simultaneous parsing.

The issue primarily showed up in 3.11 by multithreaded users of
@ref{1c2,,ast.parse()}.  In 3.12 a change to when garbage collection can be
triggered prevented the race condition from occurring.

@item 
gh-108866@footnote{https://github.com/python/cpython/issues/108866}: Change the API and contract of @code{_PyExecutorObject} to return
the next_instr pointer, instead of the frame, and to always execute at
least one instruction.

@item 
gh-90350@footnote{https://github.com/python/cpython/issues/90350}: Optimize builtin functions @ref{110b,,min()} and @ref{110c,,max()}.

@item 
gh-112943@footnote{https://github.com/python/cpython/issues/112943}: Correctly compute end column offsets for multiline tokens in
the @ref{101,,tokenize} module. Patch by Pablo Galindo

@item 
gh-112125@footnote{https://github.com/python/cpython/issues/112125}: Fix @code{None.__ne__(None)} returning @code{NotImplemented} instead
of @code{False}.

@item 
gh-74616@footnote{https://github.com/python/cpython/issues/74616}: @ref{14f0,,input()} now raises a ValueError when output on the
terminal if the prompt contains embedded null characters instead of
silently truncating it.

@item 
gh-112716@footnote{https://github.com/python/cpython/issues/112716}: Fix SystemError in the @code{import} statement and in
@code{__reduce__()} methods of builtin types when @code{__builtins__} is not a
dict.

@item 
gh-112730@footnote{https://github.com/python/cpython/issues/112730}: Use color to highlight error locations in tracebacks. Patch by
Pablo Galindo

@item 
gh-112625@footnote{https://github.com/python/cpython/issues/112625}: Fixes a bug where a bytearray object could be cleared while
iterating over an argument in the @code{bytearray.join()} method that could
result in reading memory after it was freed.

@item 
gh-112660@footnote{https://github.com/python/cpython/issues/112660}: Do not clear unexpected errors during formatting error messages
for ImportError and AttributeError for modules.

@item 
gh-105967@footnote{https://github.com/python/cpython/issues/105967}: Workaround a bug in Apple's macOS platform zlib library where
@ref{1a10,,zlib.crc32()} and @ref{1a11,,binascii.crc32()} could produce incorrect
results on multi-gigabyte inputs. Including when using @ref{137,,zipfile} on
zips containing large data.

@item 
gh-95754@footnote{https://github.com/python/cpython/issues/95754}: Provide a better error message when accessing invalid attributes
on partially initialized modules. The origin of the module being accessed
is now included in the message to help with the common issue of shadowing
other modules.

@item 
gh-112217@footnote{https://github.com/python/cpython/issues/112217}: Add check for the type of @code{__cause__} returned from calling
the type @code{T} in @code{raise from T}.

@item 
gh-111058@footnote{https://github.com/python/cpython/issues/111058}: Change coro.cr_frame/gen.gi_frame to return @code{None} after the
coroutine/generator has been closed. This fixes a bug where
@ref{101a,,getcoroutinestate()} and @ref{144e,,getgeneratorstate()}
return the wrong state for a closed coroutine/generator.

@item 
gh-112388@footnote{https://github.com/python/cpython/issues/112388}: Fix an error that was causing the parser to try to overwrite
tokenizer errors. Patch by pablo Galindo

@item 
gh-112387@footnote{https://github.com/python/cpython/issues/112387}: Fix error positions for decoded strings with backwards tokenize
errors. Patch by Pablo Galindo

@item 
gh-99606@footnote{https://github.com/python/cpython/issues/99606}: Make code generated for an empty f-string identical to the code
of an empty normal string.

@item 
gh-112367@footnote{https://github.com/python/cpython/issues/112367}: Avoid undefined behaviour when using the perf trampolines by
not freeing the code arenas until shutdown. Patch by Pablo Galindo

@item 
gh-112320@footnote{https://github.com/python/cpython/issues/112320}: The Tier 2 translator now tracks the confidence level for
staying "on trace" (i.e. not exiting back to the Tier 1 interpreter) for
branch instructions based on the number of bits set in the branch
"counter". Trace translation ends when the confidence drops below 1/3rd.

@item 
gh-109598@footnote{https://github.com/python/cpython/issues/109598}:
@ref{1a12,,PyComplex_RealAsDouble()}/@ref{1a13,,PyComplex_ImagAsDouble()} now
tries to convert an object to a @ref{197,,complex} instance using its
@code{__complex__()} method before falling back to the @code{__float__()}
method. Patch by Sergey B Kirpichev.

@item 
gh-94606@footnote{https://github.com/python/cpython/issues/94606}: Fix UnicodeEncodeError when @code{email.message.get_payload()}
reads a message with a Unicode surrogate character and the message content
is not well-formed for surrogateescape encoding. Patch by Sidney
Markowitz.

@item 
bpo-21861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21861}: Use the object's actual class name in
@code{_io.FileIO.__repr__()}, @code{_io._WindowsConsoleIO()} and
@code{_io.TextIOWrapper.__repr__()}, to make these methods subclass
friendly.

@item 
bpo-45369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45369}: Remove LibreSSL workarounds as per 
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/}.

@item 
bpo-34392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34392}: Added @ref{559,,sys._is_interned()}.
@end itemize

@node ライブラリ<62>,ドキュメント<19>,Core and Builtins<57>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id254}@anchor{1a14}
@subsubsection ライブラリ



@itemize -

@item 
gh-114077@footnote{https://github.com/python/cpython/issues/114077}: Fix possible @ref{a81,,OverflowError} in
@ref{105d,,socket.socket.sendfile()} when pass `count' larger than 2 GiB on
32-bit platform.

@item 
gh-111803@footnote{https://github.com/python/cpython/issues/111803}: @ref{b0,,plistlib} now supports loading more deeply nested lists
in binary format.

@item 
gh-114014@footnote{https://github.com/python/cpython/issues/114014}: Fixed a bug in @ref{213,,fractions.Fraction} where an invalid
string using @code{d} in the decimals part creates a different error compared
to other invalid letters/characters. Patch by Jeremiah Gabriel Pascual.

@item 
gh-108364@footnote{https://github.com/python/cpython/issues/108364}: @ref{54f,,sqlite3.Connection.iterdump()} now ensures that foreign
key support is disabled before dumping the database schema, if there is
any foreign key violation. Patch by Erlend E. Aasland and Mariusz
Felisiak.

@item 
gh-113971@footnote{https://github.com/python/cpython/issues/113971}: The @ref{2cb,,zipfile.ZipInfo} previously protected
@code{._compresslevel} attribute has been made public as @code{.compress_level}
with the old @code{_compresslevel} name remaining available as a property to
retain compatibility.

@item 
gh-113877@footnote{https://github.com/python/cpython/issues/113877}: Fix @ref{f6,,tkinter} method @code{winfo_pathname()} on 64-bit
Windows.

@item 
gh-113868@footnote{https://github.com/python/cpython/issues/113868}: Added @ref{1a15,,mmap.MAP_NORESERVE}, @ref{1a16,,mmap.MAP_NOEXTEND},
@ref{1a17,,mmap.MAP_HASSEMAPHORE}, @ref{1a18,,mmap.MAP_NOCACHE},
@ref{1a19,,mmap.MAP_JIT}, @ref{1a1a,,mmap.MAP_RESILIENT_CODESIGN},
@ref{1a1b,,mmap.MAP_RESILIENT_MEDIA}, @ref{1a1c,,mmap.MAP_32BIT},
@ref{1a1d,,mmap.MAP_TRANSLATED_ALLOW_EXECUTE}, @ref{1a1e,,mmap.MAP_UNIX03} and
@ref{1a1f,,mmap.MAP_TPRO}. All of them are @code{mmap(2)} flags on macOS.

@item 
gh-113848@footnote{https://github.com/python/cpython/issues/113848}: @ref{4d1,,asyncio.TaskGroup()} and @ref{814,,asyncio.timeout()} context
managers now handle @ref{4d4,,CancelledError} subclasses as well as
exact @code{CancelledError}.

@item 
gh-113661@footnote{https://github.com/python/cpython/issues/113661}: unittest runner: Don't exit 5 if tests were skipped. The
intention of exiting 5 was to detect issues where the test suite wasn't
discovered at all. If we skipped tests, it was correctly discovered.

@item 
gh-96037@footnote{https://github.com/python/cpython/issues/96037}: Insert @ref{a36,,TimeoutError} in the context of the exception that
was raised during exiting an expired @ref{814,,asyncio.timeout()} block.

@item 
gh-113781@footnote{https://github.com/python/cpython/issues/113781}: Silence unraisable AttributeError when warnings are emitted
during Python finalization.

@item 
gh-113238@footnote{https://github.com/python/cpython/issues/113238}: Add @code{Anchor} to @code{importlib.resources} (in order for the
code to comply with the documentation)

@item 
gh-111693@footnote{https://github.com/python/cpython/issues/111693}: @ref{1a20,,asyncio.Condition.wait()} now re-raises the same
@code{CancelledError} instance that may have caused it to be interrupted.
Fixed race condition in @ref{1a21,,asyncio.Semaphore.acquire()} when interrupted
with a @code{CancelledError}.

@item 
gh-113791@footnote{https://github.com/python/cpython/issues/113791}: Add @code{CLOCK_MONOTONIC_RAW_APPROX} and
@code{CLOCK_UPTIME_RAW_APPROX} to @ref{f4,,time} on macOS. These are clocks
available on macOS 10.12 or later.

@item 
gh-112932@footnote{https://github.com/python/cpython/issues/112932}: Restore the ability for @ref{137,,zipfile} to @code{extractall} from
zip files with a "/" directory entry in them as is commonly added to zips
by some wiki or bug tracker data exporters.

@item 
gh-113568@footnote{https://github.com/python/cpython/issues/113568}: Raise deprecation warnings from @ref{6cd,,pathlib.PurePath} and
not its private base class @code{PurePathBase}.

@item 
gh-113594@footnote{https://github.com/python/cpython/issues/113594}: Fix @ref{887,,UnicodeEncodeError} in @ref{3f,,email} when re-fold
lines that contain unknown-8bit encoded part followed by non-unknown-8bit
encoded part.

@item 
gh-113538@footnote{https://github.com/python/cpython/issues/113538}: In @code{asyncio.StreamReaderProtocol.connection_made()}, there
is callback that logs an error if the task wrapping the "connected
callback" fails. This callback would itself fail if the task was
cancelled. Prevent this by checking whether the task was cancelled first.
If so, close the transport but don't log an error.

@item 
gh-113626@footnote{https://github.com/python/cpython/issues/113626}: Add support for the `allow_code' argument in the @ref{91,,marshal}
module. Passing @code{allow_code=False} prevents serialization and
de-serialization of code objects which is incompatible between Python
versions.

@item 
gh-85567@footnote{https://github.com/python/cpython/issues/85567}: Fix resource warnings for unclosed files in @ref{ab,,pickle} and
@ref{ac,,pickletools} command line interfaces.

@item 
gh-113537@footnote{https://github.com/python/cpython/issues/113537}: Support loads @code{str} in @ref{b49,,plistlib.loads()}.

@item 
gh-89850@footnote{https://github.com/python/cpython/issues/89850}: Add default implementations of
@ref{190c,,pickle.Pickler.persistent_id()} and
@ref{1914,,pickle.Unpickler.persistent_load()} methods in the C implementation.
Calling @code{super().persistent_id()} and @code{super().persistent_load()} in
subclasses of the C implementation of @ref{c13,,pickle.Pickler} and
@ref{1777,,pickle.Unpickler} classes no longer causes infinite recursion.

@item 
gh-113569@footnote{https://github.com/python/cpython/issues/113569}: Indicate if there were no actual calls in unittest
@ref{1a22,,assert_has_calls()} failure.

@item 
gh-101225@footnote{https://github.com/python/cpython/issues/101225}: Increase the backlog for
@ref{1a23,,multiprocessing.connection.Listener} objects created by
@code{multiprocessing.manager} and @code{multiprocessing.resource_sharer}
to significantly reduce the risk of getting a connection refused error
when creating a @ref{12f8,,multiprocessing.connection.Connection} to them.

@item 
gh-113568@footnote{https://github.com/python/cpython/issues/113568}: Raise audit events from @ref{266,,pathlib.Path} and not its
private base class @code{PathBase}.

@item 
gh-113543@footnote{https://github.com/python/cpython/issues/113543}: Make sure that @code{webbrowser.MacOSXOSAScript} sends
@code{webbrowser.open} audit event.

@item 
gh-113028@footnote{https://github.com/python/cpython/issues/113028}: When a second reference to a string appears in the input to
@ref{ab,,pickle}, and the Python implementation is in use, we are guaranteed
that a single copy gets pickled and a single object is shared when
reloaded. Previously, in protocol 0, when a string contained certain
characters (e.g. newline) it resulted in duplicate objects.

@item 
gh-113421@footnote{https://github.com/python/cpython/issues/113421}: Fix multiprocessing logger for @code{%(filename)s}.

@item 
gh-111784@footnote{https://github.com/python/cpython/issues/111784}: Fix segfaults in the @code{_elementtree} module. Fix first
segfault during deallocation of @code{_elementtree.XMLParser} instances by
keeping strong reference to @code{pyexpat} module in module state for capsule
lifetime. Fix second segfault which happens in the same deallocation
process  by keeping strong reference to @code{_elementtree} module in
@code{XMLParser} structure for @code{_elementtree} module lifetime.

@item 
gh-113407@footnote{https://github.com/python/cpython/issues/113407}: Fix import of @ref{10d,,unittest.mock} when CPython is built
without docstrings.

@item 
gh-113320@footnote{https://github.com/python/cpython/issues/113320}: Fix regression in Python 3.12 where @ref{56b,,Protocol}
classes that were not marked as @ref{675,,runtime-checkable} would be unnecessarily introspected,
potentially causing exceptions to be raised if the protocol had
problematic members. Patch by Alex Waygood.

@item 
gh-53502@footnote{https://github.com/python/cpython/issues/53502}: Add a new option @code{aware_datetime} in @ref{b0,,plistlib} to loads
or dumps aware datetime.

@item 
gh-113358@footnote{https://github.com/python/cpython/issues/113358}: Fix rendering tracebacks with exceptions with a broken
__getattr__

@item 
gh-113214@footnote{https://github.com/python/cpython/issues/113214}: Fix an @code{AttributeError} during asyncio SSL protocol aborts in
SSL-over-SSL scenarios.

@item 
gh-113246@footnote{https://github.com/python/cpython/issues/113246}: Update bundled pip to 23.3.2.

@item 
gh-87264@footnote{https://github.com/python/cpython/issues/87264}: Fixed tarfile list() method to show file type.

@item 
gh-112182@footnote{https://github.com/python/cpython/issues/112182}: @code{asyncio.futures.Future.set_exception()} now transforms
@ref{df5,,StopIteration} into @ref{244,,RuntimeError} instead of hanging or other
misbehavior. Patch contributed by Jamie Phan.

@item 
gh-113225@footnote{https://github.com/python/cpython/issues/113225}: Speed up @ref{537,,pathlib.Path.glob()} by using
@ref{19f8,,os.DirEntry.path} where possible.

@item 
gh-113149@footnote{https://github.com/python/cpython/issues/113149}: Improve error message when a JSON array or object contains a
trailing comma. Patch by Carson Radtke.

@item 
gh-113117@footnote{https://github.com/python/cpython/issues/113117}: The @ref{dc,,subprocess} module can now use the
@ref{52e,,os.posix_spawn()} function with @code{close_fds=True} on platforms where
@code{posix_spawn_file_actions_addclosefrom_np} is available. Patch by Jakub
Kulik.

@item 
gh-113199@footnote{https://github.com/python/cpython/issues/113199}: Make @code{http.client.HTTPResponse.read1} and
@code{http.client.HTTPResponse.readline} close IO after reading all data when
content length is known. Patch by Illia Volochii.

@item 
gh-113191@footnote{https://github.com/python/cpython/issues/113191}: Add support of @ref{52a,,os.fchmod()} and a file descriptor in
@ref{529,,os.chmod()} on Windows.

@item 
gh-113188@footnote{https://github.com/python/cpython/issues/113188}: Fix @ref{1a24,,shutil.copymode()} and @ref{1346,,shutil.copystat()} on
Windows. Previously they worked differently if `dst' is a symbolic link:
they modified the permission bits of `dst' itself rather than the file it
points to if `follow_symlinks' is true or `src' is not a symbolic link,
and did not modify the permission bits if `follow_symlinks' is false and
`src' is a symbolic link.

@item 
gh-113119@footnote{https://github.com/python/cpython/issues/113119}: @ref{52e,,os.posix_spawn()} now accepts @code{env=None}, which makes
the newly spawned process use the current process environment. Patch by
Jakub Kulik.

@item 
gh-113202@footnote{https://github.com/python/cpython/issues/113202}: Add a @code{strict} option to @code{batched()} in the @code{itertools}
module.

@item 
gh-61648@footnote{https://github.com/python/cpython/issues/61648}: Detect line numbers of properties in doctests.

@item 
gh-113175@footnote{https://github.com/python/cpython/issues/113175}: Sync with importlib_metadata 7.0, including improved type
annotations, fixed issue with symlinked packages in
@code{package_distributions}, added @code{EntryPoints.__repr__}, introduced the
@code{diagnose} script, added @code{Distribution.origin} property, and removed
deprecated @code{EntryPoint} access by numeric index (tuple behavior).

@item 
gh-59616@footnote{https://github.com/python/cpython/issues/59616}: Add support of @ref{528,,os.lchmod()} and the `follow_symlinks'
argument in @ref{529,,os.chmod()} on Windows. Note that the default value of
`follow_symlinks' in @code{os.lchmod()} is @code{False} on Windows.

@item 
gh-112559@footnote{https://github.com/python/cpython/issues/112559}: @ref{134c,,signal.signal()} and @ref{1a25,,signal.getsignal()} no longer
call @code{repr} on callable handlers. @ref{2f3,,asyncio.run()} and
@ref{194d,,asyncio.Runner.run()} no longer call @code{repr} on the task results.
Patch by Yilei Yang.

@item 
gh-112962@footnote{https://github.com/python/cpython/issues/112962}: @ref{3c,,dis} module functions add cache information to the
@ref{203,,Instruction} instance rather than creating fake
@ref{203,,Instruction} instances to represent the cache entries.

@item 
gh-112989@footnote{https://github.com/python/cpython/issues/112989}: Reduce overhead to connect sockets with @ref{b,,asyncio}
SelectorEventLoop.

@item 
gh-112970@footnote{https://github.com/python/cpython/issues/112970}: Use @code{closefrom()} on Linux where available (e.g.
glibc-2.34), rather than only FreeBSD.

@item 
gh-110190@footnote{https://github.com/python/cpython/issues/110190}: Fix ctypes structs with array on PPC64LE platform by setting
@code{MAX_STRUCT_SIZE} to 64 in stgdict. Patch by Diego Russo.

@item 
gh-112540@footnote{https://github.com/python/cpython/issues/112540}: The statistics.geometric_mean() function now returns zero for
datasets containing a zero.  Formerly, it would raise an exception.

@item 
gh-87286@footnote{https://github.com/python/cpython/issues/87286}: Added @code{LOG_FTP}, @code{LOG_NETINFO},
@code{LOG_REMOTEAUTH}, @code{LOG_INSTALL}, @code{LOG_RAS}, and
@code{LOG_LAUNCHD} tot the @ref{e2,,syslog} module, all of them constants
on used on macOS.

@item 
gh-112800@footnote{https://github.com/python/cpython/issues/112800}: Fix @ref{b,,asyncio} @code{SubprocessTransport.close()} not to throw
@code{PermissionError} when used with setuid executables.

@item 
gh-51944@footnote{https://github.com/python/cpython/issues/51944}: Add the following constants to the @ref{e7,,termios} module. These
values are present in macOS system headers: @code{ALTWERASE}, @code{B14400},
@code{B28800}, @code{B7200}, @code{B76800}, @code{CCAR_OFLOW}, @code{CCTS_OFLOW},
@code{CDSR_OFLOW}, @code{CDTR_IFLOW}, @code{CIGNORE}, @code{CRTS_IFLOW}, @code{EXTPROC},
@code{IUTF8}, @code{MDMBUF}, @code{NL2}, @code{NL3}, @code{NOKERNINFO}, @code{ONOEOT},
@code{OXTABS}, @code{VDSUSP}, @code{VSTATUS}.

@item 
gh-79325@footnote{https://github.com/python/cpython/issues/79325}: Fix an infinite recursion error in
@ref{144c,,tempfile.TemporaryDirectory()} cleanup on Windows.

@item 
gh-94692@footnote{https://github.com/python/cpython/issues/94692}: @ref{356,,shutil.rmtree()} now only catches OSError exceptions.
Previously a symlink attack resistant version of @code{shutil.rmtree()} could
ignore or pass to the error handler arbitrary exception when invalid
arguments were provided.

@item 
gh-112736@footnote{https://github.com/python/cpython/issues/112736}: The use of del-safe symbols in @code{subprocess} was refactored to
allow for use in cross-platform build environments.

@item 
gh-112727@footnote{https://github.com/python/cpython/issues/112727}: Speed up @ref{1a26,,pathlib.Path.absolute()}. Patch by Barney Gale.

@item 
gh-74690@footnote{https://github.com/python/cpython/issues/74690}: Speedup @ref{9c4,,issubclass()} checks against simple
@ref{675,,runtime-checkable protocols} by around
6%. Patch by Alex Waygood.

@item 
gh-74690@footnote{https://github.com/python/cpython/issues/74690}: Speedup @ref{2ad,,isinstance()} checks by roughly 20% for
@ref{675,,runtime-checkable protocols} that only
have one callable member. Speedup @ref{9c4,,issubclass()} checks for these
protocols by roughly 10%. Patch by Alex Waygood.

@item 
gh-112645@footnote{https://github.com/python/cpython/issues/112645}: Remove deprecation error on passing @code{onerror} to
@ref{356,,shutil.rmtree()}.

@item 
gh-112640@footnote{https://github.com/python/cpython/issues/112640}: Add @code{kwdefaults} parameter to @ref{a83,,types.FunctionType} to
set default keyword argument values.

@item 
gh-112622@footnote{https://github.com/python/cpython/issues/112622}: Ensure @code{name} parameter is passed to event loop in
@ref{1c9,,asyncio.create_task()}.

@item 
gh-112618@footnote{https://github.com/python/cpython/issues/112618}: Fix a caching bug relating to @ref{b37,,typing.Annotated}.
@code{Annotated[str, True]} is no longer identical to @code{Annotated[str, 1]}.

@item 
gh-112334@footnote{https://github.com/python/cpython/issues/112334}: Fixed a performance regression in 3.12's @ref{dc,,subprocess} on
Linux where it would no longer use the fast-path @code{vfork()} system call
when it could have due to a logic bug, instead falling back to the safe
but slower @code{fork()}.

Also fixed a second 3.12.0 potential security bug.  If a value of
@code{extra_groups=[]} was passed to @ref{4b7,,subprocess.Popen} or related APIs,
the underlying @code{setgroups(0, NULL)} system call to clear the groups list
would not be made in the child process prior to @code{exec()}.

This was identified via code inspection in the process of fixing the first
bug.

@item 
gh-110190@footnote{https://github.com/python/cpython/issues/110190}: Fix ctypes structs with array on Arm platform by setting
@code{MAX_STRUCT_SIZE} to 32 in stgdict. Patch by Diego Russo.

@item 
gh-81194@footnote{https://github.com/python/cpython/issues/81194}: Fix a crash in @ref{c24,,socket.if_indextoname()} with specific value
(UINT_MAX). Fix an integer overflow in @ref{c24,,socket.if_indextoname()} on
64-bit non-Windows platforms.

@item 
gh-112578@footnote{https://github.com/python/cpython/issues/112578}: Fix a spurious @ref{4d7,,RuntimeWarning} when executing the
@ref{137,,zipfile} module.

@item 
gh-112516@footnote{https://github.com/python/cpython/issues/112516}: Update the bundled copy of pip to version 23.3.1.

@item 
gh-112510@footnote{https://github.com/python/cpython/issues/112510}: Add @ref{1a27,,readline.backend} for the backend readline uses
(@code{editline} or @code{readline})

@item 
gh-112328@footnote{https://github.com/python/cpython/issues/112328}: [Enum] Make @code{EnumDict}, @code{EnumDict.member_names},
@code{EnumType._add_alias_} and @code{EnumType._add_value_alias_} public.

@item 
gh-112509@footnote{https://github.com/python/cpython/issues/112509}: Fix edge cases that could cause a key to be present in both the
@code{__required_keys__} and @code{__optional_keys__} attributes of a
@ref{332,,typing.TypedDict}. Patch by Jelle Zijlstra.

@item 
gh-101336@footnote{https://github.com/python/cpython/issues/101336}: Add @code{keep_alive} keyword parameter for
@code{AbstractEventLoop.create_server()} and
@code{BaseEventLoop.create_server()}.

@item 
gh-63284@footnote{https://github.com/python/cpython/issues/63284}: Added support for TLS-PSK (pre-shared key) mode to the
@ref{d5,,ssl} module.

@item 
gh-112414@footnote{https://github.com/python/cpython/issues/112414}: Fix regression in Python 3.12 where calling @ref{1c1,,repr()} on a
module that had been imported using a custom @ref{1a28,,loader} could fail
with @ref{5f0,,AttributeError}. Patch by Alex Waygood.

@item 
gh-112358@footnote{https://github.com/python/cpython/issues/112358}: Revert change to @ref{1778,,struct.Struct} initialization that
broke some cases of subclassing.

@item 
gh-112405@footnote{https://github.com/python/cpython/issues/112405}: Optimize @ref{2fd,,pathlib.PurePath.relative_to()}. Patch by Alex
Waygood.

@item 
gh-94722@footnote{https://github.com/python/cpython/issues/94722}: Fix bug where comparison between instances of
@ref{1a29,,DocTest} fails if one of them has @code{None} as its lineno.

@item 
gh-112361@footnote{https://github.com/python/cpython/issues/112361}: Speed up a small handful of @ref{a8,,pathlib} methods by removing
some temporary objects.

@item 
gh-112345@footnote{https://github.com/python/cpython/issues/112345}: Improve error message when trying to call @ref{9c4,,issubclass()}
against a @ref{56b,,typing.Protocol} that has non-method members. Patch by
Randolf Scholz.

@item 
gh-112137@footnote{https://github.com/python/cpython/issues/112137}: Change @ref{3c,,dis} output to display no-lineno as "--" instead
of "None".

@item 
gh-112332@footnote{https://github.com/python/cpython/issues/112332}: Deprecate the @code{exc_type} field of
@ref{563,,traceback.TracebackException}. Add @code{exc_type_str} to replace it.

@item 
gh-81620@footnote{https://github.com/python/cpython/issues/81620}: Add extra tests for @ref{6d7,,random.binomialvariate()}

@item 
gh-112292@footnote{https://github.com/python/cpython/issues/112292}: Fix a crash in @ref{bf,,readline} when imported from a sub
interpreter. Patch by Anthony Shaw

@item 
gh-77621@footnote{https://github.com/python/cpython/issues/77621}: Slightly improve the import time of the @ref{a8,,pathlib} module by
deferring some imports. Patch by Barney Gale.

@item 
gh-112137@footnote{https://github.com/python/cpython/issues/112137}: Change @ref{3c,,dis} output to display logical labels for jump
targets instead of offsets.

@item 
gh-112139@footnote{https://github.com/python/cpython/issues/112139}: Add @code{Signature.format()} to format signatures to string
with extra options. And use it in @ref{ba,,pydoc} to render more readable
signatures that have new lines between parameters.

@item 
gh-112105@footnote{https://github.com/python/cpython/issues/112105}: Make @ref{1a2a,,readline.set_completer_delims()} work with libedit

@item 
gh-106922@footnote{https://github.com/python/cpython/issues/106922}: Display multiple lines with @code{traceback} when errors span
multiple lines.

@item 
gh-111874@footnote{https://github.com/python/cpython/issues/111874}: When creating a @ref{331,,typing.NamedTuple} class, ensure
@ref{e48,,__set_name__()} is called on all objects that define
@code{__set_name__} and exist in the values of the @code{NamedTuple} class's
class dictionary. Patch by Alex Waygood.

@item 
gh-68166@footnote{https://github.com/python/cpython/issues/68166}: Add support of the "vsapi" element type in
@ref{55f,,tkinter.ttk.Style.element_create()}.

@item 
gh-110275@footnote{https://github.com/python/cpython/issues/110275}: Named tuple's methods @code{_replace()} and @code{__replace__()} now
raise TypeError instead of ValueError for invalid keyword arguments.

@item 
gh-99367@footnote{https://github.com/python/cpython/issues/99367}: Do not mangle @code{sys.path[0]} in @ref{aa,,pdb} if safe_path is set

@item 
gh-111615@footnote{https://github.com/python/cpython/issues/111615}: Fix a regression caused by a fix to gh-93162@footnote{https://github.com/python/cpython/issues/93162} whereby you
couldn't configure a @code{QueueHandler} without specifying handlers.

@item 
gh-75666@footnote{https://github.com/python/cpython/issues/75666}: Fix the behavior of @ref{f6,,tkinter} widget's @code{unbind()} method
with two arguments. Previously, @code{widget.unbind(sequence, funcid)}
destroyed the current binding for `sequence', leaving `sequence' unbound,
and deleted the `funcid' command. Now it removes only `funcid' from the
binding for `sequence', keeping other commands, and deletes the `funcid'
command. It leaves `sequence' unbound only if `funcid' was the last bound
command.

@item 
gh-67790@footnote{https://github.com/python/cpython/issues/67790}: Implement basic formatting support (minimum width, alignment,
fill) for @ref{213,,fractions.Fraction}.

@item 
gh-111049@footnote{https://github.com/python/cpython/issues/111049}: Fix crash during garbage collection of the @ref{10a4,,io.BytesIO}
buffer object.

@item 
gh-102980@footnote{https://github.com/python/cpython/issues/102980}: Redirect the output of @code{interact} command of @ref{aa,,pdb} to
the same channel as the debugger. Add tests and improve docs.

@item 
gh-102988@footnote{https://github.com/python/cpython/issues/102988}: @ref{4f3,,email.utils.getaddresses()} and
@ref{4f4,,email.utils.parseaddr()} now return @code{('@w{'}, '@w{'})} 2-tuples in more
situations where invalid email addresses are encountered instead of
potentially inaccurate values. Add optional `strict' parameter to these
two functions: use @code{strict=False} to get the old behavior, accept
malformed inputs. @code{getattr(email.utils, 'supports_strict_parsing',
False)} can be use to check if the `strict' parameter is available. Patch
by Thomas Dwyer and Victor Stinner to improve the 
@geindex Common Vulnerabilities and Exposures; CVE 2023-27043
CVE 2023-27043@footnote{https://www.cve.org/CVERecord?id=CVE-2023-27043} fix.

@item 
gh-52161@footnote{https://github.com/python/cpython/issues/52161}: @ref{1a2b,,cmd.Cmd.do_help()} now cleans docstrings with
@ref{1a2c,,inspect.cleandoc()} before writing them. Patch by Filip Łapkiewicz.

@item 
gh-82300@footnote{https://github.com/python/cpython/issues/82300}: Add @code{track} parameter to
@ref{19d8,,multiprocessing.shared_memory.SharedMemory} that allows using
shared memory blocks without having to register with the POSIX resource
tracker that automatically releases them upon process exit.

@item 
gh-110109@footnote{https://github.com/python/cpython/issues/110109}: Add private @code{pathlib._PurePathBase} class: a base class for
@ref{6cd,,pathlib.PurePath} that omits certain magic methods. It may be made
public (along with @code{_PathBase}) in future.

@item 
gh-109858@footnote{https://github.com/python/cpython/issues/109858}: Protect @ref{137,,zipfile} from "quoted-overlap" zipbomb. It now
raises BadZipFile when try to read an entry that overlaps with other entry
or central directory.

@item 
gh-109786@footnote{https://github.com/python/cpython/issues/109786}: Fix possible reference leaks and crash when re-enter the
@code{__next__()} method of @ref{a16,,itertools.pairwise}.

@item 
gh-91539@footnote{https://github.com/python/cpython/issues/91539}: Small (10 - 20%) and trivial performance improvement of
@code{urllib.request.getproxies_environment()}, typically useful when there
are many environment variables to go over.

@item 
gh-103363@footnote{https://github.com/python/cpython/issues/103363}: Add `follow_symlinks' keyword-only argument to
@ref{53b,,pathlib.Path.owner()} and @ref{53c,,group()}, defaulting to
@code{True}.

@item 
gh-102130@footnote{https://github.com/python/cpython/issues/102130}: Support tab completion in @ref{1a,,cmd} for @code{editline}.

@item 
gh-99437@footnote{https://github.com/python/cpython/issues/99437}: @ref{4a4,,runpy.run_path()} now decodes path-like objects, making
sure __file__ and sys.argv[0] of the module being run are always strings.

@item 
gh-104003@footnote{https://github.com/python/cpython/issues/104003}: Add @ref{489,,warnings.deprecated()}, a decorator to mark deprecated
functions to static type checkers and to warn on usage of deprecated
classes and functions. See 
@geindex Python Enhancement Proposals; PEP 702
PEP 702@footnote{https://peps.python.org/pep-0702/}. Patch by Jelle Zijlstra.

@item 
gh-103708@footnote{https://github.com/python/cpython/issues/103708}: Make hardcoded python name, a configurable parameter so that
different implementations of python can override it instead of making huge
diffs in sysconfig.py

@item 
gh-66515@footnote{https://github.com/python/cpython/issues/66515}: @ref{1a2d,,mailbox.MH} now supports folders that do not contain a
@code{.mh_sequences} file (e.g. Claws Mail IMAP-cache folders). Patch by
Serhiy Storchaka.

@item 
gh-83162@footnote{https://github.com/python/cpython/issues/83162}: Renamed @code{re.error} to @code{PatternError} for clarity, and
kept @code{re.error} for backward compatibility. Patch by Matthias
Bussonnier and Adam Chhina.

@item 
gh-91133@footnote{https://github.com/python/cpython/issues/91133}: Fix a bug in @ref{144c,,tempfile.TemporaryDirectory} cleanup, which
now no longer dereferences symlinks when working around file system
permission errors.

@item 
bpo-43153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43153}: On Windows, @code{tempfile.TemporaryDirectory} previously masked a
@code{PermissionError} with @code{NotADirectoryError} during directory cleanup.
It now correctly raises @code{PermissionError} if errors are not ignored.
Patch by Andrei Kulakov and Ken Jin.

@item 
bpo-32731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32731}: @ref{65a,,getpass.getuser()} now raises @ref{2c0,,OSError} for all
failures rather than @ref{65b,,ImportError} on systems lacking the @ref{b7,,pwd}
module or @ref{5e7,,KeyError} if the password database is empty.

@item 
bpo-34321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34321}: @ref{519,,mmap.mmap} now has a `trackfd' parameter on Unix; if it
is @code{False}, the file descriptor specified by `fileno' will not be
duplicated.

@item 
bpo-35332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35332}: The @ref{356,,shutil.rmtree()} function now ignores errors when
calling @ref{d6b,,os.close()} when `ignore_errors' is @code{True}, and
@ref{d6b,,os.close()} no longer retried after error.

@item 
bpo-35928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35928}: @ref{9be,,io.TextIOWrapper} now correctly handles the decoding
buffer after @code{read()} and @code{write()}.

@item 
bpo-26791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26791}: @ref{c51,,shutil.move()} now moves a symlink into a directory when
that directory is the target of the symlink.  This provides the same
behavior as the mv shell command.  The previous behavior raised an
exception.  Patch by Jeffrey Kintscher.

@item 
bpo-41422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41422}: Fixed memory leaks of @ref{c13,,pickle.Pickler} and
@ref{1777,,pickle.Unpickler} involving cyclic references via the internal
memo mapping.

@item 
bpo-19821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19821}: The @code{pydoc.ispackage()} function has been deprecated.

@item 
bpo-40262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40262}: The @code{ssl.SSLSocket.recv_into()} method no longer requires
the `buffer' argument to implement @code{__len__} and supports buffers with
arbitrary item size.

@item 
bpo-39912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39912}: @ref{16c2,,warnings.filterwarnings()} and
@ref{8d0,,warnings.simplefilter()} now raise appropriate exceptions instead of
@code{AssertionError}. Patch contributed by Rémi Lapeyre.

@item 
bpo-37260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37260}: Fixed a race condition in @ref{356,,shutil.rmtree()} in which
directory entries removed by another process or thread while
@code{shutil.rmtree()} is running can cause it to raise FileNotFoundError.
Patch by Jeffrey Kintscher.

@item 
bpo-36959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36959}: Fix some error messages for invalid ISO format string
combinations in @code{strptime()} that referred to directives not contained
in the format string. Patch by Gordon P. Hemsley.

@item 
bpo-18060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18060}: Fixed a class inheritance issue that can cause segfaults when
deriving two or more levels of subclasses from a base class of Structure
or Union.

@item 
bpo-29779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29779}: Add a new 
@geindex PYTHON_HISTORY
@geindex 環境変数; PYTHON_HISTORY
@ref{4b0,,PYTHON_HISTORY} environment variable to set
the location of a @code{.python_history} file.

@item 
bpo-21360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21360}: @ref{65e,,mailbox.Maildir} now ignores files with a leading dot.
@end itemize

@node ドキュメント<19>,テスト<17>,ライブラリ<62>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id255}@anchor{1a2e}
@subsubsection ドキュメント



@itemize -

@item 
gh-111699@footnote{https://github.com/python/cpython/issues/111699}: Relocate @code{smtpd} deprecation notice to its own section rather
than under @code{locale} in What's New in Python 3.12 document

@item 
gh-110746@footnote{https://github.com/python/cpython/issues/110746}: Improved markup for valid options/values for methods
ttk.treeview.column and ttk.treeview.heading, and for Layouts.

@item 
gh-95649@footnote{https://github.com/python/cpython/issues/95649}: Document that the @ref{b,,asyncio} module contains code taken from
v0.16.0 of the uvloop project@footnote{https://github.com/MagicStack/uvloop/tree/v0.16.0}, as well as the
required MIT licensing information.
@end itemize

@node テスト<17>,ビルド<20>,ドキュメント<19>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id256}@anchor{1a2f}
@subsubsection テスト



@itemize -

@item 
gh-111798@footnote{https://github.com/python/cpython/issues/111798}: Disable @code{test_super_deep()} from @code{test_call} under pydebug
builds on WASI; the stack depth is too small to make the test useful.

@item 
gh-111801@footnote{https://github.com/python/cpython/issues/111801}: Lower the recursion limit in @code{test_isinstance} for
@code{test_infinitely_many_bases()}. This prevents a stack overflow on a
pydebug build of WASI.

@item 
gh-111802@footnote{https://github.com/python/cpython/issues/111802}: Specify a low recursion depth for @code{test_bad_getattr()} in
@code{test.pickletester} to avoid exhausting the stack under a pydebug build
for WASI.

@item 
gh-44626@footnote{https://github.com/python/cpython/issues/44626}: Fix @ref{531,,os.path.isabs()} incorrectly returning @code{True} when
given a path that starts with exactly one (back)slash on Windows.

Fix @code{pathlib.PureWindowsPath.is_absolute()} incorrectly returning
@code{False} for some paths beginning with two (back)slashes.

@item 
gh-113633@footnote{https://github.com/python/cpython/issues/113633}: Use module state for the _testcapi extension module.

@item 
gh-109980@footnote{https://github.com/python/cpython/issues/109980}: Fix @code{test_tarfile_vs_tar} in @code{test_shutil} for macOS, where
system tar can include more information in the archive than
@ref{6da,,shutil.make_archive}.

@item 
gh-112769@footnote{https://github.com/python/cpython/issues/112769}: The tests now correctly compare zlib version when
@ref{1386,,zlib.ZLIB_RUNTIME_VERSION} contains non-integer suffixes. For
example zlib-ng defines the version as @code{1.3.0.zlib-ng}.

@item 
gh-112334@footnote{https://github.com/python/cpython/issues/112334}: Adds a regression test to verify that @code{vfork()} is used when
expected by @ref{dc,,subprocess} on vfork enabled POSIX systems (Linux).

@item 
gh-108927@footnote{https://github.com/python/cpython/issues/108927}: Fixed order dependence in running tests in the same process
when a test that has submodules (e.g. test_importlib) follows a test that
imports its submodule (e.g. test_importlib.util) and precedes a test (e.g.
test_unittest or test_compileall) that uses that submodule.

@item 
bpo-40648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40648}: Test modes that file can get with chmod() on Windows.
@end itemize

@node ビルド<20>,Windows<19>,テスト<17>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id257}@anchor{1a30}
@subsubsection ビルド



@itemize -

@item 
gh-114013@footnote{https://github.com/python/cpython/issues/114013}: Fix @code{Tools/wasm/wasi.py} to not include the path to
@code{python.wasm} as part of @code{HOSTRUNNER}. The environment variable is
meant to specify how to run the WASI host only, having @code{python.wasm} and
relevant flags appended to the @code{HOSTRUNNER}. This fixes @code{make test}
work.

@item 
gh-113258@footnote{https://github.com/python/cpython/issues/113258}: Changed the Windows build to write out generated frozen modules
into the build tree instead of the source tree.

@item 
gh-112305@footnote{https://github.com/python/cpython/issues/112305}: Fixed the @code{check-clean-src} step performed on out of tree
builds to detect errant @code{$(srcdir)/Python/frozen_modules/*.h} files and
recommend appropriate source tree cleanup steps to get a working build
again.

@item 
gh-112536@footnote{https://github.com/python/cpython/issues/112536}: Add support for thread sanitizer (TSAN)

@item 
gh-112867@footnote{https://github.com/python/cpython/issues/112867}: Fix the build for the case that WITH_PYMALLOC_RADIX_TREE=0 set.

@item 
gh-103065@footnote{https://github.com/python/cpython/issues/103065}: Introduce @code{Tools/wasm/wasi.py} to simplify doing a WASI
build.

@item 
bpo-11102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11102}: The @ref{195e,,os.major()}, @ref{1960,,os.makedev()}, and @ref{195f,,os.minor()}
functions are now available on HP-UX v3.

@item 
bpo-36351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36351}: Do not set ipv6type when cross-compiling.
@end itemize

@node Windows<19>,macOS<12>,ビルド<20>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id258}@anchor{1a31}
@subsubsection Windows



@itemize -

@item 
gh-114096@footnote{https://github.com/python/cpython/issues/114096}: Process privileges that are activated for creating directory
junctions are now restored afterwards, avoiding behaviour changes in other
parts of the program.

@item 
gh-111877@footnote{https://github.com/python/cpython/issues/111877}: @ref{26d,,os.stat()} calls were returning incorrect time values for
files that could not be accessed directly.

@item 
gh-111973@footnote{https://github.com/python/cpython/issues/111973}: Update Windows installer to use SQLite 3.44.2.

@item 
gh-113009@footnote{https://github.com/python/cpython/issues/113009}: @ref{98,,multiprocessing}: On Windows, fix a race condition in
@code{Process.terminate()}: no longer set the @code{returncode} attribute to
always call @code{WaitForSingleObject()} in @code{Process.wait()}.  Previously,
sometimes the process was still running after @code{TerminateProcess()} even
if @code{GetExitCodeProcess()} is not @code{STILL_ACTIVE}. Patch by Victor
Stinner.

@item 
gh-86179@footnote{https://github.com/python/cpython/issues/86179}: Fixes path calculations when launching Python on Windows through
a symlink.

@item 
gh-71383@footnote{https://github.com/python/cpython/issues/71383}: Update Tcl/Tk in Windows installer to 8.6.13 with a patch to
suppress incorrect ThemeChanged warnings.

@item 
gh-111650@footnote{https://github.com/python/cpython/issues/111650}: Ensures the @code{Py_GIL_DISABLED} preprocessor variable is
defined in @code{pyconfig.h} so that extension modules written in C are
able to use it.

@item 
gh-112278@footnote{https://github.com/python/cpython/issues/112278}: Reduce the time cost for some functions in @ref{af,,platform} on
Windows if current user has no permission to the WMI.

@item 
gh-73427@footnote{https://github.com/python/cpython/issues/73427}: Deprecate @ref{33e,,sys._enablelegacywindowsfsencoding()}. Use
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} instead. Patch by Inada Naoki.

@item 
gh-87868@footnote{https://github.com/python/cpython/issues/87868}: Correctly sort and remove duplicate environment variables in
@code{_winapi.CreateProcess()}.

@item 
bpo-37308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37308}: Fix mojibake in @ref{519,,mmap.mmap} when using a non-ASCII
`tagname' argument on Windows.
@end itemize

@node macOS<12>,IDLE<11>,Windows<19>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id259}@anchor{1a32}
@subsubsection macOS



@itemize -

@item 
gh-113666@footnote{https://github.com/python/cpython/issues/113666}: Add the following constants to module @ref{d6,,stat}:
@code{UF_SETTABLE}, @code{UF_TRACKED}, @code{UF_DATAVAULT}, @code{SF_SUPPORTED},
@code{SF_SETTABLE}, @code{SF_SYNTHETIC}, @code{SF_RESTRICTED}, @code{SF_FIRMLINK} and
@code{SF_DATALESS}. The values @code{UF_SETTABLE}, @code{SF_SUPPORTED},
@code{SF_SETTABLE} and @code{SF_SYNTHETIC} are only available on macOS.

@item 
gh-113536@footnote{https://github.com/python/cpython/issues/113536}: @ref{f99,,os.waitid()} is now available on macOS

@item 
gh-110459@footnote{https://github.com/python/cpython/issues/110459}: Running @code{configure ... --with-openssl-rpath=X/Y/Z} no longer
fails to detect OpenSSL on macOS.

@item 
gh-74573@footnote{https://github.com/python/cpython/issues/74573}: Document that @ref{38,,dbm.ndbm} can silently corrupt DBM files on
updates when exceeding undocumented platform limits, and can crash
(segmentation fault) when reading such a corrupted file. (FB8919203)

@item 
gh-65701@footnote{https://github.com/python/cpython/issues/65701}: The @code{freeze} tool doesn't work with framework builds of
Python. Document this and bail out early when running the tool with such a
build.

@item 
gh-87277@footnote{https://github.com/python/cpython/issues/87277}: webbrowser: Don't look for X11 browsers on macOS. Those are
generally not used and probing for them can result in starting XQuartz
even if it isn't used otherwise.

@item 
gh-111973@footnote{https://github.com/python/cpython/issues/111973}: Update macOS installer to use SQLite 3.44.2.

@item 
gh-108269@footnote{https://github.com/python/cpython/issues/108269}: Set @code{CFBundleAllowMixedLocalizations} to true in the
Info.plist for the framework, embedded Python.app and IDLE.app with
framework installs on macOS.  This allows applications to pick up the
user's preferred locale when that's different from english.

@item 
gh-102362@footnote{https://github.com/python/cpython/issues/102362}: Make sure the result of @code{sysconfig.get_plaform()} includes
at least a major and minor versions, even if @code{MACOSX_DEPLOYMENT_TARGET}
is set to only a major version during build to match the format expected
by pip.

@item 
gh-110017@footnote{https://github.com/python/cpython/issues/110017}: Disable a signal handling stress test on macOS due to a bug in
macOS (FB13453490).

@item 
gh-110820@footnote{https://github.com/python/cpython/issues/110820}: Make sure the preprocessor definitions for
@code{ALIGNOF_MAX_ALIGN_T}, @code{SIZEOF_LONG_DOUBLE} and
@code{HAVE_GCC_ASM_FOR_X64} are correct for Universal 2 builds on macOS.

@item 
gh-109981@footnote{https://github.com/python/cpython/issues/109981}: Use @code{/dev/fd} on macOS to determine the number of open files
in @code{test.support.os_helper.fd_count} to avoid a crash with "guarded"
file descriptors when probing for open files.
@end itemize

@node IDLE<11>,C API<20>,macOS<12>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id260}@anchor{1a33}
@subsubsection IDLE



@itemize -

@item 
gh-72284@footnote{https://github.com/python/cpython/issues/72284}: Improve the lists of features, editor key bindings, and shell
key bingings in the IDLE doc.

@item 
gh-113903@footnote{https://github.com/python/cpython/issues/113903}: Fix rare failure of test.test_idle, in test_configdialog.

@item 
gh-113729@footnote{https://github.com/python/cpython/issues/113729}: Fix the "Help -> IDLE Doc" menu bug in 3.11.7 and 3.12.1.

@item 
gh-113269@footnote{https://github.com/python/cpython/issues/113269}: Fix test_editor hang on macOS Catalina.

@item 
gh-112898@footnote{https://github.com/python/cpython/issues/112898}: Fix processing unsaved files when quitting IDLE on macOS.

@item 
bpo-13586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13586}: Enter the selected text when opening the "Replace" dialog.
@end itemize

@node C API<20>,,IDLE<11>,Python 3 13 0 alpha 3
@anchor{whatsnew/changelog id261}@anchor{1a34}
@subsubsection C API



@itemize -

@item 
gh-106560@footnote{https://github.com/python/cpython/issues/106560}: Fix redundant declarations in the public C API. Declare
PyBool_Type, PyLong_Type and PySys_Audit() only once. Patch by Victor
Stinner.

@item 
gh-112438@footnote{https://github.com/python/cpython/issues/112438}: Fix support of format units "es", "et", "es#", and "et#" in
nested tuples in @ref{3c1,,PyArg_ParseTuple()}-like functions.

@item 
gh-111545@footnote{https://github.com/python/cpython/issues/111545}: Add @ref{425,,Py_HashPointer()} function to hash a pointer. Patch
by Victor Stinner.

@item 
gh-65210@footnote{https://github.com/python/cpython/issues/65210}: Change the declaration of the `keywords' parameter of
@ref{624,,PyArg_ParseTupleAndKeywords()} and
@ref{625,,PyArg_VaParseTupleAndKeywords()} for better compatibility with C++.
@end itemize

@node Python 3 13 0 alpha 2,Python 3 13 0 alpha 1,Python 3 13 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-13-0-alpha-2}@anchor{1a35}
@subsection Python 3.13.0 alpha 2


`Release date: 2023-11-22'

@menu
* Core and Builtins: Core and Builtins<58>. 
* ライブラリ: ライブラリ<63>. 
* テスト: テスト<18>. 
* ビルド: ビルド<21>. 
* Windows: Windows<20>. 
* macOS: macOS<13>. 
* IDLE: IDLE<12>. 
* Tools/Demos: Tools/Demos<18>. 
* C API: C API<21>. 

@end menu

@node Core and Builtins<58>,ライブラリ<63>,,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id262}@anchor{1a36}
@subsubsection Core and Builtins



@itemize -

@item 
gh-112243@footnote{https://github.com/python/cpython/issues/112243}: Don't include comments in f-string debug expressions. Patch by
Pablo Galindo

@item 
gh-112287@footnote{https://github.com/python/cpython/issues/112287}: Slightly optimize the Tier 2 (uop) interpreter by only loading
@code{oparg} and @code{operand} when needed. Also double the trace size limit
again, to 512 this time.

@item 
gh-112266@footnote{https://github.com/python/cpython/issues/112266}: Change docstrings of @ref{77d,,__dict__} and
@code{__weakref__}.

@item 
gh-111807@footnote{https://github.com/python/cpython/issues/111807}: Lower the max parser stack depth to 1000 under WASI debug
builds.

@item 
gh-111798@footnote{https://github.com/python/cpython/issues/111798}: When Python is built in debug mode, set the C recursion limit
to 500 instead of 1500. A debug build is likely built with low
optimization level which implies higher stack memory usage than a release
build. Patch by Victor Stinner.

@item 
gh-106529@footnote{https://github.com/python/cpython/issues/106529}: Enable translating unspecialized @code{FOR_ITER} to Tier 2.

@item 
gh-111916@footnote{https://github.com/python/cpython/issues/111916}: Make hashlib related modules thread-safe without the GIL

@item 
gh-81137@footnote{https://github.com/python/cpython/issues/81137}: Deprecate assignment to a function's @code{__code__} field when the
new code object is of a mismatched type (e.g., from a generator to a plain
function).

@item 
gh-79932@footnote{https://github.com/python/cpython/issues/79932}: Raise exception if @ref{585,,frame.clear()} is called on a suspended
frame.

@item 
gh-81925@footnote{https://github.com/python/cpython/issues/81925}: Implement native thread ids for GNU KFreeBSD.

@item 
gh-111843@footnote{https://github.com/python/cpython/issues/111843}: Use exponential backoff to reduce the number of failed tier 2
optimization attempts by over 99%.

@item 
gh-110829@footnote{https://github.com/python/cpython/issues/110829}: Joining a thread now ensures the underlying OS thread has
exited. This is required for safer fork() in multi-threaded processes.

@item 
gh-109369@footnote{https://github.com/python/cpython/issues/109369}: Make sure that tier 2 traces are de-optimized if the code is
instrumented

@item 
gh-111772@footnote{https://github.com/python/cpython/issues/111772}: Specialize slot loads and stores for _Py_T_OBJECT as well as
Py_T_OBJECT_EX

@item 
gh-111666@footnote{https://github.com/python/cpython/issues/111666}: Speed up @ref{1a37,,BaseExceptionGroup.derive()},
@ref{1a38,,BaseExceptionGroup.subgroup()}, and @ref{18d8,,BaseExceptionGroup.split()}
by changing how they parse passed arguments.

@item 
gh-111654@footnote{https://github.com/python/cpython/issues/111654}: Fix runtime crash when some error happens in opcode
@code{LOAD_FROM_DICT_OR_DEREF}.

@item 
gh-111623@footnote{https://github.com/python/cpython/issues/111623}: Add support for sharing tuples between interpreters using the
cross-interpreter API.  Patch by Anthony Shaw.

@item 
gh-111354@footnote{https://github.com/python/cpython/issues/111354}: The oparg of @ref{5ba,,YIELD_VALUE} is now @code{1} if the
instruction is part of a yield-from or await, and @code{0} otherwise.

The SUSPENDED frame state is now split into @code{SUSPENDED} and
@code{SUSPENDED_YIELD_FROM}. This simplifies the code in @code{_PyGen_yf}.

@item 
gh-111520@footnote{https://github.com/python/cpython/issues/111520}: Merge the Tier 1 (bytecode) and Tier 2 (micro-ops) interpreters
together, moving the Tier 2 interpreter loop and switch into
@code{_PyEval_EvalFrameDefault()} in @code{Python/ceval.c}. The
@code{Python/executor.c} file is gone. Also the @code{TIER_ONE} and @code{TIER_TWO}
macros are now handled by the code generator.

`Beware!' This changes the environment variables to enable micro-ops and
their debugging to @code{PYTHON_UOPS} and @code{PYTHON_LLTRACE}.

@item 
gh-109181@footnote{https://github.com/python/cpython/issues/109181}: Speed up @code{Traceback} object creation by lazily compute
the line number. Patch by Pablo Galindo

@item 
gh-111420@footnote{https://github.com/python/cpython/issues/111420}: Allow type comments in parenthesized @code{with} statements

@item 
gh-111438@footnote{https://github.com/python/cpython/issues/111438}: Add support for sharing floats between interpreters using the
cross-interpreter API.  Patch by Anthony Shaw.

@item 
gh-111435@footnote{https://github.com/python/cpython/issues/111435}: Add support for sharing of @code{True} and @code{False} between
interpreters using the cross-interpreter API.  Patch by Anthony Shaw.

@item 
gh-102388@footnote{https://github.com/python/cpython/issues/102388}: Fix a bug where @code{iso2022_jp_3} and @code{iso2022_jp_2004} codecs
read out of bounds

@item 
gh-111366@footnote{https://github.com/python/cpython/issues/111366}: Fix an issue in the @ref{1d,,codeop} that was causing
@ref{18e,,SyntaxError} exceptions raised in the presence of invalid syntax to
not contain precise error messages. Patch by Pablo Galindo

@item 
gh-111380@footnote{https://github.com/python/cpython/issues/111380}: Fix a bug that was causing @ref{1ae,,SyntaxWarning} to appear twice
when parsing if invalid syntax is encountered later. Patch by Pablo
galindo

@item 
gh-111374@footnote{https://github.com/python/cpython/issues/111374}: Added a new environment variable
@geindex PYTHON_FROZEN_MODULES
@geindex 環境変数; PYTHON_FROZEN_MODULES
@ref{4ad,,PYTHON_FROZEN_MODULES}. It determines whether or not frozen
modules are ignored by the import machinery, equivalent of the @ref{16f,,-X frozen_modules} command-line option.

@item 
gh-111354@footnote{https://github.com/python/cpython/issues/111354}: Remove @code{oparg} from @ref{5ba,,YIELD_VALUE}. Change @code{oparg}
of @ref{5bb,,RESUME} to include information about the except-depth. These
changes make it possible to simplify the code in generator close.

@item 
gh-94438@footnote{https://github.com/python/cpython/issues/94438}: Fix a regression that prevented jumping across @code{is None} and
@code{is not None} when debugging. Patch by Savannah Ostrowski.

@item 
gh-67224@footnote{https://github.com/python/cpython/issues/67224}: Show source lines in tracebacks when using the @code{-c} option
when running Python. Patch by Pablo Galindo

@item 
gh-111123@footnote{https://github.com/python/cpython/issues/111123}: Fix a bug where a @ref{4ac,,global} declaration in an
@ref{1ab,,except} block is rejected when the global is used in the
@ref{17c,,else} block.

@item 
gh-110938@footnote{https://github.com/python/cpython/issues/110938}: Fix error messages for indented blocks with functions and
classes with generic type parameters. Patch by Pablo Galindo

@item 
gh-109214@footnote{https://github.com/python/cpython/issues/109214}: Remove unnecessary instruction pointer updates before returning
from frames.

@item 
gh-110912@footnote{https://github.com/python/cpython/issues/110912}: Correctly display the traceback for @ref{179e,,MemoryError}
exceptions using the @ref{104,,traceback} module. Patch by Pablo Galindo

@item 
gh-109894@footnote{https://github.com/python/cpython/issues/109894}: Fixed crash due to improperly initialized static
@ref{179e,,MemoryError} in subinterpreter.

@item 
gh-110892@footnote{https://github.com/python/cpython/issues/110892}: Return @code{NULL} for @code{PyTrace_RETURN} events caused by an
exception

@item 
gh-110864@footnote{https://github.com/python/cpython/issues/110864}: Fix argument parsing by @code{_PyArg_UnpackKeywordsWithVararg} for
functions defining pos-or-keyword, vararg, and kw-only parameters.

@item 
gh-109094@footnote{https://github.com/python/cpython/issues/109094}: Replace @code{prev_instr} on the interpreter frame by
@code{instr_ptr} which points to the beginning of the instruction that is
currently executing (or will execute once the frame resumes).

@item 
gh-110805@footnote{https://github.com/python/cpython/issues/110805}: Allow the repl to show source code and complete tracebacks.
Patch by Pablo Galindo

@item 
gh-110722@footnote{https://github.com/python/cpython/issues/110722}: Add 
@geindex PYTHON_PRESITE=package.module
@geindex 環境変数; PYTHON_PRESITE=package.module
@code{PYTHON_PRESITE=package.module} to import a module
early in the interpreter lifecycle before @code{site.py} is executed.  Python
needs to be @ref{509,,built in debug mode} for this option to
exist.

@item 
gh-110481@footnote{https://github.com/python/cpython/issues/110481}: Implement biased reference counting in @code{--disable-gil}
builds.

@item 
gh-110543@footnote{https://github.com/python/cpython/issues/110543}: Fix regression in Python 3.12 where
@code{types.CodeType.replace()} would produce a broken code object if
called on a module or class code object that contains a comprehension.
Patch by Jelle Zijlstra.

@item 
gh-89519@footnote{https://github.com/python/cpython/issues/89519}: Removed chained @ref{48e,,classmethod} descriptors (introduced in
bpo-19072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19072}).  This can no longer be used to wrap other descriptors
such as @ref{4b3,,property}.  The core design of this feature was flawed and
caused a number of downstream problems.  To "pass-through" a
@ref{48e,,classmethod}, consider using the @code{__wrapped__} attribute
that was added in Python 3.10.

@item 
gh-103615@footnote{https://github.com/python/cpython/issues/103615}: Use local events for opcode tracing

@item 
bpo-46657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46657}: Add mimalloc memory allocator support.

@item 
gh-106718@footnote{https://github.com/python/cpython/issues/106718}: When PyConfig.stdlib_dir is explicitly set, it's now respected
and won't be overridden by PyConfig.home.

@item 
gh-106905@footnote{https://github.com/python/cpython/issues/106905}: Fix incorrect SystemError about AST constructor recursion depth
mismatch.

@item 
gh-100445@footnote{https://github.com/python/cpython/issues/100445}: Improve error message for unterminated strings with escapes.

@item 
bpo-45759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45759}: Improved error messages for @code{elif}/@code{else} statements not
matching any valid statements. Patch by Jeremiah Vivian.
@end itemize

@node ライブラリ<63>,テスト<18>,Core and Builtins<58>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id263}@anchor{1a39}
@subsubsection ライブラリ



@itemize -

@item 
gh-111942@footnote{https://github.com/python/cpython/issues/111942}: Fix SystemError in the TextIOWrapper constructor with
non-encodable "errors" argument in non-debug mode.

@item 
gh-111995@footnote{https://github.com/python/cpython/issues/111995}: Added the @code{NI_IDN} constant to the @ref{d1,,socket} module when
present in C at build time for use with @ref{1a3a,,socket.getnameinfo()}.

@item 
gh-109538@footnote{https://github.com/python/cpython/issues/109538}: Issue warning message instead of having @ref{244,,RuntimeError}
be displayed when event loop has already been closed at
@code{StreamWriter.__del__()}.

@item 
gh-111942@footnote{https://github.com/python/cpython/issues/111942}: Fix crashes in @ref{d40,,io.TextIOWrapper.reconfigure()} when pass
invalid arguments, e.g. non-string encoding.

@item 
gh-111460@footnote{https://github.com/python/cpython/issues/111460}: @ref{2f,,curses}: restore wide character support (including
@ref{12aa,,curses.unget_wch()} and @ref{12a9,,get_wch()}) on macOS,
which was unavailable due to a regression in Python 3.12.

@item 
gh-103791@footnote{https://github.com/python/cpython/issues/103791}: @ref{1129,,contextlib.suppress} now supports suppressing
exceptions raised as part of a @ref{566,,BaseExceptionGroup}, in addition to
the recent support for @ref{4d2,,ExceptionGroup}.

@item 
gh-111835@footnote{https://github.com/python/cpython/issues/111835}: The @ref{519,,mmap.mmap} class now has an
@ref{51a,,seekable()} method that can be used when a seekable
file-like object is required. The @ref{51b,,seek()} method now
returns the new absolute position. Patch by Donghee Na.

@item 
gh-111804@footnote{https://github.com/python/cpython/issues/111804}: Remove posix.fallocate() under WASI as the underlying
posix_fallocate() is not available in WASI preview2.

@item 
gh-111841@footnote{https://github.com/python/cpython/issues/111841}: Fix truncating arguments on an embedded null character in
@ref{25b,,os.putenv()} and @ref{25c,,os.unsetenv()} on Windows.

@item 
gh-111768@footnote{https://github.com/python/cpython/issues/111768}: @ref{1a3b,,wsgiref.util.is_hop_by_hop()} is now exposed correctly in
@code{__all__}.

@item 
gh-80731@footnote{https://github.com/python/cpython/issues/80731}: Avoid executing the default function in @ref{184e,,cmd.Cmd} in an
except block

@item 
gh-111541@footnote{https://github.com/python/cpython/issues/111541}: Fix @ref{3e,,doctest} for @ref{18e,,SyntaxError} not-builtin
subclasses.

@item 
gh-111719@footnote{https://github.com/python/cpython/issues/111719}: Add extra argument validation for @code{alias} command in
@ref{aa,,pdb}

@item 
gh-111482@footnote{https://github.com/python/cpython/issues/111482}: @ref{f4,,time}: Make @ref{1376,,time.clock_gettime()} and
@ref{cdb,,time.clock_gettime_ns()} functions up to 2x faster by faster calling
convention. Patch by Victor Stinner.

@item 
gh-110894@footnote{https://github.com/python/cpython/issues/110894}: Call loop exception handler for exceptions in
@code{client_connected_cb} of @ref{d0f,,asyncio.start_server()} so that
applications can handle it. Patch by Kumar Aditya.

@item 
gh-111531@footnote{https://github.com/python/cpython/issues/111531}: Fix reference leaks in @code{bind_class()} and @code{bind_all()}
methods of @ref{f6,,tkinter} widgets.

@item 
gh-111246@footnote{https://github.com/python/cpython/issues/111246}: @ref{4ca,,asyncio.loop.create_unix_server()} will now automatically
remove the Unix socket when the server is closed.

@item 
gh-111356@footnote{https://github.com/python/cpython/issues/111356}: Added @ref{1a3c,,io.text_encoding()}, @ref{1a3d,,io.DEFAULT_BUFFER_SIZE},
and @ref{1a3e,,io.IncrementalNewlineDecoder} to @code{io.__all__}.

@item 
gh-66425@footnote{https://github.com/python/cpython/issues/66425}: Remove the code to set the REMOTE_HOST header from wsgiref
module, as it is unreachable. This header is used for performance reasons,
which is not necessary in the wsgiref module.

@item 
gh-111429@footnote{https://github.com/python/cpython/issues/111429}: Speed up @ref{2fd,,pathlib.PurePath.relative_to()} and
@ref{2fe,,is_relative_to()}.

@item 
gh-111342@footnote{https://github.com/python/cpython/issues/111342}: Fixed typo in @ref{6bf,,math.sumprod()}.

@item 
gh-68166@footnote{https://github.com/python/cpython/issues/68166}: Remove mention of not supported "vsapi" element type in
@ref{55f,,tkinter.ttk.Style.element_create()}. Add tests for
@code{element_create()} and other @code{ttk.Style} methods. Add examples for
@code{element_create()} in the documentation.

@item 
gh-111388@footnote{https://github.com/python/cpython/issues/111388}: Add @code{show_group} parameter to
@ref{a4e,,traceback.format_exception_only()}, which allows to format
@ref{4d2,,ExceptionGroup} instances.

@item 
gh-79033@footnote{https://github.com/python/cpython/issues/79033}: Another attempt at fixing @ref{1a3f,,asyncio.Server.wait_closed()}. It
now blocks until both conditions are true: the server is closed, `and'
there are no more active connections. (This means that in some cases where
in 3.12.0 this function would `incorrectly' have returned immediately, it
will now block; in particular, when there are no active connections but
the server hasn't been closed yet.)

@item 
gh-111259@footnote{https://github.com/python/cpython/issues/111259}: Optimize recursive wildcards in @ref{a8,,pathlib}.

@item 
gh-111295@footnote{https://github.com/python/cpython/issues/111295}: Fix @ref{f4,,time} not checking for errors when initializing.

@item 
gh-111253@footnote{https://github.com/python/cpython/issues/111253}: Add error checking during @code{_socket} module init.

@item 
gh-111251@footnote{https://github.com/python/cpython/issues/111251}: Fix @code{_blake2} not checking for errors when initializing.

@item 
gh-111233@footnote{https://github.com/python/cpython/issues/111233}: Fix @ref{c6,,select} not checking for errors when initializing.

@item 
gh-111230@footnote{https://github.com/python/cpython/issues/111230}: Fix @ref{d5,,ssl} not checking for errors when initializing.

@item 
gh-111174@footnote{https://github.com/python/cpython/issues/111174}: Fix crash in @ref{140a,,io.BytesIO.getbuffer()} called repeatedly for
empty BytesIO.

@item 
gh-111187@footnote{https://github.com/python/cpython/issues/111187}: Postpone removal version for locale.getdefaultlocale() to
Python 3.15.

@item 
gh-111159@footnote{https://github.com/python/cpython/issues/111159}: Fix @ref{3e,,doctest} output comparison for exceptions with notes.

@item 
gh-110910@footnote{https://github.com/python/cpython/issues/110910}: Fix invalid state handling in @ref{4d1,,asyncio.TaskGroup} and
@ref{1a40,,asyncio.Timeout}. They now raise proper RuntimeError if they are
improperly used and are left in consistent state after this.

@item 
gh-111092@footnote{https://github.com/python/cpython/issues/111092}: Make turtledemo run without default root enabled.

@item 
gh-110944@footnote{https://github.com/python/cpython/issues/110944}: Support alias and convenience vars for @ref{aa,,pdb} completion

@item 
gh-110745@footnote{https://github.com/python/cpython/issues/110745}: Added `newline' parameter to @ref{1045,,pathlib.Path.read_text()}.
Patch by Junya Okabe.

@item 
gh-84583@footnote{https://github.com/python/cpython/issues/84583}: Make @ref{aa,,pdb} enter post-mortem mode even for
@ref{18e,,SyntaxError}

@item 
gh-80675@footnote{https://github.com/python/cpython/issues/80675}: Set @code{f_trace_lines = True} on all frames upon
@ref{272,,pdb.set_trace()}

@item 
gh-110771@footnote{https://github.com/python/cpython/issues/110771}: Expose the setup and cleanup portions of
@code{asyncio.run_forever()} as the standalone methods
@code{asyncio.run_forever_setup()} and @code{asyncio.run_forever_cleanup()}.
This allows for tighter integration with GUI event loops.

@item 
gh-110774@footnote{https://github.com/python/cpython/issues/110774}: Support setting the @ref{2f5,,asyncio.Runner} loop_factory kwarg
in @ref{361,,unittest.IsolatedAsyncioTestCase}

@item 
gh-110392@footnote{https://github.com/python/cpython/issues/110392}: Fix @ref{1a41,,tty.setraw()} and @ref{19f5,,tty.setcbreak()}: previously
they returned partially modified list of the original tty attributes.
@ref{1a42,,tty.cfmakeraw()} and @ref{19f6,,tty.cfmakecbreak()} now make a copy of the
list of special characters before modifying it.

@item 
gh-59013@footnote{https://github.com/python/cpython/issues/59013}: Make line number of function breakpoint more precise in
@ref{aa,,pdb}

@item 
gh-88434@footnote{https://github.com/python/cpython/issues/88434}: Emit deprecation warning for non-integer numbers in
@ref{67,,gettext} functions and methods that consider plural forms even if
the translation was not found.

@item 
gh-110395@footnote{https://github.com/python/cpython/issues/110395}: Ensure that @ref{1a43,,select.kqueue()} objects correctly appear as
closed in forked children, to prevent operations on an invalid file
descriptor.

@item 
gh-110196@footnote{https://github.com/python/cpython/issues/110196}: Add @code{__reduce__} method to @code{IPv6Address} in order to
keep @code{scope_id}

@item 
gh-109747@footnote{https://github.com/python/cpython/issues/109747}: Improve errors for unsupported look-behind patterns. Now
re.error is raised instead of OverflowError or RuntimeError for too large
width of look-behind pattern.

@item 
gh-109466@footnote{https://github.com/python/cpython/issues/109466}: Add the @ref{50b,,ipaddress.IPv4Address.ipv6_mapped} property,
which returns the IPv4-mapped IPv6 address.

@item 
gh-85098@footnote{https://github.com/python/cpython/issues/85098}: Implement the CLI of the @ref{de,,symtable} module and improve the
repr of @ref{289,,Symbol}.

@item 
gh-108791@footnote{https://github.com/python/cpython/issues/108791}: Improved error handling in @ref{aa,,pdb} command line interface,
making it produce more concise error messages.

@item 
gh-105931@footnote{https://github.com/python/cpython/issues/105931}: Change @ref{21,,compileall} to only strip the stripdir prefix from
the full path recorded in the compiled @code{.pyc} file, when the prefix
matches the start of the full path in its entirety. When the prefix does
not match, no stripping is performed and a warning to this effect is
displayed.

Previously all path components of the stripdir prefix that matched the
full path were removed, while those that did not match were left alone
(including ones interspersed between matching components).

@item 
gh-107431@footnote{https://github.com/python/cpython/issues/107431}: Make the @code{DictProxy} and @code{ListProxy} types in
@ref{9b,,multiprocessing.managers} @ref{8c1,,Generic Alias Types} for @code{[]} use in typing contexts.

@item 
gh-72904@footnote{https://github.com/python/cpython/issues/72904}: Add @ref{4fb,,glob.translate()}. This function converts a pathname
with shell-style wildcards to a regular expression.

@item 
gh-90026@footnote{https://github.com/python/cpython/issues/90026}: Define @code{USE_XATTRS} on Cygwin so that XATTR-related functions
in the @ref{a5,,os} module become available.

@item 
gh-90890@footnote{https://github.com/python/cpython/issues/90890}: New methods @ref{1a44,,mailbox.Maildir.get_info()},
@ref{1a45,,mailbox.Maildir.set_info()}, @ref{1a46,,mailbox.Maildir.get_flags()},
@ref{1a47,,mailbox.Maildir.set_flags()}, @ref{1a48,,mailbox.Maildir.add_flag()},
@ref{1a49,,mailbox.Maildir.remove_flag()}. These methods speed up accessing a
message's info and/or flags and are useful when it is not necessary to
access the message's contents, as when iterating over a Maildir to find
messages with specific flags.

@item 
gh-102956@footnote{https://github.com/python/cpython/issues/102956}: Fix returning of empty byte strings after seek in zipfile
module

@item 
gh-102895@footnote{https://github.com/python/cpython/issues/102895}: Added a parameter @code{local_exit} for @ref{1890,,code.interact()} to
prevent @code{exit()} and @code{quit} from closing @code{sys.stdin} and raise
@code{SystemExit}.

@item 
gh-97928@footnote{https://github.com/python/cpython/issues/97928}: Change the behavior of @code{tkinter.Text.count()}. It now always
returns an integer if one or less counting options are specified.
Previously it could return a single count as a 1-tuple, an integer (only
if option @code{"update"} was specified) or @code{None} if no items found. The
result is now the same if @code{wantobjects} is set to @code{0}.

@item 
gh-96954@footnote{https://github.com/python/cpython/issues/96954}: Switch the storage of the unicode codepoint names to use a
different data-structure, a directed acyclic word graph@footnote{https://en.wikipedia.org/wiki/Deterministic_acyclic_finite_state_automaton}.
This makes the unicodedata shared library about 440 KiB smaller.
Contributed by Carl Friedrich Bolz-Tereick using code from the PyPy
project.

@item 
gh-73561@footnote{https://github.com/python/cpython/issues/73561}: Omit the interface scope from an IPv6 address when used as Host
header by @ref{73,,http.client}.

@item 
gh-86826@footnote{https://github.com/python/cpython/issues/86826}: @code{zipinfo} now supports the full range of values in the TZ
string determined by RFC 8536 and detects all invalid formats. Both Python
and C implementations now raise exceptions of the same type on invalid
data.
@end itemize

@node テスト<18>,ビルド<21>,ライブラリ<63>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id264}@anchor{1a4a}
@subsubsection テスト



@itemize -

@item 
gh-111808@footnote{https://github.com/python/cpython/issues/111808}: Make the default value of @code{test.support.infinite_recursion()}
to be conditional based on whether optimizations were used when compiling
the interpreter. This helps with platforms like WASI whose stack size is
greatly restricted in debug builds.

@item 
gh-110722@footnote{https://github.com/python/cpython/issues/110722}: Gathering line coverage of standard libraries within the
regression test suite is now precise, as well as much faster. Patch by
Łukasz Langa.

@item 
gh-110367@footnote{https://github.com/python/cpython/issues/110367}: Make regrtest @code{--verbose3} option compatible with
@code{--huntrleaks -jN} options. The @code{./python -m test -j1 -R 3:3
--verbose3} command now works as expected. Patch by Victor Stinner.

@item 
gh-111165@footnote{https://github.com/python/cpython/issues/111165}: Remove no longer used functions @code{run_unittest()} and
@code{run_doctest()} from the @ref{ea,,test.support} module.

@item 
gh-110932@footnote{https://github.com/python/cpython/issues/110932}: Fix regrtest if the @code{SOURCE_DATE_EPOCH} environment variable
is defined: use the variable value as the random seed. Patch by Victor
Stinner.

@item 
gh-110995@footnote{https://github.com/python/cpython/issues/110995}: test_gdb: Fix detection of gdb built without Python scripting
support. Patch by Victor Stinner.

@item 
gh-110918@footnote{https://github.com/python/cpython/issues/110918}: Test case matching patterns specified by options @code{--match},
@code{--ignore}, @code{--matchfile} and @code{--ignorefile} are now tested in the
order of specification, and the last match determines whether the test
case be run or ignored.

@item 
gh-108747@footnote{https://github.com/python/cpython/issues/108747}: Add unit test for @code{usercustomize} and @code{sitecustomize} hooks
from @ref{cc,,site}.
@end itemize

@node ビルド<21>,Windows<20>,テスト<18>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id265}@anchor{1a4b}
@subsubsection ビルド



@itemize -

@item 
gh-96954@footnote{https://github.com/python/cpython/issues/96954}: Make @code{make regen-unicodedata} work for out-of-tree builds of
CPython.

@item 
gh-112088@footnote{https://github.com/python/cpython/issues/112088}: Add @code{Tools/build/regen-configure.sh} script to regenerate the
@code{configure} with an Ubuntu container image. The
@code{quay.io/tiran/cpython_autoconf:271} container image
(tiran/cpython_autoconf@footnote{https://github.com/tiran/cpython_autoconf}) is
no longer used. Patch by Victor Stinner.

@item 
gh-111046@footnote{https://github.com/python/cpython/issues/111046}: For wasi-threads, memory is now exported to fix compatibility
issues with some wasm runtimes.

@item 
gh-110828@footnote{https://github.com/python/cpython/issues/110828}: AIX 32bit needs @code{-latomic} to build the @code{_testcapi}
extension module.

@item 
gh-85283@footnote{https://github.com/python/cpython/issues/85283}: The @code{errno}, @code{md5}, @code{resource}, @code{winsound},
@code{_ctypes_test}, @code{_multiprocessing.posixshmem}, @code{_scproxy},
@code{_stat}, @code{_testimportmultiple} and @code{_uuid} C extensions are now
built with the @ref{637,,limited C API}. Patch by Victor
Stinner.
@end itemize

@node Windows<20>,macOS<13>,ビルド<21>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id266}@anchor{1a4c}
@subsubsection Windows



@itemize -

@item 
gh-111856@footnote{https://github.com/python/cpython/issues/111856}: Fixes @ref{f8c,,fstat()} on file systems that do not support
file ID requests. This includes FAT32 and exFAT.

@item 
gh-111293@footnote{https://github.com/python/cpython/issues/111293}: Fix @ref{1a4d,,os.DirEntry.inode} dropping higher 64 bits of a file
id on some filesystems on Windows.

@item 
gh-110913@footnote{https://github.com/python/cpython/issues/110913}: WindowsConsoleIO now correctly chunks large buffers without
splitting up UTF-8 sequences.
@end itemize

@node macOS<13>,IDLE<12>,Windows<20>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id267}@anchor{1a4e}
@subsubsection macOS



@itemize -

@item 
gh-59703@footnote{https://github.com/python/cpython/issues/59703}: For macOS framework builds, in @code{getpath.c} use the system
@code{dladdr} function to find the path to the shared library rather than
depending on deprecated macOS APIs.

@item 
gh-110950@footnote{https://github.com/python/cpython/issues/110950}: Update macOS installer to include an upstream Tcl/Tk fix for
the @code{Secure coding is not enabled for restorable state!} warning
encountered in Tkinter on macOS 14 Sonoma.

@item 
gh-111015@footnote{https://github.com/python/cpython/issues/111015}: Ensure that IDLE.app and Python Launcher.app are installed with
appropriate permissions on macOS builds.

@item 
gh-71383@footnote{https://github.com/python/cpython/issues/71383}: Update macOS installer to include an upstream Tcl/Tk fix for the
@code{ttk::ThemeChanged} error encountered in Tkinter.

@item 
gh-92603@footnote{https://github.com/python/cpython/issues/92603}: Update macOS installer to include a fix accepted by upstream
Tcl/Tk for a crash encountered after the first @ref{19ac,,tkinter.Tk()} instance
is destroyed.
@end itemize

@node IDLE<12>,Tools/Demos<18>,macOS<13>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id268}@anchor{1a4f}
@subsubsection IDLE



@itemize -

@item 
bpo-35668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35668}: Add docstrings to the IDLE debugger module. Fix two bugs:
initialize @code{Idb.botframe} (should be in Bdb); in @code{Idb.in_rpc_code},
check whether @code{prev_frame} is @code{None} before trying to use it. Greatly
expand test_debugger.
@end itemize

@node Tools/Demos<18>,C API<21>,IDLE<12>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id269}@anchor{1a50}
@subsubsection Tools/Demos



@itemize -

@item 
gh-111903@footnote{https://github.com/python/cpython/issues/111903}: Argument Clinic now supports the @code{@@critical_section}
directive that instructs Argument Clinic to generate a critical section
around the function call, which locks the @code{self} object in
@code{--disable-gil} builds. Patch by Sam Gross.
@end itemize

@node C API<21>,,Tools/Demos<18>,Python 3 13 0 alpha 2
@anchor{whatsnew/changelog id270}@anchor{1a51}
@subsubsection C API



@itemize -

@item 
gh-112026@footnote{https://github.com/python/cpython/issues/112026}: Add again the private @code{_PyThreadState_UncheckedGet()}
function as an alias to the new public
@ref{423,,PyThreadState_GetUnchecked()} function. Patch by Victor Stinner.

@item 
gh-112026@footnote{https://github.com/python/cpython/issues/112026}: Restore the removed @code{_PyDict_GetItemStringWithError()}
function. It is used by numpy. Patch by Victor Stinner.

@item 
gh-112026@footnote{https://github.com/python/cpython/issues/112026}: Restore removed private C API functions, macros and structures
which have no simple replacement for now:


@itemize *

@item 
_PyDict_GetItem_KnownHash()

@item 
_PyDict_NewPresized()

@item 
_PyHASH_BITS

@item 
_PyHASH_IMAG

@item 
_PyHASH_INF

@item 
_PyHASH_MODULUS

@item 
_PyHASH_MULTIPLIER

@item 
_PyLong_Copy()

@item 
_PyLong_FromDigits()

@item 
_PyLong_New()

@item 
_PyLong_Sign()

@item 
_PyObject_CallMethodId()

@item 
_PyObject_CallMethodNoArgs()

@item 
_PyObject_CallMethodOneArg()

@item 
_PyObject_CallOneArg()

@item 
_PyObject_EXTRA_INIT

@item 
_PyObject_FastCallDict()

@item 
_PyObject_GetAttrId()

@item 
_PyObject_Vectorcall()

@item 
_PyObject_VectorcallMethod()

@item 
_PyStack_AsDict()

@item 
_PyThread_CurrentFrames()

@item 
_PyUnicodeWriter structure

@item 
_PyUnicodeWriter_Dealloc()

@item 
_PyUnicodeWriter_Finish()

@item 
_PyUnicodeWriter_Init()

@item 
_PyUnicodeWriter_Prepare()

@item 
_PyUnicodeWriter_PrepareKind()

@item 
_PyUnicodeWriter_WriteASCIIString()

@item 
_PyUnicodeWriter_WriteChar()

@item 
_PyUnicodeWriter_WriteLatin1String()

@item 
_PyUnicodeWriter_WriteStr()

@item 
_PyUnicodeWriter_WriteSubstring()

@item 
_PyUnicode_AsString()

@item 
_PyUnicode_FromId()

@item 
_PyVectorcall_Function()

@item 
_Py_IDENTIFIER()

@item 
_Py_c_abs()

@item 
_Py_c_diff()

@item 
_Py_c_neg()

@item 
_Py_c_pow()

@item 
_Py_c_prod()

@item 
_Py_c_quot()

@item 
_Py_c_sum()

@item 
_Py_static_string()

@item 
_Py_static_string_init()
@end itemize

Patch by Victor Stinner.

@item 
gh-112026@footnote{https://github.com/python/cpython/issues/112026}: Add again @code{<ctype.h>} and @code{<unistd.h>} includes in
@code{Python.h}, but don't include them in the limited C API version 3.13 and
newer. Patch by Victor Stinner.

@item 
gh-111956@footnote{https://github.com/python/cpython/issues/111956}: Add internal-only one-time initialization API: @code{_PyOnceFlag}
and @code{_PyOnceFlag_CallOnce}.

@item 
gh-111262@footnote{https://github.com/python/cpython/issues/111262}: Add @ref{422,,PyDict_Pop()} and @ref{5e5,,PyDict_PopString()}
functions: remove a key from a dictionary and optionally return the
removed value. This is similar to @ref{5e6,,dict.pop()}, but without the
default value and not raising @ref{5e7,,KeyError} if the key missing. Patch by
Stefan Behnel and Victor Stinner.

@item 
gh-111863@footnote{https://github.com/python/cpython/issues/111863}: Rename @code{Py_NOGIL} to @code{Py_GIL_DISABLED}. Patch by Hugo van
Kemenade.

@item 
gh-111138@footnote{https://github.com/python/cpython/issues/111138}: Add @ref{600,,PyList_Extend()} and @ref{601,,PyList_Clear()}
functions: similar to Python @code{list.extend()} and @code{list.clear()}
methods. Patch by Victor Stinner.

@item 
gh-108765@footnote{https://github.com/python/cpython/issues/108765}: On Windows, @code{Python.h} no longer includes the @code{<stddef.h>}
standard header file. If needed, it should now be included explicitly.
Patch by Victor Stinner.

@item 
gh-111569@footnote{https://github.com/python/cpython/issues/111569}: Implement "Python Critical Sections" from 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}. These are
macros to help replace the GIL with per-object locks in the
@code{--disable-gil} build of CPython. The macros are no-ops in the default
build.

@item 
gh-111506@footnote{https://github.com/python/cpython/issues/111506}: In the limited C API version 3.13, @ref{aa8,,Py_SET_REFCNT()}
function is now implemented as an opaque function call. Patch by Victor
Stinner.

@item 
gh-108082@footnote{https://github.com/python/cpython/issues/108082}: Add @ref{5f1,,PyErr_FormatUnraisable()} function.

@item 
gh-110964@footnote{https://github.com/python/cpython/issues/110964}: Move the undocumented private _PyArg functions and
_PyArg_Parser structure to internal C API (@code{pycore_modsupport.h}). Patch
by Victor Stinner.

@item 
gh-110815@footnote{https://github.com/python/cpython/issues/110815}: Support non-ASCII keyword names in
@ref{624,,PyArg_ParseTupleAndKeywords()}.

@item 
gh-109587@footnote{https://github.com/python/cpython/issues/109587}: Introduced @code{PyUnstable_PerfTrampoline_CompileCode()},
@code{PyUnstable_PerfTrampoline_SetPersistAfterFork()} and
@code{PyUnstable_CopyPerfMapFile()}. These functions allow extension
modules to initialize trampolines eagerly, after the application is
"warmed up". This makes it possible to have perf-trampolines running in an
always-enabled fashion.

@item 
gh-85283@footnote{https://github.com/python/cpython/issues/85283}: Add the @ref{613,,PySys_Audit()} function to the limited C API.
Patch by Victor Stinner.

@item 
gh-85283@footnote{https://github.com/python/cpython/issues/85283}: Add @ref{631,,PyMem_RawMalloc()}, @ref{632,,PyMem_RawCalloc()},
@ref{633,,PyMem_RawRealloc()} and @ref{634,,PyMem_RawFree()} to the limited C
API. Patch by Victor Stinner.

@item 
gh-106672@footnote{https://github.com/python/cpython/issues/106672}: Functions @ref{628,,PyDict_GetItem()},
@ref{629,,PyDict_GetItemString()}, @ref{620,,PyMapping_HasKey()},
@ref{622,,PyMapping_HasKeyString()}, @ref{61c,,PyObject_HasAttr()},
@ref{61e,,PyObject_HasAttrString()}, and @ref{62a,,PySys_GetObject()}, which
clear all errors occurred during calling the function, report now them
using @ref{507,,sys.unraisablehook()}.

@item 
gh-67565@footnote{https://github.com/python/cpython/issues/67565}: Remove redundant C-contiguity check in @code{getargs.c},
@ref{11,,binascii}, @ref{d5,,ssl} and Argument Clinic. Patched by Stefan Krah
and Furkan Onder
@end itemize

@node Python 3 13 0 alpha 1,Python 3 12 0 beta 1,Python 3 13 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-13-0-alpha-1}@anchor{1a52}
@subsection Python 3.13.0 alpha 1


`Release date: 2023-10-13'

@menu
* セキュリティ: セキュリティ<21>. 
* Core and Builtins: Core and Builtins<59>. 
* ライブラリ: ライブラリ<64>. 
* ドキュメント: ドキュメント<20>. 
* テスト: テスト<19>. 
* ビルド: ビルド<22>. 
* Windows: Windows<21>. 
* macOS: macOS<14>. 
* IDLE: IDLE<13>. 
* Tools/Demos: Tools/Demos<19>. 
* C API: C API<22>. 

@end menu

@node セキュリティ<21>,Core and Builtins<59>,,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id271}@anchor{1a53}
@subsubsection セキュリティ



@itemize -

@item 
gh-108310@footnote{https://github.com/python/cpython/issues/108310}: Fixed an issue where instances of @ref{ae7,,ssl.SSLSocket} were
vulnerable to a bypass of the TLS handshake and included protections (like
certificate verification) and treating sent unencrypted data as if it were
post-handshake TLS encrypted data.  Security issue reported as
@geindex Common Vulnerabilities and Exposures; CVE 2023-40217
CVE 2023-40217@footnote{https://www.cve.org/CVERecord?id=CVE-2023-40217} by Aapo Oksman. Patch by Gregory P. Smith.

@item 
gh-107774@footnote{https://github.com/python/cpython/issues/107774}: PEP 669 specifies that @code{sys.monitoring.register_callback}
will generate an audit event. Pre-releases of Python 3.12 did not generate
the audit event. This is now fixed.

@item 
gh-102988@footnote{https://github.com/python/cpython/issues/102988}: Reverted the @ref{54,,email.utils} security improvement change
released in 3.12beta4 that unintentionally caused
@ref{4f3,,email.utils.getaddresses} to fail to parse email addresses with a
comma in the quoted name field. See gh-106669@footnote{https://github.com/python/cpython/issues/106669}.

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Refresh our new HACL* built-in @ref{6c,,hashlib} code from
upstream. Built-in SHA2 should be faster and an issue with SHA3 on 32-bit
platforms is fixed.

@item 
gh-102509@footnote{https://github.com/python/cpython/issues/102509}: Start initializing @code{ob_digit} during creation of
@ref{39e,,PyLongObject} objects. Patch by Illia Volochii.
@end itemize

@node Core and Builtins<59>,ライブラリ<64>,セキュリティ<21>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id272}@anchor{1a54}
@subsubsection Core and Builtins



@itemize -

@item 
gh-110782@footnote{https://github.com/python/cpython/issues/110782}: Fix crash when @ref{486,,typing.TypeVar} is constructed with a
keyword argument. Patch by Jelle Zijlstra.

@item 
gh-110752@footnote{https://github.com/python/cpython/issues/110752}: Reset @code{ceval.eval_breaker} in @code{interpreter_clear()}

@item 
gh-110721@footnote{https://github.com/python/cpython/issues/110721}: Use the @ref{104,,traceback} implementation for the default
@code{PyErr_Display()} functionality. Patch by Pablo Galindo

@item 
gh-110696@footnote{https://github.com/python/cpython/issues/110696}: Fix incorrect error message for invalid argument unpacking.
Patch by Pablo Galindo

@item 
gh-104169@footnote{https://github.com/python/cpython/issues/104169}: Split the tokenizer into two separate directories: - One part
includes the actual lexeme producing logic and lives in @code{Parser/lexer}.
- The second part wraps the lexer according to the different tokenization
modes   we have (string, utf-8, file, interactive, readline) and lives in
@code{Parser/tokenizer}.

@item 
gh-110688@footnote{https://github.com/python/cpython/issues/110688}: Remove undocumented @code{test_c_api} method from @ref{184,,set},
which was only defined for testing purposes under @code{Py_DEBUG}. Now we
have proper CAPI tests.

@item 
gh-104584@footnote{https://github.com/python/cpython/issues/104584}: Fix a reference leak when running with 
@geindex PYTHONUOPS
@geindex 環境変数; PYTHONUOPS
@code{PYTHONUOPS} or
@ref{16f,,-X uops} enabled.

@item 
gh-110514@footnote{https://github.com/python/cpython/issues/110514}: Add @code{PY_THROW} to @ref{1717,,sys.setprofile()} events

@item 
gh-110489@footnote{https://github.com/python/cpython/issues/110489}: Optimise @ref{15d8,,math.ceil()} when the input is exactly a float,
resulting in about a 10% improvement.

@item 
gh-110455@footnote{https://github.com/python/cpython/issues/110455}: Guard @code{assert(tstate->thread_id > 0)} with @code{#ifndef
HAVE_PTHREAD_STUBS}. This allows for for pydebug builds to work under
WASI which (currently) lacks thread support.

@item 
gh-110309@footnote{https://github.com/python/cpython/issues/110309}: Remove unnecessary empty constant nodes in the ast of f-string
specs.

@item 
gh-110259@footnote{https://github.com/python/cpython/issues/110259}: Correctly identify the format spec in f-strings (with single or
triple quotes) that have multiple lines in the expression part and include
a formatting spec. Patch by Pablo Galindo

@item 
gh-110237@footnote{https://github.com/python/cpython/issues/110237}: Fix missing error checks for calls to @code{PyList_Append} in
@code{_PyEval_MatchClass}.

@item 
gh-110164@footnote{https://github.com/python/cpython/issues/110164}: regrtest: If the @code{SOURCE_DATE_EPOCH} environment variable is
defined, regrtest now disables tests randomization. Patch by Victor
Stinner.

@item 
gh-109889@footnote{https://github.com/python/cpython/issues/109889}: Fix the compiler's redundant NOP detection algorithm to skip
over NOPs with no line number when looking for the next instruction's
lineno.

@item 
gh-109853@footnote{https://github.com/python/cpython/issues/109853}: @code{sys.path[0]} is now set correctly for subinterpreters.

@item 
gh-109923@footnote{https://github.com/python/cpython/issues/109923}: Set line number on the @code{POP_TOP} that follows a
@code{RETURN_GENERATOR}.

@item 
gh-105716@footnote{https://github.com/python/cpython/issues/105716}: Subinterpreters now correctly handle the case where they have
threads running in the background.  Before, such threads would interfere
with cleaning up and destroying them, as well as prevent running another
script.

@item 
gh-109369@footnote{https://github.com/python/cpython/issues/109369}: The internal eval_breaker and supporting flags, plus the
monitoring version have been merged into a single atomic integer to speed
up checks.

@item 
gh-109823@footnote{https://github.com/python/cpython/issues/109823}: Fix bug where compiler does not adjust labels when removing an
empty basic block which is a jump target.

@item 
gh-109793@footnote{https://github.com/python/cpython/issues/109793}: The main thread no longer exits prematurely when a
subinterpreter is cleaned up during runtime finalization.  The bug was a
problem particularly because, when triggered, the Python process would
always return with a 0 exitcode, even if it failed.

@item 
gh-109719@footnote{https://github.com/python/cpython/issues/109719}: Fix missing jump target labels when compiler reorders cold/warm
blocks.

@item 
gh-109595@footnote{https://github.com/python/cpython/issues/109595}: Add @ref{16f,,-X cpu_count}  command line option to
override return results of @ref{4db,,os.cpu_count()} and
@ref{4da,,os.process_cpu_count()}. This option is useful for users who need to
limit CPU resources of a container system without having to modify the
container (application code). Patch by Donghee Na.

@item 
gh-109627@footnote{https://github.com/python/cpython/issues/109627}: Fix bug where the compiler does not assign a new jump target
label to a duplicated small exit block.

@item 
gh-109596@footnote{https://github.com/python/cpython/issues/109596}: Fix some tokens in the grammar that were incorrectly marked as
soft keywords. Also fix some repeated rule names and ensure that repeated
rules are not allowed. Patch by Pablo Galindo

@item 
gh-109496@footnote{https://github.com/python/cpython/issues/109496}: On a Python built in debug mode, @ref{790,,Py_DECREF()} now
calls @code{_Py_NegativeRefcount()} if the object is a dangling pointer to
deallocated memory: memory filled with @code{0xDD} "dead byte" by the debug
hook on memory allocators. The fix is to check the reference count
`before' checking for @code{_Py_IsImmortal()}. Patch by Victor Stinner.

@item 
gh-107265@footnote{https://github.com/python/cpython/issues/107265}: Deopt opcodes hidden by the executor when base opcode is needed

@item 
gh-109371@footnote{https://github.com/python/cpython/issues/109371}: Deopted instructions correctly for tool initialization and
modified the incorrect assertion in instrumentation, when a previous tool
already sets INSTRUCTION events

@item 
gh-105658@footnote{https://github.com/python/cpython/issues/105658}: Fix bug where the line trace of an except block ending with a
conditional includes an excess event with the line of the conditional
expression.

@item 
gh-109219@footnote{https://github.com/python/cpython/issues/109219}: Fix compiling type param scopes that use a name which is also
free in an inner scope.

@item 
gh-109351@footnote{https://github.com/python/cpython/issues/109351}: Fix crash when compiling an invalid AST involving a named
(walrus) expression.

@item 
gh-109341@footnote{https://github.com/python/cpython/issues/109341}: Fix crash when compiling an invalid AST involving a
@ref{1a55,,ast.TypeAlias}.

@item 
gh-109195@footnote{https://github.com/python/cpython/issues/109195}: Fix source location for the @code{LOAD_*} instruction preceding a
@code{LOAD_SUPER_ATTR} to load the @code{super} global (or shadowing variable)
so that it encompasses only the name @code{super} and not the following
parentheses.

@item 
gh-109256@footnote{https://github.com/python/cpython/issues/109256}: Opcode IDs for specialized opcodes are allocated in their own
range to improve stability of the IDs for the 'real' opcodes.

@item 
gh-109216@footnote{https://github.com/python/cpython/issues/109216}: Fix possible memory leak in @ref{369,,BUILD_MAP}.

@item 
gh-109207@footnote{https://github.com/python/cpython/issues/109207}: Fix a SystemError in @code{__repr__} of symtable entry object.

@item 
gh-109179@footnote{https://github.com/python/cpython/issues/109179}: Fix bug where the C traceback display drops notes from
@ref{18e,,SyntaxError}.

@item 
gh-109118@footnote{https://github.com/python/cpython/issues/109118}: Disallow nested scopes (lambdas, generator expressions, and
comprehensions) within PEP 695 annotation scopes that are nested within
classes.

@item 
gh-109156@footnote{https://github.com/python/cpython/issues/109156}: Add tests for de-instrumenting instructions while keeping the
instrumentation for lines

@item 
gh-109114@footnote{https://github.com/python/cpython/issues/109114}: Relax the detection of the error message for invalid lambdas
inside f-strings to not search for arbitrary replacement fields to avoid
false positives. Patch by Pablo Galindo

@item 
gh-105848@footnote{https://github.com/python/cpython/issues/105848}: Add a new @ref{372,,CALL_KW} opcode, used for calls containing
keyword arguments. Also, fix a possible crash when jumping over method
calls in a debugger.

@item 
gh-109052@footnote{https://github.com/python/cpython/issues/109052}: Use the base opcode when comparing code objects to avoid
interference from instrumentation

@item 
gh-109118@footnote{https://github.com/python/cpython/issues/109118}: Fix interpreter crash when a NameError is raised inside the
type parameters of a generic class.

@item 
gh-88943@footnote{https://github.com/python/cpython/issues/88943}: Improve syntax error for non-ASCII character that follows a
numerical literal. It now points on the invalid non-ASCII character, not
on the valid numerical literal.

@item 
gh-108976@footnote{https://github.com/python/cpython/issues/108976}: Fix crash that occurs after de-instrumenting a code object in a
monitoring callback.

@item 
gh-108732@footnote{https://github.com/python/cpython/issues/108732}: Make iteration variables of module- and class-scoped
comprehensions visible to pdb and other tools that use @code{frame.f_locals}
again.

@item 
gh-108959@footnote{https://github.com/python/cpython/issues/108959}: Fix caret placement for error locations for subscript and
binary operations that involve non-semantic parentheses and spaces. Patch
by Pablo Galindo

@item 
gh-104584@footnote{https://github.com/python/cpython/issues/104584}: Fix a crash when running with 
@geindex PYTHONUOPS
@geindex 環境変数; PYTHONUOPS
@code{PYTHONUOPS} or
@ref{16f,,-X uops} enabled and an error occurs during optimization.

@item 
gh-108727@footnote{https://github.com/python/cpython/issues/108727}: Define @code{tp_dealloc} for @code{CounterOptimizer_Type}. This fixes
a segfault on deallocation.

@item 
gh-108520@footnote{https://github.com/python/cpython/issues/108520}: Fix @code{multiprocessing.synchronize.SemLock.__setstate__()} to
properly initialize
@code{multiprocessing.synchronize.SemLock._is_fork_ctx}. This fixes a
regression when passing a SemLock across nested processes.

Rename @code{multiprocessing.synchronize.SemLock.is_fork_ctx} to
@code{multiprocessing.synchronize.SemLock._is_fork_ctx} to avoid exposing
it as public API.

@item 
gh-108654@footnote{https://github.com/python/cpython/issues/108654}: Restore locals shadowed by an inlined comprehension if the
comprehension raises an exception.

@item 
gh-108488@footnote{https://github.com/python/cpython/issues/108488}: Change the initialization of inline cache entries so that the
cache entry for @code{JUMP_BACKWARD} is initialized to zero, instead of the
@code{adaptive_counter_warmup()} value used for all other instructions. This
counter, unique among instructions, counts up from zero.

@item 
gh-108716@footnote{https://github.com/python/cpython/issues/108716}: Turn off deep-freezing of code objects. Modules are still
frozen, so that a file system search is not needed for common modules.

@item 
gh-108614@footnote{https://github.com/python/cpython/issues/108614}: Add RESUME_CHECK instruction, to avoid having to handle
instrumentation, signals, and contexts switches in the tier 2 execution
engine.

@item 
gh-108487@footnote{https://github.com/python/cpython/issues/108487}: Move an assert that would cause a spurious crash in a devious
case that should only trigger deoptimization.

@item 
gh-106176@footnote{https://github.com/python/cpython/issues/106176}: Use a @code{WeakValueDictionary} to track the lists containing the
modules each thread is currently importing. This helps avoid a reference
leak from keeping the list around longer than necessary. Weakrefs are used
as GC can't interrupt the cleanup.

@item 
gh-105481@footnote{https://github.com/python/cpython/issues/105481}: The regen-opcode build stage was removed and its work is now
done in regen-cases.

@item 
gh-107901@footnote{https://github.com/python/cpython/issues/107901}: Fix missing line number on @ref{91a,,JUMP_BACKWARD} at the end
of a for loop.

@item 
gh-108113@footnote{https://github.com/python/cpython/issues/108113}: The @ref{4b1,,compile()} built-in can now accept a new flag,
@code{ast.PyCF_OPTIMIZED_AST}, which is similar to @code{ast.PyCF_ONLY_AST}
except that the returned @code{AST} is optimized according to the value of
the @code{optimize} argument.

@ref{1c2,,ast.parse()} now accepts an optional argument @code{optimize} which is
passed on to the @ref{4b1,,compile()} built-in. This makes it possible to
obtain an optimized @code{AST}.

@item 
gh-107971@footnote{https://github.com/python/cpython/issues/107971}: Opcode IDs are generated from bytecodes.c instead of being hard
coded in opcode.py.

@item 
gh-107944@footnote{https://github.com/python/cpython/issues/107944}: Improve error message for function calls with bad keyword
arguments. Patch by Pablo Galindo

@item 
gh-108390@footnote{https://github.com/python/cpython/issues/108390}: Raise an exception when setting a non-local event (@code{RAISE},
@code{EXCEPTION_HANDLED}, etc.) in @code{sys.monitoring.set_local_events}.

Fixes crash when tracing in recursive calls to Python classes.

@item 
gh-108035@footnote{https://github.com/python/cpython/issues/108035}: Remove the @code{_PyCFrame} struct, moving the pointer to the
current interpreter frame back to the threadstate, as it was for 3.10 and
earlier. The @code{_PyCFrame} existed as a performance optimization for
tracing. Since PEP 669 has been implemented, this optimization no longer
applies.

@item 
gh-91051@footnote{https://github.com/python/cpython/issues/91051}: Fix abort / segfault when using all eight type watcher slots, on
platforms where @code{char} is signed by default.

@item 
gh-106581@footnote{https://github.com/python/cpython/issues/106581}: Fix possible assertion failures and missing instrumentation
events when 
@geindex PYTHONUOPS
@geindex 環境変数; PYTHONUOPS
@code{PYTHONUOPS} or @ref{16f,,-X uops} is enabled.

@item 
gh-107526@footnote{https://github.com/python/cpython/issues/107526}: Revert converting @code{vars}, @code{dir}, @code{next}, @code{getattr}, and
@code{iter} to argument clinic.

@item 
gh-84805@footnote{https://github.com/python/cpython/issues/84805}: Autogenerate signature for @ref{16ed,,METH_NOARGS} and
@ref{1720,,METH_O} extension functions.

@item 
gh-107758@footnote{https://github.com/python/cpython/issues/107758}: Make the @code{dump_stack()} routine used by the @code{lltrace}
feature (low-level interpreter debugging) robust against recursion by
ensuring that it never calls a @code{__repr__} method implemented in Python.
Also make the similar output for Tier-2 uops appear on @code{stdout} (instead
of @code{stderr}), to match the @code{lltrace} code in ceval.c.

@item 
gh-107659@footnote{https://github.com/python/cpython/issues/107659}: Add docstrings for @ref{1a56,,ctypes.pointer()} and
@ref{1f1,,ctypes.POINTER()}.

@item 
gh-105848@footnote{https://github.com/python/cpython/issues/105848}: Modify the bytecode so that the actual callable for a
@ref{915,,CALL} is at a consistent position on the stack (regardless of
whether or not bound-method-calling optimizations are active).

@item 
gh-107674@footnote{https://github.com/python/cpython/issues/107674}: Fixed performance regression in @code{sys.settrace}.

@item 
gh-107724@footnote{https://github.com/python/cpython/issues/107724}: In pre-release versions of 3.12, up to rc1, the sys.monitoring
callback function for the @code{PY_THROW} event was missing the third,
exception argument. That is now fixed.

@item 
gh-84436@footnote{https://github.com/python/cpython/issues/84436}: Skip reference count modifications for many known immortal
objects.

@item 
gh-107596@footnote{https://github.com/python/cpython/issues/107596}: Specialize subscripting @ref{169,,str} objects by @ref{19b,,int}
indexes.

@item 
gh-107080@footnote{https://github.com/python/cpython/issues/107080}: Trace refs builds (@code{--with-trace-refs}) were crashing when
used with isolated subinterpreters.  The problematic global state has been
isolated to each interpreter.  Other fixing the crashes, this change does
not affect users.

@item 
gh-107557@footnote{https://github.com/python/cpython/issues/107557}: Generate the cases needed for the barebones tier 2 abstract
interpreter for optimization passes in CPython.

@item 
gh-106608@footnote{https://github.com/python/cpython/issues/106608}: Make @code{_PyUOpExecutorObject} variable length.

@item 
gh-100964@footnote{https://github.com/python/cpython/issues/100964}: Clear generators' exception state after @code{return} to break
reference cycles.

@item 
gh-107455@footnote{https://github.com/python/cpython/issues/107455}: Improve error messages when converting an incompatible type to
@ref{1a57,,ctypes.c_char_p}, @ref{1a58,,ctypes.c_wchar_p} and
@ref{1a59,,ctypes.c_void_p}.

@item 
gh-107263@footnote{https://github.com/python/cpython/issues/107263}: Increase C recursion limit for functions other than the main
interpreter from 800 to 1500. This should allow functions like
@code{list.__repr__} and @code{json.dumps} to handle all the inputs that they
could prior to 3.12

@item 
gh-104584@footnote{https://github.com/python/cpython/issues/104584}: Fix an issue which caused incorrect inline caches to be read
when running with 
@geindex PYTHONUOPS
@geindex 環境変数; PYTHONUOPS
@code{PYTHONUOPS} or @ref{16f,,-X uops} enabled.

@item 
gh-104432@footnote{https://github.com/python/cpython/issues/104432}: Fix potential unaligned memory access on C APIs involving
returned sequences of @code{char *} pointers within the @ref{6a,,grp} and
@ref{d1,,socket} modules. These were revealed using a
@code{-fsaniziter=alignment} build on ARM macOS. Patch by Christopher Chavez.

@item 
gh-106078@footnote{https://github.com/python/cpython/issues/106078}: Isolate @code{_decimal} (apply 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}). Patch by Charlie
Zhao.

@item 
gh-106898@footnote{https://github.com/python/cpython/issues/106898}: Add the exception as the third argument to @code{PY_UNIND}
callbacks in @code{sys.monitoring}. This makes the @code{PY_UNWIND} callback
consistent with the other exception handling callbacks.

@item 
gh-106895@footnote{https://github.com/python/cpython/issues/106895}: Raise a @code{ValueError} when a monitoring callback function
returns @code{DISABLE} for events that cannot be disabled locally.

@item 
gh-106897@footnote{https://github.com/python/cpython/issues/106897}: Add a @code{RERAISE} event to @code{sys.monitoring}, which occurs
when an exception is reraise, either explicitly by a plain @code{raise}
statement, or implicitly in an @code{except} or @code{finally} block.

@item 
gh-77377@footnote{https://github.com/python/cpython/issues/77377}: Ensure that multiprocessing synchronization objects created in a
fork context are not sent to a different process created in a spawn
context. This changes a segfault into an actionable RuntimeError in the
parent process.

@item 
gh-106931@footnote{https://github.com/python/cpython/issues/106931}: Statically allocated string objects are now interned globally
instead of per-interpreter.  This fixes a situation where such a string
would only be interned in a single interpreter. Normal string objects are
unaffected.

@item 
gh-104621@footnote{https://github.com/python/cpython/issues/104621}: Unsupported modules now always fail to be imported.

@item 
gh-107122@footnote{https://github.com/python/cpython/issues/107122}: Add @code{dbm.ndbm.ndbm.clear()} to @ref{38,,dbm.ndbm}. Patch By
Donghee Na.

@item 
gh-107122@footnote{https://github.com/python/cpython/issues/107122}: Add @code{dbm.gnu.gdbm.clear()} to @ref{37,,dbm.gnu}. Patch By
Donghee Na.

@item 
gh-107015@footnote{https://github.com/python/cpython/issues/107015}: The ASYNC and AWAIT tokens are removed from the Grammar, which
removes the possibility of making @code{async} and @code{await} soft keywords
when using @code{feature_version<7} in @ref{1c2,,ast.parse()}.

@item 
gh-106917@footnote{https://github.com/python/cpython/issues/106917}: Fix classmethod-style @ref{1a6,,super()} method calls (i.e., where
the second argument to @ref{1a6,,super()}, or the implied second argument drawn
from @code{self/cls} in the case of zero-arg super, is a type) when the
target of the call is not a classmethod.

@item 
gh-105699@footnote{https://github.com/python/cpython/issues/105699}: Python no longer crashes due an infrequent race when
initializing per-interpreter interned strings.  The crash would manifest
when the interpreter was finalized.

@item 
gh-105699@footnote{https://github.com/python/cpython/issues/105699}: Python no longer crashes due to an infrequent race in setting
@code{Py_FileSystemDefaultEncoding} and @code{Py_FileSystemDefaultEncodeErrors}
(both deprecated), when simultaneously initializing two isolated
subinterpreters.  Now they are only set during runtime initialization.

@item 
gh-106908@footnote{https://github.com/python/cpython/issues/106908}: Fix various hangs, reference leaks, test failures, and
tracing/introspection bugs when running with 
@geindex PYTHONUOPS
@geindex 環境変数; PYTHONUOPS
@code{PYTHONUOPS} or
@ref{16f,,-X uops} enabled.

@item 
gh-106092@footnote{https://github.com/python/cpython/issues/106092}: Fix a segmentation fault caused by a use-after-free bug in
@code{frame_dealloc} when the trashcan delays the deallocation of a
@code{PyFrameObject}.

@item 
gh-106485@footnote{https://github.com/python/cpython/issues/106485}: Reduce the number of materialized instances dictionaries by
dematerializing them when possible.

@item 
gh-106719@footnote{https://github.com/python/cpython/issues/106719}: No longer suppress arbitrary errors in the @code{__annotations__}
getter and setter in the type and module types.

@item 
gh-106723@footnote{https://github.com/python/cpython/issues/106723}: Propagate @code{frozen_modules} to multiprocessing spawned process
interpreters.

@item 
gh-104909@footnote{https://github.com/python/cpython/issues/104909}: Split @code{LOAD_ATTR_INSTANCE_VALUE} into micro-ops.

@item 
gh-104909@footnote{https://github.com/python/cpython/issues/104909}: Split @ref{1a5a,,LOAD_GLOBAL} specializations into micro-ops.

@item 
gh-106597@footnote{https://github.com/python/cpython/issues/106597}: A new debug structure of offsets has been added to the
@code{_PyRuntimeState} that will help out-of-process debuggers and profilers
to obtain the offsets to relevant interpreter structures in a way that is
agnostic of how Python was compiled and that doesn't require copying the
headers. Patch by Pablo Galindo

@item 
gh-106487@footnote{https://github.com/python/cpython/issues/106487}: Allow the `count' argument of @ref{4b8,,str.replace()} to be a
keyword. Patch by Hugo van Kemenade.

@item 
gh-96844@footnote{https://github.com/python/cpython/issues/96844}: Improve error message of @ref{1a5b,,list.remove()}. Patch by Donghee
Na.

@item 
gh-81283@footnote{https://github.com/python/cpython/issues/81283}: Compiler now strips indents from docstrings. It reduces @code{pyc}
file size 5% when the module is heavily documented. This change affects to
@code{__doc__} so tools like doctest will be affected.

@item 
gh-106396@footnote{https://github.com/python/cpython/issues/106396}: When the format specification of an f-string expression is
empty, the parser now generates an empty @ref{1a5c,,ast.JoinedStr} node for
it instead of an one-element @ref{1a5c,,ast.JoinedStr} with an empty string
@ref{2ef,,ast.Constant}.

@item 
gh-100288@footnote{https://github.com/python/cpython/issues/100288}: Specialize @ref{704,,LOAD_ATTR} for non-descriptors on the
class. Adds @code{LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES} and
@code{LOAD_ATTR_NONDESCRIPTOR_NO_DICT}.

@item 
gh-106008@footnote{https://github.com/python/cpython/issues/106008}: Fix possible reference leaks when failing to optimize
comparisons with @ref{885,,None} in the bytecode compiler.

@item 
gh-106145@footnote{https://github.com/python/cpython/issues/106145}: Make @code{end_lineno} and @code{end_col_offset} required on
@code{type_param} ast nodes.

@item 
gh-106213@footnote{https://github.com/python/cpython/issues/106213}: Changed the way that Emscripten call trampolines work for
compatibility with Wasm/JS Promise integration.

@item 
gh-106182@footnote{https://github.com/python/cpython/issues/106182}: @ref{e53,,sys.getfilesystemencoding()} and
@ref{ee2,,sys.getfilesystemencodeerrors} now return interned Unicode object.

@item 
gh-106210@footnote{https://github.com/python/cpython/issues/106210}: Removed Emscripten import trampoline as it was no longer
necessary for Pyodide.

@item 
gh-104584@footnote{https://github.com/python/cpython/issues/104584}: Added a new, experimental, tracing optimizer and interpreter
(a.k.a. "tier 2"). This currently pessimizes, so don't use yet -- this is
infrastructure so we can experiment with optimizing passes. To enable it,
pass @code{-Xuops} or set @code{PYTHONUOPS=1}. To get debug output, set
@code{PYTHONUOPSDEBUG=N} where @code{N} is a debug level (0-4, where 0 is no
debug output and 4 is excessively verbose).

@item 
gh-105775@footnote{https://github.com/python/cpython/issues/105775}: @ref{1a5d,,LOAD_CLOSURE} is now a pseudo-op.

@item 
gh-105730@footnote{https://github.com/python/cpython/issues/105730}: Allow any callable other than type objects as the condition
predicate in @ref{18d8,,BaseExceptionGroup.split()} and
@ref{1a38,,BaseExceptionGroup.subgroup()}.

@item 
gh-105979@footnote{https://github.com/python/cpython/issues/105979}: Fix crash in @code{_imp.get_frozen_object()} due to improper
exception handling.

@item 
gh-106003@footnote{https://github.com/python/cpython/issues/106003}: Add a new @ref{1a5e,,TO_BOOL} instruction, which performs boolean
conversions for @ref{1a5f,,POP_JUMP_IF_TRUE}, @ref{1a60,,POP_JUMP_IF_FALSE},
and @ref{1a61,,UNARY_NOT} (which all expect exact @ref{3c3,,bool} values now).
Also, modify the oparg of @ref{b61,,COMPARE_OP} to include an optional
"boolean conversion" flag.

@item 
gh-98931@footnote{https://github.com/python/cpython/issues/98931}: Ensure custom @ref{18e,,SyntaxError} error messages are raised for
invalid imports with multiple targets. Patch by Pablo Galindo

@item 
gh-105724@footnote{https://github.com/python/cpython/issues/105724}: Improve @code{assert} error messages by providing exact error
range.

@item 
gh-105908@footnote{https://github.com/python/cpython/issues/105908}: Fixed bug where gh-99111@footnote{https://github.com/python/cpython/issues/99111} breaks future import
@code{barry_as_FLUFL} in the Python REPL.

@item 
gh-105840@footnote{https://github.com/python/cpython/issues/105840}: Fix possible crashes when specializing function calls with too
many @code{__defaults__}.

@item 
gh-105831@footnote{https://github.com/python/cpython/issues/105831}: Fix an f-string bug, where using a debug expression (the @code{=}
sign) that appears in the last line of a file results to the debug buffer
that holds the expression text being one character too small.

@item 
gh-105800@footnote{https://github.com/python/cpython/issues/105800}: Correctly issue @ref{1ae,,SyntaxWarning} in f-strings if invalid
sequences are used. Patch by Pablo Galindo

@item 
gh-105340@footnote{https://github.com/python/cpython/issues/105340}: Include the comprehension iteration variable in @code{locals()}
inside a module- or class-scope comprehension.

@item 
gh-105331@footnote{https://github.com/python/cpython/issues/105331}: Raise @ref{2ec,,ValueError} if the @code{delay} argument to
@ref{c64,,asyncio.sleep()} is a NaN (matching @ref{8ac,,time.sleep()}).

@item 
gh-105587@footnote{https://github.com/python/cpython/issues/105587}: The runtime can't guarantee that immortal objects will not be
mutated by Extensions. Thus, this modifies _PyStaticObject_CheckRefcnt to
warn instead of asserting.

@item 
gh-105564@footnote{https://github.com/python/cpython/issues/105564}: Don't include artificil newlines in the @code{line} attribute of
tokens in the APIs of the @ref{101,,tokenize} module. Patch by Pablo Galindo

@item 
gh-105549@footnote{https://github.com/python/cpython/issues/105549}: Tokenize separately @code{NUMBER} and @code{NAME} tokens that are not
ambiguous. Patch by Pablo Galindo.

@item 
gh-105588@footnote{https://github.com/python/cpython/issues/105588}: Fix an issue that could result in crashes when compiling
malformed @ref{9,,ast} nodes.

@item 
gh-100987@footnote{https://github.com/python/cpython/issues/100987}: Allow objects other than code objects as the "executable" in
internal frames. In the long term, this can help tools like Cython and
PySpy interact more efficiently. In the shorter term, it allows us to
perform some optimizations more simply.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in the @ref{13,,builtins} module where exceptions could
end up being overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bug in the compiler where an exception could end up being
overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Improve error handling in @ref{1a62,,PyUnicode_BuildEncodingMap()}
where an exception could end up being overwritten.

@item 
gh-105486@footnote{https://github.com/python/cpython/issues/105486}: Change the repr of @code{ParamSpec} list of args in
@code{types.GenericAlias}.

@item 
gh-105678@footnote{https://github.com/python/cpython/issues/105678}: Break the @code{MAKE_FUNCTION} instruction into two parts,
@code{MAKE_FUNCTION} which makes the function and @code{SET_FUNCTION_ATTRIBUTE}
which sets the attributes on the function. This makes the stack effect of
@code{MAKE_FUNCTION} regular to ease optimization and code generation.

@item 
gh-105435@footnote{https://github.com/python/cpython/issues/105435}: Fix spurious newline character if file ends on a comment
without a newline. Patch by Pablo Galindo

@item 
gh-105390@footnote{https://github.com/python/cpython/issues/105390}: Correctly raise @ref{764,,tokenize.TokenError} exceptions instead
of @ref{18e,,SyntaxError} for tokenize errors such as incomplete input. Patch
by Pablo Galindo

@item 
gh-105259@footnote{https://github.com/python/cpython/issues/105259}: Don't include newline character for trailing @code{NEWLINE} tokens
emitted in the @ref{101,,tokenize} module. Patch by Pablo Galindo

@item 
gh-104635@footnote{https://github.com/python/cpython/issues/104635}: Eliminate redundant @ref{1a63,,STORE_FAST} instructions in the
compiler. Patch by Donghee Na and Carl Meyer.

@item 
gh-105324@footnote{https://github.com/python/cpython/issues/105324}: Fix the main function of the @ref{101,,tokenize} module when
reading from @code{sys.stdin}. Patch by Pablo Galindo

@item 
gh-33092@footnote{https://github.com/python/cpython/issues/33092}: Simplify and speed up interpreter for f-strings. Removes
@code{FORMAT_VALUE} opcode. Add @code{CONVERT_VALUE}, @code{FORMAT_SIMPLE} and
@code{FORMAT_WITH_SPEC} opcode. Compiler emits more efficient sequence for
each format expression.

@item 
gh-105229@footnote{https://github.com/python/cpython/issues/105229}: Remove remaining two-codeunit superinstructions. All remaining
superinstructions only take a single codeunit, simplifying instrumentation
and quickening.

@item 
gh-105235@footnote{https://github.com/python/cpython/issues/105235}: Prevent out-of-bounds memory access during @code{mmap.find()}
calls.

@item 
gh-98963@footnote{https://github.com/python/cpython/issues/98963}: Restore the ability for a subclass of @ref{4b3,,property} to
define @code{__slots__} or otherwise be dict-less by ignoring failures to set
a docstring on such a class.  This behavior had regressed in 3.12beta1.
An @ref{5f0,,AttributeError} where there had not previously been one was
disruptive to existing code.

@item 
gh-104812@footnote{https://github.com/python/cpython/issues/104812}: The "pending call" machinery now works for all interpreters,
not just the main interpreter, and runs in all threads, not just the main
thread. Some calls are still only done in the main thread, ergo in the
main interpreter. This change does not affect signal handling nor the
existing public C-API (@code{Py_AddPendingCall()}), which both still only
target the main thread. The new functionality is meant strictly for
internal use for now, since consequences of its use are not well
understood yet outside some very restricted cases.  This change brings the
capability in line with the intention when the state was made
per-interpreter several years ago.

@item 
gh-105194@footnote{https://github.com/python/cpython/issues/105194}: Do not escape with backslashes f-string format specifiers.
Patch by Pablo Galindo

@item 
gh-105229@footnote{https://github.com/python/cpython/issues/105229}: Replace some dynamic superinstructions with single instruction
equivalents.

@item 
gh-105162@footnote{https://github.com/python/cpython/issues/105162}: Fixed bug in generator.close()/throw() where an inner iterator
would be ignored when the outer iterator was instrumented.

@item 
gh-105164@footnote{https://github.com/python/cpython/issues/105164}: Ensure annotations are set up correctly if the only annotation
in a block is within a @ref{a0e,,match} block. Patch by Jelle Zijlstra.

@item 
gh-105148@footnote{https://github.com/python/cpython/issues/105148}: Make @code{_PyASTOptimizeState} internal to ast_opt.c. Make
@code{_PyAST_Optimize} take two integers instead of a pointer to this struct.
This avoids the need to include pycore_compile.h in ast_opt.c.

@item 
gh-104799@footnote{https://github.com/python/cpython/issues/104799}: Attributes of @ref{9,,ast} nodes that are lists now default to
the empty list if omitted. This means that some code that previously
raised @ref{198,,TypeError} when the AST node was used will now proceed with
the empty list instead. Patch by Jelle Zijlstra.

@item 
gh-105111@footnote{https://github.com/python/cpython/issues/105111}: Remove the old trashcan macros @code{Py_TRASHCAN_SAFE_BEGIN} and
@code{Py_TRASHCAN_SAFE_END}. They should be replaced by the new macros
@code{Py_TRASHCAN_BEGIN} and @code{Py_TRASHCAN_END}.

@item 
gh-105035@footnote{https://github.com/python/cpython/issues/105035}: Fix @ref{1a6,,super()} calls on types with custom
@ref{1a64,,tp_getattro} implementation (e.g. meta-types.)

@item 
gh-105017@footnote{https://github.com/python/cpython/issues/105017}: Show CRLF lines in the tokenize string attribute in both NL and
NEWLINE tokens. Patch by Marta Gómez.

@item 
gh-105013@footnote{https://github.com/python/cpython/issues/105013}: Fix handling of multiline parenthesized lambdas in
@ref{17c3,,inspect.getsource()}. Patch by Pablo Galindo

@item 
gh-105017@footnote{https://github.com/python/cpython/issues/105017}: Do not include an additional final @code{NL} token when parsing
files having CRLF lines. Patch by Marta Gómez.

@item 
gh-104976@footnote{https://github.com/python/cpython/issues/104976}: Ensure that trailing @code{DEDENT} @code{tokenize.TokenInfo}
objects emitted by the @ref{101,,tokenize} module are reported as in Python
3.11. Patch by Pablo Galindo

@item 
gh-104972@footnote{https://github.com/python/cpython/issues/104972}: Ensure that the @code{line} attribute in
@code{tokenize.TokenInfo} objects in the @ref{101,,tokenize} module are
always correct. Patch by Pablo Galindo

@item 
gh-104955@footnote{https://github.com/python/cpython/issues/104955}: Fix signature for the new @ref{1a65,,__release_buffer__()}
slot. Patch by Jelle Zijlstra.

@item 
gh-104690@footnote{https://github.com/python/cpython/issues/104690}: Starting new threads and process creation through
@ref{4b5,,os.fork()} during interpreter shutdown (such as from @ref{d,,atexit}
handlers) is no longer supported.  It can lead to race condition between
the main Python runtime thread freeing thread states while internal
@ref{f3,,threading} routines are trying to allocate and use the state of just
created threads. Or forked children trying to use the mid-shutdown runtime
and thread state in the child process.

@item 
gh-104879@footnote{https://github.com/python/cpython/issues/104879}: Fix crash when accessing the @code{__module__} attribute of type
aliases defined outside a module. Patch by Jelle Zijlstra.

@item 
gh-104825@footnote{https://github.com/python/cpython/issues/104825}: Tokens emitted by the @ref{101,,tokenize} module do not include an
implicit @code{\n} character in the @code{line} attribute anymore. Patch by
Pablo Galindo

@item 
gh-104770@footnote{https://github.com/python/cpython/issues/104770}: If a generator returns a value upon being closed, the value is
now returned by @ref{1793,,generator.close()}.

@item 
gh-89091@footnote{https://github.com/python/cpython/issues/89091}: Raise @ref{4d7,,RuntimeWarning} for unawaited async generator
methods like @ref{ad6,,asend()}, @ref{71d,,athrow()} and
@ref{ad5,,aclose()}. Patch by Kumar Aditya.

@item 
gh-96663@footnote{https://github.com/python/cpython/issues/96663}: Add a better, more introspect-able error message when setting
attributes on classes without a @code{__dict__} and no slot member for the
attribute.

@item 
gh-93627@footnote{https://github.com/python/cpython/issues/93627}: Update the Python pickle module implementation to match the C
implementation of the pickle module. For objects setting reduction methods
like @ref{196b,,__reduce_ex__()} or @ref{bc6,,__reduce__()} to
@code{None}, pickling will result in a @ref{198,,TypeError}.

@item 
gh-101006@footnote{https://github.com/python/cpython/issues/101006}: Improve error handling when read @ref{91,,marshal} data.

@item 
gh-91095@footnote{https://github.com/python/cpython/issues/91095}: Specializes calls to most Python classes. Specifically, any
class that inherits from @code{object}, or another Python class, and does not
override @code{__new__}.

The specialized instruction does the following:


@enumerate 

@item 
Creates the object (by calling @code{object.__new__})

@item 
Pushes a shim frame to the frame stack (to cleanup after @code{__init__})

@item 
Pushes the frame for @code{__init__} to the frame stack
@end enumerate

Speeds up the instantiation of most Python classes.
@end itemize

@node ライブラリ<64>,ドキュメント<20>,Core and Builtins<59>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id273}@anchor{1a66}
@subsubsection ライブラリ



@itemize -

@item 
gh-110786@footnote{https://github.com/python/cpython/issues/110786}: @ref{e1,,sysconfig}'s CLI now ignores @ref{1267,,BrokenPipeError},
making it exit normally if its output is being piped and the pipe closes.

@item 
gh-103480@footnote{https://github.com/python/cpython/issues/103480}: The @ref{e1,,sysconfig} module is now a package, instead of a
single-file module.

@item 
gh-110733@footnote{https://github.com/python/cpython/issues/110733}: Micro-optimization: Avoid calling @code{min()}, @code{max()} in
@code{BaseEventLoop._run_once()}.

@item 
gh-94597@footnote{https://github.com/python/cpython/issues/94597}: Added @ref{1a67,,asyncio.EventLoop} for use with the
@ref{2f3,,asyncio.run()} `loop_factory' kwarg to avoid calling the asyncio
policy system.

@item 
gh-110682@footnote{https://github.com/python/cpython/issues/110682}: @ref{675,,runtime-checkable protocols}
used to consider @code{__match_args__} a protocol member in
@code{__instancecheck__} if it was present on the protocol. Now, this
attribute is ignored if it is present.

@item 
gh-110488@footnote{https://github.com/python/cpython/issues/110488}: Fix a couple of issues in @ref{1a68,,pathlib.PurePath.with_name()}: a
single dot was incorrectly considered a valid name, and in
@code{PureWindowsPath}, a name with an NTFS alternate data stream, like
@code{a:b}, was incorrectly considered invalid.

@item 
gh-110590@footnote{https://github.com/python/cpython/issues/110590}: Fix a bug in @code{_sre.compile()} where @ref{198,,TypeError} would
be overwritten by @ref{a81,,OverflowError} when the `code' argument was a list
of non-ints.

@item 
gh-65052@footnote{https://github.com/python/cpython/issues/65052}: Prevent @ref{aa,,pdb} from crashing when trying to display
undisplayable objects

@item 
gh-110519@footnote{https://github.com/python/cpython/issues/110519}: Deprecation warning about non-integer number in @ref{67,,gettext}
now always refers to the line in the user code where gettext function or
method is used. Previously it could refer to a line in @code{gettext} code.

@item 
gh-89902@footnote{https://github.com/python/cpython/issues/89902}: Deprecate non-standard format specifier "N" for
@ref{1fe,,decimal.Decimal}. It was not documented and only supported in the
C implementation.

@item 
gh-110378@footnote{https://github.com/python/cpython/issues/110378}: @ref{141b,,contextmanager()} and
@ref{d1f,,asynccontextmanager()} context managers now close an
invalid underlying generator object that yields more then one value.

@item 
gh-106670@footnote{https://github.com/python/cpython/issues/106670}: In @ref{aa,,pdb}, set convenience variable @code{$_exception} for
post mortem debugging.

@item 
gh-110365@footnote{https://github.com/python/cpython/issues/110365}: Fix @ref{1a69,,termios.tcsetattr()} bug that was overwriting existing
errors during parsing integers from @code{term} list.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Slightly improve the import time of several standard-library
modules by deferring imports of @ref{118,,warnings} within those modules.
Patch by Alex Waygood.

@item 
gh-110273@footnote{https://github.com/python/cpython/issues/110273}: @ref{1a6a,,dataclasses.replace()} now raises TypeError instead of
ValueError if specify keyword argument for a field declared with
init=False or miss keyword argument for required InitVar field.

@item 
gh-110249@footnote{https://github.com/python/cpython/issues/110249}: Add @code{--inline-caches} flag to @code{dis} command line.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Fix a Python 3.12 regression in the import time of
@ref{bd,,random}. Patch by Alex Waygood.

@item 
gh-110222@footnote{https://github.com/python/cpython/issues/110222}: Add support of struct sequence objects in @ref{1c0,,copy.replace()}.
Patched by Xuehai Pan.

@item 
gh-109649@footnote{https://github.com/python/cpython/issues/109649}: @ref{98,,multiprocessing}, @ref{24,,concurrent.futures},
@ref{21,,compileall}: Replace @ref{4db,,os.cpu_count()} with
@ref{4da,,os.process_cpu_count()} to select the default number of worker
threads and processes. Get the CPU affinity if supported. Patch by Victor
Stinner.

@item 
gh-110150@footnote{https://github.com/python/cpython/issues/110150}: Fix base case handling in statistics.quantiles.  Now allows a
single data point.

@item 
gh-110036@footnote{https://github.com/python/cpython/issues/110036}: On Windows, multiprocessing @code{Popen.terminate()} now catches
@ref{f3e,,PermissionError} and get the process exit code. If the process is
still running, raise again the @ref{f3e,,PermissionError}. Otherwise, the
process terminated as expected: store its exit code. Patch by Victor
Stinner.

@item 
gh-110038@footnote{https://github.com/python/cpython/issues/110038}: Fixed an issue that caused @code{KqueueSelector.select()} to not
return all the ready events in some cases when a file descriptor is
registered for both read and write.

@item 
gh-110045@footnote{https://github.com/python/cpython/issues/110045}: Update the @ref{de,,symtable} module to support the new scopes
introduced by 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}.

@item 
gh-88402@footnote{https://github.com/python/cpython/issues/88402}: Add new variables to @ref{298,,sysconfig.get_config_vars()} on
Windows: @code{LIBRARY}, @code{LDLIBRARY}, @code{LIBDIR}, @code{SOABI}, and
@code{Py_NOGIL}.

@item 
gh-109631@footnote{https://github.com/python/cpython/issues/109631}: @ref{be,,re} functions such as @ref{122b,,re.findall()},
@ref{5a2,,re.split()}, @ref{1444,,re.search()} and @ref{5a3,,re.sub()} which perform short
repeated matches can now be interrupted by user.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Reduce the import time of @ref{54,,email.utils} by around 43%.
This results in the import time of @ref{48,,email.message} falling by around
18%, which in turn reduces the import time of @ref{7e,,importlib.metadata} by
around 6%. Patch by Alex Waygood.

@item 
gh-109818@footnote{https://github.com/python/cpython/issues/109818}: Fix @ref{140c,,reprlib.recursive_repr()} not copying
@code{__type_params__} from decorated function.

@item 
gh-109047@footnote{https://github.com/python/cpython/issues/109047}: @ref{24,,concurrent.futures}: The `executor manager thread' now
catches exceptions when adding an item to the `call queue'. During Python
finalization, creating a new thread can now raise @ref{244,,RuntimeError}.
Catch the exception and call @code{terminate_broken()} in this case. Patch by
Victor Stinner.

@item 
gh-109782@footnote{https://github.com/python/cpython/issues/109782}: Ensure the signature of @ref{c05,,os.path.isdir()} is identical on
all platforms. Patch by Amin Alaee.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Improve import time of @ref{63,,functools} by around 13%. Patch by
Alex Waygood.

@item 
gh-109590@footnote{https://github.com/python/cpython/issues/109590}: @ref{6db,,shutil.which()} will prefer files with an extension in
@code{PATHEXT} if the given mode includes @code{os.X_OK} on win32. If no
@code{PATHEXT} match is found, a file without an extension in @code{PATHEXT} can
be returned. This change will have @ref{6db,,shutil.which()} act more similarly
to previous behavior in Python 3.11.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Reduce the import time of @ref{5a,,enum} by over 50%. Patch by
Alex Waygood.

@item 
gh-109593@footnote{https://github.com/python/cpython/issues/109593}: Avoid deadlocking on a reentrant call to the multiprocessing
resource tracker. Such a reentrant call, though unlikely, can happen if a
GC pass invokes the finalizer for a multiprocessing object such as
SemLock.

@item 
gh-109653@footnote{https://github.com/python/cpython/issues/109653}: Reduce the import time of @ref{10a,,typing} by around a third.
Patch by Alex Waygood.

@item 
gh-109649@footnote{https://github.com/python/cpython/issues/109649}: Add @ref{4da,,os.process_cpu_count()} function to get the number of
logical CPUs usable by the calling thread of the current process. Patch by
Victor Stinner.

@item 
gh-74481@footnote{https://github.com/python/cpython/issues/74481}: Add @code{set_error_mode} related constants in @code{msvcrt} module in
Python debug build.

@item 
gh-109613@footnote{https://github.com/python/cpython/issues/109613}: Fix @ref{26d,,os.stat()} and @ref{1a6b,,os.DirEntry.stat()}: check for
exceptions. Previously, on Python built in debug mode, these functions
could trigger a fatal Python error (and abort the process) when a function
succeeded with an exception set. Patch by Victor Stinner.

@item 
gh-109599@footnote{https://github.com/python/cpython/issues/109599}: Expose the type of PyCapsule objects as @code{types.CapsuleType}.

@item 
gh-109109@footnote{https://github.com/python/cpython/issues/109109}: You can now get the raw TLS certificate chains from TLS
connections via @ref{195c,,ssl.SSLSocket.get_verified_chain()} and
@ref{195d,,ssl.SSLSocket.get_unverified_chain()} methods.

Contributed by Mateusz Nowak.

@item 
gh-109559@footnote{https://github.com/python/cpython/issues/109559}: Update @ref{10b,,unicodedata} database to Unicode 15.1.0.

@item 
gh-109543@footnote{https://github.com/python/cpython/issues/109543}: Remove unnecessary @ref{6f9,,hasattr()} check during
@ref{332,,typing.TypedDict} creation.

@item 
gh-109495@footnote{https://github.com/python/cpython/issues/109495}: Remove unnecessary extra @code{__slots__} in
@ref{4e2,,datetime}'s pure python implementation to reduce memory
size, as they are defined in the superclass. Patch by James Hilton-Balfe

@item 
gh-109461@footnote{https://github.com/python/cpython/issues/109461}: @ref{8b,,logging}: Use a context manager for lock acquisition.

@item 
gh-109096@footnote{https://github.com/python/cpython/issues/109096}: @ref{325,,http.server.CGIHTTPRequestHandler} has been deprecated
for removal in 3.15.  Its design is old and the web world has long since
moved beyond CGI.

@item 
gh-109409@footnote{https://github.com/python/cpython/issues/109409}: Fix error when it was possible to inherit a frozen dataclass
from multiple parents some of which were possibly not frozen.

@item 
gh-109375@footnote{https://github.com/python/cpython/issues/109375}: The @ref{aa,,pdb} @code{alias} command now prevents registering
aliases without arguments.

@item 
gh-109319@footnote{https://github.com/python/cpython/issues/109319}: Deprecate the @code{dis.HAVE_ARGUMENT} field in favour of
@code{dis.hasarg}.

@item 
gh-107219@footnote{https://github.com/python/cpython/issues/107219}: Fix a race condition in @code{concurrent.futures}. When a process
in the process pool was terminated abruptly (while the future was running
or pending), close the connection write end. If the call queue is blocked
on sending bytes to a worker process, closing the connection write end
interrupts the send, so the queue can be closed. Patch by Victor Stinner.

@item 
gh-66143@footnote{https://github.com/python/cpython/issues/66143}: The @ref{1a6c,,codecs.CodecInfo} object has been made copyable and
pickleable. Patched by Robert Lehmann and Furkan Onder.

@item 
gh-109187@footnote{https://github.com/python/cpython/issues/109187}: @ref{1a6d,,pathlib.Path.resolve()} now treats symlink loops like
other errors: in strict mode, @ref{2c0,,OSError} is raised, and in non-strict
mode, no exception is raised.

@item 
gh-50644@footnote{https://github.com/python/cpython/issues/50644}: Attempts to pickle or create a shallow or deep copy of
@ref{1c,,codecs} streams now raise a TypeError. Previously, copying failed
with a RecursionError, while pickling produced wrong results that
eventually caused unpickling to fail with a RecursionError.

@item 
gh-109174@footnote{https://github.com/python/cpython/issues/109174}: Add support of @ref{4e5,,types.SimpleNamespace} in
@ref{1c0,,copy.replace()}.

@item 
gh-109164@footnote{https://github.com/python/cpython/issues/109164}: @ref{aa,,pdb}: Replace @ref{65,,getopt} with @ref{7,,argparse} for
parsing command line arguments.

@item 
gh-109151@footnote{https://github.com/python/cpython/issues/109151}: Enable @code{readline} editing features in the @ref{674,,sqlite3 command-line interface} (@code{python -m sqlite3}).

@item 
gh-108987@footnote{https://github.com/python/cpython/issues/108987}: Fix @ref{4b4,,_thread.start_new_thread()} race condition. If a
thread is created during Python finalization, the newly spawned thread now
exits immediately instead of trying to access freed memory and lead to a
crash. Patch by Victor Stinner.

@item 
gh-108682@footnote{https://github.com/python/cpython/issues/108682}: Enum: require @code{names=()} or @code{type=...} to create an empty
enum using the functional syntax.

@item 
gh-109033@footnote{https://github.com/python/cpython/issues/109033}: Exceptions raised by os.utime builtin function now include the
related filename

@item 
gh-108843@footnote{https://github.com/python/cpython/issues/108843}: Fix an issue in @ref{ae2,,ast.unparse()} when unparsing f-strings
containing many quote types.

@item 
gh-108469@footnote{https://github.com/python/cpython/issues/108469}: @ref{ae2,,ast.unparse()} now supports new @ref{66b,,f-string} syntax
introduced in Python 3.12. Note that the @ref{66b,,f-string} quotes are
reselected for simplicity under the new syntax. (Patch by Steven Sun)

@item 
gh-108751@footnote{https://github.com/python/cpython/issues/108751}: Add @ref{1c0,,copy.replace()} function which allows to create a
modified copy of an object. It supports named tuples, dataclasses, and
many other objects.

@item 
gh-108682@footnote{https://github.com/python/cpython/issues/108682}: Enum: raise @ref{198,,TypeError} if @code{super().__new__()} is called
from a custom @code{__new__}.

@item 
gh-108278@footnote{https://github.com/python/cpython/issues/108278}: Deprecate passing the callback callable by keyword for the
following @ref{54d,,sqlite3.Connection} APIs:


@itemize *

@item 
@ref{5a9,,set_authorizer()}

@item 
@ref{5aa,,set_progress_handler()}

@item 
@ref{5ab,,set_trace_callback()}
@end itemize

The affected parameters will become positional-only in Python 3.15.

Patch by Erlend E. Aasland.

@item 
gh-105829@footnote{https://github.com/python/cpython/issues/105829}: Fix concurrent.futures.ProcessPoolExecutor deadlock

@item 
gh-108295@footnote{https://github.com/python/cpython/issues/108295}: Fix crashes related to use of weakrefs on
@ref{486,,typing.TypeVar}.

@item 
gh-108463@footnote{https://github.com/python/cpython/issues/108463}: Make expressions/statements work as expected in pdb

@item 
gh-108277@footnote{https://github.com/python/cpython/issues/108277}: Add @ref{51f,,os.timerfd_create()}, @ref{520,,os.timerfd_settime()},
@ref{522,,os.timerfd_gettime()}, @ref{521,,os.timerfd_settime_ns()}, and
@ref{523,,os.timerfd_gettime_ns()} to provide a low level interface for Linux's
timer notification file descriptor.

@item 
gh-107811@footnote{https://github.com/python/cpython/issues/107811}: @ref{e4,,tarfile}: extraction of members with overly large UID or
GID (e.g. on an OS with 32-bit @code{id_t}) now fails in the same way
as failing to set the ID.

@item 
gh-64662@footnote{https://github.com/python/cpython/issues/64662}: Fix support for virtual tables in
@ref{54f,,sqlite3.Connection.iterdump()}. Patch by Aviv Palivoda.

@item 
gh-108111@footnote{https://github.com/python/cpython/issues/108111}: Fix a regression introduced in gh-101251@footnote{https://github.com/python/cpython/issues/101251} for 3.12, resulting in
an incorrect offset calculation in @code{gzip.GzipFile.seek()}.

@item 
gh-108294@footnote{https://github.com/python/cpython/issues/108294}: @ref{8ac,,time.sleep()} now raises an auditing event.

@item 
gh-108278@footnote{https://github.com/python/cpython/issues/108278}: Deprecate passing name, number of arguments, and the callable
as keyword arguments, for the following @ref{54d,,sqlite3.Connection} APIs:


@itemize *

@item 
@ref{5a7,,create_function()}

@item 
@ref{5a8,,create_aggregate()}
@end itemize

The affected parameters will become positional-only in Python 3.15.

Patch by Erlend E. Aasland.

@item 
gh-108322@footnote{https://github.com/python/cpython/issues/108322}: Speed-up NormalDist.samples() by using the inverse CDF method
instead of calling random.gauss().

@item 
gh-83417@footnote{https://github.com/python/cpython/issues/83417}: Add the ability for venv to create a @code{.gitignore} file which
causes the created environment to be ignored by Git. It is on by default
when venv is called via its CLI.

@item 
gh-105736@footnote{https://github.com/python/cpython/issues/105736}: Harmonized the pure Python version of
@ref{7f3,,OrderedDict} with the C version. Now, both versions
set up their internal state in @code{__new__}.  Formerly, the pure Python
version did the set up in @code{__init__}.

@item 
gh-108083@footnote{https://github.com/python/cpython/issues/108083}: Fix bugs in the constructor of @ref{54d,,sqlite3.Connection} and
@ref{54e,,sqlite3.Connection.close()} where exceptions could be leaked. Patch
by Erlend E. Aasland.

@item 
gh-107932@footnote{https://github.com/python/cpython/issues/107932}: Fix @code{dis} module to properly report and display bytecode that
do not have source lines.

@item 
gh-105539@footnote{https://github.com/python/cpython/issues/105539}: @ref{d4,,sqlite3} now emits an @ref{54c,,ResourceWarning} if a
@ref{54d,,sqlite3.Connection} object is not @code{closed} explicitly. Patch by Erlend E. Aasland.

@item 
gh-107995@footnote{https://github.com/python/cpython/issues/107995}: The @code{__module__} attribute on instances of
@ref{763,,functools.cached_property} is now set to the name of the module in
which the cached_property is defined, rather than "functools". This means
that doctests in @code{cached_property} docstrings are now properly collected
by the @ref{3e,,doctest} module. Patch by Tyler Smart.

@item 
gh-107963@footnote{https://github.com/python/cpython/issues/107963}: Fix @ref{1908,,multiprocessing.set_forkserver_preload()} to check the
given list of modules names. Patch by Donghee Na.

@item 
gh-106242@footnote{https://github.com/python/cpython/issues/106242}: Fixes @ref{1531,,os.path.normpath()} to handle embedded null
characters without truncating the path.

@item 
gh-81555@footnote{https://github.com/python/cpython/issues/81555}: @ref{128,,xml.dom.minidom} now only quotes @code{"} in attributes.

@item 
gh-50002@footnote{https://github.com/python/cpython/issues/50002}: @ref{128,,xml.dom.minidom} now preserves whitespaces in attributes.

@item 
gh-93057@footnote{https://github.com/python/cpython/issues/93057}: Passing more than one positional argument to
@ref{5a6,,sqlite3.connect()} and the @ref{54d,,sqlite3.Connection} constructor is
deprecated. The remaining parameters will become keyword-only in Python
3.15. Patch by Erlend E. Aasland.

@item 
gh-76913@footnote{https://github.com/python/cpython/issues/76913}: Add `merge_extra' parameter/feature to
@ref{150d,,logging.LoggerAdapter}

@item 
gh-107913@footnote{https://github.com/python/cpython/issues/107913}: Fix possible losses of @code{errno} and @code{winerror} values in
@ref{2c0,,OSError} exceptions if they were cleared or modified by the cleanup
code before creating the exception object.

@item 
gh-107845@footnote{https://github.com/python/cpython/issues/107845}: @ref{29a,,tarfile.data_filter()} now takes the location of symlinks
into account when determining their target, so it will no longer reject
some valid tarballs with @code{LinkOutsideDestinationError}.

@item 
gh-107812@footnote{https://github.com/python/cpython/issues/107812}: Extend socket's netlink support to the FreeBSD platform.

@item 
gh-107805@footnote{https://github.com/python/cpython/issues/107805}: Fix signatures of module-level generated functions in
@ref{107,,turtle}.

@item 
gh-107782@footnote{https://github.com/python/cpython/issues/107782}: @ref{ba,,pydoc} is now able to show signatures which are not
representable in Python, e.g. for @code{getattr} and @code{dict.pop}.

@item 
gh-56166@footnote{https://github.com/python/cpython/issues/56166}: Deprecate passing optional arguments `maxsplit', `count' and
`flags' in module-level functions @ref{5a2,,re.split()}, @ref{5a3,,re.sub()} and
@ref{5a4,,re.subn()} as positional. They should only be passed by keyword.

@item 
gh-107710@footnote{https://github.com/python/cpython/issues/107710}: Speed up @ref{1a6e,,logging.getHandlerNames()}.

@item 
gh-107715@footnote{https://github.com/python/cpython/issues/107715}: Fix @ref{1a6f,,doctest.DocTestFinder.find()} in presence of class
names with special characters. Patch by Gertjan van Zwieten.

@item 
gh-100814@footnote{https://github.com/python/cpython/issues/100814}: Passing a callable object as an option value to a Tkinter image
now raises the expected TclError instead of an AttributeError.

@item 
gh-72684@footnote{https://github.com/python/cpython/issues/72684}: Add @ref{f6,,tkinter} widget methods: @code{tk_busy_hold()},
@code{tk_busy_configure()}, @code{tk_busy_cget()},
@code{tk_busy_forget()}, @code{tk_busy_current()}, and
@code{tk_busy_status()}.

@item 
gh-106684@footnote{https://github.com/python/cpython/issues/106684}: Raise @ref{54c,,ResourceWarning} when @ref{1a70,,asyncio.StreamWriter}
is not closed leading to memory leaks. Patch by Kumar Aditya.

@item 
gh-107465@footnote{https://github.com/python/cpython/issues/107465}: Add @ref{534,,pathlib.Path.from_uri()} classmethod.

@item 
gh-107077@footnote{https://github.com/python/cpython/issues/107077}: Seems that in some conditions, OpenSSL will return
@code{SSL_ERROR_SYSCALL} instead of @code{SSL_ERROR_SSL} when a certification
verification has failed, but the error parameters will still contain
@code{ERR_LIB_SSL} and @code{SSL_R_CERTIFICATE_VERIFY_FAILED}. We are now
detecting this situation and raising the appropriate
@code{ssl.SSLCertVerificationError}. Patch by Pablo Galindo

@item 
gh-107576@footnote{https://github.com/python/cpython/issues/107576}: Fix @ref{6f5,,types.get_original_bases()} to only return
@code{__orig_bases__} if it is present on @code{cls} directly. Patch by
James Hilton-Balfe.

@item 
gh-105481@footnote{https://github.com/python/cpython/issues/105481}: Remove @code{opcode.is_pseudo}, @code{opcode.MIN_PSEUDO_OPCODE} and
@code{opcode.MAX_PSEUDO_OPCODE}, which were added in 3.12, were never
documented and were not intended to be used externally.

@item 
gh-105481@footnote{https://github.com/python/cpython/issues/105481}: @code{opcode.ENABLE_SPECIALIZATION} (which was added in 3.12
but never documented or intended for external usage) is moved to
@code{_opcode.ENABLE_SPECIALIZATION} where tests can access it.

@item 
gh-107396@footnote{https://github.com/python/cpython/issues/107396}: tarfiles; Fixed use before assignment of self.exception for
gzip decompression

@item 
gh-107409@footnote{https://github.com/python/cpython/issues/107409}: Set @code{__wrapped__} attribute in
@ref{140c,,reprlib.recursive_repr()}.

@item 
gh-107406@footnote{https://github.com/python/cpython/issues/107406}: Implement new @code{__repr__()} method for
@ref{1778,,struct.Struct}. Now it returns @code{Struct(<format repr>)}.

@item 
gh-107369@footnote{https://github.com/python/cpython/issues/107369}: Optimize @ref{57d,,textwrap.indent()}. It is ~30% faster for large
input. Patch by Inada Naoki.

@item 
gh-78722@footnote{https://github.com/python/cpython/issues/78722}: Fix issue where @ref{26e,,pathlib.Path.iterdir()} did not raise
@ref{2c0,,OSError} until iterated.

@item 
gh-105578@footnote{https://github.com/python/cpython/issues/105578}: Deprecate @ref{5ac,,typing.AnyStr} in favor of the new Type
Parameter syntax. See PEP 695.

@item 
gh-62519@footnote{https://github.com/python/cpython/issues/62519}: Make @ref{be8,,gettext.pgettext()} search plural definitions when
translation is not found.

@item 
gh-107089@footnote{https://github.com/python/cpython/issues/107089}: Shelves opened with @ref{1a71,,shelve.open()} have a much faster
@code{clear()} method. Patch by James Cave.

@item 
gh-82500@footnote{https://github.com/python/cpython/issues/82500}: Fix overflow on 32-bit systems with @ref{b,,asyncio}
@ref{d05,,os.sendfile()} implementation.

@item 
gh-83006@footnote{https://github.com/python/cpython/issues/83006}: Document behavior of @ref{1345,,shutil.disk_usage()} for non-mounted
filesystems on Unix.

@item 
gh-65495@footnote{https://github.com/python/cpython/issues/65495}: Use lowercase @code{mail from} and @code{rcpt to} in
@code{smptlib.SMTP}.

@item 
gh-106186@footnote{https://github.com/python/cpython/issues/106186}: Do not report @code{MultipartInvariantViolationDefect} defect when
the @ref{13b5,,email.parser.Parser} class is used to parse emails with
@code{headersonly=True}.

@item 
gh-105002@footnote{https://github.com/python/cpython/issues/105002}: Fix invalid result from @code{PurePath.relative_to()} method
when attempting to walk a "@code{..}" segment in `other' with `walk_up'
enabled. A @ref{2ec,,ValueError} exception is now raised in this case.

@item 
gh-106739@footnote{https://github.com/python/cpython/issues/106739}: Add the @code{rtype_cache} to the warning message (as an addition
to the type of leaked objects and the number of leaked objects already
included in the message) to make debugging leaked objects easier when the
multiprocessing resource tracker process finds leaked objects at shutdown.
This helps more quickly identify what was leaked and/or why the leaked
object was not properly cleaned up.

@item 
gh-106751@footnote{https://github.com/python/cpython/issues/106751}: Optimize @code{SelectSelector.select()} for many iteration case.
Patch By Donghee Na.

@item 
gh-106751@footnote{https://github.com/python/cpython/issues/106751}: Optimize @code{_PollLikeSelector.select()} for many iteration
case.

@item 
gh-106751@footnote{https://github.com/python/cpython/issues/106751}: Optimize @code{KqueueSelector.select()} for many iteration case.
Patch By Donghee Na.

@item 
gh-106831@footnote{https://github.com/python/cpython/issues/106831}: Fix potential missing @code{NULL} check of @code{d2i_SSL_SESSION}
result in @code{_ssl.c}.

@item 
gh-105481@footnote{https://github.com/python/cpython/issues/105481}: The various opcode lists in the @ref{3c,,dis} module are now
generated from bytecodes.c instead of explicitly constructed in opcode.py.

@item 
gh-106727@footnote{https://github.com/python/cpython/issues/106727}: Make @ref{17c3,,inspect.getsource()} smarter for class for same name
definitions

@item 
gh-106789@footnote{https://github.com/python/cpython/issues/106789}: Remove import of @ref{b3,,pprint} from @ref{e1,,sysconfig}.

@item 
gh-105726@footnote{https://github.com/python/cpython/issues/105726}: Added @code{__slots__} to
@ref{e8a,,contextlib.AbstractContextManager} and
@ref{d20,,contextlib.AbstractAsyncContextManager} so that child classes can
use @code{__slots__}.

@item 
gh-106774@footnote{https://github.com/python/cpython/issues/106774}: Update the bundled copy of pip to version 23.2.1.

@item 
gh-106751@footnote{https://github.com/python/cpython/issues/106751}: @ref{c7,,selectors}: Optimize @code{EpollSelector.select()} code by
moving some code outside of the loop.

@item 
gh-106752@footnote{https://github.com/python/cpython/issues/106752}: Fixed several bugs in zipfile.Path, including: in
@code{zipfile.Path.match()}, Windows separators are no longer honored (and
never were meant to be); Fixed @code{name}/@code{suffix}/@code{suffixes}/@code{stem}
operations when no filename is present and the Path is not at the root of
the zipfile; Reworked glob for performance and more correct matching
behavior.

@item 
gh-105293@footnote{https://github.com/python/cpython/issues/105293}: Remove call to @code{SSL_CTX_set_session_id_context} during client
side context creation in the @ref{d5,,ssl} module.

@item 
gh-106734@footnote{https://github.com/python/cpython/issues/106734}: Disable tab completion in multiline mode of @ref{aa,,pdb}

@item 
gh-105481@footnote{https://github.com/python/cpython/issues/105481}: Expose opcode metadata through @code{_opcode}.

@item 
gh-106670@footnote{https://github.com/python/cpython/issues/106670}: Add the new @code{exceptions} command to the Pdb debugger. It
makes it possible to move between chained exceptions when using post
mortem debugging.

@item 
gh-106602@footnote{https://github.com/python/cpython/issues/106602}: Add __copy__ and __deepcopy__ in @ref{5a,,enum}

@item 
gh-106664@footnote{https://github.com/python/cpython/issues/106664}: @ref{c7,,selectors}: Add @code{_SelectorMapping.get()} method and
optimize @code{_SelectorMapping.__getitem__()}.

@item 
gh-106628@footnote{https://github.com/python/cpython/issues/106628}: Speed up parsing of emails by about 20% by not compiling a new
regular expression for every single email.

@item 
gh-89427@footnote{https://github.com/python/cpython/issues/89427}: Set the environment variable @code{VIRTUAL_ENV_PROMPT} at
@ref{117,,venv} activation, even when @code{VIRTUAL_ENV_DISABLE_PROMPT} is set.

@item 
gh-106530@footnote{https://github.com/python/cpython/issues/106530}: Revert a change to @ref{1a72,,colorsys.rgb_to_hls()} that caused
division by zero for certain almost-white inputs.  Patch by Terry Jan
Reedy.

@item 
gh-106584@footnote{https://github.com/python/cpython/issues/106584}: Fix exit code for @code{unittest} if all tests are skipped. Patch
by Egor Eliseev.

@item 
gh-106566@footnote{https://github.com/python/cpython/issues/106566}: Optimize @code{(?!)} (pattern which always fails) in regular
expressions.

@item 
gh-106554@footnote{https://github.com/python/cpython/issues/106554}: @ref{c7,,selectors}: Reduce Selector overhead by using a
@code{dict.get()} to lookup file descriptors.

@item 
gh-106558@footnote{https://github.com/python/cpython/issues/106558}: Remove ref cycle in callers of
@code{convert_to_error()} by deleting @code{result}
from scope in a @code{finally} block.

@item 
gh-100502@footnote{https://github.com/python/cpython/issues/100502}: Add @code{pathlib.PurePath.pathmod} class attribute that
stores the implementation of @ref{a6,,os.path} used for low-level path
operations: either @code{posixpath} or @code{ntpath}.

@item 
gh-106527@footnote{https://github.com/python/cpython/issues/106527}: Reduce overhead to add and remove @ref{b,,asyncio} readers and
writers.

@item 
gh-106524@footnote{https://github.com/python/cpython/issues/106524}: Fix crash in @code{_sre.template()} with templates containing
invalid group indices.

@item 
gh-106531@footnote{https://github.com/python/cpython/issues/106531}: Removed @code{_legacy} and the names it provided from
@code{importlib.resources}: @code{Resource}, @code{contents}, @code{is_resource},
@code{open_binary}, @code{open_text}, @code{path}, @code{read_binary}, and
@code{read_text}.

@item 
gh-106052@footnote{https://github.com/python/cpython/issues/106052}: @ref{be,,re} module: fix the matching of possessive quantifiers in
the case of a subpattern containing backtracking.

@item 
gh-106510@footnote{https://github.com/python/cpython/issues/106510}: Improve debug output for atomic groups in regular expressions.

@item 
gh-106503@footnote{https://github.com/python/cpython/issues/106503}: Fix ref cycle in @code{asyncio._SelectorSocketTransport} by
removing @code{_write_ready} in @code{close}.

@item 
gh-105497@footnote{https://github.com/python/cpython/issues/105497}: Fix flag mask inversion when unnamed flags exist.

@item 
gh-90876@footnote{https://github.com/python/cpython/issues/90876}: Prevent @code{multiprocessing.spawn} from failing to `import' in
environments where @code{sys.executable} is @code{None}.  This regressed in 3.11
with the addition of support for path-like objects in multiprocessing.

@item 
gh-106403@footnote{https://github.com/python/cpython/issues/106403}: Instances of @ref{486,,typing.TypeVar},
@ref{487,,typing.ParamSpec}, @ref{9c9,,typing.ParamSpecArgs},
@ref{9ca,,typing.ParamSpecKwargs}, and @ref{488,,typing.TypeVarTuple} once
again support weak references, fixing a regression introduced in Python
3.12.0 beta 1. Patch by Jelle Zijlstra.

@item 
gh-89812@footnote{https://github.com/python/cpython/issues/89812}: Add private @code{pathlib._PathBase} class, which provides
experimental support for virtual filesystems, and may be made public in a
future version of Python.

@item 
gh-106292@footnote{https://github.com/python/cpython/issues/106292}: Check for an instance-dict cached value in the @code{__get__()}
method of @ref{763,,functools.cached_property()}. This better matches the
pre-3.12 behavior and improves compatibility for users subclassing
@ref{763,,functools.cached_property()} and adding a @code{__set__()} method.

@item 
gh-106350@footnote{https://github.com/python/cpython/issues/106350}: Detect possible memory allocation failure in the libtommath
function @code{mp_init()} used by the @code{_tkinter} module.

@item 
gh-106330@footnote{https://github.com/python/cpython/issues/106330}: Fix incorrect matching of empty paths in
@ref{6d3,,pathlib.PurePath.match()}. This bug was introduced in Python 3.12.0
beta 1.

@item 
gh-106309@footnote{https://github.com/python/cpython/issues/106309}: Deprecate @ref{333,,typing.no_type_check_decorator()}. No major type
checker ever added support for this decorator. Patch by Alex Waygood.

@item 
gh-102541@footnote{https://github.com/python/cpython/issues/102541}: Make @code{pydoc.doc()} catch bad module @ref{65b,,ImportError} when
output stream is not @code{None}.

@item 
gh-106263@footnote{https://github.com/python/cpython/issues/106263}: Fix crash when calling @code{repr} with a manually constructed
SignalDict object. Patch by Charlie Zhao.

@item 
gh-106236@footnote{https://github.com/python/cpython/issues/106236}: Replace @code{assert} statements with @code{raise RuntimeError} in
@ref{f3,,threading}, so that @code{_DummyThread} cannot be joined even with
@code{-OO}.

@item 
gh-106238@footnote{https://github.com/python/cpython/issues/106238}: Fix rare concurrency bug in lock acquisition by the logging
package.

@item 
gh-106152@footnote{https://github.com/python/cpython/issues/106152}: Added PY_THROW event hook for @ref{2b,,cProfile} for generators

@item 
gh-106075@footnote{https://github.com/python/cpython/issues/106075}: Added @code{asyncio.taskgroups.__all__} to @code{asyncio.__all__} for
export in star imports.

@item 
gh-104527@footnote{https://github.com/python/cpython/issues/104527}: Zipapp will now skip over appending an archive to itself.

@item 
gh-106046@footnote{https://github.com/python/cpython/issues/106046}: Improve the error message from @ref{e4d,,os.fspath()} if called on
an object where @code{__fspath__} is set to @code{None}. Patch by Alex Waygood.

@item 
gh-105987@footnote{https://github.com/python/cpython/issues/105987}: Fix crash due to improper reference counting in @ref{b,,asyncio}
eager task factory internal routines.

@item 
gh-105974@footnote{https://github.com/python/cpython/issues/105974}: Fix bug where a @ref{56b,,typing.Protocol} class that had one or
more non-callable members would raise @ref{198,,TypeError} when
@ref{9c4,,issubclass()} was called against it, even if it defined a custom
@code{__subclasshook__} method. The behaviour in Python 3.11 and lower --
which has now been restored -- was not to raise @ref{198,,TypeError} in these
situations if a custom @code{__subclasshook__} method was defined. Patch by
Alex Waygood.

@item 
gh-96145@footnote{https://github.com/python/cpython/issues/96145}: Reverted addition of @code{json.AttrDict}.

@item 
gh-89812@footnote{https://github.com/python/cpython/issues/89812}: Add @ref{533,,pathlib.UnsupportedOperation}, which is raised instead
of @ref{36b,,NotImplementedError} when a path operation isn't supported.

@item 
gh-105808@footnote{https://github.com/python/cpython/issues/105808}: Fix a regression introduced in gh-101251@footnote{https://github.com/python/cpython/issues/101251} for 3.12, causing
@code{gzip.GzipFile.flush()} to not flush the compressor (nor pass along
the @code{zip_mode} argument).

@item 
gh-105481@footnote{https://github.com/python/cpython/issues/105481}: @ref{1132,,stack_effect()} no longer raises an exception if an
@code{oparg} is provided for an @code{opcode} that doesn't use its arg, or when
it is not provided for an @code{opcode} that does use it. In the latter case,
the stack effect is returned for @code{oparg=0}.

@item 
gh-104799@footnote{https://github.com/python/cpython/issues/104799}: Enable @ref{ae2,,ast.unparse()} to unparse function and class
definitions created without the new @code{type_params} field from 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}.
Patch by Jelle Zijlstra.

@item 
gh-105793@footnote{https://github.com/python/cpython/issues/105793}: Add `follow_symlinks' keyword-only argument to
@ref{53a,,pathlib.Path.is_dir()} and @ref{539,,is_file()}, defaulting
to @code{True}.

@item 
gh-105570@footnote{https://github.com/python/cpython/issues/105570}: Deprecate two methods of creating @ref{332,,typing.TypedDict}
classes with 0 fields using the functional syntax: @code{TD =
TypedDict("TD")} and @code{TD = TypedDict("TD", None)}. Both will be
disallowed in Python 3.15. To create a @code{TypedDict} class with 0 fields,
either use @code{class TD(TypedDict): pass} or @code{TD = TypedDict("TD", @{@})}.

@item 
gh-105745@footnote{https://github.com/python/cpython/issues/105745}: Fix @code{webbrowser.Konqueror.open} method.

@item 
gh-105733@footnote{https://github.com/python/cpython/issues/105733}: @ref{2e,,ctypes}: Deprecate undocumented
@code{ctypes.SetPointerType()} and @code{ctypes.ARRAY()} functions. Patch
by Victor Stinner.

@item 
gh-105687@footnote{https://github.com/python/cpython/issues/105687}: Remove deprecated @code{re.template}, @code{re.T}, @code{re.TEMPLATE},
@code{sre_constans.SRE_FLAG_TEMPLATE}.

@item 
gh-105684@footnote{https://github.com/python/cpython/issues/105684}: Supporting @ref{bd0,,asyncio.Task.set_name()} is now mandatory for
third party task implementations. The undocumented @code{_set_task_name()}
function (deprecated since 3.8) has been removed. Patch by Kumar Aditya.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix a bug in @code{_Unpickler_SetInputStream()} where an
exception could end up being overwritten in case of failure.

@item 
gh-105626@footnote{https://github.com/python/cpython/issues/105626}: Change the default return value of
@ref{1a73,,http.client.HTTPConnection.get_proxy_response_headers()} to be
@code{None} and not @code{@{@}}.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @ref{df,,sys} where exceptions could end up being
overwritten because of deferred error handling.

@item 
gh-105605@footnote{https://github.com/python/cpython/issues/105605}: Harden @code{pyexpat} error handling during module
initialisation to prevent exceptions from possibly being overwritten, and
objects from being dereferenced twice.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bug in @ref{3a,,decimal} where an exception could end up being
overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @code{_datetime} where exceptions could be
overwritten in case of module initialisation failure.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @code{_ssl} initialisation which could lead to
leaked references and overwritten exceptions.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix a bug in @ref{4be,,array.array} where an exception could end
up being overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @code{_ctypes} where exceptions could end up being
overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix a bug in the @ref{b2,,posix} module where an exception could
be overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @code{_elementtree} where exceptions could be
overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @ref{13a,,zoneinfo} where exceptions could be
overwritten.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @ref{5b,,errno} where exceptions could be overwritten.

@item 
gh-105566@footnote{https://github.com/python/cpython/issues/105566}: Deprecate creating a @ref{331,,typing.NamedTuple} class using
keyword arguments to denote the fields (@code{NT = NamedTuple("NT", x=int,
y=str)}). This will be disallowed in Python 3.15. Use the class-based
syntax or the functional syntax instead.

Two methods of creating @code{NamedTuple} classes with 0 fields using the
functional syntax are also deprecated, and will be disallowed in Python
3.15: @code{NT = NamedTuple("NT")} and @code{NT = NamedTuple("NT", None)}. To
create a @code{NamedTuple} class with 0 fields, either use @code{class
NT(NamedTuple): pass} or @code{NT = NamedTuple("NT", [])}.

@item 
gh-105545@footnote{https://github.com/python/cpython/issues/105545}: Remove deprecated in 3.11 @code{webbrowser.MacOSXOSAScript._name}
attribute.

@item 
gh-105497@footnote{https://github.com/python/cpython/issues/105497}: Fix flag inversion when alias/mask members exist.

@item 
gh-105509@footnote{https://github.com/python/cpython/issues/105509}: @ref{b37,,typing.Annotated} is now implemented as an instance of
@code{typing._SpecialForm} rather than a class. This should have no
user-facing impact for users of the @ref{10a,,typing} module public API.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix bugs in @ref{ab,,pickle} where exceptions could be
overwritten.

@item 
gh-70303@footnote{https://github.com/python/cpython/issues/70303}: Emit @ref{659,,FutureWarning} from @ref{537,,pathlib.Path.glob()} and
@ref{538,,rglob()} if the given pattern ends with "@code{**}". In a
future Python release, patterns with this ending will match both files and
directories. Add a trailing slash to only match directories.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix a bug in @ref{d4,,sqlite3} where an exception could be
overwritten in the @ref{886,,collation}
callback.

@item 
gh-105382@footnote{https://github.com/python/cpython/issues/105382}: Remove `cafile', `capath' and `cadefault' parameters of the
@ref{307,,urllib.request.urlopen()} function, deprecated in Python 3.6. Patch
by Victor Stinner.

@item 
gh-105376@footnote{https://github.com/python/cpython/issues/105376}: @ref{8b,,logging}: Remove undocumented and untested
@code{Logger.warn()} and @code{LoggerAdapter.warn()} methods and
@code{logging.warn()} function. Deprecated since Python 3.3, they were
aliases to the @ref{1a74,,logging.Logger.warning()} method,
@code{logging.LoggerAdapter.warning()} method and @ref{354,,logging.warning()}
function. Patch by Victor Stinner.

@item 
gh-105332@footnote{https://github.com/python/cpython/issues/105332}: Revert pickling method from by-name back to by-value.

@item 
gh-104554@footnote{https://github.com/python/cpython/issues/104554}: Add RTSPS scheme support in urllib.parse

@item 
gh-105292@footnote{https://github.com/python/cpython/issues/105292}: Add option to @ref{a4e,,traceback.format_exception_only()} to
recurse into the nested exception of a @ref{566,,BaseExceptionGroup}.

@item 
gh-105280@footnote{https://github.com/python/cpython/issues/105280}: Fix bug where @code{isinstance([], collections.abc.Mapping)} could
evaluate to @code{True} if garbage collection happened at the wrong time. The
bug was caused by changes to the implementation of
@ref{56b,,typing.Protocol} in Python 3.12.

@item 
gh-80480@footnote{https://github.com/python/cpython/issues/80480}: @ref{8,,array}: Add @code{'w'} typecode that represents @code{Py_UCS4}.

@item 
gh-105239@footnote{https://github.com/python/cpython/issues/105239}: Fix longstanding bug where @code{issubclass(object,
typing.Protocol)} would evaluate to @code{True} in some edge cases. Patch by
Alex Waygood.

@item 
gh-104310@footnote{https://github.com/python/cpython/issues/104310}: In the beta 1 release we added a utility function for extension
module authors, to use when testing their module for support in multiple
interpreters or under a per-interpreter GIL.  The name of that function
has changed from @code{allowing_all_extensions} to
@code{_incompatible_extension_module_restrictions}.  The default for the
"disable_check" argument has change from @code{True} to @code{False}, to better
match the new function name.

@item 
gh-105080@footnote{https://github.com/python/cpython/issues/105080}: Fixed inconsistent signature on derived classes for
@ref{22f,,inspect.signature()}

@item 
gh-105144@footnote{https://github.com/python/cpython/issues/105144}: Fix a recent regression in the @ref{10a,,typing} module. The
regression meant that doing @code{class Foo(X, typing.Protocol)}, where @code{X}
was a class that had @ref{111c,,abc.ABCMeta} as its metaclass, would then
cause subsequent @code{isinstance(1, X)} calls to erroneously raise
@ref{198,,TypeError}. Patch by Alex Waygood.

@item 
gh-62948@footnote{https://github.com/python/cpython/issues/62948}: The @ref{505,,io.IOBase} finalizer now logs the @code{close()} method
errors with @ref{507,,sys.unraisablehook}. Previously, errors were ignored
silently by default, and only logged in @ref{508,,Python Development Mode} or on @ref{509,,Python built on debug mode}.  Patch
by Victor Stinner.

@item 
gh-105096@footnote{https://github.com/python/cpython/issues/105096}: @ref{119,,wave}: Deprecate the @code{getmark()}, @code{setmark()} and
@code{getmarkers()} methods of the @ref{336,,wave.Wave_read} and
@ref{337,,wave.Wave_write} classes. They will be removed in Python 3.15.
Patch by Victor Stinner.

@item 
gh-104992@footnote{https://github.com/python/cpython/issues/104992}: Remove the untested and undocumented
@code{unittest.TestProgram.usageExit()} method, deprecated in Python 3.11.
Patch by Hugo van Kemenade.

@item 
gh-104996@footnote{https://github.com/python/cpython/issues/104996}: Improve performance of @ref{6cd,,pathlib.PurePath} initialisation
by deferring joining of paths when multiple arguments are given.

@item 
gh-101588@footnote{https://github.com/python/cpython/issues/101588}: Deprecate undocumented copy/deepcopy/pickle support for
itertools.

@item 
gh-103631@footnote{https://github.com/python/cpython/issues/103631}: Fix @code{pathlib.PurePosixPath(pathlib.PureWindowsPath(...))} not
converting path separators to restore 3.11 compatible behavior.

@item 
gh-104947@footnote{https://github.com/python/cpython/issues/104947}: Make comparisons between @ref{1a75,,pathlib.PureWindowsPath}
objects consistent across Windows and Posix to match 3.11 behavior.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{audioop} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{aifc} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{uu} module, deprecated in Python
3.11. Patch by Victor Stinner.

@item 
gh-104935@footnote{https://github.com/python/cpython/issues/104935}: Fix bugs with the interaction between
@ref{675,,typing.runtime_checkable()} and @ref{17b6,,typing.Generic} that were
introduced by the 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} implementation. Patch by Jelle Zijlstra.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{crypt} module and its private
@code{_crypt} extension, deprecated in Python 3.11. Patch by Victor
Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{nis} module, deprecated in Python
3.11. Patch by Victor Stinner.

@item 
gh-104898@footnote{https://github.com/python/cpython/issues/104898}: Add missing @ref{1704,,__slots__} to @ref{e4b,,os.PathLike}.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{xdrlib} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{nntplib} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104886@footnote{https://github.com/python/cpython/issues/104886}: Remove the undocumented
@code{configparser.LegacyInterpolation} class, deprecated in the
docstring since Python 3.2, and with a deprecation warning since Python
3.11. Patch by Hugo van Kemenade.

@item 
gh-104786@footnote{https://github.com/python/cpython/issues/104786}: Remove kwargs-based @ref{332,,typing.TypedDict} creation

@item 
gh-104876@footnote{https://github.com/python/cpython/issues/104876}: Remove the @code{turtle.RawTurtle.settiltangle()} method,
deprecated in docs since Python 3.1 and with a deprecation warning since
Python 3.11. Patch by Hugo van Kemenade.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Removed the @code{msilib} package, deprecated in
Python 3.11.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{spwd} module, deprecated in
Python 3.11: the python-pam@footnote{https://pypi.org/project/python-pam/} project can be used instead. Patch by
Victor Stinner.

@item 
gh-75552@footnote{https://github.com/python/cpython/issues/75552}: Removed the @code{tkinter.tix} module, deprecated since Python 3.6.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{chunk} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{mailcap} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{sunau} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104780@footnote{https://github.com/python/cpython/issues/104780}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{ossaudiodev} module, deprecated
in Python 3.11. Patch Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{pipes} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104873@footnote{https://github.com/python/cpython/issues/104873}: Add @ref{56a,,typing.get_protocol_members()} to return the set of
members defining a @ref{56b,,typing.Protocol}.  Add
@ref{56c,,typing.is_protocol()} to check whether a class is a
@ref{56b,,typing.Protocol}. Patch by Jelle Zijlstra.

@item 
gh-104874@footnote{https://github.com/python/cpython/issues/104874}: Document the @code{__name__} and @code{__supertype__} attributes of
@ref{ef1,,typing.NewType}. Patch by Jelle Zijlstra.

@item 
gh-104835@footnote{https://github.com/python/cpython/issues/104835}: Removed the following @ref{10c,,unittest} functions, deprecated in
Python 3.11:


@itemize *

@item 
@code{unittest.findTestCases()}

@item 
@code{unittest.makeSuite()}

@item 
@code{unittest.getTestCaseNames()}
@end itemize

Use @ref{593,,TestLoader} methods instead:


@itemize *

@item 
@ref{594,,unittest.TestLoader.loadTestsFromModule()}

@item 
@ref{595,,unittest.TestLoader.loadTestsFromTestCase()}

@item 
@ref{596,,unittest.TestLoader.getTestCaseNames()}
@end itemize

Patch by Hugo van Kemenade.

@item 
gh-104804@footnote{https://github.com/python/cpython/issues/104804}: Remove the untested and undocumented @ref{11b,,webbrowser}
@code{MacOSX} class, deprecated in Python 3.11. Patch by Hugo van
Kemenade.

@item 
gh-83863@footnote{https://github.com/python/cpython/issues/83863}: Support for using @ref{266,,pathlib.Path} objects as context
managers has been removed. Before Python 3.9, exiting the context manager
marked a path as "closed", which caused some (but not all!) methods to
raise when called. Since Python 3.9, using a path as a context manager
does nothing.

@item 
gh-104799@footnote{https://github.com/python/cpython/issues/104799}: Adjust the location of the (see 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}) @code{type_params}
field on @ref{1a76,,ast.ClassDef}, @ref{1a77,,ast.AsyncFunctionDef}, and
@ref{1a78,,ast.FunctionDef} to better preserve backward compatibility. Patch
by Jelle Zijlstra

@item 
gh-104797@footnote{https://github.com/python/cpython/issues/104797}: Allow @ref{56b,,typing.Protocol} classes to inherit from
@ref{343,,collections.abc.Buffer}. Patch by Jelle Zijlstra.

@item 
gh-104783@footnote{https://github.com/python/cpython/issues/104783}: Remove @code{locale.resetlocale()} function deprecated in Python
3.11. Patch by Victor Stinner.

@item 
gh-104780@footnote{https://github.com/python/cpython/issues/104780}: Remove the @code{2to3} program and the @code{lib2to3} module,
deprecated in Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{telnetlib} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{imghdr} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{cgi} and @code{cgitb} modules,
deprecated in Python 3.11. Patch by Victor Stinner.

@item 
gh-104773@footnote{https://github.com/python/cpython/issues/104773}: 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}: Remove the @code{sndhdr} module, deprecated in
Python 3.11. Patch by Victor Stinner.

@item 
gh-104372@footnote{https://github.com/python/cpython/issues/104372}: On Linux where @ref{dc,,subprocess} can use the @code{vfork()}
syscall for faster spawning, prevent the parent process from blocking
other threads by dropping the GIL while it waits for the vfork'ed child
process @code{exec()} outcome. This prevents spawning a binary from a slow
filesystem from blocking the rest of the application.

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: We now release the GIL around built-in @ref{6c,,hashlib}
computations of reasonable size for the SHA families and MD5 hash
functions, matching what our OpenSSL backed hash computations already
does.

@item 
gh-102613@footnote{https://github.com/python/cpython/issues/102613}: Improve performance of @ref{537,,pathlib.Path.glob()} when expanding
a pattern with a non-terminal "@code{**}" component by filtering walked paths
through a regular expression, rather than calling @ref{c54,,os.scandir()} more
than once on each directory.

@item 
gh-104399@footnote{https://github.com/python/cpython/issues/104399}: Prepare the @code{_tkinter} module for building with Tcl 9.0 and
future libtommath by replacing usage of deprecated functions
@code{mp_to_unsigned_bin_n()} and @code{mp_unsigned_bin_size()} when
necessary.

@item 
gh-102676@footnote{https://github.com/python/cpython/issues/102676}: Add fields @code{start_offset}, @code{cache_offset}, @code{end_offset},
@code{baseopname}, @code{baseopcode}, @code{jump_target} and @code{oparg} to
@ref{203,,dis.Instruction}.

@item 
gh-103558@footnote{https://github.com/python/cpython/issues/103558}: Fixed @code{parent} argument validation mechanism of
@ref{7,,argparse}. Improved test coverage.

@item 
gh-103464@footnote{https://github.com/python/cpython/issues/103464}: Provide helpful usage messages when parsing incorrect
@ref{aa,,pdb} commands.

@item 
gh-103384@footnote{https://github.com/python/cpython/issues/103384}: Generalize the regex pattern @code{BaseConfigurator.INDEX_PATTERN}
to allow spaces and non-alphanumeric characters in keys.

@item 
gh-103124@footnote{https://github.com/python/cpython/issues/103124}: Added multiline statement support for @ref{aa,,pdb}

@item 
gh-101162@footnote{https://github.com/python/cpython/issues/101162}: Forbid using @code{builtins.issubclass()} with
@ref{9ec,,types.GenericAlias} as the first argument.

@item 
gh-103200@footnote{https://github.com/python/cpython/issues/103200}: Fix cache repopulation semantics of
zipimport.invalidate_caches(). The cache is now repopulated upon
retrieving files with an invalid cache, not when the cache is invalidated.

@item 
gh-100061@footnote{https://github.com/python/cpython/issues/100061}: Fix a bug that causes wrong matches for regular expressions
with possessive qualifier.

@item 
gh-77609@footnote{https://github.com/python/cpython/issues/77609}: Add `follow_symlinks' argument to @ref{537,,pathlib.Path.glob()} and
@ref{538,,rglob()}, defaulting to false.

@item 
gh-102541@footnote{https://github.com/python/cpython/issues/102541}: Hide traceback in @ref{ad4,,help()} prompt, when import failed.

@item 
gh-102120@footnote{https://github.com/python/cpython/issues/102120}: Added a stream mode to @code{tarfile} that allows for reading
archives without caching info about the inner files.

@item 
gh-102029@footnote{https://github.com/python/cpython/issues/102029}: Deprecate passing any arguments to @ref{32e,,threading.RLock()}.

@item 
gh-88233@footnote{https://github.com/python/cpython/issues/88233}: Refactored @code{zipfile._strip_extra} to use higher level
abstractions for extras instead of a heavy-state loop.

@item 
gh-102024@footnote{https://github.com/python/cpython/issues/102024}: Reduce calls of @code{_idle_semaphore.release()} in
@code{concurrent.futures.thread._worker()}.

@item 
gh-73435@footnote{https://github.com/python/cpython/issues/73435}: Add support for recursive wildcards in
@ref{6d3,,pathlib.PurePath.match()}.

@item 
gh-84867@footnote{https://github.com/python/cpython/issues/84867}: @ref{593,,unittest.TestLoader} no longer loads test cases from
exact @ref{2b3,,unittest.TestCase} and @ref{1a79,,unittest.FunctionTestCase}
classes.

@item 
gh-99203@footnote{https://github.com/python/cpython/issues/99203}: Restore following CPython <= 3.10.5 behavior of
@ref{6da,,shutil.make_archive()}: do not create an empty archive if
@code{root_dir} is not a directory, and, in that case, raise
@ref{264,,FileNotFoundError} or @ref{1265,,NotADirectoryError} regardless of
@code{format} choice. Beyond the brought-back behavior, the function may now
also raise these exceptions in @code{dry_run} mode.

@item 
gh-80480@footnote{https://github.com/python/cpython/issues/80480}: Emit @ref{1a3,,DeprecationWarning} for @ref{8,,array}'s @code{'u'} type
code, deprecated in docs since Python 3.3.

@item 
gh-94924@footnote{https://github.com/python/cpython/issues/94924}: @ref{1934,,unittest.mock.create_autospec()} now properly returns
coroutine functions compatible with @ref{30d,,inspect.iscoroutinefunction()}

@item 
gh-94777@footnote{https://github.com/python/cpython/issues/94777}: Fix hanging @ref{98,,multiprocessing} @code{ProcessPoolExecutor} when
a child process crashes while data is being written in the call queue.

@item 
gh-92871@footnote{https://github.com/python/cpython/issues/92871}: Remove the @code{typing.io} and @code{typing.re} namespaces,
deprecated since Python 3.8. All items are still available from the main
@ref{10a,,typing} module.

@item 
bpo-43633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43633}: Improve the textual representation of IPv4-mapped IPv6
addresses (
@geindex RFC; RFC 4291
RFC 4291@footnote{https://datatracker.ietf.org/doc/html/rfc4291.html} Sections 2.2, 2.5.5.2) in @ref{84,,ipaddress}. Patch
by Oleksandr Pavliuk.

@item 
bpo-44850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44850}: Improve performance of @ref{1034,,operator.methodcaller()} using the
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} @code{vectorcall} convention. Patch by Anthony Lee and Pieter
Eendebak.

@item 
bpo-44185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44185}: @ref{11e9,,unittest.mock.mock_open()} will call the @code{close()}
method of the file handle mock when it is exiting from the context
manager. Patch by Samet Yaslan.

@item 
bpo-40988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40988}: Improve performance of @ref{be5,,functools.singledispatchmethod}
by caching the generated dispatch wrapper. Optimization suggested by
frederico. Patch by @@mental32, Alex Waygood and Pieter Eendebak.

@item 
bpo-41768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41768}: @ref{10d,,unittest.mock} speccing no longer calls class properties.
Patch by Melanie Witt.

@item 
bpo-18319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18319}: Ensure @code{gettext(msg)} retrieve translations even if a plural
form exists. In other words: @code{gettext(msg) == ngettext(msg, '@w{'}, 1)}.

@item 
bpo-17013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17013}: Add @code{ThreadingMock} to @ref{10d,,unittest.mock} that can be used
to create Mock objects that can wait until they are called. Patch by
Karthikeyan Singaravelan and Mario Corchero.
@end itemize

@node ドキュメント<20>,テスト<19>,ライブラリ<64>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id274}@anchor{1a7a}
@subsubsection ドキュメント



@itemize -

@item 
gh-109209@footnote{https://github.com/python/cpython/issues/109209}: The minimum Sphinx version required for the documentation is
now 4.2.

@item 
gh-108826@footnote{https://github.com/python/cpython/issues/108826}: @ref{3c,,dis} module command-line interface is now mentioned in
documentation.

@item 
gh-107305@footnote{https://github.com/python/cpython/issues/107305}: Add documentation for @ref{78e,,PyInterpreterConfig} and
@ref{689,,Py_NewInterpreterFromConfig()}.  Also clarify some of the nearby
docs relative to per-interpreter GIL.

@item 
gh-107008@footnote{https://github.com/python/cpython/issues/107008}: Document the @ref{2f,,curses} module variables
@ref{fec,,LINES} and @ref{fed,,COLS}.

@item 
gh-106948@footnote{https://github.com/python/cpython/issues/106948}: Add a number of standard external names to @code{nitpick_ignore}.

@item 
gh-106232@footnote{https://github.com/python/cpython/issues/106232}: Make timeit doc command lines compatible with Windows by using
double quotes for arguments.  This works on linux and macOS also.

@item 
gh-105172@footnote{https://github.com/python/cpython/issues/105172}: Fixed @ref{be2,,functools.lru_cache()} docstring accounting for
@code{typed} argument's different handling of str and int. Patch by Bar
Harel.

@item 
gh-105052@footnote{https://github.com/python/cpython/issues/105052}: Update @code{timeit} doc to specify that time in seconds is just
the default.

@item 
gh-89455@footnote{https://github.com/python/cpython/issues/89455}: Add missing documentation for the @code{max_group_depth} and
@code{max_group_width} parameters and the @code{exceptions} attribute of the
@ref{563,,traceback.TracebackException} class.

@item 
gh-89412@footnote{https://github.com/python/cpython/issues/89412}: Add missing documentation for the @code{end_lineno} and
@code{end_offset} attributes of the @ref{563,,traceback.TracebackException}
class.

@item 
gh-104943@footnote{https://github.com/python/cpython/issues/104943}: Remove mentions of old Python versions in
@ref{331,,typing.NamedTuple}.

@item 
gh-54738@footnote{https://github.com/python/cpython/issues/54738}: Add documentation on how to localize the @ref{7,,argparse} module.

@item 
gh-102823@footnote{https://github.com/python/cpython/issues/102823}: Document the return type of @code{x // y} when @code{x} and @code{y}
have type @ref{196,,float}.

@item 
gh-102759@footnote{https://github.com/python/cpython/issues/102759}: Align function signature for @code{functools.reduce} in
documentation and docstring with the C implementation.
@end itemize

@node テスト<19>,ビルド<22>,ドキュメント<20>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id275}@anchor{1a7b}
@subsubsection テスト



@itemize -

@item 
gh-110647@footnote{https://github.com/python/cpython/issues/110647}: Fix test_stress_modifying_handlers() of test_signal. Patch by
Victor Stinner.

@item 
gh-103053@footnote{https://github.com/python/cpython/issues/103053}: Fix test_tools.test_freeze on FreeBSD: run "make distclean"
instead of "make clean" in the copied source directory to remove also the
"python" program. Patch by Victor Stinner.

@item 
gh-110167@footnote{https://github.com/python/cpython/issues/110167}: Fix a deadlock in test_socket when server fails with a timeout
but the client is still running in its thread. Don't hold a lock to call
cleanup functions in doCleanups(). One of the cleanup function waits until
the client completes, whereas the client could deadlock if it called
addCleanup() in such situation. Patch by Victor Stinner.

@item 
gh-110388@footnote{https://github.com/python/cpython/issues/110388}: Add tests for @ref{106,,tty}.

@item 
gh-81002@footnote{https://github.com/python/cpython/issues/81002}: Add tests for @ref{e7,,termios}.

@item 
gh-110367@footnote{https://github.com/python/cpython/issues/110367}: regrtest: When using worker processes (-jN) with --verbose3
option, regrtest can now display the worker output even if a worker
process does crash. Previously, sys.stdout and sys.stderr were replaced
and so the worker output was lost on a crash. Patch by Victor Stinner.

@item 
gh-110267@footnote{https://github.com/python/cpython/issues/110267}: Add tests for pickling and copying PyStructSequence objects.
Patched by Xuehai Pan.

@item 
gh-110171@footnote{https://github.com/python/cpython/issues/110171}: @code{libregrtest} now always sets and shows @code{random.seed}, so
tests are more reproducible. Use @code{--randseed} flag to pass the explicit
random seed for tests.

@item 
gh-110152@footnote{https://github.com/python/cpython/issues/110152}: Remove @code{Tools/scripts/run_tests.py} and @code{make
hostrunnertest}. Just run @code{./python -m test --slow-ci}, @code{make
buildbottest} or @code{make test} instead. Python test runner (regrtest) now
handles cross-compilation and HOSTRUNNER. It also adds options to Python
such fast @code{-u -E -W default -bb} when @code{--fast-ci} or @code{--slow-ci}
option is used. Patch by Victor Stinner.

@item 
gh-110031@footnote{https://github.com/python/cpython/issues/110031}: Skip test_threading tests using thread+fork if Python is built
with Address Sanitizer (ASAN). Patch by Victor Stinner.

@item 
gh-110088@footnote{https://github.com/python/cpython/issues/110088}: Fix test_asyncio timeouts: don't measure the maximum duration,
a test should not measure a CI performance. Only measure the minimum
duration when a task has a timeout or delay. Add @code{CLOCK_RES} to
@code{test_asyncio.utils}. Patch by Victor Stinner.

@item 
gh-109974@footnote{https://github.com/python/cpython/issues/109974}: Fix race conditions in test_threading lock tests. Wait until a
condition is met rather than using @ref{8ac,,time.sleep()} with a hardcoded
number of seconds. Patch by Victor Stinner.

@item 
gh-110033@footnote{https://github.com/python/cpython/issues/110033}: Fix @code{test_interprocess_signal()} of @code{test_signal}. Make
sure that the @code{subprocess.Popen} object is deleted before the test
raising an exception in a signal handler. Otherwise, @code{Popen.__del__()}
can get the exception which is logged as @code{Exception ignored in: ...} and
the test fails. Patch by Victor Stinner.

@item 
gh-109594@footnote{https://github.com/python/cpython/issues/109594}: Fix test_timeout() of test_concurrent_futures.test_wait. Remove
the future which may or may not complete depending if it takes longer than
the timeout or not. Keep the second future which does not complete before
wait() timeout. Patch by Victor Stinner.

@item 
gh-109972@footnote{https://github.com/python/cpython/issues/109972}: Split test_gdb.py file into a test_gdb package made of multiple
tests, so tests can now be run in parallel. Patch by Victor Stinner.

@item 
gh-109566@footnote{https://github.com/python/cpython/issues/109566}: regrtest: When @code{--fast-ci} or @code{--slow-ci} option is used,
regrtest now replaces the current process with a new process to add @code{-u
-W default -bb -E} options to Python. Patch by Victor Stinner.

@item 
gh-109748@footnote{https://github.com/python/cpython/issues/109748}: Fix @code{test_zippath_from_non_installed_posix()} of test_venv:
don't copy @code{__pycache__/} sub-directories, because they can be modified
by other Python tests running in parallel. Patch by Victor Stinner.

@item 
gh-109739@footnote{https://github.com/python/cpython/issues/109739}: regrtest: Fix reference leak check on Windows. Disable the load
tracker on Windows in the reference leak check mode (-R option). Patch by
Victor Stinner.

@item 
gh-109276@footnote{https://github.com/python/cpython/issues/109276}: regrtest: When a test fails with "env changed" and the --rerun
option is used, the test is now re-run in verbose mode in a fresh process.
Patch by Victor Stinner.

@item 
gh-103053@footnote{https://github.com/python/cpython/issues/103053}: Skip test_freeze_simple_script() of test_tools.test_freeze if
Python is built with @code{./configure --enable-optimizations}, which means
with Profile Guided Optimization (PGO): it just makes the test too slow.
The freeze tool is tested by many other CIs with other (faster) compiler
flags. Patch by Victor Stinner.

@item 
gh-109580@footnote{https://github.com/python/cpython/issues/109580}: Skip @code{test_perf_profiler} if Python is built with ASAN, MSAN
or UBSAN sanitizer. Python does crash randomly in this test on such build.
Patch by Victor Stinner.

@item 
gh-109566@footnote{https://github.com/python/cpython/issues/109566}: regrtest: Add @code{--fast-ci} and @code{--slow-ci} options.
@code{--fast-ci} uses a default timeout of 10 minutes and @code{-u all,-cpu}
(skip slowest tests). @code{--slow-ci} uses a default timeout of 20 minutes
and @code{-u all} (run all tests). Patch by Victor Stinner.

@item 
gh-109425@footnote{https://github.com/python/cpython/issues/109425}: libregrtest now decodes stdout of test worker processes with
the "backslashreplace" error handler to log corrupted stdout, instead of
failing with an error and not logging the stdout. Patch by Victor Stinner.

@item 
gh-109396@footnote{https://github.com/python/cpython/issues/109396}: Fix @code{test_socket.test_hmac_sha1()} in FIPS mode. Use a longer
key: FIPS mode requires at least of at least 112 bits. The previous key
was only 32 bits. Patch by Victor Stinner.

@item 
gh-104736@footnote{https://github.com/python/cpython/issues/104736}: Fix test_gdb on Python built with LLVM clang 16 on Linux
ppc64le (ex: Fedora 38). Search patterns in gdb "bt" command output to
detect when gdb fails to retrieve the traceback. For example, skip a test
if @code{Backtrace stopped: frame did not save the PC} is found. Patch by
Victor Stinner.

@item 
gh-109276@footnote{https://github.com/python/cpython/issues/109276}: libregrtest now calls @ref{148b,,random.seed()} before running each
test file when @code{-r/--randomize} command line option is used. Moreover,
it's also called in worker processes.  It should help to make tests more
deterministic. Previously, it was only called once in the main process
before running all test files and it was not called in worker processes.
Patch by Victor Stinner.

@item 
gh-109276@footnote{https://github.com/python/cpython/issues/109276}: libregrtest now uses a separated file descriptor to write test
result as JSON. Previously, if a test wrote debug messages late around the
JSON, the main test process failed to parse JSON. Patch by Victor Stinner.

@item 
gh-108996@footnote{https://github.com/python/cpython/issues/108996}: Fix and enable @code{test_msvcrt}.

@item 
gh-109237@footnote{https://github.com/python/cpython/issues/109237}: Fix @code{test_site.test_underpth_basic()} when the working
directory contains at least one non-ASCII character: encode the @code{._pth}
file to UTF-8 and enable the UTF-8 Mode to use UTF-8 for the child process
stdout. Patch by Victor Stinner.

@item 
gh-109230@footnote{https://github.com/python/cpython/issues/109230}: Fix @code{test_pyexpat.test_exception()}: it can now be run from a
directory different than Python source code directory. Before, the test
failed in this case.  Skip the test if Modules/pyexpat.c source is not
available. Skip also the test on Python implementations other than
CPython. Patch by Victor Stinner.

@item 
gh-108996@footnote{https://github.com/python/cpython/issues/108996}: Add tests for @code{msvcrt}.

@item 
gh-109015@footnote{https://github.com/python/cpython/issues/109015}: Fix test_asyncio, test_imaplib and test_socket tests on FreeBSD
if the TCP blackhole is enabled (@code{sysctl net.inet.tcp.blackhole}). Skip
the few tests which failed with @code{ETIMEDOUT} which such non standard
configuration. Currently, the FreeBSD GCP image enables TCP and UDP blackhole@footnote{https://reviews.freebsd.org/D41751} (@code{sysctl
net.inet.tcp.blackhole=2} and @code{sysctl net.inet.udp.blackhole=1}).
Patch by Victor Stinner.

@item 
gh-91960@footnote{https://github.com/python/cpython/issues/91960}: Skip @code{test_gdb} if gdb is unable to retrieve Python frame
objects: if a frame is @code{<optimized out>}. When Python is built with
"clang -Og", gdb can fail to retrieve the `frame' parameter of
@code{_PyEval_EvalFrameDefault()}. In this case, tests like @code{py_bt()} are
likely to fail. Without getting access to Python frames, @code{python-gdb.py}
is mostly clueless on retrieving the Python traceback. Moreover,
@code{test_gdb} is no longer skipped on macOS if Python is built with Clang.
Patch by Victor Stinner.

@item 
gh-108962@footnote{https://github.com/python/cpython/issues/108962}: Skip @code{test_tempfile.test_flags()} if @code{chflags()} fails with
"OSError: [Errno 45] Operation not supported" (ex: on FreeBSD 13). Patch
by Victor Stinner.

@item 
gh-91960@footnote{https://github.com/python/cpython/issues/91960}: FreeBSD 13.2 CI coverage for pull requests is now provided by
Cirrus-CI (a hosted CI service that supports Linux, macOS, Windows, and
FreeBSD).

@item 
gh-89392@footnote{https://github.com/python/cpython/issues/89392}: Removed support of @code{test_main()} function in tests. They now
always use normal unittest test runner.

@item 
gh-108851@footnote{https://github.com/python/cpython/issues/108851}: Fix @code{test_tomllib} recursion tests for WASI buildbots: reduce
the recursion limit and compute the maximum nested array/dict depending on
the current available recursion limit. Patch by Victor Stinner.

@item 
gh-108851@footnote{https://github.com/python/cpython/issues/108851}: Add @code{get_recursion_available()} and @code{get_recursion_depth()}
functions to the @ref{ea,,test.support} module. Patch by Victor Stinner.

@item 
gh-108834@footnote{https://github.com/python/cpython/issues/108834}: Add @code{--fail-rerun option} option to regrtest: if a test
failed when then passed when rerun in verbose mode, exit the process with
exit code 2 (error), instead of exit code 0 (success). Patch by Victor
Stinner.

@item 
gh-108834@footnote{https://github.com/python/cpython/issues/108834}: Rename regrtest @code{--verbose2} option (@code{-w}) to @code{--rerun}.
Keep @code{--verbose2} as a deprecated alias. Patch by Victor Stinner.

@item 
gh-108834@footnote{https://github.com/python/cpython/issues/108834}: When regrtest reruns failed tests in verbose mode (@code{./python
-m test --rerun}), tests are now rerun in fresh worker processes rather
than being executed in the main process. If a test does crash or is killed
by a timeout, the main process can detect and handle the killed worker
process. Tests are rerun in parallel if the @code{-jN} option is used to run
tests in parallel. Patch by Victor Stinner.

@item 
gh-108822@footnote{https://github.com/python/cpython/issues/108822}: @code{regrtest} now computes statistics on all tests: successes,
failures and skipped. @code{test_netrc}, @code{test_pep646_syntax} and
@code{test_xml_etree} now return results in their @code{test_main()} function.
Patch by Victor Stinner and Alex Waygood.

@item 
gh-108794@footnote{https://github.com/python/cpython/issues/108794}: The @ref{4ee,,doctest.DocTestRunner.run()} method now counts the
number of skipped tests. Add @ref{4ef,,doctest.DocTestRunner.skips} and
@ref{4f0,,doctest.TestResults.skipped} attributes. Patch by Victor Stinner.

@item 
gh-108388@footnote{https://github.com/python/cpython/issues/108388}: Convert test_concurrent_futures to a package of 7 sub-tests.
Patch by Victor Stinner.

@item 
gh-108388@footnote{https://github.com/python/cpython/issues/108388}: Split test_multiprocessing_fork,
test_multiprocessing_forkserver and test_multiprocessing_spawn into test
packages. Each package is made of 4 sub-tests: processes, threads, manager
and misc. It allows running more tests in parallel and so reduce the total
test duration. Patch by Victor Stinner.

@item 
gh-105776@footnote{https://github.com/python/cpython/issues/105776}: Fix test_cppext when the C compiler command @code{-std=c11}
option: remove @code{-std=} options from the compiler command. Patch by
Victor Stinner.

@item 
gh-107652@footnote{https://github.com/python/cpython/issues/107652}: Set up CIFuzz to run fuzz targets in GitHub Actions. Patch by
Illia Volochii.

@item 
gh-107237@footnote{https://github.com/python/cpython/issues/107237}: @code{test_logging}: Fix @code{test_udp_reconnection()} by increasing
the timeout from 100 ms to 5 minutes (LONG_TIMEOUT). Patch by Victor
Stinner.

@item 
gh-107178@footnote{https://github.com/python/cpython/issues/107178}: Add the C API test for functions in the Mapping Protocol, the
Sequence Protocol and some functions in the Object Protocol.

@item 
gh-106714@footnote{https://github.com/python/cpython/issues/106714}: test_capi: Fix test_no_FatalError_infinite_loop() to no longer
write a coredump, by using test.support.SuppressCrashReport. Patch by
Victor Stinner.

@item 
gh-104090@footnote{https://github.com/python/cpython/issues/104090}: Avoid creating a reference to the test object in
@ref{1a7c,,collectedDurations()}.

@item 
gh-106752@footnote{https://github.com/python/cpython/issues/106752}: Moved tests for @code{zipfile.Path} into
@code{Lib/test/test_zipfile/_path}. Made @code{zipfile._path} a package.

@item 
gh-106690@footnote{https://github.com/python/cpython/issues/106690}: Add .coveragerc to cpython repository for use with coverage
package.

@item 
gh-101634@footnote{https://github.com/python/cpython/issues/101634}: When running the Python test suite with @code{-jN} option, if a
worker stdout cannot be decoded from the locale encoding report a failed
testn so the exitcode is non-zero. Patch by Victor Stinner.

@item 
gh-105084@footnote{https://github.com/python/cpython/issues/105084}: When the Python build is configured @code{--with-wheel-pkg-dir},
tests requiring the @code{setuptools} and @code{wheel} wheels will search for
the wheels in @code{WHEEL_PKG_DIR}.

@item 
gh-81005@footnote{https://github.com/python/cpython/issues/81005}: String tests are modified to reflect that @code{str} and
@code{unicode} are merged in Python 3. Patch by Daniel Fortunov.

@item 
gh-103186@footnote{https://github.com/python/cpython/issues/103186}: Suppress and assert expected RuntimeWarnings in
test_sys_settrace.py

@item 
gh-69714@footnote{https://github.com/python/cpython/issues/69714}: Add additional tests to @ref{15,,calendar} to achieve full test
coverage.
@end itemize

@node ビルド<22>,Windows<21>,テスト<19>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id276}@anchor{1a7d}
@subsubsection ビルド



@itemize -

@item 
gh-103053@footnote{https://github.com/python/cpython/issues/103053}: "make check-clean-src" now also checks if the "python" program
is found in the source directory: fail with an error if it does exist.
Patch by Victor Stinner.

@item 
gh-109191@footnote{https://github.com/python/cpython/issues/109191}: Fix compile error when building with recent versions of
libedit.

@item 
gh-110276@footnote{https://github.com/python/cpython/issues/110276}: No longer ignore 
@geindex PROFILE_TASK
@geindex 環境変数; PROFILE_TASK
@ref{1a7e,,PROFILE_TASK} failure silently:
command used by Profile Guided Optimization (PGO). Patch by Victor
Stinner.

@item 
gh-109566@footnote{https://github.com/python/cpython/issues/109566}: Remove @code{make testall} target: use @code{make buildbottest}
instead. Patch by Victor Stinner.

@item 
gh-109740@footnote{https://github.com/python/cpython/issues/109740}: The experimental @code{--disable-gil} configure flag now includes
"t" (for "threaded") in extension ABI tags.

@item 
gh-109054@footnote{https://github.com/python/cpython/issues/109054}: Fix building the @code{_testcapi} extension on Linux AArch64 which
requires linking to libatomic when @code{<cpython/pyatomic.h>} is used: the
@code{_Py_atomic_or_uint64()} function requires libatomic
@code{__atomic_fetch_or_8()} on this platform. The configure script now
checks if linking to libatomic is needed and generates a new LIBATOMIC
variable used to build the _testcapi extension. Patch by Victor Stinner.

@item 
gh-63760@footnote{https://github.com/python/cpython/issues/63760}: Fix Solaris build: no longer redefine the @code{gethostname()}
function. Solaris defines the function since 2005. Patch by Victor
Stinner, original patch by Jakub Kulík.

@item 
gh-108740@footnote{https://github.com/python/cpython/issues/108740}: Fix a race condition in @code{make regen-all}. The
@code{deepfreeze.c} source and files generated by Argument Clinic are now
generated or updated before generating "global objects". Previously, some
identifiers may miss depending on the order in which these files were
generated. Patch by Victor Stinner.

@item 
gh-108634@footnote{https://github.com/python/cpython/issues/108634}: Python built with @code{configure} @ref{636,,--with-trace-refs}
(tracing references) is now ABI compatible with Python release build and
@ref{509,,debug build}. Patch by Victor Stinner.

@item 
gh-85283@footnote{https://github.com/python/cpython/issues/85283}: The @code{_stat} C extension is now built with the @ref{637,,limited C API}. Patch by Victor Stinner.

@item 
gh-108447@footnote{https://github.com/python/cpython/issues/108447}: Fix x86_64 GNU/Hurd build

@item 
gh-107814@footnote{https://github.com/python/cpython/issues/107814}: When calling @code{find_python.bat} with @code{-q} it did not
properly silence the output of nuget. That is now fixed.

@item 
gh-105481@footnote{https://github.com/python/cpython/issues/105481}: Remove the make target @code{regen-opcode-targets}, merge its work
into @code{regen-opcode} which repeats most of the calculation. This
simplifies the code for the build and reduces code duplication.

@item 
gh-106881@footnote{https://github.com/python/cpython/issues/106881}: Check for @code{linux/limits.h} before including it in
@code{Modules/posixmodule.c}.

@item 
gh-95855@footnote{https://github.com/python/cpython/issues/95855}: Refactor platform triplet detection code and add detection for
MIPS soft float and musl libc.

@item 
gh-106962@footnote{https://github.com/python/cpython/issues/106962}: Detect MPI compilers in @code{configure}.

@item 
gh-106118@footnote{https://github.com/python/cpython/issues/106118}: Fix compilation for platforms without @code{O_CLOEXEC}. The
issue was introduced with Python 3.12b1 in gh-103295@footnote{https://github.com/python/cpython/issues/103295}. Patch by Erlend
Aasland.

@item 
gh-105875@footnote{https://github.com/python/cpython/issues/105875}: SQLite 3.15.2 or newer is required to build the @ref{d4,,sqlite3}
extension module. Patch by Erlend Aasland.

@item 
gh-90005@footnote{https://github.com/python/cpython/issues/90005}: Fix a regression in @code{configure} where we could end up
unintentionally linking with @code{libbsd}.

@item 
gh-102404@footnote{https://github.com/python/cpython/issues/102404}: Document how to perform a WASI build on Linux. Also add
Tools/wasm/build_wasi.sh as a reference implementation of the docs.

@item 
gh-89886@footnote{https://github.com/python/cpython/issues/89886}: Autoconf 2.71 and aclocal 1.16.4 is now required to regenerate
@code{configure}.

@item 
gh-104692@footnote{https://github.com/python/cpython/issues/104692}: Include @code{commoninstall} as a prerequisite for @code{bininstall}

This ensures that @code{commoninstall} is completed before @code{bininstall} is
started when parallel builds are used (@code{make -j install}), and so the
@code{python3} symlink is only installed after all standard library modules
are installed.

@item 
gh-101538@footnote{https://github.com/python/cpython/issues/101538}: Add experimental wasi-threads support. Patch by Takashi
Yamamoto.
@end itemize

@node Windows<21>,macOS<14>,ビルド<22>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id277}@anchor{1a7f}
@subsubsection Windows



@itemize -

@item 
gh-110437@footnote{https://github.com/python/cpython/issues/110437}: Allows overriding the source of VC redistributables so that
releases can be guaranteed to never downgrade between updates.

@item 
gh-109286@footnote{https://github.com/python/cpython/issues/109286}: Update Windows installer to use SQLite 3.43.1.

@item 
gh-82367@footnote{https://github.com/python/cpython/issues/82367}: @ref{262,,os.path.realpath()} now resolves MS-DOS style file names
even if the file is not accessible. Patch by Moonsik Park.

@item 
gh-109991@footnote{https://github.com/python/cpython/issues/109991}: Update Windows build to use OpenSSL 3.0.11.

@item 
gh-106242@footnote{https://github.com/python/cpython/issues/106242}: Fixes @ref{262,,realpath()} to behave consistently when
passed a path containing an embedded null character on Windows. In strict
mode, it now raises @ref{2c0,,OSError} instead of the unexpected
@ref{2ec,,ValueError}, and in non-strict mode will make the path absolute.

@item 
gh-83180@footnote{https://github.com/python/cpython/issues/83180}: Changes the @ref{7da,,Python install manager} to prefer an active virtual
environment when the launched script has a shebang line using a Unix-like
virtual command, even if the command requests a specific version of
Python.

@item 
gh-106844@footnote{https://github.com/python/cpython/issues/106844}: Fix integer overflow and truncating by the null character in
@code{_winapi.LCMapStringEx()} which affects @code{ntpath.normcase()}.

@item 
gh-105436@footnote{https://github.com/python/cpython/issues/105436}: Ensure that an empty environment block is terminated by two
null characters, as is required by Windows.

@item 
gh-105146@footnote{https://github.com/python/cpython/issues/105146}: Updated the links at the end of the installer to point to
Discourse rather than the mailing lists.

@item 
gh-103646@footnote{https://github.com/python/cpython/issues/103646}: When installed from the Microsoft Store, @code{pip} no longer
defaults to per-user installs. However, as the install directory is
unwritable, it should automatically decide to do a per-user install
anyway. This should resolve issues when @code{pip} is passed an option that
conflicts with @code{--user}.

@item 
gh-88745@footnote{https://github.com/python/cpython/issues/88745}: Improve performance of @ref{c50,,shutil.copy2()} by using the
operating system's @code{CopyFile2} function. This may result in subtle
changes to metadata copied along with some files, bringing them in line
with normal OS behavior.

@item 
gh-104820@footnote{https://github.com/python/cpython/issues/104820}: Fixes @ref{26d,,stat()} and related functions on file systems
that do not support file ID requests. This includes FAT32 and exFAT.

@item 
gh-104803@footnote{https://github.com/python/cpython/issues/104803}: Add @ref{19c2,,os.path.isdevdrive()} to detect whether a path is on a
Windows Dev Drive. Returns @code{False} on platforms that do not support Dev
Drive, and is absent on non-Windows platforms.
@end itemize

@node macOS<14>,IDLE<13>,Windows<21>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id278}@anchor{1a80}
@subsubsection macOS



@itemize -

@item 
gh-109286@footnote{https://github.com/python/cpython/issues/109286}: Update macOS installer to use SQLite 3.43.1.

@item 
gh-109991@footnote{https://github.com/python/cpython/issues/109991}: Update macOS installer to use OpenSSL 3.0.11.

@item 
gh-99079@footnote{https://github.com/python/cpython/issues/99079}: Update macOS installer to use OpenSSL 3.0.9.
@end itemize

@node IDLE<13>,Tools/Demos<19>,macOS<14>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id279}@anchor{1a81}
@subsubsection IDLE



@itemize -

@item 
gh-104719@footnote{https://github.com/python/cpython/issues/104719}: Remove IDLE's modification of tokenize.tabsize and test other
uses of tokenize data and methods.
@end itemize

@node Tools/Demos<19>,C API<22>,IDLE<13>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id280}@anchor{1a82}
@subsubsection Tools/Demos



@itemize -

@item 
gh-109991@footnote{https://github.com/python/cpython/issues/109991}: Update GitHub CI workflows to use OpenSSL 3.0.11 and
multissltests to use 1.1.1w, 3.0.11, and 3.1.3.

@item 
gh-108494@footnote{https://github.com/python/cpython/issues/108494}: Argument Clinic@footnote{https://devguide.python.org/development-tools/clinic/} now has a
partial support of the @ref{637,,Limited API}: see
documentation in the Python Developer's Guide@footnote{https://devguide.python.org/development-tools/clinic/#clinic-howto-limited-capi}
Patch by Victor Stinner.

@item 
gh-107704@footnote{https://github.com/python/cpython/issues/107704}: It is now possible to deprecate passing keyword arguments for
keyword-or-positional parameters with Argument Clinic, using the new @code{/
[from X.Y]} syntax. (To be read as `"positional-only from Python version
X.Y"'.) See documentation in the Python Developer's Guide@footnote{https://devguide.python.org/development-tools/clinic/#clinic-howto-deprecate-keyword}
for more information.

@item 
gh-107880@footnote{https://github.com/python/cpython/issues/107880}: Argument Clinic can now clone @code{__init__()} and
@code{__new__()} methods.

@item 
gh-104683@footnote{https://github.com/python/cpython/issues/104683}: Add @code{--exclude} option to Argument Clinic CLI.

@item 
gh-95065@footnote{https://github.com/python/cpython/issues/95065}: Argument Clinic now supports overriding automatically generated
signature by using directive @code{@@text_signature}. See documentation in the Python Developer's Guide@footnote{https://devguide.python.org/development-tools/clinic/#clinic-howto-override-signature}

@item 
gh-107609@footnote{https://github.com/python/cpython/issues/107609}: Fix duplicate module check in Argument Clinic. Previously, a
duplicate definition would incorrectly be silently accepted. Patch by
Erlend E. Aasland.

@item 
gh-107467@footnote{https://github.com/python/cpython/issues/107467}: The Argument Clinic command-line tool now prints to stderr
instead of stdout on failure.

@item 
gh-106970@footnote{https://github.com/python/cpython/issues/106970}: Fix bugs in the Argument Clinic @code{destination <name> clear}
command; the destination buffers would never be cleared, and the
@code{destination} directive parser would simply continue to the fault
handler after processing the command. Patch by Erlend E. Aasland.

@item 
gh-106706@footnote{https://github.com/python/cpython/issues/106706}: Change bytecode syntax for families to remove redundant name
matching pseudo syntax.

@item 
gh-106359@footnote{https://github.com/python/cpython/issues/106359}: Argument Clinic now explicitly forbids "kwarg splats" in
function calls used as annotations.

@item 
gh-103186@footnote{https://github.com/python/cpython/issues/103186}: @code{freeze} now fetches @code{CONFIG_ARGS} from the original
CPython instance the Makefile uses to call utility scripts. Patch by
Ijtaba Hussain.

@item 
gh-95065@footnote{https://github.com/python/cpython/issues/95065}: It is now possible to deprecate passing parameters positionally
with Argument Clinic, using the new @code{* [from X.Y]} syntax. (To be read
as `"keyword-only from Python version X.Y"'.) See documentation in the Python Developer's Guide@footnote{https://devguide.python.org/development-tools/clinic/#clinic-howto-deprecate-positional}
for more information. Patch by Erlend E. Aasland with help from Alex
Waygood, Nikita Sobolev, and Serhiy Storchaka.
@end itemize

@node C API<22>,,Tools/Demos<19>,Python 3 13 0 alpha 1
@anchor{whatsnew/changelog id281}@anchor{1a83}
@subsubsection C API



@itemize -

@item 
gh-85283@footnote{https://github.com/python/cpython/issues/85283}: If the @ref{660,,Py_LIMITED_API} macro is defined,
@code{Py_BUILD_CORE}, @code{Py_BUILD_CORE_BUILTIN} and
@code{Py_BUILD_CORE_MODULE} macros are now undefined by
@code{<Python.h>}. Patch by Victor Stinner.

@item 
gh-110289@footnote{https://github.com/python/cpython/issues/110289}: Add @ref{619,,PyUnicode_EqualToUTF8AndSize()} and
@ref{61a,,PyUnicode_EqualToUTF8()} functions.

@item 
gh-110235@footnote{https://github.com/python/cpython/issues/110235}: Raise @ref{198,,TypeError} for duplicate/unknown fields in
@code{PyStructSequence} constructor. Patched by Xuehai Pan.

@item 
gh-110014@footnote{https://github.com/python/cpython/issues/110014}: Remove undocumented @code{PY_TIMEOUT_MAX} constant from the
limited C API. Patch by Victor Stinner.

@item 
gh-109521@footnote{https://github.com/python/cpython/issues/109521}: @ref{1a84,,PyImport_GetImporter()} now sets RuntimeError if it
fails to get @ref{1225,,sys.path_hooks} or @ref{7fa,,sys.path_importer_cache} or
they are not list and dict correspondingly. Previously it could return
NULL without setting error in obscure cases, crash or raise SystemError if
these attributes have wrong type.

@item 
gh-108724@footnote{https://github.com/python/cpython/issues/108724}: Add @ref{484,,PyMutex} internal-only lightweight locking API.

@item 
gh-85283@footnote{https://github.com/python/cpython/issues/85283}: Add @ref{612,,PySys_AuditTuple()} function: similar to
@ref{613,,PySys_Audit()}, but pass event arguments as a Python @ref{614,,tuple}
object.  Patch by Victor Stinner.

@item 
gh-108867@footnote{https://github.com/python/cpython/issues/108867}: Add @ref{423,,PyThreadState_GetUnchecked()} function: similar to
@ref{615,,PyThreadState_Get()}, but don't kill the process with a fatal
error if it is NULL. The caller is responsible to check if the result is
NULL. Previously, the function was private and known as
@code{_PyThreadState_UncheckedGet()}. Patch by Victor Stinner.

@item 
gh-108765@footnote{https://github.com/python/cpython/issues/108765}: @code{Python.h} no longer includes the @code{<ctype.h>} standard
header file. If needed, it should now be included explicitly. For example,
it provides @code{isalpha()} and @code{tolower()} functions which are locale
dependent. Python provides locale independent functions, like
@code{Py_ISALPHA()} and @code{Py_TOLOWER()}. Patch by Victor Stinner.

@item 
gh-108765@footnote{https://github.com/python/cpython/issues/108765}: @code{Python.h} no longer includes the @code{<unistd.h>} standard
header file. If needed, it should now be included explicitly. For example,
it provides the functions: @code{close()}, @code{getpagesize()}, @code{getpid()}
and @code{sysconf()}. Patch by Victor Stinner.

@item 
gh-108765@footnote{https://github.com/python/cpython/issues/108765}: @code{Python.h} no longer includes the @code{<ieeefp.h>} standard
header. It was included for the @code{finite()} function which is now
provided by the @code{<math.h>} header. It should now be included explicitly
if needed. Remove also the @code{HAVE_IEEEFP_H} macro. Patch by Victor
Stinner.

@item 
gh-108765@footnote{https://github.com/python/cpython/issues/108765}: @code{Python.h} no longer includes these standard header files:
@code{<time.h>}, @code{<sys/select.h>} and @code{<sys/time.h>}. If needed, they
should now be included explicitly. For example, @code{<time.h>} provides the
@code{clock()} and @code{gmtime()} functions, @code{<sys/select.h>} provides the
@code{select()} function, and @code{<sys/time.h>} provides the @code{futimes()},
@code{gettimeofday()} and @code{setitimer()} functions. Patch by Victor Stinner.

@item 
gh-108511@footnote{https://github.com/python/cpython/issues/108511}: Add functions @ref{61b,,PyObject_HasAttrWithError()},
@ref{61d,,PyObject_HasAttrStringWithError()},
@ref{61f,,PyMapping_HasKeyWithError()} and
@ref{621,,PyMapping_HasKeyStringWithError()}.

@item 
gh-107073@footnote{https://github.com/python/cpython/issues/107073}: Add @ref{60d,,PyObject_VisitManagedDict()} and
@ref{60e,,PyObject_ClearManagedDict()} functions which must be called by the
traverse and clear functions of a type using
@ref{60f,,Py_TPFLAGS_MANAGED_DICT} flag. Patch by Victor Stinner.

@item 
gh-108634@footnote{https://github.com/python/cpython/issues/108634}: Python built with @code{configure} @ref{636,,--with-trace-refs}
(tracing references) now supports the @ref{637,,Limited API}.
Patch by Victor Stinner.

@item 
gh-108014@footnote{https://github.com/python/cpython/issues/108014}: Add @ref{604,,PyLong_AsInt()} function: similar to
@ref{605,,PyLong_AsLong()}, but store the result in a C int instead
of a C long. Previously, it was known as the private function
@code{_PyLong_AsInt()} (with an underscore prefix). Patch by Victor
Stinner.

@item 
gh-108314@footnote{https://github.com/python/cpython/issues/108314}: Add @ref{5dd,,PyDict_ContainsString()} function: same as
@ref{5de,,PyDict_Contains()}, but `key' is specified as a const char* UTF-8 encoded bytes string, rather than a @ref{5df,,PyObject}*.
Patch by Victor Stinner.

@item 
gh-108337@footnote{https://github.com/python/cpython/issues/108337}: Add atomic operations on additional data types in pyatomic.h.

@item 
gh-108014@footnote{https://github.com/python/cpython/issues/108014}: Add @ref{5fd,,Py_IsFinalizing()} function: check if the main
Python interpreter is @ref{479,,shutting down}. Patch
by Victor Stinner.

@item 
gh-107916@footnote{https://github.com/python/cpython/issues/107916}: C API functions @ref{1a85,,PyErr_SetFromErrnoWithFilename()},
@ref{1a86,,PyErr_SetExcFromWindowsErrWithFilename()} and
@ref{1a87,,PyErr_SetFromWindowsErrWithFilename()} save now the error code
before calling @ref{1a88,,PyUnicode_DecodeFSDefault()}.

@item 
gh-107915@footnote{https://github.com/python/cpython/issues/107915}: Such C API functions as @code{PyErr_SetString()},
@code{PyErr_Format()}, @code{PyErr_SetFromErrnoWithFilename()} and many others
no longer crash or ignore errors if it failed to format the error message
or decode the filename. Instead, they keep a corresponding error.

@item 
gh-107810@footnote{https://github.com/python/cpython/issues/107810}: Improve @ref{1a3,,DeprecationWarning} for uses of
@ref{1a89,,PyType_Spec} with metaclasses that have custom @code{tp_new}.

@item 
gh-107249@footnote{https://github.com/python/cpython/issues/107249}: Implement the @ref{1a8a,,Py_UNUSED} macro for Windows MSVC
compiler. Patch by Victor Stinner.

@item 
gh-107226@footnote{https://github.com/python/cpython/issues/107226}: @ref{60a,,PyModule_AddObjectRef()} is now only available in the
limited API version 3.10 or later.

@item 
gh-106320@footnote{https://github.com/python/cpython/issues/106320}: Remove private @code{_PyUnicode_AsString()} alias to
@ref{424,,PyUnicode_AsUTF8()}. It was kept for backward compatibility with
Python 3.0 - 3.2. The @ref{424,,PyUnicode_AsUTF8()} is available since Python
3.3. The @ref{13a6,,PyUnicode_AsUTF8String()} function can be used to keep
compatibility with Python 3.2 and older. Patch by Victor Stinner.

@item 
gh-106572@footnote{https://github.com/python/cpython/issues/106572}: Convert @ref{1831,,PyObject_DelAttr()} and
@ref{1832,,PyObject_DelAttrString()} macros to functions. Patch by Victor
Stinner.

@item 
gh-106307@footnote{https://github.com/python/cpython/issues/106307}: Add @ref{5e8,,PyMapping_GetOptionalItem()} function.

@item 
gh-106521@footnote{https://github.com/python/cpython/issues/106521}: Add @ref{5ec,,PyObject_GetOptionalAttr()} and
@ref{5ed,,PyObject_GetOptionalAttrString()} functions.

@item 
gh-106320@footnote{https://github.com/python/cpython/issues/106320}: Remove @code{_PyInterpreterState_Get()} alias to
@ref{64c,,PyInterpreterState_Get()} which was kept for backward
compatibility with Python 3.8. Patch by Victor Stinner.

@item 
gh-106316@footnote{https://github.com/python/cpython/issues/106316}: Remove @code{cpython/pytime.h} header file: it only contained
private functions. Patch by Victor Stinner.

@item 
gh-106023@footnote{https://github.com/python/cpython/issues/106023}: Remove private @code{_PyObject_FastCall()} function: use
@code{PyObject_Vectorcall()} which is available since Python 3.8
(
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}). Patch by Victor Stinner.

@item 
gh-106168@footnote{https://github.com/python/cpython/issues/106168}: If Python is built in @ref{509,,debug mode} or
@ref{62d,,with assertions}, @ref{62e,,PyTuple_SET_ITEM()}
and @ref{62f,,PyList_SET_ITEM()} now check the index argument with an
assertion. If the assertion fails, make sure that the size is set before.
Patch by Victor Stinner.

@item 
gh-106084@footnote{https://github.com/python/cpython/issues/106084}: Remove the old aliases to functions calling functions which
were kept for backward compatibility with Python 3.8 provisional API:


@itemize *

@item 
@code{_PyObject_CallMethodNoArgs()}: use @code{PyObject_CallMethodNoArgs()}

@item 
@code{_PyObject_CallMethodOneArg()}: use @code{PyObject_CallMethodOneArg()}

@item 
@code{_PyObject_CallOneArg()}: use @code{PyObject_CallOneArg()}

@item 
@code{_PyObject_FastCallDict()}: use @code{PyObject_VectorcallDict()}

@item 
@code{_PyObject_Vectorcall()}: use @code{PyObject_Vectorcall()}

@item 
@code{_PyObject_VectorcallMethod()}: use @code{PyObject_VectorcallMethod()}

@item 
@code{_PyVectorcall_Function()}: use @code{PyVectorcall_Function()}
@end itemize

Just remove the underscore prefix to update your code. Patch by Victor
Stinner.

@item 
gh-106004@footnote{https://github.com/python/cpython/issues/106004}: Adds @ref{5e0,,PyDict_GetItemRef()} and
@ref{421,,PyDict_GetItemStringRef()} functions: similar to
@ref{5e1,,PyDict_GetItemWithError()} but returning a @ref{5e2,,strong reference}
instead of a @ref{3d7,,borrowed reference}. Patch by Victor Stinner.

@item 
gh-105927@footnote{https://github.com/python/cpython/issues/105927}: Deprecate the @ref{3dd,,PyWeakref_GetObject()} and
@ref{3de,,PyWeakref_GET_OBJECT()} functions: use the new
@ref{3df,,PyWeakref_GetRef()} function instead. Patch by Victor Stinner.

@item 
gh-105927@footnote{https://github.com/python/cpython/issues/105927}: Add @ref{3df,,PyWeakref_GetRef()} function: similar to
@ref{3dd,,PyWeakref_GetObject()} but returns a @ref{5e2,,strong reference}, or
@code{NULL} if the referent is no longer live. Patch by Victor Stinner.

@item 
gh-105922@footnote{https://github.com/python/cpython/issues/105922}: Add @ref{5fb,,PyImport_AddModuleRef()}: similar to
@ref{5fc,,PyImport_AddModule()}, but return a @ref{5e2,,strong reference}
instead of a @ref{3d7,,borrowed reference}. Patch by Victor Stinner.

@item 
gh-105227@footnote{https://github.com/python/cpython/issues/105227}: The new @ref{1a8b,,PyType_GetDict()} provides the dictionary for
the given type object that is normally exposed by @code{cls.__dict__}.
Normally it's sufficient to use @ref{1a8c,,tp_dict}, but for
the static builtin types @code{tp_dict} is now always @code{NULL}.
@code{PyType_GetDict()} provides the correct dict object instead.

@item 
gh-105375@footnote{https://github.com/python/cpython/issues/105375}: Fix a bug in @ref{1a8d,,PyErr_WarnExplicit()} where an exception
could end up being overwritten if the API failed internally.

@item 
gh-105603@footnote{https://github.com/python/cpython/issues/105603}: We've renamed the new (in 3.12) @code{PyInterpreterConfig.own_gil}
to @code{PyInterpreterConfig.gil} and changed the meaning of the value from
"bool" to an integer with supported values of
@code{PyInterpreterConfig_DEFAULT_GIL}, @code{PyInterpreterConfig_SHARED_GIL},
and @code{PyInterpreterConfig_OWN_GIL}. The default is "shared".

@item 
gh-105387@footnote{https://github.com/python/cpython/issues/105387}: In the limited C API version 3.12, @ref{78f,,Py_INCREF()} and
@ref{790,,Py_DECREF()} functions are now implemented as opaque function calls
to hide implementation details. Patch by Victor Stinner.

@item 
gh-105396@footnote{https://github.com/python/cpython/issues/105396}: Deprecate the @ref{3db,,PyImport_ImportModuleNoBlock()} function
which is just an alias to @ref{3dc,,PyImport_ImportModule()} since Python
3.3. Patch by Victor Stinner.

@item 
gh-103968@footnote{https://github.com/python/cpython/issues/103968}: @ref{772,,PyType_FromMetaclass()} now allows metaclasses with
@code{tp_new} set to @code{NULL}.

@item 
gh-105268@footnote{https://github.com/python/cpython/issues/105268}: Remove the old private, undocumented and untested
@code{_PyGC_FINALIZED()} macro which was kept for backward compatibility with
Python 3.8 and older. Patch by Victor Stinner.

@item 
gh-105182@footnote{https://github.com/python/cpython/issues/105182}: Remove @code{PyEval_AcquireLock()} and @code{PyEval_ReleaseLock()}
functions, deprecated in Python 3.2. Patch by Victor Stinner.

@item 
gh-105182@footnote{https://github.com/python/cpython/issues/105182}: Remove @code{PyEval_InitThreads()} and
@code{PyEval_ThreadsInitialized()} functions, deprecated in Python 3.9. Patch
by Victor Stinner.

@item 
gh-105145@footnote{https://github.com/python/cpython/issues/105145}: Deprecate old Python initialization functions:


@itemize *

@item 
@ref{3f4,,PySys_ResetWarnOptions()}

@item 
@ref{3e9,,Py_GetExecPrefix()}

@item 
@ref{3e3,,Py_GetPath()}

@item 
@ref{3e5,,Py_GetPrefix()}

@item 
@ref{3ec,,Py_GetProgramFullPath()}

@item 
@ref{3ee,,Py_GetProgramName()}

@item 
@ref{3ef,,Py_GetPythonHome()}
@end itemize

Patch by Victor Stinner.

@item 
gh-85275@footnote{https://github.com/python/cpython/issues/85275}: @code{PyObject_AsCharBuffer()}, @code{PyObject_AsReadBuffer()},
@code{PyObject_CheckReadBuffer()}, and @code{PyObject_AsWriteBuffer()} are
removed. Please migrate to new buffer protocol;
@ref{63a,,PyObject_GetBuffer()} and @ref{63b,,PyBuffer_Release()}.

@item 
gh-105156@footnote{https://github.com/python/cpython/issues/105156}: Deprecate the old @code{Py_UNICODE} and @code{PY_UNICODE_TYPE} types:
use directly the @code{wchar_t} type instead. Since Python 3.3,
@code{Py_UNICODE} and @code{PY_UNICODE_TYPE} are just aliases to
@code{wchar_t}. Patch by Victor Stinner.

@item 
gh-105145@footnote{https://github.com/python/cpython/issues/105145}: Remove the following old functions to configure the Python
initialization, deprecated in Python 3.11:


@itemize *

@item 
@code{PySys_AddWarnOptionUnicode()}

@item 
@code{PySys_AddWarnOption()}

@item 
@code{PySys_AddXOption()}

@item 
@code{PySys_HasWarnOptions()}

@item 
@code{PySys_SetArgvEx()}

@item 
@code{PySys_SetArgv()}

@item 
@code{PySys_SetPath()}

@item 
@code{Py_SetPath()}

@item 
@code{Py_SetProgramName()}

@item 
@code{Py_SetPythonHome()}

@item 
@code{Py_SetStandardStreamEncoding()}

@item 
@code{_Py_SetProgramFullPath()}
@end itemize

Patch by Victor Stinner.

@item 
gh-105107@footnote{https://github.com/python/cpython/issues/105107}: Remove functions deprecated in Python 3.9.


@itemize *

@item 
@code{PyEval_CallObject()}, @code{PyEval_CallObjectWithKeywords()}: use
@ref{63c,,PyObject_CallNoArgs()} and @ref{63d,,PyObject_Call()} (positional
arguments must not be `NULL') instead.

@item 
@code{PyEval_CallFunction()}: use @ref{63f,,PyObject_CallFunction()} instead.

@item 
@code{PyEval_CallMethod()}: use @ref{640,,PyObject_CallMethod()} instead.

@item 
@code{PyCFunction_Call()}: use @ref{63d,,PyObject_Call()} instead.
@end itemize

Patch by Victor Stinner.

@item 
gh-105115@footnote{https://github.com/python/cpython/issues/105115}: @code{PyTypeObject.tp_bases} (and @code{tp_mro}) for builtin static
types are now shared by all interpreters, whereas in 3.12-beta1 they were
stored on @code{PyInterpreterState}.  Also note that now the tuples are
immortal objects.

@item 
gh-105071@footnote{https://github.com/python/cpython/issues/105071}: Add @code{PyUnstable_Exc_PrepReraiseStar} to the unstable C api to
expose the implementation of @ref{1ac,,except*}.

@item 
gh-104922@footnote{https://github.com/python/cpython/issues/104922}: @code{PY_SSIZE_T_CLEAN} is no longer required to use @code{'#'}
formats in APIs like @ref{3c1,,PyArg_ParseTuple()} and
@ref{3c2,,Py_BuildValue()}. They uses @code{Py_ssize_t} for @code{'#'} regardless
@code{PY_SSIZE_T_CLEAN}.

@item 
gh-104584@footnote{https://github.com/python/cpython/issues/104584}: Add an unstable C API for hooking in an optimizer. This is
mainly internal, but marked "unstable" to allow third-party
experimentation.

@item 
gh-104668@footnote{https://github.com/python/cpython/issues/104668}: Don't call @ref{7a4,,PyOS_InputHook} or
@ref{7a5,,PyOS_ReadlineFunctionPointer} in subinterpreters, since it's
generally difficult to avoid using global state in their registered
callbacks. This also avoids situations where extensions may find
themselves running in a subinterpreter they don't support (or haven't yet
been loaded in).

@item 
bpo-42327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42327}: Add @ref{609,,PyModule_Add()} function: similar to
@ref{60a,,PyModule_AddObjectRef()} and @ref{60b,,PyModule_AddObject()}, but
always steals a reference to the value.

@item 
bpo-40309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40309}: Properly handle trailing spaces before closing parenthesis in
@ref{3c2,,Py_BuildValue()} format strings.
@end itemize

@node Python 3 12 0 beta 1,Python 3 12 0 alpha 7,Python 3 13 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-12-0-beta-1}@anchor{1a8e}
@subsection Python 3.12.0 beta 1


`Release date: 2023-05-22'

@menu
* セキュリティ: セキュリティ<22>. 
* ライブラリ: ライブラリ<65>. 
* Core and Builtins: Core and Builtins<60>. 
* ライブラリ: ライブラリ<66>. 
* Core and Builtins: Core and Builtins<61>. 
* ライブラリ: ライブラリ<67>. 
* ドキュメント: ドキュメント<21>. 
* テスト: テスト<20>. 
* ビルド: ビルド<23>. 
* Windows: Windows<22>. 
* macOS: macOS<15>. 
* IDLE: IDLE<14>. 
* Tools/Demos: Tools/Demos<20>. 
* C API: C API<23>. 

@end menu

@node セキュリティ<22>,ライブラリ<65>,,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id282}@anchor{1a8f}
@subsubsection セキュリティ



@itemize -

@item 
gh-99889@footnote{https://github.com/python/cpython/issues/99889}: Fixed a security in flaw in @code{uu.decode()} that could allow
for directory traversal based on the input if no @code{out_file} was
specified.

@item 
gh-104049@footnote{https://github.com/python/cpython/issues/104049}: Do not expose the local on-disk location in directory indexes
produced by @code{http.client.SimpleHTTPRequestHandler}.

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Upgrade built-in @ref{6c,,hashlib} SHA3 implementation to a
verified implementation from the @code{HACL*} project.  Used when OpenSSL is
not present or lacks SHA3.

@item 
gh-102153@footnote{https://github.com/python/cpython/issues/102153}: @ref{f3a,,urllib.parse.urlsplit()} now strips leading C0 control and
space characters following the specification for URLs defined by WHATWG in
response to 
@geindex Common Vulnerabilities and Exposures; CVE 2023-24329
CVE 2023-24329@footnote{https://www.cve.org/CVERecord?id=CVE-2023-24329}. Patch by Illia Volochii.
@end itemize

@node ライブラリ<65>,Core and Builtins<60>,セキュリティ<22>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id283}@anchor{1a90}
@subsubsection ライブラリ



@itemize -

@item 
gh-102856@footnote{https://github.com/python/cpython/issues/102856}: Implement PEP 701 changes in the @ref{101,,tokenize} module. Patch
by Marta Gómez Macías and Pablo Galindo Salgado
@end itemize

@node Core and Builtins<60>,ライブラリ<66>,ライブラリ<65>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id284}@anchor{1a91}
@subsubsection Core and Builtins



@itemize -

@item 
gh-104615@footnote{https://github.com/python/cpython/issues/104615}: Fix wrong ordering of assignments in code like @code{a, a = x, y}.
Contributed by Carl Meyer.

@item 
gh-104572@footnote{https://github.com/python/cpython/issues/104572}: Improve syntax error message for invalid constructs in
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} contexts and in annotations when @code{from __future__ import
annotations} is active.

@item 
gh-104482@footnote{https://github.com/python/cpython/issues/104482}: Fix three error handling bugs in ast.c's validation of pattern
matching statements.

@item 
gh-102818@footnote{https://github.com/python/cpython/issues/102818}: Do not add a frame to the traceback in the @code{sys.setprofile}
and @code{sys.settrace} trampoline functions. This ensures that frames are
not duplicated if an exception is raised in the callback function, and
ensures that frames are not omitted if a C callback is used and that does
not add the frame.

@item 
gh-104405@footnote{https://github.com/python/cpython/issues/104405}: Fix an issue where some @ref{4aa,,bytecode} instructions could
ignore 
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/} when "inlining" calls.

@item 
gh-103082@footnote{https://github.com/python/cpython/issues/103082}: Change behavior of @code{sys.monitoring.events.LINE} events in
@code{sys.monitoring}: Line events now occur when a new line is reached
dynamically, instead of using a static approximation, as before. This
makes the behavior very similar to that of "line" events in
@code{sys.settrace}. This should ease porting of tools from 3.11 to 3.12.

@item 
gh-104263@footnote{https://github.com/python/cpython/issues/104263}: Fix @code{float("nan")} to produce a quiet NaN on platforms (like
MIPS) where the meaning of the signalling / quiet bit is inverted from its
usual meaning. Also introduce a new macro @code{Py_INFINITY} matching C99's
@code{INFINITY}, and refactor internals to rely on C99's @code{NAN} and
@code{INFINITY} macros instead of hard-coding bit patterns for infinities and
NaNs. Thanks Sebastian Berg.

@item 
gh-99113@footnote{https://github.com/python/cpython/issues/99113}: Multi-phase init extension modules may now indicate that they
support running in subinterpreters that have their own GIL.  This is done
by using @code{Py_MOD_PER_INTERPRETER_GIL_SUPPORTED} as the value for the
@code{Py_mod_multiple_interpreters} module def slot.  Otherwise the module,
by default, cannot be imported in such subinterpreters.  (This does not
affect the main interpreter or subinterpreters that do not have their own
GIL.)  In addition to the isolation that multi-phase init already normally
requires, support for per-interpreter GIL involves one additional
constraint: thread-safety.  If the module has external (linked)
dependencies and those libraries have any state that isn't thread-safe
then the module must do the additional work to add thread-safety.  This
should be an uncommon case.

@item 
gh-99113@footnote{https://github.com/python/cpython/issues/99113}: The GIL is now (optionally) per-interpreter.  This is the
fundamental change for PEP 684.  This is all made possible by virtue of
the isolated state of each interpreter in the process.  The behavior of
the main interpreter remains unchanged.  Likewise, interpreters created
using @code{Py_NewInterpreter()} are not affected.  To get an interpreter
with its own GIL, call @code{Py_NewInterpreterFromConfig()}.

@item 
gh-104108@footnote{https://github.com/python/cpython/issues/104108}: Multi-phase init extension modules may now indicate whether or
not they actually support multiple interpreters.  By default such modules
are expected to support use in multiple interpreters.  In the uncommon
case that one does not, it may use the new
@code{Py_mod_multiple_interpreters} module def slot.  A value of @code{0} means
the module does not support them. @code{1} means it does.  The default is
@code{1}.

@item 
gh-104142@footnote{https://github.com/python/cpython/issues/104142}: Fix an issue where @ref{24d,,list} or @ref{614,,tuple} repetition
could fail to respect 
@geindex Python Enhancement Proposals; PEP 683
PEP 683@footnote{https://peps.python.org/pep-0683/}.

@item 
gh-104078@footnote{https://github.com/python/cpython/issues/104078}: Improve the performance of @ref{61e,,PyObject_HasAttrString()}

@item 
gh-104066@footnote{https://github.com/python/cpython/issues/104066}: Improve the performance of @ref{6f9,,hasattr()} for module objects
with a missing attribute.

@item 
gh-104028@footnote{https://github.com/python/cpython/issues/104028}: Reduce object creation while calling callback function from gc.
Patch by Donghee Na.

@item 
gh-104018@footnote{https://github.com/python/cpython/issues/104018}: Disallow the "z" format specifier in %-format of bytes objects.

@item 
gh-102213@footnote{https://github.com/python/cpython/issues/102213}: Fix performance loss when accessing an object's attributes with
@code{__getattr__}  defined.

@item 
gh-103895@footnote{https://github.com/python/cpython/issues/103895}: Improve handling of edge cases in showing
@code{Exception.__notes__}. Ensures that the messages always end with a
newline and that string/bytes are not exploded over multiple lines. Patch
by Carey Metcalfe.

@item 
gh-103907@footnote{https://github.com/python/cpython/issues/103907}: Don't modify the refcounts of known immortal objects
(@ref{e07,,True}, @ref{d2b,,False}, and @ref{885,,None}) in the main interpreter
loop.

@item 
gh-103899@footnote{https://github.com/python/cpython/issues/103899}: Provide a helpful hint in the @ref{198,,TypeError} message when
accidentally calling a @ref{19de,,module} object that has a callable attribute
of the same name (such as @ref{205,,dis.dis()} or @ref{4e2,,datetime.datetime}).

@item 
gh-103845@footnote{https://github.com/python/cpython/issues/103845}: Remove both line and instruction instrumentation before adding
new ones for monitoring, to avoid newly added instrumentation being
removed immediately.

@item 
gh-103763@footnote{https://github.com/python/cpython/issues/103763}: Implement 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}, adding syntactic support for generic
classes, generic functions, and type aliases.

A new @code{type X = ...} syntax is added for type aliases, which resolves at
runtime to an instance of the new class @code{typing.TypeAliasType}. The
value is lazily evaluated and is accessible through the @code{.__value__}
attribute. This is implemented as a new AST node @code{ast.TypeAlias}.

New syntax (@code{class X[T]: ...}, @code{def func[T](): ...}) is added for
defining generic functions and classes. This is implemented as a new
@code{type_params} attribute on the AST nodes for classes and functions. This
node holds instances of the new AST classes @code{ast.TypeVar},
@code{ast.ParamSpec}, and @code{ast.TypeVarTuple}.

@code{typing.TypeVar}, @code{typing.ParamSpec}, @code{typing.ParamSpecArgs},
@code{typing.ParamSpecKwargs}, @code{typing.TypeVarTuple}, and
@code{typing.Generic} are now implemented in C rather than Python.

There are new bytecode instructions @code{LOAD_LOCALS},
@code{LOAD_CLASSDICT_OR_GLOBAL}, and @code{LOAD_CLASSDICT_OR_DEREF} to support
correct resolution of names in class namespaces.

Patch by Eric Traut, Larry Hastings, and Jelle Zijlstra.
@end itemize

@node ライブラリ<66>,Core and Builtins<61>,Core and Builtins<60>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id285}@anchor{1a92}
@subsubsection ライブラリ



@itemize -

@item 
gh-103801@footnote{https://github.com/python/cpython/issues/103801}: Adds three minor linting fixes to the wasm module caught that
were caught by ruff.

@item 
gh-103793@footnote{https://github.com/python/cpython/issues/103793}: Optimized asyncio Task creation by deferring expensive string
formatting (task name generation) from Task creation to the first time
@code{get_name} is called. This makes asyncio benchmarks up to 5% faster.
@end itemize

@node Core and Builtins<61>,ライブラリ<67>,ライブラリ<66>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id286}@anchor{1a93}
@subsubsection Core and Builtins



@itemize -

@item 
gh-102310@footnote{https://github.com/python/cpython/issues/102310}: Change the error range for invalid bytes literals.

@item 
gh-103590@footnote{https://github.com/python/cpython/issues/103590}: Do not wrap a single exception raised from a @code{try-except*}
construct in an @ref{4d2,,ExceptionGroup}.

@item 
gh-103650@footnote{https://github.com/python/cpython/issues/103650}: Change the perf map format to remove the '0x' prefix from the
addresses

@item 
gh-102856@footnote{https://github.com/python/cpython/issues/102856}: Implement the required C tokenizer changes for PEP 701. Patch
by Pablo Galindo Salgado, Lysandros Nikolaou, Batuhan Taskaya, Marta Gómez
Macías and sunmy2019.

@item 
gh-100530@footnote{https://github.com/python/cpython/issues/100530}: Clarify the error message raised when the called part of a
class pattern isn't actually a class.

@item 
gh-101517@footnote{https://github.com/python/cpython/issues/101517}: Fix bug in line numbers of instructions emitted for
@ref{1ac,,except*}.

@item 
gh-103492@footnote{https://github.com/python/cpython/issues/103492}: Clarify @ref{1ae,,SyntaxWarning} with literal @code{is} comparison by
specifying which literal is problematic, since comparisons using @code{is}
with e.g. @code{None} and bool literals are idiomatic.

@item 
gh-87729@footnote{https://github.com/python/cpython/issues/87729}: Add @ref{702,,LOAD_SUPER_ATTR} (and a specialization for
@code{super().method()}) to speed up @code{super().method()} and
@code{super().attr}. This makes @code{super().method()} roughly 2.3x faster and
brings it within 20% of the performance of a simple method call. Patch by
Vladimir Matveev and Carl Meyer.

@item 
gh-103488@footnote{https://github.com/python/cpython/issues/103488}: Change the internal offset distinguishing yield and return
target addresses, so that the instruction pointer is correct for exception
handling and other stack unwinding.

@item 
gh-82012@footnote{https://github.com/python/cpython/issues/82012}: The bitwise inversion operator (@code{~}) on bool is deprecated. It
returns the bitwise inversion of the underlying @code{int} representation
such that @code{bool(~True) == True}, which can be confusing. Use @code{not} for
logical negation of bools. In the rare case that you really need the
bitwise inversion of the underlying @code{int}, convert to int explicitly
@code{~int(x)}.

@item 
gh-77757@footnote{https://github.com/python/cpython/issues/77757}: Exceptions raised in a typeobject's @code{__set_name__} method are
no longer wrapped by a @ref{244,,RuntimeError}. Context information is added
to the exception as a 
@geindex Python Enhancement Proposals; PEP 678
PEP 678@footnote{https://peps.python.org/pep-0678/} note.

@item 
gh-103333@footnote{https://github.com/python/cpython/issues/103333}: @ref{5f0,,AttributeError} now retains the @code{name} attribute when
pickled and unpickled.

@item 
gh-103242@footnote{https://github.com/python/cpython/issues/103242}: Migrate @ref{135b,,set_ecdh_curve()} method not to
use deprecated OpenSSL APIs. Patch by Donghee Na.

@item 
gh-103323@footnote{https://github.com/python/cpython/issues/103323}: We've replaced our use of @code{_PyRuntime.tstate_current} with a
thread-local variable.  This is a fairly low-level implementation detail,
and there should be no change in behavior.

@item 
gh-84436@footnote{https://github.com/python/cpython/issues/84436}: The implementation of PEP-683 which adds Immortal Objects by
using a fixed reference count that skips reference counting to make
objects truly immutable.

@item 
gh-102700@footnote{https://github.com/python/cpython/issues/102700}: Allow built-in modules to be submodules. This allows submodules
to be statically linked into a CPython binary.

@item 
gh-103082@footnote{https://github.com/python/cpython/issues/103082}: Implement 
@geindex Python Enhancement Proposals; PEP 669
PEP 669@footnote{https://peps.python.org/pep-0669/} Low Impact Monitoring for CPython.

@item 
gh-88691@footnote{https://github.com/python/cpython/issues/88691}: Reduce the number of inline @ref{908,,CACHE} entries for
@ref{915,,CALL}.

@item 
gh-102500@footnote{https://github.com/python/cpython/issues/102500}: Make the buffer protocol accessible in Python code using the
new @code{__buffer__} and @code{__release_buffer__} magic methods. See
@geindex Python Enhancement Proposals; PEP 688
PEP 688@footnote{https://peps.python.org/pep-0688/} for details. Patch by Jelle Zijlstra.

@item 
gh-97933@footnote{https://github.com/python/cpython/issues/97933}: 
@geindex Python Enhancement Proposals; PEP 709
PEP 709@footnote{https://peps.python.org/pep-0709/}: inline list, dict and set comprehensions to improve
performance and reduce bytecode size.

@item 
gh-99184@footnote{https://github.com/python/cpython/issues/99184}: Bypass instance attribute access of @code{__name__} in @code{repr} of
@ref{11f2,,weakref.ref}.

@item 
gh-98003@footnote{https://github.com/python/cpython/issues/98003}: Complex function calls are now faster and consume no C stack
space.

@item 
bpo-39610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39610}: @code{len()} for 0-dimensional @ref{165,,memoryview} objects (such
as @code{memoryview(ctypes.c_uint8(42))}) now raises a @ref{198,,TypeError}.
Previously this returned @code{1}, which was not consistent with
@code{mem_0d[0]} raising an @ref{174e,,IndexError}.
@end itemize

@node ライブラリ<67>,ドキュメント<21>,Core and Builtins<61>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id287}@anchor{1a94}
@subsubsection ライブラリ



@itemize -

@item 
bpo-31821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31821}: Fix @code{pause_reading()} to work when called from
@code{connection_made()} in @ref{b,,asyncio}.

@item 
gh-104600@footnote{https://github.com/python/cpython/issues/104600}: @ref{1223,,functools.update_wrapper()} now sets the
@code{__type_params__} attribute (added by 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}).

@item 
gh-104340@footnote{https://github.com/python/cpython/issues/104340}: When an @code{asyncio} pipe protocol loses its connection due to
an error, and the caller doesn't await @code{wait_closed()} on the
corresponding @code{StreamWriter}, don't log a warning about an exception
that was never retrieved. After all, according to the
@code{StreamWriter.close()} docs, the @code{wait_closed()} call is optional
("not mandatory").

@item 
gh-104555@footnote{https://github.com/python/cpython/issues/104555}: Fix issue where an @ref{9c4,,issubclass()} check comparing a class
@code{X} against a @ref{675,,runtime-checkable protocol} @code{Y} with non-callable members would not
cause @ref{198,,TypeError} to be raised if an @ref{2ad,,isinstance()} call had
previously been made comparing an instance of @code{X} to @code{Y}. This issue
was present in edge cases on Python 3.11, but became more prominent in
3.12 due to some unrelated changes that were made to runtime-checkable
protocols. Patch by Alex Waygood.

@item 
gh-104372@footnote{https://github.com/python/cpython/issues/104372}: Refactored the @code{_posixsubprocess} internals to avoid Python C
API usage between fork and exec when marking @code{pass_fds=} file
descriptors inheritable.

@item 
gh-104484@footnote{https://github.com/python/cpython/issues/104484}: Added `case_sensitive' argument to
@ref{6d3,,pathlib.PurePath.match()}

@item 
gh-75367@footnote{https://github.com/python/cpython/issues/75367}: Fix data descriptor detection in
@ref{6bc,,inspect.getattr_static()}.

@item 
gh-104536@footnote{https://github.com/python/cpython/issues/104536}: Fix a race condition in the internal
@code{multiprocessing.process} cleanup logic that could manifest as an
unintended @code{AttributeError} when calling @code{process.close()}.

@item 
gh-103857@footnote{https://github.com/python/cpython/issues/103857}: Update datetime deprecations' stracktrace to point to the
calling line

@item 
gh-101520@footnote{https://github.com/python/cpython/issues/101520}: Move the core functionality of the @code{tracemalloc} module in
the @code{Python/} folder, leaving just the module wrapper in @code{Modules/}.

@item 
gh-104392@footnote{https://github.com/python/cpython/issues/104392}: Remove undocumented and unused @code{_paramspec_tvars} attribute
from some classes in @ref{10a,,typing}.

@item 
gh-102613@footnote{https://github.com/python/cpython/issues/102613}: Fix issue where @ref{537,,pathlib.Path.glob()} raised
@ref{f68,,RecursionError} when walking deep directory trees.

@item 
gh-103000@footnote{https://github.com/python/cpython/issues/103000}: Improve performance of @ref{1a95,,dataclasses.asdict()} for the
common case where `dict_factory' is @code{dict}. Patch by David C Ellis.

@item 
gh-104301@footnote{https://github.com/python/cpython/issues/104301}: Allow leading whitespace in disambiguated statements in
@ref{aa,,pdb}.

@item 
gh-104139@footnote{https://github.com/python/cpython/issues/104139}: Teach @code{urllib.parse.unsplit()} to retain the @code{"//"} when
assembling @code{itms-services://?action=generate-bugs} style Apple Platform Deployment@footnote{https://support.apple.com/en-gb/guide/deployment/depce7cefc4d/web}
URLs.

@item 
gh-104307@footnote{https://github.com/python/cpython/issues/104307}: @ref{1a3a,,socket.getnameinfo()} now releases the GIL while
contacting the DNS server

@item 
gh-104310@footnote{https://github.com/python/cpython/issues/104310}: Users may now use @code{importlib.util.allowing_all_extensions()}
(a context manager) to temporarily disable the strict compatibility checks
for importing extension modules in subinterpreters.

@item 
gh-87695@footnote{https://github.com/python/cpython/issues/87695}: Fix issue where @ref{537,,pathlib.Path.glob()} raised @ref{2c0,,OSError}
when it encountered a symlink to an overly long path.

@item 
gh-104265@footnote{https://github.com/python/cpython/issues/104265}: Prevent possible crash by disallowing instantiation of the
@code{_csv.Reader} and @code{_csv.Writer} types. The regression was
introduced in 3.10.0a4 with PR 23224 (bpo-14935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14935}). Patch by Radislav
Chugunov.

@item 
gh-102613@footnote{https://github.com/python/cpython/issues/102613}: Improve performance of @ref{537,,pathlib.Path.glob()} when expanding
recursive wildcards ("@code{**}") by merging adjacent wildcards and
de-duplicating results only when necessary.

@item 
gh-65772@footnote{https://github.com/python/cpython/issues/65772}: Remove unneeded comments and code in turtle.py.

@item 
gh-90208@footnote{https://github.com/python/cpython/issues/90208}: Fixed issue where @ref{537,,pathlib.Path.glob()} returned incomplete
results when it encountered a @ref{f3e,,PermissionError}. This method now
suppresses all @ref{2c0,,OSError} exceptions, except those raised from calling
@ref{53a,,is_dir()} on the top-level path.

@item 
gh-104144@footnote{https://github.com/python/cpython/issues/104144}: Optimize @ref{4d1,,asyncio.TaskGroup} when using
@ref{6a2,,asyncio.eager_task_factory()}. Skip scheduling a done callback if a
TaskGroup task completes eagerly.

@item 
gh-104144@footnote{https://github.com/python/cpython/issues/104144}: Optimize @ref{813,,asyncio.gather()} when using
@ref{6a2,,asyncio.eager_task_factory()} to complete eagerly if all fututres
completed eagerly. Avoid scheduling done callbacks for futures that
complete eagerly.

@item 
gh-104114@footnote{https://github.com/python/cpython/issues/104114}: Fix issue where @ref{537,,pathlib.Path.glob()} returns paths using
the case of non-wildcard segments for corresponding path segments, rather
than the real filesystem case.

@item 
gh-104104@footnote{https://github.com/python/cpython/issues/104104}: Improve performance of @ref{537,,pathlib.Path.glob()} by using
@ref{1a96,,re.IGNORECASE} to implement case-insensitive matching.

@item 
gh-104102@footnote{https://github.com/python/cpython/issues/104102}: Improve performance of @ref{537,,pathlib.Path.glob()} when
evaluating patterns that contain @code{'../'} segments.

@item 
gh-103822@footnote{https://github.com/python/cpython/issues/103822}: Update the return type of @code{weekday} to the newly added Day
attribute

@item 
gh-103629@footnote{https://github.com/python/cpython/issues/103629}: Update the @code{repr} of @ref{19a6,,typing.Unpack} according to
@geindex Python Enhancement Proposals; PEP 692
PEP 692@footnote{https://peps.python.org/pep-0692/}.

@item 
gh-103963@footnote{https://github.com/python/cpython/issues/103963}: Make @ref{3c,,dis} display the names of the args for
@code{CALL_INTRINSIC_*}.

@item 
gh-104035@footnote{https://github.com/python/cpython/issues/104035}: Do not ignore user-defined @code{__getstate__} and
@code{__setstate__} methods for slotted frozen dataclasses.

@item 
gh-103987@footnote{https://github.com/python/cpython/issues/103987}: In @ref{94,,mmap}, fix several bugs that could lead to access to
memory-mapped files after they have been invalidated.

@item 
gh-103977@footnote{https://github.com/python/cpython/issues/103977}: Improve import time of @ref{af,,platform} module.

@item 
gh-88773@footnote{https://github.com/python/cpython/issues/88773}: Added @ref{1a97,,turtle.teleport()} to the @ref{107,,turtle} module to
move a turtle to a new point without tracing a line, visible or invisible.
Patch by Liam Gersten.

@item 
gh-103935@footnote{https://github.com/python/cpython/issues/103935}: Use @ref{1a98,,io.open_code()} for files to be executed instead of
raw @ref{316,,open()}

@item 
gh-68968@footnote{https://github.com/python/cpython/issues/68968}: Fixed garbled output of @ref{74c,,assertEqual()}
when an input lacks final newline.

@item 
gh-100370@footnote{https://github.com/python/cpython/issues/100370}: Fix potential @ref{a81,,OverflowError} in
@ref{891,,sqlite3.Connection.blobopen()} for 32-bit builds. Patch by Erlend E.
Aasland.

@item 
gh-102628@footnote{https://github.com/python/cpython/issues/102628}: Substitute CTRL-D with CTRL-Z in @ref{d4,,sqlite3} CLI banner when
running on Windows.

@item 
gh-103636@footnote{https://github.com/python/cpython/issues/103636}: Module-level attributes @code{January} and @code{February} are
deprecated from @ref{15,,calendar}.

@item 
gh-103583@footnote{https://github.com/python/cpython/issues/103583}: Isolate @code{_multibytecodec} and codecs extension modules.
Patches by Erlend E. Aasland.

@item 
gh-103848@footnote{https://github.com/python/cpython/issues/103848}: Add checks to ensure that @code{[} bracketed @code{]} hosts found by
@ref{f3a,,urllib.parse.urlsplit()} are of IPv6 or IPvFuture format.

@item 
gh-103872@footnote{https://github.com/python/cpython/issues/103872}: Update the bundled copy of pip to version 23.1.2.

@item 
gh-99944@footnote{https://github.com/python/cpython/issues/99944}: Make @ref{3c,,dis} display the value of oparg of
@code{KW_NAMES}.

@item 
gh-74940@footnote{https://github.com/python/cpython/issues/74940}: The C.UTF-8 locale is no longer converted to en_US.UTF-8,
enabling the use of UTF-8 encoding on systems which have no locales
installed.

@item 
gh-103861@footnote{https://github.com/python/cpython/issues/103861}: Fix @code{zipfile.Zipfile} creating invalid zip files when
@code{force_zip64} was used to add files to them. Patch by Carey Metcalfe.

@item 
gh-103857@footnote{https://github.com/python/cpython/issues/103857}: Deprecated @ref{351,,datetime.datetime.utcnow()} and
@ref{352,,datetime.datetime.utcfromtimestamp()}. (Patch by Paul Ganssle)

@item 
gh-103839@footnote{https://github.com/python/cpython/issues/103839}: Avoid compilation error due to tommath.h not being found when
building Tkinter against Tcl 8.7 built with bundled libtommath.

@item 
gh-103791@footnote{https://github.com/python/cpython/issues/103791}: @ref{1129,,contextlib.suppress} now supports suppressing
exceptions raised as part of an @ref{4d2,,ExceptionGroup}. If other exceptions
exist on the group, they are re-raised in a group that does not contain
the suppressed exceptions.

@item 
gh-90750@footnote{https://github.com/python/cpython/issues/90750}: Use @ref{be0,,datetime.datetime.fromisocalendar()} in the
implementation of @ref{1950,,datetime.datetime.strptime()}, which should now
accept only valid ISO dates. (Patch by Paul Ganssle)

@item 
gh-103685@footnote{https://github.com/python/cpython/issues/103685}: Prepare @code{tkinter.Menu.index()} for Tk 8.7 so that it does
not raise @code{TclError: expected integer but got ""} when it should return
@code{None}.

@item 
gh-81403@footnote{https://github.com/python/cpython/issues/81403}: @ref{1a99,,urllib.request.CacheFTPHandler} no longer raises
@code{URLError} if a cached FTP instance is reused. ftplib's endtransfer
method calls voidresp to drain the connection to handle FTP instance reuse
properly.

@item 
gh-103699@footnote{https://github.com/python/cpython/issues/103699}: Add @code{__orig_bases__} to non-generic TypedDicts, call-based
TypedDicts, and call-based NamedTuples. Other TypedDicts and NamedTuples
already had the attribute.

@item 
gh-103693@footnote{https://github.com/python/cpython/issues/103693}: Add convenience variable feature to @ref{aa,,pdb}

@item 
gh-92248@footnote{https://github.com/python/cpython/issues/92248}: Deprecate @code{type}, @code{choices}, and @code{metavar} parameters of
@code{argparse.BooleanOptionalAction}.

@item 
gh-89415@footnote{https://github.com/python/cpython/issues/89415}: Add @ref{d1,,socket} constants for source-specific multicast. Patch
by Reese Hyde.

@item 
gh-103673@footnote{https://github.com/python/cpython/issues/103673}: @ref{d2,,socketserver} gains @code{ForkingUnixStreamServer} and
@code{ForkingUnixDatagramServer} classes. Patch by Jay Berry.

@item 
gh-103636@footnote{https://github.com/python/cpython/issues/103636}: Added Enum for months and days in the calendar module.

@item 
gh-84976@footnote{https://github.com/python/cpython/issues/84976}: Create a new @code{Lib/_pydatetime.py} file that defines the Python
version of the @code{datetime} module, and make @code{datetime} import the
contents of the new library only if the C implementation is missing.
Currently, the full Python implementation is defined and then deleted if
the C implementation is not available, slowing down @code{import datetime}
unnecessarily.

@item 
gh-103596@footnote{https://github.com/python/cpython/issues/103596}: Attributes/methods are no longer shadowed by same-named enum
members, although they may be shadowed by enum.property's.

@item 
gh-103584@footnote{https://github.com/python/cpython/issues/103584}: Updated @code{importlib.metadata} with changes from
@code{importlib_metadata} 5.2 through 6.5.0, including: Support
@code{installed-files.txt} for @code{Distribution.files} when present.
@code{PackageMetadata} now stipulates an additional @code{get} method allowing
for easy querying of metadata keys that may not be present.
@code{packages_distributions} now honors packages and modules with Python
modules that not @code{.py} sources (e.g. @code{.pyc}, @code{.so}). Expand protocol
for @code{PackageMetadata.get_all} to match the upstream implementation of
@code{email.message.Message.get_all} in python/typeshed#9620. Deprecated use
of @code{Distribution} without defining abstract methods. Deprecated
expectation that @code{PackageMetadata.__getitem__} will return @code{None} for
missing keys. In the future, it will raise a @code{KeyError}.

@item 
gh-103578@footnote{https://github.com/python/cpython/issues/103578}: Fixed a bug where @ref{aa,,pdb} crashes when reading source file
with different encoding by replacing @ref{740,,io.open()} with
@ref{1a98,,io.open_code()}. The new method would also call into the hook set by
@ref{1a9a,,PyFile_SetOpenCodeHook()}.

@item 
gh-103556@footnote{https://github.com/python/cpython/issues/103556}: Now creating @ref{4e3,,inspect.Signature} objects with
positional-only parameter with a default followed by a
positional-or-keyword parameter without one is impossible.

@item 
gh-103559@footnote{https://github.com/python/cpython/issues/103559}: Update the bundled copy of pip to version 23.1.1.

@item 
gh-103548@footnote{https://github.com/python/cpython/issues/103548}: Improve performance of @ref{1a26,,pathlib.Path.absolute()} and
@ref{1a9b,,cwd()} by joining paths only when necessary. Also
improve performance of @ref{1a9c,,pathlib.PurePath.is_absolute()} on Posix by
skipping path parsing and normalization.

@item 
gh-103538@footnote{https://github.com/python/cpython/issues/103538}: Remove @code{_tkinter} module code guarded by definition of the
@code{TK_AQUA} macro which was only needed for Tk 8.4.7 or earlier and was
never actually defined by any build system or documented for manual use.

@item 
gh-103533@footnote{https://github.com/python/cpython/issues/103533}: Update @ref{2b,,cProfile} to use PEP 669 API

@item 
gh-103525@footnote{https://github.com/python/cpython/issues/103525}: Fix misleading exception message when mixed @code{str} and
@code{bytes} arguments are supplied to @ref{6cd,,pathlib.PurePath} and
@ref{266,,Path}.

@item 
gh-103489@footnote{https://github.com/python/cpython/issues/103489}: Add @ref{6e0,,getconfig()} and
@ref{6e1,,setconfig()} to @ref{54d,,Connection} to
make configuration changes to a database connection. Patch by Erlend E.
Aasland.

@item 
gh-103365@footnote{https://github.com/python/cpython/issues/103365}: Set default Flag boundary to @code{STRICT} and fix bitwise
operations.

@item 
gh-103472@footnote{https://github.com/python/cpython/issues/103472}: Avoid a potential @ref{54c,,ResourceWarning} in
@ref{d35,,http.client.HTTPConnection} by closing the proxy / tunnel's
CONNECT response explicitly.

@item 
gh-103462@footnote{https://github.com/python/cpython/issues/103462}: Fixed an issue with using
@ref{17c9,,writelines()} in @ref{b,,asyncio} to send very
large payloads that exceed the amount of data that can be written in one
call to @ref{fa7,,socket.socket.send()} or @ref{6a1,,socket.socket.sendmsg()},
resulting in the remaining buffer being left unwritten.

@item 
gh-103449@footnote{https://github.com/python/cpython/issues/103449}: Fix a bug in doc string generation in
@ref{4e1,,dataclasses.dataclass()}.

@item 
gh-103092@footnote{https://github.com/python/cpython/issues/103092}: Isolate @code{_collections} (apply 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}). Patch by
Erlend E. Aasland.

@item 
gh-103357@footnote{https://github.com/python/cpython/issues/103357}: Added support for @ref{16b0,,logging.Formatter} @code{defaults}
parameter to @ref{13c8,,logging.config.dictConfig()} and
@ref{d48,,logging.config.fileConfig()}. Patch by Bar Harel.

@item 
gh-103092@footnote{https://github.com/python/cpython/issues/103092}: Adapt the @ref{11c,,winreg} extension module to 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}.

@item 
gh-74690@footnote{https://github.com/python/cpython/issues/74690}: The performance of @ref{2ad,,isinstance()} checks against
@ref{675,,runtime-checkable protocols} has been
considerably improved for protocols that only have a few members. To
achieve this improvement, several internal implementation details of the
@ref{10a,,typing} module have been refactored, including
@code{typing._ProtocolMeta.__instancecheck__},
@code{typing._is_callable_members_only}, and @code{typing._get_protocol_attrs}.
Patches by Alex Waygood.

@item 
gh-74690@footnote{https://github.com/python/cpython/issues/74690}: The members of a runtime-checkable protocol are now considered
"frozen" at runtime as soon as the class has been created. See
@ref{6f8,,"What's new in Python 3.12"} for more
details.

@item 
gh-103256@footnote{https://github.com/python/cpython/issues/103256}: Fixed a bug that caused @ref{6e,,hmac} to raise an exception when
the requested hash algorithm was not available in OpenSSL despite being
available separately as part of @code{hashlib} itself.  It now falls back
properly to the built-in. This could happen when, for example, your
OpenSSL does not include SHA3 support and you want to compute
@code{hmac.digest(b'K', b'M', 'sha3_256')}.

@item 
gh-102778@footnote{https://github.com/python/cpython/issues/102778}: Support @code{sys.last_exc} in @ref{77,,idlelib}.

@item 
gh-103285@footnote{https://github.com/python/cpython/issues/103285}: Improve performance of @ref{bcb,,ast.get_source_segment()}.

@item 
gh-103225@footnote{https://github.com/python/cpython/issues/103225}: Fix a bug in @ref{aa,,pdb} when displaying line numbers of
module-level source code.

@item 
gh-103092@footnote{https://github.com/python/cpython/issues/103092}: Adapt the @ref{97,,msvcrt} extension module to 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}.

@item 
gh-103092@footnote{https://github.com/python/cpython/issues/103092}: Adapt the @ref{11d,,winsound} extension module to 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}.

@item 
gh-93910@footnote{https://github.com/python/cpython/issues/93910}: Remove deprecation of enum @code{member.member} access.

@item 
gh-102978@footnote{https://github.com/python/cpython/issues/102978}: Fixes @ref{1092,,unittest.mock.patch()} not enforcing function
signatures for methods decorated with @code{@@classmethod} or
@code{@@staticmethod} when patch is called with @code{autospec=True}.

@item 
gh-103092@footnote{https://github.com/python/cpython/issues/103092}: Isolate @code{_socket} (apply 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}). Patch by Erlend E.
Aasland.

@item 
gh-100479@footnote{https://github.com/python/cpython/issues/100479}: Add @ref{6ce,,pathlib.PurePath.with_segments()}, which creates a
path object from arguments. This method is called whenever a derivative
path is created, such as from @ref{1a9d,,pathlib.PurePath.parent}. Subclasses
may override this method to share information between path objects.

@item 
gh-103220@footnote{https://github.com/python/cpython/issues/103220}: Fix issue where @ref{19a9,,os.path.join()} added a slash when joining
onto an incomplete UNC drive with a trailing slash on Windows.

@item 
gh-103204@footnote{https://github.com/python/cpython/issues/103204}: Fixes @ref{76,,http.server} accepting HTTP requests with HTTP
version numbers preceded by '+', or '-', or with digit-separating '_'
characters.  The length of the version numbers is also constrained.

@item 
gh-75586@footnote{https://github.com/python/cpython/issues/75586}: Fix various Windows-specific issues with @code{shutil.which}.

@item 
gh-103193@footnote{https://github.com/python/cpython/issues/103193}: Improve performance of @ref{6bc,,inspect.getattr_static()}. Patch by
Alex Waygood.

@item 
gh-103176@footnote{https://github.com/python/cpython/issues/103176}: @ref{6e9,,sys._current_exceptions()} now returns a mapping from
thread-id to an exception instance, rather than to a @code{(typ, exc, tb)}
tuple.

@item 
gh-103143@footnote{https://github.com/python/cpython/issues/103143}: Polish the help messages and docstrings of @ref{aa,,pdb}.

@item 
gh-103015@footnote{https://github.com/python/cpython/issues/103015}: Add `entrypoint' keyword-only parameter to
@ref{6df,,sqlite3.Connection.load_extension()}, for overriding the SQLite
extension entry point. Patch by Erlend E. Aasland.

@item 
gh-103000@footnote{https://github.com/python/cpython/issues/103000}: Improve performance of @ref{1a9e,,dataclasses.astuple()} and
@ref{1a95,,dataclasses.asdict()} in cases where the contents are common Python
types.

@item 
gh-102953@footnote{https://github.com/python/cpython/issues/102953}: The extraction methods in @ref{e4,,tarfile}, and
@ref{696,,shutil.unpack_archive()}, have a new a `filter' argument that allows
limiting tar features than may be surprising or dangerous, such as
creating files outside the destination directory. See
@ref{697,,Extraction filters} for details.

@item 
gh-97696@footnote{https://github.com/python/cpython/issues/97696}: Implemented an eager task factory in asyncio. When used as a
task factory on an event loop, it performs eager execution of coroutines.
Coroutines that are able to complete synchronously (e.g. return or raise
without blocking) are returned immediately as a finished task, and the
task is never scheduled to the event loop. If the coroutine blocks, the
(pending) task is scheduled and returned.

@item 
gh-81079@footnote{https://github.com/python/cpython/issues/81079}: Add `case_sensitive' keyword-only argument to
@ref{537,,pathlib.Path.glob()} and @ref{538,,rglob()}.

@item 
gh-101819@footnote{https://github.com/python/cpython/issues/101819}: Isolate the @ref{83,,io} extension module by applying 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}.
Patch by Kumar Aditya, Victor Stinner, and Erlend E. Aasland.

@item 
gh-91896@footnote{https://github.com/python/cpython/issues/91896}: Deprecate @ref{342,,collections.abc.ByteString}

@item 
gh-101362@footnote{https://github.com/python/cpython/issues/101362}: Speed up @ref{266,,pathlib.Path} construction by omitting the
path anchor from the internal list of path parts.

@item 
gh-102114@footnote{https://github.com/python/cpython/issues/102114}: Functions in the @ref{3c,,dis} module that accept a source code
string as argument now print a more concise traceback when the string
contains a syntax or indentation error.

@item 
gh-62432@footnote{https://github.com/python/cpython/issues/62432}: The @ref{10c,,unittest} runner will now exit with status code 5 if
no tests were run. It is common for test runner misconfiguration to fail
to find any tests, this should be an error.

@item 
gh-78079@footnote{https://github.com/python/cpython/issues/78079}: Fix incorrect normalization of UNC device path roots, and
partial UNC share path roots, in @ref{6cd,,pathlib.PurePath}. Pathlib no
longer appends a trailing slash to such paths.

@item 
gh-85984@footnote{https://github.com/python/cpython/issues/85984}: Add @ref{1a42,,tty.cfmakeraw()} and @ref{19f6,,tty.cfmakecbreak()} to
@ref{106,,tty} and modernize, the behavior of @ref{1a41,,tty.setraw()} and
@ref{19f5,,tty.setcbreak()} to use POSIX.1-2017 Chapter 11 "General Terminal
Interface" flag masks by default.

@item 
gh-101688@footnote{https://github.com/python/cpython/issues/101688}: Implement @ref{6f5,,types.get_original_bases()} to provide further
introspection for types.

@item 
gh-101640@footnote{https://github.com/python/cpython/issues/101640}: @ref{1bd,,argparse.ArgumentParser} now catches errors when
writing messages, such as when @ref{b33,,sys.stderr} is @code{None}. Patch by
Oleg Iarygin.

@item 
gh-83861@footnote{https://github.com/python/cpython/issues/83861}: Fix datetime.astimezone method return value when invoked on a
naive datetime instance that represents local time falling in a timezone
transition gap. PEP 495 requires that instances with fold=1 produce
earlier times than those with fold=0 in this case.

@item 
gh-89550@footnote{https://github.com/python/cpython/issues/89550}: Decrease execution time of some @ref{6b,,gzip} file writes by 15%
by adding more appropriate buffering.

@item 
gh-95299@footnote{https://github.com/python/cpython/issues/95299}: Remove the bundled setuptools wheel from @code{ensurepip}, and stop
installing setuptools in environments created by @code{venv}.

@item 
gh-99353@footnote{https://github.com/python/cpython/issues/99353}: Respect the @ref{d35,,http.client.HTTPConnection} @code{.debuglevel}
flag in @code{urllib.request.AbstractHTTPHandler} when its constructor
parameter @code{debuglevel} is not set. And do the same for @code{*HTTPS*}.

@item 
gh-98040@footnote{https://github.com/python/cpython/issues/98040}: Remove the long-deprecated @code{imp} module.

@item 
gh-97850@footnote{https://github.com/python/cpython/issues/97850}: Deprecate @code{pkgutil.find_loader()} and
@code{pkgutil.get_loader()} in favor of @ref{5af,,importlib.util.find_spec()}.

@item 
gh-94473@footnote{https://github.com/python/cpython/issues/94473}: Flatten arguments in @code{tkinter.Canvas.coords()}. It now
accepts not only @code{x1, y1, x2, y2, ...} and @code{[x1, y1, x2, y2, ...]},
but also @code{(x1, y1), (x2, y2), ...} and @code{[(x1, y1), (x2, y2), ...]}.

@item 
gh-98040@footnote{https://github.com/python/cpython/issues/98040}: Remove more deprecated importlib APIs: @code{find_loader()},
@code{find_module()}, @code{importlib.abc.Finder}, @code{pkgutil.ImpImporter},
@code{pkgutil.ImpLoader}.

@item 
gh-96522@footnote{https://github.com/python/cpython/issues/96522}: Fix potential deadlock in pty.spawn()

@item 
gh-96534@footnote{https://github.com/python/cpython/issues/96534}: Support divert(4) added in FreeBSD 14.

@item 
gh-87474@footnote{https://github.com/python/cpython/issues/87474}: Fix potential file descriptor leaks in
@ref{4b7,,subprocess.Popen}.

@item 
gh-94906@footnote{https://github.com/python/cpython/issues/94906}: Support multiple steps in @ref{6c0,,math.nextafter()}. Patch by
Shantanu Jain and Matthias Gorgens.

@item 
gh-51574@footnote{https://github.com/python/cpython/issues/51574}: Make @ref{52d,,tempfile.mkdtemp()} return absolute paths when its
`dir' parameter is relative.

@item 
gh-94518@footnote{https://github.com/python/cpython/issues/94518}: Convert private @code{_posixsubprocess.fork_exec()} to use
Argument Clinic.

@item 
gh-92184@footnote{https://github.com/python/cpython/issues/92184}: When creating zip files using @ref{137,,zipfile}, @code{os.altsep}, if
not @code{None}, will always be treated as a path separator even when it is
not @code{/}. Patch by Carey Metcalfe.

@item 
bpo-46797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46797}: Deprecation warnings are now emitted for @code{ast.Num},
@code{ast.Bytes}, @code{ast.Str}, @code{ast.NameConstant} and
@code{ast.Ellipsis}. These have been documented as deprecated since
Python 3.8, and will be removed in Python 3.14.

@item 
bpo-44844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44844}: Enables @ref{11b,,webbrowser} to detect and launch Microsoft Edge
browser.

@item 
bpo-45606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45606}: Fixed the bug in @ref{537,,pathlib.Path.glob()} -- previously a
dangling symlink would not be found by this method when the pattern is an
exact match, but would be found when the pattern contains a wildcard or
the recursive wildcard (@code{**}). With this change, a dangling symlink will
be found in both cases.

@item 
bpo-23041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23041}: Add @ref{6ad,,QUOTE_STRINGS} and @ref{6ac,,QUOTE_NOTNULL}
to the suite of @ref{2d,,csv} module quoting styles.

@item 
bpo-24964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24964}: Added
@ref{1a73,,http.client.HTTPConnection.get_proxy_response_headers()} that
provides access to the HTTP headers on a proxy server response to the
@code{CONNECT} request.

@item 
bpo-17258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17258}: @ref{98,,multiprocessing} now supports stronger HMAC algorithms
for inter-process connection authentication rather than only HMAC-MD5.

@item 
bpo-39744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39744}: Make @ref{1a9f,,asyncio.subprocess.Process.communicate()} close the
subprocess's stdin even when called with @code{input=None}.

@item 
bpo-22708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22708}: http.client CONNECT method tunnel improvements: Use HTTP 1.1
protocol; send a matching Host: header with CONNECT, if one is not
provided; convert IDN domain names to Punycode. Patch by Michael Handler.
@end itemize

@node ドキュメント<21>,テスト<20>,ライブラリ<67>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id288}@anchor{1aa0}
@subsubsection ドキュメント



@itemize -

@item 
gh-67056@footnote{https://github.com/python/cpython/issues/67056}: Document that the effect of registering or unregistering an
@ref{d,,atexit} cleanup function from within a registered cleanup function
is undefined.

@item 
gh-103629@footnote{https://github.com/python/cpython/issues/103629}: Mention the new way of typing @code{**kwargs} with @code{Unpack} and
@code{TypedDict} introduced in 
@geindex Python Enhancement Proposals; PEP 692
PEP 692@footnote{https://peps.python.org/pep-0692/}.

@item 
gh-48241@footnote{https://github.com/python/cpython/issues/48241}: Clarifying documentation about the url parameter to
urllib.request.urlopen and urllib.request.Request needing to be encoded
properly.

@item 
gh-86094@footnote{https://github.com/python/cpython/issues/86094}: Add support for Unicode Path Extra Field in ZipFile. Patch by
Yeojin Kim and Andrea Giudiceandrea

@item 
gh-99202@footnote{https://github.com/python/cpython/issues/99202}: Fix extension type from documentation for compiling in C++20
mode
@end itemize

@node テスト<20>,ビルド<23>,ドキュメント<21>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id289}@anchor{1aa1}
@subsubsection テスト



@itemize -

@item 
gh-104494@footnote{https://github.com/python/cpython/issues/104494}: Update @code{test_pack_configure_in} and
@code{test_place_configure_in} for changes to error message formatting in Tk
8.7.

@item 
gh-104461@footnote{https://github.com/python/cpython/issues/104461}: Run test_configure_screen on X11 only, since the @code{DISPLAY}
environment variable and @code{-screen} option for toplevels are not useful
on Tk for Win32 or Aqua.

@item 
gh-86275@footnote{https://github.com/python/cpython/issues/86275}: Added property-based tests to the @ref{13a,,zoneinfo} tests, along
with stubs for the @code{hypothesis} interface. (Patch by Paul Ganssle)

@item 
gh-103329@footnote{https://github.com/python/cpython/issues/103329}: Regression tests for the behaviour of
@code{unittest.mock.PropertyMock} were added.

@item 
gh-102795@footnote{https://github.com/python/cpython/issues/102795}: fix use of poll in test_epoll's test_control_and_wait

@item 
gh-75729@footnote{https://github.com/python/cpython/issues/75729}: Fix the @ref{31b,,os.spawn*} tests failing on Windows
when the working directory or interpreter path contains spaces.
@end itemize

@node ビルド<23>,Windows<22>,テスト<20>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id290}@anchor{1aa2}
@subsubsection ビルド



@itemize -

@item 
gh-101282@footnote{https://github.com/python/cpython/issues/101282}: BOLT optimization is now applied to the libpython shared
library if building a shared library. BOLT instrumentation and application
settings can now be influenced via the @code{BOLT_INSTRUMENT_FLAGS} and
@code{BOLT_APPLY_FLAGS} configure variables.

@item 
gh-99017@footnote{https://github.com/python/cpython/issues/99017}: @code{PYTHON_FOR_REGEN} now require Python 3.10 or newer.

@item 
gh-104490@footnote{https://github.com/python/cpython/issues/104490}: Define @code{.PHONY} / virtual make targets consistently and
properly.

@item 
gh-104106@footnote{https://github.com/python/cpython/issues/104106}: Add gcc fallback of mkfifoat/mknodat for macOS. Patch by
Donghee Na.

@item 
gh-103532@footnote{https://github.com/python/cpython/issues/103532}: The @code{TKINTER_PROTECT_LOADTK} macro is no longer defined or
used in the @code{_tkinter} module.  It was previously only defined when
building against Tk 8.4.13 and older, but Tk older than 8.5.12 has been
unsupported since gh-91152@footnote{https://github.com/python/cpython/issues/91152}.

@item 
gh-99069@footnote{https://github.com/python/cpython/issues/99069}: Extended workaround defining @code{static_assert} when missing from
the libc headers to all clang and gcc builds. In particular, this fixes
building on macOS <= 10.10.

@item 
gh-100220@footnote{https://github.com/python/cpython/issues/100220}: Changed the default value of the @code{SHELL} Makefile variable
from @code{/bin/sh} to @code{/bin/sh -e} to ensure that complex recipes
correctly fail after an error. Previously, @code{make install} could fail to
install some files and yet return a successful result.

@item 
gh-90656@footnote{https://github.com/python/cpython/issues/90656}: Add platform triplets for 64-bit LoongArch:


@itemize *

@item 
loongarch64-linux-gnusf

@item 
loongarch64-linux-gnuf32

@item 
loongarch64-linux-gnu
@end itemize

Patch by Zhang Na.
@end itemize

@node Windows<22>,macOS<15>,ビルド<23>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id291}@anchor{1aa3}
@subsubsection Windows



@itemize -

@item 
gh-104623@footnote{https://github.com/python/cpython/issues/104623}: Update Windows installer to use SQLite 3.42.0.

@item 
gh-82814@footnote{https://github.com/python/cpython/issues/82814}: Fix a potential @code{[Errno 13] Permission denied} when using
@ref{1346,,shutil.copystat()} within Windows Subsystem for Linux (WSL) on a
mounted filesystem by adding @code{errno.EACCES} to the list of ignored
errors within the internal implementation.

@item 
gh-103088@footnote{https://github.com/python/cpython/issues/103088}: Fix virtual environment @code{activate} script having
incorrect line endings for Cygwin.

@item 
gh-103088@footnote{https://github.com/python/cpython/issues/103088}: Fixes venvs not working in bash on Windows across different
disks

@item 
gh-102997@footnote{https://github.com/python/cpython/issues/102997}: Update Windows installer to use SQLite 3.41.2.

@item 
gh-88013@footnote{https://github.com/python/cpython/issues/88013}: Fixed a bug where @ref{198,,TypeError} was raised when calling
@code{ntpath.realpath()} with a bytes parameter in some cases.
@end itemize

@node macOS<15>,IDLE<14>,Windows<22>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id292}@anchor{1aa4}
@subsubsection macOS



@itemize -

@item 
gh-99834@footnote{https://github.com/python/cpython/issues/99834}: Update macOS installer to Tcl/Tk 8.6.13.

@item 
gh-104623@footnote{https://github.com/python/cpython/issues/104623}: Update macOS installer to SQLite 3.42.0.

@item 
gh-103545@footnote{https://github.com/python/cpython/issues/103545}: Add @code{os.PRIO_DARWIN_THREAD}, @code{os.PRIO_DARWIN_PROCESS},
@code{os.PRIO_DARWIN_BG} and @code{os.PRIO_DARWIN_NONUI}. These can be used with
@code{os.setpriority} to run the process at a lower priority and make use of
the efficiency cores on Apple Silicon systems.

@item 
gh-104180@footnote{https://github.com/python/cpython/issues/104180}: Support reading SOCKS proxy configuration from macOS System
Configuration. Patch by Sam Schott.

@item 
gh-60436@footnote{https://github.com/python/cpython/issues/60436}: update curses textbox to additionally handle backspace using the
@code{curses.ascii.DEL} key press.

@item 
gh-102997@footnote{https://github.com/python/cpython/issues/102997}: Update macOS installer to SQLite 3.41.2.
@end itemize

@node IDLE<14>,Tools/Demos<20>,macOS<15>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id293}@anchor{1aa5}
@subsubsection IDLE



@itemize -

@item 
gh-104499@footnote{https://github.com/python/cpython/issues/104499}: Fix completions for Tk Aqua 8.7 (currently blank).

@item 
gh-104496@footnote{https://github.com/python/cpython/issues/104496}: About prints both tcl and tk versions if different (expected
someday).

@item 
gh-88496@footnote{https://github.com/python/cpython/issues/88496}: Fix IDLE test hang on macOS.
@end itemize

@node Tools/Demos<20>,C API<23>,IDLE<14>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id294}@anchor{1aa6}
@subsubsection Tools/Demos



@itemize -

@item 
gh-104389@footnote{https://github.com/python/cpython/issues/104389}: Argument Clinic C converters now accept the @code{unused} keyword,
for wrapping a parameter with @ref{1a8a,,Py_UNUSED}. Patch by Erlend E.
Aasland.
@end itemize

@node C API<23>,,Tools/Demos<20>,Python 3 12 0 beta 1
@anchor{whatsnew/changelog id295}@anchor{1aa7}
@subsubsection C API



@itemize -

@item 
gh-101291@footnote{https://github.com/python/cpython/issues/101291}: Added unstable C API for extracting the value of "compact"
integers: @ref{7a6,,PyUnstable_Long_IsCompact()} and
@ref{7a7,,PyUnstable_Long_CompactValue()}.

@item 
gh-104109@footnote{https://github.com/python/cpython/issues/104109}: We've added @code{Py_NewInterpreterFromConfig()} and
@code{PyInterpreterConfig} to the public C-API (but not the stable ABI; not
yet at least).  The new function may be used to create a new interpreter
with various features configured.  The function was added to support PEP
684 (per-interpreter GIL).

@item 
gh-103968@footnote{https://github.com/python/cpython/issues/103968}: @ref{79d,,PyType_FromSpec()} and its variants now allow creating
classes whose metaclass overrides @ref{79f,,tp_new}. The
@code{tp_new} is ignored. This behavior is deprecated and will be disallowed
in 3.14+. The new @ref{772,,PyType_FromMetaclass()} already disallows it.

@item 
gh-103743@footnote{https://github.com/python/cpython/issues/103743}: Add @ref{1aa8,,PyUnstable_Object_GC_NewWithExtraData()} function
that can be used to allocate additional memory after an object for data
not managed by Python.

@item 
gh-103295@footnote{https://github.com/python/cpython/issues/103295}: Introduced @ref{1aa9,,PyUnstable_WritePerfMapEntry()},
@ref{1aaa,,PyUnstable_PerfMapState_Init()} and
@ref{1aab,,PyUnstable_PerfMapState_Fini()}. These allow extension modules (JIT
compilers in particular) to write to perf-map files in a thread safe
manner. The @ref{1aac,,Python support for the Linux perf profiler} also uses these APIs to write
entries in the perf-map file.

@item 
gh-103509@footnote{https://github.com/python/cpython/issues/103509}: Added C API for extending types whose instance memory layout is
opaque: @ref{76a,,PyType_Spec.basicsize} can now be zero or negative,
@ref{76b,,PyObject_GetTypeData()} can be used to get subclass-specific data,
and @ref{76d,,Py_TPFLAGS_ITEMS_AT_END} can be used to safely extend
variable-size objects. See 
@geindex Python Enhancement Proposals; PEP 697
PEP 697@footnote{https://peps.python.org/pep-0697/} for details.

@item 
gh-103091@footnote{https://github.com/python/cpython/issues/103091}: Add a new C-API function to eagerly assign a version tag to a
PyTypeObject: @code{PyUnstable_Type_AssignVersionTag()}.

@item 
gh-101408@footnote{https://github.com/python/cpython/issues/101408}: @ref{1aad,,PyObject_GC_Resize} should calculate preheader size
if needed. Patch by Donghee Na.

@item 
gh-98836@footnote{https://github.com/python/cpython/issues/98836}: Add support of more formatting options (left aligning, octals,
uppercase hexadecimals, @code{intmax_t}, @code{ptrdiff_t},
@code{wchar_t} C strings, variable width and precision) in
@ref{62b,,PyUnicode_FromFormat()} and @ref{794,,PyUnicode_FromFormatV()}.

@item 
gh-96803@footnote{https://github.com/python/cpython/issues/96803}: Add unstable C-API functions to get the code object, lasti and
line number from the internal @code{_PyInterpreterFrame} in the limited API.
The functions are:


@itemize *

@item 
@code{PyCodeObject * PyUnstable_InterpreterFrame_GetCode(struct _PyInterpreterFrame *frame)}

@item 
@code{int PyUnstable_InterpreterFrame_GetLasti(struct _PyInterpreterFrame *frame)}

@item 
@code{int PyUnstable_InterpreterFrame_GetLine(struct _PyInterpreterFrame *frame)}
@end itemize
@end itemize

@node Python 3 12 0 alpha 7,Python 3 12 0 alpha 6,Python 3 12 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-12-0-alpha-7}@anchor{1aae}
@subsection Python 3.12.0 alpha 7


`Release date: 2023-04-04'

@menu
* Core and Builtins: Core and Builtins<62>. 
* ライブラリ: ライブラリ<68>. 
* Core and Builtins: Core and Builtins<63>. 
* ビルド: ビルド<24>. 
* Core and Builtins: Core and Builtins<64>. 
* ライブラリ: ライブラリ<69>. 
* ドキュメント: ドキュメント<22>. 
* テスト: テスト<21>. 
* ビルド: ビルド<25>. 
* Windows: Windows<23>. 
* Tools/Demos: Tools/Demos<21>. 
* C API: C API<24>. 

@end menu

@node Core and Builtins<62>,ライブラリ<68>,,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id296}@anchor{1aaf}
@subsubsection Core and Builtins



@itemize -

@item 
gh-102192@footnote{https://github.com/python/cpython/issues/102192}: Deprecated @code{_PyErr_ChainExceptions} in favour of
@code{_PyErr_ChainExceptions1}.

@item 
gh-89987@footnote{https://github.com/python/cpython/issues/89987}: Reduce the number of inline @ref{908,,CACHE} entries for
@code{BINARY_SUBSCR}.

@item 
gh-102859@footnote{https://github.com/python/cpython/issues/102859}: Removed @code{JUMP_IF_FALSE_OR_POP} and
@code{JUMP_IF_TRUE_OR_POP} instructions.

@item 
gh-101975@footnote{https://github.com/python/cpython/issues/101975}: Fixed @code{stacktop} value on tracing entries to avoid corruption
on garbage collection.

@item 
gh-102778@footnote{https://github.com/python/cpython/issues/102778}: Add @ref{6e5,,sys.last_exc} and deprecate @ref{6e6,,sys.last_type},
@ref{6e7,,sys.last_value} and @ref{6e8,,sys.last_traceback}, which hold the same
information in its legacy form.

@item 
gh-100982@footnote{https://github.com/python/cpython/issues/100982}: Replace all occurrences of @code{COMPARE_AND_BRANCH} with
@ref{b61,,COMPARE_OP}.

@item 
gh-102701@footnote{https://github.com/python/cpython/issues/102701}: Fix overflow when creating very large dict.

@item 
gh-102755@footnote{https://github.com/python/cpython/issues/102755}: Add @ref{435,,PyErr_DisplayException()} which takes just an
exception instance, to replace the legacy @code{PyErr_Display()} which
takes the @code{(typ, exc, tb)} triplet.

@item 
gh-102594@footnote{https://github.com/python/cpython/issues/102594}: Add note to exception raised in @code{PyErr_SetObject} when
normalization fails.

@item 
gh-90997@footnote{https://github.com/python/cpython/issues/90997}: Shrink the number of inline @ref{908,,CACHE} entries used by
@ref{1a5a,,LOAD_GLOBAL}.
@end itemize

@node ライブラリ<68>,Core and Builtins<63>,Core and Builtins<62>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id297}@anchor{1ab0}
@subsubsection ライブラリ



@itemize -

@item 
gh-102491@footnote{https://github.com/python/cpython/issues/102491}: Improve import time of @code{platform} by removing IronPython
version parsing. The IronPython version parsing was not functional (see
@indicateurl{https://github.com/IronLanguages/ironpython3/issues/1667}).
@end itemize

@node Core and Builtins<63>,ビルド<24>,ライブラリ<68>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id298}@anchor{1ab1}
@subsubsection Core and Builtins



@itemize -

@item 
gh-101291@footnote{https://github.com/python/cpython/issues/101291}: Rearrage bits in first field (after header) of PyLongObject. *
Bits 0 and 1: 1 - sign. I.e. 0 for positive numbers, 1 for zero and 2 for
negative numbers. * Bit 2 reserved (probably for the immortal bit) * Bits
3+ the unsigned size.

This makes a few operations slightly more efficient, and will enable a
more compact and faster 2s-complement representation of most ints in
future.

@item 
gh-102397@footnote{https://github.com/python/cpython/issues/102397}: Fix segfault from race condition in signal handling during
garbage collection. Patch by Kumar Aditya.

@item 
gh-102406@footnote{https://github.com/python/cpython/issues/102406}: @ref{1c,,codecs} encoding/decoding errors now get the context
information (which operation and which codecs) attached as 
@geindex Python Enhancement Proposals; PEP 678
PEP 678@footnote{https://peps.python.org/pep-0678/}
notes instead of through chaining a new instance of the exception.

@item 
gh-102281@footnote{https://github.com/python/cpython/issues/102281}: Fix potential nullptr dereference and use of uninitialized
memory in fileutils. Patch by Max Bachmann.

@item 
gh-102300@footnote{https://github.com/python/cpython/issues/102300}: Reuse operands with refcount of 1 in float specializations of
BINARY_OP.

@item 
gh-102213@footnote{https://github.com/python/cpython/issues/102213}: Fix performance loss when accessing an object's attributes with
@code{__getattr__}  defined.

@item 
gh-102255@footnote{https://github.com/python/cpython/issues/102255}: Improve build support for the Xbox. Patch by Max Bachmann.
@end itemize

@node ビルド<24>,Core and Builtins<64>,Core and Builtins<63>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id299}@anchor{1ab2}
@subsubsection ビルド



@itemize -

@item 
gh-102027@footnote{https://github.com/python/cpython/issues/102027}: Fix SSE2 and SSE3 detection in @code{_blake2} internal module.
Patch by Max Bachmann.
@end itemize

@node Core and Builtins<64>,ライブラリ<69>,ビルド<24>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id300}@anchor{1ab3}
@subsubsection Core and Builtins



@itemize -

@item 
gh-101865@footnote{https://github.com/python/cpython/issues/101865}: Deprecate @code{co_lnotab} in code objects, schedule it for
removal in Python 3.14
@end itemize

@node ライブラリ<69>,ドキュメント<22>,Core and Builtins<64>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id301}@anchor{1ab4}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Adapt @code{_pickle} to 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}. Patch by Mohamed Koubaa
and Erlend Aasland.

@item 
gh-103085@footnote{https://github.com/python/cpython/issues/103085}: Pure python @ref{329,,locale.getencoding()} will not warn
deprecation.

@item 
gh-103068@footnote{https://github.com/python/cpython/issues/103068}: It's no longer possible to register conditional breakpoints in
@ref{273,,Pdb} that raise @ref{18e,,SyntaxError}. Patch by Tian Gao.

@item 
gh-102549@footnote{https://github.com/python/cpython/issues/102549}: Don't ignore exceptions in member type creation.

@item 
gh-103056@footnote{https://github.com/python/cpython/issues/103056}: Ensure final @code{_generate_next_value_} is a @code{staticmethod}.

@item 
gh-103046@footnote{https://github.com/python/cpython/issues/103046}: Display current line label correctly in @ref{3c,,dis} when
@code{show_caches} is False and @code{lasti} points to a CACHE entry.

@item 
gh-102433@footnote{https://github.com/python/cpython/issues/102433}: @ref{2ad,,isinstance()} checks against @ref{675,,runtime-checkable protocols} now use
@ref{6bc,,inspect.getattr_static()} rather than @ref{6f9,,hasattr()} to lookup
whether attributes exist. This means that descriptors and
@ref{6fa,,__getattr__()} methods are no longer unexpectedly evaluated
during @code{isinstance()} checks against runtime-checkable protocols.
However, it may also mean that some objects which used to be considered
instances of a runtime-checkable protocol may no longer be considered
instances of that protocol on Python 3.12+, and vice versa. Most users are
unlikely to be affected by this change. Patch by Alex Waygood.

@item 
gh-103023@footnote{https://github.com/python/cpython/issues/103023}: It's no longer possible to register expressions to display in
@ref{273,,Pdb} that raise @ref{18e,,SyntaxError}. Patch by Tian Gao.

@item 
gh-102947@footnote{https://github.com/python/cpython/issues/102947}: Improve traceback when @ref{1935,,dataclasses.fields()} is called on
a non-dataclass. Patch by Alex Waygood

@item 
gh-102780@footnote{https://github.com/python/cpython/issues/102780}: The @ref{1a40,,asyncio.Timeout} context manager now works reliably
even when performing cleanup due to task cancellation.  Previously it
could raise a @ref{4d4,,CancelledError} instead of an
@ref{1ab5,,TimeoutError} in such cases.

@item 
gh-102871@footnote{https://github.com/python/cpython/issues/102871}: Remove support for obsolete browsers from @ref{11b,,webbrowser}.
Removed browsers include Grail, Mosaic, Netscape, Galeon, Skipstone,
Iceape, Firebird, and Firefox versions 35 and below.

@item 
gh-102839@footnote{https://github.com/python/cpython/issues/102839}: Improve performance of @ref{16d9,,math.log()} arguments handling by
removing the argument clinic.

@item 
gh-102828@footnote{https://github.com/python/cpython/issues/102828}: Add the @code{onexc} arg to @ref{356,,shutil.rmtree()}, which is like
@code{onerror} but expects an exception instance rather than an exc_info
tuple. Deprecate @code{onerror}.

@item 
gh-88965@footnote{https://github.com/python/cpython/issues/88965}: typing: Fix a bug relating to substitution in custom classes
generic over a @ref{487,,ParamSpec}. Previously, if the
@code{ParamSpec} was substituted with a parameters list that itself contained
a @ref{486,,TypeVar}, the @code{TypeVar} in the parameters list could
not be subsequently substituted. This is now fixed.

Patch by Nikita Sobolev.

@item 
gh-76846@footnote{https://github.com/python/cpython/issues/76846}: Fix issue where @code{__new__()} and @code{__init__()} methods of
@ref{6cd,,pathlib.PurePath} and @ref{266,,Path} subclasses were not
called in some circumstances.

@item 
gh-78530@footnote{https://github.com/python/cpython/issues/78530}: @ref{6a7,,asyncio.wait()} now accepts generators yielding tasks.
Patch by Kumar Aditya.

@item 
gh-102748@footnote{https://github.com/python/cpython/issues/102748}: @ref{6a6,,asyncio.iscoroutine()} now returns @code{False} for
generators as @ref{b,,asyncio} does not support legacy generator-based
coroutines. Patch by Kumar Aditya.

@item 
gh-102670@footnote{https://github.com/python/cpython/issues/102670}: Optimized fmean(), correlation(), covariance(), and
linear_regression() using the new math.sumprod() function.

@item 
gh-102615@footnote{https://github.com/python/cpython/issues/102615}: Typing: Improve the @code{repr} of generic aliases for classes
generic over a @ref{487,,ParamSpec}. (Use square brackets to
represent a parameter list.)

@item 
gh-100112@footnote{https://github.com/python/cpython/issues/100112}: @ref{bcf,,asyncio.Task.get_coro()} now always returns a coroutine
when wrapping an awaitable object. Patch by Kumar Aditya.

@item 
gh-102578@footnote{https://github.com/python/cpython/issues/102578}: Speed up setting or deleting mutable attributes on
non-dataclass subclasses of frozen dataclasses. Due to the implementation
of @code{__setattr__} and @code{__delattr__} for frozen dataclasses, this
previously had a time complexity of `O'(`n'). It now has a time
complexity of `O'(1).

@item 
gh-102519@footnote{https://github.com/python/cpython/issues/102519}: Add @ref{6c5,,os.listdrives()}, @ref{6c6,,os.listvolumes()} and
@ref{6c7,,os.listmounts()} functions on Windows for enumerating drives, volumes
and mount points

@item 
gh-74468@footnote{https://github.com/python/cpython/issues/74468}: Attribute name of the extracted @ref{e4,,tarfile} file object now
holds filename of itself rather than of the archive it is contained in.
Patch by Oleg Iarygin.

@item 
gh-102378@footnote{https://github.com/python/cpython/issues/102378}: Private helper method
@code{inspect._signature_strip_non_python_syntax} will no longer strip @code{/}
from the input string.

@item 
gh-79940@footnote{https://github.com/python/cpython/issues/79940}: Add @ref{6ba,,inspect.getasyncgenstate()} and
@ref{6bb,,inspect.getasyncgenlocals()}. Patch by Thomas Krennwallner.

@item 
gh-102103@footnote{https://github.com/python/cpython/issues/102103}: Add @code{module} argument to @ref{185c,,dataclasses.make_dataclass()}
and make classes produced by it pickleable.

@item 
gh-102069@footnote{https://github.com/python/cpython/issues/102069}: Fix @code{__weakref__} descriptor generation for custom
dataclasses.

@item 
gh-102038@footnote{https://github.com/python/cpython/issues/102038}: Skip a @code{stat} in @ref{cc,,site} if we have already found a
@code{pyvenv.cfg}

@item 
gh-98886@footnote{https://github.com/python/cpython/issues/98886}: Fix issues when defining dataclasses that have fields with
specific underscore names that aren't clearly reserved by
@ref{33,,dataclasses}.

@item 
gh-101673@footnote{https://github.com/python/cpython/issues/101673}: Fix a @ref{aa,,pdb} bug where @code{ll} clears the changes to local
variables.

@item 
gh-101313@footnote{https://github.com/python/cpython/issues/101313}: Added -h and --help arguments to the webbrowser CLI

@item 
gh-100372@footnote{https://github.com/python/cpython/issues/100372}: @ref{10ee,,ssl.SSLContext.load_verify_locations()} no longer
incorrectly accepts some cases of trailing data when parsing DER.

@item 
gh-89727@footnote{https://github.com/python/cpython/issues/89727}: Fix pathlib.Path.walk RecursionError on deep directory trees by
rewriting it using iteration instead of recursion.

@item 
gh-100131@footnote{https://github.com/python/cpython/issues/100131}: Added an optional @code{delete} keyword argument to
@ref{144c,,tempfile.TemporaryDirectory}.

@item 
gh-48330@footnote{https://github.com/python/cpython/issues/48330}: Added @code{--durations} command line option, showing the N slowest
test cases. @ref{1ab6,,unittest.TextTestRunner} and
@ref{754,,unittest.TextTestResult} constructors accept a new `durations'
keyword argument. Subclasses should take this into account or accept
@code{**kwargs}. Added @ref{1ab7,,unittest.TestResult.addDuration()} method and
@ref{1a7c,,unittest.TestResult.collectedDurations} attribute.

(Contributed by Giampaolo Rodola)

@item 
gh-98169@footnote{https://github.com/python/cpython/issues/98169}: Fix @ref{1a9e,,dataclasses.astuple()} crash when
@ref{13d4,,collections.defaultdict} is present in the attributes.

@item 
gh-96931@footnote{https://github.com/python/cpython/issues/96931}: Fix incorrect results from @ref{106c,,ssl.SSLSocket.shared_ciphers()}

@item 
gh-95495@footnote{https://github.com/python/cpython/issues/95495}: When built against OpenSSL 3.0, the @ref{d5,,ssl} module had a bug
where it reported unauthenticated EOFs (i.e. without close_notify) as a
clean TLS-level EOF. It now raises @ref{1ab8,,SSLEOFError}, matching the
behavior in previous versions of OpenSSL. The
@ref{a39,,options} attribute on @ref{357,,SSLContext} also
no longer includes @ref{a38,,OP_IGNORE_UNEXPECTED_EOF} by default. This
option may be set to specify the previous OpenSSL 3.0 behavior.

@item 
gh-94684@footnote{https://github.com/python/cpython/issues/94684}: Now @ref{2e5,,uuid.uuid3()} and @ref{2e6,,uuid.uuid5()} functions support
@ref{192,,bytes} objects as their `name' argument.

@item 
gh-94440@footnote{https://github.com/python/cpython/issues/94440}: Fix a @code{concurrent.futures.process} bug where
@code{ProcessPoolExecutor} shutdown could hang after a future has been
quickly submitted and canceled.

@item 
gh-72346@footnote{https://github.com/python/cpython/issues/72346}: Added deprecation warning to `isdst' parameter of
@ref{2f7,,email.utils.localtime()}.

@item 
bpo-36305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36305}: Fix handling of Windows filenames that resemble drives, such as
@code{./a:b}, in @ref{a8,,pathlib}.
@end itemize

@node ドキュメント<22>,テスト<21>,ライブラリ<69>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id302}@anchor{1ab9}
@subsubsection ドキュメント



@itemize -

@item 
gh-103112@footnote{https://github.com/python/cpython/issues/103112}: Add docstring to @ref{18af,,http.client.HTTPResponse.read()} to fix
@code{pydoc} output.
@end itemize

@node テスト<21>,ビルド<25>,ドキュメント<22>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id303}@anchor{1aba}
@subsubsection テスト



@itemize -

@item 
gh-102980@footnote{https://github.com/python/cpython/issues/102980}: Improve test coverage on @ref{aa,,pdb}.

@item 
gh-102537@footnote{https://github.com/python/cpython/issues/102537}: Adjust the error handling strategy in
@code{test_zoneinfo.TzPathTest.python_tzpath_context}. Patch by Paul Ganssle.

@item 
gh-101377@footnote{https://github.com/python/cpython/issues/101377}: Improved test_locale_calendar_formatweekday of calendar.
@end itemize

@node ビルド<25>,Windows<23>,テスト<21>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id304}@anchor{1abb}
@subsubsection ビルド



@itemize -

@item 
gh-102973@footnote{https://github.com/python/cpython/issues/102973}: Add a dev container (along with accompanying Dockerfile) for
development purposes.

@item 
gh-102711@footnote{https://github.com/python/cpython/issues/102711}: Fix @code{-Wstrict-prototypes} compiler warnings.
@end itemize

@node Windows<23>,Tools/Demos<21>,ビルド<25>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id305}@anchor{1abc}
@subsubsection Windows



@itemize -

@item 
gh-102690@footnote{https://github.com/python/cpython/issues/102690}: Update @ref{11b,,webbrowser} to fall back to Microsoft Edge instead
of Internet Explorer.

@item 
gh-99726@footnote{https://github.com/python/cpython/issues/99726}: Improves correctness of stat results for Windows, and uses
faster API when available
@end itemize

@node Tools/Demos<21>,C API<24>,Windows<23>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id306}@anchor{1abd}
@subsubsection Tools/Demos



@itemize -

@item 
gh-102809@footnote{https://github.com/python/cpython/issues/102809}: @code{Misc/gdbinit} was removed.
@end itemize

@node C API<24>,,Tools/Demos<21>,Python 3 12 0 alpha 7
@anchor{whatsnew/changelog id307}@anchor{1abe}
@subsubsection C API



@itemize -

@item 
gh-102013@footnote{https://github.com/python/cpython/issues/102013}: Add a new (unstable) C-API function for iterating over GC'able
objects using a callback: @code{PyUnstable_VisitObjects}.
@end itemize

@node Python 3 12 0 alpha 6,Python 3 12 0 alpha 5,Python 3 12 0 alpha 7,変更履歴
@anchor{whatsnew/changelog python-3-12-0-alpha-6}@anchor{1abf}
@subsection Python 3.12.0 alpha 6


`Release date: 2023-03-07'

@menu
* セキュリティ: セキュリティ<23>. 
* Core and Builtins: Core and Builtins<65>. 
* ライブラリ: ライブラリ<70>. 
* ドキュメント: ドキュメント<23>. 
* テスト: テスト<22>. 
* ビルド: ビルド<26>. 
* Windows: Windows<24>. 
* macOS: macOS<16>. 
* C API: C API<25>. 

@end menu

@node セキュリティ<23>,Core and Builtins<65>,,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id308}@anchor{1ac0}
@subsubsection セキュリティ



@itemize -

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Replace builtin hashlib implementations of MD5 and SHA1 with
verified ones from the HACL* project.

@item 
gh-101727@footnote{https://github.com/python/cpython/issues/101727}: Updated the OpenSSL version used in Windows and macOS binary
release builds to 1.1.1t to address 
@geindex Common Vulnerabilities and Exposures; CVE 2023-0286
CVE 2023-0286@footnote{https://www.cve.org/CVERecord?id=CVE-2023-0286}, 
@geindex Common Vulnerabilities and Exposures; CVE 2022-4303
CVE 2022-4303@footnote{https://www.cve.org/CVERecord?id=CVE-2022-4303},
and 
@geindex Common Vulnerabilities and Exposures; CVE 2022-4303
CVE 2022-4303@footnote{https://www.cve.org/CVERecord?id=CVE-2022-4303} per the OpenSSL 2023-02-07 security advisory@footnote{https://openssl-library.org/news/secadv/20230207.txt}.

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Replace the builtin @ref{6c,,hashlib} implementations of SHA2-384
and SHA2-512 originally from LibTomCrypt with formally verified,
side-channel resistant code from the HACL*@footnote{https://github.com/hacl-star/hacl-star/} project. The builtins remain a
fallback only used when OpenSSL does not provide them.

@item 
gh-101283@footnote{https://github.com/python/cpython/issues/101283}: @ref{4b7,,subprocess.Popen} now uses a safer approach to find
@code{cmd.exe} when launching with @code{shell=True}. Patch by Eryk Sun, based
on a patch by Oleg Iarygin.
@end itemize

@node Core and Builtins<65>,ライブラリ<70>,セキュリティ<23>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id309}@anchor{1ac1}
@subsubsection Core and Builtins



@itemize -

@item 
gh-102493@footnote{https://github.com/python/cpython/issues/102493}: Fix regression in semantics of normalisation in
@code{PyErr_SetObject}.

@item 
gh-102416@footnote{https://github.com/python/cpython/issues/102416}: Do not memoize incorrectly automatically generated loop rules
in the parser. Patch by Pablo Galindo.

@item 
gh-102356@footnote{https://github.com/python/cpython/issues/102356}: Fix a bug that caused a crash when deallocating deeply nested
filter objects. Patch by Marta Gómez Macías.

@item 
gh-102336@footnote{https://github.com/python/cpython/issues/102336}: Cleanup Windows 7 specific special handling. Patch by Max
Bachmann.

@item 
gh-102250@footnote{https://github.com/python/cpython/issues/102250}: Fixed a segfault occurring when the interpreter calls a
@code{__bool__} method that raises.

@item 
gh-102126@footnote{https://github.com/python/cpython/issues/102126}: Fix deadlock at shutdown when clearing thread states if any
finalizer tries to acquire the runtime head lock. Patch by Kumar Aditya.

@item 
gh-102027@footnote{https://github.com/python/cpython/issues/102027}: Use @code{GetCurrentProcessId} on Windows when @code{getpid} is
unavailable. Patch by Max Bachmann.

@item 
gh-102056@footnote{https://github.com/python/cpython/issues/102056}: Fix error handling bugs in interpreter's exception printing
code, which could cause a crash on infinite recursion.

@item 
gh-100982@footnote{https://github.com/python/cpython/issues/100982}: Restrict the scope of the @code{FOR_ITER_RANGE} instruction
to the scope of the original @ref{1ac2,,FOR_ITER} instruction, to allow
instrumentation.

@item 
gh-101967@footnote{https://github.com/python/cpython/issues/101967}: Fix possible segfault in @code{positional_only_passed_as_keyword}
function, when new list created.

@item 
gh-101952@footnote{https://github.com/python/cpython/issues/101952}: Fix possible segfault in @code{BUILD_SET} opcode, when new set
created.

@item 
gh-74895@footnote{https://github.com/python/cpython/issues/74895}: @ref{1ac3,,socket.getaddrinfo} no longer raises
@ref{a81,,OverflowError} for @ref{19b,,int} `port' values outside of the C
long range. Out of range values are left up to the underlying string based
C library API to report. A @ref{1ac4,,socket.gaierror} @code{SAI_SERVICE} may
occur instead, or no error at all as not all platform C libraries generate
an error.

@item 
gh-101799@footnote{https://github.com/python/cpython/issues/101799}: Add @ref{708,,CALL_INTRINSIC_2} and use it instead of
@code{PREP_RERAISE_STAR}.

@item 
gh-101857@footnote{https://github.com/python/cpython/issues/101857}: Fix xattr support detection on Linux systems by widening the
check to linux, not just glibc. This fixes support for musl.

@item 
gh-84783@footnote{https://github.com/python/cpython/issues/84783}: Make the slice object hashable. Patch by Will Bradshaw and
Furkan Onder.

@item 
gh-87849@footnote{https://github.com/python/cpython/issues/87849}: Change the @code{SEND} instruction to leave the receiver on the
stack. This allows the specialized form of @code{SEND} to skip the chain of C
calls and jump directly to the @code{RESUME} in the generator or coroutine.

@item 
gh-101765@footnote{https://github.com/python/cpython/issues/101765}: Fix SystemError / segmentation fault in iter @code{__reduce__}
when internal access of @code{builtins.__dict__} keys mutates the iter
object.

@item 
gh-101430@footnote{https://github.com/python/cpython/issues/101430}: Update @ref{105,,tracemalloc} to handle presize of object properly.
Patch by Donghee Na.

@item 
gh-101696@footnote{https://github.com/python/cpython/issues/101696}: Invalidate type version tag in @code{_PyStaticType_Dealloc} for
static types, avoiding bug where a false cache hit could crash the
interpreter. Patch by Kumar Aditya.

@item 
gh-101632@footnote{https://github.com/python/cpython/issues/101632}: Adds a new @code{RETURN_CONST} instruction.

@item 
gh-100719@footnote{https://github.com/python/cpython/issues/100719}: Remove gi_code field from generator (and coroutine and async
generator) objects as it is redundant. The frame already includes a
reference to the code object.

@item 
gh-98627@footnote{https://github.com/python/cpython/issues/98627}: When an interpreter is configured to check (and only then),
importing an extension module will now fail when the extension does not
support multiple interpreters (i.e. doesn't implement PEP 489 multi-phase
init). This does not apply to the main interpreter, nor to subinterpreters
created with @code{Py_NewInterpreter()}.
@end itemize

@node ライブラリ<70>,ドキュメント<23>,Core and Builtins<65>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id310}@anchor{1ac5}
@subsubsection ライブラリ



@itemize -

@item 
gh-102302@footnote{https://github.com/python/cpython/issues/102302}: Micro-optimise hashing of @ref{4e4,,inspect.Parameter}, reducing
the time it takes to hash an instance by around 40%.

@item 
gh-101979@footnote{https://github.com/python/cpython/issues/101979}: Fix a bug where parentheses in the @code{metavar} argument to
@ref{4bc,,argparse.ArgumentParser.add_argument()} were dropped. Patch by Yeojin
Kim.

@item 
gh-91038@footnote{https://github.com/python/cpython/issues/91038}: @ref{1ac6,,platform.platform()} now has boolean default arguments.

@item 
gh-81652@footnote{https://github.com/python/cpython/issues/81652}: Add @ref{1ac7,,mmap.MAP_ALIGNED_SUPER} FreeBSD and
@ref{1ac8,,mmap.MAP_CONCEAL} OpenBSD constants to @ref{94,,mmap}. Patch by
Yeojin Kim.

@item 
gh-102179@footnote{https://github.com/python/cpython/issues/102179}: Fix @ref{d5a,,os.dup2()} error message for negative fds.

@item 
gh-101961@footnote{https://github.com/python/cpython/issues/101961}: For the binary mode, @code{fileinput.hookcompressed()} doesn't
set the @code{encoding} value even if the value is @code{None}. Patch by Gihwan
Kim.

@item 
gh-101936@footnote{https://github.com/python/cpython/issues/101936}: The default value of @code{fp} becomes @ref{10a4,,io.BytesIO} if
@ref{11e0,,HTTPError} is initialized without a designated @code{fp}
parameter. Patch by Long Vo.

@item 
gh-101566@footnote{https://github.com/python/cpython/issues/101566}: In zipfile, sync Path with zipp 3.14@footnote{https://zipp.readthedocs.io/en/latest/history.html#v3-14-0}, including
fix for extractall on the underlying zipfile after being wrapped in
@code{Path}.

@item 
gh-97930@footnote{https://github.com/python/cpython/issues/97930}: Apply changes from importlib_resources 5.12@footnote{https://importlib-resources.readthedocs.io/en/latest/history.html#v5-12-0},
including fix for @code{MultiplexedPath} to support directories in multiple
namespaces (python/importlib_resources#265).

@item 
gh-101997@footnote{https://github.com/python/cpython/issues/101997}: Upgrade pip wheel bundled with ensurepip (pip 23.0.1)

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: The built-in extension modules for @ref{6c,,hashlib} SHA2
algorithms, used when OpenSSL does not provide them, now live in a single
internal @code{_sha2} module instead of separate @code{_sha256} and @code{_sha512}
modules.

@item 
gh-101892@footnote{https://github.com/python/cpython/issues/101892}: Callable iterators no longer raise @ref{795,,SystemError} when
the callable object exhausts the iterator but forgets to either return a
sentinel value or raise @ref{df5,,StopIteration}.

@item 
gh-87634@footnote{https://github.com/python/cpython/issues/87634}: Remove locking behavior from @ref{763,,functools.cached_property()}.

@item 
gh-97786@footnote{https://github.com/python/cpython/issues/97786}: Fix potential undefined behaviour in corner cases of
floating-point-to-time conversions.

@item 
gh-101517@footnote{https://github.com/python/cpython/issues/101517}: Fixed bug where @ref{10,,bdb} looks up the source line with
@ref{89,,linecache} with a @code{lineno=None}, which causes it to fail with an
unhandled exception.

@item 
gh-101773@footnote{https://github.com/python/cpython/issues/101773}: Optimize @ref{213,,fractions.Fraction} for small components. The
private argument @code{_normalize} of the @ref{213,,fractions.Fraction}
constructor has been removed.

@item 
gh-101693@footnote{https://github.com/python/cpython/issues/101693}: In @ref{5b0,,sqlite3.Cursor.execute()}, @ref{1a3,,DeprecationWarning} is
now emitted when @ref{5b2,,named placeholders} are used
together with parameters supplied as a @ref{716,,sequence} instead of as a
@ref{183,,dict}. Starting from Python 3.14, using named placeholders with
parameters supplied as a sequence will raise a
@ref{305,,ProgrammingError}. Patch by Erlend E. Aasland.

@item 
gh-101446@footnote{https://github.com/python/cpython/issues/101446}: Change repr of @ref{7f3,,collections.OrderedDict} to use regular
dictionary formatting instead of pairs of keys and values.

@item 
gh-101362@footnote{https://github.com/python/cpython/issues/101362}: Speed up @ref{6cd,,pathlib.PurePath} construction by handling
arguments more uniformly. When a @ref{266,,pathlib.Path} argument is
supplied, we use its string representation rather than joining its parts
with @ref{19a9,,os.path.join()}.

@item 
gh-101362@footnote{https://github.com/python/cpython/issues/101362}: Speed up @ref{6cd,,pathlib.PurePath} construction by calling
@ref{19a9,,os.path.join()} only when two or more arguments are given.

@item 
gh-101362@footnote{https://github.com/python/cpython/issues/101362}: Speed up @ref{266,,pathlib.Path} construction by running the path
flavour compatibility check only when pathlib is imported.

@item 
gh-85984@footnote{https://github.com/python/cpython/issues/85984}: Refactored the implementation of @ref{1ac9,,pty.fork()} to use
@ref{1aca,,os.login_tty()}.

A @ref{1a3,,DeprecationWarning} is now raised by @code{pty.master_open()} and
@code{pty.slave_open()}. They were undocumented and deprecated long long ago
in the docstring in favor of @ref{301,,pty.openpty()}.

@item 
gh-101561@footnote{https://github.com/python/cpython/issues/101561}: Add a new decorator @ref{67d,,typing.override()}. See 
@geindex Python Enhancement Proposals; PEP 698
PEP 698@footnote{https://peps.python.org/pep-0698/} for
details. Patch by Steven Troxler.

@item 
gh-63301@footnote{https://github.com/python/cpython/issues/63301}: Set exit code when @ref{e3,,tabnanny} CLI exits on error.

@item 
gh-101360@footnote{https://github.com/python/cpython/issues/101360}: Fix anchor matching in @code{pathlib.PureWindowsPath.match()}.
Path and pattern anchors are now matched with @ref{60,,fnmatch}, just like
other path parts. This allows patterns such as @code{"*:/Users/*"} to be
matched.

@item 
gh-101277@footnote{https://github.com/python/cpython/issues/101277}: Remove global state from @ref{85,,itertools} module (
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/}).
Patches by Erlend E. Aasland.

@item 
gh-100809@footnote{https://github.com/python/cpython/issues/100809}: Fix handling of drive-relative paths (like 'C:' and 'C:foo') in
@ref{1a26,,pathlib.Path.absolute()}. This method now uses the OS API to retrieve
the correct current working directory for the drive.

@item 
gh-99138@footnote{https://github.com/python/cpython/issues/99138}: Apply 
@geindex Python Enhancement Proposals; PEP 687
PEP 687@footnote{https://peps.python.org/pep-0687/} to @ref{13a,,zoneinfo}. Patch by Erlend E. Aasland.

@item 
gh-96764@footnote{https://github.com/python/cpython/issues/96764}: @ref{815,,asyncio.wait_for()} now uses @ref{814,,asyncio.timeout()} as its
underlying implementation. Patch by Kumar Aditya.

@item 
gh-88233@footnote{https://github.com/python/cpython/issues/88233}: Correctly preserve "extra" fields in @code{zipfile} regardless of
their ordering relative to a zip64 "extra."

@item 
bpo-23224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23224}: Fix segfaults when creating @ref{1acb,,lzma.LZMADecompressor} and
@ref{1acc,,bz2.BZ2Decompressor} objects without calling @code{__init__()}, and
fix leakage of locks and internal buffers when calling the @code{__init__()}
methods of @ref{1acb,,lzma.LZMADecompressor}, @ref{1acd,,lzma.LZMACompressor},
@ref{1ace,,bz2.BZ2Compressor}, and @ref{1acc,,bz2.BZ2Decompressor} objects
multiple times.
@end itemize

@node ドキュメント<23>,テスト<22>,ライブラリ<70>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id311}@anchor{1acf}
@subsubsection ドキュメント



@itemize -

@item 
gh-85417@footnote{https://github.com/python/cpython/issues/85417}: Update @ref{19,,cmath} documentation to clarify behaviour on branch
cuts.

@item 
gh-97725@footnote{https://github.com/python/cpython/issues/97725}: Fix @ref{1ad0,,asyncio.Task.print_stack()} description for
@code{file=None}. Patch by Oleg Iarygin.
@end itemize

@node テスト<22>,ビルド<26>,ドキュメント<23>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id312}@anchor{1ad1}
@subsubsection テスト



@itemize -

@item 
gh-102019@footnote{https://github.com/python/cpython/issues/102019}: Fix deadlock on shutdown if @code{test_current_@{exception,frames@}}
fails. Patch by Jacob Bower.

@item 
gh-85984@footnote{https://github.com/python/cpython/issues/85984}: Utilize new "winsize" functions from termios in pty tests.

@item 
gh-89792@footnote{https://github.com/python/cpython/issues/89792}: @code{test_tools} now copies up to 10x less source data to a
temporary directory during the @code{freeze} test by ignoring git metadata
and other artifacts.  It also limits its python build parallelism based on
os.cpu_count instead of hard coding it as 8 cores.
@end itemize

@node ビルド<26>,Windows<24>,テスト<22>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id313}@anchor{1ad2}
@subsubsection ビルド



@itemize -

@item 
gh-99942@footnote{https://github.com/python/cpython/issues/99942}: On Android, in a static build, python-config in embed mode no
longer incorrectly reports a library to link to.

@item 
gh-99942@footnote{https://github.com/python/cpython/issues/99942}: On Android, python.pc now correctly reports the library to link
to, the same as python-config.sh.

@item 
gh-100221@footnote{https://github.com/python/cpython/issues/100221}: Fix creating install directories in @code{make sharedinstall} if
they exist outside @code{DESTDIR} already.

@item 
gh-96821@footnote{https://github.com/python/cpython/issues/96821}: Explicitly mark C extension modules that need defined signed
integer overflow, and add a configure option
@ref{1ad3,,--with-strict-overflow}. Patch by Matthias Görgens and Shantanu
Jain.
@end itemize

@node Windows<24>,macOS<16>,ビルド<26>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id314}@anchor{1ad4}
@subsubsection Windows



@itemize -

@item 
gh-102344@footnote{https://github.com/python/cpython/issues/102344}: Implement @code{winreg.QueryValue} using @code{QueryValueEx} and
@code{winreg.SetValue} using @code{SetValueEx}. Patch by Max Bachmann.

@item 
gh-101881@footnote{https://github.com/python/cpython/issues/101881}: Handle read and write operations on non-blocking pipes properly
on Windows.

@item 
gh-101881@footnote{https://github.com/python/cpython/issues/101881}: Add support for the os.get_blocking() and os.set_blocking()
functions on Windows.

@item 
gh-101849@footnote{https://github.com/python/cpython/issues/101849}: Ensures installer will correctly upgrade existing @code{py.exe}
launcher installs.

@item 
gh-101763@footnote{https://github.com/python/cpython/issues/101763}: Updates copy of libffi bundled with Windows installs to 3.4.4.

@item 
gh-101759@footnote{https://github.com/python/cpython/issues/101759}: Update Windows installer to SQLite 3.40.1.

@item 
gh-101614@footnote{https://github.com/python/cpython/issues/101614}: Correctly handle extensions built against debug binaries that
reference @code{python3_d.dll}.

@item 
gh-101196@footnote{https://github.com/python/cpython/issues/101196}: The functions @code{os.path.isdir}, @code{os.path.isfile},
@code{os.path.islink} and @code{os.path.exists} are now 13% to 28% faster on
Windows, by making fewer Win32 API calls.
@end itemize

@node macOS<16>,C API<25>,Windows<24>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id315}@anchor{1ad5}
@subsubsection macOS



@itemize -

@item 
gh-101759@footnote{https://github.com/python/cpython/issues/101759}: Update macOS installer to SQLite 3.40.1.
@end itemize

@node C API<25>,,macOS<16>,Python 3 12 0 alpha 6
@anchor{whatsnew/changelog id316}@anchor{1ad6}
@subsubsection C API



@itemize -

@item 
gh-101907@footnote{https://github.com/python/cpython/issues/101907}: Removes use of non-standard C++ extension in public header
files.

@item 
gh-99293@footnote{https://github.com/python/cpython/issues/99293}: Document that the Py_TPFLAGS_VALID_VERSION_TAG is an internal
feature, should not be used, and will be removed.

@item 
gh-101578@footnote{https://github.com/python/cpython/issues/101578}: Add @ref{429,,PyErr_GetRaisedException()} and
@ref{42c,,PyErr_SetRaisedException()} for saving and restoring the current
exception. These functions return and accept a single exception object,
rather than the triple arguments of the now-deprecated
@ref{428,,PyErr_Fetch()} and @ref{42b,,PyErr_Restore()}. This is less error
prone and a bit more efficient.

Add @ref{78b,,PyException_GetArgs()} and @ref{78c,,PyException_SetArgs()} as
convenience functions for retrieving and modifying the
@ref{78d,,args} passed to the exception's constructor.

@item 
gh-91744@footnote{https://github.com/python/cpython/issues/91744}: Introduced the `Unstable C API tier', marking APi that is
allowed to change in minor releases without a deprecation period. See
@geindex Python Enhancement Proposals; PEP 689
PEP 689@footnote{https://peps.python.org/pep-0689/} for details.
@end itemize

@node Python 3 12 0 alpha 5,Python 3 12 0 alpha 4,Python 3 12 0 alpha 6,変更履歴
@anchor{whatsnew/changelog python-3-12-0-alpha-5}@anchor{1ad7}
@subsection Python 3.12.0 alpha 5


`Release date: 2023-02-07'

@menu
* セキュリティ: セキュリティ<24>. 
* Core and Builtins: Core and Builtins<66>. 
* ライブラリ: ライブラリ<71>. 
* ドキュメント: ドキュメント<24>. 
* テスト: テスト<23>. 
* ビルド: ビルド<27>. 
* Windows: Windows<25>. 

@end menu

@node セキュリティ<24>,Core and Builtins<66>,,Python 3 12 0 alpha 5
@anchor{whatsnew/changelog id317}@anchor{1ad8}
@subsubsection セキュリティ



@itemize -

@item 
gh-99108@footnote{https://github.com/python/cpython/issues/99108}: Replace the builtin @ref{6c,,hashlib} implementations of SHA2-224
and SHA2-256 originally from LibTomCrypt with formally verified,
side-channel resistant code from the HACL*@footnote{https://github.com/hacl-star/hacl-star/} project. The builtins remain a
fallback only used when OpenSSL does not provide them.
@end itemize

@node Core and Builtins<66>,ライブラリ<71>,セキュリティ<24>,Python 3 12 0 alpha 5
@anchor{whatsnew/changelog id319}@anchor{1ad9}
@subsubsection Core and Builtins



@itemize -

@item 
gh-92173@footnote{https://github.com/python/cpython/issues/92173}: Fix the @code{defs} and @code{kwdefs} arguments to
@ref{1ada,,PyEval_EvalCodeEx()} and a reference leak in that function.

@item 
gh-59956@footnote{https://github.com/python/cpython/issues/59956}: The GILState API is now partially compatible with
subinterpreters. Previously, @code{PyThreadState_GET()} and
@code{PyGILState_GetThisThreadState()} would get out of sync, causing
inconsistent behavior and crashes.

@item 
gh-101400@footnote{https://github.com/python/cpython/issues/101400}: Fix wrong lineno in exception message on @ref{180,,continue} or
@ref{17f,,break} which are not in a loop. Patch by Donghee Na.

@item 
gh-101372@footnote{https://github.com/python/cpython/issues/101372}: Fix @ref{c3c,,is_normalized()} to properly handle the
UCD 3.2.0 cases. Patch by Donghee Na.

@item 
gh-101266@footnote{https://github.com/python/cpython/issues/101266}: Fix @ref{1adb,,sys.getsizeof()} reporting for @ref{19b,,int}
subclasses.

@item 
gh-101291@footnote{https://github.com/python/cpython/issues/101291}: Refactor the @code{PyLongObject} struct into a normal Python
object header and a @code{PyLongValue} struct.

@item 
gh-101046@footnote{https://github.com/python/cpython/issues/101046}: Fix a possible memory leak in the parser when raising
@ref{179e,,MemoryError}. Patch by Pablo Galindo

@item 
gh-101037@footnote{https://github.com/python/cpython/issues/101037}: Fix potential memory underallocation issue for instances of
@ref{19b,,int} subclasses with value zero.

@item 
gh-100762@footnote{https://github.com/python/cpython/issues/100762}: Record the (virtual) exception block depth in the oparg of
@ref{5ba,,YIELD_VALUE}. Use this to avoid the expensive @code{throw()} when
closing generators (and coroutines) that can be closed trivially.

@item 
gh-100982@footnote{https://github.com/python/cpython/issues/100982}: Adds a new @code{COMPARE_AND_BRANCH} instruction. This is a
bit more efficient when performing a comparison immediately followed by a
branch, and restores the design intent of PEP 659 that specializations are
local to a single instruction.

@item 
gh-100942@footnote{https://github.com/python/cpython/issues/100942}: Fixed segfault in property.getter/setter/deleter that occurred
when a property subclass overrode the @code{__new__} method to return a
non-property instance.

@item 
gh-100923@footnote{https://github.com/python/cpython/issues/100923}: Remove the @code{mask} cache entry for the @ref{b61,,COMPARE_OP}
instruction and embed the mask into the oparg.

@item 
gh-100892@footnote{https://github.com/python/cpython/issues/100892}: Fix race while iterating over thread states in clearing
@ref{185f,,threading.local}. Patch by Kumar Aditya.

@item 
gh-91351@footnote{https://github.com/python/cpython/issues/91351}: Fix a case where re-entrant imports could corrupt the import
deadlock detection code and cause a @ref{5e7,,KeyError} to be raised out of
@code{importlib/_bootstrap}.  In addition to the straightforward cases,
this could also happen when garbage collection leads to a warning being
emitted -- as happens when it collects an open socket or file)

@item 
gh-100726@footnote{https://github.com/python/cpython/issues/100726}: Optimize construction of @code{range} object for medium size
integers.

@item 
gh-100712@footnote{https://github.com/python/cpython/issues/100712}: Added option to build cpython with specialization disabled, by
setting @code{ENABLE_SPECIALIZATION=False} in @code{opcode}, followed by
@code{make regen-all}.
@end itemize

@node ライブラリ<71>,ドキュメント<24>,Core and Builtins<66>,Python 3 12 0 alpha 5
@anchor{whatsnew/changelog id320}@anchor{1adc}
@subsubsection ライブラリ



@itemize -

@item 
bpo-32780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32780}: Inter-field padding is now inserted into the PEP3118 format
strings obtained from @ref{1e5,,ctypes.Structure} objects, reflecting their
true representation in memory.

@item 
gh-101541@footnote{https://github.com/python/cpython/issues/101541}: [Enum] - fix psuedo-flag creation

@item 
gh-101570@footnote{https://github.com/python/cpython/issues/101570}: Upgrade pip wheel bundled with ensurepip (pip 23.0)

@item 
gh-101323@footnote{https://github.com/python/cpython/issues/101323}: Fix a bug where errors where not thrown by
zlib._ZlibDecompressor if encountered during decompressing.

@item 
gh-101317@footnote{https://github.com/python/cpython/issues/101317}: Add `ssl_shutdown_timeout' parameter for
@ref{819,,asyncio.StreamWriter.start_tls()}.

@item 
gh-101326@footnote{https://github.com/python/cpython/issues/101326}: Fix regression when passing @code{None} as second or third
argument to @code{FutureIter.throw}.

@item 
gh-92123@footnote{https://github.com/python/cpython/issues/92123}: Adapt the @code{_elementtree} extension module to multi-phase init
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}). Patches by Erlend E. Aasland.

@item 
gh-100795@footnote{https://github.com/python/cpython/issues/100795}: Avoid potential unexpected @code{freeaddrinfo} call (double free)
in @ref{d1,,socket} when when a libc @code{getaddrinfo()} implementation leaves
garbage in an output pointer when returning an error. Original patch by
Sergey G. Brester.

@item 
gh-101143@footnote{https://github.com/python/cpython/issues/101143}: Remove unused references to @ref{1add,,TimerHandle} in
@code{asyncio.base_events.BaseEventLoop._add_callback}.

@item 
gh-101144@footnote{https://github.com/python/cpython/issues/101144}: Make @ref{1907,,zipfile.Path.open()} and
@ref{1ade,,zipfile.Path.read_text()} also accept @code{encoding} as a positional
argument. This was the behavior in Python 3.9 and earlier.  3.10
introduced a regression where supplying it as a positional argument would
lead to a @ref{198,,TypeError}.

@item 
gh-94518@footnote{https://github.com/python/cpython/issues/94518}: Group-related variables of @code{_posixsubprocess} module are
renamed to stress that supplementary group affinity is added to a fork,
not replace the inherited ones. Patch by Oleg Iarygin.

@item 
gh-101015@footnote{https://github.com/python/cpython/issues/101015}: Fix @ref{8c0,,typing.get_type_hints()} on @code{'*tuple[...]'} and
@code{*tuple[...]}. It must not drop the @code{Unpack} part.

@item 
gh-101000@footnote{https://github.com/python/cpython/issues/101000}: Add @ref{6cb,,os.path.splitroot()}, which splits a path into a
3-item tuple @code{(drive, root, tail)}. This new function is used by
@ref{a8,,pathlib} to improve the performance of path construction by up to a
third.

@item 
gh-100573@footnote{https://github.com/python/cpython/issues/100573}: Fix a Windows @ref{b,,asyncio} bug with named pipes where a
client doing @code{os.stat()} on the pipe would cause an error in the server
that disabled serving future requests.

@item 
gh-39615@footnote{https://github.com/python/cpython/issues/39615}: @ref{1732,,warnings.warn()} now has the ability to skip stack frames
based on code filename prefix rather than only a numeric @code{stacklevel}
via the new @code{skip_file_prefixes} keyword argument.

@item 
gh-100750@footnote{https://github.com/python/cpython/issues/100750}: pass encoding kwarg to subprocess in platform

@item 
gh-100160@footnote{https://github.com/python/cpython/issues/100160}: Emit a deprecation warning in
@code{asyncio.DefaultEventLoopPolicy.get_event_loop()} if there is no
current event loop set and it decides to create one.

@item 
gh-96290@footnote{https://github.com/python/cpython/issues/96290}: Fix handling of partial and invalid UNC drives in
@code{ntpath.splitdrive()}, and in @code{ntpath.normpath()} on non-Windows
systems. Paths such as '\server' and '\' are now considered by
@code{splitdrive()} to contain only a drive, and consequently are not
modified by @code{normpath()} on non-Windows systems. The behaviour of
@code{normpath()} on Windows systems is unaffected, as native OS APIs are
used. Patch by Eryk Sun, with contributions by Barney Gale.

@item 
gh-99952@footnote{https://github.com/python/cpython/issues/99952}: Fix a reference undercounting issue in @ref{1e5,,ctypes.Structure}
with @code{from_param()} results larger than a C pointer.

@item 
gh-67790@footnote{https://github.com/python/cpython/issues/67790}: Add float-style formatting support for
@ref{213,,fractions.Fraction} instances.

@item 
gh-99266@footnote{https://github.com/python/cpython/issues/99266}: Preserve more detailed error messages in @ref{2e,,ctypes}.

@item 
gh-86682@footnote{https://github.com/python/cpython/issues/86682}: Ensure runtime-created collections have the correct module name
using the newly added (internal) @ref{1adf,,sys._getframemodulename()}.

@item 
gh-88597@footnote{https://github.com/python/cpython/issues/88597}: @ref{116,,uuid} now has a command line interface. Try @code{python -m
uuid -h}.

@item 
gh-60580@footnote{https://github.com/python/cpython/issues/60580}: @code{ctypes.wintypes.BYTE} definition changed from
@ref{1ae0,,c_byte} to @ref{1ae1,,c_ubyte} to match Windows SDK.
Patch by Anatoly Techtonik and Oleg Iarygin.

@item 
gh-94518@footnote{https://github.com/python/cpython/issues/94518}: @code{_posixsubprocess} now initializes all UID and GID variables
using a reserved @code{-1} value instead of a separate flag. Patch by Oleg
Iarygin.

@item 
bpo-38941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38941}: The @ref{12b,,xml.etree.ElementTree} module now emits
@ref{1a3,,DeprecationWarning} when testing the truth value of an
@ref{363,,xml.etree.ElementTree.Element}. Before, the Python implementation
emitted @ref{659,,FutureWarning}, and the C implementation emitted nothing.

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert @code{elementtree} types to heap types. Patch by Erlend
E. Aasland.

@item 
bpo-29847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29847}: Fix a bug where @ref{266,,pathlib.Path} accepted and ignored
keyword arguments. Patch provided by Yurii Karabas.

@item 
gh-77772@footnote{https://github.com/python/cpython/issues/77772}: @ref{bdc,,ctypes.CDLL}, @ref{1ae2,,ctypes.OleDLL},
@ref{1ae3,,ctypes.WinDLL}, and @ref{1ae4,,ctypes.PyDLL} now accept
@ref{5a1,,path-like objects} as their @code{name} argument.
Patch by Robert Hoelzl.
@end itemize

@node ドキュメント<24>,テスト<23>,ライブラリ<71>,Python 3 12 0 alpha 5
@anchor{whatsnew/changelog id321}@anchor{1ae5}
@subsubsection ドキュメント



@itemize -

@item 
gh-88324@footnote{https://github.com/python/cpython/issues/88324}: Reword @ref{dc,,subprocess} to emphasize default behavior of
`stdin', `stdout', and `stderr' arguments. Remove inaccurate statement
about child file handle inheritance.
@end itemize

@node テスト<23>,ビルド<27>,ドキュメント<24>,Python 3 12 0 alpha 5
@anchor{whatsnew/changelog id322}@anchor{1ae6}
@subsubsection テスト



@itemize -

@item 
gh-101334@footnote{https://github.com/python/cpython/issues/101334}: @code{test_tarfile} has been updated to pass when run as a high
UID.
@end itemize

@node ビルド<27>,Windows<25>,テスト<23>,Python 3 12 0 alpha 5
@anchor{whatsnew/changelog id323}@anchor{1ae7}
@subsubsection ビルド



@itemize -

@item 
gh-101282@footnote{https://github.com/python/cpython/issues/101282}: Update BOLT configuration not to use deprecated usage of
@code{--split functions}. Patch by Donghee Na.

@item 
gh-101522@footnote{https://github.com/python/cpython/issues/101522}: Allow overriding Windows dependencies versions and paths using
MSBuild properties.

@item 
gh-77532@footnote{https://github.com/python/cpython/issues/77532}: Minor fixes to allow building with @code{PlatformToolset=ClangCL}
on Windows.

@item 
gh-101152@footnote{https://github.com/python/cpython/issues/101152}: In accordance with 
@geindex Python Enhancement Proposals; PEP 699
PEP 699@footnote{https://peps.python.org/pep-0699/}, the @code{ma_version_tag} field in
@ref{64f,,PyDictObject} is deprecated for extension modules. Accessing this
field will generate a compiler warning at compile time. This field will be
removed in Python 3.14.

@item 
gh-100340@footnote{https://github.com/python/cpython/issues/100340}: Allows -Wno-int-conversion for wasm-sdk 17 and onwards, thus
enables building WASI builds once against the latest sdk.

@item 
gh-101060@footnote{https://github.com/python/cpython/issues/101060}: Conditionally add @code{-fno-reorder-blocks-and-partition} in
configure. Effectively fixes @code{--enable-bolt} when using Clang, as this
appears to be a GCC-only flag.

@item 
gh-98705@footnote{https://github.com/python/cpython/issues/98705}: @code{__bool__} is defined in AIX system header files which breaks
the build in AIX, so undefine it.

@item 
gh-98636@footnote{https://github.com/python/cpython/issues/98636}: Fix a regression in detecting @code{gdbm_compat} library for the
@code{_gdbm} module build.

@item 
gh-96305@footnote{https://github.com/python/cpython/issues/96305}: @code{_aix_support} now uses a simple code to get platform details
rather than the now non-existent @code{_bootsubprocess} during bootstrap.
@end itemize

@node Windows<25>,,ビルド<27>,Python 3 12 0 alpha 5
@anchor{whatsnew/changelog id324}@anchor{1ae8}
@subsubsection Windows



@itemize -

@item 
gh-101543@footnote{https://github.com/python/cpython/issues/101543}: Ensure the install path in the registry is only used when the
standard library hasn't been located in any other way.

@item 
gh-101467@footnote{https://github.com/python/cpython/issues/101467}: The @code{py.exe} launcher now correctly filters when only a
single runtime is installed. It also correctly handles prefix matches on
tags so that @code{-3.1} does not match @code{3.11}, but would still match
@code{3.1-32}.

@item 
gh-99834@footnote{https://github.com/python/cpython/issues/99834}: Updates bundled copy of Tcl/Tk to 8.6.13.0

@item 
gh-101135@footnote{https://github.com/python/cpython/issues/101135}: Restore ability to launch older 32-bit versions from the
@code{py.exe} launcher when both 32-bit and 64-bit installs of the same
version are available.

@item 
gh-82052@footnote{https://github.com/python/cpython/issues/82052}: Fixed an issue where writing more than 32K of Unicode output to
the console screen in one go can result in mojibake.

@item 
gh-100320@footnote{https://github.com/python/cpython/issues/100320}: Ensures the @code{PythonPath} registry key from an install is used
when launching from a different copy of Python that relies on an existing
install to provide a copy of its modules and standard library.

@item 
gh-100247@footnote{https://github.com/python/cpython/issues/100247}: Restores support for the @code{py.exe} launcher finding
shebang commands in its configuration file using the full command name.
@end itemize

@node Python 3 12 0 alpha 4,Python 3 12 0 alpha 3,Python 3 12 0 alpha 5,変更履歴
@anchor{whatsnew/changelog python-3-12-0-alpha-4}@anchor{1ae9}
@subsection Python 3.12.0 alpha 4


`Release date: 2023-01-10'

@menu
* Core and Builtins: Core and Builtins<67>. 
* ライブラリ: ライブラリ<72>. 
* Core and Builtins: Core and Builtins<68>. 
* ライブラリ: ライブラリ<73>. 
* Core and Builtins: Core and Builtins<69>. 
* ライブラリ: ライブラリ<74>. 
* ドキュメント: ドキュメント<25>. 
* テスト: テスト<24>. 
* ビルド: ビルド<28>. 
* Windows: Windows<26>. 
* macOS: macOS<17>. 
* Tools/Demos: Tools/Demos<22>. 
* C API: C API<26>. 

@end menu

@node Core and Builtins<67>,ライブラリ<72>,,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id325}@anchor{1aea}
@subsubsection Core and Builtins



@itemize -

@item 
gh-100776@footnote{https://github.com/python/cpython/issues/100776}: Fix misleading default value in @ref{14f0,,input()}'s
@code{__text_signature__}.

@item 
gh-99005@footnote{https://github.com/python/cpython/issues/99005}: Remove @code{UNARY_POSITIVE}, @code{ASYNC_GEN_WRAP} and
@code{LIST_TO_TUPLE}, replacing them with intrinsics.

@item 
gh-99005@footnote{https://github.com/python/cpython/issues/99005}: Add new @ref{707,,CALL_INTRINSIC_1} instruction. Remove
@code{IMPORT_STAR}, @code{PRINT_EXPR} and
@code{STOPITERATION_ERROR}, replacing them with the
@ref{707,,CALL_INTRINSIC_1} instruction.

@item 
gh-100288@footnote{https://github.com/python/cpython/issues/100288}: Remove the LOAD_ATTR_METHOD_WITH_DICT specialized instruction.
Stats show it is not useful.

@item 
gh-100720@footnote{https://github.com/python/cpython/issues/100720}: Added @code{_PyFrame_NumSlotsForCodeObject}, which returns the
number of slots needed in a frame for a given code object.

@item 
gh-100719@footnote{https://github.com/python/cpython/issues/100719}: Removed the co_nplaincellvars field from the code object, as it
is redundant.

@item 
gh-100637@footnote{https://github.com/python/cpython/issues/100637}: Fix @code{int.__sizeof__()} calculation to include the 1-element
@code{ob_digit} array for @code{0} and @code{False}.

@item 
gh-100649@footnote{https://github.com/python/cpython/issues/100649}: Update the native_thread_id field of PyThreadState after fork.

@item 
gh-100126@footnote{https://github.com/python/cpython/issues/100126}: Fix an issue where "incomplete" frames could be briefly visible
to C code while other frames are being torn down, possibly resulting in
corruption or hard crashes of the interpreter while running finalizers.

@item 
gh-87447@footnote{https://github.com/python/cpython/issues/87447}: Fix @ref{18e,,SyntaxError} on comprehension rebind checking with
names that are not actually redefined.

Now reassigning @code{b} in @code{[(b := 1) for a, b.prop in some_iter]} is
allowed. Reassigning @code{a} is still disallowed as per 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/}.

@item 
gh-100268@footnote{https://github.com/python/cpython/issues/100268}: Add @ref{1aeb,,int.is_integer()} to improve duck type compatibility
between @ref{19b,,int} and @ref{196,,float}.

@item 
gh-100425@footnote{https://github.com/python/cpython/issues/100425}: Improve the accuracy of @code{sum()} with compensated summation.
@end itemize

@node ライブラリ<72>,Core and Builtins<68>,Core and Builtins<67>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id326}@anchor{1aec}
@subsubsection ライブラリ



@itemize -

@item 
gh-100374@footnote{https://github.com/python/cpython/issues/100374}: Fix incorrect result and delay in @ref{1aed,,socket.getfqdn()}. Patch
by Dominic Socular.
@end itemize

@node Core and Builtins<68>,ライブラリ<73>,ライブラリ<72>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id327}@anchor{1aee}
@subsubsection Core and Builtins



@itemize -

@item 
gh-100357@footnote{https://github.com/python/cpython/issues/100357}: Convert @code{vars}, @code{dir}, @code{next}, @code{getattr}, and @code{iter}
to argument clinic.

@item 
gh-100117@footnote{https://github.com/python/cpython/issues/100117}: Improve the output of @ref{350,,codeobject.co_lines()} by emitting
only one entry for each line range.

@item 
gh-90043@footnote{https://github.com/python/cpython/issues/90043}: Handle NaNs when specializing @ref{b61,,COMPARE_OP} for
@ref{196,,float} values.

@item 
gh-100222@footnote{https://github.com/python/cpython/issues/100222}: Redefine the @code{_Py_CODEUNIT} typedef as a union to describe
its layout to the C compiler, avoiding type punning and improving clarity.

@item 
gh-99955@footnote{https://github.com/python/cpython/issues/99955}: Internal compiler functions (in compile.c) now consistently
return -1 on error and 0 on success.

@item 
gh-100188@footnote{https://github.com/python/cpython/issues/100188}: The @code{BINARY_SUBSCR_LIST_INT} and @code{BINARY_SUBSCR_TUPLE_INT}
instructions are no longer used for negative integers because those
instructions always miss when encountering negative integers.

@item 
gh-99110@footnote{https://github.com/python/cpython/issues/99110}: Initialize frame->previous in frameobject.c to fix a
segmentation fault when accessing frames created by @ref{1aef,,PyFrame_New()}.

@item 
gh-94155@footnote{https://github.com/python/cpython/issues/94155}: Improved the hashing algorithm for code objects, mitigating some
hash collisions.

@item 
gh-99540@footnote{https://github.com/python/cpython/issues/99540}: @code{None} now hashes to a constant value. This is not a
requirements change.

@item 
gh-100143@footnote{https://github.com/python/cpython/issues/100143}: When built with @code{--enable-pystats}, stats collection is now
off by default. To enable it early at startup, pass the @code{-Xpystats}
flag.  Stats are now always dumped, even if switched off.

@item 
gh-100146@footnote{https://github.com/python/cpython/issues/100146}: Improve @code{BUILD_LIST} opcode so that it works similarly to the
@code{BUILD_TUPLE} opcode, by stealing references from the stack rather than
repeatedly using stack operations to set list elements.  Implementation
details are in a new private API @code{_PyList_FromArraySteal()}.

@item 
gh-100110@footnote{https://github.com/python/cpython/issues/100110}: Specialize @code{FOR_ITER} for tuples.

@item 
gh-100050@footnote{https://github.com/python/cpython/issues/100050}: Honor existing errors obtained when searching for mismatching
parentheses in the tokenizer. Patch by Pablo Galindo

@item 
gh-92216@footnote{https://github.com/python/cpython/issues/92216}: Improve the performance of @ref{6f9,,hasattr()} for type objects with
a missing attribute.

@item 
gh-99582@footnote{https://github.com/python/cpython/issues/99582}: Freeze @ref{138,,zipimport} module into @code{_bootstrap_python}.

@item 
gh-99554@footnote{https://github.com/python/cpython/issues/99554}: Pack debugging location tables more efficiently during bytecode
compilation.

@item 
gh-98522@footnote{https://github.com/python/cpython/issues/98522}: Add an internal version number to code objects, to give better
versioning of inner functions and comprehensions, and thus better
specialization of those functions. This change is invisible to both Python
and C extensions.

@item 
gh-94603@footnote{https://github.com/python/cpython/issues/94603}: Improve performance of @code{list.pop} for small lists.
@end itemize

@node ライブラリ<73>,Core and Builtins<69>,Core and Builtins<68>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id328}@anchor{1af0}
@subsubsection ライブラリ



@itemize -

@item 
gh-89051@footnote{https://github.com/python/cpython/issues/89051}: Add @ref{1af1,,ssl.OP_LEGACY_SERVER_CONNECT}
@end itemize

@node Core and Builtins<69>,ライブラリ<74>,ライブラリ<73>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id329}@anchor{1af2}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32782}: @code{ctypes} arrays of length 0 now report a correct itemsize
when a @code{memoryview} is constructed from them, rather than always giving
a value of 0.
@end itemize

@node ライブラリ<74>,ドキュメント<25>,Core and Builtins<69>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id330}@anchor{1af3}
@subsubsection ライブラリ



@itemize -

@item 
gh-100833@footnote{https://github.com/python/cpython/issues/100833}: Speed up @ref{15ed,,math.fsum()} by removing defensive @code{volatile}
qualifiers.

@item 
gh-100805@footnote{https://github.com/python/cpython/issues/100805}: Modify @ref{1448,,random.choice()} implementation to once again work
with NumPy arrays.

@item 
gh-100813@footnote{https://github.com/python/cpython/issues/100813}: Add @code{socket.IP_PKTINFO} constant.

@item 
gh-100792@footnote{https://github.com/python/cpython/issues/100792}: Make @ref{1af4,,email.message.Message.__contains__()} twice as fast.

@item 
gh-91851@footnote{https://github.com/python/cpython/issues/91851}: Microoptimizations for @ref{1af5,,fractions.Fraction.__round__()},
@ref{1af6,,fractions.Fraction.__ceil__()} and
@ref{1af7,,fractions.Fraction.__floor__()}.

@item 
gh-90104@footnote{https://github.com/python/cpython/issues/90104}: Avoid RecursionError on @code{repr} if a dataclass field definition
has a cyclic reference.

@item 
gh-100689@footnote{https://github.com/python/cpython/issues/100689}: Fix crash in @code{pyexpat} by statically allocating
@code{PyExpat_CAPI} capsule.

@item 
gh-100740@footnote{https://github.com/python/cpython/issues/100740}: Fix @code{unittest.mock.Mock} not respecting the spec for
attribute names prefixed with @code{assert}.

@item 
gh-91219@footnote{https://github.com/python/cpython/issues/91219}: Change @code{SimpleHTTPRequestHandler} to support subclassing to
provide a different set of index file names instead of using @code{__init__}
parameters.

@item 
gh-100690@footnote{https://github.com/python/cpython/issues/100690}: @code{Mock} objects which are not unsafe will now raise an
@code{AttributeError} when accessing an attribute that matches the name of an
assertion but without the prefix @code{assert_}, e.g. accessing
@code{called_once} instead of @code{assert_called_once}. This is in addition to
this already happening for accessing attributes with prefixes @code{assert},
@code{assret}, @code{asert}, @code{aseert}, and @code{assrt}.

@item 
gh-89727@footnote{https://github.com/python/cpython/issues/89727}: Simplify and optimize @ref{6d0,,os.walk()} by using
@ref{2ad,,isinstance()} checks to check the top of the stack.

@item 
gh-100485@footnote{https://github.com/python/cpython/issues/100485}: Add math.sumprod() to compute the sum of products.

@item 
gh-86508@footnote{https://github.com/python/cpython/issues/86508}: Fix @ref{d0e,,asyncio.open_connection()} to skip binding to local
addresses of different family. Patch by Kumar Aditya.

@item 
gh-97930@footnote{https://github.com/python/cpython/issues/97930}: @code{importlib.resources.files} now accepts a module as an anchor
instead of only accepting packages. If a module is passed, resources are
resolved adjacent to that module (in the same package or at the package
root). The parameter was renamed from @code{package} to @code{anchor} with a
compatibility shim for those passing by keyword. Additionally, the new
@code{anchor} parameter is now optional and will default to the caller's
module.

@item 
gh-100585@footnote{https://github.com/python/cpython/issues/100585}: Fixed a bug where importlib.resources.as_file was leaving file
pointers open

@item 
gh-100562@footnote{https://github.com/python/cpython/issues/100562}: Improve performance of @ref{1a26,,pathlib.Path.absolute()} by nearly
2x. This comes at the cost of a performance regression in
@ref{1a9b,,pathlib.Path.cwd()}, which is generally used less frequently in user
code.

@item 
gh-100519@footnote{https://github.com/python/cpython/issues/100519}: Small simplification of @code{http.cookiejar.eff_request_host()}
that improves readability and better matches the RFC wording.

@item 
gh-100287@footnote{https://github.com/python/cpython/issues/100287}: Fix the interaction of @ref{d9a,,unittest.mock.seal()} with
@ref{c3e,,unittest.mock.AsyncMock}.

@item 
gh-100488@footnote{https://github.com/python/cpython/issues/100488}: Add @code{Fraction.is_integer()} to check whether a
@ref{213,,fractions.Fraction} is an integer. This improves duck type
compatibility with @ref{196,,float} and @ref{19b,,int}.

@item 
gh-100474@footnote{https://github.com/python/cpython/issues/100474}: @ref{76,,http.server} now checks that an index page is actually a
regular file before trying to serve it.  This avoids issues with
directories named @code{index.html}.

@item 
gh-100363@footnote{https://github.com/python/cpython/issues/100363}: Speed up @ref{d01,,asyncio.get_running_loop()} by removing redundant
@code{getpid} checks. Patch by Kumar Aditya.

@item 
gh-78878@footnote{https://github.com/python/cpython/issues/78878}: Fix crash when creating an instance of @code{_ctypes.CField}.

@item 
gh-100348@footnote{https://github.com/python/cpython/issues/100348}: Fix ref cycle in @code{asyncio._SelectorSocketTransport} by
removing @code{_read_ready_cb} in @code{close}.

@item 
gh-100344@footnote{https://github.com/python/cpython/issues/100344}: Provide C implementation for @ref{6a5,,asyncio.current_task()} for a
4x-6x speedup.

@item 
gh-100272@footnote{https://github.com/python/cpython/issues/100272}: Fix JSON serialization of OrderedDict.  It now preserves the
order of keys.

@item 
gh-83076@footnote{https://github.com/python/cpython/issues/83076}: Instantiation of @code{Mock()} and @code{AsyncMock()} is now 3.8x
faster.

@item 
gh-100234@footnote{https://github.com/python/cpython/issues/100234}: Set a default value of 1.0 for the @code{lambd} parameter in
random.expovariate().

@item 
gh-100228@footnote{https://github.com/python/cpython/issues/100228}: A @ref{1a3,,DeprecationWarning} may be raised when @ref{4b5,,os.fork()}
or @ref{4b6,,os.forkpty()} is called from multi-threaded processes.  Forking
with threads is unsafe and can cause deadlocks, crashes and subtle
problems. Lack of a warning does not indicate that the fork call was
actually safe, as Python may not be aware of all threads.

@item 
gh-100039@footnote{https://github.com/python/cpython/issues/100039}: Improve signatures for enums and flags.

@item 
gh-100133@footnote{https://github.com/python/cpython/issues/100133}: Fix regression in @ref{b,,asyncio} where a subprocess would
sometimes lose data received from pipe.

@item 
bpo-44592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44592}: Fixes inconsistent handling of case sensitivity of
`extrasaction' arg in @ref{1417,,csv.DictWriter}.

@item 
gh-100098@footnote{https://github.com/python/cpython/issues/100098}: Fix @code{tuple} subclasses being cast to @code{tuple} when used as
enum values.

@item 
gh-85432@footnote{https://github.com/python/cpython/issues/85432}: Rename the `fmt' parameter of the pure-Python implementation of
@ref{1af8,,datetime.time.strftime()} to `format'. Rename the `t' parameter of
@ref{712,,datetime.datetime.fromtimestamp()} to `timestamp'. These changes mean
the parameter names in the pure-Python implementation now match the
parameter names in the C implementation. Patch by Alex Waygood.

@item 
gh-98778@footnote{https://github.com/python/cpython/issues/98778}: Update @ref{11e0,,HTTPError} to be initialized
properly, even if the @code{fp} is @code{None}. Patch by Donghee Na.

@item 
gh-99925@footnote{https://github.com/python/cpython/issues/99925}: Unify error messages in JSON serialization between
@code{json.dumps(float('nan'), allow_nan=False)} and
@code{json.dumps(float('nan'), allow_nan=False, indent=<SOMETHING>)}. Now
both include the representation of the value that could not be serialized.

@item 
gh-89727@footnote{https://github.com/python/cpython/issues/89727}: Fix issue with @ref{6d0,,os.walk()} where a @ref{f68,,RecursionError}
would occur on deep directory structures by adjusting the implementation
of @ref{6d0,,os.walk()} to be iterative instead of recursive.

@item 
gh-94943@footnote{https://github.com/python/cpython/issues/94943}: Add @ref{1af9,,データクラスのサポート} to the @ref{842,,Enum}
@ref{1afa,,__repr__()}. When inheriting from a
@ref{4e1,,dataclass}, only show the field names in the value
section of the member @ref{1c1,,repr()}, and not the dataclass' class name.

@item 
gh-83035@footnote{https://github.com/python/cpython/issues/83035}: Fix @ref{17c3,,inspect.getsource()} handling of decorator calls with
nested parentheses.

@item 
gh-99576@footnote{https://github.com/python/cpython/issues/99576}: Fix @code{.save()} method for @code{LWPCookieJar} and
@code{MozillaCookieJar}: saved file was not truncated on repeated save.

@item 
gh-94912@footnote{https://github.com/python/cpython/issues/94912}: Add @ref{6b8,,inspect.markcoroutinefunction()} decorator which
manually marks a function as a coroutine for the benefit of
@code{iscoroutinefunction()}.

@item 
gh-99509@footnote{https://github.com/python/cpython/issues/99509}: Add 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} support for
@code{multiprocessing.queues.Queue}.

@item 
gh-99482@footnote{https://github.com/python/cpython/issues/99482}: Remove @code{Jython} partial compatibility code from several stdlib
modules.

@item 
gh-99433@footnote{https://github.com/python/cpython/issues/99433}: Fix @ref{3e,,doctest} failure on @ref{85b,,types.MethodWrapperType}
in modules.

@item 
gh-85267@footnote{https://github.com/python/cpython/issues/85267}: Several improvements to @ref{22f,,inspect.signature()}'s handling of
@code{__text_signature}. - Fixes a case where @ref{22f,,inspect.signature()}
dropped parameters - Fixes a case where @ref{22f,,inspect.signature()} raised
@ref{764,,tokenize.TokenError} - Allows @ref{22f,,inspect.signature()} to
understand defaults involving binary operations of constants -
@ref{22f,,inspect.signature()} is documented as only raising @ref{198,,TypeError}
or @ref{2ec,,ValueError}, but sometimes raised @ref{244,,RuntimeError}. These
cases now raise @ref{2ec,,ValueError} - Removed a dead code path

@item 
gh-91166@footnote{https://github.com/python/cpython/issues/91166}: @ref{b,,asyncio} is optimized to avoid excessive copying when
writing to socket and use @ref{6a1,,sendmsg()} if the platform
supports it. Patch by Kumar Aditya.

@item 
gh-98030@footnote{https://github.com/python/cpython/issues/98030}: Add missing TCP socket options from Linux: @code{TCP_MD5SIG},
@code{TCP_THIN_LINEAR_TIMEOUTS}, @code{TCP_THIN_DUPACK}, @code{TCP_REPAIR},
@code{TCP_REPAIR_QUEUE}, @code{TCP_QUEUE_SEQ}, @code{TCP_REPAIR_OPTIONS},
@code{TCP_TIMESTAMP}, @code{TCP_CC_INFO}, @code{TCP_SAVE_SYN}, @code{TCP_SAVED_SYN},
@code{TCP_REPAIR_WINDOW}, @code{TCP_FASTOPEN_CONNECT}, @code{TCP_ULP},
@code{TCP_MD5SIG_EXT}, @code{TCP_FASTOPEN_KEY}, @code{TCP_FASTOPEN_NO_COOKIE},
@code{TCP_ZEROCOPY_RECEIVE}, @code{TCP_INQ}, @code{TCP_TX_DELAY}.

@item 
gh-88500@footnote{https://github.com/python/cpython/issues/88500}: Reduced the memory usage of @ref{1afb,,urllib.parse.unquote()} and
@ref{1afc,,urllib.parse.unquote_to_bytes()} on large values.

@item 
gh-96127@footnote{https://github.com/python/cpython/issues/96127}: @code{inspect.signature} was raising @code{TypeError} on call with
mock objects. Now it correctly returns @code{(*args, **kwargs)} as inferred
signature.

@item 
gh-95882@footnote{https://github.com/python/cpython/issues/95882}: Fix a 3.11 regression in
@ref{d1f,,asynccontextmanager()}, which caused it to propagate
exceptions with incorrect tracebacks and fix a 3.11 regression in
@ref{141b,,contextmanager()}, which caused it to propagate
exceptions with incorrect tracebacks for @ref{df5,,StopIteration}.

@item 
gh-78707@footnote{https://github.com/python/cpython/issues/78707}: Deprecate passing more than one positional argument to
@ref{2fd,,pathlib.PurePath.relative_to()} and
@ref{2fe,,is_relative_to()}.

@item 
gh-92122@footnote{https://github.com/python/cpython/issues/92122}: Fix reStructuredText syntax errors in docstrings in the
@ref{5a,,enum} module.

@item 
gh-91851@footnote{https://github.com/python/cpython/issues/91851}: Optimize the @ref{213,,Fraction} arithmetics for small
components.

@item 
bpo-24132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24132}: Make @ref{6cd,,pathlib.PurePath} and @ref{266,,Path}
subclassable (private to start). Previously, attempting to instantiate a
subclass resulted in an @ref{5f0,,AttributeError} being raised. Patch by
Barney Gale.

@item 
bpo-40447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40447}: Accept @ref{e4b,,os.PathLike} (such as @ref{266,,pathlib.Path}) in
the @code{stripdir} arguments of @ref{fe1,,compileall.compile_file()} and
@ref{d1b,,compileall.compile_dir()}.

@item 
bpo-36880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36880}: Fix a reference counting issue when a @ref{2e,,ctypes} callback
with return type @ref{1f3,,py_object} returns @code{None}, which could
cause crashes.
@end itemize

@node ドキュメント<25>,テスト<24>,ライブラリ<74>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id331}@anchor{1afd}
@subsubsection ドキュメント



@itemize -

@item 
gh-100616@footnote{https://github.com/python/cpython/issues/100616}: Document existing @code{attr} parameter to
@ref{1afe,,curses.window.vline()} function in @ref{2f,,curses}.

@item 
gh-100472@footnote{https://github.com/python/cpython/issues/100472}: Remove claim in documentation that the @code{stripdir},
@code{prependdir} and @code{limit_sl_dest} parameters of
@ref{d1b,,compileall.compile_dir()} and @ref{fe1,,compileall.compile_file()} could
be @ref{192,,bytes}.

@item 
bpo-25377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25377}: Clarify use of octal format of mode argument in help(os.chmod)
as well as help(os.fchmod)
@end itemize

@node テスト<24>,ビルド<28>,ドキュメント<25>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id332}@anchor{1aff}
@subsubsection テスト



@itemize -

@item 
gh-100454@footnote{https://github.com/python/cpython/issues/100454}: Start running SSL tests with OpenSSL 3.1.0-beta1.

@item 
gh-100086@footnote{https://github.com/python/cpython/issues/100086}: The Python test runner (libregrtest) now logs Python build
information like "debug" vs "release" build, or LTO and PGO optimizations.
Patch by Victor Stinner.

@item 
gh-93018@footnote{https://github.com/python/cpython/issues/93018}: Make two tests forgiving towards host system libexpat with
backported security fixes applied.
@end itemize

@node ビルド<28>,Windows<26>,テスト<24>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id333}@anchor{1b00}
@subsubsection ビルド



@itemize -

@item 
gh-100540@footnote{https://github.com/python/cpython/issues/100540}: Removed the @code{--with-system-ffi} @code{configure} option;
@code{libffi} must now always be supplied by the system on all non-Windows
platforms.  The option has had no effect on non-Darwin platforms for
several releases, and in 3.11 only had the non-obvious effect of invoking
@code{pkg-config} to find @code{libffi} and never setting
@code{-DUSING_APPLE_OS_LIBFFI}.  Now on Darwin platforms @code{configure} will
first check for the OS @code{libffi} and then fall back to the same
processing as other platforms if it is not found.

@item 
gh-88267@footnote{https://github.com/python/cpython/issues/88267}: Avoid exporting Python symbols in linked Windows applications
when the core is built as static.

@item 
bpo-41916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41916}: Allow override of ac_cv_cxx_thread so that cross compiled
python can set -pthread for CXX.
@end itemize

@node Windows<26>,macOS<17>,ビルド<28>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id334}@anchor{1b01}
@subsubsection Windows



@itemize -

@item 
gh-100180@footnote{https://github.com/python/cpython/issues/100180}: Update Windows installer to OpenSSL 1.1.1s

@item 
gh-99191@footnote{https://github.com/python/cpython/issues/99191}: Use @code{_MSVC_LANG >= 202002L} instead of less-precise @code{_MSC_VER
>=1929} to more accurately test for C++20 support in
@code{PC/_wmimodule.cpp}.

@item 
gh-79218@footnote{https://github.com/python/cpython/issues/79218}: Define @code{MS_WIN64} for Mingw-w64 64bit, fix cython compilation
failure.

@item 
gh-99941@footnote{https://github.com/python/cpython/issues/99941}: Ensure that @ref{1b02,,asyncio.Protocol.data_received()} receives an
immutable @ref{192,,bytes} object (as documented), instead of
@ref{344,,bytearray}.

@item 
bpo-43984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43984}: @ref{1b03,,winreg.SetValueEx()} now leaves the target value untouched
in the case of conversion errors. Previously, @code{-1} would be written in
case of such errors.

@item 
bpo-34816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34816}: @code{hasattr(ctypes.windll, 'nonexistant')} now returns @code{False}
instead of raising @ref{2c0,,OSError}.
@end itemize

@node macOS<17>,Tools/Demos<22>,Windows<26>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id335}@anchor{1b04}
@subsubsection macOS



@itemize -

@item 
gh-100180@footnote{https://github.com/python/cpython/issues/100180}: Update macOS installer to OpenSSL 1.1.1s

@item 
gh-100540@footnote{https://github.com/python/cpython/issues/100540}: Removed obsolete @code{dlfcn.h} shim from the @code{_ctypes}
extension module, which has not been necessary since Mac OS X 10.2.
@end itemize

@node Tools/Demos<22>,C API<26>,macOS<17>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id336}@anchor{1b05}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-45256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45256}: Fix a bug that caused an @ref{5f0,,AttributeError} to be raised in
@code{python-gdb.py} when @code{py-locals} is used without a frame.

@item 
gh-100342@footnote{https://github.com/python/cpython/issues/100342}: Add missing @code{NULL} check for possible allocation failure in
@code{*args} parsing in Argument Clinic.
@end itemize

@node C API<26>,,Tools/Demos<22>,Python 3 12 0 alpha 4
@anchor{whatsnew/changelog id337}@anchor{1b06}
@subsubsection C API



@itemize -

@item 
gh-99947@footnote{https://github.com/python/cpython/issues/99947}: Raising SystemError on import will now have its cause be set to
the original unexpected exception.

@item 
gh-99240@footnote{https://github.com/python/cpython/issues/99240}: In argument parsing, after deallocating newly allocated memory,
reset its pointer to NULL.

@item 
gh-98724@footnote{https://github.com/python/cpython/issues/98724}: The @ref{798,,Py_CLEAR}, @ref{799,,Py_SETREF} and
@ref{79a,,Py_XSETREF} macros now only evaluate their arguments once. If an
argument has side effects, these side effects are no longer duplicated.
Patch by Victor Stinner.
@end itemize

@node Python 3 12 0 alpha 3,Python 3 12 0 alpha 2,Python 3 12 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-12-0-alpha-3}@anchor{1b07}
@subsection Python 3.12.0 alpha 3


`リリース日: 2022-12-06'

@menu
* セキュリティ: セキュリティ<25>. 
* Core and Builtins: Core and Builtins<70>. 
* ライブラリ: ライブラリ<75>. 
* Core and Builtins: Core and Builtins<71>. 
* ライブラリ: ライブラリ<76>. 
* ドキュメント: ドキュメント<26>. 
* テスト: テスト<25>. 
* ビルド: ビルド<29>. 
* Windows: Windows<27>. 
* macOS: macOS<18>. 
* Tools/Demos: Tools/Demos<23>. 
* C API: C API<27>. 

@end menu

@node セキュリティ<25>,Core and Builtins<70>,,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id338}@anchor{1b08}
@subsubsection セキュリティ



@itemize -

@item 
gh-100001@footnote{https://github.com/python/cpython/issues/100001}: @code{python -m http.server} no longer allows terminal control
characters sent within a garbage request to be printed to the stderr
server log.

This is done by changing the @ref{76,,http.server}
@code{BaseHTTPRequestHandler} @code{.log_message} method to replace control
characters with a @code{\x@var{HH}} hex escape before printing.

@item 
gh-87604@footnote{https://github.com/python/cpython/issues/87604}: Avoid publishing list of active per-interpreter audit hooks via
the @ref{64,,gc} module
@end itemize

@node Core and Builtins<70>,ライブラリ<75>,セキュリティ<25>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id339}@anchor{1b09}
@subsubsection Core and Builtins



@itemize -

@item 
gh-99891@footnote{https://github.com/python/cpython/issues/99891}: Fix a bug in the tokenizer that could cause infinite recursion
when showing syntax warnings that happen in the first line of the source.
Patch by Pablo Galindo

@item 
gh-91054@footnote{https://github.com/python/cpython/issues/91054}: Add @ref{787,,PyCode_AddWatcher()} and
@ref{788,,PyCode_ClearWatcher()} APIs to register callbacks to receive
notification on creation and destruction of code objects.

@item 
gh-99729@footnote{https://github.com/python/cpython/issues/99729}: Fix an issue that could cause frames to be visible to Python
code as they are being torn down, possibly leading to memory corruption or
hard crashes of the interpreter.

@item 
gh-99708@footnote{https://github.com/python/cpython/issues/99708}: Fix bug where compiler crashes on an if expression with an empty
body block.

@item 
gh-99578@footnote{https://github.com/python/cpython/issues/99578}: Fix a reference bug in @code{_imp.create_builtin()} after the
creation of the first sub-interpreter for modules @code{builtins} and
@code{sys}. Patch by Victor Stinner.

@item 
gh-99581@footnote{https://github.com/python/cpython/issues/99581}: Fixed a bug that was causing a buffer overflow if the tokenizer
copies a line missing the newline character from a file that is as long as
the available tokenizer buffer. Patch by Pablo galindo

@item 
gh-99553@footnote{https://github.com/python/cpython/issues/99553}: Fix bug where an @ref{4d2,,ExceptionGroup} subclass can wrap a
@ref{7d6,,BaseException}.
@end itemize

@node ライブラリ<75>,Core and Builtins<71>,Core and Builtins<70>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id340}@anchor{1b0a}
@subsubsection ライブラリ



@itemize -

@item 
gh-99547@footnote{https://github.com/python/cpython/issues/99547}: Add a function to os.path to check if a path is a junction:
isjunction. Add similar functionality to pathlib.Path as is_junction.

@item 
gh-99370@footnote{https://github.com/python/cpython/issues/99370}: Fix zip path for venv created from a non-installed python on
POSIX platforms.
@end itemize

@node Core and Builtins<71>,ライブラリ<76>,ライブラリ<75>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id341}@anchor{1b0b}
@subsubsection Core and Builtins



@itemize -

@item 
gh-99377@footnote{https://github.com/python/cpython/issues/99377}: Add audit events for thread creation and clear operations.

@item 
gh-98686@footnote{https://github.com/python/cpython/issues/98686}: Remove the @code{BINARY_OP_GENERIC} and @code{COMPARE_OP_GENERIC}
"specializations".

@item 
gh-99298@footnote{https://github.com/python/cpython/issues/99298}: Remove the remaining error paths for attribute specializations,
and refuse to specialize attribute accesses on types that haven't had
@ref{980,,PyType_Ready()} called on them yet.

@item 
gh-99127@footnote{https://github.com/python/cpython/issues/99127}: Allow some features of @ref{e2,,syslog} to the main interpreter
only. Patch by Donghee Na.

@item 
gh-91053@footnote{https://github.com/python/cpython/issues/91053}: Optimizing interpreters and JIT compilers may need to invalidate
internal metadata when functions are modified. This change adds the
ability to provide a callback that will be invoked each time a function is
created, modified, or destroyed.

@item 
gh-90994@footnote{https://github.com/python/cpython/issues/90994}: Improve error messages when there's a syntax error with call
arguments. The following three cases are covered: - No value is assigned
to a named argument, eg @code{foo(a=)}. - A value is assigned to a star
argument, eg @code{foo(*args=[0])}. - A value is assigned to a double-star
keyword argument, eg @code{foo(**kwarg=@{'a': 0@})}.

@item 
bpo-45026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45026}: Optimize the @ref{b3d,,range} object iterator. It is now smaller,
faster iteration of ranges containing large numbers. Smaller pickles,
faster unpickling.

@item 
bpo-31718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31718}: Raise @ref{2ec,,ValueError} instead of @ref{795,,SystemError} when
methods of uninitialized @ref{1a3e,,io.IncrementalNewlineDecoder} objects are
called. Patch by Oren Milman.

@item 
bpo-38031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38031}: Fix a possible assertion failure in @ref{1527,,io.FileIO} when the
opener returns an invalid file descriptor.
@end itemize

@node ライブラリ<76>,ドキュメント<26>,Core and Builtins<71>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id342}@anchor{1b0c}
@subsubsection ライブラリ



@itemize -

@item 
gh-100001@footnote{https://github.com/python/cpython/issues/100001}: Also escape s in the http.server
BaseHTTPRequestHandler.log_message so that it is technically possible to
parse the line and reconstruct what the original data was.  Without this a
xHH is ambiguous as to if it is a hex replacement we put in or the
characters r"x" came through in the original request line.

@item 
gh-99957@footnote{https://github.com/python/cpython/issues/99957}: Add @code{frozen_default} parameter to
@ref{6fb,,typing.dataclass_transform()}.

@item 
gh-79033@footnote{https://github.com/python/cpython/issues/79033}: Fix @ref{1a3f,,asyncio.Server.wait_closed()} to actually do what the
docs promise -- wait for all existing connections to complete, after
closing the server.

@item 
gh-51524@footnote{https://github.com/python/cpython/issues/51524}: Fix bug when calling trace.CoverageResults with valid infile.

@item 
gh-99645@footnote{https://github.com/python/cpython/issues/99645}: Fix a bug in handling class cleanups in
@ref{2b3,,unittest.TestCase}.  Now @code{addClassCleanup()} uses separate lists
for different @code{TestCase} subclasses, and @code{doClassCleanups()} only
cleans up the particular class.

@item 
gh-99508@footnote{https://github.com/python/cpython/issues/99508}: Fix @code{TypeError} in @code{Lib/importlib/_bootstrap_external.py}
while calling @code{_imp.source_hash()}.

@item 
gh-66285@footnote{https://github.com/python/cpython/issues/66285}: Fix @ref{b,,asyncio} to not share event loop and signal wakeupfd
in forked processes. Patch by Kumar Aditya.

@item 
gh-97001@footnote{https://github.com/python/cpython/issues/97001}: Release the GIL when calling termios APIs to avoid blocking
threads.

@item 
gh-92647@footnote{https://github.com/python/cpython/issues/92647}: Use final status of an enum to determine lookup or creation
branch of functional API.

@item 
gh-99388@footnote{https://github.com/python/cpython/issues/99388}: Add `loop_factory' parameter to @ref{2f3,,asyncio.run()} to allow
specifying a custom event loop factory. Patch by Kumar Aditya.

@item 
gh-99341@footnote{https://github.com/python/cpython/issues/99341}: Fix @ref{1b0d,,ast.increment_lineno()} to also cover
@ref{1b0e,,ast.TypeIgnore} when changing line numbers.

@item 
gh-99382@footnote{https://github.com/python/cpython/issues/99382}: Check the number of arguments in substitution in user generics
containing a @ref{488,,TypeVarTuple} and one or more
@ref{486,,TypeVar}.

@item 
gh-99379@footnote{https://github.com/python/cpython/issues/99379}: Fix substitution of @ref{487,,ParamSpec} followed by
@ref{488,,TypeVarTuple} in generic aliases.

@item 
gh-99344@footnote{https://github.com/python/cpython/issues/99344}: Fix substitution of @ref{488,,TypeVarTuple} and
@ref{487,,ParamSpec} together in user generics.

@item 
gh-99284@footnote{https://github.com/python/cpython/issues/99284}: Remove @code{_use_broken_old_ctypes_structure_semantics_} old
untested and undocumented hack from @ref{2e,,ctypes}.

@item 
gh-99201@footnote{https://github.com/python/cpython/issues/99201}: Fix @ref{174e,,IndexError} when initializing the config variables on
Windows if @code{HAVE_DYNAMIC_LOADING} is not set.

@item 
gh-99240@footnote{https://github.com/python/cpython/issues/99240}: Fix double-free bug in Argument Clinic @code{str_converter} by
extracting memory clean up to a new @code{post_parsing} section.

@item 
gh-64490@footnote{https://github.com/python/cpython/issues/64490}: Fix refcount error when arguments are packed to tuple in
Argument Clinic.

@item 
gh-99029@footnote{https://github.com/python/cpython/issues/99029}: @ref{2fd,,pathlib.PurePath.relative_to()} now treats naked Windows
drive paths as relative. This brings its behaviour in line with other
parts of pathlib.

@item 
gh-98253@footnote{https://github.com/python/cpython/issues/98253}: The implementation of the typing module is now more resilient to
reference leaks in binary extension modules.

Previously, a reference leak in a typed C API-based extension module could
leak internals of the typing module, which could in turn introduce leaks
in essentially any other package with typed function signatures. Although
the typing package is not the original source of the problem, such
non-local dependences exacerbate debugging of large-scale projects, and
the implementation was therefore changed to reduce harm by providing
better isolation.

@item 
gh-98458@footnote{https://github.com/python/cpython/issues/98458}: Fix infinite loop in unittest when a self-referencing chained
exception is raised

@item 
gh-93453@footnote{https://github.com/python/cpython/issues/93453}: @ref{2f2,,asyncio.get_event_loop()} and many other @ref{b,,asyncio}
functions like @ref{e71,,asyncio.ensure_future()}, @ref{c65,,asyncio.shield()} or
@ref{813,,asyncio.gather()}, and also the
@code{get_event_loop()} method of
@code{asyncio.BaseDefaultEventLoopPolicy} now raise a
@ref{244,,RuntimeError} if called when there is no running event loop and the
current event loop was not set. Previously they implicitly created and set
a new current event loop. @ref{1a3,,DeprecationWarning} is no longer emitted
if there is no running event loop but the current event loop was set.

@item 
gh-97966@footnote{https://github.com/python/cpython/issues/97966}: On @code{uname_result}, restored expectation that @code{_fields} and
@code{_asdict} would include all six properties including @code{processor}.

@item 
gh-98248@footnote{https://github.com/python/cpython/issues/98248}: Provide informative error messages in @ref{148e,,struct.pack()} when
its integral arguments are not in range.

@item 
gh-98108@footnote{https://github.com/python/cpython/issues/98108}: @code{zipfile.Path} is now pickleable if its initialization
parameters were pickleable (e.g. for file system paths).

@item 
gh-98098@footnote{https://github.com/python/cpython/issues/98098}: Created packages from zipfile and test_zipfile modules,
separating @code{zipfile.Path} functionality.

@item 
gh-82836@footnote{https://github.com/python/cpython/issues/82836}: Fix @ref{19c3,,is_private} properties in the
@ref{84,,ipaddress} module. Previously non-private networks (0.0.0.0/0) would
return @code{True} from this method; now they correctly return @code{False}.

@item 
gh-96828@footnote{https://github.com/python/cpython/issues/96828}: Add an @ref{1b0f,,OP_ENABLE_KTLS} option for enabling the use
of the kernel TLS (kTLS). Patch by Illia Volochii.

@item 
gh-88863@footnote{https://github.com/python/cpython/issues/88863}: To avoid apparent memory leaks when
@ref{d0e,,asyncio.open_connection()} raises, break reference cycles generated
by local exception and future instances (which has exception instance as
its member var). Patch by Dong Uk, Kang.

@item 
gh-91078@footnote{https://github.com/python/cpython/issues/91078}: @code{TarFile.next()} now returns @code{None} when called on an
empty tarfile.

@item 
bpo-47220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47220}: Document the optional `callback' parameter of
@code{WeakMethod}. Patch by Géry Ogam.

@item 
bpo-44817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44817}: Ignore WinError 53 (ERROR_BAD_NETPATH), 65
(ERROR_NETWORK_ACCESS_DENIED) and 161 (ERROR_BAD_PATHNAME) when using
ntpath.realpath().

@item 
bpo-41260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41260}: Rename the `fmt' parameter of the pure Python implementation of
@ref{e8f,,datetime.date.strftime()} to `format'.

@item 
bpo-15999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15999}: All built-in functions now accept arguments of any type instead
of just @code{bool} and @code{int} for boolean parameters.
@end itemize

@node ドキュメント<26>,テスト<25>,ライブラリ<76>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id343}@anchor{1b10}
@subsubsection ドキュメント



@itemize -

@item 
gh-99931@footnote{https://github.com/python/cpython/issues/99931}: Use sphinxext-opengraph@footnote{https://sphinxext-opengraph.readthedocs.io/} to generate OpenGraph metadata@footnote{https://ogp.me/}.

@item 
gh-89682@footnote{https://github.com/python/cpython/issues/89682}: Reworded docstring of the default @code{__contains__} to clarify
that it returns a @ref{3c3,,bool}.

@item 
gh-88330@footnote{https://github.com/python/cpython/issues/88330}: Improved the description of what a resource is in
importlib.resources docs.

@item 
gh-92892@footnote{https://github.com/python/cpython/issues/92892}: Document that calling variadic functions with ctypes requires
special care on macOS/arm64 (and possibly other platforms).

@item 
bpo-41825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41825}: Restructured the documentation for the @ref{f98,,os.wait*} family of functions, and improved the docs for
@ref{f99,,os.waitid()} with more explanation of the possible argument
constants.
@end itemize

@node テスト<25>,ビルド<29>,ドキュメント<26>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id344}@anchor{1b11}
@subsubsection テスト



@itemize -

@item 
gh-99892@footnote{https://github.com/python/cpython/issues/99892}: Skip test_normalization() of test_unicodedata if it fails to
download NormalizationTest.txt file from pythontest.net. Patch by Victor
Stinner.

@item 
gh-99934@footnote{https://github.com/python/cpython/issues/99934}: Correct test_marsh on (32 bit) x86: test_deterministic sets was
failing.

@item 
gh-99741@footnote{https://github.com/python/cpython/issues/99741}: We've implemented multi-phase init (PEP 489/630/687) for the
internal (for testing) _xxsubinterpreters module.

@item 
gh-99659@footnote{https://github.com/python/cpython/issues/99659}: Optional big memory tests in @code{test_sqlite3} now catch the
correct @code{sqlite.DataError} exception type in case of too large
strings and/or blobs passed.

@item 
gh-99593@footnote{https://github.com/python/cpython/issues/99593}: Cover the Unicode C API with tests.

@item 
gh-96002@footnote{https://github.com/python/cpython/issues/96002}: Add functional test for Argument Clinic.
@end itemize

@node ビルド<29>,Windows<27>,テスト<25>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id345}@anchor{1b12}
@subsubsection ビルド



@itemize -

@item 
gh-99086@footnote{https://github.com/python/cpython/issues/99086}: Fix @code{-Wimplicit-int}, @code{-Wstrict-prototypes}, and
@code{-Wimplicit-function-declaration} compiler warnings in
@code{configure} checks.

@item 
gh-99337@footnote{https://github.com/python/cpython/issues/99337}: Fix a compilation issue with GCC 12 on macOS.

@item 
gh-99289@footnote{https://github.com/python/cpython/issues/99289}: Add a @code{COMPILEALL_OPTS} variable in Makefile to override
@ref{21,,compileall} options (default: @code{-j0}) in @code{make install}. Also
merged the @code{compileall} commands into a single command building .pyc
files for the all optimization levels (0, 1, 2) at once. Patch by Victor
Stinner.

@item 
gh-98872@footnote{https://github.com/python/cpython/issues/98872}: Fix a possible fd leak in @code{Programs/_freeze_module.c}
introduced in Python 3.11.

@item 
gh-88226@footnote{https://github.com/python/cpython/issues/88226}: Always define @code{TARGET_*} labels in @code{Python/ceval.c}, even if
@code{USE_COMPUTED_GOTOS} is disabled.  This allows breakpoints to be set at
those labels in (for instance) @code{gdb}.
@end itemize

@node Windows<27>,macOS<18>,ビルド<29>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id346}@anchor{1b13}
@subsubsection Windows



@itemize -

@item 
gh-99345@footnote{https://github.com/python/cpython/issues/99345}: Use faster initialization functions to detect install location
for Windows Store package

@item 
gh-98629@footnote{https://github.com/python/cpython/issues/98629}: Fix initialization of @ref{49c,,sys.version} and @code{sys._git} on
Windows

@item 
gh-99442@footnote{https://github.com/python/cpython/issues/99442}: Fix handling in @ref{7da,,Python install manager} when @code{argv[0]} does not
include a file extension.

@item 
bpo-40882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40882}: Fix a memory leak in
@ref{19d8,,multiprocessing.shared_memory.SharedMemory} on Windows.
@end itemize

@node macOS<18>,Tools/Demos<23>,Windows<27>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id347}@anchor{1b14}
@subsubsection macOS



@itemize -

@item 
gh-87235@footnote{https://github.com/python/cpython/issues/87235}: On macOS @code{python3 /dev/fd/9 9</path/to/script.py} failed for
any script longer than a couple of bytes.

@item 
gh-98940@footnote{https://github.com/python/cpython/issues/98940}: Fix @code{Mac/Extras.install.py} file filter bug.
@end itemize

@node Tools/Demos<23>,C API<27>,macOS<18>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id348}@anchor{1b15}
@subsubsection Tools/Demos



@itemize -

@item 
gh-64490@footnote{https://github.com/python/cpython/issues/64490}: Argument Clinic varargs bugfixes


@itemize *

@item 
Fix out-of-bounds error in @code{_PyArg_UnpackKeywordsWithVararg()}.

@item 
Fix incorrect check which allowed more than one varargs in clinic.py.

@item 
Fix miscalculation of @code{noptargs} in generated code.

@item 
Do not generate @code{noptargs} when there is a vararg argument and no optional argument.
@end itemize
@end itemize

@node C API<27>,,Tools/Demos<23>,Python 3 12 0 alpha 3
@anchor{whatsnew/changelog id349}@anchor{1b16}
@subsubsection C API



@itemize -

@item 
gh-98680@footnote{https://github.com/python/cpython/issues/98680}: @code{PyBUF_*} constants were marked as part of Limited API of
Python 3.11+. These were available in 3.11.0 with
@ref{660,,Py_LIMITED_API} defined for 3.11, and are necessary to use the
buffer API.

@item 
gh-99612@footnote{https://github.com/python/cpython/issues/99612}: Fix @ref{1b17,,PyUnicode_DecodeUTF8Stateful()} for ASCII-only data:
@code{*consumed} was not set.

@item 
gh-47146@footnote{https://github.com/python/cpython/issues/47146}: The @code{structmember.h} header is deprecated. Its non-deprecated
contents are now available just by including @code{Python.h}, with a @code{Py_}
prefix added if it was missing. (Deprecated contents are
@ref{7b0,,T_OBJECT}, @ref{7b2,,T_NONE}, and no-op flags.) Patch by Petr
Viktorin, based on earlier work by Alexander Belopolsky and Matthias
Braun.
@end itemize

@node Python 3 12 0 alpha 2,Python 3 12 0 alpha 1,Python 3 12 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-12-0-alpha-2}@anchor{1b18}
@subsection Python 3.12.0 alpha 2


`Release date: 2022-11-14'

@menu
* セキュリティ: セキュリティ<26>. 
* Core and Builtins: Core and Builtins<72>. 
* ビルド: ビルド<30>. 
* Core and Builtins: Core and Builtins<73>. 
* ライブラリ: ライブラリ<77>. 
* ドキュメント: ドキュメント<27>. 
* テスト: テスト<26>. 
* ビルド: ビルド<31>. 
* Windows: Windows<28>. 
* macOS: macOS<19>. 
* C API: C API<28>. 

@end menu

@node セキュリティ<26>,Core and Builtins<72>,,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id350}@anchor{1b19}
@subsubsection セキュリティ



@itemize -

@item 
gh-98433@footnote{https://github.com/python/cpython/issues/98433}: The IDNA codec decoder used on DNS hostnames by @ref{d1,,socket} or
@ref{b,,asyncio} related name resolution functions no longer involves a
quadratic algorithm. This prevents a potential CPU denial of service if an
out-of-spec excessive length hostname involving bidirectional characters
were decoded. Some protocols such as @ref{10e,,urllib} http @code{3@var{xx}}
redirects potentially allow for an attacker to supply such a name.

Individual labels within an IDNA encoded DNS name will now raise an error
early during IDNA decoding if they are longer than 1024 unicode characters
given that each decoded DNS label must be 63 or fewer characters and the
entire decoded DNS name is limited to 255. Only an application presenting
a hostname or label consisting primarily of 
@geindex RFC; RFC 3454
RFC 3454@footnote{https://datatracker.ietf.org/doc/html/rfc3454.html} section 3.1
"Nothing" characters to be removed would run into of this new limit. See
also 
@geindex RFC; RFC 5894
RFC 5894@footnote{https://datatracker.ietf.org/doc/html/rfc5894.html} section 6 and 
@geindex RFC; RFC 3491
RFC 3491@footnote{https://datatracker.ietf.org/doc/html/rfc3491.html}.

@item 
gh-98739@footnote{https://github.com/python/cpython/issues/98739}: Update bundled libexpat to 2.5.0
@end itemize

@node Core and Builtins<72>,ビルド<30>,セキュリティ<26>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id351}@anchor{1b1a}
@subsubsection Core and Builtins



@itemize -

@item 
gh-81057@footnote{https://github.com/python/cpython/issues/81057}: The docs clearly say that @ref{1b1b,,PyImport_Inittab},
@ref{1b1c,,PyImport_AppendInittab()}, and @ref{1b1d,,PyImport_ExtendInittab()}
should not be used after @ref{460,,Py_Initialize()} has been called. We now
enforce this for the two functions.  Additionally, the runtime now uses an
internal copy of @ref{1b1b,,PyImport_Inittab}, to guard against
modification.

@item 
gh-99298@footnote{https://github.com/python/cpython/issues/99298}: Fix an issue that could potentially cause incorrect error
handling for some bytecode instructions.

@item 
gh-99254@footnote{https://github.com/python/cpython/issues/99254}: The compiler now removes all unused constants from code objects
(except the first one, which may be a docstring).

@item 
gh-99205@footnote{https://github.com/python/cpython/issues/99205}: Fix an issue that prevented @ref{990,,PyThreadState} and
@ref{aba,,PyInterpreterState} memory from being freed properly.

@item 
gh-81057@footnote{https://github.com/python/cpython/issues/81057}: The 18 global C variables holding the state of the allocators
have been moved to @code{_PyRuntimeState}.  This is a strictly internal
change with no change in behavior.

@item 
gh-99181@footnote{https://github.com/python/cpython/issues/99181}: Fix failure in @ref{1ac,,except*} with unhashable
exceptions.

@item 
gh-99204@footnote{https://github.com/python/cpython/issues/99204}: Fix calculation of @code{sys._base_executable} when inside a
POSIX virtual environment using copies of the python binary when the base
installation does not provide the executable name used by the venv.
Calculation will fall back to alternative names ("python<MAJOR>",
"python<MAJOR>.<MINOR>").

@item 
gh-96055@footnote{https://github.com/python/cpython/issues/96055}: Update @ref{5c,,faulthandler} to emit an error message with the
proper unexpected signal number. Patch by Donghee Na.

@item 
gh-99153@footnote{https://github.com/python/cpython/issues/99153}: Fix location of @ref{18e,,SyntaxError} for a @ref{8f8,,try} block
with both @ref{1ab,,except} and @ref{1ac,,except*}.

@item 
gh-98686@footnote{https://github.com/python/cpython/issues/98686}: Merge the adaptive opcode logic into each instruction's
unquickened variant, and merge the logic in @code{EXTENDED_ARG_QUICK} into
@ref{1b1e,,EXTENDED_ARG}. With these changes, the quickening that happens at
code object creation is now only responsible for initializing warmup
counters and inserting superinstructions.

@item 
gh-99103@footnote{https://github.com/python/cpython/issues/99103}: Fix the error reporting positions of specialized traceback
anchors when the source line contains Unicode characters.

@item 
gh-99139@footnote{https://github.com/python/cpython/issues/99139}: Improve the error suggestion for @ref{452,,NameError} exceptions for
instances. Now if a @ref{452,,NameError} is raised in a method and the
instance has an attribute that's exactly equal to the name in the
exception, the suggestion will include @code{self.<NAME>} instead of the
closest match in the method scope. Patch by Pablo Galindo

@item 
gh-98401@footnote{https://github.com/python/cpython/issues/98401}: Octal escapes with value larger than @code{0o377} (ex: @code{"\477"}),
deprecated in Python 3.11, now produce a @ref{1ae,,SyntaxWarning}, instead of
@ref{1a3,,DeprecationWarning}. In a future Python version they will be
eventually a @ref{18e,,SyntaxError}. Patch by Victor Stinner.

@item 
gh-98401@footnote{https://github.com/python/cpython/issues/98401}: A backslash-character pair that is not a valid escape sequence
now generates a @ref{1ae,,SyntaxWarning}, instead of
@ref{1a3,,DeprecationWarning}.  For example, @code{re.compile("\d+\.\d+")} now
emits a @ref{1ae,,SyntaxWarning} (@code{"\d"} is an invalid escape sequence), use
raw strings for regular expression: @code{re.compile(r"\d+\.\d+")}. In a
future Python version, @ref{18e,,SyntaxError} will eventually be raised,
instead of @ref{1ae,,SyntaxWarning}. Patch by Victor Stinner.

@item 
gh-96793@footnote{https://github.com/python/cpython/issues/96793}: Handle StopIteration and StopAsyncIteration raised in generator
or coroutines in the bytecode, rather than in wrapping C code.

@item 
gh-98931@footnote{https://github.com/python/cpython/issues/98931}: Improve the @ref{18e,,SyntaxError} error message when the user types
@code{import x from y} instead of @code{from y import x}. Patch by Pablo Galindo

@item 
gh-98852@footnote{https://github.com/python/cpython/issues/98852}: Fix subscription of type aliases containing bare generic types
or types like @ref{486,,TypeVar}: for example @code{tuple[A, T][int]}
and @code{tuple[TypeVar, T][int]}, where @code{A} is a generic type, and @code{T}
is a type variable.

@item 
gh-98925@footnote{https://github.com/python/cpython/issues/98925}: Lower the recursion depth for marshal on WASI to support
(in-development) wasmtime 2.0.

@item 
gh-98783@footnote{https://github.com/python/cpython/issues/98783}: Fix multiple crashes in debug mode when @code{str} subclasses are
used instead of @code{str} itself.

@item 
gh-98811@footnote{https://github.com/python/cpython/issues/98811}: Use complete source locations to simplify detection of
@code{__future__} imports which are not at the beginning of the file. Also
corrects the offset in the exception raised in one case, which was off by
one and impeded highlighting.

@item 
gh-96793@footnote{https://github.com/python/cpython/issues/96793}: Add specialization of @ref{1ac2,,FOR_ITER} for generators. Saves
multiple layers of dispatch and checking to get from the
@ref{1ac2,,FOR_ITER} instruction in the caller to the @ref{5bb,,RESUME} in
the generator.

@item 
gh-98762@footnote{https://github.com/python/cpython/issues/98762}: Fix source locations of @ref{a0e,,match} sub-patterns.

@item 
gh-98586@footnote{https://github.com/python/cpython/issues/98586}: Added the methods @ref{77e,,PyObject_Vectorcall()} and
@ref{77f,,PyObject_VectorcallMethod()} to the @ref{775,,Limited API}
along with the auxiliary macro constant
@ref{780,,PY_VECTORCALL_ARGUMENTS_OFFSET}.

The availability of these functions enables more efficient 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
vector calls from binary extension modules that avoid argument
boxing/unboxing overheads.

@item 
gh-99257@footnote{https://github.com/python/cpython/issues/99257}: Fix an issue where member descriptors (such as those for
@ref{1704,,__slots__}) could behave incorrectly or crash instead of
raising a @ref{198,,TypeError} when accessed via an instance of an invalid
type.

@item 
gh-93143@footnote{https://github.com/python/cpython/issues/93143}: Rather than changing @code{co_code}, the
interpreter will now display a @ref{4d7,,RuntimeWarning} and assign
@ref{885,,None} to any fast locals that are left unbound after jumps or
@ref{1b1f,,del} statements executed while tracing.

@item 
gh-96421@footnote{https://github.com/python/cpython/issues/96421}: When calling into Python code from C code, through
@ref{122f,,PyEval_EvalFrameEx()} or a related C-API function, a shim frame in
inserted into the call stack. This occurs in the
@code{_PyEval_EvalFrameDefault()} function. The extra frame should be
invisible to all Python and most C extensions, but out-of-process
profilers and debuggers need to be aware of it. These shim frames can be
detected by checking @code{frame->owner == FRAME_OWNED_BY_CSTACK}.

Extensions implementing their own interpreters using PEP 523 need to be
aware of this shim frame and the changes to the semantics of
@ref{1b20,,RETURN_VALUE}, @ref{5ba,,YIELD_VALUE}, and
@ref{90b,,RETURN_GENERATOR}, which now clear the frame.
@end itemize

@node ビルド<30>,Core and Builtins<73>,Core and Builtins<72>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id352}@anchor{1b21}
@subsubsection ビルド



@itemize -

@item 
gh-98415@footnote{https://github.com/python/cpython/issues/98415}: Fix detection of MAC addresses for @ref{116,,uuid} on certain OSs.
Patch by Chaim Sanders
@end itemize

@node Core and Builtins<73>,ライブラリ<77>,ビルド<30>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id353}@anchor{1b22}
@subsubsection Core and Builtins



@itemize -

@item 
gh-98686@footnote{https://github.com/python/cpython/issues/98686}: Quicken all code objects, and specialize adaptive bytecode
instructions more aggressively.

@item 
gh-92119@footnote{https://github.com/python/cpython/issues/92119}: Print exception class name instead of its string representation
when raising errors from @ref{2e,,ctypes} calls.

@item 
gh-91058@footnote{https://github.com/python/cpython/issues/91058}: @ref{65b,,ImportError} raised from failed @code{from <module> import
<name>} now include suggestions for the value of @code{<name>} based on the
available names in @code{<module>}. Patch by Pablo Galindo

@item 
gh-96793@footnote{https://github.com/python/cpython/issues/96793}: The @ref{1ac2,,FOR_ITER} now leaves the iterator on the stack on
termination of the loop. This is to assist specialization of loops for
generators.

@item 
gh-90716@footnote{https://github.com/python/cpython/issues/90716}: Add _pylong.py module.  It includes asymptotically faster
algorithms that can be used for operations on integers with many digits.
It is used by longobject.c to speed up some operations.

@item 
gh-95389@footnote{https://github.com/python/cpython/issues/95389}: Expose @ref{1b23,,ETH_P_ALL} and some of the
@ref{1b24,,ETHERTYPE_* constants} in @ref{d1,,socket}.
Patch by Noam Cohen.
@end itemize

@node ライブラリ<77>,ドキュメント<27>,Core and Builtins<73>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id354}@anchor{1b25}
@subsubsection ライブラリ



@itemize -

@item 
gh-93696@footnote{https://github.com/python/cpython/issues/93696}: Allow @ref{aa,,pdb} to locate source for frozen modules in the
standard library.

@item 
gh-99418@footnote{https://github.com/python/cpython/issues/99418}: Fix bug in @ref{362,,urllib.parse.urlparse()} that causes URL schemes
that begin with a digit, a plus sign, or a minus sign to be parsed
incorrectly.

@item 
gh-94597@footnote{https://github.com/python/cpython/issues/94597}: Deprecate @code{asyncio.AbstractChildWatcher} to be removed in
Python 3.14. Patch by Kumar Aditya.

@item 
gh-99305@footnote{https://github.com/python/cpython/issues/99305}: Improve performance of @ref{1b26,,secrets.token_hex()}.

@item 
gh-74044@footnote{https://github.com/python/cpython/issues/74044}: Fixed bug where @ref{22f,,inspect.signature()} reported incorrect
arguments for decorated methods.

@item 
gh-99275@footnote{https://github.com/python/cpython/issues/99275}: Fix @code{SystemError} in @ref{2e,,ctypes} when exception was not set
during @code{__initsubclass__}.

@item 
gh-99277@footnote{https://github.com/python/cpython/issues/99277}: Remove older version of
@code{_SSLProtocolTransport.get_write_buffer_limits} in
@code{asyncio.sslproto}

@item 
gh-99248@footnote{https://github.com/python/cpython/issues/99248}: fix negative numbers failing in verify()

@item 
gh-99155@footnote{https://github.com/python/cpython/issues/99155}: Fix @ref{c2d,,statistics.NormalDist} pickle with @code{0} and @code{1}
protocols.

@item 
gh-93464@footnote{https://github.com/python/cpython/issues/93464}: @code{enum.auto()} is now correctly activated when combined with
other assignment values.  E.g. @code{ONE = auto(), 'some text'} will now
evaluate as @code{(1, 'some text')}.

@item 
gh-99134@footnote{https://github.com/python/cpython/issues/99134}: Update the bundled copy of pip to version 22.3.1.

@item 
gh-92584@footnote{https://github.com/python/cpython/issues/92584}: Remove the @code{distutils} package. It was deprecated in Python
3.10 by 
@geindex Python Enhancement Proposals; PEP 632
PEP 632@footnote{https://peps.python.org/pep-0632/} "Deprecate distutils module". For projects still using
@code{distutils} and cannot be updated to something else, the @code{setuptools}
project can be installed: it still provides @code{distutils}. Patch by Victor
Stinner.

@item 
gh-98999@footnote{https://github.com/python/cpython/issues/98999}: Now @code{_pyio} is consistent with @code{_io} in raising
@code{ValueError} when executing methods over closed buffers.

@item 
gh-83004@footnote{https://github.com/python/cpython/issues/83004}: Clean up refleak on failed module initialisation in
@code{_zoneinfo}

@item 
gh-83004@footnote{https://github.com/python/cpython/issues/83004}: Clean up refleaks on failed module initialisation in
@code{_pickle}

@item 
gh-83004@footnote{https://github.com/python/cpython/issues/83004}: Clean up refleak on failed module initialisation in @code{_io}.

@item 
gh-98897@footnote{https://github.com/python/cpython/issues/98897}: Fix memory leak in @ref{bf5,,math.dist()} when both points don't have
the same dimension. Patch by Kumar Aditya.

@item 
gh-98878@footnote{https://github.com/python/cpython/issues/98878}: Use the frame bound builtins when offering a name suggestion in
@ref{104,,traceback} to prevent crashing when @code{__builtins__} is not a dict.

@item 
gh-98139@footnote{https://github.com/python/cpython/issues/98139}: In @code{importlib._bootstrap}, enhance namespace package repr
to @code{<module 'x' (namespace) from ['path']>}.

@item 
gh-90352@footnote{https://github.com/python/cpython/issues/90352}: Fix @code{_SelectorDatagramTransport} to inherit from
@ref{1b27,,DatagramTransport} in @ref{b,,asyncio}. Patch by Kumar
Aditya.

@item 
gh-98793@footnote{https://github.com/python/cpython/issues/98793}: Fix argument typechecks in @code{_overlapped.WSAConnect()} and
@code{_overlapped.Overlapped.WSASendTo()} functions.

@item 
gh-98744@footnote{https://github.com/python/cpython/issues/98744}: Prevent crashing in @ref{104,,traceback} when retrieving the
byte-offset for some source files that contain certain unicode characters.

@item 
gh-98740@footnote{https://github.com/python/cpython/issues/98740}: Fix internal error in the @ref{be,,re} module which in very rare
circumstances prevented compilation of a regular expression containing a
@ref{1b28,,conditional expression} without the
"else" branch.

@item 
gh-98703@footnote{https://github.com/python/cpython/issues/98703}: Fix @ref{1b29,,asyncio.StreamWriter.drain()} to call
@code{protocol.connection_lost} callback only once on Windows.

@item 
gh-98624@footnote{https://github.com/python/cpython/issues/98624}: Add a mutex to unittest.mock.NonCallableMock to protect
concurrent access to mock attributes.

@item 
gh-98658@footnote{https://github.com/python/cpython/issues/98658}: The @ref{4be,,array.array} class now supports subscripting, making
it a @ref{1a1,,generic type}.

@item 
gh-98284@footnote{https://github.com/python/cpython/issues/98284}: Improved @ref{198,,TypeError} message for undefined abstract
methods of a @ref{111b,,abc.ABC} instance. The names of the missing methods
are surrounded by single-quotes to highlight them.

@item 
gh-96151@footnote{https://github.com/python/cpython/issues/96151}: Allow @code{BUILTINS} to be a valid field name for frozen
dataclasses.

@item 
gh-98086@footnote{https://github.com/python/cpython/issues/98086}: Make sure @code{patch.dict()} can be applied on async functions.

@item 
gh-72719@footnote{https://github.com/python/cpython/issues/72719}: Remove modules @code{asyncore} and @code{asynchat}, which were
deprecated by 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}.

@item 
gh-96192@footnote{https://github.com/python/cpython/issues/96192}: Fix handling of @code{bytes} @ref{5a1,,path-like objects} in @code{os.ismount()}.

@item 
gh-94172@footnote{https://github.com/python/cpython/issues/94172}: @ref{62,,ftplib}: Remove the @code{FTP_TLS.ssl_version} class
attribute: use the `context' parameter instead. Patch by Victor Stinner

@item 
gh-94172@footnote{https://github.com/python/cpython/issues/94172}: Remove the `keyfile' and `certfile' parameters from the
@ref{62,,ftplib}, @ref{78,,imaplib}, @ref{b1,,poplib} and @ref{cf,,smtplib} modules,
and the `key_file', `cert_file' and `check_hostname' parameters from the
@ref{73,,http.client} module, all deprecated since Python 3.6. Use the
`context' parameter (`ssl_context' in @ref{78,,imaplib}) instead. Patch by
Victor Stinner.

@item 
gh-83638@footnote{https://github.com/python/cpython/issues/83638}: Add the @ref{6dd,,autocommit} attribute to
@ref{54d,,sqlite3.Connection} and the `autocommit' parameter to
@ref{5a6,,sqlite3.connect()} to control 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/}-compliant @ref{6de,,transaction handling}. Patch by Erlend E.
Aasland.

@item 
gh-92452@footnote{https://github.com/python/cpython/issues/92452}: Fixed a race condition that could cause
@ref{174,,sysconfig.get_config_var()} to incorrectly return @ref{885,,None} in
multi-threaded programs.

@item 
gh-91803@footnote{https://github.com/python/cpython/issues/91803}: Fix an error when using a method of objects mocked with
@ref{1934,,unittest.mock.create_autospec()} after it was sealed with
@ref{d9a,,unittest.mock.seal()} function.

@item 
bpo-38523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38523}: @ref{c1e,,shutil.copytree()} now applies the
`ignore_dangling_symlinks' argument recursively.

@item 
bpo-40358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40358}: Add walk_up argument in @ref{2fd,,pathlib.PurePath.relative_to()}.

@item 
bpo-36267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36267}: Fix IndexError in @ref{1bd,,argparse.ArgumentParser} when a
@code{store_true} action is given an explicit argument.
@end itemize

@node ドキュメント<27>,テスト<26>,ライブラリ<77>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id355}@anchor{1b2a}
@subsubsection ドキュメント



@itemize -

@item 
gh-98832@footnote{https://github.com/python/cpython/issues/98832}: Changes wording of docstring for @ref{26e,,pathlib.Path.iterdir()}.

@item 
gh-97966@footnote{https://github.com/python/cpython/issues/97966}: Update uname docs to clarify the special nature of the platform
attribute and to indicate when it became late-bound.
@end itemize

@node テスト<26>,ビルド<31>,ドキュメント<27>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id356}@anchor{1b2b}
@subsubsection テスト



@itemize -

@item 
gh-98903@footnote{https://github.com/python/cpython/issues/98903}: The Python test suite now fails with exit code 4 if no tests
ran. It should help detecting typos in test names and test methods.

@item 
gh-98713@footnote{https://github.com/python/cpython/issues/98713}: Fix a bug in the @ref{10a,,typing} tests where a test relying on
CPython-specific implementation details was not decorated with
@code{@@cpython_only} and was not skipped on other implementations.

@item 
gh-87390@footnote{https://github.com/python/cpython/issues/87390}: Add tests for star-unpacking with PEP 646, and some other
miscellaneous PEP 646 tests.

@item 
gh-96853@footnote{https://github.com/python/cpython/issues/96853}: Added explicit coverage of @code{Py_Initialize} (and hence
@code{Py_InitializeEx}) back to the embedding tests (all other embedding
tests migrated to @code{Py_InitializeFromConfig} in Python 3.11)

@item 
bpo-34272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34272}: Some C API tests were moved into the new Lib/test/test_capi/
directory.
@end itemize

@node ビルド<31>,Windows<28>,テスト<26>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id357}@anchor{1b2c}
@subsubsection ビルド



@itemize -

@item 
gh-99086@footnote{https://github.com/python/cpython/issues/99086}: Fix @code{-Wimplicit-int} compiler warning in @code{configure}
check for @code{PTHREAD_SCOPE_SYSTEM}.

@item 
gh-99016@footnote{https://github.com/python/cpython/issues/99016}: Fix build with @code{PYTHON_FOR_REGEN=python3.8}.

@item 
gh-97731@footnote{https://github.com/python/cpython/issues/97731}: Specify the full path to the source location for @code{make
docclean} (needed for cross-builds).

@item 
gh-98949@footnote{https://github.com/python/cpython/issues/98949}: Drop unused build dependency on @code{readelf}.

@item 
gh-98989@footnote{https://github.com/python/cpython/issues/98989}: Use @code{python3.11}, if available, for regeneration and freezing.

@item 
gh-98831@footnote{https://github.com/python/cpython/issues/98831}: Add new tooling, in @code{Tools/cases_generator}, to generate the
interpreter switch statement from a list of opcode definitions. This only
affects adding, modifying or removing instruction definitions. The
instruction definitions now live in @code{Python/bytecodes.c}, in the form of
a custom DSL (under development)@footnote{https://github.com/faster-cpython/ideas/blob/main/3.12/interpreter_definition.md}.
The tooling reads this file and writes @code{Python/generated_cases.c.h},
which is then included by @code{Python/ceval.c} to provide most of the cases
of the main interpreter switch.

@item 
gh-98817@footnote{https://github.com/python/cpython/issues/98817}: Remove PCbuild/lib.pyproj: it's not used for anything, is only a
minor convenience for Visual Studio users (who probably mostly don't even
know about it), and it takes a lot of maintenance effort to keep updated.

@item 
gh-98776@footnote{https://github.com/python/cpython/issues/98776}: Fix @code{make regen-test-levenshtein} for out-of-tree builds.

@item 
gh-98707@footnote{https://github.com/python/cpython/issues/98707}: Don't use vendored @code{libmpdec} headers if
@ref{657,,--with-system-libmpdec} is passed to @code{configure}. Don't
use vendored @code{libexpat} headers if @ref{1b2d,,--with-system-expat} is
passed to @code{configure}.
@end itemize

@node Windows<28>,macOS<19>,ビルド<31>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id358}@anchor{1b2e}
@subsubsection Windows



@itemize -

@item 
gh-98689@footnote{https://github.com/python/cpython/issues/98689}: Update Windows builds to zlib v1.2.13.  v1.2.12 has
@geindex Common Vulnerabilities and Exposures; CVE 2022-37434
CVE 2022-37434@footnote{https://www.cve.org/CVERecord?id=CVE-2022-37434}, but the vulnerable @code{inflateGetHeader} API is not used
by Python.

@item 
gh-98790@footnote{https://github.com/python/cpython/issues/98790}: Assumes that a missing @code{DLLs} directory means that standard
extension modules are in the executable's directory.

@item 
gh-98745@footnote{https://github.com/python/cpython/issues/98745}: Update @code{py.exe} launcher to install 3.11 by default and
3.12 on request.

@item 
gh-98692@footnote{https://github.com/python/cpython/issues/98692}: Fix the @ref{7da,,Python install manager} ignoring unrecognized shebang lines
instead of treating them as local paths

@item 
gh-94328@footnote{https://github.com/python/cpython/issues/94328}: Update Windows installer to use SQLite 3.39.4.
@end itemize

@node macOS<19>,C API<28>,Windows<28>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id359}@anchor{1b2f}
@subsubsection macOS



@itemize -

@item 
gh-94328@footnote{https://github.com/python/cpython/issues/94328}: Update macOS installer to SQLite 3.39.4.
@end itemize

@node C API<28>,,macOS<19>,Python 3 12 0 alpha 2
@anchor{whatsnew/changelog id360}@anchor{1b30}
@subsubsection C API



@itemize -

@item 
gh-98724@footnote{https://github.com/python/cpython/issues/98724}: The @ref{798,,Py_CLEAR}, @ref{799,,Py_SETREF} and
@ref{79a,,Py_XSETREF} macros now only evaluate their argument once. If the
argument has side effects, these side effects are no longer duplicated.
Patch by Victor Stinner.

@item 
gh-98978@footnote{https://github.com/python/cpython/issues/98978}: Fix use-after-free in @code{Py_SetPythonHome(NULL)},
@code{Py_SetProgramName(NULL)} and @code{_Py_SetProgramFullPath(NULL)} function
calls. Issue reported by Benedikt Reinartz. Patch by Victor Stinner.

@item 
gh-98410@footnote{https://github.com/python/cpython/issues/98410}: Add @code{getbufferproc} and @code{releasebufferproc} to the stable
API.

@item 
gh-98610@footnote{https://github.com/python/cpython/issues/98610}: Some configurable capabilities of sub-interpreters have changed.
They always allow subprocesses (@ref{dc,,subprocess}) now, whereas before
subprocesses could be optionally disallowed for a sub-interpreter. Instead
@code{os.exec()} can now be disallowed. Disallowing daemon threads is now
supported.  Disallowing all threads is still allowed, but is never done by
default. Note that the optional restrictions are only available through
@code{_Py_NewInterpreterFromConfig()}, which isn't a public API. They do not
affect the main interpreter, nor @ref{1b31,,Py_NewInterpreter()}.

@item 
gh-98608@footnote{https://github.com/python/cpython/issues/98608}: A @code{_PyInterpreterConfig} has been added and
@code{_Py_NewInterpreter()} has been renamed to
@code{_Py_NewInterpreterFromConfig()}.  The "isolated_subinterpreters"
argument is now a granular config that captures the previous behavior.
Note that this is all "private" API.

@item 
gh-96853@footnote{https://github.com/python/cpython/issues/96853}: @code{Py_InitializeEx} now correctly calls @code{PyConfig_Clear} after
initializing the interpreter (the omission didn't cause a memory leak only
because none of the dynamically allocated config fields are populated by
the wrapper function)

@item 
gh-91248@footnote{https://github.com/python/cpython/issues/91248}: Add @ref{789,,PyFrame_GetVar()} and @ref{78a,,PyFrame_GetVarString()}
functions to get a frame variable by its name. Patch by Victor Stinner.
@end itemize

@node Python 3 12 0 alpha 1,Python 3 11 0 beta 1,Python 3 12 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-12-0-alpha-1}@anchor{1b32}
@subsection Python 3.12.0 alpha 1


`Release date: 2022-10-25'

@menu
* セキュリティ: セキュリティ<27>. 
* Core and Builtins: Core and Builtins<74>. 
* ライブラリ: ライブラリ<78>. 
* Core and Builtins: Core and Builtins<75>. 
* ライブラリ: ライブラリ<79>. 
* Core and Builtins: Core and Builtins<76>. 
* ライブラリ: ライブラリ<80>. 
* Core and Builtins: Core and Builtins<77>. 
* ライブラリ: ライブラリ<81>. 
* Core and Builtins: Core and Builtins<78>. 
* ライブラリ: ライブラリ<82>. 
* Core and Builtins: Core and Builtins<79>. 
* ライブラリ: ライブラリ<83>. 
* Core and Builtins: Core and Builtins<80>. 
* ライブラリ: ライブラリ<84>. 
* Core and Builtins: Core and Builtins<81>. 
* ライブラリ: ライブラリ<85>. 
* Core and Builtins: Core and Builtins<82>. 
* ライブラリ: ライブラリ<86>. 
* Core and Builtins: Core and Builtins<83>. 
* ライブラリ: ライブラリ<87>. 
* ドキュメント: ドキュメント<28>. 
* テスト: テスト<27>. 
* ビルド: ビルド<32>. 
* Windows: Windows<29>. 
* macOS: macOS<20>. 
* IDLE: IDLE<15>. 
* Tools/Demos: Tools/Demos<24>. 
* C API: C API<29>. 

@end menu

@node セキュリティ<27>,Core and Builtins<74>,,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id361}@anchor{1b33}
@subsubsection セキュリティ



@itemize -

@item 
gh-97616@footnote{https://github.com/python/cpython/issues/97616}: Fix multiplying a list by an integer (@code{list *= int}): detect
the integer overflow when the new allocated length is close to the maximum
size. Issue reported by Jordan Limor.  Patch by Victor Stinner.

@item 
gh-97514@footnote{https://github.com/python/cpython/issues/97514}: On Linux the @ref{98,,multiprocessing} module returns to using
filesystem backed unix domain sockets for communication with the
`forkserver' process instead of the Linux abstract socket namespace.  Only
code that chooses to use the @ref{1d5,,"forkserver" start method} is affected.

Abstract sockets have no permissions and could allow any user on the
system in the same network namespace@footnote{https://man7.org/linux/man-pages/man7/network_namespaces.7.html} (often
the whole system) to inject code into the multiprocessing `forkserver'
process. This was a potential privilege escalation. Filesystem based
socket permissions restrict this to the `forkserver' process user as was
the default in Python 3.8 and earlier.

This prevents Linux 
@geindex Common Vulnerabilities and Exposures; CVE 2022-42919
CVE 2022-42919@footnote{https://www.cve.org/CVERecord?id=CVE-2022-42919}.

@item 
gh-87389@footnote{https://github.com/python/cpython/issues/87389}: @ref{76,,http.server}: Fix an open redirection vulnerability in the
HTTP server when an URI path starts with @code{//}.  Vulnerability
discovered, and initial fix proposed, by Hamza Avvan.

@item 
gh-79096@footnote{https://github.com/python/cpython/issues/79096}: LWPCookieJar and MozillaCookieJar create files with file mode
600 instead of 644 (Microsoft Windows is not affected)

@item 
gh-92888@footnote{https://github.com/python/cpython/issues/92888}: Fix @code{memoryview} use after free when accessing the backing
buffer in certain cases.

@item 
gh-68966@footnote{https://github.com/python/cpython/issues/68966}: The deprecated mailcap module now refuses to inject unsafe text
(filenames, MIME types, parameters) into shell commands. Instead of using
such text, it will warn and act as if a match was not found (or for test
commands, as if the test failed).
@end itemize

@node Core and Builtins<74>,ライブラリ<78>,セキュリティ<27>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id362}@anchor{1b34}
@subsubsection Core and Builtins



@itemize -

@item 
gh-98374@footnote{https://github.com/python/cpython/issues/98374}: Suppress ImportError for invalid query for help() command. Patch
by Donghee Na.

@item 
gh-98461@footnote{https://github.com/python/cpython/issues/98461}: Fix source location in bytecode for list, set and dict
comprehensions as well as generator expressions.

@item 
gh-98354@footnote{https://github.com/python/cpython/issues/98354}: Added unicode check for @code{name} attribute of @code{spec} argument
passed in @code{_imp.create_builtin()} function.

@item 
gh-98398@footnote{https://github.com/python/cpython/issues/98398}: Fix source location of 'assert' bytecodes.

@item 
gh-98390@footnote{https://github.com/python/cpython/issues/98390}: Fix location of sub-expressions of boolean expressions, by
reducing their scope to that of the sub-expression.

@item 
gh-98254@footnote{https://github.com/python/cpython/issues/98254}: Modules from the standard library are now potentially suggested
as part of the error messages displayed by the interpreter when an
@ref{452,,NameError} is raised to the top level. Patch by Pablo Galindo

@item 
gh-97997@footnote{https://github.com/python/cpython/issues/97997}: Add running column offset to the tokenizer state to avoid
calculating AST column information with pointer arithmetic.

@item 
gh-97973@footnote{https://github.com/python/cpython/issues/97973}: Modify the tokenizer to return all necessary information the
parser needs to set location information in the AST nodes, so that the
parser does not have to calculate those doing pointer arithmetic.
@end itemize

@node ライブラリ<78>,Core and Builtins<75>,Core and Builtins<74>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id363}@anchor{1b35}
@subsubsection ライブラリ



@itemize -

@item 
gh-96078@footnote{https://github.com/python/cpython/issues/96078}: @ref{1329,,os.sched_yield()} now release the GIL while calling
sched_yield(2). Patch by Donghee Na.

@item 
gh-97955@footnote{https://github.com/python/cpython/issues/97955}: Migrate @ref{13a,,zoneinfo} to Argument Clinic.
@end itemize

@node Core and Builtins<75>,ライブラリ<79>,ライブラリ<78>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id364}@anchor{1b36}
@subsubsection Core and Builtins



@itemize -

@item 
gh-97912@footnote{https://github.com/python/cpython/issues/97912}: The compiler now avoids quadratic behavior when finding which
instructions should use the @ref{70b,,LOAD_FAST_CHECK} opcode.

@item 
gh-97002@footnote{https://github.com/python/cpython/issues/97002}: Fix an issue where several frame objects could be backed by the
same interpreter frame, possibly leading to corrupted memory and hard
crashes of the interpreter.

@item 
gh-97943@footnote{https://github.com/python/cpython/issues/97943}: Bugfix: @ref{1b37,,PyFunction_GetAnnotations()} should return a
borrowed reference. It was returning a new reference.

@item 
gh-97922@footnote{https://github.com/python/cpython/issues/97922}: The Garbage Collector now runs only on the eval breaker
mechanism of the Python bytecode evaluation loop instead on object
allocations. The GC can also run when @ref{693,,PyErr_CheckSignals()} is
called so C extensions that need to run for a long time without executing
any Python code also have a chance to execute the GC periodically.

@item 
gh-65961@footnote{https://github.com/python/cpython/issues/65961}: When @code{__package__} is different than @code{__spec__.parent},
raise a @code{DeprecationWarning} instead of @code{ImportWarning}.

Also remove @code{importlib.util.set_package()} which was scheduled for
removal.

@item 
gh-97850@footnote{https://github.com/python/cpython/issues/97850}: Long deprecated, @code{module_repr()} should now be completely
eradicated.

@item 
gh-86298@footnote{https://github.com/python/cpython/issues/86298}: In cases where @code{warnings.warn_explicit()} consults the
module's loader, an @code{DeprecationWarning} is issued when @code{m.__loader__}
differs from @code{m.__spec__.loader}.

@item 
gh-97779@footnote{https://github.com/python/cpython/issues/97779}: Ensure that all Python frame objects are backed by "complete"
frames.

@item 
gh-91052@footnote{https://github.com/python/cpython/issues/91052}: Add API for subscribing to modification events on selected
dictionaries.

@item 
gh-97752@footnote{https://github.com/python/cpython/issues/97752}: Fix possible data corruption or crashes when accessing the
@code{f_back} member of newly-created generator or coroutine frames.

@item 
gh-97591@footnote{https://github.com/python/cpython/issues/97591}: Fixed a missing incref/decref pair in
@code{Exception.__setstate__()}. Patch by Ofey Chan.

@item 
gh-97670@footnote{https://github.com/python/cpython/issues/97670}: Remove the @code{sys.getdxp()} function and the
@code{Tools/scripts/analyze_dxp.py} script. DXP stands for "dynamic execution
pairs". They were related to @code{DYNAMIC_EXECUTION_PROFILE} and @code{DXPAIRS}
macros which have been removed in Python 3.11. Python can now be built
with @ref{1b38,,./configure --enable-pystats} to gather
statistics on Python opcodes.  Patch by Victor Stinner.

@item 
gh-94526@footnote{https://github.com/python/cpython/issues/94526}: Fix the Python path configuration used to initialized
@ref{3e4,,sys.path} at Python startup. Paths are no longer encoded to
UTF-8/strict to avoid encoding errors if it contains surrogate characters
(bytes paths are decoded with the surrogateescape error handler). Patch by
Victor Stinner.

@item 
gh-96670@footnote{https://github.com/python/cpython/issues/96670}: The parser now raises @ref{18e,,SyntaxError} when parsing source
code containing null bytes. Patch by Pablo Galindo

@item 
gh-96975@footnote{https://github.com/python/cpython/issues/96975}: Fix a crash occurring when @ref{1b39,,PyEval_GetFrame()} is called
while the topmost Python frame is in a partially-initialized state.

@item 
gh-96848@footnote{https://github.com/python/cpython/issues/96848}: Fix command line parsing: reject @ref{16f,,-X int_max_str_digits} option with no value (invalid) when the
@geindex PYTHONINTMAXSTRDIGITS
@geindex 環境変数; PYTHONINTMAXSTRDIGITS
@ref{1b3a,,PYTHONINTMAXSTRDIGITS} environment variable is set to a valid
limit. Patch by Victor Stinner.

@item 
gh-95921@footnote{https://github.com/python/cpython/issues/95921}: Fix overly-broad source position information for chained
comparisons used as branching conditions.
@end itemize

@node ライブラリ<79>,Core and Builtins<76>,Core and Builtins<75>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id365}@anchor{1b3b}
@subsubsection ライブラリ



@itemize -

@item 
gh-96821@footnote{https://github.com/python/cpython/issues/96821}: Fix undefined behaviour in @code{audioop.c}.
@end itemize

@node Core and Builtins<76>,ライブラリ<80>,ライブラリ<79>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id366}@anchor{1b3c}
@subsubsection Core and Builtins



@itemize -

@item 
gh-96821@footnote{https://github.com/python/cpython/issues/96821}: Fix undefined behaviour in @code{_testcapimodule.c}.

@item 
gh-95778@footnote{https://github.com/python/cpython/issues/95778}: When @ref{2ec,,ValueError} is raised if an integer is larger than
the limit, mention the @ref{18f1,,sys.set_int_max_str_digits()} function in the
error message. Patch by Victor Stinner.

@item 
gh-96387@footnote{https://github.com/python/cpython/issues/96387}: At Python exit, sometimes a thread holding the GIL can wait
forever for a thread (usually a daemon thread) which requested to drop the
GIL, whereas the thread already exited. To fix the race condition, the
thread which requested the GIL drop now resets its request before exiting.
Issue discovered and analyzed by Mingliang ZHAO. Patch by Victor Stinner.

@item 
gh-96864@footnote{https://github.com/python/cpython/issues/96864}: Fix a possible assertion failure, fatal error, or
@ref{795,,SystemError} if a line tracing event raises an exception while
opcode tracing is enabled.

@item 
gh-95778@footnote{https://github.com/python/cpython/issues/95778}: The @code{PyLong_FromString} function was refactored to make it
more maintainable and extensible.

@item 
gh-96678@footnote{https://github.com/python/cpython/issues/96678}: Fix undefined behaviour in C code of null pointer arithmetic.

@item 
gh-96754@footnote{https://github.com/python/cpython/issues/96754}: Make sure that all frame objects created are created from valid
interpreter frames. Prevents the possibility of invalid frames in
backtraces and signal handlers.

@item 
gh-90997@footnote{https://github.com/python/cpython/issues/90997}: Improve the performance of reading and writing inline bytecode
caches on some platforms.

@item 
gh-96751@footnote{https://github.com/python/cpython/issues/96751}: Remove dead code from @code{CALL_FUNCTION_EX} opcode.

@item 
gh-90751@footnote{https://github.com/python/cpython/issues/90751}: @ref{165,,memoryview} now supports half-floats. Patch by Donghee
Na and Antoine Pitrou.

@item 
gh-96678@footnote{https://github.com/python/cpython/issues/96678}: Fix case of undefined behavior in ceval.c
@end itemize

@node ライブラリ<80>,Core and Builtins<77>,Core and Builtins<76>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id367}@anchor{1b3d}
@subsubsection ライブラリ



@itemize -

@item 
gh-64373@footnote{https://github.com/python/cpython/issues/64373}: Convert @code{_functools} to argument clinic.

@item 
gh-96641@footnote{https://github.com/python/cpython/issues/96641}: Do not expose @code{KeyWrapper} in @code{_functools}.
@end itemize

@node Core and Builtins<77>,ライブラリ<81>,ライブラリ<80>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id368}@anchor{1b3e}
@subsubsection Core and Builtins



@itemize -

@item 
gh-96636@footnote{https://github.com/python/cpython/issues/96636}: Ensure that tracing, @code{sys.setrace()}, is turned on
immediately. In pre-release versions of 3.11, some tracing events might
have been lost when turning on tracing in a @code{__del__} method or
interrupt.

@item 
gh-96572@footnote{https://github.com/python/cpython/issues/96572}: Fix use after free in trace refs build mode. Patch by Kumar
Aditya.

@item 
gh-96611@footnote{https://github.com/python/cpython/issues/96611}: When loading a file with invalid UTF-8 inside a multi-line
string, a correct SyntaxError is emitted.

@item 
gh-96612@footnote{https://github.com/python/cpython/issues/96612}: Make sure that incomplete frames do not show up in tracemalloc
traces.

@item 
gh-90230@footnote{https://github.com/python/cpython/issues/90230}: Fix compiler warnings and test failures when building with
@code{--enable-pystats}.

@item 
gh-96587@footnote{https://github.com/python/cpython/issues/96587}: Correctly raise @code{SyntaxError} on exception groups (
@geindex Python Enhancement Proposals; PEP 654
PEP 654@footnote{https://peps.python.org/pep-0654/})
on python versions prior to 3.11

@item 
gh-96569@footnote{https://github.com/python/cpython/issues/96569}: Remove two cases of undefined behavior, by adding NULL checks.

@item 
gh-96582@footnote{https://github.com/python/cpython/issues/96582}: Fix possible @code{NULL} pointer dereference in
@code{_PyThread_CurrentFrames}. Patch by Kumar Aditya.

@item 
gh-91079@footnote{https://github.com/python/cpython/issues/91079}: Separate Python recursion checking from C recursion checking
which reduces the chance of C stack overflow and allows the recursion
limit to be increased safely.

@item 
gh-93911@footnote{https://github.com/python/cpython/issues/93911}: Fix an issue that could prevent @ref{704,,LOAD_ATTR} from
specializing properly when accessing properties.

@item 
gh-96348@footnote{https://github.com/python/cpython/issues/96348}: Emit a DeprecationWarning when @ref{71c,,throw()},
@ref{71b,,throw()} or @ref{71d,,athrow()} are called with more than
one argument.

@item 
gh-95196@footnote{https://github.com/python/cpython/issues/95196}: Disable incorrect pickling of the C implemented classmethod
descriptors.

@item 
gh-96364@footnote{https://github.com/python/cpython/issues/96364}: Fix text signatures of @code{list.__getitem__} and
@code{dict.__getitem__}.

@item 
gh-96352@footnote{https://github.com/python/cpython/issues/96352}: Fix @ref{5f0,,AttributeError} missing @code{name} and @code{obj}
attributes in @ref{dcb,,object.__getattribute__()}. Patch by Philip Georgi.

@item 
gh-93554@footnote{https://github.com/python/cpython/issues/93554}: Change the jump opcodes so that all conditional jumps are
forward jumps. Backward jumps are converted by the assembler into a
conditional forward jump whose target is the fallthrough block (and with a
reversed condition), followed by an unconditional backward jump. For
example:

@code{POP_JUMP_IF_TRUE BACKWARD_TARGET} becomes @code{POP_JUMP_IF_FALSE
NEXT_BLOCK; JUMP BACKWARD_TARGET}.

All the directed conditional jump opcodes were removed:
@code{POP_JUMP_FORWARD_IF_TRUE}, @code{POP_JUMP_BACKWARD_IF_TRUE},
@code{POP_JUMP_FORWARD_IF_FALSE}, @code{POP_JUMP_BACKWARD_IF_FALSE},
@code{POP_JUMP_FORWARD_IF_NONE}, @code{POP_JUMP_BACKWARD_IF_NONE},
@code{POP_JUMP_FORWARD_IF_NOT_NONE}, @code{POP_JUMP_BACKWARD_IF_NOT_NONE}.

The corresponding opcodes without direction are no longer
pseudo-instructions, and they implement the forward conditional jumps.

@item 
gh-96268@footnote{https://github.com/python/cpython/issues/96268}: Loading a file with invalid UTF-8 will now report the broken
character at the correct location.

@item 
gh-96237@footnote{https://github.com/python/cpython/issues/96237}: The internal field @code{_PyInterpreterFrame.f_func} is renamed to
@code{_PyInterpreterFrame.f_funcobj} and may be any object. The @code{f_globals}
and @code{f_builtin} fields may hold junk values.

It is safest to treat the @code{_PyInterpreterFrame} struct as opaque.

@item 
gh-96187@footnote{https://github.com/python/cpython/issues/96187}: Fixed a bug that caused @code{_PyCode_GetExtra} to return garbage
for negative indexes. Patch by Pablo Galindo

@item 
gh-96143@footnote{https://github.com/python/cpython/issues/96143}: Add a new @code{-X perf} Python command line option as well as
@ref{69a,,sys.activate_stack_trampoline()} and
@ref{69b,,sys.deactivate_stack_trampoline()} function in the @ref{df,,sys} module
that allows to set/unset the interpreter in a way that the Linux @code{perf}
profiler can detect Python calls. The new
@ref{69c,,sys.is_stack_trampoline_active()} function allows to query the state
of the perf trampoline. Design by Pablo Galindo. Patch by Pablo Galindo
and Christian Heimes with contributions from Gregory P. Smith [Google] and
Mark Shannon.

@item 
gh-96071@footnote{https://github.com/python/cpython/issues/96071}: Fix a deadlock in @ref{64a,,PyGILState_Ensure()} when allocating
new thread state. Patch by Kumar Aditya.

@item 
gh-96046@footnote{https://github.com/python/cpython/issues/96046}: @ref{980,,PyType_Ready()} now initializes @code{ht_cached_keys} and
performs additional checks to ensure that type objects are properly
configured. This avoids crashes in 3rd party packages that don't use
regular API to create new types.

@item 
gh-96005@footnote{https://github.com/python/cpython/issues/96005}: On WASI @ref{1b3f,,ENOTCAPABLE} is now mapped to
@ref{f3e,,PermissionError}. The @ref{5b,,errno} modules exposes the new error
number. @code{getpath.py} now ignores @ref{f3e,,PermissionError} when it cannot
open landmark files @code{pybuilddir.txt} and @code{pyenv.cfg}.

@item 
gh-93678@footnote{https://github.com/python/cpython/issues/93678}: Added test a harness for direct unit tests of the compiler's
optimization stage. The @code{_testinternalcapi.optimize_cfg()} function runs
the optimiser on a sequence of instructions. The
@code{CfgOptimizationTestCase} class in @code{test.support} has utilities for
invoking the optimizer and checking the output.

@item 
gh-95245@footnote{https://github.com/python/cpython/issues/95245}: Reduces the size of a "simple" Python object from 8 to 6 words
by moving the weakreflist pointer into the pre-header directly before the
object's dict/values pointer.

@item 
gh-90997@footnote{https://github.com/python/cpython/issues/90997}: Compile virtual @ref{8f8,,try}/@ref{1ab,,except} blocks to
handle exceptions raised during @ref{1793,,close()} or
@ref{71c,,throw()} calls through a suspended frame.

@item 
gh-95977@footnote{https://github.com/python/cpython/issues/95977}: Optimized calling @ref{1701,,__get__()} with vectorcall. Patch
by Kumar Aditya.

@item 
gh-91210@footnote{https://github.com/python/cpython/issues/91210}: Improve error message when a parameter without a default value
follows one with a default value, and show the same message, even when the
non-default/default sequence is preceded by positional-only parameters.

@item 
gh-95922@footnote{https://github.com/python/cpython/issues/95922}: Fixed bug where the compiler's @code{eliminate_empty_basic_blocks}
function ignores the last block of the code unit.

@item 
gh-95818@footnote{https://github.com/python/cpython/issues/95818}: Skip over incomplete frames in @ref{991,,PyThreadState_GetFrame()}.

@item 
gh-95876@footnote{https://github.com/python/cpython/issues/95876}: Fix format string in @code{_PyPegen_raise_error_known_location}
that can lead to memory corruption on some 64bit systems. The function was
building a tuple with @code{i} (int) instead of @code{n} (Py_ssize_t) for
Py_ssize_t arguments.

@item 
gh-95605@footnote{https://github.com/python/cpython/issues/95605}: Fix misleading contents of error message when converting an
all-whitespace string to @ref{196,,float}.

@item 
gh-95150@footnote{https://github.com/python/cpython/issues/95150}: Update code object hashing and equality to consider all
debugging and exception handling tables. This fixes an issue where certain
non-identical code objects could be "deduplicated" during compilation.

@item 
gh-91146@footnote{https://github.com/python/cpython/issues/91146}: Reduce allocation size of @ref{24d,,list} from @ref{10aa,,str.split()}
and @ref{146d,,str.rsplit()}. Patch by Donghee Na and Inada Naoki.

@item 
gh-87092@footnote{https://github.com/python/cpython/issues/87092}: Create a 'jump target label' abstraction in the compiler so that
the compiler's codegen stage does not work directly with basic blocks.
This prepares the code for changes to the underlying CFG generation
mechanism.

@item 
gh-95355@footnote{https://github.com/python/cpython/issues/95355}: @code{_PyPegen_Parser_New} now properly detects token memory
allocation errors. Patch by Honglin Zhu.

@item 
gh-90081@footnote{https://github.com/python/cpython/issues/90081}: Run Python code in tracer/profiler function at full speed. Fixes
slowdown in earlier versions of 3.11.

@item 
gh-95324@footnote{https://github.com/python/cpython/issues/95324}: Emit a warning in debug mode if an object does not call
@ref{171e,,PyObject_GC_UnTrack()} before deallocation. Patch by Pablo Galindo.

@item 
gh-95245@footnote{https://github.com/python/cpython/issues/95245}: Merge managed dict and values pointer into a single tagged
pointer to save one word in the pre-header.

@item 
gh-93678@footnote{https://github.com/python/cpython/issues/93678}: Add cfg_builder struct and refactor the relevant code so that a
cfg can be constructed without an instance of the compiler struct.

@item 
gh-95185@footnote{https://github.com/python/cpython/issues/95185}: Prevented crashes in the AST constructor when compiling some
absurdly long expressions like @code{"+0"*1000000}. @ref{f68,,RecursionError} is
now raised instead. Patch by Pablo Galindo

@item 
gh-93351@footnote{https://github.com/python/cpython/issues/93351}: @ref{4c3,,ast.AST} node positions are now validated when provided
to @ref{4b1,,compile()} and other related functions. If invalid positions are
detected, a @ref{2ec,,ValueError} will be raised.

@item 
gh-94438@footnote{https://github.com/python/cpython/issues/94438}: Fix an issue that caused extended opcode arguments and some
conditional pops to be ignored when calculating valid jump targets for
assignments to the @code{f_lineno} attribute of frame objects. In some cases,
this could cause inconsistent internal state, resulting in a hard crash of
the interpreter.

@item 
gh-95060@footnote{https://github.com/python/cpython/issues/95060}: Undocumented @code{PyCode_Addr2Location} function now properly
returns when @code{addrq} argument is less than zero.

@item 
gh-95113@footnote{https://github.com/python/cpython/issues/95113}: Replace all @code{EXTENDED_ARG_QUICK} instructions with basic
@ref{1b1e,,EXTENDED_ARG} instructions in unquickened code. Consumers of
non-adaptive bytecode should be able to handle extended arguments the same
way they were handled in CPython 3.10 and older.

@item 
gh-91409@footnote{https://github.com/python/cpython/issues/91409}: Fix incorrect source location info caused by certain
optimizations in the bytecode compiler.
@end itemize

@node ライブラリ<81>,Core and Builtins<78>,Core and Builtins<77>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id369}@anchor{1b40}
@subsubsection ライブラリ



@itemize -

@item 
gh-95023@footnote{https://github.com/python/cpython/issues/95023}: Implement @ref{1b41,,os.setns()} and  @ref{1b42,,os.unshare()} for Linux.
Patch by Noam Cohen.
@end itemize

@node Core and Builtins<78>,ライブラリ<82>,ライブラリ<81>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id370}@anchor{1b43}
@subsubsection Core and Builtins



@itemize -

@item 
gh-94036@footnote{https://github.com/python/cpython/issues/94036}: Fix incorrect source location info for some multi-line attribute
accesses and method calls.

@item 
gh-94938@footnote{https://github.com/python/cpython/issues/94938}: Fix error detection in some builtin functions when keyword
argument name is an instance of a str subclass with overloaded @code{__eq__}
and @code{__hash__}. Previously it could cause SystemError or other undesired
behavior.
@end itemize

@node ライブラリ<82>,Core and Builtins<79>,Core and Builtins<78>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id371}@anchor{1b44}
@subsubsection ライブラリ



@itemize -

@item 
gh-94996@footnote{https://github.com/python/cpython/issues/94996}: @ref{1c2,,ast.parse()} will no longer parse function definitions with
positional-only params when passed @code{feature_version} less than @code{(3,
8)}. Patch by Shantanu Jain.
@end itemize

@node Core and Builtins<79>,ライブラリ<83>,ライブラリ<82>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id372}@anchor{1b45}
@subsubsection Core and Builtins



@itemize -

@item 
gh-94739@footnote{https://github.com/python/cpython/issues/94739}: Allow jumping within, out of, and across exception handlers in
the debugger.
@end itemize

@node ライブラリ<83>,Core and Builtins<80>,Core and Builtins<79>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id373}@anchor{1b46}
@subsubsection ライブラリ



@itemize -

@item 
gh-94949@footnote{https://github.com/python/cpython/issues/94949}: @ref{1c2,,ast.parse()} will no longer parse parenthesized context
managers when passed @code{feature_version} less than @code{(3, 9)}. Patch by
Shantanu Jain.

@item 
gh-94947@footnote{https://github.com/python/cpython/issues/94947}: @ref{1c2,,ast.parse()} will no longer parse assignment expressions
when passed @code{feature_version} less than @code{(3, 8)}. Patch by Shantanu
Jain.
@end itemize

@node Core and Builtins<80>,ライブラリ<84>,ライブラリ<83>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id374}@anchor{1b47}
@subsubsection Core and Builtins



@itemize -

@item 
gh-91256@footnote{https://github.com/python/cpython/issues/91256}: Ensures the program name is known for help text during
interpreter startup.

@item 
gh-94869@footnote{https://github.com/python/cpython/issues/94869}: Fix the column offsets for some expressions in multi-line
f-strings @ref{9,,ast} nodes. Patch by Pablo Galindo.

@item 
gh-94893@footnote{https://github.com/python/cpython/issues/94893}: Fix an issue where frame object manipulations could corrupt
inline bytecode caches.

@item 
gh-94822@footnote{https://github.com/python/cpython/issues/94822}: Fix an issue where lookups of metaclass descriptors may be
ignored when an identically-named attribute also exists on the class
itself.

@item 
gh-91153@footnote{https://github.com/python/cpython/issues/91153}: Fix an issue where a @ref{344,,bytearray} item assignment could
crash if it's resized by the new value's @code{__index__()} method.

@item 
gh-90699@footnote{https://github.com/python/cpython/issues/90699}: Fix reference counting bug in @code{bool.__repr__()}. Patch by
Kumar Aditya.

@item 
gh-94694@footnote{https://github.com/python/cpython/issues/94694}: Fix an issue that could cause code with multi-line method
lookups to have misleading or incorrect column offset information. In some
cases (when compiling a hand-built AST) this could have resulted in a hard
crash of the interpreter.

@item 
gh-93252@footnote{https://github.com/python/cpython/issues/93252}: Fix an issue that caused internal frames to outlive failed
Python function calls, possibly resulting in memory leaks or hard
interpreter crashes.

@item 
gh-94215@footnote{https://github.com/python/cpython/issues/94215}: Fix an issue where exceptions raised by line-tracing events
would cause frames to be left in an invalid state, possibly resulting in a
hard crash of the interpreter.

@item 
gh-92228@footnote{https://github.com/python/cpython/issues/92228}: Disable the compiler's inline-small-exit-blocks optimization for
exit blocks that are associated with source code lines. This fixes a bug
where the debugger cannot tell where an exception handler ends and the
following code block begins.

@item 
gh-94485@footnote{https://github.com/python/cpython/issues/94485}: Line number of a module's @code{RESUME} instruction is set to 0 as
specified in 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/}.

@item 
gh-94438@footnote{https://github.com/python/cpython/issues/94438}: Account for instructions that can push NULL to the stack when
setting line number in a frame. Prevents some (unlikely) crashes.

@item 
gh-91719@footnote{https://github.com/python/cpython/issues/91719}: Reload @code{opcode} when raising @code{unknown opcode error} in the
interpreter main loop, for C compilers to generate dispatching code
independently.

@item 
gh-94329@footnote{https://github.com/python/cpython/issues/94329}: Compile and run code with unpacking of extremely large sequences
(1000s of elements). Such code failed to compile. It now compiles and runs
correctly.

@item 
gh-94360@footnote{https://github.com/python/cpython/issues/94360}: Fixed a tokenizer crash when reading encoded files with syntax
errors from @code{stdin} with non utf-8 encoded text. Patch by Pablo Galindo

@item 
gh-88116@footnote{https://github.com/python/cpython/issues/88116}: Fix an issue when reading line numbers from code objects if the
encoded line numbers are close to @code{INT_MIN}. Patch by Pablo Galindo

@item 
gh-94262@footnote{https://github.com/python/cpython/issues/94262}: Don't create frame objects for incomplete frames. Prevents the
creation of generators and closures from being observable to Python and C
extensions, restoring the behavior of 3.10 and earlier.

@item 
gh-94192@footnote{https://github.com/python/cpython/issues/94192}: Fix error for dictionary literals with invalid expression as
value.

@item 
gh-87995@footnote{https://github.com/python/cpython/issues/87995}: @ref{698,,types.MappingProxyType} instances are now hashable if
the underlying mapping is hashable.

@item 
gh-93883@footnote{https://github.com/python/cpython/issues/93883}: Revise the display strategy of traceback enhanced error
locations.  The indicators are only shown when the location doesn't span
the whole line.

@item 
gh-94163@footnote{https://github.com/python/cpython/issues/94163}: Add @ref{705,,BINARY_SLICE} and @ref{706,,STORE_SLICE}
instructions for more efficient handling and better specialization of
slicing operations, where the slice is explicit in the source code.

@item 
gh-94021@footnote{https://github.com/python/cpython/issues/94021}: Fix unreachable code warning in @code{Python/specialize.c}.

@item 
gh-93911@footnote{https://github.com/python/cpython/issues/93911}: Specialize @code{LOAD_ATTR} for objects with custom
@code{__getattribute__}.

@item 
gh-93955@footnote{https://github.com/python/cpython/issues/93955}: Improve performance of attribute lookups on objects with custom
@code{__getattribute__} and @code{__getattr__}. Patch by Ken Jin.

@item 
gh-93911@footnote{https://github.com/python/cpython/issues/93911}: Specialize @code{LOAD_ATTR} for @code{property()} attributes.

@item 
gh-93678@footnote{https://github.com/python/cpython/issues/93678}: Refactor compiler optimisation code so that it no longer needs
the @code{struct assembler} and @code{struct compiler} passed around. Instead,
each function takes the CFG and other data that it actually needs. This
will make it possible to test this code directly.

@item 
gh-93841@footnote{https://github.com/python/cpython/issues/93841}: When built with @code{-enable-pystats}, @code{sys._stats_on()},
@code{sys._stats_off()}, @code{sys._stats_clear()} and @code{sys._stats_dump()}
functions have been added to enable gathering stats for parts of programs.

@item 
gh-93516@footnote{https://github.com/python/cpython/issues/93516}: Store offset of first traceable instruction in code object to
avoid having to recompute it for each instruction when tracing.

@item 
gh-93516@footnote{https://github.com/python/cpython/issues/93516}: Lazily create a table mapping bytecode offsets to line numbers
to speed up calculation of line numbers when tracing.

@item 
gh-89828@footnote{https://github.com/python/cpython/issues/89828}: @ref{9ec,,types.GenericAlias} no longer relays the @code{__class__}
attribute. For example, @code{isinstance(list[int], type)} no longer returns
@code{True}.

@item 
gh-93678@footnote{https://github.com/python/cpython/issues/93678}: Refactor the compiler to reduce boilerplate and repetition.

@item 
gh-93671@footnote{https://github.com/python/cpython/issues/93671}: Fix some exponential backtrace case happening with deeply nested
sequence patterns in match statements. Patch by Pablo Galindo

@item 
gh-93662@footnote{https://github.com/python/cpython/issues/93662}: Make sure that the end column offsets are correct in multi-line
method calls. Previously, the end column could precede the column offset.
@end itemize

@node ライブラリ<84>,Core and Builtins<81>,Core and Builtins<80>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id375}@anchor{1b48}
@subsubsection ライブラリ



@itemize -

@item 
gh-93461@footnote{https://github.com/python/cpython/issues/93461}: @ref{e0a,,importlib.invalidate_caches()} now drops entries from
@ref{7fa,,sys.path_importer_cache} with a relative path as name. This solves
a caching issue when a process changes its current working directory.

@code{FileFinder} no longer inserts a dot in the path, e.g. @code{/egg/./spam}
is now @code{/egg/spam}.
@end itemize

@node Core and Builtins<81>,ライブラリ<85>,ライブラリ<84>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id376}@anchor{1b49}
@subsubsection Core and Builtins



@itemize -

@item 
gh-93621@footnote{https://github.com/python/cpython/issues/93621}: Change order of bytecode instructions emitted for
@ref{186,,with} and @ref{185,,async with} to reduce the number of entries
in the exception table.

@item 
gh-93533@footnote{https://github.com/python/cpython/issues/93533}: Reduce the size of the inline cache for @code{LOAD_METHOD} by 2
bytes.

@item 
gh-93444@footnote{https://github.com/python/cpython/issues/93444}: Removed redundant fields from the compiler's basicblock struct:
@code{b_nofallthrough}, @code{b_exit}, @code{b_return}. They can be easily
calculated from the opcode of the last instruction of the block.

@item 
gh-93429@footnote{https://github.com/python/cpython/issues/93429}: @code{LOAD_METHOD} instruction has been removed. It was merged back
into @code{LOAD_ATTR}.

@item 
gh-93418@footnote{https://github.com/python/cpython/issues/93418}: Fixed an assert where an f-string has an equal sign '='
following an expression, but there's no trailing brace. For example,
f"@{i=".

@item 
gh-93382@footnote{https://github.com/python/cpython/issues/93382}: Cache the result of @ref{97c,,PyCode_GetCode()} function to restore
the `O'(1) lookup of the @code{co_code} attribute.

@item 
gh-93359@footnote{https://github.com/python/cpython/issues/93359}: Ensure that custom @ref{9,,ast} nodes without explicit end
positions can be compiled. Patch by Pablo Galindo.

@item 
gh-93356@footnote{https://github.com/python/cpython/issues/93356}: Code for exception handlers is emitted at the end of the code
unit's bytecode. This avoids one jump when no exception is raised.

@item 
gh-93354@footnote{https://github.com/python/cpython/issues/93354}: Use exponential backoff for specialization counters in the
interpreter. Can reduce the number of failed specializations significantly
and avoid slowdown for those parts of a program that are not suitable for
specialization.

@item 
gh-93283@footnote{https://github.com/python/cpython/issues/93283}: Improve error message for invalid syntax of conversion character
in f-string expressions.

@item 
gh-93345@footnote{https://github.com/python/cpython/issues/93345}: Fix a crash in substitution of a @code{TypeVar} in nested generic
alias after @code{TypeVarTuple}.

@item 
gh-93223@footnote{https://github.com/python/cpython/issues/93223}: When a bytecode instruction jumps to an unconditional jump
instruction, the first instruction can often be optimized to target the
unconditional jump's target directly. For tracing reasons, this would
previously only occur if both instructions have the same line number. This
also now occurs if the unconditional jump is artificial, i.e., if it has
no associated line number.

@item 
gh-84694@footnote{https://github.com/python/cpython/issues/84694}: The @code{--experimental-isolated-subinterpreters} configure option
and @code{EXPERIMENTAL_ISOLATED_SUBINTERPRETERS} macro have been removed.

@item 
gh-91924@footnote{https://github.com/python/cpython/issues/91924}: Fix @code{__lltrace__} debug feature if the stdout encoding is not
UTF-8. Patch by Victor Stinner.

@item 
gh-93040@footnote{https://github.com/python/cpython/issues/93040}: Wraps unused parameters in @code{Objects/obmalloc.c} with
@code{Py_UNUSED}.

@item 
gh-93143@footnote{https://github.com/python/cpython/issues/93143}: Avoid @code{NULL} checks for uninitialized local variables by
determining at compile time which variables must be initialized.

@item 
gh-93061@footnote{https://github.com/python/cpython/issues/93061}: Backward jumps after @code{async for} loops are no longer given
dubious line numbers.

@item 
gh-93065@footnote{https://github.com/python/cpython/issues/93065}: Fix contextvars HAMT implementation to handle iteration over
deep trees.

The bug was discovered and fixed by Eli Libman. See
MagicStack/immutables#84@footnote{https://github.com/MagicStack/immutables/issues/84} for more details.

@item 
gh-93012@footnote{https://github.com/python/cpython/issues/93012}: Added the new function @ref{772,,PyType_FromMetaclass()}, which
generalizes the existing @ref{773,,PyType_FromModuleAndSpec()} using an
additional metaclass argument. This is useful for language binding tools,
where it can be used to intercept type-related operations like subclassing
or static attribute access by specifying a metaclass with custom slots.

Importantly, @ref{772,,PyType_FromMetaclass()} is available in the Limited
API, which provides a path towards migrating more binding tools onto the
Stable ABI.

@item 
gh-93021@footnote{https://github.com/python/cpython/issues/93021}: Fix the @code{__text_signature__} for @code{__get__()} methods
implemented in C. Patch by Jelle Zijlstra.

@item 
gh-89914@footnote{https://github.com/python/cpython/issues/89914}: The operand of the @code{YIELD_VALUE} instruction is set to the
stack depth. This is done to help frame handling on @code{yield} and may
assist debuggers.

@item 
gh-92955@footnote{https://github.com/python/cpython/issues/92955}: Fix memory leak in code object's lines and positions iterators
as they were not finalized at exit. Patch by Kumar Aditya.

@item 
gh-92930@footnote{https://github.com/python/cpython/issues/92930}: Fixed a crash in @code{_pickle.c} from mutating collections during
@code{__reduce__} or @code{persistent_id}.

@item 
gh-90690@footnote{https://github.com/python/cpython/issues/90690}: The PRECALL instruction has been removed. It offered only a
small advantage for specialization and is not needed in the vast majority
of cases.

@item 
gh-92914@footnote{https://github.com/python/cpython/issues/92914}: Always round the allocated size for lists up to the nearest even
number.

@item 
gh-92858@footnote{https://github.com/python/cpython/issues/92858}: Improve error message for some suites with syntax error before
':'

@item 
gh-90473@footnote{https://github.com/python/cpython/issues/90473}: Decrease default recursion limit on WASI to address limited call
stack size.

@item 
gh-92804@footnote{https://github.com/python/cpython/issues/92804}: Fix memory leak in @code{memoryview} iterator as it was not
finalized at exit. Patch by Kumar Aditya.

@item 
gh-92777@footnote{https://github.com/python/cpython/issues/92777}: Specialize @code{LOAD_METHOD} for objects with lazy dictionaries.
Patch by Ken Jin.

@item 
gh-92658@footnote{https://github.com/python/cpython/issues/92658}: Add support for connecting and binding to Hyper-V sockets on
Windows Hyper-V hosts and guests.

@item 
gh-92236@footnote{https://github.com/python/cpython/issues/92236}: Remove spurious "LINE" event when starting a generator or
coroutine, visible tracing functions implemented in C.
@end itemize

@node ライブラリ<85>,Core and Builtins<82>,Core and Builtins<81>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id377}@anchor{1b4a}
@subsubsection ライブラリ



@itemize -

@item 
gh-91102@footnote{https://github.com/python/cpython/issues/91102}: @code{_warnings.warn_explicit()} is ported to Argument Clinic.
@end itemize

@node Core and Builtins<82>,ライブラリ<86>,ライブラリ<85>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id378}@anchor{1b4b}
@subsubsection Core and Builtins



@itemize -

@item 
gh-92619@footnote{https://github.com/python/cpython/issues/92619}: Make the compiler duplicate an exit block only if none of its
instructions have a lineno (previously only the first instruction in the
block was checked, leading to unnecessarily duplicated blocks).

@item 
gh-88750@footnote{https://github.com/python/cpython/issues/88750}: The deprecated debug build only @code{PYTHONTHREADDEBUG}
environment variable no longer does anything.
@end itemize

@node ライブラリ<86>,Core and Builtins<83>,Core and Builtins<82>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id379}@anchor{1b4c}
@subsubsection ライブラリ



@itemize -

@item 
gh-92261@footnote{https://github.com/python/cpython/issues/92261}: Fix hang when trying to iterate over a @code{typing.Union}.
@end itemize

@node Core and Builtins<83>,ライブラリ<87>,ライブラリ<86>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id380}@anchor{1b4d}
@subsubsection Core and Builtins



@itemize -

@item 
gh-91432@footnote{https://github.com/python/cpython/issues/91432}: Specialized the @ref{1ac2,,FOR_ITER} opcode using the PEP 659
machinery

@item 
gh-91399@footnote{https://github.com/python/cpython/issues/91399}: Removed duplicate '@{0, 0, 0, 0, 0, 0@}' entry in
'Objects/unicodetype_db.h'.

@item 
gh-91578@footnote{https://github.com/python/cpython/issues/91578}: Updates the error message for abstract class.

@item 
bpo-47091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47091}: Improve performance of repetition of @ref{24d,,list} and
@ref{614,,tuple} by using @code{memcpy} to copy data and performing the
reference increments in one step.

@item 
bpo-46142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46142}: Make @code{--help} output shorter by moving some info to the new
@code{--help-env} and @code{--help-xoptions} command-line options. Also add
@code{--help-all} option to print complete usage.

@item 
bpo-42316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42316}: Document some places where an assignment expression needs
parentheses.
@end itemize

@node ライブラリ<87>,ドキュメント<28>,Core and Builtins<83>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id381}@anchor{1b4e}
@subsubsection ライブラリ



@itemize -

@item 
gh-89237@footnote{https://github.com/python/cpython/issues/89237}: Fix hang on Windows in @code{subprocess.wait_closed()} in
@ref{b,,asyncio} with @ref{81d,,ProactorEventLoop}. Patch by Kumar
Aditya.

@item 
gh-97928@footnote{https://github.com/python/cpython/issues/97928}: @code{tkinter.Text.count()} raises now an exception for options
starting with "-" instead of silently ignoring them.

@item 
gh-98393@footnote{https://github.com/python/cpython/issues/98393}: The @ref{a5,,os} module no longer accepts bytes-like paths, like
@ref{344,,bytearray} and @ref{165,,memoryview} types: only the exact
@ref{192,,bytes} type is accepted for bytes strings. Patch by Victor
Stinner.

@item 
gh-98363@footnote{https://github.com/python/cpython/issues/98363}: Added itertools.batched() to batch data into lists of a given
length with the last list possibly being shorter than the others.

@item 
gh-98331@footnote{https://github.com/python/cpython/issues/98331}: Update the bundled copies of pip and setuptools to versions 22.3
and 65.5.0 respectively.

@item 
gh-98307@footnote{https://github.com/python/cpython/issues/98307}: A @ref{86b,,createSocket()} method
was added to @ref{86c,,SysLogHandler}.

@item 
gh-96035@footnote{https://github.com/python/cpython/issues/96035}: Fix bug in @ref{362,,urllib.parse.urlparse()} that causes certain
port numbers containing whitespace, underscores, plus and minus signs, or
non-ASCII digits to be incorrectly accepted.

@item 
gh-98257@footnote{https://github.com/python/cpython/issues/98257}: Make @ref{1717,,sys.setprofile()} and @ref{2e1,,sys.settrace()} functions
reentrant. They can no long fail with: @code{RuntimeError("Cannot install a
trace function while another trace function is being installed")}. Patch
by Victor Stinner.

@item 
gh-98251@footnote{https://github.com/python/cpython/issues/98251}: Allow @ref{117,,venv} to pass along @code{PYTHON*} variables to
@code{ensurepip} and @code{pip} when they do not impact path resolution

@item 
gh-94597@footnote{https://github.com/python/cpython/issues/94597}: Deprecated
@code{asyncio.AbstractEventLoopPolicy.get_child_watcher()} and
@code{asyncio.AbstractEventLoopPolicy.set_child_watcher()} methods to be
removed in Python 3.14. Patch by Kumar Aditya.

@item 
gh-98178@footnote{https://github.com/python/cpython/issues/98178}: On macOS, fix a crash in @ref{762,,syslog.syslog()} in multi-threaded
applications. On macOS, the libc @code{syslog()} function is not thread-safe,
so @ref{762,,syslog.syslog()} no longer releases the GIL to call it. Patch by
Victor Stinner.

@item 
gh-44098@footnote{https://github.com/python/cpython/issues/44098}: Release the GIL when creating @ref{519,,mmap.mmap} objects on
Unix.

@item 
gh-87730@footnote{https://github.com/python/cpython/issues/87730}: Wrap network errors consistently in urllib FTP support, so the
test suite doesn't fail when a network is available but the public
internet is not reachable.

@item 
gh-94597@footnote{https://github.com/python/cpython/issues/94597}: The child watcher classes
@code{MultiLoopChildWatcher},
@code{FastChildWatcher} and @code{SafeChildWatcher}
are deprecated and will be removed in Python 3.14. Patch by Kumar Aditya.

@item 
gh-98023@footnote{https://github.com/python/cpython/issues/98023}: Change default child watcher to
@code{PidfdChildWatcher} on Linux systems which supports it.
Patch by Kumar Aditya.

@item 
gh-90985@footnote{https://github.com/python/cpython/issues/90985}: Earlier in 3.11 we deprecated
@code{asyncio.Task.cancel("message")}. We realized we were too harsh, and
have undeprecated it.

@item 
gh-65961@footnote{https://github.com/python/cpython/issues/65961}: Do not rely solely on @code{__cached__} on modules; code will also
support @code{__spec__.cached}.

@item 
gh-97646@footnote{https://github.com/python/cpython/issues/97646}: Replace deprecated @code{application/javascript} with
@code{text/javascript} in @ref{93,,mimetypes}. See 
@geindex RFC; RFC 9239
RFC 9239@footnote{https://datatracker.ietf.org/doc/html/rfc9239.html}. Patch by Noam
Cohen.

@item 
gh-97930@footnote{https://github.com/python/cpython/issues/97930}: Apply changes from importlib_resources 5.8 and 5.9:
@code{Traversable.joinpath} provides a concrete implementation. @code{as_file}
now supports directories of resources.

@item 
gh-97850@footnote{https://github.com/python/cpython/issues/97850}: Remove deprecated @code{importlib.util.set_loader()} and
@code{importlib.util.module_for_loader()} from @ref{81,,importlib.util}.

@item 
gh-97837@footnote{https://github.com/python/cpython/issues/97837}: Change deprecate warning message in @ref{10c,,unittest} from

@code{It is deprecated to return a value!=None}

to

@code{It is deprecated to return a value that is not None from a test case}

@item 
gh-97825@footnote{https://github.com/python/cpython/issues/97825}: Fixes @ref{5f0,,AttributeError} when @ref{11c4,,subprocess.check_output()}
is used with argument @code{input=None} and either of the arguments
`encoding' or `errors' are used.

@item 
gh-97008@footnote{https://github.com/python/cpython/issues/97008}: @ref{452,,NameError} and @ref{5f0,,AttributeError} spelling suggestions
provided since gh-82711@footnote{https://github.com/python/cpython/issues/82711} are now also emitted by the pure Python
@ref{104,,traceback} module. Tests for those suggestions now exercise both
implementations to ensure they are equivalent. Patch by Carl Friedrich
Bolz-Tereick and Łukasz Langa.

@item 
gh-97799@footnote{https://github.com/python/cpython/issues/97799}: @code{dataclass} now uses @ref{a14,,inspect.get_annotations()} to
examine the annotations on class objects.

@item 
gh-97781@footnote{https://github.com/python/cpython/issues/97781}: Removed deprecated interfaces in @code{importlib.metadata} (entry
points accessed as dictionary, implicit dictionary construction of
sequence of @code{EntryPoint} objects, mutablility of @code{EntryPoints} result,
access of entry point by index). @code{entry_points} now has a simpler, more
straightforward API (returning @code{EntryPoints}).

@item 
gh-96827@footnote{https://github.com/python/cpython/issues/96827}: Avoid spurious tracebacks from @ref{b,,asyncio} when default
executor cleanup is delayed until after the event loop is closed (e.g. as
the result of a keyboard interrupt).

@item 
gh-95534@footnote{https://github.com/python/cpython/issues/95534}: @code{gzip.GzipFile.read()} reads 10% faster.

@item 
gh-97592@footnote{https://github.com/python/cpython/issues/97592}: Avoid a crash in the C version of
@ref{1911,,asyncio.Future.remove_done_callback()} when an evil argument is
passed.

@item 
gh-97639@footnote{https://github.com/python/cpython/issues/97639}: Remove @code{tokenize.NL} check from @ref{e3,,tabnanny}.

@item 
gh-97545@footnote{https://github.com/python/cpython/issues/97545}: Make Semaphore run faster.

@item 
gh-73588@footnote{https://github.com/python/cpython/issues/73588}: Fix generation of the default name of
@code{tkinter.Checkbutton}. Previously, checkbuttons in different parent
widgets could have the same short name and share the same state if
arguments "name" and "variable" are not specified. Now they are globally
unique.

@item 
gh-96865@footnote{https://github.com/python/cpython/issues/96865}: fix Flag to use boundary CONFORM

This restores previous Flag behavior of allowing flags with non-sequential
values to be combined; e.g.

class Skip(Flag):         TWO = 2         EIGHT = 8

Skip.TWO | Skip.EIGHT -> <Skip.TWO|EIGHT: 10>

@item 
gh-97005@footnote{https://github.com/python/cpython/issues/97005}: Update bundled libexpat to 2.4.9

@item 
gh-85760@footnote{https://github.com/python/cpython/issues/85760}: Fix race condition in @ref{b,,asyncio} where
@ref{1b4f,,process_exited()} called before the
@ref{1b50,,pipe_data_received()} leading to
inconsistent output. Patch by Kumar Aditya.

@item 
gh-96704@footnote{https://github.com/python/cpython/issues/96704}: Pass the correct @code{contextvars.Context} when a @code{asyncio}
exception handler is called on behalf of a task or callback handle. This
adds a new @code{Task} method, @code{get_context}, and also a new @code{Handle}
method with the same name. If this method is not found on a task object
(perhaps because it is a third-party library that does not yet provide
this method), the context prevailing at the time the exception handler is
called is used.

@item 
gh-96819@footnote{https://github.com/python/cpython/issues/96819}: Fixed check in @code{multiprocessing.resource_tracker} that
guarantees that the length of a write to a pipe is not greater than
@code{PIPE_BUF}.

@item 
gh-95865@footnote{https://github.com/python/cpython/issues/95865}: Reduce @ref{1b51,,urllib.parse.quote_from_bytes()} memory use on large
values.

Contributed by Dennis Sweeney.

@item 
gh-96741@footnote{https://github.com/python/cpython/issues/96741}: Corrected type annotation for dataclass attribute
@code{pstats.FunctionProfile.ncalls} to be @code{str}.

@item 
gh-96734@footnote{https://github.com/python/cpython/issues/96734}: Update @ref{10b,,unicodedata} database to Unicode 15.0.0.

@item 
gh-96735@footnote{https://github.com/python/cpython/issues/96735}: Fix undefined behaviour in @ref{185a,,struct.unpack()}.

@item 
gh-46412@footnote{https://github.com/python/cpython/issues/46412}: Improve performance of @code{bool(db)} for large ndb/gdb databases.
Previously this would call @code{len(db)} which would iterate over all keys
-- the answer (empty or not) is known after the first key.

@item 
gh-96652@footnote{https://github.com/python/cpython/issues/96652}: Fix the faulthandler implementation of
@code{faulthandler.register(signal, chain=True)} if the @code{sigaction()}
function is not available: don't call the previous signal handler if it's
NULL. Patch by Victor Stinner.

@item 
gh-68163@footnote{https://github.com/python/cpython/issues/68163}: Correct conversion of @ref{14d6,,numbers.Rational}'s to
@ref{196,,float}.

@item 
gh-96538@footnote{https://github.com/python/cpython/issues/96538}: Speed up @code{bisect.bisect()} functions by taking advantage of
type-stability.

@item 
gh-96465@footnote{https://github.com/python/cpython/issues/96465}: Fraction hashes are now cached.

@item 
gh-96079@footnote{https://github.com/python/cpython/issues/96079}: In @ref{10a,,typing}, fix missing field @code{name} and incorrect
@code{__module__} in _AnnotatedAlias.

@item 
gh-96415@footnote{https://github.com/python/cpython/issues/96415}: Remove @code{types._cell_factory} from module namespace.

@item 
gh-95987@footnote{https://github.com/python/cpython/issues/95987}: Fix @code{repr} of @code{Any} subclasses.

@item 
gh-96388@footnote{https://github.com/python/cpython/issues/96388}: Work around missing socket functions in
@ref{fa1,,socket}'s @code{__repr__}.

@item 
gh-96385@footnote{https://github.com/python/cpython/issues/96385}: Fix @code{TypeVarTuple.__typing_prepare_subst__}. @code{TypeError} was
not raised when using more than one @code{TypeVarTuple}, like @code{[*T, *V]} in
type alias substitutions.

@item 
gh-96142@footnote{https://github.com/python/cpython/issues/96142}: Add @code{match_args}, @code{kw_only}, @code{slots}, and @code{weakref_slot}
to @code{_DataclassParams}.

@item 
gh-96073@footnote{https://github.com/python/cpython/issues/96073}: In @ref{82,,inspect}, fix overeager replacement of "@code{typing.}" in
formatting annotations.

@item 
gh-89258@footnote{https://github.com/python/cpython/issues/89258}: Added a @ref{1b52,,getChildren()} method to
@ref{d46,,logging.Logger}, to get the immediate child loggers of a logger.

@item 
gh-96346@footnote{https://github.com/python/cpython/issues/96346}: Use double caching for compiled RE patterns.

@item 
gh-96349@footnote{https://github.com/python/cpython/issues/96349}: Fixed a minor performance regression in
@code{threading.Event.__init__()}

@item 
gh-90467@footnote{https://github.com/python/cpython/issues/90467}: Fix @code{asyncio.streams.StreamReaderProtocol} to keep a
strong reference to the created task, so that it's not garbage collected

@item 
gh-96172@footnote{https://github.com/python/cpython/issues/96172}: Fix a bug in @code{unicodedata}: @code{east_asian_width} used to
return the wrong value for unassigned characters; and for yet unassigned,
but reserved characters.

@item 
gh-96159@footnote{https://github.com/python/cpython/issues/96159}: Fix a performance regression in logging
TimedRotatingFileHandler. Only check for special files when the rollover
time has passed.

@item 
gh-96175@footnote{https://github.com/python/cpython/issues/96175}: Fix unused @code{localName} parameter in the @code{Attr} class in
@ref{128,,xml.dom.minidom}.

@item 
gh-96145@footnote{https://github.com/python/cpython/issues/96145}: Add AttrDict to JSON module for use with object_hook.

@item 
gh-96052@footnote{https://github.com/python/cpython/issues/96052}: Fix handling compiler warnings (SyntaxWarning and
DeprecationWarning) in @ref{1b53,,codeop.compile_command()} when checking for
incomplete input. Previously it emitted warnings and raised a SyntaxError.
Now it always returns @code{None} for incomplete input without emitting any
warnings.

@item 
gh-96125@footnote{https://github.com/python/cpython/issues/96125}: Fix incorrect condition that causes @code{sys.thread_info.name} to
be wrong on pthread platforms.

@item 
gh-96019@footnote{https://github.com/python/cpython/issues/96019}: Fix a bug in the @code{makeunicodedata.py} script leading to about
13 KiB of space saving in the @code{unicodedata} module, specifically the
character decomposition data.

@item 
gh-95463@footnote{https://github.com/python/cpython/issues/95463}: Remove an incompatible change from bpo-28080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28080} that caused a
regression that ignored the utf8 in @code{ZipInfo.flag_bits}. Patch by Pablo
Galindo.

@item 
gh-69142@footnote{https://github.com/python/cpython/issues/69142}: Add @code{%:z} strftime format code (generates tzoffset with colons
as separator), see @ref{1b54,,strftime() and strptime() behavior}.

@item 
gh-95899@footnote{https://github.com/python/cpython/issues/95899}: Fix @ref{2f5,,asyncio.Runner} to call
@ref{1b55,,asyncio.set_event_loop()} only once to avoid calling
@code{attach_loop()} multiple times on child
watchers. Patch by Kumar Aditya.

@item 
gh-95736@footnote{https://github.com/python/cpython/issues/95736}: Fix @ref{361,,unittest.IsolatedAsyncioTestCase} to set event loop
before calling setup functions. Patch by Kumar Aditya.

@item 
gh-95865@footnote{https://github.com/python/cpython/issues/95865}: Speed up @ref{1b51,,urllib.parse.quote_from_bytes()} by replacing a
list comprehension with @code{map()}.

@item 
gh-95861@footnote{https://github.com/python/cpython/issues/95861}: Add support for computing Spearman's correlation coefficient to
the existing statistics.correlation() function.

@item 
gh-95804@footnote{https://github.com/python/cpython/issues/95804}: Fix @code{logging} shutdown handler so it respects
@code{MemoryHandler.flushOnClose}.

@item 
gh-95704@footnote{https://github.com/python/cpython/issues/95704}: When a task catches @ref{4d4,,asyncio.CancelledError} and raises
some other error, the other error should generally not silently be
suppressed.

@item 
gh-95149@footnote{https://github.com/python/cpython/issues/95149}: The @ref{afc,,HTTPStatus} enum offers a couple
of properties to indicate the HTTP status category e.g.
@code{HTTPStatus.OK.is_success}.

@item 
gh-95609@footnote{https://github.com/python/cpython/issues/95609}: Update bundled pip to 22.2.2.

@item 
gh-95289@footnote{https://github.com/python/cpython/issues/95289}: Fix @ref{4d1,,asyncio.TaskGroup} to propagate exception when
@ref{4d4,,asyncio.CancelledError} was replaced with another exception by a
context manager. Patch by Kumar Aditya and Guido van Rossum.

@item 
gh-94909@footnote{https://github.com/python/cpython/issues/94909}: Fix incorrect joining of relative Windows paths with drives in
@ref{6cd,,pathlib.PurePath} initializer.

@item 
gh-95385@footnote{https://github.com/python/cpython/issues/95385}: Faster @code{json.dumps()} when sorting of keys is not requested
(default).

@item 
gh-83901@footnote{https://github.com/python/cpython/issues/83901}: Improve @ref{1892,,Signature.bind} error
message for missing keyword-only arguments.

@item 
gh-95339@footnote{https://github.com/python/cpython/issues/95339}: Update bundled pip to 22.2.1.

@item 
gh-95045@footnote{https://github.com/python/cpython/issues/95045}: Fix GC crash when deallocating @code{_lsprof.Profiler} by
untracking it before calling any callbacks. Patch by Kumar Aditya.

@item 
gh-95231@footnote{https://github.com/python/cpython/issues/95231}: Fail gracefully if @ref{1b56,,EPERM} or
@ref{1b57,,ENOSYS} is raised when loading @code{crypt} methods. This
may happen when trying to load @code{MD5} on a Linux kernel with @abbr{FIPS,Federal Information Processing Standard} enabled.

@item 
gh-95097@footnote{https://github.com/python/cpython/issues/95097}: Fix @ref{2f3,,asyncio.run()} for @ref{1c7,,asyncio.Task}
implementations without @ref{4d6,,uncancel()} method. Patch by
Kumar Aditya.

@item 
gh-95087@footnote{https://github.com/python/cpython/issues/95087}: Fix IndexError in parsing invalid date in the @ref{3f,,email}
module.

@item 
gh-95199@footnote{https://github.com/python/cpython/issues/95199}: Upgrade bundled setuptools to 63.2.0.

@item 
gh-95194@footnote{https://github.com/python/cpython/issues/95194}: Upgrade bundled pip to 22.2.

@item 
gh-93899@footnote{https://github.com/python/cpython/issues/93899}: Fix check for existence of @ref{1b58,,os.EFD_CLOEXEC},
@ref{1b59,,os.EFD_NONBLOCK} and @ref{1b5a,,os.EFD_SEMAPHORE} flags on older
kernel versions where these flags are not present. Patch by Kumar Aditya.

@item 
gh-95166@footnote{https://github.com/python/cpython/issues/95166}: Fix @ref{1dc,,concurrent.futures.Executor.map()} to cancel the
currently waiting on future on an error - e.g. TimeoutError or
KeyboardInterrupt.

@item 
gh-95132@footnote{https://github.com/python/cpython/issues/95132}: Fix a @ref{d4,,sqlite3} regression where @code{*args} and @code{**kwds}
were incorrectly relayed from @ref{5a6,,connect()} to the
@ref{54d,,Connection} factory. The regression was introduced in
3.11a1 with PR 24421 (gh-85128@footnote{https://github.com/python/cpython/issues/85128}). Patch by Erlend E. Aasland.

@item 
gh-93157@footnote{https://github.com/python/cpython/issues/93157}: Fix @ref{5f,,fileinput} module didn't support @code{errors} option
when @code{inplace} is true.

@item 
gh-91212@footnote{https://github.com/python/cpython/issues/91212}: Fixed flickering of the turtle window when the tracer is turned
off. Patch by Shin-myoung-serp.

@item 
gh-95077@footnote{https://github.com/python/cpython/issues/95077}: Add deprecation warning for enum @code{member.member} access (e.g.
@code{Color.RED.BLUE}). Remove @code{EnumMeta.__getattr__}.

@item 
gh-95109@footnote{https://github.com/python/cpython/issues/95109}: Ensure that timeouts scheduled with @ref{1a40,,asyncio.Timeout}
that have already expired are delivered promptly.

@item 
gh-95105@footnote{https://github.com/python/cpython/issues/95105}: @code{wsgiref.types.InputStream.__iter__()} should return
@code{Iterator[bytes]}, not @code{Iterable[bytes]}. Patch by Shantanu Jain.

@item 
gh-95066@footnote{https://github.com/python/cpython/issues/95066}: Replaced assert with exception in @ref{1c2,,ast.parse()}, when
@code{feature_version} has an invalid major version. Patch by Shantanu Jain.

@item 
gh-77617@footnote{https://github.com/python/cpython/issues/77617}: Add @ref{d4,,sqlite3} @ref{674,,command-line interface}.
Patch by Erlend Aasland.

@item 
gh-95005@footnote{https://github.com/python/cpython/issues/95005}: Replace _PyAccu with _PyUnicodeWriter in
JSON encoder and StringIO and remove the _PyAccu implementation.

@item 
gh-90085@footnote{https://github.com/python/cpython/issues/90085}: Remove @code{-c/--clock} and @code{-t/--time} CLI options of
@ref{f5,,timeit}. The options had been deprecated since Python 3.3 and the
functionality was removed in Python 3.7. Patch by Shantanu Jain.

@item 
gh-94857@footnote{https://github.com/python/cpython/issues/94857}: Fix refleak in @code{_io.TextIOWrapper.reconfigure}. Patch by Kumar
Aditya.

@item 
gh-94821@footnote{https://github.com/python/cpython/issues/94821}: Fix binding of unix socket to empty address on Linux to use an
available address from the abstract namespace, instead of "0".

@item 
gh-94736@footnote{https://github.com/python/cpython/issues/94736}: Fix crash when deallocating an instance of a subclass of
@code{_multiprocessing.SemLock}. Patch by Kumar Aditya.

@item 
gh-81620@footnote{https://github.com/python/cpython/issues/81620}: Add random.binomialvariate().

@item 
gh-74116@footnote{https://github.com/python/cpython/issues/74116}: Allow @ref{1b29,,asyncio.StreamWriter.drain()} to be awaited
concurrently by multiple tasks. Patch by Kumar Aditya.

@item 
gh-87822@footnote{https://github.com/python/cpython/issues/87822}: When called with @code{capture_locals=True}, the @ref{104,,traceback}
module functions swallow exceptions raised from calls to @code{repr()} on
local variables of frames. This is in order to prioritize the original
exception over rendering errors.  An indication of the failure is printed
in place of the missing value.  (Patch by Simon-Martin Schroeder).

@item 
gh-88050@footnote{https://github.com/python/cpython/issues/88050}: Fix @ref{b,,asyncio} subprocess transport to kill process cleanly
when process is blocked and avoid @code{RuntimeError} when loop is closed.
Patch by Kumar Aditya.

@item 
gh-94637@footnote{https://github.com/python/cpython/issues/94637}: @code{SSLContext.set_default_verify_paths()} now releases the GIL
around @code{SSL_CTX_set_default_verify_paths} call. The function call
performs I/O and CPU intensive work.

@item 
gh-94309@footnote{https://github.com/python/cpython/issues/94309}: Deprecate aliases @ref{717,,typing.Hashable} and
@ref{718,,typing.Sized}

@item 
gh-92546@footnote{https://github.com/python/cpython/issues/92546}: An undocumented @code{python -m pprint} benchmark is moved into
@code{pprint} suite of pyperformance. Patch by Oleg Iarygin.

@item 
gh-94607@footnote{https://github.com/python/cpython/issues/94607}: Fix subclassing complex generics with type variables in
@ref{10a,,typing}. Previously an error message saying @code{Some type variables
... are not listed in Generic[...]} was shown. @ref{10a,,typing} no longer
populates @code{__parameters__} with the @code{__parameters__} of a Python
class.

@item 
gh-94619@footnote{https://github.com/python/cpython/issues/94619}: Remove the long-deprecated @code{module_repr()} from
@ref{7b,,importlib}.

@item 
gh-93910@footnote{https://github.com/python/cpython/issues/93910}: The ability to access the other values of an enum on an enum
(e.g. @code{Color.RED.BLUE}) has been restored in order to fix a performance
regression.

@item 
gh-93896@footnote{https://github.com/python/cpython/issues/93896}: Fix @ref{2f3,,asyncio.run()} and
@ref{361,,unittest.IsolatedAsyncioTestCase} to always the set event loop as
it was done in Python 3.10 and earlier. Patch by Kumar Aditya.

@item 
gh-94343@footnote{https://github.com/python/cpython/issues/94343}: Allow setting the attributes of @code{reprlib.Repr} during object
initialization

@item 
gh-94382@footnote{https://github.com/python/cpython/issues/94382}: Port static types of @code{_multiprocessing} module to heap types.
Patch by Kumar Aditya.

@item 
gh-78724@footnote{https://github.com/python/cpython/issues/78724}: Fix crash in @ref{1778,,struct.Struct} when it was not completely
initialized by initializing it in @ref{7a0,,__new__()}.  Patch by Kumar
Aditya.

@item 
gh-94510@footnote{https://github.com/python/cpython/issues/94510}: Re-entrant calls to @ref{1717,,sys.setprofile()} and
@ref{2e1,,sys.settrace()} now raise @ref{244,,RuntimeError}. Patch by Pablo
Galindo.

@item 
gh-92336@footnote{https://github.com/python/cpython/issues/92336}: Fix bug where @ref{240,,linecache.getline()} fails on bad files with
@ref{c08,,UnicodeDecodeError} or @ref{18e,,SyntaxError}. It now returns an empty
string as per the documentation.

@item 
gh-94398@footnote{https://github.com/python/cpython/issues/94398}: Once a @ref{4d1,,asyncio.TaskGroup} has started shutting down
(i.e., at least one task has failed and the task group has started
cancelling the remaining tasks), it should not be possible to add new
tasks to the task group.

@item 
gh-94383@footnote{https://github.com/python/cpython/issues/94383}: @code{xml.etree}: Remove the @code{ElementTree.Element.copy()}
method of the pure Python implementation, deprecated in Python 3.10, use
the @ref{757,,copy.copy()} function instead. The C implementation of
@code{xml.etree} has no @code{copy()} method, only a @code{__copy__()} method.
Patch by Victor Stinner.

@item 
gh-94379@footnote{https://github.com/python/cpython/issues/94379}: @ref{138,,zipimport}: Remove @code{find_loader()} and @code{find_module()}
methods, deprecated in Python 3.10: use the @code{find_spec()} method
instead. See 
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/} for the rationale. Patch by Victor Stinner.

@item 
gh-94352@footnote{https://github.com/python/cpython/issues/94352}: @ref{75e,,shlex.split()}: Passing @code{None} for `s' argument now
raises an exception, rather than reading @ref{75f,,sys.stdin}. The feature
was deprecated in Python 3.9. Patch by Victor Stinner.

@item 
gh-94318@footnote{https://github.com/python/cpython/issues/94318}: Strip trailing spaces in @ref{ba,,pydoc} text output.

@item 
gh-89988@footnote{https://github.com/python/cpython/issues/89988}: Fix memory leak in @ref{c13,,pickle.Pickler} when looking up
@code{dispatch_table}. Patch by Kumar Aditya.

@item 
gh-90016@footnote{https://github.com/python/cpython/issues/90016}: Deprecate @ref{d4,,sqlite3} @ref{714,,default adapters and converters}. Patch by Erlend E. Aasland.

@item 
gh-94254@footnote{https://github.com/python/cpython/issues/94254}: Fixed types of @ref{db,,struct} module to be immutable. Patch by
Kumar Aditya.

@item 
gh-93259@footnote{https://github.com/python/cpython/issues/93259}: Now raise @code{ValueError} when @code{None} or an empty string are
passed to @code{Distribution.from_name} (and other callers).

@item 
gh-74696@footnote{https://github.com/python/cpython/issues/74696}: @ref{6da,,shutil.make_archive()} now passes the `root_dir' argument
to custom archivers which support it.

@item 
gh-94216@footnote{https://github.com/python/cpython/issues/94216}: The @ref{3c,,dis} module now has the opcodes for pseudo
instructions (those which are used by the compiler during code generation
but then removed or replaced by real opcodes before the final bytecode is
emitted).

@item 
gh-93096@footnote{https://github.com/python/cpython/issues/93096}: Removed undocumented @code{python -m codecs}. Use @code{python -m
unittest test.test_codecs.EncodedFileTest} instead.

@item 
gh-94207@footnote{https://github.com/python/cpython/issues/94207}: Made @code{_struct.Struct} GC-tracked in order to fix a
reference leak in the @code{_struct} module.

@item 
gh-93096@footnote{https://github.com/python/cpython/issues/93096}: Removed undocumented @code{-t} argument of @code{python -m base64}.
Use @code{python -m unittest
test.test_base64.LegacyBase64TestCase.test_encodebytes} instead.

@item 
gh-94226@footnote{https://github.com/python/cpython/issues/94226}: Remove the @code{locale.format()} function, deprecated in Python
3.7: use @ref{742,,locale.format_string()} instead. Patch by Victor Stinner.

@item 
gh-94199@footnote{https://github.com/python/cpython/issues/94199}: Remove the @code{ssl.match_hostname()} function. The
@code{ssl.match_hostname()} was deprecated in Python 3.7. OpenSSL performs
hostname matching since Python 3.7, Python no longer uses the
@code{ssl.match_hostname()} function. Patch by Victor Stinner.

@item 
gh-94214@footnote{https://github.com/python/cpython/issues/94214}: Document the @code{context} object used in the @code{venv.EnvBuilder}
class, and add the new environment's library path to it.

@item 
gh-94199@footnote{https://github.com/python/cpython/issues/94199}: Remove the @code{ssl.wrap_socket()} function, deprecated in
Python 3.7: instead, create a @ref{357,,ssl.SSLContext} object and call its
@ref{748,,ssl.SSLContext.wrap_socket} method. Any package that still uses
@code{ssl.wrap_socket()} is broken and insecure. The function neither sends
a SNI TLS extension nor validates server hostname. Code is subject to
@geindex Common Weakness Enumeration; CWE 295
CWE 295@footnote{https://cwe.mitre.org/data/definitions/295.html} Improper Certificate Validation. Patch by Victor Stinner.

@item 
gh-94199@footnote{https://github.com/python/cpython/issues/94199}: Remove the @code{ssl.RAND_pseudo_bytes()} function, deprecated in
Python 3.6: use @ref{746,,os.urandom()} or @ref{747,,ssl.RAND_bytes()} instead.
Patch by Victor Stinner.

@item 
gh-94199@footnote{https://github.com/python/cpython/issues/94199}: @ref{6c,,hashlib}: Remove the pure Python implementation of
@ref{733,,hashlib.pbkdf2_hmac()}, deprecated in Python 3.10. Python 3.10 and
newer requires OpenSSL 1.1.1 (
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/}): this OpenSSL version provides a
C implementation of @ref{733,,pbkdf2_hmac()} which is faster. Patch by
Victor Stinner.

@item 
gh-94196@footnote{https://github.com/python/cpython/issues/94196}: @ref{6b,,gzip}: Remove the @code{filename} attribute of
@ref{65c,,gzip.GzipFile}, deprecated since Python 2.6, use the
@ref{731,,name} attribute instead. In write mode, the
@code{filename} attribute added @code{'.gz'} file extension if it was not
present. Patch by Victor Stinner.

@item 
gh-94182@footnote{https://github.com/python/cpython/issues/94182}: run the @code{asyncio.PidfdChildWatcher} on the running loop,
this allows event loops to run subprocesses when there is no default event
loop running on the main thread

@item 
gh-94169@footnote{https://github.com/python/cpython/issues/94169}: Remove @code{io.OpenWrapper} and @code{_pyio.OpenWrapper}, deprecated
in Python 3.10: just use @ref{316,,open()} instead. The @ref{316,,open()}
(@ref{740,,io.open()}) function is a built-in function. Since Python 3.10,
@code{_pyio.open()} is also a static method. Patch by Victor Stinner.

@item 
gh-91742@footnote{https://github.com/python/cpython/issues/91742}: Fix @ref{aa,,pdb} crash after jump caused by a null pointer
dereference. Patch by Kumar Aditya.

@item 
gh-94101@footnote{https://github.com/python/cpython/issues/94101}: Manual instantiation of @ref{ed9,,ssl.SSLSession} objects is no
longer allowed as it lead to misconfigured instances that crashed the
interpreter when attributes where accessed on them.

@item 
gh-84753@footnote{https://github.com/python/cpython/issues/84753}: @ref{30d,,inspect.iscoroutinefunction()},
@ref{1b5b,,inspect.isgeneratorfunction()}, and
@ref{1b5c,,inspect.isasyncgenfunction()} now properly return @code{True} for
duck-typed function-like objects like instances of
@ref{c3e,,unittest.mock.AsyncMock}.

This makes @ref{30d,,inspect.iscoroutinefunction()} consistent with the
behavior of @code{asyncio.iscoroutinefunction()}.  Patch by Mehdi ABAAKOUK.

@item 
gh-94028@footnote{https://github.com/python/cpython/issues/94028}: Fix a regression in the @ref{d4,,sqlite3} where statement objects
were not properly cleared and reset after use in cursor iters. The
regression was introduced by PR 27884 in Python 3.11a1. Patch by Erlend E.
Aasland.

@item 
gh-93973@footnote{https://github.com/python/cpython/issues/93973}: Add keyword argument @code{all_errors} to
@code{asyncio.create_connection} so that multiple connection errors can be
raised as an @code{ExceptionGroup}.

@item 
gh-93963@footnote{https://github.com/python/cpython/issues/93963}: Officially deprecate from @code{importlib.abc} classes moved to
@code{importlib.resources.abc}.

@item 
gh-93858@footnote{https://github.com/python/cpython/issues/93858}: Prevent error when activating venv in nested fish instances.

@item 
gh-93820@footnote{https://github.com/python/cpython/issues/93820}: Pickle @ref{835,,enum.Flag} by name.

@item 
gh-93847@footnote{https://github.com/python/cpython/issues/93847}: Fix repr of enum of generic aliases.

@item 
gh-91404@footnote{https://github.com/python/cpython/issues/91404}: Revert the @ref{be,,re} memory leak when a match is terminated by a
signal or memory allocation failure as the implemented fix caused a major
performance regression.

@item 
gh-83499@footnote{https://github.com/python/cpython/issues/83499}: Fix double closing of file description in @ref{e6,,tempfile}.

@item 
gh-93820@footnote{https://github.com/python/cpython/issues/93820}: Fixed a regression when @ref{757,,copy.copy()}-ing @ref{835,,enum.Flag}
with multiple flag members.

@item 
gh-79512@footnote{https://github.com/python/cpython/issues/79512}: Fixed names and @code{__module__} value of @ref{11a,,weakref} classes
@ref{1b5d,,ReferenceType}, @ref{1b5e,,ProxyType},
@ref{1b5f,,CallableProxyType}. It makes them pickleable.

@item 
gh-91389@footnote{https://github.com/python/cpython/issues/91389}: Fix an issue where @ref{3c,,dis} utilities could report missing or
incorrect position information in the presence of @code{CACHE} entries.

@item 
gh-93626@footnote{https://github.com/python/cpython/issues/93626}: Set @code{__future__.annotations} to have a @code{None}
mandatoryRelease to indicate that it is currently 'TBD'.

@item 
gh-90473@footnote{https://github.com/python/cpython/issues/90473}: Emscripten and WASI have no home directory and cannot provide
@geindex Python Enhancement Proposals; PEP 370
PEP 370@footnote{https://peps.python.org/pep-0370/} user site directory.

@item 
gh-90494@footnote{https://github.com/python/cpython/issues/90494}: @ref{757,,copy.copy()} and @ref{d65,,copy.deepcopy()} now always raise a
TypeError if @code{__reduce__()} returns a tuple with length 6 instead of
silently ignore the 6th item or produce incorrect result.

@item 
gh-90549@footnote{https://github.com/python/cpython/issues/90549}: Fix a multiprocessing bug where a global named resource (such as
a semaphore) could leak when a child process is spawned (as opposed to
forked).

@item 
gh-93521@footnote{https://github.com/python/cpython/issues/93521}: Fixed a case where dataclasses would try to add @code{__weakref__}
into the @code{__slots__} for a dataclass that specified
@code{weakref_slot=True} when it was already defined in one of its bases.
This resulted in a @code{TypeError} upon the new class being created.

@item 
gh-79579@footnote{https://github.com/python/cpython/issues/79579}: @ref{d4,,sqlite3} now correctly detects DML queries with leading
comments. Patch by Erlend E. Aasland.

@item 
gh-93421@footnote{https://github.com/python/cpython/issues/93421}: Update @ref{1b60,,sqlite3.Cursor.rowcount} when a DML statement has
run to completion. This fixes the row count for SQL queries like @code{UPDATE
... RETURNING}. Patch by Erlend E. Aasland.

@item 
gh-93475@footnote{https://github.com/python/cpython/issues/93475}: Expose @code{FICLONE} and @code{FICLONERANGE} constants in
@ref{5d,,fcntl}. Patch by Illia Volochii.

@item 
gh-93370@footnote{https://github.com/python/cpython/issues/93370}: Deprecate @code{version} and @code{version_info}.

@item 
gh-91810@footnote{https://github.com/python/cpython/issues/91810}: Suppress writing an XML declaration in open files in
@code{ElementTree.write()} with @code{encoding='unicode'} and
@code{xml_declaration=None}.

@item 
gh-91162@footnote{https://github.com/python/cpython/issues/91162}: Support splitting of unpacked arbitrary-length tuple over
@code{TypeVar} and @code{TypeVarTuple} parameters. For example:


@itemize *

@item 
@code{A[T, *Ts][*tuple[int, ...]]} -> @code{A[int, *tuple[int, ...]]}

@item 
@code{A[*Ts, T][*tuple[int, ...]]} -> @code{A[*tuple[int, ...], int]}
@end itemize

@item 
gh-93353@footnote{https://github.com/python/cpython/issues/93353}: Fix the @ref{6b5,,importlib.resources.as_file()} context manager to
remove the temporary file if destroyed late during Python finalization:
keep a local reference to the @ref{1308,,os.remove()} function. Patch by Victor
Stinner.

@item 
gh-83658@footnote{https://github.com/python/cpython/issues/83658}: Make @code{multiprocessing.Pool} raise an exception if
@code{maxtasksperchild} is not @code{None} or a positive int.

@item 
gh-93312@footnote{https://github.com/python/cpython/issues/93312}: Add @ref{6c2,,os.PIDFD_NONBLOCK} flag to open a file descriptor
for a process with @ref{6a4,,os.pidfd_open()} in non-blocking mode. Patch by
Kumar Aditya.

@item 
gh-88123@footnote{https://github.com/python/cpython/issues/88123}: Implement @code{Enum.__contains__} that returns @code{True} or
@code{False} to replace the deprecated behaviour that would sometimes raise a
@ref{198,,TypeError}.

@item 
gh-93297@footnote{https://github.com/python/cpython/issues/93297}: Make asyncio task groups prevent child tasks from being GCed

@item 
gh-85308@footnote{https://github.com/python/cpython/issues/85308}: Changed @ref{1bd,,argparse.ArgumentParser} to use
@ref{75d,,filesystem encoding and error handler} instead of default text
encoding to read arguments from file (e.g. @code{fromfile_prefix_chars}
option). This change affects Windows; argument file should be encoded with
UTF-8 instead of ANSI Codepage.

@item 
gh-93156@footnote{https://github.com/python/cpython/issues/93156}: Accessing the @ref{a21,,pathlib.PurePath.parents} sequence of an
absolute path using negative index values produced incorrect results.

@item 
gh-93162@footnote{https://github.com/python/cpython/issues/93162}: Add the ability for @ref{13c8,,logging.config.dictConfig()} to
usefully configure @ref{1b61,,QueueHandler} and
@ref{242,,QueueListener} as a pair, and add
@ref{1b62,,logging.getHandlerByName()} and @ref{1a6e,,logging.getHandlerNames()} APIs
to allow access to handlers by name.

@item 
gh-93243@footnote{https://github.com/python/cpython/issues/93243}: The @code{smtpd} module was removed per the schedule in
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}.

@item 
gh-92886@footnote{https://github.com/python/cpython/issues/92886}: Replace @code{assert} statements with @code{raise AssertionError()} in
@code{BaseHandler} so that the tested behaviour is maintained
running with optimizations @code{(-O)}.

@item 
gh-90155@footnote{https://github.com/python/cpython/issues/90155}: Fix broken @ref{c68,,asyncio.Semaphore} when acquire is cancelled.

@item 
gh-90817@footnote{https://github.com/python/cpython/issues/90817}: The @code{locale.resetlocale()} function is deprecated and will
be removed in Python 3.13. Use @code{locale.setlocale(locale.LC_ALL, "")}
instead. Patch by Victor Stinner.

@item 
gh-91513@footnote{https://github.com/python/cpython/issues/91513}: Added @code{taskName} attribute to @ref{8b,,logging} module for use
with @ref{b,,asyncio} tasks.

@item 
gh-74696@footnote{https://github.com/python/cpython/issues/74696}: @ref{6da,,shutil.make_archive()} no longer temporarily changes the
current working directory during creation of standard @code{.zip} or tar
archives.

@item 
gh-92728@footnote{https://github.com/python/cpython/issues/92728}: The @code{re.template()} function and the corresponding
@code{re.TEMPLATE} and @code{re.T} flags are restored after they were
removed in 3.11.0b1, but they are now deprecated, so they might be removed
from Python 3.13.

@item 
gh-93033@footnote{https://github.com/python/cpython/issues/93033}: Search in some strings (platform dependent i.e [U+0xFFFF,
U+0x0100] on Windows or [U+0xFFFFFFFF, U+0x00010000] on Linux 64-bit) are
now up to 10 times faster.

@item 
gh-89973@footnote{https://github.com/python/cpython/issues/89973}: Fix @code{re.error} raised in @ref{60,,fnmatch} if the pattern
contains a character range with upper bound lower than lower bound (e.g.
@code{[c-a]}). Now such ranges are interpreted as empty ranges.

@item 
gh-93044@footnote{https://github.com/python/cpython/issues/93044}: No longer convert the database argument of
@ref{5a6,,sqlite3.connect()} to bytes before passing it to the factory.

@item 
gh-93010@footnote{https://github.com/python/cpython/issues/93010}: In a very special case, the email package tried to append the
nonexistent @code{InvalidHeaderError} to the defect list. It should have been
@code{InvalidHeaderDefect}.

@item 
gh-92986@footnote{https://github.com/python/cpython/issues/92986}: Fix @ref{ae2,,ast.unparse()} when @code{ImportFrom.level} is @code{None}

@item 
gh-92932@footnote{https://github.com/python/cpython/issues/92932}: Now @ref{205,,dis()} and @ref{4ec,,get_instructions()} handle
operand values for instructions prefixed by @code{EXTENDED_ARG_QUICK}. Patch
by Sam Gross and Donghee Na.

@item 
gh-92675@footnote{https://github.com/python/cpython/issues/92675}: Fix @code{venv.ensure_directories()} to accept
@ref{266,,pathlib.Path} arguments in addition to @ref{169,,str} paths. Patch
by David Foster.

@item 
gh-87901@footnote{https://github.com/python/cpython/issues/87901}: Removed the @code{encoding} argument from @ref{31a,,os.popen()} that was
added in 3.11b1.

@item 
gh-91922@footnote{https://github.com/python/cpython/issues/91922}: Fix function @code{sqlite.connect()} and the
@code{sqlite.Connection} constructor on non-UTF-8 locales. Also, they
now support bytes paths non-decodable with the current FS encoding.

@item 
gh-92869@footnote{https://github.com/python/cpython/issues/92869}: Added @ref{1b63,,c_time_t} to @ref{2e,,ctypes}, which has the
same size as the @code{time_t} type in C.

@item 
gh-92839@footnote{https://github.com/python/cpython/issues/92839}: Fixed crash resulting from calling bisect.insort() or
bisect.insort_left() with the key argument not equal to @code{None}.

@item 
gh-90473@footnote{https://github.com/python/cpython/issues/90473}: @ref{dc,,subprocess} now fails early on Emscripten and WASI
platforms to work around missing @ref{1b64,,os.pipe()} on WASI.

@item 
gh-89325@footnote{https://github.com/python/cpython/issues/89325}: Removed many old deprecated @ref{10c,,unittest} features:
@ref{2b3,,TestCase} method aliases, undocumented and broken
@ref{2b3,,TestCase} method @code{assertDictContainsSubset},
undocumented @ref{594,,TestLoader.loadTestsFromModule} parameter `use_load_tests', and
an underscored alias of the @ref{754,,TextTestResult} class.

@item 
gh-92734@footnote{https://github.com/python/cpython/issues/92734}: Allow multi-element reprs emitted by @ref{c0,,reprlib} to be
pretty-printed using configurable indentation.

@item 
gh-92671@footnote{https://github.com/python/cpython/issues/92671}: Fixed @ref{ae2,,ast.unparse()} for empty tuples in the assignment
target context.

@item 
gh-91581@footnote{https://github.com/python/cpython/issues/91581}: @ref{352,,utcfromtimestamp()} no longer attempts
to resolve @code{fold} in the pure Python implementation, since the fold is
never 1 in UTC. In addition to being slightly faster in the common case,
this also prevents some errors when the timestamp is close to
@ref{1b65,,datetime.min}.  Patch by Paul Ganssle.

@item 
gh-86388@footnote{https://github.com/python/cpython/issues/86388}: Removed randrange() functionality deprecated since Python 3.10.
Formerly, randrange(10.0) losslessly converted to randrange(10). Now, it
raises a TypeError. Also, the exception raised for non-integral values
such as randrange(10.5) or randrange('10') has been changed from
ValueError to TypeError.

@item 
gh-90385@footnote{https://github.com/python/cpython/issues/90385}: Add @ref{6cf,,pathlib.Path.walk()} as an alternative to
@ref{6d0,,os.walk()}.

@item 
gh-92550@footnote{https://github.com/python/cpython/issues/92550}: Fix @ref{538,,pathlib.Path.rglob()} for empty pattern.

@item 
gh-92591@footnote{https://github.com/python/cpython/issues/92591}: Allow @ref{8b,,logging} filters to return a
@ref{11e8,,logging.LogRecord} instance so that filters attached to
@ref{16af,,logging.Handler}s can enrich records without side effects on
other handlers.

@item 
gh-92445@footnote{https://github.com/python/cpython/issues/92445}: Fix a bug in @ref{7,,argparse} where @code{nargs="*"} would raise an
error instead of returning an empty list when 0 arguments were supplied if
choice was also defined in @code{parser.add_argument}.

@item 
gh-92547@footnote{https://github.com/python/cpython/issues/92547}: Remove undocumented @ref{d4,,sqlite3} features deprecated in Python
3.10:


@itemize *

@item 
@code{sqlite3.enable_shared_cache()}

@item 
@code{sqlite3.OptimizedUnicode}
@end itemize

Patch by Erlend E. Aasland.

@item 
gh-92530@footnote{https://github.com/python/cpython/issues/92530}: Fix an issue that occurred after interrupting
@ref{1b66,,threading.Condition.notify()}.

@item 
gh-92531@footnote{https://github.com/python/cpython/issues/92531}: The statistics.median_grouped() function now always return a
float. Formerly, it did not convert the input type when for sequences of
length one.

@item 
gh-84131@footnote{https://github.com/python/cpython/issues/84131}: The @ref{266,,pathlib.Path} deprecated method @code{link_to} has been
removed. Use 3.10's @ref{a22,,hardlink_to()} method instead as
its semantics are consistent with that of
@ref{a23,,symlink_to()}.

@item 
gh-89336@footnote{https://github.com/python/cpython/issues/89336}: Removed @ref{26,,configparser} module APIs: the
@code{SafeConfigParser} class alias, the @code{ParsingError.filename} property
and parameter, and the @code{ConfigParser.readfp} method, all of which were
deprecated since Python 3.2.

@item 
gh-92391@footnote{https://github.com/python/cpython/issues/92391}: Add @ref{943,,__class_getitem__()} to
@ref{bd8,,csv.DictReader} and @ref{1417,,csv.DictWriter}, allowing them to be
parameterized at runtime. Patch by Marc Mueller.

@item 
gh-91968@footnote{https://github.com/python/cpython/issues/91968}: Add @code{SO_RTABLE} and @code{SO_USER_COOKIE} constants to
@ref{d1,,socket}.

@item 
gh-91810@footnote{https://github.com/python/cpython/issues/91810}: @ref{b47,,ElementTree} method
@ref{c8c,,write()} and function
@ref{11f7,,tostring()} now use the text file's encoding
("UTF-8" if not available) instead of locale encoding in XML declaration
when @code{encoding="unicode"} is specified.

@item 
gh-81790@footnote{https://github.com/python/cpython/issues/81790}: @ref{def,,os.path.splitdrive()} now understands DOS device paths with
UNC links (beginning @code{\\?\UNC\}). Contributed by Barney Gale.

@item 
gh-91760@footnote{https://github.com/python/cpython/issues/91760}: Apply more strict rules for numerical group references and group
names in regular expressions. Only sequence of ASCII digits is now
accepted as a numerical reference. The group name in bytes patterns and
replacement strings can now only contain ASCII letters and digits and
underscore.

@item 
gh-90622@footnote{https://github.com/python/cpython/issues/90622}: Worker processes for
@ref{1d6,,concurrent.futures.ProcessPoolExecutor} are no longer spawned on
demand (a feature added in 3.9) when the multiprocessing context start
method is @code{"fork"} as that can lead to deadlocks in the child processes
due to a fork happening while threads are running.

@item 
gh-91577@footnote{https://github.com/python/cpython/issues/91577}: Move imports in @code{SharedMemory} methods
to module level so that they can be executed late in python finalization.

@item 
gh-91581@footnote{https://github.com/python/cpython/issues/91581}: Remove an unhandled error case in the C implementation of calls
to @ref{712,,datetime.fromtimestamp} with
no time zone (i.e. getting a local time from an epoch timestamp). This
should have no user-facing effect other than giving a possibly more
accurate error message when called with timestamps that fall on
10000-01-01 in the local time. Patch by Paul Ganssle.

@item 
gh-91539@footnote{https://github.com/python/cpython/issues/91539}: Improve performance of @code{urllib.request.getproxies_environment}
when there are many environment variables

@item 
gh-91524@footnote{https://github.com/python/cpython/issues/91524}: Speed up the regular expression substitution (functions
@ref{5a3,,re.sub()} and @ref{5a4,,re.subn()} and corresponding @ref{1b67,,re.Pattern}
methods) for replacement strings containing group references by 2--3
times.

@item 
gh-91447@footnote{https://github.com/python/cpython/issues/91447}: Fix findtext in the xml module to only give an empty string when
the text attribute is set to @code{None}.

@item 
gh-91456@footnote{https://github.com/python/cpython/issues/91456}: Deprecate current default auto() behavior:  In 3.13 the default
will be for for auto() to always return the largest member value
incremented by 1, and to raise if incompatible value types are used.

@item 
bpo-47231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47231}: Fixed an issue with inconsistent trailing slashes in tarfile
longname directories.

@item 
bpo-39064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39064}: @ref{8d3,,zipfile.ZipFile} now raises @ref{1b68,,zipfile.BadZipFile}
instead of @code{ValueError} when reading a corrupt zip file in which the
central directory offset is negative.

@item 
bpo-41287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41287}: Fix handling of the @code{doc} argument in subclasses of
@ref{4b3,,property()}.

@item 
gh-90005@footnote{https://github.com/python/cpython/issues/90005}: @ref{2e,,ctypes} dependency @code{libffi} is now detected with
@code{pkg-config}.

@item 
bpo-32547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32547}: The constructors for @ref{1417,,DictWriter} and
@ref{bd8,,DictReader} now coerce the @code{fieldnames} argument to a
@ref{24d,,list} if it is an iterator.

@item 
bpo-35540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35540}: Fix @ref{1a95,,dataclasses.asdict()} crash when
@ref{13d4,,collections.defaultdict} is present in the attributes.

@item 
bpo-47063@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47063}: Add an index_pages parameter to support using non-default index
page names.

@item 
bpo-47025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47025}: Drop support for @ref{192,,bytes} on @ref{3e4,,sys.path}.

@item 
bpo-46951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46951}: Order the contents of zipapp archives, to make builds more
reproducible.

@item 
bpo-42777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42777}: Implement @ref{c0c,,pathlib.Path.is_mount()} for Windows paths.

@item 
bpo-46755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46755}: In @code{QueueHandler}, clear @code{stack_info} from
@code{LogRecord} to prevent stack trace from being written twice.

@item 
bpo-45393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45393}: Fix the formatting for @code{await x} and @code{not x} in the
operator precedence table when using the @ref{ad4,,help()} system.

@item 
bpo-46642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46642}: Improve error message when trying to subclass an instance of
@ref{486,,typing.TypeVar}, @ref{487,,typing.ParamSpec},
@ref{488,,typing.TypeVarTuple}, etc. Based on patch by Gregory Beauregard.

@item 
bpo-46364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46364}: Restrict use of sockets instead of pipes for stdin of
subprocesses created by @ref{b,,asyncio} to AIX platform only.

@item 
bpo-28249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28249}: Set @ref{17c7,,doctest.DocTest.lineno} to @code{None} when an object
does not have @ref{b21,,__doc__}.

@item 
bpo-46197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46197}: Fix @ref{59,,ensurepip} environment isolation for subprocess
running @code{pip}.

@item 
bpo-45924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45924}: Fix @ref{b,,asyncio} incorrect traceback when future's exception
is raised multiple times. Patch by Kumar Aditya.

@item 
bpo-45046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45046}: Add support of context managers in @ref{10c,,unittest}: methods
@ref{8c8,,enterContext()} and
@ref{8c9,,enterClassContext()} of class
@ref{2b3,,TestCase}, method
@ref{8ca,,enterAsyncContext()} of class
@ref{361,,IsolatedAsyncioTestCase} and function
@ref{8cb,,unittest.enterModuleContext()}.

@item 
bpo-44173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44173}: Enable fast seeking of uncompressed unencrypted
@code{zipfile.ZipExtFile}

@item 
bpo-42627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42627}: Fix incorrect parsing of Windows registry proxy settings

@item 
bpo-42047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42047}: Add @ref{c32,,threading.get_native_id()} support for DragonFly BSD.
Patch by David Carlier.

@item 
bpo-14243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14243}: The @ref{6ed,,tempfile.NamedTemporaryFile} function has a new
optional parameter `delete_on_close'

@item 
bpo-41246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41246}: Give the same callback function for when the overlapped
operation is done to the functions @code{recv}, @code{recv_into}, @code{recvfrom},
@code{sendto}, @code{send} and @code{sendfile} inside @code{IocpProactor}.

@item 
bpo-39264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39264}: Fixed @code{collections.UserDict.get()} to not call
@ref{13d5,,__missing__()} when a value is not found. This matches the
behavior of @ref{183,,dict}. Patch by Bar Harel.

@item 
bpo-38693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38693}: @ref{7b,,importlib} now uses f-strings internally instead of
@code{str.format}.

@item 
bpo-38267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38267}: Add `timeout' parameter to
@ref{ae4,,asyncio.loop.shutdown_default_executor()}. The default value is
@code{None}, which means the executor will be given an unlimited amount of
time. When called from @ref{2f5,,asyncio.Runner} or @ref{2f3,,asyncio.run()}, the
default timeout is 5 minutes.

@item 
bpo-34828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34828}: @ref{54f,,sqlite3.Connection.iterdump()} now handles databases that
use @code{AUTOINCREMENT} in one or more tables.

@item 
bpo-32990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32990}: Support reading wave files with the @code{WAVE_FORMAT_EXTENSIBLE}
format in the @ref{119,,wave} module.

@item 
bpo-26253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26253}: Allow adjustable compression level for tarfile streams in
@ref{1077,,tarfile.open()}.
@end itemize

@node ドキュメント<28>,テスト<27>,ライブラリ<87>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id382}@anchor{1b69}
@subsubsection ドキュメント



@itemize -

@item 
gh-85525@footnote{https://github.com/python/cpython/issues/85525}: Remove extra row

@item 
gh-86404@footnote{https://github.com/python/cpython/issues/86404}: Deprecated tools @code{make suspicious} and @code{rstlint.py} are now
removed. They have been replaced by sphinx-lint@footnote{https://pypi.org/project/sphinx-lint/}.

@item 
gh-97741@footnote{https://github.com/python/cpython/issues/97741}: Fix @code{!} in c domain ref target syntax via a @code{conf.py} patch,
so it works as intended to disable ref target resolution.

@item 
gh-96432@footnote{https://github.com/python/cpython/issues/96432}: Fraction literals now support whitespace around the forward
slash, @code{Fraction('2 / 3')}.

@item 
gh-96098@footnote{https://github.com/python/cpython/issues/96098}: Improve discoverability of the higher level concurrent.futures
module by providing clearer links from the lower level threading and
multiprocessing modules.

@item 
gh-95957@footnote{https://github.com/python/cpython/issues/95957}: What's New 3.11 now has instructions for how to provide compiler
and linker flags for Tcl/Tk and OpenSSL on RHEL 7 and CentOS 7.

@item 
gh-95588@footnote{https://github.com/python/cpython/issues/95588}: Clarified the conflicting advice given in the @ref{9,,ast}
documentation about @ref{e12,,ast.literal_eval()} being "safe" for use on
untrusted input while at the same time warning that it can crash the
process. The latter statement is true and is deemed unfixable without a
large amount of work unsuitable for a bugfix. So we keep the warning and
no longer claim that @code{literal_eval} is safe.

@item 
gh-91207@footnote{https://github.com/python/cpython/issues/91207}: Fix stylesheet not working in Windows CHM htmlhelp docs and add
warning that they are deprecated. Contributed by C.A.M. Gerlach.

@item 
gh-95454@footnote{https://github.com/python/cpython/issues/95454}: Replaced incorrectly written true/false values in documentation.
Patch by Robert O'Shea

@item 
gh-95451@footnote{https://github.com/python/cpython/issues/95451}: Update library documentation with @ref{1b6a,,availability information} on WebAssembly platforms @code{wasm32-emscripten} and
@code{wasm32-wasi}.

@item 
gh-95415@footnote{https://github.com/python/cpython/issues/95415}: Use consistent syntax for platform availability. The directive
now supports a content body and emits a warning when it encounters an
unknown platform.

@item 
gh-94321@footnote{https://github.com/python/cpython/issues/94321}: Document the 
@geindex Python Enhancement Proposals; PEP 246
PEP 246@footnote{https://peps.python.org/pep-0246/} style protocol type
@ref{1b6b,,sqlite3.PrepareProtocol}.

@item 
gh-86128@footnote{https://github.com/python/cpython/issues/86128}: Document a limitation in ThreadPoolExecutor where its exit
handler is executed before any handlers in atexit.

@item 
gh-61162@footnote{https://github.com/python/cpython/issues/61162}: Clarify @ref{d4,,sqlite3} behavior when
@ref{1b6c,,接続(connection)コンテキストマネージャの使い方}.

@item 
gh-87260@footnote{https://github.com/python/cpython/issues/87260}: Align @ref{d4,,sqlite3} argument specs with the actual
implementation.

@item 
gh-86986@footnote{https://github.com/python/cpython/issues/86986}: The minimum Sphinx version required to build the documentation
is now 3.2.

@item 
gh-88831@footnote{https://github.com/python/cpython/issues/88831}: Augmented documentation of asyncio.create_task(). Clarified the
need to keep strong references to tasks and added a code snippet detailing
how to do this.

@item 
gh-86438@footnote{https://github.com/python/cpython/issues/86438}: Clarify that @ref{ac6,,-W} and 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} are
matched literally and case-insensitively, rather than as regular
expressions, in @ref{118,,warnings}.

@item 
gh-93031@footnote{https://github.com/python/cpython/issues/93031}: Update tutorial introduction output to use 3.10+ SyntaxError
invalid range.

@item 
gh-92240@footnote{https://github.com/python/cpython/issues/92240}: Added release dates for "What's New in Python 3.X" for 3.0, 3.1,
3.2, 3.8 and 3.10

@item 
bpo-47161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47161}: Document that @ref{6cd,,pathlib.PurePath} does not collapse
initial double slashes because they denote UNC paths.

@item 
bpo-40838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40838}: Document that @ref{bed,,inspect.getdoc()},
@ref{1b6d,,inspect.getmodule()}, and @ref{1b6e,,inspect.getsourcefile()} might return
@code{None}.

@item 
bpo-43689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43689}: The @code{Differ} documentation now also mentions other whitespace
characters, which make it harder to understand the diff output.

@item 
bpo-38056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38056}: Overhaul the @ref{1b6f,,エラーハンドラ} documentation in
@ref{1c,,codecs}.

@item 
bpo-13553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13553}: Document tkinter.Tk args.
@end itemize

@node テスト<27>,ビルド<32>,ドキュメント<28>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id383}@anchor{1b70}
@subsubsection テスト



@itemize -

@item 
gh-95027@footnote{https://github.com/python/cpython/issues/95027}: On Windows, when the Python test suite is run with the @code{-jN}
option, the ANSI code page is now used as the encoding for the stdout
temporary file, rather than using UTF-8 which can lead to decoding errors.
Patch by Victor Stinner.

@item 
gh-96624@footnote{https://github.com/python/cpython/issues/96624}: Fixed the failure of repeated runs of @code{test.test_unittest}
caused by side effects in @code{test_dotted_but_module_not_loaded}.

@item 
gh-95243@footnote{https://github.com/python/cpython/issues/95243}: Mitigate the inherent race condition from using
find_unused_port() in testSockName() by trying to find an unused port a
few times before failing. Patch by Ross Burton.

@item 
gh-95573@footnote{https://github.com/python/cpython/issues/95573}: Lib/test/test_asyncio/test_ssl.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/test/test_asyncio/test_ssl.py} exposed a bug in the
macOS kernel where intense concurrent load on non-blocking sockets
occasionally causes @ref{1b71,,errno.ENOBUFS} ("No buffer space available")
to be emitted. FB11063974 filed with Apple, in the mean time as a
workaround buffer size used in tests on macOS is decreased to avoid
intermittent failures.  Patch by Fantix King.

@item 
gh-95280@footnote{https://github.com/python/cpython/issues/95280}: Fix problem with @code{test_ssl} @code{test_get_ciphers} on systems
that require perfect forward secrecy (PFS) ciphers.

@item 
gh-95212@footnote{https://github.com/python/cpython/issues/95212}: Make multiprocessing test case @code{test_shared_memory_recreate}
parallel-safe.

@item 
gh-95218@footnote{https://github.com/python/cpython/issues/95218}: Move tests for importlib.resources into
test_importlib.resources.

@item 
gh-93963@footnote{https://github.com/python/cpython/issues/93963}: Updated tests to use preferred location for
@code{importlib.resources} ABCs.

@item 
gh-94675@footnote{https://github.com/python/cpython/issues/94675}: Add a regression test for @ref{be,,re} exponentional slowdown when
using rjsmin.

@item 
gh-91330@footnote{https://github.com/python/cpython/issues/91330}: Added more tests for @ref{33,,dataclasses} to cover behavior with
data descriptor-based fields.

@item 
gh-94208@footnote{https://github.com/python/cpython/issues/94208}: @code{test_ssl} is now checking for supported TLS version and
protocols in more tests.

@item 
gh-94315@footnote{https://github.com/python/cpython/issues/94315}: Tests now check for DAC override capability instead of relying
on @ref{1b72,,os.geteuid()}.

@item 
gh-54781@footnote{https://github.com/python/cpython/issues/54781}: Rename test_tk to test_tkinter, and rename test_ttk_guionly to
test_ttk. Patch by Victor Stinner.

@item 
gh-93839@footnote{https://github.com/python/cpython/issues/93839}: Move @code{Lib/ctypes/test/} to @code{Lib/test/test_ctypes/}. Patch by
Victor Stinner.

@item 
gh-93951@footnote{https://github.com/python/cpython/issues/93951}: In test_bdb.StateTestCase.test_skip, avoid including auxiliary
importers.

@item 
gh-93957@footnote{https://github.com/python/cpython/issues/93957}: Provide nicer error reporting from subprocesses in
test_venv.EnsurePipTest.test_with_pip.

@item 
gh-93884@footnote{https://github.com/python/cpython/issues/93884}: Add test cases for @ref{1b73,,PyNumber_ToBase()} that take a large
number or a non-int object as parameter.

@item 
gh-93852@footnote{https://github.com/python/cpython/issues/93852}: test_asyncio, test_logging, test_socket and test_socketserver
now create AF_UNIX domains in the current directory to no longer fail with
@code{OSError("AF_UNIX path too long")} if the temporary directory (the
@geindex TMPDIR
@geindex 環境変数; TMPDIR
@code{TMPDIR} environment variable) is too long. Patch by Victor
Stinner.

@item 
gh-93353@footnote{https://github.com/python/cpython/issues/93353}: regrtest now checks if a test leaks temporary files or
directories if run with -jN option. Patch by Victor Stinner.

@item 
gh-84461@footnote{https://github.com/python/cpython/issues/84461}: @code{run_tests.py} now handles cross compiling env vars correctly
and pass @code{HOSTRUNNER} to regression tests.

@item 
gh-93616@footnote{https://github.com/python/cpython/issues/93616}: @code{test_modulefinder} now creates a temporary directory in
@code{ModuleFinderTest.setUp()} instead of module scope.

@item 
gh-93575@footnote{https://github.com/python/cpython/issues/93575}: Fix issue with test_unicode test_raiseMemError. The test case
now use @code{test.support.calcobjsize} to calculate size of PyUnicode
structs. @ref{1adb,,sys.getsizeof()} may return different size when string has
UTF-8 memory.

@item 
gh-90473@footnote{https://github.com/python/cpython/issues/90473}: WASI does not have a @code{chmod(2)} syscall. @ref{529,,os.chmod()} is
now a dummy function on WASI. Skip all tests that depend on working
@ref{529,,os.chmod()}.

@item 
gh-90473@footnote{https://github.com/python/cpython/issues/90473}: Skip tests on WASI that require symlinks with absolute paths.

@item 
gh-57539@footnote{https://github.com/python/cpython/issues/57539}: Increase calendar test coverage for
@code{calendar.LocaleTextCalendar.formatweekday()}.

@item 
gh-90473@footnote{https://github.com/python/cpython/issues/90473}: Skip symlink tests on WASI. wasmtime uses @code{openat2(2)} with
@code{RESOLVE_BENEATH} flag, which prevents symlinks with absolute paths.

@item 
gh-89858@footnote{https://github.com/python/cpython/issues/89858}: Fix @code{test_embed} for out-of-tree builds. Patch by Kumar
Aditya.

@item 
gh-92886@footnote{https://github.com/python/cpython/issues/92886}: Fixing tests that fail when running with optimizations (@code{-O})
in @code{test_imaplib.py}.

@item 
gh-92886@footnote{https://github.com/python/cpython/issues/92886}: Fixing tests that fail when running with optimizations (@code{-O})
in @code{test_zipimport.py}

@item 
gh-92886@footnote{https://github.com/python/cpython/issues/92886}: Fixing tests that fail when running with optimizations (@code{-O})
in @code{test_py_compile.py}

@item 
gh-92886@footnote{https://github.com/python/cpython/issues/92886}: Fixing tests that fail when running with optimizations (@code{-O})
in @code{test_sys_settrace.py}.

@item 
gh-92886@footnote{https://github.com/python/cpython/issues/92886}: Fixing tests that fail when running with optimizations (@code{-O})
in @code{_test_multiprocessing.py}

@item 
gh-92670@footnote{https://github.com/python/cpython/issues/92670}: Skip @code{test_shutil.TestCopy.test_copyfile_nonexistent_dir} test
on AIX as the test uses a trailing slash to force the OS consider the path
as a directory, but on AIX the trailing slash has no effect and is
considered as a file.

@item 
gh-92514@footnote{https://github.com/python/cpython/issues/92514}: Remove unused @code{test.support.BasicTestRunner}. Patch by Jelle
Zijlstra.

@item 
bpo-47016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47016}: Create a GitHub Actions workflow for verifying bundled pip and
setuptools. Patch by Illia Volochii and Adam Turner.
@end itemize

@node ビルド<32>,Windows<29>,テスト<27>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id384}@anchor{1b74}
@subsubsection ビルド



@itemize -

@item 
gh-96761@footnote{https://github.com/python/cpython/issues/96761}: Fix the build process of clang compiler for
@code{_bootstrap_python} if LTO optimization is applied. Patch by
Matthias Görgens and Donghee Na.

@item 
gh-96883@footnote{https://github.com/python/cpython/issues/96883}: @code{wasm32-emscripten} builds for browsers now include
@ref{24,,concurrent.futures} for @ref{b,,asyncio} and @ref{10d,,unittest.mock}.

@item 
gh-85936@footnote{https://github.com/python/cpython/issues/85936}: CPython now uses the ThinLTO option as the default policy if the
Clang compiler accepts the flag. Patch by Donghee Na.

@item 
gh-96729@footnote{https://github.com/python/cpython/issues/96729}: Ensure that Windows releases built with
@code{Tools\msi\buildrelease.bat} are upgradable to and from official Python
releases.

@item 
gh-96269@footnote{https://github.com/python/cpython/issues/96269}: Shared module targets now depend on new @code{MODULE_DEPS}
variable, which includes @code{EXPORTSYMS}. This fixes a build order issue on
unsupported AIX platform.

@item 
gh-84461@footnote{https://github.com/python/cpython/issues/84461}: @code{wasm32-emscripten} platform no longer builds @ref{c1,,resource}
module, @ref{152d,,getresuid()}, @ref{152c,,getresgid()}, and their setters.
The APIs are stubs and not functional.

@item 
gh-95973@footnote{https://github.com/python/cpython/issues/95973}: Add a new @code{--with-dsymutil} configure option to link debug
information in macOS. Patch by Pablo Galindo.

@item 
gh-90536@footnote{https://github.com/python/cpython/issues/90536}: Use the BOLT post-link optimizer to improve performance,
particularly on medium-to-large applications.

@item 
gh-93744@footnote{https://github.com/python/cpython/issues/93744}: Remove the @code{configure --with-cxx-main} build option: it didn't
work for many years. Remove the @code{MAINCC} variable from @code{configure} and
@code{Makefile}. Patch by Victor Stinner.

@item 
gh-94801@footnote{https://github.com/python/cpython/issues/94801}: Fix a regression in @code{configure} script that caused some header
checks to ignore custom @code{CPPFLAGS}. The regression was introduced in
gh-94802@footnote{https://github.com/python/cpython/issues/94802}.

@item 
gh-95145@footnote{https://github.com/python/cpython/issues/95145}: wasm32-wasi builds no longer depend on WASIX's pthread stubs.
Python now has its own stubbed pthread API.

@item 
gh-95174@footnote{https://github.com/python/cpython/issues/95174}: Python now detects missing @code{dup} function in WASI and works
around some missing @ref{5b,,errno}, @ref{c6,,select}, and @ref{d1,,socket}
constants.

@item 
gh-95174@footnote{https://github.com/python/cpython/issues/95174}: Python now skips missing @ref{d1,,socket} functions and methods on
WASI. WASI can only create sockets from existing fd / accept and has no
netdb.

@item 
gh-95085@footnote{https://github.com/python/cpython/issues/95085}: Platforms @code{wasm32-unknown-emscripten} and
@code{wasm32-unknown-wasi} have been promoted to 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} tier 3 platform
support.

@item 
gh-94847@footnote{https://github.com/python/cpython/issues/94847}: Fixed @code{_decimal} module build issue on GCC when compiling with
LTO and pydebug. Debug builds no longer force inlining of functions.

@item 
gh-94841@footnote{https://github.com/python/cpython/issues/94841}: Fix the possible performance regression of
@ref{e60,,PyObject_Free()} compiled with MSVC version 1932.

@item 
gh-94801@footnote{https://github.com/python/cpython/issues/94801}: @code{configure} now uses custom flags like @code{ZLIB_CFLAGS} and
@code{ZLIB_LIBS} when searching for headers and libraries.

@item 
gh-94773@footnote{https://github.com/python/cpython/issues/94773}: @code{deepfreeze.py} now supports code object with frozensets that
contain incompatible, unsortable types.

@item 
gh-94682@footnote{https://github.com/python/cpython/issues/94682}: Build and test with OpenSSL 1.1.1q

@item 
gh-90005@footnote{https://github.com/python/cpython/issues/90005}: Dependencies of @ref{bf,,readline} and @ref{2f,,curses} module are now
detected in @code{configure} script with @code{pkg-config}. Only @code{ncurses} /
@code{ncursesw} are detected automatically. The old @code{curses} library is not
configured automatically. Workaround for missing @code{termcap} or @code{tinfo}
library has been removed.

@item 
gh-90005@footnote{https://github.com/python/cpython/issues/90005}: Fix building @code{_ctypes} extension without @code{pkg-config}.

@item 
gh-90005@footnote{https://github.com/python/cpython/issues/90005}: @code{_dbm} module dependencies are now detected by configure.

@item 
gh-94404@footnote{https://github.com/python/cpython/issues/94404}: @code{makesetup} now works around an issue with sed on macOS and
uses correct CFLAGS for object files that end up in a shared extension.
Module CFLAGS are used before PY_STDMODULE_CFLAGS to avoid clashes with
system headers.

@item 
gh-93939@footnote{https://github.com/python/cpython/issues/93939}: C extension modules are now built by @code{configure} and @code{make}
instead of @code{distutils} and @code{setup.py}.

@item 
gh-93939@footnote{https://github.com/python/cpython/issues/93939}: The @code{2to3}, @code{idle}, and @code{pydoc} scripts are now generated
and installed by @code{Makefile} instead of @code{setup.py}.

@item 
gh-94280@footnote{https://github.com/python/cpython/issues/94280}: Updated pegen regeneration script on Windows to find and use
Python 3.9 or higher.  Prior to this, pegen regeneration already required
3.9 or higher, but the script may have used lower versions of Python.

@item 
gh-93584@footnote{https://github.com/python/cpython/issues/93584}: Address race condition in @code{Makefile} when installing a PGO
build. All @code{test} and @code{install} targets now depend on @code{all} target.

@item 
gh-93491@footnote{https://github.com/python/cpython/issues/93491}: @code{configure} now detects and reports 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} support tiers.

@item 
gh-69093@footnote{https://github.com/python/cpython/issues/69093}: Fix @code{Modules/Setup.stdlib.in} rule for @code{_sqlite3} extension.

@item 
gh-93207@footnote{https://github.com/python/cpython/issues/93207}: @code{va_start()} with two parameters, like @code{va_start(args,
format),} is now required to build Python. @code{va_start()} is no longer
called with a single parameter. Patch by Kumar Aditya.

@item 
gh-93202@footnote{https://github.com/python/cpython/issues/93202}: Python now always use the @code{%zu} and @code{%zd} printf formats to
format a @code{size_t} or @code{Py_ssize_t} number. Building Python 3.12
requires a C11 compiler, so these printf formats are now always supported.
Patch by Victor Stinner.

@item 
gh-90473@footnote{https://github.com/python/cpython/issues/90473}: Disable pymalloc and increase stack size on @code{wasm32-wasi}.

@item 
bpo-34449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34449}: Drop invalid compiler switch @code{-fPIC} for HP aCC on HP-UX.
Patch by Michael Osipov.
@end itemize

@node Windows<29>,macOS<20>,ビルド<32>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id385}@anchor{1b75}
@subsubsection Windows



@itemize -

@item 
gh-98360@footnote{https://github.com/python/cpython/issues/98360}: Fixes @ref{98,,multiprocessing} spawning child processes on Windows
from a virtual environment to ensure that child processes that also use
@ref{98,,multiprocessing} to spawn more children will recognize that they are
in a virtual environment.

@item 
gh-98414@footnote{https://github.com/python/cpython/issues/98414}: Fix @code{py.exe} launcher handling of @code{-V:@var{<company>}/}
option when default preferences have been set in environment variables or
configuration files.

@item 
gh-97728@footnote{https://github.com/python/cpython/issues/97728}: Fix possible crashes caused by the use of uninitialized
variables when pass invalid arguments in @ref{1676,,os.system()} on Windows and
in Windows-specific modules (like @code{winreg}).

@item 
gh-90989@footnote{https://github.com/python/cpython/issues/90989}: Made @ref{7da,,Python install manager} install per-user by default (unless an all
users install already exists), and clarify some text in the installer.

@item 
gh-97649@footnote{https://github.com/python/cpython/issues/97649}: The @code{Tools} directory is no longer installed on Windows

@item 
gh-96965@footnote{https://github.com/python/cpython/issues/96965}: Update libffi to 3.4.3

@item 
gh-96577@footnote{https://github.com/python/cpython/issues/96577}: Fixes a potential buffer overrun in @code{msilib}.

@item 
gh-96559@footnote{https://github.com/python/cpython/issues/96559}: Fixes the Windows launcher not using the compatible
interpretation of default tags found in configuration files when no tag
was passed to the command.

@item 
gh-94781@footnote{https://github.com/python/cpython/issues/94781}: Fix @code{pcbuild.proj} to clean previous instances of output
files in @code{Python\deepfreeze} and @code{Python\frozen_modules} directories
on Windows. Patch by Charlie Zhao.

@item 
gh-89545@footnote{https://github.com/python/cpython/issues/89545}: Updates @ref{af,,platform} code getting the Windows version to use
native Windows Management Instrumentation (WMI) queries to determine OS
version, type, and architecture.

@item 
gh-95733@footnote{https://github.com/python/cpython/issues/95733}: Make certain requirements of the Windows Store package optional
to allow installing on earlier updates of Windows.

@item 
gh-95656@footnote{https://github.com/python/cpython/issues/95656}: Enable the @ref{a3f,,enable_load_extension()}
@ref{d4,,sqlite3} API.

@item 
gh-95587@footnote{https://github.com/python/cpython/issues/95587}: Fixes some issues where the Windows installer would incorrectly
detect certain features of an existing install when upgrading.

@item 
gh-94399@footnote{https://github.com/python/cpython/issues/94399}: Restores the behaviour of @ref{7da,,Python install manager} for @code{/usr/bin/env}
shebang lines, which will now search 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} for an executable
matching the given command. If none is found, the usual search process is
used.

@item 
gh-95445@footnote{https://github.com/python/cpython/issues/95445}: Fixes the unsuccessful removal of the HTML document directory
when uninstalling with Windows msi.

@item 
gh-95359@footnote{https://github.com/python/cpython/issues/95359}: Fix @ref{7da,,Python install manager} handling of @code{py.ini} commands (it was
incorrectly expecting a @code{py_} prefix on keys) and crashes when reading
per-user configuration file.

@item 
gh-95285@footnote{https://github.com/python/cpython/issues/95285}: Fix @ref{7da,,Python install manager} handling of command lines where it is only
passed a short executable name.

@item 
gh-90844@footnote{https://github.com/python/cpython/issues/90844}: Allow virtual environments to correctly launch when they have
spaces in the path.

@item 
gh-94772@footnote{https://github.com/python/cpython/issues/94772}: Fix incorrect handling of shebang lines in py.exe launcher

@item 
gh-94018@footnote{https://github.com/python/cpython/issues/94018}: @ref{137,,zipfile} will now remove trailing spaces from path
components when extracting files on Windows.

@item 
gh-93824@footnote{https://github.com/python/cpython/issues/93824}: Drag and drop of files onto Python files in Windows Explorer has
been enabled for Windows ARM64.

@item 
gh-43414@footnote{https://github.com/python/cpython/issues/43414}: @ref{131a,,os.get_terminal_size()} now attempts to read the size from
any provided handle, rather than only supporting file descriptors 0, 1 and
2.

@item 
gh-92817@footnote{https://github.com/python/cpython/issues/92817}: Ensures that @code{py.exe} will prefer an active virtual
environment over default tags specified with environment variables or
through a @code{py.ini} file.

@item 
gh-92984@footnote{https://github.com/python/cpython/issues/92984}: Explicitly disable incremental linking for non-Debug builds

@item 
gh-92841@footnote{https://github.com/python/cpython/issues/92841}: @ref{b,,asyncio} no longer throws @code{RuntimeError: Event loop is
closed} on interpreter exit after asynchronous socket activity. Patch by
Oleg Iarygin.

@item 
bpo-46907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46907}: Update Windows installer to use SQLite 3.38.4.

@item 
gh-91061@footnote{https://github.com/python/cpython/issues/91061}: Accept os.PathLike for the argument to winsound.PlaySound

@item 
bpo-42658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42658}: Support native Windows case-insensitive path comparisons by
using @code{LCMapStringEx} instead of @ref{1b76,,str.lower()} in
@code{ntpath.normcase()}. Add @code{LCMapStringEx} to the @code{_winapi}
module.

@item 
bpo-38704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38704}: Prevent installation on unsupported Windows versions.
@end itemize

@node macOS<20>,IDLE<15>,Windows<29>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id386}@anchor{1b77}
@subsubsection macOS



@itemize -

@item 
gh-97897@footnote{https://github.com/python/cpython/issues/97897}: The macOS 13 SDK includes support for the @code{mkfifoat} and
@code{mknodat} system calls. Using the @code{dir_fd} option with either
@ref{f90,,os.mkfifo()} or @ref{f91,,os.mknod()} could result in a segfault if
cpython is built with the macOS 13 SDK but run on an earlier version of
macOS. Prevent this by adding runtime support for detection of these
system calls ("weaklinking") as is done for other newer syscalls on macOS.
@end itemize

@node IDLE<15>,Tools/Demos<24>,macOS<20>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id387}@anchor{1b78}
@subsubsection IDLE



@itemize -

@item 
gh-97527@footnote{https://github.com/python/cpython/issues/97527}: Fix a bug in the previous bugfix that caused IDLE to not start
when run with 3.10.8, 3.12.0a1, and at least Microsoft Python 3.10.2288.0
installed without the Lib/test package.  3.11.0 was never affected.

@item 
gh-65802@footnote{https://github.com/python/cpython/issues/65802}: Document handling of extensions in Save As dialogs.

@item 
gh-95191@footnote{https://github.com/python/cpython/issues/95191}: Include prompts when saving Shell (interactive input and
output).

@item 
gh-95511@footnote{https://github.com/python/cpython/issues/95511}: Fix the Shell context menu copy-with-prompts bug of copying an
extra line when one selects whole lines.

@item 
gh-95471@footnote{https://github.com/python/cpython/issues/95471}: In the Edit menu, move @code{Select All} and add a new separator.

@item 
gh-95411@footnote{https://github.com/python/cpython/issues/95411}: Enable using IDLE's module browser with .pyw files.

@item 
gh-89610@footnote{https://github.com/python/cpython/issues/89610}: Add .pyi as a recognized extension for IDLE on macOS.    This
allows opening stub files by double clicking on them in the Finder.
@end itemize

@node Tools/Demos<24>,C API<29>,IDLE<15>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id388}@anchor{1b79}
@subsubsection Tools/Demos



@itemize -

@item 
gh-68686@footnote{https://github.com/python/cpython/issues/68686}: Remove ptags and eptags scripts.

@item 
gh-97681@footnote{https://github.com/python/cpython/issues/97681}: Remove the @code{Tools/demo/} directory which contained old demo
scripts. A copy can be found in the old-demos project@footnote{https://github.com/gvanrossum/old-demos}.  Patch by Victor Stinner.

@item 
gh-97669@footnote{https://github.com/python/cpython/issues/97669}: Remove outdated example scripts of the @code{Tools/scripts/}
directory. A copy can be found in the old-demos project@footnote{https://github.com/gvanrossum/old-demos}. Patch by Victor Stinner.

@item 
gh-95853@footnote{https://github.com/python/cpython/issues/95853}: The @code{wasm_build.py} script now pre-builds Emscripten ports,
checks for broken EMSDK versions, and warns about pkg-config env vars.

@item 
gh-95853@footnote{https://github.com/python/cpython/issues/95853}: The new tool @code{Tools/wasm/wasm_builder.py} automates configure,
compile, and test steps for building CPython on WebAssembly platforms.

@item 
gh-95731@footnote{https://github.com/python/cpython/issues/95731}: Fix handling of module docstrings in
@code{Tools/i18n/pygettext.py}.

@item 
gh-93939@footnote{https://github.com/python/cpython/issues/93939}: Add script @code{Tools/scripts/check_modules.py} to check and
validate builtin and shared extension modules. The script also handles
@code{Modules/Setup} and will eventually replace @code{setup.py}.

@item 
gh-94538@footnote{https://github.com/python/cpython/issues/94538}: Fix Argument Clinic output to custom file destinations. Patch by
Erlend E. Aasland.

@item 
gh-94430@footnote{https://github.com/python/cpython/issues/94430}: Allow parameters named @code{module} and @code{self} with custom C
names in Argument Clinic. Patch by Erlend E. Aasland

@item 
gh-86087@footnote{https://github.com/python/cpython/issues/86087}: The @code{Tools/scripts/parseentities.py} script used to parse
HTML4 entities has been removed.
@end itemize

@node C API<29>,,Tools/Demos<24>,Python 3 12 0 alpha 1
@anchor{whatsnew/changelog id390}@anchor{1b7a}
@subsubsection C API



@itemize -

@item 
gh-98393@footnote{https://github.com/python/cpython/issues/98393}: The @ref{797,,PyUnicode_FSDecoder()} function no longer accepts
bytes-like paths, like @ref{344,,bytearray} and @ref{165,,memoryview} types:
only the exact @ref{192,,bytes} type is accepted for bytes strings. Patch by
Victor Stinner.

@item 
gh-91051@footnote{https://github.com/python/cpython/issues/91051}: Add @ref{786,,PyType_Watch()} and related APIs to allow callbacks
on @ref{1b7b,,PyType_Modified()}.

@item 
gh-95756@footnote{https://github.com/python/cpython/issues/95756}: Lazily create and cache @code{co_} attributes for better
performance for code getters.

@item 
gh-96512@footnote{https://github.com/python/cpython/issues/96512}: Configuration for the @ref{80b,,integer string conversion length limitation} now lives in the PyConfig C API struct.

@item 
gh-95589@footnote{https://github.com/python/cpython/issues/95589}: Extensions classes that set @code{tp_dictoffset} and
@code{tp_weaklistoffset} lose the support for multiple inheritance, but are
now safe. Extension classes should use @ref{60f,,Py_TPFLAGS_MANAGED_DICT}
and @ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF} instead.

@item 
gh-95781@footnote{https://github.com/python/cpython/issues/95781}: An unrecognized format character in
@ref{62b,,PyUnicode_FromFormat()} and @ref{794,,PyUnicode_FromFormatV()} now
sets a @ref{795,,SystemError}. In previous versions it caused all the rest of
the format string to be copied as-is to the result string, and any extra
arguments discarded.

@item 
gh-92678@footnote{https://github.com/python/cpython/issues/92678}: Restore the 3.10 behavior for multiple inheritance of C
extension classes that store their dictionary at the end of the struct.

@item 
gh-92678@footnote{https://github.com/python/cpython/issues/92678}: Support C extensions using managed dictionaries by setting the
@code{Py_TPFLAGS_MANAGED_DICT} flag.

@item 
gh-93274@footnote{https://github.com/python/cpython/issues/93274}: API for implementing vectorcall
(@ref{776,,Py_TPFLAGS_HAVE_VECTORCALL}, @ref{777,,PyVectorcall_NARGS()} and
@ref{778,,PyVectorcall_Call()}) was added to the limited API and stable ABI.

@item 
gh-95504@footnote{https://github.com/python/cpython/issues/95504}: Fix sign placement when specifying width or precision in
@ref{62b,,PyUnicode_FromFormat()} and @ref{794,,PyUnicode_FromFormatV()}. Patch
by Philip Georgi.

@item 
gh-93012@footnote{https://github.com/python/cpython/issues/93012}: The @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag is now removed
from a class when the class's @ref{77a,,__call__()} method is
reassigned. This makes vectorcall safe to use with mutable types (i.e.
heap types without the @code{immutable}
flag). Mutable types that do not override
@ref{77b,,tp_call} now inherit the
@ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag.

@item 
gh-95388@footnote{https://github.com/python/cpython/issues/95388}: Creating @ref{3cf,,immutable types}
with mutable bases is deprecated and is planned to be disabled in Python
3.14.

@item 
gh-92678@footnote{https://github.com/python/cpython/issues/92678}: Adds unstable C-API functions @code{_PyObject_VisitManagedDict} and
@code{_PyObject_ClearManagedDict} to allow C extensions to allow the VM to
manage their object's dictionaries.

@item 
gh-94936@footnote{https://github.com/python/cpython/issues/94936}: Added @ref{97d,,PyCode_GetVarnames()}, @ref{97e,,PyCode_GetCellvars()}
and @ref{97f,,PyCode_GetFreevars()} for accessing @code{co_varnames},
@code{co_cellvars} and @code{co_freevars} respectively via the C API.

@item 
gh-94930@footnote{https://github.com/python/cpython/issues/94930}: Fix @code{SystemError} raised when
@ref{624,,PyArg_ParseTupleAndKeywords()} is used with @code{#} in @code{(...)} but
without @code{PY_SSIZE_T_CLEAN} defined.

@item 
gh-94731@footnote{https://github.com/python/cpython/issues/94731}: Python again uses C-style casts for most casting operations when
compiled with C++. This may trigger compiler warnings, if they are enabled
with e.g. @code{-Wold-style-cast} or @code{-Wzero-as-null-pointer-constant}
options for @code{g++}.

@item 
gh-93937@footnote{https://github.com/python/cpython/issues/93937}: The following frame functions and type are now directly
available with @code{#include <Python.h>}, it's no longer needed to add
@code{#include <frameobject.h>}:


@itemize *

@item 
@ref{988,,PyFrame_Check()}

@item 
@ref{989,,PyFrame_GetBack()}

@item 
@ref{96f,,PyFrame_GetBuiltins()}

@item 
@ref{970,,PyFrame_GetGenerator()}

@item 
@ref{971,,PyFrame_GetGlobals()}

@item 
@ref{972,,PyFrame_GetLasti()}

@item 
@ref{661,,PyFrame_GetLocals()}

@item 
@ref{98a,,PyFrame_Type}
@end itemize

Patch by Victor Stinner.

@item 
gh-91321@footnote{https://github.com/python/cpython/issues/91321}: Fix the compatibility of the Python C API with C++ older than
C++11. Patch by Victor Stinner.

@item 
gh-91731@footnote{https://github.com/python/cpython/issues/91731}: Avoid defining the @code{static_assert} when compiling with C++ 11,
where this is a keyword and redefining it can lead to undefined behavior.
Patch by Pablo Galindo

@item 
gh-89546@footnote{https://github.com/python/cpython/issues/89546}: @ref{772,,PyType_FromMetaclass()} (and other @code{PyType_From*}
functions) now check that offsets and the base class's
@ref{b7e,,tp_basicsize} fit in the new class's
@code{tp_basicsize}.

@item 
gh-93503@footnote{https://github.com/python/cpython/issues/93503}: Add two new public functions to the public C-API,
@ref{781,,PyEval_SetProfileAllThreads()} and
@ref{664,,PyEval_SetTraceAllThreads()}, that allow to set tracing and
profiling functions in all running threads in addition to the calling one.
Also, two analogous functions to the @ref{f3,,threading} module
(@ref{6f0,,threading.setprofile_all_threads()} and
@ref{6ef,,threading.settrace_all_threads()}) that allow to do the same from
Python. Patch by Pablo Galindo

@item 
gh-93442@footnote{https://github.com/python/cpython/issues/93442}: Add C++ overloads for _Py_CAST_impl() to handle 0/NULL.  This
will allow C++ extensions that pass 0 or NULL to macros using _Py_CAST()
to continue to compile.

@item 
gh-93466@footnote{https://github.com/python/cpython/issues/93466}: Slot IDs in PyType_Spec may not be repeated. The documentation
was updated to mention this. For some cases of repeated slots,
PyType_FromSpec and related functions will now raise an exception.

@item 
gh-92898@footnote{https://github.com/python/cpython/issues/92898}: Fix C++ compiler warnings when casting function arguments to
@code{PyObject*}. Patch by Serge Guelton.

@item 
gh-93103@footnote{https://github.com/python/cpython/issues/93103}: Deprecate global configuration variables, like
@ref{40a,,Py_IgnoreEnvironmentFlag}, in the documentation: the
@ref{3f6,,Py_InitializeFromConfig()} API should be instead. Patch by Victor
Stinner.

@item 
gh-77782@footnote{https://github.com/python/cpython/issues/77782}: Deprecate global configuration variable like
@ref{40a,,Py_IgnoreEnvironmentFlag}: the @ref{3f6,,Py_InitializeFromConfig()}
API should be instead. Patch by Victor Stinner.

@item 
gh-92913@footnote{https://github.com/python/cpython/issues/92913}: Ensures changes to @ref{643,,PyConfig.module_search_paths} are
ignored unless @ref{805,,PyConfig.module_search_paths_set} is set

@item 
gh-92781@footnote{https://github.com/python/cpython/issues/92781}: Avoid mixing declarations and code in the C API to fix the
compiler warning: "ISO C90 forbids mixed declarations and code"
[-Werror=declaration-after-statement]. Patch by Victor Stinner.

@item 
gh-92651@footnote{https://github.com/python/cpython/issues/92651}: Remove the @code{token.h} header file. There was never any public
tokenizer C API. The @code{token.h} header file was only designed to be used
by Python internals. Patch by Victor Stinner.

@item 
gh-92536@footnote{https://github.com/python/cpython/issues/92536}: Remove legacy Unicode APIs based on @code{Py_UNICODE*}.

@item 
gh-85858@footnote{https://github.com/python/cpython/issues/85858}: Remove the @code{PyUnicode_InternImmortal()} function and the
@code{SSTATE_INTERNED_IMMORTAL} macro. Patch by Victor Stinner.

@item 
gh-92193@footnote{https://github.com/python/cpython/issues/92193}: Add new function @ref{782,,PyFunction_SetVectorcall()} to the C API
which sets the vectorcall field of a given @ref{783,,PyFunctionObject}.

Warning: extensions using this API must preserve the behavior of the
unaltered function!

@item 
gh-59121@footnote{https://github.com/python/cpython/issues/59121}: Fixed an assert that prevented @code{PyRun_InteractiveOne} from
providing tracebacks when parsing from the provided FD.

@item 
bpo-45383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45383}: The @ref{79d,,PyType_FromSpec()} API will now find and use a
metaclass based on the provided bases. An error will be raised if there is
a metaclass conflict.
@end itemize

@node Python 3 11 0 beta 1,Python 3 11 0 alpha 7,Python 3 12 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-11-0-beta-1}@anchor{1b7c}
@subsection Python 3.11.0 beta 1


`Release date: 2022-05-06'

@menu
* セキュリティ: セキュリティ<28>. 
* Core and Builtins: Core and Builtins<84>. 
* ライブラリ: ライブラリ<88>. 
* Core and Builtins: Core and Builtins<85>. 
* ビルド: ビルド<33>. 
* Core and Builtins: Core and Builtins<86>. 
* ライブラリ: ライブラリ<89>. 
* ドキュメント: ドキュメント<29>. 
* テスト: テスト<28>. 
* ビルド: ビルド<34>. 
* Windows: Windows<30>. 
* macOS: macOS<21>. 
* Tools/Demos: Tools/Demos<25>. 
* C API: C API<30>. 

@end menu

@node セキュリティ<28>,Core and Builtins<84>,,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id391}@anchor{1b7d}
@subsubsection セキュリティ



@itemize -

@item 
gh-57684@footnote{https://github.com/python/cpython/issues/57684}: Add the @ref{7c1,,-P} command line option and the
@geindex PYTHONSAFEPATH
@geindex 環境変数; PYTHONSAFEPATH
@ref{7c2,,PYTHONSAFEPATH} environment variable to not prepend a potentially
unsafe path to @ref{3e4,,sys.path}. Patch by Victor Stinner.
@end itemize

@node Core and Builtins<84>,ライブラリ<88>,セキュリティ<28>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id392}@anchor{1b7e}
@subsubsection Core and Builtins



@itemize -

@item 
gh-89519@footnote{https://github.com/python/cpython/issues/89519}: Chaining classmethod descriptors (introduced in bpo-19072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19072}) is
deprecated. It can no longer be used to wrap other descriptors such as
property().  The core design of this feature was flawed, and it caused a
number of downstream problems.

@item 
gh-92345@footnote{https://github.com/python/cpython/issues/92345}: @code{pymain_run_python()} now imports @code{readline} and
@code{rlcompleter} before sys.path is extended to include the current working
directory of an interactive interpreter. Non-interactive interpreters are
not affected.

@item 
bpo-43857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43857}: Improve the @ref{5f0,,AttributeError} message when deleting a
missing attribute. Patch by Géry Ogam.

@item 
gh-92245@footnote{https://github.com/python/cpython/issues/92245}: Make sure that PEP 523 is respected in all cases. In 3.11a7,
specialization may have prevented Python-to-Python calls respecting PEP
523.

@item 
gh-92203@footnote{https://github.com/python/cpython/issues/92203}: Add a closure keyword-only parameter to @ref{4a2,,exec()}. It can
only be specified when exec-ing a code object that uses free variables.
When specified, it must be a tuple, with exactly the number of cell
variables referenced by the code object. closure has a default value of
@code{None}, and it must be @code{None} if the code object doesn't refer to any
free variables.

@item 
gh-91173@footnote{https://github.com/python/cpython/issues/91173}: Disable frozen modules in debug builds. Patch by Kumar Aditya.

@item 
gh-92114@footnote{https://github.com/python/cpython/issues/92114}: Improve error message when subscript a type with
@code{__class_getitem__} set to @code{None}.

@item 
gh-92112@footnote{https://github.com/python/cpython/issues/92112}: Fix crash triggered by an evil custom @code{mro()} on a metaclass.

@item 
gh-92063@footnote{https://github.com/python/cpython/issues/92063}: The @code{PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS} instruction
now ensures methods are called only on objects of the correct type.

@item 
gh-92031@footnote{https://github.com/python/cpython/issues/92031}: Deoptimize statically allocated code objects during
@code{Py_FINALIZE()} so that future @code{_PyCode_Quicken} calls always start
with unquickened code.

@item 
gh-92036@footnote{https://github.com/python/cpython/issues/92036}: Fix a crash in subinterpreters related to the garbage collector.
When a subinterpreter is deleted, untrack all objects tracked by its GC.
To prevent a crash in deallocator functions expecting objects to be
tracked by the GC, leak a strong reference to these objects on purpose, so
they are never deleted and their deallocator functions are not called.
Patch by Victor Stinner.

@item 
gh-92032@footnote{https://github.com/python/cpython/issues/92032}: The interpreter can now autocomplete soft keywords, as of now
@code{match}, @code{case}, and @code{_} (wildcard pattern) from 
@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/}.

@item 
gh-87999@footnote{https://github.com/python/cpython/issues/87999}: The warning emitted by the Python parser for a numeric literal
immediately followed by keyword has been changed from deprecation warning
to syntax warning.

@item 
gh-91869@footnote{https://github.com/python/cpython/issues/91869}: Fix an issue where specialized opcodes with extended arguments
could produce incorrect tracing output or lead to assertion failures.

@item 
gh-91603@footnote{https://github.com/python/cpython/issues/91603}: Speed up @ref{2a7,,types.UnionType} instantiation. Based on patch
provided by Yurii Karabas.

@item 
gh-89373@footnote{https://github.com/python/cpython/issues/89373}: If Python is built in debug mode, Python now ensures that
deallocator functions leave the current exception unchanged. Patch by
Victor Stinner.

@item 
gh-91632@footnote{https://github.com/python/cpython/issues/91632}: Fix a minor memory leak at exit: release the memory of the
@code{generic_alias_iterator} type. Patch by Donghee Na.

@item 
gh-81548@footnote{https://github.com/python/cpython/issues/81548}: Octal escapes with value larger than @code{0o377} now produce a
@ref{1a3,,DeprecationWarning}. In a future Python version they will be a
@ref{1ae,,SyntaxWarning} and eventually a @ref{18e,,SyntaxError}.

@item 
bpo-43950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43950}: Use a single compact table for line starts, ends and column
offsets. Reduces memory consumption for location info by half

@item 
gh-91102@footnote{https://github.com/python/cpython/issues/91102}: Use Argument Clinic for @code{EncodingMap}.  Patch by Oleg
Iarygin.

@item 
gh-91636@footnote{https://github.com/python/cpython/issues/91636}: Fixed a crash in a garbage-collection edge-case, in which a
@code{PyFunction_Type.tp_clear} function could leave a python function object
in an inconsistent state.

@item 
gh-91603@footnote{https://github.com/python/cpython/issues/91603}: Speed up @ref{2ad,,isinstance()} and @ref{9c4,,issubclass()} checks for
@ref{2a7,,types.UnionType}. Patch by Yurii Karabas.

@item 
gh-91625@footnote{https://github.com/python/cpython/issues/91625}: Fixed a bug in which adaptive opcodes ignored any preceding
@code{EXTENDED_ARG}s on specialization failure.

@item 
gh-78607@footnote{https://github.com/python/cpython/issues/78607}: The LLTRACE special build now looks for the name @code{__lltrace__}
defined in module globals, rather than the name @code{__ltrace__}, which had
been introduced as a typo.

@item 
gh-91576@footnote{https://github.com/python/cpython/issues/91576}: Speed up iteration of ascii strings by 50%. Patch by Kumar
Aditya.

@item 
gh-89279@footnote{https://github.com/python/cpython/issues/89279}: Improve interpreter performance on Windows by inlining a few
specific macros.

@item 
gh-91502@footnote{https://github.com/python/cpython/issues/91502}: Add a new @code{_PyFrame_IsEntryFrame()} API function, to
check if a @ref{98c,,PyFrameObject} is an entry frame. Patch by Pablo
Galindo.

@item 
gh-91266@footnote{https://github.com/python/cpython/issues/91266}: Refactor the @code{bytearray} strip methods @code{strip}, @code{lstrip}
and @code{rstrip} to use a common implementation.

@item 
gh-91479@footnote{https://github.com/python/cpython/issues/91479}: Replaced the @code{__note__} field of @ref{7d6,,BaseException} (added
in an earlier version of 3.11) with the final design of 
@geindex Python Enhancement Proposals; PEP 678
PEP 678@footnote{https://peps.python.org/pep-0678/}.
Namely, @ref{7d6,,BaseException} gets an @code{add_note()} method, and its
@code{__notes__} field is created when necessary.

@item 
gh-46055@footnote{https://github.com/python/cpython/issues/46055}: Speed up right shift of negative integers, by removing
unnecessary creation of temporaries. Original patch by Xinhang Xu,
reworked by Mark Dickinson.

@item 
gh-91462@footnote{https://github.com/python/cpython/issues/91462}: Make the interpreter's low-level tracing (lltrace) feature
output more readable by displaying opcode names (rather than just
numbers), and by displaying stack contents before each opcode.

@item 
gh-89455@footnote{https://github.com/python/cpython/issues/89455}: Fixed an uninitialized bool value in the traceback printing code
path that was introduced by the initial bpo-45292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45292} exception groups work.

@item 
gh-91421@footnote{https://github.com/python/cpython/issues/91421}: Fix a potential integer overflow in _Py_DecodeUTF8Ex.

@item 
gh-91428@footnote{https://github.com/python/cpython/issues/91428}: Add @code{static const char *const _PyOpcode_OpName[256] = @{...@};}
to @code{opcode.h} for debug builds to assist in debugging the Python
interpreter. It is now more convenient to make various forms of debugging
output more human-readable by including opcode names rather than just the
corresponding decimal digits.

@item 
bpo-47120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47120}: Make @ref{1a5f,,POP_JUMP_IF_TRUE}, @ref{1a60,,POP_JUMP_IF_FALSE},
@ref{1b7f,,POP_JUMP_IF_NONE} and @ref{1b80,,POP_JUMP_IF_NOT_NONE} virtual,
mapping to new relative jump opcodes.

@item 
bpo-45317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45317}: Add internal documentation explaining design of new (for 3.11)
frame stack.
@end itemize

@node ライブラリ<88>,Core and Builtins<85>,Core and Builtins<84>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id393}@anchor{1b81}
@subsubsection ライブラリ



@itemize -

@item 
bpo-47197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47197}: ctypes used to mishandle @code{void} return types, so that for
instance a function declared like @code{ctypes.CFUNCTYPE(None, ctypes.c_int)}
would be called with signature @code{int f(int)} instead of @code{void f(int)}.
Wasm targets require function pointers to be called with the correct
signatures so this led to crashes. The problem is now fixed.
@end itemize

@node Core and Builtins<85>,ビルド<33>,ライブラリ<88>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id394}@anchor{1b82}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-47120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47120}: Make opcodes @code{JUMP_IF_TRUE_OR_POP} and
@code{JUMP_IF_FALSE_OR_POP} relative rather than absolute.

@item 
bpo-47177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47177}: Replace the @code{f_lasti} member of the internal
@code{_PyInterpreterFrame} structure with a @code{prev_instr} pointer, which
reduces overhead in the main interpreter loop. The @code{f_lasti} attribute
of Python-layer frame objects is preserved for backward-compatibility.

@item 
bpo-46961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46961}: Integer mod/remainder operations, including the three-argument
form of @ref{1a4,,pow()}, now consistently return ints from the global small
integer cache when applicable.

@item 
bpo-46962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46962}: Classes and functions that unconditionally declared their
docstrings ignoring the @code{--without-doc-strings} compilation flag no
longer do so.

The classes affected are @code{ctypes.UnionType},
@ref{177b,,pickle.PickleBuffer}, @code{testcapi.RecursingInfinitelyError},
and @ref{9ec,,types.GenericAlias}.

The functions affected are 24 methods in @ref{2e,,ctypes}.

Patch by Oleg Iarygin.

@item 
bpo-46942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46942}: Use Argument Clinic for the @ref{1b83,,types.MethodType}
constructor.  Patch by Oleg Iarygin.

@item 
bpo-46764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46764}: Fix wrapping bound methods with @@classmethod

@item 
bpo-43464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43464}: Optimize @ref{1b84,,set.intersection()} for non-set arguments.

@item 
bpo-46721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46721}: Optimize @ref{1b85,,set.issuperset()} for non-set argument.

@item 
bpo-46509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46509}: Add type-specialized versions of the @code{Py_DECREF()}, and use
them for @code{float}, @code{int}, @code{str}, @code{bool}, and @code{None} to avoid
pointer-chasing at runtime where types are known at C compile time.
@end itemize

@node ビルド<33>,Core and Builtins<86>,Core and Builtins<85>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id395}@anchor{1b86}
@subsubsection ビルド



@itemize -

@item 
bpo-46045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46045}: Do not use POSIX semaphores on NetBSD
@end itemize

@node Core and Builtins<86>,ライブラリ<89>,ビルド<33>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id396}@anchor{1b87}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-36819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36819}: Fix crashes in built-in encoders with error handlers that
return position less or equal than the starting position of non-encodable
characters.

@item 
bpo-34093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34093}: @code{marshal.dumps()} uses @code{FLAG_REF} for all interned strings.
This makes output more deterministic and helps reproducible build.

@item 
bpo-26579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26579}: Added @code{object.__getstate__} which provides the default
implementation of the @code{__getstate__()} method.

Copying and pickling instances of subclasses of builtin types bytearray,
set, frozenset, collections.OrderedDict, collections.deque,
weakref.WeakSet, and datetime.tzinfo now copies and pickles instance
attributes implemented as slots.
@end itemize

@node ライブラリ<89>,ドキュメント<29>,Core and Builtins<86>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id397}@anchor{1b88}
@subsubsection ライブラリ



@itemize -

@item 
gh-87901@footnote{https://github.com/python/cpython/issues/87901}: Add the `encoding' parameter to @ref{31a,,os.popen()}.

@item 
gh-90997@footnote{https://github.com/python/cpython/issues/90997}: Fix an issue where @ref{3c,,dis} utilities may interpret populated
inline cache entries as valid instructions.

@item 
gh-92332@footnote{https://github.com/python/cpython/issues/92332}: Deprecate @ref{360,,typing.Text} (removal of the class is
currently not planned). Patch by Alex Waygood.

@item 
gh-78157@footnote{https://github.com/python/cpython/issues/78157}: Deprecate nested classes in enum definitions becoming members --
in 3.13 they will be normal classes; add @code{member} and @code{nonmember}
functions to allow control over results now.

@item 
gh-92356@footnote{https://github.com/python/cpython/issues/92356}: Fixed a performance regression in ctypes function calls.

@item 
gh-90997@footnote{https://github.com/python/cpython/issues/90997}: Show the actual named values stored in inline caches when
@code{show_caches=True} is passed to @ref{3c,,dis} utilities.

@item 
gh-92301@footnote{https://github.com/python/cpython/issues/92301}: Prefer @code{close_range()} to iterating over procfs for file
descriptor closing in @ref{dc,,subprocess} for better performance.

@item 
gh-67248@footnote{https://github.com/python/cpython/issues/67248}: Sort the miscellaneous topics in Cmd.do_help()

@item 
gh-92210@footnote{https://github.com/python/cpython/issues/92210}: Port @code{socket.__init__} to Argument Clinic. Patch by Cinder.

@item 
gh-80010@footnote{https://github.com/python/cpython/issues/80010}: Add support for generalized ISO 8601 parsing to
@ref{82a,,datetime.datetime.fromisoformat()},
@ref{828,,datetime.date.fromisoformat()} and
@ref{829,,datetime.time.fromisoformat()}. Patch by Paul Ganssle.

@item 
gh-92118@footnote{https://github.com/python/cpython/issues/92118}: Fix a 3.11 regression in @ref{141b,,contextmanager()},
which caused it to propagate exceptions with incorrect tracebacks.

@item 
gh-90887@footnote{https://github.com/python/cpython/issues/90887}: Adding @code{COPYFILE_STAT}, @code{COPYFILE_ACL} and
@code{COPYFILE_XATTR} constants for @code{os.fcopyfile()} available in macOs.

@item 
gh-91215@footnote{https://github.com/python/cpython/issues/91215}: For @ref{4e1,,@@~dataclasses.dataclass}, add `weakref_slot'. The new
parameter defaults to @code{False}. If true, and if @code{slots=True}, add a
slot named @code{"__weakref__"}, which will allow instances to be weakref'd.
Contributed by Eric V. Smith

@item 
gh-85984@footnote{https://github.com/python/cpython/issues/85984}: New function os.login_tty() for Unix.

@item 
gh-92128@footnote{https://github.com/python/cpython/issues/92128}: Add @ref{943,,__class_getitem__()} to
@ref{150d,,logging.LoggerAdapter} and @ref{1411,,logging.StreamHandler},
allowing them to be parameterized at runtime. Patch by Alex Waygood.

@item 
gh-92049@footnote{https://github.com/python/cpython/issues/92049}: Forbid pickling constants @code{re._constants.SUCCESS} etc.
Previously, pickling did not fail, but the result could not be unpickled.

@item 
gh-92062@footnote{https://github.com/python/cpython/issues/92062}: @ref{4e4,,inspect.Parameter} now raises @ref{2ec,,ValueError} if
@code{name} is a keyword, in addition to the existing check that it is an
identifier.

@item 
gh-87390@footnote{https://github.com/python/cpython/issues/87390}: Add an @code{__unpacked__} attribute to
@ref{9ec,,types.GenericAlias}. Patch by Jelle Zijlstra.

@item 
gh-88089@footnote{https://github.com/python/cpython/issues/88089}: Add support for generic @ref{331,,typing.NamedTuple}.

@item 
gh-91996@footnote{https://github.com/python/cpython/issues/91996}: New http.HTTPMethod enum to represent all the available HTTP
request methods in a convenient way

@item 
gh-91984@footnote{https://github.com/python/cpython/issues/91984}: Modified test strings in test_argparse.py to not contain
trailing spaces before end of line.

@item 
gh-91952@footnote{https://github.com/python/cpython/issues/91952}: Add @code{encoding="locale"} support to
@code{TextIOWrapper.reconfigure()}.

@item 
gh-91954@footnote{https://github.com/python/cpython/issues/91954}: Add `encoding' and `errors' arguments to
@ref{11c5,,subprocess.getoutput()} and @ref{11c6,,subprocess.getstatusoutput()}.

@item 
bpo-47029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47029}: Always close the read end of the pipe used by
@ref{1b89,,multiprocessing.Queue} `after' the last write of buffered data to
the write end of the pipe to avoid @ref{1267,,BrokenPipeError} at garbage
collection and at @ref{1b8a,,multiprocessing.Queue.close()} calls. Patch by Géry
Ogam.

@item 
gh-91928@footnote{https://github.com/python/cpython/issues/91928}: Add @code{datetime.UTC} alias for @code{datetime.timezone.utc}.

Patch by Kabir Kwatra.

@item 
gh-68966@footnote{https://github.com/python/cpython/issues/68966}: The @code{mailcap} module is now deprecated and will be removed
in Python 3.13. See 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} for the rationale and the @ref{93,,mimetypes}
module for an alternative. Patch by Victor Stinner.

@item 
gh-91401@footnote{https://github.com/python/cpython/issues/91401}: Provide a way to disable @ref{dc,,subprocess} use of @code{vfork()}
just in case it is ever needed and document the existing mechanism for
@code{posix_spawn()}.

@item 
gh-64783@footnote{https://github.com/python/cpython/issues/64783}: Fix @ref{1b8b,,signal.NSIG} value on FreeBSD to accept signal
numbers greater than 32, like @code{signal.SIGRTMIN} and
@code{signal.SIGRTMAX}. Patch by Victor Stinner.

@item 
gh-91910@footnote{https://github.com/python/cpython/issues/91910}: Add missing f prefix to f-strings in error messages from the
@ref{98,,multiprocessing} and @ref{b,,asyncio} modules.

@item 
gh-91860@footnote{https://github.com/python/cpython/issues/91860}: Add @ref{6fb,,typing.dataclass_transform()}, implementing 
@geindex Python Enhancement Proposals; PEP 681
PEP 681@footnote{https://peps.python.org/pep-0681/}.
Patch by Jelle Zijlstra.

@item 
gh-91832@footnote{https://github.com/python/cpython/issues/91832}: Add @code{required} attribute to @ref{1b8c,,argparse.Action} repr
output.

@item 
gh-91827@footnote{https://github.com/python/cpython/issues/91827}: In the @ref{f6,,tkinter} module add method @code{info_patchlevel()}
which returns the exact version of the Tcl library as a named tuple
similar to @ref{8af,,sys.version_info}.

@item 
gh-84461@footnote{https://github.com/python/cpython/issues/84461}: Add @ref{1b8d,,--enable-wasm-pthreads} to enable pthreads support
for WASM builds. @code{Emscripten/node} no longer has threading enabled by
default. Include additional file systems.

@item 
gh-91821@footnote{https://github.com/python/cpython/issues/91821}: Fix unstable @code{test_from_tuple} test in @code{test_decimal.py}.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the xdrlib module.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the uu module.

@item 
gh-91760@footnote{https://github.com/python/cpython/issues/91760}: More strict rules will be applied for numerical group references
and group names in regular expressions. For now, a deprecation warning is
emitted for group references and group names which will be errors in
future Python versions.

@item 
gh-84461@footnote{https://github.com/python/cpython/issues/84461}: Add provisional @ref{1b8e,,sys._emscripten_info} named tuple with
build-time and run-time information about Emscripten platform.

@item 
gh-90623@footnote{https://github.com/python/cpython/issues/90623}: @ref{1b8f,,signal.raise_signal()} and @ref{157f,,os.kill()} now check
immediately for pending signals. Patch by Victor Stinner.

@item 
gh-91734@footnote{https://github.com/python/cpython/issues/91734}: Fix OSS audio support on Solaris.

@item 
gh-90633@footnote{https://github.com/python/cpython/issues/90633}: Include the passed value in the exception thrown by
@ref{8b6,,typing.assert_never()}. Patch by Jelle Zijlstra.

@item 
gh-91700@footnote{https://github.com/python/cpython/issues/91700}: Compilation of regular expression containing a conditional
expression @code{(?(group)...)} now raises an appropriate @code{re.error} if
the group number refers to not defined group. Previously an internal
RuntimeError was raised.

@item 
gh-91231@footnote{https://github.com/python/cpython/issues/91231}: Add an optional keyword `shutdown_timeout' parameter to the
@code{multiprocessing.BaseManager} constructor. Kill the process if
terminate() takes longer than the timeout. Patch by Victor Stinner.

@item 
gh-91621@footnote{https://github.com/python/cpython/issues/91621}: Fix @ref{8c0,,typing.get_type_hints()} for
@ref{9eb,,collections.abc.Callable}. Patch by Shantanu Jain.

@item 
gh-90568@footnote{https://github.com/python/cpython/issues/90568}: Parsing @code{\N} escapes of Unicode Named Character Sequences in a
@ref{be,,regular expression} raises now @code{re.error} instead of
@code{TypeError}.

@item 
gh-91670@footnote{https://github.com/python/cpython/issues/91670}: Remove deprecated @code{SO} config variable in @ref{e1,,sysconfig}.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the telnetlib module.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the sunau module.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the spwd module.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the sndhdr module, as well as inline needed
functionality for @code{email.mime.MIMEAudio}.

@item 
gh-91616@footnote{https://github.com/python/cpython/issues/91616}: @ref{be,,re} module, fix @ref{1188,,fullmatch()} mismatch
when using Atomic Grouping or Possessive Quantifiers.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the 'pipes' module.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the ossaudiodev module.

@item 
bpo-47256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47256}: @ref{be,,re} module, limit the maximum capturing group to
1,073,741,823 in 64-bit build, this increases the depth of backtracking.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the nis module.

@item 
gh-91595@footnote{https://github.com/python/cpython/issues/91595}: Fix the comparison of character and integer inside
@code{Tools.gdb.libpython.write_repr()}. Patch by Yu Liu.

@item 
gh-74166@footnote{https://github.com/python/cpython/issues/74166}: Add option to raise all errors from
@ref{882,,create_connection()} in an @ref{4d2,,ExceptionGroup} when it
fails to create a connection. The default remains to raise only the last
error that had occurred when multiple addresses were tried.

@item 
gh-91487@footnote{https://github.com/python/cpython/issues/91487}: Optimize asyncio UDP speed, over 100 times faster when
transferring a large file.

@item 
gh-91575@footnote{https://github.com/python/cpython/issues/91575}: Update case-insensitive matching in the @ref{be,,re} module to the
latest Unicode version.

@item 
gh-90622@footnote{https://github.com/python/cpython/issues/90622}: In @code{concurrent.futures.process.ProcessPoolExecutor} disallow
the "fork" multiprocessing start method when the new
@code{max_tasks_per_child} feature is used as the mix of threads+fork can
hang the child processes. Default to using the safe "spawn" start method
in that circumstance if no @code{mp_context} was supplied.

@item 
gh-89022@footnote{https://github.com/python/cpython/issues/89022}: In @ref{d4,,sqlite3}, @code{SQLITE_MISUSE} result codes are now mapped
to @ref{88d,,InterfaceError} instead of
@ref{305,,ProgrammingError}. Also, more accurate exceptions are
raised when binding parameters fail. Patch by Erlend E. Aasland.

@item 
gh-91526@footnote{https://github.com/python/cpython/issues/91526}: Stop calling @code{os.device_encoding(file.fileno())} in
@code{TextIOWrapper}. It was complex, never documented, and didn't work
for most cases. (Patch by Inada Naoki.)

@item 
gh-88116@footnote{https://github.com/python/cpython/issues/88116}: Change the frame-related functions in the @ref{82,,inspect} module
to return a regular object (that is backwards compatible with the old
tuple-like interface) that include the extended 
@geindex Python Enhancement Proposals; PEP 657
PEP 657@footnote{https://peps.python.org/pep-0657/} position
information (end line number, column and end column). The affected
functions are: @ref{85f,,inspect.getframeinfo()},
@ref{860,,inspect.getouterframes()}, @ref{861,,inspect.getinnerframes()},
@ref{862,,inspect.stack()} and @ref{863,,inspect.trace()}. Patch by Pablo Galindo.

@item 
gh-69093@footnote{https://github.com/python/cpython/issues/69093}: Add indexing and slicing support to @ref{892,,sqlite3.Blob}. Patch
by Aviv Palivoda and Erlend E. Aasland.

@item 
gh-69093@footnote{https://github.com/python/cpython/issues/69093}: Add @ref{1e1,,context manager} support to @ref{892,,sqlite3.Blob}.
Patch by Aviv Palivoda and Erlend E. Aasland.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate nntplib.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate msilib.

@item 
gh-91404@footnote{https://github.com/python/cpython/issues/91404}: Improve the performance of @ref{be,,re} matching by using computed
gotos (or "threaded code") on supported platforms and removing expensive
pointer indirections.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the imghdr module.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the crypt module.

@item 
gh-91276@footnote{https://github.com/python/cpython/issues/91276}: Make space for longer opcodes in @ref{3c,,dis} output.

@item 
bpo-47000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47000}: Make @code{TextIOWrapper} uses locale encoding when
@code{encoding="locale"} is specified even in UTF-8 mode.

@item 
gh-91230@footnote{https://github.com/python/cpython/issues/91230}: @ref{179,,warnings.catch_warnings()} now accepts arguments for
@ref{8d0,,warnings.simplefilter()}, providing a more concise way to locally
ignore warnings or convert them to errors.

@item 
gh-91217@footnote{https://github.com/python/cpython/issues/91217}: Deprecate the chunk module.

@item 
gh-91498@footnote{https://github.com/python/cpython/issues/91498}: Add the @code{TCP_CONNECTION_INFO} option (available on macOS) to
@ref{d1,,socket}.

@item 
bpo-47260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47260}: Fix @code{os.closerange()} potentially being a no-op in a Linux
seccomp sandbox.

@item 
bpo-47087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47087}: Implement @code{typing.Required} and @code{typing.NotRequired}
(
@geindex Python Enhancement Proposals; PEP 655
PEP 655@footnote{https://peps.python.org/pep-0655/}). Patch by David Foster and Jelle Zijlstra.

@item 
bpo-47061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47061}: Deprecate cgi and cgitb.

@item 
bpo-47061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47061}: Deprecate audioop.

@item 
bpo-47000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47000}: Add @ref{329,,locale.getencoding()} to get the current locale
encoding. It is similar to @code{locale.getpreferredencoding(False)} but
ignores the @ref{866,,Python UTF-8 Mode}.

@item 
bpo-42012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42012}: Add @ref{122,,wsgiref.types}, containing WSGI-specific types for
static type checking.

@item 
bpo-47227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47227}: Suppress expression chaining for more @ref{be,,re} parsing errors.

@item 
bpo-47211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47211}: Remove undocumented and never working function
@code{re.template()} and flag @code{re.TEMPLATE}. This was later reverted in
3.11.0b2 and deprecated instead.

@item 
bpo-47135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47135}: @ref{159e,,decimal.localcontext()} now accepts context attributes via
keyword arguments

@item 
bpo-43323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43323}: Fix errors in the @ref{3f,,email} module if the charset itself
contains undecodable/unencodable characters.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Disassembly of quickened code.

@item 
bpo-46681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46681}: Forward gzip.compress() compresslevel to zlib.

@item 
bpo-45100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45100}: Add @ref{8bd,,typing.get_overloads()} and
@ref{8be,,typing.clear_overloads()}. Patch by Jelle Zijlstra.

@item 
bpo-44807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44807}: @ref{56b,,typing.Protocol} no longer silently replaces
@code{__init__()} methods defined on subclasses. Patch by Adrian Garcia
Badaracco.

@item 
bpo-46787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46787}: Fix @ref{1d6,,concurrent.futures.ProcessPoolExecutor} exception
memory leak

@item 
bpo-46720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46720}: Add support for path-like objects to
@ref{1b90,,multiprocessing.set_executable()} for Windows to be on a par with
Unix-like systems. Patch by Géry Ogam.

@item 
bpo-46696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46696}: Add @code{SO_INCOMING_CPU} constant to @ref{d1,,socket}.

@item 
bpo-46053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46053}: Fix OSS audio support on NetBSD.

@item 
bpo-45639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45639}: @code{image/avif} and @code{image/webp} were added to
@ref{93,,mimetypes}.

@item 
bpo-46285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46285}: Add command-line option @code{-p}/@code{--protocol} to module
@ref{76,,http.server} which specifies the HTTP version to which the server is
conformant (HTTP/1.1 conformant servers can now be run from the
command-line interface of module @ref{76,,http.server}). Patch by Géry Ogam.

@item 
bpo-44791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44791}: Accept ellipsis as the last argument of
@ref{9c7,,typing.Concatenate}.

@item 
bpo-46547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46547}: Remove variables leaking into @code{pydoc.Helper} class namespace.

@item 
bpo-46415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46415}: Fix ipaddress.ip_@{address,interface,network@} raising TypeError
instead of ValueError if given invalid tuple as address parameter.

@item 
bpo-46075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46075}: @code{CookieJar} with @code{DefaultCookiePolicy} now can process
cookies from localhost with domain=localhost explicitly specified in
Set-Cookie header.

@item 
bpo-45995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45995}: Add a "z" option to the string formatting specification that
coerces negative zero floating-point values to positive zero after
rounding to the format precision.  Contributed by John Belmonte.

@item 
bpo-26175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26175}: Fully implement the @ref{8a3,,io.BufferedIOBase} or
@ref{8a4,,io.TextIOBase} interface for
@ref{8a2,,tempfile.SpooledTemporaryFile} objects. This lets them work
correctly with higher-level layers (like compression modules). Patch by
Carey Metcalfe.

@item 
bpo-45138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45138}: Fix a regression in the @ref{d4,,sqlite3} trace callback where
bound parameters were not expanded in the passed statement string. The
regression was introduced in Python 3.10 by bpo-40318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40318}. Patch by
Erlend E. Aasland.

@item 
bpo-44863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44863}: Allow @ref{332,,TypedDict} subclasses to also include
@ref{17b6,,Generic} as a base class in class based syntax. Thereby
allowing the user to define a generic @code{TypedDict}, just like a
user-defined generic but with @code{TypedDict} semantics.

@item 
bpo-44587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44587}: Fix BooleanOptionalAction to not automatically add a default
string.  If a default string is desired, use a formatter to add it.

@item 
bpo-43827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43827}: All positional-or-keyword parameters to @code{ABCMeta.__new__} are
now positional-only to avoid conflicts with keyword arguments to be passed
to @code{__init_subclass__()}.

@item 
bpo-43218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43218}: Prevent creation of a venv whose path contains the PATH
separator. This could affect the usage of the activate script. Patch by
Dustin Rodrigues.

@item 
bpo-38435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38435}: Add a @code{process_group} parameter to @ref{4b7,,subprocess.Popen}
to help move more things off of the unsafe @code{preexec_fn} parameter.

@item 
bpo-42066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42066}: Fix cookies getting sorted in @code{CookieJar.__iter__()} which
is an extra behavior and not mentioned in RFC 2965 or Netscape cookie
protocol. Now the cookies in @code{CookieJar} follows the order of the
@code{Set-Cookie} header. Patch by Iman Kermani.

@item 
bpo-40617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40617}: Add @ref{890,,create_window_function()} to
@ref{54d,,sqlite3.Connection} for creating aggregate window functions. Patch
by Erlend E. Aasland.

@item 
bpo-40676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40676}: Convert @ref{2d,,csv} to use Argument Clinic for
@ref{1b91,,csv.field_size_limit()}, @ref{1b92,,csv.get_dialect()},
@ref{1b93,,csv.unregister_dialect()} and @ref{1b94,,csv.list_dialects()}.

@item 
bpo-39716@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39716}: Raise an @code{ArgumentError} when the same subparser name is
added twice to an @code{argparse.ArgumentParser}.  This is consistent with
the (default) behavior when the same option string is added twice to an
@code{ArgumentParser}.

@item 
bpo-36073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36073}: Raise @ref{305,,ProgrammingError} instead of segfaulting
on recursive usage of cursors in @ref{d4,,sqlite3} converters. Patch by
Sergey Fedoseev.

@item 
bpo-34975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34975}: Adds a @code{start_tls()} method to
@code{StreamWriter}, which upgrades the connection with
TLS using the given @ref{357,,SSLContext}.

@item 
bpo-22276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22276}: @ref{266,,Path} methods @ref{537,,glob()} and
@ref{538,,rglob()} return only directories if `pattern' ends with
a pathname components separator (@code{/} or @ref{87a,,sep}). Patch by
Eisuke Kawashima.

@item 
bpo-24905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24905}: Add @ref{891,,blobopen()} to
@ref{54d,,sqlite3.Connection}. @ref{892,,sqlite3.Blob} allows incremental I/O
operations on blobs. Patch by Aviv Palivoda and Erlend E. Aasland.
@end itemize

@node ドキュメント<29>,テスト<28>,ライブラリ<89>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id398}@anchor{1b95}
@subsubsection ドキュメント



@itemize -

@item 
gh-91888@footnote{https://github.com/python/cpython/issues/91888}: Add a new @code{gh} role to the documentation to link to GitHub
issues.

@item 
gh-91783@footnote{https://github.com/python/cpython/issues/91783}: Document security issues concerning the use of the function
@ref{696,,shutil.unpack_archive()}

@item 
gh-91547@footnote{https://github.com/python/cpython/issues/91547}: Remove "Undocumented modules" page.

@item 
gh-91298@footnote{https://github.com/python/cpython/issues/91298}: In @code{importlib.resources.abc}, refined the documentation of the
Traversable Protocol, applying changes from importlib_resources 5.7.1.

@item 
bpo-44347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44347}: Clarify the meaning of `dirs_exist_ok', a kwarg of
@ref{c1e,,shutil.copytree()}.

@item 
bpo-36329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36329}: Remove 'make -C Doc serve' in favour of 'make -C Doc htmlview'

@item 
bpo-47189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47189}: Add a What's New in Python 3.11 entry for the Faster CPython
project. Documentation by Ken Jin and Kumar Aditya.

@item 
bpo-38668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38668}: Update the introduction to documentation for @ref{a6,,os.path} to
remove warnings that became irrelevant after the implementations of
@geindex Python Enhancement Proposals; PEP 383
PEP 383@footnote{https://peps.python.org/pep-0383/} and 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/}.

@item 
bpo-47115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47115}: The documentation now lists which members of C structs are part
of the @ref{775,,Limited API/Stable ABI}.

@item 
bpo-46962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46962}: All docstrings in code snippets are now wrapped into
@ref{1b96,,PyDoc_STR} to follow the guideline of 
@geindex Python Enhancement Proposals; PEP 0007#documentation-strings
PEP 7's Documentation Strings paragraph@footnote{https://peps.python.org/pep-0007/#documentation-strings}. Patch by
Oleg Iarygin.

@item 
bpo-26792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26792}: Improve the docstrings of @ref{1b97,,runpy.run_module()} and
@ref{4a4,,runpy.run_path()}. Original patch by Andrew Brezovsky.
@end itemize

@node テスト<28>,ビルド<34>,ドキュメント<29>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id399}@anchor{1b98}
@subsubsection テスト



@itemize -

@item 
gh-92169@footnote{https://github.com/python/cpython/issues/92169}: Use @code{warnings_helper.import_deprecated()} to import deprecated
modules uniformly in tests. Patch by Hugo van Kemenade.

@item 
gh-84461@footnote{https://github.com/python/cpython/issues/84461}: When multiprocessing is enabled, libregrtest can now use a
Python executable other than @code{sys.executable} via the @code{--python}
flag.

@item 
gh-91904@footnote{https://github.com/python/cpython/issues/91904}: Fix initialization of 
@geindex PYTHONREGRTEST_UNICODE_GUARD
@geindex 環境変数; PYTHONREGRTEST_UNICODE_GUARD
@code{PYTHONREGRTEST_UNICODE_GUARD}
which prevented running regression tests on non-UTF-8 locale.

@item 
gh-91752@footnote{https://github.com/python/cpython/issues/91752}: Added @@requires_zlib to test.test_tools.test_freeze.TestFreeze.

@item 
gh-91607@footnote{https://github.com/python/cpython/issues/91607}: Fix @code{test_concurrent_futures} to test the correct
multiprocessing start method context in several cases where the test logic
mixed this up.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Threading tests are now skipped on WASM targets without pthread
support.

@item 
bpo-47109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47109}: Test for @code{ctypes.macholib.dyld},
@code{ctypes.macholib.dylib}, and @code{ctypes.macholib.framework} are
brought from manual pre-@ref{10c,,unittest} times to @code{ctypes.test}
location and structure. Patch by Oleg Iarygin.

@item 
bpo-29890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29890}: Add tests for @ref{1b99,,ipaddress.IPv4Interface} and
@ref{1b9a,,ipaddress.IPv6Interface} construction with tuple arguments.
Original patch and tests by louisom.
@end itemize

@node ビルド<34>,Windows<30>,テスト<28>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id400}@anchor{1b9b}
@subsubsection ビルド



@itemize -

@item 
gh-89452@footnote{https://github.com/python/cpython/issues/89452}: gdbm-compat is now preferred over ndbm if both are available on
the system. This allows avoiding the problematic ndbm.h on macOS.

@item 
gh-91731@footnote{https://github.com/python/cpython/issues/91731}: Python is now built with @code{-std=c11} compiler option, rather
than @code{-std=c99}. Patch by Victor Stinner.

@item 
bpo-47152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47152}: Add script and make target for generating @code{sre_constants.h}.

@item 
bpo-47103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47103}: Windows @code{PGInstrument} builds now copy a required DLL into
the output directory, making it easier to run the profile stage of a PGO
build.
@end itemize

@node Windows<30>,macOS<21>,ビルド<34>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id401}@anchor{1b9c}
@subsubsection Windows



@itemize -

@item 
bpo-46907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46907}: Update Windows installer to use SQLite 3.38.3.

@item 
bpo-47239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47239}: Fixed --list and --list-paths output for @ref{7da,,Python install manager} when
used in an active virtual environment.

@item 
bpo-46907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46907}: Update Windows installer to use SQLite 3.38.2.

@item 
bpo-46785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46785}: Fix race condition between @ref{26d,,os.stat()} and unlinking a file
on Windows, by using errors codes returned by @code{FindFirstFileW()} when
appropriate in @code{win32_xstat_impl}.

@item 
bpo-40859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40859}: Update Windows build to use xz-5.2.5
@end itemize

@node macOS<21>,Tools/Demos<25>,Windows<30>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id402}@anchor{1b9d}
@subsubsection macOS



@itemize -

@item 
bpo-46907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46907}: Update macOS installer to SQLite 3.38.4.
@end itemize

@node Tools/Demos<25>,C API<30>,macOS<21>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id403}@anchor{1b9e}
@subsubsection Tools/Demos



@itemize -

@item 
gh-91583@footnote{https://github.com/python/cpython/issues/91583}: Fix regression in the code generated by Argument Clinic for
functions with the @code{defining_class} parameter.

@item 
gh-91575@footnote{https://github.com/python/cpython/issues/91575}: Add script @code{Tools/scripts/generate_re_casefix.py} and the make
target @code{regen-re} for generating additional data for case-insensitive
matching according to the current Unicode version.

@item 
gh-91551@footnote{https://github.com/python/cpython/issues/91551}: Remove the ancient Pynche color editor.  It has moved to
@indicateurl{https://gitlab.com/warsaw/pynche}
@end itemize

@node C API<30>,,Tools/Demos<25>,Python 3 11 0 beta 1
@anchor{whatsnew/changelog id404}@anchor{1b9f}
@subsubsection C API



@itemize -

@item 
gh-88279@footnote{https://github.com/python/cpython/issues/88279}: Deprecate the C functions: @code{PySys_SetArgv()},
@code{PySys_SetArgvEx()}, @code{PySys_SetPath()}. Patch by Victor
Stinner.

@item 
gh-92154@footnote{https://github.com/python/cpython/issues/92154}: Added the @ref{97c,,PyCode_GetCode()} function. This function does
the equivalent of the Python code @code{getattr(code_object, 'co_code')}.

@item 
gh-92173@footnote{https://github.com/python/cpython/issues/92173}: Fix the @code{closure} argument to @ref{1ada,,PyEval_EvalCodeEx()}.

@item 
gh-91320@footnote{https://github.com/python/cpython/issues/91320}: Fix C++ compiler warnings about "old-style cast" (@code{g++
-Wold-style-cast}) in the Python C API. Use C++ @code{reinterpret_cast<>}
and @code{static_cast<>} casts when the Python C API is used in C++. Patch by
Victor Stinner.

@item 
gh-80527@footnote{https://github.com/python/cpython/issues/80527}: Mark functions as deprecated by 
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/}:
@code{PyUnicode_AS_DATA()}, @code{PyUnicode_AS_UNICODE()},
@code{PyUnicode_GET_DATA_SIZE()}, @code{PyUnicode_GET_SIZE()}. Patch
by Victor Stinner.

@item 
gh-91768@footnote{https://github.com/python/cpython/issues/91768}: @ref{2cf,,Py_REFCNT()}, @ref{3c9,,Py_TYPE()}, @ref{985,,Py_SIZE()} and
@ref{1ba0,,Py_IS_TYPE()} functions argument type is now @code{PyObject*}, rather
than @code{const PyObject*}. Patch by Victor Stinner.

@item 
gh-91020@footnote{https://github.com/python/cpython/issues/91020}: Add @code{PyBytes_Type.tp_alloc} to initialize
@code{PyBytesObject.ob_shash} for bytes subclasses.

@item 
bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}: Add @code{PyFrame_GetLasti} C-API function to access frame
object's @code{f_lasti} attribute safely from C code.

@item 
bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}: Remove the @code{Include/code.h} header file. C extensions should
only include the main @code{<Python.h>} header file. Patch by Victor Stinner.

@item 
bpo-47169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47169}: @ref{1ba1,,PyOS_CheckStack()} is now exported in the Stable ABI on
Windows.

@item 
bpo-47169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47169}: @ref{1ba2,,PyThread_get_thread_native_id()} is excluded from the
stable ABI on platforms where it doesn't exist (like Solaris).

@item 
bpo-46343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46343}: Added @ref{973,,PyErr_GetHandledException()} and
@ref{974,,PyErr_SetHandledException()} as simpler alternatives to
@ref{976,,PyErr_GetExcInfo()} and @ref{975,,PyErr_SetExcInfo()}.

They are included in the stable ABI.
@end itemize

@node Python 3 11 0 alpha 7,Python 3 11 0 alpha 6,Python 3 11 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-11-0-alpha-7}@anchor{1ba3}
@subsection Python 3.11.0 alpha 7


`Release date: 2022-04-05'

@menu
* Core and Builtins: Core and Builtins<87>. 
* ライブラリ: ライブラリ<90>. 
* Core and Builtins: Core and Builtins<88>. 
* ライブラリ: ライブラリ<91>. 
* Core and Builtins: Core and Builtins<89>. 
* ライブラリ: ライブラリ<92>. 
* ドキュメント: ドキュメント<30>. 
* テスト: テスト<29>. 
* ビルド: ビルド<35>. 
* Windows: Windows<31>. 
* macOS: macOS<22>. 
* Tools/Demos: Tools/Demos<26>. 
* C API: C API<31>. 

@end menu

@node Core and Builtins<87>,ライブラリ<90>,,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id405}@anchor{1ba4}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-47212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47212}: Raise @ref{1750,,IndentationError} instead of @ref{18e,,SyntaxError} for
a bare @code{except} with no following indent. Improve @ref{18e,,SyntaxError}
locations for an un-parenthesized generator used as arguments. Patch by
Matthieu Dartiailh.

@item 
bpo-47186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47186}: Replace @code{JUMP_IF_NOT_EG_MATCH} by
@ref{911,,CHECK_EG_MATCH} + jump.

@item 
bpo-47176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47176}: Emscripten builds cannot handle signals in the usual way due to
platform limitations. Python can now handle signals. To use, set
Module.Py_EmscriptenSignalBuffer to be a single byte SharedArrayBuffer and
set Py_EMSCRIPTEN_SIGNAL_HANDLING to 1. Writing a number into the
SharedArrayBuffer will cause the corresponding signal to be raised into
the Python thread.

@item 
bpo-47186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47186}: Replace @code{JUMP_IF_NOT_EXC_MATCH} by
@ref{919,,CHECK_EXC_MATCH} + jump.

@item 
bpo-47120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47120}: Replace the absolute jump opcode @ref{1ba5,,JUMP_NO_INTERRUPT} by
the relative @ref{90e,,JUMP_BACKWARD_NO_INTERRUPT}.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Avoid unnecessary allocations when comparing code objects.

@item 
bpo-47182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47182}: Fix a crash when using a named unicode character like
@code{"\N@{digit nine@}"} after the main interpreter has been initialized a
second time.

@item 
bpo-47162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47162}: WebAssembly cannot deal with bad function pointer casts
(different count or types of arguments). Python can now use call
trampolines to mitigate the problem. Define @code{PY_CALL_TRAMPOLINE}
to enable call trampolines.

@item 
bpo-46775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46775}: Some Windows system error codes(>= 10000) are now mapped into
the correct errno and may now raise a subclass of @ref{2c0,,OSError}. Patch by
Donghee Na.

@item 
bpo-47129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47129}: Improve error messages in f-string syntax errors concerning
empty expressions.

@item 
bpo-47117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47117}: Fix a crash if we fail to decode characters in interactive mode
if the tokenizer buffers are uninitialized. Patch by Pablo Galindo.

@item 
bpo-47127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47127}: Speed up calls to c functions with keyword arguments by 25%
with specialization. Patch by Kumar Aditya.

@item 
bpo-47120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47120}: Replaced @code{JUMP_ABSOLUTE} by the relative jump
@ref{91a,,JUMP_BACKWARD}.

@item 
bpo-42197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42197}: @code{PyFrame_FastToLocalsWithError()} and
@code{PyFrame_LocalsToFast()} are no longer called during profiling nor
tracing. C code can access the @code{f_locals} attribute of
@ref{98c,,PyFrameObject} by calling @ref{661,,PyFrame_GetLocals()}.

@item 
bpo-47070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47070}: Improve performance of @code{array_inplace_repeat} by reducing the
number of invocations of @code{memcpy}. Refactor the @code{repeat} and inplace
@code{repeat} methods of @code{array}, @code{bytes}, @code{bytearray} and
@code{unicodeobject} to use the common @code{_PyBytes_Repeat}.

@item 
bpo-47053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47053}: Reduce de-optimization in the specialized
@code{BINARY_OP_INPLACE_ADD_UNICODE} opcode.

@item 
bpo-47045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47045}: Remove the @code{f_state} field from the _PyInterpreterFrame
struct. Add the @code{owner} field to the _PyInterpreterFrame struct to make
ownership explicit to simplify clearing and deallocing frames and
generators.
@end itemize

@node ライブラリ<90>,Core and Builtins<88>,Core and Builtins<87>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id406}@anchor{1ba6}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46968}: Check for the existence of the "sys/auxv.h" header in
@ref{5c,,faulthandler} to avoid compilation problems in systems where this
header doesn't exist. Patch by Pablo Galindo
@end itemize

@node Core and Builtins<88>,ライブラリ<91>,ライブラリ<90>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id407}@anchor{1ba7}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46329}: Use low bit of @code{LOAD_GLOBAL} to indicate whether to push a
@code{NULL} before the global. Helps streamline the call sequence a bit.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Quicken bytecode in-place by storing it as part of the
corresponding @code{PyCodeObject}.

@item 
bpo-47012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47012}: Speed up iteration of @ref{192,,bytes} and @ref{344,,bytearray} by
30%. Patch by Kumar Aditya.

@item 
bpo-47009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47009}: Improved the performance of @ref{8dc,,list.append()} and list
comprehensions by optimizing for the common case, where no resize is
needed. Patch by Dennis Sweeney.

@item 
bpo-47005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47005}: Improve performance of @code{bytearray_repeat} and
@code{bytearray_irepeat} by reducing the number of invocations of @code{memcpy}.
@end itemize

@node ライブラリ<91>,Core and Builtins<89>,Core and Builtins<88>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id408}@anchor{1ba8}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46829}: Deprecate passing a message into @ref{1ba9,,asyncio.Future.cancel()}
and @ref{4d3,,asyncio.Task.cancel()}
@end itemize

@node Core and Builtins<89>,ライブラリ<92>,ライブラリ<91>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id409}@anchor{1baa}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46993}: Speed up @ref{344,,bytearray} creation from @ref{24d,,list} and
@ref{614,,tuple} by 40%. Patch by Kumar Aditya.

@item 
bpo-39829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39829}: Removed the @code{__len__()} call when initializing a list and
moved initializing to @code{list_extend}. Patch by Jeremiah Pascual.

@item 
bpo-46944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46944}: Speed up throwing exception in generator with
@ref{199e,,METH_FASTCALL} calling convention. Patch by Kumar Aditya.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Modify @ref{1bab,,STORE_SUBSCR} to use an inline cache entry
(rather than its oparg) as an adaptive counter.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Use inline caching for @code{PRECALL} and @ref{915,,CALL},
and remove the internal machinery for managing the (now unused) non-inline
caches.

@item 
bpo-46881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46881}: Statically allocate and initialize the latin1 characters.

@item 
bpo-46838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46838}: Improve syntax errors for incorrect function definitions. Patch
by Pablo Galindo

@item 
bpo-43721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43721}: Fix docstrings of @ref{19d9,,getter},
@ref{19da,,setter}, and @ref{19db,,deleter} to clarify that
they create a new copy of the property.

@item 
bpo-43224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43224}: Make grammar changes required for PEP 646.
@end itemize

@node ライブラリ<92>,ドキュメント<30>,Core and Builtins<89>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id410}@anchor{1bac}
@subsubsection ライブラリ



@itemize -

@item 
bpo-47208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47208}: Allow vendors to override @code{CTYPES_MAX_ARGCOUNT}.

@item 
bpo-23689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23689}: @ref{be,,re} module: fix memory leak when a match is terminated by
a signal or memory allocation failure. Patch by Ma Lin.

@item 
bpo-47167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47167}: Allow overriding a future compliance check in
@ref{1c7,,asyncio.Task}.

@item 
bpo-47151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47151}: When subprocess tries to use vfork, it now falls back to fork
if vfork returns an error. This allows use in situations where vfork isn't
allowed by the OS kernel.

@item 
bpo-47152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47152}: Convert the @ref{be,,re} module into a package. Deprecate modules
@code{sre_compile}, @code{sre_constants} and @code{sre_parse}.

@item 
bpo-4833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4833}: Add @code{ZipFile.mkdir()}

@item 
bpo-27929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27929}: Fix @ref{fc8,,asyncio.loop.sock_connect()} to only resolve names for
@ref{1bad,,socket.AF_INET} or @ref{1bae,,socket.AF_INET6} families. Resolution
may not make sense for other families, like @ref{1baf,,socket.AF_BLUETOOTH}
and @ref{1bb0,,socket.AF_UNIX}.

@item 
bpo-14265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14265}: Adds the fully qualified test name to unittest output

@item 
bpo-47061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47061}: Deprecate the aifc module.

@item 
bpo-39622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39622}: Handle Ctrl+C in asyncio programs to interrupt the main task.

@item 
bpo-47101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47101}: @ref{158c,,hashlib.algorithms_available} now lists only algorithms
that are provided by activated crypto providers on OpenSSL 3.0. Legacy
algorithms are not listed unless the legacy provider has been loaded into
the default OSSL context.

@item 
bpo-47099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47099}: All @code{URLError} exception messages raised in
@code{urllib.request.URLopener} now contain a colon between @code{ftp
error} and the rest of the message. Previously,
@code{open_ftp()} missed the colon. Patch by Oleg
Iarygin.

@item 
bpo-47099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47099}: Exception chaining is changed from
@code{Exception.with_traceback()}/@ref{89a,,sys.exc_info()} to 
@geindex Python Enhancement Proposals; PEP 3134
PEP 3134@footnote{https://peps.python.org/pep-3134/}.
Patch by Oleg Iarygin.

@item 
bpo-47095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47095}: @ref{6c,,hashlib}'s internal @code{_blake2} module now prefers
@code{libb2} from @indicateurl{https://www.blake2.net/} over Python's vendored copy of
blake2.

@item 
bpo-47098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47098}: The Keccak Code Package for @ref{6c,,hashlib}'s internal @code{_sha3}
module has been replaced with tiny_sha3. The module is used as fallback
when Python is built without OpenSSL.

@item 
bpo-47088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47088}: Implement @ref{7e6,,typing.LiteralString}, part of 
@geindex Python Enhancement Proposals; PEP 675
PEP 675@footnote{https://peps.python.org/pep-0675/}.
Patch by Jelle Zijlstra.

@item 
bpo-42885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42885}: Optimize @ref{1444,,re.search()}, @ref{5a2,,re.split()},
@ref{122b,,re.findall()}, @ref{1713,,re.finditer()} and @ref{5a3,,re.sub()} for regular
expressions starting with @code{\A} or @code{^}.

@item 
bpo-23691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23691}: Protect the @ref{1713,,re.finditer()} iterator from re-entering.

@item 
bpo-47067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47067}: Optimize calling @code{GenericAlias} objects by using 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} and by replacing @code{PyObject_SetAttrString} with
@code{PyObject_SetAttr}.

@item 
bpo-28080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28080}: Add the `metadata_encoding' parameter in the
@ref{8d3,,zipfile.ZipFile} constructor and the @code{--metadata-encoding}
option in the @ref{137,,zipfile} CLI to allow reading zipfiles using
non-standard codecs to encode the filenames within the archive.

@item 
bpo-47000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47000}: Make @ref{1a3c,,io.text_encoding()} returns "utf-8" when UTF-8 mode
is enabled.

@item 
bpo-42369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42369}: Fix thread safety of @code{zipfile._SharedFile.tell()} to avoid
a "zipfile.BadZipFile: Bad CRC-32 for file" exception when reading a
@code{ZipFile} from multiple threads.

@item 
bpo-38256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38256}: Fix @ref{1a11,,binascii.crc32()} when it is compiled to use zlib'c
crc32 to work properly on inputs 4+GiB in length instead of returning the
wrong result. The workaround prior to this was to always feed the function
data in increments smaller than 4GiB or to just call the zlib module
function.

We also have @ref{1a11,,binascii.crc32()} release the GIL when computing on
larger inputs as @ref{1a10,,zlib.crc32()} and @ref{6c,,hashlib} do.

This also boosts performance on Windows as it now uses the zlib crc32
implementation for @ref{1a11,,binascii.crc32()} for a 2-3x speedup.

That the stdlib has a crc32 API in two modules is a known historical
oddity. This moves us closer to a single implementation behind them.

@item 
bpo-47066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47066}: Global inline flags (e.g. @code{(?i)}) can now only be used at the
start of the regular expressions.  Using them not at the start of
expression was deprecated since Python 3.6.

@item 
bpo-39394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39394}: A warning about inline flags not at the start of the regular
expression now contains the position of the flag.

@item 
bpo-433030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=433030}: Add support of atomic grouping (@code{(?>...)}) and possessive
quantifiers (@code{*+}, @code{++}, @code{?+}, @code{@{m,n@}+}) in @ref{be,,regular expressions}.

@item 
bpo-47062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47062}: Implement @ref{2f5,,asyncio.Runner} context manager.

@item 
bpo-46382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46382}: @ref{4e1,,dataclass()} @code{slots=True} now correctly
omits slots already defined in base classes. Patch by Arie Bovenberg.

@item 
bpo-47057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47057}: Use FASTCALL convention for @code{FutureIter.throw()}

@item 
bpo-47061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47061}: Deprecate the various modules listed by 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}:

aifc, asynchat, asyncore, audioop, cgi, cgitb, chunk, crypt, imghdr,
msilib, nntplib, nis, ossaudiodev, pipes, smtpd, sndhdr, spwd, sunau,
telnetlib, uu, xdrlib

@item 
bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790}: Remove passing coroutine objects to @ref{6a7,,asyncio.wait()}.

@item 
bpo-47039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47039}: Normalize @code{repr()} of asyncio future and task objects.

@item 
bpo-2604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2604}: Fix bug where doctests using globals would fail when run
multiple times.

@item 
bpo-45150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45150}: Add @ref{854,,hashlib.file_digest()} helper for efficient hashing of
file object.

@item 
bpo-34861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34861}: Made cumtime the default sorting key for cProfile

@item 
bpo-45997@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45997}: Fix @ref{c68,,asyncio.Semaphore} re-aquiring FIFO order.

@item 
bpo-47022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47022}: The @code{asynchat}, @code{asyncore} and  @code{smtpd}
modules have been deprecated since at least Python 3.6. Their
documentation and deprecation warnings and have now been updated to note
they will removed in Python 3.12 (
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}).

@item 
bpo-43253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43253}: Fix a crash when closing transports where the underlying socket
handle is already invalid on the Proactor event loop.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: @ref{fa0,,select.select()} now passes @code{NULL} to @code{select} for
each empty fdset.

@item 
bpo-47004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47004}: Apply bugfixes from importlib_metadata 4.11.3, including bugfix
for EntryPoint.extras, which was returning match objects and not the
extras strings.

@item 
bpo-46998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46998}: Allow subclassing of @ref{8bb,,typing.Any}. Patch by Shantanu
Jain.

@item 
bpo-46995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46995}: Deprecate missing @ref{bd0,,asyncio.Task.set_name()} for third-party
task implementations, schedule making it mandatory in Python 3.13.

@item 
bpo-46994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46994}: Accept explicit contextvars.Context in
@ref{1c9,,asyncio.create_task()} and @ref{1ca,,asyncio.loop.create_task()}.

@item 
bpo-46981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46981}: @code{typing.get_args(typing.Tuple[()])} now returns @code{()}
instead of @code{((),)}.

@item 
bpo-46968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46968}: Add @code{os.sysconf_names['SC_MINSIGSTKSZ']}.

@item 
bpo-46985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46985}: Upgrade pip wheel bundled with ensurepip (pip 22.0.4)

@item 
bpo-46968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46968}: @ref{5c,,faulthandler}: On Linux 5.14 and newer, dynamically
determine size of signal handler stack size CPython allocates using
@code{getauxval(AT_MINSIGSTKSZ)}. This changes allows for Python extension's
request to Linux kernel to use AMX_TILE instruction set on Sapphire Rapids
Xeon processor to succeed, unblocking use of the ISA in frameworks.

@item 
bpo-46917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46917}: The @ref{873,,math.nan} value is now always available. Patch by
Victor Stinner.

@item 
bpo-46955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46955}: Expose @code{asyncio.base_events.Server} as
@ref{d08,,asyncio.Server}. Patch by Stefan Zabka.

@item 
bpo-23325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23325}: The @ref{cb,,signal} module no longer assumes that
@ref{1bb1,,SIG_IGN} and @ref{1bb2,,SIG_DFL} are small int
singletons.

@item 
bpo-46932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46932}: Update bundled libexpat to 2.4.7

@item 
bpo-46933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46933}: The @ref{b7,,pwd} module is now optional.
@ref{c09,,os.path.expanduser()} returns the path when the @ref{b7,,pwd} module is
not available.

@item 
bpo-40059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40059}: 
@geindex Python Enhancement Proposals; PEP 680
PEP 680@footnote{https://peps.python.org/pep-0680/}, the @ref{102,,tomllib} module. Adds support for parsing
TOML.

@item 
bpo-464471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=464471}: @ref{814,,asyncio.timeout()} and @ref{1bb3,,asyncio.timeout_at()} context
managers added. Patch by Tin Tvrtković and Andrew Svetlov.

@item 
bpo-46805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46805}: Added raw datagram socket functions for asyncio:
@code{sock_sendto()},
@code{sock_recvfrom()} and
@code{sock_recvfrom_into()}.

@item 
bpo-46644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46644}: No longer require valid typeforms to be callable. This allows
@ref{b37,,typing.Annotated} to wrap @ref{9c9,,typing.ParamSpecArgs} and
@ref{1bb4,,dataclasses.InitVar}. Patch by Gregory Beauregard.

@item 
bpo-46581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46581}: Brings @code{ParamSpec} propagation for @code{GenericAlias}
in line with @code{Concatenate} (and others).

@item 
bpo-45413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45413}: Define `posix_venv' and `nt_venv' @ref{449,,sysconfig installation schemes} to be used for bootstrapping new virtual
environments. Add `venv' sysconfig installation scheme to get the
appropriate one of the above. The schemes are identical to the
pre-existing `posix_prefix' and `nt' install schemes. The @ref{117,,venv}
module now uses the `venv' scheme to create new virtual environments
instead of hardcoding the paths depending only on the platform. Downstream
Python distributors customizing the `posix_prefix' or `nt' install scheme
in a way that is not compatible with the install scheme used in virtual
environments are encouraged not to customize the `venv' schemes. When
Python itself runs in a virtual environment,
@ref{1bb5,,sysconfig.get_default_scheme()} and
@ref{89f,,sysconfig.get_preferred_scheme()} with @code{key="prefix"} returns
`venv'.

@item 
bpo-43224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43224}: Implement support for PEP 646 in typing.py.

@item 
bpo-43224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43224}: Allow unpacking types.GenericAlias objects, e.g. @code{*tuple[int,
str]}.

@item 
bpo-46557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46557}: Warnings captured by the logging module are now logged without
a format string to prevent systems that group logs by the msg argument
from grouping captured warnings together.

@item 
bpo-41370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41370}: @ref{8c0,,typing.get_type_hints()} now supports evaluating strings
as forward references in @ref{8c1,,PEP 585 generic aliases}.

@item 
bpo-46607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46607}: Add @ref{1a3,,DeprecationWarning} to @code{LegacyInterpolation},
deprecated in the docstring since Python 3.2. Will be removed in Python
3.13. Use @code{BasicInterpolation} or @code{ExtendedInterpolation}
instead.

@item 
bpo-26120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26120}: @ref{ba,,pydoc} now excludes __future__ imports from the module's
data items.

@item 
bpo-46480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46480}: Add @ref{8ba,,typing.assert_type()}. Patch by Jelle Zijlstra.

@item 
bpo-46421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46421}: Fix a unittest issue where if the command was invoked as
@code{python -m unittest} and the filename(s) began with a dot (.), a
@code{ValueError} is returned.

@item 
bpo-46245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46245}: Add optional parameter `dir_fd' in @ref{356,,shutil.rmtree()}.

@item 
bpo-22859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22859}: @code{unittest.TestProgram.usageExit()} is marked as
deprecated, to be removed in Python 3.13.

@item 
bpo-46170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46170}: Improve the error message when you try to subclass an instance
of @ref{ef1,,typing.NewType}.

@item 
bpo-40296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40296}: Fix supporting generic aliases in @ref{ba,,pydoc}.

@item 
bpo-20392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20392}: Fix inconsistency with uppercase file extensions in
@code{MimeTypes.guess_type()}. Patch by Kumar Aditya.

@item 
bpo-46030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46030}: Add @code{LOCAL_CREDS}, @code{LOCAL_CREDS_PERSISTENT} and
@code{SCM_CREDS2} FreeBSD constants to the socket module.

@item 
bpo-44439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44439}: Fix @code{.write()} method of a member file in @code{ZipFile}, when
the input data is an object that supports the buffer protocol, the file
length may be wrong.

@item 
bpo-45171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45171}: Fix handling of the @code{stacklevel} argument to logging
functions in the @ref{8b,,logging} module so that it is consistent across all
logging functions and, as advertised, similar to the @code{stacklevel}
argument used in @ref{1732,,warn()}.

@item 
bpo-24959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24959}: Fix bug where @ref{10c,,unittest} sometimes drops frames from
tracebacks of exceptions raised in tests.

@item 
bpo-44859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44859}: Raise more accurate and 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} compatible exceptions in
@ref{d4,,sqlite3}.


@itemize *

@item 
Raise @ref{88d,,InterfaceError} instead of
@ref{305,,ProgrammingError} for @code{SQLITE_MISUSE} errors.

@item 
Don't overwrite @ref{1797,,BufferError} with @ref{2ec,,ValueError} when conversion to
BLOB fails.

@item 
Raise @ref{305,,ProgrammingError} instead of @ref{1bb6,,Warning} if
user tries to @ref{5b0,,execute()} more than one SQL statement.

@item 
Raise @ref{305,,ProgrammingError} instead of @ref{2ec,,ValueError} if an SQL
query contains null characters.
@end itemize

@item 
bpo-44493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44493}: Add missing terminated NUL in sockaddr_un's length

This was potentially observable when using non-abstract AF_UNIX datagram
sockets to processes written in another programming language.

@item 
bpo-41930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41930}: Add @ref{88e,,serialize()} and
@ref{88f,,deserialize()} support to @ref{d4,,sqlite3}. Patch
by Erlend E. Aasland.

@item 
bpo-33178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33178}: Added @ref{1bb7,,ctypes.BigEndianUnion} and
@ref{1bb8,,ctypes.LittleEndianUnion} classes, as originally documented in the
library docs but not yet implemented.

@item 
bpo-43352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43352}: Add an Barrier object in synchronization primitives of
`asyncio' Lib in order to be consistent with Barrier from `threading' and
`multiprocessing' libs*

@item 
bpo-35859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35859}: @ref{be,,re} module, fix a few bugs about capturing group. In rare
cases, capturing group gets an incorrect string. Patch by Ma Lin.
@end itemize

@node ドキュメント<30>,テスト<29>,ライブラリ<92>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id411}@anchor{1bb9}
@subsubsection ドキュメント



@itemize -

@item 
bpo-45099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45099}: Document internal @ref{b,,asyncio} API.

@item 
bpo-47126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47126}: Update PEP URLs to 
@geindex Python Enhancement Proposals; PEP 676
PEP 676@footnote{https://peps.python.org/pep-0676/}'s new canonical form.

@item 
bpo-47040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47040}: Clarified the old Python versions compatibility note of
@ref{1a11,,binascii.crc32()} / @ref{1bba,,zlib.adler32()} / @ref{1a10,,zlib.crc32()}
functions.

@item 
bpo-46033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46033}: Clarify @code{for} statement execution in its doc.

@item 
bpo-45790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45790}: Adjust inaccurate phrasing in
@ref{1bbb,,拡張の型の定義; チュートリアル} about the @code{ob_base} field and the
macros used to access its contents.

@item 
bpo-42340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42340}: Document that in some circumstances @ref{bc5,,KeyboardInterrupt}
may cause the code to enter an inconsistent state. Provided a sample
workaround to avoid it if needed.

@item 
bpo-41233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41233}: Link the errnos referenced in @code{Doc/library/exceptions.rst} to
their respective section in @code{Doc/library/errno.rst}, and vice versa.
Previously this was only done for EINTR and InterruptedError. Patch by Yan
"yyyyyyyan" Orestes.
@end itemize

@node テスト<29>,ビルド<35>,ドキュメント<30>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id412}@anchor{1bbc}
@subsubsection テスト



@itemize -

@item 
bpo-47205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47205}: Skip test for @ref{1322,,sched_getaffinity()} and
@ref{1326,,sched_setaffinity()} error case on FreeBSD.

@item 
bpo-46126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46126}: Restore 'descriptions' when running tests internally.

@item 
bpo-47104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47104}: Rewrite @ref{ae5,,asyncio.to_thread()} tests to use
@ref{361,,unittest.IsolatedAsyncioTestCase}.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: The test suite is now passing on the Emscripten platform. All
fork, socket, and subprocess-based tests are skipped.

@item 
bpo-47037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47037}: Skip @code{strftime("%4Y")} feature test on Windows. It can cause
an assertion error in debug builds.

@item 
bpo-46587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46587}: Skip tests if platform's @code{strftime} does not support
non-portable glibc extensions.

@item 
bpo-47015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47015}: A test case for @ref{d05,,os.sendfile()} is converted from
deprecated @code{asyncore} (see 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}) to @ref{b,,asyncio}. Patch by
Oleg Iarygin.
@end itemize

@node ビルド<35>,Windows<31>,テスト<29>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id413}@anchor{1bbd}
@subsubsection ビルド



@itemize -

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Add configure option @ref{1bbe,,--enable-wasm-dynamic-linking} to
enable @code{dlopen} and MAIN_MODULE / SIDE_MODULE on @code{wasm32-emscripten}.

@item 
bpo-46023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46023}: @code{makesetup} now detects and skips all duplicated module
definitions. The first entry wins.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Add SOABI @code{wasm32-emscripten} for Emscripten and
@code{wasm32-wasi} for WASI on 32bit WASM as well as @code{wasm64} counter
parts.

@item 
bpo-47032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47032}: Ensure Windows install builds fail correctly with a non-zero
exit code when part of the build fails.

@item 
bpo-47024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47024}: Update OpenSSL to 1.1.1n for macOS installers and all Windows
builds.

@item 
bpo-46996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46996}: The @ref{f6,,tkinter} package now requires Tcl/Tk version 8.5.12
or newer.

@item 
bpo-46973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46973}: Add @code{regen-configure} make target to regenerate configure
script with Christian's container image
@code{quay.io/tiran/cpython_autoconf:269}.

@item 
bpo-46917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46917}: Building Python now requires support of IEEE 754 floating-point
numbers. Patch by Victor Stinner.

@item 
bpo-45774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45774}: @code{configure} now verifies that all SQLite C APIs needed for
the @ref{d4,,sqlite3} extension module are found.
@end itemize

@node Windows<31>,macOS<22>,ビルド<35>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id414}@anchor{1bbf}
@subsubsection Windows



@itemize -

@item 
bpo-47194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47194}: Update @code{zlib} to v1.2.12 to resolve 
@geindex Common Vulnerabilities and Exposures; CVE 2018-25032
CVE 2018-25032@footnote{https://www.cve.org/CVERecord?id=CVE-2018-25032}.

@item 
bpo-47171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47171}: Enables installing the @code{py.exe} launcher on Windows
ARM64.

@item 
bpo-46566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46566}: Upgraded @ref{7da,,Python install manager} to support a new @code{-V:company/tag}
argument for full 
@geindex Python Enhancement Proposals; PEP 514
PEP 514@footnote{https://peps.python.org/pep-0514/} support and to detect ARM64 installs. The
@code{-64} suffix on arguments is deprecated, but still selects any
non-32-bit install. Setting 
@geindex PYLAUNCHER_ALLOW_INSTALL
@geindex 環境変数; PYLAUNCHER_ALLOW_INSTALL
@code{PYLAUNCHER_ALLOW_INSTALL} and
specifying a version that is not installed will attempt to install the
requested version from the Microsoft Store.

@item 
bpo-47086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47086}: The installer for Windows now includes documentation as loose
HTML files rather than a single compiled @code{.chm} file.

@item 
bpo-46907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46907}: Update Windows installer to use SQLite 3.38.1.

@item 
bpo-44549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44549}: Update bzip2 to 1.0.8 in Windows builds to mitigate
@geindex Common Vulnerabilities and Exposures; CVE 2016-3189
CVE 2016-3189@footnote{https://www.cve.org/CVERecord?id=CVE-2016-3189} and 
@geindex Common Vulnerabilities and Exposures; CVE 2019-12900
CVE 2019-12900@footnote{https://www.cve.org/CVERecord?id=CVE-2019-12900}.

@item 
bpo-46948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46948}: Prevent 
@geindex Common Vulnerabilities and Exposures; CVE 2022-26488
CVE 2022-26488@footnote{https://www.cve.org/CVERecord?id=CVE-2022-26488} by ensuring the Add to PATH option in
the Windows installer uses the correct path when being repaired.
@end itemize

@node macOS<22>,Tools/Demos<26>,Windows<31>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id415}@anchor{1bc0}
@subsubsection macOS



@itemize -

@item 
bpo-46890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46890}: Fix a regression in the setting of @code{sys._base_executable} in
framework builds, and thereby fix a regression in @ref{117,,venv} virtual
environments with such builds.

@item 
bpo-46907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46907}: Update macOS installer to SQLite 3.38.1.
@end itemize

@node Tools/Demos<26>,C API<31>,macOS<22>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id416}@anchor{1bc1}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Replace Emscripten's limited shell with Katie Bell's browser-ui
REPL from python-wasm project.
@end itemize

@node C API<31>,,Tools/Demos<26>,Python 3 11 0 alpha 7
@anchor{whatsnew/changelog id417}@anchor{1bc2}
@subsubsection C API



@itemize -

@item 
bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}: Add @code{PyFrame_GetBuiltins}, @code{PyFrame_GetGenerator} and
@code{PyFrame_GetGlobals} C-API functions to access frame object attributes
safely from C code.

@item 
bpo-46850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46850}: Move the private @code{_PyFrameEvalFunction} type, and private
@code{_PyInterpreterState_GetEvalFrameFunc()} and
@code{_PyInterpreterState_SetEvalFrameFunc()} functions to the internal C
API. The @code{_PyFrameEvalFunction} callback function type now uses the
@code{_PyInterpreterFrame} type which is part of the internal C API. Patch by
Victor Stinner.

@item 
bpo-46850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46850}: Move the private undocumented @code{_PyEval_EvalFrameDefault()}
function to the internal C API. The function now uses the
@code{_PyInterpreterFrame} type which is part of the internal C API. Patch by
Victor Stinner.

@item 
bpo-46850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46850}: Remove the private undocumented function
@code{_PyEval_CallTracing()} from the C API. Call the public
@ref{1bc3,,sys.call_tracing()} function instead. Patch by Victor Stinner.

@item 
bpo-46850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46850}: Remove the private undocumented function
@code{_PyEval_GetCoroutineOriginTrackingDepth()} from the C API. Call the
public @ref{d84,,sys.get_coroutine_origin_tracking_depth()} function instead.
Patch by Victor Stinner.

@item 
bpo-46850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46850}: Remove the following private undocumented functions from the C
API:


@itemize *

@item 
@code{_PyEval_GetAsyncGenFirstiter()}

@item 
@code{_PyEval_GetAsyncGenFinalizer()}

@item 
@code{_PyEval_SetAsyncGenFirstiter()}

@item 
@code{_PyEval_SetAsyncGenFinalizer()}
@end itemize

Call the public @ref{1bc4,,sys.get_asyncgen_hooks()} and
@ref{199d,,sys.set_asyncgen_hooks()} functions instead. Patch by Victor Stinner.

@item 
bpo-46987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46987}: Remove private functions @code{_PySys_GetObjectId()} and
@code{_PySys_SetObjectId()}. Patch by Donghee Na.

@item 
bpo-46906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46906}: Add new functions to pack and unpack C double (serialize and
deserialize): @ref{969,,PyFloat_Pack2()}, @ref{96a,,PyFloat_Pack4()},
@ref{96b,,PyFloat_Pack8()}, @ref{96c,,PyFloat_Unpack2()},
@ref{96d,,PyFloat_Unpack4()} and @ref{96e,,PyFloat_Unpack8()}. Patch by Victor
Stinner.
@end itemize

@node Python 3 11 0 alpha 6,Python 3 11 0 alpha 5,Python 3 11 0 alpha 7,変更履歴
@anchor{whatsnew/changelog python-3-11-0-alpha-6}@anchor{1bc5}
@subsection Python 3.11.0 alpha 6


`Release date: 2022-03-07'

@menu
* Core and Builtins: Core and Builtins<90>. 
* ライブラリ: ライブラリ<93>. 
* Core and Builtins: Core and Builtins<91>. 
* ライブラリ: ライブラリ<94>. 
* Core and Builtins: Core and Builtins<92>. 
* ライブラリ: ライブラリ<95>. 
* Core and Builtins: Core and Builtins<93>. 
* ライブラリ: ライブラリ<96>. 
* ドキュメント: ドキュメント<31>. 
* テスト: テスト<30>. 
* ビルド: ビルド<36>. 
* Windows: Windows<32>. 
* IDLE: IDLE<16>. 
* C API: C API<32>. 

@end menu

@node Core and Builtins<90>,ライブラリ<93>,,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id418}@anchor{1bc6}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46940}: Avoid overriding @ref{5f0,,AttributeError} metadata information for
nested attribute access calls. Patch by Pablo Galindo.

@item 
bpo-46927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46927}: Include the type's name in the error message for subscripting
non-generic types.

@item 
bpo-46921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46921}: Support vectorcall for @code{super()}. Patch by Ken Jin.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Fix incorrect handling of inline cache entries when
specializing @ref{366,,BINARY_OP}.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Use an oparg to simplify the construction of helpful error
messages in @ref{1bc7,,GET_AWAITABLE}.

@item 
bpo-46903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46903}: Make sure that str subclasses can be used as attribute names
for instances with virtual dictionaries. Fixes regression in 3.11alpha

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Add more detailed specialization failure stats for
@ref{b61,,COMPARE_OP} followed by @ref{1b1e,,EXTENDED_ARG}.

@item 
bpo-46891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46891}: Fix bug introduced during 3.11alpha where subclasses of
@code{types.ModuleType} with @code{__slots__} were not initialized correctly,
resulting in an interpreter crash.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Use inline caching for @ref{704,,LOAD_ATTR},
@code{LOAD_METHOD}, and @ref{1bc8,,STORE_ATTR}.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Use inline cache for @code{BINARY_SUBSCR}.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Use inline caching for @ref{b61,,COMPARE_OP}.

@item 
bpo-46864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46864}: Deprecate @code{PyBytesObject.ob_shash}. It will be removed in
Python 3.13.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Use inline caching for @ref{1bc9,,UNPACK_SEQUENCE}.

@item 
bpo-46845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46845}: Reduces dict size by removing hash value from hash table when
all inserted keys are Unicode. For example,
@code{sys.getsizeof(dict.fromkeys("abcdefg"))} becomes 272 bytes from 352
bytes on 64bit platform.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Use inline cache for @ref{1a5a,,LOAD_GLOBAL}.

@item 
bpo-46852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46852}: Rename the private undocumented @code{float.__set_format__()}
method to @code{float.__setformat__()} to fix a typo introduced in Python
3.7. The method is only used by test_float. Patch by Victor Stinner.

@item 
bpo-46852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46852}: Remove the undocumented private @code{float.__set_format__()}
method, previously known as @code{float.__setformat__()} in Python 3.7. Its
docstring said: "You probably don't want to use this function. It exists
mainly to be used in Python's test suite." Patch by Victor Stinner.

@item 
bpo-40116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40116}: Fix regression that dict.update(other) may don't respect
iterate order of other when other is key sharing dict.

@item 
bpo-46712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46712}: Share global string identifiers in deep-frozen modules.

@item 
bpo-46430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46430}: Fix memory leak in interned strings of deep-frozen modules.

@item 
bpo-46841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46841}: Store @ref{366,,BINARY_OP} caches inline using a new
@ref{908,,CACHE} instruction.

@item 
bpo-45107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45107}: Specialize @code{LOAD_METHOD} for instances with a dict.

@item 
bpo-44337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44337}: Reduce the memory usage of specialized @ref{704,,LOAD_ATTR} and
@ref{1bc8,,STORE_ATTR} instructions.

@item 
bpo-46729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46729}: Add number of sub-exceptions to @code{BaseException.__str__()}.

@item 
bpo-45885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45885}: Don't un-adapt @ref{b61,,COMPARE_OP} when collecting
specialization stats.

@item 
bpo-46329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46329}: Fix specialization stats gathering for @code{PRECALL}
instructions.
@end itemize

@node ライブラリ<93>,Core and Builtins<91>,Core and Builtins<90>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id419}@anchor{1bca}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46794}: Bump up the libexpat version into 2.4.6
@end itemize

@node Core and Builtins<91>,ライブラリ<94>,ライブラリ<93>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id420}@anchor{1bcb}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46823}: Implement a specialized combined opcode
@code{LOAD_FAST__LOAD_ATTR_INSTANCE_VALUE}.  Patch by Dennis Sweeney.

@item 
bpo-46820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46820}: Fix parsing a numeric literal immediately (without spaces)
followed by "not in" keywords, like in @code{1not in x}. Now the parser only
emits a warning, not a syntax error.

@item 
bpo-46329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46329}: Move @code{KW_NAMES} before @code{PRECALL} instruction in call
sequence. Change @code{operand} of @code{CALL} to match @code{PRECALL} for easier
specialization.

@item 
bpo-46808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46808}: Remove the @code{NEXT_BLOCK} macro from compile.c, and make the
compiler automatically generate implicit blocks when they are needed.

@item 
bpo-46329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46329}: Add @code{PUSH_NULL} instruction. This is used as a prefix when
evaluating a callable, so that the stack has the same shape for methods
and other calls. @code{PRECALL_FUNCTION} and @code{PRECALL_METHOD} are merged
into a single @code{PRECALL} instruction.

There is no change in semantics.

@item 
bpo-46762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46762}: Fix an assert failure in debug builds when a '<', '>', or '='
is the last character in an f-string that's missing a closing right brace.

@item 
bpo-46730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46730}: Message of AttributeError caused by getting, setting or
deleting a property without the corresponding function now mentions that
the attribute is in fact a property and also specifies type of the class
that it belongs to.

@item 
bpo-46724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46724}: Make sure that all backwards jumps use the @code{JUMP_ABSOLUTE}
instruction, rather than @code{JUMP_FORWARD} with an argument of
@code{(2**32)+offset}.

@item 
bpo-46732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46732}: Correct the docstring for the @ref{14ed,,__bool__()} method.
Patch by Jelle Zijlstra.

@item 
bpo-46072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46072}: Add more detailed specialization failure statistics for
@ref{366,,BINARY_OP}.

@item 
bpo-46707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46707}: Avoid potential exponential backtracking when producing some
syntax errors involving lots of brackets. Patch by Pablo Galindo.
@end itemize

@node ライブラリ<94>,Core and Builtins<92>,Core and Builtins<91>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id421}@anchor{1bcc}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46323}: @ref{2e,,ctypes} now allocates memory on the stack instead of on
the heap to pass arguments while calling a Python callback function. Patch
by Donghee Na.
@end itemize

@node Core and Builtins<92>,ライブラリ<95>,ライブラリ<94>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id422}@anchor{1bcd}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-45923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45923}: Add a quickened form of @ref{5bb,,RESUME} that skips quickening
checks.

@item 
bpo-46702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46702}: Specialize @ref{1bc9,,UNPACK_SEQUENCE} for @ref{614,,tuple} and
@ref{24d,,list} unpackings.

@item 
bpo-46072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46072}: Opcode pair stats are now gathered with @code{--enable-pystats}.
Defining @code{DYNAMIC_EXECUTION_PROFILE} or  @code{DXPAIRS} no longer has any
effect.

@item 
bpo-46675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46675}: Allow more than 16 items in a split dict before it is combined.
The limit is now 254.
@end itemize

@node ライブラリ<95>,Core and Builtins<93>,Core and Builtins<92>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id423}@anchor{1bce}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: Add a missing call to @code{va_end()} in
@code{Modules/_hashopenssl.c}.

@item 
bpo-46323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46323}: Use @ref{77e,,PyObject_Vectorcall()} while calling ctypes callback
function. Patch by Donghee Na.
@end itemize

@node Core and Builtins<93>,ライブラリ<96>,ライブラリ<95>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id424}@anchor{1bcf}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46615}: When iterating over sets internally in @code{setobject.c}, acquire
strong references to the resulting items from the set.  This prevents
crashes in corner-cases of various set operations where the set gets
mutated.

@item 
bpo-45828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45828}: The bytecode compiler now attempts to apply runtime stack
manipulations at compile-time (whenever it is feasible to do so).

@item 
bpo-30496@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30496}: Fixed a minor portability issue in the implementation of
@ref{1bd0,,PyLong_FromLong()}, and added a fast path for single-digit integers
to @ref{1bd1,,PyLong_FromLongLong()}.
@end itemize

@node ライブラリ<96>,ドキュメント<31>,Core and Builtins<93>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id425}@anchor{1bd2}
@subsubsection ライブラリ



@itemize -

@item 
bpo-25707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25707}: Fixed a file leak in @ref{57a,,xml.etree.ElementTree.iterparse()}
when the iterator is not exhausted. Patch by Jacob Walls.

@item 
bpo-46877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46877}: Export @ref{1bd3,,unittest.doModuleCleanups()} in @ref{10c,,unittest}.
Patch by Kumar Aditya.

@item 
bpo-46848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46848}: For performance, use the optimized string-searching
implementations from @ref{1bd4,,find()} and @ref{1bd5,,rfind()} for
@code{find()} and @code{rfind()}.

@item 
bpo-46736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46736}: @ref{d38,,SimpleHTTPRequestHandler} now uses HTML5
grammar. Patch by Donghee Na.

@item 
bpo-44886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44886}: Inherit asyncio proactor datagram transport from
@ref{1b27,,asyncio.DatagramTransport}.

@item 
bpo-46827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46827}: Support UDP sockets in  @ref{fc8,,asyncio.loop.sock_connect()} for
selector-based event loops.  Patch by Thomas Grainger.

@item 
bpo-46811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46811}: Make test suite support Expat >=2.4.5

@item 
bpo-46252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46252}: Raise @ref{198,,TypeError} if @ref{ae7,,ssl.SSLSocket} is passed to
transport-based APIs.

@item 
bpo-46784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46784}: Fix libexpat symbols collisions with user dynamically loaded or
statically linked libexpat in embedded Python.

@item 
bpo-46786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46786}: The HTML serialisation in xml.etree.ElementTree now writes
@code{embed}, @code{source}, @code{track} and @code{wbr} as empty tags, as defined in
HTML 5.

@item 
bpo-39327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39327}: @ref{356,,shutil.rmtree()} can now work with VirtualBox shared
folders when running from the guest operating-system.

@item 
bpo-45390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45390}: Propagate @ref{4d4,,asyncio.CancelledError} message from inner task
to outer awaiter.

@item 
bpo-46756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46756}: Fix a bug in
@ref{1bd6,,urllib.request.HTTPPasswordMgr.find_user_password()} and
@ref{1bd7,,urllib.request.HTTPPasswordMgrWithPriorAuth.is_authenticated()} which
allowed to bypass authorization. For example, access to URI
@code{example.org/foobar} was allowed if the user was authorized for URI
@code{example.org/foo}.

@item 
bpo-46737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46737}: @ref{1bd8,,random.gauss()} and @ref{1bd9,,random.normalvariate()} now have
default arguments.

@item 
bpo-46752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46752}: Add task groups to asyncio (structured concurrency, inspired by
Trio's nurseries). This also introduces a change to task cancellation,
where a cancelled task can't be cancelled again until it calls
.uncancel().

@item 
bpo-46724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46724}: Fix @ref{3c,,dis} behavior on negative jump offsets.

@item 
bpo-46333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46333}: The @code{__repr__()} method of @ref{1bda,,typing.ForwardRef} now
includes the @code{module} parameter of @ref{1bda,,typing.ForwardRef} when it is
set.

@item 
bpo-46643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46643}: In @ref{8c0,,typing.get_type_hints()}, support evaluating
stringified @code{ParamSpecArgs} and @code{ParamSpecKwargs} annotations. Patch
by Gregory Beauregard.

@item 
bpo-45863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45863}: When the @ref{e4,,tarfile} module creates a pax format archive, it
will put an integer representation of timestamps in the ustar header (if
possible) for the benefit of older unarchivers, in addition to the
existing full-precision timestamps in the pax extended header.

@item 
bpo-46066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46066}: Deprecate kwargs-based syntax for @ref{332,,typing.TypedDict}
definitions. It had confusing semantics when specifying totality, and was
largely unused. Patch by Jingchen Ye.

@item 
bpo-46676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46676}: Make @ref{487,,typing.ParamSpec} args and kwargs equal to
themselves. Patch by Gregory Beauregard.

@item 
bpo-46323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46323}: @code{ctypes.CFUNCTYPE()} and @code{ctypes.WINFUNCTYPE()} now fail to
create the type if its @code{_argtypes_} member contains too many arguments.
Previously, the error was only raised when calling a function. Patch by
Victor Stinner.

@item 
bpo-46672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46672}: Fix @code{NameError} in @ref{813,,asyncio.gather()} when initial type
check fails.

@item 
bpo-46659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46659}: The @ref{94b,,calendar.LocaleTextCalendar} and
@ref{94c,,calendar.LocaleHTMLCalendar} classes now use
@ref{327,,locale.getlocale()}, instead of using
@ref{326,,locale.getdefaultlocale()}, if no locale is specified. Patch by
Victor Stinner.

@item 
bpo-46659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46659}: The @ref{326,,locale.getdefaultlocale()} function is deprecated and
will be removed in Python 3.13. Use @ref{328,,locale.setlocale()},
@ref{75c,,locale.getpreferredencoding(False)}
and @ref{327,,locale.getlocale()} functions instead.  Patch by Victor Stinner.

@item 
bpo-46655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46655}: In @ref{8c0,,typing.get_type_hints()}, support evaluating bare
stringified @code{TypeAlias} annotations. Patch by Gregory Beauregard.

@item 
bpo-45948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45948}: Fixed a discrepancy in the C implementation of the
@ref{12b,,xml.etree.ElementTree} module. Now, instantiating an
@ref{c49,,xml.etree.ElementTree.XMLParser} with a @code{target=None} keyword
provides a default @ref{c4a,,xml.etree.ElementTree.TreeBuilder} target as
the Python implementation does.

@item 
bpo-46626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46626}: Expose Linux's @code{IP_BIND_ADDRESS_NO_PORT} option in
@ref{d1,,socket}.

@item 
bpo-46521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46521}: Fix a bug in the @ref{1d,,codeop} module that was incorrectly
identifying invalid code involving string quotes as valid code.

@item 
bpo-46571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46571}: Improve @ref{8c3,,typing.no_type_check()}.

Now it does not modify external classes and functions. We also now
correctly mark classmethods as not to be type checked.

@item 
bpo-46400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46400}: expat: Update libexpat from 2.4.1 to 2.4.4

@item 
bpo-46556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46556}: Deprecate undocumented support for using a
@ref{266,,pathlib.Path} object as a context manager.

@item 
bpo-46534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46534}: Implement 
@geindex Python Enhancement Proposals; PEP 673
PEP 673@footnote{https://peps.python.org/pep-0673/} @ref{7e3,,typing.Self}. Patch by James
Hilton-Balfe.

@item 
bpo-46522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46522}: Make various module @code{__getattr__} AttributeErrors more
closely match a typical AttributeError

@item 
bpo-46475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46475}: Add @ref{8b7,,typing.Never} and @ref{8b6,,typing.assert_never()}. Patch
by Jelle Zijlstra.

@item 
bpo-46333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46333}: The @code{__eq__()} and @code{__hash__()} methods of
@ref{1bda,,typing.ForwardRef} now honor the @code{module} parameter of
@ref{1bda,,typing.ForwardRef}. Forward references from different modules are
now differentiated.

@item 
bpo-46246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46246}: Add missing @code{__slots__} to
@code{importlib.metadata.DeprecatedList}. Patch by Arie Bovenberg.

@item 
bpo-46232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46232}: The @ref{d5,,ssl} module now handles certificates with bit strings
in DN correctly.

@item 
bpo-46195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46195}: @ref{8c0,,typing.get_type_hints()} no longer adds @code{Optional} to
parameters with @code{None} as a default. This aligns to changes to PEP 484
in @indicateurl{https://github.com/python/peps/pull/689}

@item 
bpo-31369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31369}: Add @ref{83f,,RegexFlag} to @code{re.__all__} and documented it.
Add @code{NOFLAG} to indicate no flags being set.

@item 
bpo-45898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45898}: @ref{2e,,ctypes} no longer defines @code{ffi_type_*} symbols in
@code{cfield.c}. The symbols have been provided by libffi for over a decade.

@item 
bpo-44953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44953}: Calling @code{operator.itemgetter} objects and
@code{operator.attrgetter} objects is now faster due to use of the vectorcall
calling convention.

@item 
bpo-44289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44289}: Fix an issue with @ref{1bdb,,is_tarfile()} method when using
`fileobj' argument: position in the `fileobj' was advanced forward which
made it unreadable with @ref{1bdc,,tarfile.TarFile.open()}.

@item 
bpo-44011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44011}: Reimplement SSL/TLS support in asyncio, borrow the
implementation from uvloop library.

@item 
bpo-41086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41086}: Make the @ref{4de,,configparser.ConfigParser} constructor raise
@ref{198,,TypeError} if the @code{interpolation} parameter is not of type
@code{configparser.Interpolation}

@item 
bpo-29418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29418}: Implement @ref{85a,,inspect.ismethodwrapper()} and fix
@ref{1bdd,,inspect.isroutine()} for cases where methodwrapper is given. Patch by
Hakan Çelik.

@item 
bpo-14156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14156}: argparse.FileType now supports an argument of '-' in binary
mode, returning the .buffer attribute of sys.stdin/sys.stdout as
appropriate. Modes including 'x' and 'a' are treated equivalently to 'w'
when argument is '-'. Patch contributed by Josh Rosenberg
@end itemize

@node ドキュメント<31>,テスト<30>,ライブラリ<96>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id426}@anchor{1bde}
@subsubsection ドキュメント



@itemize -

@item 
bpo-42238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42238}: @code{Doc/tools/rstlint.py} has moved to its own repository and is
now packaged on PyPI as @code{sphinx-lint}.
@end itemize

@node テスト<30>,ビルド<36>,ドキュメント<31>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id427}@anchor{1bdf}
@subsubsection テスト



@itemize -

@item 
bpo-46913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46913}: Fix test_faulthandler.test_sigfpe() if Python is built with
undefined behavior sanitizer (UBSAN): disable UBSAN on the
faulthandler_sigfpe() function. Patch by Victor Stinner.

@item 
bpo-46760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46760}: Remove bytecode offsets from expected values in test.test_dis
module. Reduces the obstacles to modifying the VM or compiler.

@item 
bpo-46708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46708}: Prevent default asyncio event loop policy modification warning
after @code{test_asyncio} execution.

@item 
bpo-46678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46678}: The function @code{make_legacy_pyc} in
@code{Lib/test/support/import_helper.py} no longer fails when
@code{PYTHONPYCACHEPREFIX} is set to a directory on a different device from
where tempfiles are stored.

@item 
bpo-46623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46623}: Skip test_pair() and test_speech128() of test_zlib on s390x
since they fail if zlib uses the s390x hardware accelerator. Patch by
Victor Stinner.
@end itemize

@node ビルド<36>,Windows<32>,テスト<30>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id428}@anchor{1be0}
@subsubsection ビルド



@itemize -

@item 
bpo-46860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46860}: Respect @code{--with-suffix} when building on case-insensitive
file systems.

@item 
bpo-46656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46656}: Building Python now requires a C11 compiler. Optional C11
features are not required. Patch by Victor Stinner.

@item 
bpo-46656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46656}: Building Python now requires support for floating-point
Not-a-Number (NaN): remove the @code{Py_NO_NAN} macro. Patch by Victor
Stinner.

@item 
bpo-46640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46640}: Building Python now requires a C99 @code{<math.h>} header file
providing a @code{NAN} constant, or the @code{__builtin_nan()} built-in
function. Patch by Victor Stinner.

@item 
bpo-46608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46608}: Exclude marshalled-frozen data if deep-freezing to save 300 KB
disk space. This includes adding a new @code{is_package} field to
@ref{979,,_frozen}. Patch by Kumar Aditya.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Fix wasm32-emscripten test failures and platform issues. -
Disable syscalls that are not supported or don't work, e.g.   wait,
getrusage, prlimit, mkfifo, mknod, setres[gu]id, setgroups. - Use fd_count
to count open fds. - Add more checks for subprocess and fork. - Add
workarounds for missing _multiprocessing and failing socket.accept(). -
Enable bzip2. - Disable large file support. - Disable signal.alarm.

@item 
bpo-46430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46430}: Intern strings in deep-frozen modules. Patch by Kumar Aditya.
@end itemize

@node Windows<32>,IDLE<16>,ビルド<36>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id429}@anchor{1be1}
@subsubsection Windows



@itemize -

@item 
bpo-46744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46744}: The default all users install directory for ARM64 is now under
the native @code{Program Files} folder, rather than @code{Program Files (Arm)}
which is intended for ARM (32-bit) files.

@item 
bpo-46567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46567}: Adds Tcl and Tk support for Windows ARM64. This also adds IDLE
to the installation.

@item 
bpo-46638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46638}: Ensures registry virtualization is consistently disabled. For
3.10 and earlier, it remains enabled (some registry writes are protected),
while for 3.11 and later it is disabled (registry modifications affect all
applications).
@end itemize

@node IDLE<16>,C API<32>,Windows<32>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id430}@anchor{1be2}
@subsubsection IDLE



@itemize -

@item 
bpo-46630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46630}: Make query dialogs on Windows start with a cursor in the entry
box.

@item 
bpo-45447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45447}: Apply IDLE syntax highlighting to @code{.pyi} files. Patch by Alex
Waygood and Terry Jan Reedy.
@end itemize

@node C API<32>,,IDLE<16>,Python 3 11 0 alpha 6
@anchor{whatsnew/changelog id431}@anchor{1be3}
@subsubsection C API



@itemize -

@item 
bpo-46748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46748}: Python's public headers no longer import @code{<stdbool.h>},
leaving code that embeds/extends Python free to define @code{bool}, @code{true}
and @code{false}.

@item 
bpo-46836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46836}: Move the @ref{98c,,PyFrameObject} type definition (@code{struct
_frame}) to the internal C API @code{pycore_frame.h} header file. Patch by
Victor Stinner.

@item 
bpo-45459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45459}: Rename @code{Include/buffer.h} header file to
@code{Include/pybuffer.h} to avoid conflicts with projects having an existing
@code{buffer.h} header file. Patch by Victor Stinner.

@item 
bpo-45412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45412}: Remove the @code{HAVE_PY_SET_53BIT_PRECISION} macro (moved to the
internal C API). Patch by Victor Stinner.

@item 
bpo-46613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46613}: Added function @ref{635,,PyType_GetModuleByDef()}, which allows
access to module state when a method's defining class is not available.
@end itemize

@node Python 3 11 0 alpha 5,Python 3 11 0 alpha 4,Python 3 11 0 alpha 6,変更履歴
@anchor{whatsnew/changelog python-3-11-0-alpha-5}@anchor{1be4}
@subsection Python 3.11.0 alpha 5


`Release date: 2022-02-03'

@menu
* Core and Builtins: Core and Builtins<94>. 
* ライブラリ: ライブラリ<97>. 
* Core and Builtins: Core and Builtins<95>. 
* ライブラリ: ライブラリ<98>. 
* ビルド: ビルド<37>. 
* Core and Builtins: Core and Builtins<96>. 
* ライブラリ: ライブラリ<99>. 
* ドキュメント: ドキュメント<32>. 
* テスト: テスト<31>. 
* ビルド: ビルド<38>. 
* Windows: Windows<33>. 
* macOS: macOS<23>. 
* IDLE: IDLE<17>. 
* C API: C API<33>. 

@end menu

@node Core and Builtins<94>,ライブラリ<97>,,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id432}@anchor{1be5}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-45773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45773}: Remove two invalid "peephole" optimizations from the bytecode
compiler.

@item 
bpo-46564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46564}: Do not create frame objects when creating @ref{1a6,,super}
object. Patch by Kumar Aditya.

@item 
bpo-45885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45885}: Added more fined-grained specialization failure stats regarding
the @code{COMPARE_OP} bytecode.

@item 
bpo-44977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44977}: The delegation of @ref{19b,,int()} to @code{__trunc__()} is now
deprecated. Calling @code{int(a)} when @code{type(a)} implements
@code{__trunc__()} but not @code{__int__()} or @code{__index__()} now raises
a @ref{1a3,,DeprecationWarning}.

@item 
bpo-46458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46458}: Reorder code emitted by the compiler for a
@ref{8f8,,try}-@ref{1ab,,except} block so that the @ref{17c,,else} block's
code immediately follows the @ref{8f8,,try} body (without a jump). This is
more optimal for the happy path.

@item 
bpo-46527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46527}: Allow passing @code{iterable} as a keyword argument to
@ref{169a,,enumerate()} again. Patch by Jelle Zijlstra.

@item 
bpo-46528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46528}: Replace several stack manipulation instructions (@code{DUP_TOP},
@code{DUP_TOP_TWO}, @code{ROT_TWO}, @code{ROT_THREE}, @code{ROT_FOUR}, and @code{ROT_N})
with new @ref{917,,COPY} and @ref{918,,SWAP} instructions.

@item 
bpo-46329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46329}: Use two or three bytecodes to implement most calls.

Calls without named arguments are implemented as a sequence of two
instructions: @code{PRECALL; CALL}. Calls with named arguments are
implemented as a sequence of three instructions: @code{PRECALL; KW_NAMES;
CALL}. There are two different @code{PRECALL} instructions:
@code{PRECALL_FUNTION} and @code{PRECALL_METHOD}. The latter pairs with
@code{LOAD_METHOD}.

This partition into pre-call and call allows better specialization, and
thus better performance ultimately.

There is no change in semantics.

@item 
bpo-46503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46503}: Fix an assert when parsing some invalid N escape sequences in
f-strings.

@item 
bpo-46431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46431}: Improve error message on invalid calls to
@code{BaseExceptionGroup.__new__()}.

@item 
bpo-46476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46476}: Fix memory leak in code objects generated by deepfreeze. Patch
by Kumar Aditya.

@item 
bpo-46481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46481}: Speed up calls to @code{weakref.ref.__call__()} by using the
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} @code{vectorcall} calling convention. Patch by Donghee Na.

@item 
bpo-46417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46417}: Fix a race condition on setting a type @code{__bases__} attribute:
the internal function @code{add_subclass()} now gets the
@code{PyTypeObject.tp_subclasses} member after calling
@ref{1be6,,PyWeakref_NewRef()} which can trigger a garbage collection which
can indirectly modify @code{PyTypeObject.tp_subclasses}. Patch by Victor
Stinner.

@item 
bpo-46417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46417}: @code{python -X showrefcount} now shows the total reference count
after clearing and destroyed the main Python interpreter. Previously, it
was shown before. Patch by Victor Stinner.

@item 
bpo-43683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43683}: Add ASYNC_GEN_WRAP opcode to wrap the value to be yielded in
async generators. Removes the need to special case async generators in the
@code{YIELD_VALUE} instruction.

@item 
bpo-46407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46407}: Optimize some modulo operations in @code{Objects/longobject.c}.
Patch by Jeremiah Vivian.

@item 
bpo-46409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46409}: Add new @code{RETURN_GENERATOR} bytecode to make generators.
Simplifies calling Python functions in the VM, as they no longer any need
to special case generator functions.

Also add @code{JUMP_NO_INTERRUPT} bytecode that acts like @code{JUMP_ABSOLUTE},
but does not check for interrupts.

@item 
bpo-46406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46406}: The integer division @code{//} implementation has been optimized
to better let the compiler understand its constraints. It can be 20%
faster on the amd64 platform when dividing an int by a value smaller than
@code{2**30}.
@end itemize

@node ライブラリ<97>,Core and Builtins<95>,Core and Builtins<94>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id433}@anchor{1be7}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46383}: Fix invalid signature of @code{_zoneinfo}'s @code{module_free}
function to resolve a crash on wasm32-emscripten platform.
@end itemize

@node Core and Builtins<95>,ライブラリ<98>,ライブラリ<97>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id434}@anchor{1be8}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46361}: Ensure that "small" integers created by @ref{1be9,,int.from_bytes()}
and @ref{1fe,,decimal.Decimal} are properly cached.

@item 
bpo-46161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46161}: Fix the class building error when the arguments are constants
and CALL_FUNCTION_EX is used.

@item 
bpo-46028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46028}: Fixes calculation of @code{sys._base_executable} when inside a
virtual environment that uses symlinks with different binary names than
the base environment provides.

@item 
bpo-46091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46091}: Correctly calculate indentation levels for lines with
whitespace character that are ended by line continuation characters. Patch
by Pablo Galindo
@end itemize

@node ライブラリ<98>,ビルド<37>,Core and Builtins<95>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id435}@anchor{1bea}
@subsubsection ライブラリ



@itemize -

@item 
bpo-30512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30512}: Add CAN Socket support for NetBSD.
@end itemize

@node ビルド<37>,Core and Builtins<96>,ライブラリ<98>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id436}@anchor{1beb}
@subsubsection ビルド



@itemize -

@item 
bpo-46045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46045}: Do not use POSIX semaphores on NetBSD
@end itemize

@node Core and Builtins<96>,ライブラリ<99>,ビルド<37>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id437}@anchor{1bec}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44024}: Improve the @ref{198,,TypeError} message for non-string second
arguments passed to the built-in functions @ref{dca,,getattr()} and
@ref{6f9,,hasattr()}. Patch by Géry Ogam.
@end itemize

@node ライブラリ<99>,ドキュメント<32>,Core and Builtins<96>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id438}@anchor{1bed}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46624}: Restore support for non-integer arguments of
@ref{a6b,,random.randrange()} and @ref{1447,,random.randint()}.

@item 
bpo-46591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46591}: Make the IDLE doc URL on the About IDLE dialog clickable.

@item 
bpo-46565@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46565}: Remove loop variables that are leaking into modules'
namespaces.

@item 
bpo-46553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46553}: In @ref{8c0,,typing.get_type_hints()}, support evaluating bare
stringified @code{ClassVar} annotations. Patch by Gregory Beauregard.

@item 
bpo-46544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46544}: Don't leak @code{x} & @code{uspace} intermediate vars in
@ref{11cf,,textwrap.TextWrapper}.

@item 
bpo-46487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46487}: Add the @code{get_write_buffer_limits} method to
@code{asyncio.transports.WriteTransport} and to the SSL transport.

@item 
bpo-45173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45173}: Note the configparser deprecations will be removed in Python
3.12.

@item 
bpo-45162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45162}: The deprecated @ref{10c,,unittest} APIs removed in 3.11a1 have been
temporarily restored to be removed in 3.12 while cleanups in external
projects go in.

@item 
bpo-46539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46539}: In @ref{8c0,,typing.get_type_hints()}, support evaluating
stringified @code{ClassVar} and @code{Final} annotations inside @code{Annotated}.
Patch by Gregory Beauregard.

@item 
bpo-46510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46510}: Add missing test for @ref{cea,,types.TracebackType} and
@ref{1bee,,types.FrameType}. Calculate them directly from the caught
exception without calling @ref{89a,,sys.exc_info()}.

@item 
bpo-46491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46491}: Allow @ref{b37,,typing.Annotated} to wrap @ref{56e,,typing.Final} and
@ref{56d,,typing.ClassVar}. Patch by Gregory Beauregard.

@item 
bpo-46483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46483}: Remove @ref{943,,__class_getitem__()} from
@ref{6cd,,pathlib.PurePath} as this class was not supposed to be generic.

@item 
bpo-46436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46436}: Fix command-line option @code{-d}/@code{--directory} in module
@ref{76,,http.server} which is ignored when combined with command-line option
@code{--cgi}. Patch by Géry Ogam.

@item 
bpo-41403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41403}: Make @code{mock.patch()} raise a @ref{198,,TypeError} with a
relevant error message on invalid arg. Previously it allowed a cryptic
@ref{5f0,,AttributeError} to escape.

@item 
bpo-46474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46474}: In @code{importlib.metadata.EntryPoint.pattern}, avoid potential
REDoS by limiting ambiguity in consecutive whitespace.

@item 
bpo-46474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46474}: Removed private method from @code{importlib.metadata.Path}. Sync
with importlib_metadata 4.10.0.

@item 
bpo-46470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46470}: Remove unused branch from @code{typing._remove_dups_flatten}

@item 
bpo-46469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46469}: @ref{b,,asyncio} generic classes now return
@ref{9ec,,types.GenericAlias} in @code{__class_getitem__} instead of the same
class.

@item 
bpo-41906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41906}: Support passing filter instances in the @code{filters} values of
@code{handlers} and @code{loggers} in the dictionary passed to
@ref{13c8,,logging.config.dictConfig()}.

@item 
bpo-46422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46422}: Use @code{dis.Positions} in @code{dis.Instruction} instead of a
regular @code{tuple}.

@item 
bpo-46434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46434}: @ref{aa,,pdb} now gracefully handles @code{help} when
@ref{1bef,,__doc__} is missing, for example when run with pregenerated
optimized @code{.pyc} files.

@item 
bpo-43869@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43869}: Python uses the same time Epoch on all platforms. Add an
explicit unit test to ensure that it's the case. Patch by Victor Stinner.

@item 
bpo-46414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46414}: Add @ref{8b9,,typing.reveal_type()}. Patch by Jelle Zijlstra.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: @ref{dc,,subprocess} now imports Windows-specific imports when
@code{msvcrt} module is available, and POSIX-specific imports on all other
platforms. This gives a clean exception when @code{_posixsubprocess} is not
available (e.g. Emscripten browser target).

@item 
bpo-40066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40066}: @code{IntEnum}, @code{IntFlag}, and @code{StrEnum} use the mixed-in type
for their @code{str()} and @code{format()} output.

@item 
bpo-46316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46316}: Optimize @ref{26e,,pathlib.Path.iterdir()} by removing an
unnecessary check for special entries.

@item 
bpo-29688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29688}: Document @ref{1a26,,pathlib.Path.absolute()} (which has always
existed).

@item 
bpo-43012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43012}: The pathlib module's obsolete and internal @code{_Accessor} class
has been removed to prepare the terrain for upcoming enhancements to the
module.

@item 
bpo-46258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46258}: Speed up @ref{bf8,,math.isqrt()} for small positive integers by
replacing two division steps with a lookup table.

@item 
bpo-46242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46242}: Improve error message when creating a new @ref{842,,enum.Enum}
type subclassing an existing @code{Enum} with @code{_member_names_} using
@code{enum.Enum.__call__()}.

@item 
bpo-43118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43118}: Fix a bug in @ref{22f,,inspect.signature()} that was causing it to
fail on some subclasses of classes with a @code{__text_signature__}
referencing module globals. Patch by Weipeng Hong.

@item 
bpo-26552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26552}: Fixed case where failing @ref{e71,,asyncio.ensure_future()} did not
close the coroutine. Patch by Kumar Aditya.

@item 
bpo-21987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21987}: Fix an issue with @ref{1bf0,,tarfile.TarFile.getmember()} getting a
directory name with a trailing slash.

@item 
bpo-46124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46124}: Update @ref{13a,,zoneinfo} to rely on importlib.resources
traversable API.

@item 
bpo-46103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46103}: Now @ref{1bf1,,inspect.getmembers()} only gets @code{__bases__}
attribute from class type. Patch by Weipeng Hong.

@item 
bpo-46080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46080}: Fix exception in argparse help text generation if a
@ref{1bf2,,argparse.BooleanOptionalAction} argument's default is
@code{argparse.SUPPRESS} and it has @code{help} specified.  Patch by Felix
Fontein.

@item 
bpo-44791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44791}: Fix substitution of @ref{487,,ParamSpec} in
@ref{9c7,,Concatenate} with different parameter expressions.
Substitution with a list of types returns now a tuple of types.
Substitution with @code{Concatenate} returns now a @code{Concatenate} with
concatenated lists of arguments.
@end itemize

@node ドキュメント<32>,テスト<31>,ライブラリ<99>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id439}@anchor{1bf3}
@subsubsection ドキュメント



@itemize -

@item 
bpo-46463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46463}: Fixes @code{escape4chm.py} script used when building the CHM
documentation file
@end itemize

@node テスト<31>,ビルド<38>,ドキュメント<32>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id440}@anchor{1bf4}
@subsubsection テスト



@itemize -

@item 
bpo-43478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43478}: Mocks can no longer be provided as the specs for other Mocks.
As a result, an already-mocked object cannot be passed to @code{mock.Mock()}.
This can uncover bugs in tests since these Mock-derived Mocks will always
pass certain tests (e.g. isinstance) and builtin assert functions (e.g.
assert_called_once_with) will unconditionally pass.

@item 
bpo-46616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46616}: Ensures @code{test_importlib.test_windows} cleans up registry keys
after completion.

@item 
bpo-44359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44359}: test_ftplib now silently ignores socket errors to prevent
logging unhandled threading exceptions. Patch by Victor Stinner.

@item 
bpo-46600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46600}: Fix test_gdb.test_pycfunction() for Python built with @code{clang
-Og}. Tolerate inlined functions in the gdb traceback. Patch by Victor
Stinner.

@item 
bpo-46542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46542}: Fix a Python crash in test_lib2to3 when using Python built in
debug mode: limit the recursion limit. Patch by Victor Stinner.

@item 
bpo-46576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46576}: test_peg_generator now disables compiler optimization when
testing compilation of its own C extensions to significantly speed up the
testing on non-debug builds of CPython.

@item 
bpo-46542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46542}: Fix @code{test_json} tests checking for @ref{f68,,RecursionError}:
modify these tests to use @code{support.infinite_recursion()}. Patch by
Victor Stinner.

@item 
bpo-13886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13886}: Skip test_builtin PTY tests on non-ASCII characters if the
readline module is loaded. The readline module changes input() behavior,
but test_builtin is not intended to test the readline module. Patch by
Victor Stinner.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Add @code{test.support.requires_fork()} decorators to mark tests
that require a working @ref{4b5,,os.fork()}.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Add @code{test.support.requires_subprocess()} decorator to mark
tests which require working @ref{dc,,subprocess} module or @code{os.spawn*}. The
wasm32-emscripten platform has no support for processes.

@item 
bpo-46126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46126}: Disable 'descriptions' when running tests internally.
@end itemize

@node ビルド<38>,Windows<33>,テスト<31>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id441}@anchor{1bf5}
@subsubsection ビルド



@itemize -

@item 
bpo-46602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46602}: Tidied up configure.ac so that conftest.c is truncated rather
than appended. This assists in the case where the 'rm' of conftest.c fails
to happen between tests.  Downstream issues such as a clobbered SOABI can
result.

@item 
bpo-46600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46600}: Fix the test checking if the C compiler supports @code{-Og} option
in the @code{./configure} script to also use @code{-Og} on clang which supports
it. Patch by Victor Stinner.

@item 
bpo-38472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38472}: Fix GCC detection in setup.py when cross-compiling. The C
compiler is now run with LC_ALL=C. Previously, the detection failed with a
German locale.

@item 
bpo-46513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46513}: @code{configure} no longer uses @code{AC_C_CHAR_UNSIGNED}
macro and @code{pyconfig.h} no longer defines reserved symbol
@code{__CHAR_UNSIGNED__}.

@item 
bpo-46471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46471}: Use global singletons for single byte bytes objects in
deepfreeze.

@item 
bpo-46443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46443}: Deepfreeze now uses cached small integers as it saves some
space for common small integers.

@item 
bpo-46429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46429}: Merge all deep-frozen files into one for space savings. Patch
by Kumar Aditya.

@item 
bpo-45569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45569}: The build now defaults to using 30-bit digits for Python
integers. Previously either 15-bit or 30-bit digits would be selected,
depending on the platform. 15-bit digits may still be selected using the
@code{--enable-big-digits=15} option to the @code{configure} script, or by
defining @code{PYLONG_BITS_IN_DIGIT} in @code{pyconfig.h}.

@item 
bpo-45925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45925}: Update Windows installer to use SQLite 3.37.2.

@item 
bpo-43112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43112}: Detect musl libc as a separate SOABI (tagged as
@code{linux-musl}).
@end itemize

@node Windows<33>,macOS<23>,ビルド<38>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id442}@anchor{1bf6}
@subsubsection Windows



@itemize -

@item 
bpo-33125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33125}: The traditional EXE/MSI based installer for Windows is now
available for ARM64

@item 
bpo-46362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46362}: os.path.abspath("C:CON") is now fixed to return "\.CON", not
the same path. The regression was true of all legacy DOS devices such as
COM1, LPT1, or NUL.

@item 
bpo-44934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44934}: The installer now offers a command-line only option to add the
installation directory to the end of 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} instead of at the
start.
@end itemize

@node macOS<23>,IDLE<17>,Windows<33>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id443}@anchor{1bf7}
@subsubsection macOS



@itemize -

@item 
bpo-45925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45925}: Update macOS installer to SQLite 3.37.2.
@end itemize

@node IDLE<17>,C API<33>,macOS<23>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id444}@anchor{1bf8}
@subsubsection IDLE



@itemize -

@item 
bpo-45296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45296}: Clarify close, quit, and exit in IDLE.  In the File menu,
'Close' and 'Exit' are now 'Close Window' (the current one) and 'Exit' is
now 'Exit IDLE' (by closing all windows).  In Shell, 'quit()' and 'exit()'
mean 'close Shell'. If there are no other windows, this also exits IDLE.
@end itemize

@node C API<33>,,IDLE<17>,Python 3 11 0 alpha 5
@anchor{whatsnew/changelog id445}@anchor{1bf9}
@subsubsection C API



@itemize -

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Remove the @code{PyHeapType_GET_MEMBERS()} macro. It was exposed
in the public C API by mistake, it must only be used by Python internally.
Use the @code{PyTypeObject.tp_members} member instead. Patch by Victor
Stinner.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Move _Py_GetAllocatedBlocks() and _PyObject_DebugMallocStats()
private functions to the internal C API. Patch by Victor Stinner.

@item 
bpo-46433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46433}: The internal function _PyType_GetModuleByDef now correctly
handles inheritance patterns involving static types.

@item 
bpo-45459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45459}: @ref{95c,,Py_buffer} and various @code{Py_buffer} related functions
are now part of the limited API and stable ABI.

@item 
bpo-14916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14916}: Fixed bug in the tokenizer that prevented
@code{PyRun_InteractiveOne} from parsing from the provided FD.
@end itemize

@node Python 3 11 0 alpha 4,Python 3 11 0 alpha 3,Python 3 11 0 alpha 5,変更履歴
@anchor{whatsnew/changelog python-3-11-0-alpha-4}@anchor{1bfa}
@subsection Python 3.11.0 alpha 4


`リリース日: 2022-01-13'

@menu
* Core and Builtins: Core and Builtins<97>. 
* ライブラリ: ライブラリ<100>. 
* Core and Builtins: Core and Builtins<98>. 
* ライブラリ: ライブラリ<101>. 
* Core and Builtins: Core and Builtins<99>. 
* ライブラリ: ライブラリ<102>. 
* Core and Builtins: Core and Builtins<100>. 
* ライブラリ: ライブラリ<103>. 
* ドキュメント: ドキュメント<33>. 
* テスト: テスト<32>. 
* ビルド: ビルド<39>. 
* Windows: Windows<34>. 
* macOS: macOS<24>. 
* C API: C API<34>. 

@end menu

@node Core and Builtins<97>,ライブラリ<100>,,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id446}@anchor{1bfb}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46070}: @ref{1845,,Py_EndInterpreter()} now explicitly untracks all objects
currently tracked by the GC. Previously, if an object was used later by
another interpreter, calling @ref{171e,,PyObject_GC_UnTrack()} on the object
crashed if the previous or the next object of the @code{PyGC_Head}
structure became a dangling pointer. Patch by Victor Stinner.

@item 
bpo-46347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46347}: Fix memory leak in PyEval_EvalCodeEx.

@item 
bpo-46339@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46339}: Fix a crash in the parser when retrieving the error text for
multi-line f-strings expressions that do not start in the first line of
the string. Patch by Pablo Galindo

@item 
bpo-46331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46331}: Do not set line number of instruction storing doc-string. Fixes
regression introduced in 3.11 alpha.

@item 
bpo-46314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46314}: Remove spurious "call" event when creating a lambda function
that was accidentally introduced in 3.11a4.

@item 
bpo-46289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46289}: ASDL declaration of @code{FormattedValue} has changed to reflect
@code{conversion} field is not optional.

@item 
bpo-46297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46297}: Fixed an interpreter crash on bootup with multiple PythonPaths
set in the Windows registry. Patch by Derzsi Dániel.

@item 
bpo-46237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46237}: Fix the line number of tokenizer errors inside f-strings. Patch
by Pablo Galindo.

@item 
bpo-46263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46263}: We always expect the "use_frozen_modules" config to be set, now
that getpath.c was rewritten in pure Python and the logic improved.

@item 
bpo-46006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46006}: Fix a regression when a type method like @code{__init__()} is
modified in a subinterpreter. Fix a regression in
@code{_PyUnicode_EqualToASCIIId()} and type @code{update_slot()}. Revert the
change which made the Unicode dictionary of interned strings compatible
with subinterpreters: the internal interned dictionary is shared again by
all interpreters. Patch by Victor Stinner.

@item 
bpo-45923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45923}: Add RESUME opcode. This is a logical no-op. It is emitted by
the compiler anywhere a Python function can be entered. It is used by the
interpreter to perform tracing and optimizer checks.
@end itemize

@node ライブラリ<100>,Core and Builtins<98>,Core and Builtins<97>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id447}@anchor{1bfc}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46208}: Fix the regression of os.path.normpath("A/../../B") not
returning expected "../B" but "B".
@end itemize

@node Core and Builtins<98>,ライブラリ<101>,ライブラリ<100>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id448}@anchor{1bfd}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46240}: Correct the error message for unclosed parentheses when the
tokenizer doesn't reach the end of the source when the error is reported.
Patch by Pablo Galindo

@item 
bpo-46009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46009}: Remove the @code{GEN_START} opcode.

@item 
bpo-46235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46235}: Certain sequence multiplication operations like @code{[0] * 1_000}
are now faster due to reference-counting optimizations. Patch by Dennis
Sweeney.

@item 
bpo-46221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46221}: @code{PREP_RERAISE_STAR} no longer pushes @code{lasti} to the
stack.

@item 
bpo-46202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46202}: Remove @code{POP_EXCEPT_AND_RERAISE} and replace it by an
equivalent sequence of other opcodes.
@end itemize

@node ライブラリ<101>,Core and Builtins<99>,Core and Builtins<98>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id449}@anchor{1bfe}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46085}: Fix iterator cache mechanism of @code{OrderedDict}.
@end itemize

@node Core and Builtins<99>,ライブラリ<102>,ライブラリ<101>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id450}@anchor{1bff}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46055}: Speed up shifting operation involving integers less than
@ref{1c00,,PyLong_BASE}. Patch by Xinhang Xu.

@item 
bpo-46110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46110}: Add a maximum recursion check to the PEG parser to avoid stack
overflow. Patch by Pablo Galindo

@item 
bpo-46107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46107}: Fix bug where @code{ExceptionGroup.split()} and
@code{ExceptionGroup.subgroup()} did not copy the exception group's
@code{__note__} field to the parts.

@item 
bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}: The interpreter state's representation of handled exceptions
(a.k.a exc_info, or _PyErr_StackItem) now has only the @code{exc_value}
field, @code{exc_type} and @code{exc_traceback} have been removed as their
values can be derived from @code{exc_value}.

@item 
bpo-44525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44525}: Replace the four call bytecode instructions which one pre-call
instruction and two call instructions.

Removes @code{CALL_FUNCTION}, @code{CALL_FUNCTION_KW}, @code{CALL_METHOD} and
@code{CALL_METHOD_KW}.

Adds @code{CALL_NO_KW} and @code{CALL_KW} call instructions, and
@code{PRECALL_METHOD} prefix for pairing with @code{LOAD_METHOD}.

@item 
bpo-46039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46039}: Remove the @code{YIELD_FROM} instruction and replace it with the
@code{SEND} instruction which performs the same operation, but without the
loop.

@item 
bpo-45635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45635}: The code called from @code{_PyErr_Display()} was refactored
to improve error handling. It now exits immediately upon an unrecoverable
error.

@item 
bpo-46054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46054}: Fix parser error when parsing non-utf8 characters in source
files. Patch by Pablo Galindo.

@item 
bpo-46042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46042}: Improve the location of the caret in @ref{18e,,SyntaxError}
exceptions emitted by the symbol table. Patch by Pablo Galindo.

@item 
bpo-46049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46049}: Ensure @code{._pth} files work as intended on platforms other
than Windows.

@item 
bpo-46048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46048}: Fixes parsing of @code{._pth} files on startup so that
single-character paths are correctly read.

@item 
bpo-37971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37971}: Fix a bug where the line numbers given in a traceback when a
decorator application raised an exception were wrong.

@item 
bpo-46031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46031}: Add @ref{1b80,,POP_JUMP_IF_NOT_NONE} and
@ref{1b7f,,POP_JUMP_IF_NONE} opcodes to speed up conditional jumps.

@item 
bpo-45654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45654}: Deepfreeze @ref{c3,,runpy}, patch by Kumar Aditya.

@item 
bpo-46025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46025}: Fix a crash in the @ref{d,,atexit} module involving functions
that unregister themselves before raising exceptions. Patch by Pablo
Galindo.
@end itemize

@node ライブラリ<102>,Core and Builtins<100>,Core and Builtins<99>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id451}@anchor{1c01}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46000}: Improve compatibility of the @ref{2f,,curses} module with NetBSD
curses.
@end itemize

@node Core and Builtins<100>,ライブラリ<103>,ライブラリ<102>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id452}@anchor{1c02}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44525}: Specialize the CALL_FUNCTION instruction for calls to builtin
types with a single argument. Speeds up @code{range(x)}, @code{list(x)}, and
specifically @code{type(obj)}.

@item 
bpo-42918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42918}: Fix bug where the built-in @ref{4b1,,compile()} function did not
always raise a @ref{18e,,SyntaxError} when passed multiple statements in
'single' mode. Patch by Weipeng Hong.

@item 
bpo-45953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45953}: The main interpreter in _PyRuntimeState.interpreters is now
statically allocated (as part of _PyRuntime).  Likewise for the initial
thread state of each interpreter.  This means less allocation during
runtime init, as well as better memory locality for these key state
objects.

@item 
bpo-45292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45292}: Complete the 
@geindex Python Enhancement Proposals; PEP 654
PEP 654@footnote{https://peps.python.org/pep-0654/} implementation: add @code{except*}.

@item 
bpo-43413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43413}: Revert changes in @code{set.__init__}. Subclass of @ref{184,,set}
needs to define a @code{__init__()} method if it defines a @code{__new__()}
method with additional keyword parameters.

@item 
bpo-43931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43931}: Added the @ref{381,,Py_Version} constant which bears the same
value as @ref{382,,PY_VERSION_HEX}. Patch by Gabriele N. Tornetta.
@end itemize

@node ライブラリ<103>,ドキュメント<33>,Core and Builtins<100>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id453}@anchor{1c03}
@subsubsection ライブラリ



@itemize -

@item 
bpo-46342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46342}: The @code{@@typing.final} decorator now sets the @code{__final__}
attribute on the decorated object to allow runtime introspection. Patch by
Jelle Zijlstra.

@item 
bpo-46328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46328}: Added the @ref{89b,,sys.exception()} method which returns the active
exception instance.

@item 
bpo-46307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46307}: Add @ref{896,,string.Template.is_valid()} and
@ref{895,,string.Template.get_identifiers()} methods.

@item 
bpo-46306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46306}: Assume that @ref{32f,,types.CodeType} always has
@code{types.CodeType.co_firstlineno} in @ref{3e,,doctest}.

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: Fix @ref{6c,,hashlib} `usedforsecurity' option to work correctly
with OpenSSL 3.0.0 in FIPS mode.

@item 
bpo-46070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46070}: Fix possible segfault when importing the @ref{b,,asyncio} module
from different sub-interpreters in parallel. Patch by Erlend E. Aasland.

@item 
bpo-46244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46244}: Removed @code{__slots__} from @ref{487,,typing.ParamSpec} and
@ref{486,,typing.TypeVar}. They served no purpose. Patch by Arie Bovenberg.

@item 
bpo-46278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46278}: Reflect @code{context} argument in @code{AbstractEventLoop.call_*()}
methods. Loop implementations already support it.

@item 
bpo-46269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46269}: Remove special-casing of @code{__new__} in
@ref{1c04,,enum.Enum.__dir__()}.

@item 
bpo-46266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46266}: Improve day constants in @ref{15,,calendar}.

Now all constants (@code{MONDAY} ... @code{SUNDAY}) are documented, tested, and
added to @code{__all__}.

@item 
bpo-46257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46257}: Optimized the mean, variance, and stdev functions in the
statistics module. If the input is an iterator, it is consumed in a single
pass rather than eating memory by conversion to a list.  The single pass
algorithm is about twice as fast as the previous two pass code.

@item 
bpo-41011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41011}: Added two new variables to `pyvenv.cfg' which is generated by
@ref{117,,venv} module: `executable' for the executable and `command' for the
command line used to create the environment.

@item 
bpo-46239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46239}: Improve error message when importing
@code{asyncio.windows_events} on non-Windows.

@item 
bpo-46238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46238}: Reuse @code{_winapi} constants in @code{asyncio.windows_events}.

@item 
bpo-46222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46222}: Adding @code{SF_NOCACHE} sendfile constant for FreeBSD for the
posixmodule.

@item 
bpo-37295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37295}: Add fast path for @code{0 <= k <= n <= 67} for @ref{8df,,math.comb()}.

@item 
bpo-46176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46176}: Adding the @code{MAP_STACK} constant for the mmap module.

@item 
bpo-43424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43424}: Deprecate @code{webbrowser.MacOSXOSAScript._name} and use
@code{name} instead.

@item 
bpo-45321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45321}: Added missing error codes to module
@code{xml.parsers.expat.errors}.

@item 
bpo-46125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46125}: Refactor tests to test traversable API directly. Includes
changes from importlib 5.4.0.

@item 
bpo-46118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46118}: Moved importlib.resources and its related functionality to a
package.

@item 
bpo-37578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37578}: Add `include_hidden' parameter to @ref{5a0,,glob()} and
@ref{a08,,iglob()} to match hidden files and directories when using
special characters like @code{*}, @code{**}, @code{?} and @code{[]}.

@item 
bpo-20369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20369}: @ref{1c05,,concurrent.futures.wait()} no longer blocks forever when
given duplicate Futures. Patch by Kumar Aditya.

@item 
bpo-46105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46105}: Honor spec when generating requirement specs with urls and
extras (importlib_metadata 4.8.3).

@item 
bpo-44893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44893}: EntryPoint objects are no longer tuples. Recommended means to
access is by attribute ('.name', '.group') or accessor ('.load()'). Access
by index is deprecated and will raise deprecation warning.

@item 
bpo-22815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22815}: Print unexpected successes together with failures and errors in
summary in @ref{754,,unittest.TextTestResult}.

@item 
bpo-22047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22047}: Calling @code{add_argument_group()} on an argument group is
deprecated. Calling @code{add_argument_group()} or
@code{add_mutually_exclusive_group()} on a mutually exclusive group is
deprecated.

These features were never supported and do not always work correctly. The
functions exist on the API by accident through inheritance and will be
removed in the future.

@item 
bpo-26952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26952}: @ref{7,,argparse} raises @ref{2ec,,ValueError} with clear message
when trying to render usage for an empty mutually exclusive group.
Previously it raised a cryptic @ref{174e,,IndexError}.

@item 
bpo-45615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45615}: Functions in the @ref{104,,traceback} module raise @ref{198,,TypeError}
rather than @ref{5f0,,AttributeError} when an exception argument is not of
type @ref{7d6,,BaseException}.

@item 
bpo-16594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16594}: Add allow allow_reuse_port flag in socketserver.

@item 
bpo-27718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27718}: Fix help for the @ref{cb,,signal} module. Some functions (e.g.
@code{signal()} and @code{getsignal()}) were omitted.

@item 
bpo-46032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46032}: The @code{registry()} method of @ref{84b,,functools.singledispatch()}
functions checks now the first argument or the first parameter annotation
and raises a TypeError if it is not supported. Previously unsupported
"types" were ignored (e.g. @code{typing.List[int]}) or caused an error at
calling time (e.g. @code{list[int]}).

@item 
bpo-46014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46014}: Add ability to use @code{typing.Union} and @code{types.UnionType} as
dispatch argument to @code{functools.singledispatch}. Patch provided by Yurii
Karabas.

@item 
bpo-27062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27062}: Add @code{__all__} to @ref{82,,inspect}, patch by Kumar Aditya.

@item 
bpo-46018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46018}: Ensure that @ref{1405,,math.expm1()} does not raise on underflow.

@item 
bpo-46016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46016}: Adding @code{F_DUP2FD} and @code{F_DUP2FD_CLOEXEC}
constants from FreeBSD into the @ref{5d,,fcntl} module.

@item 
bpo-45755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45755}: @ref{10a,,typing} generic aliases now reveal the class attributes
of the original generic class when passed to @code{dir()}. This was the
behavior up to Python 3.6, but was changed in 3.7-3.9.

@item 
bpo-45874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45874}: The empty query string, consisting of no query arguments, is
now handled correctly in @code{urllib.parse.parse_qsl}. This caused problems
before when strict parsing was enabled.

@item 
bpo-44674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44674}: Change how dataclasses disallows mutable default values.  It
used to use a list of known types (list, dict, set).  Now it disallows
unhashable objects to be defaults.  It's using unhashability as a proxy
for mutability.  Patch by Eric V. Smith, idea by Raymond Hettinger.

@item 
bpo-23882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23882}: Remove namespace package (PEP 420) support from unittest
discovery. It was introduced in Python 3.4 but has been broken since
Python 3.7.

@item 
bpo-25066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25066}: Added a @code{__repr__()} method to
@ref{1c06,,multiprocessing.Event} objects, patch by Kumar Aditya.

@item 
bpo-45643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45643}: Added @ref{1c07,,signal.SIGSTKFLT} on platforms where this signal
is defined.

@item 
bpo-44092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44092}: Fetch across rollback no longer raises
@ref{88d,,InterfaceError}. Instead we leave it to the SQLite library
to handle these cases. Patch by Erlend E. Aasland.

@item 
bpo-42413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42413}: Replace @code{concurrent.futures.TimeoutError} and
@code{asyncio.TimeoutError} with builtin @ref{a36,,TimeoutError}, keep these
names as deprecated aliases.
@end itemize

@node ドキュメント<33>,テスト<32>,ライブラリ<103>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id454}@anchor{1c08}
@subsubsection ドキュメント



@itemize -

@item 
bpo-46196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46196}: Document method @ref{1c09,,cmd.Cmd.columnize()}.

@item 
bpo-46120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46120}: State that @code{|} is preferred for readability over @code{Union} in
the @ref{10a,,typing} docs.

@item 
bpo-46109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46109}: Extracted @code{importlib.resources} and
@code{importlib.resources.abc} documentation into separate files.

@item 
bpo-19737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19737}: Update the documentation for the @ref{1c0a,,globals()} function.
@end itemize

@node テスト<32>,ビルド<39>,ドキュメント<33>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id455}@anchor{1c0b}
@subsubsection テスト



@itemize -

@item 
bpo-46296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46296}: Add a test case for @ref{5a,,enum} with @code{_use_args_ == True} and
@code{_member_type_ == object}.

@item 
bpo-46205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46205}: Fix hang in runtest_mp due to race condition

@item 
bpo-46263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46263}: Fix test_capi on FreeBSD 14-dev: instruct jemalloc to not fill
freed memory with junk byte.

@item 
bpo-46262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46262}: Cover @code{ValueError} path in tests for
@code{enum.Flag._missing_()}.

@item 
bpo-46150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46150}: Now @code{fakename} in
@code{test_pathlib.PosixPathTest.test_expanduser} is checked to be
non-existent.

@item 
bpo-46129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46129}: Rewrite @code{asyncio.locks} tests with
@ref{361,,unittest.IsolatedAsyncioTestCase} usage.

@item 
bpo-23819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23819}: Fixed @ref{b,,asyncio} tests in python optimized mode. Patch by
Kumar Aditya.

@item 
bpo-46114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46114}: Fix test case for OpenSSL 3.0.1 version. OpenSSL 3.0 uses
@code{0xMNN00PP0L}.
@end itemize

@node ビルド<39>,Windows<34>,テスト<32>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id456}@anchor{1c0c}
@subsubsection ビルド



@itemize -

@item 
bpo-44133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44133}: When Python is configured with
@ref{a8e,,--without-static-libpython}, the Python static library
(libpython.a) is no longer built. Patch by Victor Stinner.

@item 
bpo-44133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44133}: When Python is built without @ref{a63,,--enable-shared}, the
@code{python} program is now linked to object files, rather than being linked
to the Python static library (libpython.a), to make sure that all symbols
are exported. Previously, the linker omitted some symbols like the
@code{Py_FrozenMain()} function. Patch by Victor Stinner.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: The @code{configure} script has a new option
@code{--with-emscripten-target} to select browser or node as Emscripten build
target.

@item 
bpo-46315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46315}: Added and fixed @code{#ifdef HAVE_FEATURE} checks for
functionality that is not available on WASI platform.

@item 
bpo-45723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45723}: Fixed a regression in @code{configure} check for
@ref{1196,,select.epoll()}.

@item 
bpo-46263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46263}: @code{configure} no longer sets @code{MULTIARCH} on FreeBSD
platforms.

@item 
bpo-46106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46106}: Updated OpenSSL to 1.1.1m in Windows builds, macOS installer
builds, and CI. Patch by Kumar Aditya.

@item 
bpo-46088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46088}: Automatically detect or install bootstrap Python runtime when
building from Visual Studio.

@item 
bpo-46072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46072}: Add a --with-pystats configure option to turn on internal
statistics gathering.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: A new directory @code{Tools/wasm} contains WebAssembly-related
helpers like @code{config.site} override for wasm32-emscripten, wasm assets
generator to bundle the stdlib, and a README.

@item 
bpo-46023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46023}: @code{makesetup} no longer builds extensions that have been
marked as `disabled'. This allows users to disable modules in
@code{Modules/Setup.local}.

@item 
bpo-45949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45949}: Use pure Python @code{freeze_module} for all but importlib
bootstrap files. @code{--with-freeze-module} @code{configure} option is
no longer needed for cross builds.
@end itemize

@node Windows<34>,macOS<24>,ビルド<39>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id457}@anchor{1c0d}
@subsubsection Windows



@itemize -

@item 
bpo-46217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46217}: Removed parameter that is unsupported on Windows 8.1 and early
Windows 10 and may have caused build or runtime failures.
@end itemize

@node macOS<24>,C API<34>,Windows<34>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id458}@anchor{1c0e}
@subsubsection macOS



@itemize -

@item 
bpo-40477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40477}: The Python Launcher app for macOS now properly launches scripts
and, if necessary, the Terminal app when running on recent macOS releases.
@end itemize

@node C API<34>,,macOS<24>,Python 3 11 0 alpha 4
@anchor{whatsnew/changelog id459}@anchor{1c0f}
@subsubsection C API



@itemize -

@item 
bpo-46236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46236}: Fix a bug in @ref{1b37,,PyFunction_GetAnnotations()} that caused it
to return a @code{tuple} instead of a @code{dict}.

@item 
bpo-46140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46140}: @ref{95d,,PyBuffer_GetPointer()},
@ref{960,,PyBuffer_FromContiguous()}, @ref{95f,,PyBuffer_ToContiguous()} and
@ref{965,,PyMemoryView_FromBuffer()} now take buffer info by @code{const
Py_buffer *} instead of @code{Py_buffer *}, as they do not need mutability.
@ref{960,,PyBuffer_FromContiguous()} also now takes the source buffer as
@code{const void *}, and similarly @ref{95d,,PyBuffer_GetPointer()} takes the
strides as @code{const Py_ssize_t *}.

@item 
bpo-45855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45855}: Document that the `no_block' argument to
@ref{1c10,,PyCapsule_Import()} is a no-op now.

@item 
bpo-45855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45855}: Replaced deprecated usage of
@ref{3db,,PyImport_ImportModuleNoBlock()} with
@ref{3dc,,PyImport_ImportModule()} in stdlib modules. Patch by Kumar Aditya.

@item 
bpo-46007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46007}: The @code{PyUnicode_CHECK_INTERNED()} macro has been excluded
from the limited C API. It was never usable there, because it used
internal structures which are not available in the limited C API. Patch by
Victor Stinner.
@end itemize

@node Python 3 11 0 alpha 3,Python 3 11 0 alpha 2,Python 3 11 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-11-0-alpha-3}@anchor{1c11}
@subsection Python 3.11.0 alpha 3


`Release date: 2021-12-08'

@menu
* Core and Builtins: Core and Builtins<101>. 
* ライブラリ: ライブラリ<104>. 
* Core and Builtins: Core and Builtins<102>. 
* ライブラリ: ライブラリ<105>. 
* ドキュメント: ドキュメント<34>. 
* テスト: テスト<33>. 
* ビルド: ビルド<40>. 
* Windows: Windows<35>. 
* macOS: macOS<25>. 
* C API: C API<35>. 

@end menu

@node Core and Builtins<101>,ライブラリ<104>,,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id460}@anchor{1c12}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46009}: Restore behavior from 3.9 and earlier when sending non-None to
newly started generator. In 3.9 this did not affect the state of the
generator. In 3.10.0 and 3.10.1 @code{gen_func().send(0)} is equivalent to
@code{gen_func().throw(TypeError(...)} which exhausts the generator. In
3.10.2 onward, the behavior has been reverted to that of 3.9.

@item 
bpo-46004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46004}: Fix the @ref{18e,,SyntaxError} location for errors involving for
loops with invalid targets. Patch by Pablo Galindo

@item 
bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}: @code{_PyErr_ChainStackItem()} no longer normalizes
@code{exc_info} (including setting the traceback on the exception instance)
because @code{exc_info} is always normalized.

@item 
bpo-45607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45607}: The @code{__note__} field was added to @ref{7d6,,BaseException}. It is
@code{None} by default but can be set to a string which is added to the
exception's traceback.

@item 
bpo-45947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45947}: Place pointers to dict and values immediately before GC header.
This reduces number of dependent memory loads to access either dict or
values from 3 to 1.

@item 
bpo-45915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45915}: @code{is_valid_fd} now uses faster @code{fcntl(fd, F_GETFD)} on
Linux, macOS, and Windows.

@item 
bpo-44530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44530}: Reverts a change to the @code{code.__new__} @ref{1c13,,audit event} from an earlier prerelease.

@item 
bpo-42268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42268}: Fail the configure step if the selected compiler doesn't
support memory sanitizer. Patch by Pablo Galindo

@item 
bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}: The three values of @code{exc_info} are now always consistent with
each other. In particular, the @code{type} and @code{traceback} fields are now
derived from the exception instance. This impacts the return values of
@ref{89a,,sys.exc_info()} and @ref{976,,PyErr_GetExcInfo()} if the exception
instance is modified while the exception is handled, as well as
@ref{975,,PyErr_SetExcInfo()}, which now ignores the @code{type} and
@code{traceback} arguments provided to it.

@item 
bpo-45727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45727}: Refine the custom syntax error that suggests that a comma may
be missing to trigger only when the expressions are detected between
parentheses or brackets. Patch by Pablo Galindo

@item 
bpo-45885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45885}: Specialized the @code{COMPARE_OP} opcode using the PEP 659
machinery.

@item 
bpo-45786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45786}: Allocate space for the interpreter frame in the frame object,
to avoid an additional allocation when the frame object outlives the frame
activation.
@end itemize

@node ライブラリ<104>,Core and Builtins<102>,Core and Builtins<101>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id461}@anchor{1c14}
@subsubsection ライブラリ



@itemize -

@item 
bpo-45614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45614}: Fix @ref{104,,traceback} display for exceptions with invalid module
name.
@end itemize

@node Core and Builtins<102>,ライブラリ<105>,ライブラリ<104>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id462}@anchor{1c15}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-45813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45813}: Fix crash when calling coro.cr_frame.clear() after coroutine
has been freed.

@item 
bpo-45811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45811}: Improve the tokenizer errors when encountering invisible
control characters in the parser. Patch by Pablo Galindo

@item 
bpo-45848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45848}: Allow the parser to obtain error lines directly from encoded
files. Patch by Pablo Galindo

@item 
bpo-45709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45709}: Restore behavior from 3.10 when tracing an exception raised
within a with statement.

@item 
bpo-44525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44525}: Adds new @ref{90d,,COPY_FREE_VARS} opcode, to make copying of
free variables from function to frame explicit. Helps optimization of
calls to Python function.

@item 
bpo-45829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45829}: Specialize @code{BINARY_SUBSCR} for classes with a
@code{__getitem__} method implemented in Python

@item 
bpo-45826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45826}: Fixed a crash when calling @code{.with_traceback(None)} on
@code{NameError}. This occurs internally in
@code{unittest.TestCase.assertRaises()}.

@item 
bpo-45822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45822}: Fixed a bug in the parser that was causing it to not respect
@geindex Python Enhancement Proposals; PEP 263
PEP 263@footnote{https://peps.python.org/pep-0263/} coding cookies when no flags are provided. Patch by Pablo
Galindo

@item 
bpo-45820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45820}: Fix a segfault when the parser fails without reading any input.
Patch by Pablo Galindo

@item 
bpo-45636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45636}: Simplify the implementation of @ref{366,,BINARY_OP} by indexing
into an array of function pointers (rather than switching on the oparg).

@item 
bpo-42540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42540}: Fix crash when @ref{4b5,,os.fork()} is called with an active
non-default memory allocator.

@item 
bpo-45738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45738}: Fix computation of error location for invalid continuation
characters in the parser. Patch by Pablo Galindo.

@item 
bpo-45636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45636}: Remove an existing "fast path" for old-style string formatting,
since it no longer appears to have any measurable impact.

@item 
bpo-45753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45753}: Make recursion checks a bit more efficient by tracking amount
of calls left before overflow.

@item 
bpo-45773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45773}: Fix a compiler hang when attempting to optimize certain jump
patterns.

@item 
bpo-45764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45764}: The parser now gives a better error message when leaving out
the opening parenthesis @code{(} after a @code{def}-statement:

@example
>>> def f:
  File "<stdin>", line 1
    def f:
         ^
SyntaxError: expected '('
@end example

@item 
bpo-45609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45609}: Specialized the @code{STORE_SUBSCR} opcode using the PEP 659
machinery.

@item 
bpo-45636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45636}: Replace all numeric @code{BINARY_*} and @code{INPLACE_*} instructions
with a single @ref{366,,BINARY_OP} implementation.

@item 
bpo-45582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45582}: Path calculation (known as @code{getpath}) has been reimplemented
as a frozen Python module. This should have no visible impact, but may
affect calculation of all paths referenced in @ref{df,,sys} and
@ref{e1,,sysconfig}.

@item 
bpo-45450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45450}: Improve the syntax error message for parenthesized arguments.
Patch by Pablo Galindo.
@end itemize

@node ライブラリ<105>,ドキュメント<34>,Core and Builtins<102>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id463}@anchor{1c16}
@subsubsection ライブラリ



@itemize -

@item 
bpo-27946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27946}: Fix possible crash when getting an attribute of
@ref{363,,xml.etree.ElementTree.Element} simultaneously with replacing the
@code{attrib} dict.

@item 
bpo-45711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45711}: Make @ref{b,,asyncio} normalize exceptions as soon as they are
captured with @ref{428,,PyErr_Fetch()}, and before they are stored as an
exc_info triplet. This brings @ref{b,,asyncio} in line with the rest of the
codebase, where an exc_info triplet is always normalized.

@item 
bpo-23819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23819}: Replaced asserts with exceptions in asyncio, patch by Kumar
Aditya.

@item 
bpo-13236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13236}: @ref{754,,unittest.TextTestResult} and
@ref{1ab6,,unittest.TextTestRunner} flush now the output stream more often.

@item 
bpo-45917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45917}: Added @ref{870,,math.exp2()}:, which returns 2 raised to the power
of x.

@item 
bpo-37658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37658}: Fix issue when on certain conditions @code{asyncio.wait_for()} may
allow a coroutine to complete successfully, but fail to return the result,
potentially causing memory leaks or other issues.

@item 
bpo-45876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45876}: Improve the accuracy of stdev() and pstdev() in the statistics
module.  When the inputs are floats or fractions, the output is a
correctly rounded float

@item 
bpo-44649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44649}: Handle dataclass(slots=True) with a field that has default a
default value, but for which init=False.

@item 
bpo-45803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45803}: Added missing kw_only parameter to
dataclasses.make_dataclass().

@item 
bpo-45837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45837}: The @code{turtle.RawTurtle.settiltangle()} is deprecated since
Python 3.1, it now emits a deprecation warning and will be removed in
Python 3.13.

Use @code{turtle.RawTurtle.tiltangle()} instead.

@code{turtle.RawTurtle.tiltangle()} was earlier incorrectly marked as
deprecated, its docstring has been corrected.

Patch by Hugo van Kemenade.

@item 
bpo-45831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45831}: @ref{5c,,faulthandler} can now write ASCII-only strings (like
filenames and function names) with a single write() syscall when dumping a
traceback. It reduces the risk of getting an unreadable dump when two
threads or two processes dump a traceback to the same file (like stderr)
at the same time. Patch by Victor Stinner.

@item 
bpo-45828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45828}: @code{sqlite} C callbacks now use unraisable exceptions if
callback tracebacks are enabled. Patch by Erlend E. Aasland.

@item 
bpo-41735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41735}: Fix thread lock in @code{zlib.Decompress.flush()} method before
@code{PyObject_GetBuffer}.

@item 
bpo-45235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45235}: Reverted an argparse bugfix that caused regression in the
handling of default arguments for subparsers.  This prevented leaf level
arguments from taking precedence over root level arguments.

@item 
bpo-45754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45754}: Fix a regression in Python 3.11a1 and 3.11a2 where
@ref{d4,,sqlite3} incorrectly would use @code{SQLITE_LIMIT_LENGTH} when checking
SQL statement lengths. Now, @code{SQLITE_LIMIT_SQL_LENGTH} is used. Patch by
Erlend E. Aasland.

@item 
bpo-45766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45766}: Added `proportional' option to
@ref{a32,,statistics.linear_regression()}.

@item 
bpo-45765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45765}: In importlib.metadata, fix distribution discovery for an empty
path.

@item 
bpo-45757@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45757}: Fix bug where @ref{3c,,dis} produced an incorrect oparg when
@ref{1b1e,,EXTENDED_ARG} is followed by an opcode that does not use its
argument.

@item 
bpo-45644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45644}: In-place JSON file formatting using @code{python3 -m json.tool
infile infile} now works correctly, previously it left the file empty.
Patch by Chris Wesseling.

@item 
bpo-45703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45703}: When a namespace package is imported before another module from
the same namespace is created/installed in a different @ref{3e4,,sys.path}
location while the program is running, calling the
@ref{e0a,,importlib.invalidate_caches()} function will now also guarantee the
new module is noticed.

@item 
bpo-45535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45535}: Improve output of @code{dir()} with Enums.

@item 
bpo-45664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45664}: Fix @ref{d95,,types.resolve_bases()} and @ref{1379,,types.new_class()} for
@ref{9ec,,types.GenericAlias} instance as a base.

@item 
bpo-45663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45663}: Fix @ref{1c17,,dataclasses.is_dataclass()} for dataclasses which are
subclasses of @ref{9ec,,types.GenericAlias}.

@item 
bpo-45662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45662}: Fix the repr of @ref{1bb4,,dataclasses.InitVar} with a type alias
to the built-in class, e.g. @code{InitVar[list[int]]}.

@item 
bpo-43137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43137}: Launch GNOME web browsers via gio tool instead of obsolete
gvfs-open

@item 
bpo-45429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45429}: On Windows, @ref{8ac,,time.sleep()} now uses a waitable timer which
supports high-resolution timers. Patch by Donghee Na and Eryk Sun.

@item 
bpo-37295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37295}: Optimize @ref{8df,,math.comb()} and @ref{8e0,,math.perm()}.

@item 
bpo-45514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45514}: Deprecated legacy functions in @ref{7f,,importlib.resources}.

@item 
bpo-45507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45507}: Add tests for truncated/missing trailers in gzip.decompress
implementation.

@item 
bpo-45359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45359}: Implement 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} for @ref{ade,,graphlib.TopologicalSorter}.

@item 
bpo-44733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44733}: Add @code{max_tasks_per_child} to
@ref{1d6,,concurrent.futures.ProcessPoolExecutor}. This allows users to
specify the maximum number of tasks a single process should execute before
the process needs to be restarted.

@item 
bpo-28806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28806}: Improve netrc library. netrc file no longer needs to contain
all tokens. And if the login name is anonymous, security check is no
longer need.

@item 
bpo-43498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43498}: Avoid a possible `"RuntimeError: dictionary changed size during
iteration"' when adjusting the process count of
@code{ProcessPoolExecutor}.

@item 
bpo-42158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42158}: Add MIME types for N-quads, N-triples, Notation3 and TriG to
@code{mimetypes}.

@item 
bpo-30533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30533}: Add @ref{859,,inspect.getmembers_static()} , it return all members
without triggering dynamic lookup via the descriptor protocol. Patch by
Weipeng Hong.
@end itemize

@node ドキュメント<34>,テスト<33>,ライブラリ<105>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id464}@anchor{1c18}
@subsubsection ドキュメント



@itemize -

@item 
bpo-42238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42238}: @code{make -C Doc suspicious} will be removed soon in favor of
@code{make -C Doc check}, mark it as deprecated.

@item 
bpo-45840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45840}: Improve cross-references in the documentation for the data
model.

@item 
bpo-45640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45640}: Properly marked-up grammar tokens in the documentation are now
clickable and take you to the definition of a given piece of grammar.
Patch by Arthur Milchior.

@item 
bpo-45788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45788}: Link doc for sys.prefix to sysconfig doc on installation paths.

@item 
bpo-45772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45772}: @code{socket.socket} documentation is corrected to a class from a
function.

@item 
bpo-45392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45392}: Update the docstring of the @ref{f44,,type} built-in to remove a
redundant line and to mention keyword arguments for the constructor.

@item 
bpo-45250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45250}: Update the documentation to note that CPython does not
consistently require iterators to define @code{__iter__}.

@item 
bpo-25381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25381}: In the extending chapter of the extending doc, update a
paragraph about the global variables containing exception information.

@item 
bpo-43905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43905}: Expanded @ref{1a9e,,astuple()} and
@ref{1a95,,asdict()} docs, warning about deepcopy being applied and
providing a workaround.
@end itemize

@node テスト<33>,ビルド<40>,ドキュメント<34>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id465}@anchor{1c19}
@subsubsection テスト



@itemize -

@item 
bpo-45695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45695}: Out-of-tree builds with a read-only source directory are now
tested by CI.

@item 
bpo-19460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19460}: Add new Test for
@code{Lib/email/mime/nonmultipart.py::MIMENonMultipart}.

@item 
bpo-45835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45835}: Fix race condition in test_queue tests with multiple "feeder"
threads.

@item 
bpo-45783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45783}: The test for the freeze tool now handles file moves and
deletions.

@item 
bpo-45745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45745}: Remove the @code{--findleaks} command line option of regrtest: use
the @code{--fail-env-changed} option instead. Since Python 3.7, it was a
deprecated alias to the @code{--fail-env-changed} option.

@item 
bpo-45701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45701}: Add tests with @code{tuple} type with @ref{be2,,functools.lru_cache()}
to @code{test_functools}.
@end itemize

@node ビルド<40>,Windows<35>,テスト<33>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id466}@anchor{1c1a}
@subsubsection ビルド



@itemize -

@item 
bpo-44035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44035}: CI now verifies that autoconf files have been regenerated with
a current and unpatched autoconf package.

@item 
bpo-45950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45950}: The build system now uses a @code{_bootstrap_python}
interpreter for freezing and deepfreezing again. To speed up build process
the build tools @code{_bootstrap_python} and @code{_freeze_module}
are no longer build with LTO.

@item 
bpo-45881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45881}: The @code{configure} script now accepts
@code{--with-build-python} and @code{--with-freeze-module} options to make cross
compiling easier.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Emscripten platform now uses @code{.wasm} suffix by default.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: Disable unusable core extension modules on WASM/Emscripten
targets.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: @code{configure} now checks for socket @code{shutdown} function. The
check makes it possible to disable @code{SYS_shutdown} with
@code{ac_cv_func_shutdown=no} in CONFIG_SITE.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: @code{configure} now checks for functions @code{fork1, getegid,
geteuid, getgid, getppid, getuid, opendir, pipe, system, wait, ttyname}.

@item 
bpo-33393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33393}: Update @code{config.guess} to 2021-06-03 and @code{config.sub} to
2021-08-14. @code{Makefile} now has an @code{update-config} target to make
updating more convenient.

@item 
bpo-45866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45866}: @code{make regen-all} now produces the same output when run from a
directory other than the source tree: when building Python out of the
source tree. pegen now strips directory of the "generated by pygen from
<FILENAME>" header Patch by Victor Stinner.

@item 
bpo-40280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40280}: @code{configure} now accepts machine @code{wasm32} or @code{wasm64} and
OS @code{wasi} or @code{emscripten} for cross building, e.g.
@code{wasm32-unknown-emscripten}, @code{wasm32-wasi}, or
@code{wasm32-unknown-wasi}.

@item 
bpo-41498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41498}: Python now compiles on platforms without @code{sigset_t}. Several
functions in @ref{cb,,signal} are not available when @code{sigset_t} is missing.

Based on patch by Roman Yurchak for pyodide.

@item 
bpo-45881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45881}: @code{setup.py} now uses @code{CC} from environment first to discover
multiarch and cross compile paths.

@item 
bpo-45886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45886}: The @code{_freeze_module} program path can now be overridden on
the command line, e.g. @code{make
FREEZE_MODULE=../x86_64/Program/_freeze_module}.

@item 
bpo-45873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45873}: Get rid of the @code{_bootstrap_python} build step. The
deepfreeze.py script is now run using @code{$(PYTHON_FOR_REGEN)} which can be
Python 3.7 or newer (on Windows, 3.8 or newer).

@item 
bpo-45847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45847}: Port builtin hashlib extensions to @code{PY_STDLIB_MOD} macro and
@code{addext()}.

@item 
bpo-45723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45723}: Add @code{autoconf} helpers for saving and restoring environment
variables:


@itemize *

@item 
@code{SAVE_ENV}: Save @code{$CFLAGS}, @code{$LDFLAGS}, @code{$LIBS}, and
@code{$CPPFLAGS}.

@item 
@code{RESTORE_ENV}: Restore @code{$CFLAGS}, @code{$LDFLAGS}, @code{$LIBS}, and
@code{$CPPFLAGS}.

@item 
@code{WITH_SAVE_ENV([SCRIPT])}: Run @code{SCRIPT} wrapped with @code{SAVE_ENV} and
@code{RESTORE_ENV}.
@end itemize

Patch by Erlend E. Aasland.

@item 
bpo-45573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45573}: Mandatory core modules, that are required to bootstrap Python,
are now in @code{Modules/Setup.bootstrap}.

@item 
bpo-45573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45573}: @code{configure} now creates @code{Modules/Setup.stdlib} with
conditionally enabled/disabled extension module lines. The file is not
used, yet.

@item 
bpo-45573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45573}: @code{configure} now uses a unified format to set state, compiler
flags, and linker flags in Makefile. The new macro @code{PY_STDLIB_MOD} sets
three variables that are consumed by @code{Modules/Setup} and @code{setup.py}.

@item 
bpo-45816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45816}: Python now supports building with Visual Studio 2022 (MSVC
v143, VS Version 17.0). Patch by Jeremiah Vivian.

@item 
bpo-45800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45800}: Settings for @code{pyexpat} C extension are now detected by
@code{configure}. The bundled @code{expat} library is built in @code{Makefile}.

@item 
bpo-45798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45798}: Settings for @ref{3a,,decimal} internal C extension are now
detected by @code{configure}. The bundled @code{libmpdec} library is built in
@code{Makefile}.

@item 
bpo-45723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45723}: @code{configure} has a new option @code{--with-pkg-config} to
disable or require pkg-config.

@item 
bpo-45774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45774}: The build dependencies for @ref{d4,,sqlite3} are now detected by
@code{configure} and @code{pkg-config}. Patch by Erlend E. Aasland.

@item 
bpo-45763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45763}: The build dependencies for @ref{139,,zlib}, @ref{14,,bz2}, and
@ref{8e,,lzma} are now detected by @code{configure}.

@item 
bpo-45747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45747}: gdbm and dbm build dependencies are now detected by
@code{configure}.

@item 
bpo-45743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45743}: On macOS, the build system no longer passes
@code{search_paths_first} to the linker. The flag has been the default since
Xcode 4 / macOS 10.6.

@item 
bpo-45723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45723}: @code{configure.ac} is now compatible with autoconf 2.71.
Deprecated checks @code{STDC_HEADERS} and @code{AC_HEADER_TIME} have been
removed.

@item 
bpo-45723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45723}: @code{configure} now prints a warning when pkg-config is missing.

@item 
bpo-45731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45731}: @code{configure --enable-loadable-sqlite-extensions} is now
handled by new @code{PY_SQLITE_ENABLE_LOAD_EXTENSION} macro instead of logic
in setup.py.

@item 
bpo-45723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45723}: configure.ac now uses custom helper macros and
@code{AC_CACHE_CHECK} to simplify and speed up configure runs.

@item 
bpo-45696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45696}: Skip the marshal step for frozen modules by generating C code
that produces a set of ready-to-use code objects. This speeds up startup
time by another 10% or more.

@item 
bpo-45561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45561}: Run smelly.py tool from $(srcdir).
@end itemize

@node Windows<35>,macOS<25>,ビルド<40>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id467}@anchor{1c1b}
@subsubsection Windows



@itemize -

@item 
bpo-46105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46105}: Fixed calculation of @ref{3e4,,sys.path} in a venv on Windows.

@item 
bpo-45901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45901}: When installed through the Microsoft Store and set as the
default app for @code{*.py} files, command line arguments will now be
passed to Python when invoking a script without explicitly launching
Python (that is, @code{script.py args} rather than @code{python script.py
args}).

@item 
bpo-45616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45616}: Fix Python Launcher's ability to distinguish between versions
3.1 and 3.10 when either one is explicitly requested.  Previously, 3.1
would be used if 3.10 was requested but not installed, and 3.10 would be
used if 3.1 was requested but 3.10 was installed.

@item 
bpo-45850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45850}: Implement changes to build with deep-frozen modules on Windows.
Note that we now require Python 3.10 as the "bootstrap" or "host" Python.

@item 
bpo-45732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45732}: Updates bundled Tcl/Tk to 8.6.12.

@item 
bpo-45720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45720}: Internal reference to @code{shlwapi.dll} was dropped to help
improve startup time. This DLL will no longer be loaded at the start of
every Python process.
@end itemize

@node macOS<25>,C API<35>,Windows<35>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id468}@anchor{1c1c}
@subsubsection macOS



@itemize -

@item 
bpo-45732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45732}: Update python.org macOS installer to use Tcl/Tk 8.6.12.
@end itemize

@node C API<35>,,macOS<25>,Python 3 11 0 alpha 3
@anchor{whatsnew/changelog id469}@anchor{1c1d}
@subsubsection C API



@itemize -

@item 
bpo-39026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39026}: Fix Python.h to build C extensions with Xcode: remove a
relative include from @code{Include/cpython/pystate.h}.
@end itemize

@node Python 3 11 0 alpha 2,Python 3 11 0 alpha 1,Python 3 11 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-11-0-alpha-2}@anchor{1c1e}
@subsection Python 3.11.0 alpha 2


`リリース日: 2021-11-05'

@menu
* Core and Builtins: Core and Builtins<103>. 
* ライブラリ: ライブラリ<106>. 
* ドキュメント: ドキュメント<35>. 
* テスト: テスト<34>. 
* ビルド: ビルド<41>. 
* Windows: Windows<36>. 
* macOS: macOS<26>. 
* IDLE: IDLE<18>. 
* C API: C API<36>. 

@end menu

@node Core and Builtins<103>,ライブラリ<106>,,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id470}@anchor{1c1f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-45716@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45716}: Improve the @ref{18e,,SyntaxError} message when using @code{True},
@code{None} or @code{False} as keywords in a function call. Patch by Pablo
Galindo.

@item 
bpo-45688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45688}: @ref{a42,,sys.stdlib_module_names} now contains the macOS-specific
module @code{_scproxy}.

@item 
bpo-45379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45379}: Clarify @ref{65b,,ImportError} message when we try to explicitly
import a frozen module but frozen modules are disabled.

@item 
bpo-44525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44525}: Specialize simple calls to Python functions (no starargs,
keyword dict, or closure)

@item 
bpo-45530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45530}: Cases of sorting using tuples as keys may now be significantly
faster in some cases. Patch by Tim Peters.

The order of the result may differ from earlier releases if the tuple
elements don't define a total ordering (see
@ref{1c20,,値の比較} for information on total ordering).
It's generally true that the result of sorting simply isn't well-defined
in the absence of a total ordering on list elements.

@item 
bpo-45526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45526}: In obmalloc, set ADDRESS_BITS to not ignore any bits (ignored
16 before). That is safer in the case that the kernel gives user-space
virtual addresses that span a range greater than 48 bits.

@item 
bpo-30570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30570}: Fixed a crash in @code{issubclass()} from infinite recursion when
searching pathological @code{__bases__} tuples.

@item 
bpo-45521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45521}: Fix a bug in the obmalloc radix tree code.  On 64-bit machines,
the bug causes the tree to hold 46-bits of virtual addresses, rather than
the intended 48-bits.

@item 
bpo-45494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45494}: Fix parser crash when reporting errors involving invalid
continuation characters. Patch by Pablo Galindo.

@item 
bpo-45445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45445}: Python now fails to initialize if it finds an invalid
@ref{16f,,-X} option in the command line. Patch by Pablo Galindo.

@item 
bpo-45340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45340}: Object attributes are held in an array instead of a dictionary.
An object's dictionary are created lazily, only when needed. Reduces the
memory consumption of a typical Python object by about 30%. Patch by Mark
Shannon.

@item 
bpo-45408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45408}: Fix a crash in the parser when reporting tokenizer errors that
occur at the same time unclosed parentheses are detected. Patch by Pablo
Galindo.

@item 
bpo-29410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29410}: Add SipHash13 for string hash algorithm and use it by default.

@item 
bpo-45385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45385}: Fix reference leak from descr_check. Patch by Donghee Na.

@item 
bpo-45367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45367}: Specialized the @code{BINARY_MULTIPLY} opcode to
@code{BINARY_MULTIPLY_INT} and @code{BINARY_MULTIPLY_FLOAT} using the PEP 659
machinery.

@item 
bpo-21736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21736}: Frozen stdlib modules now have @code{__file__} to the .py file
they would otherwise be loaded from, if possible.  For packages,
@code{__path__} now has the correct entry instead of being an empty list,
which allows unfrozen submodules to be imported.  These are set only if
the stdlib directory is known when the runtime is initialized.  Note that
the file at @code{__file__} is not guaranteed to exist.  None of this affects
non-stdlib frozen modules nor, for now, frozen modules imported using
@code{PyImport_ImportFrozenModule()}.  Also, at the moment @code{co_filename} is
not updated for the module.

@item 
bpo-45020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45020}: For frozen stdlib modules, record the original module name as
@code{module.__spec__.loader_state.origname}.  If the value is different than
@code{module.__spec__.name} then the module was defined as an alias in
Tools/scripts/freeze_modules.py.  If it is @code{None} then the module comes
from a source file outside the stdlib.

@item 
bpo-45324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45324}: In FrozenImporter.find_spec(), we now preserve the information
needed in exec_module() to load the module.  This change mostly impacts
internal details, rather than changing the importer's behavior.

@item 
bpo-45292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45292}: Implement 
@geindex Python Enhancement Proposals; PEP 654
PEP 654@footnote{https://peps.python.org/pep-0654/}. Add @ref{4d2,,ExceptionGroup} and
@ref{566,,BaseExceptionGroup}. Update traceback display code.

@item 
bpo-40116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40116}: Change to the implementation of split dictionaries. Classes
where the instances differ either in the exact set of attributes, or in
the order in which those attributes are set, can still share keys. This
should have no observable effect on users of Python or the C-API. Patch by
Mark Shannon.

@item 
bpo-44050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44050}: Extensions that indicate they use global state (by setting
@code{m_size} to -1) can again be used in multiple interpreters. This reverts
to behavior of Python 3.8.

@item 
bpo-44525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44525}: Setup initial specialization infrastructure for the
@code{CALL_FUNCTION} opcode. Implemented initial specializations for C
function calls:


@itemize *

@item 
@code{CALL_FUNCTION_BUILTIN_O} for @code{METH_O} flag.

@item 
@code{CALL_FUNCTION_BUILTIN_FAST} for @code{METH_FASTCALL} flag without keywords.

@item 
@code{CALL_FUNCTION_LEN} for @code{len(o)}.

@item 
@code{CALL_FUNCTION_ISINSTANCE} for @code{isinstance(o, t)}.
@end itemize

@item 
bpo-44511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44511}: Improve the generated bytecode for class and mapping patterns.

@item 
bpo-43706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43706}: Speed up calls to @code{enumerate()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.
@end itemize

@node ライブラリ<106>,ドキュメント<35>,Core and Builtins<103>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id471}@anchor{1c21}
@subsubsection ライブラリ



@itemize -

@item 
bpo-45679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45679}: Fix caching of multi-value @ref{a55,,typing.Literal}.
@code{Literal[True, 2]} is no longer equal to @code{Literal[1, 2]}.

@item 
bpo-42064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42064}: Convert @ref{d4,,sqlite3} to multi-phase initialisation (PEP 489).
Patches by Erlend E. Aasland.

@item 
bpo-45438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45438}: Fix typing.Signature string representation for generic builtin
types.

@item 
bpo-45613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45613}: @ref{d4,,sqlite3} now sets @ref{88c,,sqlite3.threadsafety} based on
the default threading mode the underlying SQLite library has been compiled
with. Patch by Erlend E. Aasland.

@item 
bpo-45574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45574}: Fix warning about @code{print_escape} being unused.

@item 
bpo-45581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45581}: @ref{5a6,,sqlite3.connect()} now correctly raises @ref{179e,,MemoryError}
if the underlying SQLite API signals memory error. Patch by Erlend E.
Aasland.

@item 
bpo-45557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45557}: @ref{a29,,pprint.pprint()} now handles `underscore_numbers'
correctly. Previously it was always setting it to @code{False}.

@item 
bpo-44019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44019}: Add @ref{1c22,,operator.call()} to @code{operator.__all__}. Patch by
Kreusada.

@item 
bpo-42174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42174}: @ref{131b,,shutil.get_terminal_size()} now falls back to sane values
if the column or line count are 0.

@item 
bpo-35673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35673}: Improve the introspectability of the @code{__loader__} attribute
for namespace packages.  @ref{1158,,importlib.machinery.NamespaceLoader} is
now public, and implements the @ref{1156,,importlib.abc.InspectLoader}
interface. @code{_NamespaceLoader} is kept for backward compatibility.

@item 
bpo-45515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45515}: Add references to @ref{13a,,zoneinfo} in the @ref{34,,datetime}
documentation, mostly replacing outdated references to @code{dateutil.tz}.
Change by Paul Ganssle.

@item 
bpo-45475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45475}: Reverted optimization of iterating @ref{65c,,gzip.GzipFile},
@ref{a66,,bz2.BZ2File}, and @ref{120e,,lzma.LZMAFile} (see bpo-43787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43787}) because
it caused regression when user iterate them without having reference of
them. Patch by Inada Naoki.

@item 
bpo-45489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45489}: Update @ref{1bda,,ForwardRef} to support @code{|} operator.
Patch by Donghee Na.

@item 
bpo-42222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42222}: Removed deprecated support for float arguments in
`randrange()'.

@item 
bpo-45428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45428}: Fix a regression in py_compile when reading filenames from
standard input.

@item 
bpo-45467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45467}: Fix incremental decoder and stream reader in the
"raw-unicode-escape" codec. Previously they failed if the escape sequence
was split.

@item 
bpo-45461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45461}: Fix incremental decoder and stream reader in the
"unicode-escape" codec. Previously they failed if the escape sequence was
split.

@item 
bpo-45239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45239}: Fixed @ref{1c23,,email.utils.parsedate_tz()} crashing with
@ref{174f,,UnboundLocalError} on certain invalid input instead of returning
@code{None}. Patch by Ben Hoyt.

@item 
bpo-45417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45417}: Fix quadratic behaviour in the enum module: Creation of enum
classes with a lot of entries was quadratic.

@item 
bpo-45249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45249}: Fix the behaviour of @ref{1c24,,traceback.print_exc()} when
displaying the caret when the @code{end_offset} in the exception is set to 0.
Patch by Pablo Galindo

@item 
bpo-45416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45416}: Fix use of @ref{c67,,asyncio.Condition} with explicit
@ref{c66,,asyncio.Lock} objects, which was a regression due to removal of
explicit loop arguments. Patch by Joongi Kim.

@item 
bpo-20028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20028}: Empty escapechar/quotechar is not allowed when initializing
@ref{1827,,csv.Dialect}. Patch by Vajrasky Kok and Donghee Na.

@item 
bpo-44904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44904}: Fix bug in the @ref{3e,,doctest} module that caused it to fail if
a docstring included an example with a @code{classmethod} @code{property}. Patch
by Alex Waygood.

@item 
bpo-45406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45406}: Make @ref{1b6d,,inspect.getmodule()} catch @code{FileNotFoundError}
raised by @code{inspect.getabsfile()}, and return @code{None} to indicate that
the module could not be determined.

@item 
bpo-45411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45411}: Add extensions for files containing subtitles - .srt & .vtt -
to the mimetypes.py module.

@item 
bpo-10716@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10716}: Migrated pydoc to HTML5 (without changing the look of it). Side
effect is to update xmlrpc's @code{ServerHTMLDoc} which now uses the CSS too.
cgitb now relies less on pydoc (as it can't use the CSS file).

@item 
bpo-27580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27580}: Add support of null characters in @ref{2d,,csv}.

@item 
bpo-45262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45262}: Prevent use-after-free in asyncio. Make sure the cached running
loop holder gets cleared on dealloc to prevent use-after-free in
get_running_loop

@item 
bpo-45386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45386}: Make @ref{134,,xmlrpc.client} more robust to C runtimes where the
underlying C @code{strftime} function results in a @code{ValueError} when
testing for year formatting options.

@item 
bpo-20028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20028}: Improve error message of @ref{1827,,csv.Dialect} when
initializing. Patch by Vajrasky Kok and Donghee Na.

@item 
bpo-45343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45343}: Update bundled pip to 21.2.4 and setuptools to 58.1.0

@item 
bpo-45328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45328}: Fixed @ref{d35,,http.client.HTTPConnection} to work properly in
OSs that don't support the @code{TCP_NODELAY} socket option.

@item 
bpo-45243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45243}: Add @ref{88a,,setlimit()} and
@ref{88b,,getlimit()} to @ref{54d,,sqlite3.Connection} for
setting and getting SQLite limits by connection basis. Patch by Erlend E.
Aasland.

@item 
bpo-45320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45320}: Removed from the @ref{82,,inspect} module:


@itemize *

@item 

@table @asis

@item the @code{getargspec} function, deprecated since Python 3.0;

use @ref{22f,,inspect.signature()} or @ref{941,,inspect.getfullargspec()} instead.
@end table

@item 
the @code{formatargspec} function, deprecated since Python 3.5;
use the @ref{22f,,inspect.signature()} function and @code{Signature} object
directly.

@item 
the undocumented @code{Signature.from_builtin} and @code{Signature.from_function}
functions, deprecated since Python 3.5; use the
@ref{942,,Signature.from_callable()} method
instead.
@end itemize

Patch by Hugo van Kemenade.

@item 
bpo-45192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45192}: Fix the @code{tempfile._infer_return_type} function so that the
@code{dir} argument of the @ref{e6,,tempfile} functions accepts an object
implementing the @code{os.PathLike} protocol.

Patch by Kyungmin Lee.

@item 
bpo-45160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45160}: When tracing a tkinter variable used by a ttk OptionMenu,
callbacks are no longer made twice.

@item 
bpo-25625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25625}: Added non parallel-safe @ref{820,,chdir()} context
manager to change the current working directory and then restore it on
exit. Simple wrapper around @ref{821,,chdir()}.

@item 
bpo-24139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24139}: Add support for SQLite extended result codes in
@ref{1c25,,sqlite3.Error}. Patch by Erlend E. Aasland.

@item 
bpo-24444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24444}: Fixed an error raised in @ref{7,,argparse} help display when help
for an option is set to 1+ blank spaces or when `choices' arg is an empty
container.

@item 
bpo-44547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44547}: Implement @code{Fraction.__int__}, so that a
@ref{213,,fractions.Fraction} instance @code{f} passes an @code{isinstance(f,
typing.SupportsInt)} check.

@item 
bpo-40321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40321}: Adds support for HTTP 308 redirects to @ref{10e,,urllib}. See
@geindex RFC; RFC 7538
RFC 7538@footnote{https://datatracker.ietf.org/doc/html/rfc7538.html} for details. Patch by Jochem Schulenklopper.

@item 
bpo-41374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41374}: Ensure that @code{socket.TCP_*} constants are exposed on Cygwin
3.1.6 and greater.

@item 
bpo-35970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35970}: Add help flag to the base64 module's command line interface.
Patch contributed by Robert Kuska.
@end itemize

@node ドキュメント<35>,テスト<34>,ライブラリ<106>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id472}@anchor{1c26}
@subsubsection ドキュメント



@itemize -

@item 
bpo-45726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45726}: Improve documentation for @ref{84b,,functools.singledispatch()} and
@ref{be5,,functools.singledispatchmethod}.

@item 
bpo-45680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45680}: Amend the docs on @code{GenericAlias} objects to clarify that
non-container classes can also implement @code{__class_getitem__}. Patch
contributed by Alex Waygood.

@item 
bpo-45618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45618}: Update Sphinx version used to build the documentation to 4.2.0.
Patch by Maciej Olko.

@item 
bpo-45655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45655}: Add a new "relevant PEPs" section to the top of the
documentation for the @code{typing} module. Patch by Alex Waygood.

@item 
bpo-45604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45604}: Add @code{level} argument to @code{multiprocessing.log_to_stderr}
function docs.

@item 
bpo-45516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45516}: Add protocol description to the
@code{importlib.abc.TraversableResources} documentation.

@item 
bpo-45464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45464}: Mention in the documentation of @ref{1c27,,Built-in Exceptions} that inheriting from multiple exception types in a
single subclass is not recommended due to possible memory layout
incompatibility.

@item 
bpo-45449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45449}: Add note about 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} in @ref{1f,,collections.abc}.

@item 
bpo-45516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45516}: Add protocol description to the
@code{importlib.abc.Traversable} documentation.

@item 
bpo-20692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20692}: Add Programming FAQ entry explaining that int literal attribute
access requires either a space after or parentheses around the literal.
@end itemize

@node テスト<34>,ビルド<41>,ドキュメント<35>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id473}@anchor{1c28}
@subsubsection テスト



@itemize -

@item 
bpo-45678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45678}: Add tests for scenarios in which
@ref{be5,,functools.singledispatchmethod} is stacked on top of a method that
has already been wrapped by two other decorators. Patch by Alex Waygood.

@item 
bpo-45578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45578}: Add tests for @ref{206,,dis.distb()}

@item 
bpo-45678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45678}: Add tests to ensure that @code{functools.singledispatchmethod}
correctly wraps the attributes of the target function.

@item 
bpo-45668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45668}: PGO tests now pass when Python is built without test extension
modules.

@item 
bpo-45577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45577}: Add subtests for all @code{pickle} protocols in @code{test_zoneinfo}.

@item 
bpo-45566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45566}: Fix @code{test_frozen_pickle} in @code{test_dataclasses} to check all
@code{pickle} versions.

@item 
bpo-43592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43592}: @code{test.libregrtest} now raises the soft resource limit for
the maximum number of file descriptors when the default is too low for our
test suite as was often the case on macOS.

@item 
bpo-39679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39679}: Add more test cases for @code{@@functools.singledispatchmethod}
when combined with @code{@@classmethod} or @code{@@staticmethod}.

@item 
bpo-45410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45410}: When libregrtest spawns a worker process, stderr is now written
into stdout to keep messages order. Use a single pipe for stdout and
stderr, rather than two pipes. Previously, messages were out of order
which made analysis of buildbot logs harder Patch by Victor Stinner.

@item 
bpo-45402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45402}: Fix test_tools.test_sundry() when Python is built out of tree:
fix how the freeze_modules.py tool locates the _freeze_module program.
Patch by Victor Stinner.

@item 
bpo-45403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45403}: Fix test_sys.test_stdlib_dir() when Python is built outside the
source tree: compare normalized paths. Patch by Victor Stinner.

@item 
bpo-45400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45400}: Fix
test_name_error_suggestions_do_not_trigger_for_too_many_locals() of
test_exceptions if a directory name contains "a1" (like
"Python-3.11.0a1"): use a stricter regular expression. Patch by Victor
Stinner.

@item 
bpo-10572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10572}: Rename @ref{d4,,sqlite3} tests from @code{test_sqlite} to
@code{test_sqlite3}, and relocate them to @code{Lib/test/test_sqlite3}. Patch by
Erlend E. Aasland.
@end itemize

@node ビルド<41>,Windows<36>,テスト<34>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id474}@anchor{1c29}
@subsubsection ビルド



@itemize -

@item 
bpo-43158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43158}: @code{setup.py} now uses values from configure script to build the
@code{_uuid} extension module. Configure now detects util-linux's
@code{libuuid}, too.

@item 
bpo-45666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45666}: Fix warning of @code{swprintf} and @code{%s} usage in
@code{_testembed.c}

@item 
bpo-45548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45548}: @code{Modules/Setup} and @code{Modules/makesetup} have been improved.
The @code{Setup} file now contains working rules for all extensions. Outdated
comments have been removed. Rules defined by @code{makesetup} track
dependencies correctly.

@item 
bpo-45548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45548}: The @ref{92,,math} and @ref{19,,cmath} implementation now require a
C99 compatible @code{libm} and no longer ship with workarounds for missing
acosh, asinh, atanh, expm1, and log1p functions.

@item 
bpo-45595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45595}: @code{setup.py} and @code{makesetup} now track build dependencies on
all Python header files and module specific header files.

@item 
bpo-45571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45571}: @code{Modules/Setup} now use @code{PY_CFLAGS_NODIST} instead of
@code{PY_CFLAGS} to compile shared modules.

@item 
bpo-45570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45570}: @code{pyexpat} and @code{_elementtree} no longer define
obsolete macros @code{HAVE_EXPAT_CONFIG_H} and @code{USE_PYEXPAT_CAPI}.
@code{XML_POOR_ENTROPY} is now defined in @code{expat_config.h}.

@item 
bpo-43974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43974}: @code{setup.py} no longer defines @code{Py_BUILD_CORE_MODULE}.
Instead every module, that uses the internal API, defines the macro.

@item 
bpo-45548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45548}: Fill in missing entries in Modules/Setup.

@item 
bpo-45532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45532}: Update @ref{49c,,sys.version} to use @code{main} as fallback
information. Patch by Jeong YunWon.

@item 
bpo-45536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45536}: The @code{configure} script now checks whether OpenSSL headers and
libraries provide required APIs. Most common APIs are verified. The check
detects outdated or missing OpenSSL. Failures do not stop configure.

@item 
bpo-45221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45221}: Fixed regression in handling of @code{LDFLAGS} and @code{CPPFLAGS}
options where @code{argparse.parse_known_args()} could interpret an option
as one of the built-in command line argument, for example @code{-h} for help.

@item 
bpo-45440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45440}: Building Python now requires a C99 @code{<math.h>} header file
providing the following functions: @code{copysign()}, @code{hypot()},
@code{isfinite()}, @code{isinf()}, @code{isnan()}, @code{round()}. Patch by Victor
Stinner.

@item 
bpo-45405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45405}: Prevent @code{internal configure error} when running @code{configure}
with recent versions of non-Apple clang.  Patch by David Bohman.

@item 
bpo-45433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45433}: Avoid linking libpython with libcrypt.
@end itemize

@node Windows<36>,macOS<26>,ビルド<41>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id475}@anchor{1c2a}
@subsubsection Windows



@itemize -

@item 
bpo-43652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43652}: Update Tcl/Tk to 8.6.11, actually this time. The previous
update incorrectly included 8.6.10.

@item 
bpo-45337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45337}: venv now warns when the created environment may need to be
accessed at a different path, due to redirections, links or junctions. It
also now correctly installs or upgrades components when the alternate path
is required.

@item 
bpo-43851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43851}: Build SQLite @code{SQLITE_OMIT_AUTOINIT} on Windows. Patch by
Erlend E. Aasland.
@end itemize

@node macOS<26>,IDLE<18>,Windows<36>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id476}@anchor{1c2b}
@subsubsection macOS



@itemize -

@item 
bpo-44828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44828}: Avoid tkinter file dialog failure on macOS 12 Monterey when
using the Tk 8.6.11 provided by python.org macOS installers. Patch by Marc
Culler of the Tk project.
@end itemize

@node IDLE<18>,C API<36>,macOS<26>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id477}@anchor{1c2c}
@subsubsection IDLE



@itemize -

@item 
bpo-45495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45495}: Add context keywords 'case' and 'match' to completions list.
@end itemize

@node C API<36>,,IDLE<18>,Python 3 11 0 alpha 2
@anchor{whatsnew/changelog id478}@anchor{1c2d}
@subsubsection C API



@itemize -

@item 
bpo-29103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29103}: @ref{773,,PyType_FromSpec*} now
copies the class name from the spec to a buffer owned by the class, so the
original can be safely deallocated. Patch by Petr Viktorin.

@item 
bpo-45522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45522}: The internal freelists for frame, float, list, dict, async
generators, and context objects can now be disabled.

@item 
bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}: Exclude @ref{3de,,PyWeakref_GET_OBJECT()} from the limited C API.
It never worked since the @code{PyWeakReference} structure is opaque
in the limited C API.

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: Move the @code{interpreteridobject.h} header file from
@code{Include/} to @code{Include/internal/}. It only provides private functions.
Patch by Victor Stinner.

@item 
bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}: The non-limited API files @code{cellobject.h}, @code{classobject.h},
@code{context.h}, @code{funcobject.h}, @code{genobject.h} and @code{longintrepr.h}
have been moved to the @code{Include/cpython} directory. Moreover, the
@code{eval.h} header file was removed. These files must not be included
directly, as they are already included in @code{Python.h}: @ref{987,,Include Files}. If they have been included directly, consider
including @code{Python.h} instead. Patch by Victor Stinner.

@item 
bpo-45474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45474}: The following items are no longer available when
@code{Py_LIMITED_API} is defined:


@itemize *

@item 
@ref{999,,PyMarshal_WriteLongToFile()}

@item 
@ref{99a,,PyMarshal_WriteObjectToFile()}

@item 
@ref{99b,,PyMarshal_ReadObjectFromString()}

@item 
@ref{99c,,PyMarshal_WriteObjectToString()}

@item 
@code{Py_MARSHAL_VERSION} マクロ
@end itemize

These are not part of the @ref{99d,,limited API}.

Patch by Victor Stinner.

@item 
bpo-45434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45434}: Remove the @code{pystrhex.h} header file. It only contains private
functions. C extensions should only include the main @code{<Python.h>} header
file. Patch by Victor Stinner.

@item 
bpo-45440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45440}: Remove the @code{Py_FORCE_DOUBLE()} macro. It was used by the
@code{Py_IS_INFINITY()} macro. Patch by Victor Stinner.

@item 
bpo-45434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45434}: @code{<Python.h>} no longer includes the header files
@code{<stdlib.h>}, @code{<stdio.h>}, @code{<errno.h>} and @code{<string.h>} when the
@code{Py_LIMITED_API} macro is set to @code{0x030b0000} (Python 3.11) or higher.
C extensions should explicitly include the header files after @code{#include
<Python.h>}. Patch by Victor Stinner.

@item 
bpo-41123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41123}: Remove @code{Py_UNICODE_COPY()} and @code{Py_UNICODE_FILL()} macros,
deprecated since Python 3.3. Use @code{PyUnicode_CopyCharacters()} or
@code{memcpy()} (@code{wchar_t*} string), and @code{PyUnicode_Fill()} functions
instead. Patch by Victor Stinner.

@item 
bpo-45412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45412}: Remove the following math macros using the @code{errno} variable:


@itemize *

@item 
@code{Py_ADJUST_ERANGE1()}

@item 
@code{Py_ADJUST_ERANGE2()}

@item 
@code{Py_OVERFLOWED()}

@item 
@code{Py_SET_ERANGE_IF_OVERFLOW()}

@item 
@code{Py_SET_ERRNO_ON_MATH_ERROR()}
@end itemize

Patch by Victor Stinner.

@item 
bpo-45395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45395}: Custom frozen modules (the array set to
@code{PyImport_FrozenModules}) are now treated as additions, rather than
replacing all the default frozen modules. Frozen stdlib modules can still
be disabled by setting the "code" field of the custom array entry to NULL.

@item 
bpo-43760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43760}: Add new @ref{95a,,PyThreadState_EnterTracing()}, and
@ref{95b,,PyThreadState_LeaveTracing()} functions to the limited C API to
suspend and resume tracing and profiling. Patch by Victor Stinner.

@item 
bpo-44220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44220}: @ref{b79,,PyStructSequence_UnnamedField} is added to the Stable
ABI.
@end itemize

@node Python 3 11 0 alpha 1,Python 3 10 0 beta 1,Python 3 11 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-11-0-alpha-1}@anchor{1c2e}
@subsection Python 3.11.0 alpha 1


`Release date: 2021-10-05'

@menu
* セキュリティ: セキュリティ<29>. 
* Core and Builtins: Core and Builtins<104>. 
* ライブラリ: ライブラリ<107>. 
* Core and Builtins: Core and Builtins<105>. 
* ライブラリ: ライブラリ<108>. 
* Core and Builtins: Core and Builtins<106>. 
* ライブラリ: ライブラリ<109>. 
* Core and Builtins: Core and Builtins<107>. 
* ライブラリ: ライブラリ<110>. 
* Core and Builtins: Core and Builtins<108>. 
* ライブラリ: ライブラリ<111>. 
* Core and Builtins: Core and Builtins<109>. 
* ライブラリ: ライブラリ<112>. 
* Core and Builtins: Core and Builtins<110>. 
* ライブラリ: ライブラリ<113>. 
* Core and Builtins: Core and Builtins<111>. 
* ライブラリ: ライブラリ<114>. 
* Core and Builtins: Core and Builtins<112>. 
* ライブラリ: ライブラリ<115>. 
* Core and Builtins: Core and Builtins<113>. 
* ライブラリ: ライブラリ<116>. 
* ドキュメント: ドキュメント<36>. 
* テスト: テスト<35>. 
* ビルド: ビルド<42>. 
* Windows: Windows<37>. 
* macOS: macOS<27>. 
* IDLE: IDLE<19>. 
* Tools/Demos: Tools/Demos<27>. 
* C API: C API<37>. 

@end menu

@node セキュリティ<29>,Core and Builtins<104>,,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id479}@anchor{1c2f}
@subsubsection セキュリティ



@itemize -

@item 
bpo-42278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42278}: Replaced usage of @ref{1c30,,tempfile.mktemp()} with
@ref{144c,,TemporaryDirectory} to avoid a potential race condition.

@item 
bpo-44600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44600}: Fix incorrect line numbers while tracing some failed patterns
in @ref{a0e,,match} statements. Patch by Charles Burkland.

@item 
bpo-41180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41180}: Add auditing events to the @ref{91,,marshal} module, and stop
raising @code{code.__init__} events for every unmarshalled code object.
Directly instantiated code objects will continue to raise an event, and
audit event handlers should inspect or collect the raw marshal data. This
reduces a significant performance overhead when loading from @code{.pyc}
files.

@item 
bpo-44394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44394}: Update the vendored copy of libexpat to 2.4.1 (from 2.2.8) to
get the fix for the 
@geindex Common Vulnerabilities and Exposures; CVE 2013-0340
CVE 2013-0340@footnote{https://www.cve.org/CVERecord?id=CVE-2013-0340} "Billion Laughs" vulnerability. This
copy is most used on Windows and macOS.

@item 
bpo-43124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43124}: Made the internal @code{putcmd} function in @ref{cf,,smtplib}
sanitize input for presence of @code{\r} and @code{\n} characters to avoid
(unlikely) command injection.

@item 
bpo-44022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44022}: @ref{73,,http.client} now avoids infinitely reading potential HTTP
headers after a @code{100 Continue} status response from the server.
@end itemize

@node Core and Builtins<104>,ライブラリ<107>,セキュリティ<29>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id480}@anchor{1c31}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43760}: The number of hardware branches per instruction dispatch is
reduced from two to one by adding a special instruction for tracing. Patch
by Mark Shannon.

@item 
bpo-45061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45061}: Add a deallocator to the bool type to detect refcount bugs in C
extensions which call Py_DECREF(Py_True) or Py_DECREF(Py_False) by
mistake. Detect also refcount bugs when the empty tuple singleton or the
Unicode empty string singleton is destroyed by mistake. Patch by Victor
Stinner.

@item 
bpo-24076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24076}: sum() was further optimised for summing up single digit
integers.

@item 
bpo-45190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45190}: Update Unicode databases to Unicode 14.0.0.

@item 
bpo-45167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45167}: Fix deepcopying of @ref{9ec,,types.GenericAlias} objects.

@item 
bpo-45155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45155}: @ref{1c32,,int.to_bytes()} and @ref{1be9,,int.from_bytes()} now take a
default value of @code{"big"} for the @code{byteorder} argument.
@ref{1c32,,int.to_bytes()} also takes a default value of @code{1} for the
@code{length} argument.
@end itemize

@node ライブラリ<107>,Core and Builtins<105>,Core and Builtins<104>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id481}@anchor{1c33}
@subsubsection ライブラリ



@itemize -

@item 
bpo-44219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44219}: Release the GIL while performing @code{isatty} system calls on
arbitrary file descriptors. In particular, this affects @ref{1c34,,os.isatty()},
@ref{1c35,,os.device_encoding()} and @ref{9be,,io.TextIOWrapper}. By extension,
@ref{740,,io.open()} in text mode is also affected. This change solves a
deadlock in @ref{1c34,,os.isatty()}. Patch by Vincent Michel in bpo-44219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44219}.
@end itemize

@node Core and Builtins<105>,ライブラリ<108>,ライブラリ<107>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id482}@anchor{1c36}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44959}: Added fallback to extension modules with '.sl' suffix on HP-UX
@end itemize

@node ライブラリ<108>,Core and Builtins<106>,Core and Builtins<105>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id483}@anchor{1c37}
@subsubsection ライブラリ



@itemize -

@item 
bpo-45121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45121}: Fix issue where @code{Protocol.__init__} raises @code{RecursionError}
when it's called directly or via @code{super()}. Patch provided by Yurii
Karabas.
@end itemize

@node Core and Builtins<106>,ライブラリ<109>,ライブラリ<108>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id484}@anchor{1c38}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44348}: The deallocator function of the @ref{7d6,,BaseException} type now
uses the trashcan mechanism to prevent stack overflow. For example, when a
@ref{f68,,RecursionError} instance is raised, it can be linked to another
RecursionError through the @code{__context__} attribute or the
@code{__traceback__} attribute, and then a chain of exceptions is created.
When the chain is destroyed, nested deallocator function calls can crash
with a stack overflow if the chain is too long compared to the available
stack memory. Patch by Victor Stinner.

@item 
bpo-45123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45123}: Fix PyAiter_Check to only check for the __anext__ presence (not
for __aiter__). Rename PyAiter_Check to PyAIter_Check, PyObject_GetAiter
-> PyObject_GetAIter.

@item 
bpo-1514420@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1514420}: Interpreter no longer attempts to open files with names in
angle brackets (like "<string>" or "<stdin>") when formatting an
exception.

@item 
bpo-41031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41031}: Match C and Python code formatting of unprintable exceptions
and exceptions in the @ref{1,,__main__} module.

@item 
bpo-37330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37330}: @ref{316,,open()}, @ref{740,,io.open()}, @ref{315,,codecs.open()} and
@ref{940,,fileinput.FileInput} no longer accept @code{'U'} ("universal
newline") in the file mode. This flag was deprecated since Python 3.3.
Patch by Victor Stinner.

@item 
bpo-45083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45083}: When the interpreter renders an exception, its name now has a
complete qualname. Previously only the class name was concatenated to the
module name, which sometimes resulted in an incorrect full name being
displayed.

(This issue impacted only the C code exception rendering, the
@ref{104,,traceback} module was using qualname already).

@item 
bpo-34561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34561}: List sorting now uses the merge-ordering strategy from Munro
and Wild's @code{powersort()}. Unlike the former strategy, this is provably
near-optimal in the entropy of the distribution of run lengths. Most uses
of @code{list.sort()} probably won't see a significant time difference, but
may see significant improvements in cases where the former strategy was
exceptionally poor. However, as these are all fast linear-time
approximations to a problem that's inherently at best quadratic-time to
solve truly optimally, it's also possible to contrive cases where the
former strategy did better.

@item 
bpo-45056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45056}: Compiler now removes trailing unused constants from co_consts.

@item 
bpo-45020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45020}: Add a new command line option, "-X frozen_modules=[on|off]" to
opt out of (or into) using optional frozen modules.  This defaults to "on"
(or "off" if it's running out of the source tree).
@end itemize

@node ライブラリ<109>,Core and Builtins<107>,Core and Builtins<106>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id485}@anchor{1c39}
@subsubsection ライブラリ



@itemize -

@item 
bpo-45012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45012}: In @ref{b2,,posix}, release GIL during @code{stat()}, @code{lstat()},
and @code{fstatat()} syscalls made by @ref{1a6b,,os.DirEntry.stat()}. Patch by
Stanisław Skonieczny.
@end itemize

@node Core and Builtins<107>,ライブラリ<110>,ライブラリ<109>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id486}@anchor{1c3a}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-45018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45018}: Fixed pickling of range iterators that iterated for over
@code{2**32} times.

@item 
bpo-45000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45000}: A @ref{18e,,SyntaxError} is now raised when trying to delete
@ref{9da,,__debug__}. Patch by Donghee Na.

@item 
bpo-44963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44963}: Implement @code{send()} and @code{throw()} methods for
@code{anext_awaitable} objects. Patch by Pablo Galindo.
@end itemize

@node ライブラリ<110>,Core and Builtins<108>,Core and Builtins<107>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id487}@anchor{1c3b}
@subsubsection ライブラリ



@itemize -

@item 
bpo-44962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44962}: Fix a race in WeakKeyDictionary, WeakValueDictionary and
WeakSet when two threads attempt to commit the last pending removal. This
fixes asyncio.create_task and fixes a data loss in asyncio.run where
shutdown_asyncgens is not run
@end itemize

@node Core and Builtins<108>,ライブラリ<111>,ライブラリ<110>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id488}@anchor{1c3c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24234}: Implement the @code{__bytes__()} special method on the
@ref{192,,bytes} type, so a bytes object @code{b}  passes an @code{isinstance(b,
typing.SupportsBytes)} check.

@item 
bpo-24234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24234}: Implement the @code{__complex__()} special method on the
@ref{197,,complex} type, so a complex number @code{z} passes an @code{isinstance(z,
typing.SupportsComplex)} check.

@item 
bpo-44954@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44954}: Fixed a corner case bug where the result of
@code{float.fromhex('0x.8p-1074')} was rounded the wrong way.

@item 
bpo-44947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44947}: Refine the syntax error for trailing commas in import
statements. Patch by Pablo Galindo.

@item 
bpo-44945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44945}: Specialize the BINARY_ADD instruction using the PEP 659
machinery. Adds five new instructions:


@itemize *

@item 
BINARY_ADD_ADAPTIVE

@item 
BINARY_ADD_FLOAT

@item 
BINARY_ADD_INT

@item 
BINARY_ADD_UNICODE

@item 
BINARY_ADD_UNICODE_INPLACE_FAST
@end itemize
@end itemize

@node ライブラリ<111>,Core and Builtins<109>,Core and Builtins<108>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id489}@anchor{1c3d}
@subsubsection ライブラリ



@itemize -

@item 
bpo-44929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44929}: Fix some edge cases of @code{enum.Flag} string representation in
the REPL. Patch by Pablo Galindo.
@end itemize

@node Core and Builtins<109>,ライブラリ<112>,ライブラリ<111>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id490}@anchor{1c3e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44914}: Class version tags are no longer recycled.

This means that a version tag serves as a unique identifier for the state
of a class. We rely on this for effective specialization of the LOAD_ATTR
and other instructions.

@item 
bpo-44698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44698}: Restore behaviour of complex exponentiation with integer-valued
exponent of type @ref{196,,float} or @ref{197,,complex}.

@item 
bpo-44895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44895}: A debug variable 
@geindex PYTHONDUMPREFSFILE
@geindex 環境変数; PYTHONDUMPREFSFILE
@ref{1c3f,,PYTHONDUMPREFSFILE} is added for
creating a dump file which is generated by @ref{636,,--with-trace-refs}.
Patch by Donghee Na.

@item 
bpo-44900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44900}: Add five superinstructions for PEP 659 quickening:


@itemize *

@item 
LOAD_FAST LOAD_FAST

@item 
STORE_FAST LOAD_FAST

@item 
LOAD_FAST LOAD_CONST

@item 
LOAD_CONST LOAD_FAST

@item 
STORE_FAST STORE_FAST
@end itemize

@item 
bpo-44889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44889}: Initial implementation of adaptive specialization of
@code{LOAD_METHOD}. The following specialized forms were added:


@itemize *

@item 
@code{LOAD_METHOD_CACHED}

@item 
@code{LOAD_METHOD_MODULE}

@item 
@code{LOAD_METHOD_CLASS}
@end itemize

@item 
bpo-44890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44890}: Specialization stats are always collected in debug builds.

@item 
bpo-44885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44885}: Correct the ast locations of f-strings with format specs and
repeated expressions. Patch by Pablo Galindo

@item 
bpo-44878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44878}: Remove the loop from the bytecode interpreter. All instructions
end with a DISPATCH macro, so the loop is now redundant.

@item 
bpo-44878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44878}: Remove switch statement for interpreter loop when using
computed gotos. This makes sure that we only have one dispatch table in
the interpreter.

@item 
bpo-44874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44874}: Deprecate the old trashcan macros
(@code{Py_TRASHCAN_SAFE_BEGIN}/@code{Py_TRASHCAN_SAFE_END}). They should be
replaced by the new macros @code{Py_TRASHCAN_BEGIN} and @code{Py_TRASHCAN_END}.

@item 
bpo-44872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44872}: Use new trashcan macros (Py_TRASHCAN_BEGIN/END) in
frameobject.c instead of the old ones (Py_TRASHCAN_SAFE_BEGIN/END).

@item 
bpo-33930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33930}: Fix segmentation fault with deep recursion when cleaning method
objects. Patch by Augusto Goulart and Pablo Galindo.

@item 
bpo-25782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25782}: Fix bug where @code{PyErr_SetObject} hangs when the current
exception has a cycle in its context chain.

@item 
bpo-44856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44856}: Fix reference leaks in the error paths of @code{update_bases()}
and @code{__build_class__}. Patch by Pablo Galindo.

@item 
bpo-44826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44826}: Initial implementation of adaptive specialization of STORE_ATTR

Three specialized forms of STORE_ATTR are added:


@itemize *

@item 
STORE_ATTR_SLOT

@item 
STORE_ATTR_SPLIT_KEYS

@item 
STORE_ATTR_WITH_HINT
@end itemize

@item 
bpo-44838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44838}: Fixed a bug that was causing the parser to raise an incorrect
custom @ref{18e,,SyntaxError} for invalid 'if' expressions. Patch by Pablo
Galindo.

@item 
bpo-44821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44821}: Create instance dictionaries (__dict__) eagerly, to improve
regularity of object layout and assist specialization.

@item 
bpo-44792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44792}: Improve syntax errors for if expressions. Patch by Miguel Brito

@item 
bpo-34013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34013}: Generalize the invalid legacy statement custom error message
(like the one generated when "print" is called without parentheses) to
include more generic expressions. Patch by Pablo Galindo

@item 
bpo-44732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44732}: Rename @code{types.Union} to @code{types.UnionType}.

@item 
bpo-44725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44725}: Expose specialization stats in python via
@code{_opcode.get_specialization_stats()}.

@item 
bpo-44717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44717}: Improve AttributeError on circular imports of submodules.

@item 
bpo-44698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44698}: Fix undefined behaviour in complex object exponentiation.

@item 
bpo-44653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44653}: Support @ref{10a,,typing} types in parameter substitution in the
union type.

@item 
bpo-44676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44676}: Add ability to serialise @code{types.Union} objects. Patch
provided by Yurii Karabas.

@item 
bpo-44633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44633}: Parameter substitution of the union type with wrong types now
raises @code{TypeError} instead of returning @ref{1a2,,NotImplemented}.

@item 
bpo-44661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44661}: Update @code{property_descr_set} to use vectorcall if possible.
Patch by Donghee Na.

@item 
bpo-44662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44662}: Add @code{__module__} to @code{types.Union}. This also fixes
@code{types.Union} issues with @code{typing.Annotated}. Patch provided by Yurii
Karabas.

@item 
bpo-44655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44655}: Include the name of the type in unset __slots__ attribute
errors. Patch by Pablo Galindo

@item 
bpo-44655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44655}: Don't include a missing attribute with the same name as the
failing one when offering suggestions for missing attributes. Patch by
Pablo Galindo

@item 
bpo-44646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44646}: Fix the hash of the union type: it no longer depends on the
order of arguments.

@item 
bpo-44636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44636}: Collapse union of equal types. E.g. the result of @code{int | int}
is now @code{int}. Fix comparison of the union type with non-hashable
objects. E.g. @code{int | str == @{@}} no longer raises a TypeError.
@end itemize

@node ライブラリ<112>,Core and Builtins<110>,Core and Builtins<109>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id491}@anchor{1c40}
@subsubsection ライブラリ



@itemize -

@item 
bpo-44611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44611}: On Windows, @ref{746,,os.urandom()}: uses BCryptGenRandom API
instead of CryptGenRandom API which is deprecated from Microsoft Windows
API. Patch by Donghee Na.
@end itemize

@node Core and Builtins<110>,ライブラリ<113>,ライブラリ<112>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id492}@anchor{1c41}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44635}: Convert @code{None} to @code{type(None)} in the union type
constructor.

@item 
bpo-26280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26280}: Implement adaptive specialization for BINARY_SUBSCR

Three specialized forms of BINARY_SUBSCR are added:


@itemize *

@item 
BINARY_SUBSCR_LIST_INT

@item 
BINARY_SUBSCR_TUPLE_INT

@item 
BINARY_SUBSCR_DICT
@end itemize

@item 
bpo-44589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44589}: Mapping patterns in @code{match} statements with two or more equal
literal keys will now raise a @ref{18e,,SyntaxError} at compile-time.

@item 
bpo-44606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44606}: Fix @code{__instancecheck__} and @code{__subclasscheck__} for the
union type.

@item 
bpo-42073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42073}: The @code{@@classmethod} decorator can now wrap other
classmethod-like descriptors.

@item 
bpo-41972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41972}: Tuned the string-searching algorithm of fastsearch.h to have a
shorter inner loop for most cases.

@item 
bpo-44590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44590}: All necessary data for executing a Python function (local
variables, stack, etc) is now kept in a per-thread stack. Frame objects
are lazily allocated on demand. This increases performance by about 7% on
the standard benchmark suite. Introspection and debugging are unaffected
as frame objects are always available when needed. Patch by Mark Shannon.

@item 
bpo-44584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44584}: The threading debug (@code{PYTHONTHREADDEBUG} environment
variable) is deprecated in Python 3.10 and will be removed in Python 3.12.
This feature requires a debug build of Python. Patch by Victor Stinner.

@item 
bpo-43895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43895}: An obsolete internal cache of shared object file handles added
in 1995 that attempted, but did not guarantee, that a .so would not be
dlopen'ed twice to work around flaws in mid-1990s posix-ish operating
systems has been removed from dynload_shlib.c.
@end itemize

@node ライブラリ<113>,Core and Builtins<111>,Core and Builtins<110>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id493}@anchor{1c42}
@subsubsection ライブラリ



@itemize -

@item 
bpo-44490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44490}: @ref{10a,,typing} now searches for type parameters in
@code{types.Union} objects. @code{get_type_hints} will also properly resolve
annotations with nested @code{types.Union} objects. Patch provided by Yurii
Karabas.
@end itemize

@node Core and Builtins<111>,ライブラリ<114>,ライブラリ<113>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id494}@anchor{1c43}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43950}: Code objects can now provide the column information for
instructions when available. This is levaraged during traceback printing
to show the expressions responsible for errors.

Contributed by Pablo Galindo, Batuhan Taskaya and Ammar Askar as part of
@geindex Python Enhancement Proposals; PEP 657
PEP 657@footnote{https://peps.python.org/pep-0657/}.

@item 
bpo-44562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44562}: Remove uses of @ref{171c,,PyObject_GC_Del()} in error path when
initializing @ref{9ec,,types.GenericAlias}.
@end itemize

@node ライブラリ<114>,Core and Builtins<112>,Core and Builtins<111>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id495}@anchor{1c44}
@subsubsection ライブラリ



@itemize -

@item 
bpo-41486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41486}: Fix a memory consumption and copying performance regression in
earlier 3.10 beta releases if someone used an output buffer larger than
4GiB with zlib.decompress on input data that expands that large.
@end itemize

@node Core and Builtins<112>,ライブラリ<115>,ライブラリ<114>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id496}@anchor{1c45}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43908}: Heap types with the @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} flag
can now inherit the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} vectorcall protocol.  Previously, this was
only possible for @ref{983,,static types}.  Patch by Erlend E.
Aasland.

@item 
bpo-44553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44553}: Implement GC methods for @code{types.Union} to break reference
cycles and prevent memory leaks.

@item 
bpo-44490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44490}: Add @code{__parameters__} attribute and @code{__getitem__} operator
to @code{types.Union}. Patch provided by Yurii Karabas.

@item 
bpo-44523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44523}: Remove the pass-through for @ref{801,,hash()} of
@ref{c46,,weakref.proxy} objects to prevent unintended consequences when the
original referred object dies while the proxy is part of a hashable
object. Patch by Pablo Galindo.

@item 
bpo-44483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44483}: Fix a crash in @code{types.Union} objects when creating a union of
an object with bad @code{__module__} field.

@item 
bpo-44486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44486}: Modules will always have a dictionary, even when created by
@code{types.ModuleType.__new__()}

@item 
bpo-44472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44472}: Fix ltrace functionality when exceptions are raised. Patch by
Pablo Galindo

@item 
bpo-12022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12022}: A @ref{198,,TypeError} is now raised instead of an
@ref{5f0,,AttributeError} in @ref{186,,with} and @ref{185,,async with}
statements for objects which do not support the @ref{1e1,,context manager} or
@ref{7f0,,asynchronous context manager} protocols correspondingly.

@item 
bpo-44297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44297}: Make sure that the line number is set when entering a
comprehension scope. This ensures that backtraces including generator
expressions show the correct line number.

@item 
bpo-44456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44456}: Improve the syntax error when mixing positional and keyword
patterns. Patch by Pablo Galindo.

@item 
bpo-44409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44409}: Fix error location information for tokenizer errors raised on
initialization of the tokenizer. Patch by Pablo Galindo.

@item 
bpo-44396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44396}: Fix a possible crash in the tokenizer when raising syntax
errors for unclosed strings. Patch by Pablo Galindo.

@item 
bpo-44376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44376}: Exact integer exponentiation (like @code{i**2} or @code{pow(i, 2)})
with a small exponent is much faster, due to reducing overhead in such
cases.

@item 
bpo-44313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44313}: Directly imported objects and modules (through import and from
import statements) don't generate @code{LOAD_METHOD}/@code{CALL_METHOD} for
directly accessed objects on their namespace. They now use the regular
@code{LOAD_ATTR}/@code{CALL_FUNCTION}.

@item 
bpo-44338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44338}: Implement adaptive specialization for LOAD_GLOBAL

Two specialized forms of LOAD_GLOBAL are added:


@itemize *

@item 
LOAD_GLOBAL_MODULE

@item 
LOAD_GLOBAL_BUILTIN
@end itemize

@item 
bpo-44368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44368}: Improve syntax errors for invalid "as" targets. Patch by Pablo
Galindo

@item 
bpo-44349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44349}: Fix an edge case when displaying text from files with encoding
in syntax errors. Patch by Pablo Galindo.

@item 
bpo-44337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44337}: Initial implementation of adaptive specialization of LOAD_ATTR

Four specialized forms of LOAD_ATTR are added:


@itemize *

@item 
LOAD_ATTR_SLOT

@item 
LOAD_ATTR_SPLIT_KEYS

@item 
LOAD_ATTR_WITH_HINT

@item 
LOAD_ATTR_MODULE
@end itemize

@item 
bpo-44335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44335}: Fix a regression when identifying incorrect characters in
syntax errors. Patch by Pablo Galindo

@item 
bpo-43693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43693}: Computation of the offsets of cell variables is done in the
compiler instead of at runtime. This reduces the overhead of handling cell
and free variables, especially in the case where a variable is both an
argument and cell variable.

@item 
bpo-44317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44317}: Improve tokenizer error with improved locations. Patch by Pablo
Galindo.
@end itemize

@node ライブラリ<115>,Core and Builtins<113>,Core and Builtins<112>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id497}@anchor{1c46}
@subsubsection ライブラリ



@itemize -

@item 
bpo-44304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44304}: Fix a crash in the @ref{d4,,sqlite3} module that happened when the
garbage collector clears @code{sqlite.Statement} objects. Patch by Pablo
Galindo
@end itemize

@node Core and Builtins<113>,ライブラリ<116>,ライブラリ<115>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id498}@anchor{1c47}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44305}: Improve error message for @code{try} blocks without @code{except} or
@code{finally} blocks. Patch by Pablo Galindo.

@item 
bpo-43413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43413}: Constructors of subclasses of some builtin classes (e.g.
@ref{614,,tuple}, @ref{24d,,list}, @ref{7f2,,frozenset}) no longer accept
arbitrary keyword arguments. [reverted in 3.11a4] Subclass of @ref{184,,set}
can now define a @code{__new__()} method with additional keyword parameters
without overriding also @code{__init__()}.

@item 
bpo-43667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43667}: Improve Unicode support in non-UTF locales on Oracle Solaris.
This issue does not affect other Solaris systems.

@item 
bpo-43693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43693}: A new opcode MAKE_CELL has been added that effectively moves
some of the work done on function entry into the compiler and into the
eval loop.  In addition to creating the required cell objects, the new
opcode converts relevant arguments (and other locals) to cell variables on
function entry.

@item 
bpo-44232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44232}: Fix a regression in @ref{f44,,type()} when a metaclass raises an
exception. The C function @code{type_new()} must properly report the
exception when a metaclass constructor raises an exception and the winner
class is not the metaclass. Patch by Victor Stinner.

@item 
bpo-44201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44201}: Avoid side effects of checking for specialized syntax errors in
the REPL that was causing it to ask for extra tokens after a syntax error
had been detected. Patch by Pablo Galindo

@item 
bpo-43693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43693}: @code{PyCodeObject} gained @code{co_fastlocalnames} and
@code{co_fastlocalkinds} as the authoritative source of fast locals info.
Marshaled code objects have changed accordingly.

@item 
bpo-44184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44184}: Fix a crash at Python exit when a deallocator function removes
the last strong reference to a heap type. Patch by Victor Stinner.

@item 
bpo-44187@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44187}: Implement quickening in the interpreter. This offers no
advantages as yet, but is an enabler of future optimizations. See PEP 659
for full explanation.

@item 
bpo-44180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44180}: The parser doesn't report generic syntax errors that happen in
a position further away that the one it reached in the first pass. Patch
by Pablo Galindo

@item 
bpo-44168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44168}: Fix error message in the parser involving keyword arguments
with invalid expressions. Patch by Pablo Galindo

@item 
bpo-44156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44156}: String caches in @code{compile.c} are now subinterpreter
compatible.

@item 
bpo-44143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44143}: Fixed a crash in the parser that manifest when raising
tokenizer errors when an existing exception was present. Patch by Pablo
Galindo.

@item 
bpo-44032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44032}: Move 'fast' locals and other variables from the frame object to
a per-thread datastack.

@item 
bpo-44114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44114}: Fix incorrect dictkeys_reversed and dictitems_reversed function
signatures in C code, which broke webassembly builds.

@item 
bpo-44110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44110}: Improve @code{str.__getitem__()} error message

@item 
bpo-26110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26110}: Add @code{CALL_METHOD_KW} opcode to speed up method calls with
keyword arguments.  Idea originated from PyPy.  A side effect is executing
@code{CALL_METHOD} is now branchless in the evaluation loop.

@item 
bpo-28307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28307}: Compiler now optimizes simple C-style formatting with literal
format containing only format codes %s, %r and %a by converting them to
f-string expressions.

@item 
bpo-43149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43149}: Correct the syntax error message regarding multiple exception
types to not refer to "exception groups". Patch by Pablo Galindo

@item 
bpo-43822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43822}: The parser will prioritize tokenizer errors over custom syntax
errors when raising exceptions. Patch by Pablo Galindo.

@item 
bpo-40222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40222}: "Zero cost" exception handling.


@itemize *

@item 
Uses a lookup table to determine how to handle exceptions.

@item 
Removes SETUP_FINALLY and POP_TOP block instructions, eliminating the runtime overhead of try statements.

@item 
Reduces the size of the frame object by about 60%.
@end itemize

Patch by Mark Shannon

@item 
bpo-43918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43918}: Document the signature and @code{default} argument in the
docstring of the new @code{anext} builtin.

@item 
bpo-43833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43833}: Emit a deprecation warning if the numeric literal is
immediately followed by one of keywords: and, else, for, if, in, is, or.
Raise a syntax error with more informative message if it is immediately
followed by other keyword or identifier.

@item 
bpo-43879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43879}: Add native_thread_id to PyThreadState. Patch by Gabriele N.
Tornetta.

@item 
bpo-43693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43693}: Compute cell offsets relative to locals in compiler. Allows the
interpreter to treats locals and cells a single array, which is slightly
more efficient. Also make the LOAD_CLOSURE opcode an alias for LOAD_FAST.
Preserving LOAD_CLOSURE helps keep bytecode a bit more readable.

@item 
bpo-17792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17792}: More accurate error messages for access of unbound locals or
free vars.

@item 
bpo-28146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28146}: Fix a confusing error message in @ref{833,,str.format()}.

@item 
bpo-11105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11105}: When compiling @ref{4c3,,ast.AST} objects with recursive
references through @ref{4b1,,compile()}, the interpreter doesn't crash anymore
instead it raises a @ref{f68,,RecursionError}.

@item 
bpo-39091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39091}: Fix crash when using passing a non-exception to a generator's
@code{throw()} method. Patch by Noah Oxer

@item 
bpo-33346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33346}: Asynchronous comprehensions are now allowed inside
comprehensions in asynchronous functions.  Outer comprehensions implicitly
become asynchronous.
@end itemize

@node ライブラリ<116>,ドキュメント<36>,Core and Builtins<113>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id499}@anchor{1c48}
@subsubsection ライブラリ



@itemize -

@item 
bpo-45371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45371}: Fix clang rpath issue in @code{distutils}. The UnixCCompiler now
uses correct clang option to add a runtime library directory (rpath) to a
shared library.

@item 
bpo-45329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45329}: Fix freed memory access in @code{pyexpat.xmlparser} when
building it with an installed expat library <= 2.2.0.

@item 
bpo-41710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41710}: On Unix, if the @code{sem_clockwait()} function is available in
the C library (glibc 2.30 and newer), the @ref{8a7,,threading.Lock.acquire()}
method now uses the monotonic clock (@ref{8a8,,time.CLOCK_MONOTONIC}) for
the timeout, rather than using the system clock
(@ref{8a9,,time.CLOCK_REALTIME}), to not be affected by system clock
changes. Patch by Victor Stinner.

@item 
bpo-1596321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1596321}: Fix the @code{threading._shutdown()} function when the
@ref{f3,,threading} module was imported first from a thread different than
the main thread: no longer log an error at Python exit.

@item 
bpo-45274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45274}: Fix a race condition in the @ref{13fd,,Thread.join()} method of the @ref{f3,,threading} module. If the
function is interrupted by a signal and the signal handler raises an
exception, make sure that the thread remains in a consistent state to
prevent a deadlock. Patch by Victor Stinner.

@item 
bpo-21302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21302}: In Unix operating systems, @ref{8ac,,time.sleep()} now uses the
@code{nanosleep()} function, if @code{clock_nanosleep()} is not available but
@code{nanosleep()} is available. @code{nanosleep()} allows to sleep with
nanosecond precision.

@item 
bpo-21302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21302}: On Windows, @ref{8ac,,time.sleep()} now uses a waitable timer which
has a resolution of 100 nanoseconds (10@w{^-7} seconds). Previously,
it had a resolution of 1 millisecond (10@w{^-3} seconds). Patch by
Benjamin Szőke and Victor Stinner.

@item 
bpo-45238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45238}: Fix @code{unittest.IsolatedAsyncioTestCase.debug()}: it runs now
asynchronous methods and callbacks.

@item 
bpo-36674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36674}: @ref{1c49,,unittest.TestCase.debug()} raises now a
@ref{11e6,,unittest.SkipTest} if the class or the test method are decorated
with the skipping decorator.

@item 
bpo-45235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45235}: Fix an issue where argparse would not preserve values in a
provided namespace when using a subparser with defaults.

@item 
bpo-45183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45183}: Have zipimport.zipimporter.find_spec() not raise an exception
when the underlying zip file has been deleted and the internal cache has
been reset via invalidate_cache().

@item 
bpo-45234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45234}: Fixed a regression in @ref{c4e,,copyfile()},
@ref{c4f,,copy()}, @ref{c50,,copy2()} raising
@ref{264,,FileNotFoundError} when source is a directory, which should raise
@ref{1264,,IsADirectoryError}

@item 
bpo-45228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45228}: Fix stack buffer overflow in parsing J1939 network address.

@item 
bpo-45225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45225}: use map function instead of genexpr in capwords.

@item 
bpo-42135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42135}: Fix typo: @code{importlib.find_loader} is really slated for
removal in Python 3.12 not 3.10, like the others in PR 25169.

Patch by Hugo van Kemenade.

@item 
bpo-20524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20524}: Improves error messages on @code{.format()} operation for @code{str},
@code{float}, @code{int}, and @code{complex}. New format now shows the problematic
pattern and the object type.

@item 
bpo-45168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45168}: Change @ref{205,,dis.dis()} output to omit op arg values that cannot
be resolved due to @code{co_consts}, @code{co_names} etc not being provided.
Previously the oparg itself was repeated in the value field, which is not
useful and can be confusing.

@item 
bpo-21302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21302}: In Unix operating systems, @ref{8ac,,time.sleep()} now uses the
@code{clock_nanosleep()} function, if available, which allows to sleep for an
interval specified with nanosecond precision.

@item 
bpo-45173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45173}: Remove from the @ref{26,,configparser} module: the
@code{SafeConfigParser} class, the @code{filename} property of the
@ref{729,,ParsingError} class, the @code{readfp()} method of
the @ref{4de,,ConfigParser} class, deprecated since Python
3.2.

Patch by Hugo van Kemenade.

@item 
bpo-44987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44987}: Pure ASCII strings are now normalized in constant time by
@ref{8e4,,unicodedata.normalize()}. Patch by Donghee Na.

@item 
bpo-35474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35474}: Calling @ref{1c4a,,mimetypes.guess_all_extensions()} with
@code{strict=False} no longer affects the result of the following call with
@code{strict=True}. Also, mutating the returned list no longer affects the
global state.

@item 
bpo-45166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45166}: @ref{8c0,,typing.get_type_hints()} now works with
@ref{56e,,Final} wrapped in @ref{1bda,,ForwardRef}.

@item 
bpo-45162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45162}: Remove many old deprecated @ref{10c,,unittest} features:


@itemize *

@item 
"@code{fail*}" and "@code{assert*}" aliases of @ref{2b3,,TestCase} methods.

@item 
Broken from start @ref{2b3,,TestCase} method @code{assertDictContainsSubset()}.

@item 
Ignored @code{<unittest.TestLoader.loadTestsFromModule> TestLoader.loadTestsFromModule()} parameter `use_load_tests'.

@item 
Old alias @code{_TextTestResult} of @ref{754,,TextTestResult}.
@end itemize

@item 
bpo-38371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38371}: Remove the deprecated @code{split()} method of
@code{_tkinter.TkappType}. Patch by Erlend E. Aasland.

@item 
bpo-20499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20499}: Improve the speed and accuracy of statistics.pvariance().

@item 
bpo-45132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45132}: Remove @ref{588,,__getitem__()} methods of
@ref{93e,,xml.dom.pulldom.DOMEventStream}, @ref{93f,,wsgiref.util.FileWrapper}
and @ref{940,,fileinput.FileInput}, deprecated since Python 3.9.

Patch by Hugo van Kemenade.

@item 
bpo-45129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45129}: Due to significant security concerns, the `reuse_address'
parameter of @ref{93c,,asyncio.loop.create_datagram_endpoint()}, disabled in
Python 3.9, is now entirely removed. This is because of the behavior of
the socket option @code{SO_REUSEADDR} in UDP.

Patch by Hugo van Kemenade.

@item 
bpo-45124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45124}: The @code{bdist_msi} command, deprecated in Python 3.9, is now
removed.

Use @code{bdist_wheel} (wheel packages) instead.

Patch by Hugo van Kemenade.

@item 
bpo-30856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30856}: @ref{137f,,unittest.TestResult} methods
@ref{1c4b,,addFailure()},
@ref{1c4c,,addError()},
@ref{1c4d,,addSkip()} and
@ref{1c4e,,addSubTest()} are now called immediately after
raising an exception in test or finishing a subtest. Previously they were
called only after finishing the test clean up.

@item 
bpo-45034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45034}: Changes how error is formatted for @code{struct.pack} with @code{'H'}
and @code{'h'} modes and too large / small numbers. Now it shows the actual
numeric limits, while previously it was showing arithmetic expressions.

@item 
bpo-25894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25894}: @ref{10c,,unittest} now always reports skipped and failed subtests
separately: separate characters in default mode and separate lines in
verbose mode. Also the test description is now output for errors in test
method, class and module cleanups.

@item 
bpo-45081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45081}: Fix issue when dataclasses that inherit from
@code{typing.Protocol} subclasses have wrong @code{__init__}. Patch provided by
Yurii Karabas.

@item 
bpo-45085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45085}: The @code{binhex} module, deprecated in Python 3.9, is now
removed. The following @ref{11,,binascii} functions, deprecated in Python
3.9, are now also removed:


@itemize *

@item 
@code{a2b_hqx()}, @code{b2a_hqx()};

@item 
@code{rlecode_hqx()}, @code{rledecode_hqx()}.
@end itemize

The @ref{93d,,binascii.crc_hqx()} function remains available.

Patch by Victor Stinner.

@item 
bpo-40360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40360}: The @code{lib2to3} package is now deprecated and may not be
able to parse Python 3.10 or newer. See the 
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/} (New PEG parser for
CPython). Patch by Victor Stinner.

@item 
bpo-45075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45075}: Rename @code{traceback.StackSummary.format_frame()} to
@ref{8b2,,traceback.StackSummary.format_frame_summary()}. This method was added
for 3.11 so it was not released yet.

Updated code and docs to better distinguish frame and FrameSummary.

@item 
bpo-31299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31299}: Add option to completely drop frames from a traceback by
returning @code{None} from a @code{format_frame()}
override.

@item 
bpo-41620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41620}: @ref{137e,,run()} now always return a
@ref{137f,,TestResult} instance. Previously it returned @code{None} if
the test class or method was decorated with a skipping decorator.

@item 
bpo-45021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45021}: Fix a potential deadlock at shutdown of forked children when
using @ref{24,,concurrent.futures} module

@item 
bpo-43913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43913}: Fix bugs in cleaning up classes and modules in @ref{10c,,unittest}:


@itemize *

@item 
Functions registered with @ref{c40,,addModuleCleanup()} were not called unless the user defines @code{tearDownModule()} in their test module.

@item 
Functions registered with @ref{c41,,addClassCleanup()} were not called if @code{tearDownClass} is set to @code{None}.

@item 
Buffering in @ref{137f,,TestResult} did not work with functions registered with @code{addClassCleanup()} and @code{addModuleCleanup()}.

@item 
Errors in functions registered with @code{addClassCleanup()} and @code{addModuleCleanup()} were not handled correctly in buffered and debug modes.

@item 
Errors in @code{setUpModule()} and functions registered with @code{addModuleCleanup()} were reported in wrong order.

@item 
And several lesser bugs.
@end itemize

@item 
bpo-45030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45030}: Fix integer overflow in pickling and copying the range
iterator.

@item 
bpo-45001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45001}: Made email date parsing more robust against malformed input,
namely a whitespace-only @code{Date:} header. Patch by Wouter Bolsterlee.

@item 
bpo-45010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45010}: Remove support of special method @code{__div__} in
@ref{10d,,unittest.mock}. It is not used in Python 3.

@item 
bpo-39218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39218}: Improve accuracy of variance calculations by using @code{x*x}
instead of @code{x**2}.

@item 
bpo-43613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43613}: Improve the speed of @ref{84e,,gzip.compress()} and
@ref{1426,,gzip.decompress()} by compressing and decompressing at once in memory
instead of in a streamed fashion.

@item 
bpo-37596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37596}: Ensure that @ref{184,,set} and @ref{7f2,,frozenset} objects are
always @ref{91,,marshalled} reproducibly.

@item 
bpo-44019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44019}: A new function @code{operator.call} has been added, such that
@code{operator.call(obj, *args, **kwargs) == obj(*args, **kwargs)}.

@item 
bpo-42255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42255}: @code{webbrowser.MacOSX} is deprecated and will be removed
in Python 3.13. It is untested and undocumented and also not used by
@ref{11b,,webbrowser} itself. Patch by Donghee Na.

@item 
bpo-44955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44955}: Method @ref{1562,,stopTestRun()} is now always
called in pair with method @ref{1561,,startTestRun()} for
@ref{137f,,TestResult} objects implicitly created in
@ref{137e,,run()}. Previously it was not called for test
methods and classes decorated with a skipping decorator.

@item 
bpo-39039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39039}: tarfile.open raises @ref{1c4f,,ReadError} when a zlib error
occurs during file extraction.

@item 
bpo-44935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44935}: @ref{dc,,subprocess} on Solaris now also uses
@ref{52e,,os.posix_spawn()} for better performance.

@item 
bpo-44911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44911}: @ref{361,,IsolatedAsyncioTestCase} will no longer throw
an exception while cancelling leaked tasks. Patch by Bar Harel.

@item 
bpo-41322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41322}: Added @code{DeprecationWarning} for tests and async tests that
return a value!=None (as this may indicate an improperly written test, for
example a test written as a generator function).

@item 
bpo-44524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44524}: Make exception message more useful when subclass from typing
special form alias. Patch provided by Yurii Karabas.

@item 
bpo-38956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38956}: @ref{1bf2,,argparse.BooleanOptionalAction}'s default value is no
longer printed twice when used with
@ref{1c50,,argparse.ArgumentDefaultsHelpFormatter}.

@item 
bpo-44860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44860}: Fix the @code{posix_user} scheme in @ref{e1,,sysconfig} to not depend
on @ref{b32,,sys.platlibdir}.

@item 
bpo-44859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44859}: Improve error handling in @ref{d4,,sqlite3} and raise more
accurate exceptions.


@itemize *

@item 
@ref{179e,,MemoryError} is now raised instead of @ref{1bb6,,sqlite3.Warning} when memory is not enough for encoding a statement to UTF-8 in @code{Connection.__call__()} and @code{Cursor.execute()}.

@item 
@code{UnicodEncodeError} is now raised instead of @ref{1bb6,,sqlite3.Warning} when the statement contains surrogate characters in @code{Connection.__call__()} and @code{Cursor.execute()}.

@item 
@ref{198,,TypeError} is now raised instead of @ref{2ec,,ValueError} for non-string script argument in @code{Cursor.executescript()}.

@item 
@ref{2ec,,ValueError} is now raised for script containing the null character instead of truncating it in @code{Cursor.executescript()}.

@item 
Correctly handle exceptions raised when getting boolean value of the result of the progress handler.

@item 
Add many tests covering different corner cases.
@end itemize

@item 
bpo-44581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44581}: Upgrade bundled pip to 21.2.3 and setuptools to 57.4.0

@item 
bpo-44849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44849}: Fix the @ref{10fe,,os.set_inheritable()} function on FreeBSD 14 for
file descriptor opened with the @ref{1174,,O_PATH} flag: ignore the
@ref{b54,,EBADF} error on @code{ioctl()}, fallback on the @code{fcntl()}
implementation. Patch by Victor Stinner.

@item 
bpo-44605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44605}: The @@functools.total_ordering() decorator now works with
metaclasses.

@item 
bpo-44524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44524}: Fixed an issue wherein the @code{__name__} and @code{__qualname__}
attributes of subscribed specialforms could be @code{None}.

@item 
bpo-44839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44839}: @ref{179e,,MemoryError} raised in user-defined functions will now
produce a @code{MemoryError} in @ref{d4,,sqlite3}. @ref{a81,,OverflowError} will
now be converted to @ref{1c51,,DataError}. Previously
@ref{1c52,,OperationalError} was produced in these cases.

@item 
bpo-44822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44822}: @ref{d4,,sqlite3} user-defined functions and aggregators returning
@ref{169,,strings} with embedded NUL characters are no longer
truncated. Patch by Erlend E. Aasland.

@item 
bpo-44801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44801}: Ensure that the @ref{487,,ParamSpec} variable in Callable
can only be substituted with a parameters expression (a list of types, an
ellipsis, ParamSpec or Concatenate).

@item 
bpo-44806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44806}: Non-protocol subclasses of @ref{56b,,typing.Protocol} ignore now
the @code{__init__} method inherited from protocol base classes.

@item 
bpo-27275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27275}: @ref{1505,,collections.OrderedDict.popitem()} and
@code{collections.OrderedDict.pop()} no longer call @code{__getitem__} and
@code{__delitem__} methods of the OrderedDict subclasses.

@item 
bpo-44793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44793}: Fix checking the number of arguments when subscribe a generic
type with @code{ParamSpec} parameter.

@item 
bpo-44784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44784}: In importlib.metadata tests, override warnings behavior under
expected DeprecationWarnings (importlib_metadata 4.6.3).

@item 
bpo-44667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44667}: The @ref{700,,tokenize.tokenize()} doesn't incorrectly generate a
@code{NEWLINE} token if the source doesn't end with a new line character but
the last line is a comment, as the function is already generating a @code{NL}
token. Patch by Pablo Galindo

@item 
bpo-44771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44771}: Added @code{importlib.simple} module implementing adapters from a
low-level resources reader interface to a @code{TraversableResources}
interface. Legacy API (@code{path}, @code{contents}, ...) is now supported
entirely by the @code{.files()} API with a compatibility shim supplied for
resource loaders without that functionality. Feature parity with
@code{importlib_resources} 5.2.

@item 
bpo-44752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44752}: @code{rcompleter} does not call @ref{dca,,getattr()} on
@ref{4b3,,property} objects to avoid the side-effect of  evaluating the
corresponding method.

@item 
bpo-44747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44747}: Refactor usage of @code{sys._getframe} in @code{typing} module. Patch
provided by Yurii Karabas.

@item 
bpo-42378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42378}: Fixes the issue with log file being overwritten when
@ref{1c53,,logging.FileHandler} is used in @ref{d,,atexit} with `filemode' set
to @code{'w'}. Note this will cause the message in `atexit' not being logged
if the log stream is already closed due to shutdown of logging.

@item 
bpo-44720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44720}: @code{weakref.proxy} objects referencing non-iterators now raise
@code{TypeError} rather than dereferencing the null @code{tp_iternext} slot and
crashing.

@item 
bpo-44704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44704}: The implementation of @code{collections.abc.Set._hash()} now
matches that of @code{frozenset.__hash__()}.

@item 
bpo-44666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44666}: Fixed issue in @ref{fe1,,compileall.compile_file()} when
@code{sys.stdout} is redirected. Patch by Stefan Hölzl.

@item 
bpo-44688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44688}: @ref{886,,sqlite3.Connection.create_collation()} now accepts
non-ASCII collation names. Patch by Erlend E. Aasland.

@item 
bpo-44690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44690}: Adopt `binacii.a2b_base64''s strict mode in `base64.b64decode'.

@item 
bpo-42854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42854}: Fixed a bug in the @code{_ssl} module that was throwing
@ref{a81,,OverflowError} when using @code{_ssl._SSLSocket.write()} and
@code{_ssl._SSLSocket.read()} for a big value of the @code{len} parameter.
Patch by Pablo Galindo.

@item 
bpo-44686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44686}: Replace @code{unittest.mock._importer} with
@code{pkgutil.resolve_name}.

@item 
bpo-44353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44353}: Make @code{NewType.__call__} faster by implementing it in C. Patch
provided by Yurii Karabas.

@item 
bpo-44682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44682}: Change the @ref{aa,,pdb} `commands' directive to disallow setting
commands for an invalid breakpoint and to display an appropriate error.

@item 
bpo-44353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44353}: Refactor @code{typing.NewType} from function into callable class.
Patch provided by Yurii Karabas.

@item 
bpo-44678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44678}: Added a separate error message for discontinuous padding in
`binascii.a2b_base64' strict mode.

@item 
bpo-44524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44524}: Add missing @code{__name__} and @code{__qualname__} attributes to
@code{typing} module classes. Patch provided by Yurii Karabas.

@item 
bpo-40897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40897}: Give priority to using the current class constructor in
@ref{22f,,inspect.signature()}. Patch by Weipeng Hong.

@item 
bpo-44638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44638}: Add a reference to the zipp project and hint as to how to use
it.

@item 
bpo-44648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44648}: Fixed wrong error being thrown by @ref{17c3,,inspect.getsource()}
when examining a class in the interactive session. Instead of
@ref{198,,TypeError}, it should be @ref{2c0,,OSError} with appropriate error
message.

@item 
bpo-44608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44608}: Fix memory leak in @code{_tkinter._flatten()} if it is called
with a sequence or set, but not list or tuple.

@item 
bpo-44594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44594}: Fix an edge case of @code{ExitStack} and
@code{AsyncExitStack} exception chaining.  They will now match @code{with}
block behavior when @code{__context__} is explicitly set to @code{None} when the
exception is in flight.

@item 
bpo-42799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42799}: In @ref{60,,fnmatch}, the cache size for compiled regex patterns
(@ref{be2,,functools.lru_cache()}) was bumped up from 256 to 32768, affecting
functions: @ref{1c54,,fnmatch.fnmatch()}, @ref{1c55,,fnmatch.fnmatchcase()},
@ref{1c56,,fnmatch.filter()}.

@item 
bpo-41928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41928}: Update @ref{c4e,,shutil.copyfile()} to raise
@ref{264,,FileNotFoundError} instead of confusing @ref{1264,,IsADirectoryError}
when a path ending with a @code{os.path.sep} does not exist;
@ref{c4f,,shutil.copy()} and @ref{c50,,shutil.copy2()} are also affected.

@item 
bpo-44569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44569}: Added the @code{StackSummary.format_frame()} function in
@ref{104,,traceback}. This allows users to customize the way individual lines
are formatted in tracebacks without re-implementing logic to handle
recursive tracebacks.

@item 
bpo-44566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44566}: handle StopIteration subclass raised from
@@contextlib.contextmanager generator

@item 
bpo-44558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44558}: Make the implementation consistency of
@ref{ad8,,indexOf()} between C and Python versions. Patch by Donghee
Na.

@item 
bpo-41249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41249}: Fixes @code{TypedDict} to work with @code{typing.get_type_hints()}
and postponed evaluation of annotations across modules.

@item 
bpo-44554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44554}: Refactor argument processing in @code{pdb.main()} to simplify
detection of errors in input loading and clarify behavior around module or
script invocation.

@item 
bpo-34798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34798}: Break up paragraph about @ref{1181,,pprint.PrettyPrinter}
construction parameters to make it easier to read.

@item 
bpo-44539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44539}: Added support for recognizing JPEG files without JFIF or Exif
markers.

@item 
bpo-44461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44461}: Fix bug with @ref{aa,,pdb}'s handling of import error due to a
package which does not have a @code{__main__} module

@item 
bpo-43625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43625}: Fix a bug in the detection of CSV file headers by
@ref{1c57,,csv.Sniffer.has_header()} and improve documentation of same.

@item 
bpo-44516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44516}: Update vendored pip to 21.1.3

@item 
bpo-42892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42892}: Fixed an exception thrown while parsing a malformed multipart
email by @ref{580,,email.message.EmailMessage}.

@item 
bpo-44468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44468}: @ref{8c0,,typing.get_type_hints()} now finds annotations in classes
and base classes with unexpected @code{__module__}. Previously, it skipped
those MRO elements.

@item 
bpo-44491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44491}: Allow clearing the @ref{d4,,sqlite3} authorizer callback by
passing @ref{885,,None} to @ref{5a9,,set_authorizer()}. Patch
by Erlend E. Aasland.

@item 
bpo-43977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43977}: Set the proper @ref{1c58,,Py_TPFLAGS_MAPPING} and
@ref{1c59,,Py_TPFLAGS_SEQUENCE} flags for subclasses created before a
parent has been registered as a @ref{ac7,,collections.abc.Mapping} or
@ref{13dc,,collections.abc.Sequence}.

@item 
bpo-44482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44482}: Fix very unlikely resource leak in @ref{68,,glob} in alternate
Python implementations.

@item 
bpo-44466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44466}: The @ref{5c,,faulthandler} module now detects if a fatal error
occurs during a garbage collector collection. Patch by Victor Stinner.

@item 
bpo-44471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44471}: A @ref{198,,TypeError} is now raised instead of an
@ref{5f0,,AttributeError} in @ref{7ee,,contextlib.ExitStack.enter_context()} and
@ref{7ef,,contextlib.AsyncExitStack.enter_async_context()} for objects which do
not support the @ref{1e1,,context manager} or @ref{7f0,,asynchronous context manager} protocols correspondingly.

@item 
bpo-44404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44404}: @ref{f6,,tkinter}'s @code{after()} method now supports callables
without the @code{__name__} attribute.

@item 
bpo-41546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41546}: Make @ref{b3,,pprint} (like the builtin @code{print}) not attempt to
write to @code{stdout} when it is @code{None}.

@item 
bpo-44458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44458}: @code{BUFFER_BLOCK_SIZE} is now declared static, to avoid linking
collisions when bz2, lmza or zlib are statically linked.

@item 
bpo-44464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44464}: Remove exception for flake8 in deprecated importlib.metadata
interfaces. Sync with importlib_metadata 4.6.

@item 
bpo-44446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44446}: Take into account that @code{lineno} might be @code{None} in
@ref{1084,,traceback.FrameSummary}.

@item 
bpo-44439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44439}: Fix in @code{bz2.BZ2File.write()} / @code{lzma.LZMAFile.write()}
methods, when the input data is an object that supports the buffer
protocol, the file length may be wrong.

@item 
bpo-44434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44434}: _thread.start_new_thread() no longer calls
PyThread_exit_thread() explicitly at the thread exit, the call was
redundant. On Linux with the glibc, pthread_exit() aborts the whole
process if dlopen() fails to open libgcc_s.so file (ex: EMFILE error).
Patch by Victor Stinner.

@item 
bpo-42972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42972}: The _thread.RLock type now fully implement the GC protocol: add
a traverse function and the @ref{981,,Py_TPFLAGS_HAVE_GC} flag. Patch by
Victor Stinner.

@item 
bpo-44422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44422}: The @ref{1c5a,,threading.enumerate()} function now uses a reentrant
lock to prevent a hang on reentrant call. Patch by Victor Stinner.

@item 
bpo-38291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38291}: Importing typing.io or typing.re now prints a
@code{DeprecationWarning}.

@item 
bpo-37880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37880}: argparse actions store_const and append_const each receive a
default value of @code{None} when the @code{const} kwarg is not provided.
Previously, this raised a @ref{198,,TypeError}.

@item 
bpo-44389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44389}: Fix deprecation of @ref{1c5b,,ssl.OP_NO_TLSv1_3}

@item 
bpo-27827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27827}: @code{pathlib.PureWindowsPath.is_reserved()} now identifies a
greater range of reserved filenames, including those with trailing spaces
or colons.

@item 
bpo-44395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44395}: Fix @code{as_string()} to pass unixfrom
properly. Patch by Donghee Na.

@item 
bpo-34266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34266}: Handle exceptions from parsing the arg of @ref{aa,,pdb}'s
run/restart command.

@item 
bpo-44362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44362}: Improve @ref{d5,,ssl} module's deprecation messages, error
reporting, and documentation for deprecations.

@item 
bpo-44342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44342}: [Enum] Change pickling from by-value to by-name.

@item 
bpo-44356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44356}: [Enum] Allow multiple data-type mixins if they are all the
same.

@item 
bpo-44351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44351}: Restore back @code{parse_makefile()} in @code{distutils.sysconfig}
because it behaves differently than the similar implementation in
@ref{e1,,sysconfig}.

@item 
bpo-35800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35800}: @code{smtpd.MailmanProxy} is now removed as it is unusable
without an external module, @code{mailman}. Patch by Donghee Na.

@item 
bpo-44357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44357}: Added a function that returns cube root of the given number
@ref{871,,math.cbrt()}

@item 
bpo-44339@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44339}: Change @code{math.pow(±0.0, -math.inf)} to return @code{inf} instead
of raising @code{ValueError}. This brings the special-case handling of
@code{math.pow} into compliance with the IEEE 754 standard.

@item 
bpo-44242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44242}: Remove missing flag check from Enum creation and move into a
@code{verify} decorator.

@item 
bpo-44246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44246}: In @code{importlib.metadata}, restore compatibility in the result
from @code{Distribution.entry_points} (@code{EntryPoints}) to honor expectations
in older implementations and issuing deprecation warnings for these cases:
A. @code{EntryPoints} objects are once again mutable, allowing   for
@code{sort()} and other list-based mutation operations.   Avoid deprecation
warnings by casting to a   mutable sequence (e.g.
@code{list(dist.entry_points).sort()}). B. @code{EntryPoints} results once again
allow   for access by index. To avoid deprecation warnings,   cast the
result to a Sequence first   (e.g. @code{tuple(dist.entry_points)[0]}).

@item 
bpo-44246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44246}: In importlib.metadata.entry_points, de-duplication of
distributions no longer requires loading the full metadata for
PathDistribution objects, improving entry point loading performance by
~10x.

@item 
bpo-43858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43858}: Added a function that returns a copy of a dict of logging
levels: @ref{869,,logging.getLevelNamesMapping()}

@item 
bpo-44260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44260}: The @ref{1c5c,,random.Random} constructor no longer reads system
entropy without need.

@item 
bpo-44254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44254}: On Mac, give turtledemo button text a color that works on both
light or dark background.  Programmers cannot control the latter.

@item 
bpo-44258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44258}: Support PEP 515 for Fraction's initialization from string.

@item 
bpo-44235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44235}: Remove deprecated functions in the @ref{67,,gettext}. Patch by
Donghee Na.

@item 
bpo-38693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38693}: Prefer f-strings to @code{.format} in importlib.resources.

@item 
bpo-33693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33693}: Importlib.metadata now prefers f-strings to .format.

@item 
bpo-44241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44241}: Incorporate minor tweaks from importlib_metadata 4.1:
SimplePath protocol, support for Metadata 2.2.

@item 
bpo-43216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43216}: Remove the @code{@@asyncio.coroutine} @ref{93a,,decorator} enabling
legacy generator-based coroutines to be compatible with async/await code;
remove @code{asyncio.coroutines.CoroWrapper} used for wrapping legacy
coroutine objects in the debug mode. The decorator has been deprecated
since Python 3.8 and the removal was initially scheduled for Python 3.10.
Patch by Illia Volochii.

@item 
bpo-44210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44210}: Make importlib.metadata._meta.PackageMetadata public.

@item 
bpo-43643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43643}: Declare readers.MultiplexedPath.name as a property per the
spec.

@item 
bpo-27334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27334}: The @ref{d4,,sqlite3} context manager now performs a rollback
(thus releasing the database lock) if commit failed.  Patch by Luca Citi
and Erlend E. Aasland.

@item 
bpo-4928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4928}: Documented existing behavior on POSIX: NamedTemporaryFiles are
not deleted when creating process is killed with SIGKILL

@item 
bpo-44154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44154}: Optimize @ref{213,,fractions.Fraction} pickling for large
components.

@item 
bpo-33433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33433}: For IPv4 mapped IPv6 addresses (
@geindex RFC; RFC 4291
RFC 4291@footnote{https://datatracker.ietf.org/doc/html/rfc4291.html} Section 2.5.5.2),
the @ref{19c4,,ipaddress.IPv6Address.is_private} check is deferred to the
mapped IPv4 address. This solves a bug where public mapped IPv4 addresses
were considered private by the IPv6 check.

@item 
bpo-44150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44150}: Add optional `weights' argument to statistics.fmean().

@item 
bpo-44142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44142}: @ref{ae2,,ast.unparse()} will now drop the redundant parentheses
when tuples used as assignment targets (e.g in for loops).

@item 
bpo-44145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44145}: @ref{6e,,hmac} computations were not releasing the GIL while
calling the OpenSSL @code{HMAC_Update} C API (a new feature in 3.9).  This
unintentionally prevented parallel computation as other @ref{6c,,hashlib}
algorithms support.

@item 
bpo-44095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44095}: @ref{8d8,,zipfile.Path} now supports @ref{8d5,,zipfile.Path.stem},
@ref{8d7,,zipfile.Path.suffixes}, and @ref{8d6,,zipfile.Path.suffix} attributes.

@item 
bpo-44077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44077}: It's now possible to receive the type of service (ToS), a.k.a.
differentiated services (DS), a.k.a. differentiated services code point
(DSCP) and explicit congestion notification (ECN) IP header fields with
@code{socket.IP_RECVTOS}.

@item 
bpo-37788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37788}: Fix a reference leak when a Thread object is never joined.

@item 
bpo-38908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38908}: Subclasses of @code{typing.Protocol} which only have data
variables declared will now raise a @code{TypeError} when checked with
@code{isinstance} unless they are decorated with @code{runtime_checkable()}.
Previously, these checks passed silently. Patch provided by Yurii Karabas.

@item 
bpo-44098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44098}: @code{typing.ParamSpec} will no longer be found in the
@code{__parameters__} of most @ref{10a,,typing} generics except in valid use
locations specified by 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/}. This prevents incorrect usage like
@code{typing.List[P][int]}. This change means incorrect usage which may have
passed silently in 3.10 beta 1 and earlier will now error.

@item 
bpo-44089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44089}: Allow subclassing @code{csv.Error} in 3.10 (it was allowed in 3.9
and earlier but was disallowed in early versions of 3.10).

@item 
bpo-44081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44081}: @ref{ae2,,ast.unparse()} now doesn't use redundant spaces to
separate @code{lambda} and the @code{:} if there are no parameters.

@item 
bpo-44061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44061}: Fix regression in previous release when calling
@ref{f47,,pkgutil.iter_modules()} with a list of @ref{266,,pathlib.Path} objects

@item 
bpo-44059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44059}: Register the SerenityOS Browser in the @ref{11b,,webbrowser}
module.

@item 
bpo-36515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36515}: The @ref{6c,,hashlib} module no longer does unaligned memory
accesses when compiled for ARM platforms.

@item 
bpo-40465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40465}: Remove random module features deprecated in Python 3.9.

@item 
bpo-44018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44018}: random.seed() no longer mutates bytearray inputs.

@item 
bpo-38352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38352}: Add @code{IO}, @code{BinaryIO}, @code{TextIO}, @code{Match}, and
@code{Pattern} to @code{typing.__all__}. Patch by Jelle Zijlstra.

@item 
bpo-44002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44002}: @ref{110,,urllib.parse} now uses @code{functool.lru_cache()} for its
internal URL splitting and quoting caches instead of rolling its own like
its the '90s.

The undocumented internal @ref{110,,urllib.parse} @code{Quoted} class API is now
deprecated, for removal in 3.14.

@item 
bpo-43972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43972}: When @ref{d38,,http.server.SimpleHTTPRequestHandler} sends a
@code{301 (Moved Permanently)} for a directory path not ending with @code{/},
add a @code{Content-Length: 0} header. This improves the behavior for certain
clients.

@item 
bpo-28528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28528}: Fix a bug in @ref{aa,,pdb} where @code{checkline()} raises
@ref{5f0,,AttributeError} if it is called after @code{reset()}.

@item 
bpo-43853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43853}: Improved string handling for @ref{d4,,sqlite3} user-defined
functions and aggregates:


@itemize *

@item 
It is now possible to pass strings with embedded null characters to UDFs

@item 
Conversion failures now correctly raise @ref{179e,,MemoryError}
@end itemize

Patch by Erlend E. Aasland.

@item 
bpo-43666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43666}: AIX: @code{Lib/_aix_support.get_platform()} may fail in an AIX
WPAR. The fileset bos.rte appears to have a builddate in both LPAR and
WPAR so this fileset is queried rather than bos.mp64. To prevent a similar
situation (no builddate in ODM) a value (9988) sufficient for completing a
build is provided. Patch by M Felt.

@item 
bpo-43650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43650}: Fix @ref{179e,,MemoryError} in @ref{696,,shutil.unpack_archive()} which
fails inside @code{shutil._unpack_zipfile()} on large files. Patch by Igor
Bolshakov.

@item 
bpo-43612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43612}: @ref{84f,,zlib.compress()} now accepts a wbits parameter which
allows users to compress data as a raw deflate block without zlib headers
and trailers in one go. Previously this required instantiating a
@code{zlib.compressobj}. It also provides a faster alternative to
@code{gzip.compress} when wbits=31 is used.

@item 
bpo-43392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43392}: @code{importlib._bootstrap._find_and_load()} now implements a
two-step check to avoid locking when modules have been already imported
and are ready. This improves performance of repeated calls to
@ref{73c,,importlib.import_module()} and @ref{1279,,importlib.__import__()}.

@item 
bpo-43318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43318}: Fix a bug where @ref{aa,,pdb} does not always echo cleared
breakpoints.

@item 
bpo-43234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43234}: Prohibit passing
non-@ref{949,,concurrent.futures.ThreadPoolExecutor} executors to
@code{loop.set_default_executor()} following a deprecation in Python 3.8.
Patch by Illia Volochii.

@item 
bpo-43232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43232}: Prohibit previously deprecated potentially disruptive
operations on @code{asyncio.trsock.TransportSocket}. Patch by Illia
Volochii.

@item 
bpo-30077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30077}: Added support for Apple's aifc/sowt pseudo-compression

@item 
bpo-42971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42971}: Add definition of @code{errno.EQFULL} for platforms that define
this constant (such as macOS).

@item 
bpo-43086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43086}: Added a new optional @code{strict_mode} parameter to
`binascii.a2b_base64'. When @code{scrict_mode} is set to @code{True},
the `a2b_base64' function will accept only valid base64 content. More
details about what "valid base64 content" is, can be found in the
function's documentation.

@item 
bpo-43024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43024}: Improve the help signature of
@ref{a4f,,traceback.print_exception()}, @ref{a4d,,traceback.format_exception()} and
@ref{a4e,,traceback.format_exception_only()}.

@item 
bpo-33809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33809}: Add the @ref{8b3,,traceback.TracebackException.print()} method which
prints the formatted exception information.

@item 
bpo-42862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42862}: @ref{d4,,sqlite3} now utilizes @ref{be2,,functools.lru_cache()} to
implement the connection statement cache. As a small optimisation, the
default statement cache size has been increased from 100 to 128. Patch by
Erlend E. Aasland.

@item 
bpo-41818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41818}: Soumendra Ganguly: add termios.tcgetwinsize(),
termios.tcsetwinsize().

@item 
bpo-40497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40497}: @ref{11c4,,subprocess.check_output()} now raises @ref{2ec,,ValueError}
when the invalid keyword argument `check' is passed by user code.
Previously such use would fail later with a @ref{198,,TypeError}. Patch by
Rémi Lapeyre.

@item 
bpo-37449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37449}: @code{ensurepip} now uses @code{importlib.resources.files()}
traversable APIs

@item 
bpo-40956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40956}: Use Argument Clinic in @ref{d4,,sqlite3}.  Patches by Erlend E.
Aasland.

@item 
bpo-41730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41730}: @code{DeprecationWarning} is now raised when importing
@code{tkinter.tix}, which has been deprecated in documentation since
Python 3.6.

@item 
bpo-20684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20684}: Remove unused @code{_signature_get_bound_param} function from
@ref{82,,inspect} - by Anthony Sottile.

@item 
bpo-41402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41402}: Fix @ref{1c5d,,email.message.EmailMessage.set_content()} when called
with binary data and @code{7bit} content transfer encoding.

@item 
bpo-32695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32695}: The `compresslevel' and `preset' keyword arguments of
@ref{1077,,tarfile.open()} are now both documented and tested.

@item 
bpo-41137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41137}: Use utf-8 encoding while reading .pdbrc files. Patch by
Srinivas Reddy Thatiparthy

@item 
bpo-24391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24391}: Improved reprs of @ref{f3,,threading} synchronization objects:
@ref{136e,,Semaphore}, @ref{136f,,BoundedSemaphore},
@ref{1370,,Event} and @ref{13fc,,Barrier}.

@item 
bpo-5846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5846}: Deprecated the following @ref{10c,,unittest} functions, scheduled
for removal in Python 3.13:


@itemize *

@item 
@code{findTestCases()}

@item 
@code{makeSuite()}

@item 
@code{getTestCaseNames()}
@end itemize

Use @ref{593,,TestLoader} methods instead:


@itemize *

@item 
@ref{594,,unittest.TestLoader.loadTestsFromModule()}

@item 
@ref{595,,unittest.TestLoader.loadTestsFromTestCase()}

@item 
@ref{596,,unittest.TestLoader.getTestCaseNames()}
@end itemize

Patch by Erlend E. Aasland.

@item 
bpo-40563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40563}: Support pathlike objects on dbm/shelve. Patch by Hakan Çelik
and Henry-Joseph Audéoud.

@item 
bpo-34990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34990}: Fixed a Y2k38 bug in the compileall module where it would fail
to compile files with a modification time after the year 2038.

@item 
bpo-39549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39549}: Whereas the code for reprlib.Repr had previously used a
hardcoded string value of '...', this PR updates it to use of a
“fillvalue” attribute, whose value defaults to '...' and can be reset in
either individual reprlib.Repr instances or in subclasses thereof.

@item 
bpo-37022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37022}: @ref{aa,,pdb} now displays exceptions from @code{repr()} with its
@code{p} and @code{pp} commands.

@item 
bpo-38840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38840}: Fix @code{test___all__} on platforms lacking a shared memory
implementation.

@item 
bpo-39359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39359}: Add one missing check that the password is a bytes object for
an encrypted zipfile.

@item 
bpo-38741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38741}: @ref{26,,configparser}: using ']' inside a section header will no
longer cut the section name short at the ']'

@item 
bpo-38415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38415}: Added missing behavior to
@ref{d1f,,contextlib.asynccontextmanager()} to match
@ref{141b,,contextlib.contextmanager()} so decorated functions can themselves be
decorators.

@item 
bpo-30256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30256}: Pass multiprocessing BaseProxy argument @code{manager_owned}
through AutoProxy.

@item 
bpo-27513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27513}: @ref{4f3,,email.utils.getaddresses()} now accepts
@ref{1c5e,,email.header.Header} objects along with string values. Patch by
Zackery Spytz.

@item 
bpo-16379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16379}: Add SQLite error code and name to @ref{d4,,sqlite3} exceptions.
Patch by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland.

@item 
bpo-26228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26228}: pty.spawn no longer hangs on FreeBSD, macOS, and Solaris.

@item 
bpo-33349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33349}: lib2to3 now recognizes async generators everywhere.

@item 
bpo-29298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29298}: Fix @code{TypeError} when required subparsers without @code{dest} do
not receive arguments. Patch by Anthony Sottile.
@end itemize

@node ドキュメント<36>,テスト<35>,ライブラリ<116>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id500}@anchor{1c5f}
@subsubsection ドキュメント



@itemize -

@item 
bpo-45216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45216}: Remove extra documentation listing methods in @code{difflib}. It
was rendering twice in pydoc and was outdated in some places.

@item 
bpo-45024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45024}: @ref{1f,,collections.abc} documentation has been expanded to
explicitly cover how instance and subclass checks work, with additional
doctest examples and an exhaustive list of ABCs which test membership
purely by presence of the right @ref{1c60,,special method}s. Patch by Raymond
Hettinger.

@item 
bpo-44957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44957}: Promote PEP 604 union syntax by using it where possible. Also,
mention @code{X | Y} more prominently in section about @code{Union} and mention
@code{X | None} at all in section about @code{Optional}.

@item 
bpo-16580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16580}: Added code equivalents for the @ref{1c32,,int.to_bytes()} and
@ref{1be9,,int.from_bytes()} methods, as well as tests ensuring that these code
equivalents are valid.

@item 
bpo-44903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44903}: Removed the @code{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@footnote{https://wiki.python.org/moin/GuiProgramming}.

@item 
bpo-33479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33479}: Tkinter documentation has been greatly expanded with new
"Architecture" and "Threading model" sections.

@item 
bpo-36700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36700}: @ref{f,,base64} RFC references were updated to point to
@geindex RFC; RFC 4648
RFC 4648@footnote{https://datatracker.ietf.org/doc/html/rfc4648.html}; a section was added to point users to the new "security
considerations" section of the RFC.

@item 
bpo-44740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44740}: Replaced occurrences of uppercase "Web" and "Internet" with
lowercase versions per the 2016 revised Associated Press Style Book.

@item 
bpo-44693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44693}: Update the definition of __future__ in the glossary by
replacing the confusing word "pseudo-module" with a more accurate
description.

@item 
bpo-35183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35183}: Add typical examples to os.path.splitext docs

@item 
bpo-30511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30511}: Clarify that @ref{6da,,shutil.make_archive()} is not thread-safe due
to reliance on changing the current working directory.

@item 
bpo-44561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44561}: Update of three expired hyperlinks in
Doc/distributing/index.rst: "Project structure", "Building and packaging
the project", and "Uploading the project to the Python Packaging Index".

@item 
bpo-44651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44651}: Delete entry "coercion" in Doc/glossary.rst for its outdated
definition.

@item 
bpo-42958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42958}: Updated the docstring and docs of @ref{19dd,,filecmp.cmp()} to be
more accurate and less confusing especially in respect to `shallow' arg.

@item 
bpo-44631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44631}: Refactored the @code{repr()} code of the @code{_Environ} (os module).

@item 
bpo-44613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44613}: importlib.metadata is no longer provisional.

@item 
bpo-44558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44558}: Match the docstring and python implementation of
@ref{ad9,,countOf()} to the behavior of its c implementation.

@item 
bpo-44544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44544}: List all kwargs for @ref{16e0,,textwrap.wrap()},
@ref{16df,,textwrap.fill()}, and @ref{11d2,,textwrap.shorten()}. Now, there are nav
links to attributes of @code{TextWrap}, which makes navigation much
easier while minimizing duplication in the documentation.

@item 
bpo-38062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38062}: Clarify that atexit uses equality comparisons internally.

@item 
bpo-40620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40620}: Convert examples in tutorial controlflow.rst section 4.3 to be
interpreter-demo style.

@item 
bpo-43066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43066}: Added a warning to @ref{137,,zipfile} docs: filename arg with a
leading slash may cause archive to be un-openable on Windows systems.

@item 
bpo-39452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39452}: Rewrote @code{Doc/library/__main__.rst}. Broadened scope of the
document to explicitly discuss and differentiate between @code{__main__.py}
in packages versus the @code{__name__ == '__main__'} expression (and the
idioms that surround it).

@item 
bpo-13814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13814}: In the Design FAQ, answer "Why don't generators support the
with statement?"

@item 
bpo-27752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27752}: Documentation of csv.Dialect is more descriptive.

@item 
bpo-44453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44453}: Fix documentation for the return type of
@ref{1545,,sysconfig.get_path()}.

@item 
bpo-44392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44392}: Added a new section in the C API documentation for types used
in type hinting.  Documented @code{Py_GenericAlias} and
@code{Py_GenericAliasType}.

@item 
bpo-38291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38291}: Mark @code{typing.io} and @code{typing.re} as deprecated since Python
3.8 in the documentation. They were never properly supported by type
checkers.

@item 
bpo-44322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44322}: Document that SyntaxError args have a details tuple and that
details are adjusted for errors in f-string field replacement expressions.

@item 
bpo-42392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42392}: Document the deprecation and removal of the @code{loop} parameter
for many functions and classes in @ref{b,,asyncio}.

@item 
bpo-44195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44195}: Corrected references to @code{TraversableResources} in docs. There
is no @code{TraversableReader}.

@item 
bpo-41963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41963}: Document that @code{ConfigParser} strips off comments when reading
configuration files.

@item 
bpo-44072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44072}: Correct where in the numeric ABC hierarchy @code{**} support is
added, i.e., in numbers.Complex, not numbers.Integral.

@item 
bpo-43558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43558}: Add the remark to @ref{33,,dataclasses} documentation that the
@code{__init__()} of any base class has to be called in
@code{__post_init__()}, along with a code example.

@item 
bpo-44025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44025}: Clarify when '_' in match statements is a keyword, and when
not.

@item 
bpo-41706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41706}: Fix docs about how methods like @code{__add__} are invoked when
evaluating operator expressions.

@item 
bpo-41621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41621}: Document that @ref{13d4,,collections.defaultdict} parameter
@code{default_factory} defaults to @code{None} and is positional-only.

@item 
bpo-41576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41576}: document BaseException in favor of bare except

@item 
bpo-21760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21760}: The description for __file__ fixed. Patch by Furkan Onder

@item 
bpo-39498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39498}: Add a "Security Considerations" index which links to standard
library modules that have explicitly documented security considerations.

@item 
bpo-33479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33479}: Remove the unqualified claim that tkinter is threadsafe. It has
not been true for several years and likely never was. An explanation of
what is true may be added later, after more discussion, and possibly after
patching _tkinter.c,
@end itemize

@node テスト<35>,ビルド<42>,ドキュメント<36>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id501}@anchor{1c61}
@subsubsection テスト



@itemize -

@item 
bpo-40173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40173}: Fix @ref{1c62,,test.support.import_helper.import_fresh_module()}.

@item 
bpo-45280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45280}: Add a test case for empty @ref{331,,typing.NamedTuple}.

@item 
bpo-45269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45269}: Cover case when invalid @code{markers} type is supplied to
@code{c_make_encoder}.

@item 
bpo-45128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45128}: Fix @code{test_multiprocessing_fork} failure due to
@code{test_logging} and @code{sys.modules} manipulation.

@item 
bpo-45209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45209}: Fix @code{UserWarning: resource_tracker} warning in
@code{_test_multiprocessing._TestSharedMemory.test_shared_memory_cleaned_after_process_termination}

@item 
bpo-45185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45185}: Enables @code{TestEnumerations} test cases in @code{test_ssl} suite.

@item 
bpo-45195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45195}: Fix test_readline.test_nonascii(): sometimes, the newline
character is not written at the end, so don't expect it in the output.
Patch by Victor Stinner.

@item 
bpo-45156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45156}: Fixes infinite loop on @ref{d9a,,unittest.mock.seal()} of mocks
created by @code{create_autospec()}.

@item 
bpo-45125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45125}: Improves pickling tests and docs of @code{SharedMemory} and
@code{SharableList} objects.

@item 
bpo-44860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44860}: Update @code{test_sysconfig.test_user_similar()} for the
posix_user scheme: @code{platlib} doesn't use @ref{b32,,sys.platlibdir}. Patch
by Victor Stinner.

@item 
bpo-45052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45052}: @code{WithProcessesTestSharedMemory.test_shared_memory_basics}
test was ignored, because @code{self.assertEqual(sms.size, sms2.size)} line
was failing. It is now removed and test is unskipped.

The main motivation for this line to be removed from the test is that the
@code{size} of @code{SharedMemory} is not ever guaranteed to be the same. It is
decided by the platform.

@item 
bpo-44895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44895}: libregrtest now clears the type cache later to reduce the risk
of false alarm when checking for reference leaks. Previously, the type
cache was cleared too early and libregrtest raised a false alarm about
reference leaks under very specific conditions. Patch by Irit Katriel and
Victor Stinner.

@item 
bpo-45042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45042}: Fixes that test classes decorated with
@code{@@hashlib_helper.requires_hashdigest} were skipped all the time.

@item 
bpo-25130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25130}: Add calls of @ref{1b3,,gc.collect()} in tests to support PyPy.

@item 
bpo-45011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45011}: Made tests relying on the @code{_asyncio} C extension module
optional to allow running on alternative Python implementations. Patch by
Serhiy Storchaka.

@item 
bpo-44949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44949}: Fix auto history tests of test_readline: sometimes, the newline
character is not written at the end, so don't expect it in the output.

@item 
bpo-44891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44891}: Tests were added to clarify @ref{163c,,id()} is preserved when @code{obj
* 1} is used on @ref{169,,str} and @ref{192,,bytes} objects. Patch by Nikita
Sobolev.

@item 
bpo-44852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44852}: Add ability to wholesale silence DeprecationWarnings while
running the regression test suite.

@item 
bpo-40928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40928}: Notify users running test_decimal regression tests on macOS of
potential harmless "malloc can't allocate region" messages spewed by
test_decimal.

@item 
bpo-44734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44734}: Fixed floating-point precision issue in turtle tests.

@item 
bpo-44708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44708}: Regression tests, when run with -w, are now re-running only the
affected test methods instead of re-running the entire test file.

@item 
bpo-42095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42095}: Added interop tests for Apple plists: generate plist files with
Python plistlib and parse with Apple plutil; and the other way round.

@item 
bpo-44647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44647}: Added a permanent Unicode-valued environment variable to
regression tests to ensure they handle this use case in the future. If
your test environment breaks because of that, report a bug to us, and
temporarily set PYTHONREGRTEST_UNICODE_GUARD=0 in your test environment.

@item 
bpo-44515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44515}: Adjust recently added contextlib tests to avoid assuming the
use of a refcounted GC

@item 
bpo-44287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44287}: Fix asyncio test_popen() of test_windows_utils by using a
longer timeout. Use military grade battle-tested
@ref{1c63,,test.support.SHORT_TIMEOUT} timeout rather than a hardcoded timeout
of 10 seconds: it's 30 seconds by default, but it is made longer on slow
buildbots. Patch by Victor Stinner.

@item 
bpo-44451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44451}: Reset @code{DeprecationWarning} filters in
@code{test.test_importlib.test_metadata_api.APITests.test_entry_points_by_index}
to avoid @code{StopIteration} error if @code{DeprecationWarnings} are ignored.

@item 
bpo-44363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44363}: Account for address sanitizer in test_capi. test_capi now
passes when run GCC address sanitizer.

@item 
bpo-44364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44364}: Add non integral tests for @ref{bf9,,math.sqrt()} function.

@item 
bpo-43921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43921}: Fix test_ssl.test_wrong_cert_tls13(): use
@code{suppress_ragged_eofs=False}, since @code{read()} can raise
@ref{1ab8,,ssl.SSLEOFError} on Windows. Patch by Victor Stinner.

@item 
bpo-43921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43921}: Fix test_pha_required_nocert() of test_ssl: catch two more EOF
cases (when the @code{recv()} method returns an empty string). Patch by
Victor Stinner.

@item 
bpo-44131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44131}: Add test_frozenmain to test_embed to test the
@code{Py_FrozenMain()} C function. Patch by Victor Stinner.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Ignore error string case in test_file_not_exists().

@item 
bpo-42083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42083}: Add test to check that @code{PyStructSequence_NewType} accepts a
@code{PyStructSequence_Desc} with @code{doc} field set to @code{NULL}.

@item 
bpo-35753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35753}: Fix crash in doctest when doctest parses modules that include
unwrappable functions by skipping those functions.

@item 
bpo-30256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30256}: Add test for nested queues when using @code{multiprocessing}
shared objects @code{AutoProxy[Queue]} inside @code{ListProxy} and @code{DictProxy}
@end itemize

@node ビルド<42>,Windows<37>,テスト<35>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id502}@anchor{1c64}
@subsubsection ビルド



@itemize -

@item 
bpo-45220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45220}: Avoid building with the Windows 11 SDK previews automatically.
This may be overridden by setting the @code{DefaultWindowsSDKVersion}
environment variable before building.

@item 
bpo-45020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45020}: Freeze stdlib modules that are imported during startup.  This
provides significant performance improvements to startup.  If necessary,
use the previously added "-X frozen_modules=off" commandline option to
force importing the source modules.

@item 
bpo-45188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45188}: Windows builds now regenerate frozen modules as the first part
of the build. Previously the regeneration was later in the build, which
would require it to be restarted if any modules had changed.

@item 
bpo-45163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45163}: Fixes Haiku platform build.

@item 
bpo-45067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45067}: The ncurses function extended_color_content was introduced in
2017

(@indicateurl{https://invisible-island.net/ncurses/NEWS.html#index-t20170401}).  The

ncurses-devel package in CentOS 7 had a older version ncurses resulted in
compilation error.  For compiling ncurses with extended color support, we
verify the version of the ncurses library >= 20170401.

@item 
bpo-45019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45019}: Generate lines in relevant files for frozen modules.  Up until
now each of the files had to be edited manually.  This change makes it
easier to add to and modify the frozen modules.

@item 
bpo-44340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44340}: Add support for building with clang thin lto via
--with-lto=thin/full. Patch by Donghee Na and Brett Holman.

@item 
bpo-44535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44535}: Enable building using a Visual Studio 2022 install on Windows.

@item 
bpo-43298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43298}: Improved error message when building without a Windows SDK
installed.

@item 
bpo-44381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44381}: The Windows build now accepts 
@geindex EnableControlFlowGuard
@geindex 環境変数; EnableControlFlowGuard
@code{EnableControlFlowGuard}
set to @code{guard} to enable CFG.

@item 
bpo-41282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41282}: Fix broken @code{make install} that caused standard library
extension modules to be unnecessarily and incorrectly rebuilt during the
install phase of cpython.
@end itemize

@node Windows<37>,macOS<27>,ビルド<42>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id503}@anchor{1c65}
@subsubsection Windows



@itemize -

@item 
bpo-45375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45375}: Fixes an assertion failure due to searching for the standard
library in unnormalised paths.

@item 
bpo-45022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45022}: Update Windows release to include libffi 3.4.2

@item 
bpo-45007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45007}: Update to OpenSSL 1.1.1l in Windows build

@item 
bpo-44848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44848}: Upgrade Windows installer to use SQLite 3.36.0.

@item 
bpo-44572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44572}: Avoid consuming standard input in the @ref{af,,platform} module

@item 
bpo-44582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44582}: Accelerate speed of @ref{93,,mimetypes} initialization using a
native implementation of the registry scan.

@item 
bpo-41299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41299}: Fix 16 milliseconds jitter when using timeouts in
@ref{f3,,threading}, such as with @ref{8a7,,threading.Lock.acquire()} or
@ref{1c66,,threading.Condition.wait()}.

@item 
bpo-42686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42686}: Build @ref{d4,,sqlite3} with math functions enabled. Patch by
Erlend E. Aasland.

@item 
bpo-40263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40263}: This is a follow-on bug from
@indicateurl{https://bugs.python.org/issue26903}. Once that is applied we run into an
off-by-one assertion problem. The assert was not correct.
@end itemize

@node macOS<27>,IDLE<19>,Windows<37>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id504}@anchor{1c67}
@subsubsection macOS



@itemize -

@item 
bpo-45007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45007}: Update macOS installer builds to use OpenSSL 1.1.1l.

@item 
bpo-34602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34602}: When building CPython on macOS with @code{./configure
--with-undefined-behavior-sanitizer --with-pydebug}, the stack size is
now quadrupled to allow for the entire test suite to pass.

@item 
bpo-44848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44848}: Update macOS installer to use SQLite 3.36.0.

@item 
bpo-44689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44689}: @ref{f45,,ctypes.util.find_library()} now works correctly on macOS
11 Big Sur even if Python is built on an older version of macOS.
Previously, when built on older macOS systems, @code{find_library} was not
able to find  macOS system libraries when running on Big Sur due to
changes in  how system libraries are stored.

@item 
bpo-41972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41972}: The framework build's user header path in sysconfig is changed
to add a 'pythonX.Y' component to match distutils's behavior.

@item 
bpo-43109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43109}: Allow --with-lto configure option to work with Apple-supplied
Xcode or Command Line Tools.

@item 
bpo-34932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34932}: Add socket.TCP_KEEPALIVE support for macOS. Patch by Shane
Harvey.
@end itemize

@node IDLE<19>,Tools/Demos<27>,macOS<27>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id505}@anchor{1c68}
@subsubsection IDLE



@itemize -

@item 
bpo-45296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45296}: On Windows, change exit/quit message to suggest Ctrl-D, which
works, instead of <Ctrl-Z Return>, which does not work in IDLE.

@item 
bpo-45193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45193}: Make completion boxes appear on Ubuntu again.

@item 
bpo-40128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40128}: Mostly fix completions on macOS when not using tcl/tk 8.6.11
(as with 3.9). The added update_idletask call should be harmless and
possibly helpful otherwise.

@item 
bpo-33962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33962}: Move the indent space setting from the Font tab to the new
Windows tab. Patch by Mark Roseman and Terry Jan Reedy.

@item 
bpo-40468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40468}: Split the settings dialog General tab into Windows and Shell/ED
tabs. Move help sources, which extend the Help menu, to the Extensions
tab. Make space for new options and shorten the dialog. The latter makes
the dialog better fit small screens.

@item 
bpo-41611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41611}: Avoid uncaught exceptions in
@code{AutoCompleteWindow.winconfig_event()}.

@item 
bpo-41611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41611}: Fix IDLE sometimes freezing upon tab-completion on macOS.

@item 
bpo-44010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44010}: Highlight the new @ref{a0e,,match} statement's @ref{a0d,,soft keywords}: @ref{a0e,,match}, @ref{a0e,,case}, and
@ref{a0f,,_}. However, this highlighting is not
perfect and will be incorrect in some rare cases, including some @code{_}-s
in @code{case} patterns.

@item 
bpo-44026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44026}: Include interpreter's typo fix suggestions in message line for
NameErrors and AttributeErrors.  Patch by E. Paine.
@end itemize

@node Tools/Demos<27>,C API<37>,IDLE<19>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id506}@anchor{1c69}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-44786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44786}: Fix a warning in regular expression in the c-analyzer script.

@item 
bpo-44967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44967}: pydoc now returns a non-zero status code when a module cannot
be found.

@item 
bpo-44978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44978}: Allow the Argument Clinic tool to handle @code{__complex__}
special methods.

@item 
bpo-43425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43425}: Removed the 'test2to3' demo project that demonstrated using
lib2to3 to support Python 2.x and Python 3.x from a single source in a
distutils package. Patch by Donghee Na

@item 
bpo-44074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44074}: Make patchcheck automatically detect the correct base branch
name (previously it was hardcoded to 'master')

@item 
bpo-20291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20291}: Added support for variadic positional parameters in Argument
Clinic.
@end itemize

@node C API<37>,,Tools/Demos<27>,Python 3 11 0 alpha 1
@anchor{whatsnew/changelog id507}@anchor{1c6a}
@subsubsection C API



@itemize -

@item 
bpo-41710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41710}: The PyThread_acquire_lock_timed() function now clamps the
timeout if it is too large, rather than aborting the process. Patch by
Victor Stinner.

@item 
bpo-44687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44687}: @code{BufferedReader.peek()} no longer raises @ref{2ec,,ValueError}
when the entire file has already been buffered.

@item 
bpo-45116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45116}: Add the @ref{1c6b,,Py_ALWAYS_INLINE} macro to ask the compiler
to always inline a static inline function. The compiler can ignore it and
decides to not inline the function. Patch by Victor Stinner.

@item 
bpo-45094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45094}: Add the @ref{1802,,Py_NO_INLINE} macro to disable inlining on a
function. Patch by Victor Stinner.

@item 
bpo-45061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45061}: Add a deallocator to the @ref{3c3,,bool} type to detect refcount
bugs in C extensions which call @code{Py_DECREF(Py_True);} or
@code{Py_DECREF(Py_False);} by mistake. Patch by Victor Stinner.

@item 
bpo-42035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42035}: Add a new @ref{959,,PyType_GetQualName()} function to get type's
qualified name.

@item 
bpo-41103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41103}: Reverts removal of the old buffer protocol because they are
part of stable ABI.

@item 
bpo-44751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44751}: Remove @code{crypt.h} include from the public @code{Python.h} header.

@item 
bpo-42747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42747}: The @code{Py_TPFLAGS_HAVE_VERSION_TAG} type flag now does nothing.
The @code{Py_TPFLAGS_HAVE_AM_SEND} flag (which was added in 3.10) is removed.
Both were unnecessary because it is not possible to have type objects with
the relevant fields missing.

@item 
bpo-44530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44530}: Added the @code{co_qualname} to the @code{PyCodeObject} structure to
propagate the qualified name from the compiler to code objects.

Patch by Gabriele N. Tornetta

@item 
bpo-44441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44441}: @ref{bbc,,Py_RunMain()} now resets @ref{1b1b,,PyImport_Inittab} to
its initial value at exit. It must be possible to call
@ref{1b1c,,PyImport_AppendInittab()} or @ref{1b1d,,PyImport_ExtendInittab()} at
each Python initialization. Patch by Victor Stinner.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Remove 4 private trashcan C API functions which were only kept
for the backward compatibility of the stable ABI with Python 3.8 and
older, since the trashcan API was not usable with the limited C API on
Python 3.8 and older. The trashcan API was excluded from the limited C API
in Python 3.9.

Removed functions:


@itemize *

@item 
_PyTrash_deposit_object()

@item 
_PyTrash_destroy_chain()

@item 
_PyTrash_thread_deposit_object()

@item 
_PyTrash_thread_destroy_chain()
@end itemize

The trashcan C API was never usable with the limited C API, since old
trashcan macros accessed directly @ref{990,,PyThreadState} members like
@code{_tstate->trash_delete_nesting}, whereas the @ref{990,,PyThreadState}
structure is opaque in the limited C API.

Exclude also the @code{PyTrash_UNWIND_LEVEL} constant from the C API.

Patch by Victor Stinner.

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Removed documentation for the removed @code{PyParser_*} C API.

@item 
bpo-43795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43795}: The list in @ref{99d,,限定版APIの内容} now shows the public name
@ref{98c,,PyFrameObject} rather than @code{_frame}. The non-existing entry
@code{_node} no longer appears in the list.

@item 
bpo-44378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44378}: @ref{1ba0,,Py_IS_TYPE()} no longer uses @ref{3c9,,Py_TYPE()} to avoid
a compiler warning: no longer cast @code{const PyObject*} to @code{PyObject*}.
Patch by Victor Stinner.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Convert the @ref{3c9,,Py_TYPE()} and @ref{985,,Py_SIZE()} macros to
static inline functions. The @ref{984,,Py_SET_TYPE()} and
@ref{986,,Py_SET_SIZE()} functions must now be used to set an object type and
size. Patch by Victor Stinner.

@item 
bpo-44263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44263}: The @ref{980,,PyType_Ready()} function now raises an error if a
type is defined with the @ref{981,,Py_TPFLAGS_HAVE_GC} flag set but has no
traverse function (@ref{982,,PyTypeObject.tp_traverse}). Patch by Victor
Stinner.

@item 
bpo-43795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43795}: The undocumented function @code{Py_FrozenMain()} is removed
from the Limited API.

@item 
bpo-44113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44113}: Deprecate the following functions to configure the Python
initialization:


@itemize *

@item 
@code{PySys_AddWarnOptionUnicode()}

@item 
@code{PySys_AddWarnOption()}

@item 
@code{PySys_AddXOption()}

@item 
@code{PySys_HasWarnOptions()}

@item 
@code{Py_SetPath()}

@item 
@code{Py_SetProgramName()}

@item 
@code{Py_SetPythonHome()}

@item 
@code{Py_SetStandardStreamEncoding()}

@item 
@code{_Py_SetProgramFullPath()}
@end itemize

Use the new @ref{3f7,,PyConfig} API of the @ref{646,,Python Initialization Configuration} instead (
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/}).

@item 
bpo-44094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44094}: Remove @code{PyErr_SetFromErrnoWithUnicodeFilename()},
@code{PyErr_SetFromWindowsErrWithUnicodeFilename()}, and
@code{PyErr_SetExcFromWindowsErrWithUnicodeFilename()}. They are not
documented and have been deprecated since Python 3.3.

@item 
bpo-43795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43795}: @ref{a97,,PyCodec_Unregister()} is now properly exported as a
function in the Windows Stable ABI DLL.

@item 
bpo-44029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44029}: Remove deprecated @code{Py_UNICODE} APIs: @code{PyUnicode_Encode},
@code{PyUnicode_EncodeUTF7}, @code{PyUnicode_EncodeUTF8},
@code{PyUnicode_EncodeUTF16}, @code{PyUnicode_EncodeUTF32},
@code{PyUnicode_EncodeLatin1}, @code{PyUnicode_EncodeMBCS},
@code{PyUnicode_EncodeDecimal}, @code{PyUnicode_EncodeRawUnicodeEscape},
@code{PyUnicode_EncodeCharmap}, @code{PyUnicode_EncodeUnicodeEscape},
@code{PyUnicode_TransformDecimalToASCII}, @code{PyUnicode_TranslateCharmap},
@code{PyUnicodeEncodeError_Create}, @code{PyUnicodeTranslateError_Create}. See
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} and 
@geindex Python Enhancement Proposals; PEP 624
PEP 624@footnote{https://peps.python.org/pep-0624/} for reference.

@item 
bpo-42035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42035}: Add a new @ref{958,,PyType_GetName()} function to get type's short
name.
@end itemize

@node Python 3 10 0 beta 1,Python 3 10 0 alpha 7,Python 3 11 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-10-0-beta-1}@anchor{1c6c}
@subsection Python 3.10.0 beta 1


`リリース日: 2021-05-03'

@menu
* セキュリティ: セキュリティ<30>. 
* Core and Builtins: Core and Builtins<114>. 
* ライブラリ: ライブラリ<117>. 
* Core and Builtins: Core and Builtins<115>. 
* ライブラリ: ライブラリ<118>. 
* Core and Builtins: Core and Builtins<116>. 
* ライブラリ: ライブラリ<119>. 
* ドキュメント: ドキュメント<37>. 
* テスト: テスト<36>. 
* ビルド: ビルド<43>. 
* Windows: Windows<38>. 
* macOS: macOS<28>. 
* IDLE: IDLE<20>. 
* C API: C API<38>. 

@end menu

@node セキュリティ<30>,Core and Builtins<114>,,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id508}@anchor{1c6d}
@subsubsection セキュリティ



@itemize -

@item 
bpo-43434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43434}: Creating @ref{54d,,sqlite3.Connection} objects now also produces
@code{sqlite3.connect} and @code{sqlite3.connect/handle} @ref{1c6e,,auditing events}. Previously these events were only produced by
@ref{5a6,,sqlite3.connect()} calls. Patch by Erlend E. Aasland.

@item 
bpo-43998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43998}: The @ref{d5,,ssl} module sets more secure cipher suites defaults.
Ciphers without forward secrecy and with SHA-1 MAC are disabled by
default. Security level 2 prohibits weak RSA, DH, and ECC keys with less
than 112 bits of security. @ref{357,,SSLContext} defaults to minimum
protocol version TLS 1.2. Settings are based on Hynek Schlawack's
research.

@item 
bpo-43882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43882}: The presence of newline or tab characters in parts of a URL
could allow some forms of attacks.

Following the controlling specification for URLs defined by WHATWG
@ref{110,,urllib.parse()} now removes ASCII newlines and tabs from URLs,
preventing such attacks.

@item 
bpo-43472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43472}: Ensures interpreter-level audit hooks receive the
@code{cpython.PyInterpreterState_New} event when called through the
@code{_xxsubinterpreters} module.

@item 
bpo-43362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43362}: Fix invalid free in _sha3 module. The issue was introduced in
3.10.0a1. Python 3.9 and earlier are not affected.

@item 
bpo-43762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43762}: Add audit events for @code{sqlite3.connect/handle()},
@ref{a3f,,sqlite3.Connection.enable_load_extension()}, and
@ref{6df,,sqlite3.Connection.load_extension()}. Patch by Erlend E. Aasland.

@item 
bpo-43756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43756}: Add new audit event @code{glob.glob/2} to incorporate the new
`root_dir' and `dir_fd' arguments added to @ref{5a0,,glob.glob()} and
@ref{a08,,glob.iglob()}.

@item 
bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384}: @ref{84,,ipaddress} module no longer accepts any leading zeros in
IPv4 address strings. Leading zeros are ambiguous and interpreted as octal
notation by some libraries. For example the legacy function
@ref{b5a,,socket.inet_aton()} treats leading zeros as octal notation. glibc
implementation of modern @ref{b5b,,inet_pton()} does not accept any
leading zeros. For a while the @ref{84,,ipaddress} module used to accept
ambiguous leading zeros.

@item 
bpo-43075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43075}: Fix Regular Expression Denial of Service (ReDoS) vulnerability
in @ref{1c6f,,urllib.request.AbstractBasicAuthHandler}.  The ReDoS-vulnerable
regex has quadratic worst-case complexity and it allows cause a denial of
service when identifying crafted invalid RFCs. This ReDoS issue is on the
client side and needs remote attackers to control the HTTP server.

@item 
bpo-42800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42800}: Audit hooks are now fired for frame.f_code, traceback.tb_frame,
and generator code/frame attribute access.

@item 
bpo-37363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37363}: Add audit events to the @ref{73,,http.client} module.
@end itemize

@node Core and Builtins<114>,ライブラリ<117>,セキュリティ<30>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id509}@anchor{1c70}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43977}: Prevent classes being both a sequence and a mapping when
pattern matching.

@item 
bpo-43977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43977}: Use @ref{1c71,,tp_flags} on the class object to
determine if the subject is a sequence or mapping when pattern matching.
Avoids the need to import @ref{1f,,collections.abc} when pattern matching.

@item 
bpo-43892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43892}: Restore proper validation of complex literal value patterns
when parsing @code{match} blocks.

@item 
bpo-43933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43933}: Set frame.f_lineno to the line number of the 'with' kweyword
when executing the call to @code{__exit__}.

@item 
bpo-43933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43933}: If the current position in a frame has no line number then set
the f_lineno attribute to None, instead of -1, to conform to PEP 626. This
should not normally be possible, but might occur in some unusual
circumstances.

@item 
bpo-43963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43963}: Importing the @code{_signal} module in a subinterpreter has no
longer side effects.

@item 
bpo-42739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42739}: The internal representation of line number tables is changed to
not use sentinels, and an explicit length parameter is added to the out of
process API function @code{PyLineTable_InitAddressRange}. This makes the
handling of line number tables more robust in some circumstances.
@end itemize

@node ライブラリ<117>,Core and Builtins<115>,Core and Builtins<114>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id510}@anchor{1c72}
@subsubsection ライブラリ



@itemize -

@item 
bpo-43908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43908}: Make @ref{be,,re} types immutable. Patch by Erlend E. Aasland.

@item 
bpo-43908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43908}: Make the @ref{4be,,array.array} type immutable. Patch by Erlend
E. Aasland.
@end itemize

@node Core and Builtins<115>,ライブラリ<118>,ライブラリ<117>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id511}@anchor{1c73}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43901}: Change class and module objects to lazy-create empty
annotations dicts on demand.  The annotations dicts are stored in the
object's __dict__ for backwards compatibility.

@item 
bpo-43892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43892}: Match patterns now use new dedicated AST nodes (@code{MatchValue},
@code{MatchSingleton}, @code{MatchSequence}, @code{MatchStar}, @code{MatchMapping},
@code{MatchClass}) rather than reusing expression AST nodes. @code{MatchAs} and
@code{MatchOr} are now defined as pattern nodes rather than as expression
nodes. Patch by Nick Coghlan.

@item 
bpo-42725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42725}: Usage of @code{await}/@code{yield}/@code{yield from} and named
expressions within an annotation is now forbidden when PEP 563 is
activated.

@item 
bpo-43754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43754}: When performing structural pattern matching (
@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/}),
captured names are now left unbound until the `entire' pattern has matched
successfully.

@item 
bpo-42737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42737}: Annotations for complex targets (everything beside simple
names) no longer cause any runtime effects with @code{from __future__ import
annotations}.

@item 
bpo-43914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43914}: @ref{18e,,SyntaxError} exceptions raised by the interpreter will
highlight the full error range of the expression that constitutes the
syntax error itself, instead of just where the problem is detected. Patch
by Pablo Galindo.

@item 
bpo-38605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38605}: Revert making @code{from __future__ import annotations} the
default. This follows the Steering Council decision to postpone PEP 563
changes to at least Python 3.11. See the original email for more
information regarding the decision:
@indicateurl{https://mail.python.org/archives/list/python-dev@@python.org/thread/CLVXXPQ2T2LQ5MP2Y53VVQFCXYWQJHKZ/}.
Patch by Pablo Galindo.

@item 
bpo-43475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43475}: Hashes of NaN values now depend on object identity.  Formerly,
they always hashed to 0 even though NaN values are not equal to one
another.  Having the same hash for unequal values caused pile-ups in hash
tables.

@item 
bpo-43859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43859}: Improve the error message for @ref{1750,,IndentationError}
exceptions. Patch by Pablo Galindo

@item 
bpo-41323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41323}: Constant tuple folding in bytecode optimizer now reuses tuple
in constant table.

@item 
bpo-43846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43846}: Data stack usage is much reduced for large literal and call
expressions.

@item 
bpo-38530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38530}: When printing @ref{452,,NameError} raised by the interpreter,
@code{PyErr_Display()} will offer suggestions of similar variable names
in the function that the exception was raised from. Patch by Pablo Galindo

@item 
bpo-43823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43823}: Improve syntax errors for invalid dictionary literals. Patch by
Pablo Galindo.

@item 
bpo-43822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43822}: Improve syntax errors in the parser for missing commas between
expressions. Patch by Pablo Galindo.

@item 
bpo-43798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43798}: @ref{1c74,,ast.alias} nodes now include source location metadata
attributes e.g. lineno, col_offset.

@item 
bpo-43797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43797}: Improve @code{SyntaxError} error messages for invalid comparisons.
Patch by Pablo Galindo.

@item 
bpo-43760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43760}: Move the flag for checking whether tracing is enabled to the C
stack, from the heap. Should speed up dispatch in the interpreter.

@item 
bpo-43682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43682}: Static methods (@ref{453,,@@staticmethod}) and class methods
(@ref{48e,,@@classmethod}) now inherit the method attributes (@code{__module__},
@code{__name__}, @code{__qualname__}, @code{__doc__}, @code{__annotations__}) and have
a new @code{__wrapped__} attribute. Patch by Victor Stinner.

@item 
bpo-43751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43751}: Fixed a bug where @code{anext(ait, default)} would erroneously
return None.

@item 
bpo-42128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42128}: @ref{1c75,,__match_args__} is no longer allowed to be a
list.

@item 
bpo-43683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43683}: Add GEN_START opcode. Marks start of generator, including
async, or coroutine and handles sending values to a newly created
generator or coroutine.
@end itemize

@node ライブラリ<118>,Core and Builtins<116>,Core and Builtins<115>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id512}@anchor{1c76}
@subsubsection ライブラリ



@itemize -

@item 
bpo-43105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43105}: Importlib now resolves relative paths when creating module spec
objects from file locations.
@end itemize

@node Core and Builtins<116>,ライブラリ<119>,ライブラリ<118>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id513}@anchor{1c77}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43682}: Static methods (@ref{453,,@@staticmethod}) are now callable as
regular functions. Patch by Victor Stinner.

@item 
bpo-42609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42609}: Prevented crashes in the AST validator and optimizer when
compiling some absurdly long expressions like @code{"+0"*1000000}.
@ref{f68,,RecursionError} is now raised instead.

@item 
bpo-38530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38530}: When printing @ref{5f0,,AttributeError}, @code{PyErr_Display()}
will offer suggestions of similar attribute names in the object that the
exception was raised from. Patch by Pablo Galindo
@end itemize

@node ライブラリ<119>,ドキュメント<37>,Core and Builtins<116>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id514}@anchor{1c78}
@subsubsection ライブラリ



@itemize -

@item 
bpo-44015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44015}: In @@dataclass(), raise a TypeError if KW_ONLY is specified more
than once.

@item 
bpo-25478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25478}: Added a `total()' method to collections.Counter() to compute
the sum of the counts.

@item 
bpo-43733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43733}: Change @ref{1c79,,netrc.netrc} to use UTF-8 encoding before using
locale encoding.

@item 
bpo-43979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43979}: Removed an unnecessary list comprehension before looping from
@ref{31e,,urllib.parse.parse_qsl()}.  Patch by Christoph Zwerschke and Donghee
Na.

@item 
bpo-43993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43993}: Update bundled pip to 21.1.1.

@item 
bpo-43957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43957}: [Enum] Deprecate @code{TypeError} when non-member is used in a
containment check; In 3.12 @code{True} or @code{False} will be returned instead,
and containment will return @code{True} if the value is either a member of
that enum or one of its members' value.

@item 
bpo-42904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42904}: For backwards compatibility with previous minor versions of
Python, if @ref{8c0,,typing.get_type_hints()} receives no namespace dictionary
arguments, @ref{8c0,,typing.get_type_hints()} will search through the global
then local namespaces during evaluation of stringized type annotations
(string forward references) inside a class.

@item 
bpo-43945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43945}: [Enum] Deprecate non-standard mixin format() behavior: in 3.12
the enum member, not the member's value, will be used for format() calls.

@item 
bpo-41139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41139}: Deprecate undocumented @code{cgi.log()} API.

@item 
bpo-43937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43937}: Fixed the @ref{107,,turtle} module working with non-default root
window.

@item 
bpo-43930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43930}: Update bundled pip to 21.1 and setuptools to 56.0.0

@item 
bpo-43907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43907}: Fix a bug in the pure-Python pickle implementation when using
protocol 5, where bytearray instances that occur several time in the
pickled object graph would incorrectly unpickle into repeated copies of
the bytearray object.

@item 
bpo-43926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43926}: In @code{importlib.metadata}, provide a uniform interface to
@code{Description}, allow for any field to be encoded with multiline values,
remove continuation lines from multiline values, and add a @code{.json}
property for easy access to the PEP 566 JSON-compatible form. Sync with
@code{importlib_metadata 4.0}.

@item 
bpo-43920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43920}: OpenSSL 3.0.0: @ref{10ee,,load_verify_locations()}
now returns a consistent error message when cadata contains no valid
certificate.

@item 
bpo-43607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43607}: @ref{10e,,urllib} can now convert Windows paths with @code{\\?\}
prefixes into URL paths.

@item 
bpo-43817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43817}: Add @ref{a14,,inspect.get_annotations()}, which safely computes the
annotations defined on an object.  It works around the quirks of accessing
the annotations from various types of objects, and makes very few
assumptions about the object passed in. @ref{a14,,inspect.get_annotations()}
can also correctly un-stringize stringized annotations.

@ref{22f,,inspect.signature()}, @code{inspect.from_callable()}, and
@code{inspect.from_function()} now call @ref{a14,,inspect.get_annotations()} to
retrieve annotations.  This means @ref{22f,,inspect.signature()} and
@code{inspect.from_callable()} can now un-stringize stringized annotations,
too.

@item 
bpo-43284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43284}: platform.win32_ver derives the windows version from
sys.getwindowsversion().platform_version which in turn derives the version
from kernel32.dll (which can be of a different version than Windows
itself). Therefore change the platform.win32_ver to determine the version
using the platform module's _syscmd_ver private function to return an
accurate version.

@item 
bpo-42854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42854}: The @ref{d5,,ssl} module now uses @code{SSL_read_ex} and
@code{SSL_write_ex} internally. The functions support reading and writing of
data larger than 2 GB. Writing zero-length data no longer fails with a
protocol violation error.

@item 
bpo-42333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42333}: Port @code{_ssl} extension module to multiphase initialization.

@item 
bpo-43880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43880}: @ref{d5,,ssl} now raises DeprecationWarning for OP_NO_SSL/TLS*
options, old TLS versions, old protocols, and other features that have
been deprecated since Python 3.6, 3.7, or OpenSSL 1.1.0.

@item 
bpo-41559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41559}: 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} is now implemented purely in Python; builtin
@code{types.GenericAlias} objects no longer include @code{typing.ParamSpec} in
@code{__parameters__} (with the exception of @code{collections.abc.Callable}'s
@code{GenericAlias}). This means previously invalid uses of @code{ParamSpec}
(such as @code{list[P]}) which worked in earlier versions of Python 3.10
alpha, will now raise @code{TypeError} during substitution.

@item 
bpo-43867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43867}: The @ref{98,,multiprocessing} @code{Server} class now explicitly
catches @ref{f3c,,SystemExit} and closes the client connection in this case.
It happens when the @code{Server.serve_client()} method reaches the end of
file (EOF).

@item 
bpo-40443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40443}: Remove unused imports: pyclbr no longer uses copy, and typing
no longer uses ast. Patch by Victor Stinner.

@item 
bpo-43820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43820}: Remove an unneeded copy of the namespace passed to
dataclasses.make_dataclass().

@item 
bpo-43787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43787}: Add @code{__iter__()} method to @ref{a66,,bz2.BZ2File},
@ref{65c,,gzip.GzipFile}, and @ref{120e,,lzma.LZMAFile}. It makes iterating
them about 2x faster. Patch by Inada Naoki.

@item 
bpo-43680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43680}: Deprecate io.OpenWrapper and _pyio.OpenWrapper: use io.open and
_pyio.open instead. Until Python 3.9, _pyio.open was not a static method
and builtins.open was set to OpenWrapper to not become a bound method when
set to a class variable. _io.open is a built-in function whereas
_pyio.open is a Python function. In Python 3.10, _pyio.open() is now a
static method, and builtins.open() is now io.open().

@item 
bpo-43680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43680}: The Python @code{_pyio.open()} function becomes a static method
to behave as @ref{740,,io.open()} built-in function: don't become a bound
method when stored as a class variable. It becomes possible since static
methods are now callable in Python 3.10. Moreover,
@code{_pyio.OpenWrapper()} becomes a simple alias to @code{_pyio.open()}.
Patch by Victor Stinner.

@item 
bpo-41515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41515}: Fix @ref{5e7,,KeyError} raised in @ref{8c0,,typing.get_type_hints()} due
to synthetic modules that don't appear in @code{sys.modules}.

@item 
bpo-43776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43776}: When @ref{4b7,,subprocess.Popen} args are provided as a string or
as @ref{266,,pathlib.Path}, the Popen instance repr now shows the right
thing.

@item 
bpo-42248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42248}: [Enum] ensure exceptions raised in @code{_missing__} are released

@item 
bpo-43744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43744}: fix issue with enum member name matching the start of a private
variable name

@item 
bpo-43772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43772}: Fixed the return value of @code{TypeVar.__ror__}. Patch by Jelle
Zijlstra.

@item 
bpo-43764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43764}: Add match_args parameter to @@dataclass decorator to allow
suppression of __match_args__ generation.

@item 
bpo-43799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43799}: OpenSSL 3.0.0: define @code{OPENSSL_API_COMPAT} 1.1.1 to suppress
deprecation warnings. Python requires OpenSSL 1.1.1 APIs.

@item 
bpo-43478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43478}: Mocks can no longer be used as the specs for other Mocks. As a
result, an already-mocked object cannot have an attribute mocked using
@code{autospec=True} or be the subject of a @code{create_autospec(...)} call.
This can uncover bugs in tests since these Mock-derived Mocks will always
pass certain tests (e.g. @ref{2ad,,isinstance()}) and builtin assert functions
(e.g. assert_called_once_with) will unconditionally pass.

@item 
bpo-43794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43794}: Add @ref{a38,,ssl.OP_IGNORE_UNEXPECTED_EOF} constants (OpenSSL
3.0.0)

@item 
bpo-43785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43785}: Improve @code{bz2.BZ2File} performance by removing the RLock from
BZ2File. This makes BZ2File thread unsafe in the face of multiple
simultaneous readers or writers, just like its equivalent classes in
@ref{6b,,gzip} and @ref{8e,,lzma} have always been.  Patch by Inada Naoki.

@item 
bpo-43789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43789}: OpenSSL 3.0.0: Don't call the password callback function a
second time when first call has signaled an error condition.

@item 
bpo-43788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43788}: The header files for @ref{d5,,ssl} error codes are now OpenSSL
version-specific. Exceptions will now show correct reason and library
codes. The @code{make_ssl_data.py} script has been rewritten to use OpenSSL's
text file with error codes.

@item 
bpo-43766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43766}: Implement 
@geindex Python Enhancement Proposals; PEP 647
PEP 647@footnote{https://peps.python.org/pep-0647/} in the @ref{10a,,typing} module by adding
@code{TypeGuard}.

@item 
bpo-25264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25264}: @ref{262,,os.path.realpath()} now accepts a `strict' keyword-only
argument. When set to @code{True}, @ref{2c0,,OSError} is raised if a path doesn't
exist or a symlink loop is encountered.

@item 
bpo-43780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43780}: In @code{importlib.metadata}, incorporate changes from
importlib_metadata 3.10: Add mtime-based caching during distribution
discovery. Flagged use of dict result from @code{entry_points()} as
deprecated.

@item 
gh-47383@footnote{https://github.com/python/cpython/issues/47383}: The @code{P.args} and @code{P.kwargs} attributes of
@ref{487,,typing.ParamSpec} are now instances of the new classes
@ref{9c9,,typing.ParamSpecArgs} and @ref{9ca,,typing.ParamSpecKwargs}, which
enables a more useful @code{repr()}. Patch by Jelle Zijlstra.

@item 
bpo-43731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43731}: Add an @code{encoding} parameter @code{logging.fileConfig()}.

@item 
bpo-43712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43712}: Add @code{encoding} and @code{errors} parameters to
@ref{a00,,fileinput.input()} and @ref{940,,fileinput.FileInput}.

@item 
bpo-38659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38659}: A @code{simple_enum} decorator is added to the @code{enum} module to
convert a normal class into an Enum. @code{test_simple_enum} added to test
simple enums against a corresponding normal Enum.  Standard library
modules updated to use @code{simple_enum}.

@item 
bpo-43764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43764}: Fix an issue where @ref{1c75,,__match_args__} generation
could fail for some @ref{33,,dataclasses}.

@item 
bpo-43752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43752}: Fix @ref{d4,,sqlite3} regression for zero-sized blobs with
converters, where @code{b""} was returned instead of @code{None}. The regression
was introduced by PR 24723. Patch by Erlend E. Aasland.

@item 
bpo-43655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43655}: @ref{f6,,tkinter} dialog windows are now recognized as dialogs by
window managers on macOS and X Window.

@item 
bpo-43723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43723}: The following @code{threading} methods are now deprecated and
should be replaced:


@itemize -

@item 
@code{currentThread} => @ref{35e,,threading.current_thread()}

@item 
@code{activeCount} => @ref{35f,,threading.active_count()}

@item 
@code{Condition.notifyAll} => @ref{359,,threading.Condition.notify_all()}

@item 
@code{Event.isSet} => @ref{35a,,threading.Event.is_set()}

@item 
@code{Thread.setName} => @ref{2a0,,threading.Thread.name}

@item 
@code{thread.getName} => @ref{2a0,,threading.Thread.name}

@item 
@code{Thread.isDaemon} => @ref{35c,,threading.Thread.daemon}

@item 
@code{Thread.setDaemon} => @ref{35c,,threading.Thread.daemon}
@end itemize

Patch by Jelle Zijlstra.

@item 
bpo-2135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2135}: Deprecate find_module() and find_loader() implementations in
importlib and zipimport.

@item 
bpo-43534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43534}: @ref{1c7a,,turtle.textinput()} and @ref{1c7b,,turtle.numinput()} create now
a transient window working on behalf of the canvas window.

@item 
bpo-43532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43532}: Add the ability to specify keyword-only fields to dataclasses.
These fields will become keyword-only arguments to the generated __init__.

@item 
bpo-43522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43522}: Fix problem with
@ref{d76,,hostname_checks_common_name}. OpenSSL does not copy
hostflags from `struct SSL_CTX' to `struct SSL'.

@item 
bpo-8978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8978}: Improve error message for @ref{1077,,tarfile.open()} when @ref{8e,,lzma}
/ @ref{14,,bz2} are unavailable.  Patch by Anthony Sottile.

@item 
bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}: Allow @ref{192,,bytes} @code{separator} argument in
@code{urllib.parse.parse_qs} and @code{urllib.parse.parse_qsl} when parsing
@ref{169,,str} query strings. Previously, this raised a @code{TypeError}.

@item 
bpo-43296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43296}: Improve @ref{d4,,sqlite3} error handling: @code{sqlite3_value_blob()}
errors that set @code{SQLITE_NOMEM} now raise @ref{179e,,MemoryError}. Patch by
Erlend E. Aasland.

@item 
bpo-43312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43312}: New functions @ref{89f,,sysconfig.get_preferred_scheme()} and
@ref{1bb5,,sysconfig.get_default_scheme()} are added to query a platform for its
preferred "user", "home", and "prefix" (default) scheme names.

@item 
bpo-43265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43265}: Improve @ref{d73,,sqlite3.Connection.backup()} error handling. The
error message for non-existent target database names is now @code{unknown
database <database name>} instead of @code{SQL logic error}. Patch by Erlend
E. Aasland.

@item 
bpo-41282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41282}: Install schemes in @code{distutils.command.install} are now loaded
from @ref{e1,,sysconfig}.

@item 
bpo-41282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41282}: @code{distutils.sysconfig} has been merged to @ref{e1,,sysconfig}.

@item 
bpo-43176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43176}: Fixed processing of a dataclass that inherits from a frozen
dataclass with no fields.  It is now correctly detected as an error.

@item 
bpo-43080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43080}: @ref{b3,,pprint} now has support for
@ref{4e1,,dataclasses.dataclass}. Patch by Lewis Gaul.

@item 
bpo-39950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39950}: Add @code{pathlib.Path.hardlink_to()} method that supersedes
@code{link_to()}. The new method has the same argument order as
@code{symlink_to()}.

@item 
bpo-42904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42904}: @ref{8c0,,typing.get_type_hints()} now checks the local namespace of
a class when evaluating 
@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/} annotations inside said class.

@item 
bpo-42269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42269}: Add @code{slots} parameter to @code{dataclasses.dataclass} decorator
to automatically generate @code{__slots__} for class. Patch provided by Yurii
Karabas.

@item 
bpo-39529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39529}: Deprecated use of @ref{2f2,,asyncio.get_event_loop()} without
running event loop. Emit deprecation warning for @ref{b,,asyncio} functions
which implicitly create a @ref{dc6,,Future} or
@ref{1c7,,Task} objects if there is no running event loop and no
explicit `loop' argument is passed: @ref{e71,,ensure_future()},
@ref{1c7c,,wrap_future()}, @ref{813,,gather()},
@ref{c65,,shield()}, @ref{4c6,,as_completed()} and constructors of
@ref{dc6,,Future}, @ref{1c7,,Task},
@ref{1c7d,,StreamReader}, @code{StreamReaderProtocol}.

@item 
bpo-18369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18369}: Certificate and PrivateKey classes were added to the ssl
module. Certificates and keys can now be loaded from memory buffer, too.

@item 
bpo-41486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41486}: Use a new output buffer management code for @ref{14,,bz2} /
@ref{8e,,lzma} / @ref{139,,zlib} modules, and add @code{.readall()} function to
@code{_compression.DecompressReader} class. These bring some performance
improvements. Patch by Ma Lin.

@item 
bpo-31870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31870}: The @ref{a3d,,ssl.get_server_certificate()} function now has a
`timeout' parameter.

@item 
bpo-41735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41735}: Fix thread locks in zlib module may go wrong in rare case.
Patch by Ma Lin.

@item 
bpo-36470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36470}: Fix dataclasses with @code{InitVar}s and
@ref{1a6a,,replace()}. Patch by Claudiu Popa.

@item 
bpo-40849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40849}: Expose X509_V_FLAG_PARTIAL_CHAIN ssl flag

@item 
bpo-35114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35114}: @ref{1c7e,,ssl.RAND_status()} now returns a boolean value (as
documented) instead of @code{1} or @code{0}.

@item 
bpo-39906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39906}: @ref{a24,,pathlib.Path.stat()} and @ref{a25,,chmod()} now
accept a `follow_symlinks' keyword-only argument for consistency with
corresponding functions in the @ref{a5,,os} module.

@item 
bpo-39899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39899}: @ref{c09,,os.path.expanduser()} now refuses to guess Windows home
directories if the basename of current user's home directory does not
match their username.

@ref{1042,,pathlib.Path.expanduser()} and @ref{1043,,home()} now
consistently raise @ref{244,,RuntimeError} exception when a home directory
cannot be resolved. Previously a @ref{5e7,,KeyError} exception could be raised
on Windows when the @code{"USERNAME"}  environment variable was unset.

@item 
bpo-36076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36076}: Added SNI support to @ref{a3d,,ssl.get_server_certificate()}.

@item 
bpo-38490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38490}: Covariance, Pearson's correlation, and simple linear regression
functionality was added to statistics module. Patch by Tymoteusz Wołodźko.

@item 
bpo-33731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33731}: Provide a locale.localize() function, which converts a
normalized number string into a locale format.

@item 
bpo-32745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32745}: Fix a regression in the handling of ctypes'
@ref{1a58,,ctypes.c_wchar_p} type: embedded null characters would cause a
@ref{2ec,,ValueError} to be raised. Patch by Zackery Spytz.
@end itemize

@node ドキュメント<37>,テスト<36>,ライブラリ<119>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id515}@anchor{1c7f}
@subsubsection ドキュメント



@itemize -

@item 
bpo-43987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43987}: Add "Annotations Best Practices" document as a new HOWTO.

@item 
bpo-43977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43977}: Document the new @ref{1c58,,Py_TPFLAGS_MAPPING} and
@ref{1c59,,Py_TPFLAGS_SEQUENCE} type flags.

@item 
bpo-43959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43959}: The documentation on the PyContextVar C-API was clarified.

@item 
bpo-43938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43938}: Update dataclasses documentation to express that
FrozenInstanceError is derived from AttributeError.

@item 
bpo-43778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43778}: Fix the Sphinx glossary_search extension: create the _static/
sub-directory if it doesn't exist.

@item 
bpo-43755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43755}: Update documentation to reflect that unparenthesized lambda
expressions can no longer be the expression part in an @code{if} clause in
comprehensions and generator expressions since Python 3.9.

@item 
bpo-43739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43739}: Fixing the example code in Doc/extending/extending.rst to
declare and initialize the pmodule variable to be of the right type.
@end itemize

@node テスト<36>,ビルド<43>,ドキュメント<37>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id516}@anchor{1c80}
@subsubsection テスト



@itemize -

@item 
bpo-43961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43961}: Fix test_logging.test_namer_rotator_inheritance() on Windows:
use @ref{130a,,os.replace()} rather than @ref{1309,,os.rename()}. Patch by Victor
Stinner.

@item 
bpo-43842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43842}: Fix a race condition in the SMTP test of test_logging. Don't
close a file descriptor (socket) from a different thread while
asyncore.loop() is polling the file descriptor. Patch by Victor Stinner.

@item 
bpo-43843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43843}: @code{test.libregrtest} now marks a test as ENV_CHANGED
(altered the execution environment) if a thread raises an exception but
does not catch it. It sets a hook on @ref{a4b,,threading.excepthook()}. Use
@code{--fail-env-changed} option to mark the test as failed. Patch by Victor
Stinner.

@item 
bpo-43811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43811}: Tests multiple OpenSSL versions on GitHub Actions. Use ccache
to speed up testing.

@item 
bpo-43791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43791}: OpenSSL 3.0.0: Disable testing of legacy protocols TLS 1.0 and
1.1. Tests are failing with TLSV1_ALERT_INTERNAL_ERROR.
@end itemize

@node ビルド<43>,Windows<38>,テスト<36>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id517}@anchor{1c81}
@subsubsection ビルド



@itemize -

@item 
bpo-43567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43567}: Improved generated code refresh (AST/tokens/opcodes/keywords)
on Windows.

@item 
bpo-43669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43669}: Implement 
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/}. Python now requires OpenSSL 1.1.1 or
newer.
@end itemize

@node Windows<38>,macOS<28>,ビルド<43>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id518}@anchor{1c82}
@subsubsection Windows



@itemize -

@item 
bpo-35306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35306}: Adds additional arguments to @ref{1c83,,os.startfile()} function.

@item 
bpo-43538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43538}: Avoid raising errors from @ref{c0b,,pathlib.Path.exists()} when
passed an invalid filename.

@item 
bpo-38822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38822}: Fixed @ref{26d,,os.stat()} failing on inaccessible directories with
a trailing slash, rather than falling back to the parent directory's
metadata. This implicitly affected @ref{c03,,os.path.exists()} and
@ref{c05,,os.path.isdir()}.

@item 
bpo-26227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26227}: Fixed decoding of host names in @ref{1c84,,socket.gethostbyaddr()}
and @ref{1c85,,socket.gethostbyname_ex()}.

@item 
bpo-40432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40432}: Updated pegen regeneration script on Windows to find and use
Python 3.8 or higher.  Prior to this, pegen regeneration already required
3.8 or higher, but the script may have used lower versions of Python.

@item 
bpo-43745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43745}: Actually updates Windows release to OpenSSL 1.1.1k. Earlier
releases were mislabelled and actually included 1.1.1i again.

@item 
bpo-43652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43652}: Update Tcl and Tk to 8.6.11 in Windows installer.

@item 
bpo-43492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43492}: Upgrade Windows installer to use SQLite 3.35.5.

@item 
bpo-30555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30555}: Fix @code{WindowsConsoleIO} errors in the presence of fd
redirection. Patch by Segev Finer.
@end itemize

@node macOS<28>,IDLE<20>,Windows<38>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id519}@anchor{1c86}
@subsubsection macOS



@itemize -

@item 
bpo-42119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42119}: Fix check for macOS SDK paths when building Python. Narrow
search to match contents of SDKs, namely only files in
@code{/System/Library}, @code{/System/IOSSupport}, and @code{/usr} other than
@code{/usr/local}. Previously, anything under @code{/System} was assumed to be
in an SDK which causes problems with the new file system layout in 10.15+
where user file systems may appear to be mounted under @code{/System}.  Paths
in @code{/Library} were also incorrectly treated as SDK locations.

@item 
bpo-43568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43568}: Drop support for MACOSX_DEPLOYMENT_TARGET < 10.3

@item 
bpo-44009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44009}: Provide "python3.x-intel64" executable to allow reliably
forcing macOS universal2 framework builds to run under Rosetta 2 Intel-64
emulation on Apple Silicon Macs.  This can be useful for testing or when
universal2 wheels are not yet available.

@item 
bpo-43851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43851}: Build SQLite with @code{SQLITE_OMIT_AUTOINIT} on macOS. Patch by
Erlend E. Aasland.

@item 
bpo-43492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43492}: Update macOS installer to use SQLite 3.35.4.

@item 
bpo-42235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42235}: @code{Mac/BuildScript/build-installer.py} will now use
"--enable-optimizations" and @code{--with-lto} when building on macOS 10.15
or later.
@end itemize

@node IDLE<20>,C API<38>,macOS<28>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id520}@anchor{1c87}
@subsubsection IDLE



@itemize -

@item 
bpo-37903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37903}: Add mouse actions to the shell sidebar.  Left click and
optional drag selects one or more lines, as with the editor line number
sidebar.  Right click after selecting raises a context menu with 'copy
with prompts'.  This zips together prompts from the sidebar with lines
from the selected text.

@item 
bpo-43981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43981}: Fix reference leak in test_sidebar and test_squeezer. Patches
by Terry Jan Reedy and Pablo Galindo

@item 
bpo-37892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37892}: Indent IDLE Shell input with spaces instead of tabs

@item 
bpo-43655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43655}: IDLE dialog windows are now recognized as dialogs by window
managers on macOS and X Window.

@item 
bpo-37903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37903}: IDLE's shell now shows prompts in a separate side-bar.
@end itemize

@node C API<38>,,IDLE<20>,Python 3 10 0 beta 1
@anchor{whatsnew/changelog id521}@anchor{1c88}
@subsubsection C API



@itemize -

@item 
bpo-43916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43916}: Add a new @ref{7a2,,Py_TPFLAGS_DISALLOW_INSTANTIATION} type
flag to disallow creating type instances. Patch by Victor Stinner.

@item 
bpo-43774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43774}: Remove the now unused @code{PYMALLOC_DEBUG} macro. Debug hooks on
memory allocators are now installed by default if Python is built in debug
mode (if @code{Py_DEBUG} macro is defined). Moreover, they can now be used on
Python build in release mode (ex: using @code{PYTHONMALLOC=debug} environment
variable).

@item 
bpo-43962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43962}: _PyInterpreterState_IDIncref() now calls
_PyInterpreterState_IDInitref() and always increments id_refcount.
Previously, calling _xxsubinterpreters.get_current() could create an
id_refcount inconsistency when a _xxsubinterpreters.InterpreterID object
was deallocated. Patch by Victor Stinner.

@item 
bpo-28254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28254}: Add new C-API functions to control the state of the garbage
collector: @ref{aa4,,PyGC_Enable()}, @ref{aa5,,PyGC_Disable()},
@ref{aa6,,PyGC_IsEnabled()}, corresponding to the functions in the
@ref{64,,gc} module.

@item 
bpo-43908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43908}: Introduce @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} flag for
immutable type objects, and modify @ref{980,,PyType_Ready()} to set it for
static types. Patch by Erlend E. Aasland.

@item 
bpo-43795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43795}: @ref{10ad,,PyMem_Calloc()} is now available in the limited C API
(@code{Py_LIMITED_API}).

@item 
bpo-43868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43868}: @ref{7a5,,PyOS_ReadlineFunctionPointer()} is no longer exported by
limited C API headers and by @code{python3.dll} on Windows. Like any function
that takes @code{FILE*}, it is not part of the stable ABI.

@item 
bpo-43795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43795}: Stable ABI and limited API definitions are generated from a
central manifest (
@geindex Python Enhancement Proposals; PEP 652
PEP 652@footnote{https://peps.python.org/pep-0652/}).

@item 
bpo-43753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43753}: Add the @ref{aa0,,Py_Is(x@comma{} y)} function to test if the
`x' object is the `y' object, the same as @code{x is y} in Python. Add also
the @ref{aa1,,Py_IsNone()}, @ref{aa2,,Py_IsTrue()}, @ref{aa3,,Py_IsFalse()}
functions to test if an object is, respectively, the @code{None} singleton,
the @code{True} singleton or the @code{False} singleton. Patch by Victor
Stinner.
@end itemize

@node Python 3 10 0 alpha 7,Python 3 10 0 alpha 6,Python 3 10 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-10-0-alpha-7}@anchor{1c89}
@subsection Python 3.10.0 alpha 7


`Release date: 2021-04-05'

@menu
* セキュリティ: セキュリティ<31>. 
* Core and Builtins: Core and Builtins<117>. 
* ライブラリ: ライブラリ<120>. 
* Core and Builtins: Core and Builtins<118>. 
* ライブラリ: ライブラリ<121>. 
* ドキュメント: ドキュメント<38>. 
* テスト: テスト<37>. 
* ビルド: ビルド<44>. 
* Windows: Windows<39>. 
* IDLE: IDLE<21>. 
* C API: C API<39>. 

@end menu

@node セキュリティ<31>,Core and Builtins<117>,,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id522}@anchor{1c8a}
@subsubsection セキュリティ



@itemize -

@item 
bpo-42988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42988}: 
@geindex Common Vulnerabilities and Exposures; CVE 2021-3426
CVE 2021-3426@footnote{https://www.cve.org/CVERecord?id=CVE-2021-3426}: Remove the @code{getfile} feature of the
@ref{ba,,pydoc} module which could be abused to read arbitrary files on the
disk (directory traversal vulnerability). Moreover, even source code of
Python modules can contain sensitive data like passwords. Vulnerability
reported by David Schwörer.

@item 
bpo-43285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43285}: @ref{62,,ftplib} no longer trusts the IP address value returned
from the server in response to the PASV command by default.  This prevents
a malicious FTP server from using the response to probe IPv4 address and
port combinations on the client network.

Code that requires the former vulnerable behavior may set a
@code{trust_server_pasv_ipv4_address} attribute on their @ref{af6,,ftplib.FTP}
instances to @code{True} to re-enable it.

@item 
bpo-43439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43439}: Add audit hooks for @ref{a04,,gc.get_objects()},
@ref{a05,,gc.get_referrers()} and @ref{a06,,gc.get_referents()}. Patch by Pablo
Galindo.
@end itemize

@node Core and Builtins<117>,ライブラリ<120>,セキュリティ<31>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id523}@anchor{1c8b}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27129}: Update CPython bytecode magic number.

@item 
bpo-43672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43672}: Raise ImportWarning when calling find_loader().

@item 
bpo-43660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43660}: Fix crash that happens when replacing @code{sys.stderr} with a
callable that can remove the object while an exception is being printed.
Patch by Pablo Galindo.

@item 
bpo-27129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27129}: The bytecode interpreter uses instruction, rather byte, offsets
internally. This reduces the number of EXTENDED_ARG instructions needed
and streamlines instruction dispatch a bit.
@end itemize

@node ライブラリ<120>,Core and Builtins<118>,Core and Builtins<117>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id524}@anchor{1c8c}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40645}: Fix reference leak in the @code{_hashopenssl} extension. Patch
by Pablo Galindo.
@end itemize

@node Core and Builtins<118>,ライブラリ<121>,ライブラリ<120>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id525}@anchor{1c8d}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42134}: Calls to find_module() by the import system now raise
ImportWarning.

@item 
bpo-41064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41064}: Improve the syntax error for invalid usage of double starred
elements ('**') in f-strings. Patch by Pablo Galindo.

@item 
bpo-43575@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43575}: Speed up calls to @code{map()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.

@item 
bpo-42137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42137}: The import system now prefers using @code{__spec__} for
@code{ModuleType.__repr__} over @code{module_repr()}.

@item 
bpo-43452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43452}: Added micro-optimizations to @code{_PyType_Lookup()} to improve
cache lookup performance in the common case of cache hits.

@item 
bpo-43555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43555}: Report the column offset for @ref{18e,,SyntaxError} for invalid
line continuation characters. Patch by Pablo Galindo.

@item 
bpo-43517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43517}: Fix misdetection of circular imports when using @code{from pkg.mod
import attr}, which caused false positives in non-trivial multi-threaded
code.

@item 
bpo-43497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43497}: Emit SyntaxWarnings for assertions with tuple constants, this
is a regression introduced in python3.7

@item 
bpo-39316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39316}: Tracing now has correct line numbers for attribute accesses
when the attribute is on a different line from the object. Improves
debugging and profiling for multi-line method chains.

@item 
bpo-35883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35883}: Python no longer fails at startup with a fatal error if a
command line argument contains an invalid Unicode character. The
@ref{dc0,,Py_DecodeLocale()} function now escapes byte sequences which would
be decoded as Unicode characters outside the [U+0000; U+10ffff] range.

@item 
bpo-43410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43410}: Fix a bug that was causing the parser to crash when emitting
syntax errors when reading input from stdin. Patch by Pablo Galindo

@item 
bpo-43406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43406}: Fix a possible race condition where @code{PyErr_CheckSignals}
tries to execute a non-Python signal handler.

@item 
bpo-42128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42128}: Add @code{__match_args__} to @ref{13d7,,struct sequence objects}. Patch by Pablo Galindo.

@item 
bpo-43390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43390}: CPython now sets the @code{SA_ONSTACK} flag in @code{PyOS_setsig} for
the VM's default signal handlers.  This is friendlier to other in-process
code that an extension module or embedding use could pull in (such as
Golang's cgo) where tiny thread stacks are the norm and @code{sigaltstack()}
has been used to provide for signal handlers.  This is a no-op change for
the vast majority of processes that don't use sigaltstack.

@item 
bpo-43287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43287}: Speed up calls to @code{filter()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.

@item 
bpo-37448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37448}: Add a radix tree based memory map to track in-use obmalloc
arenas. Use to replace the old implementation of address_in_range(). The
radix tree approach makes it easy to increase pool sizes beyond the OS
page size. Boosting the pool and arena size allows obmalloc to handle a
significantly higher percentage of requests from its ultra-fast paths.

It also has the advantage of eliminating the memory unsanitary behavior of
the previous address_in_range(). The old address_in_range() was marked
with the annotations _Py_NO_SANITIZE_ADDRESS, _Py_NO_SANITIZE_THREAD, and
_Py_NO_SANITIZE_MEMORY. Those annotations are no longer needed.

To disable the radix tree map, set a preprocessor flag as follows:
@code{-DWITH_PYMALLOC_RADIX_TREE=0}.

Co-authored-by: Tim Peters <@email{tim.peters@@gmail.com}>

@item 
bpo-29988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29988}: Only handle asynchronous exceptions and requests to drop the
GIL when returning from a call or on the back edges of loops. Makes sure
that @ref{1518,,__exit__()} is always called in with statements, even
for interrupts.
@end itemize

@node ライブラリ<121>,ドキュメント<38>,Core and Builtins<118>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id526}@anchor{1c8e}
@subsubsection ライブラリ



@itemize -

@item 
bpo-43720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43720}: Document various stdlib deprecations in imp, pkgutil, and
importlib.util for removal in Python 3.12.

@item 
bpo-43433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43433}: @ref{c4c,,xmlrpc.client.ServerProxy} no longer ignores query and
fragment in the URL of the server.

@item 
bpo-31956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31956}: The @ref{9e1,,index()} method of @ref{4be,,array.array}
now has optional `start' and `stop' parameters.

@item 
bpo-40066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40066}: Enum: adjust @code{repr()} to show only enum and member name (not
value, nor angle brackets) and @code{str()} to show only member name.  Update
and improve documentation to match.

@item 
bpo-42136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42136}: Deprecate all module_repr() methods found in importlib as their
use is being phased out by Python 3.12.

@item 
bpo-35930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35930}: Raising an exception raised in a "future" instance will create
reference cycles.

@item 
bpo-41369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41369}: Finish updating the vendored libmpdec to version 2.5.1.  Patch
by Stefan Krah.

@item 
bpo-43422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43422}: Revert the _decimal C API which was added in bpo-41324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41324}.

@item 
bpo-43577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43577}: Fix deadlock when using @ref{357,,ssl.SSLContext} debug callback
with @ref{1c8f,,ssl.SSLContext.sni_callback()}.

@item 
bpo-43571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43571}: It's now possible to create MPTCP sockets with IPPROTO_MPTCP

@item 
bpo-43542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43542}: @code{image/heic} and @code{image/heif} were added to
@ref{93,,mimetypes}.

@item 
bpo-40645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40645}: The @ref{6e,,hmac} module now uses OpenSSL's HMAC implementation
when digestmod argument is a hash name or builtin hash function.

@item 
bpo-43510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43510}: Implement 
@geindex Python Enhancement Proposals; PEP 597
PEP 597@footnote{https://peps.python.org/pep-0597/}: Add @code{EncodingWarning} warning, @code{-X
warn_default_encoding} option, 
@geindex PYTHONWARNDEFAULTENCODING
@geindex 環境変数; PYTHONWARNDEFAULTENCODING
@ref{9bf,,PYTHONWARNDEFAULTENCODING}
environment variable and @code{encoding="locale"} argument value.

@item 
bpo-43521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43521}: @code{ast.unparse} can now render NaNs and empty sets.

@item 
bpo-42914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42914}: @ref{a29,,pprint.pprint()} gains a new boolean
@code{underscore_numbers} optional argument to emit integers with thousands
separated by an underscore character for improved readability (for example
@code{1_000_000} instead of @code{1000000}).

@item 
bpo-41361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41361}: @ref{1c90,,rotate()} calls are now slightly faster
due to faster argument parsing.

@item 
bpo-43423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43423}: @code{subprocess.communicate()} no longer raises an IndexError
when there is an empty stdout or stderr IO buffer during a timeout on
Windows.

@item 
bpo-27820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27820}: Fixed long-standing bug of smtplib.SMTP where doing AUTH LOGIN
with initial_response_ok=False will fail.

The cause is that SMTP.auth_login _always_ returns a password if provided
with a challenge string, thus non-compliant with the standard for AUTH
LOGIN.

Also fixes bug with the test for smtpd.

@item 
bpo-43445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43445}: Add frozen modules to @ref{a42,,sys.stdlib_module_names}. For
example, add @code{"_frozen_importlib"} and @code{"_frozen_importlib_external"}
names.

@item 
bpo-43245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43245}: Add keyword arguments support to @code{ChainMap.new_child()}.

@item 
bpo-29982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29982}: Add optional parameter `ignore_cleanup_errors' to
@ref{144c,,tempfile.TemporaryDirectory()} and allow multiple @code{cleanup()}
attempts. Contributed by C.A.M. Gerlach.

@item 
bpo-43428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43428}: Include changes from importlib_metadata 3.7@footnote{https://importlib-metadata.readthedocs.io/en/latest/history.html#v3-7-0}:

Performance enhancements to distribution discovery.

@code{entry_points} only returns unique distributions.

Introduces new @code{EntryPoints} object for containing a set of entry points
with convenience methods for selecting entry points by group or name.
@code{entry_points} now returns this object if selection parameters are
supplied but continues to return a dict object for compatibility. Users
are encouraged to rely on the selection interface. The dict object result
is likely to be deprecated in the future.

Added packages_distributions function to return a mapping of packages to
the distributions that provide them.

@item 
bpo-43332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43332}: Improves the networking efficiency of @ref{73,,http.client} when
using a proxy via @code{set_tunnel()}.  Fewer small send
calls are made during connection setup.

@item 
bpo-43420@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43420}: Improve performance of @ref{213,,fractions.Fraction} arithmetics
for large components.  Contributed by Sergey B. Kirpichev.

@item 
bpo-43356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43356}: Allow passing a signal number to @code{_thread.interrupt_main()}.

@item 
bpo-43399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43399}: Fix @code{ElementTree.extend} not working on iterators when using
the Python implementation

@item 
bpo-43369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43369}: Improve @ref{d4,,sqlite3} error handling: If
@code{sqlite3_column_text()} and @code{sqlite3_column_blob()} set
@code{SQLITE_NOMEM}, @ref{179e,,MemoryError} is now raised. Patch by Erlend E.
Aasland.

@item 
bpo-43368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43368}: Fix a regression introduced in PR 24562, where an empty
bytestring was fetched as @code{None} instead of @code{b'@w{'}} in @ref{d4,,sqlite3}.
Patch by Mariusz Felisiak.

@item 
bpo-41282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41282}: Fixed stacklevel of @code{DeprecationWarning} emitted from
@code{import distutils}.

@item 
bpo-42129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42129}: @code{importlib.resources} now honors namespace packages, merging
resources from each location in the namespace as introduced in
@code{importlib_resources} 3.2 and including incidental changes through
5.0.3.

@item 
bpo-43295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43295}: @ref{1950,,datetime.datetime.strptime()} now raises @code{ValueError}
instead of @code{IndexError} when matching @code{'z'} with the @code{%z} format
specifier.

@item 
bpo-43125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43125}: Return empty string if base64mime.body_encode receive empty
bytes

@item 
bpo-43084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43084}: @ref{1c91,,curses.window.enclose()} returns now @code{True} or @code{False}
(as was documented) instead of @code{1} or @code{0}.

@item 
bpo-42994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42994}: Add MIME types for opus, AAC, 3gpp and 3gpp2

@item 
bpo-14678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14678}: Add an invalidate_caches() method to the zipimport.zipimporter
class to support importlib.invalidate_caches(). Patch by Desmond Cheong.

@item 
bpo-42782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42782}: Fail fast in @ref{c51,,shutil.move()} to avoid creating destination
directories on failure.

@item 
bpo-40066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40066}: Enum's @code{repr()} and @code{str()} have changed: @code{repr()} is now
`EnumClass.MemberName' and @code{str()} is `MemberName'.  Additionally,
stdlib Enum's whose contents are available as module attributes, such as
@code{RegexFlag.IGNORECASE}, have their @code{repr()} as `module.name', e.g.
@code{re.IGNORECASE}.

@item 
bpo-26053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26053}: Fixed bug where the @ref{aa,,pdb} interactive run command echoed
the args from the shell command line, even if those have been overridden
at the pdb prompt.

@item 
bpo-24160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24160}: Fixed bug where breakpoints did not persist across multiple
debugger sessions in @ref{aa,,pdb}'s interactive mode.

@item 
bpo-40701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40701}: When the @ref{1c92,,tempfile.tempdir} global variable is set to a
value of type bytes, it is now handled consistently.  Previously
exceptions could be raised from some tempfile APIs when the directory did
not already exist in this situation.  Also ensures that the
@ref{1c93,,tempfile.gettempdir()} and @ref{1c94,,tempfile.gettempdirb()} functions
`always' return @code{str} and @code{bytes} respectively.

@item 
bpo-39342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39342}: Expose @code{X509_V_FLAG_ALLOW_PROXY_CERTS} as
@ref{1c95,,VERIFY_ALLOW_PROXY_CERTS} to allow proxy certificate
validation as explained in
@indicateurl{https://docs.openssl.org/1.1.1/man7/proxy-certificates/}.

@item 
bpo-31861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31861}: Add builtins.aiter and builtins.anext. Patch by Joshua Bronson
(@@jab), Daniel Pope (@@lordmauve), and Justin Wang (@@justin39).
@end itemize

@node ドキュメント<38>,テスト<37>,ライブラリ<121>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id527}@anchor{1c96}
@subsubsection ドキュメント



@itemize -

@item 
bpo-43199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43199}: Answer "Why is there no goto?" in the Design and History FAQ.

@item 
bpo-43407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43407}: Clarified that a result from @ref{55c,,time.monotonic()},
@ref{c7a,,time.perf_counter()}, @ref{c7b,,time.process_time()}, or
@ref{b30,,time.thread_time()} can be compared with the result from any
following call to the same function - not just the next immediate call.

@item 
bpo-43354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43354}: Fix type documentation for @code{Fault.faultCode}; the type has to
be @code{int} instead of @code{str}.

@item 
bpo-41933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41933}: Clarified wording of s * n in the Common Sequence Operations
@end itemize

@node テスト<37>,ビルド<44>,ドキュメント<38>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id528}@anchor{1c97}
@subsubsection テスト



@itemize -

@item 
bpo-37945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37945}: Fix test_getsetlocale_issue1813() of test_locale: skip the test
if @code{setlocale()} fails. Patch by Victor Stinner.

@item 
bpo-41561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41561}: Add workaround for Ubuntu's custom OpenSSL security level
policy.
@end itemize

@node ビルド<44>,Windows<39>,テスト<37>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id529}@anchor{1c98}
@subsubsection ビルド



@itemize -

@item 
bpo-43179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43179}: Introduce and correctly use ALIGNOF_X in place of SIZEOF_X for
alignment-related code in optimized string routines. Patch by Jessica
Clarke.

@item 
bpo-43631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43631}: Update macOS, Windows, and CI to OpenSSL 1.1.1k.

@item 
bpo-43617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43617}: Improve configure.ac: Check for presence of autoconf-archive
package and remove our copies of M4 macros.

@item 
bpo-43466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43466}: The @code{configure} script now supports @code{--with-openssl-rpath}
option.

@item 
bpo-43372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43372}: Use @code{_freeze_importlib} to generate code for the
@code{__hello__} module. This approach ensures the code matches the
interpreter version.  Previously, PYTHON_FOR_REGEN was used to generate
the code, which might be wrong.  The marshal format for code objects has
changed with bpo-42246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42246}, commit 877df851. Update the code and the expected
code sizes in ctypes test_frozentable.
@end itemize

@node Windows<39>,IDLE<21>,ビルド<44>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id530}@anchor{1c99}
@subsubsection Windows



@itemize -

@item 
bpo-43440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43440}: Build @ref{d4,,sqlite3} with the @code{R*Tree} module enabled. Patch
by Erlend E. Aasland.
@end itemize

@node IDLE<21>,C API<39>,Windows<39>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id531}@anchor{1c9a}
@subsubsection IDLE



@itemize -

@item 
bpo-42225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42225}: Document that IDLE can fail on Unix either from misconfigured
IP masquerade rules or failure displaying complex colored (non-ascii)
characters.
@end itemize

@node C API<39>,,IDLE<21>,Python 3 10 0 alpha 7
@anchor{whatsnew/changelog id532}@anchor{1c9b}
@subsubsection C API



@itemize -

@item 
bpo-43688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43688}: The limited C API is now supported if Python is built in debug
mode (if the @code{Py_DEBUG} macro is defined). In the limited C API, the
@ref{78f,,Py_INCREF()} and @ref{790,,Py_DECREF()} functions are now implemented
as opaque function calls, rather than accessing directly the
@ref{a9f,,PyObject.ob_refcnt} member, if Python is built in debug mode
and the @code{Py_LIMITED_API} macro targets Python 3.10 or newer. It became
possible to support the limited C API in debug mode because the
@ref{5df,,PyObject} structure is the same in release and debug mode since
Python 3.8 (see bpo-36465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36465}).

The limited C API is still not supported in the @code{--with-trace-refs}
special build (@code{Py_TRACE_REFS} macro).

Patch by Victor Stinner.

@item 
bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}: Remove the @code{pyarena.h} header file with functions:


@itemize *

@item 
@code{PyArena_New()}

@item 
@code{PyArena_Free()}

@item 
@code{PyArena_Malloc()}

@item 
@code{PyArena_AddPyObject()}
@end itemize

These functions were undocumented, excluded from the limited C API, and
were only used internally by the compiler. Patch by Victor Stinner.

@item 
bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}: Remove the compiler and parser functions using @code{struct _mod}
type, because the public AST C API was removed:


@itemize *

@item 
@code{PyAST_Compile()}

@item 
@code{PyAST_CompileEx()}

@item 
@code{PyAST_CompileObject()}

@item 
@code{PyFuture_FromAST()}

@item 
@code{PyFuture_FromASTObject()}

@item 
@code{PyParser_ASTFromFile()}

@item 
@code{PyParser_ASTFromFileObject()}

@item 
@code{PyParser_ASTFromFilename()}

@item 
@code{PyParser_ASTFromString()}

@item 
@code{PyParser_ASTFromStringObject()}
@end itemize

These functions were undocumented and excluded from the limited C API.
Patch by Victor Stinner.

@item 
bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}: Remove @code{ast.h}, @code{asdl.h}, and @code{Python-ast.h} header
files. These functions were undocumented and excluded from the limited C
API. Most names defined by these header files were not prefixed by @code{Py}
and so could create names conflicts. For example, @code{Python-ast.h} defined
a @code{Yield} macro which was conflict with the @code{Yield} name used by the
Windows @code{<winbase.h>} header. Use the Python @ref{9,,ast} module instead.
Patch by Victor Stinner.

@item 
bpo-43541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43541}: Fix a @code{PyEval_EvalCodeEx()} regression: fix reference
counting on builtins. Patch by Victor Stinner.

@item 
bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}: Remove the @code{symtable.h} header file and the undocumented
functions:


@itemize *

@item 
@code{PyST_GetScope()}

@item 
@code{PySymtable_Build()}

@item 
@code{PySymtable_BuildObject()}

@item 
@code{PySymtable_Free()}

@item 
@code{Py_SymtableString()}

@item 
@code{Py_SymtableStringObject()}
@end itemize

The @code{Py_SymtableString()} function was part the stable ABI by mistake
but it could not be used, because the @code{symtable.h} header file was
excluded from the limited C API.

The Python @ref{de,,symtable} module remains available and is unchanged.

Patch by Victor Stinner.

@item 
bpo-43244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43244}: Remove the @code{PyAST_Validate()} function. It is no longer
possible to build a AST object (@code{mod_ty} type) with the public C API.
The function was already excluded from the limited C API (
@geindex Python Enhancement Proposals; PEP 384
PEP 384@footnote{https://peps.python.org/pep-0384/}).
Patch by Victor Stinner.
@end itemize

@node Python 3 10 0 alpha 6,Python 3 10 0 alpha 5,Python 3 10 0 alpha 7,変更履歴
@anchor{whatsnew/changelog python-3-10-0-alpha-6}@anchor{1c9c}
@subsection Python 3.10.0 alpha 6


`Release date: 2021-03-01'

@menu
* セキュリティ: セキュリティ<32>. 
* Core and Builtins: Core and Builtins<119>. 
* ライブラリ: ライブラリ<122>. 
* Core and Builtins: Core and Builtins<120>. 
* ライブラリ: ライブラリ<123>. 
* Core and Builtins: Core and Builtins<121>. 
* ライブラリ: ライブラリ<124>. 
* ドキュメント: ドキュメント<39>. 
* テスト: テスト<38>. 
* ビルド: ビルド<45>. 
* Windows: Windows<40>. 
* macOS: macOS<29>. 
* IDLE: IDLE<22>. 
* C API: C API<40>. 

@end menu

@node セキュリティ<32>,Core and Builtins<119>,,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id533}@anchor{1c9d}
@subsubsection セキュリティ



@itemize -

@item 
bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}: Fix web cache poisoning vulnerability by defaulting the query
args separator to @code{&}, and allowing the user to choose a custom
separator.
@end itemize

@node Core and Builtins<119>,ライブラリ<122>,セキュリティ<32>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id534}@anchor{1c9e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43321}: Fix @code{SystemError} raised when @code{PyArg_Parse*()} is used with
@code{#} but without @code{PY_SSIZE_T_CLEAN} defined.

@item 
bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}: @code{PyArg_Parse*()} functions now emits @code{DeprecationWarning}
when @code{u} or @code{Z} format is used. See 
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/} for detail.

@item 
bpo-43277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43277}: Add a new @ref{a9d,,PySet_CheckExact()} function to the C-API to
check if an object is an instance of @ref{184,,set} but not an instance of a
subtype. Patch by Pablo Galindo.

@item 
bpo-42990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42990}: The @ref{a83,,types.FunctionType} constructor now inherits the
current builtins if the `globals' dictionary has no @code{"__builtins__"}
key, rather than using @code{@{"None": None@}} as builtins: same behavior as
@ref{4a3,,eval()} and @ref{4a2,,exec()} functions. Defining a function with @code{def
function(...): ...} in Python is not affected, globals cannot be
overridden with this syntax: it also inherits the current builtins. Patch
by Victor Stinner.

@item 
bpo-42990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42990}: Functions have a new @code{__builtins__} attribute which is used
to look for builtin symbols when a function is executed, instead of
looking into @code{__globals__['__builtins__']}. Patch by Mark Shannon and
Victor Stinner.

@item 
bpo-43149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43149}: Improve the error message in the parser for exception groups
without parentheses. Patch by Pablo Galindo.

@item 
bpo-43121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43121}: Fixed an incorrect @ref{18e,,SyntaxError} message for missing comma
in literals. Patch by Pablo Galindo.
@end itemize

@node ライブラリ<122>,Core and Builtins<120>,Core and Builtins<119>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id535}@anchor{1c9f}
@subsubsection ライブラリ



@itemize -

@item 
bpo-42819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42819}: @ref{bf,,readline}: Explicitly disable bracketed paste in the
interactive interpreter, even if it's set in the inputrc, is enabled by
default (eg GNU Readline 8.1), or a user calls
@code{readline.read_init_file()}. The Python REPL has not implemented
bracketed paste support. Also, bracketed mode writes the @code{"\x1b[?2004h"}
escape sequence into stdout which causes test failures in applications
that don't support it. It can still be explicitly enabled by calling
@code{readline.parse_and_bind("set enable-bracketed-paste on")}. Patch by
Dustin Rodrigues.
@end itemize

@node Core and Builtins<120>,ライブラリ<123>,ライブラリ<122>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id536}@anchor{1ca0}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42808}: Simple calls to @code{type(object)} are now faster due to the
@code{vectorcall} calling convention. Patch by Dennis Sweeney.

@item 
bpo-42217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42217}: Make the compiler merges same co_code and co_linetable objects
in a module like already did for co_consts.

@item 
bpo-41972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41972}: Substring search functions such as @code{str1 in str2} and
@code{str2.find(str1)} now sometimes use the "Two-Way" string comparison
algorithm to avoid quadratic behavior on long strings.

@item 
bpo-42128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42128}: Implement 
@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/} (structural pattern matching). Patch by
Brandt Bucher.
@end itemize

@node ライブラリ<123>,Core and Builtins<121>,Core and Builtins<120>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id537}@anchor{1ca1}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40692}: In the @ref{1d6,,concurrent.futures.ProcessPoolExecutor},
validate that @code{multiprocess.synchronize()} is available on a given
platform and rely on that check in the @ref{24,,concurrent.futures} test
suite so we can run tests that are unrelated to
@code{ProcessPoolExecutor} on those platforms.
@end itemize

@node Core and Builtins<121>,ライブラリ<124>,ライブラリ<123>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id538}@anchor{1ca2}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-38302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38302}: If @ref{9d3,,object.__ipow__()} returns @ref{1a2,,NotImplemented}, the
operator will correctly fall back to @ref{9d4,,object.__pow__()} and
@ref{1a5,,object.__rpow__()} as expected.
@end itemize

@node ライブラリ<124>,ドキュメント<39>,Core and Builtins<121>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id539}@anchor{1ca3}
@subsubsection ライブラリ



@itemize -

@item 
bpo-43316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43316}: The @code{python -m gzip} command line application now properly
fails when detecting an unsupported extension. It exits with a non-zero
exit code and prints an error message to stderr.

@item 
bpo-43317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43317}: Set the chunk size for the @code{gzip} module main function to
io.DEFAULT_BUFFER_SIZE. This is slightly faster than the 1024 bytes
constant that was used previously.

@item 
bpo-43146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43146}: Handle None in single-arg versions of
@ref{a4f,,print_exception()} and
@ref{a4d,,format_exception()}.

@item 
bpo-43260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43260}: Fix TextIOWrapper can not flush internal buffer forever after
very large text is written.

@item 
bpo-43258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43258}: Prevent needless allocation of @ref{d4,,sqlite3} aggregate
function context when no rows match an aggregate query. Patch by Erlend E.
Aasland.

@item 
bpo-43251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43251}: Improve @ref{d4,,sqlite3} error handling:
@code{sqlite3_column_name()} failures now result in @ref{179e,,MemoryError}. Patch
by Erlend E. Aasland.

@item 
bpo-40956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40956}: Fix segfault in @ref{d73,,sqlite3.Connection.backup()} if no
argument was provided. The regression was introduced by PR 23838. Patch by
Erlend E. Aasland.

@item 
bpo-43172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43172}: The readline module now passes its tests when built directly
against libedit. Existing irreconcilable API differences remain in
@ref{1ca4,,readline.get_begidx()} and @ref{1ca5,,readline.get_endidx()} behavior based
on libreadline vs libedit use.

@item 
bpo-43163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43163}: Fix a bug in @ref{1d,,codeop} that was causing it to not ask for
more input when multi-line snippets have unclosed parentheses. Patch by
Pablo Galindo

@item 
bpo-43162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43162}: deprecate unsupported ability to access enum members as
attributes of other enum members

@item 
bpo-43146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43146}: Fix recent regression in None argument handling in
@ref{104,,traceback} module functions.

@item 
bpo-43102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43102}: The namedtuple __new__ method had its __builtins__ set to None
instead of an actual dictionary.  This created problems for introspection
tools.

@item 
bpo-43106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43106}: Added @ref{a1b,,O_EVTONLY}, @ref{a1c,,O_FSYNC},
@ref{a1d,,O_SYMLINK} and @ref{a1e,,O_NOFOLLOW_ANY} for macOS. Patch by
Donghee Na.

@item 
bpo-42960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42960}: Adds @ref{1ca6,,resource.RLIMIT_KQUEUES} constant from FreeBSD to
the @ref{c1,,resource} module.

@item 
bpo-42151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42151}: Make the pure Python implementation of
@ref{12b,,xml.etree.ElementTree} behave the same as the C implementation
(@code{_elementree}) regarding default attribute values (by not setting
@code{specified_attributes=1}).

@item 
bpo-29753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29753}: In ctypes, now packed bitfields are calculated properly and the
first item of packed bitfields is now shrank correctly.
@end itemize

@node ドキュメント<39>,テスト<38>,ライブラリ<124>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id540}@anchor{1ca7}
@subsubsection ドキュメント



@itemize -

@item 
bpo-27646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27646}: Clarify that 'yield from <expr>' works with any iterable, not
just iterators.

@item 
bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}: Update some deprecated unicode APIs which are documented as
"will be removed in 4.0" to "3.12". See 
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/} for detail.
@end itemize

@node テスト<38>,ビルド<45>,ドキュメント<39>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id541}@anchor{1ca8}
@subsubsection テスト



@itemize -

@item 
bpo-43288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43288}: Fix test_importlib to correctly skip Unicode file tests if the
filesystem does not support them.
@end itemize

@node ビルド<45>,Windows<40>,テスト<38>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id542}@anchor{1ca9}
@subsubsection ビルド



@itemize -

@item 
bpo-43174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43174}: Windows build now uses @code{/utf-8} compiler option.

@item 
bpo-43103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43103}: Add a new configure @code{--without-static-libpython} option to
not build the @code{libpythonMAJOR.MINOR.a} static library and not install
the @code{python.o} object file.

@item 
bpo-13501@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13501}: The configure script can now use `libedit' instead of
`readline' with the command line option @code{--with-readline=editline}.

@item 
bpo-42603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42603}: Make configure script use pkg-config to detect the location of
Tcl/Tk headers and libraries, used to build tkinter.

On macOS, a Tcl/Tk configuration provided by pkg-config will be preferred
over Tcl/Tk frameworks installed in @code{/@{System/,@}Library/Frameworks}. If
both exist and the latter is preferred, the appropriate @code{--with-tcltk-*}
configuration options need to be explicitly set.

@item 
bpo-39448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39448}: Add the "regen-frozen" makefile target that regenerates the
code for the frozen @code{__hello__} module.
@end itemize

@node Windows<40>,macOS<29>,ビルド<45>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id543}@anchor{1caa}
@subsubsection Windows



@itemize -

@item 
bpo-43155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43155}: @ref{1cab,,PyCMethod_New()} is now present in @code{python3.lib}.
@end itemize

@node macOS<29>,IDLE<22>,Windows<40>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id544}@anchor{1cac}
@subsubsection macOS



@itemize -

@item 
bpo-41837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41837}: Update macOS installer build to use OpenSSL 1.1.1j.
@end itemize

@node IDLE<22>,C API<40>,macOS<29>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id545}@anchor{1cad}
@subsubsection IDLE



@itemize -

@item 
bpo-43283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43283}: Document why printing to IDLE's Shell is often slower than
printing to a system terminal and that it can be made faster by
pre-formatting a single string before printing.
@end itemize

@node C API<40>,,IDLE<22>,Python 3 10 0 alpha 6
@anchor{whatsnew/changelog id546}@anchor{1cae}
@subsubsection C API



@itemize -

@item 
bpo-43278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43278}: Always put compiler and system information on the first line of
the REPL welcome message.

@item 
bpo-43270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43270}: Remove the private @code{_PyErr_OCCURRED()} macro: use the public
@ref{1caf,,PyErr_Occurred()} function instead.

@item 
bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}: Move odictobject.h, parser_interface.h, picklebufobject.h,
pydebug.h, and pyfpe.h into the cpython/ directory. They must not be
included directly, as they are already included by Python.h: @ref{987,,Include Files}.

@item 
bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}: Move pyarena.h, pyctype.h, and pytime.h into the cpython/
directory. They must not be included directly, as they are already
included by Python.h: @ref{987,,Include Files}.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: @ref{c5b,,PyExceptionClass_Name()} is now always declared as a
function, in order to hide implementation details. The macro accessed
@ref{1cb0,,PyTypeObject.tp_name} directly.  Patch by Erlend E. Aasland.

@item 
bpo-43239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43239}: The @ref{1cb1,,PyCFunction_New()} function is now exported in the
ABI when compiled with @code{-fvisibility=hidden}.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: @ref{1cb2,,PyIter_Check()} is now always declared as a function, in
order to hide implementation details. The macro accessed
@ref{1709,,PyTypeObject.tp_iternext} directly. Patch by Erlend E. Aasland.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Convert @ref{1cb3,,PyDescr_IsData()} macro to a function to hide
implementation details: The macro accessed
@ref{1cb4,,PyTypeObject.tp_descr_set} directly. Patch by Erlend E.
Aasland.

@item 
bpo-43181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43181}: Convert @ref{1cb5,,PyObject_TypeCheck()} macro to a static inline
function. Patch by Erlend E. Aasland.
@end itemize

@node Python 3 10 0 alpha 5,Python 3 10 0 alpha 4,Python 3 10 0 alpha 6,変更履歴
@anchor{whatsnew/changelog python-3-10-0-alpha-5}@anchor{1cb6}
@subsection Python 3.10.0 alpha 5


`Release date: 2021-02-02'

@menu
* セキュリティ: セキュリティ<33>. 
* Core and Builtins: Core and Builtins<122>. 
* ライブラリ: ライブラリ<125>. 
* Core and Builtins: Core and Builtins<123>. 
* ライブラリ: ライブラリ<126>. 
* ドキュメント: ドキュメント<40>. 
* テスト: テスト<39>. 
* ビルド: ビルド<46>. 
* Windows: Windows<41>. 
* macOS: macOS<30>. 
* IDLE: IDLE<23>. 
* C API: C API<41>. 

@end menu

@node セキュリティ<33>,Core and Builtins<122>,,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id547}@anchor{1cb7}
@subsubsection セキュリティ



@itemize -

@item 
bpo-42938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42938}: Avoid static buffers when computing the repr of
@ref{1cb8,,ctypes.c_double} and @ref{1cb9,,ctypes.c_longdouble} values.
@end itemize

@node Core and Builtins<122>,ライブラリ<125>,セキュリティ<33>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id548}@anchor{1cba}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42990}: Refactor the @code{PyEval_} family of functions.


@itemize *

@item 
An new function @code{_PyEval_Vector} is added to simplify calls to Python from C.

@item 
@code{_PyEval_EvalCodeWithName} is removed

@item 
@code{PyEval_EvalCodeEx} is retained as part of the API, but is not used internally
@end itemize

@item 
bpo-38631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38631}: Replace @ref{b7a,,Py_FatalError()} calls in the compiler with
regular @ref{795,,SystemError} exceptions. Patch by Victor Stinner.

@item 
bpo-42997@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42997}: Improve error message for missing ":" before blocks. Patch by
Pablo Galindo.

@item 
bpo-43017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43017}: Improve error message in the parser when using un-parenthesised
tuples in comprehensions. Patch by Pablo Galindo.

@item 
bpo-42986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42986}: Fix parser crash when reporting syntax errors in f-string with
newlines. Patch by Pablo Galindo.

@item 
bpo-40176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40176}: Syntax errors for unterminated string literals now point to the
start of the string instead of reporting EOF/EOL.

@item 
bpo-42927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42927}: The inline cache for @code{LOAD_ATTR} now also optimizes access to
attributes defined by @code{__slots__}. This makes reading such attribute up
to 30% faster.

@item 
bpo-42864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42864}: Improve error messages in the parser when parentheses are not
closed. Patch by Pablo Galindo.

@item 
bpo-42924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42924}: Fix @code{bytearray} repetition incorrectly copying data from the
start of the buffer, even if the data is offset within the buffer (e.g.
after reassigning a slice at the start of the @code{bytearray} to a shorter
byte string).

@item 
bpo-42882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42882}: Fix the @code{_PyUnicode_FromId()} function
(_Py_IDENTIFIER(var) API) when @ref{460,,Py_Initialize()} /
@ref{45f,,Py_Finalize()} is called multiple times: preserve
@code{_PyRuntime.unicode_ids.next_index} value.

@item 
bpo-42827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42827}: Fix a crash when working out the error line of a
@ref{18e,,SyntaxError} in some multi-line expressions.

@item 
bpo-42823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42823}: frame.f_lineno is correct even if frame.f_trace is set to True
@end itemize

@node ライブラリ<125>,Core and Builtins<123>,Core and Builtins<122>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id549}@anchor{1cbb}
@subsubsection ライブラリ



@itemize -

@item 
bpo-37324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37324}: Remove deprecated aliases to
@ref{a78,,コレクション抽象基底クラス} from the @ref{1e,,collections}
module.
@end itemize

@node Core and Builtins<123>,ライブラリ<126>,ライブラリ<125>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id550}@anchor{1cbc}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41994}: Fixed possible leak in @code{import} when @code{sys.modules} is not a
@code{dict}.

@item 
bpo-27772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27772}: In string formatting, preceding the `width' field by @code{'0'} no
longer affects the default alignment for strings.
@end itemize

@node ライブラリ<126>,ドキュメント<40>,Core and Builtins<123>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id551}@anchor{1cbd}
@subsubsection ライブラリ



@itemize -

@item 
bpo-43108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43108}: Fixed a reference leak in the @ref{2f,,curses} module. Patch by
Pablo Galindo

@item 
bpo-43077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43077}: Update the bundled pip to 21.0.1 and setuptools to 52.0.0.

@item 
bpo-41282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41282}: Deprecate @code{distutils} in documentation and add warning on
import.

@item 
bpo-43014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43014}: Improve performance of @ref{101,,tokenize} by 20-30%.  Patch by
Anthony Sottile.

@item 
bpo-42323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42323}: Fix @ref{6c0,,math.nextafter()} for NaN on AIX.

@item 
bpo-42955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42955}: Add @ref{a42,,sys.stdlib_module_names}, containing the list of the
standard library module names. Patch by Victor Stinner.

@item 
bpo-42944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42944}: Fix @code{random.Random.sample} when @code{counts} argument is not
@code{None}.

@item 
bpo-42934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42934}: Use @ref{563,,TracebackException}'s new @code{compact}
param in @ref{137f,,TestResult} to reduce time and memory consumed
by traceback formatting.

@item 
bpo-42931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42931}: Add @code{randbytes()} to @code{random.__all__}.

@item 
bpo-38250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38250}: [Enum] Flags consisting of a single bit are now considered
canonical, and will be the only flags returned from listing and iterating
over a Flag class or a Flag member.  Multi-bit flags are considered
aliases; they will be returned from lookups and operations that result in
their value. Iteration for both Flag and Flag members is in definition
order.

@item 
bpo-42877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42877}: Added the @code{compact} parameter to the constructor of
@ref{563,,traceback.TracebackException} to reduce time and memory for use
cases that only need to call @code{TracebackException.format()} and
@code{TracebackException.format_exception_only()}.

@item 
bpo-42923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42923}: The @ref{b7a,,Py_FatalError()} function and the
@ref{5c,,faulthandler} module now dump the list of extension modules on a
fatal error.

@item 
bpo-42848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42848}: Removed recursion from @ref{563,,TracebackException}
to allow it to handle long exception chains.

@item 
bpo-42901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42901}: [Enum] move member creation from @code{EnumMeta.__new__} to
@code{_proto_member.__set_name__}, allowing members to be created and visible
in @code{__init_subclass__}.

@item 
bpo-42780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42780}: Fix os.set_inheritable() for O_PATH file descriptors on Linux.

@item 
bpo-42866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42866}: Fix a reference leak in the @code{getcodec()} function of CJK
codecs. Patch by Victor Stinner.

@item 
bpo-42846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42846}: Convert the 6 CJK codec extension modules (_codecs_cn,
_codecs_hk, _codecs_iso2022, _codecs_jp, _codecs_kr and _codecs_tw) to the
multiphase initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}). Patch by Victor Stinner.

@item 
bpo-42851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42851}: remove __init_subclass__ support for Enum members

@item 
bpo-42834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42834}: Make internal caches of the @code{_json} module compatible with
subinterpreters.

@item 
bpo-41748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41748}: Fix HTMLParser parsing rules for element attributes containing
commas with spaces. Patch by Karl Dubost.

@item 
bpo-40810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40810}: Require SQLite 3.7.15 or newer. Patch by Erlend E. Aasland.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Convert the _multibytecodec extension module (CJK codecs) to
multi-phase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).  Patch by Erlend E. Aasland.

@item 
bpo-42802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42802}: The distutils @code{bdist_wininst} command deprecated in Python
3.8 has been removed. The distutils @code{bdist_wheel} command is now
recommended to distribute binary packages on Windows.

@item 
bpo-24464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24464}: The undocumented built-in function
@code{sqlite3.enable_shared_cache} is now deprecated, scheduled for removal
in Python 3.12.  Its use is strongly discouraged by the SQLite3
documentation.  Patch by Erlend E. Aasland.

@item 
bpo-42384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42384}: Make pdb populate sys.path[0] exactly the same as regular
python execution.

@item 
bpo-42383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42383}: Fix pdb: previously pdb would fail to restart the debugging
target if it was specified using a relative path and the current directory
changed.

@item 
bpo-42005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42005}: Fix CLI of @ref{2b,,cProfile} and @ref{b4,,profile} to catch
@ref{1267,,BrokenPipeError}.

@item 
bpo-41604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41604}: Don't decrement the reference count of the previous user_ptr
when set_panel_userptr fails.

@item 
bpo-41149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41149}: Allow executing callables that have a boolean value of
@code{False} when passed to @code{Threading.thread} as the target. Patch
contributed by Barney Stratford.

@item 
bpo-38307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38307}: Add an 'end_lineno' attribute to the Class and Function objects
that appear in the tree returned by pyclbr functions.  This and the
existing 'lineno' attribute define the extent of class and def statements.
Patch by Aviral Srivastava.

@item 
bpo-39273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39273}: The @code{BUTTON5_*} constants are now exposed in the
@ref{2f,,curses} module if available.

@item 
bpo-33289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33289}: Correct call to @ref{f7,,tkinter.colorchooser} to return RGB
triplet of ints instead of floats.  Patch by Cheryl Sabella.
@end itemize

@node ドキュメント<40>,テスト<39>,ライブラリ<126>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id552}@anchor{1cbe}
@subsubsection ドキュメント



@itemize -

@item 
bpo-40304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40304}: Fix doc for type(name, bases, dict).  Patch by Boris
Verkhovskiy and Éric Araujo.

@item 
bpo-42811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42811}: Updated importlib.util.resolve_name() doc to use
__spec__.parent instead of __package__. (Thanks Yair Frid.)
@end itemize

@node テスト<39>,ビルド<46>,ドキュメント<40>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id553}@anchor{1cbf}
@subsubsection テスト



@itemize -

@item 
bpo-40823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40823}: Use @code{unittest.TestLoader().loadTestsFromTestCase()} instead
of @code{unittest.makeSuite()} in @ref{d4,,sqlite3} tests. Patch by Erlend E.
Aasland.

@item 
bpo-40810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40810}: In @ref{d4,,sqlite3}, fix @code{CheckTraceCallbackContent} for SQLite
pre 3.7.15.
@end itemize

@node ビルド<46>,Windows<41>,テスト<39>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id554}@anchor{1cc0}
@subsubsection ビルド



@itemize -

@item 
bpo-43031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43031}: Pass @code{--timeout=$(TESTTIMEOUT)} option to the default profile
task @code{./python -m test --pgo} command.

@item 
bpo-36143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36143}: @code{make regen-all} now also runs @code{regen-keyword}. Patch by
Victor Stinner.

@item 
bpo-42874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42874}: Removed the grep -q and -E flags in the tzpath validation
section of the configure script to better accommodate users of some
platforms (specifically Solaris 10).

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Add library search path by wr-cc in add_cross_compiling_paths()
for VxWorks.

@item 
bpo-42856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42856}: Add @code{--with-wheel-pkg-dir=PATH} option to the @code{./configure}
script. If specified, the @ref{59,,ensurepip} module looks for @code{setuptools}
and @code{pip} wheel packages in this directory: if both are present, these
wheel packages are used instead of ensurepip bundled wheel packages.

Some Linux distribution packaging policies recommend against bundling
dependencies. For example, Fedora installs wheel packages in the
@code{/usr/share/python-wheels/} directory and don't install the
@code{ensurepip._bundled} package.
@end itemize

@node Windows<41>,macOS<30>,ビルド<46>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id555}@anchor{1cc1}
@subsubsection Windows



@itemize -

@item 
bpo-41837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41837}: Updated Windows installer to include OpenSSL 1.1.1i

@item 
bpo-42584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42584}: Upgrade Windows installer to use SQLite 3.34.0.
@end itemize

@node macOS<30>,IDLE<23>,Windows<41>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id556}@anchor{1cc2}
@subsubsection macOS



@itemize -

@item 
bpo-42504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42504}: Ensure that the value of
sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') is always a string,
even in when the value is parsable as an integer.
@end itemize

@node IDLE<23>,C API<41>,macOS<30>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id557}@anchor{1cc3}
@subsubsection IDLE



@itemize -

@item 
bpo-43008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43008}: Make IDLE invoke @ref{a0c,,sys.excepthook()} in normal, 2-process
mode. Patch by Ken Hilton.

@item 
bpo-33065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33065}: Fix problem debugging user classes with __repr__ method.

@item 
bpo-23544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23544}: Disable Debug=>Stack Viewer when user code is running or
Debugger is active, to prevent hang or crash.  Patch by Zackery Spytz.

@item 
bpo-32631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32631}: Finish zzdummy example extension module: make menu entries
work; add docstrings and tests with 100% coverage.
@end itemize

@node C API<41>,,IDLE<23>,Python 3 10 0 alpha 5
@anchor{whatsnew/changelog id558}@anchor{1cc4}
@subsubsection C API



@itemize -

@item 
bpo-42979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42979}: When Python is built in debug mode (with C assertions), calling
a type slot like @code{sq_length} (@code{__len__()} in Python) now fails with a
fatal error if the slot succeeded with an exception set, or failed with no
exception set. The error message contains the slot, the type name, and the
current exception (if an exception is set). Patch by Victor Stinner.

@item 
bpo-43030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43030}: Fixed a compiler warning in @ref{1cc5,,Py_UNICODE_ISSPACE()} on
platforms with signed @code{wchar_t}.
@end itemize

@node Python 3 10 0 alpha 4,Python 3 10 0 alpha 3,Python 3 10 0 alpha 5,変更履歴
@anchor{whatsnew/changelog python-3-10-0-alpha-4}@anchor{1cc6}
@subsection Python 3.10.0 alpha 4


`Release date: 2021-01-04'

@menu
* Core and Builtins: Core and Builtins<124>. 
* ライブラリ: ライブラリ<127>. 
* Core and Builtins: Core and Builtins<125>. 
* ライブラリ: ライブラリ<128>. 
* Core and Builtins: Core and Builtins<126>. 
* ライブラリ: ライブラリ<129>. 
* ドキュメント: ドキュメント<41>. 
* テスト: テスト<40>. 
* ビルド: ビルド<47>. 
* macOS: macOS<31>. 
* Tools/Demos: Tools/Demos<28>. 
* C API: C API<42>. 

@end menu

@node Core and Builtins<124>,ライブラリ<127>,,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id559}@anchor{1cc7}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42814}: Fix undefined behavior in @code{Objects/genericaliasobject.c}.

@item 
bpo-42806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42806}: Fix the column offsets for f-strings @ref{9,,ast} nodes
surrounded by parentheses and for nodes that spawn multiple lines. Patch
by Pablo Galindo.

@item 
bpo-40631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40631}: Fix regression where a single parenthesized starred expression
was a valid assignment target.

@item 
bpo-27794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27794}: Improve the error message for failed writes/deletes to property
objects. When possible, the attribute name is now shown. Patch provided by
Yurii Karabas.

@item 
bpo-42745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42745}: Make the type attribute lookup cache per-interpreter. Patch by
Victor Stinner.

@item 
bpo-42246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42246}: Jumps to jumps are not eliminated when it would break PEP 626.

@item 
bpo-42246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42246}: Make sure that the @code{f_lasti} and @code{f_lineno} attributes of a
frame are set correctly when an exception is raised or re-raised. Required
for PEP 626.

@item 
bpo-32381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32381}: The coding cookie (ex: @code{# coding: latin1}) is now ignored in
the command passed to the @ref{1a8,,-c} command line option. Patch by
Victor Stinner.

@item 
bpo-30858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30858}: Improve error location in expressions that contain assignments.
Patch by Pablo Galindo and Lysandros Nikolaou.

@item 
bpo-42615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42615}: Remove jump commands made redundant by the deletion of
unreachable bytecode blocks
@end itemize

@node ライブラリ<127>,Core and Builtins<125>,Core and Builtins<124>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id560}@anchor{1cc8}
@subsubsection ライブラリ



@itemize -

@item 
bpo-42639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42639}: Make the @ref{d,,atexit} module state per-interpreter. It is now
safe have more than one @ref{d,,atexit} module instance. Patch by Donghee Na
and Victor Stinner.
@end itemize

@node Core and Builtins<125>,ライブラリ<128>,ライブラリ<127>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id561}@anchor{1cc9}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32381}: Fix encoding name when running a @code{.pyc} file on Windows:
@ref{1cca,,PyRun_SimpleFileExFlags()} now uses the correct encoding to
decode the filename.
@end itemize

@node ライブラリ<128>,Core and Builtins<126>,Core and Builtins<125>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id562}@anchor{1ccb}
@subsubsection ライブラリ



@itemize -

@item 
bpo-42195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42195}: The @code{__args__} of the parameterized generics for
@ref{9c8,,typing.Callable} and @ref{9eb,,collections.abc.Callable} are now
consistent.  The @code{__args__} for @ref{9eb,,collections.abc.Callable} are
now flattened while @ref{9c8,,typing.Callable}'s have not changed.  To allow
this change, @ref{9ec,,types.GenericAlias} can now be subclassed and
@code{collections.abc.Callable}'s @code{__class_getitem__} will now return a
subclass of @code{types.GenericAlias}.  Tests for typing were also updated to
not subclass things like @code{Callable[..., T]} as that is not a valid base
class.  Finally, both @code{Callable}s no longer validate their
@code{argtypes}, in @code{Callable[[argtypes], resulttype]} to prepare for
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/}.  Patch by Ken Jin.

@item 
bpo-40137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40137}: Convert functools module to use
@ref{773,,PyType_FromModuleAndSpec()}.

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert @ref{8,,array} to use heap types, and establish module
state for these.

@item 
bpo-42008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42008}: Fix _random.Random() seeding.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{pyexpat} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).
@end itemize

@node Core and Builtins<126>,ライブラリ<129>,ライブラリ<128>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id563}@anchor{1ccc}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40521}: Make the Unicode dictionary of interned strings compatible with
subinterpreters. Patch by Victor Stinner.

@item 
bpo-39465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39465}: Make @code{_PyUnicode_FromId()} function compatible with
subinterpreters. Each interpreter now has an array of identifier objects
(interned strings decoded from UTF-8). Patch by Victor Stinner.
@end itemize

@node ライブラリ<129>,ドキュメント<41>,Core and Builtins<126>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id564}@anchor{1ccd}
@subsubsection ライブラリ



@itemize -

@item 
bpo-42257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42257}: Handle empty string in variable executable in
platform.libc_ver()

@item 
bpo-42772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42772}: randrange() now raises a TypeError when step is specified
without a stop argument.  Formerly, it silently ignored the step argument.

@item 
bpo-42759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42759}: Fixed equality comparison of @code{tkinter.Variable} and
@ref{1cce,,tkinter.font.Font}. Objects which belong to different Tcl
interpreters are now always different, even if they have the same name.

@item 
bpo-42756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42756}: Configure LMTP Unix-domain socket to use socket global default
timeout when a timeout is not explicitly provided.

@item 
bpo-23328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23328}: Allow / character in username, password fields on _PROXY
envars.

@item 
bpo-42740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42740}: @ref{2ac,,typing.get_args()} and @ref{2ab,,typing.get_origin()} now
support 
@geindex Python Enhancement Proposals; PEP 604
PEP 604@footnote{https://peps.python.org/pep-0604/} union types and 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} additions to @code{Callable}.

@item 
bpo-42655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42655}: @ref{dc,,subprocess} `extra_groups' is now correctly passed into
setgroups() system call.

@item 
bpo-42727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42727}: @code{EnumMeta.__prepare__} now accepts @code{**kwds} to properly
support @code{__init_subclass__}

@item 
bpo-38308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38308}: Add optional `weights' to `statistics.harmonic_mean()'.

@item 
bpo-42721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42721}: When simple query dialogs (@ref{fe,,tkinter.simpledialog}),
message boxes (@ref{fc,,tkinter.messagebox}) or color choose dialog
(@ref{f7,,tkinter.colorchooser}) are created without arguments `master' and
`parent', and the default root window is not yet created, and
@code{NoDefaultRoot()} was not called, a new temporal hidden root
window will be created automatically. It will not be set as the default
root window and will be destroyed right after closing the dialog window.
It will help to use these simple dialog windows in programs which do not
need other GUI.

@item 
bpo-25246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25246}: Optimized @ref{1ccf,,collections.deque.remove()}.

@item 
bpo-35728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35728}: Added a root parameter to @ref{1cd0,,tkinter.font.nametofont()}.

@item 
bpo-15303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15303}: @ref{f6,,tkinter} supports now widgets with boolean value False.

@item 
bpo-42681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42681}: Fixed range checks for color and pair numbers in @ref{2f,,curses}.

@item 
bpo-42685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42685}: Improved placing of simple query windows in Tkinter (such as
@ref{1cd1,,tkinter.simpledialog.askinteger()}). They are now centered at the
center of the parent window if it is specified and shown, otherwise at the
center of the screen.

@item 
bpo-9694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9694}: Argparse help no longer uses the confusing phrase, "optional
arguments". It uses "options" instead.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_thread} extension module to the multiphase
initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}) and convert its static types to heap
types.

@item 
bpo-37961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37961}: Fix crash in @code{tracemalloc.Traceback.__repr__()} (regressed
in Python 3.9).

@item 
bpo-42630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42630}: @ref{f6,,tkinter} functions and constructors which need a default
root window raise now @ref{244,,RuntimeError} with descriptive message instead
of obscure @ref{5f0,,AttributeError} or @ref{452,,NameError} if it is not created
yet or cannot be created automatically.

@item 
bpo-42639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42639}: @code{atexit._run_exitfuncs()} now logs callback exceptions
using @ref{507,,sys.unraisablehook}, rather than logging them directly into
@ref{b33,,sys.stderr} and raise the last exception.

@item 
bpo-42644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42644}: @code{logging.disable} will now validate the types and value of
its parameter. It also now accepts strings representing the levels (as
does @code{logging.setLevel}) instead of only the numerical values.

@item 
bpo-42639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42639}: At Python exit, if a callback registered with
@ref{a7e,,atexit.register()} fails, its exception is now logged. Previously,
only some exceptions were logged, and the last exception was always
silently ignored.

@item 
bpo-36541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36541}: Fixed lib2to3.pgen2 to be able to parse PEP-570 positional only
argument syntax.

@item 
bpo-42382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42382}: In @code{importlib.metadata}: -  @code{EntryPoint} objects now expose
a @code{.dist} object referencing the @code{Distribution} when constructed from
a @code{Distribution}. - Add support for package discovery under package
normalization rules. - The object returned by @code{metadata()} now has a
formally defined protocol called @code{PackageMetadata} with declared support
for the @code{.get_all()} method. - Synced with importlib_metadata 3.3.

@item 
bpo-41877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41877}: A check is added against misspellings of autospect, auto_spec
and set_spec being passed as arguments to patch, patch.object and
create_autospec.

@item 
bpo-39717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39717}: [tarfile] update nested exception raising to use @code{from None}
or @code{from e}

@item 
bpo-41877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41877}: AttributeError for suspected misspellings of assertions on
mocks are now pointing out that the cause are misspelled assertions and
also what to do if the misspelling is actually an intended attribute name.
The unittest.mock document is also updated to reflect the current set of
recognised misspellings.

@item 
bpo-41559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41559}: Implemented 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/}: added @code{ParamSpec} and @code{Concatenate}
to @ref{10a,,typing}.  Patch by Ken Jin.

@item 
bpo-42385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42385}: StrEnum: fix _generate_next_value_ to return a str

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Define THREAD_STACK_SIZE for VxWorks.

@item 
bpo-34750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34750}: [Enum] @code{_EnumDict.update()} is now supported.

@item 
bpo-42517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42517}: Enum: private names do not become members / do not generate
errors -- they remain normal attributes

@item 
bpo-42678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42678}: @code{Enum}: call @code{__init_subclass__} after members have been
added

@item 
bpo-28964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28964}: @ref{e12,,ast.literal_eval()} adds line number information (if
available) in error message for malformed nodes.

@item 
bpo-42470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42470}: @ref{94d,,random.sample()} no longer warns on a sequence which is
also a set.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: @code{posixpath.expanduser()} returns the input `path' unchanged
if user home directory is None on VxWorks.

@item 
bpo-42388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42388}: Fix subprocess.check_output(..., input=None) behavior when
text=True to be consistent with that of the documentation and
universal_newlines=True.

@item 
bpo-34463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34463}: Fixed discrepancy between @ref{104,,traceback} and the interpreter
in formatting of SyntaxError with lineno not set (@ref{104,,traceback} was
changed to match interpreter).

@item 
bpo-42393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42393}: Raise @ref{a81,,OverflowError} instead of silent truncation in
@ref{a80,,socket.ntohs()} and @ref{a7f,,socket.htons()}.  Silent truncation was
deprecated in Python 3.7. Patch by Erlend E. Aasland

@item 
bpo-42222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42222}: Harmonized @ref{a6b,,random.randrange()} argument handling to match
@ref{b3d,,range()}.


@itemize *

@item 
The integer test and conversion in @code{randrange()} now uses
@ref{1cd2,,operator.index()}.

@item 
Non-integer arguments to @code{randrange()} are deprecated.

@item 
The @code{ValueError} is deprecated in favor of a @code{TypeError}.

@item 
It now runs a little faster than before.
@end itemize

(Contributed by Raymond Hettinger and Serhiy Storchaka.)

@item 
bpo-42163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42163}: Restore compatibility for @code{uname_result} around deepcopy and
_replace.

@item 
bpo-42090@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42090}: @code{zipfile.Path.joinpath} now accepts arbitrary arguments, same
as @code{pathlib.Path.joinpath}.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the _csv module to the multi-phase initialization API
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-42059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42059}: @ref{332,,typing.TypedDict} types created using the alternative
call-style syntax now correctly respect the @code{total} keyword argument
when setting their @code{__required_keys__} and @code{__optional_keys__} class
attributes.

@item 
bpo-41960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41960}: Add @code{globalns} and @code{localns} parameters to the
@ref{22f,,inspect.signature()} and @ref{942,,inspect.Signature.from_callable()}.

@item 
bpo-41907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41907}: fix @code{format()} behavior for @code{IntFlag}

@item 
bpo-41891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41891}: Ensure asyncio.wait_for waits for task completion

@item 
bpo-24792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24792}: Fixed bug where @code{zipimporter} sometimes reports an
incorrect cause of import errors.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix site and sysconfig modules for VxWorks RTOS which has no
home directories.

@item 
bpo-41462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41462}: Add @ref{103a,,os.set_blocking()} support for VxWorks RTOS.

@item 
bpo-40219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40219}: Lowered @code{tkinter.ttk.LabeledScale} dummy widget to
prevent hiding part of the content label.

@item 
bpo-37193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37193}: Fixed memory leak in @code{socketserver.ThreadingMixIn} introduced
in Python 3.7.

@item 
bpo-39068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39068}: Fix initialization race condition in @code{a85encode()} and
@code{b85encode()} in @ref{f,,base64}. Patch by Brandon Stansbury.
@end itemize

@node ドキュメント<41>,テスト<40>,ライブラリ<129>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id565}@anchor{1cd3}
@subsubsection ドキュメント



@itemize -

@item 
bpo-17140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17140}: Add documentation for the
@ref{1cd4,,multiprocessing.pool.ThreadPool} class.

@item 
bpo-34398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34398}: Prominently feature listings from the glossary in documentation
search results. Patch by Ammar Askar.
@end itemize

@node テスト<40>,ビルド<47>,ドキュメント<41>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id566}@anchor{1cd5}
@subsubsection テスト



@itemize -

@item 
bpo-42794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42794}: Update test_nntplib to use official group name of news.aioe.org
for testing. Patch by Donghee Na.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Skip some asyncio tests on VxWorks.

@item 
bpo-42641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42641}: Enhance @code{test_select.test_select()}: it now takes 500
milliseconds rather than 10 seconds. Use Python rather than a shell to
make the test more portable.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Skip some tests in _test_all_chown_common() on VxWorks.

@item 
bpo-42199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42199}: Fix bytecode helper assertNotInBytecode.

@item 
bpo-41443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41443}: Add more attribute checking in test_posix.py

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Disable os.popen and impacted tests on VxWorks

@item 
bpo-41439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41439}: Port test_ssl and test_uuid to VxWorks RTOS.
@end itemize

@node ビルド<47>,macOS<31>,テスト<40>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id567}@anchor{1cd6}
@subsubsection ビルド



@itemize -

@item 
bpo-42692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42692}: Fix __builtin_available check on older compilers. Patch by
Joshua Root.

@item 
bpo-27640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27640}: Added @code{--disable-test-modules} option to the @code{configure}
script: don't build nor install test modules. Patch by Xavier de Gaye,
Thomas Petazzoni and Peixing Xin.

@item 
bpo-42604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42604}: Now all platforms use a value for the "EXT_SUFFIX" build
variable derived from SOABI (for instance in freeBSD, "EXT_SUFFIX" is now
".cpython-310d.so" instead of ".so"). Previously only Linux, Mac and
VxWorks were using a value for "EXT_SUFFIX" that included "SOABI".

@item 
bpo-42598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42598}: Fix implicit function declarations in configure which could
have resulted in incorrect configuration checks.  Patch contributed by
Joshua Root.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Enable libpython3.so for VxWorks.

@item 
bpo-29076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29076}: Add fish shell support to macOS installer.
@end itemize

@node macOS<31>,Tools/Demos<28>,ビルド<47>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id568}@anchor{1cd7}
@subsubsection macOS



@itemize -

@item 
bpo-42361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42361}: Update macOS installer build to use Tcl/Tk 8.6.11 (rc2,
expected to be final release).

@item 
bpo-41837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41837}: Update macOS installer build to use OpenSSL 1.1.1i.

@item 
bpo-42584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42584}: Update macOS installer to use SQLite 3.34.0.
@end itemize

@node Tools/Demos<28>,C API<42>,macOS<31>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id569}@anchor{1cd8}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-42726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42726}: Fixed Python 3 compatibility issue with gdb/libpython.py
handling of attribute dictionaries.

@item 
bpo-42613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42613}: Fix @code{freeze.py} tool to use the prope config and library
directories. Patch by Victor Stinner.
@end itemize

@node C API<42>,,Tools/Demos<28>,Python 3 10 0 alpha 4
@anchor{whatsnew/changelog id570}@anchor{1cd9}
@subsubsection C API



@itemize -

@item 
bpo-42591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42591}: Export the @code{Py_FrozenMain()} function: fix a Python 3.9.0
regression. Python 3.9 uses @code{-fvisibility=hidden} and the function was
not exported explicitly and so not exported.

@item 
bpo-32381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32381}: Remove the private @code{_Py_fopen()} function which is no
longer needed. Use @code{_Py_wfopen()} or @code{_Py_fopen_obj()}
instead. Patch by Victor Stinner.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{c1,,resource} extension module to module state

@item 
bpo-42111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42111}: Update the @code{xxlimited} module to be a better example of how
to use the limited C API.

@item 
bpo-40052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40052}: Fix an alignment build warning/error in function
@code{PyVectorcall_Function()}. Patch by Andreas Schneider, Antoine Pitrou
and Petr Viktorin.
@end itemize

@node Python 3 10 0 alpha 3,Python 3 10 0 alpha 2,Python 3 10 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-10-0-alpha-3}@anchor{1cda}
@subsection Python 3.10.0 alpha 3


`リリース日: 2020-12-07'

@menu
* セキュリティ: セキュリティ<34>. 
* Core and Builtins: Core and Builtins<127>. 
* ライブラリ: ライブラリ<130>. 
* Core and Builtins: Core and Builtins<128>. 
* ライブラリ: ライブラリ<131>. 
* Core and Builtins: Core and Builtins<129>. 
* ライブラリ: ライブラリ<132>. 
* Core and Builtins: Core and Builtins<130>. 
* ライブラリ: ライブラリ<133>. 
* ドキュメント: ドキュメント<42>. 
* テスト: テスト<41>. 
* ビルド: ビルド<48>. 
* Windows: Windows<42>. 
* macOS: macOS<32>. 
* IDLE: IDLE<24>. 
* Tools/Demos: Tools/Demos<29>. 
* C API: C API<43>. 

@end menu

@node セキュリティ<34>,Core and Builtins<127>,,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id571}@anchor{1cdb}
@subsubsection セキュリティ



@itemize -

@item 
bpo-40791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40791}: Add @code{volatile} to the accumulator variable in
@code{hmac.compare_digest}, making constant-time-defeating optimizations less
likely.
@end itemize

@node Core and Builtins<127>,ライブラリ<130>,セキュリティ<34>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id572}@anchor{1cdc}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42576}: @code{types.GenericAlias} will now raise a @code{TypeError} when
attempting to initialize with a keyword argument.  Previously, this would
cause the interpreter to crash if the interpreter was compiled with debug
symbols. This does not affect interpreters compiled for release.  Patch by
Ken Jin.

@item 
bpo-42536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42536}: Several built-in and standard library types now ensure that
their internal result tuples are always tracked by the @ref{17d8,,garbage collector}:


@itemize -

@item 
@ref{7f3,,collections.OrderedDict.items()}

@item 
@ref{9d2,,dict.items()}

@item 
@ref{169a,,enumerate()}

@item 
@ref{21a,,functools.reduce()}

@item 
@ref{1529,,itertools.combinations()}

@item 
@ref{1499,,itertools.combinations_with_replacement()}

@item 
@ref{1cdd,,itertools.permutations()}

@item 
@ref{152a,,itertools.product()}

@item 
@ref{14b6,,itertools.zip_longest()}

@item 
@ref{1a0,,zip()}
@end itemize

Previously, they could have become untracked by a prior garbage
collection. Patch by Brandt Bucher.

@item 
bpo-42500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42500}: Improve handling of exceptions near recursion limit. Converts a
number of Fatal Errors in RecursionErrors.

@item 
bpo-42246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42246}: PEP 626: After a return, the f_lineno attribute of a frame is
always the last line executed.

@item 
bpo-42435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42435}: Speed up comparison of bytes objects with non-bytes objects
when option @ref{7f9,,-b} is specified. Speed up comparison of bytarray
objects with non-buffer object.
@end itemize

@node ライブラリ<130>,Core and Builtins<128>,Core and Builtins<127>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id573}@anchor{1cde}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_warnings} extension module to the multi-phase
initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}). Patch by Victor Stinner.
@end itemize

@node Core and Builtins<128>,ライブラリ<131>,ライブラリ<130>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id574}@anchor{1cdf}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41686}: On Windows, the @code{SIGINT} event, @code{_PyOS_SigintEvent()}, is
now created even if Python is configured to not install signal handlers
(if @ref{abb,,PyConfig.install_signal_handlers} equals to 0, or
@code{Py_InitializeEx(0)}).

@item 
bpo-42381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42381}: Allow assignment expressions in set literals and set
comprehensions as per PEP 572. Patch by Pablo Galindo.

@item 
bpo-42202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42202}: Change function parameters annotations internal representation
to tuple of strings. Patch provided by Yurii Karabas.

@item 
bpo-42374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42374}: Fix a regression introduced by the new parser, where an
unparenthesized walrus operator was not allowed within generator
expressions.

@item 
bpo-42316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42316}: Allow an unparenthesized walrus in subscript indexes.

@item 
bpo-42349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42349}: Make sure that the compiler front-end produces a well-formed
control flow graph. Be more aggressive in the compiler back-end, as it is
now safe to do so.

@item 
bpo-42296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42296}: On Windows, fix a regression in signal handling which prevented
to interrupt a program using CTRL+C. The signal handler can be run in a
thread different than the Python thread, in which case the test deciding
if the thread can handle signals is wrong.

@item 
bpo-42332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42332}: @ref{9ec,,types.GenericAlias} objects can now be the targets of
weakrefs.

@item 
bpo-42282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42282}: Optimise constant subexpressions that appear as part of named
expressions (previously the AST optimiser did not descend into named
expressions). Patch by Nick Coghlan.

@item 
bpo-42266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42266}: Fixed a bug with the LOAD_ATTR opcode cache that was not
respecting monkey-patching a class-level attribute to make it a
descriptor. Patch by Pablo Galindo.
@end itemize

@node ライブラリ<131>,Core and Builtins<129>,Core and Builtins<128>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id575}@anchor{1ce0}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert @ref{bb,,queue} to use heap types.
@end itemize

@node Core and Builtins<129>,ライブラリ<132>,ライブラリ<131>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id576}@anchor{1ce1}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42246}: Improved accuracy of line tracing events and f_lineno attribute
of Frame objects. See PEP 626 for details.
@end itemize

@node ライブラリ<132>,Core and Builtins<130>,Core and Builtins<129>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id577}@anchor{1ce2}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert @ref{94,,mmap} to use heap types.
@end itemize

@node Core and Builtins<130>,ライブラリ<133>,ライブラリ<132>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id578}@anchor{1ce3}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42233}: Allow @code{GenericAlias} objects to use @ref{9c5,,union type expressions}. This allows expressions like @code{list[int] |
dict[float, str]} where previously a @code{TypeError} would have been
thrown.  This also fixes union type expressions not de-duplicating
@code{GenericAlias} objects. (Contributed by Ken Jin in bpo-42233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42233}.)

@item 
bpo-26131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26131}: The import system triggers a @code{ImportWarning} when it falls
back to using @code{load_module()}.
@end itemize

@node ライブラリ<133>,ドキュメント<42>,Core and Builtins<130>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id579}@anchor{1ce4}
@subsubsection ライブラリ



@itemize -

@item 
bpo-5054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5054}: CGIHTTPRequestHandler.run_cgi() HTTP_ACCEPT improperly parsed.
Replace the special purpose getallmatchingheaders with generic get_all
method and add relevant tests.

Original Patch by Martin Panter. Modified by Senthil Kumaran.

@item 
bpo-42562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42562}: Fix issue when dis failed to parse function that has no line
numbers. Patch provided by Yurii Karabas.

@item 
bpo-17735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17735}: @code{inspect.findsource()} now raises @ref{2c0,,OSError} instead of
@ref{174e,,IndexError} when @code{co_lineno} of a code object is greater than
the file length. This can happen, for example, when a file is edited after
it was imported.  PR by Irit Katriel.

@item 
bpo-42116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42116}: Fix handling of trailing comments by @ref{17c3,,inspect.getsource()}.

@item 
bpo-42532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42532}: Remove unexpected call of @code{__bool__} when passing a
@code{spec_arg} argument to a Mock.

@item 
bpo-38200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38200}: Added itertools.pairwise()

@item 
bpo-41818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41818}: Fix test_master_read() so that it succeeds on all platforms
that either raise OSError or return b"" upon reading from master.

@item 
bpo-42487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42487}: ChainMap.__iter__ no longer calls __getitem__ on underlying
maps

@item 
bpo-42482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42482}: @ref{563,,TracebackException} no longer holds a
reference to the exception's traceback object. Consequently, instances of
TracebackException for equivalent but non-equal exceptions now compare as
equal.

@item 
bpo-41818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41818}: Make test_openpty() avoid unexpected success due to number of
rows and/or number of columns being == 0.

@item 
bpo-42392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42392}: Remove loop parameter from @code{asyncio.subprocess} and
@code{asyncio.tasks} functions. Patch provided by Yurii Karabas.

@item 
bpo-42392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42392}: Remove loop parameter from @code{asyncio.open_connection} and
@code{asyncio.start_server} functions. Patch provided by Yurii Karabas.

@item 
bpo-28468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28468}: Add @ref{a27,,platform.freedesktop_os_release()} function to parse
freedesktop.org @code{os-release} files.

@item 
bpo-42299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42299}: Removed the @code{formatter} module, which was deprecated in
Python 3.4. It is somewhat obsolete, little used, and not tested. It was
originally scheduled to be removed in Python 3.6, but such removals were
delayed until after Python 2.7 EOL. Existing users should copy whatever
classes they use into their code. Patch by Donghee Na and and Terry J.
Reedy.

@item 
bpo-26131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26131}: Deprecate zipimport.zipimporter.load_module() in favour of
exec_module().

@item 
bpo-41818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41818}: Updated tests for the pty library. test_basic() has been
changed to test_openpty(); this additionally checks if slave termios and
slave winsize are being set properly by pty.openpty(). In order to add
support for FreeBSD, NetBSD, OpenBSD, and Darwin, this also adds
test_master_read(), which demonstrates that pty.spawn() should not depend
on an OSError to exit from its copy loop.

@item 
bpo-42392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42392}: Remove loop parameter from @code{__init__} in all
@code{asyncio.locks} and @code{asyncio.Queue} classes. Patch provided by Yurii
Karabas.

@item 
bpo-15450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15450}: Make @ref{1142,,filecmp.dircmp} respect subclassing. Now the
@ref{1ce5,,filecmp.dircmp.subdirs} behaves as expected when subclassing
dircmp.

@item 
bpo-42413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42413}: The exception @ref{a35,,socket.timeout} is now an alias of
@ref{a36,,TimeoutError}.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Support signal module on VxWorks.

@item 
bpo-42406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42406}: We fixed an issue in @code{pickle.whichmodule} in which importing
@code{multiprocessing} could change the how pickle identifies which module an
object belongs to, potentially breaking the unpickling of those objects.

@item 
bpo-42403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42403}: Simplify the @ref{7b,,importlib} external bootstrap code:
@code{importlib._bootstrap_external} now uses regular imports to import
builtin modules. When it is imported, the builtin @ref{ad1,,__import__()}
function is already fully working and so can be used to import builtin
modules like @ref{df,,sys}. Patch by Victor Stinner.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Convert _sre module types to heap types (PEP 384). Patch by
Erlend E. Aasland.

@item 
bpo-42375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42375}: subprocess module update for DragonFlyBSD support.

@item 
bpo-41713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41713}: Port the @code{_signal} extension module to the multi-phase
initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}). Patch by Victor Stinner and Mohamed
Koubaa.

@item 
bpo-37205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37205}: @ref{55d,,time.time()}, @ref{c7a,,time.perf_counter()} and
@ref{55c,,time.monotonic()} functions can no longer fail with a Python fatal
error, instead raise a regular Python exception on failure.

@item 
bpo-42328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42328}: Fixed @ref{1ce6,,tkinter.ttk.Style.map()}. The function accepts now
the representation of the default state as empty sequence (as returned by
@code{Style.map()}). The structure of the result is now the same on all
platform and does not depend on the value of @code{wantobjects}.

@item 
bpo-42345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42345}: Fix various issues with @code{typing.Literal} parameter handling
(flatten, deduplicate, use type to cache key). Patch provided by Yurii
Karabas.

@item 
bpo-37205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37205}: @ref{c7a,,time.perf_counter()} on Windows and @ref{55c,,time.monotonic()}
on macOS are now system-wide. Previously, they used an offset computed at
startup to reduce the precision loss caused by the float type. Use
@ref{cde,,time.perf_counter_ns()} and @ref{cdd,,time.monotonic_ns()} added in Python
3.7 to avoid this precision loss.

@item 
bpo-42318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42318}: Fixed support of non-BMP characters in @ref{f6,,tkinter} on macOS.

@item 
bpo-42350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42350}: Fix the @ref{176,,threading.Thread} class at fork: do nothing if
the thread is already stopped (ex: fork called at Python exit).
Previously, an error was logged in the child process.

@item 
bpo-42333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42333}: Port _ssl extension module to heap types.

@item 
bpo-42014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42014}: The @code{onerror} callback from @code{shutil.rmtree} now receives
correct function when @code{os.open} fails.

@item 
bpo-42237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42237}: Fix @code{os.sendfile()} on illumos.

@item 
bpo-42308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42308}: Add @ref{a4a,,threading.__excepthook__} to allow retrieving the
original value of @ref{a4b,,threading.excepthook()} in case it is set to a
broken or a different value. Patch by Mario Corchero.

@item 
bpo-42131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42131}: Implement PEP 451/spec methods on zipimport.zipimporter:
find_spec(), create_module(), and exec_module().

This also allows for the documented deprecation of find_loader(),
find_module(), and load_module().

@item 
bpo-41877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41877}: Mock objects which are not unsafe will now raise an
AttributeError if an attribute with the prefix asert, aseert, or assrt is
accessed, in addition to this already happening for the prefixes assert or
assret.

@item 
bpo-42264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42264}: @code{sqlite3.OptimizedUnicode} has been undocumented and obsolete
since Python 3.3, when it was made an alias to @ref{169,,str}.  It is now
deprecated, scheduled for removal in Python 3.12.

@item 
bpo-42251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42251}: Added @ref{a46,,threading.gettrace()} and
@ref{a47,,threading.getprofile()} to retrieve the functions set by
@ref{a48,,threading.settrace()} and @ref{a49,,threading.setprofile()} respectively.
Patch by Mario Corchero.

@item 
bpo-42249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42249}: Fixed writing binary Plist files larger than 4 GiB.

@item 
bpo-42236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42236}: On Unix, the @ref{1c35,,os.device_encoding()} function now returns
@code{'UTF-8'} rather than the device encoding if the @ref{866,,Python UTF-8 Mode} is enabled.

@item 
bpo-41754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41754}: webbrowser: Ignore `NotADirectoryError' when calling
@code{xdg-settings}.

@item 
bpo-42183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42183}: Fix a stack overflow error for asyncio Task or Future repr().

The overflow occurs under some circumstances when a Task or Future
recursively returns itself.

@item 
bpo-42140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42140}: Improve asyncio.wait function to create the futures set just
one time.

@item 
bpo-42133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42133}: Update various modules in the stdlib to fall back on
@code{__spec__.loader} when @code{__loader__} isn't defined on a module.

@item 
bpo-26131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26131}: The @code{load_module()} methods found in @code{importlib} now
trigger a @code{DeprecationWarning}.

@item 
bpo-39825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39825}: Windows: Change @code{sysconfig.get_config_var('EXT_SUFFIX')} to
the expected full @code{platform_tag.extension} format. Previously it was
hard-coded to @code{.pyd}, now it is compatible with @code{distutils.sysconfig}
and will result in something like @code{.cp38-win_amd64.pyd}. This brings
windows into conformance with the other platforms.

@item 
bpo-26389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26389}: The @ref{a4d,,traceback.format_exception()},
@ref{a4e,,traceback.format_exception_only()}, and
@ref{a4f,,traceback.print_exception()} functions can now take an exception
object as a positional-only argument.

@item 
bpo-41889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41889}: Enum: fix regression involving inheriting a multiply inherited
enum

@item 
bpo-41861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41861}: Convert @ref{d4,,sqlite3} to use heap types (PEP 384). Patch by
Erlend E. Aasland.

@item 
bpo-40624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40624}: Added support for the XPath @code{!=} operator in xml.etree

@item 
bpo-28850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28850}: Fix @ref{1ce7,,pprint.PrettyPrinter.format()} overrides being ignored
for contents of small containers. The @code{pprint._safe_repr()} function
was removed.

@item 
bpo-41625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41625}: Expose the @code{splice()} as @ref{a1a,,os.splice()} in the
@ref{a5,,os} module. Patch by Pablo Galindo

@item 
bpo-34215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34215}: Clarify the error message for
@ref{1ce8,,asyncio.IncompleteReadError} when @code{expected} is @code{None}.

@item 
bpo-41543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41543}: Add async context manager support for contextlib.nullcontext.

@item 
bpo-21041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21041}: @ref{a21,,pathlib.PurePath.parents} now supports negative
indexing. Patch contributed by Yaroslav Pankovych.

@item 
bpo-41332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41332}: Added missing connect_accepted_socket() method to
@code{asyncio.AbstractEventLoop}.

@item 
bpo-12800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12800}: Extracting a symlink from a tarball should succeed and
overwrite the symlink if it already exists. The fix is to remove the
existing file or symlink before extraction. Based on patch by Chris AtLee,
Jeffrey Kintscher, and Senthil Kumaran.

@item 
bpo-40968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40968}: @ref{111,,urllib.request} and @ref{73,,http.client} now send
@code{http/1.1} ALPN extension during TLS handshake when no custom context is
supplied.

@item 
bpo-41001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41001}: Add @ref{a19,,os.eventfd()} to provide a low level interface for
Linux's event notification file descriptor.

@item 
bpo-40816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40816}: Add AsyncContextDecorator to contextlib to support async
context manager as a decorator.

@item 
bpo-40550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40550}: Fix time-of-check/time-of-action issue in
subprocess.Popen.send_signal.

@item 
bpo-39411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39411}: Add an @code{is_async} identifier to @ref{b9,,pyclbr}'s @code{Function}
objects. Patch by Batuhan Taskaya

@item 
bpo-35498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35498}: Add slice support to @ref{a21,,pathlib.PurePath.parents}.
@end itemize

@node ドキュメント<42>,テスト<41>,ライブラリ<133>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id580}@anchor{1ce9}
@subsubsection ドキュメント



@itemize -

@item 
bpo-42238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42238}: Tentative to deprecate @code{make suspicious} by first removing it
from the CI and documentation builds, but keeping it around for manual
uses.

@item 
bpo-42153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42153}: Fix the URL for the IMAP protocol documents.

@item 
bpo-41028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41028}: Language and version switchers, previously maintained in every
cpython branches, are now handled by docsbuild-script.
@end itemize

@node テスト<41>,ビルド<48>,ドキュメント<42>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id581}@anchor{1cea}
@subsubsection テスト



@itemize -

@item 
bpo-41473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41473}: Re-enable test_gdb on gdb 9.2 and newer:
@indicateurl{https://bugzilla.redhat.com/show_bug.cgi?id=1866884} bug is fixed in gdb
10.1.

@item 
bpo-42553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42553}: Fix @code{test_asyncio.test_call_later()} race condition: don't
measure asyncio performance in the @code{call_later()} unit test. The test
failed randomly on the CI.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix test_netrc on VxWorks: create temporary directories using
temp_cwd().

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: skip test_getaddrinfo_ipv6_scopeid_symbolic and
test_getnameinfo_ipv6_scopeid_symbolic on VxWorks

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: skip test_test of test_mailcap on VxWorks

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: add shell requirement for test_pipes

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: skip some tests related to fifo on VxWorks

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix test_doctest.py failures for VxWorks.

@item 
bpo-40754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40754}: Include @code{_testinternalcapi} module in Windows installer for
test suite

@item 
bpo-41561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41561}: test_ssl: skip test_min_max_version_mismatch when TLS 1.0 is
not available

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix os module failures for VxWorks RTOS.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix fifo test cases for VxWorks RTOS.
@end itemize

@node ビルド<48>,Windows<42>,テスト<41>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id582}@anchor{1ceb}
@subsubsection ビルド



@itemize -

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: remove libnet dependency from detect_socket() for VxWorks

@item 
bpo-42398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42398}: Fix a race condition in "make regen-all" when make -jN option
is used to run jobs in parallel. The clinic.py script now only use atomic
write to write files. Moveover, generated files are now left unchanged if
the content does not change, to not change the file modification time.

@item 
bpo-41617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41617}: Fix building @code{pycore_bitutils.h} internal header on old clang
version without @code{__builtin_bswap16()} (ex: Xcode 4.6.3 on Mac OS X
10.7). Patch by Joshua Root and Victor Stinner.

@item 
bpo-38823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38823}: It is no longer possible to build the @code{_ctypes} extension
module without @code{wchar_t} type: remove @code{CTYPES_UNICODE} macro.
Anyway, the @code{wchar_t} type is required to build Python. Patch by
Victor Stinner.

@item 
bpo-42087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42087}: Support was removed for AIX 5.3 and below. See bpo-40680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40680}.

@item 
bpo-40998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40998}: Addressed three compiler warnings found by undefined behavior
sanitizer (ubsan).
@end itemize

@node Windows<42>,macOS<32>,ビルド<48>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id583}@anchor{1cec}
@subsubsection Windows



@itemize -

@item 
bpo-42120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42120}: Remove macro definition of @code{copysign} (to @code{_copysign}) in
headers.

@item 
bpo-38506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38506}: The Windows launcher now properly handles Python 3.10 when
listing installed Python versions.
@end itemize

@node macOS<32>,IDLE<24>,Windows<42>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id584}@anchor{1ced}
@subsubsection macOS



@itemize -

@item 
bpo-42504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42504}: Fix build on macOS Big Sur when MACOSX_DEPLOYMENT_TARGET=11

@item 
bpo-41116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41116}: Ensure distutils.unixxcompiler.find_library_file can find
system provided libraries on macOS 11.

@item 
bpo-41100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41100}: Add support for macOS 11 and Apple Silicon systems.

It is now possible to build "Universal 2" binaries using
"--enable-universalsdk --with-universal-archs=universal2".

Binaries build on later macOS versions can be deployed back to older
versions (tested up to macOS 10.9), when using the correct deployment
target. This is tested using Xcode 11 and later.

@item 
bpo-42232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42232}: Added Darwin specific madvise options to mmap module.

@item 
bpo-38443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38443}: The @code{--enable-universalsdk} and @code{--with-universal-archs}
options for the configure script now check that the specified
architectures can be used.
@end itemize

@node IDLE<24>,Tools/Demos<29>,macOS<32>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id585}@anchor{1cee}
@subsubsection IDLE



@itemize -

@item 
bpo-42508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42508}: Keep IDLE running on macOS.  Remove obsolete workaround that
prevented running files with shortcuts when using new universal2
installers built on macOS 11.

@item 
bpo-42426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42426}: Fix reporting offset of the RE error in searchengine.

@item 
bpo-42415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42415}: Get docstrings for IDLE calltips more often by using
inspect.getdoc.
@end itemize

@node Tools/Demos<29>,C API<43>,IDLE<24>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id586}@anchor{1cef}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-42212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42212}: The smelly.py script now also checks the Python dynamic library
and extension modules, not only the Python static library. Make also the
script more verbose: explain what it does.

@item 
bpo-36310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36310}: Allow @code{Tools/i18n/pygettext.py} to detect calls to
@code{gettext} in f-strings.
@end itemize

@node C API<43>,,Tools/Demos<29>,Python 3 10 0 alpha 3
@anchor{whatsnew/changelog id587}@anchor{1cf0}
@subsubsection C API



@itemize -

@item 
bpo-42423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42423}: The @ref{79e,,PyType_FromSpecWithBases()} and
@ref{773,,PyType_FromModuleAndSpec()} functions now accept a single class as
the `bases' argument.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{c6,,select} extension module to multiphase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _posixsubprocess extension module to multiphase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _posixshmem extension module to multiphase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _struct extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @code{spwd} extension module to multiphase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{64,,gc} extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _queue extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Convert @ref{3c9,,Py_TYPE()} and @ref{985,,Py_SIZE()} back to macros
to allow using them as an l-value. Many third party C extension modules
rely on the ability of using Py_TYPE() and Py_SIZE() to set an object type
and size: @code{Py_TYPE(obj) = type;} and @code{Py_SIZE(obj) = size;}.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{de,,symtable} extension module to multiphase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{6a,,grp} and @ref{b7,,pwd} extension modules to
multiphase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _random extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _hashlib extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/})

@item 
bpo-41713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41713}: Removed the undocumented @code{PyOS_InitInterrupts()} function.
Initializing Python already implicitly installs signal handlers: see
@ref{abb,,PyConfig.install_signal_handlers}. Patch by Victor Stinner.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: The @code{Py_TRASHCAN_BEGIN} macro no longer accesses PyTypeObject
attributes, but now can get the condition by calling the new private
@code{_PyTrash_cond()} function which hides implementation details.

@item 
bpo-42260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42260}: @ref{3e3,,Py_GetPath()}, @ref{3e5,,Py_GetPrefix()},
@ref{3e9,,Py_GetExecPrefix()}, @ref{3ec,,Py_GetProgramFullPath()},
@ref{3ef,,Py_GetPythonHome()} and @ref{3ee,,Py_GetProgramName()} functions now
return @code{NULL} if called before @ref{460,,Py_Initialize()} (before Python is
initialized). Use the new @ref{646,,Python Initialization Configuration API} to get the @ref{aaa,,Python Path Configuration.}. Patch by Victor Stinner.

@item 
bpo-42260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42260}: The @ref{993,,PyConfig_Read()} function now only parses
@ref{3f1,,PyConfig.argv} arguments once: @ref{1cf1,,PyConfig.parse_argv}
is set to @code{2} after arguments are parsed. Since Python arguments are
strippped from @ref{3f1,,PyConfig.argv}, parsing arguments twice would
parse the application options as Python options.

@item 
bpo-42262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42262}: Added @ref{a9a,,Py_NewRef()} and @ref{a9b,,Py_XNewRef()} functions to
increment the reference count of an object and return the object. Patch by
Victor Stinner.

@item 
bpo-42260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42260}: When @ref{460,,Py_Initialize()} is called twice, the second call
now updates more @ref{df,,sys} attributes for the configuration, rather than
only @ref{147c,,sys.argv}. Patch by Victor Stinner.

@item 
bpo-41832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41832}: The @ref{773,,PyType_FromModuleAndSpec()} function now accepts
NULL @code{tp_doc} slot.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Added @ref{60a,,PyModule_AddObjectRef()} function: similar to
@ref{60b,,PyModule_AddObject()} but don't steal a reference to the value on
success. Patch by Victor Stinner.

@item 
bpo-42171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42171}: The @ref{199e,,METH_FASTCALL} calling convention is added to the
limited API. The functions  @ref{b6c,,PyModule_AddType()},
@ref{773,,PyType_FromModuleAndSpec()}, @ref{b66,,PyType_GetModule()} and
@ref{b67,,PyType_GetModuleState()} are added to the limited API on Windows.

@item 
bpo-42085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42085}: Add dedicated entry to PyAsyncMethods for sending values

@item 
bpo-41073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41073}: @ref{a9c,,PyType_GetSlot()} can now accept static types.

@item 
bpo-30459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30459}: @ref{62f,,PyList_SET_ITEM()}, @ref{62e,,PyTuple_SET_ITEM()} and
@ref{aab,,PyCell_SET()} macros can no longer be used as l-value or r-value.
For example, @code{x = PyList_SET_ITEM(a, b, c)} and @code{PyList_SET_ITEM(a, b,
c) = x} now fail with a compiler error. It prevents bugs like @code{if
(PyList_SET_ITEM (a, b, c) < 0) ...} test. Patch by Zackery Spytz and
Victor Stinner.
@end itemize

@node Python 3 10 0 alpha 2,Python 3 10 0 alpha 1,Python 3 10 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-10-0-alpha-2}@anchor{1cf2}
@subsection Python 3.10.0 alpha 2


`Release date: 2020-11-03'

@menu
* セキュリティ: セキュリティ<35>. 
* Core and Builtins: Core and Builtins<131>. 
* ライブラリ: ライブラリ<134>. 
* Core and Builtins: Core and Builtins<132>. 
* ライブラリ: ライブラリ<135>. 
* ドキュメント: ドキュメント<43>. 
* テスト: テスト<42>. 
* ビルド: ビルド<49>. 
* Windows: Windows<43>. 
* macOS: macOS<33>. 
* IDLE: IDLE<25>. 
* C API: C API<44>. 

@end menu

@node セキュリティ<35>,Core and Builtins<131>,,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id588}@anchor{1cf3}
@subsubsection セキュリティ



@itemize -

@item 
bpo-42103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42103}: Prevented potential DoS attack via CPU and RAM exhaustion when
processing malformed Apple Property List files in binary format.

@item 
bpo-42051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42051}: The @ref{b0,,plistlib} module no longer accepts entity
declarations in XML plist files to avoid XML vulnerabilities. This should
not affect users as entity declarations are not used in regular plist
files.
@end itemize

@node Core and Builtins<131>,ライブラリ<134>,セキュリティ<35>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id589}@anchor{1cf4}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42236}: If the @code{nl_langinfo(CODESET)} function returns an empty
string, Python now uses UTF-8 as the filesystem encoding. Patch by Victor
Stinner.

@item 
bpo-42218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42218}: Fixed a bug in the PEG parser that was causing crashes in debug
mode. Now errors are checked in left-recursive rules to avoid cases where
such errors do not get handled in time and appear as long-distance crashes
in other places.

@item 
bpo-42214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42214}: Fixed a possible crash in the PEG parser when checking for the
'!=' token in the @code{barry_as_flufl} rule. Patch by Pablo Galindo.

@item 
bpo-42206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42206}: Propagate and raise the errors caused by
@code{PyAST_Validate()} in the parser.

@item 
bpo-41796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41796}: The @ref{9,,ast} module internal state is now per interpreter.
Patch by Victor Stinner.

@item 
bpo-42143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42143}: Fix handling of errors during creation of @code{PyFunctionObject},
which resulted in operations on uninitialized memory. Patch by Yonatan
Goldschmidt.

@item 
bpo-41659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41659}: Fix a bug in the parser, where a curly brace following a
@code{primary} didn't fail immediately. This led to invalid expressions like
@code{a @{b@}} to throw a @ref{18e,,SyntaxError} with a wrong offset, or invalid
expressions ending with a curly brace like @code{a @{} to not fail immediately
in the REPL.

@item 
bpo-42150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42150}: Fix possible buffer overflow in the new parser when checking
for continuation lines. Patch by Pablo Galindo.

@item 
bpo-42123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42123}: Run the parser two times. On the first run, disable all the
rules that only generate better error messages to gain performance. If
there's a parse failure, run the parser a second time with those enabled.

@item 
bpo-42093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42093}: The @code{LOAD_ATTR} instruction now uses new "per opcode cache"
mechanism and it is about 36% faster now. Patch by Pablo Galindo and Yury
Selivanov.

@item 
bpo-42030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42030}: Support for the legacy AIX-specific shared library loading
support has been removed. All versions of AIX since 4.3 have supported and
defaulted to using the common Unix mechanism instead.

@item 
bpo-41984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41984}: The garbage collector now tracks all user-defined classes.
Patch by Brandt Bucher.

@item 
bpo-41993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41993}: Fixed potential issues with removing not completely initialized
module from @code{sys.modules} when import fails.

@item 
bpo-41979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41979}: Star-unpacking is now allowed for with item's targets in the
PEG parser.

@item 
bpo-41974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41974}: Removed special methods @code{__int__}, @code{__float__},
@code{__floordiv__}, @code{__mod__}, @code{__divmod__}, @code{__rfloordiv__},
@code{__rmod__} and @code{__rdivmod__} of the @ref{197,,complex} class.  They
always raised a @ref{198,,TypeError}.

@item 
bpo-41902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41902}: Micro optimization when compute
@ref{1cf5,,sq_item} and
@ref{1cf6,,mp_subscript} of @ref{b3d,,range}. Patch by
Donghee Na.

@item 
bpo-41894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41894}: When loading a native module and a load failure occurs, prevent
a possible UnicodeDecodeError when not running in a UTF-8 locale by
decoding the load error message using the current locale's encoding.

@item 
bpo-41902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41902}: Micro optimization for range.index if step is 1. Patch by
Donghee Na.
@end itemize

@node ライブラリ<134>,Core and Builtins<132>,Core and Builtins<131>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id590}@anchor{1cf7}
@subsubsection ライブラリ



@itemize -

@item 
bpo-41435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41435}: Add @code{sys._current_exceptions()} function to retrieve a
dictionary mapping each thread's identifier to the topmost exception
currently active in that thread at the time the function is called.
@end itemize

@node Core and Builtins<132>,ライブラリ<135>,ライブラリ<134>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id591}@anchor{1cf8}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-38605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38605}: Enable @code{from __future__ import annotations} (
@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/}) by
default. The values found in @ref{458,,__annotations__} dicts are now
strings, for example @code{@{"x": "int"@}} instead of @code{@{"x": int@}}.
@end itemize

@node ライブラリ<135>,ドキュメント<43>,Core and Builtins<132>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id592}@anchor{1cf9}
@subsubsection ライブラリ



@itemize -

@item 
bpo-35455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35455}: On Solaris, @ref{b30,,thread_time()} is now implemented with
@code{gethrvtime()} because @code{clock_gettime(CLOCK_THREAD_CPUTIME_ID)} is not
always available. Patch by Jakub Kulik.

@item 
bpo-42233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42233}: The @ref{1c1,,repr()} of @ref{10a,,typing} types containing
@ref{8c1,,Generic Alias Types} previously did not show
the parameterized types in the @code{GenericAlias}.  They have now been
changed to do so.

@item 
bpo-29566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29566}: @code{binhex.binhex()} consistently writes macOS 9 line endings.

@item 
bpo-26789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26789}: The @ref{1c53,,logging.FileHandler} class now keeps a reference to
the builtin @ref{316,,open()} function to be able to open or reopen the file
during Python finalization. Fix errors like: @code{NameError: name 'open' is
not defined}. Patch by Victor Stinner.

@item 
bpo-42157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42157}: Removed the @code{unicodedata.ucnhash_CAPI} attribute which was an
internal PyCapsule object. The related private @code{_PyUnicode_Name_CAPI}
structure was moved to the internal C API. Patch by Victor Stinner.

@item 
bpo-42157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42157}: Convert the @ref{10b,,unicodedata} extension module to the
multiphase initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}) and convert the
@code{unicodedata.UCD} static type to a heap type. Patch by Mohamed Koubaa
and Victor Stinner.

@item 
bpo-42146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42146}: Fix memory leak in @ref{4b7,,subprocess.Popen()} in case an uid
(gid) specified in @code{user} (@code{group}, @code{extra_groups}) overflows
@code{uid_t} (@code{gid_t}).

@item 
bpo-42103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42103}: @ref{1cfa,,InvalidFileException} and @ref{f68,,RecursionError}
are now the only errors caused by loading malformed binary Plist file
(previously ValueError and TypeError could be raised in some specific
cases).

@item 
bpo-41490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41490}: In @code{importlib.resources}, @code{.path} method is more aggressive
about releasing handles to zipfile objects early, enabling use-cases like
certifi to leave the context open but delete the underlying zip file.

@item 
bpo-41052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41052}: Pickling heap types implemented in C with protocols 0 and 1
raises now an error instead of producing incorrect data.

@item 
bpo-42089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42089}: In @code{importlib.metadata.PackageNotFoundError}, make reference
to the package metadata being missing to improve the user experience.

@item 
bpo-41491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41491}: plistlib: fix parsing XML plists with hexadecimal integer
values

@item 
bpo-42065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42065}: Fix an incorrectly formatted error from
@code{_codecs.charmap_decode()} when called with a mapped value outside
the range of valid Unicode code points. PR by Max Bernstein.

@item 
bpo-41966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41966}: Fix pickling pure Python @ref{1fb,,datetime.time} subclasses.
Patch by Dean Inwood.

@item 
bpo-19270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19270}: @ref{1cfb,,sched.scheduler.cancel()} will now cancel the correct
event, if two events with same priority are scheduled for the same time.
Patch by Bar Harel.

@item 
bpo-28660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28660}: @ref{16e0,,textwrap.wrap()} now attempts to break long words after
hyphens when @code{break_long_words=True} and @code{break_on_hyphens=True}.

@item 
bpo-35823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35823}: Use @code{vfork()} instead of @code{fork()} for
@ref{4b7,,subprocess.Popen()} on Linux to improve performance in cases where it
is deemed safe.

@item 
bpo-42043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42043}: Add support for @code{zipfile.Path} inheritance.
@code{zipfile.Path.is_file()} now returns False for non-existent names.
@code{zipfile.Path} objects now expose a @code{.filename} attribute and rely on
that to resolve @code{.name} and @code{.parent} when the @code{Path} object is at
the root of the zipfile.

@item 
bpo-42021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42021}: Fix possible ref leaks in @ref{d4,,sqlite3} module init.

@item 
bpo-39101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39101}: Fixed tests using IsolatedAsyncioTestCase from hanging on
BaseExceptions.

@item 
bpo-41976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41976}: Fixed a bug that was causing @ref{f45,,ctypes.util.find_library()}
to return @code{None} when triying to locate a library in an environment when
gcc>=9 is available and @code{ldconfig} is not. Patch by Pablo Galindo

@item 
bpo-41943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41943}: Fix bug where TestCase.assertLogs doesn't correctly filter
messages by level.

@item 
bpo-41923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41923}: Implement 
@geindex Python Enhancement Proposals; PEP 613
PEP 613@footnote{https://peps.python.org/pep-0613/}, introducing @ref{9cc,,typing.TypeAlias}
annotation.

@item 
bpo-41905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41905}: A new function in abc: `update_abstractmethods' to re-calculate
an abstract class's abstract status. In addition, `dataclass' has been
changed to call this function.

@item 
bpo-23706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23706}: Added `newline' parameter to @code{pathlib.Path.write_text()}.

@item 
bpo-41876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41876}: Tkinter font class repr uses font name

@item 
bpo-41831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41831}: @code{str()} for the @code{type} attribute of the @code{tkinter.Event}
object always returns now the numeric code returned by Tk instead of the
name of the event type.

@item 
bpo-39337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39337}: @ref{9fd,,encodings.normalize_encoding()} now ignores non-ASCII
characters.

@item 
bpo-41747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41747}: Ensure all methods that generated from
@ref{4e1,,dataclasses.dataclass()} objects now have the proper @code{__qualname__}
attribute referring to the class they belong to. Patch by Batuhan Taskaya.

@item 
bpo-30681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30681}: Handle exceptions caused by unparsable date headers when using
email "default" policy.  Patch by Tim Bell, Georges Toth

@item 
bpo-41586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41586}: Add F_SETPIPE_SZ and F_GETPIPE_SZ to fcntl module. Allow
setting pipesize on subprocess.Popen.

@item 
bpo-41229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41229}: Add @code{contextlib.aclosing} for deterministic cleanup of async
generators which is analogous to @code{contextlib.closing} for non-async
generators. Patch by Joongi Kim and John Belmonte.

@item 
bpo-16396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16396}: Allow @code{ctypes.wintypes} to be imported on non-Windows
systems.

@item 
bpo-4356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4356}: Add a key function to the bisect module.

@item 
bpo-40592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40592}: @ref{6db,,shutil.which()} now ignores empty entries in
@geindex PATHEXT
@geindex 環境変数; PATHEXT
@code{PATHEXT} instead of treating them as a match.

@item 
bpo-40492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40492}: Fix @code{--outfile} for @ref{2b,,cProfile} / @ref{b4,,profile} not
writing the output file in the original directory when the program being
profiled changes the working directory.  PR by Anthony Sottile.

@item 
bpo-34204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34204}: The @ref{c8,,shelve} module now uses
@ref{a2f,,pickle.DEFAULT_PROTOCOL} by default instead of @ref{ab,,pickle}
protocol @code{3}.

@item 
bpo-27321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27321}: Fixed KeyError exception when flattening an email to a string
attempts to replace a non-existent Content-Transfer-Encoding header.

@item 
bpo-38976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38976}: The @ref{74,,http.cookiejar} module now supports the parsing of
cookies in CURL-style cookiejar files through MozillaCookieJar on all
platforms. Previously, such cookie entries would be silently ignored when
loading a cookiejar with such entries.

Additionally, the HTTP Only attribute is persisted in the object, and will
be correctly written to file if the MozillaCookieJar object is
subsequently dumped.
@end itemize

@node ドキュメント<43>,テスト<42>,ライブラリ<135>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id593}@anchor{1cfc}
@subsubsection ドキュメント



@itemize -

@item 
bpo-42061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42061}: Document __format__ functionality for IP addresses.

@item 
bpo-41910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41910}: Document the default implementation of @code{object.__eq__}.

@item 
bpo-42010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42010}: Clarify that subscription expressions are also valid for
certain @ref{1cfd,,classes} and @ref{1cfe,,types} in the standard
library, and for user-defined classes and types if the classmethod
@code{__class_getitem__()} is provided.

@item 
bpo-41805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41805}: Documented @ref{8c1,,generic alias type} and
@ref{9ec,,types.GenericAlias}. Also added an entry in glossary for
@ref{1a1,,generic types}.

@item 
bpo-39693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39693}: Fix tarfile's extractfile documentation

@item 
bpo-39416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39416}: Document some restrictions on the default string
representations of numeric classes.
@end itemize

@node テスト<42>,ビルド<49>,ドキュメント<43>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id594}@anchor{1cff}
@subsubsection テスト



@itemize -

@item 
bpo-41739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41739}: Fix test_logging.test_race_between_set_target_and_flush(): the
test now waits until all threads complete to avoid leaking running
threads.

@item 
bpo-41970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41970}: Avoid a test failure in @code{test_lib2to3} if the module has
already imported at the time the test executes. Patch by Pablo Galindo.

@item 
bpo-41944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41944}: Tests for CJK codecs no longer call @code{eval()} on content
received via HTTP.

@item 
bpo-41306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41306}: Fixed a failure in @code{test_tk.test_widgets.ScaleTest} happening
when executing the test with Tk 8.6.10.
@end itemize

@node ビルド<49>,Windows<43>,テスト<42>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id595}@anchor{1d00}
@subsubsection ビルド



@itemize -

@item 
bpo-38980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38980}: Add @code{-fno-semantic-interposition} to both the compile and
link line when building with @code{--enable-optimizations}. Patch by Victor
Stinner and Pablo Galindo.
@end itemize

@node Windows<43>,macOS<33>,ビルド<49>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id596}@anchor{1d01}
@subsubsection Windows



@itemize -

@item 
bpo-38439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38439}: Updates the icons for IDLE in the Windows Store package.

@item 
bpo-38252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38252}: Use 8-byte step to detect ASCII sequence in 64-bit Windows
build.

@item 
bpo-39107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39107}: Update Tcl and Tk to 8.6.10 in Windows installer.

@item 
bpo-41557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41557}: Update Windows installer to use SQLite 3.33.0.

@item 
bpo-38324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38324}: Avoid Unicode errors when accessing certain locale data on
Windows.
@end itemize

@node macOS<33>,IDLE<25>,Windows<43>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id597}@anchor{1d02}
@subsubsection macOS



@itemize -

@item 
bpo-41471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41471}: Ignore invalid prefix lengths in system proxy excludes.
@end itemize

@node IDLE<25>,C API<44>,macOS<33>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id598}@anchor{1d03}
@subsubsection IDLE



@itemize -

@item 
bpo-33987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33987}: Mostly finish using ttk widgets, mainly for editor, settings,
and searches. Some patches by Mark Roseman.

@item 
bpo-40511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40511}: Typing opening and closing parentheses inside the parentheses
of a function call will no longer cause unnecessary "flashing" off and on
of an existing open call-tip, e.g. when typed in a string literal.

@item 
bpo-38439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38439}: Add a 256×256 pixel IDLE icon to the Windows .ico file. Created
by Andrew Clover. Remove the low-color gif variations from the .ico file.
@end itemize

@node C API<44>,,IDLE<25>,Python 3 10 0 alpha 2
@anchor{whatsnew/changelog id599}@anchor{1d04}
@subsubsection C API



@itemize -

@item 
bpo-42157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42157}: The private @code{_PyUnicode_Name_CAPI} structure of the PyCapsule
API @code{unicodedata.ucnhash_CAPI} has been moved to the internal C API.
Patch by Victor Stinner.

@item 
bpo-42015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42015}: Fix potential crash in deallocating method objects when
dynamically allocated @ref{16f0,,PyMethodDef}'s lifetime is managed through
the @code{self} argument of a @ref{1691,,PyCFunction}.

@item 
bpo-40423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40423}: The @ref{dc,,subprocess} module and @code{os.closerange} will now use
the @code{close_range(low, high, flags)} syscall when it is available for
more efficient closing of ranges of descriptors.

@item 
bpo-41845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41845}: @ref{1d05,,PyObject_GenericGetDict()} is available again in the
limited API when targeting 3.10 or later.

@item 
bpo-40422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40422}: Add @code{_Py_closerange} function to provide performant closing
of a range of file descriptors.

@item 
bpo-41986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41986}: @code{Py_FileSystemDefaultEncodeErrors} and
@code{Py_UTF8Mode} are available again in limited API.

@item 
bpo-41756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41756}: Add @code{PyIter_Send} function to allow sending value into
generator/coroutine/iterator without raising StopIteration exception to
signal return.

@item 
bpo-41784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41784}: Added @code{PyUnicode_AsUTF8AndSize} to the limited C API.
@end itemize

@node Python 3 10 0 alpha 1,Python 3 9 0 beta 1,Python 3 10 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-10-0-alpha-1}@anchor{1d06}
@subsection Python 3.10.0 alpha 1


`Release date: 2020-10-05'

@menu
* セキュリティ: セキュリティ<36>. 
* Core and Builtins: Core and Builtins<133>. 
* ライブラリ: ライブラリ<136>. 
* Core and Builtins: Core and Builtins<134>. 
* ライブラリ: ライブラリ<137>. 
* Core and Builtins: Core and Builtins<135>. 
* ライブラリ: ライブラリ<138>. 
* Core and Builtins: Core and Builtins<136>. 
* ライブラリ: ライブラリ<139>. 
* Core and Builtins: Core and Builtins<137>. 
* ライブラリ: ライブラリ<140>. 
* Core and Builtins: Core and Builtins<138>. 
* ライブラリ: ライブラリ<141>. 
* Core and Builtins: Core and Builtins<139>. 
* ライブラリ: ライブラリ<142>. 
* Core and Builtins: Core and Builtins<140>. 
* ライブラリ: ライブラリ<143>. 
* Core and Builtins: Core and Builtins<141>. 
* ライブラリ: ライブラリ<144>. 
* Core and Builtins: Core and Builtins<142>. 
* ライブラリ: ライブラリ<145>. 
* Core and Builtins: Core and Builtins<143>. 
* ライブラリ: ライブラリ<146>. 
* Core and Builtins: Core and Builtins<144>. 
* ライブラリ: ライブラリ<147>. 
* Core and Builtins: Core and Builtins<145>. 
* ライブラリ: ライブラリ<148>. 
* Core and Builtins: Core and Builtins<146>. 
* ライブラリ: ライブラリ<149>. 
* Core and Builtins: Core and Builtins<147>. 
* ライブラリ: ライブラリ<150>. 
* ドキュメント: ドキュメント<44>. 
* テスト: テスト<43>. 
* ビルド: ビルド<50>. 
* Windows: Windows<44>. 
* macOS: macOS<34>. 
* IDLE: IDLE<26>. 
* C API: C API<45>. 

@end menu

@node セキュリティ<36>,Core and Builtins<133>,,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id600}@anchor{1d07}
@subsubsection セキュリティ



@itemize -

@item 
bpo-41304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41304}: Fixes @code{python3x._pth} being ignored on Windows, caused by the
fix for bpo-29778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29778} (
@geindex Common Vulnerabilities and Exposures; CVE 2020-15801
CVE 2020-15801@footnote{https://www.cve.org/CVERecord?id=CVE-2020-15801}).

@item 
bpo-41162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41162}: Audit hooks are now cleared later during finalization to avoid
missing events.

@item 
bpo-29778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29778}: Ensure @code{python3.dll} is loaded from correct locations
when Python is embedded (
@geindex Common Vulnerabilities and Exposures; CVE 2020-15523
CVE 2020-15523@footnote{https://www.cve.org/CVERecord?id=CVE-2020-15523}).

@item 
bpo-41004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41004}: The __hash__() methods of  ipaddress.IPv4Interface and
ipaddress.IPv6Interface incorrectly generated constant hash values of 32
and 128 respectively. This resulted in always causing hash collisions. The
fix uses hash() to generate hash values for the tuple of (address, mask
length, network address).

@item 
bpo-39603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39603}: Prevent http header injection by rejecting control characters
in http.client.putrequest(...).
@end itemize

@node Core and Builtins<133>,ライブラリ<136>,セキュリティ<36>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id601}@anchor{1d08}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41909}: Fixed stack overflow in @ref{9c4,,issubclass()} and
@ref{2ad,,isinstance()} when getting the @code{__bases__} attribute leads to
infinite recursion.

@item 
bpo-41922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41922}: Speed up calls to @code{reversed()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.

@item 
bpo-41873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41873}: Calls to @code{float()} are now faster due to the @code{vectorcall}
calling convention. Patch by Dennis Sweeney.

@item 
bpo-41870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41870}: Speed up calls to @code{bool()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.
@end itemize

@node ライブラリ<136>,Core and Builtins<134>,Core and Builtins<133>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id602}@anchor{1d09}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_bisect} module to the multi-phase
initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).
@end itemize

@node Core and Builtins<134>,ライブラリ<137>,ライブラリ<136>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id603}@anchor{1d0a}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-39934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39934}: Correctly count control blocks in 'except' in compiler. Ensures
that a syntax error, rather a fatal error, occurs for deeply nested, named
exception handlers.

@item 
bpo-41780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41780}: Fix @code{__dir__()} of @ref{9ec,,types.GenericAlias}. Patch by
Batuhan Taskaya.
@end itemize

@node ライブラリ<137>,Core and Builtins<135>,Core and Builtins<134>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id604}@anchor{1d0b}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_lsprof} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @ref{19,,cmath} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_scproxy} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @ref{e7,,termios} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Convert the @code{_sha256} extension module types to heap
types.
@end itemize

@node Core and Builtins<135>,ライブラリ<138>,ライブラリ<137>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id605}@anchor{1d0c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41690}: Fix a possible stack overflow in the parser when parsing
functions and classes with a huge amount of arguments. Patch by Pablo
Galindo.
@end itemize

@node ライブラリ<138>,Core and Builtins<136>,Core and Builtins<135>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id606}@anchor{1d0d}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_overlapped} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_curses_panel} extension module to
multi-phase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_opcode} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).
@end itemize

@node Core and Builtins<136>,ライブラリ<139>,ライブラリ<138>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id607}@anchor{1d0e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41681}: Fixes the wrong error description in the error raised by using
2 @code{,} in format string in f-string and @ref{833,,str.format()}.
@end itemize

@node ライブラリ<139>,Core and Builtins<137>,Core and Builtins<136>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id608}@anchor{1d0f}
@subsubsection ライブラリ



@itemize -

@item 
bpo-41675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41675}: The implementation of @ref{134d,,signal.siginterrupt()} now uses
@code{sigaction()} (if it is available in the system) instead of the
deprecated @code{siginterrupt()}. Patch by Pablo Galindo.
@end itemize

@node Core and Builtins<137>,ライブラリ<140>,ライブラリ<139>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id609}@anchor{1d10}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41670}: Prevent line trace being skipped on platforms not compiled with
@code{USE_COMPUTED_GOTOS}. Fixes issue where some lines nested within a
try-except block were not being traced on Windows.

@item 
bpo-41654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41654}: Fix a crash that occurred when destroying subclasses of
@ref{179e,,MemoryError}. Patch by Pablo Galindo.
@end itemize

@node ライブラリ<140>,Core and Builtins<138>,Core and Builtins<137>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id610}@anchor{1d11}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @ref{139,,zlib} extension module to multi-phase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).
@end itemize

@node Core and Builtins<138>,ライブラリ<141>,ライブラリ<140>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id611}@anchor{1d12}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41631}: The @code{_ast} module uses again a global state. Using a module
state per module instance is causing subtle practical problems. For
example, the Mercurial project replaces the @code{__import__()} function to
implement lazy import, whereas Python expected that @code{import _ast} always
return a fully initialized @code{_ast} module.
@end itemize

@node ライブラリ<141>,Core and Builtins<139>,Core and Builtins<138>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id612}@anchor{1d13}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert @code{_operator} to use @ref{79d,,PyType_FromSpec()}.
@end itemize

@node Core and Builtins<139>,ライブラリ<142>,ライブラリ<141>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id613}@anchor{1d14}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-1653741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1653741}: Port @code{_sha3} to multi-phase init.  Convert static types
to heap types.
@end itemize

@node ライブラリ<142>,Core and Builtins<140>,Core and Builtins<139>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id614}@anchor{1d15}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_blake2} extension module to the multi-phase
initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).
@end itemize

@node Core and Builtins<140>,ライブラリ<143>,ライブラリ<142>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id615}@anchor{1d16}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41533}: Free the stack allocated in @code{va_build_stack} if
@code{do_mkstack} fails and the stack is not a @code{small_stack}.

@item 
bpo-41531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41531}: Fix a bug that was dropping keys when compiling dict literals
with more than 0xFFFF elements. Patch by Pablo Galindo.

@item 
bpo-41525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41525}: The output of @code{python --help} contains now only ASCII
characters.
@end itemize

@node ライブラリ<143>,Core and Builtins<141>,Core and Builtins<140>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id616}@anchor{1d17}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_sha1}, @code{_sha512}, and @code{_md5}
extension modules to multi-phase initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).
@end itemize

@node Core and Builtins<141>,ライブラリ<144>,ライブラリ<143>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id617}@anchor{1d18}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41431}: Optimize @code{dict_merge()} for copying dict (e.g. @code{dict(d)}
and @code{@{@}.update(d)}).

@item 
bpo-41428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41428}: Implement PEP 604. This supports (int | str) etc. in place of
Union[str, int].

@item 
bpo-41340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41340}: Removed fallback implementation for @code{strdup}.

@item 
bpo-38156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38156}: Handle interrupts that come after EOF correctly in
@code{PyOS_StdioReadline}.

@item 
bpo-41342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41342}: @ref{14f2,,round()} with integer argument is now faster (9--60%).

@item 
bpo-41334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41334}: Constructors @ref{169,,str()}, @ref{192,,bytes()} and @ref{344,,bytearray()}
are now faster (around 30--40% for small objects).

@item 
bpo-41295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41295}: Resolve a regression in CPython 3.8.4 where defining
"__setattr__" in a multi-inheritance setup and calling up the hierarchy
chain could fail if builtins/extension types were involved in the base
types.

@item 
bpo-41323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41323}: Bytecode optimizations are performed directly on the control
flow graph. This will result in slightly more compact code objects in some
circumstances.

@item 
bpo-41247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41247}: Always cache the running loop holder when running
@code{asyncio.set_running_loop}.

@item 
bpo-41252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41252}: Fix incorrect refcounting in _ssl.c's
@code{_servername_callback()}.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{98,,multiprocessing} to multi-phase initialization
@end itemize

@node ライブラリ<144>,Core and Builtins<142>,Core and Builtins<141>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id618}@anchor{1d19}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @code{winapi} to multiphase initialization
@end itemize

@node Core and Builtins<142>,ライブラリ<145>,ライブラリ<144>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id619}@anchor{1d1a}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41215}: Use non-NULL default values in the PEG parser keyword list to
overcome a bug that was preventing Python from being properly compiled
when using the XLC compiler. Patch by Pablo Galindo.

@item 
bpo-41218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41218}: Python 3.8.3 had a regression where compiling with
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT would aggressively mark list comprehension
with CO_COROUTINE. Now only list comprehension making use of async/await
will tagged as so.
@end itemize

@node ライブラリ<145>,Core and Builtins<143>,Core and Builtins<142>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id620}@anchor{1d1b}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{5c,,faulthandler} to multiphase initialization.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @code{sha256} to multiphase initialization
@end itemize

@node Core and Builtins<143>,ライブラリ<146>,ライブラリ<145>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id621}@anchor{1d1c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41175}: Guard against a NULL pointer dereference within bytearrayobject
triggered by the @code{bytearray() + bytearray()} operation.

@item 
bpo-41100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41100}: add arm64 to the allowable Mac OS arches in mpdecimal.h

@item 
bpo-41094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41094}: Fix decoding errors with audit when open files with non-ASCII
names on non-UTF-8 locale.

@item 
bpo-39960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39960}: The "hackcheck" that prevents sneaking around a type's
__setattr__() by calling the superclass method was rewritten to allow C
implemented heap types.

@item 
bpo-41084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41084}: Prefix the error message with 'f-string: ', when parsing an
f-string expression which throws a @ref{18e,,SyntaxError}.

@item 
bpo-40521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40521}: Empty frozensets are no longer singletons.

@item 
bpo-41076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41076}: Pre-feed the parser with the location of the f-string
expression, not the f-string itself, which allows us to skip the shifting
of the AST node locations after the parsing is completed.

@item 
bpo-41056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41056}: Fixes a reference to deallocated stack space during startup
when constructing sys.path involving a relative symlink when code was
supplied via -c.  (discovered via Coverity)

@item 
bpo-41061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41061}: Fix incorrect expressions and asserts in hashtable code and
tests.

@item 
bpo-41052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41052}: Opt out serialization/deserialization for _random.Random

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Rename @code{PyPegen*} functions to @code{PyParser*}, so that we can
remove the old set of @code{PyParser*} functions that were using the old
parser, but keep everything backwards-compatible.

@item 
bpo-35975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35975}: Stefan Behnel reported that cf_feature_version is used even
when PyCF_ONLY_AST is not set. This is against the intention and against
the documented behavior, so it's been fixed.

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Remove the remaining files from the old parser and the
@code{symbol} module.
@end itemize

@node ライブラリ<146>,Core and Builtins<144>,Core and Builtins<143>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id622}@anchor{1d1d}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert @code{_bz2} to use @ref{79d,,PyType_FromSpec()}.
@end itemize

@node Core and Builtins<144>,ライブラリ<147>,ライブラリ<146>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id623}@anchor{1d1e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41006}: The @code{encodings.latin_1} module is no longer imported at
startup. Now it is only imported when it is the filesystem encoding or the
stdio encoding.

@item 
bpo-40636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40636}: @ref{1a0,,zip()} now supports 
@geindex Python Enhancement Proposals; PEP 618
PEP 618@footnote{https://peps.python.org/pep-0618/}'s @code{strict} parameter,
which raises a @ref{2ec,,ValueError} if the arguments are exhausted at
different lengths. Patch by Brandt Bucher.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @code{_gdbm} to multiphase initialization.

@item 
bpo-40985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40985}: Fix a bug that caused the @ref{18e,,SyntaxError} text to be empty
when a file ends with a line ending in a line continuation character (i.e.
backslash). The error text should contain the text of the last line.

@item 
bpo-40958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40958}: Fix a possible buffer overflow in the PEG parser when gathering
information for emitting syntax errors. Patch by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @code{_dbm} to multiphase initialization.

@item 
bpo-40957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40957}: Fix refleak in _Py_fopen_obj() when PySys_Audit() fails
@end itemize

@node ライブラリ<147>,Core and Builtins<145>,Core and Builtins<144>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id624}@anchor{1d1f}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40950}: Add a state to the @code{nis} module (
@geindex Python Enhancement Proposals; PEP 3121
PEP 3121@footnote{https://peps.python.org/pep-3121/}) and apply
the multiphase initialization. Patch by Donghee Na.
@end itemize

@node Core and Builtins<145>,ライブラリ<148>,ライブラリ<147>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id625}@anchor{1d20}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40947}: The Python @ref{aaa,,Path Configuration} now
takes @ref{1d21,,PyConfig.platlibdir} in account.

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Remove the old parser, the @code{parser} module and all
associated support code, command-line options and environment variables.
Patch by Pablo Galindo.

@item 
bpo-40847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40847}: Fix a bug where a line with only a line continuation character
is not considered a blank line at tokenizer level. In such cases, more
than a single @code{NEWLINE} token was emitted. The old parser was working
around the issue, but the new parser threw a @ref{18e,,SyntaxError} for valid
input due to this. For example, an empty line following a line
continuation character was interpreted as a @ref{18e,,SyntaxError}.

@item 
bpo-40890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40890}: Each dictionary view now has a @code{mapping} attribute that
provides a @ref{698,,types.MappingProxyType} wrapping the original
dictionary.  Patch contributed by Dennis Sweeney.

@item 
bpo-40889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40889}: Improved the performance of symmetric difference operations on
dictionary item views.  Patch by Dennis Sweeney.

@item 
bpo-40904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40904}: Fix possible segfault in the new PEG parser when parsing
f-string containing yield statements with no value (@code{f"@{yield@}"}).
Patch by Pablo Galindo

@item 
bpo-40903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40903}: Fixed a possible segfault in the new PEG parser when producing
error messages for invalid assignments of the form @code{p=p=}. Patch by
Pablo Galindo

@item 
bpo-40880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40880}: Fix invalid memory read in the new parser when checking
newlines in string literals. Patch by Pablo Galindo.

@item 
bpo-40883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40883}: Fix memory leak in when parsing f-strings in the new parser.
Patch by Pablo Galindo

@item 
bpo-40870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40870}: Raise @ref{2ec,,ValueError} when validating custom AST's where the
constants @code{True}, @code{False} and @code{None} are used within a
@ref{1d22,,ast.Name} node.

@item 
bpo-40854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40854}: Allow overriding @ref{b32,,sys.platlibdir} via a new
@geindex PYTHONPLATLIBDIR
@geindex 環境変数; PYTHONPLATLIBDIR
@ref{1d23,,PYTHONPLATLIBDIR} environment variable.

@item 
bpo-40826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40826}: Fix GIL usage in @code{PyOS_Readline()}: lock the GIL to set
an exception and pass the Python thread state when checking if there is a
pending signal.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{5d,,fcntl} to multiphase initialization.

@item 
bpo-19468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19468}: Delete unnecessary instance check in importlib.reload(). Patch
by Furkan Önder.

@item 
bpo-40824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40824}: Unexpected errors in calling the @code{__iter__} method are no
longer masked by @code{TypeError} in the @ref{34b,,in} operator and functions
@ref{ad7,,contains()}, @ref{ad8,,indexOf()} and
@ref{ad9,,countOf()} of the @ref{a3,,operator} module.

@item 
bpo-40792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40792}: Attributes @code{start}, @code{stop} and @code{step} of the
@ref{b3d,,range} object now always has exact type @ref{19b,,int}.  Previously,
they could have been an instance of a subclass of @code{int}.

@item 
bpo-40780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40780}: Fix a corner case where g-style string formatting of a float
failed to remove trailing zeros.

@item 
bpo-38964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38964}: When there's a @ref{18e,,SyntaxError} in the expression part of an
fstring, the filename attribute of the @ref{18e,,SyntaxError} gets correctly
set to the name of the file the fstring resides in.

@item 
bpo-40750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40750}: Support the "-d" debug flag in the new PEG parser. Patch by
Pablo Galindo

@item 
bpo-40217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40217}: Instances of types created with
@ref{79e,,PyType_FromSpecWithBases()} will no longer automatically visit
their class object when traversing references in the garbage collector.
The user is expected to manually visit the object's class. Patch by Pablo
Galindo.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: @ref{3c9,,Py_TYPE()} is changed to the inline static function.
Patch by Donghee Na.

@item 
bpo-40696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40696}: Fix a hang that can arise after @ref{71c,,generator.throw()} due to
a cycle in the exception context chain.

@item 
bpo-40521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40521}: Each interpreter now its has own free lists, singletons and
caches:


@itemize *

@item 
Free lists: float, tuple, list, dict, frame, context,
asynchronous generator, MemoryError.

@item 
Singletons: empty tuple, empty bytes string, empty Unicode string,
single byte character, single Unicode (latin1) character.

@item 
Slice cache.
@end itemize

They are no longer shared by all interpreters.

@item 
bpo-40679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40679}: Certain @ref{198,,TypeError} messages about missing or extra
arguments now include the function's @ref{1d24,,qualified name}.  Patch by
Dennis Sweeney.

@item 
bpo-29590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29590}: Make the stack trace correct after calling
@ref{71c,,generator.throw()} on a generator that has yielded from a @code{yield
from}.

@item 
bpo-4022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4022}: Improve performance of generators by not raising internal
StopIteration.
@end itemize

@node ライブラリ<148>,Core and Builtins<146>,Core and Builtins<145>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id626}@anchor{1d25}
@subsubsection ライブラリ



@itemize -

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{94,,mmap} to multiphase initialization.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @code{_lzma} to multiphase initialization.
@end itemize

@node Core and Builtins<146>,ライブラリ<149>,ライブラリ<148>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id627}@anchor{1d26}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-37999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37999}: Builtin and extension functions that take integer arguments no
longer accept @ref{1fe,,Decimal}s, @ref{213,,Fraction}s and other objects that can be converted to integers only with a loss
(e.g. that have the @ref{19d,,__int__()} method but do not have the
@ref{19e,,__index__()} method).

@item 
bpo-29882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29882}: Add @ref{9cf,,int.bit_count()}, counting the number of ones in the
binary representation of an integer. Patch by Niklas Fiekas.
@end itemize

@node ライブラリ<149>,Core and Builtins<147>,Core and Builtins<146>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id628}@anchor{1d27}
@subsubsection ライブラリ



@itemize -

@item 
bpo-36982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36982}: Use ncurses extended color functions when available to support
terminals with 256 colors, and add the new function
@ref{9f6,,curses.has_extended_color_support()} to indicate whether extended
color support is provided by the underlying ncurses library.
@end itemize

@node Core and Builtins<147>,ライブラリ<150>,ライブラリ<149>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id629}@anchor{1d28}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-19569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19569}: Add the private macros @code{_Py_COMP_DIAG_PUSH},
@code{_Py_COMP_DIAG_IGNORE_DEPR_DECLS}, and @code{_Py_COMP_DIAG_POP}.

@item 
bpo-26680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26680}: The int type now supports the x.is_integer() method for
compatibility with float.
@end itemize

@node ライブラリ<150>,ドキュメント<44>,Core and Builtins<147>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id630}@anchor{1d29}
@subsubsection ライブラリ



@itemize -

@item 
bpo-41900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41900}: C14N 2.0 serialisation in xml.etree.ElementTree failed for
unprefixed attributes when a default namespace was defined.

@item 
bpo-41887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41887}: Strip leading spaces and tabs on @ref{e12,,ast.literal_eval()}. Also
document stripping of spaces and tabs for @ref{4a3,,eval()}.

@item 
bpo-41773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41773}: Note in documentation that @ref{ec1,,random.choices()} doesn't
support non-finite weights, raise @ref{2ec,,ValueError} when given non-finite
weights.

@item 
bpo-41840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41840}: Fix a bug in the @ref{de,,symtable} module that was causing
module-scope global variables to not be reported as both local and global.
Patch by Pablo Galindo.

@item 
bpo-41842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41842}: Add @ref{9e9,,codecs.unregister()} function to unregister a codec
search function.

@item 
bpo-40564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40564}: In @code{zipfile.Path}, mutate the passed ZipFile object type
instead of making a copy. Prevents issues when both the local copy and the
caller’s copy attempt to close the same file handle.

@item 
bpo-40670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40670}: More reliable validation of statements in
@ref{16e1,,timeit.Timer}. It now accepts "empty" statements (only whitespaces
and comments) and rejects misindentent statements.

@item 
bpo-41833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41833}: The @ref{176,,threading.Thread} constructor now uses the target
name if the `target' argument is specified but the `name' argument is
omitted.

@item 
bpo-41817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41817}: fix @code{tkinter.EventType} Enum so all members are strings, and
none are tuples

@item 
bpo-41810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41810}: @ref{a51,,types.EllipsisType}, @ref{a53,,types.NotImplementedType}
and @ref{a52,,types.NoneType} have been reintroduced, providing a new set of
types readily interpretable by static type checkers.

@item 
bpo-41815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41815}: Fix SQLite3 segfault when backing up closed database. Patch
contributed by Peter David McCormick.

@item 
bpo-41816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41816}: StrEnum added: it ensures that all members are already strings
or string candidates

@item 
bpo-41517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41517}: fix bug allowing Enums to be extended via multiple inheritance

@item 
bpo-39587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39587}: use the correct mix-in data type when constructing Enums

@item 
bpo-41792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41792}: Add is_typeddict function to typing.py to check if a type is a
TypedDict class

Previously there was no way to check that without using private API. See
the relevant issue in python/typing@footnote{https://github.com/python/typing/issues/751}.

@item 
bpo-41789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41789}: Honor @code{object} overrides in @code{Enum} class creation
(specifically, @code{__str__}, @code{__repr__}, @code{__format__}, and
@code{__reduce_ex__}).

@item 
bpo-32218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32218}: @code{enum.Flag} and @code{enum.IntFlag} members are now iterable.

@item 
bpo-39651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39651}: Fix a race condition in the @code{call_soon_threadsafe()} method
of @code{asyncio.ProactorEventLoop}: do nothing if the self-pipe socket has
been closed.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{mashal} extension module to the multi-phase
initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port the @code{_string} extension module to the multi-phase
initialization API (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-41732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41732}: Added an @ref{4c8,,iterator} to @ref{165,,memoryview}.

@item 
bpo-41720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41720}: Fixed @code{turtle.Vec2D.__rmul__()} for arguments which are not
int or float.

@item 
bpo-41696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41696}: Fix handling of debug mode in @ref{2f3,,asyncio.run()}. This allows
setting @code{PYTHONASYNCIODEBUG} or @code{-X dev} to enable asyncio debug mode
when using @ref{2f3,,asyncio.run()}.

@item 
bpo-41687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41687}: Fix implementation of sendfile to be compatible with Solaris.

@item 
bpo-41662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41662}: No longer override exceptions raised in @code{__len__()} of a
sequence of parameters in @ref{d4,,sqlite3} with
@ref{305,,ProgrammingError}.

@item 
bpo-39010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39010}: Restarting a @code{ProactorEventLoop} on Windows no longer logs
spurious @code{ConnectionResetErrors}.

@item 
bpo-41638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41638}: @ref{305,,ProgrammingError} message for absent parameter
in @ref{d4,,sqlite3} contains now the name of the parameter instead of its
index when parameters are supplied as a dict.

@item 
bpo-41662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41662}: Fixed crash when mutate list of parameters during iteration in
@ref{d4,,sqlite3}.

@item 
bpo-41513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41513}: Improved the accuracy of math.hypot().  Internally, each step
is computed with extra precision so that the result is now almost always
correctly rounded.

@item 
bpo-41609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41609}: The pdb whatis command correctly reports instance methods as
'Method' rather than 'Function'.

@item 
bpo-39994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39994}: Fixed pprint's handling of dict subclasses that override
__repr__.

@item 
bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}: When cancelling the task due to a timeout,
@ref{815,,asyncio.wait_for()} will now wait until the cancellation is complete
also in the case when `timeout' is <= 0, like it does with positive
timeouts.

@item 
bpo-37658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37658}: @ref{815,,asyncio.wait_for()} now properly handles races between
cancellation of itself and the completion of the wrapped awaitable.

@item 
bpo-40782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40782}: Change the method asyncio.AbstractEventLoop.run_in_executor to
not be a coroutine.

@item 
bpo-41520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41520}: Fix @ref{1d,,codeop} regression that prevented turning compile
warnings into errors.

@item 
bpo-41528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41528}: turtle uses math module functions to convert degrees to radians
and vice versa and to calculate vector norm

@item 
bpo-41513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41513}: Minor algorithmic improvement to math.hypot() and math.dist()
giving small gains in speed and accuracy.

@item 
bpo-41503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41503}: Fixed a race between setTarget and flush in
logging.handlers.MemoryHandler.

@item 
bpo-41497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41497}: Fix potential UnicodeDecodeError in dis module.

@item 
bpo-41467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41467}: On Windows, fix asyncio @code{recv_into()} return value when the
socket/pipe is closed (@ref{1267,,BrokenPipeError}): return @code{0} rather than
an empty byte string (@code{b'@w{'}}).

@item 
bpo-41425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41425}: Make tkinter doc example runnable.

@item 
bpo-41421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41421}: Make an algebraic simplification to random.paretovariate().  It
now is slightly less subject to round-off error and is slightly faster.
Inputs that used to cause ZeroDivisionError now cause an OverflowError
instead.

@item 
bpo-41440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41440}: Add @ref{4db,,os.cpu_count()} support for VxWorks RTOS.

@item 
bpo-41316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41316}: Fix the @ref{e4,,tarfile} module to write only basename of TAR
file to GZIP compression header.

@item 
bpo-41384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41384}: Raise TclError instead of TypeError when an unknown option is
passed to tkinter.OptionMenu.

@item 
bpo-41317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41317}: Use add_done_callback() in asyncio.loop.sock_accept() to
unsubscribe reader early on cancellation.

@item 
bpo-41364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41364}: Reduce import overhead of @ref{116,,uuid}.

@item 
bpo-35328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35328}: Set the environment variable @code{VIRTUAL_ENV_PROMPT} at
@ref{117,,venv} activation.

@item 
bpo-41341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41341}: Recursive evaluation of @code{typing.ForwardRef} in
@code{get_type_hints}.

@item 
bpo-41344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41344}: Prevent creating @code{shared_memory.SharedMemory} objects
with @code{size=0}.

@item 
bpo-41333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41333}: @code{collections.OrderedDict.pop()} is now 2 times faster.

@item 
bpo-41288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41288}: Unpickling invalid NEWOBJ_EX opcode with the C implementation
raises now UnpicklingError instead of crashing.

@item 
bpo-39017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39017}: Avoid infinite loop when reading specially crafted TAR files
using the tarfile module (
@geindex Common Vulnerabilities and Exposures; CVE 2019-20907
CVE 2019-20907@footnote{https://www.cve.org/CVERecord?id=CVE-2019-20907}).

@item 
bpo-41273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41273}: Speed up any transport using @code{_ProactorReadPipeTransport} by
calling @code{recv_into} instead of @code{recv}, thus not creating a new buffer
for each @code{recv} call in the transport's read loop.

@item 
bpo-41235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41235}: Fix the error handling in
@ref{135a,,ssl.SSLContext.load_dh_params()}.

@item 
bpo-41207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41207}: In distutils.spawn, restore expectation that DistutilsExecError
is raised when the command is not found.

@item 
bpo-29727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29727}: Register @ref{4be,,array.array} as a
@ref{4bf,,MutableSequence}. Patch by Pablo Galindo.

@item 
bpo-39168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39168}: Remove the @code{__new__} method of @ref{17b6,,typing.Generic}.

@item 
bpo-41194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41194}: Fix a crash in the @code{_ast} module: it can no longer be loaded
more than once. It now uses a global state rather than a module state.

@item 
bpo-41195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41195}: Add read-only ssl.SSLContext.security_level attribute to
retrieve the context's security level.

@item 
bpo-41193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41193}: The @code{write_history()} atexit function of the readline
completer now ignores any @ref{2c0,,OSError} to ignore error if the filesystem
is read-only, instead of only ignoring @ref{264,,FileNotFoundError} and
@ref{f3e,,PermissionError}.

@item 
bpo-41182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41182}: selector: use DefaultSelector based upon implementation

@item 
bpo-41161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41161}: The decimal module now requires libmpdec-2.5.0. Users of
--with-system-libmpdec should update their system library.

@item 
bpo-40874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40874}: The decimal module now requires libmpdec-2.5.0.

@item 
bpo-41138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41138}: Fixed the @ref{103,,trace} module CLI for Python source files with
non-UTF-8 encoding.

@item 
bpo-31082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31082}: Use the term "iterable" in the docstring for
@ref{21a,,functools.reduce()}.

@item 
bpo-40521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40521}: Remove freelist from collections.deque().

@item 
bpo-31938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31938}: Fix default-value signatures of several functions in the
@ref{c6,,select} module - by Anthony Sottile.

@item 
bpo-41068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41068}: Fixed reading files with non-ASCII names from ZIP archive
directly after writing them.

@item 
bpo-41058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41058}: @code{pdb.find_function()} now correctly determines the source
file encoding.

@item 
bpo-41056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41056}: Invalid file descriptor values are now prevented from being
passed to os.fpathconf. (discovered by Coverity)

@item 
bpo-41056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41056}: Fix a NULL pointer dereference within the ssl module during a
MemoryError in the keylog callback. (discovered by Coverity)

@item 
bpo-41056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41056}: Fixed an instance where a MemoryError within the zoneinfo
module might not be reported or not reported at its source. (found by
Coverity)

@item 
bpo-41048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41048}: @ref{1d2a,,mimetypes.read_mime_types()} function reads the rule file
using UTF-8 encoding, not the locale encoding. Patch by Srinivas Reddy
Thatiparthy.

@item 
bpo-41043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41043}: Fixed the use of @ref{5a0,,glob()} in the stdlib: literal part
of the path is now always correctly escaped.

@item 
bpo-41025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41025}: Fixed an issue preventing the C implementation of
@ref{adc,,zoneinfo.ZoneInfo} from being subclassed.

@item 
bpo-35018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35018}: Add the @ref{a5c,,xml.sax.handler.LexicalHandler} class that is
present in other SAX XML implementations.

@item 
bpo-41002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41002}: Improve performance of HTTPResponse.read with a given amount.
Patch by Bruce Merry.

@item 
bpo-40448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40448}: @ref{59,,ensurepip} now disables the use of @code{pip} cache when
installing the bundled versions of @code{pip} and @code{setuptools}.  Patch by
Krzysztof Konopko.

@item 
bpo-40967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40967}: Removed @code{asyncio.Task.current_task()} and
@code{asyncio.Task.all_tasks()}. Patch contributed by Rémi Lapeyre.

@item 
bpo-40924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40924}: Ensure @code{importlib.resources.path} returns an extant path for
the SourceFileLoader's resource reader. Avoids the regression identified
in master while a long-term solution is devised.

@item 
bpo-40955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40955}: Fix a minor memory leak in @ref{dc,,subprocess} module when
extra_groups was specified.

@item 
bpo-40855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40855}: The standard deviation and variance functions in the statistics
module were ignoring their mu and xbar arguments.

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Use the new PEG parser when generating the stdlib
@ref{88,,keyword} module.

@item 
bpo-23427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23427}: Add @ref{a41,,sys.orig_argv} attribute: the list of the original
command line arguments passed to the Python executable.

@item 
bpo-33689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33689}: Ignore empty or whitespace-only lines in .pth files. This
matches the documentated behavior. Before, empty lines caused the
site-packages dir to appear multiple times in sys.path. By Ido Michael,
contributors Malcolm Smith and Tal Einat.

@item 
bpo-40884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40884}: Added a @code{defaults} parameter to @ref{16b0,,logging.Formatter},
to allow specifying default values for custom fields. Patch by Asaf Alon
and Bar Harel.

@item 
bpo-40876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40876}: Clarify error message in the @ref{2d,,csv} module.

@item 
bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791}: Refresh importlib.metadata from importlib_metadata 1.6.1.

@item 
bpo-40807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40807}: Stop codeop._maybe_compile, used by code.InteractiveInterpreter
(and IDLE). from emitting each warning three times.

@item 
bpo-32604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32604}: Fix reference leak in the @ref{c6,,select} module when the module
is imported in a subinterpreter.

@item 
bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791}: Built-in loaders (SourceFileLoader and ZipImporter) now supply
@code{TraversableResources} implementations for @code{ResourceReader}, and the
fallback function has been removed.

@item 
bpo-39314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39314}: @ref{1d2b,,rlcompleter.Completer} and the standard Python shell
now close the parenthesis for functions that take no arguments. Patch
contributed by Rémi Lapeyre.

@item 
bpo-17005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17005}: The topological sort functionality that was introduced
initially in the @ref{63,,functools} module has been moved to a new
@ref{69,,graphlib} module to better accommodate the new tools and keep the
original scope of the @ref{63,,functools} module. Patch by Pablo Galindo

@item 
bpo-40834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40834}: Fix truncate when sending str object
with_xxsubinterpreters.channel_send.

@item 
bpo-40755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40755}: Add rich comparisons to collections.Counter().

@item 
bpo-26407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26407}: Unexpected errors in calling the @code{__iter__} method are no
longer masked by @code{TypeError} in @ref{6ae,,csv.reader()},
@code{csv.writer.writerow()} and @code{csv.writer.writerows()}.

@item 
bpo-39384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39384}: Fixed email.contentmanager to allow set_content() to set a null
string.

@item 
bpo-40744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40744}: The @ref{d4,,sqlite3} module uses SQLite API functions that
require SQLite v3.7.3 or higher.  This patch removes support for older
SQLite versions, and explicitly requires SQLite 3.7.3 both at build,
compile and runtime.  Patch by Sergey Fedoseev and Erlend E. Aasland.

@item 
bpo-40777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40777}: Initialize PyDateTime_IsoCalendarDateType.tp_base at run-time
to avoid errors on some compilers.

@item 
bpo-38488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38488}: Update ensurepip to install pip 20.1.1 and setuptools 47.1.0.

@item 
bpo-40792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40792}: The result of @ref{1cd2,,operator.index()} now always has exact type
@ref{19b,,int}. Previously, the result could have been an instance of a
subclass of @code{int}.

@item 
bpo-40767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40767}: @ref{11b,,webbrowser} now properly finds the default browser in
pure Wayland systems by checking the WAYLAND_DISPLAY environment variable.
Patch contributed by Jérémy Attali.

@item 
bpo-40791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40791}: @code{hashlib.compare_digest()} uses OpenSSL's
@code{CRYPTO_memcmp()} function when OpenSSL is available.

@item 
bpo-40795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40795}: @ref{2e,,ctypes} module: If ctypes fails to convert the result of
a callback or if a ctypes callback function raises an exception,
sys.unraisablehook is now called with an exception set. Previously, the
error was logged into stderr by @ref{1d2c,,PyErr_Print()}.

@item 
bpo-16995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16995}: Add @ref{9e4,,base64.b32hexencode()} and @ref{9e5,,base64.b32hexdecode()}
to support the Base32 Encoding with Extended Hex Alphabet.

@item 
bpo-30008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30008}: Fix @ref{d5,,ssl} code to be compatible with OpenSSL 1.1.x builds
that use @code{no-deprecated} and @code{--api=1.1.0}.

@item 
bpo-30064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30064}: Fix asyncio @code{loop.sock_*} race condition issue

@item 
bpo-40759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40759}: Deprecate the @code{symbol} module.

@item 
bpo-40756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40756}: The second argument (extra) of @code{LoggerAdapter.__init__} now
defaults to None.

@item 
bpo-37129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37129}: Add a new @ref{1d2d,,os.RWF_APPEND} flag for @ref{d57,,os.pwritev()}.

@item 
bpo-40737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40737}: Fix possible reference leak for @ref{d4,,sqlite3} initialization.

@item 
bpo-40726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40726}: Handle cases where the @code{end_lineno} is @code{None} on
@ref{1b0d,,ast.increment_lineno()}.

@item 
bpo-40698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40698}: @code{distutils} upload creates SHA2-256 and Blake2b-256 digests.
MD5 digests is skipped if platform blocks MD5.

@item 
bpo-40695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40695}: @ref{6c,,hashlib} no longer falls back to builtin hash
implementations when OpenSSL provides a hash digest and the algorithm is
blocked by security policy.

@item 
bpo-9216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9216}: @ref{1d2e,,hashlib.new()} passed @code{usedforsecurity} to OpenSSL EVP
constructor @code{_hashlib.new()}. test_hashlib and test_smtplib handle
strict security policy better.

@item 
bpo-40614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40614}: @ref{1c2,,ast.parse()} will not parse self documenting expressions
in f-strings when passed @code{feature_version} is less than @code{(3, 8)}.

@item 
bpo-40626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40626}: Add h5 file extension as MIME Type application/x-hdf5, as per
HDF Group recommendation for HDF5 formatted data files. Patch contributed
by Mark Schwab.

@item 
bpo-25920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25920}: On macOS, when building Python for macOS 10.4 and older, which
wasn't the case for python.org macOS installer, @ref{1ac3,,socket.getaddrinfo()}
no longer uses an internal lock to prevent race conditions when calling
@code{getaddrinfo()} which is thread-safe since macOS 10.5. Python 3.9
requires macOS 10.6 or newer. The internal lock caused random hang on fork
when another thread was calling @ref{1ac3,,socket.getaddrinfo()}. The lock was
also used on FreeBSD older than 5.3, OpenBSD older than 201311 and NetBSD
older than 4.

@item 
bpo-40671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40671}: Prepare @code{_hashlib} for 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} and use
@ref{b6c,,PyModule_AddType()}.

@item 
bpo-32309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32309}: Added a new @ref{6b9,,coroutine} @ref{ae5,,asyncio.to_thread()}. It is
mainly used for running IO-bound functions in a separate thread to avoid
blocking the event loop, and essentially works as a high-level version of
@ref{ae6,,run_in_executor()} that can directly take keyword
arguments.

@item 
bpo-36543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36543}: Restored the deprecated @code{xml.etree.cElementTree} module.

@item 
bpo-40611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40611}: @ref{1d2f,,MAP_POPULATE} constant has now been added to the
list of exported @ref{94,,mmap} module flags.

@item 
bpo-39881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39881}: PEP 554 for use in the test suite. (Patch By Joannah Nanjekye)

@item 
bpo-13097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13097}: @code{ctypes} now raises an @code{ArgumentError} when a callback is
invoked with more than 1024 arguments.

@item 
bpo-39385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39385}: A new test assertion context-manager,
@code{unittest.assertNoLogs()} will ensure a given block of code emits no
log messages using the logging module. Contributed by Kit Yan Choi.

@item 
bpo-23082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23082}: Updated the error message and docs of PurePath.relative_to() to
better reflect the function behaviour.

@item 
bpo-40318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40318}: Use SQLite3 trace v2 API, if it is available.

@item 
bpo-40105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40105}: ZipFile truncates files to avoid corruption when a shorter
comment is provided in append ("a") mode. Patch by Jan Mazur.

@item 
bpo-40084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40084}: Fix @code{Enum.__dir__}: dir(Enum.member) now includes attributes
as well as methods.

@item 
bpo-31122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31122}: ssl.wrap_socket() now raises ssl.SSLEOFError rather than
OSError when peer closes connection during TLS negotiation

@item 
bpo-39728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39728}: fix default @code{_missing_} so a duplicate @code{ValueError} is not
set as the @code{__context__} of the original @code{ValueError}.

@item 
bpo-39244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39244}: Fixed @code{multiprocessing.context.get_all_start_methods} to
properly return the default method first on macOS.

@item 
bpo-39040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39040}: Fix parsing of invalid mime headers parameters by collapsing
whitespace between encoded words in a bare-quote-string.

@item 
bpo-38731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38731}: Add @code{--quiet} option to command-line interface of
@ref{b8,,py_compile}. Patch by Gregory Schevchenko.

@item 
bpo-35714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35714}: @ref{153b,,struct.error} is now raised if there is a null character
in a @ref{db,,struct} format string.

@item 
bpo-38144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38144}: Added the `root_dir' and `dir_fd' parameters in
@ref{5a0,,glob.glob()}.

@item 
bpo-26543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26543}: Fix @code{IMAP4.noop()} when debug mode is enabled (ex:
@code{imaplib.Debug = 3}).

@item 
bpo-12178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12178}: @ref{6af,,csv.writer()} now correctly escapes `escapechar' when
input contains `escapechar'.  Patch by Catalin Iacob, Berker Peksag, and
Itay Elbirt.

@item 
bpo-36290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36290}: AST nodes are now raising @ref{198,,TypeError} on conflicting
keyword arguments. Patch contributed by Rémi Lapeyre.

@item 
bpo-33944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33944}: Added site.py site-packages tracing in verbose mode.

@item 
bpo-35078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35078}: Refactor formatweekday, formatmonthname methods in
LocaleHTMLCalendar and LocaleTextCalendar classes in calendar module to
call the base class methods.This enables customizable CSS classes for
LocaleHTMLCalendar. Patch by Srinivas Reddy Thatiparthy

@item 
bpo-29620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29620}: @ref{137c,,assertWarns()} no longer raises a
@code{RuntimeException} when accessing a module's @code{__warningregistry__}
causes importation of a new module, or when a new module is imported in
another thread. Patch by Kernc.

@item 
bpo-31844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31844}: Remove @code{ParserBase.error()} method from the private and
undocumented @code{_markupbase} module.  @ref{a77,,html.parser.HTMLParser} is
the only subclass of @code{ParserBase} and its @code{error()} implementation was
deprecated in Python 3.4 and removed in Python 3.5.

@item 
bpo-34226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34226}: Fix @code{cgi.parse_multipart} without content_length. Patch by
Roger Duran

@item 
bpo-33660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33660}: Fix pathlib.PosixPath to resolve a relative path located on the
root directory properly.

@item 
bpo-28557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28557}: Improve the error message for a misbehaving @code{rawio.readinto}

@item 
bpo-26680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26680}: The d.is_integer() method is added to the Decimal type, for
compatibility with other number types.

@item 
bpo-26680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26680}: The x.is_integer() method is incorporated into the abstract
types of the numeric tower, Real, Rational and Integral, with appropriate
default implementations.
@end itemize

@node ドキュメント<44>,テスト<43>,ライブラリ<150>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id631}@anchor{1d30}
@subsubsection ドキュメント



@itemize -

@item 
bpo-41428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41428}: Add documentation for 
@geindex Python Enhancement Proposals; PEP 604
PEP 604@footnote{https://peps.python.org/pep-0604/} (Allow writing union types as
@code{X | Y}).

@item 
bpo-41774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41774}: In Programming FAQ "Sequences (Tuples/Lists)" section, add "How
do you remove multiple items from a list".

@item 
bpo-35293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35293}: Fix RemovedInSphinx40Warning when building the documentation.
Patch by Donghee Na.

@item 
bpo-37149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37149}: Change Shipman tkinter doc link from archive.org to TkDocs.
(The doc has been removed from the NMT server.)  The new link responds
much faster and includes a short explanatory note.

@item 
bpo-41726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41726}: Update the refcounts info of @code{PyType_FromModuleAndSpec}.

@item 
bpo-41624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41624}: Fix the signature of @ref{1d31,,typing.Coroutine}.

@item 
bpo-40204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40204}: Enable Sphinx 3.2 @code{c_allow_pre_v3} option and disable
@code{c_warn_on_allowed_pre_v3} option to make the documentation compatible
with Sphinx 2 and Sphinx 3.

@item 
bpo-41045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41045}: Add documentation for debug feature of f-strings.

@item 
bpo-41314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41314}: Changed the release when @code{from __future__ import annotations}
becomes the default from @code{4.0} to @code{3.10} (following a change in PEP
563).

@item 
bpo-40979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40979}: Refactored typing.rst, arranging more than 70 classes,
functions, and decorators into new sub-sections.

@item 
bpo-40552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40552}: Fix in tutorial section 4.2. Code snippet is now correct.

@item 
bpo-39883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39883}: Make code, examples, and recipes in the Python documentation be
licensed under the more permissive BSD0 license in addition to the
existing Python 2.0 license.

@item 
bpo-37703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37703}: Updated Documentation to comprehensively elaborate on the
behaviour of gather.cancel()
@end itemize

@node テスト<43>,ビルド<50>,ドキュメント<44>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id632}@anchor{1d32}
@subsubsection テスト



@itemize -

@item 
bpo-41939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41939}: Fix test_site.test_license_exists_at_url(): call
@code{urllib.request.urlcleanup()} to reset the global
@code{urllib.request._opener}. Patch by Victor Stinner.

@item 
bpo-41731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41731}: Make test_cmd_line_script pass with option '-vv'.

@item 
bpo-41602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41602}: Add tests for SIGINT handling in the runpy module.

@item 
bpo-41521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41521}: @ref{ea,,test.support}: Rename @code{blacklist} parameter of
@ref{1d33,,check__all__()} to @code{not_exported}.

@item 
bpo-41477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41477}: Make ctypes optional in test_genericalias.

@item 
bpo-41085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41085}: Fix integer overflow in the @ref{9e1,,array.array.index()} method on
64-bit Windows for index larger than @code{2**31}.

@item 
bpo-41069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41069}: @code{test.support.TESTFN} and the current directory for tests
when run via @code{test.regrtest} contain now non-ascii characters if
possible.

@item 
bpo-38377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38377}: On Linux, skip tests using multiprocessing if the current user
cannot create a file in @code{/dev/shm/} directory. Add the
@ref{1d34,,skip_if_broken_multiprocessing_synchronize()} function
to the @ref{ea,,test.support} module.

@item 
bpo-41009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41009}: Fix use of @code{support.require_@{linux|mac|freebsd@}_version()}
decorators as class decorator.

@item 
bpo-41003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41003}: Fix @code{test_copyreg} when @code{numpy} is installed:
@code{test.pickletester} now saves/restores warnings filters when importing
@code{numpy}, to ignore filters installed by @code{numpy}.

@item 
bpo-40964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40964}: Disable remote @ref{78,,imaplib} tests, host cyrus.andrew.cmu.edu
is blocking incoming connections.

@item 
bpo-40927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40927}: Fix test_binhex when run twice: it now uses
import_fresh_module() to ensure that it raises DeprecationWarning each
time.

@item 
bpo-17258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17258}: Skip some @ref{98,,multiprocessing} tests when MD5 hash digest is
blocked.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Increase LOOPBACK_TIMEOUT to 10 for VxWorks RTOS.

@item 
bpo-38169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38169}: Increase code coverage for SharedMemory and ShareableList

@item 
bpo-34401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34401}: Make test_gdb properly run on HP-UX. Patch by Michael Osipov.
@end itemize

@node ビルド<50>,Windows<44>,テスト<43>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id633}@anchor{1d35}
@subsubsection ビルド



@itemize -

@item 
bpo-38249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38249}: Update @ref{dae,,Py_UNREACHABLE} to use __builtin_unreachable()
if only the compiler is able to use it. Patch by Donghee Na.

@item 
bpo-41617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41617}: Fix @code{pycore_bitutils.h} header file to support old clang
versions: @code{__builtin_bswap16()} is not available in LLVM clang 3.0.

@item 
bpo-40204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40204}: Pin Sphinx version to 2.3.1 in @code{Doc/Makefile}.

@item 
bpo-36020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36020}: The C99 functions @code{snprintf()} and @code{vsnprintf()}
are now required to build Python.

@item 
bpo-40684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40684}: @code{make install} now uses the @code{PLATLIBDIR} variable for the
destination @code{lib-dynload/} directory when @code{./configure
--with-platlibdir} is used.

@item 
bpo-40683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40683}: Fixed an issue where the @ref{13a,,zoneinfo} module and its tests
were not included when Python is installed with @code{make}.
@end itemize

@node Windows<44>,macOS<34>,ビルド<50>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id634}@anchor{1d36}
@subsubsection Windows



@itemize -

@item 
bpo-41744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41744}: Fixes automatic import of props file when using the Nuget
package.

@item 
bpo-41627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41627}: The user site directory for 32-bit now includes a @code{-32}
suffix to distinguish it from the 64-bit interpreter's directory.

@item 
bpo-41526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41526}: Fixed layout of final page of the installer by removing the
special thanks to Mark Hammond (with his permission).

@item 
bpo-41492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41492}: Fixes the description that appears in UAC prompts.

@item 
bpo-40948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40948}: Improve post-install message to direct people to the "py"
command.

@item 
bpo-41412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41412}: The installer will now fail to install on Windows 7 and Windows
8. Further, the UCRT dependency is now always downloaded on demand.

@item 
bpo-40741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40741}: Update Windows release to include SQLite 3.32.3.

@item 
bpo-41142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41142}: @code{msilib} now supports creating CAB files with non-ASCII
file path and adding files with non-ASCII file path to them.

@item 
bpo-41074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41074}: Fixed support of non-ASCII names in functions
@code{msilib.OpenDatabase()} and @code{msilib.init_database()} and
non-ASCII SQL in method @code{msilib.Database.OpenView()}.

@item 
bpo-41039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41039}: Stable ABI redirection DLL (python3.dll) now uses @code{#pragma
comment(linker)} for re-exporting.

@item 
bpo-40164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40164}: Updates Windows OpenSSL to 1.1.1g

@item 
bpo-39631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39631}: Changes the registered MIME type for @code{.py} files on Windows
to @code{text/x-python} instead of @code{text/plain}.

@item 
bpo-40677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40677}: Manually define IO_REPARSE_TAG_APPEXECLINK in case some old
Windows SDK doesn't have it.

@item 
bpo-37556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37556}: Extend py.exe help to mention overrides via venv, shebang,
environmental variables & ini files.
@end itemize

@node macOS<34>,IDLE<26>,Windows<44>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id635}@anchor{1d37}
@subsubsection macOS



@itemize -

@item 
bpo-41557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41557}: Update macOS installer to use SQLite 3.33.0.

@item 
bpo-39580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39580}: Avoid opening Finder window if running installer from the
command line. Patch contributed by Rick Heil.

@item 
bpo-41100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41100}: Fix configure error when building on macOS 11. Note that the
current Python release was released shortly after the first developer
preview of macOS 11 (Big Sur); there are other known issues with building
and running on the developer preview. Big Sur is expected to be fully
supported in a future bugfix release of Python 3.8.x and with 3.9.0.

@item 
bpo-40741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40741}: Update macOS installer to use SQLite 3.32.3.

@item 
bpo-41005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41005}: fixed an XDG settings issue not allowing macos to open browser
in webbrowser.py

@item 
bpo-40741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40741}: Update macOS installer to use SQLite 3.32.2.
@end itemize

@node IDLE<26>,C API<45>,macOS<34>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id636}@anchor{1d38}
@subsubsection IDLE



@itemize -

@item 
bpo-41775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41775}: Use 'IDLE Shell' as shell title

@item 
bpo-35764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35764}: Rewrite the Calltips doc section.

@item 
bpo-40181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40181}: In calltips, stop reminding that '/' marks the end of
positional-only arguments.

@item 
bpo-41468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41468}: Improve IDLE run crash error message (which users should never
see).

@item 
bpo-41373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41373}: Save files loaded with no line ending, as when blank, or
different line endings, by setting its line ending to the system default.
Fix regression in 3.8.4 and 3.9.0b4.

@item 
bpo-41300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41300}: Save files with non-ascii chars. Fix regression released in
3.9.0b4 and 3.8.4.

@item 
bpo-37765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37765}: Add keywords to module name completion list.  Rewrite
Completions section of IDLE doc.

@item 
bpo-41152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41152}: The encoding of @code{stdin}, @code{stdout} and @code{stderr} in IDLE is
now always UTF-8.

@item 
bpo-41144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41144}: Make Open Module open a special module such as os.path.

@item 
bpo-39885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39885}: Make context menu Cut and Copy work again when right-clicking
within a selection.

@item 
bpo-40723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40723}: Make test_idle pass when run after import.
@end itemize

@node C API<45>,,IDLE<26>,Python 3 10 0 alpha 1
@anchor{whatsnew/changelog id637}@anchor{1d39}
@subsubsection C API



@itemize -

@item 
bpo-41936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41936}: Removed undocumented macros @code{Py_ALLOW_RECURSION} and
@code{Py_END_ALLOW_RECURSION} and the @code{recursion_critical} field of the
@ref{aba,,PyInterpreterState} structure.

@item 
bpo-41692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41692}: The @code{PyUnicode_InternImmortal()} function is now deprecated
and will be removed in Python 3.12: use @ref{aae,,PyUnicode_InternInPlace()}
instead. Patch by Victor Stinner.

@item 
bpo-41842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41842}: Add @ref{a97,,PyCodec_Unregister()} function to unregister a codec
search function.

@item 
bpo-41834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41834}: Remove the @code{_Py_CheckRecursionLimit} variable: it has been
replaced by @code{ceval.recursion_limit} of the @ref{aba,,PyInterpreterState}
structure. Patch by Victor Stinner.

@item 
bpo-41689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41689}: Types created with @ref{79d,,PyType_FromSpec()} now make any
signature in their @code{tp_doc} slot accessible from @code{__text_signature__}.

@item 
bpo-41524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41524}: Fix bug in @ref{1d3a,,PyOS_mystrnicmp()} and
@ref{1d3b,,PyOS_mystricmp()} that incremented pointers beyond the end of a
string.

@item 
bpo-41324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41324}: Add a minimal decimal capsule API.  The API supports fast
conversions between Decimals up to 38 digits and their triple
representation as a C struct.

@item 
bpo-30155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30155}: Add @ref{a95,,PyDateTime_DATE_GET_TZINFO()} and
@ref{a96,,PyDateTime_TIME_GET_TZINFO()} macros for accessing the @code{tzinfo}
attributes of @ref{4e2,,datetime.datetime} and @ref{1fb,,datetime.time}
objects.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Revert @ref{1d3c,,PyType_HasFeature()} change: it reads again
directly the @ref{1c71,,PyTypeObject.tp_flags} member when the limited C
API is not used, rather than always calling @ref{1d3d,,PyType_GetFlags()}
which hides implementation details.

@item 
bpo-41123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41123}: Remove @code{PyUnicode_AsUnicodeCopy}.

@item 
bpo-41123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41123}: Removed @code{PyLong_FromUnicode()}.

@item 
bpo-41123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41123}: Removed @code{PyUnicode_GetMax()}.

@item 
bpo-41123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41123}: Removed @code{Py_UNICODE_str*} functions manipulating
@code{Py_UNICODE*} strings.

@item 
bpo-41103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41103}: @code{PyObject_AsCharBuffer()}, @code{PyObject_AsReadBuffer()},
@code{PyObject_CheckReadBuffer()}, and @code{PyObject_AsWriteBuffer()} are
removed. Please migrate to new buffer protocol;
@ref{63a,,PyObject_GetBuffer()} and @ref{63b,,PyBuffer_Release()}.

@item 
bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}: Raises DeprecationWarning for @code{PyUnicode_FromUnicode(NULL,
size)} and @code{PyUnicode_FromStringAndSize(NULL, size)} with @code{size > 0}.

@item 
bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}: Mark @code{Py_UNICODE_COPY}, @code{Py_UNICODE_FILL},
@code{PyUnicode_WSTR_LENGTH}, @code{PyUnicode_FromUnicode},
@code{PyUnicode_AsUnicode}, and @code{PyUnicode_AsUnicodeAndSize} as deprecated
in C. Remove @code{Py_UNICODE_MATCH} which was deprecated and broken since
Python 3.3.

@item 
bpo-40989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40989}: The @ref{1d3e,,PyObject_INIT()} and @ref{1d3f,,PyObject_INIT_VAR()}
macros become aliases to, respectively, @ref{c60,,PyObject_Init()} and
@ref{1d40,,PyObject_InitVar()} functions.

@item 
bpo-36020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36020}: On Windows, @code{#include "pyerrors.h"} no longer defines
@code{snprintf} and @code{vsnprintf} macros.

@item 
bpo-40943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40943}: The @code{PY_SSIZE_T_CLEAN} macro must now be defined to use
@ref{3c1,,PyArg_ParseTuple()} and @ref{3c2,,Py_BuildValue()} formats which use
@code{#}: @code{es#}, @code{et#}, @code{s#}, @code{u#}, @code{y#}, @code{z#}, @code{U#} and
@code{Z#}. See @ref{3d5,,Parsing arguments and building values} and
the 
@geindex Python Enhancement Proposals; PEP 353
PEP 353@footnote{https://peps.python.org/pep-0353/}.

@item 
bpo-40910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40910}: Export explicitly the @ref{1d41,,Py_GetArgcArgv()} function to the
C API and document the function. Previously, it was exported implicitly
which no longer works since Python is built with @code{-fvisibility=hidden}.

@item 
bpo-40724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40724}: Allow defining buffer slots in type specs.

@item 
bpo-40679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40679}: Fix a @code{_PyEval_EvalCode()} crash if `qualname' argument is
NULL.

@item 
bpo-40839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40839}: Calling @ref{628,,PyDict_GetItem()} without @ref{164,,GIL} held had
been allowed for historical reason. It is no longer allowed.

@item 
bpo-40826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40826}: @ref{1d42,,PyOS_InterruptOccurred()} now fails with a fatal error
if it is called with the GIL released.

@item 
bpo-40792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40792}: The result of @ref{a93,,PyNumber_Index()} now always has exact
type @ref{19b,,int}. Previously, the result could have been an instance of a
subclass of @code{int}.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Convert @ref{2cf,,Py_REFCNT()} and @ref{985,,Py_SIZE()} macros to
static inline functions. They cannot be used as l-value anymore: use
@ref{aa8,,Py_SET_REFCNT()} and @ref{986,,Py_SET_SIZE()} to set an object
reference count and size. This change is backward incompatible on purpose,
to prepare the C API for an opaque @ref{5df,,PyObject} structure.

@item 
bpo-40703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40703}: The PyType_FromSpec*() functions no longer overwrite the type's
"__module__" attribute if it is set via "Py_tp_members" or "Py_tp_getset".

@item 
bpo-39583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39583}: Remove superfluous "extern C" declarations from
@code{Include/cpython/*.h}.
@end itemize

@node Python 3 9 0 beta 1,Python 3 9 0 alpha 6,Python 3 10 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-9-0-beta-1}@anchor{1d43}
@subsection Python 3.9.0 beta 1


`リリース日: 2020-05-19'

@menu
* セキュリティ: セキュリティ<37>. 
* Core and Builtins: Core and Builtins<148>. 
* ライブラリ: ライブラリ<151>. 
* ドキュメント: ドキュメント<45>. 
* テスト: テスト<44>. 
* ビルド: ビルド<51>. 
* Windows: Windows<45>. 
* macOS: macOS<35>. 
* Tools/Demos: Tools/Demos<30>. 
* C API: C API<46>. 

@end menu

@node セキュリティ<37>,Core and Builtins<148>,,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id638}@anchor{1d44}
@subsubsection セキュリティ



@itemize -

@item 
bpo-40501@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40501}: @ref{116,,uuid} no longer uses @ref{2e,,ctypes} to load
@code{libuuid} or @code{rpcrt4.dll} at runtime.
@end itemize

@node Core and Builtins<148>,ライブラリ<151>,セキュリティ<37>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id639}@anchor{1d45}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40663}: Correctly generate annotations where parentheses are omitted
but required (e.g: @code{Type[(str, int, *other))]}.

@item 
bpo-40596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40596}: Fixed @ref{1d46,,str.isidentifier()} for non-canonicalized strings
containing non-BMP characters on Windows.

@item 
bpo-40593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40593}: Improved syntax errors for invalid characters in source code.

@item 
bpo-40585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40585}: Fixed a bug when using @ref{1b53,,codeop.compile_command()} that was
causing exceptions to be swallowed with the new parser. Patch by Pablo
Galindo

@item 
bpo-40566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40566}: Apply 
@geindex Python Enhancement Proposals; PEP 573
PEP 573@footnote{https://peps.python.org/pep-0573/} to @ref{4,,abc}.

@item 
bpo-40502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40502}: Initialize @code{n->n_col_offset}. (Patch by Joannah Nanjekye)

@item 
bpo-40527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40527}: Fix command line argument parsing: no longer write errors
multiple times into stderr.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{5b,,errno} to multiphase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-40523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40523}: Add pass-throughs for @ref{801,,hash()} and @ref{a65,,reversed()} to
@ref{c46,,weakref.proxy} objects. Patch by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{e2,,syslog} to multiphase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-40246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40246}: Reporting a specialised error message for invalid string
prefixes, which was introduced in bpo-40246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40246}, is being reverted due to
backwards compatibility concerns for strings that immediately follow a
reserved keyword without whitespace between them. Constructs like
@code{bg="#d00" if clear else"#fca"} were failing to parse, which is not an
acceptable breakage on such short notice.

@item 
bpo-40417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40417}: Fix imp module deprecation warning when PyImport_ReloadModule
is called. Patch by Robert Rouhani.

@item 
bpo-40408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40408}: Fixed support of nested type variables in GenericAlias (e.g.
@code{list[list[T]]}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _stat module to multiphase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-29587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29587}: Enable implicit exception chaining when calling
@ref{71c,,generator.throw()}.

@item 
bpo-40328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40328}: Add tools for generating mappings headers for CJKCodecs.

@item 
bpo-40228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40228}: Setting frame.f_lineno is now robust w.r.t. changes in the
source-to-bytecode compiler

@item 
bpo-38880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38880}: Added the ability to list interpreters associated with channel
ends in the internal subinterpreters module.

@item 
bpo-37986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37986}: Improve performance of @ref{b3c,,PyLong_FromDouble()} for values
that fit into long.
@end itemize

@node ライブラリ<151>,ドキュメント<45>,Core and Builtins<148>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id640}@anchor{1d47}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40662}: Fixed @ref{bcb,,ast.get_source_segment()} for ast nodes that have
incomplete location information. Patch by Irit Katriel.

@item 
bpo-40665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40665}: Convert @ref{12,,bisect} to use Argument Clinic.

@item 
bpo-40536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40536}: Added the @ref{1d48,,available_timezones()} function to the
@ref{13a,,zoneinfo} module. Patch by Paul Ganssle.

@item 
bpo-40645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40645}: The @ref{d33,,hmac.HMAC} exposes internal implementation details.
The attributes @code{digest_cons}, @code{inner}, and @code{outer} are deprecated
and will be removed in the future.

@item 
bpo-40645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40645}: The internal module @code{_hashlib} wraps and exposes OpenSSL's
HMAC API. The new code will be used in Python 3.10 after the internal
implementation details of the pure Python HMAC module are no longer part
of the public API.

@item 
bpo-40637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40637}: Builtin hash modules can now be disabled or selectively enabled
with @code{configure --with-builtin-hashlib-hashes=sha3,blake1} or
@code{--without-builtin-hashlib-hashes}.

@item 
bpo-37630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37630}: The @ref{6c,,hashlib} module can now use SHA3 hashes and SHAKE XOF
from OpenSSL when available.

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: The @ref{6c,,hashlib} now compiles with OpenSSL 3.0.0-alpha2.

@item 
bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}: Revert changes to @ref{bed,,inspect.getdoc()}.

@item 
bpo-40607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40607}: When cancelling a task due to timeout, @ref{815,,asyncio.wait_for()}
will now propagate the exception if an error happens during cancellation.
Patch by Roman Skurikhin.

@item 
bpo-40612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40612}: Fix edge cases in SyntaxError formatting. If the offset is <=
0, no caret is printed. If the offset is > line length, the caret is
printed pointing just after the last character.

@item 
bpo-40597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40597}: If text content lines are longer than policy.max_line_length,
always use a content-encoding to make sure they are wrapped.

@item 
bpo-40571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40571}: Added functools.cache() as a simpler, more discoverable way to
access the unbounded cache variant of lru_cache(maxsize=None).

@item 
bpo-40503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40503}: 
@geindex Python Enhancement Proposals; PEP 615
PEP 615@footnote{https://peps.python.org/pep-0615/}, the @ref{13a,,zoneinfo} module. Adds support for the
IANA time zone database.

@item 
bpo-40397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40397}: Removed attributes @code{__args__} and @code{__parameters__} from
special generic aliases like @code{typing.List} (not subscripted).

@item 
bpo-40549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40549}: Convert posixmodule.c ("posix" or "nt" module) to the
multiphase initialization (PEP 489).

@item 
bpo-31033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31033}: Add a @code{msg} argument to @code{Future.cancel()} and
@code{Task.cancel()}.

@item 
bpo-40541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40541}: Added an optional `counts' parameter to random.sample().

@item 
bpo-40515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40515}: The @ref{d5,,ssl} and @ref{6c,,hashlib} modules now actively check
that OpenSSL is build with thread support. Python 3.7.0 made thread
support mandatory and no longer works safely with a no-thread builds.

@item 
bpo-31033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31033}: When a @ref{1c7,,asyncio.Task} is cancelled, the exception
traceback now chains all the way back to where the task was first
interrupted.

@item 
bpo-40504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40504}: @ref{be2,,functools.lru_cache()} objects can now be the targets of
weakrefs.

@item 
bpo-40559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40559}: Fix possible memory leak in the C implementation of
@ref{1c7,,asyncio.Task}.

@item 
bpo-40480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40480}: @code{fnmatch.fnmatch()} could take exponential time in the
presence of multiple @code{*} pattern characters.  This was repaired by
generating more elaborate regular expressions to avoid futile
backtracking.

@item 
bpo-40495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40495}: @ref{21,,compileall} is now able to use hardlinks to prevent
duplicates in a case when @code{.pyc} files for different optimization levels
have the same content.

@item 
bpo-40457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40457}: The ssl module now support OpenSSL builds without TLS 1.0 and
1.1 methods.

@item 
bpo-40355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40355}: Improve error reporting in @ref{e12,,ast.literal_eval()} in the
presence of malformed @ref{1d49,,ast.Dict} nodes instead of silently ignoring
any non-conforming elements. Patch by Curtis Bucher.

@item 
bpo-40465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40465}: Deprecated the optional `random' argument to
`random.shuffle()'.

@item 
bpo-40459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40459}: @ref{1d4a,,platform.win32_ver()} now produces correct `ptype' strings
instead of empty strings.

@item 
bpo-39435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39435}: The first argument of @ref{f0d,,pickle.loads()} is now
positional-only.

@item 
bpo-39305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39305}: Update @code{nntplib} to merge @code{nntplib.NNTP} and
@code{nntplib._NNTPBase}. Patch by Donghee Na.

@item 
bpo-32494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32494}: Update @ref{37,,dbm.gnu} to use gdbm_count if possible when
calling @ref{840,,len()}. Patch by Donghee Na.

@item 
bpo-40453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40453}: Add @code{isolated=True} keyword-only parameter to
@code{_xxsubinterpreters.create()}. An isolated subinterpreter cannot spawn
threads, spawn a child process or call @code{os.fork()}.

@item 
bpo-40286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40286}: Remove @code{_random.Random.randbytes()}: the C implementation of
@code{randbytes()}. Implement the method in Python to ease subclassing:
@code{randbytes()} now directly reuses @code{getrandbits()}.

@item 
bpo-40394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40394}: Added default arguments to
@ref{1d4b,,difflib.SequenceMatcher.find_longest_match()}.

@item 
bpo-39995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39995}: Fix a race condition in concurrent.futures._ThreadWakeup:
access to _ThreadWakeup is now protected with the shutdown lock.

@item 
bpo-30966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30966}: @code{Process.shutdown(wait=True)} of @ref{24,,concurrent.futures}
now closes explicitly the result queue.

@item 
bpo-30966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30966}: Add a new @ref{b11,,close()} method to
the @ref{b10,,SimpleQueue} class to explicitly close the
queue.

@item 
bpo-39966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39966}: Revert bpo-25597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25597}. @ref{108f,,unittest.mock.MagicMock} with wraps'
set uses default return values for magic methods.

@item 
bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791}: Added @code{files()} function to importlib.resources with support
for subdirectories in package data, matching backport in
importlib_resources 1.5.

@item 
bpo-40375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40375}: @ref{b03,,imaplib.IMAP4.unselect()} is added. Patch by Donghee Na.

@item 
bpo-40389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40389}: @code{repr()} now returns @code{typing.Optional[T]} when called for
@code{typing.Union} of two types, one of which is @code{NoneType}.

@item 
bpo-40291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40291}: Add support for CAN_J1939 sockets (available on Linux 5.4+)

@item 
bpo-40273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40273}: @ref{698,,types.MappingProxyType} is now reversible.

@item 
bpo-39075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39075}: The repr for @ref{4e5,,types.SimpleNamespace} is now insertion
ordered rather than alphabetical.

@item 
bpo-40192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40192}: On AIX, @ref{b30,,thread_time()} is now implemented with
@code{thread_cputime()} which has nanosecond resolution, rather than
@code{clock_gettime(CLOCK_THREAD_CPUTIME_ID)} which has a resolution of 10
milliseconds. Patch by Batuhan Taskaya.

@item 
bpo-40025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40025}: Raise TypeError when _generate_next_value_ is defined after
members. Patch by Ethan Onstott.

@item 
bpo-39058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39058}: In the argparse module, the repr for Namespace() and other
argument holders now displayed in the order attributes were added.
Formerly, it displayed in alphabetical order even though argument order is
preserved the user visible parts of the module.

@item 
bpo-24416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24416}: The @code{isocalendar()} methods of @ref{1fa,,datetime.date} and
@ref{4e2,,datetime.datetime} now return a @ref{85e,,named tuple} instead of a
@ref{614,,tuple}.
@end itemize

@node ドキュメント<45>,テスト<44>,ライブラリ<151>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id641}@anchor{1d4c}
@subsubsection ドキュメント



@itemize -

@item 
bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790}: Add version of removal for explicit passing of coros to
@code{asyncio.wait()}'s documentation

@item 
bpo-40561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40561}: Provide docstrings for webbrowser open functions.

@item 
bpo-40499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40499}: Mention that @ref{6a7,,asyncio.wait()} requires a non-empty set of
awaitables.

@item 
bpo-39705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39705}: Tutorial example for sorted() in the Loop Techniques section is
given a better explanation. Also a new example is included to explain
sorted()'s basic behavior.

@item 
bpo-39435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39435}: Fix an incorrect signature for @ref{f0d,,pickle.loads()} in the docs
@end itemize

@node テスト<44>,ビルド<51>,ドキュメント<45>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id642}@anchor{1d4d}
@subsubsection テスト



@itemize -

@item 
bpo-40055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40055}: distutils.tests now saves/restores warnings filters to leave
them unchanged. Importing tests imports docutils which imports
pkg_resources which adds a warnings filter.

@item 
bpo-40436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40436}: test_gdb and test.pythoninfo now check gdb command exit code.
@end itemize

@node ビルド<51>,Windows<45>,テスト<44>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id643}@anchor{1d4e}
@subsubsection ビルド



@itemize -

@item 
bpo-40653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40653}: Move _dirnameW out of HAVE_SYMLINK to fix a potential compiling
issue.

@item 
bpo-40514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40514}: Add @code{--with-experimental-isolated-subinterpreters} build
option to @code{configure}: better isolate subinterpreters, experimental
build mode.
@end itemize

@node Windows<45>,macOS<35>,ビルド<51>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id644}@anchor{1d4f}
@subsubsection Windows



@itemize -

@item 
bpo-40650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40650}: Include winsock2.h in pytime.c for timeval.

@item 
bpo-40458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40458}: Increase reserved stack space to prevent overflow crash on
Windows.

@item 
bpo-39148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39148}: Add IPv6 support to @ref{b,,asyncio} datagram endpoints in
ProactorEventLoop. Change the raised exception for unknown address
families to ValueError as it's not coming from Windows API.
@end itemize

@node macOS<35>,Tools/Demos<30>,Windows<45>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id645}@anchor{1d50}
@subsubsection macOS



@itemize -

@item 
bpo-34956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34956}: When building Python on macOS from source, @code{_tkinter} now
links with non-system Tcl and Tk frameworks if they are installed in
@code{/Library/Frameworks}, as had been the case on older releases of macOS.
If a macOS SDK is explicitly configured, by using
@code{--enable-universalsdk=} or @code{-isysroot}, only the SDK itself is
searched. The default behavior can still be overridden with
@code{--with-tcltk-includes} and @code{--with-tcltk-libs}.

@item 
bpo-35569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35569}: Expose RFC 3542 IPv6 socket options.
@end itemize

@node Tools/Demos<30>,C API<46>,macOS<35>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id646}@anchor{1d51}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: Update multissltest helper to test with latest OpenSSL 1.0.2,
1.1.0, 1.1.1, and 3.0.0-alpha.

@item 
bpo-40431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40431}: Fix a syntax typo in @code{turtledemo} that now raises a
@code{SyntaxError}.

@item 
bpo-40163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40163}: Fix multissltest tool. OpenSSL has changed download URL for old
releases. The multissltest tool now tries to download from current and old
download URLs.
@end itemize

@node C API<46>,,Tools/Demos<30>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id647}@anchor{1d52}
@subsubsection C API



@itemize -

@item 
bpo-39465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39465}: Remove the @code{_PyUnicode_ClearStaticStrings()} function from
the C API.

@item 
bpo-38787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38787}: Add PyCFunction_CheckExact() macro for exact type checks now
that we allow subtypes of PyCFunction, as well as PyCMethod_CheckExact()
and PyCMethod_Check() for the new PyCMethod subtype.

@item 
bpo-40545@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40545}: Declare @code{_PyErr_GetTopmostException()} with @code{PyAPI_FUNC()}
to properly export the function in the C API. The function remains private
(@code{_Py}) prefix.

@item 
bpo-40412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40412}: Nullify inittab_copy during finalization, preventing future
interpreter initializations in an embedded situation from crashing. Patch
by Gregory Szorc.

@item 
bpo-40429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40429}: The @ref{991,,PyThreadState_GetFrame()} function now returns a
strong reference to the frame.

@item 
bpo-40428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40428}: Remove the following functions from the C API. Call
@ref{b85,,PyGC_Collect()} explicitly to free all free lists.


@itemize *

@item 
@code{PyAsyncGen_ClearFreeLists()}

@item 
@code{PyContext_ClearFreeList()}

@item 
@code{PyDict_ClearFreeList()}

@item 
@code{PyFloat_ClearFreeList()}

@item 
@code{PyFrame_ClearFreeList()}

@item 
@code{PyList_ClearFreeList()}

@item 
@code{PySet_ClearFreeList()}

@item 
@code{PyTuple_ClearFreeList()}
@end itemize

@item 
bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}: New @ref{989,,PyFrame_GetBack()} function: get the frame next
outer frame.

@item 
bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}: New @ref{98d,,PyFrame_GetCode()} function: return a borrowed
reference to the frame code.

@item 
bpo-40217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40217}: Ensure that instances of types created with
@ref{79e,,PyType_FromSpecWithBases()} will visit its class object when
traversing references in the garbage collector (implemented as an
extension of the provided @ref{982,,tp_traverse}). Patch by
Pablo Galindo.

@item 
bpo-38787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38787}: Module C state is now accessible from C-defined heap type
methods (
@geindex Python Enhancement Proposals; PEP 573
PEP 573@footnote{https://peps.python.org/pep-0573/}). Patch by Marcel Plch and Petr Viktorin.
@end itemize

@node Python 3 9 0 alpha 6,Python 3 9 0 alpha 5,Python 3 9 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-9-0-alpha-6}@anchor{1d53}
@subsection Python 3.9.0 alpha 6


`リリース日: 2020-04-27'

@menu
* セキュリティ: セキュリティ<38>. 
* Core and Builtins: Core and Builtins<149>. 
* ライブラリ: ライブラリ<152>. 
* ドキュメント: ドキュメント<46>. 
* テスト: テスト<45>. 
* ビルド: ビルド<52>. 
* Windows: Windows<46>. 
* macOS: macOS<36>. 
* IDLE: IDLE<27>. 
* Tools/Demos: Tools/Demos<31>. 
* C API: C API<47>. 

@end menu

@node セキュリティ<38>,Core and Builtins<149>,,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id648}@anchor{1d54}
@subsubsection セキュリティ



@itemize -

@item 
bpo-40121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40121}: Fixes audit events raised on creating a new socket.

@item 
bpo-39073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39073}: Disallow CR or LF in email.headerregistry.Address arguments to
guard against header injection attacks.

@item 
bpo-39503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39503}: 
@geindex Common Vulnerabilities and Exposures; CVE 2020-8492
CVE 2020-8492@footnote{https://www.cve.org/CVERecord?id=CVE-2020-8492}: The
@ref{1c6f,,AbstractBasicAuthHandler} class of the
@ref{111,,urllib.request} module uses an inefficient regular expression which
can be exploited by an attacker to cause a denial of service. Fix the
regex to prevent the catastrophic backtracking. Vulnerability reported by
Ben Caller and Matt Schwager.
@end itemize

@node Core and Builtins<149>,ライブラリ<152>,セキュリティ<38>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id649}@anchor{1d55}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40313}: Improve the performance of bytes.hex().

@item 
bpo-40334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40334}: Switch to a new parser, based on PEG.  For more details see PEP
617. To temporarily switch back to the old parser, use @code{-X oldparser} or
@code{PYTHONOLDPARSER=1}.  In Python 3.10 we will remove the old parser
completely, including the @code{parser} module (already deprecated) and
anything that depends on it.

@item 
bpo-40267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40267}: Fix the tokenizer to display the correct error message, when
there is a @code{SyntaxError} on the last input character and no newline
follows. It used to be @code{unexpected EOF while parsing}, while it should
be @code{invalid syntax}.

@item 
bpo-39522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39522}: Correctly unparse explicit @code{u} prefix for strings when
postponed evaluation for annotations activated. Patch by Batuhan Taskaya.

@item 
bpo-40246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40246}: Report a specialized error message, @code{invalid string prefix},
when the tokenizer encounters a string with an invalid prefix.

@item 
bpo-40082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40082}: Fix the signal handler: it now always uses the main
interpreter, rather than trying to get the current Python thread state.

@item 
bpo-37388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37388}: str.encode() and str.decode() no longer check the encoding and
errors in development mode or in debug mode during Python finalization.
The codecs machinery can no longer work on very late calls to str.encode()
and str.decode().

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Fix possible refleaks in @code{_json}, memo of PyScannerObject
should be traversed.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{dict()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention.

@item 
bpo-40141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40141}: Add column and line information to @code{ast.keyword} nodes. Patch
by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{c1,,resource} to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{92,,math} to multiphase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _uuid module to multiphase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert json module to use @ref{79d,,PyType_FromSpec()}.

@item 
bpo-40067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40067}: Improve the error message for multiple star expressions in an
assignment. Patch by Furkan Onder

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _functools module to multiphase initialization (PEP
489). Patch by Paulo Henrique Silva.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port operator module to multiphase initialization (PEP 489).
Patch by Paulo Henrique Silva.

@item 
bpo-20526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20526}: Fix @ref{1991,,PyThreadState_Clear()}. @code{PyThreadState.frame} is
a borrowed reference, not a strong reference: @code{PyThreadState_Clear()}
must not call @code{Py_CLEAR(tstate->frame)}.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port time module to multiphase initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).
Patch by Paulo Henrique Silva.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _weakref extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-40020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40020}: Fix a leak and subsequent crash in parsetok.c caused by realloc
misuse on a rare codepath.

@item 
bpo-39939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39939}: Added str.removeprefix and str.removesuffix methods and
corresponding bytes, bytearray, and collections.UserString methods to
remove affixes from a string if present. See 
@geindex Python Enhancement Proposals; PEP 616
PEP 616@footnote{https://peps.python.org/pep-0616/} for a full
description. Patch by Dennis Sweeney.

@item 
bpo-39481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39481}: Implement PEP 585. This supports list[int], tuple[str, ...]
etc.

@item 
bpo-32894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32894}: Support unparsing of infinity numbers in postponed annotations.
Patch by Batuhan Taşkaya.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{list()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Mark Shannon.
@end itemize

@node ライブラリ<152>,ドキュメント<46>,Core and Builtins<149>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id650}@anchor{1d56}
@subsubsection ライブラリ



@itemize -

@item 
bpo-40398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40398}: @ref{2ac,,typing.get_args()} now always returns an empty tuple for
special generic aliases.

@item 
bpo-40396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40396}: Functions @ref{2ab,,typing.get_origin()}, @ref{2ac,,typing.get_args()}
and @ref{8c0,,typing.get_type_hints()} support now generic aliases like
@code{list[int]}.

@item 
bpo-38061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38061}: Optimize the @ref{dc,,subprocess} module on FreeBSD using
@code{closefrom()}. A single @code{close(fd)} syscall is cheap, but when
@code{sysconf(_SC_OPEN_MAX)} is high, the loop calling @code{close(fd)} on each
file descriptor can take several milliseconds.

The workaround on FreeBSD to improve performance was to load and mount the
fdescfs kernel module, but this is not enabled by default.

Initial patch by Ed Maste (emaste), Conrad Meyer (cem), Kyle Evans
(kevans) and Kubilay Kocak (koobs):
@indicateurl{https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=242274}

@item 
bpo-38061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38061}: On FreeBSD, @code{os.closerange(fd_low, fd_high)} now calls
@code{closefrom(fd_low)} if `fd_high' is greater than or equal to
@code{sysconf(_SC_OPEN_MAX)}.

Initial patch by Ed Maste (emaste), Conrad Meyer (cem), Kyle Evans
(kevans) and Kubilay Kocak (koobs):
@indicateurl{https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=242274}

@item 
bpo-40360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40360}: The @code{lib2to3} module is pending deprecation due to
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/}.

@item 
bpo-40138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40138}: Fix the Windows implementation of @ref{f9a,,os.waitpid()} for exit
code larger than @code{INT_MAX >> 8}. The exit status is now interpreted as
an unsigned number.

@item 
bpo-39942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39942}: Set "__main__" as the default module name when "__name__" is
missing in @ref{486,,typing.TypeVar}. Patch by Weipeng Hong.

@item 
bpo-40275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40275}: The @ref{8b,,logging} package is now imported lazily in
@ref{10c,,unittest} only when the @ref{a59,,assertLogs()}
assertion is used.

@item 
bpo-40275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40275}: The @ref{b,,asyncio} package is now imported lazily in
@ref{10c,,unittest} only when the @ref{361,,IsolatedAsyncioTestCase}
class is used.

@item 
bpo-40330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40330}: In @code{ShareableList.__setitem__()}, check the size of a new
string item after encoding it to utf-8, not before.

@item 
bpo-40148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40148}: Added @code{pathlib.Path.with_stem()} to create a new Path with
the stem replaced.

@item 
bpo-40325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40325}: Deprecated support for set objects in random.sample().

@item 
bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}: Improved help for the @ref{10a,,typing} module. Docstrings are now
shown for all special forms and special generic aliases (like @code{Union}
and @code{List}). Using @code{help()} with generic alias like @code{List[int]} will
show the help for the correspondent concrete type (@code{list} in this case).

@item 
bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}: @ref{bed,,inspect.getdoc()} no longer returns docstring inherited
from the type of the object or from parent class if it is a class if it is
not defined in the object itself. In @ref{ba,,pydoc} the documentation string
is now shown not only for class, function, method etc, but for any object
that has its own @code{__doc__} attribute.

@item 
bpo-40287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40287}: Fixed @code{SpooledTemporaryFile.seek()} to return the position.

@item 
bpo-40290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40290}: Added zscore() to statistics.NormalDist().

@item 
bpo-40282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40282}: Allow @code{random.getrandbits(0)} to succeed and to return 0.

@item 
bpo-40286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40286}: Add @ref{1826,,random.randbytes()} function and
@ref{b23,,random.Random.randbytes()} method to generate random bytes.

@item 
bpo-40277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40277}: @ref{4e0,,collections.namedtuple()} now provides a human-readable
repr for its field accessors.

@item 
bpo-40270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40270}: The included copy of sqlite3 on Windows is now compiled with
the json extension. This allows the use of functions such as
@code{json_object}.

@item 
bpo-29255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29255}: Wait in @code{KqueueSelector.select} when no fds are registered

@item 
bpo-40260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40260}: Ensure @ref{95,,modulefinder} uses @ref{1a98,,io.open_code()} and
respects coding comments.

@item 
bpo-40234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40234}: Allow again to spawn daemon threads in subinterpreters (revert
change which denied them).

@item 
bpo-39207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39207}: Workers in @ref{1d6,,ProcessPoolExecutor} are
now spawned on demand, only when there are no available idle workers to
reuse. This optimizes startup overhead and reduces the amount of lost CPU
time to idle workers. Patch by Kyle Stanley.

@item 
bpo-40091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40091}: Fix a hang at fork in the logging module: the new private
_at_fork_reinit() method is now used to reinitialize locks at fork in the
child process.

@item 
bpo-40149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40149}: Implement traverse and clear slots in _abc._abc_data type.

@item 
bpo-40208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40208}: Remove deprecated @code{symtable.SymbolTable.has_exec()}.

@item 
bpo-40196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40196}: Fix a bug in the @ref{de,,symtable} module that was causing
incorrectly report global variables as local. Patch by Pablo Galindo.

@item 
bpo-40190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40190}: Add support for @code{_SC_AIX_REALMEM} to @code{posix.sysconf()}.

@item 
bpo-40182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40182}: Removed the @code{_field_types} attribute of the
@ref{331,,typing.NamedTuple} class.

@item 
bpo-36517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36517}: Multiple inheritance with @ref{331,,typing.NamedTuple} now raises
an error instead of silently ignoring other types.

@item 
bpo-40126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40126}: Fixed reverting multiple patches in unittest.mock. Patcher's
@code{__exit__()} is now never called if its @code{__enter__()} is failed.
Returning true from @code{__exit__()} silences now the exception.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: CGIHTTPRequestHandler of http.server now logs the CGI script
exit code, rather than the CGI script exit status of os.waitpid(). For
example, if the script is killed by signal 11, it now logs: "CGI script
exit code -11."

@item 
bpo-40108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40108}: Improve the error message when triying to import a module using
@ref{c3,,runpy} and incorrectly using the ".py" extension at the end of the
module name. Patch by Pablo Galindo.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: Add @ref{b17,,os.waitstatus_to_exitcode()} function: convert a wait
status to an exit code.

@item 
bpo-40089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40089}: Fix threading._after_fork(): if fork was not called by a thread
spawned by threading.Thread, threading._after_fork() now creates a
_MainThread instance for _main_thread, instead of a _DummyThread instance.

@item 
bpo-40089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40089}: Add a private @code{_at_fork_reinit()} method to
@code{_thread.Lock}, @code{_thread.RLock}, @ref{32e,,threading.RLock}
and @ref{136d,,threading.Condition} classes: reinitialize the lock at fork in
the child process, reset the lock to the unlocked state. Rename also the
private @code{_reset_internal_locks()} method of @ref{1370,,threading.Event} to
@code{_at_fork_reinit()}.

@item 
bpo-25780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25780}: Expose @ref{b2b,,CAN_RAW_JOIN_FILTERS} in the
@ref{d1,,socket} module.

@item 
bpo-39503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39503}: @ref{1c6f,,AbstractBasicAuthHandler} of
@ref{111,,urllib.request} now parses all WWW-Authenticate HTTP headers and
accepts multiple challenges per header: use the realm of the first Basic
challenge.

@item 
bpo-39812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39812}: Removed daemon threads from @ref{24,,concurrent.futures} by adding
an internal @code{threading._register_atexit()}, which calls registered
functions prior to joining all non-daemon threads. This allows for
compatibility with subinterpreters, which don't support daemon threads.

@item 
bpo-40050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40050}: Fix @code{importlib._bootstrap_external}: avoid creating a new
@code{winreg} builtin module if it's already available in
@ref{17e6,,sys.modules}, and remove redundant imports.

@item 
bpo-40014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40014}: Fix @code{os.getgrouplist()}: if @code{getgrouplist()} function fails
because the group list is too small, retry with a larger group list. On
failure, the glibc implementation of @code{getgrouplist()} sets @code{ngroups}
to the total number of groups. For other implementations, double the group
list size.

@item 
bpo-40017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40017}: Add @ref{1d57,,time.CLOCK_TAI} constant if the operating system
support it.

@item 
bpo-40016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40016}: In re docstring, clarify the relationship between inline and
argument compile flags.

@item 
bpo-39953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39953}: Update internal table of OpenSSL error codes in the @code{ssl}
module.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Added 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} operators to
@ref{192a,,weakref.WeakValueDictionary}.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Added 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} operators to
@ref{1929,,weakref.WeakKeyDictionary}.

@item 
bpo-38891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38891}: Fix linear runtime behaviour of the @code{__getitem__} and
@code{__setitem__} methods in
@ref{1d58,,multiprocessing.shared_memory.ShareableList}. This avoids
quadratic performance when iterating a @code{ShareableList}. Patch by Thomas
Krennwallner.

@item 
bpo-39682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39682}: Remove undocumented support for `closing' a @code{pathlib.Path}
object via its context manager. The context manager magic methods remain,
but they are now a no-op, making @code{Path} objects immutable.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Added 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} operators (@code{|} and @code{|=}) to
@ref{e16,,collections.ChainMap}.

@item 
bpo-39011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39011}: Normalization of line endings in ElementTree attributes was
removed, as line endings which were replaced by entity numbers should be
preserved in original form.

@item 
bpo-38410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38410}: Properly handle @ref{191b,,sys.audit()} failures in
@ref{199d,,sys.set_asyncgen_hooks()}.

@item 
bpo-36541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36541}: lib2to3 now recognizes named assignment expressions (the walrus
operator, @code{:=})

@item 
bpo-35967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35967}: In platform, delay the invocation of 'uname -p' until the
processor attribute is requested.

@item 
bpo-35113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35113}: @ref{17c3,,inspect.getsource()} now returns correct source code for
inner class with same name as module level class. Decorators are also
returned as part of source of the class. Patch by Karthikeyan
Singaravelan.

@item 
bpo-33262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33262}: Deprecate passing None as an argument for @ref{75e,,shlex.split()}'s
@code{s} parameter.  Patch by Zackery Spytz.

@item 
bpo-31758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31758}: Prevent crashes when using an uninitialized
@code{_elementtree.XMLParser} object. Patch by Oren Milman.
@end itemize

@node ドキュメント<46>,テスト<45>,ライブラリ<152>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id651}@anchor{1d59}
@subsubsection ドキュメント



@itemize -

@item 
bpo-27635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27635}: The pickle documentation incorrectly claimed that @code{__new__}
isn't called by default when unpickling.

@item 
bpo-39879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39879}: Updated @ref{1d5a,,データモデル} docs to include @ref{183,,dict()} insertion
order preservation. Patch by Furkan Onder and Samy Lahfa.

@item 
bpo-38387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38387}: Document @ref{1d5b,,PyDoc_STRVAR} macro in the C-API reference.

@item 
bpo-13743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13743}: Some methods within xml.dom.minidom.Element class are now
better documented.
@end itemize

@node テスト<45>,ビルド<52>,ドキュメント<46>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id652}@anchor{1d5c}
@subsubsection テスト



@itemize -

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Set expected default encoding in test_c_locale_coercion.py for
VxWorks RTOS.

@item 
bpo-40162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40162}: Update Travis CI configuration to OpenSSL 1.1.1f.

@item 
bpo-40146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40146}: Update OpenSSL to 1.1.1f in Azure Pipelines.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: Add @ref{1d5d,,test.support.wait_process()} function.

@item 
bpo-40003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40003}: @code{test.bisect_cmd} now copies Python command line options like
@code{-O} or @code{-W}. Moreover, emit a warning if @code{test.bisect_cmd} is used
with @code{-w}/@code{--verbose2} option.

@item 
bpo-39380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39380}: Add the encoding in @ref{af6,,ftplib.FTP} and
@ref{af7,,ftplib.FTP_TLS} to the constructor as keyword-only and change the
default from @code{latin-1} to @code{utf-8} to follow 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://datatracker.ietf.org/doc/html/rfc2640.html}.

@item 
bpo-39793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39793}: Use the same domain when testing @code{make_msgid}. Patch by
Batuhan Taskaya.

@item 
bpo-1812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1812}: Fix newline handling in doctest.testfile when loading from a
package whose loader has a get_data method. Patch by Peter Donis.
@end itemize

@node ビルド<52>,Windows<46>,テスト<45>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id653}@anchor{1d5e}
@subsubsection ビルド



@itemize -

@item 
bpo-38360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38360}: Support single-argument form of macOS -isysroot flag.

@item 
bpo-40158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40158}: Fix CPython MSBuild Properties in NuGet Package
(build/native/python.props)

@item 
bpo-38527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38527}: Fix configure check on Solaris for "float word ordering":
sometimes, the correct "grep" command was not being used. Patch by Arnon
Yaari.
@end itemize

@node Windows<46>,macOS<36>,ビルド<52>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id654}@anchor{1d5f}
@subsubsection Windows



@itemize -

@item 
bpo-40164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40164}: Updates Windows to OpenSSL 1.1.1f

@item 
bpo-8901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8901}: Ignore the Windows registry when the @code{-E} option is used.
@end itemize

@node macOS<36>,IDLE<27>,Windows<46>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id655}@anchor{1d60}
@subsubsection macOS



@itemize -

@item 
bpo-38329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38329}: python.org macOS installers now update the Current version
symlink of /Library/Frameworks/Python.framework/Versions for 3.9 installs.
Previously, Current was only updated for Python 2.x installs. This should
make it easier to embed Python 3 into other macOS applications.

@item 
bpo-40164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40164}: Update macOS installer builds to use OpenSSL 1.1.1g.
@end itemize

@node IDLE<27>,Tools/Demos<31>,macOS<36>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id656}@anchor{1d61}
@subsubsection IDLE



@itemize -

@item 
bpo-38439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38439}: Add a 256×256 pixel IDLE icon to support more modern
environments. Created by Andrew Clover. Delete the unused macOS idle.icns
icon file.

@item 
bpo-38689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38689}: IDLE will no longer freeze when inspect.signature fails when
fetching a calltip.
@end itemize

@node Tools/Demos<31>,C API<47>,IDLE<27>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id657}@anchor{1d62}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-40385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40385}: Removed the checkpyc.py tool. Please see compileall without
force mode as a potential alternative.

@item 
bpo-40179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40179}: Fixed translation of @code{#elif} in Argument Clinic.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: Fix @code{which.py} script exit code: it now uses
@ref{b17,,os.waitstatus_to_exitcode()} to convert @ref{1676,,os.system()} exit status
into an exit code.
@end itemize

@node C API<47>,,Tools/Demos<31>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id658}@anchor{1d63}
@subsubsection C API



@itemize -

@item 
bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241}: Move the @code{PyGC_Head} structure to the internal C API.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Convert @ref{b7b,,PyObject_IS_GC()} macro to a function to hide
implementation details.

@item 
bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241}: Add the functions @ref{b6d,,PyObject_GC_IsTracked()} and
@ref{b6e,,PyObject_GC_IsFinalized()} to the public API to allow to query if
Python objects are being currently tracked or have been already finalized
by the garbage collector respectively. Patch by Pablo Galindo.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: The @code{PyObject_NEW()} macro becomes an alias to the
@ref{b7c,,PyObject_New()} macro, and the @code{PyObject_NEW_VAR()} macro
becomes an alias to the @ref{b7d,,PyObject_NewVar()} macro, to hide
implementation details. They no longer access directly the
@ref{b7e,,PyTypeObject.tp_basicsize} member.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: @ref{1d3c,,PyType_HasFeature()} now always calls
@ref{1d3d,,PyType_GetFlags()} to hide implementation details. Previously, it
accessed directly the @ref{1c71,,PyTypeObject.tp_flags} member when the
limited C API was not used.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Convert the @code{PyObject_GET_WEAKREFS_LISTPTR()} macro to a
function to hide implementation details: the macro accessed directly to
the @ref{b7f,,PyTypeObject.tp_weaklistoffset} member.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Convert @ref{639,,PyObject_CheckBuffer()} macro to a function to
hide implementation details: the macro accessed directly the
@ref{b80,,PyTypeObject.tp_as_buffer} member.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Always declare @ref{b81,,PyIndex_Check()} as an opaque function to
hide implementation details: remove @code{PyIndex_Check()} macro. The macro
accessed directly the @ref{b82,,PyTypeObject.tp_as_number} member.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{b6a,,PyThreadState_GetID()} function: get the unique
identifier of a Python thread state.
@end itemize

@node Python 3 9 0 alpha 5,Python 3 9 0 alpha 4,Python 3 9 0 alpha 6,変更履歴
@anchor{whatsnew/changelog python-3-9-0-alpha-5}@anchor{1d64}
@subsection Python 3.9.0 alpha 5


`リリース日: 2020-03-23'

@menu
* セキュリティ: セキュリティ<39>. 
* Core and Builtins: Core and Builtins<150>. 
* ライブラリ: ライブラリ<153>. 
* ドキュメント: ドキュメント<47>. 
* テスト: テスト<46>. 
* ビルド: ビルド<53>. 
* Windows: Windows<47>. 
* macOS: macOS<37>. 
* IDLE: IDLE<28>. 
* Tools/Demos: Tools/Demos<32>. 
* C API: C API<48>. 

@end menu

@node セキュリティ<39>,Core and Builtins<150>,,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id659}@anchor{1d65}
@subsubsection セキュリティ



@itemize -

@item 
bpo-38576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38576}: Disallow control characters in hostnames in http.client,
addressing 
@geindex Common Vulnerabilities and Exposures; CVE 2019-18348
CVE 2019-18348@footnote{https://www.cve.org/CVERecord?id=CVE-2019-18348}. Such potentially malicious header injection
URLs now cause a InvalidURL to be raised.
@end itemize

@node Core and Builtins<150>,ライブラリ<153>,セキュリティ<39>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id660}@anchor{1d66}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40010}: Optimize pending calls in multithreaded applications. If a
thread different than the main thread schedules a pending call
(@ref{b78,,Py_AddPendingCall()}), the bytecode evaluation loop is no longer
interrupted at each bytecode instruction to check for pending calls which
cannot be executed. Only the main thread can execute pending calls.

Previously, the bytecode evaluation loop was interrupted at each
instruction until the main thread executes pending calls.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _weakref extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _collections module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-40010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40010}: Optimize signal handling in multithreaded applications. If a
thread different than the main thread gets a signal, the bytecode
evaluation loop is no longer interrupted at each bytecode instruction to
check for pending signals which cannot be handled. Only the main thread of
the main interpreter can handle signals.

Previously, the bytecode evaluation loop was interrupted at each
instruction until the main thread handles signals.

@item 
bpo-39984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39984}: If @ref{b78,,Py_AddPendingCall()} is called in a subinterpreter,
the function is now scheduled to be called from the subinterpreter, rather
than being called from the main interpreter. Each subinterpreter now has
its own list of scheduled calls.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _heapq module to multiphase initialization.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port itertools module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{frozenset()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.

@item 
bpo-39984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39984}: subinterpreters: Move
@code{_PyRuntimeState.ceval.tracing_possible} to
@code{PyInterpreterState.ceval.tracing_possible}: each interpreter now has
its own variable.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{set()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _statistics module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-39968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39968}: Use inline function to replace extension modules'
get_module_state macros.

@item 
bpo-39965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39965}: Correctly raise @code{SyntaxError} if `await' is used inside
non-async functions and @code{PyCF_ALLOW_TOP_LEVEL_AWAIT} is set (like in the
asyncio REPL). Patch by Pablo Galindo.

@item 
bpo-39562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39562}: Allow executing asynchronous comprehensions on the top level
when the @code{PyCF_ALLOW_TOP_LEVEL_AWAIT} flag is given. Patch by Batuhan
Taskaya.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{tuple()} by using the 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}
@code{vectorcall} calling convention. Patch by Donghee Na.

@item 
bpo-38373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38373}: Changed list overallocation strategy. It no longer
overallocates if the new size is closer to overallocated size than to the
old size and adds padding.

@item 
bpo-39926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39926}: Update Unicode database to Unicode version 13.0.0.

@item 
bpo-19466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19466}: Clear the frames of daemon threads earlier during the Python
shutdown to call objects destructors. So "unclosed file" resource warnings
are now emitted for daemon threads in a more reliable way.

@item 
bpo-38894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38894}: Fix a bug that was causing incomplete results when calling
@code{pathlib.Path.glob} in the presence of symlinks that point to files
where the user does not have read access. Patch by Pablo Galindo and Matt
Wozniski.

@item 
bpo-39877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39877}: Fix @ref{648,,PyEval_RestoreThread()} random crash at exit with
daemon threads. It now accesses the @code{_PyRuntime} variable directly
instead of using @code{tstate->interp->runtime}, since @code{tstate} can be a
dangling pointer after @ref{45f,,Py_Finalize()} has been called. Moreover,
the daemon thread now exits before trying to take the GIL.

@item 
bpo-39871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39871}: Fix a possible @ref{795,,SystemError} in
@code{math.@{atan2,copysign,remainder@}()} when the first argument cannot be
converted to a @ref{196,,float}. Patch by Zackery Spytz.

@item 
bpo-39776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39776}: Fix race condition where threads created by PyGILState_Ensure()
could get a duplicate id.

This affects consumers of tstate->id like the contextvar caching
machinery, which could return invalid cached objects under heavy thread
load (observed in embedded scenarios).

@item 
bpo-39778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39778}: Fixed a crash due to incorrect handling of weak references in
@code{collections.OrderedDict} classes. Patch by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port audioop extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-39702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39702}: Relax @ref{93a,,decorator} grammar restrictions to allow any valid
expression (
@geindex Python Enhancement Proposals; PEP 614
PEP 614@footnote{https://peps.python.org/pep-0614/}).

@item 
bpo-38091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38091}: Tweak import deadlock detection code to not deadlock itself.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _locale extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-39087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39087}: Optimize @ref{424,,PyUnicode_AsUTF8()} and
@ref{a99,,PyUnicode_AsUTF8AndSize()} slightly when they need to create
internal UTF-8 cache.

@item 
bpo-39520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39520}: Fix unparsing of ext slices with no items (@code{foo[:,]}). Patch
by Batuhan Taskaya.

@item 
bpo-39220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39220}: Do not optimize annotations if 'from __future__ import
annotations' is used. Patch by Pablo Galindo.

@item 
bpo-35712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35712}: Using @ref{1a2,,NotImplemented} in a boolean context has been
deprecated. Patch contributed by Josh Rosenberg.

@item 
bpo-22490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22490}: Don't leak environment variable @code{__PYVENV_LAUNCHER__} into
the interpreter session on macOS.
@end itemize

@node ライブラリ<153>,ドキュメント<47>,Core and Builtins<150>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id661}@anchor{1d67}
@subsubsection ライブラリ



@itemize -

@item 
bpo-39830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39830}: Add @ref{8d8,,zipfile.Path} to @code{__all__} in the @ref{137,,zipfile}
module.

@item 
bpo-40000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40000}: Improved error messages for validation of @code{ast.Constant}
nodes. Patch by Batuhan Taskaya.

@item 
bpo-39999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39999}: @code{__module__} of the AST node classes is now set to "ast"
instead of "_ast". Added docstrings for dummy AST node classes and
deprecated attributes.

@item 
bpo-39991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39991}: @ref{da0,,uuid.getnode()} now skips IPv6 addresses with the same
string length than a MAC address (17 characters): only use MAC addresses.

@item 
bpo-39988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39988}: Deprecated @code{ast.AugLoad} and @code{ast.AugStore} node classes
because they are no longer used.

@item 
bpo-39656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39656}: Ensure @code{bin/python3.#} is always present in virtual
environments on POSIX platforms - by Anthony Sottile.

@item 
bpo-39969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39969}: Deprecated @code{ast.Param} node class because it's no longer
used. Patch by Batuhan Taskaya.

@item 
bpo-39360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39360}: Ensure all workers exit when finalizing a
@code{multiprocessing.Pool} implicitly via the module finalization
handlers of multiprocessing. This fixes a deadlock situation that can be
experienced when the Pool is not properly finalized via the context
manager or a call to @code{multiprocessing.Pool.terminate}. Patch by Batuhan
Taskaya and Pablo Galindo.

@item 
bpo-35370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35370}: sys.settrace(), sys.setprofile() and _lsprof.Profiler.enable()
now properly report @ref{613,,PySys_Audit()} error if "sys.setprofile" or
"sys.settrace" audit event is denied.

@item 
bpo-39936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39936}: AIX: Fix _aix_support module when the subprocess is not
available, when building Python from scratch. It now uses new private
_bootsubprocess module, rather than having two implementations depending
if subprocess is available or not. So _aix_support.aix_platform() result
is now the same if subprocess is available or not.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{7f3,,collections.OrderedDict} now implements @code{|} and
@code{|=} (
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/}).

@item 
bpo-39652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39652}: The column name found in @code{sqlite3.Cursor.description} is now
truncated on the first '[' only if the PARSE_COLNAMES option is set.

@item 
bpo-39915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39915}: Ensure @ref{1d68,,unittest.mock.AsyncMock.await_args_list} has call
objects in the order of awaited arguments instead of using
@ref{1d69,,unittest.mock.Mock.call_args} which has the last value of the call.
Patch by Karthikeyan Singaravelan.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Updated @ref{259,,os.environ} and @ref{25a,,os.environb} to support
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/}'s merge (@code{|}) and update (@code{|=}) operators.

@item 
bpo-38662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38662}: The @code{ensurepip} module now invokes @code{pip} via the @code{runpy}
module. Hence it is no longer tightly coupled with the internal API of the
bundled @code{pip} version, allowing easier updates to a newer @code{pip}
version both internally and for distributors.

@item 
bpo-38075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38075}: Fix the @ref{1d6a,,random.Random.seed()} method when a @ref{3c3,,bool}
is passed as the seed.

@item 
bpo-39916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39916}: More reliable use of @code{os.scandir()} in @code{Path.glob()}. It no
longer emits a ResourceWarning when interrupted.

@item 
bpo-39850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39850}: @ref{98,,multiprocessing} now supports abstract socket addresses
(if abstract sockets are supported in the running platform). When creating
arbitrary addresses (like when default-constructing
@ref{1a23,,multiprocessing.connection.Listener} objects) abstract sockets are
preferred to avoid the case when the temporary-file-generated address is
too large for an AF_UNIX socket address. Patch by Pablo Galindo.

@item 
bpo-36287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36287}: @ref{ae1,,ast.dump()} no longer outputs optional fields and
attributes with default values. The default values for optional fields and
attributes of AST nodes are now set as class attributes (e.g.
@code{Constant.kind} is set to @code{None}).

@item 
bpo-39889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39889}: Fixed @ref{ae2,,ast.unparse()} for extended slices containing a
single element (e.g. @code{a[i:j,]}). Remove redundant tuples when index with
a tuple (e.g. @code{a[i, j]}).

@item 
bpo-39828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39828}: Fix @ref{87,,json.tool} to catch @ref{1267,,BrokenPipeError}. Patch by
Donghee Na.

@item 
bpo-13487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13487}: Avoid a possible `"RuntimeError: dictionary changed size during
iteration"' from @ref{1b6d,,inspect.getmodule()} when it tried to loop through
@ref{17e6,,sys.modules}.

@item 
bpo-39674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39674}: Revert "bpo-37330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37330}: open() no longer accept 'U' in file mode".
The "U" mode of open() is kept in Python 3.9 to ease transition from
Python 2.7, but will be removed in Python 3.10.

@item 
bpo-28577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28577}: The hosts method on 32-bit prefix length IPv4Networks and
128-bit prefix IPv6Networks now returns a list containing the single
Address instead of an empty list.

@item 
bpo-39826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39826}: Add getConnection method to logging HTTPHandler to enable
custom connections.

@item 
bpo-39763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39763}: Reimplement @code{distutils.spawn.spawn} function with the
@ref{dc,,subprocess} module.

@item 
bpo-39794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39794}: Add --without-decimal-contextvar build option.  This enables a
thread-local rather than a coroutine local context.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{13d4,,collections.defaultdict} now implements @code{|}
(
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/}).

@item 
bpo-39517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39517}: Fix runpy.run_path() when using pathlike objects

@item 
bpo-39775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39775}: Change @code{inspect.Signature.parameters} back to
@code{collections.OrderedDict}. This was changed to @code{dict} in Python
3.9.0a4.

@item 
bpo-39678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39678}: Refactor queue_manager in
@ref{1d6,,concurrent.futures.ProcessPoolExecutor} to make it easier to
maintain.

@item 
bpo-39764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39764}: Fix AttributeError when calling get_stack on a PyAsyncGenObject
Task

@item 
bpo-39769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39769}: The @ref{d1b,,compileall.compile_dir()} function's `ddir' parameter
and the compileall command line flag @code{-d} no longer write the wrong
pathname to the generated pyc file for submodules beneath the root of the
directory tree being compiled.  This fixes a regression introduced with
Python 3.5.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{698,,types.MappingProxyType} objects now support the merge
(@code{|}) operator from 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/}.

@item 
bpo-38691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38691}: The @ref{7b,,importlib} module now ignores the
@geindex PYTHONCASEOK
@geindex 環境変数; PYTHONCASEOK
@ref{b55,,PYTHONCASEOK} environment variable when the @ref{b56,,-E} or
@ref{b57,,-I} command line options are being used.

@item 
bpo-39719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39719}: Remove @code{tempfile.SpooledTemporaryFile.softspace()} as files
no longer have the @code{softspace} attribute in Python 3. Patch by Shantanu.

@item 
bpo-39667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39667}: Improve pathlib.Path compatibility on zipfile.Path and correct
performance degradation as found in zipp 3.0.

@item 
bpo-39638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39638}: Keep ASDL signatures in the docstrings for @code{AST} nodes. Patch
by Batuhan Taskaya

@item 
bpo-39639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39639}: Deprecated @code{ast.Suite} node class because it's no longer
used. Patch by Batuhan Taskaya.

@item 
bpo-39609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39609}: Add thread_name_prefix to default asyncio executor

@item 
bpo-39548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39548}: Fix handling of header in
@ref{1d6b,,urllib.request.AbstractDigestAuthHandler} when the optional
@code{qop} parameter is not present.

@item 
bpo-39509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39509}: HTTP status codes @code{103 EARLY_HINTS} and @code{425 TOO_EARLY} are
added to @ref{afc,,http.HTTPStatus}. Patch by Donghee Na.

@item 
bpo-39507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39507}: Adding HTTP status 418 "I'm a Teapot" to HTTPStatus in http
library. Patch by Ross Rhodes.

@item 
bpo-39495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39495}: Remove default value from `attrs' parameter of
@ref{1d6c,,xml.etree.ElementTree.TreeBuilder.start()} for consistency between
Python and C implementations.

@item 
bpo-38971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38971}: Open issue in the BPO indicated a desire to make the
implementation of codecs.open() at parity with io.open(), which implements
a try/except to assure file stream gets closed before an exception is
raised.

@item 
bpo-38641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38641}: Added starred expressions support to @code{return} and @code{yield}
statements for @code{lib2to3}. Patch by Vlad Emelianov.

@item 
bpo-37534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37534}: When using minidom module to generate XML documents the ability
to add Standalone Document Declaration is added. All the changes are made
to generate a document in compliance with Extensible Markup Language (XML)
1.0 (Fifth Edition) W3C Recommendation (available here:
@indicateurl{https://www.w3.org/TR/xml/#sec-prolog-dtd}).

@item 
bpo-34788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34788}: Add support for scoped IPv6 addresses to @ref{84,,ipaddress}.
Patch by Oleksandr Pavliuk.

@item 
bpo-34822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34822}: Simplified AST for subscription. Simple indices are now
represented by their value, extended slices are represented as tuples.
@ref{9,,ast} classes @code{Index} and @code{ExtSlice} are considered deprecated
and will be removed in future Python versions. In the meantime,
@code{Index(value)} now returns a @code{value} itself, @code{ExtSlice(slices)}
returns @code{Tuple(slices, Load())}.
@end itemize

@node ドキュメント<47>,テスト<46>,ライブラリ<153>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id662}@anchor{1d6d}
@subsubsection ドキュメント



@itemize -

@item 
bpo-39868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39868}: Updated the Language Reference for 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/}.

@item 
bpo-13790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13790}: Change 'string' to 'specification' in format doc.

@item 
bpo-17422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17422}: The language reference no longer restricts default class
namespaces to dicts only.

@item 
bpo-39530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39530}: Fix misleading documentation about mixed-type numeric
comparisons.

@item 
bpo-39718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39718}: Update @ref{100,,token} documentation to reflect additions in
Python 3.8

@item 
bpo-39677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39677}: Changed operand name of `MAKE_FUNCTION' from `argc' to
`flags' for module @ref{3c,,dis}
@end itemize

@node テスト<46>,ビルド<53>,ドキュメント<47>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id663}@anchor{1d6e}
@subsubsection テスト



@itemize -

@item 
bpo-40019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40019}: test_gdb now skips tests if it detects that gdb failed to read
debug information because the Python binary is optimized.

@item 
bpo-27807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27807}: @code{test_site.test_startup_imports()} is now skipped if a path
of @ref{3e4,,sys.path} contains a @code{.pth} file.

@item 
bpo-26067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26067}: Do not fail test_shutil test_chown test when uid or gid of user
cannot be resolved to a name.

@item 
bpo-39855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39855}: test_subprocess.test_user() now skips the test on an user name
if the user name doesn't exist. For example, skip the test if the user
"nobody" doesn't exist on Linux.
@end itemize

@node ビルド<53>,Windows<47>,テスト<46>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id664}@anchor{1d6f}
@subsubsection ビルド



@itemize -

@item 
bpo-39761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39761}: Fix build with DTrace but without additional DFLAGS.

@item 
bpo-39763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39763}: setup.py now uses a basic implementation of the
@ref{dc,,subprocess} module if the @ref{dc,,subprocess} module is not available:
before required C extension modules are built.

@item 
bpo-1294959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1294959}: Add @code{--with-platlibdir} option to the configure script:
name of the platform-specific library directory, stored in the new
@ref{b32,,sys.platlibdir} attribute. It is used to build the path of
platform-specific extension modules and the path of the standard library.
It is equal to @code{"lib"} on most platforms. On Fedora and SuSE, it is
equal to @code{"lib64"} on 64-bit platforms. Patch by Jan Matějek, Matěj
Cepl, Charalampos Stratakis and Victor Stinner.
@end itemize

@node Windows<47>,macOS<37>,ビルド<53>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id665}@anchor{1d70}
@subsubsection Windows



@itemize -

@item 
bpo-39930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39930}: Ensures the required @code{vcruntime140.dll} is included in
install packages.

@item 
bpo-39847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39847}: Avoid hang when computer is hibernated whilst waiting for a
mutex (for lock-related objects from @ref{f3,,threading}) around 49-day
uptime.

@item 
bpo-38597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38597}: @code{distutils} will no longer statically link
@code{vcruntime140.dll} when a redistributable version is unavailable.
All future releases of CPython will include a copy of this DLL to ensure
distributed extensions can continue to load.

@item 
bpo-38380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38380}: Update Windows builds to use SQLite 3.31.1

@item 
bpo-39789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39789}: Update Windows release build machines to Visual Studio 2019
(MSVC 14.2).

@item 
bpo-34803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34803}: Package for nuget.org now includes repository reference and
bundled icon image.
@end itemize

@node macOS<37>,IDLE<28>,Windows<47>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id666}@anchor{1d71}
@subsubsection macOS



@itemize -

@item 
bpo-38380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38380}: Update macOS builds to use SQLite 3.31.1
@end itemize

@node IDLE<28>,Tools/Demos<32>,macOS<37>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id667}@anchor{1d72}
@subsubsection IDLE



@itemize -

@item 
bpo-27115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27115}: For 'Go to Line', use a Query box subclass with IDLE standard
behavior and improved error checking.

@item 
bpo-39885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39885}: Since clicking to get an IDLE context menu moves the cursor,
any text selection should be and now is cleared.

@item 
bpo-39852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39852}: Edit "Go to line" now clears any selection, preventing
accidental deletion. It also updates Ln and Col on the status bar.

@item 
bpo-39781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39781}: Selecting code context lines no longer causes a jump.
@end itemize

@node Tools/Demos<32>,C API<48>,IDLE<28>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id668}@anchor{1d73}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-36184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36184}: Port python-gdb.py to FreeBSD. python-gdb.py now checks for
"take_gil" function name to check if a frame tries to acquire the GIL,
instead of checking for "pthread_cond_timedwait" which is specific to
Linux and can be a different condition than the GIL.

@item 
bpo-38080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38080}: Added support to fix @code{getproxies} in the
@code{lib2to3.fixes.fix_urllib} module. Patch by José Roberto Meza
Cabrera.
@end itemize

@node C API<48>,,Tools/Demos<32>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id669}@anchor{1d74}
@subsubsection C API



@itemize -

@item 
bpo-40024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40024}: Add @ref{b6c,,PyModule_AddType()} helper function: add a type to a
module. Patch by Donghee Na.

@item 
bpo-39946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39946}: Remove @code{_PyRuntime.getframe} hook and remove
@code{_PyThreadState_GetFrame} macro which was an alias to
@code{_PyRuntime.getframe}. They were only exposed by the internal C API.
Remove also @code{PyThreadFrameGetter} type.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{991,,PyThreadState_GetFrame()} function: get the current
frame of a Python thread state.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Add _PyArg_NoKwnames helper function. Patch by Donghee Na.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{b69,,PyThreadState_GetInterpreter()}: get the interpreter
of a Python thread state.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{64c,,PyInterpreterState_Get()} function to the limited C
API.

@item 
bpo-35370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35370}: If @ref{613,,PySys_Audit()} fails in @ref{1716,,PyEval_SetProfile()}
or @ref{663,,PyEval_SetTrace()}, log the error as an unraisable exception.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Move the static inline function flavor of
Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() to the internal C API:
they access PyThreadState attributes. The limited C API provides regular
functions which hide implementation details.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Py_TRASHCAN_BEGIN_CONDITION and Py_TRASHCAN_END macro no longer
access PyThreadState attributes, but call new private _PyTrash_begin() and
_PyTrash_end() functions which hide implementation details.

@item 
bpo-39884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39884}: @ref{1d75,,PyDescr_NewMethod()} and @ref{1d76,,PyCFunction_NewEx()} now
include the method name in the SystemError "bad call flags" error message
to ease debug.

@item 
bpo-39877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39877}: Deprecated @code{PyEval_InitThreads()} and
@code{PyEval_ThreadsInitialized()}. Calling
@code{PyEval_InitThreads()} now does nothing.

@item 
bpo-38249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38249}: @ref{dae,,Py_UNREACHABLE} is now implemented with
@code{__builtin_unreachable()} and analogs in release mode.

@item 
bpo-38643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38643}: @ref{1b73,,PyNumber_ToBase()} now raises a @ref{795,,SystemError}
instead of crashing when called with invalid base.

@item 
bpo-39882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39882}: The @ref{b7a,,Py_FatalError()} function is replaced with a macro
which logs automatically the name of the current function, unless the
@code{Py_LIMITED_API} macro is defined.

@item 
bpo-39824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39824}: Extension modules: @ref{b71,,m_traverse},
@ref{b72,,m_clear} and @ref{b73,,m_free}
functions of @ref{b74,,PyModuleDef} are no longer called if the module
state was requested but is not allocated yet. This is the case immediately
after the module is created and before the module is executed
(@ref{b75,,Py_mod_exec} function). More precisely, these functions are not
called if @ref{b76,,m_size} is greater than 0 and the module
state (as returned by @ref{b77,,PyModule_GetState()}) is @code{NULL}.

Extension modules without module state (@code{m_size <= 0}) are not affected.

@item 
bpo-38913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38913}: Fixed segfault in @code{Py_BuildValue()} called with a format
containing "#" and undefined PY_SSIZE_T_CLEAN whwn an exception is set.

@item 
bpo-38500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38500}: Add a private API to get and set the frame evaluation function:
add @ref{1d77,,_PyInterpreterState_GetEvalFrameFunc()} and
@ref{1d78,,_PyInterpreterState_SetEvalFrameFunc()} C functions. The
@ref{97a,,_PyFrameEvalFunction} function type now takes a `tstate'
parameter.
@end itemize

@node Python 3 9 0 alpha 4,Python 3 9 0 alpha 3,Python 3 9 0 alpha 5,変更履歴
@anchor{whatsnew/changelog python-3-9-0-alpha-4}@anchor{1d79}
@subsection Python 3.9.0 alpha 4


`Release date: 2020-02-25'

@menu
* セキュリティ: セキュリティ<40>. 
* Core and Builtins: Core and Builtins<151>. 
* ライブラリ: ライブラリ<154>. 
* ドキュメント: ドキュメント<48>. 
* テスト: テスト<47>. 
* ビルド: ビルド<54>. 
* Windows: Windows<48>. 
* IDLE: IDLE<29>. 
* C API: C API<49>. 

@end menu

@node セキュリティ<40>,Core and Builtins<151>,,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id670}@anchor{1d7a}
@subsubsection セキュリティ



@itemize -

@item 
bpo-39184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39184}: Add audit events to functions in @code{fcntl}, @code{msvcrt}, @code{os},
@code{resource}, @code{shutil}, @code{signal} and @code{syslog}.

@item 
bpo-39401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39401}: Avoid unsafe DLL load at startup on Windows 7 and earlier.

@item 
bpo-39184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39184}: Add audit events to command execution functions in os and pty
modules.
@end itemize

@node Core and Builtins<151>,ライブラリ<154>,セキュリティ<40>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id671}@anchor{1d7b}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-39382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39382}: Fix a use-after-free in the single inheritance path of
@code{issubclass()}, when the @code{__bases__} of an object has a single
reference, and so does its first item. Patch by Yonatan Goldschmidt.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Update clinic tool to use @ref{1ba0,,Py_IS_TYPE()}. Patch by
Donghee Na.

@item 
bpo-39619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39619}: Enable use of @ref{1d7c,,os.chroot()} on HP-UX systems.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add @ref{1ba0,,Py_IS_TYPE()} static inline function to check
whether the object `o' type is `type'.

@item 
bpo-39606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39606}: Fix regression caused by fix for bpo-39386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39386}, that prevented
calling @code{aclose} on an async generator that had already been closed or
exhausted.

@item 
bpo-39579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39579}: Change the ending column offset of @code{Attribute} nodes
constructed in @code{ast_for_dotted_name} to point at the end of the current
node and not at the end of the last @code{NAME} node.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _crypt extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _contextvars extension module to multiphase
initialization (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-39510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39510}: Fix segfault in @code{readinto()} method on closed BufferedReader.

@item 
bpo-39502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39502}: Fix @ref{1712,,time.localtime()} on 64-bit AIX  to support years
before 1902 and after 2038. Patch by M Felt.

@item 
bpo-39492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39492}: Fix a reference cycle in the C Pickler that was preventing the
garbage collection of deleted, pickled objects.

@item 
bpo-39453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39453}: Fixed a possible crash in @code{list.__contains__()} when a list
is changed during comparing items. Patch by Donghee Na.

@item 
bpo-39434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39434}: @ref{b3e,,floor division} of float operation now has a better
performance. Also the message of @ref{b3f,,ZeroDivisionError} for this
operation is updated. Patch by Donghee Na.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _codecs extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _bz2 extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _abc extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-39320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39320}: Replace two complex bytecodes for building dicts with two
simpler ones. The new bytecodes @code{DICT_MERGE} and @code{DICT_UPDATE} have
been added The old bytecodes @code{BUILD_MAP_UNPACK} and
@code{BUILD_MAP_UNPACK_WITH_CALL} have been removed.

@item 
bpo-39219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39219}: Syntax errors raised in the tokenizer now always set correct
"text" and "offset" attributes.

@item 
bpo-36051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36051}: Drop the GIL during large @code{bytes.join} operations. Patch by
Bruce Merry.

@item 
bpo-38960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38960}: Fix DTrace build issues on FreeBSD. Patch by David Carlier.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{range()} by about 30%, by using the PEP
590 @code{vectorcall} calling convention. Patch by Mark Shannon.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{183,,dict} (and @ref{1d7d,,collections.UserDict}) objects now
support PEP 584's merge (@code{|}) and update (@code{|=}) operators. Patch by
Brandt Bucher.

@item 
bpo-32856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32856}: Optimized the idiom for assignment a temporary variable in
comprehensions. Now @code{for y in [expr]} in comprehensions is as fast as a
simple assignment @code{y = expr}.
@end itemize

@node ライブラリ<154>,ドキュメント<48>,Core and Builtins<151>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id672}@anchor{1d7e}
@subsubsection ライブラリ



@itemize -

@item 
bpo-30566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30566}: Fix @ref{174e,,IndexError} when trying to decode an invalid string
with punycode codec.

@item 
bpo-39649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39649}: Remove obsolete check for @code{__args__} in
@code{bdb.Bdb.format_stack_entry}.

@item 
bpo-39648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39648}: Expanded @ref{b0c,,math.gcd()} and @ref{b0d,,math.lcm()} to handle
multiple arguments.

@item 
bpo-39681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39681}: Fix a regression where the C pickle module wouldn't allow
unpickling from a file-like object that doesn't expose a readinto()
method.

@item 
bpo-35950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35950}: Raise @ref{1d7f,,io.UnsupportedOperation} in
@code{io.BufferedReader.truncate()} when it is called on a read-only
@ref{1427,,io.BufferedReader} instance.

@item 
bpo-39479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39479}: Add @ref{b0d,,math.lcm()} function: least common multiple.

@item 
bpo-39674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39674}: Revert "Do not expose abstract collection classes in the
collections module" change (bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}). Aliases to ABC like
collections.Mapping are kept in Python 3.9 to ease transition from Python
2.7, but will be removed in Python 3.10.

@item 
bpo-39104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39104}: Fix hanging ProcessPoolExcutor on @code{shutdown(wait=False)} when
a task has failed pickling.

@item 
bpo-39627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39627}: Fixed TypedDict totality check for inherited keys.

@item 
bpo-39474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39474}: Fixed starting position of AST for expressions like @code{(a)(b)},
@code{(a)[b]} and @code{(a).b}.

@item 
bpo-21016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21016}: The @ref{ba,,pydoc} and @ref{103,,trace} modules now use the
@ref{e1,,sysconfig} module to get the path to the Python standard library, to
support uncommon installation path like @code{/usr/lib64/python3.9/} on
Fedora. Patch by Jan Matějek.

@item 
bpo-39590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39590}: Collections.deque now holds strong references during
deque.__contains__ and deque.count, fixing crashes.

@item 
bpo-39586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39586}: The distutils @code{bdist_msi} command is deprecated in Python
3.9, use @code{bdist_wheel} (wheel packages) instead.

@item 
bpo-39595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39595}: Improved performance of zipfile.Path for files with a large
number of entries. Also improved performance and fixed minor issue as
published with importlib_metadata 1.5@footnote{https://importlib-metadata.readthedocs.io/en/latest/history.html#v1-5-0}.

@item 
bpo-39350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39350}: Fix regression in @ref{213,,fractions.Fraction} if the numerator
and/or the denominator is an @ref{19b,,int} subclass. The @ref{b0c,,math.gcd()}
function is now used to normalize the `numerator' and `denominator'.
@ref{b0c,,math.gcd()} always return a @ref{19b,,int} type. Previously, the GCD
type depended on `numerator' and `denominator'.

@item 
bpo-39567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39567}: Added audit for @ref{6d0,,os.walk()}, @ref{d52,,os.fwalk()},
@ref{537,,pathlib.Path.glob()} and @ref{538,,pathlib.Path.rglob()}.

@item 
bpo-39559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39559}: Remove unused, undocumented argument @code{getters} from
@ref{da0,,uuid.getnode()}

@item 
bpo-38149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38149}: @ref{191b,,sys.audit()} is now called only once per call of
@ref{5a0,,glob.glob()} and @ref{a08,,glob.iglob()}.

@item 
bpo-39546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39546}: Fix a regression in @ref{1bd,,ArgumentParser} where
@code{allow_abbrev=False} was ignored for long options that used a prefix
character other than "-".

@item 
bpo-39450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39450}: Striped whitespace from docstring before returning it from
@code{unittest.case.shortDescription()}.

@item 
bpo-12915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12915}: A new function @code{resolve_name} has been added to the
@code{pkgutil} module. This resolves a string of the form @code{'a.b.c.d'} or
@code{'a.b:c.d'} to an object. In the example, @code{a.b} is a package/module
and @code{c.d} is an object within that package/module reached via recursive
attribute access.

@item 
bpo-39353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39353}: The @ref{93d,,binascii.crc_hqx()} function is no longer deprecated.

@item 
bpo-39493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39493}: Mark @code{typing.IO.closed} as a property

@item 
bpo-39491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39491}: Add @ref{b37,,typing.Annotated} and @code{include_extras} parameter
to @ref{8c0,,typing.get_type_hints()} as part of 
@geindex Python Enhancement Proposals; PEP 593
PEP 593@footnote{https://peps.python.org/pep-0593/}. Patch by Till
Varoquaux, documentation by Till Varoquaux and Konstantin Kashin.

@item 
bpo-39485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39485}: Fix a bug in @ref{1934,,unittest.mock.create_autospec()} that would
complain about the wrong number of arguments for custom descriptors
defined in an extension module returning functions.

@item 
bpo-38932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38932}: Mock fully resets child objects on reset_mock(). Patch by
Vegard Stikbakke

@item 
bpo-39082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39082}: Allow AsyncMock to correctly patch static/class methods

@item 
bpo-39432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39432}: Implement PEP-489 algorithm for non-ascii "PyInit_..." symbol
names in distutils to make it export the correct init symbol also on
Windows.

@item 
bpo-18819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18819}: Omit @code{devmajor} and @code{devminor} fields for non-device files
in @ref{e4,,tarfile} archives, enabling bit-for-bit compatibility with GNU
@code{tar(1)}.

@item 
bpo-39349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39349}: Added a new `cancel_futures' parameter to
@ref{aea,,concurrent.futures.Executor.shutdown()} that cancels all pending
futures which have not started running, instead of waiting for them to
complete before shutting down the executor.

@item 
bpo-39274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39274}: @code{bool(fraction.Fraction)} now returns a boolean even if
(numerator != 0) does not return a boolean (ex: numpy number).

@item 
bpo-34793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34793}: Remove support for @code{with (await asyncio.lock):} and @code{with
(yield from asyncio.lock):}.  The same is correct for
@code{asyncio.Condition} and @code{asyncio.Semaphore}.

@item 
bpo-25597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25597}: Ensure, if @code{wraps} is supplied to
@ref{108f,,unittest.mock.MagicMock}, it is used to calculate return values
for the magic methods instead of using the default return values. Patch by
Karthikeyan Singaravelan.

@item 
bpo-36350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36350}: @code{inspect.Signature.parameters} and
@code{inspect.BoundArguments.arguments} are now dicts instead of
OrderedDicts. Patch contributed by Rémi Lapeyre.

@item 
bpo-35727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35727}: Fix sys.exit() and sys.exit(None) exit code propagation when
used in multiprocessing.Process.

@item 
bpo-32173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32173}: * Add @code{lazycache} function to @code{__all__}. * Use
@code{dict.clear} to clear the cache. * Refactoring @code{getline} function and
@code{checkcache} function.
@end itemize

@node ドキュメント<48>,テスト<47>,ライブラリ<154>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id673}@anchor{1d80}
@subsubsection ドキュメント



@itemize -

@item 
bpo-17422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17422}: The language reference now specifies restrictions on class
namespaces. Adapted from a patch by Ethan Furman.

@item 
bpo-39572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39572}: Updated documentation of @code{total} flag of @code{TypedDict}.

@item 
bpo-39654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39654}: In pyclbr doc, update 'class' to 'module' where appropriate and
add readmodule comment. Patch by Hakan Çelik.

@item 
bpo-39153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39153}: Clarify refcounting semantics for the following functions: -
PyObject_SetItem - PyMapping_SetItemString - PyDict_SetItem -
PyDict_SetItemString

@item 
bpo-39392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39392}: Explain that when filling with turtle, overlap regions may be
left unfilled.

@item 
bpo-39369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39369}: Update mmap readline method description. The fact that the
readline method does update the file position should not be ignored since
this might give the impression for the programmer that it doesn't update
it.

@item 
bpo-9056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9056}: Include subsection in TOC for PDF version of docs.
@end itemize

@node テスト<47>,ビルド<54>,ドキュメント<48>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id674}@anchor{1d81}
@subsubsection テスト



@itemize -

@item 
bpo-38325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38325}: Skip tests on non-BMP characters of test_winconsoleio.

@item 
bpo-39502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39502}: Skip test_zipfile.test_add_file_after_2107() if
@ref{1712,,time.localtime()} fails with @ref{a81,,OverflowError}. It is the case on
AIX 6.1 for example.
@end itemize

@node ビルド<54>,Windows<48>,テスト<47>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id675}@anchor{1d82}
@subsubsection ビルド



@itemize -

@item 
bpo-39489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39489}: Remove @code{COUNT_ALLOCS} special build.
@end itemize

@node Windows<48>,IDLE<29>,ビルド<54>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id676}@anchor{1d83}
@subsubsection Windows



@itemize -

@item 
bpo-39553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39553}: Delete unused code related to SxS manifests.

@item 
bpo-39439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39439}: Honor the Python path when a virtualenv is active on Windows.

@item 
bpo-39393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39393}: Improve the error message when attempting to load a DLL with
unresolved dependencies.

@item 
bpo-38883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38883}: @ref{1043,,home()} and @ref{1042,,expanduser()}
on Windows now prefer 
@geindex USERPROFILE
@geindex 環境変数; USERPROFILE
@code{USERPROFILE} and no longer use
@geindex HOME
@geindex 環境変数; HOME
@code{HOME}, which is not normally set for regular user accounts. This
makes them again behave like @ref{c09,,os.path.expanduser()}, which was changed
to ignore 
@geindex HOME
@geindex 環境変数; HOME
@code{HOME} in 3.8, see bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264}.

@item 
bpo-39185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39185}: The build.bat script has additional options for very-quiet
output (-q) and very-verbose output (-vv)
@end itemize

@node IDLE<29>,C API<49>,Windows<48>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id677}@anchor{1d84}
@subsubsection IDLE



@itemize -

@item 
bpo-39663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39663}: Add tests for pyparse find_good_parse_start().

@item 
bpo-39600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39600}: In the font configuration window, remove duplicated font names.

@item 
bpo-30780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30780}: Add remaining configdialog tests for buttons and highlights and
keys tabs.

@item 
bpo-39388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39388}: IDLE Settings Cancel button now cancels pending changes

@item 
bpo-38792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38792}: Close an IDLE shell calltip if a @ref{bc5,,KeyboardInterrupt} or
shell restart occurs.  Patch by Zackery Spytz.
@end itemize

@node C API<49>,,IDLE<29>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id678}@anchor{1d85}
@subsubsection C API



@itemize -

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: Move the @code{bytes_methods.h} header file to the internal C API
as @code{pycore_bytes_methods.h}: it only contains private symbols (prefixed
by @code{_Py}), except of the @code{PyDoc_STRVAR_shared()} macro.

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: Move the @code{dtoa.h} header file to the internal C API as
@code{pycore_dtoa.h}: it only contains private functions (prefixed by
@code{_Py}). The @ref{92,,math} and @ref{19,,cmath} modules must now be compiled
with the @code{Py_BUILD_CORE} macro defined.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add @ref{986,,Py_SET_SIZE()} function to set the size of an
object.

@item 
bpo-39500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39500}: @ref{1d86,,PyUnicode_IsIdentifier()} does not call
@ref{b7a,,Py_FatalError()} anymore if the string is not ready.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add @ref{984,,Py_SET_TYPE()} function to set the type of an
object.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add a @ref{aa8,,Py_SET_REFCNT()} function to set the reference
counter of an object.

@item 
bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}: Convert @ref{1d3c,,PyType_HasFeature()}, @ref{1d87,,PyType_Check()} and
@ref{1d88,,PyType_CheckExact()} macros to static inline functions.

@item 
bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}: In the limited C API, @code{PyObject_INIT()} and
@code{PyObject_INIT_VAR()} are now defined as aliases to
@ref{c60,,PyObject_Init()} and @ref{1d40,,PyObject_InitVar()} to make their
implementation opaque. It avoids to leak implementation details in the
limited C API. Exclude the following functions from the limited C API:
@code{_Py_NewReference()}, @code{_Py_ForgetReference()},
@code{_PyTraceMalloc_NewReference()} and @code{_Py_GetRefTotal()}.

@item 
bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}: Exclude trashcan mechanism from the limited C API: it requires
access to PyTypeObject and PyThreadState structure fields, whereas these
structures are opaque in the limited C API.

@item 
bpo-39511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39511}: The @ref{1991,,PyThreadState_Clear()} function now calls the
@code{PyThreadState.on_delete} callback. Previously, that happened in
@ref{1d89,,PyThreadState_Delete()}.

@item 
bpo-38076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38076}: Fix to clear the interpreter state only after clearing module
globals to guarantee module state access from C Extensions during runtime
destruction

@item 
bpo-39245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39245}: The Vectorcall API (PEP 590) was made public, adding the
functions @code{PyObject_Vectorcall}, @code{PyObject_VectorcallMethod},
@code{PyVectorcall_Function}, @code{PyObject_CallOneArg},
@code{PyObject_CallMethodNoArgs}, @code{PyObject_CallMethodOneArg},
@code{PyObject_FastCallDict}, and the flag @code{Py_TPFLAGS_HAVE_VECTORCALL}.
@end itemize

@node Python 3 9 0 alpha 3,Python 3 9 0 alpha 2,Python 3 9 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-9-0-alpha-3}@anchor{1d8a}
@subsection Python 3.9.0 alpha 3


`Release date: 2020-01-24'

@menu
* Core and Builtins: Core and Builtins<152>. 
* ライブラリ: ライブラリ<155>. 
* ドキュメント: ドキュメント<49>. 
* ビルド: ビルド<55>. 
* IDLE: IDLE<30>. 
* C API: C API<50>. 

@end menu

@node Core and Builtins<152>,ライブラリ<155>,,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id679}@anchor{1d8b}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-39427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39427}: Document all possibilities for the @code{-X} options in the
command line help section. Patch by Pablo Galindo.

@item 
bpo-39421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39421}: Fix possible crashes when operating with the functions in the
@ref{6d,,heapq} module and custom comparison operators.

@item 
bpo-39386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39386}: Prevent double awaiting of async iterator.

@item 
bpo-17005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17005}: Add @code{functools.TopologicalSorter} to the
@ref{63,,functools} module to offers functionality to perform topological
sorting of graphs. Patch by Pablo Galindo, Tim Peters and Larry Hastings.

@item 
bpo-39320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39320}: Replace four complex bytecodes for building sequences with
three simpler ones.

The following four bytecodes have been removed:


@itemize *

@item 
BUILD_LIST_UNPACK

@item 
BUILD_TUPLE_UNPACK

@item 
BUILD_SET_UNPACK

@item 
BUILD_TUPLE_UNPACK_WITH_CALL
@end itemize

The following three bytecodes have been added:


@itemize *

@item 
LIST_TO_TUPLE

@item 
LIST_EXTEND

@item 
SET_UPDATE
@end itemize

@item 
bpo-39336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39336}: Import loaders which publish immutable module objects can now
publish immutable packages in addition to individual modules.

@item 
bpo-39322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39322}: Added a new function @ref{af9,,gc.is_finalized()} to check if an
object has been finalized by the garbage collector. Patch by Pablo
Galindo.

@item 
bpo-39048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39048}: Improve the displayed error message when incorrect types are
passed to @code{async with} statements by looking up the @code{__aenter__()}
special method before the @code{__aexit__()} special method when entering
an asynchronous context manager. Patch by Géry Ogam.

@item 
bpo-39235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39235}: Fix AST end location for lone generator expression in function
call, e.g. f(i for i in a).

@item 
bpo-39209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39209}: Correctly handle multi-line tokens in interactive mode. Patch
by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _json extension module to multiphase initialization
(
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}).

@item 
bpo-39216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39216}: Fix constant folding optimization for positional only arguments
- by Anthony Sottile.

@item 
bpo-39215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39215}: Fix @code{SystemError} when nested function has annotation on
positional-only argument - by Anthony Sottile.

@item 
bpo-39200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39200}: Correct the error message when calling the @ref{110b,,min()} or
@ref{110c,,max()} with no arguments. Patch by Donghee Na.

@item 
bpo-39200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39200}: Correct the error message when trying to construct
@ref{b3d,,range} objects with no arguments. Patch by Pablo Galindo.

@item 
bpo-39166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39166}: Fix incorrect line execution reporting in trace functions when
tracing the last iteration of asynchronous for loops. Patch by Pablo
Galindo.

@item 
bpo-39114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39114}: Fix incorrect line execution reporting in trace functions when
tracing exception handlers with name binding. Patch by Pablo Galindo.

@item 
bpo-39156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39156}: Split the COMPARE_OP bytecode instruction into four distinct
instructions.


@itemize *

@item 
COMPARE_OP for rich comparisons

@item 
IS_OP for 'is' and 'is not' tests

@item 
CONTAINS_OP for 'in' and 'is not' tests

@item 
JUMP_IF_NOT_EXC_MATCH for checking exceptions in 'try-except' statements.
@end itemize

This improves the clarity of the interpreter and should provide a modest
speedup.

@item 
bpo-38588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38588}: Fix possible crashes in dict and list when calling
@ref{1d8c,,PyObject_RichCompareBool()}.

@item 
bpo-13601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13601}: By default, @code{sys.stderr} is line-buffered now, even if
@code{stderr} is redirected to a file. You can still make @code{sys.stderr}
unbuffered by passing the @ref{1d8d,,-u} command-line option or setting the
@geindex PYTHONUNBUFFERED
@geindex 環境変数; PYTHONUNBUFFERED
@ref{1d8e,,PYTHONUNBUFFERED} environment variable.

(Contributed by Jendrik Seipp in bpo-13601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13601}.)

@item 
bpo-38610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38610}: Fix possible crashes in several list methods by holding strong
references to list elements when calling
@ref{1d8c,,PyObject_RichCompareBool()}.

@item 
bpo-32021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32021}: Include brotli .br encoding in mimetypes encodings_map
@end itemize

@node ライブラリ<155>,ドキュメント<49>,Core and Builtins<152>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id680}@anchor{1d8f}
@subsubsection ライブラリ



@itemize -

@item 
bpo-39430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39430}: Fixed race condition in lazy imports in @ref{e4,,tarfile}.

@item 
bpo-39413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39413}: The @ref{25c,,os.unsetenv()} function is now also available on
Windows.

@item 
bpo-39390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39390}: Fixed a regression with the @code{ignore} callback of
@ref{c1e,,shutil.copytree()}. The argument types are now @code{str} and
@code{List[str]} again.

@item 
bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395}: The @ref{25b,,os.putenv()} and @ref{25c,,os.unsetenv()} functions are now
always available.

@item 
bpo-39406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39406}: If @code{setenv()} C function is available, @ref{25b,,os.putenv()} is
now implemented with @code{setenv()} instead of @code{putenv()}, so Python
doesn't have to handle the environment variable memory.

@item 
bpo-39396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39396}: Fix @code{math.nextafter(-0.0, +0.0)} on AIX 7.1.

@item 
bpo-29435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29435}: Allow @ref{1bdb,,tarfile.is_tarfile()} to be used with file and
file-like objects, like @ref{1542,,zipfile.is_zipfile()}. Patch by William
Woodruff.

@item 
bpo-39377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39377}: Removed @code{encoding} option from @ref{b4e,,json.loads()}.  It has
been deprecated since Python 3.1.

@item 
bpo-39389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39389}: Write accurate compression level metadata in @ref{6b,,gzip}
archives, rather than always signaling maximum compression.

@item 
bpo-39366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39366}: The previously deprecated @code{xpath()} and @code{xgtitle()} methods
of @code{nntplib.NNTP} have been removed.

@item 
bpo-39357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39357}: Remove the `buffering' parameter of @ref{a66,,bz2.BZ2File}. Since
Python 3.0, it was ignored and using it was emitting
@ref{1a3,,DeprecationWarning}. Pass an open file object, to control how the
file is opened. The `compresslevel' parameter becomes keyword-only.

@item 
bpo-39353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39353}: Deprecate binhex4 and hexbin4 standards. Deprecate the
@code{binhex} module and the following @ref{11,,binascii} functions:
@code{b2a_hqx()}, @code{a2b_hqx()},
@code{rlecode_hqx()}, @code{rledecode_hqx()},
@ref{93d,,crc_hqx()}.

@item 
bpo-39351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39351}: Remove @code{base64.encodestring()} and @code{base64.decodestring()},
aliases deprecated since Python 3.1: use @ref{b4c,,base64.encodebytes()} and
@ref{b4d,,base64.decodebytes()} instead.

@item 
bpo-39350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39350}: Remove @code{fractions.gcd()} function, deprecated since Python
3.5 (bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486}): use @ref{b0c,,math.gcd()} instead.

@item 
bpo-39329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39329}: @ref{b29,,LMTP} constructor now has an optional
`timeout' parameter. Patch by Donghee Na.

@item 
bpo-39313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39313}: Add a new @code{exec_function} option (`--exec-function' in the
CLI) to @code{RefactoringTool} for making @code{exec} a function. Patch by
Batuhan Taskaya.

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @ref{af7,,FTP_TLS} and @ref{af7,,FTP_TLS} now raise
a @ref{2ec,,ValueError} if the given timeout for their constructor is zero
to prevent the creation of a non-blocking socket. Patch by Donghee Na.

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @ref{b27,,SMTP} and @ref{b28,,SMTP_SSL} now raise
a @ref{2ec,,ValueError} if the given timeout for their constructor is zero
to prevent the creation of a non-blocking socket. Patch by Donghee Na.

@item 
bpo-39310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39310}: Add @ref{b0e,,math.ulp()}: return the value of the least significant
bit of a float.

@item 
bpo-39297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39297}: Improved performance of importlib.metadata distribution
discovery and resilients to inaccessible sys.path entries
(importlib_metadata v1.4.0).

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @code{NNTP} and @code{NNTP_SSL} now raise a
@ref{2ec,,ValueError} if the given timeout for their constructor is zero to
prevent the creation of a non-blocking socket. Patch by Donghee Na.

@item 
bpo-38901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38901}: When you specify prompt='.' or equivalently python -m venv
--prompt . ... the basename of the current directory is used to set the
created venv's prompt when it's activated.

@item 
bpo-39288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39288}: Add @ref{6c0,,math.nextafter()}: return the next floating-point
value after `x' towards `y'.

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @ref{b1d,,POP3} and @ref{b1e,,POP3_SSL} now raise a
@ref{2ec,,ValueError} if the given timeout for their constructor is zero to
prevent the creation of a non-blocking socket. Patch by Donghee Na.

@item 
bpo-39242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39242}: Updated the Gmane domain from news.gmane.org to news.gmane.io
which is used for examples of @code{NNTP} news reader server and
nntplib tests.

@item 
bpo-35292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35292}: Proxy the @code{SimpleHTTPRequestHandler.guess_type} to
@code{mimetypes.guess_type} so the @code{mimetypes.init} is called lazily to
avoid unnecessary costs when @ref{76,,http.server} module is imported.

@item 
bpo-39239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39239}: The @ref{b53,,select.epoll.unregister()} method no longer ignores
the @ref{b54,,EBADF} error.

@item 
bpo-38907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38907}: In http.server script, restore binding to IPv4 on Windows.

@item 
bpo-39152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39152}: Fix ttk.Scale.configure([name]) to return configuration tuple
for name or all options.  Giovanni Lombardo contributed part of the patch.

@item 
bpo-39198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39198}: If an exception were to be thrown in @code{Logger.isEnabledFor}
(say, by asyncio timeouts or stopit) , the @code{logging} global lock may not
be released appropriately, resulting in deadlock.  This change wraps that
block of code with @code{try...finally} to ensure the lock is released.

@item 
bpo-39191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39191}: Perform a check for running loop before starting a new task in
@code{loop.run_until_complete()} to fail fast; it prevents the side effect of
new task spawning before exception raising.

@item 
bpo-38871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38871}: Correctly parenthesize filter-based statements that contain
lambda expressions in @code{lib2to3}. Patch by Donghee Na.

@item 
bpo-39142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39142}: A change was made to logging.config.dictConfig to avoid
converting instances of named tuples to ConvertingTuple. It's assumed that
named tuples are too specialised to be treated like ordinary tuples; if a
user of named tuples requires ConvertingTuple functionality, they will
have to implement that themselves in their named tuple class.

@item 
bpo-39158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39158}: ast.literal_eval() now supports empty sets.

@item 
bpo-39129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39129}: Fix import path for @code{asyncio.TimeoutError}

@item 
bpo-39057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39057}: @code{urllib.request.proxy_bypass_environment()} now ignores
leading dots and no longer ignores a trailing newline.

@item 
bpo-39056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39056}: Fixed handling invalid warning category in the -W option.  No
longer import the re module if it is not needed.

@item 
bpo-39055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39055}: @ref{1d90,,base64.b64decode()} with @code{validate=True} raises now a
binascii.Error if the input ends with a single @code{\n}.

@item 
bpo-21600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21600}: Fix @code{mock.patch.stopall()} to stop active patches that were
created with @code{mock.patch.dict()}.

@item 
bpo-39019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39019}: Implement dummy @code{__class_getitem__} for
@ref{8a2,,tempfile.SpooledTemporaryFile}.

@item 
bpo-39019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39019}: Implement dummy @code{__class_getitem__} for @code{subprocess.Popen},
@code{subprocess.CompletedProcess}

@item 
bpo-38914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38914}: Adjusted the wording of the warning issued by distutils'
@code{check} command when the @code{author} and @code{maintainer} fields are
supplied but no corresponding e-mail field (@code{author_email} or
@code{maintainer_email}) is found. The wording now reflects the fact that
these fields are suggested, but not required. Patch by Juergen Gmach.

@item 
bpo-38878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38878}: Fixed __subclasshook__ of @ref{e4b,,os.PathLike} to return a
correct result upon inheritance. Patch by Bar Harel.

@item 
bpo-38615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38615}: @ref{aff,,IMAP4} and @ref{b00,,IMAP4_SSL} now
have an optional `timeout' parameter for their constructors. Also, the
@ref{b01,,open()} method now has an optional `timeout' parameter
with this change. The overridden methods of @ref{b00,,IMAP4_SSL}
and @ref{b02,,IMAP4_stream} were applied to this change. Patch by
Donghee Na.

@item 
bpo-35182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35182}: Fixed @code{Popen.communicate()} subsequent call crash when the
child process has already closed any piped standard stream, but still
continues to be running. Patch by Andriy Maletsky.

@item 
bpo-38630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38630}: On Unix, @ref{15f7,,subprocess.Popen.send_signal()} now polls the
process status. Polling reduces the risk of sending a signal to the wrong
process if the process completed, the @ref{c83,,subprocess.Popen.returncode}
attribute is still @code{None}, and the pid has been reassigned (recycled) to
a new different process.

@item 
bpo-38536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38536}: Removes trailing space in formatted currency with
@code{international=True} and a locale with symbol following value. E.g.
@code{locale.currency(12.34, international=True)} returned @code{'12,34 EUR '}
instead of @code{'12,34 EUR'}.

@item 
bpo-38473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38473}: Use signature from inner mock for autospecced methods attached
with @code{unittest.mock.attach_mock()}. Patch by Karthikeyan Singaravelan.

@item 
bpo-38361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38361}: Fixed an issue where @code{ident} could include a leading path
separator when @ref{760,,syslog.openlog()} was called without arguments.

@item 
bpo-38293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38293}: Add @ref{757,,copy.copy()} and @ref{d65,,copy.deepcopy()} support to
@ref{4b3,,property()} objects.

@item 
bpo-37958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37958}: Added the pstats.Stats.get_profile_dict() method to return the
profile data as a StatsProfile instance.

@item 
bpo-28367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28367}: Termios magic constants for the following baud rates:   -
B500000   - B576000   - B921600   - B1000000   - B1152000   - B1500000   -
B2000000   - B2500000   - B3000000   - B3500000   - B4000000 Patch by
Andrey Smirnov
@end itemize

@node ドキュメント<49>,ビルド<55>,ライブラリ<155>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id681}@anchor{1d91}
@subsubsection ドキュメント



@itemize -

@item 
bpo-39381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39381}: Mention in docs that @ref{2f2,,asyncio.get_event_loop()} implicitly
creates new event loop only if called from the main thread.

@item 
bpo-38918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38918}: Add an entry for @code{__module__} in the "function" & "method"
sections of the @ref{82,,inspect} docs' @ref{1d92,,型とメンバー} table.

@item 
bpo-3530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3530}: In the @ref{9,,ast} module documentation, fix a misleading
@code{NodeTransformer} example and add advice on when to use the
@code{fix_missing_locations} function.
@end itemize

@node ビルド<55>,IDLE<30>,ドキュメント<49>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id682}@anchor{1d93}
@subsubsection ビルド



@itemize -

@item 
bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395}: On non-Windows platforms, the @code{setenv()} and
@code{unsetenv()} functions are now required to build Python.

@item 
bpo-39160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39160}: Updated the documentation in @code{./configure --help} to show
default values, reference documentation where required and add additional
explanation where needed.

@item 
bpo-39144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39144}: The ctags and etags build targets both include Modules/_ctypes
and Python standard library source files.
@end itemize

@node IDLE<30>,C API<50>,ビルド<55>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id683}@anchor{1d94}
@subsubsection IDLE



@itemize -

@item 
bpo-39050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39050}: Make IDLE Settings dialog Help button work again.

@item 
bpo-34118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34118}: Tag memoryview, range, and tuple as classes, the same as list,
etcetera, in the library manual built-in functions list.

@item 
bpo-32989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32989}: Add tests for editor newline_and_indent_event method. Remove
dead code from pyparse find_good_parse_start method.
@end itemize

@node C API<50>,,IDLE<30>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id684}@anchor{1d95}
@subsubsection C API



@itemize -

@item 
bpo-39372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39372}: Clean header files of interfaces defined but with no
implementation. The public API symbols being removed are:
@code{_PyBytes_InsertThousandsGroupingLocale},
@code{_PyBytes_InsertThousandsGrouping}, @code{_Py_InitializeFromArgs},
@code{_Py_InitializeFromWideArgs}, @code{_PyFloat_Repr}, @code{_PyFloat_Digits},
@code{_PyFloat_DigitsInit}, @code{PyFrame_ExtendStack},
@code{_PyAIterWrapper_Type}, @code{PyNullImporter_Type}, @code{PyCmpWrapper_Type},
@code{PySortWrapper_Type}, @code{PyNoArgsFunction}.

@item 
bpo-39164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39164}: Add a private @code{_PyErr_GetExcInfo()} function to retrieve
exception information of the specified Python thread state.
@end itemize

@node Python 3 9 0 alpha 2,Python 3 9 0 alpha 1,Python 3 9 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-9-0-alpha-2}@anchor{1d96}
@subsection Python 3.9.0 alpha 2


`Release date: 2019-12-18'

@menu
* セキュリティ: セキュリティ<41>. 
* Core and Builtins: Core and Builtins<153>. 
* ライブラリ: ライブラリ<156>. 
* ドキュメント: ドキュメント<50>. 
* テスト: テスト<48>. 
* ビルド: ビルド<56>. 
* Windows: Windows<49>. 
* macOS: macOS<38>. 
* IDLE: IDLE<31>. 
* C API: C API<51>. 

@end menu

@node セキュリティ<41>,Core and Builtins<153>,,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id685}@anchor{1d97}
@subsubsection セキュリティ



@itemize -

@item 
bpo-38945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38945}: Newline characters have been escaped when performing uu
encoding to prevent them from overflowing into to content section of the
encoded file. This prevents malicious or accidental modification of data
during the decoding process.

@item 
bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228}: Due to significant security concerns, the `reuse_address'
parameter of @ref{93c,,asyncio.loop.create_datagram_endpoint()} is no longer
supported. This is because of the behavior of @code{SO_REUSEADDR} in UDP. For
more details, see the documentation for
@code{loop.create_datagram_endpoint()}. (Contributed by Kyle Stanley, Antoine
Pitrou, and Yury Selivanov in bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228}.)

@item 
bpo-38804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38804}: Fixes a ReDoS vulnerability in @ref{74,,http.cookiejar}. Patch by
Ben Caller.
@end itemize

@node Core and Builtins<153>,ライブラリ<156>,セキュリティ<41>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id686}@anchor{1d98}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-39028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39028}: Slightly improve the speed of keyword argument parsing with
many kwargs by strengthening the assumption that kwargs are interned
strings.

@item 
bpo-39080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39080}: Fix the value of `end_col_offset' for Starred Expression AST
nodes when they are among the elements in the `args' attribute of Call AST
nodes.

@item 
bpo-39031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39031}: When parsing an "elif" node, lineno and col_offset of the node
now point to the "elif" keyword and not to its condition, making it
consistent with the "if" node. Patch by Lysandros Nikolaou.

@item 
bpo-20443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20443}: In Python 3.9.0a1, sys.argv[0] was made an absolute path if a
filename was specified on the command line. Revert this change, since most
users expect sys.argv to be unmodified.

@item 
bpo-39008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39008}: @ref{613,,PySys_Audit()} now requires @code{Py_ssize_t} to be used
for size arguments in the format string, regardless of whether
@code{PY_SSIZE_T_CLEAN} was defined at include time.

@item 
bpo-38673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38673}: In REPL mode, don't switch to PS2 if the line starts with
comment or whitespace. Based on work by Batuhan Taşkaya.

@item 
bpo-38922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38922}: Calling @code{replace} on a code object now raises the
@code{code.__new__} audit event.

@item 
bpo-38920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38920}: Add audit hooks for when @ref{a0c,,sys.excepthook()} and
@ref{507,,sys.unraisablehook()} are invoked.

@item 
bpo-38892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38892}: Improve documentation for audit events table and functions.

@item 
bpo-38852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38852}: Set the thread stack size to 8 Mb for debug builds on android
platforms.

@item 
bpo-38858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38858}: Each Python subinterpreter now has its own "small integer
singletons": numbers in [-5; 257] range. It is no longer possible to
change the number of small integers at build time by overriding
@code{NSMALLNEGINTS} and @code{NSMALLPOSINTS} macros: macros should now be
modified manually in @code{pycore_pystate.h} header file.

@item 
bpo-36854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36854}: The garbage collector state becomes per interpreter
(@code{PyInterpreterState.gc}), rather than being global
(@code{_PyRuntimeState.gc}).

@item 
bpo-38835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38835}: The @code{PyFPE_START_PROTECT()} and @code{PyFPE_END_PROTECT()}
macros are empty: they have been doing nothing for the last year, so stop
using them.

@item 
bpo-38328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38328}: Sped up the creation time of constant @ref{24d,,list} and
@ref{184,,set} displays. Patch by Brandt Bucher.

@item 
bpo-38707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38707}: @code{MainThread.native_id} is now correctly reset in child
processes spawned using @ref{252,,multiprocessing.Process}, instead of
retaining the parent's value.

@item 
bpo-38629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38629}: Added @code{__floor__} and @code{__ceil__} methods to float object.
Patch by Batuhan Taşkaya.

@item 
bpo-27145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27145}: int + int and int - int operators can now return small integer
singletons. Patch by hongweipeng.

@item 
bpo-38021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38021}: Provide a platform tag for AIX that is sufficient for PEP425
binary distribution identification. Patch by Michael Felt.

@item 
bpo-35409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35409}: Ignore GeneratorExit exceptions when throwing an exception into
the aclose coroutine of an asynchronous generator.

@item 
bpo-33387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33387}: Removed WITH_CLEANUP_START, WITH_CLEANUP_FINISH, BEGIN_FINALLY,
END_FINALLY, CALL_FINALLY and POP_FINALLY bytecodes. Replaced with RERAISE
and WITH_EXCEPT_START bytecodes. The compiler now generates different code
for exceptional and non-exceptional branches for 'with' and 'try-except'
statements. For 'try-finally' statements the 'finally' block is replicated
for each exit from the 'try' body.
@end itemize

@node ライブラリ<156>,ドキュメント<50>,Core and Builtins<153>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id687}@anchor{1d99}
@subsubsection ライブラリ



@itemize -

@item 
bpo-39033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39033}: Fix @ref{452,,NameError} in @ref{138,,zipimport}. Patch by Karthikeyan
Singaravelan.

@item 
bpo-39022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39022}: Update importlib.metadata to include improvements from
importlib_metadata 1.3 including better serialization of EntryPoints and
improved documentation for custom finders.

@item 
bpo-39006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39006}: Fix asyncio when the ssl module is missing: only check for
ssl.SSLSocket instance if the ssl module is available.

@item 
bpo-38708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38708}: Fix a potential IndexError in email parser when parsing an
empty msg-id.

@item 
bpo-38698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38698}: Add a new @code{InvalidMessageID} token to email parser to
represent invalid Message-ID headers.  Also, add defects when there is
remaining value after parsing the header.

@item 
bpo-38994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38994}: Implement @code{__class_getitem__} for @code{os.PathLike},
@code{pathlib.Path}.

@item 
bpo-38979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38979}: Return class from @code{ContextVar.__class_getitem__} to simplify
subclassing.

@item 
bpo-38978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38978}: Implement @code{__class_getitem__} on asyncio objects (Future,
Task, Queue). Patch by Batuhan Taskaya.

@item 
bpo-38916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38916}: @ref{4be,,array.array}: Remove @code{tostring()} and
@code{fromstring()} methods. They were aliases to @code{tobytes()} and
@code{frombytes()}, deprecated since Python 3.2.

@item 
bpo-38986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38986}: Make repr of C accelerated TaskWakeupMethWrapper the same as of
pure Python version.

@item 
bpo-38982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38982}: Fix asyncio @code{PidfdChildWatcher}: handle @code{waitpid()} error.
If @code{waitpid()} is called elsewhere, @code{waitpid()} call fails with
@ref{1263,,ChildProcessError}: use return code 255 in this case, and log a
warning. It ensures that the pidfd file descriptor is closed if this error
occurs.

@item 
bpo-38529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38529}: Drop too noisy asyncio warning about deletion of a stream
without explicit @code{.close()} call.

@item 
bpo-27413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27413}: Added ability to pass through @code{ensure_ascii} options to
json.dumps in the @code{json.tool} command-line interface.

@item 
bpo-38634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38634}: The @ref{bf,,readline} module now detects if Python is linked to
libedit at runtime on all platforms.  Previously, the check was only done
on macOS.

@item 
bpo-33684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33684}: Fix @code{json.tool} failed to read a JSON file with non-ASCII
characters when locale encoding is not UTF-8.

@item 
bpo-38698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38698}: Prevent UnboundLocalError to pop up in parse_message_id.

parse_message_id() was improperly using a token defined inside an
exception handler, which was raising @code{UnboundLocalError} on parsing an
invalid value. Patch by Claudiu Popa.

@item 
bpo-38927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38927}: Use @code{python -m pip} instead of @code{pip} to upgrade
dependencies in venv.

@item 
bpo-26730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26730}: Fix @code{SpooledTemporaryFile.rollover()} might corrupt the file
when it is in text mode. Patch by Serhiy Storchaka.

@item 
bpo-38881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38881}: random.choices() now raises a ValueError when all the weights
are zero.

@item 
bpo-38876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38876}: Raise pickle.UnpicklingError when loading an item from memo for
invalid input.

The previous code was raising a @code{KeyError} for both the Python and C
implementation. This was caused by the specified index of an invalid input
which did not exist in the memo structure, where the pickle stores what
objects it has seen. The malformed input would have caused either a
@code{BINGET} or @code{LONG_BINGET} load from the memo, leading to a
@code{KeyError} as the determined index was bogus. Patch by Claudiu Popa.

@item 
bpo-38688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38688}: Calling func:@code{shutil.copytree} to copy a directory tree from
one directory to another subdirectory resulted in an endless loop and a
RecursionError. A fix was added to consume an iterator and create the list
of the entries to be copied, avoiding the recursion for newly created
directories. Patch by Bruno P. Kinoshita.

@item 
bpo-38863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38863}: Improve @code{is_cgi()} function in @ref{76,,http.server}, which
enables processing the case that cgi directory is a child of another
directory other than root.

@item 
bpo-37838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37838}: @ref{8c0,,typing.get_type_hints()} properly handles functions
decorated with @ref{115f,,functools.wraps()}.

@item 
bpo-38870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38870}: Expose @ref{ae2,,ast.unparse()} as a function of the @ref{9,,ast}
module that can be used to unparse an @ref{4c3,,ast.AST} object and produce
a string with code that would produce an equivalent @ref{4c3,,ast.AST}
object when parsed. Patch by Pablo Galindo and Batuhan Taskaya.

@item 
bpo-38859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38859}: AsyncMock now returns StopAsyncIteration on the exhaustion of a
side_effects iterable. Since PEP-479 its Impossible to raise a
StopIteration exception from a coroutine.

@item 
bpo-38857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38857}: AsyncMock fix for return values that are awaitable types.  This
also covers side_effect iterable values that happened to be awaitable, and
wraps callables that return an awaitable type. Before these awaitables
were being awaited instead of being returned as is.

@item 
bpo-38834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38834}: @ref{332,,typing.TypedDict} subclasses now track which keys are
optional using the @code{__required_keys__} and @code{__optional_keys__}
attributes, to enable runtime validation by downstream projects.  Patch by
Zac Hatfield-Dodds.

@item 
bpo-38821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38821}: Fix unhandled exceptions in @ref{7,,argparse} when
internationalizing error messages for arguments with @code{nargs} set to
special (non-integer) values. Patch by Federico Bond.

@item 
bpo-38820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38820}: Make Python compatible with OpenSSL 3.0.0.
@ref{11ba,,ssl.SSLSocket.getpeercert()} no longer returns IPv6 addresses with a
trailing new line.

@item 
bpo-38811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38811}: Fix an unhandled exception in @ref{a8,,pathlib} when
@ref{1307,,os.link()} is missing. Patch by Toke Høiland-Jørgensen.

@item 
bpo-38686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38686}: Added support for multiple @code{qop} values in
@ref{1d6b,,urllib.request.AbstractDigestAuthHandler}.

@item 
bpo-38712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38712}: Add the Linux-specific @ref{b25,,signal.pidfd_send_signal()}
function, which allows sending a signal to a process identified by a file
descriptor rather than a pid.

@item 
bpo-38348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38348}: Add @code{-i} and @code{--indent} (indentation level), and
@code{--no-type-comments} (type comments) command line options to ast parsing
tool.

@item 
bpo-37523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37523}: Change @code{zipfile.ZipExtFile} to raise @code{ValueError} when
trying to access the underlying file object after it has been closed. This
new behavior is consistent with how accessing closed files is handled in
other parts of Python.

@item 
bpo-38045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38045}: Improve the performance of @code{enum._decompose()} in
@ref{5a,,enum}. Patch by hongweipeng.

@item 
bpo-36820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36820}: Break cycle generated when saving an exception in socket.py,
codeop.py and dyld.py as they keep alive not only the exception but user
objects through the @code{__traceback__} attribute. Patch by Mario Corchero.

@item 
bpo-36406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36406}: Handle namespace packages in @ref{3e,,doctest}. Patch by
Karthikeyan Singaravelan.

@item 
bpo-34776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34776}: Fix dataclasses to support forward references in type
annotations

@item 
bpo-20928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20928}: ElementTree supports recursive XInclude processing.  Patch by
Stefan Behnel.

@item 
bpo-29636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29636}: Add whitespace options for formatting JSON with the
@code{json.tool} CLI. The following mutually exclusive options are now
supported: @code{--indent} for setting the indent level in spaces; @code{--tab}
for indenting with tabs; @code{--no-indent} for suppressing newlines; and
@code{--compact} for suppressing all whitespace. The default behavior remains
the same as @code{--indent=4}.
@end itemize

@node ドキュメント<50>,テスト<48>,ライブラリ<156>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id688}@anchor{1d9a}
@subsubsection ドキュメント



@itemize -

@item 
bpo-38928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38928}: Correct when venv's @code{upgrade_dependencies()} and
@code{--upgrade-deps} are added.

@item 
bpo-38899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38899}: Update documentation to state that to activate virtual
environments under fish one should use @code{source}, not @code{.} as documented
at @indicateurl{https://fishshell.com/docs/current/cmds/source.html}.

@item 
bpo-22377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22377}: Improves documentation of the values that
@ref{1950,,datetime.datetime.strptime()} accepts for @code{%Z}. Patch by Karl
Dubost.
@end itemize

@node テスト<48>,ビルド<56>,ドキュメント<50>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id689}@anchor{1d9b}
@subsubsection テスト



@itemize -

@item 
bpo-38546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38546}: Fix test_ressources_gced_in_workers() of
test_concurrent_futures: explicitly stop the manager to prevent leaking a
child process running in the background after the test completes.

@item 
bpo-38546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38546}: Multiprocessing and concurrent.futures tests now stop the
resource tracker process when tests complete.

@item 
bpo-38614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38614}: Replace hardcoded timeout constants in tests with new
@ref{ea,,test.support} constants: @ref{1d9c,,LOOPBACK_TIMEOUT},
@ref{1d9d,,INTERNET_TIMEOUT},
@ref{1c63,,SHORT_TIMEOUT} and
@ref{1d9e,,LONG_TIMEOUT}. It becomes easier to adjust these four
timeout constants for all tests at once, rather than having to adjust
every single test file.

@item 
bpo-38547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38547}: Fix test_pty: if the process is the session leader, closing the
master file descriptor raises a SIGHUP signal: simply ignore SIGHUP when
running the tests.

@item 
bpo-38992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38992}: Fix a test for @ref{15ed,,math.fsum()} that was failing due to
constant folding.

@item 
bpo-38991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38991}: @ref{ea,,test.support}:
@code{run_python_until_end()},
@code{assert_python_ok()} and
@code{assert_python_failure()} functions no longer strip
whitespaces from stderr. Remove @code{test.support.strip_python_stderr()}
function.

@item 
bpo-38965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38965}: Fix test_faulthandler on GCC 10. Use the "volatile" keyword in
@code{faulthandler._stack_overflow()} to prevent tail call optimization on
any compiler, rather than relying on compiler specific pragma.

@item 
bpo-38875@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38875}: test_capi: trashcan tests now require the test "cpu" resource.

@item 
bpo-38841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38841}: Skip asyncio test_create_datagram_endpoint_existing_sock_unix
on platforms lacking a functional bind() for named unix domain sockets.

@item 
bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}: Skip the test_posix.test_pidfd_open() test if
@code{os.pidfd_open()} fails with a @ref{f3e,,PermissionError}. This situation
can happen in a Linux sandbox using a syscall whitelist which doesn't
allow the @code{pidfd_open()} syscall yet.

@item 
bpo-38839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38839}: Fix some unused functions in tests. Patch by Adam Johnson.

@item 
bpo-38669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38669}: Raise @ref{198,,TypeError} when passing target as a string with
@ref{1906,,unittest.mock.patch.object()}.

@item 
bpo-37957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37957}: test.regrtest now can receive a list of test patterns to ignore
(using the -i/--ignore argument) or a file with a list of patterns to
ignore (using the --ignore-file argument). Patch by Pablo Galindo.
@end itemize

@node ビルド<56>,Windows<49>,テスト<48>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id690}@anchor{1d9f}
@subsubsection ビルド



@itemize -

@item 
bpo-37404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37404}: @ref{b,,asyncio} now raises @ref{198,,TypeError} when calling
incompatible methods with an @ref{ae7,,ssl.SSLSocket} socket.  Patch by Ido
Michael.

@item 
bpo-36500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36500}: Added an optional "regen" project to the Visual Studio solution
that will regenerate all grammar, tokens, and opcodes.
@end itemize

@node Windows<49>,macOS<38>,ビルド<56>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id691}@anchor{1da0}
@subsubsection Windows



@itemize -

@item 
bpo-39007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39007}: Add auditing events to functions in @ref{11c,,winreg}.

@item 
bpo-33125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33125}: Add support for building and releasing Windows ARM64 packages.
@end itemize

@node macOS<38>,IDLE<31>,Windows<49>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id692}@anchor{1da1}
@subsubsection macOS



@itemize -

@item 
bpo-37931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37931}: Fixed a crash on OSX dynamic builds that occurred when
re-initializing the posix module after a Py_Finalize if the environment
had changed since the previous @code{import posix}. Patch by Benoît Hudson.
@end itemize

@node IDLE<31>,C API<51>,macOS<38>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id693}@anchor{1da2}
@subsubsection IDLE



@itemize -

@item 
bpo-38944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38944}: Escape key now closes IDLE completion windows.  Patch by Johnny
Najera.

@item 
bpo-38943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38943}: Fix IDLE autocomplete windows not always appearing on some
systems. Patch by Johnny Najera.

@item 
bpo-38862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38862}: 'Strip Trailing Whitespace' on the Format menu removes extra
newlines at the end of non-shell files.

@item 
bpo-38636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38636}: Fix IDLE Format menu tab toggle and file indent width. These
functions (default shortcuts Alt-T and Alt-U) were mistakenly disabled in
3.7.5 and 3.8.0.
@end itemize

@node C API<51>,,IDLE<31>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id694}@anchor{1da3}
@subsubsection C API



@itemize -

@item 
bpo-38896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38896}: Remove @code{PyUnicode_ClearFreeList()} function: the Unicode free
list has been removed in Python 3.3.

@item 
bpo-37340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37340}: Remove @code{PyMethod_ClearFreeList()} and
@code{PyCFunction_ClearFreeList()} functions: the free lists of bound method
objects have been removed.

@item 
bpo-38835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38835}: Exclude @code{PyFPE_START_PROTECT()} and @code{PyFPE_END_PROTECT()}
macros of @code{pyfpe.h} from @code{Py_LIMITED_API} (stable API).
@end itemize

@node Python 3 9 0 alpha 1,Python 3 8 0 beta 1,Python 3 9 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-9-0-alpha-1}@anchor{1da4}
@subsection Python 3.9.0 alpha 1


`Release date: 2019-11-19'

@menu
* セキュリティ: セキュリティ<42>. 
* Core and Builtins: Core and Builtins<154>. 
* ライブラリ: ライブラリ<157>. 
* ドキュメント: ドキュメント<51>. 
* テスト: テスト<49>. 
* ビルド: ビルド<57>. 
* Windows: Windows<50>. 
* macOS: macOS<39>. 
* IDLE: IDLE<32>. 
* Tools/Demos: Tools/Demos<33>. 
* C API: C API<52>. 

@end menu

@node セキュリティ<42>,Core and Builtins<154>,,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id695}@anchor{1da5}
@subsubsection セキュリティ



@itemize -

@item 
bpo-38722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38722}: @ref{c3,,runpy} now uses @ref{1a98,,io.open_code()} to open code files.
Patch by Jason Killen.

@item 
bpo-38622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38622}: Add additional audit events for the @ref{2e,,ctypes} module.

@item 
bpo-38418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38418}: Fixes audit event for @ref{1676,,os.system()} to be named
@code{os.system}.

@item 
bpo-38243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38243}: Escape the server title of
@ref{1da6,,xmlrpc.server.DocXMLRPCServer} when rendering the document page as
HTML. (Contributed by Donghee Na in bpo-38243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38243}.)

@item 
bpo-38174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38174}: Update vendorized expat library version to 2.2.8, which
resolves 
@geindex Common Vulnerabilities and Exposures; CVE 2019-15903
CVE 2019-15903@footnote{https://www.cve.org/CVERecord?id=CVE-2019-15903}.

@item 
bpo-37764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37764}: Fixes email._header_value_parser.get_unstructured going into an
infinite loop for a specific case in which the email header does not have
trailing whitespace, and the case in which it contains an invalid encoded
word. Patch by Ashwin Ramaswami.

@item 
bpo-37461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37461}: Fix an infinite loop when parsing specially crafted email
headers. Patch by Abhilash Raj.

@item 
bpo-37363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37363}: Adds audit events for the range of supported run commands (see
@ref{1da7,,コマンドラインと環境}).

@item 
bpo-37463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37463}: ssl.match_hostname() no longer accepts IPv4 addresses with
additional text after the address and only quad-dotted notation without
trailing whitespaces. Some inet_aton() implementations ignore whitespace
and all data after whitespace, e.g. '127.0.0.1 whatever'.

@item 
bpo-37363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37363}: Adds audit events for @ref{59,,ensurepip}, @ref{62,,ftplib},
@ref{68,,glob}, @ref{78,,imaplib}, @code{nntplib}, @ref{aa,,pdb}, @ref{b1,,poplib},
@ref{ca,,shutil}, @ref{cf,,smtplib}, @ref{d4,,sqlite3}, @ref{dc,,subprocess},
@code{telnetlib}, @ref{e6,,tempfile} and @ref{11b,,webbrowser}, as well as
@ref{1312,,os.listdir()}, @ref{c54,,os.scandir()} and @ref{271,,breakpoint()}.

@item 
bpo-37364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37364}: @ref{1a98,,io.open_code()} is now used when reading @code{.pth}
files.

@item 
bpo-34631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34631}: Updated OpenSSL to 1.1.1c in Windows installer

@item 
bpo-34155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34155}: Fix parsing of invalid email addresses with more than one @code{@@}
(e.g. a@@b@@c.com.) to not return the part before 2nd @code{@@} as valid email
address. Patch by maxking & jpic.
@end itemize

@node Core and Builtins<154>,ライブラリ<157>,セキュリティ<42>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id696}@anchor{1da8}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-38631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38631}: Replace @code{Py_FatalError()} call with a regular
@ref{244,,RuntimeError} exception in @code{float.__getformat__()}.

@item 
bpo-38639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38639}: Optimized @ref{15d7,,math.floor()}, @ref{15d8,,math.ceil()} and
@ref{15d9,,math.trunc()} for floats.

@item 
bpo-38640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38640}: Fixed a bug in the compiler that was causing to raise in the
presence of break statements and continue statements inside always false
while loops. Patch by Pablo Galindo.

@item 
bpo-38613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38613}: Optimized some set operations (e.g. @code{|}, @code{^}, and @code{-}) of
@code{dict_keys}. @code{d.keys() | other} was slower than @code{set(d) | other} but
they are almost same performance for now.

@item 
bpo-28029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28029}: @code{"".replace("", s, n)} now returns @code{s} instead of an empty
string for all non-zero @code{n}.  There are similar changes for
@ref{192,,bytes} and @ref{344,,bytearray} objects.

@item 
bpo-38535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38535}: Fixed line numbers and column offsets for AST nodes for calls
without arguments in decorators.

@item 
bpo-38525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38525}: Fix a segmentation fault when using reverse iterators of empty
@code{dict} objects. Patch by Donghee Na and Inada Naoki.

@item 
bpo-38465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38465}: @ref{344,,bytearray}, @ref{4be,,array} and
@ref{519,,mmap} objects allow now to export more than @code{2**31}
buffers at a time.

@item 
bpo-38469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38469}: Fixed a bug where the scope of named expressions was not being
resolved correctly in the presence of the `global' keyword. Patch by Pablo
Galindo.

@item 
bpo-38437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38437}: Activate the @code{GC_DEBUG} macro for debug builds of the
interpreter (when @code{Py_DEBUG} is set). Patch by Pablo Galindo.

@item 
bpo-38379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38379}: When the garbage collector makes a collection in which some
objects resurrect (they are reachable from outside the isolated cycles
after the finalizers have been executed), do not block the collection of
all objects that are still unreachable. Patch by Pablo Galindo and Tim
Peters.

@item 
bpo-38379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38379}: When cyclic garbage collection (gc) runs finalizers that
resurrect unreachable objects, the current gc run ends, without collecting
any cyclic trash.  However, the statistics reported by @code{collect()} and
@code{get_stats()} claimed that all cyclic trash found was collected, and
that the resurrected objects were collected.   Changed the stats to report
that none were collected.

@item 
bpo-38392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38392}: In debug mode, @ref{171d,,PyObject_GC_Track()} now calls
@code{tp_traverse()} of the object type to ensure that the object is valid:
test that objects visited by @code{tp_traverse()} are valid.

@item 
bpo-38210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38210}: Remove unnecessary intersection and update set operation in
dictview with empty set. (Contributed by Donghee Na in bpo-38210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38210}.)

@item 
bpo-38402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38402}: Check the error from the system's underlying @code{crypt} or
@code{crypt_r}.

@item 
bpo-37474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37474}: On FreeBSD, Python no longer calls @code{fedisableexcept()} at
startup to control the floating-point control mode. The call became
useless since FreeBSD 6: it became the default mode.

@item 
bpo-38006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38006}: Fix a bug due to the interaction of weakrefs and the cyclic
garbage collector. We must clear any weakrefs in garbage in order to
prevent their callbacks from executing and causing a crash.

@item 
bpo-38317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38317}: Fix warnings options priority: @code{PyConfig.warnoptions} has the
highest priority, as stated in the 
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/}.

@item 
bpo-38310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38310}: Predict @code{BUILD_MAP_UNPACK_WITH_CALL} -> @code{CALL_FUNCTION_EX}
opcode pairs in the main interpreter loop. Patch by Brandt Bucher.

@item 
bpo-36871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36871}: Improve error handling for the assert_has_calls and
assert_has_awaits methods of mocks. Fixed a bug where any errors
encountered while binding the expected calls to the mock's spec were
silently swallowed, leading to misleading error output.

@item 
bpo-11410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11410}: Better control over symbol visibility is provided through use
of the visibility attributes available in gcc >= 4.0, provided in a
uniform way across POSIX and Windows. The POSIX build files have been
updated to compile with -fvisibility=hidden, minimising exported symbols.

@item 
bpo-38219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38219}: Optimized the @ref{183,,dict} constructor and the
@ref{167e,,update()} method for the case when the argument is a dict.

@item 
bpo-38236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38236}: Python now dumps path configuration if it fails to import the
Python codecs of the filesystem and stdio encodings.

@item 
bpo-38013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38013}: Allow to call @code{async_generator_athrow().throw(...)} even for
non-started async generator helper. It fixes annoying warning at the end
of @ref{2f3,,asyncio.run()} call.

@item 
bpo-38124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38124}: Fix an off-by-one error in PyState_AddModule that could cause
out-of-bounds memory access.

@item 
bpo-38116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38116}: The select module is now PEP-384 compliant and no longer has
static state

@item 
bpo-38113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38113}: ast module updated to PEP-384 and all statics removed

@item 
bpo-38076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38076}: The struct module is now PEP-384 compatible

@item 
bpo-38075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38075}: The random module is now PEP-384 compatible

@item 
bpo-38074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38074}: zlib module made PEP-384 compatible

@item 
bpo-38073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38073}: Make pwd extension module PEP-384 compatible

@item 
bpo-38072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38072}: grp module made PEP-384 compatible

@item 
bpo-38069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38069}: Make _posixsubprocess PEP-384 compatible

@item 
bpo-38071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38071}: Make termios extension module PEP-384 compatible

@item 
bpo-38005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38005}: Fixed comparing and creating of InterpreterID and ChannelID.

@item 
bpo-36946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36946}: Fix possible signed integer overflow when handling slices.
Patch by hongweipeng.

@item 
bpo-37994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37994}: Fixed silencing arbitrary errors if an attribute lookup fails
in several sites. Only AttributeError should be silenced.

@item 
bpo-8425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8425}: Optimize set difference_update for the case when the other set
is much larger than the base set.  (Suggested by Evgeny Kapun with code
contributed by Michele Orrù).

@item 
bpo-37966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37966}: The implementation of @ref{c3c,,is_normalized()} has
been greatly sped up on strings that aren't normalized, by implementing
the full normalization-quick-check algorithm from the Unicode standard.

@item 
bpo-37947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37947}: Adjust correctly the recursion level in the symtable generation
for named expressions. Patch by Pablo Galindo.

@item 
bpo-37812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37812}: The @code{CHECK_SMALL_INT} macro used inside
@code{Object/longobject.c} has been replaced with an explicit @code{return}
at each call site.

@item 
bpo-37751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37751}: Fix @ref{b5c,,codecs.lookup()} to normalize the encoding name the
same way than @ref{9fd,,encodings.normalize_encoding()}, except that
@ref{b5c,,codecs.lookup()} also converts the name to lower case.

@item 
bpo-37830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37830}: Fixed compilation of @ref{17f,,break} and @ref{180,,continue}
in the @ref{1b0,,finally} block when the corresponding @ref{8f8,,try}
block contains @ref{1af,,return} with a non-constant value.

@item 
bpo-20490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20490}: Improve import error message for partially initialized module
on circular @code{from} imports - by Anthony Sottile.

@item 
bpo-37840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37840}: Fix handling of negative indices in
@ref{1cf5,,sq_item} of @ref{344,,bytearray}. Patch by
Sergey Fedoseev.

@item 
bpo-37802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37802}: Slightly improve performance of
@ref{18bd,,PyLong_FromUnsignedLong()}, @ref{18be,,PyLong_FromUnsignedLongLong()}
and @ref{18bf,,PyLong_FromSize_t()}. Patch by Sergey Fedoseev.

@item 
bpo-37409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37409}: Ensure explicit relative imports from interactive sessions and
scripts (having no parent package) always raise ImportError, rather than
treating the current module as the package. Patch by Ben Lewis.

@item 
bpo-32912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32912}: Reverted bpo-32912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32912}: emitting @ref{1ae,,SyntaxWarning} instead
of @ref{1a3,,DeprecationWarning} for invalid escape sequences in string and
bytes literals.

@item 
bpo-37757@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37757}: 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/}: As described in the PEP, assignment expressions now
raise @ref{18e,,SyntaxError} when their interaction with comprehension scoping
results in an ambiguous target scope.

The @code{TargetScopeError} subclass originally proposed by the PEP has been
removed in favour of just raising regular syntax errors for the disallowed
cases.

@item 
bpo-36279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36279}: Fix potential use of uninitialized memory in @ref{f96,,os.wait3()}.

@item 
bpo-36311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36311}: Decoding bytes objects larger than 2GiB is faster and no longer
fails when a multibyte characters spans a chunk boundary.

@item 
bpo-34880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34880}: The @ref{b60,,assert} statement now works properly if the
@ref{8b8,,AssertionError} exception is being shadowed. Patch by Zackery Spytz.

@item 
bpo-37340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37340}: Removed object cache (@code{free_list}) for bound method objects.
Temporary bound method objects are less used than before thanks to the
@code{LOAD_METHOD} opcode and the @code{_PyObject_VectorcallMethod} C API.

@item 
bpo-37648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37648}: Fixed minor inconsistency in @code{list.__contains__()},
@code{tuple.__contains__()} and a few other places. The collection's item
is now always at the left and the needle is on the right of @code{==}.

@item 
bpo-37444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37444}: Update differing exception between @code{builtins.__import__()}
and @ref{1279,,importlib.__import__()}.

@item 
bpo-37619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37619}: When adding a wrapper descriptor from one class to a different
class (for example, setting @code{__add__ = str.__add__} on an @code{int}
subclass), an exception is correctly raised when the operator is called.

@item 
bpo-37593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37593}: Swap the positions of the `posonlyargs' and `args' parameters
in the constructor of @code{ast.parameters} nodes.

@item 
bpo-37543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37543}: Optimized pymalloc for non PGO build.

@item 
bpo-37537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37537}: Compute allocated pymalloc blocks inside
_Py_GetAllocatedBlocks().  This slows down _Py_GetAllocatedBlocks() but
gives a small speedup to _PyObject_Malloc() and _PyObject_Free().

@item 
bpo-37467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37467}: Fix @ref{a0c,,sys.excepthook()} and @code{PyErr_Display()} if a
filename is a bytes string. For example, for a SyntaxError exception where
the filename attribute is a bytes string.

@item 
bpo-37433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37433}: Fix @code{SyntaxError} indicator printing too many spaces for
multi-line strings - by Anthony Sottile.

@item 
bpo-37417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37417}: @ref{1791,,bytearray.extend()} now correctly handles errors that
arise during iteration. Patch by Brandt Bucher.

@item 
bpo-37414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37414}: The undocumented @code{sys.callstats()} function has been removed.
Since Python 3.7, it was deprecated and always returned @code{None}. It
required a special build option @code{CALL_PROFILE} which was already removed
in Python 3.7.

@item 
bpo-37392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37392}: Remove @code{sys.getcheckinterval()} and
@code{sys.setcheckinterval()} functions. They were deprecated since Python
3.2. Use @ref{b43,,sys.getswitchinterval()} and @ref{b44,,sys.setswitchinterval()}
instead. Remove also @code{check_interval} field of the
@code{PyInterpreterState} structure.

@item 
bpo-37388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37388}: In development mode and in debug build, `encoding' and `errors'
arguments are now checked on string encoding and decoding operations.
Examples: @ref{316,,open()}, @ref{ad2,,str.encode()} and @ref{ad3,,bytes.decode()}.

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.

@item 
bpo-37348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37348}: Optimized decoding short ASCII string with UTF-8 and ascii
codecs. @code{b"foo".decode()} is about 15% faster.  Patch by Inada Naoki.

@item 
bpo-24214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24214}: Improved support of the surrogatepass error handler in the
UTF-8 and UTF-16 incremental decoders.

@item 
bpo-37330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37330}: @ref{316,,open()}, @ref{740,,io.open()}, @ref{315,,codecs.open()} and
@ref{940,,fileinput.FileInput} no longer accept @code{'U'} ("universal
newline") in the file mode. This flag was deprecated since Python 3.3.

@item 
bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224}: Reverse evaluation order of key: value in dict comprehensions
as proposed in PEP 572. I.e. in @code{@{k: v for ...@}}, @code{k} will be
evaluated before @code{v}.

@item 
bpo-37316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37316}: Fix the @ref{613,,PySys_Audit()} call in @ref{519,,mmap.mmap}.

@item 
bpo-37300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37300}: Remove an unnecessary Py_XINCREF in classobject.c.

@item 
bpo-37269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37269}: Fix a bug in the peephole optimizer that was not treating
correctly constant conditions with binary operators. Patch by Pablo
Galindo.

@item 
bpo-20443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20443}: Python now gets the absolute path of the script filename
specified on the command line (ex: "python3 script.py"): the __file__
attribute of the __main__ module and sys.path[0] become an absolute path,
rather than a relative path.

@item 
bpo-37257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37257}: Python's small object allocator (@code{obmalloc.c}) now allows (no
more than) one empty arena to remain available for immediate reuse,
without returning it to the OS.  This prevents thrashing in simple loops
where an arena could be created and destroyed anew on each iteration.

@item 
bpo-37231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37231}: The dispatching of type slots to special methods (for example
calling @code{__mul__} when doing @code{x * y}) has been made faster.

@item 
bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}: Implemented separate vectorcall functions for every calling
convention of builtin functions and methods. This improves performance for
calls.

@item 
bpo-37213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37213}: Handle correctly negative line offsets in the peephole
optimizer. Patch by Pablo Galindo.

@item 
bpo-37219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37219}: Remove erroneous optimization for empty set differences.

@item 
bpo-15913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15913}: Implement @ref{95e,,PyBuffer_SizeFromFormat()} function
(previously documented but not implemented): call @ref{1da9,,struct.calcsize()}.
Patch by Joannah Nanjekye.

@item 
bpo-36922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36922}: Slot functions optimize any callable with
@code{Py_TPFLAGS_METHOD_DESCRIPTOR} instead of only instances of
@code{function}.

@item 
bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}: The slot @code{tp_vectorcall_offset} is inherited unconditionally
to support @code{super().__call__()} when the base class uses vectorcall.

@item 
bpo-37160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37160}: @ref{c32,,threading.get_native_id()} now also supports NetBSD.

@item 
bpo-37077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37077}: Add @ref{c32,,threading.get_native_id()} support for AIX. Patch by
M. Felt

@item 
bpo-36781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36781}: @ref{695,,sum()} has been optimized for boolean values.

@item 
bpo-34556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34556}: Add @code{--upgrade-deps} to venv module. Patch by Cooper Ry Lees

@item 
bpo-20523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20523}: @code{pdb.Pdb} supports ~/.pdbrc in Windows 7. Patch by Tim Hopper
and Dan Lidral-Porter.

@item 
bpo-35551@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35551}: Updated encodings: - Removed the "tis260" encoding, which was
an alias for the nonexistent "tactis" codec. - Added "mac_centeuro" as an
alias for the mac_latin2 encoding.

@item 
bpo-19072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19072}: The @ref{48e,,classmethod} decorator can now wrap other
descriptors such as property objects.  Adapted from a patch written by
Graham Dumpleton.

@item 
bpo-27575@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27575}: Improve speed of dictview intersection by directly using set
intersection logic. Patch by David Su.

@item 
bpo-30773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30773}: Prohibit parallel running of aclose() / asend() / athrow(). Fix
ag_running to reflect the actual running status of the AG.
@end itemize

@node ライブラリ<157>,ドキュメント<51>,Core and Builtins<154>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id697}@anchor{1daa}
@subsubsection ライブラリ



@itemize -

@item 
bpo-36589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36589}: The @ref{feb,,curses.update_lines_cols()} function now returns
@code{None} instead of @code{1} on success.

@item 
bpo-38807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38807}: Update @ref{198,,TypeError} messages for @ref{19a9,,os.path.join()} to
include @ref{e4b,,os.PathLike} objects as acceptable input types.

@item 
bpo-38724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38724}: Add a repr for @code{subprocess.Popen} objects. Patch by Andrey
Doroschenko.

@item 
bpo-38786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38786}: pydoc now recognizes and parses HTTPS URLs. Patch by python273.

@item 
bpo-38785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38785}: Prevent asyncio from crashing if parent @code{__init__} is not
called from a constructor of object derived from @code{asyncio.Future}.

@item 
bpo-38723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38723}: @ref{aa,,pdb} now uses @ref{1a98,,io.open_code()} to trigger auditing
events.

@item 
bpo-27805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27805}: Allow opening pipes and other non-seekable files in append mode
with @ref{316,,open()}.

@item 
bpo-38438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38438}: Simplify the @ref{7,,argparse} usage message for @code{nargs="*"}.

@item 
bpo-38761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38761}: WeakSet is now registered as a collections.abc.MutableSet.

@item 
bpo-38716@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38716}: logging: change RotatingHandler namer and rotator to
class-level attributes. This stops __init__ from setting them to None in
the case where a subclass defines them with eponymous methods.

@item 
bpo-38713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38713}: Add @ref{b16,,os.P_PIDFD} constant, which may be passed to
@ref{f99,,os.waitid()} to wait on a Linux process file descriptor.

@item 
bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}: Add @code{asyncio.PidfdChildWatcher}, a Linux-specific child
watcher implementation that polls process file descriptors.

@item 
bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}: Expose the Linux @code{pidfd_open} syscall as
@ref{6a4,,os.pidfd_open()}.

@item 
bpo-38602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38602}: Added constants @code{F_OFD_GETLK},
@code{F_OFD_SETLK} and @code{F_OFD_SETLKW} to the
@ref{5d,,fcntl} module. Patch by Donghee Na.

@item 
bpo-38334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38334}: Fixed seeking backward on an encrypted
@code{zipfile.ZipExtFile}.

@item 
bpo-38312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38312}: Add @ref{aec,,curses.get_escdelay()}, @ref{aed,,curses.set_escdelay()},
@ref{aee,,curses.get_tabsize()}, and @ref{aef,,curses.set_tabsize()} functions - by
Anthony Sottile.

@item 
bpo-38586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38586}: Now @ref{d48,,fileConfig()} correctly sets the .name
of handlers loaded.

@item 
bpo-38565@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38565}: Add new cache_parameters() method for functools.lru_cache() to
better support pickling.

@item 
bpo-34679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34679}: asynci.ProactorEventLoop.close() now only calls
signal.set_wakeup_fd() in the main thread.

@item 
bpo-31202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31202}: The case the result of @code{pathlib.WindowsPath.glob()} matches
now the case of the pattern for literal parts.

@item 
bpo-36321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36321}: Remove misspelled attribute.  The 3.8 changelog noted that this
would be removed in 3.9.

@item 
bpo-38521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38521}: Fixed erroneous equality comparison in statistics.NormalDist().

@item 
bpo-38493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38493}: Added @ref{b14,,CLD_KILLED} and @ref{b15,,CLD_STOPPED} for
@code{si_code}. Patch by Donghee Na.

@item 
bpo-38478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38478}: Fixed a bug in @code{inspect.signature.bind()} that was causing
it to fail when handling a keyword argument with same name as
positional-only parameter. Patch by Pablo Galindo.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Fixed @code{hmac.new} and @code{hmac.HMAC} to raise TypeError instead
of ValueError when the digestmod parameter, now required in 3.8, is
omitted. Also clarified the hmac module documentation and docstrings.

@item 
bpo-38378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38378}: Parameters `out' and `in' of @ref{d05,,os.sendfile()} was renamed to
`out_fd' and `in_fd'.

@item 
bpo-38417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38417}: Added support for setting the umask in the child process to the
subprocess module on POSIX systems.

@item 
bpo-38449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38449}: Revert PR 15522, which introduces a regression in
@ref{517,,mimetypes.guess_type()} due to improper handling of filenames as
urls.

@item 
bpo-38431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38431}: Fix @code{__repr__} method for @ref{1bb4,,dataclasses.InitVar} to
support typing objects, patch by Samuel Colvin.

@item 
bpo-38109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38109}: Add missing @ref{11bd,,stat.S_IFDOOR}, @ref{11be,,stat.S_IFPORT},
@ref{11bf,,stat.S_IFWHT}, @ref{1dab,,stat.S_ISDOOR()}, @ref{1dac,,stat.S_ISPORT()}, and
@ref{1dad,,stat.S_ISWHT()} values to the Python implementation of @ref{d6,,stat}.

@item 
bpo-38422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38422}: Clarify docstrings of pathlib suffix(es)

@item 
bpo-38405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38405}: Nested subclasses of @ref{331,,typing.NamedTuple} are now
pickleable.

@item 
bpo-38332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38332}: Prevent @ref{5e7,,KeyError} thrown by
@code{_encoded_words.decode()} when given an encoded-word with invalid
content-type encoding from propagating all the way to
@code{email.message.get()}.

@item 
bpo-38371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38371}: Deprecated the @code{split()} method in
@code{_tkinter.TkappType} in favour of the @code{splitlist()} method which
has more consistent and predictable behavior.

@item 
bpo-38341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38341}: Add @ref{1dae,,smtplib.SMTPNotSupportedError} to the @ref{cf,,smtplib}
exported names.

@item 
bpo-38319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38319}: sendfile() used in socket and shutil modules was raising
OverflowError for files >= 2GiB on 32-bit architectures.  (patch by
Giampaolo Rodola)

@item 
bpo-38242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38242}: Revert the new asyncio Streams API

@item 
bpo-13153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13153}: OS native encoding is now used for converting between Python
strings and Tcl objects.  This allows to display, copy and paste to
clipboard emoji and other non-BMP characters.  Converting strings from Tcl
to Python and back now never fails (except MemoryError).

@item 
bpo-38019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38019}: Correctly handle pause/resume reading of closed asyncio unix
pipe.

@item 
bpo-38163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38163}: Child mocks will now detect their type as either synchronous or
asynchronous, asynchronous child mocks will be AsyncMocks and synchronous
child mocks will be either MagicMock or Mock (depending on their parent
type).

@item 
bpo-38161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38161}: Removes _AwaitEvent from AsyncMock.

@item 
bpo-38216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38216}: Allow the rare code that wants to send invalid http requests
from the @code{http.client} library a way to do so.  The fixes for bpo-30458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30458}
led to breakage for some projects that were relying on this ability to
test their own behavior in the face of bad requests.

@item 
bpo-28286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28286}: Deprecate opening @ref{65c,,GzipFile} for writing
implicitly.  Always specify the `mode' argument for writing.

@item 
bpo-38108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38108}: Any synchronous magic methods on an AsyncMock now return a
MagicMock. Any asynchronous magic methods on a MagicMock now return an
AsyncMock.

@item 
bpo-38265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38265}: Update the `length' parameter of @ref{d56,,os.pread()} to accept
@ref{c55,,Py_ssize_t} instead of int.

@item 
bpo-38112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38112}: @ref{21,,compileall} has a higher default recursion limit and new
command-line arguments for path manipulation, symlinks handling, and
multiple optimization levels.

@item 
bpo-38248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38248}: asyncio: Fix inconsistent immediate Task cancellation

@item 
bpo-38237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38237}: The arguments for the builtin pow function are more
descriptive. They can now also be passed in as keywords.

@item 
bpo-34002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34002}: Improve efficiency in parts of email package by changing
while-pop to a for loop, using isdisjoint instead of set intersections.

@item 
bpo-38191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38191}: Constructors of @ref{331,,NamedTuple} and
@ref{332,,TypedDict} types now accept arbitrary keyword argument
names, including "cls", "self", "typename", "_typename", "fields" and
"_fields".

@item 
bpo-38155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38155}: Add @code{__all__} to  @ref{34,,datetime}. Patch by Tahia Khan.

@item 
bpo-38185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38185}: Fixed case-insensitive string comparison in
@ref{1071,,sqlite3.Row} indexing.

@item 
bpo-38136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38136}: Changes AsyncMock call count and await count to be two
different counters. Now await count only counts when a coroutine has been
awaited, not when it has been called, and vice-versa. Update the
documentation around this.

@item 
bpo-37828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37828}: Fix default mock name in
@ref{ef4,,unittest.mock.Mock.assert_called()} exceptions. Patch by Abraham
Toriz Cruz.

@item 
bpo-38175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38175}: Fix a memory leak in comparison of @ref{1071,,sqlite3.Row}
objects.

@item 
bpo-33936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33936}: _hashlib no longer calls obsolete OpenSSL initialization
function with OpenSSL 1.1.0+.

@item 
bpo-34706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34706}: Preserve subclassing in inspect.Signature.from_callable.

@item 
bpo-38153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38153}: Names of hashing algorithms from OpenSSL are now normalized to
follow Python's naming conventions. For example OpenSSL uses sha3-512
instead of sha3_512 or blake2b512 instead of blake2b.

@item 
bpo-38115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38115}: Fix a bug in dis.findlinestarts() where it would return invalid
bytecode offsets. Document that a code object's co_lnotab can contain
invalid bytecode offsets.

@item 
bpo-38148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38148}: Add slots to @ref{b,,asyncio} transport classes, which can reduce
memory usage.

@item 
bpo-38142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38142}: The _hashlib OpenSSL wrapper extension module is now PEP-384
compliant.

@item 
bpo-9216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9216}: hashlib constructors now support usedforsecurity flag to signal
that a hashing algorithm is not used in a security context.

@item 
bpo-36991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36991}: Fixes a potential incorrect AttributeError exception escaping
ZipFile.extract() in some unsupported input error situations.

@item 
bpo-38134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38134}: Remove obsolete copy of PBKDF2_HMAC_fast. All supported OpenSSL
versions contain a fast implementation.

@item 
bpo-38132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38132}: The OpenSSL hashlib wrapper uses a simpler implementation.
Several Macros and pointless caches are gone. The hash name now comes from
OpenSSL's EVP. The algorithm name stays the same, except it is now always
lower case.

@item 
bpo-38008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38008}: Fix parent class check in protocols to correctly identify the
module that provides a builtin protocol, instead of assuming they all come
from the @ref{1f,,collections.abc} module

@item 
bpo-34037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34037}: For @ref{b,,asyncio}, add a new coroutine
@code{loop.shutdown_default_executor()}. The new coroutine provides an API
to schedule an executor shutdown that waits on the threadpool to finish
closing. Also, @ref{2f3,,asyncio.run()} has been updated to utilize the new
coroutine. Patch by Kyle Stanley.

@item 
bpo-37405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37405}: Fixed regression bug for socket.getsockname() for non-CAN_ISOTP
AF_CAN address family sockets by returning a 1-tuple instead of string.

@item 
bpo-38121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38121}: Update parameter names on functions in importlib.metadata
matching the changes in the 0.22 release of importlib_metadata.

@item 
bpo-38110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38110}: The os.closewalk() implementation now uses the libc fdwalk()
API on platforms where it is available.

@item 
bpo-38093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38093}: Fixes AsyncMock so it doesn't crash when used with
AsyncContextManagers or AsyncIterators.

@item 
bpo-37488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37488}: Add warning to @code{datetime.utctimetuple()},
@code{datetime.utcnow()} and @code{datetime.utcfromtimestamp()} .

@item 
bpo-35640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35640}: Allow passing a @ref{5a1,,path-like object} as @code{directory}
argument to the @ref{d38,,http.server.SimpleHTTPRequestHandler} class. Patch
by Géry Ogam.

@item 
bpo-38086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38086}: Update importlib.metadata with changes from importlib_metadata 0.21@footnote{https://gitlab.com/python-devs/importlib_metadata/blob/0.21/importlib_metadata/docs/changelog.rst}.

@item 
bpo-37251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37251}: Remove @code{__code__} check in AsyncMock that incorrectly
evaluated function specs as async objects but failed to evaluate classes
with @code{__await__} but no @code{__code__} attribute defined as async objects.

@item 
bpo-38037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38037}: Fix reference counters in the @ref{cb,,signal} module.

@item 
bpo-38066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38066}: Hide internal asyncio.Stream methods: feed_eof(), feed_data(),
set_exception() and set_transport().

@item 
bpo-38059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38059}: inspect.py now uses sys.exit() instead of exit()

@item 
bpo-38049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38049}: Added command-line interface for the @ref{9,,ast} module.

@item 
bpo-37953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37953}: In @ref{10a,,typing}, improved the @code{__hash__} and @code{__eq__}
methods for @code{ForwardReferences}.

@item 
bpo-38026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38026}: Fixed @ref{6bc,,inspect.getattr_static()} used @code{isinstance} while
it should avoid dynamic lookup.

@item 
bpo-35923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35923}: Update @ref{ead,,importlib.machinery.BuiltinImporter} to use
@code{loader._ORIGIN} instead of a hardcoded value. Patch by Donghee Na.

@item 
bpo-38010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38010}: In @code{importlib.metadata} sync with @code{importlib_metadata}
0.20, clarifying behavior of @code{files()} and fixing issue where only one
requirement was returned for @code{requires()} on @code{dist-info} packages.

@item 
bpo-38006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38006}: weakref.WeakValueDictionary defines a local remove() function
used as callback for weak references. This function was created with a
closure. Modify the implementation to avoid the closure.

@item 
bpo-37995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37995}: Added the `indent' option to @ref{ae1,,ast.dump()} which allows it
to produce a multiline indented output.

@item 
bpo-34410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34410}: Fixed a crash in the @code{tee()} iterator when re-enter it.
RuntimeError is now raised in this case.

@item 
bpo-37140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37140}: Fix a ctypes regression of Python 3.8. When a ctypes.Structure
is passed by copy to a function, ctypes internals created a temporary
object which had the side effect of calling the structure finalizer
(__del__) twice. The Python semantics requires a finalizer to be called
exactly once. Fix ctypes internals to no longer call the finalizer twice.

@item 
bpo-37587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37587}: @code{_json.scanstring} is now up to 3x faster when there are many
backslash escaped characters in the JSON string.

@item 
bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834}: Prevent shutil.rmtree exception when built on non-Windows
system without fd system call support, like older versions of macOS.

@item 
bpo-10978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10978}: Semaphores and BoundedSemaphores can now release more than one
waiting thread at a time.

@item 
bpo-37972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37972}: Subscripts to the @code{unittest.mock.call} objects now receive
the same chaining mechanism as any other custom attributes, so that the
following usage no longer raises a @code{TypeError}:

@code{call().foo().__getitem__('bar')}

Patch by blhsing

@item 
bpo-37965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37965}: Fix C compiler warning caused by
distutils.ccompiler.CCompiler.has_function.

@item 
bpo-37964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37964}: Add @code{F_GETPATH} command to @ref{5d,,fcntl}.

@item 
bpo-37960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37960}: @code{repr()} of buffered and text streams now silences only
expected exceptions when get the value of "name" and "mode" attributes.

@item 
bpo-37961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37961}: Add a @code{total_nframe} field to the traces collected by the
tracemalloc module. This field indicates the original number of frames
before it was truncated.

@item 
bpo-37951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37951}: Most features of the subprocess module now work again in
subinterpreters. Only `preexec_fn' is restricted in subinterpreters.

@item 
bpo-36205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36205}: Fix the rusage implementation of time.process_time() to
correctly report the sum of the system and user CPU time.

@item 
bpo-37950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37950}: Fix @ref{ae1,,ast.dump()} when call with incompletely initialized
node.

@item 
bpo-34679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34679}: Restores instantiation of Windows IOCP event loops from the
non-main thread.

@item 
bpo-36917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36917}: Add default implementation of the
@ref{c63,,ast.NodeVisitor.visit_Constant()} method which emits a deprecation
warning and calls corresponding methods @code{visit_Num()}, @code{visit_Str()},
etc.

@item 
bpo-37798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37798}: Update test_statistics.py to verify that the statistics module
works well for both C and Python implementations. Patch by Donghee Na

@item 
bpo-26589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26589}: Added a new status code to the http module: 451
UNAVAILABLE_FOR_LEGAL_REASONS

@item 
bpo-37915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37915}: Fix a segmentation fault that appeared when comparing instances
of @code{datetime.timezone} and @code{datetime.tzinfo} objects. Patch by Pablo
Galindo.

@item 
bpo-32554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32554}: Deprecate having random.seed() call hash on arbitrary types.

@item 
bpo-9938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9938}: Add optional keyword argument @code{exit_on_error} for
@code{ArgumentParser}.

@item 
bpo-37851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37851}: The @ref{5c,,faulthandler} module no longer allocates its
alternative stack at Python startup. Now the stack is only allocated at
the first faulthandler usage.

@item 
bpo-32793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32793}: Fix a duplicated debug message when
@ref{1daf,,smtplib.SMTP.connect()} is called.

@item 
bpo-37885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37885}: venv: Don't generate unset variable warning on deactivate.

@item 
bpo-37868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37868}: Fix dataclasses.is_dataclass when given an instance that never
raises AttributeError in __getattr__.  That is, an object that returns
something for __dataclass_fields__ even if it's not a dataclass.

@item 
bpo-37811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37811}: Fix @code{socket} module's @code{socket.connect(address)} function
being unable to establish connection in case of interrupted system call.
The problem was observed on all OSes which @code{poll(2)} system call can
take only non-negative integers and -1 as a timeout value.

@item 
bpo-37863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37863}: Optimizations for Fraction.__hash__ suggested by Tim Peters.

@item 
bpo-21131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21131}: Fix @code{faulthandler.register(chain=True)} stack. faulthandler
now allocates a dedicated stack of @code{SIGSTKSZ*2} bytes, instead of just
@code{SIGSTKSZ} bytes. Calling the previous signal handler in faulthandler
signal handler uses more than @code{SIGSTKSZ} bytes of stack memory on some
platforms.

@item 
bpo-37798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37798}: Add C fastpath for statistics.NormalDist.inv_cdf() Patch by
Donghee Na

@item 
bpo-37804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37804}: Remove the deprecated method @code{threading.Thread.isAlive()}.
Patch by Donghee Na.

@item 
bpo-37819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37819}: Add Fraction.as_integer_ratio() to match the corresponding
methods in bool, int, float, and decimal.

@item 
bpo-14465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14465}: Add an xml.etree.ElementTree.indent() function for
pretty-printing XML trees. Contributed by Stefan Behnel.

@item 
bpo-37810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37810}: Fix @ref{3b,,difflib} @code{?} hint in diff output when dealing with
tabs.  Patch by Anthony Sottile.

@item 
bpo-37772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37772}: In @code{zipfile.Path}, when adding implicit dirs, ensure that
ancestral directories are added and that duplicates are excluded.

@item 
bpo-18578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18578}: Renamed and documented @code{test.bytecode_helper} as
@code{test.support.bytecode_helper}. Patch by Joannah Nanjekye.

@item 
bpo-37785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37785}: Fix xgettext warnings in @ref{7,,argparse}.

@item 
bpo-34488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34488}: @code{writelines()} method of @ref{10a4,,io.BytesIO} is now
slightly faster when many small lines are passed. Patch by Sergey
Fedoseev.

@item 
bpo-37449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37449}: @code{ensurepip} now uses @code{importlib.resources.read_binary()} to
read data instead of @code{pkgutil.get_data()}. Patch by Joannah Nanjekye.

@item 
bpo-28292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28292}: Mark calendar.py helper functions as being private.  The
follows PEP 8 guidance to maintain the style conventions in the module and
it addresses a known case of user confusion.

@item 
bpo-18049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18049}: Add definition of THREAD_STACK_SIZE for AIX in
Python/thread_pthread.h The default thread stacksize caused crashes with
the default recursion limit Patch by M Felt

@item 
bpo-37742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37742}: The logging.getLogger() API now returns the root logger when
passed the name 'root', whereas previously it returned a non-root logger
named 'root'. This could affect cases where user code explicitly wants a
non-root logger named 'root', or instantiates a logger using
logging.getLogger(__name__) in some top-level module called 'root.py'.

@item 
bpo-37738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37738}: Fix the implementation of curses @code{addch(str, color_pair)}:
pass the color pair to @code{setcchar()}, instead of always passing 0 as the
color pair.

@item 
bpo-37723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37723}: Fix performance regression on regular expression parsing with
huge character sets. Patch by Yann Vaginay.

@item 
bpo-35943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35943}: The function @ref{dac,,PyImport_GetModule()} now ensures any
module it returns is fully initialized. Patch by Joannah Nanjekye.

@item 
bpo-32178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32178}: Fix IndexError in @ref{3f,,email} package when trying to parse
invalid address fields starting with @code{:}.

@item 
bpo-37268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37268}: The @code{parser} module is deprecated and will be removed in
future versions of Python.

@item 
bpo-11953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11953}: Completing WSA* error codes in @ref{d1,,socket}.

@item 
bpo-37685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37685}: Fixed comparisons of @ref{bc3,,datetime.timedelta} and
@ref{12d5,,datetime.timezone}.

@item 
bpo-37697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37697}: Synchronize @code{importlib.metadata} with importlib_metadata 0.19@footnote{https://gitlab.com/python-devs/importlib_metadata/-/milestones/20},
improving handling of EGG-INFO files and fixing a crash when entry point
names contained colons.

@item 
bpo-37695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37695}: Correct @ref{12aa,,curses.unget_wch()} error message.  Patch by
Anthony Sottile.

@item 
bpo-37689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37689}: Add @code{is_relative_to()} in @code{PurePath} to determine
whether or not one path is relative to another.

@item 
bpo-29553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29553}: Fixed @ref{1db0,,argparse.ArgumentParser.format_usage()} for mutually
exclusive groups. Patch by Andrew Nester.

@item 
bpo-37691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37691}: Let math.dist() accept coordinates as sequences (or iterables)
rather than just tuples.

@item 
bpo-37685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37685}: Fixed @code{__eq__}, @code{__lt__} etc implementations in some
classes. They now return @ref{1a2,,NotImplemented} for unsupported type of
the other operand. This allows the other operand to play role (for example
the equality comparison with @ref{1db1,,ANY} will return
@code{True}).

@item 
bpo-37354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37354}: Make Activate.ps1 Powershell script static to allow for signing
it.

@item 
bpo-37664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37664}: Update wheels bundled with ensurepip (pip 19.2.3 and setuptools
41.2.0)

@item 
bpo-37663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37663}: Bring consistency to venv shell activation scripts by always
using __VENV_PROMPT__.

@item 
bpo-37642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37642}: Allowed the pure Python implementation of
@ref{12d5,,datetime.timezone} to represent sub-minute offsets close to
minimum and maximum boundaries, specifically in the ranges (23:59, 24:00)
and (-23:59, 24:00). Patch by Ngalim Siregar

@item 
bpo-36161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36161}: In @ref{b2,,posix}, use @code{ttyname_r} instead of @code{ttyname} for
thread safety.

@item 
bpo-36324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36324}: Make internal attributes for statistics.NormalDist() private.

@item 
bpo-37555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37555}: Fix @code{NonCallableMock._call_matcher} returning tuple instead
of @code{_Call} object when @code{self._spec_signature} exists. Patch by
Elizabeth Uselton

@item 
bpo-29446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29446}: Make @code{from tkinter import *} import only the expected
objects.

@item 
bpo-16970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16970}: Adding a value error when an invalid value in passed to nargs
Patch by Robert Leenders

@item 
bpo-34443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34443}: Exceptions from @ref{5a,,enum} now use the @code{__qualname} of the
enum class in the exception message instead of the @code{__name__}.

@item 
bpo-37491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37491}: Fix @code{IndexError} when parsing email headers with unexpectedly
ending bare-quoted string value. Patch by Abhilash Raj.

@item 
bpo-37587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37587}: Make json.loads faster for long strings. (Patch by Marco
Paolini)

@item 
bpo-18378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18378}: Recognize "UTF-8" as a valid value for LC_CTYPE in
locale._parse_localename.

@item 
bpo-37579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37579}: Return @ref{1a2,,NotImplemented} in Python implementation of
@code{__eq__} for @ref{bc3,,timedelta} and @ref{1fb,,time}
when the other object being compared is not of the same type to match C
implementation. Patch by Karthikeyan Singaravelan.

@item 
bpo-21478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21478}: Record calls to parent when autospecced object is attached to a
mock using @code{unittest.mock.attach_mock()}. Patch by Karthikeyan
Singaravelan.

@item 
bpo-37531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37531}: "python3 -m test -jN --timeout=TIMEOUT" now kills a worker
process if it runs longer than `TIMEOUT' seconds.

@item 
bpo-37482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37482}: Fix serialization of display name in originator or destination
address fields with both encoded words and special chars.

@item 
bpo-36993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36993}: Improve error reporting for corrupt zip files with bad zip64
extra data. Patch by Daniel Hillier.

@item 
bpo-37502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37502}: pickle.loads() no longer raises TypeError when the buffers
argument is set to None

@item 
bpo-37520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37520}: Correct behavior for zipfile.Path.parent when the path object
identifies a subdirectory.

@item 
bpo-18374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18374}: Fix the @code{.col_offset} attribute of nested @ref{1db2,,ast.BinOp}
instances which had a too large value in some situations.

@item 
bpo-37424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37424}: Fixes a possible hang when using a timeout on
@code{subprocess.run()} while capturing output.  If the child process spawned
its own children or otherwise connected its stdout or stderr handles with
another process, we could hang after the timeout was reached and our child
was killed when attempting to read final output from the pipes.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: Fix @code{multiprocessing.util.get_temp_dir()} finalizer: clear
also the 'tempdir' configuration of the current process, so next call to
@code{get_temp_dir()} will create a new temporary directory, rather than
reusing the removed temporary directory.

@item 
bpo-37481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37481}: The distutils @code{bdist_wininst} command is deprecated in Python
3.8, use @code{bdist_wheel} (wheel packages) instead.

@item 
bpo-37479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37479}: When @code{Enum.__str__} is overridden in a derived class, the
override will be used by @code{Enum.__format__} regardless of whether mixin
classes are present.

@item 
bpo-37440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37440}: http.client now enables TLS 1.3 post-handshake authentication
for default context or if a cert_file is passed to HTTPSConnection.

@item 
bpo-37437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37437}: Update vendorized expat version to 2.2.7.

@item 
bpo-37428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37428}: SSLContext.post_handshake_auth = True no longer sets
SSL_VERIFY_POST_HANDSHAKE verify flag for client connections. Although the
option is documented as ignored for clients, OpenSSL implicitly enables
cert chain validation when the flag is set.

@item 
bpo-37420@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37420}: @ref{1326,,os.sched_setaffinity()} now correctly handles errors that
arise during iteration over its @code{mask} argument. Patch by Brandt Bucher.

@item 
bpo-37412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37412}: The @ref{c82,,os.getcwdb()} function now uses the UTF-8 encoding on
Windows, rather than the ANSI code page: see 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} for the rationale.
The function is no longer deprecated on Windows.

@item 
bpo-37406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37406}: The sqlite3 module now raises TypeError, rather than
ValueError, if operation argument type is not str: execute(),
executemany() and calling a connection.

@item 
bpo-29412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29412}: Fix IndexError in parsing a header value ending unexpectedly.
Patch by Abhilash Raj.

@item 
bpo-36546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36546}: The `dist' argument for statistics.quantiles() is now
positional only. The current name doesn't reflect that the argument can be
either a dataset or a distribution.  Marking the parameter as positional
avoids confusion and makes it possible to change the name later.

@item 
bpo-37394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37394}: Fix a bug that was causing the @ref{bb,,queue} module to fail if
the accelerator module was not available. Patch by Pablo Galindo.

@item 
bpo-37376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37376}: @ref{b3,,pprint} now has support for
@ref{4e5,,types.SimpleNamespace}. Patch by Carl Bordum Hansen.

@item 
bpo-26967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26967}: An @ref{1bd,,ArgumentParser} with
@code{allow_abbrev=False} no longer disables grouping of short flags, such as
@code{-vv}, but only disables abbreviation of long flags as documented. Patch
by Zac Hatfield-Dodds.

@item 
bpo-37212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37212}: @ref{1db3,,unittest.mock.call()} now preserves the order of keyword
arguments in repr output. Patch by Karthikeyan Singaravelan.

@item 
bpo-37372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37372}: Fix error unpickling datetime.time objects from Python 2 with
seconds>=24. Patch by Justin Blanchard.

@item 
bpo-37345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37345}: Add formal support for UDPLITE sockets. Support was present
before, but it is now easier to detect support with @code{hasattr(socket,
'IPPROTO_UDPLITE')} and there are constants defined for each of the
values needed: @code{socket.IPPROTO_UDPLITE}, @code{UDPLITE_SEND_CSCOV}, and
@code{UDPLITE_RECV_CSCOV}. Patch by Gabe Appleton.

@item 
bpo-37358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37358}: Optimized @code{functools.partial} by using vectorcall.

@item 
bpo-37347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37347}: @ref{5a8,,sqlite3.Connection.create_aggregate()},
@ref{5a7,,sqlite3.Connection.create_function()},
@ref{5a9,,sqlite3.Connection.set_authorizer()},
@ref{5aa,,sqlite3.Connection.set_progress_handler()}
@ref{5ab,,sqlite3.Connection.set_trace_callback()} methods lead to segfaults if
some of these methods are called twice with an equal object but not the
same. Now callbacks are stored more carefully. Patch by Aleksandr Balezin.

@item 
bpo-37163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37163}: The `obj' argument of @ref{1a6a,,dataclasses.replace()} is
positional-only now.

@item 
bpo-37085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37085}: Add the optional Linux SocketCAN Broadcast Manager constants,
used as flags to configure the BCM behaviour, in the socket module.  Patch
by Karl Ding.

@item 
bpo-37328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37328}: @code{HTMLParser.unescape} is removed.  It was undocumented and
deprecated since Python 3.4.

@item 
bpo-37305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37305}: Add .webmanifest -> application/manifest+json to list of
recognized file types and content type headers

@item 
bpo-37320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37320}: @code{aifc.openfp()} alias to @code{aifc.open()}, @code{sunau.openfp()}
alias to @code{sunau.open()}, and @code{wave.openfp()} alias to @code{wave.open()}
have been removed. They were deprecated since Python 3.7.

@item 
bpo-37315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37315}: Deprecated accepting floats with integral value (like @code{5.0})
in @ref{b41,,math.factorial()}.

@item 
bpo-37312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37312}: @code{_dummy_thread} and @code{dummy_threading} modules have been
removed. These modules were deprecated since Python 3.7 which requires
threading support.

@item 
bpo-33972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33972}: Email with single part but content-type set to @code{multipart/*}
doesn't raise AttributeError anymore.

@item 
bpo-37280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37280}: Use threadpool for reading from file for sendfile fallback
mode.

@item 
bpo-37279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37279}: Fix asyncio sendfile support when sendfile sends extra data in
fallback mode.

@item 
bpo-19865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19865}: @ref{1db4,,ctypes.create_unicode_buffer()} now also supports non-BMP
characters on platforms with 16-bit @code{wchar_t} (for example,
Windows and AIX).

@item 
bpo-37266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37266}: In a subinterpreter, spawning a daemon thread now raises an
exception. Daemon threads were never supported in subinterpreters.
Previously, the subinterpreter finalization crashed with a Python fatal
error if a daemon thread was still running.

@item 
bpo-37210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37210}: Allow pure Python implementation of @ref{ab,,pickle} to work even
when the C @code{_pickle} module is unavailable.

@item 
bpo-21872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21872}: Fix @ref{8e,,lzma}: module decompresses data incompletely. When
decompressing a FORMAT_ALONE format file, and it doesn't have the end
marker, sometimes the last one to dozens bytes can't be output. Patch by
Ma Lin.

@item 
bpo-35922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35922}: Fix @code{RobotFileParser.crawl_delay()} and
@code{RobotFileParser.request_rate()} to return @code{None} rather than raise
@ref{5f0,,AttributeError} when no relevant rule is defined in the robots.txt
file.  Patch by Rémi Lapeyre.

@item 
bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766}: Change the format of feature_version to be a (major, minor)
tuple.

@item 
bpo-36607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36607}: Eliminate @ref{244,,RuntimeError} raised by
@ref{b4f,,asyncio.all_tasks()} if internal tasks weak set is changed by another
thread during iteration.

@item 
bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748}: @code{_pyio.IOBase} destructor now does nothing if getting
the @code{closed} attribute fails to better mimic @code{_io.IOBase}
finalizer.

@item 
bpo-36402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36402}: Fix a race condition at Python shutdown when waiting for
threads. Wait until the Python thread state of all non-daemon threads get
deleted (join all non-daemon threads), rather than just wait until
non-daemon Python threads complete.

@item 
bpo-37206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37206}: Default values which cannot be represented as Python objects no
longer improperly represented as @code{None} in function signatures.

@item 
bpo-37111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37111}: Added @code{encoding} and @code{errors} keyword parameters to
@code{logging.basicConfig}.

@item 
bpo-12144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12144}: Ensure cookies with @code{expires} attribute are handled in
@code{CookieJar.make_cookies()}.

@item 
bpo-34886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34886}: Fix an unintended ValueError from @ref{d7f,,subprocess.run()} when
checking for conflicting `input' and `stdin' or `capture_output' and
`stdout' or `stderr' args when they were explicitly provided but with
@code{None} values within a passed in @code{**kwargs} dict rather than as passed
directly by name. Patch contributed by Rémi Lapeyre.

@item 
bpo-37173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37173}: The exception message for @code{inspect.getfile()} now correctly
reports the passed class rather than the builtins module.

@item 
bpo-37178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37178}: Give math.perm() a one argument form that means the same as
math.factorial().

@item 
bpo-37178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37178}: For math.perm(n, k), let k default to n, giving the same result
as factorial.

@item 
bpo-37165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37165}: Converted _collections._count_elements to use the Argument
Clinic.

@item 
bpo-34767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34767}: Do not always create a @ref{7f4,,collections.deque} in
@ref{c66,,asyncio.Lock}.

@item 
bpo-37158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37158}: Speed-up statistics.fmean() by switching from a function to a
generator.

@item 
bpo-34282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34282}: Remove @code{Enum._convert} method, deprecated in 3.8.

@item 
bpo-37150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37150}: @code{argparse._ActionsContainer.add_argument} now throws error,
if someone accidentally pass FileType class object instead of instance of
FileType as @code{type} argument.

@item 
bpo-28724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28724}: The socket module now has the @ref{b2d,,socket.send_fds()} and
@code{socket.recv.fds()} methods. Contributed by Joannah Nanjekye, Shinya
Okano and Victor Stinner.

@item 
bpo-35621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35621}: Support running asyncio subprocesses when execution event loop
in a thread on UNIX.

@item 
bpo-36520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36520}: Lengthy email headers with UTF-8 characters are now properly
encoded when they are folded. Patch by Jeffrey Kintscher.

@item 
bpo-30835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30835}: Fixed a bug in email parsing where a message with invalid bytes
in content-transfer-encoding of a multipart message can cause an
AttributeError. Patch by Andrew Donnellan.

@item 
bpo-31163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31163}: pathlib.Path instance's rename and replace methods now return
the new Path instance.

@item 
bpo-25068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25068}: @ref{1db5,,urllib.request.ProxyHandler} now lowercases the keys of
the passed dictionary.

@item 
bpo-26185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26185}: Fix @ref{1c1,,repr()} on empty @code{ZipInfo} object. Patch by
Mickaël Schoentgen.

@item 
bpo-21315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21315}: Email headers containing RFC2047 encoded words are parsed
despite the missing whitespace, and a defect registered. Also missing
trailing whitespace after encoded words is now registered as a defect.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Port test_datetime to VxWorks: skip zoneinfo tests on VxWorks

@item 
bpo-35805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35805}: Add parser for Message-ID header and add it to default
HeaderRegistry. This should prevent folding of Message-ID using RFC 2048
encoded words.

@item 
bpo-36871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36871}: Ensure method signature is used instead of constructor
signature of a class while asserting mock object against method calls.
Patch by Karthikeyan Singaravelan.

@item 
bpo-35070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35070}: posix.getgrouplist() now works correctly when the user belongs
to NGROUPS_MAX supplemental groups. Patch by Jeffrey Kintscher.

@item 
bpo-31783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31783}: Fix race condition in ThreadPoolExecutor when worker threads
are created during interpreter shutdown.

@item 
bpo-36582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36582}: Fix @code{UserString.encode()} to correctly return @code{bytes}
rather than a @code{UserString} instance.

@item 
bpo-32424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32424}: Deprecate xml.etree.ElementTree.Element.copy() in favor of
copy.copy().

Patch by Gordon P. Hemsley

@item 
bpo-36564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36564}: Fix infinite loop in email header folding logic that would be
triggered when an email policy's max_line_length is not long enough to
include the required markup and any values in the message. Patch by Paul
Ganssle

@item 
bpo-36543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36543}: Removed methods Element.getchildren(), Element.getiterator()
and ElementTree.getiterator() and the xml.etree.cElementTree module.

@item 
bpo-36409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36409}: Remove the old plistlib API deprecated in Python 3.4

@item 
bpo-36302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36302}: distutils sorts source file lists so that Extension .so files
build more reproducibly by default

@item 
bpo-36250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36250}: Ignore @code{ValueError} from @code{signal} with @code{interaction} in
non-main thread.

@item 
bpo-36046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36046}: Added @code{user}, @code{group} and @code{extra_groups} parameters to
the subprocess.Popen constructor. Patch by Patrick McLean.

@item 
bpo-32627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32627}: Fix compile error when @code{_uuid} headers conflicting included.

@item 
bpo-35800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35800}: Deprecate @code{smtpd.MailmanProxy} ready for future removal.

@item 
bpo-35168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35168}: @ref{1db6,,shlex.shlex.punctuation_chars} is now a read-only
property.

@item 
bpo-8538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8538}: Add support for boolean actions like @code{--foo} and @code{--no-foo}
to argparse. Patch contributed by Rémi Lapeyre.

@item 
bpo-20504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20504}: Fixes a bug in @code{cgi} module when a multipart/form-data
request has no @code{Content-Length} header.

@item 
bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}: The abstract base classes in @ref{1f,,collections.abc} no longer
are exposed in the regular @ref{1e,,collections} module.

@item 
bpo-11122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11122}: Distutils won't check for rpmbuild in specified paths only.

@item 
bpo-34775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34775}: Division handling of PurePath now returns NotImplemented
instead of raising a TypeError when passed something other than an
instance of str or PurePath. Patch by Roger Aiudi.

@item 
bpo-34749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34749}: @ref{19a4,,binascii.a2b_base64()} is now up to 2 times faster. Patch
by Sergey Fedoseev.

@item 
bpo-34519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34519}: Add additional aliases for HP Roman 8. Patch by Michael Osipov.

@item 
bpo-28009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28009}: Fix uuid.getnode() on platforms with '.' as MAC Addr delimiter
as well fix for MAC Addr format that omits a leading 0 in MAC Addr values.
Currently, AIX is the only know platform with these settings. Patch by
Michael Felt.

@item 
bpo-30618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30618}: Add @ref{b19,,readlink()}. Patch by Girts Folkmanis.

@item 
bpo-32498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32498}: Made @ref{1afb,,urllib.parse.unquote()} accept bytes in addition to
strings. Patch by Stein Karlsen.

@item 
bpo-33348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33348}: lib2to3 now recognizes expressions after @code{*} and @code{**} like
in @code{f(*[] or [])}.

@item 
bpo-32689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32689}: Update @ref{c51,,shutil.move()} function to allow for Path objects
to be used as source argument. Patch by Emily Morehouse and Maxwell
"5.13b" McKinnon.

@item 
bpo-32820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32820}: Added @code{__format__} to IPv4 and IPv6 classes.  Always outputs
a fully zero-padded string. Supports b/x/n modifiers (bin/hex/native
format). Native format for IPv4 is bin, native format for IPv6 is hex.
Also supports '#' and '_' modifiers.

@item 
bpo-27657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27657}: Fix urllib.parse.urlparse() with numeric paths. A string like
"path:80" is no longer parsed as a path but as a scheme ("path") and a
path ("80").

@item 
bpo-4963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4963}: Fixed non-deterministic behavior related to mimetypes extension
mapping and module reinitialization.
@end itemize

@node ドキュメント<51>,テスト<49>,ライブラリ<157>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id698}@anchor{1db7}
@subsubsection ドキュメント



@itemize -

@item 
bpo-21767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21767}: Explicitly mention abc support in functools.singledispatch

@item 
bpo-38816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38816}: Provides more details about the interaction between
@code{fork()} and CPython's runtime, focusing just on the C-API.  This
includes cautions about where @code{fork()} should and shouldn't be
called.

@item 
bpo-38351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38351}: Modernize @ref{3f,,email} examples from %-formatting to f-strings.

@item 
bpo-38778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38778}: Document the fact that @ref{244,,RuntimeError} is raised if
@ref{4b5,,os.fork()} is called in a subinterpreter.

@item 
bpo-38592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38592}: Add Brazilian Portuguese to the language switcher at Python
Documentation website.

@item 
bpo-38294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38294}: Add list of no-longer-escaped chars to re.escape documentation

@item 
bpo-38053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38053}: Modernized the plistlib documentation

@item 
bpo-26868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26868}: Fix example usage of @ref{60b,,PyModule_AddObject()} to properly
handle errors.

@item 
bpo-36797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36797}: Fix a dead link in the distutils API Reference.

@item 
bpo-37977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37977}: Warn more strongly and clearly about pickle insecurity

@item 
bpo-37979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37979}: Added a link to dateutil.parser.isoparse in the
datetime.fromisoformat documentation. Patch by Paul Ganssle

@item 
bpo-12707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12707}: Deprecate info(), geturl(), getcode() methods in favor of the
headers, url, and status properties, respectively, for HTTPResponse and
addinfourl. Also deprecate the code attribute of addinfourl in favor of
the status attribute. Patch by Ashwin Ramaswami

@item 
bpo-37937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37937}: Mention @code{frame.f_trace} in @ref{2e1,,sys.settrace()} docs.

@item 
bpo-37878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37878}: Make @ref{1db8,,PyThreadState_DeleteCurrent()} Internal.

@item 
bpo-37759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37759}: Beginning edits to Whatsnew 3.8

@item 
bpo-37726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37726}: Stop recommending getopt in the tutorial for command line
argument parsing and promote argparse.

@item 
bpo-32910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32910}: Remove implementation-specific behaviour of how venv's
Deactivate works.

@item 
bpo-37256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37256}: Fix wording of arguments for @code{Request} in
@ref{111,,urllib.request}

@item 
bpo-37284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37284}: Add a brief note to indicate that any new
@code{sys.implementation} required attributes must go through the PEP
process.

@item 
bpo-30088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30088}: Documented that @ref{65e,,mailbox.Maildir} constructor doesn't
attempt to verify the maildir folder layout correctness. Patch by
Sviatoslav Sydorenko.

@item 
bpo-37521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37521}: Fix @code{importlib} examples to insert any newly created modules
via importlib.util.module_from_spec() immediately into sys.modules instead
of after calling loader.exec_module().

Thanks to Benjamin Mintz for finding the bug.

@item 
bpo-37456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37456}: Slash ('/') is now part of syntax.

@item 
bpo-37487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37487}: Fix PyList_GetItem index description to include 0.

@item 
bpo-37149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37149}: Replace the dead link to the Tkinter 8.5 reference by John
Shipman, New Mexico Tech, with a link to the archive.org copy.

@item 
bpo-37478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37478}: Added possible exceptions to the description of os.chdir().

@item 
bpo-34903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34903}: Documented that in @ref{1950,,datetime.datetime.strptime()}, the
leading zero in some two-digit formats is optional. Patch by Mike Gleen.

@item 
bpo-36260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36260}: Add decompression pitfalls to zipfile module documentation.

@item 
bpo-37004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37004}: In the documentation for difflib, a note was added explicitly
warning that the results of SequenceMatcher's ratio method may depend on
the order of the input strings.

@item 
bpo-36960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36960}: Restructured the @ref{34,,datetime} docs in the interest of making
them more user-friendly and improving readability. Patch by Brad Solomon.

@item 
bpo-36487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36487}: Make C-API docs clear about what the "main" interpreter is.

@item 
bpo-23460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23460}: The documentation for decimal string formatting using the
@code{:g} specifier has been updated to reflect the correct exponential
notation cutoff point. Original patch contributed by Tuomas Suutari.

@item 
bpo-35803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35803}: Document and test that @code{tempfile} functions may accept a
@ref{5a1,,path-like object} for the @code{dir} argument.  Patch by Anthony
Sottile.

@item 
bpo-33944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33944}: Added a note about the intended use of code in .pth files.

@item 
bpo-34293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34293}: Fix the Doc/Makefile regarding PAPER environment variable and
PDF builds

@item 
bpo-25237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25237}: Add documentation for tkinter modules
@end itemize

@node テスト<49>,ビルド<57>,ドキュメント<51>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id699}@anchor{1db9}
@subsubsection テスト



@itemize -

@item 
bpo-38614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38614}: Fix test_communicate() of test_asyncio.test_subprocess: use
@code{support.LONG_TIMEOUT} (5 minutes), instead of just 1 minute.

@item 
bpo-38614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38614}: Add timeout constants to @ref{ea,,test.support}:
@ref{1d9c,,LOOPBACK_TIMEOUT},
@ref{1d9d,,INTERNET_TIMEOUT},
@ref{1c63,,SHORT_TIMEOUT} and
@ref{1d9e,,LONG_TIMEOUT}.

@item 
bpo-38502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38502}: test.regrtest now uses process groups in the multiprocessing
mode (-jN command line option) if process groups are available: if
@ref{1dba,,os.setsid()} and @ref{1dbb,,os.killpg()} functions are available.

@item 
bpo-35998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35998}: Fix a race condition in test_asyncio.test_start_tls_server_1().
Previously, there was a race condition between the test main() function
which replaces the protocol and the test ServerProto protocol which sends
ANSWER once it gets HELLO. Now, only the test main() function is
responsible to send data, ServerProto no longer sends data.

@item 
bpo-38470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38470}: Fix @code{test_compileall.test_compile_dir_maxlevels()} on Windows
without long path support: only create 3 subdirectories instead of between
20 and 100 subdirectories.

@item 
bpo-37531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37531}: On timeout, regrtest no longer attempts to call
@code{popen.communicate()} again: it can hang until all child processes using
stdout and stderr pipes completes. Kill the worker process and ignores its
output. Change also the faulthandler timeout of the main process from 1
minute to 5 minutes, for Python slowest buildbots.

@item 
bpo-38239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38239}: Fix test_gdb for Link Time Optimization (LTO) builds.

@item 
bpo-38275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38275}: test_ssl now handles disabled TLS/SSL versions better.
OpenSSL's crypto policy and run-time settings are recognized and tests for
disabled versions are skipped. Tests also accept more TLS minimum_versions
for platforms that override OpenSSL's default with strict settings.

@item 
bpo-38271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38271}: The private keys for test_ssl were encrypted with 3DES in
traditional PKCS#5 format. 3DES and the digest algorithm of PKCS#5 are
blocked by some strict crypto policies. Use PKCS#8 format with AES256
encryption instead.

@item 
bpo-38270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38270}: test.support now has a helper function to check for
availability of a hash digest function. Several tests are refactored avoid
MD5 and use SHA256 instead. Other tests are marked to use MD5 and skipped
when MD5 is disabled.

@item 
bpo-37123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37123}: Multiprocessing test test_mymanager() now also expects
-SIGTERM, not only exitcode 0. BaseManager._finalize_manager() sends
SIGTERM to the manager process if it takes longer than 1 second to stop,
which happens on slow buildbots.

@item 
bpo-38212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38212}: Multiprocessing tests: increase
test_queue_feeder_donot_stop_onexc() timeout from 1 to 60 seconds.

@item 
bpo-38117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38117}: Test with OpenSSL 1.1.1d

@item 
bpo-38018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38018}: Increase code coverage for multiprocessing.shared_memory.

@item 
bpo-37805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37805}: Add tests for json.dump(..., skipkeys=True). Patch by Donghee
Na.

@item 
bpo-37531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37531}: Enhance regrtest multiprocess timeout: write a message when
killing a worker process, catch popen.kill() and popen.wait() exceptions,
put a timeout on the second call to popen.communicate().

@item 
bpo-37876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37876}: Add tests for ROT-13 codec.

@item 
bpo-36833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36833}: Added tests for @code{PyDateTime_@var{xxx}_GET_@var{xxx}()} macros of
the C API of the @ref{34,,datetime} module. Patch by Joannah Nanjekye.

@item 
bpo-37558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37558}: Fix test_shared_memory_cleaned_after_process_termination name
handling

@item 
bpo-37526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37526}: Add @code{test.support.catch_threading_exception()}: context
manager catching @ref{176,,threading.Thread} exception using
@ref{a4b,,threading.excepthook()}.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_concurrent_futures now explicitly stops the ForkServer
instance if it's running.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: multiprocessing tests now stop the ForkServer instance if it's
running: close the "alive" file descriptor to ask the server to stop and
then remove its UNIX address.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_distutils.test_build_ext() is now able to remove the
temporary directory on Windows: don't import the newly built C extension
("xx") in the current process, but test it in a separated process.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_concurrent_futures now cleans up multiprocessing to remove
immediately temporary directories created by
multiprocessing.util.get_temp_dir().

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_winconsoleio doesn't leak a temporary file anymore: use
tempfile.TemporaryFile() to remove it when the test completes.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: multiprocessing tests now explicitly call @code{_run_finalizers()}
to immediately remove temporary directories created by tests.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: urllib.request tests now call
@ref{1dbc,,urlcleanup()} to remove temporary files created by
@code{urlretrieve()} tests and to clear the @code{_opener} global variable set
by @code{urlopen()} and functions calling indirectly @code{urlopen()}.

@item 
bpo-37472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37472}: Remove @code{Lib/test/outstanding_bugs.py}.

@item 
bpo-37199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37199}: Fix test failures when IPv6 is unavailable or disabled.

@item 
bpo-19696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19696}: Replace deprecated method "random.choose" with "random.choice"
in "test_pkg_import.py".

@item 
bpo-37335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37335}: Remove no longer necessary code from c locale coercion tests

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: Fix test_shutil to no longer leak temporary files.

@item 
bpo-37411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37411}: Fix test_wsgiref.testEnviron() to no longer depend on the
environment variables (don't fail if "X" variable is set).

@item 
bpo-37400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37400}: Fix test_os.test_chown(): use os.getgroups() rather than
grp.getgrall() to get groups. Rename also the test to test_chown_gid().

@item 
bpo-37359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37359}: Add --cleanup option to python3 -m test to remove
@code{test_python_*} directories of previous failed jobs. Add "make
cleantest" to run @code{python3 -m test --cleanup}.

@item 
bpo-37362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37362}: test_gdb no longer fails if it gets an "unexpected" message on
stderr: it now ignores stderr. The purpose of test_gdb is to test that
python-gdb.py commands work as expected, not to test gdb.

@item 
bpo-35998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35998}: Avoid TimeoutError in test_asyncio: test_start_tls_server_1()

@item 
bpo-37278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37278}: Fix test_asyncio ProactorLoopCtrlC: join the thread to prevent
leaking a running thread and leaking a reference.

@item 
bpo-37261@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37261}: Fix @ref{1dbd,,test.support.catch_unraisable_exception()}: its
__exit__() method now ignores unraisable exception raised when clearing
its @code{unraisable} attribute.

@item 
bpo-37069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37069}: regrtest now uses @ref{507,,sys.unraisablehook()} to mark a test as
"environment altered" (ENV_CHANGED) if it emits an "unraisable exception".
Moreover, regrtest logs a warning in this case.

Use @code{python3 -m test --fail-env-changed} to catch unraisable exceptions
in tests.

@item 
bpo-37252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37252}: Fix assertions in @code{test_close} and
@code{test_events_mask_overflow} devpoll tests.

@item 
bpo-37169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37169}: Rewrite @code{_PyObject_IsFreed()} unit tests.

@item 
bpo-37153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37153}: @code{test_venv.test_multiprocessing()} now explicitly calls
@code{pool.terminate()} to wait until the pool completes.

@item 
bpo-34001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34001}: Make test_ssl pass with LibreSSL. LibreSSL handles minimum and
maximum TLS version differently than OpenSSL.

@item 
bpo-36919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36919}: Make @code{test_source_encoding.test_issue2301} implementation
independent. The test will work now for both CPython and IronPython.

@item 
bpo-30202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30202}: Update @code{test.test_importlib.test_abc} to test
@code{find_spec()}.

@item 
bpo-28009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28009}: Modify the test_uuid logic to test when a program is available
AND can be used to obtain a MACADDR as basis for an UUID. Patch by M. Felt

@item 
bpo-34596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34596}: Fallback to a default reason when @ref{1dbe,,unittest.skip()} is
uncalled. Patch by Naitree Zhu.
@end itemize

@node ビルド<57>,Windows<50>,テスト<49>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id700}@anchor{1dbf}
@subsubsection ビルド



@itemize -

@item 
bpo-38809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38809}: On Windows, build scripts will now recognize and use python.exe
from an active virtual env.

@item 
bpo-38684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38684}: Fix _hashlib build when Blake2 is disabled, but OpenSSL
supports it.

@item 
bpo-38468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38468}: Misc/python-config.in now uses @code{getvar()} for all still
existing @code{sysconfig.get_config_var()} calls. Patch by Joannah Nanjekye.

@item 
bpo-37415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37415}: Fix stdatomic.h header check for ICC compiler: the ICC
implementation lacks atomic_uintptr_t type which is needed by Python.

@item 
bpo-38301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38301}: In Solaris family, we must be sure to use @code{-D_REENTRANT}.
Patch by Jesús Cea Avión.

@item 
bpo-36002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36002}: Locate @code{llvm-profdata} and @code{llvm-ar} binaries using
@code{AC_PATH_TOOL} rather than @code{AC_PATH_TARGET_TOOL}.

@item 
bpo-37936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37936}: The @code{.gitignore} file systematically keeps "rooted", with
a non-trailing slash, all the rules that are meant to apply to files in a
specific place in the repo.  Previously, when the intended file to ignore
happened to be at the root of the repo, we'd most often accidentally also
ignore files and directories with the same name anywhere in the tree.

@item 
bpo-37760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37760}: The @code{Tools/unicode/makeunicodedata.py} script, which is
used for converting information from the Unicode Character Database into
generated code and data used by the methods of @ref{169,,str} and by the
@ref{10b,,unicodedata} module, now handles each character's data as a
@code{dataclass} with named attributes, rather than a length-18 list of
different fields.

@item 
bpo-37936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37936}: The @code{.gitignore} file no longer applies to any files that
are in fact tracked in the Git repository.  Patch by Greg Price.

@item 
bpo-37725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37725}: Change "clean" makefile target to also clean the program guided
optimization (PGO) data.  Previously you would have to use "make clean"
and "make profile-removal", or "make clobber".

@item 
bpo-37707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37707}: Mark some individual tests to skip when --pgo is used.  The
tests marked increase the PGO task time significantly and likely don't
help improve optimization of the final executable.

@item 
bpo-36044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36044}: Reduce the number of unit tests run for the PGO generation
task.  This speeds up the task by a factor of about 15x.  Running the full
unit test suite is slow.  This change may result in a slightly less
optimized build since not as many code branches will be executed.  If you
are willing to wait for the much slower build, the old behavior can be
restored using './configure [..] PROFILE_TASK="-m test --pgo-extended"'.
We make no guarantees as to which PGO task set produces a faster build.
Users who care should run their own relevant benchmarks as results can
depend on the environment, workload, and compiler tool chain.

@item 
bpo-37468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37468}: @code{make install} no longer installs @code{wininst-*.exe} files
used by distutils bdist_wininst: bdist_wininst only works on Windows.

@item 
bpo-37189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37189}: Many @code{PyRun_@var{XXX}()} functions like
@ref{1dc0,,PyRun_String()} were no longer exported in @code{libpython38.dll} by
mistake. Export them again to fix the ABI compatibility.

@item 
bpo-25361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25361}: Enables use of SSE2 instructions in Windows 32-bit build.

@item 
bpo-36210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36210}: Update optional extension module detection for AIX. ossaudiodev
and spwd are not applicable for AIX, and are no longer reported as
missing. 3rd-party packaging of ncurses (with ASIS support) conflicts with
officially supported AIX curses library, so configure AIX to use
libcurses.a. However, skip trying to build _curses_panel.

patch by M Felt
@end itemize

@node Windows<50>,macOS<39>,ビルド<57>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id701}@anchor{1dc1}
@subsubsection Windows



@itemize -

@item 
bpo-38589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38589}: Fixes HTML Help shortcut when Windows is not installed to C
drive

@item 
bpo-38453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38453}: Ensure ntpath.realpath() correctly resolves relative paths.

@item 
bpo-38519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38519}: Restores the internal C headers that were missing from the
nuget.org and Microsoft Store packages.

@item 
bpo-38492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38492}: Remove @code{pythonw.exe} dependency on the Microsoft C++ runtime.

@item 
bpo-38344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38344}: Fix error message in activate.bat

@item 
bpo-38359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38359}: Ensures @code{pyw.exe} launcher reads correct registry key.

@item 
bpo-38355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38355}: Fixes @code{ntpath.realpath} failing on @code{sys.executable}.

@item 
bpo-38117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38117}: Update bundled OpenSSL to 1.1.1d

@item 
bpo-38092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38092}: Reduce overhead when using multiprocessing in a Windows virtual
environment.

@item 
bpo-38133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38133}: Allow py.exe launcher to locate installations from the
Microsoft Store and improve display of active virtual environments.

@item 
bpo-38114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38114}: The @code{pip.ini} is no longer included in the Nuget package.

@item 
bpo-32592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32592}: Set Windows 8 as the minimum required version for API support

@item 
bpo-36634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36634}: @ref{4db,,os.cpu_count()} now returns active processors rather than
maximum processors.

@item 
bpo-36634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36634}: venv activate.bat now works when the existing variables contain
double quote characters.

@item 
bpo-38081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38081}: Prevent error calling @ref{262,,os.path.realpath()} on @code{'NUL'}.

@item 
bpo-38087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38087}: Fix case sensitivity in test_pathlib and test_ntpath.

@item 
bpo-38088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38088}: Fixes distutils not finding vcruntime140.dll with only the v142
toolset installed.

@item 
bpo-37283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37283}: Ensure command-line and unattend.xml setting override
previously detected states in Windows installer.

@item 
bpo-38030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38030}: Fixes @ref{26d,,os.stat()} failing for block devices on Windows

@item 
bpo-38020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38020}: Fixes potential crash when calling @ref{b1a,,os.readlink()} (or
indirectly through @ref{262,,realpath()}) on a file that is not a
supported link.

@item 
bpo-37705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37705}: Improve the implementation of @code{winerror_to_errno()}.

@item 
bpo-37549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37549}: @ref{1dc2,,os.dup()} no longer fails for standard streams on Windows
7.

@item 
bpo-1311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1311}: The @code{nul} file on Windows now returns True from
@ref{c03,,exists()} and a valid result from @ref{26d,,os.stat()} with
@code{S_IFCHR} set.

@item 
bpo-9949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9949}: Enable support for following symlinks in @code{os.realpath()}.

@item 
bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834}: Treat all name surrogate reparse points on Windows in
@ref{6c8,,os.lstat()} and other reparse points as regular files in
@ref{26d,,os.stat()}.

@item 
bpo-36266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36266}: Add the module name in the formatted error message when DLL
load fail happens during module import in
@code{_PyImport_FindSharedFuncptrWindows()}. Patch by Srinivas Nyayapati.

@item 
bpo-25172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25172}: Trying to import the @code{crypt} module on Windows will
result in an @ref{65b,,ImportError} with a message explaining that the module
isn't supported on Windows. On other platforms, if the underlying
@code{_crypt} module is not available, the ImportError will include a message
explaining the problem.

@item 
bpo-37778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37778}: Fixes the icons used for file associations to the Microsoft
Store package.

@item 
bpo-37734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37734}: Fix use of registry values to launch Python from Microsoft
Store app.

@item 
bpo-37702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37702}: Fix memory leak on Windows in creating an SSLContext object or
running @code{urllib.request.urlopen('https://...')}.

@item 
bpo-37672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37672}: Switch Windows Store package's pip to use bundled
@code{pip.ini} instead of 
@geindex PIP_USER
@geindex 環境変数; PIP_USER
@code{PIP_USER} variable.

@item 
bpo-10945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10945}: Officially drop support for creating bdist_wininst installers
on non-Windows systems.

@item 
bpo-37445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37445}: Include the @code{FORMAT_MESSAGE_IGNORE_INSERTS} flag in
@code{FormatMessageW()} calls.

@item 
bpo-37369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37369}: Fixes path for @ref{3ed,,sys.executable} when running from the
Microsoft Store.

@item 
bpo-37380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37380}: Don't collect unfinished processes with @code{subprocess._active}
on Windows to cleanup later. Patch by Ruslan Kuprieiev.

@item 
bpo-37351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37351}: Removes libpython38.a from standard Windows distribution.

@item 
bpo-35360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35360}: Update Windows builds to use SQLite 3.28.0.

@item 
bpo-37267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37267}: On Windows, @ref{1dc2,,os.dup()} no longer creates an inheritable fd
when handling a character file.

@item 
bpo-36779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36779}: Ensure @code{time.tzname} is correct on Windows when the active
code page is set to CP_UTF7 or CP_UTF8.

@item 
bpo-32587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32587}: Make @ref{1dc3,,winreg.REG_MULTI_SZ} support zero-length strings.

@item 
bpo-28269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28269}: Replace use of @code{strcasecmp()} for the system function
@code{_stricmp()}. Patch by Minmin Gong.

@item 
bpo-36590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36590}: Add native Bluetooth RFCOMM support to socket module.
@end itemize

@node macOS<39>,IDLE<32>,Windows<50>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id702}@anchor{1dc4}
@subsubsection macOS



@itemize -

@item 
bpo-38117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38117}: Updated OpenSSL to 1.1.1d in macOS installer.

@item 
bpo-38089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38089}: Move Azure Pipelines to latest VM versions and make macOS tests
optional

@item 
bpo-18049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18049}: Increase the default stack size of threads from 5MB to 16MB on
macOS, to match the stack size of the main thread. This avoids crashes on
deep recursion in threads.

@item 
bpo-34602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34602}: Avoid test suite failures on macOS by no longer calling
resource.setrlimit to increase the process stack size limit at runtime.
The runtime change is no longer needed since the interpreter is being
built with a larger default stack size.

@item 
bpo-35360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35360}: Update macOS installer to use SQLite 3.28.0.

@item 
bpo-34631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34631}: Updated OpenSSL to 1.1.1c in macOS installer.
@end itemize

@node IDLE<32>,Tools/Demos<33>,macOS<39>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id703}@anchor{1dc5}
@subsubsection IDLE



@itemize -

@item 
bpo-26353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26353}: Stop adding newline when saving an IDLE shell window.

@item 
bpo-4630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4630}: Add an option to toggle IDLE's cursor blink for shell, editor,
and output windows.  See Settings, General, Window Preferences, Cursor
Blink. Patch by Zackery Spytz.

@item 
bpo-38598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38598}: Do not try to compile IDLE shell or output windows

@item 
bpo-36698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36698}: IDLE no longer fails when write non-encodable characters to
stderr.  It now escapes them with a backslash, as the regular Python
interpreter. Added the @code{errors} field to the standard streams.

@item 
bpo-35379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35379}: When exiting IDLE, catch any AttributeError.  One happens when
EditorWindow.close is called twice.  Printing a traceback, when IDLE is
run from a terminal, is useless and annoying.

@item 
bpo-38183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38183}: To avoid problems, test_idle ignores the user config directory.
It no longer tries to create or access .idlerc or any files within. Users
must run IDLE to discover problems with saving settings.

@item 
bpo-38077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38077}: IDLE no longer adds 'argv' to the user namespace when
initializing it.  This bug only affected 3.7.4 and 3.8.0b2 to 3.8.0b4.

@item 
bpo-38041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38041}: Shell restart lines now fill the window width, always start
with '=', and avoid wrapping unnecessarily. The line will still wrap if
the included file name is long relative to the width.

@item 
bpo-35771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35771}: To avoid occasional spurious test_idle failures on slower
machines, increase the @code{hover_delay} in test_tooltip.

@item 
bpo-37824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37824}: Properly handle user input warnings in IDLE shell. Cease
turning SyntaxWarnings into SyntaxErrors.

@item 
bpo-37929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37929}: IDLE Settings dialog now closes properly when there is no shell
window.

@item 
bpo-37902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37902}: Add mousewheel scrolling for IDLE module, path, and stack
browsers. Patch by George Zhang.

@item 
bpo-37849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37849}: Fixed completions list appearing too high or low when shown
above the current line.

@item 
bpo-36419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36419}: Refactor IDLE autocomplete and improve testing.

@item 
bpo-37748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37748}: Reorder the Run menu.  Put the most common choice, Run Module,
at the top.

@item 
bpo-37692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37692}: Improve highlight config sample with example shell interaction
and better labels for shell elements.

@item 
bpo-37628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37628}: Settings dialog no longer expands with font size.

@item 
bpo-37627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37627}: Initialize the Customize Run dialog with the command line
arguments most recently entered before.  The user can optionally edit
before submitting them.

@item 
bpo-33610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33610}: Fix code context not showing the correct context when first
toggled on.

@item 
bpo-37530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37530}: Optimize code context to reduce unneeded background activity.
Font and highlight changes now occur along with text changes instead of
after a random delay.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: Cleanup @code{config.py} by inlining @code{RemoveFile} and
simplifying the handling of @code{file} in @code{CreateConfigHandlers}.

@item 
bpo-37325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37325}: Fix tab focus traversal order for help source and custom run
dialogs.

@item 
bpo-37321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37321}: Both subprocess connection error messages now refer to the
'Startup failure' section of the IDLE doc.

@item 
bpo-17535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17535}: Add optional line numbers for IDLE editor windows.  Windows
open without line numbers unless set otherwise in the General tab of the
configuration dialog.

@item 
bpo-26806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26806}: To compensate for stack frames added by IDLE and avoid possible
problems with low recursion limits, add 30 to limits in the user code
execution process.  Subtract 30 when reporting recursion limits to make
this addition mostly transparent.

@item 
bpo-37177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37177}: Properly 'attach' search dialogs to their main window so that
they behave like other dialogs and do not get hidden behind their main
window.

@item 
bpo-37039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37039}: Adjust "Zoom Height" to individual screens by momentarily
maximizing the window on first use with a particular screen.  Changing
screen settings may invalidate the saved height.  While a window is
maximized, "Zoom Height" has no effect.

@item 
bpo-35763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35763}: Make calltip reminder about '/' meaning positional-only less
obtrusive by only adding it when there is room on the first line.

@item 
bpo-5680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5680}: Add 'Run... Customized' to the Run menu to run a module with
customized settings.  Any 'command line arguments' entered are added to
sys.argv. One can suppress the normal Shell main module restart.

@item 
bpo-36390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36390}: Gather Format menu functions into format.py.  Combine
paragraph.py, rstrip.py, and format methods from editor.py.
@end itemize

@node Tools/Demos<33>,C API<52>,IDLE<32>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id704}@anchor{1dc6}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-38118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38118}: Update Valgrind suppression file to ignore a false alarm in
@ref{1dc7,,PyUnicode_Decode()} when using GCC builtin strcmp().

@item 
bpo-38347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38347}: pathfix.py: Assume all files that end on '.py' are Python
scripts when working recursively.

@item 
bpo-37803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37803}: pdb's @code{--help} and @code{--version} long options now work.

@item 
bpo-37942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37942}: Improve ArgumentClinic converter for floats.

@item 
bpo-37704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37704}: Remove @code{Tools/scripts/h2py.py}: use cffi to access a C API in
Python.

@item 
bpo-37675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37675}: 2to3 now works when run from a zipped standard library.

@item 
bpo-37034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37034}: Argument Clinic now uses the argument name on errors with
keyword-only argument instead of their position. Patch contributed by Rémi
Lapeyre.

@item 
bpo-37064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37064}: Add option -k to pathscript.py script: preserve shebang flags.
Add option -a to pathscript.py script: add flags.
@end itemize

@node C API<52>,,Tools/Demos<33>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id705}@anchor{1dc8}
@subsubsection C API



@itemize -

@item 
bpo-37633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37633}: Re-export some function compatibility wrappers for macros in
@code{pythonrun.h}.

@item 
bpo-38644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38644}: Provide @ref{3d2,,Py_EnterRecursiveCall()} and
@ref{b6b,,Py_LeaveRecursiveCall()} as regular functions for the limited API.
Previously, there were defined as macros, but these macros didn't work
with the limited API which cannot access @code{PyThreadState.recursion_depth}
field. Remove @code{_Py_CheckRecursionLimit} from the stable ABI.

@item 
bpo-38650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38650}: The global variable @ref{b79,,PyStructSequence_UnnamedField} is
now a constant and refers to a constant string.

@item 
bpo-38540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38540}: Fixed possible leak in @ref{180e,,PyArg_Parse()} and similar
functions for format units @code{"es#"} and @code{"et#"} when the macro
@code{PY_SSIZE_T_CLEAN} is not defined.

@item 
bpo-38395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38395}: Fix a crash in @ref{c46,,weakref.proxy} objects due to incorrect
lifetime management when calling some associated methods that may delete
the last reference to object being referenced by the proxy. Patch by Pablo
Galindo.

@item 
bpo-36389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36389}: The @code{_PyObject_CheckConsistency()} function is now also
available in release mode. For example, it can be used to debug a crash in
the @code{visit_decref()} function of the GC.

@item 
bpo-38266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38266}: Revert the removal of PyThreadState_DeleteCurrent() with
documentation.

@item 
bpo-38303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38303}: Update audioop extension module to use the stable ABI
(PEP-384). Patch by Tyler Kieft.

@item 
bpo-38234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38234}: @code{Py_SetPath()} now sets @ref{3ed,,sys.executable} to the
program full path (@ref{3ec,,Py_GetProgramFullPath()}) rather than to the
program name (@ref{3ee,,Py_GetProgramName()}).

@item 
bpo-38234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38234}: Python ignored arguments passed to @code{Py_SetPath()},
@code{Py_SetPythonHome()} and @code{Py_SetProgramName()}: fix Python
initialization to use specified arguments.

@item 
bpo-38205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38205}: The @ref{dae,,Py_UNREACHABLE()} macro now calls
@ref{b7a,,Py_FatalError()}.

@item 
bpo-38140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38140}: Make dict and weakref offsets opaque for C heap types by
passing the offsets through PyMemberDef

@item 
bpo-15088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15088}: The C function @code{PyGen_NeedsFinalizing} has been removed. It
was not documented, tested or used anywhere within CPython after the
implementation of 
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/}. Patch by Joannah Nanjekye. (Patch by Joannah
Nanjekye)

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Options added by @code{PySys_AddXOption()} are now handled the
same way than @code{PyConfig.xoptions} and command line @code{-X} options.

@item 
bpo-37926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37926}: Fix a crash in @code{PySys_SetArgvEx(0, NULL, 0)}.

@item 
bpo-37879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37879}: Fix subtype_dealloc to suppress the type decref when the base
type is a C heap type

@item 
bpo-37645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37645}: Add @code{_PyObject_FunctionStr()} to get a user-friendly
string representation of a function-like object. Patch by Jeroen Demeyer.

@item 
bpo-29548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29548}: The functions @code{PyEval_CallObject}, @code{PyEval_CallFunction},
@code{PyEval_CallMethod} and @code{PyEval_CallObjectWithKeywords} are
deprecated. Use @ref{63d,,PyObject_Call()} and its variants instead.

@item 
bpo-37151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37151}: @code{PyCFunction_Call} is now a deprecated alias of
@ref{63d,,PyObject_Call()}.

@item 
bpo-37540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37540}: The vectorcall protocol now requires that the caller passes
only strings as keyword names.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: The vectorcall protocol is now enabled for @code{type} objects:
set @code{tp_vectorcall} to a vectorcall function to be used instead of
@code{tp_new} and @code{tp_init} when calling the class itself.

@item 
bpo-21120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21120}: Exclude Python-ast.h, ast.h and asdl.h from the limited API.

@item 
bpo-37483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37483}: Add new function @code{_PyObject_CallOneArg} for calling an object
with one positional argument.

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Add @ref{1dc9,,PyConfig_SetWideStringList()} function.

@item 
bpo-37337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37337}: Add fast functions for calling methods:
@code{_PyObject_VectorcallMethod()},
@code{_PyObject_CallMethodNoArgs()} and
@code{_PyObject_CallMethodOneArg()}.

@item 
bpo-28805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28805}: The @ref{199e,,METH_FASTCALL} calling convention has been
documented.

@item 
bpo-37221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37221}: The new function @code{PyCode_NewWithPosOnlyArgs()} allows to
create code objects like @code{PyCode_New()}, but with an extra
`posonlyargcount' parameter for indicating the number of positonal-only
arguments.

@item 
bpo-37215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37215}: Fix dtrace issue introduce by bpo-36842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36842}

@item 
bpo-37194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37194}: Add a new public @ref{63c,,PyObject_CallNoArgs()} function to the
C API: call a callable Python object without any arguments. It is the most
efficient way to call a callback without any argument. On x86-64, for
example, @code{PyObject_CallFunctionObjArgs(func, NULL)} allocates 960 bytes
on the stack per call, whereas @code{PyObject_CallNoArgs(func)} only
allocates 624 bytes per call.

@item 
bpo-37170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37170}: Fix the cast on error in
@ref{1dca,,PyLong_AsUnsignedLongLongMask()}.

@item 
bpo-35381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35381}: Convert posixmodule.c statically allocated types
@code{DirEntryType} and @code{ScandirIteratorType} to heap-allocated types.

@item 
bpo-34331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34331}: Use singular/plural noun in error message when instantiating an
abstract class with non-overridden abstract method(s).
@end itemize

@node Python 3 8 0 beta 1,Python 3 8 0 alpha 4,Python 3 9 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-8-0-beta-1}@anchor{1dcb}
@subsection Python 3.8.0 beta 1


`Release date: 2019-06-04'

@menu
* セキュリティ: セキュリティ<43>. 
* Core and Builtins: Core and Builtins<155>. 
* ライブラリ: ライブラリ<158>. 
* ドキュメント: ドキュメント<52>. 
* テスト: テスト<50>. 
* ビルド: ビルド<58>. 
* Windows: Windows<51>. 
* macOS: macOS<40>. 
* IDLE: IDLE<33>. 
* Tools/Demos: Tools/Demos<34>. 
* C API: C API<53>. 

@end menu

@node セキュリティ<43>,Core and Builtins<155>,,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id706}@anchor{1dcc}
@subsubsection セキュリティ



@itemize -

@item 
bpo-35907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35907}: 
@geindex Common Vulnerabilities and Exposures; CVE 2019-9948
CVE 2019-9948@footnote{https://www.cve.org/CVERecord?id=CVE-2019-9948}: Avoid file reading by disallowing
@code{local-file://} and @code{local_file://} URL schemes in
@code{URLopener().open()} and @code{URLopener().retrieve()} of
@ref{111,,urllib.request}.

@item 
bpo-33529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33529}: Prevent fold function used in email header encoding from
entering infinite loop when there are too many non-ASCII characters in a
header.

@item 
bpo-33164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33164}: Updated blake2 implementation which uses secure memset
implementation provided by platform.
@end itemize

@node Core and Builtins<155>,ライブラリ<158>,セキュリティ<43>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id707}@anchor{1dcd}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-35814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35814}: Allow unpacking in the right hand side of annotated
assignments. In particular, @code{t: Tuple[int, ...] = x, y, *z} is now
allowed.

@item 
bpo-37126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37126}: All structseq objects are now tracked by the garbage collector.
Patch by Pablo Galindo.

@item 
bpo-37122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37122}: Make the `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.

@item 
bpo-20092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20092}: Constructors of @ref{19b,,int}, @ref{196,,float} and
@ref{197,,complex} will now use the @ref{19e,,__index__()} special
method, if available and the corresponding method @ref{19d,,__int__()},
@ref{bc1,,__float__()} or @ref{7fd,,__complex__()} is not available.

@item 
bpo-37087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37087}: Add native thread ID (TID) support to OpenBSD.

@item 
bpo-26219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26219}: Implemented per opcode cache mechanism and @code{LOAD_GLOBAL}
instruction use it. @code{LOAD_GLOBAL} is now about 40% faster. Contributed
by Yury Selivanov, and Inada Naoki.

@item 
bpo-37072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37072}: Fix crash in PyAST_FromNodeObject() when flags is NULL.

@item 
bpo-37029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37029}: Freeing a great many small objects could take time quadratic in
the number of arenas, due to using linear search to keep @code{obmalloc.c}'s
list of usable arenas sorted by order of number of free memory pools.
This is accomplished without search now, leaving the worst-case time
linear in the number of arenas.  For programs where this quite visibly
matters (typically with more than 100 thousand small objects alive
simultaneously), this can greatly reduce the time needed to release their
memory.

@item 
bpo-26423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26423}: Fix possible overflow in @code{wrap_lenfunc()} when @code{sizeof(long)
< sizeof(Py_ssize_t)} (e.g., 64-bit Windows).

@item 
bpo-37050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37050}: Improve the AST for "debug" f-strings, which use '=' to print
out the source of the expression being evaluated.  Delete expr_text from
the FormattedValue node, and instead use a Constant string node (possibly
merged with adjacent constant expressions inside the f-string).

@item 
bpo-22385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22385}: The @code{bytes.hex}, @code{bytearray.hex}, and @code{memoryview.hex}
methods as well as the @code{binascii.hexlify} and @code{b2a_hex} functions now
have the ability to include an optional separator between hex bytes.  This
functionality was inspired by MicroPython's hexlify implementation.

@item 
bpo-26836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26836}: Add @ref{bfe,,os.memfd_create()}.

@item 
bpo-37032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37032}: Added new @code{replace()} method to the code type
(@ref{32f,,types.CodeType}).

@item 
bpo-37007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37007}: Implement @ref{c22,,socket.if_nameindex()},
@ref{c23,,socket.if_nametoindex()}, and @ref{c24,,socket.if_indextoname()} on
Windows.

@item 
bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829}: @ref{5f2,,PyErr_WriteUnraisable()} now creates a traceback object
if there is no current traceback. Moreover, call
@ref{42a,,PyErr_NormalizeException()} and @ref{1dce,,PyException_SetTraceback()}
to normalize the exception value. Ignore any error.

@item 
bpo-36878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36878}: Only accept text after @code{# type: ignore} if the first
character is ASCII. This is to disallow things like @code{# type: ignoreé}.

@item 
bpo-36878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36878}: Store text appearing after a @code{# type: ignore} comment in the
AST. For example a type ignore like @code{# type: ignore[E1000]} will have
the string @code{"[E1000]"} stored in its AST node.

@item 
bpo-2180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2180}: Treat line continuation at EOF as a @code{SyntaxError} by Anthony
Sottile.

@item 
bpo-36907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36907}: Fix a crash when calling a C function with a keyword dict
(@code{f(**kwargs)}) and changing the dict @code{kwargs} while that function is
running.

@item 
bpo-36946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36946}: Fix possible signed integer overflow when handling slices.

@item 
bpo-36826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36826}: Add NamedExpression kind support to ast_unparse.c

@item 
bpo-1875@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1875}: A @ref{18e,,SyntaxError} is now raised if a code blocks that will be
optimized away (e.g. if conditions that are always false) contains syntax
errors. Patch by Pablo Galindo.

@item 
bpo-36027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36027}: Allow computation of modular inverses via three-argument
@code{pow}: the second argument is now permitted to be negative in the case
where the first and third arguments are relatively prime.

@item 
bpo-36861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36861}: Update the Unicode database to version 12.1.0.

@item 
bpo-28866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28866}: Avoid caching attributes of classes which type defines mro() to
avoid a hard cache invalidation problem.

@item 
bpo-36851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36851}: The @code{FrameType} stack is now correctly cleaned up if the
execution ends with a return and the stack is not empty.

@item 
bpo-34616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34616}: The @code{compile()} builtin functions now support the
@code{ast.PyCF_ALLOW_TOP_LEVEL_AWAIT} flag,  which allow to compile sources
that  contains top-level @code{await}, @code{async with} or @code{async for}. This
is useful to evaluate async-code from with an already async functions; for
example in a custom REPL.

@item 
bpo-36842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36842}: Implement PEP 578, adding sys.audit, io.open_code and related
APIs.

@item 
bpo-27639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27639}: Correct return type for UserList slicing operations. Patch by
Michael Blahay, Erick Cervantes, and vaultah

@item 
bpo-36737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36737}: Move PyRuntimeState.warnings into per-interpreter state (via
"module state").

@item 
bpo-36793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36793}: Removed @code{__str__} implementations from builtin types
@ref{3c3,,bool}, @ref{19b,,int}, @ref{196,,float}, @ref{197,,complex} and few
classes from the standard library. They now inherit @code{__str__()} from
@ref{c7e,,object}.

@item 
bpo-36817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36817}: Add a @code{=} feature f-strings for debugging. This can precede
@code{!s}, @code{!r}, or @code{!a}. It produces the text of the expression,
followed by an equal sign, followed by the repr of the value of the
expression. So @code{f'@{3*9+15=@}'} would be equal to the string
@code{'3*9+15=42'}.  If @code{=} is specified, the default conversion is set to
@code{!r}, unless a format spec is given, in which case the formatting
behavior is unchanged, and __format__ will be used.

@item 
bpo-24048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24048}: Save the live exception during import.c's @code{remove_module()}.

@item 
bpo-27987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27987}: pymalloc returns memory blocks aligned by 16 bytes, instead of
8 bytes, on 64-bit platforms to conform x86-64 ABI. Recent compilers
assume this alignment more often. Patch by Inada Naoki.

@item 
bpo-36601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36601}: A long-since-meaningless check for @code{getpid() == main_pid} was
removed from Python's internal C signal handler.

@item 
bpo-36594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36594}: Fix incorrect use of @code{%p} in format strings. Patch by Zackery
Spytz.

@item 
bpo-36045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36045}: @code{builtins.help()} now prefixes @code{async} for async functions.

@item 
bpo-36084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36084}: Add native thread ID (TID) to threading.Thread objects
(supported platforms: Windows, FreeBSD, Linux, macOS)

@item 
bpo-36035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36035}: Added fix for broken symlinks in combination with pathlib

@item 
bpo-35983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35983}: Added new trashcan macros to deal with a double deallocation
that could occur when the @code{tp_dealloc} of a subclass calls the
@code{tp_dealloc} of a base class and that base class uses the trashcan
mechanism. Patch by Jeroen Demeyer.

@item 
bpo-20602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20602}: Do not clear @ref{89c,,sys.flags} and @ref{1dcf,,sys.float_info}
during shutdown. Patch by Zackery Spytz.

@item 
bpo-26826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26826}: Expose @code{copy_file_range()} as a low level API in the
@ref{a5,,os} module.

@item 
bpo-32388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32388}: Remove cross-version binary compatibility requirement in
tp_flags.

@item 
bpo-31862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31862}: Port binascii to PEP 489 multiphase initialization. Patch by
Marcel Plch.
@end itemize

@node ライブラリ<158>,ドキュメント<52>,Core and Builtins<155>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id708}@anchor{1dd0}
@subsubsection ライブラリ



@itemize -

@item 
bpo-37128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37128}: Added @ref{8e0,,math.perm()}.

@item 
bpo-37120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37120}: Add SSLContext.num_tickets to control the number of TLSv1.3
session tickets.

@item 
bpo-12202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12202}: Fix the error handling in
@code{msilib.SummaryInformation.GetProperty()}. Patch by Zackery Spytz.

@item 
bpo-26835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26835}: The fcntl module now contains file sealing constants for
sealing of memfds.

@item 
bpo-29262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29262}: Add @code{get_origin()} and @code{get_args()} introspection helpers
to @code{typing} module.

@item 
bpo-12639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12639}: @code{msilib.Directory.start_component()} no longer fails if
`keyfile' is not @code{None}.

@item 
bpo-36999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36999}: Add the @code{asyncio.Task.get_coro()} method to publicly expose
the tasks's coroutine object.

@item 
bpo-35246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35246}: Make @ref{c6b,,asyncio.create_subprocess_exec()} accept path-like
arguments.

@item 
bpo-35279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35279}: Change default `max_workers' of @code{ThreadPoolExecutor} from
@code{cpu_count() * 5} to @code{min(32, cpu_count() + 4)}.  Previous value was
unreasonably large on many cores machines.

@item 
bpo-37076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37076}: @ref{4b4,,_thread.start_new_thread()} now logs uncaught exception
raised by the function using @ref{507,,sys.unraisablehook()}, rather than
@ref{a0c,,sys.excepthook()}, so the hook gets access to the function which
raised the exception.

@item 
bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725}: On macOS, the @ref{98,,multiprocessing} module now uses `spawn'
start method by default.

@item 
bpo-37054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37054}: Fix destructor @code{_pyio.BytesIO} and
@code{_pyio.TextIOWrapper}: initialize their @code{_buffer} attribute as
soon as possible (in the class body), because it's used by @code{__del__()}
which calls @code{close()}.

@item 
bpo-37058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37058}: PEP 544: Add @code{Protocol} and @code{@@runtime_checkable} to the
@code{typing} module.

@item 
bpo-36933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36933}: The functions @code{sys.set_coroutine_wrapper} and
@code{sys.get_coroutine_wrapper} that were deprecated and marked for removal
in 3.8 have been removed.

@item 
bpo-37047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37047}: Handle late binding and attribute access in
@ref{c3e,,unittest.mock.AsyncMock} setup for autospeccing. Document newly
implemented async methods in @ref{108f,,unittest.mock.MagicMock}.

@item 
bpo-37049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37049}: PEP 589: Add @code{TypedDict} to the @code{typing} module.

@item 
bpo-37046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37046}: PEP 586: Add @code{Literal} to the @code{typing} module.

@item 
bpo-37045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37045}: PEP 591: Add @code{Final} qualifier and @code{@@final} decorator to
the @code{typing} module.

@item 
bpo-37035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37035}: Don't log OSError based exceptions if a fatal error has
occurred in asyncio transport. Peer can generate almost any OSError, user
cannot avoid these exceptions by fixing own code. Errors are still
propagated to user code, it's just logging them is pointless and pollute
asyncio logs.

@item 
bpo-37001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37001}: @ref{1dd1,,symtable.symtable()} now accepts the same input types for
source code as the built-in @ref{4b1,,compile()} function. Patch by Dino
Viehland.

@item 
bpo-37028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37028}: Implement asyncio REPL

@item 
bpo-37027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37027}: Return safe to use proxy socket object from
transport.get_extra_info('socket')

@item 
bpo-32528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32528}: Make asyncio.CancelledError a BaseException.

This will address the common mistake many asyncio users make: an "except
Exception" clause breaking Tasks cancellation.

In addition to this change, we stop inheriting asyncio.TimeoutError and
asyncio.InvalidStateError from their concurrent.futures.* counterparts.
There's no point for these exceptions to share the inheritance chain.

@item 
bpo-1230540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1230540}: Add a new @ref{a4b,,threading.excepthook()} function which handles
uncaught @ref{c31,,threading.Thread.run()} exception. It can be overridden to
control how uncaught @ref{c31,,threading.Thread.run()} exceptions are handled.

@item 
bpo-36996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36996}: Handle @ref{1092,,unittest.mock.patch()} used as a decorator on async
functions.

@item 
bpo-37008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37008}: Add support for calling @ref{9d8,,next()} with the mock resulting
from @ref{11e9,,unittest.mock.mock_open()}

@item 
bpo-27737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27737}: Allow whitespace only header encoding in @code{email.header} - by
Batuhan Taskaya

@item 
bpo-36969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36969}: PDB command @code{args} now  display positional only arguments.
Patch contributed by Rémi Lapeyre.

@item 
bpo-36969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36969}: PDB command @code{args} now  display keyword only arguments. Patch
contributed by Rémi Lapeyre.

@item 
bpo-36983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36983}: Add missing names to @code{typing.__all__}: @code{ChainMap},
@code{ForwardRef}, @code{OrderedDict} - by Anthony Sottile.

@item 
bpo-36972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36972}: Add SupportsIndex protocol to the typing module to allow type
checking to detect classes that can be passed to @code{hex()}, @code{oct()} and
@code{bin()}.

@item 
bpo-32972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32972}: Implement @code{unittest.IsolatedAsyncioTestCase} to help testing
asyncio-based code.

@item 
bpo-36952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36952}: @ref{a00,,fileinput.input()} and @ref{940,,fileinput.FileInput}
`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.

@item 
bpo-36952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36952}: Starting with Python 3.3, importing ABCs from
@ref{1e,,collections} is deprecated, and import should be done from
@ref{1f,,collections.abc}. Still being able to import from @ref{1e,,collections}
was marked for removal in 3.8, but has been delayed to 3.9; documentation
and @code{DeprecationWarning} clarified.

@item 
bpo-36949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36949}: Implement __repr__ for WeakSet objects.

@item 
bpo-36948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36948}: Fix @ref{452,,NameError} in
@code{urllib.request.URLopener.retrieve()}. Patch by Karthikeyan
Singaravelan.

@item 
bpo-33524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33524}: Fix the folding of email header when the max_line_length is 0
or None and the header contains non-ascii characters.  Contributed by
Licht Takeuchi (@@Licht-T).

@item 
bpo-24564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24564}: @ref{1346,,shutil.copystat()} now ignores @ref{1dd2,,errno.EINVAL} on
@ref{131f,,os.setxattr()} which may occur when copying files on filesystems
without extended attributes support.

Original patch by Giampaolo Rodola, updated by Ying Wang.

@item 
bpo-36888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36888}: Python child processes can now access the status of their
parent process using multiprocessing.process.parent_process

@item 
bpo-36921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36921}: Deprecate @code{@@coroutine} for sake of @code{async def}.

@item 
bpo-25652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25652}: Fix bug in @code{__rmod__} of @code{UserString} - by Batuhan Taskaya.

@item 
bpo-36916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36916}: Remove a message about an unhandled exception in a task when
writer.write() is used without await and writer.drain() fails with an
exception.

@item 
bpo-36889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36889}: Introduce @code{asyncio.Stream} class that merges
@ref{1c7d,,asyncio.StreamReader} and @ref{1a70,,asyncio.StreamWriter}
functionality. @code{asyncio.Stream} can work in readonly, writeonly and
readwrite modes. Provide @code{asyncio.connect()},
@code{asyncio.connect_unix()}, @code{asyncio.connect_read_pipe()} and
@code{asyncio.connect_write_pipe()} factories to open
@code{asyncio.Stream} connections. Provide @code{asyncio.StreamServer}
and @code{UnixStreamServer} to serve servers with asyncio.Stream API.
Modify @ref{c6c,,asyncio.create_subprocess_shell()} and
@ref{c6b,,asyncio.create_subprocess_exec()} to use @code{asyncio.Stream}
instead of deprecated @code{StreamReader} and @code{StreamWriter}.
Deprecate @ref{1c7d,,asyncio.StreamReader} and @ref{1a70,,asyncio.StreamWriter}.
Deprecate usage of private classes, e.g.
@code{asyncio.FlowControlMixing} and
@code{asyncio.StreamReaderProtocol} outside of asyncio package.

@item 
bpo-36845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36845}: Added validation of integer prefixes to the construction of IP
networks and interfaces in the ipaddress module.

@item 
bpo-23378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23378}: Add an extend action to argparser.

@item 
bpo-36867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36867}: Fix a bug making a SharedMemoryManager instance and its parent
process use two separate resource_tracker processes.

@item 
bpo-23896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23896}: Adds a grammar to lib2to3.pygram that contains exec as a
function not as statement.

@item 
bpo-36895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36895}: The function @code{time.clock()} was deprecated in 3.3 in favor of
@code{time.perf_counter()} and marked for removal in 3.8, it has removed.

@item 
bpo-35545@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35545}: Fix asyncio discarding IPv6 scopes when ensuring hostname
resolutions internally

@item 
bpo-36887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36887}: Add new function @ref{bf8,,math.isqrt()} to compute integer square
roots.

@item 
bpo-34632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34632}: Introduce the @code{importlib.metadata} module with (provisional)
support for reading metadata from third-party packages.

@item 
bpo-36878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36878}: When using @code{type_comments=True} in @code{ast.parse}, treat @code{#
type: ignore} followed by a non-alphanumeric character and then arbitrary
text as a type ignore, instead of requiring nothing but whitespace or
another comment. This is to permit formations such as @code{# type:
ignore[E1000]}.

@item 
bpo-36778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36778}: @code{cp65001} encoding (Windows code page 65001) becomes an alias
to @code{utf_8} encoding.

@item 
bpo-36867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36867}: The multiprocessing.resource_tracker replaces the
multiprocessing.semaphore_tracker module. Other than semaphores,
resource_tracker also tracks shared_memory segments.

@item 
bpo-30262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30262}: The @code{Cache} and @code{Statement} objects of the @ref{d4,,sqlite3}
module are not exposed to the user.  Patch by Aviv Palivoda.

@item 
bpo-24538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24538}: In @code{shutil.copystat()}, first copy extended file attributes
and then file permissions, since extended attributes can only be set on
the destination while it is still writeable.

@item 
bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829}: Add new @ref{507,,sys.unraisablehook()} function which can be
overridden to control how "unraisable exceptions" are handled. It is
called when an exception has occurred but there is no way for Python to
handle it. For example, when a destructor raises an exception or during
garbage collection (@ref{1b3,,gc.collect()}).

@item 
bpo-36832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36832}: Introducing @code{zipfile.Path}, a pathlib-compatible wrapper for
traversing zip files.

@item 
bpo-36814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36814}: Fix an issue where os.posix_spawnp() would incorrectly raise a
TypeError when file_actions is None.

@item 
bpo-33110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33110}: Handle exceptions raised by functions added by
concurrent.futures add_done_callback correctly when the Future has already
completed.

@item 
bpo-26903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26903}: Limit @code{max_workers} in @code{ProcessPoolExecutor} to 61 to work
around a WaitForMultipleObjects limitation.

@item 
bpo-36813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36813}: Fix @ref{242,,QueueListener} to call
@code{queue.task_done()} upon stopping. Patch by Bar Harel.

@item 
bpo-36806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36806}: Forbid creation of asyncio stream objects like StreamReader,
StreamWriter, Process, and their protocols outside of asyncio package.

@item 
bpo-36802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36802}: Provide both sync and async calls for StreamWriter.write() and
StreamWriter.close()

@item 
bpo-36801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36801}: Properly handle SSL connection closing in asyncio
StreamWriter.drain() call.

@item 
bpo-36785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36785}: Implement PEP 574 (pickle protocol 5 with out-of-band buffers).

@item 
bpo-36772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36772}: functools.lru_cache() can now be used as a straight decorator
in addition to its existing usage as a function that returns a decorator.

@item 
bpo-6584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6584}: Add a @ref{bea,,BadGzipFile} exception to the @ref{6b,,gzip}
module.

@item 
bpo-36748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36748}: Optimized write buffering in C implementation of
@code{TextIOWrapper}. Writing ASCII string to @code{TextIOWrapper} with ascii,
latin1, or utf-8 encoding is about 20% faster.  Patch by Inada Naoki.

@item 
bpo-8138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8138}: Don't mark @code{wsgiref.simple_server.SimpleServer} as
multi-threaded since @code{wsgiref.simple_server.WSGIServer} is
single-threaded.

@item 
bpo-22640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22640}: @ref{c1a,,py_compile.compile()} now supports silent mode. Patch by
Joannah Nanjekye

@item 
bpo-29183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29183}: Fix double exceptions in @ref{1dd3,,wsgiref.handlers.BaseHandler}
by calling its @code{close()} method only
when no exception is raised.

@item 
bpo-36548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36548}: Improved the repr of regular expression flags.

@item 
bpo-36542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36542}: The signature of Python functions can now be overridden by
specifying the @code{__text_signature__} attribute.

@item 
bpo-36533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36533}: Reinitialize logging.Handler locks in forked child processes
instead of attempting to acquire them all in the parent before forking
only to be released in the child process.  The acquire/release pattern was
leading to deadlocks in code that has implemented any form of chained
logging handlers that depend upon one another as the lock acquisition
order cannot be guaranteed.

@item 
bpo-35252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35252}: Throw a TypeError instead of an AssertionError when using an
invalid type annotation with singledispatch.

@item 
bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900}: Allow reduction methods to return a 6-item tuple where the 6th
item specifies a custom state-setting method that's called instead of the
regular @code{__setstate__} method.

@item 
bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900}: enable custom reduction callback registration for functions and
classes in _pickle.c, using the new Pickler's attribute
@code{reducer_override}

@item 
bpo-36368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36368}: Fix a bug crashing SharedMemoryManager instances in interactive
sessions after a ctrl-c (KeyboardInterrupt) was sent

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix mmap fail for VxWorks

@item 
bpo-27497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27497}: @ref{1418,,csv.DictWriter.writeheader()} now returns the return value
of the underlying @code{csv.Writer.writerow()} method. Patch contributed by
Ashish Nitin Patil.

@item 
bpo-36239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36239}: Parsing .mo files now ignores comments starting and ending with
#-#-#-#-#.

@item 
bpo-26707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26707}: Enable plistlib to read and write binary plist files that were
created as a KeyedArchive file. Specifically, this allows the plistlib to
process 0x80 tokens as UID objects.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Add posix module support for VxWorks.

@item 
bpo-35125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35125}: Asyncio: Remove inner callback on outer cancellation in shield

@item 
bpo-35721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35721}: Fix @code{asyncio.SelectorEventLoop.subprocess_exec()} leaks
file descriptors if @code{Popen} fails and called with
@code{stdin=subprocess.PIPE}. Patch by Niklas Fiekas.

@item 
bpo-31855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31855}: @ref{11e9,,unittest.mock.mock_open()} results now respects the
argument of read([size]). Patch contributed by Rémi Lapeyre.

@item 
bpo-35431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35431}: Implement @ref{8df,,math.comb()} that returns binomial coefficient,
that computes the number of ways to choose k items from n items without
repetition and without order. Patch by Yash Aggarwal and Keller Fuchs.

@item 
bpo-26660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26660}: Fixed permission errors in
@ref{144c,,TemporaryDirectory} clean up. Previously
@code{TemporaryDirectory.cleanup()} failed when non-writeable or
non-searchable files or directories were created inside a temporary
directory.

@item 
bpo-34271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34271}: Add debugging helpers to ssl module. It's now possible to dump
key material and to trace TLS protocol. The default and stdlib contexts
also support SSLKEYLOGFILE env var.

@item 
bpo-26467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26467}: Added AsyncMock to support using unittest to mock asyncio
coroutines. Patch by Lisa Roach.

@item 
bpo-33569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33569}: dataclasses.InitVar: Exposes the type used to create the init
var.

@item 
bpo-34424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34424}: Fix serialization of messages containing encoded strings when
the policy.linesep is set to a multi-character string. Patch by Jens
Troeger.

@item 
bpo-34303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34303}: Performance of @ref{21a,,functools.reduce()} is slightly improved.
Patch by Sergey Fedoseev.

@item 
bpo-33361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33361}: Fix a bug in @ref{1dd4,,codecs.StreamRecoder} where seeking might
leave old data in a buffer and break subsequent read calls. Patch by Ammar
Askar.

@item 
bpo-22454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22454}: The @ref{c9,,shlex} module now exposes @ref{c1c,,shlex.join()}, the
inverse of @ref{75e,,shlex.split()}. Patch by Bo Bayles.

@item 
bpo-31922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31922}: @code{asyncio.AbstractEventLoop.create_datagram_endpoint()}: Do
not connect UDP socket when broadcast is allowed. This allows to receive
replies after a UDP broadcast.

@item 
bpo-24882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24882}: Change ThreadPoolExecutor to use existing idle threads before
spinning up new ones.

@item 
bpo-31961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31961}: Added support for bytes and path-like objects in
@ref{4b7,,subprocess.Popen()} on Windows.  The `args' parameter now accepts a
@ref{5a1,,path-like object} if `shell' is @code{False} and a sequence containing
bytes and path-like objects. The `executable' parameter now accepts a
bytes and @ref{5a1,,path-like object}. The `cwd' parameter now accepts a
bytes object. Based on patch by Anders Lorentsen.

@item 
bpo-33123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33123}: @ref{1dd5,,pathlib.Path.unlink} now accepts a `missing_ok'
parameter to avoid a @ref{264,,FileNotFoundError} from being raised. Patch by
Robert Buchholz.

@item 
bpo-32941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32941}: Allow @ref{519,,mmap.mmap} objects to access the madvise() system
call (through @ref{bfb,,mmap.mmap.madvise()}).

@item 
bpo-22102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22102}: Added support for ZIP files with disks set to 0. Such files are
commonly created by builtin tools on Windows when use ZIP64 extension.
Patch by Francisco Facioni.

@item 
bpo-32515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32515}: trace.py can now run modules via python3 -m trace -t --module
module_name

@item 
bpo-32299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32299}: Changed @ref{1967,,unittest.mock.patch.dict()} to return the patched
dictionary when used as context manager. Patch by Vadim Tsander.

@item 
bpo-27141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27141}: Added a @code{__copy__()} to @code{collections.UserList} and
@code{collections.UserDict} in order to correctly implement shallow copying
of the objects. Patch by Bar Harel.

@item 
bpo-31829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31829}: @code{\r}, @code{\0} and @code{\x1a} (end-of-file on Windows) are now
escaped in protocol 0 pickles of Unicode strings. This allows to load them
without loss from files open in text mode in Python 2.

@item 
bpo-23395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23395}: @code{_thread.interrupt_main()} now avoids setting the Python
error status if the @code{SIGINT} signal is ignored or not handled by Python.
@end itemize

@node ドキュメント<52>,テスト<50>,ライブラリ<158>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id709}@anchor{1dd6}
@subsubsection ドキュメント



@itemize -

@item 
bpo-36896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36896}: Clarify that some types have unstable constructor signature
between Python versions.

@item 
bpo-36686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36686}: Improve documentation of the stdin, stdout, and stderr
arguments of the @code{asyncio.subprocess_exec} function to specify which
values are supported. Also mention that decoding as text is not supported.

Add a few tests to verify that the various values passed to the std*
arguments actually work.

@item 
bpo-36984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36984}: Improve version added references in @code{typing} module - by
Anthony Sottile.

@item 
bpo-36868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36868}: What's new now mentions SSLContext.hostname_checks_common_name
instead of SSLContext.host_flags.

@item 
bpo-35924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35924}: Add a note to the @code{curses.addstr()} documentation to warn
that multiline strings can cause segfaults because of an ncurses bug.

@item 
bpo-36783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36783}: Added C API Documentation for Time_FromTimeAndFold and
PyDateTime_FromDateAndTimeAndFold as per PEP 495. Patch by Edison
Abahurire.

@item 
bpo-36797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36797}: More of the legacy distutils documentation has been either
pruned, or else more clearly marked as being retained solely until the
setuptools documentation covers it independently.

@item 
bpo-22865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22865}: Add detail to the documentation on the @code{pty.spawn} function.

@item 
bpo-35397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35397}: Remove deprecation and document urllib.parse.unwrap(). Patch
contributed by Rémi Lapeyre.

@item 
bpo-32995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32995}: Added the context variable in glossary.

@item 
bpo-33519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33519}: Clarify that @code{copy()} is not part of the @code{MutableSequence}
ABC.

@item 
bpo-33482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33482}: Make @code{codecs.StreamRecoder.writelines} take a list of bytes.

@item 
bpo-25735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25735}: Added documentation for func factorial to indicate that returns
integer values

@item 
bpo-20285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20285}: Expand object.__doc__ (docstring) to make it clearer. Modify
pydoc.py so that help(object) lists object methods (for other classes,
help omits methods of the object base class.)
@end itemize

@node テスト<50>,ビルド<58>,ドキュメント<52>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id710}@anchor{1dd7}
@subsubsection テスト



@itemize -

@item 
bpo-37069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37069}: Modify test_coroutines, test_cprofile, test_generators,
test_raise, test_ssl and test_yield_from to use
@ref{1dbd,,test.support.catch_unraisable_exception()} rather than
@ref{1dd8,,test.support.captured_stderr()}.

@item 
bpo-37098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37098}: Fix test_memfd_create on older Linux Kernels.

@item 
bpo-37081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37081}: Test with OpenSSL 1.1.1c

@item 
bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829}: Add @ref{1dbd,,test.support.catch_unraisable_exception()}: context
manager catching unraisable exception using @ref{507,,sys.unraisablehook()}.

@item 
bpo-36915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36915}: The main regrtest process now always removes all temporary
directories of worker processes even if they crash or if they are killed
on KeyboardInterrupt (CTRL+c).

@item 
bpo-36719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36719}: "python3 -m test -jN ..." now continues the execution of next
tests when a worker process crash (CHILD_ERROR state). Previously, the
test suite stopped immediately. Use --failfast to stop at the first error.

@item 
bpo-36816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36816}: Update Lib/test/selfsigned_pythontestdotnet.pem to match
self-signed.pythontest.net's new TLS certificate.

@item 
bpo-35925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35925}: Skip httplib and nntplib networking tests when they would
otherwise fail due to a modern OS or distro with a default OpenSSL policy
of rejecting connections to servers with weak certificates.

@item 
bpo-36782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36782}: Add tests for several C API functions in the @ref{34,,datetime}
module. Patch by Edison Abahurire.

@item 
bpo-36342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36342}: Fix test_multiprocessing in test_venv if platform lacks
functioning sem_open.
@end itemize

@node ビルド<58>,Windows<51>,テスト<50>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id711}@anchor{1dd9}
@subsubsection ビルド



@itemize -

@item 
bpo-36721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36721}: To embed Python into an application, a new @code{--embed} option
must be passed to @code{python3-config --libs --embed} to get @code{-lpython3.8}
(link the application to libpython). To support both 3.8 and older, try
@code{python3-config --libs --embed} first and fallback to @code{python3-config
--libs} (without @code{--embed}) if the previous command fails.

Python をアプリケーションに組み込むために、@code{python-3.8-embed} pkg-config モジュールが追加されました: @code{pkg-config python-3.8-embed --libs} の出力は、@code{-lpython3.8} を含みます。 Python3.8 以前との互換性を保つためには、@code{pkg-config python-X.Y-embed --libs} をまず試みてから、失敗した場合 @code{pkg-config python-X.Y --libs} (@code{--embed} なし) にフォールバックしてください。(@code{X.Y} を使用するPython のバージョンに置き換えてください)

On the other hand, @code{pkg-config python3.8 --libs} no longer contains
@code{-lpython3.8}. C extensions must not be linked to libpython (except on
Android, case handled by the script); this change is backward incompatible
on purpose.

@item 
bpo-36786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36786}: "make install" now runs compileall in parallel.
@end itemize

@node Windows<51>,macOS<40>,ビルド<58>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id712}@anchor{1dda}
@subsubsection Windows



@itemize -

@item 
bpo-36965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36965}: include of STATUS_CONTROL_C_EXIT without depending on MSC
compiler

@item 
bpo-35926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35926}: Update to OpenSSL 1.1.1b for Windows.

@item 
bpo-29883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29883}: Add Windows support for UDP transports for the Proactor Event
Loop. Patch by Adam Meily.

@item 
bpo-33407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33407}: The @ref{c9b,,Py_DEPRECATED()} macro has been implemented for
MSVC.
@end itemize

@node macOS<40>,IDLE<33>,Windows<51>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id713}@anchor{1ddb}
@subsubsection macOS



@itemize -

@item 
bpo-36231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36231}: Support building Python on macOS without /usr/include
installed. As of macOS 10.14, system header files are only available
within an SDK provided by either the Command Line Tools or the Xcode app.
@end itemize

@node IDLE<33>,Tools/Demos<34>,macOS<40>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id714}@anchor{1ddc}
@subsubsection IDLE



@itemize -

@item 
bpo-35610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35610}: Replace now redundant .context_use_ps1 with .prompt_last_line.
This finishes change started in bpo-31858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31858}.

@item 
bpo-37038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37038}: Make idlelib.run runnable; add test clause.

@item 
bpo-36958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36958}: Print any argument other than None or int passed to SystemExit
or sys.exit().

@item 
bpo-36807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36807}: When saving a file, call os.fsync() so bits are flushed to e.g.
USB drive.

@item 
bpo-32411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32411}: In browser.py, remove extraneous sorting by line number since
dictionary was created in line number order.
@end itemize

@node Tools/Demos<34>,C API<53>,IDLE<33>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id715}@anchor{1ddd}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-37053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37053}: Handle strings like u"bar" correctly in
Tools/parser/unparse.py. Patch by Chih-Hsuan Yen.
@end itemize

@node C API<53>,,Tools/Demos<34>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id716}@anchor{1dde}
@subsubsection C API



@itemize -

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Implement the 
@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/} "Python Initialization Configuration".

@item 
bpo-36379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36379}: Fix crashes when attempting to use the `modulo' parameter when
@code{__ipow__} is implemented in C.

@item 
bpo-37107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37107}: Update @ref{1ddf,,PyObject_CallMethodObjArgs()} and
@code{_PyObject_CallMethodIdObjArgs} to use @code{_PyObject_GetMethod} to avoid
creating a bound method object in many cases. Patch by Michael J.
Sullivan.

@item 
bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}: Implement 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/}: Vectorcall: a fast calling protocol for
CPython. This is a new protocol to optimize calls of custom callable
objects.

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: @code{Py_Main()} now returns the exitcode rather than calling
@code{Py_Exit(exitcode)} when calling @code{PyErr_Print()} if the current
exception type is @code{SystemExit}.

@item 
bpo-36922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36922}: Add new type flag @code{Py_TPFLAGS_METHOD_DESCRIPTOR} for objects
behaving like unbound methods. These are objects supporting the
optimization given by the @code{LOAD_METHOD}/@code{CALL_METHOD} opcodes. See PEP
590.

@item 
bpo-36728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36728}: The @code{PyEval_ReInitThreads()} function has been removed
from the C API. It should not be called explicitly: use
@ref{430,,PyOS_AfterFork_Child()} instead.
@end itemize

@node Python 3 8 0 alpha 4,Python 3 8 0 alpha 3,Python 3 8 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-8-0-alpha-4}@anchor{1de0}
@subsection Python 3.8.0 alpha 4


`Release date: 2019-05-06'

@menu
* セキュリティ: セキュリティ<44>. 
* Core and Builtins: Core and Builtins<156>. 
* ライブラリ: ライブラリ<159>. 
* ドキュメント: ドキュメント<53>. 
* テスト: テスト<51>. 
* ビルド: ビルド<59>. 
* Windows: Windows<52>. 
* macOS: macOS<41>. 
* IDLE: IDLE<34>. 
* Tools/Demos: Tools/Demos<35>. 
* C API: C API<54>. 

@end menu

@node セキュリティ<44>,Core and Builtins<156>,,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id717}@anchor{1de1}
@subsubsection セキュリティ



@itemize -

@item 
bpo-36742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36742}: Fixes mishandling of pre-normalization characters in
urlsplit().

@item 
bpo-30458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30458}: Address 
@geindex Common Vulnerabilities and Exposures; CVE 2019-9740
CVE 2019-9740@footnote{https://www.cve.org/CVERecord?id=CVE-2019-9740} by disallowing URL paths with embedded
whitespace or control characters through into the underlying http client
request.  Such potentially malicious header injection URLs now cause an
http.client.InvalidURL exception to be raised.

@item 
bpo-35755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35755}: @ref{6db,,shutil.which()} now uses @code{os.confstr("CS_PATH")} if
available and if the 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable is not set.
Remove also the current directory from @code{posixpath.defpath}. On Unix,
@ref{6db,,shutil.which()} and the @ref{dc,,subprocess} module no longer search the
executable in the current directory if the 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment
variable is not set.
@end itemize

@node Core and Builtins<156>,ライブラリ<159>,セキュリティ<44>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id718}@anchor{1de2}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-36722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36722}: In debug build, import now also looks for C extensions compiled
in release mode and for C extensions compiled in the stable ABI.

@item 
bpo-32849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32849}: Fix Python Initialization code on FreeBSD to detect properly
when stdin file descriptor (fd 0) is invalid.

@item 
bpo-36623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36623}: Remove parser headers and related function declarations that
lack implementations after the removal of pgen.

@item 
bpo-20180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20180}: @code{dict.pop()} is now up to 33% faster thanks to Argument
Clinic. Patch by Inada Naoki.

@item 
bpo-36611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36611}: Debug memory allocators: disable serialno field by default from
debug hooks on Python memory allocators to reduce the memory footprint by
5%. Enable @ref{105,,tracemalloc} to get the traceback where a memory block
has been allocated when a fatal memory error is logged to decide where to
put a breakpoint. Compile Python with @code{PYMEM_DEBUG_SERIALNO} defined to
get back the field.

@item 
bpo-36588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36588}: On AIX, @ref{291,,sys.platform} doesn't contain the major version
anymore. Always return @code{'aix'}, instead of @code{'aix3'} .. @code{'aix7'}.
Since older Python versions include the version number, it is recommended
to always use @code{sys.platform.startswith('aix')}. Contributed by M. Felt.

@item 
bpo-36549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36549}: Change str.capitalize to use titlecase for the first character
instead of uppercase.

@item 
bpo-36540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36540}: Implement 
@geindex Python Enhancement Proposals; PEP 570
PEP 570@footnote{https://peps.python.org/pep-0570/} (Python positional-only parameters). Patch
by Pablo Galindo.

@item 
bpo-36475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36475}: @code{PyEval_AcquireLock()} and
@code{PyEval_AcquireThread()} now terminate the current thread if called
while the interpreter is finalizing, making them consistent with
@ref{648,,PyEval_RestoreThread()}, @ref{c7f,,Py_END_ALLOW_THREADS()}, and
@ref{64a,,PyGILState_Ensure()}.

@item 
bpo-36504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36504}: Fix signed integer overflow in _ctypes.c's
@code{PyCArrayType_new()}.

@item 
bpo-20844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20844}: Fix running script with encoding cookie and LF line ending may
fail on Windows.

@item 
bpo-24214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24214}: Fixed support of the surrogatepass error handler in the UTF-8
incremental decoder.

@item 
bpo-36452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36452}: Changing @code{dict} keys during iteration of the dict itself,
@code{keys()}, @code{values()}, or @code{items()} will now be detected in certain
corner cases where keys are deleted/added so that the number of keys isn't
changed. A @code{RuntimeError} will be raised after @code{len(dict)} iterations.
Contributed by Thomas Perl.

@item 
bpo-36459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36459}: Fix a possible double @code{PyMem_FREE()} due to tokenizer.c's
@code{tok_nextc()}.

@item 
bpo-36433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36433}: Fixed TypeError message in classmethoddescr_call.

@item 
bpo-36430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36430}: Fix a possible reference leak in @ref{149b,,itertools.count()}.

@item 
bpo-36440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36440}: Include node names in @code{ParserError} messages, instead of
numeric IDs. Patch by A. Skrobov.

@item 
bpo-36143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36143}: Regenerate @ref{88,,keyword} from the Grammar and Tokens file
using pgen. Patch by Pablo Galindo.

@item 
bpo-18372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18372}: Add missing @ref{171d,,PyObject_GC_Track()} calls in the
@ref{ab,,pickle} module. Patch by Zackery Spytz.
@end itemize

@node ライブラリ<159>,ドキュメント<53>,Core and Builtins<156>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id719}@anchor{1de3}
@subsubsection ライブラリ



@itemize -

@item 
bpo-35952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35952}: Fix pythoninfo when the compiler is missing.

@item 
bpo-28238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28238}: The @code{.find*()} methods of xml.etree.ElementTree can now
search for wildcards like @code{@{*@}tag} and @code{@{ns@}*} that match a tag in any
namespace or all tags in a namespace.  Patch by Stefan Behnel.

@item 
bpo-26978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26978}: @code{pathlib.path.link_to()} is now implemented. It creates a
hard link pointing to a path.

@item 
bpo-1613500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1613500}: @ref{940,,fileinput.FileInput} now uses the input file mode to
correctly set the output file mode (previously it was hardcoded to
@code{'w'})  when @code{inplace=True} is passed to its constructor.

@item 
bpo-36734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36734}: Fix compilation of @code{faulthandler.c} on HP-UX. Initialize
@code{stack_t current_stack} to zero using @code{memset()}.

@item 
bpo-13611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13611}: The xml.etree.ElementTree packages gained support for C14N 2.0
serialisation. Patch by Stefan Behnel.

@item 
bpo-36669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36669}: Add missing matrix multiplication operator support to
weakref.proxy.

@item 
bpo-36676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36676}: The XMLParser() in xml.etree.ElementTree provides namespace
prefix context to the parser target if it defines the callback methods
"start_ns()" and/or "end_ns()". Patch by Stefan Behnel.

@item 
bpo-36673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36673}: The TreeBuilder and XMLPullParser in xml.etree.ElementTree
gained support for parsing comments and processing instructions. Patch by
Stefan Behnel.

@item 
bpo-36650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36650}: The C version of functools.lru_cache() was treating calls with
an empty @code{**kwargs} dictionary as being distinct from calls with no
keywords at all. This did not result in an incorrect answer, but it did
trigger an unexpected cache miss.

@item 
bpo-28552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28552}: Fix @code{distutils.sysconfig} if @ref{3ed,,sys.executable} is
@code{None} or an empty string: use @ref{1909,,os.getcwd()} to initialize
@code{project_base}.  Fix also the distutils build command: don't use
@ref{3ed,,sys.executable} if it is @code{None} or an empty string.

@item 
bpo-35755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35755}: @ref{6db,,shutil.which()} and @code{distutils.spawn.find_executable}
now use @code{os.confstr("CS_PATH")} if available instead of
@ref{1de4,,os.defpath}, if the @code{PATH} environment variable is not set.
Moreover, don't use @code{os.confstr("CS_PATH")} nor @ref{1de4,,os.defpath} if
the @code{PATH} environment variable is set to an empty string.

@item 
bpo-25430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25430}: improve performance of @code{IPNetwork.__contains__()}

@item 
bpo-30485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30485}: Path expressions in xml.etree.ElementTree can now avoid
explicit namespace prefixes for tags (or the "@{namespace@}tag" notation) by
passing a default namespace with an empty string prefix.

@item 
bpo-36613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36613}: Fix @ref{b,,asyncio} wait() not removing callback if exception

@item 
bpo-36598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36598}: Fix @code{isinstance} check for Mock objects with spec when the
code is executed under tracing. Patch by Karthikeyan Singaravelan.

@item 
bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748}: In development mode (@ref{16f,,-X} @code{dev}) and in debug build,
the @ref{505,,io.IOBase} destructor now logs @code{close()} exceptions. These
exceptions are silent by default in release mode.

@item 
bpo-36575@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36575}: The @code{_lsprof} module now uses internal timer same to
@code{time.perf_counter()} by default. @code{gettimeofday(2)} was used on Unix.
New timer has better resolution on most Unix platforms and timings are no
longer impacted by system clock updates since @code{perf_counter()} is
monotonic. Patch by Inada Naoki.

@item 
bpo-33461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33461}: @code{json.loads} now emits @code{DeprecationWarning} when
@code{encoding} option is specified.  Patch by Matthias Bussonnier.

@item 
bpo-36559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36559}: The random module now prefers the lean internal _sha512 module
over hashlib for seed(version=2) to optimize import time.

@item 
bpo-17561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17561}: Set backlog=None as the default for socket.create_server.

@item 
bpo-34373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34373}: Fix @ref{1401,,time.mktime()} error handling on AIX for year before
1970.

@item 
bpo-36232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36232}: Improve error message when trying to open existing DBM database
that actually doesn't exist. Patch by Marco Rougeth.

@item 
bpo-36546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36546}: Add statistics.quantiles()

@item 
bpo-36050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36050}: Optimized @code{http.client.HTTPResponse.read()} for large
response. Patch by Inada Naoki.

@item 
bpo-36522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36522}: If `debuglevel' is set to >0 in @ref{73,,http.client}, print all
values for headers with multiple values for the same header name. Patch by
Matt Houglum.

@item 
bpo-36492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36492}: Deprecated passing required arguments like `func' as keyword
arguments in functions which should accept arbitrary keyword arguments and
pass them to other function. Arbitrary keyword arguments (even with names
"self" and "func") can now be passed to these functions if the required
arguments are passed as positional arguments.

@item 
bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}: Add statistics.geometric_mean().

@item 
bpo-30427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30427}: @code{os.path.normcase()} relies on @code{os.fspath()} to check the
type of its argument. Redundant checks have been removed from its
@code{posixpath.normcase()} and @code{ntpath.normcase()} implementations. Patch
by Wolfgang Maier.

@item 
bpo-36385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36385}: Stop rejecting IPv4 octets for being ambiguously octal. Leading
zeros are ignored, and no longer are assumed to specify octal octets.
Octets are always decimal numbers. Octets must still be no more than three
digits, including leading zeroes.

@item 
bpo-36434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36434}: Errors during writing to a ZIP file no longer prevent to
properly close it.

@item 
bpo-36407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36407}: Fixed wrong indentation writing for CDATA section in
xml.dom.minidom. Patch by Vladimir Surjaninov.

@item 
bpo-36326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36326}: inspect.getdoc() can now find docstrings for member objects
when __slots__ is a dictionary.

@item 
bpo-36366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36366}: Calling @code{stop()} on an unstarted or stopped
@ref{1092,,unittest.mock.patch()} object will now return @code{None} instead of
raising @ref{244,,RuntimeError}, making the method idempotent. Patch by
Karthikeyan Singaravelan.

@item 
bpo-36348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36348}: The @code{imap.IMAP4.logout()} method no longer ignores silently
arbitrary exceptions.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Add time module support and fix test_time failures for VxWorks.

@item 
bpo-36227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36227}: Added support for keyword arguments @code{default_namespace} and
@code{xml_declaration} in functions @code{ElementTree.tostring()} and
@code{ElementTree.tostringlist()}.

@item 
bpo-36004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36004}: Added new alternate constructors
@ref{bdf,,datetime.date.fromisocalendar()} and
@ref{be0,,datetime.datetime.fromisocalendar()}, which construct date objects
from ISO year, week number and weekday; these are the inverse of each
class's @code{isocalendar} method. Patch by Paul Ganssle.

@item 
bpo-35936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35936}: @ref{95,,modulefinder} no longer depends on the deprecated
@ref{7a,,imp} module, and the initializer for
@ref{1de5,,modulefinder.ModuleFinder} now has immutable default arguments.
Patch by Brandt Bucher.

@item 
bpo-35376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35376}: @ref{95,,modulefinder} correctly handles modules that have the
same name as a bad package. Patch by Brandt Bucher.

@item 
bpo-17396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17396}: @ref{95,,modulefinder} no longer crashes when encountering syntax
errors in followed imports. Patch by Brandt Bucher.

@item 
bpo-35934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35934}: Added @ref{c20,,create_server()} and
@ref{c21,,has_dualstack_ipv6()} convenience functions to automate the
necessary tasks usually involved when creating a server socket, including
accepting both IPv4 and IPv6 connections on the same socket.  (Contributed
by Giampaolo Rodola in bpo-17561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17561}.)

@item 
bpo-23078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23078}: Add support for @ref{48e,,classmethod()} and @ref{453,,staticmethod()} to
@ref{1934,,unittest.mock.create_autospec()}.  Initial patch by Felipe Ochoa.

@item 
bpo-35416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35416}: Fix potential resource warnings in distutils. Patch by Mickaël
Schoentgen.

@item 
bpo-25451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25451}: Add transparency methods to @code{tkinter.PhotoImage}.  Patch
by Zackery Spytz.

@item 
bpo-35082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35082}: Don't return deleted attributes when calling dir on a
@ref{c3f,,unittest.mock.Mock}.

@item 
bpo-34547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34547}: @ref{1dd3,,wsgiref.handlers.BaseHandler} now handles abrupt client
connection terminations gracefully. Patch by Petter Strandmark.

@item 
bpo-31658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31658}: @ref{1de6,,xml.sax.parse()} now supports @ref{5a1,,path-like}. Patch by Mickaël Schoentgen.

@item 
bpo-34139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34139}: Remove stale unix datagram socket before binding

@item 
bpo-33530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33530}: Implemented Happy Eyeballs in @code{asyncio.create_connection()}.
Added two new arguments, `happy_eyeballs_delay' and `interleave', to
specify Happy Eyeballs behavior.

@item 
bpo-33291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33291}: Do not raise AttributeError when calling the inspect functions
isgeneratorfunction, iscoroutinefunction, isasyncgenfunction on a method
created from an arbitrary callable. Instead, return False.

@item 
bpo-31310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31310}: Fix the multiprocessing.semaphore_tracker so it is reused by
child processes

@item 
bpo-31292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31292}: Fix @code{setup.py check --restructuredtext} for files containing
@code{include} directives.
@end itemize

@node ドキュメント<53>,テスト<51>,ライブラリ<159>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id720}@anchor{1de7}
@subsubsection ドキュメント



@itemize -

@item 
bpo-36625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36625}: Remove obsolete comments from docstrings in fractions.Fraction

@item 
bpo-30840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30840}: Document relative imports

@item 
bpo-36523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36523}: Add docstring for io.IOBase.writelines().

@item 
bpo-36425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36425}: New documentation translation: Simplified Chinese@footnote{https://docs.python.org/zh-cn/}.

@item 
bpo-36345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36345}: Avoid the duplication of code from @code{Tools/scripts/serve.py}
in using the @code{literalinclude} directive for the basic
wsgiref-based web server in the documentation of @ref{11e,,wsgiref}.
Contributed by Stéphane Wirtel.

@item 
bpo-36345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36345}: Using the code of the @code{Tools/scripts/serve.py} script as an
example in the @ref{11e,,wsgiref} documentation.  Contributed by Stéphane
Wirtel.

@item 
bpo-36157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36157}: Added documentation for PyInterpreterState_Main().

@item 
bpo-33043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33043}: Updates the docs.python.org page with the addition of a
'Contributing to Docs' link at the end of the page (between 'Reporting
Bugs' and 'About Documentation'). Updates the 'Found a Bug' page with
additional links and information in the Documentation Bugs section.

@item 
bpo-35581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35581}: @@typing.type_check_only now allows type stubs to mark functions
and classes not available during runtime.

@item 
bpo-33832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33832}: Add glossary entry for 'magic method'.

@item 
bpo-32913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32913}: Added re.Match.groupdict example to regex HOWTO.
@end itemize

@node テスト<51>,ビルド<59>,ドキュメント<53>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id721}@anchor{1de8}
@subsubsection テスト



@itemize -

@item 
bpo-36719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36719}: regrtest now always detects uncollectable objects. Previously,
the check was only enabled by @code{--findleaks}. The check now also works
with @code{-jN/--multiprocess N}. @code{--findleaks} becomes a deprecated alias
to @code{--fail-env-changed}.

@item 
bpo-36725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36725}: When using multiprocessing mode (-jN), regrtest now better
reports errors if a worker process fails, and it exits immediately on a
worker thread failure or when interrupted.

@item 
bpo-36454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36454}: Change test_time.test_monotonic() to test only the lower bound
of elapsed time after a sleep command rather than the upper bound. This
prevents unnecessary test failures on slow buildbots. Patch by Victor
Stinner.

@item 
bpo-32424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32424}: Improve test coverage for xml.etree.ElementTree. Patch by
Gordon P. Hemsley.

@item 
bpo-32424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32424}: Fix typo in test_cyclic_gc() test for xml.etree.ElementTree.
Patch by Gordon P. Hemsley.

@item 
bpo-36635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36635}: Add a new @code{_testinternalcapi} module to test the internal
C API.

@item 
bpo-36629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36629}: Fix @code{test_imap4_host_default_value()} of @code{test_imaplib}:
catch also @ref{1de9,,errno.ENETUNREACH} error.

@item 
bpo-36611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36611}: Fix @code{test_sys.test_getallocatedblocks()} when
@ref{105,,tracemalloc} is enabled.

@item 
bpo-36560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36560}: Fix reference leak hunting in regrtest: compute also deltas (of
reference count, allocated memory blocks, file descriptor count) during
warmup, to ensure that everything is initialized before starting to hunt
reference leaks.

@item 
bpo-36565@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36565}: Fix reference hunting (@code{python3 -m test -R 3:3}) when Python
has no built-in abc module.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Port test_resource to VxWorks: skip tests cases setting
RLIMIT_FSIZE and RLIMIT_CPU.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix test_tabnanny on VxWorks: adjust ENOENT error message.

@item 
bpo-36436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36436}: Fix @code{_testcapi.pymem_buffer_overflow()}: handle memory
allocation failure.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix test_utf8_mode on VxWorks: Python always use UTF-8 on
VxWorks.

@item 
bpo-36341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36341}: Fix tests that may fail with PermissionError upon calling
bind() on AF_UNIX sockets.
@end itemize

@node ビルド<59>,Windows<52>,テスト<51>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id722}@anchor{1dea}
@subsubsection ビルド



@itemize -

@item 
bpo-36747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36747}: Remove the stale scriptsinstall Makefile target.

@item 
bpo-21536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21536}: On Unix, C extensions are no longer linked to libpython except
on Android and Cygwin.

It is now possible for a statically linked Python to load a C extension
built using a shared library Python.

When Python is embedded, @code{libpython} must not be loaded with
@code{RTLD_LOCAL}, but @code{RTLD_GLOBAL} instead. Previously, using
@code{RTLD_LOCAL}, it was already not possible to load C extensions which
were not linked to @code{libpython}, such as C extensions of the standard
library built by the @code{*shared*} section of @code{Modules/Setup}.

distutils, python-config and python-config.py have been modified.

@item 
bpo-36707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36707}: @code{./configure --with-pymalloc} no longer adds the @code{m} flag
to SOABI (sys.implementation.cache_tag). Enabling or disabling pymalloc
has no impact on the ABI.

@item 
bpo-36635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36635}: Change @code{PyAPI_FUNC(type)}, @code{PyAPI_DATA(type)} and
@code{PyMODINIT_FUNC} macros of @code{pyport.h} when @code{Py_BUILD_CORE_MODULE} is
defined. The @code{Py_BUILD_CORE_MODULE} define must be now be used to build
a C extension as a dynamic library accessing Python internals: export the
@code{PyInit_@var{xxx}()} function in DLL exports on Windows.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Don't build the @code{_crypt} extension on VxWorks.

@item 
bpo-36618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36618}: Add @code{-fmax-type-align=8} to CFLAGS when clang compiler is
detected. The pymalloc memory allocator aligns memory on 8 bytes. On
x86-64, clang expects alignment on 16 bytes by default and so uses MOVAPS
instruction which can lead to segmentation fault. Instruct clang that
Python is limited to alignment on 8 bytes to use MOVUPS instruction
instead: slower but don't trigger a SIGSEGV if the memory is not aligned
on 16 bytes. Sadly, the flag must be added to @code{CFLAGS} and not just
@code{CFLAGS_NODIST}, since third party C extensions can have the same issue.

@item 
bpo-36605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36605}: @code{make tags} and @code{make TAGS} now also parse
@code{Modules/_io/*.c} and @code{Modules/_io/*.h}.

@item 
bpo-36465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36465}: Release builds and debug builds are now ABI compatible:
defining the @code{Py_DEBUG} macro no longer implies the @code{Py_TRACE_REFS}
macro, which introduces the only ABI incompatibility. The
@code{Py_TRACE_REFS} macro, which adds the @ref{28e,,sys.getobjects()} function
and the 
@geindex PYTHONDUMPREFS
@geindex 環境変数; PYTHONDUMPREFS
@ref{b9e,,PYTHONDUMPREFS} environment variable, can be set using
the new @code{./configure --with-trace-refs} build option.

@item 
bpo-36577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36577}: setup.py now correctly reports missing OpenSSL headers and
libraries again.

@item 
bpo-36544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36544}: Fix regression introduced in bpo-36146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36146} refactoring setup.py

@item 
bpo-36508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36508}: @code{python-config --ldflags} no longer includes flags of the
@code{LINKFORSHARED} variable. The @code{LINKFORSHARED} variable must only be
used to build executables.

@item 
bpo-36503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36503}: Remove references to "aix3" and "aix4". Patch by M. Felt.
@end itemize

@node Windows<52>,macOS<41>,ビルド<59>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id723}@anchor{1deb}
@subsubsection Windows



@itemize -

@item 
bpo-35920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35920}: Added platform.win32_edition() and platform.win32_is_iot().
Added support for cross-compiling packages for Windows ARM32. Skip tests
that are not expected to work on Windows IoT Core ARM32.

@item 
bpo-36649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36649}: Remove trailing spaces for registry keys when installed via the
Store.

@item 
bpo-34144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34144}: Fixed activate.bat to correctly update codepage when chcp.com
returns dots in output. Patch by Lorenz Mende.

@item 
bpo-36509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36509}: Added preset-iot layout for Windows IoT ARM containers. This
layout doesn't contain UI components like tkinter or IDLE. It also doesn't
contain files to support on-target builds since Windows ARM32 builds must
be cross-compiled when using MSVC.

@item 
bpo-35941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35941}: enum_certificates function of the ssl module now returns
certificates from all available certificate stores inside windows in a
query instead of returning only certificates from the system wide
certificate store. This includes certificates from these certificate
stores: local machine, local machine enterprise, local machine group
policy, current user, current user group policy, services, users.
ssl.enum_crls() function is changed in the same way to return all
certificate revocation lists inside the windows certificate revocation
list stores.

@item 
bpo-36441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36441}: Fixes creating a venv when debug binaries are installed.

@item 
bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085}: Enable better DLL resolution on Windows by using safe DLL
search paths and adding @ref{bdd,,os.add_dll_directory()}.

@item 
bpo-36010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36010}: Add the venv standard library module to the nuget distribution
for Windows.

@item 
bpo-29515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29515}: Add the following socket module constants on Windows:
IPPROTO_AH IPPROTO_CBT IPPROTO_DSTOPTS IPPROTO_EGP IPPROTO_ESP
IPPROTO_FRAGMENT IPPROTO_GGP IPPROTO_HOPOPTS IPPROTO_ICLFXBM
IPPROTO_ICMPV6 IPPROTO_IDP IPPROTO_IGMP IPPROTO_IGP IPPROTO_IPV4
IPPROTO_IPV6 IPPROTO_L2TP IPPROTO_MAX IPPROTO_ND IPPROTO_NONE IPPROTO_PGM
IPPROTO_PIM IPPROTO_PUP IPPROTO_RDP IPPROTO_ROUTING IPPROTO_SCTP
IPPROTO_ST

@item 
bpo-35947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35947}: Added current version of libffi to cpython-source-deps. Change
_ctypes to use current version of libffi on Windows.

@item 
bpo-34060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34060}: Report system load when running test suite on Windows. Patch by
Ammar Askar. Based on prior work by Jeremy Kloth.

@item 
bpo-31512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31512}: With the Windows 10 Creators Update, non-elevated users can now
create symlinks as long as the computer has Developer Mode enabled.
@end itemize

@node macOS<41>,IDLE<34>,Windows<52>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id724}@anchor{1dec}
@subsubsection macOS



@itemize -

@item 
bpo-34602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34602}: Avoid failures setting macOS stack resource limit with
resource.setrlimit. This reverts an earlier fix for bpo-18075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18075} which forced
a non-default stack size when building the interpreter executable on
macOS.
@end itemize

@node IDLE<34>,Tools/Demos<35>,macOS<41>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id725}@anchor{1ded}
@subsubsection IDLE



@itemize -

@item 
bpo-36429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36429}: Fix starting IDLE with pyshell. Add idlelib.pyshell alias at
top; remove pyshell alias at bottom. Remove obsolete __name__=='__main__'
command.
@end itemize

@node Tools/Demos<35>,C API<54>,IDLE<34>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id726}@anchor{1dee}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-14546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14546}: Fix the argument handling in Tools/scripts/lll.py.
@end itemize

@node C API<54>,,Tools/Demos<35>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id727}@anchor{1def}
@subsubsection C API



@itemize -

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Fix memory leak in @code{Py_SetStandardStreamEncoding()}:
release memory if the function is called twice.

@item 
bpo-36641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36641}: @ref{1df0,,PyDoc_VAR}(name) and @ref{1d5b,,PyDoc_STRVAR}(name, str)
now create @code{static const char name[]} instead of @code{static char name[]}.
Patch by Inada Naoki.

@item 
bpo-36389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36389}: Change the value of @code{CLEANBYTE}, @code{DEADDYTE} and
@code{FORBIDDENBYTE} internal constants used by debug hooks on Python memory
allocators (@ref{e64,,PyMem_SetupDebugHooks()} function). Byte patterns
@code{0xCB}, @code{0xDB} and @code{0xFB} have been replaced with @code{0xCD}, @code{0xDD}
and @code{0xFD} to use the same values than Windows CRT debug @code{malloc()}
and @code{free()}.

@item 
bpo-36443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36443}: Since Python 3.7.0, calling @ref{dc0,,Py_DecodeLocale()} before
@ref{460,,Py_Initialize()} produces mojibake if the @code{LC_CTYPE} locale is
coerced and/or if the UTF-8 Mode is enabled by the user configuration. The
LC_CTYPE coercion and UTF-8 Mode are now disabled by default to fix the
mojibake issue. They must now be enabled explicitly (opt-in) using the new
@code{_Py_PreInitialize()} API with @code{_PyPreConfig}.

@item 
bpo-36025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36025}: Fixed an accidental change to the datetime C API where the
arguments to the @ref{1df1,,PyDate_FromTimestamp()} function were incorrectly
interpreted as a single timestamp rather than an arguments tuple, which
causes existing code to start raising @ref{198,,TypeError}. The
backwards-incompatible change was only present in alpha releases of Python
3.8. Patch by Paul Ganssle.

@item 
bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810}: Modify @code{PyObject_Init} to correctly increase the refcount of
heap-allocated Type objects. Also fix the refcounts of the heap-allocated
types that were either doing this manually or not decreasing the type's
refcount in tp_dealloc
@end itemize

@node Python 3 8 0 alpha 3,Python 3 8 0 alpha 2,Python 3 8 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-8-0-alpha-3}@anchor{1df2}
@subsection Python 3.8.0 alpha 3


`Release date: 2019-03-25'

@menu
* セキュリティ: セキュリティ<45>. 
* Core and Builtins: Core and Builtins<157>. 
* ライブラリ: ライブラリ<160>. 
* ドキュメント: ドキュメント<54>. 
* テスト: テスト<52>. 
* ビルド: ビルド<60>. 
* Windows: Windows<53>. 
* IDLE: IDLE<35>. 
* Tools/Demos: Tools/Demos<36>. 
* C API: C API<55>. 

@end menu

@node セキュリティ<45>,Core and Builtins<157>,,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id728}@anchor{1df3}
@subsubsection セキュリティ



@itemize -

@item 
bpo-36216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36216}: Changes urlsplit() to raise ValueError when the URL contains
characters that decompose under IDNA encoding (NFKC-normalization) into
characters that affect how the URL is parsed.

@item 
bpo-35121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35121}: Don't send cookies of domain A without Domain attribute to
domain B when domain A is a suffix match of domain B while using a
cookiejar with @ref{1df4,,http.cookiejar.DefaultCookiePolicy} policy. Patch
by Karthikeyan Singaravelan.
@end itemize

@node Core and Builtins<157>,ライブラリ<160>,セキュリティ<45>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id729}@anchor{1df5}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-36421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36421}: Fix a possible double decref in _ctypes.c's
@code{PyCArrayType_new()}.

@item 
bpo-36412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36412}: Fix a possible crash when creating a new dictionary.

@item 
bpo-36398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36398}: Fix a possible crash in @code{structseq_repr()}.

@item 
bpo-36256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36256}: Fix bug in parsermodule when parsing a state in a DFA that has
two or more arcs with labels of the same type. Patch by Pablo Galindo.

@item 
bpo-36365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36365}: repr(structseq) is no longer limited to 512 bytes.

@item 
bpo-36374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36374}: Fix a possible null pointer dereference in
@code{merge_consts_recursive()}. Patch by Zackery Spytz.

@item 
bpo-36236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36236}: At Python initialization, the current directory is no longer
prepended to @ref{3e4,,sys.path} if it has been removed.

@item 
bpo-36352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36352}: Python initialization now fails with an error, rather than
silently truncating paths, if a path is too long.

@item 
bpo-36301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36301}: Python initialization now fails if decoding @code{pybuilddir.txt}
configuration file fails at startup.

@item 
bpo-36333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36333}: Fix leak in _PyRuntimeState_Fini. Contributed by Stéphane
Wirtel.

@item 
bpo-36332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36332}: The builtin @ref{4b1,,compile()} can now handle AST objects that
contain assignment expressions. Patch by Pablo Galindo.

@item 
bpo-36282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36282}: Improved error message for too much positional arguments in
some builtin functions.

@item 
bpo-30040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30040}: New empty dict uses fewer memory for now.  It used more memory
than empty dict created by @code{dict.clear()}.  And empty dict creation and
deletion is about 2x faster.  Patch by Inada Naoki.

@item 
bpo-36262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36262}: Fix an unlikely memory leak on conversion from string to float
in the function @code{_Py_dg_strtod()} used by @code{float(str)},
@code{complex(str)}, @ref{f0c,,pickle.load()}, @ref{1df6,,marshal.load()}, etc.

@item 
bpo-36252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36252}: Update Unicode databases to version 12.0.0.

@item 
bpo-36218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36218}: Fix a segfault occurring when sorting a list of heterogeneous
values. Patch contributed by Rémi Lapeyre and Elliot Gorokhovsky.

@item 
bpo-36188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36188}: Cleaned up left-over vestiges of Python 2 unbound method
handling in method objects and documentation. Patch by Martijn Pieters

@item 
bpo-36124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36124}: Add a new interpreter-specific dict and expose it in the C-API
via PyInterpreterState_GetDict().  This parallels PyThreadState_GetDict().
However, extension modules should continue using PyModule_GetState() for
their own internal per-interpreter state.

@item 
bpo-35975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35975}: Add a @code{feature_version} flag to @code{ast.parse()} (documented)
and @code{compile()} (hidden) that allows tweaking the parser to support
older versions of the grammar. In particular, if @code{feature_version} is 5
or 6, the hacks for the @code{async} and @code{await} keyword from PEP 492 are
reinstated. (For 7 or higher, these are unconditionally treated as
keywords, but they are still special tokens rather than @code{NAME} tokens
that the parser driver recognizes.)

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Use UTF-8 as the system encoding on VxWorks.

@item 
bpo-36048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36048}: The @ref{19e,,__index__()} special method will be used
instead of @ref{19d,,__int__()} for implicit conversion of Python
numbers to C integers.  Using the @code{__int__()} method in implicit
conversions has been deprecated.

@item 
bpo-35808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35808}: Retire pgen and use a modified version of pgen2 to generate the
parser. Patch by Pablo Galindo.
@end itemize

@node ライブラリ<160>,ドキュメント<54>,Core and Builtins<157>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id730}@anchor{1df7}
@subsubsection ライブラリ



@itemize -

@item 
bpo-36401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36401}: The class documentation created by pydoc now has a separate
section for readonly properties.

@item 
bpo-36320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36320}: The typing.NamedTuple() class has deprecated the _field_types
attribute in favor of the __annotations__ attribute which carried the same
information. Also, both attributes were converted from OrderedDict to a
regular dict.

@item 
bpo-34745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34745}: Fix @ref{b,,asyncio} ssl memory issues caused by circular
references

@item 
bpo-36324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36324}: Add method to statistics.NormalDist for computing the inverse
cumulative normal distribution.

@item 
bpo-36321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36321}: collections.namedtuple() misspelled the name of an attribute.
To be consistent with typing.NamedTuple, the attribute name should have
been "_field_defaults" instead of "_fields_defaults".  For backwards
compatibility, both spellings are now created.  The misspelled version may
be removed in the future.

@item 
bpo-36297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36297}: "unicode_internal" codec is removed.  It was deprecated since
Python 3.3. Patch by Inada Naoki.

@item 
bpo-36298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36298}: Raise ModuleNotFoundError in pyclbr when a module can't be
found. Thanks to 'mental' for the bug report.

@item 
bpo-36268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36268}: Switch the default format used for writing tars with
@ref{e4,,tarfile} to the modern POSIX.1-2001 pax standard, from the
vendor-specific GNU. Contributed by C.A.M. Gerlach.

@item 
bpo-36285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36285}: Fix integer overflows in the array module. Patch by Stephan
Hohe.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Add _signal module support for VxWorks.

@item 
bpo-36272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36272}: @ref{8b,,logging} does not silently ignore RecursionError anymore.
Patch contributed by Rémi Lapeyre.

@item 
bpo-36280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36280}: Add a kind field to ast.Constant. It is 'u' if the literal has
a 'u' prefix (i.e. a Python 2 style unicode literal), else None.

@item 
bpo-35931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35931}: The @ref{aa,,pdb} @code{debug} command now gracefully handles all
exceptions.

@item 
bpo-36251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36251}: Fix format strings used for stderrprinter and re.Match reprs.
Patch by Stephan Hohe.

@item 
bpo-36235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36235}: Fix @code{CFLAGS} in @code{customize_compiler()} of
@code{distutils.sysconfig}: when the @code{CFLAGS} environment variable is
defined, don't override @code{CFLAGS} variable with the @code{OPT} variable
anymore. Initial patch written by David Malcolm.

@item 
bpo-35807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35807}: Update ensurepip to install pip 19.0.3 and setuptools 40.8.0.

@item 
bpo-36139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36139}: Release GIL when closing @ref{519,,mmap} objects.

@item 
bpo-36179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36179}: Fix two unlikely reference leaks in _hashopenssl. The leaks
only occur in out-of-memory cases.

@item 
bpo-36169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36169}: Add overlap() method to statistics.NormalDist.  Computes the
overlapping coefficient for two normal distributions.

@item 
bpo-36103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36103}: Default buffer size used by @code{shutil.copyfileobj()} is changed
from 16 KiB to 64 KiB on non-Windows platform to reduce system call
overhead. Contributed by Inada Naoki.

@item 
bpo-36130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36130}: Fix @code{pdb} with @code{skip=...} when stepping into a frame
without a @code{__name__} global.  Patch by Anthony Sottile.

@item 
bpo-35652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35652}: shutil.copytree(copy_function=...) erroneously pass DirEntry
instead of a path string.

@item 
bpo-35178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35178}: Ensure custom @ref{1df8,,warnings.formatwarning()} function can
receive @code{line} as positional argument. Based on patch by Tashrif Billah.

@item 
bpo-36106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36106}: Resolve potential name clash with libm's sinpi(). Patch by
Dmitrii Pasechnik.

@item 
bpo-36091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36091}: Clean up reference to async generator in Lib/types. Patch by
Henry Chen.

@item 
bpo-36043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36043}: @code{FileCookieJar} supports @ref{5a1,,path-like object}.
Contributed by Stéphane Wirtel

@item 
bpo-35899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35899}: Enum has been fixed to correctly handle empty strings and
strings with non-Latin characters (ie. 'α', 'א') without crashing.
Original patch contributed by Maxwell. Assisted by Stéphane Wirtel.

@item 
bpo-21269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21269}: Add @code{args} and @code{kwargs} properties to mock call objects.
Contributed by Kumar Akshay.

@item 
bpo-30670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30670}: @code{pprint.pp} 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 @code{pprint.pprint},
@code{pprint.pformat} and @code{pprint.PrettyPrinter}. Contributed by Rémi
Lapeyre.

@item 
bpo-35843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35843}: Implement @code{__getitem__} for @code{_NamespacePath}.  Patch by
Anthony Sottile.

@item 
bpo-35802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35802}: Clean up code which checked presence of @code{os.stat} /
@code{os.lstat} / @code{os.chmod} which are always present.  Patch by Anthony
Sottile.

@item 
bpo-35715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35715}: Librates the return value of a ProcessPoolExecutor
_process_worker after it's no longer needed to free memory

@item 
bpo-35493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35493}: Use @ref{12f7,,multiprocessing.connection.wait()} instead of polling
each 0.2 seconds for worker updates in @code{multiprocessing.Pool}.
Patch by Pablo Galindo.

@item 
bpo-35661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35661}: Store the venv prompt in pyvenv.cfg.

@item 
bpo-35121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35121}: Don't set cookie for a request when the request path is a
prefix match of the cookie's path attribute but doesn't end with "/".
Patch by Karthikeyan Singaravelan.

@item 
bpo-21478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21478}: Calls to a child function created with
@ref{1934,,unittest.mock.create_autospec()} should propagate to the parent.
Patch by Karthikeyan Singaravelan.

@item 
bpo-35198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35198}: Fix C++ extension compilation on AIX
@end itemize

@node ドキュメント<54>,テスト<52>,ライブラリ<160>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id731}@anchor{1df9}
@subsubsection ドキュメント



@itemize -

@item 
bpo-36329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36329}: Declare the path of the Python binary for the usage of
@code{Tools/scripts/serve.py} when executing @code{make -C Doc/ serve}.
Contributed by Stéphane Wirtel

@item 
bpo-36138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36138}: Improve documentation about converting datetime.timedelta to
scalars.

@item 
bpo-21314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21314}: A new entry was added to the Core Language Section of the
Programming FAQ, which explaines the usage of slash(/) in the signature of
a function. Patch by Lysandros Nikolaou
@end itemize

@node テスト<52>,ビルド<60>,ドキュメント<54>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id732}@anchor{1dfa}
@subsubsection テスト



@itemize -

@item 
bpo-36234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36234}: test_posix.PosixUidGidTests: add tests for invalid uid/gid type
(str). Initial patch written by David Malcolm.

@item 
bpo-29571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29571}: Fix @code{test_re.test_locale_flag()}:  use
@code{locale.getpreferredencoding()} rather than @code{locale.getlocale()} to
get the locale encoding. With some locales, @code{locale.getlocale()} returns
the wrong encoding.

@item 
bpo-36123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36123}: Fix race condition in test_socket.
@end itemize

@node ビルド<60>,Windows<53>,テスト<52>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id733}@anchor{1dfb}
@subsubsection ビルド



@itemize -

@item 
bpo-36356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36356}: Fix leaks that led to build failure when configured with
address sanitizer.

@item 
bpo-36146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36146}: Add @code{TEST_EXTENSIONS} constant to @code{setup.py} to allow to
not build test extensions like @code{_testcapi}.

@item 
bpo-36146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36146}: Fix setup.py on macOS: only add @code{/usr/include/ffi} to include
directories of _ctypes, not for all extensions.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Enable build system to cross-build for VxWorks RTOS.
@end itemize

@node Windows<53>,IDLE<35>,ビルド<60>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id734}@anchor{1dfc}
@subsubsection Windows



@itemize -

@item 
bpo-36312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36312}: Fixed decoders for the following code pages: 50220, 50221,
50222, 50225, 50227, 50229, 57002 through 57011, 65000 and 42.

@item 
bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264}: Don't honor POSIX @code{HOME} in @code{os.path.expanduser} on
windows.  Patch by Anthony Sottile.

@item 
bpo-24643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24643}: Fix name collisions due to @code{#define timezone _timezone} in
PC/pyconfig.h.
@end itemize

@node IDLE<35>,Tools/Demos<36>,Windows<53>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id735}@anchor{1dfd}
@subsubsection IDLE



@itemize -

@item 
bpo-36405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36405}: Use dict unpacking in idlelib.

@item 
bpo-36396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36396}: Remove fgBg param of idlelib.config.GetHighlight(). This param
was only used twice and changed the return type.

@item 
bpo-36176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36176}: Fix IDLE autocomplete & calltip popup colors. Prevent conflicts
with Linux dark themes (and slightly darken calltip background).

@item 
bpo-23205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23205}: For the grep module, add tests for findfiles, refactor
findfiles to be a module-level function, and refactor findfiles to use
os.walk.

@item 
bpo-23216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23216}: Add docstrings to IDLE search modules.

@item 
bpo-36152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36152}: Remove colorizer.ColorDelegator.close_when_done and the
corresponding argument of .close().  In IDLE, both have always been None
or False since 2007.

@item 
bpo-32129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32129}: Avoid blurry IDLE application icon on macOS with Tk 8.6. Patch
by Kevin Walzer.

@item 
bpo-36096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36096}: Refactor class variables to instance variables in colorizer.

@item 
bpo-30348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30348}: Increase test coverage of idlelib.autocomplete by 30%. Patch by
Louie Lu
@end itemize

@node Tools/Demos<36>,C API<55>,IDLE<35>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id736}@anchor{1dfe}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-35132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35132}: Fix py-list and py-bt commands of python-gdb.py on gdb7.

@item 
bpo-32217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32217}: Fix freeze script on Windows.
@end itemize

@node C API<55>,,Tools/Demos<36>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id737}@anchor{1dff}
@subsubsection C API



@itemize -

@item 
bpo-36381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36381}: Raise @code{DeprecationWarning} when '#' formats are used for
building or parsing values without @code{PY_SSIZE_T_CLEAN}.

@item 
bpo-36142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36142}: The whole coreconfig.h header is now excluded from
Py_LIMITED_API. Move functions definitions into a new internal
pycore_coreconfig.h header.
@end itemize

@node Python 3 8 0 alpha 2,Python 3 8 0 alpha 1,Python 3 8 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-8-0-alpha-2}@anchor{1e00}
@subsection Python 3.8.0 alpha 2


`Release date: 2019-02-25'

@menu
* Core and Builtins: Core and Builtins<158>. 
* ライブラリ: ライブラリ<161>. 
* ドキュメント: ドキュメント<55>. 
* テスト: テスト<53>. 
* Windows: Windows<54>. 
* IDLE: IDLE<36>. 

@end menu

@node Core and Builtins<158>,ライブラリ<161>,,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id738}@anchor{1e01}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-36052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36052}: Raise a @ref{18e,,SyntaxError} when assigning a value to
@code{__debug__} with the Assignment Operator. Contributed by Stéphane Wirtel
and Pablo Galindo.

@item 
bpo-36012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36012}: Doubled the speed of class variable writes.  When a non-dunder
attribute was updated, there was an unnecessary call to update slots.

@item 
bpo-35942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35942}: The error message emitted when returning invalid types from
@code{__fspath__} in interfaces that allow passing @ref{e4b,,PathLike}
objects has been improved and now it does explain the origin of the error.

@item 
bpo-36016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36016}: @code{gc.get_objects} can now receive an optional parameter
indicating a generation to get objects from. Patch by Pablo Galindo.

@item 
bpo-1054041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1054041}: When the main interpreter exits due to an uncaught
KeyboardInterrupt, the process now exits in the appropriate manner for its
parent process to detect that a SIGINT or ^C terminated the process.  This
allows shells and batch scripts to understand that the user has asked them
to stop.

@item 
bpo-35992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35992}: Fix @code{__class_getitem__()} not being called on a class with a
custom non-subscriptable metaclass.

@item 
bpo-35993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35993}: Fix a crash on fork when using subinterpreters. Contributed by
Stéphane Wirtel

@item 
bpo-35991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35991}: Fix a potential double free in Modules/_randommodule.c.

@item 
bpo-35961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35961}: Fix a crash in slice_richcompare(): use strong references
rather than stolen references for the two temporary internal tuples.

@item 
bpo-35911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35911}: Enable the creation of cell objects by adding a
@code{cell.__new__} method, and expose the type @code{cell} in @code{Lib/types.py}
under the name CellType. Patch by Pierre Glaser.

@item 
bpo-12822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12822}: Use monotonic clock for @code{pthread_cond_timedwait} when
@code{pthread_condattr_setclock} and @code{CLOCK_MONOTONIC} are available.

@item 
bpo-15248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15248}: The compiler emits now syntax warnings in the case when a comma
is likely missed before tuple or list.

@item 
bpo-35886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35886}: The implementation of PyInterpreterState has been moved into
the internal header files (guarded by Py_BUILD_CORE).

@item 
bpo-31506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31506}: Clarify the errors reported when @code{object.__new__} and
@code{object.__init__} receive more than one argument. Contributed by Sanyam
Khurana.

@item 
bpo-35724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35724}: Signal-handling is now guaranteed to happen relative to the
main interpreter.

@item 
bpo-33608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33608}: We added a new internal _Py_AddPendingCall() that operates
relative to the provided interpreter.  This allows us to use the existing
implementation to ask another interpreter to do work that cannot be done
in the current interpreter, like decref an object the other interpreter
owns.  The existing Py_AddPendingCall() only operates relative to the main
interpreter.

@item 
bpo-33989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33989}: Fix a possible crash in @ref{dc8,,list.sort()} when sorting objects
with @code{ob_type->tp_richcompare == NULL}.  Patch by Zackery Spytz.
@end itemize

@node ライブラリ<161>,ドキュメント<55>,Core and Builtins<158>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id739}@anchor{1e02}
@subsubsection ライブラリ



@itemize -

@item 
bpo-35512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35512}: @ref{1967,,unittest.mock.patch.dict()} used as a decorator with
string target resolves the target during function call instead of during
decorator construction. Patch by Karthikeyan Singaravelan.

@item 
bpo-36018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36018}: Add statistics.NormalDist, a tool for creating and manipulating
normal distributions of random variable.  Features a composite class that
treats the mean and standard deviation of measurement data as single
entity.

@item 
bpo-35904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35904}: Added statistics.fmean() as a faster, floating-point variant of
the existing mean() function.

@item 
bpo-35918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35918}: Removed broken @code{has_key} method from
multiprocessing.managers.SyncManager.dict. Contributed by Rémi Lapeyre.

@item 
bpo-18283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18283}: Add support for bytes to @ref{6db,,shutil.which()}.

@item 
bpo-35960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35960}: Fix @ref{195a,,dataclasses.field()} throwing away empty mapping
objects passed as metadata.

@item 
bpo-35500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35500}: Write expected and actual call parameters on separate lines in
@ref{1e03,,unittest.mock.Mock.assert_called_with()} assertion errors.
Contributed by Susan Su.

@item 
bpo-35931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35931}: The @ref{aa,,pdb} @code{debug} command now gracefully handles syntax
errors.

@item 
bpo-24209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24209}: In http.server script, rely on getaddrinfo to bind to preferred
address based on the bind parameter. Now default bind or binding to a name
may bind to IPv6 or dual-stack, depending on the environment.

@item 
bpo-35321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35321}: Set @code{__spec__.origin} of  @code{_frozen_importlib} to frozen so
that it matches the behavior of @code{_frozen_importlib_external}.  Patch by
Nina Zakharenko.

@item 
bpo-35378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35378}: Fix a reference issue inside @code{multiprocessing.Pool} that
caused the pool to remain alive if it was deleted without being closed or
terminated explicitly. A new strong reference is added to the pool
iterators to link the lifetime of the pool to the lifetime of its
iterators so the pool does not get destroyed if a pool iterator is still
alive.

@item 
bpo-34294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34294}: re module, fix wrong capturing groups in rare cases.
@ref{1444,,re.search()}, @ref{122b,,re.findall()}, @ref{5a3,,re.sub()} and other functions
that scan through string looking for a match, should reset capturing
groups between two match attempts. Patch by Ma Lin.

@item 
bpo-35615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35615}: @ref{11a,,weakref}: Fix a RuntimeError when copying a
WeakKeyDictionary or a WeakValueDictionary, due to some keys or values
disappearing while iterating.

@item 
bpo-35606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35606}: Implement @ref{bf7,,math.prod()} as analogous function to
@ref{695,,sum()} that returns the product of a 'start' value (default: 1) times
an iterable of numbers. Patch by Pablo Galindo.

@item 
bpo-32417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32417}: Performing arithmetic between @ref{4e2,,datetime.datetime}
subclasses and @ref{bc3,,datetime.timedelta} now returns an object of the
same type as the @ref{4e2,,datetime.datetime} subclass. As a result,
@ref{bc4,,datetime.datetime.astimezone()} and alternate constructors like
@ref{711,,datetime.datetime.now()} and @code{datetime.fromtimestamp()} called
with a @code{tz} argument now `also' retain their subclass.

@item 
bpo-35153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35153}: Add `headers' optional keyword-only parameter to
@ref{c4c,,xmlrpc.client.ServerProxy}, @code{xmlrpc.client.Transport} and
@code{xmlrpc.client.SafeTransport}.  Patch by Cédric Krier.

@item 
bpo-34572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34572}: Fix C implementation of pickle.loads to use importlib's locking
mechanisms, and thereby avoid using partially loaded modules. Patch by Tim
Burgess.
@end itemize

@node ドキュメント<55>,テスト<53>,ライブラリ<161>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id740}@anchor{1e04}
@subsubsection ドキュメント



@itemize -

@item 
bpo-36083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36083}: Fix formatting of --check-hash-based-pycs options in the
manpage Synopsis.

@item 
bpo-36007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36007}: Bump minimum sphinx version to 1.8.  Patch by Anthony Sottile.

@item 
bpo-22062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22062}: Update documentation and docstrings for pathlib. Original patch
by Mike Short.
@end itemize

@node テスト<53>,Windows<54>,ドキュメント<55>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id741}@anchor{1e05}
@subsubsection テスト



@itemize -

@item 
bpo-27313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27313}: Avoid test_ttk_guionly ComboboxTest failure with macOS Cocoa
Tk.

@item 
bpo-36019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36019}: Add test.support.TEST_HTTP_URL and replace references of
@indicateurl{http://www.example.com} by this new constant. Contributed by Stéphane
Wirtel.

@item 
bpo-36037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36037}: Fix test_ssl for strict OpenSSL configuration like RHEL8 strict
crypto policy. Use older TLS version for minimum TLS version of the server
SSL context if needed, to test TLS version older than default minimum TLS
version.

@item 
bpo-35798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35798}: Added @code{test.support.check_syntax_warning()}.

@item 
bpo-35505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35505}: Make test_imap4_host_default_value independent on whether the
local IMAP server is running.

@item 
bpo-35917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35917}: multiprocessing: provide unit tests for SyncManager and
SharedMemoryManager classes + all the shareable types which are supposed
to be supported by them.  (patch by Giampaolo Rodola)

@item 
bpo-35704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35704}: Skip @code{test_shutil.test_unpack_archive_xztar} to prevent a
MemoryError on 32-bit AIX when MAXDATA setting is less than 0x20000000.

Patch by Michael Felt (aixtools)

@item 
bpo-34720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34720}: Assert m_state != NULL to mimic GC traversal functions that do
not correctly handle module creation when the module state has not been
created.
@end itemize

@node Windows<54>,IDLE<36>,テスト<53>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id742}@anchor{1e06}
@subsubsection Windows



@itemize -

@item 
bpo-35976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35976}: Added ARM build support to Windows build files in PCBuild.

@item 
bpo-35692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35692}: @code{pathlib} no longer raises when checking file and directory
existence on drives that are not ready

@item 
bpo-35872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35872}: Uses the base Python executable when invoking venv in a virtual
environment

@item 
bpo-35873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35873}: Prevents venv paths being inherited by child processes

@item 
bpo-35299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35299}: Fix sysconfig detection of the source directory and distutils
handling of pyconfig.h during PGO profiling
@end itemize

@node IDLE<36>,,Windows<54>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id743}@anchor{1e07}
@subsubsection IDLE



@itemize -

@item 
bpo-24310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24310}: IDLE -- Document settings dialog font tab sample.

@item 
bpo-35833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35833}: Revise IDLE doc for control codes sent to Shell. Add a code
example block.

@item 
bpo-35689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35689}: Add docstrings and unittests for colorizer.py.
@end itemize

@node Python 3 8 0 alpha 1,Python 3 7 0 final,Python 3 8 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-8-0-alpha-1}@anchor{1e08}
@subsection Python 3.8.0 alpha 1


`Release date: 2019-02-03'

@menu
* セキュリティ: セキュリティ<46>. 
* Core and Builtins: Core and Builtins<159>. 
* ライブラリ: ライブラリ<162>. 
* ドキュメント: ドキュメント<56>. 
* テスト: テスト<54>. 
* ビルド: ビルド<61>. 
* Windows: Windows<55>. 
* macOS: macOS<42>. 
* IDLE: IDLE<37>. 
* Tools/Demos: Tools/Demos<37>. 
* C API: C API<56>. 

@end menu

@node セキュリティ<46>,Core and Builtins<159>,,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id744}@anchor{1e09}
@subsubsection セキュリティ



@itemize -

@item 
bpo-35746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35746}: 
@geindex Common Vulnerabilities and Exposures; CVE 2019-5010
CVE 2019-5010@footnote{https://www.cve.org/CVERecord?id=CVE-2019-5010}: Fix a NULL pointer deref in ssl module. The
cert parser did not handle CRL distribution points with empty DP or URI
correctly. A malicious or buggy certificate can result into segfault.
Vulnerability (TALOS-2018-0758) reported by Colin Read and Nicolas Edet of
Cisco.

@item 
bpo-34812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34812}: The @ref{b57,,-I} command line option (run Python in isolated
mode) is now also copied by the @ref{98,,multiprocessing} and @code{distutils}
modules when spawning child processes. Previously, only @ref{b56,,-E} and
@ref{15a6,,-s} options (enabled by @ref{b57,,-I}) were copied.

@item 
bpo-34791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34791}: The xml.sax and xml.dom.domreg no longer use environment
variables to override parser implementations when
sys.flags.ignore_environment is set by -E or -I arguments.

@item 
bpo-17239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17239}: The xml.sax and xml.dom.minidom parsers no longer processes
external entities by default. External DTD and ENTITY declarations no
longer load files or create network connections.

@item 
bpo-34623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34623}: 
@geindex Common Vulnerabilities and Exposures; CVE 2018-14647
CVE 2018-14647@footnote{https://www.cve.org/CVERecord?id=CVE-2018-14647}: The C accelerated _elementtree module now
initializes hash randomization salt from _Py_HashSecret instead of
libexpat's default CSPRNG.

@item 
bpo-34405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34405}: Updated to OpenSSL 1.1.0i for Windows builds.

@item 
bpo-33871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33871}: Fixed sending the part of the file in @ref{d05,,os.sendfile()} on
macOS.  Using the `trailers' argument could cause sending more bytes from
the input file than was specified.

@item 
bpo-32533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32533}: Fixed thread-safety of error handling in _ssl.

@item 
bpo-33136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33136}: Harden ssl module against LibreSSL 
@geindex Common Vulnerabilities and Exposures; CVE 2018-8970
CVE 2018-8970@footnote{https://www.cve.org/CVERecord?id=CVE-2018-8970}.
X509_VERIFY_PARAM_set1_host() is called with an explicit namelen. A new
test ensures that NULL bytes are not allowed.

@item 
bpo-33001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33001}: Minimal fix to prevent buffer overrun in os.symlink on Windows

@item 
bpo-32981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32981}: Regexes in difflib and poplib were vulnerable to catastrophic
backtracking. These regexes formed potential DOS vectors (REDOS). They
have been refactored. This resolves 
@geindex Common Vulnerabilities and Exposures; CVE 2018-1060
CVE 2018-1060@footnote{https://www.cve.org/CVERecord?id=CVE-2018-1060} and 
@geindex Common Vulnerabilities and Exposures; CVE 2018-1061
CVE 2018-1061@footnote{https://www.cve.org/CVERecord?id=CVE-2018-1061}.
Patch by Jamie Davis.

@item 
bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414}: The ssl module now allows users to perform their own IDN
en/decoding when using SNI.
@end itemize

@node Core and Builtins<159>,ライブラリ<162>,セキュリティ<46>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id745}@anchor{1e0a}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-35877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35877}: Make parenthesis optional for named expressions in while
statement. Patch by Karthikeyan Singaravelan.

@item 
bpo-35814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35814}: Allow same right hand side expressions in annotated assignments
as in normal ones. In particular, @code{x: Tuple[int, int] = 1, 2} (without
parentheses on the right) is now allowed.

@item 
bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766}: Add the option to parse PEP 484 type comments in the ast
module. (Off by default.) This is merging the key functionality of the
third party fork thereof,
[typed_ast](@indicateurl{https://github.com/python/typed_ast}).

@item 
bpo-35713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35713}: Reorganize Python initialization to get working exceptions and
sys.stderr earlier.

@item 
bpo-33416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33416}: Add end line and end column position information to the Python
AST nodes. This is a C-level backwards incompatible change.

@item 
bpo-35720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35720}: Fixed a minor memory leak in pymain_parse_cmdline_impl function
in Modules/main.c

@item 
bpo-35634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35634}: @code{func(**kwargs)} will now raise an error when @code{kwargs} is a
mapping containing multiple entries with the same key. An error was
already raised when other keyword arguments are passed before @code{**kwargs}
since Python 3.6.

@item 
bpo-35623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35623}: Fix a crash when sorting very long lists. Patch by Stephan
Hohe.

@item 
bpo-35214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35214}: clang Memory Sanitizer build instrumentation was added to work
around false positives from posix, socket, time, test_io, and
test_faulthandler.

@item 
bpo-35560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35560}: Fix an assertion error in @ref{199,,format()} in debug build for
floating-point formatting with "n" format, zero padding and small width.
Release build is not impacted. Patch by Karthikeyan Singaravelan.

@item 
bpo-35552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35552}: Format characters @code{%s} and @code{%V} in
@ref{62b,,PyUnicode_FromFormat()} and @code{%s} in @ref{1e0b,,PyBytes_FromFormat()}
no longer read memory past the limit if `precision' is specified.

@item 
bpo-35504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35504}: Fix segfaults and @ref{795,,SystemError}s when deleting certain
attributes. Patch by Zackery Spytz.

@item 
bpo-35504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35504}: Fixed a SystemError when delete the characters_written
attribute of an OSError.

@item 
bpo-35494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35494}: Improved syntax error messages for unbalanced parentheses in
f-string.

@item 
bpo-35444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35444}: Fixed error handling in pickling methods when fail to look up
builtin "getattr". Sped up pickling iterators.

@item 
bpo-35436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35436}: Fix various issues with memory allocation error handling.
Patch by Zackery Spytz.

@item 
bpo-35423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35423}: Separate the signal handling trigger in the eval loop from the
"pending calls" machinery. There is no semantic change and the difference
in performance is insignificant.

@item 
bpo-35357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35357}: Internal attributes' names of unittest.mock._Call and
unittest.mock.MagicProxy (name, parent & from_kall) are now prefixed with
_mock_ in order to prevent clashes with widely used object attributes.
Fixed minor typo in test function name.

@item 
bpo-35372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35372}: Fixed the code page decoder for input longer than 2 GiB
containing undecodable bytes.

@item 
bpo-35336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35336}: Fix PYTHONCOERCECLOCALE=1 environment variable: only coerce the
C locale if the LC_CTYPE locale is "C".

@item 
bpo-31241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31241}: The `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.

@item 
bpo-33954@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33954}: For @ref{833,,str.format()}, @code{float.__format__()} and
@code{complex.__format__()} methods for non-ASCII decimal point when using
the "n" formatter.

@item 
bpo-35269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35269}: Fix a possible segfault involving a newly created coroutine.
Patch by Zackery Spytz.

@item 
bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224}: Implement 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/} (assignment expressions). Patch by Emily
Morehouse.

@item 
bpo-32492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32492}: Speed up @code{namedtuple()} attribute access by 1.6x using a C
fast-path for the name descriptors. Patch by Pablo Galindo.

@item 
bpo-35214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35214}: Fixed an out of bounds memory access when parsing a truncated
unicode escape sequence at the end of a string such as @code{'\N'}.  It would
read one byte beyond the end of the memory allocation.

@item 
bpo-35214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35214}: The interpreter and extension modules have had annotations
added so that they work properly under clang's Memory Sanitizer.  A new
configure flag --with-memory-sanitizer has been added to make test builds
of this nature easier to perform.

@item 
bpo-35193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35193}: Fix an off by one error in the bytecode peephole optimizer
where it could read bytes beyond the end of bounds of an array when
removing unreachable code. This bug was present in every release of Python
3.6 and 3.7 until now.

@item 
bpo-35169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35169}: Improved error messages for forbidden assignments.

@item 
bpo-34022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34022}: Fix handling of hash-based bytecode files in @ref{138,,zipimport}.
Patch by Elvis Pranskevichus.

@item 
bpo-28401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28401}: Debug builds will no longer to attempt to import extension
modules built for the ABI as they were never compatible to begin with.
Patch by Stefano Rivera.

@item 
bpo-29341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29341}: Clarify in the docstrings of @ref{a5,,os} methods that path-like
objects are also accepted as input parameters.

@item 
bpo-35050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35050}: @ref{d1,,socket}: Fix off-by-one bug in length check for
@code{AF_ALG} name and type.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Raise @ref{2ec,,ValueError} instead of @ref{a81,,OverflowError} in case
of a negative @code{_length_} in a @ref{1e0c,,ctypes.Array} subclass.  Also
raise @ref{198,,TypeError} instead of @ref{5f0,,AttributeError} for non-integer
@code{_length_}. Original patch by Oren Milman.

@item 
bpo-16806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16806}: Fix @code{lineno} and @code{col_offset} for multi-line string tokens.

@item 
bpo-35029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35029}: @ref{1ae,,SyntaxWarning} raised as an exception at code generation
time will be now replaced with a @ref{18e,,SyntaxError} for better error
reporting.

@item 
bpo-34983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34983}: Expose @ref{1e0d,,symtable.Symbol.is_nonlocal()} in the symtable
module. Patch by Pablo Galindo.

@item 
bpo-34974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34974}: @ref{192,,bytes} and @ref{344,,bytearray} constructors no longer
convert unexpected exceptions (e.g. @ref{179e,,MemoryError} and
@ref{bc5,,KeyboardInterrupt}) to @ref{198,,TypeError}.

@item 
bpo-34939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34939}: Allow annotated names in module namespace that are declared
global before the annotation happens. Patch by Pablo Galindo.

@item 
bpo-34973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34973}: Fixed crash in @ref{192,,bytes()} when the @ref{24d,,list} argument is
mutated while it is iterated.

@item 
bpo-34876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34876}: The `lineno' and `col_offset' attributes of the AST for
decorated function and class refer now to the position of the
corresponding @code{def}, @code{async def} and @code{class} instead of the position
of the first decorator. This leads to more correct line reporting in
tracing. This is the only case when the position of child AST nodes can
precede the position of the parent AST node.

@item 
bpo-34879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34879}: Fix a possible null pointer dereference in bytesobject.c.
Patch by Zackery Spytz.

@item 
bpo-34784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34784}: Fix the implementation of PyStructSequence_NewType in order to
create heap allocated StructSequences.

@item 
bpo-32912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32912}: A @ref{1ae,,SyntaxWarning} is now emitted instead of a
@ref{1a3,,DeprecationWarning} for invalid escape sequences in string and bytes
literals.

@item 
bpo-34854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34854}: Fixed a crash in compiling string annotations containing a
lambda with a keyword-only argument that doesn't have a default value.

@item 
bpo-34850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34850}: The compiler now produces a @ref{1ae,,SyntaxWarning} when identity
checks (@code{is} and @code{is not}) are used with certain types of literals
(e.g. strings, ints).  These can often work by accident in CPython, but
are not guaranteed by the language spec.  The warning advises users to use
equality tests (@code{==} and @code{!=}) instead.

@item 
bpo-34824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34824}: Fix a possible null pointer dereference in Modules/_ssl.c.
Patch by Zackery Spytz.

@item 
bpo-30156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30156}: The C function @code{property_descr_get()} uses a "cached" tuple
to optimize function calls. But this tuple can be discovered in debug mode
with @ref{28e,,sys.getobjects()}. Remove the optimization, it's not really
worth it and it causes 3 different crashes last years.

@item 
bpo-34762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34762}: Fix contextvars C API to use PyObject* pointer types.

@item 
bpo-34751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34751}: The hash function for tuples is now based on xxHash which gives
better collision results on (formerly) pathological cases. Additionally,
on 64-bit systems it improves tuple hashes in general. Patch by Jeroen
Demeyer with substantial contributions by Tim Peters.

@item 
bpo-34735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34735}: Fix a memory leak in Modules/timemodule.c.  Patch by Zackery
Spytz.

@item 
bpo-34683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34683}: Fixed a bug where some SyntaxError error pointed to locations
that were off-by-one.

@item 
bpo-34651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34651}: Only allow the main interpreter to fork.  The avoids the
possibility of affecting the main interpreter, which is critical to
operation of the runtime.

@item 
bpo-34653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34653}: Remove unused function PyParser_SimpleParseStringFilename.

@item 
bpo-32236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32236}: Warn that line buffering is not supported if @ref{316,,open()} is
called with binary mode and @code{buffering=1}.

@item 
bpo-34641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34641}: Further restrict the syntax of the left-hand side of keyword
arguments in function calls. In particular, @code{f((keyword)=arg)} is now
disallowed.

@item 
bpo-34637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34637}: Make the `start' argument to `sum()' visible as a keyword
argument.

@item 
bpo-1621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1621}: Do not assume signed integer overflow behavior (C undefined
behavior) when performing set hash table resizing.

@item 
bpo-34588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34588}: Fix an off-by-one in the recursive call pruning feature of
traceback formatting.

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: On Windows, the LC_CTYPE is now set to the user preferred
locale at startup. Previously, the LC_CTYPE locale was "C" at startup, but
changed when calling setlocale(LC_CTYPE, "") or setlocale(LC_ALL, "").

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: Standard streams like sys.stdout now use the "surrogateescape"
error handler, instead of "strict", on the POSIX locale (when the C locale
is not coerced and the UTF-8 Mode is disabled).

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: Fix the error handler of standard streams like sys.stdout:
PYTHONIOENCODING=":" is now ignored instead of setting the error handler
to "strict".

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: Python now gets the locale encoding with C code to initialize
the encoding of standard streams like sys.stdout. Moreover, the encoding
is now initialized to the Python codec name to get a normalized encoding
name and to ensure that the codec is loaded. The change avoids importing
_bootlocale and _locale modules at startup by default.

@item 
bpo-34527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34527}: On FreeBSD, Py_DecodeLocale() and Py_EncodeLocale() now also
forces the ASCII encoding if the LC_CTYPE locale is "POSIX", not only if
the LC_CTYPE locale is "C".

@item 
bpo-34527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34527}: The UTF-8 Mode is now also enabled by the "POSIX" locale, not
only by the "C" locale.

@item 
bpo-34403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34403}: On HP-UX with C or POSIX locale, sys.getfilesystemencoding()
now returns "ascii" instead of "roman8" (when the UTF-8 Mode is disabled
and the C locale is not coerced).

@item 
bpo-34523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34523}: The Python filesystem encoding is now read earlier during the
Python initialization.

@item 
bpo-12458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12458}: Tracebacks show now correct line number for subexpressions in
multiline expressions. Tracebacks show now the line number of the first
line for multiline expressions instead of the line number of the last
subexpression.

@item 
bpo-34408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34408}: Prevent a null pointer dereference and resource leakage in
@code{PyInterpreterState_New()}.

@item 
bpo-34400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34400}: Fix undefined behavior in parsetok.c.  Patch by Zackery Spytz.

@item 
bpo-33073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33073}: Added as_integer_ratio to ints to make them more interoperable
with floats.

@item 
bpo-34377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34377}: Update valgrind suppression list to use
@code{_PyObject_Free}/@code{_PyObject_Realloc} instead of
@code{PyObject_Free}/@code{PyObject_Realloc}.

@item 
bpo-34353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34353}: Added the "socket" option in the @code{stat.filemode()} Python
implementation to match the C implementation.

@item 
bpo-34320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34320}: Fix @code{dict(od)} didn't copy iteration order of OrderedDict.

@item 
bpo-34113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34113}: Fixed crash on debug builds when opcode stack was adjusted with
negative numbers. Patch by Constantin Petrisor.

@item 
bpo-34100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34100}: Compiler now merges constants in tuples and frozensets
recursively. Code attributes like @code{co_names} are merged too.

@item 
bpo-34151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34151}: Performance of list concatenation, repetition and slicing
operations is slightly improved. Patch by Sergey Fedoseev.

@item 
bpo-34170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34170}: -X dev: it is now possible to override the memory allocator
using PYTHONMALLOC even if the developer mode is enabled.

@item 
bpo-33237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33237}: Improved @ref{5f0,,AttributeError} message for partially
initialized module.

@item 
bpo-34149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34149}: Fix min and max functions to get default behavior when key is
None.

@item 
bpo-34125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34125}: Profiling of unbound built-in methods now works when
@code{**kwargs} is given.

@item 
bpo-34141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34141}: Optimized pickling atomic types (None, bool, int, float, bytes,
str).

@item 
bpo-34126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34126}: Fix crashes when profiling certain invalid calls of unbound
methods. Patch by Jeroen Demeyer.

@item 
bpo-24618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24618}: Fixed reading invalid memory when create the code object with
too small varnames tuple or too large argument counts.

@item 
bpo-34068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34068}: In @ref{506,,io.IOBase.close()}, ensure that the
@ref{1e0e,,closed} attribute is not set with a live exception.
Patch by Zackery Spytz and Serhiy Storchaka.

@item 
bpo-34087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34087}: Fix buffer overflow while converting unicode to numeric values.

@item 
bpo-34080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34080}: Fixed a memory leak in the compiler when it raised some
uncommon errors during tokenizing.

@item 
bpo-34066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34066}: Disabled interruption by Ctrl-C between calling @code{open()} and
entering a `with' block in @code{with open()}.

@item 
bpo-34042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34042}: Fix dict.copy() to maintain correct total refcount (as reported
by sys.gettotalrefcount()).

@item 
bpo-33418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33418}: Fix potential memory leak in function object when it creates
reference cycle.

@item 
bpo-33985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33985}: Implement contextvars.ContextVar.name attribute.

@item 
bpo-33956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33956}: Update vendored Expat library copy to version 2.2.5.

@item 
bpo-24596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24596}: Decref the module object in @ref{1cca,,PyRun_SimpleFileExFlags()}
before calling @ref{1d2c,,PyErr_Print()}.  Patch by Zackery Spytz.

@item 
bpo-33451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33451}: Close directly executed pyc files before calling
@code{PyEval_EvalCode()}.

@item 
bpo-1617161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1617161}: The hash of @code{BuiltinMethodType} instances (methods of
built-in classes) now depends on the hash of the identity of `__self__'
instead of its value. The hash and equality of @code{ModuleType} and
@code{MethodWrapperType} instances (methods of user-defined classes and
some methods of built-in classes like @code{str.__add__}) now depend on the
hash and equality of the identity of `__self__' instead of its value.
@code{MethodWrapperType} instances no longer support ordering.

@item 
bpo-33824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33824}: Fix "LC_ALL=C python3.7 -V": reset properly the command line
parser when the encoding changes after reading the Python configuration.

@item 
bpo-33803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33803}: Fix a crash in hamt.c caused by enabling GC tracking for an
object that hadn't all of its fields set to NULL.

@item 
bpo-33738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33738}: Seven macro incompatibilities with the Limited API were fixed,
and the macros @ref{1cb2,,PyIter_Check()}, @ref{b81,,PyIndex_Check()} and
@ref{c5b,,PyExceptionClass_Name()} were added as functions. A script for
automatic macro checks was added.

@item 
bpo-33786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33786}: Fix asynchronous generators to handle GeneratorExit in athrow()
correctly

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: @code{PyRun_SimpleFileExFlags} removes @code{__cached__} from module
in addition to @code{__file__}.

@item 
bpo-33706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33706}: Fix a crash in Python initialization when parsing the command
line options. Thanks Christoph Gohlke for the bug report and the fix!

@item 
bpo-33597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33597}: Reduce @code{PyGC_Head} size from 3 words to 2 words.

@item 
bpo-30654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30654}: Fixed reset of the SIGINT handler to SIG_DFL on interpreter
shutdown even when there was a custom handler set previously. Patch by
Philipp Kerling.

@item 
bpo-33622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33622}: Fixed a leak when the garbage collector fails to add an object
with the @code{__del__} method or referenced by it into the
@ref{13d9,,gc.garbage} list. @ref{b85,,PyGC_Collect()} can now be called when an
exception is set and preserves it.

@item 
bpo-33462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33462}: Make dict and dict views reversible. Patch by Rémi Lapeyre.

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: A @ref{244,,RuntimeError} is now raised when the custom metaclass
doesn't provide the @code{__classcell__} entry in the namespace passed to
@code{type.__new__}.  A @ref{1a3,,DeprecationWarning} was emitted in Python
3.6--3.7.

@item 
bpo-33499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33499}: Add 
@geindex PYTHONPYCACHEPREFIX
@geindex 環境変数; PYTHONPYCACHEPREFIX
@ref{b9b,,PYTHONPYCACHEPREFIX} environment variable and
@ref{16f,,-X} @code{pycache_prefix} command-line option to set an alternate
root directory for writing module bytecode cache files.

@item 
bpo-25711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25711}: The @ref{138,,zipimport} module has been rewritten in pure Python.

@item 
bpo-33509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33509}: Fix module_globals parameter of warnings.warn_explicit(): don't
crash if module_globals is not a dict.

@item 
bpo-31849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31849}: Fix signed/unsigned comparison warning in pyhash.c.

@item 
bpo-33475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33475}: Fixed miscellaneous bugs in converting annotations to strings
and optimized parentheses in the string representation.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Added support for the @code{setpgroup}, @code{resetids},
@code{setsigmask}, @code{setsigdef} and @code{scheduler} parameters of
@code{posix_spawn}. Patch by Pablo Galindo.

@item 
bpo-33391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33391}: Fix a leak in set_symmetric_difference().

@item 
bpo-33363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33363}: Raise a SyntaxError for @code{async with} and @code{async for}
statements outside of async functions.

@item 
bpo-28055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28055}: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

@item 
bpo-33128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33128}: Fix a bug that causes PathFinder to appear twice on
sys.meta_path. Patch by Pablo Galindo Salgado.

@item 
bpo-33331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33331}: Modules imported last are now cleared first at interpreter
shutdown.

@item 
bpo-33312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33312}: Fixed clang ubsan (undefined behavior sanitizer) warnings in
dictobject.c by adjusting how the internal struct _dictkeysobject shared
keys structure is declared.

@item 
bpo-33305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33305}: Improved syntax error messages for invalid numerical literals.

@item 
bpo-33306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33306}: Improved syntax error messages for unbalanced parentheses.

@item 
bpo-33234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33234}: The list constructor will pre-size and not over-allocate when
the input length is known.

@item 
bpo-33270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33270}: Intern the names for all anonymous code objects.  Patch by
Zackery Spytz.

@item 
bpo-30455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30455}: The C and Python code and the documentation related to tokens
are now generated from a single source file @code{Grammar/Tokens}.

@item 
bpo-33176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33176}: Add a @code{toreadonly()} method to memoryviews.

@item 
bpo-33231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33231}: Fix potential memory leak in @code{normalizestring()}.

@item 
bpo-33205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33205}: Change dict growth function from
@code{round_up_to_power_2(used*2+hashtable_size/2)} to
@code{round_up_to_power_2(used*3)}.  Previously, dict is shrunk only when
@code{used == 0}. Now dict has more chance to be shrunk.

@item 
bpo-29922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29922}: Improved error messages in 'async with' when @code{__aenter__()}
or @code{__aexit__()} return non-awaitable object.

@item 
bpo-33199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33199}: Fix @code{ma_version_tag} in dict implementation is uninitialized
when copying from key-sharing dict.

@item 
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053}: When using the -m switch, sys.path[0] is now explicitly
expanded as the `starting' working directory, rather than being left as
the empty path (which allows imports from the current working directory at
the time of the import)

@item 
bpo-33138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33138}: Changed standard error message for non-pickleable and
non-copyable types. It now says "cannot pickle" instead of "can't pickle"
or "cannot serialize".

@item 
bpo-33018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33018}: Improve consistency of errors raised by @code{issubclass()} when
called with a non-class and an abstract base class as the first and second
arguments, respectively. Patch by Josh Bronson.

@item 
bpo-33083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33083}: @code{math.factorial} no longer accepts arguments that are not
int-like. Patch by Pablo Galindo.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Added new opcode @ref{ca0,,END_ASYNC_FOR} and fixes the
following issues:


@itemize *

@item 
Setting global @ref{1e0f,,StopAsyncIteration} no longer breaks @code{async for}
loops.

@item 
Jumping into an @code{async for} loop is now disabled.

@item 
Jumping out of an @code{async for} loop no longer corrupts the stack.
@end itemize

@item 
bpo-25750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25750}: Fix rare Python crash due to bad refcounting in
@code{type_getattro()} if a descriptor deletes itself from the class. Patch
by Jeroen Demeyer.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Fixed bytecode generation for "async for" with a complex
target. A StopAsyncIteration raised on assigning or unpacking will be now
propagated instead of stopping the iteration.

@item 
bpo-33026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33026}: Fixed jumping out of "with" block by setting f_lineno.

@item 
bpo-33005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33005}: Fix a crash on fork when using a custom memory allocator (ex:
using PYTHONMALLOC env var). _PyGILState_Reinit() and
_PyInterpreterState_Enable() now use the default RAW memory allocator to
allocate a new interpreters mutex on fork.

@item 
bpo-32911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32911}: Due to unexpected compatibility issues discovered during
downstream beta testing, reverted bpo-29463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29463}. @code{docstring} field is
removed from Module, ClassDef, FunctionDef, and AsyncFunctionDef ast nodes
which was added in 3.7a1.  Docstring expression is restored as a first
statement in their body. Based on patch by Inada Naoki.

@item 
bpo-17288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17288}: Prevent jumps from 'return' and 'exception' trace events.

@item 
bpo-32946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32946}: Importing names from already imported module with "from ...
import ..." is now 30% faster if the module is not a package.

@item 
bpo-32932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32932}: Make error message more revealing when there are non-str
objects in @code{__all__}.

@item 
bpo-32925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32925}: Optimized iterating and containing test for literal lists
consisting of non-constants: @code{x in [a, b]} and @code{for x in [a, b]}. The
case of all constant elements already was optimized.

@item 
bpo-32889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32889}: Update Valgrind suppression list to account for the rename of
@code{Py_ADDRESS_IN_RANG} to @code{address_in_range}.

@item 
bpo-32836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32836}: Don't use temporary variables in cases of list/dict/set
comprehensions

@item 
bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356}: Remove the new API added in bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356} (gc.ensure_disabled()
context manager).

@item 
bpo-32305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32305}: For namespace packages, ensure that both @code{__file__} and
@code{__spec__.origin} are set to None.

@item 
bpo-32303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32303}: Make sure @code{__spec__.loader} matches @code{__loader__} for
namespace packages.

@item 
bpo-32711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32711}: Fix the warning messages for Python/ast_unparse.c. Patch by
Stéphane Wirtel

@item 
bpo-32583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32583}: Fix possible crashing in builtin Unicode decoders caused by
write out-of-bound errors when using customized decode error handlers.

@item 
bpo-32489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32489}: A @ref{180,,continue} statement is now allowed in the
@ref{1b0,,finally} clause.

@item 
bpo-17611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17611}: Simplified the interpreter loop by moving the logic of
unrolling the stack of blocks into the compiler. The compiler emits now
explicit instructions for adjusting the stack of values and calling the
cleaning up code for @ref{17f,,break}, @ref{180,,continue} and
@ref{1af,,return}.

Removed opcodes @code{BREAK_LOOP}, @code{CONTINUE_LOOP},
@code{SETUP_LOOP} and @code{SETUP_EXCEPT}. Added new opcodes
@code{ROT_FOUR}, @code{BEGIN_FINALLY} and @code{CALL_FINALLY} and
@code{POP_FINALLY}. Changed the behavior of @code{END_FINALLY} and
@code{WITH_CLEANUP_START}.

@item 
bpo-32285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32285}: New function unicodedata.is_normalized, which can check whether
a string is in a specific normal form.

@item 
bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544}: Yield expressions are now disallowed in comprehensions and
generator expressions except the expression for the outermost iterable.

@item 
bpo-32117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32117}: Iterable unpacking is now allowed without parentheses in yield
and return statements, e.g. @code{yield 1, 2, 3, *rest}. Thanks to David
Cuthbert for the change and Jordan Chapman for added tests.

@item 
bpo-31902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31902}: Fix the @code{col_offset} attribute for ast nodes
@code{ast.AsyncFor}, @code{ast.AsyncFunctionDef}, and @code{ast.AsyncWith}.
Previously, @code{col_offset} pointed to the keyword after @code{async}.

@item 
bpo-25862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25862}: Fix assertion failures in the @code{tell()} method of
@code{io.TextIOWrapper}. Patch by Zackery Spytz.

@item 
bpo-21983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21983}: Fix a crash in @code{ctypes.cast()} in case the type argument is a
ctypes structured data type. Patch by Eryk Sun and Oren Milman.

@item 
bpo-31577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31577}: Fix a crash in @code{os.utime()} in case of a bad ns argument.
Patch by Oren Milman.

@item 
bpo-29832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29832}: Remove references to 'getsockaddrarg' from various socket error
messages. Patch by Oren Milman.
@end itemize

@node ライブラリ<162>,ドキュメント<56>,Core and Builtins<159>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id746}@anchor{1e10}
@subsubsection ライブラリ



@itemize -

@item 
bpo-35845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35845}: Add 'order' parameter to memoryview.tobytes().

@item 
bpo-35864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35864}: The _asdict() method for collections.namedtuple now returns a
regular dict instead of an OrderedDict.

@item 
bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}: An ExitStack is now used internally within subprocess.Popen to
clean up pipe file handles. No behavior change in normal operation. But if
closing one handle were ever to cause an exception, the others will now be
closed instead of leaked.  (patch by Giampaolo Rodola)

@item 
bpo-35847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35847}: RISC-V needed the CTYPES_PASS_BY_REF_HACK.  Fixes ctypes
Structure test_pass_by_value.

@item 
bpo-35813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35813}: Shared memory submodule added to multiprocessing to avoid need
for serialization between processes

@item 
bpo-35780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35780}: Fix lru_cache() errors arising in recursive, reentrant, or
multi-threaded code. These errors could result in orphan links and in the
cache being trapped in a state with fewer than the specified maximum
number of links. Fix handling of negative maxsize which should have been
treated as zero. Fix errors in toggling the "full" status flag. Fix
misordering of links when errors are encountered.  Sync-up the C code and
pure Python code for the space saving path in functions with a single
positional argument. In this common case, the space overhead of an lru
cache entry is reduced by almost half.  Fix counting of cache misses. In
error cases, the miss count was out of sync with the actual number of
times the underlying user function was called.

@item 
bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}: @ref{52e,,os.posix_spawn()} and @ref{1e11,,os.posix_spawnp()} now have a
`setsid' parameter.

@item 
bpo-23846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23846}: @ref{81d,,asyncio.ProactorEventLoop} now catches and logs send
errors when the self-pipe is full.

@item 
bpo-34323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34323}: @ref{b,,asyncio}: Enhance @code{IocpProactor.close()} log: wait 1
second before the first log, then log every second. Log also the number of
seconds since @code{close()} was called.

@item 
bpo-35674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35674}: Add a new @ref{1e11,,os.posix_spawnp()} function. Patch by Joannah
Nanjekye.

@item 
bpo-35733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35733}: @code{ast.Constant(boolean)} no longer an instance of
@code{ast.Num}.  Patch by Anthony Sottile.

@item 
bpo-35726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35726}: QueueHandler.prepare() now makes a copy of the record before
modifying and enqueueing it, to avoid affecting other handlers in the
chain.

@item 
bpo-35719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35719}: Sped up multi-argument @ref{92,,math} functions atan2(),
copysign(), remainder() and hypot() by 1.3--2.5 times.

@item 
bpo-35717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35717}: Fix KeyError exception raised when using enums and compile.
Patch contributed by Rémi Lapeyre.

@item 
bpo-35699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35699}: Fixed detection of Visual Studio Build Tools 2017 in distutils

@item 
bpo-32710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32710}: Fix memory leaks in asyncio ProactorEventLoop on overlapped
operation failure.

@item 
bpo-35702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35702}: The @ref{c37,,time.CLOCK_UPTIME_RAW} constant is now available
for macOS 10.12.

@item 
bpo-32710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32710}: Fix a memory leak in asyncio in the ProactorEventLoop when
@code{ReadFile()} or @code{WSASend()} overlapped operation fail immediately:
release the internal buffer.

@item 
bpo-35682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35682}: Fix @code{asyncio.ProactorEventLoop.sendfile()}: don't attempt to
set the result of an internal future if it's already done.

@item 
bpo-35283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35283}: Add a deprecated warning for the
@code{threading.Thread.isAlive()} method. Patch by Donghee Na.

@item 
bpo-35664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35664}: Improve operator.itemgetter() performance by 33% with optimized
argument handling and with adding a fast path for the common case of a
single non-negative integer index into a tuple (which is the typical use
case in the standard library).

@item 
bpo-35643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35643}: Fixed a SyntaxWarning: invalid escape sequence in
Modules/_sha3/cleanup.py. Patch by Mickaël Schoentgen.

@item 
bpo-35619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35619}: Improved support of custom data descriptors in @ref{ad4,,help()} and
@ref{ba,,pydoc}.

@item 
bpo-28503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28503}: The @code{crypt} module now internally uses the @code{crypt_r()}
library function instead of @code{crypt()} when available.

@item 
bpo-35614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35614}: Fixed help() on metaclasses. Patch by Sanyam Khurana.

@item 
bpo-35568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35568}: Expose @code{raise(signum)} as @code{raise_signal}

@item 
bpo-35588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35588}: The floor division and modulo operations and the @ref{b99,,divmod()}
function on @ref{213,,fractions.Fraction} types are 2--4x faster. Patch by
Stefan Behnel.

@item 
bpo-35585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35585}: Speed-up building enums by value, e.g. http.HTTPStatus(200).

@item 
bpo-30561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30561}: random.gammavariate(1.0, beta) now computes the same result as
random.expovariate(1.0 / beta).  This synchronizes the two algorithms and
eliminates some idiosyncrasies in the old implementation.  It does however
produce a difference stream of random variables than it used to.

@item 
bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}: The @ref{dc,,subprocess} module can now use the
@ref{52e,,os.posix_spawn()} function in some cases for better performance.

@item 
bpo-35526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35526}: Delaying the 'joke' of barry_as_FLUFL.mandatory to Python
version 4.0

@item 
bpo-35523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35523}: Remove @ref{2e,,ctypes} callback workaround: no longer create a
callback at startup. Avoid SELinux alert on @code{import ctypes} and @code{import
uuid}.

@item 
bpo-31784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31784}: @ref{da1,,uuid.uuid1()} now calls @ref{ce0,,time.time_ns()} rather than
@code{int(time.time() * 1e9)}.

@item 
bpo-35513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35513}: @code{TextTestRunner} of
@code{unittest.runner} now uses @ref{c7a,,time.perf_counter()} rather than
@ref{55d,,time.time()} to measure the execution time of a test:
@ref{55d,,time.time()} can go backwards, whereas @ref{c7a,,time.perf_counter()} is
monotonic.

@item 
bpo-35502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35502}: Fixed reference leaks in
@ref{c4a,,xml.etree.ElementTree.TreeBuilder} in case of unfinished building
of the tree (in particular when an error was raised during parsing XML).

@item 
bpo-35348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35348}: Make @ref{1a06,,platform.architecture()} parsing of @code{file} command
output more reliable: add the @code{-b} option to the @code{file} command to
omit the filename, force the usage of the C locale, and search also the
"shared object" pattern.

@item 
bpo-35491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35491}: @ref{98,,multiprocessing}: Add @code{Pool.__repr__()} and enhance
@code{BaseProcess.__repr__()} (add pid and parent pid) to ease debugging.
Pool state constant values are now strings instead of integers, for
example @code{RUN} value becomes @code{'RUN'} instead of @code{0}.

@item 
bpo-35477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35477}: @code{multiprocessing.Pool.__enter__()} now fails if the pool is
not running: @code{with pool:} fails if used more than once.

@item 
bpo-31446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31446}: Copy command line that was passed to CreateProcessW since this
function can change the content of the input buffer.

@item 
bpo-35471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35471}: Python 2.4 dropped MacOS 9 support. The macpath module was
deprecated in Python 3.7. The module is now removed.

@item 
bpo-23057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23057}: Unblock Proactor event loop when keyboard interrupt is received
on Windows

@item 
bpo-35052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35052}: Fix xml.dom.minidom cloneNode() on a document with an entity:
pass the correct arguments to the user data handler of an entity.

@item 
bpo-20239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20239}: Allow repeated assignment deletion of
@ref{c3f,,unittest.mock.Mock} attributes. Patch by Pablo Galindo.

@item 
bpo-17185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17185}: Set @code{__signature__} on mock for @ref{82,,inspect} to get
signature. Patch by Karthikeyan Singaravelan.

@item 
bpo-35445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35445}: Memory errors during creating posix.environ no longer ignored.

@item 
bpo-35415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35415}: Validate fileno= argument to socket.socket().

@item 
bpo-35424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35424}: @code{multiprocessing.Pool} destructor now emits
@ref{54c,,ResourceWarning} if the pool is still running.

@item 
bpo-35330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35330}: When a @code{Mock} instance was used to wrap an object, if
@code{side_effect} is used in one of the mocks of it methods, don't call the
original implementation and return the result of using the side effect the
same way that it is done with return_value.

@item 
bpo-35346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35346}: Drop Mac OS 9 and Rhapsody support from the @ref{af,,platform}
module. Rhapsody last release was in 2000. Mac OS 9 last release was in
2001.

@item 
bpo-10496@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10496}: @code{check_environ()} of @code{distutils.utils}
now catches @ref{5e7,,KeyError} on calling @ref{1e12,,pwd.getpwuid()}: don't create
the @code{HOME} environment variable in this case.

@item 
bpo-10496@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10496}: @code{posixpath.expanduser()} now returns the input `path'
unchanged if the @code{HOME} environment variable is not set and the current
user has no home directory (if the current user identifier doesn't exist
in the password database). This change fix the @ref{cc,,site} module if the
current user doesn't exist in the password database (if the user has no
home directory).

@item 
bpo-35389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35389}: @ref{17f5,,platform.libc_ver()} now uses
@code{os.confstr('CS_GNU_LIBC_VERSION')} if available and the `executable'
parameter is not set.

@item 
bpo-35394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35394}: Add empty slots to asyncio abstract protocols.

@item 
bpo-35310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35310}: Fix a bug in @ref{fa0,,select.select()} where, in some cases, the
file descriptor sequences were returned unmodified after a signal
interruption, even though the file descriptors might not be ready yet.
@ref{fa0,,select.select()} will now always return empty lists if a timeout has
occurred.  Patch by Oran Avraham.

@item 
bpo-35380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35380}: Enable TCP_NODELAY on Windows for proactor asyncio event loop.

@item 
bpo-35341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35341}: Add generic version of @code{collections.OrderedDict} to the
@code{typing} module. Patch by Ismo Toijala.

@item 
bpo-35371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35371}: Fixed possible crash in @code{os.utime()} on Windows when pass
incorrect arguments.

@item 
bpo-35346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35346}: @ref{1e13,,platform.uname()} now redirects @code{stderr} to
@ref{1e14,,os.devnull} when running external programs like @code{cmd /c ver}.

@item 
bpo-35066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35066}: Previously, calling the strftime() method on a datetime object
with a trailing '%' in the format string would result in an exception.
However, this only occurred when the datetime C module was being used; the
python implementation did not match this behavior. Datetime is now PEP-399
compliant, and will not throw an exception on a trailing '%'.

@item 
bpo-35345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35345}: The function @code{platform.popen} has been removed, it was
deprecated since Python 3.3: use @ref{31a,,os.popen()} instead.

@item 
bpo-35344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35344}: On macOS, @ref{1ac6,,platform.platform()} now uses
@ref{1e15,,platform.mac_ver()}, if it returns a non-empty release string, to get
the macOS version rather than the darwin version.

@item 
bpo-35312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35312}: Make @code{lib2to3.pgen2.parse.ParseError} round-trip pickle-able.
Patch by Anthony Sottile.

@item 
bpo-35308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35308}: Fix regression in @code{webbrowser} where default browsers may be
preferred over browsers in the @code{BROWSER} environment variable.

@item 
bpo-24746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24746}: Avoid stripping trailing whitespace in doctest fancy diff.
Original patch by R. David Murray & Jairo Trad. Enhanced by Sanyam
Khurana.

@item 
bpo-28604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28604}: @ref{df8,,locale.localeconv()} now sets temporarily the @code{LC_CTYPE}
locale to the @code{LC_MONETARY} locale if the two locales are different and
monetary strings are non-ASCII. This temporary change affects other
threads.

@item 
bpo-35277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35277}: Update ensurepip to install pip 18.1 and setuptools 40.6.2.

@item 
bpo-24209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24209}: Adds IPv6 support when invoking http.server directly.

@item 
bpo-35226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35226}: Recursively check arguments when testing for equality of
@ref{1db3,,unittest.mock.call} objects and add note that tracking of
parameters used to create ancestors of mocks in @code{mock_calls} is not
possible.

@item 
bpo-29564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29564}: The warnings module now suggests to enable tracemalloc if the
source is specified, the tracemalloc module is available, but tracemalloc
is not tracing memory allocations.

@item 
bpo-35189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35189}: Modify the following fnctl function to retry if interrupted by
a signal (EINTR): flock, lockf, fnctl

@item 
bpo-30064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30064}: Use add_done_callback() in sock_* asyncio API to unsubscribe
reader/writer early on calcellation.

@item 
bpo-35186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35186}: Removed the "built with" comment added when @code{setup.py upload}
is used with either @code{bdist_rpm} or @code{bdist_dumb}.

@item 
bpo-35152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35152}: Allow sending more than 2 GB at once on a multiprocessing
connection on non-Windows systems.

@item 
bpo-35062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35062}: Fix incorrect parsing of
@ref{1a3e,,io.IncrementalNewlineDecoder}'s `translate' argument.

@item 
bpo-35065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35065}: Remove @code{StreamReaderProtocol._untrack_reader}. The call to
@code{_untrack_reader} is currently performed too soon, causing the protocol
to forget about the reader before @code{connection_lost} can run and feed the
EOF to the reader.

@item 
bpo-34160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34160}: ElementTree and minidom now preserve the attribute order
specified by the user.

@item 
bpo-35079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35079}: Improve difflib.SequenceManager.get_matching_blocks doc by
adding 'non-overlapping' and changing '!=' to '<'.

@item 
bpo-33710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33710}: Deprecated @code{l*gettext()} functions and methods in the
@ref{67,,gettext} module. They return encoded bytes instead of Unicode
strings and are artifacts from Python 2 times. Also deprecated functions
and methods related to setting the charset for @code{l*gettext()} functions
and methods.

@item 
bpo-35017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35017}: @ref{1357,,socketserver.BaseServer.serve_forever()} now exits
immediately if it's @ref{1e16,,shutdown()} method is
called while it is polling for new events.

@item 
bpo-35024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35024}: @code{importlib} no longer logs @code{wrote <bytecode path>}
redundantly after @code{(created|could not create) <bytecode path>} is
already logged. Patch by Quentin Agren.

@item 
bpo-35047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35047}: @code{unittest.mock} now includes mock calls in exception messages
if @code{assert_not_called}, @code{assert_called_once}, or
@code{assert_called_once_with} fails. Patch by Petter Strandmark.

@item 
bpo-31047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31047}: Fix @code{ntpath.abspath} regression where it didn't remove a
trailing separator on Windows. Patch by Tim Graham.

@item 
bpo-35053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35053}: tracemalloc now tries to update the traceback when an object is
reused from a "free list" (optimization for faster object creation, used
by the builtin list type for example).

@item 
bpo-31553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31553}: Add the --json-lines option to json.tool. Patch by hongweipeng.

@item 
bpo-34794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34794}: Fixed a leak in Tkinter when pass the Python wrapper around
Tcl_Obj back to Tcl/Tk.

@item 
bpo-34909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34909}: Enum: fix grandchildren subclassing when parent mixed with
concrete data types.

@item 
bpo-35022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35022}: @ref{108f,,unittest.mock.MagicMock} now supports the
@code{__fspath__} method (from @ref{e4b,,os.PathLike}).

@item 
bpo-35008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35008}: Fixed references leaks when call the @code{__setstate__()} method
of @ref{363,,xml.etree.ElementTree.Element} in the C implementation for
already initialized element.

@item 
bpo-23420@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23420}: Verify the value for the parameter '-s' of the cProfile CLI.
Patch by Robert Kuska

@item 
bpo-33947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33947}: dataclasses now handle recursive reprs without raising
RecursionError.

@item 
bpo-34890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34890}: Make @ref{30d,,inspect.iscoroutinefunction()},
@ref{1b5b,,inspect.isgeneratorfunction()} and @ref{1b5c,,inspect.isasyncgenfunction()}
work with @ref{217,,functools.partial()}. Patch by Pablo Galindo.

@item 
bpo-34521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34521}: Use @ref{1e17,,socket.CMSG_SPACE()} to calculate ancillary data size
instead of @ref{1e18,,socket.CMSG_LEN()} in
@code{multiprocessing.reduction.recvfds()} as 
@geindex RFC; RFC 3542
RFC 3542@footnote{https://datatracker.ietf.org/doc/html/rfc3542.html} requires the use
of the former for portable applications.

@item 
bpo-31522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31522}: The @code{mailbox.mbox.get_string} function `from_' parameter can
now successfully be set to a non-default value.

@item 
bpo-34970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34970}: Protect tasks weak set manipulation in @code{asyncio.all_tasks()}

@item 
bpo-34969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34969}: gzip: Add --fast, --best on the gzip CLI, these parameters will
be used for the fast compression method (quick) or the best method
compress (slower, but smaller file). Also, change the default compression
level to 6 (tradeoff).

@item 
bpo-16965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16965}: The 2to3 @code{execfile} fixer now opens the file with mode
@code{'rb'}.  Patch by Zackery Spytz.

@item 
bpo-34966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34966}: @ref{ba,,pydoc} now supports aliases not only to methods defined
in the end class, but also to inherited methods.  The docstring is not
duplicated for aliases.

@item 
bpo-34926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34926}: @ref{1e19,,mimetypes.MimeTypes.guess_type()} now accepts
@ref{5a1,,path-like object} in addition to url strings. Patch by Mayank
Asthana.

@item 
bpo-23831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23831}: Add @code{moveto()} method to the @code{tkinter.Canvas} widget. Patch
by Juliette Monsel.

@item 
bpo-34941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34941}: Methods @code{find()}, @code{findtext()} and @code{findall()} of the
@code{Element} class in the @ref{12b,,xml.etree.ElementTree} module are now able
to find children which are instances of @code{Element} subclasses.

@item 
bpo-32680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32680}: @ref{b27,,smtplib.SMTP} objects now always have a @code{sock}
attribute present

@item 
bpo-34769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34769}: Fix for async generators not finalizing when event loop is in
debug mode and garbage collector runs in another thread.

@item 
bpo-34936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34936}: Fix @code{TclError} in @code{tkinter.Spinbox.selection_element()}.
Patch by Juliette Monsel.

@item 
bpo-34829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34829}: Add methods @code{selection_from}, @code{selection_range},
@code{selection_present} and @code{selection_to} to the @code{tkinter.Spinbox} for
consistency with the @code{tkinter.Entry} widget. Patch by Juliette Monsel.

@item 
bpo-34911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34911}: Added `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.

@item 
bpo-34922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34922}: Fixed integer overflow in the @ref{1e1a,,digest()} and
@ref{1e1b,,hexdigest()} methods for the SHAKE algorithm in the
@ref{6c,,hashlib} module.

@item 
bpo-34925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34925}: 25% speedup in argument parsing for the functions in the bisect
module.

@item 
bpo-34900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34900}: Fixed @ref{1c49,,unittest.TestCase.debug()} when used to call test
methods with subtests.  Patch by Bruno Oliveira.

@item 
bpo-34844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34844}: logging.Formatter enhancement - Ensure styles and fmt matches
in logging.Formatter - Added validate method in each format style class:
StrFormatStyle, PercentStyle, StringTemplateStyle. - This method is called
in the constructor of logging.Formatter class - Also re-raise the KeyError
in the format method of each style class, so it would a bit clear that
it's an error with the invalid format fields.

@item 
bpo-34897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34897}: Adjust test.support.missing_compiler_executable check so that a
nominal command name of "" is ignored. Patch by Michael Felt.

@item 
bpo-34871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34871}: Fix inspect module polluted @code{sys.modules} when parsing
@code{__text_signature__} of callable.

@item 
bpo-34898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34898}: Add @code{mtime} argument to @code{gzip.compress} for reproducible
output. Patch by Guo Ci Teo.

@item 
bpo-28441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28441}: On Cygwin and MinGW, ensure that @code{sys.executable} always
includes the full filename in the path, including the @code{.exe} suffix
(unless it is a symbolic link).

@item 
bpo-34866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34866}: Adding @code{max_num_fields} to @code{cgi.FieldStorage} to make DOS
attacks harder by limiting the number of @code{MiniFieldStorage} objects
created by @code{FieldStorage}.

@item 
bpo-34711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34711}: http.server ensures it reports HTTPStatus.NOT_FOUND when the
local path ends with "/" and is not a directory, even if the underlying OS
(e.g. AIX) accepts such paths as a valid file reference. Patch by Michael
Felt.

@item 
bpo-34872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34872}: Fix self-cancellation in C implementation of asyncio.Task

@item 
bpo-34849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34849}: Don't log waiting for @code{selector.select} in asyncio loop
iteration. The waiting is pretty normal for any asyncio program, logging
its time just adds a noise to logs without any useful information
provided.

@item 
bpo-34022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34022}: The 
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable no longer
overrides the value of the `invalidation_mode' argument to
@ref{c1a,,py_compile.compile()}, and determines its default value instead.

@item 
bpo-34819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34819}: Use a monotonic clock to compute timeouts in
@code{Executor.map()} and @code{as_completed()}, in order to prevent
timeouts from deviating when the system clock is adjusted.

@item 
bpo-34758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34758}: Add .wasm -> application/wasm to list of recognized file types
and content type headers

@item 
bpo-34789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34789}: @ref{1e1c,,xml.sax.make_parser()} now accepts any iterable as its
`parser_list' argument.  Patch by Andrés Delfino.

@item 
bpo-34334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34334}: In @code{QueueHandler}, clear @code{exc_text} from
@code{LogRecord} to prevent traceback from being written twice.

@item 
bpo-34687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34687}: On Windows, asyncio now uses ProactorEventLoop, instead of
SelectorEventLoop, by default.

@item 
bpo-5950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5950}: Support reading zip files with archive comments in
@ref{138,,zipimport}.

@item 
bpo-32892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32892}: The parser now represents all constants as
@ref{2ef,,ast.Constant} instead of using specific constant AST types
(@code{Num}, @code{Str}, @code{Bytes}, @code{NameConstant} and @code{Ellipsis}). These
classes are considered deprecated and will be removed in future Python
versions.

@item 
bpo-34728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34728}: Add deprecation warning when @code{loop} is used in methods:
@code{asyncio.sleep}, @code{asyncio.wait} and @code{asyncio.wait_for}.

@item 
bpo-34738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34738}: ZIP files created by @code{distutils} will now include entries for
directories.

@item 
bpo-34659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34659}: Add an optional `initial' argument to itertools.accumulate().

@item 
bpo-29577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29577}: Support multiple mixin classes when creating Enums.

@item 
bpo-34670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34670}: Add SSLContext.post_handshake_auth and
SSLSocket.verify_client_post_handshake for TLS 1.3's post handshake
authentication feature.

@item 
bpo-32718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32718}: The Activate.ps1 script from venv works with PowerShell Core
6.1 and is now available under all operating systems.

@item 
bpo-31177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31177}: Fix bug that prevented using @ref{ef6,,reset_mock} on mock instances with deleted attributes

@item 
bpo-34672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34672}: Add a workaround, so the @code{'Z'} @ref{1402,,time.strftime()}
specifier on the musl C library can work in some cases.

@item 
bpo-34666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34666}: Implement @code{asyncio.StreamWriter.awrite} and
@code{asyncio.StreamWriter.aclose()} coroutines.  Methods are needed for
providing a consistent stream API with control flow switched on by
default.

@item 
bpo-6721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6721}: Acquire the logging module's commonly used internal locks while
fork()ing to avoid deadlocks in the child process.

@item 
bpo-34658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34658}: Fix a rare interpreter unhandled exception state SystemError
only seen when using subprocess with a preexec_fn while an after_parent
handler has been registered with os.register_at_fork and the fork system
call fails.

@item 
bpo-34652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34652}: Ensure @ref{528,,os.lchmod()} is never defined on Linux.

@item 
bpo-34638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34638}: Store a weak reference to stream reader to break strong
references loop between reader and protocol.  It allows to detect and
close the socket if the stream is deleted (garbage collected) without
@code{close()} call.

@item 
bpo-34536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34536}: @code{Enum._missing_}:  raise @code{ValueError} if None returned and
@code{TypeError} if non-member is returned.

@item 
bpo-34636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34636}: Speed up re scanning of many non-matching characters for s w
and d within bytes objects. (microoptimization)

@item 
bpo-24412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24412}: Add @ref{c40,,addModuleCleanup()} and
@ref{c41,,addClassCleanup()} to unittest to support cleanups
for @ref{c42,,setUpModule()} and
@ref{c43,,setUpClass()}. Patch by Lisa Roach.

@item 
bpo-34630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34630}: Don't log SSL certificate errors in asyncio code (connection
error logging is skipped already).

@item 
bpo-32490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32490}: Prevent filename duplication in @ref{dc,,subprocess} exception
messages.  Patch by Zackery Spytz.

@item 
bpo-34363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34363}: dataclasses.asdict() and .astuple() now handle namedtuples
correctly.

@item 
bpo-34625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34625}: Update vendorized expat library version to 2.2.6.

@item 
bpo-32270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32270}: The subprocess module no longer mistakenly closes redirected
fds even when they were in pass_fds when outside of the default @{0, 1, 2@}
set.

@item 
bpo-34622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34622}: Create a dedicated @code{asyncio.CancelledError},
@code{asyncio.InvalidStateError} and @code{asyncio.TimeoutError} exception
classes.  Inherit them from corresponding exceptions from
@code{concurrent.futures} package. Extract @code{asyncio} exceptions into a
separate file.

@item 
bpo-34610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34610}: Fixed iterator of @code{multiprocessing.managers.DictProxy}.

@item 
bpo-34421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34421}: Fix distutils logging for non-ASCII strings.  This caused
installation issues on Windows.

@item 
bpo-34604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34604}: Fix possible mojibake in the error message of @code{pwd.getpwnam}
and @code{grp.getgrnam} using string representation because of invisible
characters or trailing whitespaces. Patch by William Grzybowski.

@item 
bpo-30977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30977}: Make uuid.UUID use @code{__slots__} to reduce its memory
footprint. Based on original patch by Wouter Bolsterlee.

@item 
bpo-34574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34574}: OrderedDict iterators are not exhausted during pickling
anymore. Patch by Sergey Fedoseev.

@item 
bpo-8110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8110}: Refactored @ref{dc,,subprocess} to check for Windows-specific
modules rather than @code{sys.platform == 'win32'}.

@item 
bpo-34530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34530}: @code{distutils.spawn.find_executable()} now falls back on
@ref{1de4,,os.defpath} if the @code{PATH} environment variable is not set.

@item 
bpo-34563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34563}: On Windows, fix multiprocessing.Connection for very large read:
fix _winapi.PeekNamedPipe() and _winapi.ReadFile() for read larger than
INT_MAX (usually @code{2**31-1}).

@item 
bpo-34558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34558}: Correct typo in Lib/ctypes/_aix.py

@item 
bpo-34282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34282}: Move @code{Enum._convert} to @code{EnumMeta._convert_} and fix enum
members getting shadowed by parent attributes.

@item 
bpo-22872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22872}: When the queue is closed, @ref{2ec,,ValueError} is now raised by
@ref{1e1d,,multiprocessing.Queue.put()} and @ref{1e1e,,multiprocessing.Queue.get()}
instead of @ref{8b8,,AssertionError} and @ref{2c0,,OSError}, respectively. Patch
by Zackery Spytz.

@item 
bpo-34515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34515}: Fix parsing non-ASCII identifiers in
@code{lib2to3.pgen2.tokenize} (
@geindex Python Enhancement Proposals; PEP 3131
PEP 3131@footnote{https://peps.python.org/pep-3131/}).

@item 
bpo-13312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13312}: Avoids a possible integer underflow (undefined behavior) in the
time module's year handling code when passed a very low negative year
value.

@item 
bpo-34472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34472}: Improved compatibility for streamed files in @ref{137,,zipfile}.
Previously an optional signature was not being written and certain ZIP
applications were not supported. Patch by Silas Sewell.

@item 
bpo-34454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34454}: Fix the .fromisoformat() methods of datetime types crashing
when given unicode with non-UTF-8-encodable code points.  Specifically,
datetime.fromisoformat() now accepts surrogate unicode code points used as
the separator. Report and tests by Alexey Izbyshev, patch by Paul Ganssle.

@item 
bpo-6700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6700}: Fix inspect.getsourcelines for module level frames/tracebacks.
Patch by Vladimir Matveev.

@item 
bpo-34171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34171}: Running the @ref{103,,trace} module no longer creates the
@code{trace.cover} file.

@item 
bpo-34441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34441}: Fix crash when an @code{ABC}-derived class with invalid
@code{__subclasses__} is passed as the second argument to @ref{9c4,,issubclass()}.
Patch by Alexey Izbyshev.

@item 
bpo-34427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34427}: Fix infinite loop in @code{a.extend(a)} for @code{MutableSequence}
subclasses.

@item 
bpo-34412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34412}: Make @ref{1e1f,,signal.strsignal()} work on HP-UX. Patch by Michael
Osipov.

@item 
bpo-20849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20849}: shutil.copytree now accepts a new @code{dirs_exist_ok} keyword
argument. Patch by Josh Bronson.

@item 
bpo-31715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31715}: Associate @code{.mjs} file extension with
@code{application/javascript} MIME Type.

@item 
bpo-34384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34384}: @ref{b1a,,os.readlink()} now accepts @ref{5a1,,path-like} and @ref{192,,bytes} objects on Windows.

@item 
bpo-22602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22602}: The UTF-7 decoder now raises @ref{c08,,UnicodeDecodeError} for
ill-formed sequences starting with "+" (as specified in RFC 2152).  Patch
by Zackery Spytz.

@item 
bpo-2122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2122}: The @ref{c8f,,mmap.flush()} method now returns
@code{None} on success, raises an exception on error under all platforms.

@item 
bpo-34341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34341}: Appending to the ZIP archive with the ZIP64 extension no longer
grows the size of extra fields of existing entries.

@item 
bpo-34333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34333}: Fix %-formatting in @ref{1956,,pathlib.PurePath.with_suffix()} when
formatting an error message.

@item 
bpo-18540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18540}: The @ref{aff,,imaplib.IMAP4} and @ref{b00,,imaplib.IMAP4_SSL}
classes now resolve to the local host IP correctly when the default value
of `host' parameter (@code{'@w{'}}) is used.

@item 
bpo-26502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26502}: Implement @code{traceback.FrameSummary.__len__()} method to
preserve compatibility with the old tuple API.

@item 
bpo-34318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34318}: @ref{750,,assertRaises()},
@ref{752,,assertRaisesRegex()},
@ref{137c,,assertWarns()} and
@ref{137d,,assertWarnsRegex()} no longer success if the
passed callable is None. They no longer ignore unknown keyword arguments
in the context manager mode. A DeprecationWarning was raised in these
cases since Python 3.5.

@item 
bpo-9372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9372}: Deprecate @ref{588,,__getitem__()} methods of
@ref{93e,,xml.dom.pulldom.DOMEventStream}, @ref{93f,,wsgiref.util.FileWrapper}
and @ref{940,,fileinput.FileInput}.

@item 
bpo-33613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33613}: Fix a race condition in @code{multiprocessing.semaphore_tracker}
when the tracker receives SIGINT before it can register signal handlers
for ignoring it.

@item 
bpo-34248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34248}: Report filename in the exception raised when the database file
cannot be opened by @ref{1e20,,dbm.gnu.open()} and @ref{1e21,,dbm.ndbm.open()} due to
OS-related error. Patch by Zsolt Cserna.

@item 
bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089}: Add math.dist() to compute the Euclidean distance between two
points.

@item 
bpo-34246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34246}: @ref{105a,,smtplib.SMTP.send_message()} no longer modifies the
content of the `mail_options' argument. Patch by Pablo S. Blum de Aguiar.

@item 
bpo-31047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31047}: Fix @code{ntpath.abspath} for invalid paths on windows. Patch by
Franz Woellert.

@item 
bpo-32321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32321}: Add pure Python fallback for functools.reduce. Patch by Robert
Wright.

@item 
bpo-34270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34270}: The default asyncio task class now always has a name which can
be get or set using two new methods (@ref{bd1,,get_name()} and
@ref{bd0,,set_name()}) and is visible in the @ref{1c1,,repr()} output.
An initial name can also be set using the new @code{name} keyword argument to
@ref{1c9,,asyncio.create_task()} or the
@code{create_task()} method of the event loop.
If no initial name is set, the default Task implementation generates a
name like @code{Task-1} using a monotonic counter.

@item 
bpo-34263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34263}: asyncio's event loop will not pass timeouts longer than one day
to epoll/select etc.

@item 
bpo-34035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34035}: Fix several AttributeError in zipfile seek() methods. Patch by
Mickaël Schoentgen.

@item 
bpo-32215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32215}: Fix performance regression in @ref{d4,,sqlite3} when a DML
statement appeared in a different line than the rest of the SQL query.

@item 
bpo-34075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34075}: Deprecate passing non-ThreadPoolExecutor instances to
@code{AbstractEventLoop.set_default_executor()}.

@item 
bpo-34251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34251}: Restore @code{msilib.Win64} to preserve backwards compatibility
since it's already used by @code{distutils}' @code{bdist_msi} command.

@item 
bpo-19891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19891}: Ignore errors caused by missing / non-writable homedir while
writing history during exit of an interactive session.  Patch by Anthony
Sottile.

@item 
bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089}: Enhanced math.hypot() to support more than two dimensions.

@item 
bpo-34228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34228}: tracemalloc: PYTHONTRACEMALLOC=0 environment variable and -X
tracemalloc=0 command line option are now allowed to disable explicitly
tracemalloc at startup.

@item 
bpo-13041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13041}: Use @ref{131b,,shutil.get_terminal_size()} to calculate the terminal
width correctly in the @code{argparse.HelpFormatter} class.  Initial patch by
Zbyszek Jędrzejewski-Szmek.

@item 
bpo-34213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34213}: Allow frozen dataclasses to have a field named "object".
Previously this conflicted with an internal use of "object".

@item 
bpo-34052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34052}: @ref{5a8,,sqlite3.Connection.create_aggregate()},
@ref{5a7,,sqlite3.Connection.create_function()},
@ref{5a9,,sqlite3.Connection.set_authorizer()},
@ref{5aa,,sqlite3.Connection.set_progress_handler()} methods raises TypeError
when unhashable objects are passed as callable. These methods now don't
pass such objects to SQLite API. Previous behavior could lead to
segfaults. Patch by Sergey Fedoseev.

@item 
bpo-34197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34197}: Attributes `skipinitialspace', `doublequote' and `strict' of
the `dialect' attribute of the @ref{2d,,csv} reader are now @ref{3c3,,bool}
instances instead of integers 0 or 1.

@item 
bpo-32788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32788}: Errors other than @ref{198,,TypeError} raised in methods
@code{__adapt__()} and @code{__conform__()} in the @ref{d4,,sqlite3} module are now
propagated to the user.

@item 
bpo-21446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21446}: The @code{reload} fixer now uses @ref{73d,,importlib.reload()} instead
of deprecated @code{imp.reload()}.

@item 
bpo-940286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=940286}: pydoc's @code{Helper.showtopic()} method now prints the cross
references of a topic correctly.

@item 
bpo-34164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34164}: @ref{1226,,base64.b32decode()} could raise UnboundLocalError or
OverflowError for incorrect padding.  Now it always raises
@code{base64.Error} in these cases.

@item 
bpo-33729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33729}: Fixed issues with arguments parsing in @ref{6c,,hashlib}.

@item 
bpo-34097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34097}: ZipFile can zip files older than 1980-01-01 and newer than
2107-12-31 using a new @code{strict_timestamps} parameter at the cost of
setting the timestamp to the limit.

@item 
bpo-34108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34108}: Remove extraneous CR in 2to3 refactor.

@item 
bpo-34070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34070}: Make sure to only check if the handle is a tty, when opening a
file with @code{buffering=-1}.

@item 
bpo-27494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27494}: Reverted bpo-27494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27494}. 2to3 rejects now a trailing comma in
generator expressions.

@item 
bpo-33967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33967}: functools.singledispatch now raises TypeError instead of
IndexError when no positional arguments are passed.

@item 
bpo-34041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34041}: Add the parameter `deterministic' to the
@ref{5a7,,sqlite3.Connection.create_function()} method. Patch by Sergey
Fedoseev.

@item 
bpo-34056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34056}: Ensure the loader shim created by @code{imp.load_module} always
returns bytes from its @code{get_data()} function. This fixes using
@code{imp.load_module} with 
@geindex Python Enhancement Proposals; PEP 552
PEP 552@footnote{https://peps.python.org/pep-0552/} hash-based pycs.

@item 
bpo-34054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34054}: The multiprocessing module now uses the monotonic clock
@ref{55c,,time.monotonic()} instead of the system clock @ref{55d,,time.time()} to
implement timeout.

@item 
bpo-34043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34043}: Optimize tarfile uncompress performance about 15% when gzip is
used.

@item 
bpo-34044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34044}: @code{subprocess.Popen} now copies the `startupinfo' argument to
leave it unchanged: it will modify the copy, so that the same
@code{STARTUPINFO} object can be used multiple times.

@item 
bpo-34010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34010}: Fixed a performance regression for reading streams with
tarfile. The buffered read should use a list, instead of appending to a
bytes object.

@item 
bpo-34019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34019}: webbrowser: Correct the arguments passed to Opera Browser when
opening a new URL using the @code{webbrowser} module. Patch by Bumsik Kim.

@item 
bpo-34003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34003}: csv.DictReader now creates dicts instead of OrderedDicts. Patch
by Michael Selik.

@item 
bpo-33978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33978}: Closed existing logging handlers before reconfiguration via
fileConfig and dictConfig. Patch by Karthikeyan Singaravelan.

@item 
bpo-14117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14117}: Make minor tweaks to turtledemo. The 'wikipedia' example is now
'rosette', describing what it draws.  The 'penrose' print output is
reduced. The'1024' output of 'tree' is eliminated.

@item 
bpo-33974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33974}: Fixed passing lists and tuples of strings containing special
characters @code{"}, @code{\}, @code{@{}, @code{@}} and @code{\n} as options to
@ref{ff,,ttk} widgets.

@item 
bpo-27500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27500}: Fix getaddrinfo to resolve IPv6 addresses correctly.

@item 
bpo-24567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24567}: Improve random.choices() to handle subnormal input weights that
could occasionally trigger an IndexError.

@item 
bpo-33871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33871}: Fixed integer overflow in @ref{d55,,os.readv()}, @ref{d58,,os.writev()},
@ref{d54,,os.preadv()} and @ref{d57,,os.pwritev()} and in @ref{d05,,os.sendfile()} with
`headers' or `trailers' arguments (on BSD-based OSes and macOS).

@item 
bpo-25007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25007}: Add @ref{757,,copy.copy()} and @ref{d65,,copy.deepcopy()} support to zlib
compressors and decompressors.  Patch by Zackery Spytz.

@item 
bpo-33929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33929}: multiprocessing: Fix a race condition in Popen of
multiprocessing.popen_spawn_win32. The child process now duplicates the
read end of pipe instead of "stealing" it. Previously, the read end of
pipe was "stolen" by the child process, but it leaked a handle if the
child process had been terminated before it could steal the handle from
the parent process.

@item 
bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899}: Tokenize module now implicitly emits a NEWLINE when provided
with input that does not have a trailing new line.  This behavior now
matches what the C tokenizer does internally.  Contributed by Ammar Askar.

@item 
bpo-33897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33897}: Added a 'force' keyword argument to logging.basicConfig().

@item 
bpo-33695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33695}: @ref{c1e,,shutil.copytree()} uses @ref{c54,,os.scandir()} function and
all copy functions depending from it use cached @ref{26d,,os.stat()} values.
The speedup for copying a directory with 8000 files is around +9% on
Linux, +20% on Windows and + 30% on a Windows SMB share. Also the number
of @ref{26d,,os.stat()} syscalls is reduced by 38% making
@ref{c1e,,shutil.copytree()} especially faster on network filesystems.
(Contributed by Giampaolo Rodola' in bpo-33695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33695}.)

@item 
bpo-33916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33916}: bz2 and lzma: When Decompressor.__init__() is called twice,
free the old lock to not leak memory.

@item 
bpo-32568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32568}: Make select.epoll() and its documentation consistent regarding
`sizehint' and `flags'.

@item 
bpo-33833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33833}: Fixed bug in asyncio where ProactorSocketTransport logs
AssertionError if force closed during write.

@item 
bpo-33663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33663}: Convert content length to string before putting to header.

@item 
bpo-33721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33721}: @ref{a6,,os.path} functions that return a boolean result like
@ref{c03,,exists()}, @ref{c04,,lexists()}, @ref{c05,,isdir()},
@ref{c06,,isfile()}, @ref{c01,,islink()}, and
@ref{c07,,ismount()}, and @ref{266,,pathlib.Path} methods that return a
boolean result like @ref{c0b,,exists()},
@ref{53a,,is_dir()}, @ref{539,,is_file()},
@ref{c0c,,is_mount()}, @ref{c0d,,is_symlink()},
@ref{c0e,,is_block_device()},
@ref{c0f,,is_char_device()}, @ref{c10,,is_fifo()},
@ref{c11,,is_socket()} now return @code{False} instead of raising
@ref{2ec,,ValueError} or its subclasses @ref{887,,UnicodeEncodeError} and
@ref{c08,,UnicodeDecodeError} for paths that contain characters or bytes
unrepresentable at the OS level.

@item 
bpo-26544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26544}: Fixed implementation of @ref{17f5,,platform.libc_ver()}. It almost
always returned version '2.9' for glibc.

@item 
bpo-33843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33843}: Remove deprecated @code{cgi.escape}, @code{cgi.parse_qs} and
@code{cgi.parse_qsl}.

@item 
bpo-33842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33842}: Remove @code{tarfile.filemode} which is deprecated since Python
3.3.

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by
Steve Weber.

@item 
bpo-33805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33805}: Improve error message of dataclasses.replace() when an InitVar
is not specified

@item 
bpo-33687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33687}: Fix the call to @code{os.chmod()} for @code{uu.decode()} if a mode is
given or decoded. Patch by Timo Furrer.

@item 
bpo-33812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33812}: Datetime instance d with non-None tzinfo, but with
d.tzinfo.utcoffset(d) returning None is now treated as naive by the
astimezone() method.

@item 
bpo-32108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32108}: In configparser, don't clear section when it is assigned to
itself.

@item 
bpo-27397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27397}: Make email module properly handle invalid-length base64
strings.

@item 
bpo-33578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33578}: Implement multibyte encoder/decoder state methods

@item 
bpo-30805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30805}: Avoid race condition with debug logging

@item 
bpo-33476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33476}: Fix _header_value_parser.py when address group is missing final
';'. Contributed by Enrique Perez-Terron

@item 
bpo-33694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33694}: asyncio: Fix a race condition causing data loss on
pause_reading()/resume_reading() when using the ProactorEventLoop.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Correct test for @code{uuid_enc_be} availability in
@code{configure.ac}. Patch by Michael Felt.

@item 
bpo-33792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33792}: Add asyncio.WindowsSelectorEventLoopPolicy and
asyncio.WindowsProactorEventLoopPolicy.

@item 
bpo-33274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33274}: W3C DOM Level 1 specifies return value of
Element.removeAttributeNode() as "The Attr node that was removed."
xml.dom.minidom now complies with this requirement.

@item 
bpo-33778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33778}: Update @code{unicodedata}'s database to Unicode version 11.0.0.

@item 
bpo-33165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33165}: Added a stacklevel parameter to logging calls to allow use of
wrapper/helper functions for logging APIs.

@item 
bpo-33770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33770}: improve base64 exception message for encoded inputs of invalid
length

@item 
bpo-33769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33769}: asyncio/start_tls: Fix error message; cancel callbacks in case
of an unhandled error; mark SSLTransport as closed if it is aborted.

@item 
bpo-33767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33767}: The concatenation (@code{+}) and repetition (@code{*}) sequence
operations now raise @ref{198,,TypeError} instead of @ref{795,,SystemError} when
performed on @ref{519,,mmap.mmap} objects.  Patch by Zackery Spytz.

@item 
bpo-33734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33734}: asyncio/ssl: Fix AttributeError, increase default handshake
timeout

@item 
bpo-31014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31014}: Fixed creating a controller for @ref{11b,,webbrowser} when a user
specifies a path to an entry in the BROWSER environment variable.  Based
on patch by John Still.

@item 
bpo-2504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2504}: Add gettext.pgettext() and variants.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Add description property for _ParameterKind

@item 
bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}: When cancelling the task due to a timeout,
@ref{815,,asyncio.wait_for()} will now wait until the cancellation is complete.

@item 
bpo-32684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32684}: Fix gather to propagate cancellation of itself even with
return_exceptions.

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Support protocol type switching in SSLTransport.set_protocol().

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Pause the transport as early as possible to further reduce the
risk of data_received() being called before connection_made().

@item 
bpo-33671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33671}: @ref{c4e,,shutil.copyfile()}, @ref{c4f,,shutil.copy()},
@ref{c50,,shutil.copy2()}, @ref{c1e,,shutil.copytree()} and @ref{c51,,shutil.move()} use
platform-specific fast-copy syscalls on Linux and macOS in order to copy
the file more efficiently. On Windows @ref{c4e,,shutil.copyfile()} uses a
bigger default buffer size (1 MiB instead of 16 KiB) and a
@ref{165,,memoryview()}-based variant of @ref{c52,,shutil.copyfileobj()} is used.
The speedup for copying a 512MiB file is about +26% on Linux, +50% on
macOS and +40% on Windows. Also, much less CPU cycles are consumed.
(Contributed by Giampaolo Rodola' in bpo-25427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25427}.)

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Fix a race condition in SSLProtocol.connection_made() of
asyncio.sslproto: start immediately the handshake instead of using
call_soon(). Previously, data_received() could be called before the
handshake started, causing the handshake to hang or fail.

@item 
bpo-31647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31647}: Fixed bug where calling write_eof() on a
_SelectorSocketTransport after it's already closed raises AttributeError.

@item 
bpo-32610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32610}: Make asyncio.all_tasks() return only pending tasks.

@item 
bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410}: Avoid blocking on file IO in sendfile fallback code

@item 
bpo-33469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33469}: Fix RuntimeError after closing loop that used run_in_executor

@item 
bpo-33672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33672}: Fix Task.__repr__ crash with Cython's bogus coroutines

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Fix transport.set_protocol() to support switching between
asyncio.Protocol and asyncio.BufferedProtocol.  Fix loop.start_tls() to
work with asyncio.BufferedProtocols.

@item 
bpo-33652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33652}: Pickles of type variables and subscripted generics are now
future-proof and compatible with older Python versions.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Fixed @ref{da1,,uuid.uuid1()} on FreeBSD.

@item 
bpo-33238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33238}: Add @code{InvalidStateError} to @ref{24,,concurrent.futures}.
@code{Future.set_result} and @code{Future.set_exception} now raise
@code{InvalidStateError} if the futures are not pending or running. Patch by
Jason Haydaman.

@item 
bpo-33618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33618}: Finalize and document preliminary and experimental TLS 1.3
support with OpenSSL 1.1.1

@item 
bpo-33625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33625}: Release GIL on @code{grp.getgrnam}, @code{grp.getgrgid},
@code{pwd.getpwnam} and @code{pwd.getpwuid} if reentrant variants of these
functions are available. Patch by William Grzybowski.

@item 
bpo-33623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33623}: Fix possible SIGSGV when asyncio.Future is created in __del__

@item 
bpo-11874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11874}: Use a better regex when breaking usage into wrappable parts.
Avoids bogus assertion errors from custom metavar strings.

@item 
bpo-30877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30877}: Fixed a bug in the Python implementation of the JSON decoder
that prevented the cache of parsed strings from clearing after finishing
the decoding. Based on patch by c-fos.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Remove HMAC default to md5 marked for removal in 3.8 (removal
originally planned in 3.6, bump to 3.8 in PR 7062).

@item 
bpo-33582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33582}: Emit a deprecation warning for inspect.formatargspec

@item 
bpo-21145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21145}: Add @code{functools.cached_property} decorator, for computed
properties cached for the life of the instance.

@item 
bpo-33570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33570}: Change TLS 1.3 cipher suite settings for compatibility with
OpenSSL 1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 ciphers
enabled by default.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Do not simplify arguments to @code{typing.Union}. Now
@code{Union[Manager, Employee]} is not simplified to @code{Employee} at runtime.
Such simplification previously caused several bugs and limited
possibilities for introspection.

@item 
bpo-12486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12486}: @ref{701,,tokenize.generate_tokens()} is now documented as a public
API to tokenize unicode strings. It was previously present but
undocumented.

@item 
bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540}: Add a new @code{block_on_close} class attribute to
@code{ForkingMixIn} and @code{ThreadingMixIn} classes of @ref{d2,,socketserver}.

@item 
bpo-33548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33548}: tempfile._candidate_tempdir_list should consider common TEMP
locations

@item 
bpo-33109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33109}: argparse subparsers are once again not required by default,
reverting the change in behavior introduced by bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510} in 3.7.0a2.

@item 
bpo-33541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33541}: Remove unused private method @code{_strptime.LocaleTime.__pad}
(a.k.a. @code{_LocaleTime__pad}).

@item 
bpo-33536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33536}: dataclasses.make_dataclass now checks for invalid field names
and duplicate fields. Also, added a check for invalid field
specifications.

@item 
bpo-33542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33542}: Prevent @code{uuid.get_node} from using a DUID instead of a MAC on
Windows. Patch by Zvi Effron

@item 
bpo-26819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26819}: Fix race condition with @code{ReadTransport.resume_reading} in
Windows proactor event loop.

@item 
Fix failure in @code{typing.get_type_hints()} when ClassVar was provided as a
string forward reference.

@item 
bpo-33516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33516}: @ref{108f,,unittest.mock.MagicMock} now supports the @code{__round__}
magic method.

@item 
bpo-28612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28612}: Added support for Site Maps to urllib's @code{RobotFileParser} as
@ref{1e22,,RobotFileParser.site_maps()}. Patch by Lady Red, based
on patch by Peter Wirtz.

@item 
bpo-28167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28167}: Remove platform.linux_distribution, which was deprecated since
3.5.

@item 
bpo-33504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33504}: Switch the default dictionary implementation for
@ref{26,,configparser} from @ref{7f3,,collections.OrderedDict} to the standard
@ref{183,,dict} type.

@item 
bpo-33505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33505}: Optimize asyncio.ensure_future() by reordering if checks: 1.17x
faster.

@item 
bpo-33497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33497}: Add errors param to cgi.parse_multipart and make an encoding in
FieldStorage use the given errors (needed for Twisted).  Patch by Amber
Brown.

@item 
bpo-29235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29235}: The @code{cProfile.Profile} class can now be used as a
context manager. Patch by Scott Sanderson.

@item 
bpo-33495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33495}: Change dataclasses.Fields repr to use the repr of each of its
members, instead of str.  This makes it more clear what each field
actually represents.  This is especially true for the 'type' member.

@item 
bpo-26103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26103}: Correct @code{inspect.isdatadescriptor} to look for @code{__set__} or
@code{__delete__}.  Patch by Aaron Hall.

@item 
bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209}: Removed the @code{doctype()} method and the `html' parameter of
the constructor of @ref{c49,,XMLParser}.  The
@code{doctype()} method defined in a subclass will no longer be called.
Deprecated methods @code{getchildren()} and @code{getiterator()} in the
@ref{12b,,ElementTree} module emit now a @ref{1a3,,DeprecationWarning}
instead of @ref{ac5,,PendingDeprecationWarning}.

@item 
bpo-33453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33453}: Fix dataclasses to work if using literal string type
annotations or if using PEP 563 "Postponed Evaluation of Annotations".
Only specific string prefixes are detected for both ClassVar ("ClassVar"
and "typing.ClassVar") and InitVar ("InitVar" and "dataclasses.InitVar").

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Minor fixes in typing module: add annotations to
@code{NamedTuple.__new__}, pass @code{*args} and @code{**kwds} in
@code{Generic.__new__}.  Original PRs by Paulius Šarka and Chad Dombrova.

@item 
bpo-33365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33365}: Print the header values besides the header keys instead just
the header keys if `debuglevel' is set to >0 in @ref{73,,http.client}. Patch
by Marco Strigl.

@item 
bpo-20087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20087}: Updated alias mapping with glibc 2.27 supported locales.

@item 
bpo-33422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33422}: Fix trailing quotation marks getting deleted when looking up
byte/string literals on pydoc. Patch by Andrés Delfino.

@item 
bpo-28167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28167}: The function @code{platform.linux_distribution} and
@code{platform.dist} now trigger a @code{DeprecationWarning} and have been
marked for removal in Python 3.8

@item 
bpo-33281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33281}: Fix ctypes.util.find_library regression on macOS.

@item 
bpo-33311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33311}: Text and html output generated by cgitb does not display
parentheses if the current call is done directly in the module. Patch by
Stéphane Blondon.

@item 
bpo-27300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27300}: The file classes in `tempfile' now accept an `errors' parameter
that complements the already existing `encoding'.  Patch by Stephan Hohe.

@item 
bpo-32933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32933}: @ref{11e9,,unittest.mock.mock_open()} now supports iteration over the
file contents. Patch by Tony Flury.

@item 
bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217}: Raise @ref{198,,TypeError} when looking up non-Enum objects in Enum
classes and Enum members.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Update error message when constructing invalid
inspect.Parameters Patch by Donghee Na.

@item 
bpo-33383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33383}: Fixed crash in the get() method of the @ref{38,,dbm.ndbm} database
object when it is called with a single argument.

@item 
bpo-33375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33375}: The warnings module now finds the Python file associated with a
warning from the code object, rather than the frame's global namespace.
This is consistent with how tracebacks and pdb find filenames, and should
work better for dynamically executed code.

@item 
bpo-33336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33336}: @code{imaplib} now allows @code{MOVE} command in @code{IMAP4.uid()} (RFC
6851: IMAP MOVE Extension) and potentially as a name of supported method
of @code{IMAP4} object.

@item 
bpo-32455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32455}: Added `jump' parameter to @ref{1132,,dis.stack_effect()}.

@item 
bpo-27485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27485}: Rename and deprecate undocumented functions in
@ref{110,,urllib.parse()}.

@item 
bpo-33332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33332}: Add @code{signal.valid_signals()} to expose the POSIX sigfillset()
functionality.

@item 
bpo-33251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33251}: @code{ConfigParser.items()} was fixed so that key-value pairs
passed in via @ref{1e23,,vars()} are not included in the resulting output.

@item 
bpo-33329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33329}: Fix multiprocessing regression on newer glibcs

@item 
bpo-33334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33334}: @ref{1132,,dis.stack_effect()} now supports all defined opcodes
including NOP and EXTENDED_ARG.

@item 
bpo-991266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=991266}: Fix quoting of the @code{Comment} attribute of
@ref{1e24,,http.cookies.SimpleCookie}.

@item 
bpo-33131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33131}: Upgrade bundled version of pip to 10.0.1.

@item 
bpo-33308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33308}: Fixed a crash in the @code{parser} module when converting an ST
object to a tree of tuples or lists with @code{line_info=False} and
@code{col_info=True}.

@item 
bpo-23403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23403}: lib2to3 now uses pickle protocol 4 for pre-computed grammars.

@item 
bpo-33266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33266}: lib2to3 now recognizes @code{rf'...'} strings.

@item 
bpo-11594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11594}: Ensure line-endings are respected when using lib2to3.

@item 
bpo-33254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33254}: Have @ref{503,,importlib.resources.contents()} and
@code{importlib.abc.ResourceReader.contents()} return an @ref{12f1,,iterable}
instead of an @ref{4c8,,iterator}.

@item 
bpo-33265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33265}: @code{contextlib.ExitStack} and @code{contextlib.AsyncExitStack} now
use a method instead of a wrapper function for exit callbacks.

@item 
bpo-33263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33263}: Fix FD leak in @code{_SelectorSocketTransport}  Patch by Vlad
Starostin.

@item 
bpo-33256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33256}: Fix display of @code{<module>} call in the html produced by
@code{cgitb.html()}. Patch by Stéphane Blondon.

@item 
bpo-33144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33144}: @code{random.Random()} and its subclassing mechanism got optimized
to check only once at class/subclass instantiation time whether its
@code{getrandbits()} method can be relied on by other methods, including
@code{randrange()}, for the generation of arbitrarily large random integers.
Patch by Wolfgang Maier.

@item 
bpo-33185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33185}: Fixed regression when running pydoc with the @ref{23c,,-m}
switch. (The regression was introduced in 3.7.0b3 by the resolution of
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053})

This fix also changed pydoc to add @code{os.getcwd()} to @ref{3e4,,sys.path}
when necessary, rather than adding @code{"."}.

@item 
bpo-29613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29613}: Added support for the @code{SameSite} cookie flag to the
@code{http.cookies} module.

@item 
bpo-33169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33169}: Delete entries of @code{None} in @ref{7fa,,sys.path_importer_cache}
when @code{importlib.machinery.invalidate_caches()} is called.

@item 
bpo-33203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33203}: @code{random.Random.choice()} now raises @code{IndexError} for empty
sequences consistently even when called from subclasses without a
@code{getrandbits()} implementation.

@item 
bpo-33224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33224}: Update difflib.mdiff() for 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/}.  Convert an uncaught
StopIteration in a generator into a return-statement.

@item 
bpo-33209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33209}: End framing at the end of C implementation of
@ref{1e25,,pickle.Pickler.dump()}.

@item 
bpo-32861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32861}: The urllib.robotparser's @code{__str__} representation now
includes wildcard entries and the "Crawl-delay" and "Request-rate" fields.
Also removes extra newlines that were being appended to the end of the
string. Patch by Michael Lazar.

@item 
bpo-23403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23403}: @code{DEFAULT_PROTOCOL} in @ref{ab,,pickle} was bumped to 4. Protocol
4 is described in 
@geindex Python Enhancement Proposals; PEP 3154
PEP 3154@footnote{https://peps.python.org/pep-3154/} and available since Python 3.4. It offers
better performance and smaller size compared to protocol 3 introduced in
Python 3.0.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Improved error handling and fixed a reference leak in
@ref{52e,,os.posix_spawn()}.

@item 
bpo-33106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33106}: Deleting a key from a read-only dbm database raises module
specific error instead of KeyError.

@item 
bpo-33175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33175}: In dataclasses, Field.__set_name__ now looks up the
__set_name__ special method on the class, not the instance, of the default
value.

@item 
bpo-32380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32380}: Create functools.singledispatchmethod to support generic single
dispatch on descriptors and methods.

@item 
bpo-33141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33141}: Have Field objects pass through __set_name__ to their default
values, if they have their own __set_name__.

@item 
bpo-33096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33096}: Allow ttk.Treeview.insert to insert iid that has a false
boolean value. Note iid=0 and iid=False would be same. Patch by Garvit
Khatri.

@item 
bpo-32873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32873}: Treat type variables and special typing forms as immutable by
copy and pickle.  This fixes several minor issues and inconsistencies, and
improves backwards compatibility with Python 3.6.

@item 
bpo-33134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33134}: When computing dataclass's __hash__, use the lookup table to
contain the function which returns the __hash__ value.  This is an
improvement over looking up a string, and then testing that string to see
what to do.

@item 
bpo-33127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33127}: The ssl module now compiles with LibreSSL 2.7.1.

@item 
bpo-32505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32505}: Raise TypeError if a member variable of a dataclass is of type
Field, but doesn't have a type annotation.

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the failure on OSX caused by the tests relying on
sem_getvalue

@item 
bpo-33116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33116}: Add 'Field' to dataclasses.__all__.

@item 
bpo-32896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32896}: Fix an error where subclassing a dataclass with a field that
uses a default_factory would generate an incorrect class.

@item 
bpo-33100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33100}: Dataclasses: If a field has a default value that's a
MemberDescriptorType, then it's from that field being in __slots__, not an
actual default value.

@item 
bpo-32953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32953}: If a non-dataclass inherits from a frozen dataclass, allow
attributes to be added to the derived class.  Only attributes from the
frozen dataclass cannot be assigned to.  Require all dataclasses in a
hierarchy to be either all frozen or all non-frozen.

@item 
bpo-33097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33097}: Raise RuntimeError when @code{executor.submit} is called during
interpreter shutdown.

@item 
bpo-32968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32968}: Modulo and floor division involving Fraction and float should
return float.

@item 
bpo-33061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33061}: Add missing @code{NoReturn} to @code{__all__} in typing.py

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the size handling in multiprocessing.Queue when a pickling
error occurs.

@item 
bpo-33064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33064}: lib2to3 now properly supports trailing commas after @code{*args}
and @code{**kwargs} in function signatures.

@item 
bpo-33056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33056}: FIX properly close leaking fds in
concurrent.futures.ProcessPoolExecutor.

@item 
bpo-33021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33021}: Release the GIL during fstat() calls, avoiding hang of all
threads when calling mmap.mmap(), os.urandom(), and random.seed().  Patch
by Nir Soffer.

@item 
bpo-31804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31804}: Avoid failing in multiprocessing.Process if the standard
streams are closed or None at exit.

@item 
bpo-33034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33034}: Providing an explicit error message when casting the port
property to anything that is not an integer value using @code{urlparse()} and
@code{urlsplit()}. Patch by Matt Eaton.

@item 
bpo-30249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30249}: Improve struct.unpack_from() exception messages for problems
with the buffer size and offset.

@item 
bpo-33037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33037}: Skip sending/receiving data after SSL transport closing.

@item 
bpo-27683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27683}: Fix a regression in @ref{84,,ipaddress} that result of
@code{hosts()} is empty when the network is constructed by a tuple
containing an integer mask and only 1 bit left for addresses.

@item 
bpo-22674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22674}: Add the strsignal() function in the signal module that returns
the system description of the given signal, as returned by strsignal(3).

@item 
bpo-32999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32999}: Fix C implementation of @code{ABC.__subclasscheck__(cls,
subclass)} crashed when @code{subclass} is not a type object.

@item 
bpo-33009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33009}: Fix inspect.signature() for single-parameter partialmethods.

@item 
bpo-32969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32969}: Expose several missing constants in zlib and fix corresponding
documentation.

@item 
bpo-32056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32056}: Improved exceptions raised for invalid number of channels and
sample width when read an audio file in modules @code{aifc}, @ref{119,,wave}
and @code{sunau}.

@item 
bpo-32970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32970}: Improved disassembly of the MAKE_FUNCTION instruction.

@item 
bpo-32844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32844}: Fix wrong redirection of a low descriptor (0 or 1) to stderr in
subprocess if another low descriptor is closed.

@item 
bpo-32960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32960}: For dataclasses, disallow inheriting frozen from non-frozen
classes, and also disallow inheriting non-frozen from frozen classes. This
restriction will be relaxed at a future date.

@item 
bpo-32713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32713}: Fixed tarfile.itn handling of out-of-bounds float values. Patch
by Joffrey Fuhrer.

@item 
bpo-32257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32257}: The ssl module now contains OP_NO_RENEGOTIATION constant,
available with OpenSSL 1.1.0h or 1.1.1.

@item 
bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951}: Direct instantiation of SSLSocket and SSLObject objects is now
prohibited. The constructors were never documented, tested, or designed as
public constructors. Users were suppose to use ssl.wrap_socket() or
SSLContext.

@item 
bpo-32929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32929}: Remove the tri-state parameter "hash", and add the boolean
"unsafe_hash". If unsafe_hash is True, add a __hash__ function, but if a
__hash__ exists, raise TypeError.  If unsafe_hash is False, add a __hash__
based on the values of eq= and frozen=.  The unsafe_hash=False behavior is
the same as the old hash=None behavior.  unsafe_hash=False is the default,
just as hash=None used to be.

@item 
bpo-32947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32947}: Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround for TLSv1.3
for future compatibility with OpenSSL 1.1.1.

@item 
bpo-32146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32146}: Document the interaction between frozen executables and the
spawn and forkserver start methods in multiprocessing.

@item 
bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622}: The ssl module now detects missing NPN support in LibreSSL.

@item 
bpo-32922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32922}: dbm.open() now encodes filename with the filesystem encoding
rather than default encoding.

@item 
bpo-32759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32759}: Free unused arenas in multiprocessing.heap.

@item 
bpo-32859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32859}: In @code{os.dup2}, don't check every call whether the @code{dup3}
syscall exists or not.

@item 
bpo-32556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32556}: nt._getfinalpathname, nt._getvolumepathname and
nt._getdiskusage now correctly convert from bytes.

@item 
bpo-21060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21060}: Rewrite confusing message from setup.py upload from "No dist
file created in earlier command" to the more helpful "Must create and
upload files in one command".

@item 
bpo-32857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32857}: In @ref{f6,,tkinter}, @code{after_cancel(None)} now raises a
@ref{2ec,,ValueError} instead of canceling the first scheduled function.
Patch by Cheryl Sabella.

@item 
bpo-32852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32852}: Make sure sys.argv remains as a list when running trace.

@item 
bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333}: @code{_abc} module is added.  It is a speedup module with C
implementations for various functions and methods in @code{abc}.  Creating an
ABC subclass and calling @code{isinstance} or @code{issubclass} with an ABC
subclass are up to 1.5x faster. In addition, this makes Python start-up up
to 10% faster.

Note that the new implementation hides internal registry and caches,
previously accessible via private attributes @code{_abc_registry},
@code{_abc_cache}, and @code{_abc_negative_cache}.  There are three debugging
helper methods that can be used instead @code{_dump_registry},
@code{_abc_registry_clear}, and @code{_abc_caches_clear}.

@item 
bpo-32841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32841}: Fixed @code{asyncio.Condition} issue which silently ignored
cancellation after notifying and cancelling a conditional lock. Patch by
Bar Harel.

@item 
bpo-32819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32819}: ssl.match_hostname() has been simplified and no longer depends
on re and ipaddress module for wildcard and IP addresses. Error reporting
for invalid wildcards has been improved.

@item 
bpo-19675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19675}: @code{multiprocessing.Pool} no longer leaks processes if its
initialization fails.

@item 
bpo-32394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32394}: socket: Remove
TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older version
Windows during run-time.

@item 
bpo-31787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31787}: Fixed refleaks of @code{__init__()} methods in various modules.
(Contributed by Oren Milman)

@item 
bpo-30157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30157}: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when
only the last field is quoted.  Patch by Jake Davis.

@item 
bpo-30688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30688}: Added support of @code{\N@{name@}} escapes in regular expressions.
Based on patch by Jonathan Eunice.

@item 
bpo-32792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32792}: collections.ChainMap() preserves the order of the underlying
mappings.

@item 
bpo-32775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32775}: @ref{184f,,fnmatch.translate()} no longer produces patterns which
contain set operations. Sets starting with '[' or containing '--', '&&',
'~~' or '||' will be interpreted differently in regular expressions in
future versions. Currently they emit warnings. fnmatch.translate() now
avoids producing patterns containing such sets by accident.

@item 
bpo-32622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32622}: Implement native fast sendfile for Windows proactor event loop.

@item 
bpo-32777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32777}: Fix a rare but potential pre-exec child process deadlock in
subprocess on POSIX systems when marking file descriptors inheritable on
exec in the child process.  This bug appears to have been introduced in
3.4.

@item 
bpo-32647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32647}: The ctypes module used to depend on indirect linking for
dlopen. The shared extension is now explicitly linked against libdl on
platforms with dl.

@item 
bpo-32749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32749}: A @ref{36,,dbm.dumb} database opened with flags 'r' is now
read-only. @ref{c8d,,dbm.dumb.open()} with flags 'r' and 'w' no longer creates
a database if it does not exist.

@item 
bpo-32741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32741}: Implement @code{asyncio.TimerHandle.when()} method.

@item 
bpo-32691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32691}: Use mod_spec.parent when running modules with pdb

@item 
bpo-32734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32734}: Fixed @code{asyncio.Lock()} safety issue which allowed acquiring
and locking the same lock multiple times, without it being free. Patch by
Bar Harel.

@item 
bpo-32727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32727}: Do not include name field in SMTP envelope from address. Patch
by Stéphane Wirtel

@item 
bpo-31453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31453}: Add TLSVersion constants and SSLContext.maximum_version /
minimum_version attributes. The new API wraps OpenSSL 1.1
@indicateurl{https://web.archive.org/web/20180309043602/https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html}
feature.

@item 
bpo-24334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24334}: Internal implementation details of ssl module were cleaned up.
The SSLSocket has one less layer of indirection. Owner and session
information are now handled by the SSLSocket and SSLObject constructor.
Channel binding implementation has been simplified.

@item 
bpo-31848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31848}: Fix the error handling in Aifc_read.initfp() when the SSND
chunk is not found. Patch by Zackery Spytz.

@item 
bpo-32585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32585}: Add Ttk spinbox widget to @ref{ff,,tkinter.ttk}.  Patch by Alan D
Moore.

@item 
bpo-32512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32512}: @ref{b4,,profile} CLI accepts @code{-m module_name} as an alternative
to script path.

@item 
bpo-8525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8525}: help() on a type now displays builtin subclasses. This is
intended primarily to help with notification of more specific exception
subclasses.

Patch by Sanyam Khurana.

@item 
bpo-31639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31639}: http.server now exposes a ThreadingHTTPServer class and uses it
when the module is run with @code{-m} to cope with web browsers pre-opening
sockets.

@item 
bpo-29877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29877}: compileall: import ProcessPoolExecutor only when needed,
preventing hangs on low resource platforms

@item 
bpo-32221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32221}: Various functions returning tuple containing IPv6 addresses now
omit @code{%scope} part since the same information is already encoded in
`scopeid' tuple item. Especially this speeds up @code{socket.recvfrom()}
when it receives multicast packet since useless resolving of network
interface name is omitted.

@item 
bpo-32147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32147}: @ref{1e26,,binascii.unhexlify()} is now up to 2 times faster. Patch
by Sergey Fedoseev.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The TarFile class now recurses directories in a reproducible
way.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The ZipFile class now recurses directories in a reproducible
way.

@item 
bpo-31680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31680}: Added @ref{bda,,curses.ncurses_version}.

@item 
bpo-31908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31908}: Fix output of cover files for @code{trace} module command-line
tool. Previously emitted cover files only when @code{--missing} option was
used. Patch by Michael Selik.

@item 
bpo-31608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31608}: Raise a @code{TypeError} instead of crashing if a
@code{collections.deque} subclass returns a non-deque from @code{__new__}. Patch
by Oren Milman.

@item 
bpo-31425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31425}: Add support for sockets of the AF_QIPCRTR address family,
supported by the Linux kernel. This is used to communicate with services,
such as GPS or radio, running on Qualcomm devices. Patch by Bjorn
Andersson.

@item 
bpo-22005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22005}: Implemented unpickling instances of
@ref{4e2,,datetime}, @ref{1fa,,date} and
@ref{1fb,,time} pickled by Python 2. @code{encoding='latin1'} should
be used for successful decoding.

@item 
bpo-27645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27645}: @ref{54d,,sqlite3.Connection} now exposes a
@ref{d73,,backup} method, if the underlying SQLite
library is at version 3.6.11 or higher.  Patch by Lele Gaifax.

@item 
bpo-16865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16865}: Support arrays >=2GiB in @ref{2e,,ctypes}.  Patch by Segev Finer.

@item 
bpo-31508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31508}: Removed support of arguments in
@code{tkinter.ttk.Treeview.selection}. It was deprecated in 3.6.  Use
specialized methods like @code{selection_set} for changing the selection.

@item 
bpo-29456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29456}: Fix bugs in hangul normalization: u1176, u11a7 and u11c3
@end itemize

@node ドキュメント<56>,テスト<54>,ライブラリ<162>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id747}@anchor{1e27}
@subsubsection ドキュメント



@itemize -

@item 
bpo-21257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21257}: Document @ref{1e28,,http.client.parse_headers()}.

@item 
bpo-34764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34764}: Improve example of iter() with 2nd sentinel argument.

@item 
bpo-35564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35564}: Explicitly set master_doc variable in conf.py for compliance
with Sphinx 2.0

@item 
bpo-35511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35511}: Specified that profile.Profile class doesn't not support enable
or disable methods. Also, elaborated that Profile object as a context
manager is only supported in cProfile module.

@item 
bpo-10536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10536}: Enhance the gettext docs. Patch by Éric Araujo

@item 
bpo-35089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35089}: Remove mention of @code{typing.io} and @code{typing.re}. Their types
should be imported from @code{typing} directly.

@item 
bpo-35038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35038}: Fix the documentation about an unexisting @code{f_restricted}
attribute in the frame object. Patch by Stéphane Wirtel

@item 
bpo-35042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35042}: Replace PEP XYZ by the pep role and allow to use the direct
links to the PEPs.

@item 
bpo-35044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35044}: Fix the documentation with the role @code{exc} for the
appropriated exception. Patch by Stéphane Wirtel

@item 
bpo-35035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35035}: Rename documentation for @ref{54,,email.utils} to
@code{email.utils.rst}.

@item 
bpo-34967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34967}: Use app.add_object_type() instead of the deprecated Sphinx
function app.description_unit()

@item 
bpo-34913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34913}: Add documentation about the new command line interface of the
gzip module.

@item 
bpo-32174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32174}: chm document displays non-ASCII characters properly on some
MBCS Windows systems.

@item 
bpo-11233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11233}: Create availability directive for documentation.  Original
patch by Georg Brandl.

@item 
bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790}: Document how passing coroutines to asyncio.wait() can be
confusing.

@item 
bpo-34552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34552}: Make clear that @code{==} operator sometimes is equivalent to
@code{is}. The @code{<}, @code{<=}, @code{>} and @code{>=} operators are only defined
where they make sense.

@item 
bpo-28617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28617}: Fixed info in the stdtypes docs concerning the types that
support membership tests.

@item 
bpo-20177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20177}: Migrate datetime.date.fromtimestamp to Argument Clinic. Patch
by Tim Hoffmann.

@item 
bpo-34065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34065}: Fix wrongly written basicConfig documentation markup syntax

@item 
bpo-33460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33460}: replaced ellipsis with correct error codes in tutorial chapter
3.

@item 
bpo-33847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33847}: Add '@@' operator entry to index.

@item 
bpo-33409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33409}: Clarified the relationship between 
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/}'s
PYTHONCOERCECLOCALE and PEP 540's PYTHONUTF8 mode.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Add versionadded tag to the documentation of
ParameterKind.description

@item 
bpo-17045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17045}: Improve the C-API doc for PyTypeObject.  This includes adding
several quick-reference tables and a lot of missing slot/typedef entries.
The existing entries were also cleaned up with a slightly more consistent
format.

@item 
bpo-33736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33736}: Improve the documentation of @ref{d0e,,asyncio.open_connection()},
@ref{d0f,,asyncio.start_server()} and their UNIX socket counterparts.

@item 
bpo-23859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23859}: Document that @code{asyncio.wait()} does not cancel its futures on
timeout.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Document 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} changes to asyncio.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Update HMAC md5 default to a DeprecationWarning, bump removal
to 3.8.

@item 
bpo-33594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33594}: Document @code{getargspec}, @code{from_function} and @code{from_builtin}
as deprecated in their respective docstring, and include version since
deprecation in DeprecationWarning message.

@item 
bpo-33503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33503}: Fix broken pypi link

@item 
bpo-33421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33421}: Add missing documentation for @code{typing.AsyncContextManager}.

@item 
bpo-33487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33487}: BZ2file now emit a DeprecationWarning when buffering=None is
passed, the deprecation message and documentation also now explicitly
state it is deprecated since 3.0.

@item 
bpo-33378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33378}: Add Korean language switcher for @indicateurl{https://docs.python.org/3/}

@item 
bpo-33276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33276}: Clarify that the @code{__path__} attribute on modules cannot be
just any value.

@item 
bpo-33201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33201}: Modernize documentation for writing C extension types.

@item 
bpo-33195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33195}: Deprecate @code{Py_UNICODE} usage in @code{c-api/arg} document.
@code{Py_UNICODE} related APIs are deprecated since Python 3.3, but it is
missed in the document.

@item 
bpo-33126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33126}: Document PyBuffer_ToContiguous().

@item 
bpo-27212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27212}: Modify documentation for the @code{islice()} recipe to consume
initial values up to the start index.

@item 
bpo-28247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28247}: Update @ref{136,,zipapp} documentation to describe how to make
standalone applications.

@item 
bpo-18802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18802}: Documentation changes for ipaddress.  Patch by Jon Foster and
Berker Peksag.

@item 
bpo-27428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27428}: Update documentation to clarify that @code{WindowsRegistryFinder}
implements @code{MetaPathFinder}. (Patch by Himanshu Lakhara)

@item 
bpo-28124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28124}: The ssl module function ssl.wrap_socket() has been
de-emphasized and deprecated in favor of the more secure and efficient
SSLContext.wrap_socket() method.

@item 
bpo-17232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17232}: Clarify docs for -O and -OO.  Patch by Terry Reedy.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Add documentation for the contextvars module (PEP 567).

@item 
bpo-32800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32800}: Update link to w3c doc for xml default namespaces.

@item 
bpo-11015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11015}: Update @ref{ea,,test.support} documentation.

@item 
bpo-32613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32613}: Update the faq/windows.html to use the py command from PEP 397
instead of python.

@item 
bpo-8722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8722}: Document @code{__getattr__()} behavior when property @code{get()}
method raises @ref{5f0,,AttributeError}.

@item 
bpo-32614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32614}: Modify RE examples in documentation to use raw strings to
prevent @ref{1a3,,DeprecationWarning} and add text to REGEX HOWTO to highlight
the deprecation.

@item 
bpo-20709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20709}: Remove the paragraph where we explain that os.utime() does not
support a directory as path under Windows. Patch by Jan-Philip Gehrcke

@item 
bpo-32722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32722}: Remove the bad example in the tutorial of the Generator
Expression. Patch by Stéphane Wirtel

@item 
bpo-31972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31972}: Improve docstrings for @code{pathlib.PurePath} subclasses.

@item 
bpo-30607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30607}: Use the externalized @code{python-docs-theme} package when
building the documentation.

@item 
bpo-8243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8243}: Add a note about curses.addch and curses.addstr exception
behavior when writing outside a window, or pad.

@item 
bpo-32337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32337}: Update documentation related with @code{dict} order.

@item 
bpo-25041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25041}: Document @code{AF_PACKET} in the @ref{d1,,socket} module.

@item 
bpo-31432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31432}: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED
flags for ssl.SSLContext.verify_mode.
@end itemize

@node テスト<54>,ビルド<61>,ドキュメント<56>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id748}@anchor{1e29}
@subsubsection テスト



@itemize -

@item 
bpo-35772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35772}: Fix sparse file tests of test_tarfile on ppc64 with the tmpfs
filesystem. Fix the function testing if the filesystem supports sparse
files: create a file which contains data and "holes", instead of creating
a file which contains no data. tmpfs effective block size is a page size
(tmpfs lives in the page cache). RHEL uses 64 KiB pages on aarch64, ppc64,
ppc64le, only s390x and x86_64 use 4 KiB pages, whereas the test punch
holes of 4 KiB.

@item 
bpo-35045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35045}: Make ssl tests less strict and also accept TLSv1 as system
default. The changes unbreaks test_min_max_version on Fedora 29.

@item 
bpo-32710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32710}: @code{test_asyncio/test_sendfile.py} now resets the event loop
policy using @code{tearDownModule()} as done in other tests, to prevent a
warning when running tests on Windows.

@item 
bpo-33717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33717}: test.pythoninfo now logs information of all clocks, not only
time.time() and time.perf_counter().

@item 
bpo-35488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35488}: Add a test to pathlib's Path.match() to verify it does not
support glob-style ** recursive pattern matching.

@item 
bpo-31731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31731}: Fix a race condition in @code{check_interrupted_write()} of
test_io: create directly the thread with SIGALRM signal blocked, rather
than blocking the signal later from the thread. Previously, it was
possible that the thread gets the signal before the signal is blocked.

@item 
bpo-35424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35424}: Fix test_multiprocessing_main_handling: use
@code{multiprocessing.Pool} with a context manager and then explicitly
join the pool.

@item 
bpo-35519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35519}: Rename @code{test.bisect} module to @code{test.bisect_cmd} to
avoid conflict with @ref{12,,bisect} module when running directly a test like
@code{./python Lib/test/test_xmlrpc.py}.

@item 
bpo-35513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35513}: Replace @ref{55d,,time.time()} with @ref{55c,,time.monotonic()} in tests
to measure time delta.

@item 
bpo-34279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34279}: @code{test.support.run_unittest()} no longer raise
@code{TestDidNotRun} if the test result contains skipped tests. The
exception is now only raised if no test have been run and no test have
been skipped.

@item 
bpo-35412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35412}: Add testcase to @code{test_future4}: check unicode literal.

@item 
bpo-26704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26704}: Added test demonstrating double-patching of an instance method.
Patch by Anthony Sottile.

@item 
bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725}: test_multiprocessing_fork may crash on recent versions of
macOS.  Until the issue is resolved, skip the test on macOS.

@item 
bpo-35352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35352}: Modify test_asyncio to use the certificate set from the test
directory.

@item 
bpo-35317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35317}: Fix @code{mktime()} overflow error in @code{test_email}: run
@code{test_localtime_daylight_true_dst_true()} and
@code{test_localtime_daylight_false_dst_true()} with a specific timezone.

@item 
bpo-21263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21263}: After several reports that test_gdb does not work properly on
macOS and since gdb is not shipped by default anymore, test_gdb is now
skipped on macOS when LLVM Clang has been used to compile Python. Patch by
Lysandros Nikolaou

@item 
bpo-34279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34279}: regrtest issue a warning when no tests have been executed in a
particular test file. Also, a new final result state is issued if no test
have been executed across all test files. Patch by Pablo Galindo.

@item 
bpo-34962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34962}: make docstest in Doc now passes., and is enforced in CI

@item 
bpo-23596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23596}: Use argparse for the command line of the gzip module. Patch by
Antony Lee

@item 
bpo-34537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34537}: Fix @code{test_gdb.test_strings()} when @code{LC_ALL=C} and GDB was
compiled with Python 3.6 or earlier.

@item 
bpo-34587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34587}: test_socket: Remove RDSTest.testCongestion(). The test tries to
fill the receiver's socket buffer and expects an error. But the RDS
protocol doesn't require that. Moreover, the Linux implementation of RDS
expects that the producer of the messages reduces its rate, it's not the
role of the receiver to trigger an error. The test fails on Fedora 28 by
design, so just remove it.

@item 
bpo-34661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34661}: Fix test_shutil if unzip doesn't support -t.

@item 
bpo-34200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34200}: Fixed non-deterministic flakiness of test_pkg by not using the
scary test.support.module_cleanup() logic to save and restore sys.modules
contents between test cases.

@item 
bpo-34569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34569}: The experimental PEP 554 data channels now correctly pass
negative PyLong objects between subinterpreters on 32-bit systems. Patch
by Michael Felt.

@item 
bpo-34594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34594}: Fix usage of hardcoded @code{errno} values in the tests.

@item 
bpo-34579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34579}: Fix test_embed for AIX Patch by Michael Felt

@item 
bpo-34542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34542}: Use 3072 RSA keys and SHA-256 signature for test certs and
keys.

@item 
bpo-11193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11193}: Remove special condition for AIX in
@code{test_subprocess.test_undecodable_env}

@item 
bpo-34347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34347}: Fix @code{test_utf8_mode.test_cmd_line} for AIX

@item 
bpo-34490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34490}: On AIX with AF_UNIX family sockets getsockname() does not
provide 'sockname', so skip calls to transport.get_extra_info('sockname')

@item 
bpo-34391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34391}: Fix ftplib test for TLS 1.3 by reading from data socket.

@item 
bpo-11192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11192}: Fix @code{test_socket} on AIX 6.1 and later IPv6 zone id supports
only supported by @code{inet_pton6_zone()}. Switch to runtime-based
@code{platform.system()} to establish current platform rather than build-time
based @code{sys.platform()}

@item 
bpo-34399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34399}: Update all RSA keys and DH params to use at least 2048 bits.

@item 
bpo-34373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34373}: Fix @code{test_mktime} and @code{test_pthread_getcpuclickid} tests
for AIX Add range checking for @code{_PyTime_localtime} for AIX Patch by
Michael Felt

@item 
bpo-11191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11191}: Skip the distutils test 'test_search_cpp' when using XLC as
compiler patch by aixtools (Michael Felt)

@item 
Improved an error message when mock assert_has_calls fails.

@item 
bpo-33746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33746}: Fix test_unittest when run in verbose mode.

@item 
bpo-33901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33901}: Fix test_dbm_gnu on macOS with gdbm 1.15: add a larger value to
make sure that the file size changes.

@item 
bpo-33873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33873}: Fix a bug in @code{regrtest} that caused an extra test to run if
--huntrleaks/-R was used. Exit with error in case that invalid parameters
are specified to --huntrleaks/-R (at least one warmup run and one
repetition must be used).

@item 
bpo-33562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33562}: Check that a global asyncio event loop policy is not left
behind by any tests.

@item 
bpo-33655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33655}: Ignore test_posix_fallocate failures on BSD platforms that
might be due to running on ZFS.

@item 
bpo-32962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32962}: Fixed test_gdb when Python is compiled with flags -mcet
-fcf-protection -O0.

@item 
bpo-33358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33358}: Fix @code{test_embed.test_pre_initialization_sys_options()} when
the interpreter is built with @code{--enable-shared}.

@item 
bpo-32872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32872}: Avoid regrtest compatibility issue with namespace packages.

@item 
bpo-32517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32517}: Fix failing @code{test_asyncio} on macOS 10.12.2+ due to transport
of @code{KqueueSelector} loop was not being closed.

@item 
bpo-32663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32663}: Making sure the @code{SMTPUTF8SimTests} class of tests gets run in
@code{test_smtplib.py}.

@item 
bpo-27643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27643}: Test_C test case needs "signed short" bitfields, but the IBM
XLC compiler (on AIX) does not support this Skip the code and test when
AIX and XLC are used

Applicable to Python2-2.7 and later

@item 
bpo-19417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19417}: Add test_bdb.py.

@item 
bpo-31809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31809}: Add tests to verify connection with secp ECDH curves.
@end itemize

@node ビルド<61>,Windows<55>,テスト<54>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id749}@anchor{1e2a}
@subsubsection ビルド



@itemize -

@item 
bpo-34691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34691}: The _contextvars module is now built into the core Python
library on Windows.

@item 
bpo-35683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35683}: Improved Azure Pipelines build steps and now verifying layouts
correctly

@item 
bpo-35642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35642}: Remove asynciomodule.c from pythoncore.vcxproj

@item 
bpo-35550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35550}: Fix incorrect Solaris #ifdef checks to look for __sun && __SVR4
instead of sun when compiling.

@item 
bpo-35499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35499}: @code{make profile-opt} no longer replaces @code{CFLAGS_NODIST} with
@code{CFLAGS}. It now adds profile-guided optimization (PGO) flags to
@code{CFLAGS_NODIST}: existing @code{CFLAGS_NODIST} flags are kept.

@item 
bpo-35257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35257}: Avoid leaking the linker flags from Link Time Optimizations
(LTO) into distutils when compiling C extensions.

@item 
bpo-35351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35351}: When building Python with clang and LTO, LTO flags are no
longer passed into CFLAGS to build third-party C extensions through
distutils.

@item 
bpo-35139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35139}: Fix a compiler error when statically linking @code{pyexpat} in
@code{Modules/Setup}.

@item 
bpo-35059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35059}: PCbuild: Set InlineFunctionExpansion to OnlyExplicitInline
("/Ob1" option) in pyproject.props in Debug mode to expand functions
marked as inline. This change should make Python compiled in Debug mode a
little bit faster on Windows.

@item 
bpo-35011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35011}: Restores the use of pyexpatns.h to isolate our embedded copy of
the expat C library so that its symbols do not conflict at link or dynamic
loading time with an embedding application or other extension modules with
their own version of libexpat.

@item 
bpo-28015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28015}: Have --with-lto works correctly with clang.

@item 
bpo-34765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34765}: Update the outdated install-sh file to the latest revision from
automake v1.16.1

@item 
bpo-34585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34585}: Check for floating-point byte order in configure.ac using
compilation tests instead of executing code, so that these checks work in
cross-compiled builds.

@item 
bpo-34710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34710}: Fixed SSL module build with OpenSSL & pedantic CFLAGS.

@item 
bpo-34582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34582}: Add JUnit XML output for regression tests and update Azure
DevOps builds.

@item 
bpo-34081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34081}: Make Sphinx warnings as errors in the Docs Makefile.

@item 
bpo-34555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34555}: Fix for case where it was not possible to have both
@code{HAVE_LINUX_VM_SOCKETS_H} and @code{HAVE_SOCKADDR_ALG} be undefined.

@item 
bpo-33015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33015}: Fix an undefined behaviour in the pthread implementation of
@ref{1e2b,,PyThread_start_new_thread()}: add a function wrapper to always
return @code{NULL}.

@item 
bpo-34245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34245}: The Python shared library is now installed with write
permission (mode 0755), which is the standard way of installing such
libraries.

@item 
bpo-34121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34121}: Fix detection of C11 atomic support on clang.

@item 
bpo-32430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32430}: Rename Modules/Setup.dist to Modules/Setup, and remove the
necessity to copy the former manually to the latter when updating the
local source tree.

@item 
bpo-30345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30345}: Add -g to LDFLAGS when compiling with LTO to get debug symbols.

@item 
bpo-5755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5755}: Move @code{-Wstrict-prototypes} option to @code{CFLAGS_NODIST} from
@code{OPT}. This option emitted annoying warnings when building extension
modules written in C++.

@item 
bpo-33614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33614}: Ensures module definition files for the stable ABI on Windows
are correctly regenerated.

@item 
bpo-33648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33648}: The --with-c-locale-warning configuration flag has been
removed. It has had no effect for about a year.

@item 
bpo-33522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33522}: Enable CI builds on Visual Studio Team Services at
@indicateurl{https://python.visualstudio.com/cpython}

@item 
bpo-33512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33512}: configure's check for "long double" has been simplified

@item 
bpo-33483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33483}: C compiler is now correctly detected from the standard
environment variables. --without-gcc and --with-icc options have been
removed.

@item 
bpo-33394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33394}: Enable the verbose build for extension modules, when GNU make
is passed macros on the command line.

@item 
bpo-33393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33393}: Update config.guess and config.sub files.

@item 
bpo-33377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33377}: Add new triplets for mips r6 and riscv variants (used in
extension suffixes).

@item 
bpo-32232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32232}: By default, modules configured in @code{Modules/Setup} are no
longer built with @code{-DPy_BUILD_CORE}. Instead, modules that specifically
need that preprocessor definition include it in their individual entries.

@item 
bpo-33182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33182}: The embedding tests can once again be built with clang 6.0

@item 
bpo-33163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33163}: Upgrade pip to 9.0.3 and setuptools to v39.0.1.

@item 
bpo-33012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33012}: gcc 8 has added a new warning heuristic to detect invalid
function casts and a stock python build seems to hit that warning quite
often.  The most common is the cast of a METH_NOARGS function (that uses
just one argument) to a PyCFunction. Fix this by adding a dummy argument
to all functions that implement METH_NOARGS.

@item 
bpo-32898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32898}: Fix the python debug build when using COUNT_ALLOCS.

@item 
bpo-29442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29442}: Replace optparse with argparse in setup.py
@end itemize

@node Windows<55>,macOS<42>,ビルド<61>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id750}@anchor{1e2c}
@subsubsection Windows



@itemize -

@item 
bpo-35890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35890}: Fix API calling consistency of GetVersionEx and wcstok.

@item 
bpo-32560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32560}: The @code{py} launcher now forwards its @code{STARTUPINFO} structure
to child processes.

@item 
bpo-35854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35854}: Fix EnvBuilder and --symlinks in venv on Windows

@item 
bpo-35811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35811}: Avoid propagating venv settings when launching via py.exe

@item 
bpo-35797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35797}: Fix default executable used by the multiprocessing module

@item 
bpo-35758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35758}: Allow building on ARM with MSVC.

@item 
bpo-29734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29734}: Fix handle leaks in os.stat on Windows.

@item 
bpo-35596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35596}: Use unchecked PYCs for the embeddable distro to avoid zipimport
restrictions.

@item 
bpo-35596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35596}: Fix vcruntime140.dll being added to embeddable distro multiple
times.

@item 
bpo-35402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35402}: Update Windows build to use Tcl and Tk 8.6.9

@item 
bpo-35401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35401}: Updates Windows build to OpenSSL 1.1.0j

@item 
bpo-34977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34977}: venv on Windows will now use a python.exe redirector rather
than copying the actual binaries from the base environment.

@item 
bpo-34977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34977}: Adds support for building a Windows App Store package

@item 
bpo-35067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35067}: Remove _distutils_findvs module and use vswhere.exe instead.

@item 
bpo-32557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32557}: Allow shutil.disk_usage to take a file path on Windows

@item 
bpo-34770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34770}: Fix a possible null pointer dereference in pyshellext.cpp.

@item 
bpo-34603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34603}: Fix returning structs from functions produced by MSVC

@item 
bpo-34581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34581}: Guard MSVC-specific code in socketmodule.c with @code{#ifdef
_MSC_VER}.

@item 
bpo-34532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34532}: Fixes exit code of list version arguments for py.exe.

@item 
bpo-34062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34062}: Fixed the '--list' and '--list-paths' arguments for the py.exe
launcher

@item 
bpo-34225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34225}: Ensure INCLUDE and LIB directories do not end with a backslash.

@item 
bpo-34011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34011}: A suite of code has been changed which copied across DLLs and
init.tcl from the running Python location into a venv being created. These
copies are needed only when running from a Python source build, and the
copying code is now only run when that is the case, rather than whenever a
venv is created.

@item 
bpo-34006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34006}: Revert line length limit for Windows help docs. The line-length
limit is not needed because the pages appear in a separate app rather than
on a browser tab.  It can also interact badly with the DPI setting.

@item 
bpo-31546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31546}: Restore running PyOS_InputHook while waiting for user input at
the prompt. The restores integration of interactive GUI windows (such as
Matplotlib figures) with the prompt on Windows.

@item 
bpo-30237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30237}: Output error when ReadConsole is canceled by
CancelSynchronousIo instead of crashing.

@item 
bpo-33895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33895}: GIL is released while calling functions that acquire Windows
loader lock.

@item 
bpo-33720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33720}: Reduces maximum marshal recursion depth on release builds.

@item 
bpo-29097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29097}: Fix bug where @code{datetime.fromtimestamp()} erroneously throws
an @ref{2c0,,OSError} on Windows for values between 0 and 86400. Patch by
Ammar Askar.

@item 
bpo-33316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33316}: PyThread_release_lock always fails

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update Windows installer to use OpenSSL 1.1.0h.

@item 
bpo-32890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32890}: Fix usage of GetLastError() instead of errno in os.execve() and
os.truncate().

@item 
bpo-33016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33016}: Fix potential use of uninitialized memory in
nt._getfinalpathname

@item 
bpo-32903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32903}: Fix a memory leak in os.chdir() on Windows if the current
directory is set to a UNC path.

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update Tcl and Tk versions to 8.6.8

@item 
bpo-31966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31966}: Fixed WindowsConsoleIO.write() for writing empty data.

@item 
bpo-32409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32409}: Ensures activate.bat can handle Unicode contents.

@item 
bpo-32457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32457}: Improves handling of denormalized executable path when
launching Python.

@item 
bpo-32370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32370}: Use the correct encoding for ipconfig output in the uuid
module. Patch by Segev Finer.

@item 
bpo-29248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29248}: Fix @ref{b1a,,os.readlink()} on Windows, which was mistakenly
treating the @code{PrintNameOffset} field of the reparse data buffer as a
number of characters instead of bytes. Patch by Craig Holmquist and SSE4.

@item 
bpo-1104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1104}: Correctly handle string length in
@code{msilib.SummaryInfo.GetProperty()} to prevent it from truncating the
last character.
@end itemize

@node macOS<42>,IDLE<37>,Windows<55>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id751}@anchor{1e2d}
@subsubsection macOS



@itemize -

@item 
bpo-35401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35401}: Update macOS installer to use OpenSSL 1.1.0j.

@item 
bpo-35025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35025}: Properly guard the use of the @code{CLOCK_GETTIME} et al. macros
in @code{timemodule} on macOS.

@item 
bpo-24658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24658}: On macOS, fix reading from and writing into a file with a size
larger than 2 GiB.

@item 
bpo-34405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34405}: Update to OpenSSL 1.1.0i for macOS installer builds.

@item 
bpo-33635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33635}: In macOS stat on some file descriptors (/dev/fd/3 f.e) will
result in bad file descriptor OSError. Guard against this exception was
added in is_dir, is_file and similar methods. DirEntry.is_dir can also
throw this exception so _RecursiveWildcardSelector._iterate_directories
was also extended with the same error ignoring pattern.

@item 
bpo-13631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13631}: The .editrc file in user's home directory is now processed
correctly during the readline initialization through editline emulation on
macOS.

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update macOS installer build to use OpenSSL 1.1.0h.

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Build and link with private copy of Tcl/Tk 8.6 for the macOS
10.6+ installer. The 10.9+ installer variant already does this.  This
means that the Python 3.7 provided by the python.org macOS installers no
longer need or use any external versions of Tcl/Tk, either system-provided
or user-installed, such as ActiveTcl.

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update macOS 10.9+ installer to Tcl/Tk 8.6.8.

@item 
bpo-31903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31903}: In @code{_scproxy}, drop the GIL when calling into
@code{SystemConfiguration} to avoid deadlocks.
@end itemize

@node IDLE<37>,Tools/Demos<37>,macOS<42>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id752}@anchor{1e2e}
@subsubsection IDLE



@itemize -

@item 
bpo-35770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35770}: IDLE macosx deletes Options => Configure IDLE. It previously
deleted Window => Zoom Height by mistake. (Zoom Height is now on the
Options menu).  On Mac, the settings dialog is accessed via Preferences on
the IDLE menu.

@item 
bpo-35769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35769}: Change IDLE's new file name from 'Untitled' to 'untitled'

@item 
bpo-35660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35660}: Fix imports in idlelib.window.

@item 
bpo-35641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35641}: Proper format @code{calltip} when the function has no docstring.

@item 
bpo-33987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33987}: Use ttk Frame for ttk widgets.

@item 
bpo-34055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34055}: Fix erroneous 'smart' indents and newlines in IDLE Shell.

@item 
bpo-35591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35591}: Find Selection now works when selection not found.

@item 
bpo-35196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35196}: Speed up squeezer line counting.

@item 
bpo-35598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35598}: Update config_key: use PEP 8 names and ttk widgets, make some
objects global, and add tests.

@item 
bpo-28097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28097}: Add Previous/Next History entries to Shell menu.

@item 
bpo-35208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35208}: Squeezer now properly counts wrapped lines before newlines.

@item 
bpo-35555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35555}: Gray out Code Context menu entry when it's not applicable.

@item 
bpo-35521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35521}: Document the IDLE editor code context feature. Add some
internal references within the IDLE doc.

@item 
bpo-22703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22703}: The Code Context menu label now toggles between Show/Hide Code
Context. The Zoom Height menu now toggles between Zoom/Restore Height.
Zoom Height has moved from the Window menu to the Options menu.

@item 
bpo-35213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35213}: Where appropriate, use 'macOS' in idlelib.

@item 
bpo-34864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34864}: On macOS, warn if the system preference "Prefer tabs when
opening documents" is set to "Always".

@item 
bpo-34864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34864}: Document two IDLE on MacOS issues. The System Preferences Dock
"prefer tabs always" setting disables some IDLE features.  Menus are a bit
different than as described for Windows and Linux.

@item 
bpo-35202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35202}: Remove unused imports from lib/idlelib

@item 
bpo-33000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33000}: Document that IDLE's shell has no line limit. A program that
runs indefinitely can overfill memory.

@item 
bpo-23220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23220}: Explain how IDLE's Shell displays output.

@item 
bpo-35099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35099}: Improve the doc about IDLE running user code.   The section is
renamed from "IDLE -- console differences" is renamed "Running user code".
It mostly covers the implications of using custom @code{sys.std@var{xxx}}
objects.

@item 
bpo-35097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35097}: Add IDLE doc subsection explaining editor windows. Topics
include opening, title and status bar, .py* extension, and running.

@item 
bpo-35093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35093}: Document the IDLE document viewer in the IDLE doc. Add a
paragraph in "Help and preferences", "Help sources" subsection.

@item 
bpo-35088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35088}: Update idlelib.help.copy_string docstring. We now use git and
backporting instead of hg and forward merging.

@item 
bpo-35087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35087}: Update idlelib help files for the current doc build. The main
change is the elimination of chapter-section numbers.

@item 
bpo-34548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34548}: Use configured color theme for read-only text views.

@item 
bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353}: Enable "squeezing" of long outputs in the shell, to avoid
performance degradation and to clean up the history without losing it.
Squeezed outputs may be copied, viewed in a separate window, and
"unsqueezed".

@item 
bpo-34047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34047}: Fixed mousewheel scrolling direction on macOS.

@item 
bpo-34275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34275}: Make IDLE calltips always visible on Mac. Some MacOS-tk
combinations need .update_idletasks(). Patch by Kevin Walzer.

@item 
bpo-34120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34120}: Fix unresponsiveness after closing certain windows and dialogs.

@item 
bpo-33975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33975}: Avoid small type when running htests. Since part of the purpose
of human-viewed tests is to determine that widgets look right, it is
important that they look the same for testing as when running IDLE.

@item 
bpo-33905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33905}: Add test for idlelib.stackview.StackBrowser.

@item 
bpo-33924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33924}: Change mainmenu.menudefs key 'windows' to 'window'. Every other
menudef key is lowercase version of main menu entry.

@item 
bpo-33906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33906}: Rename idlelib.windows as window Match Window on the main menu
and remove last plural module name.

@item 
bpo-33917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33917}: Fix and document idlelib/idle_test/template.py. The revised
file compiles, runs, and tests OK.  idle_test/README.txt explains how to
use it to create new IDLE test files.

@item 
bpo-33904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33904}: IDLE: In rstrip, rename class RstripExtension as Rstrip

@item 
bpo-33907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33907}: For consistency and clarity, rename an IDLE module and classes.
Module calltips and its class CallTips are now calltip and Calltip. In
module calltip_w, class CallTip is now CalltipWindow.

@item 
bpo-33856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33856}: Add "help" in the welcome message of IDLE

@item 
bpo-33839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33839}: IDLE: refactor ToolTip and CallTip and add documentation and
tests

@item 
bpo-33855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33855}: Minimally test all IDLE modules. Add missing files, import
module, instantiate classes, and check coverage. Check existing files.

@item 
bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}: On Windows, add API call saying that tk scales for DPI. On
Windows 8.1+ or 10, with DPI compatibility properties of the Python binary
unchanged, and a monitor resolution greater than 96 DPI, this should make
text and lines sharper.  It should otherwise have no effect.

@item 
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}: Clicking on a context line moves that line to the top of the
editor window.

@item 
bpo-33763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33763}: IDLE: Use read-only text widget for code context instead of
label widget.

@item 
bpo-33664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33664}: Scroll IDLE editor text by lines. Previously, the mouse wheel
and scrollbar slider moved text by a fixed number of pixels, resulting in
partial lines at the top of the editor box.  The change also applies to
the shell and grep output windows, but not to read-only text views.

@item 
bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}: Enable theme-specific color configuration for Code Context. Use
the Highlights tab to see the setting for built-in themes or add settings
to custom themes.

@item 
bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}: Display up to maxlines non-blank lines for Code Context. If
there is no current context, show a single blank line.

@item 
bpo-33628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33628}: IDLE: Cleanup codecontext.py and its test.

@item 
bpo-33564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33564}: IDLE's code context now recognizes async as a block opener.

@item 
bpo-21474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21474}: Update word/identifier definition from ascii to unicode. In
text and entry boxes, this affects selection by double-click, movement
left/right by control-left/right, and deletion left/right by
control-BACKSPACE/DEL.

@item 
bpo-33204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33204}: IDLE: consistently color invalid string prefixes. A 'u' string
prefix cannot be paired with either 'r' or 'f'. Consistently color as much
of the prefix, starting at the right, as is valid. Revise and extend
colorizer test.

@item 
bpo-32984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32984}: Set @code{__file__} while running a startup file.  Like Python,
IDLE optionally runs one startup file in the Shell window before
presenting the first interactive input prompt.  For IDLE, @code{-s} runs a
file named in environmental variable  
@geindex IDLESTARTUP
@geindex 環境変数; IDLESTARTUP
@code{IDLESTARTUP} or
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP}; @code{-r file} runs @code{file}.  Python sets
@code{__file__} to the startup file name before running the file and unsets
it before the first prompt.  IDLE now does the same when run normally,
without the @code{-n} option.

@item 
bpo-32940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32940}: Simplify and rename StringTranslatePseudoMapping in pyparse.

@item 
bpo-32916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32916}: Change @code{str} to @code{code} in pyparse.

@item 
bpo-32905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32905}: Remove unused code in pyparse module.

@item 
bpo-32874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32874}: Add tests for pyparse.

@item 
bpo-32837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32837}: Using the system and place-dependent default encoding for
open() is a bad idea for IDLE's system and location-independent files.

@item 
bpo-32826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32826}: Add "encoding=utf-8" to open() in IDLE's test_help_about. GUI
test test_file_buttons() only looks at initial ascii-only lines, but
failed on systems where open() defaults to 'ascii' because readline()
internally reads and decodes far enough ahead to encounter a non-ascii
character in CREDITS.txt.

@item 
bpo-32831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32831}: Add docstrings and tests for codecontext.

@item 
bpo-32765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32765}: Update configdialog General tab docstring to add new widgets to
the widget list.
@end itemize

@node Tools/Demos<37>,C API<56>,IDLE<37>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id753}@anchor{1e2f}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-35884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35884}: Add a benchmark script for timing various ways to access
variables: @code{Tools/scripts/var_access_benchmark.py}.

@item 
bpo-34989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34989}: python-gdb.py now handles errors on computing the line number
of a Python frame.

@item 
bpo-20260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20260}: Argument Clinic now has non-bitwise unsigned int converters.

@item 
bpo-32962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32962}: python-gdb now catches @code{UnicodeDecodeError} exceptions when
calling @code{string()}.

@item 
bpo-32962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32962}: python-gdb now catches ValueError on read_var(): when Python
has no debug symbols for example.

@item 
bpo-33189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33189}: @code{pygettext.py} now recognizes only literal strings as
docstrings and translatable strings, and rejects bytes literals and
f-string expressions.

@item 
bpo-31920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31920}: Fixed handling directories as arguments in the @code{pygettext}
script. Based on patch by Oleg Krasnikov.

@item 
bpo-29673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29673}: Fix pystackv and pystack gdbinit macros.

@item 
bpo-25427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25427}: Remove the pyvenv script in favor of @code{python3 -m venv} in
order to lower confusion as to what Python interpreter a virtual
environment will be created for.

@item 
bpo-32885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32885}: Add an @code{-n} flag for @code{Tools/scripts/pathfix.py} to disable
automatic backup creation (files with @code{~} suffix).

@item 
bpo-32222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32222}: Fix pygettext not extracting docstrings for functions with type
annotated arguments. Patch by Toby Harradine.

@item 
bpo-31583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31583}: Fix 2to3 for using with --add-suffix option but without
--output-dir option for relative path to files in current directory.
@end itemize

@node C API<56>,,Tools/Demos<37>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id754}@anchor{1e30}
@subsubsection C API



@itemize -

@item 
bpo-35713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35713}: The @code{PyByteArray_Init()} and @code{PyByteArray_Fini()}
functions have been removed. They did nothing since Python 2.7.4 and
Python 3.2.0, were excluded from the limited API (stable ABI), and were
not documented.

@item 
bpo-33817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33817}: Fixed @ref{19ce,,_PyBytes_Resize()} for empty bytes objects.

@item 
bpo-35322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35322}: Fix memory leak in @ref{dc3,,PyUnicode_EncodeLocale()} and
@ref{1e31,,PyUnicode_EncodeFSDefault()} on error handling.

@item 
bpo-35059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35059}: The following C macros have been converted to static inline
functions: @ref{78f,,Py_INCREF()}, @ref{790,,Py_DECREF()}, @ref{c5a,,Py_XINCREF()},
@ref{992,,Py_XDECREF()}, @ref{1d3e,,PyObject_INIT()},
@ref{1d3f,,PyObject_INIT_VAR()}.

@item 
bpo-35296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35296}: @code{make install} now also installs the internal API:
@code{Include/internal/*.h} header files.

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: Internal APIs surrounded by @code{#ifdef Py_BUILD_CORE} have been
moved from @code{Include/*.h} headers to new header files
@code{Include/internal/pycore_*.h}.

@item 
bpo-35259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35259}: Conditionally declare @ref{f11,,Py_FinalizeEx()} (new in 3.6)
based on Py_LIMITED_API. Patch by Arthur Neufeld.

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: The @code{_PyObject_GC_TRACK()} and
@code{_PyObject_GC_UNTRACK()} macros have been removed from the public C
API.

@item 
bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}: Creation of a new @code{Include/cpython/} subdirectory.

@item 
bpo-34725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34725}: Adds _Py_SetProgramFullPath so embedders may override
sys.executable

@item 
bpo-34910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34910}: Ensure that @ref{198b,,PyObject_Print()} always returns @code{-1} on
error.  Patch by Zackery Spytz.

@item 
bpo-34523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34523}: Py_DecodeLocale() and Py_EncodeLocale() now use the UTF-8
encoding on Windows if Py_LegacyWindowsFSEncodingFlag is zero.

@item 
bpo-34193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34193}: Fix pluralization in TypeError messages in getargs.c and
typeobject.c: '1 argument' instead of '1 arguments' and '1 element'
instead of '1 elements'.

@item 
bpo-34127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34127}: Return grammatically correct error message based on argument
count. Patch by Karthikeyan Singaravelan.

@item 
bpo-23927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23927}: Fixed @ref{795,,SystemError} in
@ref{624,,PyArg_ParseTupleAndKeywords()} when the @code{w*} format unit is used
for optional parameter.

@item 
bpo-32455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32455}: Added @ref{1e32,,PyCompile_OpcodeStackEffectWithJump()}.

@item 
bpo-34008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34008}: Py_Main() can again be called after Py_Initialize(), as in
Python 3.6.

@item 
bpo-32500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32500}: Fixed error messages for @ref{1e33,,PySequence_Size()},
@ref{1e34,,PySequence_GetItem()}, @ref{1e35,,PySequence_SetItem()} and
@ref{1e36,,PySequence_DelItem()} called with a mapping and
@ref{1e37,,PyMapping_Size()} called with a sequence.

@item 
bpo-33818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33818}: @ref{c5b,,PyExceptionClass_Name()} will now return @code{const char
*} instead of @code{char *}.

@item 
bpo-33042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33042}: Embedding applications may once again call
PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption prior to
calling Py_Initialize.

@item 
bpo-32374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32374}: Document that m_traverse for multi-phase initialized modules
can be called with m_state=NULL, and add a sanity check

@item 
bpo-30863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30863}: @ref{1e38,,PyUnicode_AsWideChar()} and
@ref{ab9,,PyUnicode_AsWideCharString()} no longer cache the @code{wchar_t*}
representation of string objects.
@end itemize

@node Python 3 7 0 final,Python 3 7 0 release candidate 1,Python 3 8 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-7-0-final}@anchor{1e39}
@subsection Python 3.7.0 final


`Release date: 2018-06-27'

@menu
* ライブラリ: ライブラリ<163>. 
* C API: C API<57>. 

@end menu

@node ライブラリ<163>,C API<57>,,Python 3 7 0 final
@anchor{whatsnew/changelog id755}@anchor{1e3a}
@subsubsection ライブラリ



@itemize -

@item 
bpo-33851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33851}: Fix @ref{1e3b,,ast.get_docstring()} for a node that lacks a
docstring.
@end itemize

@node C API<57>,,ライブラリ<163>,Python 3 7 0 final
@anchor{whatsnew/changelog id756}@anchor{1e3c}
@subsubsection C API



@itemize -

@item 
bpo-33932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33932}: Calling Py_Initialize() twice does nothing, instead of failing
with a fatal error: restore the Python 3.6 behaviour.
@end itemize

@node Python 3 7 0 release candidate 1,Python 3 7 0 beta 5,Python 3 7 0 final,変更履歴
@anchor{whatsnew/changelog python-3-7-0-release-candidate-1}@anchor{1e3d}
@subsection Python 3.7.0 release candidate 1


`Release date: 2018-06-12'

@menu
* Core and Builtins: Core and Builtins<160>. 
* ライブラリ: ライブラリ<164>. 
* ドキュメント: ドキュメント<57>. 
* ビルド: ビルド<62>. 
* Windows: Windows<56>. 
* IDLE: IDLE<38>. 

@end menu

@node Core and Builtins<160>,ライブラリ<164>,,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id757}@anchor{1e3e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33803}: Fix a crash in hamt.c caused by enabling GC tracking for an
object that hadn't all of its fields set to NULL.

@item 
bpo-33706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33706}: Fix a crash in Python initialization when parsing the command
line options. Thanks Christoph Gohlke for the bug report and the fix!

@item 
bpo-30654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30654}: Fixed reset of the SIGINT handler to SIG_DFL on interpreter
shutdown even when there was a custom handler set previously. Patch by
Philipp Kerling.

@item 
bpo-31849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31849}: Fix signed/unsigned comparison warning in pyhash.c.
@end itemize

@node ライブラリ<164>,ドキュメント<57>,Core and Builtins<160>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id758}@anchor{1e3f}
@subsubsection ライブラリ



@itemize -

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by
Steve Weber.

@item 
bpo-33812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33812}: Datetime instance d with non-None tzinfo, but with
d.tzinfo.utcoffset(d) returning None is now treated as naive by the
astimezone() method.

@item 
bpo-30805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30805}: Avoid race condition with debug logging

@item 
bpo-33694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33694}: asyncio: Fix a race condition causing data loss on
pause_reading()/resume_reading() when using the ProactorEventLoop.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Correct test for @code{uuid_enc_be} availability in
@code{configure.ac}. Patch by Michael Felt.

@item 
bpo-33792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33792}: Add asyncio.WindowsSelectorEventLoopPolicy and
asyncio.WindowsProactorEventLoopPolicy.

@item 
bpo-33778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33778}: Update @code{unicodedata}'s database to Unicode version 11.0.0.

@item 
bpo-33770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33770}: improve base64 exception message for encoded inputs of invalid
length

@item 
bpo-33769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33769}: asyncio/start_tls: Fix error message; cancel callbacks in case
of an unhandled error; mark SSLTransport as closed if it is aborted.

@item 
bpo-33767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33767}: The concatenation (@code{+}) and repetition (@code{*}) sequence
operations now raise @ref{198,,TypeError} instead of @ref{795,,SystemError} when
performed on @ref{519,,mmap.mmap} objects.  Patch by Zackery Spytz.

@item 
bpo-33734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33734}: asyncio/ssl: Fix AttributeError, increase default handshake
timeout

@item 
bpo-11874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11874}: Use a better regex when breaking usage into wrappable parts.
Avoids bogus assertion errors from custom metavar strings.

@item 
bpo-33582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33582}: Emit a deprecation warning for inspect.formatargspec
@end itemize

@node ドキュメント<57>,ビルド<62>,ライブラリ<164>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id759}@anchor{1e40}
@subsubsection ドキュメント



@itemize -

@item 
bpo-33409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33409}: Clarified the relationship between 
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/}'s
PYTHONCOERCECLOCALE and PEP 540's PYTHONUTF8 mode.

@item 
bpo-33736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33736}: Improve the documentation of @ref{d0e,,asyncio.open_connection()},
@ref{d0f,,asyncio.start_server()} and their UNIX socket counterparts.

@item 
bpo-31432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31432}: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED
flags for ssl.SSLContext.verify_mode.
@end itemize

@node ビルド<62>,Windows<56>,ドキュメント<57>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id760}@anchor{1e41}
@subsubsection ビルド



@itemize -

@item 
bpo-5755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5755}: Move @code{-Wstrict-prototypes} option to @code{CFLAGS_NODIST} from
@code{OPT}. This option emitted annoying warnings when building extension
modules written in C++.
@end itemize

@node Windows<56>,IDLE<38>,ビルド<62>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id761}@anchor{1e42}
@subsubsection Windows



@itemize -

@item 
bpo-33720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33720}: Reduces maximum marshal recursion depth on release builds.
@end itemize

@node IDLE<38>,,Windows<56>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id762}@anchor{1e43}
@subsubsection IDLE



@itemize -

@item 
bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}: On Windows, add API call saying that tk scales for DPI. On
Windows 8.1+ or 10, with DPI compatibility properties of the Python binary
unchanged, and a monitor resolution greater than 96 DPI, this should make
text and lines sharper.  It should otherwise have no effect.

@item 
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}: Clicking on a context line moves that line to the top of the
editor window.

@item 
bpo-33763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33763}: IDLE: Use read-only text widget for code context instead of
label widget.

@item 
bpo-33664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33664}: Scroll IDLE editor text by lines. Previously, the mouse wheel
and scrollbar slider moved text by a fixed number of pixels, resulting in
partial lines at the top of the editor box.  The change also applies to
the shell and grep output windows, but not to read-only text views.

@item 
bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}: Enable theme-specific color configuration for Code Context. Use
the Highlights tab to see the setting for built-in themes or add settings
to custom themes.

@item 
bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}: Display up to maxlines non-blank lines for Code Context. If
there is no current context, show a single blank line.
@end itemize

@node Python 3 7 0 beta 5,Python 3 7 0 beta 4,Python 3 7 0 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-7-0-beta-5}@anchor{1e44}
@subsection Python 3.7.0 beta 5


`Release date: 2018-05-30'

@menu
* Core and Builtins: Core and Builtins<161>. 
* ライブラリ: ライブラリ<165>. 
* ドキュメント: ドキュメント<58>. 
* テスト: テスト<55>. 
* ビルド: ビルド<63>. 
* macOS: macOS<43>. 
* IDLE: IDLE<39>. 

@end menu

@node Core and Builtins<161>,ライブラリ<165>,,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id763}@anchor{1e45}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33622}: Fixed a leak when the garbage collector fails to add an object
with the @code{__del__} method or referenced by it into the
@ref{13d9,,gc.garbage} list. @ref{b85,,PyGC_Collect()} can now be called when an
exception is set and preserves it.

@item 
bpo-33509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33509}: Fix module_globals parameter of warnings.warn_explicit(): don't
crash if module_globals is not a dict.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: The new @code{os.posix_spawn} added in 3.7.0b1 was removed as we
are still working on what the API should look like.  Expect this in 3.8
instead.

@item 
bpo-33475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33475}: Fixed miscellaneous bugs in converting annotations to strings
and optimized parentheses in the string representation.

@item 
bpo-33391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33391}: Fix a leak in set_symmetric_difference().

@item 
bpo-28055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28055}: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

@item 
bpo-32911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32911}: Due to unexpected compatibility issues discovered during
downstream beta testing, reverted bpo-29463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29463}. @code{docstring} field is
removed from Module, ClassDef, FunctionDef, and AsyncFunctionDef ast nodes
which was added in 3.7a1.  Docstring expression is restored as a first
statement in their body. Based on patch by Inada Naoki.

@item 
bpo-21983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21983}: Fix a crash in @code{ctypes.cast()} in case the type argument is a
ctypes structured data type. Patch by Eryk Sun and Oren Milman.
@end itemize

@node ライブラリ<165>,ドキュメント<58>,Core and Builtins<161>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id764}@anchor{1e46}
@subsubsection ライブラリ



@itemize -

@item 
bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}: When cancelling the task due to a timeout,
@ref{815,,asyncio.wait_for()} will now wait until the cancellation is complete.

@item 
bpo-32684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32684}: Fix gather to propagate cancellation of itself even with
return_exceptions.

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Support protocol type switching in SSLTransport.set_protocol().

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Pause the transport as early as possible to further reduce the
risk of data_received() being called before connection_made().

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Fix a race condition in SSLProtocol.connection_made() of
asyncio.sslproto: start immediately the handshake instead of using
call_soon(). Previously, data_received() could be called before the
handshake started, causing the handshake to hang or fail.

@item 
bpo-31647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31647}: Fixed bug where calling write_eof() on a
_SelectorSocketTransport after it's already closed raises AttributeError.

@item 
bpo-32610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32610}: Make asyncio.all_tasks() return only pending tasks.

@item 
bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410}: Avoid blocking on file IO in sendfile fallback code

@item 
bpo-33469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33469}: Fix RuntimeError after closing loop that used run_in_executor

@item 
bpo-33672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33672}: Fix Task.__repr__ crash with Cython's bogus coroutines

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Fix transport.set_protocol() to support switching between
asyncio.Protocol and asyncio.BufferedProtocol.  Fix loop.start_tls() to
work with asyncio.BufferedProtocols.

@item 
bpo-33652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33652}: Pickles of type variables and subscripted generics are now
future-proof and compatible with older Python versions.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Fixed @ref{da1,,uuid.uuid1()} on FreeBSD.

@item 
bpo-33618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33618}: Finalize and document preliminary and experimental TLS 1.3
support with OpenSSL 1.1.1

@item 
bpo-33623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33623}: Fix possible SIGSGV when asyncio.Future is created in __del__

@item 
bpo-30877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30877}: Fixed a bug in the Python implementation of the JSON decoder
that prevented the cache of parsed strings from clearing after finishing
the decoding. Based on patch by c-fos.

@item 
bpo-33570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33570}: Change TLS 1.3 cipher suite settings for compatibility with
OpenSSL 1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 ciphers
enabled by default.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Do not simplify arguments to @code{typing.Union}. Now
@code{Union[Manager, Employee]} is not simplified to @code{Employee} at runtime.
Such simplification previously caused several bugs and limited
possibilities for introspection.

@item 
bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540}: Add a new @code{block_on_close} class attribute to
@code{ForkingMixIn} and @code{ThreadingMixIn} classes of @ref{d2,,socketserver}.

@item 
bpo-33548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33548}: tempfile._candidate_tempdir_list should consider common TEMP
locations

@item 
bpo-33109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33109}: argparse subparsers are once again not required by default,
reverting the change in behavior introduced by bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510} in 3.7.0a2.

@item 
bpo-33536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33536}: dataclasses.make_dataclass now checks for invalid field names
and duplicate fields. Also, added a check for invalid field
specifications.

@item 
bpo-33542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33542}: Prevent @code{uuid.get_node} from using a DUID instead of a MAC on
Windows. Patch by Zvi Effron

@item 
bpo-26819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26819}: Fix race condition with @code{ReadTransport.resume_reading} in
Windows proactor event loop.

@item 
Fix failure in @code{typing.get_type_hints()} when ClassVar was provided as a
string forward reference.

@item 
bpo-33505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33505}: Optimize asyncio.ensure_future() by reordering if checks: 1.17x
faster.

@item 
bpo-33497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33497}: Add errors param to cgi.parse_multipart and make an encoding in
FieldStorage use the given errors (needed for Twisted).  Patch by Amber
Brown.

@item 
bpo-33495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33495}: Change dataclasses.Fields repr to use the repr of each of its
members, instead of str.  This makes it more clear what each field
actually represents.  This is especially true for the 'type' member.

@item 
bpo-33453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33453}: Fix dataclasses to work if using literal string type
annotations or if using PEP 563 "Postponed Evaluation of Annotations".
Only specific string prefixes are detected for both ClassVar ("ClassVar"
and "typing.ClassVar") and InitVar ("InitVar" and "dataclasses.InitVar").

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Minor fixes in typing module: add annotations to
@code{NamedTuple.__new__}, pass @code{*args} and @code{**kwds} in
@code{Generic.__new__}.  Original PRs by Paulius Šarka and Chad Dombrova.

@item 
bpo-20087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20087}: Updated alias mapping with glibc 2.27 supported locales.

@item 
bpo-33422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33422}: Fix trailing quotation marks getting deleted when looking up
byte/string literals on pydoc. Patch by Andrés Delfino.

@item 
bpo-28167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28167}: The function @code{platform.linux_distribution} and
@code{platform.dist} now trigger a @code{DeprecationWarning} and have been
marked for removal in Python 3.8

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Update error message when constructing invalid
inspect.Parameters Patch by Donghee Na.

@item 
bpo-33263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33263}: Fix FD leak in @code{_SelectorSocketTransport}  Patch by Vlad
Starostin.

@item 
bpo-32861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32861}: The urllib.robotparser's @code{__str__} representation now
includes wildcard entries and the "Crawl-delay" and "Request-rate" fields.
Patch by Michael Lazar.

@item 
bpo-32257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32257}: The ssl module now contains OP_NO_RENEGOTIATION constant,
available with OpenSSL 1.1.0h or 1.1.1.

@item 
bpo-16865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16865}: Support arrays >=2GiB in @ref{2e,,ctypes}.  Patch by Segev Finer.
@end itemize

@node ドキュメント<58>,テスト<55>,ライブラリ<165>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id765}@anchor{1e47}
@subsubsection ドキュメント



@itemize -

@item 
bpo-23859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23859}: Document that @code{asyncio.wait()} does not cancel its futures on
timeout.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Document 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} changes to asyncio.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Update HMAC md5 default to a DeprecationWarning, bump removal
to 3.8.

@item 
bpo-33503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33503}: Fix broken pypi link

@item 
bpo-33421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33421}: Add missing documentation for @code{typing.AsyncContextManager}.
@end itemize

@node テスト<55>,ビルド<63>,ドキュメント<58>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id766}@anchor{1e48}
@subsubsection テスト



@itemize -

@item 
bpo-33655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33655}: Ignore test_posix_fallocate failures on BSD platforms that
might be due to running on ZFS.

@item 
bpo-32604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32604}: Remove the _xxsubinterpreters module (meant for testing) and
associated helpers.  This module was originally added recently in 3.7b1.
@end itemize

@node ビルド<63>,macOS<43>,テスト<55>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id767}@anchor{1e49}
@subsubsection ビルド



@itemize -

@item 
bpo-33614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33614}: Ensures module definition files for the stable ABI on Windows
are correctly regenerated.

@item 
bpo-33522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33522}: Enable CI builds on Visual Studio Team Services at
@indicateurl{https://python.visualstudio.com/cpython}

@item 
bpo-33012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33012}: Add @code{-Wno-cast-function-type} for gcc 8 for silencing
warnings about function casts like casting to PyCFunction in method
definition lists.
@end itemize

@node macOS<43>,IDLE<39>,ビルド<63>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id768}@anchor{1e4a}
@subsubsection macOS



@itemize -

@item 
bpo-13631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13631}: The .editrc file in user's home directory is now processed
correctly during the readline initialization through editline emulation on
macOS.
@end itemize

@node IDLE<39>,,macOS<43>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id769}@anchor{1e4b}
@subsubsection IDLE



@itemize -

@item 
bpo-33628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33628}: IDLE: Cleanup codecontext.py and its test.

@item 
bpo-33564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33564}: IDLE's code context now recognizes async as a block opener.

@item 
bpo-32831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32831}: Add docstrings and tests for codecontext.
@end itemize

@node Python 3 7 0 beta 4,Python 3 7 0 beta 3,Python 3 7 0 beta 5,変更履歴
@anchor{whatsnew/changelog python-3-7-0-beta-4}@anchor{1e4c}
@subsection Python 3.7.0 beta 4


`Release date: 2018-05-02'

@menu
* Core and Builtins: Core and Builtins<162>. 
* ライブラリ: ライブラリ<166>. 
* ドキュメント: ドキュメント<59>. 
* テスト: テスト<56>. 
* ビルド: ビルド<64>. 
* Windows: Windows<57>. 
* macOS: macOS<44>. 
* IDLE: IDLE<40>. 
* Tools/Demos: Tools/Demos<38>. 

@end menu

@node Core and Builtins<162>,ライブラリ<166>,,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id770}@anchor{1e4d}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33363}: Raise a SyntaxError for @code{async with} and @code{async for}
statements outside of async functions.

@item 
bpo-33128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33128}: Fix a bug that causes PathFinder to appear twice on
sys.meta_path. Patch by Pablo Galindo Salgado.

@item 
bpo-33312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33312}: Fixed clang ubsan (undefined behavior sanitizer) warnings in
dictobject.c by adjusting how the internal struct _dictkeysobject shared
keys structure is declared.

@item 
bpo-33231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33231}: Fix potential memory leak in @code{normalizestring()}.

@item 
bpo-33205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33205}: Change dict growth function from
@code{round_up_to_power_2(used*2+hashtable_size/2)} to
@code{round_up_to_power_2(used*3)}.  Previously, dict is shrunk only when
@code{used == 0}. Now dict has more chance to be shrunk.

@item 
bpo-29922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29922}: Improved error messages in 'async with' when @code{__aenter__()}
or @code{__aexit__()} return non-awaitable object.

@item 
bpo-33199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33199}: Fix @code{ma_version_tag} in dict implementation is uninitialized
when copying from key-sharing dict.
@end itemize

@node ライブラリ<166>,ドキュメント<59>,Core and Builtins<162>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id771}@anchor{1e4e}
@subsubsection ライブラリ



@itemize -

@item 
bpo-33281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33281}: Fix ctypes.util.find_library regression on macOS.

@item 
bpo-33383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33383}: Fixed crash in the get() method of the @ref{38,,dbm.ndbm} database
object when it is called with a single argument.

@item 
bpo-33329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33329}: Fix multiprocessing regression on newer glibcs

@item 
bpo-991266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=991266}: Fix quoting of the @code{Comment} attribute of
@ref{1e24,,http.cookies.SimpleCookie}.

@item 
bpo-33131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33131}: Upgrade bundled version of pip to 10.0.1.

@item 
bpo-33308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33308}: Fixed a crash in the @code{parser} module when converting an ST
object to a tree of tuples or lists with @code{line_info=False} and
@code{col_info=True}.

@item 
bpo-33266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33266}: lib2to3 now recognizes @code{rf'...'} strings.

@item 
bpo-11594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11594}: Ensure line-endings are respected when using lib2to3.

@item 
bpo-33254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33254}: Have @ref{503,,importlib.resources.contents()} and
@code{importlib.abc.ResourceReader.contents()} return an @ref{12f1,,iterable}
instead of an @ref{4c8,,iterator}.

@item 
bpo-33256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33256}: Fix display of @code{<module>} call in the html produced by
@code{cgitb.html()}. Patch by Stéphane Blondon.

@item 
bpo-33185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33185}: Fixed regression when running pydoc with the @ref{23c,,-m}
switch. (The regression was introduced in 3.7.0b3 by the resolution of
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053}) This fix also changed pydoc to add @code{os.getcwd()} to
@ref{3e4,,sys.path} when necessary, rather than adding @code{"."}.

@item 
bpo-33169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33169}: Delete entries of @code{None} in @ref{7fa,,sys.path_importer_cache}
when @code{importlib.machinery.invalidate_caches()} is called.

@item 
bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217}: Deprecate looking up non-Enum objects in Enum classes and Enum
members (will raise @ref{198,,TypeError} in 3.8+).

@item 
bpo-33203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33203}: @code{random.Random.choice()} now raises @code{IndexError} for empty
sequences consistently even when called from subclasses without a
@code{getrandbits()} implementation.

@item 
bpo-33224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33224}: Update difflib.mdiff() for 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/}.  Convert an uncaught
StopIteration in a generator into a return-statement.

@item 
bpo-33209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33209}: End framing at the end of C implementation of
@ref{1e25,,pickle.Pickler.dump()}.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Improved error handling and fixed a reference leak in
@ref{52e,,os.posix_spawn()}.

@item 
bpo-33175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33175}: In dataclasses, Field.__set_name__ now looks up the
__set_name__ special method on the class, not the instance, of the default
value.

@item 
bpo-33097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33097}: Raise RuntimeError when @code{executor.submit} is called during
interpreter shutdown.

@item 
bpo-31908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31908}: Fix output of cover files for @code{trace} module command-line
tool. Previously emitted cover files only when @code{--missing} option was
used. Patch by Michael Selik.
@end itemize

@node ドキュメント<59>,テスト<56>,ライブラリ<166>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id772}@anchor{1e4f}
@subsubsection ドキュメント



@itemize -

@item 
bpo-33378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33378}: Add Korean language switcher for @indicateurl{https://docs.python.org/3/}

@item 
bpo-33276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33276}: Clarify that the @code{__path__} attribute on modules cannot be
just any value.

@item 
bpo-33201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33201}: Modernize documentation for writing C extension types.

@item 
bpo-33195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33195}: Deprecate @code{Py_UNICODE} usage in @code{c-api/arg} document.
@code{Py_UNICODE} related APIs are deprecated since Python 3.3, but it is
missed in the document.

@item 
bpo-8243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8243}: Add a note about curses.addch and curses.addstr exception
behavior when writing outside a window, or pad.

@item 
bpo-32337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32337}: Update documentation related with @code{dict} order.
@end itemize

@node テスト<56>,ビルド<64>,ドキュメント<59>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id773}@anchor{1e50}
@subsubsection テスト



@itemize -

@item 
bpo-33358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33358}: Fix @code{test_embed.test_pre_initialization_sys_options()} when
the interpreter is built with @code{--enable-shared}.
@end itemize

@node ビルド<64>,Windows<57>,テスト<56>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id774}@anchor{1e51}
@subsubsection ビルド



@itemize -

@item 
bpo-33394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33394}: Enable the verbose build for extension modules, when GNU make
is passed macros on the command line.

@item 
bpo-33393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33393}: Update config.guess and config.sub files.

@item 
bpo-33377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33377}: Add new triplets for mips r6 and riscv variants (used in
extension suffixes).

@item 
bpo-32232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32232}: By default, modules configured in @code{Modules/Setup} are no
longer built with @code{-DPy_BUILD_CORE}. Instead, modules that specifically
need that preprocessor definition include it in their individual entries.

@item 
bpo-33182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33182}: The embedding tests can once again be built with clang 6.0
@end itemize

@node Windows<57>,macOS<44>,ビルド<64>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id775}@anchor{1e52}
@subsubsection Windows



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update Windows installer to use OpenSSL 1.1.0h.
@end itemize

@node macOS<44>,IDLE<40>,Windows<57>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id776}@anchor{1e53}
@subsubsection macOS



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update macOS installer build to use OpenSSL 1.1.0h.
@end itemize

@node IDLE<40>,Tools/Demos<38>,macOS<44>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id777}@anchor{1e54}
@subsubsection IDLE



@itemize -

@item 
bpo-21474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21474}: Update word/identifier definition from ascii to unicode. In
text and entry boxes, this affects selection by double-click, movement
left/right by control-left/right, and deletion left/right by
control-BACKSPACE/DEL.

@item 
bpo-33204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33204}: IDLE: consistently color invalid string prefixes. A 'u' string
prefix cannot be paired with either 'r' or 'f'. Consistently color as much
of the prefix, starting at the right, as is valid. Revise and extend
colorizer test.
@end itemize

@node Tools/Demos<38>,,IDLE<40>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id778}@anchor{1e55}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-33189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33189}: @code{pygettext.py} now recognizes only literal strings as
docstrings and translatable strings, and rejects bytes literals and
f-string expressions.

@item 
bpo-31920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31920}: Fixed handling directories as arguments in the @code{pygettext}
script. Based on patch by Oleg Krasnikov.

@item 
bpo-29673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29673}: Fix pystackv and pystack gdbinit macros.

@item 
bpo-31583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31583}: Fix 2to3 for using with --add-suffix option but without
--output-dir option for relative path to files in current directory.
@end itemize

@node Python 3 7 0 beta 3,Python 3 7 0 beta 2,Python 3 7 0 beta 4,変更履歴
@anchor{whatsnew/changelog python-3-7-0-beta-3}@anchor{1e56}
@subsection Python 3.7.0 beta 3


`Release date: 2018-03-29'

@menu
* セキュリティ: セキュリティ<47>. 
* Core and Builtins: Core and Builtins<163>. 
* ライブラリ: ライブラリ<167>. 
* ドキュメント: ドキュメント<60>. 
* テスト: テスト<57>. 
* ビルド: ビルド<65>. 
* Windows: Windows<58>. 
* macOS: macOS<45>. 
* IDLE: IDLE<41>. 
* Tools/Demos: Tools/Demos<39>. 
* C API: C API<58>. 

@end menu

@node セキュリティ<47>,Core and Builtins<163>,,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id779}@anchor{1e57}
@subsubsection セキュリティ



@itemize -

@item 
bpo-33136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33136}: Harden ssl module against LibreSSL 
@geindex Common Vulnerabilities and Exposures; CVE 2018-8970
CVE 2018-8970@footnote{https://www.cve.org/CVERecord?id=CVE-2018-8970}.
X509_VERIFY_PARAM_set1_host() is called with an explicit namelen. A new
test ensures that NULL bytes are not allowed.

@item 
bpo-33001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33001}: Minimal fix to prevent buffer overrun in os.symlink on Windows

@item 
bpo-32981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32981}: Regexes in difflib and poplib were vulnerable to catastrophic
backtracking. These regexes formed potential DOS vectors (REDOS). They
have been refactored. This resolves 
@geindex Common Vulnerabilities and Exposures; CVE 2018-1060
CVE 2018-1060@footnote{https://www.cve.org/CVERecord?id=CVE-2018-1060} and 
@geindex Common Vulnerabilities and Exposures; CVE 2018-1061
CVE 2018-1061@footnote{https://www.cve.org/CVERecord?id=CVE-2018-1061}.
Patch by Jamie Davis.
@end itemize

@node Core and Builtins<163>,ライブラリ<167>,セキュリティ<47>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id780}@anchor{1e58}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053}: When using the -m switch, sys.path[0] is now explicitly
expanded as the `starting' working directory, rather than being left as
the empty path (which allows imports from the current working directory at
the time of the import)

@item 
bpo-33018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33018}: Improve consistency of errors raised by @code{issubclass()} when
called with a non-class and an abstract base class as the first and second
arguments, respectively. Patch by Josh Bronson.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Fixed jumping when the function contains an @code{async for} loop.

@item 
bpo-33026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33026}: Fixed jumping out of "with" block by setting f_lineno.

@item 
bpo-33005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33005}: Fix a crash on fork when using a custom memory allocator (ex:
using PYTHONMALLOC env var). _PyGILState_Reinit() and
_PyInterpreterState_Enable() now use the default RAW memory allocator to
allocate a new interpreters mutex on fork.

@item 
bpo-17288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17288}: Prevent jumps from 'return' and 'exception' trace events.

@item 
bpo-32836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32836}: Don't use temporary variables in cases of list/dict/set
comprehensions
@end itemize

@node ライブラリ<167>,ドキュメント<60>,Core and Builtins<163>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id781}@anchor{1e59}
@subsubsection ライブラリ



@itemize -

@item 
bpo-33141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33141}: Have Field objects pass through __set_name__ to their default
values, if they have their own __set_name__.

@item 
bpo-33096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33096}: Allow ttk.Treeview.insert to insert iid that has a false
boolean value. Note iid=0 and iid=False would be same. Patch by Garvit
Khatri.

@item 
bpo-32873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32873}: Treat type variables and special typing forms as immutable by
copy and pickle.  This fixes several minor issues and inconsistencies, and
improves backwards compatibility with Python 3.6.

@item 
bpo-33134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33134}: When computing dataclass's __hash__, use the lookup table to
contain the function which returns the __hash__ value.  This is an
improvement over looking up a string, and then testing that string to see
what to do.

@item 
bpo-33127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33127}: The ssl module now compiles with LibreSSL 2.7.1.

@item 
bpo-32505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32505}: Raise TypeError if a member variable of a dataclass is of type
Field, but doesn't have a type annotation.

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the failure on OSX caused by the tests relying on
sem_getvalue

@item 
bpo-33116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33116}: Add 'Field' to dataclasses.__all__.

@item 
bpo-32896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32896}: Fix an error where subclassing a dataclass with a field that
uses a default_factory would generate an incorrect class.

@item 
bpo-33100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33100}: Dataclasses: If a field has a default value that's a
MemberDescriptorType, then it's from that field being in __slots__, not an
actual default value.

@item 
bpo-32953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32953}: If a non-dataclass inherits from a frozen dataclass, allow
attributes to be added to the derived class.  Only attributes from the
frozen dataclass cannot be assigned to.  Require all dataclasses in a
hierarchy to be either all frozen or all non-frozen.

@item 
bpo-33061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33061}: Add missing @code{NoReturn} to @code{__all__} in typing.py

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the size handling in multiprocessing.Queue when a pickling
error occurs.

@item 
bpo-33064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33064}: lib2to3 now properly supports trailing commas after @code{*args}
and @code{**kwargs} in function signatures.

@item 
bpo-33056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33056}: FIX properly close leaking fds in
concurrent.futures.ProcessPoolExecutor.

@item 
bpo-33021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33021}: Release the GIL during fstat() calls, avoiding hang of all
threads when calling mmap.mmap(), os.urandom(), and random.seed().  Patch
by Nir Soffer.

@item 
bpo-31804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31804}: Avoid failing in multiprocessing.Process if the standard
streams are closed or None at exit.

@item 
bpo-33037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33037}: Skip sending/receiving data after SSL transport closing.

@item 
bpo-27683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27683}: Fix a regression in @ref{84,,ipaddress} that result of
@code{hosts()} is empty when the network is constructed by a tuple
containing an integer mask and only 1 bit left for addresses.

@item 
bpo-32999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32999}: Fix C implementation of @code{ABC.__subclasscheck__(cls,
subclass)} crashed when @code{subclass} is not a type object.

@item 
bpo-33009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33009}: Fix inspect.signature() for single-parameter partialmethods.

@item 
bpo-32969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32969}: Expose several missing constants in zlib and fix corresponding
documentation.

@item 
bpo-32056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32056}: Improved exceptions raised for invalid number of channels and
sample width when read an audio file in modules @code{aifc}, @ref{119,,wave}
and @code{sunau}.

@item 
bpo-32844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32844}: Fix wrong redirection of a low descriptor (0 or 1) to stderr in
subprocess if another low descriptor is closed.

@item 
bpo-32857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32857}: In @ref{f6,,tkinter}, @code{after_cancel(None)} now raises a
@ref{2ec,,ValueError} instead of canceling the first scheduled function.
Patch by Cheryl Sabella.

@item 
bpo-31639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31639}: http.server now exposes a ThreadedHTTPServer class and uses it
when the module is run with @code{-m} to cope with web browsers pre-opening
sockets.

@item 
bpo-27645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27645}: @ref{54d,,sqlite3.Connection} now exposes a
@ref{d73,,backup} method, if the underlying SQLite
library is at version 3.6.11 or higher.  Patch by Lele Gaifax.
@end itemize

@node ドキュメント<60>,テスト<57>,ライブラリ<167>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id782}@anchor{1e5a}
@subsubsection ドキュメント



@itemize -

@item 
bpo-33126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33126}: Document PyBuffer_ToContiguous().

@item 
bpo-27212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27212}: Modify documentation for the @code{islice()} recipe to consume
initial values up to the start index.

@item 
bpo-28247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28247}: Update @ref{136,,zipapp} documentation to describe how to make
standalone applications.

@item 
bpo-18802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18802}: Documentation changes for ipaddress.  Patch by Jon Foster and
Berker Peksag.

@item 
bpo-27428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27428}: Update documentation to clarify that @code{WindowsRegistryFinder}
implements @code{MetaPathFinder}. (Patch by Himanshu Lakhara)
@end itemize

@node テスト<57>,ビルド<65>,ドキュメント<60>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id783}@anchor{1e5b}
@subsubsection テスト



@itemize -

@item 
bpo-32872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32872}: Avoid regrtest compatibility issue with namespace packages.

@item 
bpo-32517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32517}: Fix failing @code{test_asyncio} on macOS 10.12.2+ due to transport
of @code{KqueueSelector} loop was not being closed.

@item 
bpo-19417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19417}: Add test_bdb.py.
@end itemize

@node ビルド<65>,Windows<58>,テスト<57>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id784}@anchor{1e5c}
@subsubsection ビルド



@itemize -

@item 
bpo-33163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33163}: Upgrade pip to 9.0.3 and setuptools to v39.0.1.
@end itemize

@node Windows<58>,macOS<45>,ビルド<65>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id785}@anchor{1e5d}
@subsubsection Windows



@itemize -

@item 
bpo-33016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33016}: Fix potential use of uninitialized memory in
nt._getfinalpathname

@item 
bpo-32903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32903}: Fix a memory leak in os.chdir() on Windows if the current
directory is set to a UNC path.
@end itemize

@node macOS<45>,IDLE<41>,Windows<58>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id786}@anchor{1e5e}
@subsubsection macOS



@itemize -

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Build and link with private copy of Tcl/Tk 8.6 for the macOS
10.6+ installer. The 10.9+ installer variant already does this.  This
means that the Python 3.7 provided by the python.org macOS installers no
longer need or use any external versions of Tcl/Tk, either system-provided
or user-installed, such as ActiveTcl.
@end itemize

@node IDLE<41>,Tools/Demos<39>,macOS<45>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id787}@anchor{1e5f}
@subsubsection IDLE



@itemize -

@item 
bpo-32984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32984}: Set @code{__file__} while running a startup file.  Like Python,
IDLE optionally runs one startup file in the Shell window before
presenting the first interactive input prompt.  For IDLE, @code{-s} runs a
file named in environmental variable  
@geindex IDLESTARTUP
@geindex 環境変数; IDLESTARTUP
@code{IDLESTARTUP} or
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP}; @code{-r file} runs @code{file}.  Python sets
@code{__file__} to the startup file name before running the file and unsets
it before the first prompt.  IDLE now does the same when run normally,
without the @code{-n} option.

@item 
bpo-32940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32940}: Simplify and rename StringTranslatePseudoMapping in pyparse.
@end itemize

@node Tools/Demos<39>,C API<58>,IDLE<41>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id788}@anchor{1e60}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-32885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32885}: Add an @code{-n} flag for @code{Tools/scripts/pathfix.py} to disable
automatic backup creation (files with @code{~} suffix).
@end itemize

@node C API<58>,,Tools/Demos<39>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id789}@anchor{1e61}
@subsubsection C API



@itemize -

@item 
bpo-33042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33042}: Embedding applications may once again call
PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption prior to
calling Py_Initialize.

@item 
bpo-32374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32374}: Document that m_traverse for multi-phase initialized modules
can be called with m_state=NULL, and add a sanity check
@end itemize

@node Python 3 7 0 beta 2,Python 3 7 0 beta 1,Python 3 7 0 beta 3,変更履歴
@anchor{whatsnew/changelog python-3-7-0-beta-2}@anchor{1e62}
@subsection Python 3.7.0 beta 2


`Release date: 2018-02-27'

@menu
* セキュリティ: セキュリティ<48>. 
* Core and Builtins: Core and Builtins<164>. 
* ライブラリ: ライブラリ<168>. 
* ドキュメント: ドキュメント<61>. 
* テスト: テスト<58>. 
* ビルド: ビルド<66>. 
* Windows: Windows<59>. 
* macOS: macOS<46>. 
* IDLE: IDLE<42>. 
* Tools/Demos: Tools/Demos<40>. 

@end menu

@node セキュリティ<48>,Core and Builtins<164>,,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id790}@anchor{1e63}
@subsubsection セキュリティ



@itemize -

@item 
bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414}: The ssl module now allows users to perform their own IDN
en/decoding when using SNI.
@end itemize

@node Core and Builtins<164>,ライブラリ<168>,セキュリティ<48>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id791}@anchor{1e64}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32889}: Update Valgrind suppression list to account for the rename of
@code{Py_ADDRESS_IN_RANG} to @code{address_in_range}.

@item 
bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356}: Remove the new API added in bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356} (gc.ensure_disabled()
context manager).

@item 
bpo-32305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32305}: For namespace packages, ensure that both @code{__file__} and
@code{__spec__.origin} are set to None.

@item 
bpo-32303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32303}: Make sure @code{__spec__.loader} matches @code{__loader__} for
namespace packages.

@item 
bpo-32711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32711}: Fix the warning messages for Python/ast_unparse.c. Patch by
Stéphane Wirtel

@item 
bpo-32583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32583}: Fix possible crashing in builtin Unicode decoders caused by
write out-of-bound errors when using customized decode error handlers.
@end itemize

@node ライブラリ<168>,ドキュメント<61>,Core and Builtins<164>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id792}@anchor{1e65}
@subsubsection ライブラリ



@itemize -

@item 
bpo-32960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32960}: For dataclasses, disallow inheriting frozen from non-frozen
classes, and also disallow inheriting non-frozen from frozen classes. This
restriction will be relaxed at a future date.

@item 
bpo-32713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32713}: Fixed tarfile.itn handling of out-of-bounds float values. Patch
by Joffrey Fuhrer.

@item 
bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951}: Direct instantiation of SSLSocket and SSLObject objects is now
prohibited. The constructors were never documented, tested, or designed as
public constructors. Users were suppose to use ssl.wrap_socket() or
SSLContext.

@item 
bpo-32929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32929}: Remove the tri-state parameter "hash", and add the boolean
"unsafe_hash". If unsafe_hash is True, add a __hash__ function, but if a
__hash__ exists, raise TypeError.  If unsafe_hash is False, add a __hash__
based on the values of eq= and frozen=.  The unsafe_hash=False behavior is
the same as the old hash=None behavior.  unsafe_hash=False is the default,
just as hash=None used to be.

@item 
bpo-32947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32947}: Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround for TLSv1.3
for future compatibility with OpenSSL 1.1.1.

@item 
bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622}: The ssl module now detects missing NPN support in LibreSSL.

@item 
bpo-32922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32922}: dbm.open() now encodes filename with the filesystem encoding
rather than default encoding.

@item 
bpo-32859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32859}: In @code{os.dup2}, don't check every call whether the @code{dup3}
syscall exists or not.

@item 
bpo-32556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32556}: nt._getfinalpathname, nt._getvolumepathname and
nt._getdiskusage now correctly convert from bytes.

@item 
bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}: Emit a @ref{1a3,,DeprecationWarning} when using or importing an ABC
directly from @ref{1e,,collections} rather than from @ref{1f,,collections.abc}.

@item 
bpo-21060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21060}: Rewrite confusing message from setup.py upload from "No dist
file created in earlier command" to the more helpful "Must create and
upload files in one command".

@item 
bpo-32852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32852}: Make sure sys.argv remains as a list when running trace.

@item 
bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333}: @code{_abc} module is added.  It is a speedup module with C
implementations for various functions and methods in @code{abc}.  Creating an
ABC subclass and calling @code{isinstance} or @code{issubclass} with an ABC
subclass are up to 1.5x faster. In addition, this makes Python start-up up
to 10% faster. Note that the new implementation hides internal registry
and caches, previously accessible via private attributes
@code{_abc_registry}, @code{_abc_cache}, and @code{_abc_negative_cache}.  There are
three debugging helper methods that can be used instead
@code{_dump_registry}, @code{_abc_registry_clear}, and @code{_abc_caches_clear}.

@item 
bpo-32841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32841}: Fixed @code{asyncio.Condition} issue which silently ignored
cancellation after notifying and cancelling a conditional lock. Patch by
Bar Harel.

@item 
bpo-32819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32819}: ssl.match_hostname() has been simplified and no longer depends
on re and ipaddress module for wildcard and IP addresses. Error reporting
for invalid wildcards has been improved.

@item 
bpo-32394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32394}: socket: Remove
TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older version
Windows during run-time.

@item 
bpo-31787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31787}: Fixed refleaks of @code{__init__()} methods in various modules.
(Contributed by Oren Milman)

@item 
bpo-30157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30157}: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when
only the last field is quoted.  Patch by Jake Davis.

@item 
bpo-32792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32792}: collections.ChainMap() preserves the order of the underlying
mappings.

@item 
bpo-32775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32775}: @ref{184f,,fnmatch.translate()} no longer produces patterns which
contain set operations. Sets starting with '[' or containing '--', '&&',
'~~' or '||' will be interpreted differently in regular expressions in
future versions. Currently they emit warnings. fnmatch.translate() now
avoids producing patterns containing such sets by accident.

@item 
bpo-32622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32622}: Implement native fast sendfile for Windows proactor event loop.

@item 
bpo-32777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32777}: Fix a rare but potential pre-exec child process deadlock in
subprocess on POSIX systems when marking file descriptors inheritable on
exec in the child process.  This bug appears to have been introduced in
3.4.

@item 
bpo-32647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32647}: The ctypes module used to depend on indirect linking for
dlopen. The shared extension is now explicitly linked against libdl on
platforms with dl.

@item 
bpo-32741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32741}: Implement @code{asyncio.TimerHandle.when()} method.

@item 
bpo-32691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32691}: Use mod_spec.parent when running modules with pdb

@item 
bpo-32734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32734}: Fixed @code{asyncio.Lock()} safety issue which allowed acquiring
and locking the same lock multiple times, without it being free. Patch by
Bar Harel.

@item 
bpo-32727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32727}: Do not include name field in SMTP envelope from address. Patch
by Stéphane Wirtel

@item 
bpo-31453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31453}: Add TLSVersion constants and SSLContext.maximum_version /
minimum_version attributes. The new API wraps OpenSSL 1.1
@indicateurl{https://web.archive.org/web/20180309043602/https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html}
feature.

@item 
bpo-24334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24334}: Internal implementation details of ssl module were cleaned up.
The SSLSocket has one less layer of indirection. Owner and session
information are now handled by the SSLSocket and SSLObject constructor.
Channel binding implementation has been simplified.

@item 
bpo-31848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31848}: Fix the error handling in Aifc_read.initfp() when the SSND
chunk is not found. Patch by Zackery Spytz.

@item 
bpo-32585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32585}: Add Ttk spinbox widget to @ref{ff,,tkinter.ttk}.  Patch by Alan D
Moore.

@item 
bpo-32221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32221}: Various functions returning tuple containing IPv6 addresses now
omit @code{%scope} part since the same information is already encoded in
`scopeid' tuple item. Especially this speeds up @code{socket.recvfrom()}
when it receives multicast packet since useless resolving of network
interface name is omitted.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The TarFile class now recurses directories in a reproducible
way.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The ZipFile class now recurses directories in a reproducible
way.
@end itemize

@node ドキュメント<61>,テスト<58>,ライブラリ<168>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id793}@anchor{1e66}
@subsubsection ドキュメント



@itemize -

@item 
bpo-28124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28124}: The ssl module function ssl.wrap_socket() has been
de-emphasized and deprecated in favor of the more secure and efficient
SSLContext.wrap_socket() method.

@item 
bpo-17232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17232}: Clarify docs for -O and -OO.  Patch by Terry Reedy.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Add documentation for the contextvars module (PEP 567).

@item 
bpo-32800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32800}: Update link to w3c doc for xml default namespaces.

@item 
bpo-11015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11015}: Update @ref{ea,,test.support} documentation.

@item 
bpo-8722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8722}: Document @code{__getattr__()} behavior when property @code{get()}
method raises @ref{5f0,,AttributeError}.

@item 
bpo-32614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32614}: Modify RE examples in documentation to use raw strings to
prevent @ref{1a3,,DeprecationWarning} and add text to REGEX HOWTO to highlight
the deprecation.

@item 
bpo-31972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31972}: Improve docstrings for @code{pathlib.PurePath} subclasses.
@end itemize

@node テスト<58>,ビルド<66>,ドキュメント<61>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id794}@anchor{1e67}
@subsubsection テスト



@itemize -

@item 
bpo-31809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31809}: Add tests to verify connection with secp ECDH curves.
@end itemize

@node ビルド<66>,Windows<59>,テスト<58>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id795}@anchor{1e68}
@subsubsection ビルド



@itemize -

@item 
bpo-32898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32898}: Fix the python debug build when using COUNT_ALLOCS.
@end itemize

@node Windows<59>,macOS<46>,ビルド<66>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id796}@anchor{1e69}
@subsubsection Windows



@itemize -

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update Tcl and Tk versions to 8.6.8

@item 
bpo-31966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31966}: Fixed WindowsConsoleIO.write() for writing empty data.

@item 
bpo-32409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32409}: Ensures activate.bat can handle Unicode contents.

@item 
bpo-32457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32457}: Improves handling of denormalized executable path when
launching Python.

@item 
bpo-32370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32370}: Use the correct encoding for ipconfig output in the uuid
module. Patch by Segev Finer.

@item 
bpo-29248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29248}: Fix @ref{b1a,,os.readlink()} on Windows, which was mistakenly
treating the @code{PrintNameOffset} field of the reparse data buffer as a
number of characters instead of bytes. Patch by Craig Holmquist and SSE4.
@end itemize

@node macOS<46>,IDLE<42>,Windows<59>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id797}@anchor{1e6a}
@subsubsection macOS



@itemize -

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update macOS 10.9+ installer to Tcl/Tk 8.6.8.
@end itemize

@node IDLE<42>,Tools/Demos<40>,macOS<46>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id798}@anchor{1e6b}
@subsubsection IDLE



@itemize -

@item 
bpo-32916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32916}: Change @code{str} to @code{code} in pyparse.

@item 
bpo-32905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32905}: Remove unused code in pyparse module.

@item 
bpo-32874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32874}: Add tests for pyparse.

@item 
bpo-32837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32837}: Using the system and place-dependent default encoding for
open() is a bad idea for IDLE's system and location-independent files.

@item 
bpo-32826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32826}: Add "encoding=utf-8" to open() in IDLE's test_help_about. GUI
test test_file_buttons() only looks at initial ascii-only lines, but
failed on systems where open() defaults to 'ascii' because readline()
internally reads and decodes far enough ahead to encounter a non-ascii
character in CREDITS.txt.

@item 
bpo-32765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32765}: Update configdialog General tab docstring to add new widgets to
the widget list.
@end itemize

@node Tools/Demos<40>,,IDLE<42>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id799}@anchor{1e6c}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-32222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32222}: Fix pygettext not extracting docstrings for functions with type
annotated arguments. Patch by Toby Harradine.
@end itemize

@node Python 3 7 0 beta 1,Python 3 7 0 alpha 4,Python 3 7 0 beta 2,変更履歴
@anchor{whatsnew/changelog python-3-7-0-beta-1}@anchor{1e6d}
@subsection Python 3.7.0 beta 1


`Release date: 2018-01-30'

@menu
* Core and Builtins: Core and Builtins<165>. 
* ライブラリ: ライブラリ<169>. 
* ドキュメント: ドキュメント<62>. 
* テスト: テスト<59>. 
* ビルド: ビルド<67>. 
* Windows: Windows<60>. 
* macOS: macOS<47>. 
* C API: C API<59>. 

@end menu

@node Core and Builtins<165>,ライブラリ<169>,,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id800}@anchor{1e6e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32703}: Fix coroutine's ResourceWarning when there's an active error
set when it's being finalized.

@item 
bpo-32650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32650}: Pdb and other debuggers dependent on bdb.py will correctly step
over (next command) native coroutines. Patch by Pablo Galindo.

@item 
bpo-28685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28685}: Optimize list.sort() and sorted() by using type specialized
comparisons when possible.

@item 
bpo-32685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32685}: Improve suggestion when the Python 2 form of print statement is
either present on the same line as the header of a compound statement or
else terminated by a semi-colon instead of a newline. Patch by Nitish
Chandra.

@item 
bpo-32697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32697}: Python now explicitly preserves the definition order of
keyword-only parameters.  It's always preserved their order, but this
behavior was never guaranteed before; this behavior is now guaranteed and
tested.

@item 
bpo-32690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32690}: The locals() dictionary now displays in the lexical order that
variables were defined.  Previously, the order was reversed.

@item 
bpo-32677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32677}: Add @code{.isascii()} method to @code{str}, @code{bytes} and
@code{bytearray}. It can be used to test that string contains only ASCII
characters.

@item 
bpo-32670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32670}: Enforce 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/} for all code. This means that manually
raising a StopIteration exception from a generator is prohibited for all
code, regardless of whether 'from __future__ import generator_stop' was
used or not.

@item 
bpo-32591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32591}: Added built-in support for tracking the origin of coroutine
objects; see sys.set_coroutine_origin_tracking_depth and
CoroutineType.cr_origin. This replaces the asyncio debug mode's use of
coroutine wrapping for native coroutine objects.

@item 
bpo-31368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31368}: Expose preadv and pwritev system calls in the os module. Patch
by Pablo Galindo

@item 
bpo-32544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32544}: @code{hasattr(obj, name)} and @code{getattr(obj, name, default)} are
about 4 times faster than before when @code{name} is not found and @code{obj}
doesn't override @code{__getattr__} or @code{__getattribute__}.

@item 
bpo-26163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26163}: Improved frozenset() hash to create more distinct hash values
when faced with datasets containing many similar values.

@item 
bpo-32550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32550}: Remove the STORE_ANNOTATION bytecode.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Expose posix_spawn as a low level API in the os module.
(removed before 3.7.0rc1)

@item 
bpo-24340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24340}: Fixed estimation of the code stack size.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Implement 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} Context Variables.

@item 
bpo-18533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18533}: @code{repr()} on a dict containing its own @code{values()} or
@code{items()} no longer raises @code{RecursionError}; OrderedDict similarly.
Instead, use @code{...}, as for other recursive structures.  Patch by Ben
North.

@item 
bpo-20891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20891}: Py_Initialize() now creates the GIL. The GIL is no longer
created "on demand" to fix a race condition when PyGILState_Ensure() is
called in a non-Python thread.

@item 
bpo-32028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32028}: Leading whitespace is now correctly ignored when generating
suggestions for converting Py2 print statements to Py3 builtin print
function calls. Patch by Sanyam Khurana.

@item 
bpo-31179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31179}: Make dict.copy() up to 5.5 times faster.

@item 
bpo-31113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31113}: Get rid of recursion in the compiler for normal control flow.
@end itemize

@node ライブラリ<169>,ドキュメント<62>,Core and Builtins<165>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id801}@anchor{1e6f}
@subsubsection ライブラリ



@itemize -

@item 
bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}: Deprecate exposing the contents of collections.abc in the
regular collections module.

@item 
bpo-31429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31429}: The default cipher suite selection of the ssl module now uses a
blacklist approach rather than a hard-coded whitelist. Python no longer
re-enables ciphers that have been blocked by OpenSSL security update.
Default cipher suite selection can be configured on compile time.

@item 
bpo-30306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30306}: contextlib.contextmanager now releases the arguments passed to
the underlying generator as soon as the context manager is entered.
Previously it would keep them alive for as long as the context manager was
alive, even when not being used as a function decorator. Patch by Martin
Teichmann.

@item 
bpo-21417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21417}: Added support for setting the compression level for
zipfile.ZipFile.

@item 
bpo-32251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32251}: Implement asyncio.BufferedProtocol (provisional API).

@item 
bpo-32513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32513}: In dataclasses, allow easier overriding of dunder methods
without specifying decorator parameters.

@item 
bpo-32660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32660}: @ref{e7,,termios} makes available @code{FIONREAD}, @code{FIONCLEX},
@code{FIOCLEX}, @code{FIOASYNC} and @code{FIONBIO} also under Solaris/derivatives.

@item 
bpo-27931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27931}: Fix email address header parsing error when the username is an
empty quoted string. Patch by Xiang Zhang.

@item 
bpo-32659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32659}: Under Solaris and derivatives, @ref{16da,,os.stat_result} provides
a st_fstype attribute.

@item 
bpo-32662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32662}: Implement Server.start_serving(), Server.serve_forever(), and
Server.is_serving() methods.  Add 'start_serving' keyword parameter to
loop.create_server() and loop.create_unix_server().

@item 
bpo-32391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32391}: Implement @ref{d02,,asyncio.StreamWriter.wait_closed()} and
@ref{d03,,asyncio.StreamWriter.is_closing()} methods

@item 
bpo-32643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32643}: Make Task._step, Task._wakeup and Future._schedule_callbacks
methods private.

@item 
bpo-32630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32630}: Refactor decimal module to use contextvars to store decimal
context.

@item 
bpo-32622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32622}: Add @code{asyncio.AbstractEventLoop.sendfile()} method.

@item 
bpo-32304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32304}: distutils' upload command no longer corrupts tar files ending
with a CR byte, and no longer tries to convert CR to CRLF in any of the
upload text fields.

@item 
bpo-32502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32502}: uuid.uuid1 no longer raises an exception if a 64-bit hardware
address is encountered.

@item 
bpo-32596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32596}: @code{concurrent.futures} imports @code{ThreadPoolExecutor} and
@code{ProcessPoolExecutor} lazily (using 
@geindex Python Enhancement Proposals; PEP 562
PEP 562@footnote{https://peps.python.org/pep-0562/}). It makes @code{import
asyncio} about 15% faster because asyncio uses only
@code{ThreadPoolExecutor} by default.

@item 
bpo-31801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31801}: Add @code{_ignore_} to @code{Enum} so temporary variables can be used
during class construction without being turned into members.

@item 
bpo-32576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32576}: Use queue.SimpleQueue() in places where it can be invoked from
a weakref callback.

@item 
bpo-32574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32574}: Fix memory leak in asyncio.Queue, when the queue has limited
size and it is full, the cancellation of queue.put() can cause a memory
leak. Patch by: José Melero.

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: The nis module is now compatible with new libnsl and headers
location.

@item 
bpo-32467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32467}: collections.abc.ValuesView now inherits from
collections.abc.Collection.

@item 
bpo-32473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32473}: Improve ABCMeta._dump_registry() output readability

@item 
bpo-32102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32102}: New argument @code{capture_output} for subprocess.run

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: glibc has removed Sun RPC. Use replacement libtirpc headers and
library in nis module.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: UUID module fixes build for FreeBSD/OpenBSD

@item 
bpo-32503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32503}: Pickling with protocol 4 no longer creates too small frames.

@item 
bpo-29237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29237}: Create enum for pstats sorting options

@item 
bpo-32454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32454}: Add close(fd) function to the socket module.

@item 
bpo-25942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25942}: The subprocess module is now more graceful when handling a
Ctrl-C KeyboardInterrupt during subprocess.call, subprocess.run, or a
Popen context manager.  It now waits a short amount of time for the child
(presumed to have also gotten the SIGINT) to exit, before continuing the
KeyboardInterrupt exception handling.  This still includes a SIGKILL in
the call() and run() APIs, but at least the child had a chance first.

@item 
bpo-32433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32433}: The hmac module now has hmac.digest(), which provides an
optimized HMAC digest.

@item 
bpo-28134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28134}: Sockets now auto-detect family, type and protocol from file
descriptor by default.

@item 
bpo-32404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32404}: Fix bug where @ref{712,,datetime.datetime.fromtimestamp()} did not
call __new__ in @ref{4e2,,datetime.datetime} subclasses.

@item 
bpo-32403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32403}: Improved speed of @ref{1fa,,datetime.date} and
@ref{4e2,,datetime.datetime} alternate constructors.

@item 
bpo-32228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32228}: Ensure that @code{truncate()} preserves the file position (as
reported by @code{tell()}) after writes longer than the buffer size.

@item 
bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410}: Implement @code{loop.sock_sendfile} for asyncio event loop.

@item 
bpo-22908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22908}: Added seek and tell to the ZipExtFile class. This only works if
the file object used to open the zipfile is seekable.

@item 
bpo-32373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32373}: Add socket.getblocking() method.

@item 
bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248}: Add @ref{7f,,importlib.resources} and
@code{importlib.abc.ResourceReader} as the unified API for reading
resources contained within packages.  Loaders wishing to support resource
reading must implement the @code{get_resource_reader()} method.  File-based
and zipimport-based loaders both implement these APIs.
@ref{de2,,importlib.abc.ResourceLoader} is deprecated in favor of these new
APIs.

@item 
bpo-32320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32320}: collections.namedtuple() now supports default values.

@item 
bpo-29302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29302}: Add contextlib.AsyncExitStack. Patch by Alexander Mohr and Ilya
Kulakov.

@item 
bpo-31961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31961}: `Removed in Python 3.7.0b2.' The `args' argument of
subprocess.Popen can now be a @ref{5a1,,path-like object}. If `args' is given
as a sequence, it's first element can now be a @ref{5a1,,path-like object} as
well.

@item 
bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900}: The @ref{df8,,locale.localeconv()} function now sets temporarily the
@code{LC_CTYPE} locale to the @code{LC_NUMERIC} locale to decode
@code{decimal_point} and @code{thousands_sep} byte strings if they are non-ASCII
or longer than 1 byte, and the @code{LC_NUMERIC} locale is different than the
@code{LC_CTYPE} locale. This temporary change affects other threads. Same
change for the @ref{833,,str.format()} method when formatting a number
(@ref{19b,,int}, @ref{196,,float}, @ref{196,,float} and subclasses) with the
@code{n} type (ex: @code{'@{:n@}'.format(1234)}).

@item 
bpo-31853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31853}: Use super().method instead of socket.method in SSLSocket.  They
were there most likely for legacy reasons.

@item 
bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399}: The ssl module now uses OpenSSL's X509_VERIFY_PARAM_set1_host()
and X509_VERIFY_PARAM_set1_ip() API to verify hostname and IP addresses.
Subject common name fallback can be disabled with
SSLContext.hostname_checks_common_name.

@item 
bpo-14976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14976}: Add a queue.SimpleQueue class, an unbounded FIFO queue with a
reentrant C implementation of put().
@end itemize

@node ドキュメント<62>,テスト<59>,ライブラリ<169>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id802}@anchor{1e70}
@subsubsection ドキュメント



@itemize -

@item 
bpo-32724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32724}: Add references to some commands in the documentation of Pdb.
Patch by Stéphane Wirtel

@item 
bpo-32649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32649}: Complete the C API documentation, profiling and tracing part
with the newly added per-opcode events.

@item 
bpo-17799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17799}: Explain real behaviour of sys.settrace and sys.setprofile and
their C-API counterparts regarding which type of events are received in
each function. Patch by Pablo Galindo Salgado.
@end itemize

@node テスト<59>,ビルド<67>,ドキュメント<62>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id803}@anchor{1e71}
@subsubsection テスト



@itemize -

@item 
bpo-32721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32721}: Fix test_hashlib to not fail if the _md5 module is not built.

@item 
bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414}: Add test cases for IDNA 2003 and 2008 host names. IDNA 2003
internationalized host names are working since bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399} has landed. IDNA
2008 are still broken.

@item 
bpo-32604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32604}: Add a new "_xxsubinterpreters" extension module that exposes
the existing subinterpreter C-API and a new cross-interpreter data sharing
mechanism. The module is primarily intended for more thorough testing of
the existing subinterpreter support. Note that the _xxsubinterpreters
module has been removed in 3.7.0rc1.

@item 
bpo-32602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32602}: Add test certs and test for ECDSA cert and EC/RSA dual mode.

@item 
bpo-32549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32549}: On Travis CI, Python now Compiles and uses a local copy of
OpenSSL 1.1.0g for testing.
@end itemize

@node ビルド<67>,Windows<60>,テスト<59>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id804}@anchor{1e72}
@subsubsection ビルド



@itemize -

@item 
bpo-32635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32635}: Fix segfault of the crypt module when libxcrypt is provided
instead of libcrypt at the system.

@item 
bpo-32598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32598}: Use autoconf to detect OpenSSL libs, headers and supported
features. The ax_check_openssl M4 macro uses pkg-config to locate OpenSSL
and falls back to manual search.

@item 
bpo-32593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32593}: Drop support of FreeBSD 9 and older.

@item 
bpo-29708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29708}: If the 
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable is set,
@ref{b8,,py_compile} will always create hash-based @code{.pyc} files.
@end itemize

@node Windows<60>,macOS<47>,ビルド<67>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id805}@anchor{1e73}
@subsubsection Windows



@itemize -

@item 
bpo-32588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32588}: Create standalone _distutils_findvs module and add missing
_queue module to installer.

@item 
bpo-29911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29911}: Ensure separate Modify and Uninstall buttons are displayed.

@item 
bpo-32507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32507}: Use app-local UCRT install rather than the proper update for
old versions of Windows.
@end itemize

@node macOS<47>,C API<59>,Windows<60>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id806}@anchor{1e74}
@subsubsection macOS



@itemize -

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Provide an additional, more modern macOS installer variant that
supports macOS 10.9+ systems in 64-bit mode only.  Upgrade the supplied
third-party libraries to OpenSSL 1.1.0g and to SQLite 3.22.0.  The 10.9+
installer now links with and supplies its own copy of Tcl/Tk 8.6.

@item 
bpo-28440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28440}: No longer add /Library/Python/3.x/site-packages to sys.path for
macOS framework builds to avoid future conflicts.
@end itemize

@node C API<59>,,macOS<47>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id807}@anchor{1e75}
@subsubsection C API



@itemize -

@item 
bpo-32681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32681}: Fix uninitialized variable 'res' in the C implementation of
os.dup2. Patch by Stéphane Wirtel

@item 
bpo-10381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10381}: Add C API access to the @code{datetime.timezone} constructor and
@code{datetime.timezone.UTC} singleton.
@end itemize

@node Python 3 7 0 alpha 4,Python 3 7 0 alpha 3,Python 3 7 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-7-0-alpha-4}@anchor{1e76}
@subsection Python 3.7.0 alpha 4


`Release date: 2018-01-08'

@menu
* Core and Builtins: Core and Builtins<166>. 
* ライブラリ: ライブラリ<170>. 
* ドキュメント: ドキュメント<63>. 
* テスト: テスト<60>. 
* Windows: Windows<61>. 
* Tools/Demos: Tools/Demos<41>. 
* C API: C API<60>. 

@end menu

@node Core and Builtins<166>,ライブラリ<170>,,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id808}@anchor{1e77}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31975}: The default warning filter list now starts with a
"default::DeprecationWarning:__main__" entry, so deprecation warnings are
once again shown by default in single-file scripts and at the interactive
prompt.

@item 
bpo-32226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32226}: @code{__class_getitem__} is now an automatic class method.

@item 
bpo-32399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32399}: Add AIX uuid library support for RFC4122 using uuid_create() in
libc.a

@item 
bpo-32390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32390}: Fix the compilation failure on AIX after the f_fsid field has
been added to the object returned by os.statvfs() (bpo-32143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32143}). Original
patch by Michael Felt.

@item 
bpo-32379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32379}: Make MRO computation faster when a class inherits from a single
base.

@item 
bpo-32259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32259}: The error message of a TypeError raised when unpack
non-iterable is now more specific.

@item 
bpo-27169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27169}: The @code{__debug__} constant is now optimized out at compile
time. This fixes also bpo-22091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22091}.

@item 
bpo-32329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32329}: The @ref{1e78,,-R} option now turns on hash randomization when
the 
@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} environment variable is set to @code{0}.
Previously, the option was ignored. Moreover,
@code{sys.flags.hash_randomization} is now properly set to 0 when hash
randomization is turned off by @code{PYTHONHASHSEED=0}.

@item 
bpo-30416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30416}: The optimizer is now protected from spending much time doing
complex calculations and consuming much memory for creating large
constants in constant folding. Increased limits for constants that can be
produced in constant folding.

@item 
bpo-32282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32282}: Fix an unnecessary ifdef in the include of VersionHelpers.h in
socketmodule on Windows.

@item 
bpo-30579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30579}: Implement TracebackType.__new__ to allow Python-level creation
of traceback objects, and make TracebackType.tb_next mutable.

@item 
bpo-32260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32260}: Don't byte swap the input keys to the SipHash algorithm on
big-endian platforms. This should ensure siphash gives consistent results
across platforms.

@item 
bpo-31506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31506}: Improve the error message logic for object.__new__ and
object.__init__. Patch by Sanyam Khurana.

@item 
bpo-20361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20361}: @code{-b} and @code{-bb} now inject @code{'default::BytesWarning'} and
@code{error::BytesWarning} entries into @code{sys.warnoptions}, ensuring that
they take precedence over any other warning filters configured via the
@code{-W} option or the @code{PYTHONWARNINGS} environment variable.

@item 
bpo-32230@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32230}: @code{-X dev} now injects a @code{'default'} entry into
sys.warnoptions, ensuring that it behaves identically to actually passing
@code{-Wdefault} at the command line.

@item 
bpo-29240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29240}: Add a new UTF-8 mode: implementation of the 
@geindex Python Enhancement Proposals; PEP 540
PEP 540@footnote{https://peps.python.org/pep-0540/}.

@item 
bpo-32226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32226}: 
@geindex Python Enhancement Proposals; PEP 560
PEP 560@footnote{https://peps.python.org/pep-0560/}: Add support for @code{__mro_entries__} and
@code{__class_getitem__}. Implemented by Ivan Levkivskyi.

@item 
bpo-32225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32225}: 
@geindex Python Enhancement Proposals; PEP 562
PEP 562@footnote{https://peps.python.org/pep-0562/}: Add support for module @code{__getattr__} and
@code{__dir__}. Implemented by Ivan Levkivskyi.

@item 
bpo-31901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31901}: The @code{atexit} module now has its callback stored per
interpreter.

@item 
bpo-31650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31650}: Implement 
@geindex Python Enhancement Proposals; PEP 552
PEP 552@footnote{https://peps.python.org/pep-0552/} (Deterministic pycs). Python now supports
invalidating bytecode cache files bashed on a source content hash rather
than source last-modified time.

@item 
bpo-29469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29469}: Move constant folding from bytecode layer to AST layer.
Original patch by Eugene Toder.
@end itemize

@node ライブラリ<170>,ドキュメント<63>,Core and Builtins<166>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id809}@anchor{1e79}
@subsubsection ライブラリ



@itemize -

@item 
bpo-32506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32506}: Now that dict is defined as keeping insertion order, drop
OrderedDict and just use plain dict.

@item 
bpo-32279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32279}: Add params to dataclasses.make_dataclasses(): init, repr, eq,
order, hash, and frozen.  Pass them through to dataclass().

@item 
bpo-32278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32278}: Make type information optional on dataclasses.make_dataclass().
If omitted, the string 'typing.Any' is used.

@item 
bpo-32499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32499}: Add dataclasses.is_dataclass(obj), which returns True if obj is
a dataclass or an instance of one.

@item 
bpo-32468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32468}: Improve frame repr() to mention filename, code name and current
line number.

@item 
bpo-23749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23749}: asyncio: Implement loop.start_tls()

@item 
bpo-32441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32441}: Return the new file descriptor (i.e., the second argument) from
@code{os.dup2}. Previously, @code{None} was always returned.

@item 
bpo-32422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32422}: @code{functools.lru_cache} uses less memory (3 words for each
cached key) and takes about 1/3 time for cyclic GC.

@item 
bpo-31721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31721}: Prevent Python crash from happening when Future._log_traceback
is set to True manually.  Now it can only be set to False, or a ValueError
is raised.

@item 
bpo-32415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32415}: asyncio: Add Task.get_loop() and Future.get_loop()

@item 
bpo-26133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26133}: Don't unsubscribe signals in asyncio UNIX event loop on
interpreter shutdown.

@item 
bpo-32363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32363}: Make asyncio.Task.set_exception() and set_result() raise
NotImplementedError. Task._step() and Future.__await__() raise proper
exceptions when they are in an invalid state, instead of raising an
AssertionError.

@item 
bpo-32357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32357}: Optimize asyncio.iscoroutine() and loop.create_task() for
non-native coroutines (e.g. async/await compiled with Cython).
'loop.create_task(python_coroutine)' used to be 20% faster than
'loop.create_task(cython_coroutine)'.  Now, the latter is as fast.

@item 
bpo-32356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32356}: asyncio.transport.resume_reading() and pause_reading() are now
idempotent. New transport.is_reading() method is added.

@item 
bpo-32355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32355}: Optimize asyncio.gather(); now up to 15% faster.

@item 
bpo-32351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32351}: Use fastpath in asyncio.sleep if delay<0 (2x boost)

@item 
bpo-32348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32348}: Optimize asyncio.Future schedule/add/remove callback.  The
optimization shows 3-6% performance improvements of async/await code.

@item 
bpo-32331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32331}: Fix socket.settimeout() and socket.setblocking() to keep
socket.type as is. Fix socket.socket() constructor to reset any bit flags
applied to socket's type.  This change only affects OSes that have
SOCK_NONBLOCK and/or SOCK_CLOEXEC.

@item 
bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248}: Add @code{importlib.abc.ResourceReader} as an ABC for
loaders to provide a unified API for reading resources contained within
packages.  Also add @ref{7f,,importlib.resources} as the port of
@code{importlib_resources}.

@item 
bpo-32311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32311}: Implement asyncio.create_task(coro) shortcut

@item 
bpo-32327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32327}: Convert asyncio functions that were documented as coroutines to
coroutines. Affected functions: loop.sock_sendall, loop.sock_recv,
loop.sock_accept, loop.getaddrinfo, loop.getnameinfo.

@item 
bpo-32323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32323}: @ref{f3a,,urllib.parse.urlsplit()} does not convert zone-id (scope)
to lower case for scoped IPv6 addresses in hostnames now.

@item 
bpo-32302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32302}: Fix bdist_wininst of distutils for CRT v142: it binary
compatible with CRT v140.

@item 
bpo-29711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29711}: Fix @code{stop_serving} in asyncio proactor loop kill all
listening servers

@item 
bpo-32308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32308}: @ref{5a3,,re.sub()} now replaces empty matches adjacent to a
previous non-empty match.

@item 
bpo-29970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29970}: Abort asyncio SSLProtocol connection if handshake not complete
within 10 seconds.

@item 
bpo-32314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32314}: Implement asyncio.run().

@item 
bpo-17852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17852}: Revert incorrect fix based on misunderstanding of
_Py_PyAtExit() semantics.

@item 
bpo-32296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32296}: Implement asyncio._get_running_loop() and get_event_loop() in
C. This makes them 4x faster.

@item 
bpo-32250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32250}: Implement @code{asyncio.current_task()} and
@code{asyncio.all_tasks()}. Add helpers intended to be used by alternative
task implementations: @code{asyncio._register_task}, @code{asyncio._enter_task},
@code{asyncio._leave_task} and @code{asyncio._unregister_task}. Deprecate
@code{asyncio.Task.current_task()} and @code{asyncio.Task.all_tasks()}.

@item 
bpo-32255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32255}: A single empty field is now always quoted when written into a
CSV file. This allows to distinguish an empty row from a row consisting of
a single empty field. Patch by Licht Takeuchi.

@item 
bpo-32277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32277}: Raise @code{NotImplementedError} instead of @code{SystemError} on
platforms where @code{chmod(..., follow_symlinks=False)} is not supported.
Patch by Anthony Sottile.

@item 
bpo-30050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30050}: New argument warn_on_full_buffer to signal.set_wakeup_fd lets
you control whether Python prints a warning on stderr when the wakeup fd
buffer overflows.

@item 
bpo-29137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29137}: The @code{fpectl} library has been removed. It was never enabled
by default, never worked correctly on x86-64, and it changed the Python
ABI in ways that caused unexpected breakage of C extensions.

@item 
bpo-32273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32273}: Move asyncio.test_utils to test.test_asyncio.

@item 
bpo-32272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32272}: Remove asyncio.async() function.

@item 
bpo-32269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32269}: Add asyncio.get_running_loop() function.

@item 
bpo-32265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32265}: All class and static methods of builtin types now are correctly
classified by inspect.classify_class_attrs() and grouped in pydoc output.
Added types.ClassMethodDescriptorType for unbound class methods of builtin
types.

@item 
bpo-32253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32253}: Deprecate @code{yield from lock}, @code{await lock}, @code{with (yield
from lock)} and @code{with await lock} for asyncio synchronization
primitives.

@item 
bpo-22589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22589}: Changed MIME type of .bmp from 'image/x-ms-bmp' to 'image/bmp'

@item 
bpo-32193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32193}: Convert asyncio to use `async/await' syntax. Old styled @code{yield
from} is still supported too.

@item 
bpo-32206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32206}: Add support to run modules with pdb

@item 
bpo-32227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32227}: @code{functools.singledispatch} now supports registering
implementations using type annotations.

@item 
bpo-15873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15873}: Added new alternate constructors
@ref{82a,,datetime.datetime.fromisoformat()},
@ref{829,,datetime.time.fromisoformat()} and
@ref{828,,datetime.date.fromisoformat()} as the inverse operation of each
classes's respective @code{isoformat} methods.

@item 
bpo-32199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32199}: The getnode() ip getter now uses 'ip link' instead of 'ip link
list'.

@item 
bpo-32143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32143}: os.statvfs() includes the f_fsid field from statvfs(2)

@item 
bpo-26439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26439}: Fix ctypes.util.find_library() for AIX by implementing
ctypes._aix.find_library() Patch by: Michael Felt

@item 
bpo-31993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31993}: The pickler now uses less memory when serializing large bytes
and str objects into a file.  Pickles created with protocol 4 will require
less memory for unpickling large bytes and str objects.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: Ensure TCP_NODELAY is set on Linux. Tests by Victor Stinner.

@item 
bpo-31778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31778}: ast.literal_eval() is now more strict. Addition and subtraction
of arbitrary numbers no longer allowed.

@item 
bpo-31802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31802}: Importing native path module (@code{posixpath}, @code{ntpath}) now
works even if the @code{os} module still is not imported.

@item 
bpo-30241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30241}: Add contextlib.AbstractAsyncContextManager. Patch by Jelle
Zijlstra.

@item 
bpo-31699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31699}: Fix deadlocks in
@ref{1d6,,concurrent.futures.ProcessPoolExecutor} when task arguments or
results cause pickling or unpickling errors. This should make sure that
calls to the @code{ProcessPoolExecutor} API always eventually return.

@item 
bpo-15216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15216}: @code{TextIOWrapper.reconfigure()} supports changing `encoding',
`errors', and `newline'.
@end itemize

@node ドキュメント<63>,テスト<60>,ライブラリ<170>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id810}@anchor{1e7a}
@subsubsection ドキュメント



@itemize -

@item 
bpo-32418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32418}: Add get_loop() method to Server and AbstractServer classes.
@end itemize

@node テスト<60>,Windows<61>,ドキュメント<63>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id811}@anchor{1e7b}
@subsubsection テスト



@itemize -

@item 
bpo-32252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32252}: Fix faulthandler_suppress_crash_report() used to prevent core
dump files when testing crashes. getrlimit() returns zero on success.

@item 
bpo-32002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32002}: Adjust C locale coercion testing for the empty locale and POSIX
locale cases to more readily adjust to platform dependent behaviour.
@end itemize

@node Windows<61>,Tools/Demos<41>,テスト<60>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id812}@anchor{1e7c}
@subsubsection Windows



@itemize -

@item 
bpo-19764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19764}: Implement support for @code{subprocess.Popen(close_fds=True)} on
Windows. Patch by Segev Finer.
@end itemize

@node Tools/Demos<41>,C API<60>,Windows<61>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id813}@anchor{1e7d}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-24960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24960}: 2to3 and lib2to3 can now read pickled grammar files using
pkgutil.get_data() rather than probing the filesystem. This lets 2to3 and
lib2to3 work when run from a zipfile.
@end itemize

@node C API<60>,,Tools/Demos<41>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id814}@anchor{1e7e}
@subsubsection C API



@itemize -

@item 
bpo-32030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32030}: Py_Initialize() doesn't reset the memory allocators to default
if the @code{PYTHONMALLOC} environment variable is not set.

@item 
bpo-29084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29084}: Undocumented C API for OrderedDict has been excluded from the
limited C API. It was added by mistake and actually never worked in the
limited C API.

@item 
bpo-32264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32264}: Moved the pygetopt.h header into internal/, since it has no
public APIs.

@item 
bpo-32241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32241}: @code{Py_SetProgramName()} and @code{Py_SetPythonHome()}
now take the @code{const wchar *} arguments instead of @code{wchar *}.
@end itemize

@node Python 3 7 0 alpha 3,Python 3 7 0 alpha 2,Python 3 7 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-7-0-alpha-3}@anchor{1e7f}
@subsection Python 3.7.0 alpha 3


`Release date: 2017-12-05'

@menu
* Core and Builtins: Core and Builtins<167>. 
* ライブラリ: ライブラリ<171>. 
* ドキュメント: ドキュメント<64>. 
* テスト: テスト<61>. 
* ビルド: ビルド<68>. 
* Windows: Windows<62>. 
* macOS: macOS<48>. 
* IDLE: IDLE<43>. 
* Tools/Demos: Tools/Demos<42>. 
* C API: C API<61>. 

@end menu

@node Core and Builtins<167>,ライブラリ<171>,,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id815}@anchor{1e80}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32176}: co_flags.CO_NOFREE is now always set correctly by the code
object constructor based on freevars and cellvars, rather than needing to
be set correctly by the caller. This ensures it will be cleared
automatically when additional cell references are injected into a modified
code object and function.

@item 
bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544}: Yield expressions are now deprecated in comprehensions and
generator expressions. They are still permitted in the definition of the
outermost iterable, as that is evaluated directly in the enclosing scope.

@item 
bpo-32137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32137}: The repr of deeply nested dict now raises a RecursionError
instead of crashing due to a stack overflow.

@item 
bpo-32096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32096}: Revert memory allocator changes in the C API: move structures
back from _PyRuntime to Objects/obmalloc.c. The memory allocators are once
again initialized statically, and so PyMem_RawMalloc() and
Py_DecodeLocale() can be called before _PyRuntime_Initialize().

@item 
bpo-32043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32043}: Add a new "developer mode": new "-X dev" command line option to
enable debug checks at runtime.

@item 
bpo-32023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32023}: SyntaxError is now correctly raised when a generator expression
without parenthesis is used instead of an inheritance list in a class
definition. The duplication of the parentheses can be omitted only on
calls.

@item 
bpo-32012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32012}: SyntaxError is now correctly raised when a generator expression
without parenthesis is passed as an argument, but followed by a trailing
comma. A generator expression always needs to be directly inside a set of
parentheses and cannot have a comma on either side.

@item 
bpo-28180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28180}: A new internal @code{_Py_SetLocaleFromEnv(category)} helper
function has been added in order to improve the consistency of behaviour
across different @code{libc} implementations (e.g. Android doesn't support
setting the locale from the environment by default).

@item 
bpo-31949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31949}: Fixed several issues in printing tracebacks
(PyTraceBack_Print()). Setting sys.tracebacklimit to 0 or less now
suppresses printing tracebacks. Setting sys.tracebacklimit to None now
causes using the default limit. Setting sys.tracebacklimit to an integer
larger than LONG_MAX now means using the limit LONG_MAX rather than the
default limit. Fixed integer overflows in the case of more than @code{2**31}
traceback items on Windows. Fixed output errors handling.

@item 
bpo-30696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30696}: Fix the interactive interpreter looping endlessly when no
memory.

@item 
bpo-20047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20047}: Bytearray methods partition() and rpartition() now accept only
bytes-like objects as separator, as documented.  In particular they now
raise TypeError rather of returning a bogus result when an integer is
passed as a separator.

@item 
bpo-21720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21720}: BytesWarning no longer emitted when the `fromlist' argument of
@code{__import__()} or the @code{__all__} attribute of the module contain bytes
instances.

@item 
bpo-31845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31845}: Environment variables are once more read correctly at
interpreter startup.

@item 
bpo-28936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28936}: Ensure that lexically first syntax error involving a parameter
and @code{global} or @code{nonlocal} is detected first at a given scope. Patch
by Ivan Levkivskyi.

@item 
bpo-31825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31825}: Fixed OverflowError in the 'unicode-escape' codec and in
codecs.escape_decode() when decode an escaped non-ascii byte.

@item 
bpo-31618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31618}: The per-frame tracing logic added in 3.7a1 has been altered so
that @code{frame->f_lineno} is updated before either @code{"line"} or
@code{"opcode"} events are emitted. Previously, opcode events were emitted
first, and therefore would occasionally see stale line numbers on the
frame. The behavior of this feature has changed slightly as a result: when
both @code{f_trace_lines} and @code{f_trace_opcodes} are enabled, line events
now occur first.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Print the full context/cause chain of exceptions on interpreter
exit, even if an exception in the chain is unhashable or compares equal to
later ones. Patch by Zane Bitter.

@item 
bpo-31786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31786}: Fix timeout rounding in the select module to round correctly
negative timeouts between -1.0 and 0.0. The functions now block waiting
for events as expected. Previously, the call was incorrectly non-blocking.
Patch by Pablo Galindo.

@item 
bpo-31781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31781}: Prevent crashes when calling methods of an uninitialized
@code{zipimport.zipimporter} object. Patch by Oren Milman.

@item 
bpo-30399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30399}: Standard repr() of BaseException with a single argument no
longer contains redundant trailing comma.

@item 
bpo-31626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31626}: Fixed a bug in debug memory allocator.  There was a write to
freed memory after shrinking a memory block.

@item 
bpo-30817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30817}: @code{PyErr_PrintEx()} clears now the ignored exception that may
be raised by @code{_PySys_SetObjectId()}, for example when no memory.
@end itemize

@node ライブラリ<171>,ドキュメント<64>,Core and Builtins<167>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id816}@anchor{1e81}
@subsubsection ライブラリ



@itemize -

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Two minor fixes for @code{typing} module: allow shallow copying
instances of generic classes, improve interaction of @code{__init_subclass__}
with generics. Original PRs by Ivan Levkivskyi.

@item 
bpo-32214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32214}: PEP 557, Data Classes. Provides a decorator which adds
boilerplate methods to classes which use type annotations so specify
fields.

@item 
bpo-27240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27240}: The header folding algorithm for the new email policies has
been rewritten, which also fixes bpo-30788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30788}, bpo-31831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31831}, and bpo-32182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32182}.  In
particular, RFC2231 folding is now done correctly.

@item 
bpo-32186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32186}: io.FileIO.readall() and io.FileIO.read() now release the GIL
when getting the file size. Fixed hang of all threads with inaccessible
NFS server. Patch by Nir Soffer.

@item 
bpo-32101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32101}: Add @ref{1e82,,sys.flags.dev_mode} flag

@item 
bpo-32154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32154}: The @code{asyncio.windows_utils.socketpair()} function has been
removed: use directly @ref{df0,,socket.socketpair()} which is available on all
platforms since Python 3.5 (before, it wasn't available on Windows).
@code{asyncio.windows_utils.socketpair()} was just an alias to
@code{socket.socketpair} on Python 3.5 and newer.

@item 
bpo-32089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32089}: warnings: In development (-X dev) and debug mode (pydebug
build), use the "default" action for ResourceWarning, rather than the
"always" action, in the default warnings filters.

@item 
bpo-32107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32107}: @code{uuid.getnode()} now preferentially returns universally
administered MAC addresses if available, over locally administered MAC
addresses.  This makes a better guarantee for global uniqueness of UUIDs
returned from @code{uuid.uuid1()}.  If only locally administered MAC
addresses are available, the first such one found is returned.

@item 
bpo-23033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23033}: Wildcard is now supported in hostname when it is one and only
character in the left most segment of hostname in second argument of
@code{ssl.match_hostname()}.  Patch by Mandeep Singh.

@item 
bpo-12239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12239}: Make @code{msilib.SummaryInformation.GetProperty()} return
@code{None} when the value of property is @code{VT_EMPTY}.  Initial patch by
Mark Mc Mahon.

@item 
bpo-28334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28334}: Use @ref{c09,,os.path.expanduser()} to find the @code{~/.netrc} file in
@ref{1c79,,netrc.netrc}.  If it does not exist, @ref{264,,FileNotFoundError} is
raised.  Patch by Dimitri Merejkowsky.

@item 
bpo-32121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32121}: Made @code{tracemalloc.Traceback} behave more like the traceback
module, sorting the frames from oldest to most recent.
@code{Traceback.format()} now accepts negative `limit', truncating the result
to the @code{abs(limit)} oldest frames. To get the old behaviour, one can use
the new `most_recent_first' argument to @code{Traceback.format()}. (Patch by
Jesse Bakker.)

@item 
bpo-31325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31325}: Fix wrong usage of @ref{4e0,,collections.namedtuple()} in the
@ref{1e83,,RobotFileParser.parse()}
method. Initial patch by Robin Wellner.

@item 
bpo-12382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12382}: @code{msilib.OpenDatabase()} now raises a better exception
message when it couldn't open or create an MSI file.  Initial patch by
William Tisäter.

@item 
bpo-19610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19610}: @code{setup()} now warns about invalid types for some fields. The
@code{distutils.dist.Distribution} class now warns when @code{classifiers},
@code{keywords} and @code{platforms} fields are not specified as a list or a
string.

@item 
bpo-32071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32071}: Added the @code{-k} command-line option to @code{python -m unittest}
to run only tests that match the given pattern(s).

@item 
bpo-10049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10049}: Added `nullcontext' no-op context manager to contextlib. This
provides a simpler and faster alternative to ExitStack() when handling
optional context managers.

@item 
bpo-28684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28684}: The new test.support.skip_unless_bind_unix_socket() decorator
is used here to skip asyncio tests that fail because the platform lacks a
functional bind() function for unix domain sockets (as it is the case for
non root users on the recent Android versions that run now SELinux in
enforcing mode).

@item 
bpo-32110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32110}: @code{codecs.StreamReader.read(n)} now returns not more than `n'
characters/bytes for non-negative `n'. This makes it compatible with
@code{read()} methods of other file-like objects.

@item 
bpo-27535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27535}: The warnings module doesn't leak memory anymore in the hidden
warnings registry for the "ignore" action of warnings filters.
warn_explicit() function doesn't add the warning key to the registry
anymore for the "ignore" action.

@item 
bpo-32088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32088}: warnings:  When Python is build is debug mode (@code{Py_DEBUG}),
@ref{1a3,,DeprecationWarning}, @ref{ac5,,PendingDeprecationWarning} and
@ref{71e,,ImportWarning} warnings are now displayed by default.

@item 
bpo-1647489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1647489}: Fixed searching regular expression patterns that could match
an empty string. Non-empty string can now be correctly found after
matching an empty string.

@item 
bpo-25054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25054}: Added support of splitting on a pattern that could match an
empty string.

@item 
bpo-32072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32072}: Fixed issues with binary plists: Fixed saving bytearrays.
Identical objects will be saved only once. Equal references will be load
as identical objects. Added support for saving and loading recursive data
structures.

@item 
bpo-32069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32069}: Drop legacy SSL transport from asyncio, ssl.MemoryBIO is always
used anyway.

@item 
bpo-32066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32066}: asyncio: Support pathlib.Path in create_unix_connection; sock
arg should be optional

@item 
bpo-32046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32046}: Updates 2to3 to convert from operator.isCallable(obj) to
callable(obj). Patch by Donghee Na.

@item 
bpo-32018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32018}: inspect.signature should follow 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/}, if the parameter has
an annotation and a default value. Patch by Donghee Na.

@item 
bpo-32025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32025}: Add time.thread_time() and time.thread_time_ns()

@item 
bpo-32037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32037}: Integers that fit in a signed 32-bit integer will be now
pickled with protocol 0 using the INT opcode.  This will decrease the size
of a pickle, speed up pickling and unpickling, and make these integers be
unpickled as int instances in Python 2.

@item 
bpo-32034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32034}: Make asyncio.IncompleteReadError and LimitOverrunError
pickleable.

@item 
bpo-32015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32015}: Fixed the looping of asyncio in the case of reconnection the
socket during waiting async read/write from/to the socket.

@item 
bpo-32011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32011}: Restored support of loading marshal files with the TYPE_INT64
code. These files can be produced in Python 2.7.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Enhance add_reader/writer check that socket is not used by some
transport. Before, only cases when add_reader/writer were called with an
int FD were supported.  Now the check is implemented correctly for all
file-like objects.

@item 
bpo-31976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31976}: Fix race condition when flushing a file is slow, which can
cause a segfault if closing the file from another thread.

@item 
bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985}: Formally deprecated aifc.openfp, sunau.openfp, and wave.openfp.
Since change 7bc817d5ba917528e8bd07ec461c635291e7b06a in 1993, openfp in
each of the three modules had been pointing to that module's open function
as a matter of backwards compatibility, though it had been both untested
and undocumented.

@item 
bpo-21862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21862}: cProfile command line now accepts @code{-m module_name} as an
alternative to script path. Patch by Sanyam Khurana.

@item 
bpo-31970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31970}: Reduce performance overhead of asyncio debug mode.

@item 
bpo-31843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31843}: `database' argument of sqlite3.connect() now accepts a
@ref{5a1,,path-like object}, instead of just a string.

@item 
bpo-31945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31945}: Add Configurable `blocksize' to @code{HTTPConnection} and
@code{HTTPSConnection} for improved upload throughput.  Patch by Nir Soffer.

@item 
bpo-31943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31943}: Add a @code{cancelled()} method to @ref{1e84,,asyncio.Handle}.  Patch
by Marat Sharafutdinov.

@item 
bpo-9678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9678}: Fixed determining the MAC address in the uuid module: Using
ifconfig on NetBSD and OpenBSD. Using arp on Linux, FreeBSD, NetBSD and
OpenBSD. Based on patch by Takayuki Shimizukawa.

@item 
bpo-30057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30057}: Fix potential missed signal in signal.signal().

@item 
bpo-31933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31933}: Fix Blake2 params leaf_size and node_offset on big endian
platforms. Patch by Jack O'Connor.

@item 
bpo-21423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21423}: Add an initializer argument to @{Process,Thread@}PoolExecutor

@item 
bpo-31927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31927}: Fixed compilation of the socket module on NetBSD 8.  Fixed
assertion failure or reading arbitrary data when parse a AF_BLUETOOTH
address on NetBSD and DragonFly BSD.

@item 
bpo-27666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27666}: Fixed stack corruption in curses.box() and curses.ungetmouse()
when the size of types chtype or mmask_t is less than the size of C long.
curses.box() now accepts characters as arguments.  Based on patch by Steve
Fink.

@item 
bpo-31917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31917}: Add 3 new clock identifiers: @ref{d87,,time.CLOCK_BOOTTIME},
@ref{d88,,time.CLOCK_PROF} and @ref{d89,,time.CLOCK_UPTIME}.

@item 
bpo-31897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31897}: plistlib now catches more errors when read binary plists and
raises InvalidFileException instead of unexpected exceptions.

@item 
bpo-25720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25720}: Fix the method for checking pad state of curses WINDOW. Patch
by Masayuki Yamamoto.

@item 
bpo-31893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31893}: Fixed the layout of the kqueue_event structure on OpenBSD and
NetBSD. Fixed the comparison of the kqueue_event objects.

@item 
bpo-31891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31891}: Fixed building the curses module on NetBSD.

@item 
bpo-31884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31884}: added required constants to subprocess module for setting
priority on windows

@item 
bpo-28281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28281}: Remove year (1-9999) limits on the Calendar.weekday() function.
Patch by Mark Gollahon.

@item 
bpo-31702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31702}: crypt.mksalt() now allows to specify the number of rounds for
SHA-256 and SHA-512 hashing.

@item 
bpo-30639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30639}: @ref{1e85,,inspect.getfile()} no longer computes the repr of unknown
objects to display in an error message, to protect against badly behaved
custom reprs.

@item 
bpo-30768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30768}: Fix the pthread+semaphore implementation of
PyThread_acquire_lock_timed() when called with timeout > 0 and
intr_flag=0: recompute the timeout if sem_timedwait() is interrupted by a
signal (EINTR). See also the 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/}.

@item 
bpo-31854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31854}: Add @code{mmap.ACCESS_DEFAULT} constant.

@item 
bpo-31834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31834}: Use optimized code for BLAKE2 only with SSSE3+. The pure SSE2
implementation is slower than the pure C reference implementation.

@item 
bpo-28292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28292}: Calendar.itermonthdates() will now consistently raise an
exception when a date falls outside of the 0001-01-01 through 9999-12-31
range.  To support applications that cannot tolerate such exceptions, the
new methods itermonthdays3() and itermonthdays4() are added.  The new
methods return tuples and are not restricted by the range supported by
datetime.date.

@item 
bpo-28564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28564}: The shutil.rmtree() function has been sped up to 20--40%. This
was done using the os.scandir() function.

@item 
bpo-28416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28416}: Instances of pickle.Pickler subclass with the persistent_id()
method and pickle.Unpickler subclass with the persistent_load() method no
longer create reference cycles.

@item 
bpo-31653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31653}: Don't release the GIL if we can acquire a multiprocessing
semaphore immediately.

@item 
bpo-28326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28326}: Fix multiprocessing.Process when stdout and/or stderr is closed
or None.

@item 
bpo-20825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20825}: Add @code{subnet_of} and @code{superset_of} containment tests to
@ref{50f,,ipaddress.IPv6Network} and @ref{50e,,ipaddress.IPv4Network}. Patch
by Michel Albert and Cheryl Sabella.

@item 
bpo-31827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31827}: Remove the os.stat_float_times() function. It was introduced in
Python 2.3 for backward compatibility with Python 2.2, and was deprecated
since Python 3.1.

@item 
bpo-31756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31756}: Add a @code{subprocess.Popen(text=False)} keyword argument to
@code{subprocess} functions to be more explicit about when the library should
attempt to decode outputs into text. Patch by Andrew Clegg.

@item 
bpo-31819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31819}: Add AbstractEventLoop.sock_recv_into().

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: If nested log adapters are used, the inner @code{process()}
methods are no longer omitted.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: The @code{manager} property on LoggerAdapter objects is now
properly settable.

@item 
bpo-31806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31806}: Fix timeout rounding in time.sleep(), threading.Lock.acquire()
and socket.socket.settimeout() to round correctly negative timeouts
between -1.0 and 0.0. The functions now block waiting for events as
expected. Previously, the call was incorrectly non-blocking. Patch by
Pablo Galindo.

@item 
bpo-31803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31803}: time.clock() and time.get_clock_info('clock') now emit a
DeprecationWarning warning.

@item 
bpo-31800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31800}: Extended support for parsing UTC offsets. strptime '%z' can now
parse the output generated by datetime.isoformat, including seconds and
microseconds.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: traceback: Fix a TypeError that occurred during printing of
exception tracebacks when either the current exception or an exception in
its context/cause chain is unhashable. Patch by Zane Bitter.

@item 
bpo-30541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30541}: Add new function to seal a mock and prevent the automatically
creation of child mocks. Patch by Mario Corchero.

@item 
bpo-31784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31784}: Implement the 
@geindex Python Enhancement Proposals; PEP 564
PEP 564@footnote{https://peps.python.org/pep-0564/}, add new 6 new functions with
nanosecond resolution to the @ref{f4,,time} module:
@ref{cdb,,clock_gettime_ns()}, @ref{cdc,,clock_settime_ns()},
@ref{cdd,,monotonic_ns()}, @ref{cde,,perf_counter_ns()},
@ref{cdf,,process_time_ns()}, @ref{ce0,,time_ns()}.

@item 
bpo-30143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30143}: 2to3 now generates a code that uses abstract collection classes
from collections.abc rather than collections.

@item 
bpo-31770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31770}: Prevent a crash when calling the @code{__init__()} method of a
@code{sqlite3.Cursor} object more than once. Patch by Oren Milman.

@item 
bpo-31764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31764}: Prevent a crash in @code{sqlite3.Cursor.close()} in case the
@code{Cursor} object is uninitialized. Patch by Oren Milman.

@item 
bpo-31752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31752}: Fix possible crash in timedelta constructor called with custom
integers.

@item 
bpo-31620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31620}: an empty asyncio.Queue now doesn't leak memory when queue.get
pollers timeout

@item 
bpo-31690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31690}: Allow the flags re.ASCII, re.LOCALE, and re.UNICODE to be used
as group flags for regular expressions.

@item 
bpo-30349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30349}: FutureWarning is now emitted if a regular expression contains
character set constructs that will change semantically in the future
(nested sets and set operations).

@item 
bpo-31664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31664}: Added support for the Blowfish hashing in the crypt module.

@item 
bpo-31632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31632}: Fix method set_protocol() of class _SSLProtocolTransport in
asyncio module. This method was previously modifying a wrong reference to
the protocol.

@item 
bpo-15037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15037}: Added a workaround for getkey() in curses for ncurses 5.7 and
earlier.

@item 
bpo-31307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31307}: Allow use of bytes objects for arguments to
@ref{1681,,configparser.ConfigParser.read()}. Patch by Vincent Michel.

@item 
bpo-31334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31334}: Fix @code{poll.poll([timeout])} in the @code{select} module for
arbitrary negative timeouts on all OSes where it can only be a
non-negative integer or -1. Patch by Riccardo Coccioli.

@item 
bpo-31310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31310}: multiprocessing's semaphore tracker should be launched again if
crashed.

@item 
bpo-31308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31308}: Make multiprocessing's forkserver process immune to Ctrl-C and
other user interruptions. If it crashes, restart it when necessary.

@item 
bpo-31245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31245}: Added support for AF_UNIX socket in asyncio
@code{create_datagram_endpoint}.

@item 
bpo-30553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30553}: Add HTTP/2 status code 421 (Misdirected Request) to
@ref{afc,,http.HTTPStatus}. Patch by Vitor Pereira.
@end itemize

@node ドキュメント<64>,テスト<61>,ライブラリ<171>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id817}@anchor{1e86}
@subsubsection ドキュメント



@itemize -

@item 
bpo-32105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32105}: Added asyncio.BaseEventLoop.connect_accepted_socket
versionadded marker.
@end itemize

@node テスト<61>,ビルド<68>,ドキュメント<64>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id818}@anchor{1e87}
@subsubsection テスト



@itemize -

@item 
bpo-31380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31380}: Skip test_httpservers test_undecodable_file on macOS: fails on
APFS.

@item 
bpo-31705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31705}: Skip test_socket.test_sha256() on Linux kernel older than 4.5.
The test fails with ENOKEY on kernel 3.10 (on ppc64le). A fix was merged
into the kernel 4.5.

@item 
bpo-32138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32138}: Skip on Android test_faulthandler tests that raise SIGSEGV and
remove the test.support.requires_android_level decorator.

@item 
bpo-32136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32136}: The runtime embedding tests have been split out from
@code{Lib/test/test_capi.py} into a new @code{Lib/test/test_embed.py} file.

@item 
bpo-28668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28668}: test.support.requires_multiprocessing_queue is removed. Skip
tests with test.support.import_module('multiprocessing.synchronize')
instead when the semaphore implementation is broken or missing.

@item 
bpo-32126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32126}: Skip test_get_event_loop_new_process in
test.test_asyncio.test_events when sem_open() is not functional.

@item 
bpo-31174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31174}: Fix test_tools.test_unparse: DirectoryTestCase now stores the
names sample to always test the same files. It prevents false alarms when
hunting reference leaks.
@end itemize

@node ビルド<68>,Windows<62>,テスト<61>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id819}@anchor{1e88}
@subsubsection ビルド



@itemize -

@item 
bpo-28538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28538}: Revert the previous changes, the if_nameindex structure is
defined by Unified Headers.

@item 
bpo-28762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28762}: Revert the last commit, the F_LOCK macro is defined by Android
Unified Headers.

@item 
bpo-29040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29040}: Support building Android with Unified Headers. The first NDK
release to support Unified Headers is android-ndk-r14.

@item 
bpo-32059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32059}: @code{detect_modules()} in @code{setup.py} now also searches the
sysroot paths when cross-compiling.

@item 
bpo-31957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31957}: Fixes Windows SDK version detection when building for Windows.

@item 
bpo-31609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31609}: Fixes quotes in PCbuild/clean.bat

@item 
bpo-31934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31934}: Abort the build when building out of a not clean source tree.

@item 
bpo-31926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31926}: Fixed Argument Clinic sometimes causing compilation errors when
there was more than one function and/or method in a .c file with the same
name.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update Windows builds to use SQLite 3.21.0.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update OS X installer to use SQLite 3.21.0.

@item 
bpo-28643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28643}: Record profile-opt build progress with stamp files.

@item 
bpo-31866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31866}: Finish removing support for AtheOS.
@end itemize

@node Windows<62>,macOS<48>,ビルド<68>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id820}@anchor{1e89}
@subsubsection Windows



@itemize -

@item 
bpo-1102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1102}: Return @code{None} when @code{View.Fetch()} returns
@code{ERROR_NO_MORE_ITEMS} instead of raising @code{MSIError}. Initial patch by
Anthony Tuininga.

@item 
bpo-31944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31944}: Fixes Modify button in Apps and Features dialog.

@item 
bpo-20486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20486}: Implement the @code{Database.Close()} method to help closing MSI
database objects.

@item 
bpo-31857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31857}: Make the behavior of USE_STACKCHECK deterministic in a
multi-threaded environment.
@end itemize

@node macOS<48>,IDLE<43>,Windows<62>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id821}@anchor{1e8a}
@subsubsection macOS



@itemize -

@item 
bpo-31392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31392}: Update macOS installer to use OpenSSL 1.0.2m
@end itemize

@node IDLE<43>,Tools/Demos<42>,macOS<48>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id822}@anchor{1e8b}
@subsubsection IDLE



@itemize -

@item 
bpo-32207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32207}: Improve tk event exception tracebacks in IDLE. When tk event
handling is driven by IDLE's run loop, a confusing and distracting
queue.EMPTY traceback context is no longer added to tk event exception
tracebacks.  The traceback is now the same as when event handling is
driven by user code.  Patch based on a suggestion by Serhiy Storchaka.

@item 
bpo-32164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32164}: Delete unused file idlelib/tabbedpages.py. Use of TabbedPageSet
in configdialog was replaced by ttk.Notebook.

@item 
bpo-32100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32100}: IDLE: Fix old and new bugs in pathbrowser; improve tests. Patch
mostly by Cheryl Sabella.

@item 
bpo-31858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31858}: IDLE -- Restrict shell prompt manipulation to the shell. Editor
and output windows only see an empty last prompt line.  This simplifies
the code and fixes a minor bug when newline is inserted. Sys.ps1, if
present, is read on Shell start-up, but is not set or changed.

@item 
bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860}: The font sample in the IDLE configuration dialog is now
editable. Changes persist while IDLE remains open

@item 
bpo-31836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31836}: Test_code_module now passes if run after test_idle, which sets
ps1. The code module uses sys.ps1 if present or sets it to '>>> ' if not.
Test_code_module now properly tests both behaviors.  Ditto for ps2.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Fix a TypeError that caused a shell restart when printing a
traceback that includes an exception that is unhashable. Patch by Zane
Bitter.

@item 
bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802}: Use non-Latin characters in the IDLE's Font settings sample.
Even if one selects a font that defines a limited subset of the unicode
Basic Multilingual Plane, tcl/tk will use other fonts that define a
character. The expanded example give users of non-Latin characters a
better idea of what they might see in IDLE's shell and editors. To make
room for the expanded sample, frames on the Font tab are re-arranged.  The
Font/Tabs help explains a bit about the additions.
@end itemize

@node Tools/Demos<42>,C API<61>,IDLE<43>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id823}@anchor{1e8c}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-32159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32159}: Remove CVS and Subversion tools: remove svneol.py and
treesync.py scripts. CPython migrated from CVS to Subversion, to
Mercurial, and then to Git. CVS and Subversion are no longer used to
develop CPython.

@item 
bpo-30722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30722}: Make redemo work with Python 3.6 and newer versions. Also,
remove the @code{LOCALE} option since it doesn't work with string patterns in
Python 3. Patch by Christoph Sarnowski.
@end itemize

@node C API<61>,,Tools/Demos<42>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id824}@anchor{1e8d}
@subsubsection C API



@itemize -

@item 
bpo-20891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20891}: Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in
a non-Python thread before PyEval_InitThreads(), only call
PyEval_InitThreads() after calling PyThreadState_New() to fix a crash.

@item 
bpo-32125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32125}: The @code{Py_UseClassExceptionsFlag} flag has been removed. It was
deprecated and wasn't used anymore since Python 2.0.

@item 
bpo-25612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25612}: Move the current exception state from the frame object to the
co-routine. This simplifies the interpreter and fixes a couple of obscure
bugs caused by having swap exception state when entering or exiting a
generator.

@item 
bpo-23699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23699}: Add Py_RETURN_RICHCOMPARE macro to reduce boilerplate code in
rich comparison functions.

@item 
bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697}: The @code{PyExc_RecursionErrorInst} singleton is removed and
@code{PyErr_NormalizeException()} does not use it anymore. This singleton is
persistent and its members being never cleared may cause a segfault during
finalization of the interpreter. See also bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898}.
@end itemize

@node Python 3 7 0 alpha 2,Python 3 7 0 alpha 1,Python 3 7 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-7-0-alpha-2}@anchor{1e8e}
@subsection Python 3.7.0 alpha 2


`Release date: 2017-10-16'

@menu
* Core and Builtins: Core and Builtins<168>. 
* ライブラリ: ライブラリ<172>. 
* ドキュメント: ドキュメント<65>. 
* ビルド: ビルド<69>. 
* IDLE: IDLE<44>. 
* C API: C API<62>. 

@end menu

@node Core and Builtins<168>,ライブラリ<172>,,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id825}@anchor{1e8f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31558}: @code{gc.freeze()} is a new API that allows for moving all objects
currently tracked by the garbage collector to a permanent generation,
effectively removing them from future collection events. This can be used
to protect those objects from having their PyGC_Head mutated. In effect,
this enables great copy-on-write stability at fork().

@item 
bpo-31642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31642}: Restored blocking "from package import module" by setting
sys.modules["package.module"] to None.

@item 
bpo-31708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31708}: Allow use of asynchronous generator expressions in synchronous
functions.

@item 
bpo-31709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31709}: Drop support of asynchronous __aiter__.

@item 
bpo-30404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30404}: The -u option now makes the stdout and stderr streams
unbuffered rather than line-buffered.

@item 
bpo-31619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31619}: Fixed a ValueError when convert a string with large number of
underscores to integer with binary base.

@item 
bpo-31602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31602}: Fix an assertion failure in @code{zipimporter.get_source()} in
case of a bad @code{zlib.decompress()}. Patch by Oren Milman.

@item 
bpo-31592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31592}: Fixed an assertion failure in Python parser in case of a bad
@code{unicodedata.normalize()}. Patch by Oren Milman.

@item 
bpo-31588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31588}: Raise a @code{TypeError} with a helpful error message when class
creation fails due to a metaclass with a bad @code{__prepare__()} method.
Patch by Oren Milman.

@item 
bpo-31574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31574}: Importlib was instrumented with two dtrace probes to profile
import timing.

@item 
bpo-31566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31566}: Fix an assertion failure in @code{_warnings.warn()} in case of a
bad @code{__name__} global. Patch by Oren Milman.

@item 
bpo-31506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31506}: Improved the error message logic for @code{object.__new__} and
@code{object.__init__}.

@item 
bpo-31505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31505}: Fix an assertion failure in @code{json}, in case
@code{_json.make_encoder()} received a bad @code{encoder()} argument. Patch by
Oren Milman.

@item 
bpo-31492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31492}: Fix assertion failures in case of failing to import from a
module with a bad @code{__name__} attribute, and in case of failing to access
an attribute of such a module. Patch by Oren Milman.

@item 
bpo-31478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31478}: Fix an assertion failure in @code{_random.Random.seed()} in case
the argument has a bad @code{__abs__()} method. Patch by Oren Milman.

@item 
bpo-31336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31336}: Speed up class creation by 10-20% by reducing the overhead in
the necessary special method lookups.  Patch by Stefan Behnel.

@item 
bpo-31415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31415}: Add @code{-X importtime} option to show how long each import
takes. It can be used to optimize application's startup time.  Support the
@geindex PYTHONPROFILEIMPORTTIME
@geindex 環境変数; PYTHONPROFILEIMPORTTIME
@ref{ced,,PYTHONPROFILEIMPORTTIME} as an equivalent way to enable this.

@item 
bpo-31410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31410}: Optimized calling wrapper and classmethod descriptors.

@item 
bpo-31353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31353}: 
@geindex Python Enhancement Proposals; PEP 553
PEP 553@footnote{https://peps.python.org/pep-0553/} - Add a new built-in called @code{breakpoint()} which
calls @code{sys.breakpointhook()}.  By default this imports @code{pdb} and calls
@code{pdb.set_trace()}, but users may override @code{sys.breakpointhook()} to
call whatever debugger they want.  The original value of the hook is saved
in @code{sys.__breakpointhook__}.

@item 
bpo-17852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17852}: Maintain a list of open buffered files, flush them before
exiting the interpreter.  Based on a patch from Armin Rigo.

@item 
bpo-31315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31315}: Fix an assertion failure in imp.create_dynamic(), when
spec.name is not a string. Patch by Oren Milman.

@item 
bpo-31311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31311}: Fix a crash in the @code{__setstate__()} method of
@code{ctypes._CData}, in case of a bad @code{__dict__}. Patch by Oren Milman.

@item 
bpo-31293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31293}: Fix crashes in true division and multiplication of a timedelta
object by a float with a bad as_integer_ratio() method. Patch by Oren
Milman.

@item 
bpo-31285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31285}: Fix an assertion failure in @code{warnings.warn_explicit}, when
the return value of the received loader's @code{get_source()} has a bad
@code{splitlines()} method. Patch by Oren Milman.

@item 
bpo-30406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30406}: Make @code{async} and @code{await} proper keywords, as specified in
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/}.
@end itemize

@node ライブラリ<172>,ドキュメント<65>,Core and Builtins<168>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id826}@anchor{1e90}
@subsubsection ライブラリ



@itemize -

@item 
bpo-30058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30058}: Fixed buffer overflow in select.kqueue.control().

@item 
bpo-31672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31672}: @code{idpattern} in @code{string.Template} matched some non-ASCII
characters. Now it uses @code{-i} regular expression local flag to avoid
non-ASCII characters.

@item 
bpo-31701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31701}: On Windows, faulthandler.enable() now ignores MSC and COM
exceptions.

@item 
bpo-31728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31728}: Prevent crashes in @code{_elementtree} due to unsafe cleanup of
@code{Element.text} and @code{Element.tail}. Patch by Oren Milman.

@item 
bpo-31671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31671}: Now @code{re.compile()} converts passed RegexFlag to normal int
object before compiling. bm_regex_compile benchmark shows 14% performance
improvements.

@item 
bpo-30397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30397}: The types of compiled regular objects and match objects are now
exposed as @code{re.Pattern} and @code{re.Match}.  This adds information in
pydoc output for the @code{re} module.

@item 
bpo-31675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31675}: Fixed memory leaks in Tkinter's methods splitlist() and split()
when pass a string larger than 2 GiB.

@item 
bpo-31673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31673}: Fixed typo in the name of Tkinter's method adderrorinfo().

@item 
bpo-31648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31648}: Improvements to path predicates in ElementTree: Allow
whitespace around predicate parts, i.e. "[a = 'text']" instead of
requiring the less readable "[a='text']". Add support for text comparison
of the current node, like "[.='text']". Patch by Stefan Behnel.

@item 
bpo-30806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30806}: Fix the string representation of a netrc object.

@item 
bpo-31638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31638}: Add optional argument @code{compressed} to
@code{zipapp.create_archive}, and add option @code{--compress} to the command
line interface of @code{zipapp}.

@item 
bpo-25351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25351}: Avoid venv activate failures with undefined variables

@item 
bpo-20519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20519}: Avoid ctypes use (if possible) and improve import time for
uuid.

@item 
bpo-28293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28293}: The regular expression cache is no longer completely dumped
when it is full.

@item 
bpo-31596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31596}: Added pthread_getcpuclockid() to the time module

@item 
bpo-27494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27494}: Make 2to3 accept a trailing comma in generator expressions. For
example, @code{set(x for x in [],)} is now allowed.

@item 
bpo-30347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30347}: Stop crashes when concurrently iterate over itertools.groupby()
iterators.

@item 
bpo-30346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30346}: An iterator produced by itertools.groupby() iterator now
becomes exhausted after advancing the groupby iterator.

@item 
bpo-31556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31556}: Cancel asyncio.wait_for future faster if timeout <= 0

@item 
bpo-31540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31540}: Allow passing a context object in
@ref{1d6,,concurrent.futures.ProcessPoolExecutor} constructor. Also, free
job resources in @ref{1d6,,concurrent.futures.ProcessPoolExecutor} earlier
to improve memory usage when a worker waits for new jobs.

@item 
bpo-31516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31516}: @code{threading.current_thread()} should not return a dummy thread
at shutdown.

@item 
bpo-31525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31525}: In the sqlite module, require the sqlite3_prepare_v2 API. Thus,
the sqlite module now requires sqlite version at least 3.3.9.

@item 
bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510}: argparse subparsers are now required by default.  This matches
behaviour in Python 2. For optional subparsers, use the new parameter
@code{add_subparsers(required=False)}. Patch by Anthony Sottile. (As of
3.7.0rc1, the default was changed to not required as had been the case
since Python 3.3.)

@item 
bpo-27541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27541}: Reprs of subclasses of some collection and iterator classes
(@code{bytearray}, @code{array.array}, @code{collections.deque},
@code{collections.defaultdict}, @code{itertools.count}, @code{itertools.repeat})
now contain actual type name instead of hardcoded names of the base class.

@item 
bpo-31351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31351}: python -m ensurepip now exits with non-zero exit code if pip
bootstrapping has failed.

@item 
bpo-31389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31389}: @code{pdb.set_trace()} now takes an optional keyword-only argument
@code{header}. If given, this is printed to the console just before debugging
begins.
@end itemize

@node ドキュメント<65>,ビルド<69>,ライブラリ<172>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id827}@anchor{1e91}
@subsubsection ドキュメント



@itemize -

@item 
bpo-31537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31537}: Fix incorrect usage of @code{get_history_length} in readline
documentation example code. Patch by Brad Smith.

@item 
bpo-30085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30085}: The operator functions without double underscores are preferred
for clarity. The one with underscores are only kept for
back-compatibility.
@end itemize

@node ビルド<69>,IDLE<44>,ドキュメント<65>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id828}@anchor{1e92}
@subsubsection ビルド



@itemize -

@item 
bpo-31696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31696}: Improve compiler version information in @ref{49c,,sys.version}
when Python is built with Clang.

@item 
bpo-31625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31625}: Stop using ranlib on static libraries. Instead, we assume ar
supports the 's' flag.

@item 
bpo-31624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31624}: Remove support for BSD/OS.

@item 
bpo-22140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22140}: Prevent double substitution of prefix in python-config.sh.

@item 
bpo-31569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31569}: Correct PCBuild/ case to PCbuild/ in build scripts and
documentation.

@item 
bpo-31536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31536}: Avoid wholesale rebuild after @code{make regen-all} if nothing
changed.
@end itemize

@node IDLE<44>,C API<62>,ビルド<69>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id829}@anchor{1e93}
@subsubsection IDLE



@itemize -

@item 
bpo-31460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31460}: Simplify the API of IDLE's Module Browser. Passing a widget
instead of an flist with a root widget opens the option of creating a
browser frame that is only part of a window.  Passing a full file name
instead of pieces assumed to come from a .py file opens the possibility of
browsing python files that do not end in .py.

@item 
bpo-31649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31649}: IDLE - Make _htest, _utest parameters keyword only.

@item 
bpo-31559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31559}: Remove test order dependence in idle_test.test_browser.

@item 
bpo-31459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31459}: Rename IDLE's module browser from Class Browser to Module
Browser. The original module-level class and method browser became a
module browser, with the addition of module-level functions, years ago.
Nested classes and functions were added yesterday.  For
back-compatibility, the virtual event <<open-class-browser>>, which
appears on the Keys tab of the Settings dialog, is not changed. Patch by
Cheryl Sabella.

@item 
bpo-31500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31500}: Default fonts now are scaled on HiDPI displays.

@item 
bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262}: IDLE module browser now shows nested classes and functions.
Original patches for code and tests by Guilherme Polo and Cheryl Sabella,
respectively.
@end itemize

@node C API<62>,,IDLE<44>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id830}@anchor{1e94}
@subsubsection C API



@itemize -

@item 
bpo-28280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28280}: Make @code{PyMapping_Keys()}, @code{PyMapping_Values()} and
@code{PyMapping_Items()} always return a @code{list} (rather than a @code{list} or
a @code{tuple}). Patch by Oren Milman.

@item 
bpo-31532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31532}: Fix memory corruption due to allocator mix in getpath.c between
Py_GetPath() and Py_SetPath()

@item 
bpo-25658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25658}: Implement 
@geindex Python Enhancement Proposals; PEP 539
PEP 539@footnote{https://peps.python.org/pep-0539/} for Thread Specific Storage (TSS) API: it
is a new Thread Local Storage (TLS) API to CPython which would supersede
use of the existing TLS API within the CPython interpreter, while
deprecating the existing API. PEP written by Erik M. Bray, patch by
Masayuki Yamamoto.
@end itemize

@node Python 3 7 0 alpha 1,Python 3 6 6 final,Python 3 7 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-7-0-alpha-1}@anchor{1e95}
@subsection Python 3.7.0 alpha 1


`Release date: 2017-09-19'

@menu
* セキュリティ: セキュリティ<49>. 
* Core and Builtins: Core and Builtins<169>. 
* ライブラリ: ライブラリ<173>. 
* ドキュメント: ドキュメント<66>. 
* テスト: テスト<62>. 
* ビルド: ビルド<70>. 
* Windows: Windows<63>. 
* IDLE: IDLE<45>. 
* Tools/Demos: Tools/Demos<43>. 
* C API: C API<63>. 

@end menu

@node セキュリティ<49>,Core and Builtins<169>,,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id831}@anchor{1e96}
@subsubsection セキュリティ



@itemize -

@item 
bpo-29781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29781}: SSLObject.version() now correctly returns None when handshake
over BIO has not been performed yet.

@item 
bpo-29505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29505}: Add fuzz tests for float(str), int(str), unicode(str); for
oss-fuzz.

@item 
bpo-30947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30947}: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to
get security fixes.

@item 
bpo-30730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30730}: Prevent environment variables injection in subprocess on
Windows.  Prevent passing other environment variables and command
arguments.

@item 
bpo-30694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30694}: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple
security vulnerabilities including: 
@geindex Common Vulnerabilities and Exposures; CVE 2017-9233
CVE 2017-9233@footnote{https://www.cve.org/CVERecord?id=CVE-2017-9233} (External entity
infinite loop DoS), 
@geindex Common Vulnerabilities and Exposures; CVE 2016-9063
CVE 2016-9063@footnote{https://www.cve.org/CVERecord?id=CVE-2016-9063} (Integer overflow, re-fix),
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718} (Fix regression bugs from 2.2.0's fix to
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718}) and 
@geindex Common Vulnerabilities and Exposures; CVE 2012-0876
CVE 2012-0876@footnote{https://www.cve.org/CVERecord?id=CVE-2012-0876} (Counter hash flooding with
SipHash). Note: the 
@geindex Common Vulnerabilities and Exposures; CVE 2016-5300
CVE 2016-5300@footnote{https://www.cve.org/CVERecord?id=CVE-2016-5300} (Use os-specific entropy sources like
getrandom) doesn't impact Python, since Python already gets entropy from
the OS to set the expat secret using @code{XML_SetHashSalt()}.

@item 
bpo-30500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30500}: Fix urllib.parse.splithost() to correctly parse fragments. For
example, @code{splithost('//127.0.0.1#@@evil.com/')} now correctly returns the
@code{127.0.0.1} host, instead of treating @code{@@evil.com} as the host in an
authentication (@code{login@@host}).

@item 
bpo-29591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29591}: Update expat copy from 2.1.1 to 2.2.0 to get fixes of
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718} and 
@geindex Common Vulnerabilities and Exposures; CVE 2016-4472
CVE 2016-4472@footnote{https://www.cve.org/CVERecord?id=CVE-2016-4472}. See
@indicateurl{https://sourceforge.net/p/expat/bugs/537/} for more information.
@end itemize

@node Core and Builtins<169>,ライブラリ<173>,セキュリティ<49>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id832}@anchor{1e97}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31490}: Fix an assertion failure in @code{ctypes} class definition, in
case the class has an attribute whose name is specified in @code{_anonymous_}
but not in @code{_fields_}. Patch by Oren Milman.

@item 
bpo-31471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31471}: Fix an assertion failure in @code{subprocess.Popen()} on Windows,
in case the env argument has a bad @code{keys()} method. Patch by Oren
Milman.

@item 
bpo-31418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31418}: Fix an assertion failure in @code{PyErr_WriteUnraisable()} in case
of an exception with a bad @code{__module__} attribute. Patch by Oren Milman.

@item 
bpo-31416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31416}: Fix assertion failures in case of a bad warnings.filters or
warnings.defaultaction. Patch by Oren Milman.

@item 
bpo-28411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28411}: Change direct usage of PyInterpreterState.modules to
PyImport_GetModuleDict(). Also introduce more uniformity in other code
that deals with sys.modules. This helps reduce complications when working
on sys.modules.

@item 
bpo-28411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28411}: Switch to the abstract API when dealing with
@code{PyInterpreterState.modules}. This allows later support for all dict
subclasses and other Mapping implementations.  Also add a
@code{PyImport_GetModule()} function to reduce a bunch of duplicated code.

@item 
bpo-31411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31411}: Raise a TypeError instead of SystemError in case
warnings.onceregistry is not a dictionary. Patch by Oren Milman.

@item 
bpo-31344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31344}: For finer control of tracing behaviour when testing the
interpreter, two new frame attributes have been added to control the
emission of particular trace events: @code{f_trace_lines} (@code{True} by
default) to turn off per-line trace events; and @code{f_trace_opcodes}
(@code{False} by default) to turn on per-opcode trace events.

@item 
bpo-31373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31373}: Fix several possible instances of undefined behavior due to
floating-point demotions.

@item 
bpo-30465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30465}: Location information (@code{lineno} and @code{col_offset}) in
f-strings is now (mostly) correct.  This fixes tools like flake8 from
showing warnings on the wrong line (typically the first line of the file).

@item 
bpo-30860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30860}: Consolidate CPython's global runtime state under a single
struct.  This improves discoverability of the runtime state.

@item 
bpo-31347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31347}: Fix possible undefined behavior in _PyObject_FastCall_Prepend.

@item 
bpo-31343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31343}: Include sys/sysmacros.h for major(), minor(), and makedev().
GNU C library plans to remove the functions from sys/types.h.

@item 
bpo-31291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31291}: Fix an assertion failure in @code{zipimport.zipimporter.get_data}
on Windows, when the return value of @code{pathname.replace('/','\\')} isn't
a string. Patch by Oren Milman.

@item 
bpo-31271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31271}: Fix an assertion failure in the @code{write()} method of
@code{io.TextIOWrapper}, when the encoder doesn't return a bytes object.
Patch by Oren Milman.

@item 
bpo-31243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31243}: Fix a crash in some methods of @code{io.TextIOWrapper}, when the
decoder's state is invalid. Patch by Oren Milman.

@item 
bpo-30721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30721}: @code{print} now shows correct usage hint for using Python 2
redirection syntax.  Patch by Sanyam Khurana.

@item 
bpo-31070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31070}: Fix a race condition in importlib _get_module_lock().

@item 
bpo-30747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30747}: Add a non-dummy implementation of _Py_atomic_store and
_Py_atomic_load on MSVC.

@item 
bpo-31095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31095}: Fix potential crash during GC caused by @code{tp_dealloc} which
doesn't call @code{PyObject_GC_UnTrack()}.

@item 
bpo-31071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31071}: Avoid masking original TypeError in call with * unpacking when
other arguments are passed.

@item 
bpo-30978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30978}: str.format_map() now passes key lookup exceptions through.
Previously any exception was replaced with a KeyError exception.

@item 
bpo-30808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30808}: Use _Py_atomic API for concurrency-sensitive signal state.

@item 
bpo-30876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30876}: Relative import from unloaded package now reimports the package
instead of failing with SystemError.  Relative import from non-package now
fails with ImportError rather than SystemError.

@item 
bpo-30703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30703}: Improve signal delivery. Avoid using Py_AddPendingCall from
signal handler, to avoid calling signal-unsafe functions. The tests I'm
adding here fail without the rest of the patch, on Linux and OS X. This
means our signal delivery logic had defects (some signals could be lost).

@item 
bpo-30765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30765}: Avoid blocking in pthread_mutex_lock() when
PyThread_acquire_lock() is asked not to block.

@item 
bpo-31161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31161}: Make sure the 'Missing parentheses' syntax error message is
only applied to SyntaxError, not to subclasses. Patch by Martijn Pieters.

@item 
bpo-30814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30814}: Fixed a race condition when import a submodule from a package.

@item 
bpo-30736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30736}: The internal unicodedata database has been upgraded to Unicode
10.0.

@item 
bpo-30604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30604}: Move co_extra_freefuncs from per-thread to per-interpreter to
avoid crashes.

@item 
bpo-30597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30597}: @code{print} now shows expected input in custom error message when
used as a Python 2 statement. Patch by Sanyam Khurana.

@item 
bpo-30682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30682}: Removed a too-strict assertion that failed for certain
f-strings, such as eval("f'\n'") and eval("f'\r'").

@item 
bpo-30501@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30501}: The compiler now produces more optimal code for complex
condition expressions in the "if", "while" and "assert" statement, the
"if" expression, and generator expressions and comprehensions.

@item 
bpo-28180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28180}: Implement 
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/} (legacy C locale coercion). This means
that when a suitable coercion target locale is available, both the core
interpreter and locale-aware C extensions will assume the use of UTF-8 as
the default text encoding, rather than ASCII.

@item 
bpo-30486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30486}: Allows setting cell values for __closure__. Patch by Lisa
Roach.

@item 
bpo-30537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30537}: itertools.islice now accepts integer-like objects (having an
__index__ method) as start, stop, and slice arguments

@item 
bpo-25324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25324}: Tokens needed for parsing in Python moved to C. @code{COMMENT},
@code{NL} and @code{ENCODING}. This way the tokens and tok_names in the token
module don't get changed when you import the tokenize module.

@item 
bpo-29104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29104}: Fixed parsing backslashes in f-strings.

@item 
bpo-27945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27945}: Fixed various segfaults with dict when input collections are
mutated during searching, inserting or comparing.  Based on patches by
Duane Griffin and Tim Mitchell.

@item 
bpo-25794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25794}: Fixed type.__setattr__() and type.__delattr__() for
non-interned attribute names.  Based on patch by Eryk Sun.

@item 
bpo-30039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30039}: If a KeyboardInterrupt happens when the interpreter is in the
middle of resuming a chain of nested 'yield from' or 'await' calls, it's
now correctly delivered to the innermost frame.

@item 
bpo-28974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28974}: @code{object.__format__(x, '@w{'})} is now equivalent to @code{str(x)}
rather than @code{format(str(self), '@w{'})}.

@item 
bpo-30024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30024}: Circular imports involving absolute imports with binding a
submodule to a name are now supported.

@item 
bpo-12414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12414}: sys.getsizeof() on a code object now returns the sizes which
includes the code struct and sizes of objects which it references. Patch
by Donghee Na.

@item 
bpo-29839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29839}: len() now raises ValueError rather than OverflowError if
__len__() returned a large negative integer.

@item 
bpo-11913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11913}: README.rst is now included in the list of distutils standard
READMEs and therefore included in source distributions.

@item 
bpo-29914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29914}: Fixed default implementations of __reduce__ and
__reduce_ex__(). object.__reduce__() no longer takes arguments,
object.__reduce_ex__() now requires one argument.

@item 
bpo-29949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29949}: Fix memory usage regression of set and frozenset object.

@item 
bpo-29935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29935}: Fixed error messages in the index() method of tuple, list and
deque when pass indices of wrong type.

@item 
bpo-29816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29816}: Shift operation now has less opportunity to raise
OverflowError. ValueError always is raised rather than OverflowError for
negative counts. Shifting zero with non-negative count always returns
zero.

@item 
bpo-24821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24821}: Fixed the slowing down to 25 times in the searching of some
unlucky Unicode characters.

@item 
bpo-29102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29102}: Add a unique ID to PyInterpreterState.  This makes it easier to
identify each subinterpreter.

@item 
bpo-29894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29894}: The deprecation warning is emitted if __complex__ returns an
instance of a strict subclass of complex.  In a future versions of Python
this can be an error.

@item 
bpo-29859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29859}: Show correct error messages when any of the pthread_* calls in
thread_pthread.h fails.

@item 
bpo-29849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29849}: Fix a memory leak when an ImportError is raised during from
import.

@item 
bpo-28856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28856}: Fix an oversight that %b format for bytes should support
objects follow the buffer protocol.

@item 
bpo-29723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29723}: The @code{sys.path[0]} initialization change for bpo-29139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29139} caused
a regression by revealing an inconsistency in how sys.path is initialized
when executing @code{__main__} from a zipfile, directory, or other import
location. The interpreter now consistently avoids ever adding the import
location's parent directory to @code{sys.path}, and ensures no other
@code{sys.path} entries are inadvertently modified when inserting the import
location named on the command line.

@item 
bpo-29568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29568}: Escaped percent "%%" in the format string for classic string
formatting no longer allows any characters between two percents.

@item 
bpo-29714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29714}: Fix a regression that bytes format may fail when containing
zero bytes inside.

@item 
bpo-29695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29695}: bool(), float(), list() and tuple() no longer take keyword
arguments. The first argument of int() can now be passes only as
positional argument.

@item 
bpo-28893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28893}: Set correct __cause__ for errors about invalid awaitables
returned from __aiter__ and __anext__.

@item 
bpo-28876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28876}: @code{bool(range)} works even if @code{len(range)} raises
@ref{a81,,OverflowError}.

@item 
bpo-29683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29683}: Fixes to memory allocation in _PyCode_SetExtra.  Patch by Brian
Coleman.

@item 
bpo-29684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29684}: Fix minor regression of PyEval_CallObjectWithKeywords. It
should raise TypeError when kwargs is not a dict.  But it might cause segv
when args=NULL and kwargs is not a dict.

@item 
bpo-28598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28598}: Support __rmod__ for subclasses of str being called before
str.__mod__. Patch by Martijn Pieters.

@item 
bpo-29607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29607}: Fix stack_effect computation for CALL_FUNCTION_EX. Patch by
Matthieu Dartiailh.

@item 
bpo-29602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29602}: Fix incorrect handling of signed zeros in complex constructor
for complex subclasses and for inputs having a __complex__ method. Patch
by Serhiy Storchaka.

@item 
bpo-29347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29347}: Fixed possibly dereferencing undefined pointers when creating
weakref objects.

@item 
bpo-29463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29463}: Add @code{docstring} field to Module, ClassDef, FunctionDef, and
AsyncFunctionDef ast nodes.  docstring is not first stmt in their body
anymore.  It affects @code{co_firstlineno} and @code{co_lnotab} of code object
for module and class. (Reverted in bpo-32911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32911}.)

@item 
bpo-29438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29438}: Fixed use-after-free problem in key sharing dict.

@item 
bpo-29546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29546}: Set the 'path' and 'name' attribute on ImportError for @code{from
... import ...}.

@item 
bpo-29546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29546}: Improve from-import error message with location

@item 
bpo-29478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29478}: If max_line_length=None is specified while using the Compat32
policy, it is no longer ignored.  Patch by Mircea Cosbuc.

@item 
bpo-29319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29319}: Prevent RunMainFromImporter overwriting sys.path[0].

@item 
bpo-29337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29337}: Fixed possible BytesWarning when compare the code objects.
Warnings could be emitted at compile time.

@item 
bpo-29327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29327}: Fixed a crash when pass the iterable keyword argument to
sorted().

@item 
bpo-29034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29034}: Fix memory leak and use-after-free in os module
(path_converter).

@item 
bpo-29159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29159}: Fix regression in bytes(x) when x.__index__() raises Exception.

@item 
bpo-29049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29049}: Call _PyObject_GC_TRACK() lazily when calling Python function.
Calling function is up to 5% faster.

@item 
bpo-28927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28927}: bytes.fromhex() and bytearray.fromhex() now ignore all ASCII
whitespace, not only spaces.  Patch by Robert Xiao.

@item 
bpo-28932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28932}: Do not include <sys/random.h> if it does not exist.

@item 
bpo-25677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25677}: Correct the positioning of the syntax error caret for indented
blocks. Based on patch by Michael Layzell.

@item 
bpo-29000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29000}: Fixed bytes formatting of octals with zero padding in alternate
form.

@item 
bpo-18896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18896}: Python function can now have more than 255 parameters.
collections.namedtuple() now supports tuples with more than 255 elements.

@item 
bpo-28596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28596}: The preferred encoding is UTF-8 on Android. Patch written by
Chi Hsuan Yen.

@item 
bpo-22257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22257}: Clean up interpreter startup (see 
@geindex Python Enhancement Proposals; PEP 432
PEP 432@footnote{https://peps.python.org/pep-0432/}).

@item 
bpo-26919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26919}: On Android, operating system data is now always encoded/decoded
to/from UTF-8, instead of the locale encoding to avoid inconsistencies
with os.fsencode() and os.fsdecode() which are already using UTF-8.

@item 
bpo-28991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28991}: functools.lru_cache() was susceptible to an obscure reentrancy
bug triggerable by a monkey-patched len() function.

@item 
bpo-28147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28147}: Fix a memory leak in split-table dictionaries: setattr() must
not convert combined table into split table. Patch written by INADA Naoki.

@item 
bpo-28739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28739}: f-string expressions are no longer accepted as docstrings and
by ast.literal_eval() even if they do not include expressions.

@item 
bpo-28512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28512}: Fixed setting the offset attribute of SyntaxError by
PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

@item 
bpo-28918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28918}: Fix the cross compilation of xxlimited when Python has been
built with Py_DEBUG defined.

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: Rather than silently producing a class that doesn't support
zero-argument @code{super()} in methods, failing to pass the new
@code{__classcell__} namespace entry up to @code{type.__new__} now results in a
@code{DeprecationWarning} and a class that supports zero-argument
@code{super()}.

@item 
bpo-28797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28797}: Modifying the class __dict__ inside the __set_name__ method of
a descriptor that is used inside that class no longer prevents calling the
__set_name__ method of other descriptors.

@item 
bpo-28799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28799}: Remove the @code{PyEval_GetCallStats()} function and deprecate the
untested and undocumented @code{sys.callstats()} function. Remove the
@code{CALL_PROFILE} special build: use the @ref{1717,,sys.setprofile()} function,
@ref{2b,,cProfile} or @ref{b4,,profile} to profile function calls.

@item 
bpo-12844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12844}: More than 255 arguments can now be passed to a function.

@item 
bpo-28782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28782}: Fix a bug in the implementation @code{yield from} when checking if
the next instruction is YIELD_FROM. Regression introduced by WORDCODE
(bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647}).

@item 
bpo-28774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28774}: Fix error position of the unicode error in ASCII and Latin1
encoders when a string returned by the error handler contains multiple
non-encodable characters (non-ASCII for the ASCII codec, characters out of
the U+0000-U+00FF range for Latin1).

@item 
bpo-28731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28731}: Optimize _PyDict_NewPresized() to create correct size dict.
Improve speed of dict literal with constant keys up to 30%.

@item 
bpo-28532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28532}: Show sys.version when -V option is supplied twice.

@item 
bpo-27100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27100}: The with-statement now checks for __enter__ before it checks
for __exit__. This gives less confusing error messages when both methods
are missing. Patch by Jonathan Ellington.

@item 
bpo-28746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28746}: Fix the set_inheritable() file descriptor method on platforms
that do not have the ioctl FIOCLEX and FIONCLEX commands.

@item 
bpo-26920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26920}: Fix not getting the locale's charset upon initializing the
interpreter, on platforms that do not have langinfo.

@item 
bpo-28648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28648}: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X
when decode astral characters.  Patch by Xiang Zhang.

@item 
bpo-28665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28665}: Improve speed of the STORE_DEREF opcode by 40%.

@item 
bpo-19398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19398}: Extra slash no longer added to sys.path components in case of
empty compile-time PYTHONPATH components.

@item 
bpo-28621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28621}: Sped up converting int to float by reusing faster bits counting
implementation.  Patch by Adrian Wielgosik.

@item 
bpo-28580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28580}: Optimize iterating split table values. Patch by Xiang Zhang.

@item 
bpo-28583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28583}: PyDict_SetDefault didn't combine split table when needed. Patch
by Xiang Zhang.

@item 
bpo-28128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28128}: Deprecation warning for invalid str and byte escape sequences
now prints better information about where the error occurs. Patch by
Serhiy Storchaka and Eric Smith.

@item 
bpo-28509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28509}: dict.update() no longer allocate unnecessary large memory.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Fixed potential crash in PyUnicode_AsDecodedObject() in debug
build.

@item 
bpo-28517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28517}: Fixed of-by-one error in the peephole optimizer that caused
keeping unreachable code.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Improved exception reporting for problematic __set_name__
attributes.

@item 
bpo-23782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23782}: Fixed possible memory leak in _PyTraceback_Add() and exception
loss in PyTraceBack_Here().

@item 
bpo-28183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28183}: Optimize and cleanup dict iteration.

@item 
bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}: Added C implementation of asyncio.Future. Original patch by
Yury Selivanov.

@item 
bpo-28379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28379}: Added sanity checks and tests for PyUnicode_CopyCharacters().
Patch by Xiang Zhang.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The type of long range iterator is now registered as Iterator.
Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: Creating instances of range_iterator by calling range_iterator
type now is disallowed.  Calling iter() on range instance is the only way.
Patch by Oren Milman.

@item 
bpo-26906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26906}: Resolving special methods of uninitialized type now causes
implicit initialization of the type instead of a fail.

@item 
bpo-18287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18287}: PyType_Ready() now checks that tp_name is not NULL. Original
patch by Niklas Koep.

@item 
bpo-24098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24098}: Fixed possible crash when AST is changed in process of
compiling it.

@item 
bpo-28201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28201}: Dict reduces possibility of 2nd conflict in hash table when
hashes have same lower bits.

@item 
bpo-28350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28350}: String constants with null character no longer interned.

@item 
bpo-26617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26617}: Fix crash when GC runs during weakref callbacks.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: String constants now interned recursively in tuples and
frozensets.

@item 
bpo-28289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28289}: ImportError.__init__ now resets not specified attributes.

@item 
bpo-21578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21578}: Fixed misleading error message when ImportError called with
invalid keyword args.

@item 
bpo-28203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28203}: Fix incorrect type in complex(1.0, @{2:3@}) error message. Patch
by Soumya Sharma.

@item 
bpo-28086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28086}: Single var-positional argument of tuple subtype was passed
unscathed to the C-defined function.  Now it is converted to exact tuple.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Now __set_name__ is looked up on the class instead of the
instance.

@item 
bpo-27955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27955}: Fallback on reading /dev/urandom device when the getrandom()
syscall fails with EPERM, for example when blocked by SECCOMP.

@item 
bpo-28192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28192}: Don't import readline in isolated mode.

@item 
bpo-27441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27441}: Remove some redundant assignments to ob_size in longobject.c.
Thanks Oren Milman.

@item 
bpo-27222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27222}: Clean up redundant code in long_rshift function. Thanks Oren
Milman.

@item 
Upgrade internal unicode databases to Unicode version 9.0.0.

@item 
bpo-28131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28131}: Fix a regression in zipimport's compile_source().  zipimport
should use the same optimization level as the interpreter.

@item 
bpo-28126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28126}: Replace Py_MEMCPY with memcpy(). Visual Studio can properly
optimize memcpy().

@item 
bpo-28120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28120}: Fix dict.pop() for split dictionary when trying to remove a
"pending key" (Not yet inserted in split-table). Patch by Xiang Zhang.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Raise DeprecationWarning when async and await keywords are used
as variable/attribute/class/function name.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Fix a refleak in code that raises DeprecationWarning.

@item 
bpo-28721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28721}: Fix asynchronous generators aclose() and athrow() to handle
StopAsyncIteration propagation properly.

@item 
bpo-26110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26110}: Speed-up method calls: add LOAD_METHOD and CALL_METHOD opcodes.
@end itemize

@node ライブラリ<173>,ドキュメント<66>,Core and Builtins<169>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id833}@anchor{1e98}
@subsubsection ライブラリ



@itemize -

@item 
bpo-31499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31499}: xml.etree: Fix a crash when a parser is part of a reference
cycle.

@item 
bpo-31482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31482}: @code{random.seed()} now works with bytes in version=1

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: typing.get_type_hints now finds the right globalns for classes
and modules by default (when no @code{globalns} was specified by the caller).

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Speed improvements to the @code{typing} module.  Original PRs by
Ivan Levkivskyi and Mitar.

@item 
bpo-31544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31544}: The C accelerator module of ElementTree ignored exceptions
raised when looking up TreeBuilder target methods in XMLParser().

@item 
bpo-31234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31234}: socket.create_connection() now fixes manually a reference
cycle: clear the variable storing the last exception on success.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: LoggerAdapter objects can now be nested.

@item 
bpo-31431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31431}: SSLContext.check_hostname now automatically sets
SSLContext.verify_mode to ssl.CERT_REQUIRED instead of failing with a
ValueError.

@item 
bpo-31233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31233}: socketserver.ThreadingMixIn now keeps a list of non-daemonic
threads to wait until all these threads complete in server_close().

@item 
bpo-28638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28638}: Changed the implementation strategy for
collections.namedtuple() to substantially reduce the use of exec() in
favor of precomputed methods. As a result, the `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.)

@item 
bpo-31400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31400}: Improves SSL error handling to avoid losing error numbers.

@item 
bpo-27629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27629}: Make return types of SSLContext.wrap_bio() and
SSLContext.wrap_socket() customizable.

@item 
bpo-28958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28958}: ssl.SSLContext() now uses OpenSSL error information when a
context cannot be instantiated.

@item 
bpo-28182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28182}: The SSL module now raises SSLCertVerificationError when OpenSSL
fails to verify the peer's certificate. The exception contains more
information about the error.

@item 
bpo-27340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27340}: SSLSocket.sendall() now uses memoryview to create slices of
data. This fixes support for all bytes-like object. It is also more
efficient and avoids costly copies.

@item 
bpo-14191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14191}: A new function
@code{argparse.ArgumentParser.parse_intermixed_args} provides the ability to
parse command lines where there user intermixes options and positional
arguments.

@item 
bpo-31178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31178}: Fix string concatenation bug in rare error path in the
subprocess module

@item 
bpo-31350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31350}: Micro-optimize @code{asyncio._get_running_loop()} to become up
to 10% faster.

@item 
bpo-31170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31170}: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of
partial characters for UTF-8 input (libexpat bug 115):
@indicateurl{https://github.com/libexpat/libexpat/issues/115}

@item 
bpo-29136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29136}: Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

@item 
bpo-1198569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1198569}: @code{string.Template} subclasses can optionally define
@code{braceidpattern} if they want to specify different placeholder patterns
inside and outside the braces.  If None (the default) it falls back to
@code{idpattern}.

@item 
bpo-31326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31326}: concurrent.futures.ProcessPoolExecutor.shutdown() now
explicitly closes the call queue. Moreover, shutdown(wait=True) now also
join the call queue thread, to prevent leaking a dangling thread.

@item 
bpo-27144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27144}: The @code{map()} and @code{as_completed()} iterators in
@code{concurrent.futures} now avoid keeping a reference to yielded objects.

@item 
bpo-31281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31281}: Fix @code{fileinput.FileInput(files, inplace=True)} when @code{files}
contain @code{pathlib.Path} objects.

@item 
bpo-10746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10746}: Fix ctypes producing wrong 
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} type codes for integer
types.

@item 
bpo-27584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27584}: @code{AF_VSOCK} has been added to the socket interface which
allows communication between virtual machines and their host.

@item 
bpo-22536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22536}: The subprocess module now sets the filename when
FileNotFoundError is raised on POSIX systems due to the executable or cwd
not being found.

@item 
bpo-29741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29741}: Update some methods in the _pyio module to also accept integer
types. Patch by Oren Milman.

@item 
bpo-31249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31249}: concurrent.futures: WorkItem.run() used by ThreadPoolExecutor
now breaks a reference cycle between an exception object and the WorkItem
object.

@item 
bpo-31247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31247}: xmlrpc.server now explicitly breaks reference cycles when using
sys.exc_info() in code handling exceptions.

@item 
bpo-23835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23835}: configparser: reading defaults in the @code{ConfigParser()}
constructor is now using @code{read_dict()}, making its behavior consistent
with the rest of the parser.  Non-string keys and values in the defaults
dictionary are now being implicitly converted to strings.  Patch by James
Tocknell.

@item 
bpo-31238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31238}: pydoc: the stop() method of the private ServerThread class now
waits until DocServer.serve_until_quit() completes and then explicitly
sets its docserver attribute to None to break a reference cycle.

@item 
bpo-5001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5001}: Many asserts in @code{multiprocessing} are now more informative,
and some error types have been changed to more specific ones.

@item 
bpo-31109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31109}: Convert zipimport to use Argument Clinic.

@item 
bpo-30102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30102}: The ssl and hashlib modules now call
OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0. The function
detects CPU features and enables optimizations on some CPU architectures
such as POWER8. Patch is based on research from Gustavo Serra Scalet.

@item 
bpo-18966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18966}: Non-daemonic threads created by a multiprocessing.Process are
now joined on child exit.

@item 
bpo-31183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31183}: @code{dis} now works with asynchronous generator and coroutine
objects. Patch by George Collins based on diagnosis by Luciano Ramalho.

@item 
bpo-5001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5001}: There are a number of uninformative asserts in the
@code{multiprocessing} module, as noted in issue 5001. This change fixes two
of the most potentially problematic ones, since they are in
error-reporting code, in the @code{multiprocessing.managers.convert_to_error}
function. (It also makes more informative a ValueError message.) The only
potentially problematic change is that the AssertionError is now a
TypeError; however, this should also help distinguish it from an
AssertionError being `reported' by the function/its caller (such as in
issue 31169). - Patch by Allen W. Smith (drallensmith on github).

@item 
bpo-31185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31185}: Fixed miscellaneous errors in asyncio speedup module.

@item 
bpo-31151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31151}: socketserver.ForkingMixIn.server_close() now waits until all
child processes completed to prevent leaking zombie processes.

@item 
bpo-31072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31072}: Add an @code{include_file} parameter to
@code{zipapp.create_archive()}

@item 
bpo-24700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24700}: Optimize array.array comparison. It is now from 10x up to 70x
faster when comparing arrays holding values of the same integer type.

@item 
bpo-31135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31135}: ttk: fix the destroy() method of LabeledScale and OptionMenu
classes. Call the parent destroy() method even if the used attribute
doesn't exist. The LabeledScale.destroy() method now also explicitly
clears label and scale attributes to help the garbage collector to destroy
all widgets.

@item 
bpo-31107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31107}: Fix @code{copyreg._slotnames()} mangled attribute calculation for
classes whose name begins with an underscore. Patch by Shane Harvey.

@item 
bpo-31080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31080}: Allow @code{logging.config.fileConfig} to accept kwargs and/or
args.

@item 
bpo-30897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30897}: @code{pathlib.Path} objects now include an @code{is_mount()} method
(only implemented on POSIX).  This is similar to @code{os.path.ismount(p)}.
Patch by Cooper Ry Lees.

@item 
bpo-31061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31061}: Fixed a crash when using asyncio and threads.

@item 
bpo-30987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30987}: Added support for CAN ISO-TP protocol in the socket module.

@item 
bpo-30522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30522}: Added a @code{setStream} method to @code{logging.StreamHandler} to
allow the stream to be set after creation.

@item 
bpo-30502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30502}: Fix handling of long oids in ssl.  Based on patch by Christian
Heimes.

@item 
bpo-5288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5288}: Support tzinfo objects with sub-minute offsets.

@item 
bpo-30919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30919}: Fix shared memory performance regression in multiprocessing in
3.x. Shared memory used anonymous memory mappings in 2.x, while 3.x mmaps
actual files. Try to be careful to do as little disk I/O as possible.

@item 
bpo-26732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26732}: Fix too many fds in processes started with the "forkserver"
method. A child process would inherit as many fds as the number of
still-running children.

@item 
bpo-29403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29403}: Fix @code{unittest.mock}'s autospec to not fail on method-bound
builtin functions.  Patch by Aaron Gallagher.

@item 
bpo-30961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30961}: Fix decrementing a borrowed reference in tracemalloc.

@item 
bpo-19896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19896}: Fix multiprocessing.sharedctypes to recognize typecodes @code{'q'}
and @code{'Q'}.

@item 
bpo-30946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30946}: Remove obsolete code in readline module for platforms where GNU
readline is older than 2.1 or where select() is not available.

@item 
bpo-25684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25684}: Change @code{ttk.OptionMenu} radiobuttons to be unique across
instances of @code{OptionMenu}.

@item 
bpo-30886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30886}: Fix multiprocessing.Queue.join_thread(): it now waits until the
thread completes, even if the thread was started by the same process which
created the queue.

@item 
bpo-29854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29854}: Fix segfault in readline when using readline's history-size
option.  Patch by Nir Soffer.

@item 
bpo-30794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30794}: Added multiprocessing.Process.kill method to terminate using
the SIGKILL signal on Unix.

@item 
bpo-30319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30319}: socket.close() now ignores ECONNRESET error.

@item 
bpo-30828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30828}: Fix out of bounds write in
@code{asyncio.CFuture.remove_done_callback()}.

@item 
bpo-30302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30302}: Use keywords in the @code{repr} of @code{datetime.timedelta}.

@item 
bpo-30807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30807}: signal.setitimer() may disable the timer when passed a tiny
value. Tiny values (such as 1e-6) are valid non-zero values for
setitimer(), which is specified as taking microsecond-resolution
intervals. However, on some platform, our conversion routine could convert
1e-6 into a zero interval, therefore disabling the timer instead of
(re-)scheduling it.

@item 
bpo-30441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30441}: Fix bug when modifying os.environ while iterating over it

@item 
bpo-29585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29585}: Avoid importing @code{sysconfig} from @code{site} to improve startup
speed. Python startup is about 5% faster on Linux and 30% faster on macOS.

@item 
bpo-29293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29293}: Add missing parameter "n" on
multiprocessing.Condition.notify(). The doc claims
multiprocessing.Condition behaves like threading.Condition, but its
notify() method lacked the optional "n" argument (to specify the number of
sleepers to wake up) that threading.Condition.notify() accepts.

@item 
bpo-30532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30532}: Fix email header value parser dropping folding white space in
certain cases.

@item 
bpo-30596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30596}: Add a @code{close()} method to @code{multiprocessing.Process}.

@item 
bpo-9146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9146}: Fix a segmentation fault in _hashopenssl when standard hash
functions such as md5 are not available in the linked OpenSSL library.  As
in some special FIPS-140 build environments.

@item 
bpo-29169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29169}: Update zlib to 1.2.11.

@item 
bpo-30119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30119}: ftplib.FTP.putline() now throws ValueError on commands that
contains CR or LF. Patch by Donghee Na.

@item 
bpo-30879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30879}: os.listdir() and os.scandir() now emit bytes names when called
with bytes-like argument.

@item 
bpo-30746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30746}: Prohibited the '=' character in environment variable names in
@code{os.putenv()} and @code{os.spawn*()}.

@item 
bpo-30664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30664}: The description of a unittest subtest now preserves the order
of keyword arguments of TestCase.subTest().

@item 
bpo-21071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21071}: struct.Struct.format type is now @ref{169,,str} instead of
@ref{192,,bytes}.

@item 
bpo-29212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29212}: Fix concurrent.futures.thread.ThreadPoolExecutor threads to
have a non repr() based thread name by default when no thread_name_prefix
is supplied. They will now identify themselves as
"ThreadPoolExecutor-y_n".

@item 
bpo-29755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29755}: Fixed the lgettext() family of functions in the gettext module.
They now always return bytes.

@item 
bpo-30616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30616}: Functional API of enum allows to create empty enums. Patched by
Donghee Na

@item 
bpo-30038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30038}: Fix race condition between signal delivery and wakeup file
descriptor. Patch by Nathaniel Smith.

@item 
bpo-23894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23894}: lib2to3 now recognizes @code{rb'...'} and @code{f'...'} strings.

@item 
bpo-24744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24744}: pkgutil.walk_packages function now raises ValueError if `path'
is a string. Patch by Sanyam Khurana.

@item 
bpo-24484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24484}: Avoid race condition in multiprocessing cleanup.

@item 
bpo-30589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30589}: Fix multiprocessing.Process.exitcode to return the opposite of
the signal number when the process is killed by a signal (instead of 255)
when using the "forkserver" method.

@item 
bpo-28994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28994}: The traceback no longer displayed for SystemExit raised in a
callback registered by atexit.

@item 
bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508}: Don't log exceptions if Task/Future "cancel()" method was
called.

@item 
bpo-30645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30645}: Fix path calculation in @code{imp.load_package()}, fixing it for
cases when a package is only shipped with bytecodes. Patch by Alexandru
Ardelean.

@item 
bpo-11822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11822}: The dis.dis() function now is able to disassemble nested code
objects.

@item 
bpo-30624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30624}: selectors does not take KeyboardInterrupt and SystemExit into
account, leaving a fd in a bad state in case of error. Patch by Giampaolo
Rodola'.

@item 
bpo-30595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30595}: multiprocessing.Queue.get() with a timeout now polls its reader
in non-blocking mode if it succeeded to acquire the lock but the acquire
took longer than the timeout.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Updates to typing module: Add generic AsyncContextManager, add
support for ContextManager on all versions. Original PRs by Jelle Zijlstra
and Ivan Levkivskyi

@item 
bpo-30605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30605}: re.compile() no longer raises a BytesWarning when compiling a
bytes instance with misplaced inline modifier.  Patch by Roy Williams.

@item 
bpo-29870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29870}: Fix ssl sockets leaks when connection is aborted in asyncio/ssl
implementation. Patch by Michaël Sghaïer.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Closing transport during handshake process leaks open socket.
Patch by Nikolay Kim

@item 
bpo-27585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27585}: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu
Sornay.

@item 
bpo-30014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30014}: modify() method of poll(), epoll() and devpoll() based classes
of selectors module is around 10% faster.  Patch by Giampaolo Rodola'.

@item 
bpo-30418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30418}: On Windows, subprocess.Popen.communicate() now also ignore
EINVAL on stdin.write() if the child process is still running but closed
the pipe.

@item 
bpo-30463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30463}: Added empty __slots__ to abc.ABC.  This allows subclassers to
deny __dict__ and __weakref__ creation.  Patch by Aaron Hall.

@item 
bpo-30520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30520}: Loggers are now pickleable.

@item 
bpo-30557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30557}: faulthandler now correctly filters and displays exception codes
on Windows

@item 
bpo-30526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30526}: Add TextIOWrapper.reconfigure() and a
TextIOWrapper.write_through attribute.

@item 
bpo-30245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30245}: Fix possible overflow when organize struct.pack_into error
message.  Patch by Yuan Liu.

@item 
bpo-30378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30378}: Fix the problem that logging.handlers.SysLogHandler cannot
handle IPv6 addresses.

@item 
bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500}: Allow registering at-fork handlers.

@item 
bpo-30470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30470}: Deprecate invalid ctypes call protection on Windows.  Patch by
Mariatta Wijaya.

@item 
bpo-30414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30414}: multiprocessing.Queue._feed background running thread do not
break from main loop on exception.

@item 
bpo-30003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30003}: Fix handling escape characters in HZ codec.  Based on patch by
Ma Lin.

@item 
bpo-30149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30149}: inspect.signature() now supports callables with
variable-argument parameters wrapped with partialmethod. Patch by Donghee
Na.

@item 
bpo-30436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30436}: importlib.find_spec() raises ModuleNotFoundError instead of
AttributeError if the specified parent module is not a package (i.e. lacks
a __path__ attribute).

@item 
bpo-30301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30301}: Fix AttributeError when using SimpleQueue.empty() under `spawn'
and `forkserver' start methods.

@item 
bpo-30375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30375}: Warnings emitted when compile a regular expression now always
point to the line in the user code.  Previously they could point into
inners of the re module if emitted from inside of groups or conditionals.

@item 
bpo-30329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30329}: imaplib and poplib now catch the Windows socket WSAEINVAL error
(code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted.
This error occurs sometimes on SSL connections.

@item 
bpo-29196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29196}: Removed previously deprecated in Python 2.4 classes Plist, Dict
and _InternalDict in the plistlib module.  Dict values in the result of
functions readPlist() and readPlistFromBytes() are now normal dicts.  You
no longer can use attribute access to access items of these dictionaries.

@item 
bpo-9850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9850}: The @code{macpath} is now deprecated and will be removed in
Python 3.8.

@item 
bpo-30299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30299}: Compiling regular expression in debug mode on CPython now
displays the compiled bytecode in human readable form.

@item 
bpo-30048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30048}: Fixed @code{Task.cancel()} can be ignored when the task is running
coroutine and the coroutine returned without any more @code{await}.

@item 
bpo-30266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30266}: contextlib.AbstractContextManager now supports
anti-registration by setting __enter__ = None or __exit__ = None,
following the pattern introduced in bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}. Patch by Jelle Zijlstra.

@item 
bpo-30340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30340}: Enhanced regular expressions optimization. This increased the
performance of matching some patterns up to 25 times.

@item 
bpo-30298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30298}: Weaken the condition of deprecation warnings for inline
modifiers. Now allowed several subsequential inline modifiers at the start
of the pattern (e.g. @code{'(?i)(?s)...'}).  In verbose mode whitespaces and
comments now are allowed before and between inline modifiers (e.g. @code{'(?x)
(?i) (?s)...'}).

@item 
bpo-30285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30285}: Optimized case-insensitive matching and searching of regular
expressions.

@item 
bpo-29990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29990}: Fix range checking in GB18030 decoder.  Original patch by Ma
Lin.

@item 
bpo-29979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29979}: rewrite cgi.parse_multipart, reusing the FieldStorage class and
making its results consistent with those of FieldStorage for
multipart/form-data requests. Patch by Pierre Quentel.

@item 
bpo-30243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30243}: Removed the __init__ methods of _json's scanner and encoder.
Misusing them could cause memory leaks or crashes.  Now scanner and
encoder objects are completely initialized in the __new__ methods.

@item 
bpo-30215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30215}: Compiled regular expression objects with the re.LOCALE flag no
longer depend on the locale at compile time.  Only the locale at matching
time affects the result of matching.

@item 
bpo-30185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30185}: Avoid KeyboardInterrupt tracebacks in forkserver helper process
when Ctrl-C is received.

@item 
bpo-30103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30103}: binascii.b2a_uu() and uu.encode() now support using @code{'`'} as
zero instead of space.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: add typing.NoReturn type, use
WrapperDescriptorType, minor bug-fixes.  Original PRs by Jim
Fasarakis-Hilliard and Ivan Levkivskyi.

@item 
bpo-30205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30205}: Fix getsockname() for unbound AF_UNIX sockets on Linux.

@item 
bpo-30228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30228}: The seek() and tell() methods of io.FileIO now set the internal
seekable attribute to avoid one syscall on open() (in buffered or text
mode).

@item 
bpo-30190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30190}: unittest's assertAlmostEqual and assertNotAlmostEqual provide a
better message in case of failure which includes the difference between
left and right arguments.  (patch by Giampaolo Rodola')

@item 
bpo-30101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30101}: Add support for curses.A_ITALIC.

@item 
bpo-29822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29822}: inspect.isabstract() now works during __init_subclass__.  Patch
by Nate Soares.

@item 
bpo-29960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29960}: Preserve generator state when _random.Random.setstate() raises
an exception. Patch by Bryan Olson.

@item 
bpo-30070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30070}: Fixed leaks and crashes in errors handling in the parser
module.

@item 
bpo-22352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22352}: Column widths in the output of dis.dis() are now adjusted for
large line numbers and instruction offsets.

@item 
bpo-30061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30061}: Fixed crashes in IOBase methods __next__() and readlines() when
readline() or __next__() respectively return non-sizeable object. Fixed
possible other errors caused by not checking results of PyObject_Size(),
PySequence_Size(), or PyMapping_Size().

@item 
bpo-30218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30218}: Fix PathLike support for shutil.unpack_archive. Patch by Jelle
Zijlstra.

@item 
bpo-10076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10076}: Compiled regular expression and match objects in the re module
now support copy.copy() and copy.deepcopy() (they are considered atomic).

@item 
bpo-30068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30068}: _io._IOBase.readlines will check if it's closed first when hint
is present.

@item 
bpo-29694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29694}: Fixed race condition in pathlib mkdir with flags parents=True.
Patch by Armin Rigo.

@item 
bpo-29692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29692}: Fixed arbitrary unchaining of RuntimeError exceptions in
contextlib.contextmanager.  Patch by Siddharth Velankar.

@item 
bpo-26187@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26187}: Test that sqlite3 trace callback is not called multiple times
when schema is changing.  Indirectly fixed by switching to use
sqlite3_prepare_v2() in bpo-9303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9303}.  Patch by Aviv Palivoda.

@item 
bpo-30017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30017}: Allowed calling the close() method of the zip entry writer
object multiple times.  Writing to a closed writer now always produces a
ValueError.

@item 
bpo-29998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29998}: Pickling and copying ImportError now preserves name and path
attributes.

@item 
bpo-29995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29995}: re.escape() now escapes only regex special characters.

@item 
bpo-29962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29962}: Add math.remainder operation, implementing remainder as
specified in IEEE 754.

@item 
bpo-29649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29649}: Improve struct.pack_into() exception messages for problems with
the buffer size and offset.  Patch by Andrew Nester.

@item 
bpo-29654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29654}: Support If-Modified-Since HTTP header (browser cache).  Patch
by Pierre Quentel.

@item 
bpo-29931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29931}: Fixed comparison check for ipaddress.ip_interface objects.
Patch by Sanjay Sundaresan.

@item 
bpo-29953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29953}: Fixed memory leaks in the replace() method of datetime and time
objects when pass out of bound fold argument.

@item 
bpo-29942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29942}: Fix a crash in itertools.chain.from_iterable when encountering
long runs of empty iterables.

@item 
bpo-10030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10030}: Sped up reading encrypted ZIP files by 2 times.

@item 
bpo-29204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29204}: Element.getiterator() and the html parameter of XMLParser()
were deprecated only in the documentation (since Python 3.2 and 3.4
correspondingly). Now using them emits a deprecation warning.

@item 
bpo-27863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27863}: Fixed multiple crashes in ElementTree caused by race conditions
and wrong types.

@item 
bpo-25996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25996}: Added support of file descriptors in os.scandir() on Unix.
os.fwalk() is sped up by 2 times by using os.scandir().

@item 
bpo-28699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28699}: Fixed a bug in pools in multiprocessing.pool that raising an
exception at the very first of an iterable may swallow the exception or
make the program hang. Patch by Davin Potts and Xiang Zhang.

@item 
bpo-23890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23890}: unittest.TestCase.assertRaises() now manually breaks a
reference cycle to not keep objects alive longer than expected.

@item 
bpo-29901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29901}: The zipapp module now supports general path-like objects, not
just pathlib.Path.

@item 
bpo-25803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25803}: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when
the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-29861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29861}: Release references to tasks, their arguments and their results
as soon as they are finished in multiprocessing.Pool.

@item 
bpo-19930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19930}: The mode argument of os.makedirs() no longer affects the file
permission bits of newly created intermediate-level directories.

@item 
bpo-29884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29884}: faulthandler: Restore the old sigaltstack during teardown.
Patch by Christophe Zeitouny.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive buffered file-like objects.

@item 
bpo-29800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29800}: Fix crashes in partial.__repr__ if the keys of partial.keywords
are not strings.  Patch by Michael Seifert.

@item 
bpo-8256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8256}: Fixed possible failing or crashing input() if attributes
"encoding" or "errors" of sys.stdin or sys.stdout are not set or are not
strings.

@item 
bpo-28692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28692}: Using non-integer value for selecting a plural form in gettext
is now deprecated.

@item 
bpo-26121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26121}: Use C library implementation for math functions erf() and
erfc().

@item 
bpo-29619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29619}: os.stat() and os.DirEntry.inode() now convert inode (st_ino)
using unsigned integers.

@item 
bpo-28298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28298}: Fix a bug that prevented array 'Q', 'L' and 'I' from accepting
big intables (objects that have __int__) as elements.

@item 
bpo-29645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29645}: Speed up importing the webbrowser module.
webbrowser.register() is now thread-safe.

@item 
bpo-28231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28231}: The zipfile module now accepts path-like objects for external
paths.

@item 
bpo-26915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26915}: index() and count() methods of collections.abc.Sequence now
check identity before checking equality when do comparisons.

@item 
bpo-28682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28682}: Added support for bytes paths in os.fwalk().

@item 
bpo-29728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29728}: Add new @code{socket.TCP_NOTSENT_LOWAT} (Linux 3.12)
constant. Patch by Nathaniel J. Smith.

@item 
bpo-29623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29623}: Allow use of path-like object as a single argument in
ConfigParser.read(). Patch by David Ellis.

@item 
bpo-9303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9303}: Migrate sqlite3 module to _v2 API.  Patch by Aviv Palivoda.

@item 
bpo-28963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28963}: Fix out of bound iteration in
asyncio.Future.remove_done_callback implemented in C.

@item 
bpo-29704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29704}: asyncio.subprocess.SubprocessStreamProtocol no longer closes
before all pipes are closed.

@item 
bpo-29271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29271}: Fix Task.current_task and Task.all_tasks implemented in C to
accept None argument as their pure Python implementation.

@item 
bpo-29703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29703}: Fix asyncio to support instantiation of new event loops in
child processes.

@item 
bpo-29615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29615}: SimpleXMLRPCDispatcher no longer chains KeyError (or any other
exception) to exception(s) raised in the dispatched methods. Patch by Petr
Motejlek.

@item 
bpo-7769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7769}: Method register_function() of
xmlrpc.server.SimpleXMLRPCDispatcher and its subclasses can now be used as
a decorator.

@item 
bpo-29376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29376}: Fix assertion error in threading._DummyThread.is_alive().

@item 
bpo-28624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28624}: Add a test that checks that cwd parameter of Popen() accepts
PathLike objects.  Patch by Sayan Chowdhury.

@item 
bpo-28518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28518}: Start a transaction implicitly before a DML statement. Patch by
Aviv Palivoda.

@item 
bpo-29742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29742}: get_extra_info() raises exception if get called on closed ssl
transport. Patch by Nikolay Kim.

@item 
bpo-16285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16285}: urllib.parse.quote is now based on RFC 3986 and hence includes
'~' in the set of characters that is not quoted by default. Patch by
Christian Theune and Ratnadeep Debnath.

@item 
bpo-29532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29532}: Altering a kwarg dictionary passed to functools.partial() no
longer affects a partial object after creation.

@item 
bpo-29110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29110}: Fix file object leak in aifc.open() when file is given as a
filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

@item 
bpo-22807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22807}: Add uuid.SafeUUID and uuid.UUID.is_safe to relay information
from the platform about whether generated UUIDs are generated with a
multiprocessing safe method.

@item 
bpo-29576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29576}: Improve some deprecations in importlib. Some deprecated methods
now emit DeprecationWarnings and have better descriptive messages.

@item 
bpo-29534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29534}: Fixed different behaviour of Decimal.from_float() for _decimal
and _pydecimal. Thanks Andrew Nester.

@item 
bpo-10379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10379}: locale.format_string now supports the 'monetary' keyword
argument, and locale.format is deprecated.

@item 
bpo-29851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29851}: importlib.reload() now raises ModuleNotFoundError if the module
lacks a spec.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: typing.Counter,
typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle
Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

@item 
bpo-29100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29100}: Fix datetime.fromtimestamp() regression introduced in Python
3.6.0: check minimum and maximum years.

@item 
bpo-29416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29416}: Prevent infinite loop in pathlib.Path.mkdir

@item 
bpo-29444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29444}: Fixed out-of-bounds buffer access in the group() method of the
match object. Based on patch by WGH.

@item 
bpo-29377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29377}: Add WrapperDescriptorType, MethodWrapperType, and
MethodDescriptorType built-in types to types module. Original patch by
Manuel Krebber.

@item 
bpo-29218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29218}: Unused install_misc command is now removed.  It has been
documented as unused since 2000.  Patch by Eric N. Vander Weele.

@item 
bpo-29368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29368}: The extend() method is now called instead of the append()
method when unpickle collections.deque and other list-like objects. This
can speed up unpickling to 2 times.

@item 
bpo-29338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29338}: The help of a builtin or extension class now includes the
constructor signature if __text_signature__ is provided for the class.

@item 
bpo-29335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29335}: Fix subprocess.Popen.wait() when the child process has exited
to a stopped instead of terminated state (ex: when under ptrace).

@item 
bpo-29290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29290}: Fix a regression in argparse that help messages would wrap at
non-breaking spaces.

@item 
bpo-28735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28735}: Fixed the comparison of mock.MagickMock with mock.ANY.

@item 
bpo-29197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29197}: Removed deprecated function ntpath.splitunc().

@item 
bpo-29210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29210}: Removed support of deprecated argument "exclude" in
tarfile.TarFile.add().

@item 
bpo-29219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29219}: Fixed infinite recursion in the repr of uninitialized
ctypes.CDLL instances.

@item 
bpo-29192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29192}: Removed deprecated features in the http.cookies module.

@item 
bpo-29193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29193}: A format string argument for string.Formatter.format() is now
positional-only.

@item 
bpo-29195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29195}: Removed support of deprecated undocumented keyword arguments in
methods of regular expression objects.

@item 
bpo-28969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28969}: Fixed race condition in C implementation of
functools.lru_cache. KeyError could be raised when cached function with
full cache was simultaneously called from different threads with the same
uncached arguments.

@item 
bpo-20804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20804}: The unittest.mock.sentinel attributes now preserve their
identity when they are copied or pickled.

@item 
bpo-29142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29142}: In urllib.request, suffixes in no_proxy environment variable
with leading dots could match related hostnames again (e.g. .b.c matches
a.b.c). Patch by Milan Oberkirch.

@item 
bpo-28961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28961}: Fix unittest.mock._Call helper: don't ignore the name parameter
anymore. Patch written by Jiajun Huang.

@item 
bpo-15812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15812}: inspect.getframeinfo() now correctly shows the first line of a
context. Patch by Sam Breese.

@item 
bpo-28985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28985}: Update authorizer constants in sqlite3 module. Patch by
Dingyuan Wang.

@item 
bpo-29079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29079}: Prevent infinite loop in pathlib.resolve() on Windows

@item 
bpo-13051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13051}: Fixed recursion errors in large or resized
curses.textpad.Textbox.  Based on patch by Tycho Andersen.

@item 
bpo-9770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9770}: curses.ascii predicates now work correctly with negative
integers.

@item 
bpo-28427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28427}: old keys should not remove new values from WeakValueDictionary
when collecting from another thread.

@item 
bpo-28923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28923}: Remove editor artifacts from Tix.py.

@item 
bpo-28871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28871}: Fixed a crash when deallocate deep ElementTree.

@item 
bpo-19542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19542}: Fix bugs in WeakValueDictionary.setdefault() and
WeakValueDictionary.pop() when a GC collection happens in another thread.

@item 
bpo-20191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20191}: Fixed a crash in resource.prlimit() when passing a sequence
that doesn't own its elements as limits.

@item 
bpo-16255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16255}: subprocess.Popen uses /system/bin/sh on Android as the shell,
instead of /bin/sh.

@item 
bpo-28779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28779}: multiprocessing.set_forkserver_preload() would crash the
forkserver process if a preloaded module instantiated some multiprocessing
objects such as locks.

@item 
bpo-26937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26937}: The chown() method of the tarfile.TarFile class does not fail
now when the grp module cannot be imported, as for example on Android
platforms.

@item 
bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847}: dbm.dumb now supports reading read-only files and no longer
writes the index file when it is not changed.  A deprecation warning is
now emitted if the index file is missed and recreated in the 'r' and 'w'
modes (will be an error in future Python releases).

@item 
bpo-27030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27030}: Unknown escapes consisting of @code{'\'} and an ASCII letter in
re.sub() replacement templates regular expressions now are errors.

@item 
bpo-28835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28835}: Fix a regression introduced in warnings.catch_warnings(): call
warnings.showwarning() if it was overridden inside the context manager.

@item 
bpo-27172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27172}: To assist with upgrades from 2.7, the previously documented
deprecation of @code{inspect.getfullargspec()} has been reversed. This
decision may be revisited again after the Python 2.7 branch is no longer
officially supported.

@item 
bpo-28740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28740}: Add sys.getandroidapilevel(): return the build time API version
of Android as an integer. Function only available on Android.

@item 
bpo-26273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26273}: Add new @code{socket.TCP_CONGESTION} (Linux 2.6.13) and
@code{socket.TCP_USER_TIMEOUT} (Linux 2.6.37) constants. Patch written
by Omar Sandoval.

@item 
bpo-28752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28752}: Restored the __reduce__() methods of datetime objects.

@item 
bpo-28727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28727}: Regular expression patterns, _sre.SRE_Pattern objects created
by re.compile(), become comparable (only x==y and x!=y operators). This
change should fix the bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: don't duplicate warning filters when
the warnings module is reloaded (thing usually only done in unit tests).

@item 
bpo-20572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20572}: Remove the subprocess.Popen.wait endtime parameter.  It was
deprecated in 3.4 and undocumented prior to that.

@item 
bpo-25659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25659}: In ctypes, prevent a crash calling the from_buffer() and
from_buffer_copy() methods on abstract classes like Array.

@item 
bpo-28548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28548}: In the "http.server" module, parse the protocol version if
possible, to avoid using HTTP 0.9 in some error responses.

@item 
bpo-19717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19717}: Makes Path.resolve() succeed on paths that do not exist. Patch
by Vajrasky Kok

@item 
bpo-28563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28563}: Fixed possible DoS and arbitrary code execution when handle
plural form selections in the gettext module.  The expression parser now
supports exact syntax supported by GNU gettext.

@item 
bpo-28387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28387}: Fixed possible crash in _io.TextIOWrapper deallocator when the
garbage collector is invoked in other thread.  Based on patch by Sebastian
Cufre.

@item 
bpo-27517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27517}: LZMA compressor and decompressor no longer raise exceptions if
given empty data twice.  Patch by Benjamin Fogle.

@item 
bpo-28549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28549}: Fixed segfault in curses's addch() with ncurses6.

@item 
bpo-28449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28449}: tarfile.open() with mode "r" or "r:" now tries to open a tar
file with compression before trying to open it without compression.
Otherwise it had 50% chance failed with ignore_zeros=True.

@item 
bpo-23262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23262}: The webbrowser module now supports Firefox 36+ and derived
browsers.  Based on patch by Oleg Broytman.

@item 
bpo-24241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24241}: The webbrowser in an X environment now prefers using the
default browser directly. Also, the webbrowser register() function now has
a documented 'preferred' argument, to specify browsers to be returned by
get() with no arguments. Patch by David Steele

@item 
bpo-27939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27939}: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused
by representing the scale as float value internally in Tk.  tkinter.IntVar
now works if float value is set to underlying Tk variable.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar.prweek() no longer prints a space after a
weeks's calendar.  calendar.TextCalendar.pryear() no longer prints
redundant newline after a year's calendar.  Based on patch by Xiang Zhang.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar.prmonth() no longer prints a space at the
start of new line after printing a month's calendar.  Patch by Xiang
Zhang.

@item 
bpo-20491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20491}: The textwrap.TextWrapper class now honors non-breaking spaces.
Based on patch by Kaarle Ritvanen.

@item 
bpo-28353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28353}: os.fwalk() no longer fails on broken links.

@item 
bpo-28430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28430}: Fix iterator of C implemented asyncio.Future doesn't accept
non-None value is passed to it.send(val).

@item 
bpo-27025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27025}: Generated names for Tkinter widgets now start by the "!" prefix
for readability.

@item 
bpo-25464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25464}: Fixed HList.header_exists() in tkinter.tix module by addin a
workaround to Tix library bug.

@item 
bpo-28488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28488}: shutil.make_archive() no longer adds entry "./" to ZIP archive.

@item 
bpo-25953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25953}: re.sub() now raises an error for invalid numerical group
reference in replacement template even if the pattern is not found in the
string.  Error message for invalid group reference now includes the group
index and the position of the reference. Based on patch by SilentGhost.

@item 
bpo-28469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28469}: timeit now uses the sequence 1, 2, 5, 10, 20, 50,... instead of
1, 10, 100,... for autoranging.

@item 
bpo-28115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28115}: Command-line interface of the zipfile module now uses argparse.
Added support of long options.

@item 
bpo-18219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18219}: Optimize csv.DictWriter for large number of columns. Patch by
Mariatta Wijaya.

@item 
bpo-28448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28448}: Fix C implemented asyncio.Future didn't work on Windows.

@item 
bpo-23214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23214}: In the "io" module, the argument to BufferedReader and
BytesIO's read1() methods is now optional and can be -1, matching the
BufferedIOBase specification.

@item 
bpo-28480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28480}: Fix error building socket module when multithreading is
disabled.

@item 
bpo-28240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28240}: timeit: remove @code{-c/--clock} and @code{-t/--time} command line
options which were deprecated since Python 3.3.

@item 
bpo-28240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28240}: timeit now repeats the benchmarks 5 times instead of only 3 to
make benchmarks more reliable.

@item 
bpo-28240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28240}: timeit autorange now uses a single loop iteration if the
benchmark takes less than 10 seconds, instead of 10 iterations. "python3
-m timeit -s 'import time' 'time.sleep(1)'" now takes 4 seconds instead of
40 seconds.

@item 
Distutils.sdist now looks for README and setup.py files with case
sensitivity. This behavior matches that found in Setuptools 6.0 and later.
See setuptools 100@footnote{https://github.com/pypa/setuptools/issues/100} for
rationale.

@item 
bpo-24452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24452}: Make webbrowser support Chrome on Mac OS X. Patch by Ned
Batchelder.

@item 
bpo-20766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20766}: Fix references leaked by pdb in the handling of SIGINT
handlers.

@item 
bpo-27998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27998}: Fixed bytes path support in os.scandir() on Windows. Patch by
Eryk Sun.

@item 
bpo-28317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28317}: The disassembler now decodes FORMAT_VALUE argument.

@item 
bpo-28380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28380}: unittest.mock Mock autospec functions now properly support
assert_called, assert_not_called, and assert_called_once.

@item 
bpo-28229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28229}: lzma module now supports pathlib.

@item 
bpo-28321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28321}: Fixed writing non-BMP characters with binary format in
plistlib.

@item 
bpo-28225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28225}: bz2 module now supports pathlib.  Initial patch by Ethan
Furman.

@item 
bpo-28227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28227}: gzip now supports pathlib.  Patch by Ethan Furman.

@item 
bpo-28332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28332}: Deprecated silent truncations in socket.htons and socket.ntohs.
Original patch by Oren Milman.

@item 
bpo-27358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27358}: Optimized merging var-keyword arguments and improved error
message when passing a non-mapping as a var-keyword argument.

@item 
bpo-28257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28257}: Improved error message when passing a non-iterable as a
var-positional argument.  Added opcode BUILD_TUPLE_UNPACK_WITH_CALL.

@item 
bpo-28322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28322}: Fixed possible crashes when unpickle itertools objects from
incorrect pickle data.  Based on patch by John Leitch.

@item 
bpo-28228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28228}: imghdr now supports pathlib.

@item 
bpo-28226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28226}: compileall now supports pathlib.

@item 
bpo-28314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28314}: Fix function declaration (C flags) for the getiterator() method
of xml.etree.ElementTree.Element.

@item 
bpo-28148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28148}: Stop using localtime() and gmtime() in the time module.
Introduced platform independent _PyTime_localtime API that is similar to
POSIX localtime_r, but available on all platforms.  Patch by Ed Schouten.

@item 
bpo-28253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28253}: Fixed calendar functions for extreme months: 0001-01 and
9999-12. Methods itermonthdays() and itermonthdays2() are reimplemented so
that they don't call itermonthdates() which can cause datetime.date
under/overflow.

@item 
bpo-28275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28275}: Fixed possible use after free in the decompress() methods of
the LZMADecompressor and BZ2Decompressor classes. Original patch by John
Leitch.

@item 
bpo-27897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27897}: Fixed possible crash in sqlite3.Connection.create_collation()
if pass invalid string-like object as a name.  Patch by Xiang Zhang.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: random.choices() now has k as a keyword-only argument to
improve the readability of common cases and come into line with the
signature used in other languages.

@item 
bpo-18893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18893}: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py.
Patch by Madison May.

@item 
bpo-27611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27611}: Fixed support of default root window in the tkinter.tix module.
Added the master parameter in the DisplayStyle constructor.

@item 
bpo-27348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27348}: In the traceback module, restore the formatting of exception
messages like "Exception: None".  This fixes a regression introduced in
3.5a2.

@item 
bpo-25651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25651}: Allow false values to be used for msg parameter of subTest().

@item 
bpo-27778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27778}: Fix a memory leak in os.getrandom() when the getrandom() is
interrupted by a signal and a signal handler raises a Python exception.

@item 
bpo-28200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28200}: Fix memory leak on Windows in the os module (fix
path_converter() function).

@item 
bpo-25400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25400}: RobotFileParser now correctly returns default values for
crawl_delay and request_rate.  Initial patch by Peter Wirtz.

@item 
bpo-27932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}: Prevent memory leak in win32_ver().

@item 
Fix UnboundLocalError in socket._sendfile_use_sendfile.

@item 
bpo-28075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28075}: Check for ERROR_ACCESS_DENIED in Windows implementation of
os.stat().  Patch by Eryk Sun.

@item 
bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}: Warning message emitted by using inline flags in the middle of
regular expression now contains a (truncated) regex pattern. Patch by Tim
Graham.

@item 
bpo-25270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25270}: Prevent codecs.escape_encode() from raising SystemError when an
empty bytestring is passed.

@item 
bpo-28181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28181}: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

@item 
bpo-25895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25895}: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by
Gergely Imreh and Markus Holtermann.

@item 
bpo-28114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28114}: Fix a crash in parse_envlist() when env contains byte strings.
Patch by Eryk Sun.

@item 
bpo-27599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27599}: Fixed buffer overrun in binascii.b2a_qp() and
binascii.a2b_qp().

@item 
bpo-27906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27906}: Fix socket accept exhaustion during high TCP traffic. Patch by
Kevin Conway.

@item 
bpo-28174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28174}: Handle when SO_REUSEPORT isn't properly supported. Patch by
Seth Michael Larson.

@item 
bpo-26654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26654}: Inspect functools.partial in asyncio.Handle.__repr__. Patch by
iceboy.

@item 
bpo-26909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26909}: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

@item 
bpo-28176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28176}: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

@item 
bpo-27759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27759}: Fix selectors incorrectly retain invalid file descriptors.
Patch by Mark Williams.

@item 
bpo-28325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28325}: Remove vestigial MacOS 9 macurl2path module and its tests.

@item 
bpo-28368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28368}: Refuse monitoring processes if the child watcher has no loop
attached. Patch by Vincent Michel.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Raise RuntimeError when transport's FD is used with add_reader,
add_writer, etc.

@item 
bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг
Марк.

@item 
bpo-28371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28371}: Deprecate passing asyncio.Handles to run_in_executor.

@item 
bpo-28372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28372}: Fix asyncio to support formatting of non-python coroutines.

@item 
bpo-28399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28399}: Remove UNIX socket from FS before binding. Patch by Коренберг
Марк.

@item 
bpo-27972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27972}: Prohibit Tasks to await on themselves.

@item 
bpo-24142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24142}: Reading a corrupt config file left configparser in an invalid
state. Original patch by Florian Höch.

@item 
bpo-29581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29581}: ABCMeta.__new__ now accepts @code{**kwargs}, allowing abstract
base classes to use keyword parameters in __init_subclass__. Patch by Nate
Soares.

@item 
bpo-25532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25532}: inspect.unwrap() will now only try to unwrap an object
sys.getrecursionlimit() times, to protect against objects which create a
new object on every attribute access.

@item 
bpo-30177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30177}: path.resolve(strict=False) no longer cuts the path after the
first element not present in the filesystem.  Patch by Antoine Pietri.
@end itemize

@node ドキュメント<66>,テスト<62>,ライブラリ<173>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id834}@anchor{1e99}
@subsubsection ドキュメント



@itemize -

@item 
bpo-31294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31294}: Fix incomplete code snippet in the ZeroMQSocketListener and
ZeroMQSocketHandler examples and adapt them to Python 3.

@item 
bpo-21649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21649}: Add RFC 7525 and Mozilla server side TLS links to SSL
documentation.

@item 
bpo-31128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31128}: Allow the pydoc server to bind to arbitrary hostnames.

@item 
bpo-30803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30803}: Clarify doc on truth value testing. Original patch by Peter
Thomassen.

@item 
bpo-30176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30176}: Add missing attribute related constants in curses
documentation.

@item 
bpo-30052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30052}: the link targets for @ref{192,,bytes()} and @ref{344,,bytearray()} are
now their respective type definitions, rather than the corresponding
builtin function entries. Use @ref{1e9a,,bytes} and
@ref{1e9b,,bytearray} to reference the latter. In order to
ensure this and future cross-reference updates are applied automatically,
the daily documentation builds now disable the default output caching
features in Sphinx.

@item 
bpo-26985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26985}: Add missing info of code object in inspect documentation.

@item 
bpo-19824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19824}: Improve the documentation for, and links to, template strings
by emphasizing their utility for internationalization, and by clarifying
some usage constraints. (See also: bpo-20314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20314}, bpo-12518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12518})

@item 
bpo-28929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28929}: Link the documentation to its source file on GitHub.

@item 
bpo-25008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25008}: Document smtpd.py as effectively deprecated and add a pointer
to aiosmtpd, a third-party asyncio-based replacement.

@item 
bpo-26355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26355}: Add canonical header link on each page to corresponding major
version of the documentation. Patch by Matthias Bussonnier.

@item 
bpo-29349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29349}: Fix Python 2 syntax in code for building the documentation.

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: The data model reference and the porting section in the 3.6
What's New guide now cover the additional @code{__classcell__} handling
needed for custom metaclasses to fully support 
@geindex Python Enhancement Proposals; PEP 487
PEP 487@footnote{https://peps.python.org/pep-0487/} and
zero-argument @code{super()}.

@item 
bpo-28513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28513}: Documented command-line interface of zipfile.
@end itemize

@node テスト<62>,ビルド<70>,ドキュメント<66>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id835}@anchor{1e9c}
@subsubsection テスト



@itemize -

@item 
bpo-29639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29639}: test.support.HOST is now "localhost", a new HOSTv4 constant has
been added for your @code{127.0.0.1} needs, similar to the existing HOSTv6
constant.

@item 
bpo-31320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31320}: Silence traceback in test_ssl

@item 
bpo-31346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31346}: Prefer PROTOCOL_TLS_CLIENT and PROTOCOL_TLS_SERVER protocols
for SSLContext.

@item 
bpo-25674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25674}: Remove sha256.tbs-internet.com ssl test

@item 
bpo-30715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30715}: Address ALPN callback changes for OpenSSL 1.1.0f. The latest
version behaves like OpenSSL 1.0.2 and no longer aborts handshake.

@item 
bpo-30822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30822}: regrtest: Exclude tzdata from regrtest --all. When running the
test suite using --use=all / -u all, exclude tzdata since it makes
test_datetime too slow (15-20 min on some buildbots) which then times out
on some buildbots. Fix also regrtest command line parser to allow passing
-u extralargefile to run test_zipfile64.

@item 
bpo-30695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30695}: Add the @code{set_nomemory(start, stop)} and
@code{remove_mem_hooks()} functions to the @code{_testcapi} module.

@item 
bpo-30357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30357}: test_thread: setUp() now uses support.threading_setup() and
support.threading_cleanup() to wait until threads complete to avoid random
side effects on following tests. Initial patch written by Grzegorz
Grzywacz.

@item 
bpo-30197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30197}: Enhanced functions swap_attr() and swap_item() in the
test.support module. They now work when delete replaced attribute or item
inside the with statement.  The old value of the attribute or item (or
None if it doesn't exist) now will be assigned to the target of the "as"
clause, if there is one.

@item 
bpo-24932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24932}: Use proper command line parsing in _testembed

@item 
bpo-28950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28950}: Disallow -j0 to be combined with -T/-l in regrtest command line
arguments.

@item 
bpo-28683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28683}: Fix the tests that bind() a unix socket and raise
PermissionError on Android for a non-root user.

@item 
bpo-26936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26936}: Fix the test_socket failures on Android - getservbyname(),
getservbyport() and getaddrinfo() are broken on some Android API levels.

@item 
bpo-28666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28666}: Now test.support.rmtree is able to remove unwritable or
unreadable directories.

@item 
bpo-23839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23839}: Various caches now are cleared before running every test file.

@item 
bpo-26944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26944}: Fix test_posix for Android where 'id -G' is entirely wrong or
missing the effective gid.

@item 
bpo-28409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28409}: regrtest: fix the parser of command line arguments.

@item 
bpo-28217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28217}: Adds _testconsole module to test console input.

@item 
bpo-26939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26939}: Add the support.setswitchinterval() function to fix
test_functools hanging on the Android armv7 qemu emulator.
@end itemize

@node ビルド<70>,Windows<63>,テスト<62>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id836}@anchor{1e9d}
@subsubsection ビルド



@itemize -

@item 
bpo-31354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31354}: Allow @code{--with-lto} to be used on all builds, not just @code{make
profile-opt}.

@item 
bpo-31370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31370}: Remove support for building --without-threads. This option is
not really useful anymore in the 21st century. Removing lots of
conditional paths allows us to simplify the code base, including in
difficult to maintain low-level internal code.

@item 
bpo-31341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31341}: Per 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/}, support for the IRIX operating system was
removed.

@item 
bpo-30854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30854}: Fix compile error when compiling --without-threads. Patch by
Masayuki Yamamoto.

@item 
bpo-30687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30687}: Locate msbuild.exe on Windows when building rather than
vcvarsall.bat

@item 
bpo-20210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20210}: Support the `disabled' marker in Setup files. Extension modules
listed after this marker are not built at all, neither by the Makefile nor
by setup.py.

@item 
bpo-29941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29941}: Add @code{--with-assertions} configure flag to explicitly enable C
@code{assert()} checks. Defaults to off. @code{--with-pydebug} implies
@code{--with-assertions}.

@item 
bpo-28787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28787}: Fix out-of-tree builds of Python when configured with
@code{--with--dtrace}.

@item 
bpo-29243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29243}: Prevent unnecessary rebuilding of Python during @code{make test},
@code{make install} and some other make targets when configured with
@code{--enable-optimizations}.

@item 
bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404}: Don't regenerate generated files based on file modification
time anymore: the action is now explicit. Replace @code{make touch} with
@code{make regen-all}.

@item 
bpo-29643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29643}: Fix @code{--enable-optimization} didn't work.

@item 
bpo-27593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27593}: sys.version and the platform module python_build(),
python_branch(), and python_revision() functions now use git information
rather than hg when building from a repo.

@item 
bpo-29572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29572}: Update Windows build and OS X installers to use OpenSSL 1.0.2k.

@item 
bpo-27659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27659}: Prohibit implicit C function declarations: use
@code{-Werror=implicit-function-declaration} when possible (GCC and Clang,
but it depends on the compiler version). Patch written by Chi Hsuan Yen.

@item 
bpo-29384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29384}: Remove old Be OS helper scripts.

@item 
bpo-26851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26851}: Set Android compilation and link flags.

@item 
bpo-28768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28768}: Fix implicit declaration of function _setmode. Patch by
Masayuki Yamamoto

@item 
bpo-29080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29080}: Removes hard dependency on hg.exe from PCBuild/build.bat

@item 
bpo-23903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23903}: Added missed names to PC/python3.def.

@item 
bpo-28762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28762}: lockf() is available on Android API level 24, but the F_LOCK
macro is not defined in android-ndk-r13.

@item 
bpo-28538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28538}: Fix the compilation error that occurs because if_nameindex() is
available on Android API level 24, but the if_nameindex structure is not
defined.

@item 
bpo-20211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20211}: Do not add the directory for installing C header files and the
directory for installing object code libraries to the cross compilation
search paths. Original patch by Thomas Petazzoni.

@item 
bpo-28849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28849}: Do not define sys.implementation._multiarch on Android.

@item 
bpo-10656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10656}: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
Michael Haubenwallner.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Rename --with-optimiations to --enable-optimizations.

@item 
bpo-28444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28444}: Fix missing extensions modules when cross compiling.

@item 
bpo-28208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28208}: Update Windows build and OS X installers to use SQLite 3.14.2.

@item 
bpo-28248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28248}: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

@item 
bpo-21124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21124}: Fix building the _struct module on Cygwin by passing @code{NULL}
instead of @code{&PyType_Type} to PyVarObject_HEAD_INIT.  Patch by Masayuki
Yamamoto.

@item 
bpo-13756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13756}: Fix building extensions modules on Cygwin.  Patch by Roumen
Petrov, based on original patch by Jason Tishler.

@item 
bpo-21085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21085}: Add configure check for siginfo_t.si_band, which Cygwin does
not provide. Patch by Masayuki Yamamoto with review and rebase by Erik
Bray.

@item 
bpo-28258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28258}: Fixed build with Estonian locale (python-config and distclean
targets in Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-26661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26661}: setup.py now detects system libffi with multiarch wrapper.

@item 
bpo-27979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27979}: A full copy of libffi is no longer bundled for use when
building _ctypes on non-OSX UNIX platforms.  An installed copy of libffi
is now required when building _ctypes on such platforms.

@item 
bpo-15819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15819}: Remove redundant include search directory option for building
outside the source tree.

@item 
bpo-28676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28676}: Prevent missing 'getentropy' declaration warning on macOS.
Patch by Gareth Rees.
@end itemize

@node Windows<63>,IDLE<45>,ビルド<70>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id837}@anchor{1e9e}
@subsubsection Windows



@itemize -

@item 
bpo-31392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31392}: Update Windows build to use OpenSSL 1.1.0f

@item 
bpo-30389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30389}: Adds detection of Visual Studio 2017 to distutils on Windows.

@item 
bpo-31358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31358}: zlib is no longer bundled in the CPython source, instead it is
downloaded on demand just like bz2, lzma, OpenSSL, Tcl/Tk, and SQLite.

@item 
bpo-31340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31340}: Change to building with MSVC v141 (included with Visual Studio
2017)

@item 
bpo-30581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30581}: os.cpu_count() now returns the correct number of processors on
Windows when the number of logical processors is greater than 64.

@item 
bpo-30916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30916}: Pre-build OpenSSL, Tcl and Tk and include the binaries in the
build.

@item 
bpo-30731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30731}: Add a missing xmlns to python.manifest so that it matches the
schema.

@item 
bpo-30291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30291}: Allow requiring 64-bit interpreters from py.exe using -64
suffix. Contributed by Steve (Gadget) Barnes.

@item 
bpo-30362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30362}: Adds list options (-0, -0p) to py.exe launcher. Contributed by
Steve Barnes.

@item 
bpo-23451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23451}: Fix socket deprecation warnings in socketmodule.c. Patch by
Segev Finer.

@item 
bpo-30450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30450}: The build process on Windows no longer depends on Subversion,
instead pulling external code from GitHub via a Python script.  If Python
3.6 is not found on the system (via @code{py -3.6}), NuGet is used to
download a copy of 32-bit Python.

@item 
bpo-29579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29579}: Removes readme.txt from the installer.

@item 
bpo-25778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25778}: winreg does not truncate string correctly (Patch by Eryk Sun)

@item 
bpo-28896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28896}: Deprecate WindowsRegistryFinder and disable it by default

@item 
bpo-28522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28522}: Fixes mishandled buffer reallocation in getpathp.c

@item 
bpo-28402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28402}: Adds signed catalog files for stdlib on Windows.

@item 
bpo-28333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28333}: Enables Unicode for ps1/ps2 and input() prompts. (Patch by Eryk
Sun)

@item 
bpo-28251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28251}: Improvements to help manuals on Windows.

@item 
bpo-28110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28110}: launcher.msi has different product codes between 32-bit and
64-bit

@item 
bpo-28161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28161}: Opening CON for write access fails

@item 
bpo-28162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28162}: WindowsConsoleIO readall() fails if first line starts with
Ctrl+Z

@item 
bpo-28163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28163}: WindowsConsoleIO fileno() passes wrong flags to _open_osfhandle

@item 
bpo-28164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28164}: _PyIO_get_console_type fails for various paths

@item 
bpo-28137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28137}: Renames Windows path file to ._pth

@item 
bpo-28138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28138}: Windows ._pth file should allow import site
@end itemize

@node IDLE<45>,Tools/Demos<43>,Windows<63>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id838}@anchor{1e9f}
@subsubsection IDLE



@itemize -

@item 
bpo-31493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31493}: IDLE code context -- fix code update and font update timers.
Canceling timers prevents a warning message when test_idle completes.

@item 
bpo-31488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31488}: IDLE - Update non-key options in former extension classes. When
applying configdialog changes, call .reload for each feature class. Change
ParenMatch so updated options affect existing instances attached to
existing editor windows.

@item 
bpo-31477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31477}: IDLE - Improve rstrip entry in doc. Strip trailing whitespace
strips more than blank spaces.  Multiline string literals are not skipped.

@item 
bpo-31480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31480}: IDLE - make tests pass with zzdummy extension disabled by
default.

@item 
bpo-31421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31421}: Document how IDLE runs tkinter programs. IDLE calls tcl/tk
update in the background in order to make live interaction and
experimentation with tkinter applications much easier.

@item 
bpo-31414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31414}: IDLE -- fix tk entry box tests by deleting first. Adding to an
int entry is not the same as deleting and inserting because int('@w{'}) will
fail.

@item 
bpo-31051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31051}: Rearrange IDLE configdialog GenPage into Window, Editor, and
Help sections.

@item 
bpo-30617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30617}: IDLE - Add docstrings and tests for outwin subclass of editor.
Move some data and functions from the class to module level. Patch by
Cheryl Sabella.

@item 
bpo-31287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31287}: IDLE - Do not modify tkinter.message in test_configdialog.

@item 
bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099}: Convert IDLE's built-in 'extensions' to regular features. About
10 IDLE features were implemented as supposedly optional extensions. Their
different behavior could be confusing or worse for users and not good for
maintenance. Hence the conversion. The main difference for users is that
user configurable key bindings for builtin features are now handled
uniformly. Now, editing a binding in a keyset only affects its value in
the keyset. All bindings are defined together in the system-specific
default keysets in config-extensions.def. All custom keysets are saved as
a whole in config-extension.cfg.  All take effect as soon as one clicks
Apply or Ok. The affected events are '<<force-open-completions>>',
'<<expand-word>>', '<<force-open-calltip>>', '<<flash-paren>>',
'<<format-paragraph>>', '<<run-module>>', '<<check-module>>', and
'<<zoom-height>>'.  Any (global) customizations made before 3.6.3 will not
affect their keyset-specific customization after 3.6.3. and vice versa.
Initial patch by Charles Wohlganger.

@item 
bpo-31206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31206}: IDLE: Factor HighPage(Frame) class from ConfigDialog. Patch by
Cheryl Sabella.

@item 
bpo-31001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31001}: Add tests for configdialog highlight tab.  Patch by Cheryl
Sabella.

@item 
bpo-31205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31205}: IDLE: Factor KeysPage(Frame) class from ConfigDialog.  The
slightly modified tests continue to pass.  Patch by Cheryl Sabella.

@item 
bpo-31130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31130}: IDLE -- stop leaks in test_configdialog. Initial patch by
Victor Stinner.

@item 
bpo-31002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31002}: Add tests for configdialog keys tab. Patch by Cheryl Sabella.

@item 
bpo-19903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19903}: IDLE: Calltips use @code{inspect.signature} instead of
@code{inspect.getfullargspec}. This improves calltips for builtins converted
to use Argument Clinic. Patch by Louie Lu.

@item 
bpo-31083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31083}: IDLE - Add an outline of a TabPage class in configdialog.
Update existing classes to match outline. Initial patch by Cheryl Sabella.

@item 
bpo-31050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31050}: Factor GenPage(Frame) class from ConfigDialog. The slightly
modified tests continue to pass. Patch by Cheryl Sabella.

@item 
bpo-31004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31004}: IDLE - Factor FontPage(Frame) class from ConfigDialog. Slightly
modified tests continue to pass. Fix General tests. Patch mostly by Cheryl
Sabella.

@item 
bpo-30781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30781}: IDLE - Use ttk widgets in ConfigDialog. Patches by Terry Jan
Reedy and Cheryl Sabella.

@item 
bpo-31060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31060}: IDLE - Finish rearranging methods of ConfigDialog Grouping
methods pertaining to each tab and the buttons will aid writing tests and
improving the tabs and will enable splitting the groups into classes.

@item 
bpo-30853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30853}: IDLE -- Factor a VarTrace class out of ConfigDialog. Instance
tracers manages pairs consisting of a tk variable and a callback function.
When tracing is turned on, setting the variable calls the function.  Test
coverage for the new class is 100%.

@item 
bpo-31003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31003}: IDLE: Add more tests for General tab.

@item 
bpo-30993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30993}: IDLE - Improve configdialog font page and tests. In
configdialog: Document causal pathways in create_font_tab docstring.
Simplify some attribute names. Move set_samples calls to var_changed_font
(idea from Cheryl Sabella).  Move related functions to positions after the
create widgets function. In test_configdialog: Fix test_font_set so not
order dependent.  Fix renamed test_indent_scale so it tests the widget.
Adjust tests for movement of set_samples call.  Add tests for load
functions.  Put all font tests in one class and tab indent tests in
another.  Except for two lines, these tests completely cover the related
functions.

@item 
bpo-30981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30981}: IDLE -- Add more configdialog font page tests.

@item 
bpo-28523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28523}: IDLE: replace 'colour' with 'color' in configdialog.

@item 
bpo-30917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30917}: Add tests for idlelib.config.IdleConf. Increase coverage from
46% to 96%. Patch by Louie Lu.

@item 
bpo-30934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30934}: Document coverage details for idlelib tests. Add section to
idlelib/idle-test/README.txt. Include check that branches are taken both
ways. Exclude IDLE-specific code that does not run during unit tests.

@item 
bpo-30913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30913}: IDLE: Document ConfigDialog tk Vars, methods, and widgets in
docstrings This will facilitate improving the dialog and splitting up the
class. Original patch by Cheryl Sabella.

@item 
bpo-30899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30899}: IDLE: Add tests for ConfigParser subclasses in config. Patch by
Louie Lu.

@item 
bpo-30881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30881}: IDLE: Add docstrings to browser.py. Patch by Cheryl Sabella.

@item 
bpo-30851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30851}: IDLE: Remove unused variables in configdialog.  One is a
duplicate, one is set but cannot be altered by users. Patch by Cheryl
Sabella.

@item 
bpo-30870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30870}: IDLE: In Settings dialog, select font with Up, Down keys as
well as mouse. Initial patch by Louie Lu.

@item 
bpo-8231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8231}: IDLE: call config.IdleConf.GetUserCfgDir only once.

@item 
bpo-30779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30779}: IDLE: Factor ConfigChanges class from configdialog, put in
config; test. * In config, put dump test code in a function; run it and
unittest in   'if __name__ == '__main__'. * Add class config.ConfigChanges
based on changes_class_v4.py on bpo issue. * Add class
test_config.ChangesTest, partly using configdialog_tests_v1.py. * Revise
configdialog to use ConfigChanges; see tracker msg297804. * Revise
test_configdialog to match configdialog changes. * Remove configdialog
functions unused or moved to ConfigChanges. Cheryl Sabella contributed
parts of the patch.

@item 
bpo-30777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30777}: IDLE: configdialog - Add docstrings and fix comments. Patch by
Cheryl Sabella.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: IDLE: Improve textview with docstrings, PEP8 names, and more
tests. Patch by Cheryl Sabella.

@item 
bpo-30723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30723}: IDLE: Make several improvements to parenmatch. Add 'parens'
style to highlight both opener and closer. Make 'default' style, which is
not default, a synonym for 'opener'. Make time-delay work the same with
all styles. Add help for config dialog extensions tab, including help for
parenmatch. Add new tests.  Original patch by Charles Wohlganger.

@item 
bpo-30674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30674}: IDLE: add docstrings to grep module. Patch by Cheryl Sabella

@item 
bpo-21519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21519}: IDLE's basic custom key entry dialog now detects duplicates
properly. Original patch by Saimadhav Heblikar.

@item 
bpo-29910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29910}: IDLE no longer deletes a character after commenting out a
region by a key shortcut.  Add @code{return 'break'} for this and other
potential conflicts between IDLE and default key bindings.

@item 
bpo-30728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30728}: Review and change idlelib.configdialog names. Lowercase method
and attribute names. Replace 'colour' with 'color', expand overly cryptic
names, delete unneeded underscores. Replace @code{import *} with specific
imports. Patches by Cheryl Sabella.

@item 
bpo-6739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6739}: IDLE: Verify user-entered key sequences by trying to bind them
with tk. Add tests for all 3 validation functions. Original patch by G
Polo.  Tests added by Cheryl Sabella.

@item 
bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786}: Fix several problems with IDLE's autocompletion box. The
following should now work: clicking on selection box items; using the
scrollbar; selecting an item by hitting Return. Hangs on MacOSX should no
longer happen. Patch by Louie Lu.

@item 
bpo-25514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25514}: Add doc subsubsection about IDLE failure to start. Popup
no-connection message directs users to this section.

@item 
bpo-30642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30642}: Fix reference leaks in IDLE tests. Patches by Louie Lu and
Terry Jan Reedy.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: Add docstrings for textview.py and use PEP8 names. Patches by
Cheryl Sabella and Terry Jan Reedy.

@item 
bpo-30290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30290}: Help-about: use pep8 names and add tests. Increase coverage to
100%. Patches by Louie Lu, Cheryl Sabella, and Terry Jan Reedy.

@item 
bpo-30303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30303}: Add _utest option to textview; add new tests. Increase coverage
to 100%. Patches by Louie Lu and Terry Jan Reedy.

@item 
bpo-29071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29071}: IDLE colors f-string prefixes (but not invalid ur prefixes).

@item 
bpo-28572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28572}: Add 10% to coverage of IDLE's test_configdialog. Update and
augment description of the configuration system.
@end itemize

@node Tools/Demos<43>,C API<63>,IDLE<45>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id839}@anchor{1ea0}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-30983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30983}: gdb integration commands (py-bt, etc.) work on optimized shared
builds now, too.  
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/} introduced _PyEval_EvalFrameDefault which
inlines PyEval_EvalFrameEx on non-debug shared builds.  This broke the
ability to use py-bt, py-up, and a few other Python-specific gdb
integrations. The problem is fixed by only looking for
_PyEval_EvalFrameDefault frames in python-gdb.py.  Original patch by Bruno
"Polaco" Penteado.

@item 
bpo-29748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29748}: Added the slice index converter in Argument Clinic.

@item 
bpo-24037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24037}: Argument Clinic now uses the converter @code{bool(accept=@{int@})}
rather than @code{int} for semantical booleans.  This avoids repeating the
default value for Python and C and will help in converting to @code{bool} in
future.

@item 
bpo-29367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29367}: python-gdb.py now supports also @code{method-wrapper}
(@code{wrapperobject}) objects.

@item 
bpo-28023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28023}: Fix python-gdb.py didn't support new dict implementation.

@item 
bpo-15369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15369}: The pybench and pystone microbenchmark have been removed from
Tools. Please use the new Python benchmark suite
@indicateurl{https://github.com/python/pyperformance} which is more reliable and
includes a portable version of pybench working on Python 2 and Python 3.

@item 
bpo-28102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28102}: The zipfile module CLI now prints usage to stderr. Patch by
Stephen J. Turnbull.
@end itemize

@node C API<63>,,Tools/Demos<43>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id840}@anchor{1ea1}
@subsubsection C API



@itemize -

@item 
bpo-31338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31338}: Added the @code{Py_UNREACHABLE()} macro for code paths which are
never expected to be reached.  This and a few other useful macros are now
documented in the C API manual.

@item 
bpo-30832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30832}: Remove own implementation for thread-local storage. CPython has
provided the own implementation for thread-local storage (TLS) on
Python/thread.c, it's used in the case which a platform has not supplied
native TLS.  However, currently all supported platforms (Windows and
pthreads) have provided native TLS and defined the Py_HAVE_NATIVE_TLS
macro with unconditional in any case.

@item 
bpo-30708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30708}: PyUnicode_AsWideCharString() now raises a ValueError if the
second argument is NULL and the wchar_t* string contains null characters.

@item 
bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500}: Deprecate PyOS_AfterFork() and add PyOS_BeforeFork(),
PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().

@item 
bpo-6532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6532}: The type of results of PyThread_start_new_thread() and
PyThread_get_thread_ident(), and the id parameter of
PyThreadState_SetAsyncExc() changed from "long" to "unsigned long".

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() is deprecated and replaced with
a macro if Py_LIMITED_API is not set or set to the value between
0x03050400 and 0x03060000 (not including) or 0x03060100 or higher.  Added
functions PySlice_Unpack() and PySlice_AdjustIndices().

@item 
bpo-29083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29083}: Fixed the declaration of some public API functions.
PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in
limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and
Py_BuildValue() were not available in limited API of version < 3.3 when
PY_SSIZE_T_CLEAN is defined.

@item 
bpo-28769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28769}: The result of PyUnicode_AsUTF8AndSize() and PyUnicode_AsUTF8()
is now of type @code{const char *} rather of @code{char *}.

@item 
bpo-29058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29058}: All stable API extensions added after Python 3.2 are now
available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of
the minimum Python version supporting this API.

@item 
bpo-28822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28822}: The index parameters `start' and `end' of PyUnicode_FindChar()
are now adjusted to behave like @code{str[start:end]}.

@item 
bpo-28808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28808}: PyUnicode_CompareWithASCIIString() now never raises exceptions.

@item 
bpo-28761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28761}: The fields name and doc of structures PyMemberDef, PyGetSetDef,
PyStructSequence_Field, PyStructSequence_Desc, and wrapperbase are now of
type @code{const char *} rather of @code{char *}.

@item 
bpo-28748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28748}: Private variable _Py_PackageContext is now of type @code{const char
*} rather of @code{char *}.

@item 
bpo-19569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19569}: Compiler warnings are now emitted if use most of deprecated
functions.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Deprecated undocumented functions PyUnicode_AsEncodedObject(),
PyUnicode_AsDecodedObject(), PyUnicode_AsDecodedUnicode() and
PyUnicode_AsEncodedUnicode().
@end itemize

@node Python 3 6 6 final,Python 3 6 6 release candidate 1,Python 3 7 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-6-6-final}@anchor{1ea2}
@subsection Python 3.6.6 final


`Release date: 2018-06-27'

There were no new changes in version 3.6.6.

@node Python 3 6 6 release candidate 1,Python 3 6 5 final,Python 3 6 6 final,変更履歴
@anchor{whatsnew/changelog python-3-6-6-release-candidate-1}@anchor{1ea3}
@subsection Python 3.6.6 release candidate 1


`Release date: 2018-06-11'

@menu
* Core and Builtins: Core and Builtins<170>. 
* ライブラリ: ライブラリ<174>. 
* ドキュメント: ドキュメント<67>. 
* テスト: テスト<63>. 
* ビルド: ビルド<71>. 
* Windows: Windows<64>. 
* macOS: macOS<49>. 
* IDLE: IDLE<46>. 
* Tools/Demos: Tools/Demos<44>. 
* C API: C API<64>. 

@end menu

@node Core and Builtins<170>,ライブラリ<174>,,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id841}@anchor{1ea4}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33786}: Fix asynchronous generators to handle GeneratorExit in athrow()
correctly

@item 
bpo-30654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30654}: Fixed reset of the SIGINT handler to SIG_DFL on interpreter
shutdown even when there was a custom handler set previously. Patch by
Philipp Kerling.

@item 
bpo-33622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33622}: Fixed a leak when the garbage collector fails to add an object
with the @code{__del__} method or referenced by it into the
@ref{13d9,,gc.garbage} list. @ref{b85,,PyGC_Collect()} can now be called when an
exception is set and preserves it.

@item 
bpo-31849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31849}: Fix signed/unsigned comparison warning in pyhash.c.

@item 
bpo-33391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33391}: Fix a leak in set_symmetric_difference().

@item 
bpo-28055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28055}: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

@item 
bpo-33231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33231}: Fix potential memory leak in @code{normalizestring()}.

@item 
bpo-29922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29922}: Improved error messages in 'async with' when @code{__aenter__()}
or @code{__aexit__()} return non-awaitable object.

@item 
bpo-33199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33199}: Fix @code{ma_version_tag} in dict implementation is uninitialized
when copying from key-sharing dict.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Fixed jumping when the function contains an @code{async for} loop.

@item 
bpo-32282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32282}: Fix an unnecessary ifdef in the include of VersionHelpers.h in
socketmodule on Windows.

@item 
bpo-21983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21983}: Fix a crash in @code{ctypes.cast()} in case the type argument is a
ctypes structured data type. Patch by Eryk Sun and Oren Milman.
@end itemize

@node ライブラリ<174>,ドキュメント<67>,Core and Builtins<170>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id842}@anchor{1ea5}
@subsubsection ライブラリ



@itemize -

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by
Steve Weber.

@item 
bpo-33812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33812}: Datetime instance d with non-None tzinfo, but with
d.tzinfo.utcoffset(d) returning None is now treated as naive by the
astimezone() method.

@item 
bpo-30805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30805}: Avoid race condition with debug logging

@item 
bpo-33767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33767}: The concatenation (@code{+}) and repetition (@code{*}) sequence
operations now raise @ref{198,,TypeError} instead of @ref{795,,SystemError} when
performed on @ref{519,,mmap.mmap} objects.  Patch by Zackery Spytz.

@item 
bpo-32684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32684}: Fix gather to propagate cancellation of itself even with
return_exceptions.

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Fix a race condition in SSLProtocol.connection_made() of
asyncio.sslproto: start immediately the handshake instead of using
call_soon(). Previously, data_received() could be called before the
handshake started, causing the handshake to hang or fail.

@item 
bpo-31647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31647}: Fixed bug where calling write_eof() on a
_SelectorSocketTransport after it's already closed raises AttributeError.

@item 
bpo-33672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33672}: Fix Task.__repr__ crash with Cython's bogus coroutines

@item 
bpo-33469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33469}: Fix RuntimeError after closing loop that used run_in_executor

@item 
bpo-11874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11874}: Use a better regex when breaking usage into wrappable parts.
Avoids bogus assertion errors from custom metavar strings.

@item 
bpo-30877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30877}: Fixed a bug in the Python implementation of the JSON decoder
that prevented the cache of parsed strings from clearing after finishing
the decoding. Based on patch by c-fos.

@item 
bpo-33548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33548}: tempfile._candidate_tempdir_list should consider common TEMP
locations

@item 
bpo-33542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33542}: Prevent @code{uuid.get_node} from using a DUID instead of a MAC on
Windows. Patch by Zvi Effron

@item 
bpo-26819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26819}: Fix race condition with @code{ReadTransport.resume_reading} in
Windows proactor event loop.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Minor fixes in typing module: add annotations to
@code{NamedTuple.__new__}, pass @code{*args} and @code{**kwds} in
@code{Generic.__new__}.  Original PRs by Paulius Šarka and Chad Dombrova.

@item 
bpo-20087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20087}: Updated alias mapping with glibc 2.27 supported locales.

@item 
bpo-33422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33422}: Fix trailing quotation marks getting deleted when looking up
byte/string literals on pydoc. Patch by Andrés Delfino.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Update error message when constructing invalid
inspect.Parameters Patch by Donghee Na.

@item 
bpo-33383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33383}: Fixed crash in the get() method of the @ref{38,,dbm.ndbm} database
object when it is called with a single argument.

@item 
bpo-33329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33329}: Fix multiprocessing regression on newer glibcs

@item 
bpo-991266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=991266}: Fix quoting of the @code{Comment} attribute of
@ref{1e24,,http.cookies.SimpleCookie}.

@item 
bpo-33131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33131}: Upgrade bundled version of pip to 10.0.1.

@item 
bpo-33308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33308}: Fixed a crash in the @code{parser} module when converting an ST
object to a tree of tuples or lists with @code{line_info=False} and
@code{col_info=True}.

@item 
bpo-33263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33263}: Fix FD leak in @code{_SelectorSocketTransport}  Patch by Vlad
Starostin.

@item 
bpo-33256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33256}: Fix display of @code{<module>} call in the html produced by
@code{cgitb.html()}. Patch by Stéphane Blondon.

@item 
bpo-33203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33203}: @code{random.Random.choice()} now raises @code{IndexError} for empty
sequences consistently even when called from subclasses without a
@code{getrandbits()} implementation.

@item 
bpo-33224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33224}: Update difflib.mdiff() for 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/}.  Convert an uncaught
StopIteration in a generator into a return-statement.

@item 
bpo-33209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33209}: End framing at the end of C implementation of
@ref{1e25,,pickle.Pickler.dump()}.

@item 
bpo-32861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32861}: The urllib.robotparser's @code{__str__} representation now
includes wildcard entries and the "Crawl-delay" and "Request-rate" fields.
Patch by Michael Lazar.

@item 
bpo-33096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33096}: Allow ttk.Treeview.insert to insert iid that has a false
boolean value. Note iid=0 and iid=False would be same. Patch by Garvit
Khatri.

@item 
bpo-33127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33127}: The ssl module now compiles with LibreSSL 2.7.1.

@item 
bpo-33021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33021}: Release the GIL during fstat() calls, avoiding hang of all
threads when calling mmap.mmap(), os.urandom(), and random.seed().  Patch
by Nir Soffer.

@item 
bpo-27683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27683}: Fix a regression in @ref{84,,ipaddress} that result of
@code{hosts()} is empty when the network is constructed by a tuple
containing an integer mask and only 1 bit left for addresses.

@item 
bpo-32844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32844}: Fix wrong redirection of a low descriptor (0 or 1) to stderr in
subprocess if another low descriptor is closed.

@item 
bpo-31908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31908}: Fix output of cover files for @code{trace} module command-line
tool. Previously emitted cover files only when @code{--missing} option was
used. Patch by Michael Selik.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: If nested log adapters are used, the inner @code{process()}
methods are no longer omitted.

@item 
bpo-16865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16865}: Support arrays >=2GiB in @ref{2e,,ctypes}.  Patch by Segev Finer.

@item 
bpo-31238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31238}: pydoc: the stop() method of the private ServerThread class now
waits until DocServer.serve_until_quit() completes and then explicitly
sets its docserver attribute to None to break a reference cycle.
@end itemize

@node ドキュメント<67>,テスト<63>,ライブラリ<174>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id843}@anchor{1ea6}
@subsubsection ドキュメント



@itemize -

@item 
bpo-33503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33503}: Fix broken pypi link

@item 
bpo-33421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33421}: Add missing documentation for @code{typing.AsyncContextManager}.

@item 
bpo-33378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33378}: Add Korean language switcher for @indicateurl{https://docs.python.org/3/}

@item 
bpo-33276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33276}: Clarify that the @code{__path__} attribute on modules cannot be
just any value.

@item 
bpo-33201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33201}: Modernize documentation for writing C extension types.

@item 
bpo-33195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33195}: Deprecate @code{Py_UNICODE} usage in @code{c-api/arg} document.
@code{Py_UNICODE} related APIs are deprecated since Python 3.3, but it is
missed in the document.

@item 
bpo-33126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33126}: Document PyBuffer_ToContiguous().

@item 
bpo-27212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27212}: Modify documentation for the @code{islice()} recipe to consume
initial values up to the start index.

@item 
bpo-28247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28247}: Update @ref{136,,zipapp} documentation to describe how to make
standalone applications.

@item 
bpo-18802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18802}: Documentation changes for ipaddress.  Patch by Jon Foster and
Berker Peksag.

@item 
bpo-27428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27428}: Update documentation to clarify that @code{WindowsRegistryFinder}
implements @code{MetaPathFinder}. (Patch by Himanshu Lakhara)

@item 
bpo-8243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8243}: Add a note about curses.addch and curses.addstr exception
behavior when writing outside a window, or pad.

@item 
bpo-31432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31432}: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED
flags for ssl.SSLContext.verify_mode.
@end itemize

@node テスト<63>,ビルド<71>,ドキュメント<67>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id844}@anchor{1ea7}
@subsubsection テスト



@itemize -

@item 
bpo-33655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33655}: Ignore test_posix_fallocate failures on BSD platforms that
might be due to running on ZFS.

@item 
bpo-19417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19417}: Add test_bdb.py.
@end itemize

@node ビルド<71>,Windows<64>,テスト<63>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id845}@anchor{1ea8}
@subsubsection ビルド



@itemize -

@item 
bpo-5755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5755}: Move @code{-Wstrict-prototypes} option to @code{CFLAGS_NODIST} from
@code{OPT}. This option emitted annoying warnings when building extension
modules written in C++.

@item 
bpo-33614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33614}: Ensures module definition files for the stable ABI on Windows
are correctly regenerated.

@item 
bpo-33522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33522}: Enable CI builds on Visual Studio Team Services at
@indicateurl{https://python.visualstudio.com/cpython}

@item 
bpo-33012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33012}: Add @code{-Wno-cast-function-type} for gcc 8 for silencing
warnings about function casts like casting to PyCFunction in method
definition lists.

@item 
bpo-33394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33394}: Enable the verbose build for extension modules, when GNU make
is passed macros on the command line.
@end itemize

@node Windows<64>,macOS<49>,ビルド<71>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id846}@anchor{1ea9}
@subsubsection Windows



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update Windows installer to OpenSSL 1.0.2o.
@end itemize

@node macOS<49>,IDLE<46>,Windows<64>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id847}@anchor{1eaa}
@subsubsection macOS



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update macOS installer build to use OpenSSL 1.0.2o.
@end itemize

@node IDLE<46>,Tools/Demos<44>,macOS<49>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id848}@anchor{1eab}
@subsubsection IDLE



@itemize -

@item 
bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}: On Windows, add API call saying that tk scales for DPI. On
Windows 8.1+ or 10, with DPI compatibility properties of the Python binary
unchanged, and a monitor resolution greater than 96 DPI, this should make
text and lines sharper.  It should otherwise have no effect.

@item 
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}: Clicking on a context line moves that line to the top of the
editor window.

@item 
bpo-33763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33763}: IDLE: Use read-only text widget for code context instead of
label widget.

@item 
bpo-33664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33664}: Scroll IDLE editor text by lines. Previously, the mouse wheel
and scrollbar slider moved text by a fixed number of pixels, resulting in
partial lines at the top of the editor box.  The change also applies to
the shell and grep output windows, but not to read-only text views.

@item 
bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}: Enable theme-specific color configuration for Code Context. Use
the Highlights tab to see the setting for built-in themes or add settings
to custom themes.

@item 
bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}: Display up to maxlines non-blank lines for Code Context. If
there is no current context, show a single blank line.

@item 
bpo-33628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33628}: IDLE: Cleanup codecontext.py and its test.

@item 
bpo-33564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33564}: IDLE's code context now recognizes async as a block opener.

@item 
bpo-29706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29706}: IDLE now colors async and await as keywords in 3.6. They become
full keywords in 3.7.

@item 
bpo-21474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21474}: Update word/identifier definition from ascii to unicode. In
text and entry boxes, this affects selection by double-click, movement
left/right by control-left/right, and deletion left/right by
control-BACKSPACE/DEL.

@item 
bpo-33204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33204}: IDLE: consistently color invalid string prefixes. A 'u' string
prefix cannot be paired with either 'r' or 'f'. Consistently color as much
of the prefix, starting at the right, as is valid. Revise and extend
colorizer test.

@item 
bpo-32831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32831}: Add docstrings and tests for codecontext.
@end itemize

@node Tools/Demos<44>,C API<64>,IDLE<46>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id849}@anchor{1eac}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-33189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33189}: @code{pygettext.py} now recognizes only literal strings as
docstrings and translatable strings, and rejects bytes literals and
f-string expressions.

@item 
bpo-31920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31920}: Fixed handling directories as arguments in the @code{pygettext}
script. Based on patch by Oleg Krasnikov.

@item 
bpo-29673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29673}: Fix pystackv and pystack gdbinit macros.

@item 
bpo-32885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32885}: Add an @code{-n} flag for @code{Tools/scripts/pathfix.py} to disable
automatic backup creation (files with @code{~} suffix).

@item 
bpo-31583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31583}: Fix 2to3 for using with --add-suffix option but without
--output-dir option for relative path to files in current directory.
@end itemize

@node C API<64>,,Tools/Demos<44>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id850}@anchor{1ead}
@subsubsection C API



@itemize -

@item 
bpo-32374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32374}: Document that m_traverse for multi-phase initialized modules
can be called with m_state=NULL, and add a sanity check
@end itemize

@node Python 3 6 5 final,Python 3 6 5 release candidate 1,Python 3 6 6 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-6-5-final}@anchor{1eae}
@subsection Python 3.6.5 final


`Release date: 2018-03-28'

@menu
* テスト: テスト<64>. 
* ビルド: ビルド<72>. 

@end menu

@node テスト<64>,ビルド<72>,,Python 3 6 5 final
@anchor{whatsnew/changelog id851}@anchor{1eaf}
@subsubsection テスト



@itemize -

@item 
bpo-32872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32872}: Avoid regrtest compatibility issue with namespace packages.
@end itemize

@node ビルド<72>,,テスト<64>,Python 3 6 5 final
@anchor{whatsnew/changelog id852}@anchor{1eb0}
@subsubsection ビルド



@itemize -

@item 
bpo-33163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33163}: Upgrade pip to 9.0.3 and setuptools to v39.0.1.
@end itemize

@node Python 3 6 5 release candidate 1,Python 3 6 4 final,Python 3 6 5 final,変更履歴
@anchor{whatsnew/changelog python-3-6-5-release-candidate-1}@anchor{1eb1}
@subsection Python 3.6.5 release candidate 1


`Release date: 2018-03-13'

@menu
* セキュリティ: セキュリティ<50>. 
* Core and Builtins: Core and Builtins<171>. 
* ライブラリ: ライブラリ<175>. 
* ドキュメント: ドキュメント<68>. 
* テスト: テスト<65>. 
* ビルド: ビルド<73>. 
* Windows: Windows<65>. 
* macOS: macOS<50>. 
* IDLE: IDLE<47>. 
* Tools/Demos: Tools/Demos<45>. 
* C API: C API<65>. 

@end menu

@node セキュリティ<50>,Core and Builtins<171>,,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id853}@anchor{1eb2}
@subsubsection セキュリティ



@itemize -

@item 
bpo-33001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33001}: Minimal fix to prevent buffer overrun in os.symlink on Windows

@item 
bpo-32981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32981}: Regexes in difflib and poplib were vulnerable to catastrophic
backtracking. These regexes formed potential DOS vectors (REDOS). They
have been refactored. This resolves 
@geindex Common Vulnerabilities and Exposures; CVE 2018-1060
CVE 2018-1060@footnote{https://www.cve.org/CVERecord?id=CVE-2018-1060} and 
@geindex Common Vulnerabilities and Exposures; CVE 2018-1061
CVE 2018-1061@footnote{https://www.cve.org/CVERecord?id=CVE-2018-1061}.
Patch by Jamie Davis.
@end itemize

@node Core and Builtins<171>,ライブラリ<175>,セキュリティ<50>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id854}@anchor{1eb3}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33026}: Fixed jumping out of "with" block by setting f_lineno.

@item 
bpo-17288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17288}: Prevent jumps from 'return' and 'exception' trace events.

@item 
bpo-32889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32889}: Update Valgrind suppression list to account for the rename of
@code{Py_ADDRESS_IN_RANG} to @code{address_in_range}.

@item 
bpo-32650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32650}: Pdb and other debuggers dependent on bdb.py will correctly step
over (next command) native coroutines. Patch by Pablo Galindo.

@item 
bpo-32685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32685}: Improve suggestion when the Python 2 form of print statement is
either present on the same line as the header of a compound statement or
else terminated by a semi-colon instead of a newline. Patch by Nitish
Chandra.

@item 
bpo-32583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32583}: Fix possible crashing in builtin Unicode decoders caused by
write out-of-bound errors when using customized decode error handlers.

@item 
bpo-26163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26163}: Improved frozenset() hash to create more distinct hash values
when faced with datasets containing many similar values.

@item 
bpo-27169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27169}: The @code{__debug__} constant is now optimized out at compile
time. This fixes also bpo-22091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22091}.

@item 
bpo-32329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32329}: @code{sys.flags.hash_randomization} is now properly set to 0 when
hash randomization is turned off by @code{PYTHONHASHSEED=0}.

@item 
bpo-30416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30416}: The optimizer is now protected from spending much time doing
complex calculations and consuming much memory for creating large
constants in constant folding.

@item 
bpo-18533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18533}: @code{repr()} on a dict containing its own @code{values()} or
@code{items()} no longer raises @code{RecursionError}; OrderedDict similarly.
Instead, use @code{...}, as for other recursive structures.  Patch by Ben
North.

@item 
bpo-32028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32028}: Leading whitespace is now correctly ignored when generating
suggestions for converting Py2 print statements to Py3 builtin print
function calls. Patch by Sanyam Khurana.

@item 
bpo-32137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32137}: The repr of deeply nested dict now raises a RecursionError
instead of crashing due to a stack overflow.
@end itemize

@node ライブラリ<175>,ドキュメント<68>,Core and Builtins<171>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id855}@anchor{1eb4}
@subsubsection ライブラリ



@itemize -

@item 
bpo-33064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33064}: lib2to3 now properly supports trailing commas after @code{*args}
and @code{**kwargs} in function signatures.

@item 
bpo-31804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31804}: Avoid failing in multiprocessing.Process if the standard
streams are closed or None at exit.

@item 
bpo-33037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33037}: Skip sending/receiving data after SSL transport closing.

@item 
bpo-30353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30353}: Fix ctypes pass-by-value for structs on 64-bit Cygwin/MinGW.

@item 
bpo-33009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33009}: Fix inspect.signature() for single-parameter partialmethods.

@item 
bpo-32969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32969}: Expose several missing constants in zlib and fix corresponding
documentation.

@item 
bpo-32713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32713}: Fixed tarfile.itn handling of out-of-bounds float values. Patch
by Joffrey Fuhrer.

@item 
bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622}: The ssl module now detects missing NPN support in LibreSSL.

@item 
bpo-32922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32922}: dbm.open() now encodes filename with the filesystem encoding
rather than default encoding.

@item 
bpo-32859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32859}: In @code{os.dup2}, don't check every call whether the @code{dup3}
syscall exists or not.

@item 
bpo-21060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21060}: Rewrite confusing message from setup.py upload from "No dist
file created in earlier command" to the more helpful "Must create and
upload files in one command".

@item 
bpo-32857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32857}: In @ref{f6,,tkinter}, @code{after_cancel(None)} now raises a
@ref{2ec,,ValueError} instead of canceling the first scheduled function.
Patch by Cheryl Sabella.

@item 
bpo-32852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32852}: Make sure sys.argv remains as a list when running trace.

@item 
bpo-32841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32841}: Fixed @code{asyncio.Condition} issue which silently ignored
cancellation after notifying and cancelling a conditional lock. Patch by
Bar Harel.

@item 
bpo-31787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31787}: Fixed refleaks of @code{__init__()} methods in various modules.
(Contributed by Oren Milman)

@item 
bpo-30157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30157}: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when
only the last field is quoted.  Patch by Jake Davis.

@item 
bpo-32394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32394}: socket: Remove TCP_FASTOPEN, TCP_KEEPCNT flags on older version
Windows during run-time.

@item 
bpo-32777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32777}: Fix a rare but potential pre-exec child process deadlock in
subprocess on POSIX systems when marking file descriptors inheritable on
exec in the child process.  This bug appears to have been introduced in
3.4.

@item 
bpo-32647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32647}: The ctypes module used to depend on indirect linking for
dlopen. The shared extension is now explicitly linked against libdl on
platforms with dl.

@item 
bpo-32734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32734}: Fixed @code{asyncio.Lock()} safety issue which allowed acquiring
and locking the same lock multiple times, without it being free. Patch by
Bar Harel.

@item 
bpo-32727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32727}: Do not include name field in SMTP envelope from address. Patch
by Stéphane Wirtel

@item 
bpo-27931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27931}: Fix email address header parsing error when the username is an
empty quoted string. Patch by Xiang Zhang.

@item 
bpo-32304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32304}: distutils' upload command no longer corrupts tar files ending
with a CR byte, and no longer tries to convert CR to CRLF in any of the
upload text fields.

@item 
bpo-32502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32502}: uuid.uuid1 no longer raises an exception if a 64-bit hardware
address is encountered.

@item 
bpo-31848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31848}: Fix the error handling in Aifc_read.initfp() when the SSND
chunk is not found. Patch by Zackery Spytz.

@item 
bpo-32555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32555}: On FreeBSD and Solaris, os.strerror() now always decode the
byte string from the current locale encoding, rather than using
ASCII/surrogateescape in some cases.

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: The nis module is now compatible with new libnsl and headers
location.

@item 
bpo-32473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32473}: Improve ABCMeta._dump_registry() output readability

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: glibc has removed Sun RPC. Use replacement libtirpc headers and
library in nis module.

@item 
bpo-32228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32228}: Ensure that @code{truncate()} preserves the file position (as
reported by @code{tell()}) after writes longer than the buffer size.

@item 
bpo-26133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26133}: Don't unsubscribe signals in asyncio UNIX event loop on
interpreter shutdown.

@item 
bpo-32185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32185}: The SSL module no longer sends IP addresses in SNI TLS
extension on platforms with OpenSSL 1.0.2+ or inet_pton.

@item 
bpo-32323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32323}: @ref{f3a,,urllib.parse.urlsplit()} does not convert zone-id (scope)
to lower case for scoped IPv6 addresses in hostnames now.

@item 
bpo-32302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32302}: Fix bdist_wininst of distutils for CRT v142: it binary
compatible with CRT v140.

@item 
bpo-32255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32255}: A single empty field is now always quoted when written into a
CSV file. This allows to distinguish an empty row from a row consisting of
a single empty field. Patch by Licht Takeuchi.

@item 
bpo-32277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32277}: Raise @code{NotImplementedError} instead of @code{SystemError} on
platforms where @code{chmod(..., follow_symlinks=False)} is not supported.
Patch by Anthony Sottile.

@item 
bpo-32199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32199}: The getnode() ip getter now uses 'ip link' instead of 'ip link
list'.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: Ensure TCP_NODELAY is set on Linux. Tests by Victor Stinner.

@item 
bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900}: The @ref{df8,,locale.localeconv()} function now sets temporarily the
@code{LC_CTYPE} locale to the @code{LC_NUMERIC} locale to decode
@code{decimal_point} and @code{thousands_sep} byte strings if they are non-ASCII
or longer than 1 byte, and the @code{LC_NUMERIC} locale is different than the
@code{LC_CTYPE} locale. This temporary change affects other threads. Same
change for the @ref{833,,str.format()} method when formatting a number
(@ref{19b,,int}, @ref{196,,float}, @ref{196,,float} and subclasses) with the
@code{n} type (ex: @code{'@{:n@}'.format(1234)}).

@item 
bpo-31802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31802}: Importing native path module (@code{posixpath}, @code{ntpath}) now
works even if the @code{os} module still is not imported.
@end itemize

@node ドキュメント<68>,テスト<65>,ライブラリ<175>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id856}@anchor{1eb5}
@subsubsection ドキュメント



@itemize -

@item 
bpo-17232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17232}: Clarify docs for -O and -OO.  Patch by Terry Reedy.

@item 
bpo-32800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32800}: Update link to w3c doc for xml default namespaces.

@item 
bpo-8722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8722}: Document @code{__getattr__()} behavior when property @code{get()}
method raises @ref{5f0,,AttributeError}.

@item 
bpo-32614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32614}: Modify RE examples in documentation to use raw strings to
prevent @ref{1a3,,DeprecationWarning} and add text to REGEX HOWTO to highlight
the deprecation.

@item 
bpo-31972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31972}: Improve docstrings for @code{pathlib.PurePath} subclasses.

@item 
bpo-17799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17799}: Explain real behaviour of sys.settrace and sys.setprofile and
their C-API counterparts regarding which type of events are received in
each function. Patch by Pablo Galindo Salgado.
@end itemize

@node テスト<65>,ビルド<73>,ドキュメント<68>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id857}@anchor{1eb6}
@subsubsection テスト



@itemize -

@item 
bpo-32517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32517}: Fix failing @code{test_asyncio} on macOS 10.12.2+ due to transport
of @code{KqueueSelector} loop was not being closed.

@item 
bpo-32721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32721}: Fix test_hashlib to not fail if the _md5 module is not built.

@item 
bpo-32252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32252}: Fix faulthandler_suppress_crash_report() used to prevent core
dump files when testing crashes. getrlimit() returns zero on success.

@item 
bpo-31518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31518}: Debian Unstable has disabled TLS 1.0 and 1.1 for
SSLv23_METHOD(). Change TLS/SSL protocol of some tests to PROTOCOL_TLS or
PROTOCOL_TLSv1_2 to make them pass on Debian.
@end itemize

@node ビルド<73>,Windows<65>,テスト<65>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id858}@anchor{1eb7}
@subsubsection ビルド



@itemize -

@item 
bpo-32635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32635}: Fix segfault of the crypt module when libxcrypt is provided
instead of libcrypt at the system.
@end itemize

@node Windows<65>,macOS<50>,ビルド<73>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id859}@anchor{1eb8}
@subsubsection Windows



@itemize -

@item 
bpo-33016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33016}: Fix potential use of uninitialized memory in
nt._getfinalpathname

@item 
bpo-32903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32903}: Fix a memory leak in os.chdir() on Windows if the current
directory is set to a UNC path.

@item 
bpo-31966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31966}: Fixed WindowsConsoleIO.write() for writing empty data.

@item 
bpo-32409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32409}: Ensures activate.bat can handle Unicode contents.

@item 
bpo-32457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32457}: Improves handling of denormalized executable path when
launching Python.

@item 
bpo-32370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32370}: Use the correct encoding for ipconfig output in the uuid
module. Patch by Segev Finer.

@item 
bpo-29248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29248}: Fix @ref{b1a,,os.readlink()} on Windows, which was mistakenly
treating the @code{PrintNameOffset} field of the reparse data buffer as a
number of characters instead of bytes. Patch by Craig Holmquist and SSE4.

@item 
bpo-32588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32588}: Create standalone _distutils_findvs module.
@end itemize

@node macOS<50>,IDLE<47>,Windows<65>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id860}@anchor{1eb9}
@subsubsection macOS



@itemize -

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Provide an additional, more modern macOS installer variant that
supports macOS 10.9+ systems in 64-bit mode only. Upgrade the supplied
third-party libraries to OpenSSL 1.0.2n, XZ 5.2.3, and SQLite 3.22.0. The
10.9+ installer now links with and supplies its own copy of Tcl/Tk 8.6.8.
@end itemize

@node IDLE<47>,Tools/Demos<45>,macOS<50>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id861}@anchor{1eba}
@subsubsection IDLE



@itemize -

@item 
bpo-32984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32984}: Set @code{__file__} while running a startup file.  Like Python,
IDLE optionally runs one startup file in the Shell window before
presenting the first interactive input prompt.  For IDLE, @code{-s} runs a
file named in environmental variable  
@geindex IDLESTARTUP
@geindex 環境変数; IDLESTARTUP
@code{IDLESTARTUP} or
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP}; @code{-r file} runs @code{file}.  Python sets
@code{__file__} to the startup file name before running the file and unsets
it before the first prompt.  IDLE now does the same when run normally,
without the @code{-n} option.

@item 
bpo-32940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32940}: Simplify and rename StringTranslatePseudoMapping in pyparse.

@item 
bpo-32916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32916}: Change @code{str} to @code{code} in pyparse.

@item 
bpo-32905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32905}: Remove unused code in pyparse module.

@item 
bpo-32874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32874}: Add tests for pyparse.

@item 
bpo-32837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32837}: Using the system and place-dependent default encoding for
open() is a bad idea for IDLE's system and location-independent files.

@item 
bpo-32826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32826}: Add "encoding=utf-8" to open() in IDLE's test_help_about. GUI
test test_file_buttons() only looks at initial ascii-only lines, but
failed on systems where open() defaults to 'ascii' because readline()
internally reads and decodes far enough ahead to encounter a non-ascii
character in CREDITS.txt.

@item 
bpo-32765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32765}: Update configdialog General tab docstring to add new widgets to
the widget list.
@end itemize

@node Tools/Demos<45>,C API<65>,IDLE<47>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id862}@anchor{1ebb}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-24960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24960}: 2to3 and lib2to3 can now read pickled grammar files using
pkgutil.get_data() rather than probing the filesystem. This lets 2to3 and
lib2to3 work when run from a zipfile.

@item 
bpo-32222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32222}: Fix pygettext not extracting docstrings for functions with type
annotated arguments. Patch by Toby Harradine.
@end itemize

@node C API<65>,,Tools/Demos<45>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id863}@anchor{1ebc}
@subsubsection C API



@itemize -

@item 
bpo-29084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29084}: Undocumented C API for OrderedDict has been excluded from the
limited C API. It was added by mistake and actually never worked in the
limited C API.
@end itemize

@node Python 3 6 4 final,Python 3 6 4 release candidate 1,Python 3 6 5 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-6-4-final}@anchor{1ebd}
@subsection Python 3.6.4 final


`Release date: 2017-12-18'

There were no new code changes in version 3.6.4 since v3.6.4rc1.

@node Python 3 6 4 release candidate 1,Python 3 6 3 final,Python 3 6 4 final,変更履歴
@anchor{whatsnew/changelog python-3-6-4-release-candidate-1}@anchor{1ebe}
@subsection Python 3.6.4 release candidate 1


`Release date: 2017-12-05'

@menu
* Core and Builtins: Core and Builtins<172>. 
* ライブラリ: ライブラリ<176>. 
* ドキュメント: ドキュメント<69>. 
* テスト: テスト<66>. 
* ビルド: ビルド<74>. 
* Windows: Windows<66>. 
* macOS: macOS<51>. 
* IDLE: IDLE<48>. 
* Tools/Demos: Tools/Demos<46>. 
* C API: C API<66>. 

@end menu

@node Core and Builtins<172>,ライブラリ<176>,,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id864}@anchor{1ebf}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32176}: co_flags.CO_NOFREE is now always set correctly by the code
object constructor based on freevars and cellvars, rather than needing to
be set correctly by the caller. This ensures it will be cleared
automatically when additional cell references are injected into a modified
code object and function.

@item 
bpo-31949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31949}: Fixed several issues in printing tracebacks
(PyTraceBack_Print()). Setting sys.tracebacklimit to 0 or less now
suppresses printing tracebacks. Setting sys.tracebacklimit to None now
causes using the default limit. Setting sys.tracebacklimit to an integer
larger than LONG_MAX now means using the limit LONG_MAX rather than the
default limit. Fixed integer overflows in the case of more than @code{2**31}
traceback items on Windows. Fixed output errors handling.

@item 
bpo-30696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30696}: Fix the interactive interpreter looping endlessly when no
memory.

@item 
bpo-20047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20047}: Bytearray methods partition() and rpartition() now accept only
bytes-like objects as separator, as documented.  In particular they now
raise TypeError rather of returning a bogus result when an integer is
passed as a separator.

@item 
bpo-31852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31852}: Fix a segmentation fault caused by a combination of the async
soft keyword and continuation lines.

@item 
bpo-21720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21720}: BytesWarning no longer emitted when the `fromlist' argument of
@code{__import__()} or the @code{__all__} attribute of the module contain bytes
instances.

@item 
bpo-31825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31825}: Fixed OverflowError in the 'unicode-escape' codec and in
codecs.escape_decode() when decode an escaped non-ascii byte.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Print the full context/cause chain of exceptions on interpreter
exit, even if an exception in the chain is unhashable or compares equal to
later ones. Patch by Zane Bitter.

@item 
bpo-31786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31786}: Fix timeout rounding in the select module to round correctly
negative timeouts between -1.0 and 0.0. The functions now block waiting
for events as expected. Previously, the call was incorrectly non-blocking.
Patch by Pablo Galindo.

@item 
bpo-31642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31642}: Restored blocking "from package import module" by setting
sys.modules["package.module"] to None.

@item 
bpo-31626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31626}: Fixed a bug in debug memory allocator.  There was a write to
freed memory after shrinking a memory block.

@item 
bpo-31619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31619}: Fixed a ValueError when convert a string with large number of
underscores to integer with binary base.

@item 
bpo-31592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31592}: Fixed an assertion failure in Python parser in case of a bad
@code{unicodedata.normalize()}. Patch by Oren Milman.

@item 
bpo-31588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31588}: Raise a @code{TypeError} with a helpful error message when class
creation fails due to a metaclass with a bad @code{__prepare__()} method.
Patch by Oren Milman.

@item 
bpo-31566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31566}: Fix an assertion failure in @code{_warnings.warn()} in case of a
bad @code{__name__} global. Patch by Oren Milman.

@item 
bpo-31505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31505}: Fix an assertion failure in @code{json}, in case
@code{_json.make_encoder()} received a bad @code{encoder()} argument. Patch by
Oren Milman.

@item 
bpo-31492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31492}: Fix assertion failures in case of failing to import from a
module with a bad @code{__name__} attribute, and in case of failing to access
an attribute of such a module. Patch by Oren Milman.

@item 
bpo-31490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31490}: Fix an assertion failure in @code{ctypes} class definition, in
case the class has an attribute whose name is specified in @code{_anonymous_}
but not in @code{_fields_}. Patch by Oren Milman.

@item 
bpo-31478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31478}: Fix an assertion failure in @code{_random.Random.seed()} in case
the argument has a bad @code{__abs__()} method. Patch by Oren Milman.

@item 
bpo-31315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31315}: Fix an assertion failure in imp.create_dynamic(), when
spec.name is not a string. Patch by Oren Milman.

@item 
bpo-31311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31311}: Fix a crash in the @code{__setstate__()} method of
@code{ctypes._CData}, in case of a bad @code{__dict__}. Patch by Oren Milman.

@item 
bpo-31293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31293}: Fix crashes in true division and multiplication of a timedelta
object by a float with a bad as_integer_ratio() method. Patch by Oren
Milman.

@item 
bpo-31285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31285}: Fix an assertion failure in @code{warnings.warn_explicit}, when
the return value of the received loader's @code{get_source()} has a bad
@code{splitlines()} method. Patch by Oren Milman.

@item 
bpo-30817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30817}: @code{PyErr_PrintEx()} clears now the ignored exception that may
be raised by @code{_PySys_SetObjectId()}, for example when no memory.
@end itemize

@node ライブラリ<176>,ドキュメント<69>,Core and Builtins<172>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id865}@anchor{1ec0}
@subsubsection ライブラリ



@itemize -

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Two minor fixes for @code{typing} module: allow shallow copying
instances of generic classes, improve interaction of @code{__init_subclass__}
with generics. Original PRs by Ivan Levkivskyi.

@item 
bpo-27240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27240}: The header folding algorithm for the new email policies has
been rewritten, which also fixes bpo-30788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30788}, bpo-31831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31831}, and bpo-32182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32182}.  In
particular, RFC2231 folding is now done correctly.

@item 
bpo-32186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32186}: io.FileIO.readall() and io.FileIO.read() now release the GIL
when getting the file size. Fixed hang of all threads with inaccessible
NFS server. Patch by Nir Soffer.

@item 
bpo-12239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12239}: Make @code{msilib.SummaryInformation.GetProperty()} return
@code{None} when the value of property is @code{VT_EMPTY}.  Initial patch by
Mark Mc Mahon.

@item 
bpo-31325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31325}: Fix wrong usage of @ref{4e0,,collections.namedtuple()} in the
@ref{1e83,,RobotFileParser.parse()}
method. Initial patch by Robin Wellner.

@item 
bpo-12382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12382}: @code{msilib.OpenDatabase()} now raises a better exception
message when it couldn't open or create an MSI file.  Initial patch by
William Tisäter.

@item 
bpo-32110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32110}: @code{codecs.StreamReader.read(n)} now returns not more than `n'
characters/bytes for non-negative `n'. This makes it compatible with
@code{read()} methods of other file-like objects.

@item 
bpo-32072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32072}: Fixed issues with binary plists: Fixed saving bytearrays.
Identical objects will be saved only once. Equal references will be load
as identical objects. Added support for saving and loading recursive data
structures.

@item 
bpo-32034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32034}: Make asyncio.IncompleteReadError and LimitOverrunError
pickleable.

@item 
bpo-32015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32015}: Fixed the looping of asyncio in the case of reconnection the
socket during waiting async read/write from/to the socket.

@item 
bpo-32011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32011}: Restored support of loading marshal files with the TYPE_INT64
code. These files can be produced in Python 2.7.

@item 
bpo-31970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31970}: Reduce performance overhead of asyncio debug mode.

@item 
bpo-9678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9678}: Fixed determining the MAC address in the uuid module: Using
ifconfig on NetBSD and OpenBSD. Using arp on Linux, FreeBSD, NetBSD and
OpenBSD. Based on patch by Takayuki Shimizukawa.

@item 
bpo-30057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30057}: Fix potential missed signal in signal.signal().

@item 
bpo-31933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31933}: Fix Blake2 params leaf_size and node_offset on big endian
platforms. Patch by Jack O'Connor.

@item 
bpo-31927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31927}: Fixed compilation of the socket module on NetBSD 8.  Fixed
assertion failure or reading arbitrary data when parse a AF_BLUETOOTH
address on NetBSD and DragonFly BSD.

@item 
bpo-27666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27666}: Fixed stack corruption in curses.box() and curses.ungetmouse()
when the size of types chtype or mmask_t is less than the size of C long.
curses.box() now accepts characters as arguments.  Based on patch by Steve
Fink.

@item 
bpo-31897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31897}: plistlib now catches more errors when read binary plists and
raises InvalidFileException instead of unexpected exceptions.

@item 
bpo-25720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25720}: Fix the method for checking pad state of curses WINDOW. Patch
by Masayuki Yamamoto.

@item 
bpo-31893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31893}: Fixed the layout of the kqueue_event structure on OpenBSD and
NetBSD. Fixed the comparison of the kqueue_event objects.

@item 
bpo-31891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31891}: Fixed building the curses module on NetBSD.

@item 
bpo-28416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28416}: Instances of pickle.Pickler subclass with the persistent_id()
method and pickle.Unpickler subclass with the persistent_load() method no
longer create reference cycles.

@item 
bpo-28326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28326}: Fix multiprocessing.Process when stdout and/or stderr is closed
or None.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: If nested log adapters are used, the inner @code{process()}
methods are no longer omitted.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: The @code{manager} property on LoggerAdapter objects is now
properly settable.

@item 
bpo-31806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31806}: Fix timeout rounding in time.sleep(), threading.Lock.acquire()
and socket.socket.settimeout() to round correctly negative timeouts
between -1.0 and 0.0. The functions now block waiting for events as
expected. Previously, the call was incorrectly non-blocking. Patch by
Pablo Galindo.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: traceback: Fix a TypeError that occurred during printing of
exception tracebacks when either the current exception or an exception in
its context/cause chain is unhashable. Patch by Zane Bitter.

@item 
bpo-30058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30058}: Fixed buffer overflow in select.kqueue.control().

@item 
bpo-31770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31770}: Prevent a crash when calling the @code{__init__()} method of a
@code{sqlite3.Cursor} object more than once. Patch by Oren Milman.

@item 
bpo-31672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31672}: @code{idpattern} in @code{string.Template} matched some non-ASCII
characters. Now it uses @code{-i} regular expression local flag to avoid
non-ASCII characters.

@item 
bpo-31764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31764}: Prevent a crash in @code{sqlite3.Cursor.close()} in case the
@code{Cursor} object is uninitialized. Patch by Oren Milman.

@item 
bpo-31752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31752}: Fix possible crash in timedelta constructor called with custom
integers.

@item 
bpo-31701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31701}: On Windows, faulthandler.enable() now ignores MSC and COM
exceptions.

@item 
bpo-31728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31728}: Prevent crashes in @code{_elementtree} due to unsafe cleanup of
@code{Element.text} and @code{Element.tail}. Patch by Oren Milman.

@item 
bpo-31620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31620}: an empty asyncio.Queue now doesn't leak memory when queue.get
pollers timeout

@item 
bpo-31632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31632}: Fix method set_protocol() of class _SSLProtocolTransport in
asyncio module. This method was previously modifying a wrong reference to
the protocol.

@item 
bpo-31675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31675}: Fixed memory leaks in Tkinter's methods splitlist() and split()
when pass a string larger than 2 GiB.

@item 
bpo-31673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31673}: Fixed typo in the name of Tkinter's method adderrorinfo().

@item 
bpo-30806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30806}: Fix the string representation of a netrc object.

@item 
bpo-15037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15037}: Added a workaround for getkey() in curses for ncurses 5.7 and
earlier.

@item 
bpo-25351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25351}: Avoid venv activate failures with undefined variables

@item 
bpo-25532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25532}: inspect.unwrap() will now only try to unwrap an object
sys.getrecursionlimit() times, to protect against objects which create a
new object on every attribute access.

@item 
bpo-30347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30347}: Stop crashes when concurrently iterate over itertools.groupby()
iterators.

@item 
bpo-31516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31516}: @code{threading.current_thread()} should not return a dummy thread
at shutdown.

@item 
bpo-31351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31351}: python -m ensurepip now exits with non-zero exit code if pip
bootstrapping has failed.

@item 
bpo-31482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31482}: @code{random.seed()} now works with bytes in version=1

@item 
bpo-31334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31334}: Fix @code{poll.poll([timeout])} in the @code{select} module for
arbitrary negative timeouts on all OSes where it can only be a
non-negative integer or -1. Patch by Riccardo Coccioli.

@item 
bpo-31310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31310}: multiprocessing's semaphore tracker should be launched again if
crashed.

@item 
bpo-31308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31308}: Make multiprocessing's forkserver process immune to Ctrl-C and
other user interruptions. If it crashes, restart it when necessary.
@end itemize

@node ドキュメント<69>,テスト<66>,ライブラリ<176>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id866}@anchor{1ec1}
@subsubsection ドキュメント



@itemize -

@item 
bpo-32105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32105}: Added asyncio.BaseEventLoop.connect_accepted_socket
versionadded marker.

@item 
bpo-31537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31537}: Fix incorrect usage of @code{get_history_length} in readline
documentation example code. Patch by Brad Smith.

@item 
bpo-30085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30085}: The operator functions without double underscores are preferred
for clarity. The one with underscores are only kept for
back-compatibility.
@end itemize

@node テスト<66>,ビルド<74>,ドキュメント<69>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id867}@anchor{1ec2}
@subsubsection テスト



@itemize -

@item 
bpo-31380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31380}: Skip test_httpservers test_undecodable_file on macOS: fails on
APFS.

@item 
bpo-31705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31705}: Skip test_socket.test_sha256() on Linux kernel older than 4.5.
The test fails with ENOKEY on kernel 3.10 (on ppc64le). A fix was merged
into the kernel 4.5.

@item 
bpo-31174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31174}: Fix test_tools.test_unparse: DirectoryTestCase now stores the
names sample to always test the same files. It prevents false alarms when
hunting reference leaks.

@item 
bpo-30695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30695}: Add the @code{set_nomemory(start, stop)} and
@code{remove_mem_hooks()} functions to the @code{_testcapi} module.
@end itemize

@node ビルド<74>,Windows<66>,テスト<66>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id868}@anchor{1ec3}
@subsubsection ビルド



@itemize -

@item 
bpo-32059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32059}: @code{detect_modules()} in @code{setup.py} now also searches the
sysroot paths when cross-compiling.

@item 
bpo-31957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31957}: Fixes Windows SDK version detection when building for Windows.

@item 
bpo-31609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31609}: Fixes quotes in PCbuild/clean.bat

@item 
bpo-31934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31934}: Abort the build when building out of a not clean source tree.

@item 
bpo-31926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31926}: Fixed Argument Clinic sometimes causing compilation errors when
there was more than one function and/or method in a .c file with the same
name.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update Windows builds to use SQLite 3.21.0.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update OS X installer to use SQLite 3.21.0.

@item 
bpo-22140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22140}: Prevent double substitution of prefix in python-config.sh.

@item 
bpo-31536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31536}: Avoid wholesale rebuild after @code{make regen-all} if nothing
changed.
@end itemize

@node Windows<66>,macOS<51>,ビルド<74>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id869}@anchor{1ec4}
@subsubsection Windows



@itemize -

@item 
bpo-1102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1102}: Return @code{None} when @code{View.Fetch()} returns
@code{ERROR_NO_MORE_ITEMS} instead of raising @code{MSIError}. Initial patch by
Anthony Tuininga.

@item 
bpo-31944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31944}: Fixes Modify button in Apps and Features dialog.
@end itemize

@node macOS<51>,IDLE<48>,Windows<66>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id870}@anchor{1ec5}
@subsubsection macOS



@itemize -

@item 
bpo-31392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31392}: Update macOS installer to use OpenSSL 1.0.2m
@end itemize

@node IDLE<48>,Tools/Demos<46>,macOS<51>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id871}@anchor{1ec6}
@subsubsection IDLE



@itemize -

@item 
bpo-32207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32207}: Improve tk event exception tracebacks in IDLE. When tk event
handling is driven by IDLE's run loop, a confusing and distracting
queue.EMPTY traceback context is no longer added to tk event exception
tracebacks.  The traceback is now the same as when event handling is
driven by user code.  Patch based on a suggestion by Serhiy Storchaka.

@item 
bpo-32164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32164}: Delete unused file idlelib/tabbedpages.py. Use of TabbedPageSet
in configdialog was replaced by ttk.Notebook.

@item 
bpo-32100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32100}: IDLE: Fix old and new bugs in pathbrowser; improve tests. Patch
mostly by Cheryl Sabella.

@item 
bpo-31858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31858}: IDLE -- Restrict shell prompt manipulation to the shell. Editor
and output windows only see an empty last prompt line.  This simplifies
the code and fixes a minor bug when newline is inserted. Sys.ps1, if
present, is read on Shell start-up, but is not set or changed.

@item 
bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860}: The font sample in the IDLE configuration dialog is now
editable. Changes persist while IDLE remains open

@item 
bpo-31836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31836}: Test_code_module now passes if run after test_idle, which sets
ps1. The code module uses sys.ps1 if present or sets it to '>>> ' if not.
Test_code_module now properly tests both behaviors.  Ditto for ps2.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Fix a TypeError that caused a shell restart when printing a
traceback that includes an exception that is unhashable. Patch by Zane
Bitter.

@item 
bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802}: Use non-Latin characters in the IDLE's Font settings sample.
Even if one selects a font that defines a limited subset of the unicode
Basic Multilingual Plane, tcl/tk will use other fonts that define a
character. The expanded example give users of non-Latin characters a
better idea of what they might see in IDLE's shell and editors. To make
room for the expanded sample, frames on the Font tab are re-arranged. The
Font/Tabs help explains a bit about the additions.

@item 
bpo-31460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31460}: Simplify the API of IDLE's Module Browser. Passing a widget
instead of an flist with a root widget opens the option of creating a
browser frame that is only part of a window.  Passing a full file name
instead of pieces assumed to come from a .py file opens the possibility of
browsing python files that do not end in .py.

@item 
bpo-31649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31649}: IDLE - Make _htest, _utest parameters keyword only.

@item 
bpo-31559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31559}: Remove test order dependence in idle_test.test_browser.

@item 
bpo-31459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31459}: Rename IDLE's module browser from Class Browser to Module
Browser. The original module-level class and method browser became a
module browser, with the addition of module-level functions, years ago.
Nested classes and functions were added yesterday.  For
back-compatibility, the virtual event <<open-class-browser>>, which
appears on the Keys tab of the Settings dialog, is not changed. Patch by
Cheryl Sabella.

@item 
bpo-31500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31500}: Default fonts now are scaled on HiDPI displays.

@item 
bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262}: IDLE module browser now shows nested classes and functions.
Original patches for code and tests by Guilherme Polo and Cheryl Sabella,
respectively.
@end itemize

@node Tools/Demos<46>,C API<66>,IDLE<48>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id872}@anchor{1ec7}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-30722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30722}: Make redemo work with Python 3.6 and newer versions. Also,
remove the @code{LOCALE} option since it doesn't work with string patterns in
Python 3. Patch by Christoph Sarnowski.
@end itemize

@node C API<66>,,Tools/Demos<46>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id873}@anchor{1ec8}
@subsubsection C API



@itemize -

@item 
bpo-20891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20891}: Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in
a non-Python thread before PyEval_InitThreads(), only call
PyEval_InitThreads() after calling PyThreadState_New() to fix a crash.

@item 
bpo-31532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31532}: Fix memory corruption due to allocator mix in getpath.c between
Py_GetPath() and Py_SetPath()

@item 
bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697}: The @code{PyExc_RecursionErrorInst} singleton is removed and
@code{PyErr_NormalizeException()} does not use it anymore. This singleton is
persistent and its members being never cleared may cause a segfault during
finalization of the interpreter. See also bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898}.
@end itemize

@node Python 3 6 3 final,Python 3 6 3 release candidate 1,Python 3 6 4 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-6-3-final}@anchor{1ec9}
@subsection Python 3.6.3 final


`Release date: 2017-10-03'

@menu
* ライブラリ: ライブラリ<177>. 
* ビルド: ビルド<75>. 

@end menu

@node ライブラリ<177>,ビルド<75>,,Python 3 6 3 final
@anchor{whatsnew/changelog id874}@anchor{1eca}
@subsubsection ライブラリ



@itemize -

@item 
bpo-31641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31641}: Re-allow arbitrary iterables in
@code{concurrent.futures.as_completed()}. Fixes regression in 3.6.3rc1.
@end itemize

@node ビルド<75>,,ライブラリ<177>,Python 3 6 3 final
@anchor{whatsnew/changelog id875}@anchor{1ecb}
@subsubsection ビルド



@itemize -

@item 
bpo-31662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31662}: Fix typos in Windows @code{uploadrelease.bat} script. Fix Windows
Doc build issues in @code{Doc/make.bat}.

@item 
bpo-31423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31423}: Fix building the PDF documentation with newer versions of
Sphinx.
@end itemize

@node Python 3 6 3 release candidate 1,Python 3 6 2 final,Python 3 6 3 final,変更履歴
@anchor{whatsnew/changelog python-3-6-3-release-candidate-1}@anchor{1ecc}
@subsection Python 3.6.3 release candidate 1


`Release date: 2017-09-18'

@menu
* セキュリティ: セキュリティ<51>. 
* Core and Builtins: Core and Builtins<173>. 
* ライブラリ: ライブラリ<178>. 
* ドキュメント: ドキュメント<70>. 
* テスト: テスト<67>. 
* ビルド: ビルド<76>. 
* Windows: Windows<67>. 
* IDLE: IDLE<49>. 
* Tools/Demos: Tools/Demos<47>. 

@end menu

@node セキュリティ<51>,Core and Builtins<173>,,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id876}@anchor{1ecd}
@subsubsection セキュリティ



@itemize -

@item 
bpo-29781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29781}: SSLObject.version() now correctly returns None when handshake
over BIO has not been performed yet.

@item 
bpo-30947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30947}: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to
get security fixes.
@end itemize

@node Core and Builtins<173>,ライブラリ<178>,セキュリティ<51>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id877}@anchor{1ece}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31471}: Fix an assertion failure in @code{subprocess.Popen()} on Windows,
in case the env argument has a bad @code{keys()} method. Patch by Oren
Milman.

@item 
bpo-31418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31418}: Fix an assertion failure in @code{PyErr_WriteUnraisable()} in case
of an exception with a bad @code{__module__} attribute. Patch by Oren Milman.

@item 
bpo-31416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31416}: Fix assertion failures in case of a bad warnings.filters or
warnings.defaultaction. Patch by Oren Milman.

@item 
bpo-31411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31411}: Raise a TypeError instead of SystemError in case
warnings.onceregistry is not a dictionary. Patch by Oren Milman.

@item 
bpo-31373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31373}: Fix several possible instances of undefined behavior due to
floating-point demotions.

@item 
bpo-30465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30465}: Location information (@code{lineno} and @code{col_offset}) in
f-strings is now (mostly) correct.  This fixes tools like flake8 from
showing warnings on the wrong line (typically the first line of the file).

@item 
bpo-31343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31343}: Include sys/sysmacros.h for major(), minor(), and makedev().
GNU C library plans to remove the functions from sys/types.h.

@item 
bpo-31291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31291}: Fix an assertion failure in @code{zipimport.zipimporter.get_data}
on Windows, when the return value of @code{pathname.replace('/','\\')} isn't
a string. Patch by Oren Milman.

@item 
bpo-31271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31271}: Fix an assertion failure in the @code{write()} method of
@code{io.TextIOWrapper}, when the encoder doesn't return a bytes object.
Patch by Oren Milman.

@item 
bpo-31243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31243}: Fix a crash in some methods of @code{io.TextIOWrapper}, when the
decoder's state is invalid. Patch by Oren Milman.

@item 
bpo-30721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30721}: @code{print} now shows correct usage hint for using Python 2
redirection syntax.  Patch by Sanyam Khurana.

@item 
bpo-31070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31070}: Fix a race condition in importlib _get_module_lock().

@item 
bpo-31095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31095}: Fix potential crash during GC caused by @code{tp_dealloc} which
doesn't call @code{PyObject_GC_UnTrack()}.

@item 
bpo-31071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31071}: Avoid masking original TypeError in call with * unpacking when
other arguments are passed.

@item 
bpo-30978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30978}: str.format_map() now passes key lookup exceptions through.
Previously any exception was replaced with a KeyError exception.

@item 
bpo-30808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30808}: Use _Py_atomic API for concurrency-sensitive signal state.

@item 
bpo-30876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30876}: Relative import from unloaded package now reimports the package
instead of failing with SystemError.  Relative import from non-package now
fails with ImportError rather than SystemError.

@item 
bpo-30703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30703}: Improve signal delivery. Avoid using Py_AddPendingCall from
signal handler, to avoid calling signal-unsafe functions. The tests I'm
adding here fail without the rest of the patch, on Linux and OS X. This
means our signal delivery logic had defects (some signals could be lost).

@item 
bpo-30765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30765}: Avoid blocking in pthread_mutex_lock() when
PyThread_acquire_lock() is asked not to block.

@item 
bpo-31161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31161}: Make sure the 'Missing parentheses' syntax error message is
only applied to SyntaxError, not to subclasses. Patch by Martijn Pieters.

@item 
bpo-30814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30814}: Fixed a race condition when import a submodule from a package.

@item 
bpo-30597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30597}: @code{print} now shows expected input in custom error message when
used as a Python 2 statement. Patch by Sanyam Khurana.
@end itemize

@node ライブラリ<178>,ドキュメント<70>,Core and Builtins<173>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id878}@anchor{1ecf}
@subsubsection ライブラリ



@itemize -

@item 
bpo-31499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31499}: xml.etree: Fix a crash when a parser is part of a reference
cycle.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: typing.get_type_hints now finds the right globalns for classes
and modules by default (when no @code{globalns} was specified by the caller).

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Speed improvements to the @code{typing} module.  Original PRs by
Ivan Levkivskyi and Mitar.

@item 
bpo-31544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31544}: The C accelerator module of ElementTree ignored exceptions
raised when looking up TreeBuilder target methods in XMLParser().

@item 
bpo-31234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31234}: socket.create_connection() now fixes manually a reference
cycle: clear the variable storing the last exception on success.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: LoggerAdapter objects can now be nested.

@item 
bpo-31400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31400}: Improves SSL error handling to avoid losing error numbers.

@item 
bpo-28958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28958}: ssl.SSLContext() now uses OpenSSL error information when a
context cannot be instantiated.

@item 
bpo-27340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27340}: SSLSocket.sendall() now uses memoryview to create slices of
data. This fixes support for all bytes-like object. It is also more
efficient and avoids costly copies.

@item 
bpo-31178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31178}: Fix string concatenation bug in rare error path in the
subprocess module

@item 
bpo-31350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31350}: Micro-optimize @code{asyncio._get_running_loop()} to become up
to 10% faster.

@item 
bpo-31170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31170}: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of
partial characters for UTF-8 input (libexpat bug 115):
@indicateurl{https://github.com/libexpat/libexpat/issues/115}

@item 
bpo-29136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29136}: Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

@item 
bpo-29212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29212}: Fix concurrent.futures.thread.ThreadPoolExecutor threads to
have a non repr() based thread name by default when no thread_name_prefix
is supplied. They will now identify themselves as
"ThreadPoolExecutor-y_n".

@item 
bpo-9146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9146}: Fix a segmentation fault in _hashopenssl when standard hash
functions such as md5 are not available in the linked OpenSSL library.  As
in some special FIPS-140 build environments.

@item 
bpo-27144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27144}: The @code{map()} and @code{as_completed()} iterators in
@code{concurrent.futures} now avoid keeping a reference to yielded objects.

@item 
bpo-10746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10746}: Fix ctypes producing wrong 
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} type codes for integer
types.

@item 
bpo-22536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22536}: The subprocess module now sets the filename when
FileNotFoundError is raised on POSIX systems due to the executable or cwd
not being found.

@item 
bpo-31249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31249}: concurrent.futures: WorkItem.run() used by ThreadPoolExecutor
now breaks a reference cycle between an exception object and the WorkItem
object.

@item 
bpo-31247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31247}: xmlrpc.server now explicitly breaks reference cycles when using
sys.exc_info() in code handling exceptions.

@item 
bpo-30102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30102}: The ssl and hashlib modules now call
OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0. The function
detects CPU features and enables optimizations on some CPU architectures
such as POWER8. Patch is based on research from Gustavo Serra Scalet.

@item 
bpo-31185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31185}: Fixed miscellaneous errors in asyncio speedup module.

@item 
bpo-31135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31135}: ttk: fix the destroy() method of LabeledScale and OptionMenu
classes. Call the parent destroy() method even if the used attribute
doesn't exist. The LabeledScale.destroy() method now also explicitly
clears label and scale attributes to help the garbage collector to destroy
all widgets.

@item 
bpo-31107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31107}: Fix @code{copyreg._slotnames()} mangled attribute calculation for
classes whose name begins with an underscore. Patch by Shane Harvey.

@item 
bpo-31061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31061}: Fixed a crash when using asyncio and threads.

@item 
bpo-30502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30502}: Fix handling of long oids in ssl.  Based on patch by Christian
Heimes.

@item 
bpo-30119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30119}: ftplib.FTP.putline() now throws ValueError on commands that
contains CR or LF. Patch by Donghee Na.

@item 
bpo-30595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30595}: multiprocessing.Queue.get() with a timeout now polls its reader
in non-blocking mode if it succeeded to acquire the lock but the acquire
took longer than the timeout.

@item 
bpo-29403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29403}: Fix @code{unittest.mock}'s autospec to not fail on method-bound
builtin functions.  Patch by Aaron Gallagher.

@item 
bpo-30961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30961}: Fix decrementing a borrowed reference in tracemalloc.

@item 
bpo-25684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25684}: Change @code{ttk.OptionMenu} radiobuttons to be unique across
instances of @code{OptionMenu}.

@item 
bpo-30886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30886}: Fix multiprocessing.Queue.join_thread(): it now waits until the
thread completes, even if the thread was started by the same process which
created the queue.

@item 
bpo-29854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29854}: Fix segfault in readline when using readline's history-size
option.  Patch by Nir Soffer.

@item 
bpo-30319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30319}: socket.close() now ignores ECONNRESET error.

@item 
bpo-30828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30828}: Fix out of bounds write in
@code{asyncio.CFuture.remove_done_callback()}.

@item 
bpo-30807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30807}: signal.setitimer() may disable the timer when passed a tiny
value. Tiny values (such as 1e-6) are valid non-zero values for
setitimer(), which is specified as taking microsecond-resolution
intervals. However, on some platform, our conversion routine could convert
1e-6 into a zero interval, therefore disabling the timer instead of
(re-)scheduling it.

@item 
bpo-30441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30441}: Fix bug when modifying os.environ while iterating over it

@item 
bpo-30532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30532}: Fix email header value parser dropping folding white space in
certain cases.

@item 
bpo-30879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30879}: os.listdir() and os.scandir() now emit bytes names when called
with bytes-like argument.

@item 
bpo-30746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30746}: Prohibited the '=' character in environment variable names in
@code{os.putenv()} and @code{os.spawn*()}.

@item 
bpo-29755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29755}: Fixed the lgettext() family of functions in the gettext module.
They now always return bytes.
@end itemize

@node ドキュメント<70>,テスト<67>,ライブラリ<178>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id879}@anchor{1ed0}
@subsubsection ドキュメント



@itemize -

@item 
bpo-31294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31294}: Fix incomplete code snippet in the ZeroMQSocketListener and
ZeroMQSocketHandler examples and adapt them to Python 3.

@item 
bpo-21649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21649}: Add RFC 7525 and Mozilla server side TLS links to SSL
documentation.

@item 
bpo-30803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30803}: Clarify doc on truth value testing. Original patch by Peter
Thomassen.
@end itemize

@node テスト<67>,ビルド<76>,ドキュメント<70>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id880}@anchor{1ed1}
@subsubsection テスト



@itemize -

@item 
bpo-31320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31320}: Silence traceback in test_ssl

@item 
bpo-25674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25674}: Remove sha256.tbs-internet.com ssl test

@item 
bpo-30715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30715}: Address ALPN callback changes for OpenSSL 1.1.0f. The latest
version behaves like OpenSSL 1.0.2 and no longer aborts handshake.

@item 
bpo-30822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30822}: regrtest: Exclude tzdata from regrtest --all. When running the
test suite using --use=all / -u all, exclude tzdata since it makes
test_datetime too slow (15-20 min on some buildbots) which then times out
on some buildbots. Fix also regrtest command line parser to allow passing
-u extralargefile to run test_zipfile64.
@end itemize

@node ビルド<76>,Windows<67>,テスト<67>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id881}@anchor{1ed2}
@subsubsection ビルド



@itemize -

@item 
bpo-30854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30854}: Fix compile error when compiling --without-threads. Patch by
Masayuki Yamamoto.
@end itemize

@node Windows<67>,IDLE<49>,ビルド<76>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id882}@anchor{1ed3}
@subsubsection Windows



@itemize -

@item 
bpo-30389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30389}: Adds detection of Visual Studio 2017 to distutils on Windows.

@item 
bpo-31340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31340}: Change to building with MSVC v141 (included with Visual Studio
2017)

@item 
bpo-30581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30581}: os.cpu_count() now returns the correct number of processors on
Windows when the number of logical processors is greater than 64.

@item 
bpo-30731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30731}: Add a missing xmlns to python.manifest so that it matches the
schema.
@end itemize

@node IDLE<49>,Tools/Demos<47>,Windows<67>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id883}@anchor{1ed4}
@subsubsection IDLE



@itemize -

@item 
bpo-31493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31493}: IDLE code context -- fix code update and font update timers.
Canceling timers prevents a warning message when test_idle completes.

@item 
bpo-31488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31488}: IDLE - Update non-key options in former extension classes. When
applying configdialog changes, call .reload for each feature class. Change
ParenMatch so updated options affect existing instances attached to
existing editor windows.

@item 
bpo-31477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31477}: IDLE - Improve rstrip entry in doc. Strip trailing whitespace
strips more than blank spaces.  Multiline string literals are not skipped.

@item 
bpo-31480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31480}: IDLE - make tests pass with zzdummy extension disabled by
default.

@item 
bpo-31421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31421}: Document how IDLE runs tkinter programs. IDLE calls tcl/tk
update in the background in order to make live interaction and
experimentation with tkinter applications much easier.

@item 
bpo-31414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31414}: IDLE -- fix tk entry box tests by deleting first. Adding to an
int entry is not the same as deleting and inserting because int('@w{'}) will
fail.

@item 
bpo-31051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31051}: Rearrange IDLE configdialog GenPage into Window, Editor, and
Help sections.

@item 
bpo-30617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30617}: IDLE - Add docstrings and tests for outwin subclass of editor.
Move some data and functions from the class to module level. Patch by
Cheryl Sabella.

@item 
bpo-31287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31287}: IDLE - Do not modify tkinter.message in test_configdialog.

@item 
bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099}: Convert IDLE's built-in 'extensions' to regular features. About
10 IDLE features were implemented as supposedly optional extensions. Their
different behavior could be confusing or worse for users and not good for
maintenance. Hence the conversion. The main difference for users is that
user configurable key bindings for builtin features are now handled
uniformly. Now, editing a binding in a keyset only affects its value in
the keyset. All bindings are defined together in the system-specific
default keysets in config-extensions.def. All custom keysets are saved as
a whole in config-extension.cfg.  All take effect as soon as one clicks
Apply or Ok. The affected events are '<<force-open-completions>>',
'<<expand-word>>', '<<force-open-calltip>>', '<<flash-paren>>',
'<<format-paragraph>>', '<<run-module>>', '<<check-module>>', and
'<<zoom-height>>'.  Any (global) customizations made before 3.6.3 will not
affect their keyset-specific customization after 3.6.3. and vice versa.
Initial patch by Charles Wohlganger.

@item 
bpo-31206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31206}: IDLE: Factor HighPage(Frame) class from ConfigDialog. Patch by
Cheryl Sabella.

@item 
bpo-31001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31001}: Add tests for configdialog highlight tab.  Patch by Cheryl
Sabella.

@item 
bpo-31205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31205}: IDLE: Factor KeysPage(Frame) class from ConfigDialog.  The
slightly modified tests continue to pass.  Patch by Cheryl Sabella.

@item 
bpo-31130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31130}: IDLE -- stop leaks in test_configdialog. Initial patch by
Victor Stinner.

@item 
bpo-31002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31002}: Add tests for configdialog keys tab. Patch by Cheryl Sabella.

@item 
bpo-19903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19903}: IDLE: Calltips use @code{inspect.signature} instead of
@code{inspect.getfullargspec}. This improves calltips for builtins converted
to use Argument Clinic. Patch by Louie Lu.

@item 
bpo-31083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31083}: IDLE - Add an outline of a TabPage class in configdialog.
Update existing classes to match outline. Initial patch by Cheryl Sabella.

@item 
bpo-31050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31050}: Factor GenPage(Frame) class from ConfigDialog. The slightly
modified tests continue to pass. Patch by Cheryl Sabella.

@item 
bpo-31004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31004}: IDLE - Factor FontPage(Frame) class from ConfigDialog. Slightly
modified tests continue to pass. Fix General tests. Patch mostly by Cheryl
Sabella.

@item 
bpo-30781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30781}: IDLE - Use ttk widgets in ConfigDialog. Patches by Terry Jan
Reedy and Cheryl Sabella.

@item 
bpo-31060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31060}: IDLE - Finish rearranging methods of ConfigDialog Grouping
methods pertaining to each tab and the buttons will aid writing tests and
improving the tabs and will enable splitting the groups into classes.

@item 
bpo-30853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30853}: IDLE -- Factor a VarTrace class out of ConfigDialog. Instance
tracers manages pairs consisting of a tk variable and a callback function.
When tracing is turned on, setting the variable calls the function.  Test
coverage for the new class is 100%.

@item 
bpo-31003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31003}: IDLE: Add more tests for General tab.

@item 
bpo-30993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30993}: IDLE - Improve configdialog font page and tests. In
configdialog: Document causal pathways in create_font_tab docstring.
Simplify some attribute names. Move set_samples calls to var_changed_font
(idea from Cheryl Sabella).  Move related functions to positions after the
create widgets function. In test_configdialog: Fix test_font_set so not
order dependent.  Fix renamed test_indent_scale so it tests the widget.
Adjust tests for movement of set_samples call.  Add tests for load
functions.  Put all font tests in one class and tab indent tests in
another.  Except for two lines, these tests completely cover the related
functions.

@item 
bpo-30981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30981}: IDLE -- Add more configdialog font page tests.

@item 
bpo-28523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28523}: IDLE: replace 'colour' with 'color' in configdialog.

@item 
bpo-30917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30917}: Add tests for idlelib.config.IdleConf. Increase coverage from
46% to 96%. Patch by Louie Lu.

@item 
bpo-30934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30934}: Document coverage details for idlelib tests. Add section to
idlelib/idle-test/README.txt. Include check that branches are taken both
ways. Exclude IDLE-specific code that does not run during unit tests.

@item 
bpo-30913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30913}: IDLE: Document ConfigDialog tk Vars, methods, and widgets in
docstrings This will facilitate improving the dialog and splitting up the
class. Original patch by Cheryl Sabella.

@item 
bpo-30899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30899}: IDLE: Add tests for ConfigParser subclasses in config. Patch by
Louie Lu.

@item 
bpo-30881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30881}: IDLE: Add docstrings to browser.py. Patch by Cheryl Sabella.

@item 
bpo-30851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30851}: IDLE: Remove unused variables in configdialog.  One is a
duplicate, one is set but cannot be altered by users. Patch by Cheryl
Sabella.

@item 
bpo-30870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30870}: IDLE: In Settings dialog, select font with Up, Down keys as
well as mouse. Initial patch by Louie Lu.

@item 
bpo-8231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8231}: IDLE: call config.IdleConf.GetUserCfgDir only once.

@item 
bpo-30779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30779}: IDLE: Factor ConfigChanges class from configdialog, put in
config; test. * In config, put dump test code in a function; run it and
unittest in   'if __name__ == '__main__'. * Add class config.ConfigChanges
based on changes_class_v4.py on bpo issue. * Add class
test_config.ChangesTest, partly using configdialog_tests_v1.py. * Revise
configdialog to use ConfigChanges; see tracker msg297804. * Revise
test_configdialog to match configdialog changes. * Remove configdialog
functions unused or moved to ConfigChanges. Cheryl Sabella contributed
parts of the patch.

@item 
bpo-30777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30777}: IDLE: configdialog - Add docstrings and fix comments. Patch by
Cheryl Sabella.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: IDLE: Improve textview with docstrings, PEP8 names, and more
tests. Patch by Cheryl Sabella.

@item 
bpo-30723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30723}: IDLE: Make several improvements to parenmatch. Add 'parens'
style to highlight both opener and closer. Make 'default' style, which is
not default, a synonym for 'opener'. Make time-delay work the same with
all styles. Add help for config dialog extensions tab, including help for
parenmatch. Add new tests.  Original patch by Charles Wohlganger.

@item 
bpo-30674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30674}: IDLE: add docstrings to grep module. Patch by Cheryl Sabella

@item 
bpo-21519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21519}: IDLE's basic custom key entry dialog now detects duplicates
properly. Original patch by Saimadhav Heblikar.

@item 
bpo-29910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29910}: IDLE no longer deletes a character after commenting out a
region by a key shortcut.  Add @code{return 'break'} for this and other
potential conflicts between IDLE and default key bindings.

@item 
bpo-30728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30728}: Review and change idlelib.configdialog names. Lowercase method
and attribute names. Replace 'colour' with 'color', expand overly cryptic
names, delete unneeded underscores. Replace @code{import *} with specific
imports. Patches by Cheryl Sabella.

@item 
bpo-6739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6739}: IDLE: Verify user-entered key sequences by trying to bind them
with tk. Add tests for all 3 validation functions. Original patch by G
Polo.  Tests added by Cheryl Sabella.
@end itemize

@node Tools/Demos<47>,,IDLE<49>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id884}@anchor{1ed5}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-30983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30983}: gdb integration commands (py-bt, etc.) work on optimized shared
builds now, too.  
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/} introduced _PyEval_EvalFrameDefault which
inlines PyEval_EvalFrameEx on non-debug shared builds.  This broke the
ability to use py-bt, py-up, and a few other Python-specific gdb
integrations. The problem is fixed by only looking for
_PyEval_EvalFrameDefault frames in python-gdb.py.  Original patch by Bruno
"Polaco" Penteado.
@end itemize

@node Python 3 6 2 final,Python 3 6 2 release candidate 2,Python 3 6 3 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-6-2-final}@anchor{1ed6}
@subsection Python 3.6.2 final


`Release date: 2017-07-17'

No changes since release candidate 2

@node Python 3 6 2 release candidate 2,Python 3 6 2 release candidate 1,Python 3 6 2 final,変更履歴
@anchor{whatsnew/changelog python-3-6-2-release-candidate-2}@anchor{1ed7}
@subsection Python 3.6.2 release candidate 2


`Release date: 2017-07-07'

@menu
* セキュリティ: セキュリティ<52>. 

@end menu

@node セキュリティ<52>,,,Python 3 6 2 release candidate 2
@anchor{whatsnew/changelog id885}@anchor{1ed8}
@subsubsection セキュリティ



@itemize -

@item 
bpo-30730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30730}: Prevent environment variables injection in subprocess on
Windows.  Prevent passing other environment variables and command
arguments.

@item 
bpo-30694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30694}: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple
security vulnerabilities including: 
@geindex Common Vulnerabilities and Exposures; CVE 2017-9233
CVE 2017-9233@footnote{https://www.cve.org/CVERecord?id=CVE-2017-9233} (External entity
infinite loop DoS), 
@geindex Common Vulnerabilities and Exposures; CVE 2016-9063
CVE 2016-9063@footnote{https://www.cve.org/CVERecord?id=CVE-2016-9063} (Integer overflow, re-fix),
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718} (Fix regression bugs from 2.2.0's fix to
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718}) and 
@geindex Common Vulnerabilities and Exposures; CVE 2012-0876
CVE 2012-0876@footnote{https://www.cve.org/CVERecord?id=CVE-2012-0876} (Counter hash flooding with
SipHash). Note: the 
@geindex Common Vulnerabilities and Exposures; CVE 2016-5300
CVE 2016-5300@footnote{https://www.cve.org/CVERecord?id=CVE-2016-5300} (Use os-specific entropy sources like
getrandom) doesn't impact Python, since Python already gets entropy from
the OS to set the expat secret using @code{XML_SetHashSalt()}.

@item 
bpo-30500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30500}: Fix urllib.parse.splithost() to correctly parse fragments. For
example, @code{splithost('//127.0.0.1#@@evil.com/')} now correctly returns the
@code{127.0.0.1} host, instead of treating @code{@@evil.com} as the host in an
authentication (@code{login@@host}).
@end itemize

@node Python 3 6 2 release candidate 1,Python 3 6 1 final,Python 3 6 2 release candidate 2,変更履歴
@anchor{whatsnew/changelog python-3-6-2-release-candidate-1}@anchor{1ed9}
@subsection Python 3.6.2 release candidate 1


`Release date: 2017-06-17'

@menu
* セキュリティ: セキュリティ<53>. 
* Core and Builtins: Core and Builtins<174>. 
* ライブラリ: ライブラリ<179>. 
* IDLE: IDLE<50>. 
* C API: C API<67>. 
* ビルド: ビルド<77>. 
* ドキュメント: ドキュメント<71>. 
* Tools/Demos: Tools/Demos<48>. 
* テスト: テスト<68>. 
* Windows: Windows<68>. 

@end menu

@node セキュリティ<53>,Core and Builtins<174>,,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id886}@anchor{1eda}
@subsubsection セキュリティ



@itemize -

@item 
bpo-29591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29591}: Update expat copy from 2.1.1 to 2.2.0 to get fixes of
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718} and 
@geindex Common Vulnerabilities and Exposures; CVE 2016-4472
CVE 2016-4472@footnote{https://www.cve.org/CVERecord?id=CVE-2016-4472}. See
@indicateurl{https://sourceforge.net/p/expat/bugs/537/} for more information.
@end itemize

@node Core and Builtins<174>,ライブラリ<179>,セキュリティ<53>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id887}@anchor{1edb}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-30682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30682}: Removed a too-strict assertion that failed for certain
f-strings, such as eval("f'\n'") and eval("f'\r'").

@item 
bpo-30604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30604}: Move co_extra_freefuncs to not be per-thread to avoid crashes

@item 
bpo-29104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29104}: Fixed parsing backslashes in f-strings.

@item 
bpo-27945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27945}: Fixed various segfaults with dict when input collections are
mutated during searching, inserting or comparing.  Based on patches by
Duane Griffin and Tim Mitchell.

@item 
bpo-25794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25794}: Fixed type.__setattr__() and type.__delattr__() for
non-interned attribute names.  Based on patch by Eryk Sun.

@item 
bpo-30039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30039}: If a KeyboardInterrupt happens when the interpreter is in the
middle of resuming a chain of nested 'yield from' or 'await' calls, it's
now correctly delivered to the innermost frame.

@item 
bpo-12414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12414}: sys.getsizeof() on a code object now returns the sizes which
includes the code struct and sizes of objects which it references. Patch
by Donghee Na.

@item 
bpo-29949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29949}: Fix memory usage regression of set and frozenset object.

@item 
bpo-29935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29935}: Fixed error messages in the index() method of tuple, list and
deque when pass indices of wrong type.

@item 
bpo-29859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29859}: Show correct error messages when any of the pthread_* calls in
thread_pthread.h fails.

@item 
bpo-28876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28876}: @code{bool(range)} works even if @code{len(range)} raises
@ref{a81,,OverflowError}.

@item 
bpo-29600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29600}: Fix wrapping coroutine return values in StopIteration.

@item 
bpo-28856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28856}: Fix an oversight that %b format for bytes should support
objects follow the buffer protocol.

@item 
bpo-29714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29714}: Fix a regression that bytes format may fail when containing
zero bytes inside.

@item 
bpo-29478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29478}: If max_line_length=None is specified while using the Compat32
policy, it is no longer ignored.  Patch by Mircea Cosbuc.
@end itemize

@node ライブラリ<179>,IDLE<50>,Core and Builtins<174>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id888}@anchor{1edc}
@subsubsection ライブラリ



@itemize -

@item 
bpo-30616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30616}: Functional API of enum allows to create empty enums. Patched by
Donghee Na

@item 
bpo-30038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30038}: Fix race condition between signal delivery and wakeup file
descriptor. Patch by Nathaniel Smith.

@item 
bpo-23894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23894}: lib2to3 now recognizes @code{rb'...'} and @code{f'...'} strings.

@item 
bpo-23890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23890}: unittest.TestCase.assertRaises() now manually breaks a
reference cycle to not keep objects alive longer than expected.

@item 
bpo-30149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30149}: inspect.signature() now supports callables with
variable-argument parameters wrapped with partialmethod. Patch by Donghee
Na.

@item 
bpo-30645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30645}: Fix path calculation in imp.load_package(), fixing it for cases
when a package is only shipped with bytecodes. Patch by Alexandru
Ardelean.

@item 
bpo-29931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29931}: Fixed comparison check for ipaddress.ip_interface objects.
Patch by Sanjay Sundaresan.

@item 
bpo-30605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30605}: re.compile() no longer raises a BytesWarning when compiling a
bytes instance with misplaced inline modifier.  Patch by Roy Williams.

@item 
bpo-24484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24484}: Avoid race condition in multiprocessing cleanup (#2159)

@item 
bpo-28994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28994}: The traceback no longer displayed for SystemExit raised in a
callback registered by atexit.

@item 
bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508}: Don't log exceptions if Task/Future "cancel()" method was
called.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Updates to typing module: Add generic AsyncContextManager, add
support for ContextManager on all versions. Original PRs by Jelle Zijlstra
and Ivan Levkivskyi

@item 
bpo-29870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29870}: Fix ssl sockets leaks when connection is aborted in asyncio/ssl
implementation. Patch by Michaël Sghaïer.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Closing transport during handshake process leaks open socket.
Patch by Nikolay Kim

@item 
bpo-27585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27585}: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu
Sornay.

@item 
bpo-30418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30418}: On Windows, subprocess.Popen.communicate() now also ignore
EINVAL on stdin.write() if the child process is still running but closed
the pipe.

@item 
bpo-29822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29822}: inspect.isabstract() now works during __init_subclass__.  Patch
by Nate Soares.

@item 
bpo-29581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29581}: ABCMeta.__new__ now accepts @code{**kwargs}, allowing abstract
base classes to use keyword parameters in __init_subclass__. Patch by Nate
Soares.

@item 
bpo-30557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30557}: faulthandler now correctly filters and displays exception codes
on Windows

@item 
bpo-30378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30378}: Fix the problem that logging.handlers.SysLogHandler cannot
handle IPv6 addresses.

@item 
bpo-29960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29960}: Preserve generator state when _random.Random.setstate() raises
an exception. Patch by Bryan Olson.

@item 
bpo-30414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30414}: multiprocessing.Queue._feed background running thread do not
break from main loop on exception.

@item 
bpo-30003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30003}: Fix handling escape characters in HZ codec.  Based on patch by
Ma Lin.

@item 
bpo-30301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30301}: Fix AttributeError when using SimpleQueue.empty() under `spawn'
and `forkserver' start methods.

@item 
bpo-30329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30329}: imaplib and poplib now catch the Windows socket WSAEINVAL error
(code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted.
This error occurs sometimes on SSL connections.

@item 
bpo-30375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30375}: Warnings emitted when compile a regular expression now always
point to the line in the user code.  Previously they could point into
inners of the re module if emitted from inside of groups or conditionals.

@item 
bpo-30048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30048}: Fixed @code{Task.cancel()} can be ignored when the task is running
coroutine and the coroutine returned without any more @code{await}.

@item 
bpo-30266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30266}: contextlib.AbstractContextManager now supports
anti-registration by setting __enter__ = None or __exit__ = None,
following the pattern introduced in bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}. Patch by Jelle Zijlstra.

@item 
bpo-30298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30298}: Weaken the condition of deprecation warnings for inline
modifiers. Now allowed several subsequential inline modifiers at the start
of the pattern (e.g. @code{'(?i)(?s)...'}).  In verbose mode whitespaces and
comments now are allowed before and between inline modifiers (e.g. @code{'(?x)
(?i) (?s)...'}).

@item 
bpo-29990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29990}: Fix range checking in GB18030 decoder.  Original patch by Ma
Lin.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Change resulted because of zipfile breakage. (See also:
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094})

@item 
bpo-30243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30243}: Removed the __init__ methods of _json's scanner and encoder.
Misusing them could cause memory leaks or crashes.  Now scanner and
encoder objects are completely initialized in the __new__ methods.

@item 
bpo-30185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30185}: Avoid KeyboardInterrupt tracebacks in forkserver helper process
when Ctrl-C is received.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: add typing.NoReturn type, use
WrapperDescriptorType, minor bug-fixes.  Original PRs by Jim
Fasarakis-Hilliard and Ivan Levkivskyi.

@item 
bpo-30205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30205}: Fix getsockname() for unbound AF_UNIX sockets on Linux.

@item 
bpo-30070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30070}: Fixed leaks and crashes in errors handling in the parser
module.

@item 
bpo-30061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30061}: Fixed crashes in IOBase methods __next__() and readlines() when
readline() or __next__() respectively return non-sizeable object. Fixed
possible other errors caused by not checking results of PyObject_Size(),
PySequence_Size(), or PyMapping_Size().

@item 
bpo-30017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30017}: Allowed calling the close() method of the zip entry writer
object multiple times.  Writing to a closed writer now always produces a
ValueError.

@item 
bpo-30068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30068}: _io._IOBase.readlines will check if it's closed first when hint
is present.

@item 
bpo-29694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29694}: Fixed race condition in pathlib mkdir with flags parents=True.
Patch by Armin Rigo.

@item 
bpo-29692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29692}: Fixed arbitrary unchaining of RuntimeError exceptions in
contextlib.contextmanager.  Patch by Siddharth Velankar.

@item 
bpo-29998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29998}: Pickling and copying ImportError now preserves name and path
attributes.

@item 
bpo-29953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29953}: Fixed memory leaks in the replace() method of datetime and time
objects when pass out of bound fold argument.

@item 
bpo-29942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29942}: Fix a crash in itertools.chain.from_iterable when encountering
long runs of empty iterables.

@item 
bpo-27863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27863}: Fixed multiple crashes in ElementTree caused by race conditions
and wrong types.

@item 
bpo-28699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28699}: Fixed a bug in pools in multiprocessing.pool that raising an
exception at the very first of an iterable may swallow the exception or
make the program hang. Patch by Davin Potts and Xiang Zhang.

@item 
bpo-25803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25803}: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when
the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-29861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29861}: Release references to tasks, their arguments and their results
as soon as they are finished in multiprocessing.Pool.

@item 
bpo-29884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29884}: faulthandler: Restore the old sigaltstack during teardown.
Patch by Christophe Zeitouny.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive buffered file-like objects.

@item 
bpo-29800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29800}: Fix crashes in partial.__repr__ if the keys of partial.keywords
are not strings.  Patch by Michael Seifert.

@item 
bpo-29742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29742}: get_extra_info() raises exception if get called on closed ssl
transport. Patch by Nikolay Kim.

@item 
bpo-8256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8256}: Fixed possible failing or crashing input() if attributes
"encoding" or "errors" of sys.stdin or sys.stdout are not set or are not
strings.

@item 
bpo-28298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28298}: Fix a bug that prevented array 'Q', 'L' and 'I' from accepting
big intables (objects that have __int__) as elements.  Patch by Oren
Milman.

@item 
bpo-28231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28231}: The zipfile module now accepts path-like objects for external
paths.

@item 
bpo-26915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26915}: index() and count() methods of collections.abc.Sequence now
check identity before checking equality when do comparisons.

@item 
bpo-29615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29615}: SimpleXMLRPCDispatcher no longer chains KeyError (or any other
exception) to exception(s) raised in the dispatched methods. Patch by Petr
Motejlek.

@item 
bpo-30177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30177}: path.resolve(strict=False) no longer cuts the path after the
first element not present in the filesystem.  Patch by Antoine Pietri.
@end itemize

@node IDLE<50>,C API<67>,ライブラリ<179>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id889}@anchor{1edd}
@subsubsection IDLE



@itemize -

@item 
bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786}: Fix several problems with IDLE's autocompletion box. The
following should now work: clicking on selection box items; using the
scrollbar; selecting an item by hitting Return. Hangs on MacOSX should no
longer happen. Patch by Louie Lu.

@item 
bpo-25514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25514}: Add doc subsubsection about IDLE failure to start. Popup
no-connection message directs users to this section.

@item 
bpo-30642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30642}: Fix reference leaks in IDLE tests. Patches by Louie Lu and
Terry Jan Reedy.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: Add docstrings for textview.py and use PEP8 names. Patches by
Cheryl Sabella and Terry Jan Reedy.

@item 
bpo-30290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30290}: Help-about: use pep8 names and add tests. Increase coverage to
100%. Patches by Louie Lu, Cheryl Sabella, and Terry Jan Reedy.

@item 
bpo-30303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30303}: Add _utest option to textview; add new tests. Increase coverage
to 100%. Patches by Louie Lu and Terry Jan Reedy.
@end itemize

@node C API<67>,ビルド<77>,IDLE<50>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id890}@anchor{1ede}
@subsubsection C API



@itemize -

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() no longer replaced with a macro
if Py_LIMITED_API is not set.
@end itemize

@node ビルド<77>,ドキュメント<71>,C API<67>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id891}@anchor{1edf}
@subsubsection ビルド



@itemize -

@item 
bpo-29941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29941}: Add @code{--with-assertions} configure flag to explicitly enable C
@code{assert()} checks. Defaults to off. @code{--with-pydebug} implies
@code{--with-assertions}.

@item 
bpo-28787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28787}: Fix out-of-tree builds of Python when configured with
@code{--with--dtrace}.

@item 
bpo-29243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29243}: Prevent unnecessary rebuilding of Python during @code{make test},
@code{make install} and some other make targets when configured with
@code{--enable-optimizations}.

@item 
bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404}: Don't regenerate generated files based on file modification
time anymore: the action is now explicit. Replace @code{make touch} with
@code{make regen-all}.

@item 
bpo-29643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29643}: Fix @code{--enable-optimization} didn't work.
@end itemize

@node ドキュメント<71>,Tools/Demos<48>,ビルド<77>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id892}@anchor{1ee0}
@subsubsection ドキュメント



@itemize -

@item 
bpo-30176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30176}: Add missing attribute related constants in curses
documentation.

@item 
bpo-30052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30052}: the link targets for @ref{192,,bytes()} and @ref{344,,bytearray()} are
now their respective type definitions, rather than the corresponding
builtin function entries. Use @ref{1e9a,,bytes} and
@ref{1e9b,,bytearray} to reference the latter. In order to
ensure this and future cross-reference updates are applied automatically,
the daily documentation builds now disable the default output caching
features in Sphinx.

@item 
bpo-26985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26985}: Add missing info of code object in inspect documentation.
@end itemize

@node Tools/Demos<48>,テスト<68>,ドキュメント<71>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id893}@anchor{1ee1}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-29367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29367}: python-gdb.py now supports also @code{method-wrapper}
(@code{wrapperobject}) objects.
@end itemize

@node テスト<68>,Windows<68>,Tools/Demos<48>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id894}@anchor{1ee2}
@subsubsection テスト



@itemize -

@item 
bpo-30357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30357}: test_thread: setUp() now uses support.threading_setup() and
support.threading_cleanup() to wait until threads complete to avoid random
side effects on following tests. Initial patch written by Grzegorz
Grzywacz.

@item 
bpo-30197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30197}: Enhanced functions swap_attr() and swap_item() in the
test.support module. They now work when delete replaced attribute or item
inside the with statement.  The old value of the attribute or item (or
None if it doesn't exist) now will be assigned to the target of the "as"
clause, if there is one.
@end itemize

@node Windows<68>,,テスト<68>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id895}@anchor{1ee3}
@subsubsection Windows



@itemize -

@item 
bpo-30687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30687}: Locate msbuild.exe on Windows when building rather than
vcvarsall.bat

@item 
bpo-30450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30450}: The build process on Windows no longer depends on Subversion,
instead pulling external code from GitHub via a Python script.  If Python
3.6 is not found on the system (via @code{py -3.6}), NuGet is used to
download a copy of 32-bit Python.
@end itemize

@node Python 3 6 1 final,Python 3 6 1 release candidate 1,Python 3 6 2 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-6-1-final}@anchor{1ee4}
@subsection Python 3.6.1 final


`Release date: 2017-03-21'

@menu
* Core and Builtins: Core and Builtins<175>. 
* ビルド: ビルド<78>. 

@end menu

@node Core and Builtins<175>,ビルド<78>,,Python 3 6 1 final
@anchor{whatsnew/changelog id896}@anchor{1ee5}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-29723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29723}: The @code{sys.path[0]} initialization change for bpo-29139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29139} caused
a regression by revealing an inconsistency in how sys.path is initialized
when executing @code{__main__} from a zipfile, directory, or other import
location. The interpreter now consistently avoids ever adding the import
location's parent directory to @code{sys.path}, and ensures no other
@code{sys.path} entries are inadvertently modified when inserting the import
location named on the command line.
@end itemize

@node ビルド<78>,,Core and Builtins<175>,Python 3 6 1 final
@anchor{whatsnew/changelog id897}@anchor{1ee6}
@subsubsection ビルド



@itemize -

@item 
bpo-27593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27593}: fix format of git information used in sys.version

@item 
Fix incompatible comment in python.h
@end itemize

@node Python 3 6 1 release candidate 1,Python 3 6 0 final,Python 3 6 1 final,変更履歴
@anchor{whatsnew/changelog python-3-6-1-release-candidate-1}@anchor{1ee7}
@subsection Python 3.6.1 release candidate 1


`Release date: 2017-03-04'

@menu
* Core and Builtins: Core and Builtins<176>. 
* ライブラリ: ライブラリ<180>. 
* IDLE: IDLE<51>. 
* Windows: Windows<69>. 
* C API: C API<68>. 
* ドキュメント: ドキュメント<72>. 
* テスト: テスト<69>. 
* ビルド: ビルド<79>. 

@end menu

@node Core and Builtins<176>,ライブラリ<180>,,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id898}@anchor{1ee8}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28893}: Set correct __cause__ for errors about invalid awaitables
returned from __aiter__ and __anext__.

@item 
bpo-29683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29683}: Fixes to memory allocation in _PyCode_SetExtra.  Patch by Brian
Coleman.

@item 
bpo-29684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29684}: Fix minor regression of PyEval_CallObjectWithKeywords. It
should raise TypeError when kwargs is not a dict.  But it might cause segv
when args=NULL and kwargs is not a dict.

@item 
bpo-28598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28598}: Support __rmod__ for subclasses of str being called before
str.__mod__. Patch by Martijn Pieters.

@item 
bpo-29607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29607}: Fix stack_effect computation for CALL_FUNCTION_EX. Patch by
Matthieu Dartiailh.

@item 
bpo-29602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29602}: Fix incorrect handling of signed zeros in complex constructor
for complex subclasses and for inputs having a __complex__ method. Patch
by Serhiy Storchaka.

@item 
bpo-29347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29347}: Fixed possibly dereferencing undefined pointers when creating
weakref objects.

@item 
bpo-29438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29438}: Fixed use-after-free problem in key sharing dict.

@item 
bpo-29319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29319}: Prevent RunMainFromImporter overwriting sys.path[0].

@item 
bpo-29337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29337}: Fixed possible BytesWarning when compare the code objects.
Warnings could be emitted at compile time.

@item 
bpo-29327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29327}: Fixed a crash when pass the iterable keyword argument to
sorted().

@item 
bpo-29034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29034}: Fix memory leak and use-after-free in os module
(path_converter).

@item 
bpo-29159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29159}: Fix regression in bytes(x) when x.__index__() raises Exception.

@item 
bpo-28932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28932}: Do not include <sys/random.h> if it does not exist.

@item 
bpo-25677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25677}: Correct the positioning of the syntax error caret for indented
blocks. Based on patch by Michael Layzell.

@item 
bpo-29000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29000}: Fixed bytes formatting of octals with zero padding in alternate
form.

@item 
bpo-26919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26919}: On Android, operating system data is now always encoded/decoded
to/from UTF-8, instead of the locale encoding to avoid inconsistencies
with os.fsencode() and os.fsdecode() which are already using UTF-8.

@item 
bpo-28991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28991}: functools.lru_cache() was susceptible to an obscure reentrancy
bug triggerable by a monkey-patched len() function.

@item 
bpo-28739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28739}: f-string expressions are no longer accepted as docstrings and
by ast.literal_eval() even if they do not include expressions.

@item 
bpo-28512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28512}: Fixed setting the offset attribute of SyntaxError by
PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

@item 
bpo-28918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28918}: Fix the cross compilation of xxlimited when Python has been
built with Py_DEBUG defined.

@item 
bpo-28731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28731}: Optimize _PyDict_NewPresized() to create correct size dict.
Improve speed of dict literal with constant keys up to 30%.
@end itemize

@node ライブラリ<180>,IDLE<51>,Core and Builtins<176>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id899}@anchor{1ee9}
@subsubsection ライブラリ



@itemize -

@item 
bpo-29169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29169}: Update zlib to 1.2.11.

@item 
bpo-29623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29623}: Allow use of path-like object as a single argument in
ConfigParser.read(). Patch by David Ellis.

@item 
bpo-28963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28963}: Fix out of bound iteration in
asyncio.Future.remove_done_callback implemented in C.

@item 
bpo-29704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29704}: asyncio.subprocess.SubprocessStreamProtocol no longer closes
before all pipes are closed.

@item 
bpo-29271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29271}: Fix Task.current_task and Task.all_tasks implemented in C to
accept None argument as their pure Python implementation.

@item 
bpo-29703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29703}: Fix asyncio to support instantiation of new event loops in
child processes.

@item 
bpo-29376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29376}: Fix assertion error in threading._DummyThread.is_alive().

@item 
bpo-28624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28624}: Add a test that checks that cwd parameter of Popen() accepts
PathLike objects.  Patch by Sayan Chowdhury.

@item 
bpo-28518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28518}: Start a transaction implicitly before a DML statement. Patch by
Aviv Palivoda.

@item 
bpo-29532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29532}: Altering a kwarg dictionary passed to functools.partial() no
longer affects a partial object after creation.

@item 
bpo-29110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29110}: Fix file object leak in aifc.open() when file is given as a
filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: typing.Counter,
typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle
Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

@item 
bpo-29100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29100}: Fix datetime.fromtimestamp() regression introduced in Python
3.6.0: check minimum and maximum years.

@item 
bpo-29519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29519}: Fix weakref spewing exceptions during interpreter shutdown when
used with a rare combination of multiprocessing and custom codecs.

@item 
bpo-29416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29416}: Prevent infinite loop in pathlib.Path.mkdir

@item 
bpo-29444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29444}: Fixed out-of-bounds buffer access in the group() method of the
match object. Based on patch by WGH.

@item 
bpo-29335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29335}: Fix subprocess.Popen.wait() when the child process has exited
to a stopped instead of terminated state (ex: when under ptrace).

@item 
bpo-29290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29290}: Fix a regression in argparse that help messages would wrap at
non-breaking spaces.

@item 
bpo-28735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28735}: Fixed the comparison of mock.MagickMock with mock.ANY.

@item 
bpo-29316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29316}: Restore the provisional status of typing module, add
corresponding note to documentation. Patch by Ivan L.

@item 
bpo-29219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29219}: Fixed infinite recursion in the repr of uninitialized
ctypes.CDLL instances.

@item 
bpo-29011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29011}: Fix an important omission by adding Deque to the typing module.

@item 
bpo-28969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28969}: Fixed race condition in C implementation of
functools.lru_cache. KeyError could be raised when cached function with
full cache was simultaneously called from different threads with the same
uncached arguments.

@item 
bpo-29142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29142}: In urllib.request, suffixes in no_proxy environment variable
with leading dots could match related hostnames again (e.g. .b.c matches
a.b.c). Patch by Milan Oberkirch.

@item 
bpo-28961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28961}: Fix unittest.mock._Call helper: don't ignore the name parameter
anymore. Patch written by Jiajun Huang.

@item 
bpo-29203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29203}: functools.lru_cache() now respects 
@geindex Python Enhancement Proposals; PEP 468
PEP 468@footnote{https://peps.python.org/pep-0468/} and preserves the
order of keyword arguments.  f(a=1, b=2) is now cached separately from
f(b=2, a=1) since both calls could potentially give different results.

@item 
bpo-15812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15812}: inspect.getframeinfo() now correctly shows the first line of a
context. Patch by Sam Breese.

@item 
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094}: Offsets in a ZIP file created with extern file object and modes
"w" and "x" now are relative to the start of the file.

@item 
bpo-29085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29085}: Allow random.Random.seed() to use high quality OS randomness
rather than the pid and time.

@item 
bpo-29061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29061}: Fixed bug in secrets.randbelow() which would hang when given a
negative input.  Patch by Brendan Donegan.

@item 
bpo-29079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29079}: Prevent infinite loop in pathlib.resolve() on Windows

@item 
bpo-13051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13051}: Fixed recursion errors in large or resized
curses.textpad.Textbox.  Based on patch by Tycho Andersen.

@item 
bpo-29119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29119}: Fix weakrefs in the pure python version of
collections.OrderedDict move_to_end() method. Contributed by Andra
Bogildea.

@item 
bpo-9770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9770}: curses.ascii predicates now work correctly with negative
integers.

@item 
bpo-28427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28427}: old keys should not remove new values from WeakValueDictionary
when collecting from another thread.

@item 
bpo-28923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28923}: Remove editor artifacts from Tix.py.

@item 
bpo-29055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29055}: Neaten-up empty population error on random.choice() by
suppressing the upstream exception.

@item 
bpo-28871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28871}: Fixed a crash when deallocate deep ElementTree.

@item 
bpo-19542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19542}: Fix bugs in WeakValueDictionary.setdefault() and
WeakValueDictionary.pop() when a GC collection happens in another thread.

@item 
bpo-20191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20191}: Fixed a crash in resource.prlimit() when passing a sequence
that doesn't own its elements as limits.

@item 
bpo-28779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28779}: multiprocessing.set_forkserver_preload() would crash the
forkserver process if a preloaded module instantiated some multiprocessing
objects such as locks.

@item 
bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847}: dbm.dumb now supports reading read-only files and no longer
writes the index file when it is not changed.

@item 
bpo-26937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26937}: The chown() method of the tarfile.TarFile class does not fail
now when the grp module cannot be imported, as for example on Android
platforms.
@end itemize

@node IDLE<51>,Windows<69>,ライブラリ<180>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id900}@anchor{1eea}
@subsubsection IDLE



@itemize -

@item 
bpo-29071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29071}: IDLE colors f-string prefixes (but not invalid ur prefixes).

@item 
bpo-28572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28572}: Add 10% to coverage of IDLE's test_configdialog. Update and
augment description of the configuration system.
@end itemize

@node Windows<69>,C API<68>,IDLE<51>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id901}@anchor{1eeb}
@subsubsection Windows



@itemize -

@item 
bpo-29579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29579}: Removes readme.txt from the installer

@item 
bpo-29326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29326}: Ignores blank lines in ._pth files (Patch by Alexey Izbyshev)

@item 
bpo-28164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28164}: Correctly handle special console filenames (patch by Eryk Sun)

@item 
bpo-29409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29409}: Implement 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} for io.FileIO (Patch by Eryk Sun)

@item 
bpo-29392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29392}: Prevent crash when passing invalid arguments into msvcrt
module.

@item 
bpo-25778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25778}: winreg does not truncate string correctly (Patch by Eryk Sun)

@item 
bpo-28896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28896}: Deprecate WindowsRegistryFinder and disable it by default.
@end itemize

@node C API<68>,ドキュメント<72>,Windows<69>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id902}@anchor{1eec}
@subsubsection C API



@itemize -

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() is replaced with a macro if
Py_LIMITED_API is not set or set to the value between 0x03050400 and
0x03060000 (not including) or 0x03060100 or higher.

@item 
bpo-29083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29083}: Fixed the declaration of some public API functions.
PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in
limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and
Py_BuildValue() were not available in limited API of version < 3.3 when
PY_SSIZE_T_CLEAN is defined.

@item 
bpo-29058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29058}: All stable API extensions added after Python 3.2 are now
available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of
the minimum Python version supporting this API.
@end itemize

@node ドキュメント<72>,テスト<69>,C API<68>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id903}@anchor{1eed}
@subsubsection ドキュメント



@itemize -

@item 
bpo-28929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28929}: Link the documentation to its source file on GitHub.

@item 
bpo-25008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25008}: Document smtpd.py as effectively deprecated and add a pointer
to aiosmtpd, a third-party asyncio-based replacement.

@item 
bpo-26355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26355}: Add canonical header link on each page to corresponding major
version of the documentation. Patch by Matthias Bussonnier.

@item 
bpo-29349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29349}: Fix Python 2 syntax in code for building the documentation.
@end itemize

@node テスト<69>,ビルド<79>,ドキュメント<72>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id904}@anchor{1eee}
@subsubsection テスト



@itemize -

@item 
bpo-28087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28087}: Skip test_asyncore and test_eintr poll failures on macOS. Skip
some tests of select.poll when running on macOS due to unresolved issues
with the underlying system poll function on some macOS versions.

@item 
bpo-29571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29571}: to match the behaviour of the @code{re.LOCALE} flag,
test_re.test_locale_flag now uses @code{locale.getpreferredencoding(False)}
to determine the candidate encoding for the test regex (allowing it to
correctly skip the test when the default locale encoding is a multi-byte
encoding)

@item 
bpo-28950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28950}: Disallow -j0 to be combined with -T/-l in regrtest command line
arguments.

@item 
bpo-28683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28683}: Fix the tests that bind() a unix socket and raise
PermissionError on Android for a non-root user.

@item 
bpo-26939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26939}: Add the support.setswitchinterval() function to fix
test_functools hanging on the Android armv7 qemu emulator.
@end itemize

@node ビルド<79>,,テスト<69>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id905}@anchor{1eef}
@subsubsection ビルド



@itemize -

@item 
bpo-27593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27593}: sys.version and the platform module python_build(),
python_branch(), and python_revision() functions now use git information
rather than hg when building from a repo.

@item 
bpo-29572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29572}: Update Windows build and OS X installers to use OpenSSL 1.0.2k.

@item 
bpo-26851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26851}: Set Android compilation and link flags.

@item 
bpo-28768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28768}: Fix implicit declaration of function _setmode. Patch by
Masayuki Yamamoto

@item 
bpo-29080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29080}: Removes hard dependency on hg.exe from PCBuild/build.bat

@item 
bpo-23903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23903}: Added missed names to PC/python3.def.

@item 
bpo-28762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28762}: lockf() is available on Android API level 24, but the F_LOCK
macro is not defined in android-ndk-r13.

@item 
bpo-28538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28538}: Fix the compilation error that occurs because if_nameindex() is
available on Android API level 24, but the if_nameindex structure is not
defined.

@item 
bpo-20211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20211}: Do not add the directory for installing C header files and the
directory for installing object code libraries to the cross compilation
search paths. Original patch by Thomas Petazzoni.

@item 
bpo-28849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28849}: Do not define sys.implementation._multiarch on Android.
@end itemize

@node Python 3 6 0 final,Python 3 6 0 release candidate 2,Python 3 6 1 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-6-0-final}@anchor{1ef0}
@subsection Python 3.6.0 final


`Release date: 2016-12-23'

No changes since release candidate 2

@node Python 3 6 0 release candidate 2,Python 3 6 0 release candidate 1,Python 3 6 0 final,変更履歴
@anchor{whatsnew/changelog python-3-6-0-release-candidate-2}@anchor{1ef1}
@subsection Python 3.6.0 release candidate 2


`Release date: 2016-12-16'

@menu
* Core and Builtins: Core and Builtins<177>. 
* Tools/Demos: Tools/Demos<49>. 
* Windows: Windows<70>. 
* ビルド: ビルド<80>. 

@end menu

@node Core and Builtins<177>,Tools/Demos<49>,,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id906}@anchor{1ef2}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28147}: Fix a memory leak in split-table dictionaries: setattr() must
not convert combined table into split table. Patch written by INADA Naoki.

@item 
bpo-28990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28990}: Fix asyncio SSL hanging if connection is closed before
handshake is completed. (Patch by HoHo-Ho)
@end itemize

@node Tools/Demos<49>,Windows<70>,Core and Builtins<177>,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id907}@anchor{1ef3}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-28770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28770}: Fix python-gdb.py for fastcalls.
@end itemize

@node Windows<70>,ビルド<80>,Tools/Demos<49>,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id908}@anchor{1ef4}
@subsubsection Windows



@itemize -

@item 
bpo-28896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28896}: Deprecate WindowsRegistryFinder.
@end itemize

@node ビルド<80>,,Windows<70>,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id909}@anchor{1ef5}
@subsubsection ビルド



@itemize -

@item 
bpo-28898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28898}: Prevent gdb build errors due to HAVE_LONG_LONG redefinition.
@end itemize

@node Python 3 6 0 release candidate 1,Python 3 6 0 beta 4,Python 3 6 0 release candidate 2,変更履歴
@anchor{whatsnew/changelog python-3-6-0-release-candidate-1}@anchor{1ef6}
@subsection Python 3.6.0 release candidate 1


`Release date: 2016-12-06'

@menu
* Core and Builtins: Core and Builtins<178>. 
* ライブラリ: ライブラリ<181>. 
* C API: C API<69>. 
* ドキュメント: ドキュメント<73>. 
* Tools/Demos: Tools/Demos<50>. 

@end menu

@node Core and Builtins<178>,ライブラリ<181>,,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id910}@anchor{1ef7}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: Rather than silently producing a class that doesn't support
zero-argument @code{super()} in methods, failing to pass the new
@code{__classcell__} namespace entry up to @code{type.__new__} now results in a
@code{DeprecationWarning} and a class that supports zero-argument
@code{super()}.

@item 
bpo-28797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28797}: Modifying the class __dict__ inside the __set_name__ method of
a descriptor that is used inside that class no longer prevents calling the
__set_name__ method of other descriptors.

@item 
bpo-28782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28782}: Fix a bug in the implementation @code{yield from} when checking if
the next instruction is YIELD_FROM. Regression introduced by WORDCODE
(bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647}).
@end itemize

@node ライブラリ<181>,C API<69>,Core and Builtins<178>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id911}@anchor{1ef8}
@subsubsection ライブラリ



@itemize -

@item 
bpo-27030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27030}: Unknown escapes in re.sub() replacement template are allowed
again.  But they still are deprecated and will be disabled in 3.7.

@item 
bpo-28835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28835}: Fix a regression introduced in warnings.catch_warnings(): call
warnings.showwarning() if it was overridden inside the context manager.

@item 
bpo-27172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27172}: To assist with upgrades from 2.7, the previously documented
deprecation of @code{inspect.getfullargspec()} has been reversed. This
decision may be revisited again after the Python 2.7 branch is no longer
officially supported.

@item 
bpo-26273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26273}: Add new @code{socket.TCP_CONGESTION} (Linux 2.6.13) and
@code{socket.TCP_USER_TIMEOUT} (Linux 2.6.37) constants. Patch written
by Omar Sandoval.

@item 
bpo-24142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24142}: Reading a corrupt config file left configparser in an invalid
state. Original patch by Florian Höch.

@item 
bpo-28843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28843}: Fix asyncio C Task to handle exceptions __traceback__.
@end itemize

@node C API<69>,ドキュメント<73>,ライブラリ<181>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id912}@anchor{1ef9}
@subsubsection C API



@itemize -

@item 
bpo-28808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28808}: PyUnicode_CompareWithASCIIString() now never raises exceptions.
@end itemize

@node ドキュメント<73>,Tools/Demos<50>,C API<69>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id913}@anchor{1efa}
@subsubsection ドキュメント



@itemize -

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: The data model reference and the porting section in the What's
New guide now cover the additional @code{__classcell__} handling needed for
custom metaclasses to fully support 
@geindex Python Enhancement Proposals; PEP 487
PEP 487@footnote{https://peps.python.org/pep-0487/} and zero-argument
@code{super()}.
@end itemize

@node Tools/Demos<50>,,ドキュメント<73>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id914}@anchor{1efb}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-28023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28023}: Fix python-gdb.py didn't support new dict implementation.
@end itemize

@node Python 3 6 0 beta 4,Python 3 6 0 beta 3,Python 3 6 0 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-6-0-beta-4}@anchor{1efc}
@subsection Python 3.6.0 beta 4


`Release date: 2016-11-21'

@menu
* Core and Builtins: Core and Builtins<179>. 
* ライブラリ: ライブラリ<182>. 
* ドキュメント: ドキュメント<74>. 
* テスト: テスト<70>. 
* ビルド: ビルド<81>. 

@end menu

@node Core and Builtins<179>,ライブラリ<182>,,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id915}@anchor{1efd}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28532}: Show sys.version when -V option is supplied twice.

@item 
bpo-27100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27100}: The with-statement now checks for __enter__ before it checks
for __exit__. This gives less confusing error messages when both methods
are missing. Patch by Jonathan Ellington.

@item 
bpo-28746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28746}: Fix the set_inheritable() file descriptor method on platforms
that do not have the ioctl FIOCLEX and FIONCLEX commands.

@item 
bpo-26920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26920}: Fix not getting the locale's charset upon initializing the
interpreter, on platforms that do not have langinfo.

@item 
bpo-28648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28648}: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X
when decode astral characters.  Patch by Xiang Zhang.

@item 
bpo-19398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19398}: Extra slash no longer added to sys.path components in case of
empty compile-time PYTHONPATH components.

@item 
bpo-28665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28665}: Improve speed of the STORE_DEREF opcode by 40%.

@item 
bpo-28583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28583}: PyDict_SetDefault didn't combine split table when needed. Patch
by Xiang Zhang.

@item 
bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}: Change PendingDeprecationWarning -> DeprecationWarning. As it
was agreed in the issue, __aiter__ returning an awaitable should result in
PendingDeprecationWarning in 3.5 and in DeprecationWarning in 3.6.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Fix a refleak in code that raises DeprecationWarning.

@item 
bpo-28721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28721}: Fix asynchronous generators aclose() and athrow() to handle
StopAsyncIteration propagation properly.
@end itemize

@node ライブラリ<182>,ドキュメント<74>,Core and Builtins<179>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id916}@anchor{1efe}
@subsubsection ライブラリ



@itemize -

@item 
bpo-28752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28752}: Restored the __reduce__() methods of datetime objects.

@item 
bpo-28727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28727}: Regular expression patterns, _sre.SRE_Pattern objects created
by re.compile(), become comparable (only x==y and x!=y operators). This
change should fix the bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: don't duplicate warning filters when
the warnings module is reloaded (thing usually only done in unit tests).

@item 
bpo-20572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20572}: The subprocess.Popen.wait method's undocumented endtime
parameter now raises a DeprecationWarning.

@item 
bpo-25659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25659}: In ctypes, prevent a crash calling the from_buffer() and
from_buffer_copy() methods on abstract classes like Array.

@item 
bpo-19717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19717}: Makes Path.resolve() succeed on paths that do not exist. Patch
by Vajrasky Kok

@item 
bpo-28563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28563}: Fixed possible DoS and arbitrary code execution when handle
plural form selections in the gettext module.  The expression parser now
supports exact syntax supported by GNU gettext.

@item 
bpo-28387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28387}: Fixed possible crash in _io.TextIOWrapper deallocator when the
garbage collector is invoked in other thread.  Based on patch by Sebastian
Cufre.

@item 
bpo-28600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28600}: Optimize loop.call_soon.

@item 
bpo-28613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28613}: Fix get_event_loop() return the current loop if called from
coroutines/callbacks.

@item 
bpo-28634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28634}: Fix asyncio.isfuture() to support unittest.Mock.

@item 
bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}: Fix refleak in _asyncio.Future.__iter__().throw.

@item 
bpo-28639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28639}: Fix inspect.isawaitable to always return bool Patch by Justin
Mayfield.

@item 
bpo-28652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28652}: Make loop methods reject socket kinds they do not support.

@item 
bpo-28653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28653}: Fix a refleak in functools.lru_cache.

@item 
bpo-28703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28703}: Fix asyncio.iscoroutinefunction to handle Mock objects.

@item 
bpo-28704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28704}: Fix create_unix_server to support Path-like objects (PEP 519).

@item 
bpo-28720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28720}: Add collections.abc.AsyncGenerator.
@end itemize

@node ドキュメント<74>,テスト<70>,ライブラリ<182>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id917}@anchor{1eff}
@subsubsection ドキュメント



@itemize -

@item 
bpo-28513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28513}: Documented command-line interface of zipfile.
@end itemize

@node テスト<70>,ビルド<81>,ドキュメント<74>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id918}@anchor{1f00}
@subsubsection テスト



@itemize -

@item 
bpo-28666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28666}: Now test.support.rmtree is able to remove unwritable or
unreadable directories.

@item 
bpo-23839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23839}: Various caches now are cleared before running every test file.
@end itemize

@node ビルド<81>,,テスト<70>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id919}@anchor{1f01}
@subsubsection ビルド



@itemize -

@item 
bpo-10656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10656}: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
Michael Haubenwallner.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Rename --with-optimiations to --enable-optimizations.

@item 
bpo-28676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28676}: Prevent missing 'getentropy' declaration warning on macOS.
Patch by Gareth Rees.
@end itemize

@node Python 3 6 0 beta 3,Python 3 6 0 beta 2,Python 3 6 0 beta 4,変更履歴
@anchor{whatsnew/changelog python-3-6-0-beta-3}@anchor{1f02}
@subsection Python 3.6.0 beta 3


`Release date: 2016-10-31'

@menu
* Core and Builtins: Core and Builtins<180>. 
* ライブラリ: ライブラリ<183>. 
* Windows: Windows<71>. 
* ビルド: ビルド<82>. 
* テスト: テスト<71>. 

@end menu

@node Core and Builtins<180>,ライブラリ<183>,,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id920}@anchor{1f03}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28128}: Deprecation warning for invalid str and byte escape sequences
now prints better information about where the error occurs. Patch by
Serhiy Storchaka and Eric Smith.

@item 
bpo-28509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28509}: dict.update() no longer allocate unnecessary large memory.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Fixed potential crash in PyUnicode_AsDecodedObject() in debug
build.

@item 
bpo-28517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28517}: Fixed of-by-one error in the peephole optimizer that caused
keeping unreachable code.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Improved exception reporting for problematic __set_name__
attributes.

@item 
bpo-23782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23782}: Fixed possible memory leak in _PyTraceback_Add() and exception
loss in PyTraceBack_Here().

@item 
bpo-28471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28471}: Fix "Python memory allocator called without holding the GIL"
crash in socket.setblocking.
@end itemize

@node ライブラリ<183>,Windows<71>,Core and Builtins<180>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id921}@anchor{1f04}
@subsubsection ライブラリ



@itemize -

@item 
bpo-27517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27517}: LZMA compressor and decompressor no longer raise exceptions if
given empty data twice.  Patch by Benjamin Fogle.

@item 
bpo-28549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28549}: Fixed segfault in curses's addch() with ncurses6.

@item 
bpo-28449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28449}: tarfile.open() with mode "r" or "r:" now tries to open a tar
file with compression before trying to open it without compression.
Otherwise it had 50% chance failed with ignore_zeros=True.

@item 
bpo-23262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23262}: The webbrowser module now supports Firefox 36+ and derived
browsers.  Based on patch by Oleg Broytman.

@item 
bpo-27939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27939}: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused
by representing the scale as float value internally in Tk.  tkinter.IntVar
now works if float value is set to underlying Tk variable.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: The various ways of specifying weights for random.choices() now
produce the same result sequences.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar().prmonth() no longer prints a space at
the start of new line after printing a month's calendar.  Patch by Xiang
Zhang.

@item 
bpo-20491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20491}: The textwrap.TextWrapper class now honors non-breaking spaces.
Based on patch by Kaarle Ritvanen.

@item 
bpo-28353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28353}: os.fwalk() no longer fails on broken links.

@item 
bpo-28430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28430}: Fix iterator of C implemented asyncio.Future doesn't accept
non-None value is passed to it.send(val).

@item 
bpo-27025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27025}: Generated names for Tkinter widgets now start by the "!" prefix
for readability.

@item 
bpo-25464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25464}: Fixed HList.header_exists() in tkinter.tix module by addin a
workaround to Tix library bug.

@item 
bpo-28488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28488}: shutil.make_archive() no longer adds entry "./" to ZIP archive.

@item 
bpo-25953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25953}: re.sub() now raises an error for invalid numerical group
reference in replacement template even if the pattern is not found in the
string.  Error message for invalid group reference now includes the group
index and the position of the reference. Based on patch by SilentGhost.

@item 
bpo-18219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18219}: Optimize csv.DictWriter for large number of columns. Patch by
Mariatta Wijaya.

@item 
bpo-28448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28448}: Fix C implemented asyncio.Future didn't work on Windows.

@item 
bpo-28480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28480}: Fix error building socket module when multithreading is
disabled.

@item 
bpo-24452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24452}: Make webbrowser support Chrome on Mac OS X.

@item 
bpo-20766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20766}: Fix references leaked by pdb in the handling of SIGINT
handlers.

@item 
bpo-28492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28492}: Fix how StopIteration exception is raised in _asyncio.Future.

@item 
bpo-28500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28500}: Fix asyncio to handle async gens GC from another thread.

@item 
bpo-26923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26923}: Fix asyncio.Gather to refuse being cancelled once all children
are done. Patch by Johannes Ebke.

@item 
bpo-26796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26796}: Don't configure the number of workers for default threadpool
executor. Initial patch by Hans Lawrenz.

@item 
bpo-28544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28544}: Implement asyncio.Task in C.
@end itemize

@node Windows<71>,ビルド<82>,ライブラリ<183>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id922}@anchor{1f05}
@subsubsection Windows



@itemize -

@item 
bpo-28522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28522}: Fixes mishandled buffer reallocation in getpathp.c
@end itemize

@node ビルド<82>,テスト<71>,Windows<71>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id923}@anchor{1f06}
@subsubsection ビルド



@itemize -

@item 
bpo-28444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28444}: Fix missing extensions modules when cross compiling.

@item 
bpo-28208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28208}: Update Windows build and OS X installers to use SQLite 3.14.2.

@item 
bpo-28248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28248}: Update Windows build and OS X installers to use OpenSSL 1.0.2j.
@end itemize

@node テスト<71>,,ビルド<82>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id924}@anchor{1f07}
@subsubsection テスト



@itemize -

@item 
bpo-26944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26944}: Fix test_posix for Android where 'id -G' is entirely wrong or
missing the effective gid.

@item 
bpo-28409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28409}: regrtest: fix the parser of command line arguments.
@end itemize

@node Python 3 6 0 beta 2,Python 3 6 0 beta 1,Python 3 6 0 beta 3,変更履歴
@anchor{whatsnew/changelog python-3-6-0-beta-2}@anchor{1f08}
@subsection Python 3.6.0 beta 2


`Release date: 2016-10-10'

@menu
* Core and Builtins: Core and Builtins<181>. 
* ライブラリ: ライブラリ<184>. 
* Windows: Windows<72>. 
* C API: C API<70>. 
* ビルド: ビルド<83>. 
* テスト: テスト<72>. 

@end menu

@node Core and Builtins<181>,ライブラリ<184>,,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id925}@anchor{1f09}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28183}: Optimize and cleanup dict iteration.

@item 
bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}: Added C implementation of asyncio.Future. Original patch by
Yury Selivanov.

@item 
bpo-28379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28379}: Added sanity checks and tests for PyUnicode_CopyCharacters().
Patch by Xiang Zhang.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The type of long range iterator is now registered as Iterator.
Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: Creating instances of range_iterator by calling range_iterator
type now is deprecated.  Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The constructor of range_iterator now checks that step is not
0. Patch by Oren Milman.

@item 
bpo-26906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26906}: Resolving special methods of uninitialized type now causes
implicit initialization of the type instead of a fail.

@item 
bpo-18287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18287}: PyType_Ready() now checks that tp_name is not NULL. Original
patch by Niklas Koep.

@item 
bpo-24098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24098}: Fixed possible crash when AST is changed in process of
compiling it.

@item 
bpo-28201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28201}: Dict reduces possibility of 2nd conflict in hash table when
hashes have same lower bits.

@item 
bpo-28350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28350}: String constants with null character no longer interned.

@item 
bpo-26617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26617}: Fix crash when GC runs during weakref callbacks.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: String constants now interned recursively in tuples and
frozensets.

@item 
bpo-21578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21578}: Fixed misleading error message when ImportError called with
invalid keyword args.

@item 
bpo-28203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28203}: Fix incorrect type in complex(1.0, @{2:3@}) error message. Patch
by Soumya Sharma.

@item 
bpo-28086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28086}: Single var-positional argument of tuple subtype was passed
unscathed to the C-defined function.  Now it is converted to exact tuple.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Now __set_name__ is looked up on the class instead of the
instance.

@item 
bpo-27955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27955}: Fallback on reading /dev/urandom device when the getrandom()
syscall fails with EPERM, for example when blocked by SECCOMP.

@item 
bpo-28192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28192}: Don't import readline in isolated mode.

@item 
Upgrade internal unicode databases to Unicode version 9.0.0.

@item 
bpo-28131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28131}: Fix a regression in zipimport's compile_source().  zipimport
should use the same optimization level as the interpreter.

@item 
bpo-28126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28126}: Replace Py_MEMCPY with memcpy(). Visual Studio can properly
optimize memcpy().

@item 
bpo-28120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28120}: Fix dict.pop() for split dictionary when trying to remove a
"pending key" (Not yet inserted in split-table). Patch by Xiang Zhang.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Raise DeprecationWarning when async and await keywords are used
as variable/attribute/class/function name.
@end itemize

@node ライブラリ<184>,Windows<72>,Core and Builtins<181>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id926}@anchor{1f0a}
@subsubsection ライブラリ



@itemize -

@item 
bpo-27998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27998}: Fixed bytes path support in os.scandir() on Windows. Patch by
Eryk Sun.

@item 
bpo-28317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28317}: The disassembler now decodes FORMAT_VALUE argument.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Fixed writing ZIP files that starts not from the start of the
file.  Offsets in ZIP file now are relative to the start of the archive in
conforming to the specification.

@item 
bpo-28380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28380}: unittest.mock Mock autospec functions now properly support
assert_called, assert_not_called, and assert_called_once.

@item 
bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}: remove statistics.geometric_mean and defer until 3.7.

@item 
bpo-28229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28229}: lzma module now supports pathlib.

@item 
bpo-28321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28321}: Fixed writing non-BMP characters with binary format in
plistlib.

@item 
bpo-28225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28225}: bz2 module now supports pathlib.  Initial patch by Ethan
Furman.

@item 
bpo-28227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28227}: gzip now supports pathlib.  Patch by Ethan Furman.

@item 
bpo-27358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27358}: Optimized merging var-keyword arguments and improved error
message when passing a non-mapping as a var-keyword argument.

@item 
bpo-28257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28257}: Improved error message when passing a non-iterable as a
var-positional argument.  Added opcode BUILD_TUPLE_UNPACK_WITH_CALL.

@item 
bpo-28322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28322}: Fixed possible crashes when unpickle itertools objects from
incorrect pickle data.  Based on patch by John Leitch.

@item 
bpo-28228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28228}: imghdr now supports pathlib.

@item 
bpo-28226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28226}: compileall now supports pathlib.

@item 
bpo-28314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28314}: Fix function declaration (C flags) for the getiterator() method
of xml.etree.ElementTree.Element.

@item 
bpo-28148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28148}: Stop using localtime() and gmtime() in the time module.
Introduced platform independent _PyTime_localtime API that is similar to
POSIX localtime_r, but available on all platforms.  Patch by Ed Schouten.

@item 
bpo-28253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28253}: Fixed calendar functions for extreme months: 0001-01 and
9999-12. Methods itermonthdays() and itermonthdays2() are reimplemented so
that they don't call itermonthdates() which can cause datetime.date
under/overflow.

@item 
bpo-28275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28275}: Fixed possible use after free in the decompress() methods of
the LZMADecompressor and BZ2Decompressor classes. Original patch by John
Leitch.

@item 
bpo-27897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27897}: Fixed possible crash in sqlite3.Connection.create_collation()
if pass invalid string-like object as a name.  Patch by Xiang Zhang.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: random.choices() now has k as a keyword-only argument to
improve the readability of common cases and come into line with the
signature used in other languages.

@item 
bpo-18893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18893}: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py.
Patch by Madison May.

@item 
bpo-27611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27611}: Fixed support of default root window in the tkinter.tix module.
Added the master parameter in the DisplayStyle constructor.

@item 
bpo-27348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27348}: In the traceback module, restore the formatting of exception
messages like "Exception: None".  This fixes a regression introduced in
3.5a2.

@item 
bpo-25651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25651}: Allow false values to be used for msg parameter of subTest().

@item 
bpo-27778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27778}: Fix a memory leak in os.getrandom() when the getrandom() is
interrupted by a signal and a signal handler raises a Python exception.

@item 
bpo-28200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28200}: Fix memory leak on Windows in the os module (fix
path_converter() function).

@item 
bpo-25400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25400}: RobotFileParser now correctly returns default values for
crawl_delay and request_rate.  Initial patch by Peter Wirtz.

@item 
bpo-27932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}: Prevent memory leak in win32_ver().

@item 
Fix UnboundLocalError in socket._sendfile_use_sendfile.

@item 
bpo-28075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28075}: Check for ERROR_ACCESS_DENIED in Windows implementation of
os.stat().  Patch by Eryk Sun.

@item 
bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}: Warning message emitted by using inline flags in the middle of
regular expression now contains a (truncated) regex pattern. Patch by Tim
Graham.

@item 
bpo-25270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25270}: Prevent codecs.escape_encode() from raising SystemError when an
empty bytestring is passed.

@item 
bpo-28181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28181}: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

@item 
bpo-25895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25895}: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by
Gergely Imreh and Markus Holtermann.

@item 
bpo-28114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28114}: Fix a crash in parse_envlist() when env contains byte strings.
Patch by Eryk Sun.

@item 
bpo-27599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27599}: Fixed buffer overrun in binascii.b2a_qp() and
binascii.a2b_qp().

@item 
bpo-27906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27906}: Fix socket accept exhaustion during high TCP traffic. Patch by
Kevin Conway.

@item 
bpo-28174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28174}: Handle when SO_REUSEPORT isn't properly supported. Patch by
Seth Michael Larson.

@item 
bpo-26654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26654}: Inspect functools.partial in asyncio.Handle.__repr__. Patch by
iceboy.

@item 
bpo-26909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26909}: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

@item 
bpo-28176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28176}: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

@item 
bpo-27759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27759}: Fix selectors incorrectly retain invalid file descriptors.
Patch by Mark Williams.

@item 
bpo-28368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28368}: Refuse monitoring processes if the child watcher has no loop
attached. Patch by Vincent Michel.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Raise RuntimeError when transport's FD is used with add_reader,
add_writer, etc.

@item 
bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг
Марк.

@item 
bpo-28371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28371}: Deprecate passing asyncio.Handles to run_in_executor.

@item 
bpo-28372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28372}: Fix asyncio to support formatting of non-python coroutines.

@item 
bpo-28399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28399}: Remove UNIX socket from FS before binding. Patch by Коренберг
Марк.

@item 
bpo-27972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27972}: Prohibit Tasks to await on themselves.
@end itemize

@node Windows<72>,C API<70>,ライブラリ<184>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id927}@anchor{1f0b}
@subsubsection Windows



@itemize -

@item 
bpo-28402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28402}: Adds signed catalog files for stdlib on Windows.

@item 
bpo-28333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28333}: Enables Unicode for ps1/ps2 and input() prompts. (Patch by Eryk
Sun)

@item 
bpo-28251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28251}: Improvements to help manuals on Windows.

@item 
bpo-28110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28110}: launcher.msi has different product codes between 32-bit and
64-bit

@item 
bpo-28161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28161}: Opening CON for write access fails

@item 
bpo-28162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28162}: WindowsConsoleIO readall() fails if first line starts with
Ctrl+Z

@item 
bpo-28163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28163}: WindowsConsoleIO fileno() passes wrong flags to _open_osfhandle

@item 
bpo-28164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28164}: _PyIO_get_console_type fails for various paths

@item 
bpo-28137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28137}: Renames Windows path file to ._pth

@item 
bpo-28138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28138}: Windows ._pth file should allow import site
@end itemize

@node C API<70>,ビルド<83>,Windows<72>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id928}@anchor{1f0c}
@subsubsection C API



@itemize -

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Deprecated undocumented functions PyUnicode_AsEncodedObject(),
PyUnicode_AsDecodedObject(), PyUnicode_AsDecodedUnicode() and
PyUnicode_AsEncodedUnicode().
@end itemize

@node ビルド<83>,テスト<72>,C API<70>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id929}@anchor{1f0d}
@subsubsection ビルド



@itemize -

@item 
bpo-28258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28258}: Fixed build with Estonian locale (python-config and distclean
targets in Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-26661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26661}: setup.py now detects system libffi with multiarch wrapper.

@item 
bpo-15819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15819}: Remove redundant include search directory option for building
outside the source tree.
@end itemize

@node テスト<72>,,ビルド<83>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id930}@anchor{1f0e}
@subsubsection テスト



@itemize -

@item 
bpo-28217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28217}: Adds _testconsole module to test console input.
@end itemize

@node Python 3 6 0 beta 1,Python 3 6 0 alpha 4,Python 3 6 0 beta 2,変更履歴
@anchor{whatsnew/changelog python-3-6-0-beta-1}@anchor{1f0f}
@subsection Python 3.6.0 beta 1


`Release date: 2016-09-12'

@menu
* Core and Builtins: Core and Builtins<182>. 
* ライブラリ: ライブラリ<185>. 
* IDLE: IDLE<52>. 
* C API: C API<71>. 
* テスト: テスト<73>. 
* ビルド: ビルド<84>. 
* Tools/Demos: Tools/Demos<51>. 
* Windows: Windows<73>. 

@end menu

@node Core and Builtins<182>,ライブラリ<185>,,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id931}@anchor{1f10}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: The __class__ cell used by zero-argument super() is now
initialized from type.__new__ rather than __build_class__, so class
methods relying on that will now work correctly when called from metaclass
methods during class creation. Patch by Martin Teichmann.

@item 
bpo-25221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25221}: Fix corrupted result from PyLong_FromLong(0) when Python is
compiled with NSMALLPOSINTS = 0.

@item 
bpo-27080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27080}: Implement formatting support for 
@geindex Python Enhancement Proposals; PEP 515
PEP 515@footnote{https://peps.python.org/pep-0515/}.  Initial patch by
Chris Angelico.

@item 
bpo-27199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27199}: In tarfile, expose copyfileobj bufsize to improve throughput.
Patch by Jason Fried.

@item 
bpo-27948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27948}: In f-strings, only allow backslashes inside the braces (where
the expressions are).  This is a breaking change from the 3.6 alpha
releases, where backslashes are allowed anywhere in an f-string.  Also,
require that expressions inside f-strings be enclosed within literal
braces, and not escapes like @code{f'\x7b"hi"\x7d'}.

@item 
bpo-28046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28046}: Remove platform-specific directories from sys.path.

@item 
bpo-28071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28071}: Add early-out for differencing from an empty set.

@item 
bpo-25758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25758}: Prevents zipimport from unnecessarily encoding a filename
(patch by Eryk Sun)

@item 
bpo-25856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25856}: The __module__ attribute of extension classes and functions now
is interned. This leads to more compact pickle data with protocol 4.

@item 
bpo-27213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27213}: Rework CALL_FUNCTION* opcodes to produce shorter and more
efficient bytecode. Patch by Demur Rumed, design by Serhiy Storchaka,
reviewed by Serhiy Storchaka and Victor Stinner.

@item 
bpo-26331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26331}: Implement tokenizing support for 
@geindex Python Enhancement Proposals; PEP 515
PEP 515@footnote{https://peps.python.org/pep-0515/}. Patch by Georg
Brandl.

@item 
bpo-27999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27999}: Make "global after use" a SyntaxError, and ditto for nonlocal.
Patch by Ivan Levkivskyi.

@item 
bpo-28003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28003}: Implement 
@geindex Python Enhancement Proposals; PEP 525
PEP 525@footnote{https://peps.python.org/pep-0525/} -- Asynchronous Generators.

@item 
bpo-27985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27985}: Implement 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} -- Syntax for Variable Annotations. Patch
by Ivan Levkivskyi.

@item 
bpo-26058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26058}: Add a new private version to the builtin dict type, incremented
at each dictionary creation and at each dictionary change. Implementation
of the PEP 509.

@item 
bpo-27364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27364}: A backslash-character pair that is not a valid escape sequence
now generates a DeprecationWarning.  Patch by Emanuel Barry.

@item 
bpo-27350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27350}: @code{dict} implementation is changed like PyPy. It is more
compact and preserves insertion order. (Concept developed by Raymond
Hettinger and patch by Inada Naoki.)

@item 
bpo-27911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27911}: Remove unnecessary error checks in
@code{exec_builtin_or_dynamic()}.

@item 
bpo-27078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27078}: Added BUILD_STRING opcode.  Optimized f-strings evaluation.

@item 
bpo-17884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17884}: Python now requires systems with inttypes.h and stdint.h

@item 
bpo-27961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27961}: Require platforms to support @code{long long}. Python hasn't
compiled without @code{long long} for years, so this is basically a
formality.

@item 
bpo-27355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27355}: Removed support for Windows CE.  It was never finished, and
Windows CE is no longer a relevant platform for Python.

@item 
Implement 
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/}.

@item 
bpo-27870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27870}: A left shift of zero by a large integer no longer attempts to
allocate large amounts of memory.

@item 
bpo-25402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25402}: In int-to-decimal-string conversion, improve the estimate of
the intermediate memory required, and remove an unnecessarily strict
overflow check. Patch by Serhiy Storchaka.

@item 
bpo-27214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27214}: In long_invert, be more careful about modifying object returned
by long_add, and remove an unnecessary check for small longs. Thanks Oren
Milman for analysis and patch.

@item 
bpo-27506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27506}: Support passing the bytes/bytearray.translate() "delete"
argument by keyword.

@item 
bpo-27812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27812}: Properly clear out a generator's frame's backreference to the
generator to prevent crashes in frame.clear().

@item 
bpo-27811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27811}: Fix a crash when a coroutine that has not been awaited is
finalized with warnings-as-errors enabled.

@item 
bpo-27587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27587}: Fix another issue found by PVS-Studio: Null pointer check after
use of 'def' in _PyState_AddModule(). Initial patch by Christian Heimes.

@item 
bpo-27792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27792}: The modulo operation applied to @code{bool} and other @code{int}
subclasses now always returns an @code{int}. Previously the return type
depended on the input values. Patch by Xiang Zhang.

@item 
bpo-26984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26984}: int() now always returns an instance of exact int.

@item 
bpo-25604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25604}: Fix a minor bug in integer true division; this bug could
potentially have caused off-by-one-ulp results on platforms with
unreliable ldexp implementations.

@item 
bpo-24254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24254}: Make class definition namespace ordered by default.

@item 
bpo-27662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27662}: Fix an overflow check in @code{List_New}: the original code was
checking against @code{Py_SIZE_MAX} instead of the correct upper bound of
@code{Py_SSIZE_T_MAX}. Patch by Xiang Zhang.

@item 
bpo-27782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27782}: Multi-phase extension module import now correctly allows the
@code{m_methods} field to be used to add module level functions to instances
of non-module types returned from @code{Py_create_mod}. Patch by Xiang Zhang.

@item 
bpo-27936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27936}: The round() function accepted a second None argument for some
types but not for others.  Fixed the inconsistency by accepting None for
all numeric types.

@item 
bpo-27487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27487}: Warn if a submodule argument to "python -m" or
runpy.run_module() is found in sys.modules after parent packages are
imported, but before the submodule is executed.

@item 
bpo-27157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27157}: Make only type() itself accept the one-argument form. Patch by
Eryk Sun and Emanuel Barry.

@item 
bpo-27558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27558}: Fix a SystemError in the implementation of "raise" statement.
In a brand new thread, raise a RuntimeError since there is no active
exception to reraise. Patch written by Xiang Zhang.

@item 
bpo-28008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28008}: Implement 
@geindex Python Enhancement Proposals; PEP 530
PEP 530@footnote{https://peps.python.org/pep-0530/} -- asynchronous comprehensions.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: Fix memory leak in codeobject.c
@end itemize

@node ライブラリ<185>,IDLE<52>,Core and Builtins<182>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id932}@anchor{1f11}
@subsubsection ライブラリ



@itemize -

@item 
bpo-28732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28732}: Fix crash in os.spawnv() with no elements in args

@item 
bpo-28485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28485}: Always raise ValueError for negative
compileall.compile_dir(workers=...) parameter, even when multithreading is
unavailable.

@item 
bpo-28037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28037}: Use sqlite3_get_autocommit() instead of setting
Connection->inTransaction manually.

@item 
bpo-25283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25283}: Attributes tm_gmtoff and tm_zone are now available on all
platforms in the return values of time.localtime() and time.gmtime().

@item 
bpo-24454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24454}: Regular expression match object groups are now accessible using
__getitem__. "mo[x]" is equivalent to "mo.group(x)".

@item 
bpo-10740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10740}: sqlite3 no longer implicitly commit an open transaction before
DDL statements.

@item 
bpo-17941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17941}: Add a `module' parameter to collections.namedtuple().

@item 
bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}: Inline flags now should be used only at the start of the
regular expression. Deprecation warning is emitted if uses them in the
middle of the regular expression.

@item 
bpo-26885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26885}: xmlrpc now supports unmarshalling additional data types used by
Apache XML-RPC implementation for numerics and None.

@item 
bpo-28070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28070}: Fixed parsing inline verbose flag in regular expressions.

@item 
bpo-19500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19500}: Add client-side SSL session resumption to the ssl module.

@item 
bpo-28022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28022}: Deprecate ssl-related arguments in favor of SSLContext. The
deprecation include manual creation of SSLSocket and certfile/keyfile (or
similar) in ftplib, httplib, imaplib, smtplib, poplib and urllib.

@item 
bpo-28043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28043}: SSLContext has improved default settings: OP_NO_SSLv2,
OP_NO_SSLv3, OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE,
OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE and HIGH ciphers without MD5.

@item 
bpo-24693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24693}: Changed some RuntimeError's in the zipfile module to more
appropriate types. Improved some error messages and debugging output.

@item 
bpo-17909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17909}: @code{json.load} and @code{json.loads} now support binary input
encoded as UTF-8, UTF-16 or UTF-32. Patch by Serhiy Storchaka.

@item 
bpo-27137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27137}: the pure Python fallback implementation of
@code{functools.partial} now matches the behaviour of its accelerated C
counterpart for subclassing, pickling and text representation purposes.
Patch by Emanuel Barry and Serhiy Storchaka.

@item 
Fix possible integer overflows and crashes in the mmap module with unusual
usage patterns.

@item 
bpo-1703178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1703178}: Fix the ability to pass the --link-objects option to the
distutils build_ext command.

@item 
bpo-28019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28019}: itertools.count() no longer rounds non-integer step in range
between 1.0 and 2.0 to 1.

@item 
bpo-18401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18401}: Pdb now supports the 'readrc' keyword argument to control
whether .pdbrc files should be read.  Patch by Martin Matusiak and Sam
Kimbrel.

@item 
bpo-25969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25969}: Update the lib2to3 grammar to handle the unpacking
generalizations added in 3.5.

@item 
bpo-14977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14977}: mailcap now respects the order of the lines in the mailcap
files ("first match"), as required by RFC 1542.  Patch by Michael Lazar.

@item 
bpo-28082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28082}: Convert re flag constants to IntFlag.

@item 
bpo-28025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28025}: Convert all ssl module constants to IntEnum and IntFlags.
SSLContext properties now return flags and enums.

@item 
bpo-23591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23591}: Add Flag, IntFlag, and auto() to enum module.

@item 
bpo-433028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=433028}: Added support of modifier spans in regular expressions.

@item 
bpo-24594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24594}: Validates persist parameter when opening MSI database

@item 
bpo-17582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17582}: xml.etree.ElementTree nows preserves whitespaces in attributes
(Patch by Duane Griffin.  Reviewed and approved by Stefan Behnel.)

@item 
bpo-28047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28047}: Fixed calculation of line length used for the base64 CTE in the
new email policies.

@item 
bpo-27576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27576}: Fix call order in OrderedDict.__init__().

@item 
email.generator.DecodedGenerator now supports the policy keyword.

@item 
bpo-28027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28027}: Remove undocumented modules from @code{Lib/plat-*}: IN, CDROM,
DLFCN, TYPES, CDIO, and STROPTS.

@item 
bpo-27445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27445}: Don't pass str(_charset) to MIMEText.set_payload(). Patch by
Claude Paroz.

@item 
bpo-24277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24277}: The new email API is no longer provisional, and the docs have
been reorganized and rewritten to emphasize the new API.

@item 
bpo-22450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22450}: urllib now includes an @code{Accept: */*} header among the default
headers. This makes the results of REST API requests more consistent and
predictable especially when proxy servers are involved.

@item 
lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
between runs given the same Grammar.txt input regardless of the hash
randomization setting.

@item 
bpo-28005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28005}: Allow ImportErrors in encoding implementation to propagate.

@item 
bpo-26667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26667}: Support path-like objects in importlib.util.

@item 
bpo-27570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27570}: Avoid zero-length memcpy() etc calls with null source pointers
in the "ctypes" and "array" modules.

@item 
bpo-22233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22233}: Break email header lines `only' on the RFC specified CR and LF
characters, not on arbitrary unicode line breaks.  This also fixes a bug
in HTTP header parsing.

@item 
bpo-27331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27331}: The email.mime classes now all accept an optional policy
keyword.

@item 
bpo-27988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27988}: Fix email iter_attachments incorrect mutation of payload list.

@item 
bpo-16113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16113}: Add SHA-3 and SHAKE support to hashlib module.

@item 
Eliminate a tautological-pointer-compare warning in _scproxy.c.

@item 
bpo-27776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27776}: The @ref{746,,os.urandom()} function does now block on Linux 3.17
and newer until the system urandom entropy pool is initialized to increase
the security. This change is part of the 
@geindex Python Enhancement Proposals; PEP 524
PEP 524@footnote{https://peps.python.org/pep-0524/}.

@item 
bpo-27778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27778}: Expose the Linux @code{getrandom()} syscall as a new
@ref{eb9,,os.getrandom()} function. This change is part of the 
@geindex Python Enhancement Proposals; PEP 524
PEP 524@footnote{https://peps.python.org/pep-0524/}.

@item 
bpo-27691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27691}: Fix ssl module's parsing of GEN_RID subject alternative name
fields in X.509 certs.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: Add random.choices().

@item 
bpo-25761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25761}: Improved error reporting about truncated pickle data in C
implementation of unpickler.  UnpicklingError is now raised instead of
AttributeError and ValueError in some cases.

@item 
bpo-26798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26798}: Add BLAKE2 (blake2b and blake2s) to hashlib.

@item 
bpo-26032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26032}: Optimized globbing in pathlib by using os.scandir(); it is now
about 1.5--4 times faster.

@item 
bpo-25596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25596}: Optimized glob() and iglob() functions in the glob module; they
are now about 3--6 times faster.

@item 
bpo-27928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27928}: Add scrypt (password-based key derivation function) to hashlib
module (requires OpenSSL 1.1.0).

@item 
bpo-27850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27850}: Remove 3DES from ssl module's default cipher list to counter
measure sweet32 attack (
@geindex Common Vulnerabilities and Exposures; CVE 2016-2183
CVE 2016-2183@footnote{https://www.cve.org/CVERecord?id=CVE-2016-2183}).

@item 
bpo-27766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27766}: Add ChaCha20 Poly1305 to ssl module's default cipher list.
(Required OpenSSL 1.1.0 or LibreSSL).

@item 
bpo-25387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25387}: Check return value of winsound.MessageBeep.

@item 
bpo-27866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27866}: Add SSLContext.get_ciphers() method to get a list of all
enabled ciphers.

@item 
bpo-27744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27744}: Add AF_ALG (Linux Kernel crypto) to socket module.

@item 
bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}: Port ssl and hashlib module to OpenSSL 1.1.0.

@item 
bpo-11620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11620}: Fix support for SND_MEMORY in winsound.PlaySound.  Based on a
patch by Tim Lesher.

@item 
bpo-11734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11734}: Add support for IEEE 754 half-precision floats to the struct
module. Based on a patch by Eli Stevens.

@item 
bpo-27919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27919}: Deprecated @code{extra_path} distribution option in distutils
packaging.

@item 
bpo-23229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23229}: Add new @code{cmath} constants: @code{cmath.inf} and @code{cmath.nan} to
match @code{math.inf} and @code{math.nan}, and also @code{cmath.infj} and
@code{cmath.nanj} to match the format used by complex repr.

@item 
bpo-27842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27842}: The csv.DictReader now returns rows of type OrderedDict.
(Contributed by Steve Holden.)

@item 
Remove support for passing a file descriptor to os.access. It never worked
but previously didn't raise.

@item 
bpo-12885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12885}: Fix error when distutils encounters symlink.

@item 
bpo-27881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27881}: Fixed possible bugs when setting
sqlite3.Connection.isolation_level. Based on patch by Xiang Zhang.

@item 
bpo-27861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27861}: Fixed a crash in sqlite3.Connection.cursor() when a factory
creates not a cursor.  Patch by Xiang Zhang.

@item 
bpo-19884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19884}: Avoid spurious output on OS X with Gnu Readline.

@item 
bpo-27706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27706}: Restore deterministic behavior of random.Random().seed() for
string seeds using seeding version 1.  Allows sequences of calls to
random() to exactly match those obtained in Python 2. Patch by Nofar
Schnider.

@item 
bpo-10513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10513}: Fix a regression in Connection.commit().  Statements should not
be reset after a commit.

@item 
bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}: Chunked transfer encoding support added to
http.client.HTTPConnection requests.  The
urllib.request.AbstractHTTPHandler class does not enforce a Content-Length
header any more.  If a HTTP request has a file or iterable body, but no
Content-Length header, the library now falls back to use chunked
transfer-encoding.

@item 
A new version of typing.py from @indicateurl{https://github.com/python/typing}: -
Collection (only for 3.6) (bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}) - Add FrozenSet to __all__
(upstream #261) - fix crash in _get_type_vars() (upstream #259) - Remove
the dict constraint in ForwardRef._eval_type (upstream #252)

@item 
bpo-27832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27832}: Make @code{_normalize} parameter to @code{Fraction} constructor
keyword-only, so that @code{Fraction(2, 3, 4)} now raises @code{TypeError}.

@item 
bpo-27539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27539}: Fix unnormalised @code{Fraction.__pow__} result in the case of
negative exponent and negative base.

@item 
bpo-21718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21718}: cursor.description is now available for queries using CTEs.

@item 
bpo-27819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27819}: In distutils sdists, simply produce the "gztar" (gzipped tar
format) distributions on all platforms unless "formats" is supplied.

@item 
bpo-2466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2466}: posixpath.ismount now correctly recognizes mount points which
the user does not have permission to access.

@item 
bpo-9998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9998}: On Linux, ctypes.util.find_library now looks in LD_LIBRARY_PATH
for shared libraries.

@item 
bpo-27573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27573}: exit message for code.interact is now configurable.

@item 
bpo-27930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27930}: Improved behaviour of logging.handlers.QueueListener. Thanks to
Paulo Andrade and Petr Viktorin for the analysis and patch.

@item 
bpo-6766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6766}: Distributed reference counting added to multiprocessing to
support nesting of shared values / proxy objects.

@item 
bpo-21201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21201}: Improves readability of multiprocessing error message.  Thanks
to Wojciech Walczak for patch.

@item 
asyncio: Add set_protocol / get_protocol to Transports.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: asyncio: Set TCP_NODELAY by default.
@end itemize

@node IDLE<52>,C API<71>,ライブラリ<185>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id933}@anchor{1f12}
@subsubsection IDLE



@itemize -

@item 
bpo-15308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15308}: Add 'interrupt execution' (^C) to Shell menu. Patch by Roger
Serwy, updated by Bayard Randel.

@item 
bpo-27922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27922}: Stop IDLE tests from 'flashing' gui widgets on the screen.

@item 
bpo-27891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27891}: Consistently group and sort imports within idlelib modules.

@item 
bpo-17642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17642}: add larger font sizes for classroom projection.

@item 
Add version to title of IDLE help window.

@item 
bpo-25564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25564}: In section on IDLE -- console differences, mention that using
exec means that __builtins__ is defined for each statement.

@item 
bpo-27821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27821}: Fix 3.6.0a3 regression that prevented custom key sets from
being selected when no custom theme was defined.
@end itemize

@node C API<71>,テスト<73>,IDLE<52>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id934}@anchor{1f13}
@subsubsection C API



@itemize -

@item 
bpo-26900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26900}: Excluded underscored names and other private API from limited
API.

@item 
bpo-26027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26027}: Add support for path-like objects in PyUnicode_FSConverter() &
PyUnicode_FSDecoder().
@end itemize

@node テスト<73>,ビルド<84>,C API<71>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id935}@anchor{1f14}
@subsubsection テスト



@itemize -

@item 
bpo-27427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27427}: Additional tests for the math module. Patch by Francisco Couzo.

@item 
bpo-27953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27953}: Skip math and cmath tests that fail on OS X 10.4 due to a poor
libm implementation of tan.

@item 
bpo-26040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26040}: Improve test_math and test_cmath coverage and rigour. Patch by
Jeff Allen.

@item 
bpo-27787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27787}: Call gc.collect() before checking each test for "dangling
threads", since the dangling threads are weak references.
@end itemize

@node ビルド<84>,Tools/Demos<51>,テスト<73>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id936}@anchor{1f15}
@subsubsection ビルド



@itemize -

@item 
bpo-27566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27566}: Fix clean target in freeze makefile (patch by Lisa Roach)

@item 
bpo-27705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27705}: Update message in validate_ucrtbase.py

@item 
bpo-27976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27976}: Deprecate building _ctypes with the bundled copy of libffi on
non-OSX UNIX platforms.

@item 
bpo-27983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27983}: Cause lack of llvm-profdata tool when using clang as required
for PGO linking to be a configure time error rather than make time when
@code{--with-optimizations} is enabled.  Also improve our ability to find the
llvm-profdata tool on MacOS and some Linuxes.

@item 
bpo-21590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21590}: Support for DTrace and SystemTap probes.

@item 
bpo-26307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26307}: The profile-opt build now applies PGO to the built-in modules.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Add the --with-optimizations flag to turn on LTO and PGO build
support when available.

@item 
bpo-27917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27917}: Set platform triplets for Android builds.

@item 
bpo-25825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25825}: Update references to the $(LIBPL) installation path on AIX.
This path was changed in 3.2a4.

@item 
Update OS X installer to use SQLite 3.14.1 and XZ 5.2.2.

@item 
bpo-21122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21122}: Fix LTO builds on OS X.

@item 
bpo-17128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17128}: Build OS X installer with a private copy of OpenSSL. Also
provide a sample Install Certificates command script to install a set of
root certificates from the third-party certifi module.
@end itemize

@node Tools/Demos<51>,Windows<73>,ビルド<84>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id937}@anchor{1f16}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-27952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27952}: Get Tools/scripts/fixcid.py working with Python 3 and the
current "re" module, avoid invalid Python backslash escapes, and fix a bug
parsing escaped C quote signs.
@end itemize

@node Windows<73>,,Tools/Demos<51>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id938}@anchor{1f17}
@subsubsection Windows



@itemize -

@item 
bpo-28065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28065}: Update xz dependency to 5.2.2 and build it from source.

@item 
bpo-25144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25144}: Ensures TargetDir is set before continuing with custom install.

@item 
bpo-1602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1602}: Windows console doesn't input or print Unicode (PEP 528)

@item 
bpo-27781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27781}: Change file system encoding on Windows to UTF-8 (PEP 529)

@item 
bpo-27731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27731}: Opt-out of MAX_PATH on Windows 10

@item 
bpo-6135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6135}: Adds encoding and errors parameters to subprocess.

@item 
bpo-27959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27959}: Adds oem encoding, alias ansi to mbcs, move aliasmbcs to codec
lookup.

@item 
bpo-27982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27982}: The functions of the winsound module now accept keyword
arguments.

@item 
bpo-20366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20366}: Build full text search support into SQLite on Windows.

@item 
bpo-27756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27756}: Adds new icons for Python files and processes on Windows.
Designs by Cherry Wang.

@item 
bpo-27883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27883}: Update sqlite to 3.14.1.0 on Windows.
@end itemize

@node Python 3 6 0 alpha 4,Python 3 6 0 alpha 3,Python 3 6 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-6-0-alpha-4}@anchor{1f18}
@subsection Python 3.6.0 alpha 4


`Release date: 2016-08-15'

@menu
* Core and Builtins: Core and Builtins<183>. 
* ライブラリ: ライブラリ<186>. 
* IDLE: IDLE<53>. 
* テスト: テスト<74>. 
* Windows: Windows<74>. 
* ビルド: ビルド<85>. 

@end menu

@node Core and Builtins<183>,ライブラリ<186>,,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id939}@anchor{1f19}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27704}: Optimized creating bytes and bytearray from byte-like objects
and iterables. Speed up to 3 times for short objects.  Original patch by
Naoki Inada.

@item 
bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}: Large sections of repeated lines in tracebacks are now
abbreviated as "[Previous line repeated @{count@} more times]" by the
builtin traceback rendering. Patch by Emanuel Barry.

@item 
bpo-27574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27574}: Decreased an overhead of parsing keyword arguments in functions
implemented with using Argument Clinic.

@item 
bpo-22557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22557}: Now importing already imported modules is up to 2.5 times
faster.

@item 
bpo-17596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17596}: Include <wincrypt.h> to help with Min GW building.

@item 
bpo-17599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17599}: On Windows, rename the privately defined REPARSE_DATA_BUFFER
structure to avoid conflicting with the definition from Min GW.

@item 
bpo-27507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27507}: Add integer overflow check in bytearray.extend().  Patch by
Xiang Zhang.

@item 
bpo-27581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27581}: Don't rely on wrapping for overflow check in
PySequence_Tuple().  Patch by Xiang Zhang.

@item 
bpo-1621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1621}: Avoid signed integer overflow in list and tuple operations.
Patch by Xiang Zhang.

@item 
bpo-27419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27419}: Standard __import__() no longer look up "__import__" in globals
or builtins for importing submodules or "from import".  Fixed a crash if
raise a warning about unabling to resolve package from __spec__ or
__package__.

@item 
bpo-27083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27083}: Respect the PYTHONCASEOK environment variable under Windows.

@item 
bpo-27514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27514}: Make having too many statically nested blocks a SyntaxError
instead of SystemError.

@item 
bpo-27366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27366}: Implemented 
@geindex Python Enhancement Proposals; PEP 487
PEP 487@footnote{https://peps.python.org/pep-0487/} (Simpler customization of class
creation). Upon subclassing, the __init_subclass__ classmethod is called
on the base class. Descriptors are initialized with __set_name__ after
class creation.
@end itemize

@node ライブラリ<186>,IDLE<53>,Core and Builtins<183>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id940}@anchor{1f1a}
@subsubsection ライブラリ



@itemize -

@item 
bpo-26027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26027}: Add 
@geindex Python Enhancement Proposals; PEP 519
PEP 519@footnote{https://peps.python.org/pep-0519/}/__fspath__() support to the os and os.path
modules. Includes code from Jelle Zijlstra. (See also: bpo-27524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27524})

@item 
bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}: Add Collections to collections.abc. Patch by Ivan Levkivskyi,
docs by Neil Girdhar.

@item 
bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}: Support "anti-registration" of special methods from various
ABCs, like __hash__, __iter__ or __len__.  All these (and several more)
can be set to None in an implementation class and the behavior will be as
if the method is not defined at all. (Previously, this mechanism existed
only for __hash__, to make mutable classes unhashable.)  Code contributed
by Andrew Barnert and Ivan Levkivskyi.

@item 
bpo-16764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16764}: Support keyword arguments to zlib.decompress().  Patch by Xiang
Zhang.

@item 
bpo-27736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27736}: Prevent segfault after interpreter re-initialization due to ref
count problem introduced in code for bpo-27038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27038} in 3.6.0a3. Patch by
Xiang Zhang.

@item 
bpo-25628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25628}: The `verbose' and `rename' parameters for
collections.namedtuple are now keyword-only.

@item 
bpo-12345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12345}: Add mathematical constant tau to math and cmath. See also
@geindex Python Enhancement Proposals; PEP 628
PEP 628@footnote{https://peps.python.org/pep-0628/}.

@item 
bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}: traceback.StackSummary.format now abbreviates large sections of
repeated lines as "[Previous line repeated @{count@} more times]" (this
change then further affects other traceback display operations in the
module). Patch by Emanuel Barry.

@item 
bpo-27664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27664}: Add to concurrent.futures.thread.ThreadPoolExecutor() the
ability to specify a thread name prefix.

@item 
bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}: Add geometric_mean and harmonic_mean to statistics module.

@item 
bpo-27573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27573}: code.interact now prints an message when exiting.

@item 
bpo-6422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6422}: Add autorange method to timeit.Timer objects.

@item 
bpo-27773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27773}: Correct some memory management errors server_hostname in
_ssl.wrap_socket().

@item 
bpo-26750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26750}: unittest.mock.create_autospec() now works properly for
subclasses of property() and other data descriptors.  Removes the never
publicly used, never documented unittest.mock.DescriptorTypes tuple.

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: Undocumented support of general bytes-like objects as path in
compile() and similar functions is now deprecated.

@item 
bpo-26800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26800}: Undocumented support of general bytes-like objects as paths in
os functions is now deprecated.

@item 
bpo-26981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26981}: Add _order_ compatibility shim to enum.Enum for Python 2/3 code
bases.

@item 
bpo-27661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27661}: Added tzinfo keyword argument to datetime.combine.

@item 
In the curses module, raise an error if window.getstr() or window.instr()
is passed a negative value.

@item 
bpo-27783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27783}: Fix possible usage of uninitialized memory in
operator.methodcaller.

@item 
bpo-27774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27774}: Fix possible Py_DECREF on unowned object in _sre.

@item 
bpo-27760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27760}: Fix possible integer overflow in binascii.b2a_qp.

@item 
bpo-27758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27758}: Fix possible integer overflow in the _csv module for large
record lengths.

@item 
bpo-27568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27568}: Prevent HTTPoxy attack (
@geindex Common Vulnerabilities and Exposures; CVE 2016-1000110
CVE 2016-1000110@footnote{https://www.cve.org/CVERecord?id=CVE-2016-1000110}). Ignore the
HTTP_PROXY variable when REQUEST_METHOD environment is set, which
indicates that the script is in CGI mode.

@item 
bpo-7063@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7063}: Remove dead code from the "array" module's slice handling. Patch
by Chuck.

@item 
bpo-27656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27656}: Do not assume sched.h defines any SCHED_* constants.

@item 
bpo-27130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27130}: In the "zlib" module, fix handling of large buffers (typically
4 GiB) when compressing and decompressing.  Previously, inputs were
limited to 4 GiB, and compression and decompression operations did not
properly handle results of 4 GiB.

@item 
bpo-24773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24773}: Implemented 
@geindex Python Enhancement Proposals; PEP 495
PEP 495@footnote{https://peps.python.org/pep-0495/} (Local Time Disambiguation).

@item 
Expose the EPOLLEXCLUSIVE constant (when it is defined) in the select
module.

@item 
bpo-27567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27567}: Expose the EPOLLRDHUP and POLLRDHUP constants in the select
module.

@item 
bpo-1621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1621}: Avoid signed int negation overflow in the "audioop" module.

@item 
bpo-27533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27533}: Release GIL in nt._isdir

@item 
bpo-17711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17711}: Fixed unpickling by the persistent ID with protocol 0. Original
patch by Alexandre Vassalotti.

@item 
bpo-27522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27522}: Avoid an unintentional reference cycle in email.feedparser.

@item 
bpo-27512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27512}: Fix a segfault when os.fspath() called an __fspath__() method
that raised an exception. Patch by Xiang Zhang.
@end itemize

@node IDLE<53>,テスト<74>,ライブラリ<186>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id941}@anchor{1f1b}
@subsubsection IDLE



@itemize -

@item 
bpo-27714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27714}: text_textview and test_autocomplete now pass when re-run in the
same process.  This occurs when test_idle fails when run with the -w
option but without -jn.  Fix warning from test_config.

@item 
bpo-27621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27621}: Put query response validation error messages in the query box
itself instead of in a separate messagebox.  Redo tests to match. Add Mac
OSX refinements. Original patch by Mark Roseman.

@item 
bpo-27620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27620}: Escape key now closes Query box as cancelled.

@item 
bpo-27609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27609}: IDLE: tab after initial whitespace should tab, not
autocomplete. This fixes problem with writing docstrings at least twice
indented.

@item 
bpo-27609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27609}: Explicitly return None when there are also non-None returns. In
a few cases, reverse a condition and eliminate a return.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: IDLE no longer runs buggy code because of its tkinter imports.
Users must include the same imports required to run directly in Python.

@item 
bpo-27173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27173}: Add 'IDLE Modern Unix' to the built-in key sets. Make the
default key set depend on the platform. Add tests for the changes to the
config module.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: add line counter and crc to IDLE configHandler test dump.
@end itemize

@node テスト<74>,Windows<74>,IDLE<53>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id942}@anchor{1f1c}
@subsubsection テスト



@itemize -

@item 
bpo-25805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25805}: Skip a test in test_pkgutil as needed that doesn't work when
@code{__name__ == __main__}. Patch by SilentGhost.

@item 
bpo-27472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27472}: Add test.support.unix_shell as the path to the default shell.

@item 
bpo-27369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27369}: In test_pyexpat, avoid testing an error message detail that
changed in Expat 2.2.0.

@item 
bpo-27594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27594}: Prevent assertion error when running test_ast with coverage
enabled: ensure code object has a valid first line number. Patch suggested
by Ivan Levkivskyi.
@end itemize

@node Windows<74>,ビルド<85>,テスト<74>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id943}@anchor{1f1d}
@subsubsection Windows



@itemize -

@item 
bpo-27647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27647}: Update bundled Tcl/Tk to 8.6.6.

@item 
bpo-27610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27610}: Adds 
@geindex Python Enhancement Proposals; PEP 514
PEP 514@footnote{https://peps.python.org/pep-0514/} metadata to Windows installer

@item 
bpo-27469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27469}: Adds a shell extension to the launcher so that drag and drop
works correctly.

@item 
bpo-27309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27309}: Enables proper Windows styles in python[w].exe manifest.
@end itemize

@node ビルド<85>,,Windows<74>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id944}@anchor{1f1e}
@subsubsection ビルド



@itemize -

@item 
bpo-27713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27713}: Suppress spurious build warnings when updating importlib's
bootstrap files. Patch by Xiang Zhang

@item 
bpo-25825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25825}: Correct the references to Modules/python.exp, which is required
on AIX.  The references were accidentally changed in 3.5.0a1.

@item 
bpo-27453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27453}: CPP invocation in configure must use CPPFLAGS. Patch by Chi
Hsuan Yen.

@item 
bpo-27641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27641}: The configure script now inserts comments into the makefile to
prevent the pgen and _freeze_importlib executables from being
cross-compiled.

@item 
bpo-26662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26662}: Set PYTHON_FOR_GEN in configure as the Python program to be
used for file generation during the build.

@item 
bpo-10910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10910}: Avoid C++ compilation errors on FreeBSD and OS X. Also update
FreedBSD version checks for the original ctype UTF-8 workaround.
@end itemize

@node Python 3 6 0 alpha 3,Python 3 6 0 alpha 2,Python 3 6 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-6-0-alpha-3}@anchor{1f1f}
@subsection Python 3.6.0 alpha 3


`Release date: 2016-07-11'

@menu
* セキュリティ: セキュリティ<54>. 
* Core and Builtins: Core and Builtins<184>. 
* ライブラリ: ライブラリ<187>. 
* IDLE: IDLE<54>. 
* C API: C API<72>. 
* ビルド: ビルド<86>. 
* Tools/Demos: Tools/Demos<52>. 
* ドキュメント: ドキュメント<75>. 
* テスト: テスト<75>. 

@end menu

@node セキュリティ<54>,Core and Builtins<184>,,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id945}@anchor{1f20}
@subsubsection セキュリティ



@itemize -

@item 
bpo-27278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27278}: Fix os.urandom() implementation using getrandom() on Linux.
Truncate size to INT_MAX and loop until we collected enough random bytes,
instead of casting a directly Py_ssize_t to int.

@item 
bpo-22636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22636}: Avoid shell injection problems with ctypes.util.find_library().
@end itemize

@node Core and Builtins<184>,ライブラリ<187>,セキュリティ<54>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id946}@anchor{1f21}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27473}: Fixed possible integer overflow in bytes and bytearray
concatenations. Patch by Xiang Zhang.

@item 
bpo-23034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23034}: The output of a special Python build with defined COUNT_ALLOCS,
SHOW_ALLOC_COUNT or SHOW_TRACK_COUNT macros is now off by  default.  It
can be re-enabled using the "-X showalloccount" option.  It now outputs to
stderr instead of stdout.

@item 
bpo-27443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27443}: __length_hint__() of bytearray iterators no longer return a
negative integer for a resized bytearray.

@item 
bpo-27007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27007}: The fromhex() class methods of bytes and bytearray subclasses
now return an instance of corresponding subclass.
@end itemize

@node ライブラリ<187>,IDLE<54>,Core and Builtins<184>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id947}@anchor{1f22}
@subsubsection ライブラリ



@itemize -

@item 
bpo-26844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26844}: Fix error message for imp.find_module() to refer to 'path'
instead of 'name'. Patch by Lev Maximov.

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL zero-length recv() calls to not block and not raise an
error about unclean EOF.

@item 
bpo-27466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27466}: Change time format returned by http.cookie.time2netscape,
confirming the netscape cookie format and making it consistent with
documentation.

@item 
bpo-21708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21708}: Deprecated dbm.dumb behavior that differs from common dbm
behavior: creating a database in 'r' and 'w' modes and modifying a
database in 'r' mode.

@item 
bpo-26721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26721}: Change the socketserver.StreamRequestHandler.wfile attribute to
implement BufferedIOBase. In particular, the write() method no longer does
partial writes.

@item 
bpo-22115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22115}: Added methods trace_add, trace_remove and trace_info in the
tkinter.Variable class.  They replace old methods trace_variable, trace,
trace_vdelete and trace_vinfo that use obsolete Tcl commands and might not
work in future versions of Tcl.  Fixed old tracing methods:
trace_vdelete() with wrong mode no longer break tracing, trace_vinfo() now
always returns a list of pairs of strings, tracing in the "u" mode now
works.

@item 
bpo-26243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26243}: Only the level argument to zlib.compress() is keyword argument
now.  The first argument is positional-only.

@item 
bpo-27038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27038}: Expose the DirEntry type as os.DirEntry. Code patch by Jelle
Zijlstra.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Update os.fspath()/PyOS_FSPath() to check the return value of
__fspath__() to be either str or bytes.

@item 
bpo-18726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18726}: All optional parameters of the dump(), dumps(), load() and
loads() functions and JSONEncoder and JSONDecoder class constructors in
the json module are now keyword-only.

@item 
bpo-27319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27319}: Methods selection_set(), selection_add(), selection_remove()
and selection_toggle() of ttk.TreeView now allow passing multiple items as
multiple arguments instead of passing them as a tuple.  Deprecated
undocumented ability of calling the selection() method with arguments.

@item 
bpo-27079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27079}: Fixed curses.ascii functions isblank(), iscntrl() and
ispunct().

@item 
bpo-27294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27294}: Numerical state in the repr for Tkinter event objects is now
represented as a combination of known flags.

@item 
bpo-27177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27177}: Match objects in the re module now support index-like objects
as group indices.  Based on patches by Jeroen Demeyer and Xiang Zhang.

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: Some functions (compile() etc) accepted a filename argument
encoded as an iterable of integers. Now only strings and byte-like objects
are accepted.

@item 
bpo-26536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26536}: socket.ioctl now supports SIO_LOOPBACK_FAST_PATH. Patch by
Daniel Stokes.

@item 
bpo-27048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27048}: Prevents distutils failing on Windows when environment
variables contain non-ASCII characters

@item 
bpo-27330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27330}: Fixed possible leaks in the ctypes module.

@item 
bpo-27238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27238}: Got rid of bare excepts in the turtle module.  Original patch
by Jelle Zijlstra.

@item 
bpo-27122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27122}: When an exception is raised within the context being managed by
a contextlib.ExitStack() and one of the exit stack generators catches and
raises it in a chain, do not re-raise the original exception when exiting,
let the new chained one through.  This avoids the 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/} bug described
in issue25782.

@item 
bpo-16864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16864}: sqlite3.Cursor.lastrowid now supports REPLACE statement.
Initial patch by Alex LordThorsen.

@item 
bpo-26386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26386}: Fixed ttk.TreeView selection operations with item id's
containing spaces.

@item 
bpo-8637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8637}: Honor a pager set by the env var MANPAGER (in preference to one
set by the env var PAGER).

@item 
bpo-16182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16182}: Fix various functions in the "readline" module to use the
locale encoding, and fix get_begidx() and get_endidx() to return code
point indexes.

@item 
bpo-27392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27392}: Add loop.connect_accepted_socket(). Patch by Jim Fulton.
@end itemize

@node IDLE<54>,C API<72>,ライブラリ<187>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id948}@anchor{1f23}
@subsubsection IDLE



@itemize -

@item 
bpo-27477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27477}: IDLE search dialogs now use ttk widgets.

@item 
bpo-27173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27173}: Add 'IDLE Modern Unix' to the built-in key sets. Make the
default key set depend on the platform. Add tests for the changes to the
config module.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: make command line "idle-test> python test_help.py" work.
__file__ is relative when python is started in the file's directory.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: add line counter and crc to IDLE configHandler test dump.

@item 
bpo-27380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27380}: IDLE: add query.py with base Query dialog and ttk widgets.
Module had subclasses SectionName, ModuleName, and HelpSource, which are
used to get information from users by configdialog and file =>Load Module.
Each subclass has itw own validity checks.  Using ModuleName allows users
to edit bad module names instead of starting over. Add tests and delete
the two files combined into the new one.

@item 
bpo-27372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27372}: Test_idle no longer changes the locale.

@item 
bpo-27365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27365}: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.

@item 
bpo-27245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27245}: IDLE: Cleanly delete custom themes and key bindings.
Previously, when IDLE was started from a console or by import, a cascade
of warnings was emitted. Patch by Serhiy Storchaka.

@item 
bpo-24137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24137}: Run IDLE, test_idle, and htest with tkinter default root
disabled.  Fix code and tests that fail with this restriction.  Fix htests
to not create a second and redundant root and mainloop.

@item 
bpo-27310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27310}: Fix IDLE.app failure to launch on OS X due to vestigial import.
@end itemize

@node C API<72>,ビルド<86>,IDLE<54>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id949}@anchor{1f24}
@subsubsection C API



@itemize -

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: PyUnicode_FSDecoder() accepted a filename argument encoded as
an iterable of integers. Now only strings and byte-like objects are
accepted.
@end itemize

@node ビルド<86>,Tools/Demos<52>,C API<72>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id950}@anchor{1f25}
@subsubsection ビルド



@itemize -

@item 
bpo-28066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28066}: Fix the logic that searches build directories for generated
include files when building outside the source tree.

@item 
bpo-27442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27442}: Expose the Android API level that python was built against, in
sysconfig.get_config_vars() as 'ANDROID_API_LEVEL'.

@item 
bpo-27434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27434}: The interpreter that runs the cross-build, found in PATH, must
now be of the same feature version (e.g. 3.6) as the source being built.

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update Windows builds to use OpenSSL 1.0.2h.

@item 
bpo-23968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23968}: Rename the platform directory from plat-$(MACHDEP) to
plat-$(PLATFORM_TRIPLET). Rename the config directory (LIBPL) from
config-$(LDVERSION) to config-$(LDVERSION)-$(PLATFORM_TRIPLET). Install
the platform specific _sysconfigdata module into the platform directory
and rename it to include the ABIFLAGS.

@item 
Don't use largefile support for GNU/Hurd.
@end itemize

@node Tools/Demos<52>,ドキュメント<75>,ビルド<86>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id951}@anchor{1f26}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-27332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27332}: Fixed the type of the first argument of module-level functions
generated by Argument Clinic.  Patch by Petr Viktorin.

@item 
bpo-27418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27418}: Fixed Tools/importbench/importbench.py.
@end itemize

@node ドキュメント<75>,テスト<75>,Tools/Demos<52>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id952}@anchor{1f27}
@subsubsection ドキュメント



@itemize -

@item 
bpo-19489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19489}: Moved the search box from the sidebar to the header and footer
of each page. Patch by Ammar Askar.

@item 
bpo-27285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27285}: Update documentation to reflect the deprecation of @code{pyvenv}
and normalize on the term "virtual environment". Patch by Steve Piercy.
@end itemize

@node テスト<75>,,ドキュメント<75>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id953}@anchor{1f28}
@subsubsection テスト



@itemize -

@item 
bpo-27027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27027}: Added test.support.is_android that is True when this is an
Android build.
@end itemize

@node Python 3 6 0 alpha 2,Python 3 6 0 alpha 1,Python 3 6 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-6-0-alpha-2}@anchor{1f29}
@subsection Python 3.6.0 alpha 2


`Release date: 2016-06-13'

@menu
* セキュリティ: セキュリティ<55>. 
* Core and Builtins: Core and Builtins<185>. 
* ライブラリ: ライブラリ<188>. 
* IDLE: IDLE<55>. 
* ドキュメント: ドキュメント<76>. 
* テスト: テスト<76>. 
* Windows: Windows<75>. 
* ビルド: ビルド<87>. 
* C API: C API<73>. 
* Tools/Demos: Tools/Demos<53>. 

@end menu

@node セキュリティ<55>,Core and Builtins<185>,,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id954}@anchor{1f2a}
@subsubsection セキュリティ



@itemize -

@item 
bpo-26556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26556}: Update expat to 2.1.1, fixes 
@geindex Common Vulnerabilities and Exposures; CVE 2015-1283
CVE 2015-1283@footnote{https://www.cve.org/CVERecord?id=CVE-2015-1283}.

@item 
Fix TLS stripping vulnerability in smtplib, 
@geindex Common Vulnerabilities and Exposures; CVE 2016-0772
CVE 2016-0772@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0772}. Reported by
Team Oststrom.

@item 
bpo-26839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26839}: On Linux, @ref{746,,os.urandom()} now calls @code{getrandom()} with
@code{GRND_NONBLOCK} to fall back on reading @code{/dev/urandom} if the urandom
entropy pool is not initialized yet. Patch written by Colm Buckley.
@end itemize

@node Core and Builtins<185>,ライブラリ<188>,セキュリティ<55>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id955}@anchor{1f2b}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27095}: Simplified MAKE_FUNCTION and removed MAKE_CLOSURE opcodes.
Patch by Demur Rumed.

@item 
bpo-27190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27190}: Raise NotSupportedError if sqlite3 is older than 3.3.1. Patch
by Dave Sawyer.

@item 
bpo-27286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27286}: Fixed compiling BUILD_MAP_UNPACK_WITH_CALL opcode.  Calling
function with generalized unpacking (PEP 448) and conflicting keyword
names could cause undefined behavior.

@item 
bpo-27140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27140}: Added BUILD_CONST_KEY_MAP opcode.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add support for os.PathLike objects to open() (part of
@geindex Python Enhancement Proposals; PEP 519
PEP 519@footnote{https://peps.python.org/pep-0519/}).

@item 
bpo-27066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27066}: Fixed SystemError if a custom opener (for open()) returns a
negative number without setting an exception.

@item 
bpo-26983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26983}: float() now always return an instance of exact float. The
deprecation warning is emitted if __float__ returns an instance of a
strict subclass of float.  In a future versions of Python this can be an
error.

@item 
bpo-27097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27097}: Python interpreter is now about 7% faster due to optimized
instruction decoding.  Based on patch by Demur Rumed.

@item 
bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647}: Python interpreter now uses 16-bit wordcode instead of
bytecode. Patch by Demur Rumed.

@item 
bpo-23275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23275}: Allow assigning to an empty target list in round brackets: () =
iterable.

@item 
bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}: Update the __aiter__ protocol: instead of returning an
awaitable that resolves to an asynchronous iterator, the asynchronous
iterator should be returned directly.  Doing the former will trigger a
PendingDeprecationWarning.
@end itemize

@node ライブラリ<188>,IDLE<55>,Core and Builtins<185>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id956}@anchor{1f2c}
@subsubsection ライブラリ



@itemize -

@item 
Comment out socket (SO_REUSEPORT) and posix (O_SHLOCK, O_EXLOCK) constants
exposed on the API which are not implemented on GNU/Hurd. They would not
work at runtime anyway.

@item 
bpo-27025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27025}: Generated names for Tkinter widgets are now more meaningful and
recognizable.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive ElementTree.Element and
functools.partial objects.

@item 
bpo-27294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27294}: Improved repr for Tkinter event objects.

@item 
bpo-20508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20508}: Improve exception message of IPv@{4,6@}Network.__getitem__. Patch
by Gareth Rees.

@item 
bpo-21386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21386}: Implement missing IPv4Address.is_global property.  It was
documented since 07a5610bae9d.  Initial patch by Roger Luethi.

@item 
bpo-27029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27029}: Removed deprecated support of universal newlines mode from
ZipFile.open().

@item 
bpo-27030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27030}: Unknown escapes consisting of @code{'\'} and an ASCII letter in
regular expressions now are errors.  The re.LOCALE flag now can be used
only with bytes patterns.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add os.PathLike support to DirEntry (part of 
@geindex Python Enhancement Proposals; PEP 519
PEP 519@footnote{https://peps.python.org/pep-0519/}).
Initial patch by Jelle Zijlstra.

@item 
bpo-20900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20900}: distutils register command now decodes HTTP responses
correctly.  Initial patch by ingrid.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add os.PathLike support to pathlib, removing its provisional
status (part of PEP 519). Initial patch by Dusty Phillips.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add support for os.PathLike objects to os.fsencode() and
os.fsdecode() (part of 
@geindex Python Enhancement Proposals; PEP 519
PEP 519@footnote{https://peps.python.org/pep-0519/}).

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Introduce os.PathLike and os.fspath() (part of 
@geindex Python Enhancement Proposals; PEP 519
PEP 519@footnote{https://peps.python.org/pep-0519/}).

@item 
A new version of typing.py provides several new classes and features:
@@overload outside stubs, Reversible, DefaultDict, Text, ContextManager,
Type[], NewType(), TYPE_CHECKING, and numerous bug fixes (note that some
of the new features are not yet implemented in mypy or other static
analyzers). Also classes for 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} (Awaitable, AsyncIterable,
AsyncIterator) have been added (in fact they made it into 3.5.1 but were
never mentioned).

@item 
bpo-25738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25738}: Stop http.server.BaseHTTPRequestHandler.send_error() from
sending a message body for 205 Reset Content.  Also, don't send Content
header fields in responses that don't have a body.  Patch by Susumu
Koshiba.

@item 
bpo-21313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21313}: Fix the "platform" module to tolerate when sys.version contains
truncated build information.

@item 
bpo-23883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23883}: Added missing APIs to __all__ to match the documented APIs for
the following modules: cgi, mailbox, mimetypes, plistlib and smtpd.
Patches by Jacek Kołodziej.

@item 
bpo-27164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27164}: In the zlib module, allow decompressing raw Deflate streams
with a predefined zdict.  Based on patch by Xiang Zhang.

@item 
bpo-24291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24291}: Fix wsgiref.simple_server.WSGIRequestHandler to completely
write data to the client.  Previously it could do partial writes and
truncate data.  Also, wsgiref.handler.ServerHandler can now handle stdout
doing partial writes, but this is deprecated.

@item 
bpo-21272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21272}: Use _sysconfigdata.py to initialize distutils.sysconfig.

@item 
bpo-19611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19611}: @ref{82,,inspect} now reports the implicit @code{.0} parameters
generated by the compiler for comprehension and generator expression
scopes as if they were positional-only parameters called @code{implicit0}.
Patch by Jelle Zijlstra.

@item 
bpo-26809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26809}: Add @code{__all__} to @ref{d8,,string}.  Patch by Emanuel Barry.

@item 
bpo-26373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26373}: subprocess.Popen.communicate now correctly ignores
BrokenPipeError when the child process dies before .communicate() is
called in more/all circumstances.

@item 
signal, socket, and ssl module IntEnum constant name lookups now return a
consistent name for values having multiple names.  Ex: signal.Signals(6)
now refers to itself as signal.SIGALRM rather than flipping between that
and signal.SIGIOT based on the interpreter's hash randomization seed.

@item 
bpo-27167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27167}: Clarify the subprocess.CalledProcessError error message text
when the child process died due to a signal.

@item 
bpo-25931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25931}: Don't define socketserver.Forking* names on platforms such as
Windows that do not support os.fork().

@item 
bpo-21776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21776}: distutils.upload now correctly handles HTTPError. Initial patch
by Claudiu Popa.

@item 
bpo-26526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26526}: Replace custom parse tree validation in the parser module with
a simple DFA validator.

@item 
bpo-27114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27114}: Fix SSLContext._load_windows_store_certs fails with
PermissionError

@item 
bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: Avoid creating duplicate filters when using filterwarnings and
simplefilter. Based on patch by Alex Shkop.

@item 
bpo-23026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23026}: winreg.QueryValueEx() now return an integer for REG_QWORD type.

@item 
bpo-26741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26741}: subprocess.Popen destructor now emits a ResourceWarning warning
if the child process is still running.

@item 
bpo-27056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27056}: Optimize pickle.load() and pickle.loads(), up to 10% faster to
deserialize a lot of small objects.

@item 
bpo-21271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21271}: New keyword only parameters in reset_mock call.
@end itemize

@node IDLE<55>,ドキュメント<76>,ライブラリ<188>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id957}@anchor{1f2d}
@subsubsection IDLE



@itemize -

@item 
bpo-5124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5124}: Paste with text selected now replaces the selection on X11. This
matches how paste works on Windows, Mac, most modern Linux apps, and ttk
widgets. Original patch by Serhiy Storchaka.

@item 
bpo-24750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24750}: Switch all scrollbars in IDLE to ttk versions. Where needed,
minimal tests are added to cover changes.

@item 
bpo-24759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24759}: IDLE requires tk 8.5 and availability ttk widgets. Delete now
unneeded tk version tests and code for older versions. Add test for IDLE
syntax colorizer.

@item 
bpo-27239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27239}: idlelib.macosx.isXyzTk functions initialize as needed.

@item 
bpo-27262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27262}: move Aqua unbinding code, which enable context menus, to
macosx.

@item 
bpo-24759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24759}: Make clear in idlelib.idle_test.__init__ that the directory is
a private implementation of test.test_idle and tool for maintainers.

@item 
bpo-27196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27196}: Stop 'ThemeChanged' warnings when running IDLE tests. These
persisted after other warnings were suppressed in #20567. Apply Serhiy
Storchaka's update_idletasks solution to four test files. Record this
additional advice in idle_test/README.txt

@item 
bpo-20567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20567}: Revise idle_test/README.txt with advice about avoiding tk
warning messages from tests.  Apply advice to several IDLE tests.

@item 
bpo-24225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24225}: Update idlelib/README.txt with new file names and event
handlers.

@item 
bpo-27156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27156}: Remove obsolete code not used by IDLE.

@item 
bpo-27117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27117}: Make colorizer htest and turtledemo work with dark themes. Move
code for configuring text widget colors to a new function.

@item 
bpo-24225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24225}: Rename many @code{idlelib/*.py} and @code{idle_test/test_*.py} files.
Edit files to replace old names with new names when the old name referred
to the module rather than the class it contained. See the issue and IDLE
section in What's New in 3.6 for more.

@item 
bpo-26673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26673}: When tk reports font size as 0, change to size 10. Such fonts
on Linux prevented the configuration dialog from opening.

@item 
bpo-21939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21939}: Add test for IDLE's percolator. Original patch by Saimadhav
Heblikar.

@item 
bpo-21676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21676}: Add test for IDLE's replace dialog. Original patch by Saimadhav
Heblikar.

@item 
bpo-18410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18410}: Add test for IDLE's search dialog. Original patch by Westley
Martínez.

@item 
bpo-21703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21703}: Add test for undo delegator.  Patch mostly by Saimadhav
Heblikar .

@item 
bpo-27044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27044}: Add ConfigDialog.remove_var_callbacks to stop memory leaks.

@item 
bpo-23977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23977}: Add more asserts to test_delegator.
@end itemize

@node ドキュメント<76>,テスト<76>,IDLE<55>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id958}@anchor{1f2e}
@subsubsection ドキュメント



@itemize -

@item 
bpo-16484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16484}: Change the default PYTHONDOCS URL to "https:", and fix the
resulting links to use lowercase.  Patch by Sean Rodman, test by Kaushik
Nadikuditi.

@item 
bpo-24136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24136}: Document the new 
@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} unpacking syntax of 3.5.

@item 
bpo-22558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22558}: Add remaining doc links to source code for Python-coded
modules. Patch by Yoni Lavi.
@end itemize

@node テスト<76>,Windows<75>,ドキュメント<76>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id959}@anchor{1f2f}
@subsubsection テスト



@itemize -

@item 
bpo-25285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25285}: regrtest now uses subprocesses when the -j1 command line option
is used: each test file runs in a fresh child process. Before, the -j1
option was ignored.

@item 
bpo-25285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25285}: Tools/buildbot/test.bat script now uses -j1 by default to run
each test file in fresh child process.
@end itemize

@node Windows<75>,ビルド<87>,テスト<76>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id960}@anchor{1f30}
@subsubsection Windows



@itemize -

@item 
bpo-27064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27064}: The py.exe launcher now defaults to Python 3. The Windows
launcher @code{py.exe} no longer prefers an installed Python 2 version over
Python 3 by default when used interactively.

@item 
bpo-17500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17500}: Remove unused and outdated icons. (See also:
@indicateurl{https://github.com/python/pythondotorg/issues/945})
@end itemize

@node ビルド<87>,C API<73>,Windows<75>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id961}@anchor{1f31}
@subsubsection ビルド



@itemize -

@item 
bpo-27229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27229}: Fix the cross-compiling pgen rule for in-tree builds.  Patch by
Xavier de Gaye.

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update OS X 10.5+ 32-bit-only installer to build and link with
OpenSSL 1.0.2h.
@end itemize

@node C API<73>,Tools/Demos<53>,ビルド<87>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id962}@anchor{1f32}
@subsubsection C API



@itemize -

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add the PyOS_FSPath() function (part of 
@geindex Python Enhancement Proposals; PEP 519
PEP 519@footnote{https://peps.python.org/pep-0519/}).

@item 
bpo-26282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26282}: PyArg_ParseTupleAndKeywords() now supports positional-only
parameters.
@end itemize

@node Tools/Demos<53>,,C API<73>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id963}@anchor{1f33}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-26282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26282}: Argument Clinic now supports positional-only and keyword
parameters in the same function.
@end itemize

@node Python 3 6 0 alpha 1,Python 3 5 5 final,Python 3 6 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-6-0-alpha-1}@anchor{1f34}
@subsection Python 3.6.0 alpha 1


`Release date: 2016-05-16'

@menu
* セキュリティ: セキュリティ<56>. 
* Core and Builtins: Core and Builtins<186>. 
* ライブラリ: ライブラリ<189>. 
* IDLE: IDLE<56>. 
* ドキュメント: ドキュメント<77>. 
* テスト: テスト<77>. 
* ビルド: ビルド<88>. 
* Windows: Windows<76>. 
* Tools/Demos: Tools/Demos<54>. 
* C API: C API<74>. 

@end menu

@node セキュリティ<56>,Core and Builtins<186>,,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id964}@anchor{1f35}
@subsubsection セキュリティ



@itemize -

@item 
bpo-26657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26657}: Fix directory traversal vulnerability with http.server on
Windows.  This fixes a regression that was introduced in 3.3.4rc1 and
3.4.0rc1.  Based on patch by Philipp Hagemeister.

@item 
bpo-26313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26313}: ssl.py _load_windows_store_certs fails if windows cert store is
empty. Patch by Baji.

@item 
bpo-25939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25939}: On Windows open the cert store readonly in
ssl.enum_certificates.
@end itemize

@node Core and Builtins<186>,ライブラリ<189>,セキュリティ<56>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id965}@anchor{1f36}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-20041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20041}: Fixed TypeError when frame.f_trace is set to None. Patch by
Xavier de Gaye.

@item 
bpo-26168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26168}: Fixed possible refleaks in failing Py_BuildValue() with the "N"
format unit.

@item 
bpo-26991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26991}: Fix possible refleak when creating a function with annotations.

@item 
bpo-27039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27039}: Fixed bytearray.remove() for values greater than 127.  Based on
patch by Joe Jevnik.

@item 
bpo-23640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23640}: int.from_bytes() no longer bypasses constructors for
subclasses.

@item 
bpo-27005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27005}: Optimized the float.fromhex() class method for exact float. It
is now 2 times faster.

@item 
bpo-18531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18531}: Single var-keyword argument of dict subtype was passed
unscathed to the C-defined function.  Now it is converted to exact dict.

@item 
bpo-26811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26811}: gc.get_objects() no longer contains a broken tuple with NULL
pointer.

@item 
bpo-20120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20120}: Use RawConfigParser for .pypirc parsing, removing support for
interpolation unintentionally added with move to Python 3. Behavior no
longer does any interpolation in .pypirc files, matching behavior in
Python 2.7 and Setuptools 19.0.

@item 
bpo-26249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26249}: Memory functions of the @ref{e5f,,PyMem_Malloc()} domain
(@ref{e63,,PYMEM_DOMAIN_MEM}) now use the @ref{f0b,,pymalloc allocator} rather than system @code{malloc()}. Applications calling
@ref{e5f,,PyMem_Malloc()} without holding the GIL can now crash: use
@code{PYTHONMALLOC=debug} environment variable to validate the usage of
memory allocators in your application.

@item 
bpo-26802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26802}: Optimize function calls only using unpacking like
@code{func(*tuple)} (no other positional argument, no keyword): avoid copying
the tuple. Patch written by Joe Jevnik.

@item 
bpo-26659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26659}: Make the builtin slice type support cycle collection.

@item 
bpo-26718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26718}: super.__init__ no longer leaks memory if called multiple times.
NOTE: A direct call of super.__init__ is not endorsed!

@item 
bpo-27138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27138}: Fix the doc comment for FileFinder.find_spec().

@item 
bpo-27147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27147}: Mention 
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} in the importlib docs.

@item 
bpo-25339@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25339}: PYTHONIOENCODING now has priority over locale in setting the
error handler for stdin and stdout.

@item 
bpo-26494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26494}: Fixed crash on iterating exhausting iterators. Affected classes
are generic sequence iterators, iterators of str, bytes, bytearray, list,
tuple, set, frozenset, dict, OrderedDict, corresponding views and
os.scandir() iterator.

@item 
bpo-26574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26574}: Optimize @code{bytes.replace(b'@w{'}, b'.')} and
@code{bytearray.replace(b'@w{'}, b'.')}. Patch written by Josh Snider.

@item 
bpo-26581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26581}: If coding cookie is specified multiple times on a line in
Python source code file, only the first one is taken to account.

@item 
bpo-19711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19711}: Add tests for reloading namespace packages.

@item 
bpo-21099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21099}: Switch applicable importlib tests to use 
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/} API.

@item 
bpo-26563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26563}: Debug hooks on Python memory allocators now raise a fatal error
if functions of the @ref{e5f,,PyMem_Malloc()} family are called without
holding the GIL.

@item 
bpo-26564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26564}: On error, the debug hooks on Python memory allocators now use
the @ref{105,,tracemalloc} module to get the traceback where a memory block
was allocated.

@item 
bpo-26558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26558}: The debug hooks on Python memory allocator
@ref{e62,,PyObject_Malloc()} now detect when functions are called without
holding the GIL.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: Add 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable to set the
Python memory allocators and/or install debug hooks.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: The @ref{e64,,PyMem_SetupDebugHooks()} function can now also be
used on Python compiled in release mode.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: The 
@geindex PYTHONMALLOCSTATS
@geindex 環境変数; PYTHONMALLOCSTATS
@ref{1f37,,PYTHONMALLOCSTATS} environment variable can now
also be used on Python compiled in release mode. It now has no effect if
set to an empty string.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: In debug mode, debug hooks are now also installed on Python
memory allocators when Python is configured without pymalloc.

@item 
bpo-26464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26464}: Fix str.translate() when string is ASCII and first replacements
removes character, but next replacement uses a non-ASCII character or a
string longer than 1 character. Regression introduced in Python 3.5.0.

@item 
bpo-22836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22836}: Ensure exception reports from PyErr_Display() and
PyErr_WriteUnraisable() are sensible even when formatting them produces
secondary errors.  This affects the reports produced by
sys.__excepthook__() and when __del__() raises an exception.

@item 
bpo-26302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26302}: Correct behavior to reject comma as a legal character for
cookie names.

@item 
bpo-26136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26136}: Upgrade the warning when a generator raises StopIteration from
PendingDeprecationWarning to DeprecationWarning.  Patch by Anish Shah.

@item 
bpo-26204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26204}: The compiler now ignores all constant statements: bytes, str,
int, float, complex, name constants (None, False, True), Ellipsis and
ast.Constant; not only str and int. For example, @code{1.0} is now ignored in
@code{def f(): 1.0}.

@item 
bpo-4806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4806}: Avoid masking the original TypeError exception when using star
(@code{*}) unpacking in function calls.  Based on patch by Hagen Fürstenau
and Daniel Urban.

@item 
bpo-26146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26146}: Add a new kind of AST node: @code{ast.Constant}. It can be used by
external AST optimizers, but the compiler does not emit directly such
node.

@item 
bpo-23601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23601}: Sped-up allocation of dict key objects by using Python's small
object allocator.  (Contributed by Julian Taylor.)

@item 
bpo-18018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18018}: Import raises ImportError instead of SystemError if a relative
import is attempted without a known parent package.

@item 
bpo-25843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25843}: When compiling code, don't merge constants if they are equal
but have a different types. For example, @code{f1, f2 = lambda: 1, lambda:
1.0} is now correctly compiled to two different functions: @code{f1()}
returns @code{1} (@code{int}) and @code{f2()} returns @code{1.0} (@code{float}), even if
@code{1} and @code{1.0} are equal.

@item 
bpo-26107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26107}: The format of the @code{co_lnotab} attribute of code objects
changes to support negative line number delta.

@item 
bpo-26154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26154}: Add a new private _PyThreadState_UncheckedGet() function to get
the current Python thread state, but don't issue a fatal error if it is
NULL. This new function must be used instead of accessing directly the
_PyThreadState_Current variable.  The variable is no more exposed since
Python 3.5.1 to hide the exact implementation of atomic C types, to avoid
compiler issues.

@item 
bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791}: If __package__ != __spec__.parent or if neither __package__ or
__spec__ are defined then ImportWarning is raised.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: [UPDATE] Comment out the one of the pickleability tests in
_PyObject_GetState() due to regressions observed in Cython-based projects.

@item 
bpo-25961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25961}: Disallowed null characters in the type name.

@item 
bpo-25973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25973}: Fix segfault when an invalid nonlocal statement binds a name
starting with two underscores.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Instances of extension types with a state that aren't
subclasses of list or dict and haven't implemented any pickle-related
methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, or
__getstate__), can no longer be pickled.  Including memoryview.

@item 
bpo-20440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20440}: Massive replacing unsafe attribute setting code with special
macro Py_SETREF.

@item 
bpo-25766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25766}: Special method __bytes__() now works in str subclasses.

@item 
bpo-25421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25421}: __sizeof__ methods of builtin types now use dynamic basic size.
This allows sys.getsize() to work correctly with their subclasses with
__slots__ defined.

@item 
bpo-25709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25709}: Fixed problem with in-place string concatenation and utf-8
cache.

@item 
bpo-5319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5319}: New Py_FinalizeEx() API allowing Python to set an exit status of
120 on failure to flush buffered streams.

@item 
bpo-25485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25485}: telnetlib.Telnet is now a context manager.

@item 
bpo-24097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24097}: Fixed crash in object.__reduce__() if slot name is freed inside
__getattr__.

@item 
bpo-24731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24731}: Fixed crash on converting objects with special methods
__bytes__, __trunc__, and __float__ returning instances of subclasses of
bytes, int, and float to subclasses of bytes, int, and float
correspondingly.

@item 
bpo-25630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25630}: Fix a possible segfault during argument parsing in functions
that accept filesystem paths.

@item 
bpo-23564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23564}: Fixed a partially broken sanity check in the _posixsubprocess
internals regarding how fds_to_pass were passed to the child.  The bug had
no actual impact as subprocess.py already avoided it.

@item 
bpo-25388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25388}: Fixed tokenizer crash when processing undecodable source code
with a null byte.

@item 
bpo-25462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25462}: The hash of the key now is calculated only once in most
operations in C implementation of OrderedDict.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Default implementation of __reduce__ and __reduce_ex__ now
rejects builtin types with not defined __new__.

@item 
bpo-24802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24802}: Avoid buffer overreads when int(), float(), compile(), exec()
and eval() are passed bytes-like objects.  These objects are not
necessarily terminated by a null byte, but the functions assumed they
were.

@item 
bpo-25555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25555}: Fix parser and AST: fill lineno and col_offset of "arg" node
when compiling AST from Python objects.

@item 
bpo-24726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24726}: Fixed a crash and leaking NULL in repr() of OrderedDict that
was mutated by direct calls of dict methods.

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Iterating OrderedDict with keys with unstable hash now raises
KeyError in C implementations as well as in Python implementation.

@item 
bpo-25395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25395}: Fixed crash when highly nested OrderedDict structures were
garbage collected.

@item 
bpo-25401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25401}: Optimize bytes.fromhex() and bytearray.fromhex(): they are now
between 2x and 3.5x faster.

@item 
bpo-25399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25399}: Optimize bytearray % args using the new private _PyBytesWriter
API. Formatting is now between 2.5 and 5 times faster.

@item 
bpo-25274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25274}: sys.setrecursionlimit() now raises a RecursionError if the new
recursion limit is too low depending at the current recursion depth.
Modify also the "lower-water mark" formula to make it monotonic. This mark
is used to decide when the overflowed flag of the thread state is reset.

@item 
bpo-24402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24402}: Fix input() to prompt to the redirected stdout when
sys.stdout.fileno() fails.

@item 
bpo-25349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25349}: Optimize bytes % args using the new private _PyBytesWriter API.
Formatting is now up to 2 times faster.

@item 
bpo-24806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24806}: Prevent builtin types that are not allowed to be subclassed
from being subclassed through multiple inheritance.

@item 
bpo-25301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25301}: The UTF-8 decoder is now up to 15 times as fast for error
handlers: @code{ignore}, @code{replace} and @code{surrogateescape}.

@item 
bpo-24848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24848}: Fixed a number of bugs in UTF-7 decoding of misformed data.

@item 
bpo-25267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25267}: The UTF-8 encoder is now up to 75 times as fast for error
handlers: @code{ignore}, @code{replace}, @code{surrogateescape}, @code{surrogatepass}.
Patch co-written with Serhiy Storchaka.

@item 
bpo-25280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25280}: Import trace messages emitted in verbose (-v) mode are no
longer formatted twice.

@item 
bpo-25227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25227}: Optimize ASCII and latin1 encoders with the @code{surrogateescape}
error handler: the encoders are now up to 3 times as fast. Initial patch
written by Serhiy Storchaka.

@item 
bpo-25003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25003}: On Solaris 11.3 or newer, os.urandom() now uses the getrandom()
function instead of the getentropy() function. The getentropy() function
is blocking to generate very good quality entropy, os.urandom() doesn't
need such high-quality entropy.

@item 
bpo-9232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9232}: Modify Python's grammar to allow trailing commas in the argument
list of a function declaration.  For example, "def f(*, a = 3,): pass" is
now legal. Patch from Mark Dickinson.

@item 
bpo-24965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24965}: Implement 
@geindex Python Enhancement Proposals; PEP 498
PEP 498@footnote{https://peps.python.org/pep-0498/} "Literal String Interpolation". This
allows you to embed expressions inside f-strings, which are converted to
normal strings at run time. Given x=3, then f'value=@{x@}' == 'value=3'.
Patch by Eric V. Smith.

@item 
bpo-26478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26478}: Fix semantic bugs when using binary operators with dictionary
views and tuples.

@item 
bpo-26171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26171}: Fix possible integer overflow and heap corruption in
zipimporter.get_data().

@item 
bpo-25660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25660}: Fix TAB key behaviour in REPL with readline.

@item 
bpo-26288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26288}: Optimize PyLong_AsDouble.

@item 
bpo-26289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26289}: Optimize floor and modulo division for single-digit longs.
Microbenchmarks show 2-2.5x improvement.  Built-in 'divmod' function is
now also ~10% faster. (See also: bpo-26315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26315})

@item 
bpo-25887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25887}: Raise a RuntimeError when a coroutine object is awaited more
than once.
@end itemize

@node ライブラリ<189>,IDLE<56>,Core and Builtins<186>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id966}@anchor{1f38}
@subsubsection ライブラリ



@itemize -

@item 
bpo-27057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27057}: Fix os.set_inheritable() on Android, ioctl() is blocked by
SELinux and fails with EACCESS. The function now falls back to fcntl().
Patch written by Michał Bednarski.

@item 
bpo-27014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27014}: Fix infinite recursion using typing.py.  Thanks to Kalle Tuure!

@item 
bpo-27031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27031}: Removed dummy methods in Tkinter widget classes: tk_menuBar()
and tk_bindForTraversal().

@item 
bpo-14132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14132}: Fix urllib.request redirect handling when the target only has a
query string.  Original fix by Ján Janech.

@item 
bpo-17214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17214}: The "urllib.request" module now percent-encodes non-ASCII bytes
found in redirect target URLs.  Some servers send Location header fields
with non-ASCII bytes, but "http.client" requires the request target to be
ASCII-encodable, otherwise a UnicodeEncodeError is raised.  Based on patch
by Christian Heimes.

@item 
bpo-27033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27033}: The default value of the decode_data parameter for
smtpd.SMTPChannel and smtpd.SMTPServer constructors is changed to False.

@item 
bpo-27034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27034}: Removed deprecated class asynchat.fifo.

@item 
bpo-26870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26870}: Added readline.set_auto_history(), which can stop entries being
automatically added to the history list.  Based on patch by Tyler
Crompton.

@item 
bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}: zipfile.ZipFile.open() can now be used to write data into a ZIP
file, as well as for extracting data.  Patch by Thomas Kluyver.

@item 
bpo-26892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26892}: Honor debuglevel flag in urllib.request.HTTPHandler. Patch
contributed by Chi Hsuan Yen.

@item 
bpo-22274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22274}: In the subprocess module, allow stderr to be redirected to
stdout even when stdout is not redirected.  Patch by Akira Li.

@item 
bpo-26807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26807}: mock_open 'files' no longer error on readline at end of file.
Patch from Yolanda Robla.

@item 
bpo-25745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25745}: Fixed leaking a userptr in curses panel destructor.

@item 
bpo-26977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26977}: Removed unnecessary, and ignored, call to sum of squares helper
in statistics.pvariance.

@item 
bpo-26002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26002}: Use bisect in statistics.median instead of a linear search.
Patch by Upendra Kuma.

@item 
bpo-25974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25974}: Make use of new Decimal.as_integer_ratio() method in statistics
module. Patch by Stefan Krah.

@item 
bpo-26996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26996}: Add secrets module as described in 
@geindex Python Enhancement Proposals; PEP 506
PEP 506@footnote{https://peps.python.org/pep-0506/}.

@item 
bpo-26881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26881}: The modulefinder module now supports extended opcode arguments.

@item 
bpo-23815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23815}: Fixed crashes related to directly created instances of types in
_tkinter and curses.panel modules.

@item 
bpo-17765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17765}: weakref.ref() no longer silently ignores keyword arguments.
Patch by Georg Brandl.

@item 
bpo-26873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26873}: xmlrpc now raises ResponseError on unsupported type tags
instead of silently return incorrect result.

@item 
bpo-26915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26915}: The __contains__ methods in the collections ABCs now check for
identity before checking equality.  This better matches the behavior of
the concrete classes, allows sensible handling of NaNs, and makes it
easier to reason about container invariants.

@item 
bpo-26711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26711}: Fixed the comparison of plistlib.Data with other types.

@item 
bpo-24114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24114}: Fix an uninitialized variable in @code{ctypes.util}. The bug only
occurs on SunOS when the ctypes implementation searches for the @code{crle}
program. Patch by Xiang Zhang.  Tested on SunOS by Kees Bos.

@item 
bpo-26864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26864}: In urllib.request, change the proxy bypass host checking
against no_proxy to be case-insensitive, and to not match unrelated host
names that happen to have a bypassed hostname as a suffix.  Patch by Xiang
Zhang.

@item 
bpo-24902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24902}: Print server URL on http.server startup.  Initial patch by
Felix Kaiser.

@item 
bpo-25788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25788}: fileinput.hook_encoded() now supports an "errors" argument for
passing to open.  Original patch by Joseph Hackman.

@item 
bpo-26634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26634}: recursive_repr() now sets __qualname__ of wrapper.  Patch by
Xiang Zhang.

@item 
bpo-26804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26804}: urllib.request will prefer lower_case proxy environment
variables over UPPER_CASE or Mixed_Case ones. Patch contributed by
Hans-Peter Jansen.

@item 
bpo-26837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26837}: assertSequenceEqual() now correctly outputs non-stringified
differing items (like bytes in the -b mode).  This affects
assertListEqual() and assertTupleEqual().

@item 
bpo-26041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26041}: Remove "will be removed in Python 3.7" from deprecation
messages of platform.dist() and platform.linux_distribution(). Patch by
Kumaripaba Miyurusara Athukorala.

@item 
bpo-26822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26822}: itemgetter, attrgetter and methodcaller objects no longer
silently ignore keyword arguments.

@item 
bpo-26733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26733}: Disassembling a class now disassembles class and static
methods. Patch by Xiang Zhang.

@item 
bpo-26801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26801}: Fix error handling in @ref{131b,,shutil.get_terminal_size()}, catch
@ref{5f0,,AttributeError} instead of @ref{452,,NameError}. Patch written by
Emanuel Barry.

@item 
bpo-24838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24838}: tarfile's ustar and gnu formats now correctly calculate name
and link field limits for multibyte character encodings like utf-8.

@item 
bpo-26717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26717}: Stop encoding Latin-1-ized WSGI paths with UTF-8.  Patch by
Anthony Sottile.

@item 
bpo-26782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26782}: Add STARTUPINFO to subprocess.__all__ on Windows.

@item 
bpo-26404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26404}: Add context manager to socketserver.  Patch by Aviv Palivoda.

@item 
bpo-26735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26735}: Fix @ref{746,,os.urandom()} on Solaris 11.3 and newer when reading
more than 1,024 bytes: call @code{getrandom()} multiple times with a limit of
1024 bytes per call.

@item 
bpo-26585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26585}: Eliminate http.server._quote_html() and use
html.escape(quote=False).  Patch by Xiang Zhang.

@item 
bpo-26685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26685}: Raise OSError if closing a socket fails.

@item 
bpo-16329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16329}: Add .webm to mimetypes.types_map.  Patch by Giampaolo Rodola'.

@item 
bpo-13952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13952}: Add .csv to mimetypes.types_map.  Patch by Geoff Wilson.

@item 
bpo-26587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26587}: the site module now allows .pth files to specify files to be
added to sys.path (e.g. zip files).

@item 
bpo-25609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25609}: Introduce contextlib.AbstractContextManager and
typing.ContextManager.

@item 
bpo-26709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26709}: Fixed Y2038 problem in loading binary PLists.

@item 
bpo-23735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23735}: Handle terminal resizing with Readline 6.3+ by installing our
own SIGWINCH handler.  Patch by Eric Price.

@item 
bpo-25951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25951}: Change SSLSocket.sendall() to return None, as explicitly
documented for plain socket objects.  Patch by Aviv Palivoda.

@item 
bpo-26586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26586}: In http.server, respond with "413 Request header fields too
large" if there are too many header fields to parse, rather than killing
the connection and raising an unhandled exception.  Patch by Xiang Zhang.

@item 
bpo-26676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26676}: Added missing XMLPullParser to ElementTree.__all__.

@item 
bpo-22854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22854}: Change BufferedReader.writable() and BufferedWriter.readable()
to always return False.

@item 
bpo-26492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26492}: Exhausted iterator of array.array now conforms with the
behavior of iterators of other mutable sequences: it lefts exhausted even
if iterated array is extended.

@item 
bpo-26641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26641}: doctest.DocFileTest and doctest.testfile() now support packages
(module split into multiple directories) for the package parameter.

@item 
bpo-25195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25195}: Fix a regression in mock.MagicMock. _Call is a subclass of
tuple (changeset 3603bae63c13 only works for classes) so we need to
implement __ne__ ourselves.  Patch by Andrew Plummer.

@item 
bpo-26644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26644}: Raise ValueError rather than SystemError when a negative length
is passed to SSLSocket.recv() or read().

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL recv(0) and read(0) methods to return zero bytes
instead of up to 1024.

@item 
bpo-26616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26616}: Fixed a bug in datetime.astimezone() method.

@item 
bpo-26637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26637}: The @ref{7b,,importlib} module now emits an @ref{65b,,ImportError}
rather than a @ref{198,,TypeError} if @ref{ad1,,__import__()} is tried during the
Python shutdown process but @ref{3e4,,sys.path} is already cleared (set to
@code{None}).

@item 
bpo-21925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21925}: @ref{1df8,,warnings.formatwarning()} now catches exceptions when
calling @ref{240,,linecache.getline()} and
@ref{1f39,,tracemalloc.get_object_traceback()} to be able to log
@ref{54c,,ResourceWarning} emitted late during the Python shutdown process.

@item 
bpo-23848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23848}: On Windows, faulthandler.enable() now also installs an
exception handler to dump the traceback of all Python threads on any
Windows exception, not only on UNIX signals (SIGSEGV, SIGFPE, SIGABRT).

@item 
bpo-26530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26530}: Add C functions @code{_PyTraceMalloc_Track()} and
@code{_PyTraceMalloc_Untrack()} to track memory blocks using the
@ref{105,,tracemalloc} module. Add @code{_PyTraceMalloc_GetTraceback()} to
get the traceback of an object.

@item 
bpo-26588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26588}: The _tracemalloc now supports tracing memory allocations of
multiple address spaces (domains).

@item 
bpo-24266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24266}: Ctrl+C during Readline history search now cancels the search
mode when compiled with Readline 7.

@item 
bpo-26590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26590}: Implement a safe finalizer for the _socket.socket type. It now
releases the GIL to close the socket.

@item 
bpo-18787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18787}: spwd.getspnam() now raises a PermissionError if the user
doesn't have privileges.

@item 
bpo-26560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26560}: Avoid potential ValueError in BaseHandler.start_response.
Initial patch by Peter Inglesby.

@item 
bpo-26567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26567}: Add a new function @ref{f13,,PyErr_ResourceWarning()} function to
pass the destroyed object. Add a `source' attribute to
@code{warnings.WarningMessage}. Add warnings._showwarnmsg() which uses
tracemalloc to get the traceback where source object was allocated.

@item 
bpo-26569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26569}: Fix @ref{a2c,,pyclbr.readmodule()} and @ref{a2d,,pyclbr.readmodule_ex()}
to support importing packages.

@item 
bpo-26499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26499}: Account for remaining Content-Length in HTTPResponse.readline()
and read1(). Based on patch by Silent Ghost. Also document that
HTTPResponse now supports these methods.

@item 
bpo-25320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25320}: Handle sockets in directories unittest discovery is scanning.
Patch from Victor van den Elzen.

@item 
bpo-16181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16181}: cookiejar.http2time() now returns None if year is higher than
datetime.MAXYEAR.

@item 
bpo-26513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26513}: Fixes platform module detection of Windows Server

@item 
bpo-23718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23718}: Fixed parsing time in week 0 before Jan 1.  Original patch by
Tamás Bence Gedai.

@item 
bpo-26323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26323}: Add Mock.assert_called() and Mock.assert_called_once() methods
to unittest.mock. Patch written by Amit Saha.

@item 
bpo-20589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20589}: Invoking Path.owner() and Path.group() on Windows now raise
NotImplementedError instead of ImportError.

@item 
bpo-26177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26177}: Fixed the keys() method for Canvas and Scrollbar widgets.

@item 
bpo-15068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15068}: Got rid of excessive buffering in fileinput. The bufsize
parameter is now deprecated and ignored.

@item 
bpo-19475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19475}: Added an optional argument timespec to the datetime isoformat()
method to choose the precision of the time component.

@item 
bpo-2202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2202}: Fix UnboundLocalError in
AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu
Dupuy.

@item 
bpo-26167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26167}: Minimized overhead in copy.copy() and copy.deepcopy().
Optimized copying and deepcopying bytearrays, NotImplemented, slices,
short lists, tuples, dicts, sets.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed pickling and copying the accumulate() iterator with total
is None.

@item 
bpo-26475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26475}: Fixed debugging output for regular expressions with the (?x)
flag.

@item 
bpo-26482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26482}: Allowed pickling recursive dequeues.

@item 
bpo-26335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26335}: Make mmap.write() return the number of bytes written like other
write methods.  Patch by Jakub Stasiak.

@item 
bpo-26457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26457}: Fixed the subnets() methods in IP network classes for the case
when resulting prefix length is equal to maximal prefix length. Based on
patch by Xiang Zhang.

@item 
bpo-26385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26385}: Remove the file if the internal open() call in
NamedTemporaryFile() fails. Patch by Silent Ghost.

@item 
bpo-26402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26402}: Fix XML-RPC client to retry when the server shuts down a
persistent connection.  This was a regression related to the new
http.client.RemoteDisconnected exception in 3.5.0a4.

@item 
bpo-25913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25913}: Leading @code{<~} is optional now in base64.a85decode() with
adobe=True.  Patch by Swati Jaiswal.

@item 
bpo-26186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26186}: Remove an invalid type check in importlib.util.LazyLoader.

@item 
bpo-26367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26367}: importlib.__import__() raises ImportError like
builtins.__import__() when @code{level} is specified but without an
accompanying package specified.

@item 
bpo-26309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26309}: In the "socketserver" module, shut down the request (closing
the connected socket) when verify_request() returns false.  Patch by Aviv
Palivoda.

@item 
bpo-23430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23430}: Change the socketserver module to only catch exceptions raised
from a request handler that are derived from Exception (instead of
BaseException). Therefore SystemExit and KeyboardInterrupt no longer
trigger the handle_error() method, and will now to stop a single-threaded
server.

@item 
bpo-25995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25995}: os.walk() no longer uses FDs proportional to the tree depth.

@item 
bpo-25994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25994}: Added the close() method and the support of the context manager
protocol for the os.scandir() iterator.

@item 
bpo-23992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23992}: multiprocessing: make MapResult not fail-fast upon exception.

@item 
bpo-26243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26243}: Support keyword arguments to zlib.compress().  Patch by Aviv
Palivoda.

@item 
bpo-26117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26117}: The os.scandir() iterator now closes file descriptor not only
when the iteration is finished, but when it was failed with error.

@item 
bpo-25949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25949}: __dict__ for an OrderedDict instance is now created only when
needed.

@item 
bpo-25911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25911}: Restored support of bytes paths in os.walk() on Windows.

@item 
bpo-26045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26045}: Add UTF-8 suggestion to error message when posting a
non-Latin-1 string with http.client.

@item 
bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}: Added zipfile.ZipInfo.from_file() and zipinfo.ZipInfo.is_dir().
Patch by Thomas Kluyver.

@item 
bpo-12923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12923}: Reset FancyURLopener's redirect counter even if there is an
exception. Based on patches by Brian Brazil and Daniel Rocco.

@item 
bpo-25945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25945}: Fixed a crash when unpickle the functools.partial object with
wrong state. Fixed a leak in failed functools.partial constructor. "args"
and "keywords" attributes of functools.partial have now always types tuple
and dict correspondingly.

@item 
bpo-26202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26202}: copy.deepcopy() now correctly copies range() objects with
non-atomic attributes.

@item 
bpo-23076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23076}: Path.glob() now raises a ValueError if it's called with an
invalid pattern. Patch by Thomas Nyberg.

@item 
bpo-19883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19883}: Fixed possible integer overflows in zipimport.

@item 
bpo-26227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26227}: On Windows, getnameinfo(), gethostbyaddr() and
gethostbyname_ex() functions of the socket module now decode the hostname
from the ANSI code page rather than UTF-8.

@item 
bpo-26099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26099}: The site module now writes an error into stderr if
sitecustomize module can be imported but executing the module raise an
ImportError. Same change for usercustomize.

@item 
bpo-26147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26147}: xmlrpc now works with strings not encodable with used non-UTF-8
encoding.

@item 
bpo-25935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25935}: Garbage collector now breaks reference loops with OrderedDict.

@item 
bpo-16620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16620}: Fixed AttributeError in msilib.Directory.glob().

@item 
bpo-26013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26013}: Added compatibility with broken protocol 2 pickles created in
old Python 3 versions (3.4.3 and lower).

@item 
bpo-26129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26129}: Deprecated accepting non-integers in grp.getgrgid().

@item 
bpo-25850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25850}: Use cross-compilation by default for 64-bit Windows.

@item 
bpo-25822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25822}: Add docstrings to the fields of urllib.parse results. Patch
contributed by Swati Jaiswal.

@item 
bpo-22642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22642}: Convert trace module option parsing mechanism to argparse.
Patch contributed by SilentGhost.

@item 
bpo-24705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24705}: Fix sysconfig._parse_makefile not expanding $@{@} vars appearing
before $() vars.

@item 
bpo-26069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26069}: Remove the deprecated apis in the trace module.

@item 
bpo-22138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22138}: Fix mock.patch behavior when patching descriptors. Restore
original values after patching. Patch contributed by Sean McCully.

@item 
bpo-25672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25672}: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode
option if it is safe to do so.

@item 
bpo-26012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26012}: Don't traverse into symlinks for @code{**} pattern in
pathlib.Path.[r]glob().

@item 
bpo-24120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24120}: Ignore PermissionError when traversing a tree with
pathlib.Path.[r]glob(). Patch by Ulrich Petri.

@item 
bpo-21815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21815}: Accept ] characters in the data portion of imap responses, in
order to handle the flags with square brackets accepted and produced by
servers such as gmail.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: fileinput now uses sys.stdin as-is if it does not have a buffer
attribute (restores backward compatibility).

@item 
bpo-25971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25971}: Optimized creating Fractions from floats by 2 times and from
Decimals by 3 times.

@item 
bpo-25802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25802}: Document as deprecated the remaining implementations of
importlib.abc.Loader.load_module().

@item 
bpo-25928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25928}: Add Decimal.as_integer_ratio().

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: Copying the lru_cache() wrapper object now always works,
independently from the type of the wrapped object (by returning the
original object unchanged).

@item 
bpo-25768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25768}: Have the functions in compileall return booleans instead of
ints and add proper documentation and tests for the return values.

@item 
bpo-24103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24103}: Fixed possible use after free in ElementTree.XMLPullParser.

@item 
bpo-25860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25860}: os.fwalk() no longer skips remaining directories when error
occurs. Original patch by Samson Lee.

@item 
bpo-25914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25914}: Fixed and simplified OrderedDict.__sizeof__.

@item 
bpo-25869@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25869}: Optimized deepcopying ElementTree; it is now 20 times faster.

@item 
bpo-25873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25873}: Optimized iterating ElementTree.  Iterating elements
Element.iter() is now 40% faster, iterating text Element.itertext() is now
up to 2.5 times faster.

@item 
bpo-25902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25902}: Fixed various refcount issues in ElementTree iteration.

@item 
bpo-22227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22227}: The TarFile iterator is reimplemented using generator. This
implementation is simpler that using class.

@item 
bpo-25638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25638}: Optimized ElementTree.iterparse(); it is now 2x faster.
Optimized ElementTree parsing; it is now 10% faster.

@item 
bpo-25761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25761}: Improved detecting errors in broken pickle data.

@item 
bpo-25717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25717}: Restore the previous behaviour of tolerating most fstat()
errors when opening files.  This was a regression in 3.5a1, and stopped
anonymous temporary files from working in special cases.

@item 
bpo-24903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24903}: Fix regression in number of arguments compileall accepts when
'-d' is specified.  The check on the number of arguments has been dropped
completely as it never worked correctly anyway.

@item 
bpo-25764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25764}: In the subprocess module, preserve any exception caused by
fork() failure when preexec_fn is used.

@item 
bpo-25771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25771}: Tweak the exception message for importlib.util.resolve_name()
when 'package' isn't specified but necessary.

@item 
bpo-6478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6478}: _strptime's regexp cache now is reset after changing timezone
with time.tzset().

@item 
bpo-14285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14285}: When executing a package with the "python -m package" option,
and package initialization fails, a proper traceback is now reported.  The
"runpy" module now lets exceptions from package initialization pass back
to the caller, rather than raising ImportError.

@item 
bpo-19771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19771}: Also in runpy and the "-m" option, omit the irrelevant message
". . . is a package and cannot be directly executed" if the package could
not even be initialized (e.g. due to a bad @code{*.pyc} file).

@item 
bpo-25177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25177}: Fixed problem with the mean of very small and very large
numbers. As a side effect, statistics.mean and statistics.variance should
be significantly faster.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed copying object with state with boolean value is false.

@item 
bpo-10131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10131}: Fixed deep copying of minidom documents.  Based on patch by
Marian Ganisin.

@item 
bpo-7990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7990}: dir() on ElementTree.Element now lists properties: "tag",
"text", "tail" and "attrib".  Original patch by Santoso Wijaya.

@item 
bpo-25725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25725}: Fixed a reference leak in pickle.loads() when unpickling
invalid data including tuple instructions.

@item 
bpo-25663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25663}: In the Readline completer, avoid listing duplicate global
names, and search the global namespace before searching builtins.

@item 
bpo-25688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25688}: Fixed file leak in ElementTree.iterparse() raising an error.

@item 
bpo-23914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23914}: Fixed SystemError raised by unpickler on broken pickle data.

@item 
bpo-25691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25691}: Fixed crash on deleting ElementTree.Element attributes.

@item 
bpo-25624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25624}: ZipFile now always writes a ZIP_STORED header for directory
entries.  Patch by Dingyuan Wang.

@item 
bpo-25626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25626}: Change three zlib functions to accept sizes that fit in
Py_ssize_t, but internally cap those sizes to UINT_MAX.  This resolves a
regression in 3.5 where GzipFile.read() failed to read chunks larger than
2 or 4 GiB.  The change affects the zlib.Decompress.decompress()
max_length parameter, the zlib.decompress() bufsize parameter, and the
zlib.Decompress.flush() length parameter.

@item 
bpo-25583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25583}: Avoid incorrect errors raised by os.makedirs(exist_ok=True)
when the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-25593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25593}: Change semantics of EventLoop.stop() in asyncio.

@item 
bpo-6973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6973}: When we know a subprocess.Popen process has died, do not allow
the send_signal(), terminate(), or kill() methods to do anything as they
could potentially signal a different process.

@item 
bpo-23883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23883}: Added missing APIs to __all__ to match the documented APIs for
the following modules: calendar, csv, enum, fileinput, ftplib, logging,
optparse, tarfile, threading and wave.  Also added a
test.support.check__all__() helper. Patches by Jacek Kołodziej, Mauro S.
M. Rodrigues and Joel Taddei.

@item 
bpo-25590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25590}: In the Readline completer, only call getattr() once per
attribute.  Also complete names of attributes such as properties and slots
which are listed by dir() but not yet created on an instance.

@item 
bpo-25498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25498}: Fix a crash when garbage-collecting ctypes objects created by
wrapping a memoryview.  This was a regression made in 3.5a1.  Based on
patch by Eryksun.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Added "escape" to the __all__ list in the glob module.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Fixed recursive glob() with patterns starting with @code{**}.

@item 
bpo-25446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25446}: Fix regression in smtplib's AUTH LOGIN support.

@item 
bpo-18010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18010}: Fix the pydoc web server's module search function to handle
exceptions from importing packages.

@item 
bpo-25554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25554}: Got rid of circular references in regular expression parsing.

@item 
bpo-18973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18973}: Command-line interface of the calendar module now uses argparse
instead of optparse.

@item 
bpo-25510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25510}: fileinput.FileInput.readline() now returns b'@w{'} instead of '@w{'} at
the end if the FileInput was opened with binary mode. Patch by Ryosuke
Ito.

@item 
bpo-25503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25503}: Fixed inspect.getdoc() for inherited docstrings of properties.
Original patch by John Mark Vandenberg.

@item 
bpo-25515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25515}: Always use os.urandom as a source of randomness in uuid.uuid4.

@item 
bpo-21827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21827}: Fixed textwrap.dedent() for the case when largest common
whitespace is a substring of smallest leading whitespace. Based on patch
by Robert Li.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: The lru_cache() wrapper objects now can be copied and pickled
(by returning the original object unchanged).

@item 
bpo-25390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25390}: typing: Don't crash on Union[str, Pattern].

@item 
bpo-25441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25441}: asyncio: Raise error from drain() when socket is closed.

@item 
bpo-25410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25410}: Cleaned up and fixed minor bugs in C implementation of
OrderedDict.

@item 
bpo-25411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25411}: Improved Unicode support in SMTPHandler through better use of
the email package. Thanks to user simon04 for the patch.

@item 
Move the imp module from a PendingDeprecationWarning to
DeprecationWarning.

@item 
bpo-25407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25407}: Remove mentions of the formatter module being removed in Python
3.6.

@item 
bpo-25406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25406}: Fixed a bug in C implementation of OrderedDict.move_to_end()
that caused segmentation fault or hang in iterating after moving several
items to the start of ordered dict.

@item 
bpo-25382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25382}: pickletools.dis() now outputs implicit memo index for the
MEMOIZE opcode.

@item 
bpo-25357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25357}: Add an optional newline parameter to binascii.b2a_base64().
base64.b64encode() uses it to avoid a memory copy.

@item 
bpo-24164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24164}: Objects that need calling @code{__new__} with keyword arguments,
can now be pickled using pickle protocols older than protocol version 4.

@item 
bpo-25364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25364}: zipfile now works in threads disabled builds.

@item 
bpo-25328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25328}: smtpd's SMTPChannel now correctly raises a ValueError if both
decode_data and enable_SMTPUTF8 are set to true.

@item 
bpo-16099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16099}: RobotFileParser now supports Crawl-delay and Request-rate
extensions.  Patch by Nikolay Bogoychev.

@item 
bpo-25316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25316}: distutils raises OSError instead of DistutilsPlatformError when
MSVC is not installed.

@item 
bpo-25380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25380}: Fixed protocol for the STACK_GLOBAL opcode in
pickletools.opcodes.

@item 
bpo-23972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23972}: Updates asyncio datagram create method allowing reuseport and
reuseaddr socket options to be set prior to binding the socket. Mirroring
the existing asyncio create_server method the reuseaddr option for
datagram sockets defaults to True if the O/S is 'posix' (except if the
platform is Cygwin). Patch by Chris Laws.

@item 
bpo-25304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25304}: Add asyncio.run_coroutine_threadsafe().  This lets you submit a
coroutine to a loop from another thread, returning a
concurrent.futures.Future.  By Vincent Michel.

@item 
bpo-25232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25232}: Fix CGIRequestHandler to split the query from the URL at the
first question mark (?) rather than the last. Patch from Xiang Zhang.

@item 
bpo-24657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24657}: Prevent CGIRequestHandler from collapsing slashes in the query
part of the URL as if it were a path. Patch from Xiang Zhang.

@item 
bpo-25287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25287}: Don't add crypt.METHOD_CRYPT to crypt.methods if it's not
supported. Check if it is supported, it may not be supported on OpenBSD
for example.

@item 
bpo-23600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23600}: Default implementation of tzinfo.fromutc() was returning wrong
results in some cases.

@item 
bpo-25203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25203}: Failed readline.set_completer_delims() no longer left the
module in inconsistent state.

@item 
bpo-25011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25011}: rlcompleter now omits private and special attribute names
unless the prefix starts with underscores.

@item 
bpo-25209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25209}: rlcompleter now can add a space or a colon after completed
keyword.

@item 
bpo-22241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22241}: timezone.utc name is now plain 'UTC', not 'UTC-00:00'.

@item 
bpo-23517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23517}: fromtimestamp() and utcfromtimestamp() methods of
datetime.datetime now round microseconds to nearest with ties going to
nearest even integer (ROUND_HALF_EVEN), as round(float), instead of
rounding towards -Infinity (ROUND_FLOOR).

@item 
bpo-23552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23552}: Timeit now warns when there is substantial (4x) variance
between best and worst times. Patch from Serhiy Storchaka.

@item 
bpo-24633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24633}: site-packages/README -> README.txt.

@item 
bpo-24879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24879}: help() and pydoc can now list named tuple fields in the order
they were defined rather than alphabetically.  The ordering is determined
by the _fields attribute if present.

@item 
bpo-24874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24874}: Improve speed of itertools.cycle() and make its pickle more
compact.

@item 
Fix crash in itertools.cycle.__setstate__() when the first argument wasn't
a list.

@item 
bpo-20059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20059}: urllib.parse raises ValueError on all invalid ports. Patch by
Martin Panter.

@item 
bpo-24360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24360}: Improve __repr__ of argparse.Namespace() for invalid
identifiers.  Patch by Matthias Bussonnier.

@item 
bpo-23426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23426}: run_setup was broken in distutils. Patch from Alexander
Belopolsky.

@item 
bpo-13938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13938}: 2to3 converts StringTypes to a tuple. Patch from Mark Hammond.

@item 
bpo-2091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2091}: open() accepted a 'U' mode string containing '+', but 'U' can
only be used with 'r'. Patch from Jeff Balogh and John O'Connor.

@item 
bpo-8585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8585}: improved tests for zipimporter2. Patch from Mark Lawrence.

@item 
bpo-18622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18622}: unittest.mock.mock_open().reset_mock would recurse infinitely.
Patch from Nicola Palumbo and Laurent De Buyst.

@item 
bpo-24426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24426}: Fast searching optimization in regular expressions now works
for patterns that starts with capturing groups.  Fast searching
optimization now can't be disabled at compile time.

@item 
bpo-23661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23661}: unittest.mock side_effects can now be exceptions again. This
was a regression vs Python 3.4. Patch from Ignacio Rossi

@item 
bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}: Remove deprecated inspect.getmoduleinfo function.

@item 
bpo-25578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25578}: Fix (another) memory leak in SSLSocket.getpeercer().

@item 
bpo-25530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25530}: Disable the vulnerable SSLv3 protocol by default when creating
ssl.SSLContext.

@item 
bpo-25569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25569}: Fix memory leak in SSLSocket.getpeercert().

@item 
bpo-25471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25471}: Sockets returned from accept() shouldn't appear to be
nonblocking.

@item 
bpo-25319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25319}: When threading.Event is reinitialized, the underlying condition
should use a regular lock rather than a recursive lock.

@item 
Skip getaddrinfo if host is already resolved. Patch by A. Jesse Jiryu
Davis.

@item 
bpo-26050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26050}: Add asyncio.StreamReader.readuntil() method. Patch by Марк
Коренберг.

@item 
bpo-25924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25924}: Avoid unnecessary serialization of getaddrinfo(3) calls on OS X
versions 10.5 or higher.  Original patch by A. Jesse Jiryu Davis.

@item 
bpo-26406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26406}: Avoid unnecessary serialization of getaddrinfo(3) calls on
current versions of OpenBSD and NetBSD.  Patch by A. Jesse Jiryu Davis.

@item 
bpo-26848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26848}: Fix asyncio/subprocess.communicate() to handle empty input.
Patch by Jack O'Connor.

@item 
bpo-27040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27040}: Add loop.get_exception_handler method

@item 
bpo-27041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27041}: asyncio: Add loop.create_future method
@end itemize

@node IDLE<56>,ドキュメント<77>,ライブラリ<189>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id967}@anchor{1f3a}
@subsubsection IDLE



@itemize -

@item 
bpo-20640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20640}: Add tests for idlelib.configHelpSourceEdit. Patch by Saimadhav
Heblikar.

@item 
In the 'IDLE-console differences' section of the IDLE doc, clarify how
running with IDLE affects sys.modules and the standard streams.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: fix incorrect change in IOBinding that prevented printing.
Augment IOBinding htest to include all major IOBinding functions.

@item 
bpo-25905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25905}: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION
MARK in README.txt and open this and NEWS.txt with 'ascii'. Re-encode
CREDITS.txt to utf-8 and open it with 'utf-8'.

@item 
bpo-15348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15348}: Stop the debugger engine (normally in a user process) before
closing the debugger window (running in the IDLE process). This prevents
the RuntimeErrors that were being caught and ignored.

@item 
bpo-24455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24455}: Prevent IDLE from hanging when a) closing the shell while the
debugger is active (15347); b) closing the debugger with the [X] button
(15348); and c) activating the debugger when already active (24455). The
patch by Mark Roseman does this by making two changes. 1. Suspend and
resume the gui.interaction method with the tcl vwait mechanism intended
for this purpose (instead of root.mainloop & .quit). 2. In gui.run, allow
any existing interaction to terminate first.

@item 
Change 'The program' to 'Your program' in an IDLE 'kill program?' message
to make it clearer that the program referred to is the currently running
user program, not IDLE itself.

@item 
bpo-24750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24750}: Improve the appearance of the IDLE editor window status bar.
Patch by Mark Roseman.

@item 
bpo-25313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25313}: Change the handling of new built-in text color themes to better
address the compatibility problem introduced by the addition of IDLE Dark.
Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.

@item 
bpo-24782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24782}: Extension configuration is now a tab in the IDLE Preferences
dialog rather than a separate dialog.  The former tabs are now a sorted
list.  Patch by Mark Roseman.

@item 
bpo-22726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22726}: Re-activate the config dialog help button with some content
about the other buttons and the new IDLE Dark theme.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: IDLE now has an 'IDLE Dark' built-in text color theme. It is
more or less IDLE Classic inverted, with a cobalt blue background.
Strings, comments, keywords, ... are still green, red, orange, ... . To
use it with IDLEs released before November 2015, hit the 'Save as New
Custom Theme' button and enter a new name, such as 'Custom Dark'.  The
custom theme will work with any IDLE release, and can be modified.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: README.txt is now an idlelib index for IDLE developers and
curious users. The previous user content is now in the IDLE doc chapter.
'IDLE' now means 'Integrated Development and Learning Environment'.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: Users can now set breakpoint colors in Settings -> Custom
Highlighting. Original patch by Mark Roseman.

@item 
bpo-24972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24972}: Inactive selection background now matches active selection
background, as configured by users, on all systems.  Found items are now
always highlighted on Windows.  Initial patch by Mark Roseman.

@item 
bpo-24570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24570}: Idle: make calltip and completion boxes appear on Macs affected
by a tk regression.  Initial patch by Mark Roseman.

@item 
bpo-24988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24988}: Idle ScrolledList context menus (used in debugger) now work on
Mac Aqua. Patch by Mark Roseman.

@item 
bpo-24801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24801}: Make right-click for context menu work on Mac Aqua. Patch by
Mark Roseman.

@item 
bpo-25173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25173}: Associate tkinter messageboxes with a specific widget. For Mac
OSX, make them a 'sheet'.  Patch by Mark Roseman.

@item 
bpo-25198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25198}: Enhance the initial html viewer now used for Idle Help.
Properly indent fixed-pitch text (patch by Mark Roseman). Give code
snippet a very Sphinx-like light blueish-gray background. Re-use initial
width and height set by users for shell and editor. When the Table of
Contents (TOC) menu is used, put the section header at the top of the
screen.

@item 
bpo-25225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25225}: Condense and rewrite Idle doc section on text colors.

@item 
bpo-21995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21995}: Explain some differences between IDLE and console Python.

@item 
bpo-22820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22820}: Explain need for `print' when running file from Idle editor.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: Doc: augment Idle feature list and no-subprocess section.

@item 
bpo-25219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25219}: Update doc for Idle command line options. Some were missing and
notes were not correct.

@item 
bpo-24861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24861}: Most of idlelib is private and subject to change. Use
idleib.idle.* to start Idle. See idlelib.__init__.__doc__.

@item 
bpo-25199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25199}: Idle: add synchronization comments for future maintainers.

@item 
bpo-16893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16893}: Replace help.txt with help.html for Idle doc display. The new
idlelib/help.html is rstripped Doc/build/html/library/idle.html. It looks
better than help.txt and will better document Idle as released. The
tkinter html viewer that works for this file was written by Rose Roseman.
The now unused EditorWindow.HelpDialog class and helt.txt file are
deprecated.

@item 
bpo-24199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24199}: Deprecate unused idlelib.idlever with possible removal in 3.6.

@item 
bpo-24790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24790}: Remove extraneous code (which also create 2 & 3 conflicts).
@end itemize

@node ドキュメント<77>,テスト<77>,IDLE<56>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id968}@anchor{1f3b}
@subsubsection ドキュメント



@itemize -

@item 
bpo-26736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26736}: Used HTTPS for external links in the documentation if possible.

@item 
bpo-6953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6953}: Rework the Readline module documentation to group related
functions together, and add more details such as what underlying Readline
functions and variables are accessed.

@item 
bpo-23606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23606}: Adds note to ctypes documentation regarding cdll.msvcrt.

@item 
bpo-24952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24952}: Clarify the default size argument of stack_size() in the
"threading" and "_thread" modules. Patch from Mattip.

@item 
bpo-26014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26014}: Update 3.x packaging documentation: * "See also" links to the
new docs are now provided in the legacy pages * links to setuptools
documentation have been updated
@end itemize

@node テスト<77>,ビルド<88>,ドキュメント<77>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id969}@anchor{1f3c}
@subsubsection テスト



@itemize -

@item 
bpo-21916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21916}: Added tests for the turtle module.  Patch by ingrid, Gregory
Loyse and Jelle Zijlstra.

@item 
bpo-26295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26295}: When using "python3 -m test --testdir=TESTDIR", regrtest
doesn't add "test." prefix to test module names.

@item 
bpo-26523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26523}: The multiprocessing thread pool (multiprocessing.dummy.Pool)
was untested.

@item 
bpo-26015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26015}: Added new tests for pickling iterators of mutable sequences.

@item 
bpo-26325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26325}: Added test.support.check_no_resource_warning() to check that no
ResourceWarning is emitted.

@item 
bpo-25940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25940}: Changed test_ssl to use its internal local server more.  This
avoids relying on svn.python.org, which recently changed root certificate.

@item 
bpo-25616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25616}: Tests for OrderedDict are extracted from test_collections into
separate file test_ordered_dict.

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Added tests for OrderedDict subclasses.

@item 
bpo-25188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25188}: Add -P/--pgo to test.regrtest to suppress error output when
running the test suite for the purposes of a PGO build. Initial patch by
Alecsandru Patrascu.

@item 
bpo-22806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22806}: Add @code{python -m test --list-tests} command to list tests.

@item 
bpo-18174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18174}: @code{python -m test --huntrleaks ...} now also checks for leak of
file descriptors. Patch written by Richard Oudkerk.

@item 
bpo-25260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25260}: Fix @code{python -m test --coverage} on Windows. Remove the list
of ignored directories.

@item 
@code{PCbuild\rt.bat} now accepts an unlimited number of arguments to pass
along to regrtest.py.  Previously there was a limit of 9.

@item 
bpo-26583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26583}: Skip test_timestamp_overflow in test_import if bytecode files
cannot be written.
@end itemize

@node ビルド<88>,Windows<76>,テスト<77>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id970}@anchor{1f3d}
@subsubsection ビルド



@itemize -

@item 
bpo-21277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21277}: Don't try to link _ctypes with a ffi_convenience library.

@item 
bpo-26884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26884}: Fix linking extension modules for cross builds. Patch by Xavier
de Gaye.

@item 
bpo-26932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26932}: Fixed support of RTLD_* constants defined as enum values, not
via macros (in particular on Android).  Patch by Chi Hsuan Yen.

@item 
bpo-22359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22359}: Disable the rules for running _freeze_importlib and pgen when
cross-compiling.  The output of these programs is normally saved with the
source code anyway, and is still regenerated when doing a native build.
Patch by Xavier de Gaye.

@item 
bpo-21668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21668}: Link audioop, _datetime, _ctypes_test modules to libm, except
on Mac OS X. Patch written by Chi Hsuan Yen.

@item 
bpo-25702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25702}: A --with-lto configure option has been added that will enable
link time optimizations at build time during a make profile-opt. Some
compilers and toolchains are known to not produce stable code when using
LTO, be sure to test things thoroughly before relying on it. It can
provide a few % speed up over profile-opt alone.

@item 
bpo-26624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26624}: Adds validation of ucrtbase[d].dll version with warning for old
versions.

@item 
bpo-17603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17603}: Avoid error about nonexistent fileblocks.o file by using a
lower-level check for st_blocks in struct stat.

@item 
bpo-26079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26079}: Fixing the build output folder for tix-8.4.3.6. Patch by Bjoern
Thiel.

@item 
bpo-26465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26465}: Update Windows builds to use OpenSSL 1.0.2g.

@item 
bpo-25348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25348}: Added @code{--pgo} and @code{--pgo-job} arguments to
@code{PCbuild\build.bat} for building with Profile-Guided Optimization.  The
old @code{PCbuild\build_pgo.bat} script is removed.

@item 
bpo-25827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25827}: Add support for building with ICC to @code{configure}, including a
new @code{--with-icc} flag.

@item 
bpo-25696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25696}: Fix installation of Python on UNIX with make -j9.

@item 
bpo-24986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24986}: It is now possible to build Python on Windows without errors
when external libraries are not available.

@item 
bpo-24421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24421}: Compile Modules/_math.c once, before building extensions.
Previously it could fail to compile properly if the math and cmath builds
were concurrent.

@item 
bpo-26465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26465}: Update OS X 10.5+ 32-bit-only installer to build and link with
OpenSSL 1.0.2g.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update Windows builds to use OpenSSL 1.0.2f.

@item 
bpo-25136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25136}: Support Apple Xcode 7's new textual SDK stub libraries.

@item 
bpo-24324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24324}: Do not enable unreachable code warnings when using gcc as the
option does not work correctly in older versions of gcc and has been
silently removed as of gcc-4.5.
@end itemize

@node Windows<76>,Tools/Demos<54>,ビルド<88>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id971}@anchor{1f3e}
@subsubsection Windows



@itemize -

@item 
bpo-27053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27053}: Updates make_zip.py to correctly generate library ZIP file.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update the prepare_ssl.py script to handle OpenSSL releases
that don't include the contents of the include directory (that is, 1.0.2e
and later).

@item 
bpo-26071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26071}: bdist_wininst created binaries fail to start and find 32bit
Python

@item 
bpo-26073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26073}: Update the list of magic numbers in launcher

@item 
bpo-26065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26065}: Excludes venv from library when generating embeddable distro.

@item 
bpo-25022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25022}: Removed very outdated PC/example_nt/ directory.
@end itemize

@node Tools/Demos<54>,C API<74>,Windows<76>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id972}@anchor{1f3f}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-26799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26799}: Fix python-gdb.py: don't get C types once when the Python code
is loaded, but get C types on demand. The C types can change if
python-gdb.py is loaded before the Python executable. Patch written by
Thomas Ilsche.

@item 
bpo-26271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26271}: Fix the Freeze tool to properly use flags passed through
configure. Patch by Daniel Shaulov.

@item 
bpo-26489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26489}: Add dictionary unpacking support to Tools/parser/unparse.py.
Patch by Guo Ci Teo.

@item 
bpo-26316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26316}: Fix variable name typo in Argument Clinic.

@item 
bpo-25440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25440}: Fix output of python-config --extension-suffix.

@item 
bpo-25154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25154}: The pyvenv script has been deprecated in favour of @code{python3 -m
venv}.
@end itemize

@node C API<74>,,Tools/Demos<54>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id973}@anchor{1f40}
@subsubsection C API



@itemize -

@item 
bpo-26312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26312}: SystemError is now raised in all programming bugs with using
PyArg_ParseTupleAndKeywords().  RuntimeError did raised before in some
programming bugs.

@item 
bpo-26198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26198}: ValueError is now raised instead of TypeError on buffer
overflow in parsing "es#" and "et#" format units.  SystemError is now
raised instead of TypeError on programmatical error in parsing format
string.
@end itemize

@node Python 3 5 5 final,Python 3 5 5 release candidate 1,Python 3 6 0 alpha 1,変更履歴
@anchor{whatsnew/changelog python-3-5-5-final}@anchor{1f41}
@subsection Python 3.5.5 final


`Release date: 2018-02-04'

There were no new changes in version 3.5.5.

@node Python 3 5 5 release candidate 1,Python 3 5 4 final,Python 3 5 5 final,変更履歴
@anchor{whatsnew/changelog python-3-5-5-release-candidate-1}@anchor{1f42}
@subsection Python 3.5.5 release candidate 1


`Release date: 2018-01-23'

@menu
* セキュリティ: セキュリティ<57>. 
* Core and Builtins: Core and Builtins<187>. 
* ライブラリ: ライブラリ<190>. 

@end menu

@node セキュリティ<57>,Core and Builtins<187>,,Python 3 5 5 release candidate 1
@anchor{whatsnew/changelog id974}@anchor{1f43}
@subsubsection セキュリティ



@itemize -

@item 
bpo-32551@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32551}: The @code{sys.path[0]} initialization change for bpo-29139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29139} caused
a regression by revealing an inconsistency in how sys.path is initialized
when executing @code{__main__} from a zipfile, directory, or other import
location. This is considered a potential security issue, as it may lead to
privileged processes unexpectedly loading code from user controlled
directories in situations where that was not previously the case. The
interpreter now consistently avoids ever adding the import location's
parent directory to @code{sys.path}, and ensures no other @code{sys.path}
entries are inadvertently modified when inserting the import location
named on the command line. (Originally reported as bpo-29723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29723} against
Python 3.6rc1, but it was missed at the time that the then upcoming Python
3.5.4 release would also be affected)

@item 
bpo-30657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30657}: Fixed possible integer overflow in PyBytes_DecodeEscape,
@geindex Common Vulnerabilities and Exposures; CVE 2017-1000158
CVE 2017-1000158@footnote{https://www.cve.org/CVERecord?id=CVE-2017-1000158}. Original patch by Jay Bosamiya; rebased to Python 3
by Miro Hrončok.

@item 
bpo-30947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30947}: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to
get security fixes.
@end itemize

@node Core and Builtins<187>,ライブラリ<190>,セキュリティ<57>,Python 3 5 5 release candidate 1
@anchor{whatsnew/changelog id975}@anchor{1f44}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31095}: Fix potential crash during GC caused by @code{tp_dealloc} which
doesn't call @code{PyObject_GC_UnTrack()}.
@end itemize

@node ライブラリ<190>,,Core and Builtins<187>,Python 3 5 5 release candidate 1
@anchor{whatsnew/changelog id976}@anchor{1f45}
@subsubsection ライブラリ



@itemize -

@item 
bpo-32072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32072}: Fixed issues with binary plists: Fixed saving bytearrays.
Identical objects will be saved only once. Equal references will be load
as identical objects. Added support for saving and loading recursive data
structures.

@item 
bpo-31170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31170}: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of
partial characters for UTF-8 input (libexpat bug 115):
@indicateurl{https://github.com/libexpat/libexpat/issues/115}
@end itemize

@node Python 3 5 4 final,Python 3 5 4 release candidate 1,Python 3 5 5 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-5-4-final}@anchor{1f46}
@subsection Python 3.5.4 final


`Release date: 2017-08-07'

@menu
* ライブラリ: ライブラリ<191>. 

@end menu

@node ライブラリ<191>,,,Python 3 5 4 final
@anchor{whatsnew/changelog id977}@anchor{1f47}
@subsubsection ライブラリ



@itemize -

@item 
bpo-30119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30119}: ftplib.FTP.putline() now throws ValueError on commands that
contains CR or LF. Patch by Donghee Na.
@end itemize

@node Python 3 5 4 release candidate 1,Python 3 5 3 final,Python 3 5 4 final,変更履歴
@anchor{whatsnew/changelog python-3-5-4-release-candidate-1}@anchor{1f48}
@subsection Python 3.5.4 release candidate 1


`Release date: 2017-07-23'

@menu
* セキュリティ: セキュリティ<58>. 
* Core and Builtins: Core and Builtins<188>. 
* ライブラリ: ライブラリ<192>. 
* ドキュメント: ドキュメント<78>. 
* テスト: テスト<78>. 
* ビルド: ビルド<89>. 
* Windows: Windows<77>. 
* C API: C API<75>. 

@end menu

@node セキュリティ<58>,Core and Builtins<188>,,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id978}@anchor{1f49}
@subsubsection セキュリティ



@itemize -

@item 
bpo-30730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30730}: Prevent environment variables injection in subprocess on
Windows.  Prevent passing other environment variables and command
arguments.

@item 
bpo-30694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30694}: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple
security vulnerabilities including: 
@geindex Common Vulnerabilities and Exposures; CVE 2017-9233
CVE 2017-9233@footnote{https://www.cve.org/CVERecord?id=CVE-2017-9233} (External entity
infinite loop DoS), 
@geindex Common Vulnerabilities and Exposures; CVE 2016-9063
CVE 2016-9063@footnote{https://www.cve.org/CVERecord?id=CVE-2016-9063} (Integer overflow, re-fix),
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718} (Fix regression bugs from 2.2.0's fix to
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718}) and 
@geindex Common Vulnerabilities and Exposures; CVE 2012-0876
CVE 2012-0876@footnote{https://www.cve.org/CVERecord?id=CVE-2012-0876} (Counter hash flooding with
SipHash). Note: the 
@geindex Common Vulnerabilities and Exposures; CVE 2016-5300
CVE 2016-5300@footnote{https://www.cve.org/CVERecord?id=CVE-2016-5300} (Use os-specific entropy sources like
getrandom) doesn't impact Python, since Python already gets entropy from
the OS to set the expat secret using @code{XML_SetHashSalt()}.

@item 
bpo-30500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30500}: Fix urllib.parse.splithost() to correctly parse fragments. For
example, @code{splithost('//127.0.0.1#@@evil.com/')} now correctly returns the
@code{127.0.0.1} host, instead of treating @code{@@evil.com} as the host in an
authentication (@code{login@@host}).

@item 
bpo-29591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29591}: Update expat copy from 2.1.1 to 2.2.0 to get fixes of
@geindex Common Vulnerabilities and Exposures; CVE 2016-0718
CVE 2016-0718@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0718} and 
@geindex Common Vulnerabilities and Exposures; CVE 2016-4472
CVE 2016-4472@footnote{https://www.cve.org/CVERecord?id=CVE-2016-4472}. See
@indicateurl{https://sourceforge.net/p/expat/bugs/537/} for more information.
@end itemize

@node Core and Builtins<188>,ライブラリ<192>,セキュリティ<58>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id979}@anchor{1f4a}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-30876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30876}: Relative import from unloaded package now reimports the package
instead of failing with SystemError.  Relative import from non-package now
fails with ImportError rather than SystemError.

@item 
bpo-30765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30765}: Avoid blocking in pthread_mutex_lock() when
PyThread_acquire_lock() is asked not to block.

@item 
bpo-27945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27945}: Fixed various segfaults with dict when input collections are
mutated during searching, inserting or comparing.  Based on patches by
Duane Griffin and Tim Mitchell.

@item 
bpo-25794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25794}: Fixed type.__setattr__() and type.__delattr__() for
non-interned attribute names.  Based on patch by Eryk Sun.

@item 
bpo-29935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29935}: Fixed error messages in the index() method of tuple, list and
deque when pass indices of wrong type.

@item 
bpo-28876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28876}: @code{bool(range)} works even if @code{len(range)} raises
@ref{a81,,OverflowError}.

@item 
bpo-29600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29600}: Fix wrapping coroutine return values in StopIteration.

@item 
bpo-29537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29537}: Restore runtime compatibility with bytecode files generated by
CPython 3.5.0 to 3.5.2, and adjust the eval loop to avoid the problems
that could be caused by the malformed variant of the
BUILD_MAP_UNPACK_WITH_CALL opcode that they may contain. Patch by Petr
Viktorin, Serhiy Storchaka, and Nick Coghlan.

@item 
bpo-28598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28598}: Support __rmod__ for subclasses of str being called before
str.__mod__. Patch by Martijn Pieters.

@item 
bpo-29602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29602}: Fix incorrect handling of signed zeros in complex constructor
for complex subclasses and for inputs having a __complex__ method. Patch
by Serhiy Storchaka.

@item 
bpo-29347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29347}: Fixed possibly dereferencing undefined pointers when creating
weakref objects.

@item 
bpo-29438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29438}: Fixed use-after-free problem in key sharing dict.

@item 
bpo-29319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29319}: Prevent RunMainFromImporter overwriting sys.path[0].

@item 
bpo-29337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29337}: Fixed possible BytesWarning when compare the code objects.
Warnings could be emitted at compile time.

@item 
bpo-29478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29478}: If max_line_length=None is specified while using the Compat32
policy, it is no longer ignored.  Patch by Mircea Cosbuc.
@end itemize

@node ライブラリ<192>,ドキュメント<78>,Core and Builtins<188>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id980}@anchor{1f4b}
@subsubsection ライブラリ



@itemize -

@item 
bpo-29403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29403}: Fix @code{unittest.mock}'s autospec to not fail on method-bound
builtin functions.  Patch by Aaron Gallagher.

@item 
bpo-30961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30961}: Fix decrementing a borrowed reference in tracemalloc.

@item 
bpo-30886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30886}: Fix multiprocessing.Queue.join_thread(): it now waits until the
thread completes, even if the thread was started by the same process which
created the queue.

@item 
bpo-29854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29854}: Fix segfault in readline when using readline's history-size
option.  Patch by Nir Soffer.

@item 
bpo-30807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30807}: signal.setitimer() may disable the timer when passed a tiny
value. Tiny values (such as 1e-6) are valid non-zero values for
setitimer(), which is specified as taking microsecond-resolution
intervals. However, on some platform, our conversion routine could convert
1e-6 into a zero interval, therefore disabling the timer instead of
(re-)scheduling it.

@item 
bpo-30441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30441}: Fix bug when modifying os.environ while iterating over it

@item 
bpo-30532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30532}: Fix email header value parser dropping folding white space in
certain cases.

@item 
bpo-29169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29169}: Update zlib to 1.2.11.

@item 
bpo-30879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30879}: os.listdir() and os.scandir() now emit bytes names when called
with bytes-like argument.

@item 
bpo-30746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30746}: Prohibited the '=' character in environment variable names in
@code{os.putenv()} and @code{os.spawn*()}.

@item 
bpo-29755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29755}: Fixed the lgettext() family of functions in the gettext module.
They now always return bytes.

@item 
bpo-30645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30645}: Fix path calculation in imp.load_package(), fixing it for cases
when a package is only shipped with bytecodes. Patch by Alexandru
Ardelean.

@item 
bpo-23890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23890}: unittest.TestCase.assertRaises() now manually breaks a
reference cycle to not keep objects alive longer than expected.

@item 
bpo-30149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30149}: inspect.signature() now supports callables with
variable-argument parameters wrapped with partialmethod. Patch by Donghee
Na.

@item 
bpo-29931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29931}: Fixed comparison check for ipaddress.ip_interface objects.
Patch by Sanjay Sundaresan.

@item 
bpo-24484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24484}: Avoid race condition in multiprocessing cleanup.

@item 
bpo-28994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28994}: The traceback no longer displayed for SystemExit raised in a
callback registered by atexit.

@item 
bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508}: Don't log exceptions if Task/Future "cancel()" method was
called.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Updates to typing module: Add generic AsyncContextManager, add
support for ContextManager on all versions. Original PRs by Jelle Zijlstra
and Ivan Levkivskyi

@item 
bpo-29870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29870}: Fix ssl sockets leaks when connection is aborted in asyncio/ssl
implementation. Patch by Michaël Sghaïer.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Closing transport during handshake process leaks open socket.
Patch by Nikolay Kim

@item 
bpo-27585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27585}: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu
Sornay.

@item 
bpo-30418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30418}: On Windows, subprocess.Popen.communicate() now also ignore
EINVAL on stdin.write() if the child process is still running but closed
the pipe.

@item 
bpo-30378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30378}: Fix the problem that logging.handlers.SysLogHandler cannot
handle IPv6 addresses.

@item 
bpo-29960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29960}: Preserve generator state when _random.Random.setstate() raises
an exception. Patch by Bryan Olson.

@item 
bpo-30414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30414}: multiprocessing.Queue._feed background running thread do not
break from main loop on exception.

@item 
bpo-30003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30003}: Fix handling escape characters in HZ codec.  Based on patch by
Ma Lin.

@item 
bpo-30301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30301}: Fix AttributeError when using SimpleQueue.empty() under `spawn'
and `forkserver' start methods.

@item 
bpo-30329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30329}: imaplib and poplib now catch the Windows socket WSAEINVAL error
(code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted.
This error occurs sometimes on SSL connections.

@item 
bpo-30375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30375}: Warnings emitted when compile a regular expression now always
point to the line in the user code.  Previously they could point into
inners of the re module if emitted from inside of groups or conditionals.

@item 
bpo-30048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30048}: Fixed @code{Task.cancel()} can be ignored when the task is running
coroutine and the coroutine returned without any more @code{await}.

@item 
bpo-29990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29990}: Fix range checking in GB18030 decoder.  Original patch by Ma
Lin.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Change resulted because of zipfile breakage. (See also:
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094})

@item 
bpo-30243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30243}: Removed the __init__ methods of _json's scanner and encoder.
Misusing them could cause memory leaks or crashes.  Now scanner and
encoder objects are completely initialized in the __new__ methods.

@item 
bpo-30185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30185}: Avoid KeyboardInterrupt tracebacks in forkserver helper process
when Ctrl-C is received.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: add typing.NoReturn type, use
WrapperDescriptorType, minor bug-fixes.  Original PRs by Jim
Fasarakis-Hilliard and Ivan Levkivskyi.

@item 
bpo-30205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30205}: Fix getsockname() for unbound AF_UNIX sockets on Linux.

@item 
bpo-30070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30070}: Fixed leaks and crashes in errors handling in the parser
module.

@item 
bpo-30061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30061}: Fixed crashes in IOBase methods __next__() and readlines() when
readline() or __next__() respectively return non-sizeable object. Fixed
possible other errors caused by not checking results of PyObject_Size(),
PySequence_Size(), or PyMapping_Size().

@item 
bpo-30068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30068}: _io._IOBase.readlines will check if it's closed first when hint
is present.

@item 
bpo-29694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29694}: Fixed race condition in pathlib mkdir with flags parents=True.
Patch by Armin Rigo.

@item 
bpo-29692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29692}: Fixed arbitrary unchaining of RuntimeError exceptions in
contextlib.contextmanager.  Patch by Siddharth Velankar.

@item 
bpo-29998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29998}: Pickling and copying ImportError now preserves name and path
attributes.

@item 
bpo-29942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29942}: Fix a crash in itertools.chain.from_iterable when encountering
long runs of empty iterables.

@item 
bpo-27863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27863}: Fixed multiple crashes in ElementTree caused by race conditions
and wrong types.

@item 
bpo-28699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28699}: Fixed a bug in pools in multiprocessing.pool that raising an
exception at the very first of an iterable may swallow the exception or
make the program hang. Patch by Davin Potts and Xiang Zhang.

@item 
bpo-25803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25803}: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when
the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-29861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29861}: Release references to tasks, their arguments and their results
as soon as they are finished in multiprocessing.Pool.

@item 
bpo-29884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29884}: faulthandler: Restore the old sigaltstack during teardown.
Patch by Christophe Zeitouny.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive buffered file-like objects.

@item 
bpo-29800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29800}: Fix crashes in partial.__repr__ if the keys of partial.keywords
are not strings.  Patch by Michael Seifert.

@item 
bpo-29742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29742}: get_extra_info() raises exception if get called on closed ssl
transport. Patch by Nikolay Kim.

@item 
bpo-8256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8256}: Fixed possible failing or crashing input() if attributes
"encoding" or "errors" of sys.stdin or sys.stdout are not set or are not
strings.

@item 
bpo-28298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28298}: Fix a bug that prevented array 'Q', 'L' and 'I' from accepting
big intables (objects that have __int__) as elements.  Patch by Oren
Milman.

@item 
bpo-29615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29615}: SimpleXMLRPCDispatcher no longer chains KeyError (or any other
exception) to exception(s) raised in the dispatched methods. Patch by Petr
Motejlek.

@item 
bpo-29704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29704}: asyncio.subprocess.SubprocessStreamProtocol no longer closes
before all pipes are closed.

@item 
bpo-29703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29703}: Fix asyncio to support instantiation of new event loops in
child processes.

@item 
bpo-29376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29376}: Fix assertion error in threading._DummyThread.is_alive().

@item 
bpo-29110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29110}: Fix file object leak in aifc.open() when file is given as a
filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

@item 
bpo-28961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28961}: Fix unittest.mock._Call helper: don't ignore the name parameter
anymore. Patch written by Jiajun Huang.

@item 
bpo-29532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29532}: Altering a kwarg dictionary passed to functools.partial() no
longer affects a partial object after creation.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: typing.Counter,
typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle
Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

@item 
bpo-29100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29100}: Fix datetime.fromtimestamp() regression introduced in Python
3.6.0: check minimum and maximum years.

@item 
bpo-29519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29519}: Fix weakref spewing exceptions during interpreter shutdown when
used with a rare combination of multiprocessing and custom codecs.

@item 
bpo-29416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29416}: Prevent infinite loop in pathlib.Path.mkdir

@item 
bpo-29444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29444}: Fixed out-of-bounds buffer access in the group() method of the
match object. Based on patch by WGH.

@item 
bpo-29335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29335}: Fix subprocess.Popen.wait() when the child process has exited
to a stopped instead of terminated state (ex: when under ptrace).

@item 
bpo-29290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29290}: Fix a regression in argparse that help messages would wrap at
non-breaking spaces.

@item 
bpo-28735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28735}: Fixed the comparison of mock.MagickMock with mock.ANY.

@item 
bpo-29011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29011}: Fix an important omission by adding Deque to the typing module.

@item 
bpo-29219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29219}: Fixed infinite recursion in the repr of uninitialized
ctypes.CDLL instances.

@item 
bpo-28969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28969}: Fixed race condition in C implementation of
functools.lru_cache. KeyError could be raised when cached function with
full cache was simultaneously called from different threads with the same
uncached arguments.

@item 
bpo-29142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29142}: In urllib.request, suffixes in no_proxy environment variable
with leading dots could match related hostnames again (e.g. .b.c matches
a.b.c). Patch by Milan Oberkirch.
@end itemize

@node ドキュメント<78>,テスト<78>,ライブラリ<192>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id981}@anchor{1f4c}
@subsubsection ドキュメント



@itemize -

@item 
bpo-30176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30176}: Add missing attribute related constants in curses
documentation.

@item 
bpo-26985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26985}: Add missing info of code object in inspect documentation.

@item 
bpo-28929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28929}: Link the documentation to its source file on GitHub.

@item 
bpo-25008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25008}: Document smtpd.py as effectively deprecated and add a pointer
to aiosmtpd, a third-party asyncio-based replacement.

@item 
bpo-26355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26355}: Add canonical header link on each page to corresponding major
version of the documentation. Patch by Matthias Bussonnier.

@item 
bpo-29349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29349}: Fix Python 2 syntax in code for building the documentation.
@end itemize

@node テスト<78>,ビルド<89>,ドキュメント<78>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id982}@anchor{1f4d}
@subsubsection テスト



@itemize -

@item 
bpo-30822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30822}: Fix regrtest command line parser to allow passing -u
extralargefile to run test_zipfile64.

@item 
bpo-30383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30383}: regrtest: Enhance regrtest and backport features from the
master branch. Add options: --coverage, --testdir, --list-tests (list test
files, don't run them), --list-cases (list test identifiers, don't run
them, bpo-30523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30523}), --matchfile (load a list of test filters from a
text file, bpo-30540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30540}), --slowest (alias to --slow). Enhance output:
add timestamp, test result, currently running tests, "Tests result: xxx"
summary with total duration, etc. Fix reference leak hunting in regrtest,
--huntrleaks: regrtest now warms up caches, create explicitly all internal
singletons which are created on demand to prevent false positives when
checking for reference leaks. (bpo-30675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30675}).

@item 
bpo-30357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30357}: test_thread: setUp() now uses support.threading_setup() and
support.threading_cleanup() to wait until threads complete to avoid random
side effects on following tests. Initial patch written by Grzegorz
Grzywacz.

@item 
bpo-28087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28087}: Skip test_asyncore and test_eintr poll failures on macOS. Skip
some tests of select.poll when running on macOS due to unresolved issues
with the underlying system poll function on some macOS versions.

@item 
bpo-30197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30197}: Enhanced functions swap_attr() and swap_item() in the
test.support module. They now work when delete replaced attribute or item
inside the with statement.  The old value of the attribute or item (or
None if it doesn't exist) now will be assigned to the target of the "as"
clause, if there is one.

@item 
bpo-29571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29571}: to match the behaviour of the @code{re.LOCALE} flag,
test_re.test_locale_flag now uses @code{locale.getpreferredencoding(False)}
to determine the candidate encoding for the test regex (allowing it to
correctly skip the test when the default locale encoding is a multi-byte
encoding)
@end itemize

@node ビルド<89>,Windows<77>,テスト<78>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id983}@anchor{1f4e}
@subsubsection ビルド



@itemize -

@item 
bpo-29243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29243}: Prevent unnecessary rebuilding of Python during @code{make test},
@code{make install} and some other make targets when configured with
@code{--enable-optimizations}.

@item 
bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404}: Don't regenerate generated files based on file modification
time anymore: the action is now explicit. Replace @code{make touch} with
@code{make regen-all}.

@item 
bpo-29643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29643}: Fix @code{--enable-optimization} didn't work.
@end itemize

@node Windows<77>,C API<75>,ビルド<89>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id984}@anchor{1f4f}
@subsubsection Windows



@itemize -

@item 
bpo-30687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30687}: Locate msbuild.exe on Windows when building rather than
vcvarsall.bat

@item 
bpo-29392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29392}: Prevent crash when passing invalid arguments into msvcrt
module.
@end itemize

@node C API<75>,,Windows<77>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id985}@anchor{1f50}
@subsubsection C API



@itemize -

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() is replaced with a macro if
Py_LIMITED_API is set to the value between 0x03050400 and 0x03060000 (not
including) or 0x03060100 or higher.

@item 
bpo-29083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29083}: Fixed the declaration of some public API functions.
PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in
limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and
Py_BuildValue() were not available in limited API of version < 3.3 when
PY_SSIZE_T_CLEAN is defined.
@end itemize

@node Python 3 5 3 final,Python 3 5 3 release candidate 1,Python 3 5 4 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-5-3-final}@anchor{1f51}
@subsection Python 3.5.3 final


`Release date: 2017-01-17'

There were no code changes between 3.5.3rc1 and 3.5.3 final.

@node Python 3 5 3 release candidate 1,Python 3 5 2 final,Python 3 5 3 final,変更履歴
@anchor{whatsnew/changelog python-3-5-3-release-candidate-1}@anchor{1f52}
@subsection Python 3.5.3 release candidate 1


`Release date: 2017-01-02'

@menu
* セキュリティ: セキュリティ<59>. 
* Core and Builtins: Core and Builtins<189>. 
* ライブラリ: ライブラリ<193>. 
* IDLE: IDLE<57>. 
* C API: C API<76>. 
* ドキュメント: ドキュメント<79>. 
* テスト: テスト<79>. 
* Tools/Demos: Tools/Demos<55>. 
* Windows: Windows<78>. 
* ビルド: ビルド<90>. 

@end menu

@node セキュリティ<59>,Core and Builtins<189>,,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id986}@anchor{1f53}
@subsubsection セキュリティ



@itemize -

@item 
bpo-27278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27278}: Fix os.urandom() implementation using getrandom() on Linux.
Truncate size to INT_MAX and loop until we collected enough random bytes,
instead of casting a directly Py_ssize_t to int.

@item 
bpo-22636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22636}: Avoid shell injection problems with ctypes.util.find_library().
@end itemize

@node Core and Builtins<189>,ライブラリ<193>,セキュリティ<59>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id987}@anchor{1f54}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-29073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29073}: bytearray formatting no longer truncates on first null byte.

@item 
bpo-28932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28932}: Do not include <sys/random.h> if it does not exist.

@item 
bpo-28147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28147}: Fix a memory leak in split-table dictionaries: setattr() must
not convert combined table into split table.

@item 
bpo-25677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25677}: Correct the positioning of the syntax error caret for indented
blocks. Based on patch by Michael Layzell.

@item 
bpo-29000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29000}: Fixed bytes formatting of octals with zero padding in alternate
form.

@item 
bpo-28512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28512}: Fixed setting the offset attribute of SyntaxError by
PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

@item 
bpo-28991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28991}: functools.lru_cache() was susceptible to an obscure reentrancy
bug caused by a monkey-patched len() function.

@item 
bpo-28648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28648}: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X
when decode astral characters.  Patch by Xiang Zhang.

@item 
bpo-19398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19398}: Extra slash no longer added to sys.path components in case of
empty compile-time PYTHONPATH components.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Fixed potential crash in PyUnicode_AsDecodedObject() in debug
build.

@item 
bpo-23782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23782}: Fixed possible memory leak in _PyTraceback_Add() and exception
loss in PyTraceBack_Here().

@item 
bpo-28379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28379}: Added sanity checks and tests for PyUnicode_CopyCharacters().
Patch by Xiang Zhang.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The type of long range iterator is now registered as Iterator.
Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The constructor of range_iterator now checks that step is not
0. Patch by Oren Milman.

@item 
bpo-26906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26906}: Resolving special methods of uninitialized type now causes
implicit initialization of the type instead of a fail.

@item 
bpo-18287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18287}: PyType_Ready() now checks that tp_name is not NULL. Original
patch by Niklas Koep.

@item 
bpo-24098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24098}: Fixed possible crash when AST is changed in process of
compiling it.

@item 
bpo-28350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28350}: String constants with null character no longer interned.

@item 
bpo-26617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26617}: Fix crash when GC runs during weakref callbacks.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: String constants now interned recursively in tuples and
frozensets.

@item 
bpo-21578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21578}: Fixed misleading error message when ImportError called with
invalid keyword args.

@item 
bpo-28203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28203}: Fix incorrect type in error message from @code{complex(1.0,
@{2:3@})}. Patch by Soumya Sharma.

@item 
bpo-27955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27955}: Fallback on reading /dev/urandom device when the getrandom()
syscall fails with EPERM, for example when blocked by SECCOMP.

@item 
bpo-28131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28131}: Fix a regression in zipimport's compile_source().  zipimport
should use the same optimization level as the interpreter.

@item 
bpo-25221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25221}: Fix corrupted result from PyLong_FromLong(0) when Python is
compiled with NSMALLPOSINTS = 0.

@item 
bpo-25758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25758}: Prevents zipimport from unnecessarily encoding a filename
(patch by Eryk Sun)

@item 
bpo-28189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28189}: dictitems_contains no longer swallows compare errors. (Patch by
Xiang Zhang)

@item 
bpo-27812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27812}: Properly clear out a generator's frame's backreference to the
generator to prevent crashes in frame.clear().

@item 
bpo-27811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27811}: Fix a crash when a coroutine that has not been awaited is
finalized with warnings-as-errors enabled.

@item 
bpo-27587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27587}: Fix another issue found by PVS-Studio: Null pointer check after
use of 'def' in _PyState_AddModule(). Initial patch by Christian Heimes.

@item 
bpo-26020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26020}: set literal evaluation order did not match documented
behaviour.

@item 
bpo-27782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27782}: Multi-phase extension module import now correctly allows the
@code{m_methods} field to be used to add module level functions to instances
of non-module types returned from @code{Py_create_mod}. Patch by Xiang Zhang.

@item 
bpo-27936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27936}: The round() function accepted a second None argument for some
types but not for others.  Fixed the inconsistency by accepting None for
all numeric types.

@item 
bpo-27487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27487}: Warn if a submodule argument to "python -m" or
runpy.run_module() is found in sys.modules after parent packages are
imported, but before the submodule is executed.

@item 
bpo-27558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27558}: Fix a SystemError in the implementation of "raise" statement.
In a brand new thread, raise a RuntimeError since there is no active
exception to reraise. Patch written by Xiang Zhang.

@item 
bpo-27419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27419}: Standard __import__() no longer look up "__import__" in globals
or builtins for importing submodules or "from import".  Fixed handling an
error of non-string package name.

@item 
bpo-27083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27083}: Respect the PYTHONCASEOK environment variable under Windows.

@item 
bpo-27514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27514}: Make having too many statically nested blocks a SyntaxError
instead of SystemError.

@item 
bpo-27473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27473}: Fixed possible integer overflow in bytes and bytearray
concatenations. Patch by Xiang Zhang.

@item 
bpo-27507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27507}: Add integer overflow check in bytearray.extend().  Patch by
Xiang Zhang.

@item 
bpo-27581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27581}: Don't rely on wrapping for overflow check in
PySequence_Tuple().  Patch by Xiang Zhang.

@item 
bpo-27443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27443}: __length_hint__() of bytearray iterators no longer return a
negative integer for a resized bytearray.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: Fix memory leak in codeobject.c
@end itemize

@node ライブラリ<193>,IDLE<57>,Core and Builtins<189>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id988}@anchor{1f55}
@subsubsection ライブラリ



@itemize -

@item 
bpo-15812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15812}: inspect.getframeinfo() now correctly shows the first line of a
context. Patch by Sam Breese.

@item 
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094}: Offsets in a ZIP file created with extern file object and modes
"w" and "x" now are relative to the start of the file.

@item 
bpo-13051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13051}: Fixed recursion errors in large or resized
curses.textpad.Textbox.  Based on patch by Tycho Andersen.

@item 
bpo-29119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29119}: Fix weakrefs in the pure python version of
collections.OrderedDict move_to_end() method. Contributed by Andra
Bogildea.

@item 
bpo-9770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9770}: curses.ascii predicates now work correctly with negative
integers.

@item 
bpo-28427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28427}: old keys should not remove new values from WeakValueDictionary
when collecting from another thread.

@item 
bpo-28923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28923}: Remove editor artifacts from Tix.py.

@item 
bpo-28871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28871}: Fixed a crash when deallocate deep ElementTree.

@item 
bpo-19542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19542}: Fix bugs in WeakValueDictionary.setdefault() and
WeakValueDictionary.pop() when a GC collection happens in another thread.

@item 
bpo-20191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20191}: Fixed a crash in resource.prlimit() when pass a sequence that
doesn't own its elements as limits.

@item 
bpo-28779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28779}: multiprocessing.set_forkserver_preload() would crash the
forkserver process if a preloaded module instantiated some multiprocessing
objects such as locks.

@item 
bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847}: dbm.dumb now supports reading read-only files and no longer
writes the index file when it is not changed.

@item 
bpo-25659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25659}: In ctypes, prevent a crash calling the from_buffer() and
from_buffer_copy() methods on abstract classes like Array.

@item 
bpo-28732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28732}: Fix crash in os.spawnv() with no elements in args

@item 
bpo-28485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28485}: Always raise ValueError for negative
compileall.compile_dir(workers=...) parameter, even when multithreading is
unavailable.

@item 
bpo-28387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28387}: Fixed possible crash in _io.TextIOWrapper deallocator when the
garbage collector is invoked in other thread.  Based on patch by Sebastian
Cufre.

@item 
bpo-27517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27517}: LZMA compressor and decompressor no longer raise exceptions if
given empty data twice.  Patch by Benjamin Fogle.

@item 
bpo-28549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28549}: Fixed segfault in curses's addch() with ncurses6.

@item 
bpo-28449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28449}: tarfile.open() with mode "r" or "r:" now tries to open a tar
file with compression before trying to open it without compression.
Otherwise it had 50% chance failed with ignore_zeros=True.

@item 
bpo-23262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23262}: The webbrowser module now supports Firefox 36+ and derived
browsers.  Based on patch by Oleg Broytman.

@item 
bpo-27939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27939}: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused
by representing the scale as float value internally in Tk.  tkinter.IntVar
now works if float value is set to underlying Tk variable.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar().prmonth() no longer prints a space at
the start of new line after printing a month's calendar.  Patch by Xiang
Zhang.

@item 
bpo-20491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20491}: The textwrap.TextWrapper class now honors non-breaking spaces.
Based on patch by Kaarle Ritvanen.

@item 
bpo-28353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28353}: os.fwalk() no longer fails on broken links.

@item 
bpo-25464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25464}: Fixed HList.header_exists() in tkinter.tix module by addin a
workaround to Tix library bug.

@item 
bpo-28488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28488}: shutil.make_archive() no longer add entry "./" to ZIP archive.

@item 
bpo-24452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24452}: Make webbrowser support Chrome on Mac OS X.

@item 
bpo-20766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20766}: Fix references leaked by pdb in the handling of SIGINT
handlers.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Fixed writing ZIP files that starts not from the start of the
file.  Offsets in ZIP file now are relative to the start of the archive in
conforming to the specification.

@item 
bpo-28321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28321}: Fixed writing non-BMP characters with binary format in
plistlib.

@item 
bpo-28322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28322}: Fixed possible crashes when unpickle itertools objects from
incorrect pickle data.  Based on patch by John Leitch.

@item 
Fix possible integer overflows and crashes in the mmap module with unusual
usage patterns.

@item 
bpo-1703178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1703178}: Fix the ability to pass the --link-objects option to the
distutils build_ext command.

@item 
bpo-28253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28253}: Fixed calendar functions for extreme months: 0001-01 and
9999-12. Methods itermonthdays() and itermonthdays2() are reimplemented so
that they don't call itermonthdates() which can cause datetime.date
under/overflow.

@item 
bpo-28275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28275}: Fixed possible use after free in the decompress() methods of
the LZMADecompressor and BZ2Decompressor classes. Original patch by John
Leitch.

@item 
bpo-27897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27897}: Fixed possible crash in sqlite3.Connection.create_collation()
if pass invalid string-like object as a name.  Patch by Xiang Zhang.

@item 
bpo-18893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18893}: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py.
Patch by Madison May.

@item 
bpo-27611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27611}: Fixed support of default root window in the tkinter.tix module.

@item 
bpo-27348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27348}: In the traceback module, restore the formatting of exception
messages like "Exception: None".  This fixes a regression introduced in
3.5a2.

@item 
bpo-25651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25651}: Allow false values to be used for msg parameter of subTest().

@item 
bpo-27932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}: Prevent memory leak in win32_ver().

@item 
Fix UnboundLocalError in socket._sendfile_use_sendfile.

@item 
bpo-28075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28075}: Check for ERROR_ACCESS_DENIED in Windows implementation of
os.stat().  Patch by Eryk Sun.

@item 
bpo-25270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25270}: Prevent codecs.escape_encode() from raising SystemError when an
empty bytestring is passed.

@item 
bpo-28181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28181}: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

@item 
bpo-25895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25895}: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by
Gergely Imreh and Markus Holtermann.

@item 
bpo-27599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27599}: Fixed buffer overrun in binascii.b2a_qp() and
binascii.a2b_qp().

@item 
bpo-19003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19003}: m email.generator now replaces only @code{\r} and/or @code{\n} line
endings, per the RFC, instead of all unicode line endings.

@item 
bpo-28019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28019}: itertools.count() no longer rounds non-integer step in range
between 1.0 and 2.0 to 1.

@item 
bpo-25969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25969}: Update the lib2to3 grammar to handle the unpacking
generalizations added in 3.5.

@item 
bpo-14977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14977}: mailcap now respects the order of the lines in the mailcap
files ("first match"), as required by RFC 1542.  Patch by Michael Lazar.

@item 
bpo-24594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24594}: Validates persist parameter when opening MSI database

@item 
bpo-17582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17582}: xml.etree.ElementTree nows preserves whitespaces in attributes
(Patch by Duane Griffin.  Reviewed and approved by Stefan Behnel.)

@item 
bpo-28047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28047}: Fixed calculation of line length used for the base64 CTE in the
new email policies.

@item 
bpo-27445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27445}: Don't pass str(_charset) to MIMEText.set_payload(). Patch by
Claude Paroz.

@item 
bpo-22450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22450}: urllib now includes an @code{Accept: */*} header among the default
headers. This makes the results of REST API requests more consistent and
predictable especially when proxy servers are involved.

@item 
lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
between runs given the same Grammar.txt input regardless of the hash
randomization setting.

@item 
bpo-27570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27570}: Avoid zero-length memcpy() etc calls with null source pointers
in the "ctypes" and "array" modules.

@item 
bpo-22233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22233}: Break email header lines `only' on the RFC specified CR and LF
characters, not on arbitrary unicode line breaks.  This also fixes a bug
in HTTP header parsing.

@item 
bpo-27988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27988}: Fix email iter_attachments incorrect mutation of payload list.

@item 
bpo-27691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27691}: Fix ssl module's parsing of GEN_RID subject alternative name
fields in X.509 certs.

@item 
bpo-27850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27850}: Remove 3DES from ssl module's default cipher list to counter
measure sweet32 attack (
@geindex Common Vulnerabilities and Exposures; CVE 2016-2183
CVE 2016-2183@footnote{https://www.cve.org/CVERecord?id=CVE-2016-2183}).

@item 
bpo-27766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27766}: Add ChaCha20 Poly1305 to ssl module's default cipher list.
(Required OpenSSL 1.1.0 or LibreSSL).

@item 
bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}: Port ssl and hashlib module to OpenSSL 1.1.0.

@item 
Remove support for passing a file descriptor to os.access. It never worked
but previously didn't raise.

@item 
bpo-12885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12885}: Fix error when distutils encounters symlink.

@item 
bpo-27881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27881}: Fixed possible bugs when setting
sqlite3.Connection.isolation_level. Based on patch by Xiang Zhang.

@item 
bpo-27861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27861}: Fixed a crash in sqlite3.Connection.cursor() when a factory
creates not a cursor.  Patch by Xiang Zhang.

@item 
bpo-19884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19884}: Avoid spurious output on OS X with Gnu Readline.

@item 
bpo-27706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27706}: Restore deterministic behavior of random.Random().seed() for
string seeds using seeding version 1.  Allows sequences of calls to
random() to exactly match those obtained in Python 2. Patch by Nofar
Schnider.

@item 
bpo-10513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10513}: Fix a regression in Connection.commit().  Statements should not
be reset after a commit.

@item 
A new version of typing.py from @indicateurl{https://github.com/python/typing}:
Collection (only for 3.6) (bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}). Add FrozenSet to __all__
(upstream #261). Fix crash in _get_type_vars() (upstream #259). Remove the
dict constraint in ForwardRef._eval_type (upstream #252).

@item 
bpo-27539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27539}: Fix unnormalised @code{Fraction.__pow__} result in the case of
negative exponent and negative base.

@item 
bpo-21718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21718}: cursor.description is now available for queries using CTEs.

@item 
bpo-2466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2466}: posixpath.ismount now correctly recognizes mount points which
the user does not have permission to access.

@item 
bpo-27773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27773}: Correct some memory management errors server_hostname in
_ssl.wrap_socket().

@item 
bpo-26750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26750}: unittest.mock.create_autospec() now works properly for
subclasses of property() and other data descriptors.

@item 
In the curses module, raise an error if window.getstr() or window.instr()
is passed a negative value.

@item 
bpo-27783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27783}: Fix possible usage of uninitialized memory in
operator.methodcaller.

@item 
bpo-27774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27774}: Fix possible Py_DECREF on unowned object in _sre.

@item 
bpo-27760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27760}: Fix possible integer overflow in binascii.b2a_qp.

@item 
bpo-27758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27758}: Fix possible integer overflow in the _csv module for large
record lengths.

@item 
bpo-27568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27568}: Prevent HTTPoxy attack (
@geindex Common Vulnerabilities and Exposures; CVE 2016-1000110
CVE 2016-1000110@footnote{https://www.cve.org/CVERecord?id=CVE-2016-1000110}). Ignore the
HTTP_PROXY variable when REQUEST_METHOD environment is set, which
indicates that the script is in CGI mode.

@item 
bpo-27656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27656}: Do not assume sched.h defines any SCHED_* constants.

@item 
bpo-27130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27130}: In the "zlib" module, fix handling of large buffers (typically
4 GiB) when compressing and decompressing.  Previously, inputs were
limited to 4 GiB, and compression and decompression operations did not
properly handle results of 4 GiB.

@item 
bpo-27533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27533}: Release GIL in nt._isdir

@item 
bpo-17711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17711}: Fixed unpickling by the persistent ID with protocol 0. Original
patch by Alexandre Vassalotti.

@item 
bpo-27522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27522}: Avoid an unintentional reference cycle in email.feedparser.

@item 
bpo-26844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26844}: Fix error message for imp.find_module() to refer to 'path'
instead of 'name'. Patch by Lev Maximov.

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL zero-length recv() calls to not block and not raise an
error about unclean EOF.

@item 
bpo-27466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27466}: Change time format returned by http.cookie.time2netscape,
confirming the netscape cookie format and making it consistent with
documentation.

@item 
bpo-26664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26664}: Fix activate.fish by removing mis-use of @code{$}.

@item 
bpo-22115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22115}: Fixed tracing Tkinter variables: trace_vdelete() with wrong
mode no longer break tracing, trace_vinfo() now always returns a list of
pairs of strings, tracing in the "u" mode now works.

@item 
Fix a scoping issue in importlib.util.LazyLoader which triggered an
UnboundLocalError when lazy-loading a module that was already put into
sys.modules.

@item 
bpo-27079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27079}: Fixed curses.ascii functions isblank(), iscntrl() and
ispunct().

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: Some functions (compile() etc) accepted a filename argument
encoded as an iterable of integers. Now only strings and byte-like objects
are accepted.

@item 
bpo-27048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27048}: Prevents distutils failing on Windows when environment
variables contain non-ASCII characters

@item 
bpo-27330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27330}: Fixed possible leaks in the ctypes module.

@item 
bpo-27238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27238}: Got rid of bare excepts in the turtle module.  Original patch
by Jelle Zijlstra.

@item 
bpo-27122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27122}: When an exception is raised within the context being managed by
a contextlib.ExitStack() and one of the exit stack generators catches and
raises it in a chain, do not re-raise the original exception when exiting,
let the new chained one through.  This avoids the 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/} bug described
in issue25782.

@item 
bpo-26386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26386}: Fixed ttk.TreeView selection operations with item id's
containing spaces.

@item 
bpo-16182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16182}: Fix various functions in the "readline" module to use the
locale encoding, and fix get_begidx() and get_endidx() to return code
point indexes.

@item 
bpo-27392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27392}: Add loop.connect_accepted_socket(). Patch by Jim Fulton.

@item 
bpo-27930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27930}: Improved behaviour of logging.handlers.QueueListener. Thanks to
Paulo Andrade and Petr Viktorin for the analysis and patch.

@item 
bpo-21201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21201}: Improves readability of multiprocessing error message.  Thanks
to Wojciech Walczak for patch.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: asyncio: Set TCP_NODELAY by default.

@item 
bpo-27906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27906}: Fix socket accept exhaustion during high TCP traffic. Patch by
Kevin Conway.

@item 
bpo-28174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28174}: Handle when SO_REUSEPORT isn't properly supported. Patch by
Seth Michael Larson.

@item 
bpo-26654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26654}: Inspect functools.partial in asyncio.Handle.__repr__. Patch by
iceboy.

@item 
bpo-26909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26909}: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

@item 
bpo-28176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28176}: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

@item 
bpo-27759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27759}: Fix selectors incorrectly retain invalid file descriptors.
Patch by Mark Williams.

@item 
bpo-28368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28368}: Refuse monitoring processes if the child watcher has no loop
attached. Patch by Vincent Michel.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Raise RuntimeError when transport's FD is used with add_reader,
add_writer, etc.

@item 
bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг
Марк.

@item 
bpo-28371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28371}: Deprecate passing asyncio.Handles to run_in_executor.

@item 
bpo-28372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28372}: Fix asyncio to support formatting of non-python coroutines.

@item 
bpo-28399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28399}: Remove UNIX socket from FS before binding. Patch by Коренберг
Марк.

@item 
bpo-27972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27972}: Prohibit Tasks to await on themselves.

@item 
bpo-26923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26923}: Fix asyncio.Gather to refuse being cancelled once all children
are done. Patch by Johannes Ebke.

@item 
bpo-26796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26796}: Don't configure the number of workers for default threadpool
executor. Initial patch by Hans Lawrenz.

@item 
bpo-28600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28600}: Optimize loop.call_soon().

@item 
bpo-28613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28613}: Fix get_event_loop() return the current loop if called from
coroutines/callbacks.

@item 
bpo-28639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28639}: Fix inspect.isawaitable to always return bool Patch by Justin
Mayfield.

@item 
bpo-28652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28652}: Make loop methods reject socket kinds they do not support.

@item 
bpo-28653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28653}: Fix a refleak in functools.lru_cache.

@item 
bpo-28703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28703}: Fix asyncio.iscoroutinefunction to handle Mock objects.

@item 
bpo-24142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24142}: Reading a corrupt config file left the parser in an invalid
state.  Original patch by Florian Höch.

@item 
bpo-28990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28990}: Fix SSL hanging if connection is closed before handshake
completed. (Patch by HoHo-Ho)
@end itemize

@node IDLE<57>,C API<76>,ライブラリ<193>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id989}@anchor{1f56}
@subsubsection IDLE



@itemize -

@item 
bpo-15308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15308}: Add 'interrupt execution' (^C) to Shell menu. Patch by Roger
Serwy, updated by Bayard Randel.

@item 
bpo-27922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27922}: Stop IDLE tests from 'flashing' gui widgets on the screen.

@item 
Add version to title of IDLE help window.

@item 
bpo-25564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25564}: In section on IDLE -- console differences, mention that using
exec means that __builtins__ is defined for each statement.

@item 
bpo-27714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27714}: text_textview and test_autocomplete now pass when re-run in the
same process.  This occurs when test_idle fails when run with the -w
option but without -jn.  Fix warning from test_config.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: IDLE no longer runs buggy code because of its tkinter imports.
Users must include the same imports required to run directly in Python.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: add line counter and crc to IDLE configHandler test dump.

@item 
bpo-27365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27365}: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.

@item 
bpo-27245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27245}: IDLE: Cleanly delete custom themes and key bindings.
Previously, when IDLE was started from a console or by import, a cascade
of warnings was emitted. Patch by Serhiy Storchaka.
@end itemize

@node C API<76>,ドキュメント<79>,IDLE<57>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id990}@anchor{1f57}
@subsubsection C API



@itemize -

@item 
bpo-28808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28808}: PyUnicode_CompareWithASCIIString() now never raises exceptions.

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: PyUnicode_FSDecoder() accepted a filename argument encoded as
an iterable of integers. Now only strings and bytes-like objects are
accepted.
@end itemize

@node ドキュメント<79>,テスト<79>,C API<76>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id991}@anchor{1f58}
@subsubsection ドキュメント



@itemize -

@item 
bpo-28513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28513}: Documented command-line interface of zipfile.
@end itemize

@node テスト<79>,Tools/Demos<55>,ドキュメント<79>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id992}@anchor{1f59}
@subsubsection テスト



@itemize -

@item 
bpo-28950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28950}: Disallow -j0 to be combined with -T/-l/-M in regrtest command
line arguments.

@item 
bpo-28666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28666}: Now test.support.rmtree is able to remove unwritable or
unreadable directories.

@item 
bpo-23839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23839}: Various caches now are cleared before running every test file.

@item 
bpo-28409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28409}: regrtest: fix the parser of command line arguments.

@item 
bpo-27787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27787}: Call gc.collect() before checking each test for "dangling
threads", since the dangling threads are weak references.

@item 
bpo-27369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27369}: In test_pyexpat, avoid testing an error message detail that
changed in Expat 2.2.0.
@end itemize

@node Tools/Demos<55>,Windows<78>,テスト<79>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id993}@anchor{1f5a}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-27952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27952}: Get Tools/scripts/fixcid.py working with Python 3 and the
current "re" module, avoid invalid Python backslash escapes, and fix a bug
parsing escaped C quote signs.

@item 
bpo-27332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27332}: Fixed the type of the first argument of module-level functions
generated by Argument Clinic.  Patch by Petr Viktorin.

@item 
bpo-27418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27418}: Fixed Tools/importbench/importbench.py.
@end itemize

@node Windows<78>,ビルド<90>,Tools/Demos<55>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id994}@anchor{1f5b}
@subsubsection Windows



@itemize -

@item 
bpo-28251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28251}: Improvements to help manuals on Windows.

@item 
bpo-28110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28110}: launcher.msi has different product codes between 32-bit and
64-bit

@item 
bpo-25144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25144}: Ensures TargetDir is set before continuing with custom install.

@item 
bpo-27469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27469}: Adds a shell extension to the launcher so that drag and drop
works correctly.

@item 
bpo-27309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27309}: Enabled proper Windows styles in python[w].exe manifest.
@end itemize

@node ビルド<90>,,Windows<78>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id995}@anchor{1f5c}
@subsubsection ビルド



@itemize -

@item 
bpo-29080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29080}: Removes hard dependency on hg.exe from PCBuild/build.bat

@item 
bpo-23903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23903}: Added missed names to PC/python3.def.

@item 
bpo-10656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10656}: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
Michael Haubenwallner.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Rename --with-optimiations to --enable-optimizations.

@item 
bpo-28444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28444}: Fix missing extensions modules when cross compiling.

@item 
bpo-28248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28248}: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

@item 
bpo-28258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28258}: Fixed build with Estonian locale (python-config and distclean
targets in Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-26661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26661}: setup.py now detects system libffi with multiarch wrapper.

@item 
bpo-28066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28066}: Fix the logic that searches build directories for generated
include files when building outside the source tree.

@item 
bpo-15819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15819}: Remove redundant include search directory option for building
outside the source tree.

@item 
bpo-27566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27566}: Fix clean target in freeze makefile (patch by Lisa Roach)

@item 
bpo-27705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27705}: Update message in validate_ucrtbase.py

@item 
bpo-27983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27983}: Cause lack of llvm-profdata tool when using clang as required
for PGO linking to be a configure time error rather than make time when
--with-optimizations is enabled.  Also improve our ability to find the
llvm-profdata tool on MacOS and some Linuxes.

@item 
bpo-26307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26307}: The profile-opt build now applies PGO to the built-in modules.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Add the --with-optimizations configure flag.

@item 
bpo-27713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27713}: Suppress spurious build warnings when updating importlib's
bootstrap files. Patch by Xiang Zhang

@item 
bpo-25825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25825}: Correct the references to Modules/python.exp and ld_so_aix,
which are required on AIX.  This updates references to an installation
path that was changed in 3.2a4, and undoes changed references to the build
tree that were made in 3.5.0a1.

@item 
bpo-27453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27453}: CPP invocation in configure must use CPPFLAGS. Patch by Chi
Hsuan Yen.

@item 
bpo-27641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27641}: The configure script now inserts comments into the makefile to
prevent the pgen and _freeze_importlib executables from being
cross-compiled.

@item 
bpo-26662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26662}: Set PYTHON_FOR_GEN in configure as the Python program to be
used for file generation during the build.

@item 
bpo-10910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10910}: Avoid C++ compilation errors on FreeBSD and OS X. Also update
FreedBSD version checks for the original ctype UTF-8 workaround.

@item 
bpo-28676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28676}: Prevent missing 'getentropy' declaration warning on macOS.
Patch by Gareth Rees.
@end itemize

@node Python 3 5 2 final,Python 3 5 2 release candidate 1,Python 3 5 3 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-5-2-final}@anchor{1f5d}
@subsection Python 3.5.2 final


`Release date: 2016-06-26'

@menu
* Core and Builtins: Core and Builtins<190>. 
* テスト: テスト<80>. 
* IDLE: IDLE<58>. 

@end menu

@node Core and Builtins<190>,テスト<80>,,Python 3 5 2 final
@anchor{whatsnew/changelog id996}@anchor{1f5e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update Windows builds to use OpenSSL 1.0.2h.
@end itemize

@node テスト<80>,IDLE<58>,Core and Builtins<190>,Python 3 5 2 final
@anchor{whatsnew/changelog id997}@anchor{1f5f}
@subsubsection テスト



@itemize -

@item 
bpo-26867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26867}: Ubuntu's openssl OP_NO_SSLv3 is forced on by default; fix test.
@end itemize

@node IDLE<58>,,テスト<80>,Python 3 5 2 final
@anchor{whatsnew/changelog id998}@anchor{1f60}
@subsubsection IDLE



@itemize -

@item 
bpo-27365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27365}: Allow non-ascii in idlelib/NEWS.txt - minimal part for 3.5.2.
@end itemize

@node Python 3 5 2 release candidate 1,Python 3 5 1 final,Python 3 5 2 final,変更履歴
@anchor{whatsnew/changelog python-3-5-2-release-candidate-1}@anchor{1f61}
@subsection Python 3.5.2 release candidate 1


`Release date: 2016-06-12'

@menu
* セキュリティ: セキュリティ<60>. 
* Core and Builtins: Core and Builtins<191>. 
* ライブラリ: ライブラリ<194>. 
* IDLE: IDLE<59>. 
* ドキュメント: ドキュメント<80>. 
* テスト: テスト<81>. 
* ビルド: ビルド<91>. 
* Windows: Windows<79>. 
* Tools/Demos: Tools/Demos<56>. 

@end menu

@node セキュリティ<60>,Core and Builtins<191>,,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id999}@anchor{1f62}
@subsubsection セキュリティ



@itemize -

@item 
bpo-26556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26556}: Update expat to 2.1.1, fixes 
@geindex Common Vulnerabilities and Exposures; CVE 2015-1283
CVE 2015-1283@footnote{https://www.cve.org/CVERecord?id=CVE-2015-1283}.

@item 
Fix TLS stripping vulnerability in smtplib, 
@geindex Common Vulnerabilities and Exposures; CVE 2016-0772
CVE 2016-0772@footnote{https://www.cve.org/CVERecord?id=CVE-2016-0772}. Reported by
Team Oststrom.

@item 
bpo-26839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26839}: On Linux, @ref{746,,os.urandom()} now calls @code{getrandom()} with
@code{GRND_NONBLOCK} to fall back on reading @code{/dev/urandom} if the urandom
entropy pool is not initialized yet. Patch written by Colm Buckley.

@item 
bpo-26657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26657}: Fix directory traversal vulnerability with http.server on
Windows.  This fixes a regression that was introduced in 3.3.4rc1 and
3.4.0rc1.  Based on patch by Philipp Hagemeister.

@item 
bpo-26313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26313}: ssl.py _load_windows_store_certs fails if windows cert store is
empty. Patch by Baji.

@item 
bpo-25939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25939}: On Windows open the cert store readonly in
ssl.enum_certificates.
@end itemize

@node Core and Builtins<191>,ライブラリ<194>,セキュリティ<60>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1000}@anchor{1f63}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27066}: Fixed SystemError if a custom opener (for open()) returns a
negative number without setting an exception.

@item 
bpo-20041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20041}: Fixed TypeError when frame.f_trace is set to None. Patch by
Xavier de Gaye.

@item 
bpo-26168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26168}: Fixed possible refleaks in failing Py_BuildValue() with the "N"
format unit.

@item 
bpo-26991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26991}: Fix possible refleak when creating a function with annotations.

@item 
bpo-27039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27039}: Fixed bytearray.remove() for values greater than 127.  Patch by
Joe Jevnik.

@item 
bpo-23640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23640}: int.from_bytes() no longer bypasses constructors for
subclasses.

@item 
bpo-26811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26811}: gc.get_objects() no longer contains a broken tuple with NULL
pointer.

@item 
bpo-20120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20120}: Use RawConfigParser for .pypirc parsing, removing support for
interpolation unintentionally added with move to Python 3. Behavior no
longer does any interpolation in .pypirc files, matching behavior in
Python 2.7 and Setuptools 19.0.

@item 
bpo-26659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26659}: Make the builtin slice type support cycle collection.

@item 
bpo-26718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26718}: super.__init__ no longer leaks memory if called multiple times.
NOTE: A direct call of super.__init__ is not endorsed!

@item 
bpo-25339@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25339}: PYTHONIOENCODING now has priority over locale in setting the
error handler for stdin and stdout.

@item 
bpo-26494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26494}: Fixed crash on iterating exhausting iterators. Affected classes
are generic sequence iterators, iterators of str, bytes, bytearray, list,
tuple, set, frozenset, dict, OrderedDict, corresponding views and
os.scandir() iterator.

@item 
bpo-26581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26581}: If coding cookie is specified multiple times on a line in
Python source code file, only the first one is taken to account.

@item 
bpo-26464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26464}: Fix str.translate() when string is ASCII and first replacements
removes character, but next replacement uses a non-ASCII character or a
string longer than 1 character. Regression introduced in Python 3.5.0.

@item 
bpo-22836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22836}: Ensure exception reports from PyErr_Display() and
PyErr_WriteUnraisable() are sensible even when formatting them produces
secondary errors.  This affects the reports produced by
sys.__excepthook__() and when __del__() raises an exception.

@item 
bpo-26302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26302}: Correct behavior to reject comma as a legal character for
cookie names.

@item 
bpo-4806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4806}: Avoid masking the original TypeError exception when using star
(@code{*}) unpacking in function calls.  Based on patch by Hagen Fürstenau
and Daniel Urban.

@item 
bpo-27138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27138}: Fix the doc comment for FileFinder.find_spec().

@item 
bpo-26154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26154}: Add a new private _PyThreadState_UncheckedGet() function to get
the current Python thread state, but don't issue a fatal error if it is
NULL. This new function must be used instead of accessing directly the
_PyThreadState_Current variable.  The variable is no more exposed since
Python 3.5.1 to hide the exact implementation of atomic C types, to avoid
compiler issues.

@item 
bpo-26194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26194}: Deque.insert() gave odd results for bounded deques that had
reached their maximum size.  Now an IndexError will be raised when
attempting to insert into a full deque.

@item 
bpo-25843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25843}: When compiling code, don't merge constants if they are equal
but have a different types. For example, @code{f1, f2 = lambda: 1, lambda:
1.0} is now correctly compiled to two different functions: @code{f1()}
returns @code{1} (@code{int}) and @code{f2()} returns @code{1.0} (@code{int}), even if
@code{1} and @code{1.0} are equal.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: [UPDATE] Comment out the one of the pickleability tests in
_PyObject_GetState() due to regressions observed in Cython-based projects.

@item 
bpo-25961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25961}: Disallowed null characters in the type name.

@item 
bpo-25973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25973}: Fix segfault when an invalid nonlocal statement binds a name
starting with two underscores.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Instances of extension types with a state that aren't
subclasses of list or dict and haven't implemented any pickle-related
methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, or
__getstate__), can no longer be pickled.  Including memoryview.

@item 
bpo-20440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20440}: Massive replacing unsafe attribute setting code with special
macro Py_SETREF.

@item 
bpo-25766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25766}: Special method __bytes__() now works in str subclasses.

@item 
bpo-25421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25421}: __sizeof__ methods of builtin types now use dynamic basic size.
This allows sys.getsize() to work correctly with their subclasses with
__slots__ defined.

@item 
bpo-25709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25709}: Fixed problem with in-place string concatenation and utf-8
cache.

@item 
bpo-27147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27147}: Mention 
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} in the importlib docs.

@item 
bpo-24097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24097}: Fixed crash in object.__reduce__() if slot name is freed inside
__getattr__.

@item 
bpo-24731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24731}: Fixed crash on converting objects with special methods
__bytes__, __trunc__, and __float__ returning instances of subclasses of
bytes, int, and float to subclasses of bytes, int, and float
correspondingly.

@item 
bpo-26478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26478}: Fix semantic bugs when using binary operators with dictionary
views and tuples.

@item 
bpo-26171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26171}: Fix possible integer overflow and heap corruption in
zipimporter.get_data().

@item 
bpo-25660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25660}: Fix TAB key behaviour in REPL with readline.

@item 
bpo-25887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25887}: Raise a RuntimeError when a coroutine object is awaited more
than once.

@item 
bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}: Update the __aiter__ protocol: instead of returning an
awaitable that resolves to an asynchronous iterator, the asynchronous
iterator should be returned directly.  Doing the former will trigger a
PendingDeprecationWarning.
@end itemize

@node ライブラリ<194>,IDLE<59>,Core and Builtins<191>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1001}@anchor{1f64}
@subsubsection ライブラリ



@itemize -

@item 
bpo-21386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21386}: Implement missing IPv4Address.is_global property.  It was
documented since 07a5610bae9d.  Initial patch by Roger Luethi.

@item 
bpo-20900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20900}: distutils register command now decodes HTTP responses
correctly.  Initial patch by ingrid.

@item 
A new version of typing.py provides several new classes and features:
@@overload outside stubs, Reversible, DefaultDict, Text, ContextManager,
Type[], NewType(), TYPE_CHECKING, and numerous bug fixes (note that some
of the new features are not yet implemented in mypy or other static
analyzers). Also classes for 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} (Awaitable, AsyncIterable,
AsyncIterator) have been added (in fact they made it into 3.5.1 but were
never mentioned).

@item 
bpo-25738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25738}: Stop http.server.BaseHTTPRequestHandler.send_error() from
sending a message body for 205 Reset Content.  Also, don't send Content
header fields in responses that don't have a body.  Patch by Susumu
Koshiba.

@item 
bpo-21313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21313}: Fix the "platform" module to tolerate when sys.version contains
truncated build information.

@item 
bpo-27164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27164}: In the zlib module, allow decompressing raw Deflate streams
with a predefined zdict.  Based on patch by Xiang Zhang.

@item 
bpo-24291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24291}: Fix wsgiref.simple_server.WSGIRequestHandler to completely
write data to the client.  Previously it could do partial writes and
truncate data.  Also, wsgiref.handler.ServerHandler can now handle stdout
doing partial writes, but this is deprecated.

@item 
bpo-26809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26809}: Add @code{__all__} to @ref{d8,,string}.  Patch by Emanuel Barry.

@item 
bpo-26373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26373}: subprocess.Popen.communicate now correctly ignores
BrokenPipeError when the child process dies before .communicate() is
called in more/all circumstances.

@item 
bpo-21776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21776}: distutils.upload now correctly handles HTTPError. Initial patch
by Claudiu Popa.

@item 
bpo-27114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27114}: Fix SSLContext._load_windows_store_certs fails with
PermissionError

@item 
bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: Avoid creating duplicate filters when using filterwarnings and
simplefilter. Based on patch by Alex Shkop.

@item 
bpo-27057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27057}: Fix os.set_inheritable() on Android, ioctl() is blocked by
SELinux and fails with EACCESS. The function now falls back to fcntl().
Patch written by Michał Bednarski.

@item 
bpo-27014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27014}: Fix infinite recursion using typing.py.  Thanks to Kalle Tuure!

@item 
bpo-14132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14132}: Fix urllib.request redirect handling when the target only has a
query string.  Original fix by Ján Janech.

@item 
bpo-17214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17214}: The "urllib.request" module now percent-encodes non-ASCII bytes
found in redirect target URLs.  Some servers send Location header fields
with non-ASCII bytes, but "http.client" requires the request target to be
ASCII-encodable, otherwise a UnicodeEncodeError is raised.  Based on patch
by Christian Heimes.

@item 
bpo-26892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26892}: Honor debuglevel flag in urllib.request.HTTPHandler. Patch
contributed by Chi Hsuan Yen.

@item 
bpo-22274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22274}: In the subprocess module, allow stderr to be redirected to
stdout even when stdout is not redirected.  Patch by Akira Li.

@item 
bpo-26807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26807}: mock_open 'files' no longer error on readline at end of file.
Patch from Yolanda Robla.

@item 
bpo-25745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25745}: Fixed leaking a userptr in curses panel destructor.

@item 
bpo-26977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26977}: Removed unnecessary, and ignored, call to sum of squares helper
in statistics.pvariance.

@item 
bpo-26881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26881}: The modulefinder module now supports extended opcode arguments.

@item 
bpo-23815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23815}: Fixed crashes related to directly created instances of types in
_tkinter and curses.panel modules.

@item 
bpo-17765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17765}: weakref.ref() no longer silently ignores keyword arguments.
Patch by Georg Brandl.

@item 
bpo-26873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26873}: xmlrpc now raises ResponseError on unsupported type tags
instead of silently return incorrect result.

@item 
bpo-26711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26711}: Fixed the comparison of plistlib.Data with other types.

@item 
bpo-24114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24114}: Fix an uninitialized variable in @code{ctypes.util}. The bug only
occurs on SunOS when the ctypes implementation searches for the @code{crle}
program. Patch by Xiang Zhang.  Tested on SunOS by Kees Bos.

@item 
bpo-26864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26864}: In urllib.request, change the proxy bypass host checking
against no_proxy to be case-insensitive, and to not match unrelated host
names that happen to have a bypassed hostname as a suffix.  Patch by Xiang
Zhang.

@item 
bpo-26634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26634}: recursive_repr() now sets __qualname__ of wrapper.  Patch by
Xiang Zhang.

@item 
bpo-26804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26804}: urllib.request will prefer lower_case proxy environment
variables over UPPER_CASE or Mixed_Case ones. Patch contributed by
Hans-Peter Jansen.

@item 
bpo-26837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26837}: assertSequenceEqual() now correctly outputs non-stringified
differing items (like bytes in the -b mode).  This affects
assertListEqual() and assertTupleEqual().

@item 
bpo-26041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26041}: Remove "will be removed in Python 3.7" from deprecation
messages of platform.dist() and platform.linux_distribution(). Patch by
Kumaripaba Miyurusara Athukorala.

@item 
bpo-26822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26822}: itemgetter, attrgetter and methodcaller objects no longer
silently ignore keyword arguments.

@item 
bpo-26733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26733}: Disassembling a class now disassembles class and static
methods. Patch by Xiang Zhang.

@item 
bpo-26801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26801}: Fix error handling in @ref{131b,,shutil.get_terminal_size()}, catch
@ref{5f0,,AttributeError} instead of @ref{452,,NameError}. Patch written by
Emanuel Barry.

@item 
bpo-24838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24838}: tarfile's ustar and gnu formats now correctly calculate name
and link field limits for multibyte character encodings like utf-8.

@item 
bpo-26717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26717}: Stop encoding Latin-1-ized WSGI paths with UTF-8.  Patch by
Anthony Sottile.

@item 
bpo-26735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26735}: Fix @ref{746,,os.urandom()} on Solaris 11.3 and newer when reading
more than 1,024 bytes: call @code{getrandom()} multiple times with a limit of
1024 bytes per call.

@item 
bpo-16329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16329}: Add .webm to mimetypes.types_map.  Patch by Giampaolo Rodola'.

@item 
bpo-13952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13952}: Add .csv to mimetypes.types_map.  Patch by Geoff Wilson.

@item 
bpo-26709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26709}: Fixed Y2038 problem in loading binary PLists.

@item 
bpo-23735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23735}: Handle terminal resizing with Readline 6.3+ by installing our
own SIGWINCH handler.  Patch by Eric Price.

@item 
bpo-26586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26586}: In http.server, respond with "413 Request header fields too
large" if there are too many header fields to parse, rather than killing
the connection and raising an unhandled exception.  Patch by Xiang Zhang.

@item 
bpo-22854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22854}: Change BufferedReader.writable() and BufferedWriter.readable()
to always return False.

@item 
bpo-25195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25195}: Fix a regression in mock.MagicMock. _Call is a subclass of
tuple (changeset 3603bae63c13 only works for classes) so we need to
implement __ne__ ourselves.  Patch by Andrew Plummer.

@item 
bpo-26644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26644}: Raise ValueError rather than SystemError when a negative length
is passed to SSLSocket.recv() or read().

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL recv(0) and read(0) methods to return zero bytes
instead of up to 1024.

@item 
bpo-26616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26616}: Fixed a bug in datetime.astimezone() method.

@item 
bpo-21925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21925}: @ref{1df8,,warnings.formatwarning()} now catches exceptions on
@code{linecache.getline(...)} to be able to log @ref{54c,,ResourceWarning}
emitted late during the Python shutdown process.

@item 
bpo-24266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24266}: Ctrl+C during Readline history search now cancels the search
mode when compiled with Readline 7.

@item 
bpo-26560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26560}: Avoid potential ValueError in BaseHandler.start_response.
Initial patch by Peter Inglesby.

@item 
bpo-26569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26569}: Fix @ref{a2c,,pyclbr.readmodule()} and @ref{a2d,,pyclbr.readmodule_ex()}
to support importing packages.

@item 
bpo-26499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26499}: Account for remaining Content-Length in HTTPResponse.readline()
and read1(). Based on patch by Silent Ghost. Also document that
HTTPResponse now supports these methods.

@item 
bpo-25320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25320}: Handle sockets in directories unittest discovery is scanning.
Patch from Victor van den Elzen.

@item 
bpo-16181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16181}: cookiejar.http2time() now returns None if year is higher than
datetime.MAXYEAR.

@item 
bpo-26513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26513}: Fixes platform module detection of Windows Server

@item 
bpo-23718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23718}: Fixed parsing time in week 0 before Jan 1.  Original patch by
Tamás Bence Gedai.

@item 
bpo-20589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20589}: Invoking Path.owner() and Path.group() on Windows now raise
NotImplementedError instead of ImportError.

@item 
bpo-26177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26177}: Fixed the keys() method for Canvas and Scrollbar widgets.

@item 
bpo-15068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15068}: Got rid of excessive buffering in the fileinput module. The
bufsize parameter is no longer used.

@item 
bpo-2202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2202}: Fix UnboundLocalError in
AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu
Dupuy.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed pickling and copying the accumulate() iterator with total
is None.

@item 
bpo-26475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26475}: Fixed debugging output for regular expressions with the (?x)
flag.

@item 
bpo-26457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26457}: Fixed the subnets() methods in IP network classes for the case
when resulting prefix length is equal to maximal prefix length. Based on
patch by Xiang Zhang.

@item 
bpo-26385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26385}: Remove the file if the internal open() call in
NamedTemporaryFile() fails. Patch by Silent Ghost.

@item 
bpo-26402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26402}: Fix XML-RPC client to retry when the server shuts down a
persistent connection.  This was a regression related to the new
http.client.RemoteDisconnected exception in 3.5.0a4.

@item 
bpo-25913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25913}: Leading @code{<~} is optional now in base64.a85decode() with
adobe=True.  Patch by Swati Jaiswal.

@item 
bpo-26186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26186}: Remove an invalid type check in importlib.util.LazyLoader.

@item 
bpo-26367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26367}: importlib.__import__() raises SystemError like
builtins.__import__() when @code{level} is specified but without an
accompanying package specified.

@item 
bpo-26309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26309}: In the "socketserver" module, shut down the request (closing
the connected socket) when verify_request() returns false.  Patch by Aviv
Palivoda.

@item 
bpo-25995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25995}: os.walk() no longer uses FDs proportional to the tree depth.

@item 
bpo-26117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26117}: The os.scandir() iterator now closes file descriptor not only
when the iteration is finished, but when it was failed with error.

@item 
bpo-25911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25911}: Restored support of bytes paths in os.walk() on Windows.

@item 
bpo-26045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26045}: Add UTF-8 suggestion to error message when posting a
non-Latin-1 string with http.client.

@item 
bpo-12923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12923}: Reset FancyURLopener's redirect counter even if there is an
exception. Based on patches by Brian Brazil and Daniel Rocco.

@item 
bpo-25945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25945}: Fixed a crash when unpickle the functools.partial object with
wrong state. Fixed a leak in failed functools.partial constructor. "args"
and "keywords" attributes of functools.partial have now always types tuple
and dict correspondingly.

@item 
bpo-26202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26202}: copy.deepcopy() now correctly copies range() objects with
non-atomic attributes.

@item 
bpo-23076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23076}: Path.glob() now raises a ValueError if it's called with an
invalid pattern. Patch by Thomas Nyberg.

@item 
bpo-19883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19883}: Fixed possible integer overflows in zipimport.

@item 
bpo-26227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26227}: On Windows, getnameinfo(), gethostbyaddr() and
gethostbyname_ex() functions of the socket module now decode the hostname
from the ANSI code page rather than UTF-8.

@item 
bpo-26147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26147}: xmlrpc now works with strings not encodable with used non-UTF-8
encoding.

@item 
bpo-25935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25935}: Garbage collector now breaks reference loops with OrderedDict.

@item 
bpo-16620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16620}: Fixed AttributeError in msilib.Directory.glob().

@item 
bpo-26013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26013}: Added compatibility with broken protocol 2 pickles created in
old Python 3 versions (3.4.3 and lower).

@item 
bpo-25850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25850}: Use cross-compilation by default for 64-bit Windows.

@item 
bpo-17633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17633}: Improve zipimport's support for namespace packages.

@item 
bpo-24705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24705}: Fix sysconfig._parse_makefile not expanding $@{@} vars appearing
before $() vars.

@item 
bpo-22138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22138}: Fix mock.patch behavior when patching descriptors. Restore
original values after patching. Patch contributed by Sean McCully.

@item 
bpo-25672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25672}: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode
option if it is safe to do so.

@item 
bpo-26012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26012}: Don't traverse into symlinks for @code{**} pattern in
pathlib.Path.[r]glob().

@item 
bpo-24120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24120}: Ignore PermissionError when traversing a tree with
pathlib.Path.[r]glob(). Patch by Ulrich Petri.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: fileinput now uses sys.stdin as-is if it does not have a buffer
attribute (restores backward compatibility).

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: Copying the lru_cache() wrapper object now always works,
independently from the type of the wrapped object (by returning the
original object unchanged).

@item 
bpo-24103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24103}: Fixed possible use after free in ElementTree.XMLPullParser.

@item 
bpo-25860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25860}: os.fwalk() no longer skips remaining directories when error
occurs. Original patch by Samson Lee.

@item 
bpo-25914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25914}: Fixed and simplified OrderedDict.__sizeof__.

@item 
bpo-25902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25902}: Fixed various refcount issues in ElementTree iteration.

@item 
bpo-25717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25717}: Restore the previous behaviour of tolerating most fstat()
errors when opening files.  This was a regression in 3.5a1, and stopped
anonymous temporary files from working in special cases.

@item 
bpo-24903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24903}: Fix regression in number of arguments compileall accepts when
'-d' is specified.  The check on the number of arguments has been dropped
completely as it never worked correctly anyway.

@item 
bpo-25764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25764}: In the subprocess module, preserve any exception caused by
fork() failure when preexec_fn is used.

@item 
bpo-6478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6478}: _strptime's regexp cache now is reset after changing timezone
with time.tzset().

@item 
bpo-14285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14285}: When executing a package with the "python -m package" option,
and package initialization fails, a proper traceback is now reported.  The
"runpy" module now lets exceptions from package initialization pass back
to the caller, rather than raising ImportError.

@item 
bpo-19771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19771}: Also in runpy and the "-m" option, omit the irrelevant message
". . . is a package and cannot be directly executed" if the package could
not even be initialized (e.g. due to a bad @code{*.pyc} file).

@item 
bpo-25177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25177}: Fixed problem with the mean of very small and very large
numbers. As a side effect, statistics.mean and statistics.variance should
be significantly faster.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed copying object with state with boolean value is false.

@item 
bpo-10131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10131}: Fixed deep copying of minidom documents.  Based on patch by
Marian Ganisin.

@item 
bpo-25725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25725}: Fixed a reference leak in pickle.loads() when unpickling
invalid data including tuple instructions.

@item 
bpo-25663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25663}: In the Readline completer, avoid listing duplicate global
names, and search the global namespace before searching builtins.

@item 
bpo-25688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25688}: Fixed file leak in ElementTree.iterparse() raising an error.

@item 
bpo-23914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23914}: Fixed SystemError raised by unpickler on broken pickle data.

@item 
bpo-25691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25691}: Fixed crash on deleting ElementTree.Element attributes.

@item 
bpo-25624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25624}: ZipFile now always writes a ZIP_STORED header for directory
entries.  Patch by Dingyuan Wang.

@item 
Skip getaddrinfo if host is already resolved. Patch by A. Jesse Jiryu
Davis.

@item 
bpo-26050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26050}: Add asyncio.StreamReader.readuntil() method. Patch by Марк
Коренберг.

@item 
bpo-25924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25924}: Avoid unnecessary serialization of getaddrinfo(3) calls on OS X
versions 10.5 or higher.  Original patch by A. Jesse Jiryu Davis.

@item 
bpo-26406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26406}: Avoid unnecessary serialization of getaddrinfo(3) calls on
current versions of OpenBSD and NetBSD.  Patch by A. Jesse Jiryu Davis.

@item 
bpo-26848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26848}: Fix asyncio/subprocess.communicate() to handle empty input.
Patch by Jack O'Connor.

@item 
bpo-27040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27040}: Add loop.get_exception_handler method

@item 
bpo-27041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27041}: asyncio: Add loop.create_future method

@item 
bpo-27223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27223}: asyncio: Fix _read_ready and _write_ready to respect
_conn_lost. Patch by Łukasz Langa.

@item 
bpo-22970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22970}: asyncio: Fix inconsistency cancelling Condition.wait. Patch by
David Coles.
@end itemize

@node IDLE<59>,ドキュメント<80>,ライブラリ<194>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1002}@anchor{1f65}
@subsubsection IDLE



@itemize -

@item 
bpo-5124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5124}: Paste with text selected now replaces the selection on X11. This
matches how paste works on Windows, Mac, most modern Linux apps, and ttk
widgets. Original patch by Serhiy Storchaka.

@item 
bpo-24759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24759}: Make clear in idlelib.idle_test.__init__ that the directory is
a private implementation of test.test_idle and tool for maintainers.

@item 
bpo-27196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27196}: Stop 'ThemeChanged' warnings when running IDLE tests. These
persisted after other warnings were suppressed in #20567. Apply Serhiy
Storchaka's update_idletasks solution to four test files. Record this
additional advice in idle_test/README.txt

@item 
bpo-20567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20567}: Revise idle_test/README.txt with advice about avoiding tk
warning messages from tests.  Apply advice to several IDLE tests.

@item 
bpo-27117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27117}: Make colorizer htest and turtledemo work with dark themes. Move
code for configuring text widget colors to a new function.

@item 
bpo-26673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26673}: When tk reports font size as 0, change to size 10. Such fonts
on Linux prevented the configuration dialog from opening.

@item 
bpo-21939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21939}: Add test for IDLE's percolator. Original patch by Saimadhav
Heblikar.

@item 
bpo-21676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21676}: Add test for IDLE's replace dialog. Original patch by Saimadhav
Heblikar.

@item 
bpo-18410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18410}: Add test for IDLE's search dialog. Original patch by Westley
Martínez.

@item 
bpo-21703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21703}: Add test for IDLE's undo delegator. Original patch by Saimadhav
Heblikar .

@item 
bpo-27044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27044}: Add ConfigDialog.remove_var_callbacks to stop memory leaks.

@item 
bpo-23977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23977}: Add more asserts to test_delegator.

@item 
bpo-20640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20640}: Add tests for idlelib.configHelpSourceEdit. Patch by Saimadhav
Heblikar.

@item 
In the 'IDLE-console differences' section of the IDLE doc, clarify how
running with IDLE affects sys.modules and the standard streams.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: fix incorrect change in IOBinding that prevented printing.
Augment IOBinding htest to include all major IOBinding functions.

@item 
bpo-25905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25905}: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION
MARK in README.txt and open this and NEWS.txt with 'ascii'. Re-encode
CREDITS.txt to utf-8 and open it with 'utf-8'.
@end itemize

@node ドキュメント<80>,テスト<81>,IDLE<59>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1003}@anchor{1f66}
@subsubsection ドキュメント



@itemize -

@item 
bpo-19489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19489}: Moved the search box from the sidebar to the header and footer
of each page. Patch by Ammar Askar.

@item 
bpo-24136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24136}: Document the new 
@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} unpacking syntax of 3.5.

@item 
bpo-26736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26736}: Used HTTPS for external links in the documentation if possible.

@item 
bpo-6953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6953}: Rework the Readline module documentation to group related
functions together, and add more details such as what underlying Readline
functions and variables are accessed.

@item 
bpo-23606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23606}: Adds note to ctypes documentation regarding cdll.msvcrt.

@item 
bpo-25500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25500}: Fix documentation to not claim that __import__ is searched for
in the global scope.

@item 
bpo-26014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26014}: Update 3.x packaging documentation: * "See also" links to the
new docs are now provided in the legacy pages * links to setuptools
documentation have been updated
@end itemize

@node テスト<81>,ビルド<91>,ドキュメント<80>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1004}@anchor{1f67}
@subsubsection テスト



@itemize -

@item 
bpo-21916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21916}: Added tests for the turtle module.  Patch by ingrid, Gregory
Loyse and Jelle Zijlstra.

@item 
bpo-26523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26523}: The multiprocessing thread pool (multiprocessing.dummy.Pool)
was untested.

@item 
bpo-26015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26015}: Added new tests for pickling iterators of mutable sequences.

@item 
bpo-26325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26325}: Added test.support.check_no_resource_warning() to check that no
ResourceWarning is emitted.

@item 
bpo-25940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25940}: Changed test_ssl to use self-signed.pythontest.net.  This
avoids relying on svn.python.org, which recently changed root certificate.

@item 
bpo-25616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25616}: Tests for OrderedDict are extracted from test_collections into
separate file test_ordered_dict.

@item 
bpo-26583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26583}: Skip test_timestamp_overflow in test_import if bytecode files
cannot be written.
@end itemize

@node ビルド<91>,Windows<79>,テスト<81>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1005}@anchor{1f68}
@subsubsection ビルド



@itemize -

@item 
bpo-26884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26884}: Fix linking extension modules for cross builds. Patch by Xavier
de Gaye.

@item 
bpo-22359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22359}: Disable the rules for running _freeze_importlib and pgen when
cross-compiling.  The output of these programs is normally saved with the
source code anyway, and is still regenerated when doing a native build.
Patch by Xavier de Gaye.

@item 
bpo-27229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27229}: Fix the cross-compiling pgen rule for in-tree builds.  Patch by
Xavier de Gaye.

@item 
bpo-21668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21668}: Link audioop, _datetime, _ctypes_test modules to libm, except
on Mac OS X. Patch written by Xavier de Gaye.

@item 
bpo-25702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25702}: A --with-lto configure option has been added that will enable
link time optimizations at build time during a make profile-opt. Some
compilers and toolchains are known to not produce stable code when using
LTO, be sure to test things thoroughly before relying on it. It can
provide a few % speed up over profile-opt alone.

@item 
bpo-26624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26624}: Adds validation of ucrtbase[d].dll version with warning for old
versions.

@item 
bpo-17603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17603}: Avoid error about nonexistent fileblocks.o file by using a
lower-level check for st_blocks in struct stat.

@item 
bpo-26079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26079}: Fixing the build output folder for tix-8.4.3.6. Patch by Bjoern
Thiel.

@item 
bpo-26465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26465}: Update Windows builds to use OpenSSL 1.0.2g.

@item 
bpo-24421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24421}: Compile Modules/_math.c once, before building extensions.
Previously it could fail to compile properly if the math and cmath builds
were concurrent.

@item 
bpo-25348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25348}: Added @code{--pgo} and @code{--pgo-job} arguments to
@code{PCbuild\build.bat} for building with Profile-Guided Optimization.  The
old @code{PCbuild\build_pgo.bat} script is now deprecated, and simply calls
@code{PCbuild\build.bat --pgo %*}.

@item 
bpo-25827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25827}: Add support for building with ICC to @code{configure}, including a
new @code{--with-icc} flag.

@item 
bpo-25696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25696}: Fix installation of Python on UNIX with make -j9.

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update OS X 10.5+ 32-bit-only installer to build and link with
OpenSSL 1.0.2h.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update Windows builds to use OpenSSL 1.0.2f.

@item 
bpo-25136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25136}: Support Apple Xcode 7's new textual SDK stub libraries.

@item 
bpo-24324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24324}: Do not enable unreachable code warnings when using gcc as the
option does not work correctly in older versions of gcc and has been
silently removed as of gcc-4.5.
@end itemize

@node Windows<79>,Tools/Demos<56>,ビルド<91>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1006}@anchor{1f69}
@subsubsection Windows



@itemize -

@item 
bpo-27053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27053}: Updates make_zip.py to correctly generate library ZIP file.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update the prepare_ssl.py script to handle OpenSSL releases
that don't include the contents of the include directory (that is, 1.0.2e
and later).

@item 
bpo-26071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26071}: bdist_wininst created binaries fail to start and find 32bit
Python

@item 
bpo-26073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26073}: Update the list of magic numbers in launcher

@item 
bpo-26065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26065}: Excludes venv from library when generating embeddable distro.

@item 
bpo-17500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17500}: Remove unused and outdated icons. (See also:
@indicateurl{https://github.com/python/pythondotorg/issues/945})
@end itemize

@node Tools/Demos<56>,,Windows<79>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id1007}@anchor{1f6a}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-26799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26799}: Fix python-gdb.py: don't get C types once when the Python code
is loaded, but get C types on demand. The C types can change if
python-gdb.py is loaded before the Python executable. Patch written by
Thomas Ilsche.

@item 
bpo-26271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26271}: Fix the Freeze tool to properly use flags passed through
configure. Patch by Daniel Shaulov.

@item 
bpo-26489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26489}: Add dictionary unpacking support to Tools/parser/unparse.py.
Patch by Guo Ci Teo.

@item 
bpo-26316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26316}: Fix variable name typo in Argument Clinic.
@end itemize

@node Python 3 5 1 final,Python 3 5 1 release candidate 1,Python 3 5 2 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-5-1-final}@anchor{1f6b}
@subsection Python 3.5.1 final


`Release date: 2015-12-06'

@menu
* Core and Builtins: Core and Builtins<192>. 
* Windows: Windows<80>. 

@end menu

@node Core and Builtins<192>,Windows<80>,,Python 3 5 1 final
@anchor{whatsnew/changelog id1008}@anchor{1f6c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-25709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25709}: Fixed problem with in-place string concatenation and utf-8
cache.
@end itemize

@node Windows<80>,,Core and Builtins<192>,Python 3 5 1 final
@anchor{whatsnew/changelog id1009}@anchor{1f6d}
@subsubsection Windows



@itemize -

@item 
bpo-25715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25715}: Python 3.5.1 installer shows wrong upgrade path and incorrect
logic for launcher detection.
@end itemize

@node Python 3 5 1 release candidate 1,Python 3 5 0 final,Python 3 5 1 final,変更履歴
@anchor{whatsnew/changelog python-3-5-1-release-candidate-1}@anchor{1f6e}
@subsection Python 3.5.1 release candidate 1


`Release date: 2015-11-22'

@menu
* Core and Builtins: Core and Builtins<193>. 
* ライブラリ: ライブラリ<195>. 
* IDLE: IDLE<60>. 
* ドキュメント: ドキュメント<81>. 
* テスト: テスト<82>. 
* ビルド: ビルド<92>. 
* Windows: Windows<81>. 
* Tools/Demos: Tools/Demos<57>. 

@end menu

@node Core and Builtins<193>,ライブラリ<195>,,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1010}@anchor{1f6f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-25630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25630}: Fix a possible segfault during argument parsing in functions
that accept filesystem paths.

@item 
bpo-23564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23564}: Fixed a partially broken sanity check in the _posixsubprocess
internals regarding how fds_to_pass were passed to the child.  The bug had
no actual impact as subprocess.py already avoided it.

@item 
bpo-25388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25388}: Fixed tokenizer crash when processing undecodable source code
with a null byte.

@item 
bpo-25462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25462}: The hash of the key now is calculated only once in most
operations in C implementation of OrderedDict.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Default implementation of __reduce__ and __reduce_ex__ now
rejects builtin types with not defined __new__.

@item 
bpo-25555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25555}: Fix parser and AST: fill lineno and col_offset of "arg" node
when compiling AST from Python objects.

@item 
bpo-24802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24802}: Avoid buffer overreads when int(), float(), compile(), exec()
and eval() are passed bytes-like objects.  These objects are not
necessarily terminated by a null byte, but the functions assumed they
were.

@item 
bpo-24726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24726}: Fixed a crash and leaking NULL in repr() of OrderedDict that
was mutated by direct calls of dict methods.

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Iterating OrderedDict with keys with unstable hash now raises
KeyError in C implementations as well as in Python implementation.

@item 
bpo-25395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25395}: Fixed crash when highly nested OrderedDict structures were
garbage collected.

@item 
bpo-25274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25274}: sys.setrecursionlimit() now raises a RecursionError if the new
recursion limit is too low depending at the current recursion depth.
Modify also the "lower-water mark" formula to make it monotonic. This mark
is used to decide when the overflowed flag of the thread state is reset.

@item 
bpo-24402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24402}: Fix input() to prompt to the redirected stdout when
sys.stdout.fileno() fails.

@item 
bpo-24806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24806}: Prevent builtin types that are not allowed to be subclassed
from being subclassed through multiple inheritance.

@item 
bpo-24848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24848}: Fixed a number of bugs in UTF-7 decoding of misformed data.

@item 
bpo-25280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25280}: Import trace messages emitted in verbose (-v) mode are no
longer formatted twice.

@item 
bpo-25003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25003}: On Solaris 11.3 or newer, os.urandom() now uses the getrandom()
function instead of the getentropy() function. The getentropy() function
is blocking to generate very good quality entropy, os.urandom() doesn't
need such high-quality entropy.

@item 
bpo-25182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25182}: The stdprinter (used as sys.stderr before the io module is
imported at startup) now uses the backslashreplace error handler.

@item 
bpo-25131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25131}: Make the line number and column offset of set/dict literals and
comprehensions correspond to the opening brace.

@item 
bpo-25150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25150}: Hide the private @code{_Py_atomic_@var{xxx}} symbols from the
public Python.h header to fix a compilation error with OpenMP.
PyThreadState_GET() becomes an alias to PyThreadState_Get() to avoid ABI
incompatibilities.
@end itemize

@node ライブラリ<195>,IDLE<60>,Core and Builtins<193>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1011}@anchor{1f70}
@subsubsection ライブラリ



@itemize -

@item 
bpo-25626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25626}: Change three zlib functions to accept sizes that fit in
Py_ssize_t, but internally cap those sizes to UINT_MAX.  This resolves a
regression in 3.5 where GzipFile.read() failed to read chunks larger than
2 or 4 GiB.  The change affects the zlib.Decompress.decompress()
max_length parameter, the zlib.decompress() bufsize parameter, and the
zlib.Decompress.flush() length parameter.

@item 
bpo-25583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25583}: Avoid incorrect errors raised by os.makedirs(exist_ok=True)
when the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-25593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25593}: Change semantics of EventLoop.stop() in asyncio.

@item 
bpo-6973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6973}: When we know a subprocess.Popen process has died, do not allow
the send_signal(), terminate(), or kill() methods to do anything as they
could potentially signal a different process.

@item 
bpo-25590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25590}: In the Readline completer, only call getattr() once per
attribute.

@item 
bpo-25498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25498}: Fix a crash when garbage-collecting ctypes objects created by
wrapping a memoryview.  This was a regression made in 3.5a1.  Based on
patch by Eryksun.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Added "escape" to the __all__ list in the glob module.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Fixed recursive glob() with patterns starting with @code{**}.

@item 
bpo-25446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25446}: Fix regression in smtplib's AUTH LOGIN support.

@item 
bpo-18010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18010}: Fix the pydoc web server's module search function to handle
exceptions from importing packages.

@item 
bpo-25554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25554}: Got rid of circular references in regular expression parsing.

@item 
bpo-25510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25510}: fileinput.FileInput.readline() now returns b'@w{'} instead of '@w{'} at
the end if the FileInput was opened with binary mode. Patch by Ryosuke
Ito.

@item 
bpo-25503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25503}: Fixed inspect.getdoc() for inherited docstrings of properties.
Original patch by John Mark Vandenberg.

@item 
bpo-25515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25515}: Always use os.urandom as a source of randomness in uuid.uuid4.

@item 
bpo-21827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21827}: Fixed textwrap.dedent() for the case when largest common
whitespace is a substring of smallest leading whitespace. Based on patch
by Robert Li.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: The lru_cache() wrapper objects now can be copied and pickled
(by returning the original object unchanged).

@item 
bpo-25390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25390}: typing: Don't crash on Union[str, Pattern].

@item 
bpo-25441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25441}: asyncio: Raise error from drain() when socket is closed.

@item 
bpo-25410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25410}: Cleaned up and fixed minor bugs in C implementation of
OrderedDict.

@item 
bpo-25411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25411}: Improved Unicode support in SMTPHandler through better use of
the email package. Thanks to user simon04 for the patch.

@item 
bpo-25407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25407}: Remove mentions of the formatter module being removed in Python
3.6.

@item 
bpo-25406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25406}: Fixed a bug in C implementation of OrderedDict.move_to_end()
that caused segmentation fault or hang in iterating after moving several
items to the start of ordered dict.

@item 
bpo-25364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25364}: zipfile now works in threads disabled builds.

@item 
bpo-25328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25328}: smtpd's SMTPChannel now correctly raises a ValueError if both
decode_data and enable_SMTPUTF8 are set to true.

@item 
bpo-25316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25316}: distutils raises OSError instead of DistutilsPlatformError when
MSVC is not installed.

@item 
bpo-25380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25380}: Fixed protocol for the STACK_GLOBAL opcode in
pickletools.opcodes.

@item 
bpo-23972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23972}: Updates asyncio datagram create method allowing reuseport and
reuseaddr socket options to be set prior to binding the socket. Mirroring
the existing asyncio create_server method the reuseaddr option for
datagram sockets defaults to True if the O/S is 'posix' (except if the
platform is Cygwin). Patch by Chris Laws.

@item 
bpo-25304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25304}: Add asyncio.run_coroutine_threadsafe().  This lets you submit a
coroutine to a loop from another thread, returning a
concurrent.futures.Future.  By Vincent Michel.

@item 
bpo-25232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25232}: Fix CGIRequestHandler to split the query from the URL at the
first question mark (?) rather than the last. Patch from Xiang Zhang.

@item 
bpo-24657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24657}: Prevent CGIRequestHandler from collapsing slashes in the query
part of the URL as if it were a path. Patch from Xiang Zhang.

@item 
bpo-24483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24483}: C implementation of functools.lru_cache() now calculates key's
hash only once.

@item 
bpo-22958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22958}: Constructor and update method of weakref.WeakValueDictionary
now accept the self and the dict keyword arguments.

@item 
bpo-22609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22609}: Constructor of collections.UserDict now accepts the self
keyword argument.

@item 
bpo-25111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25111}: Fixed comparison of traceback.FrameSummary.

@item 
bpo-25262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25262}: Added support for BINBYTES8 opcode in Python implementation of
unpickler. Highest 32 bits of 64-bit size for BINUNICODE8 and BINBYTES8
opcodes no longer silently ignored on 32-bit platforms in C
implementation.

@item 
bpo-25034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25034}: Fix string.Formatter problem with auto-numbering and nested
format_specs. Patch by Anthon van der Neut.

@item 
bpo-25233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25233}: Rewrite the guts of asyncio.Queue and asyncio.Semaphore to be
more understandable and correct.

@item 
bpo-25203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25203}: Failed readline.set_completer_delims() no longer left the
module in inconsistent state.

@item 
bpo-23600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23600}: Default implementation of tzinfo.fromutc() was returning wrong
results in some cases.

@item 
bpo-23329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23329}: Allow the ssl module to be built with older versions of
LibreSSL.

@item 
Prevent overflow in _Unpickler_Read.

@item 
bpo-25047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25047}: The XML encoding declaration written by Element Tree now
respects the letter case given by the user. This restores the ability to
write encoding names in uppercase like "UTF-8", which worked in Python 2.

@item 
bpo-25135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25135}: Make deque_clear() safer by emptying the deque before clearing.
This helps avoid possible reentrancy issues.

@item 
bpo-19143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19143}: platform module now reads Windows version from kernel32.dll to
avoid compatibility shims.

@item 
bpo-25092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25092}: Fix datetime.strftime() failure when errno was already set to
EINVAL.

@item 
bpo-23517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23517}: Fix rounding in fromtimestamp() and utcfromtimestamp() methods
of datetime.datetime: microseconds are now rounded to nearest with ties
going to nearest even integer (ROUND_HALF_EVEN), instead of being rounding
towards minus infinity (ROUND_FLOOR). It's important that these methods
use the same rounding mode than datetime.timedelta to keep the property:
(datetime(1970,1,1) + timedelta(seconds=t)) ==
datetime.utcfromtimestamp(t). It also the rounding mode used by
round(float) for example.

@item 
bpo-25155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25155}: Fix datetime.datetime.now() and datetime.datetime.utcnow() on
Windows to support date after year 2038. It was a regression introduced in
Python 3.5.0.

@item 
bpo-25108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25108}: Omitted internal frames in traceback functions print_stack(),
format_stack(), and extract_stack() called without arguments.

@item 
bpo-25118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25118}: Fix a regression of Python 3.5.0 in os.waitpid() on Windows.

@item 
bpo-24684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24684}: socket.socket.getaddrinfo() now calls
PyUnicode_AsEncodedString() instead of calling the encode() method of the
host, to handle correctly custom string with an encode() method which
doesn't return a byte string. The encoder of the IDNA codec is now called
directly instead of calling the encode() method of the string.

@item 
bpo-25060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25060}: Correctly compute stack usage of the BUILD_MAP opcode.

@item 
bpo-24857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24857}: Comparing call_args to a long sequence now correctly returns a
boolean result instead of raising an exception.  Patch by A Kaptur.

@item 
bpo-23144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23144}: Make sure that HTMLParser.feed() returns all the data, even
when convert_charrefs is True.

@item 
bpo-24982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24982}: shutil.make_archive() with the "zip" format now adds entries
for directories (including empty directories) in ZIP file.

@item 
bpo-25019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25019}: Fixed a crash caused by setting non-string key of expat parser.
Based on patch by John Leitch.

@item 
bpo-16180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16180}: Exit pdb if file has syntax error, instead of trapping user in
an infinite loop.  Patch by Xavier de Gaye.

@item 
bpo-24891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24891}: Fix a race condition at Python startup if the file descriptor
of stdin (0), stdout (1) or stderr (2) is closed while Python is creating
sys.stdin, sys.stdout and sys.stderr objects. These attributes are now set
to None if the creation of the object failed, instead of raising an
OSError exception. Initial patch written by Marco Paolini.

@item 
bpo-24992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24992}: Fix error handling and a race condition (related to garbage
collection) in collections.OrderedDict constructor.

@item 
bpo-24881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24881}: Fixed setting binary mode in Python implementation of FileIO on
Windows and Cygwin.  Patch from Akira Li.

@item 
bpo-25578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25578}: Fix (another) memory leak in SSLSocket.getpeercer().

@item 
bpo-25530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25530}: Disable the vulnerable SSLv3 protocol by default when creating
ssl.SSLContext.

@item 
bpo-25569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25569}: Fix memory leak in SSLSocket.getpeercert().

@item 
bpo-25471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25471}: Sockets returned from accept() shouldn't appear to be
nonblocking.

@item 
bpo-25319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25319}: When threading.Event is reinitialized, the underlying condition
should use a regular lock rather than a recursive lock.

@item 
bpo-21112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21112}: Fix regression in unittest.expectedFailure on subclasses. Patch
from Berker Peksag.

@item 
bpo-24764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24764}: cgi.FieldStorage.read_multi() now ignores the Content-Length
header in part headers. Patch written by Peter Landry and reviewed by
Pierre Quentel.

@item 
bpo-24913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24913}: Fix overrun error in deque.index(). Found by John Leitch and
Bryce Darling.

@item 
bpo-24774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24774}: Fix docstring in http.server.test. Patch from Chiu-Hsiang Hsu.

@item 
bpo-21159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21159}: Improve message in
configparser.InterpolationMissingOptionError. Patch from Łukasz Langa.

@item 
bpo-20362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20362}: Honour TestCase.longMessage correctly in assertRegex. Patch
from Ilia Kurenkov.

@item 
bpo-23572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23572}: Fixed functools.singledispatch on classes with false
metaclasses.  Patch by Ethan Furman.

@item 
asyncio: ensure_future() now accepts awaitable objects.
@end itemize

@node IDLE<60>,ドキュメント<81>,ライブラリ<195>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1012}@anchor{1f71}
@subsubsection IDLE



@itemize -

@item 
bpo-15348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15348}: Stop the debugger engine (normally in a user process) before
closing the debugger window (running in the IDLE process). This prevents
the RuntimeErrors that were being caught and ignored.

@item 
bpo-24455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24455}: Prevent IDLE from hanging when a) closing the shell while the
debugger is active (15347); b) closing the debugger with the [X] button
(15348); and c) activating the debugger when already active (24455). The
patch by Mark Roseman does this by making two changes. 1. Suspend and
resume the gui.interaction method with the tcl vwait mechanism intended
for this purpose (instead of root.mainloop & .quit). 2. In gui.run, allow
any existing interaction to terminate first.

@item 
Change 'The program' to 'Your program' in an IDLE 'kill program?' message
to make it clearer that the program referred to is the currently running
user program, not IDLE itself.

@item 
bpo-24750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24750}: Improve the appearance of the IDLE editor window status bar.
Patch by Mark Roseman.

@item 
bpo-25313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25313}: Change the handling of new built-in text color themes to better
address the compatibility problem introduced by the addition of IDLE Dark.
Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.

@item 
bpo-24782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24782}: Extension configuration is now a tab in the IDLE Preferences
dialog rather than a separate dialog.  The former tabs are now a sorted
list.  Patch by Mark Roseman.

@item 
bpo-22726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22726}: Re-activate the config dialog help button with some content
about the other buttons and the new IDLE Dark theme.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: IDLE now has an 'IDLE Dark' built-in text color theme. It is
more or less IDLE Classic inverted, with a cobalt blue background.
Strings, comments, keywords, ... are still green, red, orange, ... . To
use it with IDLEs released before November 2015, hit the 'Save as New
Custom Theme' button and enter a new name, such as 'Custom Dark'.  The
custom theme will work with any IDLE release, and can be modified.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: README.txt is now an idlelib index for IDLE developers and
curious users. The previous user content is now in the IDLE doc chapter.
'IDLE' now means 'Integrated Development and Learning Environment'.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: Users can now set breakpoint colors in Settings -> Custom
Highlighting. Original patch by Mark Roseman.

@item 
bpo-24972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24972}: Inactive selection background now matches active selection
background, as configured by users, on all systems.  Found items are now
always highlighted on Windows.  Initial patch by Mark Roseman.

@item 
bpo-24570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24570}: Idle: make calltip and completion boxes appear on Macs affected
by a tk regression.  Initial patch by Mark Roseman.

@item 
bpo-24988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24988}: Idle ScrolledList context menus (used in debugger) now work on
Mac Aqua. Patch by Mark Roseman.

@item 
bpo-24801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24801}: Make right-click for context menu work on Mac Aqua. Patch by
Mark Roseman.

@item 
bpo-25173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25173}: Associate tkinter messageboxes with a specific widget. For Mac
OSX, make them a 'sheet'.  Patch by Mark Roseman.

@item 
bpo-25198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25198}: Enhance the initial html viewer now used for Idle Help.
Properly indent fixed-pitch text (patch by Mark Roseman). Give code
snippet a very Sphinx-like light blueish-gray background. Re-use initial
width and height set by users for shell and editor. When the Table of
Contents (TOC) menu is used, put the section header at the top of the
screen.

@item 
bpo-25225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25225}: Condense and rewrite Idle doc section on text colors.

@item 
bpo-21995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21995}: Explain some differences between IDLE and console Python.

@item 
bpo-22820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22820}: Explain need for `print' when running file from Idle editor.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: Doc: augment Idle feature list and no-subprocess section.

@item 
bpo-25219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25219}: Update doc for Idle command line options. Some were missing and
notes were not correct.

@item 
bpo-24861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24861}: Most of idlelib is private and subject to change. Use
idleib.idle.* to start Idle. See idlelib.__init__.__doc__.

@item 
bpo-25199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25199}: Idle: add synchronization comments for future maintainers.

@item 
bpo-16893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16893}: Replace help.txt with help.html for Idle doc display. The new
idlelib/help.html is rstripped Doc/build/html/library/idle.html. It looks
better than help.txt and will better document Idle as released. The
tkinter html viewer that works for this file was written by Mark Roseman.
The now unused EditorWindow.HelpDialog class and helt.txt file are
deprecated.

@item 
bpo-24199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24199}: Deprecate unused idlelib.idlever with possible removal in 3.6.

@item 
bpo-24790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24790}: Remove extraneous code (which also create 2 & 3 conflicts).
@end itemize

@node ドキュメント<81>,テスト<82>,IDLE<60>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1013}@anchor{1f72}
@subsubsection ドキュメント



@itemize -

@item 
bpo-22558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22558}: Add remaining doc links to source code for Python-coded
modules. Patch by Yoni Lavi.

@item 
bpo-12067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12067}: Rewrite Comparisons section in the Expressions chapter of the
language reference. Some of the details of comparing mixed types were
incorrect or ambiguous. NotImplemented is only relevant at a lower level
than the Expressions chapter. Added details of comparing range() objects,
and default behaviour and consistency suggestions for user-defined
classes. Patch from Andy Maier.

@item 
bpo-24952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24952}: Clarify the default size argument of stack_size() in the
"threading" and "_thread" modules. Patch from Mattip.

@item 
bpo-23725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23725}: Overhaul tempfile docs. Note deprecated status of mktemp. Patch
from Zbigniew Jędrzejewski-Szmek.

@item 
bpo-24808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24808}: Update the types of some PyTypeObject fields.  Patch by Joseph
Weston.

@item 
bpo-22812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22812}: Fix unittest discovery examples. Patch from Pam McA'Nulty.
@end itemize

@node テスト<82>,ビルド<92>,ドキュメント<81>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1014}@anchor{1f73}
@subsubsection テスト



@itemize -

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Added tests for OrderedDict subclasses.

@item 
bpo-25099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25099}: Make test_compileall not fail when an entry on sys.path cannot
be written to (commonly seen in administrative installs on Windows).

@item 
bpo-23919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23919}: Prevents assert dialogs appearing in the test suite.

@item 
@code{PCbuild\rt.bat} now accepts an unlimited number of arguments to pass
along to regrtest.py.  Previously there was a limit of 9.
@end itemize

@node ビルド<92>,Windows<81>,テスト<82>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1015}@anchor{1f74}
@subsubsection ビルド



@itemize -

@item 
bpo-24915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24915}: Add LLVM support for PGO builds and use the test suite to
generate the profile data. Initial patch by Alecsandru Patrascu of Intel.

@item 
bpo-24910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24910}: Windows MSIs now have unique display names.

@item 
bpo-24986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24986}: It is now possible to build Python on Windows without errors
when external libraries are not available.
@end itemize

@node Windows<81>,Tools/Demos<57>,ビルド<92>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1016}@anchor{1f75}
@subsubsection Windows



@itemize -

@item 
bpo-25450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25450}: Updates shortcuts to start Python in installation directory.

@item 
bpo-25164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25164}: Changes default all-users install directory to match per-user
directory.

@item 
bpo-25143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25143}: Improves installer error messages for unsupported platforms.

@item 
bpo-25163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25163}: Display correct directory in installer when using non-default
settings.

@item 
bpo-25361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25361}: Disables use of SSE2 instructions in Windows 32-bit build

@item 
bpo-25089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25089}: Adds logging to installer for case where launcher is not
selected on upgrade.

@item 
bpo-25165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25165}: Windows uninstallation should not remove launcher if other
versions remain

@item 
bpo-25112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25112}: py.exe launcher is missing icons

@item 
bpo-25102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25102}: Windows installer does not precompile for -O or -OO.

@item 
bpo-25081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25081}: Makes Back button in installer go back to upgrade page when
upgrading.

@item 
bpo-25091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25091}: Increases font size of the installer.

@item 
bpo-25126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25126}: Clarifies that the non-web installer will download some
components.

@item 
bpo-25213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25213}: Restores requestedExecutionLevel to manifest to disable UAC
virtualization.

@item 
bpo-25022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25022}: Removed very outdated PC/example_nt/ directory.
@end itemize

@node Tools/Demos<57>,,Windows<81>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id1017}@anchor{1f76}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-25440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25440}: Fix output of python-config --extension-suffix.
@end itemize

@node Python 3 5 0 final,Python 3 5 0 release candidate 4,Python 3 5 1 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-5-0-final}@anchor{1f77}
@subsection Python 3.5.0 final


`Release date: 2015-09-13'

@menu
* ビルド: ビルド<93>. 

@end menu

@node ビルド<93>,,,Python 3 5 0 final
@anchor{whatsnew/changelog id1018}@anchor{1f78}
@subsubsection ビルド



@itemize -

@item 
bpo-25071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25071}: Windows installer should not require TargetDir parameter when
installing quietly.
@end itemize

@node Python 3 5 0 release candidate 4,Python 3 5 0 release candidate 3,Python 3 5 0 final,変更履歴
@anchor{whatsnew/changelog python-3-5-0-release-candidate-4}@anchor{1f79}
@subsection Python 3.5.0 release candidate 4


`Release date: 2015-09-09'

@menu
* ライブラリ: ライブラリ<196>. 
* ビルド: ビルド<94>. 

@end menu

@node ライブラリ<196>,ビルド<94>,,Python 3 5 0 release candidate 4
@anchor{whatsnew/changelog id1019}@anchor{1f7a}
@subsubsection ライブラリ



@itemize -

@item 
bpo-25029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25029}: Fixes MemoryError in test_strptime.
@end itemize

@node ビルド<94>,,ライブラリ<196>,Python 3 5 0 release candidate 4
@anchor{whatsnew/changelog id1020}@anchor{1f7b}
@subsubsection ビルド



@itemize -

@item 
bpo-25027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25027}: Reverts partial-static build options and adds vcruntime140.dll
to Windows installation.
@end itemize

@node Python 3 5 0 release candidate 3,Python 3 5 0 release candidate 2,Python 3 5 0 release candidate 4,変更履歴
@anchor{whatsnew/changelog python-3-5-0-release-candidate-3}@anchor{1f7c}
@subsection Python 3.5.0 release candidate 3


`Release date: 2015-09-07'

@menu
* Core and Builtins: Core and Builtins<194>. 
* ライブラリ: ライブラリ<197>. 

@end menu

@node Core and Builtins<194>,ライブラリ<197>,,Python 3 5 0 release candidate 3
@anchor{whatsnew/changelog id1021}@anchor{1f7d}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24305}: Prevent import subsystem stack frames from being counted by the
warnings.warn(stacklevel=) parameter.

@item 
bpo-24912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24912}: Prevent __class__ assignment to immutable built-in objects.

@item 
bpo-24975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24975}: Fix AST compilation for 
@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} syntax.
@end itemize

@node ライブラリ<197>,,Core and Builtins<194>,Python 3 5 0 release candidate 3
@anchor{whatsnew/changelog id1022}@anchor{1f7e}
@subsubsection ライブラリ



@itemize -

@item 
bpo-24917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24917}: time_strftime() buffer over-read.

@item 
bpo-24748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24748}: To resolve a compatibility problem found with py2exe and
pywin32, imp.load_dynamic() once again ignores previously loaded modules
to support Python modules replacing themselves with extension modules.
Patch by Petr Viktorin.

@item 
bpo-24635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24635}: Fixed a bug in typing.py where isinstance([], typing.Iterable)
would return True once, then False on subsequent calls.

@item 
bpo-24989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24989}: Fixed buffer overread in BytesIO.readline() if a position is
set beyond size.  Based on patch by John Leitch.

@item 
bpo-24913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24913}: Fix overrun error in deque.index(). Found by John Leitch and
Bryce Darling.
@end itemize

@node Python 3 5 0 release candidate 2,Python 3 5 0 release candidate 1,Python 3 5 0 release candidate 3,変更履歴
@anchor{whatsnew/changelog python-3-5-0-release-candidate-2}@anchor{1f7f}
@subsection Python 3.5.0 release candidate 2


`Release date: 2015-08-25'

@menu
* Core and Builtins: Core and Builtins<195>. 
* ライブラリ: ライブラリ<198>. 

@end menu

@node Core and Builtins<195>,ライブラリ<198>,,Python 3 5 0 release candidate 2
@anchor{whatsnew/changelog id1023}@anchor{1f80}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24769}: Interpreter now starts properly when dynamic loading is
disabled.  Patch by Petr Viktorin.

@item 
bpo-21167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21167}: NAN operations are now handled correctly when python is
compiled with ICC even if -fp-model strict is not specified.

@item 
bpo-24492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24492}: A "package" lacking a __name__ attribute when trying to perform
a @code{from .. import ...} statement will trigger an ImportError instead of
an AttributeError.
@end itemize

@node ライブラリ<198>,,Core and Builtins<195>,Python 3 5 0 release candidate 2
@anchor{whatsnew/changelog id1024}@anchor{1f81}
@subsubsection ライブラリ



@itemize -

@item 
bpo-24847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24847}: Removes vcruntime140.dll dependency from Tcl/Tk.

@item 
bpo-24839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24839}: platform._syscmd_ver raises DeprecationWarning

@item 
bpo-24867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24867}: Fix Task.get_stack() for 'async def' coroutines
@end itemize

@node Python 3 5 0 release candidate 1,Python 3 5 0 beta 4,Python 3 5 0 release candidate 2,変更履歴
@anchor{whatsnew/changelog python-3-5-0-release-candidate-1}@anchor{1f82}
@subsection Python 3.5.0 release candidate 1


`Release date: 2015-08-09'

@menu
* Core and Builtins: Core and Builtins<196>. 
* ライブラリ: ライブラリ<199>. 
* IDLE: IDLE<61>. 
* ドキュメント: ドキュメント<82>. 
* テスト: テスト<83>. 

@end menu

@node Core and Builtins<196>,ライブラリ<199>,,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id1025}@anchor{1f83}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24667}: Resize odict in all cases that the underlying dict resizes.
@end itemize

@node ライブラリ<199>,IDLE<61>,Core and Builtins<196>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id1026}@anchor{1f84}
@subsubsection ライブラリ



@itemize -

@item 
bpo-24824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24824}: Signatures of codecs.encode() and codecs.decode() now are
compatible with pydoc.

@item 
bpo-24634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24634}: Importing uuid should not try to load libc on Windows

@item 
bpo-24798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24798}: _msvccompiler.py doesn't properly support manifests

@item 
bpo-4395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4395}: Better testing and documentation of binary operators. Patch by
Martin Panter.

@item 
bpo-23973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23973}: Update typing.py from GitHub repo.

@item 
bpo-23004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23004}: mock_open() now reads binary data correctly when the type of
read_data is bytes.  Initial patch by Aaron Hill.

@item 
bpo-23888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23888}: Handle fractional time in cookie expiry. Patch by ssh.

@item 
bpo-23652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23652}: Make it possible to compile the select module against the libc
headers from the Linux Standard Base, which do not include some EPOLL
macros.  Patch by Matt Frank.

@item 
bpo-22932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22932}: Fix timezones in email.utils.formatdate. Patch from Dmitry
Shachnev.

@item 
bpo-23779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23779}: imaplib raises TypeError if authenticator tries to abort. Patch
from Craig Holmquist.

@item 
bpo-23319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23319}: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch
written by Matthieu Gautier.

@item 
bpo-23254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23254}: Document how to close the TCPServer listening socket. Patch
from Martin Panter.

@item 
bpo-19450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19450}: Update Windows and OS X installer builds to use SQLite 3.8.11.

@item 
bpo-17527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17527}: Add PATCH to wsgiref.validator. Patch from Luca Sbardella.

@item 
bpo-24791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24791}: Fix grammar regression for call syntax: 'g(*a or b)'.
@end itemize

@node IDLE<61>,ドキュメント<82>,ライブラリ<199>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id1027}@anchor{1f85}
@subsubsection IDLE



@itemize -

@item 
bpo-23672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23672}: Allow Idle to edit and run files with astral chars in name.
Patch by Mohd Sanad Zaki Rizvi.

@item 
bpo-24745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24745}: Idle editor default font. Switch from Courier to
platform-sensitive TkFixedFont.  This should not affect current customized
font selections.  If there is a problem, edit
$HOME/.idlerc/config-main.cfg and remove '@code{font@var{xxx}}' entries from
[Editor Window].  Patch by Mark Roseman.

@item 
bpo-21192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21192}: Idle editor. When a file is run, put its name in the restart
bar. Do not print false prompts. Original patch by Adnan Umer.

@item 
bpo-13884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13884}: Idle menus. Remove tearoff lines. Patch by Roger Serwy.
@end itemize

@node ドキュメント<82>,テスト<83>,IDLE<61>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id1028}@anchor{1f86}
@subsubsection ドキュメント



@itemize -

@item 
bpo-24129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24129}: Clarify the reference documentation for name resolution. This
includes removing the assumption that readers will be familiar with the
name resolution scheme Python used prior to the introduction of lexical
scoping for function namespaces. Patch by Ivan Levkivskyi.

@item 
bpo-20769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20769}: Improve reload() docs. Patch by Dorian Pula.

@item 
bpo-23589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23589}: Remove duplicate sentence from the FAQ.  Patch by Yongzhi Pan.

@item 
bpo-24729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24729}: Correct IO tutorial to match implementation regarding encoding
parameter to open function.
@end itemize

@node テスト<83>,,ドキュメント<82>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id1029}@anchor{1f87}
@subsubsection テスト



@itemize -

@item 
bpo-24751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24751}: When running regrtest with the @code{-w} command line option, a
test run is no longer marked as a failure if all tests succeed when
re-run.
@end itemize

@node Python 3 5 0 beta 4,Python 3 5 0 beta 3,Python 3 5 0 release candidate 1,変更履歴
@anchor{whatsnew/changelog python-3-5-0-beta-4}@anchor{1f88}
@subsection Python 3.5.0 beta 4


`Release date: 2015-07-26'

@menu
* Core and Builtins: Core and Builtins<197>. 
* ライブラリ: ライブラリ<200>. 
* ビルド: ビルド<95>. 

@end menu

@node Core and Builtins<197>,ライブラリ<200>,,Python 3 5 0 beta 4
@anchor{whatsnew/changelog id1030}@anchor{1f89}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23573}: Restored optimization of bytes.rfind() and bytearray.rfind()
for single-byte argument on Linux.

@item 
bpo-24569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24569}: Make 
@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} dictionary evaluation more consistent.

@item 
bpo-24583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24583}: Fix crash when set is mutated while being updated.

@item 
bpo-24407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24407}: Fix crash when dict is mutated while being updated.

@item 
bpo-24619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24619}: New approach for tokenizing async/await. As a consequence, it
is now possible to have one-line 'async def foo(): await ..' functions.

@item 
bpo-24687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24687}: Plug refleak on SyntaxError in function parameters annotations.

@item 
bpo-15944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15944}: memoryview: Allow arbitrary formats when casting to bytes.
Patch by Martin Panter.
@end itemize

@node ライブラリ<200>,ビルド<95>,Core and Builtins<197>,Python 3 5 0 beta 4
@anchor{whatsnew/changelog id1031}@anchor{1f8a}
@subsubsection ライブラリ



@itemize -

@item 
bpo-23441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23441}: rcompleter now prints a tab character instead of displaying
possible completions for an empty word.  Initial patch by Martin Sekera.

@item 
bpo-24683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24683}: Fixed crashes in _json functions called with arguments of
inappropriate type.

@item 
bpo-21697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21697}: shutil.copytree() now correctly handles symbolic links that
point to directories.  Patch by Eduardo Seabra and Thomas Kluyver.

@item 
bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}: Fixed segmentation fault when gc.collect() is called during
constructing lru_cache (C implementation).

@item 
bpo-24695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24695}: Fix a regression in traceback.print_exception().  If
exc_traceback is None we shouldn't print a traceback header like described
in the documentation.

@item 
bpo-24620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24620}: Random.setstate() now validates the value of state last
element.

@item 
bpo-22485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22485}: Fixed an issue that caused @code{inspect.getsource} to return
incorrect results on nested functions.

@item 
bpo-22153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22153}: Improve unittest docs. Patch from Martin Panter and evilzero.

@item 
bpo-24580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24580}: Symbolic group references to open group in re patterns now are
explicitly forbidden as well as numeric group references.

@item 
bpo-24206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24206}: Fixed __eq__ and __ne__ methods of inspect classes.

@item 
bpo-24631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24631}: Fixed regression in the timeit module with multiline setup.

@item 
bpo-18622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18622}: unittest.mock.mock_open().reset_mock would recurse infinitely.
Patch from Nicola Palumbo and Laurent De Buyst.

@item 
bpo-23661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23661}: unittest.mock side_effects can now be exceptions again. This
was a regression vs Python 3.4. Patch from Ignacio Rossi

@item 
bpo-24608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24608}: chunk.Chunk.read() now always returns bytes, not str.

@item 
bpo-18684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18684}: Fixed reading out of the buffer in the re module.

@item 
bpo-24259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24259}: tarfile now raises a ReadError if an archive is truncated
inside a data segment.

@item 
bpo-15014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15014}: SMTP.auth() and SMTP.login() now support RFC 4954's optional
initial-response argument to the SMTP AUTH command.

@item 
bpo-24669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24669}: Fix inspect.getsource() for 'async def' functions. Patch by Kai
Groner.

@item 
bpo-24688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24688}: ast.get_docstring() for 'async def' functions.
@end itemize

@node ビルド<95>,,ライブラリ<200>,Python 3 5 0 beta 4
@anchor{whatsnew/changelog id1032}@anchor{1f8b}
@subsubsection ビルド



@itemize -

@item 
bpo-24603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24603}: Update Windows builds and OS X 10.5 installer to use OpenSSL
1.0.2d.
@end itemize

@node Python 3 5 0 beta 3,Python 3 5 0 beta 2,Python 3 5 0 beta 4,変更履歴
@anchor{whatsnew/changelog python-3-5-0-beta-3}@anchor{1f8c}
@subsection Python 3.5.0 beta 3


`Release date: 2015-07-05'

@menu
* Core and Builtins: Core and Builtins<198>. 
* ライブラリ: ライブラリ<201>. 
* テスト: テスト<84>. 
* ドキュメント: ドキュメント<83>. 
* ビルド: ビルド<96>. 

@end menu

@node Core and Builtins<198>,ライブラリ<201>,,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id1033}@anchor{1f8d}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24467}: Fixed possible buffer over-read in bytearray. The bytearray
object now always allocates place for trailing null byte and it's buffer
now is always null-terminated.

@item 
Upgrade to Unicode 8.0.0.

@item 
bpo-24345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24345}: Add Py_tp_finalize slot for the stable ABI.

@item 
bpo-24400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24400}: Introduce a distinct type for 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} coroutines; add
types.CoroutineType, inspect.getcoroutinestate,
inspect.getcoroutinelocals; coroutines no longer use CO_GENERATOR flag;
sys.set_coroutine_wrapper works only for 'async def' coroutines;
inspect.iscoroutine no longer uses collections.abc.Coroutine, it's
intended to test for pure 'async def' coroutines only; add new opcode:
GET_YIELD_FROM_ITER; fix generators wrapper used in types.coroutine to be
instance of collections.abc.Generator; collections.abc.Awaitable and
collections.abc.Coroutine can no longer be used to detect generator-based
coroutines--use inspect.isawaitable instead.

@item 
bpo-24450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24450}: Add gi_yieldfrom to generators and cr_await to coroutines.
Contributed by Benno Leslie and Yury Selivanov.

@item 
bpo-19235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19235}: Add new RecursionError exception. Patch by Georg Brandl.
@end itemize

@node ライブラリ<201>,テスト<84>,Core and Builtins<198>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id1034}@anchor{1f8e}
@subsubsection ライブラリ



@itemize -

@item 
bpo-21750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21750}: mock_open.read_data can now be read from each instance, as it
could in Python 3.3.

@item 
bpo-24552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24552}: Fix use after free in an error case of the _pickle module.

@item 
bpo-24514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24514}: tarfile now tolerates number fields consisting of only
whitespace.

@item 
bpo-19176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19176}: Fixed doctype() related bugs in C implementation of
ElementTree. A deprecation warning no longer issued by XMLParser subclass
with default doctype() method.  Direct call of doctype() now issues a
warning.  Parser's doctype() now is not called if target's doctype() is
called.  Based on patch by Martin Panter.

@item 
bpo-20387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20387}: Restore semantic round-trip correctness in tokenize/untokenize
for tab-indented blocks.

@item 
bpo-24456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24456}: Fixed possible buffer over-read in adpcm2lin() and lin2adpcm()
functions of the audioop module.

@item 
bpo-24336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24336}: The contextmanager decorator now works with functions with
keyword arguments called "func" and "self".  Patch by Martin Panter.

@item 
bpo-24522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24522}: Fix possible integer overflow in json accelerator module.

@item 
bpo-24489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24489}: ensure a previously set C errno doesn't disturb cmath.polar().

@item 
bpo-24408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24408}: Fixed AttributeError in measure() and metrics() methods of
tkinter.Font.

@item 
bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}: C implementation of functools.lru_cache() now can be used with
methods.

@item 
bpo-24347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24347}: Set KeyError if PyDict_GetItemWithError returns NULL.

@item 
bpo-24348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24348}: Drop superfluous incref/decref.

@item 
bpo-24359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24359}: Check for changed OrderedDict size during iteration.

@item 
bpo-24368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24368}: Support keyword arguments in OrderedDict methods.

@item 
bpo-24362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24362}: Simplify the C OrderedDict fast nodes resize logic.

@item 
bpo-24377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24377}: Fix a ref leak in OrderedDict.__repr__.

@item 
bpo-24369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24369}: Defend against key-changes during iteration.
@end itemize

@node テスト<84>,ドキュメント<83>,ライブラリ<201>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id1035}@anchor{1f8f}
@subsubsection テスト



@itemize -

@item 
bpo-24373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24373}: _testmultiphase and xxlimited now use tp_traverse and
tp_finalize to avoid reference leaks encountered when combining tp_dealloc
with PyType_FromSpec (see bpo-16690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16690} for details)
@end itemize

@node ドキュメント<83>,ビルド<96>,テスト<84>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id1036}@anchor{1f90}
@subsubsection ドキュメント



@itemize -

@item 
bpo-24458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24458}: Update documentation to cover multi-phase initialization for
extension modules (PEP 489). Patch by Petr Viktorin.

@item 
bpo-24351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24351}: Clarify what is meant by "identifier" in the context of
string.Template instances.
@end itemize

@node ビルド<96>,,ドキュメント<83>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id1037}@anchor{1f91}
@subsubsection ビルド



@itemize -

@item 
bpo-24432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24432}: Update Windows builds and OS X 10.5 installer to use OpenSSL
1.0.2c.
@end itemize

@node Python 3 5 0 beta 2,Python 3 5 0 beta 1,Python 3 5 0 beta 3,変更履歴
@anchor{whatsnew/changelog python-3-5-0-beta-2}@anchor{1f92}
@subsection Python 3.5.0 beta 2


`Release date: 2015-05-31'

@menu
* Core and Builtins: Core and Builtins<199>. 
* ライブラリ: ライブラリ<202>. 

@end menu

@node Core and Builtins<199>,ライブラリ<202>,,Python 3 5 0 beta 2
@anchor{whatsnew/changelog id1038}@anchor{1f93}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24284}: The startswith and endswith methods of the str class no longer
return True when finding the empty string and the indexes are completely
out of range.

@item 
bpo-24115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24115}: Update uses of PyObject_IsTrue(), PyObject_Not(),
PyObject_IsInstance(), PyObject_RichCompareBool() and _PyDict_Contains()
to check for and handle errors correctly.

@item 
bpo-24328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24328}: Fix importing one character extension modules.

@item 
bpo-11205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11205}: In dictionary displays, evaluate the key before the value.

@item 
bpo-24285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24285}: Fixed regression that prevented importing extension modules
from inside packages. Patch by Petr Viktorin.
@end itemize

@node ライブラリ<202>,,Core and Builtins<199>,Python 3 5 0 beta 2
@anchor{whatsnew/changelog id1039}@anchor{1f94}
@subsubsection ライブラリ



@itemize -

@item 
bpo-23247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23247}: Fix a crash in the StreamWriter.reset() of CJK codecs.

@item 
bpo-24270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24270}: Add math.isclose() and cmath.isclose() functions as per
@geindex Python Enhancement Proposals; PEP 485
PEP 485@footnote{https://peps.python.org/pep-0485/}. Contributed by Chris Barker and Tal Einat.

@item 
bpo-5633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5633}: Fixed timeit when the statement is a string and the setup is
not.

@item 
bpo-24326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24326}: Fixed audioop.ratecv() with non-default weightB argument.
Original patch by David Moore.

@item 
bpo-16991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16991}: Add a C implementation of OrderedDict.

@item 
bpo-23934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23934}: Fix inspect.signature to fail correctly for builtin types
lacking signature information.  Initial patch by James Powell.
@end itemize

@node Python 3 5 0 beta 1,Python 3 5 0 alpha 4,Python 3 5 0 beta 2,変更履歴
@anchor{whatsnew/changelog python-3-5-0-beta-1}@anchor{1f95}
@subsection Python 3.5.0 beta 1


`Release date: 2015-05-24'

@menu
* Core and Builtins: Core and Builtins<200>. 
* ライブラリ: ライブラリ<203>. 
* IDLE: IDLE<62>. 
* テスト: テスト<85>. 
* ドキュメント: ドキュメント<84>. 
* Tools/Demos: Tools/Demos<58>. 

@end menu

@node Core and Builtins<200>,ライブラリ<203>,,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id1040}@anchor{1f96}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24276}: Fixed optimization of property descriptor getter.

@item 
bpo-24268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24268}: PEP 489: Multi-phase extension module initialization. Patch by
Petr Viktorin.

@item 
bpo-23955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23955}: Add pyvenv.cfg option to suppress registry/environment lookup
for generating sys.path on Windows.

@item 
bpo-24257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24257}: Fixed system error in the comparison of faked
types.SimpleNamespace.

@item 
bpo-22939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22939}: Fixed integer overflow in iterator object.  Patch by Clement
Rouault.

@item 
bpo-23985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23985}: Fix a possible buffer overrun when deleting a slice from the
front of a bytearray and then appending some other bytes data.

@item 
bpo-24102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24102}: Fixed exception type checking in standard error handlers.

@item 
bpo-15027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15027}: The UTF-32 encoder is now 3x to 7x faster.

@item 
bpo-23290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23290}: Optimize set_merge() for cases where the target is empty.
(Contributed by Serhiy Storchaka.)

@item 
bpo-2292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2292}: PEP 448: Additional Unpacking Generalizations.

@item 
bpo-24096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24096}: Make warnings.warn_explicit more robust against mutation of the
warnings.filters list.

@item 
bpo-23996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23996}: Avoid a crash when a delegated generator raises an unnormalized
StopIteration exception.  Patch by Stefan Behnel.

@item 
bpo-23910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23910}: Optimize property() getter calls.  Patch by Joe Jevnik.

@item 
bpo-23911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23911}: Move path-based importlib bootstrap code to a separate frozen
module.

@item 
bpo-24192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24192}: Fix namespace package imports.

@item 
bpo-24022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24022}: Fix tokenizer crash when processing undecodable source code.

@item 
bpo-9951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9951}: Added a hex() method to bytes, bytearray, and memoryview.

@item 
bpo-22906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22906}: PEP 479: Change StopIteration handling inside generators.

@item 
bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017}: PEP 492: Coroutines with async and await syntax.
@end itemize

@node ライブラリ<203>,IDLE<62>,Core and Builtins<200>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id1041}@anchor{1f97}
@subsubsection ライブラリ



@itemize -

@item 
bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}: Added C implementation of functools.lru_cache().  Based on
patches by Matt Joiner and Alexey Kachayev.

@item 
bpo-24230@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24230}: The tempfile module now accepts bytes for prefix, suffix and
dir parameters and returns bytes in such situations (matching the os
module APIs).

@item 
bpo-22189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22189}: collections.UserString now supports __getnewargs__(),
__rmod__(), casefold(), format_map(), isprintable(), and maketrans().
Patch by Joe Jevnik.

@item 
bpo-24244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24244}: Prevents termination when an invalid format string is
encountered on Windows in strftime.

@item 
bpo-23973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23973}: PEP 484: Add the typing module.

@item 
bpo-23086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23086}: The collections.abc.Sequence() abstract base class added
`start' and `stop' parameters to the index() mixin. Patch by Devin
Jeanpierre.

@item 
bpo-20035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20035}: Replaced the @code{tkinter._fix} module used for setting up the
Tcl/Tk environment on Windows with a private function in the @code{_tkinter}
module that makes no permanent changes to the environment.

@item 
bpo-24257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24257}: Fixed segmentation fault in sqlite3.Row constructor with faked
cursor type.

@item 
bpo-15836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15836}: assertRaises(), assertRaisesRegex(), assertWarns() and
assertWarnsRegex() assertments now check the type of the first argument to
prevent possible user error.  Based on patch by Daniel Wagner-Hall.

@item 
bpo-9858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9858}: Add missing method stubs to _io.RawIOBase.  Patch by Laura
Rupprecht.

@item 
bpo-22955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22955}: attrgetter, itemgetter and methodcaller objects in the operator
module now support pickling.  Added readable and evaluable repr for these
objects. Based on patch by Josh Rosenberg.

@item 
bpo-22107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22107}: tempfile.gettempdir() and tempfile.mkdtemp() now try again when
a directory with the chosen name already exists on Windows as well as on
Unix. tempfile.mkstemp() now fails early if parent directory is not valid
(not exists or is a file) on Windows.

@item 
bpo-23780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23780}: Improved error message in os.path.join() with single argument.

@item 
bpo-6598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6598}: Increased time precision and random number range in
email.utils.make_msgid() to strengthen the uniqueness of the message ID.

@item 
bpo-24091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24091}: Fixed various crashes in corner cases in C implementation of
ElementTree.

@item 
bpo-21931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21931}: msilib.FCICreate() now raises TypeError in the case of a bad
argument instead of a ValueError with a bogus FCI error number. Patch by
Jeffrey Armstrong.

@item 
bpo-13866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13866}: `quote_via' argument added to urllib.parse.urlencode.

@item 
bpo-20098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20098}: New mangle_from policy option for email, default True for
compat32, but False for all other policies.

@item 
bpo-24211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24211}: The email library now supports RFC 6532: it can generate
headers using utf-8 instead of encoded words.

@item 
bpo-16314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16314}: Added support for the LZMA compression in distutils.

@item 
bpo-21804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21804}: poplib now supports RFC 6856 (UTF8).

@item 
bpo-18682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18682}: Optimized pprint functions for builtin scalar types.

@item 
bpo-22027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22027}: smtplib now supports RFC 6531 (SMTPUTF8).

@item 
bpo-23488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23488}: Random generator objects now consume 2x less memory on 64-bit.

@item 
bpo-1322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1322}: platform.dist() and platform.linux_distribution() functions are
now deprecated.  Initial patch by Vajrasky Kok.

@item 
bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486}: Added the math.gcd() function.  The fractions.gcd() function
now is deprecated.  Based on patch by Mark Dickinson.

@item 
bpo-24064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24064}: Property() docstrings are now writeable. (Patch by Berker
Peksag.)

@item 
bpo-22681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22681}: Added support for the koi8_t encoding.

@item 
bpo-22682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22682}: Added support for the kz1048 encoding.

@item 
bpo-23796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23796}: peek and read1 methods of BufferedReader now raise ValueError
if they called on a closed object. Patch by John Hergenroeder.

@item 
bpo-21795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21795}: smtpd now supports the 8BITMIME extension whenever the new
`decode_data' constructor argument is set to False.

@item 
bpo-24155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24155}: optimize heapq.heapify() for better cache performance when
heapifying large lists.

@item 
bpo-21800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21800}: imaplib now supports RFC 5161 (enable), RFC 6855
(utf8/internationalized email) and automatically encodes non-ASCII
usernames and passwords to UTF8.

@item 
bpo-20274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20274}: When calling a _sqlite.Connection, it now complains if passed
any keyword arguments.  Previously it silently ignored them.

@item 
bpo-20274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20274}: Remove ignored and erroneous "kwargs" parameters from three
METH_VARARGS methods on _sqlite.Connection.

@item 
bpo-24134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24134}: assertRaises(), assertRaisesRegex(), assertWarns() and
assertWarnsRegex() checks now emits a deprecation warning when callable is
None or keyword arguments except msg is passed in the context manager
mode.

@item 
bpo-24018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24018}: Add a collections.abc.Generator abstract base class.
Contributed by Stefan Behnel.

@item 
bpo-23880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23880}: Tkinter's getint() and getdouble() now support Tcl_Obj.
Tkinter's getdouble() now supports any numbers (in particular int).

@item 
bpo-22619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22619}: Added negative limit support in the traceback module. Based on
patch by Dmitry Kazakov.

@item 
bpo-24094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24094}: Fix possible crash in json.encode with poorly behaved dict
subclasses.

@item 
bpo-9246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9246}: On POSIX, os.getcwd() now supports paths longer than 1025 bytes.
Patch written by William Orr.

@item 
bpo-17445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17445}: add difflib.diff_bytes() to support comparison of byte strings
(fixes a regression from Python 2).

@item 
bpo-23917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23917}: Fall back to sequential compilation when ProcessPoolExecutor
doesn't exist. Patch by Claudiu Popa.

@item 
bpo-23008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23008}: Fixed resolving attributes with boolean value is False in
pydoc.

@item 
Fix asyncio issue 235: LifoQueue and PriorityQueue's put didn't increment
unfinished tasks (this bug was introduced when JoinableQueue was merged
with Queue).

@item 
bpo-23908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23908}: os functions now reject paths with embedded null character on
Windows instead of silently truncating them.

@item 
bpo-23728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23728}: binascii.crc_hqx() could return an integer outside of the range
0-0xffff for empty data.

@item 
bpo-23887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23887}: urllib.error.HTTPError now has a proper repr() representation.
Patch by Berker Peksag.

@item 
asyncio: New event loop APIs: set_task_factory() and get_task_factory().

@item 
asyncio: async() function is deprecated in favour of ensure_future().

@item 
bpo-24178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24178}: asyncio.Lock, Condition, Semaphore, and BoundedSemaphore
support new 'async with' syntax.  Contributed by Yury Selivanov.

@item 
bpo-24179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24179}: Support 'async for' for asyncio.StreamReader. Contributed by
Yury Selivanov.

@item 
bpo-24184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24184}: Add AsyncIterator and AsyncIterable ABCs to collections.abc.
Contributed by Yury Selivanov.

@item 
bpo-22547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22547}: Implement informative __repr__ for inspect.BoundArguments.
Contributed by Yury Selivanov.

@item 
bpo-24190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24190}: Implement inspect.BoundArgument.apply_defaults() method.
Contributed by Yury Selivanov.

@item 
bpo-20691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20691}: Add 'follow_wrapped' argument to
inspect.Signature.from_callable() and inspect.signature(). Contributed by
Yury Selivanov.

@item 
bpo-24248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24248}: Deprecate inspect.Signature.from_function() and
inspect.Signature.from_builtin().

@item 
bpo-23898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23898}: Fix inspect.classify_class_attrs() to support attributes with
overloaded __eq__ and __bool__.  Patch by Mike Bayer.

@item 
bpo-24298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24298}: Fix inspect.signature() to correctly unwrap wrappers around
bound methods.
@end itemize

@node IDLE<62>,テスト<85>,ライブラリ<203>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id1042}@anchor{1f98}
@subsubsection IDLE



@itemize -

@item 
bpo-23184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23184}: remove unused names and imports in idlelib. Initial patch by Al
Sweigart.
@end itemize

@node テスト<85>,ドキュメント<84>,IDLE<62>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id1043}@anchor{1f99}
@subsubsection テスト



@itemize -

@item 
bpo-21520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21520}: test_zipfile no longer fails if the word 'bad' appears anywhere
in the name of the current directory.

@item 
bpo-9517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9517}: Move script_helper into the support package. Patch by Christie
Wilson.
@end itemize

@node ドキュメント<84>,Tools/Demos<58>,テスト<85>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id1044}@anchor{1f9a}
@subsubsection ドキュメント



@itemize -

@item 
bpo-22155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22155}: Add File Handlers subsection with createfilehandler to tkinter
doc.  Remove obsolete example from FAQ.  Patch by Martin Panter.

@item 
bpo-24029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24029}: Document the name binding behavior for submodule imports.

@item 
bpo-24077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24077}: Fix typo in man page for -I command option: -s, not -S
@end itemize

@node Tools/Demos<58>,,ドキュメント<84>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id1045}@anchor{1f9b}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-24000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24000}: Improved Argument Clinic's mapping of converters to legacy
"format units". Updated the documentation to match.

@item 
bpo-24001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24001}: Argument Clinic converters now use accept=@{type@} instead of
types=@{'type'@} to specify the types the converter accepts.

@item 
bpo-23330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23330}: h2py now supports arbitrary filenames in #include.

@item 
bpo-24031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24031}: make patchcheck now supports git checkouts, too.
@end itemize

@node Python 3 5 0 alpha 4,Python 3 5 0 alpha 3,Python 3 5 0 beta 1,変更履歴
@anchor{whatsnew/changelog python-3-5-0-alpha-4}@anchor{1f9c}
@subsection Python 3.5.0 alpha 4


`Release date: 2015-04-19'

@menu
* Core and Builtins: Core and Builtins<201>. 
* ライブラリ: ライブラリ<204>. 
* ビルド: ビルド<97>. 
* テスト: テスト<86>. 
* Tools/Demos: Tools/Demos<59>. 
* C API: C API<77>. 

@end menu

@node Core and Builtins<201>,ライブラリ<204>,,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id1046}@anchor{1f9d}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-22980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22980}: Under Linux, GNU/KFreeBSD and the Hurd, C extensions now
include the architecture triplet in the extension name, to make it easy to
test builds for different ABIs in the same working tree.  Under OS X, the
extension name now includes 
@geindex Python Enhancement Proposals; PEP 3149
PEP 3149@footnote{https://peps.python.org/pep-3149/}-style information.

@item 
bpo-22631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22631}: Added Linux-specific socket constant CAN_RAW_FD_FRAMES. Patch
courtesy of Joe Jevnik.

@item 
bpo-23731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23731}: Implement 
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/}: removal of .pyo files.

@item 
bpo-23726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23726}: Don't enable GC for user subclasses of non-GC types that don't
add any new fields.  Patch by Eugene Toder.

@item 
bpo-23309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23309}: Avoid a deadlock at shutdown if a daemon thread is aborted
while it is holding a lock to a buffered I/O object, and the main thread
tries to use the same I/O object (typically stdout or stderr).  A fatal
error is emitted instead.

@item 
bpo-22977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22977}: Fixed formatting Windows error messages on Wine. Patch by
Martin Panter.

@item 
bpo-23466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23466}: %c, %o, %x, and %X in bytes formatting now raise TypeError on
non-integer input.

@item 
bpo-24044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24044}: Fix possible null pointer dereference in list.sort in out of
memory conditions.

@item 
bpo-21354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21354}: PyCFunction_New function is exposed by python DLL again.
@end itemize

@node ライブラリ<204>,ビルド<97>,Core and Builtins<201>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id1047}@anchor{1f9e}
@subsubsection ライブラリ



@itemize -

@item 
bpo-23840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23840}: tokenize.open() now closes the temporary binary file on error
to fix a resource warning.

@item 
bpo-16914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16914}: new debuglevel 2 in smtplib adds timestamps to debug output.

@item 
bpo-7159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7159}: urllib.request now supports sending auth credentials
automatically after the first 401.  This enhancement is a superset of the
enhancement from bpo-19494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19494} and supersedes that change.

@item 
bpo-23703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23703}: Fix a regression in urljoin() introduced in 901e4e52b20a. Patch
by Demian Brecht.

@item 
bpo-4254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4254}: Adds _curses.update_lines_cols().  Patch by Arnon Yaari

@item 
bpo-19933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19933}: Provide default argument for ndigits in round. Patch by
Vajrasky Kok.

@item 
bpo-23193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23193}: Add a numeric_owner parameter to tarfile.TarFile.extract and
tarfile.TarFile.extractall. Patch by Michael Vogt and Eric Smith.

@item 
bpo-23342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23342}: Add a subprocess.run() function than returns a CalledProcess
instance for a more consistent API than the existing call* functions.

@item 
bpo-21217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21217}: inspect.getsourcelines() now tries to compute the start and end
lines from the code object, fixing an issue when a lambda function is used
as decorator argument. Patch by Thomas Ballinger and Allison Kaptur.

@item 
bpo-24521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24521}: Fix possible integer overflows in the pickle module.

@item 
bpo-22931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22931}: Allow '[' and ']' in cookie values.

@item 
The keywords attribute of functools.partial is now always a dictionary.

@item 
bpo-23811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23811}: Add missing newline to the PyCompileError error message. Patch
by Alex Shkop.

@item 
bpo-21116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21116}: Avoid blowing memory when allocating a multiprocessing shared
array that's larger than 50% of the available RAM.  Patch by Médéric
Boquien.

@item 
bpo-22982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22982}: Improve BOM handling when seeking to multiple positions of a
writable text file.

@item 
bpo-23464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23464}: Removed deprecated asyncio JoinableQueue.

@item 
bpo-23529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23529}: Limit the size of decompressed data when reading from GzipFile,
BZ2File or LZMAFile.  This defeats denial of service attacks using
compressed bombs (i.e. compressed payloads which decompress to a huge
size).  Patch by Martin Panter and Nikolaus Rath.

@item 
bpo-21859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21859}: Added Python implementation of io.FileIO.

@item 
bpo-23865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23865}: close() methods in multiple modules now are idempotent and more
robust at shutdown. If they need to release multiple resources, all are
released even if errors occur.

@item 
bpo-23400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23400}: Raise same exception on both Python 2 and 3 if sem_open is not
available. Patch by Davin Potts.

@item 
bpo-10838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10838}: The subprocess now module includes SubprocessError and
TimeoutError in its list of exported names for the users wild enough to
use @code{from subprocess import *}.

@item 
bpo-23411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23411}: Added DefragResult, ParseResult, SplitResult,
DefragResultBytes, ParseResultBytes, and SplitResultBytes to
urllib.parse.__all__. Patch by Martin Panter.

@item 
bpo-23881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23881}: urllib.request.ftpwrapper constructor now closes the socket if
the FTP connection failed to fix a ResourceWarning.

@item 
bpo-23853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23853}: @ref{fa8,,socket.socket.sendall()} does no more reset the socket
timeout each time data is sent successfully. The socket timeout is now the
maximum total duration to send all data.

@item 
bpo-22721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22721}: An order of multiline pprint output of set or dict containing
orderable and non-orderable elements no longer depends on iteration order
of set or dict.

@item 
bpo-15133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15133}: _tkinter.tkapp.getboolean() now supports Tcl_Obj and always
returns bool. tkinter.BooleanVar now validates input values (accepted
bool, int, str, and Tcl_Obj).  tkinter.BooleanVar.get() now always returns
bool.

@item 
bpo-10590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10590}: xml.sax.parseString() now supports string argument.

@item 
bpo-23338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23338}: Fixed formatting ctypes error messages on Cygwin. Patch by
Makoto Kato.

@item 
bpo-15582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15582}: inspect.getdoc() now follows inheritance chains.

@item 
bpo-2175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2175}: SAX parsers now support a character stream of InputSource
object.

@item 
bpo-16840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16840}: Tkinter now supports 64-bit integers added in Tcl 8.4 and
arbitrary precision integers added in Tcl 8.5.

@item 
bpo-23834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23834}: Fix socket.sendto(), use the C Py_ssize_t type to store the
result of sendto() instead of the C int type.

@item 
bpo-23618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23618}: @ref{fa3,,socket.socket.connect()} now waits until the connection
completes instead of raising @ref{f88,,InterruptedError} if the connection is
interrupted by signals, signal handlers don't raise an exception and the
socket is blocking or has a timeout. @ref{fa3,,socket.socket.connect()} still
raise @ref{f88,,InterruptedError} for non-blocking sockets.

@item 
bpo-21526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21526}: Tkinter now supports new boolean type in Tcl 8.5.

@item 
bpo-23836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23836}: Fix the faulthandler module to handle reentrant calls to its
signal handlers.

@item 
bpo-23838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23838}: linecache now clears the cache and returns an empty result on
MemoryError.

@item 
bpo-10395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10395}: Added os.path.commonpath(). Implemented in posixpath and
ntpath. Based on patch by Rafik Draoui.

@item 
bpo-23611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23611}: Serializing more "lookupable" objects (such as unbound methods
or nested classes) now are supported with pickle protocols < 4.

@item 
bpo-13583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13583}: sqlite3.Row now supports slice indexing.

@item 
bpo-18473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18473}: Fixed 2to3 and 3to2 compatible pickle mappings.  Fixed
ambiguous reverse mappings.  Added many new mappings.  Import mapping is
no longer applied to modules already mapped with full name mapping.

@item 
bpo-23485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23485}: select.select() is now retried automatically with the
recomputed timeout when interrupted by a signal, except if the signal
handler raises an exception. This change is part of the 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/}.

@item 
bpo-23752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23752}: When built from an existing file descriptor, io.FileIO() now
only calls fstat() once. Before fstat() was called twice, which was not
necessary.

@item 
bpo-23704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23704}: collections.deque() objects now support __add__, __mul__, and
__imul__().

@item 
bpo-23171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23171}: csv.Writer.writerow() now supports arbitrary iterables.

@item 
bpo-23745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23745}: The new email header parser now handles duplicate MIME
parameter names without error, similar to how get_param behaves.

@item 
bpo-22117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22117}: Fix os.utime(), it now rounds the timestamp towards minus
infinity (-inf) instead of rounding towards zero.

@item 
bpo-23310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23310}: Fix MagicMock's initializer to work with __methods__, just like
configure_mock().  Patch by Kasia Jachim.
@end itemize

@node ビルド<97>,テスト<86>,ライブラリ<204>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id1048}@anchor{1f9f}
@subsubsection ビルド



@itemize -

@item 
bpo-23817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23817}: FreeBSD now uses "1.0" in the SOVERSION as other operating
systems, instead of just "1".

@item 
bpo-23501@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23501}: Argument Clinic now generates code into separate files by
default.
@end itemize

@node テスト<86>,Tools/Demos<59>,ビルド<97>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id1049}@anchor{1fa0}
@subsubsection テスト



@itemize -

@item 
bpo-23799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23799}: Added test.support.start_threads() for running and cleaning up
multiple threads.

@item 
bpo-22390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22390}: test.regrtest now emits a warning if temporary files or
directories are left after running a test.
@end itemize

@node Tools/Demos<59>,C API<77>,テスト<86>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id1050}@anchor{1fa1}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-18128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18128}: pygettext now uses standard +NNNN format in the
POT-Creation-Date header.

@item 
bpo-23935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23935}: Argument Clinic's understanding of format units accepting
bytes, bytearrays, and buffers is now consistent with both the
documentation and the implementation.

@item 
bpo-23944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23944}: Argument Clinic now wraps long impl prototypes at column 78.

@item 
bpo-20586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20586}: Argument Clinic now ensures that functions without docstrings
have signatures.

@item 
bpo-23492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23492}: Argument Clinic now generates argument parsing code with
PyArg_Parse instead of PyArg_ParseTuple if possible.

@item 
bpo-23500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23500}: Argument Clinic is now smarter about generating the "#ifndef"
(empty) definition of the methoddef macro: it's only generated once, even
if Argument Clinic processes the same symbol multiple times, and it's
emitted at the end of all processing rather than immediately after the
first use.
@end itemize

@node C API<77>,,Tools/Demos<59>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id1051}@anchor{1fa2}
@subsubsection C API



@itemize -

@item 
bpo-23998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23998}: PyImport_ReInitLock() now checks for lock allocation error
@end itemize

@node Python 3 5 0 alpha 3,Python 3 5 0 alpha 2,Python 3 5 0 alpha 4,変更履歴
@anchor{whatsnew/changelog python-3-5-0-alpha-3}@anchor{1fa3}
@subsection Python 3.5.0 alpha 3


`Release date: 2015-03-28'

@menu
* Core and Builtins: Core and Builtins<202>. 
* ライブラリ: ライブラリ<205>. 
* ビルド: ビルド<98>. 
* テスト: テスト<87>. 
* Tools/Demos: Tools/Demos<60>. 

@end menu

@node Core and Builtins<202>,ライブラリ<205>,,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id1052}@anchor{1fa4}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23573}: Increased performance of string search operations (str.find,
str.index, str.count, the in operator, str.split, str.partition) with
arguments of different kinds (UCS1, UCS2, UCS4).

@item 
bpo-23753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23753}: Python doesn't support anymore platforms without stat() or
fstat(), these functions are always required.

@item 
bpo-23681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23681}: The -b option now affects comparisons of bytes with int.

@item 
bpo-23632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23632}: Memoryviews now allow tuple indexing (including for
multi-dimensional memoryviews).

@item 
bpo-23192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23192}: Fixed generator lambdas.  Patch by Bruno Cauet.

@item 
bpo-23629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23629}: Fix the default __sizeof__ implementation for variable-sized
objects.
@end itemize

@node ライブラリ<205>,ビルド<98>,Core and Builtins<202>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id1053}@anchor{1fa5}
@subsubsection ライブラリ



@itemize -

@item 
bpo-14260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14260}: The groupindex attribute of regular expression pattern object
now is non-modifiable mapping.

@item 
bpo-23792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23792}: Ignore KeyboardInterrupt when the pydoc pager is active. This
mimics the behavior of the standard unix pagers, and prevents pipepager
from shutting down while the pager itself is still running.

@item 
bpo-23775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23775}: pprint() of OrderedDict now outputs the same representation as
repr().

@item 
bpo-23765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23765}: Removed IsBadStringPtr calls in ctypes

@item 
bpo-22364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22364}: Improved some re error messages using regex for hints.

@item 
bpo-23742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23742}: ntpath.expandvars() no longer loses unbalanced single quotes.

@item 
bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}: The zipfile.ZipFile.open function now supports 'x' (exclusive
creation) mode.

@item 
bpo-21802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21802}: The reader in BufferedRWPair now is closed even when closing
writer failed in BufferedRWPair.close().

@item 
bpo-23622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23622}: Unknown escapes in regular expressions that consist of @code{'\'}
and ASCII letter now raise a deprecation warning and will be forbidden in
Python 3.6.

@item 
bpo-23671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23671}: string.Template now allows specifying the "self" parameter as a
keyword argument.  string.Formatter now allows specifying the "self" and
the "format_string" parameters as keyword arguments.

@item 
bpo-23502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23502}: The pprint module now supports mapping proxies.

@item 
bpo-17530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17530}: pprint now wraps long bytes objects and bytearrays.

@item 
bpo-22687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22687}: Fixed some corner cases in breaking words in tetxtwrap. Got rid
of quadratic complexity in breaking long words.

@item 
bpo-4727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4727}: The copy module now uses pickle protocol 4 (PEP 3154) and
supports copying of instances of classes whose __new__ method takes
keyword-only arguments.

@item 
bpo-23491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23491}: Added a zipapp module to support creating executable zip file
archives of Python code. Registered ".pyz" and ".pyzw" extensions on
Windows for these archives (PEP 441).

@item 
bpo-23657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23657}: Avoid explicit checks for str in zipapp, adding support for
pathlib.Path objects as arguments.

@item 
bpo-23688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23688}: Added support of arbitrary bytes-like objects and avoided
unnecessary copying of memoryview in gzip.GzipFile.write(). Original patch
by Wolfgang Maier.

@item 
bpo-23252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23252}: Added support for writing ZIP files to unseekable streams.

@item 
bpo-23647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23647}: Increase imaplib's MAXLINE to accommodate modern mailbox sizes.

@item 
bpo-23539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23539}: If body is None, http.client.HTTPConnection.request now sets
Content-Length to 0 for PUT, POST, and PATCH headers to avoid 411 errors
from some web servers.

@item 
bpo-22351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22351}: The nntplib.NNTP constructor no longer leaves the connection
and socket open until the garbage collector cleans them up.  Patch by
Martin Panter.

@item 
bpo-23704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23704}: collections.deque() objects now support methods for index(),
insert(), and copy().  This allows deques to be registered as a
MutableSequence and it improves their substitutability for lists.

@item 
bpo-23715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23715}: @ref{fab,,signal.sigwaitinfo()} and @ref{faa,,signal.sigtimedwait()} 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.

@item 
bpo-23001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23001}: Few functions in modules mmap, ossaudiodev, socket, ssl, and
codecs, that accepted only read-only bytes-like object now accept writable
bytes-like object too.

@item 
bpo-23646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23646}: If time.sleep() is interrupted by a signal, the sleep is now
retried with the recomputed delay, except if the signal handler raises an
exception (PEP 475).

@item 
bpo-23136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23136}: _strptime now uniformly handles all days in week 0, including
Dec 30 of previous year.  Based on patch by Jim Carroll.

@item 
bpo-23700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23700}: Iterator of NamedTemporaryFile now keeps a reference to
NamedTemporaryFile instance.  Patch by Bohuslav Kabrda.

@item 
bpo-22903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22903}: The fake test case created by unittest.loader when it fails
importing a test module is now picklable.

@item 
bpo-22181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22181}: On Linux, os.urandom() now uses the new getrandom() syscall if
available, syscall introduced in the Linux kernel 3.17. It is more
reliable and more secure, because it avoids the need of a file descriptor
and waits until the kernel has enough entropy.

@item 
bpo-2211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2211}: Updated the implementation of the http.cookies.Morsel class.
Setting attributes key, value and coded_value directly now is deprecated.
update() and setdefault() now transform and check keys.  Comparing for
equality now takes into account attributes key, value and coded_value.
copy() now returns a Morsel, not a dict.  repr() now contains all
attributes. Optimized checking keys and quoting values.  Added new tests.
Original patch by Demian Brecht.

@item 
bpo-18983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18983}: Allow selection of output units in timeit. Patch by Julian
Gindi.

@item 
bpo-23631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23631}: Fix traceback.format_list when a traceback has been mutated.

@item 
bpo-23568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23568}: Add rdivmod support to MagicMock() objects. Patch by Håkan
Lövdahl.

@item 
bpo-2052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2052}: Add charset parameter to HtmlDiff.make_file().

@item 
bpo-23668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23668}: Support os.truncate and os.ftruncate on Windows.

@item 
bpo-23138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23138}: Fixed parsing cookies with absent keys or values in cookiejar.
Patch by Demian Brecht.

@item 
bpo-23051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23051}: multiprocessing.Pool methods imap() and imap_unordered() now
handle exceptions raised by an iterator.  Patch by Alon Diamant and Davin
Potts.

@item 
bpo-23581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23581}: Add matmul support to MagicMock. Patch by Håkan Lövdahl.

@item 
bpo-23566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23566}: enable(), register(), dump_traceback() and
dump_traceback_later() functions of faulthandler now accept file
descriptors. Patch by Wei Wu.

@item 
bpo-22928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22928}: Disabled HTTP header injections in http.client. Original patch
by Demian Brecht.

@item 
bpo-23615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23615}: Modules bz2, tarfile and tokenize now can be reloaded with
imp.reload(). Patch by Thomas Kluyver.

@item 
bpo-23605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23605}: os.walk() now calls os.scandir() instead of os.listdir(). The
usage of os.scandir() reduces the number of calls to os.stat(). Initial
patch written by Ben Hoyt.
@end itemize

@node ビルド<98>,テスト<87>,ライブラリ<205>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id1054}@anchor{1fa6}
@subsubsection ビルド



@itemize -

@item 
bpo-23585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23585}: make patchcheck will ensure the interpreter is built.
@end itemize

@node テスト<87>,Tools/Demos<60>,ビルド<98>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id1055}@anchor{1fa7}
@subsubsection テスト



@itemize -

@item 
bpo-23583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23583}: Added tests for standard IO streams in IDLE.

@item 
bpo-22289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22289}: Prevent test_urllib2net failures due to ftp connection timeout.
@end itemize

@node Tools/Demos<60>,,テスト<87>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id1056}@anchor{1fa8}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-22826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22826}: The result of open() in Tools/freeze/bkfile.py is now better
compatible with regular files (in particular it now supports the context
management protocol).
@end itemize

@node Python 3 5 0 alpha 2,Python 3 5 0 alpha 1,Python 3 5 0 alpha 3,変更履歴
@anchor{whatsnew/changelog python-3-5-0-alpha-2}@anchor{1fa9}
@subsection Python 3.5.0 alpha 2


`Release date: 2015-03-09'

@menu
* Core and Builtins: Core and Builtins<203>. 
* ライブラリ: ライブラリ<206>. 
* ビルド: ビルド<99>. 
* C API: C API<78>. 
* Windows: Windows<82>. 

@end menu

@node Core and Builtins<203>,ライブラリ<206>,,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id1057}@anchor{1faa}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23571}: PyObject_Call() and PyCFunction_Call() now raise a SystemError
if a function returns a result and raises an exception. The SystemError is
chained to the previous exception.
@end itemize

@node ライブラリ<206>,ビルド<99>,Core and Builtins<203>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id1058}@anchor{1fab}
@subsubsection ライブラリ



@itemize -

@item 
bpo-22524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22524}: New os.scandir() function, part of the 
@geindex Python Enhancement Proposals; PEP 471
PEP 471@footnote{https://peps.python.org/pep-0471/}:
"os.scandir() function -- a better and faster directory iterator". Patch
written by Ben Hoyt.

@item 
bpo-23103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23103}: Reduced the memory consumption of IPv4Address and IPv6Address.

@item 
bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}: BaseHTTPRequestHandler again logs response code as numeric, not
as stringified enum.  Patch by Demian Brecht.

@item 
bpo-23476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23476}: In the ssl module, enable OpenSSL's X509_V_FLAG_TRUSTED_FIRST
flag on certificate stores when it is available.

@item 
bpo-23576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23576}: Avoid stalling in SSL reads when EOF has been reached in the
SSL layer but the underlying connection hasn't been closed.

@item 
bpo-23504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23504}: Added an __all__ to the types module.

@item 
bpo-23563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23563}: Optimized utility functions in urllib.parse.

@item 
bpo-7830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7830}: Flatten nested functools.partial.

@item 
bpo-20204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20204}: Added the __module__ attribute to _tkinter classes.

@item 
bpo-19980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19980}: Improved help() for non-recognized strings.  help('@w{'}) now shows
the help on str.  help('help') now shows the help on help(). Original
patch by Mark Lawrence.

@item 
bpo-23521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23521}: Corrected pure python implementation of timedelta division.
Eliminated OverflowError from @code{timedelta * float} for some floats;
Corrected rounding in timedelta true division.

@item 
bpo-21619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21619}: Popen objects no longer leave a zombie after exit in the with
statement if the pipe was broken.  Patch by Martin Panter.

@item 
bpo-22936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22936}: Make it possible to show local variables in tracebacks for both
the traceback module and unittest.

@item 
bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}: Add an option to limit the output size in bz2.decompress().
Patch by Nikolaus Rath.

@item 
bpo-6639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6639}: Module-level turtle functions no longer raise TclError after
closing the window.

@item 
bpo-814253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=814253}: Group references and conditional group references now work in
lookbehind assertions in regular expressions. (See also: bpo-9179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9179})

@item 
bpo-23215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23215}: Multibyte codecs with custom error handlers that ignores errors
consumed too much memory and raised SystemError or MemoryError. Original
patch by Aleksi Torhamo.

@item 
bpo-5700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5700}: io.FileIO() called flush() after closing the file. flush() was
not called in close() if closefd=False.

@item 
bpo-23374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23374}: Fixed pydoc failure with non-ASCII files when stdout encoding
differs from file system encoding (e.g. on Mac OS).

@item 
bpo-23481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23481}: Remove RC4 from the SSL module's default cipher list.

@item 
bpo-21548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21548}: Fix pydoc.synopsis() and pydoc.apropos() on modules with empty
docstrings.

@item 
bpo-22885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22885}: Fixed arbitrary code execution vulnerability in the dbm.dumb
module. Original patch by Claudiu Popa.

@item 
bpo-23239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23239}: ssl.match_hostname() now supports matching of IP addresses.

@item 
bpo-23146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23146}: Fix mishandling of absolute Windows paths with forward slashes
in pathlib.

@item 
bpo-23096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23096}: Pickle representation of floats with protocol 0 now is the same
for both Python and C implementations.

@item 
bpo-19105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19105}: pprint now more efficiently uses free space at the right.

@item 
bpo-14910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14910}: Add allow_abbrev parameter to argparse.ArgumentParser. Patch by
Jonathan Paugh, Steven Bethard, paul j3 and Daniel Eriksson.

@item 
bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}: tarfile.open() now supports 'x' (exclusive creation) mode.

@item 
bpo-23344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23344}: marshal.dumps() is now 20-25% faster on average.

@item 
bpo-20416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20416}: marshal.dumps() with protocols 3 and 4 is now 40-50% faster on
average.

@item 
bpo-23421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23421}: Fixed compression in tarfile CLI.  Patch by wdv4758h.

@item 
bpo-23367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23367}: Fix possible overflows in the unicodedata module.

@item 
bpo-23361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23361}: Fix possible overflow in Windows subprocess creation code.

@item 
logging.handlers.QueueListener now takes a respect_handler_level keyword
argument which, if set to True, will pass messages to handlers taking
handler levels into account.

@item 
bpo-19705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19705}: turtledemo now has a visual sorting algorithm demo.  Original
patch from Jason Yeo.

@item 
bpo-23801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23801}: Fix issue where cgi.FieldStorage did not always ignore the
entire preamble to a multipart body.
@end itemize

@node ビルド<99>,C API<78>,ライブラリ<206>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id1059}@anchor{1fac}
@subsubsection ビルド



@itemize -

@item 
bpo-23445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23445}: pydebug builds now use "gcc -Og" where possible, to make the
resulting executable faster.

@item 
bpo-23686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23686}: Update OS X 10.5 installer build to use OpenSSL 1.0.2a.
@end itemize

@node C API<78>,Windows<82>,ビルド<99>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id1060}@anchor{1fad}
@subsubsection C API



@itemize -

@item 
bpo-20204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20204}: Deprecation warning is now raised for builtin types without the
__module__ attribute.
@end itemize

@node Windows<82>,,C API<78>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id1061}@anchor{1fae}
@subsubsection Windows



@itemize -

@item 
bpo-23465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23465}: Implement 
@geindex Python Enhancement Proposals; PEP 486
PEP 486@footnote{https://peps.python.org/pep-0486/} - Make the Python Launcher aware of
virtual environments. Patch by Paul Moore.

@item 
bpo-23437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23437}: Make user scripts directory versioned on Windows. Patch by Paul
Moore.
@end itemize

@node Python 3 5 0 alpha 1,,Python 3 5 0 alpha 2,変更履歴
@anchor{whatsnew/changelog python-3-5-0-alpha-1}@anchor{1faf}
@subsection Python 3.5.0 alpha 1


`Release date: 2015-02-08'

@menu
* Core and Builtins: Core and Builtins<204>. 
* ライブラリ: ライブラリ<207>. 
* IDLE: IDLE<63>. 
* ビルド: ビルド<100>. 
* C API: C API<79>. 
* ドキュメント: ドキュメント<85>. 
* テスト: テスト<88>. 
* Tools/Demos: Tools/Demos<61>. 
* Windows: Windows<83>. 

@end menu

@node Core and Builtins<204>,ライブラリ<207>,,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1062}@anchor{1fb0}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23285}: PEP 475 - EINTR handling.

@item 
bpo-22735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22735}: Fix many edge cases (including crashes) involving custom mro()
implementations.

@item 
bpo-22896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22896}: Avoid using PyObject_AsCharBuffer(), PyObject_AsReadBuffer()
and PyObject_AsWriteBuffer().

@item 
bpo-21295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21295}: Revert some changes (bpo-16795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16795}) to AST line numbers and
column offsets that constituted a regression.

@item 
bpo-22986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22986}: Allow changing an object's __class__ between a dynamic type and
static type in some cases.

@item 
bpo-15859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15859}: PyUnicode_EncodeFSDefault(), PyUnicode_EncodeMBCS() and
PyUnicode_EncodeCodePage() now raise an exception if the object is not a
Unicode object. For PyUnicode_EncodeFSDefault(), it was already the case
on platforms other than Windows. Patch written by Campbell Barton.

@item 
bpo-21408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21408}: The default __ne__() now returns NotImplemented if __eq__()
returned NotImplemented.  Original patch by Martin Panter.

@item 
bpo-23321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23321}: Fixed a crash in str.decode() when error handler returned
replacement string longer than malformed input data.

@item 
bpo-22286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22286}: The "backslashreplace" error handlers now works with decoding
and translating.

@item 
bpo-23253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23253}: Delay-load ShellExecute[AW] in os.startfile for reduced startup
overhead on Windows.

@item 
bpo-22038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22038}: pyatomic.h now uses stdatomic.h or GCC built-in functions for
atomic memory access if available. Patch written by Vitor de Lima and
Gustavo Temple.

@item 
bpo-20284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20284}: %-interpolation (aka printf) formatting added for bytes and
bytearray.

@item 
bpo-23048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23048}: Fix jumping out of an infinite while loop in the pdb.

@item 
bpo-20335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20335}: bytes constructor now raises TypeError when encoding or errors
is specified with non-string argument.  Based on patch by Renaud Blanch.

@item 
bpo-22834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22834}: If the current working directory ends up being set to a
non-existent directory then import will no longer raise FileNotFoundError.

@item 
bpo-22869@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22869}: Move the interpreter startup & shutdown code to a new dedicated
pylifecycle.c module

@item 
bpo-22847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22847}: Improve method cache efficiency.

@item 
bpo-22335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22335}: Fix crash when trying to enlarge a bytearray to 0x7fffffff
bytes on a 32-bit platform.

@item 
bpo-22653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22653}: Fix an assertion failure in debug mode when doing a reentrant
dict insertion in debug mode.

@item 
bpo-22643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22643}: Fix integer overflow in Unicode case operations (upper, lower,
title, swapcase, casefold).

@item 
bpo-17636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17636}: Circular imports involving relative imports are now supported.

@item 
bpo-22604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22604}: Fix assertion error in debug mode when dividing a complex
number by (nan+0j).

@item 
bpo-21052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21052}: Do not raise ImportWarning when sys.path_hooks or sys.meta_path
are set to None.

@item 
bpo-16518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16518}: Use 'bytes-like object required' in error messages that
previously used the far more cryptic "'x' does not support the buffer
protocol.

@item 
bpo-22470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22470}: Fixed integer overflow issues in "backslashreplace",
"xmlcharrefreplace", and "surrogatepass" error handlers.

@item 
bpo-22540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22540}: speed up @code{PyObject_IsInstance} and @code{PyObject_IsSubclass} in
the common case that the second argument has metaclass @code{type}.

@item 
bpo-18711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18711}: Add a new @code{PyErr_FormatV} function, similar to
@code{PyErr_Format} but accepting a @code{va_list} argument.

@item 
bpo-22520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22520}: Fix overflow checking when generating the repr of a unicode
object.

@item 
bpo-22519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22519}: Fix overflow checking in PyBytes_Repr.

@item 
bpo-22518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22518}: Fix integer overflow issues in latin-1 encoding.

@item 
bpo-16324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16324}: _charset parameter of MIMEText now also accepts
email.charset.Charset instances. Initial patch by Claude Paroz.

@item 
bpo-1764286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1764286}: Fix inspect.getsource() to support decorated functions. Patch
by Claudiu Popa.

@item 
bpo-18554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18554}: os.__all__ includes posix functions.

@item 
bpo-21391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21391}: Use os.path.abspath in the shutil module.

@item 
bpo-11471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11471}: avoid generating a JUMP_FORWARD instruction at the end of an
if-block if there is no else-clause.  Original patch by Eugene Toder.

@item 
bpo-22215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22215}: Now ValueError is raised instead of TypeError when str or bytes
argument contains not permitted null character or byte.

@item 
bpo-22258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22258}: Fix the internal function set_inheritable() on Illumos. This
platform exposes the function @code{ioctl(FIOCLEX)}, but calling it fails
with errno is ENOTTY: "Inappropriate ioctl for device". set_inheritable()
now falls back to the slower @code{fcntl()} (@code{F_GETFD} and then
@code{F_SETFD}).

@item 
bpo-21389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21389}: Displaying the __qualname__ of the underlying function in the
repr of a bound method.

@item 
bpo-22206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22206}: Using pthread, PyThread_create_key() now sets errno to ENOMEM
and returns -1 (error) on integer overflow.

@item 
bpo-20184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20184}: Argument Clinic based signature introspection added for 30 of
the builtin functions.

@item 
bpo-22116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22116}: C functions and methods (of the 'builtin_function_or_method'
type) can now be weakref'ed.  Patch by Wei Wu.

@item 
bpo-22077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22077}: Improve index error messages for bytearrays, bytes, lists, and
tuples by adding 'or slices'. Added ', not <typename>' for bytearrays.
Original patch by Claudiu Popa.

@item 
bpo-20179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20179}: Apply Argument Clinic to bytes and bytearray. Patch by Tal
Einat.

@item 
bpo-22082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22082}: Clear interned strings in slotdefs.

@item 
Upgrade Unicode database to Unicode 7.0.0.

@item 
bpo-21897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21897}: Fix a crash with the f_locals attribute with closure variables
when frame.clear() has been called.

@item 
bpo-21205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21205}: Add a new @code{__qualname__} attribute to generator, the
qualified name, and use it in the representation of a generator
(@code{repr(gen)}). The default name of the generator (@code{__name__}
attribute) is now get from the function instead of the code. Use
@code{gen.gi_code.co_name} to get the name of the code.

@item 
bpo-21669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21669}: With the aid of heuristics in SyntaxError.__init__, the parser
now attempts to generate more meaningful (or at least more search engine
friendly) error messages when "exec" and "print" are used as statements.

@item 
bpo-21642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21642}: In the conditional if-else expression, allow an integer written
with no space between itself and the @code{else} keyword (e.g. @code{True if
42else False}) to be valid syntax.

@item 
bpo-21523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21523}: Fix over-pessimistic computation of the stack effect of some
opcodes in the compiler.  This also fixes a quadratic compilation time
issue noticeable when compiling code with a large number of "and" and "or"
operators.

@item 
bpo-21418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21418}: Fix a crash in the builtin function super() when called without
argument and without current frame (ex: embedded Python).

@item 
bpo-21425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21425}: Fix flushing of standard streams in the interactive
interpreter.

@item 
bpo-21435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21435}: In rare cases, when running finalizers on objects in cyclic
trash a bad pointer dereference could occur due to a subtle flaw in
internal iteration logic.

@item 
bpo-21377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21377}: PyBytes_Concat() now tries to concatenate in-place when the
first argument has a reference count of 1.  Patch by Nikolaus Rath.

@item 
bpo-20355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20355}: -W command line options now have higher priority than the
PYTHONWARNINGS environment variable.  Patch by Arfrever.

@item 
bpo-21274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21274}: Define PATH_MAX for GNU/Hurd in Python/pythonrun.c.

@item 
bpo-20904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20904}: Support setting FPU precision on m68k.

@item 
bpo-21209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21209}: Fix sending tuples to custom generator objects with the yield
from syntax.

@item 
bpo-21193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21193}: pow(a, b, c) now raises ValueError rather than TypeError when b
is negative. Patch by Josh Rosenberg.

@item 
bpo-21176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21176}: PEP 465: Add the '@@' operator for matrix multiplication.

@item 
bpo-21134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21134}: Fix segfault when str is called on an uninitialized
UnicodeEncodeError, UnicodeDecodeError, or UnicodeTranslateError object.

@item 
bpo-19537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19537}: Fix PyUnicode_DATA() alignment under m68k.  Patch by Andreas
Schwab.

@item 
bpo-20929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20929}: Add a type cast to avoid shifting a negative number.

@item 
bpo-20731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20731}: Properly position in source code files even if they are opened
in text mode. Patch by Serhiy Storchaka.

@item 
bpo-20637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20637}: Key-sharing now also works for instance dictionaries of
subclasses.  Patch by Peter Ingebretson.

@item 
bpo-8297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8297}: Attributes missing from modules now include the module name in
the error text.  Original patch by ysj.ray.

@item 
bpo-19995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19995}: %c, %o, %x, and %X now raise TypeError on non-integer input.

@item 
bpo-19655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19655}: The ASDL parser - used by the build process to generate code
for managing the Python AST in C - was rewritten. The new parser is self
contained and does not require to carry long the spark.py parser-generator
library; spark.py was removed from the source base.

@item 
bpo-12546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12546}: Allow @code{\x00} to be used as a fill character when using str,
int, float, and complex __format__ methods.

@item 
bpo-20480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20480}: Add ipaddress.reverse_pointer. Patch by Leon Weber.

@item 
bpo-13598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13598}: Modify string.Formatter to support auto-numbering of
replacement fields. It now matches the behavior of str.format() in this
regard. Patches by Phil Elson and Ramchandra Apte.

@item 
bpo-8931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8931}: Make alternate formatting ('#') for type 'c' raise an exception.
In versions prior to 3.5, '#' with 'c' had no effect. Now specifying it is
an error. Patch by Torsten Landschoff.

@item 
bpo-23165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23165}: Perform overflow checks before allocating memory in the
_Py_char2wchar function.
@end itemize

@node ライブラリ<207>,IDLE<63>,Core and Builtins<204>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1063}@anchor{1fb1}
@subsubsection ライブラリ



@itemize -

@item 
bpo-23399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23399}: pyvenv creates relative symlinks where possible.

@item 
bpo-20289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20289}: cgi.FieldStorage() now supports the context management
protocol.

@item 
bpo-13128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13128}: Print response headers for CONNECT requests when debuglevel >
0. Patch by Demian Brecht.

@item 
bpo-15381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15381}: Optimized io.BytesIO to make less allocations and copyings.

@item 
bpo-22818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22818}: Splitting on a pattern that could match an empty string now
raises a warning.  Patterns that can only match empty strings are now
rejected.

@item 
bpo-23099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23099}: Closing io.BytesIO with exported buffer is rejected now to
prevent corrupting exported buffer.

@item 
bpo-23326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23326}: Removed __ne__ implementations.  Since fixing default __ne__
implementation in bpo-21408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21408} they are redundant.

@item 
bpo-23363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23363}: Fix possible overflow in itertools.permutations.

@item 
bpo-23364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23364}: Fix possible overflow in itertools.product.

@item 
bpo-23366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23366}: Fixed possible integer overflow in itertools.combinations.

@item 
bpo-23369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23369}: Fixed possible integer overflow in
_json.encode_basestring_ascii.

@item 
bpo-23353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23353}: Fix the exception handling of generators in
PyEval_EvalFrameEx(). At entry, save or swap the exception state even if
PyEval_EvalFrameEx() is called with throwflag=0. At exit, the exception
state is now always restored or swapped, not only if why is WHY_YIELD or
WHY_RETURN. Patch co-written with Antoine Pitrou.

@item 
bpo-14099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14099}: Restored support of writing ZIP files to tellable but
non-seekable streams.

@item 
bpo-14099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14099}: Writing to ZipFile and reading multiple ZipExtFiles is
threadsafe now.

@item 
bpo-19361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19361}: JSON decoder now raises JSONDecodeError instead of ValueError.

@item 
bpo-18518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18518}: timeit now rejects statements which can't be compiled outside a
function or a loop (e.g. "return" or "break").

@item 
bpo-23094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23094}: Fixed readline with frames in Python implementation of pickle.

@item 
bpo-23268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23268}: Fixed bugs in the comparison of ipaddress classes.

@item 
bpo-21408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21408}: Removed incorrect implementations of __ne__() which didn't
returned NotImplemented if __eq__() returned NotImplemented.  The default
__ne__() now works correctly.

@item 
bpo-19996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19996}: @code{email.feedparser.FeedParser} now handles (malformed)
headers with no key rather than assuming the body has started.

@item 
bpo-20188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20188}: Support Application-Layer Protocol Negotiation (ALPN) in the
ssl module.

@item 
bpo-23133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23133}: Pickling of ipaddress objects now produces more compact and
portable representation.

@item 
bpo-23248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23248}: Update ssl error codes from latest OpenSSL git master.

@item 
bpo-23266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23266}: Much faster implementation of ipaddress.collapse_addresses()
when there are many non-consecutive addresses.

@item 
bpo-23098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23098}: 64-bit dev_t is now supported in the os module.

@item 
bpo-21817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21817}: When an exception is raised in a task submitted to a
ProcessPoolExecutor, the remote traceback is now displayed in the parent
process.  Patch by Claudiu Popa.

@item 
bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}: Add an option to limit output size when decompressing LZMA
data.  Patch by Nikolaus Rath and Martin Panter.

@item 
bpo-23250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23250}: In the http.cookies module, capitalize "HttpOnly" and "Secure"
as they are written in the standard.

@item 
bpo-23063@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23063}: In the distutils' check command, fix parsing of reST with code
or code-block directives.

@item 
bpo-23209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23209}: selectors.BaseSelector.get_key() now raises a RuntimeError if
the selector is closed. And selectors.BaseSelector.close() now clears its
internal reference to the selector mapping to break a reference cycle.
Initial patch written by Martin Richard. (See also: bpo-23225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23225})

@item 
bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}: Provide a way to seed the linecache for a PEP-302 module
without actually loading the code.

@item 
bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}: Provide a new object API for traceback, including the ability
to not lookup lines at all until the traceback is actually rendered,
without any trace of the original objects being kept alive.

@item 
bpo-19777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19777}: Provide a home() classmethod on Path objects.  Contributed by
Victor Salgado and Mayank Tripathi.

@item 
bpo-23206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23206}: Make @code{json.dumps(..., ensure_ascii=False)} as fast as the
default case of @code{ensure_ascii=True}.  Patch by Naoki Inada.

@item 
bpo-23185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23185}: Add math.inf and math.nan constants.

@item 
bpo-23186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23186}: Add ssl.SSLObject.shared_ciphers() and
ssl.SSLSocket.shared_ciphers() to fetch the client's list ciphers sent at
handshake.

@item 
bpo-23143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23143}: Remove compatibility with OpenSSLs older than 0.9.8.

@item 
bpo-23132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23132}: Improve performance and introspection support of comparison
methods created by functool.total_ordering.

@item 
bpo-19776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19776}: Add an expanduser() method on Path objects.

@item 
bpo-23112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23112}: Fix SimpleHTTPServer to correctly carry the query string and
fragment when it redirects to add a trailing slash.

@item 
bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}: Added http.HTTPStatus enums (i.e. HTTPStatus.OK,
HTTPStatus.NOT_FOUND). Patch by Demian Brecht.

@item 
bpo-23093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23093}: In the io, module allow more operations to work on detached
streams.

@item 
bpo-23111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23111}: In the ftplib, make ssl.PROTOCOL_SSLv23 the default protocol
version.

@item 
bpo-22585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22585}: On OpenBSD 5.6 and newer, os.urandom() now calls getentropy(),
instead of reading /dev/urandom, to get pseudo-random bytes.

@item 
bpo-19104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19104}: pprint now produces evaluable output for wrapped strings.

@item 
bpo-23071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23071}: Added missing names to codecs.__all__.  Patch by Martin Panter.

@item 
bpo-22783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22783}: Pickling now uses the NEWOBJ opcode instead of the NEWOBJ_EX
opcode if possible.

@item 
bpo-15513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15513}: Added a __sizeof__ implementation for pickle classes.

@item 
bpo-19858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19858}: pickletools.optimize() now aware of the MEMOIZE opcode, can
produce more compact result and no longer produces invalid output if input
data contains MEMOIZE opcodes together with PUT or BINPUT opcodes.

@item 
bpo-22095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22095}: Fixed HTTPConnection.set_tunnel with default port.  The port
value in the host header was set to "None".  Patch by Demian Brecht.

@item 
bpo-23016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23016}: A warning no longer produces an AttributeError when the program
is run with pythonw.exe.

@item 
bpo-21775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21775}: shutil.copytree(): fix crash when copying to VFAT. An exception
handler assumed that OSError objects always have a 'winerror' attribute.
That is not the case, so the exception handler itself raised
AttributeError when run on Linux (and, presumably, any other non-Windows
OS). Patch by Greg Ward.

@item 
bpo-1218234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1218234}: Fix inspect.getsource() to load updated source of reloaded
module. Initial patch by Berker Peksag.

@item 
bpo-21740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21740}: Support wrapped callables in doctest. Patch by Claudiu Popa.

@item 
bpo-23009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23009}: Make sure selectors.EpollSelector.select() works when no FD is
registered.

@item 
bpo-22959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22959}: In the constructor of http.client.HTTPSConnection, prefer the
context's check_hostname attribute over the `check_hostname' parameter.

@item 
bpo-22696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22696}: Add function @ref{c80,,sys.is_finalizing()} to know about
interpreter shutdown.

@item 
bpo-16043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16043}: Add a default limit for the amount of data
xmlrpclib.gzip_decode will return. This resolves 
@geindex Common Vulnerabilities and Exposures; CVE 2013-1753
CVE 2013-1753@footnote{https://www.cve.org/CVERecord?id=CVE-2013-1753}.

@item 
bpo-14099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14099}: ZipFile.open() no longer reopen the underlying file.  Objects
returned by ZipFile.open() can now operate independently of the ZipFile
even if the ZipFile was created by passing in a file-like object as the
first argument to the constructor.

@item 
bpo-22966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22966}: Fix __pycache__ pyc file name clobber when pyc_compile is asked
to compile a source file containing multiple dots in the source file name.

@item 
bpo-21971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21971}: Update turtledemo doc and add module to the index.

@item 
bpo-21032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21032}: Fixed socket leak if HTTPConnection.getresponse() fails.
Original patch by Martin Panter.

@item 
bpo-22407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22407}: Deprecated the use of re.LOCALE flag with str patterns or
re.ASCII. It was newer worked.

@item 
bpo-22902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22902}: The "ip" command is now used on Linux to determine MAC address
in uuid.getnode().  Patch by Bruno Cauet.

@item 
bpo-22960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22960}: Add a context argument to xmlrpclib.ServerProxy constructor.

@item 
bpo-22389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22389}: Add contextlib.redirect_stderr().

@item 
bpo-21356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21356}: Make ssl.RAND_egd() optional to support LibreSSL. The
availability of the function is checked during the compilation. Patch
written by Bernard Spil.

@item 
bpo-22915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22915}: SAX parser now supports files opened with file descriptor or
bytes path.

@item 
bpo-22609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22609}: Constructors and update methods of mapping classes in the
collections module now accept the self keyword argument.

@item 
bpo-22940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22940}: Add readline.append_history_file.

@item 
bpo-19676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19676}: Added the "namereplace" error handler.

@item 
bpo-22788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22788}: Add `context' parameter to logging.handlers.HTTPHandler.

@item 
bpo-22921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22921}: Allow SSLContext to take the `hostname' parameter even if
OpenSSL doesn't support SNI.

@item 
bpo-22894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22894}: TestCase.subTest() would cause the test suite to be stopped
when in failfast mode, even in the absence of failures.

@item 
bpo-22796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22796}: HTTP cookie parsing is now stricter, in order to protect
against potential injection attacks.

@item 
bpo-22370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22370}: Windows detection in pathlib is now more robust.

@item 
bpo-22841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22841}: Reject coroutines in asyncio add_signal_handler(). Patch by
Ludovic.Gasc.

@item 
bpo-19494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19494}: Added urllib.request.HTTPBasicPriorAuthHandler. Patch by Matej
Cepl.

@item 
bpo-22578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22578}: Added attributes to the re.error class.

@item 
bpo-22849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22849}: Fix possible double free in the io.TextIOWrapper constructor.

@item 
bpo-12728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12728}: Different Unicode characters having the same uppercase but
different lowercase are now matched in case-insensitive regular
expressions.

@item 
bpo-22821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22821}: Fixed fcntl() with integer argument on 64-bit big-endian
platforms.

@item 
bpo-21650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21650}: Add an @code{--sort-keys} option to @code{json.tool} CLI.

@item 
bpo-22824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22824}: Updated reprlib output format for sets to use set literals.
Patch contributed by Berker Peksag.

@item 
bpo-22824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22824}: Updated reprlib output format for arrays to display empty
arrays without an unnecessary empty list.  Suggested by Serhiy Storchaka.

@item 
bpo-22406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22406}: Fixed the uu_codec codec incorrectly ported to 3.x. Based on
patch by Martin Panter.

@item 
bpo-17293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17293}: uuid.getnode() now determines MAC address on AIX using netstat.
Based on patch by Aivars Kalvāns.

@item 
bpo-22769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22769}: Fixed ttk.Treeview.tag_has() when called without arguments.

@item 
bpo-22417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22417}: Verify certificates by default in httplib (PEP 476).

@item 
bpo-22775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22775}: Fixed unpickling of http.cookies.SimpleCookie with protocol 2
and above. Patch by Tim Graham.

@item 
bpo-22776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22776}: Brought excluded code into the scope of a try block in
SysLogHandler.emit().

@item 
bpo-22665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22665}: Add missing get_terminal_size and SameFileError to
shutil.__all__.

@item 
bpo-6623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6623}: Remove deprecated Netrc class in the ftplib module. Patch by
Matt Chaput.

@item 
bpo-17381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17381}: Fixed handling of case-insensitive ranges in regular
expressions.

@item 
bpo-22410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22410}: Module level functions in the re module now cache compiled
locale-dependent regular expressions taking into account the locale.

@item 
bpo-22759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22759}: Query methods on pathlib.Path() (exists(), is_dir(), etc.) now
return False when the underlying stat call raises NotADirectoryError.

@item 
bpo-8876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8876}: distutils now falls back to copying files when hard linking
doesn't work. This allows use with special filesystems such as VirtualBox
shared folders.

@item 
bpo-22217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22217}: Implemented reprs of classes in the zipfile module.

@item 
bpo-22457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22457}: Honour load_tests in the start_dir of discovery.

@item 
bpo-18216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18216}: gettext now raises an error when a .mo file has an unsupported
major version number.  Patch by Aaron Hill.

@item 
bpo-13918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13918}: Provide a locale.delocalize() function which can remove
locale-specific number formatting from a string representing a number,
without then converting it to a specific type.  Patch by Cédric Krier.

@item 
bpo-22676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22676}: Make the pickling of global objects which don't have a
__module__ attribute less slow.

@item 
bpo-18853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18853}: Fixed ResourceWarning in shlex.__nain__.

@item 
bpo-9351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9351}: Defaults set with set_defaults on an argparse subparser are no
longer ignored when also set on the parent parser.

@item 
bpo-7559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7559}: unittest test loading ImportErrors are reported as import errors
with their import exception rather than as attribute errors after the
import has already failed.

@item 
bpo-19746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19746}: Make it possible to examine the errors from unittest discovery
without executing the test suite. The new @code{errors} attribute on
@code{TestLoader} exposes these non-fatal errors encountered during
discovery.

@item 
bpo-21991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21991}: Make email.headerregistry's header 'params' attributes be
read-only (MappingProxyType).  Previously the dictionary was modifiable
but a new one was created on each access of the attribute.

@item 
bpo-22638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22638}: SSLv3 is now disabled throughout the standard library. It can
still be enabled by instantiating a SSLContext manually.

@item 
bpo-22641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22641}: In asyncio, the default SSL context for client connections is
now created using ssl.create_default_context(), for stronger security.

@item 
bpo-17401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17401}: Include closefd in io.FileIO repr.

@item 
bpo-21338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21338}: Add silent mode for compileall. quiet parameters of
compile_@{dir, file, path@} functions now have a multilevel value. Also, -q
option of the CLI now have a multilevel value. Patch by Thomas Kluyver.

@item 
bpo-20152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20152}: Convert the array and cmath modules to Argument Clinic.

@item 
bpo-18643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18643}: Add socket.socketpair() on Windows.

@item 
bpo-22435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22435}: Fix a file descriptor leak when socketserver bind fails.

@item 
bpo-13096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13096}: Fixed segfault in CTypes POINTER handling of large values.

@item 
bpo-11694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11694}: Raise ConversionError in xdrlib as documented.  Patch by Filip
Gruszczyński and Claudiu Popa.

@item 
bpo-19380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19380}: Optimized parsing of regular expressions.

@item 
bpo-1519638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1519638}: Now unmatched groups are replaced with empty strings in
re.sub() and re.subn().

@item 
bpo-18615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18615}: sndhdr.what/whathdr now return a namedtuple.

@item 
bpo-22462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22462}: Fix pyexpat's creation of a dummy frame to make it appear in
exception tracebacks.

@item 
bpo-21965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21965}: Add support for in-memory SSL to the ssl module.  Patch by
Geert Jansen.

@item 
bpo-21173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21173}: Fix len() on a WeakKeyDictionary when .clear() was called with
an iterator alive.

@item 
bpo-11866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11866}: Eliminated race condition in the computation of names for new
threads.

@item 
bpo-21905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21905}: Avoid RuntimeError in pickle.whichmodule() when sys.modules is
mutated while iterating.  Patch by Olivier Grisel.

@item 
bpo-11271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11271}: concurrent.futures.Executor.map() now takes a `chunksize'
argument to allow batching of tasks in child processes and improve
performance of ProcessPoolExecutor.  Patch by Dan O'Reilly.

@item 
bpo-21883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21883}: os.path.join() and os.path.relpath() now raise a TypeError with
more helpful error message for unsupported or mismatched types of
arguments.

@item 
bpo-22219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22219}: The zipfile module CLI now adds entries for directories
(including empty directories) in ZIP file.

@item 
bpo-22449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22449}: In the ssl.SSLContext.load_default_certs, consult the
environmental variables SSL_CERT_DIR and SSL_CERT_FILE on Windows.

@item 
bpo-22508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22508}: The email.__version__ variable has been removed; the email code
is no longer shipped separately from the stdlib, and __version__ hasn't
been updated in several releases.

@item 
bpo-20076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20076}: Added non derived UTF-8 aliases to locale aliases table.

@item 
bpo-20079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20079}: Added locales supported in glibc 2.18 to locale alias table.

@item 
bpo-20218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20218}: Added convenience methods read_text/write_text and read_bytes/
write_bytes to pathlib.Path objects.

@item 
bpo-22396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22396}: On 32-bit AIX platform, don't expose os.posix_fadvise() nor
os.posix_fallocate() because their prototypes in system headers are wrong.

@item 
bpo-22517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22517}: When an io.BufferedRWPair object is deallocated, clear its
weakrefs.

@item 
bpo-22437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22437}: Number of capturing groups in regular expression is no longer
limited by 100.

@item 
bpo-17442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17442}: InteractiveInterpreter now displays the full chained traceback
in its showtraceback method, to match the built in interactive
interpreter.

@item 
bpo-23392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23392}: Added tests for marshal C API that works with FILE*.

@item 
bpo-10510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10510}: distutils register and upload methods now use HTML standards
compliant CRLF line endings.

@item 
bpo-9850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9850}: Fixed macpath.join() for empty first component.  Patch by Oleg
Oshmyan.

@item 
bpo-5309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5309}: distutils' build and build_ext commands now accept a @code{-j}
option to enable parallel building of extension modules.

@item 
bpo-22448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22448}: Improve canceled timer handles cleanup to prevent unbound
memory usage. Patch by Joshua Moore-Oliva.

@item 
bpo-22427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22427}: TemporaryDirectory no longer attempts to clean up twice when
used in the with statement in generator.

@item 
bpo-22362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22362}: Forbidden ambiguous octal escapes out of range 0-0o377 in
regular expressions.

@item 
bpo-20912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20912}: Now directories added to ZIP file have correct Unix and MS-DOS
directory attributes.

@item 
bpo-21866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21866}: ZipFile.close() no longer writes ZIP64 central directory
records if allowZip64 is false.

@item 
bpo-22278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22278}: Fix urljoin problem with relative urls, a regression observed
after changes to issue22118 were submitted.

@item 
bpo-22415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22415}: Fixed debugging output of the GROUPREF_EXISTS opcode in the re
module. Removed trailing spaces in debugging output.

@item 
bpo-22423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22423}: Unhandled exception in thread no longer causes unhandled
AttributeError when sys.stderr is None.

@item 
bpo-21332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21332}: Ensure that @code{bufsize=1} in subprocess.Popen() selects line
buffering, rather than block buffering.  Patch by Akira Li.

@item 
bpo-21091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21091}: Fix API bug: email.message.EmailMessage.is_attachment is now a
method.

@item 
bpo-21079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21079}: Fix email.message.EmailMessage.is_attachment to return the
correct result when the header has parameters as well as a value.

@item 
bpo-22247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22247}: Add NNTPError to nntplib.__all__.

@item 
bpo-22366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22366}: urllib.request.urlopen will accept a context object
(SSLContext) as an argument which will then be used for HTTPS connection.
Patch by Alex Gaynor.

@item 
bpo-4180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4180}: The warnings registries are now reset when the filters are
modified.

@item 
bpo-22419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22419}: Limit the length of incoming HTTP request in wsgiref server to
65536 bytes and send a 414 error code for higher lengths. Patch
contributed by Devin Cook.

@item 
Lax cookie parsing in http.cookies could be a security issue when combined
with non-standard cookie handling in some web browsers.  Reported by
Sergey Bobrov.

@item 
bpo-20537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20537}: logging methods now accept an exception instance as well as a
Boolean value or exception tuple. Thanks to Yury Selivanov for the patch.

@item 
bpo-22384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22384}: An exception in Tkinter callback no longer crashes the program
when it is run with pythonw.exe.

@item 
bpo-22168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22168}: Prevent turtle AttributeError with non-default Canvas on OS X.

@item 
bpo-21147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21147}: sqlite3 now raises an exception if the request contains a null
character instead of truncating it.  Based on patch by Victor Stinner.

@item 
bpo-13968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13968}: The glob module now supports recursive search in subdirectories
using the @code{**} pattern.

@item 
bpo-21951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21951}: Fixed a crash in Tkinter on AIX when called Tcl command with
empty string or tuple argument.

@item 
bpo-21951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21951}: Tkinter now most likely raises MemoryError instead of crash if
the memory allocation fails.

@item 
bpo-22338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22338}: Fix a crash in the json module on memory allocation failure.

@item 
bpo-12410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12410}: imaplib.IMAP4 now supports the context management protocol.
Original patch by Tarek Ziadé.

@item 
bpo-21270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21270}: We now override tuple methods in mock.call objects so that they
can be used as normal call attributes.

@item 
bpo-16662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16662}: @code{load_tests()} is now unconditionally run when it is present
in a package's @code{__init__.py}.  @code{TestLoader.loadTestsFromModule()}
still accepts use_load_tests, but it is deprecated and ignored.  A new
keyword-only attribute @code{pattern} is added and documented.  Patch given
by Robert Collins, tweaked by Barry Warsaw.

@item 
bpo-22226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22226}: First letter no longer is stripped from the "status" key in the
result of Treeview.heading().

@item 
bpo-19524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19524}: Fixed resource leak in the HTTP connection when an invalid
response is received.  Patch by Martin Panter.

@item 
bpo-20421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20421}: Add a .version() method to SSL sockets exposing the actual
protocol version in use.

@item 
bpo-19546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19546}: configparser exceptions no longer expose implementation
details. Chained KeyErrors are removed, which leads to cleaner tracebacks.
Patch by Claudiu Popa.

@item 
bpo-22051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22051}: turtledemo no longer reloads examples to re-run them.
Initialization of variables and gui setup should be done in main(), which
is called each time a demo is run, but not on import.

@item 
bpo-21933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21933}: Turtledemo users can change the code font size with a menu
selection or control(command) '-' or '+' or control-mousewheel. Original
patch by Lita Cho.

@item 
bpo-21597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21597}: The separator between the turtledemo text pane and the drawing
canvas can now be grabbed and dragged with a mouse.  The code text pane
can be widened to easily view or copy the full width of the text.  The
canvas can be widened on small screens.  Original patches by Jan Kanis and
Lita Cho.

@item 
bpo-18132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18132}: Turtledemo buttons no longer disappear when the window is
shrunk.  Original patches by Jan Kanis and Lita Cho.

@item 
bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}: time.monotonic() is now always available.
@code{threading.Lock.acquire()}, @code{threading.RLock.acquire()} and socket
operations now use a monotonic clock, instead of the system clock, when a
timeout is used.

@item 
bpo-21527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21527}: Add a default number of workers to ThreadPoolExecutor equal to
5 times the number of CPUs.  Patch by Claudiu Popa.

@item 
bpo-22216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22216}: smtplib now resets its state more completely after a quit.  The
most obvious consequence of the previous behavior was a STARTTLS failure
during a connect/starttls/quit/connect/starttls sequence.

@item 
bpo-22098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22098}: ctypes' BigEndianStructure and LittleEndianStructure now define
an empty __slots__ so that subclasses don't always get an instance dict.
Patch by Claudiu Popa.

@item 
bpo-22185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22185}: Fix an occasional RuntimeError in threading.Condition.wait()
caused by mutation of the waiters queue without holding the lock.  Patch
by Doug Zongker.

@item 
bpo-22287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22287}: On UNIX, _PyTime_gettimeofday() now uses
clock_gettime(CLOCK_REALTIME) if available. As a side effect, Python now
depends on the librt library on Solaris and on Linux (only with glibc
older than 2.17).

@item 
bpo-22182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22182}: Use e.args to unpack exceptions correctly in
distutils.file_util.move_file. Patch by Claudiu Popa.

@item 
The webbrowser module now uses subprocess's start_new_session=True rather
than a potentially risky preexec_fn=os.setsid call.

@item 
bpo-22042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22042}: signal.set_wakeup_fd(fd) now raises an exception if the file
descriptor is in blocking mode.

@item 
bpo-16808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16808}: inspect.stack() now returns a named tuple instead of a tuple.
Patch by Daniel Shahaf.

@item 
bpo-22236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22236}: Fixed Tkinter images copying operations in NoDefaultRoot mode.

@item 
bpo-2527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2527}: Add a `globals' argument to timeit functions, in order to
override the globals namespace in which the timed code is executed. Patch
by Ben Roberts.

@item 
bpo-22118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22118}: Switch urllib.parse to use RFC 3986 semantics for the
resolution of relative URLs, rather than RFCs 1808 and 2396. Patch by
Demian Brecht.

@item 
bpo-21549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21549}: Added the "members" parameter to TarFile.list().

@item 
bpo-19628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19628}: Allow compileall recursion depth to be specified with a -r
option.

@item 
bpo-15696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15696}: Add a __sizeof__ implementation for mmap objects on Windows.

@item 
bpo-22068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22068}: Avoided reference loops with Variables and Fonts in Tkinter.

@item 
bpo-22165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22165}: SimpleHTTPRequestHandler now supports undecodable file names.

@item 
bpo-15381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15381}: Optimized line reading in io.BytesIO.

@item 
bpo-8797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8797}: Raise HTTPError on failed Basic Authentication immediately.
Initial patch by Sam Bull.

@item 
bpo-20729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20729}: Restored the use of lazy iterkeys()/itervalues()/iteritems() in
the mailbox module.

@item 
bpo-21448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21448}: Changed FeedParser feed() to avoid `O'(`n'@w{^2})
behavior when parsing long line. Original patch by Raymond Hettinger.

@item 
bpo-22184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22184}: The functools LRU Cache decorator factory now gives an earlier
and clearer error message when the user forgets the required parameters.

@item 
bpo-17923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17923}: glob() patterns ending with a slash no longer match non-dirs on
AIX.  Based on patch by Delhallt.

@item 
bpo-21725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21725}: Added support for RFC 6531 (SMTPUTF8) in smtpd.

@item 
bpo-22176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22176}: Update the ctypes module's libffi to v3.1.  This release adds
support for the Linux AArch64 and POWERPC ELF ABIv2 little endian
architectures.

@item 
bpo-5411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5411}: Added support for the "xztar" format in the shutil module.

@item 
bpo-21121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21121}: Don't force 3rd party C extensions to be built with
-Werror=declaration-after-statement.

@item 
bpo-21975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21975}: Fixed crash when using uninitialized sqlite3.Row (in particular
when unpickling pickled sqlite3.Row).  sqlite3.Row is now initialized in
the __new__() method.

@item 
bpo-20170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20170}: Convert posixmodule to use Argument Clinic.

@item 
bpo-21539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21539}: Add an `exists_ok' argument to @code{Pathlib.mkdir()} to mimic
@code{mkdir -p} and @code{os.makedirs()} functionality.  When true, ignore
@code{FileExistsErrors}. Patch by Berker Peksag.

@item 
bpo-22127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22127}: Bypass IDNA for pure-ASCII host names in the socket module (in
particular for numeric IPs).

@item 
bpo-21047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21047}: set the default value for the `convert_charrefs' argument of
HTMLParser to True.  Patch by Berker Peksag.

@item 
Add an __all__ to html.entities.

@item 
bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}: the strict mode and argument of HTMLParser, HTMLParser.error,
and the HTMLParserError exception have been removed.

@item 
bpo-22085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22085}: Dropped support of Tk 8.3 in Tkinter.

@item 
bpo-21580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21580}: Now Tkinter correctly handles bytes arguments passed to Tk. In
particular this allows initializing images from binary data.

@item 
bpo-22003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22003}: When initialized from a bytes object, io.BytesIO() now defers
making a copy until it is mutated, improving performance and memory use on
some use cases. Patch by David Wilson.

@item 
bpo-22018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22018}: On Windows, signal.set_wakeup_fd() now also supports sockets. A
side effect is that Python depends to the WinSock library.

@item 
bpo-22054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22054}: Add os.get_blocking() and os.set_blocking() functions to get
and set the blocking mode of a file descriptor (False if the O_NONBLOCK
flag is set, True otherwise). These functions are not available on
Windows.

@item 
bpo-17172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17172}: Make turtledemo start as active on OS X even when run with
subprocess. Patch by Lita Cho.

@item 
bpo-21704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21704}: Fix build error for _multiprocessing when semaphores are not
available. Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-20173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20173}: Convert sha1, sha256, sha512 and md5 to ArgumentClinic. Patch
by Vajrasky Kok.

@item 
Fix repr(_socket.socket) on Windows 64-bit: don't fail with OverflowError
on closed socket. repr(socket.socket) already works fine.

@item 
bpo-22033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22033}: Reprs of most Python implemented classes now contain actual
class name instead of hardcoded one.

@item 
bpo-21947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21947}: The dis module can now disassemble generator-iterator objects
based on their gi_code attribute. Patch by Clement Rouault.

@item 
bpo-16133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16133}: The asynchat.async_chat.handle_read() method now ignores
BlockingIOError exceptions.

@item 
bpo-22044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22044}: Fixed premature DECREF in call_tzinfo_method. Patch by Tom
Flanagan.

@item 
bpo-19884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19884}: readline: Disable the meta modifier key if stdout is not a
terminal to not write the ANSI sequence @code{"\033[1034h"} into stdout. This
sequence is used on some terminal (ex: TERM=xterm-256color") to enable
support of 8 bit characters.

@item 
bpo-4350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4350}: Removed a number of out-of-dated and non-working for a long time
Tkinter methods.

@item 
bpo-6167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6167}: Scrollbar.activate() now returns the name of active element if
the argument is not specified.  Scrollbar.set() now always accepts only 2
arguments.

@item 
bpo-15275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15275}: Clean up and speed up the ntpath module.

@item 
bpo-21888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21888}: plistlib's load() and loads() now work if the fmt parameter is
specified.

@item 
bpo-22032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22032}: __qualname__ instead of __name__ is now always used to format
fully qualified class names of Python implemented classes.

@item 
bpo-22031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22031}: Reprs now always use hexadecimal format with the "0x" prefix
when contain an id in form " at 0x...".

@item 
bpo-22018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22018}: signal.set_wakeup_fd() now raises an OSError instead of a
ValueError on @code{fstat()} failure.

@item 
bpo-21044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21044}: tarfile.open() now handles fileobj with an integer 'name'
attribute.  Based on patch by Antoine Pietri.

@item 
bpo-21966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21966}: Respect -q command-line option when code module is ran.

@item 
bpo-19076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19076}: Don't pass the redundant 'file' argument to self.error().

@item 
bpo-16382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16382}: Improve exception message of warnings.warn() for bad category.
Initial patch by Phil Elson.

@item 
bpo-21932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21932}: os.read() now uses a @ref{c55,,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.

@item 
bpo-21942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21942}: Fixed source file viewing in pydoc's server mode on Windows.

@item 
bpo-11259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11259}: asynchat.async_chat().set_terminator() now raises a ValueError
if the number of received bytes is negative.

@item 
bpo-12523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12523}: asynchat.async_chat.push() now raises a TypeError if it doesn't
get a bytes string

@item 
bpo-21707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21707}: Add missing kwonlyargcount argument to
ModuleFinder.replace_paths_in_code().

@item 
bpo-20639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20639}: calling Path.with_suffix('@w{'}) allows removing the suffix again.
Patch by July Tikhonov.

@item 
bpo-21714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21714}: Disallow the construction of invalid paths using
Path.with_name().  Original patch by Antony Lee.

@item 
bpo-15014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15014}: Added 'auth' method to smtplib to make implementing auth
mechanisms simpler, and used it internally in the login method.

@item 
bpo-21151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21151}: Fixed a segfault in the winreg module when @code{None} is passed
as a @code{REG_BINARY} value to SetValueEx.  Patch by John Ehresman.

@item 
bpo-21090@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21090}: io.FileIO.readall() does not ignore I/O errors anymore. Before,
it ignored I/O errors if at least the first C call read() succeed.

@item 
bpo-5800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5800}: headers parameter of wsgiref.headers.Headers is now optional.
Initial patch by Pablo Torres Navarrete and SilentGhost.

@item 
bpo-21781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21781}: ssl.RAND_add() now supports strings longer than 2 GB.

@item 
bpo-21679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21679}: Prevent extraneous fstat() calls during open().  Patch by
Bohuslav Kabrda.

@item 
bpo-21863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21863}: cProfile now displays the module name of C extension functions,
in addition to their own name.

@item 
bpo-11453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11453}: asyncore: emit a ResourceWarning when an unclosed file_wrapper
object is destroyed. The destructor now closes the file if needed. The
close() method can now be called twice: the second call does nothing.

@item 
bpo-21858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21858}: Better handling of Python exceptions in the sqlite3 module.

@item 
bpo-21476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21476}: Make sure the email.parser.BytesParser TextIOWrapper is
discarded after parsing, so the input file isn't unexpectedly closed.

@item 
bpo-20295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20295}: imghdr now recognizes OpenEXR format images.

@item 
bpo-21729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21729}: Used the "with" statement in the dbm.dumb module to ensure
files closing. Patch by Claudiu Popa.

@item 
bpo-21491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21491}: socketserver: Fix a race condition in child processes reaping.

@item 
bpo-21719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21719}: Added the @code{st_file_attributes} field to os.stat_result on
Windows.

@item 
bpo-21832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21832}: Require named tuple inputs to be exact strings.

@item 
bpo-21722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21722}: The distutils "upload" command now exits with a non-zero return
code when uploading fails.  Patch by Martin Dengler.

@item 
bpo-21723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21723}: asyncio.Queue: support any type of number (ex: float) for the
maximum size. Patch written by Vajrasky Kok.

@item 
bpo-21711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21711}: support for "site-python" directories has now been removed from
the site module (it was deprecated in 3.4).

@item 
bpo-17552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17552}: new socket.sendfile() method allowing a file to be sent over a
socket by using high-performance os.sendfile() on UNIX. Patch by Giampaolo
Rodola'.

@item 
bpo-18039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18039}: dbm.dump.open() now always creates a new database when the flag
has the value 'n'.  Patch by Claudiu Popa.

@item 
bpo-21326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21326}: Add a new is_closed() method to asyncio.BaseEventLoop.
run_forever() and run_until_complete() methods of asyncio.BaseEventLoop
now raise an exception if the event loop was closed.

@item 
bpo-21766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21766}: Prevent a security hole in CGIHTTPServer by URL unquoting paths
before checking for a CGI script at that path.

@item 
bpo-21310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21310}: Fixed possible resource leak in failed open().

@item 
bpo-21256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21256}: Printout of keyword args should be in deterministic order in a
mock function call. This will help to write better doctests.

@item 
bpo-21677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21677}: Fixed chaining nonnormalized exceptions in io close() methods.

@item 
bpo-11709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11709}: Fix the pydoc.help function to not fail when sys.stdin is not a
valid file.

@item 
bpo-21515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21515}: tempfile.TemporaryFile now uses os.O_TMPFILE flag is available.

@item 
bpo-13223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13223}: Fix pydoc.writedoc so that the HTML documentation for methods
that use 'self' in the example code is generated correctly.

@item 
bpo-21463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21463}: In urllib.request, fix pruning of the FTP cache.

@item 
bpo-21618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21618}: The subprocess module could fail to close open fds that were
inherited by the calling process and already higher than POSIX resource
limits would otherwise allow.  On systems with a functioning /proc/self/fd
or /dev/fd interface the max is now ignored and all fds are closed.

@item 
bpo-20383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20383}: Introduce importlib.util.module_from_spec() as the preferred
way to create a new module.

@item 
bpo-21552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21552}: Fixed possible integer overflow of too long string lengths in
the tkinter module on 64-bit platforms.

@item 
bpo-14315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14315}: The zipfile module now ignores extra fields in the central
directory that are too short to be parsed instead of letting a
struct.unpack error bubble up as this "bad data" appears in many real
world zip files in the wild and is ignored by other zip tools.

@item 
bpo-13742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13742}: Added "key" and "reverse" parameters to heapq.merge(). (First
draft of patch contributed by Simon Sapin.)

@item 
bpo-21402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21402}: tkinter.ttk now works when default root window is not set.

@item 
bpo-3015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3015}: @code{_tkinter.create()} now creates @code{tkapp} object with
@code{wantobjects=1} by default.

@item 
bpo-10203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10203}: sqlite3.Row now truly supports sequence protocol.  In
particular it supports reverse() and negative indices.  Original patch by
Claudiu Popa.

@item 
bpo-18807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18807}: If copying (no symlinks) specified for a venv, then the python
interpreter aliases (python, python3) are now created by copying rather
than symlinking.

@item 
bpo-20197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20197}: Added support for the WebP image type in the imghdr module.
Patch by Fabrice Aneche and Claudiu Popa.

@item 
bpo-21513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21513}: Speedup some properties of IP addresses (IPv4Address,
IPv6Address) such as .is_private or .is_multicast.

@item 
bpo-21137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21137}: Improve the repr for threading.Lock() and its variants by
showing the "locked" or "unlocked" status.  Patch by Berker Peksag.

@item 
bpo-21538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21538}: The plistlib module now supports loading of binary plist files
when reference or offset size is not a power of two.

@item 
bpo-21455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21455}: Add a default backlog to socket.listen().

@item 
bpo-21525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21525}: Most Tkinter methods which accepted tuples now accept lists
too.

@item 
bpo-22166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22166}: With the assistance of a new internal _codecs._forget_codec
helping function, test_codecs now clears the encoding caches to avoid the
appearance of a reference leak

@item 
bpo-22236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22236}: Tkinter tests now don't reuse default root window.  New root
window is created for every test class.

@item 
bpo-10744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10744}: Fix 
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} format strings on ctypes objects with a
nontrivial shape.

@item 
bpo-20826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20826}: Optimize ipaddress.collapse_addresses().

@item 
bpo-21487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21487}: Optimize ipaddress.summarize_address_range() and
ipaddress.@{IPv4Network,IPv6Network@}.subnets().

@item 
bpo-21486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21486}: Optimize parsing of netmasks in ipaddress.IPv4Network and
ipaddress.IPv6Network.

@item 
bpo-13916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13916}: Disallowed the surrogatepass error handler for non UTF-*
encodings.

@item 
bpo-20998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20998}: Fixed re.fullmatch() of repeated single character pattern with
ignore case. Original patch by Matthew Barnett.

@item 
bpo-21075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21075}: fileinput.FileInput now reads bytes from standard stream if
binary mode is specified.  Patch by Sam Kimbrel.

@item 
bpo-19775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19775}: Add a samefile() method to pathlib Path objects.  Initial patch
by Vajrasky Kok.

@item 
bpo-21226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21226}: Set up modules properly in PyImport_ExecCodeModuleObject (and
friends).

@item 
bpo-21398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21398}: Fix a unicode error in the pydoc pager when the documentation
contains characters not encodable to the stdout encoding.

@item 
bpo-16531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16531}: ipaddress.IPv4Network and ipaddress.IPv6Network now accept an
(address, netmask) tuple argument, so as to easily construct network
objects from existing addresses.

@item 
bpo-21156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21156}: importlib.abc.InspectLoader.source_to_code() is now a
staticmethod.

@item 
bpo-21424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21424}: Simplified and optimized heaqp.nlargest() and nmsmallest() to
make fewer tuple comparisons.

@item 
bpo-21396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21396}: Fix TextIOWrapper(..., write_through=True) to not force a
flush() on the underlying binary stream.  Patch by akira.

@item 
bpo-18314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18314}: Unlink now removes junctions on Windows. Patch by Kim Gräsman

@item 
bpo-21088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21088}: Bugfix for curses.window.addch() regression in 3.4.0. In
porting to Argument Clinic, the first two arguments were reversed.

@item 
bpo-21407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21407}: _decimal: The module now supports function signatures.

@item 
bpo-10650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10650}: Remove the non-standard 'watchexp' parameter from the
Decimal.quantize() method in the Python version.  It had never been
present in the C version.

@item 
bpo-21469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21469}: Reduced the risk of false positives in robotparser by checking
to make sure that robots.txt has been read or does not exist prior to
returning True in can_fetch().

@item 
bpo-19414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19414}: Have the OrderedDict mark deleted links as unusable. This gives
an early failure if the link is deleted during iteration.

@item 
bpo-21421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21421}: Add __slots__ to the MappingViews ABC. Patch by Josh Rosenberg.

@item 
bpo-21101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21101}: Eliminate double hashing in the C speed-up code for
collections.Counter().

@item 
bpo-21321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21321}: itertools.islice() now releases the reference to the source
iterator when the slice is exhausted.  Patch by Anton Afanasyev.

@item 
bpo-21057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21057}: TextIOWrapper now allows the underlying binary stream's read()
or read1() method to return an arbitrary bytes-like object (such as a
memoryview). Patch by Nikolaus Rath.

@item 
bpo-20951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20951}: SSLSocket.send() now raises either SSLWantReadError or
SSLWantWriteError on a non-blocking socket if the operation would block.
Previously, it would return 0.  Patch by Nikolaus Rath.

@item 
bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}: removed previously deprecated asyncore.dispatcher __getattr__
cheap inheritance hack.

@item 
bpo-9815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9815}: assertRaises now tries to clear references to local variables in
the exception's traceback.

@item 
bpo-19940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19940}: ssl.cert_time_to_seconds() now interprets the given time string
in the UTC timezone (as specified in RFC 5280), not the local timezone.

@item 
bpo-13204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13204}: Calling sys.flags.__new__ would crash the interpreter, now it
raises a TypeError.

@item 
bpo-19385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19385}: Make operations on a closed dbm.dumb database always raise the
same exception.

@item 
bpo-21207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21207}: Detect when the os.urandom cached fd has been closed or
replaced, and open it anew.

@item 
bpo-21291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21291}: subprocess's Popen.wait() is now thread safe so that multiple
threads may be calling wait() or poll() on a Popen instance at the same
time without losing the Popen.returncode value.

@item 
bpo-21127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21127}: Path objects can now be instantiated from str subclass
instances (such as @code{numpy.str_}).

@item 
bpo-15002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15002}: urllib.response object to use _TemporaryFileWrapper (and
_TemporaryFileCloser) facility. Provides a better way to handle file
descriptor close. Patch contributed by Christian Theune.

@item 
bpo-12220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12220}: mindom now raises a custom ValueError indicating it doesn't
support spaces in URIs instead of letting a 'split' ValueError bubble up.

@item 
bpo-21068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21068}: The ssl.PROTOCOL* constants are now enum members.

@item 
bpo-21276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21276}: posixmodule: Don't define USE_XATTRS on KFreeBSD and the Hurd.

@item 
bpo-21262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21262}: New method assert_not_called for Mock. It raises AssertionError
if the mock has been called.

@item 
bpo-21238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21238}: New keyword argument @code{unsafe} to Mock. It raises
@code{AttributeError} in case of an attribute startswith assert or assret.

@item 
bpo-20896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20896}: ssl.get_server_certificate() now uses PROTOCOL_SSLv23, not
PROTOCOL_SSLv3, for maximum compatibility.

@item 
bpo-21239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21239}: patch.stopall() didn't work deterministically when the same
name was patched more than once.

@item 
bpo-21203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21203}: Updated fileConfig and dictConfig to remove inconsistencies.
Thanks to Jure Koren for the patch.

@item 
bpo-21222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21222}: Passing name keyword argument to mock.create_autospec now
works.

@item 
bpo-21197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21197}: Add lib64 -> lib symlink in venvs on 64-bit non-OS X POSIX.

@item 
bpo-17498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17498}: Some SMTP servers disconnect after certain errors, violating
strict RFC conformance.  Instead of losing the error code when we issue
the subsequent RSET, smtplib now returns the error code and defers raising
the SMTPServerDisconnected error until the next command is issued.

@item 
bpo-17826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17826}: setting an iterable side_effect on a mock function created by
create_autospec now works. Patch by Kushal Das.

@item 
bpo-7776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7776}: Fix @code{Host:} header and reconnection when using
http.client.HTTPConnection.set_tunnel(). Patch by Nikolaus Rath.

@item 
bpo-20968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20968}: unittest.mock.MagicMock now supports division. Patch by
Johannes Baiter.

@item 
bpo-21529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21529}: Fix arbitrary memory access in JSONDecoder.raw_decode with a
negative second parameter. Bug reported by Guido Vranken. (See also:
@geindex Common Vulnerabilities and Exposures; CVE 2014-4616
CVE 2014-4616@footnote{https://www.cve.org/CVERecord?id=CVE-2014-4616})

@item 
bpo-21169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21169}: getpass now handles non-ascii characters that the input stream
encoding cannot encode by re-encoding using the replace error handler.

@item 
bpo-21171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21171}: Fixed undocumented filter API of the rot13 codec. Patch by
Berker Peksag.

@item 
bpo-20539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20539}: Improved math.factorial error message for large positive inputs
and changed exception type (OverflowError -> ValueError) for large
negative inputs.

@item 
bpo-21172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21172}: isinstance check relaxed from dict to collections.Mapping.

@item 
bpo-21155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21155}: asyncio.EventLoop.create_unix_server() now raises a ValueError
if path and sock are specified at the same time.

@item 
bpo-21136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21136}: Avoid unnecessary normalization of Fractions resulting from
power and other operations.  Patch by Raymond Hettinger.

@item 
bpo-17621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17621}: Introduce importlib.util.LazyLoader.

@item 
bpo-21076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21076}: signal module constants were turned into enums. Patch by
Giampaolo Rodola'.

@item 
bpo-20636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20636}: Improved the repr of Tkinter widgets.

@item 
bpo-19505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19505}: The items, keys, and values views of OrderedDict now support
reverse iteration using reversed().

@item 
bpo-21149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21149}: Improved thread-safety in logging cleanup during interpreter
shutdown. Thanks to Devin Jeanpierre for the patch.

@item 
bpo-21058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21058}: Fix a leak of file descriptor in
@ref{6ed,,tempfile.NamedTemporaryFile()}, close the file descriptor if
@ref{740,,io.open()} fails

@item 
bpo-21200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21200}: Return None from pkgutil.get_loader() when __spec__ is missing.

@item 
bpo-21013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21013}: Enhance ssl.create_default_context() when used for server side
sockets to provide better security by default.

@item 
bpo-20145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20145}: @code{assertRaisesRegex} and @code{assertWarnsRegex} now raise a
@code{TypeError} if the second argument is not a string or compiled regex.

@item 
bpo-20633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20633}: Replace relative import by absolute import.

@item 
bpo-20980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20980}: Stop wrapping exception when using ThreadPool.

@item 
bpo-21082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21082}: In os.makedirs, do not set the process-wide umask. Note this
changes behavior of makedirs when exist_ok=True.

@item 
bpo-20990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20990}: Fix issues found by pyflakes for multiprocessing.

@item 
bpo-21015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21015}: SSL contexts will now automatically select an elliptic curve
for ECDH key exchange on OpenSSL 1.0.2 and later, and otherwise default to
"prime256v1".

@item 
bpo-21000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21000}: Improve the command-line interface of json.tool.

@item 
bpo-20995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20995}: Enhance default ciphers used by the ssl module to enable better
security and prioritize perfect forward secrecy.

@item 
bpo-20884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20884}: Don't assume that __file__ is defined on importlib.__init__.

@item 
bpo-21499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21499}: Ignore __builtins__ in several test_importlib.test_api tests.

@item 
bpo-20627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20627}: xmlrpc.client.ServerProxy is now a context manager.

@item 
bpo-19165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19165}: The formatter module now raises DeprecationWarning instead of
PendingDeprecationWarning.

@item 
bpo-13936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13936}: Remove the ability of datetime.time instances to be considered
false in boolean contexts.

@item 
bpo-18931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18931}: selectors module now supports /dev/poll on Solaris. Patch by
Giampaolo Rodola'.

@item 
bpo-19977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19977}: When the @code{LC_TYPE} locale is the POSIX locale (@code{C} locale),
@ref{75f,,sys.stdin} and @ref{ccd,,sys.stdout} are now using the
@code{surrogateescape} error handler, instead of the @code{strict} error
handler.

@item 
bpo-20574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20574}: Implement incremental decoder for cp65001 code (Windows code
page 65001, Microsoft UTF-8).

@item 
bpo-20879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20879}: Delay the initialization of encoding and decoding tables for
base32, ascii85 and base85 codecs in the base64 module, and delay the
initialization of the unquote_to_bytes() table of the urllib.parse module,
to not waste memory if these modules are not used.

@item 
bpo-19157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19157}: Include the broadcast address in the usable hosts for IPv6 in
ipaddress.

@item 
bpo-11599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11599}: When an external command (e.g. compiler) fails, distutils now
prints out the whole command line (instead of just the command name) if
the environment variable DISTUTILS_DEBUG is set.

@item 
bpo-4931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4931}: distutils should not produce unhelpful "error: None" messages
anymore. distutils.util.grok_environment_error is kept but doc-deprecated.

@item 
bpo-20875@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20875}: Prevent possible gzip "'read' is not defined" NameError. Patch
by Claudiu Popa.

@item 
bpo-11558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11558}: @code{email.message.Message.attach} now returns a more useful
error message if @code{attach} is called on a message for which
@code{is_multipart} is False.

@item 
bpo-20283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20283}: RE pattern methods now accept the string keyword parameters as
documented. The pattern and source keyword parameters are left as
deprecated aliases.

@item 
bpo-20778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20778}: Fix modulefinder to work with bytecode-only modules.

@item 
bpo-20791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20791}: copy.copy() now doesn't make a copy when the input is a bytes
object. Initial patch by Peter Otten.

@item 
bpo-19748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19748}: On AIX, time.mktime() now raises an OverflowError for year
outsize range [1902; 2037].

@item 
bpo-19573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19573}: inspect.signature: Use enum for parameter kind constants.

@item 
bpo-20726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20726}: inspect.signature: Make Signature and Parameter picklable.

@item 
bpo-17373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17373}: Add inspect.Signature.from_callable method.

@item 
bpo-20378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20378}: Improve repr of inspect.Signature and inspect.Parameter.

@item 
bpo-20816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20816}: Fix inspect.getcallargs() to raise correct TypeError for
missing keyword-only arguments. Patch by Jeremiah Lowin.

@item 
bpo-20817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20817}: Fix inspect.getcallargs() to fail correctly if more than 3
arguments are missing. Patch by Jeremiah Lowin.

@item 
bpo-6676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6676}: Ensure a meaningful exception is raised when attempting to parse
more than one XML document per pyexpat xmlparser instance. (Original
patches by Hirokazu Yamamoto and Amaury Forgeot d'Arc, with suggested
wording by David Gutteridge)

@item 
bpo-21117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21117}: Fix inspect.signature to better support functools.partial. Due
to the specifics of functools.partial implementation,
positional-or-keyword arguments passed as keyword arguments become
keyword-only.

@item 
bpo-20334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20334}: inspect.Signature and inspect.Parameter are now hashable.
Thanks to Antony Lee for bug reports and suggestions.

@item 
bpo-15916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15916}: doctest.DocTestSuite returns an empty unittest.TestSuite
instead of raising ValueError if it finds no tests

@item 
bpo-21209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21209}: Fix asyncio.tasks.CoroWrapper to workaround a bug in yield-from
implementation in CPythons prior to 3.4.1.

@item 
asyncio: Add gi_@{frame,running,code@} properties to CoroWrapper (upstream
bpo-163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=163}).

@item 
bpo-21311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21311}: Avoid exception in _osx_support with non-standard compiler
configurations. Patch by John Szakmeister.

@item 
bpo-11571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11571}: Ensure that the turtle window becomes the topmost window when
launched on OS X.

@item 
bpo-21801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21801}: Validate that __signature__ is None or an instance of
Signature.

@item 
bpo-21923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21923}: Prevent AttributeError in
distutils.sysconfig.customize_compiler due to possible uninitialized
_config_vars.

@item 
bpo-21323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21323}: Fix http.server to again handle scripts in CGI subdirectories,
broken by the fix for security bpo-19435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19435}.  Patch by Zach Byrne.

@item 
bpo-22733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22733}: Fix ffi_prep_args not zero-extending argument values correctly
on 64-bit Windows.

@item 
bpo-23302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23302}: Default to TCP_NODELAY=1 upon establishing an HTTPConnection.
Removed use of hard-coded MSS as it's an optimization that's no longer
needed with Nagle disabled.
@end itemize

@node IDLE<63>,ビルド<100>,ライブラリ<207>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1064}@anchor{1fb2}
@subsubsection IDLE



@itemize -

@item 
bpo-20577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20577}: Configuration of the max line length for the FormatParagraph
extension has been moved from the General tab of the Idle preferences
dialog to the FormatParagraph tab of the Config Extensions dialog. Patch
by Tal Einat.

@item 
bpo-16893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16893}: Update Idle doc chapter to match current Idle and add new
information.

@item 
bpo-3068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3068}: Add Idle extension configuration dialog to Options menu. Changes
are written to HOME/.idlerc/config-extensions.cfg. Original patch by Tal
Einat.

@item 
bpo-16233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16233}: A module browser (File : Class Browser, Alt+C) requires an
editor window with a filename.  When Class Browser is requested otherwise,
from a shell, output window, or 'Untitled' editor, Idle no longer displays
an error box. It now pops up an Open Module box (Alt+M). If a valid name
is entered and a module is opened, a corresponding browser is also opened.

@item 
bpo-4832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4832}: Save As to type Python files automatically adds .py to the name
you enter (even if your system does not display it).  Some systems
automatically add .txt when type is Text files.

@item 
bpo-21986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21986}: Code objects are not normally pickled by the pickle module. To
match this, they are no longer pickled when running under Idle.

@item 
bpo-17390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17390}: Adjust Editor window title; remove 'Python', move version to
end.

@item 
bpo-14105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14105}: Idle debugger breakpoints no longer disappear when inserting or
deleting lines.

@item 
bpo-17172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17172}: Turtledemo can now be run from Idle. Currently, the entry is on
the Help menu, but it may move to Run. Patch by Ramchandra Apt and Lita
Cho.

@item 
bpo-21765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21765}: Add support for non-ascii identifiers to HyperParser.

@item 
bpo-21940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21940}: Add unittest for WidgetRedirector. Initial patch by Saimadhav
Heblikar.

@item 
bpo-18592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18592}: Add unittest for SearchDialogBase. Patch by Phil Webster.

@item 
bpo-21694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21694}: Add unittest for ParenMatch. Patch by Saimadhav Heblikar.

@item 
bpo-21686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21686}: add unittest for HyperParser. Original patch by Saimadhav
Heblikar.

@item 
bpo-12387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12387}: Add missing upper(lower)case versions of default Windows key
bindings for Idle so Caps Lock does not disable them. Patch by Roger
Serwy.

@item 
bpo-21695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21695}: Closing a Find-in-files output window while the search is still
in progress no longer closes Idle.

@item 
bpo-18910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18910}: Add unittest for textView. Patch by Phil Webster.

@item 
bpo-18292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18292}: Add unittest for AutoExpand. Patch by Saihadhav Heblikar.

@item 
bpo-18409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18409}: Add unittest for AutoComplete. Patch by Phil Webster.

@item 
bpo-21477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21477}: htest.py - Improve framework, complete set of tests. Patches by
Saimadhav Heblikar

@item 
bpo-18104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18104}: Add idlelib/idle_test/htest.py with a few sample tests to begin
consolidating and improving human-validated tests of Idle. Change other
files as needed to work with htest.  Running the module as __main__ runs
all tests.

@item 
bpo-21139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21139}: Change default paragraph width to 72, the 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/}
recommendation.

@item 
bpo-21284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21284}: Paragraph reformat test passes after user changes reformat
width.

@item 
bpo-17654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17654}: Ensure IDLE menus are customized properly on OS X for
non-framework builds and for all variants of Tk.

@item 
bpo-23180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23180}: Rename IDLE "Windows" menu item to "Window". Patch by Al
Sweigart.
@end itemize

@node ビルド<100>,C API<79>,IDLE<63>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1065}@anchor{1fb3}
@subsubsection ビルド



@itemize -

@item 
bpo-15506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15506}: Use standard PKG_PROG_PKG_CONFIG autoconf macro in the
configure script.

@item 
bpo-22935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22935}: Allow the ssl module to be compiled if openssl doesn't support
SSL 3.

@item 
bpo-22592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22592}: Drop support of the Borland C compiler to build Python. The
distutils module still supports it to build extensions.

@item 
bpo-22591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22591}: Drop support of MS-DOS, especially of the DJGPP compiler
(MS-DOS port of GCC).

@item 
bpo-16537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16537}: Check whether self.extensions is empty in setup.py. Patch by
Jonathan Hosmer.

@item 
bpo-22359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22359}: Remove incorrect uses of recursive make.  Patch by Jonas
Wagner.

@item 
bpo-21958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21958}: Define HAVE_ROUND when building with Visual Studio 2013 and
above.  Patch by Zachary Turner.

@item 
bpo-18093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18093}: the programs that embed the CPython runtime are now in a
separate "Programs" directory, rather than being kept in the Modules
directory.

@item 
bpo-15759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15759}: "make suspicious", "make linkcheck" and "make doctest" in Doc/
now display special message when and only when there are failures.

@item 
bpo-21141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21141}: The Windows build process no longer attempts to find Perl,
instead relying on OpenSSL source being configured and ready to build.
The @code{PCbuild\build_ssl.py} script has been re-written and re-named to
@code{PCbuild\prepare_ssl.py}, and takes care of configuring OpenSSL source
for both 32 and 64 bit platforms.  OpenSSL sources obtained from
svn.python.org will always be pre-configured and ready to build.

@item 
bpo-21037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21037}: Add a build option to enable AddressSanitizer support.

@item 
bpo-19962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19962}: The Windows build process now creates "python.bat" in the root
of the source tree, which passes all arguments through to the most
recently built interpreter.

@item 
bpo-21285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21285}: Refactor and fix curses configure check to always search in a
ncursesw directory.

@item 
bpo-15234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15234}: For BerkeleyDB and Sqlite, only add the found library and
include directories if they aren't already being searched. This avoids an
explicit runtime library dependency.

@item 
bpo-17861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17861}: Tools/scripts/generate_opcode_h.py automatically regenerates
Include/opcode.h from Lib/opcode.py if the latter gets any change.

@item 
bpo-20644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20644}: OS X installer build support for documentation build changes in
3.4.1: assume externally supplied sphinx-build is available in /usr/bin.

@item 
bpo-20022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20022}: Eliminate use of deprecated bundlebuilder in OS X builds.

@item 
bpo-15968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15968}: Incorporated Tcl, Tk, and Tix builds into the Windows build
solution.

@item 
bpo-17095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17095}: Fix Modules/Setup `shared' support.

@item 
bpo-21811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21811}: Anticipated fixes to support OS X versions > 10.9.

@item 
bpo-21166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21166}: Prevent possible segfaults and other random failures of python
--generate-posix-vars in pybuilddir.txt build target.

@item 
bpo-18096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18096}: Fix library order returned by python-config.

@item 
bpo-17219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17219}: Add library build dir for Python extension cross-builds.

@item 
bpo-22919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22919}: Windows build updated to support VC 14.0 (Visual Studio 2015),
which will be used for the official release.

@item 
bpo-21236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21236}: Build _msi.pyd with cabinet.lib instead of fci.lib

@item 
bpo-17128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17128}: Use private version of OpenSSL for OS X 10.5+ installer.
@end itemize

@node C API<79>,ドキュメント<85>,ビルド<100>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1066}@anchor{1fb4}
@subsubsection C API



@itemize -

@item 
bpo-14203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14203}: Remove obsolete support for view==NULL in PyBuffer_FillInfo(),
bytearray_getbuffer(), bytesiobuf_getbuffer() and array_buffer_getbuf().
All functions now raise BufferError in that case.

@item 
bpo-22445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22445}: PyBuffer_IsContiguous() now implements precise contiguity
tests, compatible with NumPy's NPY_RELAXED_STRIDES_CHECKING compilation
flag.  Previously the function reported false negatives for corner cases.

@item 
bpo-22079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22079}: PyType_Ready() now checks that statically allocated type has no
dynamically allocated bases.

@item 
bpo-22453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22453}: Removed non-documented macro PyObject_REPR().

@item 
bpo-18395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18395}: Rename @code{_Py_char2wchar()} to @ref{dc0,,Py_DecodeLocale()},
rename @code{_Py_wchar2char()} to @ref{dc1,,Py_EncodeLocale()}, and document
these functions.

@item 
bpo-21233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21233}: Add new C functions: PyMem_RawCalloc(), PyMem_Calloc(),
PyObject_Calloc(), _PyObject_GC_Calloc(). bytes(int) is now using
@code{calloc()} instead of @code{malloc()} for large objects which is faster and
use less memory.

@item 
bpo-20942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20942}: PyImport_ImportFrozenModuleObject() no longer sets __file__ to
match what importlib does; this affects _frozen_importlib as well as any
module loaded using imp.init_frozen().
@end itemize

@node ドキュメント<85>,テスト<88>,C API<79>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1067}@anchor{1fb5}
@subsubsection ドキュメント



@itemize -

@item 
bpo-19548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19548}: Update the codecs module documentation to better cover the
distinction between text encodings and other codecs, together with other
clarifications. Patch by Martin Panter.

@item 
bpo-22394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22394}: Doc/Makefile now supports @code{make venv PYTHON=../python} to
create a venv for generating the documentation, e.g., @code{make html
PYTHON=venv/bin/python3}.

@item 
bpo-21514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21514}: The documentation of the json module now refers to new JSON RFC
7159 instead of obsoleted RFC 4627.

@item 
bpo-21777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21777}: The binary sequence methods on bytes and bytearray are now
documented explicitly, rather than assuming users will be able to derive
the expected behaviour from the behaviour of the corresponding str
methods.

@item 
bpo-6916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6916}: undocument deprecated asynchat.fifo class.

@item 
bpo-17386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17386}: Expanded functionality of the @code{Doc/make.bat} script to make
it much more comparable to @code{Doc/Makefile}.

@item 
bpo-21312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21312}: Update the thread_foobar.h template file to include newer
threading APIs. Patch by Jack McCracken.

@item 
bpo-21043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21043}: Remove the recommendation for specific CA organizations and to
mention the ability to load the OS certificates.

@item 
bpo-20765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20765}: Add missing documentation for PurePath.with_name() and
PurePath.with_suffix().

@item 
bpo-19407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19407}: New package installation and distribution guides based on the
Python Packaging Authority tools. Existing guides have been retained as
legacy links from the distutils docs, as they still contain some required
reference material for tool developers that isn't recorded anywhere else.

@item 
bpo-19697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19697}: Document cases where __main__.__spec__ is None.
@end itemize

@node テスト<88>,Tools/Demos<61>,ドキュメント<85>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1068}@anchor{1fb6}
@subsubsection テスト



@itemize -

@item 
bpo-18982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18982}: Add tests for CLI of the calendar module.

@item 
bpo-19548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19548}: Added some additional checks to test_codecs to ensure that
statements in the updated documentation remain accurate. Patch by Martin
Panter.

@item 
bpo-22838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22838}: All test_re tests now work with unittest test discovery.

@item 
bpo-22173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22173}: Update lib2to3 tests to use unittest test discovery.

@item 
bpo-16000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16000}: Convert test_curses to use unittest.

@item 
bpo-21456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21456}: Skip two tests in test_urllib2net.py if _ssl module not
present. Patch by Remi Pointel.

@item 
bpo-20746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20746}: Fix test_pdb to run in refleak mode (-R).  Patch by Xavier de
Gaye.

@item 
bpo-22060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22060}: test_ctypes has been somewhat cleaned up and simplified; it now
uses unittest test discovery to find its tests.

@item 
bpo-22104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22104}: regrtest.py no longer holds a reference to the suite of tests
loaded from test modules that don't define test_main().

@item 
bpo-22111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22111}: Assorted cleanups in test_imaplib.  Patch by Milan Oberkirch.

@item 
bpo-22002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22002}: Added @code{load_package_tests} function to test.support and used
it to implement/augment test discovery in test_asyncio, test_email,
test_importlib, test_json, and test_tools.

@item 
bpo-21976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21976}: Fix test_ssl to accept LibreSSL version strings.  Thanks to
William Orr.

@item 
bpo-21918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21918}: Converted test_tools from a module to a package containing
separate test files for each tested script.

@item 
bpo-9554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9554}: Use modern unittest features in test_argparse. Initial patch by
Denver Coneybeare and Radu Voicilas.

@item 
bpo-20155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20155}: Changed HTTP method names in failing tests in test_httpservers
so that packet filtering software (specifically Windows Base Filtering
Engine) does not interfere with the transaction semantics expected by the
tests.

@item 
bpo-19493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19493}: Refactored the ctypes test package to skip tests explicitly
rather than silently.

@item 
bpo-18492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18492}: All resources are now allowed when tests are not run by
regrtest.py.

@item 
bpo-21634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21634}: Fix pystone micro-benchmark: use floor division instead of true
division to benchmark integers instead of floating-point numbers. Set
pystone version to 1.2. Patch written by Lennart Regebro.

@item 
bpo-21605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21605}: Added tests for Tkinter images.

@item 
bpo-21493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21493}: Added test for ntpath.expanduser().  Original patch by Claudiu
Popa.

@item 
bpo-19925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19925}: Added tests for the spwd module. Original patch by Vajrasky
Kok.

@item 
bpo-21522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21522}: Added Tkinter tests for Listbox.itemconfigure(),
PanedWindow.paneconfigure(), and Menu.entryconfigure().

@item 
bpo-17756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17756}: Fix test_code test when run from the installed location.

@item 
bpo-17752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17752}: Fix distutils tests when run from the installed location.

@item 
bpo-18604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18604}: Consolidated checks for GUI availability.  All platforms now at
least check whether Tk can be instantiated when the GUI resource is
requested.

@item 
bpo-21275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21275}: Fix a socket test on KFreeBSD.

@item 
bpo-21223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21223}: Pass test_site/test_startup_imports when some of the extensions
are built as builtins.

@item 
bpo-20635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20635}: Added tests for Tk geometry managers.

@item 
Add test case for freeze.

@item 
bpo-20743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20743}: Fix a reference leak in test_tcl.

@item 
bpo-21097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21097}: Move test_namespace_pkgs into test_importlib.

@item 
bpo-21503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21503}: Use test_both() consistently in test_importlib.

@item 
bpo-20939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20939}: Avoid various network test failures due to new redirect of
@indicateurl{http://www.python.org/} to @indicateurl{https://www.python.org}: use
@indicateurl{http://www.example.com} instead.

@item 
bpo-20668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20668}: asyncio tests no longer rely on tests.txt file. (Patch by
Vajrasky Kok)

@item 
bpo-21093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21093}: Prevent failures of ctypes test_macholib on OS X if a copy of
libz exists in $HOME/lib or /usr/local/lib.

@item 
bpo-22770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22770}: Prevent some Tk segfaults on OS X when running gui tests.

@item 
bpo-23211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23211}: Workaround test_logging failure on some OS X 10.6 systems.

@item 
bpo-23345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23345}: Prevent test_ssl failures with large OpenSSL patch level values
(like 0.9.8zc).
@end itemize

@node Tools/Demos<61>,Windows<83>,テスト<88>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1069}@anchor{1fb7}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-22314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22314}: pydoc now works when the LINES environment variable is set.

@item 
bpo-22615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22615}: Argument Clinic now supports the "type" argument for the int
converter. This permits using the int converter with enums and typedefs.

@item 
bpo-20076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20076}: The makelocalealias.py script no longer ignores UTF-8 mapping.

@item 
bpo-20079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20079}: The makelocalealias.py script now can parse the SUPPORTED file
from glibc sources and supports command line options for source paths.

@item 
bpo-22201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22201}: Command-line interface of the zipfile module now correctly
extracts ZIP files with directory entries.  Patch by Ryan Wilson.

@item 
bpo-22120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22120}: For functions using an unsigned integer return converter,
Argument Clinic now generates a cast to that type for the comparison to -1
in the generated code.  (This suppresses a compilation warning.)

@item 
bpo-18974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18974}: Tools/scripts/diff.py now uses argparse instead of optparse.

@item 
bpo-21906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21906}: Make Tools/scripts/md5sum.py work in Python 3. Patch by Zachary
Ware.

@item 
bpo-21629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21629}: Fix Argument Clinic's "--converters" feature.

@item 
Add support for @code{yield from} to 2to3.

@item 
Add support for the 
@geindex Python Enhancement Proposals; PEP 465
PEP 465@footnote{https://peps.python.org/pep-0465/} matrix multiplication operator to 2to3.

@item 
bpo-16047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16047}: Fix module exception list and __file__ handling in freeze.
Patch by Meador Inge.

@item 
bpo-11824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11824}: Consider ABI tags in freeze. Patch by Meador Inge.

@item 
bpo-20535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20535}: PYTHONWARNING no longer affects the run_tests.py script. Patch
by Arfrever Frehtes Taifersar Arahesis.
@end itemize

@node Windows<83>,,Tools/Demos<61>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id1070}@anchor{1fb8}
@subsubsection Windows



@itemize -

@item 
bpo-23260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23260}: Update Windows installer

@item 
The bundled version of Tcl/Tk has been updated to 8.6.3.  The most visible
result of this change is the addition of new native file dialogs when
running on Windows Vista or newer.  See Tcl/Tk's TIP 432 for more
information.  Also, this version of Tcl/Tk includes support for Windows
10.

@item 
bpo-17896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17896}: The Windows build scripts now expect external library sources
to be in @code{PCbuild\..\externals} rather than @code{PCbuild\..\..}.

@item 
bpo-17717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17717}: The Windows build scripts now use a copy of NASM pulled from
svn.python.org to build OpenSSL.

@item 
bpo-21907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21907}: Improved the batch scripts provided for building Python.

@item 
bpo-22644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22644}: The bundled version of OpenSSL has been updated to 1.0.1j.

@item 
bpo-10747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10747}: Use versioned labels in the Windows start menu. Patch by Olive
Kilburn.

@item 
bpo-22980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22980}: .pyd files with a version and platform tag (for example,
".cp35-win32.pyd") will now be loaded in preference to those without tags.
@end itemize

`(For information about older versions, consult the HISTORY file.)'

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python チュートリアル,Python のセットアップと利用,What's New in Python,Top
@anchor{tutorial/index doc}@anchor{1fb9}@anchor{tutorial/index the-python-tutorial}@anchor{1fba}@anchor{tutorial/index translation-repo}@anchor{1fbb}@anchor{tutorial/index tutorial-index}@anchor{1fbc}
@chapter Python チュートリアル


@cartouche
@quotation Tip 
このチュートリアルはPython言語を初めて使う `プログラマー' 向けに設計されており、プログラミングが初めの `初心者' 向け `ではありません' 。
@end quotation
@end cartouche

Python は強力で、学びやすいプログラミング言語です。効率的な高レベルデータ構造と、シンプルで効果的なオブジェクト指向プログラミング機構を備えています。
Python は、洗練された文法・動的なデータ型付け・インタープリタであることなどから、スクリプティングや高速アプリケーション開発(Rapid Application Development: RAD)に理想的なプログラミング言語となっています。

Python Web サイト(@indicateurl{https://www.python.org}) は、 Python インタープリタと標準ライブラリのソースコードと、主要プラットフォームごとにコンパイル済みのバイナリファイルを無料で配布しています。また、Python Web サイトには、無料のサードパーティモジュールやプログラム、ツール、ドキュメントなども紹介しています。

Python インタプリタは、簡単に C/C++ 言語などで実装された関数やデータ型を組み込み、拡張できます。また、アプリケーションのカスタマイズを行う、拡張言語としても適しています。

このチュートリアルは、Python 言語の基本的な概念と機能を、形式ばらずに紹介します。一般的なプログラミンの基礎知識があることを前提として書かれていることに注意してください。読むだけではなく、Pythonインタープリタで実際にサンプルを実行すると理解が深まりますが、サンプルはそれぞれ独立していますので、ただ読むだけでも良いでしょう。

標準オブジェクトやモジュールの詳細は、 @ref{149,,Python 標準ライブラリ} を参照してください。 また、正式な言語定義は、 @ref{14a,,Python 言語リファレンス} にあります。 C 言語や C++ 言語で拡張モジュールを書くなら、 @ref{1fbd,,Python インタプリタの拡張と埋め込み} や @ref{1fbe,,Python/C API リファレンスマニュアル} を参照してください。Python の解説書も販売されています。

このチュートリアルは、Python全体を対象とした、包括的な解説書ではありません。よく使われる機能に限っても、全ては紹介していません。その代わり、このチュートリアルでは、Pythonのもっとも特徴的な機能を中心に紹介して、この言語の持ち味や、スタイルを感じられるようにしています。このチュートリアルを読み終えると、Python のモジュールやプログラムを読み書きできるようになっているでしょう。また、@ref{149,,Python 標準ライブラリ} のさまざまな Python ライブラリモジュールを、詳しく調べられるようになっているはずです。

@ref{1fbf,,用語集} にも目を通しておくと良いでしょう。

@menu
* やる気を高めよう:: 
* Python インタプリタを使う:: 
* 形式ばらない Python の紹介:: 
* その他の制御フローツール:: 
* データ構造:: 
* モジュール: モジュール<2>. 
* 入力と出力:: 
* エラーと例外:: 
* クラス:: 
* 標準ライブラリミニツアー:: 
* 標準ライブラリミニツアー: 標準ライブラリミニツアー --- その 2. その 2
* 仮想環境とパッケージ:: 
* さあ何を？:: 
* 対話入力編集と履歴置換:: 
* 浮動小数点演算、その問題と制限:: 
* 付録:: 

@end menu

@node やる気を高めよう,Python インタプリタを使う,,Python チュートリアル
@anchor{tutorial/appetite doc}@anchor{1fc0}@anchor{tutorial/appetite tut-intro}@anchor{1fc1}@anchor{tutorial/appetite whetting-your-appetite}@anchor{1fc2}
@section やる気を高めよう


コンピュータを使っていろいろな作業をしていると、自動化したい作業が出てくるでしょう。たとえば、たくさんのテキストファイルで検索-置換操作を行いたい、大量の写真ファイルを込み入ったやりかたでファイル名を整理して変更したり、などです。ちょっとした専用のデータベースや、何か専用のGUIアプリケーション、シンプルなゲームを作りたいかもしれません。

あなたがプロのソフト開発者として、C/C++/Java ライブラリを扱う必要があるけども、通常の編集/コンパイル/テスト/再コンパイルのサイクルを遅すぎると感じているかもしれません。上記ライブラリのためのテストを書くことにうんざりしているかもしれません。または、拡張言語を持つアプリケーションを書いているなら、そのために新しい言語一式の設計と実装をしたくないでしょう。

Pythonはそんなあなたのための言語です。

そういった処理は、Unix シェルスクリプトや Windows バッチファイルで書くこともできます。しかし、シェルスクリプトはファイル操作やテキストデータの操作には向いていますが、GUIアプリケーションやゲームにはむいていません。C/C++/Java プログラムを書くこともできますが、最初の試し書きだけでもかなりの時間がかかってしまいます。Pythonはもっと簡単に利用でき、Windows、macOS、そして Unix オペレーティングシステムで動作し、あなたの仕事をすばやく片付ける助けになるでしょう。

Python は簡単に利用できますが、本物のプログラミング言語であり、シェルスクリプトやバッチファイルよりも多くの機構があり、大きなプログラムの開発にも適しています。一方では、Python は C よりたくさんのエラーチェックを実行時に行っており、また可変長配列や辞書などの高級な型を組込みで持つ `超高級言語(very-high-level language)' です。Python は Awk や Perl などよりも汎用的なデータ型を備えており、より多くの領域で利用できます。また、Pythonはこれらの言語と比べても、少なくとも同じぐらいには簡単です。

Python では、プログラムをモジュールに分割して、他の Python プログラムで再利用できます。Python には膨大な標準モジュールが付属していて、プログラムを作る上での基盤として、あるいは Python プログラミングを学ぶためのサンプルとして利用できます。標準モジュールには、ファイル I/O、システムコール、ソケットといった機能や、Tk のようなグラフィカルユーザインターフェースツールキットを使うためのインターフェイスなども提供しています。

Python はインタプリタ言語です。コンパイルやリンクの必要がないので、プログラムを開発する際にかなりの時間を節約できます。インタプリタは対話的にも使えるので、言語の様々な機能について実験してみたり、書き捨てのプログラムを書いたり、ボトムアップでプログラムを開発する際に、関数をテストしたりといったことが簡単にできます。便利な電卓にもなります。

Python では、とてもコンパクトで読みやすいプログラムを書けます。Python で書かれたプログラムは大抵、同じ機能の C 言語, C++ 言語や Java のプログラムよりもはるかに短くなります。これには以下のようないくつかの理由があります:


@itemize *

@item 
高レベルのデータ型によって、複雑な操作を一つの実行文で表現できます。

@item 
実行文のグループ化を、グループの開始や終了の括弧ではなくインデントで行えます。

@item 
変数や引数の宣言が不要です。
@end itemize

Python には `拡張性' があります: C 言語でプログラムを書く方法を知っているなら、簡単に新たな組み込み関数やモジュールを、簡単にインタプリタに追加できます。これによって、いちばん時間のかかる処理を高速化したり、ベンダ特有のグラフィクスライブラリなどの、 バイナリ形式でしか手に入らないライブラリを Python にリンクしたりできます。その気になれば、Python インタプリタを C で書かれたアプリケーションにリンクして、アプリケーションに対する拡張言語や命令言語としても使えます。

ところで、この言語は BBC のショー番組、"モンティパイソンの空飛ぶサーカス (Monty Python's Flying Circus)" から取ったもので、爬虫類とは関係ありません。このドキュメントでは、モンティパイソンの寸劇への参照が許可されているだけでなく、むしろ推奨されています！

さて、皆さんはもう Python にワクワクして、もうちょっと詳しく調べてみたくなったはずです。プログラミング言語を習得する最良の方法は使ってみることですから、このチュートリアルではみなさんが読んだ内容を Python インタプリタで試してみることをおすすめします。

次の章では、まずインタプリタの使い方を説明します。これはわかりきった内容かもしれませんが、後に説明する例題を試してみる上で不可欠なことです。

チュートリアルの残りの部分では、Python プログラム言語と実行システムの様々な機能を例題を交えて紹介します。単純な式、実行文、データ型から始めて、関数とモジュールを経て、最後には例外処理やユーザ定義クラスといったやや高度な概念にも触れます。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python インタプリタを使う,形式ばらない Python の紹介,やる気を高めよう,Python チュートリアル
@anchor{tutorial/interpreter doc}@anchor{1fc3}@anchor{tutorial/interpreter translation-repo}@anchor{1fc4}@anchor{tutorial/interpreter tut-using}@anchor{1fc5}@anchor{tutorial/interpreter using-the-python-interpreter}@anchor{1fc6}
@section Python インタプリタを使う


@menu
* インタプリタを起動する:: 
* インタプリタとその環境:: 

@end menu

@node インタプリタを起動する,インタプリタとその環境,,Python インタプリタを使う
@anchor{tutorial/interpreter invoking-the-interpreter}@anchor{1fc7}@anchor{tutorial/interpreter tut-invoking}@anchor{1fc8}
@subsection インタプリタを起動する


Python が使用可能な環境では、インタプリタは一般的に @code{/usr/local/bin/python3.14} にインストールされています。使用している Unix シェルの検索パスに @code{/usr/local/bin} を追加すると、次のコマンドでインタプリタを開始できます:

@example
python3.14
@end example

@footnote{
Unixでは、Python 3.x インタープリタの実行ファイルはデフォルトでは @code{python} という名前ではインストールされません。同時にインストールされた Python 2.x 実行ファイルと衝突させないためです。
} どのディレクトリに Python インタプリタをインストールするかはインストール時に選択できるので、インタプリタは他のディレクトリにあるかもしれません; 身近な Python に詳しい人か、システム管理者に聞いてみてください。 (例えば、その他の場所としては @code{/usr/local/python} が一般的です。)

@ref{1fc9,,Microsoft ストア} からPythonのインストールを行った Windows マシンでは、 @code{python3.14} コマンドが利用できます。
@ref{7da,,py.exe ランチャ} をインストールした場合、 @code{py} コマンドが使えます。
Python を起動する他の方法については @ref{1fca,,Python install manager} を参照してください。

ファイル終端文字 (Unixでは @code{Control}-@code{D} 、DOS や Windows では @code{Control}-@code{Z}) を一次プロンプト (訳注: '>>>' のこと) に入力すると、インタプリタが終了ステータス 0 で終了します。もしこの操作がうまく働かないなら、コマンド: @code{quit()} と入力すればインタプリタを終了できます。

The interpreter's line-editing features include interactive editing, history
substitution and code completion on most systems.
Perhaps the quickest check to see whether command line editing is supported is
typing a word in on the Python prompt, then pressing Left arrow (or @code{Control}-@code{b}).
If the cursor moves, you have command line editing; see Appendix
@ref{1fcb,,対話入力編集と履歴置換} for an introduction to the keys.
If nothing appears to happen, or if a sequence like @code{^[[D} or @code{^B} appears,
command line editing isn't available; you'll only be able to use
backspace to remove characters from the current line.

インタプリタは Unix シェルと同じように使えます。標準入力が端末に接続された状態では、コマンドを対話的に読み込んで実行します。ファイル名を引数に指定するか、@code{python3 < filename} のように標準入力ファイルとして指定すると、インタプリタはファイルから `スクリプト' を読み込んで実行します。

インタプリタを @code{python -c command [arg] ...} のように起動する方法もあります。この形式では、シェルの @ref{1a8,,-c} オプションと同じように、 `command' に指定した文を実行します。 Python 文には、スペースなどのシェルにとって特殊な意味をもつ文字がしばしば含まれるので、 `command' 全体をクォート(訳注: @code{'})で囲っておいたほうが良いでしょう。

Python のモジュールには、スクリプトとしても便利に使えるものがあります。 @code{python -m module [arg] ...} のように起動すると、 `module' のソースファイルを、フルパスを指定して起動したかのように実行できます。

スクリプトファイルを使用する場合、スクリプトの実行が完了した後、そのまま対話モードに入れると便利なことがあります。これには @ref{16f4,,-i} をスクリプト名の前に追加します。

全てのコマンドラインオプションは @ref{1da7,,コマンドラインと環境} で説明されています。

@menu
* 引数の受け渡し:: 
* 対話モード:: 

@end menu

@node 引数の受け渡し,対話モード,,インタプリタを起動する
@anchor{tutorial/interpreter argument-passing}@anchor{1fcc}@anchor{tutorial/interpreter tut-argpassing}@anchor{1fcd}
@subsubsection 引数の受け渡し


スクリプト名と引数を指定してインタプリタを起動した場合、スクリプト名やスクリプト名以後に指定した引数は、文字列のリストに変換されて @code{sys} モジュールの @code{argv} 変数に格納されます。 @code{import sys} とすることでこのリストにアクセスできます。
@code{sys.argv} には少なくとも一つ要素が入っています。スクリプト名も引数も指定しなければ、 @code{sys.argv[0]} は空の文字列になります。
スクリプト名の代わりに @code{'-'} (標準入力を意味します) を指定すると、 @code{sys.argv[0]} は @code{'-'} になります。
@ref{1a8,,-c}  `command' を使うと、 @code{sys.argv[0]} は @code{'-c'} になります。 @ref{23c,,-m} `module' を使った場合、 @code{sys.argv[0]} はモジュールのフルパスになります。 Python インタープリタは、@ref{1a8,,-c} `command' や @ref{23c,,-m} `module' の後ろに指定したオプションは無視します。無視された引数は、@code{sys.argv} を使って `command' や `module' から参照できます。

@node 対話モード,,引数の受け渡し,インタプリタを起動する
@anchor{tutorial/interpreter interactive-mode}@anchor{1fce}@anchor{tutorial/interpreter tut-interactive}@anchor{443}
@subsubsection 対話モード


インタプリタが命令を端末 (tty) やコマンドプロンプトから読み取っている場合、インタプリタは `対話モード (interactive mode)' で動作しているといいます。
このモードでは、インタプリタは `一次プロンプト (primary prompt)' を表示して、ユーザにコマンドを入力するよう促します。一次プロンプトは普通、三つの「大なり記号」 (@code{>>>}) です。継続行では、インタプリタは `二次プロンプト (secondary prompt)' を表示します。二次プロンプトは、デフォルトでは三つのドット (@code{...}) です。
インタプリタは、最初のプロンプトを出す前にバージョン番号と著作権表示から始まる起動メッセージを出力します:

@example
$ python3.14
Python 3.14 (default, April 4 2024, 09:25:04)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
@end example

@c XXX update for new releases

継続行は、複数行の構文を入力するときに使います。例えば、 @ref{181,,if} 文は継続行を使用します

@example
>>> the_world_is_flat = True
>>> if the_world_is_flat:
...     print("Be careful not to fall off!")
...
Be careful not to fall off!
@end example

対話モードについての詳細は @ref{494,,対話モード} を参照してください。

@node インタプリタとその環境,,インタプリタを起動する,Python インタプリタを使う
@anchor{tutorial/interpreter the-interpreter-and-its-environment}@anchor{1fcf}@anchor{tutorial/interpreter tut-interp}@anchor{1fd0}
@subsection インタプリタとその環境


@menu
* ソースコードの文字コード:: 

@end menu

@node ソースコードの文字コード,,,インタプリタとその環境
@anchor{tutorial/interpreter source-code-encoding}@anchor{1fd1}@anchor{tutorial/interpreter tut-source-encoding}@anchor{1fd2}
@subsubsection ソースコードの文字コード


デフォルトでは、Python のソースコードは UTF-8 でエンコードされているものとして扱われます。UTF-8 では、世界中のほとんどの言語の文字を、同時に文字列リテラル、識別子、コメントなどに書けます。--- ただし、標準ライブラリは識別子に ASCII 文字のみを利用していて、その他のポータブルなコードもその慣習に従うべきです。それらの文字を正しく表示するためには、エディターはそのファイルが UTF-8 である事を識別して、そのファイルに含まれている文字を全てサポートしたフォントを使わなければなりません。

デフォルトエンコーディング以外のエンコーディングを使用するには、ファイルの `先頭' の行に特別なコメントを追加しなければなりません。書式は以下の通りです:

@example
# -*- coding: encoding -*-
@end example

`encoding' には、Python が @ref{1c,,codecs} でサポートしている有効なエンコーディングを指定します。

例えば、Windows-1252 エンコーディングを使用するには、ソースコードファイルの先頭行は下記のようにします:

@example
# -*- coding: cp1252 -*-
@end example

ソースコードが @ref{1fd3,,UNIX "shebang" 行} で始まる場合には、`先頭行' のルールは当てはまりません。
この場合には、エンコーディングの宣言はファイルの2行目に追加します。
例えば以下のようになります:

@example
#!/usr/bin/env python3
# -*- coding: cp1252 -*-
@end example

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 形式ばらない Python の紹介,その他の制御フローツール,Python インタプリタを使う,Python チュートリアル
@anchor{tutorial/introduction doc}@anchor{1fd4}@anchor{tutorial/introduction an-informal-introduction-to-python}@anchor{1fd5}@anchor{tutorial/introduction translation-repo}@anchor{1fd6}@anchor{tutorial/introduction tut-informal}@anchor{1fd7}
@section 形式ばらない Python の紹介


以下のサンプルでは、入力と出力はプロンプト (@ref{492,,>>>} や @ref{493,,...}) の有無で区別します: 例を実際に試す場合は、プロンプトが表示されているときに、サンプル中のプロンプトから後ろの内容全てを入力します。


@geindex # (hash);コメント

このマニュアルにあるサンプルの多くは、対話プロンプトで入力されるものでもコメントを含んでいます。 Python におけるコメント文は、ハッシュ文字 @code{#} で始まり、物理行の終わりまで続きます。コメントは行の先頭にも、空白やコードの後にも書くことができますが、文字列リテラルの内部に置くことはできません。文字列リテラル中のハッシュ文字はただのハッシュ文字です。コメントはコードを明快にするためのものであり、Pythonはコメントを解釈しません。なので、サンプルコードを実際に入力して試して見るときは、コメントを省いても大丈夫です。

いくつかの例です:

@example
# これは最初のコメント
spam = 1  # そしてこれは2つめのコメント
          # ...そして3つめ!
text = "# これはクォーテーションの間なのでコメントではない。"
@end example

@menu
* Python を電卓として使う:: 
* プログラミングへの第一歩:: 

@end menu

@node Python を電卓として使う,プログラミングへの第一歩,,形式ばらない Python の紹介
@anchor{tutorial/introduction tut-calculator}@anchor{1fd8}@anchor{tutorial/introduction using-python-as-a-calculator}@anchor{1fd9}
@subsection Python を電卓として使う


それでは、簡単な Python コマンドをいくつか試してみましょう。インタプリタを起動して、一次プロンプト、 @code{>>>} が現れるのを待ちます。 (そう長くはかからないはずです)

@menu
* 数:: 
* テキスト:: 
* リスト型 (list): リスト型 list. 

@end menu

@node 数,テキスト,,Python を電卓として使う
@anchor{tutorial/introduction numbers}@anchor{1fda}@anchor{tutorial/introduction tut-numbers}@anchor{1fdb}
@subsubsection 数


インタプリタは、簡単な電卓のように動作します: 式を入力すると、その結果が表示されます。
式の文法は素直なものです: 演算子 @code{+} 、 @code{-} 、 @code{*} 、 @code{/} によって算術演算を行うことができ、丸括弧 (@code{()}) をグループ化に使うことができます。
例えば:

@example
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # 除算は常に浮動小数点数(float)を返す
1.6
@end example

整数 (例えば、 @code{2} 、 @code{4} 、 @code{20}) は @ref{19b,,int} 型であり、小数部を持つ数 (例えば、 @code{5.0} 、 @code{1.6}) は @ref{196,,float} 型です。数値型については後のチュートリアルでさらに見ていきます。

除算 (@code{/}) は常に浮動小数点数を返します。 @code{//} 演算子は @ref{b3e,,整数除算} を行い、整数値を返します; 剰余は、@code{%} で求めます。:

@example
>>> 17 / 3  # 除算は浮動小数点数を返す
5.666666666666667
>>>
>>> 17 // 3  # 整数除算は小数部を破棄する
5
>>> 17 % 3  # % 演算子は剰余を返す
2
>>> 5 * 3 + 2  # 切り捨てられた商 * 除数 + 剰余
17
@end example

Python では、冪乗を計算するのに @code{**} 演算子が使えます @footnote{
@code{**} は @code{-} より優先順位が高いので、@code{-3**2} は @code{-(3**2)} と解釈され、計算結果は @code{-9} になります。これを避けて @code{9} を得たければ、@code{(-3)**2} と書きます。
}:

@example
>>> 5 ** 2  # 5の2乗
25
>>> 2 ** 7  # 2の7乗
128
@end example

等号 (@code{=}) は変数に値を代入するときに使います。代入を行っても、結果は出力されず、次の入力プロンプトが表示されます。:

@example
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
@end example

変数が "定義" されていない (つまり値が代入されていない) 場合、その変数を使おうとするとエラーが発生します:

@example
>>> n  # 未定義の変数にアクセスする
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
@end example

浮動小数点を完全にサポートしています。演算対象の値(オペランド)に複数の型が入り混じっている場合、演算子は整数のオペランドを浮動小数点型に変換します:

@example
>>> 4 * 3.75 - 1
14.0
@end example

対話モードでは、最後に表示された結果は変数 @code{_} に代入されます。このことを利用すると、Python を電卓として使うときに、計算を連続して行う作業が多少楽になります。以下に例を示します:

@example
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
@end example

この変数には読取りだけを行い、明示的な代入を行ってはいけません --- そんなことをすれば、同じ名前で別のローカル変数が生成され、元の特別な動作をする組み込み変数を覆い隠してしておかしなことになってしまうかもしれません。

@ref{19b,,int} と @ref{196,,float} に加え、 Python は @ref{1fe,,Decimal} や @ref{213,,Fraction} などの他の数値型もサポートしています。 @ref{1fdc,,複素数} も組み込み型としてサポートしており、 @code{j} もしくは @code{J} 接尾辞を使って虚部を示します (例:  @code{3+5j})。

@node テキスト,リスト型 list,数,Python を電卓として使う
@anchor{tutorial/introduction text}@anchor{1fdd}@anchor{tutorial/introduction tut-strings}@anchor{1fde}
@subsubsection テキスト


Python は数値だけでなくテキスト (いわゆる「文字列」である @ref{169,,str} 型によって表現されます) を扱うことができます。
@code{!} のような文字や @code{rabbit} のような単語、 @code{Paris} のような名前、  @code{Got your back.} ような文もすべて文字列です。
文字列はシングルクォート (@code{'...'}) またはダブルクォート (@code{"..."}) で囲み、どちらを使っても違いはありません @footnote{
他の言語と違って、@code{\n} のような特殊文字は、単引用符 (@code{'...'}) と二重引用符 (@code{"..."}) で同じ意味を持ちます。両者の唯一の違いは、単引用符で囲われた箇所では @code{"} をエスケープする必要がない (ただし @code{\'} はエスケープする必要がある) ことで、逆もまた同様です。
} 。

@example
>>> 'spam eggs'  # シングルクォート
'spam eggs'
>>> "Paris rabbit got your back :)! Yay!"  # ダブルクォート
'Paris rabbit got your back :)! Yay!'
>>> '1975'  # クォートに囲まれた数字も文字列
'1975'
@end example

クォートの中でクォートを使いたい場合、 @code{\} を前に付け加えることで「エスケープ」をする必要があります。
もしくは、文字列で使用したいクォートとは別の方のクォートで囲むこともできます。

@example
>>> 'doesn\'t'  #  \' を使用してシングルクォートをエスケープする
"doesn't"
>>> "doesn't"  # または代わりにダブルクォートを使用する
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
@end example

Python シェルでは、文字列を定義するときと文字列が出力されるときでは見え方が異なることがあります。
@ref{1177,,print()} 関数を使うと、両端のクォートがなくなり、エスケープされた文字や特殊文字が表示されるため、より読みやすい形で出力できます。

@example
>>> s = 'First line.\nSecond line.'  # \n は改行を意味する
>>> s  # print() を使用しない場合、特殊文字が文字列に含まれる
'First line.\nSecond line.'
>>> print(s)  # print() では特殊文字は解釈されるため、\n は改行となる
First line.
Second line.
@end example

@code{\} に続く文字を特殊文字として解釈されたくない場合は、最初の引用符の前に @code{r} を付けた `raw strings' が使えます:

@example
>>> print('C:\some\name')  # ここでは \n は改行を意味する!
C:\some
ame
>>> print(r'C:\some\name')  # 引用符の前 r に注目
C:\some\name
@end example

raw文字列には微妙な面があります: raw文字列は奇数個の`@w{`}`@w{`} 文字では終了できません。詳細と解決方法については @ref{1fdf,,the FAQ entry} を参照してください。

文字列リテラルは複数行にまたがって書けます。1 つの方法は三連引用符 (@code{"""..."""} や @code{'@w{'}'...'@w{'}'}) を使うことです。改行文字は自動的に文字列に含まれますが、行末に @code{\} を付けることで含めないようにすることもできます。次の例では最初の改行は含まれません:

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

>>>
@end example

文字列は @code{+} 演算子で連結させる (くっつけて一つにする) ことができ、@code{*} 演算子で反復させることができます:

@example
>>> # 'un' を3回繰り返し、その後に 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
@end example

連続して並んでいる複数の `文字列リテラル' (つまり、引用符に囲われた文字列) は、自動的に連結されます。

@example
>>> 'Py' 'thon'
'Python'
@end example

この機能は、長い文字列を改行したいときにとても役に立ちます:

@example
>>> text = ('複数の文字列を丸括弧で囲むと'
...         '連結される。')
>>> text
'複数の文字列を丸括弧で囲むと連結される。'
@end example

これは 2 つのリテラルどうしに対してのみ働き、変数や式には働きません:

@example
>>> prefix = 'Py'
>>> prefix 'thon'  # 変数と文字列リテラルは連結できない
  File "<stdin>", line 1
    prefix 'thon'
           ^^^^^^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
               ^^^^^
SyntaxError: invalid syntax
@end example

変数どうしや変数とリテラルを連結したい場合は、@code{+} を使ってください:

@example
>>> prefix + 'thon'
'Python'
@end example

文字列は `インデックス' (添字) を指定して文字を取得できます。最初の文字のインデックスは 0 になります。文字を表す、専用のデータ型は用意されていません; 文字とは、単に長さが 1 の文字列です:

@example
>>> word = 'Python'
>>> word[0]  # 0番目の文字
'P'
>>> word[5]  # 5番目の文字
'n'
@end example

インデックスには、負の値も指定できまます。この場合、右から数えていきます:

@example
>>> word[-1]  # 最後の文字
'n'
>>> word[-2]  # 後ろから2番目の文字
'o'
>>> word[-6]
'P'
@end example

-0 は 0 と区別できないので、負のインデックスは -1 から始まります。

インデクス表記に加え、 `スライス' もサポートされています。インデクス表記は個々の文字を取得するのに使いますが、 `スライス' を使うと部分文字列を取得することができます:

@example
>>> word[0:2]  # 0番目(含む)から2番目(含めない)までの文字
'Py'
>>> word[2:5]  #  2番目(含む)から5番目(含めない)までの文字
'tho'
@end example

スライスのインデックスには、便利なデフォルト値があります; 最初のインデックスを省略すると、0 と見なされます。二番め のインデックスを省略すると、スライスする文字列のサイズとみなされます。

@example
>>> word[:2]   # 最初から2番目(含めない)までの文字
'Py'
>>> word[4:]   # 4番目(含む)から最後までの文字
'on'
>>> word[-2:]  # 後ろから2番目(含む)から最後までの文字
'on'
@end example

開始値は常に含まれ、終了値は常に含まれないことに注意してください。なので @code{s[:i] + s[i:]} は常に @code{s}  と等しくなります:

@example
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
@end example

スライスの使い方をおぼえる良い方法は、インデックスが文字と文字の `あいだ (between)' を指しており、最初の文字の左端が 0 になっていると考えることです。そうすると、 `n' 文字からなる文字列中の最後の文字の右端はインデックス `n' となります。例えばこうです:

@example
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
@end example

1行目の数字は文字列の 0 から 6 までのインデックスの位置を示しています; 2行目は対応する負のインデックスを示しています。`i' から `j' までのスライスは、それぞれ `i' と付いた境界から `j' と付いた境界までの全ての文字から成っています。

正のインデックスの場合、スライスされたシーケンスの長さは、スライスの両端のインデックスが範囲内にあるかぎり、インデックス間の差になります。例えば、 @code{word[1:3]} の長さは 2 になります。

大き過ぎるインデックスを使おうとするとエラーが発生します:

@example
>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
@end example

しかし、スライスで範囲外のインデックスを使ったときは、上手く対応して扱ってくれます:

@example
>>> word[4:42]
'on'
>>> word[42:]
'@w{'}
@end example

Python の文字列は変更できません -- つまり @ref{15b9,,不変} です。従って、文字列のインデックスで指定したある場所に代入を行うとエラーが発生します:

@example
>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
@end example

元の文字列と別の文字列が必要な場合は、新しく文字列を作成してください:

@example
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
@end example

組込み関数 @ref{840,,len()} は文字列の長さ (length) を返します:

@example
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
@end example


@subsubheading 参考



@table @asis

@item @ref{1fe0,,テキストシーケンス型 --- str}

文字列は代表的な `シーケンス型' で、シーケンス型でサポートされている共通の操作をサポートしています。

@item @ref{1fe1,,文字列メソッド}

文字列は、基本的な変換や検索を行うための数多くのメソッドをサポートしています。

@item @ref{19a,,f-strings}

式の埋め込みをサポートした文字列リテラル

@item @ref{15b3,,書式指定文字列の文法}

@ref{833,,str.format()} を使った文字列のフォーマットについての情報があります。

@item @ref{8db,,printf 形式の文字列書式化}

文字列が @code{%} 演算子の左オペランドである場合に呼び出される古いフォーマット操作について、詳しく記述されています。
@end table


@node リスト型 list,,テキスト,Python を電卓として使う
@anchor{tutorial/introduction lists}@anchor{1fe2}@anchor{tutorial/introduction tut-lists}@anchor{1fe3}
@subsubsection リスト型 (list)


Pythonは多くの `複合 (compound)' データ型を備えており、複数の値をまとめるのに使われます。最も汎用性が高いのは `リスト (list)' で、コンマ区切りの値 (要素) の並びを角括弧で囲んだものとして書き表されます。リストは異なる型の要素を含むこともありますが、通常は同じ型の要素のみを持ちます。

@example
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
@end example

文字列 (や他の全ての組み込みの @ref{716,,シーケンス} 型) のように、リストはインデックスやスライスができます:

@example
>>> squares[0]  # インデックス指定は要素を返す
1
>>> squares[-1]
25
>>> squares[-3:]  # スライスは新しいリストを返す
[9, 16, 25]
@end example

リストは、リストの連結などもサポートしています:

@example
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
@end example

@ref{15b9,,不変} な文字列とは違って、リストは @ref{15ba,,可変} 型ですので、要素を入れ替えられます:

@example
>>> cubes = [1, 8, 27, 65, 125]  # 何かがおかしい
>>> 4 ** 3  # 4の3乗は65ではなく64!
64
>>> cubes[3] = 64  # 誤った値を置き換える
>>> cubes
[1, 8, 27, 64, 125]
@end example

@ref{8dc,,list.append()} `メソッド' を使って、リストの末尾に新しい要素を追加できます (メソッドについては後で詳しく見ていきます):

@example
>>> cubes.append(216)  # 6の3乗を追加
>>> cubes.append(7 ** 3)  # 7の3乗を追加
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
@end example

単純な代入ではPythonは決してデータをコピーしません。リストを変数に代入すると、その変数は `既存のリスト' を参照します。ある変数を通してリストに任意の変更を行うと、そのリストを参照したすべての他の変数を通して確認できます。:

@example
>>> rgb = ["Red", "Green", "Blue"]
>>> rgba = rgb
>>> id(rgb) == id(rgba)  # 同じオブジェクトを参照している
True
>>> rgba.append("Alph")
>>> rgb
["Red", "Green", "Blue", "Alph"]
@end example

全てのスライス操作は、指定された要素を含む新しいリストを返します。例えば、次のスライスは、リストの @ref{1fe4,,浅いコピー} を返します。:

@example
>>> correct_rgba = rgba[:]
>>> correct_rgba[-1] = "Alpha"
>>> correct_rgba
["Red", "Green", "Blue", "Alpha"]
>>> rgba
["Red", "Green", "Blue", "Alph"]
@end example

スライスには、代入もできます。スライスの代入で、リストのサイズを変更したり、全てを削除したりもできます:

@example
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # 一部の値を置き換える
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # 一部の値を削除する
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # 要素全体を空のリストに置き換えてリストをクリアする
>>> letters[:] = []
>>> letters
[]
@end example

組込み関数 @ref{840,,len()} はリストにも使えます:

@example
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
@end example

リストを入れ子 (ほかのリストを含むリストを造る) にできます。例えば:

@example
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
@end example

@node プログラミングへの第一歩,,Python を電卓として使う,形式ばらない Python の紹介
@anchor{tutorial/introduction first-steps-towards-programming}@anchor{1fe5}@anchor{tutorial/introduction tut-firststeps}@anchor{1fe6}
@subsection プログラミングへの第一歩


もちろん、2 たす 2 よりももっと複雑な課題にも Python を使えます。
例えば、Fibonacci series@footnote{https://en.wikipedia.org/wiki/Fibonacci_sequence} の先頭の部分列は次のように書けます:

@example
>>> # フィボナッチ数列:
>>> # 2つの要素の和で次の値を定義する
>>> a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8
@end example

上の例では、いくつか新しい機能を使用しています。


@itemize *

@item 
最初の行には `複数同時の代入 (multiple assignment)' が入っています: 変数 @code{a} と @code{b} は、それぞれ同時に新しい値 0 と 1 になっています。この代入は、最後の行でも使われています。代入文では、まず右辺の式がすべて評価され、次に代入が行われます。右辺の式は、左から右へと順番に評価されます。

@item 
@ref{1973,,while} は、条件 (ここでは `@w{`} a < 10`@w{`}) が真である限り実行を繰り返し (ループし) ます。Python では、C 言語と同様に、ゼロでない整数値は真となり、ゼロは偽です。条件式には、文字列値やリスト値なども使えます。それ以外のシーケンスも、条件式として使用できます。長さが 1 以上のシーケンスは真で、空のシーケンスは偽になります。サンプルで使われている条件テストはシンプルな比較です。標準的な比較演算子は C 言語と同様です: すなわち、 @code{<} (より小さい)、 @code{>} (より大きい)、 @code{==} (等しい)、 @code{<=} (より小さいか等しい)、 @code{>=} (より大きいか等しい)、および @code{!=} (等しくない)、です。

@item 
ループの `本体 (body)' は、 `インデント (indent, 字下げ)'  されています: インデントは Python において、実行文をグループにまとめる方法です。対話的プロンプトでは、インデントされた各行を入力するにはタブや (複数個の) スペースを使わなければなりません。実用的には、もっと複雑な処理を入力する場合はテキストエディタを使うことになるでしょう。 ほとんどのテキストエディタは、自動インデント機能を持っています。複合文を対話的に入力するときには、入力完了のしるしとして最後に空行を入力します。これは、パーザはどれが最後の行を入力なのか、判断できないためです。基本的なブロック内では、全ての行は同じだけインデントされていなければならないので注意してください。

@item 
@ref{1177,,print()} 関数は、与えられた引数の値を書き出します。これは (前に電卓の例でやったような) 単に出力したい式を書くのとは、複数の引数や浮動小数点量や文字列に対する扱い方が違います。@ref{1177,,print()} 関数では、文字列は引用符無しで出力され、要素の間に空白が挿入されて、このように出力の書式が整えられます:

@example
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
@end example

キーワード引数 `end' を使うと、出力の末尾に改行文字を出力しないようにしたり、別の文字列を末尾に出力したりできます:

@example
>>> a, b = 0, 1
>>> while a < 1000:
...     print(a, end=',')
...     a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
@end example
@end itemize

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node その他の制御フローツール,データ構造,形式ばらない Python の紹介,Python チュートリアル
@anchor{tutorial/controlflow doc}@anchor{1fe7}@anchor{tutorial/controlflow more-control-flow-tools}@anchor{1fe8}@anchor{tutorial/controlflow translation-repo}@anchor{1fe9}@anchor{tutorial/controlflow tut-morecontrol}@anchor{1fea}
@section その他の制御フローツール


前章で紹介した @ref{1973,,while} 文の他にも、 Python にはいくつか制御フローツールがあり、本章で説明します。

@menu
* if 文:: 
* for 文:: 
* range() 関数: range 関数. 
* break 文と continue 文:: 
* ループの else 節:: 
* pass 文:: 
* match 文:: 
* 関数を定義する:: 
* 関数定義についてもう少し:: 
* 間奏曲; コーディングスタイル: 間奏曲 コーディングスタイル. 

@end menu

@node if 文,for 文,,その他の制御フローツール
@anchor{tutorial/controlflow if-statements}@anchor{1feb}@anchor{tutorial/controlflow tut-if}@anchor{1fec}
@subsection @code{if} 文


おそらく最もおなじみの文型は @ref{181,,if} 文でしょう。例えば:

@example
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
@end example

ゼロ個以上の @ref{17b,,elif} 部を使うことができ、 @ref{17c,,else} 部を付けることもできます。キーワード '@code{elif}' は 'else if' を短くしたもので、過剰なインデントを避けるのに役立ちます。一連の @code{if} ... @code{elif} ... @code{elif} ...  は、他の言語における @code{switch} 文や @code{case} 文の代用となります。

いくつかの定数と同じ値かを比較する場合や、特定の型や属性かを確認する場合には、@code{match} 文が便利です。詳細は @ref{1fed,,match 文} を参照してください。

@node for 文,range 関数,if 文,その他の制御フローツール
@anchor{tutorial/controlflow for-statements}@anchor{1fee}@anchor{tutorial/controlflow tut-for}@anchor{1fef}
@subsection @code{for} 文


@geindex statement;for

Python の @ref{34a,,for} 文は、読者が C 言語や Pascal 言語で使いなれているかもしれない @ref{34a,,for} 文とは少し違います。 (Pascal のように) 常に算術型の数列にわたる反復を行ったり、 (C のように) 繰返しステップと停止条件を両方ともユーザが定義できるようにするのとは違い、Python の @code{for} 文は、任意のシーケンス型 (リストまたは文字列) にわたって反復を行います。反復の順番はシーケンス中に要素が現れる順番です。例えば:

@c One suggestion was to give a real C example here, but that may only serve to
@c confuse non-C programmers.

@example
>>> # 文字列の長さを計測:
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
@end example

コレクションオブジェクトの値を反復処理をしているときに、そのコレクションオブジェクトを変更するコードは理解するのが面倒になり得ます。
そうするよりも、コレクションオブジェクトのコピーに対して反復処理をするか、新しいコレクションオブジェクトを作成する方が通常は理解しやすいです:

@example
# コレクション作成
users = @{'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'@}

# 方針:  コピーを反復
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# 方針:  新コレクション作成
active_users = @{@}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
@end example

@node range 関数,break 文と continue 文,for 文,その他の制御フローツール
@anchor{tutorial/controlflow the-range-function}@anchor{1ff0}@anchor{tutorial/controlflow tut-range}@anchor{1ff1}
@subsection @code{range()} 関数


数列にわたって反復を行う必要がある場合、組み込み関数 @ref{b3d,,range()}  が便利です。この関数は算術型の数列を生成します:

@example
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
@end example

指定した終端値は生成されるシーケンスには入りません。@code{range(10)} は 10 個の値を生成し、長さ 10 のシーケンスにおける各項目のインデクスとなります。range を別の数から開始したり、他の増加量 (負でも; 増加量は時に 'ステップ(step)' と呼ばれることもあります) を指定することもできます:

@example
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
@end example

あるシーケンスにわたってインデクスで反復を行うには、 @ref{b3d,,range()} と @ref{840,,len()} を次のように組み合わせられます:

@example
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
@end example

しかし、多くの場合は @ref{169a,,enumerate()} 関数を使う方が便利です。 @ref{1ff2,,ループのテクニック} を参照してください。

range を直接出力すると変なことになります:

@example
>>> range(10)
range(0, 10)
@end example

@ref{b3d,,range()} が返すオブジェクトは、いろいろな点でリストであるかのように振る舞いますが、本当はリストではありません。これは、イテレートした時に望んだ数列の連続した要素を返すオブジェクトです。しかし実際にリストを作るわけではないので、スペースの節約になります。

このようなオブジェクトは @ref{12f1,,イテラブル} と呼ばれます。
これらは関数や構成物のターゲットとして、あるだけの項目を逐次与えるのに適しています。
@ref{34a,,for} 文がそのような構成物であることはすでに見てきており、イテラブルを受け取る関数の例には @ref{695,,sum()} があります:

@example
>>> sum(range(4))  # 0 + 1 + 2 + 3
6
@end example

Later we will see more functions that return iterables and take iterables as
arguments.  In chapter @ref{1ff3,,データ構造}, we will discuss @ref{24d,,list()} in more
detail.

@node break 文と continue 文,ループの else 節,range 関数,その他の制御フローツール
@anchor{tutorial/controlflow break-and-continue-statements}@anchor{1ff4}@anchor{tutorial/controlflow tut-break}@anchor{1ff5}
@subsection @code{break} 文と @code{continue} 文


@ref{17f,,break} 文は、その @cite{break} 文を内包している最も内側にある @ref{34a,,for} 文または @ref{1973,,while} 文から抜け出すことができます:

@example
>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(f"@{n@} は @{x@} * @{n//x@} と等しい")
...             break
...
4 は 2 * 2 と等しい
6 は 2 * 3 と等しい
8 は 2 * 4 と等しい
9 は 3 * 3 と等しい
@end example

@ref{180,,continue} 文はループの次のイテレーションを実行します:

@example
>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print(f"偶数 @{num@} を見つけた")
...         continue
...     print(f"奇数 @{num@} を見つけた")
...
偶数 2 を見つけた
奇数 3 を見つけた
偶数 4 を見つけた
奇数 5 を見つけた
偶数 6 を見つけた
奇数 7 を見つけた
偶数 8 を見つけた
奇数 9 を見つけた
@end example
@anchor{tutorial/controlflow tut-for-else}@anchor{1ff6}
@node ループの else 節,pass 文,break 文と continue 文,その他の制御フローツール
@anchor{tutorial/controlflow break-and-continue-statements-and-else-clauses-on-loops}@anchor{1ff7}@anchor{tutorial/controlflow else-clauses-on-loops}@anchor{1ff8}
@subsection ループの @code{else} 節


@code{for} または @code{while} ループ中の @code{break} 文は @code{else} 節と対になる場合があります。@code{break} を実行せずにループが終了すると、@code{else} 節が実行されます。

@ref{34a,,for} 文の場合、 @code{else} 節はループ処理の最後のイテレーションが実行されたあと、つまりbreakが発生しなかった場合に実行されます。

@ref{1973,,while} 文の場合は、ループ条件が偽となったあとに実行されます。

どちらのループでも、ループが @ref{17f,,break} によって終了した場合は @code{else} 句は `実行されません'。当然、 @ref{1af,,return} や例外の発生によってループが途中で終了した場合にも、@ref{17c,,else} 節の実行はスキップされます。

その例として、素数を探索する @code{for} 文を以下に示します:

@example
>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'は', x, '*', n//x, 'と等しい')
...             break
...     else:
...         # 因数が見つからないとループは最後まで実行される
...         print(n, 'は素数です')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
@end example

(そう、これは正しいコードです。よく見てください: @code{else} 節は @code{if} 文 `ではなく' 、 @code{for} ループに属しています。)

One way to think of the else clause is to imagine it paired with the @code{if}
inside the loop.  As the loop executes, it will run a sequence like
if/if/if/else. The @code{if} is inside the loop, encountered a number of times. If
the condition is ever true, a @code{break} will happen. If the condition is never
true, the @code{else} clause outside the loop will execute.

ループの @code{else} 句は、 @code{if} 文の @code{else} よりも @ref{8f8,,try} 文の @code{else} に似ています。  文の @code{else} 句は例外が発生しなかった時に実行され、ループの @code{else} 句は @code{break} されなかった場合に実行されます。 @code{try} 文と例外についての詳細は @ref{1ff9,,例外を処理する} を参照してください。

@geindex ...;ellipsisリテラル

@node pass 文,match 文,ループの else 節,その他の制御フローツール
@anchor{tutorial/controlflow pass-statements}@anchor{1ffa}@anchor{tutorial/controlflow tut-pass}@anchor{1ffb}
@subsection @code{pass} 文


@ref{17e,,pass} 文は何もしません。 @ref{17e,,pass} は、文を書くことが構文上要求されているが、プログラム上何の動作もする必要がない時に使われます:

@example
>>> while True:
...     pass  # キーボード割り込み(Ctrl+C)のためのビジーウェイト
...
@end example

これは最小のクラスを作るときによく使われる方法です:

@example
>>> class MyEmptyClass:
...     pass
...
@end example

@ref{17e,,pass} のもう 1 つの使い道は、新しいコードを書いているときの関数や条件文の仮置きの本体としてです。こうすることで、より抽象的なレベルで考え続けられます。
@code{pass} は何事も無く無視されます

@example
>>> def initlog(*args):
...     pass   # ここを忘れずに実装すること!
...
@end example

この最後の例で、多くの人は @code{pass} ではなく省略記号リテラル @code{...} を使います。 この使い方は Python に対して特別な意味はなく、言語定義の一部でもありません（ここにはどんな定数式でも使えます）が、 @code{...} は慣例的にプレースホルダ本体としても使われています。 @ref{1ffc,,Ellipsis オブジェクト} を参照してください。

@node match 文,関数を定義する,pass 文,その他の制御フローツール
@anchor{tutorial/controlflow match-statements}@anchor{1ffd}@anchor{tutorial/controlflow tut-match}@anchor{1fed}
@subsection @code{match} 文


@ref{a0e,,match} 文は1つの式を指定し、その値と次に続く1つ以上のcaseブロックに指定されたパターンを比較します。この機能はCやJava、JavaScript(や他の多数の言語)のswitch文と表面的には似ていますが、RustやHaskellのパターンマッチングにより似ています。最初にマッチしたパターンのみが実行され、コンポーネント(シーケンスの要素やオブジェクトの属性)から値を取り出して変数に代入することもできます。どのcaseにもマッチしない場合はどの分岐も実行されません。

最も単純な形式は、対象の値に対して1つ以上のリテラルです:

@example
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"
@end example

最後のブロックについて: 変数名 @code{_} は `ワイルドカード' の働きをし、マッチに絶対失敗しません。

複数のリテラルを @code{|} ("or")を使用して組み合わせて1つのパターンにできます:

@example
case 401 | 403 | 404:
    return "Not allowed"
@end example

パターンはアンパック代入ができ、変数に結びつけられます:

@example
# point(座標) は (x, y) のタプル
match point:
    case (0, 0):
        print("原点")
    case (0, y):
        print(f"Y=@{y@}")
    case (x, 0):
        print(f"X=@{x@}")
    case (x, y):
        print(f"X=@{x@}, Y=@{y@}")
    case _:
        raise ValueError("座標ではない")
@end example

このコードは注意して見てください！
最初のパターンには2つのリテラルがあり、上で示したリテラルパターンの拡張と考えることができます。
しかし次の2つのパターンはリテラルと変数の組み合わせのため、対象(@code{point})から値を取り出して変数に `結びつけ' ます。
4番目のパターンは2つの値を取り込みます。
これは、アンパック代入 @code{(x, y) = point} と概念的に似ています。

データを構造化するためにクラスを使っている場合は、クラス名の後ろにコンストラクターのように引数のリストを指定できます。属性の値は変数に取り込まれます。

@example
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("原点")
        case Point(x=0, y=y):
            print(f"Y=@{y@}")
        case Point(x=x, y=0):
            print(f"X=@{x@}")
        case Point():
            print("それ以外のどこか")
        case _:
            print("座標ではない")
@end example

いくつかの組み込みクラスでは位置引数が使用でき、属性の順番を提供します(例: データクラス)。クラスの @code{__match_args__} 特殊属性によって、パターンの中で属性の明確な位置を定義することもできます。("x", "y")が設定された場合、以下のすべてのパターンは等価です(すべて属性 @code{y} が @code{var} 変数に結びつけられます):

@example
Point(1, var)
Point(1, y=var)
Point(x=1, y=var)
Point(y=var, x=1)
@end example

おすすめのパターンの読み方は、パターンが、代入文の左辺に配置するものを拡張した形式であるとみなすことです。
これにより、どの変数になにが代入されるかが分かります。
単独の名前（上記の @code{var} など）だけがマッチ文で値が代入されます。ドット付きの名前（@code{foo.bar} など）、属性名（上記の @code{x=}、@code{y=} など ）、クラス名（名前の後ろの "(...)"  によって判別される。上記の @code{Point} など）には値は代入されません。

パターンはいくらでも入れ子 (ネスト) にすることができます。例えば、 @code{__match_args__} を追加した Point クラスのリストに対して次のようにマッチを行うことができます:

@example
class Point:
    __match_args__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

match points:
    case []:
        print("座標が存在しない")
    case [Point(0, 0)]:
        print("原点")
    case [Point(x, y)]:
        print(f"1つの座標 @{x@}, @{y@}")
    case [Point(0, y1), Point(0, y2)]:
        print(f"Y軸の @{y1@}, @{y2@} に2つの座標")
    case _:
        print("それ以外のどこか")
@end example

パターンに @code{if} 節を追加できます。これは "ガード" と呼ばれます。ガードがfalseの場合、@code{match} は次のcaseブロックの処理に移動します。ガードを評価する前に値が取り込まれることに注意してください:

@example
match point:
    case Point(x, y) if x == y:
        print(f"Y=X at @{x@}")
    case Point(x, y):
        print(f"対角線上ではない")
@end example

この文のその他のいくつか重要な特徴:


@itemize -

@item 
アンパック代入のように、タプルとリストのパターンでは正確に同じ意味で、任意のシーケンスと一致します。重要な例外として、イテレーターや文字列ではマッチしません。

@item 
シーケンスパターンは拡張アンパックをサポート: @code{[x, y, *rest]} と @code{(x, y, *rest)} はアンパック代入として同じように動作します。@code{*} のあとの変数名は @code{_} でもよく、そのため @code{(x, y, *_)} は最低でも2つのアイテムを持つシーケンスにマッチし、残りのアイテムは変数に結びつけられません。

@item 
マッピングパターン: @code{@{"bandwidth": b, "latency": l@}} は辞書から @code{"bandwidth"} と @code{"latency"} の値を取り込みます。シーケンスパターンとは異なり、それ以外のキーは無視されます。アンパッキングのような @code{**rest} もサポートされています（しかし、 @code{**_} は冗長なため禁止されています）。

@item 
サブパターンでは @code{as} キーワードを使用して値を取り込みます:

@example
case (Point(x1, y1), Point(x2, y2) as p2): ...
@end example

この例では入力から2番目の要素を @code{p2} として取り込みます（入力が2つのポイントのシーケンスである場合）

@item 
ほとんどのリテラルは同一性を比較しますが、シングルトンの @code{True}、@code{False}、@code{None} では識別値を比較します。

@item 
Patterns may use named constants.  These must be dotted names
to prevent them from being interpreted as capture variables:

@example
from enum import Enum
class Color(Enum):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'

color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))

match color:
    case Color.RED:
        print("I see red!")
    case Color.GREEN:
        print("Grass is green")
    case Color.BLUE:
        print("I'm feeling the blues :(")
@end example
@end itemize

より詳細な説明と追加の例は 
@geindex Python Enhancement Proposals; PEP 636
PEP 636@footnote{https://peps.python.org/pep-0636/} にチュートリアル形式で記述してあります。

@node 関数を定義する,関数定義についてもう少し,match 文,その他の制御フローツール
@anchor{tutorial/controlflow defining-functions}@anchor{1ffe}@anchor{tutorial/controlflow tut-functions}@anchor{1fff}
@subsection 関数を定義する


フィボナッチ数列 (Fibonacci series) を任意の上限値まで書き出すような関数を作成できます:

@example
>>> def fib(n):    # nまでのフィボナッチ数を出力する
...     """nまでのフィボナッチ数をprintする。"""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # 定義した関数を呼び出す:
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
@end example

@geindex documentation strings
@geindex docstrings
@geindex strings@comma{} documentation

@ref{1673,,def} は関数の `定義 (definition)' を導くキーワードです。 @ref{1673,,def} の後には、関数名と仮引数を丸括弧で囲んだリストを続けなければなりません。関数の実体を構成する実行文は次の行から始め、インデントされていなければなりません。

関数の本体の記述する文の最初の行は文字列リテラルにすることもできます。その場合、この文字列は関数のドキュメンテーション文字列 (documentation string)、または `docstring' と呼ばれます。 (docstring については @ref{2000,,ドキュメンテーション文字列} でさらに扱っています。) ドキュメンテーション文字列を使ったツールには、オンライン文書や印刷文書を自動的に生成したり、ユーザが対話的にコードから直接閲覧できるようにするものがあります。自分が書くコードにドキュメンテーション文字列を入れるのはよい習慣です。書く癖をつけてください。

関数を `実行 (execution)' するとき、関数のローカル変数のために使われる新たなシンボルテーブル (symbol table) が用意されます。
もっと正確にいうと、関数内で変数への代入を行うと、その値はすべてこのローカルなシンボルテーブルに記憶されます。
一方、変数の参照を行うと、まずローカルなシンボルテーブルが検索され、次にさらに外側の関数のローカルなシンボルテーブルを検索し、その後グローバルなシンボルテーブルを調べ、最後に組み込みの名前テーブルを調べます。
従って、関数の中では (グローバル変数が @ref{4ac,,global} 文で指定されていたり、外側の関数の変数が @ref{14bf,,nonlocal} 文で指定されていない限り) グローバル変数や外側の関数の変数に直接値を代入できませんが、参照することはできます。

関数を呼び出す際の実際の引数 (実引数) は、関数が呼び出されるときに関数のローカルなシンボルテーブル内に取り込まれます。そうすることで、実引数は `値渡し (call by value)' で関数に渡されることになります (ここでの `値 (value)' とは常にオブジェクトへの `参照(reference)' をいい、オブジェクトの値そのものではありません) @footnote{
実のところ、`オブジェクトへの参照渡し (call by object reference)' という言ったほうがより正確です。というのは、変更可能なオブジェクトが渡されると、呼び出された側の関数がオブジェクトに行った変更 (例えばリストに挿入された要素) はすべて、関数の呼び出し側にも反映されるからです。
}。ある関数がほかの関数を呼び出すときや、自身を再帰的に呼び出すときには、新たな呼び出しのためにローカルなシンボルテーブルが新たに作成されます。

関数の定義を行うと、関数名は関数オブジェクトとともに現在のシンボルテーブル内に取り入れられます。インタープリタはその名前が指すオブジェクトをユーザ定義関数 (user-defined function) として認識します。他の名前も同じ関数オブジェクトを指すことができ、またその関数にアクセスするために使用することができます:

@example
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
@end example

他の言語出身の人からは、 @code{fib} は値を返さないので関数ではなく手続き (procedure) だと異論があるかもしれませんね。技術的に言えば、実際には @ref{1af,,return} 文を持たない関数もややつまらない値ですが値を返しています。この値は @code{None} と呼ばれます (これは組み込みの名前です)。 @code{None} だけを書き出そうとすると、インタプリタは通常出力を抑制します。本当に出力したいのなら、以下のように @ref{1177,,print()} を使うと見ることができます:

@example
>>> fib(0)
>>> print(fib(0))
None
@end example

フィボナッチ数列の数からなるリストを出力する代わりに、値を返すような関数を書くのは簡単です:

@example
>>> def fib2(n):  # nまでのフィボナッチ数を返す
...     """nまでのフィボナッチ数を含むリストを返す。"""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # 以下参照
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # 関数を呼び出す
>>> f100                # 結果を出力する
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
@end example

この例は Python の新しい機能を示しています:


@itemize *

@item 
@ref{1af,,return} 文では、関数から一つ値を返します。 @code{return} の引数となる式がない場合、 @code{None} が返ります。関数が終了したときにも @code{None} が返ります。

@item 
文 @code{result.append(a)} では、リストオブジェクト @code{result} の `メソッド (method)' を呼び出しています。メソッドとは、オブジェクトに '属している' 関数のことで、 @code{obj} を何らかのオブジェクト (式であっても構いません)、 @code{methodname} をそのオブジェクトで定義されているメソッド名とすると、 @code{obj.methodname} と書き表されます。異なる型は異なるメソッドを定義しています。異なる型のメソッドで同じ名前のメソッドを持つことができ、あいまいさを生じることはありません。 (`クラス (class)' を使うことで、自前のオブジェクト型とメソッドを定義することもできます。 @ref{2001,,クラス} 参照) 例で示されているメソッド @code{append()} は、リストオブジェクトで定義されています; このメソッドはリストの末尾に新たな要素を追加します。この例での @ref{8dc,,append()} は @code{result = result + [a]} と等価ですが、より効率的です。
@end itemize

@node 関数定義についてもう少し,間奏曲 コーディングスタイル,関数を定義する,その他の制御フローツール
@anchor{tutorial/controlflow more-on-defining-functions}@anchor{2002}@anchor{tutorial/controlflow tut-defining}@anchor{2003}
@subsection 関数定義についてもう少し


可変個の引数を伴う関数を定義することもできます。引数の定義方法には 3 つの形式があり、それらを組み合わせることができます。

@menu
* デフォルトの引数値:: 
* キーワード引数:: 
* 特殊なパラメータ:: 
* 任意引数リスト:: 
* 引数リストのアンパック:: 
* ラムダ式:: 
* ドキュメンテーション文字列:: 
* 関数のアノテーション:: 

@end menu

@node デフォルトの引数値,キーワード引数,,関数定義についてもう少し
@anchor{tutorial/controlflow default-argument-values}@anchor{2004}@anchor{tutorial/controlflow tut-defaultargs}@anchor{2005}
@subsubsection デフォルトの引数値


もっとも便利なのは、一つ以上の引数に対してデフォルトの値を指定する形式です。この形式を使うと、定義されている引数より少ない個数の引数で呼び出せる関数を作成します:

@example
def ask_ok(prompt, retries=4, reminder='再試行してください!'):
    while True:
        reply = input(prompt)
        if reply in @{'y', 'ye', 'yes'@}:
            return True
        if reply in @{'n', 'no', 'nop', 'nope'@}:
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('無効なユーザーの入力')
        print(reminder)
@end example

この関数はいくつかの方法で呼び出せます:


@itemize *

@item 
必須の引数のみ与える: @code{ask_ok('Do you really want to quit?')}

@item 
一つのオプション引数を与える: @code{ask_ok('OK to overwrite the file?', 2)}

@item 
全ての引数を与える: @code{ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')}
@end itemize

この例では @ref{34b,,in} キーワードが導入されています。このキーワードはシーケンスが特定の値を含んでいるかどうか調べるのに使われます。

デフォルト値は、関数が定義された時点で、関数を `定義している' 側のスコープ (scope) で評価されるので

@example
i = 5

def f(arg=i):
    print(arg)

i = 6
f()
@end example

は @code{5} を出力します。

`重要な警告:'  デフォルト値は 1 度だけしか評価されません。デフォルト値がリストや辞書のような変更可能なオブジェクトの時にはその影響がでます。例えば以下の関数は、後に続く関数呼び出しで関数に渡されている引数を累積します:

@example
def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))
@end example

このコードは、以下を出力します

@example
[1]
[1, 2]
[1, 2, 3]
@end example

後続の関数呼び出しでデフォルト値を共有したくなければ、代わりに以下のように関数を書くことができます:

@example
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
@end example

@node キーワード引数,特殊なパラメータ,デフォルトの引数値,関数定義についてもう少し
@anchor{tutorial/controlflow keyword-arguments}@anchor{2006}@anchor{tutorial/controlflow tut-keywordargs}@anchor{2007}
@subsubsection キーワード引数


関数を @code{kwarg=value} という形式の @ref{f0e,,キーワード引数} を使って呼び出すこともできます。例えば、以下の関数:

@example
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")
@end example

は、必須引数 (@code{voltage}) とオプション引数 (@code{state}、@code{action}、@code{type}) を受け付けます。この関数は以下のいずれかの方法で呼び出せます:

@example
parrot(1000)                                          # 1つの位置引数
parrot(voltage=1000)                                  # 1つのキーワード引数
parrot(voltage=1000000, action='VOOOOOM')             # 2つのキーワード引数
parrot(action='VOOOOOM', voltage=1000000)             # 2つのキーワード引数
parrot('a million', 'bereft of life', 'jump')         # 3つの位置引数
parrot('a thousand', state='pushing up the daisies')  # 1との位置引数と1つのキーワード引数
@end example

が、以下の呼び出しは不適切です:

@example
parrot()                     # 必須の引数がない
parrot(voltage=5.0, 'dead')  # キーワード引数の後ろにキーワードのない引数
parrot(110, voltage=220)     # 同じ引数に対して2つの値を指定
parrot(actor='John Cleese')  # 未知のキーワード引数
@end example

関数の呼び出しにおいて、キーワード引数は位置引数の後でなければなりません。渡されるキーワード引数は全て、関数で受け付けられる引数のいずれかに対応していなければならず (例えば、@code{actor} はこの @code{parrot} 関数の引数として適切ではありません)、順序は重要ではありません。これはオプションでない引数でも同様です (例えば、@code{parrot(voltage=1000)} も適切です)。いかなる引数も値を複数回は受け取れません。この制限により失敗する例は:

@example
>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'
@end example

仮引数の最後に @code{**name} の形式のものがあると、それまでの仮引数に対応したものを除くすべてのキーワード引数が入った辞書 (@ref{cbd,,マッピング型 --- dict} を参照) を受け取ります。
@code{**name} は @code{*name} の形式をとる、仮引数のリストを超えた位置引数の入った @ref{2008,,タプル} を受け取る引数 (次の小節で述べます) と組み合わせられます。
(@code{*name} は @code{**name} より前になければなりません)。
例えば、ある関数の定義を以下のようにすると:

@example
def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])
@end example

呼び出しは以下のようになり:

@example
cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")
@end example

もちろん以下のように出力されます:

@example
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
@end example

なお、複数のキーワード引数を与えた場合に、それらが出力される順序は、関数呼び出しで与えられた順序と同じになります。

@node 特殊なパラメータ,任意引数リスト,キーワード引数,関数定義についてもう少し
@anchor{tutorial/controlflow special-parameters}@anchor{2009}
@subsubsection 特殊なパラメータ


デフォルトでは、引数は位置またはキーワードによる明示で Python 関数に渡されます。
可読性とパフォーマンスのために、その引数が位置、位置またはキーワード、キーワードのどれで渡されるかを開発者が判定するのに関数定義だけを見ればよいように、引数の渡され方を制限することには意味があります。

関数定義は次のようになります:

@example
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        位置またはキーワード    |
        |                                - キーワード専用
         -- 位置専用
@end example

ここで、@code{/} と @code{*} はオプションです。使用された場合、これらの記号は、引数が関数に渡される方法、すなわち、位置専用、位置またはキーワード、キーワード専用、といった引数の種類を示します。キーワード引数は、名前付き引数とも呼ばれます。

@menu
* 位置またはキーワード引数:: 
* 位置専用引数: 位置専用引数<2>. 
* キーワード専用引数:: 
* 関数の例:: 
* 要約:: 

@end menu

@node 位置またはキーワード引数,位置専用引数<2>,,特殊なパラメータ
@anchor{tutorial/controlflow positional-or-keyword-arguments}@anchor{200a}
@subsubsection 位置またはキーワード引数


関数定義に @code{/} も @code{*} もない場合は、引数は位置またはキーワードで関数に渡されます。

@node 位置専用引数<2>,キーワード専用引数,位置またはキーワード引数,特殊なパラメータ
@anchor{tutorial/controlflow positional-only-parameters}@anchor{200b}
@subsubsection 位置専用引数


これをもう少し詳しく見てみると、特定の引数を `位置専用' と印を付けられます。
`位置専用' の場合、引数の順序が重要であり、キーワードで引数を渡せません。
位置専用引数は @code{/} （スラッシュ）の前に配置されます。
@code{/} は、位置専用引数を残りの引数から論理的に分離するために使用されます。
関数定義に @code{/} がない場合、位置専用引数はありません。

@code{/} の後の引数は、 `位置またはキーワード' 、もしくは、 `キーワード専用' です。

@node キーワード専用引数,関数の例,位置専用引数<2>,特殊なパラメータ
@anchor{tutorial/controlflow keyword-only-arguments}@anchor{200c}
@subsubsection キーワード専用引数


引数をキーワード引数で渡す必要があることを示す `キーワード専用' として引数をマークするには、引数リストの最初の `キーワード専用' 引数の直前に  @code{*} を配置します。

@node 関数の例,要約,キーワード専用引数,特殊なパラメータ
@anchor{tutorial/controlflow function-examples}@anchor{200d}
@subsubsection 関数の例


@code{/} および @code{*} といったマーカーに注意を払って、次の関数定義の例を見てください:

@example
>>> def standard_arg(arg):
...     print(arg)
...
>>> def pos_only_arg(arg, /):
...     print(arg)
...
>>> def kwd_only_arg(*, arg):
...     print(arg)
...
>>> def combined_example(pos_only, /, standard, *, kwd_only):
...     print(pos_only, standard, kwd_only)
@end example

最も馴染みのある形式の最初の関数定義 @code{standard_arg}  は、呼び出し規約に制限を設けておらず、引数は位置またはキーワードで渡されます:

@example
>>> standard_arg(2)
2

>>> standard_arg(arg=2)
2
@end example

2番目の関数の @code{pos_only_arg} は、 @code{/} が関数定義にあるので、引数は位置専用になります:

@example
>>> pos_only_arg(1)
1

>>> pos_only_arg(arg=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'
@end example

3番目の関数 @code{kwd_only_arg} は、関数定義に @code{*} があるので、引数はキーワード専用になります:

@example
>>> kwd_only_arg(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given

>>> kwd_only_arg(arg=3)
3
@end example

そして最後の関数は3つの引数の種類を一つの関数定義の中で使用しています:

@example
>>> combined_example(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given

>>> combined_example(1, 2, kwd_only=3)
1 2 3

>>> combined_example(1, standard=2, kwd_only=3)
1 2 3

>>> combined_example(pos_only=1, standard=2, kwd_only=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'
@end example

最後に、位置引数 @code{name} と @code{name} をキーとして持つ @code{**kwds} の間に潜在的な衝突がある関数定義を考えてみましょう。

@example
def foo(name, **kwds):
    return 'name' in kwds
@end example

キーワードに @code{'name'} を入れても、先頭の引数と同じになってしまうため、この関数が @code{True} を返すような呼び出しの方法はありません。例えば、次のようになってしまいます:

@example
>>> foo(1, **@{'name': 2@})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'name'
>>>
@end example

しかし位置専用を示す @code{/} を使用すれば可能になります。 @code{name} は位置引数として、そして @code{'name'} はキーワード引数のキーワードとして認識されるからです:

@example
>>> def foo(name, /, **kwds):
...     return 'name' in kwds
...
>>> foo(1, **@{'name': 2@})
True
@end example

言い換えると、位置専用引数であれば、その名前を @code{**kwds} の中で使用しても、曖昧にならないということです。

@node 要約,,関数の例,特殊なパラメータ
@anchor{tutorial/controlflow recap}@anchor{200e}
@subsubsection 要約


使用例で、関数定義でどの種類の引数を使うかべきかがわかると思います:

@example
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
@end example

ガイドとしては、


@itemize *

@item 
もし引数の名前をユーザーに知らせる必要がないなら、位置専用引数を使用しましょう。これは引数の名前がユーザーにとって意味がなく、関数が呼ばれたときの引数の順序が問題であり、または、位置引数と任意のキーワードを使用する必要がある場合に便利です。

@item 
引数の名前に意味があり、それにより関数の定義がより明らかになる、または、ユーザーが引数の順番に縛られることを避けたほうがいいと考えるのなら、キーワード専用引数を使用しましょう。

@item 
APIの場合、将来引数の名前が変更された場合にAPIの変更ができなくなることを防ぐために、位置専用引数を使用しましょう。
@end itemize

@node 任意引数リスト,引数リストのアンパック,特殊なパラメータ,関数定義についてもう少し
@anchor{tutorial/controlflow arbitrary-argument-lists}@anchor{200f}@anchor{tutorial/controlflow tut-arbitraryargs}@anchor{2010}
@subsubsection 任意引数リスト


@geindex * (アスタリスク);関数呼び出しの中の

最後に、最も使うことの少ない選択肢として、関数が任意の個数の引数で呼び出せるよう指定する方法があります。これらの引数はタプル (@ref{2008,,タプルとシーケンス} を参照) に格納されます。可変個の引数の前に、ゼロ個かそれ以上の引数があっても構いません。

@example
def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))
@end example

通常このような `可変' 引数は、関数に渡される入力引数の残りを全て掬い取るために、仮引数リストの最後に置かれます。
@code{*args} 引数の後にある仮引数は 'キーワード専用' 引数で、位置引数ではなくキーワード引数としてのみ使えることを意味します。

@example
>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
@end example

@node 引数リストのアンパック,ラムダ式,任意引数リスト,関数定義についてもう少し
@anchor{tutorial/controlflow tut-unpacking-arguments}@anchor{2011}@anchor{tutorial/controlflow unpacking-argument-lists}@anchor{2012}
@subsubsection 引数リストのアンパック


引数がすでにリストやタプルになっていて、個別な位置引数を要求する関数呼び出しに渡すためにアンパックする必要がある場合には、逆の状況が起こります。例えば、組み込み関数 @ref{b3d,,range()} は引数 `start' と `stop' を別に与える必要があります。個別に引数を与えることができない場合、関数呼び出しを @code{*} 演算子を使って書き、リストやタプルから引数をアンパックします:

@example
>>> list(range(3, 6))            # 個別に引数を指定する通常の関数呼び出し
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # 引数リストをアンパックして関数呼び出し
[3, 4, 5]
@end example

@geindex **;関数呼び出しの中の

同じやりかたで、@code{**} オペレータを使って辞書でもキーワード引数を渡すことができます:

@example
>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = @{"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"@}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
@end example

@node ラムダ式,ドキュメンテーション文字列,引数リストのアンパック,関数定義についてもう少し
@anchor{tutorial/controlflow lambda-expressions}@anchor{2013}@anchor{tutorial/controlflow tut-lambda}@anchor{2014}
@subsubsection ラムダ式


キーワード @ref{14b5,,lambda} を使うと、名前のない小さな関数を生成できます。例えば @code{lambda a, b: a+b} は、二つの引数の和を返す関数です。ラムダ式の関数は、関数オブジェクトが要求されている場所にならどこでも使うことができます。ラムダ式は、構文上単一の式に制限されています。意味付け的には、ラムダ形式は単に通常の関数定義に構文的な糖衣をかぶせたものに過ぎません。入れ子構造になった関数定義と同様、ラムダ式もそれを取り囲むスコープから変数を参照することができます:

@example
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
@end example

上記の例ではラムダ式を使って関数を返しています。  別の使い方としては、小さな関数を引数として渡すこともできます。  たとえば、 @ref{dc8,,list.sort()} はソートキー関数 `key' を受け取りますが、これにはラムダ関数を渡せます:

@example
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
@end example

@node ドキュメンテーション文字列,関数のアノテーション,ラムダ式,関数定義についてもう少し
@anchor{tutorial/controlflow documentation-strings}@anchor{2015}@anchor{tutorial/controlflow tut-docstrings}@anchor{2000}
@subsubsection ドキュメンテーション文字列


@geindex docstrings
@geindex documentation strings
@geindex strings@comma{} documentation

ドキュメンテーション文字列については、その内容と書式に関する慣習をいくつか挙げます。

最初の行は、常に対象物の目的を短く簡潔にまとめたものでなくてはなりません。簡潔に書くために、対象物の名前や型を明示する必要はありません。名前や型は他の方法でも得られるからです (名前がたまたま関数の演算内容を記述する動詞である場合は例外です)。最初の行は大文字で始まり、ピリオドで終わっていなければなりません。

ドキュメンテーション文字列中にさらに記述すべき行がある場合、二行目は空行にし、まとめの行と残りの記述部分を視覚的に分離します。つづく行は一つまたはそれ以上の段落で、対象物の呼び出し規約や副作用について記述します。

The Python parser strips indentation from multi-line string literals when they
serve as module, class, or function docstrings.

以下に複数行のドキュメンテーション文字列の例を示します:

@example
>>> def my_function():
...     """なにもしないがドキュメントは書く。
...
...     本当になにもしない。
...
...         >>> my_function()
...         >>>
...     """
...     pass
...
>>> print(my_function.__doc__)
なにもしないがドキュメントは書く。

本当になにもしない。

    >>> my_function()
    >>>
@end example

@node 関数のアノテーション,,ドキュメンテーション文字列,関数定義についてもう少し
@anchor{tutorial/controlflow function-annotations}@anchor{2016}@anchor{tutorial/controlflow tut-annotations}@anchor{2017}
@subsubsection 関数のアノテーション


@geindex 関数;annotations
@geindex ->;関数のアノテーション
@geindex ; (コロン);関数のアノテーション

@ref{2018,,関数アノテーション} はユーザ定義関数で使用される型についての完全にオプションなメタデータ情報です (詳細は 
@geindex Python Enhancement Proposals; PEP 3107
PEP 3107@footnote{https://peps.python.org/pep-3107/} と 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} を参照してください)。

@ref{2019,,アノテーション} は関数の @ref{458,,__annotations__} 属性に辞書として格納され、関数の他の部分には何も影響を与えません。パラメータアノテーションは、パラメータ名の後にコロンを続けることによって定義され、その後にアノテーションの値として評価される式が置かれます。戻り値アノテーションは、パラメータリストと @ref{1673,,def} 文の終わりを表すコロンの間に置かれたリテラル @code{->} によって定義され、その後に式が続きます。次の例は必須の引数とオプション引数、そして戻り値のアノテーションを持っています:

@example
>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
アノテーション: @{'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>@}
引数: spam eggs
'spam and eggs'
@end example

@node 間奏曲 コーディングスタイル,,関数定義についてもう少し,その他の制御フローツール
@anchor{tutorial/controlflow intermezzo-coding-style}@anchor{201a}@anchor{tutorial/controlflow tut-codingstyle}@anchor{201b}
@subsection 間奏曲: コーディングスタイル


@geindex coding;style

Now that you are about to write longer, more complex pieces of Python, it is a
good time to talk about `coding style'.  Most languages can be written (or more
concisely, `formatted') in different styles; some are more readable than others.
Making it easy for others to read your code is always a good idea, and adopting
a nice coding style helps tremendously for that.

Python には、ほとんどのプロジェクトが守っているスタイルガイドとして 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} があります。それは非常に読み易く目に優しいコーディングスタイルを推奨しています。全ての Python 開発者はある時点でそれを読むべきです。ここに最も重要な点を抜き出しておきます:


@itemize *

@item 
インデントには空白 4 つを使い、タブは使わないこと。

空白 4 つは (深くネストできる) 小さいインデントと (読み易い) 大きいインデントのちょうど中間に当たります。タブは混乱させるので、使わずにおくのが良いです。

@item 
ソースコードの幅が 79 文字を越えないように行を折り返すこと。

こうすることで小さいディスプレイを使っているユーザも読み易くなり、大きなディスプレイではソースコードファイルを並べることもできるようになります。

@item 
関数やクラスや関数内の大きめのコードブロックの区切りに空行を使うこと。

@item 
可能なら、コメントは行に独立で書くこと。

@item 
docstring を使うこと。

@item 
演算子の前後とコンマの後には空白を入れ、括弧類のすぐ内側には空白を入れないこと: @code{a = f(1, 2) + g(3, 4)}。

@item 
クラスや関数に一貫性のある名前を付けること。慣習では @code{UpperCamelCase} をクラス名に使い、 @code{lowercase_with_underscores} を関数名やメソッド名に使います。常に @code{self} をメソッドの第 1 引数の名前 (クラスやメソッドについては @ref{201c,,クラス初見} を見よ) として使うこと。

@item 
あなたのコードを世界中で使ってもらうつもりなら、風変りなエンコーディングは使わないこと。どんな場合でも、Python のデフォルト UTF-8 またはプレーン ASCII が最も上手くいきます。

@item 
同様に、ほんの少しでも他の言語を話す人がコードを読んだりメンテナンスする可能性があるのであれば、非 ASCII 文字も識別子に使うべきではありません。
@end itemize

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node データ構造,モジュール<2>,その他の制御フローツール,Python チュートリアル
@anchor{tutorial/datastructures doc}@anchor{201d}@anchor{tutorial/datastructures data-structures}@anchor{201e}@anchor{tutorial/datastructures translation-repo}@anchor{201f}@anchor{tutorial/datastructures tut-structures}@anchor{1ff3}
@section データ構造


この章では、すでに学んだことについてより詳しく説明するとともに、いくつか新しいことを追加します。

@menu
* リスト型についてもう少し:: 
* del 文:: 
* タプルとシーケンス:: 
* 集合型:: 
* 辞書型 (dictionary): 辞書型 dictionary. 
* ループのテクニック:: 
* 条件についてもう少し:: 
* シーケンスとその他の型の比較:: 

@end menu

@node リスト型についてもう少し,del 文,,データ構造
@anchor{tutorial/datastructures more-on-lists}@anchor{2020}@anchor{tutorial/datastructures tut-morelists}@anchor{2021}
@subsection リスト型についてもう少し


@ref{2022,,list} 型には、他にもいくつかメソッドがあります。リストオブジェクトのすべてのメソッドを以下に示します:


@deffn {メソッド} list.append (x)

リストの末尾に要素を一つ追加します。@code{a[len(a):] = [x]} と同様です。
@end deffn


@deffn {メソッド} list.extend (iterable)

イテラブルのすべての要素を対象のリストに追加し、リストを拡張します。@code{a[len(a):] = iterable} と同様です。
@end deffn


@deffn {メソッド} list.insert (i, x)

指定した位置に要素を挿入します。第 1 引数は、リストのインデクスで、そのインデクスを持つ要素の直前に挿入が行われます。従って、 @code{a.insert(0, x)} はリストの先頭に挿入を行います。また @code{a.insert(len(a), x)} は @code{a.append(x)} と等価です。
@end deffn


@deffn {メソッド} list.remove (x)

リスト中で `x' と等しい値を持つ最初の要素を削除します。該当する要素がなければ @ref{2ec,,ValueError} が送出されます。
@end deffn


@deffn {メソッド} list.pop ([i])

指定された位置の要素をリストから取り除き、それを返します。インデックスが指定されていない場合、 @code{a.pop()} はリスト末尾の要素を取り除いて返します。リストが空であるか、インデックスがリストの範囲外の場合は、@ref{174e,,IndexError} を送出します。
@end deffn


@deffn {メソッド} list.clear ()

リスト中の全ての要素を削除します。@code{del a[:]} と同様です。
@end deffn


@deffn {メソッド} list.index (x[, start[, end]])

リスト中に最初に現れる `x' の位置をゼロから始まるインデックスで返します。 該当する要素がなければ @ref{2ec,,ValueError} が送出されます。

任意の引数である `start' と `end' はスライス記法として解釈され、リストの探索範囲を指定できます。返される添字は、`start' 引数からの相対位置ではなく、リスト全体の先頭からの位置になります。
@end deffn


@deffn {メソッド} list.count (x)

リストでの `x' の出現回数を返します。
@end deffn


@deffn {メソッド} list.sort (*, key=None, reverse=False)

リストの項目を、インプレース演算 (in place、元のデータを演算結果で置き換えるやりかた) でソートします。引数はソート方法のカスタマイズに使えます。 @ref{dc7,,sorted()} の説明を参照してください。
@end deffn


@deffn {メソッド} list.reverse ()

リストの要素を、インプレース演算で逆順にします。
@end deffn


@deffn {メソッド} list.copy ()

リストの浅い (shallow) コピーを返します。@code{a[:]} と同様です。
@end deffn

以下にリストのメソッドをほぼ全て使った例を示します:

@example
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # インデックス4から数えて次の banana の位置
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
@end example

@code{insert}, @code{remove}, @code{sort} などのリストを操作するメソッドの戻り値が表示されていないことに気が付いたかもしれません。これらのメソッドは @code{None} を返しています。@footnote{
他の言語では変更可能なオブジェクトを返して、@code{d->insert("a")->remove("b")->sort();} のようなメソッドチェインを許している場合もあります。
} これは Python の変更可能なデータ構造全てについての設計上の原則となっています。

もうひとつ気付くとしたら、すべてのデータでソートや比較できるわけではないということです。  例えば、 @code{[None, 'hello', 10]} はソートされません。なぜなら整数は文字列と比べられませんし、 @code{None} は他の型と比べられないからです。  また、順序関係が定義されていない型もあります。  例えば、 @code{3+4j < 5+7j} は有効な比較ではありません。

@menu
* リストをスタックとして使う:: 
* リストをキューとして使う:: 
* リストの内包表記: リストの内包表記<2>. 
* ネストしたリストの内包表記:: 

@end menu

@node リストをスタックとして使う,リストをキューとして使う,,リスト型についてもう少し
@anchor{tutorial/datastructures tut-lists-as-stacks}@anchor{2023}@anchor{tutorial/datastructures using-lists-as-stacks}@anchor{2024}
@subsubsection リストをスタックとして使う


リスト型のメソッドのおかげで、簡単にリストをスタックとして使えます。スタックでは、最後に追加された要素が最初に取り出されます ("last-in, first-out")。スタックの一番上に要素を追加するには @ref{8dc,,append()} を使います。スタックの一番上から要素を取り出すには @ref{2025,,pop()} をインデックスを指定せずに使います。例えば以下のようにします:

@example
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
@end example

@node リストをキューとして使う,リストの内包表記<2>,リストをスタックとして使う,リスト型についてもう少し
@anchor{tutorial/datastructures tut-lists-as-queues}@anchor{2026}@anchor{tutorial/datastructures using-lists-as-queues}@anchor{2027}
@subsubsection リストをキューとして使う


リストをキュー (queue) として使うことも可能です。この場合、最初に追加した要素を最初に取り出します ("first-in, first-out")。しかし、リストでは効率的にこの目的を達成することが出来ません。追加（append）や取り出し（pop）をリストの末尾に対して行うと速いのですが、挿入（insert）や取り出し（pop）をリストの先頭に対して行うと遅くなってしまいます（他の要素をひとつずつずらす必要があるからです）。

キューの実装には、 @ref{7f4,,collections.deque} を使うと良いでしょう。このクラスは良く設計されていて、高速な追加（append）と取り出し（pop）を両端に対して実現しています。例えば以下のようにします:

@example
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry が到着
>>> queue.append("Graham")          # Graham が到着
>>> queue.popleft()                 # 最初に到着した人が去って行った
'Eric'
>>> queue.popleft()                 # 2番目の人も去って行った
'John'
>>> queue                           # キューに残っているものは到着順
deque(['Michael', 'Terry', 'Graham'])
@end example

@node リストの内包表記<2>,ネストしたリストの内包表記,リストをキューとして使う,リスト型についてもう少し
@anchor{tutorial/datastructures list-comprehensions}@anchor{2028}@anchor{tutorial/datastructures tut-listcomps}@anchor{2029}
@subsubsection リストの内包表記


リスト内包表記はリストを生成する簡潔な手段を提供しています。主な利用場面は、あるシーケンスや iterable (イテレート可能オブジェクト) のそれぞれの要素に対してある操作を行った結果を要素にしたリストを作ったり、ある条件を満たす要素だけからなる部分シーケンスを作成することです。

例えば、次のような平方のリストを作りたいとします:

@example
>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
@end example

これはループが終了した後にも存在する @code{x} という名前の変数を作る (または上書きする) ことに注意してください。以下のようにして平方のリストをいかなる副作用もなく計算することができます:

@example
squares = list(map(lambda x: x**2, range(10)))
@end example

もしくは、以下でも同じです:

@example
squares = [x**2 for x in range(10)]
@end example

これはより簡潔で読みやすいです。

リスト内包表記は、括弧の中の 式、 @code{for} 句、そして0個以上の @code{for} か @code{if} 句で構成されます。
リスト内包表記の実行結果は、 @code{for} と @code{if} 句のコンテキスト中で式を評価した結果からなる新しいリストです。
例えば、次のリスト内包表記は2つのリストの要素から、違うもの同士をペアにします。

@example
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
@end example

これは次のコードと等価です:

@example
>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
@end example

@ref{34a,,for} と @ref{181,,if} 文が両方のコードで同じ順序になっていることに注目してください。

式がタプルの場合 (例: 上の例で式が @code{(x, y)} の場合) は、タプルに円括弧が必要です。

@example
>>> vec = [-4, -2, 0, 2, 4]
>>> # 値を2倍にした新しいリストを作成
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # フィルターでリストから負の数値を除外
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # 全ての要素に関数を適用
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # 各要素に対してメソッド呼び出し
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # (number, square) という2要素のタプルのリストを作成
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # タプルは丸括弧で囲まないといけない、そうでなければエラーが発生する
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1
    [x, x**2 for x in range(6)]
     ^^^^^^^
SyntaxError: did you forget parentheses around the comprehension target?
>>> # リスト内包表記で2つの 'for' を使って、リストをフラットにする
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
@end example

リスト内包表記の式には、複雑な式や関数呼び出しのネストができます:

@example
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
@end example

@node ネストしたリストの内包表記,,リストの内包表記<2>,リスト型についてもう少し
@anchor{tutorial/datastructures nested-list-comprehensions}@anchor{202a}
@subsubsection ネストしたリストの内包表記


リスト内包表記中の最初の式は任意の式なので、そこに他のリスト内包表記を書くこともできます。

次の、長さ4のリスト3つからなる、3x4 の matrix について考えます:

@example
>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
@end example

次のリスト内包表記は、matrix の行と列を入れ替えます:

@example
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
@end example

前の節で見たように、内側のリスト内包表記は、続く @ref{34a,,for} のコンテキストの中で評価されます。そのため、この例は次のコードと等価です:

@example
>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
@end example

これをもう一度変換すると、次のコードと等価になります:

@example
>>> transposed = []
>>> for i in range(4):
...     # 以下の3行はネストされたリスト内包表記と同じ実装
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
@end example

実際には複雑な流れの式よりも組み込み関数を使う方が良いです。この場合 @ref{1a0,,zip()} 関数が良い仕事をしてくれるでしょう:

@example
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
@end example

この行にあるアスタリスクの詳細については @ref{2011,,引数リストのアンパック} を参照してください。

@node del 文,タプルとシーケンス,リスト型についてもう少し,データ構造
@anchor{tutorial/datastructures the-del-statement}@anchor{202b}@anchor{tutorial/datastructures tut-del}@anchor{202c}
@subsection @code{del} 文


リストから要素を削除する際、値を指定する代わりにインデックスを指定する方法があります。それが @ref{1b1f,,del} 文です。これは @ref{2025,,pop()} メソッドと違い、値を返しません。 @code{del} 文はリストからスライスを除去したり、リスト全体を削除することもできます(以前はスライスに空のリストを代入して行っていました)。例えば以下のようにします:

@example
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
@end example

@ref{1b1f,,del} は変数全体の削除にも使えます:

@example
>>> del a
@end example

この文の後で名前 @code{a} を参照すると、(別の値を @code{a} に代入するまで) エラーになります。 @ref{1b1f,,del} の別の用途についてはまた後で取り上げます。

@node タプルとシーケンス,集合型,del 文,データ構造
@anchor{tutorial/datastructures tuples-and-sequences}@anchor{202d}@anchor{tutorial/datastructures tut-tuples}@anchor{2008}
@subsection タプルとシーケンス


リストや文字列には、インデクスやスライスを使った演算のように、数多くの共通の性質があることを見てきました。これらは `シーケンス (sequence)' データ型 (@ref{202e,,シーケンス型 --- list@comma{} tuple@comma{} range} を参照) の二つの例です。 Python はまだ進歩の過程にある言語なので、他のシーケンスデータ型が追加されるかもしれません。標準のシーケンス型はもう一つあります: `タプル (tuple)' 型です。

タプルはコンマで区切られたいくつかの値からなります。例えば以下のように書きます:

@example
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # タプルは入れ子にできる:
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # タプルは不変(イミュータブル):
>>> t[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # しかし、可変(ミュータブル)オブジェクトを含むことができる:
>>> v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
@end example

ご覧のとおり、タプルの表示には常に丸括弧がついていて、タプルのネストが正しく解釈されるようになっています。タプルを書くときは必ずしも丸括弧で囲まなくてもいいですが、(タプルが大きな式の一部だった場合は) 丸括弧が必要な場合もあります。タプルの要素を代入することはできません。しかし、タプルにリストのような変更可能型を含めることはできます。

タプルはリストと似ていますが、たいてい異なる場面と異なる目的で利用されます。タプルは @ref{15b9,,不変} で、複数の型の要素からなることもあり、要素はアンパック(この節の後半に出てきます)操作やインデックス (あるいは @ref{4e0,,namedtuples} の場合は属性)でアクセスすることが多いです。一方、リストは @ref{15ba,,可変} で、要素はたいてい同じ型のオブジェクトであり、たいていイテレートによってアクセスします。

問題は 0 個または 1 個の項目からなるタプルの構築です。これらの操作を行うため、構文には特別な細工がされています。空のタプルは空の丸括弧ペアで構築できます。一つの要素を持つタプルは、値の後ろにコンマを続ける (単一の値を丸括弧で囲むだけでは不十分です) ことで構築できます。美しくはないけれども、効果的です。例えば以下のようにします:

@example
>>> empty = ()
>>> singleton = 'hello',    # <-- 末尾のカンマに注意
0
>>> len(singleton)
1
>>> singleton
('hello',)
@end example

文 @code{t = 12345, 54321, 'hello!'} は `タプルのパック (tuple packing)' の例です。値 @code{12345}, @code{54321}, @code{'hello!'} が一つのタプルにパックされます。逆の演算も可能です:

@example
>>> x, y, z = t
@end example

この操作は、`シーケンスのアンパック (sequence unpacking)' とでも呼ぶべきもので、右辺には全てのシーケンス型を使うことができます。シーケンスのアンパックでは、等号の左辺に列挙されている変数が、右辺のシーケンスの長さと同じ数だけあることが要求されます。複数同時の代入が実はタプルのパックとシーケンスのアンパックを組み合わせたものに過ぎないことに注意してください。

@node 集合型,辞書型 dictionary,タプルとシーケンス,データ構造
@anchor{tutorial/datastructures sets}@anchor{202f}@anchor{tutorial/datastructures tut-sets}@anchor{2030}
@subsection 集合型


Python には、 @ref{2031,,sets} を扱うためのデータ型もあります。集合とは、重複する要素をもたない、順序づけられていない要素の集まりです。 Set オブジェクトは、和 (union)、積 (intersection)、差 (difference)、対称差 (symmetric difference)といった数学的な演算もサポートしています。

中括弧、または @ref{184,,set()} 関数は set を生成するために使用することができます。注: 空集合を作成するためには @code{set()} を使用しなければなりません (@code{@{@}} ではなく)。後者は空の辞書を作成します。辞書は次のセクションで議論するデータ構造です。

簡単なデモンストレーションを示します:

@example
>>> basket = @{'apple', 'orange', 'apple', 'pear', 'orange', 'banana'@}
>>> print(basket)                      # 重複が削除されていることを確認
@{'orange', 'banana', 'pear', 'apple'@}
>>> 'orange' in basket                 # 高速なメンバー判定
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
>>>
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # aのユニークな文字
@{'a', 'r', 'b', 'c', 'd'@}
>>> a - b                              # aにあってbにない文字
@{'r', 'd', 'b'@}
>>> a | b                              # aまたはbまたは両方に存在する文字
@{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'@}
>>> a & b                              # aとbの両方に存在する文字
@{'a', 'c'@}
>>> a ^ b                              # aまたはbにあるが、両方にはない文字
@{'r', 'd', 'b', 'm', 'z', 'l'@}
@end example

@ref{2029,,リスト内包} と同様に、 set 内包もサポートされています:

@example
>>> a = @{x for x in 'abracadabra' if x not in 'abc'@}
>>> a
@{'r', 'd'@}
@end example

@node 辞書型 dictionary,ループのテクニック,集合型,データ構造
@anchor{tutorial/datastructures dictionaries}@anchor{2032}@anchor{tutorial/datastructures tut-dictionaries}@anchor{2033}
@subsection 辞書型 (dictionary)


もう一つ、有用な型が Python に組み込まれています。それは `辞書 (dictionary)' (@ref{cbd,,マッピング型 --- dict} を参照)です。辞書は他の言語にも "連想記憶 (associated memory)" や "連想配列 (associative array)" という名前で存在することがあります。ある範囲の数でインデックス化されているシーケンスと異なり、辞書は `キー (key)' でインデックス化されています。このキーは何らかの変更不能な型になります。文字列、数値は常にキーにすることができます。タプルは、文字列、数値、その他のタプルのみを含む場合はキーにすることができます。直接、あるいは間接的に変更可能なオブジェクトを含むタプルはキーにできません。リストをキーとして使うことはできません。これは、リストにスライスやインデックス指定の代入を行ったり、 @ref{8dc,,append()} や @ref{602,,extend()} のようなメソッドを使うと、インプレースで変更することができるためです。

辞書は `キー(key): 値(value)' のペアの集合であり、キーが (辞書の中で)一意でなければならない、と考えるとよいでしょう。波括弧 (brace) のペア: @code{@{@}} は空の辞書を生成します。カンマで区切られた key: value のペアを波括弧ペアの間に入れると、辞書の初期値となる key: value が追加されます; この表現方法は出力時に辞書が書き出されるのと同じ方法です。

辞書での主な操作は、ある値を何らかのキーを付けて記憶することと、キーを指定して値を取り出すことです。 @code{del} で key: value のペアを削除することもできます。すでに使われているキーを使って値を記憶すると、以前そのキーに関連づけられていた値は忘れ去られてしまいます。

存在しないキーの値をインデックス指定(@code{d[key]})で取り出すと @ref{5e7,,KeyError} が発生します。存在しない可能性のあるキーへのアクセス時にこのエラーを回避するには、代わりに @ref{2034,,get()} メソッドを使用します。このメソッドは辞書にキーが存在しない場合に @code{None} (または指定されたデフォルト値)を返します。

辞書オブジェクトに対し @code{list(d)} を実行すると、辞書で使われている全てのキーからなるリストをキーが挿入された順番で返します (ソートされたリストが欲しい場合は、代わりに @code{sorted(d)} を使ってください)。ある単一のキーが辞書にあるかどうか調べるには、 @ref{34b,,in} キーワードを使います。

以下に、辞書を使った簡単な例を示します:

@example
>>> tel = @{'jack': 4098, 'sape': 4139@}
>>> tel['guido'] = 4127
>>> tel
@{'jack': 4098, 'sape': 4139, 'guido': 4127@}
>>> tel['jack']
4098
>>> tel['irv']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'irv'
>>> print(tel.get('irv'))
None
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
@{'jack': 4098, 'guido': 4127, 'irv': 4127@}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
@end example

@ref{183,,dict()} コンストラクタは、キーと値のペアのタプルを含むリストから辞書を生成します:

@example
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
@{'sape': 4139, 'guido': 4127, 'jack': 4098@}
@end example

さらに、辞書内包表現を使って、任意のキーと値のペアから辞書を作れます:

@example
>>> @{x: x**2 for x in (2, 4, 6)@}
@{2: 4, 4: 16, 6: 36@}
@end example

キーが単純な文字列の場合、キーワード引数を使って定義する方が単純な場合もあります:

@example
>>> dict(sape=4139, guido=4127, jack=4098)
@{'sape': 4139, 'guido': 4127, 'jack': 4098@}
@end example

@node ループのテクニック,条件についてもう少し,辞書型 dictionary,データ構造
@anchor{tutorial/datastructures looping-techniques}@anchor{2035}@anchor{tutorial/datastructures tut-loopidioms}@anchor{1ff2}
@subsection ループのテクニック


辞書に対してループを行う際、 @ref{9d2,,items()} メソッドを使うと、キーとそれに対応する値を同時に取り出せます。

@example
>>> knights = @{'gallahad': 'the pure', 'robin': 'the brave'@}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave
@end example

シーケンスにわたるループを行う際、 @ref{169a,,enumerate()} 関数を使うと、要素のインデックスと要素を同時に取り出すことができます。

@example
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe
@end example

二つまたはそれ以上のシーケンス型を同時にループするために、関数 @ref{1a0,,zip()} を使って各要素をひと組みにすることができます。

@example
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your @{0@}?  It is @{1@}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.
@end example

シーケンスを逆方向に渡ってループするには、まずシーケンスの範囲を順方向に指定し、次いで関数 @ref{a65,,reversed()} を呼び出します。

@example
>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1
@end example

シーケンスをソートされた順序でループするには、 @ref{dc7,,sorted()} 関数を使います。この関数は元の配列を変更せず、ソート済みの新たな配列を返します。

@example
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for i in sorted(basket):
...     print(i)
...
apple
apple
banana
orange
orange
pear
@end example

シーケンスに @ref{184,,set()} を使うと、重複要素が除去されます。
シーケンスに @ref{184,,set()} を使った上で、 @ref{dc7,,sorted()} を使うという組み合わせ方は、順番が整列されているシーケンスで、同一要素に 1 度のみループでアクセスする慣用的な方法です。

@example
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear
@end example

ときどきループ内でリストを変更したい誘惑に駆られるでしょうが、代わりに新しいリストを作ってしまうほうがより簡単で安全なことが、ままあります

@example
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]
@end example

@node 条件についてもう少し,シーケンスとその他の型の比較,ループのテクニック,データ構造
@anchor{tutorial/datastructures more-on-conditions}@anchor{2036}@anchor{tutorial/datastructures tut-conditions}@anchor{2037}
@subsection 条件についてもう少し


@code{while} や @code{if} 文で使った条件 (condition) には、値の比較だけでなく、他の演算子も使うことができます。

比較演算子 @code{in} および @code{not in} は、ある値があるコンテナーの中に存在するか (または存在しないか) どうかを確認するメンバーシップテストです。演算子 @code{is} および @code{is not} は、二つのオブジェクトが実際に同じオブジェクトであるかどうかを調べます。全ての比較演算子は同じ優先順位を持っており、ともに数値演算子よりも低い優先順位となります。

比較は連結させることができます。例えば、 @code{a < b == c} は、 @code{a} が @code{b} より小さく、かつ @code{b} と @code{c} が等しいかどうかをテストします。

ブール演算子 @code{and} や @code{or} で比較演算を組み合わせることができます。そして、比較演算 (あるいは何らかのブール式) の結果の否定は @code{not} でとれます。これらの演算子は全て、比較演算子よりも低い優先順位になっています。 @code{A and not B or C} と @code{(A and (not B)) or C} が等価になるように、ブール演算子の中で、 @code{not} の優先順位が最も高く、 @code{or} が最も低くなっています。もちろん、丸括弧を使えば望みの組み合わせを表現できます。

ブール演算子 @code{and} と @code{or} は、いわゆる `短絡 (short-circuit)' 演算子です。これらの演算子の引数は左から右へと順に評価され、結果が確定した時点で評価を止めます。例えば、 @code{A} と @code{C} は真で @code{B} が偽のとき、 @code{A and B and C} は式 @code{C} を評価しません。一般に、短絡演算子の戻り値をブール値ではなくて一般的な値として用いると、値は最後に評価された引数になります。

比較や他のブール式の結果を変数に代入することもできます。例えば、

@example
>>> string1, string2, string3 = '@w{'}, 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
@end example

Pythonでは、Cとは異なり、式の中での代入は @ref{2038,,セイウチ演算子} @code{:=} を使用して明示的に行う必要があることに注意してください。これにより、 @code{==} が意図されていたところに @code{=} を入力してしまうという、Cプログラムで発生する一般的なクラスの問題を回避できます。

@node シーケンスとその他の型の比較,,条件についてもう少し,データ構造
@anchor{tutorial/datastructures comparing-sequences-and-other-types}@anchor{2039}@anchor{tutorial/datastructures tut-comparing}@anchor{203a}
@subsection シーケンスとその他の型の比較


概して、シーケンスオブジェクトは、同じシーケンス型の他のオブジェクトと比較できます。比較には `辞書的な (lexicographical)' 順序が用いられます。まず、最初の二つの要素を比較し、その値が等しくなければその時点で比較結果が決まります。等しければ次の二つの要素を比較し、以降シーケンスの要素が尽きるまで続けます。比較しようとする二つの要素がいずれも同じシーケンス型であれば、そのシーケンス間での辞書比較を再帰的に行います。二つのシーケンスの全ての要素の比較結果が等しくなれば、シーケンスは等しいとみなされます。片方のシーケンスがもう一方の先頭部分にあたる部分シーケンスならば、短い方のシーケンスが小さいシーケンスとみなされます。文字列に対する辞書的な順序づけには、個々の文字ごとに ASCII 順序を用います。以下に、同じ型のオブジェクトを持つシーケンス間での比較を行った例を示します:

@example
(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
@end example

違う型のオブジェクト同士を @code{<} や @code{>} で比較することも、それらのオブジェクトが適切な比較メソッドを提供しているのであれば許可されます。例えば、異なる数値型同士の比較では、その数値によって比較が行われます。例えば、 0 と 0.0 は等価です。一方、適切な比較順序がない場合は、インタープリターは @ref{198,,TypeError} 例外を発生させます。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node モジュール<2>,入力と出力,データ構造,Python チュートリアル
@anchor{tutorial/modules doc}@anchor{203b}@anchor{tutorial/modules modules}@anchor{203c}@anchor{tutorial/modules translation-repo}@anchor{203d}@anchor{tutorial/modules tut-modules}@anchor{203e}
@section モジュール


Python インタプリタを終了させ、再び起動すると、これまでに行ってきた定義 (関数や変数) は失われています。ですから、より長いプログラムを書きたいなら、テキストエディタを使ってインタプリタへの入力を用意しておき、手作業の代わりにファイルを入力に使って動作させるとよいでしょう。この作業を `スクリプト (script)' の作成と言います。プログラムが長くなるにつれ、メンテナンスを楽にするために、スクリプトをいくつかのファイルに分割したくなるかもしれません。また、いくつかのプログラムで書いてきた便利な関数について、その定義をコピーすることなく個々のプログラムで使いたいと思うかもしれません。

こういった要求をサポートするために、Python では定義をファイルに書いておき、スクリプトの中やインタプリタの対話インスタンス上で使う方法があります。このファイルを `モジュール (module)' と呼びます。モジュールにある定義は、他のモジュールや `main' モジュール (実行のトップレベルや電卓モードでアクセスできる変数の集まりを指します) に `import' (取り込み) することができます。

モジュールは Python の定義や文が入ったファイルです。ファイル名はモジュール名に接尾語 @code{.py} がついたものになります。モジュールの中では、(文字列の) モジュール名をグローバル変数 @code{__name__} で取得できます。例えば、お気に入りのテキストエディタを使って、現在のディレクトリに以下の内容のファイル @code{fibo.py} を作成してみましょう:

@example
# フィボナッチ数のモジュール

def fib(n):
    """nまでのフィボナッチ数を出力する"""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):
    """nまでのフィボナッチ数を返す"""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result
@end example

次に Python インタプリタに入り、モジュールを以下のコマンドで import しましょう:

@example
>>> import fibo
@end example

この操作では、@code{fibo} で定義された関数の名前を直接現在の @ref{203f,,namespace} (詳細は @ref{2040,,Python のスコープと名前空間} を参照してください)に追加することはありません。単にモジュール名 @code{fibo} だけを名前空間に追加します。関数にはモジュール名を使ってアクセスします:

@example
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
@end example

関数を度々使うのなら、ローカルな名前に代入できます:

@example
>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

@menu
* モジュールについてもうすこし:: 
* 標準モジュール:: 
* dir() 関数: dir 関数. 
* パッケージ:: 

@end menu

@node モジュールについてもうすこし,標準モジュール,,モジュール<2>
@anchor{tutorial/modules more-on-modules}@anchor{2041}@anchor{tutorial/modules tut-moremodules}@anchor{2042}
@subsection モジュールについてもうすこし


モジュールには、関数定義に加えて実行文を入れることができます。これらの実行文はモジュールを初期化するためのものです。これらの実行文は、インポート文の中で `最初に' モジュール名が見つかったときにだけ実行されます。@footnote{
実際には、関数定義も '実行' される '文' です。モジュールレベルの関数定義を実行すると、関数名はモジュールのグローバルな名前空間に追加されます。
} (ファイルがスクリプトとして実行される場合も実行されます。)

各々のモジュールは、自分のプライベートな名前空間を持っていて、モジュールで定義されている関数はこのテーブルをグローバルな名前空間として使います。したがって、モジュールの作者は、ユーザのグローバル変数と偶然的な衝突が起こる心配をせずに、グローバルな変数をモジュールで使うことができます。一方、自分が行っている操作をきちんと理解していれば、モジュール内の関数を参照するのと同じ表記法 @code{modname.itemname} で、モジュールのグローバル変数をいじることもできます。

モジュールは他のモジュールをインポートできます。 @ref{7f8,,import} 文はモジュール（さらに言えばスクリプトでも）の先頭に置きますが、これは慣習であって必須ではありません。インポートされたモジュール名は、モジュールのトップレベル（関数やクラスの外）に書いてあれば、モジュールのグローバルな名前空間に置かれます。

@ref{7f8,,import} 文には、あるモジュール内の名前を、import を実行しているモジュールの名前空間内に直接取り込むという変型があります。例えば:

@example
>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

この操作は、import の対象となるモジュール名をローカルな名前空間内に取り入れることはありません (従って上の例では、 @code{fibo} は定義されません)。

モジュールで定義されている名前を全て import するという変型もあります:

@example
>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

この書き方ではアンダースコア (@code{_}) で始まるものを除いてすべての名前をインポートします。殆どの場面で、Python プログラマーはこの書き方を使いません。未知の名前がインタープリターに読み込まれ、定義済みの名前を上書きしてしまう可能性があるからです。

一般的には、モジュールやパッケージから @code{*} を import するというやり方には賛同できません。というのは、この操作を行うとしばしば可読性に乏しいコードになるからです。しかし、対話セッションでキータイプの量を減らすために使うのは構わないでしょう。

モジュール名の後に @code{as} が続いていた場合は、 @code{as} の後ろの名前を直接、インポートされたモジュールが束縛します。

@example
>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

これは実質的には @code{import fibo} と同じ方法でモジュールをインポートしていて、唯一の違いはインポートしたモジュールが @code{fib} という名前で取り扱えるようになっていることです。

このインポート方法は @ref{14c3,,from} が付いていても使え、同じ効果が得られます:

@example
>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

@cartouche
@quotation 注釈 
実行効率上の理由で、各モジュールはインタープリタの 1 セッションごとに 1 回だけ import されます。従って、モジュールを修正した場合には、インタープリタを再起動させなければなりません -- もしくは、その場で手直ししてテストしたいモジュールが 1 つだった場合には、例えば @code{import importlib; importlib.reload(modulename)} のように @ref{73d,,importlib.reload()} を使ってください。
@end quotation
@end cartouche

@menu
* モジュールをスクリプトとして実行する:: 
* モジュール検索パス:: 
* "コンパイル" された Python ファイル:: 

@end menu

@node モジュールをスクリプトとして実行する,モジュール検索パス,,モジュールについてもうすこし
@anchor{tutorial/modules executing-modules-as-scripts}@anchor{2043}@anchor{tutorial/modules tut-modulesasscripts}@anchor{2044}
@subsubsection モジュールをスクリプトとして実行する


Python モジュールを

@example
python fibo.py <arguments>
@end example

と実行すると、@code{__name__} に @code{__main__} が設定されている点を除いて import したときと同じようにモジュール内のコードが実行されます。つまりモジュールの末尾に:

@example
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
@end example

このコードを追加することで、このファイルが import できるモジュールであると同時にスクリプトとしても使えるようになります。なぜならモジュールが "main" ファイルとして起動されたときだけ、コマンドラインを解釈するコードが実行されるからです:

@example
$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34
@end example

モジュールが import された場合は、そのコードは実行されません:

@example
>>> import fibo
>>>
@end example

この方法はモジュールに便利なユーザインターフェースを提供したり、テストのために (スクリプトをモジュールとして起動しテストスイートを実行して) 使われます。

@node モジュール検索パス,"コンパイル" された Python ファイル,モジュールをスクリプトとして実行する,モジュールについてもうすこし
@anchor{tutorial/modules the-module-search-path}@anchor{2045}@anchor{tutorial/modules tut-searchpath}@anchor{2046}
@subsubsection モジュール検索パス


@geindex module;検索;パス

@code{spam} という名前のモジュールをインポートするとき、インタープリタはまずその名前の組み込みモジュールを探します。モジュール名の一覧は @ref{2047,,sys.builtin_module_names} にあります。見つからなかった場合は、 @code{spam.py} という名前のファイルを @ref{3e4,,sys.path} にあるディレクトリのリストから探します。 @ref{3e4,,sys.path} は以下の場所に初期化されます:


@itemize *

@item 
入力されたスクリプトのあるディレクトリ (あるいはファイルが指定されなかったときはカレントディレクトリ)。

@item 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} (ディレクトリ名のリスト。シェル変数の 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} と同じ構文)。

@item 
インストール方法に依存したデフォルト（慣例として @code{site-packages} ディレクトリーが含まれ、@ref{cc,,site} モジュールによって処理される）。
@end itemize

詳細は @ref{18dc,,sys.path モジュール検索パスの初期化} を参照してください。

@cartouche
@quotation 注釈 
シンボリックリンクをサポートするファイルシステム上では、入力されたスクリプトのあるディレクトリはシンボリックリンクをたどった後に計算されます。言い換えるとシンボリックリンクを含むディレクトリはモジュール検索パスに追加 `されません'。
@end quotation
@end cartouche

初期化された後、 Python プログラムは @ref{3e4,,sys.path} を修正することができます。スクリプトファイルを含むディレクトリが検索パスの先頭、標準ライブラリパスよりも前に追加されます。なので、ライブラリのディレクトリにあるファイルよりも、そのディレクトリにある同じ名前のスクリプトが優先してインポートされます。これは、標準ライブラリを意図して置き換えているのでない限りは間違いのもとです。より詳しい情報は @ref{2048,,標準モジュール} を参照してください。

@c %
@c Do we need stuff on zip files etc. ? DUBOIS

@node "コンパイル" された Python ファイル,,モジュール検索パス,モジュールについてもうすこし
@anchor{tutorial/modules compiled-python-files}@anchor{2049}@anchor{tutorial/modules tut-pycache}@anchor{8eb}
@subsubsection "コンパイル" された Python ファイル


モジュールの読み込みを高速化するため、Python はコンパイル済みの各モジュールを @code{__pycache__} ディレクトリの @code{module.`version'.pyc} ファイルとしてキャッシュします。ここで version はコンパイルされたファイルのフォーマットを表すもので、一般的には Python のバージョン番号です。例えば、CPython のリリース 3.3 の、コンパイル済みの spam.py は @code{__pycache__/spam.cpython-33.pyc} としてキャッシュされるでしょう。この命名の慣習により、Python の異なる複数のリリースやバージョンのコンパイル済みモジュールが共存できます。

Python はソースの変更日時をコンパイル済みのものと比較し、コンパイル済みのものが最新でなくなり再コンパイルが必要になっていないかを確認します。これは完全に自動で処理されます。また、コンパイル済みモジュールはプラットフォーム非依存なため、アーキテクチャの異なるシステム間で同一のライブラリを共有することもできます。

Python は2つの場合にキャッシュのチェックを行いません。ひとつは、コマンドラインから直接モジュールが読み込まれた場合で、常に再コンパイルされ、結果を保存することはありません。2つめは、ソース・モジュールのない場合で、キャッシュの確認を行いません。ソースのない (コンパイル済みのもののみの) 配布をサポートするには、コンパイル済みモジュールはソース・ディレクトリになくてはならず、ソース・ディレクトリにソース・モジュールがあってはいけません。

エキスパート向けのTips:


@itemize *

@item 
コンパイル済みモジュールのサイズを小さくするために、Python コマンドに @ref{18c,,-O} または @ref{fb5,,-OO} スイッチを使うことができます。@code{-O} スイッチは assert ステートメントを除去し、@code{-OO} スイッチは assert ステートメントと __doc__ 文字列を除去します。いくつかのプログラムはこれらの除去されるものに依存している可能性があるため、自分が何をしているかを理解しているときに限ってこれらのオプションを使うべきです。"最適化" されたモジュールは @code{opt-} タグを持ち、通常のコンパイル済みモジュールよりサイズが小さくなります。将来のリリースでは最適化の影響が変わる可能性があります。

@item 
@code{.pyc} ファイルや @code{.pyo} ファイルから読み出されたとしても、プログラムは @code{.py} ファイルから読み出されたときより何ら高速に動作するわけではありません。@code{.pyc} ファイルで高速化されるのは、読み込みにかかる時間だけです。

@item 
@ref{21,,compileall} モジュールを使ってディレクトリ内の全てのモジュールに対して .pyc ファイルを作ることができます。

@item 
この処理に関する詳細は、判定のフローチャートを含めて、
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} に記載されています。
@end itemize

@node 標準モジュール,dir 関数,モジュールについてもうすこし,モジュール<2>
@anchor{tutorial/modules standard-modules}@anchor{204a}@anchor{tutorial/modules tut-standardmodules}@anchor{2048}
@subsection 標準モジュール


@geindex module;sys

Python は標準モジュールライブラリを同梱していて、別の Python ライブラリリファレンスというドキュメントで解説しています。幾つかのモジュールは言語のコアにはアクセスしないものの、効率や、システムコールなどOSの機能を利用するために、インタープリター内部にビルトインされています。そういったモジュールセットはまたプラットフォームに依存した構成オプションです。例えば、 @ref{11c,,winreg} モジュールは Windows システムでのみ提供されています。 1つ注目に値するモジュールとして、 @ref{df,,sys} モジュールは、全ての Python インタープリターにビルトインされています。 @code{sys.ps1} と @code{sys.ps2} という変数は一次プロンプトと二次プロンプトに表示する文字列を定義しています:

@example
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>
@end example

これらの二つの変数は、インタプリタが対話モードにあるときだけ定義されています。

変数 @code{sys.path} は文字列からなるリストで、インタプリタがモジュールを検索するときのパスを決定します。 @code{sys.path} は環境変数 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} から得たデフォルトパスに、 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} が設定されていなければ組み込みのデフォルト値に設定されます。標準的なリスト操作で変更することができます:

@example
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
@end example

@node dir 関数,パッケージ,標準モジュール,モジュール<2>
@anchor{tutorial/modules the-dir-function}@anchor{204b}@anchor{tutorial/modules tut-dir}@anchor{204c}
@subsection @code{dir()} 関数


組込み関数 @ref{844,,dir()} は、あるモジュールがどんな名前を定義しているか調べるために使われます。 @ref{844,,dir()} はソートされた文字列のリストを返します:

@example
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
 '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
 '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
 '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
 '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
 'warnoptions']
@end example

引数がなければ、 @ref{844,,dir()} は現在定義している名前を列挙します:

@example
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
@end example

変数、モジュール、関数、その他の、すべての種類の名前をリストすることに注意してください。

@geindex module;builtins

@ref{844,,dir()} は、組込みの関数や変数の名前はリストしません。これらの名前からなるリストが必要なら、標準モジュール @ref{13,,builtins} で定義されています:

@example
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError',
 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
 '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
 'zip']
@end example

@node パッケージ,,dir 関数,モジュール<2>
@anchor{tutorial/modules packages}@anchor{204d}@anchor{tutorial/modules tut-packages}@anchor{204e}
@subsection パッケージ


パッケージ (package) は、Python のモジュール名前空間を "ドット付きモジュール名" を使って構造化する手段です。例えば、モジュール名 @code{A.B} は、 @code{A} というパッケージのサブモジュール @code{B} を表します。ちょうど、モジュールを利用すると、別々のモジュールの著者が互いのグローバル変数名について心配しなくても済むようになるのと同じように、ドット付きモジュール名を利用すると、 NumPy や Pillow のように複数モジュールからなるパッケージの著者が、互いのモジュール名について心配しなくても済むようになります。

音声ファイルや音声データを一様に扱うためのモジュールのコレクション ("パッケージ") を設計したいと仮定しましょう。 音声ファイルには多くの異なった形式がある (通常は拡張子、 例えば @code{.wav}, @code{.aiff}, @code{.au} などで認識されます) ので、増え続ける様々なファイル形式を相互変換するモジュールを、 作成したりメンテナンスしたりする必要があるかもしれません。 また、 音声データに対して実行したい様々な独自の操作 (ミキシング、 エコーの追加、 イコライザ関数の適用、 人工的なステレオ効果の作成など) があるかもしれません。 そうなると、 こうした操作を実行するモジュールを果てしなく書くことになるでしょう。 以下に (階層的なファイルシステムで表現した) パッケージの構造案を示します:

@example
sound/                          トップレベルのパッケージ
      __init__.py               soundパッケージの初期化
      formats/                  ファイルフォーマットの変換用サブパッケージ
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  サウンドエフェクトのサブパッケージ
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  フィルターのサブパッケージ
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...
@end example

パッケージを import する際、 Python は @code{sys.path} 上のディレクトリを検索して、トップレベルのパッケージの入ったサブディレクトリを探します。

ファイルを含むディレクトリをパッケージとしてPython に扱わせるには、ファイル @code{__init__.py} が必要です(より高度な機能 @ref{2b2,,namespace package} を使う場合を除く)。
これにより、 @code{string} のようなよくある名前のディレクトリにより、モジュール検索パスの後の方で見つかる正しいモジュールが意図せず隠蔽されてしまうのを防ぐためです。
最も簡単なケースでは @code{__init__.py} はただの空ファイルで構いませんが、 @code{__init__.py} ではパッケージのための初期化コードを実行したり、後述の @code{__all__} 変数を設定してもかまいません。

パッケージのユーザは、個々のモジュールをパッケージから import することができます。例えば:

@example
import sound.effects.echo
@end example

この操作はサブモジュール @code{sound.effects.echo} をロードします。このモジュールは、以下のように完全な名前で参照しなければなりません。

@example
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
@end example

サブモジュールを import するもう一つの方法を示します:

@example
from sound.effects import echo
@end example

これもサブモジュール @code{echo} をロードし、パッケージ名なしで利用可能にします。なのでこう使えます:

@example
echo.echofilter(input, output, delay=0.7, atten=4)
@end example

さらにもう一つのバリエーションとして、必要な関数や変数を直接 import する方法があります:

@example
from sound.effects.echo import echofilter
@end example

また、これもサブモジュール @code{echo} をロードしますが、 @code{echofilter()} 関数を直接利用可能にします:

@example
echofilter(input, output, delay=0.7, atten=4)
@end example

@code{from package import item} を使う場合、 `item' はパッケージ `package' のサブモジュール (またはサブパッケージ) でもかまいませんし、関数やクラス、変数のような、 `package' で定義されている別の名前でもかまわないことに注意してください。 @code{import} 文はまず、 `item' がパッケージ内で定義されているかどうか調べます。定義されていなければ、 `item' はモジュール名であると仮定して、モジュールをロードしようと試みます。もしモジュールが見つからなければ、 @ref{65b,,ImportError} が送出されます。

反対に、 @code{import item.subitem.subsubitem} のような構文を使った場合、最後の @code{subsubitem} を除く各要素はパッケージでなければなりません。最後の要素はモジュールかパッケージにできますが、一つ前の要素で定義されているクラスや関数や変数にはできません。

@menu
* パッケージから * を import する:: 
* パッケージ内参照:: 
* 複数ディレクトリ中のパッケージ:: 

@end menu

@node パッケージから * を import する,パッケージ内参照,,パッケージ
@anchor{tutorial/modules importing-from-a-package}@anchor{204f}@anchor{tutorial/modules tut-pkg-import-star}@anchor{2050}
@subsubsection パッケージから * を import する


@geindex __all__

それでは、ユーザが @code{from sound.effects import *} と書いたら、どうなるのでしょうか？理想的には、何らかの方法でファイルシステムが調べられ、そのパッケージにどんなサブモジュールがあるかを調べ上げ、全てを import する、という処理を望むことでしょう。これには長い時間がかかってしまうこともありますし、あるサブモジュールを import することで、そのモジュールが明示的に import されたときのみ発生して欲しい副作用が起きてしまうかもしれません。

唯一の解決策は、パッケージの作者にパッケージの索引を明示的に提供させる というものです。 @ref{7f8,,import} 文の使う規約は、パッケージの @code{__init__.py} コードに @code{__all__} という名前のリストが定義されていれば、 @code{from package import *} が現れたときに import すべきモジュール名のリストとして使う、というものです。 パッケージの新バージョンがリリースされるときにリストを最新の状態に更新するのは パッケージの作者の責任となります。 自分のパッケージから * を import するという使い方が考えられないならば、 パッケージの作者はこの使い方をサポートしないことにしてもかまいません。 例えば、ファイル @code{sound/effects/__init__.py} には、次のような コードを入れてもよいかもしれません:

@example
__all__ = ["echo", "surround", "reverse"]
@end example

これが意味するのは、 @code{from sound.effects import *} とすると、名前の挙がった 3つのサブモジュールが @code{sound.effects} パッケージから import される、ということです。

注意点として、サブモジュールはローカルな名前で隠されることがあります。例として、 @code{reverse} 関数を @code{sound/effects/__init__.py} に足すと、 @code{from sound.effects import *} では @code{echo} と @code{surround} の２サブモジュールだけ import されます。 @code{reverse} サブモジュールは import `されません' 。それはローカルに定義された @code{reverse} 関数で隠されたので:

@example
__all__ = [
    "echo",      # 'echo.py' ファイルを参照する
    "surround",  # 'surround.py' ファイルを参照する
    "reverse",   # !!! 'reverse' 関数を参照する !!!
]

def reverse(msg: str):  # <-- この名前は 'from sound.effects import *' を実行したときに
    return msg[::-1]    #     サブモジュールの 'reverse.py' を隠してしまう
@end example

もしも @code{__all__} が定義されていなければ、実行文 @code{from sound.effects import *} は、パッケージ @code{sound.effects} の全てのサブモジュールを現在の名前空間の中へ import `しません' 。この文は単に(場合によっては初期化コード @code{__init__.py} を実行して) パッケージ @code{sound.effects} が import されたということを確認し、そのパッケージで定義されている名前を全て import するだけです。 import される名前には、 @code{__init__.py} で定義された名前 (と、明示的にロードされたサブモジュール) が含まれます。パッケージのサブモジュールで、以前の @ref{7f8,,import} 文で明示的にロードされたものも含みます。以下のコードを考えてください:

@example
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
@end example

上の例では、 @code{echo} と @code{surround} モジュールが現在の名前空間に import されます。これらのモジュールは @code{from...import} 文が実行された際に @code{sound.effects} 内で定義されているからです。 (この機構は @code{__all__} が定義されているときにも働きます。)

特定のモジュールでは @code{import *} を使ったときに、特定のパターンに従った名前のみを公開 (export) するように設計されてはいますが、それでもやはり製品のコードでは良いことではないと考えます。

@code{from package import specific_submodule} を使っても何も問題はないことに留意してください！実際この表記法は、import を行うモジュールが他のパッケージと同じ名前を持つサブモジュールを使わなければならない場合を除いて推奨される方式です。

@node パッケージ内参照,複数ディレクトリ中のパッケージ,パッケージから * を import する,パッケージ
@anchor{tutorial/modules id2}@anchor{2051}@anchor{tutorial/modules intra-package-references}@anchor{2052}
@subsubsection パッケージ内参照


パッケージが (前述の例の @code{sound} パッケージのように) サブパッケージの集まりに構造化されている場合、絶対 import を使って兄弟関係にあるパッケージを参照できます。例えば、モジュール @code{sound.filters.vocoder} で @code{sound.effects} パッケージの @code{echo} モジュールが必要な場合、 @code{from sound.effects import echo} が使えます。

また、明示的な相対importを @code{from module import name} の形式の import 文で利用できます。この明示的な相対 import では、先頭のドットで現在および親パッケージを指定します。 @code{surround} モジュールの例では、以下のように記述できます:

@example
from . import echo
from .. import formats
from ..filters import equalizer
@end example

相対 import は現在のモジュールのパッケージ名をベースにすることに注意してください。メインモジュールはパッケージがないため、Python アプリケーションのメインモジュールとして利用されることを意図しているモジュールでは絶対 import を利用するべきです。

@node 複数ディレクトリ中のパッケージ,,パッケージ内参照,パッケージ
@anchor{tutorial/modules packages-in-multiple-directories}@anchor{2053}
@subsubsection 複数ディレクトリ中のパッケージ


パッケージはもう一つ特別な属性として @ref{2054,,__path__} をサポートしています。この属性は、パッケージの @code{__init__.py} 中のコードが実行されるよりも前に、 @code{__init__.py} の収められているディレクトリ名の文字列を含んだ 入った @ref{716,,sequence} になるよう初期化されます。この変数は変更することができます。変更を加えると、以降そのパッケージに入っているモジュールやサブパッケージの検索に影響します。

この機能はほとんど必要にはならないのですが、パッケージ内存在するモジュール群を拡張するために使うことができます。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 入力と出力,エラーと例外,モジュール<2>,Python チュートリアル
@anchor{tutorial/inputoutput doc}@anchor{2055}@anchor{tutorial/inputoutput input-and-output}@anchor{2056}@anchor{tutorial/inputoutput translation-repo}@anchor{2057}@anchor{tutorial/inputoutput tut-io}@anchor{2058}
@section 入力と出力


プログラムの出力方法にはいくつかの種類があります。
データを人間が読める形で出力することもあれば、将来使うためにファイルに書くこともあります。
この章では、こうした幾つかの出力の方法について話します。

@menu
* 出力を見やすくフォーマットする:: 
* ファイルを読み書きする:: 

@end menu

@node 出力を見やすくフォーマットする,ファイルを読み書きする,,入力と出力
@anchor{tutorial/inputoutput fancier-output-formatting}@anchor{2059}@anchor{tutorial/inputoutput tut-formatting}@anchor{205a}
@subsection 出力を見やすくフォーマットする


これまでに、値を出力する二つの方法: `式文 (expression statement)' と @ref{1177,,print()} 関数が出てきました。 (第三はファイルオブジェクトの @ref{205b,,write()} メソッドを使う方法です。標準出力を表すファイルは @code{sys.stdout} で参照できます。詳細はライブラリリファレンスを参照してください。)

単に空白区切りで値を並べただけの出力よりも、フォーマットを制御したいと思うことはよくあることでしょう。
出力をフォーマットする方法はいくつかあります。


@itemize *

@item 
@ref{205c,,フォーマット済み文字列リテラル} を使うには、開き引用符や三重の開き引用符の前に @code{f} あるいは @code{F} を付けて文字列を始めます。
この文字列の内側では、文字 @code{@{} と文字 @code{@}} の間に Python の式が書け、その式から変数やリテラル値が参照できます。

@example
>>> year = 2016
>>> event = '国民投票'
>>> f'@{year@}年の@{event@}の結果'
'2016年の国民投票の結果'
@end example

@item 
文字列の @ref{833,,str.format()} メソッドは、もう少し手間がかかります。
ここでも @code{@{} と @code{@}} を使って変数に代入する場所の印を付けて、細かいフォーマットの指示を出せますが、フォーマットされる対象の情報を与える必要があります。次のコードには、変数をフォーマットする方法の例が二つあります:

@example
>>> yes_votes = 42_572_654
>>> total_votes = 85_705_149
>>> percentage = yes_votes / total_votes
>>> '@{:-9@} 賛成票  @{:2.2%@}'.format(yes_votes, percentage)
' 42572654 賛成票  49.67%'
@end example

@code{yes_votes} が、スペースと、負数の場合は負符号で埋められていることに注意してください。この例では、100を掛けた @code{percentage} を、パーセント記号付きで小数点以下2桁で表示することも行っています。 (詳細は、 @ref{4f9,,書式指定ミニ言語仕様} を参照してください。)

@item 
最後に、文字列のスライス操作や結合操作を使い、全ての文字列を自分で処理し、思い通りのレイアウトを作成できます。
文字列型には、文字列の間隔を調整して指定されたカラム幅に揃えるのに便利な操作を行うメソッドがいくつかあります。
@end itemize

凝った出力である必要は無いけれど、デバッグ目的で変数をすばやく表示したいときは、 @ref{1c1,,repr()} 関数か @ref{169,,str()} 関数でどんな値も文字列に変換できます。

@ref{169,,str()} 関数は値の人間に読める表現を返すためのもので、 @ref{1c1,,repr()} 関数はインタープリタに読める (あるいは同値となる構文がない場合は必ず @ref{18e,,SyntaxError} になるような) 表現を返すためのものです。人間が読むのに適した特定の表現を持たないオブジェクトにおいては、 @ref{169,,str()} は @ref{1c1,,repr()} と同じ値を返します。数値や、リストや辞書を始めとするデータ構造など、多くの値がどちらの関数に対しても同じ表現を返します。一方、文字列は、2つの異なる表現を持っています。

いくつかの例です:

@example
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # 文字列に repr() を使うとクォートとバックスラッシュが追加される:
>>> hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # repr() の引数はどんな Python オブジェクトでも可:
>>> repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
@end example

The @ref{d8,,string} module contains support for a simple templating approach
based upon regular expressions, via @ref{897,,string.Template}.
This offers yet another way to substitute values into strings,
using placeholders like @code{$x} and replacing them with values from a dictionary.
This syntax is easy to use, although it offers much less control for formatting.

@geindex formatted string literal
@geindex interpolated string literal
@geindex string;formatted literal
@geindex string;interpolated literal
@geindex f-string
@geindex fstring

@menu
* フォーマット済み文字列リテラル:: 
* 文字列の format() メソッド: 文字列の format メソッド. 
* 文字列の手作業でのフォーマット:: 
* 古い文字列書式設定方法:: 

@end menu

@node フォーマット済み文字列リテラル,文字列の format メソッド,,出力を見やすくフォーマットする
@anchor{tutorial/inputoutput formatted-string-literals}@anchor{205d}@anchor{tutorial/inputoutput tut-f-strings}@anchor{205c}
@subsubsection フォーマット済み文字列リテラル


@ref{19a,,フォーマット済み文字リテラル} (短くして f-string とも呼びます) では、文字列の頭に @code{f} か @code{F} を付け、式を @code{@{expression@}} と書くことで、 Python の式の値を文字列の中に入れ込めます。

オプションのフォーマット指定子を式の後ろに付けられます。
このフォーマット指定子によって値のフォーマット方式を制御できます。
次の例では、円周率πを小数点以下3桁に丸めてフォーマットしています:

@example
>>> import math
>>> print(f'πの値はだいたい @{math.pi:.3f@} です。')
πの値はだいたい 3.142 です。
@end example

@code{':'} の後ろに整数をつけると、そのフィールドの最小の文字幅を指定できます。
この機能は縦を揃えるのに便利です。

@example
>>> table = @{'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678@}
>>> for name, phone in table.items():
...     print(f'@{name:10@} ==> @{phone:10d@}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678
@end example

他の修飾子は、フォーマットする前に値を変換するのに使えます。
@code{'!a'} は @ref{15ff,,ascii()} を、 @code{'!s'} は @ref{169,,str()} を、 @code{'!r'} は @ref{1c1,,repr()} を適用します:

@example
>>> animals = 'ウナギ'
>>> print(f'私のホバークラフトは @{animals@} でいっぱいです。')
私のホバークラフトは ウナギ でいっぱいです。
>>> print(f'私のホバークラフトは @{animals!r@} でいっぱいです。')
私のホバークラフトは 'ウナギ' でいっぱいです。
@end example

@code{=} 指定子を使用すると式を展開して、式、イコール記、式を評価した文字列表現、の形式で表示されます。

@example
>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging @{bugs=@} @{count=@} @{area=@}')
Debugging bugs='roaches' count=13 area='living room'
@end example

@code{=} 指定子の詳細については @ref{b9f,,self-documenting expressions} を参照してください。 フォーマットについての仕様は @ref{4f9,,書式指定ミニ言語仕様} のリファレンスガイドを参照してください。

@node 文字列の format メソッド,文字列の手作業でのフォーマット,フォーマット済み文字列リテラル,出力を見やすくフォーマットする
@anchor{tutorial/inputoutput the-string-format-method}@anchor{205e}@anchor{tutorial/inputoutput tut-string-format}@anchor{205f}
@subsubsection 文字列の format() メソッド


@ref{833,,str.format()} メソッドの基本的な使い方は次のようなものです:

@example
>>> print('We are the @{@} who say "@{@}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
@end example

括弧とその中の文字(これをフォーマットフィールドと呼びます)は、 @ref{833,,str.format()} メソッドに渡されたオブジェクトに置換されます。括弧の中の数字は @ref{833,,str.format()} メソッドに渡されたオブジェクトの位置を表すのに使えます。

@example
>>> print('@{0@} and @{1@}'.format('spam', 'eggs'))
spam and eggs
>>> print('@{1@} and @{0@}'.format('spam', 'eggs'))
eggs and spam
@end example

@ref{833,,str.format()} メソッドにキーワード引数が渡された場合、その値はキーワード引数の名前によって参照されます。

@example
>>> print('This @{food@} is @{adjective@}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
@end example

順序引数とキーワード引数を組み合わせて使うこともできます:

@example
>>> print('The story of @{0@}, @{1@}, and @{other@}.'.format('Bill', 'Manfred',
...                                                    other='Georg'))
The story of Bill, Manfred, and Georg.
@end example

もしも長い書式文字列があり、それを分割したくない場合には、変数を引数の位置ではなく変数の名前で参照できるとよいでしょう。これは、辞書を引数に渡して、角括弧 @code{'[]'} を使って辞書のキーを参照することで可能です。

@example
>>> table = @{'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678@}
>>> print('Jack: @{0[Jack]:d@}; Sjoerd: @{0[Sjoerd]:d@}; '
...       'Dcab: @{0[Dcab]:d@}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
@end example

辞書 @code{table} を @code{**} 記法を使ってキーワード引数として渡す方法もあります。

@example
>>> table = @{'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678@}
>>> print('Jack: @{Jack:d@}; Sjoerd: @{Sjoerd:d@}; Dcab: @{Dcab:d@}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
@end example

全てのローカルな変数が入った辞書を返す組み込み関数 @ref{1e23,,vars()} と組み合わせると特に便利です。

@example
>>> table = @{k: str(v) for k, v in vars().items()@}>>> message = " ".join([f'@{k@}: ' + '@{' + k +'@};' for k in table.keys()])>>> print(message.format(**table))__name__: __main__; __doc__: None; __package__: None; __loader__: ...
@end example

例として、下のコード行は与えられた整数とその2乗と3乗がきちんと揃った列を生成します:

@example
>>> for x in range(1, 11):
...     print('@{0:2d@} @{1:3d@} @{2:4d@}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
@end example

@ref{833,,str.format()} による文字列書式設定の完全な解説は、 @ref{15b3,,書式指定文字列の文法} を参照してください。

@node 文字列の手作業でのフォーマット,古い文字列書式設定方法,文字列の format メソッド,出力を見やすくフォーマットする
@anchor{tutorial/inputoutput manual-string-formatting}@anchor{2060}
@subsubsection 文字列の手作業でのフォーマット


次は 2 乗と 3 乗の値からなる同じ表を手作業でフォーマットしたものです:

@example
>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # 上の行で end を使用していることに注意
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
@end example

(各カラムの間のスペース一個分は @ref{1177,,print()} の動作で追加されていることに注意してください。 @ref{1177,,print()} は常に引数間に空白を追加します。)

文字列オブジェクトの @ref{2061,,str.rjust()} メソッドは、指定された幅のフィールド内に文字列が右寄せで入るように左側に空白を追加します。
同様のメソッドとして、 @ref{2062,,str.ljust()} と @ref{2063,,str.center()} があります。
これらのメソッドは何か出力を行うわけではなく、ただ新しい文字列を返します。
入力文字列が長すぎる場合、文字列を切り詰めることはせず、値をそのまま返します。この仕様のためにカラムのレイアウトが滅茶苦茶になるかもしれませんが、嘘の値が代わりに書き出されるよりはましです。
(本当に切り詰めを行いたいのなら、全てのカラムに @code{x.ljust(n)[:n]} のようにスライス表記を加えることもできます。)

もう一つのメソッド、 @ref{16cb,,str.zfill()} は、数値文字列の左側をゼロ詰めします。このメソッドは正と負の符号を正しく扱います:

@example
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
@end example

@node 古い文字列書式設定方法,,文字列の手作業でのフォーマット,出力を見やすくフォーマットする
@anchor{tutorial/inputoutput old-string-formatting}@anchor{2064}
@subsubsection 古い文字列書式設定方法


% 演算子 (剰余) は文字列のフォーマットでも使えます。 @code{format % values} (`format' は文字列) という文字列が与えられた場合、 `format' 中の @code{%} 変換指定はゼロあるいは `values' の余りの要素に置換えられます。この操作は文字列補間として知られています。例えば:

@example
>>> import math
>>> print('πの値はだいたい %5.3f です。' % math.pi)
πの値はだいたい 3.142 です。
@end example

より詳しい情報は @ref{8db,,printf 形式の文字列書式化} にあります。

@node ファイルを読み書きする,,出力を見やすくフォーマットする,入力と出力
@anchor{tutorial/inputoutput reading-and-writing-files}@anchor{2065}@anchor{tutorial/inputoutput tut-files}@anchor{2066}
@subsection ファイルを読み書きする


@geindex 組み込み関数;open
@geindex object;ファイル

@ref{316,,open()} は @ref{13db,,file object} を返します。大抵、 @code{open(filename, mode, encoding=None)} のように2つの位置引数と1つのキーワード引数を伴って呼び出されます。

@example
>>> f = open('workfile', 'w', encoding="utf-8")
@end example

@c XXX str(f) is <io.TextIOWrapper object at 0x82e8dc4>
@c 
@c >>> print(f)
@c <open file 'workfile', mode 'w' at 80a0960>

最初の引数はファイル名の入った文字列です。二つめの引数も文字列で、ファイルをどのように使うかを示す数個の文字が入っています。 `mode' は、ファイルが読み出し専用なら @code{'r'} 、書き込み専用 (同名の既存のファイルがあれば消去されます) なら @code{'w'} とします。 @code{'a'} はファイルを追記用に開きます。ファイルに書き込まれた内容は自動的にファイルの終端に追加されます。 @code{'r+'} はファイルを読み書き両用に開きます。 `mode' 引数は省略可能で、省略された場合には @code{'r'} であると仮定します。

通常、ファイルはテキストモード (`text mode') で開かれ、特定の `エンコーディング' でエンコードされたファイルに対して文字列を読み書きします。`エンコーディング' が指定されなければ、デフォルトはプラットフォーム依存です(@ref{316,,open()} を参照してください)。UTF-8は現在の事実上の標準のため、異なるエンコーディングを指定したい場合以外は @code{encoding="utf-8"} の指定がおすすめです。モードに @code{'b'} をつけるとファイルを `binary mode' で開きます。バイナリーモードでのデータは @ref{192,,bytes} オブジェクトで読み書きします。ファイルをバイナリーモードで開くときは `エンコーディング' は指定できません。

テキストモードの読み取りでは、プラットフォーム固有の行末記号 (Unix では @code{\n} 、Windows では @code{\r\n}) をただの @code{\n} に変換するのがデフォルトの動作です。テキストモードの書き込みでは、 @code{\n} が出てくる箇所をプラットフォーム固有の行末記号に戻すのがデフォルトの動作です。この裏で行われるファイルデータの変換はテキストファイルには上手く働きますが、 @code{JPEG} ファイルや @code{EXE} ファイルのようなバイナリデータを破壊する恐れがあります。そのようなファイルを読み書きする場合には注意して、バイナリモードを使うようにしてください。

ファイルオブジェクトを扱うときに @ref{186,,with} キーワードを使うのは良い習慣です。
その利点は、処理中に例外が発生しても必ず最後にファイルをちゃんと閉じることです。
@code{with} を使うと、同じことを @ref{8f8,,try}-@ref{1b0,,finally} ブロックを使って書くよりずっと簡潔に書けます:

@example
>>> with open('workfile', encoding="utf-8") as f:
...     read_data = f.read()

>>> # ファイルが自動でクローズされたことが確認できる
>>> f.closed
True
@end example

もし @ref{186,,with} キーワードを使用しない場合は、ファイルを閉じ、このファイルのために利用されたシステムのリソースを直ちに解放するために @code{f.close()} を呼び出してください。

@cartouche
@quotation 警告 
@code{f.write()} を @code{with} キーワードや @code{f.close()} を使わずに呼び出した場合、プログラムが正常に終了した場合でも、 @code{f.write()} の実引数がディスクに完全に `書き込まれないことがあります' 。
@end quotation
@end cartouche

@c See also https://bugs.python.org/issue17852

@ref{186,,with} 文や @code{f.close()} の呼び出しによって閉じられた後にファイルオブジェクトを使おうとするとそこで処理が失敗します。:

@example
>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
@end example

@menu
* ファイルオブジェクトのメソッド:: 
* json による構造化されたデータの保存:: 

@end menu

@node ファイルオブジェクトのメソッド,json による構造化されたデータの保存,,ファイルを読み書きする
@anchor{tutorial/inputoutput methods-of-file-objects}@anchor{2067}@anchor{tutorial/inputoutput tut-filemethods}@anchor{2068}
@subsubsection ファイルオブジェクトのメソッド


この節の以降の例は、 @code{f} というファイルオブジェクトが既に生成されているものと仮定します。

ファイルの内容を読み出すには、 @code{f.read(size)} を呼び出します。このメソッドはある量のデータを読み出して、文字列 (テキストモードの場合) か bytes オブジェクト (バイナリーモードの場合) として返します。 `size' はオプションの数値引数です。 `size' が省略されたり負の数であった場合、ファイルの内容全てを読み出して返します。ただし、ファイルがマシンのメモリの二倍の大きさもある場合にはどうなるかわかりません。 `size' が負でない数ならば、最大で (テキストモードの場合) `size' 文字、(バイナリモードの場合) `size' バイトを読み出して返します。ファイルの終端にすでに達していた場合、 @code{f.read()} は空の文字列 (@code{'@w{'}}) を返します。

@example
>>> f.read()
'これがファイル全体です。\n'
>>> f.read()
'@w{'}
@end example

@code{f.readline()} はファイルから 1 行だけを読み取ります。改行文字 (@code{\n}) は読み出された文字列の終端に残ります。改行が省略されるのは、ファイルが改行で終わっていない場合の最終行のみです。これは、戻り値があいまいでないようにするためです; @code{f.readline()} が空の文字列を返したら、ファイルの終端に達したことが分かります。一方、空行は @code{'\n'}、すなわち改行 1 文字だけからなる文字列で表現されます。

@example
>>> f.readline()
'これがファイルの最初の行です。\n'
>>> f.readline()
'ファイルの2行目です。\n'
>>> f.readline()
'@w{'}
@end example

ファイルから複数行を読み取るには、ファイルオブジェクトに対してループを書く方法があります。この方法はメモリを効率的に使え、高速で、簡潔なコードになります:

@example
>>> for line in f:
...     print(line, end='@w{'})
...
これがファイルの最初の行です。
ファイルの2行目です。
@end example

ファイルのすべての行をリスト形式で読み取りたいなら、@code{list(f)} や @code{f.readlines()} を使うこともできます。

@code{f.write(string)} は、`string' の内容をファイルに書き込み、書き込まれた文字数を返します。

@example
>>> f.write('This is a test\n')
15
@end example

オブジェクトの他の型は、書き込む前に変換しなければなりません -- 文字列 (テキストモード) と bytes オブジェクト (バイナリーモード) のいずれかです:

@example
>>> value = ('the answer', 42)
>>> s = str(value)  # タプルを文字列に変換
>>> f.write(s)
18
@end example

@code{f.tell()} は、ファイルオブジェクトのファイル中における現在の位置を示す整数を返します。ファイル中の現在の位置は、バイナリモードではファイルの先頭からのバイト数で、テキストモードでは不明瞭な値で表されます。

ファイルオブジェクトの位置を変更するには、@code{f.seek(offset, whence)} を使います。ファイル位置は基準点 (reference point) にオフセット値 `offset' を足して計算されます。参照点は `whence' 引数で選びます。`whence' の値が 0 ならばファイルの 先頭から測り、1 ならば現在のファイル位置を使い、2 ならばファイルの終端を参照点として使います。`whence' は省略することができ、デフォルトの値は 0、すなわち参照点としてファイルの先頭を使います。

@example
>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # ファイル内の6番目のバイトまで移動
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # 末尾から３番目のバイトに移動
13
>>> f.read(1)
b'd'
@end example

テキストファイル (mode 文字列に @code{b} を付けなかった場合) では、ファイルの先頭からの相対位置に対するシークだけが許可されています (例外として、@code{seek(0, 2)} でファイルの末尾へのシークは可能です)。また、唯一の有効な `offset' 値は @code{f.tell()} から返された値か、0 のいずれかです。それ以外の `offset' 値は未定義の振る舞いを引き起こします。

ファイルオブジェクトには、他にも @ref{2069,,isatty()} や @ref{1528,,truncate()} といった、あまり使われないメソッドがあります。ファイルオブジェクトについての完全なガイドは、ライブラリリファレンスを参照してください。

@node json による構造化されたデータの保存,,ファイルオブジェクトのメソッド,ファイルを読み書きする
@anchor{tutorial/inputoutput saving-structured-data-with-json}@anchor{206a}@anchor{tutorial/inputoutput tut-json}@anchor{206b}
@subsubsection @code{json} による構造化されたデータの保存


@geindex module;json

文字列は簡単にファイルに読み書きできます。数値の場合には少し努力が必要です。というのも、 @ref{206c,,read()} メソッドは文字列しか返さないため、 @ref{19b,,int()} のような関数にその文字列を渡して、たとえば文字列 @code{'123'} のような文字列を、数値 123 に変換しなくてはならないからです。もっと複雑なデータ型、例えば入れ子になったリストや辞書の場合、手作業でのパースやシリアライズは困難になります。

ユーザが毎回コードを書いたりデバッグしたりして複雑なデータ型をファイルに保存するかわりに、Python では一般的なデータ交換形式である JSON (JavaScript Object Notation)@footnote{https://json.org} を使うことができます。この標準モジュール @ref{86,,json} は、Python のデータ 階層を取り、文字列表現に変換します。この処理は `シリアライズ (serializing)' と呼ばれます。文字列表現からデータを再構築することは、`デシリアライズ (deserializing)' と呼ばれます。シリアライズされてからデシリアライズされるまでの間に、オブジェクトの文字列表現はファイルやデータの形で保存したり、ネットワークを通じて離れたマシンに送ったりすることができます。

@cartouche
@quotation 注釈 
JSON 形式は現代的なアプリケーションでデータをやりとりする際によく使われます。多くのプログラマーが既に JSON に詳しいため、JSON はデータの相互交換をする場合の良い選択肢です。
@end quotation
@end cartouche

オブジェクト @code{x} があり、その JSON 形式の文字列表現を見るには、単純な1行のコードを書くだけです:

@example
>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'
@end example

@ref{f41,,dumps()} に似た関数に、@ref{f40,,dump()} があり、こちらは単純にオブジェクトを @ref{206d,,text file} にシリアライズします。@code{f} が書き込み用に開かれた @ref{206d,,text file} だとすると、次のように書くことができます:

@example
json.dump(x, f)
@end example

逆にデシリアライズするには、@code{f} が読み込み用に開かれた @ref{206e,,binary file} か @ref{206d,,text file} だとすると、次のようになります:

@example
x = json.load(f)
@end example

@cartouche
@quotation 注釈 
JSONファイルは必ずUTF-8でエンコードします。JSONファイルを @ref{206d,,text file} として読み込み、書き込みで開くときには、 @code{encoding="utf-8"} を指定します。
@end quotation
@end cartouche

このような単純なシリアライズをする手法は、リストや辞書を扱うことはできますが、任意のクラス・インスタンスを JSON にシリアライズするにはもう少し努力しなくてはなりません。@ref{86,,json} モジュールのリファレンスにこれについての解説があります。


@subsubheading 参考


@ref{ab,,pickle} - pickle モジュール

@ref{206b,,JSON} とは対照的に、 `pickle' は任意の複雑な Python オブジェクトをシリアライズ可能なプロトコルです。しかし、Python に特有のプロトコルで、他の言語で記述されたアプリケーションと通信するのには使えません。さらに、デフォルトでは安全でなく、信頼できない送信元から送られてきた、スキルのある攻撃者によって生成された pickle データをデシリアライズすると、攻撃者により任意のコードが実行されてしまいます。


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node エラーと例外,クラス,入力と出力,Python チュートリアル
@anchor{tutorial/errors doc}@anchor{206f}@anchor{tutorial/errors errors-and-exceptions}@anchor{2070}@anchor{tutorial/errors translation-repo}@anchor{2071}@anchor{tutorial/errors tut-errors}@anchor{2072}
@section エラーと例外


これまでエラーメッセージについては簡単に触れるだけでしたが、チュートリアル中の例を自分で試していたら、実際にいくつかのエラーメッセージを見ていることでしょう。エラーには (少なくとも) 二つのはっきり異なる種類があります。それは `構文エラー (syntax error)' と `例外 (exception)' です。

@menu
* 構文エラー:: 
* 例外:: 
* 例外を処理する:: 
* 例外を送出する:: 
* 例外の連鎖:: 
* ユーザー定義例外:: 
* クリーンアップ動作を定義する:: 
* 定義済みクリーンアップ処理:: 
* 複数の関連しない例外の送出と処理:: 
* ノートによって例外を充実させる:: 

@end menu

@node 構文エラー,例外,,エラーと例外
@anchor{tutorial/errors syntax-errors}@anchor{2073}@anchor{tutorial/errors tut-syntaxerrors}@anchor{2074}
@subsection 構文エラー


構文エラーは構文解析エラー (parsing error) としても知られており、Python を勉強している間に最もよく遭遇する問題の一つでしょう:

@example
>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
               ^^^^^
SyntaxError: invalid syntax
@end example

パーサが構文解析エラーと判断した行が表示されるとともに、エラーが検出された部分に矢印 (^) が表示されます。ただし、この部分が本当に修正すべき箇所とは限らないので注意してください。上記の例では、エラーは関数 @ref{1177,,print()} のところで検出されており、これはその前にコロン (@code{':'}) が抜けているためです。

ファイルに書かれたコードの場合、ファイル名 (上の例では @code{<stdin>}) と行番号が表示されるので、どこを見ればよいかが分かるようになっています。

@node 例外,例外を処理する,構文エラー,エラーと例外
@anchor{tutorial/errors exceptions}@anchor{2075}@anchor{tutorial/errors tut-exceptions}@anchor{2076}
@subsection 例外


たとえ文や式が構文的に正しくても、実行しようとしたときにエラーが発生するかもしれません。実行中に検出されたエラーは `例外 (exception)' と呼ばれ、常に致命的とは限りません。これから、Python プログラムで例外をどのように扱うかを学んでいきます。ほとんどの例外はプログラムで処理されず、以下に示されるようなメッセージになります:

@example
>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    10 * (1/0)
          ~^~
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    4 + spam*3
        ^^^^
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    '2' + 2
    ~~~~^~~
TypeError: can only concatenate str (not "int") to str
@end example

エラーメッセージの最終行は何が起こったかを示しています。例外は様々な型 (type) で起こり、その型がエラーメッセージの一部として出力されます。上の例での型は @ref{b3f,,ZeroDivisionError}, @ref{452,,NameError}, @ref{198,,TypeError} です。例外型として出力される文字列は、発生した例外の組み込み名です。これは全ての組み込み例外について成り立ちますが、ユーザ定義の例外では (成り立つようにするのは有意義な慣習ですが) 必ずしも成り立ちません。標準例外の名前は組み込みの識別子です (予約語ではありません)。

残りの行は例外の詳細で、その例外の型と何が起きたかに依存します。

エラーメッセージの先頭部分では、例外が発生した実行コンテキスト (context) を、スタックのトレースバック (stack traceback) の形式で示しています。一般には、この部分にはソースコード行をリストしたトレースバックが表示されます。しかし、標準入力から読み取られたコードは表示されません。

@ref{1c27,,組み込み例外} には、組み込み例外とその意味がリストされています。

@node 例外を処理する,例外を送出する,例外,エラーと例外
@anchor{tutorial/errors handling-exceptions}@anchor{2077}@anchor{tutorial/errors tut-handling}@anchor{1ff9}
@subsection 例外を処理する


例外を選別して処理するようなプログラムを書くことができます。以下の例を見てください。この例では、有効な文字列が入力されるまでユーザに入力を促しますが、ユーザがプログラムに (@code{Control}-@code{C} か、またはオペレーティングシステムがサポートしている何らかのキーを使って) 割り込みをかけてプログラムを中断させることができるようにしています。ユーザが生成した割り込みは、 @ref{bc5,,KeyboardInterrupt} 例外が送出されることで通知されるということに注意してください。

@example
>>> while True:
...     try:
...         x = int(input("数字を入力してください: "))
...         break
...     except ValueError:
...         print("おっと!それは数字ではないようです。もう一度入力してください...")
...
@end example

@ref{8f8,,try} 文は下記のように動作します。


@itemize *

@item 
まず、 `try 節 (try clause)' (キーワード @ref{8f8,,try} と @ref{1ab,,except} の間の文) が実行されます。

@item 
何も例外が発生しなければ、 `except 節' をスキップして @ref{8f8,,try} 文の実行を終えます。

@item 
@ref{8f8,,try} 節内の実行中に例外が発生すると、その節の残りは飛ばされます。次に、例外型が @ref{1ab,,except} キーワードの後に指定されている例外に一致する場合、except 節が実行された後、 try/except ブロックの後ろへ実行が継続されます。

@item 
もしも `except 節' で指定された例外と一致しない例外が発生すると、その例外は @ref{8f8,,try} 文の外側に渡されます。例外に対するハンドラ (handler、処理部) がどこにもなければ、 `処理されない例外 (unhandled exception)' となり、エラーメッセージを出して実行を停止します。
@end itemize

一つの @ref{8f8,,try} 文には複数の `except 節' が付けられ、別々の例外に対するハンドラを指定できます。
多くとも一つのハンドラしか実行されません。
ハンドラは対応する `try 節' 内で発生した例外だけを処理し、同じ @code{try} 節内の別の例外ハンドラで起きた例外は処理しません。
`except 節' では丸括弧で囲ったタプルという形で複数の例外を指定できます。例えば次のようにします:

@example
... except (RuntimeError, TypeError, NameError):
...     pass
@end example

@ref{1ab,,except} 節 内のクラスは、そのクラスや派生クラスのインスタンスである例外とマッチします（その逆はありません --- 派生クラスが書かれた `except節' は、その基底クラスのインスタンスにはマッチしません）。例えば、次のコードは B, C, D の順に出力されます:

@example
class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")
@end example

`except 節' が逆に並んでいた場合 (@code{except B} が最初にくる場合)、 B, B, B と出力されるはずだったことに注意してください --- 最初に一致した `except 節' が駆動されるのです。

例外が発生するとき、例外は関連付けられた値を持つことができます。この値は例外の `引数 (arguments)' とも呼ばれます。引数の有無および引数の型は、例外の型に依存します。

except節は例外名の後に変数を指定できます。その変数は例外インスタンスに紐付けられ、一般的には引数を保持する @code{args} 属性を持ちます。利便性のため、組み込み例外型には @ref{830,,__str__()} が定義されており、明示的に @code{.args} を参照せずとも すべての引数を表示できます。

@example
>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # 例外の型
...     print(inst.args)     # 引数は .args に格納される
...     print(inst)          # __str__ は args を直接出力しますが、
...                          # 例外のサブクラスで上書きされる場合もあります
...     x, y = inst.args     # args をアンパックする
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
@end example

例外の @ref{830,,__str__()} 出力は、処理されない例外のメッセージ末尾 ('詳細') として表示されます。

@ref{7d6,,BaseException} はすべての例外に共通する基底クラスです。そのサブクラスの一つである @ref{bcd,,Exception} は、致命的でない例外すべての基底クラスです。 @ref{bcd,,Exception} のサブクラスではない例外は、一般的にプログラムが終了することを示すために使われているため処理されません。例えば、@ref{277,,sys.exit()} によって送出される @ref{f3c,,SystemExit} や、ユーザーがプログラムを中断させたいときに送出される @ref{bc5,,KeyboardInterrupt} があります。

@ref{bcd,,Exception} はほぼすべての例外を捕捉するワイルドカードとして使えます。しかし良い例外処理の手法とは、処理対象の例外の型をできる限り詳細に書き、予期しない例外はそのまま伝わるようにすることです。

@ref{bcd,,Exception} に対する最も一般的な例外処理のパターンでは、例外を表示あるいはログ出力してから再度送出します(呼び出し側でも例外を処理できるようにします):

@example
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OSエラー:", err)
except ValueError:
    print("データを整数に変換できません。")
except Exception as err:
    print(f"予期せぬエラー @{err=@}, @{type(err)=@}")
    raise
@end example

@ref{8f8,,try} ... @ref{1ab,,except} 文には、オプションで `else 節 (else clause)' を設けることができます。 @ref{17c,,else} 節を設ける場合、全ての @ref{1ab,,except} 節よりも後ろに置かなければなりません。 @ref{17c,,else} 節は `try 節' で全く例外が送出されなかったときに実行されるコードを書くのに役立ちます。例えば次のようにします:

@example
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print(arg, 'が開けません')
    else:
        print(arg, 'は', len(f.readlines()), '行です')
        f.close()
@end example

追加のコードを付け加えるのは @ref{8f8,,try} 節よりも @code{else} 節の方がよいでしょう。
なぜなら、そうすることで @code{try} ... @code{except} 文で保護されたコードから送出されたもの以外の例外を過って捕捉してしまうという事態を避けられるからです。

例外ハンドラは、`try 節' の直接内側で発生した例外を処理するだけではなくその `try 節' から (たとえ間接的にでも) 呼び出された関数の内部で発生した例外も処理します。例えば:

@example
>>> def this_fails():
...     x = 1/0
...
>>> try:
...     this_fails()
... except ZeroDivisionError as err:
...     print('実行時エラーを処理:', err)
...
実行時エラーを処理: division by zero
@end example

@node 例外を送出する,例外の連鎖,例外を処理する,エラーと例外
@anchor{tutorial/errors raising-exceptions}@anchor{2078}@anchor{tutorial/errors tut-raising}@anchor{2079}
@subsection 例外を送出する


@ref{803,,raise} 文を使って、特定の例外を発生させることができます。例えば:

@example
>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise NameError('HiThere')
NameError: HiThere
@end example

@ref{803,,raise} の唯一の引数は送出される例外を指し示します。
これは例外インスタンスか例外クラス(@ref{7d6,,BaseException} を継承したクラス、たとえば @ref{bcd,,Exception} やそのサブクラス)でなければなりません。
例外クラスが渡された場合は、引数無しのコンストラクタが呼び出され、暗黙的にインスタンス化されます:

@example
raise ValueError  # 'raise ValueError()' の省略記法
@end example

例外が発生したかどうかを判定したいだけで、その例外を処理するつもりがなければ、単純な形式の @ref{803,,raise} 文を使って例外を再送出させることができます:

@example
>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print('例外が通り過ぎました!')
...     raise
...
例外が通り過ぎました!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    raise NameError('HiThere')
NameError: HiThere
@end example

@node 例外の連鎖,ユーザー定義例外,例外を送出する,エラーと例外
@anchor{tutorial/errors exception-chaining}@anchor{207a}@anchor{tutorial/errors tut-exception-chaining}@anchor{207b}
@subsection 例外の連鎖


@ref{1ab,,except} 節の中で未処理の例外が発生した場合、その未処理の例外は処理された例外のエラーメッセージに含まれます:

@example
>>> try:
...     open("database.sqlite")
... except OSError:
...     raise RuntimeError("unable to handle error")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    open("database.sqlite")
    ~~~~^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
    raise RuntimeError("unable to handle error")
RuntimeError: unable to handle error
@end example

ある例外が他の例外から直接影響されていることを示すために、@ref{803,,raise} 文にオプションの @ref{803,,from} 句を指定します:

@example
# exc must be exception instance or None.
raise RuntimeError from exc
@end example

これは例外を変換するときに便利です。例えば:

@example
>>> def func():
...     raise ConnectionError
...
>>> try:
...     func()
... except ConnectionError as exc:
...     raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    func()
    ~~~~^^
  File "<stdin>", line 2, in func
ConnectionError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
    raise RuntimeError('Failed to open database') from exc
RuntimeError: Failed to open database
@end example

また、自動的な例外の連鎖を無効にするには @code{from None} を指定します。

@example
>>> try:
...     open('database.sqlite')
... except OSError:
...     raise RuntimeError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
    raise RuntimeError from None
RuntimeError
@end example

例外の連鎖の仕組みに関して、詳しくは @ref{1c27,,組み込み例外} を参照してください。

@node ユーザー定義例外,クリーンアップ動作を定義する,例外の連鎖,エラーと例外
@anchor{tutorial/errors tut-userexceptions}@anchor{207c}@anchor{tutorial/errors user-defined-exceptions}@anchor{207d}
@subsection ユーザー定義例外


プログラム上で新しい例外クラスを作成することで、独自の例外を指定することができます (Python のクラスについては @ref{2001,,クラス} 参照)。例外は、典型的に @ref{bcd,,Exception} クラスから、直接または間接的に派生したものです。

例外クラスでは、普通のクラスができることなら何でも定義することができますが、通常は単純なものにしておきます。大抵は、いくつかの属性だけを提供し、例外が発生したときにハンドラがエラーに関する情報を取り出せるようにする程度にとどめます。

ほとんどの例外は、標準の例外の名前付けと同様に、"Error" で終わる名前で定義されています。

多くの標準モジュールでは、モジュールで定義されている関数内で発生する可能性のあるエラーを報告させるために、独自の例外を定義しています。

@node クリーンアップ動作を定義する,定義済みクリーンアップ処理,ユーザー定義例外,エラーと例外
@anchor{tutorial/errors defining-clean-up-actions}@anchor{207e}@anchor{tutorial/errors tut-cleanup}@anchor{207f}
@subsection クリーンアップ動作を定義する


@ref{8f8,,try} 文にはもう一つオプションの節があります。この節はクリーンアップ動作を定義するためのもので、どんな状況でも必ず実行されます。例を示します:

@example
>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    raise KeyboardInterrupt
KeyboardInterrupt
@end example

もし @ref{1b0,,finally} 節がある場合、 @ref{8f8,,try} 文が終わる前の最後の処理を、 @code{finally} 節が実行します。 @code{try} 文が例外を発生させるか否かに関わらず、 @code{finally} 節は実行されます。以下では、例外が発生するという更に複雑なケースを議論します:


@itemize *

@item 
もし @code{try} 文の実行中に例外が発生したら、その例外は @ref{1ab,,except} 節によって処理されるでしょう。もしその例外が @code{except} 節によって処理されなければ、 @code{finally} 節が実行された後に、その例外が再送出されます。

@item 
@code{except} 節または @code{else} 節の実行中に例外が発生することがあり得ます。その場合も、 @code{finally} 節が実行された後に例外が再送出されます。

@item 
If the @code{finally} clause executes a @ref{17f,,break},
@ref{180,,continue} or @ref{1af,,return} statement, exceptions are not
re-raised. This can be confusing and is therefore discouraged. From
version 3.14 the compiler emits a @ref{1ae,,SyntaxWarning} for it
(see 
@geindex Python Enhancement Proposals; PEP 765
PEP 765@footnote{https://peps.python.org/pep-0765/}).

@item 
もし @code{try} 文が @ref{17f,,break} 文、 @ref{180,,continue} 文または @ref{1af,,return} 文のいずれかに達すると、その @code{break} 文、 @code{continue} 文または @code{return} 文の実行の直前に @code{finally} 節が実行されます。

@item 
If a @code{finally} clause includes a @code{return}
statement, the returned value will be the one from the
@code{finally} clause's @code{return} statement, not the
value from the @code{try} clause's @code{return}
statement. This can be confusing and is therefore discouraged. From
version 3.14 the compiler emits a @ref{1ae,,SyntaxWarning} for it
(see 
@geindex Python Enhancement Proposals; PEP 765
PEP 765@footnote{https://peps.python.org/pep-0765/}).
@end itemize

例えば:

@example
>>> def bool_return():
...     try:
...         return True
...     finally:
...         return False
...
>>> bool_return()
False
@end example

より複雑な例:

@example
>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print("division by zero!")
...     else:
...         print("result is", result)
...     finally:
...         print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    divide("2", "1")
    ~~~~~~^^^^^^^^^^
  File "<stdin>", line 3, in divide
    result = x / y
             ~~^~~
TypeError: unsupported operand type(s) for /: 'str' and 'str'
@end example

見てわかるとおり、 @ref{1b0,,finally} 節はどの場合にも実行されています。
文字列で割り算をすることで発生した @ref{198,,TypeError} は @ref{1ab,,except} 節で処理されていないので、 @code{finally} 節実行後に再度送出されています。

実世界のアプリケーションでは、 @ref{1b0,,finally} 節は(ファイルやネットワーク接続などの)外部リソースを、利用が成功したかどうかにかかわらず解放するために便利です。

@node 定義済みクリーンアップ処理,複数の関連しない例外の送出と処理,クリーンアップ動作を定義する,エラーと例外
@anchor{tutorial/errors predefined-clean-up-actions}@anchor{2080}@anchor{tutorial/errors tut-cleanup-with}@anchor{2081}
@subsection 定義済みクリーンアップ処理


オブジェクトのなかには、その利用の成否にかかわらず、不要になった際に実行される標準的なクリーンアップ処理が定義されているものがあります。以下の、ファイルをオープンして内容を画面に表示する例をみてください。

@example
for line in open("myfile.txt"):
    print(line, end="")
@end example

このコードの問題点は、コードの実行が終わった後に不定の時間ファイルを開いたままでいることです。これは単純なスクリプトでは問題になりませんが、大きなアプリケーションでは問題になりえます。 @ref{186,,with} 文はファイルのようなオブジェクトが常に、即座に正しくクリーンアップされることを保証します。

@example
with open("myfile.txt") as f:
    for line in f:
        print(line, end="")
@end example

この文が実行されたあとで、たとえ行の処理中に問題があったとしても、ファイル `f' は常に close されます。ファイルなどの、定義済みクリーンアップ処理を持つオブジェクトについては、それぞれのドキュメントで示されます。

@node 複数の関連しない例外の送出と処理,ノートによって例外を充実させる,定義済みクリーンアップ処理,エラーと例外
@anchor{tutorial/errors raising-and-handling-multiple-unrelated-exceptions}@anchor{2082}@anchor{tutorial/errors tut-exception-groups}@anchor{2083}
@subsection 複数の関連しない例外の送出と処理


いくつか発生した例外の報告が必要な状況があります。並列処理のフレームワークでは、複数のタスクが平行して失敗することがたびたびあります。他にも最初の例外を送出するよりも、処理を継続して複数の例外を集約した方が望ましいユースケースもあります。

組み込みの @ref{4d2,,ExceptionGroup} は例外インスタンスのリストをまとめ、同時に送出できるようにします。ExceptionGroupも例外なので、他の例外と同じように捕捉できます。:

@example
>>> def f():
...     excs = [OSError('error 1'), SystemError('error 2')]
...     raise ExceptionGroup('there were problems', excs)
...
>>> f()
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 1, in <module>
  |     f()
  |     ~^^
  |   File "<stdin>", line 3, in f
  |     raise ExceptionGroup('there were problems', excs)
  | ExceptionGroup: there were problems (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | OSError: error 1
    +---------------- 2 ----------------
    | SystemError: error 2
    +------------------------------------
>>> try:
...     f()
... except Exception as e:
...     print(f'caught @{type(e)@}: e')
...
caught <class 'ExceptionGroup'>: e
>>>
@end example

@code{except} の代わりに @code{except*} を使用すると、グループの中にある特定の型に一致した例外だけを選択して処理できます。以下の例では、ネストした例外グループに対して各 @code{except*} 節で特定の型の例外を取り出し、それ以外の例外は他の節に伝えられ、最終的に例外が送出されます。:

@example
>>> def f():
...     raise ExceptionGroup(
...         "group1",
...         [
...             OSError(1),
...             SystemError(2),
...             ExceptionGroup(
...                 "group2",
...                 [
...                     OSError(3),
...                     RecursionError(4)
...                 ]
...             )
...         ]
...     )
...
>>> try:
...     f()
... except* OSError as e:
...     print("There were OSErrors")
... except* SystemError as e:
...     print("There were SystemErrors")
...
There were OSErrors
There were SystemErrors
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 2, in <module>
  |     f()
  |     ~^^
  |   File "<stdin>", line 2, in f
  |     raise ExceptionGroup(
  |     ...<12 lines>...
  |     )
  | ExceptionGroup: group1 (1 sub-exception)
  +-+---------------- 1 ----------------
    | ExceptionGroup: group2 (1 sub-exception)
    +-+---------------- 1 ----------------
      | RecursionError: 4
      +------------------------------------
>>>
@end example

例外グループの中に含める例外は、型ではなくインスタンスである必要があることに注意してください。これは一般的に、以下のパターンようにプログラムで送出された複数の例外を捕捉することが多いためです。:

@example
>>> excs = []
... for test in tests:
...     try:
...         test.run()
...     except Exception as e:
...         excs.append(e)
...
>>> if excs:
...    raise ExceptionGroup("Test Failures", excs)
...
@end example

@node ノートによって例外を充実させる,,複数の関連しない例外の送出と処理,エラーと例外
@anchor{tutorial/errors enriching-exceptions-with-notes}@anchor{2084}@anchor{tutorial/errors tut-exception-notes}@anchor{2085}
@subsection ノートによって例外を充実させる


例外を送出するために生成するときに、通常は発生したエラーを説明する情報で初期化されます。例外を受け取ったあとに情報を追加すると便利な場合があります。この目的のために、例外は @code{add_note(note)} メソッドを持ちます。このメソッドは文字列を受け取り、例外のノートのリストに追加します。標準のトレースバックでは例外の後に、全てのノートが追加した順番に出力されます。:

@example
>>> try:
...     raise TypeError('bad type')
... except Exception as e:
...     e.add_note('Add some information')
...     e.add_note('Add some more information')
...     raise
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    raise TypeError('bad type')
TypeError: bad type
Add some information
Add some more information
>>>
@end example

たとえば、複数の例外を1つの例外グループにまとめるときに、各エラーのコンテキスト情報を追加したい場合があります。以下のグループ内の各例外が持つノートは、エラーがいつ発生したかを示しています。:

@example
>>> def f():
...     raise OSError('operation failed')
...
>>> excs = []
>>> for i in range(3):
...     try:
...         f()
...     except Exception as e:
...         e.add_note(f'Happened in Iteration @{i+1@}')
...         excs.append(e)
...
>>> raise ExceptionGroup('We have some problems', excs)
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 1, in <module>
  |     raise ExceptionGroup('We have some problems', excs)
  | ExceptionGroup: We have some problems (3 sub-exceptions)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "<stdin>", line 3, in <module>
    |     f()
    |     ~^^
    |   File "<stdin>", line 2, in f
    |     raise OSError('operation failed')
    | OSError: operation failed
    | Happened in Iteration 1
    +---------------- 2 ----------------
    | Traceback (most recent call last):
    |   File "<stdin>", line 3, in <module>
    |     f()
    |     ~^^
    |   File "<stdin>", line 2, in f
    |     raise OSError('operation failed')
    | OSError: operation failed
    | Happened in Iteration 2
    +---------------- 3 ----------------
    | Traceback (most recent call last):
    |   File "<stdin>", line 3, in <module>
    |     f()
    |     ~^^
    |   File "<stdin>", line 2, in f
    |     raise OSError('operation failed')
    | OSError: operation failed
    | Happened in Iteration 3
    +------------------------------------
>>>
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node クラス,標準ライブラリミニツアー,エラーと例外,Python チュートリアル
@anchor{tutorial/classes doc}@anchor{2086}@anchor{tutorial/classes classes}@anchor{2087}@anchor{tutorial/classes translation-repo}@anchor{2088}@anchor{tutorial/classes tut-classes}@anchor{2001}
@section クラス


クラスはデータと機能を組み合わせる方法を提供します。
新規にクラスを作成することで、新しいオブジェクトの `型' を作成し、その型を持つ新しい `インスタンス' が作れます。
クラスのそれぞれのインスタンスは自身の状態を保持する属性を持てます。
クラスのインスタンスは、その状態を変更するための (そのクラスが定義する) メソッドも持てます。

Python は、他のプログラミング言語と比較して、最小限の構文と意味付けを使ってクラスを言語に追加しています。Python のクラスは、C++ と Modula-3 のクラスメカニズムを混ぜたものです。Python のクラス機構はオブジェクト指向プログラミングの標準的な機能を全て提供しています。クラスの継承メカニズムは、複数の基底クラスを持つことができ、派生クラスで基底クラスの任意のメソッドをオーバライドすることができます。メソッドでは、基底クラスのメソッドを同じ名前で呼び出すことができます。オブジェクトには任意の種類と数のデータを格納することができます。モジュールと同じく、クラス機構も Python の動的な性質に従うように設計されています。クラスは実行時に生成され、生成後に変更することができます。

C++ の用語で言えば、通常のクラスメンバ (データメンバも含む) は (@ref{2089,,プライベート変数} に書かれている例外を除いて) `public' であり、メンバ関数はすべて `仮想関数(virtual)' です。 Modula-3 にあるような、オブジェクトのメンバをメソッドから参照するための短縮した記法は使えません: メソッド関数の宣言では、オブジェクト自体を表す第一引数を明示しなければなりません。第一引数のオブジェクトはメソッド呼び出しの際に暗黙の引数として渡されます。 Smalltalk に似て、クラスはそれ自体がオブジェクトです。そのため、 import や名前変更といった操作が可能です。 C++ や Modula-3 と違って、ユーザーは組込み型を基底クラスにして拡張を行えます。また、C++ とは同じで Modula-3 とは違う点として、特別な構文を伴うほとんどの組み込み演算子 (算術演算子 (arithmetic operator) や添字表記) はクラスインスタンスで使うために再定義できます。

(クラスに関して普遍的な用語定義がないので、 Smalltalk と C++ の用語を場合に応じて使っていくことにします。 C++ よりも Modula-3 の方がオブジェクト指向の意味論が Python に近いので、 Modula-3 の用語を使いたいのですが、ほとんどの読者は Modula-3 についてしらないでしょうから。)

@menu
* 名前とオブジェクトについて:: 
* Python のスコープと名前空間:: 
* クラス初見:: 
* いろいろな注意点:: 
* 継承:: 
* プライベート変数:: 
* 残りのはしばし:: 
* イテレータ (iterator): イテレータ iterator. 
* ジェネレータ (generator): ジェネレータ generator. 
* ジェネレータ式:: 

@end menu

@node 名前とオブジェクトについて,Python のスコープと名前空間,,クラス
@anchor{tutorial/classes a-word-about-names-and-objects}@anchor{208a}@anchor{tutorial/classes tut-object}@anchor{208b}
@subsection 名前とオブジェクトについて


オブジェクトには個体性があり、同一のオブジェクトに(複数のスコープから) 複数の名前を割り当てることができます。この機能は他の言語では別名づけ(alias) として知られています。 Python を一見しただけでは、別名づけの重要性は分からないことが多く、変更不能な基本型 (数値、文字列、タプル)を扱うときには無視して差し支えありません。しかしながら、別名付けは、リストや辞書や他の多くの型など、変更可能な型を扱う Python コード上で驚くべき効果があります。別名付けはいくつかの点でポインタのように振舞い、このことは通常はプログラムに利するように使われます。例えば、オブジェクトの受け渡しは、実装上はポインタが渡されるだけなのでコストの低い操作になります。また、関数があるオブジェクトを引数として渡されたとき、関数の呼び出し側からオブジェクトに対する変更を見ることができます --- これにより、 Pascal にあるような二つの引数渡し機構をもつ必要をなくしています。

@node Python のスコープと名前空間,クラス初見,名前とオブジェクトについて,クラス
@anchor{tutorial/classes python-scopes-and-namespaces}@anchor{208c}@anchor{tutorial/classes tut-scopes}@anchor{2040}
@subsection Python のスコープと名前空間


クラスを紹介する前に、Python のスコープのルールについてあることを話しておかなければなりません。クラス定義は巧みなトリックを名前空間に施すので、何が起こっているのかを完全に理解するには、スコープと名前空間がどのように動作するかを理解する必要があります。ちなみに、この問題に関する知識は全ての Python プログラマにとって有用です。

まず定義から始めましょう。

`名前空間 (namespace)' とは、名前からオブジェクトへの対応付け (mapping) です。ほとんどの名前空間は、現状では Python の辞書として実装されていますが、そのことは通常は (パフォーマンス以外では) 目立つことはないし、将来は変更されるかもしれません。名前空間の例には、組込み名の集合 (@ref{208d,,abs()} 等の関数や組込み例外名)、モジュール内のグローバルな名前、関数を呼び出したときのローカルな名前があります。オブジェクトの属性からなる集合もまた、ある意味では名前空間です。名前空間について知っておくべき重要なことは、異なった名前空間にある名前の間には全く関係がないということです。例えば、二つの別々のモジュールの両方で関数 @code{maximize} という関数を定義することができ、定義自体は混同されることはありません --- モジュールのユーザは名前の前にモジュール名をつけなければなりません。

ところで、 `属性' という言葉は、ドットに続く名前すべてに対して使っています --- 例えば式 @code{z.real} で、 @code{real} はオブジェクト @code{z} の属性です。厳密にいえば、モジュール内の名前に対する参照は属性の参照です。式 @code{modname.funcname} では、 @code{modname} はあるモジュールオブジェクトで、 @code{funcname} はその属性です。この場合には、モジュールの属性とモジュールの中で定義されているグローバル名の間には、直接的な対応付けがされます。これらの名前は同じ名前空間を共有しているのです！ @footnote{
例外が一つあります。モジュールオブジェクトには、秘密の読取り専用の属性 @ref{77d,,__dict__} があり、モジュールの名前空間を実装するために使われている辞書を返します; @code{__dict__} という名前は属性ですが、グローバルな名前ではありません。この属性を利用すると名前空間の実装に対する抽象化を侵すことになるので、プログラムを検死するデバッガのような用途に限るべきです。
}

属性は読取り専用にも、書込み可能にもできます。書込み可能であれば、属性に代入することができます。モジュール属性は書込み可能で、 @code{modname.the_answer = 42} と書くことができます。書込み可能な属性は、 @ref{1b1f,,del} 文で削除することもできます。例えば、 @code{del modname.the_answer} は、 @code{modname} で指定されたオブジェクトから属性 @code{the_answer} を除去します。

名前空間は様々な時点で作成され、その寿命も様々です。組み込みの名前が入った名前空間は Python インタプリタが起動するときに作成され、決して削除されることはありません。モジュールのグローバルな名前空間は、モジュール定義が読み込まれたときに作成されます。通常、モジュールの名前空間は、インタプリタが終了するまで残ります。インタプリタのトップレベルで実行された文は、スクリプトファイルから読み出されたものでも対話的に読み出されたものでも、 @ref{1,,__main__} という名前のモジュールの一部分であるとみなされるので、独自の名前空間を持つことになります。 (組み込みの名前は実際にはモジュール内に存在します。そのモジュールは @ref{13,,builtins} と呼ばれています。)

関数のローカルな名前空間は、関数が呼び出されたときに作成され、関数から戻ったときや、関数内で例外が送出され、かつ関数内で処理されなかった場合に削除されます。 (実際には、忘れられる、と言ったほうが起きていることをよく表しています。) もちろん、再帰呼出しのときには、各々の呼び出しで各自のローカルな名前空間があります。

`スコープ (scope)' とは、ある名前空間が直接アクセスできるような、 Python プログラムのテキスト上の領域です。 "直接アクセス可能" とは、修飾なしに (訳注: @code{spam.egg} ではなく単に @code{egg} のように) 名前を参照した際に、その名前空間から名前を見つけようと試みることを意味します。

スコープは静的に決定されますが、動的に使用されます。実行中はいつでも、直接名前空間にアクセス可能な、3つまたは4つの入れ子になったスコープがあります:


@itemize *

@item 
最初に探される、最も内側のスコープは、ローカルな名前を持っています。

@item 
外側の(enclosing)関数のスコープは、近いほうから順に探され、ローカルでもグローバルでもない名前を持っています。

@item 
次のスコープは、現在のモジュールのグローバルな名前を持っています。

@item 
一番外側の(最後に検索される)スコープはビルトイン名を持っています。
@end itemize

名前が global と宣言されている場合、その名前に対する参照や代入は全て、モジュールのグローバルな名前の入った最後から2番目のスコープに対して直接行われます。最内スコープの外側にある変数に再束縛するには、 @ref{14bf,,nonlocal} 文が使えます。nonlocal と宣言されなかった変数は、全て読み出し専用となります (そのような変数に対する書き込みは、単に `新しい' ローカル変数をもっとも内側のスコープで作成し、外部のスコープの値は変化しません)。

通常、ローカルスコープは (プログラムテキスト上の) 現在の関数のローカルな名前を参照します。関数の外側では、ローカルスコープはグローバルな名前空間と同じ名前空間、モジュールの名前空間を参照します。クラス定義では、ローカルスコープの中にもう一つ名前空間が置かれます。

スコープはテキスト上で決定されていると理解することが重要です。モジュール内で定義される関数のグローバルなスコープは、関数がどこから呼び出されても、どんな別名をつけて呼び出されても、そのモジュールの名前空間になります。反対に、実際の名前の検索は実行時に動的に行われます --- とはいえ、言語の定義は、"コンパイル" 時の静的な名前解決の方向に進化しているので、動的な名前解決に頼ってはいけません！ (事実、ローカルな変数は既に静的に決定されています。)

Python の特徴として、@ref{4ac,,global} や @ref{14bf,,nonlocal} 文が有効でない場合は、名前に対する参照は常に最も内側のスコープに対して有効になります。
代入はデータをコピーしません。オブジェクトを名前に束縛するだけです。削除も同様で、@code{del x} は、ローカルスコープの名前空間から  @code{x} に対する拘束を取り除きます。
つまるところ、新しい名前を与えるようなすべての操作は、ローカルスコープを使って行われます。 @ref{7f8,,import} 文、関数の定義は、モジュールや関数名をローカルスコープの名前に拘束します。

@ref{4ac,,global} 文を使うと、特定の変数がグローバルスコープに存在し、そこで再束縛されることを指示できます。 @ref{14bf,,nonlocal} 文は、特定の変数が外側のスコープに存在し、そこで再束縛されることを指示します。

@menu
* スコープと名前空間の例:: 

@end menu

@node スコープと名前空間の例,,,Python のスコープと名前空間
@anchor{tutorial/classes scopes-and-namespaces-example}@anchor{208e}@anchor{tutorial/classes tut-scopeexample}@anchor{208f}
@subsubsection スコープと名前空間の例


異なるスコープと名前空間がどのように参照されるか、また @ref{4ac,,global} および @ref{14bf,,nonlocal} が変数の束縛にどう影響するか、この例で実演します:

@example
def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
@end example

このコード例の出力は:

@example
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
@end example

このとおり、(デフォルトの) `ローカルな' 代入は `scope_test' 上の `spam' への束縛を変更しませんでした。 @ref{14bf,,nonlocal} 代入は `scope_test' 上の `spam' への束縛を変更し、 @ref{4ac,,global} 代入はモジュールレベルの束縛を変更しました。

またここから、 @ref{4ac,,global} 代入の前には `spam' に何も束縛されていなかったことも分かります。

@node クラス初見,いろいろな注意点,Python のスコープと名前空間,クラス
@anchor{tutorial/classes a-first-look-at-classes}@anchor{2090}@anchor{tutorial/classes tut-firstclasses}@anchor{201c}
@subsection クラス初見


クラスでは、新しい構文を少しと、三つの新たなオブジェクト型、そして新たな意味付けをいくつか取り入れています。

@menu
* クラス定義の構文:: 
* クラスオブジェクト:: 
* インスタンスオブジェクト:: 
* メソッドオブジェクト:: 
* クラスとインスタンス変数:: 

@end menu

@node クラス定義の構文,クラスオブジェクト,,クラス初見
@anchor{tutorial/classes class-definition-syntax}@anchor{2091}@anchor{tutorial/classes tut-classdefinition}@anchor{2092}
@subsubsection クラス定義の構文


クラス定義の最も単純な形式は、次のようになります:

@example
class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>
@end example

関数定義 (@ref{1673,,def} 文) と同様、クラス定義が効果をもつにはまず実行しなければなりません。 (クラス定義を @ref{181,,if} 文の分岐先や関数内部に置くことも、考え方としてはありえます。)

実際には、クラス定義の内側にある文は、通常は関数定義になりますが、他の文を書くこともでき、それが役に立つこともあります --- これについては後で述べます。クラス内の関数定義は通常、メソッドの呼び出し規約で決められた独特の形式の引数リストを持ちます --- これについても後で述べます。

クラス定義に入ると、新たな名前空間が作成され、ローカルな名前空間として使われます --- 従って、ローカルな変数に対する全ての代入はこの新たな名前空間に入ります。特に、関数定義を行うと、新たな関数の名前はこの名前空間に結び付けられます。

クラス定義から普通に (定義の終端に到達して) 抜けると、 `クラスオブジェクト (class object)' が生成されます。クラスオブジェクトは、基本的にはクラス定義で作成された名前空間の内容をくるむラッパー (wrapper) です。クラスオブジェクトについては次の節で詳しく学ぶことにします。 (クラス定義に入る前に有効だった) 元のローカルスコープが復帰し、生成されたクラスオブジェクトは復帰したローカルスコープにクラス定義のヘッダで指定した名前 (上の例では @code{ClassName}) で結び付けられます。

@node クラスオブジェクト,インスタンスオブジェクト,クラス定義の構文,クラス初見
@anchor{tutorial/classes class-objects}@anchor{2093}@anchor{tutorial/classes tut-classobjects}@anchor{2094}
@subsubsection クラスオブジェクト


クラスオブジェクトでは２種類の演算、属性参照とインスタンス生成をサポートしています。

`属性参照 (attribute reference)' は、Python におけるすべての属性参照で使われている標準的な構文、 @code{obj.name} を使います。クラスオブジェクトが生成された際にクラスの名前空間にあった名前すべてが有効な属性名です。従って、以下のようなクラス定義では:

@example
class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
@end example

@code{MyClass.i} と @code{MyClass.f} は有効な属性参照であり、それぞれ整数と関数オブジェクトを返します。クラス属性も代入できるため、代入により @code{MyClass.i} の値を変えられます。 @ref{2095,,__doc__} も有効な属性で、そのクラスに属しているドキュメンテーション文字列(docstring) 、この場合は @code{"A simple example class"} を返します。

クラスの `インスタンス化 (instantiation)' には関数記法を使います。クラスオブジェクトのことを、クラスの新しいインスタンスを返す、引数のない関数のように扱ってください。上記クラスで例示すると:

@example
x = MyClass()
@end example

は、クラスの新しい `インスタンス (instance)' を生成し、そのオブジェクトをローカル変数 @code{x} へ代入します。

インスタンス化操作 (クラスオブジェクトの "呼出し") では、空のオブジェクトが作られます。多くのクラスでは、特定の初期状態にカスタマイズされたオブジェクトを作りたいです。そのために、クラスには @ref{8bf,,__init__()} という名前の特殊メソッドを定義できます。例えば次のようにします:

@example
def __init__(self):
    self.data = []
@end example

クラスが @ref{8bf,,__init__()} メソッドを定義している場合、クラスをインスタンス化すると、新しく作られたクラスインスタンスに対して自動的に @code{__init__()} を呼び出します。  従って この例では、新たな初期済みインスタンスを次のようにして得られます:

@example
x = MyClass()
@end example

もちろん、より大きな柔軟性を持たせるために、 @ref{8bf,,__init__()} メソッドに複数の引数をもたせることができます。その場合、次の例のように、クラスのインスタンス化操作に渡された引数は @code{__init__()} に渡されます。例えば、

@example
>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
@end example

@node インスタンスオブジェクト,メソッドオブジェクト,クラスオブジェクト,クラス初見
@anchor{tutorial/classes instance-objects}@anchor{2096}@anchor{tutorial/classes tut-instanceobjects}@anchor{2097}
@subsubsection インスタンスオブジェクト


ところで、インスタンスオブジェクトを使うと何ができるのでしょうか？インスタンスオブジェクトが理解できる唯一の操作は、属性の参照です。有効な属性名には (データ属性およびメソッドの) 二種類あります。

`データ属性 (Data attribute)' は、 Smalltalk の "インスタンス変数" や C++の "データメンバ" に相当します。データ属性を宣言する必要はありません。ローカル変数と同様に、これらの属性は最初に代入された時点で湧き出てきます。例えば、上で生成した @code{MyClass} のインスタンス @code{x} に対して、次のコードを実行すると、跡を残さず値 @code{16} を印字します:

@example
x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print(x.counter)
del x.counter
@end example

もう一つのインスタンス属性の参照は、 `メソッド' です。メソッドとは、オブジェクトに "属する" 関数のことです。

@geindex object;メソッド

インスタンスオブジェクトで有効なメソッド名は、そのクラスによります。定義により、クラスの全ての関数オブジェクトである属性がインスタンスオブジェクトの妥当なメソッド名に決まります。従って、例では、@code{MyClass.f} は関数なので、@code{x.f} はメソッドの参照として有効です。しかし、@code{MyClass.i} は関数ではないので、@code{x.i} はメソッドの参照として有効ではありません。@code{x.f} は @code{MyClass.f} と同じものではありません --- 関数オブジェクトではなく、`メソッドオブジェクト (method object)' です。

@node メソッドオブジェクト,クラスとインスタンス変数,インスタンスオブジェクト,クラス初見
@anchor{tutorial/classes method-objects}@anchor{2098}@anchor{tutorial/classes tut-methodobjects}@anchor{2099}
@subsubsection メソッドオブジェクト


普通、メソッドはバインドされた直後に呼び出されます:

@example
x.f()
@end example

もし @code{x = MyClass()} であれば、上記のコードは文字列 @code{'hello world'} を返すでしょう。しかしながら、必ずしもメソッドをその場で呼び出さなければならないわけではありません。 @code{x.f} はメソッドオブジェクトであり、どこかに記憶しておいて後で呼び出すことができます。例えば次のコードは:

@example
xf = x.f
while True:
    print(xf())
@end example

@code{hello world} を時が終わるまで印字し続けるでしょう。

メソッドが呼び出されるときには実際には何が起きているのでしょうか？ @code{f()} の関数定義では引数を一つ指定していたにもかかわらず、上の例では @code{x.f()} が引数なしで呼び出されています。引数はどうなったのでしょうか？たしか、引数が必要な関数を引数無しで呼び出すと、 Python が例外を送出するはずです --- たとえその引数が実際には使われなくても…。

もう答は想像できているかもしれませんね:
メソッドについて特別なこととして、インスタンスオブジェクトが関数の第1引数として渡されます。
例では、 @code{x.f()} という呼び出しは、 @code{MyClass.f(x)} と厳密に等価なものです。
一般に、 `n' 個の引数リストもったメソッドの呼出しは、そのメソッドのインスタンスオブジェクトを最初の引数の前に挿入した引数リストで、メソッドに対応する関数を呼び出すことと等価です。

一般的に、メソッドは以下のように動作します。インスタンスの非データ属性が参照されたときは、そのインスタンスのクラスが検索されます。その名前が有効なクラス属性を表している関数オブジェクトなら、インスタンスオブジェクトと関数オブジェクトの両方への参照がメソッドオブジェクトにパックされます。メソッドオブジェクトが引数リストと共に呼び出されるとき、インスタンスオブジェクトと渡された引数リストから新しい引数リストを作成して、元の関数オブジェクトを新しい引数リストで呼び出します。

@node クラスとインスタンス変数,,メソッドオブジェクト,クラス初見
@anchor{tutorial/classes class-and-instance-variables}@anchor{209a}@anchor{tutorial/classes tut-class-and-instance-variables}@anchor{209b}
@subsubsection クラスとインスタンス変数


一般的に、インスタンス変数はそれぞれのインスタンスについて固有のデータのためのもので、クラス変数はそのクラスのすべてのインスタンスによって共有される属性やメソッドのためのものです:

@example
class Dog:

    kind = 'canine'         # 全インスタンスで共有されるクラス変数

    def __init__(self, name):
        self.name = name    # インスタンスごとに固有のインスタンス変数

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # すべての犬で共有
'canine'
>>> e.kind                  # すべての犬で共有
'canine'
>>> d.name                  # d 固有
'Fido'
>>> e.name                  # e 固有
'Buddy'
@end example

As discussed in @ref{208b,,名前とオブジェクトについて}, shared data can have possibly surprising
effects involving @ref{15ba,,mutable} objects such as lists and dictionaries.
For example, the `tricks' list in the following code should not be used as a
class variable because just a single list would be shared by all `Dog'
instances:

@example
class Dog:

    tricks = []             # クラス変数の間違った使用

    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                # 意図せず すべての犬で共有
['roll over', 'play dead']
@end example

このクラスの正しい設計ではインスタンス変数を代わりに使用するべきです:

@example
class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # 犬ごとに新しい空リストを作る

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']
@end example

@node いろいろな注意点,継承,クラス初見,クラス
@anchor{tutorial/classes random-remarks}@anchor{209c}@anchor{tutorial/classes tut-remarks}@anchor{209d}
@subsection いろいろな注意点


@c These should perhaps be placed more carefully...

インスタンスとクラスの両方で同じ属性名が使用されている場合、属性検索はインスタンスが優先されます。

@example
>>> class Warehouse:
...    purpose = 'storage'
...    region = 'west'
...
>>> w1 = Warehouse()
>>> print(w1.purpose, w1.region)
storage west
>>> w2 = Warehouse()
>>> w2.region = 'east'
>>> print(w2.purpose, w2.region)
storage east
@end example

データ属性は、メソッドから参照できると同時に、通常のオブジェクトのユーザ ("クライアント") からも参照できます。言い換えると、クラスは純粋な抽象データ型として使うことができません。実際、 Python では、データ隠蔽を補強するための機構はなにもありません --- データの隠蔽はすべて規約に基づいています。 (逆に、C 言語で書かれた Python の実装では実装の詳細を完全に隠蔽し、必要に応じてオブジェクトへのアクセスを制御できます。この機構は C 言語で書かれた Python 拡張で使うことができます。)

クライアントはデータ属性を注意深く扱うべきです --- クライアントは、メソッドが維持しているデータ属性の不変式を踏みにじり、台無しにするかもしれません。クライアントは、名前の衝突が回避されている限り、メソッドの有効性に影響を及ぼすことなくインスタンスに独自の属性を追加することができる、ということに注意してください --- ここでも、名前付けの規約は頭痛の種を無くしてくれます。

メソッドの中から、データ属性を (または別のメソッドも！) 参照するための短縮された記法はありません。私は、この仕様がメソッドの可読性を高めていると感じています。あるメソッドを眺めているときにローカルな変数とインスタンス変数をはっきり区別できるからです。

よく、メソッドの最初の引数を @code{self} と呼びます。この名前付けは単なる慣習でしかありません。 @code{self} という名前は、 Python では何ら特殊な意味を持ちません。とはいえ、この慣行に従わないと、コードは他の Python プログラマにとってやや読みにくいものとなります。また、 `クラスブラウザ (class browser)' プログラムがこの慣行をあてにして書かれているかもしれません。

クラス属性である関数オブジェクトはいずれも、そのクラスのインスタンスのためのメソッドを定義しています。関数定義は、テキスト上でクラス定義の中に入っている必要はありません。関数オブジェクトをクラスのローカルな変数の中に代入するのも OK です。例えば以下のコードのようにします:

@example
# クラス外で定義された関数
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1

    def g(self):
        return 'hello world'

    h = g
@end example

これで、 @code{f} 、 @code{g} 、および @code{h} は、すべて @code{C} の属性であり関数オブジェクトを参照しています。従って、これらは、すべて @code{C} のインスタンスのメソッドとなります --- @code{h} は @code{g} と全く等価です。これを実践しても、大抵は単にプログラムの読者に混乱をもたらすだけなので注意してください。

メソッドは、 @code{self} 引数のメソッド属性を使って、他のメソッドを呼び出すことができます:

@example
class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)
@end example

メソッドは、通常の関数と同じようにしてグローバルな名前を参照します。あるメソッドに関するグローバルスコープは、その定義を含むモジュールです。(クラスはグローバルなスコープとして用いられることはありません。) メソッドでグローバルなデータを使う良い理由はほとんどありませんが、グローバルなスコープを使うべき場面は多々あります。一つ挙げると、メソッド内から、グローバルなスコープに import された関数やモジュールや、そのモジュール中で定義された関数やクラスを使うことができます。通常、メソッドの入っているクラス自体はグローバルなスコープ内で定義されています。次の節では、メソッドが自分のクラスを参照する理由として正当なものを見てみましょう。

個々の値はオブジェクトなので、 `クラス' (`型' とも言います) を持っています。それは @code{object.__class__} に保持されています。

@node 継承,プライベート変数,いろいろな注意点,クラス
@anchor{tutorial/classes inheritance}@anchor{209e}@anchor{tutorial/classes tut-inheritance}@anchor{209f}
@subsection 継承


言うまでもなく、継承の概念をサポートしない言語機能は "クラス" と呼ぶに値しません。派生クラス (derived class) を定義する構文は次のようになります:

@example
class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>
@end example

基底クラス (base class) の名前 @code{BaseClassName} は、派生クラス定義の入っているスコープからアクセスできる名前空間で定義されていなければなりません。基底クラス名のかわりに任意の式を入れることもできます。これは次の例のように、基底クラスが別モジュールで定義されているときに便利なことがあります:

@example
class DerivedClassName(modname.BaseClassName):
@end example

派生クラス定義の実行は、基底クラスの場合と同じように進められます。クラスオブジェクトが構築される時、基底クラスが記憶されます。記憶された基底クラスは、属性参照を解決するために使われます。要求された属性がクラスに見つからなかった場合、基底クラスに検索が進みます。この規則は、基底クラスが他の何らかのクラスから派生したものであった場合、再帰的に適用されます。

派生クラスのインスタンス化では、特別なことは何もありません。 @code{DerivedClassName()} はクラスの新たなインスタンスを生成します。メソッドの参照は次のようにして解決されます。まず対応するクラス属性が検索されます。検索は、必要に応じ、基底クラス連鎖を下って行われ、検索の結果として何らかの関数オブジェクトがもたらされた場合、メソッド参照は有効なものとなります。

派生クラスは基底クラスのメソッドを上書き (override) することができます。メソッドは同じオブジェクトの別のメソッドを呼び出す際に何ら特殊な権限を持ちません。このため、ある基底クラスのメソッドが、同じ基底クラスで定義されているもう一つのメソッド呼び出しを行っている場合、派生クラスで上書きされた何らかのメソッドが呼び出されることになるかもしれません。 (C++ プログラマへ:  Python では、すべてのメソッドは事実上 @code{virtual} です。)

派生クラスで上書きしているメソッドでは、基底クラスの同名のメソッドを置き換えるのではなく、拡張したいのかもしれません。基底クラスのメソッドを直接呼び出す簡単な方法があります。単に @code{BaseClassName.methodname(self, arguments)} を呼び出すだけです。この仕様は、場合によってはクライアントでも役に立ちます。 (この呼び出し方が動作するのは、基底クラスがグローバルスコープの @code{BaseClassName} という名前でアクセスできるときだけです。)

Python には継承に関係する 2 つの組み込み関数があります:


@itemize *

@item 
@ref{2ad,,isinstance()} を使うとインスタンスの型が調べられます。 @code{isinstance(obj, int)} は @code{obj.__class__} が @ref{19b,,int} や @ref{19b,,int} の派生クラスの場合に限り @code{True} になります。

@item 
@ref{9c4,,issubclass()} を使うとクラスの継承関係が調べられます。 @ref{3c3,,bool} は @ref{19b,,int} のサブクラスなので @code{issubclass(bool, int)} は @code{True} です。しかし、 @ref{196,,float} は @ref{19b,,int} のサブクラスではないので @code{issubclass(float, int)} は @code{False} です。
@end itemize

@menu
* 多重継承:: 

@end menu

@node 多重継承,,,継承
@anchor{tutorial/classes multiple-inheritance}@anchor{20a0}@anchor{tutorial/classes tut-multiple}@anchor{20a1}
@subsubsection 多重継承


Python では、多重継承 (multiple inheritance) の形式もサポートしています。複数の基底クラスをもつクラス定義は次のようになります:

@example
class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
@end example

ほとんどのシンプルな多重継承において、親クラスから継承される属性の検索は、深さ優先で、左から右に、そして継承の階層の中で同じクラスが複数出てくる（訳注: ダイアモンド継承と呼ばれます）場合に２度探索をしない、と考えることができます。なので、ある属性が @code{DerivedClassName} で見つからない場合、まず @code{Base1} から検索され、そして（再帰的に） @code{Base1} の基底クラスから検索され、それでも見つからなかった場合は @code{Base2} から検索される、といった具合になります。

実際には、それよりもう少しだけ複雑です。協調的な @ref{1a6,,super()} の呼び出しのためにメソッドの解決順序は動的に変更されます。このアプローチは他の多重継承のある言語で call-next-method として知られており、単一継承しかない言語の super 呼び出しよりも強力です。

動的順序付けが必要なのは、すべての多重継承で１つ以上のダイヤモンド継承 (少なくとも 1 つの祖先クラスに対して最下位クラスから到達する経路が複数ある状態) が見られるためです。例えば、全ての新形式のクラスは @ref{c7e,,object} を継承しているので、どの多重継承でも @ref{c7e,,object} への到達経路が複数あります。基底クラスが複数回アクセスされないようにするために、動的アルゴリズムで検索順序を線形化します。それは、各クラスで指定されている左から右への順序は崩さず、各々の祖先クラスを一度だけ呼び出し、かつ単調になる (つまり祖先クラスの検索順序に影響を与えずにクラスをサブクラス化できる) ように行います。まとめると、これらの特徴のおかげで信頼性と拡張性のある多重継承したクラスを設計することができるのです。詳細は、 @ref{16c3,,The Python 2.3 Method Resolution Order} を見てください。

@node プライベート変数,残りのはしばし,継承,クラス
@anchor{tutorial/classes private-variables}@anchor{20a2}@anchor{tutorial/classes tut-private}@anchor{2089}
@subsection プライベート変数


オブジェクトの中からしかアクセス出来ない "プライベート" インスタンス変数は、 Python にはありません。しかし、ほとんどの Python コードが従っている慣習があります。アンダースコアで始まる名前 (例えば @code{_spam}) は、 (関数であれメソッドであれデータメンバであれ) 非 public なAPIとして扱います。これらは、予告なく変更されるかもしれない実装の詳細として扱われるべきです。

@geindex name;難号化

クラスのプライベートメンバについて適切なユースケース(特にサブクラスで定義された名前との衝突を避ける場合)があるので、名前マングリング (`name mangling') と呼ばれる、限定されたサポート機構があります。 @code{__spam} (先頭に二個以上の下線文字、末尾に一個以下の下線文字) という形式の識別子は、 @code{_classname__spam} へとテキスト置換されるようになりました。ここで @code{classname} は、現在のクラス名から先頭の下線文字をはぎとった名前になります。このような難号化 (mangle) は、識別子の文法的な位置にかかわらず行われるので、クラス定義内に現れた識別子全てに対して実行されます。


@subsubheading 参考


詳細と特例は、 @ref{20a3,,private name mangling specifications} 。


名前マングリングは、サブクラスが内部のメソッド呼び出しを壊さずにメソッドをオーバーライドするのに便利です。例えば:

@example
class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # 元の update() メソッドのプライベートコピー

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # update() への新シグネチャ導入
        # しかし __init__() は壊さない
        for item in zip(keys, values):
            self.items_list.append(item)
@end example

上の例は、もし仮に @code{MappingSubclass} に @code{__update} 識別子を実装したとしてもきちんと動きます。
その理由は、 @code{Mapping} クラスではその識別子を @code{_Mapping__update} に、 @code{MappingSubclass} クラスでは @code{_MappingSubclass__update} にそれぞれ置き換えるからです。

難号化の規則は主に不慮の事故を防ぐためのものだということに注意してください; 確信犯的な方法で、プライベートとされている変数にアクセスしたり変更することは依然として可能なのです。デバッガのような特殊な状況では、この仕様は便利ですらあります。

@code{exec()} や @code{eval()} へ渡されたコードでは、呼出し元のクラス名を現在のクラスと見なさないことに注意してください。この仕様は @code{global} 文の効果と似ており、その効果もまた同様に、バイトコンパイルされたコードに制限されています。同じ制約が @code{getattr()} と @code{setattr()} と @code{delattr()} にも適用されます。また、@code{__dict__} を直接参照するときにも適用されます。

@node 残りのはしばし,イテレータ iterator,プライベート変数,クラス
@anchor{tutorial/classes odds-and-ends}@anchor{20a4}@anchor{tutorial/classes tut-odds}@anchor{20a5}
@subsection 残りのはしばし


Pascal の "レコード (record)" や、C 言語の "構造体 (struct)" のような、名前つきのデータ要素を一まとめにするデータ型があると便利なことがあります。慣用的な手法として、この目的のために @ref{33,,dataclasses} を使用します。

@example
from dataclasses import dataclass

@@dataclass
class Employee:
    name: str
    dept: str
    salary: int
@end example

@example
>>> john = Employee('john', 'computer lab', 1000)
>>> john.dept
'computer lab'
>>> john.salary
1000
@end example

ある特定の抽象データ型を要求する Python コードの断片に、そのデータ型のメソッドをエミュレーションするクラスを代わりに渡すことができます。例えば、ファイルオブジェクトから何らかのデータを構築する関数がある場合、 @ref{206c,,read()} と @ref{20a6,,readline()} を持つクラスを定義して、ファイルではなく文字列バッファからデータを取得するようにしておき、引数として渡すことができます。

@c (Unfortunately, this technique has its limitations: a class can't define
@c operations that are accessed by special syntax such as sequence subscripting
@c or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will
@c not cause the interpreter to read further input from it.)

@ref{20a7,,Instance method objects} にも属性があります。 @ref{15e2,,m.__self__} はメソッド @code{m()} の属しているインスタンスオブジェクトで、@ref{1514,,m.__func__} はそのメソッドに対応する @ref{59c,,function object} です。

@node イテレータ iterator,ジェネレータ generator,残りのはしばし,クラス
@anchor{tutorial/classes iterators}@anchor{20a8}@anchor{tutorial/classes tut-iterators}@anchor{20a9}
@subsection イテレータ (iterator)


すでに気づいているでしょうが、 @ref{34a,,for} 文を使うとほとんどのコンテナオブジェクトにわたってループを行うことができます:

@example
for element in [1, 2, 3]:
    print(element)
for element in (1, 2, 3):
    print(element)
for key in @{'one':1, 'two':2@}:
    print(key)
for char in "123":
    print(char)
for line in open("myfile.txt"):
    print(line, end='@w{'})
@end example

こういう要素へのアクセス方法は明確で簡潔で使い易いものです。イテレータの活用は Python へ広く行き渡り、統一感を持たせています。裏では @code{for} 文はコンテナオブジェクトに対して @ref{9d7,,iter()} 関数を呼んでいます。関数は、コンテナの中の要素に1つずつアクセスする @ref{14e5,,__next__()} メソッドが定義されているイテレータオブジェクトを返します。これ以上要素が無い場合は、 @ref{14e5,,__next__()} メソッドは @ref{df5,,StopIteration} 例外を送出し、その通知を受け @ref{34a,,for} ループは終了します。組み込みの @ref{9d8,,next()} 関数を使って @ref{14e5,,__next__()} メソッドを直接呼ぶこともできます; この例は関数がどう働くのかを示しています:

@example
>>> s = 'abc'
>>> it = iter(s)
>>> it
<str_iterator object at 0x10c90e650>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    next(it)
StopIteration
@end example

イテレータプロトコルの裏にある仕組みを観察していれば、自作のクラスにイテレータとしての振舞いを追加するのは簡単です。 @ref{14e5,,__next__()} メソッドを持つオブジェクトを返す @ref{20aa,,__iter__()} メソッドを定義するのです。クラスが @code{__next__()} メソッドを定義している場合、 @code{__iter__()} メソッドは単に @code{self} を返すことも可能です:

@example
class Reverse:
    """シーケンスを後ろからまわるイテレータ."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
@end example

@example
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
...     print(char)
...
m
a
p
s
@end example

@node ジェネレータ generator,ジェネレータ式,イテレータ iterator,クラス
@anchor{tutorial/classes generators}@anchor{20ab}@anchor{tutorial/classes tut-generators}@anchor{20ac}
@subsection ジェネレータ (generator)


@ref{126c,,ジェネレータ} は、イテレータを作成するための簡潔で強力なツールです。ジェネレータは通常の関数のように書かれますが、何らかのデータを返すときには @ref{bc2,,yield} 文を使います。そのジェネレータに対して @ref{9d8,,next()} が呼び出されるたびに、ジェネレータは以前に中断した処理を再開します (ジェネレータは、全てのデータ値と最後にどの文が実行されたかを記憶しています)。以下の例を見れば、ジェネレータがとても簡単に作成できることがわかります:

@example
def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]
@end example

@example
>>> for char in reverse('golf'):
...     print(char)
...
f
l
o
g
@end example

ジェネレータでできることは、前の節で解説したクラスを使ったイテレータでも実現できます。ジェネレータの定義がコンパクトになるのは @ref{20ad,,__iter__()} メソッドと @ref{20ae,,__next__()} メソッドが自動で作成されるからです。

ジェネレータのもう一つの重要な機能は、呼び出しごとにローカル変数と実行状態が自動的に保存されるということです。これにより、 @code{self.index} や @code{self.data} といったインスタンス変数を使ったアプローチよりも簡単に関数を書くことができるようになります。

メソッドを自動生成したりプログラムの実行状態を自動保存するほかに、ジェネレータは終了時に自動的に @ref{df5,,StopIteration} を送出します。これらの機能を組み合わせると、通常の関数を書くのと同じ労力で、簡単にイテレータを生成できます。

@node ジェネレータ式,,ジェネレータ generator,クラス
@anchor{tutorial/classes generator-expressions}@anchor{20af}@anchor{tutorial/classes tut-genexps}@anchor{20b0}
@subsection ジェネレータ式


単純なジェネレータなら式として簡潔にコーディングできます。
その式はリスト内包表記に似た構文を使いますが、角括弧ではなく丸括弧で囲います。
ジェネレータ式は、関数の中でジェネレータをすぐに使いたいような状況のために用意されています。
ジェネレータ式は完全なジェネレータの定義よりコンパクトですが、ちょっと融通の効かないところがあります。
同じ内容を返すリスト内包表記よりはメモリに優しいことが多いという利点があります。

例:

@example
>>> sum(i*i for i in range(10))                 # 平方和
285

>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))         # ドット積
260

>>> unique_words = set(word for line in page  for word in line.split())

>>> valedictorian = max((student.gpa, student.name) for student in graduates)

>>> data = 'golf'
>>> list(data[i] for i in range(len(data)-1, -1, -1))
['f', 'l', 'o', 'g']
@end example

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 標準ライブラリミニツアー,標準ライブラリミニツアー --- その 2,クラス,Python チュートリアル
@anchor{tutorial/stdlib doc}@anchor{20b1}@anchor{tutorial/stdlib brief-tour-of-the-standard-library}@anchor{20b2}@anchor{tutorial/stdlib translation-repo}@anchor{20b3}@anchor{tutorial/stdlib tut-brieftour}@anchor{20b4}
@section 標準ライブラリミニツアー


@menu
* OSへのインターフェース:: 
* ファイルのワイルドカード表記:: 
* コマンドライン引数:: 
* エラー出力のリダイレクトとプログラムの終了:: 
* 文字列のパターンマッチング:: 
* 数学:: 
* インターネットへのアクセス:: 
* 日付と時刻:: 
* データ圧縮:: 
* パフォーマンスの計測:: 
* 品質管理:: 
* バッテリー同梱:: 

@end menu

@node OSへのインターフェース,ファイルのワイルドカード表記,,標準ライブラリミニツアー
@anchor{tutorial/stdlib operating-system-interface}@anchor{20b5}@anchor{tutorial/stdlib tut-os-interface}@anchor{20b6}
@subsection OSへのインターフェース


@ref{a5,,os} モジュールは、オペレーティングシステムと対話するための多くの関数を提供しています:

@example
>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python314'
>>> os.chdir('/server/accesslogs')   # Change current working directory
>>> os.system('mkdir today')   # Run the command mkdir in the system shell
0
@end example

@code{from os import *} ではなく、 @code{import os} 形式を使うようにしてください。そうすることで、動作が大きく異なる組み込み関数 @ref{316,,open()} が @ref{f92,,os.open()} で遮蔽されるのを避けられます。

@geindex 組み込み関数;help

組み込み関数 @ref{844,,dir()} および @ref{ad4,,help()} は、 @ref{a5,,os} のような大規模なモジュールで作業をするときに、対話的な操作上の助けになります:

@example
>>> import os
>>> dir(os)
<OSモジュールの関数すべてのリストを返す>
>>> help(os)
<モジュールの docstring から生成された詳細なマニュアルを返す>
@end example

ファイルやディレクトリの日常的な管理作業のために、より簡単に使える高水準のインターフェースが @ref{ca,,shutil} モジュールで提供されています:

@example
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'
@end example

@node ファイルのワイルドカード表記,コマンドライン引数,OSへのインターフェース,標準ライブラリミニツアー
@anchor{tutorial/stdlib file-wildcards}@anchor{20b7}@anchor{tutorial/stdlib tut-file-wildcards}@anchor{20b8}
@subsection ファイルのワイルドカード表記


@ref{68,,glob} モジュールでは、ディレクトリのワイルドカード検索からファイルのリストを生成するための関数を提供しています:

@example
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
@end example

@node コマンドライン引数,エラー出力のリダイレクトとプログラムの終了,ファイルのワイルドカード表記,標準ライブラリミニツアー
@anchor{tutorial/stdlib command-line-arguments}@anchor{20b9}@anchor{tutorial/stdlib tut-command-line-arguments}@anchor{20ba}
@subsection コマンドライン引数


一般的なユーティリティスクリプトでは、よくコマンドライン引数を扱う必要があります。コマンドライン引数は モジュールの `argv' 属性にリストとして保存されています。例として以下の @code{demo.py} ファイルを見てみましょう:

@example
# File demo.py
import sys
print(sys.argv)
@end example

以下は、コマンドライン上で @code{python demo.py one two three} と実行した時の出力です:

@example
['demo.py', 'one', 'two', 'three']
@end example

@ref{7,,argparse} モジュールは、コマンドライン引数を処理するための更に洗練された仕組みを提供します。次のスクリプトは1つ以上のファイル名を抽出し、オプションで行数を表示します。

@example
import argparse

parser = argparse.ArgumentParser(
    prog='top',
    description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)
@end example

コマンドラインで @code{python top.py --lines=5 alpha.txt beta.txt} を実行すると、上のスクリプトは @code{args.lines} を @code{5} 、 @code{args.filenames} を @code{['alpha.txt', 'beta.txt']} に設定します。

@node エラー出力のリダイレクトとプログラムの終了,文字列のパターンマッチング,コマンドライン引数,標準ライブラリミニツアー
@anchor{tutorial/stdlib error-output-redirection-and-program-termination}@anchor{20bb}@anchor{tutorial/stdlib tut-stderr}@anchor{20bc}
@subsection エラー出力のリダイレクトとプログラムの終了


@ref{df,,sys} モジュールには、 `stdin', `stdout', `stderr' を表す属性も存在します。 `stderr' は、警告やエラーメッセージを出力して、 `stdout' がリダイレクトされた場合でも読めるようにするために便利です:

@example
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
@end example

@code{sys.exit()} は、スクリプトを終了させるもっとも直接的な方法です。

@node 文字列のパターンマッチング,数学,エラー出力のリダイレクトとプログラムの終了,標準ライブラリミニツアー
@anchor{tutorial/stdlib string-pattern-matching}@anchor{20bd}@anchor{tutorial/stdlib tut-string-pattern-matching}@anchor{20be}
@subsection 文字列のパターンマッチング


@ref{be,,re} モジュールでは、より高度な文字列処理のための正規表現を提供しています。正規表現は複雑な一致検索や操作に対して簡潔で最適化された解決策を提供します:

@example
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
@end example

最小限の機能だけが必要なら、読みやすくデバッグしやすい文字列メソッドの方がお勧めです:

@example
>>> 'tea for too'.replace('too', 'two')
'tea for two'
@end example

@node 数学,インターネットへのアクセス,文字列のパターンマッチング,標準ライブラリミニツアー
@anchor{tutorial/stdlib mathematics}@anchor{20bf}@anchor{tutorial/stdlib tut-mathematics}@anchor{20c0}
@subsection 数学


@ref{92,,math} モジュールは、浮動小数点演算のための C 言語ライブラリ関数にアクセスする手段を提供しています:

@example
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
@end example

@ref{bd,,random} モジュールは、乱数に基づいた要素選択のためのツールを提供しています:

@example
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # 重複なしでサンプリング
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # [0.0, 1.0) の区間内のランダムな float
0.17970987693706186
>>> random.randrange(6)    # range(6) からランダムに選ばれた integer
4
@end example

@ref{d7,,statistics} モジュールは数値データの基礎的な統計的特性（平均、中央値、分散等）を計算します:

@example
>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095
@end example

SciPy プロジェクト <@indicateurl{https://scipy.org}> は数値処理のための多くのモジュールを提供しています。

@node インターネットへのアクセス,日付と時刻,数学,標準ライブラリミニツアー
@anchor{tutorial/stdlib internet-access}@anchor{20c1}@anchor{tutorial/stdlib tut-internet-access}@anchor{20c2}
@subsection インターネットへのアクセス


インターネットにアクセスしたりインターネットプロトコルを処理したりするための多くのモジュールがあります。最も単純な2つのモジュールは、 URL からデータを取得するための @ref{111,,urllib.request} と、メールを送るための @ref{cf,,smtplib} です:

@example
>>> from urllib.request import urlopen
>>> with urlopen('https://docs.python.org/3/') as response:
...     for line in response:
...         line = line.decode()             # Convert bytes to a str
...         if 'updated' in line:
...             print(line.rstrip())         # Remove trailing newline
...
      Last updated on Nov 11, 2025 (20:11 UTC).

>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@@example.org', 'jcaesar@@example.org',
... """To: jcaesar@@example.org
... From: soothsayer@@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()
@end example

(2つ目の例は localhost でメールサーバーが動いている必要があることに注意してください。)

@node 日付と時刻,データ圧縮,インターネットへのアクセス,標準ライブラリミニツアー
@anchor{tutorial/stdlib dates-and-times}@anchor{20c3}@anchor{tutorial/stdlib tut-dates-and-times}@anchor{20c4}
@subsection 日付と時刻


@ref{34,,datetime} モジュールは、日付や時刻を操作するためのクラスを、単純な方法と複雑な方法の両方で提供しています。日付や時刻に対する算術がサポートされている一方、実装では出力のフォーマットや操作のための効率的なデータメンバ抽出に重点を置いています。このモジュールでは、タイムゾーンに対応したオブジェクトもサポートしています。

@example
>>> # 日付 (date) は容易に作成・フォーマットが可能
>>> 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.'

>>> # date で日付の演算が可能
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
@end example

@node データ圧縮,パフォーマンスの計測,日付と時刻,標準ライブラリミニツアー
@anchor{tutorial/stdlib data-compression}@anchor{20c5}@anchor{tutorial/stdlib tut-data-compression}@anchor{20c6}
@subsection データ圧縮


一般的なデータアーカイブと圧縮形式は、以下のようなモジュールによって直接的にサポートされます: @ref{139,,zlib}, @ref{6b,,gzip}, @ref{14,,bz2}, @ref{8e,,lzma}, @ref{137,,zipfile}, @ref{e4,,tarfile}。

@example
>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979
@end example

@node パフォーマンスの計測,品質管理,データ圧縮,標準ライブラリミニツアー
@anchor{tutorial/stdlib performance-measurement}@anchor{20c7}@anchor{tutorial/stdlib tut-performance-measurement}@anchor{20c8}
@subsection パフォーマンスの計測


Python ユーザの中には、同じ問題を異なったアプローチで解いた際の相対的なパフォーマンスについて知りたいという深い興味を持っている人がいます。Python は、そういった疑問に即座に答える計測ツールを提供しています。

例えば、引数の入れ替え操作に対して、伝統的なアプローチの代わりにタプルのパックやアンパックを使ってみたいと思うかもしれません。 @ref{f5,,timeit} モジュールを使えば、パフォーマンスがほんの少し良いことがすぐに分かります:

@example
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
@end example

@ref{f5,,timeit} では小さい粒度を提供しているのに対し、 @ref{b4,,profile} や @ref{b5,,pstats} モジュールではより大きなコードブロックにおいて律速となる部分を判定するためのツールを提供しています。

@node 品質管理,バッテリー同梱,パフォーマンスの計測,標準ライブラリミニツアー
@anchor{tutorial/stdlib quality-control}@anchor{20c9}@anchor{tutorial/stdlib tut-quality-control}@anchor{20ca}
@subsection 品質管理


高い品質のソフトウェアを開発するための一つのアプローチは、各関数に対して開発と同時にテストを書き、開発の過程で頻繁にテストを走らせるというものです。

@ref{3e,,doctest} モジュールでは、モジュールを検索してプログラムの docstring に埋め込まれたテストの評価を行うためのツールを提供しています。テストの作り方は単純で、典型的な呼び出し例とその結果を docstring にカット&ペーストするだけです。この作業は、ユーザに使用例を与えるという意味でドキュメントの情報を増やすと同時に、ドキュメントに書かれているコードが正しい事を確認できるようになります:

@example
def average(values):
    """数値のリストの算術平均を計算する。

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
doctest.testmod()   # docstring に埋め込まれたテストを自動的に評価
@end example

@ref{10c,,unittest} モジュールは @ref{3e,,doctest} モジュールほど気楽に使えるものではありませんが、より網羅的なテストセットを別のファイルで管理することができます:

@example
import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20, 30, 70)

unittest.main()  # コマンドラインからこれを呼び出すとテストがすべて実行される
@end example

@node バッテリー同梱,,品質管理,標準ライブラリミニツアー
@anchor{tutorial/stdlib batteries-included}@anchor{20cb}@anchor{tutorial/stdlib tut-batteries-included}@anchor{20cc}
@subsection バッテリー同梱


Python には "バッテリー同梱 (batteries included)" 哲学があります。この哲学は、洗練され、安定した機能を持つ Python の膨大なパッケージ群に如実に表れています。例えば:


@itemize *

@item 
@ref{134,,xmlrpc.client}  および @ref{135,,xmlrpc.server} モジュールは、遠隔手続き呼び出し (remote procedure call) を全く大したことのない作業に変えてしまいます。モジュール名とは違い、XML を扱うための直接的な知識は必要ありません。

@item 
@ref{3f,,email} パッケージは、MIME やその他の 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} に基づくメッセージ文書を含む電子メールメッセージを管理するためのライブラリです。実際にメッセージを送信したり受信したりする @ref{cf,,smtplib} や @ref{b1,,poplib} と違って、email パッケージには (添付文書を含む) 複雑なメッセージ構造の構築やデコードを行ったり、インターネット標準のエンコードやヘッダプロトコルの実装を行ったりするための完全なツールセットを備えています。

@item 
@ref{86,,json} パッケージはこの一般的なデータ交換形式のパースをロバストにサポートしています。@ref{2d,,csv} モジュールはデータベースや表計算で一般的にサポートされている CSV ファイルを直接読み書きするのをサポートしています。@ref{12b,,xml.etree.ElementTree}、@ref{127,,xml.dom} ならびに @ref{12f,,xml.sax} パッケージは XML の処理をサポートしています。総合すると、これらのモジュールによって Python アプリケーションと他のツールの間でとても簡単にデータを受け渡すことが出来ます。

@item 
@ref{d4,,sqlite3} モジュールは SQLite データベースライブラリのラッパーです。若干非標準の SQL シンタックスを用いて更新や接続出来る永続的なデータベースを提供します。

@item 
国際化に関する機能は、 @ref{67,,gettext}, @ref{8a,,locale}, @ref{1c,,codecs} パッケージといったモジュール群でサポートされています。
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 標準ライブラリミニツアー --- その 2,仮想環境とパッケージ,標準ライブラリミニツアー,Python チュートリアル
@anchor{tutorial/stdlib2 doc}@anchor{20cd}@anchor{tutorial/stdlib2 brief-tour-of-the-standard-library-part-ii}@anchor{20ce}@anchor{tutorial/stdlib2 translation-repo}@anchor{20cf}@anchor{tutorial/stdlib2 tut-brieftourtwo}@anchor{20d0}
@section 標準ライブラリミニツアー --- その 2


ツアーの第2部では、プロフェッショナルプログラミングを支えるもっと高度なモジュールをカバーします。ここで挙げるモジュールは、小さなスクリプトの開発ではほとんど使いません。

@menu
* 出力のフォーマット:: 
* 文字列テンプレート:: 
* バイナリデータレコードの操作:: 
* マルチスレッディング: マルチスレッディング<2>. 
* ログ記録:: 
* 弱参照:: 
* リスト操作のためのツール:: 
* 10 進浮動小数演算:: 

@end menu

@node 出力のフォーマット,文字列テンプレート,,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 output-formatting}@anchor{20d1}@anchor{tutorial/stdlib2 tut-output-formatting}@anchor{20d2}
@subsection 出力のフォーマット


@ref{c0,,reprlib} モジュールは、大きなコンテナや、深くネストしたコンテナを省略して表示するバージョンの @ref{1c1,,repr()} を提供しています:

@example
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"@{'a', 'c', 'd', 'e', 'f', 'g', ...@}"
@end example

@ref{b3,,pprint} モジュールは、組み込み型やユーザ定義型をわかりやすく表示するための洗練された制御手段を提供しています。表示結果が複数行にわたる場合は、 "pretty printer" と呼ばれるものが改行やインデントを追加して、データ構造がより明確になるように印字します:

@example
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
...     'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
   'white',
   ['green', 'red']],
  [['magenta', 'yellow'],
   'blue']]]
@end example

@ref{f2,,textwrap} モジュールは、段落で構成された文章を、指定したスクリーン幅にぴったり収まるように調整します:

@example
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
@end example

@ref{8a,,locale} モジュールは、文化により異なるデータ表現形式のデータベースにアクセスします。 @ref{8a,,locale} の @ref{199,,format()} 関数の grouping 属性を使えば、数値を適切な桁区切り文字によりグループ化された形式に変換できます:

@example
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv()          # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format_string("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
...                      conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
@end example

@node 文字列テンプレート,バイナリデータレコードの操作,出力のフォーマット,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 templating}@anchor{20d3}@anchor{tutorial/stdlib2 tut-templating}@anchor{20d4}
@subsection 文字列テンプレート


@ref{d8,,string} モジュールには、柔軟で、エンドユーザが簡単に編集できる簡単な構文を備えた @ref{897,,Template} クラスが入っています。このクラスを使うと、ユーザがアプリケーションを修正することなしにアプリケーションの出力をカスタマイズできるようになります。

テンプレートでは、@code{$} と有効な Python 識別子名 (英数字とアンダースコア) からなるプレースホルダ名を使います。プレースホルダの周りを @{@} で囲えば、プレースホルダの後ろにスペースを挟まず、英数文字を続けることができます。@code{$$} のようにすると、@code{$} 自体をエスケープできます:

@example
>>> from string import Template
>>> t = Template('$@{village@}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
@end example

@ref{20d5,,substitute()} メソッドは、プレースホルダに相当する値が辞書やキーワード引数にない場合に @ref{5e7,,KeyError} を送出します。メールマージ機能のようなアプリケーションの場合、ユーザが入力するデータは不完全なことがあるので、欠落したデータがあるとプレースホルダをそのままにして出力する @ref{20d6,,safe_substitute()} メソッドを使う方が適切かもしれません:

@example
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
  ...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
@end example

区切り文字はデフォルトは @code{$} ですが、@ref{897,,Template} のサブクラスを派生すると変更することができます。例えば、画像ブラウザ用に一括で名前を変更するユーティリティを作っていたとして、現在の日付や画像のシーケンス番号、ファイル形式といったプレースホルダにパーセント記号を使うことにしたら、次のようになります:

@example
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
...     delimiter = '%'
...
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')
Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f

>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
...     base, ext = os.path.splitext(filename)
...     newname = t.substitute(d=date, n=i, f=ext)
...     print('@{0@} --> @{1@}'.format(filename, newname))

img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
@end example

テンプレートのもう一つの用途は、複数ある出力フォーマットからのプログラムロジックの分離です。これにより、XMLファイル用、プレーンテキストのレポート用、HTMLのwebレポート用のテンプレートに、同じプログラムロジックから値を埋め込むことができます。

@node バイナリデータレコードの操作,マルチスレッディング<2>,文字列テンプレート,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 tut-binary-formats}@anchor{20d7}@anchor{tutorial/stdlib2 working-with-binary-data-record-layouts}@anchor{20d8}
@subsection バイナリデータレコードの操作


@ref{db,,struct} モジュールでは、様々な長さのバイナリレコード形式を操作する @ref{148e,,pack()} や @ref{185a,,unpack()} といった関数を提供しています。 以下の例では、 @ref{137,,zipfile} モジュールを使わずに、ZIP ファイルのヘッダ情報を巡回する方法を示しています。@code{"H"}  と @code{"I"} というパック符号は、それぞれ2バイトと4バイトの符号無し 整数を表しています。 @code{"<"} は、そのパック符号が standard サイズであり、バイトオーダーがリトルエンディアンであることを示しています:

@example
import struct

with open('myfile.zip', 'rb') as f:
    data = f.read()

start = 0
for i in range(3):                      # show the first 3 file headers
    start += 14
    fields = struct.unpack('<IIIHH', data[start:start+16])
    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

    start += 16
    filename = data[start:start+filenamesize]
    start += filenamesize
    extra = data[start:start+extra_size]
    print(filename, hex(crc32), comp_size, uncomp_size)

    start += extra_size + comp_size     # skip to the next header
@end example

@node マルチスレッディング<2>,ログ記録,バイナリデータレコードの操作,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 multi-threading}@anchor{20d9}@anchor{tutorial/stdlib2 tut-multi-threading}@anchor{20da}
@subsection マルチスレッディング


スレッド処理 (threading) とは、順序的な依存関係にない複数のタスクを分割するテクニックです。スレッドは、ユーザの入力を受け付けつつ、背後で別のタスクを動かすようなアプリケーションの応答性を高めます。同じような使用例として、I/O を別のスレッドの計算処理と並列して動作させるというものがあります。

以下のコードでは、高水準のモジュール @ref{f3,,threading} でメインのプログラムを動かしながら背後で別のタスクを動作させられるようにする方法を示しています:

@example
import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)

background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')

background.join()    # Wait for the background task to finish
print('Main program waited until background was done.')
@end example

マルチスレッドアプリケーションを作る上で最も難しい問題は、データやリソースを共有するスレッド間の調整 (coordination)です。この問題を解決するため、@ref{f3,,threading} モジュールではロックやイベント、状態変数、セマフォといった数々の同期プリミティブを提供しています。

こうしたツールは強力な一方、ちょっとした設計上の欠陥で再現困難な問題を引き起こすことがあります。したがって、タスク間調整では @ref{bb,,queue} モジュールを使って他の複数のスレッドからのリクエストを一つのスレッドに送り込み、一つのリソースへのアクセスをできるだけ一つのスレッドに集中させるほうが良いでしょう。スレッド間の通信や調整に @ref{15ac,,Queue} オブジェクトを使うと、設計が容易になり、可読性が高まり、信頼性が増します。

@node ログ記録,弱参照,マルチスレッディング<2>,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 logging}@anchor{20db}@anchor{tutorial/stdlib2 tut-logging}@anchor{20dc}
@subsection ログ記録


@ref{8b,,logging} モジュールでは、数多くの機能をそなえた柔軟性のあるログ記録システムを提供しています。最も簡単な使い方では、ログメッセージをファイルや @code{sys.stderr} に送信します:

@example
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
@end example

これは以下の出力を生成します:

@example
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
@end example

デフォルトでは、@ref{20dd,,info()} と @ref{102b,,debug()} による出力は抑制され、出力は標準エラーに送信されます。選択可能な送信先には、email、データグラム、ソケット、HTTP サーバへの送信などがあります。新たにフィルタを作成すると、@ref{20de,,DEBUG}、@ref{20df,,INFO}、@ref{20e0,,WARNING}、@ref{20e1,,ERROR}、@ref{20e2,,CRITICAL} といったメッセージのプライオリティによって異なる送信先を選択することができます。

ログ記録システムは Python から直接設定することもできますし、アプリケーションを変更しなくてもカスタマイズできるよう、ユーザが編集可能な設定ファイルによって設定することもできます。

@node 弱参照,リスト操作のためのツール,ログ記録,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 tut-weak-references}@anchor{20e3}@anchor{tutorial/stdlib2 weak-references}@anchor{20e4}
@subsection 弱参照


Python は自動的にメモリを管理します (ほとんどのオブジェクトは参照カウント方式で管理し、 @ref{17d8,,ガベージコレクション} で循環参照を除去します)。オブジェクトに対する最後の参照がなくなってしばらくするとメモリは解放されます。

このようなアプローチはほとんどのアプリケーションでうまく動作しますが、中にはオブジェクトをどこか別の場所で利用している間だけ追跡しておきたい場合もあります。残念ながら、オブジェクトを追跡するだけでオブジェクトに対する恒久的な参照を作ることになってしまいます。 @ref{11a,,weakref} モジュールでは、オブジェクトへの参照を作らずに追跡するためのツールを提供しています。弱参照オブジェクトが不要になると、弱参照 (weakref) テーブルから自動的に除去され、コールバック関数がトリガされます。弱参照を使う典型的な応用例には、作成コストの大きいオブジェクトのキャッシュがあります:

@example
>>> import weakref, gc
>>> class A:
...     def __init__(self, value):
...         self.value = value
...     def __repr__(self):
...         return str(self.value)
...
>>> a = A(10)                   # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a            # does not create a reference
>>> d['primary']                # fetch the object if it is still alive
10
>>> del a                       # remove the one reference
>>> gc.collect()                # run garbage collection right away
0
>>> d['primary']                # entry was automatically removed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    d['primary']                # entry was automatically removed
  File "C:/python314/lib/weakref.py", line 46, in __getitem__
    o = self.data[key]()
KeyError: 'primary'
@end example

@node リスト操作のためのツール,10 進浮動小数演算,弱参照,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 tools-for-working-with-lists}@anchor{20e5}@anchor{tutorial/stdlib2 tut-list-tools}@anchor{20e6}
@subsection リスト操作のためのツール


多くのデータ構造は、組み込みリスト型を使った実装で事足ります。とはいえ、時には組み込みリストとは違うパフォーマンス上のトレードオフを持つような実装が必要になこともあります。

@ref{8,,array} (配列) モジュールでは、@ref{4be,,array} オブジェクトを提供しています。配列はリストに似ていますが、同種のデータのみを よりコンパクトに格納します。  以下の例に示すのは、通常 1 要素あたり 16 バイト使う Python の int オブジェクトのリストではなく、2 バイト使う符号無しバイナリ整数 (タイプコード @code{"H"}) の配列です:

@example
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
@end example

@ref{1e,,collections} モジュールでは、 @ref{7f4,,deque} オブジェクトを提供しています。リスト型に似ていますが、データの追加と左端からの取り出しが速く、その一方で中間にある値の参照は遅くなります。こうしたオブジェクトはキューや木構造の幅優先探索の実装に向いています:

@example
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
@end example

@example
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
    node = unsearched.popleft()
    for m in gen_moves(node):
        if is_goal(m):
            return m
        unsearched.append(m)
@end example

リストの代わりの実装以外にも、標準ライブラリにはソート済みのリストを操作するための関数を備えた @ref{12,,bisect} のようなツールも提供しています:

@example
>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
@end example

@ref{6d,,heapq} モジュールは、通常のリストでヒープを実装するための関数を提供しています。ヒープでは、最も低い値をもつエントリがつねにゼロの位置に配置されます。ヒープは、毎回リストをソートすることなく、最小の値をもつ要素に繰り返しアクセスするようなアプリケーションで便利です:

@example
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data)                      # rearrange the list into heap order
>>> heappush(data, -5)                 # add a new entry
>>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
[-5, 0, 1]
@end example

@node 10 進浮動小数演算,,リスト操作のためのツール,標準ライブラリミニツアー --- その 2
@anchor{tutorial/stdlib2 decimal-floating-point-arithmetic}@anchor{20e7}@anchor{tutorial/stdlib2 tut-decimal-fp}@anchor{20e8}
@subsection 10 進浮動小数演算


@ref{3a,,decimal} モジュールでは、 10 進浮動小数の算術演算をサポートする @ref{1fe,,Decimal} データ型を提供しています。組み込みの 2 進浮動小数の実装である @ref{196,,float} に比べて、このクラスがとりわけ便利なのは、以下の場合です


@itemize *

@item 
財務アプリケーションやその他の正確な10進表記が必要なアプリケーション、

@item 
精度の制御、

@item 
法的または規制上の理由に基づく値丸めの制御、

@item 
有効桁数の追跡が必要になる場合

@item 
ユーザが手計算の結果と同じ演算結果を期待するようなアプリケーション。
@end itemize

例えば、70 セントの電話代にかかる 5% の税金を計算しようとすると、10 進の浮動小数点値と 2 進の浮動小数点値では違う結果になってしまいます。計算結果を四捨五入してセント単位にしようとすると、以下のように違いがはっきり現れます:

@example
>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73
@end example

上の例で、@ref{1fe,,Decimal} を使った計算では、末尾桁のゼロが保存されており、有効数字2桁の被乗数から自動的に有効数字を 4 桁と判断しています。@ref{1fe,,Decimal} は手計算と 同じ方法で計算を行い、2 進浮動小数が 10 進小数成分を正確に表現できないことに よって起きる問題を回避しています。

@ref{1fe,,Decimal} クラスは厳密な値を表現できるため、2 進浮動小数点数では 期待通りに計算できないような剰余の計算や等値テストも実現できます:

@example
>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995

>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0
False
@end example

@ref{3a,,decimal} モジュールを使うと、必要なだけの精度で算術演算を行えます:

@example
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 仮想環境とパッケージ,さあ何を？,標準ライブラリミニツアー --- その 2,Python チュートリアル
@anchor{tutorial/venv doc}@anchor{20e9}@anchor{tutorial/venv translation-repo}@anchor{20ea}@anchor{tutorial/venv tut-venv}@anchor{20eb}@anchor{tutorial/venv virtual-environments-and-packages}@anchor{20ec}
@section 仮想環境とパッケージ


@menu
* はじめに: はじめに<4>. 
* 仮想環境の作成:: 
* pip を使ったパッケージ管理:: 

@end menu

@node はじめに<4>,仮想環境の作成,,仮想環境とパッケージ
@anchor{tutorial/venv introduction}@anchor{20ed}
@subsection はじめに


Python アプリケーションはよく標準ライブラリ以外のパッケージやモジュールを利用します。またアプリケーションがあるバグ修正を必要としていたり、過去のバージョンのインターフェイスに依存しているために、ライブラリの特定のバージョンを必要とすることもあります。

そのため、1つのインストールされたPythonが全てのアプリケーションの要求に対応することは不可能です。もしアプリケーションAがあるモジュールのバージョン 1.0 を要求していて、別のアプリケーションBが同じモジュールのバージョン 2.0 を要求している場合、2つの要求は衝突していて、1.0 と 2.0 のどちらかのバージョンをインストールしても片方のアプリケーションが動きません。

この問題の解決策は @ref{20ee,,仮想環境} を作ることです。仮想環境とは、特定のバージョンの Python と幾つかの追加パッケージを含んだ Python インストールを構成するディレクトリです。

別のアプリケーションはそれぞれ別の仮想環境を使うことができます。先の例にあった要求の衝突を解決する場合、アプリケーションAが固有の仮想環境を持ってそこにライブラリのバージョン 1.0 をインストールし、アプリケーションBが持つ別の仮想環境にライブラリのバージョン 2.0 をインストールすることができます。そしてアプリケーションBがライブラリのバージョンを 3.0 に更新することを要求する場合も、アプリケーションAに影響しません。

@node 仮想環境の作成,pip を使ったパッケージ管理,はじめに<4>,仮想環境とパッケージ
@anchor{tutorial/venv creating-virtual-environments}@anchor{20ef}
@subsection 仮想環境の作成


仮想環境の作成・管理に使われるモジュールは、 @ref{117,,venv} と呼ばれます。 @ref{117,,venv} は、コマンドが実行された Python のバージョン (@ref{f17,,--version} オプションで表示される) をインストールします。例えば、 @code{python3.12} でコマンドを実行すると、バージョン 3.12 がインストールされます。

仮想環境を作るには、仮想環境を置くディレクトリを決めて、 そのディレクトリのパスを指定して、 @ref{117,,venv} をスクリプトとして実行します:

@example
python -m venv tutorial-env
@end example

これは @code{tutorial-env} ディレクトリがなければ作成して、その中に Python インタプリタ、その他関連するファイルのコピーを含むサブディレクトリを作ります。

仮想環境の一般的なディレクトリの場所は @code{.venv} です。この名前は、通常はシェルで隠されているため、ディレクトリが存在する理由を説明する名前を付けても、邪魔にはなりません。また、一部のツールでサポートされている @code{.env} 環境変数定義ファイルによるクラッシュも防止します。

仮想環境を作ったら、それを有効化する必要があります。

Windows の場合:

@example
tutorial-env\Scripts\activate
@end example

Unix や Mac OS の場合:

@example
source tutorial-env/bin/activate
@end example

(このスクリプトは bash shell で書かれています。 @code{csh} や @code{fish} を利用している場合、代わりに利用できる @code{activate.csh} と @code{activate.fish} スクリプトがあります。)

仮想環境を有効化すると、シェルのプロンプトに利用中の仮想環境が表示されるようになり、@code{python} を実行するとその仮想環境の Python を実行するようになります:

@example
$ source ~/envs/tutorial-env/bin/activate
(tutorial-env) $ python
Python 3.5.1 (default, May  6 2016, 10:59:36)
  ...
>>> import sys
>>> sys.path
['@w{'}, '/usr/local/lib/python35.zip', ...,
'~/envs/tutorial-env/lib/python3.5/site-packages']
>>>
@end example

仮想環境を無効化するには、ターミナルに:

@example
deactivate
@end example

と入力します。

@node pip を使ったパッケージ管理,,仮想環境の作成,仮想環境とパッケージ
@anchor{tutorial/venv managing-packages-with-pip}@anchor{20f0}
@subsection pip を使ったパッケージ管理


　@code{pip} と呼ばれるプログラムでパッケージをインストール、アップグレード、削除することができます。デフォルトでは @code{pip} は Python Package Index@footnote{https://pypi.org} からパッケージをインストールします。ブラウザを使って Python Package Index を閲覧することができます。

@code{pip} は "install" 、 "uninstall" 、 "freeze" など、いくつかのサブコマンドを持っています。 (@code{pip} の完全なドキュメントは @ref{10f8,,Python モジュールのインストール} ガイドを参照してください。)

パッケージ名を指定してそのパッケージの最新版をインストールすることができます:

@example
(tutorial-env) $ python -m pip install novas
Collecting novas
  Downloading novas-3.1.1.3.tar.gz (136kB)
Installing collected packages: novas
  Running setup.py install for novas
Successfully installed novas-3.1.1.3
@end example

パッケージ名のあとに @code{==} とバージョン番号を付けることで、特定のバージョンのパッケージをインストールすることもできます:

@example
(tutorial-env) $ python -m pip install requests==2.6.0
Collecting requests==2.6.0
  Using cached requests-2.6.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.6.0
@end example

同じコマンドを再び実行した場合、@code{pip} は要求されたバージョンがインストール済みだと表示して何もしません。別のバージョン番号を指定すればそのバージョンをインストールしますし、@code{python -m pip install --upgrade} を実行すればそのパッケージを最新版に更新します:

@example
(tutorial-env) $ python -m pip install --upgrade requests
Collecting requests
Installing collected packages: requests
  Found existing installation: requests 2.6.0
    Uninstalling requests-2.6.0:
      Successfully uninstalled requests-2.6.0
Successfully installed requests-2.7.0
@end example

@code{python -m pip uninstall} コマンドに削除するパッケージ名を1つ以上指定します。

@code{python -m pip show} は指定されたパッケージの情報を表示します:

@example
(tutorial-env) $ python -m pip show requests
---
Metadata-Version: 2.0
Name: requests
Version: 2.7.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@@kennethreitz.com
License: Apache 2.0
Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
Requires:
@end example

@code{python -m pip list} は仮想環境にインストールされた全てのパッケージを表示します:

@example
(tutorial-env) $ python -m pip list
novas (3.1.1.3)
numpy (1.9.2)
pip (7.0.3)
requests (2.7.0)
setuptools (16.0)
@end example

@code{python -m pip freeze} はインストールされたパッケージ一覧を、@code{python -m pip install} が解釈するフォーマットで生成します。一般的な慣習として、このリストを @code{requirements.txt} というファイルに保存します:

@example
(tutorial-env) $ python -m pip freeze > requirements.txt
(tutorial-env) $ cat requirements.txt
novas==3.1.1.3
numpy==1.9.2
requests==2.7.0
@end example

@code{requirements.txt} をバージョン管理システムにコミットして、アプリケーションの一部として配布することができます。ユーザーは必要なパッケージを @code{install -r} でインストールできます:

@example
(tutorial-env) $ python -m pip install -r requirements.txt
Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))
  ...
Collecting numpy==1.9.2 (from -r requirements.txt (line 2))
  ...
Collecting requests==2.7.0 (from -r requirements.txt (line 3))
  ...
Installing collected packages: novas, numpy, requests
  Running setup.py install for novas
Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0
@end example

@code{pip} にはたくさんのオプションがあります。 @code{pip} の完全なドキュメントは @ref{10f8,,Python モジュールのインストール} を参照してください。パッケージを作成してそれを Python Package Index で公開したい場合、 Python packaging user guide@footnote{https://packaging.python.org/en/latest/tutorials/packaging-projects/} を参照してください。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node さあ何を？,対話入力編集と履歴置換,仮想環境とパッケージ,Python チュートリアル
@anchor{tutorial/whatnow doc}@anchor{20f1}@anchor{tutorial/whatnow translation-repo}@anchor{20f2}@anchor{tutorial/whatnow tut-whatnow}@anchor{20f3}@anchor{tutorial/whatnow what-now}@anchor{20f4}
@section さあ何を？


このチュートリアルを読んだことで、おそらく Python を使ってみようという関心はますます強くなったことでしょう --- 現実世界の問題を解決するために、Python を適用してみたくなったはずです。さて、それではどこで勉強をしたらよいのでしょうか？

このチュートリアルは Python のドキュメンテーションセットの一部です。セットの中の他のドキュメンテーションをいくつか紹介します:


@itemize *

@item 
@ref{149,,Python 標準ライブラリ}:

このマニュアルをざっと眺めておくと便利です。このマニュアルは型、関数、標準ライブラリのモジュールについての完全なリファレンスです。標準的なPython配布物は `たくさんの' 追加コードを含んでいます。Unix メールボックスの読み込み、HTTPによるドキュメント取得、乱数の生成、コマンドラインオプションの構文解析、データ圧縮やその他たくさんのタスクのためのモジュールがあります。ライブラリリファレンスをざっと見ることで、何が利用できるかのイメージをつかむことができます。

@item 
@ref{10f8,,Python モジュールのインストール} は、他のPythonユーザによって書かれた追加モジュールをどうやってインストールするかを説明しています。

@item 
@ref{14a,,Python 言語リファレンス}: Pythonの文法とセマンティクスを詳しく説明しています。読むのは大変ですが、言語の完全なガイドとして有用です。
@end itemize

さらなる Python に関するリソース:


@itemize *

@item 
@indicateurl{https://www.python.org}: 有名なPythonのWebサイト。コードやドキュメント、Pythonに関するWebページへのポインターを含んでいます。

@item 
@indicateurl{https://docs.python.org}: Pythonドキュメントへの素早いアクセスを提供します。

@item 
@indicateurl{https://pypi.org}:  Python パッケージインデックス、以前は Cheese Shop @footnote{
"Cheese Shop" is a Monty Python sketch: a customer enters a cheese shop,
but whatever cheese he asks for, the clerk says it's missing.
} という愛称でも呼ばれていました。これは、ユーザ作成のダウンロードできる Python モジュールの索引です。コードのリリースをしたら、ここに登録することで他の人が見つけられます。

@item 
@indicateurl{https://code.activestate.com/recipes/langs/python/}: Python クックブックはコード例、モジュール、実用的なスクリプトの巨大なコレクションです。主要なものは同名の本Python Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3)に収録されています。

@item 
@indicateurl{https://pyvideo.org} は学会やユーザグループの会合から Python 関連のビデオのリンクを集めています。

@item 
@indicateurl{https://scipy.org}: Scientific Python プロジェクトは配列の高速な計算・操作モジュールに加え、線形代数、フーリエ変換、非線形ソルバー、乱数分布、統計分析などの多くのパッケージを提供しています。
@end itemize

Python 関連の質問や問題の報告については、ニュースグループ @code{comp.lang.python} に投稿するか、またはメーリングリスト @email{python-list@@python.org} に送ることができます。ニュースグループとメーリングリストはゲートウェイされます。したがって、片方に投稿されたメッセージは、もう片方へ自動的に転送されます。質問(と回答)、新しい機能の提案、新しいモジュールの発表などで、1日に数百通の投稿があります。メーリングリストのアーカイブは @indicateurl{https://mail.python.org/pipermail/} で利用可能です。

投稿の前に、必ず @ref{20f5,,よくある質問} (FAQとも呼ばれます) のリストをチェックしてください。 FAQ は繰り返し取り上げられる多くの質問に答えています。あなたの問題に対する解決が既に含まれているかもしれません。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 対話入力編集と履歴置換,浮動小数点演算、その問題と制限,さあ何を？,Python チュートリアル
@anchor{tutorial/interactive doc}@anchor{20f6}@anchor{tutorial/interactive interactive-input-editing-and-history-substitution}@anchor{20f7}@anchor{tutorial/interactive translation-repo}@anchor{20f8}@anchor{tutorial/interactive tut-interacting}@anchor{1fcb}
@section 対話入力編集と履歴置換


いくつかのバージョンの Python インタプリタでは、Korn シェルや GNU Bash シェルに見られる機能に似た、現在の入力行に対する編集機能や履歴置換機能をサポートしています。この機能は様々な編集スタイルをサポートしている、GNU Readline@footnote{https://tiswww.case.edu/php/chet/readline/rltop.html} ライブラリを使って実装されています。このライブラリには独自のドキュメントがあり、ここでそれを繰り返すつもりはありません。

@menu
* タブ補完と履歴編集:: 
* 対話的インタープリタの代替:: 

@end menu

@node タブ補完と履歴編集,対話的インタープリタの代替,,対話入力編集と履歴置換
@anchor{tutorial/interactive tab-completion-and-history-editing}@anchor{20f9}@anchor{tutorial/interactive tut-keybindings}@anchor{20fa}
@subsection タブ補完と履歴編集


変数とモジュール名の補完はインタプリタの起動時に @ref{11cb,,自動的に有効化されます} 。 従って @code{Tab} キーは補完機能を呼び出し、Python の文の名前、現在のローカル変数、および利用可能なモジュール名を検索します。 @code{string.a} のようなドットで区切られた式については、最後の @code{'.'} までの式を評価し、結果として得られたオブジェクトの属性から補完候補を示します。 @ref{6fa,,__getattr__()} メソッドを持ったオブジェクトが式に含まれている場合、 @ref{6fa,,__getattr__()} がアプリケーション定義のコードを実行するかもしれないので注意してください。デフォルトの設定ではあなたのユーザーディレクトリの @code{.python_history} という名前のファイルに履歴を保存します。 履歴は次回の対話的なインタプリタのセッションで再び利用することができます。

@node 対話的インタープリタの代替,,タブ補完と履歴編集,対話入力編集と履歴置換
@anchor{tutorial/interactive alternatives-to-the-interactive-interpreter}@anchor{20fb}@anchor{tutorial/interactive tut-commentary}@anchor{20fc}
@subsection 対話的インタープリタの代替


この機能は、初期の版のインタープリタに比べれば大きな進歩です。とはいえ、まだいくつかの要望が残されています。例えば、行を継続するときに正しいインデントが提示されたら快適でしょう (パーサは次の行で @ref{20fd,,INDENT} トークンが必要かどうかを知っています)。補完機構がインタープリタのシンボルテーブルを使ってもよいかもしれません。括弧やクォートなどの対応をチェックする (あるいは指示する) コマンドも有用でしょう。

より優れた対話的インタープリタの代替の一つに IPython@footnote{https://ipython.org/} があります。このインタープリタは、様々なところで使われていて、タブ補完、オブジェクト探索や先進的な履歴管理といった機能を持っています。他のアプリケーションにカスタマイズされたり、組込まれこともあります。別の優れたインタラクティブ環境としては bpython@footnote{https://bpython-interpreter.org/} があります。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c import math
@c from fractions import Fraction

@node 浮動小数点演算、その問題と制限,付録,対話入力編集と履歴置換,Python チュートリアル
@anchor{tutorial/floatingpoint doc}@anchor{20fe}@anchor{tutorial/floatingpoint floating-point-arithmetic-issues-and-limitations}@anchor{20ff}@anchor{tutorial/floatingpoint translation-repo}@anchor{2100}@anchor{tutorial/floatingpoint tut-fp-issues}@anchor{2101}
@section 浮動小数点演算、その問題と制限


浮動小数点数はコンピューターのハードウェア上は2進数(binary)の分数で表されます。
たとえば、`10進数' の分数では @code{0.625} は 6/10 + 2/100 + 5/1000 という値を持ち、`2進数' の分数では @code{0.101} は 1/2 + 0/4 + 1/8 という値を持ちます。
この2つの分数はまったく同じ値を持ち、唯一異なる点は1つ目が10進数の分数で書かれており、2つ目は2進数の分数で書かれているということです。

残念なことに、ほとんどの小数は 2 進法の分数として正確に表わすことができません。その結果、一般に、入力した 10 進の浮動小数点数は、 2 進法の浮動小数点数で近似された後、実際にマシンに記憶されます。

最初は基数 10 を使うと問題を簡単に理解できます。分数 1/3 を考えてみましょう。分数 1/3 は、基数 10 の分数として、以下のように近似することができます:

@example
0.3
@end example

さらに正確な近似は、

@example
0.33
@end example

さらに正確な近似は、

@example
0.333
@end example

となり、以後同様です。何個桁数を増やして書こうが、結果は決して厳密な 1/3 にはなりません。しかし、少しづつ正確な近似にはなっていくでしょう。

同様に、基数を 2 とした表現で何桁使おうとも、10 進数の 0.1 は基数を 2 とした小数で正確に表現することはできません。基数 2 では、1/10 は循環小数 (repeating fraction) となります

@example
0.0001100110011001100110011001100110011001100110011...
@end example

どこか有限の桁で止めると、近似値を得ることになります。近年の殆どのコンピュータでは float 型は、最上位ビットから数えて最初の 53 ビットを分子、2 の冪乗を分母とした、二進小数で近似されます。1/10 の場合は、二進小数は @code{3602879701896397 / 2 ** 55} となります。これは、1/10 に近いですが、厳密に同じ値ではありません。

値が表示される方法のために、ほとんどのユーザは、近似に気づきません。Python はマシンに格納されている二進近似値の10進小数での近似値を表示するので、格納されている値が元の10進小数の近似値でしか無いことを忘れがちです。ほとんどのマシンで、もし Python が2進数で近似された 0.1 の近似値をそのまま10進数で表示していたら、その結果は次のようになったでしょう:

@example
>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
@end example

これは、ほとんどの人が必要と感じるよりも多すぎる桁数です。なので、Python は丸めた値を表示することで、桁数を扱いやすい範囲にとどめます:

@example
>>> 1 / 10
0.1
@end example

表示された結果が正確に 1/10 であるように見えたとしても、実際に格納されている値は最も近く表現できる二進小数であるということだけは覚えておいてください。

幾つかの異なる10進数の値が、同じ2進有理数の近似値を共有しています。例えば、@code{0.1} と @code{0.10000000000000001} と @code{0.1000000000000000055511151231257827021181583404541015625} はどれも @code{3602879701896397 / 2 ** 55} に近似されます。同じ近似値を共有しているので、どの10進数の値も @code{eval(repr(x)) == x} という条件を満たしたまま同じように表示されます。

昔の Python は、プロンプトと @ref{1c1,,repr()} ビルトイン関数は 17 桁の有効数字を持つ @code{0.10000000000000001} のような10進数の値を選んで表示していました。 Python 3.1 からは、ほとんどの場面で @code{0.1} のような最も短い桁数の10進数の値を選ぶようになりました。

この動作は2進数の浮動小数点にとってはごく自然なものです。これは Python のバグではありませんし、あなたのコードのバグでもありません。ハードウェアの浮動小数点演算をサポートしている全ての言語で同じ種類の問題を見つけることができます (いくつかの言語ではデフォルトの、あるいはどの出力モードを選んでも、この差を `表示' しないかもしれませんが)。

よりよい出力のために、文字列フォーマットを利用して有効桁数を制限した10進数表現を得ることができます:

@example
>>> format(math.pi, '.12g')  # give 12 significant digits
'3.14159265359'

>>> format(math.pi, '.2f')   # give 2 digits after the point
'3.14'

>>> repr(math.pi)
'3.141592653589793'
@end example

これが、実際のコンピューター上の値の `表示' を丸めているだけの、いわば錯覚だということを認識しておいてください。

もう一つの錯覚を紹介します。例えば、0.1 が正確には 1/10 ではないために、それを3回足した値もまた正確には 0.3 ではありません:

@example
>>> 0.1 + 0.1 + 0.1 == 0.3
False
@end example

0.1 はこれ以上 1/10 に近くなることができない値で、 0.3 もまた 3/10 に一番近い値なので、 @ref{14f2,,round()} 関数を使って計算前に丸めを行なっても意味がありません:

@example
>>> round(0.1, 1) + round(0.1, 1) + round(0.1, 1) == round(0.3, 1)
False
@end example

数値を意図した正確な値に近づけることはできませんが、 @ref{fb0,,math.isclose()} 関数は不正確な値を比べるのに便利です:

@example
>>> math.isclose(0.1 + 0.1 + 0.1, 0.3)
True
@end example

あるいは、 @ref{14f2,,round()} 関数を粗い近似値比較に使うこともできます:

@example
>>> round(math.pi, ndigits=2) == round(22 / 7, ndigits=2)
True
@end example

このように2進数の浮動小数点の演算には多くの驚きがあります。「0.1」の問題について詳しい説明は、「表現エラー」セクションで行います。2進数の浮動小数点の仕組みと、実際によく遭遇する問題各種についての分かりやすい概要は、 Examples of Floating Point Problems@footnote{https://jvns.ca/blog/2023/01/13/examples-of-floating-point-problems/} を参照してください。その他よくある驚きの より詳細な説明は The Perils of Floating Point@footnote{http://www.indowsway.com/floatingpoint.htm} も参照してください。

究極的にいうと、"容易な答えはありません"。ですが、浮動小数点数のことを過度に警戒しないでください！ Python の float 型操作におけるエラーは浮動小数点処理ハードウェアから受けついたものであり、ほとんどのマシン上では一つの演算あたり高々 2**53 分の 1 です。この誤差はほとんどの作業で充分以上のものですが、浮動小数点演算は 10 進の演算ではなく、浮動小数点の演算を新たに行うと、新たな丸め誤差の影響を受けることを心にとどめておいてください。

異常なケースが存在する一方で、普段の浮動小数点演算の利用では、単に最終的な結果の値を必要な 10 進の桁数に丸めて表示するのなら、最終的には期待通りの結果を得ることになるでしょう。たいては @ref{169,,str()} で十分ですが、きめ細かな制御をしたければ、 @ref{15b3,,書式指定文字列の文法} にある @ref{833,,str.format()} メソッドのフォーマット仕様を参照してください。

正確な10進数表現が必要となるような場合には、 @ref{3a,,decimal} モジュールを利用してみてください。このモジュールは会計アプリケーションや高精度の計算が求められるアプリケーションに適した、10進数の計算を実装しています。

別の正確な計算方法として、 @ref{61,,fractions} モジュールが有理数に基づく計算を実装しています (1/3 のような数を正確に表すことができます)。

あなたが浮動小数点演算のヘビーユーザーなら、SciPy プロジェクトが提供している NumPy パッケージやその他の数学用パッケージを調べてみるべきです。 <@indicateurl{https://scipy.org}> を参照してください。

Python は `本当に' float の正確な値が必要なレアケースに対応するためのツールを提供しています。 @ref{2102,,float.as_integer_ratio()} メソッドは float の値を有理数として表現します:

@example
>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)
@end example

この分数は正確なので、元の値を完全に復元することができます:

@example
>>> x == 3537115888337719 / 1125899906842624
True
@end example

@ref{2103,,float.hex()} メソッドは float の値を16進数で表現します。この値もコンピューターが持っている正確な値を表現できます:

@example
>>> x.hex()
'0x1.921f9f01b866ep+1'
@end example

この正確な16進数表現はもとの float 値を正確に復元するために使うことができます:

@example
>>> x == float.fromhex('0x1.921f9f01b866ep+1')
True
@end example

この16進数表現は正確なので、値を (プラットフォームにも依存せず) バージョンの異なるPython 間でやり取りしたり、他のこのフォーマットをサポートした言語 (Java や C99 など) と正確にやり取りするのに利用することができます。

別の便利なツールとして、合計処理における精度のロスを緩和してくれる @ref{695,,sum()} 関数があります。これは累計加算中の丸めに拡張精度を使います。これにより、誤差が最終的な合計値に影響を与えるまで蓄積されなくなり、結果が改善されます:

@example
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0
False
>>> sum([0.1] * 10) == 1.0
True
@end example

The @ref{15ed,,math.fsum()} goes further and tracks all of the "lost digits"
as values are added onto a running total so that the result has only a
single rounding.  This is slower than @ref{695,,sum()} but will be more
accurate in uncommon cases where large magnitude inputs mostly cancel
each other out leaving a final sum near zero:

@example
>>> arr = [-0.10430216751806065, -266310978.67179024, 143401161448607.16,
...        -143401161400469.7, 266262841.31058735, -0.003244936839808227]
>>> float(sum(map(Fraction, arr)))   # Exact summation with single rounding
8.042173697819788e-13
>>> math.fsum(arr)                   # Single rounding
8.042173697819788e-13
>>> sum(arr)                         # Multiple roundings in extended precision
8.042178034628478e-13
>>> total = 0.0
>>> for x in arr:
...     total += x                   # Multiple roundings in standard precision
...
>>> total                            # Straight addition has no correct digits!
-0.0051575902860057365
@end example

@menu
* 表現エラー:: 

@end menu

@node 表現エラー,,,浮動小数点演算、その問題と制限
@anchor{tutorial/floatingpoint representation-error}@anchor{2104}@anchor{tutorial/floatingpoint tut-fp-error}@anchor{2105}
@subsection 表現エラー


この章では、"0.1" の例について詳細に説明し、このようなケースに対してどのようにすれば正確な分析を自分で行えるかを示します。ここでは、 2 進法表現の浮動小数点数についての基礎的な知識があるものとして話を進めます。

表現エラー(`Representation error')は、いくつかの (実際にはほとんどの) 10 進の小数が 2 進法 (基数 2)の分数として表現できないという事実に関係しています。これは Python (あるいは Perl, C, C++, Java, Fortran. およびその他多く) が期待通りの正確な 10 進数を表示できない主要な理由です。

なぜそうなるのでしょう？ 1/10 は２進法の小数で厳密に表現できません。少なくとも2000年以降、ほぼすべてのマシンは IEEE 754 2進数の浮動小数点演算を用いており、ほぼすべてのプラットフォームでは Python の浮動小数点を IEEE 754 binary64 "倍精度 (double precision)" 値に対応付けます。 IEEE 754 binary64 値は 53 ビットの精度を持つため、計算機に入力を行おうとすると、可能な限り 0.1 を最も近い値の分数に変換し、`J'/2**`N' の形式にしようと努力します。`J' はちょうど 53 ビットの精度の整数です。

@example
1 / 10 ~= J / (2**N)
@end example

を書き直すと

@example
J ~= 2**N / 10
@end example

となります。 `J' は厳密に 53 ビットの精度を持っている (@code{>= 2**52} だが @code{< 2**53} ) ことを思い出すと、 `N' として最適な値は 56 になります:

@example
>>> 2**52 <=  2**56 // 10  < 2**53
True
@end example

すなわち、56 は `J' をちょうど 53 ビットの精度のままに保つ `N' の唯一の値です。`J' の取りえる値はその商を丸めたものです:

@example
>>> q, r = divmod(2**56, 10)
>>> r
6
@end example

剰余が 10 の半分以上なので、最良の近似は切り上げて丸めたものになります。:

@example
>>> q+1
7205759403792794
@end example

従って、IEEE 754の倍精度における 1/10 の取りえる最良の近似は:

@example
7205759403792794 / 2 ** 56
@end example

分子と分母を2で割って分数を小さくします:

@example
3602879701896397 / 2 ** 55
@end example

丸めたときに切り上げたので、この値は実際には 1/10 より少し大きいことに注目してください。
もし切り捨てをした場合は、商は 1/10 よりもわずかに小さくなります。どちらにしろ `厳密な' 1/10 ではありません！

つまり、計算機は 1/10 を "理解する" ことは決してありません。計算機が理解できるのは、上記のような厳密な分数であり、IEEE 754 の倍精度浮動小数点数で得られるもっともよい近似は以下になります:

@example
>>> 0.1 * 2 ** 55
3602879701896397.0
@end example

この分数に 10**55 を掛ければ、55 桁の十進数の値を見ることができます:

@example
>>> 3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625
@end example

これは、計算機が記憶している正確な数値が、10 進数値 0.1000000000000000055511151231257827021181583404541015625 にほぼ等しいということです。多くの言語 (古いバージョンの Python を含む) では、完全な 10 進値を表示するのではなく、結果を有効数字 17 桁に丸めます:

@example
>>> format(0.1, '.17f')
'0.10000000000000001'
@end example

@ref{61,,fractions} モジュールと @ref{3a,,decimal} モジュールを使うとこれらの計算を簡単に行えます:

@example
>>> from decimal import Decimal
>>> from fractions import Fraction

>>> Fraction.from_float(0.1)
Fraction(3602879701896397, 36028797018963968)

>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

>>> format(Decimal.from_float(0.1), '.17')
'0.10000000000000001'
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 付録,,浮動小数点演算、その問題と制限,Python チュートリアル
@anchor{tutorial/appendix doc}@anchor{2106}@anchor{tutorial/appendix appendix}@anchor{2107}@anchor{tutorial/appendix translation-repo}@anchor{2108}@anchor{tutorial/appendix tut-appendix}@anchor{2109}
@section 付録


@menu
* 対話モード: 対話モード<2>. 

@end menu

@node 対話モード<2>,,,付録
@anchor{tutorial/appendix interactive-mode}@anchor{210a}@anchor{tutorial/appendix tut-interac}@anchor{494}
@subsection 対話モード


対話型の @ref{491,,REPL} は2種類あります。  クラシックな基本インタープリタは最低限の行制御機能を持つ全プラットフォームでサポートされています。

Since Python 3.13, a new interactive shell is used by default.
This one supports color, multiline editing, history browsing, and
paste mode.  To disable color, see @ref{1b7,,色の制御} for
details.  Function keys provide some additional functionality.
@code{F1} enters the interactive help browser @ref{ba,,pydoc}.
@code{F2} allows for browsing command-line history with neither output nor the
@ref{492,,>>>} and @ref{493,,...} prompts. @code{F3} enters "paste mode", which
makes pasting larger blocks of code easier. Press @code{F3} to return to
the regular prompt.

新しい対話型シェルでは、 @code{exit} または @code{quit} と打ってシェルを終えます。これらのコマンドの後に呼び出し括弧を追加する必要はありません。

新しい対話型シェルを望まない場合は、環境変数 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL} で無効にできます。

@menu
* エラー処理:: 
* 実行可能な Python スクリプト:: 
* 対話モード用の起動時実行ファイル:: 
* カスタマイズ用モジュール:: 

@end menu

@node エラー処理,実行可能な Python スクリプト,,対話モード<2>
@anchor{tutorial/appendix error-handling}@anchor{210b}@anchor{tutorial/appendix tut-error}@anchor{210c}
@subsubsection エラー処理


エラーが発生すると、インタープリタはエラーメッセージとスタックトレースを表示します。対話モードでは、それから元のプロンプトに戻ります; ファイルから実行した場合は、スタックトレースを表示してゼロ以外の終了ステータスで終了します（@ref{8f8,,try} 文の @ref{1ab,,except} 節で処理された例外は、ここでいうエラーにはあたりません。）一部のエラーは無条件に致命的であり、ゼロ以外の終了ステータスで終了します; これは内部の不整合やある種のメモリ不足の場合に適用されます。エラーメッセージは全て標準エラー出力に書き込まれます; これに対して、通常は実行した命令から出力される内容は標準出力に書き込まれます。

割り込み文字 (interrupt character、普通は @code{Control}-@code{C} か @code{Delete}) を一次または二次プロンプトに対してタイプすると、入力が取り消されて一次プロンプトに戻ります。 @footnote{
GNU Readline パッケージに関する問題のせいで妨げられることがあります。
} コマンドの実行中に割り込み文字をタイプすると @ref{bc5,,KeyboardInterrupt} 例外が送出されます。この例外は @ref{8f8,,try} 文で処理できます。

@node 実行可能な Python スクリプト,対話モード用の起動時実行ファイル,エラー処理,対話モード<2>
@anchor{tutorial/appendix executable-python-scripts}@anchor{210d}@anchor{tutorial/appendix tut-scripts}@anchor{1fd3}
@subsubsection 実行可能な Python スクリプト


BSD 風の Unix システムでは、Python スクリプトはシェルスクリプトのように直接実行可能にできます。これを行うには、以下の行

@example
#!/usr/bin/env python3
@end example

(ここではインタプリタがユーザの 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} 上にあると仮定しています) をスクリプトの先頭に置き、スクリプトファイルに実行可能モードを設定します。 @code{#!} はファイルの最初の２文字でなければなりません。プラットフォームによっては、この最初の行を終端する改行文字が Windows 形式 (@code{'\r\n'}) ではなく、 Unix形式(@code{'\n'})でなければならないことがあります。ハッシュまたはポンド文字、すなわち @code{'#'} は、Python ではコメントを書き始めるために使われていることに注意してください。

@code{chmod} コマンドを使えば、スクリプトに実行モードや実行権限を与えることができます。

@example
$ chmod +x myscript.py
@end example

Windows では、"実行モード" のような概念はありません。Python のインストーラーは自動的に @code{.py} ファイルを @code{python.exe} に関連付けるので、Python ファイルをダブルクリックするとそれをスクリプトとして実行します。@code{.pyw} 拡張子も(訳注: @code{pythonw.exe} に)関連付けられ、通常コンソールウィンドウを抑制して実行します。

@node 対話モード用の起動時実行ファイル,カスタマイズ用モジュール,実行可能な Python スクリプト,対話モード<2>
@anchor{tutorial/appendix the-interactive-startup-file}@anchor{210e}@anchor{tutorial/appendix tut-startup}@anchor{210f}
@subsubsection 対話モード用の起動時実行ファイル


Python を対話的に使うときには、インタプリタが起動する度に実行される何らかの標準的なコマンドがあると便利なことがよくあります。これを行うには、 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} と呼ばれる環境変数を、インタプリタ起動時に実行されるコマンドが入ったファイル名に設定します。この機能は Unix シェルの @code{.profile} に似ています。

このファイルは対話セッションのときだけ読み出されます。 Python がコマンドをスクリプトから読み出しているときや、 @code{/dev/tty} がコマンドの入力元として明示的に指定されている(この場合対話的セッションのように動作します) `わけではない' 場合にはこのファイルは読み出されません。ファイル内のコマンドは、対話的コマンドが実行される名前空間と同じ名前空間内で実行されます。このため、ファイル内で定義されていたり import されたオブジェクトは、そのまま対話セッション内で使うことができます。また、このファイル内で @code{sys.ps1} や @code{sys.ps2} を変更して、プロンプトを変更することもできます。

もし現在のディレクトリから追加でスタートアップファイルを読み出したいのなら、グローバルのスタートアップファイルの中に @code{if os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())} のようなプログラムを書くことができます。スクリプト中でスタートアップファイルを使いたいのなら、以下のようにしてスクリプト中で明示的に実行しなければなりません:

@example
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    with open(filename) as fobj:
        startup_file = fobj.read()
    exec(startup_file)
@end example

@node カスタマイズ用モジュール,,対話モード用の起動時実行ファイル,対話モード<2>
@anchor{tutorial/appendix the-customization-modules}@anchor{2110}@anchor{tutorial/appendix tut-customize}@anchor{2111}
@subsubsection カスタマイズ用モジュール


Python はユーザーが Python をカスタマイズするための2つのフック、 
@geindex sitecustomize
sitecustomize と 
@geindex usercustomize
usercustomize を提供しています。これがどのように動作しているかを知るには、まずはユーザーの site-packages ディレクトリの場所を見つける必要があります。Python を起動して次のコードを実行してください:

@example
>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.x/site-packages'
@end example

@code{usercustomize.py} をそのディレクトリに作成して、そこでやりたいことをすべて書くことができます。このファイルは自動インポートを無効にする @ref{15a6,,-s} オプションを使わない限り、全ての Python の起動時に実行されます。

@geindex sitecustomize
sitecustomize モジュールも同じように動作しますが、一般的にコンピューターの管理者によって、グローバルの site-packages ディレクトリに作成され、 
@geindex usercustomize
usercustomize より先にインポートされます。詳細は @ref{cc,,site} モジュールのドキュメントを参照してください。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python のセットアップと利用,Python 言語リファレンス,Python チュートリアル,Top
@anchor{using/index doc}@anchor{2112}@anchor{using/index python-setup-and-usage}@anchor{2113}@anchor{using/index translation-repo}@anchor{2114}@anchor{using/index using-index}@anchor{2115}
@chapter Python のセットアップと利用


このドキュメントでは 異なるプラットフォームでのPython環境のセットアップの一般的な方法、インタプリタの起動とPythonでの作業を楽にする方法を説明します。

@c ATTENTION: You probably should update Misc/python.man, too, if you modify
@c this file.

@menu
* コマンドラインと環境: コマンドラインと環境<2>. 
* Unix プラットフォームで Python を使う:: 
* Python を構成する:: 
* Windows で Python を使う:: 
* macOS で Python を使う:: 
* Android で Python を使う:: 
* iOS で Python を使う:: 
* エディタと IDE:: 

@end menu

@node コマンドラインと環境<2>,Unix プラットフォームで Python を使う,,Python のセットアップと利用
@anchor{using/cmdline doc}@anchor{2116}@anchor{using/cmdline command-line-and-environment}@anchor{2117}@anchor{using/cmdline using-on-general}@anchor{1da7}
@section コマンドラインと環境


CPython インタプリタはコマンドラインと環境を読み取って様々な設定を行ないます。

他の実装のコマンドラインスキームは CPython とは異なります。さらなる情報は @ref{2118,,別のPythonの実装} を参照してください。

@menu
* コマンドライン:: 
* 環境変数:: 

@end menu

@node コマンドライン,環境変数,,コマンドラインと環境<2>
@anchor{using/cmdline command-line}@anchor{2119}@anchor{using/cmdline using-on-cmdline}@anchor{1209}
@subsection コマンドライン


Python を起動するとき、以下のうち任意のオプションを指定できます:

@example
python [-bBdEhiIOPqRsSuvVWx?] [-c command | -m module-name | script | - ] [args]
@end example

もちろん、もっとも一般的な利用方法は、単純にスクリプトを起動することです:

@example
python myscript.py
@end example

@menu
* インターフェイスオプション:: 
* 一般オプション:: 
* その他のオプション:: 
* 色の制御:: 

@end menu

@node インターフェイスオプション,一般オプション,,コマンドライン
@anchor{using/cmdline interface-options}@anchor{211a}@anchor{using/cmdline using-on-interface-options}@anchor{211b}
@subsubsection インターフェイスオプション


インタプリタのインターフェイスは UNIX シェルのものに似ていますが、より多くの起動方法を提供しています:


@itemize *

@item 
When called with standard input connected to a tty device, it prompts for
commands and executes them until an EOF (an end-of-file character, you can
produce that with @code{Ctrl}-@code{D} on UNIX or @code{Ctrl}-@code{Z,} @code{Enter} on Windows) is read.
For more on interactive mode, see @ref{494,,対話モード}.

@item 
ファイル名引数か、標準入力としてファイルを渡された場合、そのファイルからスクリプトを読み込んで実行します。

@item 
ディレクトリ名を引数に受け取った場合、そのディレクトリから適切な名前のスクリプトファイルを読み込んで実行します。

@item 
@code{-c コマンド} オプションを利用して起動された場合、 `コマンド' として渡された Python の文を実行します。 `コマンド' の部分には改行で区切られた複数行を指定することもできます。行の先頭の空白文字は Python 文の重要要素です！

@item 
@code{-m モジュール名} として Python モジュールパスにあるモジュールを指定された場合、そのモジュールをスクリプトとして実行します。
@end itemize

非インタラクティブモードでは、入力の全体が実行前にパースされます。

インタプリタによって消費されるオプションリストが終了したあと、継続する全ての引数は @ref{147c,,sys.argv} に渡ります。 -- ただし、添字 0 の先頭要素(@code{sys.argv[0]}) はプログラムのソース自体を示す文字列です。

@geindex コマンドラインオプション; -c
@anchor{using/cmdline cmdoption-c}@anchor{1a8}
@deffn {Option} @w{-}c <command>

`command' 内の Python コードを実行します。 `command' は改行によって区切られた1行以上の文です。通常のモジュールのコードと同じく、行頭の空白文字は意味を持ちます。

このオプションが指定された場合、 @ref{147c,,sys.argv} の最初の要素は @code{"-c"} になり、カレントディレクトリが @ref{3e4,,sys.path} の先頭に追加されます (そのディレクトリにあるモジュールをトップレベルモジュールとして import 出来るようになります)。

引数 @code{command} を指定して @ref{1c6e,,監査イベント} @code{cpython.run_command} を送出します。


バージョン 3.14 で変更: `command' is automatically dedented before execution.

@end deffn

@geindex コマンドラインオプション; -m
@anchor{using/cmdline cmdoption-m}@anchor{23c}
@deffn {Option} @w{-}m <module@w{-}name>

@ref{3e4,,sys.path} から指定されたモジュール名のモジュールを探し、その内容を @ref{1,,__main__} モジュールとして実行します。

引数は `module' 名なので、拡張子 (@code{.py}) を含めてはいけません。モジュール名は有効な Python の絶対モジュール名 (absolute module name) であるべきですが、実装がそれを強制しているとは限りません (例えば、ハイフンを名前に含める事を許可するかもしれません)。

パッケージ名 (名前空間パッケージも含む) でも構いません。通常のモジュールの代わりにパッケージ名が与えられた場合、インタプリタは @code{<pkg>.__main__} を main モジュールとして実行します。この挙動はスクリプト引数として渡されたディレクトリや zip ファイルをインタプリタが処理するのと意図的に同じにしています。

@cartouche
@quotation 注釈 
このオプションは組み込みモジュールや C で書かれた拡張モジュールには利用できません。 Python モジュールファイルを持っていないからです。しかし、コンパイル済みのモジュールは、たとえ元のソースファイルがなくても利用可能です。
@end quotation
@end cartouche

このオプションが指定された場合、 @ref{147c,,sys.argv} の最初の要素はモジュールファイルのフルパスになります (モジュールファイルを検索している間、最初の要素は @code{"-m"} に設定されます)。 @ref{1a8,,-c} オプションと同様に、カレントディレクトリが @ref{3e4,,sys.path} の先頭に追加されます。

@ref{b57,,-I} option can  be used to run the script in isolated mode where
@ref{3e4,,sys.path} contains neither the current directory nor the user's
site-packages directory. All @code{PYTHON*} environment variables are
ignored, too.

多くの標準ライブラリモジュールにはスクリプトとして実行された時のためのコードがあります。例えば、 @ref{f5,,timeit} モジュールは次のように実行可能です:

@example
python -m timeit -s "setup here" "benchmarked code here"
python -m timeit -h # for details
@end example

引数 @code{module-name} を指定して @ref{1c6e,,監査イベント} @code{cpython.run_module} を送出します。


@subsubheading 参考



@table @asis

@item @ref{1b97,,runpy.run_module()}

Python コードで直接使える等価な機能
@end table

@geindex Python Enhancement Proposals; PEP 338
PEP 338@footnote{https://peps.python.org/pep-0338/} - モジュールをスクリプトとして実行する



バージョン 3.1 で変更: @code{__main__} サブモジュールを実行するパッケージ名が提供されました。



バージョン 3.4 で変更: 名前空間パッケージもサポートされました

@end deffn

@anchor{using/cmdline cmdarg-dash}@anchor{211c}
@deffn {Describe} @w{-}

標準入力 (@ref{75f,,sys.stdin}) からコマンドを読み込みます。標準入力がターミナルだった場合、暗黙的に @ref{16f4,,-i} オプションが指定されます。

このオプションが指定された場合、 @ref{147c,,sys.argv} の最初の要素は @code{"-"} で、カレントディレクトリが @ref{3e4,,sys.path} の先頭に追加されます。

引数無しで @ref{1c6e,,監査イベント} @code{cpython.run_stdin} を送出します。
@end deffn

@anchor{using/cmdline cmdarg-script}@anchor{211d}
@deffn {Describe} <script>

`script' 内の Python コードを実行します。 `script' は、Python ファイル、 @code{__main__.py} ファイルがあるディレクトリ、 @code{__main__.py} ファイルがある zip ファイルのいずれかの、ファイルシステム上の (絶対または相対) パスでなければなりません。

このオプションが指定された場合、 @ref{147c,,sys.argv} の最初の要素はコマンドラインで指定されたスクリプト名になります。

スクリプト名が Python ファイルを直接指定していた場合、そのファイルを含むディレクトリが @ref{3e4,,sys.path} の先頭に追加され、そのファイルは @ref{1,,__main__} モジュールとして実行されます。

スクリプト名がディレクトリか zip ファイルを指定していた場合、スクリプト名が @ref{3e4,,sys.path} に追加され、その中の @code{__main__.py} ファイルが @ref{1,,__main__} モジュールとして実行されます。

@ref{b57,,-I} option can  be used to run the script in isolated mode where
@ref{3e4,,sys.path} contains neither the script's directory nor the user's
site-packages directory. All @code{PYTHON*} environment variables are
ignored, too.

引数 @code{filename} を指定して @ref{1c6e,,監査イベント} @code{cpython.run_file} を送出します。


@subsubheading 参考



@table @asis

@item @ref{4a4,,runpy.run_path()}

Python コードで直接使える等価な機能
@end table

@end deffn

インターフェイスオプションが与えられなかった場合、@ref{16f4,,-i} が暗黙的に指定され、@code{sys.argv[0]} が空の文字列 (@code{""}) になり、 現在のディレクトリが @ref{3e4,,sys.path} の先頭に追加されます。また、利用可能であればタブ補完と履歴編集が自動的に有効化されます (@ref{11cb,,readline の設定} を参照してください)。


@subsubheading 参考


@ref{1fc8,,インタプリタを起動する}



バージョン 3.4 で変更: タブ補完と履歴の編集が自動的に有効化されます。


@node 一般オプション,その他のオプション,インターフェイスオプション,コマンドライン
@anchor{using/cmdline generic-options}@anchor{211e}@anchor{using/cmdline using-on-generic-options}@anchor{211f}
@subsubsection 一般オプション


@geindex コマンドラインオプション; -?
@geindex コマンドラインオプション; -h
@geindex コマンドラインオプション; --help
@anchor{using/cmdline cmdoption-0}@anchor{1641}
@deffn {Option} @w{-}?
@anchor{using/cmdline cmdoption-h}@anchor{2120}
@deffnx {Option} @w{-}h
@anchor{using/cmdline cmdoption-help}@anchor{806}
@deffnx {Option} @w{-}@w{-}help

Print a short description of all command line options and corresponding
environment variables and exit.
@end deffn

@geindex コマンドラインオプション; --help-env
@anchor{using/cmdline cmdoption-help-env}@anchor{808}
@deffn {Option} @w{-}@w{-}help@w{-}env

Print a short description of Python-specific environment variables
and exit.


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; --help-xoptions
@anchor{using/cmdline cmdoption-help-xoptions}@anchor{809}
@deffn {Option} @w{-}@w{-}help@w{-}xoptions

Print a description of implementation-specific @ref{16f,,-X} options
and exit.


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; --help-all
@anchor{using/cmdline cmdoption-help-all}@anchor{80a}
@deffn {Option} @w{-}@w{-}help@w{-}all

Print complete usage information and exit.


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; -V
@geindex コマンドラインオプション; --version
@anchor{using/cmdline cmdoption-V}@anchor{49b}
@deffn {Option} @w{-}V
@anchor{using/cmdline cmdoption-version}@anchor{f17}
@deffnx {Option} @w{-}@w{-}version

Python のバージョン番号を表示して終了します。出力の例:

@example
Python 3.8.0b2+
@end example

2つ指定すると、次のようにより多くのビルドの情報を表示します:

@example
Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)
[GCC 6.2.0 20161005]
@end example


Added in version 3.6: @code{-VV} オプション。

@end deffn

@node その他のオプション,色の制御,一般オプション,コマンドライン
@anchor{using/cmdline miscellaneous-options}@anchor{2121}@anchor{using/cmdline using-on-misc-options}@anchor{120a}
@subsubsection その他のオプション


@geindex コマンドラインオプション; -b
@anchor{using/cmdline cmdoption-b}@anchor{7f9}
@deffn {Option} @w{-}b

Issue a warning when converting @ref{192,,bytes} or @ref{344,,bytearray} to
@ref{169,,str} without specifying encoding or comparing @code{bytes} or
@code{bytearray} with @code{str} or @code{bytes} with @ref{19b,,int}.
Issue an error when the option is given twice (@code{-bb}).


バージョン 3.5 で変更: Affects also comparisons of @ref{192,,bytes} with @ref{19b,,int}.

@end deffn

@geindex コマンドラインオプション; -B
@anchor{using/cmdline cmdoption-B}@anchor{15e6}
@deffn {Option} @w{-}B

与えられた場合、Python はソースモジュールのインポート時に @code{.pyc} ファイルの作成を試みません。 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@ref{15e7,,PYTHONDONTWRITEBYTECODE} 環境変数も参照してください。
@end deffn

@geindex コマンドラインオプション; --check-hash-based-pycs
@anchor{using/cmdline cmdoption-check-hash-based-pycs}@anchor{2122}
@deffn {Option} @w{-}@w{-}check@w{-}hash@w{-}based@w{-}pycs default|always|never

Control the validation behavior of hash-based @code{.pyc} files. See
@ref{802,,キャッシュされたバイトコードの無効化}. When set to @code{default}, checked and unchecked
hash-based bytecode cache files are validated according to their default
semantics. When set to @code{always}, all hash-based @code{.pyc} files, whether
checked or unchecked, are validated against their corresponding source
file. When set to @code{never}, hash-based @code{.pyc} files are not validated
against their corresponding source files.

The semantics of timestamp-based @code{.pyc} files are unaffected by this
option.
@end deffn

@geindex コマンドラインオプション; -d
@anchor{using/cmdline cmdoption-d}@anchor{2123}
@deffn {Option} @w{-}d

Turn on parser debugging output (for expert only).
See also the 
@geindex PYTHONDEBUG
@geindex 環境変数; PYTHONDEBUG
@ref{2124,,PYTHONDEBUG} environment variable.

This option requires a @ref{509,,debug build of Python}, otherwise
it's ignored.
@end deffn

@geindex コマンドラインオプション; -E
@anchor{using/cmdline cmdoption-E}@anchor{b56}
@deffn {Option} @w{-}E

Ignore all @code{PYTHON*} environment variables, e.g.
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} and 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME}, that might be set.

See also the @ref{7c1,,-P} and @ref{b57,,-I} (isolated) options.
@end deffn

@geindex コマンドラインオプション; -i
@anchor{using/cmdline cmdoption-i}@anchor{16f4}
@deffn {Option} @w{-}i

Enter interactive mode after execution.

Using the @ref{16f4,,-i} option will enter interactive mode in any of the following circumstances:


@itemize *

@item 
When a script is passed as first argument

@item 
When the @ref{1a8,,-c} option is used

@item 
When the @ref{23c,,-m} option is used
@end itemize

Interactive mode will start even when @ref{75f,,sys.stdin} does not appear to be a terminal. The
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} file is not read.

このオプションはグローバル変数や、スクリプトが例外を発生させるときにそのスタックトレースを調べるのに便利です。 
@geindex PYTHONINSPECT
@geindex 環境変数; PYTHONINSPECT
@ref{16f3,,PYTHONINSPECT} も参照してください。
@end deffn

@geindex コマンドラインオプション; -I
@anchor{using/cmdline cmdoption-I}@anchor{b57}
@deffn {Option} @w{-}I

Python を隔離モードで実行します。@ref{b56,,-E}、@ref{7c1,,-P}、および @ref{15a6,,-s} オプションも暗黙的に指定されます。

In isolated mode @ref{3e4,,sys.path} contains neither the script's directory nor
the user's site-packages directory. All @code{PYTHON*} environment
variables are ignored, too. Further restrictions may be imposed to prevent
the user from injecting malicious code.


Added in version 3.4.

@end deffn

@geindex コマンドラインオプション; -O
@anchor{using/cmdline cmdoption-O}@anchor{18c}
@deffn {Option} @w{-}O

Remove assert statements and any code conditional on the value of
@ref{9da,,__debug__}.  Augment the filename for compiled
(@ref{4aa,,bytecode}) files by adding @code{.opt-1} before the @code{.pyc}
extension (see 
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/}).  See also 
@geindex PYTHONOPTIMIZE
@geindex 環境変数; PYTHONOPTIMIZE
@ref{2125,,PYTHONOPTIMIZE}.


バージョン 3.5 で変更: 
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} に従って @code{.pyc} ファイル名を変更します。

@end deffn

@geindex コマンドラインオプション; -OO
@anchor{using/cmdline cmdoption-OO}@anchor{fb5}
@deffn {Option} @w{-}OO

Do @ref{18c,,-O} and also discard docstrings.  Augment the filename
for compiled (@ref{4aa,,bytecode}) files by adding @code{.opt-2} before the
@code{.pyc} extension (see 
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/}).


バージョン 3.5 で変更: 
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} に従って @code{.pyc} ファイル名を変更します。

@end deffn

@geindex コマンドラインオプション; -P
@anchor{using/cmdline cmdoption-P}@anchor{7c1}
@deffn {Option} @w{-}P

Don't prepend a potentially unsafe path to @ref{3e4,,sys.path}:


@itemize *

@item 
@code{python -m module} command line: Don't prepend the current working
directory.

@item 
@code{python script.py} command line: Don't prepend the script's directory.
If it's a symbolic link, resolve symbolic links.

@item 
@code{python -c code} and @code{python} (REPL) command lines: Don't prepend an
empty string, which means the current working directory.
@end itemize

See also the 
@geindex PYTHONSAFEPATH
@geindex 環境変数; PYTHONSAFEPATH
@ref{7c2,,PYTHONSAFEPATH} environment variable, and @ref{b56,,-E}
and @ref{b57,,-I} (isolated) options.


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; -q
@anchor{using/cmdline cmdoption-q}@anchor{177e}
@deffn {Option} @w{-}q

インタラクティブモードでも copyright とバージョンのメッセージを表示しません。


Added in version 3.2.

@end deffn

@geindex コマンドラインオプション; -R
@anchor{using/cmdline cmdoption-R}@anchor{1e78}
@deffn {Option} @w{-}R

Turn on hash randomization. This option only has an effect if the
@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} environment variable is set to anything other
than @code{random}, since hash randomization is enabled by default.

On previous versions of Python, this option turns on hash randomization,
so that the @ref{cf3,,__hash__()} values of str and bytes objects
are "salted" with an unpredictable random value.  Although they remain
constant within an individual Python process, they are not predictable
between repeated invocations of 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'@w{^2}) complexity.  See
@indicateurl{http://ocert.org/advisories/ocert-2011-003.html} for details.

@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} によってハッシュシードの固定値を秘密にすることが出来ます。


Added in version 3.2.3.



バージョン 3.7 で変更: このオプションが無視されなくなりました.

@end deffn

@geindex コマンドラインオプション; -s
@anchor{using/cmdline cmdoption-s}@anchor{15a6}
@deffn {Option} @w{-}s

@ref{2126,,ユーザのサイトパッケージのディレクトリ} を @ref{3e4,,sys.path} に追加しません。

See also 
@geindex PYTHONNOUSERSITE
@geindex 環境変数; PYTHONNOUSERSITE
@ref{15a7,,PYTHONNOUSERSITE}.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 370
PEP 370@footnote{https://peps.python.org/pep-0370/} -- ユーザごとの @code{site-packages} ディレクトリ

@end deffn

@geindex コマンドラインオプション; -S
@anchor{using/cmdline cmdoption-S}@anchor{13c0}
@deffn {Option} @w{-}S

@ref{cc,,site} モジュールの import と、そのモジュールが行なっていた site ごとの @ref{3e4,,sys.path} への操作を無効にします。後で @ref{cc,,site} を明示的に import しても、これらの操作は実行されません (実行したい場合は、 @ref{2127,,site.main()} を呼び出してください)。
@end deffn

@geindex コマンドラインオプション; -u
@anchor{using/cmdline cmdoption-u}@anchor{1d8d}
@deffn {Option} @w{-}u

Force the stdout and stderr streams to be unbuffered.  This option has no
effect on the stdin stream.

@geindex PYTHONUNBUFFERED
@geindex 環境変数; PYTHONUNBUFFERED
@ref{1d8e,,PYTHONUNBUFFERED} も参照してください。


バージョン 3.7 で変更: The text layer of the stdout and stderr streams now is unbuffered.

@end deffn

@geindex コマンドラインオプション; -v
@anchor{using/cmdline cmdoption-v}@anchor{163e}
@deffn {Option} @w{-}v

モジュールが初期化されるたびにメッセージを出力し、それがどこ (ファイル名やビルトインモジュール) からロードされたのかを表示します。
二回与えられた場合 (@code{-vv}) は、モジュールを検索するときにチェックしたファイルごとにメッセージを出力します。また、終了時のモジュールクリーンアップに関する情報も提供します。


バージョン 3.10 で変更: The @ref{cc,,site} module reports the site-specific paths
and @code{.pth} files being processed.


@geindex PYTHONVERBOSE
@geindex 環境変数; PYTHONVERBOSE
@ref{2128,,PYTHONVERBOSE} も参照してください。
@end deffn

@geindex コマンドラインオプション; -W
@anchor{using/cmdline using-on-warnings}@anchor{2129}@anchor{using/cmdline cmdoption-W}@anchor{ac6}
@deffn {Option} @w{-}W arg

警告制御。 Python の警告機構はデフォルトでは警告メッセージを @ref{b33,,sys.stderr} に表示します。

The simplest settings apply a particular action unconditionally to all
warnings emitted by a process (even those that are otherwise ignored by
default):

@example
-Wdefault  # Warn once per call location
-Werror    # Convert to exceptions
-Walways   # Warn every time
-Wall      # Same as -Walways
-Wmodule   # Warn once per calling module
-Wonce     # Warn once per Python process
-Wignore   # Never warn
@end example

The action names can be abbreviated as desired and the interpreter will
resolve them to the appropriate action name. For example, @code{-Wi} is the
same as @code{-Wignore}.

引数の完全形は次のようになります:

@example
action:message:category:module:lineno
@end example

Empty fields match all values; trailing empty fields may be omitted. For
example @code{-W ignore::DeprecationWarning} ignores all DeprecationWarning
warnings.

The `action' field is as explained above but only applies to warnings that
match the remaining fields.

The `message' field must match the whole warning message; this match is
case-insensitive.

The `category' field matches the warning category
(ex: @code{DeprecationWarning}). This must be a class name; the match test
whether the actual warning category of the message is a subclass of the
specified warning category.

The `module' field matches the (fully qualified) module name; this match is
case-sensitive.

The `lineno' field matches the line number, where zero matches all line
numbers and is thus equivalent to an omitted line number.

複数の @ref{ac6,,-W} オプションを指定することができます。警告が1つ以上のオプションとマッチしたときは、最後にマッチしたオプションのアクションが有効になります。不正な @ref{ac6,,-W} オプションは無視されます (最初の警告が発生したときに、不正なオプションに対する警告メッセージが表示されます)。

Warnings can also be controlled using the 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS}
environment variable and from within a Python program using the
@ref{118,,warnings} module. For example, the @ref{16c2,,warnings.filterwarnings()}
function can be used to use a regular expression on the warning message.

詳しくは @ref{1b1,,警告フィルタ} と @ref{212a,,Describing Warning Filters} を参照してください。
@end deffn

@geindex コマンドラインオプション; -x
@anchor{using/cmdline cmdoption-x}@anchor{212b}
@deffn {Option} @w{-}x

Unix 以外の形式の @code{#!cmd} を使うために、ソースの最初の行をスキップします。これは、DOS専用のハックのみを目的としています。
@end deffn

@geindex コマンドラインオプション; -X
@anchor{using/cmdline cmdoption-X}@anchor{16f}
@deffn {Option} @w{-}X

様々な実装固有のオプションのために予約されています。現在のところ CPython は以下の値を定義しています:


@itemize *

@item 
@code{-X faulthandler} to enable @ref{5c,,faulthandler}.
See also 
@geindex PYTHONFAULTHANDLER
@geindex 環境変数; PYTHONFAULTHANDLER
@ref{1291,,PYTHONFAULTHANDLER}.


Added in version 3.3.


@item 
@code{-X showrefcount} to output the total reference count and number of used
memory blocks when the program finishes or after each statement in the
interactive interpreter. This only works on @ref{509,,debug builds}.


Added in version 3.4.


@item 
@code{-X tracemalloc} to start tracing Python memory allocations using the
@ref{105,,tracemalloc} module. By default, only the most recent frame is
stored in a traceback of a trace. Use @code{-X tracemalloc=NFRAME} to start
tracing with a traceback limit of `NFRAME' frames.
See @ref{212c,,tracemalloc.start()} and 
@geindex PYTHONTRACEMALLOC
@geindex 環境変数; PYTHONTRACEMALLOC
@ref{212d,,PYTHONTRACEMALLOC}
for more information.


Added in version 3.4.


@item 
@code{-X int_max_str_digits} configures the @ref{80b,,integer string conversion length limitation}.  See also
@geindex PYTHONINTMAXSTRDIGITS
@geindex 環境変数; PYTHONINTMAXSTRDIGITS
@ref{1b3a,,PYTHONINTMAXSTRDIGITS}.


Added in version 3.11.


@item 
@code{-X importtime} to show how long each import takes. It shows module
name, cumulative time (including nested imports) and self time (excluding
nested imports).  Note that its output may be broken in multi-threaded
application.  Typical usage is @code{python -X importtime -c 'import asyncio'}.

@code{-X importtime=2} enables additional output that indicates when an
imported module has already been loaded.  In such cases, the string
@code{cached} will be printed in both time columns.

See also 
@geindex PYTHONPROFILEIMPORTTIME
@geindex 環境変数; PYTHONPROFILEIMPORTTIME
@ref{ced,,PYTHONPROFILEIMPORTTIME}.


Added in version 3.7.



バージョン 3.14 で変更: Added @code{-X importtime=2} to also trace imports of loaded modules,
and reserved values other than @code{1} and @code{2} for future use.


@item 
@code{-X dev}: enable @ref{508,,Python Development Mode}, introducing
additional runtime checks that are too expensive to be enabled by
default.  See also 
@geindex PYTHONDEVMODE
@geindex 環境変数; PYTHONDEVMODE
@ref{ce7,,PYTHONDEVMODE}.


Added in version 3.7.


@item 
@code{-X utf8} enables the @ref{866,,Python UTF-8 Mode}.
@code{-X utf8=0} explicitly disables @ref{866,,Python UTF-8 Mode}
(even when it would otherwise activate automatically).
See also 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8}.


Added in version 3.7.


@item 
@code{-X pycache_prefix=PATH} enables writing @code{.pyc} files to a parallel
tree rooted at the given directory instead of to the code tree. See also
@geindex PYTHONPYCACHEPREFIX
@geindex 環境変数; PYTHONPYCACHEPREFIX
@ref{b9b,,PYTHONPYCACHEPREFIX}.


Added in version 3.8.


@item 
@code{-X warn_default_encoding} issues a @ref{212e,,EncodingWarning} when the
locale-specific default encoding is used for opening files.
See also 
@geindex PYTHONWARNDEFAULTENCODING
@geindex 環境変数; PYTHONWARNDEFAULTENCODING
@ref{9bf,,PYTHONWARNDEFAULTENCODING}.


Added in version 3.10.


@item 
@code{-X no_debug_ranges} disables the inclusion of the tables mapping extra
location information (end line, start column offset and end column offset)
to every instruction in code objects. This is useful when smaller code
objects and pyc files are desired as well as suppressing the extra visual
location indicators when the interpreter displays tracebacks. See also
@geindex PYTHONNODEBUGRANGES
@geindex 環境変数; PYTHONNODEBUGRANGES
@ref{7d3,,PYTHONNODEBUGRANGES}.


Added in version 3.11.


@item 
@code{-X frozen_modules} determines whether or not frozen modules are
ignored by the import machinery.  A value of @code{on} means they get
imported and @code{off} means they are ignored.  The default is @code{on}
if this is an installed Python (the normal case).  If it's under
development (running from the source tree) then the default is @code{off}.
Note that the @code{importlib_bootstrap} and
@code{importlib_bootstrap_external} frozen modules are always used, even
if this flag is set to @code{off}. See also 
@geindex PYTHON_FROZEN_MODULES
@geindex 環境変数; PYTHON_FROZEN_MODULES
@ref{4ad,,PYTHON_FROZEN_MODULES}.


Added in version 3.11.


@item 
@code{-X perf} enables support for the Linux @code{perf} profiler.
When this option is provided, the @code{perf} profiler will be able to
report Python calls. This option is only available on some platforms and
will do nothing if is not supported on the current system. The default value
is "off". See also 
@geindex PYTHONPERFSUPPORT
@geindex 環境変数; PYTHONPERFSUPPORT
@ref{699,,PYTHONPERFSUPPORT} and @ref{4ae,,Python support for the Linux perf profiler}.


Added in version 3.12.


@item 
@code{-X perf_jit} enables support for the Linux @code{perf} profiler with DWARF
support. When this option is provided, the @code{perf} profiler will be able
to report Python calls using DWARF information. This option is only available on
some platforms and will do nothing if is not supported on the current
system. The default value is "off". See also 
@geindex PYTHON_PERF_JIT_SUPPORT
@geindex 環境変数; PYTHON_PERF_JIT_SUPPORT
@ref{4af,,PYTHON_PERF_JIT_SUPPORT}
and @ref{4ae,,Python support for the Linux perf profiler}.


Added in version 3.13.


@item 
@code{-X disable_remote_debug} disables the remote debugging support as described
in 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/}.  This includes both the functionality to schedule code for
execution in another process and the functionality to receive code for
execution in the current process.

This option is only available on some platforms and will do nothing
if is not supported on the current system. See also
@geindex PYTHON_DISABLE_REMOTE_DEBUG
@geindex 環境変数; PYTHON_DISABLE_REMOTE_DEBUG
@ref{16e,,PYTHON_DISABLE_REMOTE_DEBUG} and 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/}.


Added in version 3.14.


@item 
@code{-X cpu_count=@var{n}} overrides @ref{4db,,os.cpu_count()},
@ref{4da,,os.process_cpu_count()}, and @ref{1171,,multiprocessing.cpu_count()}.
`n' must be greater than or equal to 1.
This option may be useful for users who need to limit CPU resources of a
container system. See also 
@geindex PYTHON_CPU_COUNT
@geindex 環境変数; PYTHON_CPU_COUNT
@ref{51e,,PYTHON_CPU_COUNT}.
If `n' is @code{default}, nothing is overridden.


Added in version 3.13.


@item 
@code{-X presite=@var{package.module}} specifies a module that should be
imported before the @ref{cc,,site} module is executed and before the
@ref{1,,__main__} module exists.  Therefore, the imported module isn't
@ref{1,,__main__}. This can be used to execute code early during Python
initialization. Python needs to be @ref{509,,built in debug mode}
for this option to exist.  See also 
@geindex PYTHON_PRESITE
@geindex 環境変数; PYTHON_PRESITE
@ref{212f,,PYTHON_PRESITE}.


Added in version 3.13.


@item 
@code{-X gil=@var{0,1}} forces the GIL to be disabled or enabled,
respectively. Setting to @code{0} is only available in builds configured with
@ref{499,,--disable-gil}. See also 
@geindex PYTHON_GIL
@geindex 環境変数; PYTHON_GIL
@ref{49a,,PYTHON_GIL} and
@ref{46d,,フリースレッドの CPython}.


Added in version 3.13.


@item 
@code{-X thread_inherit_context=@var{0,1}} causes @ref{176,,Thread}
to, by default, use a copy of context of the caller of
@code{Thread.start()} when starting.  Otherwise, threads will start
with an empty context.  If unset, the value of this option defaults
to @code{1} on free-threaded builds and to @code{0} otherwise.  See also
@geindex PYTHON_THREAD_INHERIT_CONTEXT
@geindex 環境変数; PYTHON_THREAD_INHERIT_CONTEXT
@ref{1868,,PYTHON_THREAD_INHERIT_CONTEXT}.


Added in version 3.14.


@item 
@code{-X context_aware_warnings=@var{0,1}} causes the
@ref{179,,warnings.catch_warnings} context manager to use a
@ref{1875,,ContextVar} to store warnings filter state.  If
unset, the value of this option defaults to @code{1} on free-threaded builds
and to @code{0} otherwise.  See also 
@geindex PYTHON_CONTEXT_AWARE_WARNINGS
@geindex 環境変数; PYTHON_CONTEXT_AWARE_WARNINGS
@ref{185b,,PYTHON_CONTEXT_AWARE_WARNINGS}.


Added in version 3.14.


@item 
@code{-X tlbc=@var{0,1}} enables (1, the default) or disables (0) thread-local
bytecode in builds configured with @ref{499,,--disable-gil}.  When disabled,
this also disables the specializing interpreter.  See also
@geindex PYTHON_TLBC
@geindex 環境変数; PYTHON_TLBC
@ref{2130,,PYTHON_TLBC}.


Added in version 3.14.

@end itemize

任意の値を渡し、 @ref{2131,,sys._xoptions} 辞書から取り出すことも出来ます。


Added in version 3.2.



バージョン 3.9 で変更: Removed the @code{-X showalloccount} option.



バージョン 3.10 で変更: Removed the @code{-X oldparser} option.

@end deffn


Removed in version 3.14: @code{-J} is no longer reserved for use by Jython@footnote{https://www.jython.org/},
and now has no special meaning.


@node 色の制御,,その他のオプション,コマンドライン
@anchor{using/cmdline controlling-color}@anchor{2132}@anchor{using/cmdline using-on-controlling-color}@anchor{1b7}
@subsubsection 色の制御


デフォルトでは、 Python インタープリターは、トレースバックの表示などの特定の状況で、出力を色でハイライトするように構成されています。この振る舞いは、異なる環境変数を設定することで制御できます。

環境変数 @code{TERM} を @code{dumb} に設定することで、色付けを無効にできます。

FORCE_COLOR@footnote{https://force-color.org/} 環境変数が設定されている場合、 TERM の値にかかわらず、色付けは有効になります。これは、ターミナルではないが ANSI エスケープシーケンスを表示できる CI システムで有効です。

NO_COLOR@footnote{https://no-color.org/} 環境変数が設定されている場合、 Python は出力のすべての色を無効にします。これは @code{FORCE_COLOR} よりも優先されます。

これらのすべての環境変数は、色の出力の制御のために他のツールにも使用されます。 Python インタープリターでのみ色の出力を制御するには、 
@geindex PYTHON_COLORS
@geindex 環境変数; PYTHON_COLORS
@ref{476,,PYTHON_COLORS} 環境変数を使用できます。この変数は、 @code{FORCE_COLOR} よりも優先される @code{NO_COLOR} よりも、さらに優先されます。

@node 環境変数,,コマンドライン,コマンドラインと環境<2>
@anchor{using/cmdline environment-variables}@anchor{2133}@anchor{using/cmdline using-on-envvars}@anchor{807}
@subsection 環境変数


以下の環境変数は Python の挙動に影響します。環境変数は -E や -I 以外のコマンドラインスイッチの前に処理されます。衝突したときにコマンドラインスイッチが環境変数をオーバーライドするのは慣例です。

@geindex 環境変数; PYTHONHOME
@anchor{using/cmdline envvar-PYTHONHOME}@anchor{3f0}
@deffn {環境変数} PYTHONHOME

標準 Python ライブラリの場所を変更します。デフォルトでは、ライブラリは @code{`prefix'/lib/python`version'} と @code{`exec_prefix'/lib/python`version'} から検索されます。ここで、 @code{`prefix'} と @code{`exec_prefix'} はインストール依存のディレクトリで、両方共デフォルトでは @code{/usr/local} です。

@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} が1つのディレクトリに設定されている場合、その値は @code{`prefix'} と @code{`exec_prefix'} の両方を置き換えます。それらに別々の値を指定したい場合は、 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} を @code{`prefix':`exec_prefix'} のように指定します。
@end deffn

@geindex 環境変数; PYTHONPATH
@anchor{using/cmdline envvar-PYTHONPATH}@anchor{121f}
@deffn {環境変数} PYTHONPATH

モジュールファイルのデフォルトの検索パスを追加します。この環境変数のフォーマットはシェルの 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} と同じで、 @ref{2134,,os.pathsep} (Unix ならコロン、 Windows ならセミコロン) で区切られた1つ以上のディレクトリパスです。存在しないディレクトリは警告なしに無視されます。

通常のディレクトリに加えて、 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} のエントリはピュアPython モジュール(ソース形式でもコンパイルされた形式でも) を含む zip ファイルを参照することもできます。拡張モジュールは zip ファイルの中から import することはできません。

デフォルトの検索パスはインストール依存ですが、通常は @code{`prefix'/lib/python`version'} で始まります。 (上の 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} を参照してください。) これは `常に' 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} に追加されます。

上の @ref{211b,,インターフェイスオプション} で説明されているように、追加の検索パスディレクトリが 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} の手前に追加されます。検索パスは Python プログラムから @ref{3e4,,sys.path} 変数として操作することができます。
@end deffn

@geindex 環境変数; PYTHONSAFEPATH
@anchor{using/cmdline envvar-PYTHONSAFEPATH}@anchor{7c2}
@deffn {環境変数} PYTHONSAFEPATH

If this is set to a non-empty string, don't prepend a potentially unsafe
path to @ref{3e4,,sys.path}: see the @ref{7c1,,-P} option for details.


Added in version 3.11.

@end deffn

@geindex 環境変数; PYTHONPLATLIBDIR
@anchor{using/cmdline envvar-PYTHONPLATLIBDIR}@anchor{1d23}
@deffn {環境変数} PYTHONPLATLIBDIR

If this is set to a non-empty string, it overrides the @ref{b32,,sys.platlibdir}
value.


Added in version 3.9.

@end deffn

@geindex 環境変数; PYTHONSTARTUP
@anchor{using/cmdline envvar-PYTHONSTARTUP}@anchor{1b8}
@deffn {環境変数} PYTHONSTARTUP

この変数が読み込み可能なファイル名の場合、対話モードで最初のプロンプトが表示される前にそのファイルの Python コマンドが実行されます。
ファイル内で定義されているオブジェクトやインポートされたオブジェクトを対話セッションで修飾せずに使用するために、ファイルは対話的なコマンドと同じ名前空間で実行されます。
このファイルの中で、プロンプト @ref{2135,,sys.ps1} や @ref{2136,,sys.ps2}、ならびにフック @ref{11ca,,sys.__interactivehook__} も変更できます。


Raises an @ref{1c6e,,auditing event} @code{cpython.run_startup} with
the filename as the argument when called on startup.

@end deffn

@geindex 環境変数; PYTHONOPTIMIZE
@anchor{using/cmdline envvar-PYTHONOPTIMIZE}@anchor{2125}
@deffn {環境変数} PYTHONOPTIMIZE

この変数に空でない文字列を設定するのは @ref{18c,,-O} オプションを指定するのと等価です。整数を設定した場合、 @ref{18c,,-O} を複数回指定したのと同じになります。
@end deffn

@geindex 環境変数; PYTHONBREAKPOINT
@anchor{using/cmdline envvar-PYTHONBREAKPOINT}@anchor{cd2}
@deffn {環境変数} PYTHONBREAKPOINT

If this is set, it names a callable using dotted-path notation.  The module
containing the callable will be imported and then the callable will be run
by the default implementation of @ref{cd1,,sys.breakpointhook()} which itself is
called by built-in @ref{271,,breakpoint()}.  If not set, or set to the empty
string, it is equivalent to the value "pdb.set_trace".  Setting this to the
string "0" causes the default implementation of @ref{cd1,,sys.breakpointhook()}
to do nothing but return immediately.


Added in version 3.7.

@end deffn

@geindex 環境変数; PYTHONDEBUG
@anchor{using/cmdline envvar-PYTHONDEBUG}@anchor{2124}
@deffn {環境変数} PYTHONDEBUG

この変数に空でない文字列を設定するのは @ref{2123,,-d} オプションを指定するのと等価です。整数を指定した場合、 @ref{2123,,-d} を複数回指定したのと同じになります。

This environment variable requires a @ref{509,,debug build of Python}, otherwise it's ignored.
@end deffn

@geindex 環境変数; PYTHONINSPECT
@anchor{using/cmdline envvar-PYTHONINSPECT}@anchor{16f3}
@deffn {環境変数} PYTHONINSPECT

この変数に空でない文字列を設定するのは @ref{16f4,,-i} オプションを指定するのと等価です。

この変数は Python コードから @ref{259,,os.environ} を使って変更して、プログラム終了時のインスペクトモードを強制することができます。

引数無しで @ref{1c6e,,監査イベント} @code{cpython.run_stdin} を送出します。


バージョン 3.12.5 で変更: (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20)
Emits audit events.



バージョン 3.13 で変更: Uses PyREPL if possible, in which case 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} is
also executed. Emits audit events.

@end deffn

@geindex 環境変数; PYTHONUNBUFFERED
@anchor{using/cmdline envvar-PYTHONUNBUFFERED}@anchor{1d8e}
@deffn {環境変数} PYTHONUNBUFFERED

この変数に空でない文字列を設定するのは @ref{1d8d,,-u} オプションを指定するのと等価です。
@end deffn

@geindex 環境変数; PYTHONVERBOSE
@anchor{using/cmdline envvar-PYTHONVERBOSE}@anchor{2128}
@deffn {環境変数} PYTHONVERBOSE

この変数に空でない文字列を設定するのは @ref{163e,,-v} オプションを指定するのと等価です。整数を設定した場合、 @ref{163e,,-v} を複数回指定したのと同じになります。
@end deffn

@geindex 環境変数; PYTHONCASEOK
@anchor{using/cmdline envvar-PYTHONCASEOK}@anchor{b55}
@deffn {環境変数} PYTHONCASEOK

この環境変数が設定されている場合、 Python は @ref{7f8,,import} 文で大文字/小文字を区別しません。 これは Windows と macOS でのみ動作します。
@end deffn

@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@anchor{using/cmdline envvar-PYTHONDONTWRITEBYTECODE}@anchor{15e7}
@deffn {環境変数} PYTHONDONTWRITEBYTECODE

この変数に空でない文字列を設定した場合、 Python はソースモジュールのインポート時に @code{.pyc} ファイルを作成しようとはしなくなります。
@ref{15e6,,-B} オプションを指定するのと等価です。
@end deffn

@geindex 環境変数; PYTHONPYCACHEPREFIX
@anchor{using/cmdline envvar-PYTHONPYCACHEPREFIX}@anchor{b9b}
@deffn {環境変数} PYTHONPYCACHEPREFIX

If this is set, Python will write @code{.pyc} files in a mirror directory tree
at this path, instead of in @code{__pycache__} directories within the source
tree. This is equivalent to specifying the @ref{16f,,-X}
@code{pycache_prefix=PATH} option.


Added in version 3.8.

@end deffn

@geindex 環境変数; PYTHONHASHSEED
@anchor{using/cmdline envvar-PYTHONHASHSEED}@anchor{1289}
@deffn {環境変数} PYTHONHASHSEED

この変数が設定されていない場合や @code{random} に設定された場合、乱数値が str、bytes オブジェクトのハッシュのシードに使われます。

@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} が整数値に設定された場合、その値はハッシュランダム化が扱う型の hash() 生成の固定シードに使われます。

その目的は再現性のあるハッシュを可能にすることです。例えばインタープリタ自身の自己テストや Python プロセスのクラスタでハッシュ値を共有するのに用います。

整数は [0,4294967295] の十進数でなければなりません。0 を指定するとハッシュランダム化は無効化されます。


Added in version 3.2.3.

@end deffn

@geindex 環境変数; PYTHONINTMAXSTRDIGITS
@anchor{using/cmdline envvar-PYTHONINTMAXSTRDIGITS}@anchor{1b3a}
@deffn {環境変数} PYTHONINTMAXSTRDIGITS

If this variable is set to an integer, it is used to configure the
interpreter's global @ref{80b,,integer string conversion length limitation}.


Added in version 3.11.

@end deffn

@geindex 環境変数; PYTHONIOENCODING
@anchor{using/cmdline envvar-PYTHONIOENCODING}@anchor{120c}
@deffn {環境変数} PYTHONIOENCODING

この変数がインタープリタ実行前に設定されていた場合、@code{encodingname:errorhandler} という文法で標準入力/標準出力/標準エラー出力のエンコードを上書きします。 @code{encodingname} と @code{:errorhandler} の部分はどちらも任意で、@ref{ad2,,str.encode()} と同じ意味を持ちます。

標準エラー出力の場合、@code{:errorhandler} の部分は無視されます; ハンドラは常に @code{'backslashreplace'} です。


バージョン 3.4 で変更: @code{encodingname} の部分が任意になりました。



バージョン 3.6 で変更: On Windows, the encoding specified by this variable is ignored for interactive
console buffers unless 
@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 環境変数; PYTHONLEGACYWINDOWSSTDIO
@ref{e55,,PYTHONLEGACYWINDOWSSTDIO} is also specified.
Files and pipes redirected through the standard streams are not affected.

@end deffn

@geindex 環境変数; PYTHONNOUSERSITE
@anchor{using/cmdline envvar-PYTHONNOUSERSITE}@anchor{15a7}
@deffn {環境変数} PYTHONNOUSERSITE

この環境変数が設定されている場合、 Python は @ref{2126,,ユーザ site-packages ディレクトリ} を @ref{3e4,,sys.path} に追加しません。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 370
PEP 370@footnote{https://peps.python.org/pep-0370/} -- ユーザごとの @code{site-packages} ディレクトリ

@end deffn

@geindex 環境変数; PYTHONUSERBASE
@anchor{using/cmdline envvar-PYTHONUSERBASE}@anchor{15a5}
@deffn {環境変数} PYTHONUSERBASE

Defines the @ref{1534,,user base directory}, which is used to
compute the path of the @ref{2126,,user site-packages directory}
and @ref{2137,,installation paths} for
@code{python -m pip install --user}.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 370
PEP 370@footnote{https://peps.python.org/pep-0370/} -- ユーザごとの @code{site-packages} ディレクトリ

@end deffn

@geindex 環境変数; PYTHONEXECUTABLE
@anchor{using/cmdline envvar-PYTHONEXECUTABLE}@anchor{2138}
@deffn {環境変数} PYTHONEXECUTABLE

この環境変数が設定された場合、 @code{sys.argv[0]} に、C ランタイムから取得した値の代わりにこの環境変数の値が設定されます。macOS でのみ動作します。
@end deffn

@geindex 環境変数; PYTHONWARNINGS
@anchor{using/cmdline envvar-PYTHONWARNINGS}@anchor{da3}
@deffn {環境変数} PYTHONWARNINGS

This is equivalent to the @ref{ac6,,-W} option. If set to a comma
separated string, it is equivalent to specifying @ref{ac6,,-W} multiple
times, with filters later in the list taking precedence over those earlier
in the list.

The simplest settings apply a particular action unconditionally to all
warnings emitted by a process (even those that are otherwise ignored by
default):

@example
PYTHONWARNINGS=default  # Warn once per call location
PYTHONWARNINGS=error    # Convert to exceptions
PYTHONWARNINGS=always   # Warn every time
PYTHONWARNINGS=all      # Same as PYTHONWARNINGS=always
PYTHONWARNINGS=module   # Warn once per calling module
PYTHONWARNINGS=once     # Warn once per Python process
PYTHONWARNINGS=ignore   # Never warn
@end example

詳しくは @ref{1b1,,警告フィルタ} と @ref{212a,,Describing Warning Filters} を参照してください。
@end deffn

@geindex 環境変数; PYTHONFAULTHANDLER
@anchor{using/cmdline envvar-PYTHONFAULTHANDLER}@anchor{1291}
@deffn {環境変数} PYTHONFAULTHANDLER

If this environment variable is set to a non-empty string,
@ref{20f,,faulthandler.enable()} is called at startup: install a handler for
@ref{128c,,SIGSEGV}, @ref{128d,,SIGFPE},
@ref{128e,,SIGABRT}, @ref{128f,,SIGBUS} and
@ref{1290,,SIGILL} signals to dump the Python traceback.
This is equivalent to @ref{16f,,-X} @code{faulthandler} option.


Added in version 3.3.

@end deffn

@geindex 環境変数; PYTHONTRACEMALLOC
@anchor{using/cmdline envvar-PYTHONTRACEMALLOC}@anchor{212d}
@deffn {環境変数} PYTHONTRACEMALLOC

If this environment variable is set to a non-empty string, start tracing
Python memory allocations using the @ref{105,,tracemalloc} module. The value of
the variable is the maximum number of frames stored in a traceback of a
trace. For example, @code{PYTHONTRACEMALLOC=1} stores only the most recent
frame.
See the @ref{212c,,tracemalloc.start()} function for more information.
This is equivalent to setting the @ref{16f,,-X} @code{tracemalloc} option.


Added in version 3.4.

@end deffn

@geindex 環境変数; PYTHONPROFILEIMPORTTIME
@anchor{using/cmdline envvar-PYTHONPROFILEIMPORTTIME}@anchor{ced}
@deffn {環境変数} PYTHONPROFILEIMPORTTIME

If this environment variable is set to @code{1}, Python will show
how long each import takes. If set to @code{2}, Python will include output for
imported modules that have already been loaded.
This is equivalent to setting the @ref{16f,,-X} @code{importtime} option.


Added in version 3.7.



バージョン 3.14 で変更: Added @code{PYTHONPROFILEIMPORTTIME=2} to also trace imports of loaded modules.

@end deffn

@geindex 環境変数; PYTHONASYNCIODEBUG
@anchor{using/cmdline envvar-PYTHONASYNCIODEBUG}@anchor{2139}
@deffn {環境変数} PYTHONASYNCIODEBUG

この環境変数が空でない文字列に設定された場合、@ref{b,,asyncio} モジュールの @ref{213a,,デバッグモード} が有効化されます。


Added in version 3.4.

@end deffn

@geindex 環境変数; PYTHONMALLOC
@anchor{using/cmdline envvar-PYTHONMALLOC}@anchor{e5e}
@deffn {環境変数} PYTHONMALLOC

Set the Python memory allocators and/or install debug hooks.

Set the family of memory allocators used by Python:


@itemize *

@item 
@code{default}: use the @ref{213b,,default memory allocators}.

@item 
@code{malloc}: use the @code{malloc()} function of the C library
for all domains (@ref{213c,,PYMEM_DOMAIN_RAW}, @ref{e63,,PYMEM_DOMAIN_MEM},
@ref{e61,,PYMEM_DOMAIN_OBJ}).

@item 
@code{pymalloc}: use the @ref{f0b,,pymalloc allocator} for
@ref{e63,,PYMEM_DOMAIN_MEM} and @ref{e61,,PYMEM_DOMAIN_OBJ} domains and use
the @code{malloc()} function for the @ref{213c,,PYMEM_DOMAIN_RAW} domain.

@item 
@code{mimalloc}: use the @ref{213d,,mimalloc allocator} for
@ref{e63,,PYMEM_DOMAIN_MEM} and @ref{e61,,PYMEM_DOMAIN_OBJ} domains and use
the @code{malloc()} function for the @ref{213c,,PYMEM_DOMAIN_RAW} domain.
@end itemize

Install @ref{213e,,debug hooks}:


@itemize *

@item 
@code{debug}: install debug hooks on top of the @ref{213b,,default memory allocators}.

@item 
@code{malloc_debug}: same as @code{malloc} but also install debug hooks.

@item 
@code{pymalloc_debug}: same as @code{pymalloc} but also install debug hooks.

@item 
@code{mimalloc_debug}: same as @code{mimalloc} but also install debug hooks.
@end itemize


Added in version 3.6.



バージョン 3.7 で変更: Added the @code{"default"} allocator.

@end deffn

@geindex 環境変数; PYTHONMALLOCSTATS
@anchor{using/cmdline envvar-PYTHONMALLOCSTATS}@anchor{1f37}
@deffn {環境変数} PYTHONMALLOCSTATS

空でない文字列に設定されると、Python は新たなオブジェクトアリーナが生成される時と、シャットダウン時に @ref{f0b,,pymalloc メモリアロケータ} の統計情報を表示します。

This variable is ignored if the 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable
is used to force the @code{malloc()} allocator of the C library, or if
Python is configured without @code{pymalloc} support.


バージョン 3.6 で変更: This variable can now also be used on Python compiled in release mode.
It now has no effect if set to an empty string.

@end deffn

@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@anchor{using/cmdline envvar-PYTHONLEGACYWINDOWSFSENCODING}@anchor{33f}
@deffn {環境変数} PYTHONLEGACYWINDOWSFSENCODING

If set to a non-empty string, the default @ref{75d,,filesystem encoding and error handler} mode will revert to their pre-3.6 values of 'mbcs' and
'replace', respectively.  Otherwise, the new defaults 'utf-8' and
'surrogatepass' are used.

This may also be enabled at runtime with
@ref{33e,,sys._enablelegacywindowsfsencoding()}.

@ref{213f,,Availability}: Windows.


Added in version 3.6: より詳しくは 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} を参照してください。

@end deffn

@geindex 環境変数; PYTHONLEGACYWINDOWSSTDIO
@anchor{using/cmdline envvar-PYTHONLEGACYWINDOWSSTDIO}@anchor{e55}
@deffn {環境変数} PYTHONLEGACYWINDOWSSTDIO

If set to a non-empty string, does not use the new console reader and
writer. This means that Unicode characters will be encoded according to
the active console code page, rather than using utf-8.

This variable is ignored if the standard streams are redirected (to files
or pipes) rather than referring to console buffers.

@ref{213f,,Availability}: Windows.


Added in version 3.6.

@end deffn

@geindex 環境変数; PYTHONCOERCECLOCALE
@anchor{using/cmdline envvar-PYTHONCOERCECLOCALE}@anchor{ccc}
@deffn {環境変数} PYTHONCOERCECLOCALE

If set to the value @code{0}, causes the main Python command line application
to skip coercing the legacy ASCII-based C and POSIX locales to a more
capable UTF-8 based alternative.

If this variable is `not' set (or is set to a value other than @code{0}), the
@code{LC_ALL} locale override environment variable is also not set, and the
current locale reported for the @code{LC_CTYPE} category is either the default
@code{C} locale, or else the explicitly ASCII-based @code{POSIX} locale, then the
Python CLI will attempt to configure the following locales for the
@code{LC_CTYPE} category in the order listed before loading the interpreter
runtime:


@itemize *

@item 
@code{C.UTF-8}

@item 
@code{C.utf8}

@item 
@code{UTF-8}
@end itemize

If setting one of these locale categories succeeds, then the @code{LC_CTYPE}
environment variable will also be set accordingly in the current process
environment before the Python runtime is initialized. This ensures that in
addition to being seen by both the interpreter itself and other locale-aware
components running in the same process (such as the GNU @code{readline}
library), the updated setting is also seen in subprocesses (regardless of
whether or not those processes are running a Python interpreter), as well as
in operations that query the environment rather than the current C locale
(such as Python's own @ref{326,,locale.getdefaultlocale()}).

Configuring one of these locales (either explicitly or via the above
implicit locale coercion) automatically enables the @code{surrogateescape}
@ref{1b6f,,error handler} for @ref{75f,,sys.stdin} and
@ref{ccd,,sys.stdout} (@ref{b33,,sys.stderr} continues to use @code{backslashreplace}
as it does in any other locale). This stream handling behavior can be
overridden using 
@geindex PYTHONIOENCODING
@geindex 環境変数; PYTHONIOENCODING
@ref{120c,,PYTHONIOENCODING} as usual.

For debugging purposes, setting @code{PYTHONCOERCECLOCALE=warn} will cause
Python to emit warning messages on @code{stderr} if either the locale coercion
activates, or else if a locale that `would' have triggered coercion is
still active when the Python runtime is initialized.

Also note that even when locale coercion is disabled, or when it fails to
find a suitable target locale, 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8} will still activate by
default in legacy ASCII-based locales. Both features must be disabled in
order to force the interpreter to use @code{ASCII} instead of @code{UTF-8} for
system interfaces.

@ref{213f,,Availability}: Unix.


Added in version 3.7: より詳しくは 
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/} を参照をしてください。

@end deffn

@geindex 環境変数; PYTHONDEVMODE
@anchor{using/cmdline envvar-PYTHONDEVMODE}@anchor{ce7}
@deffn {環境変数} PYTHONDEVMODE

If this environment variable is set to a non-empty string, enable
@ref{508,,Python Development Mode}, introducing additional runtime
checks that are too expensive to be enabled by default.
This is equivalent to setting the @ref{16f,,-X} @code{dev} option.


Added in version 3.7.

@end deffn

@geindex 環境変数; PYTHONUTF8
@anchor{using/cmdline envvar-PYTHONUTF8}@anchor{ccf}
@deffn {環境変数} PYTHONUTF8

If set to @code{1}, enable the @ref{866,,Python UTF-8 Mode}.

If set to @code{0}, disable the @ref{866,,Python UTF-8 Mode}.

Setting any other non-empty string causes an error during interpreter
initialisation.


Added in version 3.7.

@end deffn

@geindex 環境変数; PYTHONWARNDEFAULTENCODING
@anchor{using/cmdline envvar-PYTHONWARNDEFAULTENCODING}@anchor{9bf}
@deffn {環境変数} PYTHONWARNDEFAULTENCODING

If this environment variable is set to a non-empty string, issue a
@ref{212e,,EncodingWarning} when the locale-specific default encoding is used.

詳細は @ref{2140,,Opt-in EncodingWarning} を参照してください。


Added in version 3.10.

@end deffn

@geindex 環境変数; PYTHONNODEBUGRANGES
@anchor{using/cmdline envvar-PYTHONNODEBUGRANGES}@anchor{7d3}
@deffn {環境変数} PYTHONNODEBUGRANGES

If this variable is set, it disables the inclusion of the tables mapping
extra location information (end line, start column offset and end column
offset) to every instruction in code objects. This is useful when smaller
code objects and pyc files are desired as well as suppressing the extra visual
location indicators when the interpreter displays tracebacks.


Added in version 3.11.

@end deffn

@geindex 環境変数; PYTHONPERFSUPPORT
@anchor{using/cmdline envvar-PYTHONPERFSUPPORT}@anchor{699}
@deffn {環境変数} PYTHONPERFSUPPORT

If this variable is set to a nonzero value, it enables support for
the Linux @code{perf} profiler so Python calls can be detected by it.

If set to @code{0}, disable Linux @code{perf} profiler support.

See also the @ref{16f,,-X perf} command-line option
and @ref{4ae,,Python support for the Linux perf profiler}.


Added in version 3.12.

@end deffn

@geindex 環境変数; PYTHON_PERF_JIT_SUPPORT
@anchor{using/cmdline envvar-PYTHON_PERF_JIT_SUPPORT}@anchor{4af}
@deffn {環境変数} PYTHON_PERF_JIT_SUPPORT

If this variable is set to a nonzero value, it enables support for
the Linux @code{perf} profiler so Python calls can be detected by it
using DWARF information.

If set to @code{0}, disable Linux @code{perf} profiler support.

See also the @ref{16f,,-X perf_jit} command-line option
and @ref{4ae,,Python support for the Linux perf profiler}.


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_DISABLE_REMOTE_DEBUG
@anchor{using/cmdline envvar-PYTHON_DISABLE_REMOTE_DEBUG}@anchor{16e}
@deffn {環境変数} PYTHON_DISABLE_REMOTE_DEBUG

If this variable is set to a non-empty string, it disables the remote
debugging feature described in 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/}. This includes both the functionality
to schedule code for execution in another process and the functionality to
receive code for execution in the current process.

See also the @ref{16f,,-X disable_remote_debug} command-line option.


Added in version 3.14.

@end deffn

@geindex 環境変数; PYTHON_CPU_COUNT
@anchor{using/cmdline envvar-PYTHON_CPU_COUNT}@anchor{51e}
@deffn {環境変数} PYTHON_CPU_COUNT

If this variable is set to a positive integer, it overrides the return
values of @ref{4db,,os.cpu_count()} and @ref{4da,,os.process_cpu_count()}.

See also the @ref{16f,,-X cpu_count} command-line option.


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_FROZEN_MODULES
@anchor{using/cmdline envvar-PYTHON_FROZEN_MODULES}@anchor{4ad}
@deffn {環境変数} PYTHON_FROZEN_MODULES

If this variable is set to @code{on} or @code{off}, it determines whether or not
frozen modules are ignored by the import machinery.  A value of @code{on} means
they get imported and @code{off} means they are ignored.  The default is @code{on}
for non-debug builds (the normal case) and @code{off} for debug builds.
Note that the @code{importlib_bootstrap} and
@code{importlib_bootstrap_external} frozen modules are always used, even
if this flag is set to @code{off}.

See also the @ref{16f,,-X frozen_modules} command-line option.


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_COLORS
@anchor{using/cmdline envvar-PYTHON_COLORS}@anchor{476}
@deffn {環境変数} PYTHON_COLORS

If this variable is set to @code{1}, the interpreter will colorize various kinds
of output. Setting it to @code{0} deactivates this behavior.
See also @ref{1b7,,色の制御}.


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_BASIC_REPL
@anchor{using/cmdline envvar-PYTHON_BASIC_REPL}@anchor{1b6}
@deffn {環境変数} PYTHON_BASIC_REPL

If this variable is set to any value, the interpreter will not attempt to
load the Python-based @ref{491,,REPL} that requires @ref{bf,,readline}, and will
instead use the traditional parser-based @ref{491,,REPL}.


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_HISTORY
@anchor{using/cmdline envvar-PYTHON_HISTORY}@anchor{4b0}
@deffn {環境変数} PYTHON_HISTORY

This environment variable can be used to set the location of a
@code{.python_history} file (by default, it is @code{.python_history} in the
user's home directory).


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_GIL
@anchor{using/cmdline envvar-PYTHON_GIL}@anchor{49a}
@deffn {環境変数} PYTHON_GIL

If this variable is set to @code{1}, the global interpreter lock (GIL) will be
forced on. Setting it to @code{0} forces the GIL off (needs Python configured with
the @ref{499,,--disable-gil} build option).

See also the @ref{16f,,-X gil} command-line option, which takes
precedence over this variable, and @ref{46d,,フリースレッドの CPython}.


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_THREAD_INHERIT_CONTEXT
@anchor{using/cmdline envvar-PYTHON_THREAD_INHERIT_CONTEXT}@anchor{1868}
@deffn {環境変数} PYTHON_THREAD_INHERIT_CONTEXT

If this variable is set to @code{1} then @ref{176,,Thread} will,
by default, use a copy of context of the caller of @code{Thread.start()}
when starting.  Otherwise, new threads will start with an empty context.
If unset, this variable defaults to @code{1} on free-threaded builds and to
@code{0} otherwise.  See also @ref{16f,,-X thread_inherit_context}.


Added in version 3.14.

@end deffn

@geindex 環境変数; PYTHON_CONTEXT_AWARE_WARNINGS
@anchor{using/cmdline envvar-PYTHON_CONTEXT_AWARE_WARNINGS}@anchor{185b}
@deffn {環境変数} PYTHON_CONTEXT_AWARE_WARNINGS

If set to @code{1} then the @ref{179,,warnings.catch_warnings} context
manager will use a @ref{1875,,ContextVar} to store warnings
filter state.  If unset, this variable defaults to @code{1} on
free-threaded builds and to @code{0} otherwise.  See @ref{16f,,-X context_aware_warnings}.


Added in version 3.14.

@end deffn

@geindex 環境変数; PYTHON_JIT
@anchor{using/cmdline envvar-PYTHON_JIT}@anchor{44d}
@deffn {環境変数} PYTHON_JIT

On builds where experimental just-in-time compilation is available, this
variable can force the JIT to be disabled (@code{0}) or enabled (@code{1}) at
interpreter startup.


Added in version 3.13.

@end deffn

@geindex 環境変数; PYTHON_TLBC
@anchor{using/cmdline envvar-PYTHON_TLBC}@anchor{2130}
@deffn {環境変数} PYTHON_TLBC

If set to @code{1} enables thread-local bytecode. If set to @code{0} thread-local
bytecode and the specializing interpreter are disabled.  Only applies to
builds configured with @ref{499,,--disable-gil}.

See also the @ref{16f,,-X tlbc} command-line option.


Added in version 3.14.

@end deffn

@menu
* デバッグモード変数:: 

@end menu

@node デバッグモード変数,,,環境変数
@anchor{using/cmdline debug-mode-variables}@anchor{2141}
@subsubsection デバッグモード変数


@geindex 環境変数; PYTHONDUMPREFS
@anchor{using/cmdline envvar-PYTHONDUMPREFS}@anchor{b9e}
@deffn {環境変数} PYTHONDUMPREFS

設定された場合、 Python はインタプリタのシャットダウン後に残っているオブジェクトと参照カウントをダンプします。

Needs Python configured with the @ref{636,,--with-trace-refs} build option.
@end deffn

@geindex 環境変数; PYTHONDUMPREFSFILE
@anchor{using/cmdline envvar-PYTHONDUMPREFSFILE}@anchor{1c3f}
@deffn {環境変数} PYTHONDUMPREFSFILE

If set, Python will dump objects and reference counts still alive
after shutting down the interpreter into a file under the path given
as the value to this environment variable.

Needs Python configured with the @ref{636,,--with-trace-refs} build option.


Added in version 3.11.

@end deffn

@geindex 環境変数; PYTHON_PRESITE
@anchor{using/cmdline envvar-PYTHON_PRESITE}@anchor{212f}
@deffn {環境変数} PYTHON_PRESITE

If this variable is set to a module, that module will be imported
early in the interpreter lifecycle, before the @ref{cc,,site} module is
executed, and before the @ref{1,,__main__} module is created.
Therefore, the imported module is not treated as @ref{1,,__main__}.

This can be used to execute code early during Python initialization.

To import a submodule, use @code{package.module} as the value, like in
an import statement.

See also the @ref{16f,,-X presite} command-line option,
which takes precedence over this variable.

Needs Python configured with the @ref{666,,--with-pydebug} build option.


Added in version 3.13.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Unix プラットフォームで Python を使う,Python を構成する,コマンドラインと環境<2>,Python のセットアップと利用
@anchor{using/unix doc}@anchor{2142}@anchor{using/unix translation-repo}@anchor{2143}@anchor{using/unix using-on-unix}@anchor{2144}@anchor{using/unix using-python-on-unix-platforms}@anchor{2145}
@section Unix プラットフォームで Python を使う


@menu
* 最新バージョンの Python の取得とインストール:: 
* Python のビルド:: 
* Python に関係するパスとファイル:: 
* その他: その他<2>. 
* カスタムの OpenSSL:: 

@end menu

@node 最新バージョンの Python の取得とインストール,Python のビルド,,Unix プラットフォームで Python を使う
@anchor{using/unix getting-and-installing-the-latest-version-of-python}@anchor{2146}
@subsection 最新バージョンの Python の取得とインストール


@menu
* Linux:: 
* FreeBSD と OpenBSD:: 

@end menu

@node Linux,FreeBSD と OpenBSD,,最新バージョンの Python の取得とインストール
@anchor{using/unix on-linux}@anchor{2147}
@subsubsection Linux


Python comes preinstalled on most Linux distributions, and is available as a
package on all others.  However there are certain features you might want to use
that are not available on your distro's package.  You can compile the
latest version of Python from source.

In the event that the latest version of Python doesn't come preinstalled and isn't
in the repositories as well, you can make packages for your own distro.  Have a
look at the following links:


@subsubheading 参考



@table @asis

@item @indicateurl{https://www.debian.org/doc/manuals/maint-guide/first.en.html}

Debian ユーザー向け

@item @indicateurl{https://en.opensuse.org/Portal:Packaging}

OpenSuse ユーザー向け

@item @indicateurl{https://docs.fedoraproject.org/en-US/package-maintainers/Packaging_Tutorial_GNU_Hello/}

Fedora ユーザー向け

@item @indicateurl{https://slackbook.org/html/package-management-making-packages.html}

Slackware ユーザー向け
@end table


@menu
* IDLE のインストール:: 

@end menu

@node IDLE のインストール,,,Linux
@anchor{using/unix installing-idle}@anchor{2148}@anchor{using/unix installing-idle-on-linux}@anchor{2149}
@subsubsection IDLE のインストール


場合によっては、 IDLE は Python インストールに含まれていない可能性があります。


@itemize *

@item 
Debian と Ubuntu ユーザー:

@example
sudo apt update
sudo apt install idle
@end example

@item 
Fedora や RHEL 、 CentOS ユーザーは:

@example
sudo dnf install python3-idle
@end example

@item 
SUSE と OpenSUSE ユーザーは:

@example
sudo zypper install python3-idle
@end example

@item 
Alpine Linux ユーザーは:

@example
sudo apk add python3-idle
@end example
@end itemize

@node FreeBSD と OpenBSD,,Linux,最新バージョンの Python の取得とインストール
@anchor{using/unix on-freebsd-and-openbsd}@anchor{214a}
@subsubsection FreeBSD と OpenBSD



@itemize *

@item 
FreeBSD ユーザーが Python パッケージを追加するには次のようにしてください:

@example
pkg install python3
@end example

@item 
OpenBSD ユーザーが Python パッケージを追加するには次のようにしてください:

@example
pkg_add -r python

pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<ここにアーキテクチャを挿入>/python-<バージョン>.tgz
@end example

例えば、i386 ユーザーが Python 2.5.1 を取得するには次のようにします:

@example
pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz
@end example
@end itemize

@node Python のビルド,Python に関係するパスとファイル,最新バージョンの Python の取得とインストール,Unix プラットフォームで Python を使う
@anchor{using/unix building-python}@anchor{214b}@anchor{using/unix building-python-on-unix}@anchor{10f6}
@subsection Python のビルド



@subsubheading 参考


If you want to contribute to CPython, refer to the
devguide@footnote{https://devguide.python.org/getting-started/setup-building/},
which includes build instructions and other tips on setting up environment.


If you want to compile CPython yourself, first thing you should do is get the
source@footnote{https://www.python.org/downloads/source/}. You can download either the
latest release's source or grab a fresh clone@footnote{https://devguide.python.org/setup/#get-the-source-code}.
You will also need to install the @ref{214c,,build requirements}.

ビルド手順は通常のコマンドで行います

@example
./configure
make
make install
@end example

@ref{214d,,Configure のオプション} や特定の Unix プラットフォームにおける注意点は Python ソースツリーのルートにある README.rst@footnote{https://github.com/python/cpython/tree/3.14/README.rst} に細かく記載されています。

@cartouche
@quotation 警告 
@code{make install} は @code{python3} バイナリを上書きまたはリンクを破壊してしまうかもしれません。そのため、@code{make install} の代わりに @code{`exec_prefix'/bin/python`version'} のみインストールする @code{make altinstall} が推奨されています。
@end quotation
@end cartouche

@node Python に関係するパスとファイル,その他<2>,Python のビルド,Unix プラットフォームで Python を使う
@anchor{using/unix python-related-paths-and-files}@anchor{214e}
@subsection Python に関係するパスとファイル


これらはローカルインストールの慣例に応じて変化します; @ref{214f,,prefix} と @ref{2150,,exec_prefix} はインストール状況に依存していて、GNU ソフトウェアによって解釈されます; この二つは同じである場合があります。

例えば、ほとんどの Linux システムでは、両方のデフォルトが @code{/usr} です。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ファイル/ディレクトリ

@tab

意味

@item

@code{`exec_prefix'/bin/python3}

@tab

インタプリタの推奨される場所

@item

@code{`prefix'/lib/python`version'},
@code{`exec_prefix'/lib/python`version'}

@tab

標準モジュールを格納するディレクトリの、推奨される場所。

@item

@code{`prefix'/include/python`version'},
@code{`exec_prefix'/include/python`version'}

@tab

Python 拡張や Python の埋込みに必要となる include ファイルを格納するディレクトリの推奨される場所。

@end multitable


@node その他<2>,カスタムの OpenSSL,Python に関係するパスとファイル,Unix プラットフォームで Python を使う
@anchor{using/unix miscellaneous}@anchor{2151}
@subsection その他


Python スクリプトを Unix で簡単に使うためには、例えば次のようにしてスクリプトを実行可能ファイルにし、

@example
$ chmod +x script
@end example

適切な shebang 行をスクリプトの先頭に置きます。たいていの場合良い方法は

@example
#!/usr/bin/env python3
@end example

で、
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} 全体から Python インタープリターを探します。しかし、いくつかの Unix は @code{env} コマンドを持たないので、インタープリターのパスを @code{/usr/bin/python3} のようにハードコードしなければならないかもしれません。

シェルコマンドを Python スクリプトから使うには、 @ref{dc,,subprocess} モジュールを参照してください。

@node カスタムの OpenSSL,,その他<2>,Unix プラットフォームで Python を使う
@anchor{using/unix custom-openssl}@anchor{2152}@anchor{using/unix unix-custom-openssl}@anchor{2153}
@subsection カスタムの OpenSSL



@enumerate 

@item 
To use your vendor's OpenSSL configuration and system trust store, locate
the directory with @code{openssl.cnf} file or symlink in @code{/etc}. On most
distribution the file is either in @code{/etc/ssl} or @code{/etc/pki/tls}. The
directory should also contain a @code{cert.pem} file and/or a @code{certs}
directory.

@example
$ find /etc/ -name openssl.cnf -printf "%h\n"
/etc/ssl
@end example

@item 
Download, build, and install OpenSSL. Make sure you use @code{install_sw} and
not @code{install}. The @code{install_sw} target does not override
@code{openssl.cnf}.

@example
$ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz
$ tar xzf openssl-VERSION
$ pushd openssl-VERSION
$ ./config \
    --prefix=/usr/local/custom-openssl \
    --libdir=lib \
    --openssldir=/etc/ssl
$ make -j1 depend
$ make -j8
$ make install_sw
$ popd
@end example

@item 
Build Python with custom OpenSSL
(see the configure @code{--with-openssl} and @code{--with-openssl-rpath} options)

@example
$ pushd python-3.x.x
$ ./configure -C \
    --with-openssl=/usr/local/custom-openssl \
    --with-openssl-rpath=auto \
    --prefix=/usr/local/python-3.x.x
$ make -j8
$ make altinstall
@end example
@end enumerate

@cartouche
@quotation 注釈 
Patch releases of OpenSSL have a backwards compatible ABI. You don't need
to recompile Python to update OpenSSL. It's sufficient to replace the
custom OpenSSL installation with a newer version.
@end quotation
@end cartouche

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python を構成する,Windows で Python を使う,Unix プラットフォームで Python を使う,Python のセットアップと利用
@anchor{using/configure doc}@anchor{2154}@anchor{using/configure configure-python}@anchor{2155}@anchor{using/configure translation-repo}@anchor{2156}
@section Python を構成する


@menu
* ビルド要件:: 
* 生成されるファイル:: 
* Configureオプション:: 
* Python ビルドシステム:: 
* Compiler and linker flags:: 

@end menu

@node ビルド要件,生成されるファイル,,Python を構成する
@anchor{using/configure build-requirements}@anchor{214c}@anchor{using/configure id1}@anchor{2157}
@subsection ビルド要件


CPython をビルドするためには、次のものが必要です:


@itemize *

@item 
C11@footnote{https://en.cppreference.com/w/c/11} コンパイラ。 C11 オプション機能@footnote{https://en.wikipedia.org/wiki/C11_(C_standard_revision)#Optional_features} は不要です。

@item 
Windows では、 Microsoft Visual Studio 2017 以降が必要です。

@item 
IEEE 754@footnote{https://en.wikipedia.org/wiki/IEEE_754} 浮動小数点数と 浮動小数点 Not-a-Number (NaN)@footnote{https://en.wikipedia.org/wiki/NaN#Floating_point} のサポート。

@item 
スレッドのサポート。
@end itemize


バージョン 3.5 で変更: Windows では、 Visual Studio 2015 以降が必要となりました。



バージョン 3.6 で変更: Selected C99 features, like @code{<stdint.h>} and @code{static inline} functions,
are now required.



バージョン 3.7 で変更: Thread support is now required.



バージョン 3.11 で変更: C11 compiler, IEEE 754 and NaN support are now required.
On Windows, Visual Studio 2017 or later is required.


See also 
@geindex Python Enhancement Proposals; PEP 7
PEP 7@footnote{https://peps.python.org/pep-0007/} "Style Guide for C Code" and 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/} "CPython platform
support".

@menu
* オプションのモジュールの要件:: 

@end menu

@node オプションのモジュールの要件,,,ビルド要件
@anchor{using/configure optional-module-requirements}@anchor{2158}@anchor{using/configure requirements-for-optional-modules}@anchor{2159}
@subsubsection オプションのモジュールの要件


Some @ref{215a,,optional modules} of the standard library
require third-party libraries installed for development
(for example, header files must be available).

Missing requirements are reported in the @code{configure} output.
Modules that are missing due to missing dependencies are listed near the end
of the @code{make} output,
sometimes using an internal name, for example, @code{_ctypes} for @ref{2e,,ctypes}
module.

If you distribute a CPython interpreter without optional modules,
it's best practice to advise users, who generally expect that
standard library modules are available.

Dependencies to build optional modules are:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

依存関係

@tab

最小バージョン

@tab

Python モジュール

@item

libbz2@footnote{https://sourceware.org/bzip2/}

@tab

@tab

@ref{14,,bz2}

@item

libffi@footnote{https://sourceware.org/libffi/}

@tab

3.3.0 推奨

@tab

@ref{2e,,ctypes}

@item

liblzma@footnote{https://tukaani.org/xz/}

@tab

@tab

@ref{8e,,lzma}

@item

libmpdec@footnote{https://www.bytereef.org/mpdecimal/doc/libmpdec/}

@tab

2.5.0

@tab

@ref{3a,,decimal} @footnote{
If `libmpdec' is not available, the @ref{3a,,decimal} module will use
a pure-Python implementation.
See @ref{657,,--with-system-libmpdec} for details.
}

@item

libreadline@footnote{https://tiswww.case.edu/php/chet/readline/rltop.html} または libedit@footnote{https://www.thrysoee.dk/editline/} @footnote{
See @ref{215b,,--with-readline} for choosing the backend for the
@ref{bf,,readline} module.
}

@tab

@tab

@ref{bf,,readline}

@item

libuuid@footnote{https://linux.die.net/man/3/libuuid}

@tab

@tab

@code{_uuid} @footnote{
The @ref{116,,uuid} module uses @code{_uuid} to generate "safe" UUIDs.
See the module documentation for details.
}

@item

ncurses@footnote{https://gnu.org/software/ncurses/ncurses.html} @footnote{
The @ref{2f,,curses} module requires the @code{libncurses} or @code{libncursesw}
library.
The @ref{31,,curses.panel} module additionally requires the @code{libpanel} or
@code{libpanelw} library.
}

@tab

@tab

@ref{2f,,curses}

@item

OpenSSL@footnote{https://openssl-library.org/}

@tab


@display
3.0.18 推奨@w{ }
(1.1.1 最小)@w{ }
@end display



@tab

@ref{d5,,ssl}, @ref{6c,,hashlib} @footnote{
If OpenSSL is not available, the @ref{6c,,hashlib} module will use
bundled implementations of several hash functions.
See @ref{215c,,--with-builtin-hashlib-hashes} for `forcing' usage of OpenSSL.
}

@item

SQLite@footnote{https://sqlite.org/}

@tab

3.15.2

@tab

@ref{d4,,sqlite3}

@item

Tcl/Tk@footnote{https://www.tcl-lang.org/}

@tab

8.5.12

@tab

@ref{f6,,tkinter}, @ref{1217,,IDLE}, @ref{107,,turtle}

@item

zlib@footnote{https://www.zlib.net}

@tab

1.2.2.1

@tab

@ref{139,,zlib}, @ref{6b,,gzip}, @ref{59,,ensurepip}

@item

zstd@footnote{https://facebook.github.io/zstd/}

@tab

1.4.5

@tab

@ref{23,,compression.zstd}

@end multitable


Note that the table does not include all optional modules; in particular,
platform-specific modules like @ref{11c,,winreg} are not listed here.


@subsubheading 参考



@itemize *

@item 
The devguide@footnote{https://devguide.python.org/getting-started/setup-building/#install-dependencies}
includes a full list of dependencies required to build all modules and
instructions on how to install them on common platforms.

@item 
@ref{1b2d,,--with-system-expat} allows building with an external
libexpat@footnote{https://libexpat.github.io/} library.

@item 
@ref{215d,,サードパーティ依存関係のオプション}
@end itemize



バージョン 3.1 で変更: @ref{f6,,tkinter} には Tcl/Tk バージョン 8.3.1 が必要となりました。



バージョン 3.5 で変更: @ref{f6,,tkinter} には Tck/Tk バージョン 8.4 が必要となりました。



バージョン 3.7 で変更: @ref{6c,,hashlib} と @ref{d5,,ssl} には OpenSSL 1.0.2 が必要となりました。



バージョン 3.10 で変更: @ref{6c,,hashlib} と @ref{d5,,ssl} には OpenSSL 1.1.1 が必要となりました。 @ref{d4,,sqlite3} には SQLite 3.7.15 が必要となりました。



バージョン 3.11 で変更: @ref{f6,,tkinter} には Tcl/Tk バージョン 8.5.12 が必要となりました。



バージョン 3.13 で変更: @ref{d4,,sqlite3} にはSQLite 3.15.2 が必要となりました。


@node 生成されるファイル,Configureオプション,ビルド要件,Python を構成する
@anchor{using/configure generated-files}@anchor{215e}
@subsection 生成されるファイル


To reduce build dependencies, Python source code contains multiple generated
files. Commands to regenerate all generated files:

@example
make regen-all
make regen-stdlib-module-names
make regen-limited-abi
make regen-configure
@end example

The @code{Makefile.pre.in} file documents generated files, their inputs, and tools used
to regenerate them. Search for @code{regen-*} make targets.

@menu
* 構成スクリプト:: 

@end menu

@node 構成スクリプト,,,生成されるファイル
@anchor{using/configure configure-script}@anchor{215f}
@subsubsection 構成スクリプト


The @code{make regen-configure} command regenerates the @code{aclocal.m4} file and
the @code{configure} script using the @code{Tools/build/regen-configure.sh} shell
script which uses an Ubuntu container to get the same tools versions and have a
reproducible output.

The container is optional, the following command can be run locally:

@example
autoreconf -ivf -Werror
@end example

The generated files can change depending on the exact versions of the
tools used.
The container that CPython uses has
Autoconf@footnote{https://gnu.org/software/autoconf} 2.72,
@code{aclocal} from Automake@footnote{https://www.gnu.org/software/automake} 1.16.5,
and pkg-config@footnote{https://www.freedesktop.org/wiki/Software/pkg-config/} 1.8.1.


バージョン 3.13 で変更: Autoconf 2.71 and aclocal 1.16.5 and are now used to regenerate
@code{configure}.



バージョン 3.14 で変更: Autoconf 2.72 is now used to regenerate @code{configure}.


@node Configureオプション,Python ビルドシステム,生成されるファイル,Python を構成する
@anchor{using/configure configure-options}@anchor{214d}@anchor{using/configure id12}@anchor{2160}
@subsection Configureオプション


次のコマンドを使用して、全ての @code{configure} スクリプトのオプションを表示できます:

@example
./configure --help
@end example

Pythonのソース配布の中の @code{Misc/SpecialBuilds.txt} も参照してください。

@menu
* 一般的なオプション:: 
* C コンパイラのオプション:: 
* リンカのオプション:: 
* サードパーティ依存関係のオプション:: 
* WebAssembly オプション:: 
* インストールオプション:: 
* パフォーマンスに関するオプション:: 
* Python デバッグビルド:: 
* Debug options:: 
* リンカのオプション: リンカのオプション<2>. 
* Libraries options:: 
* Security Options:: 
* macOS のオプション:: 
* iOS のオプション:: 
* クロスコンパイルのオプション:: 

@end menu

@node 一般的なオプション,C コンパイラのオプション,,Configureオプション
@anchor{using/configure general-options}@anchor{2161}
@subsubsection 一般的なオプション


@geindex コマンドラインオプション; --enable-loadable-sqlite-extensions
@anchor{using/configure cmdoption-enable-loadable-sqlite-extensions}@anchor{2162}
@deffn {Option} @w{-}@w{-}enable@w{-}loadable@w{-}sqlite@w{-}extensions

Support loadable extensions in the @code{_sqlite} extension module (default
is no) of the @ref{d4,,sqlite3} module.

@ref{d4,,sqlite3} モジュールの @ref{a3f,,sqlite3.Connection.enable_load_extension()} メソッドを参照してください。


Added in version 3.6.

@end deffn

@geindex コマンドラインオプション; --disable-ipv6
@anchor{using/configure cmdoption-disable-ipv6}@anchor{2163}
@deffn {Option} @w{-}@w{-}disable@w{-}ipv6

IPv6サポートを無効にします(サポートされている場合はデフォルトで有効)、 @ref{d1,,socket} モジュールを参照してください。
@end deffn

@geindex コマンドラインオプション; --enable-big-digits
@anchor{using/configure cmdoption-enable-big-digits}@anchor{953}
@deffn {Option} @w{-}@w{-}enable@w{-}big@w{-}digits=[15|30]

Python @ref{19b,,int} の桁の大きさをビット単位で定義します: 15ビットまたは30ビットです。

デフォルトでは、桁の大きさは30です。

@code{PYLONG_BITS_IN_DIGIT} を @code{15} または @code{30} に定義します。

@ref{14ab,,sys.int_info.bits_per_digit} を参照してください。
@end deffn

@geindex コマンドラインオプション; --with-suffix
@anchor{using/configure cmdoption-with-suffix}@anchor{2164}
@deffn {Option} @w{-}@w{-}with@w{-}suffix=SUFFIX

Python の実行ファイルの接尾辞を `SUFFIX' に設定します。

デフォルトの接尾辞は、 Windows と macOS では @code{.exe} ( @code{python.exe} 実行ファイル)、 Emscripten node では @code{.js} 、 Emscripten browser では @code{.html} 、 WASI では @code{.wasm} 、その他のプラットフォームでは空文字列になります ( @code{python} 実行ファイル)。


バージョン 3.11 で変更: WASM プラットフォームのデフォルトの接頭辞は、 @code{.js} 、 @code{.html} 、 @code{.wasm} のうちの1つです。

@end deffn

@geindex コマンドラインオプション; --with-tzpath
@anchor{using/configure cmdoption-with-tzpath}@anchor{2165}
@deffn {Option} @w{-}@w{-}with@w{-}tzpath=<list of absolute paths separated by pathsep>

デフォルトのタイムゾーン検索パスを @ref{2166,,zoneinfo.TZPATH} に設定します。@ref{13a,,zoneinfo} モジュールの @ref{2167,,Compile-time configuration} を参照してください。

デフォルト: @code{/usr/share/zoneinfo:/usr/lib/zoneinfo:/usr/share/lib/zoneinfo:/etc/zoneinfo}

@ref{2134,,os.pathsep} パスセパレータを参照してください。


Added in version 3.9.

@end deffn

@geindex コマンドラインオプション; --without-decimal-contextvar
@anchor{using/configure cmdoption-without-decimal-contextvar}@anchor{2168}
@deffn {Option} @w{-}@w{-}without@w{-}decimal@w{-}contextvar

コルーチンローカルコンテキスト(デフォルト)ではなく、スレッドローカルコンテキストを使用して @code{_decimal} 拡張モジュールをビルドします。 @ref{3a,,decimal} モジュールを参照してください。

@ref{2169,,decimal.HAVE_CONTEXTVAR} および @ref{28,,contextvars} モジュールを参照してください。


Added in version 3.9.

@end deffn

@geindex コマンドラインオプション; --with-dbmliborder
@anchor{using/configure cmdoption-with-dbmliborder}@anchor{216a}
@deffn {Option} @w{-}@w{-}with@w{-}dbmliborder=<list of backend names>

@ref{35,,dbm} モジュールの DB バックエンドをチェックする順序をオーバーライドします。

有効な値は、バックエンド名をコロン( @code{:} )で区切った文字列です:


@itemize *

@item 
@code{ndbm};

@item 
@code{gdbm};

@item 
@code{bdb}。
@end itemize
@end deffn

@geindex コマンドラインオプション; --without-c-locale-coercion
@anchor{using/configure cmdoption-without-c-locale-coercion}@anchor{216b}
@deffn {Option} @w{-}@w{-}without@w{-}c@w{-}locale@w{-}coercion

UTF-8 ベースのロケールへの C ロケールの強制を無効にします(デフォルトで有効)。

@code{PY_COERCE_C_LOCALE} マクロは定義しないでください。

@geindex PYTHONCOERCECLOCALE
@geindex 環境変数; PYTHONCOERCECLOCALE
@ref{ccc,,PYTHONCOERCECLOCALE} および 
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/} を参照してください。
@end deffn

@geindex コマンドラインオプション; --with-platlibdir
@anchor{using/configure cmdoption-with-platlibdir}@anchor{216c}
@deffn {Option} @w{-}@w{-}with@w{-}platlibdir=DIRNAME

Python のライブラリディレクトリ名(デフォルトは @code{lib} )。

Fedora と SuSE は64ビットプラットフォームで @code{lib64} を使用します。

@ref{b32,,sys.platlibdir} を参照してください。


Added in version 3.9.

@end deffn

@geindex コマンドラインオプション; --with-wheel-pkg-dir
@anchor{using/configure cmdoption-with-wheel-pkg-dir}@anchor{a8d}
@deffn {Option} @w{-}@w{-}with@w{-}wheel@w{-}pkg@w{-}dir=PATH

@ref{59,,ensurepip} モジュールが使用する wheel パッケージのディレクトリです(デフォルトはなし)。

Linux ディストリビューションのパッケージングポリシーの中には、依存関係をバンドルすることを推奨しているものがあります。例えば、 Fedora は wheel パッケージを @code{/usr/share/python-wheels/} ディレクトリにインストールし、 @code{ensurepip._bundled} パッケージはインストールしません。


Added in version 3.10.

@end deffn

@geindex コマンドラインオプション; --with-pkg-config
@anchor{using/configure cmdoption-with-pkg-config}@anchor{216d}
@deffn {Option} @w{-}@w{-}with@w{-}pkg@w{-}config=[check|yes|no]

configure がビルドの依存関係を検出するために @code{pkg-config} を使用するかどうかを設定します。


@itemize *

@item 
@code{check} (デフォルト): @code{pkg-config} はオプションです。

@item 
@code{yes} : @code{pkg-config} は必須です。

@item 
@code{no} : @code{pkg-config} が存在しても、 configure は使用しません。
@end itemize


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; --enable-pystats
@anchor{using/configure cmdoption-enable-pystats}@anchor{1b38}
@deffn {Option} @w{-}@w{-}enable@w{-}pystats

Turn on internal Python performance statistics gathering.

By default, statistics gathering is off. Use @code{python3 -X pystats} command
or set @code{PYTHONSTATS=1} environment variable to turn on statistics
gathering at Python startup.

At Python exit, dump statistics if statistics gathering was on and not
cleared.

Effects:


@itemize *

@item 
Add @ref{16f,,-X pystats} command line option.

@item 
Add @code{PYTHONSTATS} environment variable.

@item 
Define the @code{Py_STATS} macro.

@item 
Add functions to the @ref{df,,sys} module:


@itemize *

@item 
@code{sys._stats_on()}: Turns on statistics gathering.

@item 
@code{sys._stats_off()}: Turns off statistics gathering.

@item 
@code{sys._stats_clear()}: Clears the statistics.

@item 
@code{sys._stats_dump()}: Dump statistics to file, and clears the statistics.
@end itemize
@end itemize

The statistics will be dumped to a arbitrary (probably unique) file in
@code{/tmp/py_stats/} (Unix) or @code{C:\temp\py_stats\} (Windows). If that
directory does not exist, results will be printed on stderr.

統計情報を読むには @code{Tools/scripts/summarize_stats.py} を使用してください。

統計:


@itemize *

@item 
Opcode:


@itemize *

@item 
Specialization: success, failure, hit, deferred, miss, deopt, failures;

@item 
Execution count;

@item 
Pair count.
@end itemize

@item 
Call:


@itemize *

@item 
Inlined Python calls;

@item 
PyEval calls;

@item 
Frames pushed;

@item 
Frame object created;

@item 
Eval calls: vector, generator, legacy, function VECTORCALL, build class,
slot, function "ex", API, method.
@end itemize

@item 
Object:


@itemize *

@item 
incref and decref;

@item 
interpreter incref and decref;

@item 
allocations: all, 512 bytes, 4 kiB, big;

@item 
free;

@item 
to/from free lists;

@item 
dictionary materialized/dematerialized;

@item 
type cache;

@item 
optimization attempts;

@item 
optimization traces created/executed;

@item 
uops executed.
@end itemize

@item 
Garbage collector:


@itemize *

@item 
Garbage collections;

@item 
Objects visited;

@item 
Objects collected.
@end itemize
@end itemize


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; --disable-gil
@anchor{using/configure free-threading-build}@anchor{216e}@anchor{using/configure cmdoption-disable-gil}@anchor{499}
@deffn {Option} @w{-}@w{-}disable@w{-}gil

Enables support for running Python without the @ref{474,,global interpreter lock} (GIL): @ref{176d,,free-threaded build}.

Defines the @code{Py_GIL_DISABLED} macro and adds @code{"t"} to
@ref{c59,,sys.abiflags}.

See @ref{46d,,フリースレッドの CPython} for more detail.


Added in version 3.13.

@end deffn

@geindex コマンドラインオプション; --enable-experimental-jit
@anchor{using/configure cmdoption-enable-experimental-jit}@anchor{44e}
@deffn {Option} @w{-}@w{-}enable@w{-}experimental@w{-}jit=[no|yes|yes@w{-}off|interpreter]

Indicate how to integrate the @ref{159,,experimental just-in-time compiler}.


@itemize *

@item 
@code{no}: Don't build the JIT.

@item 
@code{yes}: Enable the JIT. To disable it at runtime, set the environment
variable 
@geindex PYTHON_JIT
@geindex 環境変数; PYTHON_JIT
@ref{44d,,PYTHON_JIT=0}.

@item 
@code{yes-off}: Build the JIT, but disable it by default. To enable it at
runtime, set the environment variable 
@geindex PYTHON_JIT
@geindex 環境変数; PYTHON_JIT
@ref{44d,,PYTHON_JIT=1}.

@item 
@code{interpreter}: Enable the "JIT interpreter" (only useful for those
debugging the JIT itself). To disable it at runtime, set the environment
variable 
@geindex PYTHON_JIT
@geindex 環境変数; PYTHON_JIT
@ref{44d,,PYTHON_JIT=0}.
@end itemize

@code{--enable-experimental-jit=no} is the default behavior if the option is not
provided, and @code{--enable-experimental-jit} is shorthand for
@code{--enable-experimental-jit=yes}.  See @code{Tools/jit/README.md} for more
information, including how to install the necessary build-time dependencies.

@cartouche
@quotation 注釈 
When building CPython with JIT enabled, ensure that your system has Python 3.11 or later installed.
@end quotation
@end cartouche


Added in version 3.13.

@end deffn

@geindex コマンドラインオプション; PKG_CONFIG
@anchor{using/configure cmdoption-arg-PKG_CONFIG}@anchor{216f}
@deffn {Option} PKG_CONFIG

Path to @code{pkg-config} utility.
@end deffn

@geindex コマンドラインオプション; PKG_CONFIG_LIBDIR
@anchor{using/configure cmdoption-arg-PKG_CONFIG_LIBDIR}@anchor{2170}
@deffn {Option} PKG_CONFIG_LIBDIR
@end deffn

@geindex コマンドラインオプション; PKG_CONFIG_PATH
@anchor{using/configure cmdoption-arg-PKG_CONFIG_PATH}@anchor{2171}
@deffn {Option} PKG_CONFIG_PATH

@code{pkg-config} options.
@end deffn

@node C コンパイラのオプション,リンカのオプション,一般的なオプション,Configureオプション
@anchor{using/configure c-compiler-options}@anchor{2172}
@subsubsection C コンパイラのオプション


@geindex コマンドラインオプション; CC
@anchor{using/configure cmdoption-arg-CC}@anchor{2173}
@deffn {Option} CC

C コンパイラのコマンド。
@end deffn

@geindex コマンドラインオプション; CFLAGS
@anchor{using/configure cmdoption-arg-CFLAGS}@anchor{2174}
@deffn {Option} CFLAGS

C コンパイラのフラグ。
@end deffn

@geindex コマンドラインオプション; CPP
@anchor{using/configure cmdoption-arg-CPP}@anchor{2175}
@deffn {Option} CPP

C プリプロセッサのコマンド。
@end deffn

@geindex コマンドラインオプション; CPPFLAGS
@anchor{using/configure cmdoption-arg-CPPFLAGS}@anchor{2176}
@deffn {Option} CPPFLAGS

C プリプロセッサのフラグ。 (@code{-I@var{include_dir}} など)
@end deffn

@node リンカのオプション,サードパーティ依存関係のオプション,C コンパイラのオプション,Configureオプション
@anchor{using/configure linker-options}@anchor{2177}
@subsubsection リンカのオプション


@geindex コマンドラインオプション; LDFLAGS
@anchor{using/configure cmdoption-arg-LDFLAGS}@anchor{2178}
@deffn {Option} LDFLAGS

リンカのフラグ。 (@code{-L@var{library_directory}} など)
@end deffn

@geindex コマンドラインオプション; LIBS
@anchor{using/configure cmdoption-arg-LIBS}@anchor{2179}
@deffn {Option} LIBS

リンカに渡すライブラリ。 (@code{-l@var{library}} など)
@end deffn

@geindex コマンドラインオプション; MACHDEP
@anchor{using/configure cmdoption-arg-MACHDEP}@anchor{217a}
@deffn {Option} MACHDEP

マシン依存のライブラリファイルの名前。
@end deffn

@node サードパーティ依存関係のオプション,WebAssembly オプション,リンカのオプション,Configureオプション
@anchor{using/configure configure-options-for-dependencies}@anchor{215d}@anchor{using/configure options-for-third-party-dependencies}@anchor{217b}
@subsubsection サードパーティ依存関係のオプション



Added in version 3.11.


@geindex コマンドラインオプション; BZIP2_CFLAGS
@anchor{using/configure cmdoption-arg-BZIP2_CFLAGS}@anchor{217c}
@deffn {Option} BZIP2_CFLAGS
@end deffn

@geindex コマンドラインオプション; BZIP2_LIBS
@anchor{using/configure cmdoption-arg-BZIP2_LIBS}@anchor{217d}
@deffn {Option} BZIP2_LIBS

C compiler and linker flags to link Python to @code{libbz2}, used by @ref{14,,bz2}
module, overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; CURSES_CFLAGS
@anchor{using/configure cmdoption-arg-CURSES_CFLAGS}@anchor{217e}
@deffn {Option} CURSES_CFLAGS
@end deffn

@geindex コマンドラインオプション; CURSES_LIBS
@anchor{using/configure cmdoption-arg-CURSES_LIBS}@anchor{217f}
@deffn {Option} CURSES_LIBS

C compiler and linker flags for @code{libncurses} or @code{libncursesw}, used by
@ref{2f,,curses} module, overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; GDBM_CFLAGS
@anchor{using/configure cmdoption-arg-GDBM_CFLAGS}@anchor{2180}
@deffn {Option} GDBM_CFLAGS
@end deffn

@geindex コマンドラインオプション; GDBM_LIBS
@anchor{using/configure cmdoption-arg-GDBM_LIBS}@anchor{2181}
@deffn {Option} GDBM_LIBS

C compiler and linker flags for @code{gdbm}.
@end deffn

@geindex コマンドラインオプション; LIBEDIT_CFLAGS
@anchor{using/configure cmdoption-arg-LIBEDIT_CFLAGS}@anchor{2182}
@deffn {Option} LIBEDIT_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBEDIT_LIBS
@anchor{using/configure cmdoption-arg-LIBEDIT_LIBS}@anchor{2183}
@deffn {Option} LIBEDIT_LIBS

C compiler and linker flags for @code{libedit}, used by @ref{bf,,readline} module,
overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; LIBFFI_CFLAGS
@anchor{using/configure cmdoption-arg-LIBFFI_CFLAGS}@anchor{2184}
@deffn {Option} LIBFFI_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBFFI_LIBS
@anchor{using/configure cmdoption-arg-LIBFFI_LIBS}@anchor{2185}
@deffn {Option} LIBFFI_LIBS

C compiler and linker flags for @code{libffi}, used by @ref{2e,,ctypes} module,
overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; LIBMPDEC_CFLAGS
@anchor{using/configure cmdoption-arg-LIBMPDEC_CFLAGS}@anchor{2186}
@deffn {Option} LIBMPDEC_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBMPDEC_LIBS
@anchor{using/configure cmdoption-arg-LIBMPDEC_LIBS}@anchor{2187}
@deffn {Option} LIBMPDEC_LIBS

C compiler and linker flags for @code{libmpdec}, used by @ref{3a,,decimal} module,
overriding @code{pkg-config}.

@cartouche
@quotation 注釈 
These environment variables have no effect unless
@ref{657,,--with-system-libmpdec} is specified.
@end quotation
@end cartouche
@end deffn

@geindex コマンドラインオプション; LIBLZMA_CFLAGS
@anchor{using/configure cmdoption-arg-LIBLZMA_CFLAGS}@anchor{2188}
@deffn {Option} LIBLZMA_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBLZMA_LIBS
@anchor{using/configure cmdoption-arg-LIBLZMA_LIBS}@anchor{2189}
@deffn {Option} LIBLZMA_LIBS

C compiler and linker flags for @code{liblzma}, used by @ref{8e,,lzma} module,
overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; LIBREADLINE_CFLAGS
@anchor{using/configure cmdoption-arg-LIBREADLINE_CFLAGS}@anchor{218a}
@deffn {Option} LIBREADLINE_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBREADLINE_LIBS
@anchor{using/configure cmdoption-arg-LIBREADLINE_LIBS}@anchor{218b}
@deffn {Option} LIBREADLINE_LIBS

C compiler and linker flags for @code{libreadline}, used by @ref{bf,,readline}
module, overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; LIBSQLITE3_CFLAGS
@anchor{using/configure cmdoption-arg-LIBSQLITE3_CFLAGS}@anchor{218c}
@deffn {Option} LIBSQLITE3_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBSQLITE3_LIBS
@anchor{using/configure cmdoption-arg-LIBSQLITE3_LIBS}@anchor{218d}
@deffn {Option} LIBSQLITE3_LIBS

C compiler and linker flags for @code{libsqlite3}, used by @ref{d4,,sqlite3}
module, overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; LIBUUID_CFLAGS
@anchor{using/configure cmdoption-arg-LIBUUID_CFLAGS}@anchor{218e}
@deffn {Option} LIBUUID_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBUUID_LIBS
@anchor{using/configure cmdoption-arg-LIBUUID_LIBS}@anchor{218f}
@deffn {Option} LIBUUID_LIBS

C compiler and linker flags for @code{libuuid}, used by @ref{116,,uuid} module,
overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; LIBZSTD_CFLAGS
@anchor{using/configure cmdoption-arg-LIBZSTD_CFLAGS}@anchor{2190}
@deffn {Option} LIBZSTD_CFLAGS
@end deffn

@geindex コマンドラインオプション; LIBZSTD_LIBS
@anchor{using/configure cmdoption-arg-LIBZSTD_LIBS}@anchor{2191}
@deffn {Option} LIBZSTD_LIBS

C compiler and linker flags for @code{libzstd}, used by @ref{23,,compression.zstd} module,
overriding @code{pkg-config}.


Added in version 3.14.

@end deffn

@geindex コマンドラインオプション; PANEL_CFLAGS
@anchor{using/configure cmdoption-arg-PANEL_CFLAGS}@anchor{2192}
@deffn {Option} PANEL_CFLAGS
@end deffn

@geindex コマンドラインオプション; PANEL_LIBS
@anchor{using/configure cmdoption-arg-PANEL_LIBS}@anchor{2193}
@deffn {Option} PANEL_LIBS

C compiler and linker flags for PANEL, overriding @code{pkg-config}.

C compiler and linker flags for @code{libpanel} or @code{libpanelw}, used by
@ref{31,,curses.panel} module, overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; TCLTK_CFLAGS
@anchor{using/configure cmdoption-arg-TCLTK_CFLAGS}@anchor{2194}
@deffn {Option} TCLTK_CFLAGS
@end deffn

@geindex コマンドラインオプション; TCLTK_LIBS
@anchor{using/configure cmdoption-arg-TCLTK_LIBS}@anchor{2195}
@deffn {Option} TCLTK_LIBS

C compiler and linker flags for TCLTK, overriding @code{pkg-config}.
@end deffn

@geindex コマンドラインオプション; ZLIB_CFLAGS
@anchor{using/configure cmdoption-arg-ZLIB_CFLAGS}@anchor{2196}
@deffn {Option} ZLIB_CFLAGS
@end deffn

@geindex コマンドラインオプション; ZLIB_LIBS
@anchor{using/configure cmdoption-arg-ZLIB_LIBS}@anchor{2197}
@deffn {Option} ZLIB_LIBS

C compiler and linker flags for @code{libzlib}, used by @ref{6b,,gzip} module,
overriding @code{pkg-config}.
@end deffn

@node WebAssembly オプション,インストールオプション,サードパーティ依存関係のオプション,Configureオプション
@anchor{using/configure webassembly-options}@anchor{2198}
@subsubsection WebAssembly オプション


@geindex コマンドラインオプション; --enable-wasm-dynamic-linking
@anchor{using/configure cmdoption-enable-wasm-dynamic-linking}@anchor{1bbe}
@deffn {Option} @w{-}@w{-}enable@w{-}wasm@w{-}dynamic@w{-}linking

WASM のダイナミックリンクサポートをオンにします。

ダイナミックリンクにより @code{dlopen} が可能になります。デッドコードの排除や機能追加に制限があるため、実行ファイルのファイルサイズが大きくなります。


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; --enable-wasm-pthreads
@anchor{using/configure cmdoption-enable-wasm-pthreads}@anchor{1b8d}
@deffn {Option} @w{-}@w{-}enable@w{-}wasm@w{-}pthreads

WASM の pthreads サポートをオンにします。


Added in version 3.11.

@end deffn

@node インストールオプション,パフォーマンスに関するオプション,WebAssembly オプション,Configureオプション
@anchor{using/configure install-options}@anchor{2199}
@subsubsection インストールオプション


@geindex コマンドラインオプション; --prefix
@anchor{using/configure cmdoption-prefix}@anchor{214f}
@deffn {Option} @w{-}@w{-}prefix=PREFIX

アーキテクチャに依存しないファイルを PREFIX にインストールします。Unix の場合、デフォルトは @code{/usr/local} です。

この値は、実行時に @ref{3e7,,sys.prefix} を使って取得することができます。

例として、 @code{--prefix="$HOME/.local/"} を使用すると、 Python をそのホームディレクトリにインストールすることができます。
@end deffn

@geindex コマンドラインオプション; --exec-prefix
@anchor{using/configure cmdoption-exec-prefix}@anchor{2150}
@deffn {Option} @w{-}@w{-}exec@w{-}prefix=EPREFIX

アーキテクチャ依存のファイルを EPREFIX にインストールします。デフォルトは @ref{214f,,--prefix} です。

この値は、実行時に @ref{3eb,,sys.exec_prefix} を使って取得することができます。
@end deffn

@geindex コマンドラインオプション; --disable-test-modules
@anchor{using/configure cmdoption-disable-test-modules}@anchor{a8c}
@deffn {Option} @w{-}@w{-}disable@w{-}test@w{-}modules

@ref{e8,,test} パッケージや @code{_testcapi} 拡張モジュール(デフォルトでビルド、インストールされます)のようなテストモジュールをビルド、インストールしないようにします。


Added in version 3.10.

@end deffn

@geindex コマンドラインオプション; --with-ensurepip
@anchor{using/configure cmdoption-with-ensurepip}@anchor{219a}
@deffn {Option} @w{-}@w{-}with@w{-}ensurepip=[upgrade|install|no]

Python のインストール時に実行される @ref{59,,ensurepip} コマンドを選択します:


@itemize *

@item 
@code{upgrade} (デフォルト): @code{python -m ensurepip --altinstall --upgrade} コマンドを実行します。

@item 
@code{install}: @code{python -m ensurepip --altinstall} コマンドを実行します。

@item 
@code{no}: ensurepip を実行しない;
@end itemize


Added in version 3.6.

@end deffn

@node パフォーマンスに関するオプション,Python デバッグビルド,インストールオプション,Configureオプション
@anchor{using/configure performance-options}@anchor{219b}
@subsubsection パフォーマンスに関するオプション


Configuring Python using @code{--enable-optimizations --with-lto} (PGO + LTO) is
recommended for best performance. The experimental @code{--enable-bolt} flag can
also be used to improve performance.

@geindex コマンドラインオプション; --enable-optimizations
@anchor{using/configure cmdoption-enable-optimizations}@anchor{a62}
@deffn {Option} @w{-}@w{-}enable@w{-}optimizations

@geindex PROFILE_TASK
@geindex 環境変数; PROFILE_TASK
@ref{1a7e,,PROFILE_TASK} を使用して Profile Guided Optimization (PGO) を有効にします(デフォルトでは無効です)。

Cコンパイラの Clang では、 PGO のために @code{llvm-profdata} プログラムが必要です。macOS では、 GCC もこれを必要とします: GCC は macOS の Clang のエイリアスにすぎません。

Disable also semantic interposition in libpython if @code{--enable-shared} and
GCC is used: add @code{-fno-semantic-interposition} to the compiler and linker
flags.

@cartouche
@quotation 注釈 
During the build, you may encounter compiler warnings about
profile data not being available for some source files.
These warnings are harmless, as only a subset of the code is exercised
during profile data acquisition.
To disable these warnings on Clang, manually suppress them by adding
@code{-Wno-profile-instr-unprofiled} to 
@geindex CFLAGS
@geindex 環境変数; CFLAGS
@ref{16d0,,CFLAGS}.
@end quotation
@end cartouche


Added in version 3.6.



バージョン 3.10 で変更: GCC で @code{-fno-semantic-interposition} を使用する。

@end deffn

@geindex 環境変数; PROFILE_TASK
@anchor{using/configure envvar-PROFILE_TASK}@anchor{1a7e}
@deffn {環境変数} PROFILE_TASK

Environment variable used in the Makefile: Python command line arguments for
the PGO generation task.

デフォルト: @code{-m test --pgo --timeout=$(TESTTIMEOUT)}


Added in version 3.8.



バージョン 3.13 で変更: Task failure is no longer ignored silently.

@end deffn

@geindex コマンドラインオプション; --with-lto
@anchor{using/configure cmdoption-with-lto}@anchor{952}
@deffn {Option} @w{-}@w{-}with@w{-}lto=[full|thin|no|yes]

Enable Link Time Optimization (LTO) in any build (disabled by default).

The C compiler Clang requires @code{llvm-ar} for LTO (@code{ar} on macOS), as well
as an LTO-aware linker (@code{ld.gold} or @code{lld}).


Added in version 3.6.



Added in version 3.11: To use ThinLTO feature, use @code{--with-lto=thin} on Clang.



バージョン 3.12 で変更: Use ThinLTO as the default optimization policy on Clang if the compiler accepts the flag.

@end deffn

@geindex コマンドラインオプション; --enable-bolt
@anchor{using/configure cmdoption-enable-bolt}@anchor{219c}
@deffn {Option} @w{-}@w{-}enable@w{-}bolt

Enable usage of the BOLT post-link binary optimizer@footnote{https://github.com/llvm/llvm-project/tree/main/bolt} (disabled by
default).

BOLT is part of the LLVM project but is not always included in their binary
distributions. This flag requires that @code{llvm-bolt} and @code{merge-fdata}
are available.

BOLT is still a fairly new project so this flag should be considered
experimental for now. Because this tool operates on machine code its success
is dependent on a combination of the build environment + the other
optimization configure args + the CPU architecture, and not all combinations
are supported.
BOLT versions before LLVM 16 are known to crash BOLT under some scenarios.
Use of LLVM 16 or newer for BOLT optimization is strongly encouraged.

The @code{BOLT_INSTRUMENT_FLAGS} and @code{BOLT_APPLY_FLAGS}
@code{configure} variables can be defined to override the default set of
arguments for @code{llvm-bolt} to instrument and apply BOLT data to
binaries, respectively.


Added in version 3.12.

@end deffn

@geindex コマンドラインオプション; BOLT_APPLY_FLAGS
@anchor{using/configure cmdoption-arg-BOLT_APPLY_FLAGS}@anchor{219d}
@deffn {Option} BOLT_APPLY_FLAGS

Arguments to @code{llvm-bolt} when creating a BOLT optimized binary@footnote{https://github.com/facebookarchive/BOLT}.


Added in version 3.12.

@end deffn

@geindex コマンドラインオプション; BOLT_INSTRUMENT_FLAGS
@anchor{using/configure cmdoption-arg-BOLT_INSTRUMENT_FLAGS}@anchor{219e}
@deffn {Option} BOLT_INSTRUMENT_FLAGS

Arguments to @code{llvm-bolt} when instrumenting binaries.


Added in version 3.12.

@end deffn

@geindex コマンドラインオプション; --with-computed-gotos
@anchor{using/configure cmdoption-with-computed-gotos}@anchor{219f}
@deffn {Option} @w{-}@w{-}with@w{-}computed@w{-}gotos

Enable computed gotos in evaluation loop (enabled by default on supported
compilers).
@end deffn

@geindex コマンドラインオプション; --with-tail-call-interp
@anchor{using/configure cmdoption-with-tail-call-interp}@anchor{172}
@deffn {Option} @w{-}@w{-}with@w{-}tail@w{-}call@w{-}interp

Enable interpreters using tail calls in CPython. If enabled, enabling PGO
(@ref{a62,,--enable-optimizations}) is highly recommended. This option specifically
requires a C compiler with proper tail call support, and the
preserve_none@footnote{https://clang.llvm.org/docs/AttributeReference.html#preserve-none}
calling convention. For example, Clang 19 and newer supports this feature.


Added in version 3.14.

@end deffn

@geindex コマンドラインオプション; --without-mimalloc
@anchor{using/configure cmdoption-without-mimalloc}@anchor{21a0}
@deffn {Option} @w{-}@w{-}without@w{-}mimalloc

Disable the fast @ref{213d,,mimalloc} allocator
(enabled by default).

See also 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable.
@end deffn

@geindex コマンドラインオプション; --without-pymalloc
@anchor{using/configure cmdoption-without-pymalloc}@anchor{21a1}
@deffn {Option} @w{-}@w{-}without@w{-}pymalloc

Disable the specialized Python memory allocator @ref{f0b,,pymalloc}
(enabled by default).

See also 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable.
@end deffn

@geindex コマンドラインオプション; --without-doc-strings
@anchor{using/configure cmdoption-without-doc-strings}@anchor{21a2}
@deffn {Option} @w{-}@w{-}without@w{-}doc@w{-}strings

Disable static documentation strings to reduce the memory footprint (enabled
by default). Documentation strings defined in Python are not affected.

Don't define the @code{WITH_DOC_STRINGS} macro.

See the @code{PyDoc_STRVAR()} macro.
@end deffn

@geindex コマンドラインオプション; --enable-profiling
@anchor{using/configure cmdoption-enable-profiling}@anchor{21a3}
@deffn {Option} @w{-}@w{-}enable@w{-}profiling

Enable C-level code profiling with @code{gprof} (disabled by default).
@end deffn

@geindex コマンドラインオプション; --with-strict-overflow
@anchor{using/configure cmdoption-with-strict-overflow}@anchor{1ad3}
@deffn {Option} @w{-}@w{-}with@w{-}strict@w{-}overflow

Add @code{-fstrict-overflow} to the C compiler flags (by default we add
@code{-fno-strict-overflow} instead).
@end deffn

@geindex コマンドラインオプション; --without-remote-debug
@anchor{using/configure cmdoption-without-remote-debug}@anchor{170}
@deffn {Option} @w{-}@w{-}without@w{-}remote@w{-}debug

Deactivate remote debugging support described in 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/} (enabled by default).
When this flag is provided the code that allows the interpreter to schedule the
execution of a Python file in a separate process as described in 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/} is
not compiled. This includes both the functionality to schedule code to be executed
and the functionality to receive code to be executed.

@geindex Py_REMOTE_DEBUG (C macro)
@anchor{using/configure c Py_REMOTE_DEBUG}@anchor{21a4}
@deffn {C のマクロ} Py_REMOTE_DEBUG

This macro is defined by default, unless Python is configured with
@ref{170,,--without-remote-debug}.

Note that even if the macro is defined, remote debugging may not be
available (for example, on an incompatible platform).
@end deffn


Added in version 3.14.

@end deffn

@node Python デバッグビルド,Debug options,パフォーマンスに関するオプション,Configureオプション
@anchor{using/configure debug-build}@anchor{509}@anchor{using/configure python-debug-build}@anchor{21a5}
@subsubsection Python デバッグビルド


デバッグビルドは、 @ref{666,,--with-pydebug} 構成オプション付きでビルドされた Python です。

デバッグビルドの影響:


@itemize *

@item 
Display all warnings by default: the list of default warning filters is empty
in the @ref{118,,warnings} module.

@item 
Add @code{d} to @ref{c59,,sys.abiflags}.

@item 
Add @code{sys.gettotalrefcount()} function.

@item 
Add @ref{16f,,-X showrefcount} command line option.

@item 
Add @ref{2123,,-d} command line option and 
@geindex PYTHONDEBUG
@geindex 環境変数; PYTHONDEBUG
@ref{2124,,PYTHONDEBUG} environment
variable to debug the parser.

@item 
Add support for the @code{__lltrace__} variable: enable low-level tracing in the
bytecode evaluation loop if the variable is defined.

@item 
Install @ref{213b,,debug hooks on memory allocators}
to detect buffer overflow and other memory errors.

@item 
Define @code{Py_DEBUG} and @code{Py_REF_DEBUG} macros.

@item 
Add runtime checks: code surrounded by @code{#ifdef Py_DEBUG} and @code{#endif}.
Enable @code{assert(...)} and @code{_PyObject_ASSERT(...)} assertions: don't set
the @code{NDEBUG} macro (see also the @ref{62d,,--with-assertions} configure
option). Main runtime checks:


@itemize *

@item 
Add sanity checks on the function arguments.

@item 
Unicode and int objects are created with their memory filled with a pattern
to detect usage of uninitialized objects.

@item 
Ensure that functions which can clear or replace the current exception are
not called with an exception raised.

@item 
Check that deallocator functions don't change the current exception.

@item 
The garbage collector (@ref{1b3,,gc.collect()} function) runs some basic checks
on objects consistency.

@item 
The @code{Py_SAFE_DOWNCAST()} macro checks for integer underflow and
overflow when downcasting from wide types to narrow types.
@end itemize
@end itemize

See also the @ref{508,,Python Development Mode} and the
@ref{636,,--with-trace-refs} configure option.


バージョン 3.8 で変更: Release builds and debug builds are now ABI compatible: defining the
@code{Py_DEBUG} macro no longer implies the @code{Py_TRACE_REFS} macro (see the
@ref{636,,--with-trace-refs} option).


@node Debug options,リンカのオプション<2>,Python デバッグビルド,Configureオプション
@anchor{using/configure debug-options}@anchor{21a6}
@subsubsection Debug options


@geindex コマンドラインオプション; --with-pydebug
@anchor{using/configure cmdoption-with-pydebug}@anchor{666}
@deffn {Option} @w{-}@w{-}with@w{-}pydebug

@ref{509,,Build Python in debug mode}: define the @code{Py_DEBUG}
macro (disabled by default).
@end deffn

@geindex コマンドラインオプション; --with-trace-refs
@anchor{using/configure cmdoption-with-trace-refs}@anchor{636}
@deffn {Option} @w{-}@w{-}with@w{-}trace@w{-}refs

Enable tracing references for debugging purpose (disabled by default).

Effects:


@itemize *

@item 
Define the @code{Py_TRACE_REFS} macro.

@item 
Add @ref{28e,,sys.getobjects()} function.

@item 
Add 
@geindex PYTHONDUMPREFS
@geindex 環境変数; PYTHONDUMPREFS
@ref{b9e,,PYTHONDUMPREFS} environment variable.
@end itemize

The 
@geindex PYTHONDUMPREFS
@geindex 環境変数; PYTHONDUMPREFS
@ref{b9e,,PYTHONDUMPREFS} environment variable can be used to dump
objects and reference counts still alive at Python exit.

@ref{983,,Statically allocated objects} are not traced.


Added in version 3.8.



バージョン 3.13 で変更: This build is now ABI compatible with release build and @ref{509,,debug build}.

@end deffn

@geindex コマンドラインオプション; --with-assertions
@anchor{using/configure cmdoption-with-assertions}@anchor{62d}
@deffn {Option} @w{-}@w{-}with@w{-}assertions

Build with C assertions enabled (default is no): @code{assert(...);} and
@code{_PyObject_ASSERT(...);}.

If set, the @code{NDEBUG} macro is not defined in the 
@geindex OPT
@geindex 環境変数; OPT
@ref{21a7,,OPT} compiler
variable.

See also the @ref{666,,--with-pydebug} option (@ref{509,,debug build}) which also enables assertions.


Added in version 3.6.

@end deffn

@geindex コマンドラインオプション; --with-valgrind
@anchor{using/configure cmdoption-with-valgrind}@anchor{21a8}
@deffn {Option} @w{-}@w{-}with@w{-}valgrind

Enable Valgrind support (default is no).
@end deffn

@geindex コマンドラインオプション; --with-dtrace
@anchor{using/configure cmdoption-with-dtrace}@anchor{21a9}
@deffn {Option} @w{-}@w{-}with@w{-}dtrace

Enable DTrace support (default is no).

See @ref{e66,,Instrumenting CPython with DTrace and SystemTap}.


Added in version 3.6.

@end deffn

@geindex コマンドラインオプション; --with-address-sanitizer
@anchor{using/configure cmdoption-with-address-sanitizer}@anchor{21aa}
@deffn {Option} @w{-}@w{-}with@w{-}address@w{-}sanitizer

Enable AddressSanitizer memory error detector, @code{asan} (default is no).
To improve ASan detection capabilities you may also want to combine this
with @ref{21a1,,--without-pymalloc} to disable the specialized small-object
allocator whose allocations are not tracked by ASan.


Added in version 3.6.

@end deffn

@geindex コマンドラインオプション; --with-memory-sanitizer
@anchor{using/configure cmdoption-with-memory-sanitizer}@anchor{21ab}
@deffn {Option} @w{-}@w{-}with@w{-}memory@w{-}sanitizer

Enable MemorySanitizer allocation error detector, @code{msan} (default is no).


Added in version 3.6.

@end deffn

@geindex コマンドラインオプション; --with-undefined-behavior-sanitizer
@anchor{using/configure cmdoption-with-undefined-behavior-sanitizer}@anchor{21ac}
@deffn {Option} @w{-}@w{-}with@w{-}undefined@w{-}behavior@w{-}sanitizer

Enable UndefinedBehaviorSanitizer undefined behaviour detector, @code{ubsan}
(default is no).


Added in version 3.6.

@end deffn

@geindex コマンドラインオプション; --with-thread-sanitizer
@anchor{using/configure cmdoption-with-thread-sanitizer}@anchor{21ad}
@deffn {Option} @w{-}@w{-}with@w{-}thread@w{-}sanitizer

Enable ThreadSanitizer data race detector, @code{tsan}
(default is no).


Added in version 3.13.

@end deffn

@node リンカのオプション<2>,Libraries options,Debug options,Configureオプション
@anchor{using/configure id13}@anchor{21ae}
@subsubsection リンカのオプション


@geindex コマンドラインオプション; --enable-shared
@anchor{using/configure cmdoption-enable-shared}@anchor{a63}
@deffn {Option} @w{-}@w{-}enable@w{-}shared

Enable building a shared Python library: @code{libpython} (default is no).
@end deffn

@geindex コマンドラインオプション; --without-static-libpython
@anchor{using/configure cmdoption-without-static-libpython}@anchor{a8e}
@deffn {Option} @w{-}@w{-}without@w{-}static@w{-}libpython

Do not build @code{libpythonMAJOR.MINOR.a} and do not install @code{python.o}
(built and enabled by default).


Added in version 3.10.

@end deffn

@node Libraries options,Security Options,リンカのオプション<2>,Configureオプション
@anchor{using/configure libraries-options}@anchor{21af}
@subsubsection Libraries options


@geindex コマンドラインオプション; --with-libs
@anchor{using/configure cmdoption-with-libs}@anchor{21b0}
@deffn {Option} @w{-}@w{-}with@w{-}libs='lib1 ...'

Link against additional libraries (default is no).
@end deffn

@geindex コマンドラインオプション; --with-system-expat
@anchor{using/configure cmdoption-with-system-expat}@anchor{1b2d}
@deffn {Option} @w{-}@w{-}with@w{-}system@w{-}expat

Build the @code{pyexpat} module using an installed @code{expat} library
(default is no).
@end deffn

@geindex コマンドラインオプション; --with-system-libmpdec
@anchor{using/configure cmdoption-with-system-libmpdec}@anchor{657}
@deffn {Option} @w{-}@w{-}with@w{-}system@w{-}libmpdec

Build the @code{_decimal} extension module using an installed @code{mpdecimal}
library, see the @ref{3a,,decimal} module (default is yes).


Added in version 3.3.



バージョン 3.13 で変更: Default to using the installed @code{mpdecimal} library.



バージョン 3.15 で変更: A bundled copy of the library will no longer be selected
implicitly if an installed @code{mpdecimal} library is not found.
In Python 3.15 only, it can still be selected explicitly using
@code{--with-system-libmpdec=no} or @code{--without-system-libmpdec}.



Deprecated since version 3.13, will be removed in version 3.16: A copy of the @code{mpdecimal} library sources will no longer be distributed
with Python 3.16.



@subsubheading 参考


@ref{2186,,LIBMPDEC_CFLAGS} and @ref{2187,,LIBMPDEC_LIBS}.

@end deffn

@geindex コマンドラインオプション; --with-readline
@anchor{using/configure cmdoption-with-readline}@anchor{215b}
@deffn {Option} @w{-}@w{-}with@w{-}readline=readline|editline

Designate a backend library for the @ref{bf,,readline} module.


@itemize *

@item 
readline: Use readline as the backend.

@item 
editline: Use editline as the backend.
@end itemize


Added in version 3.10.

@end deffn

@geindex コマンドラインオプション; --without-readline
@anchor{using/configure cmdoption-without-readline}@anchor{21b1}
@deffn {Option} @w{-}@w{-}without@w{-}readline

Don't build the @ref{bf,,readline} module (built by default).

Don't define the @code{HAVE_LIBREADLINE} macro.


Added in version 3.10.

@end deffn

@geindex コマンドラインオプション; --with-libm
@anchor{using/configure cmdoption-with-libm}@anchor{21b2}
@deffn {Option} @w{-}@w{-}with@w{-}libm=STRING

Override @code{libm} math library to `STRING' (default is system-dependent).
@end deffn

@geindex コマンドラインオプション; --with-libc
@anchor{using/configure cmdoption-with-libc}@anchor{21b3}
@deffn {Option} @w{-}@w{-}with@w{-}libc=STRING

Override @code{libc} C library to `STRING' (default is system-dependent).
@end deffn

@geindex コマンドラインオプション; --with-openssl
@anchor{using/configure cmdoption-with-openssl}@anchor{21b4}
@deffn {Option} @w{-}@w{-}with@w{-}openssl=DIR

Root of the OpenSSL directory.


Added in version 3.7.

@end deffn

@geindex コマンドラインオプション; --with-openssl-rpath
@anchor{using/configure cmdoption-with-openssl-rpath}@anchor{a8f}
@deffn {Option} @w{-}@w{-}with@w{-}openssl@w{-}rpath=[no|auto|DIR]

Set runtime library directory (rpath) for OpenSSL libraries:


@itemize *

@item 
@code{no} (default): don't set rpath;

@item 
@code{auto}: auto-detect rpath from @ref{21b4,,--with-openssl} and
@code{pkg-config};

@item 
`DIR': set an explicit rpath.
@end itemize


Added in version 3.10.

@end deffn

@node Security Options,macOS のオプション,Libraries options,Configureオプション
@anchor{using/configure security-options}@anchor{21b5}
@subsubsection Security Options


@geindex コマンドラインオプション; --with-hash-algorithm
@anchor{using/configure cmdoption-with-hash-algorithm}@anchor{21b6}
@deffn {Option} @w{-}@w{-}with@w{-}hash@w{-}algorithm=[fnv|siphash13|siphash24]

Select hash algorithm for use in @code{Python/pyhash.c}:


@itemize *

@item 
@code{siphash13} (default);

@item 
@code{siphash24};

@item 
@code{fnv}.
@end itemize


Added in version 3.4.



Added in version 3.11: @code{siphash13} is added and it is the new default.

@end deffn

@geindex コマンドラインオプション; --with-builtin-hashlib-hashes
@anchor{using/configure cmdoption-with-builtin-hashlib-hashes}@anchor{215c}
@deffn {Option} @w{-}@w{-}with@w{-}builtin@w{-}hashlib@w{-}hashes=md5,sha1,sha256,sha512,sha3,blake2

Built-in hash modules:


@itemize *

@item 
@code{md5};

@item 
@code{sha1};

@item 
@code{sha256};

@item 
@code{sha512};

@item 
@code{sha3} (with shake);

@item 
@code{blake2}.
@end itemize


Added in version 3.9.

@end deffn

@geindex コマンドラインオプション; --with-ssl-default-suites
@anchor{using/configure cmdoption-with-ssl-default-suites}@anchor{21b7}
@deffn {Option} @w{-}@w{-}with@w{-}ssl@w{-}default@w{-}suites=[python|openssl|STRING]

Override the OpenSSL default cipher suites string:


@itemize *

@item 
@code{python} (default): use Python's preferred selection;

@item 
@code{openssl}: leave OpenSSL's defaults untouched;

@item 
`STRING': use a custom string
@end itemize

See the @ref{d5,,ssl} module.


Added in version 3.7.



バージョン 3.10 で変更: The settings @code{python} and `STRING' also set TLS 1.2 as minimum
protocol version.

@end deffn

@geindex コマンドラインオプション; --disable-safety
@anchor{using/configure cmdoption-disable-safety}@anchor{445}
@deffn {Option} @w{-}@w{-}disable@w{-}safety

Disable compiler options that are recommended by OpenSSF@footnote{https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.md} for security reasons with no performance overhead.
If this option is not enabled, CPython will be built based on safety compiler options with no slow down.
When this option is enabled, CPython will not be built with the compiler options listed below.

The following compiler options are disabled with @code{--disable-safety}:


@itemize *

@item 
-fstack-protector-strong@footnote{https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.md#enable-run-time-checks-for-stack-based-buffer-overflows}: Enable run-time checks for stack-based buffer overflows.

@item 
-Wtrampolines@footnote{https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.md#enable-warning-about-trampolines-that-require-executable-stacks}: Enable warnings about trampolines that require executable stacks.
@end itemize


Added in version 3.14.

@end deffn

@geindex コマンドラインオプション; --enable-slower-safety
@anchor{using/configure cmdoption-enable-slower-safety}@anchor{446}
@deffn {Option} @w{-}@w{-}enable@w{-}slower@w{-}safety

Enable compiler options that are recommended by OpenSSF@footnote{https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.md} for security reasons which require overhead.
If this option is not enabled, CPython will not be built based on safety compiler options which performance impact.
When this option is enabled, CPython will be built with the compiler options listed below.

The following compiler options are enabled with @code{--enable-slower-safety}:


@itemize *

@item 
-D_FORTIFY_SOURCE=3@footnote{https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.md#fortify-sources-for-unsafe-libc-usage-and-buffer-overflows}: Fortify sources with compile- and run-time checks for unsafe libc usage and buffer overflows.
@end itemize


Added in version 3.14.

@end deffn

@node macOS のオプション,iOS のオプション,Security Options,Configureオプション
@anchor{using/configure macos-options}@anchor{21b8}
@subsubsection macOS のオプション


Mac/README.rst@footnote{https://github.com/python/cpython/tree/3.14/Mac/README.rst} を参照。

@geindex コマンドラインオプション; --enable-universalsdk
@anchor{using/configure cmdoption-enable-universalsdk}@anchor{b63}
@deffn {Option} @w{-}@w{-}enable@w{-}universalsdk
@end deffn

@geindex コマンドラインオプション; --enable-universalsdk
@anchor{using/configure cmdoption-0}@anchor{21b9}
@deffn {Option} @w{-}@w{-}enable@w{-}universalsdk=SDKDIR

ユニバーサルバイナリビルドを作成します。 `SDKDIR' はビルドの実行にどの macOS SDK が使用されるべきかを指定します (デフォルトでは指定しません) 。
@end deffn

@geindex コマンドラインオプション; --enable-framework
@anchor{using/configure cmdoption-enable-framework}@anchor{21ba}
@deffn {Option} @w{-}@w{-}enable@w{-}framework
@end deffn

@geindex コマンドラインオプション; --enable-framework
@anchor{using/configure cmdoption-1}@anchor{21bb}
@deffn {Option} @w{-}@w{-}enable@w{-}framework=INSTALLDIR

従来の Unix インストールではなく、 Python.framework を作成します。オプションの `INSTALLDIR' はインストール先のパスを指定します (デフォルトでは指定しません) 。
@end deffn

@geindex コマンドラインオプション; --with-universal-archs
@anchor{using/configure cmdoption-with-universal-archs}@anchor{21bc}
@deffn {Option} @w{-}@w{-}with@w{-}universal@w{-}archs=ARCH

作成するユニバーサルバイナリの種類を指定します。このオプションは、 @ref{b63,,--enable-universalsdk} が指定された場合のみ有効です。

オプション:


@itemize *

@item 
@code{universal2} (x86-64 and arm64);

@item 
@code{32-bit} (PPC and i386);

@item 
@code{64-bit}  (PPC64 and x86-64);

@item 
@code{3-way} (i386, PPC and x86-64);

@item 
@code{intel} (i386 and x86-64);

@item 
@code{intel-32} (i386);

@item 
@code{intel-64} (x86-64);

@item 
@code{all}  (PPC, i386, PPC64 and x86-64).
@end itemize

Note that values for this configuration item are `not' the same as the
identifiers used for universal binary wheels on macOS. See the Python
Packaging User Guide for details on the packaging platform compatibility tags used on macOS@footnote{https://packaging.python.org/en/latest/specifications/platform-compatibility-tags/#macos}
@end deffn

@geindex コマンドラインオプション; --with-framework-name
@anchor{using/configure cmdoption-with-framework-name}@anchor{21bd}
@deffn {Option} @w{-}@w{-}with@w{-}framework@w{-}name=FRAMEWORK

macOS の Python フレームワークの名前を指定します。 @ref{21ba,,--enable-framework} が指定された場合のみ有効です (デフォルトでは @code{Python}) 。
@end deffn

@geindex コマンドラインオプション; --with-app-store-compliance
@anchor{using/configure cmdoption-with-app-store-compliance}@anchor{1997}
@deffn {Option} @w{-}@w{-}with@w{-}app@w{-}store@w{-}compliance
@end deffn

@geindex コマンドラインオプション; --with-app-store-compliance
@anchor{using/configure cmdoption-2}@anchor{21be}
@deffn {Option} @w{-}@w{-}with@w{-}app@w{-}store@w{-}compliance=PATCH@w{-}FILE

Python 標準ライブラリは、 macOS と iOS の App Store による配布用に送信された場合に、自動検査ツールのエラーを発生させることが知られている文字列を含んでいます。このオプションを有効にした場合、 App Store コンプライアンスに合わせて修正することが知られているパッチのリストを適用します。カスタムのパッチファイルを指定することもできます。このオプションはデフォルトでは無効になっています。


Added in version 3.13.

@end deffn

@node iOS のオプション,クロスコンパイルのオプション,macOS のオプション,Configureオプション
@anchor{using/configure ios-options}@anchor{21bf}
@subsubsection iOS のオプション


iOS/README.rst@footnote{https://github.com/python/cpython/tree/3.14/iOS/README.rst} を参照。

@geindex コマンドラインオプション; --enable-framework
@anchor{using/configure cmdoption-3}@anchor{21c0}
@deffn {Option} @w{-}@w{-}enable@w{-}framework=INSTALLDIR

Python.framework を作成します。 macOS とは違い、インストールパスを指定する `INSTALLDIR' 引数は必須です。
@end deffn

@geindex コマンドラインオプション; --with-framework-name
@anchor{using/configure cmdoption-4}@anchor{21c1}
@deffn {Option} @w{-}@w{-}with@w{-}framework@w{-}name=FRAMEWORK

フレームワークの名前を指定します (デフォルト: @code{Python}) 。
@end deffn

@node クロスコンパイルのオプション,,iOS のオプション,Configureオプション
@anchor{using/configure cross-compiling-options}@anchor{21c2}
@subsubsection クロスコンパイルのオプション


クロスコンパイル、またはクロスビルドは、異なる CPU アーキテクチャやプラットフォーム用に Python をビルドするために使用できます。クロスコンパイルには、ビルドプラットフォーム用の Python インタープリターが必要です。ビルドする Python のバージョンは、クロスコンパイルされたホスト Python のバージョンと一致する必要があります。

@geindex コマンドラインオプション; --build
@anchor{using/configure cmdoption-build}@anchor{21c3}
@deffn {Option} @w{-}@w{-}build=BUILD

BUILD でビルドするための設定です。通常は、 @code{config.guess} により推測されます。
@end deffn

@geindex コマンドラインオプション; --host
@anchor{using/configure cmdoption-host}@anchor{21c4}
@deffn {Option} @w{-}@w{-}host=HOST

HOST (ターゲットプラットフォーム) で動作するプログラムをビルドするためのクロスコンパイル。
@end deffn

@geindex コマンドラインオプション; --with-build-python
@anchor{using/configure cmdoption-with-build-python}@anchor{21c5}
@deffn {Option} @w{-}@w{-}with@w{-}build@w{-}python=path/to/python

クロスコンパイル用のビルド @code{python} バイナリへのパス。


Added in version 3.11.

@end deffn

@geindex コマンドラインオプション; CONFIG_SITE
@anchor{using/configure cmdoption-arg-CONFIG_SITE}@anchor{21c6}
@deffn {Option} CONFIG_SITE=file

構成をオーバーライドするファイルを指す環境変数。

`config.site' ファイルの例:

@example
# config.site-aarch64
ac_cv_buggy_getaddrinfo=no
ac_cv_file__dev_ptmx=yes
ac_cv_file__dev_ptc=no
@end example
@end deffn

@geindex コマンドラインオプション; HOSTRUNNER
@anchor{using/configure cmdoption-arg-HOSTRUNNER}@anchor{21c7}
@deffn {Option} HOSTRUNNER

クロスコンパイル用にホストプラットフォームの CPython を実行するプログラム。


Added in version 3.11.

@end deffn

クロスコンパイルの例:

@example
CONFIG_SITE=config.site-aarch64 ../configure \
    --build=x86_64-pc-linux-gnu \
    --host=aarch64-unknown-linux-gnu \
    --with-build-python=../x86_64/python
@end example

@node Python ビルドシステム,Compiler and linker flags,Configureオプション,Python を構成する
@anchor{using/configure python-build-system}@anchor{21c8}
@subsection Python ビルドシステム


@menu
* ビルドシステムの主要なファイル:: 
* 主要なビルドステップ:: 
* Main Makefile targets:: 
* C extensions:: 

@end menu

@node ビルドシステムの主要なファイル,主要なビルドステップ,,Python ビルドシステム
@anchor{using/configure main-files-of-the-build-system}@anchor{21c9}
@subsubsection ビルドシステムの主要なファイル



@itemize *

@item 
@code{configure.ac} => @code{configure};

@item 
@code{Makefile.pre.in} => @code{Makefile} (@code{configure} により作成されます);

@item 
@code{pyconfig.h} (@code{configure} により作成されます);

@item 
@code{Modules/Setup}: @code{Module/makesetup} シェルスクリプトを使用して Makefile がビルドする C 拡張。
@end itemize

@node 主要なビルドステップ,Main Makefile targets,ビルドシステムの主要なファイル,Python ビルドシステム
@anchor{using/configure main-build-steps}@anchor{21ca}
@subsubsection 主要なビルドステップ



@itemize *

@item 
C files (@code{.c}) are built as object files (@code{.o}).

@item 
A static @code{libpython} library (@code{.a}) is created from objects files.

@item 
@code{python.o} and the static @code{libpython} library are linked into the
final @code{python} program.

@item 
C extensions are built by the Makefile (see @code{Modules/Setup}).
@end itemize

@node Main Makefile targets,C extensions,主要なビルドステップ,Python ビルドシステム
@anchor{using/configure main-makefile-targets}@anchor{21cb}
@subsubsection Main Makefile targets


@menu
* make:: 
* make platform:: 
* make profile-opt:: 
* make clean:: 
* make distclean:: 
* make install:: 
* make test:: 
* make ci:: 
* make buildbottest:: 
* make regen-all:: 

@end menu

@node make,make platform,,Main Makefile targets
@anchor{using/configure make}@anchor{21cc}
@subsubsection make


For the most part, when rebuilding after editing some code or
refreshing your checkout from upstream, all you need to do is execute
@code{make}, which (per Make's semantics) builds the default target, the
first one defined in the Makefile.  By tradition (including in the
CPython project) this is usually the @code{all} target. The
@code{configure} script expands an @code{autoconf} variable,
@code{@@DEF_MAKE_ALL_RULE@@} to describe precisely which targets @code{make
all} will build. The three choices are:


@itemize *

@item 
@code{profile-opt} (configured with @code{--enable-optimizations})

@item 
@code{build_wasm} (chosen if the host platform matches @code{wasm32-wasi*} or
@code{wasm32-emscripten})

@item 
@code{build_all} (configured without explicitly using either of the others)
@end itemize

Depending on the most recent source file changes, Make will rebuild
any targets (object files and executables) deemed out-of-date,
including running @code{configure} again if necessary. Source/target
dependencies are many and maintained manually however, so Make
sometimes doesn't have all the information necessary to correctly
detect all targets which need to be rebuilt.  Depending on which
targets aren't rebuilt, you might experience a number of problems. If
you have build or test problems which you can't otherwise explain,
@code{make clean && make} should work around most dependency problems, at
the expense of longer build times.

@node make platform,make profile-opt,make,Main Makefile targets
@anchor{using/configure make-platform}@anchor{21cd}
@subsubsection make platform


Build the @code{python} program, but don't build the standard library
extension modules. This generates a file named @code{platform} which
contains a single line describing the details of the build platform,
e.g., @code{macosx-14.3-arm64-3.12} or @code{linux-x86_64-3.13}.

@node make profile-opt,make clean,make platform,Main Makefile targets
@anchor{using/configure make-profile-opt}@anchor{21ce}
@subsubsection make profile-opt


Build Python using profile-guided optimization (PGO).  You can use the
configure @ref{a62,,--enable-optimizations} option to make this the
default target of the @code{make} command (@code{make all} or just
@code{make}).

@node make clean,make distclean,make profile-opt,Main Makefile targets
@anchor{using/configure make-clean}@anchor{21cf}
@subsubsection make clean


Remove built files.

@node make distclean,make install,make clean,Main Makefile targets
@anchor{using/configure make-distclean}@anchor{21d0}
@subsubsection make distclean


In addition to the work done by @code{make clean}, remove files
created by the configure script.  @code{configure} will have to be run
before building again. @footnote{
@code{git clean -fdx} is an even more extreme way to "clean" your
checkout. It removes all files not known to Git.
When bug hunting using @code{git bisect}, this is
@uref{https://github.com/python/cpython/issues/114505#issuecomment-1907021718,recommended between probes}
to guarantee a completely clean build. `Use with care', as it
will delete all files not checked into Git, including your
new, uncommitted work.
}

@node make install,make test,make distclean,Main Makefile targets
@anchor{using/configure make-install}@anchor{21d1}
@subsubsection make install


Build the @code{all} target and install Python.

@node make test,make ci,make install,Main Makefile targets
@anchor{using/configure make-test}@anchor{21d2}
@subsubsection make test


Build the @code{all} target and run the Python test suite with the
@code{--fast-ci} option without GUI tests. Variables:


@itemize *

@item 
@code{TESTOPTS}: additional regrtest command-line options.

@item 
@code{TESTPYTHONOPTS}: additional Python command-line options.

@item 
@code{TESTTIMEOUT}: timeout in seconds (default: 10 minutes).
@end itemize

@node make ci,make buildbottest,make test,Main Makefile targets
@anchor{using/configure make-ci}@anchor{21d3}
@subsubsection make ci


This is similar to @code{make test}, but uses the @code{-ugui} to also run GUI tests.


Added in version 3.14.


@node make buildbottest,make regen-all,make ci,Main Makefile targets
@anchor{using/configure make-buildbottest}@anchor{21d4}
@subsubsection make buildbottest


This is similar to @code{make test}, but uses the @code{--slow-ci}
option and default timeout of 20 minutes, instead of @code{--fast-ci} option.

@node make regen-all,,make buildbottest,Main Makefile targets
@anchor{using/configure make-regen-all}@anchor{21d5}
@subsubsection make regen-all


Regenerate (almost) all generated files. These include (but are not
limited to) bytecode cases, and parser generator file.
@code{make regen-stdlib-module-names} and @code{autoconf} must be run
separately for the remaining @ref{215e,,generated files}.

@node C extensions,,Main Makefile targets,Python ビルドシステム
@anchor{using/configure c-extensions}@anchor{21d6}
@subsubsection C extensions


Some C extensions are built as built-in modules, like the @code{sys} module.
They are built with the @code{Py_BUILD_CORE_BUILTIN} macro defined.
Built-in modules have no @code{__file__} attribute:

@example
>>> import sys
>>> sys
<module 'sys' (built-in)>
>>> sys.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'sys' has no attribute '__file__'
@end example

Other C extensions are built as dynamic libraries, like the @code{_asyncio} module.
They are built with the @code{Py_BUILD_CORE_MODULE} macro defined.
Example on Linux x86-64:

@example
>>> import _asyncio
>>> _asyncio
<module '_asyncio' from '/usr/lib64/python3.9/lib-dynload/_asyncio.cpython-39-x86_64-linux-gnu.so'>
>>> _asyncio.__file__
'/usr/lib64/python3.9/lib-dynload/_asyncio.cpython-39-x86_64-linux-gnu.so'
@end example

@code{Modules/Setup} is used to generate Makefile targets to build C extensions.
At the beginning of the files, C extensions are built as built-in modules.
Extensions defined after the @code{*shared*} marker are built as dynamic libraries.

The @code{PyAPI_FUNC()}, @code{PyAPI_DATA()} and
@ref{16ec,,PyMODINIT_FUNC} macros of @code{Include/exports.h} are defined
differently depending if the @code{Py_BUILD_CORE_MODULE} macro is defined:


@itemize *

@item 
Use @code{Py_EXPORTED_SYMBOL} if the @code{Py_BUILD_CORE_MODULE} is defined

@item 
Use @code{Py_IMPORTED_SYMBOL} otherwise.
@end itemize

If the @code{Py_BUILD_CORE_BUILTIN} macro is used by mistake on a C extension
built as a shared library, its @code{PyInit_@var{xxx}()} function is not exported,
causing an @ref{65b,,ImportError} on import.

@node Compiler and linker flags,,Python ビルドシステム,Python を構成する
@anchor{using/configure compiler-and-linker-flags}@anchor{21d7}
@subsection Compiler and linker flags


Options set by the @code{./configure} script and environment variables and used by
@code{Makefile}.

@menu
* Preprocessor flags:: 
* Compiler flags:: 
* Linker flags:: 

@end menu

@node Preprocessor flags,Compiler flags,,Compiler and linker flags
@anchor{using/configure preprocessor-flags}@anchor{21d8}
@subsubsection Preprocessor flags


@geindex 環境変数; CONFIGURE_CPPFLAGS
@anchor{using/configure envvar-CONFIGURE_CPPFLAGS}@anchor{21d9}
@deffn {環境変数} CONFIGURE_CPPFLAGS

Value of 
@geindex CPPFLAGS
@geindex 環境変数; CPPFLAGS
@ref{16d2,,CPPFLAGS} variable passed to the @code{./configure} script.


Added in version 3.6.

@end deffn

@geindex 環境変数; CPPFLAGS
@anchor{using/configure envvar-CPPFLAGS}@anchor{16d2}
@deffn {環境変数} CPPFLAGS

(Objective) C/C++ preprocessor flags, e.g. @code{-I@var{include_dir}} if you have
headers in a nonstandard directory `include_dir'.

Both 
@geindex CPPFLAGS
@geindex 環境変数; CPPFLAGS
@ref{16d2,,CPPFLAGS} and 
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS} need to contain the shell's
value to be able to build extension modules using the
directories specified in the environment variables.
@end deffn

@geindex 環境変数; BASECPPFLAGS
@anchor{using/configure envvar-BASECPPFLAGS}@anchor{21da}
@deffn {環境変数} BASECPPFLAGS


Added in version 3.4.

@end deffn

@geindex 環境変数; PY_CPPFLAGS
@anchor{using/configure envvar-PY_CPPFLAGS}@anchor{21db}
@deffn {環境変数} PY_CPPFLAGS

Extra preprocessor flags added for building the interpreter object files.

Default: @code{$(BASECPPFLAGS) -I. -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS)}.


Added in version 3.2.

@end deffn

@node Compiler flags,Linker flags,Preprocessor flags,Compiler and linker flags
@anchor{using/configure compiler-flags}@anchor{21dc}
@subsubsection Compiler flags


@geindex 環境変数; CC
@anchor{using/configure envvar-CC}@anchor{16cf}
@deffn {環境変数} CC

C コンパイラのコマンド。

Example: @code{gcc -pthread}.
@end deffn

@geindex 環境変数; CXX
@anchor{using/configure envvar-CXX}@anchor{21dd}
@deffn {環境変数} CXX

C++ compiler command.

Example: @code{g++ -pthread}.
@end deffn

@geindex 環境変数; CFLAGS
@anchor{using/configure envvar-CFLAGS}@anchor{16d0}
@deffn {環境変数} CFLAGS

C コンパイラのフラグ。
@end deffn

@geindex 環境変数; CFLAGS_NODIST
@anchor{using/configure envvar-CFLAGS_NODIST}@anchor{21de}
@deffn {環境変数} CFLAGS_NODIST

@geindex CFLAGS_NODIST
@geindex 環境変数; CFLAGS_NODIST
@ref{21de,,CFLAGS_NODIST} is used for building the interpreter and stdlib C
extensions.  Use it when a compiler flag should `not' be part of
@geindex CFLAGS
@geindex 環境変数; CFLAGS
@ref{16d0,,CFLAGS} once Python is installed (gh-65320@footnote{https://github.com/python/cpython/issues/65320}).

In particular, 
@geindex CFLAGS
@geindex 環境変数; CFLAGS
@ref{16d0,,CFLAGS} should not contain:


@itemize *

@item 
the compiler flag @code{-I} (for setting the search path for include files).
The @code{-I} flags are processed from left to right, and any flags in
@geindex CFLAGS
@geindex 環境変数; CFLAGS
@ref{16d0,,CFLAGS} would take precedence over user- and package-supplied @code{-I}
flags.

@item 
hardening flags such as @code{-Werror} because distributions cannot control
whether packages installed by users conform to such heightened
standards.
@end itemize


Added in version 3.5.

@end deffn

@geindex 環境変数; COMPILEALL_OPTS
@anchor{using/configure envvar-COMPILEALL_OPTS}@anchor{21df}
@deffn {環境変数} COMPILEALL_OPTS

Options passed to the @ref{21,,compileall} command line when building PYC files
in @code{make install}. Default: @code{-j0}.


Added in version 3.12.

@end deffn

@geindex 環境変数; EXTRA_CFLAGS
@anchor{using/configure envvar-EXTRA_CFLAGS}@anchor{21e0}
@deffn {環境変数} EXTRA_CFLAGS

Extra C compiler flags.
@end deffn

@geindex 環境変数; CONFIGURE_CFLAGS
@anchor{using/configure envvar-CONFIGURE_CFLAGS}@anchor{21e1}
@deffn {環境変数} CONFIGURE_CFLAGS

Value of 
@geindex CFLAGS
@geindex 環境変数; CFLAGS
@ref{16d0,,CFLAGS} variable passed to the @code{./configure}
script.


Added in version 3.2.

@end deffn

@geindex 環境変数; CONFIGURE_CFLAGS_NODIST
@anchor{using/configure envvar-CONFIGURE_CFLAGS_NODIST}@anchor{21e2}
@deffn {環境変数} CONFIGURE_CFLAGS_NODIST

Value of 
@geindex CFLAGS_NODIST
@geindex 環境変数; CFLAGS_NODIST
@ref{21de,,CFLAGS_NODIST} variable passed to the @code{./configure}
script.


Added in version 3.5.

@end deffn

@geindex 環境変数; BASECFLAGS
@anchor{using/configure envvar-BASECFLAGS}@anchor{21e3}
@deffn {環境変数} BASECFLAGS

Base compiler flags.
@end deffn

@geindex 環境変数; OPT
@anchor{using/configure envvar-OPT}@anchor{21a7}
@deffn {環境変数} OPT

Optimization flags.
@end deffn

@geindex 環境変数; CFLAGS_ALIASING
@anchor{using/configure envvar-CFLAGS_ALIASING}@anchor{21e4}
@deffn {環境変数} CFLAGS_ALIASING

Strict or non-strict aliasing flags used to compile @code{Python/dtoa.c}.


Added in version 3.7.

@end deffn

@geindex 環境変数; CCSHARED
@anchor{using/configure envvar-CCSHARED}@anchor{21e5}
@deffn {環境変数} CCSHARED

Compiler flags used to build a shared library.

For example, @code{-fPIC} is used on Linux and on BSD.
@end deffn

@geindex 環境変数; CFLAGSFORSHARED
@anchor{using/configure envvar-CFLAGSFORSHARED}@anchor{21e6}
@deffn {環境変数} CFLAGSFORSHARED

Extra C flags added for building the interpreter object files.

Default: @code{$(CCSHARED)} when @ref{a63,,--enable-shared} is used, or an empty
string otherwise.
@end deffn

@geindex 環境変数; PY_CFLAGS
@anchor{using/configure envvar-PY_CFLAGS}@anchor{21e7}
@deffn {環境変数} PY_CFLAGS

Default: @code{$(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) $(EXTRA_CFLAGS)}.
@end deffn

@geindex 環境変数; PY_CFLAGS_NODIST
@anchor{using/configure envvar-PY_CFLAGS_NODIST}@anchor{21e8}
@deffn {環境変数} PY_CFLAGS_NODIST

Default: @code{$(CONFIGURE_CFLAGS_NODIST) $(CFLAGS_NODIST) -I$(srcdir)/Include/internal}.


Added in version 3.5.

@end deffn

@geindex 環境変数; PY_STDMODULE_CFLAGS
@anchor{using/configure envvar-PY_STDMODULE_CFLAGS}@anchor{21e9}
@deffn {環境変数} PY_STDMODULE_CFLAGS

C flags used for building the interpreter object files.

Default: @code{$(PY_CFLAGS) $(PY_CFLAGS_NODIST) $(PY_CPPFLAGS) $(CFLAGSFORSHARED)}.


Added in version 3.7.

@end deffn

@geindex 環境変数; PY_CORE_CFLAGS
@anchor{using/configure envvar-PY_CORE_CFLAGS}@anchor{21ea}
@deffn {環境変数} PY_CORE_CFLAGS

Default: @code{$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE}.


Added in version 3.2.

@end deffn

@geindex 環境変数; PY_BUILTIN_MODULE_CFLAGS
@anchor{using/configure envvar-PY_BUILTIN_MODULE_CFLAGS}@anchor{21eb}
@deffn {環境変数} PY_BUILTIN_MODULE_CFLAGS

Compiler flags to build a standard library extension module as a built-in
module, like the @ref{b2,,posix} module.

Default: @code{$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE_BUILTIN}.


Added in version 3.8.

@end deffn

@geindex 環境変数; PURIFY
@anchor{using/configure envvar-PURIFY}@anchor{21ec}
@deffn {環境変数} PURIFY

Purify command. Purify is a memory debugger program.

Default: empty string (not used).
@end deffn

@node Linker flags,,Compiler flags,Compiler and linker flags
@anchor{using/configure linker-flags}@anchor{21ed}
@subsubsection Linker flags


@geindex 環境変数; LINKCC
@anchor{using/configure envvar-LINKCC}@anchor{21ee}
@deffn {環境変数} LINKCC

Linker command used to build programs like @code{python} and @code{_testembed}.

Default: @code{$(PURIFY) $(CC)}.
@end deffn

@geindex 環境変数; CONFIGURE_LDFLAGS
@anchor{using/configure envvar-CONFIGURE_LDFLAGS}@anchor{21ef}
@deffn {環境変数} CONFIGURE_LDFLAGS

Value of 
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS} variable passed to the @code{./configure} script.

Avoid assigning 
@geindex CFLAGS
@geindex 環境変数; CFLAGS
@ref{16d0,,CFLAGS}, 
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS}, etc. so users can use
them on the command line to append to these values without stomping the
pre-set values.


Added in version 3.2.

@end deffn

@geindex 環境変数; LDFLAGS_NODIST
@anchor{using/configure envvar-LDFLAGS_NODIST}@anchor{21f0}
@deffn {環境変数} LDFLAGS_NODIST

@geindex LDFLAGS_NODIST
@geindex 環境変数; LDFLAGS_NODIST
@ref{21f0,,LDFLAGS_NODIST} is used in the same manner as
@geindex CFLAGS_NODIST
@geindex 環境変数; CFLAGS_NODIST
@ref{21de,,CFLAGS_NODIST}.  Use it when a linker flag should `not' be part of
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS} once Python is installed (gh-65320@footnote{https://github.com/python/cpython/issues/65320}).

In particular, 
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS} should not contain:


@itemize *

@item 
the compiler flag @code{-L} (for setting the search path for libraries).
The @code{-L} flags are processed from left to right, and any flags in
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS} would take precedence over user- and package-supplied @code{-L}
flags.
@end itemize
@end deffn

@geindex 環境変数; CONFIGURE_LDFLAGS_NODIST
@anchor{using/configure envvar-CONFIGURE_LDFLAGS_NODIST}@anchor{21f1}
@deffn {環境変数} CONFIGURE_LDFLAGS_NODIST

Value of 
@geindex LDFLAGS_NODIST
@geindex 環境変数; LDFLAGS_NODIST
@ref{21f0,,LDFLAGS_NODIST} variable passed to the @code{./configure}
script.


Added in version 3.8.

@end deffn

@geindex 環境変数; LDFLAGS
@anchor{using/configure envvar-LDFLAGS}@anchor{16d1}
@deffn {環境変数} LDFLAGS

Linker flags, e.g. @code{-L@var{lib_dir}} if you have libraries in a nonstandard
directory `lib_dir'.

Both 
@geindex CPPFLAGS
@geindex 環境変数; CPPFLAGS
@ref{16d2,,CPPFLAGS} and 
@geindex LDFLAGS
@geindex 環境変数; LDFLAGS
@ref{16d1,,LDFLAGS} need to contain the shell's
value to be able to build extension modules using the
directories specified in the environment variables.
@end deffn

@geindex 環境変数; LIBS
@anchor{using/configure envvar-LIBS}@anchor{21f2}
@deffn {環境変数} LIBS

Linker flags to pass libraries to the linker when linking the Python
executable.

Example: @code{-lrt}.
@end deffn

@geindex 環境変数; LDSHARED
@anchor{using/configure envvar-LDSHARED}@anchor{21f3}
@deffn {環境変数} LDSHARED

Command to build a shared library.

Default: @code{@@LDSHARED@@ $(PY_LDFLAGS)}.
@end deffn

@geindex 環境変数; BLDSHARED
@anchor{using/configure envvar-BLDSHARED}@anchor{21f4}
@deffn {環境変数} BLDSHARED

Command to build @code{libpython} shared library.

Default: @code{@@BLDSHARED@@ $(PY_CORE_LDFLAGS)}.
@end deffn

@geindex 環境変数; PY_LDFLAGS
@anchor{using/configure envvar-PY_LDFLAGS}@anchor{21f5}
@deffn {環境変数} PY_LDFLAGS

Default: @code{$(CONFIGURE_LDFLAGS) $(LDFLAGS)}.
@end deffn

@geindex 環境変数; PY_LDFLAGS_NODIST
@anchor{using/configure envvar-PY_LDFLAGS_NODIST}@anchor{21f6}
@deffn {環境変数} PY_LDFLAGS_NODIST

Default: @code{$(CONFIGURE_LDFLAGS_NODIST) $(LDFLAGS_NODIST)}.


Added in version 3.8.

@end deffn

@geindex 環境変数; PY_CORE_LDFLAGS
@anchor{using/configure envvar-PY_CORE_LDFLAGS}@anchor{21f7}
@deffn {環境変数} PY_CORE_LDFLAGS

Linker flags used for building the interpreter object files.


Added in version 3.8.

@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Windows で Python を使う,macOS で Python を使う,Python を構成する,Python のセットアップと利用
@anchor{using/windows doc}@anchor{21f8}@anchor{using/windows translation-repo}@anchor{21f9}@anchor{using/windows using-on-windows}@anchor{c9e}@anchor{using/windows using-python-on-windows}@anchor{21fa}
@section Windows で Python を使う


このドキュメントは、 Python を Microsoft Windows で使うときに知っておくべき、 Windows 固有の動作についての概要を伝えることを目的としています。

Unlike most Unix systems and services, Windows does not include a system
supported installation of Python. Instead, Python can be obtained from a number
of distributors, including directly from the CPython team. Each Python
distribution will have its own benefits and drawbacks, however, consistency with
other tools you are using is generally a worthwhile benefit. Before committing
to the process described here, we recommend investigating your existing tools to
see if they can provide Python directly.

To obtain Python from the CPython team, use the Python Install Manager. This
is a standalone tool that makes Python available as global commands on your
Windows machine, integrates with the system, and supports updates over time. You
can download the Python Install Manager from python.org/downloads@footnote{https://www.python.org/downloads/} or through
the Microsoft Store app@footnote{https://apps.microsoft.com/detail/9NQ7512CXL7T}.

Once you have installed the Python Install Manager, the global @code{python}
command can be used from any terminal to launch your current latest version of
Python. This version may change over time as you add or remove different
versions, and the @code{py list} command will show which is current.

In general, we recommend that you create a @ref{20eb,,virtual environment}
for each project and run @code{<env>\Scripts\Activate} in your terminal to use it.
This provides isolation between projects, consistency over time, and ensures
that additional commands added by packages are also available in your session.
Create a virtual environment using @code{python -m venv <env path>}.

If the @code{python} or @code{py} commands do not seem to be working, please see the
@ref{21fb,,Troubleshooting} section below. There are
sometimes additional manual steps required to configure your PC.

Apart from using the Python install manager, Python can also be obtained as
NuGet packages. See @ref{21fc,,nuget.org パッケージ} below for more information on these
packages.

The embeddable distros are minimal packages of Python suitable for embedding
into larger applications. They can be installed using the Python install
manager. See @ref{21fd,,埋め込み可能なパッケージ} below for more information on these
packages.
@anchor{using/windows pymanager}@anchor{21fe}@anchor{using/windows windows-store}@anchor{1fc9}@anchor{using/windows setting-envvars}@anchor{1fca}@anchor{using/windows windows-path-mod}@anchor{125c}
@menu
* Python install manager:: 
* 埋め込み可能なパッケージ:: 
* nuget.org パッケージ: nuget org パッケージ. 
* 別のバンドル:: 
* Supported Windows versions:: 
* Removing the MAX_PATH limitation:: 
* UTF-8 モード:: 
* モジュールの検索:: 
* 追加のモジュール:: 
* Windows 上で Python をコンパイルする:: 
* The full installer (deprecated): The full installer deprecated. 
* Python launcher for Windows (deprecated): Python launcher for Windows deprecated. 

@end menu

@node Python install manager,埋め込み可能なパッケージ,,Windows で Python を使う
@anchor{using/windows launcher}@anchor{7da}@anchor{using/windows python-install-manager}@anchor{21ff}
@subsection Python install manager


@menu
* Installation:: 
* 基本的な使い方:: 
* Command help:: 
* Listing runtimes:: 
* Installing runtimes:: 
* Offline installs:: 
* Uninstalling runtimes:: 
* Configuration:: 
* Shebang lines:: 
* Advanced installation:: 
* Administrative configuration:: 
* Installing free-threaded binaries:: 
* Troubleshooting:: 

@end menu

@node Installation,基本的な使い方,,Python install manager
@anchor{using/windows installation}@anchor{2200}
@subsubsection Installation


The Python install manager can be installed from the Microsoft Store app@footnote{https://apps.microsoft.com/detail/9NQ7512CXL7T}
or downloaded and installed from python.org/downloads@footnote{https://www.python.org/downloads/}. The two versions are
identical.

To install through the Store, simply click "Install". After it has completed,
open a terminal and type @code{python} to get started.

To install the file downloaded from python.org, either double-click and select
"Install", or run @code{Add-AppxPackage <path to MSIX>} in Windows Powershell.

After installation, the @code{python}, @code{py}, and @code{pymanager} commands should be
available. If you have existing installations of Python, or you have modified
your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} variable, you may need to remove them or undo the
modifications. See @ref{21fb,,Troubleshooting} for more help with fixing
non-working commands.

When you first install a runtime, you will likely be prompted to add a directory
to your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}. This is optional, if you prefer to use the @code{py}
command, but is offered for those who prefer the full range of aliases (such
as @code{python3.14.exe}) to be available. The directory will be
@code{%LocalAppData%\Python\bin} by default, but may be customized by an
administrator. Click Start and search for "Edit environment variables for your
account" for the system settings page to add the path.

Each Python runtime you install will have its own directory for scripts. These
also need to be added to 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} if you want to use them.

The Python install manager will be automatically updated to new releases. This
does not affect any installs of Python runtimes. Uninstalling the Python install
manager does not uninstall any Python runtimes.

If you are not able to install an MSIX in your context, for example, you are
using automated deployment software that does not support it, or are targeting
Windows Server 2019, please see @ref{2201,,Advanced installation} below for more
information.

@node 基本的な使い方,Command help,Installation,Python install manager
@anchor{using/windows basic-use}@anchor{2202}
@subsubsection 基本的な使い方


The recommended command for launching Python is @code{python}, which will either
launch the version requested by the script being launched, an active virtual
environment, or the default installed version, which will be the latest stable
release unless configured otherwise. If no version is specifically requested and
no runtimes are installed at all, the current latest release will be installed
automatically.

For all scenarios involving multiple runtime versions, the recommended command
is @code{py}. This may be used anywhere in place of @code{python} or the older
@code{py.exe} launcher. By default, @code{py} matches the behaviour of @code{python}, but
also allows command line options to select a specific version as well as
subcommands to manage installations. These are detailed below.

Because the @code{py} command may already be taken by the previous version, there
is also an unambiguous @code{pymanager} command. Scripted installs that are
intending to use Python install manager should consider using @code{pymanager}, due
to the lower chance of encountering a conflict with existing installs. The only
difference between the two commands is when running without any arguments:
@code{py} will launch your default interpreter, while @code{pymanager} will display
help (@code{pymanager exec ...} provides equivalent behaviour to @code{py ...}).

Each of these commands also has a windowed version that avoids creating a
console window. These are @code{pyw}, @code{pythonw} and @code{pymanagerw}. A @code{python3}
command is also included that mimics the @code{python} command. It is intended to
catch accidental uses of the typical POSIX command on Windows, but is not meant
to be widely used or recommended.

To launch your default runtime, run @code{python} or @code{py} with the arguments you
want to be passed to the runtime (such as script files or the module to launch):

@example
$> py
...
$> python my-script.py
...
$> py -m this
...
@end example

The default runtime can be overridden with the 
@geindex PYTHON_MANAGER_DEFAULT
@geindex 環境変数; PYTHON_MANAGER_DEFAULT
@ref{2203,,PYTHON_MANAGER_DEFAULT}
environment variable, or a configuration file. See @ref{2204,,Configuration} for
information about configuration settings.

To launch a specific runtime, the @code{py} command accepts a @code{-V:<TAG>} option.
This option must be specified before any others. The tag is part or all of the
identifier for the runtime; for those from the CPython team, it looks like the
version, potentially with the platform. For compatibility, the @code{V:} may be
omitted in cases where the tag refers to an official release and starts with
@code{3}.

@example
$> py -V:3.14 ...
$> py -V:3-arm64 ...
@end example

Runtimes from other distributors may require the `company' to be included as
well. This should be separated from the tag by a slash, and may be a prefix.
Specifying the company is optional when it is @code{PythonCore}, and specifying the
tag is optional (but not the slash) when you want the latest release from a
specific company.

@example
$> py -V:Distributor\1.0 ...
$> py -V:distrib/ ...
@end example

If no version is specified, but a script file is passed, the script will be
inspected for a `shebang line'. This is a special format for the first line in
a file that allows overriding the command. See @ref{2205,,Shebang lines} for more
information. When there is no shebang line, or it cannot be resolved, the script
will be launched with the default runtime.

If you are running in an active virtual environment, have not requested a
particular version, and there is no shebang line, the default runtime will be
that virtual environment. In this scenario, the @code{python} command was likely
already overridden and none of these checks occurred. However, this behaviour
ensures that the @code{py} command can be used interchangeably.

When no runtimes are installed, any launch command will try to install the
requested version and launch it. However, after any version is installed, only
the @code{py exec ...} and @code{pymanager exec ...} commands will install if the
requested version is absent. Other forms of commands will display an error and
direct you to use @code{py install} first.

@node Command help,Listing runtimes,基本的な使い方,Python install manager
@anchor{using/windows command-help}@anchor{2206}
@subsubsection Command help


The @code{py help} command will display the full list of supported commands, along
with their options. Any command may be passed the @code{-?} option to display its
help, or its name passed to @code{py help}.

@example
$> py help
$> py help install
$> py install /?
@end example

All commands support some common options, which will be shown by @code{py help}.
These options must be specified after any subcommand. Specifying @code{-v} or
@code{--verbose} will increase the amount of output shown, and @code{-vv} will
increase it further for debugging purposes. Passing @code{-q} or @code{--quiet} will
reduce output, and @code{-qq} will reduce it further.

The @code{--config=<PATH>} option allows specifying a configuration file to
override multiple settings at once. See @ref{2204,,Configuration} below for more
information about these files.

@node Listing runtimes,Installing runtimes,Command help,Python install manager
@anchor{using/windows listing-runtimes}@anchor{2207}
@subsubsection Listing runtimes


@example
$> py list [-f=|--format=<FMT>] [-1|--one] [--online|-s=|--source=<URL>] [<TAG>...]
@end example

The list of installed runtimes can be seen using @code{py list}. A filter may be
added in the form of one or more tags (with or without company specifier), and
each may include a @code{<}, @code{<=}, @code{>=} or @code{>} prefix to restrict to a range.

A range of formats are supported, and can be passed as the @code{--format=<FMT>} or
@code{-f <FMT>} option. Formats include @code{table} (a user friendly table view),
@code{csv} (comma-separated table), @code{json} (a single JSON blob), @code{jsonl} (one
JSON blob per result), @code{exe} (just the executable path), @code{prefix} (just the
prefix path).

The @code{--one} or @code{-1} option only displays a single result. If the default
runtime is included, it will be the one. Otherwise, the "best" result is shown
("best" is deliberately vaguely defined, but will usually be the most recent
version). The result shown by @code{py list --one <TAG>} will match the runtime
that would be launched by @code{py -V:<TAG>}.

The @code{--only-managed} option excludes results that were not installed by the
Python install manager. This is useful when determining which runtimes may be
updated or uninstalled through the @code{py} command.

The @code{--online} option is short for passing @code{--source=<URL>} with the default
source. Passing either of these options will search the online index for
runtimes that can be installed. The result shown by @code{py list --online --one
<TAG>} will match the runtime that would be installed by @code{py install <TAG>}.

@example
$> py list --online 3.14
@end example

For compatibility with the old launcher, the @code{--list}, @code{--list-paths},
@code{-0} and @code{-0p} commands (e.g. @code{py -0p}) are retained. They do not allow
additional options, and will produce legacy formatted output.

@node Installing runtimes,Offline installs,Listing runtimes,Python install manager
@anchor{using/windows installing-runtimes}@anchor{2208}
@subsubsection Installing runtimes


@example
$> py install [-s=|--source=<URL>] [-f|--force] [-u|--update] [--dry-run] [<TAG>...]
@end example

New runtime versions may be added using @code{py install}. One or more tags may be
specified, and the special tag @code{default} may be used to select the default.
Ranges are not supported for installation.

The @code{--source=<URL>} option allows overriding the online index that is used to
obtain runtimes. This may be used with an offline index, as shown in
@ref{2209,,Offline installs}.

Passing @code{--force} will ignore any cached files and remove any existing install
to replace it with the specified one.

Passing @code{--update} will replace existing installs if the new version is newer.
Otherwise, they will be left. If no tags are provided with @code{--update}, all
installs managed by the Python install manager will be updated if newer versions
are available. Updates will remove any modifications made to the install,
including globally installed packages, but virtual environments will continue to
work.

Passing @code{--dry-run} will generate output and logs, but will not modify any
installs.

In addition to the above options, the @code{--target} option will extract the
runtime to the specified directory instead of doing a normal install.
This is useful for embedding runtimes into larger applications.
Unlike a normal install, @code{py} will not be aware of the extracted runtime,
and no Start menu or other shortcuts will be created.
To launch the runtime, directly execute the main executable (typically
@code{python.exe}) in the target directory.

@example
$> py install ... [-t=|--target=<PATH>] <TAG>
@end example

The @code{py exec} command will install the requested runtime if it is not already
present. This is controlled by the @code{automatic_install} configuration
(
@geindex PYTHON_MANAGER_AUTOMATIC_INSTALL
@geindex 環境変数; PYTHON_MANAGER_AUTOMATIC_INSTALL
@ref{220a,,PYTHON_MANAGER_AUTOMATIC_INSTALL}), and is enabled by default.
If no runtimes are available at all, all launch commands will do an automatic
install if the configuration setting allows. This is to ensure a good experience
for new users, but should not generally be relied on rather than using the
@code{py exec} command or explicit install commands.

@node Offline installs,Uninstalling runtimes,Installing runtimes,Python install manager
@anchor{using/windows offline-installs}@anchor{220b}@anchor{using/windows pymanager-offline}@anchor{2209}
@subsubsection Offline installs


To perform offline installs of Python, you will need to first create an offline
index on a machine that has network access.

@example
$> py install --download=<PATH> ... <TAG>...
@end example

The @code{--download=<PATH>} option will download the packages for the listed tags
and create a directory containing them and an @code{index.json} file suitable for
later installation. This entire directory can be moved to the offline machine
and used to install one or more of the bundled runtimes:

@example
$> py install --source="<PATH>\index.json" <TAG>...
@end example

The Python install manager can be installed by downloading its installer and
moving it to another machine before installing.

Alternatively, the ZIP files in an offline index directory can simply be
transferred to another machine and extracted. This will not register the install
in any way, and so it must be launched by directly referencing the executables
in the extracted directory, but it is sometimes a preferable approach in cases
where installing the Python install manager is not possible or convenient.

In this way, Python runtimes can be installed and managed on a machine without
access to the internet.

@node Uninstalling runtimes,Configuration,Offline installs,Python install manager
@anchor{using/windows uninstalling-runtimes}@anchor{220c}
@subsubsection Uninstalling runtimes


@example
$> py uninstall [-y|--yes] <TAG>...
@end example

Runtimes may be removed using the @code{py uninstall} command. One or more tags
must be specified. Ranges are not supported here.

The @code{--yes} option bypasses the confirmation prompt before uninstalling.

Instead of passing tags individually, the @code{--purge} option may be specified.
This will remove all runtimes managed by the Python install manager, including
cleaning up the Start menu, registry, and any download caches. Runtimes that
were not installed by the Python install manager will not be impacted, and
neither will manually created configuration files.

@example
$> py uninstall [-y|--yes] --purge
@end example

The Python install manager can be uninstalled through the Windows "Installed
apps" settings page. This does not remove any runtimes, and they will still be
usable, though the global @code{python} and @code{py} commands will be removed.
Reinstalling the Python install manager will allow you to manage these runtimes
again. To completely clean up all Python runtimes, run with @code{--purge} before
uninstalling the Python install manager.

@node Configuration,Shebang lines,Uninstalling runtimes,Python install manager
@anchor{using/windows configuration}@anchor{220d}@anchor{using/windows pymanager-config}@anchor{2204}
@subsubsection Configuration


Python install manager is configured with a hierarchy of configuration files,
environment variables, command-line options, and registry settings. In general,
configuration files have the ability to configure everything, including the
location of other configuration files, while registry settings are
administrator-only and will override configuration files. Command-line options
override all other settings, but not every option is available.

This section will describe the defaults, but be aware that modified or
overridden installs may resolve settings differently.

A global configuration file may be configured by an administrator, and would be
read first. The user configuration file is stored at
@code{%AppData%\Python\pymanager.json}
(note that this location is under @code{Roaming}, not @code{Local}) and is read next,
overwriting any settings from earlier files. An additional configuration file
may be specified as the @code{PYTHON_MANAGER_CONFIG} environment variable or the
@code{--config} command line option (but not both).
These locations may be modified by administrative customization options listed
later.

The following settings are those that are considered likely to be modified in
normal use. Later sections list those that are intended for administrative
customization.

@c Sphinx bug with text writer; remove widths & caption temporarily

@c :widths: 2, 2, 4

@subsubheading Standard configuration options



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Config Key

@tab

Environment Variable

@tab

説明

@item

@code{default_tag}

@tab

@geindex 環境変数; PYTHON_MANAGER_DEFAULT
@anchor{using/windows envvar-PYTHON_MANAGER_DEFAULT}@anchor{2203}
@deffn {環境変数} PYTHON_MANAGER_DEFAULT
@end deffn

@tab

The preferred default version to launch or install.
By default, this is interpreted as the most recent non-prerelease version
from the CPython team.

@item

@code{default_platform}

@tab

@code{PYTHON_MANAGER_DEFAULT_PLATFORM}

@tab

The preferred default platform to launch or install.
This is treated as a suffix to the specified tag, such that @code{py -V:3.14}
would prefer an install for @code{3.14-64} if it exists
(and @code{default_platform} is @code{-64}),
but will use @code{3.14} if no tagged install exists.

@item

@code{logs_dir}

@tab

@code{PYTHON_MANAGER_LOGS}

@tab

The location where log files are written.
By default, @code{%TEMP%}.

@item

@code{automatic_install}

@tab

@geindex 環境変数; PYTHON_MANAGER_AUTOMATIC_INSTALL
@anchor{using/windows envvar-PYTHON_MANAGER_AUTOMATIC_INSTALL}@anchor{220a}
@deffn {環境変数} PYTHON_MANAGER_AUTOMATIC_INSTALL
@end deffn

@tab

True to allow automatic installs when using @code{py exec} to launch (or
@code{py} when no runtimes are installed yet).
Other commands will not automatically install, regardless of this
setting.
By default, true.

@item

@code{include_unmanaged}

@tab

@code{PYTHON_MANAGER_INCLUDE_UNMANAGED}

@tab

True to allow listing and launching runtimes that were not installed
by the Python install manager, or false to exclude them.
By default, true.

@item

@code{shebang_can_run_anything}

@tab

@code{PYTHON_MANAGER_SHEBANG_CAN_RUN_ANYTHING}

@tab

True to allow shebangs in @code{.py} files to launch applications other than
Python runtimes, or false to prevent it.
By default, true.

@item

@code{log_level}

@tab

@code{PYMANAGER_VERBOSE}, @code{PYMANAGER_DEBUG}

@tab

Set the default level of output (0-50).
By default, 20.
Lower values produce more output.
The environment variables are boolean, and may produce additional
output during startup that is later suppressed by other configuration.

@item

@code{confirm}

@tab

@code{PYTHON_MANAGER_CONFIRM}

@tab

True to confirm certain actions before taking them (such as uninstall),
or false to skip the confirmation.
By default, true.

@item

@code{install.source}

@tab

@code{PYTHON_MANAGER_SOURCE_URL}

@tab

Override the index feed to obtain new installs from.

@item

@code{list.format}

@tab

@code{PYTHON_MANAGER_LIST_FORMAT}

@tab

Specify the default format used by the @code{py list} command.
By default, @code{table}.

@item

@code{install_dir}

@tab

(none)

@tab

Specify the root directory that runtimes will be installed into.
If you change this setting, previously installed runtimes will not be
usable unless you move them to the new location.

@item

@code{global_dir}

@tab

(none)

@tab

Specify the directory where global commands (such as @code{python3.14.exe})
are stored.
This directory should be added to your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} to make the
commands available from your terminal.

@item

@code{download_dir}

@tab

(none)

@tab

Specify the directory where downloaded files are stored.
This directory is a temporary cache, and can be cleaned up from time to
time.

@end multitable


Dotted names should be nested inside JSON objects, for example, @code{list.format}
would be specified as @code{@{"list": @{"format": "table"@}@}}.

@node Shebang lines,Advanced installation,Configuration,Python install manager
@anchor{using/windows pymanager-shebang}@anchor{2205}@anchor{using/windows shebang-lines}@anchor{220e}
@subsubsection Shebang lines


If the first line of a script file starts with @code{#!}, it is known as a
"shebang" line.  Linux and other Unix like operating systems have native
support for such lines and they are commonly used on such systems to indicate
how a script should be executed. The @code{python} and @code{py} commands allow the
same facilities to be used with Python scripts on Windows.

To allow shebang lines in Python scripts to be portable between Unix and
Windows, a number of 'virtual' commands are supported to specify which
interpreter to use.  The supported virtual commands are:


@itemize *

@item 
@code{/usr/bin/env <ALIAS>}

@item 
@code{/usr/bin/env -S <ALIAS>}

@item 
@code{/usr/bin/<ALIAS>}

@item 
@code{/usr/local/bin/<ALIAS>}

@item 
@code{<ALIAS>}
@end itemize

具体的に、もしスクリプトの1行目が

@example
#! /usr/bin/python
@end example

で始まっていたら、デフォルトの Python またはアクティブな仮想環境の位置が特定され、使用されます。多くの Unix 上で動作する Python スクリプトにはすでにこの行が存在する傾向がありますので、ランチャによりそれらのスクリプトを修正なしで使うことができるはずです。あなたが新しいスクリプトを Windows 上で書いていて、Unix 上でも有用であってほしいと思うなら、シェバン行のうち @code{/usr} で始まるものを使用すべきです。

Any of the above virtual commands can have @code{<ALIAS>} replaced by an alias from
an installed runtime. That is, any command generated in the global aliases
directory (which you may have added to your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable)
can be used in a shebang, even if it is not on your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}. This allows
the use of shebangs like @code{/usr/bin/python3.12} to select a particular runtime.

If no runtimes are installed, or if automatic installation is enabled, the
requested runtime will be installed if necessary. See @ref{2204,,Configuration}
for information about configuration settings.

The @code{/usr/bin/env} form of shebang line will also search the 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}
environment variable for unrecognized commands. This corresponds to the
behaviour of the Unix @code{env} program, which performs the same search, but
prefers launching known Python commands. A warning may be displayed when
searching for arbitrary executables, and this search may be disabled by the
@code{shebang_can_run_anything} configuration option.

Shebang lines that do not match any of patterns are treated as `Windows'
executable paths that are absolute or relative to the directory containing the
script file. This is a convenience for Windows-only scripts, such as those
generated by an installer, since the behavior is not compatible with Unix-style
shells. These paths may be quoted, and may include multiple arguments, after
which the path to the script and any additional arguments will be appended.
This functionality may be disabled by the @code{shebang_can_run_anything}
configuration option.

@cartouche
@quotation 注釈 
The behaviour of shebangs in the Python install manager is subtly different
from the previous @code{py.exe} launcher, and the old configuration options no
longer apply. If you are specifically reliant on the old behaviour or
configuration, we recommend installing the legacy launcher@footnote{https://www.python.org/ftp/python/3.14.0/win32/launcher.msi}. The legacy
launcher's @code{py} command will override PyManager's one by default, and you
will need to use @code{pymanager} commands for installing and uninstalling.
@end quotation
@end cartouche

@node Advanced installation,Administrative configuration,Shebang lines,Python install manager
@anchor{using/windows advanced-installation}@anchor{220f}@anchor{using/windows pymanager-advancedinstall}@anchor{2201}
@subsubsection Advanced installation


For situations where an MSIX cannot be installed, such as some older
administrative distribution platforms, there is an MSI available from the
python.org downloads page. This MSI has no user interface, and can only perform
per-machine installs to its default location in Program Files. It will attempt
to modify the system 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable to include this install
location, but be sure to validate this on your configuration.

@cartouche
@quotation 注釈 
Windows Server 2019 is the only version of Windows that CPython supports that
does not support MSIX. For Windows Server 2019, you should use the MSI.
@end quotation
@end cartouche

Be aware that the MSI package does not bundle any runtimes, and so is not
suitable for installs into offline environments without also creating an offline
install index. See @ref{2209,,Offline installs} and @ref{2210,,Administrative configuration}
for information on handling these scenarios.

Runtimes installed by the MSI are shared with those installed by the MSIX, and
are all per-user only. The Python install manager does not support installing
runtimes per-machine. To emulate a per-machine install, you can use @code{py install
--target=<shared location>} as administrator and add your own system-wide
modifications to 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}, the registry, or the Start menu.

When the MSIX is installed, but commands are not available in the 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}
environment variable, they can be found under
@code{%LocalAppData%\Microsoft\WindowsApps\PythonSoftwareFoundation.PythonManager_3847v3x7pw1km}
or
@code{%LocalAppData%\Microsoft\WindowsApps\PythonSoftwareFoundation.PythonManager_qbz5n2kfra8p0},
depending on whether it was installed from python.org or through the Windows
Store. Attempting to run the executable directly from Program Files is not
recommended.

To programmatically install the Python install manager, it is easiest to use
WinGet, which is included with all supported versions of Windows:

@example
$> winget install 9NQ7512CXL7T -e --accept-package-agreements --disable-interactivity

# Optionally run the configuration checker and accept all changes
$> py install --configure -y
@end example

To download the Python install manager and install on another machine, the
following WinGet command will download the required files from the Store to your
Downloads directory (add @code{-d <location>} to customize the output location).
This also generates a YAML file that appears to be unnecessary, as the
downloaded MSIX can be installed by launching or using the commands below.

@example
$> winget download 9NQ7512CXL7T -e --skip-license --accept-package-agreements --accept-source-agreements
@end example

To programmatically install or uninstall an MSIX using only PowerShell, the
Add-AppxPackage@footnote{https://learn.microsoft.com/powershell/module/appx/add-appxpackage} and Remove-AppxPackage@footnote{https://learn.microsoft.com/powershell/module/appx/remove-appxpackage} PowerShell cmdlets are recommended:

@example
$> Add-AppxPackage C:\Downloads\python-manager-25.0.msix
...
$> Get-AppxPackage PythonSoftwareFoundation.PythonManager | Remove-AppxPackage
@end example

The latest release can be downloaded and installed by Windows by passing the
AppInstaller file to the Add-AppxPackage command. This installs using the MSIX
on python.org, and is only recommended for cases where installing via the Store
(interactively or using WinGet) is not possible.

@example
$> Add-AppxPackage -AppInstallerFile https://www.python.org/ftp/python/pymanager/pymanager.appinstaller
@end example

Other tools and APIs may also be used to provision an MSIX package for all users
on a machine, but Python does not consider this a supported scenario. We suggest
looking into the PowerShell Add-AppxProvisionedPackage@footnote{https://learn.microsoft.com/powershell/module/dism/add-appxprovisionedpackage} cmdlet, the native
Windows PackageManager@footnote{https://learn.microsoft.com/uwp/api/windows.management.deployment.packagemanager} class, or the documentation and support for your
deployment tool.

Regardless of the install method, users will still need to install their own
copies of Python itself, as there is no way to trigger those installs without
being a logged in user. When using the MSIX, the latest version of Python will
be available for all users to install without network access.

Note that the MSIX downloadable from the Store and from the Python website are
subtly different and cannot be installed at the same time. Wherever possible,
we suggest using the above WinGet commands to download the package from the
Store to reduce the risk of setting up conflicting installs. There are no
licensing restrictions on the Python install manager that would prevent using
the Store package in this way.

@node Administrative configuration,Installing free-threaded binaries,Advanced installation,Python install manager
@anchor{using/windows administrative-configuration}@anchor{2211}@anchor{using/windows pymanager-admin-config}@anchor{2210}
@subsubsection Administrative configuration


There are a number of options that may be useful for administrators to override
configuration of the Python install manager. These can be used to provide local
caching, disable certain shortcut types, override bundled content. All of the
above configuration options may be set, as well as those below.

Configuration options may be overridden in the registry by setting values under
@code{HKEY_LOCAL_MACHINE\Software\Policies\Python\PyManager}, where the
value name matches the configuration key and the value type is @code{REG_SZ}. Note
that this key can itself be customized, but only by modifying the core config
file distributed with the Python install manager. We recommend, however, that
registry values are used only to set @code{base_config} to a JSON file containing
the full set of overrides. Registry key overrides will replace any other
configured setting, while @code{base_config} allows users to further modify
settings they may need.

Note that most settings with environment variables support those variables
because their default setting specifies the variable. If you override them, the
environment variable will no longer work, unless you override it with another
one. For example, the default value of @code{confirm} is literally
@code{%PYTHON_MANAGER_CONFIRM%}, which will resolve the variable at load time. If
you override the value to @code{yes}, then the environment variable will no longer
be used. If you override the value to @code{%CONFIRM%}, then that environment
variable will be used instead.

Configuration settings that are paths are interpreted as relative to the
directory containing the configuration file that specified them.

@c Sphinx bug with text writer; remove widths & caption temporarily

@c :widths: 1, 4

@subsubheading Administrative configuration options



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Config Key

@tab

説明

@item

@code{base_config}

@tab

The highest priority configuration file to read.
Note that only the built-in configuration file and the registry can
modify this setting.

@item

@code{user_config}

@tab

The second configuration file to read.

@item

@code{additional_config}

@tab

The third configuration file to read.

@item

@code{registry_override_key}

@tab

Registry location to check for overrides.
Note that only the built-in configuration file can modify this setting.

@item

@code{bundled_dir}

@tab

Read-only directory containing locally cached files.

@item

@code{install.fallback_source}

@tab

Path or URL to an index to consult when the main index cannot be accessed.

@item

@code{install.enable_shortcut_kinds}

@tab

Comma-separated list of shortcut kinds to allow (e.g. @code{"pep514,start"}).
Enabled shortcuts may still be disabled by @code{disable_shortcut_kinds}.

@item

@code{install.disable_shortcut_kinds}

@tab

Comma-separated list of shortcut kinds to exclude
(e.g. @code{"pep514,start"}).
Disabled shortcuts are not reactivated by @code{enable_shortcut_kinds}.

@item

@code{pep514_root}

@tab

Registry location to read and write PEP 514 entries into.
By default, @code{HKEY_CURRENT_USER\Software\Python}.

@item

@code{start_folder}

@tab

Start menu folder to write shortcuts into.
By default, @code{Python}.
This path is relative to the user's Programs folder.

@item

@code{virtual_env}

@tab

Path to the active virtual environment.
By default, this is @code{%VIRTUAL_ENV%}, but may be set empty
to disable venv detection.

@item

@code{shebang_can_run_anything_silently}

@tab

True to suppress visible warnings when a shebang launches an application
other than a Python runtime.

@end multitable


@node Installing free-threaded binaries,Troubleshooting,Administrative configuration,Python install manager
@anchor{using/windows install-freethreaded-windows}@anchor{497}@anchor{using/windows installing-free-threaded-binaries}@anchor{2212}
@subsubsection Installing free-threaded binaries



Added in version 3.13.


Pre-built distributions of the free-threaded build are available
by installing tags with the @code{t} suffix.

@example
$> py install 3.14t
$> py install 3.14t-arm64
$> py install 3.14t-32
@end example

This will install and register as normal. If you have no other runtimes
installed, then @code{python} will launch this one. Otherwise, you will need to use
@code{py -V:3.14t ...} or, if you have added the global aliases directory to your
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable, the @code{python3.14t.exe} commands.

@node Troubleshooting,,Installing free-threaded binaries,Python install manager
@anchor{using/windows pymanager-troubleshoot}@anchor{21fb}@anchor{using/windows troubleshooting}@anchor{2213}
@subsubsection Troubleshooting


If your Python install manager does not seem to be working correctly, please
work through these tests and fixes to see if it helps. If not, please report an
issue at our bug tracker@footnote{https://github.com/python/pymanager/issues},
including any relevant log files (written to your @code{%TEMP%} directory by
default).

@c Sphinx bug with text writer; remove widths & caption temporarily

@c :widths: 1, 1

@subsubheading Troubleshooting



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Symptom

@tab

Things to try

@item

@code{python} gives me a "command not found" error or opens the Store app
when I type it in my terminal.

@tab

Did you @ref{21fe,,install the Python install manager}?

@item

@tab

Click Start, open "Manage app execution aliases", and check that the
aliases for "Python (default)" are enabled.
If they already are, try disabling and re-enabling to refresh the command.
The "Python (default windowed)" and "Python install manager" commands
may also need refreshing.

@item

@tab

Check that the @code{py} and @code{pymanager} commands work.

@item

@tab

Ensure your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} variable contains the entry for
@code{%UserProfile%\AppData\Local\Microsoft\WindowsApps}.
The operating system includes this entry once by default, after other
user paths. If removed, shortcuts will not be found.

@item

@code{py} gives me a "command not found" error when I type it in my terminal.

@tab

Did you @ref{21fe,,install the Python install manager}?

@item

@tab

Click Start, open "Manage app execution aliases", and check that the
aliases for "Python (default)" are enabled.
If they already are, try disabling and re-enabling to refresh the command.
The "Python (default windowed)" and "Python install manager" commands
may also need refreshing.

@item

@tab

Ensure your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} variable contains the entry for
@code{%UserProfile%\AppData\Local\Microsoft\WindowsApps}.
The operating system includes this entry once by default, after other
user paths. If removed, shortcuts will not be found.

@item

@code{py} gives me a "can't open file" error when I type commands in my
terminal.

@tab

This usually means you have the legacy launcher installed and
it has priority over the Python install manager.
To remove, click Start, open "Installed apps",
search for "Python launcher" and uninstall it.

@item

@code{python} doesn't launch the same runtime as @code{py}

@tab

Click Start, open "Installed apps", look for any existing Python runtimes,
and either remove them or Modify and disable the 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} options.

@item

@tab

Click Start, open "Manage app execution aliases", and check that your
@code{python.exe} alias is set to "Python (default)"

@item

@code{python} and @code{py} don't launch the runtime I expect

@tab

Check your 
@geindex PYTHON_MANAGER_DEFAULT
@geindex 環境変数; PYTHON_MANAGER_DEFAULT
@ref{2203,,PYTHON_MANAGER_DEFAULT} environment variable
or @code{default_tag} configuration.
The @code{py list} command will show your default based on these settings.

@item

@tab

Installs that are managed by the Python install manager will be chosen
ahead of unmanaged installs.
Use @code{py install} to install the runtime you expect,
or configure your default tag.

@item

@tab

Prerelease and experimental installs that are not managed by the Python
install manager may be chosen ahead of stable releases.
Configure your default tag or uninstall the prerelease runtime
and reinstall it using @code{py install}.

@item

@code{pythonw} or @code{pyw} don't launch the same runtime as @code{python} or @code{py}

@tab

Click Start, open "Manage app execution aliases", and check that your
@code{pythonw.exe} and @code{pyw.exe} aliases are consistent with your others.

@item

@code{pip} gives me a "command not found" error when I type it in my terminal.

@tab

Have you activated a virtual environment?
Run the @code{.venv\Scripts\activate} script in your terminal to activate.

@item

@tab

The package may be available but missing the generated executable.
We recommend using the @code{python -m pip} command instead,
or alternatively the @code{python -m pip install --force pip} command
will recreate the executables and show you the path to
add to 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}.
These scripts are separated for each runtime, and so you may need to
add multiple paths.

@item

Typing @code{script-name.py} in the terminal opens in a new window.

@tab

This is a known limitation of the operating system. Either specify @code{py}
before the script name, create a batch file containing @code{@@py "%~dpn0.py" %*}
with the same name as the script, or install the legacy launcher@footnote{https://www.python.org/ftp/python/3.14.0/win32/launcher.msi}
and select it as the association for scripts.

@item

Drag-dropping files onto a script doesn't work

@tab

This is a known limitation of the operating system. It is supported with
the legacy launcher@footnote{https://www.python.org/ftp/python/3.14.0/win32/launcher.msi}, or with the Python install manager when installed
from the MSI.

@item

I have installed the Python install manager multiple times.

@tab

It is possible to install from the Store or WinGet, from the MSIX on
the Python website, and from the MSI, all at once.
They are all compatible and will share configuration and runtimes.

@item

@tab

See the earlier @ref{2201,,Advanced installation} section for ways to
uninstall the install manager other than the typical Installed Apps
(Add and Remove Programs) settings page.

@item

My old @code{py.ini} settings no longer work.

@tab

The new Python install manager no longer supports this configuration file
or its settings, and so it will be ignored.
See @ref{2204,,Configuration} for information about configuration settings.

@end multitable


@node 埋め込み可能なパッケージ,nuget org パッケージ,Python install manager,Windows で Python を使う
@anchor{using/windows the-embeddable-package}@anchor{2214}@anchor{using/windows windows-embeddable}@anchor{21fd}
@subsection 埋め込み可能なパッケージ



Added in version 3.5.


埋め込み用の配布 (embedded distribution) は、最小限の Python 環境を含んだ ZIP ファイルです。これは、エンドユーザから直接的にアクセスされるのではなく何かアプリケーションの一部として動作することを意図したものです。

To install an embedded distribution, we recommend using @code{py install} with the
@code{--target} option:

@example
$> py install 3.14-embed --target=<directory>
@end example

When extracted, the embedded distribution is (almost) fully isolated from the
user's system, including environment variables, system registry settings, and
installed packages. The standard library is included as pre-compiled and
optimized @code{.pyc} files in a ZIP, and @code{python3.dll}, @code{python313.dll},
@code{python.exe} and @code{pythonw.exe} are all provided. Tcl/tk (including all
dependents, such as Idle), pip and the Python documentation are not included.

A default @code{._pth} file is included, which further restricts the default search
paths (as described below in @ref{e1a,,モジュールの検索}). This file is
intended for embedders to modify as necessary.

サードパーティのパッケージはアプリケーションのインストーラによって、埋め込み用配布と同じ場所にインストールされるべきです。通常の Python インストレーションのように依存性管理に pip を使うことは、この配布ではサポートされません。ですが、ちょっとした注意を払えば、自動更新のために pip を含めて利用することはできるかもしれません。一般的には、ユーザに更新を提供する前に開発者が新しいバージョンとの互換性を保証できるよう、サードパーティーのパッケージはアプリケーションの一部として扱われるべきです ("vendoring")。

この配布の 2 つのお勧めできるユースケースを、以下で説明します。

@menu
* Python application:: 
* Python の埋め込み:: 

@end menu

@node Python application,Python の埋め込み,,埋め込み可能なパッケージ
@anchor{using/windows python-application}@anchor{2215}
@subsubsection Python application


Python で記述された、必ずしもユーザにその事実を意識させる必要のないアプリケーションです。埋め込み用配布はこのケースで、インストールパッケージ内に Python のプライベートバージョンを含めるのに使えるでしょう。その事実がどのように透過的であるべきかに依存して (あるいは逆に、どのようにプロフェッショナルにみえるべきか)、2 つの選択肢があります。

ランチャとなる特別な実行ファイルを使うことはちょっとしたコーディングを必要としますが、ユーザにとっては最も透過的なユーザ体験となります。カスタマイズされたランチャでは、何もしなければ Python で実行されるプログラムの明白な目印はありません; アイコンはカスタマイズし、会社名やバージョン情報を指定し、ファイルの関連付けがそれに相応しく振舞うようにできます。ほとんどのケースではカスタムランチャは、ハードコードされたコマンドライン文字列で単純に @code{Py_Main} を呼び出すので済むはずです。

より簡単なアプローチは、 @code{python.exe} または @code{pythonw.exe} を必要なコマンドライン引数とともに直接呼び出すバッチファイルかショートカットを提供することです。この場合、そのアプリケーションは実際の名前ではなく Python であるようにみえるので、ほかに動作している Python プロセスやファイルの関連付けと区別するのにユーザが困るかもしれません。

後者のアプローチではパッケージは、パス上で利用可能であることを保証するために、Python 実行ファイルと同じディレクトリにインストールされるべきです。特別なランチャの場合はアプリケーション起動前に検索パスを指定する機会があるので、パッケージはほかの場所に配置できます。

@node Python の埋め込み,,Python application,埋め込み可能なパッケージ
@anchor{using/windows embedding-python}@anchor{2216}
@subsubsection Python の埋め込み


ネイティブコードで書かれ、時々スクリプト言語のようなものを必要とするようなアプリケーションです。Python 埋め込み用の配布はこの目的に使えます。一般的に、アプリケーションの大半がネイティブコード内にあり、一部が @code{python.exe} を呼び出すか、直接的に @code{python3.dll} を使います。どちらのケースでも、ロード可能な Python インタプリタを提供するのには、埋め込み用の配布を展開してアプリケーションのインストレーションのサブディレクトリに置くことで十分です。

アプリケーションが使うパッケージは、インタプリタ初期化前に検索パスを指定する機会があるので、任意の場所にインストールできます。また、埋め込み用配布を使うのと通常の Python インストレーションを使うのとでの根本的な違いはありません。

@node nuget org パッケージ,別のバンドル,埋め込み可能なパッケージ,Windows で Python を使う
@anchor{using/windows the-nuget-org-packages}@anchor{2217}@anchor{using/windows windows-nuget}@anchor{21fc}
@subsection nuget.org パッケージ



Added in version 3.5.2.


nuget.org パッケージはサイズを縮小した Python 環境で、システム全体で使える Python が無い継続的インテグレーションやビルドシステムで使うことを意図しています。
nuget は ".NET のためのパッケージマネージャ" ですが、ビルド時に使うツールを含んだパッケージに対しても非常に上手く動作します。

nuget の使用方法についての最新の情報を得るには nuget.org@footnote{https://www.nuget.org/} に行ってください。
ここから先は Python 開発者にとって十分な要約です。

@code{nuget.exe} コマンドラインツールは、例えば curl や PowerShell を使って @code{https://aka.ms/nugetclidl} から直接ダウンロードできるでしょう。
このツールを次のように使って、 64 bit あるいは 32 bit のマシン向けの最新バージョンの Python がインストールできます:

@example
nuget.exe install python -ExcludeVersion -OutputDirectory .
nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory .
@end example

特定のバージョンを選択するには、 @code{-Version 3.x.y} を追加してください。
出力ディレクトリは @code{.} から変更されることがあり、パッケージはサブディレクトリにインストールされます。
デフォルトではサブディレクトリはパッケージと同じ名前になり、 @code{-ExcludeVersion} オプションを付けないとこの名前はインストールされたバージョンを含みます。
サブディレクトリの中にはインストールされた Python を含んでいる @code{tools} ディレクトリがあります:

@example
# Without -ExcludeVersion
> .\python.3.5.2\tools\python.exe -V
Python 3.5.2

# With -ExcludeVersion
> .\python\tools\python.exe -V
Python 3.5.2
@end example

一般的には、 nuget パッケージはアップグレードできず、より新しいバージョンは横並びにインストールされ、フルパスで参照されます。
そうする代わりに、手動で直接パッケージを削除し、再度インストールすることもできます。
多くの CI システムは、ビルド間でファイルを保存しておかない場合、この作業を自動的に行います。

@code{tools} ディレクトリと同じ場所に @code{build\native} ディレクトリがあります。
このディレクトリは、インストールされた Python を参照する C++ プロジェクトで使える MSBuild プロパティファイル @code{python.props} を含みます。
ここに設定を入れると自動的にヘッダを使い、ビルド時にライプラリをインポートします。

The package information pages on nuget.org are
www.nuget.org/packages/python@footnote{https://www.nuget.org/packages/python}
for the 64-bit version, www.nuget.org/packages/pythonx86@footnote{https://www.nuget.org/packages/pythonx86} for the 32-bit version, and
www.nuget.org/packages/pythonarm64@footnote{https://www.nuget.org/packages/pythonarm64} for the ARM64 version

@menu
* フリースレッドパッケージ (Free-threaded packages): フリースレッドパッケージ Free-threaded packages. 

@end menu

@node フリースレッドパッケージ Free-threaded packages,,,nuget org パッケージ
@anchor{using/windows free-threaded-packages}@anchor{2218}
@subsubsection フリースレッドパッケージ (Free-threaded packages)



Added in version 3.13.


フリースレッドバイナリ (free-threaded binaries) を含むパッケージは、 64-bit 版では python-freethreaded@footnote{https://www.nuget.org/packages/python-freethreaded} 、 32-bit 版では pythonx86-freethreaded@footnote{https://www.nuget.org/packages/pythonx86-freethreaded} 、 ARM64 版では pythonarm64-freethreaded@footnote{https://www.nuget.org/packages/pythonarm64-freethreaded} と命名されます。これらのパッケージはともに @code{python3.13t.exe} と @code{python.exe} エントリーポイントを含み、どちらもフリースレッドで実行されます。

@node 別のバンドル,Supported Windows versions,nuget org パッケージ,Windows で Python を使う
@anchor{using/windows alternative-bundles}@anchor{2219}
@subsection 別のバンドル


標準の CPython の配布物の他に、追加の機能を持っている修正されたパッケージがあります。以下は人気のあるバージョンとそのキーとなる機能です:


@table @asis

@item ActivePython@footnote{https://www.activestate.com/products/python/}

マルチプラットフォーム互換のインストーラー、ドキュメント、 PyWin32

@item Anaconda@footnote{https://www.anaconda.com/download/}

人気のある (numpy, scipy や pandas のような) 科学系モジュールと、パッケージマネージャ @code{conda} 。

@item Enthought Deployment Manager@footnote{https://assets.enthought.com/downloads/edm/}

"次世代の Python 環境とパッケージマネージャー" ("The Next Generation Python Environment and Package Manager")。

以前は Enthought が Canopy を提供していましたが、これは 2016 年にサポートが終了しました@footnote{https://support.enthought.com/hc/en-us/articles/360038600051-Canopy-GUI-end-of-life-transition-to-the-Enthought-Deployment-Manager-EDM-and-Visual-Studio-Code}。

@item WinPython@footnote{https://winpython.github.io/}

ビルド済みの科学系パッケージと、パッケージのビルドのためのツールを含む、Windows 固有のディストリビューション。
@end table

これらパッケージは Python や他のライブラリの最新バージョンが含まれるとは限りませんし、コア Python チームはこれらを保守もしませんしサポートもしませんのでご理解ください。

@node Supported Windows versions,Removing the MAX_PATH limitation,別のバンドル,Windows で Python を使う
@anchor{using/windows supported-windows-versions}@anchor{221a}
@subsection Supported Windows versions


As specified in 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/}, a Python release only supports a Windows platform
while Microsoft considers the platform under extended support. This means that
Python 3.14 supports Windows 10 and newer. If you require Windows 7
support, please install Python 3.8. If you require Windows 8.1 support,
please install Python 3.12.

@node Removing the MAX_PATH limitation,UTF-8 モード,Supported Windows versions,Windows で Python を使う
@anchor{using/windows max-path}@anchor{e3b}@anchor{using/windows removing-the-max-path-limitation}@anchor{221b}
@subsection Removing the MAX_PATH limitation


Windows は歴史的にパスの長さが 260 文字に制限されています。
つまり、これより長いパスは解決できず結果としてエラーになるということです。

In the latest versions of Windows, this limitation can be expanded to over
32,000 characters. Your administrator will need to activate the "Enable Win32
long paths" group policy, or set @code{LongPathsEnabled} to @code{1} in the registry
key @code{HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem}.

これにより、 @ref{316,,open()} 関数や @ref{a5,,os} モジュール、他のほとんどのパスの機能が 260 文字より長いパスを受け入れ、返すことができるようになります。

After changing the above option and rebooting, no further configuration is
required.

@node UTF-8 モード,モジュールの検索,Removing the MAX_PATH limitation,Windows で Python を使う
@anchor{using/windows utf-8-mode}@anchor{221c}@anchor{using/windows win-utf8-mode}@anchor{221d}
@subsection UTF-8 モード



Added in version 3.7.


Windows still uses legacy encodings for the system encoding (the ANSI Code
Page).  Python uses it for the default encoding of text files (e.g.
@ref{329,,locale.getencoding()}).

This may cause issues because UTF-8 is widely used on the internet
and most Unix systems, including WSL (Windows Subsystem for Linux).

You can use the @ref{866,,Python UTF-8 Mode} to change the default text
encoding to UTF-8. You can enable the @ref{866,,Python UTF-8 Mode} via
the @code{-X utf8} command line option, or the @code{PYTHONUTF8=1} environment
variable.  See 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8} for enabling UTF-8 mode, and
@ref{1fca,,Python install manager} for how to modify environment variables.

When the @ref{866,,Python UTF-8 Mode} is enabled, you can still use the
system encoding (the ANSI Code Page) via the "mbcs" codec.

Note that adding @code{PYTHONUTF8=1} to the default environment variables
will affect all Python 3.7+ applications on your system.
If you have any Python 3.7+ applications which rely on the legacy
system encoding, it is recommended to set the environment variable
temporarily or use the @code{-X utf8} command line option.

@cartouche
@quotation 注釈 
Even when UTF-8 mode is disabled, Python uses UTF-8 by default
on Windows for:


@itemize *

@item 
Console I/O including standard I/O (see 
@geindex Python Enhancement Proposals; PEP 528
PEP 528@footnote{https://peps.python.org/pep-0528/} for details).

@item 
The @ref{75d,,filesystem encoding}
(see 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} for details).
@end itemize
@end quotation
@end cartouche

@node モジュールの検索,追加のモジュール,UTF-8 モード,Windows で Python を使う
@anchor{using/windows finding-modules}@anchor{221e}@anchor{using/windows windows-finding-modules}@anchor{e1a}
@subsection モジュールの検索


These notes supplement the description at @ref{18dc,,sys.path モジュール検索パスの初期化} with
detailed Windows notes.

@code{._pth} ファイルが見付からなかったときは、 Windows では @ref{3e4,,sys.path} は次のように設定されます:


@itemize *

@item 
最初に空のエントリが追加されます。これはカレントディレクトリを指しています。

@item 
その次に、 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} 環境変数が存在するとき、 @ref{807,,環境変数} で解説されているように追加されます。 Windows ではドライブ識別子 (@code{C:\} など)と区別するために、この環境変数に含まれるパスの区切り文字はセミコロンでなければならない事に注意してください。

@item 
追加で "アプリケーションのパス" を @code{HKEY_CURRENT_USER} か @code{HKEY_LOCAL_MACHINE} の中の @code{\SOFTWARE\Python\PythonCore@{version@}\PythonPath} のサブキーとして登録することができます。サブキーはデフォルト値としてセミコロンで区切られたパス文字列を持つことができ、書くパスが @ref{3e4,,sys.path} に追加されます。 (既存のインストーラーはすべて HKLM しか利用しないので、 HKCU は通常空です)

@item 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} が設定されている場合、それが "Python Home" として扱われます。
それ以外の場合、 "Python Home" を推定するために Python の実行ファイルのパスから "目印ファイル" (@code{Lib\os.py} または @code{pythonXY.zip}) が探されます。
Python home が見つかった場合、そこからいくつかのサブディレクトリ (@code{Lib}, @code{plat-win} など) が @ref{3e4,,sys.path} に追加されます。
見つからなかった場合、コアとなる Python path はレジストリに登録された PythonPath から構築されます。

@item 
Python Home が見つからず、環境変数 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} が指定されず、レジストリエントリが見つからなかった場合、関連するデフォルトのパスが利用されます (例: @code{.\Lib;.\plat-win} など)。
@end itemize

メインの実行ファイルと同じ場所か一つ上のディレクトリに @code{pyvenv.cfg} がある場合、以下の異なった規則が適用されます:


@itemize *

@item 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} が設定されておらず、 @code{home} が絶対パスの場合、home 推定の際メインの実行ファイルから推定するのではなくこのパスを使います。
@end itemize

結果としてこうなります:


@itemize *

@item 
@code{python.exe} かそれ以外の Python ディレクトリにある .exe ファイルを実行したとき (インストールされている場合でも PCbuild から直接実行されている場合でも) core path が利用され、レジストリ内の core path は無視されます。それ以外のレジストリの "application paths" は常に読み込まれます。

@item 
Python が他の .exe ファイル (他のディレクトリに存在する場合や、COM経由で組み込まれる場合など) にホストされている場合は、 "Python Home" は推定されず、レジストリにある core path が利用されます。それ以外のレジストリの "application paths" は常に読み込まれます。

@item 
Python がその home を見つけられず、レジストリの値もない場合 (これはいくつかのとてもおかしなインストレーションセットアップの凍結された .exe)、パスは最小限のデフォルトとして相対パスが使われます。
@end itemize

自身のアプリケーションや配布物に Python をバンドルしたい場合には、以下の助言 (のいずれかまたは組合せ) によりほかのインストレーションとの衝突を避けることができます:


@itemize *

@item 
Include a @code{._pth} file alongside your executable containing the
directories to include. This will ignore paths listed in the registry and
environment variables, and also ignore @ref{cc,,site} unless @code{import site} is
listed.

@item 
If you are loading @code{python3.dll} or @code{python37.dll} in your own
executable, explicitly set @ref{643,,PyConfig.module_search_paths} before
@ref{3f6,,Py_InitializeFromConfig()}.

@item 
自身のアプリケーションから @code{python.exe} を起動する前に、 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} をクリアしたり上書きし、 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} をセットしてください。

@item 
If you cannot use the previous suggestions (for example, you are a
distribution that allows people to run @code{python.exe} directly), ensure
that the landmark file (@code{Lib\os.py}) exists in your install directory.
(Note that it will not be detected inside a ZIP file, but a correctly named
ZIP file will be detected instead.)
@end itemize

これらはシステムワイドにインストールされたファイルが、あなたのアプリケーションにバンドルされた標準ライブラリのコピーに優先しないようにします。これをしなければあなたのアプリケーションのユーザは、何かしら問題を抱えるかもしれません。上で列挙した最初の提案が最善です。ほかのものはレジストリ内の非標準のパスやユーザの site-packages の影響を少し受けやすいからです。


バージョン 3.6 で変更: Add @code{._pth} file support and removes @code{applocal} option from
@code{pyvenv.cfg}.



バージョン 3.6 で変更: Add @code{python`XX'.zip} as a potential landmark when directly adjacent
to the executable.



バージョン 3.6 で非推奨: Modules specified in the registry under @code{Modules} (not @code{PythonPath})
may be imported by @ref{f26,,importlib.machinery.WindowsRegistryFinder}.
This finder is enabled on Windows in 3.6.0 and earlier, but may need to
be explicitly added to @ref{f27,,sys.meta_path} in the future.


@node 追加のモジュール,Windows 上で Python をコンパイルする,モジュールの検索,Windows で Python を使う
@anchor{using/windows additional-modules}@anchor{221f}
@subsection 追加のモジュール


Python は全プラットフォーム互換を目指していますが、 Windows にしかないユニークな機能もあります。標準ライブラリと外部のライブラリの両方で、幾つかのモジュールと、そういった機能を使うためのスニペットがあります。

Windows 固有の標準モジュールは、 @ref{2220,,MS Windows 固有のサービス} に書かれています。

@menu
* PyWin32:: 
* cx_Freeze:: 

@end menu

@node PyWin32,cx_Freeze,,追加のモジュール
@anchor{using/windows pywin32}@anchor{2221}
@subsubsection PyWin32


The PyWin32@footnote{https://pypi.org/project/PyWin32/} module by Mark Hammond
is a collection of modules for advanced Windows-specific support.  This includes
utilities for:


@itemize *

@item 
Component Object Model@footnote{https://learn.microsoft.com/windows/win32/com/component-object-model--com--portal}
(COM)

@item 
Win32 API 呼び出し

@item 
レジストリ

@item 
イベントログ

@item 
Microsoft Foundation Classes@footnote{https://learn.microsoft.com/cpp/mfc/mfc-desktop-applications}
(MFC) user interfaces
@end itemize

PythonWin@footnote{https://web.archive.org/web/20060524042422/https://www.python.org/windows/pythonwin/} は PyWin32 に付属している、サンプルのMFCアプリケーションです。これはビルトインのデバッガを含む、組み込み可能なIDEです。


@subsubheading 参考



@table @asis

@item Win32 How Do I...?@footnote{https://timgolden.me.uk/python/win32_how_do_i.html}

by Tim Golden

@item Python and COM@footnote{https://www.boddie.org.uk/python/COM.html}

by David and Paul Boddie
@end table


@node cx_Freeze,,PyWin32,追加のモジュール
@anchor{using/windows cx-freeze}@anchor{2222}
@subsubsection cx_Freeze


cx_Freeze@footnote{https://cx-freeze.readthedocs.io/en/latest/}
wraps Python scripts into executable Windows programs
(@code{`*'.exe} files).  When you have done this, you can distribute your
application without requiring your users to install Python.

@node Windows 上で Python をコンパイルする,The full installer deprecated,追加のモジュール,Windows で Python を使う
@anchor{using/windows compiling-python-on-windows}@anchor{2223}
@subsection Windows 上で Python をコンパイルする


CPython を自分でコンパイルしたい場合、最初にすべきことは ソース@footnote{https://www.python.org/downloads/source/} を取得することです。最新リリース版のソースか、新しい チェックアウト@footnote{https://devguide.python.org/setup/#get-the-source-code} をダウンロードできます。

ソースツリーには Microsoft Visual Studio でのビルドのソリューションファイルとプロジェクトファイルが含まれていて、これが公式の Python リリースに使われているコンパイラです。これらファイルは @code{PCbuild} ディレクトリ内にあります。

ビルドプロセスについての一般的な情報は、@code{PCbuild/readme.txt} にあります。

拡張モジュールについては、 @ref{2224,,Windows 上での C および C++ 拡張モジュールのビルド} を参照してください。

@node The full installer deprecated,Python launcher for Windows deprecated,Windows 上で Python をコンパイルする,Windows で Python を使う
@anchor{using/windows the-full-installer-deprecated}@anchor{2225}@anchor{using/windows windows-full}@anchor{2226}
@subsection The full installer (deprecated)



バージョン 3.14 で非推奨: This installer is deprecated since 3.14 and will not be produced for Python
3.16 or later. See @ref{21fe,,Python install manager} for the modern installer.


@menu
* インストール手順:: 
* Removing the MAX_PATH limitation: Removing the MAX_PATH limitation<2>. 
* Installing without UI:: 
* Installing without downloading:: 
* インストール後の変更:: 
* Installing free-threaded binaries: Installing free-threaded binaries<2>. 

@end menu

@node インストール手順,Removing the MAX_PATH limitation<2>,,The full installer deprecated
@anchor{using/windows installation-steps}@anchor{2227}
@subsubsection インストール手順


ダウンロードできる Python 3.14 のインストーラは 4 つあります。
インタプリタの 32 ビット版、64 ビット版がそれぞれ 2 つずつあります。
`WEB インストーラ' は最初のダウンロードサイズは小さく、必要なコンポーネントはインストーラ実行時に必要に応じて自動的にダウンロードします。
`オフラインインストーラ' にはデフォルトインストールに必要なコンポーネントが含まれていて、インターネット接続はオプショナルな機能のためにだけに必要となります。
インストール時にダウンロードを避けるほかの方法については @ref{2228,,Installing without downloading} を参照して下さい。

インストーラを開始すると、2つの選択肢からひとつを選べます:

@image{python-figures/win_installer,,,,png}

"Install Now" を選択した場合:


@itemize *

@item 
管理者権限は `不要です' (ただし C ランタイムライブラリのシステム更新が必要であったり、 @ref{7da,,Python install manager} をすべてのユーザ向けにインストールする場合は必要です)。

@item 
Python はあなたのユーザディレクトリにインストールされます。

@item 
@ref{7da,,Python install manager} はこのインストールウィザード最初のページの下部のチェックボックス指定に従ってインストールされます。

@item 
標準ライブラリ、テストスイート、ランチャ、pip がインストールされます。

@item 
このインストールウィザード最初の下部のチェックボックスをチェックすれば、環境変数 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} にインストールディレクトリが追加されます。

@item 
ショートカットはカレントユーザだけに可視になります。
@end itemize

"Customize installation" を選択すると、インストール場所、その他オプションやインストール後のアクションの変更などのインストールの有りようを選べます。デバッグシンボルやデバッグバイナリをインストールするならこちらを選択する必要があるでしょう。

すべてのユーザのためのインストールのためには "Customize installation" を選んでください。この場合:


@itemize *

@item 
管理者資格か承認が必要かもしれません。

@item 
Python は Program Files ディレクトリにインストールされます。

@item 
@ref{7da,,Python install manager} は Windows ディレクトリにインストールされます。

@item 
オプショナルな機能はインストール中に選択できます。

@item 
標準ライブラリをバイトコードにプリコンパイルできます。

@item 
そう選択すれば、インストールディレクトリはシステム環境変数 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} に追加されます。

@item 
ショートカットがすべてのユーザで利用できるようになります。
@end itemize

@node Removing the MAX_PATH limitation<2>,Installing without UI,インストール手順,The full installer deprecated
@anchor{using/windows id2}@anchor{2229}
@subsubsection Removing the MAX_PATH limitation


Windows は歴史的にパスの長さが 260 文字に制限されています。
つまり、これより長いパスは解決できず結果としてエラーになるということです。

Windows の最新版では、この制限は約 32,000 文字まで拡張できます。
管理者が、グループポリシーの "Win32 の長いパスを有効にする (Enable Win32 long paths)" を有効にするか、レジストリキー @code{HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem} の @code{LongPathsEnabled} の値を @code{1} に設定する必要があります。

これにより、 @ref{316,,open()} 関数や @ref{a5,,os} モジュール、他のほとんどのパスの機能が 260 文字より長いパスを受け入れ、返すことができるようになります。

これらのオプションを変更したら、それ以上の設定は必要ありません。


バージョン 3.6 で変更: Python で長いパスのサポートが可能になりました。


@node Installing without UI,Installing without downloading,Removing the MAX_PATH limitation<2>,The full installer deprecated
@anchor{using/windows install-quiet-option}@anchor{804}@anchor{using/windows installing-without-ui}@anchor{222a}
@subsubsection Installing without UI


インストーラの GUI で利用できるすべてのオプションは、コマンドラインからも指定できます。これによりユーザとの対話なしで数多くの機器に同じインストールを行うような、スクリプト化されたインストールを行うことができます。ちょっとしたデフォルトの変更のために、GUI を抑制することなしにこれらコマンドラインオプションをセットすることもできます。

インストーラーには、以下のオプション (@code{/?} でインストーラを実行することで確認できます) を渡すことができます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名前

@tab

説明

@item

/passive

@tab

ユーザーの操作なしでも進捗を表示する

@item

/quiet

@tab

UI を表示せずにインストール・アンインストールする

@item

/simple

@tab

ユーザーによるカスタマイズができないようにする

@item

/uninstall

@tab

(確認無しで) Python を削除する

@item

/layout [ディレクトリ]

@tab

すべてのコンポーネントを事前にダウンロードする

@item

/log [ファイル名]

@tab

ログファイルの場所を指定する

@end multitable


ほかのすべてのオプションは @code{name=value} の形で渡します。value は大抵 @code{0} で機能を無効化、 @code{1} で機能を有効化、であるとかパスの指定です。利用可能なオプションの完全なリストは以下の通りです。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名前

@tab

説明

@tab

デフォルト

@item

InstallAllUsers

@tab

システムワイドなインストールを実行する。

@tab

0

@item

TargetDir

@tab

インストール先ディレクトリ。

@tab

InstallAllUsers に基いて選択されます。

@item

DefaultAllUsersTargetDir

@tab

すべてのユーザ向けインストールのためのデフォルトインストール先ディレクトリ。

@tab

@code{%ProgramFiles%\Python X.Y} または @code{%ProgramFiles(x86)%\Python X.Y}

@item

DefaultJustForMeTargetDir

@tab

自分一人用インストールのためのデフォルトインストール先ディレクトリ。

@tab

@code{%LocalAppData%\Programs\Python\PythonXY} または @code{%LocalAppData%\Programs\Python\PythonXY-32} または @code{%LocalAppData%\Programs\Python\PythonXY-64}

@item

DefaultCustomTargetDir

@tab

カスタムインストールディレクトリとしてデフォルトで GUI に表示される値。

@tab

(空)

@item

AssociateFiles

@tab

ランチャもインストールする場合に、ファイルの関連付けを行う。

@tab

1

@item

CompileAll

@tab

すべての @code{.py} ファイルをバイトコンパイルして @code{.pyc} を作る。

@tab

0

@item

PrependPath

@tab

@geindex PATH
@geindex 環境変数; PATH
@code{PATH} にインストールディレクトリと Scripts ディレクトリを先頭に追加し、 
@geindex PATHEXT
@geindex 環境変数; PATHEXT
@code{PATHEXT} に @code{.PY} を追加する。

@tab

0

@item

AppendPath

@tab

@geindex PATH
@geindex 環境変数; PATH
@code{PATH} にインストールディレクトリと Scripts ディレクトリを追加し、 
@geindex PATHEXT
@geindex 環境変数; PATHEXT
@code{PATHEXT} に @code{.PY} を追加する。

@tab

0

@item

Shortcuts

@tab

インストールするインタプリタ、ドキュメント、IDLE へのショートカットを作る。

@tab

1

@item

Include_doc

@tab

Python マニュアルをインストールする。

@tab

1

@item

Include_debug

@tab

デバッグバイナリをインストールする。

@tab

0

@item

Include_dev

@tab

開発者用ヘッダーとライブラリをインストールする。これを省略すると、使用不可能なインストールになる可能性があります。

@tab

1

@item

Include_exe

@tab

@code{python.exe} と関連するファイルをインストールする。これを省略すると、使用不可能なインストールになる可能性があります。

@tab

1

@item

Include_launcher

@tab

@ref{7da,,Python install manager} をインストールする。

@tab

1

@item

InstallLauncherAllUsers

@tab

すべてのユーザーにランチャーをインストールする。 @code{Include_launcher} が 1 に設定されている必要があります。

@tab

1

@item

Include_lib

@tab

標準ライブラリと拡張モジュールをインストールする。これを省略すると、使用不可能なインストールになる可能性があります。

@tab

1

@item

Include_pip

@tab

バンドル版の pip と setuptools をインストールする。

@tab

1

@item

Include_symbols

@tab

デバッグシンボル (@code{*.pdb}) をインストールする。

@tab

0

@item

Include_tcltk

@tab

Tcl/Tk サポートと IDLE をインストールする。

@tab

1

@item

Include_test

@tab

標準ライブラリのテストスイートをインストールする。

@tab

1

@item

Include_tools

@tab

ユーティリティスクリプトをインストールする。

@tab

1

@item

LauncherOnly

@tab

ランチャのみをインストールする。これは他のほとんどのオプションを上書きします。

@tab

0

@item

SimpleInstall

@tab

最大限のインストーラ GUI を無効にする。

@tab

0

@item

SimpleInstallDescription

@tab

単純化されたインストーラ GUI を使う際に表示するカスタムメッセージ。

@tab

(空)

@end multitable


例えばデフォルトでシステムワイドな Python インストレーションを静かに行うには、以下コマンドを使えます (コマンドプロンプトより):

@example
python-3.9.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
@end example

テストスイートなしの Python のパーソナルなコピーのインストールをユーザに簡単に行わせるには、以下コマンドのショートカットを作れば良いです。これはインストーラの最初のページを単純化して表示し、また、カスタマイズできないようにします:

@example
python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
    SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite."
@end example

(ランチャのインストールを省略するとファイルの関連付けも省略されるので、これはランチャインストールを含めたシステムワイドなインストールをした場合のユーザごとインストールに限った場合のお勧めです。)

上でリストしたオプションは、実行ファイルと同じ場所の @code{unattend.xml} と名付けられたファイルで与えることもできます。このファイルはオプションとその値のリストを指定します。値がアトリビュートとして与えられた場合、それは数値であれば数値に変換されます。エレメントテキストで与える場合は常に文字列のままです。以下は、先の例と同じオプションをセットするファイルの実例です:

@example
<Options>
    <Option Name="InstallAllUsers" Value="no" />
    <Option Name="Include_launcher" Value="0" />
    <Option Name="Include_test" Value="no" />
    <Option Name="SimpleInstall" Value="yes" />
    <Option Name="SimpleInstallDescription">Just for me, no test suite</Option>
</Options>
@end example

@node Installing without downloading,インストール後の変更,Installing without UI,The full installer deprecated
@anchor{using/windows install-layout-option}@anchor{2228}@anchor{using/windows installing-without-downloading}@anchor{222b}
@subsubsection Installing without downloading


Python のいくつかの機能は最初にダウンロードしたインストーラには含まれていないため、それらの機能をインストールしようと選択するとインターネット接続が必要になります。
インターネット接続が必要にならないように、全てのコンポーネントをすぐにできる限りダウンロードして、完全な `配置構成 (layout)' を作成し、どんな機能が選択されたかに関わらず、それ以上インターネット接続を必要がないようにします。
この方法のダウンロードサイズは必要以上に大きくなるかもしれませんが、たくさんの回数インストールしようとする場合には、ローカルにキャッシュされたコピーを持つことはとても有用です。

コマンドプロンプトから以下のコマンドを実行して、必要なファイルをできる限り全てダウンロードします。
@code{python-3.9.0.exe} 部分は実際のインストーラの名前に置き換え、同名のファイルどうしの衝突が起こらないように、個別のディレクトリ内に配置構成を作るのを忘れないようにしてください。

@example
python-3.9.0.exe /layout [optional target directory]
@end example

進捗表示を隠すのに @code{/quiet} オプションを指定することもできます。

@node インストール後の変更,Installing free-threaded binaries<2>,Installing without downloading,The full installer deprecated
@anchor{using/windows modifying-an-install}@anchor{222c}
@subsubsection インストール後の変更


いったん Python がインストールされたら、Windows のシステム機能の「プログラムと機能」ツールから機能の追加や削除ができます。Python のエントリを選択して「アンインストールと変更」を選ぶことで、インストーラをメンテナンスモードで開きます。

インストーラ GUI で "Modify" を選ぶと、チェックボックスの選択を変えることで機能の追加削除ができます - チェックボックスの選択を変えなければ、何かがインストールされたり削除されたりはしません。いくつかのオプションはこのモードでは変更することはできません。インストールディレクトリなどです。それらを変えたいのであれば、完全に削除してから再インストールする必要があります。

"Repair" では、現在の設定で本来インストールされるべきすべてのファイルを検証し、削除されていたり更新されていたりするファイルを修正します。

"Uninstall" は Python を完全に削除します。「プログラムと機能」内の自身のエントリを持つ @ref{7da,,Python install manager} の例外が起こります。

@node Installing free-threaded binaries<2>,,インストール後の変更,The full installer deprecated
@anchor{using/windows id3}@anchor{222d}
@subsubsection Installing free-threaded binaries



Added in version 3.13.


To install pre-built binaries with free-threading enabled (see 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}), you
should select "Customize installation". The second page of options includes the
"Download free-threaded binaries" checkbox.

@image{python-figures/win_install_freethreaded,,,,png}

Selecting this option will download and install additional binaries to the same
location as the main Python install. The main executable is called
@code{python3.13t.exe}, and other binaries either receive a @code{t} suffix or a full
ABI suffix. Python source files and bundled third-party dependencies are shared
with the main install.

The free-threaded version is registered as a regular Python install with the
tag @code{3.13t} (with a @code{-32} or @code{-arm64} suffix as normal for those
platforms). This allows tools to discover it, and for the @ref{7da,,Python install manager} to
support @code{py.exe -3.13t}. Note that the launcher will interpret @code{py.exe -3}
(or a @code{python3} shebang) as "the latest 3.x install", which will prefer the
free-threaded binaries over the regular ones, while @code{py.exe -3.13} will not.
If you use the short style of option, you may prefer to not install the
free-threaded binaries at this time.

To specify the install option at the command line, use
@code{Include_freethreaded=1}. See @ref{2228,,Installing without downloading} for instructions on
pre-emptively downloading the additional binaries for offline install. The
options to include debug symbols and binaries also apply to the free-threaded
builds.

Free-threaded binaries are also available @ref{21fc,,on nuget.org}.

@node Python launcher for Windows deprecated,,The full installer deprecated,Windows で Python を使う
@anchor{using/windows python-launcher-for-windows-deprecated}@anchor{222e}
@subsection Python launcher for Windows (deprecated)



バージョン 3.14 で非推奨: The launcher and this documentation have been superseded by the Python
Install Manager described above. This is preserved temporarily for historical
interest.



Added in version 3.3.


Windows の Python ランチャは、異なる Python のバージョンの位置の特定と実行を助けるユーティリティです。スクリプト (またはコマンドライン) で特定の Python のバージョンの設定を与えられると、位置を特定し、そのバージョンを実行します。

環境変数 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} による方法と違って、このランチャは Python の一番適切なバージョンを、正しく選択します。このランチャはシステムワイドなものよりもユーザごとのインストレーションの方を優先し、また、新しくインストールされた順よりも言語のバージョンを優先します。

ランチャのオリジナルの仕様は 
@geindex Python Enhancement Proposals; PEP 397
PEP 397@footnote{https://peps.python.org/pep-0397/} にあります。

@menu
* 最初に:: 
* Shebang lines: Shebang lines<2>. 
* シェバン行の引数:: 
* カスタマイズ:: 
* 診断:: 
* Dry run:: 
* Install on demand:: 
* Return codes:: 

@end menu

@node 最初に,Shebang lines<2>,,Python launcher for Windows deprecated
@anchor{using/windows getting-started}@anchor{222f}
@subsubsection 最初に


@menu
* コマンドラインから起動する:: 
* 仮想環境 (Virtual environments): 仮想環境 Virtual environments. 
* スクリプトから起動する:: 
* ファイルの関連付けから起動する:: 

@end menu

@node コマンドラインから起動する,仮想環境 Virtual environments,,最初に
@anchor{using/windows from-the-command-line}@anchor{2230}
@subsubsection コマンドラインから起動する



バージョン 3.6 で変更.


Python 3.3 とそれ以降のシステムワイドなインストールでは、ランチャーが 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} に追加されます。ランチャーは、入手可能なあらゆる Python のバージョンに互換性があるため、実際にどのバージョンの Python がインストールされているのかは重要ではありません。ランチャーが使えるかを確認するには以下のコマンドをコマンドプロンプトで実行してください:

@example
py
@end example

インストールされている最新バージョンの Python が起動するはずです。
通常どおりに終了することもできますし、追加のコマンドライン引数を指定して直接 Python に渡すこともできます。

複数のバージョンの Python (たとえば 3.7 と 3.14) がインストールされている場合は、Python 3.14 が起動することになります。Python 3.7 を起動したいなら、次のコマンドを実行してみてください:

@example
py -3.7
@end example

インストールしてある Python 2 の最新バージョンを起動したい場合は、次のコマンドを実行してみてください:

@example
py -2
@end example

以下のようなエラーが出るようであれば、ランチャはインストールされていません:

@example
'py' is not recognized as an internal or external command,
operable program or batch file.
@end example

このコマンド:

@example
py --list
@end example

これは、現在インストールされている Python のバージョンを表示します。

The @code{-x.y} argument is the short form of the @code{-V:Company/Tag} argument,
which allows selecting a specific Python runtime, including those that may have
come from somewhere other than python.org. Any runtime registered by following
@geindex Python Enhancement Proposals; PEP 514
PEP 514@footnote{https://peps.python.org/pep-0514/} will be discoverable. The @code{--list} command lists all available
runtimes using the @code{-V:} format.

When using the @code{-V:} argument, specifying the Company will limit selection to
runtimes from that provider, while specifying only the Tag will select from all
providers. Note that omitting the slash implies a tag:

@example
# Select any '3.*' tagged runtime
py -V:3

# Select any 'PythonCore' released runtime
py -V:PythonCore/

# Select PythonCore's latest Python 3 runtime
py -V:PythonCore/3
@end example

The short form of the argument (@code{-3}) only ever selects from core Python
releases, and not other distributions. However, the longer form (@code{-V:3}) will
select from any.

The Company is matched on the full string, case-insensitive. The Tag is matched
on either the full string, or a prefix, provided the next character is a dot or a
hyphen. This allows @code{-V:3.1} to match @code{3.1-32}, but not @code{3.10}. Tags are
sorted using numerical ordering (@code{3.10} is newer than @code{3.1}), but are
compared using text (@code{-V:3.01} does not match @code{3.1}).

@node 仮想環境 Virtual environments,スクリプトから起動する,コマンドラインから起動する,最初に
@anchor{using/windows virtual-environments}@anchor{2231}
@subsubsection 仮想環境 (Virtual environments)



Added in version 3.5.


(標準ライブラリの @ref{117,,venv} モジュールか外部ツール @code{virtualenv} で作った) 仮想環境がアクティブな状態で Python の明示的なバージョンを指定せずにランチャを起動すると、ランチャはグローバルなインタプリタではなくその仮想環境のものを実行します。グローバルなほうのインタプリタを実行するには、仮想環境の動作を停止するか、または明示的にグローバルな Python バージョンを指定してください。

@node スクリプトから起動する,ファイルの関連付けから起動する,仮想環境 Virtual environments,最初に
@anchor{using/windows from-a-script}@anchor{2232}
@subsubsection スクリプトから起動する


テスト用の Python スクリプトを作成しましょう。@code{hello.py} という名前で以下の内容のファイルを作成してください

@example
#! python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))
@end example

hello.py が存在するディレクトリで、下記コマンドを実行してください:

@example
py hello.py
@end example

インストールされている最新の Python 2.x のバージョン番号が表示されるはずです。では、1行目を以下のように変更してみてください:

@example
#! python3
@end example

コマンドを再実行すると、今度は最新の Python 3.x の情報が表示されるはずです。これまでのコマンドラインの例と同様に、より細かいバージョン修飾子を指定することもできます。Python 3.7 がインストールされている場合、最初の行を @code{#! python3.7} に変更すると、3.7 のバージョン情報が表示されるはずです。

コマンドからの呼び出しとは異なり、後ろに何もつかない "python" はインストールされている Python2.x の最新バージョンを利用することに注意してください。これは後方互換性と、 @code{python} が一般的に Python 2 を指すUnix との互換性のためです。

@node ファイルの関連付けから起動する,,スクリプトから起動する,最初に
@anchor{using/windows from-file-associations}@anchor{2233}
@subsubsection ファイルの関連付けから起動する


インストール時に、ランチャは Python ファイル (すなわち @code{.py}, @code{.pyw}, @code{.pyc} ファイル) に関連付けられたはずです。そのため、これらのファイルを Windows のエクスプローラーでダブルクリックした際はランチャが使われ、上で述べたのと同じ機能を使ってスクリプトが使われるべきバージョンを指定できるようになります。

このことによる重要な利点は、単一のランチャが先頭行の内容によって複数の Python バージョンを同時にサポートできることです。

@node Shebang lines<2>,シェバン行の引数,最初に,Python launcher for Windows deprecated
@anchor{using/windows id4}@anchor{2234}
@subsubsection Shebang lines


スクリプトファイルの先頭の行が @code{#!} で始まっている場合は、その行はシェバン (shebang) 行として知られています。
Linux や他の Unix 系 OS はこうした行をもともとサポートしているため、それらのシステムでは、スクリプトがどのように実行されるかを示すために広く使われます。
Windows の Python ランチャは、Windows 上の Python スクリプトが同じ機能を使用できるようにし、上の例ではそれらの機能の使用法を示しています。

Python スクリプトのシェバン行を Unix-Windows 間で移植可能にするため、このランチャは、どのインタプリタが使われるかを指定するための大量の '仮想' コマンドをサポートしています。サポートされる仮想コマンドには以下のものがあります:


@itemize *

@item 
@code{/usr/bin/env}

@item 
@code{/usr/bin/python}

@item 
@code{/usr/local/bin/python}

@item 
@code{python}
@end itemize

具体的に、もしスクリプトの1行目が

@example
#! /usr/bin/python
@end example

で始まっていたら、デフォルトの Python またはアクティブな仮想環境の位置が特定され、使用されます。多くの Unix 上で動作する Python スクリプトにはすでにこの行が存在する傾向がありますので、ランチャによりそれらのスクリプトを修正なしで使うことができるはずです。あなたが新しいスクリプトを Windows 上で書いていて、Unix 上でも有用であってほしいと思うなら、シェバン行のうち @code{/usr} で始まるものを使用すべきです。

上記のどの仮想コマンドでも、(メジャーバージョンだけや、メジャー・マイナーバージョンの両方で) 明示的にバージョンを指定できます。
さらに、 "-32" をマイナーバージョンの後ろに追加して 32-bit 版を要求できます。
例えば、 @code{/usr/bin/python3.7-32} は 32-bit の Python 3.7 を使うよう要求します。仮想環境がアクティブになっている場合は、バージョンは無視され、その環境が使用されます。


Added in version 3.7: python ランチャの 3.7 からは、末尾に "-64" を付けて 64-bit 版を要求できます。
さらに、マイナーバージョン無しのメジャーバージョンとアーキテクチャだけ (例えば、 @code{/usr/bin/python3-64}) で指定できます。



バージョン 3.11 で変更: The "-64" suffix is deprecated, and now implies "any architecture that is
not provably i386/32-bit". To request a specific environment, use the new
@code{-V:@var{TAG}} argument with the complete tag.



バージョン 3.13 で変更: Virtual commands referencing @code{python} now prefer an active virtual
environment rather than searching 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}. This handles cases where
the shebang specifies @code{/usr/bin/env python3} but @code{python3.exe} is
not present in the active environment.


The @code{/usr/bin/env} form of shebang line has one further special property.
Before looking for installed Python interpreters, this form will search the
executable 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} for a Python executable matching the name provided
as the first argument. This corresponds to the behaviour of the Unix @code{env}
program, which performs a 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} search.
If an executable matching the first argument after the @code{env} command cannot
be found, but the argument starts with @code{python}, it will be handled as
described for the other virtual commands.
The environment variable @code{PYLAUNCHER_NO_SEARCH_PATH} may be set
(to any value) to skip this search of 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}.

Shebang lines that do not match any of these patterns are looked up in the
@code{[commands]} section of the launcher's @ref{2235,,.INI file}.
This may be used to handle certain commands in a way that makes sense for your
system. The name of the command must be a single argument (no spaces in the
shebang executable), and the value substituted is the full path to the
executable (additional arguments specified in the .INI will be quoted as part
of the filename).

@example
[commands]
/bin/xpython=C:\Program Files\XPython\python.exe
@end example

Any commands not found in the .INI file are treated as `Windows' executable
paths that are absolute or relative to the directory containing the script file.
This is a convenience for Windows-only scripts, such as those generated by an
installer, since the behavior is not compatible with Unix-style shells.
These paths may be quoted, and may include multiple arguments, after which the
path to the script and any additional arguments will be appended.

@node シェバン行の引数,カスタマイズ,Shebang lines<2>,Python launcher for Windows deprecated
@anchor{using/windows arguments-in-shebang-lines}@anchor{2236}
@subsubsection シェバン行の引数


シェバン行では Python インタプリタに渡される追加の引数を指定することもできます。たとえば、シェバン行に以下のように書かれているとしましょう:

@example
#! /usr/bin/python -v
@end example

この場合、Python は @code{-v} オプション付きで起動するでしょう

@node カスタマイズ,診断,シェバン行の引数,Python launcher for Windows deprecated
@anchor{using/windows customization}@anchor{2237}
@subsubsection カスタマイズ


@menu
* INI ファイルによるカスタマイズ:: 
* デフォルトのPythonバージョンのカスタマイズ:: 

@end menu

@node INI ファイルによるカスタマイズ,デフォルトのPythonバージョンのカスタマイズ,,カスタマイズ
@anchor{using/windows customization-via-ini-files}@anchor{2238}@anchor{using/windows launcher-ini}@anchor{2235}
@subsubsection INI ファイルによるカスタマイズ


ランチャは2つの .ini ファイルを探しに行きます。具体的には、現在のユーザーのアプリケーションデータディレクトリ (@code{%LOCALAPPDATA%} または @code{$env:LocalAppData}) の @code{py.ini} と、ランチャと同じディレクトリにある @code{py.ini} です。'コンソール' 版のランチャ (つまり py.exe) と 'Windows' 版のランチャ (つまり pyw.exe) は同一の .ini ファイルを使用します。

"application data" ディレクトリで指定された設定は、実行ファイルの隣にあるものより優先されます。そのため、ランチャの隣にある .ini ファイルへの書き込みアクセスができないユーザは、グローバルな .ini ファイル内のコマンドを上書き (override) できます。

@node デフォルトのPythonバージョンのカスタマイズ,,INI ファイルによるカスタマイズ,カスタマイズ
@anchor{using/windows customizing-default-python-versions}@anchor{2239}
@subsubsection デフォルトのPythonバージョンのカスタマイズ


どのバージョンの Python をコマンドで使用するかを定めるため、バージョン修飾子がコマンドに含められることがあります。
バージョン修飾子はメジャーバージョン番号で始まり、オプションのピリオド ('.') とマイナーバージョン指定子がそれに続きます。
さらに、 "-32" や "-64" を追記して 32-bit あるいは 64-bit のどちらの実装が要求されるかを指示できます。

たとえば、@code{#!python} というシェバン行はバージョン修飾子を含みませんが、@code{#!python3} はメジャーバージョンを指定するバージョン修飾子を含みます。

If no version qualifiers are found in a command, the environment
variable @code{PY_PYTHON} can be set to specify the default version
qualifier. If it is not set, the default is "3". The variable can
specify any value that may be passed on the command line, such as "3",
"3.7", "3.7-32" or "3.7-64". (Note that the "-64" option is only
available with the launcher included with Python 3.7 or newer.)

マイナーバージョン修飾子が見つからない場合、環境変数 @code{PY_PYTHON@{major@}} (ここで @code{@{major@}} は、上記で決定された現在のメジャーバージョン修飾子) を設定して完全なバージョンを指定することができます。そういったオプションが見つからなければ、ランチャはインストール済みの Python バージョンを列挙して、見つかったそのメジャーバージョン向けマイナーリリースのうち最新のものを使用します。保証されているわけではありませんが、通常はそのメジャーバージョン系で最も後にインストールしたバージョンになります。

64-bit Windows で、同一の (major.minor) Python バージョンの 32-bit と 64-bit の両方の実装がインストールされていた場合、64-bit バージョンのほうが常に優先されます。これはランチャが 32-bit と 64-bit のどちらでも言えることで、32-bit のランチャは、指定されたバージョンが使用可能であれば、64-bit の Python を優先して実行します。これは、どのバージョンが PC にインストールされているかのみでランチャの挙動を予見でき、それらがインストールされた順番に関係なくなる (つまり最後にインストールされた Python とランチャが 32-bit か 64-bit かを知らなくともよい) ようにするためです。上に記したとおり、オプションの "-32", "-64" サフィックスでこの挙動を変更できます。

例:


@itemize *

@item 
関連するオプションが設定されていない場合、@code{python} および @code{python2} コマンドはインストールされている最新の Python 2.x バージョンを使用し、@code{python3} コマンドはインストールされている最新の Python 3.x を使用します。

@item 
@code{python3.7} コマンドは、バージョンが完全に指定されているため、全くオプションを参照しません。

@item 
@code{PY_PYTHON=3} の場合、@code{python} および @code{python3} コマンドはともにインストールされている最新の Python 3 を使用します。

@item 
@code{PY_PYTHON=3.7-32} の場合、@code{python} コマンドは 32-bit 版の 3.7 を使用しますが、@code{python3} コマンドはインストールされている最新の Python を使用します (メジャーバージョンが指定されているため、PY_PYTHON は全く考慮されません。)

@item 
@code{PY_PYTHON=3} で @code{PY_PYTHON3=3.7} の場合、@code{python} および @code{python3} はどちらも 3.7 を使用します
@end itemize

環境変数に加え、同じ設定をランチャが使う INI ファイルで構成することができます。INI ファイルの該当するセクションは @code{[defaults]} と呼ばれ、キー名は環境変数のキー名から @code{PY_} という接頭辞を取ったものと同じです (INI ファイルのキー名は大文字小文字を区別しないことにご注意ください)。環境変数の内容は INI ファイルでの指定を上書きします。

例えば:


@itemize *

@item 
@code{PY_PYTHON=3.7} と設定することは、INI ファイルに下記が含まれることと等価です:
@end itemize

@example
[defaults]
python=3.7
@end example


@itemize *

@item 
@code{PY_PYTHON=3} と @code{PY_PYTHON3=3.7} を設定することは、INI ファイルに下記が含まれることと等価です:
@end itemize

@example
[defaults]
python=3
python3=3.7
@end example

@node 診断,Dry run,カスタマイズ,Python launcher for Windows deprecated
@anchor{using/windows diagnostics}@anchor{223a}
@subsubsection 診断


If an environment variable @code{PYLAUNCHER_DEBUG} is set (to any value), the
launcher will print diagnostic information to stderr (i.e. to the console).
While this information manages to be simultaneously verbose `and' terse, it
should allow you to see what versions of Python were located, why a
particular version was chosen and the exact command-line used to execute the
target Python. It is primarily intended for testing and debugging.

@node Dry run,Install on demand,診断,Python launcher for Windows deprecated
@anchor{using/windows dry-run}@anchor{223b}
@subsubsection Dry run


If an environment variable @code{PYLAUNCHER_DRYRUN} is set (to any value),
the launcher will output the command it would have run, but will not actually
launch Python. This may be useful for tools that want to use the launcher to
detect and then launch Python directly. Note that the command written to
standard output is always encoded using UTF-8, and may not render correctly in
the console.

@node Install on demand,Return codes,Dry run,Python launcher for Windows deprecated
@anchor{using/windows install-on-demand}@anchor{223c}
@subsubsection Install on demand


If an environment variable @code{PYLAUNCHER_ALLOW_INSTALL} is set (to any
value), and the requested Python version is not installed but is available on
the Microsoft Store, the launcher will attempt to install it. This may require
user interaction to complete, and you may need to run the command again.

An additional @code{PYLAUNCHER_ALWAYS_INSTALL} variable causes the launcher
to always try to install Python, even if it is detected. This is mainly intended
for testing (and should be used with @code{PYLAUNCHER_DRYRUN}).

@node Return codes,,Install on demand,Python launcher for Windows deprecated
@anchor{using/windows return-codes}@anchor{223d}
@subsubsection Return codes


The following exit codes may be returned by the Python launcher. Unfortunately,
there is no way to distinguish these from the exit code of Python itself.

The names of codes are as used in the sources, and are only for reference. There
is no way to access or resolve them apart from reading this page. Entries are
listed in alphabetical order of names.


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名前

@tab

値

@tab

説明

@item

RC_BAD_VENV_CFG

@tab

107

@tab

A @code{pyvenv.cfg} was found but is corrupt.

@item

RC_CREATE_PROCESS

@tab

101

@tab

Failed to launch Python.

@item

RC_INSTALLING

@tab

111

@tab

An install was started, but the command will
need to be re-run after it completes.

@item

RC_INTERNAL_ERROR

@tab

109

@tab

Unexpected error. Please report a bug.

@item

RC_NO_COMMANDLINE

@tab

108

@tab

Unable to obtain command line from the
operating system.

@item

RC_NO_PYTHON

@tab

103

@tab

Unable to locate the requested version.

@item

RC_NO_VENV_CFG

@tab

106

@tab

A @code{pyvenv.cfg} was required but not
found.

@end multitable


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node macOS で Python を使う,Android で Python を使う,Windows で Python を使う,Python のセットアップと利用
@anchor{using/mac doc}@anchor{223e}@anchor{using/mac translation-repo}@anchor{223f}@anchor{using/mac using-on-mac}@anchor{2240}@anchor{using/mac using-python-on-macos}@anchor{2241}
@section macOS で Python を使う


This document aims to give an overview of macOS-specific behavior you should
know about to get started with Python on Mac computers.
Python on a Mac running macOS is very similar to Python on other Unix-derived platforms,
but there are some differences in installation and some features.

There are various ways to obtain and install Python for macOS.
Pre-built versions of the most recent versions of Python are available
from a number of distributors. Much of this document describes use of
the Pythons provided by the CPython release team for download from
the python.org website@footnote{https://www.python.org/downloads/}. See
@ref{2242,,Alternative Distributions} for some other options.
@anchor{using/mac getting-osx}@anchor{2243}
@menu
* Using Python for macOS from python.org: Using Python for macOS from python org. 
* Alternative Distributions:: 
* 追加の Python パッケージのインストール:: 
* GUI プログラミング:: 
* 高度なトピック:: 
* 他のリソース:: 

@end menu

@node Using Python for macOS from python org,Alternative Distributions,,macOS で Python を使う
@anchor{using/mac getting-and-installing-macpython}@anchor{2244}@anchor{using/mac using-python-for-macos-from-python-org}@anchor{2245}
@subsection Using Python for macOS from @code{python.org}


@menu
* インストール手順: インストール手順<2>. 
* Python スクリプトの実行方法:: 

@end menu

@node インストール手順<2>,Python スクリプトの実行方法,,Using Python for macOS from python org
@anchor{using/mac installation-steps}@anchor{2246}
@subsubsection インストール手順


For current Python versions@footnote{https://www.python.org/downloads/}
(other than those in @code{security} status), the release team produces a
`Python for macOS' installer package for each new release.
A list of available installers
is available here@footnote{https://www.python.org/downloads/macos/}.
We recommend using the most recent supported Python version where possible.
Current installers provide a
universal2 binary@footnote{https://en.wikipedia.org/wiki/Universal_binary} build
of Python which runs natively on all Macs (Apple Silicon and Intel) that are
supported by a wide range of macOS versions,
currently typically from at least `macOS 10.15 Catalina' on.

The downloaded file is a standard macOS installer package file (@code{.pkg}).
File integrity information (checksum, size, sigstore signature, etc) for each file is included
on the release download page. Installer packages and their contents are signed and notarized
with @code{Python Software Foundation} Apple Developer ID certificates
to meet macOS Gatekeeper requirements@footnote{https://support.apple.com/en-us/102445}.

For a default installation, double-click on the downloaded installer package file.
This should launch the standard macOS Installer app and display the first of several
installer windows steps.

@image{python-figures/mac_installer_01_introduction,,,,png}

Clicking on the `Continue' button brings up the `Read Me' for this installer.
Besides other important information, the `Read Me' documents which Python version is
going to be installed and on what versions of macOS it is supported. You may need
to scroll through to read the whole file. By default, this `Read Me' will also be
installed in @code{/Applications/Python 3.14/} and available to read anytime.

@image{python-figures/mac_installer_02_readme,,,,png}

Clicking on `Continue' proceeds to display the license for Python and for
other included software. You will then need to `Agree' to the license terms
before proceeding to the next step. This license file will also be installed
and available to be read later.

@image{python-figures/mac_installer_03_license,,,,png}

After the license terms are accepted, the next step is the `Installation Type'
display. For most uses, the standard set of installation operations is appropriate.

@image{python-figures/mac_installer_04_installation_type,,,,png}

By pressing the `Customize' button, you can choose to omit or select certain package
components of the installer. Click on each package name to see a description of
what it installs.
To also install support for the optional free-threaded feature,
see @ref{498,,フリースレッドバイナリ (Free-threaded Binaries) のインストール}.

@image{python-figures/mac_installer_05_custom_install,,,,png}

In either case, clicking `Install' will begin the install process by asking
permission to install new software. A macOS user name with @code{Administrator} privilege
is needed as the installed Python will be available to all users of the Mac.

When the installation is complete, the `Summary' window will appear.

@image{python-figures/mac_installer_06_summary,,,,png}

Double-click on the @code{Install Certificates.command}
icon or file in the @code{/Applications/Python 3.14/} window to complete the
installation.

@image{python-figures/mac_installer_07_applications,,,,png}

This will open a temporary @code{Terminal} shell window that
will use the new Python to download and install SSL root certificates
for its use.

@image{python-figures/mac_installer_08_install_certificates,,,,png}

If @code{Successfully installed certifi} and @code{update complete} appears
in the terminal window, the installation is complete.
Close this terminal window and the installer window.

A default install will include:


@itemize *

@item 
A @code{Python 3.14} folder in your @code{Applications} folder. In here
you find @code{IDLE}, the development environment that is a standard part of official
Python distributions; and @code{Python Launcher}, which handles double-clicking Python
scripts from the macOS Finder@footnote{https://support.apple.com/en-us/HT201732}.

@item 
A framework @code{/Library/Frameworks/Python.framework}, which includes the
Python executable and libraries. The installer adds this location to your shell
path. To uninstall Python, you can remove these three things.
Symlinks to the Python executable are placed in @code{/usr/local/bin/}.
@end itemize

@cartouche
@quotation 注釈 
Recent versions of macOS include a @code{python3} command in @code{/usr/bin/python3}
that links to a usually older and incomplete version of Python provided by and for use by
the Apple development tools, @code{Xcode} or the @code{Command Line Tools for Xcode}.
You should never modify or attempt to delete this installation, as it is
Apple-controlled and is used by Apple-provided or third-party software.  If
you choose to install a newer Python version from @code{python.org}, you will have
two different but functional Python installations on your computer that
can co-exist. The default installer options should ensure that its @code{python3}
will be used instead of the system @code{python3}.
@end quotation
@end cartouche

@node Python スクリプトの実行方法,,インストール手順<2>,Using Python for macOS from python org
@anchor{using/mac how-to-run-a-python-script}@anchor{2247}
@subsubsection Python スクリプトの実行方法


There are two ways to invoke the Python interpreter.
If you are familiar with using a Unix shell in a terminal
window, you can invoke @code{python3.14} or @code{python3} optionally
followed by one or more command line options (described in @ref{1da7,,コマンドラインと環境}).
The Python tutorial also has a useful section on
@ref{494,,using Python interactively from a shell}.

You can also invoke the interpreter through an integrated
development environment.
@ref{1217,,IDLE --- Python のエディタとシェル} is a basic editor and interpreter environment
which is included with the standard distribution of Python.
@code{IDLE} includes a Help menu that allows you to access Python documentation. If you
are completely new to Python, you can read the tutorial introduction
in that document.

There are many other editors and IDEs available, see @ref{2248,,エディタと IDE}
for more information.

To run a Python script file from the terminal window, you can
invoke the interpreter with the name of the script file:

@quotation

@code{python3.14} @code{myscript.py}
@end quotation

To run your script from the Finder, you can either:


@itemize *

@item 
Drag it to @code{Python Launcher}.

@item 
Select @code{Python Launcher} as the default application to open your
script (or any @code{.py} script) through the Finder Info window and double-click it.
@code{Python Launcher} has various preferences to control how your script is
launched. Option-dragging allows you to change these for one invocation, or use
its @code{Preferences} menu to change things globally.
@end itemize

Be aware that running the script directly from the macOS Finder might
produce different results than when running from a terminal window as
the script will not be run in the usual shell environment including
any setting of environment variables in shell profiles.
And, as with any other script or program,
be certain of what you are about to run.

@node Alternative Distributions,追加の Python パッケージのインストール,Using Python for macOS from python org,macOS で Python を使う
@anchor{using/mac alternative-bundles}@anchor{2242}@anchor{using/mac alternative-distributions}@anchor{2249}
@subsection Alternative Distributions


Besides the standard @code{python.org} for macOS installer, there are third-party
distributions for macOS that may include additional functionality.
Some popular distributions and their key features:


@table @asis

@item ActivePython@footnote{https://www.activestate.com/products/python/}

Installer with multi-platform compatibility, documentation

@item Anaconda@footnote{https://www.anaconda.com/download/}

Popular scientific modules (such as numpy, scipy, and pandas) and the
@code{conda} package manager.

@item Homebrew@footnote{https://brew.sh}

Package manager for macOS including multiple versions of Python and many
third-party Python-based packages (including numpy, scipy, and pandas).

@item MacPorts@footnote{https://www.macports.org}

Another package manager for macOS including multiple versions of Python and many
third-party Python-based packages. May include pre-built versions of Python and
many packages for older versions of macOS.
@end table

Note that distributions might not include the latest versions of Python or
other libraries, and are not maintained or supported by the core Python team.

@node 追加の Python パッケージのインストール,GUI プログラミング,Alternative Distributions,macOS で Python を使う
@anchor{using/mac installing-additional-python-packages}@anchor{224a}@anchor{using/mac mac-package-manager}@anchor{224b}
@subsection 追加の Python パッケージのインストール


Refer to the Python Packaging User Guide@footnote{https://packaging.python.org/en/latest/tutorials/installing-packages/} for more information.
@anchor{using/mac osx-gui-scripts}@anchor{224c}
@node GUI プログラミング,高度なトピック,追加の Python パッケージのインストール,macOS で Python を使う
@anchor{using/mac gui-programming}@anchor{224d}@anchor{using/mac gui-programming-on-the-mac}@anchor{224e}
@subsection GUI プログラミング


Python で Mac 上の GUI アプリケーションをビルドする方法がいくつかあります。

The standard Python GUI toolkit is @ref{f6,,tkinter}, based on the cross-platform
Tk toolkit (@indicateurl{https://www.tcl.tk}). A macOS-native version of Tk is included with
the installer.

`PyObjC' is a Python binding to Apple's Objective-C/Cocoa framework.
Information on PyObjC is available from pyobjc@footnote{https://pypi.org/project/pyobjc/}.

A number of alternative macOS GUI toolkits are available including:


@itemize *

@item 
PySide@footnote{https://www.qt.io/qt-for-python}: Official Python bindings to the
Qt GUI toolkit@footnote{https://wiki.qt.io/Qt_for_Python}.

@item 
PyQt@footnote{https://riverbankcomputing.com/software/pyqt/}: Alternative
Python bindings to Qt.

@item 
Kivy@footnote{https://kivy.org}: A cross-platform GUI toolkit that supports
desktop and mobile platforms.

@item 
Toga@footnote{https://toga.readthedocs.io}: Part of the BeeWare Project@footnote{https://beeware.org}; supports desktop, mobile, web and console apps.

@item 
wxPython@footnote{https://wxpython.org}: A cross-platform toolkit that
supports desktop operating systems.
@end itemize

@node 高度なトピック,他のリソース,GUI プログラミング,macOS で Python を使う
@anchor{using/mac advanced-topics}@anchor{224f}
@subsection 高度なトピック


@menu
* フリースレッドバイナリ (Free-threaded Binaries) のインストール: フリースレッドバイナリ Free-threaded Binaries のインストール. 
* Installing using the command line:: 
* Python アプリケーションの配布:: 
* App Store コンプライアンス:: 

@end menu

@node フリースレッドバイナリ Free-threaded Binaries のインストール,Installing using the command line,,高度なトピック
@anchor{using/mac install-freethreaded-macos}@anchor{498}@anchor{using/mac installing-free-threaded-binaries}@anchor{2250}
@subsubsection フリースレッドバイナリ (Free-threaded Binaries) のインストール



Added in version 3.13.


The @code{python.org} @ref{2244,,Python for macOS}
installer package can optionally install an additional build of
Python 3.14 that supports 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}, the free-threading feature
(running with the @ref{474,,global interpreter lock} disabled).
Check the release page on @code{python.org} for possible updated information.

The free-threaded mode is working and continues to be improved, but
there is some additional overhead in single-threaded workloads compared
to the regular build. Additionally, third-party packages, in particular ones
with an @ref{2251,,extension module}, may not be ready for use in a
free-threaded build, and will re-enable the @ref{164,,GIL}.
Therefore, the support for free-threading
is not installed by default. It is packaged as a separate install option,
available by clicking the `Customize' button on the `Installation Type'
step of the installer as described above.

@image{python-figures/mac_installer_09_custom_install_free_threaded,,,,png}

If the box next to the `Free-threaded Python' package name is checked,
a separate @code{PythonT.framework} will also be installed
alongside the normal @code{Python.framework} in @code{/Library/Frameworks}.
This configuration allows a free-threaded Python 3.14 build to co-exist
on your system with a traditional (GIL only) Python 3.14 build with
minimal risk while installing or testing. This installation layout may
change in future releases.

Known cautions and limitations:


@itemize -

@item 
The `UNIX command-line tools' package, which is selected by default,
will install links in @code{/usr/local/bin} for @code{python3.14t},
the free-threaded interpreter, and @code{python3.14t-config},
a configuration utility which may be useful for package builders.
Since @code{/usr/local/bin} is typically included in your shell @code{PATH},
in most cases no changes to your @code{PATH} environment variables should
be needed to use @code{python3.14t}.

@item 
For this release, the `Shell profile updater' package and the
@code{Update Shell Profile.command} in @code{/Applications/Python 3.14/}
do not support the free-threaded package.

@item 
The free-threaded build and the traditional build have separate search
paths and separate @code{site-packages} directories so, by default,
if you need a package available in both builds, it may need to be installed in both.
The free-threaded package will install a separate instance of @code{pip} for use
with @code{python3.14t}.


@itemize -

@item 
To install a package using @code{pip} without a @code{venv}:

@example
python3.14t -m pip install <package_name>
@end example
@end itemize

@item 
When working with multiple Python environments, it is usually safest and easiest
to @ref{20eb,,create and use virtual environments}.
This can avoid possible command name conflicts and confusion about which Python is in use:

@example
python3.14t -m venv <venv_name>
@end example

then @code{activate}.

@item 
To run a free-threaded version of IDLE:

@example
python3.14t -m idlelib
@end example

@item 
The interpreters in both builds respond to the same
@ref{807,,PYTHON environment variables}
which may have unexpected results, for example, if you have @code{PYTHONPATH}
set in a shell profile. If necessary, there are
@ref{211b,,command line options} like @code{-E}
to ignore these environment variables.

@item 
The free-threaded build links to the third-party shared libraries,
such as @code{OpenSSL} and @code{Tk}, installed in the traditional framework.
This means that both builds also share one set of trust certificates
as installed by the @code{Install Certificates.command} script,
thus it only needs to be run once.

@item 
If you cannot depend on the link in @code{/usr/local/bin} pointing to the
@code{python.org} free-threaded @code{python3.14t} (for example, if you want
to install your own version there or some other distribution does),
you can explicitly set your shell @code{PATH} environment variable to
include the @code{PythonT} framework @code{bin} directory:

@example
export PATH="/Library/Frameworks/PythonT.framework/Versions/3.14/bin":"$PATH"
@end example

The traditional framework installation by default does something similar,
except for @code{Python.framework}. Be aware that having both framework @code{bin}
directories in @code{PATH} can lead to confusion if there are duplicate names
like @code{python3.14} in both; which one is actually used depends on the order
they appear in @code{PATH}. The @code{which python3.x} or @code{which python3.xt}
commands can show which path is being used. Using virtual environments
can help avoid such ambiguities. Another option might be to create
a shell @code{alias} to the desired interpreter, like:

@example
alias py3.14="/Library/Frameworks/Python.framework/Versions/3.14/bin/python3.14"
alias py3.14t="/Library/Frameworks/PythonT.framework/Versions/3.14/bin/python3.14t"
@end example
@end itemize

@node Installing using the command line,Python アプリケーションの配布,フリースレッドバイナリ Free-threaded Binaries のインストール,高度なトピック
@anchor{using/mac installing-using-the-command-line}@anchor{2252}
@subsubsection Installing using the command line


If you want to use automation to install the @code{python.org} installer package
(rather than by using the familiar macOS @code{Installer} GUI app),
the macOS command line @code{installer} utility lets you select non-default
options, too. If you are not familiar with @code{installer}, it can be
somewhat cryptic (see @code{man installer} for more information).
As an example, the following shell snippet shows one way to do it,
using the @code{3.14.0b2} release and selecting the free-threaded interpreter
option:

@example
RELEASE="python-3.140b2-macos11.pkg"

# download installer pkg
curl -O https://www.python.org/ftp/python/3.14.0/$@{RELEASE@}

# create installer choicechanges to customize the install:
#    enable the PythonTFramework-3.14 package
#    while accepting the other defaults (install all other packages)
cat > ./choicechanges.plist <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
        <dict>
                <key>attributeSetting</key>
                <integer>1</integer>
                <key>choiceAttribute</key>
                <string>selected</string>
                <key>choiceIdentifier</key>
                <string>org.python.Python.PythonTFramework-3.14</string>
        </dict>
</array>
</plist>
EOF

sudo installer -pkg ./$@{RELEASE@} -applyChoiceChangesXML ./choicechanges.plist -target /
@end example

You can then test that both installer builds are now available with something like:

@example
$ # test that the free-threaded interpreter was installed if the Unix Command Tools package was enabled
$ /usr/local/bin/python3.14t -VV
Python 3.14.0b2 free-threading build (v3.14.0b2:3a83b172af, Jun  5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
$ #    and the traditional interpreter
$ /usr/local/bin/python3.14 -VV
Python 3.14.0b2 (v3.14.0b2:3a83b172af, Jun  5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
$ # test that they are also available without the prefix if /usr/local/bin is on $PATH
$ python3.14t -VV
Python 3.14.0b2 free-threading build (v3.14.0b2:3a83b172af, Jun  5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
$ python3.14 -VV
Python 3.14.0b2 (v3.14.0b2:3a83b172af, Jun  5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
@end example

@cartouche
@quotation 注釈 
Current @code{python.org} installers only install to fixed locations like
@code{/Library/Frameworks/}, @code{/Applications}, and @code{/usr/local/bin}.
You cannot use the @code{installer} @code{-domain} option to install to
other locations.
@end quotation
@end cartouche

@node Python アプリケーションの配布,App Store コンプライアンス,Installing using the command line,高度なトピック
@anchor{using/mac distributing-python-applications}@anchor{2253}@anchor{using/mac distributing-python-applications-on-the-mac}@anchor{2254}
@subsubsection Python アプリケーションの配布


Python コードをスタンドアローンな配布アプリケーションに変換するツールには様々なものがあります:


@itemize *

@item 
py2app@footnote{https://pypi.org/project/py2app/}: Supports creating macOS @code{.app}
bundles from a Python project.

@item 
Briefcase@footnote{https://briefcase.readthedocs.io}: Part of the BeeWare Project@footnote{https://beeware.org}; a cross-platform packaging tool that supports
creation of @code{.app} bundles on macOS, as well as managing signing and
notarization.

@item 
PyInstaller@footnote{https://pyinstaller.org/}: A cross-platform packaging tool that creates
a single file or folder as a distributable artifact.
@end itemize

@node App Store コンプライアンス,,Python アプリケーションの配布,高度なトピック
@anchor{using/mac app-store-compliance}@anchor{2255}
@subsubsection App Store コンプライアンス


Apps submitted for distribution through the macOS App Store must pass Apple's
app review process. This process includes a set of automated validation rules
that inspect the submitted application bundle for problematic code.

The Python standard library contains some code that is known to violate these
automated rules. While these violations appear to be false positives, Apple's
review rules cannot be challenged. Therefore, it is necessary to modify the
Python standard library for an app to pass App Store review.

The Python source tree contains
a patch file@footnote{https://github.com/python/cpython/tree/3.14/Mac/Resources/app-store-compliance.patch} that will remove
all code that is known to cause issues with the App Store review process. This
patch is applied automatically when CPython is configured with the
@ref{1997,,--with-app-store-compliance} option.

This patch is not normally required to use CPython on a Mac; nor is it required
if you are distributing an app `outside' the macOS App Store. It is `only'
required if you are using the macOS App Store as a distribution channel.

@node 他のリソース,,高度なトピック,macOS で Python を使う
@anchor{using/mac other-resources}@anchor{2256}
@subsection 他のリソース


The python.org Help page@footnote{https://www.python.org/about/help/} has links to many useful resources.
The Pythonmac-SIG mailing list@footnote{https://www.python.org/community/sigs/current/pythonmac-sig/}
is another support resource specifically for Python users and developers on the Mac.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Android で Python を使う,iOS で Python を使う,macOS で Python を使う,Python のセットアップと利用
@anchor{using/android doc}@anchor{2257}@anchor{using/android translation-repo}@anchor{2258}@anchor{using/android using-android}@anchor{2259}@anchor{using/android using-python-on-android}@anchor{225a}
@section Android で Python を使う


Android における Pythonは、デスクトッププラットフォームにおける Python とは異なります。 デスクトッププラットフォームでは、 Python は一般的にコンピューターのどのユーザーでも使えるシステムリソースとしてインストールされます。そして、ユーザーは @code{python} 実行可能ファイルを実行して対話型プロンプトにコマンドを入力したり、 Python スクリプトを実行したりして、 Python を使用することができるのです。

Android においては、システムリソースとしてのインストールという概念はありません。ソフトウェア配布が可能なのは、 "アプリ" だけです。また、 @code{python} 実行可能ファイルの実行したり、 Python の REPL を使用したりする、コンソールも存在しません。

このため、 Python を Android 上で使うただ一つの方法は、埋め込みモード、つまり、ネイティブ Android アプリケーションを書き、 @code{libpython} を使用して Python インタープリタを埋め込み、そして @ref{225b,,Python 埋め込み API} を使用して Python コードを呼び出すことです。 それにより、完全な Python インタープリタ、標準ライブラリ、及び Python のコードが、アプリにパッケージ化され、独自の私的用途に使用されます。

Python の 標準ライブラリには、 Android におけるいくつかの重要な省略や制限があります。詳細は @ref{225c,,API 利用可能性ガイド} を参照してください。

@menu
* Android アプリに Python を追加する:: 
* Android 向けの Python パッケージをビルドする:: 

@end menu

@node Android アプリに Python を追加する,Android 向けの Python パッケージをビルドする,,Android で Python を使う
@anchor{using/android adding-python-to-an-android-app}@anchor{225d}
@subsection Android アプリに Python を追加する


ほとんどのアプリ開発者は、次のツールの一つを使用するべきです。これにより、はるかに簡単な体験が提供されます:


@itemize *

@item 
BeeWare プロジェクトの Briefcase@footnote{https://briefcase.readthedocs.io}

@item 
Kivy プロジェクトの Buildozer@footnote{https://buildozer.readthedocs.io}

@item 
Chaquopy@footnote{https://chaquo.com/chaquopy}

@item 
pyqtdeploy@footnote{https://www.riverbankcomputing.com/static/Docs/pyqtdeploy/}

@item 
Termux@footnote{https://termux.dev/en/}
@end itemize

If you're sure you want to do all of this manually, read on. You can use the
testbed app@footnote{https://github.com/python/cpython/tree/3.14/Android/testbed} as a guide; each step below contains a
link to the relevant file.


@itemize *

@item 
First, acquire a build of Python for Android:


@itemize *

@item 
The easiest way is to download an Android release from python.org@footnote{https://www.python.org/downloads/android/}. The @code{prefix} directory
mentioned below is at the top level of the package.

@item 
Or if you want to build it yourself, follow the instructions in
Android/README.md@footnote{https://github.com/python/cpython/tree/3.14/Android/README.md}. The @code{prefix} directory will be created under
@code{cross-build/@var{HOST}}.
@end itemize

@item 
Add code to your build.gradle@footnote{https://github.com/python/cpython/tree/3.14/Android/testbed/app/build.gradle.kts}
file to copy the following items into your project. All except your own Python
code can be copied from @code{prefix/lib}:


@itemize *

@item 
In your JNI libraries:


@itemize *

@item 
@code{libpython*.*.so}

@item 
@code{lib*_python.so} (external libraries such as OpenSSL)
@end itemize

@item 
In your assets:


@itemize *

@item 
@code{python*.*} (the Python standard library)

@item 
@code{python*.*/site-packages} (your own Python code)
@end itemize
@end itemize

@item 
Add code to your app to extract the assets to the filesystem@footnote{https://github.com/python/cpython/tree/3.14/Android/testbed/app/src/main/java/org/python/testbed/MainActivity.kt}.

@item 
Add code to your app to start Python in embedded mode@footnote{https://github.com/python/cpython/tree/3.14/Android/testbed/app/src/main/c/main_activity.c}. This will need to be C code
called via JNI.
@end itemize

@node Android 向けの Python パッケージをビルドする,,Android アプリに Python を追加する,Android で Python を使う
@anchor{using/android building-a-python-package-for-android}@anchor{225e}
@subsection Android 向けの Python パッケージをビルドする


Python packages can be built for Android as wheels and released on PyPI. The
recommended tool for doing this is cibuildwheel@footnote{https://cibuildwheel.pypa.io/en/stable/platforms/#android}, which automates
all the details of setting up a cross-compilation environment, building the
wheel, and testing it on an emulator.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node iOS で Python を使う,エディタと IDE,Android で Python を使う,Python のセットアップと利用
@anchor{using/ios doc}@anchor{225f}@anchor{using/ios translation-repo}@anchor{2260}@anchor{using/ios using-ios}@anchor{2261}@anchor{using/ios using-python-on-ios}@anchor{2262}
@section iOS で Python を使う


@*著者: 
Russell Keith-Magee (2024-03)


iOS における Pythonは、デスクトッププラットフォームにおける Python とは異なります。 デスクトッププラットフォームでは、 Python は一般的にコンピューターのどのユーザーでも使えるシステムリソースとしてインストールされます。そして、ユーザーは @code{python} 実行可能ファイルを実行して対話型プロンプトにコマンドを入力したり、 Python スクリプトを実行したりして、 Python を使用することができるのです。

iOS においては、システムリソースとしてのインストールという概念はありません。ソフトウェア配布が可能なのは、 "アプリ" だけです。また、 @code{python} 実行可能ファイルを実行したり、 Python の REPL を使用したりする、コンソールも存在しません。

このため、 Python を iOS 上で使うただ一つの方法は、埋め込みモード、つまり、ネイティブ iOS アプリケーションを書き、 @code{libPython} を使用して Python インタープリタを埋め込み、そして @ref{225b,,Python 埋め込み API} を使用して Python コードを呼び出すことです。 それにより、完全な Python インタープリタ、標準ライブラリ、 及び Python のコードが、 iOS App Store を経由して配布可能なスタンドアローンなバンドルとしてパッケージ化されます。

もし、初めて iOS アプリを Python で書くことを試みているなら、 BeeWare@footnote{https://beeware.org} や Kivy@footnote{https://kivy.org} といったプロジェクトは、よりわかりやすいユーザー体験を提供するでしょう。これらのプロジェクトは iOS プロジェクトを実行することに関連する複雑なことを管理するので、あなたは Python のコードに集中するだけで良くなります。

@menu
* iOS ランタイムでの Python:: 
* iOS での Python のインストール:: 
* App Store コンプライアンス: App Store コンプライアンス<2>. 

@end menu

@node iOS ランタイムでの Python,iOS での Python のインストール,,iOS で Python を使う
@anchor{using/ios python-at-runtime-on-ios}@anchor{2263}
@subsection iOS ランタイムでの Python


@menu
* iOS のバージョン互換性:: 
* プラットフォームの識別:: 
* 標準ライブラリの利用可能性:: 
* バイナリ拡張モジュール:: 
* コンパイラスタブバイナリ:: 

@end menu

@node iOS のバージョン互換性,プラットフォームの識別,,iOS ランタイムでの Python
@anchor{using/ios ios-version-compatibility}@anchor{2264}
@subsubsection iOS のバージョン互換性


サポートされる最小の iOS バージョンは、コンパイル時に @code{configure} の @ref{21c4,,--host} オプションを使用して指定できます。デフォルトでは、 iOS 用にコンパイルする場合、 Python は最小で 13.0 の iOS バージョンをサポートするようにコンパイルされます。異なる最小 iOS バージョンを使用するには、 @code{--host} 引数の一部としてバージョン番号を提供します。例えば @code{--host=arm64-apple-ios15.4-simulator} とすると、 ARM64 シミュレーター用のビルドを Deployment Target 15.4 でコンパイルします。

@node プラットフォームの識別,標準ライブラリの利用可能性,iOS のバージョン互換性,iOS ランタイムでの Python
@anchor{using/ios platform-identification}@anchor{2265}
@subsubsection プラットフォームの識別


iOS 上で実行している場合、 @code{sys.platform} は @code{ios} となります。アプリがシミュレーターで実行されているか、物理デバイスで実行されているかにかかわらず、 iPhone または iPad ではこの値となります。

iOS バージョンやデバイスのモデル、デバイスがシミュレーターであるかどうかを含めた、特定のランタイム環境についての情報は、 @ref{2266,,platform.ios_ver()} を使用して取得できます。 @ref{2267,,platform.system()} は、デバイスにより @code{iOS} または @code{iPadOS} を報告します。

@ref{132e,,os.uname()} は、カーネルレベルの詳細を報告します。これは @code{Darwin} の名前を報告します。

@node 標準ライブラリの利用可能性,バイナリ拡張モジュール,プラットフォームの識別,iOS ランタイムでの Python
@anchor{using/ios standard-library-availability}@anchor{2268}
@subsubsection 標準ライブラリの利用可能性


Python の 標準ライブラリには、 iOS におけるいくつかの重要な省略や制限があります。詳細は @ref{225c,,iOS 向けの API 利用可能性ガイド} を参照してください。

@node バイナリ拡張モジュール,コンパイラスタブバイナリ,標準ライブラリの利用可能性,iOS ランタイムでの Python
@anchor{using/ios binary-extension-modules}@anchor{2269}
@subsubsection バイナリ拡張モジュール


プラットフォームとしての iOS についての重要な違いの一つは、 App Store での配布がアプリケーションのパッケージングに厳しい条件を課すということです。 これらの条件の一つは、バイナリ拡張モジュールの配布方法を規定します。

iOS App Store では、 iOS アプリの全てのバイナリモジュールが、パッケージ化されたアプリの @code{Frameworks} フォルダに保存された、適切なメタデータ付きのフレームワークに含まれる動的ライブラリである必要があります。フレームワークごとにバイナリは一つだけで、 @code{Frameworks} フォルダの外に実行可能バイナリデータを設置することはできません。

これは、バイナリ拡張モジュールが @code{sys.path} 上のどの場所からでも読み込み可能な、通常の Python のバイナリ配布のアプローチと衝突します。 確実に App Store ポリシーに従うために、 iOS プロジェクトはいずれの Python パッケージにも、 @code{.so} バイナリモジュールを、個別の、スタンドアローンで、適切なメタデータと署名付きのフレームワークに変換する後処理を行わなければなりません。どのように後処理を行うかの詳細は、 @ref{226a,,プロジェクトに Python を追加する} のガイドを参照してください。

Python が新しい場所にあるバイナリを見つけることを助けるために、 @code{sys.path} にある元の @code{.so} ファイルは @code{.fwork} ファイルに置き換えられます。 このファイルは、アプリバンドルからのレームワークバイナリの相対パスを含むテキストファイルです。フレームワークが元の場所に解決できるようにするためには、フレームワークは、アプリバンドルからの @code{.fwork} ファイルの相対パスが含まれた、 @code{.origin} ファイルを含む必要があります。

例えば、@code{from foo.bar import _whiz} をインポートする場合を考えてみましょう。 @code{_whiz} がバイナリモジュール @code{sources/foo/bar/_whiz.abi3.so} で実装されており、 @code{sources} のアプリケーションバンドルからの相対パスが @code{sys.path} に登録されています。このモジュールは @code{Frameworks/foo.bar._whiz.framework/foo.bar._whiz} (フレームワーク名はモジュールの完全なインポートパスから命名されています) として、バイナリをフレームワークとして識別する @code{Info.plist} ファイルを @code{.framework} ディレクトリ内に設置して配布しなければなりません。 @code{foo.bar._whiz} モジュールは、元の場所で、 @code{Frameworks/foo.bar._whiz/foo.bar._whiz} のパスを含む @code{sources/foo/bar/_whiz.abi3.fwork} マーカーファイルに記述されます。 また、フレームワークは、 @code{.fwork} へのパスを含む @code{Frameworks/foo.bar._whiz.framework/foo.bar._whiz.origin} も含まなければなりません。

iOS 上で実行している場合、 Python インタープリタは @code{.fwork} ファイルを読み込んでインポートすることができる @ref{226b,,AppleFrameworkLoader} をインストールします。インポートされると、バイナリモジュールの @code{__file__} 属性は @code{.fwork} ファイルの場所を返します。一方、読み込まれたモジュールの @ref{226c,,ModuleSpec} はフレームワークフォルダのバイナリの場所として @code{origin} を返します。

@node コンパイラスタブバイナリ,,バイナリ拡張モジュール,iOS ランタイムでの Python
@anchor{using/ios compiler-stub-binaries}@anchor{226d}
@subsubsection コンパイラスタブバイナリ


Xcode は、 iOS 用の明示的なコンパイラを提供していません。代わりに、完全なコンパイラのパスを解決する @code{xcrun} スクリプトを使用します (たとえば @code{xcrun --sdk iphoneos clang} は iPhone デバイス用の @code{clang} を取得します) 。しかし、これは2つの問題を引き起こします:


@itemize *

@item 
@code{xcrun} の出力はマシン固有のパスを含み、ユーザー間で共有できない sysconfig モジュールにつながり、

@item 
これにより、 @code{CC}/@code{CPP}/@code{LD}/@code{AR} 定義にスペースが含まれることになります。多くの C エコシステムツールが、最初のスペースでコマンドラインを分割し、コンパイラ実行ファイルを取得できることを前提としています。しかし、 @code{xcrun} を使用する場合はそうではありません。
@end itemize

これらの問題を避けるため、 Python はこれらのツール用のスタブを提供しました。これらのスタブは、コンパイルされた iOS フレームワークとともに配布される @code{bin} フォルダで配布される、基礎の @code{xcrun} ツールのシェルスクリプトラッパーです。これらのスクリプトは再配置可能で、常に適切なローカルシステムパスに解決されます。これらのスクリプトをフレームワークを伴う bin フォルダーに含めることで、 @code{sysconfig} モジュールはエンドユーザーが自身のモジュールをコンパイルするのに有用になります。iOS 用の サードパーティの Python モジュールをコンパイルするときは、これらのスタブバイナリがパス上にあることを確認するべきです。

@node iOS での Python のインストール,App Store コンプライアンス<2>,iOS ランタイムでの Python,iOS で Python を使う
@anchor{using/ios installing-python-on-ios}@anchor{226e}
@subsection iOS での Python のインストール


@menu
* iOS アプリビルド用のツール:: 
* iOS プロジェクトに Python を追加する:: 
* Python パッケージのテスト:: 

@end menu

@node iOS アプリビルド用のツール,iOS プロジェクトに Python を追加する,,iOS での Python のインストール
@anchor{using/ios tools-for-building-ios-apps}@anchor{226f}
@subsubsection iOS アプリビルド用のツール


iOS 向けのビルドには、 Apple の Xcode のツールを使用します。Xcode の最新の安定リリースを使用することを強く推奨します。Apple は古い macOS のバージョン向けには Xcode をメンテナンスしないため、これには最も (または二番目に) 最近にリリースされた macOS のバージョンが必要です。 Xcode コマンドラインツールは iOS 開発には不十分であり、完全な Xcode のインストールが必要です。

iOS シミュレーター上でコードを実行したい場合は、 iOS Simulator プラットフォームもインストールする必要があります。 Xcode を初めて実行したとき、 iOS Simulator プラットフォームを選択するプロンプトが表示されるはずです。代わりに、 Xcode の Settings パネルの Platforms タブから iOS Simulator プラットフォームを選択して追加することもできます。

@node iOS プロジェクトに Python を追加する,Python パッケージのテスト,iOS アプリビルド用のツール,iOS での Python のインストール
@anchor{using/ios adding-ios}@anchor{226a}@anchor{using/ios adding-python-to-an-ios-project}@anchor{2270}
@subsubsection iOS プロジェクトに Python を追加する


Python は、 Swift または Objective-C を使って、どの iOS プロジェクトにでも追加できます。以下の例では、 Objective-C を使用しています。 Swift を使う場合は、 PythonKit@footnote{https://github.com/pvieito/PythonKit} のようなライブラリが役に立つかもしれません。

Python を iOS Xcode プロジェクトに追加するには:


@enumerate 

@item 
Python の @code{XCFramework} をビルドまたは取得します。 Python の @code{XCFramework} をビルドする方法についての詳細は、 Apple/iOS/README.md@footnote{https://github.com/python/cpython/tree/3.14/Apple/iOS/README.md} (CPython のソースコードにあります) の説明を参照してください。最低でも、 @code{arm64-apple-ios} に加えて @code{arm64-apple-ios-simulator} または @code{x86_64-apple-ios-simulator} のどちらかをサポートするビルドが必要です。

@item 
@code{XCframework} を iOS プロジェクトにドラッグします。以降の説明では、 プロジェクトのルートに @code{XCframework} を設置したものと仮定しますが、パスを必要に応じて調整することで、他の場所を使用することも出来ます。

@item 
アプリケーションのコードを、 Xcode プロジェクトにフォルダーとして追加します。以降の説明では、 プロジェクトのルートに @code{app} という名前のユーザーコードが入ったフォルダを設置したものと仮定しますが、パスを必要に応じて調整することで、他の場所を使用することも出来ます。フォルダがアプリのターゲットに関連付けられていることを確認してください。

@item 
Xcode プロジェクトのルートノードを選択することで、アプリのターゲットを選択してください。すると、ターゲット名がサイドバーに現れるはずです。

@item 
"General" の設定の "Frameworks, Libraries and Embedded Content" に、 "Embed & Sign" を選択して @code{Python.xcframework} を追加してください。

@item 
"Build Settings" タブで、次の項目を修正してください:


@itemize -

@item 
Build Options


@itemize *

@item 
User Script Sandboxing: No

@item 
Enable Testability: Yes
@end itemize

@item 
Search Paths


@itemize *

@item 
Framework Search Paths: @code{$(PROJECT_DIR)}

@item 
Header Search Paths: @code{"$(BUILT_PRODUCTS_DIR)/Python.framework/Headers"}
@end itemize

@item 
Apple Clang - Warnings - All languages


@itemize *

@item 
Quoted Include In Framework Header: No
@end itemize
@end itemize

@item 
Python の標準ライブラリおよび独自の Python バイナリ依存関係を処理するビルドステップを追加します。 "Build Phases" タブで、新しい "Run Script" ビルドステップを "Embed Frameworks" ステップの前に追加してください。ステップの名前は "Process Python libraries" にして、 "Based on dependency analysis" のチェックボックスを外し、スクリプトの内容を次のように設定してください:

@example
set -e
source $PROJECT_DIR/Python.xcframework/build/build_utils.sh
install_python Python.xcframework app
@end example

もし XCFramework をプロジェクトのルート以外のどこかに設置した場合は、一つ目の引数へのパスを修正してください。

@item 
Python インタープリタを埋め込みモードで初期化・使用する Objective C コードを追加します。次のことを確認する必要があります:


@itemize *

@item 
UTF-8 モード (@ref{41d,,PyPreConfig.utf8_mode}) が `有効' になっていること

@item 
Buffered stdio (@ref{411,,PyConfig.buffered_stdio}) が `無効' になっていること

@item 
バイトコードの書き込み (@ref{40d,,PyConfig.write_bytecode}) が `無効' になっていること

@item 
シグナルハンドラ (@ref{abb,,PyConfig.install_signal_handlers}) が `有効' になっていること

@item 
システムログ (@ref{2271,,PyConfig.use_system_logger}) が `有効' になっていること (オプションですが、強く推奨され、デフォルトで有効化されています)

@item 
インタープリタの 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} がアプリバンドルの @code{python} サブフォルダを指すように構成されていること

@item 
インタープリタの 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} が次のものを含むこと


@itemize -

@item 
アプリのバンドルの @code{python/lib/python3.X} サブフォルダ

@item 
アプリのバンドルの @code{python/lib/python3.X/lib-dynload} サブフォルダ

@item 
アプリのバンドルの @code{app} サブフォルダ
@end itemize
@end itemize

アプリのバンドルの場所は @code{[[NSBundle mainBundle] resourcePath]} を用いて取得できます。
@end enumerate

これらの説明の手順 7, 8 は @code{app} という名前のただ一つの純粋な Python アプリケーションのコードのフォルダがあることを前提としています。もしサードパーティのバイナリモジュールがアプリに含まれる場合は、いくつかの追加の手順が必要です:


@itemize *

@item 
サードパーティのバイナリを含むフォルダが、アプリのターゲットに関連付けられている、または手順 7 の一部として明示的にコピーされていることを確認する必要があります。手順 7 では、特定のビルドがターゲットとするプラットフォームに適切でないバイナリを取り除く(つまり、もしシミュレーターをターゲットとするアプリをビルドしている場合は、デバイスバイナリを削除する)ことも必要です。

@item 
サードパーティのパッケージに別のフォルダを使用している場合は、手順 7 でフォルダが @code{install_python} の呼び出しの末尾に追加され、手順 8 の 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} 設定の一つとして追加されていることを確認してください。

@item 
サードパーティパッケージを含むフォルダが @code{.pth} ファイルを含む場合、直接 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} や @ref{3e4,,sys.path} に追加するのではなく、そのフォルダを (@ref{2272,,site.addsitedir()} を使用して) サイトディレクトリとして追加する必要があります。
@end itemize

@node Python パッケージのテスト,,iOS プロジェクトに Python を追加する,iOS での Python のインストール
@anchor{using/ios testing-a-python-package}@anchor{2273}
@subsubsection Python パッケージのテスト


CPython ソースツリーには、 iOS シミュレーター上で CPython テストスイートを実行するために使用される テストベッドプロジェクト@footnote{https://github.com/python/cpython/tree/3.14/Apple/iOS/testbed} が含まれています。このテストベッドは、 iOSで Python ライブラリのテストスイートを実行するためのテストベッドプロジェクトとしても使用できます。

iOS XCFramework (詳細は Apple/iOS/README.md@footnote{https://github.com/python/cpython/tree/3.14/Apple/iOS/README.md} を参照) をビルドまたは取得した後は、 Python iOS テストベッドプロジェクトの複製を作成してください。 XCFramework をビルドする @code{Apple} ビルドスクリプトを使用して場合は、次のコマンドを実行して行えます:

@example
$ python cross-build/iOS/testbed clone --app <module1 のパス> --app <module2 のパス> app-testbed
@end example

もしくは、独自の XCFramework を調達した場合は、次のコマンドを実行して行えます:

@example
$ python Apple/testbed clone --platform iOS --framework <Python.xcframework のパス> --app <module1 のパス> --app <module2 のパス> app-testbed
@end example

@code{--app} フラグで指定されたフォルダは、複製されたテストベッドプロジェクトにコピーされます。結果として得られるテストベッドは、 @code{app-testbed} フォルダの中に作成されます。この例では、 @code{module1} と @code{module2} が、実行時にインポート可能なモジュールとなります。プロジェクトに追加の依存関係がある場合は、 (@code{pip install --target app-testbed/Testbed/app_packages} をなど使用して) それらは @code{app-testbed/Testbed/app_packages} フォルダの中にインストールできます。

You can then use the @code{app-testbed} folder to run the test suite for your app,
For example, if @code{module1.tests} was the entry point to your test suite, you
could run:

@example
$ python app-testbed run -- module1.tests
@end example

This is the equivalent of running @code{python -m module1.tests} on a desktop
Python build. Any arguments after the @code{--} will be passed to the testbed as
if they were arguments to @code{python -m} on a desktop machine.

You can also open the testbed project in Xcode by running:

@example
$ open app-testbed/iOSTestbed.xcodeproj
@end example

This will allow you to use the full Xcode suite of tools for debugging.

The arguments used to run the test suite are defined as part of the test plan.
To modify the test plan, select the test plan node of the project tree (it
should be the first child of the root node), and select the "Configurations"
tab. Modify the "Arguments Passed On Launch" value to change the testing
arguments.

The test plan also disables parallel testing, and specifies the use of the
@code{Testbed.lldbinit} file for providing configuration of the debugger. The
default debugger configuration disables automatic breakpoints on the
@code{SIGINT}, @code{SIGUSR1}, @code{SIGUSR2}, and @code{SIGXFSZ} signals.

@node App Store コンプライアンス<2>,,iOS での Python のインストール,iOS で Python を使う
@anchor{using/ios app-store-compliance}@anchor{2274}
@subsection App Store コンプライアンス


The only mechanism for distributing apps to third-party iOS devices is to
submit the app to the iOS App Store; apps submitted for distribution must pass
Apple's app review process. This process includes a set of automated validation
rules that inspect the submitted application bundle for problematic code. There
are some steps that must be taken to ensure that your app will be able to pass
these validation steps.

@menu
* 標準ライブラリ内の互換性のないコード:: 
* プライバシーマニフェスト:: 

@end menu

@node 標準ライブラリ内の互換性のないコード,プライバシーマニフェスト,,App Store コンプライアンス<2>
@anchor{using/ios incompatible-code-in-the-standard-library}@anchor{2275}
@subsubsection 標準ライブラリ内の互換性のないコード


Python の標準ライブラリには、これらの自動ルールに違反することが知られているコードがいくつか含まれています。これらの違反は誤検出であると思われますが、 Apple の審査ルールに異議を唱えることはできません。そのため、 Python の標準ライブラリを、アプリが App Store 審査に合格するよう修正する必要があります。

Python のソースツリーは、 App Store 審査プロセスで問題を引き起こすことが知られているすべてのコードを削除する パッチファイル@footnote{https://github.com/python/cpython/tree/3.14/Mac/Resources/app-store-compliance.patch} を含んでいます。このパッチは iOS 用のビルド時に自動的に適用されます。

@node プライバシーマニフェスト,,標準ライブラリ内の互換性のないコード,App Store コンプライアンス<2>
@anchor{using/ios privacy-manifests}@anchor{2276}
@subsubsection プライバシーマニフェスト


In April 2025, Apple introduced a requirement for certain third-party libraries to provide a Privacy Manifest@footnote{https://developer.apple.com/support/third-party-SDK-requirements}.
As a result, if you have a binary module that uses one of the affected
libraries, you must provide an @code{.xcprivacy} file for that library.
OpenSSL is one library affected by this requirement, but there are others.

If you produce a binary module named @code{mymodule.so}, and use you the Xcode
build script described in step 7 above, you can place a @code{mymodule.xcprivacy}
file next to @code{mymodule.so}, and the privacy manifest will be installed into
the required location when the binary module is converted into a framework.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node エディタと IDE,,iOS で Python を使う,Python のセットアップと利用
@anchor{using/editors doc}@anchor{2277}@anchor{using/editors editors}@anchor{2248}@anchor{using/editors editors-and-ides}@anchor{2278}@anchor{using/editors translation-repo}@anchor{2279}
@section エディタと IDE


Python プログラミング言語をサポートする IDE はたくさんあります。
多くのエディタや IDE にはシンタックスハイライト機能、デバッグツール、 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} チェック機能があります。

@menu
* IDLE: IDLE --- Python のエディタとシェル. Python のエディタとシェル
* Other Editors and IDEs:: 

@end menu

@node IDLE --- Python のエディタとシェル,Other Editors and IDEs,,エディタと IDE
@anchor{using/editors idle-python-editor-and-shell}@anchor{227a}
@subsection IDLE --- Python のエディタとシェル


IDLE is Python’s Integrated Development and Learning Environment and is generally bundled with Python installs.
If you are on Linux and do not have IDLE installed see @ref{2149,,Installing IDLE on Linux}.
For more information see the @ref{1217,,IDLE docs}.

@node Other Editors and IDEs,,IDLE --- Python のエディタとシェル,エディタと IDE
@anchor{using/editors other-editors-and-ides}@anchor{227b}
@subsection Other Editors and IDEs


Python's community wiki has information submitted by the community on Editors and IDEs.
Please go to Python Editors@footnote{https://wiki.python.org/moin/PythonEditors} and
Integrated Development Environments@footnote{https://wiki.python.org/moin/IntegratedDevelopmentEnvironments}
for a comprehensive list.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python 言語リファレンス,Python 標準ライブラリ,Python のセットアップと利用,Top
@anchor{reference/index doc}@anchor{227c}@anchor{reference/index reference-index}@anchor{14a}@anchor{reference/index the-python-language-reference}@anchor{227d}@anchor{reference/index translation-repo}@anchor{227e}
@chapter Python 言語リファレンス


このリファレンスマニュアルでは、Python 言語の文法と、 "コアとなるセマンティクス" について記述します。このマニュアルはそっけない書き方かもしれませんが、正確さと完全さを優先しています。必須でない組み込みオブジェクト型や組み込み関数、組み込みモジュールに関するセマンティクスは、 @ref{149,,Python 標準ライブラリ} で述べられています。形式ばらない Python 言語入門には、 @ref{1fbc,,Python チュートリアル} を参照してください。 C 言語あるいはC++プログラマ向けには、このマニュアルとは別に二つのマニュアルがあります。 @ref{1fbd,,Python インタプリタの拡張と埋め込み} では、Python 拡張モジュールを書くための高レベルな様式について述べています。また、 @ref{1fbe,,Python/C API リファレンスマニュアル} では、C/C++ プログラマが利用できるインターフェースについて詳細に記述しています。

@menu
* はじめに: はじめに<5>. 
* 字句解析:: 
* データモデル:: 
* 実行モデル:: 
* インポートシステム:: 
* 式 (expression): 式 expression. 
* 単純文 (simple statement): 単純文 simple statement. 
* 複合文 (compound statement): 複合文 compound statement. 
* トップレベル要素:: 
* 完全な文法仕様:: 

@end menu

@node はじめに<5>,字句解析,,Python 言語リファレンス
@anchor{reference/introduction doc}@anchor{227f}@anchor{reference/introduction id1}@anchor{2280}@anchor{reference/introduction introduction}@anchor{2281}
@section はじめに


このリファレンスマニュアルは、Python プログラミング言語自体に関する記述です。チュートリアルとして書かれたものではありません。

私は本マニュアルをできるだけ正確に書こうとする一方で、文法や字句解析以外の全てについて、形式化された仕様記述ではなく英語を使うことにしました。そうすることで、このドキュメントが平均的な読者にとってより読みやすくなっているはずですが、ややあいまいな部分も残っていることでしょう。従って、もし読者のあなたが火星から来ている人で、このドキュメントだけから Python を再度実装しようとしているのなら、色々と推測しなければならないことがあり、実際にはおそらく全く別の言語を実装する羽目になるでしょう。逆に、あなたが Python を利用しており、Python 言語のある特定の領域において、厳密な規則が何か疑問に思った場合、その答えはこのドキュメントで確実に見つけられることでしょう。もしより形式化された言語定義をお望みなら、あなたの時間を提供していただいてかまいません --- もしくは、クローン生成装置でも発明してください :-)。

実装に関する詳細を言語リファレンスのドキュメントに載せすぎるのは危険なことです --- 実装は変更されるかもしれず、同じ言語でも異なる実装は異なった動作をするかもしれないからです。一方、CPython が広く使われている一つの Python 実装 (別の実装も支持され続けていますが) なので、特定のクセについては、特に実装によって何らかの制限が加えられている場合には、触れておく価値があります。従って、このテキスト全体にわたって短い "実装に関する注釈 (imprementation notes)" がちりばめられています。

Python 実装はいずれも、数々の組み込みモジュールと標準モジュールが付属します。それらについては、 @ref{149,,Python 標準ライブラリ} でドキュメント化されています。いくつかの組み込みモジュールについては、言語定義と重要なかかわりをもっているときについて触れています。

@menu
* 別のPythonの実装:: 
* 本マニュアルにおける表記法:: 

@end menu

@node 別のPythonの実装,本マニュアルにおける表記法,,はじめに<5>
@anchor{reference/introduction alternate-implementations}@anchor{2282}@anchor{reference/introduction implementations}@anchor{2118}
@subsection 別のPythonの実装


Pythonの実装としては、群を抜いて有名な実装がひとつ存在しています。それ以外の実装に関しても、特定のユーザ間で興味が持たれています。

よく知られている実装には以下のものがあります:


@table @asis

@item CPython

これは最も保守されている初代のPython実装で、C言語で書かれています。ほとんどの場合、言語の新機能がいち早く実装されます。

@item Jython

Javaで実装されたPythonです。この実装はJavaアプリケーションのためのスクリプト言語として、もしくはJavaクラスライブラリを使ったアプリケーションを作成するために使用することができます。また、Javaライブラリのテストを作成するためにもしばしば使用されています。さらなる情報については the Jython website@footnote{https://www.jython.org/} を参照してください。

@item Python for .NET

この実装は内部ではCPythonを使用していますが、 .NETアプリケーションによって管理されているので、 .NETライブラリを参照することが可能です。この実装はBrian Lloydによって作成されました。さらなる情報については、 Python for .NET home page@footnote{https://pythonnet.github.io/} を参照してください。

@item IronPython

.NETでPythonを使用するためのもう一つの実装です。Python.NETとは異なり、完全にILを生成することができるPythonの実装あり、直接Pythonコードを.NETアセンブリにコンパイルします。これはJythonの初代の開発者であるJim Huguninによって作られました。さらなる情報については the IronPython website@footnote{https://ironpython.net/} を参照してください。

@item PyPy

完全にPythonで書かれたPythonの実装です。他の実装には見られない、スタックレスのサポートや、実行時 (Just in Time) コンパイラなどの高度な機能をサポートしています。このプロジェクトの一つの目的は、（Pythonで書かれていることによって、）インタプリタを簡単に修正できるようにして、言語自体での実験を後押しすることです。さらなる情報は the PyPy project's home page@footnote{https://pypy.org/} にあります。
@end table

これらの各実装はこのマニュアルで文書化された言語とは多少異なっている、もしくは、標準のPythonドキュメントと何処が異なっているかを定めた情報が公開されているでしょう。あなたが使用している実装上で、代替手段を使う必要があるかどうかを判断するためには、各実装の仕様書を参照してください。

@node 本マニュアルにおける表記法,,別のPythonの実装,はじめに<5>
@anchor{reference/introduction id2}@anchor{2283}@anchor{reference/introduction notation}@anchor{2284}
@subsection 本マニュアルにおける表記法


@geindex BNF
@geindex 文法
@geindex 構文
@geindex 記法

The descriptions of lexical analysis and syntax use a grammar notation that
is a mixture of
EBNF@footnote{https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form}
and PEG@footnote{https://en.wikipedia.org/wiki/Parsing_expression_grammar}.
For example:

@example
@anchor{reference/introduction grammar-token-notation-name}@anchor{2285}name:   @ref{2286,,letter} (@ref{2286,,letter} | @ref{2287,,digit} | "_")*
@anchor{reference/introduction grammar-token-notation-letter}@anchor{2286}letter: "a"..."z" | "A"..."Z"
@anchor{reference/introduction grammar-token-notation-digit}@anchor{2287}digit:  "0"..."9"
@end example

In this example, the first line says that a @code{name} is a @code{letter} followed
by a sequence of zero or more @code{letter}s, @code{digit}s, and underscores.
A @code{letter} in turn is any of the single characters @code{'a'} through
@code{'z'} and @code{A} through @code{Z}; a @code{digit} is a single character from @code{0}
to @code{9}.

Each rule begins with a name (which identifies the rule that's being defined)
followed by a colon, @code{:}.
The definition to the right of the colon uses the following syntax elements:


@itemize *

@item 
@code{name}: A name refers to another rule.
Where possible, it is a link to the rule's definition.


@itemize *

@item 
@code{TOKEN}: An uppercase name refers to a @ref{2288,,token}.
For the purposes of grammar definitions, tokens are the same as rules.
@end itemize

@item 
@code{"text"}, @code{'text'}: Text in single or double quotes must match literally
(without the quotes). The type of quote is chosen according to the meaning
of @code{text}:


@itemize *

@item 
@code{'if'}: A name in single quotes denotes a @ref{2289,,keyword}.

@item 
@code{"case"}: A name in double quotes denotes a
@ref{a0d,,soft-keyword}.

@item 
@code{'@@'}: A non-letter symbol in single quotes denotes an
@ref{228a,,OP} token, that is, a @ref{228b,,delimiter} or
@ref{228c,,operator}.
@end itemize

@item 
@code{e1 e2}: Items separated only by whitespace denote a sequence.
Here, @code{e1} must be followed by @code{e2}.

@item 
@code{e1 | e2}: A vertical bar is used to separate alternatives.
It denotes PEG's "ordered choice": if @code{e1} matches, @code{e2} is
not considered.
In traditional PEG grammars, this is written as a slash, @code{/}, rather than
a vertical bar.
See 
@geindex Python Enhancement Proposals; PEP 617
PEP 617@footnote{https://peps.python.org/pep-0617/} for more background and details.

@item 
@code{e*}: A star means zero or more repetitions of the preceding item.

@item 
@code{e+}: Likewise, a plus means one or more repetitions.

@item 
@code{[e]}: A phrase enclosed in square brackets means zero or
one occurrences. In other words, the enclosed phrase is optional.

@item 
@code{e?}: A question mark has exactly the same meaning as square brackets:
the preceding item is optional.

@item 
@code{(e)}: Parentheses are used for grouping.
@end itemize

The following notation is only used in
@ref{228d,,lexical definitions}.


@itemize *

@item 
@code{"a"..."z"}: Two literal characters separated by three dots mean a choice
of any single character in the given (inclusive) range of ASCII characters.

@item 
@code{<...>}: A phrase between angular brackets gives an informal description
of the matched symbol (for example, @code{<any ASCII character except "\">}),
or an abbreviation that is defined in nearby text (for example, @code{<Lu>}).
@end itemize
@anchor{reference/introduction lexical-lookaheads}@anchor{228e}
Some definitions also use `lookaheads', which indicate that an element
must (or must not) match at a given position, but without consuming any input:


@itemize *

@item 
@code{&e}: a positive lookahead (that is, @code{e} is required to match)

@item 
@code{!e}: a negative lookahead (that is, @code{e} is required `not' to match)
@end itemize

The unary operators (@code{*}, @code{+}, @code{?}) bind as tightly as possible;
the vertical bar (@code{|}) binds most loosely.

White space is only meaningful to separate tokens.

Rules are normally contained on a single line, but rules that are too long
may be wrapped:

@example
@anchor{reference/introduction grammar-token-notation-literal}@anchor{228f}literal: stringliteral | bytesliteral
         | integer | floatnumber | imagnumber
@end example

Alternatively, rules may be formatted with the first line ending at the colon,
and each alternative beginning with a vertical bar on a new line.
For example:

@example
@anchor{reference/introduction grammar-token-notation-alt-literal}@anchor{2290}literal:
   | stringliteral
   | bytesliteral
   | integer
   | floatnumber
   | imagnumber
@end example

This does `not' mean that there is an empty first alternative.

@geindex 字句解析

@menu
* Lexical and Syntactic definitions:: 

@end menu

@node Lexical and Syntactic definitions,,,本マニュアルにおける表記法
@anchor{reference/introduction lexical-and-syntactic-definitions}@anchor{2291}@anchor{reference/introduction notation-lexical-vs-syntactic}@anchor{228d}
@subsubsection Lexical and Syntactic definitions


There is some difference between `lexical' and `syntactic' analysis:
the @ref{2292,,lexical analyzer} operates on the individual characters of the
input source, while the `parser' (syntactic analyzer) operates on the stream
of @ref{2288,,tokens} generated by the lexical analysis.
However, in some cases the exact boundary between the two phases is a
CPython implementation detail.

The practical difference between the two is that in `lexical' definitions,
all whitespace is significant.
The lexical analyzer @ref{2293,,discards} all whitespace that is not
converted to tokens like @ref{20fd,,token.INDENT} or @ref{2294,,NEWLINE}.
`Syntactic' definitions then use these tokens, rather than source characters.

This documentation uses the same BNF grammar for both styles of definitions.
All uses of BNF in the next chapter (@ref{2295,,字句解析}) are lexical definitions;
uses in subsequent chapters are syntactic definitions.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 字句解析,データモデル,はじめに<5>,Python 言語リファレンス
@anchor{reference/lexical_analysis doc}@anchor{2296}@anchor{reference/lexical_analysis lexical}@anchor{2295}@anchor{reference/lexical_analysis lexical-analysis}@anchor{2297}@anchor{reference/lexical_analysis translation-repo}@anchor{2298}
@section 字句解析


@geindex 字句解析
@geindex `@w{`}parser`@w{`}
@geindex トークン

A Python program is read by a `parser'.  Input to the parser is a stream of
@ref{2288,,tokens}, generated by the `lexical analyzer' (also known as
the `tokenizer').
This chapter describes how the lexical analyzer produces these tokens.

The lexical analyzer determines the program text's @ref{2299,,encoding}
(UTF-8 by default), and decodes the text into
@ref{229a,,source characters}.
If the text cannot be decoded, a @ref{18e,,SyntaxError} is raised.

Next, the lexical analyzer uses the source characters to generate a stream of tokens.
The type of a generated token generally depends on the next source character to
be processed. Similarly, other special behavior of the analyzer depends on
the first source character that hasn't yet been processed.
The following table gives a quick summary of these source characters,
with links to sections that contain more information.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文字

@tab

Next token (or other relevant documentation)

@item


@itemize *

@item 
空白

@item 
タブ

@item 
formfeed
@end itemize

@tab


@itemize *

@item 
@ref{2293,,Whitespace}
@end itemize

@item


@itemize *

@item 
CR, LF
@end itemize

@tab


@itemize *

@item 
@ref{229b,,New line}

@item 
@ref{229c,,Indentation}
@end itemize

@item


@itemize *

@item 
backslash (@code{\})
@end itemize

@tab


@itemize *

@item 
@ref{229d,,Explicit line joining}

@item 
(Also significant in @ref{687,,string escape sequences})
@end itemize

@item


@itemize *

@item 
hash (@code{#})
@end itemize

@tab


@itemize *

@item 
@ref{229e,,Comment}
@end itemize

@item


@itemize *

@item 
quote (@code{'}, @code{"})
@end itemize

@tab


@itemize *

@item 
@ref{229f,,String literal}
@end itemize

@item


@itemize *

@item 
ASCII letter (@code{a}-@code{z}, @code{A}-@code{Z})

@item 
non-ASCII character
@end itemize

@tab


@itemize *

@item 
@ref{22a0,,Name}

@item 
Prefixed @ref{229f,,string or bytes literal}
@end itemize

@item


@itemize *

@item 
underscore (@code{_})
@end itemize

@tab


@itemize *

@item 
@ref{22a0,,Name}

@item 
(Can also be part of @ref{22a1,,numeric literals})
@end itemize

@item


@itemize *

@item 
number (@code{0}-@code{9})
@end itemize

@tab


@itemize *

@item 
@ref{22a1,,Numeric literal}
@end itemize

@item


@itemize *

@item 
dot (@code{.})
@end itemize

@tab


@itemize *

@item 
@ref{22a1,,Numeric literal}

@item 
@ref{228c,,Operator}
@end itemize

@item


@itemize *

@item 
question mark (@code{?})

@item 
dollar (@code{$})

@item 
@c (the following uses zero-width space characters to render

@c a literal backquote)

backquote (@code{​`​})

@item 
control character
@end itemize

@tab


@itemize *

@item 
Error (outside string literals and comments)
@end itemize

@item


@itemize *

@item 
other printing character
@end itemize

@tab


@itemize *

@item 
@ref{228c,,Operator or delimiter}
@end itemize

@item


@itemize *

@item 
end of file
@end itemize

@tab


@itemize *

@item 
@ref{22a2,,End marker}
@end itemize

@end multitable


@menu
* 行構造:: 
* その他のトークン:: 
* Names (identifiers and keywords): Names identifiers and keywords. 
* リテラル:: 
* 文字列およびバイト列リテラル:: 
* 数値リテラル:: 
* Operators and delimiters:: 

@end menu

@node 行構造,その他のトークン,,字句解析
@anchor{reference/lexical_analysis id1}@anchor{22a3}@anchor{reference/lexical_analysis line-structure}@anchor{229b}
@subsection 行構造


@geindex 行構造

Python プログラムは多数の `論理行 (logical lines)' に分割されます。

@menu
* 論理行 (logical line): 論理行 logical line. 
* 物理行 (physical line): 物理行 physical line. 
* コメント (Comments): コメント Comments. 
* エンコード宣言 (encoding declaration): エンコード宣言 encoding declaration. 
* 明示的な行継続:: 
* 非明示的な行継続:: 
* 空行:: 
* インデント:: 
* トークン間の空白:: 
* End marker:: 

@end menu

@node 論理行 logical line,物理行 physical line,,行構造
@anchor{reference/lexical_analysis id2}@anchor{22a4}@anchor{reference/lexical_analysis logical-lines}@anchor{22a5}
@subsubsection 論理行 (logical line)


@geindex 論理行
@geindex 物理行
@geindex 行連結
@geindex NEWLINE トークン

The end of a logical line is represented by the token @ref{2294,,NEWLINE}.
Statements cannot cross logical line boundaries except where @code{NEWLINE}
is allowed by the syntax (e.g., between statements in compound statements).
A logical line is constructed from one or more `physical lines' by following
the @ref{229d,,explicit} or @ref{22a6,,implicit}
`line joining' rules.

@node 物理行 physical line,コメント Comments,論理行 logical line,行構造
@anchor{reference/lexical_analysis id3}@anchor{22a7}@anchor{reference/lexical_analysis physical-lines}@anchor{22a8}
@subsubsection 物理行 (physical line)


A physical line is a sequence of characters terminated by one the following
end-of-line sequences:


@itemize *

@item 
the Unix form using ASCII LF (linefeed),

@item 
the Windows form using the ASCII sequence CR LF (return followed by linefeed),

@item 
the 'Classic Mac OS@footnote{https://en.wikipedia.org/wiki/Classic_Mac_OS}' form using the ASCII CR (return) character.
@end itemize

Regardless of platform, each of these sequences is replaced by a single
ASCII LF (linefeed) character.
(This is done even inside @ref{229f,,string literals}.)
Each line can use any of the sequences; they do not need to be consistent
within a file.

The end of input also serves as an implicit terminator for the final
physical line.

Formally:

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-newline}@anchor{22a9}newline: <ASCII LF> | <ASCII CR> <ASCII LF> | <ASCII CR>
@end example

@node コメント Comments,エンコード宣言 encoding declaration,物理行 physical line,行構造
@anchor{reference/lexical_analysis comments}@anchor{229e}@anchor{reference/lexical_analysis id5}@anchor{22aa}
@subsubsection コメント (Comments)


@geindex コメント
@geindex ハッシュ文字
@geindex # (hash);コメント

コメントは文字列リテラル内に入っていないハッシュ文字 (@code{#}) から始まり、同じ物理行の末端で終わります。
非明示的な行継続規則が適用されていない限り、コメントは論理行を終端させます。
コメントは構文上無視されます。

@node エンコード宣言 encoding declaration,明示的な行継続,コメント Comments,行構造
@anchor{reference/lexical_analysis encoding-declarations}@anchor{22ab}@anchor{reference/lexical_analysis encodings}@anchor{2299}
@subsubsection エンコード宣言 (encoding declaration)


@geindex ソースコード文字セット
@geindex encoding declarations (source file)
@geindex # (hash);source encoding declaration

Python スクリプト中の一行目か二行目にあるコメントが正規表現 @code{coding[=:]\s*([-\w.]+)} にマッチする場合、コメントはエンコード宣言として処理されます; この表現の最初のグループがソースコードファイルのエンコードを指定します。エンコード宣言は自身の行になければなりません。二行目にある場合、一行目もコメントのみの行でなければなりません。エンコード宣言式として推奨する形式は

@example
# -*- coding: <encoding-name> -*-
@end example

これは GNU Emacs で認識できます。または

@example
# vim:fileencoding=<encoding-name>
@end example

これは、Bram Moolenar による VIM が認識できる形式です。

If no encoding declaration is found, the default encoding is UTF-8.  If the
implicit or explicit encoding of a file is UTF-8, an initial UTF-8 byte-order
mark (@code{b'\xef\xbb\xbf'}) is ignored rather than being a syntax error.

エンコーディングが宣言される場合、そのエンコーディング名は Python によって認識できなければなりません (@ref{fb8,,標準エンコーディング} を参照してください)。宣言されたエンコーディングは、例えば文字列リテラル、コメント、識別子などの、全ての字句解析に使われます。
@anchor{reference/lexical_analysis lexical-source-character}@anchor{229a}
All lexical analysis, including string literals, comments
and identifiers, works on Unicode text decoded using the source encoding.
Any Unicode code point, except the NUL control character, can appear in
Python source.

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-source_character}@anchor{22ac}source_character:  <any Unicode code point, except NUL>
@end example

@node 明示的な行継続,非明示的な行継続,エンコード宣言 encoding declaration,行構造
@anchor{reference/lexical_analysis explicit-joining}@anchor{229d}@anchor{reference/lexical_analysis explicit-line-joining}@anchor{22ad}
@subsubsection 明示的な行継続


@geindex 物理行
@geindex 行連結
@geindex 行継続
@geindex バックスラッシュ文字

二つまたはそれ以上の物理行を論理行としてつなげるためには、バックスラッシュ文字 (@code{\}) を使って以下のようにします: 物理行が文字列リテラルやコメント中の文字でないバックスラッシュで終わっている場合、後続する行とつなげて一つの論理行を構成し、バックスラッシュおよびバックスラッシュの後ろにある行末文字を削除します。例えば:

@example
if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1
@end example

バックスラッシュで終わる行にはコメントを入れることはできません。また、バックスラッシュを使ってコメントを継続することはできません。バックスラッシュが文字列リテラル中にある場合を除き、バックスラッシュの後ろにトークンを継続することはできません (すなわち、物理行内の文字列リテラル以外のトークンをバックスラッシュを使って分断することはできません)。上記以外の場所では、文字列リテラル外にあるバックスラッシュはどこにあっても不正となります。

@node 非明示的な行継続,空行,明示的な行継続,行構造
@anchor{reference/lexical_analysis implicit-joining}@anchor{22a6}@anchor{reference/lexical_analysis implicit-line-joining}@anchor{22ae}
@subsubsection 非明示的な行継続


丸括弧 (parentheses)、角括弧 (square bracket) 、および波括弧 (curly brace) 内の式は、バックスラッシュを使わずに一行以上の物理行に分割することができます。例えば:

@example
month_names = ['Januari', 'Februari', 'Maart',      # These are the
               'April',   'Mei',      'Juni',       # Dutch names
               'Juli',    'Augustus', 'September',  # for the months
               'Oktober', 'November', 'December']   # of the year
@end example

非明示的に継続された行にはコメントを含めることができます。継続行のインデントは重要ではありません。空の継続行を書くことができます。非明示的な継続行中には、NEWLINE トークンは存在しません。非明示的な行の継続は、三重クオートされた文字列 (下記参照) でも発生します; この場合には、コメントを含めることができません。

@node 空行,インデント,非明示的な行継続,行構造
@anchor{reference/lexical_analysis blank-lines}@anchor{22af}@anchor{reference/lexical_analysis id6}@anchor{22b0}
@subsubsection 空行


@geindex 空行

A logical line that contains only spaces, tabs, formfeeds and possibly a
comment, is ignored (i.e., no @ref{2294,,NEWLINE} token is generated).
During interactive input of statements, handling of a blank line may differ
depending on the implementation of the read-eval-print loop.
In the standard interactive interpreter, an entirely blank logical line (that
is, one containing not even whitespace or a comment) terminates a multi-line
statement.

@node インデント,トークン間の空白,空行,行構造
@anchor{reference/lexical_analysis id7}@anchor{22b1}@anchor{reference/lexical_analysis indentation}@anchor{229c}
@subsubsection インデント


@geindex インデント
@geindex 先頭の空白
@geindex 空白
@geindex タブ
@geindex グループ化
@geindex 実行文のグループ化

論理行の行頭にある、先頭の空白 (スペースおよびタブ) の連なりは、その行のインデントレベルを計算するために使われます。インデントレベルは、実行文のグループ化方法を決定するために用いられます。

タブは (左から右の方向に) 1 つにつき 8 つのスペースで置き換えられ、置き換え後の文字数は 8 の倍数になります (Unix で使われている規則と同じになるよう意図されています)。そして、最初の非空白文字までのスペースの総数が、その行のインデントを決定します。インデントは、バックスラッシュで複数の物理行に分割できません; 最初のバックスラッシュまでの空白がインデントを決定します。

ソースファイルがタブとスペースを混在させ、その意味づけがタブのスペース換算数に依存するようなら、インデントは不合理なものとして却下されます。その場合は @ref{765,,TabError} が送出されます。

`プラットフォーム間の互換性に関する注意:' 非 UNIX プラットフォームにおけるテキストエディタの性質上、一つのソースファイル内でタブとインデントを混在させて使うのは賢明ではありません。また、プラットフォームによっては、最大インデントレベルを明示的に制限しているかもしれません。

フォームフィード文字が行の先頭にあっても構いません; フォームフィード文字は上のインデントレベル計算時には無視されます。フォームフィード文字が先頭の空白中の他の場所にある場合、その影響は未定義です (例えば、スペースの数を 0 にリセットするかもしれません)。

@geindex INDENT トークン
@geindex DEDENT トークン

The indentation levels of consecutive lines are used to generate
@ref{20fd,,INDENT} and @ref{22b2,,DEDENT} tokens, using a stack,
as follows.

Before the first line of the file is read, a single zero is pushed on the stack;
this will never be popped off again.  The numbers pushed on the stack will
always be strictly increasing from bottom to top.  At the beginning of each
logical line, the line's indentation level is compared to the top of the stack.
If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
one @code{INDENT} token is generated.  If it is smaller, it `must' be one of the
numbers occurring on the stack; all numbers on the stack that are larger are
popped off, and for each number popped off a @code{DEDENT} token is generated.
At the end of the file, a @code{DEDENT} token is generated for each number
remaining on the stack that is larger than zero.

以下の例に正しく (しかし当惑させるように) インデントされた Python コードの一部を示します:

@example
def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r
@end example

以下の例は、様々なインデントエラーになります:

@example
 def perm(l):                       # error: first line indented
for i in range(len(l)):             # error: not indented
    s = l[:i] + l[i+1:]
        p = perm(l[:i] + l[i+1:])   # error: unexpected indent
        for x in p:
                r.append(l[i:i+1] + x)
            return r                # error: inconsistent dedent
@end example

(実際は、最初の 3 つのエラーはパーザによって検出されます; 最後のエラーのみが字句解析器で見つかります --- @code{return r} のインデントは、スタックから逐次除去されていくどのインデントレベル値とも一致しません)

@node トークン間の空白,End marker,インデント,行構造
@anchor{reference/lexical_analysis whitespace}@anchor{2293}@anchor{reference/lexical_analysis whitespace-between-tokens}@anchor{22b3}
@subsubsection トークン間の空白


Except at the beginning of a logical line or in string literals, the whitespace
characters space, tab and formfeed can be used interchangeably to separate
tokens:

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-whitespace}@anchor{22b4}whitespace:  ' ' | tab | formfeed
@end example

Whitespace is needed between two tokens only if their concatenation
could otherwise be interpreted as a different token. For example, @code{ab} is one
token, but @code{a b} is two tokens. However, @code{+a} and @code{+ a} both produce
two tokens, @code{+} and @code{a}, as @code{+a} is not a valid token.

@node End marker,,トークン間の空白,行構造
@anchor{reference/lexical_analysis end-marker}@anchor{22b5}@anchor{reference/lexical_analysis endmarker-token}@anchor{22a2}
@subsubsection End marker


At the end of non-interactive input, the lexical analyzer generates an
@ref{22b6,,ENDMARKER} token.

@node その他のトークン,Names identifiers and keywords,行構造,字句解析
@anchor{reference/lexical_analysis id8}@anchor{22b7}@anchor{reference/lexical_analysis other-tokens}@anchor{22b8}
@subsection その他のトークン


Besides @ref{2294,,NEWLINE}, @ref{20fd,,INDENT} and @ref{22b2,,DEDENT},
the following categories of tokens exist:
`identifiers' and `keywords' (@ref{22b9,,NAME}), `literals' (such as
@ref{22ba,,NUMBER} and @ref{22bb,,STRING}), and other symbols
(`operators' and `delimiters', @ref{228a,,OP}).
Whitespace characters (other than logical line terminators, discussed earlier)
are not tokens, but serve to delimit tokens.
Where ambiguity exists, a token comprises the longest possible string that
forms a legal token, when read from left to right.

@node Names identifiers and keywords,リテラル,その他のトークン,字句解析
@anchor{reference/lexical_analysis identifiers}@anchor{22a0}@anchor{reference/lexical_analysis names-identifiers-and-keywords}@anchor{22bc}
@subsection Names (identifiers and keywords)


@geindex 識別子
@geindex name

@ref{22b9,,NAME} tokens represent `identifiers', `keywords', and
`soft keywords'.

Names are composed of the following characters:


@itemize *

@item 
uppercase and lowercase letters (@code{A-Z} and @code{a-z}),

@item 
the underscore (@code{_}),

@item 
digits (@code{0} through @code{9}), which cannot appear as the first character, and

@item 
non-ASCII characters. Valid names may only contain "letter-like" and
"digit-like" characters; see @ref{22bd,,Non-ASCII characters in names} for details.
@end itemize

Names must contain at least one character, but have no upper length limit.
Case is significant.

Formally, names are described by the following lexical definitions:

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-NAME}@anchor{22be}NAME:          @ref{22bf,,name_start} @ref{22c0,,name_continue}*
@anchor{reference/lexical_analysis grammar-token-python-grammar-name_start}@anchor{22bf}name_start:    "a"..."z" | "A"..."Z" | "_" | <non-ASCII character>
@anchor{reference/lexical_analysis grammar-token-python-grammar-name_continue}@anchor{22c0}name_continue: name_start | "0"..."9"
@anchor{reference/lexical_analysis grammar-token-python-grammar-identifier}@anchor{22c1}identifier:    <@ref{22be,,NAME}, except keywords>
@end example

Note that not all names matched by this grammar are valid; see
@ref{22bd,,Non-ASCII characters in names} for details.

@menu
* キーワード (keyword): キーワード keyword. 
* ソフトキーワード:: 
* 予約済みの識別子種 (reserved classes of identifiers): 予約済みの識別子種 reserved classes of identifiers. 
* Non-ASCII characters in names:: 

@end menu

@node キーワード keyword,ソフトキーワード,,Names identifiers and keywords
@anchor{reference/lexical_analysis id9}@anchor{22c2}@anchor{reference/lexical_analysis keywords}@anchor{2289}
@subsubsection キーワード (keyword)


@geindex キーワード
@geindex 予約語

The following names are used as reserved words, or `keywords' of the
language, and cannot be used as ordinary identifiers.  They must be spelled
exactly as written here:

@example
False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield
@end example

@node ソフトキーワード,予約済みの識別子種 reserved classes of identifiers,キーワード keyword,Names identifiers and keywords
@anchor{reference/lexical_analysis id10}@anchor{22c3}@anchor{reference/lexical_analysis soft-keywords}@anchor{a0d}
@subsubsection ソフトキーワード


@geindex soft keyword
@geindex キーワード


Added in version 3.10.


Some names are only reserved under specific contexts. These are known as
`soft keywords':


@itemize -

@item 
@code{match}, @code{case}, and @code{_}, when used in the @ref{a0e,,match} statement.

@item 
@code{type}, when used in the @ref{66d,,type} statement.
@end itemize

These syntactically act as keywords in their specific contexts,
but this distinction is done at the parser level, not when tokenizing.

As soft keywords, their use in the grammar is possible while still
preserving compatibility with existing code that uses these names as
identifier names.


バージョン 3.12 で変更: @code{type} is now a soft keyword.


@geindex _@comma{} identifiers
@geindex __@comma{} identifiers

@node 予約済みの識別子種 reserved classes of identifiers,Non-ASCII characters in names,ソフトキーワード,Names identifiers and keywords
@anchor{reference/lexical_analysis id-classes}@anchor{22c4}@anchor{reference/lexical_analysis reserved-classes-of-identifiers}@anchor{22c5}
@subsubsection 予約済みの識別子種 (reserved classes of identifiers)


ある種の (キーワードを除く) 識別子には、特殊な意味があります。これらの識別子種は、先頭や末尾にあるアンダースコア文字のパターンで区別されます:


@table @asis

@item @code{_*}

Not imported by @code{from module import *}.

@item @code{_}

In a @code{case} pattern within a @ref{a0e,,match} statement, @code{_} is a
@ref{a0d,,soft keyword} that denotes a
@ref{a0f,,wildcard}.

Separately, the interactive interpreter makes the result of the last evaluation
available in the variable @code{_}.
(It is stored in the @ref{13,,builtins} module, alongside built-in
functions like @code{print}.)

Elsewhere, @code{_} is a regular identifier. It is often used to name
"special" items, but it is not special to Python itself.

@cartouche
@quotation 注釈 
名前 @code{_} は、しばしば国際化 (internationalization) と共に用いられます; この慣習についての詳しい情報は、 @ref{67,,gettext} を参照してください。

It is also commonly used for unused variables.
@end quotation
@end cartouche

@item @code{__*__}

システムで定義された (system-defined) 名前です。非公式には"dunder"な名前と呼ばれます(訳注: double underscoresの略)。これらの名前はインタープリタと (標準ライブラリを含む) 実装上で定義されています。 現行のシステムでの名前は @ref{e68,,特殊メソッド名} などで話題に挙げられています。 Python の将来のバージョンではより多くの名前が定義されることになります。このドキュメントで明記されている用法に従わない、 `あらゆる' @code{__*__} の名前は、いかなるコンテキストにおける利用でも、警告無く損害を引き起こすことがあります。

@item @code{__*}

クラスプライベート (class-private) な名前です。このカテゴリに属する名前は、クラス定義のコンテキスト上で用いられた場合、基底クラスと派生クラスの "プライベートな" 属性間で名前衝突が起こるのを防ぐために書き直されます。 @ref{22c6,,識別子 (identifier、または名前 (name))} を参照してください。
@end table

@node Non-ASCII characters in names,,予約済みの識別子種 reserved classes of identifiers,Names identifiers and keywords
@anchor{reference/lexical_analysis lexical-names-nonascii}@anchor{22bd}@anchor{reference/lexical_analysis non-ascii-characters-in-names}@anchor{22c7}
@subsubsection Non-ASCII characters in names


Names that contain non-ASCII characters need additional normalization
and validation beyond the rules and grammar explained
@ref{22a0,,above}.
For example, @code{ř_1}, @code{蛇}, or @code{साँप}  are valid names, but @code{r〰2},
@code{€}, or @code{🐍} are not.

This section explains the exact rules.

All names are converted into the normalization form@footnote{https://www.unicode.org/reports/tr15/#Norm_Forms} NFKC while parsing.
This means that, for example, some typographic variants of characters are
converted to their "basic" form. For example, @code{ﬁⁿₐˡᵢᶻₐᵗᵢᵒₙ} normalizes to
@code{finalization}, so Python treats them as the same name:

@example
>>> ﬁⁿₐˡᵢᶻₐᵗᵢᵒₙ = 3
>>> finalization
3
@end example

@cartouche
@quotation 注釈 
Normalization is done at the lexical level only.
Run-time functions that take names as `strings' generally do not normalize
their arguments.
For example, the variable defined above is accessible at run time in the
@ref{1c0a,,globals()} dictionary as @code{globals()["finalization"]} but not
@code{globals()["ﬁⁿₐˡᵢᶻₐᵗᵢᵒₙ"]}.
@end quotation
@end cartouche

Similarly to how ASCII-only names must contain only letters, digits and
the underscore, and cannot start with a digit, a valid name must
start with a character in the "letter-like" set @code{xid_start},
and the remaining characters must be in the "letter- and digit-like" set
@code{xid_continue}.

These sets based on the `XID_Start' and `XID_Continue' sets as defined by the
Unicode standard annex UAX-31@footnote{https://www.unicode.org/reports/tr31/}.
Python's @code{xid_start} additionally includes the underscore (@code{_}).
Note that Python does not necessarily conform to UAX-31@footnote{https://www.unicode.org/reports/tr31/}.

A non-normative listing of characters in the `XID_Start' and `XID_Continue'
sets as defined by Unicode is available in the DerivedCoreProperties.txt@footnote{https://www.unicode.org/Public/16.0.0/ucd/DerivedCoreProperties.txt}
file in the Unicode Character Database.
For reference, the construction rules for the @code{xid_*} sets are given below.

The set @code{id_start} is defined as the union of:


@itemize *

@item 
Unicode category @code{<Lu>} - uppercase letters (includes @code{A} to @code{Z})

@item 
Unicode category @code{<Ll>} - lowercase letters (includes @code{a} to @code{z})

@item 
Unicode category @code{<Lt>} - titlecase letters

@item 
Unicode category @code{<Lm>} - modifier letters

@item 
Unicode category @code{<Lo>} - other letters

@item 
Unicode category @code{<Nl>} - letter numbers

@item 
@{@code{"_"}@} - the underscore

@item 
@code{<Other_ID_Start>} - an explicit set of characters in PropList.txt@footnote{https://www.unicode.org/Public/16.0.0/ucd/PropList.txt}
to support backwards compatibility
@end itemize

The set @code{xid_start} then closes this set under NFKC normalization, by
removing all characters whose normalization is not of the form
@code{id_start id_continue*}.

The set @code{id_continue} is defined as the union of:


@itemize *

@item 
@code{id_start} (see above)

@item 
Unicode category @code{<Nd>} - decimal numbers (includes @code{0} to @code{9})

@item 
Unicode category @code{<Pc>} - connector punctuations

@item 
Unicode category @code{<Mn>} - nonspacing marks

@item 
Unicode category @code{<Mc>} - spacing combining marks

@item 
@code{<Other_ID_Continue>} - another explicit set of characters in
PropList.txt@footnote{https://www.unicode.org/Public/16.0.0/ucd/PropList.txt} to support backwards compatibility
@end itemize

Again, @code{xid_continue} closes this set under NFKC normalization.

Unicode categories use the version of the Unicode Character Database as
included in the @ref{10b,,unicodedata} module.


@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 3131
PEP 3131@footnote{https://peps.python.org/pep-3131/} -- Supporting Non-ASCII Identifiers

@item 
@geindex Python Enhancement Proposals; PEP 672
PEP 672@footnote{https://peps.python.org/pep-0672/} -- Unicode-related Security Considerations for Python
@end itemize


@node リテラル,文字列およびバイト列リテラル,Names identifiers and keywords,字句解析
@anchor{reference/lexical_analysis id11}@anchor{22c8}@anchor{reference/lexical_analysis literals}@anchor{22c9}
@subsection リテラル


@geindex リテラル
@geindex 定数

リテラル (literal) とは、いくつかの組み込み型の定数を表記したものです。

In terms of lexical analysis, Python has @ref{229f,,string@comma{} bytes}
and @ref{22a1,,numeric} literals.

Other "literals" are lexically denoted using @ref{2289,,keywords}
(@code{None}, @code{True}, @code{False}) and the special
@ref{22ca,,ellipsis token} (@code{...}).

@geindex 文字列リテラル
@geindex バイト列リテラル
@geindex ASCII
@geindex ' (single quote);文字列リテラル
@geindex " (double quote);文字列リテラル

@node 文字列およびバイト列リテラル,数値リテラル,リテラル,字句解析
@anchor{reference/lexical_analysis string-and-bytes-literals}@anchor{22cb}@anchor{reference/lexical_analysis strings}@anchor{229f}
@subsection 文字列およびバイト列リテラル


String literals are text enclosed in single quotes (@code{'}) or double
quotes (@code{"}). For example:

@example
"spam"
'eggs'
@end example

The quote used to start the literal also terminates it, so a string literal
can only contain the other quote (except with escape sequences, see below).
For example:

@example
'Say "Hello", please.'
"Don't do that!"
@end example

Except for this limitation, the choice of quote character (@code{'} or @code{"})
does not affect how the literal is parsed.

Inside a string literal, the backslash (@code{\}) character introduces an
`escape sequence', which has special meaning depending on the character
after the backslash.
For example, @code{\"} denotes the double quote character, and does `not' end
the string:

@example
>>> print("Say \"Hello\" to everyone!")
Say "Hello" to everyone!
@end example

See @ref{687,,escape sequences} below for a full list of such
sequences, and more details.

@geindex triple-quoted string
@geindex """;文字列リテラル
@geindex '@w{'}';文字列リテラル

@menu
* Triple-quoted strings:: 
* String prefixes:: 
* Formal grammar:: 
* Escape sequences:: 
* Bytes literals:: 
* Raw string literals:: 
* f-strings:: 
* t-strings:: 
* Formal grammar for f-strings:: 

@end menu

@node Triple-quoted strings,String prefixes,,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis triple-quoted-strings}@anchor{22cc}
@subsubsection Triple-quoted strings


Strings can also be enclosed in matching groups of three single or double
quotes.
These are generally referred to as `triple-quoted strings':

@example
"""This is a triple-quoted string."""
@end example

In triple-quoted literals, unescaped quotes are allowed (and are
retained), except that three unescaped quotes in a row terminate the literal,
if they are of the same kind (@code{'} or @code{"}) used at the start:

@example
"""This string has "quotes" inside."""
@end example

Unescaped newlines are also allowed and retained:

@example
'@w{'}'This triple-quoted string
continues on the next line.'@w{'}'
@end example

@geindex u';文字列リテラル
@geindex u";文字列リテラル

@node String prefixes,Formal grammar,Triple-quoted strings,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis string-prefixes}@anchor{22cd}
@subsubsection String prefixes


String literals can have an optional `prefix' that influences how the
content of the literal is parsed, for example:

@example
b"data"
f'@{result=@}'
@end example

The allowed prefixes are:


@itemize *

@item 
@code{b}: @ref{22ce,,Bytes literal}

@item 
@code{r}: @ref{22cf,,Raw string}

@item 
@code{f}: @ref{19a,,Formatted string literal} ("f-string")

@item 
@code{t}: @ref{17fa,,Template string literal} ("t-string")

@item 
@code{u}: No effect (allowed for backwards compatibility)
@end itemize

See the linked sections for details on each type.

Prefixes are case-insensitive (for example, '@code{B}' works the same as '@code{b}').
The '@code{r}' prefix can be combined with '@code{f}', '@code{t}' or '@code{b}', so '@code{fr}',
'@code{rf}', '@code{tr}', '@code{rt}', '@code{br}', and '@code{rb}' are also valid prefixes.


Added in version 3.3: raw バイト列リテラルの @code{'rb'} プレフィックスが @code{'br'} の同義語として追加されました。

Python 2.x と 3.x 両対応のコードベースのメンテナンスを単純化するために、レガシー unicode リテラル (@code{u'value'}) のサポートが再び導入されました。詳細は 
@geindex Python Enhancement Proposals; PEP 414
PEP 414@footnote{https://peps.python.org/pep-0414/} を参照してください。


@node Formal grammar,Escape sequences,String prefixes,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis formal-grammar}@anchor{22d0}
@subsubsection Formal grammar


String literals, except @ref{19a,,"f-strings"} and
@ref{17fa,,"t-strings"}, are described by the
following lexical definitions.

These definitions use @ref{228e,,negative lookaheads} (@code{!})
to indicate that an ending quote ends the literal.

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-STRING}@anchor{22d1}STRING:          [@ref{22d2,,stringprefix}] (@ref{22d3,,stringcontent})
@anchor{reference/lexical_analysis grammar-token-python-grammar-stringprefix}@anchor{22d2}stringprefix:    <("r" | "u" | "b" | "br" | "rb"), case-insensitive>
@anchor{reference/lexical_analysis grammar-token-python-grammar-stringcontent}@anchor{22d3}stringcontent:
   | "'@w{'}'" ( !"'@w{'}'" @ref{22d4,,longstringitem})* "'@w{'}'"
   | '"""' ( !'"""' @ref{22d4,,longstringitem})* '"""'
   | "'" ( !"'" @ref{22d5,,stringitem})* "'"
   | '"' ( !'"' @ref{22d5,,stringitem})* '"'
@anchor{reference/lexical_analysis grammar-token-python-grammar-stringitem}@anchor{22d5}stringitem:      @ref{22d6,,stringchar} | @ref{22d7,,stringescapeseq}
@anchor{reference/lexical_analysis grammar-token-python-grammar-stringchar}@anchor{22d6}stringchar:      <any @ref{22ac,,source_character}, except backslash and newline>
@anchor{reference/lexical_analysis grammar-token-python-grammar-longstringitem}@anchor{22d4}longstringitem:  @ref{22d5,,stringitem} | newline
@anchor{reference/lexical_analysis grammar-token-python-grammar-stringescapeseq}@anchor{22d7}stringescapeseq: "\" <any @ref{22ac,,source_character}>
@end example

Note that as in all lexical definitions, whitespace is significant.
In particular, the prefix (if any) must be immediately followed by the starting
quote.

@geindex 物理行
@geindex エスケープシーケンス
@geindex 標準 C
@geindex C
@geindex \ (backslash);エスケープシーケンス
@geindex \\;エスケープシーケンス
@geindex \a;エスケープシーケンス
@geindex \b;エスケープシーケンス
@geindex \f;エスケープシーケンス
@geindex \n;エスケープシーケンス
@geindex \r;エスケープシーケンス
@geindex \t;エスケープシーケンス
@geindex \v;エスケープシーケンス
@geindex \x;エスケープシーケンス
@geindex \N;エスケープシーケンス
@geindex \u;エスケープシーケンス
@geindex \U;エスケープシーケンス

@node Escape sequences,Bytes literals,Formal grammar,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis escape-sequences}@anchor{687}@anchor{reference/lexical_analysis id12}@anchor{22d8}
@subsubsection Escape sequences


Unless an '@code{r}' or '@code{R}' prefix is present, escape sequences in string and
bytes literals are interpreted according to rules similar to those used by
Standard C.  The recognized escape sequences are:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

エスケープシーケンス

@tab

意味

@item

@code{\}<newline>

@tab

@ref{22d9,,Ignored end of line}

@item

@code{\\}

@tab

@ref{22da,,Backslash}

@item

@code{\'}

@tab

@ref{22da,,Single quote}

@item

@code{\"}

@tab

@ref{22da,,Double quote}

@item

@code{\a}

@tab

ASCII 端末ベル (BEL)

@item

@code{\b}

@tab

ASCII バックスペース (BS)

@item

@code{\f}

@tab

ASCII フォームフィード (FF)

@item

@code{\n}

@tab

ASCII 行送り (LF)

@item

@code{\r}

@tab

ASCII 復帰 (CR)

@item

@code{\t}

@tab

ASCII 水平タブ (TAB)

@item

@code{\v}

@tab

ASCII 垂直タブ (VT)

@item

@code{\@var{ooo}}

@tab

@ref{22db,,Octal character}

@item

@code{\x@var{hh}}

@tab

@ref{22dc,,Hexadecimal character}

@item

@code{\N@{@var{name}@}}

@tab

@ref{22dd,,Named Unicode character}

@item

@code{\u@var{xxxx}}

@tab

@ref{22de,,Hexadecimal Unicode character}

@item

@code{\U@var{xxxxxxxx}}

@tab

@ref{22de,,Hexadecimal Unicode character}

@end multitable


@menu
* Ignored end of line:: 
* Escaped characters:: 
* Octal character:: 
* Hexadecimal character:: 
* Named Unicode character:: 
* Hexadecimal Unicode characters:: 
* Unrecognized escape sequences:: 

@end menu

@node Ignored end of line,Escaped characters,,Escape sequences
@anchor{reference/lexical_analysis ignored-end-of-line}@anchor{22df}@anchor{reference/lexical_analysis string-escape-ignore}@anchor{22d9}
@subsubsection Ignored end of line


A backslash can be added at the end of a line to ignore the newline:

@example
>>> 'This string will not include \
... backslashes or newline characters.'
'This string will not include backslashes or newline characters.'
@end example

The same result can be achieved using @ref{229f,,triple-quoted strings},
or parentheses and @ref{22e0,,string literal concatenation}.

@node Escaped characters,Octal character,Ignored end of line,Escape sequences
@anchor{reference/lexical_analysis escaped-characters}@anchor{22e1}@anchor{reference/lexical_analysis string-escape-escaped-char}@anchor{22da}
@subsubsection Escaped characters


To include a backslash in a non-@ref{22cf,,raw} Python string
literal, it must be doubled. The @code{\\} escape sequence denotes a single
backslash character:

@example
>>> print('C:\\Program Files')
C:\Program Files
@end example

Similarly, the @code{\'} and @code{\"} sequences denote the single and double
quote character, respectively:

@example
>>> print('\' and \"')
' and "
@end example

@node Octal character,Hexadecimal character,Escaped characters,Escape sequences
@anchor{reference/lexical_analysis octal-character}@anchor{22e2}@anchor{reference/lexical_analysis string-escape-oct}@anchor{22db}
@subsubsection Octal character


The sequence @code{\@var{ooo}} denotes a `character' with the octal (base 8)
value `ooo':

@example
>>> '\120'
'P'
@end example

Up to three octal digits (0 through 7) are accepted.

In a bytes literal, `character' means a `byte' with the given value.
In a string literal, it means a Unicode character with the given value.


バージョン 3.11 で変更: Octal escapes with value larger than @code{0o377} (255) produce a
@ref{1a3,,DeprecationWarning}.



バージョン 3.12 で変更: Octal escapes with value larger than @code{0o377} (255) produce a
@ref{1ae,,SyntaxWarning}.
In a future Python version they will raise a @ref{18e,,SyntaxError}.


@node Hexadecimal character,Named Unicode character,Octal character,Escape sequences
@anchor{reference/lexical_analysis hexadecimal-character}@anchor{22e3}@anchor{reference/lexical_analysis string-escape-hex}@anchor{22dc}
@subsubsection Hexadecimal character


The sequence @code{\x@var{hh}} denotes a `character' with the hex (base 16)
value `hh':

@example
>>> '\x50'
'P'
@end example

標準 C とは違い、ちょうど 2 桁の 16 進数しか受理されません。

In a bytes literal, `character' means a `byte' with the given value.
In a string literal, it means a Unicode character with the given value.

@node Named Unicode character,Hexadecimal Unicode characters,Hexadecimal character,Escape sequences
@anchor{reference/lexical_analysis named-unicode-character}@anchor{22e4}@anchor{reference/lexical_analysis string-escape-named}@anchor{22dd}
@subsubsection Named Unicode character


The sequence @code{\N@{@var{name}@}} denotes a Unicode character
with the given `name':

@example
>>> '\N@{LATIN CAPITAL LETTER P@}'
'P'
>>> '\N@{SNAKE@}'
'🐍'
@end example

This sequence cannot appear in @ref{22ce,,bytes literals}.


バージョン 3.3 で変更: Support for name aliases@footnote{https://www.unicode.org/Public/16.0.0/ucd/NameAliases.txt}
has been added.


@node Hexadecimal Unicode characters,Unrecognized escape sequences,Named Unicode character,Escape sequences
@anchor{reference/lexical_analysis hexadecimal-unicode-characters}@anchor{22e5}@anchor{reference/lexical_analysis string-escape-long-hex}@anchor{22de}
@subsubsection Hexadecimal Unicode characters


These sequences @code{\u@var{xxxx}} and @code{\U@var{xxxxxxxx}} denote the
Unicode character with the given hex (base 16) value.
Exactly four digits are required for @code{\u}; exactly eight digits are
required for @code{\U}.
The latter can encode any Unicode character.

@example
>>> '\u1234'
'ሴ'
>>> '\U0001f40d'
'🐍'
@end example

These sequences cannot appear in @ref{22ce,,bytes literals}.

@geindex 認識されなかったエスケープシーケンス

@node Unrecognized escape sequences,,Hexadecimal Unicode characters,Escape sequences
@anchor{reference/lexical_analysis unrecognized-escape-sequences}@anchor{22e6}
@subsubsection Unrecognized escape sequences


Unlike in Standard C, all unrecognized escape sequences are left in the string
unchanged, that is, `the backslash is left in the result':

@example
>>> print('\q')
\q
>>> list('\q')
['\\', 'q']
@end example

Note that for bytes literals, the escape sequences only recognized in string
literals (@code{\N...}, @code{\u...}, @code{\U...}) fall into the category of
unrecognized escapes.


バージョン 3.6 で変更: Unrecognized escape sequences produce a @ref{1a3,,DeprecationWarning}.



バージョン 3.12 で変更: Unrecognized escape sequences produce a @ref{1ae,,SyntaxWarning}.
In a future Python version they will raise a @ref{18e,,SyntaxError}.


@geindex b';バイト列リテラル
@geindex b";バイト列リテラル

@node Bytes literals,Raw string literals,Escape sequences,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis bytes-literal}@anchor{22ce}@anchor{reference/lexical_analysis bytes-literals}@anchor{22e7}
@subsubsection Bytes literals


`Bytes literals' are always prefixed with '@code{b}' or '@code{B}'; they produce an
instance of the @ref{192,,bytes} type instead of the @ref{169,,str} type.
They may only contain ASCII characters; bytes with a numeric value of 128
or greater must be expressed with escape sequences (typically
@ref{22dc,,Hexadecimal character} or @ref{22db,,Octal character}):

@example
>>> b'\x89PNG\r\n\x1a\n'
b'\x89PNG\r\n\x1a\n'
>>> list(b'\x89PNG\r\n\x1a\n')
[137, 80, 78, 71, 13, 10, 26, 10]
@end example

Similarly, a zero byte must be expressed using an escape sequence (typically
@code{\0} or @code{\x00}).

@geindex r';raw string literal
@geindex r";raw string literal

@node Raw string literals,f-strings,Bytes literals,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis raw-string-literals}@anchor{22e8}@anchor{reference/lexical_analysis raw-strings}@anchor{22cf}
@subsubsection Raw string literals


Both string and bytes literals may optionally be prefixed with a letter '@code{r}'
or '@code{R}'; such constructs are called `raw string literals'
and `raw bytes literals' respectively and treat backslashes as
literal characters.
As a result, in raw string literals, @ref{687,,escape sequences}
are not treated specially:

@example
>>> r'\d@{4@}-\d@{2@}-\d@{2@}'
'\\d@{4@}-\\d@{2@}-\\d@{2@}'
@end example

raw リテラルでも、引用符はバックスラッシュでエスケープできますが、バックスラッシュ自体も文字列に残ります; 例えば、@code{r"\""} は有効な文字列リテラルで、バックスラッシュと二重引用符からなる文字列を表します; @code{r"\"} は無効な文字列リテラルです (raw リテラルを奇数個連なったバックスラッシュで終わらせることはできません)。具体的には、(バックスラッシュが直後のクオート文字をエスケープしてしまうので)  `raw文字列を単一のバックスラッシュで終わらせることはできません' さらに、バックスラッシュの直後に改行がきても、行継続を意味する `のではなく'、リテラルの一部であるそれら二つの文字として解釈されます。

@geindex formatted string literal
@geindex interpolated string literal
@geindex string;formatted literal
@geindex string;interpolated literal
@geindex f-string
@geindex fstring
@geindex f';formatted string literal
@geindex f";formatted string literal
@geindex @{@} (波括弧);in formatted string literal
@geindex ! (エクスクラメーション);in formatted string literal
@geindex ; (コロン);in formatted string literal
@geindex = (等号);for help in debugging using string literals
@anchor{reference/lexical_analysis f-strings}@anchor{19a}
@node f-strings,t-strings,Raw string literals,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis formatted-string-literals}@anchor{22e9}@anchor{reference/lexical_analysis id13}@anchor{22ea}
@subsubsection f-strings



Added in version 3.6.



バージョン 3.7 で変更: The @ref{18d,,await} and @ref{ca1,,async for} can be used in expressions
within f-strings.



バージョン 3.8 で変更: Added the debug specifier (@code{=})



バージョン 3.12 で変更: Many restrictions on expressions within f-strings have been removed.
Notably, nested strings, comments, and backslashes are now permitted.


A `formatted string literal' or `f-string' is a string literal
that is prefixed with '@code{f}' or '@code{F}'.
Unlike other string literals, f-strings do not have a constant value.
They may contain `replacement fields' delimited by curly braces @code{@{@}}.
Replacement fields contain expressions which are evaluated at run time.
For example:

@example
>>> who = 'nobody'
>>> nationality = 'Spanish'
>>> f'@{who.title()@} expects the @{nationality@} Inquisition!'
'Nobody expects the Spanish Inquisition!'
@end example

Any doubled curly braces (@code{@{@{} or @code{@}@}}) outside replacement fields
are replaced with the corresponding single curly brace:

@example
>>> print(f'@{@{...@}@}')
@{...@}
@end example

Other characters outside replacement fields are treated like in ordinary
string literals.
This means that escape sequences are decoded (except when a literal is
also marked as a raw string), and newlines are possible in triple-quoted
f-strings:

@example
>>> name = 'Galahad'
>>> favorite_color = 'blue'
>>> print(f'@{name@}:\t@{favorite_color@}')
Galahad:       blue
>>> print(rf"C:\Users\@{name@}")
C:\Users\Galahad
>>> print(f'@w{'}'Three shall be the number of the counting
... and the number of the counting shall be three.'@w{'}')
Three shall be the number of the counting
and the number of the counting shall be three.
@end example

Expressions in formatted string literals are treated like regular
Python expressions.
Each expression is evaluated in the context where the formatted string literal
appears, in order from left to right.
An empty expression is not allowed, and both @ref{14b5,,lambda} and
assignment expressions @code{:=} must be surrounded by explicit parentheses:

@example
>>> f'@{(half := 1/2)@}, @{half * 42@}'
'0.5, 21.0'
@end example

Reusing the outer f-string quoting type inside a replacement field is
permitted:

@example
>>> a = dict(x=2)
>>> f"abc @{a["x"]@} def"
'abc 2 def'
@end example

Backslashes are also allowed in replacement fields and are evaluated the same
way as in any other context:

@example
>>> a = ["a", "b", "c"]
>>> print(f"List a contains:\n@{"\n".join(a)@}")
List a contains:
a
b
c
@end example

It is possible to nest f-strings:

@example
>>> name = 'world'
>>> f'Repeated:@{f' hello @{name@}' * 3@}'
'Repeated: hello world hello world hello world'
@end example

Portable Python programs should not use more than 5 levels of nesting.

`CPython 実装の詳細:' CPython does not limit nesting of f-strings.

Replacement expressions can contain newlines in both single-quoted and
triple-quoted f-strings and they can contain comments.
Everything that comes after a @code{#} inside a replacement field
is a comment (even closing braces and quotes).
This means that replacement fields with comments must be closed in a
different line:

@example
>>> a = 2
>>> f"abc@{a  # This comment  @}"  continues until the end of the line
...       + 3@}"
'abc5'
@end example

After the expression, replacement fields may optionally contain:


@itemize *

@item 
a `debug specifier' -- an equal sign (@code{=}), optionally surrounded by
whitespace on one or both sides;

@item 
a `conversion specifier' -- @code{!s}, @code{!r} or @code{!a}; and/or

@item 
a `format specifier' prefixed with a colon (@code{:}).
@end itemize

See the @ref{22eb,,Standard Library section on f-strings}
for details on how these fields are evaluated.

As that section explains, `format specifiers' are passed as the second argument
to the @ref{199,,format()} function to format a replacement field value.
For example, they can be used to specify a field width and padding characters
using the @ref{4f9,,Format Specification Mini-Language}:

@example
>>> number = 14.3
>>> f'@{number:20.7f@}'
'          14.3000000'
@end example

Top-level format specifiers may include nested replacement fields:

@example
>>> field_size = 20
>>> precision = 7
>>> f'@{number:@{field_size@}.@{precision@}f@}'
'          14.3000000'
@end example

These nested fields may include their own conversion fields and
@ref{4f9,,format specifiers}:

@example
>>> number = 3
>>> f'@{number:@{field_size@}@}'
'                   3'
>>> f'@{number:@{field_size:05@}@}'
'00000000000000000003'
@end example

However, these nested fields may not include more deeply nested replacement
fields.

Formatted string literals cannot be used as @ref{22ec,,docstrings},
even if they do not include expressions:

@example
>>> def foo():
...     f"Not a docstring"
...
>>> print(foo.__doc__)
None
@end example


@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 498
PEP 498@footnote{https://peps.python.org/pep-0498/} -- Literal String Interpolation

@item 
@geindex Python Enhancement Proposals; PEP 701
PEP 701@footnote{https://peps.python.org/pep-0701/} -- Syntactic formalization of f-strings

@item 
@ref{833,,str.format()}, which uses a related format string mechanism.
@end itemize

@anchor{reference/lexical_analysis t-strings}@anchor{17fa}
@node t-strings,Formal grammar for f-strings,f-strings,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis id14}@anchor{22ed}@anchor{reference/lexical_analysis template-string-literals}@anchor{22ee}
@subsubsection t-strings



Added in version 3.14.


A `template string literal' or `t-string' is a string literal
that is prefixed with '@code{t}' or '@code{T}'.
These strings follow the same syntax rules as
@ref{19a,,formatted string literals}.
For differences in evaluation rules, see the
@ref{22ef,,Standard Library section on t-strings}

@node Formal grammar for f-strings,,t-strings,文字列およびバイト列リテラル
@anchor{reference/lexical_analysis formal-grammar-for-f-strings}@anchor{22f0}
@subsubsection Formal grammar for f-strings


F-strings are handled partly by the @ref{2292,,lexical analyzer}, which produces the
tokens @ref{22f1,,FSTRING_START}, @ref{22f2,,FSTRING_MIDDLE}
and @ref{22f3,,FSTRING_END}, and partly by the parser, which handles
expressions in the replacement field.
The exact way the work is split is a CPython implementation detail.

Correspondingly, the f-string grammar is a mix of
@ref{228d,,lexical and syntactic definitions}.

Whitespace is significant in these situations:


@itemize *

@item 
There may be no whitespace in @ref{22f1,,FSTRING_START} (between
the prefix and quote).

@item 
Whitespace in @ref{22f2,,FSTRING_MIDDLE} is part of the literal
string contents.

@item 
In @code{fstring_replacement_field}, if @code{f_debug_specifier} is present,
all whitespace after the opening brace until the @code{f_debug_specifier},
as well as whitespace immediately following @code{f_debug_specifier},
is retained as part of the expression.

`CPython 実装の詳細:' The expression is not handled in the tokenization phase; it is
retrieved from the source code using locations of the @code{@{} token
and the token after @code{=}.
@end itemize

The @code{FSTRING_MIDDLE} definition uses
@ref{228e,,negative lookaheads} (@code{!})
to indicate special characters (backslash, newline, @code{@{}, @code{@}}) and
sequences (@code{f_quote}).

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-fstring}@anchor{22f4}fstring:    @ref{22f5,,FSTRING_START} @ref{22f6,,fstring_middle}* @ref{22f7,,FSTRING_END}

@anchor{reference/lexical_analysis grammar-token-python-grammar-FSTRING_START}@anchor{22f5}FSTRING_START:      @ref{22f8,,fstringprefix} ("'" | '"' | "'@w{'}'" | '"""')
@anchor{reference/lexical_analysis grammar-token-python-grammar-FSTRING_END}@anchor{22f7}FSTRING_END:        @ref{22f9,,f_quote}
@anchor{reference/lexical_analysis grammar-token-python-grammar-fstringprefix}@anchor{22f8}fstringprefix:      <("f" | "fr" | "rf"), case-insensitive>
@anchor{reference/lexical_analysis grammar-token-python-grammar-f_debug_specifier}@anchor{22fa}f_debug_specifier:  '='
@anchor{reference/lexical_analysis grammar-token-python-grammar-f_quote}@anchor{22f9}f_quote:            <the quote character(s) used in FSTRING_START>

@anchor{reference/lexical_analysis grammar-token-python-grammar-fstring_middle}@anchor{22f6}fstring_middle:
   | @ref{22fb,,fstring_replacement_field}
   | @ref{22fc,,FSTRING_MIDDLE}
@anchor{reference/lexical_analysis grammar-token-python-grammar-FSTRING_MIDDLE}@anchor{22fc}FSTRING_MIDDLE:
   | (!"\" !@ref{22a9,,newline} !'@{' !'@}' !@ref{22f9,,f_quote}) @ref{22ac,,source_character}
   | @ref{22d7,,stringescapeseq}
   | "@{@{"
   | "@}@}"
   | <newline, in triple-quoted f-strings only>
@anchor{reference/lexical_analysis grammar-token-python-grammar-fstring_replacement_field}@anchor{22fb}fstring_replacement_field:
   | '@{' @ref{22fd,,f_expression} [@ref{22fa,,f_debug_specifier}] [@ref{22fe,,fstring_conversion}]
         [@ref{22ff,,fstring_full_format_spec}] '@}'
@anchor{reference/lexical_analysis grammar-token-python-grammar-fstring_conversion}@anchor{22fe}fstring_conversion:
   | "!" ("s" | "r" | "a")
@anchor{reference/lexical_analysis grammar-token-python-grammar-fstring_full_format_spec}@anchor{22ff}fstring_full_format_spec:
   | ':' @ref{2300,,fstring_format_spec}*
@anchor{reference/lexical_analysis grammar-token-python-grammar-fstring_format_spec}@anchor{2300}fstring_format_spec:
   | @ref{22fc,,FSTRING_MIDDLE}
   | @ref{22fb,,fstring_replacement_field}
@anchor{reference/lexical_analysis grammar-token-python-grammar-f_expression}@anchor{22fd}f_expression:
   | ','.(@ref{2301,,conditional_expression} | "*" @ref{2302,,or_expr})+ [","]
   | @ref{2303,,yield_expression}
@end example

@cartouche
@quotation 注釈 
In the above grammar snippet, the @code{f_quote} and @code{FSTRING_MIDDLE} rules
are context-sensitive -- they depend on the contents of @code{FSTRING_START}
of the nearest enclosing @code{fstring}.

Constructing a more traditional formal grammar from this template is left
as an exercise for the reader.
@end quotation
@end cartouche

The grammar for t-strings is identical to the one for f-strings, with `t'
instead of `f' at the beginning of rule and token names and in the prefix.

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-tstring}@anchor{2304}tstring:    TSTRING_START tstring_middle* TSTRING_END

<rest of the t-string grammar is omitted; see above>
@end example

@node 数値リテラル,Operators and delimiters,文字列およびバイト列リテラル,字句解析
@anchor{reference/lexical_analysis numbers}@anchor{22a1}@anchor{reference/lexical_analysis numeric-literals}@anchor{2305}
@subsection 数値リテラル


@geindex number
@geindex 数値リテラル
@geindex 整数リテラル
@geindex floating-point literal
@geindex 16進数リテラル
@geindex 8進数リテラル
@geindex 2進数リテラル
@geindex 10進数リテラル
@geindex 虚数リテラル
@geindex 複素数リテラル

@ref{22ba,,NUMBER} tokens represent numeric literals, of which there are
three types: integers, floating-point numbers, and imaginary numbers.

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-NUMBER}@anchor{2306}NUMBER: @ref{2307,,integer} | @ref{2308,,floatnumber} | @ref{2309,,imagnumber}
@end example

The numeric value of a numeric literal is the same as if it were passed as a
string to the @ref{19b,,int}, @ref{196,,float} or @ref{197,,complex} class
constructor, respectively.
Note that not all valid inputs for those constructors are also valid literals.

Numeric literals do not include a sign; a phrase like @code{-1} is
actually an expression composed of the unary operator '@code{-}' and the literal
@code{1}.

@geindex 0b;整数リテラル
@geindex 0o;整数リテラル
@geindex 0x;整数リテラル
@geindex _ (下線);in numeric literal

@menu
* 整数リテラル:: 
* Floating-point literals:: 
* 虚数 (imaginary) リテラル: 虚数 imaginary リテラル. 

@end menu

@node 整数リテラル,Floating-point literals,,数値リテラル
@anchor{reference/lexical_analysis integer-literals}@anchor{230a}@anchor{reference/lexical_analysis integers}@anchor{230b}
@subsubsection 整数リテラル


Integer literals denote whole numbers. For example:

@example
7
3
2147483647
@end example

There is no limit for the length of integer literals apart from what can be
stored in available memory:

@example
7922816251426433759354395033679228162514264337593543950336
@end example

Underscores can be used to group digits for enhanced readability,
and are ignored for determining the numeric value of the literal.
For example, the following literals are equivalent:

@example
100_000_000_000
100000000000
1_00_00_00_00_000
@end example

Underscores can only occur between digits.
For example, @code{_123}, @code{321_}, and @code{123__321} are `not' valid literals.

Integers can be specified in binary (base 2), octal (base 8), or hexadecimal
(base 16) using the prefixes @code{0b}, @code{0o} and @code{0x}, respectively.
Hexadecimal digits 10 through 15 are represented by letters @code{A}-@code{F},
case-insensitive.  For example:

@example
0b100110111
0b_1110_0101
0o177
0o377
0xdeadbeef
0xDead_Beef
@end example

An underscore can follow the base specifier.
For example, @code{0x_1f} is a valid literal, but @code{0_x1f} and @code{0x__1f} are
not.

Leading zeros in a non-zero decimal number are not allowed.
For example, @code{0123} is not a valid literal.
This is for disambiguation with C-style octal literals, which Python used
before version 3.0.

Formally, integer literals are described by the following lexical definitions:

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-integer}@anchor{2307}integer:      @ref{230c,,decinteger} | @ref{230d,,bininteger} | @ref{230e,,octinteger} | @ref{230f,,hexinteger} | @ref{2310,,zerointeger}
@anchor{reference/lexical_analysis grammar-token-python-grammar-decinteger}@anchor{230c}decinteger:   @ref{2311,,nonzerodigit} (["_"] @ref{2312,,digit})*
@anchor{reference/lexical_analysis grammar-token-python-grammar-bininteger}@anchor{230d}bininteger:   "0" ("b" | "B") (["_"] @ref{2313,,bindigit})+
@anchor{reference/lexical_analysis grammar-token-python-grammar-octinteger}@anchor{230e}octinteger:   "0" ("o" | "O") (["_"] @ref{2314,,octdigit})+
@anchor{reference/lexical_analysis grammar-token-python-grammar-hexinteger}@anchor{230f}hexinteger:   "0" ("x" | "X") (["_"] @ref{2315,,hexdigit})+
@anchor{reference/lexical_analysis grammar-token-python-grammar-zerointeger}@anchor{2310}zerointeger:  "0"+ (["_"] "0")*
@anchor{reference/lexical_analysis grammar-token-python-grammar-nonzerodigit}@anchor{2311}nonzerodigit: "1"..."9"
@anchor{reference/lexical_analysis grammar-token-python-grammar-digit}@anchor{2312}digit:        "0"..."9"
@anchor{reference/lexical_analysis grammar-token-python-grammar-bindigit}@anchor{2313}bindigit:     "0" | "1"
@anchor{reference/lexical_analysis grammar-token-python-grammar-octdigit}@anchor{2314}octdigit:     "0"..."7"
@anchor{reference/lexical_analysis grammar-token-python-grammar-hexdigit}@anchor{2315}hexdigit:     @ref{2312,,digit} | "a"..."f" | "A"..."F"
@end example


バージョン 3.6 で変更: グループ化を目的としたリテラル中のアンダースコアが許されるようになりました。


@geindex . (ドット);in numeric literal
@geindex e;in numeric literal
@geindex _ (下線);in numeric literal

@node Floating-point literals,虚数 imaginary リテラル,整数リテラル,数値リテラル
@anchor{reference/lexical_analysis floating}@anchor{2316}@anchor{reference/lexical_analysis floating-point-literals}@anchor{2317}
@subsubsection Floating-point literals


Floating-point (float) literals, such as @code{3.14} or @code{1.5}, denote
@ref{2318,,approximations of real numbers}.

They consist of `integer' and `fraction' parts, each composed of decimal digits.
The parts are separated by a decimal point, @code{.}:

@example
2.71828
4.0
@end example

Unlike in integer literals, leading zeros are allowed.
For example, @code{077.010} is legal, and denotes the same number as @code{77.01}.

As in integer literals, single underscores may occur between digits to help
readability:

@example
96_485.332_123
3.14_15_93
@end example

Either of these parts, but not both, can be empty. For example:

@example
10.  # (equivalent to 10.0)
.001  # (equivalent to 0.001)
@end example

Optionally, the integer and fraction may be followed by an `exponent':
the letter @code{e} or @code{E}, followed by an optional sign, @code{+} or @code{-},
and a number in the same format as the integer and fraction parts.
The @code{e} or @code{E} represents "times ten raised to the power of":

@example
1.0e3  # (represents 1.0×10³, or 1000.0)
1.166e-5  # (represents 1.166×10⁻⁵, or 0.00001166)
6.02214076e+23  # (represents 6.02214076×10²³, or 602214076000000000000000.)
@end example

In floats with only integer and exponent parts, the decimal point may be
omitted:

@example
1e3  # (equivalent to 1.e3 and 1.0e3)
0e0  # (equivalent to 0.)
@end example

Formally, floating-point literals are described by the following
lexical definitions:

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-floatnumber}@anchor{2308}floatnumber:
   | @ref{2319,,digitpart} "." [@ref{2319,,digitpart}] [@ref{231a,,exponent}]
   | "." @ref{2319,,digitpart} [@ref{231a,,exponent}]
   | @ref{2319,,digitpart} @ref{231a,,exponent}
@anchor{reference/lexical_analysis grammar-token-python-grammar-digitpart}@anchor{2319}digitpart: @ref{2312,,digit} (["_"] @ref{2312,,digit})*
@anchor{reference/lexical_analysis grammar-token-python-grammar-exponent}@anchor{231a}exponent:  ("e" | "E") ["+" | "-"] @ref{2319,,digitpart}
@end example


バージョン 3.6 で変更: グループ化を目的としたリテラル中のアンダースコアが許されるようになりました。


@geindex j;in numeric literal

@node 虚数 imaginary リテラル,,Floating-point literals,数値リテラル
@anchor{reference/lexical_analysis imaginary}@anchor{231b}@anchor{reference/lexical_analysis imaginary-literals}@anchor{231c}
@subsubsection 虚数 (imaginary) リテラル


Python has @ref{1fdc,,complex number} objects, but no complex
literals.
Instead, `imaginary literals' denote complex numbers with a zero
real part.

For example, in math, the complex number 3+4.2`i' is written
as the real number 3 added to the imaginary number 4.2`i'.
Python uses a similar syntax, except the imaginary unit is written as @code{j}
rather than `i':

@example
3+4.2j
@end example

This is an expression composed
of the @ref{230b,,integer literal} @code{3},
the @ref{228c,,operator} '@code{+}',
and the @ref{231b,,imaginary literal} @code{4.2j}.
Since these are three separate tokens, whitespace is allowed between them:

@example
3 + 4.2j
@end example

No whitespace is allowed `within' each token.
In particular, the @code{j} suffix, may not be separated from the number
before it.

The number before the @code{j} has the same syntax as a floating-point literal.
Thus, the following are valid imaginary literals:

@example
4.2j
3.14j
10.j
.001j
1e100j
3.14e-10j
3.14_15_93j
@end example

Unlike in a floating-point literal the decimal point can be omitted if the
imaginary number only has an integer part.
The number is still evaluated as a floating-point number, not an integer:

@example
10j
0j
1000000000000000000000000j   # equivalent to 1e+24j
@end example

The @code{j} suffix is case-insensitive.
That means you can use @code{J} instead:

@example
3.14J   # equivalent to 3.14j
@end example

Formally, imaginary literals are described by the following lexical definition:

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-imagnumber}@anchor{2309}imagnumber: (@ref{2308,,floatnumber} | @ref{2319,,digitpart}) ("j" | "J")
@end example
@anchor{reference/lexical_analysis delimiters}@anchor{228b}@anchor{reference/lexical_analysis operators}@anchor{228c}
@node Operators and delimiters,,数値リテラル,字句解析
@anchor{reference/lexical_analysis lexical-ellipsis}@anchor{22ca}@anchor{reference/lexical_analysis operators-and-delimiters}@anchor{231d}
@subsection Operators and delimiters


@geindex 演算子
@geindex デリミタ

The following grammar defines `operator' and `delimiter' tokens,
that is, the generic @ref{228a,,OP} token type.
A @ref{231e,,list of these tokens and their names}
is also available in the @code{token} module documentation.

@example
@anchor{reference/lexical_analysis grammar-token-python-grammar-OP}@anchor{231f}OP:
   | assignment_operator
   | bitwise_operator
   | comparison_operator
   | enclosing_delimiter
   | other_delimiter
   | arithmetic_operator
   | "..."
   | other_op

@anchor{reference/lexical_analysis grammar-token-python-grammar-assignment_operator}@anchor{2320}assignment_operator:   "+=" | "-=" | "*=" | "**=" | "/="  | "//=" | "%=" |
                       "&=" | "|=" | "^=" | "<<=" | ">>=" | "@@="  | ":="
@anchor{reference/lexical_analysis grammar-token-python-grammar-bitwise_operator}@anchor{2321}bitwise_operator:      "&"  | "|"  | "^"  | "~"   | "<<"  | ">>"
@anchor{reference/lexical_analysis grammar-token-python-grammar-comparison_operator}@anchor{2322}comparison_operator:   "<=" | ">=" | "<"  | ">"   | "=="  | "!="
@anchor{reference/lexical_analysis grammar-token-python-grammar-enclosing_delimiter}@anchor{2323}enclosing_delimiter:   "("  | ")"  | "["  | "]"   | "@{"   | "@}"
@anchor{reference/lexical_analysis grammar-token-python-grammar-other_delimiter}@anchor{2324}other_delimiter:       ","  | ":"  | "!"  | ";"   | "="   | "->"
@anchor{reference/lexical_analysis grammar-token-python-grammar-arithmetic_operator}@anchor{2325}arithmetic_operator:   "+"  | "-"  | "**" | "*"   | "//"  | "/"   | "%"
@anchor{reference/lexical_analysis grammar-token-python-grammar-other_op}@anchor{2326}other_op:              "."  | "@@"
@end example

@cartouche
@quotation 注釈 
Generally, `operators' are used to combine @ref{2327,,expressions},
while `delimiters' serve other purposes.
However, there is no clear, formal distinction between the two categories.

Some tokens can serve as either operators or delimiters, depending on usage.
For example, @code{*} is both the multiplication operator and a delimiter used
for sequence unpacking, and @code{@@} is both the matrix multiplication and
a delimiter that introduces decorators.

For some tokens, the distinction is unclear.
For example, some people consider @code{.}, @code{(}, and @code{)} to be delimiters, while others
see the @ref{dca,,getattr()} operator and the function call operator(s).

Some of Python's operators, like @code{and}, @code{or}, and @code{not in}, use
@ref{2289,,keyword} tokens rather than "symbols" (operator tokens).
@end quotation
@end cartouche

A sequence of three consecutive periods (@code{...}) has a special
meaning as an @ref{2328,,Ellipsis} literal.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node データモデル,実行モデル,字句解析,Python 言語リファレンス
@anchor{reference/datamodel doc}@anchor{2329}@anchor{reference/datamodel data-model}@anchor{232a}@anchor{reference/datamodel datamodel}@anchor{1d5a}@anchor{reference/datamodel translation-repo}@anchor{232b}
@section データモデル


@menu
* オブジェクト、値、および型:: 
* 標準型の階層:: 
* 特殊メソッド名:: 
* コルーチン:: 

@end menu

@node オブジェクト、値、および型,標準型の階層,,データモデル
@anchor{reference/datamodel objects}@anchor{232c}@anchor{reference/datamodel objects-values-and-types}@anchor{232d}
@subsection オブジェクト、値、および型


@geindex object
@geindex データ

`Objects' are Python's abstraction for data.  All data in a Python program
is represented by objects or by relations between objects. Even code is
represented by objects.

@geindex 組み込み関数;id
@geindex 組み込み関数;type
@geindex オブジェクトの同一性
@geindex オブジェクトの値
@geindex オブジェクトの型
@geindex 変更可能なオブジェクト
@geindex 変更不可能なオブジェクト

すべてのオブジェクトは、同一性 (identity)、型、値をもっています。 `同一性' は生成されたあとは変更されません。これはオブジェクトのアドレスのようなものだと考えられるかもしれません。 @ref{34c,,is} 演算子は2つのオブジェクトの同一性を比較します。 @ref{163c,,id()} 関数は同一性を表す整数を返します。

CPython では、@code{id(x)} は @code{x} が格納されているメモリ上のアドレスを返します。

オブジェクトの型はオブジェクトがサポートする操作 (例: @ref{840,,len()} をサポートするか) と、オブジェクトが取りうる値を決定します。 @ref{f44,,type()} 関数はオブジェクトの型 (型自体もオブジェクトです) を返します。同一性と同じく、オブジェクトの型(`type') も変更不可能です。 @footnote{
特定の条件が満たされた場合、オブジェクトの type を変更することが `できます' 。これは、正しく扱われなかった場合にとても奇妙な動作を引き起こすので、一般的には良い考えではありません。
}

オブジェクトによっては `値' を変更することが可能です。値を変更できるオブジェクトのことを `mutable' と呼びます。生成後に値を変更できないオブジェクトのことを `immutable' と呼びます。(mutable なオブジェクトへの参照を格納している immutableなコンテナオブジェクトの値は、その格納しているオブジェクトの値が変化した時に変化しますが、コンテナがどのオブジェクトを格納しているのかが変化しないのであれば immutable だと考えることができます。したがって、immutable かどうかは値が変更可能かどうかと完全に一致するわけではありません) オブジェクトが mutable かどうかはその型によって決まります。例えば、数値型、文字列型とタプル型のインスタンスは immutable で、dict や list は mutable です。

@geindex garbage collection
@geindex 参照カウント
@geindex 到達不能オブジェクト

オブジェクトを明示的に破壊することはできません; しかし、オブジェクトに到達不能 (unreachable) になると、ガベージコレクション (garbage-collection) によって処理されるかもしれません。ガベージコレクションを遅らせたり、全く行わない実装も許されています --- 到達可能なオブジェクトを処理してしまわないかぎり、ガベージコレクションをどう実装するかは実装品質の問題です。

現在の CPython 実装では参照カウント (reference-counting) 方式を使っており、(オプションとして) 循環参照を行っているガベージオブジェクトを遅延検出します。この実装ではほとんどのオブジェクトを到達不能になると同時に処理することができますが、循環参照を含むガベージオブジェクトの収集が確実に行われるよう保証しているわけではありません。循環参照を持つガベージオブジェクト収集の制御については、 @ref{64,,gc} モジュールを参照してください。 CPython以外の実装は別の方式を使っており、CPythonも将来は別の方式を使うかもしれません。オブジェクトが到達不能になったときに即座に終了処理されることに頼らないでください (ですからファイルは必ず明示的に閉じてください)。

Note that the use of the implementation's tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a @ref{8f8,,try}...@ref{1ab,,except} statement may keep
objects alive.

Some objects contain references to "external" resources such as open files or
windows.  It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a @code{close()} method. Programs are strongly recommended to explicitly
close such objects.  The @ref{8f8,,try}...@ref{1b0,,finally} statement
and the @ref{186,,with} statement provide convenient ways to do this.

@geindex コンテナ

他のオブジェクトに対する参照をもつオブジェクトもあります; これらは `コンテナ (container)' と呼ばれます。コンテナオブジェクトの例として、タプル、リスト、および辞書が挙げられます。オブジェクトへの参照自体がコンテナの値の一部です。ほとんどの場合、コンテナの値というと、コンテナに入っているオブジェクトの値のことを指し、それらオブジェクトのアイデンティティではありません; しかしながら、コンテナの変更可能性について述べる場合、今まさにコンテナに入っているオブジェクトのアイデンティティのことを指します。したがって、 (タプルのように) 変更不能なオブジェクトが変更可能なオブジェクトへの参照を含む場合、その値が変化するのは変更可能なオブジェクトが変更された時、ということになります。

Types affect almost all aspects of object behavior.  Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed.
For example, after @code{a = 1; b = 1}, `a' and `b' may or may not refer to
the same object with the value one, depending on the implementation.
This is because @ref{19b,,int} is an immutable type, so the reference to @code{1}
can be reused. This behaviour depends on the implementation used, so should
not be relied upon, but is something to be aware of when making use of object
identity tests.
However, after @code{c = []; d = []}, `c' and `d' are guaranteed to refer to two
different, unique, newly created empty lists. (Note that @code{e = f = []} assigns
the `same' object to both `e' and `f'.)

@node 標準型の階層,特殊メソッド名,オブジェクト、値、および型,データモデル
@anchor{reference/datamodel the-standard-type-hierarchy}@anchor{232e}@anchor{reference/datamodel types}@anchor{232f}
@subsection 標準型の階層


@geindex type
@geindex データ;type
@geindex type;階層
@geindex 拡張;module
@geindex C;言語

以下は Python に組み込まれている型のリストです。(実装によって、C、Java、またはその他の言語で書かれた) 拡張モジュールで、その他の型が定義されていることがあります。新たな型 (有理数や、整数を効率的に記憶する配列、など) の追加は、たいてい標準ライブラリを通して提供されますが、将来のバージョンの Python では、型の階層構造にこのような追加がなされるかもしれません。

@geindex 属性
@geindex 特殊;属性
@geindex 汎用;特殊;属性

以下に説明する型のいくつかには、 '特殊属性 (special attribute)' を列挙した段落があります。これらの属性は実装へのアクセス手段を提供するもので、一般的な用途に利用するためのものではありません。特殊属性の定義は将来変更される可能性があります。

@menu
* None:: 
* NotImplemented:: 
* Ellipsis:: 
* numbers.Number: numbers Number. 
* シーケンス型 (sequence): シーケンス型 sequence. 
* 集合型: 集合型<2>. 
* マッピング型 (mapping): マッピング型 mapping. 
* 呼び出し可能型 (callable type): 呼び出し可能型 callable type. 
* モジュール: モジュール<3>. 
* カスタムクラス型:: 
* クラスインスタンス (class instance): クラスインスタンス class instance. 
* I/O オブジェクト (ファイルオブジェクトの別名): I/O オブジェクト ファイルオブジェクトの別名. 
* 内部型 (internal type): 内部型 internal type. 

@end menu

@node None,NotImplemented,,標準型の階層
@anchor{reference/datamodel none}@anchor{2330}
@subsubsection None


@geindex object;None

この型には単一の値しかありません。この値を持つオブジェクトはただ一つしか存在しません。このオブジェクトは組み込み名 @code{None} でアクセスされます。このオブジェクトは、様々な状況で値が存在しないことをしめします。例えば、明示的に値を返さない関数は @code{None} を返します。 @code{None} の真値 (truth value) は偽 (false) です。

@node NotImplemented,Ellipsis,None,標準型の階層
@anchor{reference/datamodel notimplemented}@anchor{2331}
@subsubsection NotImplemented


@geindex object;NotImplemented

This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name @ref{1a2,,NotImplemented}. Numeric methods
and rich comparison methods should return this value if they do not implement the
operation for the operands provided.  (The interpreter will then try the
reflected operation, or some other fallback, depending on the operator.)  It
should not be evaluated in a boolean context.

詳細は @ref{2332,,算術演算の実装} を参照してください。


バージョン 3.9 で変更: Evaluating @ref{1a2,,NotImplemented} in a boolean context was deprecated.



バージョン 3.14 で変更: Evaluating @ref{1a2,,NotImplemented} in a boolean context now raises a @ref{198,,TypeError}.
It previously evaluated to @ref{e07,,True} and emitted a @ref{1a3,,DeprecationWarning}
since Python 3.9.


@node Ellipsis,numbers Number,NotImplemented,標準型の階層
@anchor{reference/datamodel ellipsis}@anchor{2333}
@subsubsection Ellipsis


@geindex object;Ellipsis
@geindex ...;ellipsisリテラル

この型には単一の値しかありません。この値を持つオブジェクトはただ一つしか存在しません。このオブジェクトはリテラル @code{...} またはPythonで決められている名前 @code{Ellipsis} でアクセスされます。真理値は真 (true)です。

@node numbers Number,シーケンス型 sequence,Ellipsis,標準型の階層
@anchor{reference/datamodel numbers-number}@anchor{2334}
@subsubsection @code{numbers.Number}


@geindex object;数値

数値リテラルによって作成されたり、算術演算や組み込みの算術関数によって返されるオブジェクトです。数値オブジェクトは変更不能です; 一度値が生成されると、二度と変更されることはありません。Python の数値オブジェクトはいうまでもなく数学で言うところの数値と強く関係していますが、コンピュータ内で数値を表現する際に伴う制限を受けています。

@ref{82f,,__repr__()}  と @ref{830,,__str__()} から計算された数値クラスの文字列表現には次のような特性があります:


@itemize *

@item 
その文字列は、クラスコンストラクタに渡したときに、元の数値の値を持つオブジェクトを生成する有効な数値リテラルです。

@item 
できるなら、10を底として表現されます。

@item 
小数点の前にある 1 つのゼロを除いて、上に連なるゼロは表示されません。

@item 
小数点の後にある 1 つのゼロを除いて、下に連なるゼロは表示されません。

@item 
符号は数値が負数のときのみ表示されます。
@end itemize

Python distinguishes between integers, floating-point numbers, and complex
numbers:

@menu
* numbers.Integral (整数): numbers Integral 整数. 
* numbers.Real (float) (実数): numbers Real float 実数. 
* numbers.Complex (complex): numbers Complex complex. 

@end menu

@node numbers Integral 整数,numbers Real float 実数,,numbers Number
@anchor{reference/datamodel numbers-integral}@anchor{2335}
@subsubsection @code{numbers.Integral} (整数)


@geindex object;整数

整数型は、整数(正の数および負の数)を表す数学的集合内における要素を表現する型です。

@cartouche
@quotation 注釈 
@geindex 整数;表現

整数表現に関する規則は、負の整数を含むシフト演算やマスク演算において、最も有意義な解釈ができるように意図されています。
@end quotation
@end cartouche

整数には 2 種類あります:


@table @asis

@item 整数 (@ref{19b,,int})

無制限の範囲の数を表現しますが、利用可能な (仮想) メモリサイズの制限のみを受けます。シフト演算やマスク演算のために2進数表現を持つと想定されます。負の数は符号ビットが左に無限に延びているような錯覚を与える 2 の補数表現の変型で表されます。

@item ブール値 (@ref{3c3,,bool})

@geindex object;Boolean
@geindex False
@geindex True

真偽値の False と True を表します。@code{False} と @code{True} を表す 2 つのオブジェクトのみがブール値オブジェクトです。ブール型は整数型の派生型であり、ほとんどの状況でそれぞれ 0 と 1 のように振る舞いますが、例外として文字列に変換されたときはそれぞれ @code{"False"} および @code{"True"} という文字列が返されます。
@end table

@node numbers Real float 実数,numbers Complex complex,numbers Integral 整数,numbers Number
@anchor{reference/datamodel datamodel-float}@anchor{2318}@anchor{reference/datamodel numbers-real-float}@anchor{2336}
@subsubsection @code{numbers.Real} (@code{float}) (実数)


@geindex object;浮動小数点
@geindex 浮動小数点;number
@geindex C;言語
@geindex Java;言語

These represent machine-level double precision floating-point numbers. You are
at the mercy of the underlying machine architecture (and C or Java
implementation) for the accepted range and handling of overflow. Python does not
support single-precision floating-point numbers; the savings in processor and
memory usage that are usually the reason for using these are dwarfed by the
overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating-point numbers.

@node numbers Complex complex,,numbers Real float 実数,numbers Number
@anchor{reference/datamodel numbers-complex-complex}@anchor{2337}
@subsubsection @code{numbers.Complex} (@code{complex})


@geindex object;複素数
@geindex 複素数;number

These represent complex numbers as a pair of machine-level double precision
floating-point numbers.  The same caveats apply as for floating-point numbers.
The real and imaginary parts of a complex number @code{z} can be retrieved through
the read-only attributes @code{z.real} and @code{z.imag}.

@node シーケンス型 sequence,集合型<2>,numbers Number,標準型の階層
@anchor{reference/datamodel datamodel-sequences}@anchor{2338}@anchor{reference/datamodel sequences}@anchor{2339}
@subsubsection シーケンス型 (sequence)


@geindex 組み込み関数;len
@geindex object;sequence
@geindex インデックス操作
@geindex 要素の選択
@geindex 添字表記

These represent finite ordered sets indexed by non-negative numbers. The
built-in function @ref{840,,len()} returns the number of items of a sequence. When
the length of a sequence is `n', the index set contains the numbers 0, 1,
..., `n'-1.  Item `i' of sequence `a' is selected by @code{a[i]}. Some sequences,
including built-in sequences, interpret negative subscripts by adding the
sequence length. For example, @code{a[-2]} equals @code{a[n-2]}, the second to last
item of sequence a with length @code{n}.

The resulting value must be a nonnegative integer less than the number of items
in the sequence. If it is not, an @ref{174e,,IndexError} is raised.

@geindex スライス
@geindex start (スライスオブジェクトの属性)
@geindex stop (スライスオブジェクトの属性)
@geindex step (スライスオブジェクトの属性)

Sequences also support slicing: @code{a[start:stop]} selects all items with index `k' such
that `start' @code{<=} `k' @code{<} `stop'.  When used as an expression, a slice is a
sequence of the same type. The comment above about negative subscripts also applies
to negative slice positions.
Note that no error is raised if a slice position is less than zero or larger
than the length of the sequence.

If `start' is missing or @ref{885,,None}, slicing behaves as if `start' was zero.
If `stop' is missing or @code{None}, slicing behaves as if `stop' was equal to
the length of the sequence.

シーケンスによっては、第三の "ステップ (step)" パラメタを持つ "拡張スライス (extended slice)" もサポートしています: @code{a[i:j:k]} は、 @code{x = i + n*k}, `n' @code{>=} @code{0} かつ `i' @code{<=} `x' @code{<} `j' であるようなインデクス `x' を持つような `a' 全ての要素を選択します。

シーケンスは、変更可能なものか、そうでないかで区別されています:

@menu
* 変更不能なシーケンス (immutable sequence): 変更不能なシーケンス immutable sequence. 
* 変更可能なシーケンス型 (mutable sequence): 変更可能なシーケンス型 mutable sequence. 

@end menu

@node 変更不能なシーケンス immutable sequence,変更可能なシーケンス型 mutable sequence,,シーケンス型 sequence
@anchor{reference/datamodel immutable-sequences}@anchor{233a}
@subsubsection 変更不能なシーケンス (immutable sequence)


@geindex object;変更不能なシーケンス
@geindex object;immutable

変更不能なシーケンス型のオブジェクトは、一度生成されるとその値を変更することができません。 (オブジェクトに他のオブジェクトへの参照が入っている場合、参照されているオブジェクトは変更可能なオブジェクトでもよく、その値は変更される可能性があります; しかし、変更不能なオブジェクトが直接参照しているオブジェクトの集合自体は、変更することができません。)

以下の型は変更不能なシーケンス型です:

@geindex string;immutable sequences


@table @asis

@item 文字列型 (string)

@geindex 組み込み関数;chr
@geindex 組み込み関数;ord
@geindex 文字(str型)
@geindex string;要素
@geindex Unicode 文字列型

A string (@ref{169,,str}) is a sequence of values that represent
`characters', or more formally, `Unicode code points'.
All the code points in the range @code{0} to @code{0x10FFFF} can be
represented in a string.

Python doesn't have a dedicated `character' type.
Instead, every code point in the string is represented as a string
object with length @code{1}.

The built-in function @ref{233b,,ord()}
converts a code point from its string form to an integer in the
range @code{0} to @code{0x10FFFF}; @ref{19ef,,chr()} converts an integer in the range
@code{0} to @code{0x10FFFF} to the corresponding length @code{1} string object.
@ref{ad2,,str.encode()} can be used to convert a @ref{169,,str} to
@ref{192,,bytes} using the given text encoding, and
@ref{ad3,,bytes.decode()} can be used to achieve the opposite.

@item タプル型 (tuple)

@geindex object;tuple
@geindex 単一要素の;tuple
@geindex 空の;tuple

The items of a @ref{614,,tuple} are arbitrary Python objects. Tuples of two or
more items are formed by comma-separated lists of expressions.  A tuple
of one item (a 'singleton') can be formed by affixing a comma to an
expression (an expression by itself does not create a tuple, since
parentheses must be usable for grouping of expressions).  An empty
tuple can be formed by an empty pair of parentheses.

@item bytes

@geindex bytes
@geindex バイト

A @ref{192,,bytes} object is an immutable array.  The items are 8-bit bytes,
represented by integers in the range 0 <= x < 256.  Bytes literals
(like @code{b'abc'}) and the built-in @ref{192,,bytes()} constructor
can be used to create bytes objects.  Also, bytes objects can be
decoded to strings via the @ref{ad3,,decode()} method.
@end table

@node 変更可能なシーケンス型 mutable sequence,,変更不能なシーケンス immutable sequence,シーケンス型 sequence
@anchor{reference/datamodel mutable-sequences}@anchor{233c}
@subsubsection 変更可能なシーケンス型 (mutable sequence)


@geindex object;変更可能なシーケンス
@geindex object;mutable
@geindex 代入;statement
@geindex 添字表記
@geindex スライス

変更可能なシーケンスは、作成した後で変更することができます。変更可能なシーケンスでは、添字表記やスライス表記を使って指定された要素に代入を行うことができ、 @ref{1b1f,,del} (delete) 文を使って要素を削除することができます。

@cartouche
@quotation 注釈 
@geindex module;array

@geindex module;collections

The @ref{1e,,collections} and @ref{8,,array} module provide
additional examples of mutable sequence types.
@end quotation
@end cartouche

Python に最初から組み込まれている変更可能なシーケンス型は、今のところ二つです:


@table @asis

@item リスト型 (list)

@geindex object;list

リストの要素は任意の Python オブジェクトにできます。リストは、角括弧の中にカンマで区切られた式を並べて作ります。 (長さが 0 や 1 のシーケンスを作るために特殊な場合分けは必要ないことに注意してください。)

@item バイト配列

@geindex bytearray

bytearray オブジェクトは変更可能な配列です。組み込みの @ref{344,,bytearray()} コンストラクタによって作成されます。変更可能なことを除けば (つまりハッシュ化できない)、 byte array は変更不能な @ref{192,,bytes} オブジェクトと同じインターフェースと機能を提供します。
@end table

@node 集合型<2>,マッピング型 mapping,シーケンス型 sequence,標準型の階層
@anchor{reference/datamodel set-types}@anchor{233d}
@subsubsection 集合型


@geindex 組み込み関数;len
@geindex object;集合型

集合型は、順序のない、ユニークで不変なオブジェクトの有限集合を表現します。そのため、(配列の)添字を使ったインデックスアクセスはできません。ただし、イテレートは可能で、組み込み関数 @ref{840,,len()} は集合の要素数を返します。集合型の一般的な使い方は、集合に属しているかの高速なテスト、シーケンスからの重複の排除、共通集合・和集合・差・対称差といった数学的な演算の計算です。

集合の要素には、辞書のキーと同じ普遍性に関するルールが適用されます。数値型は通常の数値比較のルールに従うことに注意してください。もし2つの数値の比較結果が同値である(例えば、 @code{1} と @code{1.0})なら、そのうちの1つのみを集合に含めることができます。

現在、2つの組み込み集合型があります:


@table @asis

@item 集合型

@geindex object;集合

可変な集合型です。組み込みの @ref{184,,set()} コンストラクタで作成され、後から @ref{233e,,add()} などのいくつかのメソッドで更新できます。

@item Frozen set 型

@geindex object;frozenset

不変な集合型です。組み込みの @ref{7f2,,frozenset()} コンストラクタによって作成されます。 frozenset は不変で @ref{824,,ハッシュ可能} なので、別の集合型の要素になったり、辞書のキーにすることができます。
@end table

@node マッピング型 mapping,呼び出し可能型 callable type,集合型<2>,標準型の階層
@anchor{reference/datamodel datamodel-mappings}@anchor{233f}@anchor{reference/datamodel mappings}@anchor{2340}
@subsubsection マッピング型 (mapping)


@geindex 組み込み関数;len
@geindex 添字表記
@geindex object;mapping

任意のインデクス集合でインデクス化された、オブジェクトからなる有限の集合を表現します。添字表記 @code{a[k]} は、 @code{k} でインデクス指定された要素を @code{a} から選択します; 選択された要素は式の中で使うことができ、代入や @ref{1b1f,,del} 文の対象にすることができます。組み込み関数 @ref{840,,len()} は、マッピング内の要素数を返します。

Python に最初から組み込まれているマッピング型は、今のところ一つだけです:

@menu
* 辞書型 (dictionary): 辞書型 dictionary<2>. 

@end menu

@node 辞書型 dictionary<2>,,,マッピング型 mapping
@anchor{reference/datamodel dictionaries}@anchor{2341}
@subsubsection 辞書型 (dictionary)


@geindex object;dictionary

ほぼ任意の値でインデクスされたオブジェクトからなる有限の集合を表します。
キー (key) として使えない値の唯一の型は、リストや辞書、そしてオブジェクトの同一性でなく値で比較されるその他の変更可能な型です。
これは、辞書型を効率的に実装する上で、キーのハッシュ値が不変である必要があるためです。
数値型をキーに使う場合、キー値は通常の数値比較における規則に従います: 二つの値が等しくなる場合 (例えば @code{1} と @code{1.0})、互いに同じ辞書のエントリを表すインデクスとして使うことができます。

辞書は挿入の順序を保持します。つまり、キーは辞書に追加された順番に生成されていきます。既存のキーを置き換えても、キーの順序は変わりません。キーを削除したのちに再挿入すると、元の場所ではなく辞書の最後に追加されます。

Dictionaries are mutable; they can be created by the @code{@{@}} notation (see
section @ref{f7f,,辞書表示}).

@geindex module;dbm.ndbm
@geindex module;dbm.gnu

拡張モジュール @ref{38,,dbm.ndbm} 、 @ref{37,,dbm.gnu} は、 @ref{1e,,collections} モジュールのように、別のマッピング型の例を提供しています。


バージョン 3.7 で変更: Pythonのバージョン3.6では、辞書は挿入順序を保持しませんでした。CPython 3.6では挿入順序は保持されましたが、それは策定された言語の仕様というより、その当時の実装の細部とみなされていました。


@node 呼び出し可能型 callable type,モジュール<3>,マッピング型 mapping,標準型の階層
@anchor{reference/datamodel callable-types}@anchor{2342}
@subsubsection 呼び出し可能型 (callable type)


@geindex object;callable
@geindex 関数;call
@geindex 関数呼び出し
@geindex 関数;引数 (argument)

関数呼び出し操作 (@ref{f7d,,呼び出し (call)} 参照) を行うことができる型です:

@menu
* ユーザ定義関数 (user-defined function): ユーザ定義関数 user-defined function. 
* インスタンスメソッド:: 
* ジェネレータ関数 (generator function): ジェネレータ関数 generator function. 
* コルーチン関数 (coroutine function): コルーチン関数 coroutine function. 
* 非同期ジェネレータ関数 (asynchronous generator function): 非同期ジェネレータ関数 asynchronous generator function. 
* 組み込み関数 (built-in function): 組み込み関数 built-in function. 
* 組み込みメソッド (built-in method): 組み込みメソッド built-in method. 
* クラス: クラス<2>. 
* クラスのインスタンス:: 

@end menu

@node ユーザ定義関数 user-defined function,インスタンスメソッド,,呼び出し可能型 callable type
@anchor{reference/datamodel user-defined-funcs}@anchor{59c}@anchor{reference/datamodel user-defined-functions}@anchor{2343}
@subsubsection ユーザ定義関数 (user-defined function)


@geindex ユーザ定義の;関数
@geindex object;関数
@geindex object;ユーザ定義関数

ユーザ定義関数オブジェクトは、関数定義を行うことで生成されます (@ref{2018,,関数定義} 参照)。関数は、仮引数 (formal parameter) リストと同じ数の要素が入った引数リストとともに呼び出されます。

@menu
* Special read-only attributes:: 
* Special writable attributes:: 

@end menu

@node Special read-only attributes,Special writable attributes,,ユーザ定義関数 user-defined function
@anchor{reference/datamodel special-read-only-attributes}@anchor{2344}
@subsubsection Special read-only attributes


@geindex __builtins__ (function attribute)
@geindex __closure__ (関数属性)
@geindex __globals__ (関数属性)
@geindex グローバル;namespace


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

意味

@item

@geindex __builtins__ (function の属性)
@anchor{reference/datamodel function __builtins__}@anchor{2345}
@deffn {の属性} function.__builtins__
@end deffn

@tab

A reference to the @ref{183,,dictionary} that holds the function's
builtins namespace.


Added in version 3.10.


@item

@geindex __globals__ (function の属性)
@anchor{reference/datamodel function __globals__}@anchor{14eb}
@deffn {の属性} function.__globals__
@end deffn

@tab

A reference to the @ref{183,,dictionary} that holds the function's
@ref{2346,,global variables} -- the global namespace of the module
in which the function was defined.

@item

@geindex __closure__ (function の属性)
@anchor{reference/datamodel function __closure__}@anchor{14e8}
@deffn {の属性} function.__closure__
@end deffn

@tab

@code{None} or a @ref{614,,tuple} of cells that contain bindings for the names specified
in the @ref{2347,,co_freevars} attribute of the function's
@ref{59d,,code object}.

セルオブジェクトは属性 @code{cell_contents} を持っています。
これはセルの値を設定するのに加えて、セルの値を得るのにも使えます。

@end multitable


@node Special writable attributes,,Special read-only attributes,ユーザ定義関数 user-defined function
@anchor{reference/datamodel special-writable-attributes}@anchor{2348}
@subsubsection Special writable attributes


@geindex __doc__ (関数属性)
@geindex __name__ (関数属性)
@geindex __module__ (関数属性)
@geindex __dict__ (関数属性)
@geindex __defaults__ (関数属性)
@geindex __code__ (関数属性)
@geindex __annotations__ (関数属性)
@geindex __annotate__ (function attribute)
@geindex __kwdefaults__ (関数属性)
@geindex __type_params__ (function attribute)

Most of these attributes check the type of the assigned value:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

意味

@item

@geindex __doc__ (function の属性)
@anchor{reference/datamodel function __doc__}@anchor{13f1}
@deffn {の属性} function.__doc__
@end deffn

@tab

関数のドキュメンテーション文字列です。ドキュメンテーションがない場合は @code{None} になります。

@item

@geindex __name__ (function の属性)
@anchor{reference/datamodel function __name__}@anchor{14ec}
@deffn {の属性} function.__name__
@end deffn

@tab

The function's name.
See also: @ref{1272,,__name__ attributes}.

@item

@geindex __qualname__ (function の属性)
@anchor{reference/datamodel function __qualname__}@anchor{2349}
@deffn {の属性} function.__qualname__
@end deffn

@tab

The function's @ref{1d24,,qualified name}.
See also: @ref{1271,,__qualname__ attributes}.


Added in version 3.3.


@item

@geindex __module__ (function の属性)
@anchor{reference/datamodel function __module__}@anchor{234a}
@deffn {の属性} function.__module__
@end deffn

@tab

関数が定義されているモジュールの名前です。モジュール名がない場合は @code{None} になります。

@item

@geindex __defaults__ (function の属性)
@anchor{reference/datamodel function __defaults__}@anchor{14e9}
@deffn {の属性} function.__defaults__
@end deffn

@tab

A @ref{614,,tuple} containing default @ref{234b,,parameter} values
for those parameters that have defaults,
or @code{None} if no parameters have a default value.

@item

@geindex __code__ (function の属性)
@anchor{reference/datamodel function __code__}@anchor{59d}
@deffn {の属性} function.__code__
@end deffn

@tab

The @ref{4e6,,code object} representing
the compiled function body.

@item

@geindex __dict__ (function の属性)
@anchor{reference/datamodel function __dict__}@anchor{14ea}
@deffn {の属性} function.__dict__
@end deffn

@tab

The namespace supporting arbitrary function attributes.
See also: @ref{77d,,__dict__ attributes}.

@item

@geindex __annotations__ (function の属性)
@anchor{reference/datamodel function __annotations__}@anchor{13f0}
@deffn {の属性} function.__annotations__
@end deffn

@tab

A @ref{183,,dictionary} containing annotations of
@ref{234b,,parameters}.
The keys of the dictionary are the parameter names,
and @code{'return'} for the return annotation, if provided.
See also: @ref{458,,object.__annotations__}.


バージョン 3.14 で変更: Annotations are now @ref{685,,lazily evaluated}.
See 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}.


@item

@geindex __annotate__ (function の属性)
@anchor{reference/datamodel function __annotate__}@anchor{234c}
@deffn {の属性} function.__annotate__
@end deffn

@tab

The @ref{15d,,annotate function} for this function, or @code{None}
if the function has no annotations. See @ref{1983,,object.__annotate__}.


Added in version 3.14.


@item

@geindex __kwdefaults__ (function の属性)
@anchor{reference/datamodel function __kwdefaults__}@anchor{1229}
@deffn {の属性} function.__kwdefaults__
@end deffn

@tab

A @ref{183,,dictionary} containing defaults for keyword-only
@ref{234b,,parameters}.

@item

@geindex __type_params__ (function の属性)
@anchor{reference/datamodel function __type_params__}@anchor{234d}
@deffn {の属性} function.__type_params__
@end deffn

@tab

A @ref{614,,tuple} containing the @ref{5ad,,type parameters} of
a @ref{682,,generic function}.


Added in version 3.12.


@end multitable


Function objects also support getting and setting arbitrary attributes, which
can be used, for example, to attach metadata to functions.  Regular attribute
dot-notation is used to get and set such attributes.

`CPython 実装の詳細:' CPython's current implementation only supports function attributes
on user-defined functions. Function attributes on
@ref{234e,,built-in functions} may be supported in the
future.

Additional information about a function's definition can be retrieved from its
@ref{4e6,,code object}
(accessible via the @ref{59d,,__code__} attribute).

@node インスタンスメソッド,ジェネレータ関数 generator function,ユーザ定義関数 user-defined function,呼び出し可能型 callable type
@anchor{reference/datamodel id2}@anchor{234f}@anchor{reference/datamodel instance-methods}@anchor{20a7}
@subsubsection インスタンスメソッド


@geindex object;メソッド
@geindex object;ユーザ定義メソッド
@geindex ユーザ定義の;メソッド

インスタンスメソッドオブジェクトは、クラス、クラスインスタンスと任意の呼び出し可能オブジェクト (通常はユーザ定義関数) を結びつけます。

@geindex __func__ (メソッド属性)
@geindex __self__ (メソッド属性)
@geindex __doc__ (メソッド属性)
@geindex __name__ (メソッド属性)
@geindex __module__ (メソッド属性)

Special read-only attributes:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@geindex __self__ (method の属性)
@anchor{reference/datamodel method __self__}@anchor{15e2}
@deffn {の属性} method.__self__
@end deffn

@tab

Refers to the class instance object to which the method is
@ref{2350,,bound}

@item

@geindex __func__ (method の属性)
@anchor{reference/datamodel method __func__}@anchor{1514}
@deffn {の属性} method.__func__
@end deffn

@tab

Refers to the original @ref{59c,,function object}

@item

@geindex __doc__ (method の属性)
@anchor{reference/datamodel method __doc__}@anchor{2351}
@deffn {の属性} method.__doc__
@end deffn

@tab

The method's documentation
(same as @ref{13f1,,method.__func__.__doc__}).
A @ref{169,,string} if the original function had a docstring, else
@code{None}.

@item

@geindex __name__ (method の属性)
@anchor{reference/datamodel method __name__}@anchor{2352}
@deffn {の属性} method.__name__
@end deffn

@tab

The name of the method
(same as @ref{14ec,,method.__func__.__name__})

@item

@geindex __module__ (method の属性)
@anchor{reference/datamodel method __module__}@anchor{2353}
@deffn {の属性} method.__module__
@end deffn

@tab

The name of the module the method was defined in, or @code{None} if
unavailable.

@end multitable


Methods also support accessing (but not setting) the arbitrary function
attributes on the underlying @ref{59c,,function object}.

User-defined method objects may be created when getting an attribute of a
class (perhaps via an instance of that class), if that attribute is a
user-defined @ref{59c,,function object} or a
@ref{48e,,classmethod} object.
@anchor{reference/datamodel method-binding}@anchor{2350}
When an instance method object is created by retrieving a user-defined
@ref{59c,,function object} from a class via one of its
instances, its @ref{15e2,,__self__} attribute is the instance, and the
method object is said to be `bound'.  The new method's @ref{1514,,__func__}
attribute is the original function object.

When an instance method object is created by retrieving a @ref{48e,,classmethod}
object from a class or instance, its @ref{15e2,,__self__} attribute is the
class itself, and its @ref{1514,,__func__} attribute is the function object
underlying the class method.

When an instance method object is called, the underlying function
(@ref{1514,,__func__}) is called, inserting the class instance
(@ref{15e2,,__self__}) in front of the argument list.  For instance, when
@code{C} is a class which contains a definition for a function
@code{f()}, and @code{x} is an instance of @code{C}, calling @code{x.f(1)} is
equivalent to calling @code{C.f(x, 1)}.

When an instance method object is derived from a @ref{48e,,classmethod} object, the
"class instance" stored in @ref{15e2,,__self__} will actually be the class
itself, so that calling either @code{x.f(1)} or @code{C.f(1)} is equivalent to
calling @code{f(C,1)} where @code{f} is the underlying function.

It is important to note that user-defined functions
which are attributes of a class instance are not converted to bound
methods; this `only' happens when the function is an attribute of the
class.

@node ジェネレータ関数 generator function,コルーチン関数 coroutine function,インスタンスメソッド,呼び出し可能型 callable type
@anchor{reference/datamodel generator-functions}@anchor{2354}
@subsubsection ジェネレータ関数 (generator function)


@geindex ジェネレータ;関数
@geindex ジェネレータ;iterator

@ref{bc2,,yield} 文 (@ref{bc2,,yield 文} の節を参照) を使う関数もしくはメソッドは `ジェネレータ関数' と呼ばれます。
そのような関数が呼び出されたときは常に、関数の本体を実行するのに使える @ref{4c8,,イテレータ} オブジェクトを返します:
イテレータの @ref{14e5,,iterator.__next__()} メソッドを呼び出すと、 @code{yield} 文を使って値が提供されるまで関数を実行します。
関数の @ref{1af,,return} 文を実行するか終端に達したときは、 @ref{df5,,StopIteration} 例外が送出され、イテレータが返すべき値の最後まで到達しています。

@node コルーチン関数 coroutine function,非同期ジェネレータ関数 asynchronous generator function,ジェネレータ関数 generator function,呼び出し可能型 callable type
@anchor{reference/datamodel coroutine-functions}@anchor{2355}
@subsubsection コルーチン関数 (coroutine function)


@geindex コルーチン;関数

@ref{7ed,,async def} を使用して定義された関数やメソッドを `コルーチン関数 (coroutine function)' と呼びます。
呼び出された時、そのような関数は @ref{6b9,,coroutine} オブジェクトを返します。
コルーチン関数は @ref{185,,async with} や @ref{ca1,,async for} 文だけでなく @ref{18d,,await} 式を持つことが出来ます。
@ref{2356,,コルーチンオブジェクト} を参照してください。

@node 非同期ジェネレータ関数 asynchronous generator function,組み込み関数 built-in function,コルーチン関数 coroutine function,呼び出し可能型 callable type
@anchor{reference/datamodel asynchronous-generator-functions}@anchor{2357}
@subsubsection 非同期ジェネレータ関数 (asynchronous generator function)


@geindex asynchronous generator;関数
@geindex asynchronous generator;asynchronous iterator

@ref{7ed,,async def} を使って定義され、 @ref{bc2,,yield} 文を使用している関数やメソッドを `asynchronous generator function' と呼びます。
そのような関数は、呼び出されたとき、@ref{4c7,,非同期イテレータ} オブジェクトを返します。
このオブジェクトは @ref{ca1,,async for} 文で関数の本体を実行するのに使えます。

非同期イテレータの @ref{1882,,aiterator.__anext__} メソッドを呼び出すと、他の処理が待たされているときに、 @ref{bc2,,yield} 式を使い値を提供するところまで処理を進める @ref{4c9,,awaitable} を返します。
その関数が空の @ref{1af,,return} 文を実行する、もしくは処理の終わりに到達したときは、 @ref{1e0f,,StopAsyncIteration} 例外が送出され、非同期イテレータは出力すべき値の最後に到達したことになります。

@node 組み込み関数 built-in function,組み込みメソッド built-in method,非同期ジェネレータ関数 asynchronous generator function,呼び出し可能型 callable type
@anchor{reference/datamodel built-in-functions}@anchor{2358}@anchor{reference/datamodel builtin-functions}@anchor{234e}
@subsubsection 組み込み関数 (built-in function)


@geindex object;組み込み関数
@geindex object;関数
@geindex C;言語

A built-in function object is a wrapper around a C function.  Examples of
built-in functions are @ref{840,,len()} and @ref{16d7,,math.sin()} (@ref{92,,math} is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:


@itemize *

@item 
@code{__doc__} is the function's documentation string, or @code{None} if
unavailable. See @ref{13f1,,function.__doc__}.

@item 
@code{__name__} is the function's name. See @ref{14ec,,function.__name__}.

@item 
@code{__self__} is set to @code{None} (but see the next item).

@item 
@code{__module__} is the name of
the module the function was defined in or @code{None} if unavailable.
See @ref{234a,,function.__module__}.
@end itemize

@node 組み込みメソッド built-in method,クラス<2>,組み込み関数 built-in function,呼び出し可能型 callable type
@anchor{reference/datamodel built-in-methods}@anchor{2359}@anchor{reference/datamodel builtin-methods}@anchor{235a}
@subsubsection 組み込みメソッド (built-in method)


@geindex object;組み込みメソッド
@geindex object;メソッド
@geindex 組み込み;メソッド

This is really a different disguise of a built-in function, this time containing
an object passed to the C function as an implicit extra argument.  An example of
a built-in method is @code{alist.append()}, assuming `alist' is a list object. In
this case, the special read-only attribute @code{__self__} is set to the object
denoted by `alist'. (The attribute has the same semantics as it does with
@ref{15e2,,other instance methods}.)

@node クラス<2>,クラスのインスタンス,組み込みメソッド built-in method,呼び出し可能型 callable type
@anchor{reference/datamodel classes}@anchor{235b}@anchor{reference/datamodel id3}@anchor{235c}
@subsubsection クラス


Classes are callable.  These objects normally act as factories for new
instances of themselves, but variations are possible for class types that
override @ref{7a0,,__new__()}.  The arguments of the call are passed to
@code{__new__()} and, in the typical case, to @ref{8bf,,__init__()} to
initialize the new instance.

@node クラスのインスタンス,,クラス<2>,呼び出し可能型 callable type
@anchor{reference/datamodel class-instances}@anchor{235d}
@subsubsection クラスのインスタンス


任意のクラスのインスタンスは、クラスで @ref{77a,,__call__()} メソッドを定義することで呼び出し可能になります。

@node モジュール<3>,カスタムクラス型,呼び出し可能型 callable type,標準型の階層
@anchor{reference/datamodel module-objects}@anchor{235e}@anchor{reference/datamodel modules}@anchor{235f}
@subsubsection モジュール


@geindex statement;import
@geindex object;module

Modules are a basic organizational unit of Python code, and are created by
the @ref{2360,,import system} as invoked either by the
@ref{7f8,,import} statement, or by calling
functions such as @ref{73c,,importlib.import_module()} and built-in
@ref{ad1,,__import__()}.  A module object has a namespace implemented by a
@ref{183,,dictionary} object (this is the dictionary referenced by the
@ref{14eb,,__globals__}
attribute of functions defined in the module).  Attribute references are
translated to lookups in this dictionary, e.g., @code{m.x} is equivalent to
@code{m.__dict__["x"]}. A module object does not contain the code object used
to initialize the module (since it isn't needed once the initialization is
done).

属性の代入を行うと、モジュールの名前空間辞書の内容を更新します。例えば、 @code{m.x = 1} は @code{m.__dict__["x"] = 1} と同じです。

@geindex __name__ (モジュール属性)
@geindex __spec__ (module attribute)
@geindex __package__ (module attribute)
@geindex __loader__ (module attribute)
@geindex __path__ (module attribute)
@geindex __file__ (モジュール属性)
@geindex __cached__ (module attribute)
@geindex __doc__ (モジュール属性)
@geindex __annotations__ (module attribute)
@geindex __annotate__ (module attribute)
@geindex module;namespace

@menu
* Import-related attributes on module objects:: 
* Other writable attributes on module objects:: 
* Module dictionaries:: 

@end menu

@node Import-related attributes on module objects,Other writable attributes on module objects,,モジュール<3>
@anchor{reference/datamodel import-mod-attrs}@anchor{2361}@anchor{reference/datamodel import-related-attributes-on-module-objects}@anchor{2362}
@subsubsection Import-related attributes on module objects


Module objects have the following attributes that relate to the
@ref{2360,,import system}. When a module is created using the machinery associated
with the import system, these attributes are filled in based on the module's
@ref{2363,,spec}, before the @ref{1a28,,loader} executes and loads the
module.

To create a module dynamically rather than using the import system,
it's recommended to use @ref{1013,,importlib.util.module_from_spec()},
which will set the various import-controlled attributes to appropriate values.
It's also possible to use the @ref{1014,,types.ModuleType} constructor to create
modules directly, but this technique is more error-prone, as most attributes
must be manually set on the module object after it has been created when using
this approach.

@cartouche
@quotation 注意 
With the exception of @ref{15a3,,__name__}, it is `strongly'
recommended that you rely on @ref{2364,,__spec__} and its attributes
instead of any of the other individual attributes listed in this subsection.
Note that updating an attribute on @code{__spec__} will not update the
corresponding attribute on the module itself:

@example
>>> import typing
>>> typing.__name__, typing.__spec__.name
('typing', 'typing')
>>> typing.__spec__.name = 'spelling'
>>> typing.__name__, typing.__spec__.name
('typing', 'spelling')
>>> typing.__name__ = 'keyboard_smashing'
>>> typing.__name__, typing.__spec__.name
('keyboard_smashing', 'spelling')
@end example
@end quotation
@end cartouche

@geindex __name__ (module の属性)
@anchor{reference/datamodel module __name__}@anchor{15a3}
@deffn {の属性} module.__name__

The name used to uniquely identify the module in the import system.
For a directly executed module, this will be set to @code{"__main__"}.

This attribute must be set to the fully qualified name of the module.
It is expected to match the value of
@ref{2365,,module.__spec__.name}.
@end deffn

@geindex __spec__ (module の属性)
@anchor{reference/datamodel module __spec__}@anchor{2364}
@deffn {の属性} module.__spec__

A record of the module's import-system-related state.

Set to the @ref{226c,,module spec} that was
used when importing the module. See @ref{2366,,Module specs} for more details.


Added in version 3.4.

@end deffn

@geindex __package__ (module の属性)
@anchor{reference/datamodel module __package__}@anchor{323}
@deffn {の属性} module.__package__

The @ref{233,,package} a module belongs to.

If the module is top-level (that is, not a part of any specific package)
then the attribute should be set to @code{'@w{'}} (the empty string). Otherwise,
it should be set to the name of the module's package (which can be equal to
@ref{15a3,,module.__name__} if the module itself is a package). See 
@geindex Python Enhancement Proposals; PEP 366
PEP 366@footnote{https://peps.python.org/pep-0366/}
for further details.

This attribute is used instead of @ref{15a3,,__name__} to calculate
explicit relative imports for main modules. It defaults to @code{None} for
modules created dynamically using the @ref{1014,,types.ModuleType} constructor;
use @ref{1013,,importlib.util.module_from_spec()} instead to ensure the attribute
is set to a @ref{169,,str}.

It is `strongly' recommended that you use
@ref{324,,module.__spec__.parent}
instead of @code{module.__package__}. @ref{323,,__package__} is now only used
as a fallback if @code{__spec__.parent} is not set, and this fallback
path is deprecated.


バージョン 3.4 で変更: This attribute now defaults to @code{None} for modules created dynamically
using the @ref{1014,,types.ModuleType} constructor.
Previously the attribute was optional.



バージョン 3.6 で変更: The value of @code{__package__} is expected to be the same as
@ref{324,,__spec__.parent}.
@ref{323,,__package__} is now only used as a fallback during import
resolution if @code{__spec__.parent} is not defined.



バージョン 3.10 で変更: @ref{71e,,ImportWarning} is raised if an import resolution falls back to
@code{__package__} instead of
@ref{324,,__spec__.parent}.



バージョン 3.12 で変更: Raise @ref{1a3,,DeprecationWarning} instead of @ref{71e,,ImportWarning} when
falling back to @code{__package__} during import resolution.



Deprecated since version 3.13, will be removed in version 3.15: @code{__package__} will cease to be set or taken into consideration
by the import system or standard library.

@end deffn

@geindex __loader__ (module の属性)
@anchor{reference/datamodel module __loader__}@anchor{33b}
@deffn {の属性} module.__loader__

The @ref{1a28,,loader} object that the import machinery used to load the module.

This attribute is mostly useful for introspection, but can be used for
additional loader-specific functionality, for example getting data
associated with a loader.

@code{__loader__} defaults to @code{None} for modules created dynamically
using the @ref{1014,,types.ModuleType} constructor;
use @ref{1013,,importlib.util.module_from_spec()} instead to ensure the attribute
is set to a @ref{1a28,,loader} object.

It is `strongly' recommended that you use
@ref{33c,,module.__spec__.loader}
instead of @code{module.__loader__}.


バージョン 3.4 で変更: This attribute now defaults to @code{None} for modules created dynamically
using the @ref{1014,,types.ModuleType} constructor.
Previously the attribute was optional.



Deprecated since version 3.12, will be removed in version 3.16: Setting @code{__loader__} on a module while failing to set
@code{__spec__.loader} is deprecated. In Python 3.16,
@code{__loader__} will cease to be set or taken into consideration by
the import system or the standard library.

@end deffn

@geindex __path__ (module の属性)
@anchor{reference/datamodel module __path__}@anchor{2054}
@deffn {の属性} module.__path__

A (possibly empty) @ref{716,,sequence} of strings enumerating the locations
where the package's submodules will be found. Non-package modules should
not have a @code{__path__} attribute. See @ref{2367,,__path__ attributes on modules} for
more details.

It is `strongly' recommended that you use
@ref{2368,,module.__spec__.submodule_search_locations}
instead of @code{module.__path__}.
@end deffn

@geindex __file__ (module の属性)
@anchor{reference/datamodel module __file__}@anchor{2369}
@deffn {の属性} module.__file__
@end deffn

@geindex __cached__ (module の属性)
@anchor{reference/datamodel module __cached__}@anchor{321}
@deffn {の属性} module.__cached__

@code{__file__} and @code{__cached__} are both optional attributes that
may or may not be set. Both attributes should be a @ref{169,,str} when they
are available.

@code{__file__} indicates the pathname of the file from which the module
was loaded (if loaded from a file), or the pathname of the shared library
file for extension modules loaded dynamically from a shared library.
It might be missing for certain types of modules, such as C modules that are
statically linked into the interpreter, and the
@ref{2360,,import system} may opt to leave it unset if it
has no semantic meaning (for example, a module loaded from a database).

If @code{__file__} is set then the @code{__cached__} attribute might
also be set,  which is the path to any compiled version of
the code (for example, a byte-compiled file). The file does not need to exist
to set this attribute; the path can simply point to where the
compiled file `would' exist (see 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/}).

Note that @code{__cached__} may be set even if @code{__file__} is not
set.  However, that scenario is quite atypical.  Ultimately, the
@ref{1a28,,loader} is what makes use of the module spec provided by the
@ref{236a,,finder} (from which @code{__file__} and @code{__cached__} are
derived).  So if a loader can load from a cached module but otherwise does
not load from a file, that atypical scenario may be appropriate.

It is `strongly' recommended that you use
@ref{322,,module.__spec__.cached}
instead of @code{module.__cached__}.


Deprecated since version 3.13, will be removed in version 3.15: Setting @code{__cached__} on a module while failing to set
@code{__spec__.cached} is deprecated. In Python 3.15,
@code{__cached__} will cease to be set or taken into consideration by
the import system or standard library.

@end deffn

@node Other writable attributes on module objects,Module dictionaries,Import-related attributes on module objects,モジュール<3>
@anchor{reference/datamodel other-writable-attributes-on-module-objects}@anchor{236b}
@subsubsection Other writable attributes on module objects


As well as the import-related attributes listed above, module objects also have
the following writable attributes:

@geindex __doc__ (module の属性)
@anchor{reference/datamodel module __doc__}@anchor{1bef}
@deffn {の属性} module.__doc__

The module's documentation string, or @code{None} if unavailable.
See also: @ref{b21,,__doc__ attributes}.
@end deffn

@geindex __annotations__ (module の属性)
@anchor{reference/datamodel module __annotations__}@anchor{236c}
@deffn {の属性} module.__annotations__

A dictionary containing @ref{f51,,variable annotations}
collected during module body execution.  For best practices on working with
@code{__annotations__}, see @ref{6,,annotationlib}.


バージョン 3.14 で変更: Annotations are now @ref{685,,lazily evaluated}.
See 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}.

@end deffn

@geindex __annotate__ (module の属性)
@anchor{reference/datamodel module __annotate__}@anchor{236d}
@deffn {の属性} module.__annotate__

The @ref{15d,,annotate function} for this module, or @code{None} if the module has
no annotations. See also: @ref{1983,,__annotate__} attributes.


Added in version 3.14.

@end deffn

@node Module dictionaries,,Other writable attributes on module objects,モジュール<3>
@anchor{reference/datamodel module-dictionaries}@anchor{236e}
@subsubsection Module dictionaries


Module objects also have the following special read-only attribute:

@geindex __dict__ (モジュール属性)

@geindex __dict__ (module の属性)
@anchor{reference/datamodel module __dict__}@anchor{236f}
@deffn {の属性} module.__dict__

The module's namespace as a dictionary object. Uniquely among the attributes
listed here, @code{__dict__} cannot be accessed as a global variable from
within a module; it can only be accessed as an attribute on module objects.

CPython がモジュール辞書を削除する方法により、モジュール辞書が生きた参照を持っていたとしてもその辞書はモジュールがスコープから外れた時に削除されます。これを避けるには、辞書をコピーするか、辞書を直接使っている間モジュールを保持してください。
@end deffn

@node カスタムクラス型,クラスインスタンス class instance,モジュール<3>,標準型の階層
@anchor{reference/datamodel class-attrs-and-methods}@anchor{2370}@anchor{reference/datamodel custom-classes}@anchor{2371}
@subsubsection カスタムクラス型


Custom class types are typically created by class definitions (see section
@ref{14ef,,クラス定義}).  A class has a namespace implemented by a dictionary object.
Class attribute references are translated to lookups in this dictionary, e.g.,
@code{C.x} is translated to @code{C.__dict__["x"]} (although there are a number of
hooks which allow for other means of locating attributes). When the attribute
name is not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order which
behaves correctly even in the presence of 'diamond' inheritance structures
where there are multiple inheritance paths leading back to a common ancestor.
Additional details on the C3 MRO used by Python can be found at
@ref{16c3,,The Python 2.3 Method Resolution Order}.

@geindex object;クラス
@geindex object;クラスインスタンス
@geindex object;instance
@geindex クラスオブジェクト;call
@geindex コンテナ
@geindex object;dictionary
@geindex クラス;属性

When a class attribute reference (for class @code{C}, say) would yield a
class method object, it is transformed into an instance method object whose
@ref{15e2,,__self__} attribute is @code{C}.
When it would yield a @ref{453,,staticmethod} object,
it is transformed into the object wrapped by the static method
object. See section @ref{e49,,デスクリプタ (descriptor) の実装} for another way in which attributes
retrieved from a class may differ from those actually contained in its
@ref{77d,,__dict__}.

@geindex クラス;属性;代入

クラス属性を代入すると、そのクラスの辞書だけが更新され、基底クラスの辞書は更新しません。

@geindex クラスオブジェクト;call

クラスオブジェクトを呼び出す (上記を参照) と、クラスインスタンスを生成します (下記を参照)。

@menu
* Special attributes:: 
* Special methods:: 

@end menu

@node Special attributes,Special methods,,カスタムクラス型
@anchor{reference/datamodel special-attributes}@anchor{2372}
@subsubsection Special attributes


@geindex __name__ (クラス属性)
@geindex __module__ (クラス属性)
@geindex __dict__ (クラス属性)
@geindex __bases__ (クラス属性)
@geindex __base__ (class attribute)
@geindex __doc__ (クラス属性)
@geindex __annotations__ (class attribute)
@geindex __annotate__ (class attribute)
@geindex __type_params__ (class attribute)
@geindex __static_attributes__ (class attribute)
@geindex __firstlineno__ (class attribute)


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

意味

@item

@geindex __name__ (type の属性)
@anchor{reference/datamodel type __name__}@anchor{16c4}
@deffn {の属性} type.__name__
@end deffn

@tab

The class's name.
See also: @ref{1272,,__name__ attributes}.

@item

@geindex __qualname__ (type の属性)
@anchor{reference/datamodel type __qualname__}@anchor{2373}
@deffn {の属性} type.__qualname__
@end deffn

@tab

The class's @ref{1d24,,qualified name}.
See also: @ref{1271,,__qualname__ attributes}.

@item

@geindex __module__ (type の属性)
@anchor{reference/datamodel type __module__}@anchor{617}
@deffn {の属性} type.__module__
@end deffn

@tab

クラスが定義されているモジュールの名前。

@item

@geindex __dict__ (type の属性)
@anchor{reference/datamodel type __dict__}@anchor{e57}
@deffn {の属性} type.__dict__
@end deffn

@tab

A @ref{698,,mapping proxy}
providing a read-only view of the class's namespace.
See also: @ref{77d,,__dict__ attributes}.

@item

@geindex __bases__ (type の属性)
@anchor{reference/datamodel type __bases__}@anchor{16c5}
@deffn {の属性} type.__bases__
@end deffn

@tab

A @ref{614,,tuple} containing the class's bases.
In most cases, for a class defined as @code{class X(A, B, C)},
@code{X.__bases__} will be exactly equal to @code{(A, B, C)}.

@item

@geindex __base__ (type の属性)
@anchor{reference/datamodel type __base__}@anchor{2374}
@deffn {の属性} type.__base__
@end deffn

@tab

`CPython 実装の詳細:' The single base class in the inheritance chain that is responsible
for the memory layout of instances. This attribute corresponds to
@ref{2375,,tp_base} at the C level.

@item

@geindex __doc__ (type の属性)
@anchor{reference/datamodel type __doc__}@anchor{2095}
@deffn {の属性} type.__doc__
@end deffn

@tab

The class's documentation string, or @code{None} if undefined.
Not inherited by subclasses.

@item

@geindex __annotations__ (type の属性)
@anchor{reference/datamodel type __annotations__}@anchor{1843}
@deffn {の属性} type.__annotations__
@end deffn

@tab

A dictionary containing
@ref{f51,,variable annotations}
collected during class body execution. See also:
@ref{458,,__annotations__ attributes}.

For best practices on working with @ref{458,,__annotations__},
please see @ref{6,,annotationlib}. Use
@ref{459,,annotationlib.get_annotations()} instead of accessing this
attribute directly.

@cartouche
@quotation 警告 
Accessing the @code{__annotations__} attribute directly
on a class object may return annotations for the wrong class, specifically
in certain cases where the class, its base class, or a metaclass
is defined under @code{from __future__ import annotations}.
See 
@geindex Python Enhancement Proposals; PEP 749#pep749-metaclasses
749@footnote{https://peps.python.org/pep-0749/#pep749-metaclasses} for details.

This attribute does not exist on certain builtin classes. On
user-defined classes without @code{__annotations__}, it is an
empty dictionary.
@end quotation
@end cartouche


バージョン 3.14 で変更: Annotations are now @ref{685,,lazily evaluated}.
See 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}.


@item

@geindex __annotate__() (type のメソッド)
@anchor{reference/datamodel type __annotate__}@anchor{1867}
@deffn {メソッド} type.__annotate__ ()
@end deffn

@tab

The @ref{15d,,annotate function} for this class, or @code{None}
if the class has no annotations.
See also: @ref{1983,,__annotate__ attributes}.


Added in version 3.14.


@item

@geindex __type_params__ (type の属性)
@anchor{reference/datamodel type __type_params__}@anchor{2376}
@deffn {の属性} type.__type_params__
@end deffn

@tab

A @ref{614,,tuple} containing the @ref{5ad,,type parameters} of
a @ref{2377,,generic class}.


Added in version 3.12.


@item

@geindex __static_attributes__ (type の属性)
@anchor{reference/datamodel type __static_attributes__}@anchor{477}
@deffn {の属性} type.__static_attributes__
@end deffn

@tab

A @ref{614,,tuple} containing names of attributes of this class which are
assigned through @code{self.X} from any function in its body.


Added in version 3.13.


@item

@geindex __firstlineno__ (type の属性)
@anchor{reference/datamodel type __firstlineno__}@anchor{478}
@deffn {の属性} type.__firstlineno__
@end deffn

@tab

The line number of the first line of the class definition,
including decorators.
Setting the @ref{617,,__module__} attribute removes the
@code{__firstlineno__} item from the type's dictionary.


Added in version 3.13.


@item

@geindex __mro__ (type の属性)
@anchor{reference/datamodel type __mro__}@anchor{2378}
@deffn {の属性} type.__mro__
@end deffn

@tab

The @ref{614,,tuple} of classes that are considered when looking for
base classes during method resolution.

@end multitable


@node Special methods,,Special attributes,カスタムクラス型
@anchor{reference/datamodel special-methods}@anchor{2379}
@subsubsection Special methods


In addition to the special attributes described above, all Python classes also
have the following two methods available:

@geindex mro() (type のメソッド)
@anchor{reference/datamodel type mro}@anchor{237a}
@deffn {メソッド} type.mro ()

This method can be overridden by a metaclass to customize the method
resolution order for its instances.  It is called at class instantiation,
and its result is stored in @ref{2378,,__mro__}.
@end deffn

@geindex __subclasses__() (type のメソッド)
@anchor{reference/datamodel type __subclasses__}@anchor{793}
@deffn {メソッド} type.__subclasses__ ()

Each class keeps a list of weak references to its immediate subclasses. This
method returns a list of all those references still alive. The list is in
definition order. Example:

@example
>>> class A: pass
>>> class B(A): pass
>>> A.__subclasses__()
[<class 'B'>]
@end example
@end deffn

@node クラスインスタンス class instance,I/O オブジェクト ファイルオブジェクトの別名,カスタムクラス型,標準型の階層
@anchor{reference/datamodel id4}@anchor{237b}
@subsubsection クラスインスタンス (class instance)


@geindex object;クラスインスタンス
@geindex object;instance
@geindex クラス;instance
@geindex クラスインスタンス;属性

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 @ref{15e2,,__self__} attribute is the instance.  Static method and
class method objects are also transformed; see above under "Classes".  See
section @ref{e49,,デスクリプタ (descriptor) の実装} for another way in which attributes of a class
retrieved via its instances may differ from the objects actually stored in
the class's @ref{77d,,__dict__}.  If no class attribute is found, and the
object's class has a @ref{6fa,,__getattr__()} method, that is called to satisfy
the lookup.

@geindex クラスインスタンス;属性;代入

属性の代入や削除を行うと、インスタンスの辞書を更新しますが、クラスの辞書を更新することはありません。クラスで @ref{237c,,__setattr__()} や @ref{237d,,__delattr__()} メソッドが定義されている場合、直接インスタンスの辞書を更新する代わりにこれらのメソッドが呼び出されます。

@geindex object;数値
@geindex object;sequence
@geindex object;mapping

クラスインスタンスは、ある特定の名前のメソッドを持っている場合、数値型やシーケンス型、あるいはマップ型のように振舞うことができます。 @ref{e68,,特殊メソッド名} を参照してください。

@menu
* Special attributes: Special attributes<2>. 

@end menu

@node Special attributes<2>,,,クラスインスタンス class instance
@anchor{reference/datamodel id5}@anchor{237e}
@subsubsection Special attributes


@geindex __dict__ (インスタンス属性)
@geindex __class__ (インスタンス属性)

@geindex __class__ (object の属性)
@anchor{reference/datamodel object __class__}@anchor{16c6}
@deffn {の属性} object.__class__

クラスインスタンスが属しているクラスです。
@end deffn

@geindex __dict__ (object の属性)
@anchor{reference/datamodel object __dict__}@anchor{77d}
@deffn {の属性} object.__dict__

A dictionary or other mapping object used to store an object's (writable)
attributes. Not all instances have a @code{__dict__} attribute; see the
section on @ref{237f,,__slots__} for more details.
@end deffn

@node I/O オブジェクト ファイルオブジェクトの別名,内部型 internal type,クラスインスタンス class instance,標準型の階層
@anchor{reference/datamodel i-o-objects-also-known-as-file-objects}@anchor{2380}
@subsubsection I/O オブジェクト (ファイルオブジェクトの別名)


@geindex 組み込み関数;open
@geindex module;io
@geindex popen() (os モジュール)
@geindex makefile() (socket のメソッド)
@geindex sys.stdin
@geindex sys.stdout
@geindex sys.stderr
@geindex stdio
@geindex stdin (sys モジュール)
@geindex stdout (sys モジュール)
@geindex stderr (sys モジュール)

@ref{13db,,file object} は開かれたファイルを表します。ファイルオブジェクトを作るための様々なショートカットがあります: @ref{316,,open()} 組み込み関数、 @ref{31a,,os.popen()} 、 @ref{2381,,os.fdopen()} 、ソケットオブジェクトの @ref{13b7,,makefile()} メソッド (あるいは拡張モジュールから提供される他の関数やメソッド) 。

オブジェクト @code{sys.stdin} 、 @code{sys.stdout} および @code{sys.stderr} は、インタプリタの標準入力、標準出力、および標準エラー出力ストリームに対応するファイルオブジェクトに初期化されます。これらはすべてテキストモードで開かれ、 @ref{8a4,,io.TextIOBase} 抽象クラスによって定義されたインターフェースに従います。

@node 内部型 internal type,,I/O オブジェクト ファイルオブジェクトの別名,標準型の階層
@anchor{reference/datamodel internal-types}@anchor{2382}
@subsubsection 内部型 (internal type)


@geindex 内部型
@geindex 型@comma{} 内部の

インタプリタが内部的に使っているいくつかの型は、ユーザに公開されています。これらの定義は将来のインタプリタのバージョンでは変更される可能性がありますが、ここでは記述の完全性のために触れておきます。

@menu
* コードオブジェクト:: 
* フレーム (frame) オブジェクト: フレーム frame オブジェクト. 
* トレースバック (traceback) オブジェクト: トレースバック traceback オブジェクト. 
* スライス (slice) オブジェクト: スライス slice オブジェクト. 
* 静的メソッド (static method) オブジェクト: 静的メソッド static method オブジェクト. 
* クラスメソッドオブジェクト:: 

@end menu

@node コードオブジェクト,フレーム frame オブジェクト,,内部型 internal type
@anchor{reference/datamodel code-objects}@anchor{4e6}@anchor{reference/datamodel id6}@anchor{2383}
@subsubsection コードオブジェクト


@geindex bytecode
@geindex object;コード
@geindex コードオブジェクト

コードオブジェクトは `バイトコンパイルされた (byte-compiled)' 実行可能な Python コード、別名 @ref{4aa,,バイトコード} を表現します。コードオブジェクトと関数オブジェクトの違いは、関数オブジェクトが関数のグローバル変数 (関数を定義しているモジュールのグローバル) に対して明示的な参照を持っているのに対し、コードオブジェクトにはコンテキストがないということです; また、関数オブジェクトではデフォルト引数値を記憶できますが、コードオブジェクトではできません (実行時に計算される値を表現するため)。関数オブジェクトと違い、コードオブジェクトは変更不可能で、変更可能なオブジェクトへの参照を (直接、間接に関わらず) 含みません。

@geindex co_argcount (コードオブジェクトの属性)
@geindex co_posonlyargcount (code object attribute)
@geindex co_kwonlyargcount (code object attribute)
@geindex co_code (コードオブジェクトの属性)
@geindex co_consts (コードオブジェクトの属性)
@geindex co_filename (コードオブジェクトの属性)
@geindex co_firstlineno (コードオブジェクトの属性)
@geindex co_flags (コードオブジェクトの属性)
@geindex co_lnotab (コードオブジェクトの属性)
@geindex co_name (コードオブジェクトの属性)
@geindex co_names (コードオブジェクトの属性)
@geindex co_nlocals (コードオブジェクトの属性)
@geindex co_stacksize (コードオブジェクトの属性)
@geindex co_varnames (コードオブジェクトの属性)
@geindex co_cellvars (コードオブジェクトの属性)
@geindex co_freevars (コードオブジェクトの属性)
@geindex co_qualname (code object attribute)

@menu
* Special read-only attributes: Special read-only attributes<2>. 
* Methods on code objects:: 

@end menu

@node Special read-only attributes<2>,Methods on code objects,,コードオブジェクト
@anchor{reference/datamodel id7}@anchor{2384}
@subsubsection Special read-only attributes



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@geindex co_name (codeobject の属性)
@anchor{reference/datamodel codeobject co_name}@anchor{2385}
@deffn {の属性} codeobject.co_name
@end deffn

@tab

The function name

@item

@geindex co_qualname (codeobject の属性)
@anchor{reference/datamodel codeobject co_qualname}@anchor{2386}
@deffn {の属性} codeobject.co_qualname
@end deffn

@tab

The fully qualified function name


Added in version 3.11.


@item

@geindex co_argcount (codeobject の属性)
@anchor{reference/datamodel codeobject co_argcount}@anchor{2387}
@deffn {の属性} codeobject.co_argcount
@end deffn

@tab

The total number of positional @ref{234b,,parameters}
(including positional-only parameters and parameters with default values)
that the function has

@item

@geindex co_posonlyargcount (codeobject の属性)
@anchor{reference/datamodel codeobject co_posonlyargcount}@anchor{2388}
@deffn {の属性} codeobject.co_posonlyargcount
@end deffn

@tab

The number of positional-only @ref{234b,,parameters}
(including arguments with default values) that the function has

@item

@geindex co_kwonlyargcount (codeobject の属性)
@anchor{reference/datamodel codeobject co_kwonlyargcount}@anchor{2389}
@deffn {の属性} codeobject.co_kwonlyargcount
@end deffn

@tab

The number of keyword-only @ref{234b,,parameters}
(including arguments with default values) that the function has

@item

@geindex co_nlocals (codeobject の属性)
@anchor{reference/datamodel codeobject co_nlocals}@anchor{238a}
@deffn {の属性} codeobject.co_nlocals
@end deffn

@tab

The number of @ref{2346,,local variables} used by the function
(including parameters)

@item

@geindex co_varnames (codeobject の属性)
@anchor{reference/datamodel codeobject co_varnames}@anchor{238b}
@deffn {の属性} codeobject.co_varnames
@end deffn

@tab

A @ref{614,,tuple} containing the names of the local variables in the
function (starting with the parameter names)

@item

@geindex co_cellvars (codeobject の属性)
@anchor{reference/datamodel codeobject co_cellvars}@anchor{238c}
@deffn {の属性} codeobject.co_cellvars
@end deffn

@tab

A @ref{614,,tuple} containing the names of @ref{2346,,local variables}
that are referenced from at least one @ref{238d,,nested scope} inside the function

@item

@geindex co_freevars (codeobject の属性)
@anchor{reference/datamodel codeobject co_freevars}@anchor{2347}
@deffn {の属性} codeobject.co_freevars
@end deffn

@tab

A @ref{614,,tuple} containing the names of
@ref{1893,,free (closure) variables} that a @ref{238d,,nested scope}
references in an outer scope. See also @ref{14e8,,function.__closure__}.

Note: references to global and builtin names are `not' included.

@item

@geindex co_code (codeobject の属性)
@anchor{reference/datamodel codeobject co_code}@anchor{238e}
@deffn {の属性} codeobject.co_code
@end deffn

@tab

A string representing the sequence of @ref{4aa,,bytecode} instructions in
the function

@item

@geindex co_consts (codeobject の属性)
@anchor{reference/datamodel codeobject co_consts}@anchor{189b}
@deffn {の属性} codeobject.co_consts
@end deffn

@tab

A @ref{614,,tuple} containing the literals used by the @ref{4aa,,bytecode} in
the function

@item

@geindex co_names (codeobject の属性)
@anchor{reference/datamodel codeobject co_names}@anchor{238f}
@deffn {の属性} codeobject.co_names
@end deffn

@tab

A @ref{614,,tuple} containing the names used by the @ref{4aa,,bytecode} in
the function

@item

@geindex co_filename (codeobject の属性)
@anchor{reference/datamodel codeobject co_filename}@anchor{1585}
@deffn {の属性} codeobject.co_filename
@end deffn

@tab

The name of the file from which the code was compiled

@item

@geindex co_firstlineno (codeobject の属性)
@anchor{reference/datamodel codeobject co_firstlineno}@anchor{2390}
@deffn {の属性} codeobject.co_firstlineno
@end deffn

@tab

The line number of the first line of the function

@item

@geindex co_lnotab (codeobject の属性)
@anchor{reference/datamodel codeobject co_lnotab}@anchor{330}
@deffn {の属性} codeobject.co_lnotab
@end deffn

@tab

A string encoding the mapping from @ref{4aa,,bytecode} offsets to line
numbers. For details, see the source code of the interpreter.


バージョン 3.12 で非推奨: This attribute of code objects is deprecated, and may be removed in
Python 3.15.


@item

@geindex co_stacksize (codeobject の属性)
@anchor{reference/datamodel codeobject co_stacksize}@anchor{2391}
@deffn {の属性} codeobject.co_stacksize
@end deffn

@tab

The required stack size of the code object

@item

@geindex co_flags (codeobject の属性)
@anchor{reference/datamodel codeobject co_flags}@anchor{18db}
@deffn {の属性} codeobject.co_flags
@end deffn

@tab

An @ref{19b,,integer} encoding a number of flags for the
interpreter.

@end multitable


@geindex object;ジェネレータ

The following flag bits are defined for @ref{18db,,co_flags}:
bit @code{0x04} is set if
the function uses the @code{*arguments} syntax to accept an arbitrary number of
positional arguments; bit @code{0x08} is set if the function uses the
@code{**keywords} syntax to accept arbitrary keyword arguments; bit @code{0x20} is set
if the function is a generator. See @ref{2392,,Code Objects Bit Flags} for details
on the semantics of each flags that might be present.

Future feature declarations (for example, @code{from __future__ import division}) also use bits
in @ref{18db,,co_flags} to indicate whether a code object was compiled with a
particular feature enabled. See @ref{2393,,compiler_flag}.

Other bits in @ref{18db,,co_flags} are reserved for internal use.

@geindex ドキュメント文字列

If a code object represents a function and has a docstring,
the @ref{2394,,CO_HAS_DOCSTRING} bit is set in @ref{18db,,co_flags}
and the first item in @ref{189b,,co_consts} is
the docstring of the function.

@node Methods on code objects,,Special read-only attributes<2>,コードオブジェクト
@anchor{reference/datamodel methods-on-code-objects}@anchor{2395}
@subsubsection Methods on code objects


@geindex co_positions() (codeobject のメソッド)
@anchor{reference/datamodel codeobject co_positions}@anchor{7d0}
@deffn {メソッド} codeobject.co_positions ()

Returns an iterable over the source code positions of each @ref{4aa,,bytecode}
instruction in the code object.

The iterator returns @ref{614,,tuple}s containing the @code{(start_line, end_line,
start_column, end_column)}. The `i-th' tuple corresponds to the
position of the source code that compiled to the `i-th' code unit.
Column information is 0-indexed utf-8 byte offsets on the given source
line.

This positional information can be missing. A non-exhaustive lists of
cases where this may happen:


@itemize -

@item 
Running the interpreter with @ref{16f,,-X} @code{no_debug_ranges}.

@item 
Loading a pyc file compiled while using @ref{16f,,-X} @code{no_debug_ranges}.

@item 
Position tuples corresponding to artificial instructions.

@item 
Line and column numbers that can't be represented due to
implementation specific limitations.
@end itemize

When this occurs, some or all of the tuple elements can be
@ref{885,,None}.


Added in version 3.11.


@cartouche
@quotation 注釈 
This feature requires storing column positions in code objects which may
result in a small increase of disk usage of compiled Python files or
interpreter memory usage. To avoid storing the extra information and/or
deactivate printing the extra traceback information, the
@ref{16f,,-X} @code{no_debug_ranges} command line flag or the 
@geindex PYTHONNODEBUGRANGES
@geindex 環境変数; PYTHONNODEBUGRANGES
@ref{7d3,,PYTHONNODEBUGRANGES}
environment variable can be used.
@end quotation
@end cartouche
@end deffn

@geindex co_lines() (codeobject のメソッド)
@anchor{reference/datamodel codeobject co_lines}@anchor{350}
@deffn {メソッド} codeobject.co_lines ()

Returns an iterator that yields information about successive ranges of
@ref{4aa,,bytecode}s. Each item yielded is a @code{(start, end, lineno)}
@ref{614,,tuple}:


@itemize *

@item 
@code{start} (an @ref{19b,,int}) represents the offset (inclusive) of the start
of the @ref{4aa,,bytecode} range

@item 
@code{end} (an @ref{19b,,int}) represents the offset (exclusive) of the end of
the @ref{4aa,,bytecode} range

@item 
@code{lineno} is an @ref{19b,,int} representing the line number of the
@ref{4aa,,bytecode} range, or @code{None} if the bytecodes in the given range
have no line number
@end itemize

The items yielded will have the following properties:


@itemize *

@item 
The first range yielded will have a @code{start} of 0.

@item 
The @code{(start, end)} ranges will be non-decreasing and consecutive. That
is, for any pair of @ref{614,,tuple}s, the @code{start} of the second will be
equal to the @code{end} of the first.

@item 
No range will be backwards: @code{end >= start} for all triples.

@item 
The last @ref{614,,tuple} yielded will have @code{end} equal to the size of the
@ref{4aa,,bytecode}.
@end itemize

Zero-width ranges, where @code{start == end}, are allowed. Zero-width ranges
are used for lines that are present in the source code, but have been
eliminated by the @ref{4aa,,bytecode} compiler.


Added in version 3.10.



@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 626

@item PEP 626@footnote{https://peps.python.org/pep-0626/} - Precise line numbers for debugging and other tools.

The PEP that introduced the @code{co_lines()} method.
@end table

@end deffn

@geindex replace() (codeobject のメソッド)
@anchor{reference/datamodel codeobject replace}@anchor{2396}
@deffn {メソッド} codeobject.replace (**kwargs)

Return a copy of the code object with new values for the specified fields.

Code objects are also supported by the generic function @ref{1c0,,copy.replace()}.


Added in version 3.8.

@end deffn

@node フレーム frame オブジェクト,トレースバック traceback オブジェクト,コードオブジェクト,内部型 internal type
@anchor{reference/datamodel frame-objects}@anchor{8ef}@anchor{reference/datamodel id8}@anchor{2397}
@subsubsection フレーム (frame) オブジェクト


@geindex object;フレーム

Frame objects represent execution frames.  They may occur in
@ref{cec,,traceback objects},
and are also passed to registered trace functions.

@geindex f_back (フレーム属性)
@geindex f_code (フレーム属性)
@geindex f_globals (フレーム属性)
@geindex f_locals (フレーム属性)
@geindex f_lasti (フレーム属性)
@geindex f_builtins (フレーム属性)
@geindex f_generator (frame attribute)

@menu
* Special read-only attributes: Special read-only attributes<3>. 
* Special writable attributes: Special writable attributes<2>. 
* Frame object methods:: 

@end menu

@node Special read-only attributes<3>,Special writable attributes<2>,,フレーム frame オブジェクト
@anchor{reference/datamodel id9}@anchor{2398}
@subsubsection Special read-only attributes



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@geindex f_back (frame の属性)
@anchor{reference/datamodel frame f_back}@anchor{98f}
@deffn {の属性} frame.f_back
@end deffn

@tab

Points to the previous stack frame (towards the caller),
or @code{None} if this is the bottom stack frame

@item

@geindex f_code (frame の属性)
@anchor{reference/datamodel frame f_code}@anchor{2399}
@deffn {の属性} frame.f_code
@end deffn

@tab

The @ref{4e6,,code object} being executed in this frame.
Accessing this attribute raises an @ref{1c6e,,auditing event}
@code{object.__getattr__} with arguments @code{obj} and @code{"f_code"}.

@item

@geindex f_locals (frame の属性)
@anchor{reference/datamodel frame f_locals}@anchor{4a5}
@deffn {の属性} frame.f_locals
@end deffn

@tab

The mapping used by the frame to look up
@ref{2346,,local variables}.
If the frame refers to an @ref{4a1,,optimized scope},
this may return a write-through proxy object.


バージョン 3.13 で変更: Return a proxy for optimized scopes.


@item

@geindex f_globals (frame の属性)
@anchor{reference/datamodel frame f_globals}@anchor{239a}
@deffn {の属性} frame.f_globals
@end deffn

@tab

The dictionary used by the frame to look up
@ref{2346,,global variables}

@item

@geindex f_builtins (frame の属性)
@anchor{reference/datamodel frame f_builtins}@anchor{239b}
@deffn {の属性} frame.f_builtins
@end deffn

@tab

The dictionary used by the frame to look up
@ref{2346,,built-in (intrinsic) names}

@item

@geindex f_lasti (frame の属性)
@anchor{reference/datamodel frame f_lasti}@anchor{a88}
@deffn {の属性} frame.f_lasti
@end deffn

@tab

The "precise instruction" of the frame object
(this is an index into the @ref{4aa,,bytecode} string of the
@ref{4e6,,code object})

@item

@geindex f_generator (frame の属性)
@anchor{reference/datamodel frame f_generator}@anchor{239c}
@deffn {の属性} frame.f_generator
@end deffn

@tab

The @ref{126c,,generator} or @ref{6b9,,coroutine} object that owns this frame,
or @code{None} if the frame is a normal function.


Added in version 3.14.


@end multitable


@geindex f_trace (フレーム属性)
@geindex f_trace_lines (frame attribute)
@geindex f_trace_opcodes (frame attribute)
@geindex f_lineno (フレーム属性)

@node Special writable attributes<2>,Frame object methods,Special read-only attributes<3>,フレーム frame オブジェクト
@anchor{reference/datamodel id10}@anchor{239d}
@subsubsection Special writable attributes



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@geindex f_trace (frame の属性)
@anchor{reference/datamodel frame f_trace}@anchor{239e}
@deffn {の属性} frame.f_trace
@end deffn

@tab

If not @code{None}, this is a function called for various events during
code execution (this is used by debuggers). Normally an event is
triggered for each new source line (see @ref{dd6,,f_trace_lines}).

@item

@geindex f_trace_lines (frame の属性)
@anchor{reference/datamodel frame f_trace_lines}@anchor{dd6}
@deffn {の属性} frame.f_trace_lines
@end deffn

@tab

Set this attribute to @ref{d2b,,False} to disable triggering a tracing
event for each source line.

@item

@geindex f_trace_opcodes (frame の属性)
@anchor{reference/datamodel frame f_trace_opcodes}@anchor{dd7}
@deffn {の属性} frame.f_trace_opcodes
@end deffn

@tab

Set this attribute to @ref{e07,,True} to allow per-opcode events to be
requested. Note that this may lead to
undefined interpreter behaviour if exceptions raised by the trace
function escape to the function being traced.

@item

@geindex f_lineno (frame の属性)
@anchor{reference/datamodel frame f_lineno}@anchor{9af}
@deffn {の属性} frame.f_lineno
@end deffn

@tab

The current line number of the frame -- writing to this
from within a trace function jumps to the given line (only for the bottom-most
frame).  A debugger can implement a Jump command (aka Set Next Statement)
by writing to this attribute.

@end multitable


@node Frame object methods,,Special writable attributes<2>,フレーム frame オブジェクト
@anchor{reference/datamodel frame-object-methods}@anchor{239f}
@subsubsection Frame object methods


フレームオブジェクトはメソッドを一つサポートします:

@geindex clear() (frame のメソッド)
@anchor{reference/datamodel frame clear}@anchor{585}
@deffn {メソッド} frame.clear ()

This method clears all references to @ref{2346,,local variables} held by the
frame.  Also, if the frame belonged to a @ref{126c,,generator}, the generator
is finalized.  This helps break reference cycles involving frame
objects (for example when catching an @ref{1c27,,exception}
and storing its @ref{cec,,traceback} for later use).

@ref{244,,RuntimeError} is raised if the frame is currently executing
or suspended.


Added in version 3.4.



バージョン 3.13 で変更: Attempting to clear a suspended frame raises @ref{244,,RuntimeError}
(as has always been the case for executing frames).

@end deffn

@node トレースバック traceback オブジェクト,スライス slice オブジェクト,フレーム frame オブジェクト,内部型 internal type
@anchor{reference/datamodel id11}@anchor{23a0}@anchor{reference/datamodel traceback-objects}@anchor{cec}
@subsubsection トレースバック (traceback) オブジェクト


@geindex object;traceback
@geindex スタック;トレース
@geindex 例外;ハンドラ
@geindex 実行;スタック
@geindex exc_info (sys モジュール)
@geindex last_traceback (sys モジュール)
@geindex sys.exc_info
@geindex sys.exception
@geindex sys.last_traceback

Traceback objects represent the stack trace of an @ref{2072,,exception}.
A traceback object
is implicitly created when an exception occurs, and may also be explicitly
created by calling @ref{cea,,types.TracebackType}.


バージョン 3.7 で変更: Traceback objects can now be explicitly instantiated from Python code.


For implicitly created tracebacks, when the search for an exception handler
unwinds the execution stack, at each unwound level a traceback object is
inserted in front of the current traceback.  When an exception handler is
entered, the stack trace is made available to the program. (See section
@ref{8f8,,try 文}.) It is accessible as the third item of the
tuple returned by @ref{89a,,sys.exc_info()}, and as the
@ref{14de,,__traceback__} attribute
of the caught exception.

When the program contains no suitable
handler, the stack trace is written (nicely formatted) to the standard error
stream; if the interpreter is interactive, it is also made available to the user
as @ref{6e8,,sys.last_traceback}.

For explicitly created tracebacks, it is up to the creator of the traceback
to determine how the @ref{ceb,,tb_next} attributes should be linked to
form a full stack trace.

@geindex tb_frame (トレースバック属性)
@geindex tb_lineno (トレースバック属性)
@geindex tb_lasti (トレースバック属性)
@geindex statement;try

Special read-only attributes:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@geindex tb_frame (traceback の属性)
@anchor{reference/datamodel traceback tb_frame}@anchor{23a1}
@deffn {の属性} traceback.tb_frame
@end deffn

@tab

Points to the execution @ref{8ef,,frame} of the current
level.

Accessing this attribute raises an
@ref{1c6e,,auditing event} @code{object.__getattr__} with arguments
@code{obj} and @code{"tb_frame"}.

@item

@geindex tb_lineno (traceback の属性)
@anchor{reference/datamodel traceback tb_lineno}@anchor{23a2}
@deffn {の属性} traceback.tb_lineno
@end deffn

@tab

Gives the line number where the exception occurred

@item

@geindex tb_lasti (traceback の属性)
@anchor{reference/datamodel traceback tb_lasti}@anchor{23a3}
@deffn {の属性} traceback.tb_lasti
@end deffn

@tab

Indicates the "precise instruction".

@end multitable


The line number and last instruction in the traceback may differ from the
line number of its @ref{8ef,,frame object} if the exception
occurred in a
@ref{8f8,,try} statement with no matching except clause or with a
@ref{1b0,,finally} clause.

@geindex tb_next (トレースバック属性)

@geindex tb_next (traceback の属性)
@anchor{reference/datamodel traceback tb_next}@anchor{ceb}
@deffn {の属性} traceback.tb_next

The special writable attribute @code{tb_next} is the next level in the
stack trace (towards the frame where the exception occurred), or @code{None} if
there is no next level.


バージョン 3.7 で変更: This attribute is now writable

@end deffn

@node スライス slice オブジェクト,静的メソッド static method オブジェクト,トレースバック traceback オブジェクト,内部型 internal type
@anchor{reference/datamodel slice-objects}@anchor{23a4}
@subsubsection スライス (slice) オブジェクト


@geindex 組み込み関数;slice

スライスオブジェクトは、 @ref{588,,__getitem__()} メソッドのためのスライスを表すのに使われます。スライスオブジェクトは組み込みの @ref{694,,slice()} 関数でも生成されます。

@geindex start (スライスオブジェクトの属性)
@geindex stop (スライスオブジェクトの属性)
@geindex step (スライスオブジェクトの属性)

読み出し専用の特殊属性: @ref{23a5,,start} は下限です; @ref{23a6,,stop} は上限です; @ref{23a7,,step} はステップの値です; それぞれ省略された場合は @code{None} となっています。これらの属性は任意の型を持てます。

スライスオブジェクトはメソッドを一つサポートします:

@geindex indices() (slice のメソッド)
@anchor{reference/datamodel slice indices}@anchor{1228}
@deffn {メソッド} slice.indices (self, length)

このメソッドは単一の整数引数 `length' を取り、スライスオブジェクトが `length' 要素のシーケンスに適用されたときに表現する、スライスに関する情報を計算します。このメソッドは 3 つの整数からなるタプルを返します; それぞれ `start' および `stop' のインデックスと、`step' すなわちスライスのまたぎ幅です。インデックス値がないか、範囲外の値であれば、通常のスライスと変わらないやりかたで扱われます。
@end deffn

@node 静的メソッド static method オブジェクト,クラスメソッドオブジェクト,スライス slice オブジェクト,内部型 internal type
@anchor{reference/datamodel static-method-objects}@anchor{23a8}
@subsubsection 静的メソッド (static method) オブジェクト


静的メソッドは、上で説明したような関数オブジェクトからメソッドオブジェクトへの変換を阻止するための方法を提供します。静的メソッドオブジェクトは他の何らかのオブジェクト、通常はユーザ定義メソッドオブジェクトを包むラッパです。静的メソッドをクラスやクラスインスタンスから取得すると、実際に返されるオブジェクトはラップされたオブジェクトになり、それ以上は変換の対象にはなりません。静的メソッドオブジェクトは通常呼び出し可能なオブジェクトをラップしますが、静的オブジェクト自体は呼び出し可能です。静的オブジェクトは組み込みコンストラクタ @ref{453,,staticmethod()} で生成されます。

@node クラスメソッドオブジェクト,,静的メソッド static method オブジェクト,内部型 internal type
@anchor{reference/datamodel class-method-objects}@anchor{23a9}
@subsubsection クラスメソッドオブジェクト


A class method object, like a static method object, is a wrapper around another
object that alters the way in which that object is retrieved from classes and
class instances. The behaviour of class method objects upon such retrieval is
described above, under @ref{20a7,,"instance methods"}. Class method objects are created
by the built-in @ref{48e,,classmethod()} constructor.

@node 特殊メソッド名,コルーチン,標準型の階層,データモデル
@anchor{reference/datamodel special-method-names}@anchor{23aa}@anchor{reference/datamodel specialnames}@anchor{e68}
@subsection 特殊メソッド名


@geindex operator;オーバーロード
@geindex __getitem__() (マップオブジェクトのメソッド)

クラスは、特殊な名前のメソッドを定義して、特殊な構文 (算術演算や添え字表記、スライス表記など) による特定の演算を実装できます。これは、Python の演算子オーバロード (`operator overloading') へのアプローチです。これにより、クラスは言語の演算子に対する独自の振る舞いを定義できます。例えば、あるクラスが @ref{588,,__getitem__()} という名前のメソッドを定義しており、 @code{x} がこのクラスのインスタンスであるとすると、 @code{x[i]} は @code{type(x).__getitem__(x, i)} とほぼ等価です。特に注釈のない限り、適切なメソッドが定義されていないとき、このような演算を試みると例外 (たいていは @ref{5f0,,AttributeError} か @ref{198,,TypeError}) が送出されます。

特殊メソッドに @code{None} を設定することは、それに対応する演算が利用できないことを意味します。
例えば、クラスの @ref{e69,,__iter__()} を @code{None} に設定した場合、そのクラスはイテラブルにはならず、そのインスタンスに対し @ref{9d7,,iter()} を呼び出すと (@ref{588,,__getitem__()} に処理が戻されずに) @ref{198,,TypeError} を送出します。 @footnote{
The @ref{cf3,,__hash__()}, @ref{e69,,__iter__()},
@ref{e86,,__reversed__()}, @ref{15d3,,__contains__()},
@ref{943,,__class_getitem__()} and @ref{e4c,,__fspath__()}
methods have special handling for this. Others
will still raise a @ref{198,,TypeError}, but may do so by relying on
the behavior that @code{None} is not callable.
}

When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled.  For example, some sequences may work well with retrieval
of individual elements, but extracting a slice may not make sense.
(One example of this is the @ref{23ab,,NodeList} interface
in the W3C's Document Object Model.)

@menu
* 基本的なカスタマイズ:: 
* 属性値アクセスをカスタマイズする:: 
* クラス生成をカスタマイズする:: 
* インスタンスのカスタマイズとサブクラスチェック:: 
* ジェネリック型をエミュレートする:: 
* 呼び出し可能オブジェクトをエミュレートする:: 
* コンテナをエミュレートする:: 
* 数値型をエミュレートする:: 
* with文とコンテキストマネージャ:: 
* クラスパターンマッチの位置引数のカスタマイズ:: 
* Emulating buffer types:: 
* Annotations:: 
* 特殊メソッド検索:: 

@end menu

@node 基本的なカスタマイズ,属性値アクセスをカスタマイズする,,特殊メソッド名
@anchor{reference/datamodel basic-customization}@anchor{23ac}@anchor{reference/datamodel customization}@anchor{23ad}
@subsubsection 基本的なカスタマイズ


@geindex __new__() (object のメソッド)
@anchor{reference/datamodel object __new__}@anchor{7a0}
@deffn {メソッド} object.__new__ (cls[, ...])

@geindex サブクラス化;変更不能な型

クラス `cls' の新しいインスタンスを作るために呼び出されます。 @ref{7a0,,__new__()} は静的メソッドで (このメソッドは特別扱いされているので、明示的に静的メソッドと宣言する必要はありません)、インスタンスを生成するよう要求されているクラスを第一引数にとります。残りの引数はオブジェクトのコンストラクタの式 (クラスの呼び出し文) に渡されます。 @ref{7a0,,__new__()} の戻り値は新しいオブジェクトのインスタンス (通常は `cls' のインスタンス) でなければなりません。

典型的な実装では、クラスの新たなインスタンスを生成するときには @code{super().__new__(cls[, ...])} に適切な引数を指定してスーパクラスの @ref{7a0,,__new__()} メソッドを呼び出し、新たに生成されたインスタンスに必要な変更を加えてから返します。

もし @ref{7a0,,__new__()} が オブジェクトの作成中に呼び出され、`cls' のインスタンスを返した場合には、 @code{__init__(self[, ...])} のようにして新しいインスタンスの @ref{8bf,,__init__()} が呼び出されます。このとき、 `self' は新たに生成されたインスタンスで、残りの引数はオブジェクトコンストラクタに渡された引数と同じになります。

@ref{7a0,,__new__()} が `cls' のインスタンスを返さない場合、インスタンスの @ref{8bf,,__init__()} メソッドは呼び出されません。

@ref{7a0,,__new__()} の主な目的は、変更不能な型 (int, str, tuple など) のサブクラスでインスタンス生成をカスタマイズすることにあります。また、クラス生成をカスタマイズするために、カスタムのメタクラスでよくオーバーライドされます。
@end deffn

@geindex __init__() (object のメソッド)
@anchor{reference/datamodel object __init__}@anchor{8bf}
@deffn {メソッド} object.__init__ (self[, ...])

@geindex クラス;コンストラクタ

インスタンスが (@ref{7a0,,__new__()} によって) 生成された後、それが呼び出し元に返される前に呼び出されます。引数はクラスのコンストラクタ式に渡したものです。基底クラスとその派生クラスがともに @ref{8bf,,__init__()} メソッドを持つ場合、派生クラスの @ref{8bf,,__init__()} メソッドは基底クラスの @ref{8bf,,__init__()} メソッドを明示的に呼び出して、インスタンスの基底クラス部分が適切に初期化されること保証しなければなりません。例えば、 @code{super().__init__([args...])} 。

@ref{7a0,,__new__()} と @ref{8bf,,__init__()} は連携してオブジェクトを構成する (@ref{7a0,,__new__()} が作成し、 @ref{8bf,,__init__()} がそれをカスタマイズする) ので、 @ref{8bf,,__init__()} から非 @code{None} 値を返してはいけません; そうしてしまうと、実行時に @ref{198,,TypeError} が送出されてしまいます。
@end deffn

@geindex __del__() (object のメソッド)
@anchor{reference/datamodel object __del__}@anchor{11ff}
@deffn {メソッド} object.__del__ (self)

@geindex デストラクタ
@geindex finalizer
@geindex statement;del

インスタンスが破棄されるときに呼び出されます。
これはファイナライザや (適切ではありませんが) デストラクタとも呼ばれます。
基底クラスが @ref{11ff,,__del__()} メソッドを持っている場合は、派生クラスの @ref{11ff,,__del__()} メソッドは何であれ、基底クラスの @ref{11ff,,__del__()}  メソッドを明示的に呼び出して、インスタンスの基底クラス部分をきちんと確実に削除しなければなりません。

@ref{11ff,,__del__()} メソッドが破棄しようとしているインスタンスへの新しい参照を作り、破棄を送らせることは (推奨されないものの) 可能です。
これはオブジェクトの `復活' と呼ばれます。
復活したオブジェクトが再度破棄される直前に @ref{11ff,,__del__()} が呼び出されるかどうかは実装依存です;
現在の @ref{905,,CPython} の実装では最初の一回しか呼び出されません。

It is not guaranteed that @ref{11ff,,__del__()} methods are called for objects
that still exist when the interpreter exits.
@ref{c6f,,weakref.finalize} provides a straightforward way to register
a cleanup function to be called when an object is garbage collected.

@cartouche
@quotation 注釈 
@code{del x} は直接 @code{x.__del__()} を呼び出しません --- 前者は @code{x} の参照カウントを 1 つ減らし、後者は @code{x} の参照カウントが 0 まで落ちたときのみ呼び出されます。
@end quotation
@end cartouche

`CPython 実装の詳細:' It is possible for a reference cycle to prevent the reference count
of an object from going to zero.  In this case, the cycle will be
later detected and deleted by the @ref{17d8,,cyclic garbage collector}.  A common cause of reference cycles is when
an exception has been caught in a local variable.  The frame's
locals then reference the exception, which references its own
traceback, which references the locals of all frames caught in the
traceback.


@subsubheading 参考


@ref{64,,gc} モジュールのドキュメント。


@cartouche
@quotation 警告 
メソッド @ref{11ff,,__del__()} は不安定な状況で呼び出されるため、実行中に発生した例外は無視され、代わりに @code{sys.stderr} に警告が表示されます。特に:


@itemize *

@item 
@ref{11ff,,__del__()} は、任意のコードが実行されているときに、任意のスレッドから呼び出せます。
@ref{11ff,,__del__()} で、ロックを取ったり、ブロックするリソースを呼び出したりする必要がある場合、 @ref{11ff,,__del__()} の実行により中断されたコードにより、そのリソースが既に取得されていて、デッドロックが起きるかもしれません。

@item 
@ref{11ff,,__del__()} は、インタプリタのシャットダウン中に実行できます。
従って、(他のモジュールも含めた) アクセスする必要があるグローバル変数はすでに削除されているか、 @code{None} に設定されているかもしれません。
Python は、単一のアンダースコアで始まる名前のグローバルオブジェクトは、他のグローバル変数が削除される前にモジュールから削除されることを保証します; そのようなグローバル変数への他からの参照が存在しない場合、@ref{11ff,,__del__()} メソッドが呼ばれた時点で、インポートされたモジュールがまだ利用可能であることを保証するのに役立つかもしれません。
@end itemize
@end quotation
@end cartouche

@geindex repr() (組み込み関数);__repr__() (オブジェクトメソッド)
@end deffn

@geindex __repr__() (object のメソッド)
@anchor{reference/datamodel object __repr__}@anchor{82f}
@deffn {メソッド} object.__repr__ (self)

@ref{1c1,,repr()} 組み込み関数によって呼び出され、オブジェクトを表す「公式の (official)」文字列を計算します。可能なら、これは (適切な環境が与えられれば) 同じ値のオブジェクトを再生成するのに使える、有効な Python 式のようなものであるべきです。できないなら、 @code{<...some useful description...>} 形式の文字列が返されるべきです。戻り値は文字列オブジェクトでなければなりません。クラスが @ref{82f,,__repr__()} を定義していて @ref{830,,__str__()} は定義していなければ、そのクラスのインスタンスの「非公式の (informal)」文字列表現が要求されたときにも @ref{82f,,__repr__()} が使われます。

This is typically used for debugging, so it is important that the representation
is information-rich and unambiguous. A default implementation is provided by the
@ref{c7e,,object} class itself.

@geindex string;__str__() (オブジェクトメソッド)
@geindex format() (組み込み関数);__str__() (オブジェクトメソッド)
@geindex print() (組み込み関数);__str__() (オブジェクトメソッド)
@end deffn

@geindex __str__() (object のメソッド)
@anchor{reference/datamodel object __str__}@anchor{830}
@deffn {メソッド} object.__str__ (self)

Called by @ref{169,,str(object)}, the default @ref{831,,__format__()} implementation,
and the built-in function @ref{1177,,print()}, to compute the "informal" or nicely
printable string representation of an object.  The return value must be a
@ref{1fe0,,str} object.

@ref{830,,__str__()} が有効な Python 表現を返すことが期待されないという点で、このメソッドは @ref{82f,,object.__repr__()} とは異なります: より便利な、または簡潔な表現を使用することができます。

組み込み型 @ref{c7e,,object} によって定義されたデフォルト実装は、 @ref{82f,,object.__repr__()} を呼び出します。

@c XXX what about subclasses of string?
@end deffn

@geindex __bytes__() (object のメソッド)
@anchor{reference/datamodel object __bytes__}@anchor{7fe}
@deffn {メソッド} object.__bytes__ (self)

@geindex 組み込み関数;bytes

Called by @ref{1e9a,,bytes} to compute a byte-string representation
of an object. This should return a @ref{192,,bytes} object. The @ref{c7e,,object}
class itself does not provide this method.

@geindex string;__format__() (オブジェクトメソッド)
@geindex string;変換
@geindex 組み込み関数;print
@end deffn

@geindex __format__() (object のメソッド)
@anchor{reference/datamodel object __format__}@anchor{831}
@deffn {メソッド} object.__format__ (self, format_spec)

@ref{199,,format()} 組み込み関数、さらには @ref{19a,,フォーマット済み文字列リテラル} の評価、 @ref{833,,str.format()} メソッドによって呼び出され、オブジェクトの "フォーマット化された (formatted)" 文字列表現を作ります。 `format_spec' 引数は、 必要なフォーマット化オプションの記述を含む文字列です。 `format_spec' 引数の解釈は、 @ref{831,,__format__()} を実装する型によりますが、 ほとんどのクラスは組み込み型のいずれかにフォーマット化を委譲したり、 同じようなフォーマット化オプション構文を使います。

標準のフォーマット構文の解説は、 @ref{4f9,,書式指定ミニ言語仕様} を参照してください。

戻り値は文字列オブジェクトでなければなりません。

The default implementation by the @ref{c7e,,object} class should be given
an empty `format_spec' string. It delegates to @ref{830,,__str__()}.


バージョン 3.4 で変更: 空でない文字列が渡された場合 @code{object} 自身の __format__ メソッドは @ref{198,,TypeError} を送出します。



バージョン 3.7 で変更: @code{object.__format__(x, '@w{'})} は @code{format(str(x), '@w{'})} ではなく @code{str(x)} と等価になりました。

@end deffn

@geindex __lt__() (object のメソッド)
@geindex __le__() (object のメソッド)
@geindex __eq__() (object のメソッド)
@geindex __ne__() (object のメソッド)
@geindex __gt__() (object のメソッド)
@geindex __ge__() (object のメソッド)
@anchor{reference/datamodel richcmpfuncs}@anchor{23ae}@anchor{reference/datamodel object __lt__}@anchor{14b8}
@deffn {メソッド} object.__lt__ (self, other)
@anchor{reference/datamodel object __le__}@anchor{1522}
@deffnx {メソッド} object.__le__ (self, other)
@anchor{reference/datamodel object __eq__}@anchor{cf2}
@deffnx {メソッド} object.__eq__ (self, other)
@anchor{reference/datamodel object __ne__}@anchor{1730}
@deffnx {メソッド} object.__ne__ (self, other)
@anchor{reference/datamodel object __gt__}@anchor{1523}
@deffnx {メソッド} object.__gt__ (self, other)
@anchor{reference/datamodel object __ge__}@anchor{1524}
@deffnx {メソッド} object.__ge__ (self, other)

@geindex 比較

これらはいわゆる "拡張比較 (rich comparison)" メソッドです。演算子シンボルとメソッド名の対応は以下の通りです: @code{x<y} は @code{x.__lt__(y)} を呼び出します; @code{x<=y} は @code{x.__le__(y)} を呼び出します; @code{x==y} は @code{x.__eq__(y)} を呼び出します; @code{x!=y} は @code{x.__ne__(y)} を呼び出します; @code{x>y} は @code{x.__gt__(y)} を呼び出します; @code{x>=y} は @code{x.__ge__(y)} を呼び出します。

A rich comparison method may return the singleton @ref{1a2,,NotImplemented} if it does
not implement the operation for a given pair of arguments. By convention,
@code{False} and @code{True} are returned for a successful comparison. However, these
methods can return any value, so if the comparison operator is used in a Boolean
context (e.g., in the condition of an @code{if} statement), Python will call
@ref{3c3,,bool()} on the value to determine if the result is true or false.

By default, @code{object} implements @ref{cf2,,__eq__()} by using @code{is}, returning
@ref{1a2,,NotImplemented} in the case of a false comparison:
@code{True if x is y else NotImplemented}. For @ref{1730,,__ne__()}, by default it
delegates to @ref{cf2,,__eq__()} and inverts the result unless it is
@code{NotImplemented}.  There are no other implied relationships among the
comparison operators or default implementations; for example, the truth of
@code{(x<y or x==y)} does not imply @code{x<=y}. To automatically generate ordering
operations from a single root operation, see @ref{1144,,functools.total_ordering()}.

By default, the @ref{c7e,,object} class provides implementations consistent
with @ref{1c20,,値の比較}: equality compares according to
object identity, and order comparisons raise @ref{198,,TypeError}. Each default
method may generate these results directly, but may also return
@ref{1a2,,NotImplemented}.

カスタムの比較演算をサポートしていて、辞書のキーに使うことができる @ref{824,,ハッシュ可能} オブジェクトを作るときの重要な注意点について、 @ref{cf3,,__hash__()} のドキュメント内に書かれているので参照してください。

There are no swapped-argument versions of these methods (to be used when the
left argument does not support the operation but the right argument does);
rather, @ref{14b8,,__lt__()} and @ref{1523,,__gt__()} are each other's reflection,
@ref{1522,,__le__()} and @ref{1524,,__ge__()} are each other's reflection, and
@ref{cf2,,__eq__()} and @ref{1730,,__ne__()} are their own reflection.
If the operands are of different types, and the right operand's type is
a direct or indirect subclass of the left operand's type,
the reflected method of the right operand has priority, otherwise
the left operand's method has priority.  Virtual subclassing is
not considered.

When no appropriate method returns any value other than @ref{1a2,,NotImplemented}, the
@code{==} and @code{!=} operators will fall back to @code{is} and @code{is not}, respectively.
@end deffn

@geindex __hash__() (object のメソッド)
@anchor{reference/datamodel object __hash__}@anchor{cf3}
@deffn {メソッド} object.__hash__ (self)

@geindex object;dictionary
@geindex 組み込み関数;hash

組み込みの @ref{801,,hash()} 関数や、 @ref{184,,set}, @ref{7f2,,frozenset}, @ref{183,,dict} のようなハッシュを使ったコレクション型の要素に対する操作から呼び出されます。
@code{__hash__()} メソッドは整数を返さなければなりません。
このメソッドに必要な性質は、比較結果が等しいオブジェクトは同じハッシュ値を持つということです;
オブジェクトを比較するときでも利用される要素をタプルに詰めてハッシュ値を計算することで、それぞれの要素のハッシュ値を混合することをおすすめします。

@example
def __hash__(self):
    return hash((self.name, self.nick, self.color))
@end example

@cartouche
@quotation 注釈 
@ref{801,,hash()} はオブジェクト独自の @ref{cf3,,__hash__()}  メソッドが返す値を @ref{c55,,Py_ssize_t} のサイズに切り詰めます。
これは 64-bit でビルドされていると 8 バイトで、 32-bit でビルドされていると 4 バイトです。
オブジェクトの @ref{cf3,,__hash__()} が異なる bit サイズのビルドでも可搬性が必要である場合は、必ず全てのサポートするビルドの bit 幅をチェックしてください。
そうする簡単な方法は @code{python -c "import sys; print(sys.hash_info.width)"} を実行することです。
@end quotation
@end cartouche

クラスが @ref{cf2,,__eq__()} メソッドを定義していないなら、 @ref{cf3,,__hash__()} メソッドも定義してはなりません; クラスが @ref{cf2,,__eq__()} を定義していても @ref{cf3,,__hash__()} を定義していないなら、そのインスタンスはハッシュ可能コレクションの要素として使えません。クラスがミュータブルなオブジェクトを定義しており、 @ref{cf2,,__eq__()} メソッドを実装しているなら、 @ref{cf3,,__hash__()} を定義してはなりません。これは、@ref{824,,ハッシュ可能} コレクションの実装においてキーのハッシュ値がイミュータブルであることが要求されているからです (オブジェクトのハッシュ値が変化すると、誤ったハッシュバケツ: hash bucket に入ってしまいます)。

User-defined classes have @ref{cf2,,__eq__()} and @ref{cf3,,__hash__()} methods
by default (inherited from the @ref{c7e,,object} class); with them, all objects compare
unequal (except with themselves) and @code{x.__hash__()} returns an appropriate
value such that @code{x == y} implies both that @code{x is y} and @code{hash(x) == hash(y)}.

@ref{cf2,,__eq__()} をオーバーライドしていて @ref{cf3,,__hash__()} を定義していないクラスでは、 @ref{cf3,,__hash__()} は暗黙的に @code{None} に設定されます。
クラスの @ref{cf3,,__hash__()} メソッドが @code{None} の場合、そのクラスのインスタンスのハッシュ値を取得しようとすると適切な @ref{198,,TypeError} が送出され、 @code{isinstance(obj, collections.abc.Hashable)} でチェックするとハッシュ不能なものとして正しく認識されます。

@ref{cf2,,__eq__()} をオーバーライドしたクラスが親クラスからの @ref{cf3,,__hash__()} の 実装を保持したいなら、明示的に @code{__hash__ = <ParentClass>.__hash__} を設定することで、それをインタプリタに伝えなければなりません。

@ref{cf2,,__eq__()} をオーバーライドしていないクラスがハッシュサポートを抑制したい場合、クラス定義に @code{__hash__ = None} を含めてください。クラス自身で明示的に @ref{198,,TypeError} を送出する @ref{cf3,,__hash__()} を定義すると、 @code{isinstance(obj, collections.abc.Hashable)} 呼び出しで誤ってハッシュ可能と識別されるでしょう。

@cartouche
@quotation 注釈 
デフォルトでは、文字列とバイト列の @ref{cf3,,__hash__()} 値は予測不可能なランダム値で "ソルト" されます。 ハッシュ値は単独の 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'@w{^2}) complexity.  See
@indicateurl{http://ocert.org/advisories/ocert-2011-003.html} for details.

ハッシュ値の変更は、集合のイテレーション順序に影響します。Python はこの順序付けを保証していません (そして通常 32-bit と 64-bit の間でも異なります)。

@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} も参照してください。
@end quotation
@end cartouche


バージョン 3.3 で変更: ハッシュのランダム化がデフォルトで有効になりました。

@end deffn

@geindex __bool__() (object のメソッド)
@anchor{reference/datamodel object __bool__}@anchor{14ed}
@deffn {メソッド} object.__bool__ (self)

@geindex __len__() (マップオブジェクトのメソッド)

Called to implement truth value testing and the built-in operation
@code{bool()}; should return @code{False} or @code{True}.  When this method is not
defined, @ref{178f,,__len__()} is called, if it is defined, and the object is
considered true if its result is nonzero.  If a class defines neither
@code{__len__()} nor @code{__bool__()} (which is true of the @ref{c7e,,object}
class itself), all its instances are considered true.
@end deffn

@node 属性値アクセスをカスタマイズする,クラス生成をカスタマイズする,基本的なカスタマイズ,特殊メソッド名
@anchor{reference/datamodel attribute-access}@anchor{23af}@anchor{reference/datamodel customizing-attribute-access}@anchor{23b0}
@subsubsection 属性値アクセスをカスタマイズする


以下のメソッドを定義して、クラスインスタンスへの属性アクセス ( @code{x.name} の使用、 @code{x.name} への代入、 @code{x.name} の削除) の意味をカスタマイズすることができます。

@c XXX explain how descriptors interfere here!

@geindex __getattr__() (object のメソッド)
@anchor{reference/datamodel object __getattr__}@anchor{6fa}
@deffn {メソッド} object.__getattr__ (self, name)

Called when the default attribute access fails with an @ref{5f0,,AttributeError}
(either @ref{dcb,,__getattribute__()} raises an @ref{5f0,,AttributeError} because
`name' is not an instance attribute or an attribute in the class tree
for @code{self}; or @ref{1701,,__get__()} of a `name' property raises
@ref{5f0,,AttributeError}).  This method should either return the (computed)
attribute value or raise an @ref{5f0,,AttributeError} exception.
The @ref{c7e,,object} class itself does not provide this method.

Note that if the attribute is found through the normal mechanism,
@ref{6fa,,__getattr__()} is not called.  (This is an intentional asymmetry between
@ref{6fa,,__getattr__()} and @ref{237c,,__setattr__()}.) This is done both for efficiency
reasons and because otherwise @ref{6fa,,__getattr__()} would have no way to access
other attributes of the instance.  Note that at least for instance variables,
you can take total control by not inserting any values in the instance attribute
dictionary (but instead inserting them in another object).  See the
@ref{dcb,,__getattribute__()} method below for a way to actually get total control
over attribute access.
@end deffn

@geindex __getattribute__() (object のメソッド)
@anchor{reference/datamodel object __getattribute__}@anchor{dcb}
@deffn {メソッド} object.__getattribute__ (self, name)

クラスのインスタンスに対する属性アクセスを実装するために、無条件に呼び出されます。クラスが @ref{6fa,,__getattr__()} も定義している場合、 @ref{6fa,,__getattr__()} は、 @ref{dcb,,__getattribute__()} で明示的に呼び出すか、 @ref{5f0,,AttributeError} 例外を送出しない限り呼ばれません。このメソッドは (計算された) 属性値を返すか、 @ref{5f0,,AttributeError} 例外を送出します。このメソッドが再帰的に際限なく呼び出されてしまうのを防ぐため、実装の際には常に、必要な属性全てへのアクセスで、例えば @code{object.__getattribute__(self, name)} のように基底クラスのメソッドを同じ属性名を使って呼び出さなければなりません。

@cartouche
@quotation 注釈 
This method may still be bypassed when looking up special methods as the
result of implicit invocation via language syntax or
@ref{234e,,built-in functions}.
See @ref{23b1,,特殊メソッド検索}.
@end quotation
@end cartouche

セキュリティに関わるような @code{obj} と @code{name} を渡しての @code{object.__getattr__} を使った属性アクセスは @ref{1c6e,,監査イベント} を送出します。
@end deffn

@geindex __setattr__() (object のメソッド)
@anchor{reference/datamodel object __setattr__}@anchor{237c}
@deffn {メソッド} object.__setattr__ (self, name, value)

属性の代入が試みられた際に呼び出されます。これは通常の代入の過程 (すなわち、インスタンス辞書への値の代入) の代わりに呼び出されます。`name' は属性名で、`value' はその属性に代入する値です。

@ref{237c,,__setattr__()} の中でインスタンス属性への代入が必要なら、基底クラスのこれと同じ名前のメソッドを呼び出さなければなりません。例えば、 @code{object.__setattr__(self, name, value)} とします。

セキュリティに関わるような @code{obj} と @code{name} と @code{value} を渡しての @code{object.__setattr__} を使った属性のアサインは @ref{1c6e,,監査イベント} を送出します。
@end deffn

@geindex __delattr__() (object のメソッド)
@anchor{reference/datamodel object __delattr__}@anchor{237d}
@deffn {メソッド} object.__delattr__ (self, name)

@ref{237c,,__setattr__()} に似ていますが、代入ではなく値の削除を行います。このメソッドを実装するのは、オブジェクトにとって @code{del obj.name} が意味がある場合だけにしなければなりません。

セキュリティに関わるような @code{obj} と @code{name} を渡しての @code{object.__getattr__} を使った属性の削除は @ref{1c6e,,監査イベント} を送出します。
@end deffn

@geindex __dir__() (object のメソッド)
@anchor{reference/datamodel object __dir__}@anchor{17e2}
@deffn {メソッド} object.__dir__ (self)

Called when @ref{844,,dir()} is called on the object. An iterable must be
returned. @ref{844,,dir()} converts the returned iterable to a list and sorts it.
@end deffn

@menu
* モジュールの属性値アクセスをカスタマイズする:: 
* デスクリプタ (descriptor) の実装: デスクリプタ descriptor の実装. 
* デスクリプタの呼び出し:: 
* __slots__: __slots__<2>. 

@end menu

@node モジュールの属性値アクセスをカスタマイズする,デスクリプタ descriptor の実装,,属性値アクセスをカスタマイズする
@anchor{reference/datamodel customizing-module-attribute-access}@anchor{23b2}
@subsubsection モジュールの属性値アクセスをカスタマイズする


@geindex __getattr__ (module attribute)
@geindex __dir__ (module attribute)
@geindex __class__ (module attribute)

@geindex __getattr__() (module のメソッド)
@geindex __dir__() (module のメソッド)
@anchor{reference/datamodel module __getattr__}@anchor{cd8}
@deffn {メソッド} module.__getattr__ ()
@anchor{reference/datamodel module __dir__}@anchor{cd9}
@deffnx {メソッド} module.__dir__ ()
@end deffn

特殊な名前の @code{__getattr__} と @code{__dir__} も、モジュール属性へのアクセスをカスタマイズするのに使えます。
モジュールレベルの @code{__getattr__} 関数は属性名である 1 引数を受け取り、計算した値を返すか @ref{5f0,,AttributeError} を送出します。
属性がモジュールオブジェクトから、通常の検索、つまり @ref{dcb,,object.__getattribute__()} で見付からなかった場合は、 @ref{5f0,,AttributeError} を送出する前に、モジュールの @code{__dict__} から @code{__getattr__} が検索されます。
見付かった場合は、その属性名で呼び出され、結果が返されます。

The @code{__dir__} function should accept no arguments, and return an iterable of
strings that represents the names accessible on module. If present, this
function overrides the standard @ref{844,,dir()} search on a module.

@geindex __class__ (module の属性)
@anchor{reference/datamodel module __class__}@anchor{23b3}
@deffn {の属性} module.__class__
@end deffn

より細かい粒度でのモジュールの動作 (属性やプロパティの設定など) のカスタマイズのために、モジュールオブジェクトの @code{__class__} 属性に @ref{1014,,types.ModuleType} のサブクラスが設定できます。
例えば次のようになります:

@example
import sys
from types import ModuleType

class VerboseModule(ModuleType):
    def __repr__(self):
        return f'Verbose @{self.__name__@}'

    def __setattr__(self, attr, value):
        print(f'Setting @{attr@}...')
        super().__setattr__(attr, value)

sys.modules[__name__].__class__ = VerboseModule
@end example

@cartouche
@quotation 注釈 
モジュールの @code{__getattr__} を定義したり @code{__class__} を設定したりしても、影響があるのは属性アクセスの構文が使われる検索だけです -- モジュールの globals への直接アクセスは (モジュール内のコードからとモジュールの globals のどちらでも) 影響を受けません。
@end quotation
@end cartouche


バージョン 3.5 で変更: モジュールの属性 @code{__class__} が書き込み可能になりました。



Added in version 3.7: @code{__getattr__} モジュール属性と @code{__dir__} モジュール属性。



@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 562

@item PEP 562@footnote{https://peps.python.org/pep-0562/} - モジュールの __getattr__ と __dir__

モジュールの @code{__getattr__} 関数および @code{__dir__} 関数の説明。
@end table


@node デスクリプタ descriptor の実装,デスクリプタの呼び出し,モジュールの属性値アクセスをカスタマイズする,属性値アクセスをカスタマイズする
@anchor{reference/datamodel descriptors}@anchor{e49}@anchor{reference/datamodel implementing-descriptors}@anchor{23b4}
@subsubsection デスクリプタ (descriptor) の実装


The following methods only apply when an instance of the class containing the
method (a so-called `descriptor' class) appears in an `owner' class (the
descriptor must be in either the owner's class dictionary or in the class
dictionary for one of its parents).  In the examples below, "the attribute"
refers to the attribute whose name is the key of the property in the owner
class' @ref{77d,,__dict__}.  The @ref{c7e,,object} class itself does not
implement any of these protocols.

@geindex __get__() (object のメソッド)
@anchor{reference/datamodel object __get__}@anchor{1701}
@deffn {メソッド} object.__get__ (self, instance, owner=None)

オーナークラス（クラス属性アクセスの場合）や、クラスのインスタンス（インスタンス属性アクセスの場合）の属性取得時に呼び出されます。 `instance'  を通じて属性をアクセスする時に、オプションの `owner' 引数はオーナークラスです。 `owner' を通じて属性アクセスするときは @code{None} です。

このメソッドは、算出された属性値を返すか、 @ref{5f0,,AttributeError} 例外を送出します。

@geindex Python Enhancement Proposals; PEP 252
PEP 252@footnote{https://peps.python.org/pep-0252/} は @ref{1701,,__get__()} は1つや2つの引数を持つ呼び出し可能オブジェクトであると定義しています。Pythonの組み込みのデスクリプタはこの仕様をサポートしていますが、サードパーティ製のツールの中には両方の引数を必要とするものもあります。Pythonの @ref{dcb,,__getattribute__()} 実装は必要かどうかに関わらず、両方の引数を常に渡します。
@end deffn

@geindex __set__() (object のメソッド)
@anchor{reference/datamodel object __set__}@anchor{23b5}
@deffn {メソッド} object.__set__ (self, instance, value)

オーナークラスのインスタンス `instance' 上の属性を新たな値 `value' に設定する際に呼び出されます。

@ref{23b5,,__set__()} あるいは @ref{194f,,__delete__()} を追加すると、デスクリプタは「データデスクリプタ」に変わります。詳細は @ref{23b6,,デスクリプタの呼び出し} を参照してください。
@end deffn

@geindex __delete__() (object のメソッド)
@anchor{reference/datamodel object __delete__}@anchor{194f}
@deffn {メソッド} object.__delete__ (self, instance)

オーナークラスのインスタンス `instance' 上の属性を削除する際に呼び出されます。
@end deffn

Instances of descriptors may also have the @code{__objclass__} attribute
present:

@geindex __objclass__ (object の属性)
@anchor{reference/datamodel object __objclass__}@anchor{23b7}
@deffn {の属性} object.__objclass__

The attribute @code{__objclass__} is interpreted by the @ref{82,,inspect} module
as specifying the class where this object was defined (setting this
appropriately can assist in runtime introspection of dynamic class attributes).
For callables, it may indicate that an instance of the given type (or a
subclass) is expected or required as the first positional argument (for example,
CPython sets this attribute for unbound methods that are implemented in C).
@end deffn

@node デスクリプタの呼び出し,__slots__<2>,デスクリプタ descriptor の実装,属性値アクセスをカスタマイズする
@anchor{reference/datamodel descriptor-invocation}@anchor{23b6}@anchor{reference/datamodel invoking-descriptors}@anchor{23b8}
@subsubsection デスクリプタの呼び出し


一般にデスクリプタとは、特殊な "束縛に関する動作 (binding behaviour)" をもつオブジェクト属性のことです。デスクリプタは、デスクリプタプロトコル (descriptor protocol) のメソッド: @ref{1701,,__get__()}, @ref{23b5,,__set__()}, および @ref{194f,,__delete__()} を使って、属性アクセスをオーバーライドしているものです。これらのメソッドのいずれかがオブジェクトに対して定義されている場合、オブジェクトはデスクリプタであるといいます。

属性アクセスのデフォルトの動作は、オブジェクトの辞書から値を取り出したり、値を設定したり、削除したりするというものです。例えば、 @code{a.x} による属性の検索では、まず @code{a.__dict__['x']} 、次に @code{type(a).__dict__['x']} 、そして @code{type(a)} の基底クラスでメタクラスでないものに続く、といった具合に連鎖が起こります。

しかし、検索対象の値が、デスクリプタメソッドのいずれかを定義しているオブジェクトであれば、Python はデフォルトの動作をオーバーライドして、代わりにデスクリプタメソッドを呼び出します。先述の連鎖の中のどこでデスクリプタメソッドが呼び出されるかは、どのデスクリプタメソッドが定義されていて、どのように呼び出されたかに依存します。

デスクリプタ呼び出しの基点となるのは、属性名への束縛 (binding) 、すなわち @code{a.x} です。引数がどのようにデスクリプタに結合されるかは @code{a} に依存します:


@table @asis

@item 直接呼び出し (Direct Call)

最も単純で、かつめったに使われない呼び出し操作は、コード中で直接デスクリプタメソッドの呼び出し: @code{x.__get__(a)} を行うというものです。

@item インスタンス束縛 (Instance Binding)

オブジェクトインスタンスへ束縛すると、@code{a.x} は呼び出し @code{type(a).__dict__['x'].__get__(a, type(a))} に変換されます。

@item クラス束縛 (Class Binding)

クラスへ束縛すると、@code{A.x} は呼び出し @code{A.__dict__['x'].__get__(None, A)} に変換されます。

@item super 束縛 (Super Binding)

@code{super(A, a).x} のようなドットを使ったルックアップは @code{a.__class__.__mro__} を探索して、 @code{A} の前のクラス @code{B} をまず探し、 @code{B.__dict__['x'].__get__(a, A)} を返します。もしデスクリプタでなければ @code{x} を変更せずに返します。
@end table

@c class Desc:
@c     def __get__(*args):
@c         return args
@c 
@c class B:
@c 
@c     x = Desc()
@c 
@c class A(B):
@c 
@c     x = 999
@c 
@c     def m(self):
@c         'Demonstrate these two descriptor invocations are equivalent'
@c         result1 = super(A, self).x
@c         result2 = B.__dict__['x'].__get__(self, A)
@c         return result1 == result2

@c >>> a = A()
@c >>> a.__class__.__mro__.index(B) > a.__class__.__mro__.index(A)
@c True
@c >>> super(A, a).x == B.__dict__['x'].__get__(a, A)
@c True
@c >>> a.m()
@c True

For instance bindings, the precedence of descriptor invocation depends on
which descriptor methods are defined.  A descriptor can define any combination
of @ref{1701,,__get__()}, @ref{23b5,,__set__()} and
@ref{194f,,__delete__()}.  If it does not
define @code{__get__()}, 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 @code{__set__()} and/or @code{__delete__()}, it is a data
descriptor; if it defines neither, it is a non-data descriptor.  Normally, data
descriptors define both @code{__get__()} and @code{__set__()}, while non-data
descriptors have just the @code{__get__()} method.  Data descriptors with
@code{__get__()} and @code{__set__()} (and/or @code{__delete__()}) 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
@ref{453,,@@staticmethod} and @ref{48e,,@@classmethod}) 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.

@ref{4b3,,property()} 関数はデータデスクリプタとして実装されています。従って、インスタンスはあるプロパティの動作をオーバーライドすることができません。

@node __slots__<2>,,デスクリプタの呼び出し,属性値アクセスをカスタマイズする
@anchor{reference/datamodel id13}@anchor{23b9}@anchor{reference/datamodel slots}@anchor{237f}
@subsubsection __slots__


`__slots__' を使うと、(プロパティのように) データメンバを明示的に宣言し、 (明示的に `__slots__' で宣言しているか親クラスに存在しているかでない限り) @ref{77d,,__dict__} や `__weakref__' を作成しないようにできます。

@ref{77d,,__dict__} を使うのに比べて、節約できるメモリ空間はかなり大きいです。
属性探索のスピードもかなり向上できます。

@geindex object.__slots__ (組み込み変数)
@anchor{reference/datamodel object __slots__}@anchor{1704}
@deffn {データ} object.__slots__

このクラス変数には、インスタンスが用いる変数名を表す、文字列、イテラブル、または文字列のシーケンスを代入できます。`__slots__' は、各インスタンスに対して宣言された変数に必要な記憶領域を確保し、@ref{77d,,__dict__} と `__weakref__' が自動的に生成されないようにします。
@end deffn
@anchor{reference/datamodel datamodel-note-slots}@anchor{23ba}
Notes on using `__slots__':


@itemize *

@item 
`__slots__' を持たないクラスから継承するとき、インスタンスの @ref{77d,,__dict__} 属性と `__weakref__' 属性は常に利用可能です。

@item 
@ref{77d,,__dict__} 変数がない場合、 `__slots__' に列挙されていない新たな変数をインスタンスに代入することはできません。列挙されていない変数名を使って代入しようとした場合、 @ref{5f0,,AttributeError} が送出されます。新たな変数を動的に代入したいのなら、 `__slots__' を宣言する際に @code{'__dict__'} を変数名のシーケンスに追加してください。

@item 
`__slots__' を定義しているクラスの各インスタンスに `__weakref__' 変数がない場合、インスタンスに対する弱参照 (@ref{11a,,weak references}) はサポートされません。弱参照のサポートが必要なら、 `__slots__' を宣言する際に @code{'__weakref__'} を変数名のシーケンスに追加してください。

@item 
`__slots__' は、クラスのレベルで各変数に対する @ref{e49,,デスクリプタ} を使って実装されます。その結果、 `__slots__' に定義されているインスタンス変数のデフォルト値はクラス属性を使って設定できなくなっています; そうしないと、デスクリプタによる代入をクラス属性が上書きしてしまうからです。

@item 
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, instances of a child subclass will get a
@ref{77d,,__dict__} and `__weakref__' unless the subclass also defines
`__slots__' (which should only contain names of any `additional' slots).

@item 
あるクラスで、基底クラスですでに定義されているスロットを定義した場合、基底クラスのスロットで定義されているインスタンス変数は (デスクリプタを基底クラスから直接取得しない限り) アクセスできなくなります。これにより、プログラムの趣意が不定になってしまいます。将来は、この問題を避けるために何らかのチェックが追加されるかもしれません。

@item 
@ref{198,,TypeError} will be raised if nonempty `__slots__' are defined for a
class derived from a
@ref{23bb,,"variable-length" built-in type} such as
@ref{19b,,int}, @ref{192,,bytes}, and @ref{614,,tuple}.

@item 
Any non-string @ref{12f1,,iterable} may be assigned to `__slots__'.

@item 
If a @ref{183,,dictionary} 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
@ref{bed,,inspect.getdoc()} and displayed in the output of @ref{ad4,,help()}.

@item 
@ref{16c6,,__class__} assignment works only if both classes have the
same `__slots__'.

@item 
複数のスロットを持つ親クラスを使った @ref{20a1,,多重継承} はできますが、スロットで作成された属性を持つ親クラスは 1 つに限られます (他の基底クラスのスロットは空でなければなりません) - それに違反すると @ref{198,,TypeError} が送出されます。

@item 
もし `__slots__' に対して @ref{4c8,,イテレータ} を使用すると、イテレータの値ごとに @ref{1881,,デスクリプタ} が作られます。しかし、 `__slots__' 属性は空のイテレータとなります。
@end itemize

@node クラス生成をカスタマイズする,インスタンスのカスタマイズとサブクラスチェック,属性値アクセスをカスタマイズする,特殊メソッド名
@anchor{reference/datamodel class-customization}@anchor{e45}@anchor{reference/datamodel customizing-class-creation}@anchor{23bc}
@subsubsection クラス生成をカスタマイズする


クラスが他のクラスを継承するときに必ず、親クラスの @ref{843,,__init_subclass__()} が呼び出されます。これを利用すると、サブクラスの挙動を変更するクラスを書くことができます。これは、クラスデコレータととても良く似ていますが、クラスデコレータが、それが適用された特定のクラスにのみに影響するのに対して、 @code{__init_subclass__} は、もっぱら、このメソッドを定義したクラスの将来のサブクラスに適用されます。

@geindex __init_subclass__() (object のクラスメソッド)
@anchor{reference/datamodel object __init_subclass__}@anchor{843}
@deffn {メソッド} classmethod object.__init_subclass__ (cls)

このメソッドは、それが定義されたクラスが継承された際に必ず呼び出されます。`cls' は新しいサブクラスです。もし、このメソッドがインスタンスメソッドとして定義されると、暗黙的にクラスメソッドに変換されます。

Keyword arguments which are given to a new class are passed to
the parent class's @code{__init_subclass__}. For compatibility with
other classes using @code{__init_subclass__}, one should take out the
needed keyword arguments and pass the others over to the base
class, as in:

@example
class Philosopher:
    def __init_subclass__(cls, /, default_name, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.default_name = default_name

class AustralianPhilosopher(Philosopher, default_name="Bruce"):
    pass
@end example

@code{object.__init_subclass__} のデフォルト実装は何も行いませんが、何らかの引数とともに呼び出された場合は、エラーを送出します。

@cartouche
@quotation 注釈 
メタクラスのヒント @code{metaclass} は残りの型機構によって消費され、 @code{__init_subclass__} 実装に渡されることはありません。
実際のメタクラス (明示的なヒントではなく) は、 @code{type(cls)} としてアクセスできます。
@end quotation
@end cartouche


Added in version 3.6.

@end deffn

When a class is created, @code{type.__new__()} scans the class variables
and makes callbacks to those with a @ref{e48,,__set_name__()} hook.

@geindex __set_name__() (object のメソッド)
@anchor{reference/datamodel object __set_name__}@anchor{e48}
@deffn {メソッド} object.__set_name__ (self, owner, name)

オーナーとなるクラス `owner' が作成された時点で自動的に呼び出されます。
オブジェクトはそのクラスの `name' に割り当てられます。

@example
class A:
    x = C()  # Automatically calls: x.__set_name__(A, 'x')
@end example

If the class variable is assigned after the class is created,
@ref{e48,,__set_name__()} will not be called automatically.
If needed, @ref{e48,,__set_name__()} can be called directly:

@example
class A:
   pass

c = C()
A.x = c                  # The hook is not called
c.__set_name__(A, 'x')   # Manually invoke the hook
@end example

詳細は @ref{e44,,クラスオブジェクトの作成} を参照してください。


Added in version 3.6.

@end deffn

@menu
* メタクラス:: 
* MRO エントリの解決:: 
* 適切なメタクラスの決定:: 
* クラスの名前空間の準備:: 
* クラス本体の実行:: 
* クラスオブジェクトの作成:: 
* メタクラスの用途:: 

@end menu

@node メタクラス,MRO エントリの解決,,クラス生成をカスタマイズする
@anchor{reference/datamodel id14}@anchor{23bd}@anchor{reference/datamodel metaclasses}@anchor{23be}
@subsubsection メタクラス


@geindex metaclass
@geindex 組み込み関数;type
@geindex = (等号);class definition

デフォルトでは、クラスは @ref{f44,,type()} を使って構築されます。 クラス本体は新しい名前空間で実行され、クラス名が @code{type(name, bases, namespace)} の結果にローカルに束縛されます。

クラス生成プロセスはカスタマイズできます。
そのためにはクラス定義行で @code{metaclass} キーワード引数を渡すか、そのような引数を定義行に含む既存のクラスを継承します。
次の例で @code{MyClass} と @code{MySubclass} は両方とも @code{Meta} のインスタンスです:

@example
class Meta(type):
    pass

class MyClass(metaclass=Meta):
    pass

class MySubclass(MyClass):
    pass
@end example

クラス定義の中で指定された他のキーワード引数は、後述するすべてのメタクラス操作に渡されます。

クラス定義が実行される際に、以下のステップが生じます:


@itemize *

@item 
MRO エントリの解決が行われる;

@item 
適切なメタクラスが決定される;

@item 
クラスの名前空間が準備される;

@item 
クラスの本体が実行される;

@item 
クラスオブジェクトが作られる。
@end itemize

@node MRO エントリの解決,適切なメタクラスの決定,メタクラス,クラス生成をカスタマイズする
@anchor{reference/datamodel resolving-mro-entries}@anchor{23bf}
@subsubsection MRO エントリの解決


@geindex __mro_entries__() (object のメソッド)
@anchor{reference/datamodel object __mro_entries__}@anchor{ce3}
@deffn {メソッド} object.__mro_entries__ (self, bases)

If a base that appears in a class definition is not an instance of
@ref{f44,,type}, then an @code{__mro_entries__()} method is searched on the base.
If an @code{__mro_entries__()} method is found, the base is substituted with the
result of a call to @code{__mro_entries__()} when creating the class.
The method is called with the original bases tuple
passed to the `bases' parameter, and must return a tuple
of classes that will be used instead of the base. The returned tuple may be
empty: in these cases, the original base is ignored.
@end deffn


@subsubheading 参考



@table @asis

@item @ref{d95,,types.resolve_bases()}

Dynamically resolve bases that are not instances of @ref{f44,,type}.

@item @ref{6f5,,types.get_original_bases()}

Retrieve a class's "original bases" prior to modifications by
@ref{ce3,,__mro_entries__()}.

@geindex Python Enhancement Proposals; PEP 560

@item PEP 560@footnote{https://peps.python.org/pep-0560/}

Core support for typing module and generic types.
@end table


@node 適切なメタクラスの決定,クラスの名前空間の準備,MRO エントリの解決,クラス生成をカスタマイズする
@anchor{reference/datamodel determining-the-appropriate-metaclass}@anchor{23c0}
@subsubsection 適切なメタクラスの決定


@geindex metaclass hint

クラス定義に対して適切なメタクラスは、以下のように決定されます:


@itemize *

@item 
基底も明示的なメタクラスも与えられていない場合は、 @ref{f44,,type()} が使われます;

@item 
明示的なメタクラスが与えられていて、それが @ref{f44,,type()} のインスタンス `ではない' 場合、それをメタクラスとして直接使います;

@item 
明示的なメタクラスとして @ref{f44,,type()} のインスタンスが与えられたか、基底が定義されていた場合は、最も派生した (継承関係で最も下の) メタクラスが使われます。
@end itemize

最も派生的なメタクラスは、(もしあれば) 明示的に指定されたメタクラスと、指定されたすべてのベースクラスのメタクラスから選ばれます。最も派生的なメタクラスは、これらのメタクラス候補のすべてのサブタイプであるようなものです。メタクラス候補のどれもその基準を満たさなければ、クラス定義は @code{TypeError} で失敗します。

@node クラスの名前空間の準備,クラス本体の実行,適切なメタクラスの決定,クラス生成をカスタマイズする
@anchor{reference/datamodel prepare}@anchor{e58}@anchor{reference/datamodel preparing-the-class-namespace}@anchor{23c1}
@subsubsection クラスの名前空間の準備


@geindex __prepare__ (metaclass method)

適切なメタクラスが指定されると、クラスの名前空間が用意されます。もしメタクラスが @code{__prepare__} 属性を持っている場合、 @code{namespace = metaclass.__prepare__(name, bases, **kwds)} が呼ばれます。追加のキーワード引数は、もしクラス定義にあれば設定されます。 @code{__prepare__} メソッドは @ref{48e,,クラスメソッド} として実装する必要があります。 @code{__prepare__} が作成して返した名前空間は @code{__new__} に渡されますが、最終的なクラスオブジェクトは新しい @code{dict} にコピーして作成されます。

メタクラスに @code{__prepare__} 属性がない場合、クラスの名前空間は空の 順序付きマッピングとして初期化されます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3115

@item PEP 3115@footnote{https://peps.python.org/pep-3115/} - Metaclasses in Python 3000

@code{__prepare__} 名前空間フックの導入
@end table


@node クラス本体の実行,クラスオブジェクトの作成,クラスの名前空間の準備,クラス生成をカスタマイズする
@anchor{reference/datamodel executing-the-class-body}@anchor{23c2}
@subsubsection クラス本体の実行


@geindex クラス;body

クラス本体が (大まかには) @code{exec(body, globals(), namespace)} として実行されます。通常の呼び出しと @ref{4a2,,exec()} の重要な違いは、クラス定義が関数内部で行われる場合、レキシカルスコープによってクラス本体 (任意のメソッドを含む) が現在のスコープと外側のスコープから名前を参照できるという点です。

しかし、クラス定義が関数内部で行われる時でさえ、クラス内部で定義されたメソッドはクラススコープで定義された名前を見ることはできません。クラス変数はインスタンスメソッドかクラスメソッドの最初のパラメータからアクセスするか、次の節で説明する、暗黙的に静的スコープが切られている @code{__class__} 参照からアクセスしなければなりません。

@node クラスオブジェクトの作成,メタクラスの用途,クラス本体の実行,クラス生成をカスタマイズする
@anchor{reference/datamodel class-object-creation}@anchor{e44}@anchor{reference/datamodel creating-the-class-object}@anchor{23c3}
@subsubsection クラスオブジェクトの作成


@geindex __class__ (method cell)
@geindex __classcell__ (class namespace entry)

クラス本体の実行によってクラスの名前空間が初期化されたら、@code{metaclass(name, bases, namespace, **kwds)} を呼び出すことでクラスオブジェクトが作成されます (ここで渡される追加のキーワードは @code{__prepare__} に渡されるものと同じです)。

このクラスオブジェクトは、 @ref{1a6,,super()} の無引数形式によって参照されるものです。 @code{__class__} は、クラス本体中のメソッドが @code{__class__} または @code{super} のいずれかを参照している場合に、コンパイラによって作成される暗黙のクロージャー参照です。これは、メソッドに渡された最初の引数に基づいて現在の呼び出しを行うために使用されるクラスまたはインスタンスが識別される一方、 @ref{1a6,,super()} の無引数形式がレキシカルスコープに基づいて定義されているクラスを正確に識別することを可能にします。

CPython 3.6 以降では、 @code{__class__} セルは、クラス名前空間にある @code{__classcell__} エントリーとしてメタクラスに渡されます。
@code{__class__} セルが存在していた場合は、そのクラスが正しく初期化されるために、 @code{type.__new__} の呼び出しに到達するまで上に伝搬されます。
失敗した場合は、Python 3.8 では @ref{244,,RuntimeError} になります。

デフォルトのメタクラス @ref{f44,,type} や最終的には @code{type.__new__} を呼び出すメタクラスを使っているときは、クラスオブジェクトを作成した後に次のカスタム化の手順が起動されます:


@enumerate 

@item 
@code{type.__new__} メソッドが @ref{e48,,__set_name__()} が定義されているクラスの名前空間にある全ての属性を収集します;

@item 
それらの @code{__set_name__} メソッドが、そのメソッドが定義されているクラス、およびそこに属する属性に割り当てられている名前を引数として呼び出されます;

@item 
新しいクラスのメソッド解決順序ですぐ上に位置する親クラスで @ref{843,,__init_subclass__()} フックが呼び出されます。
@end enumerate

クラスオブジェクトが作成された後には、クラス定義に含まれているクラスデコレータ (もしあれば) にクラスオブジェクトが渡され、デコレータが返すオブジェクトがここで定義されたクラスとしてローカルの名前空間に束縛されます。

When a new class is created by @code{type.__new__}, the object provided as the
namespace parameter is copied to a new ordered mapping and the original
object is discarded. The new copy is wrapped in a read-only proxy, which
becomes the @ref{e57,,__dict__} attribute of the class object.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3135

@item PEP 3135@footnote{https://peps.python.org/pep-3135/} - New super

暗黙の @code{__class__} クロージャ参照について記述しています
@end table


@node メタクラスの用途,,クラスオブジェクトの作成,クラス生成をカスタマイズする
@anchor{reference/datamodel uses-for-metaclasses}@anchor{23c4}
@subsubsection メタクラスの用途


メタクラスは限りない潜在的利用価値を持っています。これまで試されてきたアイデアには、列挙型、ログ記録、インターフェースのチェック、 自動デリゲーション、自動プロパティ生成、プロキシ、フレームワーク、そして自動リソースロック／同期といったものがあります。

@node インスタンスのカスタマイズとサブクラスチェック,ジェネリック型をエミュレートする,クラス生成をカスタマイズする,特殊メソッド名
@anchor{reference/datamodel customizing-instance-and-subclass-checks}@anchor{23c5}
@subsubsection インスタンスのカスタマイズとサブクラスチェック


以下のメソッドは組み込み関数 @ref{2ad,,isinstance()} と @ref{9c4,,issubclass()} のデフォルトの動作を上書きするのに利用します。

特に、 @ref{111c,,abc.ABCMeta} メタクラスは、抽象基底クラス (ABCs) を"仮想基底クラス (virtual base classes)" として、他の ABC を含む、任意のクラスや (組み込み型を含む) 型に追加するために、これらのメソッドを実装しています。

@geindex __instancecheck__() (type のメソッド)
@anchor{reference/datamodel type __instancecheck__}@anchor{23c6}
@deffn {メソッド} type.__instancecheck__ (self, instance)

`instance' が (直接、または間接的に) `class' のインスタンスと考えられる場合に true を返します。定義されていれば、 @code{isinstance(instance, class)} の実装のために呼び出されます。
@end deffn

@geindex __subclasscheck__() (type のメソッド)
@anchor{reference/datamodel type __subclasscheck__}@anchor{23c7}
@deffn {メソッド} type.__subclasscheck__ (self, subclass)

`subclass' が (直接、または間接的に) `class' のサブクラスと考えられる場合に true を返します。定義されていれば、 @code{issubclass(subclass, class)} の実装のために呼び出されます。
@end deffn

なお、これらのメソッドは、クラスの型 (メタクラス) 上で検索されます。実際のクラスにクラスメソッドとして定義することはできません。これは、インスタンスそれ自体がクラスであるこの場合にのみ、インスタンスに呼び出される特殊メソッドの検索と一貫しています。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3119

@item PEP 3119@footnote{https://peps.python.org/pep-3119/} - 抽象基底クラスの導入

Includes the specification for customizing @ref{2ad,,isinstance()} and
@ref{9c4,,issubclass()} behavior through @ref{23c6,,__instancecheck__()} and
@ref{23c7,,__subclasscheck__()}, with motivation for this functionality
in the context of adding Abstract Base Classes (see the @ref{4,,abc}
module) to the language.
@end table


@node ジェネリック型をエミュレートする,呼び出し可能オブジェクトをエミュレートする,インスタンスのカスタマイズとサブクラスチェック,特殊メソッド名
@anchor{reference/datamodel emulating-generic-types}@anchor{23c8}
@subsubsection ジェネリック型をエミュレートする


When using @ref{15c,,type annotations}, it is often useful to
`parameterize' a @ref{1a1,,generic type} using Python's square-brackets notation.
For example, the annotation @code{list[int]} might be used to signify a
@ref{24d,,list} in which all the elements are of type @ref{19b,,int}.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 484

@item PEP 484@footnote{https://peps.python.org/pep-0484/} - 型ヒント

Introducing Python's framework for type annotations

@item @ref{8c1,,Generic Alias Types}

Documentation for objects representing parameterized generic classes

@item @ref{23c9,,ジェネリクス}, @ref{6f6,,user-defined generics} and @ref{17b6,,typing.Generic}

実行時にパラメータ設定が可能であり、かつ静的な型チェッカーが理解できるジェネリッククラスを実装する方法のドキュメントです。
@end table


A class can `generally' only be parameterized if it defines the special
class method @code{__class_getitem__()}.

@geindex __class_getitem__() (object のクラスメソッド)
@anchor{reference/datamodel object __class_getitem__}@anchor{943}
@deffn {メソッド} classmethod object.__class_getitem__ (cls, key)

`key' にある型引数で特殊化されたジェネリッククラスを表すオブジェクトを返します。

When defined on a class, @code{__class_getitem__()} is automatically a class
method. As such, there is no need for it to be decorated with
@ref{48e,,@@classmethod} when it is defined.
@end deffn

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

@end menu

@node The purpose of __class_getitem__,__class_getitem__ versus __getitem__,,ジェネリック型をエミュレートする
@anchor{reference/datamodel the-purpose-of-class-getitem}@anchor{23ca}
@subsubsection The purpose of `__class_getitem__'


The purpose of @ref{943,,__class_getitem__()} is to allow runtime
parameterization of standard-library generic classes in order to more easily
apply @ref{23cb,,type hints} 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 @ref{943,,__class_getitem__()}, or
inherit from @ref{17b6,,typing.Generic}, which has its own implementation of
@code{__class_getitem__()}.

Custom implementations of @ref{943,,__class_getitem__()} on classes defined
outside of the standard library may not be understood by third-party
type-checkers such as mypy. Using @code{__class_getitem__()} on any class for
purposes other than type hinting is discouraged.

@node __class_getitem__ versus __getitem__,,The purpose of __class_getitem__,ジェネリック型をエミュレートする
@anchor{reference/datamodel class-getitem-versus-getitem}@anchor{23cc}@anchor{reference/datamodel classgetitem-versus-getitem}@anchor{23cd}
@subsubsection `__class_getitem__' versus `__getitem__'


Usually, the @ref{23ce,,subscription} of an object using square
brackets will call the @ref{588,,__getitem__()} instance method defined on
the object's class. However, if the object being subscribed is itself a class,
the class method @ref{943,,__class_getitem__()} may be called instead.
@code{__class_getitem__()} should return a @ref{8c1,,GenericAlias}
object if it is properly defined.

Presented with the @ref{23cf,,expression} @code{obj[x]}, the Python interpreter
follows something like the following process to decide whether
@ref{588,,__getitem__()} or @ref{943,,__class_getitem__()} should be
called:

@example
from inspect import isclass

def subscribe(obj, x):
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type(obj)

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__(obj, x)
    if hasattr(class_of_obj, '__getitem__'):
        return class_of_obj.__getitem__(obj, x)

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__(x)
    elif isclass(obj) and hasattr(obj, '__class_getitem__'):
        return obj.__class_getitem__(x)

    # Else, raise an exception
    else:
        raise TypeError(
            f"'@{class_of_obj.__name__@}' object is not subscriptable"
        )
@end example

In Python, all classes are themselves instances of other classes. The class of
a class is known as that class's @ref{23d0,,metaclass}, and most classes have the
@ref{f44,,type} class as their metaclass. @ref{f44,,type} does not define
@ref{588,,__getitem__()}, meaning that expressions such as @code{list[int]},
@code{dict[str, float]} and @code{tuple[str, bytes]} all result in
@ref{943,,__class_getitem__()} being called:

@example
>>> # list has class "type" as its metaclass, like most classes:
>>> type(list)
<class 'type'>
>>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
True
>>> # "list[int]" calls "list.__class_getitem__(int)"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type(list[int])
<class 'types.GenericAlias'>
@end example

However, if a class has a custom metaclass that defines
@ref{588,,__getitem__()}, subscribing the class may result in different
behaviour. An example of this can be found in the @ref{5a,,enum} module:

@example
>>> from enum import Enum
>>> class Menu(Enum):
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type(Menu)
<class 'enum.EnumMeta'>
>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']
<Menu.SPAM: 'spam'>
>>> type(Menu['SPAM'])
<enum 'Menu'>
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 560

@item PEP 560@footnote{https://peps.python.org/pep-0560/} - typing モジュールとジェネリック型に対する言語コアによるサポート

Introducing @ref{943,,__class_getitem__()}, and outlining when a
@ref{23ce,,subscription} results in @code{__class_getitem__()}
being called instead of @ref{588,,__getitem__()}
@end table


@node 呼び出し可能オブジェクトをエミュレートする,コンテナをエミュレートする,ジェネリック型をエミュレートする,特殊メソッド名
@anchor{reference/datamodel emulating-callable-objects}@anchor{23d1}@anchor{reference/datamodel id15}@anchor{23d2}
@subsubsection 呼び出し可能オブジェクトをエミュレートする


@geindex __call__() (object のメソッド)
@anchor{reference/datamodel object __call__}@anchor{77a}
@deffn {メソッド} object.__call__ (self[, args...])

@geindex call;instance

Called when the instance is "called" as a function; if this method is defined,
@code{x(arg1, arg2, ...)} roughly translates to @code{type(x).__call__(x, arg1, ...)}.
The @ref{c7e,,object} class itself does not provide this method.
@end deffn

@node コンテナをエミュレートする,数値型をエミュレートする,呼び出し可能オブジェクトをエミュレートする,特殊メソッド名
@anchor{reference/datamodel emulating-container-types}@anchor{23d3}@anchor{reference/datamodel sequence-types}@anchor{23d4}
@subsubsection コンテナをエミュレートする


The following methods can be defined to implement container objects. None of them
are provided by the @ref{c7e,,object} class itself. Containers usually are
@ref{716,,sequences} (such as @ref{24d,,lists} or
@ref{614,,tuples}) or @ref{13d3,,mappings} (like
@ref{23d5,,dictionaries}),
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 @code{0 <= k <
N} where `N' is the length of the sequence, or @ref{694,,slice} objects, which define a
range of items.  It is also recommended that mappings provide the methods
@code{keys()}, @code{values()}, @code{items()}, @code{get()}, @code{clear()},
@code{setdefault()}, @code{pop()}, @code{popitem()}, @code{copy()}, and
@code{update()} behaving similar to those for Python's standard @ref{183,,dictionary}
objects.  The @ref{1f,,collections.abc} module provides a
@ref{12c0,,MutableMapping}
@ref{13ce,,abstract base class} to help create those methods from a base set of
@ref{588,,__getitem__()}, @ref{14e3,,__setitem__()},
@ref{14e4,,__delitem__()}, and @code{keys()}.

Mutable sequences should provide methods
@ref{23d6,,append()}, @ref{23d7,,clear()}, @ref{23d8,,count()},
@ref{23d9,,extend()}, @ref{1979,,index()}, @ref{23da,,insert()},
@ref{23db,,pop()}, @ref{197a,,remove()}, and @ref{23dc,,reverse()},
like Python standard @ref{24d,,list} objects.
Finally, sequence types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
@ref{23dd,,__add__()}, @ref{23de,,__radd__()}, @ref{23df,,__iadd__()},
@ref{23e0,,__mul__()}, @ref{23e1,,__rmul__()} and @ref{23e2,,__imul__()}
described below; they should not define other numerical
operators.

It is recommended that both mappings and sequences implement the
@ref{15d3,,__contains__()} method to allow efficient use of the @code{in}
operator; for
mappings, @code{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 @ref{e69,,__iter__()} method to allow efficient iteration
through the container; for mappings, @code{__iter__()} should iterate
through the object's keys; for sequences, it should iterate through the values.

@geindex __len__() (object のメソッド)
@anchor{reference/datamodel object __len__}@anchor{178f}
@deffn {メソッド} object.__len__ (self)

@geindex 組み込み関数;len
@geindex __bool__() (オブジェクトメソッド)

Called to implement the built-in function @ref{840,,len()}.  Should return the length
of the object, an integer @code{>=} 0.  Also, an object that doesn't define a
@ref{14ed,,__bool__()} method and whose @code{__len__()} method returns zero is
considered to be false in a Boolean context.

`CPython 実装の詳細:' In CPython, the length is required to be at most @ref{13dd,,sys.maxsize}.
If the length is larger than @code{sys.maxsize} some features (such as
@ref{840,,len()}) may raise @ref{a81,,OverflowError}.  To prevent raising
@code{OverflowError} by truth value testing, an object must define a
@ref{14ed,,__bool__()} method.
@end deffn

@geindex __length_hint__() (object のメソッド)
@anchor{reference/datamodel object __length_hint__}@anchor{110f}
@deffn {メソッド} object.__length_hint__ (self)

Called to implement @ref{116f,,operator.length_hint()}. Should return an estimated
length for the object (which may be greater or less than the actual length).
The length must be an integer @code{>=} 0. The return value may also be
@ref{1a2,,NotImplemented}, which is treated the same as if the
@code{__length_hint__} method didn't exist at all. This method is purely an
optimization and is never required for correctness.


Added in version 3.4.

@end deffn

@geindex object;slice

@cartouche
@quotation 注釈 
スライシングは、以下の 3 メソッドによって排他的に行われます。次のような呼び出しは

@example
a[1:2] = b
@end example

次のように翻訳され

@example
a[slice(1, 2, None)] = b
@end example

以下も同様です。存在しないスライスの要素は @code{None} で埋められます。
@end quotation
@end cartouche

@geindex __getitem__() (object のメソッド)
@anchor{reference/datamodel object __getitem__}@anchor{588}
@deffn {メソッド} object.__getitem__ (self, subscript)

Called to implement `subscription', that is, @code{self[subscript]}.
See @ref{23ce,,Subscriptions and slicings} for details on the syntax.

There are two types of built-in objects that support subscription
via @code{__getitem__()}:


@itemize -

@item 
`sequences', where `subscript' (also called
@ref{23e3,,index}) should be an integer or a @ref{694,,slice} object.
See the @ref{2338,,sequence documentation} for the expected
behavior, including handling @ref{694,,slice} objects and negative indices.

@item 
`mappings', where `subscript' is also called the @ref{23e4,,key}.
See @ref{233f,,mapping documentation} for the expected
behavior.
@end itemize

If `subscript' is of an inappropriate type, @code{__getitem__()}
should raise @ref{198,,TypeError}.
If `subscript' has an inappropriate value, @code{__getitem__()}
should raise an @ref{23e5,,LookupError} or one of its subclasses
(@ref{174e,,IndexError} for sequences; @ref{5e7,,KeyError} for mappings).

@cartouche
@quotation 注釈 
The sequence iteration protocol (used, for example, in @ref{34a,,for}
loops), expects that an @ref{174e,,IndexError} will be raised for illegal
indexes to allow proper detection of the end of a sequence.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
When @ref{23ce,,subscripting} a `class', the special
class method @ref{943,,__class_getitem__()} may be called instead of
@code{__getitem__()}. See @ref{23cd,,__class_getitem__ versus __getitem__} for more
details.
@end quotation
@end cartouche
@end deffn

@geindex __setitem__() (object のメソッド)
@anchor{reference/datamodel object __setitem__}@anchor{14e3}
@deffn {メソッド} object.__setitem__ (self, key, value)

@code{self[key]} に対する代入を実装するために呼び出されます。 @ref{588,,__getitem__()} と同じ注意事項があてはまります。このメソッドを実装できるのは、あるキーに対する値の変更をサポートしているか、新たなキーを追加できるようなマップの場合と、ある要素を置き換えることができるシーケンスの場合だけです。不正な `key' に対しては、 @ref{588,,__getitem__()} メソッドと同様の例外の送出を行わなければなりません。
@end deffn

@geindex __delitem__() (object のメソッド)
@anchor{reference/datamodel object __delitem__}@anchor{14e4}
@deffn {メソッド} object.__delitem__ (self, key)

@code{self[key]} の削除を実装するために呼び出されます。 @ref{588,,__getitem__()} と同じ注意事項があてはまります。このメソッドを実装できるのは、キーの削除をサポートしているマップの場合と、要素を削除できるシーケンスの場合だけです。不正な `key' に対しては、 @ref{588,,__getitem__()} メソッドと同様の例外の送出を行わなければなりません。
@end deffn

@geindex __missing__() (object のメソッド)
@anchor{reference/datamodel object __missing__}@anchor{13d5}
@deffn {メソッド} object.__missing__ (self, key)

@code{self[key]} の実装において辞書内にキーが存在しなかった場合に、 dict のサブクラスのために @ref{183,,dict}.@ref{588,,__getitem__()} によって呼び出されます。
@end deffn

@geindex __iter__() (object のメソッド)
@anchor{reference/datamodel object __iter__}@anchor{e69}
@deffn {メソッド} object.__iter__ (self)

このメソッドは、コンテナに対して @ref{4c8,,イテレータ} が要求された際に呼び出されます。このメソッドは、コンテナ内の全てのオブジェクトに渡って反復処理できるような、新たなイテレータオブジェクトを返さなければなりません。マッピングでは、コンテナ内のキーに渡って反復処理しなければなりません。
@end deffn

@geindex __reversed__() (object のメソッド)
@anchor{reference/datamodel object __reversed__}@anchor{e86}
@deffn {メソッド} object.__reversed__ (self)

@ref{a65,,reversed()} 組み込み関数が逆方向イテレーションを実装するために、(存在すれば)呼び出します。コンテナ内の全要素を逆順にイテレートする、新しいイテレータを返すべきです。

@ref{e86,,__reversed__()} メソッドが定義されていない場合、 @ref{a65,,reversed()} 組込み関数は sequence プロトコル (@ref{178f,,__len__()} と @ref{588,,__getitem__()}) を使った方法にフォールバックします。 sequence プロトコルをサポートしたオブジェクトは、 @ref{a65,,reversed()} よりも効率のいい実装を提供できる場合にのみ @ref{e86,,__reversed__()} を定義するべきです。
@end deffn

帰属テスト演算子 (@ref{34b,,in} および @ref{841,,not in}) は通常、コンテナの要素に対する反復処理のように実装されます。しかし、コンテナオブジェクトで以下の特殊メソッドを定義して、より効率的な実装を行ったり、オブジェクトがイテラブルでなくてもよいようにできます。

@geindex __contains__() (object のメソッド)
@anchor{reference/datamodel object __contains__}@anchor{15d3}
@deffn {メソッド} object.__contains__ (self, item)

帰属テスト演算を実装するために呼び出されます。 `item' が `self' 内に存在する場合には真を、そうでない場合には偽を返さなければなりません。マップオブジェクトの場合、値やキーと値の組ではなく、キーに対する帰属テストを考えなければなりません。

@ref{15d3,,__contains__()} を定義しないオブジェクトに対しては、メンバシップテストはまず、 @ref{e69,,__iter__()} を使った反復を試みます、次に古いシーケンス反復プロトコル @ref{588,,__getitem__()} を使います、 @ref{23e6,,言語レファレンスのこの節} を参照して下さい。
@end deffn

@node 数値型をエミュレートする,with文とコンテキストマネージャ,コンテナをエミュレートする,特殊メソッド名
@anchor{reference/datamodel emulating-numeric-types}@anchor{23e7}@anchor{reference/datamodel numeric-types}@anchor{23e8}
@subsubsection 数値型をエミュレートする


以下のメソッドを定義して、数値型オブジェクトをエミュレートすることができます。特定の種類の数値型ではサポートされていないような演算に対応するメソッド (非整数の数値に対するビット単位演算など) は、未定義のままにしておかなければなりません。

@geindex __add__() (object のメソッド)
@geindex __sub__() (object のメソッド)
@geindex __mul__() (object のメソッド)
@geindex __matmul__() (object のメソッド)
@geindex __truediv__() (object のメソッド)
@geindex __floordiv__() (object のメソッド)
@geindex __mod__() (object のメソッド)
@geindex __divmod__() (object のメソッド)
@geindex __pow__() (object のメソッド)
@geindex __lshift__() (object のメソッド)
@geindex __rshift__() (object のメソッド)
@geindex __and__() (object のメソッド)
@geindex __xor__() (object のメソッド)
@geindex __or__() (object のメソッド)
@anchor{reference/datamodel object __add__}@anchor{23dd}
@deffn {メソッド} object.__add__ (self, other)
@anchor{reference/datamodel object __sub__}@anchor{23e9}
@deffnx {メソッド} object.__sub__ (self, other)
@anchor{reference/datamodel object __mul__}@anchor{23e0}
@deffnx {メソッド} object.__mul__ (self, other)
@anchor{reference/datamodel object __matmul__}@anchor{f79}
@deffnx {メソッド} object.__matmul__ (self, other)
@anchor{reference/datamodel object __truediv__}@anchor{1090}
@deffnx {メソッド} object.__truediv__ (self, other)
@anchor{reference/datamodel object __floordiv__}@anchor{170d}
@deffnx {メソッド} object.__floordiv__ (self, other)
@anchor{reference/datamodel object __mod__}@anchor{23ea}
@deffnx {メソッド} object.__mod__ (self, other)
@anchor{reference/datamodel object __divmod__}@anchor{1091}
@deffnx {メソッド} object.__divmod__ (self, other)
@anchor{reference/datamodel object __pow__}@anchor{9d4}
@deffnx {メソッド} object.__pow__ (self, other[, modulo])
@anchor{reference/datamodel object __lshift__}@anchor{23eb}
@deffnx {メソッド} object.__lshift__ (self, other)
@anchor{reference/datamodel object __rshift__}@anchor{23ec}
@deffnx {メソッド} object.__rshift__ (self, other)
@anchor{reference/datamodel object __and__}@anchor{23ed}
@deffnx {メソッド} object.__and__ (self, other)
@anchor{reference/datamodel object __xor__}@anchor{23ee}
@deffnx {メソッド} object.__xor__ (self, other)
@anchor{reference/datamodel object __or__}@anchor{23ef}
@deffnx {メソッド} object.__or__ (self, other)

@geindex 組み込み関数;divmod
@geindex 組み込み関数;pow
@geindex 組み込み関数;pow

These methods are called to implement the binary arithmetic operations
(@code{+}, @code{-}, @code{*}, @code{@@}, @code{/}, @code{//}, @code{%}, @ref{b99,,divmod()},
@ref{1a4,,pow()}, @code{**}, @code{<<}, @code{>>}, @code{&}, @code{^}, @code{|}).  For instance, to
evaluate the expression @code{x + y}, where `x' is an instance of a class that
has an @ref{23dd,,__add__()} method, @code{type(x).__add__(x, y)} is called.  The
@ref{1091,,__divmod__()} method should be the equivalent to using
@ref{170d,,__floordiv__()} and @ref{23ea,,__mod__()}; it should not be related to
@ref{1090,,__truediv__()}.  Note that @ref{9d4,,__pow__()} should be defined to accept
an optional third argument if the three-argument version of the built-in @ref{1a4,,pow()}
function is to be supported.

If one of those methods does not support the operation with the supplied
arguments, it should return @ref{1a2,,NotImplemented}.
@end deffn

@geindex __radd__() (object のメソッド)
@geindex __rsub__() (object のメソッド)
@geindex __rmul__() (object のメソッド)
@geindex __rmatmul__() (object のメソッド)
@geindex __rtruediv__() (object のメソッド)
@geindex __rfloordiv__() (object のメソッド)
@geindex __rmod__() (object のメソッド)
@geindex __rdivmod__() (object のメソッド)
@geindex __rpow__() (object のメソッド)
@geindex __rlshift__() (object のメソッド)
@geindex __rrshift__() (object のメソッド)
@geindex __rand__() (object のメソッド)
@geindex __rxor__() (object のメソッド)
@geindex __ror__() (object のメソッド)
@anchor{reference/datamodel object __radd__}@anchor{23de}
@deffn {メソッド} object.__radd__ (self, other)
@anchor{reference/datamodel object __rsub__}@anchor{23f0}
@deffnx {メソッド} object.__rsub__ (self, other)
@anchor{reference/datamodel object __rmul__}@anchor{23e1}
@deffnx {メソッド} object.__rmul__ (self, other)
@anchor{reference/datamodel object __rmatmul__}@anchor{f7a}
@deffnx {メソッド} object.__rmatmul__ (self, other)
@anchor{reference/datamodel object __rtruediv__}@anchor{23f1}
@deffnx {メソッド} object.__rtruediv__ (self, other)
@anchor{reference/datamodel object __rfloordiv__}@anchor{23f2}
@deffnx {メソッド} object.__rfloordiv__ (self, other)
@anchor{reference/datamodel object __rmod__}@anchor{fd5}
@deffnx {メソッド} object.__rmod__ (self, other)
@anchor{reference/datamodel object __rdivmod__}@anchor{23f3}
@deffnx {メソッド} object.__rdivmod__ (self, other)
@anchor{reference/datamodel object __rpow__}@anchor{1a5}
@deffnx {メソッド} object.__rpow__ (self, other[, modulo])
@anchor{reference/datamodel object __rlshift__}@anchor{23f4}
@deffnx {メソッド} object.__rlshift__ (self, other)
@anchor{reference/datamodel object __rrshift__}@anchor{23f5}
@deffnx {メソッド} object.__rrshift__ (self, other)
@anchor{reference/datamodel object __rand__}@anchor{23f6}
@deffnx {メソッド} object.__rand__ (self, other)
@anchor{reference/datamodel object __rxor__}@anchor{23f7}
@deffnx {メソッド} object.__rxor__ (self, other)
@anchor{reference/datamodel object __ror__}@anchor{23f8}
@deffnx {メソッド} object.__ror__ (self, other)

@geindex 組み込み関数;divmod
@geindex 組み込み関数;pow

These methods are called to implement the binary arithmetic operations
(@code{+}, @code{-}, @code{*}, @code{@@}, @code{/}, @code{//}, @code{%}, @ref{b99,,divmod()},
@ref{1a4,,pow()}, @code{**}, @code{<<}, @code{>>}, @code{&}, @code{^}, @code{|}) with reflected
(swapped) operands.  These functions are only called if the operands
are of different types, when the left operand does not support the corresponding
operation @footnote{
"Does not support" here means that the class has no such method, or
the method returns @ref{1a2,,NotImplemented}.  Do not set the method to
@code{None} if you want to force fallback to the right operand's reflected
method—that will instead have the opposite effect of explicitly
`blocking' such fallback.
}, or the right operand's class is derived from the left operand's
class. @footnote{
For operands of the same type, it is assumed that if the non-reflected method
(such as @ref{23dd,,__add__()}) fails then the operation is not supported, which is why the
reflected method is not called.
} For instance, to evaluate the expression @code{x - y}, where `y' is
an instance of a class that has an @ref{23f0,,__rsub__()} method, @code{type(y).__rsub__(y, x)}
is called if @code{type(x).__sub__(x, y)} returns @ref{1a2,,NotImplemented} or @code{type(y)}
is a subclass of @code{type(x)}. @footnote{
If the right operand's type is a subclass of the left operand's type, the
reflected method having precedence allows subclasses to override their ancestors'
operations.
}

Note that @ref{1a5,,__rpow__()} should be defined to accept an optional third
argument if the three-argument version of the built-in @ref{1a4,,pow()} function
is to be supported.


バージョン 3.14 で変更: Three-argument @ref{1a4,,pow()} now try calling @ref{1a5,,__rpow__()} if necessary.
Previously it was only called in two-argument @code{pow()} and the binary
power operator.


@cartouche
@quotation 注釈 
右側の被演算子の型が左側の被演算子の型のサブクラスであり、このサブクラスであるメソッドに対する反射メソッドと異なる実装が定義されている場合には、左側の被演算子の非反射メソッドが呼ばれる前に、このメソッドが呼ばれます。この振る舞いにより、サブクラスが親の演算をオーバーライドすることが可能になります。
@end quotation
@end cartouche
@end deffn

@geindex __iadd__() (object のメソッド)
@geindex __isub__() (object のメソッド)
@geindex __imul__() (object のメソッド)
@geindex __imatmul__() (object のメソッド)
@geindex __itruediv__() (object のメソッド)
@geindex __ifloordiv__() (object のメソッド)
@geindex __imod__() (object のメソッド)
@geindex __ipow__() (object のメソッド)
@geindex __ilshift__() (object のメソッド)
@geindex __irshift__() (object のメソッド)
@geindex __iand__() (object のメソッド)
@geindex __ixor__() (object のメソッド)
@geindex __ior__() (object のメソッド)
@anchor{reference/datamodel object __iadd__}@anchor{23df}
@deffn {メソッド} object.__iadd__ (self, other)
@anchor{reference/datamodel object __isub__}@anchor{23f9}
@deffnx {メソッド} object.__isub__ (self, other)
@anchor{reference/datamodel object __imul__}@anchor{23e2}
@deffnx {メソッド} object.__imul__ (self, other)
@anchor{reference/datamodel object __imatmul__}@anchor{f7b}
@deffnx {メソッド} object.__imatmul__ (self, other)
@anchor{reference/datamodel object __itruediv__}@anchor{23fa}
@deffnx {メソッド} object.__itruediv__ (self, other)
@anchor{reference/datamodel object __ifloordiv__}@anchor{23fb}
@deffnx {メソッド} object.__ifloordiv__ (self, other)
@anchor{reference/datamodel object __imod__}@anchor{23fc}
@deffnx {メソッド} object.__imod__ (self, other)
@anchor{reference/datamodel object __ipow__}@anchor{9d3}
@deffnx {メソッド} object.__ipow__ (self, other[, modulo])
@anchor{reference/datamodel object __ilshift__}@anchor{23fd}
@deffnx {メソッド} object.__ilshift__ (self, other)
@anchor{reference/datamodel object __irshift__}@anchor{23fe}
@deffnx {メソッド} object.__irshift__ (self, other)
@anchor{reference/datamodel object __iand__}@anchor{23ff}
@deffnx {メソッド} object.__iand__ (self, other)
@anchor{reference/datamodel object __ixor__}@anchor{2400}
@deffnx {メソッド} object.__ixor__ (self, other)
@anchor{reference/datamodel object __ior__}@anchor{2401}
@deffnx {メソッド} object.__ior__ (self, other)

These methods are called to implement the augmented arithmetic assignments
(@code{+=}, @code{-=}, @code{*=}, @code{@@=}, @code{/=}, @code{//=}, @code{%=}, @code{**=}, @code{<<=},
@code{>>=}, @code{&=}, @code{^=}, @code{|=}).  These methods should attempt to do the
operation in-place (modifying `self') and return the result (which could be,
but does not have to be, `self').  If a specific method is not defined, or if
that method returns @ref{1a2,,NotImplemented}, the
augmented assignment falls back to the normal methods.  For instance, if `x'
is an instance of a class with an @ref{23df,,__iadd__()} method, @code{x += y} is
equivalent to @code{x = x.__iadd__(y)} . If @ref{23df,,__iadd__()} does not exist, or if @code{x.__iadd__(y)}
returns @code{NotImplemented}, @code{x.__add__(y)} and
@code{y.__radd__(x)} are considered, as with the evaluation of @code{x + y}. In
certain situations, augmented assignment can result in unexpected errors (see
@ref{2402,,なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?}), but this behavior is in fact
part of the data model.
@end deffn

@geindex __neg__() (object のメソッド)
@geindex __pos__() (object のメソッド)
@geindex __abs__() (object のメソッド)
@geindex __invert__() (object のメソッド)
@anchor{reference/datamodel object __neg__}@anchor{2403}
@deffn {メソッド} object.__neg__ (self)
@anchor{reference/datamodel object __pos__}@anchor{2404}
@deffnx {メソッド} object.__pos__ (self)
@anchor{reference/datamodel object __abs__}@anchor{2405}
@deffnx {メソッド} object.__abs__ (self)
@anchor{reference/datamodel object __invert__}@anchor{2406}
@deffnx {メソッド} object.__invert__ (self)

@geindex 組み込み関数;abs

呼び出して単項算術演算 (@code{-}, @code{+}, @ref{208d,,abs()} および @code{~}) を実装します。
@end deffn

@geindex __complex__() (object のメソッド)
@geindex __int__() (object のメソッド)
@geindex __float__() (object のメソッド)
@anchor{reference/datamodel object __complex__}@anchor{7fd}
@deffn {メソッド} object.__complex__ (self)
@anchor{reference/datamodel object __int__}@anchor{19d}
@deffnx {メソッド} object.__int__ (self)
@anchor{reference/datamodel object __float__}@anchor{bc1}
@deffnx {メソッド} object.__float__ (self)

@geindex 組み込み関数;複素数
@geindex 組み込み関数;int
@geindex 組み込み関数;浮動小数点数

組み込み関数の @ref{197,,complex()}, @ref{19b,,int()}, @ref{196,,float()} の実装から呼び出されます。
適切な型の値を返さなければなりません。
@end deffn

@geindex __index__() (object のメソッド)
@anchor{reference/datamodel object __index__}@anchor{19e}
@deffn {メソッド} object.__index__ (self)

呼び出して @ref{1cd2,,operator.index()} を実装します。
Python が数値オブジェクトを整数オブジェクトに損失なく変換する必要がある場合 (たとえばスライシングや、組み込みの @ref{14c0,,bin()} 、 @ref{14e7,,hex()} 、 @ref{14e6,,oct()} 関数) は常に呼び出されます。
このメソッドがあるとその数値オブジェクトが整数型であることが示唆されます。
整数を返さなければなりません。

もし @ref{19d,,__int__()}, @ref{bc1,,__float__()}, @ref{7fd,,__complex__()} が定義されていない場合、組み込み関数の @ref{19b,,int()}, @ref{196,,float()}, @ref{197,,complex()} は @ref{19e,,__index__()} にフォールバックします。
@end deffn

@geindex __round__() (object のメソッド)
@geindex __trunc__() (object のメソッド)
@geindex __floor__() (object のメソッド)
@geindex __ceil__() (object のメソッド)
@anchor{reference/datamodel object __round__}@anchor{2407}
@deffn {メソッド} object.__round__ (self[, ndigits])
@anchor{reference/datamodel object __trunc__}@anchor{19c}
@deffnx {メソッド} object.__trunc__ (self)
@anchor{reference/datamodel object __floor__}@anchor{2408}
@deffnx {メソッド} object.__floor__ (self)
@anchor{reference/datamodel object __ceil__}@anchor{2409}
@deffnx {メソッド} object.__ceil__ (self)

@geindex 組み込み関数;round

組み込み関数の @ref{14f2,,round()} と @ref{92,,math} モジュール関数の @ref{15d9,,trunc()}, @ref{15d7,,floor()}, @ref{15d8,,ceil()} の実装から呼び出されます。
`ndigits' が @code{__round__()} に渡されない限りは、これらの全てのメソッドは @ref{240a,,Integral} (たいていは @ref{19b,,int}) に切り詰められたオブジェクトの値を返すべきです。


バージョン 3.14 で変更: @ref{19b,,int()} no longer delegates to the @ref{19c,,__trunc__()} method.

@end deffn

@node with文とコンテキストマネージャ,クラスパターンマッチの位置引数のカスタマイズ,数値型をエミュレートする,特殊メソッド名
@anchor{reference/datamodel context-managers}@anchor{240b}@anchor{reference/datamodel with-statement-context-managers}@anchor{240c}
@subsubsection with文とコンテキストマネージャ


コンテキストマネージャ(`context manager') とは、 @ref{186,,with} 文の実行時にランタイムコンテキストを定義するオブジェクトです。コンテキストマネージャは、コードブロックを実行するために必要な入り口および出口の処理を扱います。コンテキストマネージャは通常、 @code{with} 文（ @ref{186,,with 文} の章を参照）により起動されますが、これらのメソッドを直接呼び出すことで起動することもできます。

@geindex statement;with
@geindex context manager

コンテキストマネージャの代表的な使い方としては、様々なグローバル情報の保存および更新、リソースのロックとアンロック、ファイルのオープンとクローズなどが挙げられます。

For more information on context managers, see @ref{240d,,コンテキストマネージャ型}.
The @ref{c7e,,object} class itself does not provide the context manager methods.

@geindex __enter__() (object のメソッド)
@anchor{reference/datamodel object __enter__}@anchor{7e4}
@deffn {メソッド} object.__enter__ (self)

コンテキストマネージャのの入り口で実行される処理です。 @ref{186,,with} 文は、文の @code{as} 節で規定された値を返すこのメソッドを呼び出します。
@end deffn

@geindex __exit__() (object のメソッド)
@anchor{reference/datamodel object __exit__}@anchor{1518}
@deffn {メソッド} object.__exit__ (self, exc_type, exc_value, traceback)

コンテキストマネージャの出口で実行される処理です。パラメータは、コンテキストが終了した原因となった例外について説明しています。コンテキストが例外を送出せず終了した場合は、全ての引き数に @ref{885,,None} が設定されます。

もし、例外が送出され、かつメソッドが例外を抑制したい場合（すなわち、例外が伝播されるのを防ぎたい場合）、このメソッドは True を返す必要があります。そうでなければ、このメソッドの終了後、例外は通常通り伝播することになります。

Note that @ref{1518,,__exit__()} methods should not reraise the passed-in exception;
this is the caller's responsibility.
@end deffn


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 343

@item PEP 343@footnote{https://peps.python.org/pep-0343/} - "with" ステートメント

Python の @ref{186,,with} 文の仕様、背景、および例が記載されています。
@end table


@node クラスパターンマッチの位置引数のカスタマイズ,Emulating buffer types,with文とコンテキストマネージャ,特殊メソッド名
@anchor{reference/datamodel class-pattern-matching}@anchor{240e}@anchor{reference/datamodel customizing-positional-arguments-in-class-pattern-matching}@anchor{240f}
@subsubsection クラスパターンマッチの位置引数のカスタマイズ


パターンの中でクラス名を利用する場合、位置引数はデフォルトでは利用できません。 @code{MyClass} で特別なサポートがないと、 @code{case MyClass(x, y)} は通常無効です。このようなパターンを利用するには、 `__match_args__' 属性をクラスに定義する必要があります。

@geindex object.__match_args__ (組み込み変数)
@anchor{reference/datamodel object __match_args__}@anchor{1c75}
@deffn {データ} object.__match_args__

このクラス変数には文字列のタプルがアサイン可能です。このクラスがクラスパターンの位置引数の中で利用されると、それぞれの位置引数は対応する `__match_args__' の中の値をキーワードとする、キーワード引数に変換されます。この属性がない時は、 @code{()} が設定されているのと同義です。
@end deffn

例えば、もし @code{MyClass.__match_args__} に @code{("left", "center", "right")} が定義されていた場合、  @code{case MyClass(x, y)} は @code{case MyClass(left=x, center=y)} と同義です。パターンの引数の数は、 `__match_args__' の要素数と同等かそれ以下でなければならない点に注意してください。もし、多かった場合には、パターンマッチは @ref{198,,TypeError} を送出します。


Added in version 3.10.



@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 634

@item PEP 634@footnote{https://peps.python.org/pep-0634/} - 構造的パターンマッチ

@code{match} 文の詳細。
@end table


@node Emulating buffer types,Annotations,クラスパターンマッチの位置引数のカスタマイズ,特殊メソッド名
@anchor{reference/datamodel emulating-buffer-types}@anchor{2410}@anchor{reference/datamodel python-buffer-protocol}@anchor{2411}
@subsubsection Emulating buffer types


The @ref{260,,buffer protocol} provides a way for Python
objects to expose efficient access to a low-level memory array. This protocol
is implemented by builtin types such as @ref{192,,bytes} and @ref{165,,memoryview},
and third-party libraries may define additional buffer types.

While buffer types are usually implemented in C, it is also possible to
implement the protocol in Python.

@geindex __buffer__() (object のメソッド)
@anchor{reference/datamodel object __buffer__}@anchor{68c}
@deffn {メソッド} object.__buffer__ (self, flags)

Called when a buffer is requested from `self' (for example, by the
@ref{165,,memoryview} constructor). The `flags' argument is an integer
representing the kind of buffer requested, affecting for example whether
the returned buffer is read-only or writable. @ref{68d,,inspect.BufferFlags}
provides a convenient way to interpret the flags. The method must return
a @ref{165,,memoryview} object.
@end deffn

@geindex __release_buffer__() (object のメソッド)
@anchor{reference/datamodel object __release_buffer__}@anchor{1a65}
@deffn {メソッド} object.__release_buffer__ (self, buffer)

Called when a buffer is no longer needed. The `buffer' argument is a
@ref{165,,memoryview} object that was previously returned by
@ref{68c,,__buffer__()}. The method must release any resources associated
with the buffer. This method should return @code{None}.
Buffer objects that do not need to perform any cleanup are not required
to implement this method.
@end deffn


Added in version 3.12.



@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 688

@item PEP 688@footnote{https://peps.python.org/pep-0688/} - Making the buffer protocol accessible in Python

Introduces the Python @code{__buffer__} and @code{__release_buffer__} methods.

@item @ref{343,,collections.abc.Buffer}

ABC for buffer types.
@end table


@node Annotations,特殊メソッド検索,Emulating buffer types,特殊メソッド名
@anchor{reference/datamodel annotations}@anchor{2412}
@subsubsection Annotations


Functions, classes, and modules may contain @ref{15c,,annotations},
which are a way to associate information (usually @ref{23cb,,type hints})
with a symbol.

@geindex __annotations__ (object の属性)
@anchor{reference/datamodel object __annotations__}@anchor{458}
@deffn {の属性} object.__annotations__

This attribute contains the annotations for an object. It is
@ref{685,,lazily evaluated}, so accessing the attribute may
execute arbitrary code and raise exceptions. If evaluation is successful, the
attribute is set to a dictionary mapping from variable names to annotations.


バージョン 3.14 で変更: Annotations are now lazily evaluated.

@end deffn

@geindex __annotate__() (object のメソッド)
@anchor{reference/datamodel object __annotate__}@anchor{1983}
@deffn {メソッド} object.__annotate__ (format)

An @ref{15d,,annotate function}.
Returns a new dictionary object mapping attribute/parameter names to their annotation values.

Takes a format parameter specifying the format in which annotations values should be provided.
It must be a member of the @ref{230,,annotationlib.Format} enum, or an integer with
a value corresponding to a member of the enum.

If an annotate function doesn't support the requested format, it must raise
@ref{36b,,NotImplementedError}. Annotate functions must always support
@ref{15e,,VALUE} format; they must not raise
@ref{36b,,NotImplementedError()} when called with this format.

When called with  @ref{15e,,VALUE} format, an annotate function may raise
@ref{452,,NameError}; it must not raise @code{NameError} when called requesting any other format.

If an object does not have any annotations, @ref{1983,,__annotate__} should preferably be set
to @code{None} (it can’t be deleted), rather than set to a function that returns an empty dict.


Added in version 3.14.

@end deffn


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 649

@item PEP 649@footnote{https://peps.python.org/pep-0649/} --- Deferred evaluation of annotation using descriptors

Introduces lazy evaluation of annotations and the @code{__annotate__} function.
@end table


@node 特殊メソッド検索,,Annotations,特殊メソッド名
@anchor{reference/datamodel special-lookup}@anchor{23b1}@anchor{reference/datamodel special-method-lookup}@anchor{2413}
@subsubsection 特殊メソッド検索


カスタムクラスでは、特殊メソッドの暗黙の呼び出しは、オブジェクトのインスタンス辞書ではなく、オブジェクトの型で定義されているときにのみ正しく動作することが保証されます。この動作のため、以下のコードは例外を送出します:

@example
>>> class C:
...     pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()
@end example

この動作の背景となる理由は、 @ref{cf3,,__hash__()} と @ref{82f,,__repr__()} といった type オブジェクトを含むすべてのオブジェクトで定義されている特殊メソッドにあります。これらのメソッドの暗黙の検索が通常の検索プロセスを使った場合、 type オブジェクト自体に対して実行されたときに失敗してしまいます:

@example
>>> 1 .__hash__() == hash(1)
True
>>> int.__hash__() == hash(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor '__hash__' of 'int' object needs an argument
@end example

クラスの非結合メソッドをこのようにして実行しようとすることは、'metaclass confusion' と呼ばれることもあり、特殊メソッドを検索するときはインスタンスをバイパスすることで回避されます:

@example
>>> type(1).__hash__(1) == hash(1)
True
>>> type(int).__hash__(int) == hash(int)
True
@end example

正確性のためにインスタンス属性をスキップするのに加えて、特殊メソッド検索はオブジェクトのメタクラスを含めて、 @ref{dcb,,__getattribute__()} メソッドもバイパスします:

@example
>>> class Meta(type):
...     def __getattribute__(*args):
...         print("Metaclass getattribute invoked")
...         return type.__getattribute__(*args)
...
>>> class C(object, metaclass=Meta):
...     def __len__(self):
...         return 10
...     def __getattribute__(*args):
...         print("Class getattribute invoked")
...         return object.__getattribute__(*args)
...
>>> c = C()
>>> c.__len__()                 # Explicit lookup via instance
Class getattribute invoked
10
>>> type(c).__len__(c)          # Explicit lookup via type
Metaclass getattribute invoked
10
>>> len(c)                      # Implicit lookup
10
@end example

このように @ref{dcb,,__getattribute__()} 機構をバイパスすることで、特殊メソッドの扱いに関するある程度の自由度と引き換えに (特殊メソッドはインタプリタから一貫して実行されるためにクラスオブジェクトに設定 `しなければならない')、インタープリタを高速化するための大きな余地が手に入ります。

@geindex コルーチン

@node コルーチン,,特殊メソッド名,データモデル
@anchor{reference/datamodel coroutines}@anchor{2414}
@subsection コルーチン


@menu
* 待機可能オブジェクト (Awaitable Object): 待機可能オブジェクト Awaitable Object. 
* コルーチンオブジェクト:: 
* 非同期イテレータ (Asynchronous Iterator): 非同期イテレータ Asynchronous Iterator. 
* 非同期コンテキストマネージャ (Asynchronous Context Manager): 非同期コンテキストマネージャ Asynchronous Context Manager. 

@end menu

@node 待機可能オブジェクト Awaitable Object,コルーチンオブジェクト,,コルーチン
@anchor{reference/datamodel awaitable-objects}@anchor{2415}
@subsubsection 待機可能オブジェクト (Awaitable Object)


@ref{4c9,,awaitable} オブジェクトは一般的には @ref{f75,,__await__()} メソッドが実装されています。 @ref{7ed,,async def} 関数が返す @ref{6b9,,Coroutineオブジェクト} は待機可能です。

@cartouche
@quotation 注釈 
@ref{1088,,types.coroutine()} デコレータでデコレータが付けられたジェネレータから返される @ref{dd9,,generator iterator} オブジェクトも待機可能ですが、 @ref{f75,,__await__()} は実装されていません。
@end quotation
@end cartouche

@geindex __await__() (object のメソッド)
@anchor{reference/datamodel object __await__}@anchor{f75}
@deffn {メソッド} object.__await__ (self)

Must return an @ref{4c8,,iterator}.  Should be used to implement
@ref{4c9,,awaitable} objects.  For instance, @ref{dc6,,asyncio.Future} implements
this method to be compatible with the @ref{18d,,await} expression.
The @ref{c7e,,object} class itself is not awaitable and does not provide
this method.

@cartouche
@quotation 注釈 
The language doesn't place any restriction on the type or value of the
objects yielded by the iterator returned by @code{__await__}, as this is
specific to the implementation of the asynchronous execution framework
(e.g. @ref{b,,asyncio}) that will be managing the @ref{4c9,,awaitable} object.
@end quotation
@end cartouche
@end deffn


Added in version 3.5.



@subsubheading 参考


待機可能オブジェクトについてより詳しくは 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} を参照してください。


@node コルーチンオブジェクト,非同期イテレータ Asynchronous Iterator,待機可能オブジェクト Awaitable Object,コルーチン
@anchor{reference/datamodel coroutine-objects}@anchor{2356}@anchor{reference/datamodel id19}@anchor{2416}
@subsubsection コルーチンオブジェクト


@ref{6b9,,Coroutineオブジェクト} は @ref{4c9,,awaitable} オブジェクトです。@ref{f75,,__await__()} を呼び出し、その返り値に対し反復処理をすることでコルーチンの実行を制御できます。コルーチンの実行が完了し制御を戻したとき、イテレータは @ref{df5,,StopIteration} を送出し、その例外の @ref{2417,,value} 属性に返り値を持たせます。コルーチンが例外を送出した場合は、イテレータにより伝搬されます。コルーチンから @ref{df5,,StopIteration} 例外を外に送出すべきではありません。

コルーチンには以下に挙げるメソッドもあり、これらはジェネレータのメソッドからの類似です (@ref{2418,,ジェネレータ-イテレータメソッド} を参照してください)。
ただし、ジェネレータと違って、コルーチンは反復処理を直接はサポートしていません。


バージョン 3.5.2 で変更: コルーチンで2回以上待機 (await) すると @ref{244,,RuntimeError} となります。


@geindex send() (coroutine のメソッド)
@anchor{reference/datamodel coroutine send}@anchor{2419}
@deffn {メソッド} coroutine.send (value)

Starts or resumes execution of the coroutine.  If `value' is @code{None},
this is equivalent to advancing the iterator returned by
@ref{f75,,__await__()}.  If `value' is not @code{None}, this method delegates
to the @ref{126d,,send()} method of the iterator that caused
the coroutine to suspend.  The result (return value,
@ref{df5,,StopIteration}, or other exception) is the same as when
iterating over the @code{__await__()} return value, described above.
@end deffn

@geindex throw() (coroutine のメソッド)
@anchor{reference/datamodel coroutine throw}@anchor{71b}
@deffn {メソッド} coroutine.throw (value)

@deffnx {メソッド} coroutine.throw (type[, value[, traceback]])

コルーチンで指定された例外を送出します。
このメソッドは、イテレータにコルーチンを一時停止する @ref{71c,,throw()} メソッドがある場合に処理を委任します。
そうでない場合には、中断した地点から例外が送出されます。
結果 (返り値か @ref{df5,,StopIteration} かその他の例外) は、上で解説したような @ref{f75,,__await__()} の返り値に対して反復処理を行ったときと同じです。
例外がコルーチンの中で捕捉されなかった場合、呼び出し元へ伝搬されます。


バージョン 3.12 で変更: The second signature (type[, value[, traceback]]) is deprecated and
may be removed in a future version of Python.

@end deffn

@geindex close() (coroutine のメソッド)
@anchor{reference/datamodel coroutine close}@anchor{241a}
@deffn {メソッド} coroutine.close ()

コルーチンが自分自身の後片付けをし終了します。
コルーチンが一時停止している場合は、コルーチンを一時停止させたイテレータに @ref{1793,,close()} メソッドがあれば、まずはそれに処理を委任します。
そして一時停止した地点から @ref{15e1,,GeneratorExit} が送出され、ただちにコルーチンが自分自身の後片付けを行います。
最後に、実行が開始されていなかった場合でも、コルーチンに実行が完了した印を付けます。

コルーチンオブジェクトが破棄されるときには、上記の手順を経て自動的に閉じられます。
@end deffn

@node 非同期イテレータ Asynchronous Iterator,非同期コンテキストマネージャ Asynchronous Context Manager,コルーチンオブジェクト,コルーチン
@anchor{reference/datamodel async-iterators}@anchor{f77}@anchor{reference/datamodel asynchronous-iterators}@anchor{241b}
@subsubsection 非同期イテレータ (Asynchronous Iterator)


`非同期イテレータ' の @code{__anext__} メソッドからは非同期のコードが呼べます。

非同期イテレータは @ref{ca1,,async for} 文の中で使えます。

The @ref{c7e,,object} class itself does not provide these methods.

@geindex __aiter__() (object のメソッド)
@anchor{reference/datamodel object __aiter__}@anchor{df6}
@deffn {メソッド} object.__aiter__ (self)

`非同期イテレータ' オブジェクトを返さなくてはなりません。
@end deffn

@geindex __anext__() (object のメソッド)
@anchor{reference/datamodel object __anext__}@anchor{1882}
@deffn {メソッド} object.__anext__ (self)

イテレータの次の値を返す `待機可能オブジェクト' を返さなければなりません。
反復処理が終了したときには @ref{1e0f,,StopAsyncIteration} エラーを送出すべきです。
@end deffn

非同期イテラブルオブジェクトの例:

@example
class Reader:
    async def readline(self):
        ...

    def __aiter__(self):
        return self

    async def __anext__(self):
        val = await self.readline()
        if val == b'@w{'}:
            raise StopAsyncIteration
        return val
@end example


Added in version 3.5.



バージョン 3.7 で変更: Python 3.7 より前では、 @ref{df6,,__aiter__()} は @ref{4c7,,非同期イテレータ} になる `awaitable' を返せました。

Python 3.7 からは、 @ref{df6,,__aiter__()} は非同期イテレータオブジェクトを返さなければなりません。
それ以外のものを返すと @ref{198,,TypeError} になります。


@node 非同期コンテキストマネージャ Asynchronous Context Manager,,非同期イテレータ Asynchronous Iterator,コルーチン
@anchor{reference/datamodel async-context-managers}@anchor{812}@anchor{reference/datamodel asynchronous-context-managers}@anchor{241c}
@subsubsection 非同期コンテキストマネージャ (Asynchronous Context Manager)


`非同期コンテキストマネージャ' は、 @code{__aenter__} メソッドと @code{__aexit__} メソッド内部で実行を一時停止できる `コンテキストマネージャ' です。

非同期コンテキストマネージャは @ref{185,,async with} 文の中で使えます。

The @ref{c7e,,object} class itself does not provide these methods.

@geindex __aenter__() (object のメソッド)
@anchor{reference/datamodel object __aenter__}@anchor{241d}
@deffn {メソッド} object.__aenter__ (self)

Semantically similar to @ref{7e4,,__enter__()}, the only
difference being that it must return an `awaitable'.
@end deffn

@geindex __aexit__() (object のメソッド)
@anchor{reference/datamodel object __aexit__}@anchor{19a1}
@deffn {メソッド} object.__aexit__ (self, exc_type, exc_value, traceback)

Semantically similar to @ref{1518,,__exit__()}, the only
difference being that it must return an `awaitable'.
@end deffn

非同期コンテキストマネージャクラスの例:

@example
class AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting context')
@end example


Added in version 3.5.


@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 実行モデル,インポートシステム,データモデル,Python 言語リファレンス
@anchor{reference/executionmodel doc}@anchor{241e}@anchor{reference/executionmodel execmodel}@anchor{241f}@anchor{reference/executionmodel execution-model}@anchor{2420}@anchor{reference/executionmodel translation-repo}@anchor{2421}
@section 実行モデル


@geindex 実行モデル
@geindex コード;ブロック

@menu
* プログラムの構造:: 
* 名前づけと束縛 (naming and binding): 名前づけと束縛 naming and binding. 
* 例外: 例外<2>. 
* Runtime Components:: 

@end menu

@node プログラムの構造,名前づけと束縛 naming and binding,,実行モデル
@anchor{reference/executionmodel prog-structure}@anchor{2422}@anchor{reference/executionmodel structure-of-a-program}@anchor{2423}
@subsection プログラムの構造


@geindex ブロック

Python プログラムはコードブロックから構成されます。
ブロック (`block') は、一つのまとまりとして実行される Python プログラムテキストの断片です。
モジュール、関数本体、そしてクラス定義はブロックであり、対話的に入力された個々のコマンドもブロックです。
スクリプトファイル (インタープリタに標準入力として与えられたり、インタープリタにコマンドライン引数として与えられたファイル) もコードブロックです。
スクリプトコマンド (インタープリタのコマンドライン上で @ref{1a8,,-c} オプションで指定されたコマンド) もコードブロックです。
引数 @ref{23c,,-m} を使用して、コマンドラインからトップレベルスクリプト(すなわちモジュール @code{__main__} )として実行されるモジュールもまたコードブロックです。組み込み関数 @ref{4a3,,eval()} や @ref{4a2,,exec()} に渡された文字列引数もコードブロックです。

@geindex 実行;フレーム

コードブロックは、実行フレーム (`execution frame') 上で実行されます。実行フレームには、 (デバッグに使われる) 管理情報が収められています。また、現在のコードブロックの実行が完了した際に、どのようにプログラムの実行を継続するかを決定しています。

@node 名前づけと束縛 naming and binding,例外<2>,プログラムの構造,実行モデル
@anchor{reference/executionmodel naming}@anchor{2346}@anchor{reference/executionmodel naming-and-binding}@anchor{2424}
@subsection 名前づけと束縛 (naming and binding)


@geindex namespace
@geindex スコープ

@menu
* 名前の束縛:: 
* 名前解決:: 
* Annotation scopes:: 
* Lazy evaluation:: 
* 組み込みと制限付きの実行:: 
* 動的な機能とのやりとり:: 

@end menu

@node 名前の束縛,名前解決,,名前づけと束縛 naming and binding
@anchor{reference/executionmodel bind-names}@anchor{2425}@anchor{reference/executionmodel binding-of-names}@anchor{2426}
@subsubsection 名前の束縛


@geindex name
@geindex 束縛;name

`名前 (name)' は、オブジェクトを参照します。名前を導入するには、名前への束縛 (name binding) 操作を行います。

@geindex from;import statement

以下の構文が名前を束縛します:


@itemize *

@item 
formal parameters to functions,

@item 
クラス定義,

@item 
関数定義,

@item 
代入式,

@item 
@ref{2427,,targets} that are identifiers if occurring in
an assignment:


@itemize +

@item 
@ref{34a,,for} loop header,

@item 
after @code{as} in a @ref{186,,with} statement, @ref{1ab,,except}
clause, @ref{1ac,,except*} clause, or in the as-pattern in structural pattern matching,

@item 
in a capture pattern in structural pattern matching
@end itemize

@item 
@ref{7f8,,import} 文.

@item 
@ref{66d,,type} statements.

@item 
@ref{5ad,,type parameter lists}.
@end itemize

The @code{import} statement of the form @code{from ... import *} binds all
names defined in the imported module, except those beginning with an underscore.
This form may only be used at the module level.

@ref{1b1f,,del} 文で指定される対象は、(@ref{1b1f,,del} の意味付けは、実際は名前の解放 (unbind) ですが) 文の目的上、束縛済みのものとみなされます。

代入文や import 文はいずれも、クラスや関数定義、モジュールレベル (トップレベルのコードブロック) 内で起こります。

@geindex 自由;variable

If a name is bound in a block, it is a local variable of that block, unless
declared as @ref{14bf,,nonlocal} or @ref{4ac,,global}.  If a name is bound at
the module level, it is a global variable.  (The variables of the module code
block are local and global.)  If a variable is used in a code block but not
defined there, it is a @ref{2428,,free variable}.

プログラムテキスト中に名前が出現するたびに、その名前が使われている最も内側の関数ブロック中で作成された `束縛 (binding)' を使って名前の参照が行われます。

@node 名前解決,Annotation scopes,名前の束縛,名前づけと束縛 naming and binding
@anchor{reference/executionmodel resolution-of-names}@anchor{2429}@anchor{reference/executionmodel resolve-names}@anchor{242a}
@subsubsection 名前解決


@geindex スコープ

スコープ (`scope') は、ブロック内の名前の可視性を決めます。
ローカル変数があるブロック内で定義されている場合、変数のスコープはそのブロックを含みます。
関数ブロック内で名前の定義を行った場合、その中のブロックが名前に別の束縛を行わない限り、定義ブロック内の全てのブロックを含むようにスコープが拡張されます。

@geindex 環境

ある名前がコードブロック内で使われると、その名前を最も近傍から囲うようなスコープ (最内スコープ: nearest enclosing scope) を使って束縛の解決を行います。こうしたスコープからなる、あるコードブロック内で参照できるスコープ全ての集合は、ブロックの環境(`environment')と呼ばれます。

@geindex NameError (組み込み例外)
@geindex UnboundLocalError

名前が全く見付からなかったときは、 @ref{452,,NameError} 例外が送出されます。
現在のスコープが関数のもので、名前が使われる場所でローカル変数がまだ値に束縛されていない場合、 @ref{174f,,UnboundLocalError} 例外が送出されます。
@ref{174f,,UnboundLocalError} は @ref{452,,NameError} の子クラスです。

ある名前がコードブロック内のどこかで束縛操作されていたら、そのブロック内で使われるその名前はすべて、現在のブロックへの参照として扱われます。このため、ある名前がそのブロック内で束縛される前に使われるとエラーにつながります。この規則は敏感です。Python には宣言がなく、コードブロックのどこでも名前束縛操作ができます。あるコードブロックにおけるローカル変数は、ブロックのテキスト全体から名前束縛操作を走査することで決定されます。例は @ref{242b,,UnboundLocalError についての FAQ 項目} を参照してください。

If the @ref{4ac,,global} 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 @ref{13,,builtins}.  The
global namespace is searched first.  If the names are not found there, the
builtins namespace is searched next. If the names are also not found in the
builtins namespace, new variables are created in the global namespace.
The global statement must precede all uses of the listed names.

@ref{4ac,,global} 文は、同じブロックの束縛操作と同じスコープを持ちます。ある自由変数の最内スコープに global 文がある場合、その自由変数はグローバル変数とみなされます。

@c XXX say more about "nonlocal" semantics here

The @ref{14bf,,nonlocal} statement causes corresponding names to refer
to previously bound variables in the nearest enclosing function scope.
@ref{18e,,SyntaxError} is raised at compile time if the given name does not
exist in any enclosing function scope. @ref{5ad,,Type parameters}
cannot be rebound with the @code{nonlocal} statement.

@geindex module;__main__

あるモジュールの名前空間は、そのモジュールが最初に import された時に自動的に作成されます。スクリプトの主モジュール (main module) は常に @ref{1,,__main__} と呼ばれます。

Class definition blocks and arguments to @ref{4a2,,exec()} and @ref{4a3,,eval()} are
special in the context of name resolution.
A class definition is an executable statement that may use and define names.
These references follow the normal rules for name resolution with an exception
that unbound local variables are looked up in the global namespace.
The namespace of the class definition becomes the attribute dictionary of
the class. The scope of names defined in a class block is limited to the
class block; it does not extend to the code blocks of methods. This includes
comprehensions and generator expressions, but it does not include
@ref{4ab,,annotation scopes},
which have access to their enclosing class scopes.
This means that the following will fail:

@example
class A:
    a = 42
    b = list(a + i for i in range(10))
@end example

However, the following will succeed:

@example
class A:
    type Alias = Nested
    class Nested: pass

print(A.Alias.__value__)  # <type 'A.Nested'>
@end example

@node Annotation scopes,Lazy evaluation,名前解決,名前づけと束縛 naming and binding
@anchor{reference/executionmodel annotation-scopes}@anchor{4ab}@anchor{reference/executionmodel id1}@anchor{242c}
@subsubsection Annotation scopes


@ref{15c,,Annotations}, @ref{5ad,,type parameter lists}
and @ref{66d,,type} statements
introduce `annotation scopes', which behave mostly like function scopes,
but with some exceptions discussed below.

Annotation scopes are used in the following contexts:


@itemize *

@item 
@ref{2019,,Function annotations}.

@item 
@ref{f51,,Variable annotations}.

@item 
Type parameter lists for @ref{684,,generic type aliases}.

@item 
Type parameter lists for @ref{682,,generic functions}.
A generic function's annotations are
executed within the annotation scope, but its defaults and decorators are not.

@item 
Type parameter lists for @ref{2377,,generic classes}.
A generic class's base classes and
keyword arguments are executed within the annotation scope, but its decorators are not.

@item 
The bounds, constraints, and default values for type parameters
(@ref{685,,lazily evaluated}).

@item 
The value of type aliases (@ref{685,,lazily evaluated}).
@end itemize

Annotation scopes differ from function scopes in the following ways:


@itemize *

@item 
Annotation scopes have access to their enclosing class namespace.
If an annotation scope is immediately within a class scope, or within another
annotation scope that is immediately within a class scope, the code in the
annotation scope can use names defined in the class scope as if it were
executed directly within the class body. This contrasts with regular
functions defined within classes, which cannot access names defined in the class scope.

@item 
Expressions in annotation scopes cannot contain @ref{bc2,,yield}, @code{yield from},
@ref{18d,,await}, or @ref{242d,,;=}
expressions. (These expressions are allowed in other scopes contained within the
annotation scope.)

@item 
Names defined in annotation scopes cannot be rebound with @ref{14bf,,nonlocal}
statements in inner scopes. This includes only type parameters, as no other
syntactic elements that can appear within annotation scopes can introduce new names.

@item 
While annotation scopes have an internal name, that name is not reflected in the
@ref{1d24,,qualified name} of objects defined within the scope.
Instead, the @ref{1271,,__qualname__}
of such objects is as if the object were defined in the enclosing scope.
@end itemize


Added in version 3.12: Annotation scopes were introduced in Python 3.12 as part of 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}.



バージョン 3.13 で変更: Annotation scopes are also used for type parameter defaults, as
introduced by 
@geindex Python Enhancement Proposals; PEP 696
PEP 696@footnote{https://peps.python.org/pep-0696/}.



バージョン 3.14 で変更: Annotation scopes are now also used for annotations, as specified in
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} and 
@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/}.


@node Lazy evaluation,組み込みと制限付きの実行,Annotation scopes,名前づけと束縛 naming and binding
@anchor{reference/executionmodel id2}@anchor{242e}@anchor{reference/executionmodel lazy-evaluation}@anchor{685}
@subsubsection Lazy evaluation


Most annotation scopes are `lazily evaluated'. This includes annotations,
the values of type aliases created through the @ref{66d,,type} statement, and
the bounds, constraints, and default values of type
variables created through the @ref{5ad,,type parameter syntax}.
This means that they are not evaluated when the type alias or type variable is
created, or when the object carrying annotations is created. Instead, they
are only evaluated when necessary, for example when the @code{__value__}
attribute on a type alias is accessed.

例:

@example
>>> type Alias = 1/0
>>> Alias.__value__
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero
>>> def func[T: 1/0](): pass
>>> T = func.__type_params__[0]
>>> T.__bound__
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero
@end example

Here the exception is raised only when the @code{__value__} attribute
of the type alias or the @code{__bound__} attribute of the type variable
is accessed.

This behavior is primarily useful for references to types that have not
yet been defined when the type alias or type variable is created. For example,
lazy evaluation enables creation of mutually recursive type aliases:

@example
from typing import Literal

type SimpleExpr = int | Parenthesized
type Parenthesized = tuple[Literal["("], Expr, Literal[")"]]
type Expr = SimpleExpr | tuple[SimpleExpr, Literal["+", "-"], Expr]
@end example

Lazily evaluated values are evaluated in @ref{4ab,,annotation scope},
which means that names that appear inside the lazily evaluated value are looked up
as if they were used in the immediately enclosing scope.


Added in version 3.12.


@node 組み込みと制限付きの実行,動的な機能とのやりとり,Lazy evaluation,名前づけと束縛 naming and binding
@anchor{reference/executionmodel builtins-and-restricted-execution}@anchor{242f}@anchor{reference/executionmodel restrict-exec}@anchor{2430}
@subsubsection 組み込みと制限付きの実行


@geindex 制限;実行

ユーザは @code{__builtins__} に触れるべきではありません; これは厳密に実装の詳細です。組み込みの名前空間の中の値をオーバーライドしたいユーザは、 @ref{13,,builtins} モジュールを @ref{7f8,,import} して、その属性を適切に変更するべきです。

あるコードブロックの実行に関連する組み込み名前空間は、実際にはコードブロックのグローバル名前空間から名前 @code{__builtins__} を検索することで見つかります; @code{__builtins__}  は辞書かモジュールでなければなりません (後者の場合はモジュールの辞書が使われます)。デフォルトでは、 @ref{1,,__main__} モジュール中においては、 @code{__builtins__} は組み込みモジュール @ref{13,,builtins} です; それ以外の任意のモジュールにおいては、 @code{__builtins__} は @ref{13,,builtins} モジュール自身の辞書のエイリアスです。

@node 動的な機能とのやりとり,,組み込みと制限付きの実行,名前づけと束縛 naming and binding
@anchor{reference/executionmodel dynamic-features}@anchor{2431}@anchor{reference/executionmodel interaction-with-dynamic-features}@anchor{2432}
@subsubsection 動的な機能とのやりとり


自由変数の名前解決はコンパイル時でなく実行時に行われます。つまり、以下のコードは42を出力します:

@example
i = 10
def f():
    print(i)
i = 42
f()
@end example

@c XXX from * also invalid with relative imports (at least currently)

@ref{4a3,,eval()} と @ref{4a2,,exec()} 関数は、名前の解決に、現在の環境の全てを使えるわけではありません。名前は呼び出し側のローカルやグローバル名前空間で解決できます。自由変数は最内名前空間ではなく、グローバル名前空間から解決されます。 @footnote{
この制限は、上記の操作によって実行されるコードが、モジュールをコンパイルしたときには利用できないために起こります。
} @ref{4a2,,exec()} と @ref{4a3,,eval()} 関数にはオプションの引数があり、グローバルとローカル名前空間をオーバライドできます。名前空間が一つしか指定されなければ、両方の名前空間として使われます。

@c XXX(ncoghlan) above is only accurate for string execution. When executing code objects,
@c closure cells may now be passed explicitly to resolve co_freevars references.
@c Docs issue: https://github.com/python/cpython/issues/122826

@node 例外<2>,Runtime Components,名前づけと束縛 naming and binding,実行モデル
@anchor{reference/executionmodel exceptions}@anchor{2433}@anchor{reference/executionmodel id4}@anchor{2434}
@subsection 例外


@geindex 例外

@geindex 例外を送出する
@geindex 例外を扱う
@geindex 例外ハンドラ
@geindex エラー
@geindex エラー処理

例外とは、コードブロックの通常の制御フローを中断して、エラーやその他の例外的な状況を処理できるようにするための手段です。例外はエラーが検出された時点で `送出 (raise)' されます; 例外は、エラーが発生部の周辺のコードブロックか、エラーが発生したコードブロック直接または間接的に呼び出しているコードブロックで `処理 (handle)' することができます。

Python インタプリタは、ランタイムエラー (ゼロ除算など) が検出されると例外を送出します。Python プログラムから、 @ref{803,,raise} 文を使って明示的に例外を送出することもできます。例外ハンドラ (exception handler) は、 @ref{8f8,,try} ... @ref{1ab,,except} 文で指定することができます。 @ref{8f8,,try} 文の @ref{1b0,,finally} 節を使うとクリーンアップコード (cleanup code) を指定できます。このコードは例外は処理しませんが、先行するコードブロックで例外が起きても起きなくても実行されます。

@geindex 終了モデル

Python は、エラー処理に "プログラムの終了 (termination)" モデルを用いています: 例外ハンドラは、プログラムに何が発生したかを把握することができ、ハンドラの外側のレベルに処理を継続することはできますが、(問題のあったコード部分を最初から実行しなおすのでない限り) エラーの原因を修復したり、実行に失敗した操作をやり直すことはできません。

@geindex SystemExit (組み込み例外)

例外が全く処理されないとき、インタプリタはプログラムの実行を終了させるか、対話メインループに処理を戻します。
どちらの場合も、例外が @ref{f3c,,SystemExit} でなければ、スタックのトレースバックを出力します。

例外は、クラスインスタンスによって識別されます。 @ref{1ab,,except} 節はインスタンスのクラスにもとづいて選択されます: これはインスタンスのクラスか、その @ref{13ce,,非仮想基底クラス} を参照します。このインスタンスはハンドラによって受け取られ、例外条件に関する追加情報を伝えることができます。

@cartouche
@quotation 注釈 
例外のメッセージは、Python API 仕様には含まれていません。メッセージの内容は、ある Python のバージョンと次のバージョンの間で警告なしに変更される可能性があるので、複数バージョンのインタプリタで動作するようなコードは、例外メッセージの内容に依存させるべきではありません。
@end quotation
@end cartouche

@ref{8f8,,try} 文については、 @ref{8f8,,try 文} 節、 @ref{803,,raise} 文については @ref{803,,raise 文} 節も参照してください。

@node Runtime Components,,例外<2>,実行モデル
@anchor{reference/executionmodel execcomponents}@anchor{2435}@anchor{reference/executionmodel runtime-components}@anchor{2436}
@subsection Runtime Components


@menu
* General Computing Model:: 
* Python Runtime Model:: 

@end menu

@node General Computing Model,Python Runtime Model,,Runtime Components
@anchor{reference/executionmodel general-computing-model}@anchor{2437}
@subsubsection General Computing Model


Python's execution model does not operate in a vacuum.  It runs on
a host machine and through that host's runtime environment, including
its operating system (OS), if there is one.  When a program runs,
the conceptual layers of how it runs on the host look something
like this:

@quotation


@display
`host machine'@w{ }
@display
`process' (global resources)@w{ }
@display
`thread' (runs machine code)@w{ }
@end display
@end display
@end display


@end quotation

Each process represents a program running on the host.  Think of each
process itself as the data part of its program.  Think of the process'
threads as the execution part of the program.  This distinction will
be important to understand the conceptual Python runtime.

The process, as the data part, is the execution context in which the
program runs.  It mostly consists of the set of resources assigned to
the program by the host, including memory, signals, file handles,
sockets, and environment variables.

Processes are isolated and independent from one another.  (The same
is true for hosts.)  The host manages the process' access to its
assigned resources, in addition to coordinating between processes.

Each thread represents the actual execution of the program's machine
code, running relative to the resources assigned to the program's
process.  It's strictly up to the host how and when that execution
takes place.

From the point of view of Python, a program always starts with exactly
one thread.  However, the program may grow to run in multiple
simultaneous threads.  Not all hosts support multiple threads per
process, but most do.  Unlike processes, threads in a process are not
isolated and independent from one another.  Specifically, all threads
in a process share all of the process' resources.

The fundamental point of threads is that each one does `run'
independently, at the same time as the others.  That may be only
conceptually at the same time ("concurrently") or physically
("in parallel").  Either way, the threads effectively run
at a non-synchronized rate.

@cartouche
@quotation 注釈 
That non-synchronized rate means none of the process' memory is
guaranteed to stay consistent for the code running in any given
thread.  Thus multi-threaded programs must take care to coordinate
access to intentionally shared resources.  Likewise, they must take
care to be absolutely diligent about not accessing any `other'
resources in multiple threads; otherwise two threads running at the
same time might accidentally interfere with each other's use of some
shared data.  All this is true for both Python programs and the
Python runtime.

The cost of this broad, unstructured requirement is the tradeoff for
the kind of raw concurrency that threads provide.  The alternative
to the required discipline generally means dealing with
non-deterministic bugs and data corruption.
@end quotation
@end cartouche

@node Python Runtime Model,,General Computing Model,Runtime Components
@anchor{reference/executionmodel python-runtime-model}@anchor{2438}
@subsubsection Python Runtime Model


The same conceptual layers apply to each Python program, with some
extra data layers specific to Python:

@quotation


@display
`host machine'@w{ }
@display
`process' (global resources)@w{ }
@display
Python global runtime (`state')@w{ }
@display
Python interpreter (`state')@w{ }
@display
`thread' (runs Python bytecode and "C-API")@w{ }
@display
Python thread `state'@w{ }
@end display
@end display
@end display
@end display
@end display
@end display


@end quotation

At the conceptual level: when a Python program starts, it looks exactly
like that diagram, with one of each.  The runtime may grow to include
multiple interpreters, and each interpreter may grow to include
multiple thread states.

@cartouche
@quotation 注釈 
A Python implementation won't necessarily implement the runtime
layers distinctly or even concretely.  The only exception is places
where distinct layers are directly specified or exposed to users,
like through the @ref{f3,,threading} module.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
The initial interpreter is typically called the "main" interpreter.
Some Python implementations, like CPython, assign special roles
to the main interpreter.

Likewise, the host thread where the runtime was initialized is known
as the "main" thread.  It may be different from the process' initial
thread, though they are often the same.  In some cases "main thread"
may be even more specific and refer to the initial thread state.
A Python runtime might assign specific responsibilities
to the main thread, such as handling signals.
@end quotation
@end cartouche

As a whole, the Python runtime consists of the global runtime state,
interpreters, and thread states.  The runtime ensures all that state
stays consistent over its lifetime, particularly when used with
multiple host threads.

The global runtime, at the conceptual level, is just a set of
interpreters.  While those interpreters are otherwise isolated and
independent from one another, they may share some data or other
resources.  The runtime is responsible for managing these global
resources safely.  The actual nature and management of these resources
is implementation-specific.  Ultimately, the external utility of the
global runtime is limited to managing interpreters.

In contrast, an "interpreter" is conceptually what we would normally
think of as the (full-featured) "Python runtime".  When machine code
executing in a host thread interacts with the Python runtime, it calls
into Python in the context of a specific interpreter.

@cartouche
@quotation 注釈 
The term "interpreter" here is not the same as the "bytecode
interpreter", which is what regularly runs in threads, executing
compiled Python code.

In an ideal world, "Python runtime" would refer to what we currently
call "interpreter".  However, it's been called "interpreter" at least
since introduced in 1997 (CPython:a027efa5b@footnote{https://github.com/python/cpython/commit/a027efa5b}).
@end quotation
@end cartouche

Each interpreter completely encapsulates all of the non-process-global,
non-thread-specific state needed for the Python runtime to work.
Notably, the interpreter's state persists between uses.  It includes
fundamental data like @ref{17e6,,sys.modules}.  The runtime ensures
multiple threads using the same interpreter will safely
share it between them.

A Python implementation may support using multiple interpreters at the
same time in the same process.  They are independent and isolated from
one another.  For example, each interpreter has its own
@ref{17e6,,sys.modules}.

For thread-specific runtime state, each interpreter has a set of thread
states, which it manages, in the same way the global runtime contains
a set of interpreters.  It can have thread states for as many host
threads as it needs.  It may even have multiple thread states for
the same host thread, though that isn't as common.

Each thread state, conceptually, has all the thread-specific runtime
data an interpreter needs to operate in one host thread.  The thread
state includes the current raised exception and the thread's Python
call stack.  It may include other thread-specific resources.

@cartouche
@quotation 注釈 
The term "Python thread" can sometimes refer to a thread state, but
normally it means a thread created using the @ref{f3,,threading} module.
@end quotation
@end cartouche

Each thread state, over its lifetime, is always tied to exactly one
interpreter and exactly one host thread.  It will only ever be used in
that thread and with that interpreter.

Multiple thread states may be tied to the same host thread, whether for
different interpreters or even the same interpreter.  However, for any
given host thread, only one of the thread states tied to it can be used
by the thread at a time.

Thread states are isolated and independent from one another and don't
share any data, except for possibly sharing an interpreter and objects
or other resources belonging to that interpreter.

Once a program is running, new Python threads can be created using the
@ref{f3,,threading} module (on platforms and Python implementations that
support threads).  Additional processes can be created using the
@ref{a5,,os}, @ref{dc,,subprocess}, and @ref{98,,multiprocessing} modules.
Interpreters can be created and used with the
@ref{25,,interpreters} module.  Coroutines (async) can
be run using @ref{b,,asyncio} in each interpreter, typically only
in a single thread (often the main thread).

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node インポートシステム,式 expression,実行モデル,Python 言語リファレンス
@anchor{reference/import doc}@anchor{2439}@anchor{reference/import importsystem}@anchor{2360}@anchor{reference/import the-import-system}@anchor{243a}@anchor{reference/import translation-repo}@anchor{243b}
@section インポートシステム


@geindex import machinery

ある 1 つの @ref{19de,,module} にある Python コードから他のモジュールを @ref{243c,,インポート} することで、そこにあるコードへアクセスできるようになります。 @ref{7f8,,import} 文はインポート機構を動かす最も一般的な方法ですが、それが唯一の方法ではありません。 @ref{73c,,importlib.import_module()} や組み込みの @ref{ad1,,__import__()} といった関数を使っても、インポート機構を動かすことができます。

@ref{7f8,,import} 文は 2 つの処理を連続して行っています; ある名前のモジュールを探し、その検索結果をローカルスコープの名前に束縛します。 @code{import} 文の検索処理は、適切な引数で @ref{ad1,,__import__()} 関数を呼び出すこととして定義されています。 @ref{ad1,,__import__()} の戻り値は @code{import} 文の名前束縛処理の実行で使われます。名前束縛処理の厳密な詳細は @code{import} 文を参照してください。

@ref{ad1,,__import__()} を直接呼び出すとモジュールの検索のみが行われ、見つかった場合、モジュールの作成処理が行われます。親パッケージのインポートや (@ref{17e6,,sys.modules} を含む) 様々なキャッシュの更新などの副作用は起きるかもしれませんが、 @ref{7f8,,import} 文のみが名前束縛処理を行います。

@ref{7f8,,import} 文が実行されるときには、標準の組み込み関数 @ref{ad1,,__import__()} が呼ばれます。インポートシステムを呼び出すその他の (@ref{73c,,importlib.import_module()} 関数のような)  メカニズムは、@ref{ad1,,__import__()} の呼び出しをバイパスして独自のインポート・セマンティクスを実装している可能性があります。

モジュールが初めてインポートされるとき、 Python はそのモジュールを検索し、見付かった場合、モジュールオブジェクトを作成し、初期化します @footnote{
@ref{1014,,types.ModuleType} を参照してください。
} 。その名前のモジュールが見付からなかった場合、 @ref{d3d,,ModuleNotFoundError} が送出されます。 Python には、インポート機構が実行されたときに名前からモジュールを検索する様々な戦略が実装されています。これらの戦略は、これ以降の節で解説される様々なフックを使って、修正したり拡張したりできます。


バージョン 3.3 で変更: インポートシステムが 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} の第 2 フェーズの完全な実装へ更新されました。もはや暗黙的なインポート機構はありません - インポート機構全体は @ref{f27,,sys.meta_path} を通して公開されています。加えて、ネイティブの名前空間パッケージのサポートは実装されています (
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} を参照) 。


@menu
* importlib: importlib<10>. 
* パッケージ: パッケージ<2>. 
* 検索:: 
* ロード:: 
* パスベース・ファインダー:: 
* 標準のインポートシステムを置き換える:: 
* Package Relative Imports:: 
* __main__ に対する特別な考慮:: 
* 参考資料:: 

@end menu

@node importlib<10>,パッケージ<2>,,インポートシステム
@anchor{reference/import importlib}@anchor{243d}
@subsection @code{importlib}


@ref{7b,,importlib} モジュールはインポート機構とやり取りするための便利な API を提供します。例えば @ref{73c,,importlib.import_module()} は、インポート機構を実行するための組み込みの @ref{ad1,,__import__()} よりもシンプルで推奨される API を提供します。より詳細なことは @ref{7b,,importlib} ライブラリのドキュメントを参照してください。

@node パッケージ<2>,検索,importlib<10>,インポートシステム
@anchor{reference/import packages}@anchor{243e}
@subsection パッケージ


@geindex package

Python にはモジュールオブジェクトの種類は 1 種類しかなく、 Python 、 C 、それ以外のもののどれで実装されているかに関係なく、すべてのモジュールはこの種類になります。モジュールの組織化を助け、名前階層を提供するために、 Python には @ref{233,,パッケージ} という概念があります。

パッケージはファイルシステムのディレクトリ、モジュールはディレクトリにあるファイルと考えることができますが、パッケージやモジュールはファイルシステムから生まれる必要はないので、この比喩を額面通りに受け取ってはいけません。この文書の目的のために、ディレクトリとファイルという便利な比喩を使うことにします。ファイルシステムのディレクトリのように、パッケージは階層構造を成し、通常のモジュールだけでなく、サブパッケージを含むこともあります。

すべてのパッケージはモジュールですが、すべてのモジュールがパッケージとは限らないことを心に留めておくのが重要です。もしくは他の言い方をすると、パッケージは単なる特別な種類のモジュールであると言えます。特に、@code{__path__} 属性を持つ任意のモジュールはパッケージと見なされます。

すべてのモジュールは名前を持ちます。Python の属性アクセスの文法と同様に、サブパッケージの名前は親パッケージ名とドット記号で区切られます。したがって、@ref{3f,,email} という名前のパッケージや、それが含む @ref{49,,email.mime} という名前のサブパッケージ、さらにそれに含まれる @ref{51,,email.mime.text} と言う名前のモジュールを考えることができます。

@menu
* 通常のパッケージ:: 
* 名前空間パッケージ:: 

@end menu

@node 通常のパッケージ,名前空間パッケージ,,パッケージ<2>
@anchor{reference/import regular-packages}@anchor{243f}
@subsubsection 通常のパッケージ


@geindex package;regular

Python では、 @ref{2440,,通常のパッケージ} と @ref{2b2,,名前空間パッケージ} の 2 種類のパッケージが定義されています。通常のパッケージは Python 3.2 以前から存在する伝統的なパッケージです。典型的な通常のパッケージは @code{__init__.py} ファイルを含むディレクトリとして実装されます。通常のパッケージがインポートされたとき、この @code{__init__.py} ファイルが暗黙的に実行され、それで定義しているオブジェクトがパッケージ名前空間にある名前に束縛されます。 @code{__init__.py} ファイルは、他のモジュールに書ける Python コードと同じものを含むことができ、モジュールがインポートされたときに Python はモジュールに属性を追加したりします。

例えば、以下のようなファイルシステム配置は、3 つのサブパッケージを持つ最上位の @code{parent} パッケージを定義します:

@example
parent/
    __init__.py
    one/
        __init__.py
    two/
        __init__.py
    three/
        __init__.py
@end example

@code{parent.one} をインポートすると暗黙的に @code{parent/__init__.py} と @code{parent/one/__init__.py} が実行されます。その後に @code{parent.two} もしくは @code{parent.three} をインポートすると、それぞれ @code{parent/two/__init__.py} や @code{parent/three/__init__.py} が実行されます。

@node 名前空間パッケージ,,通常のパッケージ,パッケージ<2>
@anchor{reference/import namespace-packages}@anchor{2441}@anchor{reference/import reference-namespace-package}@anchor{2442}
@subsubsection 名前空間パッケージ


@geindex package;namespace
@geindex package;portion

名前空間パッケージは様々な @ref{2443,,ポーション} を寄せ集めたもので、それぞれのポーションはサブパッケージを親パッケージに提供します。ポーションはファイルシステムの別々の場所にあることもあります。ポーションは、 zip ファイルの中やネットワーク上や、それ以外のインポート時に Python が探すどこかの場所で見つかることもあります。名前空間パッケージはファイルシステム上のオブジェクトに対応することもあるし、そうでないこともあります; それらは実際の実体のない仮想モジュールです。

名前空間パッケージは、  @code{__path__} 属性に普通のリストは使いません。その代わりに独自の iterable 型を使っていて、ポーションの親パッケージのパス (もしくは最上位パッケージのための @ref{3e4,,sys.path}) が変わった場合、そのパッケージでの次のインポートの際に、新たに自動でパッケージポーションを検索します。

名前空間パッケージには @code{parent/__init__.py} ファイルはありません。それどころか、異なるポーションがそれぞれ提供する複数の @code{parent} ディレクトリがインポート検索の際に見つかることもあります。したがって @code{parent/one} は物理的に @code{parent/two} の隣りにあるとは限りません。その場合、そのパッケージかサブパッケージのうち 1 つがインポートされたとき、Python は最上位の @code{parent} パッケージのための名前空間パッケージを作成します。

名前空間パッケージの仕様については 
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} も参照してください。

@node 検索,ロード,パッケージ<2>,インポートシステム
@anchor{reference/import searching}@anchor{2444}
@subsection 検索


検索を始めるためには、 Python はインポートされるモジュール (もしくはパッケージですが、ここでの議論の目的においてはささいな違いです) の @ref{1d24,,完全修飾} 名を必要とします。この名前は、 @ref{7f8,,import} 文の様々な引数や @ref{73c,,importlib.import_module()} および @ref{ad1,,__import__()} 関数のパラメータから得られます。

この名前はインポート検索の様々なフェーズで使われ、これは例えば @code{foo.bar.baz} のようなドットで区切られたサブモジュールへのパスだったりします。この場合、 Python は最初に @code{foo} を、次に @code{foo.bar} 、そして最後に @code{foo.bar.baz} をインポートしようとします。中間のいずれかのインポートに失敗した場合は、 @ref{d3d,,ModuleNotFoundError} が送出されます。

@menu
* モジュールキャッシュ:: 
* ファインダーとローダー:: 
* インポートフック:: 
* メタパス:: 

@end menu

@node モジュールキャッシュ,ファインダーとローダー,,検索
@anchor{reference/import the-module-cache}@anchor{2445}
@subsubsection モジュールキャッシュ


@geindex sys.modules

インポート検索で最初に調べる場所は @ref{17e6,,sys.modules} です。このマッピングは、中間のパスを含む、これまでにインポートされたすべてのモジュールのキャッシュを提供します。なので @code{foo.bar.baz} がインポート済みの場合、 @ref{17e6,,sys.modules} は @code{foo} 、 @code{foo.bar} 、 @code{foo.bar.baz} のエントリーを含みます。それぞれのキーはその値として対応するモジュールオブジェクトを持ちます。

インポートではモジュール名は @ref{17e6,,sys.modules} から探され、存在した場合は、対応する値がインポートされるべきモジュールであり、この処理は完了します。しかし値が @code{None} だった場合、 @ref{d3d,,ModuleNotFoundError} が送出されます。モジュール名が見付からなかった場合は、 Python はモジュールの検索を続けます。

@ref{17e6,,sys.modules} は書き込み可能です。キーの削除は対応するモジュールを破壊しない (他のモジュールがそのモジュールへの参照を持っている) かもしれませんが、指定されたモジュールのキャッシュされたエントリーを無効にし、それが次にインポートされたとき Python にそのモジュールを改めて検索させることになります。キーを @code{None} に対応付けることもできますが、次にそのモジュールがインポートされるときに @ref{d3d,,ModuleNotFoundError} となってしまいます。

たとえモジュールオブジェクトへの参照を保持しておいて、 @ref{17e6,,sys.modules} にキャッシュされたエントリーを無効にし、その指定したモジュールを再インポートしたとしても、 2 つのモジュールオブジェクトは同じでは `ない' ことに注意してください。それとは対照的に、 @ref{73d,,importlib.reload()} は `同じ' モジュールオブジェクトを再利用し、モジュールのコードを再実行することで単にモジュールの内容を再初期化するだけです。

@node ファインダーとローダー,インポートフック,モジュールキャッシュ,検索
@anchor{reference/import finders-and-loaders}@anchor{2446}@anchor{reference/import id2}@anchor{2447}
@subsubsection ファインダーとローダー


@geindex finder
@geindex loader
@geindex module spec

@ref{17e6,,sys.modules} に指定されたモジュールが見つからなかった場合は、 Python のインポートプロトコルが起動され、モジュールを見つけロードします。このプロトコルは 2 つの概念的なオブジェクト、 @ref{236a,,ファインダー} と @ref{1a28,,ローダー} から成ります。ファインダーの仕事は、知っている戦略を使って指定されたモジュールを見つけられるかどうか判断することです。両方のインターフェースを実装しているオブジェクトは @ref{2448,,インポーター} と呼ばれます - インポーターは要求されたモジュールがロードできると分かったとき、自分自身を返します。

Python にはデフォルトのファインダーとインポーターがいくつかあります。 1 つ目のものは組み込みモジュールの見つけ方を知っていて、 2 つ目のものは凍結されたモジュール (訳注: freeze ツールで処理されたモジュールのこと。 @ref{2449,,プログラミング FAQ} の「どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？」の項目を参照) の見つけ方を知っています。 3 つ目のものは @ref{244a,,インポートパス} からモジュールを探します。 @ref{244a,,インポートパス} はファイルシステムのパスや zip ファイルの位置を示すリストです。このリストは、 URL で特定できるもののような、位置を示すことのできる任意のリソースの検索にまで拡張することもできます。

インポート機構は拡張可能なので、モジュール検索の範囲とスコープを拡張するために新しいファインダーを付け加えることができます。

ファインダーは実際にはモジュールをロードしません。指定されたモジュールが見つかった場合、ファインダーは `module spec' (モジュール仕様)、すなわちモジュールのインポート関連の情報をカプセル化したものを返します。モジュールのロード時にインポート機構はそれを利用します。

次の節では、インポート機構を拡張するための新しいファインダーやローダーの作成と登録を含め、ファインダーとローダーのプロトコルについてより詳しく解説します。


バージョン 3.4 で変更: Python の以前のバージョンでは、ファインダーは直接 @ref{1a28,,ローダー} を返していましたが、現在はローダーを `含む' モジュール仕様を返します。ローダーはインポート中はまだ使われていますが、責任は減りました。


@node インポートフック,メタパス,ファインダーとローダー,検索
@anchor{reference/import import-hooks}@anchor{244b}
@subsubsection インポートフック


@geindex import hooks
@geindex meta hooks
@geindex path hooks
@geindex hooks;import
@geindex hooks;meta
@geindex hooks;パス

インポート機構は拡張可能なように設計されています; その主となる仕組みは `インポートフック' です。インポートフックには 2 種類あります: `メタフック' と `インポートパスフック' です。

メタフックはインポート処理の最初、 @ref{17e6,,sys.modules} キャッシュの検索以外のインポート処理より前に呼び出されます。これにより、 @ref{3e4,,sys.path} の処理や凍結されたモジュールや組み込みのモジュールでさえも、メタフックで上書きすることができます。メタフックは以下で解説するように、 @ref{f27,,sys.meta_path} に新しいファインダーオブジェクトを追加することで登録されます。

インポートパスフックは、 @ref{3e4,,sys.path} (もしくは @code{package.__path__}) の処理の一部として、対応するパス要素を取り扱うところで呼び出されます。インポートパスフックは以下で解説するように、新しい呼び出し可能オブジェクトを @ref{1225,,sys.path_hooks} に追加することで登録されます。

@node メタパス,,インポートフック,検索
@anchor{reference/import the-meta-path}@anchor{244c}
@subsubsection メタパス


@geindex sys.meta_path
@geindex finder;find_spec

When the named module is not found in @ref{17e6,,sys.modules}, Python next
searches @ref{f27,,sys.meta_path}, which contains a list of meta path finder
objects.  These finders are queried in order to see if they know how to handle
the named module.  Meta path finders must implement a method called
@ref{a68,,find_spec()} which takes three arguments:
a name, an import path, and (optionally) a target module.  The meta path
finder can use any strategy it wants to determine whether it can handle
the named module or not.

meta path finder が指定されたモジュールの扱い方を知っている場合は、ファインダは spec オブジェクトを返します。指定されたモジュールを扱えない場合は @code{None} を返します。 @ref{f27,,sys.meta_path} に対する処理が spec を返さずにリストの末尾に到達してしまった場合は、 @ref{d3d,,ModuleNotFoundError} を送出します。その他の送出された例外はそのまま呼び出し元に伝播され、インポート処理を異常終了させます。

The @ref{a68,,find_spec()} method of meta path
finders is called with two or three arguments.  The first is the fully
qualified name of the module being imported, for example @code{foo.bar.baz}.
The second argument is the path entries to use for the module search.  For
top-level modules, the second argument is @code{None}, but for submodules or
subpackages, the second argument is the value of the parent package's
@code{__path__} attribute. If the appropriate @code{__path__} attribute cannot
be accessed, a @ref{d3d,,ModuleNotFoundError} is raised.  The third argument
is an existing module object that will be the target of loading later.
The import system passes in a target module only during reload.

メタパスは、1 回のインポート要求で複数回走査される可能性があります。例えば、関係するモジュールがどれもまだキャッシュされていないとしたときに @code{foo.bar.baz} をインポートすると、最初は各メタパス・ファインダー (@code{mpf}) に対して @code{mpf.find_spec("foo", None, None)} を呼び出して、最上位のインポート処理を行います。@code{foo} がインポートされた後に、@code{mpf.find_spec("foo.bar", foo.__path__, None)} を呼び出していく 2 回目のメタパスの走査が行われ、@code{foo.bar} がインポートされます。@code{foo.bar} のインポートまで行われたら、最後の走査で @code{mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)} を呼び出していきます。

あるメタパス・ファインダーは最上位のインポートのみサポートしています。これらのインポーターは、2 つ目の引数に @code{None} 以外のものが渡されたとき、常に @code{None} を返します。

Python のデフォルトの @ref{f27,,sys.meta_path} は 3 つのパスファインダーを持っています。組み込みモジュールのインポートの方法を知っているもの、凍結されたモジュールのインポートの方法を知っているもの、 @ref{244a,,インポートパス} からのモジュールのインポートの方法を知っているもの (つまり @ref{244d,,パスベース・ファインダー}) があります。


バージョン 3.4 で変更: The @ref{a68,,find_spec()} method of meta path
finders replaced @code{find_module()}, which
is now deprecated.  While it will continue to work without change, the
import machinery will try it only if the finder does not implement
@ref{a68,,find_spec()}.



バージョン 3.10 で変更: Use of @code{find_module()} by the import system
now raises @ref{71e,,ImportWarning}.



バージョン 3.12 で変更: @code{find_module()} has been removed.
Use @ref{a68,,find_spec()} instead.


@node ロード,パスベース・ファインダー,検索,インポートシステム
@anchor{reference/import loading}@anchor{244e}
@subsection ロード


モジュール仕様が見つかった場合、インポート機構はモジュールをロードする時にそれ (およびそれに含まれるローダー) を使います。これは、インポートのロード部分で起こることの近似です:

@example
module = None
if spec.loader is not None and hasattr(spec.loader, 'create_module'):
    # It is assumed 'exec_module' will also be defined on the loader.
    module = spec.loader.create_module(spec)
if module is None:
    module = ModuleType(spec.name)
# The import-related module attributes get set here:
_init_module_attrs(spec, module)

if spec.loader is None:
    # unsupported
    raise ImportError
if spec.origin is None and spec.submodule_search_locations is not None:
    # namespace package
    sys.modules[spec.name] = module
elif not hasattr(spec.loader, 'exec_module'):
    module = spec.loader.load_module(spec.name)
else:
    sys.modules[spec.name] = module
    try:
        spec.loader.exec_module(module)
    except BaseException:
        try:
            del sys.modules[spec.name]
        except KeyError:
            pass
        raise
return sys.modules[spec.name]
@end example

以下の詳細に注意してください:


@itemize *

@item 
@ref{17e6,,sys.modules} の中に与えられた名前を持つ既存のモジュールオブジェクトがあるなら、 import は既にそれを返しているでしょう。

@item 
モジュールは、ローダーがモジュールコードを実行する前に @ref{17e6,,sys.modules} に存在しています。 モジュールコードが (直接的または間接的に) 自分自身をインポートする可能性があるので、これは重要です; モジュールを @ref{17e6,,sys.modules} に追加することで、最悪のケースでは無限の再帰が、そして最良のケースでは複数回のロードが、前もって防止されます。

@item 
ロード処理に失敗した場合、その失敗したモジュールは -- そして、そのモジュールだけが -- @ref{17e6,,sys.modules} から取り除かれます。 @ref{17e6,,sys.modules} キャッシュに既に含まれていたすべてのモジュールと、副作用としてロードに成功したすべてのモジュールは、常にキャッシュに残されます。これはリロードとは対照的で、リロードの場合は失敗したモジュールも @ref{17e6,,sys.modules} に残されます。

@item 
@ref{2361,,後のセクション} で要約されるように、モジュールが作られてから実行されるまでの間にインポート機構はインポート関連のモジュール属性を設定します (上記擬似コード例の "_init_module_attrs")。

@item 
モジュール実行はモジュールの名前空間が構築されるロードの重要な瞬間です。実行はローダーに完全に委任され、ローダーは何をどのように構築するかを決定することになります。

@item 
ロードの間に作成されて exec_module() に渡されたモジュールは、インポートの終わりに返されるものとは異なるかもしれません @footnote{
importlib の実装は、戻り値を直接使うことは避けています。その代わりに、モジュール名を調べて @ref{17e6,,sys.modules} からモジュールオブジェクトを得ます。こうすることの間接的な効果は、インポートされたモジュールが @ref{17e6,,sys.modules} にいる自分自身を置き換えることがあるということです。これは実装依存の動作であり、他の Python 実装では保証されていない動作です。
}。
@end itemize


バージョン 3.4 で変更: インポートシステムはローダーの定型的な責任を引き継ぎました。これらは以前は @ref{a69,,importlib.abc.Loader.load_module()} メソッドによって実行されました。


@menu
* ローダー:: 
* サブモジュール:: 
* Module specs:: 
* __path__ attributes on modules:: 
* モジュールの repr:: 
* キャッシュされたバイトコードの無効化:: 

@end menu

@node ローダー,サブモジュール,,ロード
@anchor{reference/import loaders}@anchor{244f}
@subsubsection ローダー


モジュールローダーは、ロードの重要な機能であるモジュール実行機能を提供します。インポート機構は、実行しようとするモジュールオブジェクトを単一の引数として @ref{a6a,,importlib.abc.Loader.exec_module()} メソッドを呼び出します。 @ref{a6a,,importlib.abc.Loader.exec_module()} から返された任意の値は無視されます。

ローダーは以下の仕様を満たしていなければいけません:


@itemize *

@item 
モジュールが (組み込みモジュールや動的に読み込まれる拡張モジュールではなくて) Python モジュールだった場合、ローダーはモジュールのグローバル名前空間 (@code{module.__dict__}) で、モジュールのコードを実行すべきです。

@item 
@ref{a6a,,exec_module()} の呼び出し中に @ref{65b,,ImportError} 以外の例外が送出され、伝播されてきたとしても、モジュールをロードできない場合は @ref{65b,,ImportError} を送出すべきです。
@end itemize

多くの場合、ファインダーとローダーは同じオブジェクトで構いません; そのような場合では @ref{a68,,find_spec()} メソッドは単に @code{self} (訳注: オブジェクト自身) を返すだけです。

モジュールローダーは、 @ref{eac,,create_module()} メソッドを実装することでロード中にモジュールオブジェクトを作成することを選択できます。このメソッドは、モジュール仕様を引数に取って、ロード中に使う新しいモジュールオブジェクトを返します。 @code{create_module()} はモジュールオブジェクトに属性を設定する必要はありません。もしこのメソッドが @code{None} を返すなら、インポート機構は新しいモジュールを自身で作成します。


Added in version 3.4: ローダーの @ref{eac,,create_module()} メソッド。



バージョン 3.4 で変更: @ref{a69,,load_module()} メソッドは @ref{a6a,,exec_module()} によって置き換えられ、インポート機構がロードのすべての定型的な処理を引き受けました。

既存のローダーとの互換性のため、もしローダーに @code{load_module()} メソッドが存在し、かつローダーが @code{exec_module()} を実装していなければ、インポート機構はローダーの @code{load_module()} メソッドを使います。しかし、 @code{load_module()} は deprecated であり、ローダーは代わりに @code{exec_module()} を実装すべきです。

@code{load_module()} メソッドは、モジュールを実行することに加えて上記で説明されたすべての定型的なロード機能を実施しなければなりません。同じ制約が適用されます。以下は追加の明確化です:


@itemize *

@item 
@ref{17e6,,sys.modules} に与えられた名前のモジュールが存在している場合、ローダーはその既存のモジュールを使わなければいけません。 (そうしないと @ref{73d,,importlib.reload()} は正しく動かないでしょう。) 指定されたモジュールが @ref{17e6,,sys.modules} に存在しない場合、ローダーは新しいモジュールオブジェクトを作成し、 @ref{17e6,,sys.modules} に追加しなければいけません。

@item 
無限の再帰または複数回のロードを防止するために、ローダーがモジュールコードを実行する前にモジュールは @ref{17e6,,sys.modules} に存在しなければなりません (`must')。

@item 
ロード処理に失敗した場合、ローダーは @ref{17e6,,sys.modules} に追加したモジュールを取り除かなければいけませんが、それはロードに失敗したモジュール `のみ' を、そのモジュールがローダー自身に明示的にロードされた場合に限り、除去しなければなりません。
@end itemize



バージョン 3.5 で変更: @code{exec_module()} が定義されていて @code{create_module()} が定義されていない場合、 @ref{1a3,,DeprecationWarning} が送出されるようになりました。



バージョン 3.6 で変更: @code{exec_module()} が定義されていて @code{create_module()} が定義されていない場合、 @ref{65b,,ImportError} が送出されるようになりました。



バージョン 3.10 で変更: @code{load_module()} を使用すると @ref{71e,,ImportWarning} が発生します。


@node サブモジュール,Module specs,ローダー,ロード
@anchor{reference/import submodules}@anchor{2450}
@subsubsection サブモジュール


サブモジュールをロードするのにどのようなメカニズム (例えば、 @code{importlib} API 、 @code{import} または @code{import-from} ステートメント、またはビルトイン関数の @code{__import__}) が使われた場合でも、バインディングはサブモジュールオブジェクトを親モジュールの名前空間に配置します。例えば、もしパッケージ @code{spam} がサブモジュール @code{foo} を持っていた場合、 @code{spam.foo} をインポートした後は @code{spam} は値がサブモジュールに束縛された属性 @code{foo} を持ちます。以下のディレクトリ構造を持っているとしましょう:

@example
spam/
    __init__.py
    foo.py
@end example

そして @code{spam/__init__.py} は以下のようになっているとします:

@example
from .foo import Foo
@end example

このとき、以下を実行することにより @code{spam} モジュールの中に @code{foo} と @code{Foo} に束縛された名前が置かれます:

@example
>>> import spam
>>> spam.foo
<module 'spam.foo' from '/tmp/imports/spam/foo.py'>
>>> spam.Foo
<class 'spam.foo.Foo'>
@end example

Python の慣れ親しんだ名前束縛ルールからするとこれは驚きかもしれませんが、それは実際インポートシステムの基本的な機能です。不変に保たなければならないのは (上記のインポートの後などで) @code{sys.modules['spam']} と @code{sys.modules['spam.foo']} が存在する場合、後者が前者の @code{foo} 属性として存在しなければならないということです。

@node Module specs,__path__ attributes on modules,サブモジュール,ロード
@anchor{reference/import id4}@anchor{2451}@anchor{reference/import module-specs}@anchor{2366}
@subsubsection Module specs


インポート機構は、インポートの間 (特にロードの前) に、個々のモジュールについてのさまざまな情報を扱います。情報のほとんどはすべてのモジュールで共通です。モジュール仕様の目的は、このインポート関連の情報をモジュールの単位でカプセル化することです。

インポートの際にモジュール仕様を使うことは、インポートシステムコンポーネント間、例えばモジュール仕様を作成するファインダーとそれを実行するローダーの間で状態を転送することを可能にします。最も重要なのは、それによってインポート機構がロードの定型的な作業を実行できるようになるということです。これに対して、モジュール仕様なしではローダがその責任を担っていました。

The module's spec is exposed as @ref{2364,,module.__spec__}. Setting
@code{__spec__} appropriately applies equally to
@ref{2452,,modules initialized during interpreter startup}.
The one exception is @code{__main__}, where @code{__spec__} is
@ref{2453,,set to None in some cases}.

See @ref{226c,,ModuleSpec} for details on the contents of
the module spec.


Added in version 3.4.


@node __path__ attributes on modules,モジュールの repr,Module specs,ロード
@anchor{reference/import package-path-rules}@anchor{2367}@anchor{reference/import path-attributes-on-modules}@anchor{2454}
@subsubsection __path__ attributes on modules


The @ref{2054,,__path__} attribute should be a (possibly empty)
@ref{716,,sequence} of strings enumerating the locations where the package's
submodules will be found. By definition, if a module has a @code{__path__}
attribute, it is a @ref{233,,package}.

A package's @ref{2054,,__path__} attribute is used during imports of its
subpackages.
Within the import machinery, it functions much the same as @ref{3e4,,sys.path},
i.e. providing a list of locations to search for modules during import.
However, @code{__path__} is typically much more constrained than
@code{sys.path}.

The same rules used for @ref{3e4,,sys.path} also apply to a package's
@code{__path__}. @ref{1225,,sys.path_hooks} (described below) are
consulted when traversing a package's @code{__path__}.

A package's @code{__init__.py} file may set or alter the package's
@ref{2054,,__path__}
attribute, and this was typically the way namespace packages were implemented
prior to 
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/}.  With the adoption of 
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/}, namespace packages no
longer need to supply @code{__init__.py} files containing only @code{__path__}
manipulation code; the import machinery automatically sets @code{__path__}
correctly for the namespace package.

@node モジュールの repr,キャッシュされたバイトコードの無効化,__path__ attributes on modules,ロード
@anchor{reference/import module-reprs}@anchor{2455}
@subsubsection モジュールの repr


デフォルトでは、すべてのモジュールは利用可能な repr を持っています。ただしこれは、これまでに説明した属性の設定内容に依存しており、モジュール仕様によってモジュールオブジェクトの repr をより明示的に制御することができます。

もしモジュールが仕様 (@code{__spec__}) を持っていれば、インポート機構はそこから repr を生成しようとします。もしそれが失敗するか、または仕様が存在しなければ、インポートシステムはモジュールで入手可能なあらゆる情報を使ってデフォルトの repr を構築します。それは @code{module.__name__}, @code{module.__file__}, @code{module.__loader__} を (足りない情報についてはデフォルト値を使って補いながら) repr への入力として使おうと試みます。

これが使われている正確な規則です:


@itemize *

@item 
モジュールが @code{__spec__} 属性を持っていれば、仕様に含まれる情報が repr を生成するために使われます。 "name", "loader", "origin", "has_location" 属性が参照されます。

@item 
モジュールに @code{__file__} 属性がある場合は、モジュールの repr の一部として使われます。

@item 
モジュールに @code{__file__} はないが @code{__loader__} があり、その値が @code{None} ではない場合は、ローダーの repr がモジュールの repr の一部として使われます。

@item 
そうでなければ、単にモジュールの @code{__name__} を repr の中で使います。
@end itemize


バージョン 3.12 で変更: Use of @code{module_repr()}, having been deprecated since Python 3.4, was
removed in Python 3.12 and is no longer called during the resolution of a
module's repr.


@node キャッシュされたバイトコードの無効化,,モジュールの repr,ロード
@anchor{reference/import cached-bytecode-invalidation}@anchor{2456}@anchor{reference/import pyc-invalidation}@anchor{802}
@subsubsection キャッシュされたバイトコードの無効化


Before Python loads cached bytecode from a @code{.pyc} file, it checks whether the
cache is up-to-date with the source @code{.py} file. By default, Python does this
by storing the source's last-modified timestamp and size in the cache file when
writing it. At runtime, the import system then validates the cache file by
checking the stored metadata in the cache file against the source's
metadata.

Python also supports "hash-based" cache files, which store a hash of the source
file's contents rather than its metadata. There are two variants of hash-based
@code{.pyc} files: checked and unchecked. For checked hash-based @code{.pyc} files,
Python validates the cache file by hashing the source file and comparing the
resulting hash with the hash in the cache file. If a checked hash-based cache
file is found to be invalid, Python regenerates it and writes a new checked
hash-based cache file. For unchecked hash-based @code{.pyc} files, Python simply
assumes the cache file is valid if it exists. Hash-based @code{.pyc} files
validation behavior may be overridden with the @ref{2122,,--check-hash-based-pycs}
flag.


バージョン 3.7 で変更: Added hash-based @code{.pyc} files. Previously, Python only supported
timestamp-based invalidation of bytecode caches.


@node パスベース・ファインダー,標準のインポートシステムを置き換える,ロード,インポートシステム
@anchor{reference/import the-path-based-finder}@anchor{2457}
@subsection パスベース・ファインダー


@geindex path based finder

上で触れた通り、 Python にはいくつかのデフォルトのメタパス・ファインダーが備わっています。そのうちの 1 つは @ref{244d,,パスベース・ファインダー} (@ref{1224,,PathFinder}) と呼ばれ、 @ref{2458,,パスエントリ} のリストである @ref{244a,,インポートパス} を検索します。それぞれのパスエントリは、モジュールを探す場所を指しています。

パスベース・ファインダー自体は何かのインポート方法を知っているわけではありません。その代わりに、個々のパスエントリを走査し、それぞれに特定の種類のパスの扱いを知っているパスエントリ・ファインダーを関連付けます。

デフォルトのパスエントリ・ファインダーは、ファイルシステム上のモジュールを見つけるためのすべてのセマンティクスを実装しています。それは Python ソースコード (@code{.py} ファイル) 、Python バイトコード (@code{.pyc} ファイル) 、共有ライブラリ (例えば @code{.so} ファイル) などの特別なファイルタイプを処理します。標準ライブラリの @ref{138,,zipimport} モジュールによってサポートされる場合は、デフォルトのパスエントリ・ファインダーは (共有ライブラリ以外の) すべてのファイルタイプの zip ファイルからのロードも扱います。

パスエントリはファイルシステム上の場所に限定される必要はありません。URL やデータベースクエリやその他文字列で指定できる場所を参照することも可能です。

パスベース・ファインダーにはフックやプロトコルを追加することができ、それによって検索可能なパスエントリの種類を拡張し、カスタマイズすることができます。例えば、ネットワーク上の URL をパスエントリとしてサポートしたい場合、 web 上のモジュールを見つけるために HTTP の取り扱い方を実装したフックを書くことができます。この (呼び出し可能オブジェクトである) フックは、下で解説するプロトコルをサポートする @ref{127d,,パスエントリ・ファインダー} を返します。このプロトコルは  web からモジュールのローダーを取得するのに使われます。

警告の言葉: この節と前の節の両方で `ファインダー' という言葉が、 @ref{127c,,メタパス・ファインダー} と @ref{127d,,パスエントリ・ファインダー} という用語で区別されて使われています。これら 2 種類のファインダーは非常に似ており、似たプロトコルをサポートし、インポート処理で同じように機能しますが、微妙に異なっているのを心に留めておくのは重要です。特に、メタパス・ファインダーはインポート処理の開始時、 @ref{f27,,sys.meta_path} の走査が動くときに動作します。

それとは対照的に、パスエントリ・ファインダーはある意味でパスベース・ファインダーの実装詳細であり、実際 @ref{f27,,sys.meta_path} からパスベース・ファインダーが取り除かれた場合、パスエントリ・ファインダーの実装は何も実行されないでしょう。

@menu
* パスエントリ・ファインダー:: 
* パスエントリ・ファインダー・プロトコル:: 

@end menu

@node パスエントリ・ファインダー,パスエントリ・ファインダー・プロトコル,,パスベース・ファインダー
@anchor{reference/import path-entry-finders}@anchor{2459}
@subsubsection パスエントリ・ファインダー


@geindex sys.path
@geindex sys.path_hooks
@geindex sys.path_importer_cache
@geindex PYTHONPATH

@ref{244d,,パスベース・ファインダー} には、文字列 @ref{2458,,パスエントリ} で指定された場所の Python モジュールや Python パッケージを見つけ、ロードする責任があります。ほとんどのパスエントリはファイルシステム上の場所を指定していますが、そこに制限される必要はありません。

メタパス・ファインダーとして、 @ref{244d,,パスベース・ファインダー} には前に解説した @ref{a68,,find_spec()} プロトコルが実装されていますが、これに加えて @ref{244a,,インポートパス} からモジュールを見つけ、ロードする方法をカスタマイズするために使えるフックを提供しています。

@ref{244d,,パスベース・ファインダー} は @ref{3e4,,sys.path} 、 @ref{1225,,sys.path_hooks} 、 @ref{7fa,,sys.path_importer_cache} という 3 つの変数を使います。さらにパッケージオブジェクトの @code{__path__} 属性も使います。これらによって、インポート処理をカスタマイズする方法が提供されます。

@ref{3e4,,sys.path} contains a list of strings providing search locations for
modules and packages.  It is initialized from the 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH}
environment variable and various other installation- and
implementation-specific defaults.  Entries in @ref{3e4,,sys.path} can name
directories on the file system, zip files, and potentially other "locations"
(see the @ref{cc,,site} module) that should be searched for modules, such as
URLs, or database queries.  Only strings should be present on
@ref{3e4,,sys.path}; all other data types are ignored.

@ref{244d,,パスベース・ファインダー} は @ref{127c,,メタパス・ファインダー} なので、インポート機構は、前で解説したパスベース・ファインダーの @ref{1213,,find_spec()}  メソッドを呼び出すことで @ref{244a,,インポートパス} の検索を始めます。 @code{path} 引数が @ref{1213,,find_spec()} に渡されたときは、それは走査するパス文字列のリスト - 典型的にはそのパッケージの中でインポートしているパッケージの @code{__path__} 属性になります。 @code{path} 引数が @code{None} だった場合、それは最上位のインポートであることを示していて、 @ref{3e4,,sys.path} が使われます。

The path based finder iterates over every entry in the search path, and
for each of these, looks for an appropriate @ref{127d,,path entry finder}
(@ref{a6f,,PathEntryFinder}) for the
path entry.  Because this can be an expensive operation (e.g. there may be
@code{stat()} call overheads for this search), the path based finder maintains
a cache mapping path entries to path entry finders.  This cache is maintained
in @ref{7fa,,sys.path_importer_cache} (despite the name, this cache actually
stores finder objects rather than being limited to @ref{2448,,importer} objects).
In this way, the expensive search for a particular @ref{2458,,path entry}
location's @ref{127d,,path entry finder} need only be done once.  User code is
free to remove cache entries from @ref{7fa,,sys.path_importer_cache} forcing
the path based finder to perform the path entry search again.

path entry がキャッシュの中に無かった場合、 path based finder は @ref{1225,,sys.path_hooks} の中の呼び出し可能オブジェクトを全て辿ります。
このリストのそれぞれの @ref{245a,,path entry フック} は、検索する path entry という引数 1 つを渡して呼び出されます。
その呼び出し可能オブジェクトは path entry を扱える @ref{127d,,path entry finder} を返すか、  @ref{65b,,ImportError} を送出します。
@ref{65b,,ImportError} は、フックが @ref{2458,,path entry} のための @ref{127d,,path entry finder} を探せないことを報せるために path based finder が使います。
この例外は処理されず、 @ref{244a,,import path} を辿っていく処理が続けられます。
フックは引数として文字列またはバイト列オブジェクトを期待します;
バイト列オブジェクトのエンコーディングはフックに任されていて (例えば、ファイルシステムのエンコーディングの UTF-8 やそれ以外などです) 、フックが引数をデコードできなかった場合は @ref{65b,,ImportError} を送出すべきです。

@ref{1225,,sys.path_hooks} を辿る処理が @ref{127d,,パスエントリ・ファインダー} を何も返さずに終わった場合、パスベース・ファインダーの @ref{1213,,find_spec()} メソッドは、 @ref{7fa,,sys.path_importer_cache} に (このパスエントリに対するファインダーが存在しないことを示すために) @code{None} を保存し、 @ref{127c,,メタパス・ファインダー} はモジュールが見つからなかったことを伝えるために @code{None} を返します。

@ref{1225,,sys.path_hooks} 上の @ref{245a,,パスエントリフック} 呼び出し可能オブジェクトの戻り値のいずれかが @ref{127d,,パスエントリ・ファインダー} `であった' 場合、後で出てくるモジュール仕様を探すためのプロトコルが使われ、それがモジュールをロードするために使われます。

The current working directory -- denoted by an empty string -- is handled
slightly differently from other entries on @ref{3e4,,sys.path}. First, if the
current working directory cannot be determined or is found not to exist, no
value is stored in @ref{7fa,,sys.path_importer_cache}. Second, the value for the
current working directory is looked up fresh for each module lookup. Third,
the path used for @ref{7fa,,sys.path_importer_cache} and returned by
@ref{1213,,importlib.machinery.PathFinder.find_spec()} will be the actual current
working directory and not the empty string.

@node パスエントリ・ファインダー・プロトコル,,パスエントリ・ファインダー,パスベース・ファインダー
@anchor{reference/import path-entry-finder-protocol}@anchor{245b}
@subsubsection パスエントリ・ファインダー・プロトコル


モジュールと初期化されたパッケージのインポートをサポートするため、および名前空間パッケージのポーションとして提供するために、パスエントリ・ファインダーは @ref{a6c,,find_spec()}  メソッドを実装しなければいけません。

@ref{a6c,,find_spec()} は 2 つの引数を取ります。インポートしようとしているモジュールの完全修飾名と、 (オプションの) 対象モジュールです。 @cite{find_spec()} はモジュールに対応する完全に初期化 (populated) された仕様を返します。この仕様は (1つの例外を除いて) 常に "loader" セットを持っています。

To indicate to the import machinery that the spec represents a namespace
@ref{2443,,portion}, the path entry finder sets @code{submodule_search_locations} to
a list containing the portion.


バージョン 3.4 で変更: @ref{a6c,,find_spec()} replaced
@code{find_loader()} and
@code{find_module()}, both of which
are now deprecated, but will be used if @code{find_spec()} is not defined.

古いパスエントリ・ファインダーの中には、 @code{find_spec()} の代わりにこれら 2 つの deperecated なメソッドのうちのいずれかを実装しているものがあるかもしれません。これらのメソッドは後方互換性のためにまだ考慮されています。しかし、パスエントリ・ファインダーに @code{find_spec()} が実装されていれば、古いメソッドは無視されます。

@code{find_loader()} takes one argument, the
fully qualified name of the module being imported.  @code{find_loader()}
returns a 2-tuple where the first item is the loader and the second item
is a namespace @ref{2443,,portion}.

他のインポート機構の実装に対する後方互換性のために、多くのパスエントリ・ファインダーは、メタパス・ファインダーがサポートするのと同じ伝統的な @code{find_module()}  メソッドもサポートしています。しかし、パスエントリ・ファインダーの @code{find_module()}  メソッドは、決して @code{path} 引数では呼び出されません (このメソッドは、パスフックの最初の呼び出しから適切なパス情報を記録する動作が期待されています)。

パスエントリ・ファインダーの @code{find_module()} メソッドは deprecated です。なぜなら、その方法ではパスエントリ・ファインダーが名前空間パッケージに対してポーションを提供することができないからです。もし @code{find_loader()} と @code{find_module()} の両方がパスエントリ・ファインダーに存在したら、インポートシステムは常に @code{find_module()} よりも @code{find_loader()} を優先して呼び出します。



バージョン 3.10 で変更: Calls to @code{find_module()} and
@code{find_loader()} by the import
system will raise @ref{71e,,ImportWarning}.



バージョン 3.12 で変更: @code{find_module()} and @code{find_loader()} have been removed.


@node 標準のインポートシステムを置き換える,Package Relative Imports,パスベース・ファインダー,インポートシステム
@anchor{reference/import replacing-the-standard-import-system}@anchor{245c}
@subsection 標準のインポートシステムを置き換える


インポートシステム全体を置き換えるための最も信頼性のある仕組みは、 @ref{f27,,sys.meta_path} のデフォルトの内容を削除し、全部をカスタムのメタパスフックで置き換えるものです。

If it is acceptable to only alter the behaviour of import statements
without affecting other APIs that access the import system, then replacing
the builtin @ref{ad1,,__import__()} function may be sufficient.

(標準のインポートシステム全体を停止するのではなく) すでにメタパスにいるフックからあるモジュールのインポートを選択的に防ぐためには、 @ref{a68,,find_spec()} から @code{None} を返す代わりに、直接 @ref{d3d,,ModuleNotFoundError} を送出するだけで十分です。 @code{None} を返すのはメタパスの走査を続けるべきであることを意味しますが、例外を送出するとすぐに走査を打ち切ります。

@node Package Relative Imports,__main__ に対する特別な考慮,標準のインポートシステムを置き換える,インポートシステム
@anchor{reference/import package-relative-imports}@anchor{245d}@anchor{reference/import relativeimports}@anchor{245e}
@subsection Package Relative Imports


Relative imports use leading dots. A single leading dot indicates a relative
import, starting with the current package. Two or more leading dots indicate a
relative import to the parent(s) of the current package, one level per dot
after the first. For example, given the following package layout:

@example
package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py
@end example

In either @code{subpackage1/moduleX.py} or @code{subpackage1/__init__.py},
the following are valid relative imports:

@example
from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
@end example

Absolute imports may use either the @code{import <>} or @code{from <> import <>}
syntax, but relative imports may only use the second form; the reason
for this is that:

@example
import XXX.YYY.ZZZ
@end example

should expose @code{XXX.YYY.ZZZ} as a usable expression, but .moduleY is
not a valid expression.

@node __main__ に対する特別な考慮,参考資料,Package Relative Imports,インポートシステム
@anchor{reference/import import-dunder-main}@anchor{245f}@anchor{reference/import special-considerations-for-main}@anchor{2460}
@subsection __main__ に対する特別な考慮


@ref{1,,__main__} モジュールは、 Python のインポートシステムに関連する特別なケースです。 @ref{2452,,他の場所} で言及されているように、 @code{__main__} モジュールは @ref{df,,sys} や @ref{13,,builtins} などと同様にインタプリタースタートアップで直接初期化されます。しかし、前者 2 つのモジュールと違って、 @code{__main__} は厳密にはビルトインのモジュールとしての資格を持っていません。これは、 @code{__main__} が初期化される方法がインタプリタが起動されるときのフラグやその他のオプションに依存するためです。

@menu
* __main__.__spec__: __main__ __spec__. 

@end menu

@node __main__ __spec__,,,__main__ に対する特別な考慮
@anchor{reference/import id5}@anchor{2461}@anchor{reference/import main-spec}@anchor{2453}
@subsubsection __main__.__spec__


@ref{1,,__main__} がどのように初期化されるかに依存して、 @code{__main__.__spec__} は適切に設定されることもあれば @code{None} になることもあります。

Python が @ref{23c,,-m} オプションを付けて実行された場合には、 @code{__spec__} は対応するモジュールまたはパッケージのモジュール仕様に設定されます。また、ディレクトリや zip ファイル、または他の @ref{3e4,,sys.path} エントリを実行する処理の一部として @code{__main__} モジュールがロードされる場合にも @code{__spec__} が生成 (populate) されます。

@ref{211b,,それ以外のケース} では、 @code{__main__.__spec__} は @code{None} に設定されます。これは、 @ref{1,,__main__} を生成 (populate) するために使われたコードがインポート可能なモジュールと直接一致していないためです:


@itemize -

@item 
対話プロンプト

@item 
@ref{1a8,,-c} オプション

@item 
stdin から起動された場合

@item 
ソースファイルやバイトコードファイルから直接起動された場合
@end itemize

最後のケースでは、たとえ技術的にはファイルがモジュールとして直接インポートできた `としても' @code{__main__.__spec__} は常に @code{None} になることに注意してください。もし @ref{1,,__main__} において有効なモジュールメタデータが必要なら @ref{23c,,-m} スイッチを使ってください。

@code{__main__} がインポート可能なモジュールと一致し、 @code{__main__.__spec__} がそれに応じて設定されていたとしても、それでもなお、この 2 つのモジュールは別物とみなされることに注意してください。これは、 @code{if __name__ == "__main__":} チェックによって保証されるブロックは、 @code{__main__} 名前空間を生成 (populate) するためにモジュールが使用される時にだけ実行され、通常のインポート時には実行されない、という事実に起因しています。

@node 参考資料,,__main__ に対する特別な考慮,インポートシステム
@anchor{reference/import references}@anchor{2462}
@subsection 参考資料


Python の初期の頃からすると、インポート機構は目覚ましい発展を遂げました。
一部細かいところがドキュメントが書かれたときから変わってはいますが、最初期の パッケージの仕様@footnote{https://www.python.org/doc/essays/packages/} はまだ読むことができます。

オリジナルの @ref{f27,,sys.meta_path} の仕様は 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} で、その後継となる拡張が 
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} です。

@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} introduced @ref{2b2,,namespace packages} for
Python 3.3.  
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} also introduced the @code{find_loader()} protocol as an
alternative to @code{find_module()}.

@geindex Python Enhancement Proposals; PEP 366
PEP 366@footnote{https://peps.python.org/pep-0366/} は、メインモジュールでの明示的な相対インポートのために追加した @code{__package__} 属性の解説をしています。

@geindex Python Enhancement Proposals; PEP 328
PEP 328@footnote{https://peps.python.org/pep-0328/} は絶対インポート、明示的な相対インポート、および、当初 @code{__name__} で提案し、後に 
@geindex Python Enhancement Proposals; PEP 366
PEP 366@footnote{https://peps.python.org/pep-0366/} が @code{__package__} で定めた仕様を導入しました。

@geindex Python Enhancement Proposals; PEP 338
PEP 338@footnote{https://peps.python.org/pep-0338/} はモジュールをスクリプトとして実行するときの仕様を定めています。

@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/} は、モジュール仕様オブジェクトにおけるモジュール毎のインポート状態のカプセル化を追加しています。また、ローダーの定型的な責任のほとんどをインポート機構に肩代わりさせています。これらの変更により、インポートシステムのいくつかの API が deprecate され、またファインダーとローダーには新しいメソッドが追加されました。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 式 expression,単純文 simple statement,インポートシステム,Python 言語リファレンス
@anchor{reference/expressions doc}@anchor{2463}@anchor{reference/expressions expressions}@anchor{2327}@anchor{reference/expressions id1}@anchor{2464}@anchor{reference/expressions translation-repo}@anchor{2465}
@section 式 (expression)


@geindex expression
@geindex BNF

この章では、Python の式における個々の要素の意味について解説します。

`Syntax Notes:' In this and the following chapters,
@ref{2284,,grammar notation} will be used to describe syntax,
not lexical analysis.

When (one alternative of) a syntax rule has the form:

@example
@anchor{reference/expressions grammar-token-python-grammar-name}@anchor{2466}name: othername
@end example

で記述されていて、この構文特有の意味付け (semantics) が記述されていない場合、 @code{name} の形式をとる構文の意味付けは @code{othername} の意味付けと同じになります。

@menu
* 算術変換 (arithmetic conversion): 算術変換 arithmetic conversion. 
* アトム、原子的要素 (atom): アトム、原子的要素 atom. 
* プライマリ:: 
* Await 式:: 
* べき乗演算 (power operator): べき乗演算 power operator. 
* 単項算術演算とビット単位演算 (unary arithmetic and bitwise operation): 単項算術演算とビット単位演算 unary arithmetic and bitwise operation. 
* 二項算術演算 (binary arithmetic operation): 二項算術演算 binary arithmetic operation. 
* シフト演算 (shifting operation): シフト演算 shifting operation. 
* ビット単位演算の二項演算 (binary bitwise operation): ビット単位演算の二項演算 binary bitwise operation. 
* 比較:: 
* ブール演算 (boolean operation): ブール演算 boolean operation. 
* 代入式: 代入式<2>. 
* 条件式 (Conditional Expressions): 条件式 Conditional Expressions. 
* ラムダ (lambda): ラムダ lambda. 
* 式のリスト:: 
* 評価順序:: 
* 演算子の優先順位:: 

@end menu

@node 算術変換 arithmetic conversion,アトム、原子的要素 atom,,式 expression
@anchor{reference/expressions arithmetic-conversions}@anchor{2467}@anchor{reference/expressions conversions}@anchor{2468}
@subsection 算術変換 (arithmetic conversion)


@geindex 算術;変換

When a description of an arithmetic operator below uses the phrase "the numeric
arguments are converted to a common real type", this means that the operator
implementation for built-in numeric types works as described in the
@ref{2469,,Numeric Types} section of the standard
library documentation.

Some additional rules apply for certain operators and non-numeric operands
(for example, a string as a left argument to the @code{%} operator).
Extensions must define their own conversion behavior.

@node アトム、原子的要素 atom,プライマリ,算術変換 arithmetic conversion,式 expression
@anchor{reference/expressions atoms}@anchor{246a}@anchor{reference/expressions id2}@anchor{246b}
@subsection アトム、原子的要素 (atom)


@geindex atom

Atoms are the most basic elements of expressions.
The simplest atoms are @ref{22a0,,names} or literals.
Forms enclosed in parentheses, brackets or braces are also categorized
syntactically as atoms.

Formally, the syntax for atoms is:

@example
@anchor{reference/expressions grammar-token-python-grammar-atom}@anchor{246c}atom:
   | 'True'
   | 'False'
   | 'None'
   | '...'
   | @ref{22c1,,identifier}
   | @ref{246d,,literal}
   | @ref{246e,,enclosure}
@anchor{reference/expressions grammar-token-python-grammar-enclosure}@anchor{246e}enclosure:
   | @ref{246f,,parenth_form}
   | @ref{2470,,list_display}
   | @ref{2471,,dict_display}
   | @ref{2472,,set_display}
   | @ref{2473,,generator_expression}
   | @ref{2474,,yield_atom}
@end example

@menu
* Built-in constants:: 
* 識別子 (identifier、または名前 (name)): 識別子 identifier、または名前 name. 
* リテラル: リテラル<2>. 
* 丸括弧形式 (parenthesized form): 丸括弧形式 parenthesized form. 
* リスト、集合、辞書の表示:: 
* リスト表示:: 
* 集合表示:: 
* 辞書表示:: 
* ジェネレータ式: ジェネレータ式<2>. 
* Yield 式:: 

@end menu

@node Built-in constants,識別子 identifier、または名前 name,,アトム、原子的要素 atom
@anchor{reference/expressions atom-singletons}@anchor{2475}@anchor{reference/expressions built-in-constants}@anchor{2476}
@subsubsection Built-in constants


The keywords @code{True}, @code{False}, and @code{None} name
@ref{2477,,built-in constants}.
The token @code{...} names the @ref{2328,,Ellipsis} constant.

Evaluation of these atoms yields the corresponding value.

@cartouche
@quotation 注釈 
Several more built-in constants are available as global variables,
but only the ones mentioned here are @ref{2289,,keywords}.
In particular, these names cannot be reassigned or used as attributes:

@example
>>> False = 123
  File "<input>", line 1
   False = 123
   ^^^^^
SyntaxError: cannot assign to False
@end example
@end quotation
@end cartouche

@node 識別子 identifier、または名前 name,リテラル<2>,Built-in constants,アトム、原子的要素 atom
@anchor{reference/expressions atom-identifiers}@anchor{22c6}@anchor{reference/expressions identifiers-names}@anchor{2478}
@subsubsection 識別子 (identifier、または名前 (name))


@geindex name
@geindex 識別子

アトムの形になっている識別子 (identifier) は名前 (name) です。字句定義については @ref{22a0,,Names (identifiers and keywords)} 節を、名前付けや束縛については @ref{2346,,名前づけと束縛 (naming and binding)} 節を参照してください。

@geindex 例外;NameError

名前があるオブジェクトに束縛されている場合、名前 atom を評価するとそのオブジェクトになります。名前が束縛されていない場合、 atom を評価しようとすると @ref{452,,NameError} 例外を送出します。

@geindex name;難号化
@geindex プライベートな;名前
@anchor{reference/expressions private-name-mangling}@anchor{20a3}
@menu
* Private name mangling:: 

@end menu

@node Private name mangling,,,識別子 identifier、または名前 name
@anchor{reference/expressions id3}@anchor{2479}
@subsubsection Private name mangling


When an identifier that textually occurs in a class definition begins with two
or more underscore characters and does not end in two or more underscores, it
is considered a `private name' of that class.


@subsubheading 参考


The @ref{14ef,,class specifications}.


More precisely, private names are transformed to a longer form before code is
generated for them.  If the transformed name is longer than 255 characters,
implementation-defined truncation may happen.

The transformation is independent of the syntactical context in which the
identifier is used but only the following private identifiers are mangled:


@itemize -

@item 
Any name used as the name of a variable that is assigned or read or any
name of an attribute being accessed.

The @ref{1272,,__name__} attribute of nested functions, classes, and
type aliases is however not mangled.

@item 
The name of imported modules, e.g., @code{__spam} in @code{import __spam}.
If the module is part of a package (i.e., its name contains a dot),
the name is `not' mangled, e.g., the @code{__foo} in @code{import __foo.bar}
is not mangled.

@item 
The name of an imported member, e.g., @code{__f} in @code{from spam import __f}.
@end itemize

The transformation rule is defined as follows:


@itemize -

@item 
The class name, with leading underscores removed and a single leading
underscore inserted, is inserted in front of the identifier, e.g., the
identifier @code{__spam} occurring in a class named @code{Foo}, @code{_Foo} or
@code{__Foo} is transformed to @code{_Foo__spam}.

@item 
If the class name consists only of underscores, the transformation is the
identity, e.g., the identifier @code{__spam} occurring in a class named @code{_}
or @code{__} is left as is.
@end itemize

@node リテラル<2>,丸括弧形式 parenthesized form,識別子 identifier、または名前 name,アトム、原子的要素 atom
@anchor{reference/expressions atom-literals}@anchor{247a}@anchor{reference/expressions literals}@anchor{247b}
@subsubsection リテラル


@geindex リテラル

A `literal' is a textual representation of a value.
Python supports numeric, string and bytes literals.
@ref{19a,,Format strings} and @ref{17fa,,template strings}
are treated as string literals.

Numeric literals consist of a single @ref{2306,,NUMBER}
token, which names an integer, floating-point number, or an imaginary number.
See the @ref{22a1,,数値リテラル} section in Lexical analysis documentation for details.

String and bytes literals may consist of several tokens.
See section @ref{22e0,,文字列リテラルの結合 (concatenation)} for details.

Note that negative and complex numbers, like @code{-3} or @code{3+4.2j},
are syntactically not literals, but @ref{247c,,unary} or
@ref{247d,,binary} arithmetic operations involving the @code{-} or @code{+}
operator.

Evaluation of a literal yields an object of the given type
(@ref{19b,,int}, @ref{196,,float}, @ref{197,,complex}, @ref{169,,str},
@ref{192,,bytes}, or @ref{16a,,Template}) with the given value.
The value may be approximated in the case of floating-point
and imaginary literals.

The formal grammar for literals is:

@example
@anchor{reference/expressions grammar-token-python-grammar-literal}@anchor{246d}literal: @ref{247e,,strings} | @ref{2306,,NUMBER}
@end example

@geindex immutable;データ;type
@geindex immutable;object

@menu
* Literals and object identity:: 
* 文字列リテラルの結合 (concatenation): 文字列リテラルの結合 concatenation. 

@end menu

@node Literals and object identity,文字列リテラルの結合 concatenation,,リテラル<2>
@anchor{reference/expressions literals-and-object-identity}@anchor{247f}
@subsubsection Literals and object identity


リテラルは全て変更不能なデータ型に対応します。このため、オブジェクトのアイデンティティはオブジェクトの値ほど重要ではありません。同じ値を持つ複数のリテラルを評価した場合、(それらのリテラルがプログラムの同じ場所由来のものであっても、そうでなくても) 同じオブジェクトを指しているか、まったく同じ値を持つ別のオブジェクトになります。

@cartouche
@quotation CPython implementation detail 
For example, in CPython, `small' integers with the same value evaluate
to the same object:

@example
>>> x = 7
>>> y = 7
>>> x is y
True
@end example

However, large integers evaluate to different objects:

@example
>>> x = 123456789
>>> y = 123456789
>>> x is y
False
@end example

This behavior may change in future versions of CPython.
In particular, the boundary between "small" and "large" integers has
already changed in the past.

CPython will emit a @ref{1ae,,SyntaxWarning} when you compare literals
using @code{is}:

@example
>>> x = 7
>>> x is 7
<input>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
True
@end example

See @ref{2480,,いつ is 演算子での同一性テストが頼れますか？} for more information.
@end quotation
@end cartouche

@ref{17fa,,Template strings} are immutable but may reference mutable
objects as @ref{16b,,Interpolation} values.
For the purposes of this section, two t-strings have the "same value" if
both their structure and the `identity' of the values match.

`CPython 実装の詳細:' Currently, each evaluation of a template string results in
a different object.

@node 文字列リテラルの結合 concatenation,,Literals and object identity,リテラル<2>
@anchor{reference/expressions string-concatenation}@anchor{22e0}@anchor{reference/expressions string-literal-concatenation}@anchor{2481}
@subsubsection 文字列リテラルの結合 (concatenation)


Multiple adjacent string or bytes literals, possibly
using different quoting conventions, are allowed, and their meaning is the same
as their concatenation:

@example
>>> "hello" 'world'
"helloworld"
@end example

This feature is defined at the syntactical level, so it only works with literals.
To concatenate string expressions at run time, the '+' operator may be used:

@example
>>> greeting = "Hello"
>>> space = " "
>>> name = "Blaise"
>>> print(greeting + space + name)   # not: print(greeting space name)
Hello Blaise
@end example

Literal concatenation can freely mix raw strings, triple-quoted strings,
and formatted string literals.
For example:

@example
>>> "Hello" r', ' f"@{name@}!"
"Hello, Blaise!"
@end example

This feature can be used to reduce the number of backslashes
needed, to split long strings conveniently across long lines, or even to add
comments to parts of strings. For example:

@example
re.compile("[A-Za-z_]"       # letter or underscore
           "[A-Za-z0-9_]*"   # letter, digit or underscore
          )
@end example

However, bytes literals may only be combined with other byte literals;
not with string literals of any kind.
Also, template string literals may only be combined with other template
string literals:

@example
>>> t"Hello" t"@{name@}!"
Template(strings=('Hello', '!'), interpolations=(...))
@end example

Formally:

@example
@anchor{reference/expressions grammar-token-python-grammar-strings}@anchor{247e}strings: (@ref{22d1,,STRING} | @ref{22f4,,fstring})+ | @ref{2304,,tstring}+
@end example

@node 丸括弧形式 parenthesized form,リスト、集合、辞書の表示,リテラル<2>,アトム、原子的要素 atom
@anchor{reference/expressions parenthesized}@anchor{2482}@anchor{reference/expressions parenthesized-forms}@anchor{2483}
@subsubsection 丸括弧形式 (parenthesized form)


@geindex 丸括弧形式
@geindex () (丸括弧);tuple display

丸括弧形式とは、式リストの一形態で、丸括弧で囲ったものです:

@example
@anchor{reference/expressions grammar-token-python-grammar-parenth_form}@anchor{246f}parenth_form: "(" [@ref{2484,,starred_expression}] ")"
@end example

丸括弧で囲われた式のリストは、個々の式が表現するものになります: リスト内に少なくとも一つのカンマが入っていた場合、タプルになります; そうでない場合、式のリストを構成している単一の式自体の値になります。

@geindex 空の;tuple

中身が空の丸括弧のペアは、空のタプルオブジェクトを表します。
タプルは変更不能なので、リテラルと同じ規則が適用されます (すなわち、空のタプルが二箇所で使われると、それらは同じオブジェクトになることもあるし、ならないこともあります)。

@geindex カンマ
@geindex @comma{} (comma)

タプルは丸括弧で作成されるのではなく、カンマによって作成されることに注意してください。例外は空のタプルで、この場合には丸括弧が `必要です' --- 丸括弧のつかない "何も記述しない式 (nothing)" を使えるようにしてしまうと、文法があいまいなものになってしまい、よくあるタイプミスが検出されなくなってしまいます。

@node リスト、集合、辞書の表示,リスト表示,丸括弧形式 parenthesized form,アトム、原子的要素 atom
@anchor{reference/expressions comprehensions}@anchor{7ec}@anchor{reference/expressions displays-for-lists-sets-and-dictionaries}@anchor{2485}
@subsubsection リスト、集合、辞書の表示


@geindex 内包表記

リスト、集合、辞書を構築するために、 Python は "表示 (display)" と呼ばれる特別な構文を提供していて、次の二種類ずつがあります:


@itemize *

@item 
コンテナの内容を明示的に列挙する

@item 
`内包表記 (comprehension)' と呼ばれる、ループ処理とフィルター処理の組み合わせを用いた計算結果
@end itemize

@geindex for;in comprehensions
@geindex if;in comprehensions
@geindex async for;in comprehensions

内包表記の共通の構文要素は次の通りです:

@example
@anchor{reference/expressions grammar-token-python-grammar-comprehension}@anchor{2486}comprehension: @ref{242d,,assignment_expression} @ref{2487,,comp_for}
@anchor{reference/expressions grammar-token-python-grammar-comp_for}@anchor{2487}comp_for:      ["async"] "for" @ref{2488,,target_list} "in" @ref{2489,,or_test} [@ref{248a,,comp_iter}]
@anchor{reference/expressions grammar-token-python-grammar-comp_iter}@anchor{248a}comp_iter:     @ref{2487,,comp_for} | @ref{248b,,comp_if}
@anchor{reference/expressions grammar-token-python-grammar-comp_if}@anchor{248b}comp_if:       "if" @ref{2489,,or_test} [@ref{248a,,comp_iter}]
@end example

内包表記はまず単一の式、続いて少なくとも 1 個の @code{for} 節、さらに続いて 0 個以上の @code{for} 節あるいは @code{if} 節からなります。
この場合、各々の @code{for} 節や @code{if} 節を、左から右へ深くなっていくネストしたブロックとみなし、ネストの最内のブロックに到達するごとに内包表記の先頭にある式を評価した結果が、最終的にできあがるコンテナの各要素になります。

ただし、最も左にある @code{for} 節のイテラブル式を除いて、内包表記は暗黙的にネストされた個別のスコープで実行されます。
この仕組みのおかげで、対象のリスト内で代入された名前が外側のスコープに "漏れる" ことはありません。

最も左にある @code{for} 節のイテラブル式は、それを直接囲んでいるスコープでそのまま評価され、暗黙的な入れ子のスコープに引数として渡されます。
後に続く @code{for} 節と、最も左にある @code{for} 節のフィルター条件はイテラブル式を直接囲んでいるスコープでは評価できません。というのは、それらは最も左のイテラブルから得られる値に依存しているかもしれないからです。
例えば次の通りです: @code{[x*y for x in range(10) for y in range(x, x+10)]} 。

内包表記が常に適切な型のコンテナになるのを保証するために、 @code{yield} 式や @code{yield from} 式は暗黙的な入れ子のスコープでは禁止されています。

@geindex await;in comprehensions

Since Python 3.6, in an @ref{7ed,,async def} function, an @code{async for}
clause may be used to iterate over a @ref{4c7,,asynchronous iterator}.
A comprehension in an @code{async def} function may consist of either a
@code{for} or @code{async for} clause following the leading
expression, may contain additional @code{for} or @code{async for}
clauses, and may also use @ref{18d,,await} expressions.

If a comprehension contains @code{async for} clauses, or if it contains
@code{await} expressions or other asynchronous comprehensions anywhere except
the iterable expression in the leftmost @code{for} clause, it is called an
`asynchronous comprehension'. An asynchronous comprehension may suspend the
execution of the coroutine function in which it appears.
See also 
@geindex Python Enhancement Proposals; PEP 530
PEP 530@footnote{https://peps.python.org/pep-0530/}.


Added in version 3.6: 非同期内包表記が導入されました。



バージョン 3.8 で変更: @code{yield} および @code{yield from} は暗黙的な入れ子のスコープでは禁止となりました。



バージョン 3.11 で変更: Asynchronous comprehensions are now allowed inside comprehensions in
asynchronous functions. Outer comprehensions implicitly become
asynchronous.


@node リスト表示,集合表示,リスト、集合、辞書の表示,アトム、原子的要素 atom
@anchor{reference/expressions list-displays}@anchor{248c}@anchor{reference/expressions lists}@anchor{248d}
@subsubsection リスト表示


@geindex list;表示
@geindex list;内包表記
@geindex 空の;list
@geindex object;list
@geindex [] (角カッコ);list expression
@geindex @comma{} (comma);expression list

リスト表示は、角括弧で囲われた式の系列です。系列は空の系列であってもかまいません:

@example
@anchor{reference/expressions grammar-token-python-grammar-list_display}@anchor{2470}list_display: "[" [@ref{248e,,flexible_expression_list} | @ref{2486,,comprehension}] "]"
@end example

リスト表示は、新しいリストオブジェクトを与えます。リストの内容は、式のリストまたはリスト内包表記 (list comprehension) で指定されます。
カンマで区切られた式のリストが与えられたときは、それらの各要素は左から右へと順に評価され、その順にリスト内に配置されます。
内包表記が与えられたときは、内包表記の結果の要素でリストが構成されます。

@node 集合表示,辞書表示,リスト表示,アトム、原子的要素 atom
@anchor{reference/expressions set}@anchor{248f}@anchor{reference/expressions set-displays}@anchor{2490}
@subsubsection 集合表示


@geindex 集合;表示
@geindex 集合;内包表記
@geindex object;集合
@geindex @{@} (波括弧);set expression
@geindex @comma{} (comma);expression list

集合表示は波括弧で表され、キーと値を分けるコロンがないことで辞書表現と区別されます:

@example
@anchor{reference/expressions grammar-token-python-grammar-set_display}@anchor{2472}set_display: "@{" (@ref{248e,,flexible_expression_list} | @ref{2486,,comprehension}) "@}"
@end example

集合表示は、新しいミュータブルな集合オブジェクトを与えます。集合の内容は、式の並びまたは内包表記によって指定されます。
カンマ区切りの式のリストが与えられたときは、その要素は左から右へ順に評価され、集合オブジェクトに加えられます。
内包表記が与えられたときは、内包表記の結果の要素で集合が構成されます。

空集合は @code{@{@}} で構成できません。このリテラルは空の辞書を構成します。

@node 辞書表示,ジェネレータ式<2>,集合表示,アトム、原子的要素 atom
@anchor{reference/expressions dict}@anchor{f7f}@anchor{reference/expressions dictionary-displays}@anchor{2491}
@subsubsection 辞書表示


@geindex dictionary;表示
@geindex dictionary;内包表記
@geindex キー
@geindex value
@geindex key/value pair
@geindex object;dictionary
@geindex @{@} (波括弧);dictionary expression
@geindex ; (コロン);in dictionary expressions
@geindex @comma{} (comma);in dictionary displays

A dictionary display is a possibly empty series of dict items (key/value pairs)
enclosed in curly braces:

@example
@anchor{reference/expressions grammar-token-python-grammar-dict_display}@anchor{2471}dict_display:       "@{" [@ref{2492,,dict_item_list} | @ref{2493,,dict_comprehension}] "@}"
@anchor{reference/expressions grammar-token-python-grammar-dict_item_list}@anchor{2492}dict_item_list:     @ref{2494,,dict_item} ("," @ref{2494,,dict_item})* [","]
@anchor{reference/expressions grammar-token-python-grammar-dict_item}@anchor{2494}dict_item:          @ref{182,,expression} ":" @ref{182,,expression} | "**" @ref{2302,,or_expr}
@anchor{reference/expressions grammar-token-python-grammar-dict_comprehension}@anchor{2493}dict_comprehension: @ref{182,,expression} ":" @ref{182,,expression} @ref{2487,,comp_for}
@end example

辞書表示は、新たな辞書オブジェクトを表します。

If a comma-separated sequence of dict items is given, they are evaluated
from left to right to define the entries of the dictionary: each key object is
used as a key into the dictionary to store the corresponding value.  This means
that you can specify the same key multiple times in the dict item list, and the
final dictionary's value for that key will be the last one given.

@geindex unpacking;dictionary
@geindex **;in dictionary displays

A double asterisk @code{**} denotes `dictionary unpacking'.
Its operand must be a @ref{13d3,,mapping}.  Each mapping item is added
to the new dictionary.  Later values replace values already set by
earlier dict items and earlier dictionary unpackings.


Added in version 3.5: 辞書表示のアンパックは最初に 
@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} で提案されました。


辞書内包表記は、リストや集合の内包表記とは対照的に、通常の "for" や "if" 節の前に、コロンで分けられた 2 つの式が必要です。内包表記が起動すると、結果のキーと値の要素が、作られた順に新しい辞書に挿入されます。

@geindex immutable;object
@geindex hashable

Restrictions on the types of the key values are listed earlier in section
@ref{232f,,標準型の階層}.  (To summarize, the key type should be @ref{824,,hashable}, which excludes
all mutable objects.)  Clashes between duplicate keys are not detected; the last
value (textually rightmost in the display) stored for a given key value
prevails.


バージョン 3.8 で変更: Python 3.8 より前のバージョンでは、辞書内包表記において、キーと値の評価順序は明示されていませんでした。CPython では、値がキーより先に評価されていました。バージョン 3.8 からは 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/} で提案されているように、キーが値より先に評価されます。


@node ジェネレータ式<2>,Yield 式,辞書表示,アトム、原子的要素 atom
@anchor{reference/expressions generator-expressions}@anchor{2495}@anchor{reference/expressions genexpr}@anchor{2496}
@subsubsection ジェネレータ式


@geindex ジェネレータ;expression
@geindex object;ジェネレータ
@geindex () (丸括弧);generator expression

ジェネレータ式 (generator expression) とは、丸括弧を使ったコンパクトなジェネレータ表記法です:

@example
@anchor{reference/expressions grammar-token-python-grammar-generator_expression}@anchor{2473}generator_expression: "(" @ref{182,,expression} @ref{2487,,comp_for} ")"
@end example

ジェネレータ式は新たなジェネレータオブジェクトを与えます。この構文は内包表記とほぼ同じですが、角括弧や波括弧ではなく、丸括弧で囲まれます。

Variables used in the generator expression are evaluated lazily when the
@ref{20ae,,__next__()} method is called for the generator object (in the same
fashion as normal generators).  However, the iterable expression in the
leftmost @code{for} clause is immediately evaluated, and the
@ref{4c8,,iterator} is immediately created for that iterable, so that an error
produced while creating the iterator will be emitted at the point where the generator expression
is defined, rather than at the point where the first value is retrieved.
Subsequent @code{for} clauses and any filter condition in the leftmost
@code{for} clause cannot be evaluated in the enclosing scope as they may
depend on the values obtained from the leftmost iterable. For example:
@code{(x*y for x in range(10) for y in range(x, x+10))}.

関数の唯一の引数として渡す場合には、丸括弧を省略できます。詳しくは @ref{f7d,,呼び出し (call)} 節を参照してください。

ジェネレータ式自身の期待される動作を妨げないために、 @code{yield} 式や @code{yield from} 式は暗黙的に定義されたジェネレータでは禁止されています。

ジェネレータ式が @code{async for} 節あるいは @ref{18d,,await} 式を含んでいる場合、それは `非同期ジェネレータ式' と呼ばれます。
非同期ジェネレータ式は、非同期イテレータである新しい非同期ジェネレータオブジェクトを返します (@ref{f77,,非同期イテレータ (Asynchronous Iterator)} を参照してください)。


Added in version 3.6: 非同期ジェネレータ式が導入されました。



バージョン 3.7 で変更: Python 3.7 より前では、非同期ジェネレータ式は @ref{7ed,,async def} コルーチンでしか使えませんでした。
3.7 からは、任意の関数で非同期ジェネレータ式が使えるようになりました。



バージョン 3.8 で変更: @code{yield} および @code{yield from} は暗黙的な入れ子のスコープでは禁止となりました。


@node Yield 式,,ジェネレータ式<2>,アトム、原子的要素 atom
@anchor{reference/expressions yield-expressions}@anchor{2497}@anchor{reference/expressions yieldexpr}@anchor{2498}
@subsubsection Yield 式


@geindex キーワード;yield
@geindex キーワード;from
@geindex yield;expression
@geindex ジェネレータ;関数

@example
@anchor{reference/expressions grammar-token-python-grammar-yield_atom}@anchor{2474}yield_atom:       "(" @ref{2303,,yield_expression} ")"
@anchor{reference/expressions grammar-token-python-grammar-yield_from}@anchor{2499}yield_from:       "yield" "from" @ref{182,,expression}
@anchor{reference/expressions grammar-token-python-grammar-yield_expression}@anchor{2303}yield_expression: "yield" @ref{249a,,yield_list} | @ref{2499,,yield_from}
@end example

yield 式は @ref{126c,,ジェネレータ} 関数や @ref{249b,,非同期ジェネレータ} 関数を定義するときに使われます。従って、関数定義の本体でのみ使えます。
関数の本体で yield 式 を使用するとその関数はジェネレータ関数になり、 @ref{7ed,,async def} 関数の本体で使用するとそのコルーチン関数は非同期ジェネレータ関数になります。
例えば次のようになります:

@example
def gen():  # defines a generator function
    yield 123

async def agen(): # defines an asynchronous generator function
    yield 123
@end example

含まれているスコープの副作用のため、 @code{yield} 式は暗黙的に定義されたスコープの一部として内包表記やジェネレータ式を実装するのに使うことは許可されていません。


バージョン 3.8 で変更: yield 式は、暗黙的な入れ子のスコープで内包表記やジェネレータ式を実装するための使用が禁止になりました。


ジェネレータ関数についてはすぐ下で説明されています。非同期ジェネレータ関数は、 @ref{249c,,非同期ジェネレータ関数 (asynchronous generator function)} 節に分けて説明されています。

When a generator function is called, it returns an iterator known as a
generator.  That generator then controls the execution of the generator
function.  The execution starts when one of the generator's methods is called.
At that time, the execution proceeds to the first yield expression, where it is
suspended again, returning the value of @ref{249a,,yield_list}
to the generator's caller,
or @code{None} if @ref{249a,,yield_list} is omitted.
By suspended, we mean that all local state is
retained, including the current bindings of local variables, the instruction
pointer, the internal evaluation stack, and the state of any exception handling.
When the execution is resumed by calling one of the generator's methods, the
function can proceed exactly as if the yield expression were just another
external call.  The value of the yield expression after resuming depends on the
method which resumed the execution.  If @ref{20ae,,__next__()} is used
(typically via either a @ref{34a,,for} or the @ref{9d8,,next()} builtin) then the
result is @ref{885,,None}.  Otherwise, if @ref{126d,,send()} is used, then
the result will be the value passed in to that method.

@geindex コルーチン

これまで説明した内容から、ジェネレータ関数はコルーチンにとてもよく似ています。ジェネレータ関数は何度も生成し、1つ以上のエントリポイントを持ち、その実行は一時停止されます。ジェネレータ関数は yield した後で実行の継続を制御できないことが唯一の違いです。その制御は常にジェネレータの呼び出し元へ移されます。

yield 式は @ref{8f8,,try} 構造内で使用できます。ジェネレータの (参照カウントがゼロに達するか、ガベージコレクションによる) 完了前に再開されない場合、ジェネレータ-イテレータの @ref{1793,,close()} メソッドが呼ばれ、@ref{1b0,,finally} 節が実行されます。

@geindex from;yield from expression

@code{yield from <expr>} を使用した場合、与えられた式はイテラブルでなければなりません。そのイテラブルをイテレートすることで生成された値は現在のジェネレータのメソッドの呼び出し元へ直接渡されます。@ref{126d,,send()} で渡されたあらゆる値と @ref{71c,,throw()} で渡されたあらゆる例外は根底のイテレータに適切なメソッドがあれば渡されます。適切なメソッドがない場合、@ref{126d,,send()} は @ref{5f0,,AttributeError} か @ref{198,,TypeError} を、@ref{71c,,throw()} は渡された例外を即座に送出します。

根底のイテレータの完了時、引き起こされた @ref{df5,,StopIteration} インスタンスの @ref{2417,,value} 属性はその yield 式の値となります。
@ref{df5,,StopIteration} を起こす際に明示的にセットされるか、サブイテレータがジェネレータであれば (サブイテレータからかえる値で) 自動的にセットされるかのどちらかです。


バージョン 3.3 で変更: サブイテレータに制御フローを委譲するために @code{yield from <expr>} が追加されました。


yield 式が代入文の単独の右辺式であるとき、括弧は省略できます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 255

@item PEP 255@footnote{https://peps.python.org/pep-0255/} - 単純なジェネレータ

Python へのジェネレータと @ref{bc2,,yield} 文の導入提案。

@geindex Python Enhancement Proposals; PEP 342

@item PEP 342@footnote{https://peps.python.org/pep-0342/} - 拡張されたジェネレータを用いたコルーチン

シンプルなコルーチンとして利用できるように、ジェネレータの構文と API を拡張する提案。

@geindex Python Enhancement Proposals; PEP 380

@item PEP 380@footnote{https://peps.python.org/pep-0380/} - サブジェネレータへの委譲構文

サブジェネレータの委譲を簡単にするための、 @ref{2499,,yield_from} 構文の導入提案。

@geindex Python Enhancement Proposals; PEP 525

@item PEP 525@footnote{https://peps.python.org/pep-0525/} - 非同期ジェネレータ

コルーチン関数へのジェネレータの実装能力の追加による 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} の拡張提案。
@end table


@geindex object;ジェネレータ

@menu
* ジェネレータ-イテレータメソッド:: 
* 使用例:: 
* 非同期ジェネレータ関数 (asynchronous generator function): 非同期ジェネレータ関数 asynchronous generator function<2>. 
* 非同期ジェネレータイテレータメソッド:: 

@end menu

@node ジェネレータ-イテレータメソッド,使用例,,Yield 式
@anchor{reference/expressions generator-iterator-methods}@anchor{249d}@anchor{reference/expressions generator-methods}@anchor{2418}
@subsubsection ジェネレータ-イテレータメソッド


この説ではジェネレータイテレータのメソッドについて説明します。これらはジェネレータ関数の実行制御に使用できます。

以下のジェネレータメソッドの呼び出しは、ジェネレータが既に実行中の場合 @ref{2ec,,ValueError} 例外を送出する点に注意してください。

@geindex 例外;StopIteration

@geindex __next__() (generator のメソッド)
@anchor{reference/expressions generator __next__}@anchor{20ae}
@deffn {メソッド} generator.__next__ ()

Starts the execution of a generator function or resumes it at the last
executed yield expression.  When a generator function is resumed with a
@ref{20ae,,__next__()} method, the current yield expression always
evaluates to @ref{885,,None}.  The execution then continues to the next yield
expression, where the generator is suspended again, and the value of the
@ref{249a,,yield_list} is returned to @ref{20ae,,__next__()}'s
caller.  If the generator exits without yielding another value, a
@ref{df5,,StopIteration} exception is raised.

このメソッドは通常、例えば @ref{34a,,for} ループや組み込みの @ref{9d8,,next()} 関数によって暗黙に呼び出されます。
@end deffn

@geindex send() (generator のメソッド)
@anchor{reference/expressions generator send}@anchor{126d}
@deffn {メソッド} generator.send (value)

ジェネレータ関数の内部へ値を "送り"、実行を再開します。引数の `value' はその時点の yield 式の結果になります。 @ref{126d,,send()} メソッドは次にジェネレータが生成した値を返し、ジェネレータが次の値を生成することなく終了すると @ref{df5,,StopIteration} を送出します。 @ref{126d,,send()} が呼び出されてジェネレータが開始するときは、値を受け取る yield 式が存在しないので、 @ref{885,,None} を引数として呼び出さなければなりません。
@end deffn

@geindex throw() (generator のメソッド)
@anchor{reference/expressions generator throw}@anchor{71c}
@deffn {メソッド} generator.throw (value)

@deffnx {メソッド} generator.throw (type[, value[, traceback]])

ジェネレータが中断した位置で例外を発生させて、そのジェネレータ関数が生成する次の値を返します。ジェネレータが値を生成することなく終了すると @ref{df5,,StopIteration} が発生します。ジェネレータ関数が渡された例外を捕捉しない、もしくは違う例外を発生させるなら、その例外は呼び出し元へ伝搬されます。

In typical use, this is called with a single exception instance similar to the
way the @ref{803,,raise} keyword is used.

For backwards compatibility, however, the second signature is
supported, following a convention from older versions of Python.
The `type' argument should be an exception class, and `value'
should be an exception instance. If the `value' is not provided, the
`type' constructor is called to get an instance. If `traceback'
is provided, it is set on the exception, otherwise any existing
@ref{14de,,__traceback__} attribute stored in `value' may
be cleared.


バージョン 3.12 で変更: The second signature (type[, value[, traceback]]) is deprecated and
may be removed in a future version of Python.

@end deffn

@geindex 例外;GeneratorExit

@geindex close() (generator のメソッド)
@anchor{reference/expressions generator close}@anchor{1793}
@deffn {メソッド} generator.close ()

Raises a @ref{15e1,,GeneratorExit} exception at the point where the generator
function was paused (equivalent to calling @code{throw(GeneratorExit)}).
The exception is raised by the yield expression where the generator was paused.
If the generator function catches the exception and returns a
value, this value is returned from @ref{1793,,close()}.  If the generator function
is already closed, or raises @ref{15e1,,GeneratorExit} (by not catching the
exception), @ref{1793,,close()} returns @ref{885,,None}.  If the generator yields a
value, a @ref{244,,RuntimeError} is raised.  If the generator raises any other
exception, it is propagated to the caller.  If the generator has already
exited due to an exception or normal exit, @ref{1793,,close()} returns
@ref{885,,None} and has no other effect.


バージョン 3.13 で変更: If a generator returns a value upon being closed, the value is returned
by @ref{1793,,close()}.

@end deffn

@geindex yield;例

@node 使用例,非同期ジェネレータ関数 asynchronous generator function<2>,ジェネレータ-イテレータメソッド,Yield 式
@anchor{reference/expressions examples}@anchor{249e}
@subsubsection 使用例


以下の簡単なサンプルはジェネレータとジェネレータ関数の振る舞いを実際に紹介します:

@example
>>> def echo(value=None):
...     print("Execution starts when 'next()' is called for the first time.")
...     try:
...         while True:
...             try:
...                 value = (yield value)
...             except Exception as e:
...                 value = e
...     finally:
...         print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.
@end example

@code{yield from} の使用例は、"What's New in Python." の @ref{123b,,PEP 380; サブジェネレータへの委譲構文} を参照してください。

@node 非同期ジェネレータ関数 asynchronous generator function<2>,非同期ジェネレータイテレータメソッド,使用例,Yield 式
@anchor{reference/expressions asynchronous-generator-functions}@anchor{249c}@anchor{reference/expressions id4}@anchor{249f}
@subsubsection 非同期ジェネレータ関数 (asynchronous generator function)


@ref{7ed,,async def} を使用して定義された関数やメソッドに yield 式があると、その関数は @ref{249b,,非同期ジェネレータ} 関数として定義されます。

非同期ジェネレータ関数が呼び出されると、非同期ジェネレータオブジェクトと呼ばれる非同期イテレータが返されます。
そして、そのオブジェクトはジェネレータ関数の実行を制御します。
通常、非同期ジェネレータオブジェクトは、コルーチン関数内の @ref{ca1,,async for} 文で使われ、これはジェネレータオブジェクトが @ref{34a,,for} 文で使われる様子に類似します。

Calling one of the asynchronous generator's methods returns an @ref{4c9,,awaitable}
object, and the execution starts when this object is awaited on. At that time,
the execution proceeds to the first yield expression, where it is suspended
again, returning the value of @ref{249a,,yield_list} to the
awaiting coroutine. As with a generator, suspension means that all local state
is retained, including the current bindings of local variables, the instruction
pointer, the internal evaluation stack, and the state of any exception handling.
When the execution is resumed by awaiting on the next object returned by the
asynchronous generator's methods, the function can proceed exactly as if the
yield expression were just another external call. The value of the yield
expression after resuming depends on the method which resumed the execution.  If
@ref{24a0,,__anext__()} is used then the result is @ref{885,,None}. Otherwise, if
@ref{ad6,,asend()} is used, then the result will be the value passed in to that
method.

If an asynchronous generator happens to exit early by @ref{17f,,break}, the caller
task being cancelled, or other exceptions, the generator's async cleanup code
will run and possibly raise exceptions or access context variables in an
unexpected context--perhaps after the lifetime of tasks it depends, or
during the event loop shutdown when the async-generator garbage collection hook
is called.
To prevent this, the caller must explicitly close the async generator by calling
@ref{ad5,,aclose()} method to finalize the generator and ultimately detach it
from the event loop.

非同期ジェネレータ関数では、 @ref{8f8,,try} 構造内の任意の場所で yield 式が使用できます。
ただし、非同期ジェネレータが、(参照カウントがゼロに達するか、ガベージコレクションによる) 終了処理より前に再開されない場合、 @code{try} 構造内の yield 式は失敗となり、実行待ちだった @ref{1b0,,finally} 節が実行されます。
このケースでは、非同期ジェネレータが作動しているイベントループやスケジューラの責務は、非同期ジェネレータの @ref{ad5,,aclose()} メソッドを呼び出し、残りのコルーチンオブジェクトを実行し、それによって実行待ちだった @code{finally} 節が実行できるようにします。

To take care of finalization upon event loop termination, an event loop should
define a `finalizer' function which takes an asynchronous generator-iterator and
presumably calls @ref{ad5,,aclose()} and executes the coroutine.
This  `finalizer' may be registered by calling @ref{199d,,sys.set_asyncgen_hooks()}.
When first iterated over, an asynchronous generator-iterator will store the
registered `finalizer' to be called upon finalization. For a reference example
of a `finalizer' method see the implementation of
@code{asyncio.Loop.shutdown_asyncgens} in Lib/asyncio/base_events.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/base_events.py}.

@code{yield from <expr>} 式は、非同期ジェネレータ関数で使われると文法エラーになります。

@geindex object;asynchronous-generator

@node 非同期ジェネレータイテレータメソッド,,非同期ジェネレータ関数 asynchronous generator function<2>,Yield 式
@anchor{reference/expressions asynchronous-generator-iterator-methods}@anchor{24a1}@anchor{reference/expressions asynchronous-generator-methods}@anchor{24a2}
@subsubsection 非同期ジェネレータイテレータメソッド


この小節では、ジェネレータ関数の実行制御に使われる非同期ジェネレータイテレータのメソッドについて説明します。

@geindex 例外;StopAsyncIteration

@geindex __anext__() (agen のメソッド)
@anchor{reference/expressions agen __anext__}@anchor{24a0}
@deffn {メソッド} async agen.__anext__ ()

Returns an awaitable which when run starts to execute the asynchronous
generator or resumes it at the last executed yield expression.  When an
asynchronous generator function is resumed with an @ref{24a0,,__anext__()}
method, the current yield expression always evaluates to @ref{885,,None} in the
returned awaitable, which when run will continue to the next yield
expression. The value of the @ref{249a,,yield_list} of the
yield expression is the value of the @ref{df5,,StopIteration} exception raised by
the completing coroutine.  If the asynchronous generator exits without
yielding another value, the awaitable instead raises a
@ref{1e0f,,StopAsyncIteration} exception, signalling that the asynchronous
iteration has completed.

このメソッドは通常、 @ref{34a,,for} ループによって暗黙に呼び出されます。
@end deffn

@geindex asend() (agen のメソッド)
@anchor{reference/expressions agen asend}@anchor{ad6}
@deffn {メソッド} async agen.asend (value)

Returns an awaitable which when run resumes the execution of the
asynchronous generator. As with the @ref{126d,,send()} method for a
generator, this "sends" a value into the asynchronous generator function,
and the `value' argument becomes the result of the current yield expression.
The awaitable returned by the @ref{ad6,,asend()} method will return the next
value yielded by the generator as the value of the raised
@ref{df5,,StopIteration}, or raises @ref{1e0f,,StopAsyncIteration} if the
asynchronous generator exits without yielding another value.  When
@ref{ad6,,asend()} is called to start the asynchronous
generator, it must be called with @ref{885,,None} as the argument,
because there is no yield expression that could receive the value.
@end deffn

@geindex athrow() (agen のメソッド)
@anchor{reference/expressions agen athrow}@anchor{71d}
@deffn {メソッド} async agen.athrow (value)

@deffnx {メソッド} async agen.athrow (type[, value[, traceback]])

Returns an awaitable that raises an exception of type @code{type} at the point
where the asynchronous generator was paused, and returns the next value
yielded by the generator function as the value of the raised
@ref{df5,,StopIteration} exception.  If the asynchronous generator exits
without yielding another value, a @ref{1e0f,,StopAsyncIteration} exception is
raised by the awaitable.
If the generator function does not catch the passed-in exception, or
raises a different exception, then when the awaitable is run that exception
propagates to the caller of the awaitable.


バージョン 3.12 で変更: The second signature (type[, value[, traceback]]) is deprecated and
may be removed in a future version of Python.

@end deffn

@geindex 例外;GeneratorExit

@geindex aclose() (agen のメソッド)
@anchor{reference/expressions agen aclose}@anchor{ad5}
@deffn {メソッド} async agen.aclose ()

Returns an awaitable that when run will throw a @ref{15e1,,GeneratorExit} into
the asynchronous generator function at the point where it was paused.
If the asynchronous generator function then exits gracefully, is already
closed, or raises @ref{15e1,,GeneratorExit} (by not catching the exception),
then the returned awaitable will raise a @ref{df5,,StopIteration} exception.
Any further awaitables returned by subsequent calls to the asynchronous
generator will raise a @ref{1e0f,,StopAsyncIteration} exception.  If the
asynchronous generator yields a value, a @ref{244,,RuntimeError} is raised
by the awaitable.  If the asynchronous generator raises any other exception,
it is propagated to the caller of the awaitable.  If the asynchronous
generator has already exited due to an exception or normal exit, then
further calls to @ref{ad5,,aclose()} will return an awaitable that does nothing.
@end deffn

@node プライマリ,Await 式,アトム、原子的要素 atom,式 expression
@anchor{reference/expressions id5}@anchor{24a3}@anchor{reference/expressions primaries}@anchor{24a4}
@subsection プライマリ


@geindex プライマリ

プライマリは、言語において最も結合の強い操作を表します。文法は以下のようになります:

@example
@anchor{reference/expressions grammar-token-python-grammar-primary}@anchor{24a5}primary: @ref{246c,,atom} | @ref{24a6,,attributeref} | @ref{24a7,,subscription} | @ref{24a8,,call}
@end example

@menu
* 属性参照:: 
* Subscriptions and slicings:: 
* 呼び出し (call): 呼び出し call. 

@end menu

@node 属性参照,Subscriptions and slicings,,プライマリ
@anchor{reference/expressions attribute-references}@anchor{24a9}@anchor{reference/expressions id6}@anchor{24aa}
@subsubsection 属性参照


@geindex 属性;参照
@geindex . (ドット);attribute reference

属性参照は、プライマリの後ろにピリオドと名前を連ねたものです:

@example
@anchor{reference/expressions grammar-token-python-grammar-attributeref}@anchor{24a6}attributeref: @ref{24a5,,primary} "." @ref{22c1,,identifier}
@end example

@geindex 例外;AttributeError
@geindex object;module
@geindex object;list

The primary must evaluate to an object of a type that supports attribute
references, which most objects do.  This object is then asked to produce the
attribute whose name is the identifier. The type and value produced is
determined by the object.  Multiple evaluations of the same attribute
reference may yield different objects.

This production can be customized by overriding the
@ref{dcb,,__getattribute__()} method or the @ref{6fa,,__getattr__()}
method.  The @code{__getattribute__()} method is called first and either
returns a value or raises @ref{5f0,,AttributeError} if the attribute is not
available.

If an @ref{5f0,,AttributeError} is raised and the object has a @code{__getattr__()}
method, that method is called as a fallback.

@node Subscriptions and slicings,呼び出し call,属性参照,プライマリ
@anchor{reference/expressions subscriptions}@anchor{23ce}@anchor{reference/expressions subscriptions-and-slicings}@anchor{24ab}
@subsubsection Subscriptions and slicings


@geindex 添字表記
@geindex [] (角カッコ);添字表記

@geindex object;sequence
@geindex object;mapping
@geindex object;string
@geindex object;tuple
@geindex object;list
@geindex object;dictionary
@geindex sequence;要素

The `subscription' syntax is usually used for selecting an element from a
@ref{23d4,,container} -- for example, to get a value from
a @ref{183,,dict}:

@example
>>> digits_by_name = @{'one': 1, 'two': 2@}
>>> digits_by_name['two']  # Subscripting a dictionary using the key 'two'
2
@end example

In the subscription syntax, the object being subscribed -- a
@ref{24a4,,primary} -- is followed by a `subscript' in
square brackets.
In the simplest case, the subscript is a single expression.

Depending on the type of the object being subscribed, the subscript is
sometimes called a @ref{23e4,,key} (for mappings), @ref{23e3,,index} (for sequences),
or `type argument' (for @ref{1a1,,generic types}).
Syntactically, these are all equivalent:

@example
>>> colors = ['red', 'blue', 'green', 'black']
>>> colors[3]  # Subscripting a list using the index 3
'black'

>>> list[str]  # Parameterizing the list type using the type argument str
list[str]
@end example

At runtime, the interpreter will evaluate the primary and
the subscript, and call the primary's @ref{588,,__getitem__()} or
@ref{943,,__class_getitem__()} @ref{1c60,,special method} with the subscript
as argument.
For more details on which of these methods is called, see
@ref{23cd,,__class_getitem__ versus __getitem__}.

To show how subscription works, we can define a custom object that
implements @ref{588,,__getitem__()} and prints out the value of
the subscript:

@example
>>> class SubscriptionDemo:
...     def __getitem__(self, key):
...         print(f'subscripted with: @{key!r@}')
...
>>> demo = SubscriptionDemo()
>>> demo[1]
subscripted with: 1
>>> demo['a' * 3]
subscripted with: 'aaa'
@end example

See @ref{588,,__getitem__()} documentation for how built-in types handle
subscription.

Subscriptions may also be used as targets in @ref{2427,,assignment} or
@ref{1b1f,,deletion} statements.
In these cases, the interpreter will call the subscripted object's
@ref{14e3,,__setitem__()} or @ref{14e4,,__delitem__()}
@ref{1c60,,special method}, respectively, instead of @ref{588,,__getitem__()}.

@example
>>> colors = ['red', 'blue', 'green', 'black']
>>> colors[3] = 'white'  # Setting item at index
>>> colors
['red', 'blue', 'green', 'white']
>>> del colors[3]  # Deleting item at index 3
>>> colors
['red', 'blue', 'green']
@end example

All advanced forms of `subscript' documented in the following sections
are also usable for assignment and deletion.

@geindex スライス
@geindex slice
@geindex ; (コロン);スライス
@geindex @comma{} (comma);スライス

@geindex object;sequence
@geindex object;string
@geindex object;tuple
@geindex object;list

@menu
* スライス表記 (slicing): スライス表記 slicing. 
* Comma-separated subscripts:: 
* "Starred" subscriptions:: 
* Formal subscription grammar:: 

@end menu

@node スライス表記 slicing,Comma-separated subscripts,,Subscriptions and slicings
@anchor{reference/expressions id7}@anchor{24ac}@anchor{reference/expressions slicings}@anchor{24ad}
@subsubsection スライス表記 (slicing)


A more advanced form of subscription, `slicing', is commonly used
to extract a portion of a @ref{2338,,sequence}.
In this form, the subscript is a @ref{24ae,,slice}: up to three
expressions separated by colons.
Any of the expressions may be omitted, but a slice must contain at least one
colon:

@example
>>> number_names = ['zero', 'one', 'two', 'three', 'four', 'five']
>>> number_names[1:3]
['one', 'two']
>>> number_names[1:]
['one', 'two', 'three', 'four', 'five']
>>> number_names[:3]
['zero', 'one', 'two']
>>> number_names[:]
['zero', 'one', 'two', 'three', 'four', 'five']
>>> number_names[::2]
['zero', 'two', 'four']
>>> number_names[:-3]
['zero', 'one', 'two']
>>> del number_names[4:]
>>> number_names
['zero', 'one', 'two', 'three']
@end example

When a slice is evaluated, the interpreter constructs a @ref{694,,slice} object
whose @ref{23a5,,start}, @ref{23a6,,stop} and
@ref{23a7,,step} attributes, respectively, are the results of the
expressions between the colons.
Any missing expression evaluates to @ref{885,,None}.
This @code{slice} object is then passed to the @ref{588,,__getitem__()}
or @ref{943,,__class_getitem__()} @ref{1c60,,special method}, as above.

@example
# continuing with the SubscriptionDemo instance defined above:
>>> demo[2:3]
subscripted with: slice(2, 3, None)
>>> demo[::'spam']
subscripted with: slice(None, None, 'spam')
@end example

@node Comma-separated subscripts,"Starred" subscriptions,スライス表記 slicing,Subscriptions and slicings
@anchor{reference/expressions comma-separated-subscripts}@anchor{24af}
@subsubsection Comma-separated subscripts


The subscript can also be given as two or more comma-separated expressions
or slices:

@example
# continuing with the SubscriptionDemo instance defined above:
>>> demo[1, 2, 3]
subscripted with: (1, 2, 3)
>>> demo[1:2, 3]
subscripted with: (slice(1, 2, None), 3)
@end example

This form is commonly used with numerical libraries for slicing
multi-dimensional data.
In this case, the interpreter constructs a @ref{614,,tuple} of the results of the
expressions or slices, and passes this tuple to the @ref{588,,__getitem__()}
or @ref{943,,__class_getitem__()} @ref{1c60,,special method}, as above.

The subscript may also be given as a single expression or slice followed
by a comma, to specify a one-element tuple:

@example
>>> demo['spam',]
subscripted with: ('spam',)
@end example

@node "Starred" subscriptions,Formal subscription grammar,Comma-separated subscripts,Subscriptions and slicings
@anchor{reference/expressions starred-subscriptions}@anchor{24b0}
@subsubsection "Starred" subscriptions



Added in version 3.11: Expressions in `tuple_slices' may be starred. See 
@geindex Python Enhancement Proposals; PEP 646
PEP 646@footnote{https://peps.python.org/pep-0646/}.


The subscript can also contain a starred expression.
In this case, the interpreter unpacks the result into a tuple, and passes
this tuple to @ref{588,,__getitem__()} or @ref{943,,__class_getitem__()}:

@example
# continuing with the SubscriptionDemo instance defined above:
>>> demo[*range(10)]
subscripted with: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
@end example

Starred expressions may be combined with comma-separated expressions
and slices:

@example
>>> demo['a', 'b', *range(3), 'c']
subscripted with: ('a', 'b', 0, 1, 2, 'c')
@end example

@node Formal subscription grammar,,"Starred" subscriptions,Subscriptions and slicings
@anchor{reference/expressions formal-subscription-grammar}@anchor{24b1}
@subsubsection Formal subscription grammar


@example
@anchor{reference/expressions grammar-token-python-grammar-subscription}@anchor{24a7}subscription:     @ref{24a5,,primary} '[' @ref{24b2,,subscript} ']'
@anchor{reference/expressions grammar-token-python-grammar-subscript}@anchor{24b2}subscript:        @ref{24b3,,single_subscript} | @ref{24b4,,tuple_subscript}
@anchor{reference/expressions grammar-token-python-grammar-single_subscript}@anchor{24b3}single_subscript: @ref{24b5,,proper_slice} | @ref{242d,,assignment_expression}
@anchor{reference/expressions grammar-token-python-grammar-proper_slice}@anchor{24b5}proper_slice:     [@ref{182,,expression}] ":" [@ref{182,,expression}] [ ":" [@ref{182,,expression}] ]
@anchor{reference/expressions grammar-token-python-grammar-tuple_subscript}@anchor{24b4}tuple_subscript:  ','.(@ref{24b3,,single_subscript} | @ref{2484,,starred_expression})+ [',']
@end example

Recall that the @code{|} operator @ref{2284,,denotes ordered choice}.
Specifically, in @code{subscript}, if both alternatives would match, the
first (@code{single_subscript}) has priority.

@geindex object;callable
@geindex call
@geindex 引数 (argument);call の意味付け
@geindex () (丸括弧);call
@geindex @comma{} (comma);argument list
@geindex = (等号);関数呼び出しの中の

@node 呼び出し call,,Subscriptions and slicings,プライマリ
@anchor{reference/expressions calls}@anchor{f7d}@anchor{reference/expressions id8}@anchor{24b6}
@subsubsection 呼び出し (call)


呼び出しは、呼び出し可能オブジェクト (例えば @ref{24b7,,function}) を @ref{67b,,arguments} の系列とともに呼び出します。系列は空の系列であってもかまいません:

@example
@anchor{reference/expressions grammar-token-python-grammar-call}@anchor{24a8}call:                 @ref{24a5,,primary} "(" [@ref{24b8,,argument_list} [","] | @ref{2486,,comprehension}] ")"
@anchor{reference/expressions grammar-token-python-grammar-argument_list}@anchor{24b8}argument_list:        @ref{24b9,,positional_arguments} ["," @ref{24ba,,starred_and_keywords}]
                        ["," @ref{24bb,,keywords_arguments}]
                      | @ref{24ba,,starred_and_keywords} ["," @ref{24bb,,keywords_arguments}]
                      | @ref{24bb,,keywords_arguments}
@anchor{reference/expressions grammar-token-python-grammar-positional_arguments}@anchor{24b9}positional_arguments: @ref{24bc,,positional_item} ("," @ref{24bc,,positional_item})*
@anchor{reference/expressions grammar-token-python-grammar-positional_item}@anchor{24bc}positional_item:      @ref{242d,,assignment_expression} | "*" @ref{182,,expression}
@anchor{reference/expressions grammar-token-python-grammar-starred_and_keywords}@anchor{24ba}starred_and_keywords: ("*" @ref{182,,expression} | @ref{24bd,,keyword_item})
                      ("," "*" @ref{182,,expression} | "," @ref{24bd,,keyword_item})*
@anchor{reference/expressions grammar-token-python-grammar-keywords_arguments}@anchor{24bb}keywords_arguments:   (@ref{24bd,,keyword_item} | "**" @ref{182,,expression})
                      ("," @ref{24bd,,keyword_item} | "," "**" @ref{182,,expression})*
@anchor{reference/expressions grammar-token-python-grammar-keyword_item}@anchor{24bd}keyword_item:         @ref{22c1,,identifier} "=" @ref{182,,expression}
@end example

最後の位置引数やキーワード引数の後にカンマをつけてもかまいません。構文の意味付けに影響を及ぼすことはありません。

@geindex parameter;call の意味付け

The primary must evaluate to a callable object (user-defined functions, built-in
functions, methods of built-in objects, class objects, methods of class
instances, and all objects having a @ref{77a,,__call__()} method are callable).  All
argument expressions are evaluated before the call is attempted.  Please refer
to section @ref{2018,,関数定義} for the syntax of formal @ref{234b,,parameter} lists.

@c XXX update with kwonly args PEP

キーワード引数が存在する場合、以下のようにして最初に位置引数 (positional argument) に変換されます。まず、値の入っていないスロットが仮引数に対して生成されます。N 個の位置引数がある場合、位置引数は先頭の N スロットに配置されます。次に、各キーワード引数について、識別子を使って対応するスロットを決定します (識別子が最初の仮引数名と同じなら、最初のスロットを使う、といった具合です)。スロットがすでにすべて埋まっていたなら @ref{198,,TypeError} 例外が送出されます。それ以外の場合、引数をスロットに埋めていきます。 (式が @code{None} であっても、その式でスロットを埋めます)。全ての引数が処理されたら、まだ埋められていないスロットをそれぞれに対応する関数定義時のデフォルト値で埋めます。(デフォルト値は、関数が定義されたときに一度だけ計算されます; 従って、リストや辞書のような変更可能なオブジェクトがデフォルト値として使われると、対応するスロットに引数を指定しない限り、このオブジェクトが全ての呼び出しから共有されます; このような状況は通常避けるべきです。) デフォルト値が指定されていない、値の埋められていないスロットが残っている場合 @ref{198,,TypeError} 例外が送出されます。そうでない場合、値の埋められたスロットからなるリストが呼び出しの引数として使われます。

実装では、名前を持たない位置引数を受け取る組み込み関数を提供されるかもしれません。そういった引数がドキュメント化のために '名付けられて' いたとしても、実際には名付けられていないのでキーワードでは提供されません。 CPython では、C 言語で実装された関数の、名前を持たない位置引数をパースするために @ref{3c1,,PyArg_ParseTuple()} を使用します。

仮引数スロットの数よりも多くの位置引数がある場合、構文 @code{*identifier} を使って指定された仮引数がないかぎり、 @ref{198,,TypeError} 例外が送出されます; 仮引数 @code{*identifier} がある場合、この仮引数は余分な位置引数が入ったタプル (もしくは、余分な位置引数がない場合には空のタプル) を受け取ります。

キーワード引数のいずれかが仮引数名に対応しない場合、構文 @code{**identifier} を使って指定された仮引数がない限り、 @ref{198,,TypeError} 例外が送出されます; 仮引数 @code{**identifier} がある場合、この仮引数は余分なキーワード引数が入った (キーワードをキーとし、引数値をキーに対応する値とした) 辞書を受け取ります。余分なキーワード引数がない場合には、空の (新たな) 辞書を受け取ります。

@geindex * (アスタリスク);関数呼び出しの中の
@geindex unpacking;関数呼び出しの中の

関数呼び出しに @code{*expression} という構文が現れる場合は、 @code{expression} の評価結果は @ref{12f1,,イテラブル} でなければなりません。
そのイテラブルの要素は、追加の位置引数であるかのように扱われます。
@code{f(x1, x2, *y, x3, x4)} という呼び出しにおいて、 `y' の評価結果がシーケンス `y1', ..., `yM' だった場合は、この呼び出しは M+4 個の位置引数 `x1', `x2', `y1', ..., `yM', `x3', `x4' での呼び出しと同じになります。

この結論としては、 @code{*expression} 構文がキーワード引数の `後ろ' に来ることもありますが、キーワード引数 (と任意の @code{**expression} 引数 -- 下を参照) よりも `前' にあるものとして処理されます。
従って、このような動作になります:

@example
>>> def f(a, b):
...     print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
@end example

キーワード引数と @code{*expression} 構文を同じ呼び出しで一緒に使うことはあまりないので、実際に上記のような混乱が頻繁に生じることはありません。

@geindex **;関数呼び出しの中の

関数呼び出しで @code{**expression} 構文が使われた場合、 @code{expression} の評価結果は @ref{13d3,,マッピング} でなければなりません。その内容は追加のキーワード引数として扱われます。
キーにマッチする引数が (明示的なキーワード引数によって、あるいは他のアンパックの中で) 既に値を与えられていたなら、 @ref{198,,TypeError} 例外が送出されます。

When @code{**expression} is used, each key in this mapping must be
a string.
Each value from the mapping is assigned to the first formal parameter
eligible for keyword assignment whose name is equal to the key.
A key need not be a Python identifier (e.g. @code{"max-temp °F"} is acceptable,
although it will not match any formal parameter that could be declared).
If there is no match to a formal parameter
the key-value pair is collected by the @code{**} parameter, if there is one,
or if there is not, a @ref{198,,TypeError} exception is raised.

@code{*identifier} や @code{**identifier} 構文を使った仮引数は、位置引数スロットやキーワード引数名にすることができません。


バージョン 3.5 で変更: 関数呼び出しは任意の数の @code{*} アンパックと @code{**} アンパックを受け取り、位置引数はイテラブルアンパック (@code{*}) の後ろに置け、キーワード引数は辞書アンパック (@code{**}) の後ろに置けるようになりました。
最初に 
@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} で提案されました。


呼び出しを行うと、例外を送出しない限り、常に何らかの値を返します。 @code{None} を返す場合もあります。戻り値がどのように算出されるかは、呼び出し可能オブジェクトの形態によって異なります。

各形態では---


@table @asis

@item ユーザ定義関数:

@geindex 関数;call
@geindex ユーザ定義の;関数;call
@geindex object;ユーザ定義関数
@geindex object;関数

The code block for the function is executed, passing it the argument list.  The
first thing the code block will do is bind the formal parameters to the
arguments; this is described in section @ref{2018,,関数定義}.  When the code block
executes a @ref{1af,,return} statement, this specifies the return value of the
function call.  If execution reaches the end of the code block without
executing a @ref{1af,,return} statement, the return value is @code{None}.

@item 組み込み関数またはメソッド:

@geindex 関数;call
@geindex 組み込み関数;call
@geindex メソッド;call
@geindex 組み込みメソッド;call
@geindex object;組み込みメソッド
@geindex object;組み込み関数
@geindex object;メソッド
@geindex object;関数

結果はインタプリタに依存します; 組み込み関数やメソッドの詳細は @ref{1474,,組み込み関数} を参照してください。

@item クラスオブジェクト:

@geindex object;クラス
@geindex クラスオブジェクト;call

そのクラスの新しいインスタンスが返されます。

@item クラスインスタンスメソッド:

@geindex object;クラスインスタンス
@geindex object;instance
@geindex クラスインスタンス;call

対応するユーザ定義の関数が呼び出されます。このとき、呼び出し時の引数リストより一つ長い引数リストで呼び出されます: インスタンスが引数リストの先頭に追加されます。

@item クラスインスタンス:

@geindex instance;call
@geindex __call__() (オブジェクトメソッド)

The class must define a @ref{77a,,__call__()} method; the effect is then the same as
if that method was called.
@end table

@geindex キーワード;await

@node Await 式,べき乗演算 power operator,プライマリ,式 expression
@anchor{reference/expressions await}@anchor{18d}@anchor{reference/expressions await-expression}@anchor{24be}
@subsection Await 式


@ref{4c9,,awaitable} オブジェクトでの @ref{6b9,,coroutine} 実行を一時停止します。
@ref{f73,,coroutine function} 内でのみ使用できます。

@example
@anchor{reference/expressions grammar-token-python-grammar-await_expr}@anchor{24bf}await_expr: "await" @ref{24a5,,primary}
@end example


Added in version 3.5.


@node べき乗演算 power operator,単項算術演算とビット単位演算 unary arithmetic and bitwise operation,Await 式,式 expression
@anchor{reference/expressions power}@anchor{24c0}@anchor{reference/expressions the-power-operator}@anchor{24c1}
@subsection べき乗演算 (power operator)


@geindex power;演算
@geindex operator;**

べき乗演算は、左側にある単項演算子よりも強い結合優先順位となります。一方、右側にある単項演算子よりは弱い結合優先順位になっています。構文は以下のようになります:

@example
@anchor{reference/expressions grammar-token-python-grammar-power}@anchor{24c2}power: (@ref{24bf,,await_expr} | @ref{24a5,,primary}) ["**" @ref{24c3,,u_expr}]
@end example

従って、べき乗演算子と単項演算子からなる演算列が丸括弧で囲われていない場合、演算子は右から左へと評価されます (この場合は演算子の評価順序を強制しません。つまり @code{-1**2} は @code{-1} になります)。

The power operator has the same semantics as the built-in @ref{1a4,,pow()} function,
when called with two arguments: it yields its left argument raised to the power
of its right argument.
Numeric arguments are first @ref{2469,,converted to a common type},
and the result is of that type.

整数の被演算子では、第二引数が負でない限り、結果は被演算子と同じ型になります; 第二引数が負の場合、全ての引数は浮動小数点型に変換され、浮動小数点型が返されます。例えば @code{10**2} は @code{100} を返しますが、@code{10**-2} は @code{0.01} を返します。

@code{0.0} を負の数でべき乗すると @ref{b3f,,ZeroDivisionError} を送出します。負の数を小数でべき乗した結果は複素数 (@ref{197,,complex} number) になります。 (以前のバージョンでは @ref{2ec,,ValueError} を送出していました)

This operation can be customized using the special @ref{9d4,,__pow__()} and
@ref{1a5,,__rpow__()} methods.

@node 単項算術演算とビット単位演算 unary arithmetic and bitwise operation,二項算術演算 binary arithmetic operation,べき乗演算 power operator,式 expression
@anchor{reference/expressions unary}@anchor{247c}@anchor{reference/expressions unary-arithmetic-and-bitwise-operations}@anchor{24c4}
@subsection 単項算術演算とビット単位演算 (unary arithmetic and bitwise operation)


@geindex 単項;算術;演算
@geindex 単項;ビット単位;演算

全ての単項算術演算とビット単位演算は、同じ優先順位を持っています:

@example
@anchor{reference/expressions grammar-token-python-grammar-u_expr}@anchor{24c3}u_expr: @ref{24c2,,power} | "-" @ref{24c3,,u_expr} | "+" @ref{24c3,,u_expr} | "~" @ref{24c3,,u_expr}
@end example

@geindex 否定
@geindex マイナス
@geindex operator;- (負符号)
@geindex - (負符号);単項演算子

The unary @code{-} (minus) operator yields the negation of its numeric argument; the
operation can be overridden with the @ref{2403,,__neg__()} special method.

@geindex プラス
@geindex operator;+ (プラス記号)
@geindex + (プラス記号);単項演算子

The unary @code{+} (plus) operator yields its numeric argument unchanged; the
operation can be overridden with the @ref{2404,,__pos__()} special method.

@geindex 反転
@geindex operator;~ (チルダ)

The unary @code{~} (invert) operator yields the bitwise inversion of its integer
argument.  The bitwise inversion of @code{x} is defined as @code{-(x+1)}.  It only
applies to integral numbers or to custom objects that override the
@ref{2406,,__invert__()} special method.

@geindex 例外;TypeError

上記の三つはいずれも、引数が正しい型でない場合には @ref{198,,TypeError} 例外が送出されます。

@node 二項算術演算 binary arithmetic operation,シフト演算 shifting operation,単項算術演算とビット単位演算 unary arithmetic and bitwise operation,式 expression
@anchor{reference/expressions binary}@anchor{247d}@anchor{reference/expressions binary-arithmetic-operations}@anchor{24c5}
@subsection 二項算術演算 (binary arithmetic operation)


@geindex 2進数;算術;演算

二項算術演算は、慣習的な優先順位を踏襲しています。演算子のいずれかは、特定の非数値型にも適用されるので注意してください。べき乗 (power) 演算子を除き、演算子には二つのレベル、すなわち乗算的 (multiplicatie) 演算子と加算的 (additie) 演算子しかありません:

@example
@anchor{reference/expressions grammar-token-python-grammar-m_expr}@anchor{24c6}m_expr: @ref{24c3,,u_expr} | @ref{24c6,,m_expr} "*" @ref{24c3,,u_expr} | @ref{24c6,,m_expr} "@@" @ref{24c6,,m_expr} |
        @ref{24c6,,m_expr} "//" @ref{24c3,,u_expr} | @ref{24c6,,m_expr} "/" @ref{24c3,,u_expr} |
        @ref{24c6,,m_expr} "%" @ref{24c3,,u_expr}
@anchor{reference/expressions grammar-token-python-grammar-a_expr}@anchor{24c7}a_expr: @ref{24c6,,m_expr} | @ref{24c7,,a_expr} "+" @ref{24c6,,m_expr} | @ref{24c7,,a_expr} "-" @ref{24c6,,m_expr}
@end example

@geindex 乗算
@geindex operator;* (アスタリスク)

The @code{*} (multiplication) operator yields the product of its arguments.  The
arguments must either both be numbers, or one argument must be an integer and
the other must be a sequence. In the former case, the numbers are
@ref{2469,,converted to a common real type} and then
multiplied together.  In the latter case, sequence repetition is performed;
a negative repetition factor yields an empty sequence.

This operation can be customized using the special @ref{23e0,,__mul__()} and
@ref{23e1,,__rmul__()} methods.


バージョン 3.14 で変更: If only one operand is a complex number, the other operand is converted
to a floating-point number.


@geindex matrix multiplication
@geindex operator;@@ (at)

@code{@@} (at) 演算子は行列の乗算に対し使用されます。
Python の組み込み型はこの演算子を実装していません。

This operation can be customized using the special @ref{f79,,__matmul__()} and
@ref{f7a,,__rmatmul__()} methods.


Added in version 3.5.


@geindex 例外;ZeroDivisionError
@geindex division
@geindex operator;/ (スラッシュ)
@geindex operator;//

The @code{/} (division) and @code{//} (floor division) operators yield the quotient of
their arguments.  The numeric arguments are first
@ref{2469,,converted to a common type}.
Division of integers yields a float, while floor division of integers results in an
integer; the result is that of mathematical division with the 'floor' function
applied to the result.  Division by zero raises the @ref{b3f,,ZeroDivisionError}
exception.

The division operation can be customized using the special @ref{1090,,__truediv__()}
and @ref{23f1,,__rtruediv__()} methods.
The floor division operation can be customized using the special
@ref{170d,,__floordiv__()} and @ref{23f2,,__rfloordiv__()} methods.

@geindex モジュロ
@geindex operator;% (パーセント)

The @code{%} (modulo) operator yields the remainder from the division of the first
argument by the second.  The numeric arguments are first
@ref{2469,,converted to a common type}.
A zero right argument raises the @ref{b3f,,ZeroDivisionError} exception.  The
arguments may be floating-point numbers, e.g., @code{3.14%0.7} equals @code{0.34}
(since @code{3.14} equals @code{4*0.7 + 0.34}.)  The modulo operator always yields a
result with the same sign as its second operand (or zero); the absolute value of
the result is strictly smaller than the absolute value of the second operand
@footnote{
@code{abs(x%y) < abs(y)} は数学的には真となりますが、浮動小数点に対する演算の場合には、値丸め (roundoff) のために数値計算的に真にならない場合があります。例えば、Python の浮動小数点型が IEEE754 倍精度数型になっているプラットフォームを仮定すると、 @code{-1e-100 % 1e100} は @code{1e100} と同じ符号になるはずなのに、計算結果は @code{-1e-100 + 1e100} となります。これは数値計算的には厳密に @code{1e100} と等価です。関数 @ref{24c8,,math.fmod()} は、最初の引数と符号が一致するような値を返すので、上記の場合には @code{-1e-100} を返します。どちらのアプローチが適切かは、アプリケーションに依存します。
}.

切り捨て除算演算と剰余演算は、恒等式: @code{x == (x//y)*y + (x%y)} の関係にあります。切り捨て除算や剰余はまた、組み込み関数 @ref{b99,,divmod()}: @code{divmod(x, y) == (x//y, x%y)} とも関係しています。 @footnote{
x が y の正確な整数倍に非常に近いと、丸めのために @code{x//y} が @code{(x-x%y)//y} よりも 1 だけ大きくなる可能性があります。そのような場合、Python は @code{divmod(x,y)[0] * y + x % y} が @code{x} に非常に近くなるという関係を保つために、後者の値を返します。
} 。

@code{%} 演算子は、数値に対する剰余演算を行うのに加えて、文字列 (string) オブジェクトにオーバーロードされ、旧式の文字列の書式化 (いわゆる補間) を行います。文字列の書式化の構文は Python ライブラリリファレンス @ref{8db,,printf 形式の文字列書式化} 節を参照してください。

The `modulo' operation can be customized using the special @ref{23ea,,__mod__()}
and @ref{fd5,,__rmod__()} methods.

The floor division operator, the modulo operator, and the @ref{b99,,divmod()}
function are not defined for complex numbers.  Instead, convert to a
floating-point number using the @ref{208d,,abs()} function if appropriate.

@geindex 加算
@geindex operator;+ (プラス記号)
@geindex + (プラス記号);二項演算子

The @code{+} (addition) operator yields the sum of its arguments.  The arguments
must either both be numbers or both be sequences of the same type.  In the
former case, the numbers are
@ref{2469,,converted to a common real type} and then
added together.
In the latter case, the sequences are concatenated.

This operation can be customized using the special @ref{23dd,,__add__()} and
@ref{23de,,__radd__()} methods.


バージョン 3.14 で変更: If only one operand is a complex number, the other operand is converted
to a floating-point number.


@geindex 減算
@geindex operator;- (負符号)
@geindex - (負符号);二項演算子

The @code{-} (subtraction) operator yields the difference of its arguments.
The numeric arguments are first
@ref{2469,,converted to a common real type}.

This operation can be customized using the special @ref{23e9,,__sub__()} and
@ref{23f0,,__rsub__()} methods.


バージョン 3.14 で変更: If only one operand is a complex number, the other operand is converted
to a floating-point number.


@node シフト演算 shifting operation,ビット単位演算の二項演算 binary bitwise operation,二項算術演算 binary arithmetic operation,式 expression
@anchor{reference/expressions shifting}@anchor{24c9}@anchor{reference/expressions shifting-operations}@anchor{24ca}
@subsection シフト演算 (shifting operation)


@geindex シフト;演算
@geindex operator;<<
@geindex operator;>>

シフト演算は、算術演算よりも低い優先順位を持っています:

@example
@anchor{reference/expressions grammar-token-python-grammar-shift_expr}@anchor{24cb}shift_expr: @ref{24c7,,a_expr} | @ref{24cb,,shift_expr} ("<<" | ">>") @ref{24c7,,a_expr}
@end example

これらは整数を引数にとります。引数は共通の型に変換されます。シフト演算は第一引数を、第二引数で与えられたビット数だけ、左または右にビットシフトします。

The left shift operation can be customized using the special @ref{23eb,,__lshift__()}
and @ref{23f4,,__rlshift__()} methods.
The right shift operation can be customized using the special @ref{23ec,,__rshift__()}
and @ref{23f5,,__rrshift__()} methods.

@geindex 例外;ValueError

`n' ビットの右シフトは @code{pow(2,n)} による除算として定義されます。`n' ビットの左シフトは @code{pow(2,n)} による乗算として定義されます。

@node ビット単位演算の二項演算 binary bitwise operation,比較,シフト演算 shifting operation,式 expression
@anchor{reference/expressions binary-bitwise-operations}@anchor{24cc}@anchor{reference/expressions bitwise}@anchor{24cd}
@subsection ビット単位演算の二項演算 (binary bitwise operation)


@geindex 2進数;ビット単位;演算

以下の三つのビット単位演算には、それぞれ異なる優先順位レベルがあります:

@example
@anchor{reference/expressions grammar-token-python-grammar-and_expr}@anchor{24ce}and_expr: @ref{24cb,,shift_expr} | @ref{24ce,,and_expr} "&" @ref{24cb,,shift_expr}
@anchor{reference/expressions grammar-token-python-grammar-xor_expr}@anchor{24cf}xor_expr: @ref{24ce,,and_expr} | @ref{24cf,,xor_expr} "^" @ref{24ce,,and_expr}
@anchor{reference/expressions grammar-token-python-grammar-or_expr}@anchor{2302}or_expr:  @ref{24cf,,xor_expr} | @ref{2302,,or_expr} "|" @ref{24cf,,xor_expr}
@end example

@geindex ビット単位;and
@geindex operator;& (アンパサンド)

The @code{&} operator yields the bitwise AND of its arguments, which must be
integers or one of them must be a custom object overriding @ref{23ed,,__and__()} or
@ref{23f6,,__rand__()} special methods.

@geindex ビット単位;xor
@geindex 排他的;or
@geindex operator;^ (キャレット)

The @code{^} operator yields the bitwise XOR (exclusive OR) of its arguments, which
must be integers or one of them must be a custom object overriding @ref{23ee,,__xor__()} or
@ref{23f7,,__rxor__()} special methods.

@geindex ビット単位;or
@geindex 包含的;or
@geindex operator;| (縦棒)

The @code{|} operator yields the bitwise (inclusive) OR of its arguments, which
must be integers or one of them must be a custom object overriding @ref{23ef,,__or__()} or
@ref{23f8,,__ror__()} special methods.

@node 比較,ブール演算 boolean operation,ビット単位演算の二項演算 binary bitwise operation,式 expression
@anchor{reference/expressions comparisons}@anchor{24d0}@anchor{reference/expressions id11}@anchor{24d1}
@subsection 比較


@geindex 比較
@geindex C;言語
@geindex operator;< (小さい)
@geindex operator;> (大きい)
@geindex operator;<=
@geindex operator;>=
@geindex operator;==
@geindex operator;!=

C 言語と違って、Python における比較演算子は同じ優先順位をもっており、全ての算術演算子、シフト演算子、ビット単位演算子よりも低くなっています。また @code{a < b < c} が数学で伝統的に用いられているのと同じ解釈になる点も C 言語と違います:

@example
@anchor{reference/expressions grammar-token-python-grammar-comparison}@anchor{24d2}comparison:    @ref{2302,,or_expr} (@ref{24d3,,comp_operator} @ref{2302,,or_expr})*
@anchor{reference/expressions grammar-token-python-grammar-comp_operator}@anchor{24d3}comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
               | "is" ["not"] | ["not"] "in"
@end example

Comparisons yield boolean values: @code{True} or @code{False}. Custom
`rich comparison methods' may return non-boolean values. In this case
Python will call @ref{3c3,,bool()} on such value in boolean contexts.

@geindex 連鎖;比較

比較はいくらでも連鎖することができます。例えば @code{x < y <= z} は @code{x < y and y <= z} と等価になります。ただしこの場合、前者では @code{y} はただ一度だけ評価される点が異なります (どちらの場合でも、 @code{x < y} が偽になると @code{z} の値はまったく評価されません)。

形式的には、 `a', `b', `c', ..., `y', `z' が式で `op1', `op2', ..., `opN' が比較演算子である場合、 @code{a op1 b op2 c ... y opN z} は @code{a op1 b and b op2 c and ... y opN z} と等価になります。ただし、前者では各式は多くても一度しか評価されません。

@code{a op1 b op2 c} と書いた場合、 `a' から `c' までの範囲にあるかどうかのテストを指すのではないことに注意してください。例えば @code{x < y > z} は (きれいな書き方ではありませんが) 完全に正しい文法です。

@menu
* 値の比較:: 
* 所属検査演算:: 
* 同一性の比較:: 

@end menu

@node 値の比較,所属検査演算,,比較
@anchor{reference/expressions expressions-value-comparisons}@anchor{1c20}@anchor{reference/expressions value-comparisons}@anchor{24d4}
@subsubsection 値の比較


演算子 @code{<}, @code{>}, @code{==}, @code{>=}, @code{<=}, および @code{!=} は2つのオブジェクトの値を比較します。
オブジェクトが同じ型を持つ必要はりません。

@ref{232c,,オブジェクト、値、および型} の章では、オブジェクトは (型や id に加えて) 値を持つことを述べています。
オブジェクトの値は Python ではやや抽象的な概念です: 例えば、オブジェクトの値にアクセスする正統な方法はありません。
また、その全てのデータ属性から構成されるなどの特定の方法で、オブジェクトの値を構築する必要性もありません。
比較演算子は、オブジェクトの値とは何かについての特定の概念を実装しています。
この比較の実装によって、間接的にオブジェクトの値を定義していると考えることもできます。

Because all types are (direct or indirect) subtypes of @ref{c7e,,object}, they
inherit the default comparison behavior from @ref{c7e,,object}.  Types can
customize their comparison behavior by implementing
`rich comparison methods' like @ref{14b8,,__lt__()}, described in
@ref{23ad,,基本的なカスタマイズ}.

等価比較 (@code{==} および @code{!=}) のデフォルトの振る舞いは、オブジェクトの同一性に基づいています。
従って、同一のインスタンスの等価比較の結果は等しいとなり、同一でないインスタンスの等価比較の結果は等しくないとなります。
デフォルトの振る舞いをこのようにしたのは、全てのオブジェクトを反射的 (reflexive つまり @code{x is y} ならば @code{x == y}) なものにしたかったからです。

デフォルトの順序比較 (@code{<}, @code{>}, @code{<=}, @code{>=}) は提供されません; 比較しようとすると @ref{198,,TypeError} が送出されます。
この振る舞いをデフォルトの振る舞いにした動機は、等価性と同じような不変性が欠けているからです。

同一でないインスタンスは常に等価でないとする等価比較のデフォルトの振る舞いは、型が必要とするオブジェクトの値や値に基づいた等価性の実用的な定義とは対照的に思えるでしょう。
そのような型では比較の振る舞いをカスタマイズする必要が出てきて、実際にたくさんの組み込み型でそれが行われています。

次のリストでは、最重要の組み込み型の比較の振る舞いを解説しています。


@itemize *

@item 
いくつかの組み込みの数値型 (@ref{1fdc,,数値型 int@comma{} float@comma{} complex}) と標準ライブラリの型 @ref{213,,fractions.Fraction} および @ref{1fe,,decimal.Decimal} は、これらの型の範囲で異なる型とも比較できますが、複素数では順序比較がサポートされていないという制限があります。
関わる型の制限の範囲内では、精度のロス無しに数学的に (アルゴリズム的に) 正しい比較が行われます。

非数値である @code{float('NaN')} と @code{decimal.Decimal('NaN')} は特別です。
数と非数値との任意の順序比較は偽です。
直観に反する帰結として、非数値は自分自身と等価ではないことになります。
例えば @code{x = float('NaN')} ならば、 @code{3 < x}, @code{x < 3}, @code{x == x} は全て偽で、@code{x != x} は真です。
この振る舞いは IEEE 754 に従ったものです。

@item 
@code{None} and @ref{1a2,,NotImplemented} are singletons.  
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} advises that
comparisons for singletons should always be done with @code{is} or @code{is not},
never the equality operators.

@item 
バイナリシーケンス (@ref{192,,bytes} または @ref{344,,bytearray} のインスタンス) は、これらの型の範囲で異なる型とも比較できます。
比較は要素の数としての値を使った辞書式順序で行われます。

@item 
文字列 (@ref{169,,str} のインスタンス) の比較は、文字の Unicode のコードポイントの数としての値 (組み込み関数 @ref{233b,,ord()} の返り値) を使った辞書式順序で行われます。 @footnote{
Unicode 標準では、 `コードポイント (code point)' (例えば、U+0041) と `抽象文字 (abstract character)' (例えば、"LATIN CAPITAL LETTER A") を区別します。
Unicode のほとんどの抽象文字は 1 つのコードポイントだけを使って表現されますが、複数のコードポイントの列を使っても表現できる抽象文字もたくさんあります。
例えば、抽象文字 "LATIN CAPITAL LETTER C WITH CEDILLA" はコード位置 U+00C7 にある `合成済み文字 (precomposed character)' 1 つだけでも表現できますし、コード位置 U+0043 (LATIN CAPITAL LETTER C) にある `基底文字 (base character)' の後ろに、コード位置 U+0327 (COMBINING CEDILLA) にある `結合文字 (combining character)' が続く列としても表現できます。

文字列の比較操作は Unicode のコードポイントのレベルで行われます。
これは人間にとっては直感的ではないかもしれません。
例えば、 @code{"\u00C7" == "\u0043\u0327"} は、どちらの文字も同じ抽象文字 "LATIN CAPITAL LETTER C WITH CEDILLA" を表現しているにもかかわらず、その結果は @code{False} となります。

抽象文字のレベルで (つまり、人間にとって直感的な方法で) 文字列を比較するには @ref{8e4,,unicodedata.normalize()} を使ってください。
}

文字列とバイナリシーケンスは直接には比較できません。

@item 
シーケンス (@ref{614,,tuple}, @ref{24d,,list}, or @ref{b3d,,range} のインスタンス) の比較は、同じ型どうしでしか行えず、 range は順序比較をサポートしていません。
異なる型どうしの等価比較の結果は等価でないとなり、異なる型どうしの順序比較は @ref{198,,TypeError} を送出します。

Sequences compare lexicographically using comparison of corresponding
elements.  The built-in containers typically assume identical objects are
equal to themselves.  That lets them bypass equality tests for identical
objects to improve performance and to maintain their internal invariants.

組み込みのコレクションどうしの辞書式比較は次のように動作します:


@itemize -

@item 
比較の結果が等価となる2つのコレクションは、同じ型、同じ長さ、対応する要素どうしの比較の結果が等価でなければなりません (例えば、 @code{[1,2] == (1,2)} は型が同じでないので偽です)。

@item 
順序比較をサポートしているコレクションの順序は、最初の等価でない要素の順序と同じになります (例えば、 @code{[1,2,x] <= [1,2,y]} は @code{x <= y} と同じ値になります)。
対応する要素が存在しない場合、短い方のコレクションの方が先の順序となります (例えば、 @code{[1,2] < [1,2,3]} は真です)。
@end itemize

@item 
マッピング (@ref{183,,dict} のインスタンス) の比較の結果が等価となるのは、同じ @code{(key, value)} を持っているときかつそのときに限ります。
キーと値の等価比較では反射性が強制されます。

順序比較 (@code{<}, @code{>}, @code{<=}, @code{>=}) は @ref{198,,TypeError} を送出します。

@item 
集合 (@ref{184,,set} または @ref{7f2,,frozenset} のインスタンス) の比較は、これらの型の範囲で異なる型とも行えます。

集合には、部分集合あるいは上位集合かどうかを基準とする順序比較が定義されています。
この関係は全順序を定義しません (例えば、 @code{@{1,2@}} と @code{@{2,3@}} という2つの集合は片方がもう一方の部分集合でもなく上位集合でもありません)。
従って、集合は全順序性に依存する関数の引数として適切ではありません (例えば、 @ref{110b,,min()}, @ref{110c,,max()}, @ref{dc7,,sorted()} は集合のリストを入力として与えると未定義な結果となります)。

集合の比較では、その要素の反射性が強制されます。

@item 
他の組み込み型のほとんどは比較メソッドが実装されておらず、デフォルトの比較の振る舞いを継承します。
@end itemize

比較の振る舞いをカスタマイズしたユーザ定義クラスは、可能なら次の一貫性の規則に従う必要があります:


@itemize *

@item 
等価比較は反射的でなければなりません。
つまり、同一のオブジェクトは等しくなければなりません:

@quotation

@code{x is y} ならば @code{x == y}
@end quotation

@item 
比較は対称的でなければなりません。
つまり、以下の式の結果は同じでなければなりません:

@quotation

@code{x == y} と @code{y == x}

@code{x != y} と @code{y != x}

@code{x < y} と @code{y > x}

@code{x <= y} と @code{y >= x}
@end quotation

@item 
比較は推移的でなければなりません。
以下の (包括的でない) 例がその説明です:

@quotation

@code{x > y and y > z} ならば @code{x > z}

@code{x < y and y <= z} ならば @code{x < z}
@end quotation

@item 
比較の逆は真偽値の否定でなければなりません。
つまり、以下の式の結果は同じでなければなりません:

@quotation

@code{x == y} と @code{not x != y}

@code{x < y} と @code{not x >= y} (全順序の場合)

@code{x > y} と @code{not x <= y} (全順序の場合)
@end quotation

最後の2式は全順序コレクションに当てはまります (たとえばシーケンスには当てはまりますが、集合やマッピングには当てはまりません)。
@ref{1144,,total_ordering()} デコレータも参照してください。

@item 
@ref{801,,hash()} の結果は等価性と一貫している必要があります。
等価なオブジェクトどうしは同じハッシュ値を持つか、ハッシュ値が計算できないものとされる必要があります。
@end itemize

Python はこの一貫性規則を強制しません。
事実、非数値がこの規則に従わない例となります。
@anchor{reference/expressions in}@anchor{34b}@anchor{reference/expressions not-in}@anchor{841}
@node 所属検査演算,同一性の比較,値の比較,比較
@anchor{reference/expressions membership-test-details}@anchor{23e6}@anchor{reference/expressions membership-test-operations}@anchor{24d5}
@subsubsection 所属検査演算


演算子 @ref{34b,,in} および @ref{841,,not in} は所属関係を調べます。
@code{x in s} の評価は、 `x' が `s' の要素であれば @code{True} となり、そうでなければ @code{False} となります。
@code{x not in s} は @code{x in s} の否定を返します。
すべての組み込みのシーケンス型と集合型に加えて、辞書も @code{in} を辞書が与えられたキーを持っているかを調べる演算子としてサポートしています。
リスト、タプル、集合、凍結集合、辞書、 collections.deque のようなコンテナ型において、式 @code{x in y} は @code{any(x is e or x == e for e in y)} と等価です。

文字列やバイト列型については、 @code{x in y} は `x' が `y' の部分文字列であるとき、かつそのときに限り @code{True} になります。これは @code{y.find(x) != -1} と等価です。空文字列は、他の任意の文字列の部分文字列とみなされます。従って @code{"" in "abc"} は @code{True} を返すことになります。

For user-defined classes which define the @ref{15d3,,__contains__()} method, @code{x in
y} returns @code{True} if @code{y.__contains__(x)} returns a true value, and
@code{False} otherwise.

For user-defined classes which do not define @ref{15d3,,__contains__()} but do define
@ref{e69,,__iter__()}, @code{x in y} is @code{True} if some value @code{z}, for which the
expression @code{x is z or x == z} is true, is produced while iterating over @code{y}.
If an exception is raised during the iteration, it is as if @ref{34b,,in} raised
that exception.

Lastly, the old-style iteration protocol is tried: if a class defines
@ref{588,,__getitem__()}, @code{x in y} is @code{True} if and only if there is a non-negative
integer index `i' such that @code{x is y[i] or x == y[i]}, and no lower integer index
raises the @ref{174e,,IndexError} exception.  (If any other exception is raised, it is as
if @ref{34b,,in} raised that exception).

@geindex operator;in
@geindex operator;not in
@geindex 帰属;テスト
@geindex object;sequence

演算子 @ref{841,,not in} は @ref{34b,,in} の真理値を反転した値として定義されています。

@geindex operator;is
@geindex operator;is not
@geindex 同一性;テスト
@anchor{reference/expressions is}@anchor{34c}
@node 同一性の比較,,所属検査演算,比較
@anchor{reference/expressions identity-comparisons}@anchor{24d6}@anchor{reference/expressions is-not}@anchor{24d7}
@subsubsection 同一性の比較


演算子 @ref{34c,,is} および @ref{24d7,,is not} は、オブジェクトの同一性に対するテストを行います: @code{x is y} は、 `x' と `y' が同じオブジェクトを指すとき、かつそのときに限り真になります。
オブジェクトの同一性は @ref{163c,,id()} 関数を使って判定されます。
@code{x is not y} は @ref{34c,,is} の真値を反転したものになります。 @footnote{
自動的なガベージコレクション、フリーリスト、ディスクリプタの動的特性のために、インスタンスメソッドや定数の比較を行うようなときに @ref{34c,,is} 演算子の利用は、一見すると普通ではない振る舞いだと気付くかもしれません。詳細はそれぞれのドキュメントを確認してください。
}
@anchor{reference/expressions booleans}@anchor{24d8}@anchor{reference/expressions and}@anchor{349}@anchor{reference/expressions or}@anchor{34d}
@node ブール演算 boolean operation,代入式<2>,比較,式 expression
@anchor{reference/expressions boolean-operations}@anchor{24d9}@anchor{reference/expressions not}@anchor{24da}
@subsection ブール演算 (boolean operation)


@geindex 条件;expression
@geindex Boolean;演算

@example
@anchor{reference/expressions grammar-token-python-grammar-or_test}@anchor{2489}or_test:  @ref{24db,,and_test} | @ref{2489,,or_test} "or" @ref{24db,,and_test}
@anchor{reference/expressions grammar-token-python-grammar-and_test}@anchor{24db}and_test: @ref{24dc,,not_test} | @ref{24db,,and_test} "and" @ref{24dc,,not_test}
@anchor{reference/expressions grammar-token-python-grammar-not_test}@anchor{24dc}not_test: @ref{24d2,,comparison} | "not" @ref{24dc,,not_test}
@end example

In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
@code{False}, @code{None}, numeric zero of all types, and empty strings and containers
(including strings, tuples, lists, dictionaries, sets and frozensets).  All
other values are interpreted as true.  User-defined objects can customize their
truth value by providing a @ref{14ed,,__bool__()} method.

@geindex operator;not

演算子 @ref{24da,,not} は、引数が偽である場合には @code{True} を、それ以外の場合には @code{False} になります。

@geindex operator;and

式 @code{x and y} は、まず `x' を評価します; `x' が偽なら `x' の値を返します; それ以外の場合には、 `y' を評価した結果値を返します。

@geindex operator;or

式 @code{x or y} は、まず `x' を評価します; `x' が真なら `x' の値を返します; それ以外の場合には、 `y' を評価した結果値を返します。

なお、 @ref{349,,and} も @ref{34d,,or} も、返す値を @code{True} や @code{False} に制限せず、最後に評価した引数を返します。
この仕様が便利なときもあります。例えば @code{s} が文字列で、空文字列ならデフォルトの値に置き換えたいとき、式 @code{s or 'foo'} は望んだ値を与えます。
@ref{24da,,not} は必ず新しい値を作成するので、引数の型に関係なくブール値を返します (例えば、 @code{not 'foo'} は @code{'@w{'}} ではなく @code{False} になります)。

@geindex ;= (colon equals)
@geindex assignment expression
@geindex walrus operator
@geindex named expression
@geindex 代入;expression

@node 代入式<2>,条件式 Conditional Expressions,ブール演算 boolean operation,式 expression
@anchor{reference/expressions assignment-expressions}@anchor{24dd}@anchor{reference/expressions id14}@anchor{24de}
@subsection 代入式


@example
@anchor{reference/expressions grammar-token-python-grammar-assignment_expression}@anchor{242d}assignment_expression: [@ref{22c1,,identifier} ":="] @ref{182,,expression}
@end example

An assignment expression (sometimes also called a "named expression" or
"walrus") assigns an @ref{182,,expression} to an
@ref{22c1,,identifier}, while also returning the value of the
@ref{182,,expression}.

One common use case is when handling matched regular expressions:

@example
if matching := pattern.search(data):
    do_something(matching)
@end example

Or, when processing a file stream in chunks:

@example
while chunk := file.read(9000):
    process(chunk)
@end example

Assignment expressions must be surrounded by parentheses when
used as expression statements and when used as sub-expressions in
slicing, conditional, lambda,
keyword-argument, and comprehension-if expressions and
in @code{assert}, @code{with}, and @code{assignment} statements.
In all other places where they can be used, parentheses are not required,
including in @code{if} and @code{while} statements.


Added in version 3.8: 代入式に関してより詳しくは 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/} を参照してください。


@node 条件式 Conditional Expressions,ラムダ lambda,代入式<2>,式 expression
@anchor{reference/expressions conditional-expressions}@anchor{24df}@anchor{reference/expressions if-expr}@anchor{17d}
@subsection 条件式 (Conditional Expressions)


@geindex 条件;expression
@geindex 三項;operator
@geindex if;conditional expression
@geindex else;conditional expression

@example
@anchor{reference/expressions grammar-token-python-grammar-conditional_expression}@anchor{2301}conditional_expression: @ref{2489,,or_test} ["if" @ref{2489,,or_test} "else" @ref{182,,expression}]
@anchor{reference/expressions grammar-token-python-grammar-expression}@anchor{182}expression:             @ref{2301,,conditional_expression} | @ref{24e0,,lambda_expr}
@end example

A conditional expression (sometimes called a "ternary operator") is an
alternative to the if-else statement. As it is an expression, it returns a value
and can appear as a sub-expression.

@code{x if C else y} という式は最初に `x' ではなく条件 `C' を評価します。 `C' が true の場合 `x' が評価され値が返されます。 それ以外の場合には `y' が評価され返されます。

条件演算に関してより詳しくは 
@geindex Python Enhancement Proposals; PEP 308
PEP 308@footnote{https://peps.python.org/pep-0308/} を参照してください。
@anchor{reference/expressions lambdas}@anchor{24e1}
@node ラムダ lambda,式のリスト,条件式 Conditional Expressions,式 expression
@anchor{reference/expressions id15}@anchor{24e2}@anchor{reference/expressions lambda}@anchor{14b5}
@subsection ラムダ (lambda)


@geindex lambda;expression
@geindex lambda;形式
@geindex 無名;関数
@geindex ; (コロン);lambda expression

@example
@anchor{reference/expressions grammar-token-python-grammar-lambda_expr}@anchor{24e0}lambda_expr: "lambda" [@ref{24e3,,parameter_list}] ":" @ref{182,,expression}
@end example

ラムダ式 (ラムダ形式とも呼ばれます) は無名関数を作成するのに使います。
式 @code{lambda parameters: expression} は関数オブジェクトになります。
この無名オブジェクトは以下に定義されている関数オブジェクト同様に動作します:

@example
def <lambda>(parameters):
    return expression
@end example

引数の一覧の構文は @ref{2018,,関数定義} を参照してください。ラムダ式で作成された関数は文やアノテーションを含むことができない点に注意してください。

@node 式のリスト,評価順序,ラムダ lambda,式 expression
@anchor{reference/expressions expression-lists}@anchor{24e4}@anchor{reference/expressions exprlists}@anchor{f7e}
@subsection 式のリスト


@geindex expression;list
@geindex @comma{} (comma);expression list

@example
@anchor{reference/expressions grammar-token-python-grammar-starred_expression}@anchor{2484}starred_expression:       "*" @ref{2302,,or_expr} | @ref{182,,expression}
@anchor{reference/expressions grammar-token-python-grammar-flexible_expression}@anchor{24e5}flexible_expression:      @ref{242d,,assignment_expression} | @ref{2484,,starred_expression}
@anchor{reference/expressions grammar-token-python-grammar-flexible_expression_list}@anchor{248e}flexible_expression_list: @ref{24e5,,flexible_expression} ("," @ref{24e5,,flexible_expression})* [","]
@anchor{reference/expressions grammar-token-python-grammar-starred_expression_list}@anchor{24e6}starred_expression_list:  @ref{2484,,starred_expression} ("," @ref{2484,,starred_expression})* [","]
@anchor{reference/expressions grammar-token-python-grammar-expression_list}@anchor{24e7}expression_list:          @ref{182,,expression} ("," @ref{182,,expression})* [","]
@anchor{reference/expressions grammar-token-python-grammar-yield_list}@anchor{249a}yield_list:               @ref{24e7,,expression_list} | @ref{2484,,starred_expression} "," [@ref{24e6,,starred_expression_list}]
@end example

@geindex object;tuple

リスト表示や辞書表示の一部になっているものを除き、少なくとも一つのカンマを含む式のリストはタプルになります。
タプルの長さは、リストにある式の数に等しくなります。
式は左から右へ評価されます。

@geindex iterable;unpacking
@geindex * (アスタリスク);in expression lists

アスタリスク @code{*} は `イテラブルのアンパック' を意味します。
この被演算子は @ref{12f1,,イテラブル} でなければなりません。
このイテラブルはアンパックされた位置で要素のシーケンスに展開され、新しいタプル、リスト、集合に入れ込まれます。


Added in version 3.5: 式リストでのイテラブルのアンパックは最初に 
@geindex Python Enhancement Proposals; PEP 448
PEP 448@footnote{https://peps.python.org/pep-0448/} で提案されました。



Added in version 3.11: Any item in an expression list may be starred. See 
@geindex Python Enhancement Proposals; PEP 646
PEP 646@footnote{https://peps.python.org/pep-0646/}.


@geindex 末尾の;カンマ

A trailing comma is required only to create a one-item tuple,
such as @code{1,}; it is optional in all other cases.
A single expression without a
trailing comma doesn't create a tuple, but rather yields the value of that
expression. (To create an empty tuple, use an empty pair of parentheses:
@code{()}.)

@node 評価順序,演算子の優先順位,式のリスト,式 expression
@anchor{reference/expressions evalorder}@anchor{24e8}@anchor{reference/expressions evaluation-order}@anchor{24e9}
@subsection 評価順序


@geindex 評価;順序

Python は、式を左から右へと順に評価します。
ただし、代入式を評価するときは、右辺が左辺よりも先に評価されます。

以下に示す実行文の各行での評価順序は、添え字の数字順序と同じになります:

@example
expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
@{expr1: expr2, expr3: expr4@}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2
@end example

@node 演算子の優先順位,,評価順序,式 expression
@anchor{reference/expressions operator-precedence}@anchor{24ea}@anchor{reference/expressions operator-summary}@anchor{24eb}
@subsection 演算子の優先順位


@geindex operator;優先順位

以下の表は Python における演算子の優先順位を要約したものです。優先順位の最も高い (結合が最も強い) ものから最も低い (結合が最も弱い) ものに並べてあります。同じボックス内の演算子の優先順位は同じです。構文が明示的に示されていないものは二項演算子です。同じボックス内の演算子は、左から右へとグループ化されます (例外として、べき乗および条件式は右から左にグループ化されます)。

@ref{24d0,,比較} 節で述べられているように、比較、所属、同一性のテストは全てが同じ優先順位を持っていて、左から右に連鎖するという特徴を持っていることに注意してください。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算子

@tab

説明

@item

@code{(expressions...)},

@code{[expressions...]},
@code{@{key: value...@}},
@code{@{expressions...@}}

@tab

結合式または括弧式、リスト表示、辞書表示、集合表示

@item

@code{x[index]}, @code{x[index:index]}
@code{x(arguments...)}, @code{x.attribute}

@tab

Subscription (including slicing),
call, attribute reference

@item

@ref{18d,,await x}

@tab

Await 式

@item

@code{**}

@tab

べき乗 @footnote{
べき乗演算子 @code{**} は、右側にある単項算術演算子あるいは単項ビット演算子より弱い結合優先順位となります。
つまり @code{2**-1} は @code{0.5} になります。
}

@item

@code{+x}, @code{-x}, @code{~x}

@tab

正数、負数、ビット単位 NOT

@item

@code{*}, @code{@@}, @code{/}, @code{//}, @code{%}

@tab

乗算、行列乗算、除算、切り捨て除算、剰余 @footnote{
@code{%} 演算子は文字列フォーマットにも使われ、同じ優先順位が当てはまります。
}

@item

@code{+}, @code{-}

@tab

加算および減算

@item

@code{<<}, @code{>>}

@tab

シフト演算

@item

@code{&}

@tab

ビット単位 AND

@item

@code{^}

@tab

ビット単位 XOR

@item

@code{|}

@tab

ビット単位 OR

@item

@ref{34b,,in}, @ref{841,,not in},
@ref{34c,,is}, @ref{24d7,,is not}, @code{<},
@code{<=}, @code{>}, @code{>=}, @code{!=}, @code{==}

@tab

所属や同一性のテストを含む比較

@item

@ref{24da,,not x}

@tab

ブール演算 NOT

@item

@ref{349,,and}

@tab

ブール演算 AND

@item

@ref{34d,,or}

@tab

ブール演算 OR

@item

@ref{17d,,if} -- @code{else}

@tab

条件式

@item

@ref{14b5,,lambda}

@tab

ラムダ式

@item

@code{:=}

@tab

代入式

@end multitable


@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 単純文 simple statement,複合文 compound statement,式 expression,Python 言語リファレンス
@anchor{reference/simple_stmts doc}@anchor{24ec}@anchor{reference/simple_stmts simple}@anchor{24ed}@anchor{reference/simple_stmts simple-statements}@anchor{24ee}@anchor{reference/simple_stmts translation-repo}@anchor{24ef}
@section 単純文 (simple statement)


@geindex simple;statement

単純文とは、単一の論理行内に収められる文です。単一の行内には、複数の単純文をセミコロンで区切って入れることができます。単純文の構文は以下の通りです:

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-simple_stmt}@anchor{24f0}simple_stmt: @ref{24f1,,expression_stmt}
             | @ref{24f2,,assert_stmt}
             | @ref{24f3,,assignment_stmt}
             | @ref{24f4,,augmented_assignment_stmt}
             | @ref{24f5,,annotated_assignment_stmt}
             | @ref{24f6,,pass_stmt}
             | @ref{24f7,,del_stmt}
             | @ref{24f8,,return_stmt}
             | @ref{24f9,,yield_stmt}
             | @ref{24fa,,raise_stmt}
             | @ref{24fb,,break_stmt}
             | @ref{24fc,,continue_stmt}
             | @ref{24fd,,import_stmt}
             | @ref{24fe,,future_stmt}
             | @ref{24ff,,global_stmt}
             | @ref{2500,,nonlocal_stmt}
             | @ref{2501,,type_stmt}
@end example

@menu
* 式文 (expression statement): 式文 expression statement. 
* 代入文 (assignment statement): 代入文 assignment statement. 
* assert 文:: 
* pass 文: pass 文<2>. 
* del 文: del 文<2>. 
* return 文:: 
* yield 文:: 
* raise 文:: 
* break 文:: 
* continue 文:: 
* import 文:: 
* global 文:: 
* nonlocal 文:: 
* The type statement:: 

@end menu

@node 式文 expression statement,代入文 assignment statement,,単純文 simple statement
@anchor{reference/simple_stmts expression-statements}@anchor{2502}@anchor{reference/simple_stmts exprstmts}@anchor{2503}
@subsection 式文 (expression statement)


@geindex expression;statement
@geindex expression;list

@geindex expression;list

式文は、(主に対話的な使い方では) 値を計算して出力するために使ったり、(通常は) プロシジャ (procedure: 有意な結果を返さない関数のことです; Python では、プロシジャは値 @code{None} を返します) を呼び出すために使います。その他の使い方でも式文を使うことができますし、有用なこともあります。式文の構文は以下の通りです:

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-expression_stmt}@anchor{24f1}expression_stmt: @ref{2484,,starred_expression}
@end example

式文は式のリスト (単一の式のこともあります) を値評価します。

@geindex 組み込み関数;repr
@geindex object;None
@geindex string;変換
@geindex output
@geindex standard;output
@geindex writing;`@w{`}values`@w{`}
@geindex procedure;call

対話モードでは、値が @code{None} でなければ、値を組み込み関数 @ref{1c1,,repr()} で文字列に変換して、その結果の文字列を標準出力に一行使って書き出します。 (@code{None} になる式文の値は書き出されないので、プロシジャの呼び出しを行っても出力は得られません。)

@node 代入文 assignment statement,assert 文,式文 expression statement,単純文 simple statement
@anchor{reference/simple_stmts assignment}@anchor{2427}@anchor{reference/simple_stmts assignment-statements}@anchor{2504}
@subsection 代入文 (assignment statement)


@geindex = (等号);assignment statement
@geindex 代入;statement
@geindex 束縛;name
@geindex rebinding;name
@geindex object;mutable
@geindex 属性;代入

代入文は、名前を値に (再) 束縛したり、変更可能なオブジェクトの属性や要素を変更したりするために使われます:

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-assignment_stmt}@anchor{24f3}assignment_stmt: (@ref{2488,,target_list} "=")+ (@ref{2484,,starred_expression} | @ref{2303,,yield_expression})
@anchor{reference/simple_stmts grammar-token-python-grammar-target_list}@anchor{2488}target_list:     @ref{2505,,target} ("," @ref{2505,,target})* [","]
@anchor{reference/simple_stmts grammar-token-python-grammar-target}@anchor{2505}target:          @ref{22c1,,identifier}
                 | "(" [@ref{2488,,target_list}] ")"
                 | "[" [@ref{2488,,target_list}] "]"
                 | @ref{24a6,,attributeref}
                 | @ref{24a7,,subscription}
                 | "*" @ref{2505,,target}
@end example

(See section @ref{24a4,,プライマリ} for the syntax definitions for `attributeref'
and `subscription'.)

代入文は式のリスト (これは単一の式でも、カンマで区切られた式リストでもよく、後者はタプルになることを思い出してください) を評価し、得られたそれぞれのオブジェクトをターゲット (target) のリストに対して左から右へと代入してゆきます。

@geindex target
@geindex target;list

Assignment is defined recursively depending on the form of the target (list).
When a target is part of a mutable object (an attribute reference or
subscription), the mutable object must ultimately perform the assignment and
decide about its validity, and may raise an exception if the assignment is
unacceptable.  The rules observed by various types and the exceptions raised are
given with the definition of the object types (see section @ref{232f,,標準型の階層}).

@geindex target;list;代入
@geindex @comma{} (comma);in target list
@geindex * (アスタリスク);in assignment target list
@geindex [] (角カッコ);in assignment target list
@geindex () (丸括弧);in assignment target list

ターゲットリストは、丸括弧や角括弧で囲まれていてもよく、それに対するオブジェクトの代入は、以下のように再帰的に定義されています。


@itemize *

@item 
ターゲットリストのターゲットが1つだけでコンマが続いておらず、任意に丸括弧で囲われている場合、オブジェクトはそのターゲットに代入されます。

@item 
その他:


@itemize *

@item 
"星付き"のターゲットと呼ばれる、頭にアスタリスクが一つ付いたターゲットがターゲットリストに一つだけ含まれている場合: オブジェクトはイテラブルで、少なくともターゲットリストのターゲットの数よりも一つ少ない要素を持たなければなりません。
星付きのターゲットより前のターゲットに、イテラブルの先頭の要素が左から右へ代入されます。
星付きのターゲットより後ろのターゲットに、イテラブルの末尾の要素が代入されます。
星付きのターゲットに、イテラブルの残った要素のリストが代入されます (リスト空でもかまいません)。

@item 
そうでない場合: オブジェクトは、ターゲットリストのターゲットと同じ数の要素を持つイテラブルでなければならず、要素は左から右へ対応するターゲットに代入されます。
@end itemize
@end itemize

単一のターゲットへの単一のオブジェクトの代入は、以下のようにして再帰的に定義されています。


@itemize *

@item 
ターゲットが識別子 (名前) の場合:


@itemize *

@item 
名前が現在のコードブロック内の @ref{4ac,,global} や @ref{14bf,,nonlocal} 文に書かれていないければ: 名前は現在のローカル名前空間内のオブジェクトに束縛されます。

@item 
そうでなければ: 名前はそれぞれグローバル名前空間内か、 @ref{14bf,,nonlocal} で決められた外側の名前空間内のオブジェクトに束縛されます。
@end itemize

@geindex デストラクタ

名前がすでに束縛済みの場合、再束縛 (rebind) がおこなわれます。再束縛によって、以前その名前に束縛されていたオブジェクトの参照カウント (reference count) がゼロになった場合、オブジェクトは解放 (deallocate) され、デストラクタ  (destructor) が (存在すれば) 呼び出されます。

@geindex 属性;代入

@item 
ターゲットが属性参照の場合: 参照されている一次語の式が値評価されます。値は代入可能な属性を伴うオブジェクトでなければなりません; そうでなければ、 @ref{198,,TypeError} が送出されます。次に、このオブジェクトに対して、被代入オブジェクトを指定した属性に代入してよいか問い合わせます; 代入を実行できない場合、例外 (通常は @ref{5f0,,AttributeError} ですが、必然ではありません) を送出します。
@anchor{reference/simple_stmts attr-target-note}@anchor{2506}
注意: オブジェクトがクラスインスタンスで、代入演算子の両辺に属性参照があるとき、右辺式の @code{a.x} はインスタンスの属性と (インスタンスの属性が存在しなければ) クラス属性のどちらにもアクセスする可能性があります。左辺のターゲット @code{a.x} は常にインスタンスの属性として割り当てられ、必要ならば生成されます。このとおり、現れる二つの @code{a.x} は同じ値を参照するとは限りません: 右辺式はクラス属性を参照し、左辺は新しいインスタンス属性を代入のターゲットとして生成するようなとき:

@example
class Cls:
    x = 3             # class variable
inst = Cls()
inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3
@end example

このことは、 @ref{4b3,,property()} で作成されたプロパティのようなデスクリプタ属性に対しては、必ずしもあてはまるとは限りません。

@geindex 添字表記;代入
@geindex object;mutable

@item 
If the target is a subscription: The primary expression in the reference is
evaluated.
Next, the subscript expression is evaluated.
Then, the primary's @ref{14e3,,__setitem__()} method is called with
two arguments: the subscript and the assigned object.

Typically, @ref{14e3,,__setitem__()} is defined on mutable sequence objects
(such as lists) and mapping objects (such as dictionaries), and behaves as
follows.

@geindex object;sequence
@geindex object;list

一次語が (リストのような) ミュータブルなシーケンスオブジェクトであれば、添字表記は整数を与えなければなりません。整数が負なら、シーケンスの長さが加算されます。整数は最終的に、シーケンスの長さよりも小さな非負の整数でなくてはならず、シーケンスは、そのインデクスに持つ要素に被代入オブジェクトを代入してよいか問い合わせられます。インデクスが範囲外なら、 @ref{174e,,IndexError} が送出されます (添字指定されたシーケンスに代入を行っても、リスト要素の新たな追加はできません)。

@geindex object;mapping
@geindex object;dictionary

If the primary is a mapping object (such as a dictionary), the subscript must
have a type compatible with the mapping's key type, and the mapping is then
asked to create a key/value pair which maps the subscript to the assigned
object.  This can either replace an existing key/value pair with the same key
value, or insert a new key/value pair (if no key with the same value existed).

@geindex スライス;代入

If the target is a slicing: The primary expression should evaluate to
a mutable sequence object (such as a list).
The assigned object should be @ref{12f1,,iterable}.
The slicing's lower and upper bounds should be integers; if they are @code{None}
(or not present), the defaults are zero and the sequence's length.
If either bound is negative, the sequence's length is added to it.  The
resulting bounds are clipped to lie between zero and the sequence's length,
inclusive.  Finally, the sequence object is asked to replace the slice with
the items of the assigned sequence.  The length of the slice may be different
from the length of the assigned sequence, thus changing the length of the
target sequence, if the target sequence allows it.
@end itemize

代入の定義によれば、左辺と右辺のオーバーラップは '同時 (simultaneous)' です (例えば @code{a, b = b, a} は二つの変数を入れ替えます) が、代入対象となる変数群 `どうし' のオーバーラップは左から右へ起こり、混乱の元です。例えば、以下のプログラムは @code{[0, 2]} を出力してしまいます:

@example
x = [0, 1]
i = 0
i, x[i] = 1, 2         # i is updated, then x[i] is updated
print(x)
@end example


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3132

@item PEP 3132@footnote{https://peps.python.org/pep-3132/} - Extended Iterable Unpacking

@code{*target} の指定機能。
@end table


@menu
* 累算代入文 (augmented assignment statement): 累算代入文 augmented assignment statement. 
* 注釈付き代入文 (annotated assignment statements): 注釈付き代入文 annotated assignment statements. 

@end menu

@node 累算代入文 augmented assignment statement,注釈付き代入文 annotated assignment statements,,代入文 assignment statement
@anchor{reference/simple_stmts augassign}@anchor{2507}@anchor{reference/simple_stmts augmented-assignment-statements}@anchor{2508}
@subsubsection 累算代入文 (augmented assignment statement)


@geindex augmented;代入
@geindex statement;assignment@comma{} augmented
@geindex +=;augmented assignment
@geindex -=;augmented assignment
@geindex *=;augmented assignment
@geindex /=;augmented assignment
@geindex %=;augmented assignment
@geindex &=;augmented assignment
@geindex ^=;augmented assignment
@geindex |=;augmented assignment
@geindex **=;augmented assignment
@geindex //=;augmented assignment
@geindex >>=;augmented assignment
@geindex <<=;augmented assignment

累算代入文は、二項演算と代入文を組み合わせて一つの文にしたものです:

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-augmented_assignment_stmt}@anchor{24f4}augmented_assignment_stmt: @ref{2509,,augtarget} @ref{250a,,augop} (@ref{24e7,,expression_list} | @ref{2303,,yield_expression})
@anchor{reference/simple_stmts grammar-token-python-grammar-augtarget}@anchor{2509}augtarget:                 @ref{22c1,,identifier} | @ref{24a6,,attributeref} | @ref{24a7,,subscription}
@anchor{reference/simple_stmts grammar-token-python-grammar-augop}@anchor{250a}augop:                     "+=" | "-=" | "*=" | "@@=" | "/=" | "//=" | "%=" | "**="
                           | ">>=" | "<<=" | "&=" | "^=" | "|="
@end example

(最後の3つの構文定義については @ref{24a4,,プライマリ} を参照してください。)

累算代入文は、ターゲット (通常の代入文と違って、アンパックは起こりません) と式リストを評価し、それら二つの被演算子間で特定の累算代入型の二項演算を行い、結果をもとのターゲットに代入します。ターゲットは一度しか評価されません。

An augmented assignment statement like @code{x += 1} can be rewritten as @code{x = x +
1} to achieve a similar, but not exactly equal effect. In the augmented
version, @code{x} is only evaluated once. Also, when possible, the actual operation
is performed `in-place', meaning that rather than creating a new object and
assigning that to the target, the old object is modified instead.

通常の代入とは違い、累算代入文は右辺を評価する `前に' 左辺を評価します。たとえば、@code{a[i] += f(x)} はまず @code{a[i]} を調べ、@code{f(x)} を評価して加算を行い、最後に結果を @code{a[i]} に割り当てます。

累算代入文で行われる代入は、タプルへの代入や、一文中に複数のターゲットが存在する場合を除き、通常の代入と同じように扱われます。同様に、累算代入で行われる二項演算は、場合によって `インプレース演算' が行われることを除き、通常の二項演算と同じです。

属性参照のターゲットの場合、 @ref{2506,,クラス属性とインスタンス属性についての注意} と同様に通常の代入が適用されます。

@node 注釈付き代入文 annotated assignment statements,,累算代入文 augmented assignment statement,代入文 assignment statement
@anchor{reference/simple_stmts annassign}@anchor{250b}@anchor{reference/simple_stmts annotated-assignment-statements}@anchor{250c}
@subsubsection 注釈付き代入文 (annotated assignment statements)


@geindex annotated;代入
@geindex statement;assignment@comma{} annotated
@geindex ; (コロン);annotated variable

@ref{f51,,注釈} 代入は、1 つの文の中で変数や属性のアノテーションとオプションの代入文を組み合わせたものです:

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-annotated_assignment_stmt}@anchor{24f5}annotated_assignment_stmt: @ref{2509,,augtarget} ":" @ref{182,,expression}
                           ["=" (@ref{2484,,starred_expression} | @ref{2303,,yield_expression})]
@end example

通常の @ref{2427,,代入文 (assignment statement)} との違いは、代入先が 1 つに限定されることだけです。

The assignment target is considered "simple" if it consists of a single
name that is not enclosed in parentheses.
For simple assignment targets, if in class or module scope,
the annotations are gathered in a lazily evaluated
@ref{4ab,,annotation scope}. The annotations can be
evaluated using the @ref{458,,__annotations__} attribute of a
class or module, or using the facilities in the @ref{6,,annotationlib}
module.

If the assignment target is not simple (an attribute, subscript node, or
parenthesized name), the annotation is never evaluated.

関数スコープで名前に注釈が付いていた場合は、その名前はその関数スコープでローカルなものになります。
注釈は絶対に評価されず、関数スコープにも格納されません。

If the right hand side is present, an annotated
assignment performs the actual assignment as if there was no annotation
present. If the right hand side is not present for an expression
target, then the interpreter evaluates the target except for the last
@ref{14e3,,__setitem__()} or @ref{237c,,__setattr__()} call.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 526

@item PEP 526@footnote{https://peps.python.org/pep-0526/} - Syntax for Variable Annotations

(クラス変数やインスタンス変数を含んだ) 変数の型注釈を付ける、コメントで表現するのではない文法の追加提案。

@geindex Python Enhancement Proposals; PEP 484

@item PEP 484@footnote{https://peps.python.org/pep-0484/} - Type hints

@ref{10a,,typing} モジュールを追加し、静的解析ツールや IDE で使える型アノテーションの標準的な文法を提供する提案。
@end table



バージョン 3.8 で変更: Now annotated assignments allow the same expressions in the right hand side as
regular assignments. Previously, some expressions (like un-parenthesized
tuple expressions) caused a syntax error.



バージョン 3.14 で変更: Annotations are now lazily evaluated in a separate @ref{4ab,,annotation scope}.
If the assignment target is not simple, annotations are never evaluated.


@node assert 文,pass 文<2>,代入文 assignment statement,単純文 simple statement
@anchor{reference/simple_stmts assert}@anchor{b60}@anchor{reference/simple_stmts the-assert-statement}@anchor{250d}
@subsection @code{assert} 文


@geindex statement;assert
@geindex デバッグ;assertions
@geindex @comma{} (comma);expression list

assert 文は、プログラム内にデバッグ用アサーション (debugging assertion) を仕掛けるための便利な方法です:

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-assert_stmt}@anchor{24f2}assert_stmt: "assert" @ref{182,,expression} ["," @ref{182,,expression}]
@end example

単純な形式 @code{assert expression} は

@example
if __debug__:
    if not expression: raise AssertionError
@end example

と等価です。拡張形式 @code{assert expression1, expression2} は、これと等価です

@example
if __debug__:
    if not expression1: raise AssertionError(expression2)
@end example

@geindex __debug__
@geindex 例外;AssertionError

These equivalences assume that @ref{9da,,__debug__} and @ref{8b8,,AssertionError} refer to
the built-in variables with those names.  In the current implementation, the
built-in variable @code{__debug__} is @code{True} under normal circumstances,
@code{False} when optimization is requested (command line option @ref{18c,,-O}).  The current
code generator emits no code for an @ref{b60,,assert} statement when optimization is
requested at compile time.  Note that it is unnecessary to include the source
code for the expression that failed in the error message; it will be displayed
as part of the stack trace.

@ref{9da,,__debug__} への代入は不正な操作です。組み込み変数の値は、インタプリタが開始するときに決定されます。

@node pass 文<2>,del 文<2>,assert 文,単純文 simple statement
@anchor{reference/simple_stmts pass}@anchor{17e}@anchor{reference/simple_stmts the-pass-statement}@anchor{250e}
@subsection @code{pass} 文


@geindex statement;pass
@geindex null;演算
@geindex null;演算

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-pass_stmt}@anchor{24f6}pass_stmt: "pass"
@end example

@ref{17e,,pass} はヌル操作 (null operation) です --- @ref{17e,,pass} が実行されても、何も起きません。 @ref{17e,,pass} は、構文法的には文が必要だが、コードとしては何も実行したくない場合のプレースホルダとして有用です。例えば:

@example
def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
@end example

@node del 文<2>,return 文,pass 文<2>,単純文 simple statement
@anchor{reference/simple_stmts del}@anchor{1b1f}@anchor{reference/simple_stmts the-del-statement}@anchor{250f}
@subsection @code{del} 文


@geindex statement;del
@geindex deletion;target
@geindex deletion;target;list

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-del_stmt}@anchor{24f7}del_stmt: "del" @ref{2488,,target_list}
@end example

オブジェクトの削除 (deletion) は、代入の定義と非常に似た方法で再帰的に定義されています。ここでは完全な詳細は記述せず、いくつかのヒントを述べるにとどめます。

ターゲットリストに対する削除は、各々のターゲットを左から右へと順に再帰的に削除します。

@geindex statement;グローバル
@geindex unbinding;name

Deletion of a name removes the binding of that name from the local or global
namespace, depending on whether the name occurs in a @ref{4ac,,global} statement
in the same code block.  Trying to delete an unbound name raises a
@ref{452,,NameError} exception.

@geindex 属性;deletion

Deletion of attribute references and subscriptions is passed to the
primary object involved; deletion of a slicing is in general equivalent to
assignment of an empty slice of the right type (but even this is determined by
the sliced object).


バージョン 3.2 で変更: 以前は、ある名前がネストしたブロックの自由変数として表れる場合は、ローカル名前空間からその名前を削除することは不正な処理でした。


@node return 文,yield 文,del 文<2>,単純文 simple statement
@anchor{reference/simple_stmts return}@anchor{1af}@anchor{reference/simple_stmts the-return-statement}@anchor{2510}
@subsection @code{return} 文


@geindex statement;return
@geindex 関数;definition
@geindex クラス;definition

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-return_stmt}@anchor{24f8}return_stmt: "return" [@ref{24e7,,expression_list}]
@end example

@ref{1af,,return} は、関数定義内で構文法的にネストして現れますが、ネストしたクラス定義内には現れません。

式リストがある場合、リストが値評価されます。それ以外の場合は @code{None} で置き換えられます。

@ref{1af,,return} を使うと、式リスト (または @code{None}) を戻り値として、現在の関数呼び出しから抜け出します。

@geindex キーワード;finally

@ref{1af,,return} によって、 @ref{1b0,,finally} 節をともなう @ref{8f8,,try} 文の外に処理が引き渡されると、実際に関数から抜ける前に @code{finally} 節が実行されます。

ジェネレータ関数では、 @ref{1af,,return} 文はジェネレータの終わりを示し、 @ref{df5,,StopIteration} 例外を送出させます。返された値は (あれば)、 @ref{df5,,StopIteration} を構成する引数に使われ、 @ref{2417,,StopIteration.value} 属性になります。

非同期ジェネレータ関数では、引数無しの @ref{1af,,return} 文は非同期ジェネレータの終わりを示し、 @ref{1e0f,,StopAsyncIteration} を送出させます。
引数ありの @code{return} 文は、非同期ジェネレータ関数では文法エラーです。

@node yield 文,raise 文,return 文,単純文 simple statement
@anchor{reference/simple_stmts the-yield-statement}@anchor{2511}@anchor{reference/simple_stmts yield}@anchor{bc2}
@subsection @code{yield} 文


@geindex statement;yield
@geindex ジェネレータ;関数
@geindex ジェネレータ;iterator
@geindex 関数;ジェネレータ
@geindex 例外;StopIteration

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-yield_stmt}@anchor{24f9}yield_stmt: @ref{2303,,yield_expression}
@end example

A @ref{bc2,,yield} statement is semantically equivalent to a @ref{2498,,yield expression}. The @code{yield} statement can be used to omit the
parentheses that would otherwise be required in the equivalent yield expression
statement. For example, the yield statements

@example
yield <expr>
yield from <expr>
@end example

は以下の yield 式文と等価です

@example
(yield <expr>)
(yield from <expr>)
@end example

Yield expressions and statements are only used when defining a @ref{126c,,generator}
function, and are only used in the body of the generator function.  Using @ref{bc2,,yield}
in a function definition is sufficient to cause that definition to create a
generator function instead of a normal function.

@ref{bc2,,yield} の意味の完全な説明は、 @ref{2498,,Yield 式} 節を参照してください。

@node raise 文,break 文,yield 文,単純文 simple statement
@anchor{reference/simple_stmts raise}@anchor{803}@anchor{reference/simple_stmts the-raise-statement}@anchor{2512}
@subsection @code{raise} 文


@geindex statement;raise
@geindex 例外
@geindex raising;例外
@geindex __traceback__ (exception の属性)

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-raise_stmt}@anchor{24fa}raise_stmt: "raise" [@ref{182,,expression} ["from" @ref{182,,expression}]]
@end example

If no expressions are present, @ref{803,,raise} re-raises the
exception that is currently being handled, which is also known as the `active exception'.
If there isn't currently an active exception, a @ref{244,,RuntimeError} exception is raised
indicating that this is an error.

そうでなければ、 @ref{803,,raise} は最初の式を、例外オブジェクトとして評価します。これは、 @ref{7d6,,BaseException} のサブクラスまたはインスタンスでなければなりません。クラスなら、例外インスタンスが必要なとき、クラスを無引数でインスタンス化することで得られます。

例外の `型' は例外インスタンスのクラスで、 `値' はインスタンスそのものです。

@geindex object;traceback

A traceback object is normally created automatically when an exception is raised
and attached to it as the @ref{14de,,__traceback__} attribute.
You can create an exception and set your own traceback in one step using the
@ref{2513,,with_traceback()} exception method (which returns the
same exception instance, with its traceback set to its argument), like so:

@example
raise Exception("foo occurred").with_traceback(tracebackobj)
@end example

@geindex 例外;連鎖
@geindex __cause__ (exception の属性)
@geindex __context__ (exception の属性)

The @code{from} clause is used for exception chaining: if given, the second
`expression' must be another exception class or instance. If the second
expression is an exception instance, it will be attached to the raised
exception as the @ref{14e0,,__cause__} attribute (which is writable). If the
expression is an exception class, the class will be instantiated and the
resulting exception instance will be attached to the raised exception as the
@code{__cause__} attribute. If the raised exception is not handled, both
exceptions will be printed:

@example
>>> try:
...     print(1 / 0)
... except Exception as exc:
...     raise RuntimeError("Something bad happened") from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    print(1 / 0)
          ~~^~~
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>
    raise RuntimeError("Something bad happened") from exc
RuntimeError: Something bad happened
@end example

A similar mechanism works implicitly if a new exception is raised when
an exception is already being handled.  An exception may be handled
when an @ref{1ab,,except} or @ref{1b0,,finally} clause, or a
@ref{186,,with} statement, is used.  The previous exception is then
attached as the new exception's @ref{14df,,__context__} attribute:

@example
>>> try:
...     print(1 / 0)
... except:
...     raise RuntimeError("Something bad happened")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    print(1 / 0)
          ~~^~~
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
    raise RuntimeError("Something bad happened")
RuntimeError: Something bad happened
@end example

Exception chaining can be explicitly suppressed by specifying @ref{885,,None} in
the @code{from} clause:

@example
>>> try:
...     print(1 / 0)
... except:
...     raise RuntimeError("Something bad happened") from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
@end example

例外に関する追加情報は @ref{2433,,例外} 節にあります。また、例外処理に関する情報は @ref{8f8,,try 文} 節にあります。


バージョン 3.3 で変更: @ref{885,,None} が @code{raise X from Y} の @code{Y} として使えるようになりました。

Added the @ref{2514,,__suppress_context__} attribute to suppress
automatic display of the exception context.



バージョン 3.11 で変更: If the traceback of the active exception is modified in an @ref{1ab,,except}
clause, a subsequent @code{raise} statement re-raises the exception with the
modified traceback. Previously, the exception was re-raised with the
traceback it had when it was caught.


@node break 文,continue 文,raise 文,単純文 simple statement
@anchor{reference/simple_stmts break}@anchor{17f}@anchor{reference/simple_stmts the-break-statement}@anchor{2515}
@subsection @code{break} 文


@geindex statement;break
@geindex statement;for
@geindex statement;while
@geindex loop;statement

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-break_stmt}@anchor{24fb}break_stmt: "break"
@end example

@ref{17f,,break} 文は、構文としては @ref{34a,,for} ループや @ref{1973,,while} ループの内側でのみ出現することができますが、ループ内の関数定義やクラス定義の内側には出現できません。

@geindex キーワード;else
@geindex loop control;target

@ref{17f,,break} 文は、文を囲う最も内側のループを終了させ、ループにオプションの @code{else} 節がある場合にはそれをスキップします。

@ref{34a,,for} ループを @ref{17f,,break} によって終了すると、ループ制御ターゲットはその時の値を保持します。

@geindex キーワード;finally

@ref{17f,,break} が @ref{1b0,,finally} 節を伴う @ref{8f8,,try} 文の外側に処理を渡す際には、ループを実際に抜ける前にその @code{finally} 節が実行されます。

@node continue 文,import 文,break 文,単純文 simple statement
@anchor{reference/simple_stmts continue}@anchor{180}@anchor{reference/simple_stmts the-continue-statement}@anchor{2516}
@subsection @code{continue} 文


@geindex statement;continue
@geindex statement;for
@geindex statement;while
@geindex loop;statement
@geindex キーワード;finally

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-continue_stmt}@anchor{24fc}continue_stmt: "continue"
@end example

@ref{180,,continue} 文は @ref{34a,,for} ループや @ref{1973,,while} ループ内のネストで構文法的にのみ現れますが、ループ内の関数定義やクラス定義の中には現れません。 @ref{180,,continue} 文は、文を囲う最も内側のループの次の周期に処理を継続します。

@ref{180,,continue} が @ref{1b0,,finally} 句を持った @ref{8f8,,try} 文を抜けるとき、その @code{finally} 句が次のループサイクルを始める前に実行されます。
@anchor{reference/simple_stmts import}@anchor{7f8}
@node import 文,global 文,continue 文,単純文 simple statement
@anchor{reference/simple_stmts from}@anchor{14c3}@anchor{reference/simple_stmts the-import-statement}@anchor{2517}
@subsection @code{import} 文


@geindex statement;import
@geindex module;importing
@geindex name;束縛
@geindex キーワード;from
@geindex キーワード;as
@geindex 例外;ImportError
@geindex @comma{} (comma);import statement

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-import_stmt}@anchor{24fd}import_stmt:     "import" @ref{2518,,module} ["as" @ref{22c1,,identifier}] ("," @ref{2518,,module} ["as" @ref{22c1,,identifier}])*
                 | "from" @ref{2519,,relative_module} "import" @ref{22c1,,identifier} ["as" @ref{22c1,,identifier}]
                 ("," @ref{22c1,,identifier} ["as" @ref{22c1,,identifier}])*
                 | "from" @ref{2519,,relative_module} "import" "(" @ref{22c1,,identifier} ["as" @ref{22c1,,identifier}]
                 ("," @ref{22c1,,identifier} ["as" @ref{22c1,,identifier}])* [","] ")"
                 | "from" @ref{2519,,relative_module} "import" "*"
@anchor{reference/simple_stmts grammar-token-python-grammar-module}@anchor{2518}module:          (@ref{22c1,,identifier} ".")* @ref{22c1,,identifier}
@anchor{reference/simple_stmts grammar-token-python-grammar-relative_module}@anchor{2519}relative_module: "."* @ref{2518,,module} | "."+
@end example

(@ref{14c3,,from} 節が無い) 基本の import 文は 2 つのステップで実行されます:


@enumerate 

@item 
モジュールを見付け出し、必要であればロードし初期化する

@item 
@ref{7f8,,import} 文が表れるスコープのローカル名前空間で名前を定義する。
@end enumerate

文が (カンマで区切られた) 複数の節を含んでいるときは、ちょうどその節が個別の import 文に分割されたかのように、2つのステップが節ごとに個別に実行されます。

モジュールを見付け、ロードする 1 つ目のステップの詳細については、 @ref{2360,,インポートシステム} の節により詳しく書かれています。そこでは、インポートシステムの動作をカスタマイズするのに使える全てのフックの仕組みだけでなく、様々な種類のインポートできるパッケージとモジュールについても解説されています。このステップが失敗するということは、おそらくモジュールが見付からないか、 `あるいは' モジュールにあるコードの実行を含め、モジュールの初期化の途中でエラーが起きるかのどちらかが起きていることに注意してください。

要求したモジュールが無事に取得できた場合、次の 3 つのうちの 1 つの方法でローカル名前空間で使えるようになります:

@geindex as;import statement


@itemize *

@item 
モジュール名の後に @code{as} が続いていた場合は、 @code{as} の後ろの名前を直接、インポートされたモジュールが束縛します。

@item 
他の名前が指定されておらず、インポートされているモジュールが最上位のモジュールだった場合、そのモジュール名がインポートされたモジュールへの参照として、ローカル名前空間で束縛されます

@item 
インポートされているモジュールが最上位のモジュール `でない' 場合、モジュールを含む最上位のパッケージ名が、そのパッケージへの参照として、ローカル名前空間で束縛されます。インポートされたモジュールには、直接ではなく完全修飾名を使ってアクセスしなければなりません
@end itemize

@geindex name;束縛
@geindex from;import statement

@ref{14c3,,from} 形式ではもう少し複雑な手順を踏みます:


@enumerate 

@item 
@ref{14c3,,from} 節で指定されたモジュールを見付け出し、必要であればロードし初期化する;

@item 
@ref{7f8,,import} 節で指定されたそれぞれの識別子に対し以下の処理を行う:


@enumerate 

@item 
インポートされたモジュールがその識別子名の属性を持っているかを確認する

@item 
その識別子名の属性を持っていなかった場合は、その識別子名でサブモジュールのインポートを試み、インポートされたモジュールにその属性があるか再度確認する

@item 
属性が見付からない場合は、 @ref{65b,,ImportError} を送出する。

@item 
属性が見付かった場合は、 @code{as} 節があるならそこの名前、そうでないなら属性名を使って、その値への参照がローカル名前空間に保存される
@end enumerate
@end enumerate

例:

@example
import foo                 # foo imported and bound locally
import foo.bar.baz         # foo, foo.bar, and foo.bar.baz imported, foo bound locally
import foo.bar.baz as fbb  # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb
from foo.bar import baz    # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz
from foo import attr       # foo imported and foo.attr bound as attr
@end example

@geindex * (アスタリスク);import statement

識別子のリストが星 (@code{'*'}) に置き換わっている場合は、モジュールで定義されている公開された全ての名前が、 @ref{7f8,,import} 文がいるスコープのローカル名前空間に束縛されます。

@geindex __all__ (オプションの module 属性)

@geindex __all__ (module の属性)
@anchor{reference/simple_stmts module __all__}@anchor{f3b}
The `public names' defined by a module are determined by checking the module's
namespace for a variable named @code{__all__}; if defined, it must be a sequence
of strings which are names defined or imported by that module.
Names containing non-ASCII characters must be in the normalization form@footnote{https://www.unicode.org/reports/tr15/#Norm_Forms}
NFKC; see @ref{22bd,,Non-ASCII characters in names} for details.  The names
given in @code{__all__} are all considered public and are required to exist.  If
@code{__all__} is not defined, the set of public names includes all names found
in the module's namespace which do not begin with an underscore character
(@code{'_'}).  @code{__all__} should contain the entire public API. It is intended
to avoid accidentally exporting items that are not part of the API (such as
library modules which were imported and used within the module).

インポートのワイルドカード形式 --- @code{from module import *} --- は、モジュールレベルでのみ許されます。クラスや関数定義でこの形式を使おうとすると、 @ref{18e,,SyntaxError} が送出されます。

@geindex relative;import

インポートするモジュールを指定するとき、そのモジュールの絶対名 (absolute name) を指定する必要はありません。モジュールやパッケージが他のパッケージに含まれている場合、共通のトップパッケージからそのパッケージ名を記述することなく相対インポートすることができます。 @ref{14c3,,from} の後に指定されるモジュールやパッケージの先頭に複数個のドットを付けることで、正確な名前を指定することなしに現在のパッケージ階層からいくつ上の階層へ行くかを指定することができます。先頭のドットが 1 つの場合、 import をおこなっているモジュールが存在する現在のパッケージを示します。 3 つのドットは 2 つ上のレベルを示します。なので、 @code{pkg} パッケージの中のモジュールで @code{from . import mod} を実行すると、 @code{pkg.mod} をインポートすることになります。 @code{pkg.subpkg1} の中から @code{from ..subpkg2 import mod} を実行すると、 @code{pkg.subpkg2.mod} をインポートします。相対インポートの仕様は @ref{245e,,Package Relative Imports} の節に含まれています。

どのモジュールがロードされるべきかを動的に決めたいアプリケーションのために、組み込み関数 @ref{73c,,importlib.import_module()} が提供されています。

Raises an @ref{1c6e,,auditing event} @code{import} with arguments @code{module}, @code{filename}, @code{sys.path}, @code{sys.meta_path}, @code{sys.path_hooks}.

@menu
* future 文 (future statement): future 文 future statement. 

@end menu

@node future 文 future statement,,,import 文
@anchor{reference/simple_stmts future}@anchor{45d}@anchor{reference/simple_stmts future-statements}@anchor{251a}
@subsubsection future 文 (future statement)


@geindex future;statement
@geindex __future__;future statement

`future 文' は、将来の特定の新たな機能が標準化された Python のリリースで利用可能になるような構文や意味付けを使って、特定のモジュールをコンパイルさせるための、コンパイラに対する指示句 (directive) です。

future 文は互換性のない変更がされた将来の Python のバージョンに容易に移行するためのものです。future 文によって新機能が標準となるリリースの前にそれをモジュール単位で使用することが出来ます。

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-future_stmt}@anchor{24fe}future_stmt: "from" "__future__" "import" @ref{251b,,feature} ["as" @ref{22c1,,identifier}]
             ("," @ref{251b,,feature} ["as" @ref{22c1,,identifier}])*
             | "from" "__future__" "import" "(" @ref{251b,,feature} ["as" @ref{22c1,,identifier}]
             ("," @ref{251b,,feature} ["as" @ref{22c1,,identifier}])* [","] ")"
@anchor{reference/simple_stmts grammar-token-python-grammar-feature}@anchor{251b}feature:     @ref{22c1,,identifier}
@end example

future 文は、モジュールの先頭周辺に書かなければなりません。 future 文の前に書いてよい内容は以下です :


@itemize *

@item 
モジュールのドキュメンテーション文字列 ( あれば )

@item 
コメント ,

@item 
空行 ,

@item 
その他の future 文。
@end itemize

future 文を使う必要がある唯一の機能は @code{annotations} です (
@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/} を参照してください)。

future 文で有効にできる歴史的な機能は、今でも Python 3 が認識します。
そのリストは @code{absolute_import}, @code{division}, @code{generator_stop}, @code{generators}, @code{unicode_literals}, @code{print_function}, @code{nested_scopes}, @code{with_statement} です。
これらは既に全てが有効になっていて、後方互換性のためだけに残されているため、冗長なだけです。

future 文は、コンパイル時に特別なやり方で認識され、扱われます: 言語の中核をなす構文構成 (construct) に対する意味付けが変更されている場合、変更部分はしばしば異なるコードを生成することで実現されています。新たな機能によって、(新たな予約語のような) 互換性のない新たな構文が取り入れられることさえあります。この場合、コンパイラはモジュールを別のやりかたで解析する必要があるかもしれません。こうしたコード生成に関する決定は、実行時まで先延ばしすることはできません。

これまでの全てのリリースにおいて、コンパイラはどの機能が定義済みかを知っており、 future 文に未知の機能が含まれている場合にはコンパイル時エラーを送出します。

future 文の実行時における直接的な意味付けは、 import 文と同じです。標準モジュール @ref{0,,__future__} があり、これについては後で述べます。 @ref{0,,__future__} は、 future 文が実行される際に通常の方法で import されます。

future 文の実行時における特別な意味付けは、 future 文で有効化される特定の機能によって変わります。

以下の文には、何ら特殊な意味はないので注意してください:

@example
import __future__ [as name]
@end example

これは future 文ではありません; この文は通常の import 文であり、その他の特殊な意味付けや構文的な制限はありません。

Code compiled by calls to the built-in functions @ref{4a2,,exec()} and @ref{4b1,,compile()}
that occur in a module @code{M} containing a future statement will, by default,
use the new syntax or semantics associated with the future statement.  This can
be controlled by optional arguments to @ref{4b1,,compile()} --- see the documentation
of that function for details.

対話的インタプリタのプロンプトでタイプ入力した future 文は、その後のインタプリタセッション中で有効になります。インタプリタを @ref{16f4,,-i} オプションで起動して実行すべきスクリプト名を渡し、スクリプト中に future 文を入れておくと、新たな機能はスクリプトが実行された後に開始する対話セッションで有効になります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 236

@item PEP 236@footnote{https://peps.python.org/pep-0236/} - Back to the __future__

__future__ 機構の原案
@end table


@node global 文,nonlocal 文,import 文,単純文 simple statement
@anchor{reference/simple_stmts global}@anchor{4ac}@anchor{reference/simple_stmts the-global-statement}@anchor{251c}
@subsection @code{global} 文


@geindex statement;グローバル
@geindex グローバル;name;束縛
@geindex @comma{} (comma);identifier list

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-global_stmt}@anchor{24ff}global_stmt: "global" @ref{22c1,,identifier} ("," @ref{22c1,,identifier})*
@end example

The @ref{4ac,,global} statement causes the listed identifiers to be interpreted
as globals. It would be impossible to assign to a global variable without
@code{global}, although free variables may refer to globals without being
declared global.

The @code{global} statement applies to the entire current scope
(module, function body or class definition).
A @ref{18e,,SyntaxError} is raised if a variable is used or
assigned to prior to its global declaration in the scope.

At the module level, all variables are global, so a @code{global}
statement has no effect.
However, variables must still not be used or
assigned to prior to their @code{global} declaration.
This requirement is relaxed in the interactive prompt (@ref{491,,REPL}).

@geindex 組み込み関数;exec
@geindex 組み込み関数;eval
@geindex 組み込み関数;コンパイル

`プログラマのための注意点:' @ref{4ac,,global} はパーザに対する指示句 (directive) です。この指示句は、 @code{global} 文と同時に読み込まれたコードに対してのみ適用されます。特に、組み込みの @ref{4a2,,exec()} 関数内に入っている @code{global} 文は、関数の呼び出しを `含んでいる' コードブロック内に効果を及ぼすことはなく、そのような文字列に含まれているコードは、関数の呼び出しを含むコード内の @code{global} 文に影響を受けません。同様のことが、関数 @ref{4a3,,eval()} および @ref{4b1,,compile()} にも当てはまります。

@node nonlocal 文,The type statement,global 文,単純文 simple statement
@anchor{reference/simple_stmts nonlocal}@anchor{14bf}@anchor{reference/simple_stmts the-nonlocal-statement}@anchor{251d}
@subsection @code{nonlocal} 文


@geindex statement;nonlocal
@geindex @comma{} (comma);identifier list

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-nonlocal_stmt}@anchor{2500}nonlocal_stmt: "nonlocal" @ref{22c1,,identifier} ("," @ref{22c1,,identifier})*
@end example

When the definition of a function or class is nested (enclosed) within
the definitions of other functions, its nonlocal scopes are the local
scopes of the enclosing functions. The @ref{14bf,,nonlocal} statement
causes the listed identifiers to refer to names previously bound in
nonlocal scopes. It allows encapsulated code to rebind such nonlocal
identifiers.  If a name is bound in more than one nonlocal scope, the
nearest binding is used. If a name is not bound in any nonlocal scope,
or if there is no nonlocal scope, a @ref{18e,,SyntaxError} is raised.

The @ref{14bf,,nonlocal} statement applies to the entire scope of a function or
class body. A @ref{18e,,SyntaxError} is raised if a variable is used or
assigned to prior to its nonlocal declaration in the scope.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3104

@item PEP 3104@footnote{https://peps.python.org/pep-3104/} - Access to Names in Outer Scopes

@ref{14bf,,nonlocal} 文の詳細。
@end table


`Programmer's note:' @ref{14bf,,nonlocal} is a directive to the parser
and applies only to code parsed along with it.  See the note for the
@ref{4ac,,global} statement.

@node The type statement,,nonlocal 文,単純文 simple statement
@anchor{reference/simple_stmts the-type-statement}@anchor{251e}@anchor{reference/simple_stmts type}@anchor{66d}
@subsection The @code{type} statement


@geindex statement;type

@example
@anchor{reference/simple_stmts grammar-token-python-grammar-type_stmt}@anchor{2501}type_stmt: 'type' @ref{22c1,,identifier} [@ref{251f,,type_params}] "=" @ref{182,,expression}
@end example

The @code{type} statement declares a type alias, which is an instance
of @ref{2ae,,typing.TypeAliasType}.

For example, the following statement creates a type alias:

@example
type Point = tuple[float, float]
@end example

This code is roughly equivalent to:

@example
annotation-def VALUE_OF_Point():
    return tuple[float, float]
Point = typing.TypeAliasType("Point", VALUE_OF_Point())
@end example

@code{annotation-def} indicates an @ref{4ab,,annotation scope}, which behaves
mostly like a function, but with several small differences.

The value of the
type alias is evaluated in the annotation scope. It is not evaluated when the
type alias is created, but only when the value is accessed through the type alias's
@code{__value__} attribute (see @ref{685,,Lazy evaluation}).
This allows the type alias to refer to names that are not yet defined.

Type aliases may be made generic by adding a @ref{5ad,,type parameter list}
after the name. See @ref{684,,Generic type aliases} for more.

@code{type} is a @ref{a0d,,soft keyword}.


Added in version 3.12.



@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 695

@item PEP 695@footnote{https://peps.python.org/pep-0695/} - Type Parameter Syntax

Introduced the @code{type} statement and syntax for
generic classes and functions.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 複合文 compound statement,トップレベル要素,単純文 simple statement,Python 言語リファレンス
@anchor{reference/compound_stmts doc}@anchor{2520}@anchor{reference/compound_stmts compound}@anchor{2521}@anchor{reference/compound_stmts compound-statements}@anchor{2522}@anchor{reference/compound_stmts translation-repo}@anchor{2523}
@section 複合文 (compound statement)


@geindex compound;statement

複合文には、他の文 (のグループ) が入ります; 複合文は、中に入っている他の文の実行の制御に何らかのやり方で影響を及ぼします。一般的には、複合文は複数行にまたがって書かれますが、全部の文を一行に連ねた単純な書き方もあります。

@ref{181,,if} 、 @ref{1973,,while} 、および @ref{34a,,for} 文は、伝統的な制御フロー構成を実現します。 @ref{8f8,,try} は例外処理および/または一連の文に対するクリーンアップコードを指定します。それに対して、 @ref{186,,with} 文はコードのかたまりの前後でコードの初期化と終了処理を実行できるようにします。関数とクラス定義もまた、構文的には複合文です。

@geindex clause
@geindex suite
@geindex ; (semicolon)

複合文は、一つ以上の '節 (clause)' からなります。節は、ヘッダと 'スイート (suite)' からなります。一つの複合文を成す各節のヘッダは、全て同じインデントレベルに置かれます。各節のヘッダは一意に識別するキーワードで始まり、コロンで終わります。スイートは、節によって制御される文の集まりです。スイートは、ヘッダがある行のコロンの後にセミコロンで区切って置かれた一つ以上の単純文、または、ヘッダに続く行で一つ多くインデントされた文の集まりです。後者の形式のスイートに限り、さらに複合文をネストできます; 以下の文は、 @ref{17c,,else} 節がどちらの @ref{181,,if} 節に属するかがはっきりしないなどの理由から不正になります:

@example
if test1: if test2: print(x)
@end example

また、このコンテキスト中では、セミコロンによる結合はコロンより強いです。従って、以下の例では、 @ref{1177,,print()} の呼び出しはは全て実行されるか、全く実行されないかのどちらかです:

@example
if x < y < z: print(x); print(y); print(z)
@end example

まとめると、以下のようになります:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-compound_stmt}@anchor{2524}compound_stmt: @ref{2525,,if_stmt}
               | @ref{2526,,while_stmt}
               | @ref{2527,,for_stmt}
               | @ref{2528,,try_stmt}
               | @ref{2529,,with_stmt}
               | @ref{252a,,match_stmt}
               | @ref{252b,,funcdef}
               | @ref{252c,,classdef}
               | @ref{252d,,async_with_stmt}
               | @ref{252e,,async_for_stmt}
               | @ref{252f,,async_funcdef}
@anchor{reference/compound_stmts grammar-token-python-grammar-suite}@anchor{2530}suite:         @ref{2531,,stmt_list} NEWLINE | NEWLINE INDENT @ref{2532,,statement}+ DEDENT
@anchor{reference/compound_stmts grammar-token-python-grammar-statement}@anchor{2532}statement:     @ref{2531,,stmt_list} NEWLINE | @ref{2524,,compound_stmt}
@anchor{reference/compound_stmts grammar-token-python-grammar-stmt_list}@anchor{2531}stmt_list:     @ref{24f0,,simple_stmt} (";" @ref{24f0,,simple_stmt})* [";"]
@end example

@geindex NEWLINE トークン
@geindex DEDENT トークン
@geindex dangling;else

なお、文は常に @code{NEWLINE} か、その後に @code{DEDENT} が続いたもので終了します。また、オプションの継続節は必ず、文を開始できない予約語で始まるので、曖昧さは存在しません。 (Python では、 'ぶら下がり (dangling) @ref{17c,,else}' 問題は、ネストされた @ref{181,,if} 文をインデントさせることで解決されます)。

以下の節における文法規則の記述方式は、明確さのために、各節を別々の行に書くようにしています。
@anchor{reference/compound_stmts if}@anchor{181}@anchor{reference/compound_stmts elif}@anchor{17b}
@menu
* if 文: if 文<2>. 
* while 文:: 
* for 文: for 文<2>. 
* try 文:: 
* with 文:: 
* match 文: match 文<2>. 
* 関数定義:: 
* クラス定義:: 
* コルーチン: コルーチン<2>. 
* Type parameter lists:: 
* Annotations: Annotations<2>. 

@end menu

@node if 文<2>,while 文,,複合文 compound statement
@anchor{reference/compound_stmts else}@anchor{17c}@anchor{reference/compound_stmts the-if-statement}@anchor{2533}
@subsection @code{if} 文


@geindex statement;if
@geindex キーワード;elif
@geindex キーワード;else
@geindex ; (コロン);compound statement

@ref{181,,if} 文は、条件分岐を実行するために使われます:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-if_stmt}@anchor{2525}if_stmt: "if" @ref{242d,,assignment_expression} ":" @ref{2530,,suite}
         ("elif" @ref{242d,,assignment_expression} ":" @ref{2530,,suite})*
         ["else" ":" @ref{2530,,suite}]
@end example

@ref{181,,if} 文は、式を一つ一つ評価してゆき、真になるまで続けて、真になった節のスイートだけを選択します (真: true と偽: false の定義については、 @ref{24d8,,ブール演算 (boolean operation)} 節を参照してください); 次に、選択したスイートを実行します (そして、 @ref{181,,if} 文の他の部分は、実行や評価をされません)。全ての式が偽になった場合、 @ref{17c,,else} 節があれば、そのスイートが実行されます。

@node while 文,for 文<2>,if 文<2>,複合文 compound statement
@anchor{reference/compound_stmts the-while-statement}@anchor{2534}@anchor{reference/compound_stmts while}@anchor{1973}
@subsection @code{while} 文


@geindex statement;while
@geindex キーワード;else
@geindex loop;statement
@geindex ; (コロン);compound statement

@ref{1973,,while} 文は、式の値が真である間、実行を繰り返すために使われます:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-while_stmt}@anchor{2526}while_stmt: "while" @ref{242d,,assignment_expression} ":" @ref{2530,,suite}
            ["else" ":" @ref{2530,,suite}]
@end example

@ref{1973,,while} 文は式を繰り返し真偽評価し、真であれば最初のスイートを実行します。式が偽であれば (最初から偽になっていることもありえます)、 @code{else} 節がある場合にはそれを実行し、ループを終了します。

@geindex statement;break
@geindex statement;continue

最初のスイート内で @ref{17f,,break} 文が実行されると、 @code{else} 節のスイートを実行することなくループを終了します。 @ref{180,,continue} 文が最初のスイート内で実行されると、スイート内にある残りの文の実行をスキップして、式の真偽評価に戻ります。

@node for 文<2>,try 文,while 文,複合文 compound statement
@anchor{reference/compound_stmts for}@anchor{34a}@anchor{reference/compound_stmts the-for-statement}@anchor{2535}
@subsection @code{for} 文


@geindex statement;for
@geindex キーワード;in
@geindex キーワード;else
@geindex target;list
@geindex loop;statement
@geindex object;sequence
@geindex ; (コロン);compound statement

@ref{34a,,for} 文は、シーケンス (文字列、タプルまたはリスト) や、その他の反復可能なオブジェクト (iterable object) 内の要素に渡って反復処理を行うために使われます:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-for_stmt}@anchor{2527}for_stmt: "for" @ref{2488,,target_list} "in" @ref{24e6,,starred_expression_list} ":" @ref{2530,,suite}
          ["else" ":" @ref{2530,,suite}]
@end example

The @ref{24e6,,starred_expression_list} expression is evaluated
once; it should yield an @ref{12f1,,iterable} object. An @ref{4c8,,iterator} is
created for that iterable. The first item provided by the iterator is then
assigned to the target list using the standard rules for assignments
(see @ref{2427,,代入文 (assignment statement)}), and the suite is executed. This repeats for each
item provided by the iterator. When the iterator is exhausted,
the suite in the @code{else} clause,
if present, is executed, and the loop terminates.

@geindex statement;break
@geindex statement;continue

最初のスイートの中で @ref{17f,,break} 文が実行されると、 @code{else} 節のスイートを実行することなくループを終了します。
@ref{180,,continue} 文が最初のスイート内で実行されると、スイート内にある残りの文の実行をスキップして、次の要素の処理に移るか、これ以上次の要素が無い場合は @code{else} 節の処理に移ります。

for ループはターゲットリスト内の変数への代入を行います。
これにより、for ループ内も含めて、それ以前の全ての代入は上書きされます:

@example
for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range
@end example

@geindex 組み込み関数;range

ループが終了してもターゲットリスト内の名前は削除されませんが、イテラブルが空の場合には、ループでの代入は全く行われません。ヒント: 組み込み型 @ref{b3d,,range()} は、 整数の不変算術列を表します。例えば、 @code{range(3)} を反復すると0、1そして2の順に結果を返します。


バージョン 3.11 で変更: 式のリストの中でアスタリスク付きの式 (starred elements) を指定できるようになりました。


@node try 文,with 文,for 文<2>,複合文 compound statement
@anchor{reference/compound_stmts the-try-statement}@anchor{2536}@anchor{reference/compound_stmts try}@anchor{8f8}
@subsection @code{try} 文


@geindex statement;try
@geindex キーワード;except
@geindex キーワード;finally
@geindex キーワード;else
@geindex キーワード;as
@geindex ; (コロン);compound statement

@code{try} 文は、ひとまとめの文に対して、例外処理および/またはクリーンアップコードを指定します:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-try_stmt}@anchor{2528}try_stmt:  @ref{2537,,try1_stmt} | @ref{2538,,try2_stmt} | @ref{2539,,try3_stmt}
@anchor{reference/compound_stmts grammar-token-python-grammar-try1_stmt}@anchor{2537}try1_stmt: "try" ":" @ref{2530,,suite}
           ("except" [@ref{182,,expression} ["as" @ref{22c1,,identifier}]] ":" @ref{2530,,suite})+
           ["else" ":" @ref{2530,,suite}]
           ["finally" ":" @ref{2530,,suite}]
@anchor{reference/compound_stmts grammar-token-python-grammar-try2_stmt}@anchor{2538}try2_stmt: "try" ":" @ref{2530,,suite}
           ("except" "*" @ref{182,,expression} ["as" @ref{22c1,,identifier}] ":" @ref{2530,,suite})+
           ["else" ":" @ref{2530,,suite}]
           ["finally" ":" @ref{2530,,suite}]
@anchor{reference/compound_stmts grammar-token-python-grammar-try3_stmt}@anchor{2539}try3_stmt: "try" ":" @ref{2530,,suite}
           "finally" ":" @ref{2530,,suite}
@end example

例外に関するその他の情報は @ref{2433,,例外} 節にあります。また、 @ref{803,,raise} 文の使用による例外の生成に関する情報は、 @ref{803,,raise 文} 節にあります。


バージョン 3.14 で変更: Support for optionally dropping grouping parentheses when using multiple exception types. See 
@geindex Python Enhancement Proposals; PEP 758
PEP 758@footnote{https://peps.python.org/pep-0758/}.


@menu
* except 節:: 
* except* 節:: 
* else 節:: 
* finally 節:: 

@end menu

@node except 節,except* 節,,try 文
@anchor{reference/compound_stmts except}@anchor{1ab}@anchor{reference/compound_stmts except-clause}@anchor{253a}
@subsubsection @code{except} 節


The @code{except} clause(s) specify one or more exception handlers. When no
exception occurs in the @ref{8f8,,try} clause, no exception handler is executed.
When an exception occurs in the @code{try} suite, a search for an exception
handler is started. This search inspects the @code{except} clauses in turn
until one is found that matches the exception.
An expression-less @code{except} clause, if present, must be last;
it matches any exception.

For an @code{except} clause with an expression, the
expression must evaluate to an exception type or a tuple of exception types. Parentheses
can be dropped if multiple exception types are provided and the @code{as} clause is not used.
The raised exception matches an @code{except} clause whose expression evaluates
to the class or a @ref{13ce,,non-virtual base class} of the exception object,
or to a tuple that contains such a class.

例外がどの @code{except} 節にも合致しなかった場合、現在のコードを囲うさらに外側、そして呼び出しスタックへと検索を続けます。 @footnote{
例外は、別の例外を送出するような @ref{1b0,,finally} 節が無い場合にのみ呼び出しスタックへ伝わります。新しい例外によって、古い例外は失われます。
}

@code{except} 節のヘッダにある式を値評価するときに例外が発生すると、元々のハンドラ検索はキャンセルされ、新たな例外に対する例外ハンドラの検索を現在の @ref{1ab,,except} 節の外側のコードや呼び出しスタックに対して行います (@ref{8f8,,try} 文全体が例外を発行したかのように扱われます)。

@geindex as;except clause

対応する @code{except} 節が見つかると、@code{except} 節のスイートが実行されます。その際、 @code{as} キーワードが @code{except} 節に存在すれば、その後で指定されているターゲットに例外が代入されます。全ての @code{except} 節は実行可能なブロックを持っていなければなりません。このブロックの末尾に到達すると、通常は @ref{8f8,,try} 文全体の直後から実行を継続します。(このことは、ネストされた二つの例外ハンドラが同じ例外に対して存在し、内側のハンドラ内の @code{try} 節で例外が発生した場合、外側のハンドラはその例外を処理しないことを意味します。)

例外が @code{as target} を使って代入されたとき、それは @code{except} 節の終わりに消去されます。これはちょうど、以下のコード:

@example
except E as N:
    foo
@end example

が、以下のコードに翻訳されたかのようなものです:

@example
except E as N:
    try:
        foo
    finally:
        del N
@end example

よって、例外を @code{except} 節以降で参照できるようにするためには、別の名前に代入されなければなりません。例外が削除されるのは、トレースバックが付与されると、そのスタックフレームと循環参照を形作り、次のガベージ収集までそのフレーム内のすべての局所変数を生存させてしまうからです。

@geindex module;sys
@geindex object;traceback

@code{except} 節のスイートが実行される前に、例外が @ref{df,,sys} モジュールに格納されます。
@code{except} 節の中では、 @ref{89b,,sys.exception()} を呼び出す事によってこの例外にアクセスすることができます。
例外ハンドラを抜けると、 @ref{df,,sys} モジュールに格納されている例外の値が、一つ前の値に戻ります:

@example
>>> print(sys.exception())
None
>>> try:
...     raise TypeError
... except:
...     print(repr(sys.exception()))
...     try:
...          raise ValueError
...     except:
...         print(repr(sys.exception()))
...     print(repr(sys.exception()))
...
TypeError()
ValueError()
TypeError()
>>> print(sys.exception())
None
@end example

@geindex キーワード;except_star

@node except* 節,else 節,except 節,try 文
@anchor{reference/compound_stmts except-star}@anchor{1ac}@anchor{reference/compound_stmts id2}@anchor{253b}
@subsubsection @code{except*} 節


The @code{except*} clause(s) specify one or more handlers for groups of
exceptions (@ref{566,,BaseExceptionGroup} instances). A @ref{8f8,,try} statement
can have either @ref{1ab,,except} or @code{except*} clauses, but not both.
The exception type for matching is mandatory in the case of @code{except*},
so @code{except*:} is a syntax error. The type is interpreted as in the case of
@code{except}, but matching is performed on the exceptions contained in the
group that is being handled. An @ref{198,,TypeError} is raised if a matching
type is a subclass of @code{BaseExceptionGroup}, because that would have
ambiguous semantics.

When an exception group is raised in the try block, each @code{except*}
clause splits (see @ref{18d8,,split()}) it into the subgroups
of matching and non-matching exceptions. If the matching subgroup is not empty,
it becomes the handled exception (the value returned from @ref{89b,,sys.exception()})
and assigned to the target of the @code{except*} clause (if there is one).
Then, the body of the @code{except*} clause executes. If the non-matching
subgroup is not empty, it is processed by the next @code{except*} in the
same manner. This continues until all exceptions in the group have been matched,
or the last @code{except*} clause has run.

After all @code{except*} clauses execute, the group of unhandled exceptions
is merged with any exceptions that were raised or re-raised from within
@code{except*} clauses. This merged exception group propagates on.:

@example
>>> try:
...     raise ExceptionGroup("eg",
...         [ValueError(1), TypeError(2), OSError(3), OSError(4)])
... except* TypeError as e:
...     print(f'caught @{type(e)@} with nested @{e.exceptions@}')
... except* OSError as e:
...     print(f'caught @{type(e)@} with nested @{e.exceptions@}')
...
caught <class 'ExceptionGroup'> with nested (TypeError(2),)
caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
  + Exception Group Traceback (most recent call last):
  |   File "<doctest default[0]>", line 2, in <module>
  |     raise ExceptionGroup("eg",
  |         [ValueError(1), TypeError(2), OSError(3), OSError(4)])
  | ExceptionGroup: eg (1 sub-exception)
  +-+---------------- 1 ----------------
    | ValueError: 1
    +------------------------------------
@end example

If the exception raised from the @ref{8f8,,try} block is not an exception group
and its type matches one of the @code{except*} clauses, it is caught and
wrapped by an exception group with an empty message string. This ensures that the
type of the target @code{e} is consistently @ref{566,,BaseExceptionGroup}:

@example
>>> try:
...     raise BlockingIOError
... except* BlockingIOError as e:
...     print(repr(e))
...
ExceptionGroup('@w{'}, (BlockingIOError(),))
@end example

@ref{17f,,break}, @ref{180,,continue} and @ref{1af,,return}
cannot appear in an @code{except*} clause.

@geindex キーワード;else
@geindex statement;return
@geindex statement;break
@geindex statement;continue

@node else 節,finally 節,except* 節,try 文
@anchor{reference/compound_stmts else-clause}@anchor{253c}@anchor{reference/compound_stmts except-else}@anchor{253d}
@subsubsection @code{else} 節


オプションの @code{else} 節は、コントロールフローが @ref{8f8,,try} スイートを抜け、例外が送出されず、 @ref{1af,,return} 文、 @ref{180,,continue} 文、 @ref{17f,,break} 文のいずれもが実行されなかった場合に実行されます。
@code{else} 節で起きた例外は、手前にある @ref{1ab,,except} 節では処理されません。

@geindex キーワード;finally

@node finally 節,,else 節,try 文
@anchor{reference/compound_stmts finally}@anchor{1b0}@anchor{reference/compound_stmts finally-clause}@anchor{253e}
@subsubsection @code{finally} 節


If @code{finally} is present, it specifies a 'cleanup' handler.  The
@ref{8f8,,try} clause is executed, including any @ref{1ab,,except}
and @ref{253d,,else} clauses.
If an exception occurs in any of the clauses and is not handled,
the exception is temporarily saved.
The @code{finally} clause is executed.  If there is a saved exception
it is re-raised at the end of the @code{finally} clause.
If the @code{finally} clause raises another exception, the saved exception
is set as the context of the new exception.
If the @code{finally} clause executes a @ref{1af,,return}, @ref{17f,,break}
or @ref{180,,continue} statement, the saved exception is discarded. For example,
this function returns 42.

@example
def f():
    try:
        1/0
    finally:
        return 42
@end example

@code{finally} 節を実行している間は、プログラムからは例外情報は利用できません。

@geindex statement;return
@geindex statement;break
@geindex statement;continue

@ref{8f8,,try}...@code{finally} 文の @ref{8f8,,try} スイート内で @ref{1af,,return} 、 @ref{17f,,break} 、または @ref{180,,continue} 文が実行された場合、 @code{finally} 節も、この文を '抜け出る途中に' 実行されます。

The return value of a function is determined by the last @ref{1af,,return}
statement executed.  Since the @code{finally} clause always executes, a
@code{return} statement executed in the @code{finally} clause will
always be the last one executed. The following function returns 'finally'.

@example
def foo():
    try:
        return 'try'
    finally:
        return 'finally'
@end example


バージョン 3.8 で変更: Python3.8 以前では、実装上の問題により @code{finally} 節での @ref{180,,continue} 文は不正でした。



バージョン 3.14 で変更: The compiler emits a @ref{1ae,,SyntaxWarning} when a @ref{1af,,return},
@ref{17f,,break} or @ref{180,,continue} appears in a @code{finally}
block (see 
@geindex Python Enhancement Proposals; PEP 765
PEP 765@footnote{https://peps.python.org/pep-0765/}).

@anchor{reference/compound_stmts with}@anchor{186}
@node with 文,match 文<2>,try 文,複合文 compound statement
@anchor{reference/compound_stmts as}@anchor{253f}@anchor{reference/compound_stmts the-with-statement}@anchor{2540}
@subsection @code{with} 文


@geindex statement;with
@geindex キーワード;as
@geindex as;with statement
@geindex @comma{} (comma);with statement
@geindex ; (コロン);compound statement

@ref{186,,with} 文は、ブロックの実行を、コンテキストマネージャによって定義されたメソッドでラップするために使われます (@ref{240b,,with文とコンテキストマネージャ} セクションを参照してください)。これにより、よくある @ref{8f8,,try}...@ref{1ab,,except}...@ref{1b0,,finally} 利用パターンをカプセル化して便利に再利用することができます。

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-with_stmt}@anchor{2529}with_stmt:          "with" ( "(" @ref{2541,,with_stmt_contents} ","? ")" | @ref{2541,,with_stmt_contents} ) ":" @ref{2530,,suite}
@anchor{reference/compound_stmts grammar-token-python-grammar-with_stmt_contents}@anchor{2541}with_stmt_contents: @ref{2542,,with_item} ("," @ref{2542,,with_item})*
@anchor{reference/compound_stmts grammar-token-python-grammar-with_item}@anchor{2542}with_item:          @ref{182,,expression} ["as" @ref{2505,,target}]
@end example

一つの "要素" を持つ @ref{186,,with} 文の実行は以下のように進行します:


@enumerate 

@item 
コンテキスト式 (@ref{2542,,with_item} で与えられた式) を評価することで、コンテキストマネージャを取得します。

@item 
コンテキストマネージャの @ref{7e4,,__enter__()} メソッドが、後で使うためにロードされます。

@item 
コンテキストマネージャの @ref{1518,,__exit__()} メソッドが、後で使うためにロードされます。

@item 
コンテキストマネージャの @ref{7e4,,__enter__()} メソッドが呼ばれます。

@item 
@ref{186,,with} 文にターゲットが含まれていたら、それに @ref{7e4,,__enter__()} からの戻り値が代入されます。

@cartouche
@quotation 注釈 
@ref{186,,with} 文は、 @ref{7e4,,__enter__()} メソッドがエラーなく終了した場合には @ref{1518,,__exit__()} が常に呼ばれることを保証します。ですので、もしターゲットリストへの代入中にエラーが発生した場合には、これはそのスイートの中で発生したエラーと同じように扱われます。以下のステップ 7 を参照してください。
@end quotation
@end cartouche

@item 
スイートが実行されます。

@item 
コンテキストマネージャの @ref{1518,,__exit__()} メソッドが呼ばれます。スイートが例外によって終了されたのなら、その例外の型、値、トレースバックが @ref{1518,,__exit__()} に引数として渡されます。そうでなければ、 3 つの @ref{885,,None} 引数が与えられます。

スイートが例外により終了され、 @ref{1518,,__exit__()} メソッドからの戻り値が偽（false）ならば、例外が再送出されます。この戻り値が真（true）ならば例外は抑制され、実行は @ref{186,,with} 文の次の文から続きます。

もしそのスイートが例外でない何らかの理由で終了した場合、その @ref{1518,,__exit__()} からの戻り値は無視されて、実行は発生した終了の種類に応じた通常の位置から継続します。
@end enumerate

以下のコード:

@example
with EXPRESSION as TARGET:
    SUITE
@end example

これは次と等価です:

@example
manager = (EXPRESSION)
enter = manager.__enter__
exit = manager.__exit__
value = enter()
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not exit(*sys.exc_info()):
        raise
finally:
    if not hit_except:
        exit(None, None, None)
@end example

except that implicit @ref{23b1,,special method lookup} is used
for @ref{7e4,,__enter__()} and @ref{1518,,__exit__()}.

複数の要素があるとき、コンテキストマネージャは複数の @ref{186,,with} 文がネストされたかのように進行します:

@example
with A() as a, B() as b:
    SUITE
@end example

これは次と等価です:

@example
with A() as a:
    with B() as b:
        SUITE
@end example

括弧で囲むことにより、複数のコンテキストマネージャを複数行に渡って書くことができます。
例:

@example
with (
    A() as a,
    B() as b,
):
    SUITE
@end example


バージョン 3.1 で変更: 複数のコンテキスト式をサポートしました。



バージョン 3.10 で変更: 括弧で囲むことで、文を複数行に分割して書けるようになりました。



@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 343

@item PEP 343@footnote{https://peps.python.org/pep-0343/} - "with" ステートメント

Python の @ref{186,,with} 文の仕様、背景、および例が記載されています。
@end table

@anchor{reference/compound_stmts match}@anchor{a0e}
@node match 文<2>,関数定義,with 文,複合文 compound statement
@anchor{reference/compound_stmts case}@anchor{2543}@anchor{reference/compound_stmts the-match-statement}@anchor{2544}
@subsection @code{match} 文


@geindex statement;match
@geindex キーワード;case
@geindex pattern matching
@geindex キーワード;if
@geindex キーワード;as
@geindex match;case
@geindex as;match statement
@geindex ; (コロン);compound statement


Added in version 3.10.


match 文はパターンマッチングを行う目的で使われます。
構文:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-match_stmt}@anchor{252a}match_stmt:   'match' @ref{2545,,subject_expr} ":" NEWLINE INDENT @ref{2546,,case_block}+ DEDENT
@anchor{reference/compound_stmts grammar-token-python-grammar-subject_expr}@anchor{2545}subject_expr: `!star_named_expression` "," `!star_named_expressions`?
              | `!named_expression`
@anchor{reference/compound_stmts grammar-token-python-grammar-case_block}@anchor{2546}case_block:   'case' @ref{2547,,patterns} [@ref{2548,,guard}] ":" `!block`
@end example

@cartouche
@quotation 注釈 
このセクションでは、一重引用符で囲まれているものは @ref{a0d,,ソフトキーワード} を表します。
@end quotation
@end cartouche

パターンマッチングは、パターン (@code{case} の後ろ) とマッチング対象の値 (@code{match} の後ろ)を入力とします。
パターン (サブパターンを含みうる) は、マッチング対象の値に対して、マッチするかどうかの判定が行われます。結果として次のことが起こります:


@itemize *

@item 
マッチ成功、もしくはマッチ失敗 (パターン成功・失敗とも呼ばれます)。

@item 
マッチした値の名前への束縛。必要な条件は後述します。
@end itemize

@code{match} と @code{case} キーワードは @ref{a0d,,ソフトキーワード} です。


@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/} -- 構造的パターンマッチ: 仕様

@item 
@geindex Python Enhancement Proposals; PEP 636
PEP 636@footnote{https://peps.python.org/pep-0636/} -- 構造的パターンマッチ: チュートリアル
@end itemize


@menu
* 概要:: 
* ガード: ガード<2>. 
* 論駁不可能なケースブロック:: 
* パターン:: 

@end menu

@node 概要,ガード<2>,,match 文<2>
@anchor{reference/compound_stmts overview}@anchor{2549}
@subsubsection 概要


match 文の論理的な動作の流れの概要は次の通りです:


@enumerate 

@item 
サブジェクト式 @code{subject_expr} が評価され、サブジェクト値が得られます。
サブジェクト式がコンマを含む場合、 @ref{254a,,通常のルール} に従ってタプルが作成されます。

@item 
@code{case_block} 内の各パターンに対して、サブジェクト値がマッチするかどうかをチェックします。
マッチ成功・失敗の具体的なルールは後述します。
マッチングのチェックにより、パターン内の名前の一部あるいはすべてに値が束縛されます。
具体的な束縛ルールはパターンの種類によって異なるため、後述します。
`マッチが成功したパターンの中で束縛された名前は、そのパターンのブロック内だけでなく、 match 文の後でも使用することができます'。

@cartouche
@quotation 注釈 
パターンマッチが全体として失敗しても、その中に含まれるサブパターンが成功する可能性があります。
失敗したマッチで発生する名前束縛を前提としたコードを書かないように気をつけてください。
逆に、マッチが失敗したあとで変数の値が変わっていないというのも前提にしないでください。
実際どういう振る舞いになるかは Python の実装依存であり、実装間で異なる可能性があります。
色々な実装が最適化を行えるよう、意図的に実装依存としています。
@end quotation
@end cartouche

@item 
パターンが成功した場合、該当のガードが (もしあれば) 評価されます。
この場合、パターン内の名前がすべて束縛されていることが保証されています。


@itemize *

@item 
ガードの評価値が真であるか、もしくはガードがなければ、 @code{case_block} 内の @code{block} が実行されます。

@item 
そうでなければ、次の @code{case_block} に対して再び上記の処理が実行されます。

@item 
これ以上 case block が存在しない場合は、 match 文が終了します。
@end itemize
@end enumerate

@cartouche
@quotation 注釈 
基本的に、 match 文のパターンが評価されるという前提でコードを書くべきではありません。
インタープリタの実装によっては、結果をキャッシュするなどの最適化を行い、評価をスキップする可能性があります。
@end quotation
@end cartouche

簡単な match 文の例:

@example
>>> flag = False
>>> match (100, 200):
...    case (100, 300):  # Mismatch: 200 != 300
...        print('Case 1')
...    case (100, 200) if flag:  # Successful match, but guard fails
...        print('Case 2')
...    case (100, y):  # Matches and binds y to 200
...        print(f'Case 3, y: @{y@}')
...    case _:  # Pattern not attempted
...        print('Case 4, I match anything!')
...
Case 3, y: 200
@end example

この例では、 @code{if flag} がガードです。
ガードについては次のセクションを参照してください。

@node ガード<2>,論駁不可能なケースブロック,概要,match 文<2>
@anchor{reference/compound_stmts guards}@anchor{254b}
@subsubsection ガード


@geindex guard

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-guard}@anchor{2548}guard: "if" `!named_expression`
@end example

@code{guard} (@code{case} 一部として現れる) が成功してはじめて、その @code{case} ブロックのコードが実行されます。
ガードは @ref{181,,if} の後に式を書く形で表記されます。

@code{guard} 付きの @code{case} ブロックの処理の流れは次のとおりです:


@enumerate 

@item 
@code{case} ブロックのパターンが成功するかどうかをチェックする。
失敗した場合は、 @code{guard} は評価されず、次の @code{case} ブロックのチェックに進む。

@item 
パターンが成功した場合は、 @code{guard} の評価が行われます。


@itemize *

@item 
@code{guard} 条件の評価値が真である場合、該当の case ブロックが選択されます。

@item 
@code{guard} 条件の評価値が偽の場合、該当の case ブロックは選択されません。

@item 
@code{guard} の評価中に例外が送出された場合は、その例外がそのまま送出されます。
@end itemize
@end enumerate

ガードは式であるため、副作用を起こすことができます。
ガードの評価は、最初の case ブロックから順に、パターンが失敗した case ブロックは飛ばしつつ、一つづつ評価されなければいけません (つまり、ガードの評価は書かれている順番で実行される必要があります)。
また、case ブロックが選択された時点で、ガードの評価をそれ以上行ってはいけません。

@node 論駁不可能なケースブロック,パターン,ガード<2>,match 文<2>
@anchor{reference/compound_stmts irrefutable-case}@anchor{254c}@anchor{reference/compound_stmts irrefutable-case-blocks}@anchor{254d}
@subsubsection 論駁不可能なケースブロック


@geindex irrefutable case block
@geindex case block

論駁不可能なケースブロックとは、何にでもマッチするケースブロックのことです。
match 文の中で、論駁不可能なケースブロックは最大一つまで、かつ最後に位置する必要があります。

ケースブロックが論駁不可能であるためには、ガードがなく、パターンが論駁不可能である必要があります。
パターンが論駁不可能であるためには、その文法上の構造のみから、それが常に成功することが証明できる必要があります。
論駁不可能なパターンは以下のようなもののみです:


@itemize *

@item 
左辺が論駁不可能である @ref{254e,,AS パターン}

@item 
含まれるパターンのうち少なくとも一つが論駁不可能である @ref{254f,,OR パターン}

@item 
@ref{2550,,キャプチャパターン}

@item 
@ref{a0f,,ワイルドカードパターン}

@item 
括弧で囲われた、論駁不可能なパターン
@end itemize

@node パターン,,論駁不可能なケースブロック,match 文<2>
@anchor{reference/compound_stmts patterns}@anchor{2551}
@subsubsection パターン


@geindex ! patterns
@geindex AS pattern@comma{} OR pattern@comma{} capture pattern@comma{} wildcard pattern

@cartouche
@quotation 注釈 
このセクションでは、通常のEBNFを拡張した文法記法を使用します。


@itemize *

@item 
@code{SEP.RULE+} という表記は @code{RULE (SEP RULE)*} の略です。

@item 
@code{!RULE} は否定先読みの条件を表します。
@end itemize
@end quotation
@end cartouche

@code{patterns} のトップレベルの構文は以下の通りです:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-patterns}@anchor{2547}patterns:       @ref{2552,,open_sequence_pattern} | @ref{2553,,pattern}
@anchor{reference/compound_stmts grammar-token-python-grammar-pattern}@anchor{2553}pattern:        @ref{2554,,as_pattern} | @ref{2555,,or_pattern}
@anchor{reference/compound_stmts grammar-token-python-grammar-closed_pattern}@anchor{2556}closed_pattern: | @ref{2557,,literal_pattern}
                | @ref{2558,,capture_pattern}
                | @ref{2559,,wildcard_pattern}
                | @ref{255a,,value_pattern}
                | @ref{255b,,group_pattern}
                | @ref{255c,,sequence_pattern}
                | @ref{255d,,mapping_pattern}
                | @ref{255e,,class_pattern}
@end example

以下の説明では分かりやすさのため、パターンの振る舞いを簡単に言い表した場合の説明を「簡単に言うと」の後に書いています (そのほとんどは、Raymond Hettinger 氏のドキュメントに影響を受けてのものです)。
ただし、これはあくまで理解を助けるためのであり、内部的な実装を必ずしも反映したものでは `ありません' 。
また、使用可能なすべてのパターン構造を網羅しているわけではありません。

@menu
* OR パターン:: 
* AS パターン:: 
* リテラルパターン:: 
* キャプチャパターン:: 
* ワイルドカードパターン:: 
* 値パターン:: 
* グループパターン:: 
* シーケンスパターン:: 
* マッピングパターン:: 
* クラスパターン:: 

@end menu

@node OR パターン,AS パターン,,パターン
@anchor{reference/compound_stmts id3}@anchor{255f}@anchor{reference/compound_stmts or-patterns}@anchor{254f}
@subsubsection OR パターン


OR パターンは、縦線 @code{|} で区切られた複数のパターンからなります。
構文:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-or_pattern}@anchor{2555}or_pattern: "|".@ref{2556,,closed_pattern}+
@end example

最後のサブパターン以外、 @ref{254c,,論駁不可能} であってはいけません。
また、曖昧さ回避のため、各サブパターンが束縛する名前の組み合わせは、すべて同じである必要があります。

OR パターンでは、サブジェクト値に対して順に各サブパターンのマッチングが行われます。
マッチが成功するとそこで終了し、この OR パターンは成功したとみなされます。
一方、どのサブパターンも成功しなければ、この OR パターンは失敗したことになります。

簡単に言うと、 @code{P1 | P2 | ...} というパターンは @code{P1} をマッチしようとし、失敗すれば @code{P2} を試します。
いずれかのパターンがマッチが成功すれば直ちに成功となり、それ以外の場合は失敗となります。

@node AS パターン,リテラルパターン,OR パターン,パターン
@anchor{reference/compound_stmts as-patterns}@anchor{254e}@anchor{reference/compound_stmts id4}@anchor{2560}
@subsubsection AS パターン


AS パターンはサブジェクト値に対して、 @ref{253f,,as} キーワードの左側にある OR パターンをマッチさせます。
構文:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-as_pattern}@anchor{2554}as_pattern: @ref{2555,,or_pattern} "as" @ref{2558,,capture_pattern}
@end example

OR パターンが失敗すれば、この AS パターンは失敗となります。
成功すれば、サブジェクト値が as キーワードの右側の名前に束縛され、この AS パターンは成功となります。
@code{capture_pattern} として @code{_} を指定することはできません。

簡単に言うと、 @code{P as NAME} は @code{P} をマッチさせ、成功した場合に @code{NAME = <subject>} の代入を行います。

@node リテラルパターン,キャプチャパターン,AS パターン,パターン
@anchor{reference/compound_stmts id5}@anchor{2561}@anchor{reference/compound_stmts literal-patterns}@anchor{2562}
@subsubsection リテラルパターン


リテラルパターンは、一部を除く Python の @ref{22c9,,リテラル} に対応します。
構文:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-literal_pattern}@anchor{2557}literal_pattern: @ref{2563,,signed_number}
                 | @ref{2563,,signed_number} "+" NUMBER
                 | @ref{2563,,signed_number} "-" NUMBER
                 | @ref{247e,,strings}
                 | "None"
                 | "True"
                 | "False"
@anchor{reference/compound_stmts grammar-token-python-grammar-signed_number}@anchor{2563}signed_number:   ["-"] NUMBER
@end example

The rule @code{strings} and the token @code{NUMBER} are defined in the
@ref{2564,,standard Python grammar}.  Triple-quoted strings are
supported.  Raw strings and byte strings are supported.  @ref{19a,,f-strings}
and @ref{17fa,,t-strings} are not supported.

@code{signed_number '+' NUMBER} と @code{signed_number '-' NUMBER} という構文は @ref{231b,,複素数} を表現するためのものです。
そのため、左側には実数、右側には虚数を書く必要があります。
例: @code{3 + 4j} 。

簡単に言うと、 @code{LITERAL} は @code{<subject> == LITERAL} であるときのみ成功するパターンです。
シングルトンである @code{None} と @code{True} 、 @code{False} は @ref{34c,,is} 演算子を使って比較されます。

@node キャプチャパターン,ワイルドカードパターン,リテラルパターン,パターン
@anchor{reference/compound_stmts capture-patterns}@anchor{2550}@anchor{reference/compound_stmts id6}@anchor{2565}
@subsubsection キャプチャパターン


キャプチャパターンは、サブジェクト値を名前に束縛します。
構文:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-capture_pattern}@anchor{2558}capture_pattern: !'_' NAME
@end example

アンダースコア一文字の @code{_} はキャプチャパターンではありません (@code{!'_'} が表しているのはこの条件です) 。
@ref{2559,,wildcard_pattern} として扱われます。

パターン一つの中で、一つの名前は一度しか束縛することができません。
例えば、 @code{case x, x: ...} は間違いですが、 @code{case [x] | x: ...} は正しいです。

キャプチャパターンは常に成功します。
束縛された名前のスコープは、 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/} で確立された代入式演算子のスコープルールと同じです。
すなわち、当てはまる @ref{4ac,,global} 文 か @ref{14bf,,nonlocal} 文がない限り、その局所変数のスコープは、該当の match 文を包む最も内側の関数となります。

簡単に言うと、 @code{NAME} は常に成功し、 @code{NAME = <subject>} の代入が行われます。

@node ワイルドカードパターン,値パターン,キャプチャパターン,パターン
@anchor{reference/compound_stmts id7}@anchor{2566}@anchor{reference/compound_stmts wildcard-patterns}@anchor{a0f}
@subsubsection ワイルドカードパターン


ワイルドカードパターンは常に成功 (何に対してもマッチする) し、名前の束縛はしません。
構文:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-wildcard_pattern}@anchor{2559}wildcard_pattern: '_'
@end example

@code{_} は、パターンの中で使用された場合は常に @ref{a0d,,ソフトキーワード} です。
しかし、パターンの中でない場合はソフトキーワードではありません。
たとえサブジェクト式や @code{guard} 、 @code{case} ブロックの中でも、通常の変数となります。

簡単に言うと、 @code{_} は常に成功します。

@node 値パターン,グループパターン,ワイルドカードパターン,パターン
@anchor{reference/compound_stmts id8}@anchor{2567}@anchor{reference/compound_stmts value-patterns}@anchor{2568}
@subsubsection 値パターン


値パターンは Python で名前の付けられた値を表します。
構文:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-value_pattern}@anchor{255a}value_pattern: @ref{2569,,attr}
@anchor{reference/compound_stmts grammar-token-python-grammar-attr}@anchor{2569}attr:          @ref{256a,,name_or_attr} "." NAME
@anchor{reference/compound_stmts grammar-token-python-grammar-name_or_attr}@anchor{256a}name_or_attr:  @ref{2569,,attr} | NAME
@end example

ドットがついたこの名前は、Python 標準の @ref{242a,,名前解決ルール} によって解決されます。
このパターンは、解決された値がサブジェクト値と等しい (比較演算子 @code{==} に基づく) ときに成功となります。

簡単に言うと、 @code{NAME1.NAME2} は @code{<subject> == NAME1.NAME2} であるときのみ成功します。

@cartouche
@quotation 注釈 
一つの match 文で同じ値が複数回出現する場合は、インタープリタが最初に解決された値をキャッシュし、名前解決を何度も行うことなく値を再利用する可能性があります。
このキャッシュは、その match 文のその実行一回の間だけで再利用されます。
@end quotation
@end cartouche

@node グループパターン,シーケンスパターン,値パターン,パターン
@anchor{reference/compound_stmts group-patterns}@anchor{256b}@anchor{reference/compound_stmts id9}@anchor{256c}
@subsubsection グループパターン


A group pattern allows users to add parentheses around patterns to
emphasize the intended grouping.  Otherwise, it has no additional syntax.
Syntax:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-group_pattern}@anchor{255b}group_pattern: "(" @ref{2553,,pattern} ")"
@end example

In simple terms @code{(P)} has the same effect as @code{P}.

@node シーケンスパターン,マッピングパターン,グループパターン,パターン
@anchor{reference/compound_stmts id10}@anchor{256d}@anchor{reference/compound_stmts sequence-patterns}@anchor{256e}
@subsubsection シーケンスパターン


A sequence pattern contains several subpatterns to be matched against sequence elements.
The syntax is similar to the unpacking of a list or tuple.

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-sequence_pattern}@anchor{255c}sequence_pattern:       "[" [@ref{256f,,maybe_sequence_pattern}] "]"
                        | "(" [@ref{2552,,open_sequence_pattern}] ")"
@anchor{reference/compound_stmts grammar-token-python-grammar-open_sequence_pattern}@anchor{2552}open_sequence_pattern:  @ref{2570,,maybe_star_pattern} "," [@ref{256f,,maybe_sequence_pattern}]
@anchor{reference/compound_stmts grammar-token-python-grammar-maybe_sequence_pattern}@anchor{256f}maybe_sequence_pattern: ",".@ref{2570,,maybe_star_pattern}+ ","?
@anchor{reference/compound_stmts grammar-token-python-grammar-maybe_star_pattern}@anchor{2570}maybe_star_pattern:     @ref{2571,,star_pattern} | @ref{2553,,pattern}
@anchor{reference/compound_stmts grammar-token-python-grammar-star_pattern}@anchor{2571}star_pattern:           "*" (@ref{2558,,capture_pattern} | @ref{2559,,wildcard_pattern})
@end example

There is no difference if parentheses  or square brackets
are used for sequence patterns (i.e. @code{(...)} vs @code{[...]} ).

@cartouche
@quotation 注釈 
A single pattern enclosed in parentheses without a trailing comma
(e.g. @code{(3 | 4)}) is a @ref{256b,,group pattern}.
While a single pattern enclosed in square brackets (e.g. @code{[3 | 4]}) is
still a sequence pattern.
@end quotation
@end cartouche

At most one star subpattern may be in a sequence pattern.  The star subpattern
may occur in any position. If no star subpattern is present, the sequence
pattern is a fixed-length sequence pattern; otherwise it is a variable-length
sequence pattern.

The following is the logical flow for matching a sequence pattern against a
subject value:


@enumerate 

@item 
If the subject value is not a sequence @footnote{
In pattern matching, a sequence is defined as one of the following:


@itemize *

@item 
@ref{13dc,,collections.abc.Sequence} を継承したクラス。

@item 
@ref{13dc,,collections.abc.Sequence} として登録されたPythonクラス。

@item 
a builtin class that has its (CPython) @ref{1c59,,Py_TPFLAGS_SEQUENCE} bit set

@item 
a class that inherits from any of the above
@end itemize

The following standard library classes are sequences:


@itemize *

@item 
@ref{4be,,array.array}

@item 
@ref{7f4,,collections.deque}

@item 
@ref{24d,,list}

@item 
@ref{165,,memoryview}

@item 
@ref{b3d,,range}

@item 
@ref{614,,tuple}
@end itemize

@cartouche
@quotation 注釈 
Subject values of type @code{str}, @code{bytes}, and @code{bytearray}
do not match sequence patterns.
@end quotation
@end cartouche
}, the sequence pattern
fails.

@item 
If the subject value is an instance of @code{str}, @code{bytes} or @code{bytearray}
the sequence pattern fails.

@item 
The subsequent steps depend on whether the sequence pattern is fixed or
variable-length.

If the sequence pattern is fixed-length:


@enumerate 

@item 
If the length of the subject sequence is not equal to the number of
subpatterns, the sequence pattern fails

@item 
Subpatterns in the sequence pattern are matched to their corresponding
items in the subject sequence from left to right.  Matching stops as soon
as a subpattern fails.  If all subpatterns succeed in matching their
corresponding item, the sequence pattern succeeds.
@end enumerate

Otherwise, if the sequence pattern is variable-length:


@enumerate 

@item 
If the length of the subject sequence is less than the number of non-star
subpatterns, the sequence pattern fails.

@item 
The leading non-star subpatterns are matched to their corresponding items
as for fixed-length sequences.

@item 
If the previous step succeeds, the star subpattern matches a list formed
of the remaining subject items, excluding the remaining items
corresponding to non-star subpatterns following the star subpattern.

@item 
Remaining non-star subpatterns are matched to their corresponding subject
items, as for a fixed-length sequence.
@end enumerate

@cartouche
@quotation 注釈 
The length of the subject sequence is obtained via
@ref{840,,len()} (i.e. via the @ref{178f,,__len__()} protocol).
This length may be cached by the interpreter in a similar manner as
@ref{2568,,value patterns}.
@end quotation
@end cartouche
@end enumerate

In simple terms @code{[P1, P2, P3,} ... @code{, P<N>]} matches only if all the following
happens:


@itemize *

@item 
@code{<subject>} がシーケンスかをチェックする

@item 
@code{len(subject) == <N>}

@item 
@code{P1} matches @code{<subject>[0]} (note that this match can also bind names)

@item 
@code{P2} matches @code{<subject>[1]} (note that this match can also bind names)

@item 
... and so on for the corresponding pattern/element.
@end itemize

@node マッピングパターン,クラスパターン,シーケンスパターン,パターン
@anchor{reference/compound_stmts id12}@anchor{2572}@anchor{reference/compound_stmts mapping-patterns}@anchor{2573}
@subsubsection マッピングパターン


A mapping pattern contains one or more key-value patterns.  The syntax is
similar to the construction of a dictionary.
Syntax:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-mapping_pattern}@anchor{255d}mapping_pattern:     "@{" [@ref{2574,,items_pattern}] "@}"
@anchor{reference/compound_stmts grammar-token-python-grammar-items_pattern}@anchor{2574}items_pattern:       ",".@ref{2575,,key_value_pattern}+ ","?
@anchor{reference/compound_stmts grammar-token-python-grammar-key_value_pattern}@anchor{2575}key_value_pattern:   (@ref{2557,,literal_pattern} | @ref{255a,,value_pattern}) ":" @ref{2553,,pattern}
                     | @ref{2576,,double_star_pattern}
@anchor{reference/compound_stmts grammar-token-python-grammar-double_star_pattern}@anchor{2576}double_star_pattern: "**" @ref{2558,,capture_pattern}
@end example

At most one double star pattern may be in a mapping pattern.  The double star
pattern must be the last subpattern in the mapping pattern.

Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will
raise a @ref{18e,,SyntaxError}. Two keys that otherwise have the same value will
raise a @ref{2ec,,ValueError} at runtime.

The following is the logical flow for matching a mapping pattern against a
subject value:


@enumerate 

@item 
If the subject value is not a mapping @footnote{
In pattern matching, a mapping is defined as one of the following:


@itemize *

@item 
a class that inherits from @ref{ac7,,collections.abc.Mapping}

@item 
a Python class that has been registered as @ref{ac7,,collections.abc.Mapping}

@item 
a builtin class that has its (CPython) @ref{1c58,,Py_TPFLAGS_MAPPING} bit set

@item 
a class that inherits from any of the above
@end itemize

The standard library classes @ref{183,,dict} and @ref{698,,types.MappingProxyType}
are mappings.
},the mapping pattern fails.

@item 
If every key given in the mapping pattern is present in the subject mapping,
and the pattern for each key matches the corresponding item of the subject
mapping, the mapping pattern succeeds.

@item 
If duplicate keys are detected in the mapping pattern, the pattern is
considered invalid. A @ref{18e,,SyntaxError} is raised for duplicate literal
values; or a @ref{2ec,,ValueError} for named keys of the same value.
@end enumerate

@cartouche
@quotation 注釈 
Key-value pairs are matched using the two-argument form of the mapping
subject's @code{get()} method.  Matched key-value pairs must already be present
in the mapping, and not created on-the-fly via @ref{13d5,,__missing__()}
or @ref{588,,__getitem__()}.
@end quotation
@end cartouche

In simple terms @code{@{KEY1: P1, KEY2: P2, ... @}} matches only if all the following
happens:


@itemize *

@item 
@code{<subject>} がマッピングかをチェックする

@item 
@code{KEY1 in <subject>}

@item 
@code{P1} は @code{<subject>[KEY1]} にマッチする

@item 
... and so on for the corresponding KEY/pattern pair.
@end itemize

@node クラスパターン,,マッピングパターン,パターン
@anchor{reference/compound_stmts class-patterns}@anchor{2577}@anchor{reference/compound_stmts id14}@anchor{2578}
@subsubsection クラスパターン


A class pattern represents a class and its positional and keyword arguments
(if any).  Syntax:

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-class_pattern}@anchor{255e}class_pattern:       @ref{256a,,name_or_attr} "(" [@ref{2579,,pattern_arguments} ","?] ")"
@anchor{reference/compound_stmts grammar-token-python-grammar-pattern_arguments}@anchor{2579}pattern_arguments:   @ref{257a,,positional_patterns} ["," @ref{257b,,keyword_patterns}]
                     | @ref{257b,,keyword_patterns}
@anchor{reference/compound_stmts grammar-token-python-grammar-positional_patterns}@anchor{257a}positional_patterns: ",".@ref{2553,,pattern}+
@anchor{reference/compound_stmts grammar-token-python-grammar-keyword_patterns}@anchor{257b}keyword_patterns:    ",".@ref{257c,,keyword_pattern}+
@anchor{reference/compound_stmts grammar-token-python-grammar-keyword_pattern}@anchor{257c}keyword_pattern:     NAME "=" @ref{2553,,pattern}
@end example

The same keyword should not be repeated in class patterns.

The following is the logical flow for matching a class pattern against a
subject value:


@enumerate 

@item 
If @code{name_or_attr} is not an instance of the builtin @ref{f44,,type} , raise
@ref{198,,TypeError}.

@item 
If the subject value is not an instance of @code{name_or_attr} (tested via
@ref{2ad,,isinstance()}), the class pattern fails.

@item 
If no pattern arguments are present, the pattern succeeds.  Otherwise,
the subsequent steps depend on whether keyword or positional argument patterns
are present.

For a number of built-in types (specified below), a single positional
subpattern is accepted which will match the entire subject; for these types
keyword patterns also work as for other types.

If only keyword patterns are present, they are processed as follows,
one by one:


@enumerate 

@item 
The keyword is looked up as an attribute on the subject.


@itemize *

@item 
If this raises an exception other than @ref{5f0,,AttributeError}, the
exception bubbles up.

@item 
If this raises @ref{5f0,,AttributeError}, the class pattern has failed.

@item 
Else, the subpattern associated with the keyword pattern is matched
against the subject's attribute value.  If this fails, the class
pattern fails; if this succeeds, the match proceeds to the next keyword.
@end itemize

@item 
If all keyword patterns succeed, the class pattern succeeds.
@end enumerate

If any positional patterns are present, they are converted to keyword
patterns using the @ref{1c75,,__match_args__} attribute on the class
@code{name_or_attr} before matching:


@enumerate 

@item 
The equivalent of @code{getattr(cls, "__match_args__", ())} is called.


@itemize *

@item 
If this raises an exception, the exception bubbles up.

@item 
If the returned value is not a tuple, the conversion fails and
@ref{198,,TypeError} is raised.

@item 
If there are more positional patterns than @code{len(cls.__match_args__)},
@ref{198,,TypeError} is raised.

@item 
Otherwise, positional pattern @code{i} is converted to a keyword pattern
using @code{__match_args__[i]} as the keyword.  @code{__match_args__[i]} must
be a string; if not @ref{198,,TypeError} is raised.

@item 
If there are duplicate keywords, @ref{198,,TypeError} is raised.
@end itemize


@subsubheading 参考


@ref{240e,,クラスパターンマッチの位置引数のカスタマイズ}


@item 
Once all positional patterns have been converted to keyword patterns,
the match proceeds as if there were only keyword patterns.
@end enumerate

For the following built-in types the handling of positional subpatterns is
different:


@itemize *

@item 
@ref{3c3,,bool}

@item 
@ref{344,,bytearray}

@item 
@ref{192,,bytes}

@item 
@ref{183,,dict}

@item 
@ref{196,,float}

@item 
@ref{7f2,,frozenset}

@item 
@ref{19b,,int}

@item 
@ref{24d,,list}

@item 
@ref{184,,set}

@item 
@ref{169,,str}

@item 
@ref{614,,tuple}
@end itemize

These classes accept a single positional argument, and the pattern there is matched
against the whole object rather than an attribute. For example @code{int(0|1)} matches
the value @code{0}, but not the value @code{0.0}.
@end enumerate

In simple terms @code{CLS(P1, attr=P2)} matches only if the following happens:


@itemize *

@item 
@code{isinstance(<subject>, CLS)}

@item 
convert @code{P1} to a keyword pattern using @code{CLS.__match_args__}

@item 
For each keyword argument @code{attr=P2}:


@itemize *

@item 
@code{hasattr(<subject>, "attr")}

@item 
@code{P2} は @code{<subject>.attr} にマッチする
@end itemize

@item 
... and so on for the corresponding keyword argument/pattern pair.
@end itemize


@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/} -- 構造的パターンマッチ: 仕様

@item 
@geindex Python Enhancement Proposals; PEP 636
PEP 636@footnote{https://peps.python.org/pep-0636/} -- 構造的パターンマッチ: チュートリアル
@end itemize


@geindex parameter;function definition
@anchor{reference/compound_stmts function}@anchor{2018}
@node 関数定義,クラス定義,match 文<2>,複合文 compound statement
@anchor{reference/compound_stmts def}@anchor{1673}@anchor{reference/compound_stmts function-definitions}@anchor{257d}
@subsection 関数定義


@geindex statement;def
@geindex 関数;definition
@geindex 関数;name
@geindex name;束縛
@geindex object;ユーザ定義関数
@geindex object;関数
@geindex 関数;name
@geindex name;束縛
@geindex () (丸括弧);function definition
@geindex @comma{} (comma);parameter list
@geindex ; (コロン);compound statement

関数定義は、ユーザ定義関数オブジェクトを定義します (@ref{232f,,標準型の階層} 節参照):

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-funcdef}@anchor{252b}funcdef:                   [@ref{257e,,decorators}] "def" @ref{257f,,funcname} [@ref{251f,,type_params}] "(" [@ref{24e3,,parameter_list}] ")"
                           ["->" @ref{182,,expression}] ":" @ref{2530,,suite}
@anchor{reference/compound_stmts grammar-token-python-grammar-decorators}@anchor{257e}decorators:                @ref{2580,,decorator}+
@anchor{reference/compound_stmts grammar-token-python-grammar-decorator}@anchor{2580}decorator:                 "@@" @ref{242d,,assignment_expression} NEWLINE
@anchor{reference/compound_stmts grammar-token-python-grammar-parameter_list}@anchor{24e3}parameter_list:            @ref{2581,,defparameter} ("," @ref{2581,,defparameter})* "," "/" ["," [@ref{2582,,parameter_list_no_posonly}]]
                             | @ref{2582,,parameter_list_no_posonly}
@anchor{reference/compound_stmts grammar-token-python-grammar-parameter_list_no_posonly}@anchor{2582}parameter_list_no_posonly: @ref{2581,,defparameter} ("," @ref{2581,,defparameter})* ["," [@ref{2583,,parameter_list_starargs}]]
                           | @ref{2583,,parameter_list_starargs}
@anchor{reference/compound_stmts grammar-token-python-grammar-parameter_list_starargs}@anchor{2583}parameter_list_starargs:   "*" [@ref{2584,,star_parameter}] ("," @ref{2581,,defparameter})* ["," [@ref{2585,,parameter_star_kwargs}]]
                           | "*" ("," @ref{2581,,defparameter})+ ["," [@ref{2585,,parameter_star_kwargs}]]
                           | @ref{2585,,parameter_star_kwargs}
@anchor{reference/compound_stmts grammar-token-python-grammar-parameter_star_kwargs}@anchor{2585}parameter_star_kwargs:     "**" @ref{2586,,parameter} [","]
@anchor{reference/compound_stmts grammar-token-python-grammar-parameter}@anchor{2586}parameter:                 @ref{22c1,,identifier} [":" @ref{182,,expression}]
@anchor{reference/compound_stmts grammar-token-python-grammar-star_parameter}@anchor{2584}star_parameter:            @ref{22c1,,identifier} [":" ["*"] @ref{182,,expression}]
@anchor{reference/compound_stmts grammar-token-python-grammar-defparameter}@anchor{2581}defparameter:              @ref{2586,,parameter} ["=" @ref{182,,expression}]
@anchor{reference/compound_stmts grammar-token-python-grammar-funcname}@anchor{257f}funcname:                  @ref{22c1,,identifier}
@end example

関数定義は実行可能な文です。関数定義を実行すると、現在のローカルな名前空間内で関数名を関数オブジェクト (関数の実行可能コードをくるむラッパー) に束縛します。この関数オブジェクトには、関数が呼び出された際に使われるグローバルな名前空間として、現在のグローバルな名前空間への参照が入っています。

関数定義は関数本体を実行しません; 関数本体は関数が呼び出された時にのみ実行されます。 @footnote{
A string literal appearing as the first statement in the function body is
transformed into the function's @ref{13f1,,__doc__} attribute and
therefore the function's @ref{22ec,,docstring}.
}

@geindex @@ (at);function definition

関数定義は一つ以上の @ref{93a,,デコレータ} 式でラップできます。デコレータ式は関数を定義するとき、関数定義の入っているスコープで評価されます。その結果は、関数オブジェクトを唯一の引数にとる呼び出し可能オブジェクトでなければなりません。関数オブジェクトの代わりに、返された値が関数名に束縛されます。複数のデコレータはネストして適用されます。例えば、以下のようなコード:

@example
@@f1(arg)
@@f2
def func(): pass
@end example

は、だいたい次と等価です

@example
def func(): pass
func = f1(arg)(f2(func))
@end example

ただし、前者のコードでは元々の関数を @code{func} という名前へ一時的に束縛することはない、というところを除きます。


バージョン 3.9 で変更: Functions may be decorated with any valid
@ref{242d,,assignment_expression}. Previously, the grammar was
much more restrictive; see 
@geindex Python Enhancement Proposals; PEP 614
PEP 614@footnote{https://peps.python.org/pep-0614/} for details.


A list of @ref{5ad,,type parameters} may be given in square brackets
between the function's name and the opening parenthesis for its parameter list.
This indicates to static type checkers that the function is generic. At runtime,
the type parameters can be retrieved from the function's
@ref{234d,,__type_params__}
attribute. See @ref{682,,Generic functions} for more.


バージョン 3.12 で変更: Type parameter lists are new in Python 3.12.


@geindex default;parameter;value
@geindex 引数 (argument);function definition
@geindex = (等号);function definition

1 つ以上の @ref{234b,,仮引数} が `parameter' @code{=} `expression' の形を取っているとき、関数は "デフォルト引数値" を持つと言います。デフォルト値を持つ仮引数では、呼び出し時にそれに対応する @ref{67b,,実引数} は省略でき、その場合は仮引数のデフォルト値が使われます。ある引数がデフォルト値を持っている場合、それ以降 "@code{*}" が出てくるまでの引数は全てデフォルト値を持っていなければなりません -- これは文法定義では表現されていない構文的制限です。

`デフォルト引数値は関数定義が実行されるときに左から右へ評価されます。' これは、デフォルト引数の式は関数が定義されるときにただ一度だけ評価され、同じ "計算済みの" 値が呼び出しのたびに使用されることを意味します。この仕様を理解しておくことは特に、デフォルト引数値がリストや辞書のようなミュータブルなオブジェクトであるときに重要です: 関数がこのオブジェクトを変更 (例えばリストに要素を追加) すると、このデフォルト引数値が変更の影響を受けてしまします。一般には、これは意図しない動作です。このような動作を避けるには、デフォルト値として @code{None} を使い、この値を関数本体の中で明示的にテストします。例えば以下のようにします:

@example
def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin
@end example

@geindex / (スラッシュ);function definition
@geindex * (アスタリスク);function definition
@geindex **;function definition

関数呼び出しの意味付けに関する詳細は、 @ref{f7d,,呼び出し (call)} 節で述べられています。
関数呼び出しを行うと、パラメタリストに記述された全てのパラメタに、位置引数、キーワード引数、デフォルト値のいずれかから値が代入されます。
"@code{*identifier}" 形式が存在すれば、余ったすべての位置引数を受け取ったタプルに初期化されます。
このデフォルト値は空のタプルです。
"@code{**identifier}" 形式が存在すれば、余ったすべてのキーワード引数を受け取った順序付きのマッピングオブジェクトに初期化されます。
このデフォルト値は同じ型の空のマッピングオブジェクトです。
"@code{*}" や "@code{*identifier}" の後のパラメタはキーワード専用パラメータで、キーワード引数によってのみ渡されます。
"@code{/}" の前のパラメタは位置専用パラメータで、位置引数によってのみ渡されます。


バージョン 3.8 で変更: The @code{/} function parameter syntax may be used to indicate positional-only
parameters. See 
@geindex Python Enhancement Proposals; PEP 570
PEP 570@footnote{https://peps.python.org/pep-0570/} for details.


@geindex 関数;annotations
@geindex ->;関数のアノテーション
@geindex ; (コロン);関数のアノテーション

Parameters may have an @ref{2019,,annotation} of the form "@code{: expression}"
following the parameter name.  Any parameter may have an annotation, even those of the form
@code{*identifier} or @code{**identifier}. (As a special case, parameters of the form
@code{*identifier} may have an annotation "@code{: *expression}".) Functions may have "return" annotation of
the form "@code{-> expression}" after the parameter list.  These annotations can be
any valid Python expression.  The presence of annotations does not change the
semantics of a function. See @ref{2587,,Annotations} for more information on annotations.


バージョン 3.11 で変更: Parameters of the form "@code{*identifier}" may have an annotation
"@code{: *expression}". See 
@geindex Python Enhancement Proposals; PEP 646
PEP 646@footnote{https://peps.python.org/pep-0646/}.


@geindex lambda;expression

式を即時に使用するために、無名関数 (名前に束縛されていない関数) を作成することもできます。
これは @ref{14b5,,ラムダ (lambda)} の節で解説されているラムダ式を使います。
ラムダ式は簡略化された関数定義の簡略表現に過ぎないことに注意してください;  "@ref{1673,,def}" 文で定義された関数もラムダ式で作成された関数のように、引数として渡せたり、他の名前に割り当てることができます。
複数の式とアノテーションが実行できるので、 "@code{def}" 形式の方がより強力です。

`プログラマへのメモ:' 関数は第一級オブジェクトです。関数定義内で実行された "@code{def}" 文は、返り値や引数として渡せるローカル関数を定義します。ネストした関数内で使われる自由変数は、 def を含んでいる関数のローカル変数にアクセスできます。詳細は @ref{2346,,名前づけと束縛 (naming and binding)} 節を参照してください。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3107

@item PEP 3107@footnote{https://peps.python.org/pep-3107/} - Function Annotations

関数アノテーションの元の仕様書。

@geindex Python Enhancement Proposals; PEP 484

@item PEP 484@footnote{https://peps.python.org/pep-0484/} - 型ヒント

アノテーションの標準的な意味付けである型ヒントの定義。

@geindex Python Enhancement Proposals; PEP 526

@item PEP 526@footnote{https://peps.python.org/pep-0526/} - Syntax for Variable Annotations

Ability to type hint variable declarations, including class
variables and instance variables.

@geindex Python Enhancement Proposals; PEP 563

@item PEP 563@footnote{https://peps.python.org/pep-0563/} - アノテーションの遅延評価

実行時にアノテーションを貪欲評価するのではなく文字列形式で保持することによる、アノテーションにおける前方参照のサポート

@geindex Python Enhancement Proposals; PEP 318

@item PEP 318@footnote{https://peps.python.org/pep-0318/} - Decorators for Functions and Methods

Function and method decorators were introduced.
Class decorators were introduced in 
@geindex Python Enhancement Proposals; PEP 3129
PEP 3129@footnote{https://peps.python.org/pep-3129/}.
@end table


@node クラス定義,コルーチン<2>,関数定義,複合文 compound statement
@anchor{reference/compound_stmts class}@anchor{14ef}@anchor{reference/compound_stmts class-definitions}@anchor{2588}
@subsection クラス定義


@geindex object;クラス
@geindex statement;クラス
@geindex クラス;definition
@geindex クラス;name
@geindex name;束縛
@geindex 実行;フレーム
@geindex inheritance
@geindex docstring
@geindex () (丸括弧);class definition
@geindex @comma{} (comma);expression list
@geindex ; (コロン);compound statement

クラス定義は、クラスオブジェクトを定義します (@ref{232f,,標準型の階層} 節参照):

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-classdef}@anchor{252c}classdef:    [@ref{257e,,decorators}] "class" @ref{2589,,classname} [@ref{251f,,type_params}] [@ref{258a,,inheritance}] ":" @ref{2530,,suite}
@anchor{reference/compound_stmts grammar-token-python-grammar-inheritance}@anchor{258a}inheritance: "(" [@ref{24b8,,argument_list}] ")"
@anchor{reference/compound_stmts grammar-token-python-grammar-classname}@anchor{2589}classname:   @ref{22c1,,identifier}
@end example

クラス定義は実行可能な文です。継承リストは通常、基底クラスリストを与えます (より高度な使い方は、 @ref{23be,,メタクラス} を参照してください)。ですから、リストのそれぞれの要素の評価はサブクラス化しても良いクラスであるべきです。継承リストのないクラスは、デフォルトで、基底クラス @ref{c7e,,object} を継承するので:

@example
class Foo:
    pass
@end example

は、以下と同等です

@example
class Foo(object):
    pass
@end example

次にクラスのスイートが、新たな実行フレーム (@ref{2346,,名前づけと束縛 (naming and binding)} を参照してください) 内で、新たに作られたローカル名前空間と元々のグローバル名前空間を使って実行されます (通常、このスイートには主に関数定義が含まれます)。クラスのスイートが実行し終えると、実行フレームは破棄されますが、ローカルな名前空間は保存されます。@footnote{
A string literal appearing as the first statement in the class body is
transformed into the namespace's @ref{2095,,__doc__} item and therefore
the class's @ref{22ec,,docstring}.
} 次に、継承リストを基底クラスに、保存されたローカル名前空間を属性値辞書に、それぞれ使ってクラスオブジェクトが生成されます。最後に、もとのローカル名前空間において、クラス名がこのクラスオブジェクトに束縛されます。

The order in which attributes are defined in the class body is preserved
in the new class's @ref{e57,,__dict__}.  Note that this is reliable only right
after the class is created and only for classes that were defined using
the definition syntax.

クラス作成は、 @ref{23be,,メタクラス} を利用して大幅にカスタマイズできます。

@geindex @@ (at);class definition

関数をデコレートするのと同じように、クラスもデコレートすることが出来ます、

@example
@@f1(arg)
@@f2
class Foo: pass
@end example

は、だいたい次と等価です

@example
class Foo: pass
Foo = f1(arg)(f2(Foo))
@end example

デコレータ式の評価規則は関数デコレータと同じです。結果はクラス名に束縛されます。


バージョン 3.9 で変更: Classes may be decorated with any valid
@ref{242d,,assignment_expression}. Previously, the grammar was
much more restrictive; see 
@geindex Python Enhancement Proposals; PEP 614
PEP 614@footnote{https://peps.python.org/pep-0614/} for details.


A list of @ref{5ad,,type parameters} may be given in square brackets
immediately after the class's name.
This indicates to static type checkers that the class is generic. At runtime,
the type parameters can be retrieved from the class's
@ref{2376,,__type_params__} attribute. See @ref{2377,,Generic classes} for more.


バージョン 3.12 で変更: Type parameter lists are new in Python 3.12.


`プログラマのための注釈:' クラス定義内で定義された変数はクラス属性であり、全てのインスタンス間で共有されます。インスタンス属性は、メソッドの中で @code{self.name = value} とすることで設定できます。クラス属性もインスタンス属性も "@code{self.name}" 表記でアクセスでき、この表記でアクセスしたとき、インスタンス属性は同名のクラス属性を隠蔽します。クラス属性は、インスタンス属性のデフォルト値として使えますが、そこにミュータブルな値を使うと予期せぬ結果につながります。 @ref{e49,,記述子} を使うと、詳細な実装が異なるインスタンス変数を作成できます。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3115

@item PEP 3115@footnote{https://peps.python.org/pep-3115/} - Metaclasses in Python 3000

メタクラスの宣言を現在の文法と、メタクラス付きのクラスがどのように構築されるかの意味論を変更した提案

@geindex Python Enhancement Proposals; PEP 3129

@item PEP 3129@footnote{https://peps.python.org/pep-3129/} - クラスデコレータ

クラスデコレータを追加した提案。
関数デコレータとメソッドデコレータは 
@geindex Python Enhancement Proposals; PEP 318
PEP 318@footnote{https://peps.python.org/pep-0318/} で導入されました。
@end table


@node コルーチン<2>,Type parameter lists,クラス定義,複合文 compound statement
@anchor{reference/compound_stmts async}@anchor{93b}@anchor{reference/compound_stmts coroutines}@anchor{258b}
@subsection コルーチン



Added in version 3.5.


@geindex statement;async def

@menu
* コルーチン関数定義:: 
* async for 文:: 
* async with 文:: 

@end menu

@node コルーチン関数定義,async for 文,,コルーチン<2>
@anchor{reference/compound_stmts async-def}@anchor{7ed}@anchor{reference/compound_stmts coroutine-function-definition}@anchor{258c}
@subsubsection コルーチン関数定義


@example
@anchor{reference/compound_stmts grammar-token-python-grammar-async_funcdef}@anchor{252f}async_funcdef: [@ref{257e,,decorators}] "async" "def" @ref{257f,,funcname} "(" [@ref{24e3,,parameter_list}] ")"
               ["->" @ref{182,,expression}] ":" @ref{2530,,suite}
@end example

@geindex キーワード;async
@geindex キーワード;await

Python で実行しているコルーチンは多くの時点で一時停止と再開ができます (@ref{6b9,,coroutine} を参照)。@ref{18d,,await} 式である @ref{ca1,,async for} と @ref{185,,async with} はコルーチン関数の本体でしか使えません。

Functions defined with @code{async def} syntax are always coroutine functions,
even if they do not contain @code{await} or @code{async} keywords.

コルーチン関数の本体の中で @code{yield from} 式を使用すると @ref{18e,,SyntaxError} になります。

コルーチン関数の例:

@example
async def func(param1, param2):
    do_stuff()
    await some_coroutine()
@end example


バージョン 3.7 で変更: @code{await} and @code{async} are now keywords; previously they were only
treated as such inside the body of a coroutine function.


@geindex statement;async for

@node async for 文,async with 文,コルーチン関数定義,コルーチン<2>
@anchor{reference/compound_stmts async-for}@anchor{ca1}@anchor{reference/compound_stmts the-async-for-statement}@anchor{258d}
@subsubsection @code{async for} 文


@example
@anchor{reference/compound_stmts grammar-token-python-grammar-async_for_stmt}@anchor{252e}async_for_stmt: "async" @ref{2527,,for_stmt}
@end example

@ref{f74,,asynchronous iterable} は、その @code{__anext__} メソッドで非同期なコードを実行可能な、@ref{4c7,,asynchronous iterator} を直接返す @code{__aiter__} メソッドを提供しています。

@code{async for} 文によって非同期なイテラブルを簡単にイテレーションすることができます。

以下のコード:

@example
async for TARGET in ITER:
    SUITE
else:
    SUITE2
@end example

は意味論的に以下と等価です:

@example
iter = (ITER).__aiter__()
running = True

while running:
    try:
        TARGET = await iter.__anext__()
    except StopAsyncIteration:
        running = False
    else:
        SUITE
else:
    SUITE2
@end example

except that implicit @ref{23b1,,special method lookup} is used
for @ref{df6,,__aiter__()} and @ref{1882,,__anext__()}.

コルーチン関数の本体の外で @code{async for} 文を使用すると @ref{18e,,SyntaxError} になります。

@geindex statement;async with

@node async with 文,,async for 文,コルーチン<2>
@anchor{reference/compound_stmts async-with}@anchor{185}@anchor{reference/compound_stmts the-async-with-statement}@anchor{258e}
@subsubsection @code{async with} 文


@example
@anchor{reference/compound_stmts grammar-token-python-grammar-async_with_stmt}@anchor{252d}async_with_stmt: "async" @ref{2529,,with_stmt}
@end example

@ref{7f0,,asynchronous context manager} は、 `enter' メソッドと `exit' メソッド内部で実行を一時停止できる @ref{1e1,,context manager} です。

以下のコード:

@example
async with EXPRESSION as TARGET:
    SUITE
@end example

これは次と等価です:

@example
manager = (EXPRESSION)
aenter = manager.__aenter__
aexit = manager.__aexit__
value = await aenter()
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not await aexit(*sys.exc_info()):
        raise
finally:
    if not hit_except:
        await aexit(None, None, None)
@end example

except that implicit @ref{23b1,,special method lookup} is used
for @ref{241d,,__aenter__()} and @ref{19a1,,__aexit__()}.

コルーチン関数の本体の外で @code{async with} 文を使用すると @ref{18e,,SyntaxError} になります。


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 492

@item PEP 492@footnote{https://peps.python.org/pep-0492/} - async 構文および await 構文付きのコルーチン

コルーチンを Python のまともな独り立ちした概念にし、サポートする構文を追加した提案。
@end table


@node Type parameter lists,Annotations<2>,コルーチン<2>,複合文 compound statement
@anchor{reference/compound_stmts type-parameter-lists}@anchor{258f}@anchor{reference/compound_stmts type-params}@anchor{5ad}
@subsection Type parameter lists



Added in version 3.12.



バージョン 3.13 で変更: Support for default values was added (see 
@geindex Python Enhancement Proposals; PEP 696
PEP 696@footnote{https://peps.python.org/pep-0696/}).


@geindex type parameters

@example
@anchor{reference/compound_stmts grammar-token-python-grammar-type_params}@anchor{251f}type_params:  "[" @ref{2590,,type_param} ("," @ref{2590,,type_param})* "]"
@anchor{reference/compound_stmts grammar-token-python-grammar-type_param}@anchor{2590}type_param:   @ref{2591,,typevar} | @ref{2592,,typevartuple} | @ref{2593,,paramspec}
@anchor{reference/compound_stmts grammar-token-python-grammar-typevar}@anchor{2591}typevar:      @ref{22c1,,identifier} (":" @ref{182,,expression})? ("=" @ref{182,,expression})?
@anchor{reference/compound_stmts grammar-token-python-grammar-typevartuple}@anchor{2592}typevartuple: "*" @ref{22c1,,identifier} ("=" @ref{182,,expression})?
@anchor{reference/compound_stmts grammar-token-python-grammar-paramspec}@anchor{2593}paramspec:    "**" @ref{22c1,,identifier} ("=" @ref{182,,expression})?
@end example

@ref{1673,,Functions} (including @ref{7ed,,coroutines}),
@ref{14ef,,classes} and @ref{66d,,type aliases} may
contain a type parameter list:

@example
def max[T](args: list[T]) -> T:
    ...

async def amax[T](args: list[T]) -> T:
    ...

class Bag[T]:
    def __iter__(self) -> Iterator[T]:
        ...

    def add(self, arg: T) -> None:
        ...

type ListOrSet[T] = list[T] | set[T]
@end example

Semantically, this indicates that the function, class, or type alias is
generic over a type variable. This information is primarily used by static
type checkers, and at runtime, generic objects behave much like their
non-generic counterparts.

Type parameters are declared in square brackets (@code{[]}) immediately
after the name of the function, class, or type alias. The type parameters
are accessible within the scope of the generic object, but not elsewhere.
Thus, after a declaration @code{def func[T](): pass}, the name @code{T} is not available in
the module scope. Below, the semantics of generic objects are described
with more precision. The scope of type parameters is modeled with a special
function (technically, an @ref{4ab,,annotation scope}) that
wraps the creation of the generic object.

Generic functions, classes, and type aliases have a
@ref{2594,,__type_params__} attribute listing their type parameters.

Type parameters come in three kinds:


@itemize *

@item 
@ref{486,,typing.TypeVar}, introduced by a plain name (e.g., @code{T}). Semantically, this
represents a single type to a type checker.

@item 
@ref{488,,typing.TypeVarTuple}, introduced by a name prefixed with a single
asterisk (e.g., @code{*Ts}). Semantically, this stands for a tuple of any
number of types.

@item 
@ref{487,,typing.ParamSpec}, introduced by a name prefixed with two asterisks
(e.g., @code{**P}). Semantically, this stands for the parameters of a callable.
@end itemize

@ref{486,,typing.TypeVar} declarations can define `bounds' and `constraints' with
a colon (@code{:}) followed by an expression. A single expression after the colon
indicates a bound (e.g. @code{T: int}). Semantically, this means
that the @code{typing.TypeVar} can only represent types that are a subtype of
this bound. A parenthesized tuple of expressions after the colon indicates a
set of constraints (e.g. @code{T: (str, bytes)}). Each member of the tuple should be a
type (again, this is not enforced at runtime). Constrained type variables can only
take on one of the types in the list of constraints.

For @code{typing.TypeVar}s declared using the type parameter list syntax,
the bound and constraints are not evaluated when the generic object is created,
but only when the value is explicitly accessed through the attributes @code{__bound__}
and @code{__constraints__}. To accomplish this, the bounds or constraints are
evaluated in a separate @ref{4ab,,annotation scope}.

@ref{488,,typing.TypeVarTuple}s and @ref{487,,typing.ParamSpec}s cannot have bounds
or constraints.

All three flavors of type parameters can also have a `default value', which is used
when the type parameter is not explicitly provided. This is added by appending
a single equals sign (@code{=}) followed by an expression. Like the bounds and
constraints of type variables, the default value is not evaluated when the
object is created, but only when the type parameter's @code{__default__} attribute
is accessed. To this end, the default value is evaluated in a separate
@ref{4ab,,annotation scope}. If no default value is specified
for a type parameter, the @code{__default__} attribute is set to the special
sentinel object @ref{569,,typing.NoDefault}.

The following example indicates the full set of allowed type parameter declarations:

@example
def overly_generic[
   SimpleTypeVar,
   TypeVarWithDefault = int,
   TypeVarWithBound: int,
   TypeVarWithConstraints: (str, bytes),
   *SimpleTypeVarTuple = (int, float),
   **SimpleParamSpec = (str, bytearray),
](
   a: SimpleTypeVar,
   b: TypeVarWithDefault,
   c: TypeVarWithBound,
   d: Callable[SimpleParamSpec, TypeVarWithConstraints],
   *e: SimpleTypeVarTuple,
): ...
@end example

@menu
* Generic functions:: 
* Generic classes:: 
* Generic type aliases:: 

@end menu

@node Generic functions,Generic classes,,Type parameter lists
@anchor{reference/compound_stmts generic-functions}@anchor{682}@anchor{reference/compound_stmts id17}@anchor{2595}
@subsubsection Generic functions


Generic functions are declared as follows:

@example
def func[T](arg: T): ...
@end example

This syntax is equivalent to:

@example
annotation-def TYPE_PARAMS_OF_func():
    T = typing.TypeVar("T")
    def func(arg: T): ...
    func.__type_params__ = (T,)
    return func
func = TYPE_PARAMS_OF_func()
@end example

Here @code{annotation-def} indicates an @ref{4ab,,annotation scope},
which is not actually bound to any name at runtime. (One
other liberty is taken in the translation: the syntax does not go through
attribute access on the @ref{10a,,typing} module, but creates an instance of
@ref{486,,typing.TypeVar} directly.)

The annotations of generic functions are evaluated within the annotation scope
used for declaring the type parameters, but the function's defaults and
decorators are not.

The following example illustrates the scoping rules for these cases,
as well as for additional flavors of type parameters:

@example
@@decorator
def func[T: int, *Ts, **P](*args: *Ts, arg: Callable[P, T] = some_default):
    ...
@end example

Except for the @ref{685,,lazy evaluation} of the
@ref{486,,TypeVar} bound, this is equivalent to:

@example
DEFAULT_OF_arg = some_default

annotation-def TYPE_PARAMS_OF_func():

    annotation-def BOUND_OF_T():
        return int
    # In reality, BOUND_OF_T() is evaluated only on demand.
    T = typing.TypeVar("T", bound=BOUND_OF_T())

    Ts = typing.TypeVarTuple("Ts")
    P = typing.ParamSpec("P")

    def func(*args: *Ts, arg: Callable[P, T] = DEFAULT_OF_arg):
        ...

    func.__type_params__ = (T, Ts, P)
    return func
func = decorator(TYPE_PARAMS_OF_func())
@end example

The capitalized names like @code{DEFAULT_OF_arg} are not actually
bound at runtime.

@node Generic classes,Generic type aliases,Generic functions,Type parameter lists
@anchor{reference/compound_stmts generic-classes}@anchor{2377}@anchor{reference/compound_stmts id18}@anchor{2596}
@subsubsection Generic classes


Generic classes are declared as follows:

@example
class Bag[T]: ...
@end example

This syntax is equivalent to:

@example
annotation-def TYPE_PARAMS_OF_Bag():
    T = typing.TypeVar("T")
    class Bag(typing.Generic[T]):
        __type_params__ = (T,)
        ...
    return Bag
Bag = TYPE_PARAMS_OF_Bag()
@end example

Here again @code{annotation-def} (not a real keyword) indicates an
@ref{4ab,,annotation scope}, and the name
@code{TYPE_PARAMS_OF_Bag} is not actually bound at runtime.

Generic classes implicitly inherit from @ref{17b6,,typing.Generic}.
The base classes and keyword arguments of generic classes are
evaluated within the type scope for the type parameters,
and decorators are evaluated outside that scope. This is illustrated
by this example:

@example
@@decorator
class Bag(Base[T], arg=T): ...
@end example

これは次と等価です:

@example
annotation-def TYPE_PARAMS_OF_Bag():
    T = typing.TypeVar("T")
    class Bag(Base[T], typing.Generic[T], arg=T):
        __type_params__ = (T,)
        ...
    return Bag
Bag = decorator(TYPE_PARAMS_OF_Bag())
@end example

@node Generic type aliases,,Generic classes,Type parameter lists
@anchor{reference/compound_stmts generic-type-aliases}@anchor{684}@anchor{reference/compound_stmts id19}@anchor{2597}
@subsubsection Generic type aliases


The @ref{66d,,type} statement can also be used to create a generic type alias:

@example
type ListOrSet[T] = list[T] | set[T]
@end example

Except for the @ref{685,,lazy evaluation} of the value,
this is equivalent to:

@example
annotation-def TYPE_PARAMS_OF_ListOrSet():
    T = typing.TypeVar("T")

    annotation-def VALUE_OF_ListOrSet():
        return list[T] | set[T]
    # In reality, the value is lazily evaluated
    return typing.TypeAliasType("ListOrSet", VALUE_OF_ListOrSet(), type_params=(T,))
ListOrSet = TYPE_PARAMS_OF_ListOrSet()
@end example

Here, @code{annotation-def} (not a real keyword) indicates an
@ref{4ab,,annotation scope}. The capitalized names
like @code{TYPE_PARAMS_OF_ListOrSet} are not actually bound at runtime.

@node Annotations<2>,,Type parameter lists,複合文 compound statement
@anchor{reference/compound_stmts annotations}@anchor{2587}@anchor{reference/compound_stmts id20}@anchor{2598}
@subsection Annotations



バージョン 3.14 で変更: Annotations are now lazily evaluated by default.


Variables and function parameters may carry @ref{15c,,annotations},
created by adding a colon after the name, followed by an expression:

@example
x: annotation = 1
def f(param: annotation): ...
@end example

Functions may also carry a return annotation following an arrow:

@example
def f() -> annotation: ...
@end example

Annotations are conventionally used for @ref{23cb,,type hints}, but this
is not enforced by the language, and in general annotations may contain arbitrary
expressions. The presence of annotations does not change the runtime semantics of
the code, except if some mechanism is used that introspects and uses the annotations
(such as @ref{33,,dataclasses} or @ref{84b,,functools.singledispatch()}).

By default, annotations are lazily evaluated in an @ref{4ab,,annotation scope}.
This means that they are not evaluated when the code containing the annotation is evaluated.
Instead, the interpreter saves information that can be used to evaluate the annotation later
if requested. The @ref{6,,annotationlib} module provides tools for evaluating annotations.

If the @ref{45d,,future statement} @code{from __future__ import annotations} is present,
all annotations are instead stored as strings:

@example
>>> from __future__ import annotations
>>> def f(param: annotation): ...
>>> f.__annotations__
@{'param': 'annotation'@}
@end example

This future statement will be deprecated and removed in a future version of Python,
but not before Python 3.13 reaches its end of life (see 
@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/}).
When it is used, introspection tools like
@ref{459,,annotationlib.get_annotations()} and @ref{8c0,,typing.get_type_hints()} are
less likely to be able to resolve annotations at runtime.

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node トップレベル要素,完全な文法仕様,複合文 compound statement,Python 言語リファレンス
@anchor{reference/toplevel_components doc}@anchor{2599}@anchor{reference/toplevel_components top-level}@anchor{259a}@anchor{reference/toplevel_components top-level-components}@anchor{259b}@anchor{reference/toplevel_components translation-repo}@anchor{259c}
@section トップレベル要素


@geindex インタプリタ

Python インタプリタは、標準入力や、プログラムの引数として与えられたスクリプト、対話的にタイプ入力された命令、モジュールのソースファイルなど、様々な入力源から入力を得ることができます。この章では、それぞれの場合に用いられる構文法について説明しています。

@menu
* 完全な Python プログラム:: 
* ファイル入力:: 
* 対話的入力:: 
* 式入力:: 

@end menu

@node 完全な Python プログラム,ファイル入力,,トップレベル要素
@anchor{reference/toplevel_components complete-python-programs}@anchor{259d}@anchor{reference/toplevel_components programs}@anchor{2452}
@subsection 完全な Python プログラム


@geindex プログラム

@geindex module;sys
@geindex module;__main__
@geindex module;builtins

言語仕様の中では、その言語を処理するインタプリタがどのように起動されるかまで規定する必要はないのですが、完全な Python プログラムの概念を知っておくと役に立ちます。完全な Python プログラムは、最小限に初期化された環境: 全ての組み込み変数と標準モジュールが利用可能で、かつ @ref{df,,sys} (様々なシステムサービス)、 @ref{13,,builtins} (組み込み関数、例外、および @code{None})、 @ref{1,,__main__} の 3 つを除く全てのモジュールが初期化されていない状態で動作します。 @ref{1,,__main__} は、完全なプログラムを実行する際に、ローカルおよびグローバルな名前空間を提供するために用いられます。

完全な Python プログラムの構文は、下の節で述べるファイル入力のためのものです。

@geindex 対話モード
@geindex module;__main__

インタプリタは、対話的モード (interactive mode) で起動されることもあります; この場合、インタプリタは完全なプログラムを読んで実行するのではなく、一度に単一の実行文 (複合文のときもあります) を読み込んで実行します。初期状態の環境は、完全なプログラムを実行するときの環境と同じです; 各実行文は、 @ref{1,,__main__} の名前空間内で実行されます。

@geindex UNIX
@geindex Windows
@geindex コマンドライン
@geindex 標準入力

完全なプログラムは3つの形式でインタープリタに渡せます: @ref{1a8,,-c} `string' コマンドラインオプションで、コマンドラインの第 1 引数で渡されるファイル、あるいは標準入力として渡します。
ファイルや標準入力が tty デバイスだった場合、インタープリタは対話モードに入ります。
それ以外の場合は、ファイルを完全なプログラムとして実行します。

@node ファイル入力,対話的入力,完全な Python プログラム,トップレベル要素
@anchor{reference/toplevel_components file-input}@anchor{259e}@anchor{reference/toplevel_components id1}@anchor{259f}
@subsection ファイル入力


非対話的なファイルから読み出された入力は、全て同じ形式:

@example
@anchor{reference/toplevel_components grammar-token-python-grammar-file_input}@anchor{25a0}file_input: (NEWLINE | @ref{2532,,statement})* ENDMARKER
@end example

をとります。この構文法は、以下の状況で用いられます:


@itemize *

@item 
(ファイルや文字列内の) 完全な Python プログラムを構文解析するとき;

@item 
モジュールを構文解析するとき;

@item 
@ref{4a2,,exec()} で渡された文字列を構文解析するとき;
@end itemize

@node 対話的入力,式入力,ファイル入力,トップレベル要素
@anchor{reference/toplevel_components interactive}@anchor{25a1}@anchor{reference/toplevel_components interactive-input}@anchor{25a2}
@subsection 対話的入力


対話モードでの入力は、以下の文法の下に構文解析されます:

@example
@anchor{reference/toplevel_components grammar-token-python-grammar-interactive_input}@anchor{25a3}interactive_input: [@ref{2531,,stmt_list}] NEWLINE | @ref{2524,,compound_stmt} NEWLINE | ENDMARKER
@end example

対話モードでは、(トップレベルの) 複合文の最後に空白行を入れなくてはならないことに注意してください; これは、複合文の終端をパーザが検出するための手がかりとして必要です。

@node 式入力,,対話的入力,トップレベル要素
@anchor{reference/toplevel_components expression-input}@anchor{25a4}@anchor{reference/toplevel_components id2}@anchor{25a5}
@subsection 式入力


@geindex 入力

@geindex 組み込み関数;eval

式入力には @ref{4a3,,eval()} が使われます。これは先頭の空白を無視します。 @ref{4a3,,eval()} に対する文字列引数は、以下の形式をとらなければなりません:

@example
@anchor{reference/toplevel_components grammar-token-python-grammar-eval_input}@anchor{25a6}eval_input: @ref{24e7,,expression_list} NEWLINE* ENDMARKER
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 完全な文法仕様,,トップレベル要素,Python 言語リファレンス
@anchor{reference/grammar doc}@anchor{2564}@anchor{reference/grammar full-grammar-specification}@anchor{25a7}@anchor{reference/grammar id1}@anchor{25a8}@anchor{reference/grammar translation-repo}@anchor{25a9}
@section 完全な文法仕様


以下に示すのは Python の完全な文法です。CPython のパーサを生成するための文法定義から直接導かれたものです (Grammar/python.gram@footnote{https://github.com/python/cpython/tree/3.14/Grammar/python.gram} を参照のこと)。ここに示すのは、コード生成およびエラー処理に関係する部分を省略したバージョンです。

The notation used here is the same as in the preceding docs,
and is described in the @ref{2284,,notation} section,
except for an extra complication:


@itemize *

@item 
@code{~} ("cut"): commit to the current alternative; fail the rule
if the alternative fails to parse

Python mainly uses cuts for optimizations or improved error
messages. They often appear to be useless in the listing below.

@c see gh-143054, and CutValidator in the source, if you want to change this:

Cuts currently don't appear inside parentheses, brackets, lookaheads
and similar.
Their behavior in these contexts is deliberately left unspecified.
@end itemize

@example
# PEG grammar for Python

@@trailer '@w{'}'
void *
_PyPegen_parse(Parser *p)
@{
    // Initialize keywords
    p->keywords = reserved_keywords;
    p->n_keyword_lists = n_keyword_lists;
    p->soft_keywords = soft_keywords;

    // 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);
    @}

    return result;
@}
'@w{'}'

# ========================= START OF THE GRAMMAR =========================

# General grammatical elements and rules:
#
# * Strings with double quotes (") denote SOFT KEYWORDS
# * Strings with single quotes (') denote KEYWORDS
# * Upper case names (NAME) denote tokens in the Grammar/Tokens file
# * Rule names starting with "invalid_" are used for specialized syntax errors
#     - These rules are NOT used in the first pass of the parser.
#     - Only if the first pass fails to parse, a second pass including the invalid
#       rules will be executed.
#     - If the parser fails in the second phase with a generic syntax error, the
#       location of the generic failure of the first pass will be used (this avoids
#       reporting incorrect locations due to the invalid rules).
#     - The order of the alternatives involving invalid rules matter
#       (like any rule in PEG).
#
# Grammar Syntax (see PEP 617 for more information):
#
# rule_name: expression
#   Optionally, a type can be included right after the rule name, which
#   specifies the return type of the C or Python function corresponding to the
#   rule:
# rule_name[return_type]: expression
#   If the return type is omitted, then a void * is returned in C and an Any in
#   Python.
# e1 e2
#   Match e1, then match e2.
# e1 | e2
#   Match e1 or e2.
#   The first alternative can also appear on the line after the rule name for
#   formatting purposes. In that case, a | must be used before the first
#   alternative, like so:
#       rule_name[return_type]:
#            | first_alt
#            | second_alt
# ( e )
#   Match e (allows also to use other operators in the group like '(e)*')
# [ e ] or e?
#   Optionally match e.
# e*
#   Match zero or more occurrences of e.
# e+
#   Match one or more occurrences of e.
# s.e+
#   Match one or more occurrences of e, separated by s. The generated parse tree
#   does not include the separator. This is otherwise identical to (e (s e)*).
# &e
#   Succeed if e can be parsed, without consuming any input.
# !e
#   Fail if e can be parsed, without consuming any input.
# ~
#   Commit to the current alternative, even if it fails to parse.
# &&e
#   Eager parse e. The parser will not backtrack and will immediately
#   fail with SyntaxError if e cannot be parsed.
#

# STARTING RULES
# ==============

file[mod_ty]: a=[statements] ENDMARKER @{ _PyPegen_make_module(p, a) @}
interactive[mod_ty]: a=statement_newline @{ _PyAST_Interactive(a, p->arena) @}
eval[mod_ty]: a=expressions NEWLINE* ENDMARKER @{ _PyAST_Expression(a, p->arena) @}
func_type[mod_ty]: '(' a=[type_expressions] ')' '->' b=expression NEWLINE* ENDMARKER @{ _PyAST_FunctionType(a, b, p->arena) @}

# GENERAL STATEMENTS
# ==================

statements[asdl_stmt_seq*]: a=statement+ @{ (asdl_stmt_seq*)_PyPegen_seq_flatten(p, a) @}

statement[asdl_stmt_seq*]:
    | a=compound_stmt @{ _PyPegen_register_stmts(p ,
                           (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a)
                        ) @}
    | a[asdl_stmt_seq*]=simple_stmts @{ a @}

single_compound_stmt[asdl_stmt_seq*]:
    | a=compound_stmt @{
        _PyPegen_register_stmts(p, (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a)) @}

statement_newline[asdl_stmt_seq*]:
    | a=single_compound_stmt NEWLINE @{ a @}
    | simple_stmts
    | NEWLINE @{ (asdl_stmt_seq*)_PyPegen_singleton_seq(p, CHECK(stmt_ty, _PyAST_Pass(EXTRA))) @}
    | ENDMARKER @{ _PyPegen_interactive_exit(p) @}

simple_stmts[asdl_stmt_seq*]:
    | a=simple_stmt !';' NEWLINE @{ (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a) @} # Not needed, there for speedup
    | a[asdl_stmt_seq*]=';'.simple_stmt+ [';'] NEWLINE @{ a @}

# NOTE: assignment MUST precede expression, else parsing a simple assignment
# will throw a SyntaxError.
simple_stmt[stmt_ty] (memo):
    | assignment
    | &"type" type_alias
    | e=star_expressions @{ _PyAST_Expr(e, EXTRA) @}
    | &'return' return_stmt
    | &('import' | 'from') import_stmt
    | &'raise' raise_stmt
    | &'pass' pass_stmt
    | &'del' del_stmt
    | &'yield' yield_stmt
    | &'assert' assert_stmt
    | &'break' break_stmt
    | &'continue' continue_stmt
    | &'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
    | match_stmt

# SIMPLE STATEMENTS
# =================

# 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(
            stmt_ty,
            6,
            "Variable annotation syntax is",
            _PyAST_AnnAssign(CHECK(expr_ty, _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(stmt_ty, 6, "Variable annotations syntax is", _PyAST_AnnAssign(a, b, c, 0, EXTRA)) @}
    | a[asdl_expr_seq*]=(z=star_targets '=' @{ z @})+ b=annotated_rhs !'=' tc=[TYPE_COMMENT] @{
         _PyAST_Assign(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) @}
    | a=single_target b=augassign ~ c=annotated_rhs @{
         _PyAST_AugAssign(a, b->kind, c, EXTRA) @}
    | invalid_assignment

annotated_rhs[expr_ty]: yield_expr | star_expressions

augassign[AugOperator*]:
    | '+=' @{ _PyPegen_augoperator(p, Add) @}
    | '-=' @{ _PyPegen_augoperator(p, Sub) @}
    | '*=' @{ _PyPegen_augoperator(p, Mult) @}
    | '@@=' @{ CHECK_VERSION(AugOperator*, 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) @}

return_stmt[stmt_ty]:
    | 'return' a=[star_expressions] @{ _PyAST_Return(a, EXTRA) @}

raise_stmt[stmt_ty]:
    | 'raise' a=expression b=['from' z=expression @{ z @}] @{ _PyAST_Raise(a, b, EXTRA) @}
    | 'raise' @{ _PyAST_Raise(NULL, NULL, EXTRA) @}

pass_stmt[stmt_ty]:
    | 'pass' @{ _PyAST_Pass(EXTRA) @}

break_stmt[stmt_ty]:
    | 'break' @{ _PyAST_Break(EXTRA) @}

continue_stmt[stmt_ty]:
    | 'continue' @{ _PyAST_Continue(EXTRA) @}

global_stmt[stmt_ty]: 'global' a[asdl_expr_seq*]=','.NAME+ @{
    _PyAST_Global(CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p, a)), EXTRA) @}

nonlocal_stmt[stmt_ty]: 'nonlocal' a[asdl_expr_seq*]=','.NAME+ @{
    _PyAST_Nonlocal(CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p, a)), EXTRA) @}

del_stmt[stmt_ty]:
    | 'del' a=del_targets &(';' | NEWLINE) @{ _PyAST_Delete(a, EXTRA) @}
    | invalid_del_stmt

yield_stmt[stmt_ty]: y=yield_expr @{ _PyAST_Expr(y, EXTRA) @}

assert_stmt[stmt_ty]: 'assert' a=expression b=[',' z=expression @{ z @}] @{ _PyAST_Assert(a, b, EXTRA) @}

import_stmt[stmt_ty]:
    | invalid_import
    | import_name
    | import_from

# Import statements
# -----------------

import_name[stmt_ty]: 'import' a=dotted_as_names @{ _PyAST_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 @{
        _PyPegen_checked_future_import(p, b->v.Name.id, c, _PyPegen_seq_count_dots(a), EXTRA) @}
    | 'from' a=('.' | '...')+ 'import' b=import_from_targets @{
        _PyAST_ImportFrom(NULL, b, _PyPegen_seq_count_dots(a), EXTRA) @}
import_from_targets[asdl_alias_seq*]:
    | '(' a=import_from_as_names [','] ')' @{ a @}
    | import_from_as_names !','
    | '*' @{ (asdl_alias_seq*)_PyPegen_singleton_seq(p, CHECK(alias_ty, _PyPegen_alias_for_star(p, EXTRA))) @}
    | invalid_import_from_targets
import_from_as_names[asdl_alias_seq*]:
    | a[asdl_alias_seq*]=','.import_from_as_name+ @{ a @}
import_from_as_name[alias_ty]:
    | invalid_import_from_as_name
    | a=NAME b=['as' z=NAME @{ z @}] @{ _PyAST_alias(
        a->v.Name.id, (b) ? ((expr_ty) b)->v.Name.id : NULL, EXTRA) @}

dotted_as_names[asdl_alias_seq*]:
    | a[asdl_alias_seq*]=','.dotted_as_name+ @{ a @}
dotted_as_name[alias_ty]:
    | invalid_dotted_as_name
    | a=dotted_name b=['as' z=NAME @{ z @}] @{ _PyAST_alias(
        a->v.Name.id, (b) ? ((expr_ty) b)->v.Name.id : NULL, EXTRA) @}

dotted_name[expr_ty]:
    | a=dotted_name '.' b=NAME @{ _PyPegen_join_names_with_dot(p, a, b) @}
    | NAME

# COMPOUND STATEMENTS
# ===================

# Common elements
# ---------------

block[asdl_stmt_seq*] (memo):
    | NEWLINE INDENT a=statements DEDENT @{ a @}
    | simple_stmts
    | invalid_block

decorators[asdl_expr_seq*]: a[asdl_expr_seq*]=('@@' f=named_expression NEWLINE @{ f @})+ @{ a @}

# Class definitions
# -----------------

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]:
    | invalid_class_def_raw
    | 'class' a=NAME t=[type_params] b=['(' z=[arguments] ')' @{ z @}] ':' c=block @{
        _PyAST_ClassDef(a->v.Name.id,
                     (b) ? ((expr_ty) b)->v.Call.args : NULL,
                     (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
                     c, NULL, t, EXTRA) @}

# Function definitions
# --------------------

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]:
    | invalid_def_raw
    | 'def' n=NAME t=[type_params] '(' params=[params] ')' a=['->' z=expression @{ z @}] ':' tc=[func_type_comment] b=block @{
        _PyAST_FunctionDef(n->v.Name.id,
                        (params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)),
                        b, NULL, a, NEW_TYPE_COMMENT(p, tc), t, EXTRA) @}
    | 'async' 'def' n=NAME t=[type_params] '(' params=[params] ')' a=['->' z=expression @{ z @}] ':' tc=[func_type_comment] b=block @{
        CHECK_VERSION(
            stmt_ty,
            5,
            "Async functions are",
            _PyAST_AsyncFunctionDef(n->v.Name.id,
                            (params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)),
                            b, NULL, a, NEW_TYPE_COMMENT(p, tc), t, EXTRA)
        ) @}

# Function parameters
# -------------------

params[arguments_ty]:
    | invalid_parameters
    | parameters

parameters[arguments_ty]:
    | a=slash_no_default b[asdl_arg_seq*]=param_no_default* c=param_with_default* d=[star_etc] @{
        CHECK_VERSION(arguments_ty, 8, "Positional-only parameters are", _PyPegen_make_arguments(p, a, NULL, b, c, d)) @}
    | a=slash_with_default b=param_with_default* c=[star_etc] @{
        CHECK_VERSION(arguments_ty, 8, "Positional-only parameters are", _PyPegen_make_arguments(p, NULL, a, NULL, b, c)) @}
    | a[asdl_arg_seq*]=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_arg_seq*]:
    | a[asdl_arg_seq*]=param_no_default+ '/' ',' @{ a @}
    | a[asdl_arg_seq*]=param_no_default+ '/' &')' @{ a @}
slash_with_default[SlashWithDefault*]:
    | a=param_no_default* b=param_with_default+ '/' ',' @{ _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) @}
    | a=param_no_default* b=param_with_default+ '/' &')' @{ _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) @}

star_etc[StarEtc*]:
    | invalid_star_etc
    | '*' a=param_no_default b=param_maybe_default* c=[kwds] @{
        _PyPegen_star_etc(p, a, b, c) @}
    | '*' a=param_no_default_star_annotation 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) @}

kwds[arg_ty]:
    | invalid_kwds
    | '**' 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_no_default_star_annotation[arg_ty]:
    | a=param_star_annotation ',' tc=TYPE_COMMENT? @{ _PyPegen_add_type_comment_to_arg(p, a, tc) @}
    | a=param_star_annotation 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? @{ _PyAST_arg(a->v.Name.id, b, NULL, EXTRA) @}
param_star_annotation[arg_ty]: a=NAME b=star_annotation @{ _PyAST_arg(a->v.Name.id, b, NULL, EXTRA) @}
annotation[expr_ty]: ':' a=expression @{ a @}
star_annotation[expr_ty]: ':' a=star_expression @{ a @}
default[expr_ty]: '=' a=expression @{ a @} | invalid_default

# If statement
# ------------

if_stmt[stmt_ty]:
    | invalid_if_stmt
    | 'if' a=named_expression ':' b=block c=elif_stmt @{
        _PyAST_If(a, b, CHECK(asdl_stmt_seq*, _PyPegen_singleton_seq(p, c)), EXTRA) @}
    | 'if' a=named_expression ':' b=block c=[else_block] @{ _PyAST_If(a, b, c, EXTRA) @}
elif_stmt[stmt_ty]:
    | invalid_elif_stmt
    | 'elif' a=named_expression ':' b=block c=elif_stmt @{
        _PyAST_If(a, b, CHECK(asdl_stmt_seq*, _PyPegen_singleton_seq(p, c)), EXTRA) @}
    | 'elif' a=named_expression ':' b=block c=[else_block] @{ _PyAST_If(a, b, c, EXTRA) @}
else_block[asdl_stmt_seq*]:
    | invalid_else_stmt
    | 'else' &&':' b=block @{ b @}

# While statement
# ---------------

while_stmt[stmt_ty]:
    | invalid_while_stmt
    | 'while' a=named_expression ':' b=block c=[else_block] @{ _PyAST_While(a, b, c, EXTRA) @}

# For statement
# -------------

for_stmt[stmt_ty]:
    | invalid_for_stmt
    | 'for' t=star_targets 'in' ~ ex=star_expressions ':' tc=[TYPE_COMMENT] b=block el=[else_block] @{
        _PyAST_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(stmt_ty, 5, "Async for loops are", _PyAST_AsyncFor(t, ex, b, el, NEW_TYPE_COMMENT(p, tc), EXTRA)) @}
    | invalid_for_target

# With statement
# --------------

with_stmt[stmt_ty]:
    | invalid_with_stmt_indent
    | 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' tc=[TYPE_COMMENT] b=block @{
       _PyAST_With(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) @}
    | 'with' a[asdl_withitem_seq*]=','.with_item+ ':' tc=[TYPE_COMMENT] b=block @{
        _PyAST_With(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) @}
    | 'async' 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' b=block @{
       CHECK_VERSION(stmt_ty, 5, "Async with statements are", _PyAST_AsyncWith(a, b, NULL, EXTRA)) @}
    | 'async' 'with' a[asdl_withitem_seq*]=','.with_item+ ':' tc=[TYPE_COMMENT] b=block @{
       CHECK_VERSION(stmt_ty, 5, "Async with statements are", _PyAST_AsyncWith(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA)) @}
    | invalid_with_stmt

with_item[withitem_ty]:
    | e=expression 'as' t=star_target &(',' | ')' | ':') @{ _PyAST_withitem(e, t, p->arena) @}
    | invalid_with_item
    | e=expression @{ _PyAST_withitem(e, NULL, p->arena) @}

# Try statement
# -------------

try_stmt[stmt_ty]:
    | invalid_try_stmt
    | 'try' &&':' b=block f=finally_block @{ _PyAST_Try(b, NULL, NULL, f, EXTRA) @}
    | 'try' &&':' b=block ex[asdl_excepthandler_seq*]=except_block+ el=[else_block] f=[finally_block] @{ _PyAST_Try(b, ex, el, f, EXTRA) @}
    | 'try' &&':' b=block ex[asdl_excepthandler_seq*]=except_star_block+ el=[else_block] f=[finally_block] @{
        CHECK_VERSION(stmt_ty, 11, "Exception groups are",
                      _PyAST_TryStar(b, ex, el, f, EXTRA)) @}


# Except statement
# ----------------

except_block[excepthandler_ty]:
    | invalid_except_stmt_indent
    | 'except' e=expression ':' b=block @{
        _PyAST_ExceptHandler(e, NULL, b, EXTRA) @}
    | 'except' e=expression 'as' t=NAME ':' b=block @{
        _PyAST_ExceptHandler(e, ((expr_ty) t)->v.Name.id, b, EXTRA) @}
    | 'except' e=expressions ':' b=block @{
        CHECK_VERSION(
            excepthandler_ty,
            14,
            "except expressions without parentheses are",
            _PyAST_ExceptHandler(e, NULL, b, EXTRA)) @}
    | 'except' ':' b=block @{ _PyAST_ExceptHandler(NULL, NULL, b, EXTRA) @}
    | invalid_except_stmt
except_star_block[excepthandler_ty]:
    | invalid_except_star_stmt_indent
    | 'except' '*' e=expression ':' b=block @{
        _PyAST_ExceptHandler(e, NULL, b, EXTRA) @}
    | 'except' '*' e=expression 'as' t=NAME ':' b=block @{
        _PyAST_ExceptHandler(e, ((expr_ty) t)->v.Name.id, b, EXTRA) @}
    | 'except' '*' e=expressions ':' b=block @{
        CHECK_VERSION(
            excepthandler_ty,
            14,
            "except expressions without parentheses are",
            _PyAST_ExceptHandler(e,  NULL, b, EXTRA)) @}
    | invalid_except_star_stmt
finally_block[asdl_stmt_seq*]:
    | invalid_finally_stmt
    | 'finally' &&':' a=block @{ a @}

# Match statement
# ---------------

match_stmt[stmt_ty]:
    | "match" subject=subject_expr ':' NEWLINE INDENT cases[asdl_match_case_seq*]=case_block+ DEDENT @{
        CHECK_VERSION(stmt_ty, 10, "Pattern matching is", _PyAST_Match(subject, cases, EXTRA)) @}
    | invalid_match_stmt

subject_expr[expr_ty]:
    | value=star_named_expression ',' values=star_named_expressions? @{
        _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, value, values)), Load, EXTRA) @}
    | named_expression

case_block[match_case_ty]:
    | invalid_case_block
    | "case" pattern=patterns guard=guard? ':' body=block @{
        _PyAST_match_case(pattern, guard, body, p->arena) @}

guard[expr_ty]: 'if' guard=named_expression @{ guard @}

patterns[pattern_ty]:
    | patterns[asdl_pattern_seq*]=open_sequence_pattern @{
        _PyAST_MatchSequence(patterns, EXTRA) @}
    | pattern

pattern[pattern_ty]:
    | as_pattern
    | or_pattern

as_pattern[pattern_ty]:
    | pattern=or_pattern 'as' target=pattern_capture_target @{
        _PyAST_MatchAs(pattern, target->v.Name.id, EXTRA) @}
    | invalid_as_pattern

or_pattern[pattern_ty]:
    | patterns[asdl_pattern_seq*]='|'.closed_pattern+ @{
        asdl_seq_LEN(patterns) == 1 ? asdl_seq_GET(patterns, 0) : _PyAST_MatchOr(patterns, EXTRA) @}

closed_pattern[pattern_ty] (memo):
    | literal_pattern
    | capture_pattern
    | wildcard_pattern
    | value_pattern
    | group_pattern
    | sequence_pattern
    | mapping_pattern
    | class_pattern

# Literal patterns are used for equality and identity constraints
literal_pattern[pattern_ty]:
    | value=signed_number !('+' | '-') @{ _PyAST_MatchValue(value, EXTRA) @}
    | value=complex_number @{ _PyAST_MatchValue(value, EXTRA) @}
    | value=strings @{ _PyAST_MatchValue(value, EXTRA) @}
    | 'None' @{ _PyAST_MatchSingleton(Py_None, EXTRA) @}
    | 'True' @{ _PyAST_MatchSingleton(Py_True, EXTRA) @}
    | 'False' @{ _PyAST_MatchSingleton(Py_False, EXTRA) @}

# Literal expressions are used to restrict permitted mapping pattern keys
literal_expr[expr_ty]:
    | signed_number !('+' | '-')
    | complex_number
    | &(STRING|FSTRING_START|TSTRING_START) strings
    | 'None' @{ _PyAST_Constant(Py_None, NULL, EXTRA) @}
    | 'True' @{ _PyAST_Constant(Py_True, NULL, EXTRA) @}
    | 'False' @{ _PyAST_Constant(Py_False, NULL, EXTRA) @}

complex_number[expr_ty]:
    | real=signed_real_number '+' imag=imaginary_number @{
        _PyAST_BinOp(real, Add, imag, EXTRA) @}
    | real=signed_real_number '-' imag=imaginary_number  @{
        _PyAST_BinOp(real, Sub, imag, EXTRA) @}

signed_number[expr_ty]:
    | NUMBER
    | '-' number=NUMBER @{ _PyAST_UnaryOp(USub, number, EXTRA) @}

signed_real_number[expr_ty]:
    | real_number
    | '-' real=real_number @{ _PyAST_UnaryOp(USub, real, EXTRA) @}

real_number[expr_ty]:
    | real=NUMBER @{ _PyPegen_ensure_real(p, real) @}

imaginary_number[expr_ty]:
    | imag=NUMBER @{ _PyPegen_ensure_imaginary(p, imag) @}

capture_pattern[pattern_ty]:
    | target=pattern_capture_target @{ _PyAST_MatchAs(NULL, target->v.Name.id, EXTRA) @}

pattern_capture_target[expr_ty]:
    | !"_" name=NAME !('.' | '(' | '=') @{
        _PyPegen_set_expr_context(p, name, Store) @}

wildcard_pattern[pattern_ty]:
    | "_" @{ _PyAST_MatchAs(NULL, NULL, EXTRA) @}

value_pattern[pattern_ty]:
    | attr=attr !('.' | '(' | '=') @{ _PyAST_MatchValue(attr, EXTRA) @}

attr[expr_ty]:
    | value=name_or_attr '.' attr=NAME @{
        _PyAST_Attribute(value, attr->v.Name.id, Load, EXTRA) @}

name_or_attr[expr_ty]:
    | attr
    | NAME

group_pattern[pattern_ty]:
    | '(' pattern=pattern ')' @{ pattern @}

sequence_pattern[pattern_ty]:
    | '[' patterns=maybe_sequence_pattern? ']' @{ _PyAST_MatchSequence(patterns, EXTRA) @}
    | '(' patterns=open_sequence_pattern? ')' @{ _PyAST_MatchSequence(patterns, EXTRA) @}

open_sequence_pattern[asdl_seq*]:
    | pattern=maybe_star_pattern ',' patterns=maybe_sequence_pattern? @{
        _PyPegen_seq_insert_in_front(p, pattern, patterns) @}

maybe_sequence_pattern[asdl_seq*]:
    | patterns=','.maybe_star_pattern+ ','? @{ patterns @}

maybe_star_pattern[pattern_ty]:
    | star_pattern
    | pattern

star_pattern[pattern_ty] (memo):
    | '*' target=pattern_capture_target @{
        _PyAST_MatchStar(target->v.Name.id, EXTRA) @}
    | '*' wildcard_pattern @{
        _PyAST_MatchStar(NULL, EXTRA) @}

mapping_pattern[pattern_ty]:
    | '@{' '@}' @{
        _PyAST_MatchMapping(NULL, NULL, NULL, EXTRA) @}
    | '@{' rest=double_star_pattern ','? '@}' @{
        _PyAST_MatchMapping(NULL, NULL, rest->v.Name.id, EXTRA) @}
    | '@{' items=items_pattern ',' rest=double_star_pattern ','? '@}' @{
        _PyAST_MatchMapping(
            CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, items)),
            CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, items)),
            rest->v.Name.id,
            EXTRA) @}
    | '@{' items=items_pattern ','? '@}' @{
        _PyAST_MatchMapping(
            CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, items)),
            CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, items)),
            NULL,
            EXTRA) @}

items_pattern[asdl_seq*]:
    | ','.key_value_pattern+

key_value_pattern[KeyPatternPair*]:
    | key=(literal_expr | attr) ':' pattern=pattern @{
        _PyPegen_key_pattern_pair(p, key, pattern) @}

double_star_pattern[expr_ty]:
    | '**' target=pattern_capture_target @{ target @}

class_pattern[pattern_ty]:
    | cls=name_or_attr '(' ')' @{
        _PyAST_MatchClass(cls, NULL, NULL, NULL, EXTRA) @}
    | cls=name_or_attr '(' patterns=positional_patterns ','? ')' @{
        _PyAST_MatchClass(cls, patterns, NULL, NULL, EXTRA) @}
    | cls=name_or_attr '(' keywords=keyword_patterns ','? ')' @{
        _PyAST_MatchClass(
            cls, NULL,
            CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p,
                CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, keywords)))),
            CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, keywords)),
            EXTRA) @}
    | cls=name_or_attr '(' patterns=positional_patterns ',' keywords=keyword_patterns ','? ')' @{
        _PyAST_MatchClass(
            cls,
            patterns,
            CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p,
                CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, keywords)))),
            CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, keywords)),
            EXTRA) @}
    | invalid_class_pattern

positional_patterns[asdl_pattern_seq*]:
    | args[asdl_pattern_seq*]=','.pattern+ @{ args @}

keyword_patterns[asdl_seq*]:
    | ','.keyword_pattern+

keyword_pattern[KeyPatternPair*]:
    | arg=NAME '=' value=pattern @{ _PyPegen_key_pattern_pair(p, arg, value) @}

# Type statement
# ---------------

type_alias[stmt_ty]:
    | "type" n=NAME t=[type_params] '=' b=expression @{
        CHECK_VERSION(stmt_ty, 12, "Type statement is",
        _PyAST_TypeAlias(CHECK(expr_ty, _PyPegen_set_expr_context(p, n, Store)), t, b, EXTRA)) @}

# Type parameter declaration
# --------------------------

type_params[asdl_type_param_seq*]:
    | invalid_type_params
    | '[' t=type_param_seq ']' @{
        CHECK_VERSION(asdl_type_param_seq *, 12, "Type parameter lists are", t) @}

type_param_seq[asdl_type_param_seq*]: a[asdl_type_param_seq*]=','.type_param+ [','] @{ a @}

type_param[type_param_ty] (memo):
    | a=NAME b=[type_param_bound] c=[type_param_default] @{ _PyAST_TypeVar(a->v.Name.id, b, c, EXTRA) @}
    | invalid_type_param
    | '*' a=NAME b=[type_param_starred_default] @{ _PyAST_TypeVarTuple(a->v.Name.id, b, EXTRA) @}
    | '**' a=NAME b=[type_param_default] @{ _PyAST_ParamSpec(a->v.Name.id, b, EXTRA) @}

type_param_bound[expr_ty]: ':' e=expression @{ e @}
type_param_default[expr_ty]: '=' e=expression @{
    CHECK_VERSION(expr_ty, 13, "Type parameter defaults are", e) @}
type_param_starred_default[expr_ty]: '=' e=star_expression @{
    CHECK_VERSION(expr_ty, 13, "Type parameter defaults are", e) @}

# EXPRESSIONS
# -----------

expressions[expr_ty]:
    | a=expression b=(',' c=expression @{ c @})+ [','] @{
        _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) @}
    | a=expression ',' @{ _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_singleton_seq(p, a)), Load, EXTRA) @}
    | expression

expression[expr_ty] (memo):
    | invalid_expression
    | invalid_legacy_expression
    | a=disjunction 'if' b=disjunction 'else' c=expression @{ _PyAST_IfExp(b, a, c, EXTRA) @}
    | disjunction
    | lambdef

yield_expr[expr_ty]:
    | 'yield' 'from' a=expression @{ _PyAST_YieldFrom(a, EXTRA) @}
    | 'yield' a=[star_expressions] @{ _PyAST_Yield(a, EXTRA) @}

star_expressions[expr_ty]:
    | a=star_expression b=(',' c=star_expression @{ c @})+ [','] @{
        _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) @}
    | a=star_expression ',' @{ _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_singleton_seq(p, a)), Load, EXTRA) @}
    | star_expression

star_expression[expr_ty] (memo):
    | '*' a=bitwise_or @{ _PyAST_Starred(a, Load, EXTRA) @}
    | expression

star_named_expressions[asdl_expr_seq*]: a[asdl_expr_seq*]=','.star_named_expression+ [','] @{ a @}

star_named_expression[expr_ty]:
    | '*' a=bitwise_or @{ _PyAST_Starred(a, Load, EXTRA) @}
    | named_expression

assignment_expression[expr_ty]:
    | a=NAME ':=' ~ b=expression @{
        CHECK_VERSION(expr_ty, 8, "Assignment expressions are",
        _PyAST_NamedExpr(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, Store)), b, EXTRA)) @}

named_expression[expr_ty]:
    | assignment_expression
    | invalid_named_expression
    | expression !':='

disjunction[expr_ty] (memo):
    | a=conjunction b=('or' c=conjunction @{ c @})+ @{ _PyAST_BoolOp(
        Or,
        CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),
        EXTRA) @}
    | conjunction

conjunction[expr_ty] (memo):
    | a=inversion b=('and' c=inversion @{ c @})+ @{ _PyAST_BoolOp(
        And,
        CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),
        EXTRA) @}
    | inversion

inversion[expr_ty] (memo):
    | 'not' a=inversion @{ _PyAST_UnaryOp(Not, a, EXTRA) @}
    | comparison

# Comparison operators
# --------------------

comparison[expr_ty]:
    | a=bitwise_or b=compare_op_bitwise_or_pair+ @{
        _PyAST_Compare(
            a,
            CHECK(asdl_int_seq*, _PyPegen_get_cmpops(p, b)),
            CHECK(asdl_expr_seq*, _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 operators
# -----------------

bitwise_or[expr_ty]:
    | a=bitwise_or '|' b=bitwise_xor @{ _PyAST_BinOp(a, BitOr, b, EXTRA) @}
    | bitwise_xor

bitwise_xor[expr_ty]:
    | a=bitwise_xor '^' b=bitwise_and @{ _PyAST_BinOp(a, BitXor, b, EXTRA) @}
    | bitwise_and

bitwise_and[expr_ty]:
    | a=bitwise_and '&' b=shift_expr @{ _PyAST_BinOp(a, BitAnd, b, EXTRA) @}
    | shift_expr

shift_expr[expr_ty]:
    | a=shift_expr '<<' b=sum @{ _PyAST_BinOp(a, LShift, b, EXTRA) @}
    | a=shift_expr '>>' b=sum @{ _PyAST_BinOp(a, RShift, b, EXTRA) @}
    | invalid_arithmetic
    | sum

# Arithmetic operators
# --------------------

sum[expr_ty]:
    | a=sum '+' b=term @{ _PyAST_BinOp(a, Add, b, EXTRA) @}
    | a=sum '-' b=term @{ _PyAST_BinOp(a, Sub, b, EXTRA) @}
    | term

term[expr_ty]:
    | a=term '*' b=factor @{ _PyAST_BinOp(a, Mult, b, EXTRA) @}
    | a=term '/' b=factor @{ _PyAST_BinOp(a, Div, b, EXTRA) @}
    | a=term '//' b=factor @{ _PyAST_BinOp(a, FloorDiv, b, EXTRA) @}
    | a=term '%' b=factor @{ _PyAST_BinOp(a, Mod, b, EXTRA) @}
    | a=term '@@' b=factor @{ CHECK_VERSION(expr_ty, 5, "The '@@' operator is", _PyAST_BinOp(a, MatMult, b, EXTRA)) @}
    | invalid_factor
    | factor

factor[expr_ty] (memo):
    | '+' a=factor @{ _PyAST_UnaryOp(UAdd, a, EXTRA) @}
    | '-' a=factor @{ _PyAST_UnaryOp(USub, a, EXTRA) @}
    | '~' a=factor @{ _PyAST_UnaryOp(Invert, a, EXTRA) @}
    | power

power[expr_ty]:
    | a=await_primary '**' b=factor @{ _PyAST_BinOp(a, Pow, b, EXTRA) @}
    | await_primary

# Primary elements
# ----------------

# Primary elements are things like "obj.something.something", "obj[something]", "obj(something)", "obj" ...

await_primary[expr_ty] (memo):
    | 'await' a=primary @{ CHECK_VERSION(expr_ty, 5, "Await expressions are", _PyAST_Await(a, EXTRA)) @}
    | primary

primary[expr_ty]:
    | a=primary '.' b=NAME @{ _PyAST_Attribute(a, b->v.Name.id, Load, EXTRA) @}
    | a=primary b=genexp @{ _PyAST_Call(a, CHECK(asdl_expr_seq*, (asdl_expr_seq*)_PyPegen_singleton_seq(p, b)), NULL, EXTRA) @}
    | a=primary '(' b=[arguments] ')' @{
        _PyAST_Call(a,
                 (b) ? ((expr_ty) b)->v.Call.args : NULL,
                 (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
                 EXTRA) @}
    | a=primary '[' b=slices ']' @{ _PyAST_Subscript(a, b, Load, EXTRA) @}
    | atom

slices[expr_ty]:
    | a=slice !',' @{ a @}
    | a[asdl_expr_seq*]=','.(slice | starred_expression)+ [','] @{ _PyAST_Tuple(a, Load, EXTRA) @}

slice[expr_ty]:
    | a=[expression] ':' b=[expression] c=[':' d=[expression] @{ d @}] @{ _PyAST_Slice(a, b, c, EXTRA) @}
    | a=named_expression @{ a @}

atom[expr_ty]:
    | NAME
    | 'True' @{ _PyAST_Constant(Py_True, NULL, EXTRA) @}
    | 'False' @{ _PyAST_Constant(Py_False, NULL, EXTRA) @}
    | 'None' @{ _PyAST_Constant(Py_None, NULL, EXTRA) @}
    | &(STRING|FSTRING_START|TSTRING_START) strings
    | NUMBER
    | &'(' (tuple | group | genexp)
    | &'[' (list | listcomp)
    | &'@{' (dict | set | dictcomp | setcomp)
    | '...' @{ _PyAST_Constant(Py_Ellipsis, NULL, EXTRA) @}

group[expr_ty]:
    | '(' a=(yield_expr | named_expression) ')' @{ a @}
    | invalid_group

# Lambda functions
# ----------------

lambdef[expr_ty]:
    | 'lambda' a=[lambda_params] ':' b=expression @{
        _PyAST_Lambda((a) ? a : CHECK(arguments_ty, _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[asdl_arg_seq*]=lambda_param_no_default* c=lambda_param_with_default* d=[lambda_star_etc] @{
        CHECK_VERSION(arguments_ty, 8, "Positional-only parameters are", _PyPegen_make_arguments(p, a, NULL, b, c, d)) @}
    | a=lambda_slash_with_default b=lambda_param_with_default* c=[lambda_star_etc] @{
        CHECK_VERSION(arguments_ty, 8, "Positional-only parameters are", _PyPegen_make_arguments(p, NULL, a, NULL, b, c)) @}
    | a[asdl_arg_seq*]=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_arg_seq*]:
    | a[asdl_arg_seq*]=lambda_param_no_default+ '/' ',' @{ a @}
    | a[asdl_arg_seq*]=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, (asdl_arg_seq *)a, b) @}
    | a=lambda_param_no_default* b=lambda_param_with_default+ '/' &':' @{ _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) @}

lambda_star_etc[StarEtc*]:
    | invalid_lambda_star_etc
    | '*' 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) @}

lambda_kwds[arg_ty]:
    | invalid_lambda_kwds
    | '**' 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 @{ _PyAST_arg(a->v.Name.id, NULL, NULL, EXTRA) @}

# LITERALS
# ========

fstring_middle[expr_ty]:
    | fstring_replacement_field
    | t=FSTRING_MIDDLE @{ _PyPegen_constant_from_token(p, t) @}
fstring_replacement_field[expr_ty]:
    | '@{' a=annotated_rhs debug_expr='='? conversion=[fstring_conversion] format=[fstring_full_format_spec] rbrace='@}' @{
        _PyPegen_formatted_value(p, a, debug_expr, conversion, format, rbrace, EXTRA) @}
    | invalid_fstring_replacement_field
fstring_conversion[ResultTokenWithMetadata*]:
    | conv_token="!" conv=NAME @{ _PyPegen_check_fstring_conversion(p, conv_token, conv) @}
fstring_full_format_spec[ResultTokenWithMetadata*]:
    | colon=':' spec=fstring_format_spec* @{ _PyPegen_setup_full_format_spec(p, colon, (asdl_expr_seq *) spec, EXTRA) @}
fstring_format_spec[expr_ty]:
    | t=FSTRING_MIDDLE @{ _PyPegen_decoded_constant_from_token(p, t) @}
    | fstring_replacement_field
fstring[expr_ty]:
    | a=FSTRING_START b=fstring_middle* c=FSTRING_END @{ _PyPegen_joined_str(p, a, (asdl_expr_seq*)b, c) @}

tstring_format_spec_replacement_field[expr_ty]:
    | '@{' a=annotated_rhs debug_expr='='? conversion=[fstring_conversion] format=[tstring_full_format_spec] rbrace='@}' @{
        _PyPegen_formatted_value(p, a, debug_expr, conversion, format, rbrace, EXTRA) @}
    | invalid_tstring_replacement_field
tstring_format_spec[expr_ty]:
    | t=TSTRING_MIDDLE @{ _PyPegen_decoded_constant_from_token(p, t) @}
    | tstring_format_spec_replacement_field
tstring_full_format_spec[ResultTokenWithMetadata*]:
    | colon=':' spec=tstring_format_spec* @{ _PyPegen_setup_full_format_spec(p, colon, (asdl_expr_seq *) spec, EXTRA) @}
tstring_replacement_field[expr_ty]:
    | '@{' a=annotated_rhs debug_expr='='? conversion=[fstring_conversion] format=[tstring_full_format_spec] rbrace='@}' @{
        _PyPegen_interpolation(p, a, debug_expr, conversion, format, rbrace, EXTRA) @}
    | invalid_tstring_replacement_field
tstring_middle[expr_ty]:
    | tstring_replacement_field
    | t=TSTRING_MIDDLE @{ _PyPegen_constant_from_token(p, t) @}
tstring[expr_ty] (memo):
    | a=TSTRING_START b=tstring_middle* c=TSTRING_END @{
        CHECK_VERSION(
            expr_ty,
            14,
            "t-strings are",
            _PyPegen_template_str(p, a, (asdl_expr_seq*)b, c)) @}

string[expr_ty]: s[Token*]=STRING @{ _PyPegen_constant_from_string(p, s) @}
strings[expr_ty] (memo):
    | invalid_string_tstring_concat
    | a[asdl_expr_seq*]=(fstring|string)+ @{ _PyPegen_concatenate_strings(p, a, EXTRA) @}
    | a[asdl_expr_seq*]=tstring+ @{ _PyPegen_concatenate_tstrings(p, a, EXTRA) @}

list[expr_ty]:
    | '[' a=[star_named_expressions] ']' @{ _PyAST_List(a, Load, EXTRA) @}

tuple[expr_ty]:
    | '(' a=[y=star_named_expression ',' z=[star_named_expressions] @{ _PyPegen_seq_insert_in_front(p, y, z) @} ] ')' @{
        _PyAST_Tuple(a, Load, EXTRA) @}

set[expr_ty]: '@{' a=star_named_expressions '@}' @{ _PyAST_Set(a, EXTRA) @}

# Dicts
# -----

dict[expr_ty]:
    | '@{' a=[double_starred_kvpairs] '@}' @{
        _PyAST_Dict(
            CHECK(asdl_expr_seq*, _PyPegen_get_keys(p, a)),
            CHECK(asdl_expr_seq*, _PyPegen_get_values(p, a)),
            EXTRA) @}
    | '@{' invalid_double_starred_kvpairs '@}'

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) @}

# Comprehensions & Generators
# ---------------------------

for_if_clauses[asdl_comprehension_seq*]:
    | a[asdl_comprehension_seq*]=for_if_clause+ @{ a @}

for_if_clause[comprehension_ty]:
    | 'async' 'for' a=star_targets 'in' ~ b=disjunction c[asdl_expr_seq*]=('if' z=disjunction @{ z @})* @{
        CHECK_VERSION(comprehension_ty, 6, "Async comprehensions are", _PyAST_comprehension(a, b, c, 1, p->arena)) @}
    | 'for' a=star_targets 'in' ~ b=disjunction c[asdl_expr_seq*]=('if' z=disjunction @{ z @})* @{
        _PyAST_comprehension(a, b, c, 0, p->arena) @}
    | invalid_for_if_clause
    | invalid_for_target

listcomp[expr_ty]:
    | '[' a=named_expression b=for_if_clauses ']' @{ _PyAST_ListComp(a, b, EXTRA) @}
    | invalid_comprehension

setcomp[expr_ty]:
    | '@{' a=named_expression b=for_if_clauses '@}' @{ _PyAST_SetComp(a, b, EXTRA) @}
    | invalid_comprehension

genexp[expr_ty]:
    | '(' a=( assignment_expression | expression !':=') b=for_if_clauses ')' @{ _PyAST_GeneratorExp(a, b, EXTRA) @}
    | invalid_comprehension

dictcomp[expr_ty]:
    | '@{' a=kvpair b=for_if_clauses '@}' @{ _PyAST_DictComp(a->key, a->value, b, EXTRA) @}
    | invalid_dict_comprehension

# FUNCTION CALL ARGUMENTS
# =======================

arguments[expr_ty] (memo):
    | a=args [','] &')' @{ a @}
    | invalid_arguments

args[expr_ty]:
    | a[asdl_expr_seq*]=','.(starred_expression | ( assignment_expression | expression !':=') !'=')+ b=[',' k=kwargs @{k@}] @{
        _PyPegen_collect_call_seqs(p, a, b, EXTRA) @}
    | a=kwargs @{ _PyAST_Call(_PyPegen_dummy_name(p),
                          CHECK_NULL_ALLOWED(asdl_expr_seq*, _PyPegen_seq_extract_starred_exprs(p, a)),
                          CHECK_NULL_ALLOWED(asdl_keyword_seq*, _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]:
    | invalid_starred_expression_unpacking
    | '*' a=expression @{ _PyAST_Starred(a, Load, EXTRA) @}
    | invalid_starred_expression

kwarg_or_starred[KeywordOrStarred*]:
    | invalid_kwarg
    | a=NAME '=' b=expression @{
        _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(a->v.Name.id, b, EXTRA)), 1) @}
    | a=starred_expression @{ _PyPegen_keyword_or_starred(p, a, 0) @}

kwarg_or_double_starred[KeywordOrStarred*]:
    | invalid_kwarg
    | a=NAME '=' b=expression @{
        _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(a->v.Name.id, b, EXTRA)), 1) @}
    | '**' a=expression @{ _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(NULL, a, EXTRA)), 1) @}

# ASSIGNMENT TARGETS
# ==================

# Generic targets
# ---------------

# 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 @})* [','] @{
        _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)), Store, EXTRA) @}

star_targets_list_seq[asdl_expr_seq*]: a[asdl_expr_seq*]=','.star_target+ [','] @{ a @}

star_targets_tuple_seq[asdl_expr_seq*]:
    | a=star_target b=(',' c=star_target @{ c @})+ [','] @{ (asdl_expr_seq*) _PyPegen_seq_insert_in_front(p, a, b) @}
    | a=star_target ',' @{ (asdl_expr_seq*) _PyPegen_singleton_seq(p, a) @}

star_target[expr_ty] (memo):
    | '*' a=(!'*' star_target) @{
        _PyAST_Starred(CHECK(expr_ty, _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 @{ _PyAST_Attribute(a, b->v.Name.id, Store, EXTRA) @}
    | a=t_primary '[' b=slices ']' !t_lookahead @{ _PyAST_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] ')' @{ _PyAST_Tuple(a, Store, EXTRA) @}
    | '[' a=[star_targets_list_seq] ']' @{ _PyAST_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 @{ _PyAST_Attribute(a, b->v.Name.id, Store, EXTRA) @}
    | a=t_primary '[' b=slices ']' !t_lookahead @{ _PyAST_Subscript(a, b, Store, EXTRA) @}

t_primary[expr_ty]:
    | a=t_primary '.' b=NAME &t_lookahead @{ _PyAST_Attribute(a, b->v.Name.id, Load, EXTRA) @}
    | a=t_primary '[' b=slices ']' &t_lookahead @{ _PyAST_Subscript(a, b, Load, EXTRA) @}
    | a=t_primary b=genexp &t_lookahead @{
        _PyAST_Call(a, CHECK(asdl_expr_seq*, (asdl_expr_seq*)_PyPegen_singleton_seq(p, b)), NULL, EXTRA) @}
    | a=t_primary '(' b=[arguments] ')' &t_lookahead @{
        _PyAST_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: '(' | '[' | '.'

# Targets for del statements
# --------------------------

del_targets[asdl_expr_seq*]: a[asdl_expr_seq*]=','.del_target+ [','] @{ a @}

del_target[expr_ty] (memo):
    | a=t_primary '.' b=NAME !t_lookahead @{ _PyAST_Attribute(a, b->v.Name.id, Del, EXTRA) @}
    | a=t_primary '[' b=slices ']' !t_lookahead @{ _PyAST_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] ')' @{ _PyAST_Tuple(a, Del, EXTRA) @}
    | '[' a=[del_targets] ']' @{ _PyAST_List(a, Del, EXTRA) @}

# TYPING ELEMENTS
# ---------------

# type_expressions allow */** but ignore them
type_expressions[asdl_expr_seq*]:
    | a=','.expression+ ',' '*' b=expression ',' '**' c=expression @{
        (asdl_expr_seq*)_PyPegen_seq_append_to_end(
            p,
            CHECK(asdl_seq*, _PyPegen_seq_append_to_end(p, a, b)),
            c) @}
    | a=','.expression+ ',' '*' b=expression @{ (asdl_expr_seq*)_PyPegen_seq_append_to_end(p, a, b) @}
    | a=','.expression+ ',' '**' b=expression @{ (asdl_expr_seq*)_PyPegen_seq_append_to_end(p, a, b) @}
    | '*' a=expression ',' '**' b=expression @{
        (asdl_expr_seq*)_PyPegen_seq_append_to_end(
            p,
            CHECK(asdl_seq*, _PyPegen_singleton_seq(p, a)),
            b) @}
    | '*' a=expression @{ (asdl_expr_seq*)_PyPegen_singleton_seq(p, a) @}
    | '**' a=expression @{ (asdl_expr_seq*)_PyPegen_singleton_seq(p, a) @}
    | a[asdl_expr_seq*]=','.expression+ @{a@}

func_type_comment[Token*]:
    | NEWLINE t=TYPE_COMMENT &(NEWLINE INDENT) @{ t @}  # Must be followed by indented block
    | invalid_double_type_comments
    | TYPE_COMMENT

# ========================= END OF THE GRAMMAR ===========================



# ========================= START OF INVALID RULES =======================

# From here on, there are rules for invalid syntax with specialised error messages
invalid_arguments:
    | ((','.(starred_expression | ( assignment_expression | expression !':=') !'=')+ ',' kwargs) | kwargs) a=',' ','.(starred_expression !'=')+ @{
        RAISE_SYNTAX_ERROR_STARTING_FROM(a, "iterable argument unpacking follows keyword argument unpacking") @}
    | a=expression b=for_if_clauses ',' [args | expression for_if_clauses] @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, _PyPegen_get_last_comprehension_item(PyPegen_last_item(b, comprehension_ty)), "Generator expression must be parenthesized") @}
    | a=NAME b='=' expression for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?")@}
    | (args ',')? a=NAME b='=' &(',' | ')') @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected argument value expression")@}
    | a=args b=for_if_clauses @{ _PyPegen_nonparen_genexp_in_call(p, a, b) @}
    | args ',' a=expression b=for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, _PyPegen_get_last_comprehension_item(PyPegen_last_item(b, comprehension_ty)), "Generator expression must be parenthesized") @}
    | a=args ',' args @{ _PyPegen_arguments_parsing_error(p, a) @}
invalid_kwarg:
    | a[Token*]=('True'|'False'|'None') b='=' @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "cannot assign to %s", PyBytes_AS_STRING(a->bytes)) @}
    | a=NAME b='=' expression for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?")@}
    | !(NAME '=') a=expression b='=' @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(
            a, b, "expression cannot contain assignment, perhaps you meant \"==\"?") @}
    | a='**' expression '=' b=expression @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "cannot assign to keyword argument unpacking") @}

# IMPORTANT: Note that the "_without_invalid" suffix causes the rule to not call invalid rules under it
expression_without_invalid[expr_ty]:
    | a=disjunction 'if' b=disjunction 'else' c=expression @{ _PyAST_IfExp(b, a, c, EXTRA) @}
    | disjunction
    | lambdef
invalid_legacy_expression:
    | a=NAME !'(' b=star_expressions @{
        _PyPegen_check_legacy_stmt(p, a) ? RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b,
            "Missing parentheses in call to '%U'. Did you mean %U(...)?", a->v.Name.id, a->v.Name.id) : NULL@}

invalid_type_param:
    | '*' a=NAME colon=':' e=expression @{
            RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind
                ? "cannot use constraints with TypeVarTuple"
                : "cannot use bound with TypeVarTuple")
        @}
    | '**' a=NAME colon=':' e=expression @{
            RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind
                ? "cannot use constraints with ParamSpec"
                : "cannot use bound with ParamSpec")
        @}

invalid_expression:
   |  STRING a=(!STRING expression_without_invalid)+ STRING @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE( PyPegen_first_item(a, expr_ty), PyPegen_last_item(a, expr_ty),
        "invalid syntax. Is this intended to be part of the string?") @}
    # !(NAME STRING) is not matched so we don't show this error with some invalid string prefixes like: kf"dsfsdf"
    # Soft keywords need to also be ignored because they can be parsed as NAME NAME
   | !(NAME STRING | SOFT_KEYWORD) a=disjunction b=expression_without_invalid @{
        _PyPegen_check_legacy_stmt(p, a) ? NULL : p->tokens[p->mark-1]->level == 0 ? NULL :
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") @}
   | a=disjunction 'if' b=disjunction !('else'|':') @{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") @}
   | a=disjunction 'if' b=disjunction 'else' !expression @{
        RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("expected expression after 'else', but statement is given") @}
   | a[stmt_ty]=(pass_stmt|break_stmt|continue_stmt) 'if' b=disjunction 'else' c=simple_stmt @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION (a, "expected expression before 'if', but statement is given") @}
   | a='lambda' [lambda_params] b=':' &FSTRING_MIDDLE  @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "f-string: lambda expressions are not allowed without parentheses") @}
   | a='lambda' [lambda_params] b=':' &TSTRING_MIDDLE  @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "t-string: lambda expressions are not allowed without parentheses") @}

invalid_named_expression(memo):
    | a=expression ':=' expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
            a, "cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) @}
    | a=NAME '=' b=bitwise_or !('='|':=') @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?") @}
    | !(list|tuple|genexp|'True'|'None'|'False') a=bitwise_or b='=' bitwise_or !('='|':=') @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot assign to %s here. Maybe you meant '==' instead of '='?",
                                          _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 annotated_rhs @{
        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_comprehension:
    | ('[' | '(' | '@{') a=starred_expression for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "iterable unpacking cannot be used in comprehension") @}
    | ('[' | '@{') a=star_named_expression ',' b=star_named_expressions for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, PyPegen_last_item(b, expr_ty),
        "did you forget parentheses around the comprehension target?") @}
    | ('[' | '@{') a=star_named_expression b=',' for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "did you forget parentheses around the comprehension target?") @}
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:
    | a="/" ',' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "at least one argument must precede /") @}
    | (slash_no_default | slash_with_default) param_maybe_default* a='/' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "/ may appear only once") @}
    | slash_no_default? param_no_default* invalid_parameters_helper a=param_no_default @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "parameter without a default follows parameter with a default") @}
    | param_no_default* a='(' param_no_default+ ','? b=')' @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "Function parameters cannot be parenthesized") @}
    | (slash_no_default | slash_with_default)? param_maybe_default* '*' (',' | param_no_default) param_maybe_default* a='/' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "/ must be ahead of *") @}
    | param_maybe_default+ '/' a='*' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expected comma between / and *") @}
invalid_default:
    | a='=' &(')'|',') @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expected default value expression") @}
invalid_star_etc:
    | a='*' (')' | ',' (')' | '**')) @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "named arguments must follow bare *") @}
    | '*' ',' TYPE_COMMENT @{ RAISE_SYNTAX_ERROR("bare * has associated type comment") @}
    | '*' param a='=' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "var-positional argument cannot have default value") @}
    | '*' (param_no_default | ',') param_maybe_default* a='*' (param_no_default | ',') @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "* argument may appear only once") @}
invalid_kwds:
    | '**' param a='=' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "var-keyword argument cannot have default value") @}
    | '**' param ',' a=param @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "arguments cannot follow var-keyword argument") @}
    | '**' param ',' a[Token*]=('*'|'**'|'/') @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "arguments cannot follow var-keyword argument") @}
invalid_parameters_helper: # This is only there to avoid type errors
    | a=slash_with_default @{ _PyPegen_singleton_seq(p, a) @}
    | param_with_default+
invalid_lambda_parameters:
    | a="/" ',' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "at least one argument must precede /") @}
    | (lambda_slash_no_default | lambda_slash_with_default) lambda_param_maybe_default* a='/' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "/ may appear only once") @}
    | lambda_slash_no_default? lambda_param_no_default* invalid_lambda_parameters_helper a=lambda_param_no_default @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "parameter without a default follows parameter with a default") @}
    | lambda_param_no_default* a='(' ','.lambda_param+ ','? b=')' @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "Lambda expression parameters cannot be parenthesized") @}
    | (lambda_slash_no_default | lambda_slash_with_default)? lambda_param_maybe_default* '*' (',' | lambda_param_no_default) lambda_param_maybe_default* a='/' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "/ must be ahead of *") @}
    | lambda_param_maybe_default+ '/' a='*' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expected comma between / and *") @}
invalid_lambda_parameters_helper:
    | a=lambda_slash_with_default @{ _PyPegen_singleton_seq(p, a) @}
    | lambda_param_with_default+
invalid_lambda_star_etc:
    | '*' (':' | ',' (':' | '**')) @{ RAISE_SYNTAX_ERROR("named arguments must follow bare *") @}
    | '*' lambda_param a='=' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "var-positional argument cannot have default value") @}
    | '*' (lambda_param_no_default | ',') lambda_param_maybe_default* a='*' (lambda_param_no_default | ',') @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "* argument may appear only once") @}
invalid_lambda_kwds:
    | '**' lambda_param a='=' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "var-keyword argument cannot have default value") @}
    | '**' lambda_param ',' a=lambda_param @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "arguments cannot follow var-keyword argument") @}
    | '**' lambda_param ',' a[Token*]=('*'|'**'|'/') @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "arguments cannot follow var-keyword argument") @}
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_if_clause:
    | 'async'? 'for' (bitwise_or (',' bitwise_or)* [',']) !'in' @{
        RAISE_SYNTAX_ERROR("'in' expected after for-loop variables") @}

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, "cannot use starred expression here") @}
    | '(' a='**' expression ')' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use double starred expression here") @}
invalid_import:
    | a='import' ','.dotted_name+ 'from' dotted_name @{
        RAISE_SYNTAX_ERROR_STARTING_FROM(a, "Did you mean to use 'from ... import ...' instead?") @}
    | 'import' token=NEWLINE @{
        RAISE_SYNTAX_ERROR_STARTING_FROM(token, "Expected one or more names after 'import'") @}
invalid_dotted_as_name:
    | dotted_name 'as' !(NAME (',' | ')' | ';' | NEWLINE)) a=expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a,
            "cannot use %s as import target", _PyPegen_get_expr_name(a)) @}
invalid_import_from_as_name:
    | NAME 'as' !(NAME (',' | ')' | ';' | NEWLINE)) a=expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a,
            "cannot use %s as import target", _PyPegen_get_expr_name(a)) @}

invalid_import_from_targets:
    | import_from_as_names ',' NEWLINE @{
        RAISE_SYNTAX_ERROR("trailing comma not allowed without surrounding parentheses") @}
    | token=NEWLINE @{
        RAISE_SYNTAX_ERROR_STARTING_FROM(token, "Expected one or more names after 'import'") @}

invalid_with_stmt:
    | ['async'] 'with' ','.(expression ['as' star_target])+ NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | ['async'] 'with' '(' ','.(expressions ['as' star_target])+ ','? ')' NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
invalid_with_stmt_indent:
    | ['async'] a='with' ','.(expression ['as' star_target])+ ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'with' statement on line %d", a->lineno) @}
    | ['async'] a='with' '(' ','.(expressions ['as' star_target])+ ','? ')' ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'with' statement on line %d", a->lineno) @}

invalid_try_stmt:
    | a='try' ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'try' statement on line %d", a->lineno) @}
    | 'try' ':' block !('except' | 'finally') @{ RAISE_SYNTAX_ERROR("expected 'except' or 'finally' block") @}
    | 'try' ':' block* except_block+ a='except' b='*' expression ['as' NAME] ':' @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "cannot have both 'except' and 'except*' on the same 'try'") @}
    | 'try' ':' block* except_star_block+ a='except' [expression ['as' NAME]] ':' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot have both 'except' and 'except*' on the same 'try'") @}
invalid_except_stmt:
    | 'except' a=expression ',' expressions 'as' NAME  ':' @{
        RAISE_SYNTAX_ERROR_STARTING_FROM(a, "multiple exception types must be parenthesized when using 'as'") @}
    | a='except' expression ['as' NAME ] NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | a='except' NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | 'except' expression 'as' a=expression ':' block @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
            a, "cannot use except statement with %s", _PyPegen_get_expr_name(a)) @}
invalid_except_star_stmt:
    | 'except' '*' a=expression ',' expressions 'as' NAME  ':' @{
        RAISE_SYNTAX_ERROR_STARTING_FROM(a, "multiple exception types must be parenthesized when using 'as'") @}
    | a='except' '*' expression ['as' NAME ] NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | a='except' '*' (NEWLINE | ':') @{ RAISE_SYNTAX_ERROR("expected one or more exception types") @}
    | 'except' '*' expression 'as' a=expression ':' block @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
            a, "cannot use except* statement with %s", _PyPegen_get_expr_name(a)) @}
invalid_finally_stmt:
    | a='finally' ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'finally' statement on line %d", a->lineno) @}
invalid_except_stmt_indent:
    | a='except' expression ['as' NAME ] ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'except' statement on line %d", a->lineno) @}
    | a='except' ':' NEWLINE !INDENT @{ RAISE_INDENTATION_ERROR("expected an indented block after 'except' statement on line %d", a->lineno) @}
invalid_except_star_stmt_indent:
    | a='except' '*' expression ['as' NAME ] ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'except*' statement on line %d", a->lineno) @}
invalid_match_stmt:
    | "match" subject_expr NEWLINE @{ CHECK_VERSION(void*, 10, "Pattern matching is", RAISE_SYNTAX_ERROR("expected ':'") ) @}
    | a="match" subject=subject_expr ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'match' statement on line %d", a->lineno) @}
invalid_case_block:
    | "case" patterns guard? NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | a="case" patterns guard? ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'case' statement on line %d", a->lineno) @}
invalid_as_pattern:
    | or_pattern 'as' a="_" @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use '_' as a target") @}
    | or_pattern 'as' a=expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
            a, "cannot use %s as pattern target", _PyPegen_get_expr_name(a)) @}
invalid_class_pattern:
    | name_or_attr '(' a=invalid_class_argument_pattern  @{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(
        PyPegen_first_item(a, pattern_ty),
        PyPegen_last_item(a, pattern_ty),
        "positional patterns follow keyword patterns") @}
invalid_class_argument_pattern[asdl_pattern_seq*]:
    | [positional_patterns ','] keyword_patterns ',' a=positional_patterns @{ a @}
invalid_if_stmt:
    | 'if' named_expression NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | a='if' a=named_expression ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'if' statement on line %d", a->lineno) @}
invalid_elif_stmt:
    | 'elif' named_expression NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | a='elif' named_expression ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'elif' statement on line %d", a->lineno) @}
invalid_else_stmt:
    | a='else' ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'else' statement on line %d", a->lineno) @}
    | 'else' ':' block 'elif' @{ RAISE_SYNTAX_ERROR("'elif' block follows an 'else' block")@}
invalid_while_stmt:
    | 'while' named_expression NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | a='while' named_expression ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'while' statement on line %d", a->lineno) @}
invalid_for_stmt:
    | ['async'] 'for' star_targets 'in' star_expressions NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | ['async'] a='for' star_targets 'in' star_expressions ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after 'for' statement on line %d", a->lineno) @}
invalid_def_raw:
    | ['async'] a='def' NAME [type_params] '(' [params] ')' ['->' expression] ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after function definition on line %d", a->lineno) @}
    | ['async'] 'def' NAME [type_params] &&'(' [params] ')' ['->' expression] &&':' [func_type_comment] block
invalid_class_def_raw:
    | 'class' NAME [type_params] ['(' [arguments] ')'] NEWLINE @{ RAISE_SYNTAX_ERROR("expected ':'") @}
    | a='class' NAME [type_params] ['(' [arguments] ')'] ':' NEWLINE !INDENT @{
        RAISE_INDENTATION_ERROR("expected an indented block after class definition on line %d", a->lineno) @}

invalid_double_starred_kvpairs:
    | ','.double_starred_kvpair+ ',' invalid_kvpair
    | expression ':' a='*' bitwise_or @{ RAISE_SYNTAX_ERROR_STARTING_FROM(a, "cannot use a starred expression in a dictionary value") @}
    | expression a=':' &('@}'|',') @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expression expected after dictionary key and ':'") @}
invalid_kvpair:
    | a=expression !(':') @{
        RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError, a->lineno, a->end_col_offset - 1, a->end_lineno, -1, "':' expected after dictionary key") @}
    | expression ':' a='*' bitwise_or @{ RAISE_SYNTAX_ERROR_STARTING_FROM(a, "cannot use a starred expression in a dictionary value") @}
    | expression a=':' &('@}'|',') @{RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expression expected after dictionary key and ':'") @}
invalid_starred_expression_unpacking:
    | a='*' expression '=' b=expression @{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "cannot assign to iterable argument unpacking") @}
invalid_starred_expression:
    | '*' @{ RAISE_SYNTAX_ERROR("Invalid star expression") @}

invalid_fstring_replacement_field:
    | '@{' a='=' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "f-string: valid expression required before '='") @}
    | '@{' a='!' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "f-string: valid expression required before '!'") @}
    | '@{' a=':' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "f-string: valid expression required before ':'") @}
    | '@{' a='@}' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "f-string: valid expression required before '@}'") @}
    | '@{' !annotated_rhs @{ RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: expecting a valid expression after '@{'") @}
    | '@{' annotated_rhs !('=' | '!' | ':' | '@}') @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: expecting '=', or '!', or ':', or '@}'") @}
    | '@{' annotated_rhs '=' !('!' | ':' | '@}') @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: expecting '!', or ':', or '@}'") @}
    | '@{' annotated_rhs '='? invalid_fstring_conversion_character
    | '@{' annotated_rhs '='? ['!' NAME] !(':' | '@}') @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: expecting ':' or '@}'") @}
    | '@{' annotated_rhs '='? ['!' NAME] ':' fstring_format_spec* !'@}' @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: expecting '@}', or format specs") @}
    | '@{' annotated_rhs '='? ['!' NAME] !'@}' @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: expecting '@}'") @}

invalid_fstring_conversion_character:
    | '!' &(':' | '@}') @{ RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: missing conversion character") @}
    | '!' !NAME @{ RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("f-string: invalid conversion character") @}

invalid_tstring_replacement_field:
    | '@{' a='=' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "t-string: valid expression required before '='") @}
    | '@{' a='!' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "t-string: valid expression required before '!'") @}
    | '@{' a=':' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "t-string: valid expression required before ':'") @}
    | '@{' a='@}' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "t-string: valid expression required before '@}'") @}
    | '@{' !annotated_rhs @{ RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: expecting a valid expression after '@{'") @}
    | '@{' annotated_rhs !('=' | '!' | ':' | '@}') @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: expecting '=', or '!', or ':', or '@}'") @}
    | '@{' annotated_rhs '=' !('!' | ':' | '@}') @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: expecting '!', or ':', or '@}'") @}
    | '@{' annotated_rhs '='? invalid_tstring_conversion_character
    | '@{' annotated_rhs '='? ['!' NAME] !(':' | '@}') @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: expecting ':' or '@}'") @}
    | '@{' annotated_rhs '='? ['!' NAME] ':' fstring_format_spec* !'@}' @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: expecting '@}', or format specs") @}
    | '@{' annotated_rhs '='? ['!' NAME] !'@}' @{
        PyErr_Occurred() ? NULL : RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: expecting '@}'") @}

invalid_tstring_conversion_character:
    | '!' &(':' | '@}') @{ RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: missing conversion character") @}
    | '!' !NAME @{ RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("t-string: invalid conversion character") @}

invalid_string_tstring_concat:
    | a=(fstring|string)+ b[expr_ty]=tstring @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(PyPegen_last_item(a, expr_ty), b, "cannot mix t-string literals with string or bytes literals") @}
    | a=tstring+ b[expr_ty]=(fstring|string) @{
        RAISE_SYNTAX_ERROR_KNOWN_RANGE(PyPegen_last_item(a, expr_ty), b, "cannot mix t-string literals with string or bytes literals") @}

invalid_arithmetic:
    | sum ('+'|'-'|'*'|'/'|'%'|'//'|'@@') a='not' b=inversion @{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "'not' after an operator must be parenthesized") @}
invalid_factor:
    | ('+' | '-' | '~') a='not' b=factor @{ RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "'not' after an operator must be parenthesized") @}

invalid_type_params:
    | '[' token=']' @{
        RAISE_SYNTAX_ERROR_STARTING_FROM(
            token,
            "Type parameter list cannot be empty")@}
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python 標準ライブラリ,Python インタプリタの拡張と埋め込み,Python 言語リファレンス,Top
@anchor{library/index doc}@anchor{25aa}@anchor{library/index library-index}@anchor{149}@anchor{library/index the-python-standard-library}@anchor{25ab}@anchor{library/index translation-repo}@anchor{25ac}
@chapter Python 標準ライブラリ


@ref{14a,,Python 言語リファレンス} ではプログラミング言語 Python の厳密な構文とセマンティクスについて説明されていますが、このライブラリリファレンスマニュアルでは Python とともに配付されている標準ライブラリについて説明します。また Python 配布物に収められていることの多いオプションのコンポーネントについても説明します。

Python の標準ライブラリはとても拡張性があり、下の長い目次のリストで判るように幅広いものを用意しています。このライブラリには、例えばファイル I/O のように、Python プログラマが直接アクセスできないシステム機能へのアクセス機能を提供する (Cで書かれた) 組み込みモジュールや、日々のプログラミングで生じる多くの問題に標準的な解決策を提供するPython で書かれたモジュールが入っています。これら数多くのモジュールには、プラットフォーム固有の事情をプラットフォーム独立な API へと昇華させることにより、Pythonプログラムに移植性を持たせ、それを高めるという明確な意図があります。

Windows 向けの Python インストーラはたいてい標準ライブラリのすべてを含み、しばしばそれ以外の追加のコンポーネントも含んでいます。Unix 系のオペレーティングシステムの場合は Python は一揃いのパッケージとして提供されるのが普通で、オプションのコンポーネントを手に入れるにはオペレーティングシステムのパッケージツールを使うことになるでしょう。

標準ライブラリに加えて、数10万のコンポーネントが (独立したプログラムやモジュールからパッケージ、アプリケーション開発フレームワークまで) 活動しているコレクションとしてPython Package Index@footnote{https://pypi.org} から入手可能です。

@c We don't use :numbered: option for the TOC below as it enforces
@c numbered sections for the entire stdlib docs.  If desired,
@c :numbered: can be enabled on a per-module basis.

@menu
* はじめに: はじめに<6>. 
* 組み込み関数:: 
* 組み込み定数:: 
* 組み込み型:: 
* 組み込み例外:: 
* テキスト処理サービス:: 
* バイナリデータ処理:: 
* データ型:: 
* 数値と数学モジュール:: 
* 関数型プログラミング用モジュール:: 
* ファイルとディレクトリへのアクセス:: 
* データの永続化:: 
* データ圧縮とアーカイブ:: 
* ファイルフォーマット:: 
* 暗号関連のサービス:: 
* 汎用オペレーティングシステムサービス:: 
* コマンドラインインターフェースライブラリ:: 
* 並行実行:: 
* ネットワーク通信とプロセス間通信:: 
* インターネット上のデータの操作:: 
* 構造化マークアップツール:: 
* インターネットプロトコルとサポート:: 
* マルチメディアサービス:: 
* 国際化:: 
* Graphical user interfaces with Tk:: 
* 開発ツール:: 
* デバッグとプロファイル:: 
* ソフトウェア・パッケージと配布:: 
* Python ランタイムサービス:: 
* カスタム Python インタプリタ:: 
* モジュールのインポート:: 
* Python言語サービス:: 
* MS Windows 固有のサービス:: 
* Unix-specific services:: 
* モジュールのコマンドラインインターフェース (CLI): モジュールのコマンドラインインターフェース CLI. 
* 取って代わられたモジュール群:: 
* 削除されたモジュール:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<6>. 

@end menu

@node はじめに<6>,組み込み関数,,Python 標準ライブラリ
@anchor{library/intro doc}@anchor{25ad}@anchor{library/intro introduction}@anchor{25ae}@anchor{library/intro library-intro}@anchor{25af}
@section はじめに


この "Python ライブラリ" には様々な内容が収録されています。

このライブラリには、数値型やリスト型のような、通常は言語の "核" をなす部分とみなされるデータ型が含まれています。Python 言語のコア部分では、これらの型に対してリテラル表現形式を与え、意味づけ上のいくつかの制約を与えていますが、完全にその意味づけを定義しているわけではありません。(一方で、言語のコア部分では演算子のスペルや優先順位のような構文法的な属性を定義しています。)

このライブラリにはまた、組み込み関数と例外が納められています --- 組み込み関数および例外は、全ての Python で書かれたコード上で、 @ref{7f8,,import} 文を使わずに使うことができるオブジェクトです。これらの組み込み要素のうちいくつかは言語のコア部分で定義されていますが、大半は言語コアの意味づけ上不可欠なものではないのでここでしか記述されていません。

とはいえ、このライブラリの大部分に収録されているのはモジュールのコレクションです。このコレクションを細分化する方法はいろいろあります。あるモジュールは C 言語で書かれ、Python インタプリタに組み込まれています; 一方別のモジュールは Python で書かれ、ソースコードの形式で取り込まれます。またあるモジュールは、例えば実行スタックの追跡結果を出力するといった、Python に非常に特化したインターフェースを提供し、一方他のモジュールでは、特定のハードウェアにアクセスするといった、特定のオペレーティングシステムに特化したインターフェースを提供し、さらに別のモジュールでは WWW (ワールドワイドウェブ) のような特定のアプリケーション分野に特化したインターフェースを提供しています。モジュールによっては全てのバージョン、全ての移植版の Python で利用することができたり、背後にあるシステムがサポートしている場合にのみ使えたり、Python をコンパイルしてインストールする際に特定の設定オプションを選んだときにのみ利用できたりします。

このマニュアルは "内部から外部へ" と構成されています。つまり、最初に組み込みの関数を記述し、組み込みのデータ型、例外、そして最後に各モジュールと続きます。モジュールは関係のあるものでグループ化して一つの章にしています。

つまり、このマニュアルを最初から読み始め、読み飽きたところで次の章に進めば、 Python ライブラリで利用できるモジュールやサポートしているアプリケーション領域の概要をそこそこ理解できるということです。もちろん、このマニュアルを小説のように読む必要は `ありません' --- (マニュアルの先頭部分にある) 目次にざっと目を通したり、 (最後尾にある) 索引でお目当ての関数やモジュール、用語を探すことだってできます。もしランダムな項目について勉強してみたいのなら、ランダムにページを選び (@ref{bd,,random} 参照)、そこから 1, 2 節読むこともできます。このマニュアルの各節をどんな順番で読むかに関わらず、 @ref{1474,,組み込み関数} の章から始めるとよいでしょう。マニュアルの他の部分は、この節の内容について知っているものとして書かれているからです。

それでは、ショーの始まりです！

@menu
* 利用可能性について:: 

@end menu

@node 利用可能性について,,,はじめに<6>
@anchor{library/intro availability}@anchor{213f}@anchor{library/intro notes-on-availability}@anchor{25b0}
@subsection 利用可能性について



@itemize *

@item 
「利用できる環境 : Unix 」の意味はこの関数が Unix システムにあることが多いということです。このことは特定の OS における存在を主張するものではありません。

@item 
特に記述がない場合、「利用できる環境 : Unix 」と書かれている関数は、 Unix をコアにしているmacOS、iOS、Androidでも利用することができます。

@item 
利用可能性の注釈に最小カーネルバージョンと最小 libc バージョンの両方が含まれている場合は、両方の条件を満たさなければなりません。例えば、 `Availability: Linux >= 3.17 with glibc >= 2.27' という注釈付きの機能には、 Linux 3.17 以上と、 glibc 2.27 以上の両方が必要です。
@end itemize

@menu
* WebAssembly プラットフォーム:: 
* モバイルプラットフォーム:: 

@end menu

@node WebAssembly プラットフォーム,モバイルプラットフォーム,,利用可能性について
@anchor{library/intro wasm-availability}@anchor{1b6a}@anchor{library/intro webassembly-platforms}@anchor{25b1}
@subsubsection WebAssembly プラットフォーム


WebAssembly@footnote{https://webassembly.org/} プラットフォームである @code{wasm32-emscripten} (Emscripten@footnote{https://emscripten.org/}) と @code{wasm32-wasi} (WASI@footnote{https://wasi.dev/}) は、 POSIX API のサブセットを提供します。 WebAssembly ランタイムとブラウザーはサンドボックス化されており、ホストや外部リソースへのアクセスが制限されています。プロセス、スレッド、ネットワーク、シグナル、または他の形のプロセス間通信 (IPC) を使用する標準ライブラリモジュールは、利用不可か、他の Unix ライクなシステムのようには動作しません。ファイル I/O 、ファイルシステム、 Unix の権限関係の機能も制限されています。 Emscripten はブロッキング I/O を許可しません。 @ref{8ac,,sleep()} のような他のブロッキング操作は、ブラウザーのイベントループをブロックします。

WebAssembly プラットフォーム上での Python の 性質と振る舞いは、 Emscripten@footnote{https://emscripten.org/}-SDK や WASI@footnote{https://wasi.dev/}-SDK のバージョン、 WASM ランタイム (ブラウザ、 NodeJS 、 wasmtime@footnote{https://wasmtime.dev/}) 、Python のビルド時フラグによって決まります。 WebAssembly や Emscripten 、 WASI は標準を発展させており、ネットワークなどの機能は将来的にサポートされるかもしれません

ブラウザ上の Python では、ユーザーは  Pyodide@footnote{https://pyodide.org/} や PyScript@footnote{https://pyscript.net/} を検討すべきでしょう。 PyScript は、 Pyodide をもとにして構築されており、 Pyodide 自体は CPython や Emscripten 上に構築されています。 Pyodide は、ブラウザの JavaScript と DOM API だけでなく、 JavaScript の @code{XMLHttpRequest} や @code{Fetch} API による制限されたネットワーク機能へのアクセスを提供します。


@itemize *

@item 
プロセス関連の API は利用不可能か、常にエラーにより失敗します。これには、新しいプロセスを作成 (@ref{4b5,,fork()} や @ref{1311,,execve()}) 、プロセスを待機 (@ref{f9a,,waitpid()}) 、シグナルを送信 (@ref{157f,,kill()}) 、もしくはプロセスと通信する API が含まれます。 @ref{dc,,subprocess} はインポート可能ですが、機能しません。

@item 
The @ref{d1,,socket} module is available, but is limited and behaves
differently from other platforms. On Emscripten, sockets are always
non-blocking and require additional JavaScript code and helpers on the
server to proxy TCP through WebSockets; see Emscripten Networking@footnote{https://emscripten.org/docs/porting/networking.html}
for more information. WASI snapshot preview 1 only permits sockets from an
existing file descriptor.

@item 
Some functions are stubs that either don't do anything and always return
hardcoded values.

@item 
Functions related to file descriptors, file permissions, file ownership, and
links are limited and don't support some operations. For example, WASI does
not permit symlinks with absolute file names.
@end itemize
@anchor{library/intro mobile-availability}@anchor{225c}
@node モバイルプラットフォーム,,WebAssembly プラットフォーム,利用可能性について
@anchor{library/intro ios-availability}@anchor{25b2}@anchor{library/intro mobile-platforms}@anchor{25b3}
@subsubsection モバイルプラットフォーム


Android and iOS are, in most respects, POSIX operating systems. File I/O, socket handling,
and threading all behave as they would on any POSIX operating system. However,
there are several major differences:


@itemize *

@item 
Mobile platforms can only use Python in "embedded" mode. There is no Python
REPL, and no ability to use separate executables such as @code{python} or
@code{pip}. To add Python code to your mobile app, you must use
the @ref{225b,,Python embedding API}. For more details, see
@ref{2259,,Android で Python を使う} and @ref{2261,,iOS で Python を使う}.

@item 
サブプロセス:


@itemize *

@item 
On Android, creating subprocesses is possible but officially unsupported@footnote{https://issuetracker.google.com/issues/128554619#comment4}.
In particular, Android does not support any part of the System V IPC API,
so @ref{98,,multiprocessing} is not available.

@item 
An iOS app cannot use any form of subprocessing, multiprocessing, or
inter-process communication. If an iOS app attempts to create a subprocess,
the process creating the subprocess will either lock up, or crash. An iOS app
has no visibility of other applications that are running, nor any ability to
communicate with other running applications, outside of the iOS-specific APIs
that exist for this purpose.
@end itemize

@item 
Mobile apps have limited access to modify system resources (such as the system
clock). These resources will often be `readable', but attempts to modify
those resources will usually fail.

@item 
Console input and output:


@itemize *

@item 
On Android, the native @code{stdout} and @code{stderr} are not connected to
anything, so Python installs its own streams which redirect messages to the
system log. These can be seen under the tags @code{python.stdout} and
@code{python.stderr} respectively.

@item 
iOS apps have a limited concept of console output. @code{stdout} and
@code{stderr} `exist', and content written to @code{stdout} and @code{stderr} will be
visible in logs when running in Xcode, but this content `won't' be recorded
in the system log. If a user who has installed your app provides their app
logs as a diagnostic aid, they will not include any detail written to
@code{stdout} or @code{stderr}.

@item 
Mobile apps have no usable @code{stdin} at all. While apps can display an on-screen
keyboard, this is a software feature, not something that is attached to
@code{stdin}.

As a result, Python modules that involve console manipulation (such as
@ref{2f,,curses} and @ref{bf,,readline}) are not available on mobile platforms.
@end itemize
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c XXX document all delegations to __special__ methods

@node 組み込み関数,組み込み定数,はじめに<6>,Python 標準ライブラリ
@anchor{library/functions doc}@anchor{25b4}@anchor{library/functions built-in-funcs}@anchor{1474}@anchor{library/functions built-in-functions}@anchor{25b5}@anchor{library/functions translation-repo}@anchor{25b6}
@section 組み込み関数


Python インタプリタには数多くの関数と型が組み込まれており、いつでも利用できます。それらをここにアルファベット順に挙げます。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

組み込み関数

@tab

@tab

@tab

@item


@display
`A'@w{ }
@ref{208d,,abs()}@w{ }
@ref{9d5,,aiter()}@w{ }
@ref{163b,,all()}@w{ }
@ref{9d6,,anext()}@w{ }
@ref{163a,,any()}@w{ }
@ref{15ff,,ascii()}@w{ }
@w{ }
`B'@w{ }
@ref{14c0,,bin()}@w{ }
@ref{3c3,,bool()}@w{ }
@ref{271,,breakpoint()}@w{ }
@ref{1e9b,,bytearray()}@w{ }
@ref{1e9a,,bytes()}@w{ }
@w{ }
`C'@w{ }
@ref{13de,,callable()}@w{ }
@ref{19ef,,chr()}@w{ }
@ref{48e,,classmethod()}@w{ }
@ref{4b1,,compile()}@w{ }
@ref{197,,complex()}@w{ }
@w{ }
`D'@w{ }
@ref{25b7,,delattr()}@w{ }
@ref{25b8,,dict()}@w{ }
@ref{844,,dir()}@w{ }
@ref{b99,,divmod()}@w{ }
@w{ }
@end display



@tab


@display
`E'@w{ }
@ref{169a,,enumerate()}@w{ }
@ref{4a3,,eval()}@w{ }
@ref{4a2,,exec()}@w{ }
@w{ }
`F'@w{ }
@ref{a64,,filter()}@w{ }
@ref{196,,float()}@w{ }
@ref{199,,format()}@w{ }
@ref{25b9,,frozenset()}@w{ }
@w{ }
`G'@w{ }
@ref{dca,,getattr()}@w{ }
@ref{1c0a,,globals()}@w{ }
@w{ }
`H'@w{ }
@ref{6f9,,hasattr()}@w{ }
@ref{801,,hash()}@w{ }
@ref{ad4,,help()}@w{ }
@ref{14e7,,hex()}@w{ }
@w{ }
`I'@w{ }
@ref{163c,,id()}@w{ }
@ref{14f0,,input()}@w{ }
@ref{19b,,int()}@w{ }
@ref{2ad,,isinstance()}@w{ }
@ref{9c4,,issubclass()}@w{ }
@ref{9d7,,iter()}@w{ }
@end display



@tab


@display
`L'@w{ }
@ref{840,,len()}@w{ }
@ref{25ba,,list()}@w{ }
@ref{46f,,locals()}@w{ }
@w{ }
`M'@w{ }
@ref{19f,,map()}@w{ }
@ref{110c,,max()}@w{ }
@ref{25bb,,memoryview()}@w{ }
@ref{110b,,min()}@w{ }
@w{ }
`N'@w{ }
@ref{9d8,,next()}@w{ }
@w{ }
`O'@w{ }
@ref{c7e,,object()}@w{ }
@ref{14e6,,oct()}@w{ }
@ref{316,,open()}@w{ }
@ref{233b,,ord()}@w{ }
@w{ }
`P'@w{ }
@ref{1a4,,pow()}@w{ }
@ref{1177,,print()}@w{ }
@ref{4b3,,property()}@w{ }
@w{ }
@w{ }
@w{ }
@w{ }
@end display



@tab


@display
`R'@w{ }
@ref{25bc,,range()}@w{ }
@ref{1c1,,repr()}@w{ }
@ref{a65,,reversed()}@w{ }
@ref{14f2,,round()}@w{ }
@w{ }
`S'@w{ }
@ref{25bd,,set()}@w{ }
@ref{25be,,setattr()}@w{ }
@ref{694,,slice()}@w{ }
@ref{dc7,,sorted()}@w{ }
@ref{453,,staticmethod()}@w{ }
@ref{25bf,,str()}@w{ }
@ref{695,,sum()}@w{ }
@ref{1a6,,super()}@w{ }
@w{ }
`T'@w{ }
@ref{25c0,,tuple()}@w{ }
@ref{f44,,type()}@w{ }
@w{ }
`V'@w{ }
@ref{1e23,,vars()}@w{ }
@w{ }
`Z'@w{ }
@ref{1a0,,zip()}@w{ }
@w{ }
`_'@w{ }
@ref{ad1,,__import__()}@w{ }
@end display



@end multitable


@c using :func:`dict` would create a link to another page, so local targets are
@c used, with replacement texts to make the output in the table consistent

@geindex built-in function; abs()
@anchor{library/functions abs}@anchor{208d}
@deffn {の関数} abs (number, /)

数の絶対値を返します。引数は整数、浮動小数点数または @ref{2405,,__abs__()} が実装されたオブジェクトです。引数が複素数なら、その絶対値 (magnitude) が返されます。
@end deffn

@geindex built-in function; aiter()
@anchor{library/functions aiter}@anchor{9d5}
@deffn {の関数} aiter (async_iterable, /)

@ref{f74,,asynchronous iterable} から  @ref{4c7,,asynchronous iterator} を返します。 @code{x.__aiter__()} を呼び出すのと等価です。

なお、 @ref{9d7,,iter()} とは異なり、 @ref{9d5,,aiter()} は第二引数を持ちません。


Added in version 3.10.

@end deffn

@geindex built-in function; all()
@anchor{library/functions all}@anchor{163b}
@deffn {の関数} all (iterable, /)

`iterable' の全ての要素が真ならば (もしくは `iterable' が空ならば) @code{True} を返します。以下のコードと等価です:

@example
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
@end example
@end deffn

@geindex built-in function; anext()
@anchor{library/functions anext}@anchor{9d6}
@deffn {の関数} awaitable anext (async_iterator, /)

@deffnx {の関数} awaitable anext (async_iterator, default, /)

待ち受け中に、与えられた非同期イテレータ (@ref{4c7,,asynchronous iterator}) を返します。イテレータが枯渇した場合、 `default' が与えられていれば `default' を返します。

これは組み込みの @ref{9d8,,next()} 関数の非同期版であり、同じように動作します。

これは `async_iterator' の @ref{1882,,__anext__()} メソッドを呼び出し、待ち受け可能オブジェクト (@ref{4c9,,awaitable}) を返します。待ち受けることによりイテレータの次の値を返します。 `default' が与えられた場合、イテレータが枯渇したときにその値が返されます。 `default' が与えられない場合は @ref{1e0f,,StopAsyncIteration} が送出されます。


Added in version 3.10.

@end deffn

@geindex built-in function; any()
@anchor{library/functions any}@anchor{163a}
@deffn {の関数} any (iterable, /)

`iterable' のいずれかの要素が真ならば @code{True} を返します。`iterable' が空なら @code{False} を返します。以下のコードと等価です:

@example
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
@end example
@end deffn

@geindex built-in function; ascii()
@anchor{library/functions ascii}@anchor{15ff}
@deffn {の関数} ascii (object, /)

@ref{1c1,,repr()} と同様、オブジェクトの印字可能な表現を含む文字列を返しますが、@ref{1c1,,repr()} によって返された文字列中の非 ASCII 文字は @code{\x} 、 @code{\u} 、 @code{\U} エスケープを使ってエスケープされます。これは Python 2 の @ref{1c1,,repr()} によって返されるのと同じ文字列を作ります。
@end deffn

@geindex built-in function; bin()
@anchor{library/functions bin}@anchor{14c0}
@deffn {の関数} bin (integer, /)

整数を先頭に "0b" が付いた 2 進文字列に変換します。
結果は Python の式としても使える形式になります。
`integer' が Python の @ref{19b,,int} オブジェクトでない場合、整数を返す @ref{19e,,__index__()} メソッドが定義されていなければなりません。
いくつかの例を示します:

@example
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
@end example

先頭に "0b" が付いて欲しい、もしくは付いて欲しくない場合には、次の方法のどちらでも使えます。

@example
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'@{14:#b@}', f'@{14:b@}'
('0b1110', '1110')
@end example

See also @ref{178d,,enum.bin()} to represent negative values as twos-complement.

より詳しいことは @ref{199,,format()} も参照してください。
@end deffn

@geindex bool (組み込みクラス)
@anchor{library/functions bool}@anchor{3c3}
@deffn {クラス} bool (object=False, /)

真偽値、すなわち @code{True} か @code{False} のいずれかを返します。引数は標準の @ref{1858,,真偽値判定手続き} を用いて変換されます。引数が偽かまたは省略された場合、この関数は @code{False} を返します。それ以外の場合は @code{True} を返します。 @ref{3c3,,bool} クラスは @ref{19b,,int} クラスの派生クラスです (@ref{1fdc,,数値型 int@comma{} float@comma{} complex} を参照してください)。このクラスからさらに派生することはできません。このクラスのインスタンスは @code{False} と @code{True} のみです (@ref{25c1,,ブーリアン型 - bool} を参照してください)。

@geindex Boolean;type


バージョン 3.7 で変更: 引数は位置専用になりました。

@end deffn

@geindex built-in function; breakpoint()
@anchor{library/functions breakpoint}@anchor{271}
@deffn {の関数} breakpoint (*args, **kws)

この関数は、呼び出された箇所にて処理をデバッガに移行します。具体的には、 @ref{cd1,,sys.breakpointhook()} を呼び出し、 @code{args} と @code{kws} をそのまま渡します。デフォルトでは、 @code{sys.breakpointhook()} は引数なしで @ref{272,,pdb.set_trace()} を呼び出すだけです。その場合、これは単なる便利関数でデバッガに入るために @ref{aa,,pdb} を明示的にインポートしたり多くのコードを書いたりせずに済むだけです。ですが、 @ref{cd1,,sys.breakpointhook()} は別の関数に設定でき、 @ref{271,,breakpoint()} はそれを自動で呼び出すため、自分好みのデバッガに処理を移行させることができます。 @ref{cd1,,sys.breakpointhook()} にアクセスできない場合、この関数は @ref{244,,RuntimeError} を送出します。

デフォルトでは、環境変数 
@geindex PYTHONBREAKPOINT
@geindex 環境変数; PYTHONBREAKPOINT
@ref{cd2,,PYTHONBREAKPOINT} をセットすることで @ref{271,,breakpoint()} の動作を変えることができます。
使い方の詳細は @ref{cd1,,sys.breakpointhook()} を参照してください。

ただし、 @ref{cd1,,sys.breakpointhook()} が別の関数で置き換えられている場合、上記の環境変数によって必ずしも動作を変えることができないことに注意してください。

引数 @code{breakpointhook} 付きで @ref{1c6e,,監査イベント} @code{builtins.breakpoint} を送出します。


Added in version 3.7.

@end deffn

@anchor{library/functions func-bytearray}@anchor{1e9b}
@deffn {クラス} bytearray (source=b'@w{'})

@deffnx {クラス} bytearray (source, encoding, errors='strict')

新しいバイト配列を返します。@ref{344,,bytearray} クラスは0 <= x < 256の範囲の整数からなる変更可能な配列です。@ref{25c2,,ミュータブルなシーケンス型} に記述されている変更可能な配列に対する普通のメソッドの大半を備えています。また、@ref{192,,bytes} 型が持つメソッドの大半も備えています（see @ref{25c3,,bytes と bytearray の操作})。

オプションの `source' 引数は、配列を異なる方法で初期化するのに使われます:


@itemize *

@item 
`文字列' の場合、 `encoding' (と、オプションの `errors') 引数も与えなければなりません。このとき @ref{344,,bytearray()} は文字列を @ref{ad2,,str.encode()} でバイトに変換して返します。

@item 
`整数' の場合、配列はそのサイズになり、null バイトで初期化されます。

@item 
@ref{260,,バッファインターフェース} に適合するオブジェクトの場合、そのオブジェクトの読み出し専用バッファがバイト配列の初期化に使われます。

@item 
`イテラブル' の場合、範囲 @code{0 <= x < 256} 内の整数のイテラブルでなければならず、それらが配列の初期の内容として使われます。
@end itemize

引数がなければ、長さ 0 の配列が生成されます。

@ref{25c4,,バイナリシーケンス型 --- bytes@comma{} bytearray@comma{} memoryview} と @ref{25c5,,bytearray オブジェクト} も参照してください。
@end deffn

@anchor{library/functions func-bytes}@anchor{1e9a}
@deffn {クラス} bytes (source=b'@w{'})

@deffnx {クラス} bytes (source, encoding, errors='strict')

範囲 @code{0 <= x < 256} の整数のイミュータブルなシーケンスである "bytes" オブジェクトを返します。 @ref{192,,bytes} は @ref{344,,bytearray} のイミュータブル版であり、オブジェクトを変化させないメソッドや、インデックス指定、オブジェクトのスライスについてのふるまいは同じです。

従って、コンストラクタ引数は @ref{344,,bytearray()} のものと同様に解釈されます。

バイト列オブジェクトはリテラルでも生成できます。 @ref{229f,,文字列およびバイト列リテラル} を参照してください。

@ref{25c4,,バイナリシーケンス型 --- bytes@comma{} bytearray@comma{} memoryview}, @ref{25c6,,バイトオブジェクト}, @ref{25c3,,bytes と bytearray の操作} も参照してください。
@end deffn

@geindex built-in function; callable()
@anchor{library/functions callable}@anchor{13de}
@deffn {の関数} callable (object, /)

`object' 引数が呼び出し可能オブジェクトであれば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。この関数が @code{True} を返しても、呼び出しは失敗する可能性がありますが、@code{False} であれば、 `object' の呼び出しは決して成功しません。なお、クラスは呼び出し可能 (クラスを呼び出すと新しいインスタンスを返します) です。また、インスタンスはクラスが @ref{77a,,__call__()} メソッドを持つなら呼び出し可能です。


Added in version 3.2: この関数は Python 3.0 で一度取り除かれましたが、Python 3.2 で復活しました。

@end deffn

@geindex built-in function; chr()
@anchor{library/functions chr}@anchor{19ef}
@deffn {の関数} chr (codepoint, /)

指定されたUnicode コードポイントが文字を表す文字列を返します。例えば @code{chr(97)} は文字列 @code{'a'} を、 @code{chr(8364)} は文字列 @code{'€'} を返します。 @ref{233b,,ord()} の逆です。

引数の有効な範囲は 0 から 1,114,111 (16 進数で 0x10FFFF) です。引数が範囲外の場合 @ref{2ec,,ValueError} が送出されます。
@end deffn

@geindex built-in function; classmethod()
@anchor{library/functions classmethod}@anchor{48e}
@deffn {の関数} @@classmethod

メソッドをクラスメソッドへ変換します。

クラスメソッドは、インスタンスメソッドが暗黙の第一引数としてインスタンスをとるように、第一引数としてクラスをとります。クラスメソッドを宣言するには、以下のイディオムを使います:

@example
class C:
    @@classmethod
    def f(cls, arg1, arg2): ...
@end example

@code{@@classmethod} 形式は関数 @ref{93a,,デコレータ} です。詳しくは @ref{2018,,関数定義} を参照してください。

クラスメソッドは、(@code{C.f()} のように) クラスから呼び出すことも、(@code{C().f()} のように) インスタンスから呼び出すこともできます。
インスタンスはそのクラスが何であるかを除いて無視されます。
クラスメソッドが派生クラスから呼び出される場合は、その派生クラスオブジェクトが暗黙の第一引数として渡されます。

クラスメソッドは C++ や Java の静的メソッドとは異なります。静的メソッドは、この節の @ref{453,,staticmethod()} を参照してください。クラスメソッドについてより詳しいことは  @ref{232f,,標準型の階層} を参照してください。


バージョン 3.9 で変更: クラスメソッドは @ref{4b3,,property()} など、他の @ref{1881,,デスクリプタ} をラップすることができるようになりました。



バージョン 3.10 で変更: クラスメソッドはメソッド属性 (@ref{234a,,__module__}, @ref{14ec,,__name__}, @ref{2349,,__qualname__}, @ref{13f1,,__doc__} と @ref{13f0,,__annotations__}) を継承するようになりました。また、新たに @code{__wrapped__} 属性を持つようになりました。



Deprecated since version 3.11, removed in version 3.13: クラスメソッドは @ref{4b3,,property()} など、他の @ref{1881,,デスクリプタ} をラップすることができなくなりました。

@end deffn

@geindex built-in function; compile()
@anchor{library/functions compile}@anchor{4b1}
@deffn {の関数} compile (source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

`source' をコードオブジェクト、もしくは、 AST オブジェクトにコンパイルします。 コードオブジェクトは @ref{4a2,,exec()} 文で実行したり、 @ref{4a3,,eval()} 呼び出しで評価できます。 `source' は通常の文字列、 バイト列、 AST オブジェクトのいずれでもかまいません。 AST オブジェクトへの、また、 AST オブジェクトからのコンパイルの方法は、 @ref{9,,ast} モジュールのドキュメントを参照してください。

`filename' 引数には、コードの読み出し元のファイルを与えなければなりません; ファイルから読み出されるのでなければ、認識可能な値を渡して下さい (@code{'<string>'} が一般的に使われます)。

`mode' 引数は、コンパイルされるコードの種類を指定します; `source' が一連の文から成るなら @code{'exec'} 、単一の式から成るなら @code{'eval'} 、単一の対話的文の場合 @code{'single'} です。(後者の場合、評価が @code{None} 以外である式文が印字されます)。

オプション引数 `flags' と `dont_inherit' は、どの @ref{25c7,,コンパイラオプション} を有効化するか、 @ref{45d,,将来の機能} のどれを許可するかを制御します。どちらの引数も存在しない (またはどちらもゼロである) 場合は、 @ref{4b1,,compile()} の呼び出し元のコードに作用したものと同じフラグでコンパイルされます。 `flags' 引数が与えられて `dont_inherit' が与えられない (またはゼロ) の場合、上記に加えて `flags' 引数で与えられたコンパイラオプションと future 文が使われます。 `dont_inherit' がゼロでない整数の場合、 `flags' 引数で指定されたオプションだけが有効です -- 呼び出し元コードに適用されたフラグ (将来の機能とコンパイラオプション) は無視されます。

有効化するコンパイラオプションと future 文はビットフィールドで指定可能で、ビット単位の OR をとることで複数のオプションを一緒に指定することができます。特定の future 機能を指定するために必要なビットフィールドの情報は、 @ref{0,,__future__} モジュールにおける @ref{25c8,,_Feature} インスタンスの @ref{2393,,compiler_flag} 属性で得ることができます。 @ref{25c7,,コンパイラフラグ} の情報は @ref{9,,ast} モジュールの @code{PyCF_} で始まるフラグで得ることができます。

引数 `optimize' は、コンパイラの最適化レベルを指定します; デフォルトの値 @code{-1} は、インタプリタの @ref{18c,,-O} オプションで与えられるのと同じ最適化レベルを選びます。明示的なレベルは、 @code{0} (最適化なし、 @code{__debug__} は真)、 @code{1} (assert は取り除かれ、 @code{__debug__} は偽)、 @code{2} (docstring も取り除かれる) です。

この関数は、コンパイルされたソースが不正である場合 @ref{18e,,SyntaxError} または @ref{2ec,,ValueError} を送出します。

Python コードをパースしてその AST 表現を得たいのであれば、 @ref{1c2,,ast.parse()} を参照してください。

引数 @code{source} と @code{filename} を指定して @ref{1c6e,,監査イベント} @code{compile} を送出します。これは、暗黙に行われるコンパイルでも送出される可能性があります。

@cartouche
@quotation 注釈 
複数行に渡るコードの文字列を @code{'single'} や @code{'eval'} モードでコンパイルするとき、入力は一つ以上の改行文字で終端されなければなりません。これは、 @ref{1b,,code} モジュールで不完全な文と完全な文を検知しやすくするためです。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
AST オブジェクトにコンパイルしているときに、十分に大きい文字列や複雑な文字列によって Python の抽象構文木コンパイラのスタックが深さの限界を越えることで、 Python インタプリタをクラッシュさせられます。
@end quotation
@end cartouche


バージョン 3.2 で変更: Windows や Mac の改行も受け付けます。また @code{'exec'} モードでの入力が改行で終わっている必要もありません。`optimize' 引数が追加されました。



バージョン 3.5 で変更: 以前は `source' にヌルバイトがあったときに @ref{198,,TypeError} を送出していました。



Added in version 3.8: @code{ast.PyCF_ALLOW_TOP_LEVEL_AWAIT} フラグを渡してトップレベルの @code{await}, @code{async for}, および @code{async with} のサポートを有効化することができるようになりました。

@end deffn

@geindex complex (組み込みクラス)
@anchor{library/functions complex}@anchor{197}
@deffn {クラス} complex (number=0, /)

@deffnx {クラス} complex (string, /)

@deffnx {クラス} complex (real=0, imag=0)

単一の文字列や数値を複素数に変換する、あるいは実部と虚部から複素数を作成します。

例:

@example
>>> complex('+1.23')
(1.23+0j)
>>> complex('-4.5j')
-4.5j
>>> complex('-1.23+4.5j')
(-1.23+4.5j)
>>> complex('\t( -1.23+4.5J )\n')
(-1.23+4.5j)
>>> complex('-Infinity+NaNj')
(-inf+nanj)
>>> complex(1.23)
(1.23+0j)
>>> complex(imag=-4.5)
-4.5j
>>> complex(-1.23, 4.5)
(-1.23+4.5j)
@end example

引数が文字列の場合、実数部（ @ref{196,,float()} と同じ形式）、虚数部（同様の形式で @code{'j'} または @code{'J'} 接尾辞）どちらか、あるいは両方（この場合、虚数部の符号は必須）を含まなければなりません。文字列 は空白や括弧 @code{'('} と`@w{`}')'`@w{`} で囲むこともできますが、無視されます。文字列は、 @code{'+'} 、@code{'-'} 、 @code{'j'} または @code{'J'} 接尾辞 、そして10進数の間に空白を含んではなりません。たとえば @code{complex('1+2j')} はよいですが、 @code{complex('1 + 2j')} は @ref{2ec,,ValueError} を送出します。より正確には、入力は括弧および先頭と末尾の空白文字を除去した後、以下の文法における @ref{25c9,,complexvalue} の生成規則を満たす必要があります:

@example
@anchor{library/functions grammar-token-float-complexvalue}@anchor{25c9}complexvalue: @ref{25ca,,floatvalue} |
              @ref{25ca,,floatvalue} ("j" | "J") |
              @ref{25ca,,floatvalue} @ref{25cb,,sign} @ref{25cc,,absfloatvalue} ("j" | "J")
@end example

引数が数値の場合、コンストラクタは @ref{19b,,int} や @ref{196,,float} のように数値変換します。一般的な Python オブジェクト @code{x} では、 @code{complex(x)} は @code{x.__complex__()} に委譲します。 @ref{7fd,,__complex__()} が定義されていない場合は @ref{bc1,,__float__()} にフォールバックします。 @code{__float__()} も定義されていない場合には、 @ref{19e,,__index__()} にフォールバックします。

２引数が指定されるかキーワード引数が使われている場合、各引数は任意の数値型（複素数を含む）となります。両方の引数が実数の場合には、実数成分 `real' と虚数成分 `imag' を持つ複素数を返します。引数が両方とも複素数の場合、実数成分 @code{real.real-imag.imag} と虚数成分 @code{real.imag+imag.real} を持つ複素数を返します。引数の片方が実数の場合、前述の式ではその実数成分のみ使われます。

See also @ref{195,,complex.from_number()} which only accepts a single numeric argument.

引数がすべて省略された場合は、 @code{0j} を返します。

複素数型については @ref{1fdc,,数値型 int@comma{} float@comma{} complex} に説明があります。


バージョン 3.6 で変更: コードリテラル中で桁をグループ化するのにアンダースコアを利用できます。



バージョン 3.8 で変更: @ref{7fd,,__complex__()} と @ref{bc1,,__float__()} が定義されていない場合、 @ref{19e,,__index__()} へフォールバックします。



バージョン 3.14 で非推奨: Passing a complex number as the `real' or `imag' argument is now
deprecated; it should only be passed as a single positional argument.

@end deffn

@geindex built-in function; delattr()
@anchor{library/functions delattr}@anchor{25b7}
@deffn {の関数} delattr (object, name, /)

@ref{25be,,setattr()} の親戚です。引数はオブジェクトと文字列です。文字列はオブジェクトの属性名のいずれかでなければなりません。対象のオブジェクトが許可する場合に限り、この関数は指定された名前の属性を削除します。たとえば、 @code{delattr(x, 'foobar')} は @code{del x.foobar} と等価です。 `name' は Python の識別子である必要はありません (@ref{25be,,setattr()} を参照してください)。
@end deffn

@anchor{library/functions func-dict}@anchor{25b8}
@deffn {クラス} dict (**kwargs)

@deffnx {クラス} dict (mapping, /, **kwargs)

@deffnx {クラス} dict (iterable, /, **kwargs)

新しい辞書を作成します。 @ref{183,,dict} オブジェクトは辞書クラスです。このクラスに関するドキュメンテーションは @ref{183,,dict} と @ref{cbd,,マッピング型 --- dict} を参照してください。

他のコンテナについては、 ビルトインの @ref{24d,,list}, @ref{184,,set}, @ref{614,,tuple} クラスおよび @ref{1e,,collections} モジュールを参照してください。
@end deffn

@geindex built-in function; dir()
@anchor{library/functions dir}@anchor{844}
@deffn {の関数} dir ()

@deffnx {の関数} dir (object, /)

引数がない場合、現在のローカルスコープにある名前のリストを返します。引数がある場合、そのオブジェクトの有効な属性のリストを返そうと試みます。

オブジェクトが @ref{17e2,,__dir__()} という名のメソッドを持つなら、そのメソッドが呼び出され、属性のリストを返さなければなりません。これにより、カスタムの @ref{6fa,,__getattr__()} や @ref{dcb,,__getattribute__()} 関数を実装するオブジェクトは、@ref{844,,dir()} が属性を報告するやり方をカスタマイズできます。

オブジェクトが @ref{17e2,,__dir__()} を提供しない場合、その型オブジェクトと、定義されていればオブジェクトの @ref{77d,,__dict__} 属性から、できるだけ情報を集めようとします。結果のリストは必ずしも完全ではなく、カスタムの @ref{6fa,,__getattr__()} を持つ場合は不正確かもしれません。

デフォルトの @ref{844,,dir()} メカニズムは、完全というより最重要な情報を作成しようとするため、異なる型のオブジェクトでは異なって振る舞います:


@itemize *

@item 
オブジェクトがモジュールオブジェクトの場合、リストにはモジュールの属性の名前が含まれます。

@item 
オブジェクトが型オブジェクトやクラスオブジェクトの場合、リストにはその属性の名前と、再帰的にたどったその基底クラスの属性が含まれます。

@item 
それ以外の場合には、リストにはオブジェクトの属性名、クラス属性名、再帰的にたどった基底クラスの属性名が含まれます。
@end itemize

返されるリストはアルファベット順に並べられています。例えば:

@example
>>> import struct
>>> dir()   # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
...
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
@end example

@cartouche
@quotation 注釈 
@ref{844,,dir()} は主に対話プロンプトでの使用に便利なように提供されているので、厳密性や一貫性を重視して定義された名前のセットというよりも、むしろ興味を引くような名前のセットを返そうとします。また、この関数の細かい動作はリリース間で変わる可能性があります。例えば、引数がクラスであるとき、メタクラス属性は結果のリストに含まれません。
@end quotation
@end cartouche
@end deffn

@geindex built-in function; divmod()
@anchor{library/functions divmod}@anchor{b99}
@deffn {の関数} divmod (a, b, /)

2つの (複素数でない) 数を引数としてとり、整数の除法を行ったときの商と剰余からなる2つの数のペアを返します。被演算子の型が異なる場合、二項算術演算子での規則が適用されます。整数に対する結果は @code{(a // b, a % b)} と同じです。浮動小数点数では、結果は @code{(q, a % b)} とあらわされます。 `q' は通常 @code{math.floor(a / b)} ですが、それより 1 少ないこともあります。いずれにせよ @code{q * b + a % b} は `a' に非常に近い値になります。もし @code{a % b} がゼロでないときは、その符号は `b' と同じであり、かつ @code{0 <= abs(a % b) < abs(b)} を満たします。
@end deffn

@geindex built-in function; enumerate()
@anchor{library/functions enumerate}@anchor{169a}
@deffn {の関数} enumerate (iterable, start=0)

enumerate オブジェクトを返します。 `iterable' は、シーケンスか @ref{4c8,,iterator} か、あるいはイテレーションをサポートするその他のオブジェクトでなければなりません。 @ref{169a,,enumerate()} によって返されたイテレータの @ref{14e5,,__next__()} メソッドは、 (デフォルトでは 0 となる `start' からの) カウントと、 `iterable' 上のイテレーションによって得られた値を含むタプルを返します。

@example
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
@end example

次と等価です:

@example
def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
@end example
@end deffn

@geindex built-in function; eval()
@anchor{library/functions func-eval}@anchor{25cd}@anchor{library/functions eval}@anchor{4a3}
@deffn {の関数} eval (source, /, globals=None, locals=None)

@*パラメータ: 

@itemize *

@item 
@code{source} (@ref{169,,str} | @ref{4e6,,code object}) -- Python 式。

@item 
@code{globals} (@ref{183,,dict} | @code{None}) -- グローバル名前空間 (default: @code{None}) 。

@item 
@code{locals} (@ref{13d3,,mapping} | @code{None}) -- ローカル名前空間 (default: @code{None}) 。
@end itemize


@*戻り値: 
評価された式の結果。


@*例外: 
構文エラーは例外として報告されます。


@cartouche
@quotation 警告 
この関数は任意のコードを実行します。ユーザが入力した文字列を引数としてこの関数を呼び出すと、セキュリティの脆弱性につながる可能性があります。
@end quotation
@end cartouche

`source' 引数のパースと評価は、 `globals' / `locals' のマッピング（訳注：dict相当）をグローバル / ローカルの名前空間とした Python 式 (技術的な言葉では式のリスト -- 訳注：詳細は言語リファレンス６章参照) として行われます。  `globals' 辞書が渡され それが @code{__builtins__} をキーとして持たない場合は、そのキーの下に組み込みモジュール @ref{13,,builtins} の辞書への参照が挿入されてから、`source' が解析されます。  つまり、 `globals' に独自の @code{__builtins__} 辞書を含めて @ref{4a3,,eval()} に渡すことで、実行されるコードで有効となる組み込み関数を統制できます。  `locals' マッピングが省略された場合、 `globals' 辞書がデフォルトとして使われます。どちらのマッピングも省略された場合、 @ref{4a3,,eval()} が呼び出された環境における `globals' と `locals' のもとで式が評価されます。 注意点として、`eval()' は、 @ref{4a3,,eval()} を呼び出したスコープからすでに参照されている場合（例： @ref{14bf,,nonlocal} 文より）のみ @ref{238d,,ネストされたスコープ} (ローカルでないオブジェクト) へのアクセスを持ちます。

例:

@example
>>> x = 1
>>> eval('x+1')
2
@end example

この関数は (@ref{4b1,,compile()} で生成されるような) 任意のコードオブジェクトを実行するのにも利用できます。この場合、文字列の代わりにコードオブジェクトを渡してください。このコードオブジェクトが、引数 `mode' を @code{'exec'} としてコンパイルされている場合、 @ref{4a3,,eval()} の戻り値は @code{None} になります。

ヒント: @ref{4a2,,exec()} 関数により文の動的な実行がサポートされています。@ref{1c0a,,globals()} および @ref{46f,,locals()} 関数は、それぞれ現在のグローバルおよびローカルな辞書を返すので、それらを @ref{4a3,,eval()} や @ref{4a2,,exec()} に渡して使うことができます。

ソースコードとして文字列が与えられた場合、先頭と末尾の空白文字およびタブは取り去られます。

リテラルだけを含む式の文字列を安全に評価できる関数、 @ref{e12,,ast.literal_eval()} も参照してください。

コードオブジェクトを引数として @ref{1c6e,,監査イベント} @code{exec} を送出します。コードコンパイルのイベントも送出されることがあります。


バージョン 3.13 で変更: `globals' と `locals' 引数 はキーワードとして渡せるようになった。



バージョン 3.13 で変更: デフォルトの `locals' 名前空間のセマンティクスは、 組み込み @ref{46f,,locals()} の説明のように調整された。

@end deffn

@geindex 組み込み関数;exec

@geindex built-in function; exec()
@anchor{library/functions exec}@anchor{4a2}
@deffn {の関数} exec (source, /, globals=None, locals=None, *, closure=None)

@cartouche
@quotation 警告 
この関数は任意のコードを実行します。ユーザが入力した文字列を引数としてこの関数を呼び出すと、セキュリティの脆弱性につながる可能性があります。
@end quotation
@end cartouche

この関数は Python コードの動的な実行をサポートします。 `source' は文字列かコードオブジェクトでなければなりません。文字列の場合、その文字列は一連の Python 文として解析され、そして (構文エラーにならない限り) 実行されます。 @footnote{
なお、パーサは Unix スタイルの行末の記法しか受け付けません。コードをファイルから読んでいるなら、必ず、改行変換モードで Windows や Mac スタイルの改行を変換してください。
} コードオブジェクトの場合は、単純に実行されます。どの場合でも、実行されるコードはファイル入力形式として有効であることが期待されます (リファレンスマニュアルの @ref{259e,,ファイル入力} 節を参照してください)。  @ref{14bf,,nonlocal}, @ref{bc2,,yield},  および @ref{1af,,return} 文は、 @ref{4a2,,exec()} 関数に渡されたコードの文脈中でさえ、関数定義の外側で使うことはできません。戻り値は @code{None} です。

どの場合でも、オプションの部分が省略されると、コードは現在のスコープ内で実行されます。 `globals' だけが与えられた場合、その値は辞書でなければならず (かつ辞書のサブクラスであってはならず)、グローバル変数とローカル変数の両方に使われます。 `globals' と `locals' の両方が与えられた場合、それぞれグローバル変数とローカル変数に使われます。 `locals' を指定する場合、その値はマップ型オブジェクトでなければなりません。モジュールレベルでは globals と locals は同じ辞書であることに留意してください。

@cartouche
@quotation 注釈 
@code{exec} が `globals' と `locals' 2つ別々のオブジェクトを取る場合、コードはクラス定義に埋め込まれたかのように実行されます。これは、実行されたコードで定義された関数とクラスが、トップレベルで割り当てられた変数にアクセスできないことを意味します（「トップレベル」変数はクラス定義にてクラス変数として扱われるため）。
@end quotation
@end cartouche

`globals' 辞書がキー @code{__builtins__} に対する値を含まなければ、そのキーに対して、組み込みモジュール @ref{13,,builtins} の辞書への参照が挿入されます。ですから、実行されるコードを @ref{4a2,,exec()} に渡す前に、 `globals' に自作の @code{__builtins__} 辞書を挿入することで、コードがどの組み込みを利用できるか制御できます。

The `closure' argument specifies a closure--a tuple of cellvars.
It's only valid when the `object' is a code object containing
@ref{1893,,free (closure) variables}.
The length of the tuple must exactly match the length of the code object's
@ref{2347,,co_freevars} attribute.

コードオブジェクトを引数として @ref{1c6e,,監査イベント} @code{exec} を送出します。コードコンパイルのイベントも送出されることがあります。

@cartouche
@quotation 注釈 
組み込み関数 @ref{1c0a,,globals()} および @ref{46f,,locals()} は、それぞれ現在のグローバルおよびローカルの名前空間を返すので、それらを @ref{4a2,,exec()} の第二、第三引数にそのまま渡して使うと便利なことがあります。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
標準では `locals' は後に述べる関数 @ref{46f,,locals()} のように動作します。 @ref{4a2,,exec()} の呼び出しが返る時にコードが `locals' に与える影響を知りたいなら、明示的に `locals' 辞書を渡してください。
@end quotation
@end cartouche


バージョン 3.11 で変更: `closure' パラメータが追加されました。



バージョン 3.13 で変更: `globals' と `locals' 引数 はキーワードとして渡せるようになった。



バージョン 3.13 で変更: デフォルトの `locals' 名前空間のセマンティクスは、 組み込み @ref{46f,,locals()} の説明のように調整された。

@end deffn

@geindex built-in function; filter()
@anchor{library/functions filter}@anchor{a64}
@deffn {の関数} filter (function, iterable, /)

`iterable' の要素のうち、 `function' が真であるものからイテレータを構築します。 `iterable' にはシーケンスか、イテレーションをサポートするコンテナか、イテレータを渡せます。 `function' が @code{None} のときは恒等関数が指定されたものとして扱われ、 `iterable' のうち偽であるものがすべて取り除かれます。

なお、@code{filter(function, iterable)} は、関数が @code{None} でなければジェネレータ式 @code{(item for item in iterable if function(item))} と同等で、関数が @code{None} なら @code{(item for item in iterable if item)} と同等です。

逆の働きをする関数については、 @ref{25ce,,itertools.filterfalse()} を参照してください。 `iterable' の要素のうち、 `function' が偽であるものを返します。
@end deffn

@geindex float (組み込みクラス)
@anchor{library/functions float}@anchor{196}
@deffn {クラス} float (number=0.0, /)

@deffnx {クラス} float (string, /)

@geindex NaN
@geindex Infinity

数または文字列から生成された浮動小数点数を返します。

例:

@example
>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
@end example

引数が文字列の場合、10進数でなければなりません。先頭に符号または空白を含んでもかまいません。符号は @code{'+'} か @code{'-'} のいずれかです。正符号 @code{'+'} は生成される値に対して何の効果もありません。引数は NaN (not-a-number) や正または負の無限大をあらわす文字列でもかまいません。より正確にいうと、入力は先頭と末尾の空白文字を除き、以下に示す @ref{25ca,,floatvalue} の生成規則に従う必要があります:

@example
@anchor{library/functions grammar-token-float-sign}@anchor{25cb}sign:          "+" | "-"
@anchor{library/functions grammar-token-float-infinity}@anchor{25cf}infinity:      "Infinity" | "inf"
@anchor{library/functions grammar-token-float-nan}@anchor{25d0}nan:           "nan"
@anchor{library/functions grammar-token-float-digit}@anchor{25d1}digit:         <a Unicode decimal digit, i.e. characters in Unicode general category Nd>
@anchor{library/functions grammar-token-float-digitpart}@anchor{25d2}digitpart:     @ref{25d1,,digit} (["_"] @ref{25d1,,digit})*
@anchor{library/functions grammar-token-float-number}@anchor{25d3}number:        [@ref{25d2,,digitpart}] "." @ref{25d2,,digitpart} | @ref{25d2,,digitpart} ["."]
@anchor{library/functions grammar-token-float-exponent}@anchor{25d4}exponent:      ("e" | "E") [@ref{25cb,,sign}] @ref{25d2,,digitpart}
@anchor{library/functions grammar-token-float-floatnumber}@anchor{25d5}floatnumber:   @ref{25d3,,number} [@ref{25d4,,exponent}]
@anchor{library/functions grammar-token-float-absfloatvalue}@anchor{25cc}absfloatvalue: @ref{25d5,,floatnumber} | @ref{25cf,,infinity} | @ref{25d0,,nan}
@anchor{library/functions grammar-token-float-floatvalue}@anchor{25ca}floatvalue:    [@ref{25cb,,sign}] @ref{25cc,,absfloatvalue}
@end example

大文字と小文字は重要ではないので、例えば、 "inf", "Inf", "INFINITY", "iNfINity" はすべて正の無限大を表す綴りとして受け入れられます。

また、引数が整数または浮動小数点数なら、 (Python の浮動小数点数の精度で) 同じ値の浮動小数点数が返されます。  引数が Python の浮動小数点数の範囲外なら、 @ref{a81,,OverflowError} が送出されます。

一般の Python オブジェクト @code{x} に対して、@code{float(x)} は @code{x.__float__()} に委譲します。 @ref{bc1,,__float__()} が定義されていない場合、@ref{19e,,__index__()} へフォールバックします。

See also @ref{194,,float.from_number()} which only accepts a numeric argument.

引数が与えられなければ、@code{0.0} が返されます。

浮動小数点数型については、 @ref{1fdc,,数値型 int@comma{} float@comma{} complex} も参照してください。


バージョン 3.6 で変更: コードリテラル中で桁をグループ化するのにアンダースコアを利用できます。



バージョン 3.7 で変更: 引数は位置専用になりました。



バージョン 3.8 で変更: @ref{bc1,,__float__()} が定義されていない場合、 @ref{19e,,__index__()} へフォールバックします。

@end deffn

@geindex __format__
@geindex string;format() (組み込み関数)

@geindex built-in function; format()
@anchor{library/functions format}@anchor{199}
@deffn {の関数} format (value, format_spec='@w{'}, /)

`value' を `format_spec' で指示された通りに "整形" した文字列表現に変換します。 `format_spec' の解釈は `value' 引数の型に依存しますが、ほとんどの組み込み型で使われる標準的な構文が存在します: @ref{4f9,,書式指定ミニ言語仕様}。

デフォルトの `format_spec' は空の文字列です。それは通常 @ref{169,,str(value)} の呼び出しと同じ結果になります。

@code{format(value, format_spec)} の呼び出しは、 @code{type(value).__format__(value, format_spec)} に翻訳され、これは value の @ref{831,,__format__()} メソッドの検索をするとき、インスタンス辞書を回避します。このメソッドの探索が @ref{c7e,,object} に到達しても `format_spec' が空にならなかったり、 `format_spec' や返り値が文字列でなかったりした場合、 @ref{198,,TypeError} が送出されます。


バージョン 3.4 で変更: `format_spec' が空の文字列でない場合 @code{object().__format__(format_spec)} は @ref{198,,TypeError} を送出します。

@end deffn

@anchor{library/functions func-frozenset}@anchor{25b9}
@deffn {クラス} frozenset (iterable=(), /)

新しい @ref{7f2,,frozenset} オブジェクトを返します。オプションで `iterable' から得られた要素を含みます。 @code{frozenset} はビルトインクラスです。このクラスに関するドキュメントは @ref{7f2,,frozenset} と @ref{2031,,set（集合）型 --- set@comma{} frozenset} を参照してください。

他のコンテナについては、ビルトインクラス @ref{184,,set}, @ref{24d,,list}, @ref{614,,tuple}, @ref{183,,dict} や @ref{1e,,collections} モジュールを見てください。
@end deffn

@geindex built-in function; getattr()
@anchor{library/functions getattr}@anchor{dca}
@deffn {の関数} getattr (object, name, /)

@deffnx {の関数} getattr (object, name, default, /)

`object' の指定された属性の値を返します。 `name' は文字列でなければなりません。与えられた文字列がオブジェクトの属性名のうちいずれかに一致すれば、戻り値はその属性の値になります。たとえば、 @code{getattr(x, 'foobar')} は @code{x.foobar} と等価です。もし指定された属性が存在しない場合、 `default' が指定されていればその値が返されます。そうでない場合は @ref{5f0,,AttributeError} が送出されます。 `name' は Python 識別子である必要はありません (@ref{25be,,setattr()} を参照してください)。

@cartouche
@quotation 注釈 
@ref{20a3,,プライベートな名前のマングリング} はコンパイル時に行われます。そのため、プライベートな属性 (先頭に2つのアンダースコアを伴う名前を持つ属性) の値を @ref{dca,,getattr()} で取り出すためには、属性名を手動でマングリングする必要があります。
@end quotation
@end cartouche
@end deffn

@geindex built-in function; globals()
@anchor{library/functions globals}@anchor{1c0a}
@deffn {の関数} globals ()

現在のモジュールの名前空間を実装した辞書を返します。関数内のコードに対しては、関数が定義されるときに辞書が設定され、その関数がどこから呼ばれたかにかかわらず同じ内容になります。
@end deffn

@geindex built-in function; hasattr()
@anchor{library/functions hasattr}@anchor{6f9}
@deffn {の関数} hasattr (object, name, /)

引数はオブジェクトと文字列です。文字列がオブジェクトの属性名の一つであった場合 @code{True} を、そうでない場合 @code{False} を返します。 (この関数は、 @code{getattr(object, name)} を呼び出して @ref{5f0,,AttributeError} を送出するかどうかを見ることで実装されています。)
@end deffn

@geindex built-in function; hash()
@anchor{library/functions hash}@anchor{801}
@deffn {の関数} hash (object, /)

オブジェクトのハッシュ値を (存在すれば) 返します。ハッシュ値は整数です。これらは辞書を検索する際に辞書のキーを高速に比較するために使われます。等しい値となる数値は等しいハッシュ値を持ちます (1 と 1.0 のように型が異なっていてもです)。

@cartouche
@quotation 注釈 
独自の @ref{cf3,,__hash__()} メソッドを実装したオブジェクトを使う場合、@ref{801,,hash()} が実行するマシンのビット幅に合わせて戻り値を切り捨てることに注意してください。
@end quotation
@end cartouche
@end deffn

@geindex built-in function; help()
@anchor{library/functions help}@anchor{ad4}
@deffn {の関数} help ()

@deffnx {の関数} help (request)

組み込みヘルプシステムを起動します。(この関数は対話的な使用のためのものです。) 引数が与えられていない場合、対話的ヘルプシステムはインタプリタコンソール上で起動します。引数が文字列の場合、文字列はモジュール、関数、クラス、メソッド、キーワード、またはドキュメントの項目名として検索され、ヘルプページがコンソール上に印字されます。引数がその他のオブジェクトの場合、そのオブジェクトに関するヘルプページが生成されます。

@ref{ad4,,help()} を呼び出したときに関数の引数リストにスラッシュ (/) が現れた場合は、スラッシュより前の引数が位置専用引数だという意味であることに注意してください。より詳しい情報は、 @ref{25d6,,位置専用引数についての FAQ の項目} を参照してください。

この関数は、 @ref{cc,,site} モジュールから、組み込みの名前空間に移されました。


バージョン 3.4 で変更: @ref{ba,,pydoc} と @ref{82,,inspect} への変更により、呼び出し可能オブジェクトの報告されたシグニチャがより包括的で一貫性のあるものになりました。

@end deffn

@geindex built-in function; hex()
@anchor{library/functions hex}@anchor{14e7}
@deffn {の関数} hex (integer, /)

整数を先頭に "0x" が付いた小文字の 16 進文字列に変換します。
`integer' が Python の @ref{19b,,int} オブジェクトでない場合、整数を返す @ref{19e,,__index__()} メソッドが定義されていなければなりません。
いくつかの例を示します:

@example
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
@end example

整数を大文字の 16 進文字列や小文字の 16 進文字列、先頭の "0x" 付きや "0x" 無しに変換したい場合は、次に挙げる方法が使えます:

@example
>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'@{255:#x@}', f'@{255:x@}', f'@{255:X@}'
('0xff', 'ff', 'FF')
@end example

より詳しいことは @ref{199,,format()} も参照してください。

16を底として16進数文字列を整数に変換するには @ref{19b,,int()} も参照してください。

@cartouche
@quotation 注釈 
浮動小数点数の16進文字列表記を得たい場合には、 @ref{2103,,float.hex()} メソッドを使って下さい。
@end quotation
@end cartouche
@end deffn

@geindex built-in function; id()
@anchor{library/functions id}@anchor{163c}
@deffn {の関数} id (object, /)

オブジェクトの "識別値" を返します。この値は整数で、このオブジェクトの有効期間中は一意かつ定数であることが保証されています。有効期間が重ならない 2 つのオブジェクトは同じ @ref{163c,,id()} 値を持つかもしれません。

これはオブジェクトのメモリアドレスです。

引数 @code{id} を指定して @ref{1c6e,,監査イベント} @code{builtins.id} を送出します。
@end deffn

@geindex built-in function; input()
@anchor{library/functions input}@anchor{14f0}
@deffn {の関数} input ()

@deffnx {の関数} input (prompt, /)

引数 `prompt' が存在すれば、それが末尾の改行を除いて標準出力に書き出されます。次に、この関数は入力から 1 行を読み込み、文字列に変換して (末尾の改行を除いて) 返します。 EOF が読み込まれたとき、 @ref{14f1,,EOFError} が送出されます。例:

@example
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
@end example

@ref{bf,,readline} モジュールが読み込まれていれば、 @ref{14f0,,input()} はそれを使って精緻な行編集やヒストリ機能を提供します。

入力を読み込む前に、引数 @code{prompt} 付きで @ref{1c6e,,監査イベント} @code{builtins.input} を送出します。

入力の読み込みに成功した後に、その結果付きで @ref{1c6e,,監査イベント} @code{builtins.input/result} を送出します。
@end deffn

@geindex int (組み込みクラス)
@anchor{library/functions int}@anchor{19b}
@deffn {クラス} int (number=0, /)

@deffnx {クラス} int (string, /, base=10)

数または文字列から生成された整数オブジェクトを返します。引数が指定されない場合は @code{0} を返します。

例:

@example
>>> int(123.45)
123
>>> int('123')
123
>>> int('   -12_345\n')
-12345
>>> int('FACE', 16)
64206
>>> int('0xface', 0)
64206
>>> int('01110011', base=2)
115
@end example

引数に @ref{19d,,__int__()} が定義されている場合は、 @code{int(x)} は @code{x.__int__()} を返します。引数に @ref{19e,,__index__()} が定義されている場合は、 @code{x.__index__()} を返します。浮動小数点数については、これは 0 に近い側へ切り捨てます。

引数が数値でないか、または `base' が与えられた場合、引数は `base' を基数とした整数を表現する文字列、 @ref{192,,bytes} インスタンス、または @ref{344,,bytearray} インスタンスのいずれかでなければなりません。文字列は先頭に @code{+} または @code{-} を伴ったり (符号と数値の間に空白文字を入れてはいけません)、数値の先頭に任意の数のゼロを付けたり、前後に空白文字を付けたり、各桁を単一の下線で区切ったりしても有効です。

n-進数の整数文字列は、各桁が0から n-1 の数値で表されます。ユニコードの10進数では、各桁は0から9のいずれかです。また10から35までの値は @code{a} から @code{z} (または @code{A} から @code{Z}) で表されます。デフォルトの `base' は10です。基数に指定可能な値は0および2から36までの整数です。2進数、8進数、16進数の文字列は、整数リテラルと同様に、それぞれ @code{0b}/@code{0B}, @code{0o}/@code{0O}, または @code{0x}/@code{0X} をプレフィックスとして追加することができます。基数を0に指定した場合、文字列は @ref{230b,,コードにおける整数リテラル} と同じように解釈されます。すなわち、プレフィックスによって基数が2, 8, 10, または 16 のどれになるかが決まります。基数を0にした場合先頭にゼロを追加することはできません: すなわち @code{int('010', 0)} は基数を0に指定しているため不正ですが、 @code{int('010')} や @code{int('010', 8)} は有効です。

整数型については、 @ref{1fdc,,数値型 int@comma{} float@comma{} complex} も参照してください。


バージョン 3.4 で変更: `base' が @ref{19b,,int} のインスタンスでなく、`base' オブジェクトが @ref{19e,,base.__index__} メソッドを持っている場合、そのメソッドを呼んで底に対する整数を得ることができます。以前のバージョンでは @ref{19e,,base.__index__} ではなく @ref{19d,,base.__int__} を使用していました。



バージョン 3.6 で変更: コードリテラル中で桁をグループ化するのにアンダースコアを利用できます。



バージョン 3.7 で変更: 第1引数は位置専用になりました。



バージョン 3.8 で変更: @ref{19d,,__int__()} が定義されていない場合、 @ref{19e,,__index__()} へフォールバックします。



バージョン 3.11 で変更: @ref{19b,,int} への文字列入力やその文字列表現は、サービス拒否攻撃 (DoS 攻撃) を避けるために制限されることがあります。文字列を @ref{19b,,int} に変換したり @ref{19b,,int} を文字列に変換したりする際にその制限を超えた場合、 @ref{2ec,,ValueError} が送出されます。詳しくは @ref{80b,,整数文字列の変換における長さ制限} を参照してください。



バージョン 3.14 で変更: @ref{19b,,int()} no longer delegates to the @ref{19c,,__trunc__()} method.

@end deffn

@geindex built-in function; isinstance()
@anchor{library/functions isinstance}@anchor{2ad}
@deffn {の関数} isinstance (object, classinfo, /)

`object' 引数が `classinfo' 引数に指定した型、またはその (直接、間接、または @ref{13ce,,仮想} の) サブクラスのインスタンスである場合に @code{True} を返します。 `object' が与えられた型のオブジェクトでない場合、この関数は常に @code{False} を返します。 `classinfo' が型オブジェクトのタプル (または再帰的にそのようなタプルを含むタプル) や複数の型の @ref{9c5,,Union 型} である場合、 `object' がそれらの型のいずれかのインスタンスであれば @code{True} を返します。 `classinfo' が型や型からなるタプルまたは再帰的タプルのいずれでもない場合、 @ref{198,,TypeError} 例外が送出されます。タプルの中で先行する型に対するチェックが成功した場合、後続の不正な型に対して @ref{198,,TypeError} が送出されないことがあります。


バージョン 3.10 で変更: `classinfo' に @ref{9c5,,Union 型} を指定できるようになりました。

@end deffn

@geindex built-in function; issubclass()
@anchor{library/functions issubclass}@anchor{9c4}
@deffn {の関数} issubclass (class, classinfo, /)

`class' が `classinfo' の (直接、間接、または @ref{13ce,,仮想} の) サブクラスである場合に @code{True} を返します。クラスは自身のサブクラスとみなされます。 `classinfo' はクラスオブジェクトのタプル (または再帰的にそのようなタプルを含むタプル) やクラスオブジェクトの @ref{9c5,,Union 型} でもよく、この場合は `class' が `classinfo' のいずれかのクラスのサブクラスであれば @code{True} を返します。上記以外の値が指定された場合、 @ref{198,,TypeError} 例外が送出されます。


バージョン 3.10 で変更: `classinfo' に @ref{9c5,,Union 型} を指定できるようになりました。

@end deffn

@geindex built-in function; iter()
@anchor{library/functions iter}@anchor{9d7}
@deffn {の関数} iter (iterable, /)

@deffnx {の関数} iter (callable, sentinel, /)

@ref{4c8,,iterator} オブジェクトを返します。第二引数があるかどうかによって第一引数の解釈は大きく異なります。第二引数がない場合、単一の引数は @ref{12f1,,iterable} プロトコル (@ref{e69,,__iter__()} メソッド) をサポートするコレクションオブジェクトか、またはシーケンスプロトコル (@code{0} から始まる整数を引数にとる @ref{588,,__getitem__()} メソッド) をサポートするオブジェクトでなければなりません。第一引数がどちらのプロトコルもサポートしない場合は @ref{198,,TypeError} 例外が送出されます。第二引数 `sentinel' が与えられた場合、第一引数は呼び出し可能オブジェクトでなければなりません。この場合に生成されるイテレータは @ref{14e5,,__next__()} メソッドを呼び出すごとに引数なしで `callable' を呼び出します; 戻り値が `sentinel' と等しければ、 @ref{df5,,StopIteration} が送出されます。それ以外の場合は戻り値がそのまま返されます。

@ref{25d7,,イテレータ型} も見てください。

2引数形式の @ref{9d7,,iter()} の便利な利用方法の1つは、ブロックリーダーの構築です。
例えば、バイナリのデータベースファイルから固定幅のブロックをファイルの終端に到達するまで読み出すには次のようにします:

@example
from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b'@w{'}):
        process_block(block)
@end example
@end deffn

@geindex built-in function; len()
@anchor{library/functions len}@anchor{840}
@deffn {の関数} len (object, /)

オブジェクトの長さ (要素の数) を返します。引数はシーケンス (文字列、バイト列、タプル、リスト、range 等) かコレクション (辞書、集合、凍結集合等) です。

@code{len} は、例えば @ref{b3d,,range(2 ** 100)} のような、 @ref{13dd,,sys.maxsize} を超える長さに対して @ref{a81,,OverflowError} を送出します。
@end deffn

@anchor{library/functions func-list}@anchor{25ba}
@deffn {クラス} list (iterable=(), /)

@ref{24d,,list} は、実際には関数ではなくミュータブルなシーケンス型で、 @ref{2022,,リスト型 (list)} と @ref{202e,,シーケンス型 --- list@comma{} tuple@comma{} range} にドキュメント化されています。
@end deffn

@geindex built-in function; locals()
@anchor{library/functions locals}@anchor{46f}
@deffn {の関数} locals ()

現在のローカル シンボル テーブルを表すマッピング オブジェクトを返します。これは変数名をキーとし、現在バインドされている参照を値とします。

モジュール スコープでは、単一の名前空間で @ref{4a2,,exec()} や @ref{4a3,,eval()} を使う場合と同じく、この関数は @ref{1c0a,,globals()} と同じ名前空間を返します。

クラス スコープでは、メタクラス コンストラクタに渡された名前空間を返します。

@code{exec()} や @code{eval()} が引数 local と global が分けて使われてる場合では、関数の呼び出しで渡されたローカル名前空間を返します。

上記どの場合でも、特定の実行フレーム内での各 @code{locals()} は `同じ' マッピング オブジェクトを返します。 @code{locals()} から返されたマッピング オブジェクトを通じて行われた変更は、代入、再代入、または削除されたローカル変数として可視化されます。そしてローカル変数の代入、再代入、または削除は、返されたマッピング オブジェクトの内容へ直ちに反映されます。

@ref{4a1,,optimized scope} （関数、ジェネレーター、コルーチンを含む）では、 @code{locals()} を呼び出すと、代わりに関数のローカル変数と非ローカル セル参照の現在のバインディングを含んだ新しい辞書を返します。この場合、返された辞書を使って行われた変更は、対応するローカル変数や非ローカル セル参照には `書き戻されません' 。また、ローカル変数や非ローカル セル参照へ代入、再代入、削除を行っても、以前に返された辞書の内容には `影響しません' 。

@code{locals()} 呼び出しが関数、ジェネレータ、コルーチン内の内包表記内にあれば、これはそれを含むスコープから呼び出すことと同等です。ただし内包表記の初期化された反復変数が含まれます。他のスコープでは、内包表記がネストされた関数として実行されているかのように振舞います。

@code{locals()} 呼び出しがジェネレータ式の一部であれば、ネストされたジェネレータ関数内の呼び出しと同等です。


バージョン 3.12 で変更: 内包表記における @code{locals()} の振る舞い は、 
@geindex Python Enhancement Proposals; PEP 709
PEP 709@footnote{https://peps.python.org/pep-0709/} で説明されているように更新されました。



バージョン 3.13 で変更: 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/} の一部として、この関数から返されるマッピングオブジェクトを変更するセマンティクスが定義されました。 @ref{4a1,,optimized scopes} の振る舞いは上記のようになりました。定義されただけで、その他のスコープの振る舞いは以前のバージョンのままです。

@end deffn

@geindex built-in function; map()
@anchor{library/functions map}@anchor{19f}
@deffn {の関数} map (function, iterable, /, *iterables, strict=False)

Return an iterator that applies `function' to every item of `iterable',
yielding the results.  If additional `iterables' arguments are passed,
`function' must take that many arguments and is applied to the items from all
iterables in parallel.  With multiple iterables, the iterator stops when the
shortest iterable is exhausted.  If `strict' is @code{True} and one of the
iterables is exhausted before the others, a @ref{2ec,,ValueError} is raised. For
cases where the function inputs are already arranged into argument tuples,
see @ref{12fa,,itertools.starmap()}.


バージョン 3.14 で変更: `strict' パラメータが追加されました。

@end deffn

@geindex built-in function; max()
@anchor{library/functions max}@anchor{110c}
@deffn {の関数} max (iterable, /, *, key=None)

@deffnx {の関数} max (iterable, /, *, default, key=None)

@deffnx {の関数} max (arg1, arg2, /, *args, key=None)

iterable の中で最大の要素、または2つ以上の引数の中で最大のものを返します。

位置引数が1つだけ与えられた場合、それは空でない @ref{12f1,,iterable} でなくてはいけません。その iterable の最大の要素が返されます。2 つ以上のキーワード無しの位置引数が与えられた場合、その位置引数の中で最大のものが返されます。

任意のキーワード専用引数が 2 つあります。
`key' 引数は引数を 1 つ取る順序関数 (@ref{dc8,,list.sort()} のもののように) を指定します。
`default' 引数は与えられたイテラブルが空の場合に返すオブジェクトを指定します。
イテラブルが空で `default' が与えられていない場合 @ref{2ec,,ValueError} が送出されます。

最大の要素が複数あるとき、この関数はそのうち最初に現れたものを返します。これは、@code{sorted(iterable, key=keyfunc, reverse=True)[0]} や @code{heapq.nlargest(1, iterable, key=keyfunc)} のような、他のソート安定性を維持するツールと両立します。


バージョン 3.4 で変更: キーワード専用引数 `default' が追加されました。



バージョン 3.8 で変更: `key' 引数が @code{None} であることを許容します。

@end deffn

@anchor{library/functions func-memoryview}@anchor{25bb}
@deffn {クラス} memoryview (object)

与えられたオブジェクトから作られた "メモリビュー" オブジェクトを返します。詳しくは @ref{25d8,,メモリビュー} を参照してください。
@end deffn

@geindex built-in function; min()
@anchor{library/functions min}@anchor{110b}
@deffn {の関数} min (iterable, /, *, key=None)

@deffnx {の関数} min (iterable, /, *, default, key=None)

@deffnx {の関数} min (arg1, arg2, /, *args, key=None)

iterable の中で最小の要素、または2つ以上の引数の中で最小のものを返します。

位置引数が1つだけ与えられた場合、それは空でない @ref{12f1,,iterable} でなくてはいけません。その iterable の最小の要素が返されます。2 つ以上のキーワード無しの位置引数が与えられた場合、その位置引数の中で最小のものが返されます。

任意のキーワード専用引数が 2 つあります。
`key' 引数は引数を 1 つ取る順序関数 (@ref{dc8,,list.sort()} のもののように) を指定します。
`default' 引数は与えられたイテラブルが空の場合に返すオブジェクトを指定します。
イテラブルが空で `default' が与えられていない場合 @ref{2ec,,ValueError} が送出されます。

最小の要素が複数あるとき、この関数はそのうち最初に現れたものを返します。これは、@code{sorted(iterable, key=keyfunc)[0]} や @code{heapq.nsmallest(1, iterable, key=keyfunc)} のような、他のソート安定性を維持するツールと両立します。


バージョン 3.4 で変更: キーワード専用引数 `default' が追加されました。



バージョン 3.8 で変更: `key' 引数が @code{None} であることを許容します。

@end deffn

@geindex built-in function; next()
@anchor{library/functions next}@anchor{9d8}
@deffn {の関数} next (iterator, /)

@deffnx {の関数} next (iterator, default, /)

@ref{4c8,,iterator} の @ref{14e5,,__next__()} メソッドを呼び出すことにより、次の要素を取得します。イテレータが使い尽くされた場合、 `default' が与えられていればその値が返されます。そうでない場合は @ref{df5,,StopIteration} が送出されます。
@end deffn

@geindex object (組み込みクラス)
@anchor{library/functions object}@anchor{c7e}
@deffn {クラス} object

This is the ultimate base class of all other classes. It has methods
that are common to all instances of Python classes. When the constructor
is called, it returns a new featureless object. The constructor does not
accept any arguments.

@cartouche
@quotation 注釈 
@ref{c7e,,object} インスタンスは @ref{77d,,__dict__} 属性を `持たない' ので、 @ref{c7e,,object}  クラスのインスタンスに任意の属性を代入することはできません。
@end quotation
@end cartouche
@end deffn

@geindex built-in function; oct()
@anchor{library/functions oct}@anchor{14e6}
@deffn {の関数} oct (integer, /)

整数を先頭に "0o" が付いた 8 進文字列に変換します。
結果は Python の式としても使える形式になります。
`integer' が Python の @ref{19b,,int} オブジェクトでない場合、整数を返す @ref{19e,,__index__()} メソッドが定義されていなければなりません。
例えば、次のようになります:

@example
>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
@end example

整数を接頭辞 "0o" 付きや "0o" 無しの 8 進文字列に変換したい場合は、次に挙げる方法のいずれかを使ってください。

@example
>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'@{10:#o@}', f'@{10:o@}'
('0o12', '12')
@end example

より詳しいことは @ref{199,,format()} も参照してください。
@end deffn

@geindex file object;open() built-in function

@geindex built-in function; open()
@anchor{library/functions open}@anchor{316}
@deffn {の関数} open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

`file' を開き、対応する @ref{13db,,ファイルオブジェクト} を返します。ファイルを開くことができなければ、@ref{2c0,,OSError} が送出されます。
この関数の利用例について、 @ref{2066,,ファイルを読み書きする} を参照してください。

`file' は @ref{5a1,,path-like object} で、開くファイルのパス名 (絶対パスまたは現在の作業ディレクトリからの相対パス) あるいはラップするファイルの整数のファイルデスクリプタを与えます。 (ファイルデスクリプタが与えられた場合、 `closefd' が @code{False} に設定されていないかぎり、この関数が返す I/O オブジェクトがクローズされるときにファイルデスクリプタもクローズされます。)

`mode' オプション文字列はファイルが開かれる際のモードを指定します。デフォルトは @code{'r'} で、読み込み用にテキストモードで開くという意味です。その他によく使われるモードとして、書き込み用の @code{'w'} (ファイルが既に存在する場合は上書きします) 、排他的な生成をあらわす @code{'x'} 、そして追記用の @code{'a'} ( `いくつかの' Unix システムでは、 `すべての' 書き込みは現在のシーク位置にかかわらずファイルの末尾に追記する、という意味です) です。テキストモードで `encoding' が指定されない場合に使われるエンコーディングは、プラットフォーム依存です: 現在のロケールエンコーディングを取得するために @ref{329,,locale.getencoding()} が呼ばれます。 (生のバイトデータを読み書きする際にはバイナリモードを使い、 `encoding' は指定しません。) 指定できるモードは以下の通りです:

@geindex ファイル;modes
@anchor{library/functions filemodes}@anchor{25d9}

@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文字

@tab

意味

@item

@code{'r'}

@tab

読み込み用に開く (デフォルト)

@item

@code{'w'}

@tab

書き込み用に開き、まずファイルを切り詰める

@item

@code{'x'}

@tab

排他的な生成に開き、ファイルが存在する場合は失敗する

@item

@code{'a'}

@tab

書き込み用に開き、ファイルが存在する場合には末尾に追記する

@item

@code{'b'}

@tab

バイナリモード

@item

@code{'t'}

@tab

テキストモード (デフォルト)

@item

@code{'+'}

@tab

更新用に開く (読み込み・書き込み用)

@end multitable


デフォルトのモードは @code{'r'} (テキストの読み込み用に開く、 @code{'rt'} と同義) です。 @code{'w+'} と @code{'w+b'} はファイルを開いて上書きします。 @code{'r+'} と @code{'r+b'} はファイルを上書きせずに開きます。

@ref{25da,,概要} で触れられているように、Python はバイナリとテキストの I/O を区別します。(`mode' 引数に @code{'b'} を含めて) バイナリモードで開かれたファイルは、内容をいかなるデコーディングもせずに @ref{192,,bytes}  オブジェクトとして返します。(デフォルトや、 `mode' 引数に @code{'t'} が含まれたときの) テキストモードでは、ファイルの内容は @ref{169,,str} として返され、バイト列はまず、プラットフォーム依存のエンコーディングか、`encoding' が指定された場合は指定されたエンコーディングを使ってデコードされます。

@cartouche
@quotation 注釈 
Python は、下層のオペレーティングシステムがテキストファイルをどう認識するかには依存しません; すべての処理は Python 自身で行われ、よってプラットフォーム非依存です。
@end quotation
@end cartouche

`buffering' はオプションの整数で、バッファリングのポリシーを設定するために使われます。  バッファリングを無効化するためには0を渡してください (バイナリモードでのみ設定可能です)。また行単位でのバッファリングには1を設定してください (テキストモードでの書き込み時のみ有効です)。固定サイズのチャンクバッファに対するサイズをバイト単位で指定したい場合は、1より大きい整数を渡してください。この形式でバッファサイズを指定した場合、バイナリ形式でバッファリングをサポートする I/O (buffered I/O) にはそのまま適用されますが、 @code{TextIOWrapper} (すなわち @code{mode='r+'} のモードでオープンされたファイル) では別のバッファリングを行うかもしれません。 @code{TextIOWrapper} でバッファリングを無効化するには、 @ref{d40,,io.TextIOWrapper.reconfigure()} で @code{write_through} フラグを使うことを検討してください。 `buffering' 引数が与えられなかった場合、デフォルトのバッファリングポリシーは以下のように動作します:


@itemize *

@item 
Binary files are buffered in fixed-size chunks; the size of the buffer
is @code{max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE)}
when the device block size is available.
On most systems, the buffer will typically be 128 kilobytes long.

@item 
「対話的な」テキストファイル (@ref{2069,,isatty()} が @code{True} を返すファイル) は行バッファリングを使用します。 その他のテキストファイルは、上で説明したバイナリファイル用の方針を使用します。
@end itemize

`encoding' はファイルのエンコードやデコードに使われる @ref{25db,,text encoding} の名前です。このオプションはテキストモードでのみ使用してください。デフォルトエンコーディングはプラットフォーム依存 (@ref{329,,locale.getencoding()} が返すもの) ですが、Pythonでサポートされているエンコーディングはどれでも使えます。詳しくは @ref{1c,,codecs} モジュール内のサポートしているエンコーディングのリストを参照してください。

`errors' はオプションの文字列で、エンコードやデコードでのエラーをどのように扱うかを指定するものです。バイナリモードでは使用できません。様々な標準のエラーハンドラが使用可能です (@ref{1b6f,,エラーハンドラ} に列記されています) が、 @ref{16b4,,codecs.register_error()} に登録されているエラー処理の名前も使用可能です。標準のエラーハンドラの名前には、以下のようなものがあります:


@itemize *

@item 
@code{'strict'} はエンコーディングエラーがあると例外 @ref{2ec,,ValueError} を発生させます。デフォルト値である @code{None} も同じ効果です。

@item 
@code{'ignore'} はエラーを無視します。エンコーディングエラーを無視することで、データが失われる可能性があることに注意してください。

@item 
@code{'replace'} は、不正な形式のデータが存在した場所に(@code{'?'} のような) 置換マーカーを挿入します。

@item 
@code{'surrogateescape'} は正しくないバイト列をユニコードの下位サロゲート領域のうち U+DC80 から U+DCFF の範囲のコードユニットであらわします。データの書き込み時に @code{surrogateescape} エラーハンドラが使われると、これらのサロゲートコードユニットは元と同じバイト列に変換されます。これはエンコーディングが不明なファイルを処理するのに便利です。

@item 
@code{'xmlcharrefreplace'} はファイルへの書き込み時のみサポートされます。そのエンコーディングでサポートされない文字は、@code{&#@var{nnn};} 形式の適切な XML 文字参照で置換されます。

@item 
@code{'backslashreplace'} は不正なデータを Python のバックスラッシュ付きのエスケープシーケンスで置換します。

@item 
@code{'namereplace'} (書き込み時のみサポートされています) はサポートされていない文字を @code{\N@{...@}} エスケープシーケンスで置換します。
@end itemize

@geindex universal newlines;open() built-in function
@anchor{library/functions open-newline-parameter}@anchor{948}
`newline' はストリームから受け取った改行文字をどのようにパースするかを決定します。 @code{None}, @code{'@w{'}}, @code{'\n'}, @code{'\r'}, または @code{'\r\n'} のいずれかを指定できます。これは以下のように動作します:


@itemize *

@item 
ストリームからの入力の読み込み時、`newline' が @code{None} の場合、ユニバーサル改行モードが有効になります。入力中の行は @code{'\n'}, @code{'\r'}, または @code{'\r\n'} で終わり、呼び出し元に返される前に @code{'\n'} に変換されます。 @code{'@w{'}} の場合、ユニバーサル改行モードは有効になりますが、行末は変換されずに呼び出し元に返されます。その他の正当な値の場合、入力行は与えられた文字列でのみ終わり、行末は変換されずに呼び出し元に返されます。

@item 
ストリームへの出力の書き込み時、`newline' が @code{None} の場合、全ての @code{'\n'} 文字はシステムのデフォルトの行セパレータ @ref{25dc,,os.linesep} に変換されます。 `newline' が @code{'@w{'}} または @code{'\n'} の場合は変換されません。`newline' がその他の正当な値の場合、全ての @code{'\n'} 文字は与えられた文字列に変換されます。
@end itemize

`closefd' が @code{False} で、ファイル名ではなくてファイル記述子が与えられた場合、下層のファイル記述子はファイルが閉じられた後も開いたままとなります。
ファイル名が与えられた場合、`closefd' は @code{True} (デフォルト値) でなければなりません。
そうでない場合エラーが送出されます。

呼び出し可能オブジェクトを `opener' として与えることで、カスタムのオープナーが使えます。そしてファイルオブジェクトの下層のファイル記述子は、`opener' を (`file', `flags') で呼び出して得られます。`opener' は開いたファイル記述子を返さなければなりません。 (@ref{f92,,os.open} を `opener' として渡すと、@code{None} を渡したのと同様の機能になります)。

新たに作成されたファイルは @ref{10fc,,継承不可}  です。

次の例は @ref{f92,,os.open()} 関数の @ref{1302,,dir_fd} 引数を使い、与えられたディレクトリからの相対パスで指定されたファイルを開きます:

@example
>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # ファイル記述子の解放漏れがないように
@end example

@ref{316,,open()} 関数が返す @ref{13db,,file object} の型はモードに依存します。 @ref{316,,open()} をファイルをテキストモード (@code{'w'}, @code{'r'}, @code{'wt'}, @code{'rt'}, など) で開くのに使ったときは @ref{8a4,,io.TextIOBase} (特に @ref{9be,,io.TextIOWrapper}) のサブクラスを返します。
ファイルをバッファリング付きのバイナリモードで開くのに使ったときは @ref{8a3,,io.BufferedIOBase} のサブクラスを返します。
実際のクラスは様々です。
読み込みバイナリモードでは @ref{1427,,io.BufferedReader} を返します。
書き込みバイナリモードや追記バイナリモードでは @ref{15cb,,io.BufferedWriter} を返します。
読み書きモードでは @ref{15cc,,io.BufferedRandom} を返します。
バッファリングが無効なときはrawストリーム、すなわち @ref{12e7,,io.RawIOBase} のサブクラスである @ref{1527,,io.FileIO} を返します。

@geindex line-buffered I/O
@geindex unbuffered I/O
@geindex buffer size@comma{} I/O
@geindex I/O control;buffering
@geindex バイナリモード
@geindex text mode
@geindex module;sys

@ref{5f,,fileinput} 、(@ref{316,,open()} が宣言された場所である) @ref{83,,io} 、 @ref{a5,,os} 、 @ref{a6,,os.path} 、 @ref{e6,,tempfile} 、 @ref{ca,,shutil} などの、ファイル操作モジュールも参照してください。

引数 @code{path}, @code{mode}, @code{flags} を指定して @ref{1c6e,,監査イベント} @code{open} を送出します。

@code{mode} と @code{flags} の2つの引数は呼び出し時の値から修正されたり、推量により設定されたりする可能性があります。


バージョン 3.3 で変更: 


@itemize *

@item 
`opener' 引数を追加しました。

@item 
@code{'x'} モードを追加しました。

@item 
以前は @ref{125e,,IOError} が送出されました; それは現在 @ref{2c0,,OSError} のエイリアスです。

@item 
既存のファイルを 排他的生成モード(@code{'x'})で開いた場合、 @ref{1221,,FileExistsError} を送出するようになりました。
@end itemize



バージョン 3.4 で変更: 


@itemize *

@item 
ファイルが継承不可になりました。
@end itemize



バージョン 3.5 で変更: 


@itemize *

@item 
システムコールが中断されシグナルハンドラが例外を送出しなかった場合、この関数は @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@item 
@code{'namereplace'} エラーハンドラが追加されました。
@end itemize



バージョン 3.6 で変更: 


@itemize *

@item 
@ref{e4b,,os.PathLike} を実装したオブジェクトを受け入れるようになりました。

@item 
Windowsでは、コンソールバッファのオープンは、@ref{1527,,io.FileIO} ではなく、@ref{12e7,,io.RawIOBase} のサブクラスを返すでしょう。
@end itemize



バージョン 3.11 で変更: @code{'U'} モードは削除されました。

@end deffn

@geindex built-in function; ord()
@anchor{library/functions ord}@anchor{233b}
@deffn {の関数} ord (character, /)

Return the ordinal value of a character.

If the argument is a one-character string, return the Unicode code point
of that character.  For example,
@code{ord('a')} returns the integer @code{97} and @code{ord('€')} (Euro sign)
returns @code{8364}.  This is the inverse of @ref{19ef,,chr()}.

If the argument is a @ref{192,,bytes} or @ref{344,,bytearray} object of
length 1, return its single byte value.
For example, @code{ord(b'a')} returns the integer @code{97}.
@end deffn

@geindex built-in function; pow()
@anchor{library/functions pow}@anchor{1a4}
@deffn {の関数} pow (base, exp, mod=None)

`base' の `exp' 乗を返します; `mod' があれば、`base' の `exp' 乗に対する `mod' の剰余を返します (@code{pow(base, exp) % mod} より効率よく計算されます)。二引数の形式 @code{pow(base, exp)} は、冪乗演算子を使った @code{base**exp} と等価です。

When arguments are builtin numeric types with mixed operand types, the
coercion rules for binary arithmetic operators apply.  For @ref{19b,,int}
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, @code{pow(10, 2)}
returns @code{100}, but @code{pow(10, -2)} returns @code{0.01}.  For a negative base of
type @ref{19b,,int} or @ref{196,,float} and a non-integral exponent, a complex
result is delivered.  For example, @code{pow(-9, 0.5)} returns a value close
to @code{3j}. Whereas, for a negative base of type @ref{19b,,int} or @ref{196,,float}
with an integral exponent, a float result is delivered. For example,
@code{pow(-9, 2.0)} returns @code{81.0}.

`base' と `exp' が @ref{19b,,int} オペランドで `mod' が存在するとき、 `mod' もまた整数型でなければならず、かつゼロであってはいけません。 `mod' が存在して `exp' が負の整数の場合、 `base' は `mod' と互いに素 (最大公約数が1) でなければなりません。この場合、 `inv_base' を `base' に対する `mod' を法とするモジュラ逆数 (`base' と `inv_base' の積を `mod' で割った余りが1になるような数) として、 @code{pow(inv_base, -exp, mod)} が返されます。

以下は @code{97} を法とする @code{38} のモジュラ逆数の計算例です:

@example
>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
True
@end example


バージョン 3.8 で変更: @ref{19b,,int} オペランドに対して、三引数形式の @code{pow} で第二引数に負の値を取ることができるようになりました。これによりモジュラ逆数の計算が可能になります。



バージョン 3.8 で変更: キーワード引数を取ることができるようになりました。以前は位置引数だけがサポートされていました。

@end deffn

@geindex built-in function; print()
@anchor{library/functions print}@anchor{1177}
@deffn {の関数} print (*objects, sep=' ', end='\n', file=None, flush=False)

`objects' を `sep' で区切りながらテキストストリーム `file' に表示し、最後に `end' を表示します。`sep' 、 `end' 、 `file' 、 `flush' を与える場合、キーワード引数として与える必要があります。

キーワードなしの引数はすべて、 @ref{169,,str()} がするように文字列に変換され、 `sep' で区切られながらストリームに書き出され、最後に `end' が続きます。 `sep' と `end' の両方とも、文字列でなければなりません。これらを @code{None} にすると、デフォルトの値が使われます。 `objects' が与えられなければ、 @ref{1177,,print()} は `end' だけを書き出します。

`file' 引数は、 @code{write(string)} メソッドを持つオブジェクトでなければなりません。指定されないか、 @code{None} である場合、 @ref{ccd,,sys.stdout} が使われます。表示される引数は全てテキスト文字列に変換されますから、 @ref{1177,,print()} はバイナリモードファイルオブジェクトには使用できません。代わりに @code{file.write(...)} を使ってください。

出力がバッファ化されるかどうかは通常 `file' で決まりますが、`flush' キーワード引数が真ならストリームは強制的にフラッシュされます。


バージョン 3.3 で変更: キーワード引数 `flush' が追加されました。

@end deffn

@geindex property (組み込みクラス)
@anchor{library/functions property}@anchor{4b3}
@deffn {クラス} property (fget=None, fset=None, fdel=None, doc=None)

property 属性を返します。

`fget' は属性値を取得するための関数です。`fset' は属性値を設定するための関数です。`fdel' は属性値を削除するための関数です。`doc' は属性の docstring を作成します。

典型的な使用法は、属性 @code{x} の処理の定義です:

@example
class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")
@end example

`c' が `C' のインスタンスならば、@code{c.x} は getter を呼び出し、@code{c.x = value} は setter を、@code{del c.x} は deleter を呼び出します。

`doc' は、与えられれば property 属性のドキュメント文字列になります。
与えられなければ、 property は `fget' のドキュメント文字列 (もしあれば) をコピーします。
そのため @ref{4b3,,property()} を @ref{93a,,デコレータ} として使えば、読み出し専用 property を作るのは容易です:

@example
class Parrot:
    def __init__(self):
        self._voltage = 100000

    @@property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage
@end example

@code{@@property} デコレータは @code{voltage()} を同じ名前のまま 読み出し専用属性の "getter" にし、`voltage' のドキュメント文字列を "Get the current voltage." に設定します。

@geindex built-in function; property.getter()
@anchor{library/functions property getter}@anchor{19d9}
@deffn {の関数} @@getter
@end deffn

@geindex built-in function; property.setter()
@anchor{library/functions property setter}@anchor{19da}
@deffn {の関数} @@setter
@end deffn

@geindex built-in function; property.deleter()
@anchor{library/functions property deleter}@anchor{19db}
@deffn {の関数} @@deleter

property オブジェクトは @code{getter}, @code{setter}, @code{deleter} メソッドを持っています。これらのメソッドをデコレータとして使うと、対応するアクセサ関数がデコレートされた関数に設定された、 property のコピーを作成できます。  これを一番分かりやすく説明する例があります:

@example
class C:
    def __init__(self):
        self._x = None

    @@property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @@x.setter
    def x(self, value):
        self._x = value

    @@x.deleter
    def x(self):
        del self._x
@end example

このコードは最初の例と等価です。追加の関数には、必ず元の property と同じ名前 (この例では @code{x}) を与えて下さい。

返される property オブジェクトも、コンストラクタの引数に対応した @code{fget}, @code{fset}, および @code{fdel} 属性を持ちます。
@end deffn


バージョン 3.5 で変更: 属性オブジェクトのドックストリングが書き込み可能になりました。


@geindex __name__ (property の属性)
@anchor{library/functions property __name__}@anchor{4b2}
@deffn {の属性} __name__

プロパティ名を保持する属性。プロパティ名は実行時に変更できます。


Added in version 3.13.

@end deffn
@end deffn

@anchor{library/functions func-range}@anchor{25bc}
@deffn {クラス} range (stop, /)

@deffnx {クラス} range (start, stop, step=1, /)

@ref{b3d,,range} は、実際には関数ではなくイミュータブルなシーケンス型で、 @ref{25dd,,range} と @ref{202e,,シーケンス型 --- list@comma{} tuple@comma{} range} にドキュメント化されています。
@end deffn

@geindex built-in function; repr()
@anchor{library/functions repr}@anchor{1c1}
@deffn {の関数} repr (object, /)

オブジェクトの印字可能な表現を含む文字列を返します。この関数は多くの型について、 @ref{4a3,,eval()} に渡されたときと同じ値を持つようなオブジェクトを表す文字列を生成しようとします。そうでない場合は、山括弧に囲まれたオブジェクトの型の名前と追加の情報 (大抵の場合はオブジェクトの名前とアドレスを含みます) を返します。クラスは、 @ref{82f,,__repr__()} メソッドを定義することで、この関数によりそのクラスのインスタンスが返すものを制御することができます。@ref{1738,,sys.displayhook()} にアクセスできない場合、この関数は @ref{244,,RuntimeError} を送出します。

このクラスは、eval 評価可能な独自の representation を持ちます:

@example
class Person:
   def __init__(self, name, age):
      self.name = name
      self.age = age

   def __repr__(self):
      return f"Person('@{self.name@}', @{self.age@})"
@end example
@end deffn

@geindex built-in function; reversed()
@anchor{library/functions reversed}@anchor{a65}
@deffn {の関数} reversed (object, /)

要素を逆順に取り出すイテレータ (reverse @ref{4c8,,iterator}) を返します。引数は @ref{e86,,__reversed__()} メソッドを持つか、シーケンス型プロトコル ( @ref{178f,,__len__()} メソッド、および、 @code{0} 以上の整数を引数とする @ref{588,,__getitem__()} メソッド) をサポートするオブジェクトでなければなりません。
@end deffn

@geindex built-in function; round()
@anchor{library/functions round}@anchor{14f2}
@deffn {の関数} round (number, ndigits=None)

`number' を小数点以下 `ndigits' 桁の精度で丸めた値を返します。`ndigits' が省略されたり、@code{None} だった場合、入力値に最も近い整数を返します。

@ref{14f2,,round()} をサポートする組み込み型では、値は 10 のマイナス `ndigits' 乗の倍数の中で最も近いものに丸められます; 二つの倍数が同じだけ近いなら、偶数を選ぶ方に (そのため、例えば @code{round(0.5)} と @code{round(-0.5)} は両方とも @code{0} に、 @code{round(1.5)} は @code{2} に) 丸められます。
`ndigits' には任意の整数値が有効となります (正の整数、ゼロ、負の整数)。
返り値は `ndigits' が指定されていないか @code{None} の場合は整数、そうでなければ返り値は `number' と同じ型です。

一般的な Python オブジェクト @code{number} に対して、@code{round} は処理を @cite{number.__round__} に移譲します。

@cartouche
@quotation 注釈 
浮動小数点数に対する @ref{14f2,,round()} の振る舞いは意外なものかもしれません: 例えば、 @code{round(2.675, 2)} は予想通りの @code{2.68} ではなく @code{2.67} を与えます。これはバグではありません: これはほとんどの小数が浮動小数点数で正確に表せないことの結果です。詳しくは @ref{2101,,浮動小数点演算、その問題と制限} を参照してください。
@end quotation
@end cartouche
@end deffn

@anchor{library/functions func-set}@anchor{25bd}
@deffn {クラス} set (iterable=(), /)

オプションで `iterable' の要素を持つ、新しい @ref{184,,set} オブジェクトを返します。 @code{set} は組み込みクラスです。このクラスについて詳しい情報は @ref{184,,set} や @ref{2031,,set（集合）型 --- set@comma{} frozenset} を参照してください。

他のコンテナについては @ref{1e,,collections} モジュールや組み込みの @ref{7f2,,frozenset} 、 @ref{24d,,list} 、 @ref{614,,tuple} 、 @ref{183,,dict} クラスを参照してください。
@end deffn

@geindex built-in function; setattr()
@anchor{library/functions setattr}@anchor{25be}
@deffn {の関数} setattr (object, name, value, /)

@ref{dca,,getattr()} の相方です。引数はオブジェクト、文字列、それから任意の値です。文字列は既存の属性または新たな属性の名前にできます。この関数は指定したオブジェクトが許せば、値を属性に関連付けます。例えば、 @code{setattr(x, 'foobar', 123)} は @code{x.foobar = 123} と等価です。

@ref{dcb,,__getattribute__()} のカスタマイズや @ref{1704,,__slots__} を通じてオブジェクトが強制していない限り、 `name' は @ref{22a0,,Names (identifiers and keywords)} で定義されている Python 識別子である必要はありません。属性名が識別子でない場合、ドットを使った属性へのアクセスはできませんが、 @ref{dca,,getattr()} などを通じてアクセス可能です。

@cartouche
@quotation 注釈 
@ref{20a3,,プライベートな名前のマングリング} はコンパイル時に行われます。そのため、プライベートな属性 (先頭に2つのアンダースコアを伴う名前を持つ属性) の値を @ref{25be,,setattr()} でセットするためには、属性名を手動でマングリングする必要があります。
@end quotation
@end cartouche
@end deffn

@geindex slice (組み込みクラス)
@anchor{library/functions slice}@anchor{694}
@deffn {クラス} slice (stop, /)

@deffnx {クラス} slice (start, stop, step=None, /)

@code{range(start, stop, step)} で指定されたインデックスのセットを表す @ref{24ae,,slice} オブジェクトを返します。  引数 `start' と `step' のデフォルトは @code{None} です。

Slice objects are also generated when @ref{24ad,,slicing syntax}
is used.  For example: @code{a[start:stop:step]} or @code{a[start:stop, i]}.

See @ref{d43,,itertools.islice()} for an alternate version that returns an
@ref{4c8,,iterator}.

@geindex start (slice の属性)
@geindex stop (slice の属性)
@geindex step (slice の属性)
@anchor{library/functions slice start}@anchor{23a5}
@deffn {の属性} start
@anchor{library/functions slice stop}@anchor{23a6}
@deffnx {の属性} stop
@anchor{library/functions slice step}@anchor{23a7}
@deffnx {の属性} step

These read-only attributes are set to the argument values
(or their default).  They have no other explicit functionality;
however, they are used by NumPy and other third-party packages.
@end deffn


バージョン 3.12 で変更: スライスオブジェクトが @ref{824,,hashable} (ハッシュ可能) となりました (ただし、属性 @ref{23a5,,start} 、 @ref{23a6,,stop} 、 @ref{23a7,,step} がすべてハッシュ可能である場合に限ります)。

@end deffn

@geindex built-in function; sorted()
@anchor{library/functions sorted}@anchor{dc7}
@deffn {の関数} sorted (iterable, /, *, key=None, reverse=False)

`iterable' の要素を並べ替えた新たなリストを返します。

2 つのオプション引数があり、これらはキーワード引数として指定されなければなりません。

`key' には 1 引数関数を指定します。これは `iterable' の各要素から比較キーを展開するのに使われます (例えば、 @code{key=str.lower} のように指定します)。
デフォルト値は @code{None} です (要素を直接比較します)。

`reverse' は真偽値です。 @code{True} がセットされた場合、リストの要素は個々の比較が反転したものとして並び替えられます。

旧式の `cmp' 関数を `key' 関数に変換するには @ref{13f2,,functools.cmp_to_key()} を使用してください。

組み込みの @ref{dc7,,sorted()} 関数は安定なことが保証されています。同等な要素の相対順序を変更しないことが保証されていれば、ソートは安定です。これは複数のパスでソートを行なうのに役立ちます（例えば部署でソートしてから給与の等級でソートする場合）。

ソートアルゴリズムは、要素間の比較に @code{<} 演算子だけを使います。したがってソートのためには @ref{14b8,,__lt__()} メソッドを定義すれば十分なはずですが、 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} は6つの @ref{24d0,,比較演算子} を全て実装することを推奨しています。これにより、異なるメソッドを必要とする @ref{110c,,max()} のような他のソートツールを、同じデータに対して適用することによって起こりうるバグを避ける助けになります。6つの比較演算子を全て実装することは、リフレクションによって @ref{1523,,__gt__()} メソッドを呼び出す可能性のある型混合の比較での混乱を避けることにも役立ちます。

ソートの例と簡単なチュートリアルは @ref{13f3,,ソートのテクニック} を参照して下さい。
@end deffn

@geindex built-in function; staticmethod()
@anchor{library/functions staticmethod}@anchor{453}
@deffn {の関数} @@staticmethod

メソッドを静的メソッドへ変換します。

静的メソッドは暗黙の第一引数を受け取りません。静的メソッドを宣言するには、このイディオムを使ってください:

@example
class C:
    @@staticmethod
    def f(arg1, arg2, argN): ...
@end example

@code{@@staticmethod} 形式は関数 @ref{93a,,デコレータ} です。詳しくは @ref{2018,,関数定義} を参照してください。

静的メソッドは (@code{C.f()} のように) クラスに対して呼び出すことも、 (@code{C().f()} のように) インスタンスに対して呼び出すこともできます。さらに、静的メソッド @ref{1881,,descriptor} は呼び出し可能でもあるため、(@code{f()} のように) クラス定義の中でも使用できます。

Python における静的メソッドは Java や C++ における静的メソッドと類似しています。クラスコンストラクタの代替を生成するのに役立つ変種、 @ref{48e,,classmethod()} も参照してください。

あらゆるデコレータと同じく、 @code{staticmethod} は普通の関数のように呼べ、その返り値で処理が行えます。
この機能は、クラス本体から関数を参照する必要があり、かつ、インスタンスメソッドに自動変換されるのを避けたいケースで必要になります。
そのようなケースでは、このイディオムが使えます:

@example
def regular_function():
    ...

class C:
    method = staticmethod(regular_function)
@end example

静的メソッドについて詳しい情報は @ref{232f,,標準型の階層} を参照してください。


バージョン 3.10 で変更: Static methods now inherit the method attributes
(@ref{234a,,__module__}, @ref{14ec,,__name__},
@ref{2349,,__qualname__}, @ref{13f1,,__doc__} and
@ref{13f0,,__annotations__}), have a new @code{__wrapped__} attribute,
and are now callable as regular functions.

@end deffn

@geindex string;str() (built-in function)

@anchor{library/functions func-str}@anchor{25bf}
@deffn {クラス} str (*, encoding='utf-8', errors='strict')

@deffnx {クラス} str (object)

@deffnx {クラス} str (object, encoding, errors='strict')

@deffnx {クラス} str (object, *, errors)

`object' の @ref{169,,str} 版を返します。詳細は @ref{169,,str()} を参照してください。

@code{str} は組み込みの文字列 @ref{1cfd,,クラス} です。文字列に関する一般的な情報は、@ref{1fe0,,テキストシーケンス型 --- str} を参照してください。
@end deffn

@geindex built-in function; sum()
@anchor{library/functions sum}@anchor{695}
@deffn {の関数} sum (iterable, /, start=0)

`start' と `iterable' の要素を左から右へ合計し、総和を返します。 `iterable' の要素は通常は数値で、start の値は文字列であってはなりません。

使う場面によっては、 @ref{695,,sum()} よりもいい選択肢があります。文字列からなるシーケンスを結合する高速かつ望ましい方法は @code{'@w{'}.join(sequence)} を呼ぶことです。浮動小数点数値を拡張された精度で加算するには、 @ref{15ed,,math.fsum()} を参照してください。一連のイテラブルを連結するには、 @ref{25de,,itertools.chain()} の使用を考えてください。


バージョン 3.8 で変更: `start' パラメータをキーワード引数として指定することができるようになりました。



バージョン 3.12 で変更: 浮動小数点数の総和を計算するとき、ほとんどの環境でより高精度な結果とより良い互換性が得られるアルゴリズムを使用するようになりました。



バージョン 3.14 で変更: Added specialization for summation of complexes,
using same algorithm as for summation of floats.

@end deffn

@geindex super (組み込みクラス)
@anchor{library/functions super}@anchor{1a6}
@deffn {クラス} super

@deffnx {クラス} super (type, object_or_type=None, /)

メソッドの呼び出しを `type' の親または兄弟クラスに委譲するプロキシオブジェクトを返します。これはクラスの中でオーバーライドされた継承メソッドにアクセスするのに便利です。

`object_or_type' はメソッドの検索のための @ref{25df,,method resolution order} (メソッド解決順序) を決定します。検索は `type' 直後のクラスから開始します。

例えば `object_or_type' の @ref{2378,,__mro__} 属性が @code{D -> B -> C -> A -> object} であり、 `type' の値が @code{B} だとすると、 @ref{1a6,,super()} は @code{C -> A -> object} の順番でメソッドを検索します。

The @ref{2378,,__mro__} attribute of the class corresponding to
`object_or_type' lists the method resolution search order used by both
@ref{dca,,getattr()} and @ref{1a6,,super()}.  The attribute is dynamic and can change
whenever the inheritance hierarchy is updated.

第 2 引数が省かれたなら、返されるスーパーオブジェクトは束縛されません。第 2 引数がオブジェクトであれば、 @code{isinstance(obj, type)} は真でなければなりません。第 2 引数が型であれば、 @code{issubclass(type2, type)} は真でなければなりません (これはクラスメソッドに役に立つでしょう)。

クラスの通常のメソッド中で直接呼び出される場合、どちらの引数も省けます (「ゼロ引数 @code{super()} 」) 。この場合、 `type' はその囲んでいるクラスとなり、 `obj' は直接囲んでいる関数の第一引数 (通常は @code{self} ) となります。 (つまり、ゼロ引数 @code{super()} は、ネストされた関数では期待どおりに動作しません。これには 暗にネストされた関数を作るジェネレータ式も含まれます)

`super' の典型的な用途は 2 つあります。第一に、単継承のクラス階層構造で `super' は名前を明示することなく親クラスを参照するのに使え、それゆえコードをメンテナンスしやすくなります。この用途は他のプログラミング言語で見られる `super' の用途によく似ています。

2つ目の用途は動的な実行環境において協調的 (cooperative) な多重継承をサポートすることです。これは Python に特有の用途で、静的にコンパイルされる言語や、単継承のみをサポートする言語には見られないものです。この機能により、同じ名前のメソッドを実装する複数の基底クラスを使った "ダイヤモンド型* の継承構造を実装することができます。良い設計は、そのような実装において、どのような場合でも同じ呼び出しシグネチャを持つように強制します。 (理由は呼び出しの順序が実行時に決定されること、呼び出し順序はクラス階層構造の変化に順応すること、そして呼び出し順序が実行時まで未知の兄弟クラスが含まれる場合があることです)。

両方の用途において、典型的なスーパークラスの呼び出しは次のようになります:

@example
class C(B):
    def method(self, arg):
        super().method(arg)    # これは次と同じことを行います:
                               # super(C, self).method(arg)
@end example

メソッドのルックアップに加えて、 @ref{1a6,,super()} は属性のルックアップに対しても同様に動作します。考えうる用途のひとつは親クラスや兄弟クラスの @ref{1881,,descriptors} (デスクリプタ) を呼び出すことです。

なお、@ref{1a6,,super()} は @code{super().__getitem__(name)} のような明示的なドット表記属性探索の束縛処理の一部として実装されています。これは、  @ref{dcb,,__getattribute__()} メソッドを予測可能な順序でクラスを検索するように実装し、協調的な多重継承をサポートすることで実現されています。従って、 @ref{1a6,,super()} は文や @code{super()[name]} のような演算子を使った暗黙の探索向けには定義されていません。

また、 @ref{1a6,,super()} の使用は引数無しの形式を除きメソッド内部に限定されないことにも注目して下さい。2引数の形式は、必要な要素を正確に指定するので、適当な参照を作ることができます。クラス定義中における引数無しの形式は、定義されているクラスを取り出すのに必要な詳細を、通常の方法で現在のインスタンスにアクセスするようにコンパイラが埋めるのではたらきます。

@ref{1a6,,super()} を用いて協調的なクラスを設計する方法の実践的な提案は、 guide to using super()@footnote{https://rhettinger.wordpress.com/2011/05/26/super-considered-super/} を参照してください。


バージョン 3.14 で変更: @ref{1a6,,super} オブジェクトは pickle 可能 かつ コピー可能 になりました。

@end deffn

@anchor{library/functions func-tuple}@anchor{25c0}
@deffn {クラス} tuple (iterable=(), /)

@ref{614,,tuple} は、実際は関数ではなくイミュータブルなシーケンス型で、@ref{254a,,タプル型 (tuple)} と @ref{202e,,シーケンス型 --- list@comma{} tuple@comma{} range} にドキュメント化されています。
@end deffn

@geindex type (組み込みクラス)
@anchor{library/functions type}@anchor{f44}
@deffn {クラス} type (object, /)

@deffnx {クラス} type (name, bases, dict, /, **kwargs)

@geindex object;type

引数が1つだけの場合、`object' の型を返します。返り値は型オブジェクトで、一般に @ref{16c6,,object.__class__} によって返されるのと同じオブジェクトです。

オブジェクトの型の判定には、 @ref{2ad,,isinstance()} 組み込み関数を使うことが推奨されます。これはサブクラスを考慮するからです。

引数が3つの場合、新しい型オブジェクトを返します。これは本質的には @ref{14ef,,class} 文の動的な書式です。 `name' 文字列はクラス名で、 @ref{16c4,,__name__} 属性になります。 `bases' 基底クラスのタプルで、 @ref{16c5,,__bases__} 属性になります; 空の場合は全てのクラスの基底クラスである @ref{c7e,,object} が追加されます。 `dict' は、クラス本体の属性とメソッドの定義を含む辞書です; 辞書は @ref{e57,,__dict__} 属性になる前にコピーされたり、ラップされることがあります。以下の2つの文は同じ @code{type} オブジェクトを生成します:

@example
>>> class X:
...     a = 1
...
>>> X = type('X', (), dict(a=1))
@end example

下記を参照してください。


@itemize *

@item 
@ref{2370,,Documentation on attributes and methods on classes}.

@item 
@ref{25e0,,型オブジェクト}
@end itemize

三引数形式の呼び出しに与えられたキーワード引数は、(`metaclass' を除く) クラス定義におけるキーワード引数と同様に、適切なメタクラスの機構 (通常は @ref{843,,__init_subclass__()}) に渡されます。

@ref{e45,,クラス生成をカスタマイズする} も参照してください。


バージョン 3.6 で変更: @code{type.__new__} をオーバーライドしていない @code{type} のサブクラスは、オブジェクトの型を得るのに１引数形式を利用することができません。

@end deffn

@geindex built-in function; vars()
@anchor{library/functions vars}@anchor{1e23}
@deffn {の関数} vars ()

@deffnx {の関数} vars (object, /)

モジュール、クラス、インスタンス、あるいはそれ以外の @code{__dict__} 属性を持つオブジェクトの、 @ref{77d,,__dict__} 属性を返します。

モジュールやインスタンスのようなオブジェクトは、更新可能な @ref{77d,,__dict__} 属性を持っています。ただし、それ以外のオブジェクトでは @code{__dict__} 属性への書き込みが制限されている場合があります。書き込みに制限がある例としては、辞書を直接更新されることを防ぐために @ref{698,,types.MappingProxyType} を使っているクラスがあります。

引数がない場合 @ref{1e23,,vars()} は @ref{46f,,locals()} のように動作します。

指定されたオブジェクトに @ref{77d,,__dict__} 属性がない場合 (たとえばそのクラスが @ref{1704,,__slots__} 属性を定義している場合)、 @ref{198,,TypeError} 例外が送出されます。


バージョン 3.13 で変更: この関数を引数なしで呼び出したときの返り値は、 @ref{46f,,locals()} 組み込み関数での説明に更新されました。

@end deffn

@geindex built-in function; zip()
@anchor{library/functions zip}@anchor{1a0}
@deffn {の関数} zip (*iterables, strict=False)

複数のイテラブルを並行に反復処理し、各イテラブルの要素からなるタプルを生成します。

以下はプログラム例です:

@example
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
...     print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
@end example

より正式な定義: @ref{1a0,,zip()} は、 `i' 番目のタプルが 引数に与えた各イテラブルの `i' 番目の要素を含むような、タプルのイテレータを返します。

@ref{1a0,,zip()} に対する別の考え方は、この関数は行を列に、また列を行に変換するということです。これは 行列の転置@footnote{https://en.wikipedia.org/wiki/Transpose} とよく似ています。

@ref{1a0,,zip()} は遅延評価です: イテラブルが @code{for} ループに渡されたり、 @ref{24d,,list} でラップされたりするなどして反復処理されるまで、要素が実際に処理されることはありません。

ここで考慮すべきことは、 @ref{1a0,,zip()} に渡されるイテラブルが異なる長さを持つことがあるという点です; ときには意図的な場合もあり、またときにはイテラブルを準備するコードにおけるバグのこともあるでしょう。 Python はこの問題に対して3つの異なるアプローチを提供します:


@itemize *

@item 
デフォルトでは、 @ref{1a0,,zip()} は最も短いイテラブルが消費しきった時点で停止します。より繰り返し数の長いイテラブルの残りの要素は無視して、結果を最も短いイテラブルの長さに切り詰めます:

@example
>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
[(0, 'fee'), (1, 'fi'), (2, 'fo')]
@end example

@item 
@ref{1a0,,zip()} は、しばしば受け取ったイテラブルが全て同じ長さであるという想定の下で使われます。そのような場合、 @code{strict=True} オプションの利用が推奨されます。その出力は通常の @ref{1a0,,zip()} と同じです:

@example
>>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))
[('a', 1), ('b', 2), ('c', 3)]
@end example

しかし、デフォルトの動作と異なり、あるイテラブルが他のイテラブルよりも先に消費しきった場合に @ref{2ec,,ValueError} 例外を送出します:

@example
>>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True):
...     print(item)
...
(0, 'fee')
(1, 'fi')
(2, 'fo')
Traceback (most recent call last):
  ...
ValueError: zip() argument 2 is longer than argument 1
@end example

@c This doctest is disabled because doctest does not support capturing
@c output and exceptions in the same code unit.
@c https://github.com/python/cpython/issues/65382

@code{strict=True} 引数なしの場合、長さの異なるイテラブルを生じる原因となるいかなるバグも、この時点では問題なく処理されます。そして代わりにプログラムの別の場所で、原因を特定しにくいバグとして検出されることになるでしょう。

@item 
短いイテラブルを一定の値でパディングして全てのイテラブルが同じ長さになるようにすることもできます。この機能は @ref{14b6,,itertools.zip_longest()} で提供されます。
@end itemize

エッジケース: 引数としてイテラブルをひとつだけ渡した場合、 @ref{1a0,,zip()} は 1 タプルのイテレータを返します。引数なしの場合は空のイテレータを返します。

ヒントとコツ:


@itemize *

@item 
イテラブルの左から右への評価順序は保証されています。そのため @code{zip(*[iter(s)]*n, strict=True)} を使ってデータ系列を長さ n のグループにクラスタリングするイディオムが使えます。これは、各出力タプルがイテレータを @code{n} 回呼び出した結果となるよう、 `同じ' イテレータを @code{n} 回繰り返します。これは入力を長さ n のチャンクに分割する効果があります。

@item 
@ref{1a0,,zip()} に続けて @code{*} 演算子を使うと、zip したリストを元に戻せます:

@example
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
@end example
@end itemize


バージョン 3.10 で変更: @code{strict} 引数が追加されました。

@end deffn

@geindex built-in function; __import__()
@anchor{library/functions import__}@anchor{ad1}
@deffn {の関数} __import__ (name, globals=None, locals=None, fromlist=(), level=0)

@geindex statement;import
@geindex module;builtins

@cartouche
@quotation 注釈 
これは @ref{73c,,importlib.import_module()} とは違い、日常の Python プログラミングでは必要ない高等な関数です。
@end quotation
@end cartouche

この関数は @ref{7f8,,import} 文により呼び出されます。 (@ref{13,,builtins} モジュールをインポートして @code{builtins.__import__} に代入することで) この関数を置き換えて @code{import} 文のセマンティクスを変更することができますが、同様のことをするのに通常はインポートフック (
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} 参照) を利用する方が簡単で、かつデフォルトのインポート実装が使用されていることを仮定するコードとの間で問題が起きないので、このやり方は `強く' 推奨されません。 @ref{ad1,,__import__()} を直接使用することも推奨されず、 @ref{73c,,importlib.import_module()} の方が好まれます。

この関数は、モジュール `name' をインポートし、 `globals' と `locals' が与えられれば、パッケージのコンテキストで名前をどう解釈するか決定するのに使います。 `fromlist' は `name' で与えられるモジュールからインポートされるべきオブジェクトまたはサブモジュールの名前を与ます。標準の実装では `locals' 引数はまったく使われず、 `globals' は @ref{7f8,,import} 文のパッケージコンテキストを決定するためにのみ使われます。

`level' は絶対と相対どちらのインポートを使うかを指定します。 @code{0} (デフォルト) は絶対インポートのみ実行します。正の `level' の値は、 @ref{ad1,,__import__()} を呼び出したディレクトリから検索対象となる親ディレクトリの数を示します (詳細は 
@geindex Python Enhancement Proposals; PEP 328
PEP 328@footnote{https://peps.python.org/pep-0328/} を参照してください)。

`name' 変数が @code{package.module} 形式であるとき、通常は、`name' で指名されたモジュール `ではなく'、最上位のパッケージ (最初のドットまでの名前) が返されます。しかしながら、空でない `fromlist' 引数が与えられると、 `name' で指名されたモジュールが返されます。

例えば、文 @code{import spam} は、以下のコードのようなバイトコードに帰結します:

@example
spam = __import__('spam', globals(), locals(), [], 0)
@end example

文 @code{import spam.ham} は、この呼び出しになります:

@example
spam = __import__('spam.ham', globals(), locals(), [], 0)
@end example

ここで @ref{ad1,,__import__()} がどのように最上位モジュールを返しているかに注意して下さい。 @ref{7f8,,import} 文により名前が束縛されたオブジェクトになっています。

一方で、文 @code{from spam.ham import eggs, sausage as saus} は、以下となります

@example
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
@end example

ここで、@ref{ad1,,__import__()} から @code{spam.ham} モジュールが返されます。このオブジェクトから、インポートされる名前が取り出され、それぞれの名前として代入されます。

単純に名前からモジュール (パッケージの範囲内であるかも知れません) をインポートしたいなら、 @ref{73c,,importlib.import_module()} を使ってください。


バージョン 3.3 で変更: 負の `level' の値はサポートされなくなりました (デフォルト値の 0 に変更されます)。



バージョン 3.9 で変更: コマンドラインオプション @ref{b56,,-E} or @ref{b57,,-I} が指定された場合、環境変数 
@geindex PYTHONCASEOK
@geindex 環境変数; PYTHONCASEOK
@ref{b55,,PYTHONCASEOK} は無視されるようになりました。

@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 組み込み定数,組み込み型,組み込み関数,Python 標準ライブラリ
@anchor{library/constants doc}@anchor{25e1}@anchor{library/constants built-in-constants}@anchor{25e2}@anchor{library/constants built-in-consts}@anchor{2477}@anchor{library/constants translation-repo}@anchor{25e3}
@section 組み込み定数


組み込み名前空間にはいくつかの定数があります。定数の一覧:

@geindex False (組み込み変数)
@anchor{library/constants False}@anchor{d2b}
@deffn {データ} False

@ref{3c3,,bool} 型の偽値です。@code{False} への代入は不正で、@ref{18e,,SyntaxError} を送出します。
@end deffn

@geindex True (組み込み変数)
@anchor{library/constants True}@anchor{e07}
@deffn {データ} True

@ref{3c3,,bool} 型の真値です。@code{True} への代入は不正で、@ref{18e,,SyntaxError} を送出します。
@end deffn

@geindex None (組み込み変数)
@anchor{library/constants None}@anchor{885}
@deffn {データ} None

関数にデフォルト引数が渡されなかったときなどに、値の非存在を表すのに頻繁に用いられるオブジェクトです。@code{None} への代入は不正で、@ref{18e,,SyntaxError} を送出します。@code{None} が @ref{a52,,NoneType} 型の唯一のインスタンスです。
@end deffn

@geindex NotImplemented (組み込み変数)
@anchor{library/constants NotImplemented}@anchor{1a2}
@deffn {データ} NotImplemented

特殊な二項演算のメソッド (e.g. @ref{cf2,,__eq__()}, @ref{14b8,,__lt__()}, @ref{23dd,,__add__()}, @ref{23f0,,__rsub__()}, etc.) が、他の型に対して演算が実装されていないことを示すために返す特殊値です。インプレースの特殊な二項演算のメソッド (e.g. @ref{23e2,,__imul__()}, @ref{23ff,,__iand__()}, etc.) も同じ理由でこの値を返すことがあります。この処理では真偽値コンテキストでの評価はしてはいけません。@code{NotImplemented} が @ref{a53,,types.NotImplementedType} 型の唯一のインスタンスです。

@cartouche
@quotation 注釈 
二項演算の (あるいはインプレースの) メソッドが @code{NotImplemented} を返した場合、インタープリタはもう一方の型で定義された対の演算で代用を試みます (あるいは演算によっては他の代替手段も試みます)。試行された演算全てが @code{NotImplemented} を返した場合、インタープリタは適切な例外を送出します。 @code{NotImplemented} を正しく返さないと、誤解を招きかねないエラーメッセージになったり、 @code{NotImplemented} が Python コードに返されるようなことになります。

例として @ref{2332,,算術演算の実装} を参照してください。
@end quotation
@end cartouche

@cartouche
@quotation 注意 
@code{NotImplemented} and @code{NotImplementedError} are not
interchangeable. This constant should only be used as described
above; see @ref{36b,,NotImplementedError} for details on correct usage
of the exception.
@end quotation
@end cartouche


バージョン 3.9 で変更: Evaluating @code{NotImplemented} in a boolean context was deprecated.



バージョン 3.14 で変更: Evaluating @code{NotImplemented} in a boolean context now raises a @ref{198,,TypeError}.
It previously evaluated to @ref{e07,,True} and emitted a @ref{1a3,,DeprecationWarning}
since Python 3.9.

@end deffn

@geindex ...;ellipsisリテラル

@geindex Ellipsis (組み込み変数)
@anchor{library/constants Ellipsis}@anchor{2328}
@deffn {データ} Ellipsis

The same as the ellipsis literal "@code{...}", an object frequently used to
indicate that something is omitted. Assignment to @code{Ellipsis} is possible, but
assignment to  @code{...} raises a @ref{18e,,SyntaxError}.
@code{Ellipsis} is the sole instance of the @ref{a51,,types.EllipsisType} type.
@end deffn

@geindex __debug__ (組み込み変数)
@anchor{library/constants debug__}@anchor{9da}
@deffn {データ} __debug__

この定数は、Python が @ref{18c,,-O} オプションを有効にして開始されたのでなければ真です。 @ref{b60,,assert} 文も参照して下さい。
@end deffn

@cartouche
@quotation 注釈 
名前 @ref{885,,None} 、 @ref{d2b,,False} 、 @ref{e07,,True} 、 @ref{9da,,__debug__} は再代入できない (これらに対する代入は、たとえ属性名としてであっても @ref{18e,,SyntaxError} が送出されます) ので、これらは「真の」定数であると考えられます。
@end quotation
@end cartouche

@menu
* site モジュールで追加される定数:: 

@end menu

@node site モジュールで追加される定数,,,組み込み定数
@anchor{library/constants constants-added-by-the-site-module}@anchor{25e4}@anchor{library/constants site-consts}@anchor{25e5}
@subsection @code{site} モジュールで追加される定数


@ref{cc,,site} モジュール (@ref{13c0,,-S} コマンドラインオプションが指定されない限り、スタートアップ時に自動的にインポートされます) は組み込み名前空間にいくつかの定数を追加します。それらは対話的インタープリタシェルで有用ですが、プログラム中では使うべきではありません。

@geindex quit (組み込み変数)
@geindex exit (組み込み変数)
@anchor{library/constants quit}@anchor{25e6}
@deffn {データ} quit (code=None)
@anchor{library/constants exit}@anchor{25e7}
@deffnx {データ} exit (code=None)

Objects that when printed, print a message like "Use quit() or Ctrl-D
(i.e. EOF) to exit", and when accessed directly in the interactive
interpreter or called as functions, raise @ref{f3c,,SystemExit} with the
specified exit code.
@end deffn


@deffn {データ} help

Object that when printed, prints the message "Type help() for interactive
help, or help(object) for help about object.", and when accessed directly
in the interactive interpreter, invokes the built-in help system
(see @ref{ad4,,help()}).
@end deffn

@geindex copyright (組み込み変数)
@geindex credits (組み込み変数)
@anchor{library/constants copyright}@anchor{1788}
@deffn {データ} copyright
@anchor{library/constants credits}@anchor{1789}
@deffnx {データ} credits

表示あるいは呼び出されたときに、それぞれ著作権あるいはクレジットのテキストが表示されるオブジェクトです。
@end deffn

@geindex license (組み込み変数)
@anchor{library/constants license}@anchor{1787}
@deffn {データ} license

表示されたときに "Type license() to see the full license text" というメッセージを表示し、呼び出されたときには完全なライセンスのテキストをページャのような形式で (1画面分づつ) 表示するオブジェクトです。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c XXX: reference/datamodel and this have quite a few overlaps!

@node 組み込み型,組み込み例外,組み込み定数,Python 標準ライブラリ
@anchor{library/stdtypes doc}@anchor{25e8}@anchor{library/stdtypes bltin-types}@anchor{25e9}@anchor{library/stdtypes built-in-types}@anchor{25ea}@anchor{library/stdtypes translation-repo}@anchor{25eb}
@section 組み込み型


以下のセクションでは、インタプリタに組み込まれている標準型について記述します。

@geindex 組み込み;types

主要な組み込み型は、数値、シーケンス、マッピング、クラス、インスタンス、および例外です。

コレクションクラスには、ミュータブルなものがあります。コレクションのメンバをインプレースに足し、引き、または並べ替えて、特定の要素を返さないメソッドは、コレクション自身ではなく @code{None} を返します。

演算には、複数の型でサポートされているものがあります; 特に、ほぼ全てのオブジェクトは、等価比較でき、真理値を判定でき、 (@ref{1c1,,repr()} 関数や、わずかに異なる @ref{169,,str()} 関数によって) 文字列に変換できます。オブジェクトが @ref{1177,,print()} 関数で印字されるとき、文字列に変換する関数が暗黙に使われます。

@menu
* 真理値判定:: 
* ブール演算: ブール演算 --- and or not. and, or, not
* 比較: 比較<2>. 
* 数値型 int@comma{} float@comma{} complex: 数値型 int float complex. 
* ブーリアン型 - bool:: 
* イテレータ型:: 
* シーケンス型: シーケンス型 --- list tuple range. list, tuple, range
* Text and Binary Sequence Type Methods Summary:: 
* テキストシーケンス型: テキストシーケンス型 --- str. str
* バイナリシーケンス型: バイナリシーケンス型 --- bytes bytearray memoryview. bytes, bytearray, memoryview
* set（集合）型: set（集合）型 --- set frozenset. set, frozenset
* マッピング型: マッピング型 --- dict. dict
* コンテキストマネージャ型:: 
* 型アノテーション型: 型アノテーション型 --- ジェネリックエイリアス 、 ユニオン. ジェネリックエイリアス 、 ユニオン
* その他の組み込み型:: 
* 特殊属性:: 
* 整数と文字列の変換での長さ制限:: 

@end menu

@node 真理値判定,ブール演算 --- and or not,,組み込み型
@anchor{library/stdtypes truth}@anchor{1858}@anchor{library/stdtypes truth-value-testing}@anchor{25ec}
@subsection 真理値判定


@geindex statement;if
@geindex statement;while
@geindex 真理値;value
@geindex Boolean;操作
@geindex false

どのようなオブジェクトでも真理値として判定でき、 @ref{181,,if} や @ref{1973,,while} の条件あるいは以下のブール演算の被演算子として使えます。

@geindex true

By default, an object is considered true unless its class defines either a
@ref{14ed,,__bool__()} method that returns @code{False} or a
@ref{178f,,__len__()} method that
returns zero, when called with the object. @footnote{
これらの特殊なメソッドのさらなる情報については、 Python リファレンスマニュアル (@ref{23ad,,基本的なカスタマイズ}) を参照してください。
} If one of the methods raises an
exception when called, the exception is propagated and the object does
not have a truth value (for example, @ref{1a2,,NotImplemented}).
Here are most of the built-in objects considered false:

@geindex None (組み込みオブジェクト)
@geindex False (組み込みオブジェクト)


@itemize *

@item 
偽であると定義されている定数: @code{None} と @code{False}

@item 
数値型におけるゼロ: @code{0}, @code{0.0}, @code{0j}, @code{Decimal(0)}, @code{Fraction(0, 1)}

@item 
空のシーケンスまたはコレクション: @code{'@w{'}}, @code{()}, @code{[]}, @code{@{@}}, @code{set()}, @code{range(0)}
@end itemize

@geindex operator;or
@geindex operator;and
@geindex False
@geindex True

ブール値の結果を返す演算および組み込み関数は、特に注釈のない限り常に偽値として @code{0} または @code{False} を返し、真値として @code{1} または @code{True} を返します。 (重要な例外: ブール演算 @code{or} および @code{and} は常に被演算子のうちの一つを返します。)

@node ブール演算 --- and or not,比較<2>,真理値判定,組み込み型
@anchor{library/stdtypes boolean}@anchor{25ed}@anchor{library/stdtypes boolean-operations-and-or-not}@anchor{25ee}
@subsection ブール演算 --- @code{and}, @code{or}, @code{not}


@geindex Boolean;操作

以下にブール演算を、優先順位が低い順に示します:


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

演算

@tab

結果

@tab

注釈

@item

@code{x or y}

@tab

`x' が真なら `x', そうでなければ `y'

@tab

(1)

@item

@code{x and y}

@tab

`x' が偽なら `x', そうでなければ `y'

@tab

(2)

@item

@code{not x}

@tab

`x' が偽なら @code{True}, そうでなければ @code{False}

@tab

(3)

@end multitable


@geindex operator;and
@geindex operator;or
@geindex operator;not

注釈:


@enumerate 

@item 
この演算子は短絡評価されます。つまり第一引数が偽のときにのみ、第二引数が評価されます。

@item 
この演算子は短絡評価されます。つまり第一引数が真のときにのみ、第二引数が評価されます。

@item 
@code{not} は非ブール演算子よりも優先度が低いので、 @code{not a == b} は @code{not (a == b)} と解釈され、 @code{a == not b} は構文エラーです。
@end enumerate

@node 比較<2>,数値型 int float complex,ブール演算 --- and or not,組み込み型
@anchor{library/stdtypes comparisons}@anchor{25ef}@anchor{library/stdtypes stdcomparisons}@anchor{25f0}
@subsection 比較


@geindex 連鎖;比較
@geindex operator;比較
@geindex operator;==
@geindex operator;< (小さい)
@geindex operator;<=
@geindex operator;> (大きい)
@geindex operator;>=
@geindex operator;!=
@geindex operator;is
@geindex operator;is not

Python には 8 種の比較演算があります。比較演算の優先順位は全て同じです (ブール演算より高い優先順位です)。比較は任意に連鎖できます; 例えば、 @code{x < y <= z} は @code{x < y and y <= z} とほぼ等価ですが、この `y' は一度だけしか評価されません (どちらにしても、 @code{x < y} が偽となれば `z' は評価されません)。

以下の表に比較演算をまとめます:


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

意味

@item

@code{<}

@tab

より小さい

@item

@code{<=}

@tab

以下

@item

@code{>}

@tab

より大きい

@item

@code{>=}

@tab

以上

@item

@code{==}

@tab

等しい

@item

@code{!=}

@tab

等しくない

@item

@code{is}

@tab

同一のオブジェクトである

@item

@code{is not}

@tab

同一のオブジェクトでない

@end multitable


@geindex object;数値
@geindex オブジェクト;比較する

明記されている場合を除き、異なる型のオブジェクト同士は等価になることはありません。 @code{==} 演算子は常に定義されていますが、いくつかのオブジェクト型 (たとえばクラスオブジェクト) では @ref{34c,,is} と同等になります。 @code{<}, @code{<=}, @code{>} および @code{>=} 演算子は、それらの意味が明快である場合に限って定義されます; たとえば、オペランドのいずれかが複素数である場合、これらの演算子は @ref{198,,TypeError} 例外を送出します。

@geindex __eq__() (インスタンスメソッド)
@geindex __ne__() (インスタンスメソッド)
@geindex __lt__() (インスタンスメソッド)
@geindex __le__() (インスタンスメソッド)
@geindex __gt__() (インスタンスメソッド)
@geindex __ge__() (インスタンスメソッド)

あるクラスの同一でないインスタンスは、通常等価でないとされますが、そのクラスが @ref{cf2,,__eq__()} メソッドを定義している場合は除きます。

クラスのインスタンスは、そのクラスがメソッド @ref{14b8,,__lt__()} 、 @ref{1522,,__le__()} 、 @ref{1523,,__gt__()} 、 @ref{1524,,__ge__()} のうち十分なものを定義していない限り、同じクラスの別のインスタンスや他の型のオブジェクトとは順序付けできません (一般に、比較演算子の通常の意味を求めるなら、 @ref{14b8,,__lt__()} と @ref{cf2,,__eq__()} だけで十分です)。

@ref{34c,,is} および @ref{24d7,,is not} 演算子の振る舞いはカスタマイズできません。また、これらはいかなる 2 つのオブジェクトにも適用でき、決して例外を送出しません。

@geindex operator;in
@geindex operator;not in

@ref{34b,,in} と @ref{841,,not in} という構文上で同じ優先度を持つ演算子がさらに 2 つあり、 @ref{12f1,,iterable} または @ref{15d3,,__contains__()} を実装した型でサポートされています。

@node 数値型 int float complex,ブーリアン型 - bool,比較<2>,組み込み型
@anchor{library/stdtypes numeric-types-int-float-complex}@anchor{25f1}@anchor{library/stdtypes typesnumeric}@anchor{1fdc}
@subsection 数値型 @code{int}, @code{float}, @code{complex}


@geindex object;数値
@geindex object;Boolean
@geindex object;整数
@geindex object;浮動小数点
@geindex object;complex number
@geindex C;言語

数値型には 3 種類あります: `整数' 、 `浮動小数点数' 、 `複素数' です。さらに、ブール型は整数のサブタイプです。整数には精度の制限がありません。浮動小数点型はたいていは C の double を使って実装されています; あなたのプログラムが動作するマシンでの浮動小数点型の精度と内部表現は、 @ref{1dcf,,sys.float_info} から入手可能です。複素数は実部と虚部を持ち、それぞれが浮動小数点数です。複素数 `z' から実部および虚部を取り出すには、 @code{z.real} および @code{z.imag} を使ってください。 (標準ライブラリには、さらに分数のための数値型 @ref{213,,fractions.Fraction} や、ユーザによる精度の定義が可能な浮動小数点数のための @ref{1fe,,decimal.Decimal} があります。)

@geindex 数値;リテラル
@geindex 整数;リテラル
@geindex 浮動小数点;リテラル
@geindex complex number;リテラル
@geindex 16進数;リテラル
@geindex 8進数;リテラル
@geindex 2進数;リテラル

数値は、数値リテラルによって、あるいは組み込み関数や演算子の戻り値として生成されます。 (十六進、八進、二進数を含む) 修飾のない整数リテラルは、整数を生成します。小数点または指数表記を含む数値リテラルは浮動小数点数を生成します。数値リテラルに @code{'j'} または @code{'J'} をつけると純虚数 (実部がゼロの複素数) を生成し、それに整数や浮動小数点数を加えることにより実部と虚部を持つ複素数を得ることができます。

コンストラクタ @ref{19b,,int()} 、 @ref{196,,float()} 、 @ref{197,,complex()} で、特定の型の数を生成できます。

@geindex 算術
@geindex 組み込み関数;int
@geindex 組み込み関数;浮動小数点数
@geindex 組み込み関数;複素数
@geindex operator;+ (プラス記号)
@geindex + (プラス記号);単項演算子
@geindex + (プラス記号);二項演算子
@geindex operator;- (負符号)
@geindex - (負符号);単項演算子
@geindex - (負符号);二項演算子
@geindex operator;* (アスタリスク)
@geindex operator;/ (スラッシュ)
@geindex operator;//
@geindex operator;% (パーセント)
@geindex operator;**
@anchor{library/stdtypes stdtypes-mixed-arithmetic}@anchor{2469}
Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different built-in numeric types, the operand with the "narrower"
type is widened to that of the other:


@itemize *

@item 
If both arguments are complex numbers, no conversion is performed;

@item 
if either argument is a complex or a floating-point number, the other is
converted to a floating-point number;

@item 
otherwise, both must be integers and no conversion is necessary.
@end itemize

Arithmetic with complex and real operands is defined by the usual mathematical
formula, for example:

@example
x + complex(u, v) = complex(x + u, v)x * complex(u, v) = complex(x * u, x * v)
@end example

A comparison between numbers of different types behaves as though the exact
values of those numbers were being compared. @footnote{
この結果として、リスト @code{[1, 2]} は @code{[1.0, 2.0]} と等しいと見なされます。タプルの場合も同様です。
}

全ての (複素数を除く) 組み込み数値型は以下の演算に対応しています (演算の優先順位については、 @ref{24eb,,演算子の優先順位} を参照してください):


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@tab

注釈

@tab

完全なドキュメント

@item

@code{x + y}

@tab

`x' と `y' の和

@tab

@tab

@item

@code{x - y}

@tab

`x' と `y' の差

@tab

@tab

@item

@code{x * y}

@tab

`x' と `y' の積

@tab

@tab

@item

@code{x / y}

@tab

`x' と `y' の商

@tab

@tab

@item

@code{x // y}

@tab

`x' と `y' の商を切り下げたもの

@tab

(1)(2)

@tab

@item

@code{x % y}

@tab

@code{x / y} の剰余

@tab

(2)

@tab

@item

@code{-x}

@tab

`x' の符号反転

@tab

@tab

@item

@code{+x}

@tab

`x' そのまま

@tab

@tab

@item

@code{abs(x)}

@tab

`x' の絶対値または大きさ

@tab

@tab

@ref{208d,,abs()}

@item

@code{int(x)}

@tab

`x' の整数への変換

@tab

(3)(6)

@tab

@ref{19b,,int()}

@item

@code{float(x)}

@tab

`x' の浮動小数点数への変換

@tab

(4)(6)

@tab

@ref{196,,float()}

@item

@code{complex(re, im)}

@tab

実部 `re', 虚部 `im' の複素数。 `im' の既定値はゼロ。

@tab

(6)

@tab

@ref{197,,complex()}

@item

@code{c.conjugate()}

@tab

複素数 `c' の共役複素数

@tab

@tab

@item

@code{divmod(x, y)}

@tab

@code{(x // y, x % y)} からなるペア

@tab

(2)

@tab

@ref{b99,,divmod()}

@item

@code{pow(x, y)}

@tab

`x' の `y' 乗

@tab

(5)

@tab

@ref{1a4,,pow()}

@item

@code{x ** y}

@tab

`x' の `y' 乗

@tab

(5)

@tab

@end multitable


@geindex 演算;数値;types
@geindex conjugate() (複素数のメソッド)

注釈:


@enumerate 

@item 
整数の除算とも呼ばれます。 @ref{19b,,int} 型のオペランドに対しては、結果は @ref{19b,,int} 型になります。 @ref{196,,float} 型のオペランドに対しては、結果は @ref{196,,float} 型になります。一般に結果の型は必ずしも @ref{19b,,int} 型ではありませんが、結果は常に整数です。結果は常に負の無限大の方向に丸められます: @code{1//2} は @code{0} 、 @code{(-1)//2} は @code{-1} 、 @code{1//(-2)} は @code{-1} 、そして @code{(-1)//(-2)} は @code{0} です。

@item 
複素数型には使えません。適用可能な場合には代わりに @ref{208d,,abs()} で浮動小数点型に変換してください。

@item 
@geindex module;math
@geindex floor() (math モジュール)
@geindex ceil() (math モジュール)
@geindex trunc() (math モジュール)
@geindex 数値;変換

@ref{196,,float} から @ref{19b,,int} への変換は小数点以下を切り捨てます。別の変換方法については関数 @ref{15d7,,math.floor()} や @ref{15d8,,math.ceil()} を参照してください。

@item 
浮動小数点数は、文字列 "nan" と "inf" を、オプションの接頭辞 "+" または "-" と共に、非数 (Not a Number (NaN)) や正、負の無限大として受け付けます。

@item 
Python は、プログラム言語一般でそうであるように、 @code{pow(0, 0)} および @code{0 ** 0} を @code{1} と定義します。

@item 
受け付けられる数値リテラルは数字 @code{0} から @code{9} または等価な Unicode (@code{Nd} プロパティを持つコードポイント) を含みます。

@code{Nd} プロパティを持つコードポイントの完全なリストは Unicode 標準@footnote{https://unicode.org/Public/UNIDATA/extracted/DerivedNumericType.txt} をご覧ください。
@end enumerate

全ての @ref{25f2,,numbers.Real} 型 (@ref{19b,,int} 、 @ref{196,,float}) は以下の演算も含みます:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@item

@ref{15d9,,math.trunc(x)}

@tab

`x' を @ref{240a,,Integral} (整数) に切り捨てます

@item

@ref{14f2,,round(x[@comma{} n])}

@tab

`x' を `n' 桁に丸めます。丸め方は偶数丸めです。 `n' が省略されれば 0 がデフォルトとなります。

@item

@ref{15d7,,math.floor(x)}

@tab

`x' 以下の最大の @ref{240a,,Integral} (整数) を返します

@item

@ref{15d8,,math.ceil(x)}

@tab

`x' 以上の最小の @ref{240a,,Integral} (整数) を返します

@end multitable


その他の数値演算は、 @ref{92,,math} や @ref{19,,cmath} モジュールをご覧ください。

@c XXXJH exceptions: overflow (when? what operations?) zerodivision

@menu
* 整数型におけるビット単位演算:: 
* 整数型における追加のメソッド:: 
* 浮動小数点数に対する追加のメソッド:: 
* 複素数に対する追加のメソッド:: 
* 数値型のハッシュ化:: 

@end menu

@node 整数型におけるビット単位演算,整数型における追加のメソッド,,数値型 int float complex
@anchor{library/stdtypes bitstring-ops}@anchor{25f3}@anchor{library/stdtypes bitwise-operations-on-integer-types}@anchor{25f4}
@subsubsection 整数型におけるビット単位演算


@geindex 演算;整数;types
@geindex ビット単位;操作
@geindex シフト;操作
@geindex ビットマスク;操作
@geindex operator;| (縦棒)
@geindex operator;^ (キャレット)
@geindex operator;& (アンパサンド)
@geindex operator;<<
@geindex operator;>>
@geindex operator;~ (チルダ)

ビット単位演算は整数についてのみ意味を持ちます。
ビット単位演算の結果は、あたかも両方の値の先頭を無限個の符号ビットで埋めたものに対して計算したかのような値になります。

二項ビット単位演算の優先順位は全て、数値演算よりも低く、比較よりも高くなっています; 単項演算 @code{~} の優先順位は他の単項数値演算 (@code{+} および @code{-}) と同じです。

以下の表では、ビット単位演算を優先順位が低い順に並べています:


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@tab

注釈

@item

@code{x | y}

@tab

`x' と `y' のビット単位 `論理和'

@tab

(4)

@item

@code{x ^ y}

@tab

`x' と `y' のビット単位 `排他的論理和'

@tab

(4)

@item

@code{x & y}

@tab

`x' と `y' のビット単位 `論理積'

@tab

(4)

@item

@code{x << n}

@tab

`x' の `n' ビット左シフト

@tab

(1)(2)

@item

@code{x >> n}

@tab

`x' の `n' ビット右シフト

@tab

(1)(3)

@item

@code{~x}

@tab

`x' のビット反転

@tab

@end multitable


注釈:


@enumerate 

@item 
負値のシフト数は不正であり、 @ref{2ec,,ValueError} が送出されます。

@item 
`n' ビットの左シフトは、 @code{pow(2, n)} による乗算と等価です。

@item 
`n' ビットの右シフトは、 @code{pow(2, n)} による切り捨て除算と等価です。

@item 
桁の長い方の値に少なくとも 1 つ余計に符号ビットを付け加えた幅 (計算するビット幅は @code{1 + max(x.bit_length(), y.bit_length())} かそれ以上) でこれらの計算を行えば、無限個の符号ビットがあるかのように計算したのと同じ結果を得るのに十分です。
@end enumerate

@node 整数型における追加のメソッド,浮動小数点数に対する追加のメソッド,整数型におけるビット単位演算,数値型 int float complex
@anchor{library/stdtypes additional-methods-on-integer-types}@anchor{25f5}
@subsubsection 整数型における追加のメソッド


整数型は @ref{240a,,numbers.Integral} @ref{13ce,,抽象基底クラス} を実装します。さらに、追加のメソッドをいくつか提供します:

@geindex bit_length() (int のメソッド)
@anchor{library/stdtypes int bit_length}@anchor{25f6}
@deffn {メソッド} int.bit_length ()

整数を、符号と先頭の 0 は除いて二進法で表すために必要なビットの数を返します:

@example
>>> n = -37>>> bin(n)'-0b100101'>>> n.bit_length()6
@end example

正確には、 @code{x} が非 0 なら、 @code{x.bit_length()} は @code{2**(k-1) <= abs(x) < 2**k} を満たす唯一の正の整数 @code{k} です。同様に、 @code{abs(x)} が十分小さくて対数を適切に丸められるとき、 @code{k = 1 + int(log(abs(x), 2))} です。 @code{x} が 0 なら、 @code{x.bit_length()} は @code{0} を返します。

次と等価です:

@example
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
@end example


Added in version 3.1.

@end deffn

@geindex bit_count() (int のメソッド)
@anchor{library/stdtypes int bit_count}@anchor{9cf}
@deffn {メソッド} int.bit_count ()

整数の絶対値の二進数表現における 1 の数を返します。これは population count としても知られています。 例:

@example
>>> n = 19>>> bin(n)'0b10011'>>> n.bit_count()3>>> (-n).bit_count()3
@end example

次と等価です:

@example
def bit_count(self):
    return bin(self).count("1")
@end example


Added in version 3.10.

@end deffn

@geindex to_bytes() (int のメソッド)
@anchor{library/stdtypes int to_bytes}@anchor{1c32}
@deffn {メソッド} int.to_bytes (length=1, byteorder='big', *, signed=False)

整数を表すバイト列を返します。

@example
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'
@end example

整数は `length' バイトで表されます、デフォルト値は 1 です。整数が与えられた数のバイトで表せなければ、 @ref{a81,,OverflowError} が送出されます。

`byteorder' 引数は、整数を表すのに使われるバイトオーダーを決定します。デフォルト値は @code{"big"} です。 `byteorder' が @code{"big"} なら、最上位のバイトがバイト配列の最初に来ます。 `byteorder' が @code{"little"} なら、最上位のバイトがバイト配列の最後に来ます。

`signed' 引数は、整数を表すのに 2 の補数を使うかどうかを決定します。 `signed' が @code{False} で、負の整数が与えられたなら、 @ref{a81,,OverflowError}  が送出されます。 `signed' のデフォルト値は @code{False} です。

上記のデフォルト値は整数を 1 バイトのオブジェクトに適切に変換するのに使うことができます:

@example
>>> (65).to_bytes()
b'A'
@end example

ただし、デフォルト引数で 255 より大きな整数を変換しないでください。 そうでなければ @ref{a81,,OverflowError} 例外を引き起こします。

次と等価です:

@example
def to_bytes(n, length=1, byteorder='big', signed=False):
    if byteorder == 'little':
        order = range(length)
    elif byteorder == 'big':
        order = reversed(range(length))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

    return bytes((n >> i*8) & 0xff for i in order)
@end example


Added in version 3.2.



バージョン 3.11 で変更: @code{length} と @code{byteorder} 引数にデフォルト値を追加しました。

@end deffn

@geindex from_bytes() (int のクラスメソッド)
@anchor{library/stdtypes int from_bytes}@anchor{1be9}
@deffn {メソッド} classmethod int.from_bytes (bytes, byteorder='big', *, signed=False)

与えられたバイト列の整数表現を返します。

@example
>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680
@end example

引数 `bytes' は @ref{193,,bytes-like object} か、または bytes を生成する iterable でなければなりません。

`byteorder' 引数は、整数を表すのに使われるバイトオーダーを決定します。デフォルト値は @code{"big"} です。 `byteorder' が @code{"big"} なら、最上位のバイトがバイト配列の最初に来ます。 `byteorder' が @code{"little"} なら、最上位のバイトがバイト配列の最後に来ます。ホストシステムにネイティブのバイトオーダーを要求するには、 @ref{25f7,,sys.byteorder} をバイトオーダーの値として使ってください。

`signed' 引数は、整数を表すのに 2 の補数を使うかどうかを決定します。

次と等価です:

@example
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

    n = sum(b << i*8 for i, b in enumerate(little_ordered))
    if signed and little_ordered and (little_ordered[-1] & 0x80):
        n -= 1 << 8*len(little_ordered)

    return n
@end example


Added in version 3.2.



バージョン 3.11 で変更: @code{byteorder} 引数にデフォルト値を追加しました。

@end deffn

@geindex as_integer_ratio() (int のメソッド)
@anchor{library/stdtypes int as_integer_ratio}@anchor{bc0}
@deffn {メソッド} int.as_integer_ratio ()

比が元の数と等しくなるような整数のペアを返します。戻り値の分母に相当する数は正の整数です。元の数が整数の場合の比は、常にその整数が分子であり、分母は @code{1} です。


Added in version 3.8.

@end deffn

@geindex is_integer() (int のメソッド)
@anchor{library/stdtypes int is_integer}@anchor{1aeb}
@deffn {メソッド} int.is_integer ()

常に @code{True} を返します。 @ref{25f8,,float.is_integer()} に対するダックタイピングの互換性のために存在しています。


Added in version 3.12.

@end deffn

@node 浮動小数点数に対する追加のメソッド,複素数に対する追加のメソッド,整数型における追加のメソッド,数値型 int float complex
@anchor{library/stdtypes additional-methods-on-float}@anchor{25f9}
@subsubsection 浮動小数点数に対する追加のメソッド


浮動小数点数型は、 @ref{25f2,,numbers.Real} @ref{13ce,,抽象基底クラス} を実装しています。浮動小数点型はまた、以下の追加のメソッドを持ちます。

@geindex from_number() (float のクラスメソッド)
@anchor{library/stdtypes float from_number}@anchor{194}
@deffn {メソッド} classmethod float.from_number (x)

数 `x' から生成された浮動小数点数を返すクラスメソッドです。

引数が整数または浮動小数点数の場合、(Python の浮動小数点数の精度で) 同じ値の浮動小数点数が返されます。  引数が Python の浮動小数点数の範囲外なら、 @ref{a81,,OverflowError} が送出されます。

一般の Python オブジェクト @code{x} に対して、@code{float.from_number(x)} は @code{x.__float__()} に委譲します。 @ref{bc1,,__float__()} が定義されていない場合、@ref{19e,,__index__()} へフォールバックします。


Added in version 3.14.

@end deffn

@geindex as_integer_ratio() (float のメソッド)
@anchor{library/stdtypes float as_integer_ratio}@anchor{2102}
@deffn {メソッド} float.as_integer_ratio ()

比が厳密に元の浮動小数点数であるような一対の整数を返します。比は既約分数として与えられ、分母は正の値です。無限大に対しては @ref{a81,,OverflowError} を、非数 (NaN) に対しては @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex is_integer() (float のメソッド)
@anchor{library/stdtypes float is_integer}@anchor{25f8}
@deffn {メソッド} float.is_integer ()

浮動小数点数インスタンスが有限の整数値なら @code{True} を、そうでなければ @code{False} を返します:

@example
>>> (-2.0).is_integer()True>>> (3.2).is_integer()False
@end example
@end deffn

16 進表記の文字列へ、または、 16 進表記からの変換をサポートする二つのメソッドがあります。 Python の浮動小数点数は内部的には2進数で保持されるので、浮動小数点数の `10進数' へまたは `10進数' からの変換には若干の丸め誤差があります。それに対し、16 進表記では、浮動小数点数を正確に表現できます。これはデバッグのときや、数学的な用途 (numerical work) に便利でしょう。

@geindex hex() (float のメソッド)
@anchor{library/stdtypes float hex}@anchor{2103}
@deffn {メソッド} float.hex ()

浮動小数点数の 16 進文字列表現を返します。有限の浮動小数点数に対し、この表現は常に @code{0x} で始まり @code{p} と指数が続きます。
@end deffn

@geindex fromhex() (float のクラスメソッド)
@anchor{library/stdtypes float fromhex}@anchor{25fa}
@deffn {メソッド} classmethod float.fromhex (s)

16 進文字列表現 `s' で表される、浮動小数点数を返すクラスメソッドです。文字列 `s' は、前や後にホワイトスペースを含んでいても構いません。
@end deffn

@ref{25fa,,float.fromhex()} はクラスメソッドですが、 @ref{2103,,float.hex()} はインスタンスメソッドであることに注意して下さい。

16 進文字列表現は以下の書式となります:

@example
[sign] ['0x'] integer ['.' fraction] ['p' exponent]
@end example

@code{sign} は必須ではなく、 @code{+} と @code{-} のどちらかです。 @code{integer} と @code{fraction} は 16 進数の文字列で、 @code{exponent} は 10 進数で符号もつけられます。大文字・小文字は区別されず、最低でも 1 つの 16 進数文字を整数部もしくは小数部に含む必要があります。この制限は C99 規格のセクション 6.4.4.2 で規定されていて、 Java 1.5 以降でも使われています。特に、 @ref{2103,,float.hex()} の出力は C や Java コード中で、浮動小数点数の 16 進表記として役に立つでしょう。また、 C の @code{%a} 書式や、 Java の @code{Double.toHexString} で書きだされた文字列は @ref{25fa,,float.fromhex()} で受け付けられます。

なお、指数部は 16 進数ではなく 10 進数で書かれ、係数に掛けられる 2 の累乗を与えます。例えば、16 進文字列 @code{0x3.a7p10} は浮動小数点数 @code{(3 + 10./16 + 7./16**2) * 2.0**10} すなわち @code{3740.0} を表します:

@example
>>> float.fromhex('0x3.a7p10')3740.0
@end example

逆変換を @code{3740.0} に適用すると、同じ数を表す異なる 16 進文字列表現を返します:

@example
>>> float.hex(3740.0)'0x1.d380000000000p+11'
@end example

@node 複素数に対する追加のメソッド,数値型のハッシュ化,浮動小数点数に対する追加のメソッド,数値型 int float complex
@anchor{library/stdtypes additional-methods-on-complex}@anchor{25fb}
@subsubsection 複素数に対する追加のメソッド


@code{complex} 型は、 @ref{25fc,,numbers.Complex} @ref{13ce,,抽象基底クラス} を実装しています。@code{complex} 型はまた、以下の追加のメソッドを持ちます。

@geindex from_number() (complex のクラスメソッド)
@anchor{library/stdtypes complex from_number}@anchor{195}
@deffn {メソッド} classmethod complex.from_number (x)

数値を複素数に変換するクラスメソッドです。

一般的な Python オブジェクト @code{x} に対して、 @code{complex.from_number(x)} は @code{x.__complex__()} に処理を委譲します。 @ref{7fd,,__complex__()} が定義されていない場合は @ref{bc1,,__float__()} にフォールバックします。 @code{__float__()} も定義されていない場合は @ref{19e,,__index__()} にフォールバックします。


Added in version 3.14.

@end deffn

@node 数値型のハッシュ化,,複素数に対する追加のメソッド,数値型 int float complex
@anchor{library/stdtypes hashing-of-numeric-types}@anchor{25fd}@anchor{library/stdtypes numeric-hash}@anchor{25fe}
@subsubsection 数値型のハッシュ化


数 @code{x} と @code{y} に対して、型が異なっていたとしても、 @code{x == y} であれば必ず @code{hash(x) == hash(y)} であることが要請されます (詳細は @ref{cf3,,__hash__()}  メソッドドキュメントを参照してください)。実装の簡単さと 複数の数値型 (@ref{19b,,int} 、 @ref{196,,float} 、 @ref{1fe,,decimal.Decimal} 、 @ref{213,,fractions.Fraction} を含みます) 間の効率のため、Python の 数値型に対するハッシュ値はある単一の数学的関数に基づいていて、 その関数はすべての有理数に対し定義されているため、 @ref{19b,,int} と @ref{213,,fractions.Fraction} のすべてのインスタンスと、 @ref{196,,float} と @ref{1fe,,decimal.Decimal} のすべての有限なインスタンスに 対して適用されます。本質的には、この関数は定数の素数 @code{P} に対して @code{P} を法とする還元で与えられます。 値 @code{P} は、 @ref{1201,,sys.hash_info} の @ref{25ff,,modulus} 属性として Python で利用できます。

現在使われている素数は、32 bit C long のマシンでは @code{P = 2**31 - 1} 、 64-bit C long のマシンでは @code{P = 2**61 - 1} です。

詳細な規則はこうです:


@itemize -

@item 
@code{x = m / n} が非負の有理数で、 @code{n} が @code{P} で割り切れないなら、 @code{invmod(n, P)} を @code{n} を @code{P} で割った剰余の (剰余演算の意味での) 逆数を与えるものとして、 @code{hash(x)} を @code{m * invmod(n, P) % P} と定義します。

@item 
@code{x = m / n} が非負の有理数で、 @code{n} が @code{P} で割り切れる (が @code{m} は割り切れない) なら、 @code{n} は @code{P} で割った余りの逆数を持たず、上の規則は適用できません。この場合、 @code{hash(x)} を定数 @code{sys.hash_info.inf} と定義します。

@item 
@code{x = m / n} が負の有理数なら、 @code{hash(x)} を @code{-hash(-x)} と定義します。その結果のハッシュが @code{-1} なら、 @code{-2} に置き換えます。

@item 
特定の値 @code{sys.hash_info.inf} 、 @code{-sys.hash_info.inf} は、正の無限大、負の無限大のハッシュ値を (それぞれ) 表すのに使われます。

@item 
複素 (@ref{197,,complex}) 数 @code{z} に対して、実部と虚部のハッシュ値は、 @code{hash(z.real) + sys.hash_info.imag * hash(z.imag)} の @code{2**sys.hash_info.width} を法とする還元を計算することにより組み合わせられ、よってこれは @code{range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1))} に収まります。再び、結果が @code{-1} なら、 @code{-2} で置き換えられます。
@end itemize

上述の規則をわかりやすくするため、有理数 @ref{196,,float} や、 @ref{197,,complex} のハッシュを計算する組み込みのハッシュと等価な Python コードの例を挙げます:

@example
import sys, math

def hash_fraction(m, n):
    """Compute the hash of a rational number m / n.

    Assumes m and n are integers, with n positive.
    Equivalent to hash(fractions.Fraction(m, n)).

    """
    P = sys.hash_info.modulus
    # Remove common factors of P.  (Unnecessary if m and n already coprime.)
    while m % P == n % P == 0:
        m, n = m // P, n // P

    if n % P == 0:
        hash_value = sys.hash_info.inf
    else:
        # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
        # pow(n, P-2, P) gives the inverse of n modulo P.
        hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
    if m < 0:
        hash_value = -hash_value
    if hash_value == -1:
        hash_value = -2
    return hash_value

def hash_float(x):
    """Compute the hash of a float x."""

    if math.isnan(x):
        return object.__hash__(x)
    elif math.isinf(x):
        return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
    else:
        return hash_fraction(*x.as_integer_ratio())

def hash_complex(z):
    """Compute the hash of a complex number z."""

    hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
    # do a signed reduction modulo 2**sys.hash_info.width
    M = 2**(sys.hash_info.width - 1)
    hash_value = (hash_value & (M - 1)) - (hash_value & M)
    if hash_value == -1:
        hash_value = -2
    return hash_value
@end example
@anchor{library/stdtypes bltin-boolean-values}@anchor{2600}
@node ブーリアン型 - bool,イテレータ型,数値型 int float complex,組み込み型
@anchor{library/stdtypes boolean-type-bool}@anchor{2601}@anchor{library/stdtypes typebool}@anchor{25c1}
@subsection ブーリアン型 - @code{bool}


ブーリアン型は真理値を表現します。 @ref{3c3,,bool} 型はただ2つの定数インスタンス @code{True} と @code{False} を持ちます。

@geindex False
@geindex True
@geindex Boolean;`@w{`}values`@w{`}

組み込み関数 @ref{3c3,,bool()}  は、もしその値が真理値として解釈可能ならば、任意の値を真偽値に変換します (上記 @ref{1858,,真理値判定} 節を参照してください)。

論理演算には @ref{25ed,,ブーリアン演算子} @code{and}, @code{or} および @code{not} を使ってください。2つの真偽値に対してビット演算子 @code{&}, @code{|}, @code{^} を適用した場合は、それぞれ論理演算  "and", "or", "xor" に相当するブール値を返します。しかしながら、論理演算子 @code{and}, @code{or} および @code{!=} を使うほうが @code{&}, @code{|} や @code{^} を使うよりも好ましいです。


バージョン 3.12 で非推奨: The use of the bitwise inversion operator @code{~} is deprecated and will
raise an error in Python 3.16.


@ref{3c3,,bool} は @ref{19b,,int} のサブクラスです (@ref{1fdc,,数値型 int@comma{} float@comma{} complex} を参照してください)。多くの数値的なコンテキストにおいて、 @code{False} と @code{True} はそれぞれ整数 0 と 1 であるかのように振る舞います。しかし、そのような振る舞いを信頼することは推奨されません; @ref{19b,,int()} を使って明示的に整数値に変換してください。

@node イテレータ型,シーケンス型 --- list tuple range,ブーリアン型 - bool,組み込み型
@anchor{library/stdtypes iterator-types}@anchor{2602}@anchor{library/stdtypes typeiter}@anchor{25d7}
@subsection イテレータ型


@geindex イテレータプロトコル
@geindex プロトコル;iterator
@geindex sequence;反復処理
@geindex コンテナ;での反復

Python はコンテナでの反復処理の概念をサポートしています。この概念は 2 つの別々のメソッドを使って実装されています; これらのメソッドを使ってユーザ定義のクラスで反復を行えるようにできます。後に詳しく述べるシーケンスは、必ず反復処理メソッドをサポートしています。

コンテナオブジェクトが @ref{12f1,,イテラブル} のサポートを提供するためには、一つのメソッドが定義されていなければなりません:

@c XXX duplicated in reference/datamodel!

@geindex __iter__() (container のメソッド)
@anchor{library/stdtypes container __iter__}@anchor{20aa}
@deffn {メソッド} container.__iter__ ()

@ref{4c8,,iterator} オブジェクトを返します。オブジェクトは後述するイテレータプロトコルをサポートする必要があります。もしコンテナが異なる種類の反復処理をサポートするなら、それぞれの反復処理のためのイテレータを要求するメソッドをそれぞれ提供しても構いません 。(複数の形式の反復処理を提供するオブジェクトの例として、幅優先探索と深さ優先探索をサポートする木構造が挙げられます。)このメソッドは Python/C API での Python オブジェクトの型構造体の @ref{1708,,tp_iter} スロットに対応します。
@end deffn

イテレータオブジェクト自体は以下の 2 つのメソッドをサポートする必要があります。これらのメソッドは 2 つ合わせて `iterator protocol': (イテレータプロトコル) を成します:

@geindex __iter__() (iterator のメソッド)
@anchor{library/stdtypes iterator __iter__}@anchor{20ad}
@deffn {メソッド} iterator.__iter__ ()

@ref{4c8,,iterator} オブジェクト自体を返します。このメソッドはコンテナとイテレータの両方を @ref{34a,,for} および @ref{34b,,in} 文で使えるようにするために必要です。このメソッドは Python/C API において Python オブジェクトを表す型構造体の @ref{1708,,tp_iter} スロットに対応します。
@end deffn

@geindex __next__() (iterator のメソッド)
@anchor{library/stdtypes iterator __next__}@anchor{14e5}
@deffn {メソッド} iterator.__next__ ()

@ref{4c8,,iterator} の次のアイテムを返します。もしそれ以上アイテムが無ければ @ref{df5,,StopIteration} 例外を送出します。 このメソッドは Python/C APIでのPythonオブジェクトの型構造体の @ref{1709,,tp_iternext} スロットに対応します。
@end deffn

Python では、いくつかのイテレータオブジェクトを定義して、一般のシーケンス型、特殊なシーケンス型、辞書型、その他の特殊な形式に渡って反復をサポートしています。特殊型は、イテレータプロトコルの実装以外では重要ではありません。

イテレータの @ref{14e5,,__next__()} メソッドが一旦 @ref{df5,,StopIteration} を送出したなら、以降の呼び出しでも例外を送出し続けなければなりません。この特性に従わない実装は壊れているとみなされます。

@menu
* ジェネレータ型:: 

@end menu

@node ジェネレータ型,,,イテレータ型
@anchor{library/stdtypes generator-types}@anchor{2603}@anchor{library/stdtypes id3}@anchor{2604}
@subsubsection ジェネレータ型


Python における @ref{126c,,generator} (ジェネレータ) は、イテレータプロトコルを実装する便利な方法を提供します。コンテナオブジェクトの @ref{e69,,__iter__()} メソッドがジェネレータとして実装されていれば、そのメソッドは @ref{20ad,,__iter__()} および @ref{20ae,,__next__()} メソッドを提供するイテレータオブジェクト (厳密にはジェネレータオブジェクト) を自動的に返します。ジェネレータに関する詳細な情報は、 @ref{2498,,yield 式のドキュメント} にあります。

@node シーケンス型 --- list tuple range,Text and Binary Sequence Type Methods Summary,イテレータ型,組み込み型
@anchor{library/stdtypes sequence-types-list-tuple-range}@anchor{2605}@anchor{library/stdtypes typesseq}@anchor{202e}
@subsection シーケンス型 --- @code{list}, @code{tuple}, @code{range}


基本的なシーケンス型は 3 つあります: リスト、タプル、range オブジェクトです。@ref{25c4,,バイナリデータ} や @ref{1fe0,,テキスト文字列} を処理するように仕立てられたシーケンス型は、セクションを割いて解説します。

@menu
* 共通のシーケンス演算:: 
* イミュータブルなシーケンス型:: 
* ミュータブルなシーケンス型:: 
* リスト型 (list): リスト型 list<2>. 
* タプル型 (tuple): タプル型 tuple. 
* range:: 

@end menu

@node 共通のシーケンス演算,イミュータブルなシーケンス型,,シーケンス型 --- list tuple range
@anchor{library/stdtypes common-sequence-operations}@anchor{2606}@anchor{library/stdtypes typesseq-common}@anchor{2607}
@subsubsection 共通のシーケンス演算


@geindex object;sequence

以下の表にある演算は、ほとんどのミュータブル、イミュータブル両方のシーケンスでサポートされています。カスタムのシーケンス型にこれらの演算を完全に実装するのが簡単になるように、 @ref{13dc,,collections.abc.Sequence} ABC が提供されています。

以下のテーブルで、シーケンス演算を優先順位が低い順に挙げます。表内で、 `s' と `t' は同じ型のシーケンス、 `n'、 `i'、 `j' 、 `k' は整数、`x' は `s' に課された型と値の条件を満たす任意のオブジェクトです。

@code{in} および @code{not in} 演算の優先順位は比較演算と同じです。@code{+} (結合) および @code{*} (繰り返し)の優先順位は対応する数値演算と同じです。 @footnote{
パーザが演算対象の型を識別できるようにするために、このような優先順位でなければならないのです。
}

@geindex 演算;sequence;types
@geindex 組み込み関数;len
@geindex 組み込み関数;min
@geindex 組み込み関数;max
@geindex 結合;演算
@geindex 繰り返し;演算
@geindex 添字;演算
@geindex slice;演算
@geindex operator;in
@geindex operator;not in


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@tab

注釈

@item

@code{x in s}

@tab

`s' のある要素が `x' と等しければ @code{True} , そうでなければ @code{False}

@tab

(1)

@item

@code{x not in s}

@tab

`s' のある要素が `x' と等しければ @code{False}, そうでなければ @code{True}

@tab

(1)

@item

@code{s + t}

@tab

`s' と `t' の結合

@tab

(6)(7)

@item

@code{s * n} または @code{n * s}

@tab

`s' 自身を `n' 回足すのと同じ

@tab

(2)(7)

@item

@code{s[i]}

@tab

`s' の 0 から数えて `i' 番目の要素

@tab

(3)(8)

@item

@code{s[i:j]}

@tab

`s' の `i' から `j' までのスライス

@tab

(3)(4)

@item

@code{s[i:j:k]}

@tab

`s' の `i' から `j' まで、 `k' 毎のスライス

@tab

(3)(5)

@item

@code{len(s)}

@tab

`s' の長さ

@tab

@item

@code{min(s)}

@tab

`s' の最小の要素

@tab

@item

@code{max(s)}

@tab

`s' の最大の要素

@tab

@end multitable


同じ型のシーケンスは比較もサポートしています。特に、タプルとリストは対応する要素を比較することで辞書式順序で比較されます。つまり、等しいとされるためには、すべての要素が等しく、両シーケンスの型も長さも等しくなければなりません。(完全な詳細は言語リファレンスの @ref{24d0,,比較} を参照してください。)

@geindex loop;over mutable sequence
@geindex 変更可能なシーケンス;loop over

ミュータブルなシーケンスに対する前方および逆方向イテレータはインデックスを使って要素にアクセスします。インデックスは、仮に参照するシーケンスが変化したとしても前方 (または後方) に進み続けます。イテレータは @ref{174e,,IndexError} または @ref{df5,,StopIteration} に出会った場合 (またはインデックスがゼロより小さくなった場合) にのみ終了します。

注釈:


@enumerate 

@item 
@code{in} および @code{not in} 演算は、一般に単純な包含判定にのみ使われますが、(@ref{169,,str}, @ref{192,,bytes}, @ref{344,,bytearray} のような) 特殊なシーケンスでは部分シーケンス判定にも使われます:

@example
>>> "gg" in "eggs"True
@end example

@item 
@code{0} 未満の値 `n' は @code{0} として扱われます (これは `s' と同じ型の空のシーケンスを表します)。シーケンス `s' の要素はコピーされないので注意してください; コピーではなく要素に対する参照カウントが増えます。これは Python に慣れていないプログラマをよく悩ませます。例えば以下のコードを考えます:

@example
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
@end example

ここで、@code{[[]]} が空リストを含む 1 要素のリストなので、@code{[[]] * 3} の 3 要素はこの一つの空リスト (への参照) です。@code{lists} のいずれかの要素を変更すると、その一つのリストが変更されます。別々のリストのリストを作るにはこうします:

@example
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
@end example

別の説明が FAQ エントリ @ref{2608,,多次元のリストを作るにはどうしますか？} にあります。

@item 
`i' または `j' が負の数の場合、インデックスはシーケンスの末端からの相対インデックスになります: @code{len(s) + i} または @code{len(s) + j} が代わりに使われます。
ただし @code{-0} はやはり @code{0} であることに注意してください。

@item 
The slice of `s' from `i' to `j' is defined as the sequence of items with
index `k' such that @code{i <= k < j}.


@itemize *

@item 
If `i' is omitted or @code{None}, use @code{0}.

@item 
If `j' is omitted or @code{None}, use @code{len(s)}.

@item 
If `i' or `j' is less than @code{-len(s)}, use @code{0}.

@item 
If `i' or `j' is greater than @code{len(s)}, use @code{len(s)}.

@item 
If `i' is greater than or equal to `j', the slice is empty.
@end itemize

@item 
`s' の「 `i' から `j' まででステップが `k' のスライス」は、インデックス @code{x = i + n*k} （ただし n は @code{0 <= n < (j-i)/k} を満たす任意の整数）を持つ要素からなるシーケンスとして定義されます。言い換えるとインデックスは @code{i}, @code{i+k}, @code{i+2*k}, @code{i+3*k} と続き、 `j' に達したところでストップします (ただし `j' は含みません)。 `k' が正の数である場合、 `i' または `j' が @code{len(s)} より大きければ @code{len(s)} を代わりに使用します。 `k' が負の数である場合、 `i' または `j' が @code{len(s) - 1} より大きければ @code{len(s) - 1} を代わりに使用します。 `i' または `j' を省略または @code{None} を指定すると、 "端" (どちらの端かは `k' の符号に依存) の値を代わりに使用します。なお `k' はゼロにできないので注意してください。また `k' に @code{None} を指定すると、 @code{1} が指定されたものとして扱われます。

@item 
イミュータブルなシーケンスの結合は、常に新しいオブジェクトを返します。これは、結合の繰り返しでシーケンスを構築する実行時間コストがシーケンスの長さの合計の二次式になることを意味します。実行時間コストを線形にするには、代わりに以下のいずれかにしてください:


@itemize *

@item 
@ref{169,,str} オブジェクトを結合するには、リストを構築して最後に @ref{2609,,str.join()} を使うか、 @ref{112a,,io.StringIO} インスタンスに書き込んで完成してから値を取得してください

@item 
@ref{192,,bytes} オブジェクトを結合するなら、同様に @ref{260a,,bytes.join()} や @ref{10a4,,io.BytesIO} を使うか、 @ref{344,,bytearray} オブジェクトでインプレースに結合できます。 @ref{344,,bytearray} オブジェクトはミュータブルで、効率のいい割り当て超過機構を備えています

@item 
@ref{614,,tuple} オブジェクトを結合するなら、代わりに @ref{24d,,list} を拡張してください

@item 
その他の型については、関連するクラスのドキュメントを調べてください
@end itemize

@item 
シーケンス型には、 (@ref{b3d,,range} のように) 特殊なパターンに従う項目のシーケンスのみをサポートするものがあり、それらはシーケンスの結合や繰り返しをサポートしません。

@item 
An @ref{174e,,IndexError} is raised if `i' is outside the sequence range.
@end enumerate

@subsubheading シーケンスのメソッド


シーケンス型は以下のようなメソッドをサポートしています:


@geindex count() (sequence のメソッド)
@anchor{library/stdtypes list count}@anchor{15df}@anchor{library/stdtypes sequence count}@anchor{23d8}
@deffn {メソッド} sequence.count (value, /)

`sequence' の中に `value' が出現する回数を返します。
@end deffn


@geindex index() (sequence のメソッド)
@anchor{library/stdtypes list index}@anchor{15de}@anchor{library/stdtypes sequence index}@anchor{1979}
@deffn {メソッド} sequence.index (value[, start[, stop])

`sequence' で最初に `value' が出現する場所のインデックスを返します。

`sequence' に `value' が見つからなければ @ref{2ec,,ValueError} を送出します。

The `start' or `stop' arguments allow for efficient searching
of subsections of the sequence, beginning at `start' and ending at `stop'.
This is roughly equivalent to @code{start + sequence[start:stop].index(value)},
only without copying any data.

@cartouche
@quotation 注意 
Not all sequence types support passing the `start' and `stop' arguments.
@end quotation
@end cartouche
@end deffn

@node イミュータブルなシーケンス型,ミュータブルなシーケンス型,共通のシーケンス演算,シーケンス型 --- list tuple range
@anchor{library/stdtypes immutable-sequence-types}@anchor{260b}@anchor{library/stdtypes typesseq-immutable}@anchor{260c}
@subsubsection イミュータブルなシーケンス型


@geindex immutable;sequence;types
@geindex object;tuple
@geindex 組み込み関数;hash

イミュータブルなシーケンス型が一般に実装している演算のうち、ミュータブルなシーケンス型がサポートしていないのは、組み込みの @ref{801,,hash()} だけです。

このサポートにより、@ref{614,,tuple} インスタンスのようなイミュータブルなシーケンスは、 @ref{183,,dict} のキーとして使え、 @ref{184,,set} や @ref{7f2,,frozenset} インスタンスに保存できます。

ハッシュ不可能な値を含むイミュータブルなシーケンスをハッシュ化しようとすると、 @ref{198,,TypeError} となります。

@node ミュータブルなシーケンス型,リスト型 list<2>,イミュータブルなシーケンス型,シーケンス型 --- list tuple range
@anchor{library/stdtypes mutable-sequence-types}@anchor{260d}@anchor{library/stdtypes typesseq-mutable}@anchor{25c2}
@subsubsection ミュータブルなシーケンス型


@geindex mutable;sequence;types
@geindex object;list
@geindex object;bytearray

以下のテーブルにある演算は、ほとんどのミュータブルなシーケンスでサポートされています。カスタムのシーケンス型にこれらの演算を完全に実装するのが簡単になるように、 @ref{4bf,,collections.abc.MutableSequence} ABC が提供されています。

このテーブルで、 `s' はミュータブルなシーケンス型のインスタンス、 `t' は任意のイテラブルオブジェクト、 `x' は `s' に課された型と値の条件を満たす任意のオブジェクト (例えば、 @ref{344,,bytearray} は値の制限 @code{0 <= x <= 255} に合う整数のみを受け付けます) です。

@geindex 演算;sequence;types
@geindex 演算;list;type
@geindex 添字;代入
@geindex slice;代入
@geindex statement;del


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@tab

注釈

@item

@code{s[i] = x}

@tab

`s' の要素 `i' を `x' と入れ替えます

@tab

@item

@code{del s[i]}

@tab

`s' の要素 `i' を削除します

@tab

@item

@code{s[i:j] = t}

@tab

`s' の `i' から `j' 番目までのスライスをイテラブル `t' の内容に入れ替えます

@tab

@item

@code{del s[i:j]}

@tab

リストから @code{s[i:j]} の要素を削除します(@code{s[i:j] = []} と同様です)

@tab

@item

@code{s[i:j:k] = t}

@tab

@code{s[i:j:k]} の要素を `t' の要素と入れ替えます

@tab

(1)

@item

@code{del s[i:j:k]}

@tab

リストから @code{s[i:j:k]} の要素を削除します

@tab

@item

@code{s += t}

@tab

`s' を `t' の内容で拡張します (ほとんど @code{s[len(s):len(s)] = t} と同じ)

@tab

@item

@code{s *= n}

@tab

`s' をその内容を `n' 回繰り返したもので更新

@tab

(2)

@end multitable


注釈:


@enumerate 

@item 
`k' が @code{1} と等しくない場合、 `t' はそれが入れ替えるスライスと同じ長さでなければなりません。

@item 
値 `n' は整数であるか、@ref{19e,,__index__()} を実装したオブジェクトです。 `n' の値がゼロまたは負数の場合、シーケンスをクリアします。@ref{2607,,共通のシーケンス演算} で @code{s * n} について説明したとおり、シーケンスの要素はコピーされないので注意してください; コピーではなく要素に対する参照カウントが増えます。
@end enumerate

@subsubheading ミュータブルなシーケンスのメソッド


ミュータブルなシーケンス型は以下のようなメソッドをサポートしています:


@geindex append() (sequence のメソッド)
@anchor{library/stdtypes bytearray append}@anchor{15bf}@anchor{library/stdtypes sequence append}@anchor{23d6}
@deffn {メソッド} sequence.append (value, /)

Append `value' to the end of the sequence
This is equivalent to writing @code{seq[len(seq):len(seq)] = [value]}.
@end deffn


@geindex clear() (sequence のメソッド)
@anchor{library/stdtypes bytearray clear}@anchor{260e}@anchor{library/stdtypes sequence clear}@anchor{23d7}
@deffn {メソッド} sequence.clear ()


Added in version 3.3.


Remove all items from `sequence'.
This is equivalent to writing @code{del sequence[:]}.
@end deffn


@geindex copy() (sequence のメソッド)
@anchor{library/stdtypes bytearray copy}@anchor{260f}@anchor{library/stdtypes sequence copy}@anchor{2610}
@deffn {メソッド} sequence.copy ()


Added in version 3.3.


Create a shallow copy of `sequence'.
This is equivalent to writing @code{sequence[:]}.

@cartouche
@quotation ヒント 
The @code{copy()} method is not part of the
@ref{4bf,,MutableSequence} @ref{111b,,ABC},
but most concrete mutable sequence types provide it.
@end quotation
@end cartouche
@end deffn


@geindex extend() (sequence のメソッド)
@anchor{library/stdtypes bytearray extend}@anchor{1791}@anchor{library/stdtypes sequence extend}@anchor{23d9}
@deffn {メソッド} sequence.extend (iterable, /)

Extend `sequence' with the contents of `iterable'.
For the most part, this is the same as writing
@code{seq[len(seq):len(seq)] = iterable}.
@end deffn


@geindex insert() (sequence のメソッド)
@anchor{library/stdtypes bytearray insert}@anchor{2611}@anchor{library/stdtypes sequence insert}@anchor{23da}
@deffn {メソッド} sequence.insert (index, value, /)

Insert `value' into `sequence' at the given `index'.
This is equivalent to writing @code{sequence[index:index] = [value]}.
@end deffn


@geindex pop() (sequence のメソッド)
@anchor{library/stdtypes bytearray pop}@anchor{15c0}@anchor{library/stdtypes sequence pop}@anchor{23db}
@deffn {メソッド} sequence.pop (index=-1, /)

Retrieve the item at `index' and also removes it from `sequence'.
By default, the last item in `sequence' is removed and returned.
@end deffn


@geindex remove() (sequence のメソッド)
@anchor{library/stdtypes bytearray remove}@anchor{2612}@anchor{library/stdtypes sequence remove}@anchor{197a}
@deffn {メソッド} sequence.remove (value, /)

Remove the first item from `sequence' where @code{sequence[i] == value}.

`sequence' に `value' が見つからなければ @ref{2ec,,ValueError} を送出します。
@end deffn


@geindex reverse() (sequence のメソッド)
@anchor{library/stdtypes bytearray reverse}@anchor{15c1}@anchor{library/stdtypes sequence reverse}@anchor{23dc}
@deffn {メソッド} sequence.reverse ()

Reverse the items of `sequence' in place.
This method maintains economy of space when reversing a large sequence.
To remind users that it operates by side-effect, it returns @code{None}.
@end deffn

@node リスト型 list<2>,タプル型 tuple,ミュータブルなシーケンス型,シーケンス型 --- list tuple range
@anchor{library/stdtypes lists}@anchor{2613}@anchor{library/stdtypes typesseq-list}@anchor{2022}
@subsubsection リスト型 (list)


@geindex object;list

リストはミュータブルなシーケンスで、一般的に同種の項目の集まりを格納するために使われます (厳密な類似の度合いはアプリケーションによって異なる場合があります)。

@geindex list (組み込みクラス)
@anchor{library/stdtypes list}@anchor{24d}
@deffn {クラス} list (iterable=(), /)

リストの構成にはいくつかの方法があります:


@itemize *

@item 
角括弧の対を使い、空のリストを表す: @code{[]}

@item 
角括弧を使い、項目をカンマで区切る: @code{[a]}、@code{[a, b, c]}

@item 
リスト内包表記を使う: @code{[x for x in iterable]}

@item 
型コンストラクタを使う: @code{list()} または @code{list(iterable)}
@end itemize

コンストラクタは、 `iterable' の項目と同じ項目で同じ順のリストを構築します。 `iterable' は、シーケンス、イテレートをサポートするコンテナ、またはイテレータオブジェクトです。 `iterable' が既にリストなら、 @code{iterable[:]} と同様にコピーが作られて返されます。例えば、 @code{list('abc')} は @code{['a', 'b', 'c']} を、 @code{list( (1, 2, 3) )} は @code{[1, 2, 3]} を返します。引数が与えられなければ、このコンストラクタは新しい空のリスト @code{[]} を作成します。

リストを作る方法は、他にも組み込み関数 @ref{dc7,,sorted()} などいろいろあります。

リストは @ref{2607,,共通の} および @ref{25c2,,ミュータブルの} シーケンス演算をすべて実装します。リストは、更に以下のメソッドも提供します:

@geindex sort() (list のメソッド)
@anchor{library/stdtypes list sort}@anchor{dc8}
@deffn {メソッド} sort (*, key=None, reverse=False)

このメソッドは、項目間の @code{<} 比較のみを用いてリストをインプレースにソートします。例外は抑制されません。比較演算がどこかで失敗したら、ソート演算自体が失敗します (そしてリストは部分的に変更された状態で残されるでしょう)。

@ref{dc8,,sort()} は、キーワードでしか渡せない 2 つの引数 (@ref{5a5,,キーワード専用引数}) を受け付けます:

`key' は一引数をとる関数を指定し、リストのそれぞれの要素から比較キーを取り出すのに使います (例えば、 @code{key=str.lower})。それぞれの項目に対応するキーは一度計算され、ソート処理全体に使われます。デフォルトの値 @code{None} は、別のキー値を計算せず、リストの値が直接ソートされることを意味します。

2.x 形式の `cmp' 関数を `key' 関数に変換するために、@ref{13f2,,functools.cmp_to_key()} ユーティリティが利用できます。

`reverse' は真偽値です。 @code{True} がセットされた場合、リストの要素は個々の比較が反転したものとして並び替えられます。

このメソッドは、大きなシーケンスをソートするときの容量の節約のため、シーケンスをインプレースに変化させます。副作用としてこの演算が行われることをユーザに気づかせるために、これはソートしたシーケンスを返しません (新しいリストインスタンスを明示的に要求するには @ref{dc7,,sorted()} を使ってください)。

@ref{dc8,,sort()} メソッドは安定していることが保証されています。ソートは、等しい要素の相対順序が変更されないことが保証されていれば、安定しています。これは複数パスのソートを行なう (例えば部署でソートして、それから給与の等級でソートする) のに役立ちます。

ソートの例と簡単なチュートリアルは @ref{13f3,,ソートのテクニック} を参照して下さい。

リストがソートされている間、または変更しようとする試みの影響中、あるいは検査中でさえ、リストは未定義です。Python の C 実装では、それらが続いている間、リストは空として出力され、リストがソート中に変更されていることを検知できたら @ref{2ec,,ValueError} を送出します。
@end deffn
@end deffn
@anchor{library/stdtypes thread-safety-list}@anchor{2614}
@subsubheading Thread safety for list objects


Reading a single element from a @ref{24d,,list} is
@ref{2615,,atomic}:

@example
lst[i]   # list.__getitem__
@end example

The following methods traverse the list and use @ref{2615,,atomic}
reads of each item to perform their function. That means that they may
return results affected by concurrent modifications:

@example
item in lst
lst.index(item)
lst.count(item)
@end example

All of the above operations avoid acquiring @ref{2616,,per-object locks}. They do not block concurrent modifications. Other
operations that hold a lock will not block these from observing intermediate
states.

All other operations from here on block using the @ref{2616,,per-object lock}.

Writing a single item via @code{lst[i] = x} is safe to call from multiple
threads and will not corrupt the list.

The following operations return new objects and appear
@ref{2615,,atomic} to other threads:

@example
lst1 + lst2    # concatenates two lists into a new list
x * lst        # repeats lst x times into a new list
lst.copy()     # returns a shallow copy of the list
@end example

The following methods that only operate on a single element with no shifting
required are @ref{2615,,atomic}:

@example
lst.append(x)  # append to the end of the list, no shifting required
lst.pop()      # pop element from the end of the list, no shifting required
@end example

The @ref{603,,clear()} method is also @ref{2615,,atomic}.
Other threads cannot observe elements being removed.

The @ref{dc8,,sort()} method is not @ref{2615,,atomic}.
Other threads cannot observe intermediate states during sorting, but the
list appears empty for the duration of the sort.

The following operations may allow @ref{2617,,lock-free} operations to observe
intermediate states since they modify multiple elements in place:

@example
lst.insert(idx, item)  # shifts elements
lst.pop(idx)           # idx not at the end of the list, shifts elements
lst *= x               # copies elements in place
@end example

The @ref{1a5b,,remove()} method may allow concurrent modifications since
element comparison may execute arbitrary Python code (via
@ref{cf2,,__eq__()}).

@ref{602,,extend()} is safe to call from multiple threads.  However, its
guarantees depend on the iterable passed to it. If it is a @ref{24d,,list}, a
@ref{614,,tuple}, a @ref{184,,set}, a @ref{7f2,,frozenset}, a @ref{183,,dict} or a
@ref{2618,,dictionary view object} (but not their subclasses), the
@code{extend} operation is safe from concurrent modifications to the iterable.
Otherwise, an iterator is created which can be concurrently modified by
another thread.  The same applies to inplace concatenation of a list with
other iterables when using @code{lst += iterable}.

Similarly, assigning to a list slice with @code{lst[i:j] = iterable} is safe
to call from multiple threads, but @code{iterable} is only locked when it is
also a @ref{24d,,list} (but not its subclasses).

Operations that involve multiple accesses, as well as iteration, are never
atomic. For example:

@example
# NOT atomic: read-modify-write
lst[i] = lst[i] + 1

# NOT atomic: check-then-act
if lst:
      item = lst.pop()

# NOT thread-safe: iteration while modifying
for item in lst:
      process(item)  # another thread may modify lst
@end example

Consider external synchronization when sharing @ref{24d,,list} instances
across threads.  See @ref{2619,,Python support for free threading} for more information.

@node タプル型 tuple,range,リスト型 list<2>,シーケンス型 --- list tuple range
@anchor{library/stdtypes tuples}@anchor{261a}@anchor{library/stdtypes typesseq-tuple}@anchor{254a}
@subsubsection タプル型 (tuple)


@geindex object;tuple

タプルはイミュータブルなシーケンスで、一般的に異種のデータの集まり (組み込みの @ref{169a,,enumerate()} で作られた 2-タプルなど) を格納するために使われます。タプルはまた、同種のデータのイミュータブルなシーケンスが必要な場合 (@ref{184,,set} インスタンスや @ref{183,,dict} インスタンスに保存できるようにするためなど) にも使われます。

@geindex tuple (組み込みクラス)
@anchor{library/stdtypes tuple}@anchor{614}
@deffn {クラス} tuple (iterable=(), /)

タプルの構成にはいくつかの方法があります:


@itemize *

@item 
丸括弧の対を使い、空のタプルを表す: @code{()}

@item 
カンマを使い、単要素のタプルを表す: @code{a,} または @code{(a,)}

@item 
項目をカンマで区切る: @code{a, b, c} または @code{(a, b, c)}

@item 
組み込みの @ref{614,,tuple()} を使う: @code{tuple()} または @code{tuple(iterable)}
@end itemize

コンストラクタは、 `iterable' の項目と同じ項目で同じ順のタプルを構築します。 `iterable' は、シーケンス、イテレートをサポートするコンテナ、またはイテレータオブジェクトです。 `iterable' が既にタプルなら、そのまま返されます。例えば、 @code{tuple('abc')} は @code{('a', 'b', 'c')} を、 @code{tuple( [1, 2, 3] )} は @code{(1, 2, 3)} を返します。引数が与えられなければ、このコンストラクタは新しい空のタプル @code{()} を作成します。

なお、タプルを作るのはカンマであり、丸括弧ではありません。丸括弧は省略可能ですが、空のタプルの場合や構文上の曖昧さを避けるのに必要な時は例外です。例えば、 @code{f(a, b, c)} は三引数の関数呼び出しですが、@code{f((a, b, c))} は 3-タプルを唯一の引数とする関数の呼び出しです。

タプルは @ref{2607,,共通の} シーケンス演算をすべて実装します。
@end deffn

異種のデータの集まりで、インデックスによってアクセスするよりも名前によってアクセスしたほうが明確になるものには、単純なタプルオブジェクトよりも @ref{4e0,,collections.namedtuple()} が向いているかもしれません。

@node range,,タプル型 tuple,シーケンス型 --- list tuple range
@anchor{library/stdtypes ranges}@anchor{261b}@anchor{library/stdtypes typesseq-range}@anchor{25dd}
@subsubsection range


@geindex object;range

@ref{b3d,,range} 型は、数のイミュータブルなシーケンスを表し、一般に @ref{34a,,for} ループにおいて特定の回数のループに使われます。

@geindex range (組み込みクラス)
@anchor{library/stdtypes range}@anchor{b3d}
@deffn {クラス} range (stop, /)

@deffnx {クラス} range (start, stop, step=1, /)

range コンストラクタの引数は整数 (組み込みの @ref{19b,,int} または @ref{19e,,__index__()} 特殊メソッドを実装するオブジェクト) でなければなりません。`step' 引数が省略された場合のデフォルト値は @code{1} です。`start' 引数が省略された場合のデフォルト値は  @code{0} です。 `step' が 0 の場合、@ref{2ec,,ValueError} が送出されます。

`step' が正の場合、range @code{r} の内容は式 @code{r[i] = start + step*i} で決定されます。ここで、 @code{i >= 0} かつ @code{r[i] < stop} です。

`step' が負の場合も、range @code{r} の内容は式 @code{r[i] = start + step*i} で決定されます。ただし、制約条件は @code{i >= 0} かつ @code{r[i] > stop} です。

@code{r[0]} が値の制約を満たさない場合、range オブジェクトは空になります。range は負のインデックスをサポートしますが、これらは正のインデックスにより決定されるシーケンスの末尾からのインデックス指定として解釈されます。

range は @ref{13dd,,sys.maxsize} より大きい絶対値を含むことができますが、いくつかの機能 (@ref{840,,len()} など) は @ref{a81,,OverflowError} を送出することがあります。

range の例:

@example
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
@end example

range は @ref{2607,,共通の} シーケンス演算を、結合と繰り返し以外すべて実装します (range オブジェクトは厳格なパターンに従うシーケンスのみを表せ、繰り返しと結合はたいていそのパターンを破るという事実によります)。

@geindex start (range の属性)
@anchor{library/stdtypes range start}@anchor{261c}
@deffn {の属性} start

引数 `start' の値 (この引数が与えられていない場合は @code{0})
@end deffn

@geindex stop (range の属性)
@anchor{library/stdtypes range stop}@anchor{261d}
@deffn {の属性} stop

引数 `stop' の値
@end deffn

@geindex step (range の属性)
@anchor{library/stdtypes range step}@anchor{261e}
@deffn {の属性} step

引数 `step' の値 (この引数が与えられていない場合は @code{1})
@end deffn
@end deffn

@ref{b3d,,range} 型が通常の @ref{24d,,list} や @ref{614,,tuple} にまさる点は、@ref{b3d,,range} オブジェクトがサイズや表す範囲にかかわらず常に一定の (小さな) 量のメモリを使うことです (@code{start}、@code{stop}、@code{step} の値のみを保存し、後は必要に応じて個々の項目や部分 range を計算するためです)。

range オブジェクトは @ref{13dc,,collections.abc.Sequence} ABC を実装し、包含判定、要素インデックス検索、スライシングのような機能を提供し、負のインデックスをサポートします (@ref{202e,,シーケンス型 --- list@comma{} tuple@comma{} range} を参照):

@example
>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18
@end example

@code{==} および @code{!=} による range オブジェクトの等価性の判定は、これらをシーケンスとして比較します。つまり、二つの range オブジェクトは同じ値のシーケンスを表すなら等しいとみなされます。(なお、二つの等しいとされる range オブジェクトが異なる  @ref{261c,,start}, @ref{261d,,stop} および @ref{261e,,step} 属性を持つことがあります。例えば @code{range(0) == range(2, 1, 3)} や @code{range(0, 3, 2) == range(0, 4, 2)}。)


バージョン 3.2 で変更: シーケンス ABC を実装。スライスと負のインデックスのサポート。@ref{19b,,int} オブジェクトの帰属判定を、すべてのアイテムをイテレートする代わりに、定数時間で行います。



バージョン 3.3 で変更: (オブジェクトの同一性に基づいて比較する代わりに) range オブジェクトをそれらが定義する値のシーケンスに基づいて比較するように '==' と '!=' を定義しました。

属性 @ref{261c,,start}, @ref{261d,,stop} および @ref{261e,,step} が追加。



@subsubheading 参考



@itemize *

@item 
linspace レシピ@footnote{https://code.activestate.com/recipes/579000-equally-spaced-numbers-linspace/} は浮動小数点数向けの遅延評価版 range を実装する方法を紹介しています。
@end itemize


@geindex string;テキストシーケンス型
@geindex str (組み込みクラス);(string も参照のこと)
@geindex object;string

@node Text and Binary Sequence Type Methods Summary,テキストシーケンス型 --- str,シーケンス型 --- list tuple range,組み込み型
@anchor{library/stdtypes text-and-binary-sequence-type-methods-summary}@anchor{261f}@anchor{library/stdtypes text-methods-summary}@anchor{2620}
@subsection Text and Binary Sequence Type Methods Summary


The following table summarizes the text and binary sequence types methods by
category.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xx} {xx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xx} {xx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

カテゴリ

@tab

@ref{169,,str} メソッド

@tab

@tab

@tab

@tab

@ref{192,,bytes} または @ref{344,,bytearray} メソッド

@tab

@tab

@tab

@item

Formatting

@tab

@ref{833,,str.format()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@ref{fd7,,str.format_map()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@ref{19a,,f-strings}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@ref{8db,,printf 形式の文字列書式化}

@tab

@tab

@tab

@tab

@ref{f81,,printf 形式での bytes の書式化}

@tab

@tab

@tab

@item

Searching and Replacing

@tab

@ref{10a8,,str.find()}

@tab

@ref{10a9,,str.rfind()}

@tab

@tab

@tab

@ref{1bd4,,bytes.find()}

@tab

@ref{1bd5,,bytes.rfind()}

@tab

@tab

@item

@ref{19bc,,str.index()}

@tab

@ref{146f,,str.rindex()}

@tab

@tab

@tab

@ref{2621,,bytes.index()}

@tab

@ref{2622,,bytes.rindex()}

@tab

@tab

@item

@ref{10cb,,str.startswith()}

@tab

@tab

@tab

@tab

@ref{2623,,bytes.startswith()}

@tab

@tab

@tab

@item

@ref{10cc,,str.endswith()}

@tab

@tab

@tab

@tab

@ref{2624,,bytes.endswith()}

@tab

@tab

@tab

@item

@ref{1981,,str.count()}

@tab

@tab

@tab

@tab

@ref{1982,,bytes.count()}

@tab

@tab

@tab

@item

@ref{4b8,,str.replace()}

@tab

@tab

@tab

@tab

@ref{2625,,bytes.replace()}

@tab

@tab

@tab

@item

Splitting and Joining

@tab

@ref{10aa,,str.split()}

@tab

@tab

@ref{146d,,str.rsplit()}

@tab

@tab

@ref{2626,,bytes.split()}

@tab

@tab

@ref{2627,,bytes.rsplit()}

@tab

@item

@ref{146e,,str.splitlines()}

@tab

@tab

@tab

@tab

@ref{2628,,bytes.splitlines()}

@tab

@tab

@tab

@item

@ref{10ab,,str.partition()}

@tab

@tab

@tab

@tab

@ref{2629,,bytes.partition()}

@tab

@tab

@tab

@item

@ref{1470,,str.rpartition()}

@tab

@tab

@tab

@tab

@ref{262a,,bytes.rpartition()}

@tab

@tab

@tab

@item

@ref{2609,,str.join()}

@tab

@tab

@tab

@tab

@ref{260a,,bytes.join()}

@tab

@tab

@tab

@item

String Classification

@tab

@ref{262b,,str.isalpha()}

@tab

@tab

@tab

@tab

@ref{262c,,bytes.isalpha()}

@tab

@tab

@tab

@item

@ref{262d,,str.isdecimal()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@ref{262e,,str.isdigit()}

@tab

@tab

@tab

@tab

@ref{262f,,bytes.isdigit()}

@tab

@tab

@tab

@item

@ref{2630,,str.isnumeric()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@ref{2631,,str.isalnum()}

@tab

@tab

@tab

@tab

@ref{2632,,bytes.isalnum()}

@tab

@tab

@tab

@item

@ref{1d46,,str.isidentifier()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@ref{2633,,str.islower()}

@tab

@tab

@tab

@tab

@ref{2634,,bytes.islower()}

@tab

@tab

@tab

@item

@ref{2635,,str.isupper()}

@tab

@tab

@tab

@tab

@ref{2636,,bytes.isupper()}

@tab

@tab

@tab

@item

@ref{2637,,str.istitle()}

@tab

@tab

@tab

@tab

@ref{2638,,bytes.istitle()}

@tab

@tab

@tab

@item

@ref{2639,,str.isspace()}

@tab

@tab

@tab

@tab

@ref{263a,,bytes.isspace()}

@tab

@tab

@tab

@item

@ref{fd8,,str.isprintable()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

Case Manipulation

@tab

@ref{1b76,,str.lower()}

@tab

@tab

@tab

@tab

@ref{263b,,bytes.lower()}

@tab

@tab

@tab

@item

@ref{263c,,str.upper()}

@tab

@tab

@tab

@tab

@ref{263d,,bytes.upper()}

@tab

@tab

@tab

@item

@ref{fd6,,str.casefold()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@ref{263e,,str.capitalize()}

@tab

@tab

@tab

@tab

@ref{263f,,bytes.capitalize()}

@tab

@tab

@tab

@item

@ref{2640,,str.title()}

@tab

@tab

@tab

@tab

@ref{2641,,bytes.title()}

@tab

@tab

@tab

@item

@ref{2642,,str.swapcase()}

@tab

@tab

@tab

@tab

@ref{2643,,bytes.swapcase()}

@tab

@tab

@tab

@item

Padding and Stripping

@tab

@ref{2062,,str.ljust()}

@tab

@tab

@ref{2061,,str.rjust()}

@tab

@tab

@ref{2644,,bytes.ljust()}

@tab

@tab

@ref{2645,,bytes.rjust()}

@tab

@item

@ref{2063,,str.center()}

@tab

@tab

@tab

@tab

@ref{2646,,bytes.center()}

@tab

@tab

@tab

@item

@ref{2647,,str.expandtabs()}

@tab

@tab

@tab

@tab

@ref{2648,,bytes.expandtabs()}

@tab

@tab

@tab

@item

@ref{16c8,,str.strip()}

@tab

@tab

@tab

@tab

@ref{2649,,bytes.strip()}

@tab

@tab

@tab

@item

@ref{16c9,,str.lstrip()}

@tab

@tab

@tab

@ref{16ca,,str.rstrip()}

@tab

@ref{264a,,bytes.lstrip()}

@tab

@tab

@tab

@ref{264b,,bytes.rstrip()}

@item

Translation and Encoding

@tab

@ref{264c,,str.translate()}

@tab

@tab

@tab

@tab

@ref{264d,,bytes.translate()}

@tab

@tab

@tab

@item

@ref{fd9,,str.maketrans()}

@tab

@tab

@tab

@tab

@ref{148c,,bytes.maketrans()}

@tab

@tab

@tab

@item

@ref{ad2,,str.encode()}

@tab

@tab

@tab

@tab

@tab

@tab

@tab

@item

@tab

@tab

@tab

@tab

@ref{ad3,,bytes.decode()}

@tab

@tab

@tab

@end multitable


@node テキストシーケンス型 --- str,バイナリシーケンス型 --- bytes bytearray memoryview,Text and Binary Sequence Type Methods Summary,組み込み型
@anchor{library/stdtypes text-sequence-type-str}@anchor{264e}@anchor{library/stdtypes textseq}@anchor{1fe0}
@subsection テキストシーケンス型 --- @code{str}


Python のテキストデータは @ref{169,,str} オブジェクト、すなわち `文字列' として扱われます。文字列は Unicode コードポイントのイミュータブルな @ref{202e,,シーケンス} です。文字列リテラルには様々な記述方法があります:


@itemize *

@item 
シングルクォート: @code{'"ダブル" クォートを埋め込むことができます'}

@item 
ダブルクォート: @code{"'シングル' クォートを埋め込むことができます"}。

@item 
三重引用符: @code{'@w{'}'三つのシングルクォート'@w{'}'}, @code{"""三つのダブルクォート"""}
@end itemize

三重引用符文字列は、複数行に分けることができます。関連付けられる空白はすべて文字列リテラルに含まれます。

単式の一部であり間に空白のみを含む文字列リテラルは、一つの文字列リテラルに暗黙に変換されます。つまり、@code{("spam " "eggs") == "spam eggs"} です。

サポートされている @ref{687,,エスケープシーケンス} や、ほとんどのエスケープシーケンスの処理を無効化する @code{r} ("raw") 接頭辞など、文字列リテラルのさまざまな形式についての詳細は @ref{229f,,文字列およびバイト列リテラル} を参照してください。

文字列は他のオブジェクトに @ref{169,,str} コンストラクタを使うことでも生成できます。

"character" 型が特別に用意されているわけではないので、文字列のインデックス指定を行うと長さ 1 の文字列を作成します。つまり、空でない文字列 `s' に対し、@code{s[0] == s[0:1]} です。

@geindex object;io.StringIO

ミュータブルな文字列型もありませんが、ミュータブルな断片から効率よく文字列を構成するのに @ref{2609,,str.join()} や @ref{112a,,io.StringIO} が使えます。


バージョン 3.3 で変更: Python 2 シリーズとの後方互換性のため、文字列リテラルの @code{u} 接頭辞が改めて許可されました。それは文字列リテラルとしての意味には影響がなく、 @code{r} 接頭辞と結合することはできません。


@geindex string;str (組み込みクラス)

@geindex str (組み込みクラス)
@anchor{library/stdtypes str}@anchor{169}
@deffn {クラス} str (*, encoding='utf-8', errors='strict')

@deffnx {クラス} str (object)

@deffnx {クラス} str (object, encoding, errors='strict')

@deffnx {クラス} str (object, *, errors)

`object' の @ref{1fe0,,文字列} 版を返します。 `object' が与えられなかった場合、空文字列が返されます。それ以外の場合 @code{str()} の動作は、 `encoding' や `errors' が与えられたかどうかによって次のように変わります。

`encoding' も `errors' も与えられない場合、 @code{str(object)} は "形式ばらず"、 表示用にきれいに整えられた `object' の文字列表現である @ref{830,,type(object).__str__(object)} を返します。文字列オブジェクトに対しては、文字列そのものです。 `object' が @ref{830,,__str__()} メソッドを持たない場合、 @ref{169,,str()} は代わりに @ref{1c1,,repr(object)} の結果を返します。

@geindex buffer protocol;str (組み込みクラス)
@geindex bytes;str (組み込みクラス)

`encoding' か `errors' の少なくとも一方が与えられた場合、 `object' は @ref{193,,bytes-like object} (たとえば @ref{192,,bytes} や @ref{344,,bytearray}) でなくてはなりません。`object' が @ref{192,,bytes} (もしくは @ref{344,,bytearray}) オブジェクトである場合は、 @code{str(bytes, encoding, errors)} は @ref{ad3,,bytes.decode(encoding@comma{} errors)} と等価です。そうでない場合は、 @ref{ad3,,bytes.decode()} が呼ばれる前に buffer オブジェクトの下層にある bytes オブジェクトが取得されます。 buffer オブジェクトについて詳しい情報は、 @ref{25c4,,バイナリシーケンス型 --- bytes@comma{} bytearray@comma{} memoryview} や @ref{260,,バッファプロトコル (buffer Protocol)} を参照してください。

`encoding' 引数や `errors' 引数無しに @ref{192,,bytes} オブジェクトを @ref{169,,str()} に渡すと、略式の文字列表現を返す 1 つ目の場合に該当します。(Python のコマンドラインオプション @ref{7f9,,-b} も参照してください) 例えば:

@example
>>> str(b'Zoot!')
"b'Zoot!'"
@end example

@code{str} クラスとそのメソッドについて詳しくは、 @ref{1fe0,,テキストシーケンス型 — str} や @ref{1fe1,,文字列メソッド} の節を参照してください。フォーマットされた文字列を出力するには、 @ref{19a,,f-strings} と @ref{264f,,カスタムの文字列書式化} の節を参照してください。加えて、 @ref{2650,,テキスト処理サービス} の節も参照してください。
@end deffn

@geindex string;メソッド

@menu
* 文字列メソッド: 文字列メソッド<2>. 
* Formatted String Literals (f-strings): Formatted String Literals f-strings. 
* Template String Literals (t-strings): Template String Literals t-strings. 
* printf 形式の文字列書式化:: 

@end menu

@node 文字列メソッド<2>,Formatted String Literals f-strings,,テキストシーケンス型 --- str
@anchor{library/stdtypes id5}@anchor{2651}@anchor{library/stdtypes string-methods}@anchor{1fe1}
@subsubsection 文字列メソッド


@geindex module;re

文字列は @ref{2607,,共通の} シーケンス演算全てに加え、以下に述べるメソッドを実装します。

文字列は、二形式の文字列書式化をサポートします。一方は柔軟さが高くカスタマイズできます (@ref{833,,str.format()}、 @ref{15b3,,書式指定文字列の文法} 、および @ref{264f,,カスタムの文字列書式化} を参照してください)。他方は C 言語の @code{printf} 形式の書式化に基づいてより狭い範囲と型を扱うもので、正しく扱うのは少し難しいですが、扱える場合ではたいていこちらのほうが高速です (@ref{8db,,printf 形式の文字列書式化})。

標準ライブラリの @ref{2652,,テキスト処理サービス} 節は、その他テキストに関する様々なユーティリティ (@ref{be,,re} モジュールによる正規表現サポートなど) を提供するいくつかのモジュールをカバーしています。

@geindex capitalize() (str のメソッド)
@anchor{library/stdtypes str capitalize}@anchor{263e}
@deffn {メソッド} str.capitalize ()

最初の文字を大文字にし、残りを小文字にした文字列のコピーを返します。


バージョン 3.8 で変更: 最初の文字が大文字ではなくタイトルケースに置き換えられるようになりました。つまり二重音字のような文字はすべての文字が大文字にされるのではなく、最初の文字だけ大文字にされるようになります。

@end deffn

@geindex casefold() (str のメソッド)
@anchor{library/stdtypes str casefold}@anchor{fd6}
@deffn {メソッド} str.casefold ()

文字列の casefold されたコピーを返します。casefold された文字列は、大文字小文字に関係ないマッチに使えます。

Casefolding is similar to lowercasing but more aggressive because it is
intended to remove all case distinctions in a string. For example, the German
lowercase letter @code{'ß'} is equivalent to @code{"ss"}. Since it is already
lowercase, @ref{1b76,,lower()} would do nothing to @code{'ß'}; @ref{fd6,,casefold()}
converts it to @code{"ss"}.
For example:

@example
>>> 'straße'.lower()
'straße'
>>> 'straße'.casefold()
'strasse'
@end example

The casefolding algorithm is
described in section 3.13 'Default Case Folding' of the Unicode Standard@footnote{https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G33992}.


Added in version 3.3.

@end deffn

@geindex center() (str のメソッド)
@anchor{library/stdtypes str center}@anchor{2063}
@deffn {メソッド} str.center (width, fillchar=' ', /)

Return centered in a string of length `width'. Padding is done using the
specified `fillchar' (default is an ASCII space). The original string is
returned if `width' is less than or equal to @code{len(s)}.  For example:

@example
>>> 'Python'.center(10)
'  Python  '
>>> 'Python'.center(10, '-')
'--Python--'
>>> 'Python'.center(4)
'Python'
@end example
@end deffn

@geindex count() (str のメソッド)
@anchor{library/stdtypes str count}@anchor{1981}
@deffn {メソッド} str.count (sub[, start[, end]])

[`start', `end'] の範囲に、部分文字列 `sub' が重複せず出現する回数を返します。オプション引数 `start' および `end' はスライス表記と同じように解釈されます。

If `sub' is empty, returns the number of empty strings between characters
which is the length of the string plus one. For example:

@example
>>> 'spam, spam, spam'.count('spam')
3
>>> 'spam, spam, spam'.count('spam', 5)
2
>>> 'spam, spam, spam'.count('spam', 5, 10)
1
>>> 'spam, spam, spam'.count('eggs')
0
>>> 'spam, spam, spam'.count('@w{'})
17
@end example
@end deffn

@geindex encode() (str のメソッド)
@anchor{library/stdtypes str encode}@anchor{ad2}
@deffn {メソッド} str.encode (encoding='utf-8', errors='strict')

@ref{192,,bytes} にエンコードされた文字列を返します。

`encoding' のデフォルト値は @code{'utf-8'} です; 指定可能な値については @ref{fb8,,標準エンコーディング} を参照してください。

`errors' はエンコーディングエラーをどのように取り扱うかを制御します。 @code{'strict'} (デフォルト) では @ref{462,,UnicodeError} 例外が送出されます。そのほかに指定可能な値は @code{'ignore'}, @code{'replace'}, @code{'xmlcharrefreplace'}, @code{'backslashreplace'} と、そして @ref{16b4,,codecs.register_error()} で登録された名前です。詳しくは @ref{1b6f,,エラーハンドラ} を参照してください。

For performance reasons, the value of `errors' is not checked for validity
unless an encoding error actually occurs,
@ref{508,,Python 開発モード} is enabled
or a @ref{509,,debug build} is used.
For example:

@example
>>> encoded_str_to_bytes = 'Python'.encode()
>>> type(encoded_str_to_bytes)
<class 'bytes'>
>>> encoded_str_to_bytes
b'Python'
@end example


バージョン 3.1 で変更: キーワード引数のサポートが追加されました。



バージョン 3.9 で変更: `errors' 引数の値は @ref{508,,Python 開発モード} と @ref{509,,デバッグモード} でチェックされるようになりました。

@end deffn

@geindex endswith() (str のメソッド)
@anchor{library/stdtypes str endswith}@anchor{10cc}
@deffn {メソッド} str.endswith (suffix[, start[, end]])

Return @code{True} if the string ends with the specified `suffix', otherwise return
@code{False}.  `suffix' can also be a tuple of suffixes to look for.  With optional
`start', test beginning at that position.  With optional `end', stop comparing
at that position. Using `start' and `end' is equivalent to
@code{str[start:end].endswith(suffix)}. For example:

@example
>>> 'Python'.endswith('on')
True
>>> 'a tuple of suffixes'.endswith(('at', 'in'))
False
>>> 'a tuple of suffixes'.endswith(('at', 'es'))
True
>>> 'Python is amazing'.endswith('is', 0, 9)
True
@end example

See also @ref{10cb,,startswith()} and @ref{acd,,removesuffix()}.
@end deffn

@geindex expandtabs() (str のメソッド)
@anchor{library/stdtypes str expandtabs}@anchor{2647}
@deffn {メソッド} str.expandtabs (tabsize=8)

Return a copy of the string where all tab characters are replaced by one or
more spaces, depending on the current column and the given tab size.  Tab
positions occur every `tabsize' characters (default is 8, giving tab
positions at columns 0, 8, 16 and so on).  To expand the string, the current
column is set to zero and the string is examined character by character.  If
the character is a tab (@code{\t}), one or more space characters are inserted
in the result until the current column is equal to the next tab position.
(The tab character itself is not copied.)  If the character is a newline
(@code{\n}) or return (@code{\r}), it is copied and the current column is reset to
zero.  Any other character is copied unchanged and the current column is
incremented by one regardless of how the character is represented when
printed. For example:

@example
>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'
>>> print('01\t012\n0123\t01234'.expandtabs(4))
01  012
0123    01234
@end example
@end deffn

@geindex find() (str のメソッド)
@anchor{library/stdtypes str find}@anchor{10a8}
@deffn {メソッド} str.find (sub[, start[, end]])

Return the lowest index in the string where substring `sub' is found within
the slice @code{s[start:end]}.  Optional arguments `start' and `end' are
interpreted as in slice notation.  Return @code{-1} if `sub' is not found.
For example:

@example
>>> 'spam, spam, spam'.find('sp')
0
>>> 'spam, spam, spam'.find('sp', 5)
6
@end example

See also @ref{10a9,,rfind()} and @ref{19bc,,index()}.

@cartouche
@quotation 注釈 
@ref{10a8,,find()} メソッドは、 `sub' の位置を知りたいときにのみ使うべきです。 `sub' が部分文字列であるかどうかのみを調べるには、 @ref{34b,,in} 演算子を使ってください:

@example
>>> 'Py' in 'Python'
True
@end example
@end quotation
@end cartouche
@end deffn

@geindex format() (str のメソッド)
@anchor{library/stdtypes str format}@anchor{833}
@deffn {メソッド} str.format (*args, **kwargs)

Perform a string formatting operation.  The string on which this method is
called can contain literal text or replacement fields delimited by braces
@code{@{@}}.  Each replacement field contains either the numeric index of a
positional argument, or the name of a keyword argument.  Returns a copy of
the string where each replacement field is replaced with the string value of
the corresponding argument. For example:

@example
>>> "The sum of 1 + 2 is @{0@}".format(1+2)
'The sum of 1 + 2 is 3'
>>> "The sum of @{a@} + @{b@} is @{answer@}".format(answer=1+2, a=1, b=2)
'The sum of 1 + 2 is 3'
>>> "@{1@} expects the @{0@} Inquisition!".format("Spanish", "Nobody")
'Nobody expects the Spanish Inquisition!'
@end example

書式指定のオプションについては、書式指定文字列を規定する @ref{15b3,,書式指定文字列の文法} を参照してください。

@cartouche
@quotation 注釈 
数値 (@ref{19b,,int}, @ref{196,,float}, @ref{197,,complex}, @ref{1fe,,decimal.Decimal} とサブクラス) を @code{n} の整数表現型 (例: @code{'@{:n@}'.format(1234)}) でフォーマットするとき、@code{LC_CTYPE} ロケールと @code{LC_NUMERIC} ロケールの一方または両方が 1 バイトより長い非 ASCII 文字であると同時に異なる値である場合、この関数は @code{localeconv()} の @code{decimal_point} と @code{thousands_sep} フィールドを読み取るため一時的に @code{LC_CTYPE} ロケールに @code{LC_NUMERIC} のロケール値を設定します。この一時的な変更は他のスレッドの動作に影響します。
@end quotation
@end cartouche


バージョン 3.7 で変更: 数値を @code{n} の整数表現型でフォーマットするとき、この関数は一時的に @code{LC_CTYPE} ロケールに @code{LC_NUMERIC} のロケール値を設定する場合があります。

@end deffn

@geindex format_map() (str のメソッド)
@anchor{library/stdtypes str format_map}@anchor{fd7}
@deffn {メソッド} str.format_map (mapping, /)

@code{str.format(**mapping)} と似ていますが、 @code{mapping} は @ref{183,,dict}  にコピーされず、直接使われます。これは例えば @code{mapping} が dict のサブクラスであるときに便利です:

@example
>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> '@{name@} was born in @{country@}'.format_map(Default(name='Guido'))
'Guido was born in country'
@end example


Added in version 3.2.

@end deffn

@geindex index() (str のメソッド)
@anchor{library/stdtypes str index}@anchor{19bc}
@deffn {メソッド} str.index (sub[, start[, end]])

Like @ref{10a8,,find()}, but raise @ref{2ec,,ValueError} when the substring is
not found. For example:

@example
>>> 'spam, spam, spam'.index('spam')
0
>>> 'spam, spam, spam'.index('eggs')
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    'spam, spam, spam'.index('eggs')
    ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
ValueError: substring not found
@end example

See also @ref{146f,,rindex()}.
@end deffn

@geindex isalnum() (str のメソッド)
@anchor{library/stdtypes str isalnum}@anchor{2631}
@deffn {メソッド} str.isalnum ()

Return @code{True} if all characters in the string are alphanumeric and there is at
least one character, @code{False} otherwise.  A character @code{c} is alphanumeric if one
of the following returns @code{True}: @code{c.isalpha()}, @code{c.isdecimal()},
@code{c.isdigit()}, or @code{c.isnumeric()}. For example:

@example
.. doctest::
@end example

@example
>>> 'abc123'.isalnum()
True
>>> 'abc123!@@#'.isalnum()
False
>>> '@w{'}.isalnum()
False
>>> ' '.isalnum()
False
@end example
@end deffn

@geindex isalpha() (str のメソッド)
@anchor{library/stdtypes str isalpha}@anchor{262b}
@deffn {メソッド} str.isalpha ()

Return @code{True} if all characters in the string are alphabetic and there is at least
one character, @code{False} otherwise.  Alphabetic characters are those characters defined
in the Unicode character database as "Letter", i.e., those with general category
property being one of "Lm", "Lt", "Lu", "Ll", or "Lo".  Note that this is different
from the Alphabetic property defined in the section 4.10 'Letters@comma{} Alphabetic@comma{} and Ideographic' of the Unicode Standard@footnote{https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-4/#G91002}.
For example:

@example
>>> 'Letters and spaces'.isalpha()
False
>>> 'LettersOnly'.isalpha()
True
>>> 'µ'.isalpha()  # non-ASCII characters can be considered alphabetical too
True
@end example

See @ref{2653,,Unicode プロパティ}.
@end deffn

@geindex isascii() (str のメソッド)
@anchor{library/stdtypes str isascii}@anchor{ce9}
@deffn {メソッド} str.isascii ()

Return @code{True} if the string is empty or all characters in the string are ASCII,
@code{False} otherwise.
ASCII characters have code points in the range U+0000-U+007F. For example:

@example
>>> 'ASCII characters'.isascii()
True
>>> 'µ'.isascii()
False
@end example


Added in version 3.7.

@end deffn

@geindex isdecimal() (str のメソッド)
@anchor{library/stdtypes str isdecimal}@anchor{262d}
@deffn {メソッド} str.isdecimal ()

Return @code{True} if all characters in the string are decimal
characters and there is at least one character, @code{False}
otherwise. Decimal characters are those that can be used to form
numbers in base 10, such as U+0660, ARABIC-INDIC DIGIT
ZERO.  Formally a decimal character is a character in the Unicode
General Category "Nd". For example:

@example
>>> '0123456789'.isdecimal()
True
>>> '٠١٢٣٤٥٦٧٨٩'.isdecimal()  # Arabic-Indic digits zero to nine
True
>>> 'alphabetic'.isdecimal()
False
@end example
@end deffn

@geindex isdigit() (str のメソッド)
@anchor{library/stdtypes str isdigit}@anchor{262e}
@deffn {メソッド} str.isdigit ()

文字列中の全ての文字が数字で、かつ 1 文字以上あるなら @code{True} を、そうでなければ @code{False} を返します。ここでの数字とは、十進数字に加えて、互換上付き数字のような特殊操作を必要とする数字を含みます。また 10 を基数とした表現ができないカローシュティー数字のような体系の文字も含みます。正式には、数字とは、プロパティ値 Numeric_Type=Digit または Numeric_Type=Decimal を持つ文字です。
@end deffn

@geindex isidentifier() (str のメソッド)
@anchor{library/stdtypes str isidentifier}@anchor{1d46}
@deffn {メソッド} str.isidentifier ()

文字列が、 @ref{22a0,,Names (identifiers and keywords)} 節の言語定義における有効な識別子であれば @code{True} を返します。

@ref{2654,,keyword.iskeyword()} は、文字列 @code{s} が @ref{1673,,def} や @ref{14ef,,class} のような予約済みの識別子かどうかを調べるのに使うことができます。

例:

@example
>>> from keyword import iskeyword

>>> 'hello'.isidentifier(), iskeyword('hello')
(True, False)
>>> 'def'.isidentifier(), iskeyword('def')
(True, True)
@end example
@end deffn

@geindex islower() (str のメソッド)
@anchor{library/stdtypes str islower}@anchor{2633}
@deffn {メソッド} str.islower ()

文字列中の大小文字の区別のある文字 @footnote{
大小文字の区別のある文字とは、一般カテゴリプロパティが "Lu" (Letter, uppercase (大文字))、 "Ll" (Letter, lowercase (小文字))、 "Lt" (Letter、titlecase (先頭が大文字)) のいずれかであるものです。
} 全てが小文字で、かつ大小文字の区別のある文字が 1 文字以上あるなら @code{True} を、そうでなければ @code{False} を返します。
@end deffn

@geindex isnumeric() (str のメソッド)
@anchor{library/stdtypes str isnumeric}@anchor{2630}
@deffn {メソッド} str.isnumeric ()

Return @code{True} if all characters in the string are numeric
characters, and there is at least one character, @code{False}
otherwise. Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. U+2155,
VULGAR FRACTION ONE FIFTH.  Formally, numeric characters are those with the property
value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
For example:

@example
>>> '0123456789'.isnumeric()
True
>>> '٠١٢٣٤٥٦٧٨٩'.isnumeric()  # Arabic-indic digit zero to nine
True
>>> '⅕'.isnumeric()  # Vulgar fraction one fifth
True
>>> '²'.isdecimal(), '²'.isdigit(),  '²'.isnumeric()
(False, True, True)
@end example

See also @ref{262d,,isdecimal()} and @ref{262e,,isdigit()}. Numeric characters are
a superset of decimal numbers.
@end deffn

@geindex isprintable() (str のメソッド)
@anchor{library/stdtypes str isprintable}@anchor{fd8}
@deffn {メソッド} str.isprintable ()

Return @code{True} if all characters in the string are printable, @code{False} if it
contains at least one non-printable character.

Here "printable" means the character is suitable for @ref{1c1,,repr()} to use in
its output; "non-printable" means that @ref{1c1,,repr()} on built-in types will
hex-escape the character.  It has no bearing on the handling of strings
written to @ref{ccd,,sys.stdout} or @ref{b33,,sys.stderr}.

The printable characters are those which in the Unicode character database
(see @ref{10b,,unicodedata}) have a general category in group Letter, Mark,
Number, Punctuation, or Symbol (L, M, N, P, or S); plus the ASCII space 0x20.
Nonprintable characters are those in group Separator or Other (Z or C),
except the ASCII space.

例えば:

@example
>>> '@w{'}.isprintable(), ' '.isprintable()
(True, True)
>>> '\t'.isprintable(), '\n'.isprintable()
(False, False)
@end example
@end deffn

@geindex isspace() (str のメソッド)
@anchor{library/stdtypes str isspace}@anchor{2639}
@deffn {メソッド} str.isspace ()

文字列が空白文字だけからなり、かつ 1 文字以上ある場合には @code{True} を返し、そうでない場合は @code{False} を返します。

Unicode 文字データベース (@ref{10b,,unicodedata} を参照) で一般カテゴリが @code{Zs} ("Seperator, space") であるか、 双方向クラスが　@code{WS}、@code{B}、 @code{S} のいずれかである場合、その文字は `空白文字(whitespace)' です。
@end deffn

@geindex istitle() (str のメソッド)
@anchor{library/stdtypes str istitle}@anchor{2637}
@deffn {メソッド} str.istitle ()

文字列がタイトルケース文字列であり、かつ 1 文字以上ある場合、例えば大文字は大小文字の区別のない文字の後にのみ続き、小文字は大小文字の区別のある文字の後ろにのみ続く場合には @code{True} を返します。そうでない場合は @code{False} を返します。

例えば:

@example
>>> 'Spam, Spam, Spam'.istitle()
True
>>> 'spam, spam, spam'.istitle()
False
>>> 'SPAM, SPAM, SPAM'.istitle()
False
@end example

See also @ref{2640,,title()}.
@end deffn

@geindex isupper() (str のメソッド)
@anchor{library/stdtypes str isupper}@anchor{2635}
@deffn {メソッド} str.isupper ()

文字列中の大小文字の区別のある文字 @footnote{
大小文字の区別のある文字とは、一般カテゴリプロパティが "Lu" (Letter, uppercase (大文字))、 "Ll" (Letter, lowercase (小文字))、 "Lt" (Letter、titlecase (先頭が大文字)) のいずれかであるものです。
} 全てが大文字で、かつ大小文字の区別のある文字が 1 文字以上あるなら @code{True} を、そうでなければ @code{False} を返します。

@example
>>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False
@end example
@end deffn

@geindex join() (str のメソッド)
@anchor{library/stdtypes meth-str-join}@anchor{2655}@anchor{library/stdtypes str join}@anchor{2609}
@deffn {メソッド} str.join (iterable, /)

Return a string which is the concatenation of the strings in `iterable'.
A @ref{198,,TypeError} will be raised if there are any non-string values in
`iterable', including @ref{192,,bytes} objects.  The separator between
elements is the string providing this method. For example:

@example
>>> ', '.join(['spam', 'spam', 'spam'])
'spam, spam, spam'
>>> '-'.join('Python')
'P-y-t-h-o-n'
@end example

See also @ref{10aa,,split()}.
@end deffn

@geindex ljust() (str のメソッド)
@anchor{library/stdtypes str ljust}@anchor{2062}
@deffn {メソッド} str.ljust (width, fillchar=' ', /)

長さ `width' の左揃えした文字列を返します。パディングは指定された `fillchar' (デフォルトでは ASCII スペース) を使って行われます。 `width' が @code{len(s)} 以下ならば、元の文字列が返されます。

例えば:

@example
>>> 'Python'.ljust(10)
'Python    '
>>> 'Python'.ljust(10, '.')
'Python....'
>>> 'Monty Python'.ljust(10, '.')
'Monty Python'
@end example

See also @ref{2061,,rjust()}.
@end deffn

@geindex lower() (str のメソッド)
@anchor{library/stdtypes str lower}@anchor{1b76}
@deffn {メソッド} str.lower ()

Return a copy of the string with all the cased characters @footnote{
大小文字の区別のある文字とは、一般カテゴリプロパティが "Lu" (Letter, uppercase (大文字))、 "Ll" (Letter, lowercase (小文字))、 "Lt" (Letter、titlecase (先頭が大文字)) のいずれかであるものです。
} converted to
lowercase. For example:

@example
>>> 'Lower Method Example'.lower()
'lower method example'
@end example

The lowercasing algorithm used is
described in section 3.13 'Default Case Folding' of the Unicode Standard@footnote{https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G33992}.
@end deffn

@geindex lstrip() (str のメソッド)
@anchor{library/stdtypes str lstrip}@anchor{16c9}
@deffn {メソッド} str.lstrip (chars=None, /)

文字列の先頭の文字を除去したコピーを返します。引数 `chars' は除去される文字の集合を指定する文字列です。 `chars' が省略されるか @code{None} の場合、空白文字が除去されます。 `chars' 文字列は接頭辞ではなく、その値に含まれる文字の組み合わせ全てがはぎ取られます:

@example
>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
@end example

文字の集合全てではなく、指定した文字列そのものを接頭辞として削除するメソッドについては、 @ref{acc,,str.removeprefix()} を参照してください。使用例:

@example
>>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!'
@end example
@end deffn

@geindex maketrans() (str の静的メソッド)
@anchor{library/stdtypes str maketrans}@anchor{fd9}
@deffn {メソッド} static str.maketrans (dict, /)

@deffnx {メソッド} static str.maketrans (from, to, remove='@w{'}, /)

この静的メソッドは @ref{264c,,str.translate()} に使える変換テーブルを返します。

引数を 1 つだけ与える場合、それは Unicode 序数 (整数) または文字  (長さ 1 の文字列) を、Unicode 序数、(任意長の) 文字列、または @code{None} に対応づける辞書でなければなりません。このとき、文字で指定したキーは序数に変換されます。

If there are two arguments, they must be strings of equal length, and in the
resulting dictionary, each character in `from' will be mapped to the character at
the same position in `to'.  If there is a third argument, it must be a string,
whose characters will be mapped to @code{None} in the result.
@end deffn

@geindex partition() (str のメソッド)
@anchor{library/stdtypes str partition}@anchor{10ab}
@deffn {メソッド} str.partition (sep, /)

文字列を `sep' の最初の出現位置で区切り、 3 要素のタプルを返します。タプルの内容は、区切りの前の部分、区切り文字列そのもの、そして区切りの後ろの部分です。もし区切れなければ、タプルには元の文字列そのものとその後ろに二つの空文字列が入ります。

例えば:

@example
>>> 'Monty Python'.partition(' ')
('Monty', ' ', 'Python')
>>> "Monty Python's Flying Circus".partition(' ')
('Monty', ' ', "Python's Flying Circus")
>>> 'Monty Python'.partition('-')
('Monty Python', '@w{'}, '@w{'})
@end example

See also @ref{1470,,rpartition()}.
@end deffn

@geindex removeprefix() (str のメソッド)
@anchor{library/stdtypes str removeprefix}@anchor{acc}
@deffn {メソッド} str.removeprefix (prefix, /)

If the string starts with the `prefix' string, return
@code{string[len(prefix):]}. Otherwise, return a copy of the original
string:

@example
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
@end example


Added in version 3.9.


See also @ref{acd,,removesuffix()} and @ref{10cb,,startswith()}.
@end deffn

@geindex removesuffix() (str のメソッド)
@anchor{library/stdtypes str removesuffix}@anchor{acd}
@deffn {メソッド} str.removesuffix (suffix, /)

If the string ends with the `suffix' string and that `suffix' is not empty,
return @code{string[:-len(suffix)]}. Otherwise, return a copy of the
original string:

@example
>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
@end example


Added in version 3.9.


See also @ref{acc,,removeprefix()} and @ref{10cc,,endswith()}.
@end deffn

@geindex replace() (str のメソッド)
@anchor{library/stdtypes str replace}@anchor{4b8}
@deffn {メソッド} str.replace (old, new, /, count=-1)

Return a copy of the string with all occurrences of substring `old' replaced by
`new'.  If `count' is given, only the first `count' occurrences are replaced.
If `count' is not specified or @code{-1}, then all occurrences are replaced.
For example:

@example
>>> 'spam, spam, spam'.replace('spam', 'eggs')
'eggs, eggs, eggs'
>>> 'spam, spam, spam'.replace('spam', 'eggs', 1)
'eggs, spam, spam'
@end example


バージョン 3.13 で変更: `count' はキーワード引数として指定可能になりました。

@end deffn

@geindex rfind() (str のメソッド)
@anchor{library/stdtypes str rfind}@anchor{10a9}
@deffn {メソッド} str.rfind (sub[, start[, end]])

Return the highest index in the string where substring `sub' is found, such
that `sub' is contained within @code{s[start:end]}.  Optional arguments `start'
and `end' are interpreted as in slice notation.  Return @code{-1} on failure.
For example:

@example
>>> 'spam, spam, spam'.rfind('sp')
12
>>> 'spam, spam, spam'.rfind('sp', 0, 10)
6
@end example

See also @ref{10a8,,find()} and @ref{146f,,rindex()}.
@end deffn

@geindex rindex() (str のメソッド)
@anchor{library/stdtypes str rindex}@anchor{146f}
@deffn {メソッド} str.rindex (sub[, start[, end]])

Like @ref{10a9,,rfind()} but raises @ref{2ec,,ValueError} when the substring `sub' is not
found.
For example:

@example
>>> 'spam, spam, spam'.rindex('spam')
12
>>> 'spam, spam, spam'.rindex('eggs')
Traceback (most recent call last):
  File "<stdin-0>", line 1, in <module>
    'spam, spam, spam'.rindex('eggs')
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
ValueError: substring not found
@end example

See also @ref{19bc,,index()} and @ref{10a8,,find()}.
@end deffn

@geindex rjust() (str のメソッド)
@anchor{library/stdtypes str rjust}@anchor{2061}
@deffn {メソッド} str.rjust (width, fillchar=' ', /)

`width' の長さをもつ右寄せした文字列を返します。パディングには `fillchar' で指定された文字(デフォルトでは ASCII スペース)が使われます。 `width' が @code{len(s)} 以下の場合、元の文字列が返されます。
@end deffn

@geindex rpartition() (str のメソッド)
@anchor{library/stdtypes str rpartition}@anchor{1470}
@deffn {メソッド} str.rpartition (sep, /)

文字列を `sep' の最後の出現位置で区切り、 3 要素のタプルを返します。タプルの内容は、区切りの前の部分、区切り文字列そのもの、そして区切りの後ろの部分です。もし区切れなければ、タプルには二つの空文字列とその後ろに元の文字列そのものが入ります。

例えば:

@example
>>> 'Monty Python'.rpartition(' ')
('Monty', ' ', 'Python')
>>> "Monty Python's Flying Circus".rpartition(' ')
("Monty Python's Flying", ' ', 'Circus')
>>> 'Monty Python'.rpartition('-')
('@w{'}, '@w{'}, 'Monty Python')
@end example

See also @ref{10ab,,partition()}.
@end deffn

@geindex rsplit() (str のメソッド)
@anchor{library/stdtypes str rsplit}@anchor{146d}
@deffn {メソッド} str.rsplit (sep=None, maxsplit=-1)

`sep' を区切り文字とした、文字列中の単語のリストを返します。 `maxsplit' が与えられた場合、文字列の `右端' から最大 `maxsplit' 回分割を行います。`sep' が指定されていない、あるいは @code{None} のとき、全ての空白文字が区切り文字となります。右から分割していくことを除けば、 @ref{146d,,rsplit()} は後ほど詳しく述べる @ref{10aa,,split()} と同様に振る舞います。
@end deffn

@geindex rstrip() (str のメソッド)
@anchor{library/stdtypes str rstrip}@anchor{16ca}
@deffn {メソッド} str.rstrip (chars=None, /)

Return a copy of the string with trailing characters removed.  The `chars'
argument is a string specifying the set of characters to be removed.  If omitted
or @code{None}, the `chars' argument defaults to removing whitespace.  The `chars'
argument is not a suffix; rather, all combinations of its values are stripped.
For example:

@example
>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
@end example

See @ref{acd,,removesuffix()} for a method that will remove a single suffix
string rather than all of a set of characters.  For example:

@example
>>> 'Monty Python'.rstrip(' Python')
'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty'
@end example

See also @ref{16c8,,strip()}.
@end deffn

@geindex split() (str のメソッド)
@anchor{library/stdtypes str split}@anchor{10aa}
@deffn {メソッド} str.split (sep=None, maxsplit=-1)

文字列を `sep' をデリミタ文字列として区切った単語のリストを返します。`maxsplit' が与えられていれば、最大で `maxsplit' 回分割されます (つまり、リストは最大 @code{maxsplit+1} 要素になります)。 `maxsplit' が与えられないか @code{-1} なら、分割の回数に制限はありません (可能なだけ分割されます)。

`sep' が与えられた場合、連続した区切り文字はまとめられず、空の文字列を区切っていると判断されます(例えば @code{'1,,2'.split(',')} は @code{['1', '@w{'}, '2']} を返します)。引数 `sep' は複数の文字を1つの区切り文字にもできます (複数の区切り文字で分割するには @ref{5a2,,re.split()} を使用します)。区切り文字を指定して空の文字列を分割すると、 @code{['@w{'}]} を返します。

例えば:

@example
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '@w{'}, '3', '@w{'}]
>>> '1<>2<>3<4'.split('<>')
['1', '2', '3<4']
@end example

`sep' が指定されていないか @code{None} の場合、異なる分割アルゴリズムが適用されます。連続する空白文字はひとつのデリミタとみなされます。また、文字列の先頭や末尾に空白があっても、結果の最初や最後に空文字列は含まれません。よって、空文字列や空白だけの文字列を @code{None} デリミタで分割すると @code{[]} が返されます。

例えば:

@example
>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']
@end example

If `sep' is not specified or is @code{None} and  `maxsplit' is @code{0}, only
leading runs of consecutive whitespace are considered.

例えば:

@example
>>> "".split(None, 0)
[]
>>> "   ".split(None, 0)
[]
>>> "   foo   ".split(maxsplit=0)
['foo   ']
@end example

See also @ref{2609,,join()}.
@end deffn

@geindex universal newlines;str.splitlines メソッド

@geindex splitlines() (str のメソッド)
@anchor{library/stdtypes str splitlines}@anchor{146e}
@deffn {メソッド} str.splitlines (keepends=False)

文字列を改行部分で分解し、各行からなるリストを返します。 `keepends' に真が与えらない限り、返されるリストに改行は含まれません。

このメソッドは以下の行境界で分解します。特に、以下の境界は @ref{f35,,universal newlines} のスーパーセットです。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

表現

@tab

説明

@item

@code{\n}

@tab

改行

@item

@code{\r}

@tab

復帰

@item

@code{\r\n}

@tab

改行 + 復帰

@item

@code{\v} or @code{\x0b}

@tab

垂直タブ

@item

@code{\f} or @code{\x0c}

@tab

改ページ

@item

@code{\x1c}

@tab

ファイル区切り

@item

@code{\x1d}

@tab

グループ区切り

@item

@code{\x1e}

@tab

レコード区切り

@item

@code{\x85}

@tab

改行 (C1 制御コード)

@item

@code{\u2028}

@tab

行区切り

@item

@code{\u2029}

@tab

段落区切り

@end multitable



バージョン 3.2 で変更: @code{\v} と @code{\f} が行境界のリストに追加されました。


例えば:

@example
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '@w{'}, 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
@end example

@ref{10aa,,split()} とは違って、デリミタ文字列 `sep' が与えられたとき、このメソッドは空文字列に空リストを返し、終末の改行は結果に行を追加しません:

@example
>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']
@end example

比較のために @code{split('\n')} は以下のようになります:

@example
>>> '@w{'}.split('\n')
['@w{'}]
>>> 'Two lines\n'.split('\n')
['Two lines', '@w{'}]
@end example
@end deffn

@geindex startswith() (str のメソッド)
@anchor{library/stdtypes str startswith}@anchor{10cb}
@deffn {メソッド} str.startswith (prefix[, start[, end]])

文字列が指定された `prefix' で始まるなら @code{True} を、そうでなければ @code{False} を返します。 `prefix' は見つけたい複数の接頭語のタプルでも構いません。オプションの `start' があれば、その位置から判定を始めます。オプションの `end' があれば、その位置で比較を止めます。

例えば:

@example
>>> 'Python'.startswith('Py')
True
>>> 'a tuple of prefixes'.startswith(('at', 'a'))
True
>>> 'Python is amazing'.startswith('is', 7)
True
@end example

See also @ref{10cc,,endswith()} and @ref{acc,,removeprefix()}.
@end deffn

@geindex strip() (str のメソッド)
@anchor{library/stdtypes str strip}@anchor{16c8}
@deffn {メソッド} str.strip (chars=None, /)

Return a copy of the string with the leading and trailing characters removed.
The `chars' argument is a string specifying the set of characters to be removed.
If omitted or @code{None}, the `chars' argument defaults to removing whitespace.
The `chars' argument is not a prefix or suffix; rather, all combinations of its
values are stripped.

例えば:

@example
>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
@end example

The outermost leading and trailing `chars' argument values are stripped
from the string. Characters are removed from the leading end until
reaching a string character that is not contained in the set of
characters in `chars'. A similar action takes place on the trailing end.

例えば:

@example
>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
@end example

See also @ref{16ca,,rstrip()}.
@end deffn

@geindex swapcase() (str のメソッド)
@anchor{library/stdtypes str swapcase}@anchor{2642}
@deffn {メソッド} str.swapcase ()

大文字が小文字に、小文字が大文字に変換された、文字列のコピーを返します。なお、 @code{s.swapcase().swapcase() == s} が真であるとは限りません。
@end deffn

@geindex title() (str のメソッド)
@anchor{library/stdtypes str title}@anchor{2640}
@deffn {メソッド} str.title ()

文字列を、単語ごとに大文字から始まり、残りの文字のうち大小文字の区別があるものは全て小文字にする、タイトルケースにして返します。

例えば:

@example
>>> 'Hello world'.title()
'Hello World'
@end example

このアルゴリズムは、連続した文字の集まりという、言語から独立した単純な単語の定義を使います。この定義は多くの状況ではうまく機能しますが、短縮形や所有格のアポストロフィが単語の境界になってしまい、望みの結果を得られない場合があります:

@example
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
@end example

@ref{2656,,string.capwords()} 関数は単語をスペースでのみ分割するため、この問題はありません。

または、正規表現を使うことでアポストロフィに対応できます:

@example
>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0).capitalize(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
@end example

See also @ref{2637,,istitle()}.
@end deffn

@geindex translate() (str のメソッド)
@anchor{library/stdtypes str translate}@anchor{264c}
@deffn {メソッド} str.translate (table, /)

与えられた変換テーブルに基づいて文字列を構成する各文字をマッピングし、マッピング後の文字列のコピーを返します。変換テーブルは、@ref{588,,__getitem__()} によるインデックス指定を実装するオブジェクトである必要があります。一般的には、 @ref{13d3,,mapping} または @ref{716,,sequence} です。Unicode 序数 (整数) でインデックス指定する場合、変換テーブルのオブジェクトは次のいずれも行うことができます。Unicode 序数または文字列を返して文字を 1 文字以上の別の文字にマッピングすること、@code{None} を返して返り値の文字列から指定した文字を削除すること、例外 @ref{23e5,,LookupError} を送出して文字をその文字自身にマッピングすること。

文字から文字への異なる形式のマッピングから変換マップを作成するために、 @ref{fd9,,str.maketrans()} が使えます。

文字のマッピングを好みに合わせてより柔軟に変更する方法については、@ref{1c,,codecs} モジュールも参照してください。
@end deffn

@geindex upper() (str のメソッド)
@anchor{library/stdtypes str upper}@anchor{263c}
@deffn {メソッド} str.upper ()

全ての大小文字の区別のある文字 @footnote{
大小文字の区別のある文字とは、一般カテゴリプロパティが "Lu" (Letter, uppercase (大文字))、 "Ll" (Letter, lowercase (小文字))、 "Lt" (Letter、titlecase (先頭が大文字)) のいずれかであるものです。
} が大文字に変換された、文字列のコピーを返します。なお @code{s.upper().isupper()} は、 @code{s} が大小文字の区別のある文字を含まなかったり、結果の文字の Unicode カテゴリが "Lu" ではなく例えば "Lt" (Letter, titlecase) などであったら、 @code{False} になりえます。

The uppercasing algorithm used is
described in section 3.13 'Default Case Folding' of the Unicode Standard@footnote{https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G33992}.
@end deffn

@geindex zfill() (str のメソッド)
@anchor{library/stdtypes str zfill}@anchor{16cb}
@deffn {メソッド} str.zfill (width, /)

長さが `width' になるよう ASCII @code{'0'} で左詰めした文字列のコピーを返します。先頭が符号接頭辞 (@code{'+'}/@code{'-'}) だった場合、 @code{'0'} は符号の前ではなく `後' に挿入されます。`width' が @code{len(s)} 以下の場合元の文字列を返します。

例えば:

@example
>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'
@end example
@end deffn

@geindex ! formatted string literal
@geindex formatted string literals
@geindex ! f-string
@geindex f-strings
@geindex fstring
@geindex interpolated string literal
@geindex string;formatted literal
@geindex string;interpolated literal
@geindex @{@} (波括弧);in formatted string literal
@geindex ! (exclamation mark);in formatted string literal
@geindex ; (コロン);in formatted string literal
@geindex = (等号);for help in debugging using string literals

@node Formatted String Literals f-strings,Template String Literals t-strings,文字列メソッド<2>,テキストシーケンス型 --- str
@anchor{library/stdtypes formatted-string-literals-f-strings}@anchor{2657}@anchor{library/stdtypes stdtypes-fstrings}@anchor{22eb}
@subsubsection Formatted String Literals (f-strings)



Added in version 3.6.



バージョン 3.7 で変更: The @ref{18d,,await} and @ref{ca1,,async for} can be used in expressions
within f-strings.



バージョン 3.8 で変更: Added the debug specifier (@code{=})



バージョン 3.12 で変更: Many restrictions on expressions within f-strings have been removed.
Notably, nested strings, comments, and backslashes are now permitted.


An `f-string' (formally a `formatted string literal') is
a string literal that is prefixed with @code{f} or @code{F}.
This type of string literal allows embedding the results of arbitrary Python
expressions within `replacement fields', which are delimited by curly
brackets (@code{@{@}}).
Each replacement field must contain an expression, optionally followed by:


@itemize *

@item 
a `debug specifier' -- an equal sign (@code{=});

@item 
a `conversion specifier' -- @code{!s}, @code{!r} or @code{!a}; and/or

@item 
a `format specifier' prefixed with a colon (@code{:}).
@end itemize

See the @ref{19a,,Lexical Analysis section on f-strings} for details
on the syntax of these fields.

@menu
* Debug specifier:: 
* Conversion specifier:: 
* Format specifier:: 

@end menu

@node Debug specifier,Conversion specifier,,Formatted String Literals f-strings
@anchor{library/stdtypes debug-specifier}@anchor{2658}
@subsubsection Debug specifier



Added in version 3.8.


If a debug specifier -- an equal sign (@code{=}) -- appears after the replacement
field expression, the resulting f-string will contain the expression's source,
the equal sign, and the value of the expression.
This is often useful for debugging:

@example
>>> number = 14.3
>>> f'@{number=@}'
'number=14.3'
@end example

Whitespace before, inside and after the expression, as well as whitespace
after the equal sign, is significant --- it is retained in the result:

@example
>>> f'@{ number  -  4  = @}'
' number  -  4  = 10.3'
@end example

@node Conversion specifier,Format specifier,Debug specifier,Formatted String Literals f-strings
@anchor{library/stdtypes conversion-specifier}@anchor{2659}
@subsubsection Conversion specifier


By default, the value of a replacement field expression is converted to
a string using @ref{169,,str()}:

@example
>>> from fractions import Fraction
>>> one_third = Fraction(1, 3)
>>> f'@{one_third@}'
'1/3'
@end example

When a debug specifier but no format specifier is used, the default conversion
instead uses @ref{1c1,,repr()}:

@example
>>> f'@{one_third = @}'
'one_third = Fraction(1, 3)'
@end example

The conversion can be specified explicitly using one of these specifiers:


@itemize *

@item 
@code{!s} for @ref{169,,str()}

@item 
@code{!r} for @ref{1c1,,repr()}

@item 
@code{!a} for @ref{15ff,,ascii()}
@end itemize

例えば:

@example
>>> str(one_third)
'1/3'
>>> repr(one_third)
'Fraction(1, 3)'

>>> f'@{one_third!s@} is @{one_third!r@}'
'1/3 is Fraction(1, 3)'

>>> string = "¡kočka 😸!"
>>> ascii(string)
"'\\xa1ko\\u010dka \\U0001f638!'"

>>> f'@{string = !a@}'
"string = '\\xa1ko\\u010dka \\U0001f638!'"
@end example

@node Format specifier,,Conversion specifier,Formatted String Literals f-strings
@anchor{library/stdtypes format-specifier}@anchor{265a}
@subsubsection Format specifier


After the expression has been evaluated, and possibly converted using an
explicit conversion specifier, it is formatted using the @ref{199,,format()} function.
If the replacement field includes a `format specifier' introduced by a colon
(@code{:}), the specifier is passed to @code{format()} as the second argument.
The result of @code{format()} is then used as the final value for the
replacement field. For example:

@example
>>> from fractions import Fraction
>>> one_third = Fraction(1, 3)
>>> f'@{one_third:.6f@}'
'0.333333'
>>> f'@{one_third:_^+10@}'
'___+1/3___'
>>> >>> f'@{one_third!r:_^20@}'
'___Fraction(1, 3)___'
>>> f'@{one_third = :~>10@}~'
'one_third = ~~~~~~~1/3~'
@end example

@node Template String Literals t-strings,printf 形式の文字列書式化,Formatted String Literals f-strings,テキストシーケンス型 --- str
@anchor{library/stdtypes stdtypes-tstrings}@anchor{22ef}@anchor{library/stdtypes template-string-literals-t-strings}@anchor{265b}
@subsubsection Template String Literals (t-strings)


An `t-string' (formally a `template string literal') is
a string literal that is prefixed with @code{t} or @code{T}.

These strings follow the same syntax and evaluation rules as
@ref{22eb,,formatted string literals},
with for the following differences:


@itemize *

@item 
Rather than evaluating to a @code{str} object, template string literals evaluate
to a @ref{16a,,string.templatelib.Template} object.

@item 
The @ref{199,,format()} protocol is not used.
Instead, the format specifier and conversions (if any) are passed to
a new @ref{16b,,Interpolation} object that is created
for each evaluated expression.
It is up to code that processes the resulting @ref{16a,,Template}
object to decide how to handle format specifiers and conversions.

@item 
Format specifiers containing nested replacement fields are evaluated eagerly,
prior to being passed to the @ref{16b,,Interpolation} object.
For instance, an interpolation of the form @code{@{amount:.@{precision@}f@}} will
evaluate the inner expression @code{@{precision@}} to determine the value of the
@code{format_spec} attribute.
If @code{precision} were to be @code{2}, the resulting format specifier
would be @code{'.2f'}.

@item 
When the equals sign @code{'='} is provided in an interpolation expression,
the text of the expression is appended to the literal string that precedes
the relevant interpolation.
This includes the equals sign and any surrounding whitespace.
The @code{Interpolation} instance for the expression will be created as
normal, except that @ref{265c,,conversion} will
be set to '@code{r}' (@ref{1c1,,repr()}) by default.
If an explicit conversion or format specifier are provided,
this will override the default behaviour.
@end itemize

@node printf 形式の文字列書式化,,Template String Literals t-strings,テキストシーケンス型 --- str
@anchor{library/stdtypes old-string-formatting}@anchor{8db}@anchor{library/stdtypes printf-style-string-formatting}@anchor{265d}
@subsubsection @code{printf} 形式の文字列書式化


@geindex 書式化@comma{} 文字列 (%)
@geindex 補間@comma{} 文字列 (%)
@geindex string;formatting@comma{} printf
@geindex string;interpolation@comma{} printf
@geindex printf 形式の書式化
@geindex sprintf 形式の書式化
@geindex % (パーセント);printf 形式の書式化

@cartouche
@quotation 注釈 
The formatting operations described here exhibit a variety of quirks that
lead to a number of common errors (such as failing to display tuples and
dictionaries correctly).

Using @ref{19a,,formatted string literals}, the @ref{833,,str.format()}
interface, or @ref{897,,string.Template} may help avoid these errors.
Each of these alternatives provides their own trade-offs and benefits of
simplicity, flexibility, and/or extensibility.
@end quotation
@end cartouche

文字列オブジェクトには独特の組み込み演算子: @code{%} 演算子 (モジュロ) があります。これは 文字列の `書式化' あるいは `補間' 演算子としても知られています。 @code{format % values} (`format' は文字列とします) が与えられると、`format' の中の @code{%} による変換の指定は0こ以上の `values' の要素で置き換えられます。この動作は C 言語における @code{sprintf()} 関数の利用方法に似ています。使用例:

@example
>>> print('%s has %d quote types.' % ('Python', 2))
Python has 2 quote types.
@end example

`format' が単一の引数しか要求しない場合、 `values' はタプルでない単一のオブジェクトでもかまいません。 @footnote{
従って、一個のタプルだけをフォーマット出力したい場合には出力したいタプルを唯一の要素とする単一のタプルを `values' に与えなくてはなりません。
} それ以外の場合、 `values' はフォーマット文字列中で指定された項目と正確に同じ数の要素からなるタプルか、単一のマップオブジェクトでなければなりません。

@geindex () (丸括弧);in printf-style formatting
@geindex * (アスタリスク);in printf-style formatting
@geindex . (ドット);in printf-style formatting

一つの変換指定子は 2 またはそれ以上の文字を含み、その構成要素は以下からなりますが、示した順に出現しなければなりません:


@enumerate 

@item 
指定子の開始を示す文字 @code{'%'} 。

@item 
マップキー (オプション)。丸括弧で囲った文字列からなります (例えば @code{(somename)}) 。

@item 
変換フラグ (オプション)。一部の変換型の結果に影響します。

@item 
最小のフィールド幅 (オプション)。 @code{'*'} (アスタリスク) を指定した場合、実際の文字列幅が `values' タプルの次の要素から読み出されます。タプルには最小フィールド幅やオプションの精度指定の後に変換したいオブジェクトがくるようにします。

@item 
精度 (オプション)。 @code{'.'} (ドット) とその後に続く精度で与えられます。 @code{'*'} (アスタリスク) を指定した場合、精度の桁数は `values' タプルの次の要素から読み出されます。タプルには精度指定の後に変換したい値がくるようにします。

@item 
精度長変換子 (オプション)。

@item 
変換型。
@end enumerate

@code{%} 演算子の右側の引数が辞書の場合 (またはその他のマップ型の場合), 文字列中のフォーマットには、辞書に挿入されているキーを丸括弧で囲い、文字 @code{'%'} の直後にくるようにしたものが含まれていなければ `なりません' 。マップキーはフォーマット化したい値をマップから選び出します。例えば:

@example
>>> print('%(language)s has %(number)03d quote types.' %
...       @{'language': "Python", "number": 2@})
Python has 002 quote types.
@end example

この場合、 @code{*} 指定子をフォーマットに含めてはいけません (@code{*} 指定子は順番付けされたパラメタのリストが必要だからです)。

変換フラグ文字を以下に示します:

@geindex # (hash);in printf-style formatting
@geindex - (負符号);in printf-style formatting
@geindex + (プラス記号);in printf-style formatting
@geindex 空白;in printf-style formatting


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@item

@code{'#'}

@tab

値の変換に (下で定義されている) "別の形式" を使います。

@item

@code{'0'}

@tab

数値型に対してゼロによるパディングを行います。

@item

@code{'-'}

@tab

変換された値を左寄せにします (@code{'0'} と同時に与えた場合、 @code{'0'} を上書きします) 。

@item

@code{' '}

@tab

(スペース) 符号付きの変換で正の数の場合、前に一つスペースを空けます (そうでない場合は空文字になります) 。

@item

@code{'+'}

@tab

変換の先頭に符号文字 (@code{'+'} または @code{'-'}) を付けます("スペース" フラグを上書きします) 。

@end multitable


精度長変換子(@code{h}, @code{l},または @code{L}) を使うことができますが、 Python では必要ないため無視されます。 -- つまり、例えば @code{%ld} は @code{%d} と等価です。

変換型を以下に示します:


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

変換

@tab

意味

@tab

注釈

@item

@code{'d'}

@tab

符号付き 10 進整数。

@tab

@item

@code{'i'}

@tab

符号付き 10 進整数。

@tab

@item

@code{'o'}

@tab

符号付き 8 進数。

@tab

(1)

@item

@code{'u'}

@tab

旧式の型 -- @code{'d'} と同じです。

@tab

(6)

@item

@code{'x'}

@tab

符号付き 16 進数 (小文字)。

@tab

(2)

@item

@code{'X'}

@tab

符号付き 16 進数 (大文字)。

@tab

(2)

@item

@code{'e'}

@tab

指数表記の浮動小数点数 (小文字)。

@tab

(3)

@item

@code{'E'}

@tab

指数表記の浮動小数点数 (大文字)。

@tab

(3)

@item

@code{'f'}

@tab

10 進浮動小数点数。

@tab

(3)

@item

@code{'F'}

@tab

10 進浮動小数点数。

@tab

(3)

@item

@code{'g'}

@tab

浮動小数点数。指数部が -4 以上または精度以下の場合には小文字指数表記、それ以外の場合には10進表記。

@tab

(4)

@item

@code{'G'}

@tab

浮動小数点数。指数部が -4 以上または精度以下の場合には大文字指数表記、それ以外の場合には10進表記。

@tab

(4)

@item

@code{'c'}

@tab

文字一文字 (整数または一文字からなる文字列を受理します)。

@tab

@item

@code{'r'}

@tab

文字列 (Python オブジェクトを @ref{1c1,,repr()} で変換します)。

@tab

(5)

@item

@code{'s'}

@tab

文字列 (Python オブジェクトを @ref{169,,str()} で変換します)。

@tab

(5)

@item

@code{'a'}

@tab

文字列 (Python オブジェクトを @ref{15ff,,ascii()} で変換します)。

@tab

(5)

@item

@code{'%'}

@tab

引数を変換せず、返される文字列中では文字 @code{'%'} になります。

@tab

@end multitable


注釈:


@enumerate 

@item 
別の形式を指定（訳注: 変換フラグ @code{#} を使用）すると 8 進数を表す接頭辞 (@code{'0o'}) が最初の数字の前に挿入されます。

@item 
別の形式を指定（訳注: 変換フラグ @code{#} を使用）すると 16 進数を表す接頭辞 @code{'0x'} または @code{'0X'} (使用するフォーマット文字が @code{'x'} か @code{'X'} に依存します) が最初の数字の前に挿入されます。

@item 
この形式にした場合、変換結果には常に小数点が含まれ、それはその後ろに数字が続かない場合にも適用されます。

指定精度は小数点の後の桁数を決定し、そのデフォルトは 6 です。

@item 
この形式にした場合、変換結果には常に小数点が含まれ他の形式とは違って末尾の 0 は取り除かれません。

指定精度は小数点の前後の有効桁数を決定し、そのデフォルトは 6 です。

@item 
精度が @code{N} なら、出力は @code{N} 文字に切り詰められます。

@item 
@geindex Python Enhancement Proposals; PEP 237
PEP 237@footnote{https://peps.python.org/pep-0237/} を参照してください。
@end enumerate

Python 文字列には明示的な長さ情報があるので、 @code{%s} 変換において @code{'\0'} を文字列の末端と仮定したりはしません。

@c XXX Examples?


バージョン 3.1 で変更: 絶対値が 1e50 を超える数値の @code{%f} 変換が @code{%g} 変換に置き換えられなくなりました。


@geindex buffer protocol;バイナリシーケンス型

@node バイナリシーケンス型 --- bytes bytearray memoryview,set（集合）型 --- set frozenset,テキストシーケンス型 --- str,組み込み型
@anchor{library/stdtypes binary-sequence-types-bytes-bytearray-memoryview}@anchor{265e}@anchor{library/stdtypes binaryseq}@anchor{25c4}
@subsection バイナリシーケンス型 --- @code{bytes}, @code{bytearray}, @code{memoryview}


@geindex object;bytes
@geindex object;bytearray
@geindex object;memoryview
@geindex module;array

バイナリデータを操作するためのコア組み込み型は @ref{192,,bytes} および @ref{344,,bytearray} です。これらは、別のバイナリオブジェクトのメモリにコピーを作成すること無くアクセスするための @ref{260,,バッファプロトコル} を利用する @ref{165,,memoryview} でサポートされています。

@ref{8,,array} モジュールは、32 ビット整数や IEEE754 倍精度浮動小数点値のような基本データ型の、効率的な保存をサポートしています。

@menu
* バイトオブジェクト:: 
* bytearray オブジェクト:: 
* bytes と bytearray の操作:: 
* printf 形式での bytes の書式化:: 
* メモリビュー:: 

@end menu

@node バイトオブジェクト,bytearray オブジェクト,,バイナリシーケンス型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytes-objects}@anchor{265f}@anchor{library/stdtypes typebytes}@anchor{25c6}
@subsubsection バイトオブジェクト


@geindex object;bytes

bytes はバイトの不変なシーケンスです。多くのメジャーなプロトコルがASCIIテキストエンコーディングをベースにしているので、 bytes オブジェクトは ASCII 互換のデータに対してのみ動作する幾つかのメソッドを提供していて、文字列オブジェクトと他の多くの点で近いです。

@geindex bytes (組み込みクラス)
@anchor{library/stdtypes bytes}@anchor{192}
@deffn {クラス} bytes (source=b'@w{'})

@deffnx {クラス} bytes (source, encoding, errors='strict')

まず、 bytes リテラルの構文は文字列リテラルとほぼ同じで、 @code{b} というプリフィックスを付けます:


@itemize *

@item 
シングルクォート: @code{b'still allows embedded "double" quotes'}

@item 
ダブルクォート: @code{b"still allows embedded 'single' quotes"}.

@item 
3重クォート: @code{b'@w{'}'3 single quotes'@w{'}'}, @code{b"""3 double quotes"""}
@end itemize

bytes リテラルでは (ソースコードのエンコーディングに関係なく) ASCII文字のみが許可されています。 127より大きい値を bytes リテラルに記述する場合は適切なエスケープシーケンスを書く必要があります。

文字列リテラルと同じく、 bytes リテラルでも @code{r} プリフィックスを用いてエスケープシーケンスの処理を無効にすることができます。 bytes リテラルの様々な形式やサポートされているエスケープシーケンスについては @ref{229f,,文字列およびバイト列リテラル} を参照してください。

bytesリテラルと repr 出力は ASCII テキストをベースにしたものですが、 bytes オブジェクトは、各値が @code{0 <= x < 256} の範囲に収まるような整数  (この制限に違反しようとすると @ref{2ec,,ValueError} が発生します) の不変なシーケンスとして振る舞います。多くのバイナリフォーマットがASCIIテキストを元にした要素を持っていたり何らかのテキスト操作アルゴリズムによって操作されるものの、任意のバイナリデータが一般にテキストになっているわけではないことを強調するためにこのように設計されました (何も考えずにテキスト操作アルゴリズムをASCII非互換なバイナリデータフォーマットに対して行うとデータを破壊することがあります)。

リテラル以外に、幾つかの方法で bytes オブジェクトを作ることができます:


@itemize *

@item 
指定された長さの、0で埋められた bytes オブジェクト: @code{bytes(10)}

@item 
整数の iterable から: @code{bytes(range(20))}

@item 
既存のバイナリデータからバッファプロトコルでコピーする: @code{bytes(obj)}
@end itemize

@ref{1e9a,,bytes} ビルトイン関数も参照してください。

16 進数で 2 桁の数は正確に 1 バイトに相当するため、16 進整はバイナリデータを表現する形式として広く使われています。 従って、 bytes 型にはその形式でデータを読み取るための追加のクラスメソッドがあります。

@geindex fromhex() (bytes のクラスメソッド)
@anchor{library/stdtypes bytes fromhex}@anchor{190}
@deffn {メソッド} classmethod fromhex (string, /)

この @ref{192,,bytes} のクラスメソッドは、与えられた文字列オブジェクトをデコードして bytes オブジェクトを返します。それぞれのバイトを 16 進数 2 桁で表現した文字列を指定しなければなりません。ASCII 空白文字は無視されます。

@example
>>> bytes.fromhex('2Ef0 F1f2  ')
b'.\xf0\xf1\xf2'
@end example


バージョン 3.7 で変更: @ref{190,,bytes.fromhex()} は文字列にある空白だけでなく、 ASCII の空白文字全てをスキップするようになりました。



バージョン 3.14 で変更: @ref{190,,bytes.fromhex()} now accepts ASCII @ref{192,,bytes} and
@ref{193,,bytes-like objects} as input.

@end deffn

bytes オブジェクトをその 16 進表記に変換するための、反対向きの変換関数があります。

@geindex hex() (bytes のメソッド)
@anchor{library/stdtypes bytes hex}@anchor{f65}
@deffn {メソッド} hex (*, bytes_per_sep=1)

@deffnx {メソッド} hex (sep, bytes_per_sep=1)

インスタンス内の 1 バイトにつき 2 つの 16 進数を含む、文字列オブジェクトを返します。

@example
>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
@end example

16進数文字列を読みやすく表示したい場合、単一文字パラメータ  `sep' を指定してセパレータを出力に含めることができます。デフォルトでは、セパレータはバイトごとに表示が区切られるように追加されます。2つ目のオプションパラメータ `bytes_per_sep' はセパレータを入れる間隔を制御します。正の整数値はセパレータの位置を右から計算し、負の整数値は左から計算します。

@example
>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
@end example


Added in version 3.5.



バージョン 3.8 で変更: @ref{f65,,bytes.hex()} が、16進数出力の各バイトを分割するセパレータを挿入するためのオプションパラメータ `sep' と `bytes_per_sep' をサポートするようになりました。

@end deffn
@end deffn

bytes オブジェクトは (タプルに似た) 整数のシーケンスなので、 bytes オブジェクト `b' について、 @code{b[0]} は整数になり、 @code{b[0:1]} は長さ 1 の bytes オブジェクトになります。 (この動作は、文字列に対するインデックス指定もスライスも長さ 1 の文字列を返すのと対照的です。)

bytes オブジェクトの repr 出力はリテラル形式 (@code{b'...'}) になります。 @code{bytes([46, 46, 46])} などの形式よりも便利な事が多いからです。 bytes オブジェクトはいつでも @code{list(b)} で整数のリストに変換できます。

@node bytearray オブジェクト,bytes と bytearray の操作,バイトオブジェクト,バイナリシーケンス型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytearray-objects}@anchor{2660}@anchor{library/stdtypes typebytearray}@anchor{25c5}
@subsubsection bytearray オブジェクト


@geindex object;bytearray

@ref{344,,bytearray} オブジェクトは @ref{192,,bytes} オブジェクトの可変なバージョンです。

@geindex bytearray (組み込みクラス)
@anchor{library/stdtypes bytearray}@anchor{344}
@deffn {クラス} bytearray (source=b'@w{'})

@deffnx {クラス} bytearray (source, encoding, errors='strict')

bytearray に専用のリテラル構文はないので、コンストラクタを使って作成します:


@itemize *

@item 
空のインスタンスを作る: @code{bytearray()}

@item 
指定された長さの0で埋められたインスタンスを作る: @code{bytearray(10)}

@item 
整数の iterable から: @code{bytearray(range(20))}

@item 
既存のバイナリデータからバッファプロトコルを通してコピーする: @code{bytearray(b'Hi!')}
@end itemize

bytearray オブジェクトは可変なので、 @ref{25c3,,bytes と bytearray の操作} で解説されている bytes オブジェクトと共通の操作に加えて、 @ref{25c2,,mutable} シーケンス操作もサポートしています。

@ref{1e9b,,bytearray} ビルトイン関数も参照してください。

16 進数で 2 桁の数は正確に 1 バイトに相当するため、16 進整はバイナリデータを表現する形式として広く使われています。 従って、 bytearray 型にはその形式でデータを読み取るための追加のクラスメソッドがあります。

@geindex fromhex() (bytearray のクラスメソッド)
@anchor{library/stdtypes bytearray fromhex}@anchor{191}
@deffn {メソッド} classmethod fromhex (string, /)

この @ref{344,,bytearray} のクラスメソッドは、与えられた文字列オブジェクトをデコードして bytearray オブジェクトを返します。それぞれのバイトを 16 進数 2 桁で表現した文字列を指定しなければなりません。ASCII 空白文字は無視されます。

@example
>>> bytearray.fromhex('2Ef0 F1f2  ')
bytearray(b'.\xf0\xf1\xf2')
@end example


バージョン 3.7 で変更: @ref{191,,bytearray.fromhex()} は文字列にある空白だけでなく、 ASCII の空白文字全てをスキップするようになりました。



バージョン 3.14 で変更: @ref{191,,bytearray.fromhex()} now accepts ASCII @ref{192,,bytes} and
@ref{193,,bytes-like objects} as input.

@end deffn

bytearray オブジェクトをその 16 進表記に変換するための、反対向きの変換関数があります。

@geindex hex() (bytearray のメソッド)
@anchor{library/stdtypes bytearray hex}@anchor{f66}
@deffn {メソッド} hex (*, bytes_per_sep=1)

@deffnx {メソッド} hex (sep, bytes_per_sep=1)

インスタンス内の 1 バイトにつき 2 つの 16 進数を含む、文字列オブジェクトを返します。

@example
>>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'
@end example


Added in version 3.5.



バージョン 3.8 で変更: @ref{f65,,bytes.hex()} と同様に、 @ref{f66,,bytearray.hex()} が、16進数出力の各バイトを分割するセパレータを挿入するためのオプションパラメータ `sep' と `bytes_per_sep' をサポートするようになりました。

@end deffn

@geindex resize() (bytearray のメソッド)
@anchor{library/stdtypes bytearray resize}@anchor{18ac}
@deffn {メソッド} resize (size, /)

Resize the @ref{344,,bytearray} to contain `size' bytes. `size' must be
greater than or equal to 0.

If the @ref{344,,bytearray} needs to shrink, bytes beyond `size' are truncated.

If the @ref{344,,bytearray} needs to grow, all new bytes, those beyond `size',
will be set to null bytes.

This is equivalent to:

@example
>>> def resize(ba, size):
...     if len(ba) > size:
...         del ba[size:]
...     else:
...         ba += b'\0' * (size - len(ba))
@end example

例:

@example
>>> shrink = bytearray(b'abc')
>>> shrink.resize(1)
>>> (shrink, len(shrink))
(bytearray(b'a'), 1)
>>> grow = bytearray(b'abc')
>>> grow.resize(5)
>>> (grow, len(grow))
(bytearray(b'abc\x00\x00'), 5)
@end example


Added in version 3.14.

@end deffn
@end deffn

bytearray オブジェクトは整数のシーケンス (リストのようなもの) なので、 bytearray オブジェクト `b' について、 @code{b[0]} は整数になり、 @code{b[0:1]} は長さ 1 の bytearray オブジェクトになります。(これは、文字列においてインデックス指定もスライスも長さ 1 の文字列を返すのと対照的です。)

bytearray オブジェクトの表記はバイトのリテラル形式 (@code{bytearray(b'...')}) を使用します。これは @code{bytearray([46, 46, 46])} などの形式よりも便利な事が多いためです。
bytearray オブジェクトはいつでも @code{list(b)} で整数のリストに変換できます。

@node bytes と bytearray の操作,printf 形式での bytes の書式化,bytearray オブジェクト,バイナリシーケンス型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytes-and-bytearray-operations}@anchor{2661}@anchor{library/stdtypes bytes-methods}@anchor{25c3}
@subsubsection bytes と bytearray の操作


@geindex bytes;メソッド
@geindex bytearray;メソッド

bytes と bytearray は両方共 @ref{2607,,一般のシーケンス操作} をサポートしています。また、両方とも @ref{193,,bytes-like object} をサポートしている任意のオブジェクトを対象に操作することもできます。この柔軟性により bytes と bytearray を自由に混ぜてもエラーを起こすことなく扱うことができます。ただし、操作の結果のオブジェクトはその操作の順序に依存することになります。

@cartouche
@quotation 注釈 
文字列のメソッドが引数として bytes を受け付けないのと同様、bytes オブジェクトと bytearray オブジェクトのメソッドは引数として文字列を受け付けません。例えば、以下のように書かなければなりません:

@example
a = "abc"
b = a.replace("a", "f")
@end example

および:

@example
a = b"abc"
b = a.replace(b"a", b"f")
@end example
@end quotation
@end cartouche

いくつかの bytes と bytearray の操作は ASCII と互換性のあるバイナリフォーマットが使われていると仮定していますので、フォーマットの不明なバイナリデータに対して使うことは避けるべきです。こうした制約については以下で説明します。

@cartouche
@quotation 注釈 
これらの ASCII ベースの演算を使って ASCII ベースではないバイナリデータを操作すると、データを破壊する恐れがあります。
@end quotation
@end cartouche

以下の bytes および bytearray オブジェクトのメソッドは、任意のバイナリデータに対して使用できます。

@geindex count() (bytes のメソッド)
@geindex count() (bytearray のメソッド)
@anchor{library/stdtypes bytes count}@anchor{1982}
@deffn {メソッド} bytes.count (sub[, start[, end]])
@anchor{library/stdtypes bytearray count}@anchor{1794}
@deffnx {メソッド} bytearray.count (sub[, start[, end]])

[`start', `end'] の範囲に、部分シーケンス `sub' が重複せず出現する回数を返します。オプション引数 `start' および `end' はスライス表記と同じように解釈されます。

検索対象の部分シーケンスは、任意の @ref{193,,bytes-like object} または  0 から 255 の範囲の整数にできます。

`sub' が空の場合は、文字と文字の間にある空のスライスの数、すなわちbytesオブジェクトの長さに1を加えたものを返します。


バージョン 3.3 で変更: 部分シーケンスとして 0 から 255 の範囲の整数も受け取れるようになりました。

@end deffn

@geindex removeprefix() (bytes のメソッド)
@geindex removeprefix() (bytearray のメソッド)
@anchor{library/stdtypes bytes removeprefix}@anchor{2662}
@deffn {メソッド} bytes.removeprefix (prefix, /)
@anchor{library/stdtypes bytearray removeprefix}@anchor{2663}
@deffnx {メソッド} bytearray.removeprefix (prefix, /)

バリナリーデータが文字列 `prefix' で始まる場合、  @code{bytes[len(prefix):]} を返します。それ以外の場合、元のバイナリーデータのコピーを返します:

@example
>>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'
@end example

`prefix' は、任意の @ref{193,,bytes-like object} にできます。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche


Added in version 3.9.

@end deffn

@geindex removesuffix() (bytes のメソッド)
@geindex removesuffix() (bytearray のメソッド)
@anchor{library/stdtypes bytes removesuffix}@anchor{2664}
@deffn {メソッド} bytes.removesuffix (suffix, /)
@anchor{library/stdtypes bytearray removesuffix}@anchor{2665}
@deffnx {メソッド} bytearray.removesuffix (suffix, /)

バイナリーデータが文字列 `suffix' で終わり、 `suffix' が空でない場合、 @code{bytes[:-len(suffix)]} を返します。それ以外の場合、元のバイナリーデータのコピーを返します:

@example
>>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'
@end example

`suffix' は、任意の @ref{193,,bytes-like object} にできます。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche


Added in version 3.9.

@end deffn

@geindex decode() (bytes のメソッド)
@geindex decode() (bytearray のメソッド)
@anchor{library/stdtypes bytes decode}@anchor{ad3}
@deffn {メソッド} bytes.decode (encoding='utf-8', errors='strict')
@anchor{library/stdtypes bytearray decode}@anchor{2666}
@deffnx {メソッド} bytearray.decode (encoding='utf-8', errors='strict')

@ref{169,,str} にデコードされたbytesを返します。

`encoding' のデフォルト値は @code{'utf-8'} です; 指定可能な値については @ref{fb8,,標準エンコーディング} を参照してください。

`errors' はデコーディングエラーをどのように取り扱うかを制御します。 @code{'strict'} (デフォルト) では @ref{462,,UnicodeError} 例外が送出されます。そのほかに指定可能な値は @code{'ignore'}, @code{'replace'} と、そして @ref{16b4,,codecs.register_error()} で登録された名前です。詳しくは @ref{1b6f,,エラーハンドラ} を参照してください。

パフォーマンス上の理由から、 `errors' の値の妥当性は、デコーディングエラーが実際に発生するか、 @ref{508,,Python 開発モード} が有効になっているか、もしくは @ref{509,,デバッグビルド} が使われていない限りチェックされません。

@cartouche
@quotation 注釈 
引数 `encoding' を @ref{169,,str} に渡すと @ref{193,,bytes-like object} を直接デコードすることができます。つまり、一時的な @code{bytes} や @code{bytearray} オブジェクトを作成する必要はありません。
@end quotation
@end cartouche


バージョン 3.1 で変更: キーワード引数のサポートが追加されました。



バージョン 3.9 で変更: `errors' 引数の値は @ref{508,,Python 開発モード} と @ref{509,,デバッグモード} でチェックされるようになりました。

@end deffn

@geindex endswith() (bytes のメソッド)
@geindex endswith() (bytearray のメソッド)
@anchor{library/stdtypes bytes endswith}@anchor{2624}
@deffn {メソッド} bytes.endswith (suffix[, start[, end]])
@anchor{library/stdtypes bytearray endswith}@anchor{15bc}
@deffnx {メソッド} bytearray.endswith (suffix[, start[, end]])

バイナリデータが指定された `suffix' で終わる場合は @code{True} を、そうでなければ @code{False} を返します。 `suffix' は見つけたい複数の接尾語のタプルでも構いません。オプションの `start' が指定されている場合、その位置から判定を開始します。オプションの `end' が指定されている場合、その位置で比較を終了します。

検索対象の接尾語 (複数も可) は、任意の @ref{193,,bytes-like object} にできます。
@end deffn

@geindex find() (bytes のメソッド)
@geindex find() (bytearray のメソッド)
@anchor{library/stdtypes bytes find}@anchor{1bd4}
@deffn {メソッド} bytes.find (sub[, start[, end]])
@anchor{library/stdtypes bytearray find}@anchor{15bd}
@deffnx {メソッド} bytearray.find (sub[, start[, end]])

スライス @code{s[start:end]} に部分シーケンス `sub' が含まれる場合、データ中のその `sub' の最小のインデックスを返します。オプション引数 `start' および `end' はスライス表記と同様に解釈されます。 `sub' が見つからなかった場合、 @code{-1} を返します。

検索対象の部分シーケンスは、任意の @ref{193,,bytes-like object} または  0 から 255 の範囲の整数にできます。

@cartouche
@quotation 注釈 
@ref{1bd4,,find()} メソッドは、 `sub' の位置を知りたいときにのみ使うべきです。 `sub' が部分文字列 (訳注: おそらく原文の誤り、正しくは部分シーケンス) であるかどうかのみを調べるには、 @ref{34b,,in} 演算子を使ってください:

@example
>>> b'Py' in b'Python'
True
@end example
@end quotation
@end cartouche


バージョン 3.3 で変更: 部分シーケンスとして 0 から 255 の範囲の整数も受け取れるようになりました。

@end deffn

@geindex index() (bytes のメソッド)
@geindex index() (bytearray のメソッド)
@anchor{library/stdtypes bytes index}@anchor{2621}
@deffn {メソッド} bytes.index (sub[, start[, end]])
@anchor{library/stdtypes bytearray index}@anchor{1795}
@deffnx {メソッド} bytearray.index (sub[, start[, end]])

@ref{1bd4,,find()} と同様ですが、部分シーケンスが見つからなかった場合 @ref{2ec,,ValueError} を送出します。

検索対象の部分シーケンスは、任意の @ref{193,,bytes-like object} または  0 から 255 の範囲の整数にできます。


バージョン 3.3 で変更: 部分シーケンスとして 0 から 255 の範囲の整数も受け取れるようになりました。

@end deffn

@geindex join() (bytes のメソッド)
@geindex join() (bytearray のメソッド)
@anchor{library/stdtypes bytes join}@anchor{260a}
@deffn {メソッド} bytes.join (iterable, /)
@anchor{library/stdtypes bytearray join}@anchor{2667}
@deffnx {メソッド} bytearray.join (iterable, /)

`iterable' 中のバイナリデータを結合した bytes または bytearray オブジェクトを返します。 `iterable' に @ref{169,,str} オブジェクトなど @ref{193,,bytes-like objects} ではない値が含まれている場合、 @ref{198,,TypeError} が送出されます。なお要素間のセパレータは、このメソッドを提供する bytes または bytearray オブジェクトとなります。
@end deffn

@geindex maketrans() (bytes の静的メソッド)
@geindex maketrans() (bytearray の静的メソッド)
@anchor{library/stdtypes bytes maketrans}@anchor{148c}
@deffn {メソッド} static bytes.maketrans (from, to, /)
@anchor{library/stdtypes bytearray maketrans}@anchor{148d}
@deffnx {メソッド} static bytearray.maketrans (from, to, /)

この静的メソッドは、 @ref{264d,,bytes.translate()} に渡すのに適した変換テーブルを返します。このテーブルは、 `from' 中の各バイトを `to' の同じ位置にあるバイトにマッピングします。 `from' と `to' は両方とも同じ長さの @ref{193,,bytes-like objects} でなければなりません。


Added in version 3.1.

@end deffn

@geindex partition() (bytes のメソッド)
@geindex partition() (bytearray のメソッド)
@anchor{library/stdtypes bytes partition}@anchor{2629}
@deffn {メソッド} bytes.partition (sep, /)
@anchor{library/stdtypes bytearray partition}@anchor{2668}
@deffnx {メソッド} bytearray.partition (sep, /)

区切り `sep' が最初に出現する位置でシーケンスを分割し、 3 要素のタプルを返します。タプルの内容は、区切りの前の部分、その区切りオブジェクトまたはその bytearray 型のコピー、そして区切りの後ろの部分です。もし区切りが見つからなければ、タプルには元のシーケンスのコピーと、その後ろに二つの空の bytes または bytearray オブジェクトが入ります。

検索する区切りとしては、任意の @ref{193,,bytes-like object} を指定できます。
@end deffn

@geindex replace() (bytes のメソッド)
@geindex replace() (bytearray のメソッド)
@anchor{library/stdtypes bytes replace}@anchor{2625}
@deffn {メソッド} bytes.replace (old, new, count=-1, /)
@anchor{library/stdtypes bytearray replace}@anchor{2669}
@deffnx {メソッド} bytearray.replace (old, new, count=-1, /)

部分シーケンス `old' を全て `new' に置換したシーケンスを返します。オプション引数 `count' が与えられている場合、先頭から `count' 個の `old' だけを置換します。

検索する部分シーケンスおよび置換後の部分シーケンスとしては、任意の @ref{193,,bytes-like object} を指定できます。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex rfind() (bytes のメソッド)
@geindex rfind() (bytearray のメソッド)
@anchor{library/stdtypes bytes rfind}@anchor{1bd5}
@deffn {メソッド} bytes.rfind (sub[, start[, end]])
@anchor{library/stdtypes bytearray rfind}@anchor{15be}
@deffnx {メソッド} bytearray.rfind (sub[, start[, end]])

シーケンス中の領域 @code{s[start:end]} に `sub' が含まれる場合、その最大のインデックスを返します。オプション引数 `start' および `end' はスライス表記と同様に解釈されます。 `sub' が見つからなかった場合 @code{-1}  を返します。

検索対象の部分シーケンスは、任意の @ref{193,,bytes-like object} または  0 から 255 の範囲の整数にできます。


バージョン 3.3 で変更: 部分シーケンスとして 0 から 255 の範囲の整数も受け取れるようになりました。

@end deffn

@geindex rindex() (bytes のメソッド)
@geindex rindex() (bytearray のメソッド)
@anchor{library/stdtypes bytes rindex}@anchor{2622}
@deffn {メソッド} bytes.rindex (sub[, start[, end]])
@anchor{library/stdtypes bytearray rindex}@anchor{1796}
@deffnx {メソッド} bytearray.rindex (sub[, start[, end]])

@ref{1bd5,,rfind()} と同様ですが、部分シーケンス `sub' が見つからなかった場合 @ref{2ec,,ValueError} を送出します。

検索対象の部分シーケンスは、任意の @ref{193,,bytes-like object} または  0 から 255 の範囲の整数にできます。


バージョン 3.3 で変更: 部分シーケンスとして 0 から 255 の範囲の整数も受け取れるようになりました。

@end deffn

@geindex rpartition() (bytes のメソッド)
@geindex rpartition() (bytearray のメソッド)
@anchor{library/stdtypes bytes rpartition}@anchor{262a}
@deffn {メソッド} bytes.rpartition (sep, /)
@anchor{library/stdtypes bytearray rpartition}@anchor{266a}
@deffnx {メソッド} bytearray.rpartition (sep, /)

区切り `sep' が最後に出現する位置でシーケンスを分割し、 3 要素のタプルを返します。タプルの内容は、区切りの前の部分、その区切りオブジェクトまたはその bytearray 型のコピー、そして区切りの後ろの部分です。もし区切れなければ、タプルには二つの空の bytes または bytearray オブジェクトと、その後ろに元のシーケンスのコピーが入ります。

検索する区切りとしては、任意の @ref{193,,bytes-like object} を指定できます。
@end deffn

@geindex startswith() (bytes のメソッド)
@geindex startswith() (bytearray のメソッド)
@anchor{library/stdtypes bytes startswith}@anchor{2623}
@deffn {メソッド} bytes.startswith (prefix[, start[, end]])
@anchor{library/stdtypes bytearray startswith}@anchor{15bb}
@deffnx {メソッド} bytearray.startswith (prefix[, start[, end]])

バイナリデータが指定された `prefix' で始まる場合は @code{True} を、そうでなければ @code{False} を返します。 `prefix' は見つけたい複数の接頭語のタプルでも構いません。オプションの `start' が指定されている場合、その位置から判定を開始します。オプションの `end' が指定されている場合、その位置で比較を終了します。

検索対象の接頭語 (複数も可) は、任意の @ref{193,,bytes-like object} にできます。
@end deffn

@geindex translate() (bytes のメソッド)
@geindex translate() (bytearray のメソッド)
@anchor{library/stdtypes bytes translate}@anchor{264d}
@deffn {メソッド} bytes.translate (table, /, delete=b'@w{'})
@anchor{library/stdtypes bytearray translate}@anchor{1513}
@deffnx {メソッド} bytearray.translate (table, /, delete=b'@w{'})

オプション引数 `delete' に現れるすべてのバイトを除去し、残ったバイトを与えられた変換テーブルに従ってマップした、バイト列やバイト配列オブジェクトのコピーを返します。変換テーブルは長さ 256 のバイト列オブジェクトでなければなりません。

変換テーブルの作成に、 @ref{148c,,bytes.maketrans()} メソッドを使うこともできます。

文字を削除するだけの変換には、 `table' 引数を @code{None} に設定してください:

@example
>>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
@end example


バージョン 3.6 で変更: `delete' はキーワード引数として指定可能になりました。

@end deffn

以下の bytes および bytearray オブジェクトのメソッドは、 ASCII と互換性のあるバイナリフォーマットが使われていると仮定していますが、適切な引数を指定すれば任意のバイナリデータに使用できます。なお、このセクションで紹介する bytearray のメソッドはすべてインプレースで動作 `せず' 、新しいオブジェクトを生成します。

@geindex center() (bytes のメソッド)
@geindex center() (bytearray のメソッド)
@anchor{library/stdtypes bytes center}@anchor{2646}
@deffn {メソッド} bytes.center (width, fillbyte=b' ', /)
@anchor{library/stdtypes bytearray center}@anchor{266b}
@deffnx {メソッド} bytearray.center (width, fillbyte=b' ', /)

長さ `width' の中央寄せされたシーケンスのコピーを返します。パディングには `fillbyte' で指定された値 (デフォルトでは ASCII スペース) が使われます。 @ref{192,,bytes} オブジェクトの場合、 `width' が @code{len(s)} 以下なら元のシーケンスが返されます。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex ljust() (bytes のメソッド)
@geindex ljust() (bytearray のメソッド)
@anchor{library/stdtypes bytes ljust}@anchor{2644}
@deffn {メソッド} bytes.ljust (width, fillbyte=b' ', /)
@anchor{library/stdtypes bytearray ljust}@anchor{266c}
@deffnx {メソッド} bytearray.ljust (width, fillbyte=b' ', /)

長さ `width' の左寄せされたシーケンスのコピーを返します。パディングには `fillbyte' で指定された値 (デフォルトでは ASCII スペース) が使われます。 @ref{192,,bytes} オブジェクトの場合、 `width' が @code{len(s)} 以下なら元のシーケンスが返されます。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex lstrip() (bytes のメソッド)
@geindex lstrip() (bytearray のメソッド)
@anchor{library/stdtypes bytes lstrip}@anchor{264a}
@deffn {メソッド} bytes.lstrip (bytes=None, /)
@anchor{library/stdtypes bytearray lstrip}@anchor{266d}
@deffnx {メソッド} bytearray.lstrip (bytes=None, /)

Return a copy of the sequence with specified leading bytes removed.  The
`bytes' argument is a binary sequence specifying the set of byte values to
be removed.  If omitted or @code{None}, the `bytes' argument defaults
to removing ASCII whitespace.  The `bytes' argument is not a prefix;
rather, all combinations of its values are stripped:

@example
>>> b'   spacious   '.lstrip()
b'spacious   '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'
@end example

削除したいバイト値のバイナリシーケンスには、 @ref{193,,bytes-like object} を指定することができます。バイナリシーケンスで指定した文字の集合全てではなく、指定した文字列そのものを接頭辞として削除するメソッドについては、 @ref{2662,,removeprefix()} を参照してください。使用例:

@example
>>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'
@end example

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex rjust() (bytes のメソッド)
@geindex rjust() (bytearray のメソッド)
@anchor{library/stdtypes bytes rjust}@anchor{2645}
@deffn {メソッド} bytes.rjust (width, fillbyte=b' ', /)
@anchor{library/stdtypes bytearray rjust}@anchor{266e}
@deffnx {メソッド} bytearray.rjust (width, fillbyte=b' ', /)

長さ `width' の右寄せされたシーケンスのコピーを返します。パディングには `fillbyte' で指定された値 (デフォルトでは ASCII スペース) が使われます。 @ref{192,,bytes} オブジェクトの場合、 `width' が @code{len(s)} 以下なら元のシーケンスが返されます。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex rsplit() (bytes のメソッド)
@geindex rsplit() (bytearray のメソッド)
@anchor{library/stdtypes bytes rsplit}@anchor{2627}
@deffn {メソッド} bytes.rsplit (sep=None, maxsplit=-1)
@anchor{library/stdtypes bytearray rsplit}@anchor{1799}
@deffnx {メソッド} bytearray.rsplit (sep=None, maxsplit=-1)

`sep' を区切りとして、同じ型の部分シーケンスに分割します。 `maxsplit' が与えられた場合、シーケンスの `右端' から最大 `maxsplit' 回だけ分割を行います。 `sep' が指定されていないか @code{None} のとき、 ASCII 空白文字の組み合わせで作られる部分シーケンスすべてが区切りとなります。右から分割していくことを除けば、 @ref{1799,,rsplit()} は後ほど詳しく述べる @ref{1798,,split()} と同様に振る舞います。
@end deffn

@geindex rstrip() (bytes のメソッド)
@geindex rstrip() (bytearray のメソッド)
@anchor{library/stdtypes bytes rstrip}@anchor{264b}
@deffn {メソッド} bytes.rstrip (bytes=None, /)
@anchor{library/stdtypes bytearray rstrip}@anchor{266f}
@deffnx {メソッド} bytearray.rstrip (bytes=None, /)

Return a copy of the sequence with specified trailing bytes removed.  The
`bytes' argument is a binary sequence specifying the set of byte values to
be removed.  If omitted or @code{None}, the `bytes' argument defaults to
removing ASCII whitespace.  The `bytes' argument is not a suffix; rather,
all combinations of its values are stripped:

@example
>>> b'   spacious   '.rstrip()
b'   spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'
@end example

削除したいバイト値のバイナリシーケンスには、 @ref{193,,bytes-like object} を指定することができます。バイナリシーケンスで指定した文字の集合全てではなく、指定した文字列そのものを接尾辞として削除するメソッドについては、 @ref{2664,,removesuffix()} を参照してください。使用例:

@example
>>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'
@end example

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex split() (bytes のメソッド)
@geindex split() (bytearray のメソッド)
@anchor{library/stdtypes bytes split}@anchor{2626}
@deffn {メソッド} bytes.split (sep=None, maxsplit=-1)
@anchor{library/stdtypes bytearray split}@anchor{1798}
@deffnx {メソッド} bytearray.split (sep=None, maxsplit=-1)

`sep' を区切りとして、同じ型の部分シーケンスに分割します。 `maxsplit' が与えられ、かつ負の数でない場合、シーケンスの `左端' から最大 `maxsplit' 回だけ分割を行います (したがって結果のリストの要素数は最大で @code{maxsplit+1} になります)。 `maxsplit' が指定されていないか @code{-1} のとき、分割の回数に制限はありません (可能なだけ分割されます)。

`sep' が与えられた場合、連続した区切り用バイト値はまとめられず、空の部分シーケンスを区切っていると判断されます(例えば @code{b'1,,2'.split(b',')} は @code{[b'1', b'@w{'}, b'2']} を返します)。引数 `sep' は複数バイトのシーケンスを1つの区切り文字にもできます。空のシーケンスを分割すると、分割するオブジェクトの型によって @code{[b'@w{'}]} または @code{[bytearray(b'@w{'})]} が返ります。引数 `sep' には、あらゆる @ref{193,,bytes-like object} を指定できます。

例えば:

@example
>>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'@w{'}, b'3', b'@w{'}]
>>> b'1<>2<>3<4'.split(b'<>')
[b'1', b'2', b'3<4']
@end example

`sep' が指定されていないか @code{None} の場合、異なる分割アルゴリズムが適用されます。連続する ASCII 空白文字はひとつの区切りとみなされ、またシーケンスの先頭や末尾に空白があっても、結果の最初や最後に空のシーケンスは含まれません。したがって区切りを指定せずに空のシーケンスや ASCII 空白文字だけのシーケンスを分割すると、 @code{[]} が返されます。

例えば:

@example
>>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b'   1   2   3   '.split()
[b'1', b'2', b'3']
@end example
@end deffn

@geindex strip() (bytes のメソッド)
@geindex strip() (bytearray のメソッド)
@anchor{library/stdtypes bytes strip}@anchor{2649}
@deffn {メソッド} bytes.strip (bytes=None, /)
@anchor{library/stdtypes bytearray strip}@anchor{2670}
@deffnx {メソッド} bytearray.strip (bytes=None, /)

Return a copy of the sequence with specified leading and trailing bytes
removed. The `bytes' argument is a binary sequence specifying the set of
byte values to be removed.  If omitted or @code{None}, the `bytes'
argument defaults to removing ASCII whitespace. The `bytes' argument is
not a prefix or suffix; rather, all combinations of its values are
stripped:

@example
>>> b'   spacious   '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'
@end example

除去対象のバイト値を含むバイナリシーケンスには、任意の @ref{193,,bytes-like object} を指定できます。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

以下の bytes および bytearray オブジェクトのメソッドは、 ASCII と互換性のあるバイナリフォーマットが使われていると仮定しており、任意のバイナリデータに対して使用すべきではありません。なお、このセクションで紹介する bytearray のメソッドはすべてインプレースで動作 `せず' 、新しいオブジェクトを生成します。

@geindex capitalize() (bytes のメソッド)
@geindex capitalize() (bytearray のメソッド)
@anchor{library/stdtypes bytes capitalize}@anchor{263f}
@deffn {メソッド} bytes.capitalize ()
@anchor{library/stdtypes bytearray capitalize}@anchor{2671}
@deffnx {メソッド} bytearray.capitalize ()

各バイトを ASCII 文字と解釈して、最初のバイトを大文字にし、残りを小文字にしたシーケンスのコピーを返します。 ASCII 文字と解釈できないバイト値は、変更されません。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex expandtabs() (bytes のメソッド)
@geindex expandtabs() (bytearray のメソッド)
@anchor{library/stdtypes bytes expandtabs}@anchor{2648}
@deffn {メソッド} bytes.expandtabs (tabsize=8)
@anchor{library/stdtypes bytearray expandtabs}@anchor{2672}
@deffnx {メソッド} bytearray.expandtabs (tabsize=8)

桁 (column) 位置と指定されたタブ幅 (tab size) に応じて、全ての ASCII タブ文字を 1 つ以上の ASCII スペース文字に置換したシーケンスのコピーを返します。ここで `tabsize' バイトごとの桁位置をタブ位置とします (デフォルト値である 8 の場合、タブ位置は 0 桁目、 8 桁目、 16 桁目、と続いていきます)。シーケンスを展開するにあたって、まず現桁位置をゼロに設定し、シーケンスを 1 バイトずつ調べていきます。もしバイト値が ASCII タブ文字 (@code{b'\t'}) であれば、現桁位置が次のタブ位置と一致するまで 1 つ以上の ASCII スペース文字を結果のシーケンスに挿入していきます（ASCII タブ文字自体はコピーしません）。もしバイト値が ASCII 改行文字 (@code{b'\n'} もしくは @code{b'\r'}) であれば、そのままコピーした上で現桁位置を 0 にリセットします。その他のバイト値については変更せずにコピーし、そのバイト値の表示のされ方（訳注: 全角、半角など）に関わらず現桁位置を 1 つ増加させます:

@example
>>> b'01\t012\t0123\t01234'.expandtabs()
b'01      012     0123    01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01  012 0123    01234'
@end example

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex isalnum() (bytes のメソッド)
@geindex isalnum() (bytearray のメソッド)
@anchor{library/stdtypes bytes isalnum}@anchor{2632}
@deffn {メソッド} bytes.isalnum ()
@anchor{library/stdtypes bytearray isalnum}@anchor{2673}
@deffnx {メソッド} bytearray.isalnum ()

シーケンスが空でなく、かつ全てのバイト値が ASCII 文字のアルファベットまたは数字である場合は @code{True} を、そうでなければ @code{False} を返します。ここでの ASCII 文字のアルファベットとはシーケンス @code{b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。 ASCII 文字の数字とは @code{b'0123456789'} に含まれるバイト値です。

例えば:

@example
>>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False
@end example
@end deffn

@geindex isalpha() (bytes のメソッド)
@geindex isalpha() (bytearray のメソッド)
@anchor{library/stdtypes bytes isalpha}@anchor{262c}
@deffn {メソッド} bytes.isalpha ()
@anchor{library/stdtypes bytearray isalpha}@anchor{2674}
@deffnx {メソッド} bytearray.isalpha ()

シーケンスが空でなく、かつ全てのバイト値が ASCII 文字のアルファベットである場合は @code{True} を、そうでなければ @code{False} を返します。ここでの ASCII 文字のアルファベットとはシーケンス @code{b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。

例えば:

@example
>>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False
@end example
@end deffn

@geindex isascii() (bytes のメソッド)
@geindex isascii() (bytearray のメソッド)
@anchor{library/stdtypes bytes isascii}@anchor{2675}
@deffn {メソッド} bytes.isascii ()
@anchor{library/stdtypes bytearray isascii}@anchor{2676}
@deffnx {メソッド} bytearray.isascii ()

シーケンスが空であるか、シーケンスの全てのバイトが ASCII である場合に @code{True} を、それ以外の場合に @code{False} を返します。
ASCII バイトは 0-0x7F の範囲にあります。


Added in version 3.7.

@end deffn

@geindex isdigit() (bytes のメソッド)
@geindex isdigit() (bytearray のメソッド)
@anchor{library/stdtypes bytes isdigit}@anchor{262f}
@deffn {メソッド} bytes.isdigit ()
@anchor{library/stdtypes bytearray isdigit}@anchor{2677}
@deffnx {メソッド} bytearray.isdigit ()

シーケンスが空でなく、かつ全てのバイト値が ASCII 文字の数字である場合は @code{True} を、そうでなければ @code{False} を返します。ここでの ASCII 文字の数字とは @code{b'0123456789'} に含まれるバイト値です。

例えば:

@example
>>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False
@end example
@end deffn

@geindex islower() (bytes のメソッド)
@geindex islower() (bytearray のメソッド)
@anchor{library/stdtypes bytes islower}@anchor{2634}
@deffn {メソッド} bytes.islower ()
@anchor{library/stdtypes bytearray islower}@anchor{2678}
@deffnx {メソッド} bytearray.islower ()

シーケンス中に小文字アルファベットの ASCII 文字が一つ以上あり、かつ大文字アルファベットの ASCII 文字が一つも無い場合に @code{True} を返します。そうでなければ @code{False} を返します。

例えば:

@example
>>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False
@end example

ここでの小文字の ASCII 文字とは @code{b'abcdefghijklmnopqrstuvwxyz'} に含まれるバイト値です。また大文字の ASCII 文字とは @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。
@end deffn

@geindex isspace() (bytes のメソッド)
@geindex isspace() (bytearray のメソッド)
@anchor{library/stdtypes bytes isspace}@anchor{263a}
@deffn {メソッド} bytes.isspace ()
@anchor{library/stdtypes bytearray isspace}@anchor{2679}
@deffnx {メソッド} bytearray.isspace ()

シーケンスが空でなく、かつ全てのバイト値が ASCII 空白文字である場合は @code{True} を、そうでなければ @code{False} を返します。ここでの ASCII 空白文字とはシーケンス @code{b' \t\n\r\x0b\f'} に含まれるバイト値です (半角スペース、タブ、ラインフィード、キャリッジリターン、垂直タブ、フォームフィード) 。
@end deffn

@geindex istitle() (bytes のメソッド)
@geindex istitle() (bytearray のメソッド)
@anchor{library/stdtypes bytes istitle}@anchor{2638}
@deffn {メソッド} bytes.istitle ()
@anchor{library/stdtypes bytearray istitle}@anchor{267a}
@deffnx {メソッド} bytearray.istitle ()

シーケンスが空でなく、かつ ASCII のタイトルケース文字列になっている場合は @code{True} を、そうでなければ @code{False} を返します。「タイトルケース文字列」の定義については @ref{2641,,bytes.title()} を参照してください。

例えば:

@example
>>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False
@end example
@end deffn

@geindex isupper() (bytes のメソッド)
@geindex isupper() (bytearray のメソッド)
@anchor{library/stdtypes bytes isupper}@anchor{2636}
@deffn {メソッド} bytes.isupper ()
@anchor{library/stdtypes bytearray isupper}@anchor{267b}
@deffnx {メソッド} bytearray.isupper ()

シーケンス中に大文字アルファベットの ASCII 文字が一つ以上あり、かつ小文字アルファベットの ASCII 文字が一つも無い場合に @code{True} を返します。そうでなければ @code{False} を返します。

例えば:

@example
>>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False
@end example

ここでの小文字の ASCII 文字とは @code{b'abcdefghijklmnopqrstuvwxyz'} に含まれるバイト値です。また大文字の ASCII 文字とは @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。
@end deffn

@geindex lower() (bytes のメソッド)
@geindex lower() (bytearray のメソッド)
@anchor{library/stdtypes bytes lower}@anchor{263b}
@deffn {メソッド} bytes.lower ()
@anchor{library/stdtypes bytearray lower}@anchor{267c}
@deffnx {メソッド} bytearray.lower ()

シーケンスに含まれる大文字アルファベットの ASCII 文字を全て小文字アルファベットに変換したシーケンスのコピーを返します。

例えば:

@example
>>> b'Hello World'.lower()
b'hello world'
@end example

ここでの小文字の ASCII 文字とは @code{b'abcdefghijklmnopqrstuvwxyz'} に含まれるバイト値です。また大文字の ASCII 文字とは @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex universal newlines;bytes.splitlines メソッド
@geindex universal newlines;bytearray.splitlines メソッド

@geindex splitlines() (bytes のメソッド)
@geindex splitlines() (bytearray のメソッド)
@anchor{library/stdtypes bytes splitlines}@anchor{2628}
@deffn {メソッド} bytes.splitlines (keepends=False)
@anchor{library/stdtypes bytearray splitlines}@anchor{267d}
@deffnx {メソッド} bytearray.splitlines (keepends=False)

バイナリシーケンスを ASCII の改行コードで分割し、各行をリストにして返します。このメソッドは @ref{f35,,universal newlines} アプローチで行を分割します。 `keepends' 引数に真を与えた場合を除き、改行コードは結果のリストに含まれません。

例えば:

@example
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'@w{'}, b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
@end example

@ref{2626,,split()} とは違って、空シーケンスに対して区切り `sep' を与えて呼び出すと空のリストを返します。またシーケンス末尾に改行コードがある場合、（訳註: その後ろに空行があるとは判断せず）余分な行を生成することはありません:

@example
>>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b'@w{'}], [b'Two lines', b'@w{'}])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])
@end example
@end deffn

@geindex swapcase() (bytes のメソッド)
@geindex swapcase() (bytearray のメソッド)
@anchor{library/stdtypes bytes swapcase}@anchor{2643}
@deffn {メソッド} bytes.swapcase ()
@anchor{library/stdtypes bytearray swapcase}@anchor{267e}
@deffnx {メソッド} bytearray.swapcase ()

シーケンスに含まれる小文字アルファベットの ASCII 文字を全て大文字アルファベットに変換し、さらに大文字アルファベットを同様に小文字アルファベットに変換したシーケンスのコピーを返します。

例えば:

@example
>>> b'Hello World'.swapcase()
b'hELLO wORLD'
@end example

ここでの小文字の ASCII 文字とは @code{b'abcdefghijklmnopqrstuvwxyz'} に含まれるバイト値です。また大文字の ASCII 文字とは @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。

Unlike @ref{2642,,str.swapcase()}, it is always the case that
@code{bin.swapcase().swapcase() == bin} for the binary versions. Case
conversions are symmetrical in ASCII, even though that is not generally
true for arbitrary Unicode code points.

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex title() (bytes のメソッド)
@geindex title() (bytearray のメソッド)
@anchor{library/stdtypes bytes title}@anchor{2641}
@deffn {メソッド} bytes.title ()
@anchor{library/stdtypes bytearray title}@anchor{267f}
@deffnx {メソッド} bytearray.title ()

タイトルケース化したバイナリシーケンスを返します。具体的には、各単語が大文字アルファベットの ASCII 文字で始まり、かつ残りの文字が小文字アルファベットになっているシーケンスが返ります。大文字小文字の区別が無いバイト値については変更されずそのままになります。

例えば:

@example
>>> b'Hello world'.title()
b'Hello World'
@end example

ここでの小文字の ASCII 文字とは @code{b'abcdefghijklmnopqrstuvwxyz'} に含まれるバイト値です。また大文字の ASCII 文字とは @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。その他のバイト値については、大文字小文字の区別はありません。

このアルゴリズムは、連続した文字の集まりという、言語から独立した単純な単語の定義を使います。この定義は多くの状況ではうまく機能しますが、短縮形や所有格のアポストロフィが単語の境界になってしまい、望みの結果を得られない場合があります:

@example
>>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"
@end example

正規表現を使うことでアポストロフィに対応できます:

@example
>>> import re
>>> def titlecase(s):
...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0:1].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."
@end example

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex upper() (bytes のメソッド)
@geindex upper() (bytearray のメソッド)
@anchor{library/stdtypes bytes upper}@anchor{263d}
@deffn {メソッド} bytes.upper ()
@anchor{library/stdtypes bytearray upper}@anchor{2680}
@deffnx {メソッド} bytearray.upper ()

シーケンスに含まれる小文字アルファベットの ASCII 文字を全て大文字アルファベットに変換したシーケンスのコピーを返します。

例えば:

@example
>>> b'Hello World'.upper()
b'HELLO WORLD'
@end example

ここでの小文字の ASCII 文字とは @code{b'abcdefghijklmnopqrstuvwxyz'} に含まれるバイト値です。また大文字の ASCII 文字とは @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} に含まれるバイト値です。

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@geindex zfill() (bytes のメソッド)
@geindex zfill() (bytearray のメソッド)
@anchor{library/stdtypes bytes zfill}@anchor{2681}
@deffn {メソッド} bytes.zfill (width, /)
@anchor{library/stdtypes bytearray zfill}@anchor{2682}
@deffnx {メソッド} bytearray.zfill (width, /)

長さが `width' になるよう ASCII @code{b'0'} で左詰めしたシーケンスのコピーを返します。先頭が符号接頭辞 (@code{b'+'}/@code{b'-'}) だった場合、 @code{b'0'} は符号の前ではなく `後' に挿入されます。 @ref{192,,bytes} オブジェクトの場合、 `width' が @code{len(seq)} 以下であれば元のシーケンスが返ります。

例えば:

@example
>>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
@end example

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche
@end deffn

@node printf 形式での bytes の書式化,メモリビュー,bytes と bytearray の操作,バイナリシーケンス型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytes-formatting}@anchor{f81}@anchor{library/stdtypes printf-style-bytes-formatting}@anchor{2683}
@subsubsection @code{printf} 形式での bytes の書式化


@geindex 書式化;bytes (%)
@geindex 書式化;bytearray (%)
@geindex 補間;bytes (%)
@geindex 補間;bytearray (%)
@geindex bytes;書式化
@geindex bytearray;書式化
@geindex bytes;補間
@geindex bytearray;補間
@geindex printf 形式の書式化
@geindex sprintf 形式の書式化
@geindex % (パーセント);printf 形式の書式化

@cartouche
@quotation 注釈 
ここで述べる書式化演算には様々な癖があり、よく間違いの元になっています (タプルや辞書を正しく表示できないなど)。もし表示する値がタプルや辞書かもしれない場合、それをタプルに包むようにしてください。
@end quotation
@end cartouche

bytes オブジェクト (@code{bytes}/@code{bytearray}) には固有の操作: @code{%} 演算子 (モジュロ) があります。この演算子は bytes の `書式化' または `補間' 演算子とも呼ばれます。@code{format % values} (`format' は bytes オブジェクト) とすると、`format' 中の @code{%} 変換指定は `values' 中のゼロ個またはそれ以上の要素で置換されます。この動作は C 言語における @code{sprintf()} に似ています。

`format' が単一の引数しか要求しない場合、 `values' はタプルではない単一のオブジェクトで問題ありません。 @footnote{
従って、一個のタプルだけをフォーマット出力したい場合には出力したいタプルを唯一の要素とする単一のタプルを `values' に与えなくてはなりません。
} それ以外の場合、 `values' は書式シーケンス（訳註: 先の例での `format' ）中で指定された項目と正確に同じ数の要素を含むタプルか、単一のマッピング型のオブジェクト (たとえば辞書) でなければなりません。

@geindex () (丸括弧);in printf-style formatting
@geindex * (アスタリスク);in printf-style formatting
@geindex . (ドット);in printf-style formatting

一つの変換指定子は 2 またはそれ以上の文字を含み、その構成要素は以下からなりますが、示した順に出現しなければなりません:


@enumerate 

@item 
指定子の開始を示す文字 @code{'%'} 。

@item 
マップキー (オプション)。丸括弧で囲った文字列からなります (例えば @code{(somename)}) 。

@item 
変換フラグ (オプション)。一部の変換型の結果に影響します。

@item 
最小のフィールド幅 (オプション)。 @code{'*'} (アスタリスク) を指定した場合、実際の文字列幅が `values' タプルの次の要素から読み出されます。タプルには最小フィールド幅やオプションの精度指定の後に変換したいオブジェクトがくるようにします。

@item 
精度 (オプション)。 @code{'.'} (ドット) とその後に続く精度で与えられます。 @code{'*'} (アスタリスク) を指定した場合、精度の桁数は `values' タプルの次の要素から読み出されます。タプルには精度指定の後に変換したい値がくるようにします。

@item 
精度長変換子 (オプション)。

@item 
変換型。
@end enumerate

@code{%} 演算子の右側の引数が辞書の場合 (またはその他のマッピング型の場合) 、 bytes オブジェクト中のフォーマットには、辞書のキーを丸括弧で囲って文字 @code{'%'} の直後に書いたものが含まれていなければ `なりません' 。マップキーは書式化したい値をマッピングから選び出します。例えば:

@example
>>> print(b'%(language)s has %(number)03d quote types.' %
...       @{b'language': b"Python", b"number": 2@})
b'Python has 002 quote types.'
@end example

この場合、 @code{*} 指定子をフォーマットに含めてはいけません (@code{*} 指定子は順番付けされたパラメタのリストが必要だからです)。

変換フラグ文字を以下に示します:

@geindex # (hash);in printf-style formatting
@geindex - (負符号);in printf-style formatting
@geindex + (プラス記号);in printf-style formatting
@geindex 空白;in printf-style formatting


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@item

@code{'#'}

@tab

値の変換に (下で定義されている) "別の形式" を使います。

@item

@code{'0'}

@tab

数値型に対してゼロによるパディングを行います。

@item

@code{'-'}

@tab

変換された値を左寄せにします (@code{'0'} と同時に与えた場合、 @code{'0'} を上書きします) 。

@item

@code{' '}

@tab

(スペース) 符号付きの変換で正の数の場合、前に一つスペースを空けます (そうでない場合は空文字になります) 。

@item

@code{'+'}

@tab

変換の先頭に符号文字 (@code{'+'} または @code{'-'}) を付けます("スペース" フラグを上書きします) 。

@end multitable


精度長変換子(@code{h}, @code{l},または @code{L}) を使うことができますが、 Python では必要ないため無視されます。 -- つまり、例えば @code{%ld} は @code{%d} と等価です。

変換型を以下に示します:


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

変換

@tab

意味

@tab

注釈

@item

@code{'d'}

@tab

符号付き 10 進整数。

@tab

@item

@code{'i'}

@tab

符号付き 10 進整数。

@tab

@item

@code{'o'}

@tab

符号付き 8 進数。

@tab

(1)

@item

@code{'u'}

@tab

旧式の型 -- @code{'d'} と同じです。

@tab

(8)

@item

@code{'x'}

@tab

符号付き 16 進数 (小文字)。

@tab

(2)

@item

@code{'X'}

@tab

符号付き 16 進数 (大文字)。

@tab

(2)

@item

@code{'e'}

@tab

指数表記の浮動小数点数 (小文字)。

@tab

(3)

@item

@code{'E'}

@tab

指数表記の浮動小数点数 (大文字)。

@tab

(3)

@item

@code{'f'}

@tab

10 進浮動小数点数。

@tab

(3)

@item

@code{'F'}

@tab

10 進浮動小数点数。

@tab

(3)

@item

@code{'g'}

@tab

浮動小数点数。指数部が -4 以上または精度以下の場合には小文字指数表記、それ以外の場合には10進表記。

@tab

(4)

@item

@code{'G'}

@tab

浮動小数点数。指数部が -4 以上または精度以下の場合には大文字指数表記、それ以外の場合には10進表記。

@tab

(4)

@item

@code{'c'}

@tab

1 バイト (整数または要素 1 つの @code{bytes}/@code{bytearray} オブジェクトを受理します)

@tab

@item

@code{'b'}

@tab

バイナリシーケンス (@ref{260,,buffer protocol} をサポートするか、 @ref{7fe,,__bytes__()} メソッドがあるオブジェクト)

@tab

(5)

@item

@code{'s'}

@tab

@code{'s'} は @code{'b'} の別名です。Python 2/3 の両方を対象としたコードでのみ使用すべきです。

@tab

(6)

@item

@code{'a'}

@tab

バイナリシーケンス (Python オブジェクトを @code{repr(obj).encode('ascii', 'backslashreplace')} で変換します)。

@tab

(5)

@item

@code{'r'}

@tab

@code{'r'} は @code{'a'} の別名です。Python 2/3 の両方を対象としたコードでのみ使用すべきです。

@tab

(7)

@item

@code{'%'}

@tab

引数を変換せず、返される文字列中では文字 @code{'%'} になります。

@tab

@end multitable


注釈:


@enumerate 

@item 
別の形式を指定（訳注: 変換フラグ @code{#} を使用）すると 8 進数を表す接頭辞 (@code{'0o'}) が最初の数字の前に挿入されます。

@item 
別の形式を指定（訳注: 変換フラグ @code{#} を使用）すると 16 進数を表す接頭辞 @code{'0x'} または @code{'0X'} (使用するフォーマット文字が @code{'x'} か @code{'X'} に依存します) が最初の数字の前に挿入されます。

@item 
この形式にした場合、変換結果には常に小数点が含まれ、それはその後ろに数字が続かない場合にも適用されます。

指定精度は小数点の後の桁数を決定し、そのデフォルトは 6 です。

@item 
この形式にした場合、変換結果には常に小数点が含まれ他の形式とは違って末尾の 0 は取り除かれません。

指定精度は小数点の前後の有効桁数を決定し、そのデフォルトは 6 です。

@item 
精度が @code{N} なら、出力は @code{N} 文字に切り詰められます。

@item 
@code{b'%s'} は非推奨ですが、3.x 系では削除されません。

@item 
@code{b'%r'} は非推奨ですが、3.x 系では削除されません。

@item 
@geindex Python Enhancement Proposals; PEP 237
PEP 237@footnote{https://peps.python.org/pep-0237/} を参照してください。
@end enumerate

@cartouche
@quotation 注釈 
bytearray のこのメソッドはインプレースでは動作 `しません' -- 一切変化が無い場合でも、常に新しいオブジェクトを生成します。
@end quotation
@end cartouche


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 461
PEP 461@footnote{https://peps.python.org/pep-0461/} - bytes と bytearray への % 書式化の追加



Added in version 3.5.


@node メモリビュー,,printf 形式での bytes の書式化,バイナリシーケンス型 --- bytes bytearray memoryview
@anchor{library/stdtypes memory-views}@anchor{2684}@anchor{library/stdtypes typememoryview}@anchor{25d8}
@subsubsection メモリビュー


@ref{165,,memoryview} オブジェクトは、Python コードが @ref{260,,バッファプロトコル} をサポートするオブジェクトの内部データへ、コピーすることなくアクセスすることを可能にします。

@geindex memoryview (組み込みクラス)
@anchor{library/stdtypes memoryview}@anchor{165}
@deffn {クラス} memoryview (object)

@quotation

`object' を参照する @ref{165,,memoryview} を作成します。 `object' はバッファプロトコルをサポートしていなければなりません。バッファプロトコルをサポートする組み込みオブジェクトには、 @ref{192,,bytes} 、 @ref{344,,bytearray} などがあります。

@ref{165,,memoryview} は元となる `object' が扱うメモリーの最小単位を `要素' として扱います。多くの単純なオブジェクト、例えば @ref{192,,bytes} や @ref{344,,bytearray} では、要素は単バイトになりますが、他の @ref{4be,,array.array} 等の型では、要素はより大きくなりえます。

@code{len(view)} はビューの入れ子になったリスト表現である @ref{2685,,tolist} の長さと等しくなります。ビューが @code{view.ndim = 1} を満たす場合はビューの要素数とも等しくなります。


バージョン 3.12 で変更: @code{view.ndim == 0} で @code{len(view)} の場合、1の代わりに @ref{198,,TypeError} を返すようになりました。


@ref{2686,,itemsize} 属性は各要素のバイト数を与えます。

@ref{165,,memoryview} はスライスおよびインデックス指定で内容を取得できます。一次元のスライスは部分ビューになります:

@example
>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'
@end example

もしメモリビューの @ref{124c,,format} が @ref{db,,struct} モジュールによって定義されているネイティブのフォーマット指定子であれば、整数または整数のタプルでのインデックス指定により適切な型の `要素1つ' を得ることができます。一次元のメモリビューでは、整数または整数 1 つのタプルでインデックス指定できます。多次元のメモリビューでは、その次元数を `ndim' としたとき、ちょうど `ndim' 個の整数からなるタプルでインデックス指定できます。ゼロ次元のメモリビューでは、空のタプルでインデックス指定できます。

@ref{124c,,format} が単バイト単位ではない例を示します:

@example
>>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m[0]
-11111111
>>> m[-1]
44444444
>>> m[::2].tolist()
[-11111111, -33333333]
@end example

メモリビューの参照しているオブジェクトが書き込み可能であれば、一次元スライスでの代入が可能です。ただしサイズの変更はできません:

@example
>>> data = bytearray(b'abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = ord(b'z')
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = b'123'
>>> data
bytearray(b'z123fg')
>>> v[2:3] = b'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different structures
>>> v[2:6] = b'spam'
>>> data
bytearray(b'z1spam')
@end example

'B', 'b', 'c' いずれかのフォーマットの @ref{824,,ハッシュ可能} な (読み出し専用の) 型の1次元メモリビューもまた、ハッシュ可能です。ハッシュは @code{hash(m) == hash(m.tobytes())} として定義されています:

@example
>>> v = memoryview(b'abcefg')
>>> hash(v) == hash(b'abcefg')
True
>>> hash(v[2:4]) == hash(b'ce')
True
>>> hash(v[::-2]) == hash(b'abcefg'[::-2])
True
@end example


バージョン 3.3 で変更: 1 次元のメモリビューがスライス可能になりました。 'B', 'b', 'c' いずれかのフォーマットの 1 次元のメモリビューが @ref{824,,ハッシュ可能} になりました。



バージョン 3.4 で変更: memoryview は自動的に @ref{13dc,,collections.abc.Sequence} へ登録されるようになりました。



バージョン 3.5 で変更: メモリビューは整数のタプルでインデックス指定できるようになりました。



バージョン 3.14 で変更: memoryview is now a @ref{1a1,,generic type}.


@ref{165,,memoryview} にはいくつかのメソッドがあります:

@geindex __eq__() (memoryview のメソッド)
@anchor{library/stdtypes memoryview __eq__}@anchor{2687}
@deffn {メソッド} __eq__ (exporter)

memoryview と 
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/} エクスポーターは、 shape が同じで、 @ref{db,,struct} のフォーマットで解釈したときの値が同じ場合に同値になります。

@ref{2685,,tolist()} がサポートしている @ref{db,,struct} フォーマットの一部では、 @code{v.tolist() == w.tolist()} が成り立つときに @code{v} == @code{w} になります:

@example
>>> import array
>>> a = array.array('I', [1, 2, 3, 4, 5])
>>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
>>> c = array.array('b', [5, 3, 1])
>>> x = memoryview(a)
>>> y = memoryview(b)
>>> x == a == y == b
True
>>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
True
>>> z = y[::-2]
>>> z == c
True
>>> z.tolist() == c.tolist()
True
@end example

どちらかの書式文字列が @ref{db,,struct} モジュールにサポートされていなければ、 (書式文字列とバッファの内容が同一でも) オブジェクトは常に等しくないものとして比較されます:

@example
>>> from ctypes import BigEndianStructure, c_long
>>> class BEPoint(BigEndianStructure):
...     _fields_ = [("x", c_long), ("y", c_long)]
...
>>> point = BEPoint(100, 200)
>>> a = memoryview(point)
>>> b = memoryview(point)
>>> a == point
False
>>> a == b
False
@end example

浮動小数点数の場合と同様 memoryview オブジェクトに対する @code{v is w} は @code{v == w} を意味 `しない' ことに注意してください。


バージョン 3.3 で変更: 以前のバージョンは、要素フォーマットと論理的な配列構造を無視して生のメモリを比較していました。

@end deffn

@geindex tobytes() (memoryview のメソッド)
@anchor{library/stdtypes memoryview tobytes}@anchor{2688}
@deffn {メソッド} tobytes (order='C')

バッファ中のデータをバイト文字列として返します。これはメモリビューに対して @ref{192,,bytes} コンストラクタを呼び出すのと同等です。

@example
>>> m = memoryview(b"abc")
>>> m.tobytes()
b'abc'
>>> bytes(m)
b'abc'
@end example

連続でない配列については、結果はすべての要素がバイトに変換されたものを含むフラットなリスト表現に等しくなります。 @ref{2688,,tobytes()} は、 @ref{db,,struct} モジュール文法にないものを含むすべての書式文字列をサポートします。


Added in version 3.8: `order' は @{'C', 'F', 'A'@} のいずれかを取ることができます。 `order' が 'C' か 'F' の場合、元の配列は C または Fortran のデータ並びにそれぞれ変換されます。連続したデータに対するビューの場合、 'A' は物理メモリ上のデータの正確なコピーを返します。特に、メモリ上における Fortran のデータ並びは保存されます。不連続なデータに対するビューの場合、データはまず C のデータ並びに変換されます。 `order=None' は `order='C'' と同じです。

@end deffn

@geindex hex() (memoryview のメソッド)
@anchor{library/stdtypes memoryview hex}@anchor{f67}
@deffn {メソッド} hex (*, bytes_per_sep=1)

@deffnx {メソッド} hex (sep, bytes_per_sep=1)

バッファ中の各バイトを 2 つの 16 進数で表した文字列を返します:

@example
>>> m = memoryview(b"abc")
>>> m.hex()
'616263'
@end example


Added in version 3.5.



バージョン 3.8 で変更: @ref{f65,,bytes.hex()} と同様に、 @ref{f67,,memoryview.hex()} は、16進数出力のバイト文字列を分割するセパレータを挿入するためのオプションパラメータ `sep' と `bytes_per_sep' をサポートするようになりました。

@end deffn

@geindex tolist() (memoryview のメソッド)
@anchor{library/stdtypes memoryview tolist}@anchor{2685}
@deffn {メソッド} tolist ()

バッファ中のデータを要素のリストとして返します。

@example
>>> memoryview(b'abc').tolist()
[97, 98, 99]
>>> import array
>>> a = array.array('d', [1.1, 2.2, 3.3])
>>> m = memoryview(a)
>>> m.tolist()
[1.1, 2.2, 3.3]
@end example


バージョン 3.3 で変更: @ref{2685,,tolist()} が @ref{db,,struct} モジュール文法に含まれるすべての単一文字の native フォーマットと多次元の表現をサポートするようになりました。

@end deffn

@geindex toreadonly() (memoryview のメソッド)
@anchor{library/stdtypes memoryview toreadonly}@anchor{2689}
@deffn {メソッド} toreadonly ()

読み込み専用のメモリビューオブジェクトを返します。元のメモリビューオブジェクトは変更されません。

@example
>>> m = memoryview(bytearray(b'abc'))
>>> mm = m.toreadonly()
>>> mm.tolist()
[97, 98, 99]
>>> mm[0] = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot modify read-only memory
>>> m[0] = 43
>>> mm.tolist()
[43, 98, 99]
@end example


Added in version 3.8.

@end deffn

@geindex release() (memoryview のメソッド)
@anchor{library/stdtypes memoryview release}@anchor{13d6}
@deffn {メソッド} release ()

memoryview オブジェクトによって晒されている、元になるバッファを解放します。多くのオブジェクトはビューに支配されているときに特殊なふるまいをします (例えば、 @ref{344,,bytearray} は大きさの変更を一時的に禁止します)。ですから、release() を呼び出すことは、これらの制約をできるだけ早く取り除く (そしてぶら下がったリソースをすべて解放する) のに便利です。

After this method has been called, any further operation on the view
raises a @ref{2ec,,ValueError} (except @ref{13d6,,release()} itself which can
be called multiple times):

@example
>>> m = memoryview(b'abc')
>>> m.release()
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object
@end example

コンテキストマネージャプロトコルは、 @code{with} 文を使って同様の効果を得るのに使えます:

@example
>>> with memoryview(b'abc') as m:
...     m[0]
...
97
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object
@end example


Added in version 3.2.

@end deffn

@geindex cast() (memoryview のメソッド)
@anchor{library/stdtypes memoryview cast}@anchor{124d}
@deffn {メソッド} cast (format, /)

@deffnx {メソッド} cast (format, shape, /)

memoryview を新しいフォーマットか shape にキャストします。 `shape' はデフォルトで @code{[byte_length//new_itemsize]} で、 1次元配列になります。戻り値は memoryview ですが、バッファー自体はコピーされません。サポートされている変換は 1次元配列 -> C言語型の連続配列 と C言語型の連続配列 -> 1次元配列 です（参考: @ref{124e,,contiguous}）。

キャスト後のフォーマットは単一要素のネイティブフォーマットに限定され、 @ref{db,,struct} の文法で指定します。利用可能なフォーマットのひとつはバイトフォーマット  ('B', 'b' または 'c') です。キャスト後のバイト長は元の長さと同じでなければなりません。全てのフォーマットのバイト長は、オペレーティングシステムに依存することに注意してください。

1次元 long から 1次元 unsigned byte へのキャスト:

@example
>>> import array
>>> a = array.array('l', [1,2,3])
>>> x = memoryview(a)
>>> x.format
'l'
>>> x.itemsize
8
>>> len(x)
3
>>> x.nbytes
24
>>> y = x.cast('B')
>>> y.format
'B'
>>> y.itemsize
1
>>> len(y)
24
>>> y.nbytes
24
@end example

1次元 unsigned byte から 1次元 char へのキャスト:

@example
>>> b = bytearray(b'zyz')
>>> x = memoryview(b)
>>> x[0] = b'a'
Traceback (most recent call last):
  ...
TypeError: memoryview: invalid type for format 'B'
>>> y = x.cast('c')
>>> y[0] = b'a'
>>> b
bytearray(b'ayz')
@end example

1次元 byte から 3次元 int へ、そして 1次元 signed char へのキャスト:

@example
>>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>> y.format
'i'
>>> y.itemsize
4
>>> len(y)
2
>>> y.nbytes
48
>>> z = y.cast('b')
>>> z.format
'b'
>>> z.itemsize
1
>>> len(z)
48
>>> z.nbytes
48
@end example

1次元 unsigned long から 2次元 unsigned long へのキャスト:

@example
>>> buf = struct.pack("L"*6, *list(range(6)))
>>> x = memoryview(buf)
>>> y = x.cast('L', shape=[2,3])
>>> len(y)
2
>>> y.nbytes
48
>>> y.tolist()
[[0, 1, 2], [3, 4, 5]]
@end example


Added in version 3.3.



バージョン 3.5 で変更: 単バイトのビューへキャストする場合、キャスト元のフォーマットについて制約は無くなりました。

@end deffn

@geindex count() (memoryview のメソッド)
@anchor{library/stdtypes memoryview count}@anchor{18f8}
@deffn {メソッド} count (value, /)

Count the number of occurrences of `value'.


Added in version 3.14.

@end deffn
@end quotation

@geindex index() (memoryview のメソッド)
@anchor{library/stdtypes memoryview index}@anchor{18f7}
@deffn {メソッド} index (value, start=0, stop=sys.maxsize, /)

@quotation

Return the index of the first occurrence of `value' (at or after
index `start' and before index `stop').

Raises a @ref{2ec,,ValueError} if `value' cannot be found.


Added in version 3.14.

@end quotation

読み出し専用の属性もいくつか使えます:

@geindex obj (memoryview の属性)
@anchor{library/stdtypes memoryview obj}@anchor{268a}
@deffn {の属性} obj

memoryview が参照しているオブジェクト:

@example
>>> b  = bytearray(b'xyz')
>>> m = memoryview(b)
>>> m.obj is b
True
@end example


Added in version 3.3.

@end deffn

@geindex nbytes (memoryview の属性)
@anchor{library/stdtypes memoryview nbytes}@anchor{268b}
@deffn {の属性} nbytes

@code{nbytes == product(shape) * itemsize == len(m.tobytes())}. その配列が連続表現において利用するスペースです。これは @code{len(m)} と一致するとは限りません:

@example
>>> import array
>>> a = array.array('i', [1,2,3,4,5])
>>> m = memoryview(a)
>>> len(m)
5
>>> m.nbytes
20
>>> y = m[::2]
>>> len(y)
3
>>> y.nbytes
12
>>> len(y.tobytes())
12
@end example

多次元配列:

@example
>>> import struct
>>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
>>> x = memoryview(buf)
>>> y = x.cast('d', shape=[3,4])
>>> y.tolist()
[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
>>> len(y)
3
>>> y.nbytes
96
@end example


Added in version 3.3.

@end deffn

@geindex readonly (memoryview の属性)
@anchor{library/stdtypes memoryview readonly}@anchor{268c}
@deffn {の属性} readonly

メモリが読み出し専用かどうかを示す真偽値です。
@end deffn

@geindex format (memoryview の属性)
@anchor{library/stdtypes memoryview format}@anchor{124c}
@deffn {の属性} format

ビューの中の各要素に対する (@ref{db,,struct} モジュールスタイルの) フォーマットを含む文字列。 memoryview は、任意のフォーマット文字列を使ってエクスポーターから作成することができます。しかし、いくつかのメソッド(例えば @ref{2685,,tolist()}) はネイティブの単一要素フォーマットに制限されます。


バージョン 3.3 で変更: フォーマット @code{'B'} は struct モジュール構文で扱われるようになりました。これは @code{memoryview(b'abc')[0] == b'abc'[0] == 97} ということを意味します。

@end deffn

@geindex itemsize (memoryview の属性)
@anchor{library/stdtypes memoryview itemsize}@anchor{2686}
@deffn {の属性} itemsize

memoryview の各要素のバイト単位の大きさ:

@example
>>> import array, struct
>>> m = memoryview(array.array('H', [32000, 32001, 32002]))
>>> m.itemsize
2
>>> m[0]
32000
>>> struct.calcsize('H') == m.itemsize
True
@end example
@end deffn

@geindex ndim (memoryview の属性)
@anchor{library/stdtypes memoryview ndim}@anchor{1250}
@deffn {の属性} ndim

メモリが表す多次元配列が何次元かを示す整数です。
@end deffn

@geindex shape (memoryview の属性)
@anchor{library/stdtypes memoryview shape}@anchor{1251}
@deffn {の属性} shape

メモリが表している N 次元配列の形状を表す、長さ @ref{1250,,ndim} の整数のタプルです。


バージョン 3.3 で変更: ndim = 0 の場合は @code{None} ではなく空のタプルとなるよう変更されました。

@end deffn

@geindex strides (memoryview の属性)
@anchor{library/stdtypes memoryview strides}@anchor{1252}
@deffn {の属性} strides

配列のそれぞれの次元に対して、それぞれの要素にアクセスするのに必要なバイト数を表す、長さ @ref{1250,,ndim} の整数のタプルです。


バージョン 3.3 で変更: ndim = 0 の場合は @code{None} ではなく空のタプルとなるよう変更されました。

@end deffn

@geindex suboffsets (memoryview の属性)
@anchor{library/stdtypes memoryview suboffsets}@anchor{1253}
@deffn {の属性} suboffsets

PILスタイルの配列の内部で利用している値。この値はただの情報として公開されています。
@end deffn

@geindex c_contiguous (memoryview の属性)
@anchor{library/stdtypes memoryview c_contiguous}@anchor{268d}
@deffn {の属性} c_contiguous

メモリーが C 形式の順序で連続しているかどうかを示す真偽値（参考: @ref{124e,,contiguous} ）。


Added in version 3.3.

@end deffn

@geindex f_contiguous (memoryview の属性)
@anchor{library/stdtypes memoryview f_contiguous}@anchor{268e}
@deffn {の属性} f_contiguous

メモリーがFortran形式の順序で連続しているかどうかを示す真偽値（参考: @ref{124e,,contiguous} ）。


Added in version 3.3.

@end deffn

@geindex contiguous (memoryview の属性)
@anchor{library/stdtypes memoryview contiguous}@anchor{268f}
@deffn {の属性} contiguous

メモリーが連続しているかどうかを示す真偽値（参考: @ref{124e,,contiguous} ）。


Added in version 3.3.

@end deffn
@end deffn
@end deffn

@node set（集合）型 --- set frozenset,マッピング型 --- dict,バイナリシーケンス型 --- bytes bytearray memoryview,組み込み型
@anchor{library/stdtypes set-types-set-frozenset}@anchor{2690}@anchor{library/stdtypes types-set}@anchor{2031}
@subsection set（集合）型 --- @code{set}, @code{frozenset}


@geindex object;集合

`set' オブジェクトは、固有の @ref{824,,hashable} オブジェクトの順序なしコレクションです。通常の用途には、帰属テスト、シーケンスからの重複除去、積集合、和集合、差集合、対称差 (排他的論理和) のような数学的演算の計算が含まれます。(他のコンテナについては組み込みの @ref{183,,dict}, @ref{24d,,list}, @ref{614,,tuple} クラスや @ref{1e,,collections} モジュールを参照してください。)

集合は、他のコレクションと同様、 @code{x in set}, @code{len(set)}, @code{for x in set} をサポートします。コレクションには順序がないので、集合は挿入の順序や要素の位置を記録しません。従って、集合はインデクシング、スライシング、その他のシーケンス的な振舞いをサポートしません。

There are currently two built-in set types, @ref{184,,set} and @ref{7f2,,frozenset}.
The @ref{184,,set} type is mutable --- the contents can be changed using methods
like @ref{233e,,add()} and @ref{2691,,remove()}.
Since it is mutable, it has no hash value and cannot be used as
either a dictionary key or as an element of another set.
The @ref{7f2,,frozenset} type is immutable and @ref{824,,hashable} ---
its contents cannot be altered after it is created;
it can therefore be used as a dictionary key or as an element of another set.

空でない @ref{184,,set} (@ref{7f2,,frozenset} ではない) は、@ref{184,,set} コンストラクタに加え、要素を波括弧中にカンマで区切って列挙することでも生成できます。例: @code{@{'jack', 'sjoerd'@}}。

どちらのクラスのコンストラクタも同様に働きます:

@geindex set (組み込みクラス)
@geindex frozenset (組み込みクラス)
@anchor{library/stdtypes set}@anchor{184}
@deffn {クラス} set (iterable=(), /)
@anchor{library/stdtypes frozenset}@anchor{7f2}
@deffnx {クラス} frozenset (iterable=(), /)

`iterable' から要素を取り込んだ、新しい @ref{184,,set} もしくは @ref{7f2,,frozenset} オブジェクトを返します。 集合の要素は @ref{824,,ハッシュ可能} なものでなくてはなりません。集合の集合を表現するためには、内側の集合は @ref{7f2,,frozenset} オブジェクトでなくてはなりません。`iterable' が指定されない場合、新しい空の集合が返されます。
@end deffn

集合はいくつかの方法で生成できます:


@itemize *

@item 
波括弧内にカンマ区切りで要素を列挙する: @code{@{'jack', 'sjoerd'@}}

@item 
集合内包表記を使う: @code{@{c for c in 'abracadabra' if c not in 'abc'@}}

@item 
型コンストラクタを使う: @code{set()}, @code{set('foobar')}, @code{set(['a', 'b', 'foo'])}
@end itemize

@ref{184,,set} および @ref{7f2,,frozenset} のインスタンスは以下の操作を提供します:


@deffn {Describe} len(s)

集合 `s' の要素数 (`s' の濃度) を返します。
@end deffn


@deffn {Describe} x in s

`x' が `s' のメンバーに含まれるか判定します。
@end deffn


@deffn {Describe} x not in s

`x' が `s' のメンバーに含まれていないことを判定します。
@end deffn

@geindex isdisjoint() (frozenset のメソッド)
@geindex isdisjoint() (set のメソッド)
@anchor{library/stdtypes frozenset isdisjoint}@anchor{2692}
@deffn {メソッド} frozenset.isdisjoint (other, /)
@anchor{library/stdtypes set isdisjoint}@anchor{2693}
@deffnx {メソッド} set.isdisjoint (other, /)

集合が `other' と共通の要素を持たないとき、@code{True} を返します。集合はそれらの積集合が空集合となるときのみ、互いに素 (disjoint) となります。
@end deffn

@geindex issubset() (frozenset のメソッド)
@geindex issubset() (set のメソッド)
@anchor{library/stdtypes frozenset issubset}@anchor{2694}
@deffn {メソッド} frozenset.issubset (other, /)
@anchor{library/stdtypes set issubset}@anchor{2695}
@deffnx {メソッド} set.issubset (other, /)
@end deffn


@deffn {Describe} set <= other

set の全ての要素が `other' に含まれるか判定します。
@end deffn


@deffn {Describe} set < other

set が `other' の真部分集合であるかを判定します。つまり、 @code{set <= other and set != other} と等価です。
@end deffn

@geindex issuperset() (frozenset のメソッド)
@geindex issuperset() (set のメソッド)
@anchor{library/stdtypes frozenset issuperset}@anchor{2696}
@deffn {メソッド} frozenset.issuperset (other, /)
@anchor{library/stdtypes set issuperset}@anchor{1b85}
@deffnx {メソッド} set.issuperset (other, /)
@end deffn


@deffn {Describe} set >= other

`other' の全ての要素が set に含まれるか判定します。
@end deffn


@deffn {Describe} set > other

set が `other' の真上位集合であるかを判定します。つまり、 @code{set >= other and set != other} と等価です。
@end deffn

@geindex union() (frozenset のメソッド)
@geindex union() (set のメソッド)
@anchor{library/stdtypes frozenset union}@anchor{169c}
@deffn {メソッド} frozenset.union (*others)
@anchor{library/stdtypes set union}@anchor{2697}
@deffnx {メソッド} set.union (*others)
@end deffn


@deffn {Describe} set | other | ...

set と全ての other の要素からなる新しい集合を返します。
@end deffn

@geindex intersection() (frozenset のメソッド)
@geindex intersection() (set のメソッド)
@anchor{library/stdtypes frozenset intersection}@anchor{169d}
@deffn {メソッド} frozenset.intersection (*others)
@anchor{library/stdtypes set intersection}@anchor{1b84}
@deffnx {メソッド} set.intersection (*others)
@end deffn


@deffn {Describe} set & other & ...

set と全ての other に共通する要素を持つ、新しい集合を返します。
@end deffn

@geindex difference() (frozenset のメソッド)
@geindex difference() (set のメソッド)
@anchor{library/stdtypes frozenset difference}@anchor{2698}
@deffn {メソッド} frozenset.difference (*others)
@anchor{library/stdtypes set difference}@anchor{2699}
@deffnx {メソッド} set.difference (*others)
@end deffn


@deffn {Describe} set @w{-} other @w{-} ...

set に含まれて、かつ、全ての other に含まれない要素を持つ、新しい集合を返します。
@end deffn

@geindex symmetric_difference() (frozenset のメソッド)
@geindex symmetric_difference() (set のメソッド)
@anchor{library/stdtypes frozenset symmetric_difference}@anchor{269a}
@deffn {メソッド} frozenset.symmetric_difference (other, /)
@anchor{library/stdtypes set symmetric_difference}@anchor{269b}
@deffnx {メソッド} set.symmetric_difference (other, /)
@end deffn


@deffn {Describe} set ^ other

set と `other' のいずれか一方だけに含まれる要素を持つ新しい集合を返します。
@end deffn

@geindex copy() (frozenset のメソッド)
@geindex copy() (set のメソッド)
@anchor{library/stdtypes frozenset copy}@anchor{269c}
@deffn {メソッド} frozenset.copy ()
@anchor{library/stdtypes set copy}@anchor{269d}
@deffnx {メソッド} set.copy ()

集合の浅いコピーを返します。
@end deffn

Note, the non-operator versions of @ref{169c,,union()},
@ref{169d,,intersection()}, @ref{2698,,difference()}, @ref{269a,,symmetric_difference()}, @ref{2694,,issubset()}, and
@ref{2696,,issuperset()} methods will accept any iterable as an argument.  In
contrast, their operator based counterparts require their arguments to be
sets.  This precludes error-prone constructions like @code{set('abc') & 'cbs'}
in favor of the more readable @code{set('abc').intersection('cbs')}.

@ref{184,,set} と @ref{7f2,,frozenset} のどちらも、集合同士の比較をサポートします。二つの集合は、それぞれの集合の要素全てが他方にも含まれている (互いに他方の部分集合である) とき、かつそのときに限り等しいです。一方の集合が他方の集合の真部分集合である (部分集合であるが等しくない) とき、かつそのときに限り一方の集合は他方の集合より小さいです。一方の集合が他方の集合の真上位集合である (上位集合であるが等しくない) とき、かつそのときに限り一方の集合は他方の集合より大きいです。

@ref{184,,set} のインスタンスは、 @ref{7f2,,frozenset} のインスタンスと、要素に基づいて比較されます。例えば、 @code{set('abc') == frozenset('abc')} や @code{set('abc') in set([frozenset('abc')])} は @code{True} を返します。

部分集合と等価性の比較は全順序付けを行う関数へと一般化することはできません。例えば、互いに素である二つの非空集合は、等しくなく、他方の部分集合でもありませんから、以下の `すべて' に @code{False} を返します: @code{a<b}, @code{a==b}, そして @code{a>b}.

集合は半順序（部分集合関係）しか定義しないので、集合のリストにおける @ref{dc8,,list.sort()} メソッドの出力は未定義です。

集合の要素は、辞書のキーのように、 @ref{824,,ハッシュ可能} でなければなりません。

@ref{184,,set} インスタンスと @ref{7f2,,frozenset} インスタンスを取り混ぜての二項演算は、第一被演算子の型を返します。例えば: @code{frozenset('ab') | set('bc')} は @ref{7f2,,frozenset} インスタンスを返します。

以下の表に挙げる演算は @ref{184,,set} に適用されますが、@ref{7f2,,frozenset} のイミュータブルなインスタンスには適用されません:

@geindex update() (set のメソッド)
@anchor{library/stdtypes set update}@anchor{269e}
@deffn {メソッド} set.update (*others)
@end deffn


@deffn {Describe} set |= other | ...

全ての other の要素を追加し、 set を更新します。
@end deffn

@geindex intersection_update() (set のメソッド)
@anchor{library/stdtypes set intersection_update}@anchor{169e}
@deffn {メソッド} set.intersection_update (*others)
@end deffn


@deffn {Describe} set &= other & ...

元の set と全ての other に共通する要素だけを残して set を更新します。
@end deffn

@geindex difference_update() (set のメソッド)
@anchor{library/stdtypes set difference_update}@anchor{269f}
@deffn {メソッド} set.difference_update (*others)
@end deffn


@deffn {Describe} set @w{-}= other | ...

`other' に含まれる要素を取り除き、 set を更新します。
@end deffn

@geindex symmetric_difference_update() (set のメソッド)
@anchor{library/stdtypes set symmetric_difference_update}@anchor{169f}
@deffn {メソッド} set.symmetric_difference_update (other, /)
@end deffn


@deffn {Describe} set ^= other

どちらかにのみ含まれて、共通には持たない要素のみで set を更新します。
@end deffn

@geindex add() (set のメソッド)
@anchor{library/stdtypes set add}@anchor{233e}
@deffn {メソッド} set.add (elem, /)

要素 `elem' を set に追加します。
@end deffn

@geindex remove() (set のメソッド)
@anchor{library/stdtypes set remove}@anchor{2691}
@deffn {メソッド} set.remove (elem, /)

要素 `elem' を set から取り除きます。`elem' が set に含まれていなければ @ref{5e7,,KeyError} を送出します。
@end deffn

@geindex discard() (set のメソッド)
@anchor{library/stdtypes set discard}@anchor{26a0}
@deffn {メソッド} set.discard (elem, /)

要素 `elem' が set に含まれていれば、取り除きます。
@end deffn

@geindex pop() (set のメソッド)
@anchor{library/stdtypes set pop}@anchor{26a1}
@deffn {メソッド} set.pop ()

`s' から任意の要素を取り除き、それを返します。集合が空の場合、 @ref{5e7,,KeyError} を送出します
@end deffn

@geindex clear() (set のメソッド)
@anchor{library/stdtypes set clear}@anchor{26a2}
@deffn {メソッド} set.clear ()

set の全ての要素を取り除きます。
@end deffn

Note, the non-operator versions of the @ref{269e,,update()},
@ref{169e,,intersection_update()}, @ref{269f,,difference_update()}, and
@ref{169f,,symmetric_difference_update()} methods will accept any iterable as an
argument.

Note, the `elem' argument to the @ref{15d3,,__contains__()},
@ref{2691,,remove()}, and
@ref{26a0,,discard()} methods may be a set.  To support searching for an equivalent
frozenset, a temporary one is created from `elem'.

@node マッピング型 --- dict,コンテキストマネージャ型,set（集合）型 --- set frozenset,組み込み型
@anchor{library/stdtypes mapping-types-dict}@anchor{26a3}@anchor{library/stdtypes typesmapping}@anchor{cbd}
@subsection マッピング型 --- @code{dict}


@geindex object;mapping
@geindex object;dictionary
@geindex 演算;mapping;types
@geindex 演算;dictionary;type
@geindex statement;del
@geindex 組み込み関数;len

@ref{13d3,,マッピング} オブジェクトは、 @ref{824,,ハッシュ可能} な値を任意のオブジェクトに対応付けます。マッピングはミュータブルなオブジェクトです。現在、標準のマッピング型は辞書 (`dictionary') だけです。 (他のコンテナについては組み込みの @ref{24d,,list}, @ref{184,,set}, および @ref{614,,tuple} クラスと、 @ref{1e,,collections} モジュールを参照してください。)

辞書のキーには、 `ほぼ' どんな値も使うことができます。
キーとして使えないのは、 @ref{824,,hashable} (ハッシュ可能) でない値、すなわちリストや辞書のようなミュータブルな型 (内包する値ではなくオブジェクト自体が同一であるかによって比較が行われるような型)です。
比較した際に等しいとみなされる値 (例えば @code{1} と @code{1.0} と @code{True}) は、どれを使っても同じエントリーに関連付けられます。

@geindex dict (組み込みクラス)
@anchor{library/stdtypes dict}@anchor{183}
@deffn {クラス} dict (**kwargs)

@deffnx {クラス} dict (mapping, /, **kwargs)

@deffnx {クラス} dict (iterable, /, **kwargs)

オプションの位置引数と空の可能性もあるキーワード引数の集合により初期化された新しい辞書を返します。

辞書はいくつかの方法で生成できます:


@itemize *

@item 
波括弧内にカンマ区切りで @code{key: value} 対を列挙する: @code{@{'jack': 4098, 'sjoerd': 4127@}} あるいは @code{@{4098: 'jack', 4127: 'sjoerd'@}}

@item 
辞書内包表記を使う: @code{@{@}}, @code{@{x: x ** 2 for x in range(10)@}}

@item 
型コンストラクタを使う: @code{dict()}, @code{dict([('foo', 100), ('bar', 200)])}, @code{dict(foo=100, bar=200)}
@end itemize

If no positional argument is given, an empty dictionary is created.
If a positional argument is given and it defines a @code{keys()} method, a
dictionary is created by calling @ref{588,,__getitem__()} on the argument with
each returned key from the method.  Otherwise, the positional argument must be an
@ref{12f1,,iterable} object.  Each item in the iterable must itself be an iterable
with exactly two elements.  The first element of each item becomes a key in the
new dictionary, and the second element the corresponding value.  If a key occurs
more than once, the last value for that key becomes the corresponding value in
the new dictionary.

キーワード引数が与えられた場合、キーワード引数とその値が位置引数から作られた辞書に追加されます。既に存在しているキーが追加された場合、キーワード引数の値は位置引数の値を置き換えます。

Dictionaries compare equal if and only if they have the same @code{(key,
value)} pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise
@ref{198,,TypeError}.  To illustrate dictionary creation and equality,
the following examples all return a dictionary equal to
@code{@{"one": 1, "two": 2, "three": 3@}}:

@example
>>> a = dict(one=1, two=2, three=3)
>>> b = @{'one': 1, 'two': 2, 'three': 3@}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict(@{'three': 3, 'one': 1, 'two': 2@})
>>> f = dict(@{'one': 1, 'three': 3@}, two=2)
>>> a == b == c == d == e == f
True
@end example

最初の例のようにキーワード引数を与える方法では、キーは有効な Python の識別子でなければなりません。それ以外の方法では、辞書のキーとして有効などんなキーでも使えます。

辞書は挿入順序を保存するようになりました。
キーの更新は順序には影響が無いことに注意してください。
いったん削除されてから再度追加されたキーは末尾に挿入されます。:

@example
>>> d = @{"one": 1, "two": 2, "three": 3, "four": 4@}
>>> d
@{'one': 1, 'two': 2, 'three': 3, 'four': 4@}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
@{'one': 42, 'two': 2, 'three': 3, 'four': 4@}
>>> del d["two"]
>>> d["two"] = None
>>> d
@{'one': 42, 'three': 3, 'four': 4, 'two': None@}
@end example


バージョン 3.7 で変更: 辞書の順序が挿入順序であることが保証されるようになりました。この振る舞いは CPython 3.6 の実装詳細でした。


以下は辞書型がサポートする操作です (それゆえ、カスタムのマップ型もこれらの操作をサポートするべきです):


@deffn {Describe} list(d)

辞書 `d' で使われている全てのキーのリストを返します。
@end deffn


@deffn {Describe} len(d)

辞書 `d' の項目数を返します。
@end deffn


@deffn {Describe} d[key]

`d' のキー `key' の項目を返します。マップに `key' が存在しなければ、 @ref{5e7,,KeyError} を送出します。

@geindex __missing__()

If a subclass of dict defines a method @ref{13d5,,__missing__()} and `key'
is not present, the @code{d[key]} operation calls that method with the key `key'
as argument.  The @code{d[key]} operation then returns or raises whatever is
returned or raised by the @code{__missing__(key)} call.
No other operations or methods invoke @ref{13d5,,__missing__()}. If
@ref{13d5,,__missing__()} is not defined, @ref{5e7,,KeyError} is raised.
@ref{13d5,,__missing__()} must be a method; it cannot be an instance variable:

@example
>>> class Counter(dict):
...     def __missing__(self, key):
...         return 0
...
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1
@end example

The example above shows part of the implementation of
@ref{12a3,,collections.Counter}.
A different @code{__missing__()} method is used
by @ref{13d4,,collections.defaultdict}.
@end deffn


@deffn {Describe} d[key] = value

@code{d[key]} に `value' を設定します。
@end deffn


@deffn {Describe} del d[key]

`d' から @code{d[key]} を削除します。マップに `key' が存在しなければ、 @ref{5e7,,KeyError} を送出します。
@end deffn


@deffn {Describe} key in d

`d' がキー `key' を持っていれば @code{True} を、そうでなければ、 @code{False} を返します。
@end deffn


@deffn {Describe} key not in d

@code{not key in d} と等価です。
@end deffn


@deffn {Describe} iter(d)

辞書のキーに渡るイテレータを返します。これは @code{iter(d.keys())} へのショートカットです。
@end deffn

@geindex clear() (dict のメソッド)
@anchor{library/stdtypes dict clear}@anchor{17d6}
@deffn {メソッド} clear ()

辞書の全ての項目を消去します。
@end deffn

@geindex copy() (dict のメソッド)
@anchor{library/stdtypes dict copy}@anchor{dc9}
@deffn {メソッド} copy ()

辞書の浅いコピーを返します。
@end deffn

@geindex fromkeys() (dict のクラスメソッド)
@anchor{library/stdtypes dict fromkeys}@anchor{24e}
@deffn {メソッド} classmethod fromkeys (iterable, value=None, /)

`iterable' からキーを取り、値を `value' に設定した、新しい辞書を作成します。

@ref{24e,,fromkeys()} は新しい辞書を返すクラスメソッドです。
`value' はデフォルトで @code{None} となります。
作られる辞書内のすべての値が同一のインスタンスを指すことになるため、`value' にミュータブルなオブジェクト (例えば空のリスト) を指定しても通常意味はありません。
別々の値を指すようにしたい場合は、代わりに @ref{f7f,,辞書内包表記} を使用してください。
@end deffn

@geindex get() (dict のメソッド)
@anchor{library/stdtypes dict get}@anchor{2034}
@deffn {メソッド} get (key, default=None, /)

`key' が辞書にあれば `key' に対する値を、そうでなければ `default' を返します。 `default' が与えられなかった場合、デフォルトでは @code{None} となります。そのため、このメソッドは @ref{5e7,,KeyError} を送出することはありません。
@end deffn

@geindex items() (dict のメソッド)
@anchor{library/stdtypes dict items}@anchor{9d2}
@deffn {メソッド} items ()

辞書の項目 (@code{(key, value)} 対) の新しいビューを返します。@ref{2618,,ビューオブジェクトのドキュメント} を参照してください。
@end deffn

@geindex keys() (dict のメソッド)
@anchor{library/stdtypes dict keys}@anchor{9d0}
@deffn {メソッド} keys ()

辞書のキーの新しいビューを返します。@ref{2618,,ビューオブジェクトのドキュメント} を参照してください。
@end deffn

@geindex pop() (dict のメソッド)
@anchor{library/stdtypes dict pop}@anchor{5e6}
@deffn {メソッド} pop (key, /)

@deffnx {メソッド} pop (key, default, /)

`key' が辞書に存在すればその値を辞書から消去して返し、そうでなければ `default' を返します。 `default' が与えられず、かつ `key' が辞書に存在しなければ @ref{5e7,,KeyError} を送出します。
@end deffn

@geindex popitem() (dict のメソッド)
@anchor{library/stdtypes dict popitem}@anchor{173f}
@deffn {メソッド} popitem ()

任意の @code{(key, value)} 対を辞書から消去して返します。
対は @abbr{LIFO,後入れ、先出し} の順序で返却されます。

集合のアルゴリズムで使われるのと同じように、 @ref{173f,,popitem()} は辞書に繰り返し適用して消去するのに便利です。辞書が空であれば、 @ref{173f,,popitem()} の呼び出しは @ref{5e7,,KeyError} を送出します。


バージョン 3.7 で変更: LIFO 順序が保証されるようになりました。
以前のバージョンでは、 @ref{173f,,popitem()} は任意の key/value 対を返していました。

@end deffn


@deffn {Describe} reversed(d)

辞書のキーに渡る逆イテレータを返します。これは @code{reversed(d.keys())} へのショートカットです。


Added in version 3.8.

@end deffn

@geindex setdefault() (dict のメソッド)
@anchor{library/stdtypes dict setdefault}@anchor{1285}
@deffn {メソッド} setdefault (key, default=None, /)

もし、 `key' が辞書に存在すれば、その値を返します。そうでなければ、値を `default' として `key' を挿入し、 `default' を返します。 `default' のデフォルトは @code{None} です。
@end deffn

@geindex update() (dict のメソッド)
@anchor{library/stdtypes dict update}@anchor{167e}
@deffn {メソッド} update (**kwargs)

@deffnx {メソッド} update (mapping, /, **kwargs)

@deffnx {メソッド} update (iterable, /, **kwargs)

Update the dictionary with the key/value pairs from `mapping' or `iterable' and `kwargs', overwriting
existing keys.  Return @code{None}.

@ref{167e,,update()} accepts either another object with a @code{keys()} method (in
which case @ref{588,,__getitem__()} is called with every key returned from
the method) or an iterable of key/value pairs (as tuples or other iterables
of length two). If keyword arguments are specified, the dictionary is then
updated with those key/value pairs: @code{d.update(red=1, blue=2)}.
@end deffn

@geindex values() (dict のメソッド)
@anchor{library/stdtypes dict values}@anchor{9d1}
@deffn {メソッド} values ()

辞書の値の新しいビューを返します。@ref{2618,,ビューオブジェクトのドキュメント} を参照してください。

@code{dict.values()} で得られた２つのビューの等しさを比較すると、必ず @code{False} が返ります。
@code{dict.values()} どうしを比較したときも同様です:

@example
>>> d = @{'a': 1@}
>>> d.values() == d.values()
False
@end example
@end deffn


@deffn {Describe} d | other

`d' と `other' のキーと値を統合した新しい辞書を作成します。
`d' と `other' のキーに重複がある場合は、 `other' の方の値が優先されます。


Added in version 3.9.

@end deffn


@deffn {Describe} d |= other

辞書 `d' のキーと値を `other' で更新します。
`other' は @ref{13d3,,マッピング} か、またはキーと値のペアの @ref{12f1,,イテラブル} です。
`d' と `other' のキーに重複がある場合は、 `other' の方の値が優先されます。


Added in version 3.9.

@end deffn

辞書と辞書のビューは @code{reversed()} で順序を逆にすることができます:

@example
>>> d = @{"one": 1, "two": 2, "three": 3, "four": 4@}
>>> d
@{'one': 1, 'two': 2, 'three': 3, 'four': 4@}
>>> list(reversed(d))
['four', 'three', 'two', 'one']
>>> list(reversed(d.values()))
[4, 3, 2, 1]
>>> list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
@end example


バージョン 3.8 で変更: 辞書がリバース可能になりました。

@end deffn


@subsubheading 参考


@ref{183,,dict} の読み出し専用ビューを作るために @ref{698,,types.MappingProxyType} を使うことができます。

@anchor{library/stdtypes thread-safety-dict}@anchor{26a4}
@subsubheading Thread safety for dict objects


Creating a dictionary with the @ref{183,,dict} constructor is atomic when the
argument to it is a @ref{183,,dict} or a @ref{614,,tuple}. When using the
@ref{24e,,dict.fromkeys()} method, dictionary creation is atomic when the
argument is a @ref{183,,dict}, @ref{614,,tuple}, @ref{184,,set} or
@ref{7f2,,frozenset}.

The following operations and functions are @ref{2617,,lock-free} and
@ref{2615,,atomic}.

@example
d[key]       # dict.__getitem__
d.get(key)   # dict.get
key in d     # dict.__contains__
len(d)       # dict.__len__
@end example

All other operations from here on hold the @ref{2616,,per-object lock}.

Writing or removing a single item is safe to call from multiple threads
and will not corrupt the dictionary:

@example
d[key] = value        # write
del d[key]            # delete
d.pop(key)            # remove and return
d.popitem()           # remove and return last item
d.setdefault(key, v)  # insert if missing
@end example

These operations may compare keys using @ref{cf2,,__eq__()}, which can
execute arbitrary Python code. During such comparisons, the dictionary may
be modified by another thread. For built-in types like @ref{169,,str},
@ref{19b,,int}, and @ref{196,,float}, that implement @ref{cf2,,__eq__()} in C,
the underlying lock is not released during comparisons and this is not a
concern.

The following operations return new objects and hold the @ref{2616,,per-object lock}
for the duration of the operation:

@example
d.copy()      # returns a shallow copy of the dictionary
d | other     # merges two dicts into a new dict
d.keys()      # returns a new dict_keys view object
d.values()    # returns a new dict_values view object
d.items()     # returns a new dict_items view object
@end example

The @ref{17d6,,clear()} method holds the lock for its duration. Other
threads cannot observe elements being removed.

The following operations lock both dictionaries. For @ref{167e,,update()}
and @code{|=}, this applies only when the other operand is a @ref{183,,dict}
that uses the standard dict iterator (but not subclasses that override
iteration). For equality comparison, this applies to @ref{183,,dict} and
its subclasses:

@example
d.update(other_dict)  # both locked when other_dict is a dict
d |= other_dict       # both locked when other_dict is a dict
d == other_dict       # both locked for dict and subclasses
@end example

All comparison operations also compare values using @ref{cf2,,__eq__()},
so for non-built-in types the lock may be released during comparison.

@ref{24e,,fromkeys()} locks both the new dictionary and the iterable
when the iterable is exactly a @ref{183,,dict}, @ref{184,,set}, or
@ref{7f2,,frozenset} (not subclasses):

@example
dict.fromkeys(a_dict)      # locks both
dict.fromkeys(a_set)       # locks both
dict.fromkeys(a_frozenset) # locks both
@end example

When updating from a non-dict iterable, only the target dictionary is
locked. The iterable may be concurrently modified by another thread:

@example
d.update(iterable)        # iterable is not a dict: only d locked
d |= iterable             # iterable is not a dict: only d locked
dict.fromkeys(iterable)   # iterable is not a dict/set/frozenset: only result locked
@end example

Operations that involve multiple accesses, as well as iteration, are never
atomic:

@example
# NOT atomic: read-modify-write
d[key] = d[key] + 1

# NOT atomic: check-then-act (TOCTOU)
if key in d:
      del d[key]

# NOT thread-safe: iteration while modifying
for key, value in d.items():
      process(key)  # another thread may modify d
@end example

To avoid time-of-check to time-of-use (TOCTOU) issues, use atomic
operations or handle exceptions:

@example
# Use pop() with default instead of check-then-delete
d.pop(key, None)

# Or handle the exception
try:
      del d[key]
except KeyError:
      pass
@end example

To safely iterate over a dictionary that may be modified by another
thread, iterate over a copy:

@example
# Make a copy to iterate safely
for key, value in d.copy().items():
      process(key)
@end example

Consider external synchronization when sharing @ref{183,,dict} instances
across threads. See @ref{2619,,Python support for free threading} for more information.

@menu
* 辞書ビューオブジェクト:: 

@end menu

@node 辞書ビューオブジェクト,,,マッピング型 --- dict
@anchor{library/stdtypes dict-views}@anchor{2618}@anchor{library/stdtypes dictionary-view-objects}@anchor{26a5}
@subsubsection 辞書ビューオブジェクト


@ref{9d0,,dict.keys()}, @ref{9d1,,dict.values()}, @ref{9d2,,dict.items()} によって返されるオブジェクトは、 `ビューオブジェクト' です。これらは、辞書の項目の動的なビューを提供し、辞書が変更された時、ビューはその変更を反映します。

辞書ビューは、イテレートすることで対応するデータを yield できます。また、帰属判定をサポートします:


@deffn {Describe} len(dictview)

辞書の項目数を返します。
@end deffn


@deffn {Describe} iter(dictview)

辞書のキー、値、または (@code{(key, value)} のタプルとして表される) 項目に渡るイテレータを返します。

キーと値は挿入順序で反復されます。
これにより、 @code{(value, key)} の対の列を @code{pairs = zip(d.values(), d.keys())} のように @ref{1a0,,zip()} で作成できます。
同じリストを作成する他の方法は、 @code{pairs = [(v, k) for (k, v) in d.items()]} です。

辞書の項目の追加や削除中にビューをイテレートすると、 @ref{244,,RuntimeError} を送出したり、すべての項目に渡ってイテレートできなかったりします。


バージョン 3.7 で変更: 辞書の順序が挿入順序であると保証されるようになりました。

@end deffn


@deffn {Describe} x in dictview

`x' が元の辞書のキー、値、または項目 (項目の場合、 `x' は @code{(key, value)} タプルです) にあるとき @code{True} を返します。
@end deffn


@deffn {Describe} reversed(dictview)

辞書のキーもしくは値、項目の順序を逆にしたイテレーターを返します。
戻り値のビューは、挿入された順とは逆の順でイテレートします。


バージョン 3.8 で変更: 辞書のビューがリバース可能になりました。

@end deffn


@deffn {Describe} dictview.mapping

ビューの参照先の辞書をラップする @ref{698,,types.MappingProxyType} オブジェクト を返します。


Added in version 3.10.

@end deffn

キーのビューは要素に重複がなくハッシュ可能 (@ref{824,,hashable}) であるため、集合の特性を持ちます。項目のビューも、 キーと値の対に重複がなく、かつキーがハッシュ可能であるため、集合的な演算を持っています。もし項目の全ての値がハッシュ可能ならば、項目のビューは集合と相互に演算することが可能です。 (値のビューは一般に要素に重複があるため、集合の特性を持つとはみなされません。) 集合の特性を持つビューに対しては、 @ref{26a6,,collections.abc.Set} 抽象基底クラスで定義された全ての演算が利用可能です (たとえば @code{==}, @code{<} や @code{^} など)。 集合演算に対しては、集合はオペランドとして集合しか取ることができないのに対して、これら集合の特性を持つビューはオペランドとして任意のイテラブルを取ることができます。

辞書ビューの使用法の例:

@example
>>> dishes = @{'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500@}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
...
>>> print(n)
504

>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

>>> # set operations
>>> keys & @{'eggs', 'bacon', 'salad'@}
@{'bacon'@}
>>> keys ^ @{'sausage', 'juice'@} == @{'juice', 'sausage', 'bacon', 'spam'@}
True
>>> keys | ['juice', 'juice', 'juice'] == @{'bacon', 'spam', 'juice'@}
True

>>> # get back a read-only proxy for the original dictionary
>>> values.mapping
mappingproxy(@{'bacon': 1, 'spam': 500@})
>>> values.mapping['spam']
500
@end example

@node コンテキストマネージャ型,型アノテーション型 --- ジェネリックエイリアス 、 ユニオン,マッピング型 --- dict,組み込み型
@anchor{library/stdtypes context-manager-types}@anchor{26a7}@anchor{library/stdtypes typecontextmanager}@anchor{240d}
@subsection コンテキストマネージャ型


@geindex context manager
@geindex コンテキスト管理プロトコル
@geindex プロトコル;コンテキスト管理

Python の @ref{186,,with} 文は、コンテキストマネージャによって定義される実行時コンテキストの概念をサポートします。これは、文の本体が実行される前に進入し文の終わりで脱出する実行時コンテキストを、ユーザ定義クラスが定義できるようにする一対のメソッドで実装されます:

@geindex __enter__() (contextmanager のメソッド)
@anchor{library/stdtypes contextmanager __enter__}@anchor{26a8}
@deffn {メソッド} contextmanager.__enter__ ()

実行時コンテキストに入り、このオブジェクトまたは他の実行時コンテキストに関連したオブジェクトを返します。このメソッドが返す値はこのコンテキストマネージャを使う @ref{186,,with} 文の @code{as} 節の識別子に束縛されます。

自分自身を返すコンテキストマネージャの例として @ref{13db,,ファイルオブジェクト} があります。ファイルオブジェクトは __enter__() から自分自身を返し、 @ref{316,,open()} が @ref{186,,with} 文のコンテキスト式として使われるようにします。

関連オブジェクトを返すコンテキストマネージャの例としては @ref{159e,,decimal.localcontext()} が返すものがあります。このマネージャはアクティブな10進数コンテキストをオリジナルのコンテキストのコピーにセットしてそのコピーを返します。こうすることで, @ref{186,,with} 文の本体の内部で、@code{with} 文の外側のコードに影響を与えずに、 10進数コンテキストを変更できます。
@end deffn

@geindex __exit__() (contextmanager のメソッド)
@anchor{library/stdtypes contextmanager __exit__}@anchor{26a9}
@deffn {メソッド} contextmanager.__exit__ (exc_type, exc_val, exc_tb)

実行時コンテキストから抜け、(発生していた場合) 例外を抑制するかどうかを示すブール値フラグを返します。 @ref{186,,with} 文の本体の実行中に例外が発生した場合、引数にはその例外の型と値とトレースバック情報を渡します。そうでない場合、引数は全て @code{None} となります。

Returning a true value from this method will cause the @ref{186,,with} statement
to suppress the exception and continue execution with the statement immediately
following the @code{with} statement. Otherwise the exception continues
propagating after this method has finished executing.

If this method raises an exception while handling an earlier exception from the
@ref{186,,with} block, the new exception is raised, and the original exception
is stored in its @ref{14df,,__context__} attribute.

渡された例外を明示的に再送出すべきではありません。その代わりに、このメソッドが偽の値を返すことでメソッドの正常終了と送出された例外を抑制しないことを伝えるべきです。このようにすればコンテキストマネージャは @ref{1518,,__exit__()} メソッド自体が失敗したのかどうかを簡単に見分けることができます。
@end deffn

Python は、易しいスレッド同期、ファイルなどのオブジェクトの即時クローズ、アクティブな小数算術コンテキストの単純な操作をサポートするために、いくつかのコンテキストマネージャを用意しています。各型はコンテキスト管理プロトコルを実装しているという以上の特別の取り扱いを受けるわけではありません。例については @ref{27,,contextlib} モジュールを参照してください。

Python の @ref{126c,,ジェネレータ} と @ref{141b,,contextlib.contextmanager}  @ref{93a,,デコレータ} はこのプロトコルの簡便な実装方法を提供します。ジェネレータ関数を @ref{141b,,contextlib.contextmanager} デコレータでデコレートすると、デコレートされないジェネレータ関数が作成するイテレータの代わりに、必要な @ref{26a8,,__enter__()} および @ref{26a9,,__exit__()} メソッドを実装したコンテキストマネージャを返すようになります。

これらのメソッドのために Python/C API の中の Python オブジェクトの型構造体に特別なスロットが作られたわけではないことに注意してください。これらのメソッドを定義したい拡張型はこれらを通常の Python からアクセスできるメソッドとして提供しなければなりません。実行時コンテキストを準備するオーバーヘッドに比べたら、一回のクラス辞書の探索のオーバーヘッドは無視できます。

@node 型アノテーション型 --- ジェネリックエイリアス 、 ユニオン,その他の組み込み型,コンテキストマネージャ型,組み込み型
@anchor{library/stdtypes type-annotation-types-generic-alias-union}@anchor{26aa}
@subsection 型アノテーション型 --- ジェネリックエイリアス 、 ユニオン


@geindex 注釈;type annotation; type hint

@ref{15c,,型アノテーション} の中心となる組み込みの型は @ref{8c1,,ジェネリックエイリアス} と @ref{9c5,,ユニオン} です。

@menu
* ジェネリックエイリアス型:: 
* Union 型:: 

@end menu

@node ジェネリックエイリアス型,Union 型,,型アノテーション型 --- ジェネリックエイリアス 、 ユニオン
@anchor{library/stdtypes generic-alias-type}@anchor{26ab}@anchor{library/stdtypes types-genericalias}@anchor{8c1}
@subsubsection ジェネリックエイリアス型


@geindex object;GenericAlias
@geindex Generic;Alias

@code{GenericAlias} オブジェクトは一般的に、クラスに @ref{23ce,,添字表記} をすることで作られます。
@ref{24d,,list} や @ref{183,,dict} のような @ref{23d4,,コンテナ系のクラス} に対して使われることがほとんどです。
例えば、 @code{list[int]} は @code{list} クラスに @ref{19b,,int} という引数を与えた添字表記をすることで作られる @code{GenericAlias} オブジェクトです。
@code{GenericAlias} オブジェクトは主に @ref{15c,,型アノテーション} の用途で使われます。

@cartouche
@quotation 注釈 
一般に、クラスへの添字表記は、そのクラスが特殊メソッド @ref{943,,__class_getitem__()} を実装しているときに限り可能です。
@end quotation
@end cartouche

@code{GenericAlias} オブジェクトは `パラメータ付きジェネリック型' を実装したジェネリック型 (@ref{1a1,,generic type}) の代用として振る舞います。

コンテナクラスに対してクラスの @ref{23ce,,添字表記} に与えられた単一または複数の引数は、そのオブジェクトが包含する要素の型をあらわします。たとえば @code{set[bytes]} という表記は、全ての要素が @ref{192,,bytes} であるような @ref{184,,set} をあらわす型アノテーションとして使うことができます。

@ref{943,,__class_getitem__()} メソッドを定義しているけれどもコンテナでないクラスに対しては、クラスの添字表記に与えられた単一または複数の引数は、しばしばオブジェクトに定義された単一または複数のメソッドの戻り値の型をあらわします。たとえば、 @ref{be,,正規表現操作} は @ref{169,,str} と @ref{192,,bytes} の両方のデータ型に対して使うことができます:


@itemize *

@item 
@code{x = re.search('foo', 'foo')} とした場合、 @code{x} は @ref{118a,,re.Match} オブジェクトとなり、 @code{x.group(0)} と @code{x[0]} の戻り値はどちらも @ref{169,,str} となります。このようなオブジェクトは、 @code{GenericAlias} を使った型アノテーション @code{re.Match[str]} で表現することができます。

@item 
@code{y = re.search(b'bar', b'bar')} (ここで @code{b} は @ref{192,,bytes} 型をあらわします) とした場合、@code{y} もまた @code{re.Match} のインスタンスとなりますが、 @code{y.group(0)} と @code{y[0]} の戻り値はどちらも @ref{192,,bytes} 型になります。型アノテーションでは、このような @ref{118a,,re.Match} オブジェクトは @code{re.Match[bytes]} と表現することになるでしょう。
@end itemize

@code{GenericAlias} オブジェクトは @ref{9ec,,types.GenericAlias} クラスのインスタンスです。このクラスは直接 @code{GenericAlias} オブジェクトを生成するのに使うこともできます。


@deffn {Describe} T[X, Y, ...]

型 "X", "Y", またはさらに多くの引数でパラメータ化される型 @code{T} を表現する @code{GenericAlias} を生成します。引数の数は @code{T} の使われ方によって決まります。たとえば、 @ref{196,,float} 型の要素を含む @ref{24d,,list} を引数にとる関数の型アノテーションは次のようになります:

@example
def average(values: list[float]) -> float:
    return sum(values) / len(values)
@end example

もうひとつの例として @ref{13d3,,mapping} オブジェクトの場合を示します。ここではキーと値の2つの型をパラメータとするジェネリック型である @ref{183,,dict} を使っています。この例では、関数はキーが @ref{169,,str} 型、値が @ref{19b,,int} 型であるような @code{dict} を引数にとります:

@example
def send_post_request(url: str, body: dict[str, int]) -> None:
    ...
@end example
@end deffn

組み込み関数 @ref{2ad,,isinstance()} と @ref{9c4,,issubclass()} は第二引数として @code{GenericAlias} 型を指定することはできません:

@example
>>> isinstance([1, 2], list[str])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() argument 2 cannot be a parameterized generic
@end example

Python 実行時には @ref{15c,,型アノテーション} は強制されません。この性質はジェネリック型とその型パラメータにもおよびます。 @code{GenericAlias} からコンテナオブジェクトを生成した場合、コンテナ内の要素は型のチェックを受けません。たとえば、以下のコードは推奨されませんが、エラーになることなく実行できます:

@example
>>> t = list[str]
>>> t([1, 2, 3])
[1, 2, 3]
@end example

しかも、パラメータ付きジェネリック型は、オブジェクト生成時にパラメータの型情報を削除します:

@example
>>> t = list[str]
>>> type(t)
<class 'types.GenericAlias'>

>>> l = t()
>>> type(l)
<class 'list'>
@end example

@ref{1c1,,repr()} や @ref{169,,str()} のジェネリック型に対する呼び出しは、パラメータ型を表示します:

@example
>>> repr(list[int])
'list[int]'

>>> str(list[int])
'list[int]'
@end example

ジェネリックコンテナ型の @ref{588,,__getitem__()} メソッドは、 @code{dict[str][str]} のようなミスを許さないように、例外を送出します:

@example
>>> dict[str][str]
Traceback (most recent call last):
  ...
TypeError: dict[str] is not a generic class
@end example

一方で、同様の式は @ref{23c9,,型変数} が使われた場合は有効です。添字の数は`@w{`}GenericAlias`@w{`} オブジェクトの @ref{26ac,,__args__} 属性における型変数の数と同じでなければなりません:

@example
>>> from typing import TypeVar
>>> Y = TypeVar('Y')
>>> dict[str, Y][int]
dict[str, int]
@end example

@menu
* 標準ジェネリッククラス:: 
* GenericAlias オブジェクトの特別な属性:: 

@end menu

@node 標準ジェネリッククラス,GenericAlias オブジェクトの特別な属性,,ジェネリックエイリアス型
@anchor{library/stdtypes standard-generic-classes}@anchor{26ad}
@subsubsection 標準ジェネリッククラス


以下の標準ライブラリクラスは、パラメータ付きジェネリック型をサポートします。このリストは完全に網羅されていない可能性があります。


@itemize *

@item 
@ref{614,,tuple}

@item 
@ref{24d,,list}

@item 
@ref{183,,dict}

@item 
@ref{184,,set}

@item 
@ref{7f2,,frozenset}

@item 
@ref{f44,,type}

@item 
@ref{dc6,,asyncio.Future}

@item 
@ref{1c7,,asyncio.Task}

@item 
@ref{7f4,,collections.deque}

@item 
@ref{13d4,,collections.defaultdict}

@item 
@ref{7f3,,collections.OrderedDict}

@item 
@ref{12a3,,collections.Counter}

@item 
@ref{e16,,collections.ChainMap}

@item 
’’@ref{fdc,,collections.abc.Awaitable}

@item 
@ref{fdd,,collections.abc.Coroutine}

@item 
@ref{fdf,,collections.abc.AsyncIterable}

@item 
@ref{fde,,collections.abc.AsyncIterator}

@item 
@ref{e87,,collections.abc.AsyncGenerator}

@item 
@ref{26ae,,collections.abc.Iterable}

@item 
@ref{26af,,collections.abc.Iterator}

@item 
@ref{fdb,,collections.abc.Generator}

@item 
@ref{e85,,collections.abc.Reversible}

@item 
@ref{26b0,,collections.abc.Container}

@item 
@ref{e84,,collections.abc.Collection}

@item 
@ref{9eb,,collections.abc.Callable}

@item 
@ref{26a6,,collections.abc.Set}

@item 
@ref{26b1,,collections.abc.MutableSet}

@item 
@ref{ac7,,collections.abc.Mapping}

@item 
@ref{12c0,,collections.abc.MutableMapping}

@item 
@ref{13dc,,collections.abc.Sequence}

@item 
@ref{4bf,,collections.abc.MutableSequence}

@item 
@ref{342,,collections.abc.ByteString}

@item 
@ref{26b2,,collections.abc.MappingView}

@item 
@ref{26b3,,collections.abc.KeysView}

@item 
@ref{26b4,,collections.abc.ItemsView}

@item 
@ref{26b5,,collections.abc.ValuesView}

@item 
@ref{e8a,,contextlib.AbstractContextManager}

@item 
@ref{d20,,contextlib.AbstractAsyncContextManager}

@item 
@ref{195b,,dataclasses.Field}

@item 
@ref{763,,functools.cached_property}

@item 
@ref{218,,functools.partialmethod}

@item 
@ref{e4b,,os.PathLike}

@item 
@ref{26b6,,queue.LifoQueue}

@item 
@ref{15ac,,queue.Queue}

@item 
@ref{26b7,,queue.PriorityQueue}

@item 
@ref{d61,,queue.SimpleQueue}

@item 
@ref{1189,,re.Pattern}

@item 
@ref{118a,,re.Match}

@item 
@ref{26b8,,shelve.BsdDbShelf}

@item 
@ref{26b9,,shelve.DbfilenameShelf}

@item 
@ref{119d,,shelve.Shelf}

@item 
@ref{698,,types.MappingProxyType}

@item 
@ref{1929,,weakref.WeakKeyDictionary}

@item 
@ref{11f1,,weakref.WeakMethod}

@item 
@ref{7f5,,weakref.WeakSet}

@item 
@ref{192a,,weakref.WeakValueDictionary}
@end itemize

@node GenericAlias オブジェクトの特別な属性,,標準ジェネリッククラス,ジェネリックエイリアス型
@anchor{library/stdtypes special-attributes-of-genericalias-objects}@anchor{26ba}
@subsubsection @code{GenericAlias} オブジェクトの特別な属性


全てのパラメータ付きジェネリック型は、下記に示す読み出し専用の属性を実装しています。

@geindex __origin__ (genericalias の属性)
@anchor{library/stdtypes genericalias __origin__}@anchor{26bb}
@deffn {の属性} genericalias.__origin__

この属性は、対応するパラメータ付きでないジェネリッククラスを指します:

@example
>>> list[int].__origin__
<class 'list'>
@end example
@end deffn

@geindex __args__ (genericalias の属性)
@anchor{library/stdtypes genericalias __args__}@anchor{26ac}
@deffn {の属性} genericalias.__args__

この属性は、ジェネリッククラスの元の @ref{943,,__class_getitem__()} に渡された @ref{614,,tuple} です (長さが1の場合もあります):

@example
>>> dict[str, list[int]].__args__
(<class 'str'>, list[int])
@end example
@end deffn

@geindex __parameters__ (genericalias の属性)
@anchor{library/stdtypes genericalias __parameters__}@anchor{26bc}
@deffn {の属性} genericalias.__parameters__

この属性は、 @code{__args__} にある固有の型変数のタプルで、必要に応じて遅延計算されます (空の可能性もあります):

@example
>>> from typing import TypeVar

>>> T = TypeVar('T')
>>> list[T].__parameters__
(~T,)
@end example

@cartouche
@quotation 注釈 
@ref{487,,typing.ParamSpec} パラメータを含む @code{GenericAlias} オブジェクトは、代入後に正しい @code{__parameters__} を持たない可能性があります。これは @ref{487,,typing.ParamSpec} が主に静的な型チェックを目的としているためです。
@end quotation
@end cartouche
@end deffn

@geindex __unpacked__ (genericalias の属性)
@anchor{library/stdtypes genericalias __unpacked__}@anchor{26bd}
@deffn {の属性} genericalias.__unpacked__

これは、型エイリアスが @code{*} 演算子を使って取り出された場合に真となる真偽値です (@ref{488,,TypeVarTuple} を参照してください)。


Added in version 3.11.

@end deffn


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 484

@item PEP 484@footnote{https://peps.python.org/pep-0484/} - 型ヒント

型アノテーションのための Python のフレームワークへの導入です。

@geindex Python Enhancement Proposals; PEP 585

@item PEP 585@footnote{https://peps.python.org/pep-0585/} - 標準コレクション型の型ヒントにおける総称型 (generics) の使用

特殊なクラスメソッド @ref{943,,__class_getitem__()} を実装している場合に、標準ライブラリのクラスに対してネイティブにパラメータ表記を可能にする機能への導入です。

@item @ref{23c9,,ジェネリクス}, @ref{6f6,,ユーザー定義のジェネリック型}, および  @ref{17b6,,typing.Generic}

実行時にパラメータ設定が可能であり、かつ静的な型チェッカーが理解できるジェネリッククラスを実装する方法のドキュメントです。
@end table



Added in version 3.9.


@node Union 型,,ジェネリックエイリアス型,型アノテーション型 --- ジェネリックエイリアス 、 ユニオン
@anchor{library/stdtypes types-union}@anchor{9c5}@anchor{library/stdtypes union-type}@anchor{26be}
@subsubsection Union 型


@geindex object;Union
@geindex union;type

A union object holds the value of the @code{|} (bitwise or) operation on
multiple @ref{25e0,,type objects}.  These types are intended
primarily for @ref{15c,,type annotations}. The union type expression
enables cleaner type hinting syntax compared to subscripting @ref{2a8,,typing.Union}.


@deffn {Describe} X | Y | ...

`X' と `Y' などの型を保持するUnionオブジェクトを定義すします。@code{X | Y} はXとYのいずれかを意味します。これは @code{typing.Union[X, Y]} と等価です。たとえば、以下の関数は引数として @ref{19b,,int} 型または @ref{196,,float} 型を想定しています。:

@example
def square(number: int | float) -> int | float:
    return number ** 2
@end example

@cartouche
@quotation 注釈 
@code{|} のオペランドは、実行時に1つ以上の前方参照をメンバーとして含むようなユニオンを定義するために使うことはできません。たとえば、 @code{"Foo"} がまだ定義されていないクラスへの参照である場合、 @code{int | "Foo"} は実行時に失敗します。前方参照を含むユニオンは、 @code{"int | Foo"} のように、ユニオン全体を文字列としてあらわしてください。
@end quotation
@end cartouche
@end deffn


@deffn {Describe} union_object == other

Unionオブジェクトは他のUnionオブジェクトとの等価性をテストできます。以下は詳細です:


@itemize *

@item 
ユニオン型のユニオン型は平滑化されます:

@example
(int | str) | float == int | str | float
@end example

@item 
余分な型は削除されます:

@example
int | str | int == int | str
@end example

@item 
ユニオン型を比較すると順序は無視されます:

@example
int | str == str | int
@end example

@item 
It creates instances of @ref{2a8,,typing.Union}:

@example
int | str == typing.Union[int, str]
type(int | str) is typing.Union
@end example

@item 
Optional型は @code{None} とのUnion型で記述できます:

@example
str | None == typing.Optional[str]
@end example
@end itemize
@end deffn


@deffn {Describe} isinstance(obj, union_object)
@end deffn


@deffn {Describe} issubclass(obj, union_object)

@ref{2ad,,isinstance()} と @ref{9c4,,issubclass()} の呼び出しはどちらもUnionオブジェクトをサポートしています。

@example
>>> isinstance("", int | str)
True
@end example

しかし、Unionオブジェクトの中の @ref{8c1,,parameterized generics} はチェックできません:

@example
>>> isinstance(1, int | list[int])  # short-circuit evaluation
True
>>> isinstance([1], int | list[int])
Traceback (most recent call last):
  ...
TypeError: isinstance() argument 2 cannot be a parameterized generic
@end example
@end deffn

The user-exposed type for the union object can be accessed from
@ref{2a8,,typing.Union} and used for @ref{2ad,,isinstance()} checks:

@example
>>> import typing
>>> isinstance(int | str, typing.Union)
True
>>> typing.Union()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot create 'typing.Union' instances
@end example

@cartouche
@quotation 注釈 
@code{X | Y} 構文をサポートするために、型オブジェクトに @code{__or__()} メソッドが追加されました。メタクラスで @code{__or__()} を実装するとUnionをオーバーライドする場合があります:

@example
>>> class M(type):
...     def __or__(self, other):
...         return "Hello"
...
>>> class C(metaclass=M):
...     pass
...
>>> C | int
'Hello'
>>> int | C
int | C
@end example
@end quotation
@end cartouche


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 604
PEP 604@footnote{https://peps.python.org/pep-0604/} -- @code{X | Y} 構文とUnion型を提案しているPEP



Added in version 3.10.



バージョン 3.14 で変更: Union objects are now instances of @ref{2a8,,typing.Union}. Previously, they were instances
of @ref{2a7,,types.UnionType}, which remains an alias for @ref{2a8,,typing.Union}.


@node その他の組み込み型,特殊属性,型アノテーション型 --- ジェネリックエイリアス 、 ユニオン,組み込み型
@anchor{library/stdtypes other-built-in-types}@anchor{26bf}@anchor{library/stdtypes typesother}@anchor{26c0}
@subsection その他の組み込み型


インタプリタは、その他いくつかの種類のオブジェクトをサポートしています。これらのほとんどは 1 つまたは 2 つの演算だけをサポートしています。

@menu
* モジュール: モジュール<4>. 
* クラスおよびクラスインスタンス:: 
* 関数:: 
* メソッド:: 
* コードオブジェクト: コードオブジェクト<2>. 
* 型オブジェクト:: 
* ヌルオブジェクト:: 
* Ellipsis オブジェクト:: 
* NotImplemented オブジェクト:: 
* 内部オブジェクト:: 

@end menu

@node モジュール<4>,クラスおよびクラスインスタンス,,その他の組み込み型
@anchor{library/stdtypes modules}@anchor{26c1}@anchor{library/stdtypes typesmodules}@anchor{26c2}
@subsubsection モジュール


モジュールに対する唯一の特殊な演算は属性アクセス: @code{m.name} です。ここで `m' はモジュールで、 `name' は `m' のシンボルテーブル上に定義された名前にアクセスします。モジュール属性に代入することもできます。 (なお、@ref{7f8,,import} 文は、厳密にいえば、モジュールオブジェクトに対する演算ではありません; @code{import foo} は `foo' と名づけられたモジュールオブジェクトの存在を必要とはせず、`foo' と名づけられたモジュールの (外部の) `定義' を必要とします。)

全てのモジュールにある特殊属性が @ref{77d,,__dict__} です。これはモジュールのシンボルテーブルを含む辞書です。この辞書を書き換えると実際にモジュールのシンボルテーブルを変更することができますが、@ref{77d,,__dict__} 属性を直接代入することはできません (@code{m.__dict__['a'] = 1} と書いて @code{m.a} を @code{1} に定義することはできますが、@code{m.__dict__ = @{@}} と書くことはできません)。 @ref{77d,,__dict__} を直接書き換えることは推奨されません。

インタプリタ内に組み込まれたモジュールは、 @code{<module 'sys' (built-in)>} のように書かれます。ファイルから読み出された場合、 @code{<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>} と書かれます。

@node クラスおよびクラスインスタンス,関数,モジュール<4>,その他の組み込み型
@anchor{library/stdtypes classes-and-class-instances}@anchor{26c3}@anchor{library/stdtypes typesobjects}@anchor{26c4}
@subsubsection クラスおよびクラスインスタンス


これらについては @ref{232c,,オブジェクト、値、および型} および @ref{14ef,,クラス定義} を参照してください。

@node 関数,メソッド,クラスおよびクラスインスタンス,その他の組み込み型
@anchor{library/stdtypes functions}@anchor{26c5}@anchor{library/stdtypes typesfunctions}@anchor{26c6}
@subsubsection 関数


関数オブジェクトは関数定義によって生成されます。関数オブジェクトに対する唯一の操作は、それを呼び出すことです: @code{func(argument-list)} 。

関数オブジェクトには実際には二種類あります: 組み込み関数とユーザ定義関数です。どちらも同じ操作 (関数の呼び出し) をサポートしますが、実装は異なるので、オブジェクトの型も異なります。

詳細は、 @ref{2018,,関数定義} を参照してください。

@node メソッド,コードオブジェクト<2>,関数,その他の組み込み型
@anchor{library/stdtypes methods}@anchor{26c7}@anchor{library/stdtypes typesmethods}@anchor{26c8}
@subsubsection メソッド


@geindex object;メソッド

Methods are functions that are called using the attribute notation.
There are two flavors: @ref{235a,,built-in methods}
(such as @ref{8dc,,append()} on lists)
and @ref{20a7,,class instance method}.
Built-in methods are described with the types that support them.

インスタンスを通してメソッド (クラスの名前空間内で定義された関数) にアクセスすると、特殊なオブジェクトが得られます。それは束縛メソッド (`bound method') オブジェクトで、インスタンスメソッド (@ref{20a7,,instance method}) とも呼ばれます。呼び出された時、引数リストに @code{self} 引数が追加されます。束縛メソッドには 2 つの特殊読み出し専用属性があります。 @ref{15e2,,m.__self__} はそのメソッドが操作するオブジェクトで、@ref{1514,,m.__func__} はそのメソッドを実装している関数です。 @code{m(arg-1, arg-2, ..., arg-n)} の呼び出しは、 @code{m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)} の呼び出しと完全に等価です。

@ref{59c,,function objects} と同様に、メソッドオブジェクトは任意の属性の取得をサポートしています。しかし、メソッド属性は実際には下層の関数オブジェクト (@ref{1514,,method.__func__}) に記憶されているので、バインドされるメソッドにメソッド属性を設定することは許されていません。メソッドに属性を設定しようとすると @ref{5f0,,AttributeError} が送出されます。メソッドの属性を設定するためには、次のようにその下層の関数オブジェクトに明示的に設定する必要があります:

@example
>>> class C:
...     def method(self):
...         pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method'  # can't set on the method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method' object has no attribute 'whoami'
>>> c.method.__func__.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'
@end example

詳細は @ref{20a7,,インスタンスメソッド} を参照してください。

@geindex object;コード
@geindex コードオブジェクト

@node コードオブジェクト<2>,型オブジェクト,メソッド,その他の組み込み型
@anchor{library/stdtypes bltin-code-objects}@anchor{26c9}@anchor{library/stdtypes code-objects}@anchor{26ca}
@subsubsection コードオブジェクト


@geindex 組み込み関数;コンパイル
@geindex __code__ (関数オブジェクトの属性)

コードオブジェクトは、関数本体のような "擬似コンパイルされた" Python の実行可能コードを表すために実装系によって使われます。コードオブジェクトはグローバルな実行環境への参照を持たない点で関数オブジェクトとは異なります。コードオブジェクトは組み込み関数 @ref{4b1,,compile()} によって返され、また関数オブジェクトの @ref{59d,,__code__} 属性として取り出せます。 @ref{1b,,code} モジュールも参照してください。

@ref{59d,,__code__} へのアクセスは @code{object.__getattr__} に @code{obj} と @code{"__code__"} を渡して行いますが、 @ref{1c6e,,監査イベント} を送出します。

@geindex 組み込み関数;exec
@geindex 組み込み関数;eval

コードオブジェクトは、組み込み関数 @ref{4a2,,exec()} や @ref{4a3,,eval()} に (ソース文字列の代わりに) 渡すことで、実行や評価できます。

詳細は、 @ref{232f,,標準型の階層} を参照してください。

@node 型オブジェクト,ヌルオブジェクト,コードオブジェクト<2>,その他の組み込み型
@anchor{library/stdtypes bltin-type-objects}@anchor{25e0}@anchor{library/stdtypes type-objects}@anchor{26cb}
@subsubsection 型オブジェクト


@geindex 組み込み関数;type
@geindex module;types

型オブジェクトは様々なオブジェクト型を表します。オブジェクトの型は組み込み関数 @ref{f44,,type()} でアクセスされます。型オブジェクトには特有の操作はありません。標準モジュール @ref{109,,types} には全ての組み込み型名が定義されています。

型はこのように書き表されます: @code{<class 'int'>} 。

@node ヌルオブジェクト,Ellipsis オブジェクト,型オブジェクト,その他の組み込み型
@anchor{library/stdtypes bltin-null-object}@anchor{26cc}@anchor{library/stdtypes the-null-object}@anchor{26cd}
@subsubsection ヌルオブジェクト


このオブジェクトは明示的に値を返さない関数によって返されます。このオブジェクトには特有の操作はありません。ヌルオブジェクトは一つだけで、 @code{None} (組み込み名) と名づけられています。 @code{type(None)()} は同じシングルトンを作成します。

@code{None} と書き表されます。

@geindex ...;ellipsisリテラル

@node Ellipsis オブジェクト,NotImplemented オブジェクト,ヌルオブジェクト,その他の組み込み型
@anchor{library/stdtypes bltin-ellipsis-object}@anchor{1ffc}@anchor{library/stdtypes the-ellipsis-object}@anchor{26ce}
@subsubsection Ellipsis オブジェクト


This object is commonly used to indicate that something is omitted.
It supports no special operations.  There is exactly one ellipsis object, named
@ref{2328,,Ellipsis} (a built-in name).  @code{type(Ellipsis)()} produces the
@ref{2328,,Ellipsis} singleton.

@code{Ellipsis} または @code{...} と書き表されます。

In typical use, @code{...} as the @code{Ellipsis} object appears in a few different
places, for instance:


@itemize -

@item 
In type annotations, such as @ref{26cf,,callable arguments}
or @ref{26d0,,tuple elements}.

@item 
As the body of a function instead of a @ref{1ffb,,pass statement}.

@item 
In third-party libraries, such as Numpy's slicing and striding@footnote{https://numpy.org/doc/stable/user/basics.indexing.html#slicing-and-striding}.
@end itemize

Python also uses three dots in ways that are not @code{Ellipsis} objects, for instance:


@itemize -

@item 
Doctest's @ref{1687,,ELLIPSIS}, as a pattern for missing content.

@item 
The default Python prompt of the @ref{1b5,,interactive} shell when partial input is incomplete.
@end itemize

Lastly, the Python documentation often uses three dots in conventional English
usage to mean omitted content, even in code examples that also use them as the
@code{Ellipsis}.

@node NotImplemented オブジェクト,内部オブジェクト,Ellipsis オブジェクト,その他の組み込み型
@anchor{library/stdtypes bltin-notimplemented-object}@anchor{26d1}@anchor{library/stdtypes the-notimplemented-object}@anchor{26d2}
@subsubsection NotImplemented オブジェクト


このオブジェクトは、対応していない型に対して比較演算や二項演算が求められたとき、それらの演算から返されます。詳細は @ref{24d0,,比較} を参照してください。 @ref{1a2,,NotImplemented} オブジェクトは一つだけです。 @code{type(NotImplemented)()} はこの単一のインスタンスを作成します。

@code{NotImplemented} と書き表されます。

@node 内部オブジェクト,,NotImplemented オブジェクト,その他の組み込み型
@anchor{library/stdtypes internal-objects}@anchor{26d3}@anchor{library/stdtypes typesinternal}@anchor{26d4}
@subsubsection 内部オブジェクト


この情報は @ref{232f,,標準型の階層} を参照してください。@ref{8ef,,stack frame objects}、@ref{cec,,traceback objects}、スライスオブジェクトについて記述されています。

@node 特殊属性,整数と文字列の変換での長さ制限,その他の組み込み型,組み込み型
@anchor{library/stdtypes special-attributes}@anchor{26d5}@anchor{library/stdtypes specialattrs}@anchor{26d6}
@subsection 特殊属性


実装は、いくつかのオブジェクト型に対して、適切な場合には特殊な読み出し専用の属性を追加します。そのうちいくつかは @ref{844,,dir()} 組込み関数で報告されません。

@geindex __name__ (definition の属性)
@anchor{library/stdtypes definition __name__}@anchor{1272}
@deffn {の属性} definition.__name__

クラス、関数、メソッド、デスクリプタ、ジェネレータインスタンスの名前です。
@end deffn

@geindex __qualname__ (definition の属性)
@anchor{library/stdtypes definition __qualname__}@anchor{1271}
@deffn {の属性} definition.__qualname__

クラス、関数、メソッド、デスクリプタ、ジェネレータインスタンスの @ref{1d24,,修飾名} です。


Added in version 3.3.

@end deffn

@geindex __module__ (definition の属性)
@anchor{library/stdtypes definition __module__}@anchor{26d7}
@deffn {の属性} definition.__module__

The name of the module in which a class or function was defined.
@end deffn

@geindex __doc__ (definition の属性)
@anchor{library/stdtypes definition __doc__}@anchor{b21}
@deffn {の属性} definition.__doc__

The documentation string of a class or function, or @code{None} if undefined.
@end deffn

@geindex __type_params__ (definition の属性)
@anchor{library/stdtypes definition __type_params__}@anchor{2594}
@deffn {の属性} definition.__type_params__

The @ref{5ad,,type parameters} of generic classes, functions,
and @ref{683,,type aliases}. For classes and functions that
are not generic, this will be an empty tuple.


Added in version 3.12.

@end deffn

@node 整数と文字列の変換での長さ制限,,特殊属性,組み込み型
@anchor{library/stdtypes int-max-str-digits}@anchor{80b}@anchor{library/stdtypes integer-string-conversion-length-limitation}@anchor{26d8}
@subsection 整数と文字列の変換での長さ制限


CPythonはDoS(サービス妨害攻撃)を軽減するために @ref{19b,,int} と @ref{169,,str} の間の変換に全体的な制限を設けました。この制限は10進数や2のべき乗以外の基数に `のみ' 適用されます。16進数、8進数と2進数は制限がありません。上限値は設定できます。

CPython の @ref{19b,,int} 型は、任意の長さの数をバイナリ形式で保存したものです (一般に "bignum" または多倍長整数として知られています)。基数が2のべき乗でない限り、線形の時間で文字列をバイナリ整数に、あるいはバイナリ整数を文字列に変換できるアルゴリズムは存在しません。10進数に対するアルゴリズムでは、最もよく知られているものでさえ、2次に近い (sub-quadratic) 複雑さになります。高速な CPU でも、 @code{int('1' * 500_000)} のような大きな数の変換は1秒以上かかる可能性があります。

変換するサイズを制限することは、 
@geindex Common Vulnerabilities and Exposures; CVE 2020-10735
CVE 2020-10735@footnote{https://www.cve.org/CVERecord?id=CVE-2020-10735} を回避する実践的な方法を提供します。

制限は、非線形な変換アルゴリズムが必要とされる場合に、入力または出力文字列の桁数に対して適用されます。アンダースコアや正負の符号はカウントされません。

演算の結果が制限を超えると、@ref{2ec,,ValueError} が送出されます:

@example
>>> import sys
>>> sys.set_int_max_str_digits(4300)  # Illustrative, this is the default.
>>> _ = int('2' * 5432)
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit
>>> i = int('2' * 4300)
>>> len(str(i))
4300
>>> i_squared = i*i
>>> len(str(i_squared))
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
>>> len(hex(i_squared))
7144
>>> assert int(hex(i_squared), base=16) == i*i  # Hexadecimal is unlimited.
@end example

デフォルトの上限値は4,300桁で、@ref{14ab,,sys.int_info.default_max_str_digits} で定義されています。設定可能な最小の上限値は 640 桁で、 @ref{14ab,,sys.int_info.str_digits_check_threshold} で定義されています。

確認:

@example
>>> import sys
>>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
>>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
>>> msg = int('578966293710682886880994035146873798396722250538762761564'
...           '9252925514383915483333812743580549779436104706260696366600'
...           '571186405732').to_bytes(53, 'big')
...
@end example


Added in version 3.11.


@menu
* 影響のあるAPI:: 
* 上限値を設定する:: 
* 推奨設定:: 

@end menu

@node 影響のあるAPI,上限値を設定する,,整数と文字列の変換での長さ制限
@anchor{library/stdtypes affected-apis}@anchor{26d9}
@subsubsection 影響のあるAPI


制限は @ref{19b,,int} と @ref{169,,str} または @ref{192,,bytes} の間での変換で時間がかかる可能性があると適用されます:


@itemize *

@item 
@code{int(string)} でデフォルトの基数10。

@item 
@code{int(string, base)} で2のべき乗以外のすべての基数。

@item 
@code{str(integer)}

@item 
@code{repr(integer)}

@item 
他の10進数での文字列変換。たとえば @code{f"@{integer@}"}、@code{"@{@}".format(integer)} や @code{b"%d" % integer}。
@end itemize

制限は、線形アルゴリズムの関数では適用されません。


@itemize *

@item 
@code{int(string, base)} で基数が2、4、8、16または32。

@item 
@ref{1be9,,int.from_bytes()} と @ref{1c32,,int.to_bytes()} 。

@item 
@ref{14e7,,hex()}, @ref{14e6,,oct()}, @ref{14c0,,bin()}.

@item 
@ref{4f9,,書式指定ミニ言語仕様} での16進数、8進数、2進数での表現。

@item 
@ref{169,,str} から @ref{196,,float}。

@item 
@ref{169,,str} から @ref{1fe,,decimal.Decimal}。
@end itemize

@node 上限値を設定する,推奨設定,影響のあるAPI,整数と文字列の変換での長さ制限
@anchor{library/stdtypes configuring-the-limit}@anchor{26da}
@subsubsection 上限値を設定する


Pythonを起動する前に環境変数またはインタープリタのコマンドラインのフラグで上限値を設定できます。


@itemize *

@item 
@geindex PYTHONINTMAXSTRDIGITS
@geindex 環境変数; PYTHONINTMAXSTRDIGITS
@ref{1b3a,,PYTHONINTMAXSTRDIGITS}、たとえば @code{PYTHONINTMAXSTRDIGITS=640 python3} は上限値を640に設定し、@code{PYTHONINTMAXSTRDIGITS=0 python3} は制限を無効化します。

@item 
@ref{16f,,-X int_max_str_digits}、たとえば @code{python3 -X int_max_str_digits=640}

@item 
@ref{26db,,sys.flags.int_max_str_digits} には 
@geindex PYTHONINTMAXSTRDIGITS
@geindex 環境変数; PYTHONINTMAXSTRDIGITS
@ref{1b3a,,PYTHONINTMAXSTRDIGITS} または @ref{16f,,-X int_max_str_digits} の値が設定されます。環境変数と @code{-X} オプションの両方が指定された場合は @code{-X} オプションが優先されます。  `-1' という値はどちらも未設定であることを表し、その場合は @ref{26dc,,sys.int_info.default_max_str_digits} の値が初期化時に使用されます。
@end itemize

コードでは、以下の @ref{df,,sys} APIを使用して現在の上限値を調べ、新しい値を設定できます。


@itemize *

@item 
@ref{1818,,sys.get_int_max_str_digits()} と @ref{18f1,,sys.set_int_max_str_digits()} はインタープリタ全体での上限値を取得、設定できます。サブインタープリタはそれぞれの上限値を持ちます。
@end itemize

デフォルト値と最小値に関する情報は @ref{14ab,,sys.int_info} で参照できます:


@itemize *

@item 
@ref{14ab,,sys.int_info.default_max_str_digits} はコンパイル時のデフォルト上限値です。

@item 
@ref{14ab,,sys.int_info.str_digits_check_threshold} は上限値として指定できる最低の値です(0の場合は無効になります)。
@end itemize


Added in version 3.11.


@cartouche
@quotation 注意 
小さな上限値を設定することで、問題が起きる `可能性があります' 。まれではありますが、ソースコード内で閾値を超える定数が10進数の整数として存在するコードが存在します。値に制限をつけることの帰結は、10進数の整数リテラルで制限を超える長さを持つ定数を含むコードのパース時、すなわち通常は起動時、モジュールのインポート時、またはインストール時など、そのコードのための @code{.pyc} ファイルが作られるまでのどこかの時点でのエラーです。大きな定数を含むソースコードに対する回避策は、その定数を、 @code{0x} を使って値の制限を持たない16進数の値に変換することです。

小さな上限値を使う場合、アプリケーションを徹底的にテストしてください。環境変数やフラグを使って、制限が起動時や、さらにはインストールの段階で Python が @code{.py} ファイルを事前にコンパイルして @code{.pyc} ファイルを作成する際にも適用されるようにした状態で、確実にテストが実行されるようにしてください。
@end quotation
@end cartouche

@node 推奨設定,,上限値を設定する,整数と文字列の変換での長さ制限
@anchor{library/stdtypes recommended-configuration}@anchor{26dd}
@subsubsection 推奨設定


デフォルトの @ref{26dc,,sys.int_info.default_max_str_digits} は、ほとんどのアプリケーションで適切な値であると期待されます。もしあなたのアプリケーションが異なる制限値を必要とする場合は、メインのエントリーポイントから、 Python バージョンに依存しないコードを使って制限値を設定してください。こうしなければならない理由は、これらの API が 3.12 以前のセキュリテイパッチリリースで追加されたためです。

以下はプログラム例です:

@example
>>> import sys
>>> if hasattr(sys, "set_int_max_str_digits"):
...     upper_bound = 68000
...     lower_bound = 4004
...     current_limit = sys.get_int_max_str_digits()
...     if current_limit == 0 or current_limit > upper_bound:
...         sys.set_int_max_str_digits(upper_bound)
...     elif current_limit < lower_bound:
...         sys.set_int_max_str_digits(lower_bound)
@end example

完全に無効にするには、@code{0} に設定します。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 組み込み例外,テキスト処理サービス,組み込み型,Python 標準ライブラリ
@anchor{library/exceptions doc}@anchor{26de}@anchor{library/exceptions bltin-exceptions}@anchor{1c27}@anchor{library/exceptions built-in-exceptions}@anchor{26df}@anchor{library/exceptions translation-repo}@anchor{26e0}
@section 組み込み例外


@geindex statement;try
@geindex statement;except

Python において、すべての例外は @ref{7d6,,BaseException} から派生したクラスのインスタンスでなければなりません。特定のクラスを言及する @ref{1ab,,except} 節を伴う @ref{8f8,,try} 文において、その節はそのクラスから派生した例外クラスも処理しますが、そのクラスの派生 `元' の例外クラスは処理しません。サブクラス化の関係にない 2 つの例外クラスは、それらが同じ名前だった場合でも等しくなりえません。

@geindex statement;raise

この章で挙げる組み込み例外は、インタプリタや組み込み関数によって生成されます。特に注記しないかぎり、これらはエラーの詳しい原因を示す "関連値 (associated value)" を持ちます。この値は、複数の情報 (エラーコードや、そのコードを説明する文字列など) の文字列かタプルです。関連値は通常、例外クラスのコンストラクタに引数として渡されます。

ユーザによるコードも組み込み例外を送出できます。これを使って、例外ハンドラをテストしたり、インタプリタが同じ例外を送出する状況と "ちょうど同じような" エラー条件であることを報告したりできます。しかし、ユーザのコードが適切でないエラーを送出するのを妨げる方法はないので注意してください。

組み込み例外クラスは新たな例外を定義するためにサブクラス化することができます。新しい例外は、@ref{bcd,,Exception} クラスかそのサブクラスの一つから派生することをお勧めします。 @ref{7d6,,BaseException} からは派生しないで下さい。例外を定義する上での詳しい情報は、 Python チュートリアルの @ref{207c,,ユーザー定義例外} の項目にあります。

@menu
* 例外コンテキスト:: 
* 組み込み例外から継承する:: 
* 基底クラス:: 
* 具象例外:: 
* 警告:: 
* 例外グループ:: 
* 例外のクラス階層:: 

@end menu

@node 例外コンテキスト,組み込み例外から継承する,,組み込み例外
@anchor{library/exceptions exception-context}@anchor{26e1}
@subsection 例外コンテキスト


@geindex 例外;連鎖
@geindex __cause__ (exception の属性)
@geindex __context__ (exception の属性)
@geindex __suppress_context__ (exception の属性)

例外オブジェクトの3つの属性は、例外が送出された常用に関する情報を提供します:

@geindex __context__ (BaseException の属性)
@geindex __cause__ (BaseException の属性)
@geindex __suppress_context__ (BaseException の属性)
@anchor{library/exceptions BaseException __context__}@anchor{14df}
@deffn {の属性} BaseException.__context__
@anchor{library/exceptions BaseException __cause__}@anchor{14e0}
@deffnx {の属性} BaseException.__cause__
@anchor{library/exceptions BaseException __suppress_context__}@anchor{2514}
@deffnx {の属性} BaseException.__suppress_context__

When raising a new exception while another exception
is already being handled, the new exception's
@code{__context__} attribute is automatically set to the handled
exception.  An exception may be handled when an @ref{1ab,,except} or
@ref{1b0,,finally} clause, or a @ref{186,,with} statement, is used.

This implicit exception context can be
supplemented with an explicit cause by using @code{from} with
@ref{803,,raise}:

@example
raise new_exc from original_exc
@end example

@ref{803,,from} に続く式は例外か @code{None} でなくてはなりません。
式は送出される例外の @code{__cause__} として設定されます。
@code{__cause__} を設定することは、 @code{__suppress_context__} 属性を暗黙的に @code{True} に設定することにもなるので、 @code{raise new_exc from None} を使うことで効率的に古い例外を新しいもので置き換えて表示する (例えば、 @ref{5e7,,KeyError} を @ref{5f0,,AttributeError} に置き換え)、古い例外はデバッグ時の調査で使えるよう @code{__context__} に残すことができます。

デフォルトの traceback 表示コードは、例外自体の traceback に加え、これらの連鎖された例外を表示します。@code{__cause__} で明示的に連鎖させた例外は、存在するならば常に表示されます。@code{__context__} で暗黙に連鎖させた例外は、@code{__cause__} が @ref{885,,None} かつ @code{__suppress_context__} が false の場合にのみ表示されます。

いずれにせよ、連鎖された例外に続いて、その例外自体は常に表示されます。そのため、traceback の最終行には、常に送出された最後の例外が表示されます。
@end deffn

@node 組み込み例外から継承する,基底クラス,例外コンテキスト,組み込み例外
@anchor{library/exceptions inheriting-from-built-in-exceptions}@anchor{26e2}
@subsection 組み込み例外から継承する


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 @code{args}
attribute, as well as due to possible memory layout incompatibilities.

`CPython 実装の詳細:' Most built-in exceptions are implemented in C for efficiency, see:
Objects/exceptions.c@footnote{https://github.com/python/cpython/tree/3.14/Objects/exceptions.c}.  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.

@node 基底クラス,具象例外,組み込み例外から継承する,組み込み例外
@anchor{library/exceptions base-classes}@anchor{26e3}
@subsection 基底クラス


以下の例外は、主に他の例外の基底クラスとして使われます。

@geindex BaseException
@anchor{library/exceptions BaseException}@anchor{7d6}
@deffn {例外} BaseException

全ての組み込み例外の基底クラスです。ユーザ定義の例外に直接継承されることは意図されていません (継承には @ref{bcd,,Exception} を使ってください)。このクラスのインスタンスに @ref{169,,str()} が呼ばれた場合、インスタンスへの引数の表現か、引数が無い場合には空文字列が返されます。

@geindex args (BaseException の属性)
@anchor{library/exceptions BaseException args}@anchor{78d}
@deffn {の属性} args

例外コンストラクタに与えられた引数のタプルです。組み込み例外は普通、エラーメッセージを与える一つの文字列だけを引数として呼ばれますが、中には (@ref{2c0,,OSError} など) いくつかの引数を必要とし、このタプルの要素に特別な意味を込めるものもあります。
@end deffn

@geindex with_traceback() (BaseException のメソッド)
@anchor{library/exceptions BaseException with_traceback}@anchor{2513}
@deffn {メソッド} with_traceback (tb)

This method sets `tb' as the new traceback for the exception and returns
the exception object.  It was more commonly used before the exception
chaining features of 
@geindex Python Enhancement Proposals; PEP 3134
PEP 3134@footnote{https://peps.python.org/pep-3134/} became available.  The following example
shows how we can convert an instance of @code{SomeException} into an
instance of @code{OtherException} while preserving the traceback.  Once
raised, the current frame is pushed onto the traceback of the
@code{OtherException}, as would have happened to the traceback of the
original @code{SomeException} had we allowed it to propagate to the caller.

@example
try:
    ...
except SomeException:
    tb = sys.exception().__traceback__
    raise OtherException(...).with_traceback(tb)
@end example
@end deffn

@geindex __traceback__ (BaseException の属性)
@anchor{library/exceptions BaseException __traceback__}@anchor{14de}
@deffn {の属性} __traceback__

A writable field that holds the
@ref{cec,,traceback object} associated with this
exception. See also: @ref{803,,raise 文}.
@end deffn

@geindex add_note() (BaseException のメソッド)
@anchor{library/exceptions BaseException add_note}@anchor{7d7}
@deffn {メソッド} add_note (note)

例外のノートとして文字列 @code{note} を追加します。ノートは標準のトレースバックで例外文字列の後に表示されます。@code{note} が文字列以外の場合 @ref{198,,TypeError} が送出されます。


Added in version 3.11.

@end deffn

@geindex __notes__ (BaseException の属性)
@anchor{library/exceptions BaseException __notes__}@anchor{26e4}
@deffn {の属性} __notes__

@ref{7d7,,add_note()} で追加された例外のノートのリスト。この属性は @ref{7d7,,add_note()} を呼び出すと生成されます。


Added in version 3.11.

@end deffn
@end deffn

@geindex Exception
@anchor{library/exceptions Exception}@anchor{bcd}
@deffn {例外} Exception

システム終了以外の全ての組み込み例外はこのクラスから派生しています。全てのユーザ定義例外もこのクラスから派生させるべきです。
@end deffn

@geindex ArithmeticError
@anchor{library/exceptions ArithmeticError}@anchor{26e5}
@deffn {例外} ArithmeticError

算術上の様々なエラーに対して送出される組み込み例外 @ref{a81,,OverflowError}, @ref{b3f,,ZeroDivisionError}, @ref{26e6,,FloatingPointError} の基底クラスです。
@end deffn

@geindex BufferError
@anchor{library/exceptions BufferError}@anchor{1797}
@deffn {例外} BufferError

@ref{260,,バッファ} に関連する操作が行えなかったときに送出されます。
@end deffn

@geindex LookupError
@anchor{library/exceptions LookupError}@anchor{23e5}
@deffn {例外} LookupError

マッピングまたはシーケンスで使われたキーやインデクスが無効な場合に送出される例外 @ref{174e,,IndexError} および @ref{5e7,,KeyError} の基底クラスです。 @ref{b5c,,codecs.lookup()} によって直接送出されることもあります。
@end deffn

@node 具象例外,警告,基底クラス,組み込み例外
@anchor{library/exceptions concrete-exceptions}@anchor{26e7}
@subsection 具象例外


以下の例外は、通常送出される例外です。

@geindex AssertionError
@anchor{library/exceptions AssertionError}@anchor{8b8}
@deffn {例外} AssertionError

@geindex statement;assert

@ref{b60,,assert} 文が失敗した場合に送出されます。
@end deffn

@geindex AttributeError
@anchor{library/exceptions AttributeError}@anchor{5f0}
@deffn {例外} AttributeError

属性参照 (@ref{24a9,,属性参照} を参照) や代入が失敗した場合に送出されます (オブジェクトが属性の参照や属性の代入をまったくサポートしていない場合には @ref{198,,TypeError} が送出されます)。

The optional `name' and `obj' keyword-only arguments
set the corresponding attributes:

@geindex name (AttributeError の属性)
@anchor{library/exceptions AttributeError name}@anchor{26e8}
@deffn {の属性} name

The name of the attribute that was attempted to be accessed.
@end deffn

@geindex obj (AttributeError の属性)
@anchor{library/exceptions AttributeError obj}@anchor{26e9}
@deffn {の属性} obj

The object that was accessed for the named attribute.
@end deffn


バージョン 3.10 で変更: @ref{26e8,,name} および @ref{26e9,,obj} 属性が追加されました。

@end deffn

@geindex EOFError
@anchor{library/exceptions EOFError}@anchor{14f1}
@deffn {例外} EOFError

Raised when the @ref{14f0,,input()} function hits an end-of-file condition (EOF)
without reading any data. (Note: the @code{io.IOBase.read()} and
@ref{1541,,io.IOBase.readline()} methods return an empty string when they hit EOF.)
@end deffn

@geindex FloatingPointError
@anchor{library/exceptions FloatingPointError}@anchor{26e6}
@deffn {例外} FloatingPointError

現在は使われていません。
@end deffn

@geindex GeneratorExit
@anchor{library/exceptions GeneratorExit}@anchor{15e1}
@deffn {例外} GeneratorExit

@ref{126c,,ジェネレータ} や @ref{6b9,,コルーチン} が閉じられたときに送出されます。 @ref{1793,,generator.close()} と @ref{241a,,coroutine.close()} を参照してください。この例外は厳密に言えばエラーではないので、 @ref{bcd,,Exception} ではなく @ref{7d6,,BaseException} を直接継承しています。
@end deffn

@geindex ImportError
@anchor{library/exceptions ImportError}@anchor{65b}
@deffn {例外} ImportError

@ref{7f8,,import} 文でモジュールをロードしようとして問題が発生すると送出されます。
@code{from ... import} の中の"from list" (訳注：@code{...} の部分)の名前が見つからないときにも送出されます。

オブションのキーワード専用引数  `name' と `path' は、対応する属性に設定されます:

@geindex name (ImportError の属性)
@anchor{library/exceptions ImportError name}@anchor{26ea}
@deffn {の属性} name

インポートを試みたモジュールの名前。
@end deffn

@geindex path (ImportError の属性)
@anchor{library/exceptions ImportError path}@anchor{26eb}
@deffn {の属性} path

例外を引き起こしたファイルのパス。
@end deffn


バージョン 3.3 で変更: @ref{26ea,,name} および @ref{26eb,,path} 属性が追加されました。

@end deffn

@geindex ModuleNotFoundError
@anchor{library/exceptions ModuleNotFoundError}@anchor{d3d}
@deffn {例外} ModuleNotFoundError

@ref{65b,,ImportError} のサブクラスで、@ref{7f8,,import} 文でモジュールが見つからない場合に送出されます。また、 @ref{17e6,,sys.modules} に @code{None} が含まれる場合にも送出されます。


Added in version 3.6.

@end deffn

@geindex IndexError
@anchor{library/exceptions IndexError}@anchor{174e}
@deffn {例外} IndexError

シーケンスの添字が範囲外の場合に送出されます。 (スライスのインデクスはシーケンスの範囲に収まるように暗黙のうちに調整されます; インデクスが整数でない場合、 @ref{198,,TypeError} が送出されます。)

@c XXX xref to sequences
@end deffn

@geindex KeyError
@anchor{library/exceptions KeyError}@anchor{5e7}
@deffn {例外} KeyError

マッピング (辞書) のキーが、既存のキーの集合内に見つからなかった場合に送出されます。

@c XXX xref to mapping objects?
@end deffn

@geindex KeyboardInterrupt
@anchor{library/exceptions KeyboardInterrupt}@anchor{bc5}
@deffn {例外} KeyboardInterrupt

ユーザが割り込みキー (通常は @code{Control}-@code{C} または @code{Delete}) を押した場合に送出されます。実行中、割り込みは定期的に監視されます。@ref{bcd,,Exception} を捕捉するコードに誤って捕捉されてインタプリタの終了が阻害されないように、この例外は @ref{7d6,,BaseException} を継承しています。

@cartouche
@quotation 注釈 
Catching a @ref{bc5,,KeyboardInterrupt} requires special consideration.
Because it can be raised at unpredictable points, it may, in some
circumstances, leave the running program in an inconsistent state. It is
generally best to allow @ref{bc5,,KeyboardInterrupt} to end the program as
quickly as possible or avoid raising it entirely. (See
@ref{26ec,,Note on Signal Handlers and Exceptions}.)
@end quotation
@end cartouche
@end deffn

@geindex MemoryError
@anchor{library/exceptions MemoryError}@anchor{179e}
@deffn {例外} MemoryError

ある操作中にメモリが不足したが、その状況は (オブジェクトをいくつか消去することで) まだ復旧可能かもしれない場合に送出されます。この例外の関連値は、メモリ不足になった (内部) 操作の種類を示す文字列です。下層のメモリ管理アーキテクチャ (C の @code{malloc()} 関数) のために、インタプリタが現状から完璧に復旧できるとはかぎらないので注意してください。それでも、プログラムの暴走が原因の場合に備えて実行スタックのトレースバックを出力できるように、例外が送出されます。
@end deffn

@geindex NameError
@anchor{library/exceptions NameError}@anchor{452}
@deffn {例外} NameError

ローカルまたはグローバルの名前が見つからなかった場合に送出されます。これは非修飾の (訳注: @code{spam.egg} ではなく単に @code{egg} のような) 名前のみに適用されます。関連値は見つからなかった名前を含むエラーメッセージです。

The optional `name' keyword-only argument sets the attribute:

@geindex name (NameError の属性)
@anchor{library/exceptions NameError name}@anchor{26ed}
@deffn {の属性} name

The name of the variable that was attempted to be accessed.
@end deffn


バージョン 3.10 で変更: @ref{26ed,,name} 属性が追加されました。

@end deffn

@geindex NotImplementedError
@anchor{library/exceptions NotImplementedError}@anchor{36b}
@deffn {例外} NotImplementedError

この例外は @ref{244,,RuntimeError} から派生しています。ユーザ定義の基底クラスにおいて、抽象メソッドが派生クラスでオーバライドされることを要求する場合にこの例外を送出しなくてはなりません。またはクラスは実装中であり本来の実装を追加する必要があることを示します。

@cartouche
@quotation 注釈 
演算子やメソッドがサポートされていないことを示す目的でこの例外を使用するべきではありません。そのようなケースではオペレータやメソッドを未定義のままとするか、サブクラスの場合は @ref{885,,None} を設定してください。
@end quotation
@end cartouche

@cartouche
@quotation 注意 
@code{NotImplementedError} and @code{NotImplemented} are not
interchangeable. This exception should only be used as described
above; see @ref{1a2,,NotImplemented} for details on correct usage of
the built-in constant.
@end quotation
@end cartouche
@end deffn

@geindex OSError
@anchor{library/exceptions OSError}@anchor{2c0}
@deffn {例外} OSError ([arg])

@deffnx {例外} OSError (errno, strerror[, filename[, winerror[, filename2]]])

@geindex module;errno

この例外はシステム関数がシステム関連のエラーを返した場合に送出されます。例えば "file not found" や "disk full" のような I/O の失敗が発生したときです (引数の型が不正な場合や、他の偶発的なエラーは除きます)。

コンストラクタの2番目の形式は下記の対応する属性を設定します。指定されなかった場合属性はデフォルトで @ref{885,,None} です。後方互換性のために、引数が3つ渡された場合、@ref{78d,,args} 属性は最初の2つの要素のみからなるタプルを持ちます。

コンストラクタは実際には、 @ref{26ee,,OS exceptions} で述べられている @ref{2c0,,OSError} のサブクラスを返すことがよくあります。特定のサブクラスは最終的な @ref{17b3,,errno} 値によります。この挙動は @ref{2c0,,OSError} を直接またはエイリアスで構築し、サブクラス化時に継承されなかった場合にのみ発生します。

@geindex errno (OSError の属性)
@anchor{library/exceptions OSError errno}@anchor{17b3}
@deffn {の属性} errno

C 変数 @code{errno} に由来する数値エラーコードです。
@end deffn

@geindex winerror (OSError の属性)
@anchor{library/exceptions OSError winerror}@anchor{26ef}
@deffn {の属性} winerror

Windows において、ネイティブ Windows エラーコードを与えます。そして @ref{17b3,,errno} 属性は POSIX でいうネイティブエラーコードへのおよその翻訳です。

Windows では、`winerror' コンストラクタ引数が整数の場合 @ref{17b3,,errno} 属性は Windows エラーコードから決定され、`errno' 引数は無視されます。他のプラットフォームでは `winerror' 引数は無視され、 @ref{26ef,,winerror} 属性は存在しません。
@end deffn

@geindex strerror (OSError の属性)
@anchor{library/exceptions OSError strerror}@anchor{26f0}
@deffn {の属性} strerror

The corresponding error message, as provided by
the operating system.  It is formatted by the C
functions @code{perror()} under POSIX, and @code{FormatMessage()}
under Windows.
@end deffn

@geindex filename (OSError の属性)
@geindex filename2 (OSError の属性)
@anchor{library/exceptions OSError filename}@anchor{26f1}
@deffn {の属性} filename
@anchor{library/exceptions OSError filename2}@anchor{26f2}
@deffnx {の属性} filename2

ファイルシステムパスが1つ関与する例外 (例えば @ref{316,,open()} や @ref{130d,,os.unlink()}) の場合、@ref{26f1,,filename} は関数に渡されたファイル名です。
ファイルシステムパスが2つ関与する関数 (例えば @ref{1309,,os.rename()}) の場合、@ref{26f2,,filename2} は関数に渡された2つ目のファイル名です。
@end deffn


バージョン 3.3 で変更: @ref{125f,,EnvironmentError}, @ref{125e,,IOError}, @ref{1260,,WindowsError},
@ref{1261,,socket.error}, @ref{1262,,select.error} and
@code{mmap.error} have been merged into @ref{2c0,,OSError}, and the
constructor may return a subclass.



バージョン 3.4 で変更: @ref{26f1,,filename} 属性が @ref{75d,,filesystem encoding and error handler} のエンコーディングでエンコードやデコードされた名前から、関数に渡された元々のファイル名になりました。
また、`filename2' コンストラクタ引数が追加されました。

@end deffn

@geindex OverflowError
@anchor{library/exceptions OverflowError}@anchor{a81}
@deffn {例外} OverflowError

算術演算の結果が表現できない大きな値になった場合に送出されます。これは整数では起こりません (むしろ @ref{179e,,MemoryError} が送出されることになるでしょう)。しかし、歴史的な理由のため、要求された範囲の外の整数に対して OverflowError が送出されることがあります。C の浮動小数点演算の例外処理は標準化されていないので、ほとんどの浮動小数点演算もチェックされません。
@end deffn

@geindex PythonFinalizationError
@anchor{library/exceptions PythonFinalizationError}@anchor{47a}
@deffn {例外} PythonFinalizationError

This exception is derived from @ref{244,,RuntimeError}.  It is raised when
an operation is blocked during interpreter shutdown also known as
@ref{479,,Python finalization}.

Examples of operations which can be blocked with a
@ref{47a,,PythonFinalizationError} during the Python finalization:


@itemize *

@item 
Creating a new Python thread.

@item 
@ref{13fd,,Joining} a running daemon thread.

@item 
@ref{4b5,,os.fork()}
@end itemize

@ref{c80,,sys.is_finalizing()} 関数も参照してください。


Added in version 3.13: 以前は @ref{244,,RuntimeError} をそのまま送出していました。



バージョン 3.14 で変更: @ref{13fd,,threading.Thread.join()} can now raise this exception.

@end deffn

@geindex RecursionError
@anchor{library/exceptions RecursionError}@anchor{f68}
@deffn {例外} RecursionError

この例外は @ref{244,,RuntimeError} を継承しています。インタープリタが最大再帰深度 (@ref{6eb,,sys.getrecursionlimit()} を参照) の超過を検出すると送出されます。


Added in version 3.5: 以前は @ref{244,,RuntimeError} をそのまま送出していました。

@end deffn

@geindex ReferenceError
@anchor{library/exceptions ReferenceError}@anchor{1726}
@deffn {例外} ReferenceError

@ref{c46,,weakref.proxy()} によって生成された弱参照 (weak reference) プロキシを使って、ガーベジコレクションによって回収された後の参照対象オブジェクトの属性にアクセスした場合に送出されます。弱参照については @ref{11a,,weakref} モジュールを参照してください。
@end deffn

@geindex RuntimeError
@anchor{library/exceptions RuntimeError}@anchor{244}
@deffn {例外} RuntimeError

他のカテゴリに分類できないエラーが検出された場合に送出されます。関連値は、何が問題だったのかをより詳細に示す文字列です。
@end deffn

@geindex StopIteration
@anchor{library/exceptions StopIteration}@anchor{df5}
@deffn {例外} StopIteration

組込み関数 @ref{9d8,,next()} と @ref{4c8,,iterator} の @ref{14e5,,__next__()} メソッドによって、そのイテレータが生成するアイテムがこれ以上ないことを伝えるために送出されます。

@geindex value (StopIteration の属性)
@anchor{library/exceptions StopIteration value}@anchor{2417}
@deffn {の属性} value

この例外オブジェクトには一つの属性 @code{value} があり、例外を構成する際に引数として与えられ、デフォルトは @ref{885,,None} です。
@end deffn

@ref{126c,,generator} や @ref{6b9,,coroutine} 関数が返るとき、新しい @ref{df5,,StopIteration} インスタンスが送出されます。
関数の返り値は例外のコンストラクタの @ref{2417,,value} 引数として使われます。

ジェネレータのコードが直接的あるいは間接的に @ref{df5,,StopIteration} を送出する場合は、 @ref{244,,RuntimeError} に変換されます (@ref{df5,,StopIteration} は変換後の例外の原因として保持されます)。


バージョン 3.3 で変更: @code{value} 属性とジェネレータ関数が値を返すためにそれを使う機能が追加されました。



バージョン 3.5 で変更: @code{from __future__ import generator_stop} による RuntimeError への変換が導入されました。 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/} を参照してください。



バージョン 3.7 で変更: 
@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/} が全てのコードでデフォルトで有効化されました: ジェネレータから送出された @ref{df5,,StopIteration} は @ref{244,,RuntimeError} に変換されます。

@end deffn

@geindex StopAsyncIteration
@anchor{library/exceptions StopAsyncIteration}@anchor{1e0f}
@deffn {例外} StopAsyncIteration

イテレーションを停止するために、 @ref{4c7,,asynchronous iterator} オブジェクトの @ref{1882,,__anext__()} メソッドによって返される必要があります。


Added in version 3.5.

@end deffn

@geindex SyntaxError
@anchor{library/exceptions SyntaxError}@anchor{18e}
@deffn {例外} SyntaxError (message, details)

パーザが構文エラーに遭遇した場合に送出されます。この例外は @ref{7f8,,import} 文、組み込み関数 @ref{4b1,,compile()}、@ref{4a2,,exec()} や @ref{4a3,,eval()} 、初期化スクリプトの読み込みや標準入力で (対話的な実行時にも) 起こる可能性があります。

例外インスタンスの @ref{169,,str()} はエラーメッセージのみを返します。詳細はタプルで、個々の属性としても利用できます。

@geindex filename (SyntaxError の属性)
@anchor{library/exceptions SyntaxError filename}@anchor{26f3}
@deffn {の属性} filename

構文エラーが発生したファイルの名前。
@end deffn

@geindex lineno (SyntaxError の属性)
@anchor{library/exceptions SyntaxError lineno}@anchor{26f4}
@deffn {の属性} lineno

ファイルのエラーが発生した行番号。1から数えはじめるため、ファイルの最初の行の @code{lineno} は1です。
@end deffn

@geindex offset (SyntaxError の属性)
@anchor{library/exceptions SyntaxError offset}@anchor{26f5}
@deffn {の属性} offset

行のエラーが発生した列番号。1から数えはじめるため、行の最初の文字の @code{offset} は1です。
@end deffn

@geindex text (SyntaxError の属性)
@anchor{library/exceptions SyntaxError text}@anchor{26f6}
@deffn {の属性} text

エラーを含むソースコードのテキスト。
@end deffn

@geindex end_lineno (SyntaxError の属性)
@anchor{library/exceptions SyntaxError end_lineno}@anchor{26f7}
@deffn {の属性} end_lineno

ファイルのエラーが発生した最後の行番号。1から数えはじめるため、ファイルの最初の行の @code{lineno} は1です。
@end deffn

@geindex end_offset (SyntaxError の属性)
@anchor{library/exceptions SyntaxError end_offset}@anchor{26f8}
@deffn {の属性} end_offset

行のエラーが発生した最後の列番号。1から数えはじめるため、行の最初の文字の @code{offset} は1です。
@end deffn

For errors in f-string fields, the message is prefixed by "f-string: "
and the offsets are offsets in a text constructed from the replacement
expression.  For example, compiling f'Bad @{a b@} field' results in this
args attribute: ('f-string: ...', ('@w{'}, 1, 2, '(a b)n', 1, 5)).


バージョン 3.10 で変更: @ref{26f7,,end_lineno} および @ref{26f8,,end_offset} 属性が追加されました。

@end deffn

@geindex IndentationError
@anchor{library/exceptions IndentationError}@anchor{1750}
@deffn {例外} IndentationError

正しくないインデントに関する構文エラーの基底クラスです。これは @ref{18e,,SyntaxError} のサブクラスです。
@end deffn

@geindex TabError
@anchor{library/exceptions TabError}@anchor{765}
@deffn {例外} TabError

タブとスペースを一貫しない方法でインデントに使っているときに送出されます。これは @ref{1750,,IndentationError} のサブクラスです。
@end deffn

@geindex SystemError
@anchor{library/exceptions SystemError}@anchor{795}
@deffn {例外} SystemError

Raised when the interpreter finds an internal error, but the situation does not
look so serious to cause it to abandon all hope. The associated value is a
string indicating what went wrong (in low-level terms). In @ref{905,,CPython},
this could be raised by incorrectly using Python's C API, such as returning
a @code{NULL} value without an exception set.

If you're confident that this exception wasn't your fault, or the fault of
a package you're using, you should report this to the author or maintainer
of your Python interpreter.
Be sure to report the version of the Python interpreter (@code{sys.version}; it is
also printed at the start of an interactive Python session), the exact error
message (the exception's associated value) and if possible the source of the
program that triggered the error.
@end deffn

@geindex SystemExit
@anchor{library/exceptions SystemExit}@anchor{f3c}
@deffn {例外} SystemExit

This exception is raised by the @ref{277,,sys.exit()} function.  It inherits from
@ref{7d6,,BaseException} instead of @ref{bcd,,Exception} so that it is not accidentally
caught by code that catches @ref{bcd,,Exception}.  This allows the exception to
properly propagate up and cause the interpreter to exit.  When it is not
handled, the Python interpreter exits; no stack traceback is printed.  The
constructor accepts the same optional argument passed to @ref{277,,sys.exit()}.
If the value is an integer, it specifies the system exit status (passed to
C's @code{exit()} function); if it is @code{None}, the exit status is zero; if
it has another type (such as a string), the object's value is printed and
the exit status is one.

@ref{277,,sys.exit()} は、クリーンアップのための処理 (@ref{8f8,,try} 文の @ref{1b0,,finally} 節) が実行されるようにするため、またデバッガが制御不能になるリスクを冒さずにスクリプトを実行できるようにするために例外に変換されます。即座に終了することが真に強く必要であるとき (例えば、@ref{4b5,,os.fork()} を呼んだ後の子プロセス内) には @ref{26f9,,os._exit()} 関数を使うことができます。

@geindex code (SystemExit の属性)
@anchor{library/exceptions SystemExit code}@anchor{26fa}
@deffn {の属性} code

コンストラクタに渡された終了ステータス又はエラーメッセージ。(デフォルトは @code{None})
@end deffn
@end deffn

@geindex TypeError
@anchor{library/exceptions TypeError}@anchor{198}
@deffn {例外} TypeError

組み込み演算または関数が適切でない型のオブジェクトに対して適用された際に送出されます。関連値は型の不整合に関して詳細を述べた文字列です。

この例外は、そのオブジェクトで実行しようとした操作がサポートされておらず、その予定もない場合にユーザーコードから送出されるかもしれません。オブジェクトでその操作をサポートするつもりだが、まだ実装を提供していないのであれば、送出する適切な例外は @ref{36b,,NotImplementedError} です。

誤った型の引数が渡された場合は (例えば、@ref{19b,,int} が期待されるのに、@ref{24d,,list} が渡された) @ref{198,,TypeError} となるべきです。しかし、誤った値(例えば、期待する範囲外の数)が引数として渡された場合は、 @ref{2ec,,ValueError} となるべきです。
@end deffn

@geindex UnboundLocalError
@anchor{library/exceptions UnboundLocalError}@anchor{174f}
@deffn {例外} UnboundLocalError

関数やメソッド内のローカルな変数に対して参照を行ったが、その変数には値が代入されていなかった場合に送出されます。 @ref{452,,NameError} のサブクラスです。
@end deffn

@geindex UnicodeError
@anchor{library/exceptions UnicodeError}@anchor{462}
@deffn {例外} UnicodeError

Unicode に関するエンコードまたはデコードのエラーが発生した際に送出されます。 @ref{2ec,,ValueError} のサブクラスです。

@ref{462,,UnicodeError} はエンコードまたはデコードのエラーの説明を属性として持っています。例えば、 @code{err.object[err.start:err.end]} は、無効な入力のうちコーデックが処理に失敗した箇所を表します。

@geindex encoding (UnicodeError の属性)
@anchor{library/exceptions UnicodeError encoding}@anchor{26fb}
@deffn {の属性} encoding

エラーを送出したエンコーディングの名前です。
@end deffn

@geindex reason (UnicodeError の属性)
@anchor{library/exceptions UnicodeError reason}@anchor{26fc}
@deffn {の属性} reason

そのコーデックエラーを説明する文字列です。
@end deffn

@geindex object (UnicodeError の属性)
@anchor{library/exceptions UnicodeError object}@anchor{18fc}
@deffn {の属性} object

コーデックがエンコードまたはデコードしようとしたオブジェクトです。
@end deffn

@geindex start (UnicodeError の属性)
@anchor{library/exceptions UnicodeError start}@anchor{18c0}
@deffn {の属性} start

@ref{c7e,,object} の最初の無効なデータのインデクスです。

This value should not be negative as it is interpreted as an
absolute offset but this constraint is not enforced at runtime.
@end deffn

@geindex end (UnicodeError の属性)
@anchor{library/exceptions UnicodeError end}@anchor{18c1}
@deffn {の属性} end

@ref{c7e,,object} の最後の無効なデータの次のインデクスです。

This value should not be negative as it is interpreted as an
absolute offset but this constraint is not enforced at runtime.
@end deffn
@end deffn

@geindex UnicodeEncodeError
@anchor{library/exceptions UnicodeEncodeError}@anchor{887}
@deffn {例外} UnicodeEncodeError

Unicode 関連のエラーがエンコード中に発生した際に送出されます。 @ref{462,,UnicodeError} のサブクラスです。
@end deffn

@geindex UnicodeDecodeError
@anchor{library/exceptions UnicodeDecodeError}@anchor{c08}
@deffn {例外} UnicodeDecodeError

Unicode 関連のエラーがデコード中に発生した際に送出されます。 @ref{462,,UnicodeError} のサブクラスです。
@end deffn

@geindex UnicodeTranslateError
@anchor{library/exceptions UnicodeTranslateError}@anchor{18fd}
@deffn {例外} UnicodeTranslateError

Unicode 関連のエラーが変換中に発生した際に送出されます。 @ref{462,,UnicodeError} のサブクラスです。
@end deffn

@geindex ValueError
@anchor{library/exceptions ValueError}@anchor{2ec}
@deffn {例外} ValueError

演算子や関数が、正しい型だが適切でない値を持つ引数を受け取ったときや、 @ref{174e,,IndexError} のようなより詳細な例外では記述できない状況で送出されます。
@end deffn

@geindex ZeroDivisionError
@anchor{library/exceptions ZeroDivisionError}@anchor{b3f}
@deffn {例外} ZeroDivisionError

除算や剰余演算の第二引数が 0 であった場合に送出されます。関連値は文字列で、その演算における被演算子と演算子の型を示します。
@end deffn

以下の例外は、過去のバージョンとの後方互換性のために残されています; Python 3.3 より、これらは @ref{2c0,,OSError} のエイリアスです。

@geindex EnvironmentError
@anchor{library/exceptions EnvironmentError}@anchor{125f}
@deffn {例外} EnvironmentError
@end deffn

@geindex IOError
@anchor{library/exceptions IOError}@anchor{125e}
@deffn {例外} IOError
@end deffn

@geindex WindowsError
@anchor{library/exceptions WindowsError}@anchor{1260}
@deffn {例外} WindowsError

Windows でのみ利用できます。
@end deffn

@menu
* OS 例外:: 

@end menu

@node OS 例外,,,具象例外
@anchor{library/exceptions os-exceptions}@anchor{26ee}
@subsubsection OS 例外


以下の例外は @ref{2c0,,OSError} のサブクラスで、システムエラーコードに依存して送出されます。

@geindex BlockingIOError
@anchor{library/exceptions BlockingIOError}@anchor{235}
@deffn {例外} BlockingIOError

ある操作が、ノンブロッキング操作に設定されたオブジェクト (例えばソケット) をブロックしそうになった場合に送出されます。@code{errno} @ref{26fd,,EAGAIN}, @ref{26fe,,EALREADY}, @ref{26ff,,EWOULDBLOCK} および @ref{2700,,EINPROGRESS} に対応します。

@ref{235,,BlockingIOError} は、 @ref{2c0,,OSError} の属性に加えて一つの属性を持ちます:

@geindex characters_written (BlockingIOError の属性)
@anchor{library/exceptions BlockingIOError characters_written}@anchor{2701}
@deffn {の属性} characters_written

An integer containing the number of `bytes' written to the stream
before it blocked. This attribute is available when using the
buffered I/O classes from the @ref{83,,io} module.
@end deffn
@end deffn

@geindex ChildProcessError
@anchor{library/exceptions ChildProcessError}@anchor{1263}
@deffn {例外} ChildProcessError

子プロセスの操作が失敗した場合に送出されます。@code{errno} @ref{2702,,ECHILD} に対応します。
@end deffn

@geindex ConnectionError
@anchor{library/exceptions ConnectionError}@anchor{100b}
@deffn {例外} ConnectionError

コネクション関係の問題の基底クラス。

サブクラスは @ref{1267,,BrokenPipeError}, @ref{1268,,ConnectionAbortedError}, @ref{1269,,ConnectionRefusedError}, @ref{126a,,ConnectionResetError} です。
@end deffn

@geindex BrokenPipeError
@anchor{library/exceptions BrokenPipeError}@anchor{1267}
@deffn {例外} BrokenPipeError

@ref{100b,,ConnectionError} のサブクラスで、もう一方の端が閉じられたパイプに書き込こもうとするか、書き込みのためにシャットダウンされたソケットに書き込こもうとした場合に発生します。 @code{errno}  @ref{2703,,EPIPE} と @ref{2704,,ESHUTDOWN} に対応します。
@end deffn

@geindex ConnectionAbortedError
@anchor{library/exceptions ConnectionAbortedError}@anchor{1268}
@deffn {例外} ConnectionAbortedError

@ref{100b,,ConnectionError} のサブクラスで、接続の試行が通信相手によって中断された場合に発生します。 @code{errno} @ref{2705,,ECONNABORTED} に対応します。
@end deffn

@geindex ConnectionRefusedError
@anchor{library/exceptions ConnectionRefusedError}@anchor{1269}
@deffn {例外} ConnectionRefusedError

@ref{100b,,ConnectionError} のサブクラスで、接続の試行が通信相手によって拒否された場合に発生します。 @code{errno} @ref{2706,,ECONNREFUSED} に対応します。
@end deffn

@geindex ConnectionResetError
@anchor{library/exceptions ConnectionResetError}@anchor{126a}
@deffn {例外} ConnectionResetError

@ref{100b,,ConnectionError} のサブクラスで、接続が通信相手によってリセットされた場合に発生します。 @code{errno} @ref{2707,,ECONNRESET} に対応します。
@end deffn

@geindex FileExistsError
@anchor{library/exceptions FileExistsError}@anchor{1221}
@deffn {例外} FileExistsError

すでに存在するファイルやディレクトリを作成しようとした場合に送出されます。@code{errno} @ref{2708,,EEXIST} に対応します。
@end deffn

@geindex FileNotFoundError
@anchor{library/exceptions FileNotFoundError}@anchor{264}
@deffn {例外} FileNotFoundError

要求されたファイルやディレクトリが存在しない場合に送出されます。@code{errno} @ref{2709,,ENOENT} に対応します。
@end deffn

@geindex InterruptedError
@anchor{library/exceptions InterruptedError}@anchor{f88}
@deffn {例外} InterruptedError

システムコールが入力信号によって中断された場合に送出されます。@code{errno} @ref{f87,,EINTR} に対応します。


バージョン 3.5 で変更: シグナルハンドラが例外を送出せず、システムコールが信号で中断された場合
Python は @ref{f88,,InterruptedError} を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください) 。

@end deffn

@geindex IsADirectoryError
@anchor{library/exceptions IsADirectoryError}@anchor{1264}
@deffn {例外} IsADirectoryError

ディレクトリに (@ref{1308,,os.remove()} などの) ファイル操作が要求された場合に送出されます。@code{errno} @ref{270a,,EISDIR} に対応します。
@end deffn

@geindex NotADirectoryError
@anchor{library/exceptions NotADirectoryError}@anchor{1265}
@deffn {例外} NotADirectoryError

ディレクトリへの操作(たとえば @ref{1312,,os.listdir()})をディレクトリ以外に対して要求された場合に送出されます。多くのPOSIXプラットフォームではディレクトリではないファイルをディレクトリとして開いたり移動するときにも発生する場合があります。@code{errno} @ref{270b,,ENOTDIR} に対応します。
@end deffn

@geindex PermissionError
@anchor{library/exceptions PermissionError}@anchor{f3e}
@deffn {例外} PermissionError

十分なアクセス権、例えばファイルシステム権限のない操作が試みられた場合に送出されます。@code{errno} @ref{270c,,EACCES}、@ref{1b56,,EPERM} および @ref{1b3f,,ENOTCAPABLE} に対応します。


バージョン 3.11.1 で変更: WASIの @ref{1b3f,,ENOTCAPABLE} は @ref{f3e,,PermissionError} にマップされました。

@end deffn

@geindex ProcessLookupError
@anchor{library/exceptions ProcessLookupError}@anchor{1266}
@deffn {例外} ProcessLookupError

与えられたプロセスが存在しない場合に送出されます。@code{errno} @ref{270d,,ESRCH} に対応します。
@end deffn

@geindex TimeoutError
@anchor{library/exceptions TimeoutError}@anchor{a36}
@deffn {例外} TimeoutError

システム関数がシステムレベルでタイムアウトした場合に送出されます。@code{errno} @ref{270e,,ETIMEDOUT} に対応します。
@end deffn


Added in version 3.3: 上記のすべての @ref{2c0,,OSError} サブクラスが追加されました。



@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 3151
PEP 3151@footnote{https://peps.python.org/pep-3151/} - OS および IO 例外階層の手直し


@node 警告,例外グループ,具象例外,組み込み例外
@anchor{library/exceptions warning-categories-as-exceptions}@anchor{270f}@anchor{library/exceptions warnings}@anchor{2710}
@subsection 警告


次の例外は警告カテゴリとして使われます。詳細については @ref{2711,,警告カテゴリ} のドキュメントを参照してください。

@geindex Warning
@anchor{library/exceptions Warning}@anchor{2712}
@deffn {例外} Warning

警告カテゴリの基底クラスです。
@end deffn

@geindex UserWarning
@anchor{library/exceptions UserWarning}@anchor{2713}
@deffn {例外} UserWarning

ユーザコードによって生成される警告の基底クラスです。
@end deffn

@geindex DeprecationWarning
@anchor{library/exceptions DeprecationWarning}@anchor{1a3}
@deffn {例外} DeprecationWarning

他の Python 開発者へ向けて警告を発するときの、廃止予定の機能についての警告の基底クラスです。

@code{__main__} モジュールを除いて(
@geindex Python Enhancement Proposals; PEP 565
PEP 565@footnote{https://peps.python.org/pep-0565/})、デフォルトの警告フィルターで無効化されています。@ref{508,,Python Development Mode} を有効にするとこの警告が表示されます。

The deprecation policy is described in 
@geindex Python Enhancement Proposals; PEP 387
PEP 387@footnote{https://peps.python.org/pep-0387/}.
@end deffn

@geindex PendingDeprecationWarning
@anchor{library/exceptions PendingDeprecationWarning}@anchor{ac5}
@deffn {例外} PendingDeprecationWarning

古くなって将来的に廃止される予定だが、今のところは廃止されていない機能についての警告の基底クラスです。

近々起こる可能性のある機能廃止について警告を発することはまれなので、このクラスはめったに使われず、既に決まっている廃止については @ref{1a3,,DeprecationWarning} が望ましいです。

デフォルトの警告フィルターで無効化されています。@ref{508,,Python Development Mode} を有効にするとこの警告が表示されます。

The deprecation policy is described in 
@geindex Python Enhancement Proposals; PEP 387
PEP 387@footnote{https://peps.python.org/pep-0387/}.
@end deffn

@geindex SyntaxWarning
@anchor{library/exceptions SyntaxWarning}@anchor{1ae}
@deffn {例外} SyntaxWarning

曖昧な構文に対する警告の基底クラスです。

This warning is typically emitted when compiling Python source code, and usually won't be reported
when running already compiled code.
@end deffn

@geindex RuntimeWarning
@anchor{library/exceptions RuntimeWarning}@anchor{4d7}
@deffn {例外} RuntimeWarning

あいまいなランタイム挙動に対する警告の基底クラスです。
@end deffn

@geindex FutureWarning
@anchor{library/exceptions FutureWarning}@anchor{659}
@deffn {例外} FutureWarning

Python で書かれたアプリケーションのエンドユーザーへ向けて警告を発するときの、廃止予定の機能についての警告の基底クラスです。
@end deffn

@geindex ImportWarning
@anchor{library/exceptions ImportWarning}@anchor{71e}
@deffn {例外} ImportWarning

モジュールインポートの誤りと思われるものに対する警告の基底クラスです。

デフォルトの警告フィルターで無効化されています。@ref{508,,Python Development Mode} を有効にするとこの警告が表示されます。
@end deffn

@geindex UnicodeWarning
@anchor{library/exceptions UnicodeWarning}@anchor{163d}
@deffn {例外} UnicodeWarning

Unicode に関連した警告の基底クラスです。
@end deffn

@geindex EncodingWarning
@anchor{library/exceptions EncodingWarning}@anchor{212e}
@deffn {例外} EncodingWarning

エンコーディングに関連した警告の基底クラスです。

詳細は @ref{2140,,Opt-in EncodingWarning} を参照してください。


Added in version 3.10.

@end deffn

@geindex BytesWarning
@anchor{library/exceptions BytesWarning}@anchor{e1c}
@deffn {例外} BytesWarning

@ref{192,,bytes} や @ref{344,,bytearray} に関連した警告の基底クラスです。
@end deffn

@geindex ResourceWarning
@anchor{library/exceptions ResourceWarning}@anchor{54c}
@deffn {例外} ResourceWarning

リソースの使用に関連した警告の基底クラスです。

デフォルトの警告フィルターで無効化されています。@ref{508,,Python Development Mode} を有効にするとこの警告が表示されます。


Added in version 3.2.

@end deffn

@node 例外グループ,例外のクラス階層,警告,組み込み例外
@anchor{library/exceptions exception-groups}@anchor{2714}@anchor{library/exceptions lib-exception-groups}@anchor{2715}
@subsection 例外グループ


以下は関係がない複数の例外を送出する必要があるときに使用します。例外グループは例外の階層構造の一部のため、他の例外と同様 @ref{1ab,,except} で処理できます。また、@ref{1ac,,except*} によって判別でき、例外グループに含まれている例外の型に基づいてサブグループにマッチします。

@geindex ExceptionGroup
@anchor{library/exceptions ExceptionGroup}@anchor{4d2}
@deffn {例外} ExceptionGroup (msg, excs)
@end deffn

@geindex BaseExceptionGroup
@anchor{library/exceptions BaseExceptionGroup}@anchor{566}
@deffn {例外} BaseExceptionGroup (msg, excs)

この2つの例外型は一連の例外 @code{excs} を包含します。@code{msg} 引数は文字列の必要があります。2つのクラスの異なる点は、@ref{7d6,,BaseException} は @ref{566,,BaseExceptionGroup} を拡張して任意の例外を含められますが、@ref{4d2,,ExceptionGroup} は @ref{bcd,,Exception} を拡張して @ref{bcd,,Exception} のサブクラスのみを含められます。この設計により @code{except Exception} は @ref{4d2,,ExceptionGroup} をキャッチしますが、@ref{566,,BaseExceptionGroup} はキャッチしません。

@ref{566,,BaseExceptionGroup} のコンストラクターは含まれる例外がすべて @ref{bcd,,Exception} の場合は @ref{566,,BaseExceptionGroup} ではなく @ref{4d2,,ExceptionGroup} を返すように自動的に選択されます。一方 @ref{4d2,,ExceptionGroup} コンストラクタは、@ref{bcd,,Exception} サブクラス以外の例外を含む場合は @ref{198,,TypeError} を送出します。

@geindex message (BaseExceptionGroup の属性)
@anchor{library/exceptions BaseExceptionGroup message}@anchor{2716}
@deffn {の属性} message

コンストラクタの @code{msg} 引数。この属性は読み込み専用です。
@end deffn

@geindex exceptions (BaseExceptionGroup の属性)
@anchor{library/exceptions BaseExceptionGroup exceptions}@anchor{2717}
@deffn {の属性} exceptions

コンストラクタに渡された一連の @code{excs} に含まれる例外のタプルです。この属性は読み込み専用です。
@end deffn

@geindex subgroup() (BaseExceptionGroup のメソッド)
@anchor{library/exceptions BaseExceptionGroup subgroup}@anchor{1a38}
@deffn {メソッド} subgroup (condition)

現在のグループで `条件' にマッチする礼儀のみを含む例外グループを返します。結果が空の場合は @code{None} を返します。

The condition can be an exception type or tuple of exception types, in which
case each exception is checked for a match using the same check that is used
in an @code{except} clause.  The condition can also be a callable (other than
a type object) that accepts an exception as its single argument and returns
true for the exceptions that should be in the subgroup.

The nesting structure of the current exception is preserved in the result,
as are the values of its @ref{2716,,message},
@ref{14de,,__traceback__}, @ref{14e0,,__cause__},
@ref{14df,,__context__} and
@ref{26e4,,__notes__} fields.
Empty nested groups are omitted from the result.

The condition is checked for all exceptions in the nested exception group,
including the top-level and any nested exception groups. If the condition is
true for such an exception group, it is included in the result in full.


Added in version 3.13: @code{condition} can be any callable which is not a type object.

@end deffn

@geindex split() (BaseExceptionGroup のメソッド)
@anchor{library/exceptions BaseExceptionGroup split}@anchor{18d8}
@deffn {メソッド} split (condition)

@ref{1a38,,subgroup()} と似てますが @code{(match, rest)} のペアを返します。@code{match} は @code{subgroup(condition)} で @code{rest} は残りのマッチしない部分です。
@end deffn

@geindex derive() (BaseExceptionGroup のメソッド)
@anchor{library/exceptions BaseExceptionGroup derive}@anchor{1a37}
@deffn {メソッド} derive (excs)

同じ @ref{2716,,message} の例外グループを返しますが、@code{excs} の例外を含んでいます。

This method is used by @ref{1a38,,subgroup()} and @ref{18d8,,split()}, which
are used in various contexts to break up an exception group. A
subclass needs to override it in order to make @ref{1a38,,subgroup()}
and @ref{18d8,,split()} return instances of the subclass rather
than @ref{4d2,,ExceptionGroup}.

@ref{1a38,,subgroup()} と @ref{18d8,,split()} は @ref{14de,,__traceback__}、@ref{14e0,,__cause__}、@ref{14df,,__context__} と @ref{26e4,,__notes__} フィールドを元の例外グループから @ref{1a37,,derive()} が返す例外グループにコピーするため、@ref{1a37,,derive()} ではこれらのフィールドを更新する必要がありません。

@example
>>> class MyGroup(ExceptionGroup):
...     def derive(self, excs):
...         return MyGroup(self.message, excs)
...
>>> e = MyGroup("eg", [ValueError(1), TypeError(2)])
>>> e.add_note("a note")
>>> e.__context__ = Exception("context")
>>> e.__cause__ = Exception("cause")
>>> try:
...    raise e
... except Exception as e:
...    exc = e
...
>>> match, rest = exc.split(ValueError)
>>> exc, exc.__context__, exc.__cause__, exc.__notes__
(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
>>> match, match.__context__, match.__cause__, match.__notes__
(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), ['a note'])
>>> rest, rest.__context__, rest.__cause__, rest.__notes__
(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
>>> exc.__traceback__ is match.__traceback__ is rest.__traceback__
True
@end example
@end deffn

Note that @ref{566,,BaseExceptionGroup} defines @ref{7a0,,__new__()}, so
subclasses that need a different constructor signature need to
override that rather than @ref{8bf,,__init__()}. For example, the following
defines an exception group subclass which accepts an exit_code and
constructs the group's message from it.

@example
class Errors(ExceptionGroup):
   def __new__(cls, errors, exit_code):
      self = super().__new__(Errors, f"exit code: @{exit_code@}", errors)
      self.exit_code = exit_code
      return self

   def derive(self, excs):
      return Errors(excs, self.exit_code)
@end example

Like @ref{4d2,,ExceptionGroup}, any subclass of @ref{566,,BaseExceptionGroup} which
is also a subclass of @ref{bcd,,Exception} can only wrap instances of
@ref{bcd,,Exception}.


Added in version 3.11.

@end deffn

@node 例外のクラス階層,,例外グループ,組み込み例外
@anchor{library/exceptions exception-hierarchy}@anchor{2718}
@subsection 例外のクラス階層


組み込み例外のクラス階層は以下のとおりです:

@example
BaseException
 ├── BaseExceptionGroup
 ├── GeneratorExit
 ├── KeyboardInterrupt
 ├── SystemExit
 └── Exception
      ├── ArithmeticError
      │    ├── FloatingPointError
      │    ├── OverflowError
      │    └── ZeroDivisionError
      ├── AssertionError
      ├── AttributeError
      ├── BufferError
      ├── EOFError
      ├── ExceptionGroup [BaseExceptionGroup]
      ├── 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
      │    ├── PythonFinalizationError
      │    └── RecursionError
      ├── StopAsyncIteration
      ├── StopIteration
      ├── SyntaxError
      │    └── IndentationError
      │         └── TabError
      ├── SystemError
      ├── TypeError
      ├── ValueError
      │    └── UnicodeError
      │         ├── UnicodeDecodeError
      │         ├── UnicodeEncodeError
      │         └── UnicodeTranslateError
      └── Warning
           ├── BytesWarning
           ├── DeprecationWarning
           ├── EncodingWarning
           ├── FutureWarning
           ├── ImportWarning
           ├── PendingDeprecationWarning
           ├── ResourceWarning
           ├── RuntimeWarning
           ├── SyntaxWarning
           ├── UnicodeWarning
           └── UserWarning
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)
@anchor{library/text stringservices}@anchor{2650}
@node テキスト処理サービス,バイナリデータ処理,組み込み例外,Python 標準ライブラリ
@anchor{library/text doc}@anchor{2719}@anchor{library/text text-processing-services}@anchor{271a}@anchor{library/text textservices}@anchor{2652}@anchor{library/text translation-repo}@anchor{271b}
@section テキスト処理サービス


この章で説明するモジュールは幅広い文字列操作や様々なテキスト処理サービスを提供しています。

@ref{1c,,codecs} モジュールはテキスト処理と高い関連性を持った @ref{271c,,バイナリデータ処理} のなかで説明されています。加えて Python の組み込み文字列型の @ref{1fe0,,テキストシーケンス型 --- str} のドキュメントも参照して下さい。

@menu
* string: string --- 一般的な文字列操作. 一般的な文字列操作
* string.templatelib: string templatelib --- テンプレート文字列リテラルのサポート. テンプレート文字列リテラルのサポート
* re: re --- 正規表現操作. 正規表現操作
* difflib: difflib --- 差分の計算の補助. 差分の計算の補助
* textwrap: textwrap --- テキストの折り返しと詰め込み. テキストの折り返しと詰め込み
* unicodedata: unicodedata --- Unicode データベース. Unicode データベース
* stringprep: stringprep --- インターネットの文字列調製. インターネットの文字列調製
* readline: readline --- GNU readline のインターフェース. GNU readline のインターフェース
* rlcompleter: rlcompleter --- GNU readline の補完機能. GNU readline の補完機能

@end menu

@node string --- 一般的な文字列操作,string templatelib --- テンプレート文字列リテラルのサポート,,テキスト処理サービス
@anchor{library/string doc}@anchor{271d}@anchor{library/string module-string}@anchor{d8}@anchor{library/string string-common-string-operations}@anchor{271e}
@subsection @code{string} --- 一般的な文字列操作


@geindex module; string

`Source code:' Lib/string/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/string/__init__.py}


__________________________________________________________________



@subsubheading 参考


@ref{1fe0,,テキストシーケンス型 --- str}

@ref{1fe1,,文字列メソッド}


@menu
* 文字列定数:: 
* カスタムの文字列書式化:: 
* 書式指定文字列の文法:: 
* Template strings ($-strings): Template strings $-strings. 
* ヘルパー関数:: 

@end menu

@node 文字列定数,カスタムの文字列書式化,,string --- 一般的な文字列操作
@anchor{library/string string-constants}@anchor{271f}
@subsubsection 文字列定数


このモジュールで定義されている定数は以下の通りです:

@geindex ascii_letters (string モジュール)
@anchor{library/string string ascii_letters}@anchor{14db}
@deffn {データ} string.ascii_letters

後述の @ref{2720,,ascii_lowercase} と @ref{2721,,ascii_uppercase} を合わせたもの。この値はロケールに依存しません。
@end deffn

@geindex ascii_lowercase (string モジュール)
@anchor{library/string string ascii_lowercase}@anchor{2720}
@deffn {データ} string.ascii_lowercase

小文字 @code{'abcdefghijklmnopqrstuvwxyz'} 。この値はロケールに依存せず、固定です。
@end deffn

@geindex ascii_uppercase (string モジュール)
@anchor{library/string string ascii_uppercase}@anchor{2721}
@deffn {データ} string.ascii_uppercase

大文字 @code{'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} 。この値はロケールに依存せず、固定です。
@end deffn

@geindex digits (string モジュール)
@anchor{library/string string digits}@anchor{2722}
@deffn {データ} string.digits

文字列 @code{'0123456789'} です。
@end deffn

@geindex hexdigits (string モジュール)
@anchor{library/string string hexdigits}@anchor{2723}
@deffn {データ} string.hexdigits

文字列 @code{'0123456789abcdefABCDEF'} です。
@end deffn

@geindex octdigits (string モジュール)
@anchor{library/string string octdigits}@anchor{2724}
@deffn {データ} string.octdigits

文字列 @code{'01234567'} です。
@end deffn

@geindex punctuation (string モジュール)
@anchor{library/string string punctuation}@anchor{2725}
@deffn {データ} string.punctuation

@code{C} ロケールにおいて、区切り文字 (punctuation characters) として扱われる ASCII 文字の文字列です: @code{!"#$%&'()*+,-./:;<=>?@@[\]^_`@{|@}~}.
@end deffn

@geindex printable (string モジュール)
@anchor{library/string string printable}@anchor{18b7}
@deffn {データ} string.printable

String of ASCII characters which are considered printable by Python.
This is a combination of @ref{2722,,digits}, @ref{14db,,ascii_letters},
@ref{2725,,punctuation}, and @ref{2726,,whitespace}.

@cartouche
@quotation 注釈 
By design, @ref{fd8,,string.printable.isprintable()}
returns @ref{d2b,,False}. In particular, @code{string.printable} is not
printable in the POSIX sense (see @code{LC_CTYPE@footnote{https://manpages.debian.org/locale(5)}}).
@end quotation
@end cartouche
@end deffn

@geindex whitespace (string モジュール)
@anchor{library/string string whitespace}@anchor{2726}
@deffn {データ} string.whitespace

空白 (whitespace) として扱われる ASCII 文字全てを含む文字列です。ほとんどのシステムでは、これはスペース (space)、タブ (tab)、改行 (linefeed)、復帰 (return)、改頁 (formfeed)、垂直タブ (vertical tab) です。
@end deffn

@node カスタムの文字列書式化,書式指定文字列の文法,文字列定数,string --- 一般的な文字列操作
@anchor{library/string custom-string-formatting}@anchor{2727}@anchor{library/string string-formatting}@anchor{264f}
@subsubsection カスタムの文字列書式化


The built-in string class provides the ability to do complex variable
substitutions and value formatting via the @ref{833,,format()} method described in
@geindex Python Enhancement Proposals; PEP 3101
PEP 3101@footnote{https://peps.python.org/pep-3101/}.  The @ref{10bd,,Formatter} class in the @code{string} module allows
you to create and customize your own string formatting behaviors using the same
implementation as the built-in @ref{833,,format()} method.

@geindex Formatter (string のクラス)
@anchor{library/string string Formatter}@anchor{10bd}
@deffn {クラス} string.Formatter

@ref{10bd,,Formatter} クラスは、以下のメソッドを持ちます:

@geindex format() (string.Formatter のメソッド)
@anchor{library/string string Formatter format}@anchor{dfa}
@deffn {メソッド} format (format_string, /, *args, **kwargs)

主要な API メソッドです。書式文字列と、任意の位置引数およびキーワード引数のセットを取ります。これは、@ref{2728,,vformat()} を呼び出す単なるラッパーです。


バージョン 3.7 で変更: 書式文字列は @ref{c78,,位置専用} の引数となりました。

@end deffn

@geindex vformat() (string.Formatter のメソッド)
@anchor{library/string string Formatter vformat}@anchor{2728}
@deffn {メソッド} vformat (format_string, args, kwargs)

この関数はフォーマットの実際の仕事をします。この関数は、 @code{*args} および @code{**kwargs} シンタックスを使用して、辞書を個々の引数として unpack してから再度 pack するのではなく、引数としてあらかじめ用意した辞書を渡したい場合のために、独立した関数として公開されます。 @ref{2728,,vformat()} は、書式文字列を文字データと置換フィールドに分解する仕事をします。それは、以下に記述する様々なメソッドを呼び出します。
@end deffn

さらに、 @ref{10bd,,Formatter} ではサブクラスによって置き換えられることを意図した次のようないくつかのメソッドが定義されています。

@geindex parse() (string.Formatter のメソッド)
@anchor{library/string string Formatter parse}@anchor{2729}
@deffn {メソッド} parse (format_string)

format_stringを探査し、タプル、 (`literal_text', `field_name', `format_spec', `conversion') のイテラブルを返します。これは @ref{2728,,vformat()} が文字列を文字としての文字データや置換フィールドに展開するために使用されます。

The values in the tuple conceptually represent a span of literal text
followed by a single replacement field.  If there is no literal text
(which can happen if two replacement fields occur consecutively), then
`literal_text' will be a zero-length string.  If there is no replacement
field, then the values of `field_name', `format_spec' and `conversion'
will be @code{None}. The value of `field_name' is unmodified and
auto-numbering of non-numbered positional fields is done by @ref{2728,,vformat()}.
@end deffn

@geindex get_field() (string.Formatter のメソッド)
@anchor{library/string string Formatter get_field}@anchor{272a}
@deffn {メソッド} get_field (field_name, args, kwargs)

Given `field_name', convert it to an object to be formatted.
Auto-numbering of `field_name' returned from @ref{2729,,parse()} is done by
@ref{2728,,vformat()} before calling this method.  Returns a tuple (obj, used_key).
The default version takes strings of the form defined in 
@geindex Python Enhancement Proposals; PEP 3101
PEP 3101@footnote{https://peps.python.org/pep-3101/},
such as "0[name]" or "label.title". `args' and `kwargs' are as passed in to
@ref{2728,,vformat()}. The return value `used_key' has the same meaning
as the `key' parameter to @ref{272b,,get_value()}.
@end deffn

@geindex get_value() (string.Formatter のメソッド)
@anchor{library/string string Formatter get_value}@anchor{272b}
@deffn {メソッド} get_value (key, args, kwargs)

与えられたフィールドの値を取り出します。 `key' 引数は整数でも文字列でも構いません。整数の場合は、位置引数 `args' のインデックス番号を示します。文字列の場合は、名前付きの引数 `kwargs' を意味します。

`args' 引数は、 @ref{2728,,vformat()} への位置引数のリストに設定され、 `kwargs' 引数は、キーワード引数の辞書に設定されます。

フィールド名が (ピリオドで区切られた) いくつかの要素からなっている場合、最初の要素のみがこれらの関数に渡されます。残りの要素に関しては、通常の属性またはインデックスアクセスと同様に処理されます。

つまり、例えば、フィールドが '0.name' と表現されるとき、 @ref{272b,,get_value()} は、 `key' 引数が 0 として呼び出されます。属性 @code{name} は、組み込みの @ref{dca,,getattr()} 関数が呼び出され、 @ref{272b,,get_value()} が返されたのちに検索されます。

インデックスまたはキーワードが存在しないアイテムを参照した場合、 @ref{174e,,IndexError} または @ref{5e7,,KeyError} が送出されます。
@end deffn

@geindex check_unused_args() (string.Formatter のメソッド)
@anchor{library/string string Formatter check_unused_args}@anchor{272c}
@deffn {メソッド} check_unused_args (used_args, args, kwargs)

希望に応じて未使用の引数がないか確認する機能を実装します。この関数への引数は、書式指定文字列で実際に参照されるすべての引数のキーの set (位置引数の整数、名前付き引数の文字列) と、vformat に渡される `args' と `kwargs' への参照です。使用されない引数の set は、これらのパラメータから計算されます。 @ref{272c,,check_unused_args()} は、確認の結果が偽である場合に例外を送出するものとみなされます。
@end deffn

@geindex format_field() (string.Formatter のメソッド)
@anchor{library/string string Formatter format_field}@anchor{272d}
@deffn {メソッド} format_field (value, format_spec)

@ref{272d,,format_field()} は単純に組み込みのグローバル関数 @ref{199,,format()} を呼び出します。このメソッドは、サブクラスをオーバーライドするために提供されます。
@end deffn

@geindex convert_field() (string.Formatter のメソッド)
@anchor{library/string string Formatter convert_field}@anchor{272e}
@deffn {メソッド} convert_field (value, conversion)

(@ref{272a,,get_field()} が返す) 値を (@ref{2729,,parse()} メソッドが返すタプルの形式で) 与えられた変換タイプとして変換します。デフォルトバージョンは 's' (str), 'r' (repr), 'a' (ascii) 変換タイプを理解します。
@end deffn
@end deffn

@node 書式指定文字列の文法,Template strings $-strings,カスタムの文字列書式化,string --- 一般的な文字列操作
@anchor{library/string format-string-syntax}@anchor{272f}@anchor{library/string formatstrings}@anchor{15b3}
@subsubsection 書式指定文字列の文法


The @ref{833,,str.format()} method and the @ref{10bd,,Formatter} class share the same
syntax for format strings (although in the case of @ref{10bd,,Formatter},
subclasses can define their own format string syntax).  The syntax is
related to that of @ref{19a,,formatted string literals} and
@ref{17fa,,template string literals}, but it is less sophisticated
and, in particular, does not support arbitrary expressions in interpolations.

@geindex @{@} (波括弧);文字列のフォーマットで
@geindex . (ドット);文字列のフォーマットで
@geindex [] (角カッコ);文字列のフォーマットで
@geindex ! (エクスクラメーション);文字列のフォーマットで
@geindex ; (コロン);文字列のフォーマットで

書式指定文字列は波括弧 @code{@{@}} に囲まれた "置換フィールド" を含みます。波括弧に囲まれた部分以外は全て単純な文字として扱われ、変更を加えることなく出力へコピーされます。波括弧を文字として扱う必要がある場合は、二重にすることでエスケープすることができます: @code{@{@{} および @code{@}@}} 。

置換フィールドの文法は以下です:

@example
@anchor{library/string grammar-token-format-string-replacement_field}@anchor{2730}replacement_field: "@{" [@ref{2731,,field_name}] ["!" @ref{2732,,conversion}] [":" @ref{2733,,format_spec}] "@}"
@anchor{library/string grammar-token-format-string-field_name}@anchor{2731}field_name:        @ref{2734,,arg_name} ("." @ref{2735,,attribute_name} | "[" @ref{2736,,element_index} "]")*
@anchor{library/string grammar-token-format-string-arg_name}@anchor{2734}arg_name:          [@ref{22c1,,identifier} | @ref{2312,,digit}+]
@anchor{library/string grammar-token-format-string-attribute_name}@anchor{2735}attribute_name:    @ref{22c1,,identifier}
@anchor{library/string grammar-token-format-string-element_index}@anchor{2736}element_index:     @ref{2312,,digit}+ | @ref{2737,,index_string}
@anchor{library/string grammar-token-format-string-index_string}@anchor{2737}index_string:      <any source character except "]"> +
@anchor{library/string grammar-token-format-string-conversion}@anchor{2732}conversion:        "r" | "s" | "a"
@anchor{library/string grammar-token-format-string-format_spec}@anchor{2733}format_spec:       @ref{2738,,format-spec;format_spec}
@end example

もっと簡単にいうと、置換フィールドは `field_name' で始められます。これによって指定したオブジェクトの値が、置換フィールドの代わりに書式化され出力に挿入されます。`field_name' の後に、感嘆符 @code{'!'} を挟んで `conversion' フィールドを続けることができます。最後にコロン @code{':'} を挟んで、 `format_spec' を書くことができます。これは、置換される値の非デフォルトの書式を指定します。

@ref{4f9,,書式指定ミニ言語仕様} 節も参照して下さい。

`field_name' それ自身は、数かキーワードのいずれかである `arg_name' から始まります。それが数である場合、位置引数を参照します。また、それがキーワードである場合、指定されたキーワード引数を参照します。文字列に対して @ref{262d,,str.isdecimal()} を呼び出した結果が真の場合、 `arg_name' は数として扱われます。書式文字列中で数の arg_names が順に 0, 1, 2, ... である場合、それらはすべて (いくつかではありません) 省略することができます。そして数 0, 1, 2, ... は、自動的にその順で挿入されます。 `arg_name' は引用符で区切られていないので、書式文字列内の任意の辞書キー (例えば文字列 @code{'10'} や @code{':-]'} など) を指定することはできません。 `arg_name' の後に任意の数のインデックス式または属性式を続けることができます。 @code{'.name'} 形式の式は @ref{dca,,getattr()} を使用して指定された属性を選択します。一方、 @code{'[index]'} 形式の式は @ref{588,,__getitem__()} を使用してインデックス参照を行います。


バージョン 3.1 で変更: @ref{833,,str.format()} を使い、位置引数指定を省略することができます。
@code{'@{@} @{@}'.format(a, b)} は @code{'@{0@} @{1@}'.format(a, b)} と同じになります。



バージョン 3.4 で変更: @ref{10bd,,Formatter} を使い、位置引数指定を省略することができます。


簡単な書式指定文字列の例を挙げます:

@example
"First, thou shalt count to @{0@}"  # References first positional argument
"Bring me a @{@}"                   # Implicitly references the first positional argument
"From @{@} to @{@}"                   # Same as "From @{0@} to @{1@}"
"My quest is @{name@}"              # References keyword argument 'name'
"Weight in tons @{0.weight@}"       # 'weight' attribute of first positional arg
"Units destroyed: @{players[0]@}"   # First element of keyword argument 'players'.
@end example
@anchor{library/string formatstrings-conversion}@anchor{2739}
`置換 (conversion)' フィールドにより書式変換前に型の強制変換が実施されます。通常、値の書式変換は @ref{831,,__format__()} によって実施されます。しかしながら、場合によっては、文字列として変換することを強制したり、書式指定の定義をオーバーライドしたくなることもあります。 @ref{831,,__format__()} の呼び出し前に値を文字列に変換すると、通常の書式変換の処理は飛ばされます。

現在 3つの変換フラグがサポートされています: 値に対して @ref{169,,str()} を呼ぶ @code{'!s'} 、 @ref{1c1,,repr()} を呼ぶ @code{'!r'} 、 @ref{15ff,,ascii()} を呼ぶ @code{'!a'}。

いくつかの例です:

@example
"Harold's a clever @{0!s@}"        # Calls str() on the argument first
"Bring out the holy @{name!r@}"    # Calls repr() on the argument first
"More @{!a@}"                      # Calls ascii() on the argument first
@end example

`format_spec' フィールドは、フィールド幅、文字揃え、埋め方、精度などの、値を表現する仕様を含みます。それぞれの値の型は、 "formatting mini-language" 、または、 `format_spec' の実装で定義されます。

ほとんどの組み込み型は、次のセクションに記載された共通の formatting mini-language をサポートします。

`format_spec' フィールド内には入れ子になった置換フィールドを含めることもできます。入れ子になった置換フィールドにはフィールド名、変換フラグ、書式指定を含めることができますが、さらに入れ子の階層を含めることはできません。 format_spec 中の置換フィールドは `format_spec' 文字列が解釈される前に置き換えられます。これにより、値の書式を動的に指定することができます。

@ref{273a,,書式指定例} のいくつかの例も参照して下さい。

@menu
* 書式指定ミニ言語仕様:: 
* 書式指定例:: 

@end menu

@node 書式指定ミニ言語仕様,書式指定例,,書式指定文字列の文法
@anchor{library/string format-specification-mini-language}@anchor{273b}@anchor{library/string formatspec}@anchor{4f9}
@subsubsection 書式指定ミニ言語仕様


"Format specifications" are used within replacement fields contained within a
format string to define how individual values are presented (see
@ref{15b3,,書式指定文字列の文法}, @ref{19a,,f-strings}, and @ref{17fa,,t-strings}).
They can also be passed directly to the built-in
@ref{199,,format()} function.  Each formattable type may define how the format
specification is to be interpreted.

多くの組み込み型は、書式指定に関して以下のオプションを実装します。しかしながら、いくつかの書式指定オプションは数値型でのみサポートされます。

一般的な取り決めとして、空の書式指定は、値に対して @ref{169,,str()} を呼び出したときと同じ結果を与えます。通常、空でない書式指定はその結果を変更します。

一般的な書式指定子 (`standard format specifier') の書式は以下です:

@example
@anchor{library/string grammar-token-format-spec-format_spec}@anchor{2738}format_spec:             [@ref{273c,,options}][@ref{273d,,width_and_precision}][@ref{273e,,type}]
@anchor{library/string grammar-token-format-spec-options}@anchor{273c}options:                 [[@ref{273f,,fill}]@ref{2740,,align}][@ref{2741,,sign}]["z"]["#"]["0"]
@anchor{library/string grammar-token-format-spec-fill}@anchor{273f}fill:                    <any character>
@anchor{library/string grammar-token-format-spec-align}@anchor{2740}align:                   "<" | ">" | "=" | "^"
@anchor{library/string grammar-token-format-spec-sign}@anchor{2741}sign:                    "+" | "-" | " "
@anchor{library/string grammar-token-format-spec-width_and_precision}@anchor{273d}width_and_precision:     [@ref{2742,,width_with_grouping}][@ref{2743,,precision_with_grouping}]
@anchor{library/string grammar-token-format-spec-width_with_grouping}@anchor{2742}width_with_grouping:     [@ref{2744,,width}][@ref{2745,,grouping}]
@anchor{library/string grammar-token-format-spec-precision_with_grouping}@anchor{2743}precision_with_grouping: "." [@ref{2746,,precision}][@ref{2745,,grouping}] | "." @ref{2745,,grouping}
@anchor{library/string grammar-token-format-spec-width}@anchor{2744}width:                   @ref{2312,,digit}+
@anchor{library/string grammar-token-format-spec-precision}@anchor{2746}precision:               @ref{2312,,digit}+
@anchor{library/string grammar-token-format-spec-grouping}@anchor{2745}grouping:                "," | "_"
@anchor{library/string grammar-token-format-spec-type}@anchor{273e}type:                    "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g"
                         | "G" | "n" | "o" | "s" | "x" | "X" | "%"
@end example

有効な `align' 値を指定する場合、その前に `fill' 文字を付けることができます。
この文字には任意の文字を指定でき、省略された場合はデフォルトの空白文字となります。
@ref{19a,,formatted string literal} の中や @ref{833,,str.format()} メソッドを使う場合はリテラルの波括弧 ("@code{@{}" と "@code{@}}") を `fill' 文字として使えないことに注意してください。
ただし、波括弧を入れ子になった置換フィールド内に挿入することはできます。
この制限は @ref{199,,format()} 関数には影響しません。

様々な align オプションの意味は以下のとおりです:

@geindex < (小さい);文字列のフォーマットで
@geindex > (大きい);文字列のフォーマットで
@geindex = (等号);文字列のフォーマットで
@geindex ^ (キャレット);文字列のフォーマットで


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

意味

@item

@code{'<'}

@tab

利用可能なスペースにおいて、左詰めを強制します (ほとんどのオブジェクトにおいてのデフォルト)。

@item

@code{'>'}

@tab

利用可能なスペースにおいて、右詰めを強制します (いくつかのオブジェクトにおいてのデフォルト)。

@item

@code{'='}

@tab

Forces the padding to be placed after the sign (if any)
but before the digits.  This is used for printing fields
in the form '+000000120'. This alignment option is only
valid for numeric types, excluding @ref{197,,complex}.
It becomes the default for numbers when '0' immediately
precedes the field width.

@item

@code{'^'}

@tab

利用可能なスペースにおいて、中央寄せを強制します。

@end multitable


最小のフィールド幅が定義されない限り、フィールド幅はデータを表示するために必要な幅と同じになることに注意して下さい。そのため、その場合には、 align オプションは意味を持ちません。

`sign' オプションは数値型に対してのみ有効であり、以下のうちのひとつとなります:

@geindex + (プラス記号);文字列のフォーマットで
@geindex - (負符号);文字列のフォーマットで
@geindex 空白;文字列のフォーマットで


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

意味

@item

@code{'+'}

@tab

Indicates that a sign should be used for both
positive as well as negative numbers.

@item

@code{'-'}

@tab

Indicates that a sign should be used only for negative
numbers (this is the default behavior).

@item

空白

@tab

Indicates that a leading space should be used on
positive numbers, and a minus sign on negative numbers.

@end multitable


@geindex z;文字列のフォーマットで

@code{'z'} オプションはマイナス0の浮動小数点数をフォーマットの制度で丸めたあとにプラス0に強制的に変換します。このオプションは浮動小数点数型に対してのみ有効です。


バージョン 3.11 で変更: @code{'z'} オプションが追加されました (
@geindex Python Enhancement Proposals; PEP 682
PEP 682@footnote{https://peps.python.org/pep-0682/} も参照)。


@geindex # (hash);文字列のフォーマットで

@code{'#'} オプションは、変換に「別形式」を使用します。別形式は、異なる型に対して違った風に定義されます。このオプションは、整数、浮動小数点数、複素数でのみ有効です。整数に対して2進法、8進法、または16進法の出力が使用される場合、このオプションは出力される値にそれぞれ @code{'0b'}, @code{'0o'}, @code{'0x'}, @code{'0X'} 接頭辞を加えます。浮動小数点数、複素数については、別形式では、小数点文字の後に数字がなくても変換結果には常に小数点文字が含まれます。通常は、数字が続く場合にのみ小数点文字がこれらの変換結果に現われます。さらに、@code{'g'} と @code{'G'} の変換については、最後の 0 は結果から取り除かれません。

The `width' is a decimal integer defining the minimum total field width,
including any prefixes, separators, and other formatting characters.
If not specified, then the field width will be determined by the content.

When no explicit alignment is given, preceding the `width' field by a zero
(@code{'0'}) character enables sign-aware zero-padding for numeric types,
excluding @ref{197,,complex}.  This is equivalent to a `fill' character of
@code{'0'} with an `alignment' type of @code{'='}.


バージョン 3.10 で変更: `width' フィールドに @code{'0'} を前置することは、文字列に対するデフォルトの整列に影響を与えなくなりました。


`precision' は、表現型 @code{'f'} または @code{'F'} の場合小数点以下、表現型 @code{'g'} または @code{'G'} の場合は小数点以上と以下が何桁で表示されるべきかを示す10進整数です。文字列の表現型の場合は最大フィールド幅、言い換えるとフィールドの内容から何文字が使用されるかを示します。`precision' は整数の表現型には使用できません。

The `grouping' option after `width' and `precision' fields specifies
a digit group separator for the integral and fractional parts
of a number respectively. It can be one of the following:

@geindex @comma{} (カンマ);文字列のフォーマットで
@geindex _ (下線);文字列のフォーマットで


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

意味

@item

@code{','}

@tab

Inserts a comma every 3 digits for
integer presentation type @code{'d'} and
floating-point presentation types, excluding @code{'n'}.
For other presentation types,
this option is not supported.

@item

@code{'_'}

@tab

Inserts an underscore every 3 digits for
integer presentation type @code{'d'} and
floating-point presentation types, excluding @code{'n'}.
For integer presentation types
@code{'b'}, @code{'o'}, @code{'x'}, and @code{'X'},
underscores are inserted every 4 digits.
For other presentation types,
this option is not supported.

@end multitable


For a locale aware separator, use the @code{'n'} presentation type instead.


バージョン 3.1 で変更: @code{','} オプションが追加されました (
@geindex Python Enhancement Proposals; PEP 378
PEP 378@footnote{https://peps.python.org/pep-0378/} も参照)。



バージョン 3.6 で変更: @code{'_'} オプションが追加されました (
@geindex Python Enhancement Proposals; PEP 515
PEP 515@footnote{https://peps.python.org/pep-0515/} も参照)。



バージョン 3.14 で変更: Support the `grouping' option for the fractional part.


最後に、`type' は、データがどのように表現されるかを決定します。

利用可能な文字列の表現型は以下です:

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

型

@tab

意味

@item

@code{'s'}

@tab

文字列。これがデフォルトの値で、多くの場合省略されます。

@item

None

@tab

@code{'s'} と同じです。

@end multitable

@end quotation

利用可能な整数の表現型は以下です:

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

型

@tab

意味

@item

@code{'b'}

@tab

2進数。出力される数値は2を基数とします。

@item

@code{'c'}

@tab

文字。数値を対応する Unicode 文字に変換します。

@item

@code{'d'}

@tab

10進数。出力される数値は10を基数とします。

@item

@code{'o'}

@tab

8進数。出力される数値は8を基数とします。

@item

@code{'x'}

@tab

16進数。出力される数値は16を基数とします。 10進で9を超える数字には小文字が使われます。

@item

@code{'X'}

@tab

16進数。出力される数値は16を基数とします。10進で9を超える数字には大文字が使われます。@code{'#'} が指定された場合、接頭辞 @code{'0x'} も大文字 @code{'0X'} になります

@item

@code{'n'}

@tab

Number. This is the same as @code{'d'}, except that it uses
the current locale setting to insert the appropriate
digit group separators.

@item

None

@tab

@code{'d'} と同じです。

@end multitable

@end quotation

これらの表現型に加えて、整数は (@code{'n'} と @code{None} を除く) 以下の浮動小数点数の表現型で書式指定できます。
そうすることで整数は書式変換される前に @ref{196,,float()} を使って浮動小数点数に変換されます。

利用可能な @ref{196,,float} と @ref{1fe,,Decimal} の表現型は以下です:

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

型

@tab

意味

@item

@code{'e'}

@tab

Scientific notation. For a given precision @code{p},
formats the number in scientific notation with the
letter 'e' separating the coefficient from the exponent.
The coefficient has one digit before and @code{p} digits
after the decimal point, for a total of @code{p + 1}
significant digits. With no precision given, uses a
precision of @code{6} digits after the decimal point for
@ref{196,,float}, and shows all coefficient digits
for @ref{1fe,,Decimal}.  If @code{p=0}, the decimal
point is omitted unless the @code{#} option is used.

For @ref{196,,float}, the exponent always contains at
least two digits, and is zero if the value is zero.

@item

@code{'E'}

@tab

指数表記です。大文字の 'E' を使うことを除いては、 @code{'e'} と同じです。

@item

@code{'f'}

@tab

Fixed-point notation. For a given precision @code{p},
formats the number as a decimal number with exactly
@code{p} digits following the decimal point. With no
precision given, uses a precision of @code{6} digits after
the decimal point for @ref{196,,float}, and uses a
precision large enough to show all coefficient digits
for @ref{1fe,,Decimal}.  If @code{p=0}, the decimal
point is omitted unless the @code{#} option is used.

@item

@code{'F'}

@tab

固定小数点数表記です。@code{nan} が @code{NAN} に、@code{inf} が @code{INF} に変換されることを除き @code{'f'} と同じです。

@item

@code{'g'}

@tab

汎用表記です。与えられた精度 @code{p >= 1} に対して、この表記では数値を有効桁数 @code{p} に丸めた上で、数値の大きさに応じて固定小数点表記または科学的表記で表します。精度 @code{0} は精度 @code{1} と同じものと取り扱われます。

正確なルールは次の通りです: 書式 @code{'e'} 型および精度 @code{p-1} 桁で数値をフォーマットした結果、指数部が @code{exp} になったと仮定します。このとき @code{m <= exp < p} ならば、数値は書式 @code{'f'} 型および精度 @code{p-1-exp} 桁でフォーマットされます。ただし @code{m} は浮動小数点数では -4 であり、  @ref{1fe,,Decimals} に対しては -6 です。それ以外の場合、数値は書式 @code{'e'} 型および精度 @code{p-1} 桁でフォーマットされます。どちらの場合でも、仮数部の有効でない末尾のゼロは取り除かれます。また小数点以下に表示する桁が無い場合、 @code{'#'} オプションが使われた場合をのぞき、小数点は除去されます。

精度が指定されない場合、 @ref{196,,float} に対しては有効桁数として @code{6} 桁を適用します。  @ref{1fe,,Decimal} では、フォーマット結果の係数部は実際の値の桁数によって決まります; 絶対値が @code{1e-6} より小さい値や、最下位桁の値が1より大きい値では科学的表記が使われます。それ以外の場合は固定小数点表記が使われます。

正と負の無限大と 0 および NaN は精度に関係なくそれぞれ @code{inf}, @code{-inf}, @code{0}, @code{-0} および @code{nan} となります。

@item

@code{'G'}

@tab

汎用フォーマットです。数値が大きくなったとき、 @code{'E'} に切り替わることを除き、 @code{'g'} と同じです。無限大と NaN の表示も大文字になります。

@item

@code{'n'}

@tab

Number. This is the same as @code{'g'}, except that it uses
the current locale setting to insert the appropriate
digit group separators
for the integral part of a number.

@item

@code{'%'}

@tab

パーセンテージです。数値は 100 倍され、固定小数点数フォーマット (@code{'f'}) でパーセント記号付きで表示されます。

@item

None

@tab

For @ref{196,,float} this is like the @code{'g'} type, except
that when fixed-point notation is used to format the
result, it always includes at least one digit past the
decimal point, and switches to the scientific notation
when @code{exp >= p - 1}.  When the precision is not
specified, the latter will be as large as needed to
represent the given value faithfully.

@ref{1fe,,Decimal} に対しては、現在の decimal コンテキストにおける @code{context.capitals} の値に応じて、 @code{'g'} か @code{'G'} のどちらかと同じになります。

全体として、他の書式修正指定によって変更された @ref{169,,str()} の出力に一致するような結果になります。

@end multitable

@end quotation

The result should be correctly rounded to a given precision @code{p} of digits
after the decimal point.  The rounding mode for @ref{196,,float} matches that
of the @ref{14f2,,round()} builtin.  For @ref{1fe,,Decimal}, the rounding
mode of the current @ref{2747,,context} will be used.

The available presentation types for @ref{197,,complex} are the same as those for
@ref{196,,float} (@code{'%'} is not allowed).  Both the real and imaginary components
of a complex number are formatted as floating-point numbers, according to the
specified presentation type.  They are separated by the mandatory sign of the
imaginary part, the latter being terminated by a @code{j} suffix.  If the presentation
type is missing, the result will match the output of @ref{169,,str()} (complex numbers with
a non-zero real part are also surrounded by parentheses), possibly altered by
other format modifiers.

@node 書式指定例,,書式指定ミニ言語仕様,書式指定文字列の文法
@anchor{library/string format-examples}@anchor{2748}@anchor{library/string formatexamples}@anchor{273a}
@subsubsection 書式指定例


この節では、 @ref{833,,str.format()} 構文の例を紹介し、さらに従来の @code{%}-書式と比較します。

多くの場合、新構文に @code{@{@}} を加え、 @code{%} の代わりに @code{:} を使うことで、古い @code{%}-書式に類似した書式になります。例えば、@code{'%03.2f'} は @code{'@{:03.2f@}'} と変換できます。

以下の例で示すように、新構文はさらに新たに様々なオプションもサポートしています。

位置引数を使ったアクセス:

@example
>>> '@{0@}, @{1@}, @{2@}'.format('a', 'b', 'c')
'a, b, c'
>>> '@{@}, @{@}, @{@}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '@{2@}, @{1@}, @{0@}'.format('a', 'b', 'c')
'c, b, a'
>>> '@{2@}, @{1@}, @{0@}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '@{0@}@{1@}@{0@}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'
@end example

名前を使ったアクセス:

@example
>>> 'Coordinates: @{latitude@}, @{longitude@}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = @{'latitude': '37.24N', 'longitude': '-115.81W'@}
>>> 'Coordinates: @{latitude@}, @{longitude@}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
@end example

引数の属性へのアクセス:

@example
>>> c = 3-5j
>>> ('The complex number @{0@} is formed from the real part @{0.real@} '
...  'and the imaginary part @{0.imag@}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point(@{self.x@}, @{self.y@})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
@end example

引数の要素へのアクセス:

@example
>>> coord = (3, 5)
>>> 'X: @{0[0]@};  Y: @{0[1]@}'.format(coord)
'X: 3;  Y: 5'
@end example

@code{%s} と @code{%r} の置き換え:

@example
>>> "repr() shows quotes: @{!r@}; str() doesn't: @{!s@}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
@end example

テキストの幅を指定した整列:

@example
>>> '@{:<30@}'.format('left aligned')
'left aligned                  '
>>> '@{:>30@}'.format('right aligned')
'                 right aligned'
>>> '@{:^30@}'.format('centered')
'           centered           '
>>> '@{:*^30@}'.format('centered')  # use '*' as a fill char
'***********centered***********'
@end example

@code{%+f} と @code{%-f}, @code{% f} の置換、そして符号の指定:

@example
>>> '@{:+f@}; @{:+f@}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '@{: f@}; @{: f@}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '@{:-f@}; @{:-f@}'.format(3.14, -3.14)  # show only the minus -- same as '@{:f@}; @{:f@}'
'3.140000; -3.140000'
@end example

@code{%x} と @code{%o} の置換、そして値に対する異なる底の変換:

@example
>>> # format also supports binary numbers
>>> "int: @{0:d@};  hex: @{0:x@};  oct: @{0:o@};  bin: @{0:b@}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: @{0:d@};  hex: @{0:#x@};  oct: @{0:#o@};  bin: @{0:#b@}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
@end example

Using the comma or the underscore as a digit group separator:

@example
>>> '@{:,@}'.format(1234567890)
'1,234,567,890'
>>> '@{:_@}'.format(1234567890)
'1_234_567_890'
>>> '@{:_b@}'.format(1234567890)
'100_1001_1001_0110_0000_0010_1101_0010'
>>> '@{:_x@}'.format(1234567890)
'4996_02d2'
>>> '@{:_@}'.format(123456789.123456789)
'123_456_789.12345679'
>>> '@{:.,@}'.format(123456789.123456789)
'123456789.123,456,79'
>>> '@{:,._@}'.format(123456789.123456789)
'123,456,789.123_456_79'
@end example

パーセントを表示する:

@example
>>> points = 19
>>> total = 22
>>> 'Correct answers: @{:.2%@}'.format(points/total)
'Correct answers: 86.36%'
@end example

型特有の書式指定を使う:

@example
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '@{:%Y-%m-%d %H:%M:%S@}'.format(d)
'2010-07-04 12:15:58'
@end example

引数をネストする、さらに複雑な例:

@example
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '@{0:@{fill@}@{align@}16@}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '@{:02X@}@{:02X@}@{:02X@}@{:02X@}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12):
...     for base in 'dXob':
...         print('@{0:@{width@}@{base@}@}'.format(num, base=base, width=width), end=' ')
...     print()
...
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8     8    10  1000
    9     9    11  1001
   10     A    12  1010
   11     B    13  1011
@end example

@node Template strings $-strings,ヘルパー関数,書式指定文字列の文法,string --- 一般的な文字列操作
@anchor{library/string template-strings-pep292}@anchor{2749}@anchor{library/string template-strings-strings}@anchor{274a}
@subsubsection Template strings ($-strings)


@cartouche
@quotation 注釈 
The feature described here was introduced in Python 2.4;
a simple templating method based upon regular expressions.
It predates @ref{833,,str.format()}, @ref{19a,,formatted string literals},
and @ref{274b,,template string literals}.

It is unrelated to template string literals (t-strings),
which were introduced in Python 3.14.
These evaluate to  @ref{16a,,string.templatelib.Template} objects,
found in the @ref{d9,,string.templatelib} module.
@end quotation
@end cartouche

テンプレート文字列では 
@geindex Python Enhancement Proposals; PEP 292
PEP 292@footnote{https://peps.python.org/pep-0292/} で解説されている単純な文字列置換ができます。
テンプレート文字列の主な使い道は国際化 (i18n) です。というのは、その国際化の文脈において、より簡潔な文法と機能を持つテンプレート文字列を使うと、 Python にある他の組み込みの文字列フォーマット機能よりも翻訳がしやすいからです。
テンプレート文字列の上に構築された国際化のためのライプラリの例として、 flufl.i18n@footnote{https://flufli18n.readthedocs.io/en/latest/} を調べてみてください。

@geindex $ (ダラー);テンプレート文字列の中で

テンプレート文字列は @code{$} に基づいた置換をサポートしていて、次の規則が使われています:


@itemize *

@item 
@code{$$} はエスケープ文字です; @code{$} 一つに置換されます。

@item 
@code{$identifier} は @code{"identifier"} のマッピングキーに合致する置換プレースホルダーを指定します。デフォルトでは、 @code{"identifier"} は大文字と小文字を区別しない ASCII 英数字 (アンダースコアを含む) からなら文字列に制限されています。文字列はアンダースコアか ASCII 文字から始まるものでなければなりません。@code{$} の後に識別子に使えない文字が出現すると、そこでプレースホルダ名の指定が終わります。

@item 
@code{$@{identifier@}} は @code{$identifier} と同じです。プレースホルダ名の後ろに識別子として使える文字列が続いていて、それをプレースホルダ名の一部として扱いたくない場合、例えば @code{"$@{noun@}ification"} のような場合に必要な書き方です。
@end itemize

上記以外の書き方で文字列中に @code{$} を使うと @ref{2ec,,ValueError} を送出します。

The @code{string} module provides a @ref{897,,Template} class that implements
these rules.  The methods of @ref{897,,Template} are:

@geindex Template (string のクラス)
@anchor{library/string string Template}@anchor{897}
@deffn {クラス} string.Template (template)

コンストラクタはテンプレート文字列になる引数を一つだけ取ります。

@geindex substitute() (string.Template のメソッド)
@anchor{library/string string Template substitute}@anchor{20d5}
@deffn {メソッド} substitute (mapping=@{@}, /, **kwds)

テンプレート置換を行い、新たな文字列を生成して返します。`mapping' はテンプレート中のプレースホルダに対応するキーを持つような任意の辞書類似オブジェクトです。辞書を指定する代わりに、キーワード引数も指定でき、その場合にはキーワードをプレースホルダ名に対応させます。`mapping' と `kwds' の両方が指定され、内容が重複した場合には、`kwds' に指定したプレースホルダを優先します。
@end deffn

@geindex safe_substitute() (string.Template のメソッド)
@anchor{library/string string Template safe_substitute}@anchor{20d6}
@deffn {メソッド} safe_substitute (mapping=@{@}, /, **kwds)

@ref{20d5,,substitute()} と同じですが、プレースホルダに対応するものを `mapping' や `kwds' から見つけられなかった場合に、 @ref{5e7,,KeyError} 例外を送出する代わりにもとのプレースホルダがそのまま入ります。また、 @ref{20d5,,substitute()} とは違い、規則外の書き方で @code{$} を使った場合でも、 @ref{2ec,,ValueError} を送出せず単に @code{$} を返します。

その他の例外も発生し得る一方で、このメソッドが「安全 (safe) 」と呼ばれているのは、置換操作は常に、例外を送出する代わりに利用可能な文字列を返そうとするからです。別の見方をすれば、 @ref{20d6,,safe_substitute()} は区切り間違いによるぶら下がり (dangling delimiter) や波括弧の非対応、 Python の識別子として無効なプレースホルダ名を含むような不正なテンプレートを何も警告せずに無視するため、安全とはいえないのです。
@end deffn

@geindex is_valid() (string.Template のメソッド)
@anchor{library/string string Template is_valid}@anchor{896}
@deffn {メソッド} is_valid ()

Returns @code{False} if the template has invalid placeholders that will cause
@ref{20d5,,substitute()} to raise @ref{2ec,,ValueError}.


Added in version 3.11.

@end deffn

@geindex get_identifiers() (string.Template のメソッド)
@anchor{library/string string Template get_identifiers}@anchor{895}
@deffn {メソッド} get_identifiers ()

テンプレート内の有効な識別子のリストを、その識別子が最初に現れる順番で返します。不正な識別子は無視されます。


Added in version 3.11.

@end deffn

@ref{897,,Template} のインスタンスは、次のような public な属性を提供しています:

@geindex template (string.Template の属性)
@anchor{library/string string Template template}@anchor{274c}
@deffn {の属性} template

コンストラクタの引数 `template' に渡されたオブジェクトです。通常、この値を変更すべきではありませんが、読み出し専用アクセスを強制しているわけではありません。
@end deffn
@end deffn

Templateの使い方の例を以下に示します:

@example
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
@end example

さらに進んだ使い方: @ref{897,,Template} のサブクラスを派生して、プレースホルダの書式、区切り文字、テンプレート文字列の解釈に使われている正規表現全体をカスタマイズできます。こうした作業には、以下のクラス属性をオーバライドします:


@itemize *

@item 
`delimiter' -- プレースホルダの開始を示すリテラル文字列です。
デフォルトの値は @code{$} です。
実装系はこの文字列に対して必要に応じて @ref{e03,,re.escape()} を呼び出すので、正規表現になってしまうような文字列にしては `なりません' 。
さらにクラスを作成した後に delimiter を変更できない (つまり、別の delimiter を設定したいのであれば、サブクラスの名前空間で行わなければならない) ことに注意してください。

@item 
`idpattern' -- これは波括弧なしのプレースホルダーを記述する正規表現です。デフォルト値は正規表現 @code{(?a:[_a-z][_a-z0-9]*)} です。 `idpattern' が与えられており、かつ `braceidpattern' が @code{None} の場合、このパターンは波括弧付きのプレースホルダーにも適用されます。

@cartouche
@quotation 注釈 
`flags' のデフォルトは @code{re.IGNORECASE} なので、 @code{[a-z]} というパターンはいくつかの非 ASCII 文字に適合できます。
そのため、ここではローカルの @code{a} フラグを使っています。
@end quotation
@end cartouche


バージョン 3.7 で変更: `braceidpattern' を使用すると、中括弧の内側と外側で使用する別々のパターンを定義できます。


@item 
`braceidpattern' -- これは `idpattern' に似ていますが、波括弧付きプレースホルダーのパターンを記述します。デフォルトは @code{None} で、 `idpattern' が適用されます (すなわち、波括弧の内側と外側の両方に同じパターンが使われます) 。 `braceidpattern' を使うと、波括弧付きと波括弧なしのプレースホルダーにそれぞれ異なるパターンを定義することができます。


Added in version 3.7.


@item 
`flags' -- 代入の認識のために使用される正規表現をコンパイルする際に適用される正規表現フラグ。デフォルト値は @code{re.IGNORECASE} です。@code{re.VERBOSE} が常にフラグに追加されるということに注意してください。したがって、カスタムな `idpattern' は verbose 正規表現の規約に従わなければなりません。


Added in version 3.2.

@end itemize

他にも、クラス属性 `pattern' をオーバライドして、正規表現パターン全体を指定できます。オーバライドを行う場合、 `pattern' の値は 4 つの名前つきキャプチャグループ (capturing group) を持った正規表現オブジェクトでなければなりません。これらのキャプチャグループは、上で説明した規則と、無効なプレースホルダに対する規則に対応しています:


@itemize *

@item 
`escaped' -- このグループはエスケープシーケンス、すなわちデフォルトパターンにおける @code{$$} に対応します。

@item 
`named' -- このグループは波括弧でくくらないプレースホルダ名に対応します; キャプチャグループに区切り文字を含めてはなりません。

@item 
`braced' -- このグループは波括弧でくくったプレースホルダ名に対応します; キャプチャグループに区切り文字を含めてはなりません。

@item 
`invalid' -- このグループはそのほかの区切り文字のパターン (通常は区切り文字一つ) に対応し、正規表現の末尾に出現しなければなりません。
@end itemize

このクラスのメソッドは、これらの名前付きグループに1つもマッチすることなくパターンがテンプレートにマッチした場合、 @ref{2ec,,ValueError} を送出します。

@node ヘルパー関数,,Template strings $-strings,string --- 一般的な文字列操作
@anchor{library/string helper-functions}@anchor{274d}
@subsubsection ヘルパー関数


@geindex capwords() (string モジュール)
@anchor{library/string string capwords}@anchor{2656}
@deffn {の関数} string.capwords (s, sep=None)

@ref{10aa,,str.split()} を使って引数を単語に分割し、 @ref{263e,,str.capitalize()} を使ってそれぞれの単語の先頭の文字を大文字に変換し、 @ref{2609,,str.join()} を使ってつなぎ合わせます。オプションの第2引数 `sep' が与えられないか @code{None} の場合、この置換処理は文字列中の連続する空白文字をスペース一つに置き換え、先頭と末尾の空白を削除します、それ以外の場合には `sep' は split と join に使われます。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node string templatelib --- テンプレート文字列リテラルのサポート,re --- 正規表現操作,string --- 一般的な文字列操作,テキスト処理サービス
@anchor{library/string templatelib doc}@anchor{274e}@anchor{library/string templatelib module-string templatelib}@anchor{d9}@anchor{library/string templatelib string-templatelib-support-for-template-string-literals}@anchor{274f}@anchor{library/string templatelib translation-repo}@anchor{2750}
@subsection @code{string.templatelib} --- テンプレート文字列リテラルのサポート


@geindex module; string.templatelib

`ソースコード:' Lib/string/templatelib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/string/templatelib.py}


__________________________________________________________________



@subsubheading 参考



@itemize *

@item 
@ref{19a,,フォーマット済み文字列リテラル}

@item 
@ref{17fa,,テンプレート文字列リテラル(t-string)の構文}

@item 
@geindex Python Enhancement Proposals; PEP 750
PEP 750@footnote{https://peps.python.org/pep-0750/}
@end itemize


@menu
* テンプレート文字列:: 
* 型:: 
* ヘルパー関数: ヘルパー関数<2>. 

@end menu

@node テンプレート文字列,型,,string templatelib --- テンプレート文字列リテラルのサポート
@anchor{library/string templatelib id1}@anchor{2751}@anchor{library/string templatelib template-strings}@anchor{274b}
@subsubsection テンプレート文字列



Added in version 3.14.


Template strings are a mechanism for custom string processing.
They have the full flexibility of Python's @ref{19a,,f-strings},
but return a @ref{16a,,Template} instance that gives access
to the static and interpolated (in curly brackets) parts of a string
`before' they are combined.

t-stringを書くには、このようにプレフィックスとして @code{'f'} の代わりに @code{'t'} を使用します:

@example
>>> pi = 3.14
>>> t't-strings are new in Python @{pi!s@}!'
Template(
   strings=('t-strings are new in Python ', '!'),
   interpolations=(Interpolation(3.14, 'pi', 's', '@w{'}),)
)
@end example

@node 型,ヘルパー関数<2>,テンプレート文字列,string templatelib --- テンプレート文字列リテラルのサポート
@anchor{library/string templatelib types}@anchor{2752}
@subsubsection 型


@geindex Template (string.templatelib のクラス)
@anchor{library/string templatelib string templatelib Template}@anchor{16a}
@deffn {クラス} string.templatelib.Template

The @code{Template} class describes the contents of a template string.
It is immutable, meaning that attributes of a template cannot be reassigned.

The most common way to create a @code{Template} instance is to use the
@ref{17fa,,template string literal syntax}.
This syntax is identical to that of @ref{19a,,f-strings},
except that it uses a @code{t} prefix in place of an @code{f}:

@example
>>> cheese = 'Red Leicester'
>>> template = t"We're fresh out of @{cheese@}, sir."
>>> type(template)
<class 'string.templatelib.Template'>
@end example

Templates are stored as sequences of literal @ref{2753,,strings}
and dynamic @ref{2754,,interpolations}.
A @ref{2755,,values} attribute holds the values of the interpolations:

@example
>>> cheese = 'Camembert'
>>> template = t'Ah! We do have @{cheese@}.'
>>> template.strings
('Ah! We do have ', '.')
>>> template.interpolations
(Interpolation('Camembert', ...),)
>>> template.values
('Camembert',)
@end example

The @code{strings} tuple has one more element than @code{interpolations}
and @code{values}; the interpolations “belong” between the strings.
This may be easier to understand when tuples are aligned

@example
template.strings:  ('Ah! We do have ',              '.')
template.values:   (                   'Camembert',    )
@end example

@subsubheading 属性


@geindex strings (string.templatelib.Template の属性)
@anchor{library/string templatelib string templatelib Template strings}@anchor{2753}
@deffn {の属性} strings: @ref{614,,tuple}[@ref{169,,str}, ...]

A @ref{614,,tuple} of the static strings in the template.

@example
>>> cheese = 'Camembert'
>>> template = t'Ah! We do have @{cheese@}.'
>>> template.strings
('Ah! We do have ', '.')
@end example

Empty strings `are' included in the tuple:

@example
>>> response = 'We do have '
>>> cheese = 'Camembert'
>>> template = t'Ah! @{response@}@{cheese@}.'
>>> template.strings
('Ah! ', '@w{'}, '.')
@end example

The @code{strings} tuple is never empty, and always contains one more
string than the @code{interpolations} and @code{values} tuples:

@example
>>> t'@w{'}.strings
('@w{'},)
>>> t'@w{'}.values
()
>>> t'@{'cheese'@}'.strings
('@w{'}, '@w{'})
>>> t'@{'cheese'@}'.values
('cheese',)
@end example
@end deffn

@geindex interpolations (string.templatelib.Template の属性)
@anchor{library/string templatelib string templatelib Template interpolations}@anchor{2754}
@deffn {の属性} interpolations: @ref{614,,tuple}[@ref{16b,,Interpolation}, ...]

A @ref{614,,tuple} of the interpolations in the template.

@example
>>> cheese = 'Camembert'
>>> template = t'Ah! We do have @{cheese@}.'
>>> template.interpolations
(Interpolation('Camembert', 'cheese', None, '@w{'}),)
@end example

The @code{interpolations} tuple may be empty and always contains one fewer
values than the @code{strings} tuple:

@example
>>> t'Red Leicester'.interpolations
()
@end example
@end deffn

@geindex values (string.templatelib.Template の属性)
@anchor{library/string templatelib string templatelib Template values}@anchor{2755}
@deffn {の属性} values: @ref{614,,tuple}[@ref{c7e,,object}, ...]

A tuple of all interpolated values in the template.

@example
>>> cheese = 'Camembert'
>>> template = t'Ah! We do have @{cheese@}.'
>>> template.values
('Camembert',)
@end example

The @code{values} tuple always has the same length as the
@code{interpolations} tuple. It is always equivalent to
@code{tuple(i.value for i in template.interpolations)}.
@end deffn

@subsubheading メソッド


@geindex __new__() (string.templatelib.Template のメソッド)
@anchor{library/string templatelib string templatelib Template __new__}@anchor{2756}
@deffn {メソッド} __new__ (*args: str | Interpolation)

While literal syntax is the most common way to create a @code{Template},
it is also possible to create them directly using the constructor:

@example
>>> from string.templatelib import Interpolation, Template
>>> cheese = 'Camembert'
>>> template = Template(
...     'Ah! We do have ', Interpolation(cheese, 'cheese'), '.'
... )
>>> list(template)
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, '@w{'}), '.']
@end example

If multiple strings are passed consecutively, they will be concatenated
into a single value in the @ref{2753,,strings} attribute. For example,
the following code creates a @ref{16a,,Template} with a single final string:

@example
>>> from string.templatelib import Template
>>> template = Template('Ah! We do have ', 'Camembert', '.')
>>> template.strings
('Ah! We do have Camembert.',)
@end example

If multiple interpolations are passed consecutively, they will be treated
as separate interpolations and an empty string will be inserted between them.
For example, the following code creates a template with empty placeholders
in the @ref{2753,,strings} attribute:

@example
>>> from string.templatelib import Interpolation, Template
>>> template = Template(
...     Interpolation('Camembert', 'cheese'),
...     Interpolation('.', 'punctuation'),
... )
>>> template.strings
('@w{'}, '@w{'}, '@w{'})
@end example
@end deffn


@deffn {Describe} iter(template)

Iterate over the template, yielding each non-empty string and
@ref{16b,,Interpolation} in the correct order:

@example
>>> cheese = 'Camembert'
>>> list(t'Ah! We do have @{cheese@}.')
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, '@w{'}), '.']
@end example

@cartouche
@quotation 注意 
Empty strings are `not' included in the iteration:

@example
>>> response = 'We do have '
>>> cheese = 'Camembert'
>>> list(t'Ah! @{response@}@{cheese@}.')
['Ah! ',
 Interpolation('We do have ', 'response', None, '@w{'}),
 Interpolation('Camembert', 'cheese', None, '@w{'}),
 '.']
@end example
@end quotation
@end cartouche
@end deffn


@deffn {Describe} template + other

@deffnx {Describe} template += other

Concatenate this template with another, returning a new
@code{Template} instance:

@example
>>> cheese = 'Camembert'
>>> list(t'Ah! ' + t'We do have @{cheese@}.')
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, '@w{'}), '.']
@end example

Concatenating a @code{Template} and a @code{str} is `not' supported.
This is because it is unclear whether the string should be treated as
a static string or an interpolation.
If you want to concatenate a @code{Template} with a string,
you should either wrap the string directly in a @code{Template}
(to treat it as a static string)
or use an @code{Interpolation} (to treat it as dynamic):

@example
>>> from string.templatelib import Interpolation, Template
>>> template = t'Ah! '
>>> # Treat 'We do have ' as a static string
>>> template += Template('We do have ')
>>> # Treat cheese as an interpolation
>>> cheese = 'Camembert'
>>> template += Template(Interpolation(cheese, 'cheese'))
>>> list(template)
['Ah! We do have ', Interpolation('Camembert', 'cheese', None, '@w{'})]
@end example
@end deffn
@end deffn

@geindex Interpolation (string.templatelib のクラス)
@anchor{library/string templatelib string templatelib Interpolation}@anchor{16b}
@deffn {クラス} string.templatelib.Interpolation

The @code{Interpolation} type represents an expression inside a template string.
It is immutable, meaning that attributes of an interpolation cannot be reassigned.

Interpolations support pattern matching, allowing you to match against
their attributes with the @ref{a0e,,match statement}:

@example
>>> from string.templatelib import Interpolation
>>> interpolation = t'@{1. + 2.:.2f@}'.interpolations[0]
>>> interpolation
Interpolation(3.0, '1. + 2.', None, '.2f')
>>> match interpolation:
...     case Interpolation(value, expression, conversion, format_spec):
...         print(value, expression, conversion, format_spec, sep=' | ')
...
3.0 | 1. + 2. | None | .2f
@end example

@subsubheading 属性


@geindex value (string.templatelib.Interpolation の属性)
@anchor{library/string templatelib string templatelib Interpolation value}@anchor{2757}
@deffn {の属性} value: @ref{c7e,,object}

The evaluated value of the interpolation.

@example
>>> t'@{1 + 2@}'.interpolations[0].value
3
@end example
@end deffn

@geindex expression (string.templatelib.Interpolation の属性)
@anchor{library/string templatelib string templatelib Interpolation expression}@anchor{2758}
@deffn {の属性} expression: @ref{169,,str}

For interpolations created by t-string literals, @code{expression}
is the expression text found inside the curly brackets (@code{@{} & @code{@}}),
including any whitespace, excluding the curly brackets themselves,
and ending before the first @code{!}, @code{:}, or @code{=} if any is present.
For manually created interpolations, @code{expression} is the arbitrary
string provided when constructing the interpolation instance.

We recommend using valid Python expressions or the empty string for the
@code{expression} field of manually created @code{Interpolation}
instances, although this is not enforced at runtime.

@example
>>> t'@{1 + 2@}'.interpolations[0].expression
'1 + 2'
@end example
@end deffn

@geindex conversion (string.templatelib.Interpolation の属性)
@anchor{library/string templatelib string templatelib Interpolation conversion}@anchor{265c}
@deffn {の属性} conversion: @ref{a55,,Literal}['a', 'r', 's'] | @ref{885,,None}

The conversion to apply to the value, or @code{None}.

The @code{conversion} is the optional conversion to apply
to the value:

@example
>>> t'@{1 + 2!a@}'.interpolations[0].conversion
'a'
@end example

@cartouche
@quotation 注釈 
Unlike f-strings, where conversions are applied automatically,
the expected behavior with t-strings is that code that `processes' the
@code{Template} will decide how to interpret and whether to apply
the @code{conversion}.
For convenience, the @ref{2759,,convert()} function can be used to mimic
f-string conversion semantics.
@end quotation
@end cartouche
@end deffn

@geindex format_spec (string.templatelib.Interpolation の属性)
@anchor{library/string templatelib string templatelib Interpolation format_spec}@anchor{275a}
@deffn {の属性} format_spec: @ref{169,,str}

The format specification to apply to the value.

The @code{format_spec} is an optional, arbitrary string
used as the format specification to present the value:

@example
>>> t'@{1 + 2:.2f@}'.interpolations[0].format_spec
'.2f'
@end example

@cartouche
@quotation 注釈 
Unlike f-strings, where format specifications are applied automatically
via the @ref{199,,format()} protocol, the expected behavior with
t-strings is that code that `processes' the interpolation will
decide how to interpret and whether to apply the format specification.
As a result, @code{format_spec} values in interpolations
can be arbitrary strings,
including those that do not conform to the @ref{199,,format()} protocol.
@end quotation
@end cartouche
@end deffn

@subsubheading メソッド


@geindex __new__() (string.templatelib.Interpolation のメソッド)
@anchor{library/string templatelib string templatelib Interpolation __new__}@anchor{275b}
@deffn {メソッド} __new__ (value: object, expression: str, conversion: Literal['a', 'r', 's'] | None = None, format_spec: str = '@w{'})

Create a new @code{Interpolation} object from component parts.

@*パラメータ: 

@itemize *

@item 
@code{value} -- The evaluated, in-scope result of the interpolation.

@item 
@code{expression} -- The text of a valid Python expression,
or an empty string.

@item 
@code{conversion} -- The @ref{15b3,,conversion} to be used,
one of @code{None}, @code{'a'}, @code{'r'}, or @code{'s'}.

@item 
@code{format_spec} -- An optional, arbitrary string used as the
@ref{4f9,,format specification} to present the value.
@end itemize

@end deffn
@end deffn

@node ヘルパー関数<2>,,型,string templatelib --- テンプレート文字列リテラルのサポート
@anchor{library/string templatelib helper-functions}@anchor{275c}
@subsubsection ヘルパー関数


@geindex convert() (string.templatelib モジュール)
@anchor{library/string templatelib string templatelib convert}@anchor{2759}
@deffn {の関数} string.templatelib.convert (obj, /, conversion)

Applies formatted string literal @ref{2739,,conversion}
semantics to the given object `obj'.
This is frequently useful for custom template string processing logic.

Three conversion flags are currently supported:


@itemize *

@item 
@code{'s'} which calls @ref{169,,str()} on the value (like @code{!s}),

@item 
@code{'r'} which calls @ref{1c1,,repr()} (like @code{!r}), and

@item 
@code{'a'} which calls @ref{15ff,,ascii()} (like @code{!a}).
@end itemize

If the conversion flag is @code{None}, `obj' is returned unchanged.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node re --- 正規表現操作,difflib --- 差分の計算の補助,string templatelib --- テンプレート文字列リテラルのサポート,テキスト処理サービス
@anchor{library/re doc}@anchor{275d}@anchor{library/re module-re}@anchor{be}@anchor{library/re re-regular-expression-operations}@anchor{275e}@anchor{library/re translation-repo}@anchor{275f}
@subsection @code{re} --- 正規表現操作


@geindex module; re

`ソースコード:' Lib/re/@footnote{https://github.com/python/cpython/tree/3.14/Lib/re/}


__________________________________________________________________


このモジュールは Perl に見られる正規表現マッチング操作と同様のものを提供します。

パターンおよび検索される文字列には、Unicode 文字列 (@ref{169,,str}) や 8 ビット文字列 (@ref{192,,bytes}) を使います。ただし、Unicode 文字列と 8 ビット文字列の混在はできません。つまり、Unicode 文字列にバイト列のパターンでマッチングしたり、その逆はできません。同様に、置換時の置換文字列はパターンおよび検索文字列の両方と同じ型でなくてはなりません。

正規表現では、特殊な形式を表すためや、特殊文字をその特殊な意味を発動させず使うために、バックスラッシュ文字 (@code{'\'}) を使います。こうしたバックスラッシュの使い方は、 Python の文字列リテラルにおける同じ文字の使い方と衝突します。例えば、リテラルのバックスラッシュにマッチさせるには、パターン文字列として @code{'\\\\'} と書かなければなりません。なぜなら、正規表現は @code{\\} でなければならないうえ、それぞれのバックスラッシュは標準の Python 文字列リテラルで @code{\\} と表現せねばならないからです。
Python の文字列リテラルにおいて、バックスラッシュの使用による不正なエスケープ文字がある場合は、@ref{1ae,,SyntaxWarning} が発生し、将来的には @ref{18e,,SyntaxError} になることにも注意してください。この動作は、正規表現として有効な文字列に対しても同様です。

これを解決するには、正規表現パターンに Python の raw 文字列記法を使います。 @code{'r'} を前置した文字列リテラル内ではバックスラッシュが特別扱いされません。従って @code{"\n"} が改行一文字からなる文字列であるのに対して、 @code{r"\n"} は @code{'\'} と @code{'n'} の二文字からなる文字列です。通常、 Python コード中では、パターンをこの raw 文字列記法を使って表現します。

重要なこととして、大抵の正規表現操作は、モジュールレベルの関数としても、 @ref{1189,,コンパイル済み正規表現} のメソッドとしても利用できます。関数は正規表現オブジェクトを前もってコンパイルする必要がない近道ですが、微調整のための変数が減ります。


@subsubheading 参考


The third-party regex@footnote{https://pypi.org/project/regex/} module,
which has an API compatible with the standard library @code{re} module,
but offers additional functionality and a more thorough Unicode support.


@menu
* 正規表現のシンタックス:: 
* モジュールコンテンツ:: 
* 正規表現オブジェクト:: 
* マッチオブジェクト:: 
* 正規表現の例:: 

@end menu

@node 正規表現のシンタックス,モジュールコンテンツ,,re --- 正規表現操作
@anchor{library/re re-syntax}@anchor{92e}@anchor{library/re regular-expression-syntax}@anchor{2760}
@subsubsection 正規表現のシンタックス


正規表現 (または RE) は、その表現にマッチ (match) する文字列の集合を指定します。このモジュールの関数を使えば、ある文字列が与えられた正規表現にマッチするか (または、与えられた正規表現がある文字列にマッチするか、と言い換えても同じことになります) を検査できます。

正規表現を連結することで新しい正規表現を作れます。`A' と `B' がともに正規表現であれば `AB' も正規表現です。一般的に、ある文字列 `p' が `A' にマッチし、別の文字列 `q' が `B' にマッチするなら、文字列 `pq' は AB にマッチします。ただし、 `A' または `B' に優先度の低い演算が含まれる場合や、 `A' と `B' との間に境界条件がある場合や、番号付けされたグループ参照をしている場合、を除きます。こうして、ここで述べるような簡単な基本表現から、複雑な表現を容易に構築できます。正規表現に関する理論と実装の詳細については Friedl 本 @ref{2761,,[Frie09]} か、コンパイラの構築に関するテキストを参照してください。

以下で正規表現の形式を簡単に説明します。詳細な情報ややさしい説明は、 @ref{2762,,正規表現 HOWTO} を参照してください。

正規表現には、特殊文字と通常文字の両方を含められます。 @code{'A'} 、 @code{'a'} 、または @code{'0'} のようなほとんどの通常文字は、最も単純な正規表現です。これは単純に、その文字自体にマッチします。通常文字は連結できるので、 @code{last} は文字列 @code{'last'} にマッチします。 (この節では以降、正規表現は一般にクオートを使わず @code{この特殊スタイルで} 表記し、マッチ対象の文字列は、 @code{'シングルクオートで括って'} 表記します。)

@code{'|'} や @code{'('} といったいくつかの文字は特殊です。特殊文字は通常文字の種別を表したり、周辺の通常文字に対する解釈方法に影響します。

繰り返しの演算子または修飾子 (@code{*}、 @code{+}、 @code{?}、 @code{@{m,n@}} など) は直接入れ子にはできません。これは、非貪欲な修飾子の接尾辞 @code{?} や他の実装での他の修飾子との曖昧さを回避します。内側で繰り返したものをさらに繰り返すには、丸括弧が使えます。例えば、正規表現 @code{(?:a@{6@})*} は 6 の倍数個の @code{'a'} 文字にマッチします。

特殊文字を以下に示します:

@geindex . (ドット);in regular expressions


@table @asis

@item @code{.}

(ドット) デフォルトのモードでは改行以外の任意の文字にマッチします。 @ref{2763,,DOTALL} フラグが指定されていれば改行も含む全ての文字にマッチします。@code{(?s:.)} はフラグにかかわらず全ての文字にマッチします。
@end table

@geindex ^ (キャレット);in regular expressions


@table @asis

@item @code{^}

(キャレット) 文字列の先頭にマッチし、 @ref{2764,,MULTILINE} モードでは各改行の直後にもマッチします。
@end table

@geindex $ (ダラー);in regular expressions


@table @asis

@item @code{$}

文字列の末尾、あるいは文字列の末尾の改行の直前にマッチし、 @ref{2764,,MULTILINE} モードでは改行の前にもマッチします。 @code{foo} は 'foo' と 'foobar' の両方にマッチしますが、正規表現 @code{foo$} は 'foo' だけにマッチします。興味深いことに、 @code{'foo1\nfoo2\n'} を @code{foo.$} で検索した場合、通常は 'foo2' だけにマッチしますが、 @ref{2764,,MULTILINE} モードでは 'foo1' にもマッチします。 @code{$} だけで @code{'foo\n'} を検索した場合、2 つの (空の) マッチを見つけます: 1つは改行の直前で、もう1つは文字列の末尾です。
@end table

@geindex * (アスタリスク);in regular expressions


@table @asis

@item @code{*}

直前の正規表現を 0 回以上、できるだけ多く繰り返したものにマッチさせる結果の正規表現にします。例えば @code{ab*} は 'a'、'ab'、または 'a' に任意個数の 'b' を続けたものにマッチします。
@end table

@geindex + (プラス記号);in regular expressions


@table @asis

@item @code{+}

直前の正規表現を 1 回以上繰り返したものにマッチさせる結果の正規表現にします。例えば @code{ab+} は 'a' に 1 つ以上の 'b' が続いたものにマッチし、単なる 'a' にはマッチしません。
@end table

@geindex ? (クエスチョンマーク);in regular expressions


@table @asis

@item @code{?}

直前の正規表現を 0 回か 1 回繰り返したものにマッチさせる結果の正規表現にします。例えば @code{ab?} は 'a' あるいは 'ab' にマッチします。
@end table

@geindex *?;in regular expressions
@geindex +?;in regular expressions
@geindex ??;in regular expressions


@table @asis

@item @code{*?}, @code{+?}, @code{??}

@code{'*'} 、 @code{'+'} 、および @code{'?'} 修飾子は全て `貪欲 (greedy)' マッチで、できるだけ多くのテキストにマッチします。この挙動が望ましくない時もあります。例えば正規表現 @code{<.*>} が @code{'<a> b <c>'} に対してマッチされると、 @code{'<a>'} だけでなく文字列全体にマッチしてしまいます。修飾子の後に @code{?} を追加すると、 `非貪欲 (non-greedy)' あるいは `最小 (minimal)' のマッチが行われ、できるだけ `少ない' 文字にマッチします。正規表現 @code{<.*?>} を使うと @code{'<a>'} だけにマッチします。
@end table

@geindex *+;in regular expressions
@geindex ++;in regular expressions
@geindex ?+;in regular expressions


@table @asis

@item @code{*+}, @code{++}, @code{?+}

Like the @code{'*'}, @code{'+'}, and @code{'?'} quantifiers, those where @code{'+'} is
appended also match as many times as possible.
However, unlike the true greedy quantifiers, these do not allow
back-tracking when the expression following it fails to match.
These are known as `possessive' quantifiers.
For example, @code{a*a} will match @code{'aaaa'} because the @code{a*} will match
all 4 @code{'a'}s, but, when the final @code{'a'} is encountered, the
expression is backtracked so that in the end the @code{a*} ends up matching
3 @code{'a'}s total, and the fourth @code{'a'} is matched by the final @code{'a'}.
However, when @code{a*+a} is used to match @code{'aaaa'}, the @code{a*+} will
match all 4 @code{'a'}, but when the final @code{'a'} fails to find any more
characters to match, the expression cannot be backtracked and will thus
fail to match.
@code{x*+}, @code{x++} and @code{x?+} are equivalent to @code{(?>x*)}, @code{(?>x+)}
and @code{(?>x?)} correspondingly.


Added in version 3.11.

@end table

@geindex @{@} (波括弧);in regular expressions


@table @asis

@item @code{@{m@}}

直前の正規表現をちょうど `m' 回繰り返したものにマッチさせるよう指定します。それより少ないマッチでは正規表現全体がマッチしません。例えば、 @code{a@{6@}} は 6 個ちょうどの @code{'a'} 文字にマッチしますが、 5 個ではマッチしません。

@item @code{@{m,n@}}

直前の正規表現を `m' 回から `n' 回、できるだけ多く繰り返したものにマッチさせる結果の正規表現にします。例えば、@code{a@{3,5@}} は、3 個から 5 個の @code{'a'} 文字にマッチします。`m' を省略すると下限は 0 に指定され、`n' を省略すると上限は無限に指定されます。例として、 @code{a@{4,@}b} は @code{'aaaab'} や、1,000 個の @code{'a'} 文字に @code{'b'} が続いたものにマッチしますが、@code{'aaab'} にはマッチしません。コンマは省略できません、省略すると修飾子が上で述べた形式と混同されてしまうからです。

@item @code{@{m,n@}?}

結果の正規表現は、前にある正規表現を、`m' 回から `n' 回まで繰り返したものにマッチし、できるだけ `少なく' 繰り返したものにマッチするようにします。これは、前の数量詞の非貪欲版です。例えば、 6 文字文字列 @code{'aaaaaa'} では、 @code{a@{3,5@}} は、5 個の @code{'a'} 文字にマッチしますが、 @code{a@{3,5@}?} は 3 個の文字にマッチするだけです。

@item @code{@{m,n@}+}

Causes the resulting RE to match from `m' to `n' repetitions of the
preceding RE, attempting to match as many repetitions as possible
`without' establishing any backtracking points.
This is the possessive version of the quantifier above.
For example, on the 6-character string @code{'aaaaaa'}, @code{a@{3,5@}+aa}
attempt to match 5 @code{'a'} characters, then, requiring 2 more @code{'a'}s,
will need more characters than available and thus fail, while
@code{a@{3,5@}aa} will match with @code{a@{3,5@}} capturing 5, then 4 @code{'a'}s
by backtracking and then the final 2 @code{'a'}s are matched by the final
@code{aa} in the pattern.
@code{x@{m,n@}+} is equivalent to @code{(?>x@{m,n@})}.


Added in version 3.11.

@end table

@geindex \ (backslash);in regular expressions


@table @asis

@item @code{\}

特殊文字をエスケープ ( @code{'*'} や @code{'?'} などの文字にマッチできるようにする) し、または特殊シーケンスを合図します。特殊シーケンスは後で議論します。

パターンを表現するのに raw 文字列を使っていないのであれば、 Python ももまた、バックスラッシュを文字列リテラルでエスケープシーケンスとして使うことを思い出して下さい。そのエスケープシーケンスを Python のパーザが認識しないなら、そのバックスラッシュとそれに続く文字が結果の文字列に含まれます。しかし、Python が結果のシーケンスを認識するなら、そのバックスラッシュは 2 回繰り返さなければいけません。これは複雑で理解しにくいので、ごく単純な表現以外は、全て raw 文字列を使うことを強く推奨します。
@end table

@geindex [] (角カッコ);in regular expressions


@table @asis

@item @code{[]}

文字の集合を指定するのに使います。集合の中では:


@itemize *

@item 
文字を個別に指定できます。 @code{[amk]} は @code{'a'} 、 @code{'m'} または @code{'k'} にマッチします。
@end itemize

@geindex - (負符号);in regular expressions


@itemize *

@item 
連続した文字の範囲を、 @code{'-'} を2 つの文字で挟んで指定できます。例えば、 @code{[a-z]} はあらゆる小文字の ASCII 文字にマッチします。@code{[0-5][0-9]} は @code{00} から @code{59} まで全ての 2 桁の数字にマッチします。@code{[0-9A-Fa-f]} は任意の 16 進数字にマッチします。@code{-} がエスケープされているか (例: @code{[a\-z]})、先頭や末尾の文字にされていると (例: @code{[-a]} や @code{[a-]})、リテラル @code{'-'} にマッチします。

@item 
Special characters except backslash lose their special meaning inside sets.
For example,
@code{[(+*)]} will match any of the literal characters @code{'('}, @code{'+'},
@code{'*'}, or @code{')'}.
@end itemize

@geindex \ (backslash);in regular expressions


@itemize *

@item 
Backslash either escapes characters which have special meaning in a set
such as @code{'-'}, @code{']'}, @code{'^'} and @code{'\\'} itself or signals
a special sequence which represents a single character such as
@code{\xa0} or @code{\n} or a character class such as @code{\w} or @code{\S}
(defined below).
Note that @code{\b} represents a single "backspace" character,
not a word boundary as outside a set, and numeric escapes
such as @code{\1} are always octal escapes, not group references.
Special sequences which do not match a single character such as @code{\A}
and @code{\z} are not allowed.
@end itemize

@geindex ^ (キャレット);in regular expressions


@itemize *

@item 
`補集合' をとって範囲内にない文字にマッチできます。集合の最初の文字が @code{'^'} なら、集合に `含まれない' 全ての文字にマッチします。例えば、 @code{[^5]} は @code{'5'} を除くあらゆる文字にマッチし、 @code{[^^]} は @code{'^'} を除くあらゆる文字にマッチします。 @code{^} は集合の最初の文字でなければ特別の意味を持ちません。

@item 
集合の中でリテラル @code{']'} にマッチさせるには、その前にバックスラッシュをつけるか、集合の先頭に置きます。例えば、 @code{[()[\]@{@}]} と @code{[]()[@{@}]} はどちらも閉じ角括弧、開き角括弧、波括弧、丸括弧にマッチします。
@end itemize

@c .. index:: single: --; in regular expressions

@c .. index:: single: &&; in regular expressions

@c .. index:: single: ~~; in regular expressions

@c .. index:: single: ||; in regular expressions


@itemize *

@item 
Unicode Technical Standard #18@footnote{https://unicode.org/reports/tr18/} にあるような集合の入れ子や集合操作が将来追加される可能性があります。これは構文を変化させるもので、この変化を容易にするために、さしあたって曖昧な事例には @ref{659,,FutureWarning} が送出されます。これはリテラル @code{'['} で始まる集合や、リテラル文字の連続 @code{'--'} 、 @code{'&&'} 、 @code{'~~'} および @code{'||'} を含む集合を含みます。警告を避けるにはバックスラッシュでエスケープしてください。
@end itemize


バージョン 3.7 で変更: 文字セットが将来意味論的に変化する構造を含むなら @ref{659,,FutureWarning} が送出されます。

@end table

@geindex | (縦棒);in regular expressions


@table @asis

@item @code{|}

`A' と `B' を任意の正規表現として、 @code{A|B} は `A' と `B' のいずれかにマッチする正規表現を作成します。この方法で任意の数の正規表現を @code{'|'} で分離できます。これはグループ (下記参照) 中でも使えます。対象文字列を走査するとき、@code{'|'} で分離された正規表現は左から右へ順に試されます。一つのパターンが完全にマッチしたとき、そのパターン枝が受理されます。つまり、ひとたび `A' がマッチしてしまえば、例え `B' によって全体のマッチが長くなるとしても、 `B' はもはや走査されません。言いかえると、 @code{'|'} 演算子は決して貪欲にはなりません。リテラル @code{'|'} にマッチするには、 @code{\|} を使うか、 @code{[|]} のように文字クラス中に囲みます。
@end table

@geindex () (丸括弧);in regular expressions


@table @asis

@item @code{(...)}

丸括弧で囲まれた正規表現にマッチするとともに、グループの開始と終了を表します。グループの中身は以下で述べるように、マッチが実行された後で回収したり、その文字列中で以降 @code{\number} 特殊シーケンスでマッチしたりできます。リテラル @code{'('} や @code{')'} にマッチするには、@code{\(} や @code{\)} を使うか、文字クラス中に囲みます:  @code{[(]}、 @code{[)]} 。
@end table

@geindex (?;in regular expressions


@table @asis

@item @code{(?...)}

これは拡張記法です (@code{'('} に続く @code{'?'} はそれ以上の意味を持ちません) 。 @code{'?'} に続く最初の文字がこの構造の意味と特有の構文を決定します。拡張は一般に新しいグループを作成しません。ただし @code{(?P<name>...)} はこの法則の唯一の例外です。現在サポートされている拡張は以下の通りです。

@item @code{(?aiLmsux)}

(One or more letters from the set
@code{'a'}, @code{'i'}, @code{'L'}, @code{'m'}, @code{'s'}, @code{'u'}, @code{'x'}.)
The group matches the empty string;
the letters set the corresponding flags for the entire regular expression:


@itemize *

@item 
@ref{2765,,re.A} (ASCIIのみにマッチ)

@item 
@ref{2766,,re.I} (大文字小文字を無視)

@item 
@ref{2767,,re.L} (ロケール依存)

@item 
@ref{2768,,re.M} (マルチライン)

@item 
@ref{2769,,re.S} (ドットはすべてにマッチ)

@item 
@ref{276a,,re.U} (Unicodeマッチ)

@item 
@ref{276b,,re.X} (冗長)
@end itemize

(The flags are described in @ref{276c,,モジュールコンテンツ}.)
This is useful if you wish to include the flags as part of the
regular expression, instead of passing a `flag' argument to the
@ref{dce,,re.compile()} function.
Flags should be used first in the expression string.


バージョン 3.11 で変更: This construction can only be used at the start of the expression.

@end table

@geindex (?;;in regular expressions


@table @asis

@item @code{(?:...)}

普通の丸括弧の、キャプチャしない版です。丸括弧で囲まれた正規表現にマッチしますが、このグループがマッチした部分文字列は、マッチを実行したあとで回収することも、そのパターン中で以降参照することも `できません' 。

@item @code{(?aiLmsux-imsx:...)}

(Zero or more letters from the set
@code{'a'}, @code{'i'}, @code{'L'}, @code{'m'}, @code{'s'}, @code{'u'}, @code{'x'},
optionally followed by @code{'-'} followed by
one or more letters from the @code{'i'}, @code{'m'}, @code{'s'}, @code{'x'}.)
The letters set or remove the corresponding flags for the part of the expression:


@itemize *

@item 
@ref{2765,,re.A} (ASCIIのみにマッチ)

@item 
@ref{2766,,re.I} (大文字小文字を無視)

@item 
@ref{2767,,re.L} (ロケール依存)

@item 
@ref{2768,,re.M} (マルチライン)

@item 
@ref{2769,,re.S} (ドットはすべてにマッチ)

@item 
@ref{276a,,re.U} (Unicodeマッチ)

@item 
@ref{276b,,re.X} (冗長)
@end itemize

(The flags are described in @ref{276c,,モジュールコンテンツ}.)

文字 @code{'a'} 、 @code{'L'} および @code{'u'} は相互に排他であり、組み合わせることも @code{'-'} に続けることもできません。その代わり、これらの内一つがインライングループ中に現れると、外側のグループでのマッチングモードを上書きします。 Unicode パターン中では @code{(?a:...)} は ASCII 限定マッチングに切り替え、 @code{(?u:...)} は Unicode マッチング (デフォルト) に切り替えます。バイト列パターン中では、 @code{(?L:...)} はロケール依存マッチングに切り替え、 @code{(?a:...)} は ASCII 限定マッチング (デフォルト) に切り替えます。この上書きは狭いインライングループにのみ影響し、元のマッチングモードはグループ外では復元されます。


Added in version 3.6.



バージョン 3.7 で変更: 文字 @code{'a'} 、 @code{'L'} および @code{'u'} もグループ中で使えます。


@item @code{(?>...)}

Attempts to match @code{...} as if it was a separate regular expression, and
if successful, continues to match the rest of the pattern following it.
If the subsequent pattern fails to match, the stack can only be unwound
to a point `before' the @code{(?>...)} because once exited, the expression,
known as an `atomic group', has thrown away all stack points within
itself.
Thus, @code{(?>.*).} would never match anything because first the @code{.*}
would match all characters possible, then, having nothing left to match,
the final @code{.} would fail to match.
Since there are no stack points saved in the Atomic Group, and there is
no stack point before it, the entire expression would thus fail to match.


Added in version 3.11.

@end table

@geindex (?P<;in regular expressions


@table @asis

@item @code{(?P<name>...)}

通常の丸括弧に似ていますが、このグループがマッチした部分文字列はシンボリックグループ名 `name' でアクセスできます。グループ名は有効な Python 識別子でなければならず、@ref{192,,bytes} パターンではASCIIの範囲のバイトのみを含めることができます。各グループ名は 1 個の正規表現内で一度だけ定義されていなければなりません。シンボリックグループは、そのグループが名前付けされていなかったかのように番号付けされたグループでもあります。

名前付きグループは 3 つのコンテキストで参照できます。パターンが @code{(?P<quote>['\"]).*?(?P=quote)} (シングルまたはダブルクオートで囲まれた文字列にマッチ) ならば:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

グループ "quote" を参照するコンテキスト

@tab

参照する方法

@item

その同じパターン中

@tab


@itemize *

@item 
@code{(?P=quote)} (示したとおり)

@item 
@code{\1}
@end itemize

@item

マッチオブジェクト `m' の処理時

@tab


@itemize *

@item 
@code{m.group('quote')}

@item 
@code{m.end('quote')} (など)
@end itemize

@item

@code{re.sub()} の `repl' 引数へ渡される文字列中

@tab


@itemize *

@item 
@code{\g<quote>}

@item 
@code{\g<1>}

@item 
@code{\1}
@end itemize

@end multitable



バージョン 3.12 で変更: @ref{192,,bytes} パターンではグループの `名前' にASCIIの範囲(@code{b'\x00'}-@code{b'\x7f'})のバイトのみを含めることができます。

@end table

@geindex (?P=;in regular expressions


@table @asis

@item @code{(?P=name)}

名前付きグループへの後方参照です。これは `name' という名前の既出のグループがマッチした文字列にマッチします。
@end table

@geindex (?#;in regular expressions


@table @asis

@item @code{(?#...)}

コメントです。括弧の中身は単純に無視されます。
@end table

@geindex (?=;in regular expressions


@table @asis

@item @code{(?=...)}

@code{...} が次に続くものにマッチすればマッチしますが、文字列をまったく消費しません。これは `先読みアサーション (lookahead assertion)' と呼ばれます。例えば、@code{Isaac (?=Asimov)} は @code{'Isaac '} に、その後に @code{'Asimov'} が続く場合にのみ、マッチします。
@end table

@geindex (?!;in regular expressions


@table @asis

@item @code{(?!...)}

@code{...} が次に続くものにマッチしなければマッチします。これは `否定先読みアサーション (negative lookahead assertion)' です。例えば、@code{Isaac (?!Asimov)} は @code{'Isaac '} に、その後に @code{'Asimov'} が続か `ない' 場合にのみ、マッチします。
@end table

@geindex (?<=;in regular expressions


@table @asis

@item @code{(?<=...)}

その文字列における現在位置の前に、現在位置で終わる @code{...} とのマッチがあれば、マッチします。これは `後読みアサーション' と呼ばれます。@code{(?<=abc)def} は、後読みは 3 文字をバックアップし、含まれているパターンがマッチするか検査するので @code{'abcdef'} にマッチを見つけます。含まれるパターンは、固定長の文字列にのみマッチしなければなりません。すなわち、 @code{abc} や @code{a|b} は許されますが、@code{a*} や @code{a@{3,4@}} は許されません。肯定後読みアサーションで始まるパターンは、検索される文字列の先頭とは決してマッチしないことに注意して下さい。@ref{1445,,match()} 関数ではなく @ref{1444,,search()} 関数を使う方が望ましいでしょう:

@example
>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'
@end example

この例ではハイフンに続く単語を探します:

@example
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
@end example


バージョン 3.5 で変更: 固定長のグループ参照をサポートするようになりました。

@end table

@geindex (?<!;in regular expressions


@table @asis

@item @code{(?<!...)}

その文字列における現在位置の前に @code{...} とのマッチがなければ、マッチします。これは `否定後読みアサーション(negative lookbehind assertion)' と呼ばれます。肯定後読みアサーションと同様に、含まれるパターンは固定長の文字列にのみマッチしなければなりません。否定後読みアサーションで始まるパターンは検索される文字列の先頭でマッチできます。
@end table

@geindex (?(;in regular expressions
@anchor{library/re re-conditional-expression}@anchor{1b28}

@table @asis

@item @code{(?(id/name)yes-pattern|no-pattern)}

与えられた `id' や `name' のグループが存在すれば @code{yes-pattern} との、存在しなければ @code{no-pattern} とのマッチを試みます。@code{no-pattern} はオプションであり省略できます。例えば、@code{(<)?(\w+@@\w+(?:\.\w+)+)(?(1)>|$)} は貧弱な E-mail マッチングパターンで、@code{'<user@@host.com>'} や @code{'user@@host.com'} にはマッチしますが、@code{'<user@@host.com'} や @code{'user@@host.com>'} にはマッチしません。


バージョン 3.12 で変更: グループ `id' にはASCIIの数字のみを含めることができます。@ref{192,,bytes} パターンではグループの `名前' にASCIIの範囲(@code{b'\x00'}-@code{b'\x7f'})のバイトのみを含めることができます。

@end table
@anchor{library/re re-special-sequences}@anchor{276d}
特殊シーケンスは @code{'\'} と以下のリストの文字から構成されます。通常文字が ASCII 数字でも ASCII 文字でもなければ、結果の正規表現は 2 番目の文字にマッチします。例えば、@code{\$} は文字 @code{'$'} にマッチします。

@geindex \ (backslash);in regular expressions


@table @asis

@item @code{\number}

同じ番号のグループの中身にマッチします。グループは 1 から始まる番号をつけられます。例えば、 @code{(.+) \1} は、 @code{'the the'} あるいは @code{'55 55'} にマッチしますが、 @code{'thethe'} にはマッチしません(グループの後のスペースに注意して下さい)。この特殊シーケンスは最初の 99 グループのうちの一つとのマッチにのみ使えます。 `number' の最初の桁が 0 であるか、 `number' が 3 桁の 8 進数であれば、それはグループのマッチとしてではなく、 8 進値 `number' を持つ文字として解釈されます。文字クラスの @code{'['} と @code{']'} の間では全ての数値エスケープが文字として扱われます。
@end table

@geindex \A;in regular expressions


@table @asis

@item @code{\A}

文字列の先頭でのみマッチします。
@end table

@geindex \b;in regular expressions


@table @asis

@item @code{\b}

空文字列にマッチしますが、単語の先頭か末尾でのみです。単語は単語文字の並びとして定義されます。形式的には、 @code{\b} は @code{\w} と @code{\W} 文字 (またはその逆) との、あるいは @code{\w} と文字列の先頭・末尾との境界として定義されます。例えば、 @code{r'\bat\b'} は @code{'at'} 、 @code{'at.'}、 @code{'(at)'} や @code{'as at ay'} にはマッチしますが、 @code{'attempt'} や @code{'atlas'} にはマッチしません。

The default word characters in Unicode (str) patterns
are Unicode alphanumerics and the underscore,
but this can be changed by using the @ref{83e,,ASCII} flag.
Word boundaries are determined by the current locale
if the @ref{d63,,LOCALE} flag is used.

@cartouche
@quotation 注釈 
Inside a character range, @code{\b} represents the backspace character,
for compatibility with Python's string literals.
@end quotation
@end cartouche
@end table

@geindex \B;in regular expressions


@table @asis

@item @code{\B}

空文字列にマッチしますが、それが単語の先頭か末尾 `でない' ときのみです。つまり @code{r'at\B'} は @code{'athens'}、 @code{'atom'}、@code{'attorney'} にマッチしますが、 @code{'at'}、 @code{'at.'} や @code{'at!'} にはマッチしません。 @code{\B} は @code{\b} のちょうど反対で、 Unicode パターンにおける単語文字は Unicode 英数字およびアンダースコアですが、 これは @ref{83e,,ASCII} フラグを使って変更できます。 @ref{d63,,LOCALE} フラグが使われているなら単語の境界は現在のロケールによって決定されます。


バージョン 3.14 で変更: @code{\B} now matches empty input string.

@end table

@geindex \d;in regular expressions


@table @asis

@item @code{\d}


@table @asis

@item Unicode (str) パターンでは:

任意の Unicode 10 進数字 (Unicode 文字カテゴリ [Nd]@footnote{https://www.unicode.org/versions/Unicode15.0.0/ch04.pdf#G134153})にマッチします。これは @code{[0-9]} とその他多数の数字を含みます。

@ref{83e,,ASCII} フラグを使用すると @code{[0-9]} にマッチします。

@item 8 ビット (bytes) パターンでは:

任意のASCII文字の 10 進数字にマッチします。これは @code{[0-9]} と等価です。
@end table
@end table

@geindex \D;in regular expressions


@table @asis

@item @code{\D}

Matches any character which is not a decimal digit.
This is the opposite of @code{\d}.

@ref{83e,,ASCII} フラグを使用すると @code{[^0-9]} にマッチします。
@end table

@geindex \s;in regular expressions


@table @asis

@item @code{\s}


@table @asis

@item Unicode (str) パターンでは:

Matches Unicode whitespace characters (as defined by @ref{2639,,str.isspace()}).
This includes @code{[ \t\n\r\f\v]}, and also many other characters, for example the
non-breaking spaces mandated by typography rules in many languages.

@ref{83e,,ASCII} フラグを使用すると @code{[ \t\n\r\f\v]} にマッチします。

@item 8 ビット (bytes) パターンでは:

ASCII 文字セットで空白文字と見なされる文字にマッチします。これは @code{[ \t\n\r\f\v]} と等価です。
@end table
@end table

@geindex \S;in regular expressions


@table @asis

@item @code{\S}

Matches any character which is not a whitespace character. This is
the opposite of @code{\s}.

@ref{83e,,ASCII} フラグを使用すると @code{[^ \t\n\r\f\v]} にマッチします。
@end table

@geindex \w;in regular expressions


@table @asis

@item @code{\w}


@table @asis

@item Unicode (str) パターンでは:

Matches Unicode word characters;
this includes all Unicode alphanumeric characters
(as defined by @ref{2631,,str.isalnum()}),
as well as the underscore (@code{_}).

@ref{83e,,ASCII} フラグを使用すると @code{[a-zA-Z0-9_]} にマッチします。

@item 8 ビット (bytes) パターンでは:

ASCII 文字セットで英数字と見なされる文字にマッチします。これは @code{[a-zA-Z0-9_]} と等価です。@ref{d63,,LOCALE} フラグが使われているなら、現在のロケールで英数字と見なされる文字およびアンダースコアにマッチします。
@end table
@end table

@geindex \W;in regular expressions


@table @asis

@item @code{\W}

Matches any character which is not a word character.
This is the opposite of @code{\w}.
By default, matches non-underscore (@code{_}) characters
for which @ref{2631,,str.isalnum()} returns @code{False}.

@ref{83e,,ASCII} フラグを使用すると @code{[^a-zA-Z0-9_]} にマッチします。

If the @ref{d63,,LOCALE} flag is used,
matches characters which are neither alphanumeric in the current locale
nor the underscore.
@end table

@geindex \z;in regular expressions
@geindex \Z;in regular expressions


@table @asis

@item @code{\z}

文字列の末尾でのみマッチします。


Added in version 3.14.


@item @code{\Z}

The same as @code{\z}.  For compatibility with old Python versions.
@end table

@geindex \a;in regular expressions
@geindex \b;in regular expressions
@geindex \f;in regular expressions
@geindex \n;in regular expressions
@geindex \N;in regular expressions
@geindex \r;in regular expressions
@geindex \t;in regular expressions
@geindex \u;in regular expressions
@geindex \U;in regular expressions
@geindex \v;in regular expressions
@geindex \x;in regular expressions
@geindex \\;in regular expressions

Python 文字列リテラルでサポートされている  @ref{687,,エスケープシーケンス} のほとんども正規表現パーザで受理されます:

@example
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
@end example

(@code{\b} は単語の境界を表すのに使われ、文字クラス中でのみ "後退 (backspace)" 文字を意味することに注意してください。)

@code{'\u'}、@code{'\U'} および @code{'\N'} エスケープシーケンスは、Unicode (str)パターン内でのみ認識されます。バイト列ではエラーとなります。ASCII 文字のエスケープで未知のものは将来使うために予約されていて、エラーとして扱われます。

8 進エスケープは限られた形式でのみ含まれます。その最初の桁が 0 であるか、それが 3 桁の 8 進数であるならば、それは 8 進エスケープと見なされます。そうでなければ、それはグループ参照です。文字列リテラルでは、8 進エスケープは常にたかだか 3 桁長です。


バージョン 3.3 で変更: @code{'\u'} と @code{'\U'} エスケープシーケンスが追加されました。



バージョン 3.6 で変更: @code{'\'} と ASCII 文字からなる未知のエスケープはエラーになります。



バージョン 3.8 で変更: @code{'\N@{@var{name}@}'} エスケープシーケンスが追加されました。文字列リテラルでは、同名のUnicode 文字に展開されます。(@code{'\N@{EM DASH@}'} など)


@node モジュールコンテンツ,正規表現オブジェクト,正規表現のシンタックス,re --- 正規表現操作
@anchor{library/re contents-of-module-re}@anchor{276c}@anchor{library/re module-contents}@anchor{276e}
@subsubsection モジュールコンテンツ


このモジュールはいくつかの関数、定数、例外を定義します。このうちいくつかの関数は、コンパイル済み正規表現がそなえる完全な機能のメソッドを簡易にしたものです。些細なものを除くほとんどのアプリケーションは常にコンパイル済み形式を使います。

@menu
* フラグ:: 
* 関数: 関数<2>. 
* 例外: 例外<3>. 

@end menu

@node フラグ,関数<2>,,モジュールコンテンツ
@anchor{library/re flags}@anchor{276f}
@subsubsection フラグ



バージョン 3.6 で変更: フラグ定数は、@ref{e9a,,enum.IntFlag} のサブクラスである @ref{83f,,RegexFlag} のインスタンスになりました。


@geindex RegexFlag (re のクラス)
@anchor{library/re re RegexFlag}@anchor{83f}
@deffn {クラス} re.RegexFlag

An @ref{e9a,,enum.IntFlag} class containing the regex options listed below.


Added in version 3.11: - added to @code{__all__}

@end deffn

@geindex A (re モジュール)
@geindex ASCII (re モジュール)
@anchor{library/re re A}@anchor{2765}
@deffn {データ} re.A
@anchor{library/re re ASCII}@anchor{83e}
@deffnx {データ} re.ASCII

@code{\w}、@code{\W}、@code{\b}、@code{\B}、@code{\d}、@code{\D}、@code{\s}、および @code{\S} において、ASCII 文字のみでマッチングを行います。これは Unicode(str) パターンでのみ意味があり、バイト列パターンでは無視されます。

インラインフラグの @code{(?a)} に相当します。

@cartouche
@quotation 注釈 
The @ref{276a,,U} flag still exists for backward compatibility,
but is redundant in Python 3 since
matches are Unicode by default for @code{str} patterns,
and Unicode matching isn't allowed for bytes patterns.
@ref{d64,,UNICODE} and the inline flag @code{(?u)} are similarly redundant.
@end quotation
@end cartouche
@end deffn

@geindex DEBUG (re モジュール)
@anchor{library/re re DEBUG}@anchor{2770}
@deffn {データ} re.DEBUG

コンパイルした表現に関するデバッグ情報を出力します。

対応するインラインフラグはありません。
@end deffn

@geindex I (re モジュール)
@geindex IGNORECASE (re モジュール)
@anchor{library/re re I}@anchor{2766}
@deffn {データ} re.I
@anchor{library/re re IGNORECASE}@anchor{1a96}
@deffnx {データ} re.IGNORECASE

Perform case-insensitive matching;
expressions like @code{[A-Z]} will also  match lowercase letters.
Full Unicode matching (such as @code{Ü} matching @code{ü})
also works unless the @ref{83e,,ASCII} flag
is used to disable non-ASCII matches.
The current locale does not change the effect of this flag
unless the @ref{d63,,LOCALE} flag is also used.

インラインフラグの @code{(?i)} に相当します。

Unicode パターン @code{[a-z]} または @code{[A-Z]} が @ref{1a96,,IGNORECASE} フラグとあわせて使われたとき、52 の ASCII 文字に加えて 4 の非 ASCII 文字 'İ' (U+0130, Latin capital letter I with dot above) 、 'ı' (U+0131, Latin small letter dotless i) 、 'ſ' (U+017F, Latin small letter long s) および 'K' (U+212A, Kelvin sign) にマッチすることに注意してください。 @ref{83e,,ASCII} フラグが使われているなら、文字 'a' から 'z' および 'A' から 'Z' にのみマッチします。
@end deffn

@geindex L (re モジュール)
@geindex LOCALE (re モジュール)
@anchor{library/re re L}@anchor{2767}
@deffn {データ} re.L
@anchor{library/re re LOCALE}@anchor{d63}
@deffnx {データ} re.LOCALE

Make @code{\w}, @code{\W}, @code{\b}, @code{\B} and case-insensitive matching
dependent on the current locale.
This flag can be used only with bytes patterns.

インラインフラグの @code{(?L)} に相当します。

@cartouche
@quotation 警告 
This flag is discouraged; consider Unicode matching instead.
The locale mechanism is very unreliable
as it only handles one "culture" at a time
and only works with 8-bit locales.
Unicode matching is enabled by default for Unicode (str) patterns
and it is able to handle different locales and languages.
@end quotation
@end cartouche


バージョン 3.6 で変更: @ref{d63,,LOCALE} はバイト列パターンにのみ使え、@ref{83e,,ASCII} と互換ではありません。



バージョン 3.7 で変更: @ref{d63,,LOCALE} フラグがあるコンパイル済み正規表現オブジェクトはコンパイル時のロケールに依存しなくなりました。マッチング時のロケールのみがマッチングの結果に影響します。

@end deffn

@geindex M (re モジュール)
@geindex MULTILINE (re モジュール)
@anchor{library/re re M}@anchor{2768}
@deffn {データ} re.M
@anchor{library/re re MULTILINE}@anchor{2764}
@deffnx {データ} re.MULTILINE

指定されると、パターン文字 @code{'^'} は、文字列の先頭および各行の先頭(各改行の直後)とマッチします；そしてパターン文字 @code{'$'} は文字列の末尾および各行の末尾 (改行の直前) とマッチします。デフォルトでは、 @code{'^'} は、文字列の先頭とだけマッチし、 @code{'$'} は、文字列の末尾および文字列の末尾の改行の直前(がもしあれば)とマッチします。

インラインフラグの @code{(?m)} に相当します。
@end deffn

@geindex NOFLAG (re モジュール)
@anchor{library/re re NOFLAG}@anchor{2771}
@deffn {データ} re.NOFLAG

Indicates no flag being applied, the value is @code{0}.  This flag may be used
as a default value for a function keyword argument or as a base value that
will be conditionally ORed with other flags.  Example of use as a default
value:

@example
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
@end example


Added in version 3.11.

@end deffn

@geindex S (re モジュール)
@geindex DOTALL (re モジュール)
@anchor{library/re re S}@anchor{2769}
@deffn {データ} re.S
@anchor{library/re re DOTALL}@anchor{2763}
@deffnx {データ} re.DOTALL

特殊文字 @code{'.'} を、改行を含む任意の文字と、とにかくマッチさせます；このフラグがなければ、 @code{'.'} は、改行 `以外の' 任意の文字とマッチします。

インラインフラグの @code{(?s)} に相当します。
@end deffn

@geindex U (re モジュール)
@geindex UNICODE (re モジュール)
@anchor{library/re re U}@anchor{276a}
@deffn {データ} re.U
@anchor{library/re re UNICODE}@anchor{d64}
@deffnx {データ} re.UNICODE

In Python 3, Unicode characters are matched by default
for @code{str} patterns.
This flag is therefore redundant with `no effect'
and is only kept for backward compatibility.

See @ref{83e,,ASCII} to restrict matching to ASCII characters instead.
@end deffn

@geindex X (re モジュール)
@geindex VERBOSE (re モジュール)
@anchor{library/re re X}@anchor{276b}
@deffn {データ} re.X
@anchor{library/re re VERBOSE}@anchor{2772}
@deffnx {データ} re.VERBOSE

@geindex # (hash);in regular expressions

このフラグは正規表現を、パターンの論理的な節を視覚的に分割し、コメントを加えることで、見た目よく読みやすく書けるようにします。パターン中の空白は、文字クラス中にあるときと、エスケープされていないバックスラッシュの後にあるときと、 @code{*?} 、 @code{(?:} や @code{(?P<...>} のようなトークン中を除いて無視されます。たとえば、 @code{(? :} and @code{* ?} は許されません。ある行が文字クラス中でもエスケープされていないバックスラッシュの後でもない @code{#} を含むなら、一番左のそのような @code{#} から行末までの全ての文字は無視されます。

つまり、10 進数字にマッチする下記のふたつの正規表現オブジェクトは、機能的に等価です:

@example
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
@end example

インラインフラグの @code{(?x)} に相当します。
@end deffn

@node 関数<2>,例外<3>,フラグ,モジュールコンテンツ
@anchor{library/re functions}@anchor{2773}
@subsubsection 関数


@geindex compile() (re モジュール)
@anchor{library/re re compile}@anchor{dce}
@deffn {の関数} re.compile (pattern, flags=0)

正規表現パターンを @ref{1189,,正規表現オブジェクト} にコンパイルし、以下に述べる @ref{2774,,match()} 、 @ref{2775,,search()} その他のメソッドを使ってマッチングに使えるようにします。

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).

シーケンス

@example
prog = re.compile(pattern)
result = prog.match(string)
@end example

は、以下と同等です

@example
result = re.match(pattern, string)
@end example

が、 @ref{dce,,re.compile()} を使い、結果の正規表現オブジェクトを保存して再利用するほうが、一つのプログラムでその表現を何回も使うときに効率的です。

@cartouche
@quotation 注釈 
@ref{dce,,re.compile()} やモジュールレベルのマッチング関数に渡された最新のパターンはコンパイル済みのものがキャッシュされるので、一度に正規表現を少ししか使わないプログラムでは正規表現をコンパイルする必要はありません。
@end quotation
@end cartouche
@end deffn

@geindex search() (re モジュール)
@anchor{library/re re search}@anchor{1444}
@deffn {の関数} re.search (pattern, string, flags=0)

`string' 全体を走査して、正規表現 `pattern' がマッチを発生する最初の位置を探して、対応する @ref{ec3,,Match} を返します。もし文字列内に、そのパターンとマッチする位置がないならば、 @code{None} を返します；これは、文字列内のある点で長さゼロのマッチを探すこととは異なることに注意して下さい。

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).
@end deffn

@geindex match() (re モジュール)
@anchor{library/re re match}@anchor{1445}
@deffn {の関数} re.match (pattern, string, flags=0)

もし `string' の先頭で 0 個以上の文字が正規表現 `pattern' とマッチすれば、対応する @ref{ec3,,Match} を返します。もし文字列がパターンとマッチしなければ、 @code{None} を返します；これは長さゼロのマッチとは異なることに注意して下さい。

@ref{2764,,MULTILINE} モードにおいても、@ref{1445,,re.match()} は各行の先頭でマッチするのではなく、文字列の先頭でのみマッチすることに注意してください。

`string' 中のどこででもマッチさせたいなら、代わりに @ref{1444,,search()} を使ってください (@ref{2776,,search() vs. match()} も参照してください)。

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).
@end deffn

@geindex fullmatch() (re モジュール)
@anchor{library/re re fullmatch}@anchor{1187}
@deffn {の関数} re.fullmatch (pattern, string, flags=0)

`string' 全体が正規表現 `pattern' にマッチするなら、対応する @ref{ec3,,Match} を返します。文字列がパターンにマッチしないなら @code{None} を返します。これは長さ 0 のマッチとは異なることに注意して下さい。

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).


Added in version 3.4.

@end deffn

@geindex split() (re モジュール)
@anchor{library/re re split}@anchor{5a2}
@deffn {の関数} re.split (pattern, string, maxsplit=0, flags=0)

`string' を、出現した `pattern' で分割します。 `pattern' 中でキャプチャの丸括弧が使われていれば、パターン中の全てのグループのテキストも結果のリストの一部として返されます。`maxsplit' が 0 でなければ、分割は最大 `maxsplit' 回起こり、残りの文字列はリストの最終要素として返されます。

@example
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '@w{'}]
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '@w{'}]
>>> re.split(r'\W+', 'Words, words, words.', maxsplit=1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
@end example

セパレータ中にキャプチャグループがあり、それが文字列の先頭にマッチするなら、結果は空文字列で始まります。同じことが文字列の末尾にも言えます。

@example
>>> re.split(r'(\W+)', '...words, words...')
['@w{'}, '...', 'words', ', ', 'words', '...', '@w{'}]
@end example

そうして、結果のリストにおいて、セパレータの構成要素は常に同じ相対的インデックスに見つかります。

Adjacent empty matches are not possible, but an empty match can occur
immediately after a non-empty match.

@example
>>> re.split(r'\b', 'Words, words, words.')
['@w{'}, 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['@w{'}, '@w{'}, 'w', 'o', 'r', 'd', 's', '@w{'}, '@w{'}]
>>> re.split(r'(\W*)', '...words...')
['@w{'}, '...', '@w{'}, '@w{'}, 'w', '@w{'}, 'o', '@w{'}, 'r', '@w{'}, 'd', '@w{'}, 's', '...', '@w{'}, '@w{'}, '@w{'}]
@end example

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).


バージョン 3.1 で変更: オプションの flags 引数が追加されました。



バージョン 3.7 で変更: 空文字列にマッチしうるパターンでの分割をサポートするようになりました。



バージョン 3.13 で非推奨: Passing `maxsplit' and `flags' as positional arguments is deprecated.
In future Python versions they will be
@ref{5a5,,keyword-only parameters}.

@end deffn

@geindex findall() (re モジュール)
@anchor{library/re re findall}@anchor{122b}
@deffn {の関数} 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.

@example
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.findall(r'(\w+)=(\d+)', 'set width=20 and height=10')
[('width', '20'), ('height', '10')]
@end example

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).


バージョン 3.7 で変更: 空でないマッチが前の空マッチの直後から始められるようになりました。

@end deffn

@geindex finditer() (re モジュール)
@anchor{library/re re finditer}@anchor{1713}
@deffn {の関数} re.finditer (pattern, string, flags=0)

`string' 中の正規表現 `pattern' の重複しないマッチ全てに渡る @ref{ec3,,Match} オブジェクトを yield する @ref{4c8,,イテレータ} を返します。  `string' は左から右へ走査され、マッチは見つかった順で返されます。空マッチは結果に含まれます。

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).


バージョン 3.7 で変更: 空でないマッチが前の空マッチの直後から始められるようになりました。

@end deffn

@geindex sub() (re モジュール)
@anchor{library/re re sub}@anchor{5a3}
@deffn {の関数} re.sub (pattern, repl, string, count=0, flags=0)

`string' 中に出現する最も左の重複しない `pattern' を置換 `repl' で置換することで得られる文字列を返します。
パターンが見つからない場合、 `string' がそのまま返されます。
`repl' は文字列または関数です。
`repl' が文字列の場合は、その中の全てのバックスラッシュエスケープが処理されます。
@code{\n} は 1 つの改行文字に変換され、 @code{\r} はキャリッジリターンに変換される、などです。
ASCII 文字のエスケープで未知のものは将来使うために予約されていて、エラーとして扱われます。
それ以外の @code{\&} のような未知のエスケープは残されます。
@code{\6} のような後方参照は、パターンのグループ 6 がマッチした部分文字列で置換されます。
例えば:

@example
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n@{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n@{'
@end example

もし `repl' が関数であれば、重複しない `pattern' が発生するたびにその関数が呼ばれます。この関数は一つの @ref{ec3,,Match} 引数を取り、置換文字列を返します。例えば:

@example
>>> def dashrepl(matchobj):
...     if matchobj.group(0) == '-': return ' '
...     else: return '-'
...
>>> re.sub('-@{1,2@}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'
@end example

パターンは、文字列でも @ref{1b67,,Pattern} でも構いません。

The optional argument `count' is the maximum number of pattern occurrences to be
replaced; `count' must be a non-negative integer.  If omitted or zero, all
occurrences will be replaced.

Adjacent empty matches are not possible, but an empty match can occur
immediately after a non-empty match.
As a result, @code{sub('x*', '-', 'abxd')} returns @code{'-a-b--d-'}
instead of @code{'-a-b-d-'}.

@geindex \g;in regular expressions

文字列型 `repl' 引数では、上で述べた文字エスケープや後方参照に加えて、 @code{\g<name>} は @code{(?P<name>...)} 構文で定義された @code{name} という名前のグループがマッチした部分文字列を使い、 @code{\g<number>} は対応するグループ番号を使います。よって @code{\g<2>} は @code{\2} と等価ですが、 @code{\g<2>0} のような置換においても曖昧になりません。 @code{\20} は、グループ 20 への参照として解釈され、グループ 2 への参照にリテラル文字 @code{'0'} が続いたものとしては解釈されません。後方参照 @code{\g<0>} は正規表現とマッチした部分文字列全体で置き換わります。

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).


バージョン 3.1 で変更: オプションの flags 引数が追加されました。



バージョン 3.5 で変更: マッチしなかったグループは空文字列に置き換えられます。



バージョン 3.6 で変更: `pattern' 中に @code{'\'} と ASCII 文字からなる未知のエスケープがあると、エラーになります。



バージョン 3.7 で変更: Unknown escapes in `repl' consisting of @code{'\'} and an ASCII letter
now are errors.
An empty match can occur immediately after a non-empty match.



バージョン 3.12 で変更: Group `id' can only contain ASCII digits.
In @ref{192,,bytes} replacement strings, group `name' can only contain bytes
in the ASCII range (@code{b'\x00'}-@code{b'\x7f'}).



バージョン 3.13 で非推奨: Passing `count' and `flags' as positional arguments is deprecated.
In future Python versions they will be
@ref{5a5,,keyword-only parameters}.

@end deffn

@geindex subn() (re モジュール)
@anchor{library/re re subn}@anchor{5a4}
@deffn {の関数} re.subn (pattern, repl, string, count=0, flags=0)

@ref{5a3,,sub()} と同じ操作を行いますが、タプル @code{(new_string、 number_of_subs_made)} を返します。

The expression's behaviour can be modified by specifying a `flags' value.
Values can be any of the @ref{276f,,flags} variables, combined using bitwise OR
(the @code{|} operator).
@end deffn

@geindex escape() (re モジュール)
@anchor{library/re re escape}@anchor{e03}
@deffn {の関数} re.escape (pattern)

`pattern' 中の特殊文字をエスケープします。これは正規表現メタ文字を含みうる任意のリテラル文字列にマッチしたい時に便利です。

@example
>>> print(re.escape('https://www.python.org'))
https://www\.python\.org

>>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
>>> print('[%s]+' % re.escape(legal_chars))
[abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+

>>> operators = ['+', '-', '*', '/', '**']
>>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
/|\-|\+|\*\*|\*
@end example

この関数は、バックスラッシュのみをエスケープするべき @ref{5a3,,sub()} および @ref{5a4,,subn()} における置換文字列に使われてはなりません。例えば:

@example
>>> digits_re = r'\d+'
>>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings'
>>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample))
/usr/sbin/sendmail - \d+ errors, \d+ warnings
@end example


バージョン 3.3 で変更: @code{'_'} 文字がエスケープされなくなりました。



バージョン 3.7 で変更: 正規表現で特別な意味を持つ文字だけがエスケープされます。結果として、 @code{'!'}、 @code{'"'}、 @code{'%'}、 @code{"'"}、 @code{','}、 @code{'/'}、 @code{':'}、 @code{';'}、 @code{'<'}、 @code{'='}、 @code{'>'}、 @code{'@@'}、 と @code{"`"} はもはやエスケープされません。

@end deffn

@geindex purge() (re モジュール)
@anchor{library/re re purge}@anchor{2777}
@deffn {の関数} re.purge ()

正規表現キャッシュをクリアします。
@end deffn

@node 例外<3>,,関数<2>,モジュールコンテンツ
@anchor{library/re exceptions}@anchor{2778}
@subsubsection 例外


@geindex PatternError
@anchor{library/re re PatternError}@anchor{546}
@deffn {例外} re.PatternError (msg, pattern=None, pos=None)

Exception raised when a string passed to one of the functions here is not a
valid regular expression (for example, it might contain unmatched parentheses)
or when some other error occurs during compilation or matching.  It is never an
error if a string contains no match for a pattern.  The @code{PatternError} instance has
the following additional attributes:

@geindex msg (re.PatternError の属性)
@anchor{library/re re PatternError msg}@anchor{104b}
@deffn {の属性} msg

フォーマットされていないエラーメッセージです。
@end deffn

@geindex pattern (re.PatternError の属性)
@anchor{library/re re PatternError pattern}@anchor{104c}
@deffn {の属性} pattern

正規表現のパターンです。
@end deffn

@geindex pos (re.PatternError の属性)
@anchor{library/re re PatternError pos}@anchor{104d}
@deffn {の属性} pos

`pattern' のコンパイルに失敗した場所のインデックスです (@code{None} の場合もあります)。
@end deffn

@geindex lineno (re.PatternError の属性)
@anchor{library/re re PatternError lineno}@anchor{104e}
@deffn {の属性} lineno

`pos' に対応する行です (@code{None} の場合もあります)。
@end deffn

@geindex colno (re.PatternError の属性)
@anchor{library/re re PatternError colno}@anchor{104f}
@deffn {の属性} colno

`pos' に対応する列です (@code{None} の場合もあります)。
@end deffn


バージョン 3.5 で変更: 追加の属性が追加されました。



バージョン 3.13 で変更: @code{PatternError} was originally named @code{error}; the latter is kept as an alias for
backward compatibility.

@end deffn

@node 正規表現オブジェクト,マッチオブジェクト,モジュールコンテンツ,re --- 正規表現操作
@anchor{library/re re-objects}@anchor{1189}@anchor{library/re regular-expression-objects}@anchor{2779}
@subsubsection 正規表現オブジェクト


@geindex Pattern (re のクラス)
@anchor{library/re re Pattern}@anchor{1b67}
@deffn {クラス} re.Pattern

Compiled regular expression object returned by @ref{dce,,re.compile()}.


バージョン 3.9 で変更: @ref{1b67,,re.Pattern} supports @code{[]} to indicate a Unicode (str) or bytes pattern.
See @ref{8c1,,ジェネリックエイリアス型}.

@end deffn

@geindex search() (re.Pattern のメソッド)
@anchor{library/re re Pattern search}@anchor{2775}
@deffn {メソッド} Pattern.search (string[, pos[, endpos]])

`string' 全体を走査して、この正規表現がマッチを発生する最初の位置を探して、対応する @ref{ec3,,Match} を返します。もし文字列内に、そのパターンとマッチする位置がないならば、 @code{None} を返します；これは、文字列内のある点で長さゼロのマッチを探すこととは異なることに注意して下さい。

オプションの第二引数 `pos' は、文字列のどこから探し始めるかを指定するインデックスで、デフォルトでは 0 です。これは文字列のスライスと完全には同じではありません。パターン文字 @code{'^'} は本当の文字列の先頭と改行の直後でマッチしますが、検索を開始するインデックスでマッチするとは限りません。

オプションの引数 `endpos' は文字列がどこまで検索されるかを制限します。文字列の長さが `endpos' 文字だったかのようになるので、`pos' から @code{endpos - 1} の文字に対してだけマッチを探します。`endpos' が `pos' よりも小さいと、マッチは見つかりません。そうでなければ、`rx' をコンパイル済み正規表現オブジェクトとして、@code{rx.search(string, 0, 50)} は @code{rx.search(string[:50], 0)} と等価です。

@example
>>> pattern = re.compile("d")
>>> pattern.search("dog")     # Match at index 0
<re.Match object; span=(0, 1), match='d'>
>>> pattern.search("dog", 1)  # No match; search doesn't include the "d"
@end example
@end deffn

@geindex match() (re.Pattern のメソッド)
@anchor{library/re re Pattern match}@anchor{2774}
@deffn {メソッド} Pattern.match (string[, pos[, endpos]])

もし `string' の先頭で 0 個以上の文字がこの正規表現とマッチすれば、対応する @ref{ec3,,Match} を返します。もし文字列がパターンとマッチしなければ、 @code{None} を返します；これは長さゼロのマッチとは異なることに注意して下さい。

オプションの `pos' および `endpos' 引数は @ref{2775,,search()} メソッドのものと同じ意味です。

@example
>>> pattern = re.compile("o")
>>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
<re.Match object; span=(1, 2), match='o'>
@end example

`string' 中のどこででもマッチさせたいなら、代わりに @ref{2775,,search()} を使ってください (@ref{2776,,search() vs. match()} も参照してください)。
@end deffn

@geindex fullmatch() (re.Pattern のメソッド)
@anchor{library/re re Pattern fullmatch}@anchor{1188}
@deffn {メソッド} Pattern.fullmatch (string[, pos[, endpos]])

`string' 全体がこの正規表現にマッチするなら、対応する @ref{ec3,,Match} を返します。文字列がパターンにマッチしないなら @code{None} を返します。これは長さ 0 のマッチとは異なることに注意して下さい。

オプションの `pos' および `endpos' 引数は @ref{2775,,search()} メソッドのものと同じ意味です。

@example
>>> pattern = re.compile("o[gh]")
>>> pattern.fullmatch("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.fullmatch("ogre")     # No match as not the full string matches.
>>> pattern.fullmatch("doggie", 1, 3)   # Matches within given limits.
<re.Match object; span=(1, 3), match='og'>
@end example


Added in version 3.4.

@end deffn

@geindex split() (re.Pattern のメソッド)
@anchor{library/re re Pattern split}@anchor{277a}
@deffn {メソッド} Pattern.split (string, maxsplit=0)

@ref{5a2,,split()} 関数にこのコンパイル済みパターンを使うのと同じです。
@end deffn

@geindex findall() (re.Pattern のメソッド)
@anchor{library/re re Pattern findall}@anchor{277b}
@deffn {メソッド} Pattern.findall (string[, pos[, endpos]])

@ref{122b,,findall()} 関数にこのコンパイル済みパターンを使うのと似ていますが、オプションの `pos' および `endpos' 引数で @ref{1444,,search()} のように検索範囲を制限できます。
@end deffn

@geindex finditer() (re.Pattern のメソッド)
@anchor{library/re re Pattern finditer}@anchor{277c}
@deffn {メソッド} Pattern.finditer (string[, pos[, endpos]])

@ref{1713,,finditer()} 関数にこのコンパイル済みパターンを使うのと似ていますが、オプションの `pos' および `endpos' 引数で @ref{1444,,search()} のように検索範囲を制限できます。
@end deffn

@geindex sub() (re.Pattern のメソッド)
@anchor{library/re re Pattern sub}@anchor{277d}
@deffn {メソッド} Pattern.sub (repl, string, count=0)

@ref{5a3,,sub()} 関数にこのコンパイル済みパターンを使うのと同じです。
@end deffn

@geindex subn() (re.Pattern のメソッド)
@anchor{library/re re Pattern subn}@anchor{277e}
@deffn {メソッド} Pattern.subn (repl, string, count=0)

@ref{5a4,,subn()} 関数にこのコンパイル済みパターンを使うのと同じです。
@end deffn

@geindex flags (re.Pattern の属性)
@anchor{library/re re Pattern flags}@anchor{277f}
@deffn {の属性} Pattern.flags

正規表現のマッチングフラグです。これは @ref{dce,,compile()} に与えられたフラグ、パターン中の @code{(?...)} インラインフラグ、およびパターンが Unicode 文字列だった時の @ref{d64,,UNICODE} のような暗黙のフラグの組み合わせです。
@end deffn

@geindex groups (re.Pattern の属性)
@anchor{library/re re Pattern groups}@anchor{2780}
@deffn {の属性} Pattern.groups

パターン中のキャプチャグループの数です。
@end deffn

@geindex groupindex (re.Pattern の属性)
@anchor{library/re re Pattern groupindex}@anchor{2781}
@deffn {の属性} Pattern.groupindex

@code{(?P<id>)} で定義されたあらゆるシンボリックグループ名をグループ番号へ写像する辞書です。シンボリックグループがパターン中で全く使われていなければ、この辞書は空です。
@end deffn

@geindex pattern (re.Pattern の属性)
@anchor{library/re re Pattern pattern}@anchor{2782}
@deffn {の属性} Pattern.pattern

パターンオブジェクトがコンパイルされた元のパターン文字列です。
@end deffn


バージョン 3.7 で変更: @ref{757,,copy.copy()} および @ref{d65,,copy.deepcopy()} をサポートするようになりました。コンパイル済み正規表現オブジェクトはアトミックであると見なされます。


@node マッチオブジェクト,正規表現の例,正規表現オブジェクト,re --- 正規表現操作
@anchor{library/re id3}@anchor{2783}@anchor{library/re match-objects}@anchor{118a}
@subsubsection マッチオブジェクト


マッチオブジェクトのブール値は常に @code{True} です。 @ref{2774,,match()} および @ref{2775,,search()} はマッチがないとき @code{None} を返すので、マッチがあるか単純な @code{if} 文で判定できます。

@example
match = re.search(pattern, string)
if match:
    process(match)
@end example

@geindex Match (re のクラス)
@anchor{library/re re Match}@anchor{ec3}
@deffn {クラス} re.Match

Match object returned by successful @code{match}es and @code{search}es.


バージョン 3.9 で変更: @ref{ec3,,re.Match} supports @code{[]} to indicate a Unicode (str) or bytes match.
See @ref{8c1,,ジェネリックエイリアス型}.

@end deffn

@geindex expand() (re.Match のメソッド)
@anchor{library/re re Match expand}@anchor{2784}
@deffn {メソッド} Match.expand (template)

Return the string obtained by doing backslash substitution on the template
string `template', as done by the @ref{277d,,sub()} method.
Escapes such as @code{\n} are converted to the appropriate characters,
and numeric backreferences (@code{\1}, @code{\2}) and named backreferences
(@code{\g<1>}, @code{\g<name>}) are replaced by the contents of the
corresponding group. The backreference @code{\g<0>} will be
replaced by the entire match.


バージョン 3.5 で変更: マッチしなかったグループは空文字列に置き換えられます。

@end deffn

@geindex group() (re.Match のメソッド)
@anchor{library/re re Match group}@anchor{122c}
@deffn {メソッド} Match.group ([group1, ...])

このマッチの 1 つ以上のサブグループを返します。引数が 1 つなら結果は 1 つの文字列です。複数の引数があれば、結果は引数ごとに 1 項目のタプルです。引数がなければ、 `group1' はデフォルトで 0 (マッチ全体が返される) です。 `groupN' 引数が 0 なら、対応する返り値はマッチした文字列全体です。1 以上 99 以下なら、丸括弧による対応するグループにマッチする文字列です。グループ番号が負であるかパターン中で定義されたグループの数より大きければ、 @ref{174e,,IndexError} 例外が送出されます。あるグループがパターンのマッチしなかった部分に含まれているなら、対応する結果は @code{None} です。あるグループがパターンの複数回マッチした部分に含まれているなら、最後のマッチが返されます。

@example
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
('Isaac', 'Newton')
@end example

正規表現が @code{(?P<name>...)} 構文を使うなら、 `groupN' 引数はグループ名でグループを識別する文字列でも構いません。文字列引数がパターン中でグループ名として使われていなければ、 @ref{174e,,IndexError} 例外が送出されます。

やや複雑な例:

@example
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'
@end example

名前付きグループはインデックスでも参照できます:

@example
>>> m.group(1)
'Malcolm'
>>> m.group(2)
'Reynolds'
@end example

あるグループが複数回マッチすると、その最後のマッチにのみアクセスできます:

@example
>>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
>>> m.group(1)                        # Returns only the last match.
'c3'
@end example
@end deffn

@geindex __getitem__() (re.Match のメソッド)
@anchor{library/re re Match __getitem__}@anchor{2785}
@deffn {メソッド} Match.__getitem__ (g)

これは @code{m.group(g)} と同等です。これでマッチの個別のグループに簡単にアクセスできます:

@example
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m[0]       # The entire match
'Isaac Newton'
>>> m[1]       # The first parenthesized subgroup.
'Isaac'
>>> m[2]       # The second parenthesized subgroup.
'Newton'
@end example

Named groups are supported as well:

@example
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Isaac Newton")
>>> m['first_name']
'Isaac'
>>> m['last_name']
'Newton'
@end example


Added in version 3.6.

@end deffn

@geindex groups() (re.Match のメソッド)
@anchor{library/re re Match groups}@anchor{122d}
@deffn {メソッド} Match.groups (default=None)

このマッチの、1 からパターン中のグループ数まで、全てのサブグループを含むタプルを返します。`default' 引数はマッチに関係しなかったグループに使われます。デフォルトでは @code{None} です。

例えば:

@example
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')
@end example

少数位およびその後の全てをオプションにすると、全てのグループがマッチに関係するとは限りません。そういったグループは `default' 引数が与えられない限りデフォルトで @code{None} になります。

@example
>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups()      # Second group defaults to None.
('24', None)
>>> m.groups('0')   # Now, the second group defaults to '0'.
('24', '0')
@end example
@end deffn

@geindex groupdict() (re.Match のメソッド)
@anchor{library/re re Match groupdict}@anchor{2786}
@deffn {メソッド} Match.groupdict (default=None)

このマッチの、全ての `名前付き' サブグループを含む、サブグループ名をキーとする辞書を返します。 `default' 引数はマッチに関係しなかったグループに使われます。デフォルトは @code{None} です。例えば:

@example
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.groupdict()
@{'first_name': 'Malcolm', 'last_name': 'Reynolds'@}
@end example
@end deffn

@geindex start() (re.Match のメソッド)
@geindex end() (re.Match のメソッド)
@anchor{library/re re Match start}@anchor{2787}
@deffn {メソッド} Match.start ([group])
@anchor{library/re re Match end}@anchor{2788}
@deffnx {メソッド} Match.end ([group])

`group' がマッチした部分文字列の先頭と末尾のインデックスを返します。 `group' はデフォルトで 0 (マッチした部分文字列全体という意味) です。 `group' が存在してかつマッチには寄与していなかったなら @code{-1} を返します。マッチオブジェクト `m' と、マッチに寄与したグループ `g' に対して、グループ `g' がマッチした部分文字列 (@code{m.group(g)} と等価です) は以下の通りです

@example
m.string[m.start(g):m.end(g)]
@end example

`group' が空文字列にマッチしていたら @code{m.start(group)} は @code{m.end(group)} と等しくなることに注意して下さい。例えば、 @code{m = re.search('b(c?)', 'cba')} とすると、 @code{m.start(0)} は 1 で、 @code{m.end(0)} は 2 で、 @code{m.start(1)} と @code{m.end(1)} はともに 2 であり、 @code{m.start(2)} は @ref{174e,,IndexError} 例外を発生します。

メールアドレスから `remove_this' を取り除く例:

@example
>>> email = "tony@@tiremove_thisger.net"
>>> m = re.search("remove_this", email)
>>> email[:m.start()] + email[m.end():]
'tony@@tiger.net'
@end example
@end deffn

@geindex span() (re.Match のメソッド)
@anchor{library/re re Match span}@anchor{2789}
@deffn {メソッド} Match.span ([group])

マッチ `m' について、2 タプル @code{(m.start(group), m.end(group))} を返します。 `group' がマッチに寄与していなければ、これは @code{(-1, -1)} です。 `group' はデフォルトで 0 、マッチ全体です。
@end deffn

@geindex pos (re.Match の属性)
@anchor{library/re re Match pos}@anchor{278a}
@deffn {の属性} Match.pos

@ref{1189,,正規表現オブジェクト} の @ref{2775,,search()} や @ref{2774,,match()} に渡された `pos' の値です。これは正規表現エンジンがマッチを探し始める位置の文字列のインデックスです。
@end deffn

@geindex endpos (re.Match の属性)
@anchor{library/re re Match endpos}@anchor{278b}
@deffn {の属性} Match.endpos

@ref{1189,,正規表現オブジェクト} の @ref{2775,,search()} や @ref{2774,,match()} に渡された `endpos' の値です。これは正規表現エンジンがそれ以上は進まない文字列のインデックスです。
@end deffn

@geindex lastindex (re.Match の属性)
@anchor{library/re re Match lastindex}@anchor{278c}
@deffn {の属性} Match.lastindex

最後にマッチしたキャプチャグループの整数インデックスです。どのグループも全くマッチしなければ @code{None} です。例えば、表現 @code{(a)b} 、 @code{((a)(b))} や @code{((ab))} が @code{'ab'} に適用されると @code{lastindex == 1} となり、同じ文字列に @code{(a)(b)} が適用されると @code{lastindex == 2} となります。
@end deffn

@geindex lastgroup (re.Match の属性)
@anchor{library/re re Match lastgroup}@anchor{278d}
@deffn {の属性} Match.lastgroup

最後にマッチしたキャプチャグループの名前です。そのグループに名前がないか、どのグループも全くマッチしていなければ @code{None} です。
@end deffn

@geindex re (re.Match の属性)
@anchor{library/re re Match re}@anchor{278e}
@deffn {の属性} Match.re

このマッチインスタンスを生じさせた @ref{2774,,match()} または @ref{2775,,search()} メソッドの属する @ref{1189,,正規表現オブジェクト} です。
@end deffn

@geindex string (re.Match の属性)
@anchor{library/re re Match string}@anchor{278f}
@deffn {の属性} Match.string

@ref{2774,,match()} や @ref{2775,,search()} へ渡された文字列です。
@end deffn


バージョン 3.7 で変更: @ref{757,,copy.copy()} および @ref{d65,,copy.deepcopy()} をサポートするようになりました。マッチオブジェクトはアトミックであると見なされます。


@node 正規表現の例,,マッチオブジェクト,re --- 正規表現操作
@anchor{library/re re-examples}@anchor{1475}@anchor{library/re regular-expression-examples}@anchor{2790}
@subsubsection 正規表現の例


@menu
* ペアの確認:: 
* scanf() をシミュレートする: scanf をシミュレートする. 
* search() vs. match(): search vs match. 
* 電話帳を作る:: 
* テキストの秘匿:: 
* 全ての副詞を見つける:: 
* 全ての副詞とその位置を見つける:: 
* Raw 文字列記法:: 
* トークナイザを書く:: 

@end menu

@node ペアの確認,scanf をシミュレートする,,正規表現の例
@anchor{library/re checking-for-a-pair}@anchor{2791}
@subsubsection ペアの確認


この例では、マッチオブジェクトをより美しく表示するために、この補助関数を使用します:

@example
def displaymatch(match):
    if match is None:
        return None
    return '<Match: %r, groups=%r>' % (match.group(), match.groups())
@end example

あなたがポーカープログラムを書いているとします。プレイヤーの手札は 5 文字の文字列によって表され、それぞれの文字が 1 枚のカードを表します。 "a" はエース、 "k" はキング、 "q" はクイーン、 "j" はジャック、 "t" は 10、そして "2" から "9" はその数字のカードを表します。

与えられた文字列が有効な手札であるか見るには、以下のようにできます:

@example
>>> valid = re.compile(r"^[a2-9tjqk]@{5@}$")
>>> displaymatch(valid.match("akt5q"))  # Valid.
"<Match: 'akt5q', groups=()>"
>>> displaymatch(valid.match("akt5e"))  # Invalid.
>>> displaymatch(valid.match("akt"))    # Invalid.
>>> displaymatch(valid.match("727ak"))  # Valid.
"<Match: '727ak', groups=()>"
@end example

最後の手札、 @code{"727ak"} 、はペア、すなわち同じ値の 2 枚のカードを含みます。正規表現でこれにマッチするには、このように後方参照を使えます:

@example
>>> pair = re.compile(r".*(.).*\1")
>>> displaymatch(pair.match("717ak"))     # Pair of 7s.
"<Match: '717', groups=('7',)>"
>>> displaymatch(pair.match("718ak"))     # No pairs.
>>> displaymatch(pair.match("354aa"))     # Pair of aces.
"<Match: '354aa', groups=('a',)>"
@end example

ペアになっているのがどのカードか調べるには、このようにマッチオブジェクトの @ref{122c,,group()} メソッドを使えます:

@example
>>> pair = re.compile(r".*(.).*\1")
>>> pair.match("717ak").group(1)
'7'

# Error because re.match() returns None, which doesn't have a group() method:
>>> pair.match("718ak").group(1)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    re.match(r".*(.).*\1", "718ak").group(1)
AttributeError: 'NoneType' object has no attribute 'group'

>>> pair.match("354aa").group(1)
'a'
@end example

@node scanf をシミュレートする,search vs match,ペアの確認,正規表現の例
@anchor{library/re simulating-scanf}@anchor{2792}
@subsubsection scanf() をシミュレートする


@geindex scanf (C function)

Python には現在のところ、 @code{scanf()} に相当するものがありません。正規表現は一般的に、 @code{scanf()} のフォーマット文字列より強力ですが、冗長でもあります。以下の表に、 @code{scanf()} のフォーマットトークンと正規表現のおおよその対応付けを示します。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@code{scanf()} トークン

@tab

正規表現

@item

@code{%c}

@tab

@code{.}

@item

@code{%5c}

@tab

@code{.@{5@}}

@item

@code{%d}

@tab

@code{[-+]?\d+}

@item

@code{%e}, @code{%E}, @code{%f}, @code{%g}

@tab

@code{[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?}

@item

@code{%i}

@tab

@code{[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)}

@item

@code{%o}

@tab

@code{[-+]?[0-7]+}

@item

@code{%s}

@tab

@code{\S+}

@item

@code{%u}

@tab

@code{\d+}

@item

@code{%x}, @code{%X}

@tab

@code{[-+]?(0[xX])?[\dA-Fa-f]+}

@end multitable


以下のような文字列からファイル名と数を抽出するには

@example
/usr/sbin/sendmail - 0 errors, 4 warnings
@end example

以下のように @code{scanf()} フォーマットを使えます

@example
%s - %d errors, %d warnings
@end example

等価な正規表現はこうです

@example
(\S+) - (\d+) errors, (\d+) warnings
@end example

@node search vs match,電話帳を作る,scanf をシミュレートする,正規表現の例
@anchor{library/re id4}@anchor{2793}@anchor{library/re search-vs-match}@anchor{2776}
@subsubsection search() vs. match()


Python offers different primitive operations based on regular expressions:


@itemize +

@item 
@ref{1445,,re.match()} checks for a match only at the beginning of the string

@item 
@ref{1444,,re.search()} checks for a match anywhere in the string
(this is what Perl does by default)

@item 
@ref{1187,,re.fullmatch()} checks for entire string to be a match
@end itemize

例えば:

@example
>>> re.match("c", "abcdef")    # No match
>>> re.search("c", "abcdef")   # Match
<re.Match object; span=(2, 3), match='c'>
>>> re.fullmatch("p.*n", "python") # Match
<re.Match object; span=(0, 6), match='python'>
>>> re.fullmatch("r.*n", "python") # No match
@end example

@code{'^'} で始まる正規表現を @ref{1444,,search()} で使って、マッチを文字列の先頭でのみに制限できます:

@example
>>> re.match("c", "abcdef")    # No match
>>> re.search("^c", "abcdef")  # No match
>>> re.search("^a", "abcdef")  # Match
<re.Match object; span=(0, 1), match='a'>
@end example

ただし、 @ref{2764,,MULTILINE} モードにおいて @ref{1445,,match()} は文字列の先頭でのみマッチし、 @code{'^'} で始まる正規表現で @ref{1444,,search()} を使うと各行の先頭でマッチすることに注意してください。

@example
>>> re.match("X", "A\nB\nX", re.MULTILINE)  # No match
>>> re.search("^X", "A\nB\nX", re.MULTILINE)  # Match
<re.Match object; span=(4, 5), match='X'>
@end example

@node 電話帳を作る,テキストの秘匿,search vs match,正規表現の例
@anchor{library/re making-a-phonebook}@anchor{2794}
@subsubsection 電話帳を作る


@ref{5a2,,split()} は渡されたパターンで文字列を分割してリストにします。このメソッドは、テキストデータをデータ構造に変換して、読みやすくしたり、以下の例で実演する電話帳作成のように Python で編集したりしやすくするのに、非常に役に立ちます。

最初に、入力を示します。通常、これはファイルからの入力になるでしょう。ここでは、3重引用符の書式とします。

@example
>>> text = """Ross McFluff: 834.345.1254 155 Elm Street
...
... Ronald Heathmore: 892.345.3428 436 Finley Avenue
... Frank Burger: 925.541.7625 662 South Dogwood Way
...
...
... Heather Albrecht: 548.326.4584 919 Park Place"""
@end example

各項目は 1 つ以上の改行で区切られています。まずは文字列を変換して、空行でない各行を項目とするリストにします:

@example
>>> entries = re.split("\n+", text)
>>> entries
['Ross McFluff: 834.345.1254 155 Elm Street',
'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
'Frank Burger: 925.541.7625 662 South Dogwood Way',
'Heather Albrecht: 548.326.4584 919 Park Place']
@end example

そして各項目を、ファーストネーム、ラストネーム、電話番号、住所に分割してリストにします。分割パターンである空白文字は住所にも含まれるので、 @ref{5a2,,split()} の @code{maxsplit} 引数を使います:

@example
>>> [re.split(":? ", entry, maxsplit=3) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
@end example

この @code{:?} パターンはラストネームの次のコロンにマッチして、分割結果のリストに出てこないようにします。 @code{maxsplit} を @code{4} にすれば、家屋番号とストリート名を分割できます:

@example
>>> [re.split(":? ", entry, maxsplit=4) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
@end example

@node テキストの秘匿,全ての副詞を見つける,電話帳を作る,正規表現の例
@anchor{library/re text-munging}@anchor{2795}
@subsubsection テキストの秘匿


@ref{5a3,,sub()} は出現する各パターンを文字列で、または関数の返り値で置き換えます。この例ではテキストを「秘匿」する関数と合わせて @ref{5a3,,sub()} を使うところを実演します。具体的には、文中の各単語について、最初と最後の文字を除く全ての文字をランダムに並び替えます:

@example
>>> def repl(m):
...     inner_word = list(m.group(2))
...     random.shuffle(inner_word)
...     return m.group(1) + "".join(inner_word) + m.group(3)
...
>>> text = "Professor Abdolmalek, please report your absences promptly."
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
@end example

@node 全ての副詞を見つける,全ての副詞とその位置を見つける,テキストの秘匿,正規表現の例
@anchor{library/re finding-all-adverbs}@anchor{2796}
@subsubsection 全ての副詞を見つける


@ref{1444,,search()} は最初のパターンにのみマッチしますが、 @ref{122b,,findall()} は出現する `全ての' パターンにマッチします。例えば、ライターがあるテキストの全ての副詞を見つけたいなら、以下のように @ref{122b,,findall()} を使えます:

@example
>>> text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly\b", text)
['carefully', 'quickly']
@end example

@node 全ての副詞とその位置を見つける,Raw 文字列記法,全ての副詞を見つける,正規表現の例
@anchor{library/re finding-all-adverbs-and-their-positions}@anchor{2797}
@subsubsection 全ての副詞とその位置を見つける


パターンの全てのマッチについて、マッチしたテキスト以上の情報が必要なら、文字列ではなく @ref{ec3,,Match} を返す @ref{1713,,finditer()} が便利です。先の例に続いて、ライターがあるテキストの全ての副詞 `およびその位置' を見つけたいなら、以下のように @ref{1713,,finditer()} を使えます:

@example
>>> text = "He was carefully disguised but captured quickly by police."
>>> for m in re.finditer(r"\w+ly\b", text):
...     print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
07-16: carefully
40-47: quickly
@end example

@node Raw 文字列記法,トークナイザを書く,全ての副詞とその位置を見つける,正規表現の例
@anchor{library/re raw-string-notation}@anchor{2798}
@subsubsection Raw 文字列記法


Raw 文字列記法 (@code{r"text"}) で正規表現をまともに保てます。それがなければ、正規表現中のバックスラッシュ (@code{'\'}) を個々にバックスラッシュを前置してエスケープしなければなりません。例えば、以下の 2 行のコードは機能的に等価です:

@example
>>> re.match(r"\W(.)\1\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>
>>> re.match("\\W(.)\\1\\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>
@end example

リテラルのバックスラッシュにマッチさせたいなら、正規表現中ではエスケープする必要があります。Raw 文字列記法では、@code{r"\\"}  になります。Raw 文字列記法を用いないと、@code{"\\\\"} としなくてはならず、以下のコードは機能的に等価です:

@example
>>> re.match(r"\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>
>>> re.match("\\\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>
@end example

@node トークナイザを書く,,Raw 文字列記法,正規表現の例
@anchor{library/re writing-a-tokenizer}@anchor{2799}
@subsubsection トークナイザを書く


トークナイザやスキャナ@footnote{https://en.wikipedia.org/wiki/Lexical_analysis} は文字列を解析し、文字のグループにカテゴリ分けします。これはコンパイラやインタプリタを書くうえで役立つ第一段階です。

テキストのカテゴリは正規表現で指定されます。この技法では、それらを一つのマスター正規表現に結合し、マッチの連続についてループします:

@example
from typing import NamedTuple
import re

class Token(NamedTuple):
    type: str
    value: str
    line: int
    column: int

def tokenize(code):
    keywords = @{'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'@}
    token_specification = [
        ('NUMBER',   r'\d+(\.\d*)?'),  # Integer or decimal number
        ('ASSIGN',   r':='),           # Assignment operator
        ('END',      r';'),            # Statement terminator
        ('ID',       r'[A-Za-z]+'),    # Identifiers
        ('OP',       r'[+\-*/]'),      # Arithmetic operators
        ('NEWLINE',  r'\n'),           # Line endings
        ('SKIP',     r'[ \t]+'),       # Skip over spaces and tabs
        ('MISMATCH', r'.'),            # Any other character
    ]
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
    line_num = 1
    line_start = 0
    for mo in re.finditer(tok_regex, code):
        kind = mo.lastgroup
        value = mo.group()
        column = mo.start() - line_start
        if kind == 'NUMBER':
            value = float(value) if '.' in value else int(value)
        elif kind == 'ID' and value in keywords:
            kind = value
        elif kind == 'NEWLINE':
            line_start = mo.end()
            line_num += 1
            continue
        elif kind == 'SKIP':
            continue
        elif kind == 'MISMATCH':
            raise RuntimeError(f'@{value!r@} unexpected on line @{line_num@}')
        yield Token(kind, value, line_num, column)

statements = '@w{'}'
    IF quantity THEN
        total := total + price * quantity;
        tax := price * 0.05;
    ENDIF;
'@w{'}'

for token in tokenize(statements):
    print(token)
@end example

このトークナイザは以下の出力を作成します:

@example
Token(type='IF', value='IF', line=2, column=4)
Token(type='ID', value='quantity', line=2, column=7)
Token(type='THEN', value='THEN', line=2, column=16)
Token(type='ID', value='total', line=3, column=8)
Token(type='ASSIGN', value=':=', line=3, column=14)
Token(type='ID', value='total', line=3, column=17)
Token(type='OP', value='+', line=3, column=23)
Token(type='ID', value='price', line=3, column=25)
Token(type='OP', value='*', line=3, column=31)
Token(type='ID', value='quantity', line=3, column=33)
Token(type='END', value=';', line=3, column=41)
Token(type='ID', value='tax', line=4, column=8)
Token(type='ASSIGN', value=':=', line=4, column=12)
Token(type='ID', value='price', line=4, column=15)
Token(type='OP', value='*', line=4, column=21)
Token(type='NUMBER', value=0.05, line=4, column=23)
Token(type='END', value=';', line=4, column=27)
Token(type='ENDIF', value='ENDIF', line=5, column=4)
Token(type='END', value=';', line=5, column=9)
@end example

@anchor{library/re frie09}@anchor{2761}@w{(Frie09)} 
Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O'Reilly Media, 2009. 当書の第三版ではもはや Python についてまったく取り扱っていませんが、初版では良い正規表現を書くことを綿密に取り扱っていました。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node difflib --- 差分の計算の補助,textwrap --- テキストの折り返しと詰め込み,re --- 正規表現操作,テキスト処理サービス
@anchor{library/difflib doc}@anchor{279a}@anchor{library/difflib difflib-helpers-for-computing-deltas}@anchor{279b}@anchor{library/difflib module-difflib}@anchor{3b}@anchor{library/difflib translation-repo}@anchor{279c}
@subsection @code{difflib} --- 差分の計算の補助


@geindex module; difflib

@c Markup by Fred L. Drake, Jr. <fdrake@acm.org>

`ソースコード:' Lib/difflib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/difflib.py}

@c import sys
@c from difflib import *


__________________________________________________________________


このモジュールは、シーケンスを比較するためのクラスや関数を提供しています。例えば、ファイルの差分を計算して、それを HTML や context diff, unified diff などいろいろなフォーマットで出力するために、このモジュールを利用できます。ディレクトリやファイル群を比較するためには、 @ref{5e,,filecmp} モジュールも参照してください。


@deffn {クラス} difflib.SequenceMatcher

柔軟性のあるクラスで、二つのシーケンスの要素が @ref{824,,ハッシュ可能} な型であれば、どの型の要素を含むシーケンスも比較可能です。基本的なアルゴリズムは、1980年代の後半に発表された Ratcliff と Obershelp による"ゲシュタルトパターンマッチング"と大げさに名づけられたアルゴリズム以前から知られている、やや凝ったアルゴリズムです。その考え方は、"junk" 要素を含まない最も長い互いに隣接したマッチ列を探すことです。ここで、  "junk" 要素とは、空行や空白などの、意味を持たない要素のことです。 (junk を処理するのは、Ratcliff と Obershelp のアルゴリズムに追加された拡張です。)この考え方は、マッチ列の左右に隣接するシーケンスの断片に対して再帰的にあてはめられます。この方法では編集を最小にするシーケンスは生まれませんが、人間の目からみて「正しい感じ」にマッチする傾向があります。

`実行時間:' 基本的な Ratcliff-Obershelp アルゴリズムは、最悪の場合3乗、期待値で2乗となります。 @ref{121b,,SequenceMatcher} オブジェクトでは、最悪のケースで2乗、期待値は比較されるシーケンス中に共通に現れる要素数に非常にややこしく依存しています。最良の場合は線形時間になります。

`自動 junk ヒューリスティック:' @ref{121b,,SequenceMatcher} は、シーケンスの特定の要素を自動的に junk として扱うヒューリスティックをサポートしています。このヒューリスティックは、各個要素がシーケンス内に何回現れるかを数えます。ある要素の重複数が (最初のものは除いて) 合計でシーケンスの 1% 以上になり、そのシーケンスが 200 要素以上なら、その要素は "popular" であるものとしてマークされ、シーケンスのマッチングの目的からは junk として扱われます。このヒューリスティックは、 @ref{121b,,SequenceMatcher} の作成時に @code{autojunk} パラメタを @code{False} に設定することで無効化できます。


バージョン 3.2 で変更: Added the `autojunk' parameter.

@end deffn

@geindex Differ (difflib のクラス)
@anchor{library/difflib difflib Differ}@anchor{279d}
@deffn {クラス} difflib.Differ

テキスト行からなるシーケンスを比較するクラスです。人が読むことのできる差分を作成します。 Differ クラスは @ref{121b,,SequenceMatcher} クラスを利用して、行からなるシーケンスを比較したり、(ほぼ)同一の行内の文字を比較したりします。

@ref{279d,,Differ} クラスによる差分の各行は、2文字のコードで始まります:


@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

コード

@tab

意味

@item

@code{'- '}

@tab

行はシーケンス1にのみ存在する

@item

@code{'+ '}

@tab

行はシーケンス2にのみ存在する

@item

@code{'  '}

@tab

行は両方のシーケンスで同一

@item

@code{'? '}

@tab

行は入力シーケンスのどちらにも存在しない

@end multitable


Lines beginning with '@code{?}' attempt to guide the eye to intraline differences,
and were not present in either input sequence. These lines can be confusing if
the sequences contain whitespace characters, such as spaces, tabs or line breaks.
@end deffn

@geindex HtmlDiff (difflib のクラス)
@anchor{library/difflib difflib HtmlDiff}@anchor{201}
@deffn {クラス} difflib.HtmlDiff

このクラスは、二つのテキストを左右に並べて比較表示し、行間あるいは行内の変更点を強調表示するような HTML テーブル (またはテーブルの入った完全な HTML ファイル) を生成するために使います。テーブルは完全差分モード、コンテキスト差分モードのいずれでも生成できます。

このクラスのコンストラクタは以下のようになっています:

@geindex __init__() (difflib.HtmlDiff のメソッド)
@anchor{library/difflib difflib HtmlDiff __init__}@anchor{279e}
@deffn {メソッド} __init__ (tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)

@ref{201,,HtmlDiff} のインスタンスを初期化します。

`tabsize' はオプションのキーワード引数で、タブストップ幅を指定します。デフォルトは @code{8} です。

`wrapcolumn' はオプションのキーワード引数で、テキストを折り返すカラム幅を指定します。デフォルトは @code{None} で折り返しを行いません。

`linejunk' および `charjunk' はオプションのキーワード引数で、 @ref{279f,,ndiff()}  (@ref{201,,HtmlDiff} はこの関数を使って左右のテキストの差分を HTML で生成します) に渡されます。それぞれの引数のデフォルト値および説明は @ref{279f,,ndiff()} のドキュメントを参照してください。
@end deffn

以下のメソッドが public になっています:

@geindex make_file() (difflib.HtmlDiff のメソッド)
@anchor{library/difflib difflib HtmlDiff make_file}@anchor{ff0}
@deffn {メソッド} make_file (fromlines, tolines, fromdesc='@w{'}, todesc='@w{'}, context=False, numlines=5, *, charset='utf-8')

`fromlines' と `tolines' (いずれも文字列のリスト) を比較し、行間または行内の変更点が強調表示された行差分の入った表を持つ完全な HTML ファイルを文字列で返します。

`fromdesc' および `todesc' はオプションのキーワード引数で、差分表示テーブルにおけるそれぞれ差分元、差分先ファイルのカラムのヘッダになる文字列を指定します (いずれもデフォルト値は空文字列です)。

`context' および `numlines' はともにオプションのキーワード引数です。`context' を @code{True} にするとコンテキスト差分を表示し、デフォルトの @code{False} にすると完全なファイル差分を表示します。`numlines' のデフォルト値は @code{5} で、`context' が @code{True} の場合、`numlines' は強調部分の前後にあるコンテキスト行の数を制御します。`context' が @code{False} の場合、`numlines' は "next" と書かれたハイパーリンクをたどった時に到達する場所が次の変更部分より何行前にあるかを制御します (値をゼロにした場合、"next" ハイパーリンクを辿ると変更部分の強調表示がブラウザの最上部に表示されるようになります)。

@cartouche
@quotation 注釈 
`fromdesc' と `todesc' はエスケープされていないHTMLとして解釈されます。信頼できないソースからの入力を受け取る際には適切にエスケープされるべきです。
@end quotation
@end cartouche


バージョン 3.5 で変更: `charset' キーワード専用引数が追加されました。HTML 文書のデフォルトの文字集合が @code{'ISO-8859-1'} から @code{'utf-8'} に変更されました。

@end deffn

@geindex make_table() (difflib.HtmlDiff のメソッド)
@anchor{library/difflib difflib HtmlDiff make_table}@anchor{27a0}
@deffn {メソッド} make_table (fromlines, tolines, fromdesc='@w{'}, todesc='@w{'}, context=False, numlines=5)

`fromlines' と `tolines' (いずれも文字列のリスト) を比較し、行間または行内の変更点が強調表示された行差分の入った完全な HTML テーブルを文字列で返します。

このメソッドの引数は、 @ref{ff0,,make_file()} メソッドの引数と同じです。
@end deffn
@end deffn

@geindex context_diff() (difflib モジュール)
@anchor{library/difflib difflib context_diff}@anchor{1986}
@deffn {の関数} difflib.context_diff (a, b, fromfile='@w{'}, tofile='@w{'}, fromfiledate='@w{'}, tofiledate='@w{'}, n=3, lineterm='\n')

`a' と `b' (文字列のリスト) を比較し、差分 (差分形式の行を生成する @ref{126c,,ジェネレータ}) を、 context diff のフォーマット(以下「コンテキスト形式」)で返します。

コンテキスト形式は、変更があった行に前後数行を加えてある、コンパクトな表現方法です。変更箇所は、変更前/変更後に分けて表します。コンテキスト (変更箇所前後の行) の行数は `n' で指定し、デフォルト値は 3 です。

デフォルトで、 diff 制御行 (@code{***} や @code{---} を含む行) は改行付きで生成されます。 @ref{27a1,,io.IOBase.readlines()} で作られた入力が @ref{177a,,io.IOBase.writelines()} で扱うのに適した diff になるので (なぜなら入力と出力の両方が改行付きのため) 、これは有用です。

行末に改行文字を持たない入力に対しては、出力でも改行文字を付加しないように `lineterm' 引数に @code{""} を渡してください。

コンテキスト形式は、通常、ヘッダにファイル名と変更時刻を持っています。この情報は、文字列 `fromfile', `tofile', `fromfiledate', `tofiledate' で指定できます。変更時刻の書式は、通常、ISO 8601 フォーマットで表されます。指定しなかった場合のデフォルト値は、空文字列です。

@example
>>> import sys
>>> from difflib import *
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py',
...                        tofile='after.py'))
*** before.py
--- after.py
***************
*** 1,4 ****
! bacon
! eggs
! ham
  guido
--- 1,4 ----
! python
! eggy
! hamster
  guido
@end example

より詳細な例は、 @ref{27a2,,difflib のコマンドラインインターフェース} を参照してください。
@end deffn

@geindex get_close_matches() (difflib モジュール)
@anchor{library/difflib difflib get_close_matches}@anchor{27a3}
@deffn {の関数} difflib.get_close_matches (word, possibilities, n=3, cutoff=0.6)

「十分」なマッチの上位のリストを返します。`word' はマッチさせたいシーケンス (大概は文字列) です。`possibilities' は `word' にマッチさせるシーケンスのリスト (大概は文字列のリスト) です。

オプションの引数 `n' (デフォルトでは @code{3})はメソッドの返すマッチの最大数です。`n' は @code{0} より大きくなければなりません。

オプションの引数 `cutoff' (デフォルトでは @code{0.6})は、区間 [0, 1] に入る小数の値です。`word' との一致率がそれ未満の `possibilities' の要素は無視されます。

`possibilities' の要素でマッチした上位(多くても `n' 個)は、類似度のスコアに応じて(一番似たものを先頭に)ソートされたリストとして返されます。

@example
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('pineapple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']
@end example
@end deffn

@geindex ndiff() (difflib モジュール)
@anchor{library/difflib difflib ndiff}@anchor{279f}
@deffn {の関数} difflib.ndiff (a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)

`a' と `b' (文字列のリスト) を比較し、差分 (差分形式の行を生成する @ref{126c,,ジェネレータ}) を、 @ref{279d,,Differ} のスタイルで返します。

オプションのキーワード引数 `linejunk' と `charjunk' には、フィルタ関数 (または @code{None}) を渡します。

`linejunk': A function that accepts a single string argument, and returns
true if the string is junk, or false if not. The default is @code{None}. There
is also a module-level function @ref{2d7,,IS_LINE_JUNK()}, which filters out lines
without visible characters, except for at most one hash character (@code{'#'})
-- however the underlying @ref{121b,,SequenceMatcher} class does a dynamic
analysis of which lines are so frequent as to constitute noise, and this
usually works better than using this function.

`charjunk': 文字 (長さ1の文字列) を受け取る関数です。文字列が junk の場合は真を、そうでない場合は偽を返します。デフォルトでは、モジュールレべルの関数 @ref{27a4,,IS_CHARACTER_JUNK()} であり、これは空白文字類 (空白またはタブ、改行文字をこれに含めてはいけません) をフィルタして排除します。

@example
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
>>> print('@w{'}.join(diff), end="")
- one
?  ^
+ ore
?  ^
- two
- three
?  -
+ tree
+ emu
@end example
@end deffn

@geindex restore() (difflib モジュール)
@anchor{library/difflib difflib restore}@anchor{27a5}
@deffn {の関数} difflib.restore (sequence, which)

差分を生成した元の二つのシーケンスのうち一つを返します。

@ref{27a6,,Differ.compare()} または @ref{279f,,ndiff()} によって生成された `sequence' を与えられると、行頭のプレフィクスを取りのぞいてファイル 1 または 2 (引数 `which' で指定される) に由来する行を復元します。

例:

@example
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
>>> diff = list(diff) # materialize the generated delta into a list
>>> print('@w{'}.join(restore(diff, 1)), end="")
one
two
three
>>> print('@w{'}.join(restore(diff, 2)), end="")
ore
tree
emu
@end example
@end deffn

@geindex unified_diff() (difflib モジュール)
@anchor{library/difflib difflib unified_diff}@anchor{1985}
@deffn {の関数} difflib.unified_diff (a, b, fromfile='@w{'}, tofile='@w{'}, fromfiledate='@w{'}, tofiledate='@w{'}, n=3, lineterm='\n')

`a' と `b' (文字列のリスト) を比較し、差分 (差分形式の行を生成する @ref{126c,,ジェネレータ}) を、 unified diff フォーマット(以下「ユニファイド形式」)で返します。

ユニファイド形式は変更があった行にコンテキストとなる前後数行を加えた、コンパクトな表現方法です。変更箇所は (変更前/変更後を分離したブロックではなく) インラインスタイルで表されます。コンテキストの行数は、`n' で指定し、デフォルト値は 3 です。

デフォルトで、 diff 制御行 (@code{---}, @code{+++}, @code{@@@@} を含む行) は改行付きで生成されます。 @ref{27a1,,io.IOBase.readlines()} で作られた入力が @ref{177a,,io.IOBase.writelines()} で扱うのに適した diff になるので (なぜなら入力と出力の両方が改行付きのため) 、これは有用です。

行末に改行文字を持たない入力に対しては、出力でも改行文字を付加しないように `lineterm' 引数に @code{""} を渡してください。

The unified diff format normally has a header for filenames and modification
times.  Any or all of these may be specified using strings for `fromfile',
`tofile', `fromfiledate', and `tofiledate'.  The modification times are normally
expressed in the ISO 8601 format. If not specified, the
strings default to blanks.

@example
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
--- before.py
+++ after.py
@@@@ -1,4 +1,4 @@@@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido
@end example

より詳細な例は、 @ref{27a2,,difflib のコマンドラインインターフェース} を参照してください。
@end deffn

@geindex diff_bytes() (difflib モジュール)
@anchor{library/difflib difflib diff_bytes}@anchor{ff1}
@deffn {の関数} difflib.diff_bytes (dfunc, a, b, fromfile=b'@w{'}, tofile=b'@w{'}, fromfiledate=b'@w{'}, tofiledate=b'@w{'}, n=3, lineterm=b'\n')

`dfunc' を使用して `a' と `b' (bytes オブジェクトのリスト) を比較して、差分形式の行 (これも bytes オブジェクトです) を*dfunc* の戻り値の形式で返します。`dfunc' は、呼び出し可能である必要があります。一般に、これは @ref{1985,,unified_diff()} または @ref{1986,,context_diff()} です。

未知のエンコーディングまたは一貫性のないエンコーディングのデータ同士を比較できます。`n' 以外のすべての入力は、bytes オブジェクトである必要があります。`n' 以外のすべての入力を損失なく str に変換して、@code{dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)} を呼び出すことにより動作します。`dfunc' の出力は、bytes 型に変換されます。これにより、受け取る差分形式の行のエンコーディングは、`a' と `b' の未知または一貫性のないエンコーディングと同一になります。


Added in version 3.5.

@end deffn

@geindex IS_LINE_JUNK() (difflib モジュール)
@anchor{library/difflib difflib IS_LINE_JUNK}@anchor{2d7}
@deffn {の関数} difflib.IS_LINE_JUNK (line)

無視できる行のとき @code{True} を返します。行 `line' は空白、または  @code{'#'} ひとつのときに無視できます。それ以外のときには無視できません。古いバージョンでは @ref{279f,,ndiff()} の引数 `linejunk' にデフォルトで使用されました。
@end deffn

@geindex IS_CHARACTER_JUNK() (difflib モジュール)
@anchor{library/difflib difflib IS_CHARACTER_JUNK}@anchor{27a4}
@deffn {の関数} difflib.IS_CHARACTER_JUNK (ch)

無視できる文字のとき @code{True} を返します。文字 `ch' が空白、またはタブ文字のときには無視できます。それ以外の時には無視できません。 @ref{279f,,ndiff()} の引数 `charjunk' としてデフォルトで使用されます。
@end deffn


@subsubheading 参考



@table @asis

@item Pattern Matching: The Gestalt Approach@footnote{https://jacobfilipp.com/DrDobbs/articles/DDJ/1988/8807/8807c/8807c.htm}

Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
was published in Dr. Dobb's Journal in July, 1988.
@end table


@menu
* SequenceMatcherオブジェクト:: 
* SequenceMatcher の例:: 
* Differ オブジェクト:: 
* Differ の例:: 
* difflib のコマンドラインインターフェース:: 
* ndiff example:: 

@end menu

@node SequenceMatcherオブジェクト,SequenceMatcher の例,,difflib --- 差分の計算の補助
@anchor{library/difflib sequence-matcher}@anchor{27a7}@anchor{library/difflib sequencematcher-objects}@anchor{27a8}
@subsubsection SequenceMatcherオブジェクト


@ref{121b,,SequenceMatcher} クラスには、以下のようなコンストラクタがあります:

@geindex SequenceMatcher (difflib のクラス)
@anchor{library/difflib difflib SequenceMatcher}@anchor{121b}
@deffn {クラス} difflib.SequenceMatcher (isjunk=None, a='@w{'}, b='@w{'}, autojunk=True)

オプションの引数 `isjunk' は、@code{None} (デフォルトの値です) にするか、単一の引数をとる関数でなければなりません。後者の場合、関数はシーケンスの要素を受け取り、要素が junk であり、無視すべきである場合に限り真を返すようにしなければなりません。`isjunk' に @code{None} を渡すと、@code{lambda x: False} を渡したのと同じになります; すなわち、いかなる要素も無視しなくなります。例えば以下のような引数を渡すと:

@example
lambda x: x in " \t"
@end example

空白とタブ文字を無視して文字のシーケンスを比較します。

オプションの引数 `a' と `b' は、比較される文字列で、デフォルトでは空の文字列です。両方のシーケンスの要素は、 @ref{824,,ハッシュ可能} である必要があります。

オプションの引数 `autojunk' は、自動 junk ヒューリスティックを無効にするために使えます。


バージョン 3.2 で変更: Added the `autojunk' parameter.


SequenceMatcher オブジェクトは3つのデータ属性を持っています: `bjunk' は、 `isjunk' が @code{True} であるような `b' の要素の集合です; `bpopular' は、 (無効でなければ) ヒューリスティックによって popular であると考えられる非ジャンク要素の集合です; `b2j' は、 `b' の残りの要素をそれらが生じる位置のリストに写像する dict です。この 3 つは @ref{27a9,,set_seqs()} または @ref{27aa,,set_seq2()} で `b' がリセットされる場合は常にリセットされます。


Added in version 3.2: `bjunk' および `bpopular' 属性。


@ref{121b,,SequenceMatcher} オブジェクトは以下のメソッドを持ちます:

@geindex set_seqs() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher set_seqs}@anchor{27a9}
@deffn {メソッド} set_seqs (a, b)

比較される2つの文字列を設定します。
@end deffn

@ref{121b,,SequenceMatcher} オブジェクトは、2つ目のシーケンスについての詳細な情報を計算し、キャッシュします。 1つのシーケンスをいくつものシーケンスと比較する場合、まず @ref{27aa,,set_seq2()} を使って文字列を設定しておき、別の文字列を1つずつ比較するために、繰り返し @ref{27ab,,set_seq1()} を呼び出します。

@geindex set_seq1() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher set_seq1}@anchor{27ab}
@deffn {メソッド} set_seq1 (a)

比較を行う1つ目のシーケンスを設定します。比較される2つ目のシーケンスは変更されません。
@end deffn

@geindex set_seq2() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher set_seq2}@anchor{27aa}
@deffn {メソッド} set_seq2 (b)

比較を行う2つ目のシーケンスを設定します。比較される1つ目のシーケンスは変更されません。
@end deffn

@geindex find_longest_match() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher find_longest_match}@anchor{1d4b}
@deffn {メソッド} find_longest_match (alo=0, ahi=None, blo=0, bhi=None)

@code{a[alo:ahi]} と @code{b[blo:bhi]} の中から、最長のマッチ列を探します。

`isjunk' が省略されたか @code{None} の時、 @ref{1d4b,,find_longest_match()} は @code{a[i:i+k]} が @code{b[j:j+k]} と等しいような @code{(i, j, k)} を返します。その値は @code{alo <= i <= i+k <= ahi} かつ @code{blo <= j <= j+k <= bhi} となります。 @code{(i', j', k')} でも、同じようになります。さらに @code{k >= k'}, @code{i <= i'} が @code{i == i'}, @code{j <= j'} でも同様です。言い換えると、いくつものマッチ列すべてのうち、 `a' 内で最初に始まるものを返します。そしてその `a' 内で最初のマッチ列すべてのうち `b' 内で最初に始まるものを返します。

@example
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
@end example

引数 `isjunk' が与えられている場合、上記の通り、はじめに最長のマッチ列を判定します。ブロック内に junk 要素が見当たらないような追加条件の際はこれに該当しません。次にそのマッチ列を、その両側の junk 要素にマッチするよう、できる限り広げていきます。そのため結果となる列は、探している列のたまたま直前にあった同一の junk 以外の junk にはマッチしません。

以下は前と同じサンプルですが、空白を junk とみなしています。これは @code{' abcd'} が2つ目の列の末尾にある @code{' abcd'} にマッチしないようにしています。代わりに @code{'abcd'} にはマッチします。そして 2つ目の文字列中、一番左の @code{'abcd'} にマッチします:

@example
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
@end example

どんな列にもマッチしない時は、@code{(alo, blo, 0)} を返します。

このメソッドは @ref{85e,,named tuple} @code{Match(a, b, size)} を返します。


バージョン 3.9 で変更: デフォルト引数が追加されました。

@end deffn

@geindex get_matching_blocks() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher get_matching_blocks}@anchor{27ac}
@deffn {メソッド} get_matching_blocks ()

マッチした互いに重複の無いシーケンスを表す、3つ組の値のリストを返します。
それぞれの値は @code{(i, j, n)} という形式で表され、@code{a[i:i+n] == b[j:j+n]} という関係を意味します。3つの値は `i' と `j' の間で単調に増加します。

最後の3つ組はダミーで、@code{(len(a), len(b), 0)} という値を持ちます。これは @code{n == 0} である唯一のタプルです。もし @code{(i, j, n)} と @code{(i', j', n')} がリストで並んでいる3つ組で、2つ目が最後の3つ組でなければ、@code{i+n < i'} または @code{j+n < j'} です。言い換えると並んでいる3つ組は常に隣接していない同じブロックを表しています。

@c XXX Explain why a dummy is used!

@example
>>> s = SequenceMatcher(None, "abxcd", "abcd")
>>> s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
@end example
@end deffn

@geindex get_opcodes() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher get_opcodes}@anchor{27ad}
@deffn {メソッド} get_opcodes ()

`a' を `b' にするための方法を記述する5つのタプルを返します。それぞれのタプルは @code{(tag, i1, i2, j1, j2)} という形式であらわされます。最初のタプルは @code{i1 == j1 == 0} であり、`i1' はその前にあるタプルの `i2' と同じ値です。同様に `j1' は前の `j2' と同じ値になります。

`tag' の値は文字列であり、次のような意味です:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

値

@tab

意味

@item

@code{'replace'}

@tab

@code{a[i1:i2]} は @code{b[j1:j2]} に置き換えられる。

@item

@code{'delete'}

@tab

@code{a[i1:i2]} は削除される。この時、@code{j1 == j2} である。

@item

@code{'insert'}

@tab

@code{b[j1:j2]} が @code{a[i1:i1]} に挿入される。この時 @code{i1 == i2} である。

@item

@code{'equal'}

@tab

@code{a[i1:i2] == b[j1:j2]} (サブシーケンスは等しい).

@end multitable


例えば:

@example
>>> a = "qabxcd"
>>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
...     print('@{:7@}   a[@{@}:@{@}] --> b[@{@}:@{@}] @{!r:>8@} --> @{!r@}'.format(
...         tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
delete    a[0:1] --> b[0:0]      'q' --> '@w{'}
equal     a[1:3] --> b[0:2]     'ab' --> 'ab'
replace   a[3:4] --> b[2:3]      'x' --> 'y'
equal     a[4:6] --> b[3:5]     'cd' --> 'cd'
insert    a[6:6] --> b[5:6]       '@w{'} --> 'f'
@end example
@end deffn

@geindex get_grouped_opcodes() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher get_grouped_opcodes}@anchor{27ae}
@deffn {メソッド} get_grouped_opcodes (n=3)

最大 `n' 行までのコンテキストを含むグループを生成するような、 @ref{126c,,ジェネレータ} を返します。

このメソッドは、 @ref{27ad,,get_opcodes()} で返されるグループの中から、似たような差異のかたまりに分け、間に挟まっている変更の無い部分を省きます。

グループは @ref{27ad,,get_opcodes()} と同じ書式で返されます。
@end deffn

@geindex ratio() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher ratio}@anchor{27af}
@deffn {メソッド} ratio ()

[0, 1] の範囲の浮動小数点数で、シーケンスの類似度を測る値を返します。

T が2つのシーケンスの要素数の総計だと仮定し、M をマッチした数とすると、この値は 2.0*M / T であらわされます。もしシーケンスがまったく同じ場合、値は @code{1.0} となり、まったく異なる場合には @code{0.0} となります。

このメソッドは @ref{27ac,,get_matching_blocks()} または @ref{27ad,,get_opcodes()} がまだ呼び出されていない場合には非常にコストが高いです。この場合、上限を素早く計算するために、 @ref{27b0,,quick_ratio()} もしくは @ref{27b1,,real_quick_ratio()} を最初に試してみる方がいいかもしれません。

@cartouche
@quotation 注釈 
注意: @ref{27af,,ratio()} の呼び出しの結果は引数の順序に依存します。例えば次の通りです:

@example
>>> SequenceMatcher(None, 'tide', 'diet').ratio()
0.25
>>> SequenceMatcher(None, 'diet', 'tide').ratio()
0.5
@end example
@end quotation
@end cartouche
@end deffn

@geindex quick_ratio() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher quick_ratio}@anchor{27b0}
@deffn {メソッド} quick_ratio ()

@ref{27af,,ratio()} の上界を、より高速に計算します。
@end deffn

@geindex real_quick_ratio() (difflib.SequenceMatcher のメソッド)
@anchor{library/difflib difflib SequenceMatcher real_quick_ratio}@anchor{27b1}
@deffn {メソッド} real_quick_ratio ()

@ref{27af,,ratio()} の上界を、非常に高速に計算します。
@end deffn
@end deffn

The three methods that return the ratio of matching to total characters can give
different results due to differing levels of approximation, although
@ref{27b0,,quick_ratio()} and @ref{27b1,,real_quick_ratio()}
are always at least as large as @ref{27af,,ratio()}:

@example
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0
@end example

@node SequenceMatcher の例,Differ オブジェクト,SequenceMatcherオブジェクト,difflib --- 差分の計算の補助
@anchor{library/difflib id1}@anchor{27b2}@anchor{library/difflib sequencematcher-examples}@anchor{27b3}
@subsubsection SequenceMatcher の例


この例は2つの文字列を比較します。空白を "junk" とします:

@example
>>> s = SequenceMatcher(lambda x: x == " ",
...                     "private Thread currentThread;",
...                     "private volatile Thread currentThread;")
@end example

@ref{27af,,ratio()} returns a float in [0, 1], measuring the similarity of the
sequences.  As a rule of thumb, a @ref{27af,,ratio()} value over 0.6 means the
sequences are close matches:

@example
>>> print(round(s.ratio(), 3))
0.866
@end example

If you're only interested in where the sequences match,
@ref{27ac,,get_matching_blocks()} is handy:

@example
>>> for block in s.get_matching_blocks():
...     print("a[%d] and b[%d] match for %d elements" % block)
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements
@end example

Note that the last tuple returned by @ref{27ac,,get_matching_blocks()}
is always a dummy, @code{(len(a), len(b), 0)}, and this is the only case in which the last
tuple element (number of elements matched) is @code{0}.

If you want to know how to change the first sequence into the second, use
@ref{27ad,,get_opcodes()}:

@example
>>> for opcode in s.get_opcodes():
...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
 equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
 equal a[8:29] b[17:38]
@end example


@subsubheading 参考



@itemize *

@item 
@ref{121b,,SequenceMatcher} を使った、シンプルで使えるコードを知るには、このモジュールの関数 @ref{27a3,,get_close_matches()} を参照してください。

@item 
Simple version control recipe@footnote{https://code.activestate.com/recipes/576729-simple-version-control/} for a small application
built with @ref{121b,,SequenceMatcher}.
@end itemize


@node Differ オブジェクト,Differ の例,SequenceMatcher の例,difflib --- 差分の計算の補助
@anchor{library/difflib differ-objects}@anchor{27b4}@anchor{library/difflib id2}@anchor{27b5}
@subsubsection Differ オブジェクト


@ref{279d,,Differ} オブジェクトによって生成された差分が `最小' であるなどとは言いません。むしろ、最小の差分はしばしば直観に反しています。その理由は、どこでもできるとなれば一致を見いだしてしまうからで、ときには思いがけなく100ページも離れたマッチになってしまうのです。一致点を互いに隣接したマッチに制限することで、場合によって長めの差分を出力するというコストを掛けることにはなっても、ある種の局所性を保つことができるのです。

@ref{279d,,Differ} は、以下のようなコンストラクタを持ちます:


@deffn {クラス} difflib.Differ (linejunk=None, charjunk=None)

オプションのキーワードパラメータ `linejunk' と `charjunk' は、フィルタ関数を渡します (使わないときは @code{None}):

`linejunk': ひとつの文字列引数を受け取る関数です。文字列が junk のときに真を返します。デフォルトでは、@code{None} であり、どんな行であっても junk とは見なされません。

`charjunk': この関数は文字(長さ1の文字列)を引数として受け取り、文字が junk であるときに真を返します。デフォルトは @code{None} であり、どんな文字も junk とは見なされません。

これらの junk フィルター関数により、差分を発見するマッチングが高速化し、差分の行や文字が無視されることがなくなります。説明については、 @ref{1d4b,,find_longest_match()} メソッドの `isjunk' 引数の説明をご覧ください。

@ref{279d,,Differ} オブジェクトは、以下の1つのメソッドを通して利用されます。（差分を生成します）:

@geindex compare() (difflib.Differ のメソッド)
@anchor{library/difflib difflib Differ compare}@anchor{27a6}
@deffn {メソッド} compare (a, b)

文字列からなる2つのシーケンスを比較し、差分（を表す文字列からなるシーケンス）を生成します。

各シーケンスの要素は、改行で終わる独立した単一行からなる文字列でなければなりません。そのようなシーケンスは、ファイル風オブジェクトの @ref{27a1,,readlines()} メソッドによって得ることができます。（得られる）差分は改行文字で終了する文字列のシーケンスとして得られ、ファイル風オブジェクトの @ref{177a,,writelines()} メソッドによって出力できる形になっています。
@end deffn
@end deffn

@node Differ の例,difflib のコマンドラインインターフェース,Differ オブジェクト,difflib --- 差分の計算の補助
@anchor{library/difflib differ-example}@anchor{27b6}@anchor{library/difflib differ-examples}@anchor{27b7}
@subsubsection Differ の例


This example compares two texts. First we set up the texts, sequences of
individual single-line strings ending with newlines (such sequences can also be
obtained from the @ref{27a1,,readlines()} method of file-like objects):

@example
>>> text1 = '@w{'}'  1. Beautiful is better than ugly.
...   2. Explicit is better than implicit.
...   3. Simple is better than complex.
...   4. Complex is better than complicated.
... '@w{'}'.splitlines(keepends=True)
>>> len(text1)
4
>>> text1[0][-1]
'\n'
>>> text2 = '@w{'}'  1. Beautiful is better than ugly.
...   3.   Simple is better than complex.
...   4. Complicated is better than complex.
...   5. Flat is better than nested.
... '@w{'}'.splitlines(keepends=True)
@end example

次に Differ オブジェクトをインスタンス化します:

@example
>>> d = Differ()
@end example

注意:  @ref{279d,,Differ} オブジェクトをインスタンス化するとき、行 junk と文字 junk をフィルタリングする関数を渡すことができます。詳細は @ref{279d,,Differ()} コンストラクタを参照してください。

最後に、2つを比較します:

@example
>>> result = list(d.compare(text1, text2))
@end example

@code{result} は文字列のリストなので、pretty-printしてみましょう:

@example
>>> from pprint import pprint
>>> pprint(result)
['    1. Beautiful is better than ugly.\n',
 '-   2. Explicit is better than implicit.\n',
 '-   3. Simple is better than complex.\n',
 '+   3.   Simple is better than complex.\n',
 '?     ++\n',
 '-   4. Complex is better than complicated.\n',
 '?            ^                     ---- ^\n',
 '+   4. Complicated is better than complex.\n',
 '?           ++++ ^                      ^\n',
 '+   5. Flat is better than nested.\n']
@end example

これは、複数行の文字列として、次のように出力されます:

@example
>>> import sys
>>> sys.stdout.writelines(result)
    1. Beautiful is better than ugly.
-   2. Explicit is better than implicit.
-   3. Simple is better than complex.
+   3.   Simple is better than complex.
?     ++
-   4. Complex is better than complicated.
?            ^                     ---- ^
+   4. Complicated is better than complex.
?           ++++ ^                      ^
+   5. Flat is better than nested.
@end example

@node difflib のコマンドラインインターフェース,ndiff example,Differ の例,difflib --- 差分の計算の補助
@anchor{library/difflib a-command-line-interface-to-difflib}@anchor{27b8}@anchor{library/difflib difflib-interface}@anchor{27a2}
@subsubsection difflib のコマンドラインインターフェース


This example shows how to use difflib to create a @code{diff}-like utility.

@example
""" Command line interface to difflib.py providing diffs in four formats:

* ndiff:    lists every line and highlights interline changes.
* context:  highlights clusters of changes in a before/after format.
* unified:  highlights clusters of changes in an inline format.
* html:     generates side by side comparison with change highlights.

"""

import sys, os, difflib, argparse
from datetime import datetime, timezone

def file_mtime(path):
    t = datetime.fromtimestamp(os.stat(path).st_mtime,
                               timezone.utc)
    return t.astimezone().isoformat()

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', action='store_true', default=False,
                        help='Produce a context format diff (default)')
    parser.add_argument('-u', action='store_true', default=False,
                        help='Produce a unified format diff')
    parser.add_argument('-m', action='store_true', default=False,
                        help='Produce HTML side by side diff '
                             '(can use -c and -l in conjunction)')
    parser.add_argument('-n', action='store_true', default=False,
                        help='Produce a ndiff format diff')
    parser.add_argument('-l', '--lines', type=int, default=3,
                        help='Set number of context lines (default 3)')
    parser.add_argument('fromfile')
    parser.add_argument('tofile')
    options = parser.parse_args()

    n = options.lines
    fromfile = options.fromfile
    tofile = options.tofile

    fromdate = file_mtime(fromfile)
    todate = file_mtime(tofile)
    with open(fromfile) as ff:
        fromlines = ff.readlines()
    with open(tofile) as tf:
        tolines = tf.readlines()

    if options.u:
        diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
    elif options.n:
        diff = difflib.ndiff(fromlines, tolines)
    elif options.m:
        diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
    else:
        diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)

    sys.stdout.writelines(diff)

if __name__ == '__main__':
    main()
@end example

@node ndiff example,,difflib のコマンドラインインターフェース,difflib --- 差分の計算の補助
@anchor{library/difflib ndiff-example}@anchor{27b9}
@subsubsection ndiff example


This example shows how to use @ref{279f,,difflib.ndiff()}.

@example
"""ndiff [-q] file1 file2
    or
ndiff (-r1 | -r2) < ndiff_output > file1_or_file2

Print a human-friendly file difference report to stdout.  Both inter-
and intra-line differences are noted.  In the second form, recreate file1
(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.

In the first form, if -q ("quiet") is not specified, the first two lines
of output are

-: file1
+: file2

Each remaining line begins with a two-letter code:

    "- "    line unique to file1
    "+ "    line unique to file2
    "  "    line common to both files
    "? "    line not present in either input file

Lines beginning with "? " attempt to guide the eye to intraline
differences, and were not present in either input file.  These lines can be
confusing if the source files contain tab characters.

The first file can be recovered by retaining only lines that begin with
"  " or "- ", and deleting those 2-character prefixes; use ndiff with -r1.

The second file can be recovered similarly, but by retaining only "  " and
"+ " lines; use ndiff with -r2; or, on Unix, the second file can be
recovered by piping the output through

    sed -n '/^[+ ] /s/^..//p'
"""

__version__ = 1, 7, 0

import difflib, sys

def fail(msg):
    out = sys.stderr.write
    out(msg + "\n\n")
    out(__doc__)
    return 0

# open a file & return the file object; gripe and return 0 if it
# couldn't be opened
def fopen(fname):
    try:
        return open(fname)
    except IOError as detail:
        return fail("couldn't open " + fname + ": " + str(detail))

# open two files & spray the diff to stdout; return false iff a problem
def fcompare(f1name, f2name):
    f1 = fopen(f1name)
    f2 = fopen(f2name)
    if not f1 or not f2:
        return 0

    a = f1.readlines(); f1.close()
    b = f2.readlines(); f2.close()
    for line in difflib.ndiff(a, b):
        print(line, end=' ')

    return 1

# crack args (sys.argv[1:] is normal) & compare;
# return false iff a problem

def main(args):
    import getopt
    try:
        opts, args = getopt.getopt(args, "qr:")
    except getopt.error as detail:
        return fail(str(detail))
    noisy = 1
    qseen = rseen = 0
    for opt, val in opts:
        if opt == "-q":
            qseen = 1
            noisy = 0
        elif opt == "-r":
            rseen = 1
            whichfile = val
    if qseen and rseen:
        return fail("can't specify both -q and -r")
    if rseen:
        if args:
            return fail("no args allowed with -r option")
        if whichfile in ("1", "2"):
            restore(whichfile)
            return 1
        return fail("-r value must be 1 or 2")
    if len(args) != 2:
        return fail("need 2 filename args")
    f1name, f2name = args
    if noisy:
        print('-:', f1name)
        print('+:', f2name)
    return fcompare(f1name, f2name)

# read ndiff output from stdin, and print file1 (which=='1') or
# file2 (which=='2') to stdout

def restore(which):
    restored = difflib.restore(sys.stdin.readlines(), which)
    sys.stdout.writelines(restored)

if __name__ == '__main__':
    main(sys.argv[1:])
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node textwrap --- テキストの折り返しと詰め込み,unicodedata --- Unicode データベース,difflib --- 差分の計算の補助,テキスト処理サービス
@anchor{library/textwrap doc}@anchor{27ba}@anchor{library/textwrap module-textwrap}@anchor{f2}@anchor{library/textwrap textwrap-text-wrapping-and-filling}@anchor{27bb}@anchor{library/textwrap translation-repo}@anchor{27bc}
@subsection @code{textwrap} --- テキストの折り返しと詰め込み


@geindex module; textwrap

`ソースコード:' Lib/textwrap.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/textwrap.py}


__________________________________________________________________


The @code{textwrap} module provides some convenience functions,
as well as @ref{11cf,,TextWrapper}, the class that does all the work.
If you're just wrapping or filling one or two text strings, the convenience
functions should be good enough; otherwise, you should use an instance of
@ref{11cf,,TextWrapper} for efficiency.

@geindex wrap() (textwrap モジュール)
@anchor{library/textwrap textwrap wrap}@anchor{16e0}
@deffn {の関数} textwrap.wrap (text, width=70, *, initial_indent='@w{'}, subsequent_indent='@w{'}, expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')

`text' (文字列)内の段落を一つだけ折り返しを行います。したがって、すべての行が高々 `width' 文字の長さになります。最後に改行が付かない出力行のリストを返します。

オプションのキーワード引数は、以下で説明する @ref{11cf,,TextWrapper} のインスタンス属性に対応しています。

@ref{16e0,,wrap()} の動作についての詳細は @ref{27bd,,TextWrapper.wrap()} メソッドを参照してください。
@end deffn

@geindex fill() (textwrap モジュール)
@anchor{library/textwrap textwrap fill}@anchor{16df}
@deffn {の関数} textwrap.fill (text, width=70, *, initial_indent='@w{'}, subsequent_indent='@w{'}, expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')

`text' 内の段落を一つだけ折り返しを行い、折り返しが行われた段落を含む一つの文字列を返します。 @ref{16df,,fill()} はこれの省略表現です

@example
"\n".join(wrap(text, ...))
@end example

特に、 @ref{16df,,fill()} は @ref{16e0,,wrap()} とまったく同じ名前のキーワード引数を受け取ります。
@end deffn

@geindex shorten() (textwrap モジュール)
@anchor{library/textwrap textwrap shorten}@anchor{11d2}
@deffn {の関数} textwrap.shorten (text, width, *, fix_sentence_endings=False, break_long_words=True, break_on_hyphens=True, placeholder=' [...]')

与えられた `text' を折りたたみ、切り詰めて、与えられた `width' に収まるようにします。

最初に、`text' 内の空白が折りたたまれます (すべての空白を、1 文字の空白文字で置き換えます)。結果が `width' 内に収まった場合、その結果が返されます。width に収まらない場合、残りの文字数と  `placeholder'  との和が  `width' 内に収まるように、末尾から単語が切り捨てられます:

@example
>>> textwrap.shorten("Hello  world!", width=12)
'Hello world!'
>>> textwrap.shorten("Hello  world!", width=11)
'Hello [...]'
>>> textwrap.shorten("Hello world", width=10, placeholder="...")
'Hello...'
@end example

オプションのキーワード引数は、以下で説明する @ref{11cf,,TextWrapper} インスタンスの属性に対応します。文字列が @ref{11cf,,TextWrapper} の @ref{16df,,fill()} 関数に渡される前に、空白が折りたたまれます。そのため、@ref{27be,,tabsize}、@ref{27bf,,expand_tabs}、@ref{27c0,,drop_whitespace}、@ref{27c1,,replace_whitespace} の値を変更しても、意味がありません。


Added in version 3.4.

@end deffn

@geindex dedent() (textwrap モジュール)
@anchor{library/textwrap textwrap dedent}@anchor{1a9}
@deffn {の関数} textwrap.dedent (text)

`text' の各行に対し、共通して現れる先頭の空白を削除します。

この関数は通常、三重引用符で囲われた文字列をスクリーン/その他の左端にそろえ、なおかつソースコード中ではインデントされた形式を損なわないようにするために使われます。

タブとスペースはともにホワイトスペースとして扱われますが、同じではないことに注意してください:  @code{"  hello"} という行と @code{"\thello"}  は、同じ先頭の空白文字をもっていないとみなされます。

空白文字しか含まない行は入力の際に無視され、出力の際に単一の改行文字に正規化されます。

例えば:

@example
def test():
    # end first line with \ to avoid the empty line!
    s = '@w{'}'\
    hello
      world
    '@w{'}'
    print(repr(s))          # prints '    hello\n      world\n    '
    print(repr(dedent(s)))  # prints 'hello\n  world\n'
@end example


バージョン 3.14 で変更: The @code{dedent()} function now correctly normalizes blank lines containing
only whitespace characters. Previously, the implementation only normalized
blank lines containing tabs and spaces.

@end deffn

@geindex indent() (textwrap モジュール)
@anchor{library/textwrap textwrap indent}@anchor{57d}
@deffn {の関数} textwrap.indent (text, prefix, predicate=None)

`text' の中の選択された行の先頭に `prefix' を追加します。

行の分割は @code{text.splitlines(True)} で行います。

デフォルトでは、(改行文字を含む)空白文字だけの行を除いてすべての行に `prefix' を追加します。

例えば:

@example
>>> s = 'hello\n\n \nworld'
>>> indent(s, '  ')
'  hello\n\n \n  world'
@end example

省略可能な `predicate' 引数を使って、どの行をインデントするかを制御することができます。例えば、空行や空白文字のみの行にも `prefix' を追加するのは簡単です:

@example
>>> print(indent(s, '+ ', lambda line: True))
+ hello
+
+
+ world
@end example


Added in version 3.3.

@end deffn

@ref{16e0,,wrap()}、@ref{16df,,fill()}、@ref{11d2,,shorten()} は @ref{11cf,,TextWrapper} インスタンスを作成し、その一つのメソッドを呼び出すことで機能します。そのインスタンスは再利用されません。したがって、@ref{16e0,,wrap()} や @ref{16df,,fill()} を使用して多くのテキスト文字列を処理するアプリケーションについては、独自の @ref{11cf,,TextWrapper} オブジェクトを作成する方が効率が良い方法でしょう。

テキストはなるべく空白か、ハイフンを含む語のハイフンの直後で折り返されます。 @ref{27c2,,TextWrapper.break_long_words} が偽に設定されていなければ、必要な場合に長い語が分解されます。

@geindex TextWrapper (textwrap のクラス)
@anchor{library/textwrap textwrap TextWrapper}@anchor{11cf}
@deffn {クラス} textwrap.TextWrapper (**kwargs)

@ref{11cf,,TextWrapper} コンストラクタはたくさんのオプションのキーワード引数を受け取ります。それぞれのキーワード引数は一つのインスタンス属性に対応します。したがって、例えば

@example
wrapper = TextWrapper(initial_indent="* ")
@end example

はこれと同じです

@example
wrapper = TextWrapper()
wrapper.initial_indent = "* "
@end example

同じ @ref{11cf,,TextWrapper} オブジェクトは何回も再利用できます。また、使用中にインスタンス属性へ代入することでそのオプションのどれでも変更できます。

@ref{11cf,,TextWrapper} インスタンス属性(とコンストラクタのキーワード引数)は以下の通りです:

@geindex width (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper width}@anchor{27c3}
@deffn {の属性} width

(デフォルト: @code{70}) 折り返しが行われる行の最大の長さ。入力行に @ref{27c3,,width} より長い単一の語が無い限り、 @ref{11cf,,TextWrapper} は @ref{27c3,,width} 文字より長い出力行が無いことを保証します。
@end deffn

@geindex expand_tabs (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper expand_tabs}@anchor{27bf}
@deffn {の属性} expand_tabs

(デフォルト: @code{True}) もし真ならば、そのときは `text' 内のすべてのタブ文字は `text' の @ref{2647,,expandtabs()} メソッドを用いて空白に展開されます。
@end deffn

@geindex tabsize (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper tabsize}@anchor{27be}
@deffn {の属性} tabsize

(デフォルト: @code{8}) @ref{27bf,,expand_tabs} が真の場合、 `text' の中のすべてのTAB文字は tabsize と現在のカラムに応じて、ゼロ以上のスペースに展開されます。


Added in version 3.3.

@end deffn

@geindex replace_whitespace (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper replace_whitespace}@anchor{27c1}
@deffn {の属性} replace_whitespace

(デフォルト: @code{True}) 真の場合、 @ref{16e0,,wrap()} メソッドはタブの展開の後、 wrap 処理の前に各種空白文字をスペース1文字に置換します。置換される空白文字は: TAB, 改行, 垂直TAB, FF, CR (@code{'\t\n\v\f\r'}) です。

@cartouche
@quotation 注釈 
@ref{27bf,,expand_tabs} が偽で @ref{27c1,,replace_whitespace} が真ならば、各タブ文字は1つの空白に置き換えられます。それはタブ展開と同じでは `ありません' 。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
@ref{27c1,,replace_whitespace} が偽の場合、改行が行の途中で現れることで出力がおかしくなることがあります。このため、テキストを(@ref{146e,,str.splitlines()} などを使って)段落ごとに分けて別々に wrap する必要があります。
@end quotation
@end cartouche
@end deffn

@geindex drop_whitespace (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper drop_whitespace}@anchor{27c0}
@deffn {の属性} drop_whitespace

(デフォルト: @code{True}) 真の場合、(wrap 処理のあとインデント処理の前に) 各行の最初と最後の空白文字を削除します。ただし、段落の最初の空白については、次の文字が空白文字でない場合は削除されません。削除される空白文字が行全体に及ぶ場合は、行自体を削除します。
@end deffn

@geindex initial_indent (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper initial_indent}@anchor{27c4}
@deffn {の属性} initial_indent

(default: @code{'@w{'}})  wrap の出力の最初の行の先頭に付与する文字列。最初の行の長さに加算されます。空文字列の場合インデントされません。
@end deffn

@geindex subsequent_indent (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper subsequent_indent}@anchor{27c5}
@deffn {の属性} subsequent_indent

(デフォルト: @code{'@w{'}}) 一行目以外の折り返しが行われる出力のすべての行の先頭に付けられる文字列。一行目以外の各行の折り返しまでの長さにカウントされます。
@end deffn

@geindex fix_sentence_endings (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper fix_sentence_endings}@anchor{27c6}
@deffn {の属性} fix_sentence_endings

(デフォルト: @code{False}) もし真ならば、 @ref{11cf,,TextWrapper} は文の終わりを見つけようとし、確実に文がちょうど二つの空白で常に区切られているようにします。これは一般的に固定スペースフォントのテキストに対して望ましいです。しかし、文の検出アルゴリズムは完全ではありません: 文の終わりには、後ろに空白がある @code{'.'}, @code{'!'} または @code{'?'} の中の一つ、ことによると @code{'"'} あるいは @code{"'"} が付随する小文字があると仮定しています。このアルゴリズムに伴う一つの問題は下記の"Dr."と

@example
[...] Dr. Frankenstein's monster [...]
@end example

下記の"Spot."の間の差異を検出できないことです

@example
[...] See Spot. See Spot run [...]
@end example

@ref{27c6,,fix_sentence_endings} はデフォルトで偽です。

文検出アルゴリズムは"小文字"の定義のために @code{string.lowercase} に依存し、同一行の文を区切るためにピリオドの後に二つの空白を使う慣習に依存しているため、英文テキストに限定されたものです。
@end deffn

@geindex break_long_words (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper break_long_words}@anchor{27c2}
@deffn {の属性} break_long_words

(デフォルト: @code{True}) もし真ならば、そのとき @ref{27c3,,width} より長い行が確実にないようにするために、 @ref{27c3,,width} より長い語は切られます。偽ならば、長い語は切られないでしょう。そして、 @ref{27c3,,width} より長い行があるかもしれません。 (@ref{27c3,,width} を超える分を最小にするために、長い語は単独で一行に置かれるでしょう。)
@end deffn

@geindex break_on_hyphens (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper break_on_hyphens}@anchor{27c7}
@deffn {の属性} break_on_hyphens

(デフォルト: @code{True}) 真の場合、英語で一般的なように、ラップ処理は空白か合成語に含まれるハイフンの直後で行われます。偽の場合、空白だけが改行に適した位置として判断されます。ただし、本当に語の途中で改行が行われないようにするためには、 @ref{27c2,,break_long_words} 属性を真に設定する必要があります。過去のバージョンでのデフォルトの振る舞いは、常にハイフンの直後での改行を許していました。
@end deffn

@geindex max_lines (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper max_lines}@anchor{11d0}
@deffn {の属性} max_lines

(デフォルト @code{None}) @code{None} 以外の場合、出力は行数 `max_lines' を超えないようにされ、切り詰める際には出力の最後の行を `placeholder' に置き換えます。


Added in version 3.4.

@end deffn

@geindex ...;placeholder

@geindex placeholder (textwrap.TextWrapper の属性)
@anchor{library/textwrap textwrap TextWrapper placeholder}@anchor{11d1}
@deffn {の属性} placeholder

(デフォルト: @code{' [...]'}) 切り詰める場合に出力の最後の行に置く文字列です。


Added in version 3.4.

@end deffn

@ref{11cf,,TextWrapper} はモジュールレベルの簡易関数に類似したいくつかの公開メソッドも提供します:

@geindex wrap() (textwrap.TextWrapper のメソッド)
@anchor{library/textwrap textwrap TextWrapper wrap}@anchor{27bd}
@deffn {メソッド} wrap (text)

1段落の文字列 `text' を、各行が @ref{27c3,,width} 文字以下になるように wrap します。 wrap のすべてのオプションは @ref{11cf,,TextWrapper} インスタンスの属性から取得します。結果の、行末に改行のない行のリストを返します。出力の内容が空になる場合は、返すリストも空になります。
@end deffn

@geindex fill() (textwrap.TextWrapper のメソッド)
@anchor{library/textwrap textwrap TextWrapper fill}@anchor{27c8}
@deffn {メソッド} fill (text)

`text' 内の段落を一つだけ折り返しを行い、折り返しが行われた段落を含む一つの文字列を返します。
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node unicodedata --- Unicode データベース,stringprep --- インターネットの文字列調製,textwrap --- テキストの折り返しと詰め込み,テキスト処理サービス
@anchor{library/unicodedata doc}@anchor{27c9}@anchor{library/unicodedata module-unicodedata}@anchor{10b}@anchor{library/unicodedata translation-repo}@anchor{27ca}@anchor{library/unicodedata unicodedata-unicode-database}@anchor{27cb}
@subsection @code{unicodedata} --- Unicode データベース


@geindex module; unicodedata

@geindex Unicode 文字列型
@geindex 文字(str型)
@geindex Unicode 文字列型;データベース


__________________________________________________________________


This module provides access to the Unicode Character Database (UCD) which
defines character properties for all Unicode characters. The data contained in
this database is compiled from the UCD version 16.0.0@footnote{https://www.unicode.org/Public/16.0.0/ucd}.

このモジュールは、ユニコード標準付録 #44 「 ユニコード文字データベース@footnote{https://www.unicode.org/reports/tr44/} 」で定義されているのと同じ名前およびシンボルを使用します。このモジュールは次のような関数を定義します:


@subsubheading 参考


The @ref{14bc,,Unicode HOWTO} for more information about Unicode and how to use
this module.


@geindex lookup() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata lookup}@anchor{1284}
@deffn {の関数} unicodedata.lookup (name)

Look up character by name.  If a character with the given name is found, return
the corresponding character.  If not found, @ref{5e7,,KeyError} is raised.
For example:

@example
>>> unicodedata.lookup('LEFT CURLY BRACKET')
'@{'
@end example

The characters returned by this function are the same as those produced by
@code{\N} escape sequence in string literals. For example:

@example
>>> unicodedata.lookup('MIDDLE DOT') == '\N@{MIDDLE DOT@}'
True
@end example


バージョン 3.3 で変更: name aliases @footnote{
@indicateurl{https://www.unicode.org/Public/16.0.0/ucd/NameAliases.txt}
} と named sequences @footnote{
@indicateurl{https://www.unicode.org/Public/16.0.0/ucd/NamedSequences.txt}
} のサポートが追加されました。

@end deffn

@geindex name() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata name}@anchor{27cc}
@deffn {の関数} unicodedata.name (chr, default=None, /)

Returns the name assigned to the character `chr' as a string. If no
name is defined, `default' is returned, or, if not given, @ref{2ec,,ValueError} is
raised. For example:

@example
>>> unicodedata.name('½')
'VULGAR FRACTION ONE HALF'
>>> unicodedata.name('\uFFFF', 'fallback')
'fallback'
@end example
@end deffn

@geindex decimal() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata decimal}@anchor{27cd}
@deffn {の関数} unicodedata.decimal (chr, default=None, /)

Returns the decimal value assigned to the character `chr' as integer.
If no such value is defined, `default' is returned, or, if not given,
@ref{2ec,,ValueError} is raised. For example:

@example
>>> unicodedata.decimal('\N@{ARABIC-INDIC DIGIT NINE@}')
9
>>> unicodedata.decimal('\N@{SUPERSCRIPT NINE@}', -1)
-1
@end example
@end deffn

@geindex digit() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata digit}@anchor{27ce}
@deffn {の関数} unicodedata.digit (chr, default=None, /)

Returns the digit value assigned to the character `chr' as integer.
If no such value is defined, `default' is returned, or, if not given,
@ref{2ec,,ValueError} is raised:

@example
>>> unicodedata.digit('\N@{SUPERSCRIPT NINE@}')
9
@end example
@end deffn

@geindex numeric() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata numeric}@anchor{147a}
@deffn {の関数} unicodedata.numeric (chr, default=None, /)

Returns the numeric value assigned to the character `chr' as float.
If no such value is defined, `default' is returned, or, if not given,
@ref{2ec,,ValueError} is raised:

@example
>>> unicodedata.numeric('½')
0.5
@end example
@end deffn

@geindex category() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata category}@anchor{27cf}
@deffn {の関数} unicodedata.category (chr)

Returns the general category assigned to the character `chr' as
string. General category names consist of two letters.
See the General Category Values section of the Unicode Character Database documentation@footnote{https://www.unicode.org/reports/tr44/tr44-34.html#General_Category_Values}
for a list of category codes. For example:

@example
>>> unicodedata.category('A')  # 'L'etter, 'u'ppercase
'Lu'
@end example
@end deffn

@geindex bidirectional() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata bidirectional}@anchor{27d0}
@deffn {の関数} unicodedata.bidirectional (chr)

Returns the bidirectional class assigned to the character `chr' as
string. If no such value is defined, an empty string is returned.
See the Bidirectional Class Values section of the Unicode Character Database@footnote{https://www.unicode.org/reports/tr44/tr44-34.html#Bidi_Class_Values}
documentation for a list of bidirectional codes. For example:

@example
>>> unicodedata.bidirectional('\N@{ARABIC-INDIC DIGIT SEVEN@}') # 'A'rabic, 'N'umber
'AN'
@end example
@end deffn

@geindex combining() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata combining}@anchor{27d1}
@deffn {の関数} unicodedata.combining (chr)

Returns the canonical combining class assigned to the character `chr'
as integer. Returns @code{0} if no combining class is defined.
See the Canonical Combining Class Values section of the Unicode Character Database@footnote{https://www.unicode.org/reports/tr44/tr44-34.html#Canonical_Combining_Class_Values}
for more information.
@end deffn

@geindex east_asian_width() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata east_asian_width}@anchor{27d2}
@deffn {の関数} unicodedata.east_asian_width (chr)

Returns the east asian width assigned to the character `chr' as
string. For a list of widths and or more information, see the
Unicode Standard Annex #11@footnote{https://www.unicode.org/reports/tr11/tr11-43.html}.
@end deffn

@geindex mirrored() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata mirrored}@anchor{27d3}
@deffn {の関数} unicodedata.mirrored (chr)

Returns the mirrored property assigned to the character `chr' as
integer. Returns @code{1} if the character has been identified as a "mirrored"
character in bidirectional text, @code{0} otherwise. For example:

@example
>>> unicodedata.mirrored('>')
1
@end example
@end deffn

@geindex decomposition() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata decomposition}@anchor{27d4}
@deffn {の関数} unicodedata.decomposition (chr)

Returns the character decomposition mapping assigned to the character
`chr' as string. An empty string is returned in case no such mapping is
defined. For example:

@example
>>> unicodedata.decomposition('Ã')
'0041 0303'
@end example
@end deffn

@geindex normalize() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata normalize}@anchor{8e4}
@deffn {の関数} unicodedata.normalize (form, unistr)

Unicode 文字列 `unistr' の正規形 `form' を返します。 `form' の有効な値は、'NFC'、'NFKC'、'NFD'、'NFKD' です。

Unicode 規格は標準等価性 (canonical equivalence) と互換等価性 (compatibility equivalence) に基づいて、様々な Unicode文字列の正規形を定義します。Unicode では、複数の方法で表現できる文字があります。たとえば、文字 U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) は、U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA) というシーケンスとしても表現できます。

各文字には2つの正規形があり、それぞれ正規形 C と正規形 D といいます。正規形 D (NFD) は標準分解 (canonical decomposition) としても知られており、各文字を分解された形に変換します。正規形 C (NFC) は標準分解を適用した後、結合済文字を再構成します。

In addition to these two forms, there are two additional normal forms based on
compatibility equivalence. In Unicode, certain characters are supported which
normally would be unified with other characters. For example, U+2160 (ROMAN
NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I).
However, it is supported in Unicode for compatibility with existing character
sets (for example, gb2312).

The normal form KD (NFKD) will apply the compatibility decomposition, that is,
replace all compatibility characters with their equivalents. The normal form KC
(NFKC) first applies the compatibility decomposition, followed by the canonical
composition.

2つのunicode文字列が正規化されていて人間の目に同じに見えても、片方が結合文字を持っていてもう片方が持っていない場合、それらは完全に同じではありません。
@end deffn

@geindex is_normalized() (unicodedata モジュール)
@anchor{library/unicodedata unicodedata is_normalized}@anchor{c3c}
@deffn {の関数} unicodedata.is_normalized (form, unistr)

Unicode 文字列 `unistr' が正規形 `form' かどうかを返します。 `form' の有効な値は、'NFC'、'NFKC'、'NFD'、'NFKD' です。


Added in version 3.8.

@end deffn

更に、本モジュールは以下の定数を公開します:

@geindex unidata_version (unicodedata モジュール)
@anchor{library/unicodedata unicodedata unidata_version}@anchor{27d5}
@deffn {データ} unicodedata.unidata_version

このモジュールで使われている Unicode データベースのバージョン。
@end deffn

@geindex ucd_3_2_0 (unicodedata モジュール)
@anchor{library/unicodedata unicodedata ucd_3_2_0}@anchor{164d}
@deffn {データ} unicodedata.ucd_3_2_0

これはモジュール全体と同じメソッドを具えたオブジェクトですが、Unicode データベースバージョン 3.2 を代わりに使っており、この特定のバージョンの Unicode データベースを必要とするアプリケーション(IDNA など)のためものです。
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node stringprep --- インターネットの文字列調製,readline --- GNU readline のインターフェース,unicodedata --- Unicode データベース,テキスト処理サービス
@anchor{library/stringprep doc}@anchor{27d6}@anchor{library/stringprep module-stringprep}@anchor{da}@anchor{library/stringprep stringprep-internet-string-preparation}@anchor{27d7}@anchor{library/stringprep translation-repo}@anchor{27d8}
@subsection @code{stringprep} --- インターネットの文字列調製


@geindex module; stringprep

`ソースコード:' Lib/stringprep.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/stringprep.py}


__________________________________________________________________


(ホスト名のような) インターネット上にある存在に識別名をつける際、しばしば識別名間の "等価性" 比較を行う必要があります。厳密には、例えば大小文字の区別をするかしないかいったように、比較をどのように行うかはアプリケーションの領域に依存します。また、例えば "印字可能な" 文字で構成された識別名だけを許可するといったように、可能な識別名を制限することも必要となるかもしれません。

@geindex RFC; RFC 3454
RFC 3454@footnote{https://datatracker.ietf.org/doc/html/rfc3454.html} では、インターネットプロトコル上で Unicode 文字列を "調製 (prepare)" するためのプロシジャを定義しています。文字列は通信路に載せられる前に調製プロシジャで処理され、その結果ある正規化された形式になります。RFC ではあるテーブルの集合を定義しており、それらはプロファイルにまとめられています。各プロファイルでは、どのテーブルを使い、 @code{stringprep} プロシジャのどのオプション部分がプロファイルの一部になっているかを定義しています。 @code{stringprep} プロファイルの一つの例は @code{nameprep} で、国際化されたドメイン名に使われます。

The module @code{stringprep} only exposes the tables from 
@geindex RFC; RFC 3454
RFC 3454@footnote{https://datatracker.ietf.org/doc/html/rfc3454.html}. As these
tables would be very large to represent as dictionaries or lists, the
module uses the Unicode character database internally. The module source code
itself was generated using the @code{mkstringprep.py} utility.

As a result, these tables are exposed as functions, not as data structures.
There are two kinds of tables in the RFC: sets and mappings. For a set,
@code{stringprep} provides the "characteristic function", i.e. a function that
returns @code{True} if the parameter is part of the set. For mappings, it provides the
mapping function: given the key, it returns the associated value. Below is a
list of all functions available in the module.

@geindex in_table_a1() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_a1}@anchor{27d9}
@deffn {の関数} stringprep.in_table_a1 (code)

`code' がテーブル A.1 (Unicode 3.2 における未割り当てコードポイント: unassigned code point) かどうか判定します。
@end deffn

@geindex in_table_b1() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_b1}@anchor{27da}
@deffn {の関数} stringprep.in_table_b1 (code)

`code' がテーブル B.1 (一般には何にも対応付けられていない: commonly mapped to nothing) かどうか判定します。
@end deffn

@geindex map_table_b2() (stringprep モジュール)
@anchor{library/stringprep stringprep map_table_b2}@anchor{27db}
@deffn {の関数} stringprep.map_table_b2 (code)

テーブル B.2 (NFKC で用いられる大小文字の対応付け) に従って、`code' に対応付けられた値を返します。
@end deffn

@geindex map_table_b3() (stringprep モジュール)
@anchor{library/stringprep stringprep map_table_b3}@anchor{27dc}
@deffn {の関数} stringprep.map_table_b3 (code)

テーブル B.3 (正規化を伴わない大小文字の対応付け) に従って、`code' に対応付けられた値を返します。
@end deffn

@geindex in_table_c11() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c11}@anchor{27dd}
@deffn {の関数} stringprep.in_table_c11 (code)

`code' がテーブル C.1.1 (ASCII スペース文字) かどうか判定します。
@end deffn

@geindex in_table_c12() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c12}@anchor{27de}
@deffn {の関数} stringprep.in_table_c12 (code)

`code' がテーブル C.1.2 (非 ASCII スペース文字) かどうか判定します。
@end deffn

@geindex in_table_c11_c12() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c11_c12}@anchor{27df}
@deffn {の関数} stringprep.in_table_c11_c12 (code)

`code' がテーブル C.1  (スペース文字、C.1.1 および C.1.2 の和集合) かどうか判定します。
@end deffn

@geindex in_table_c21() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c21}@anchor{27e0}
@deffn {の関数} stringprep.in_table_c21 (code)

`code' がテーブル C.2.1 (ASCII 制御文字) かどうか判定します。
@end deffn

@geindex in_table_c22() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c22}@anchor{27e1}
@deffn {の関数} stringprep.in_table_c22 (code)

`code' がテーブル C.2.2 (非 ASCII 制御文字) かどうか判定します。
@end deffn

@geindex in_table_c21_c22() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c21_c22}@anchor{27e2}
@deffn {の関数} stringprep.in_table_c21_c22 (code)

`code' がテーブル C.2  (制御文字、C.2.1 および C.2.2 の和集合) かどうか判定します。
@end deffn

@geindex in_table_c3() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c3}@anchor{27e3}
@deffn {の関数} stringprep.in_table_c3 (code)

`code' がテーブル C.3 (プライベート利用) かどうか判定します。
@end deffn

@geindex in_table_c4() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c4}@anchor{27e4}
@deffn {の関数} stringprep.in_table_c4 (code)

`code' がテーブル C.4 (非文字コードポイント: non-character code points) かどうか判定します。
@end deffn

@geindex in_table_c5() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c5}@anchor{27e5}
@deffn {の関数} stringprep.in_table_c5 (code)

`code' がテーブル C.5 (サロゲーションコード) かどうか判定します。
@end deffn

@geindex in_table_c6() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c6}@anchor{27e6}
@deffn {の関数} stringprep.in_table_c6 (code)

`code' がテーブル C.6 (平文:plain text として不適切) かどうか判定します。
@end deffn

@geindex in_table_c7() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c7}@anchor{27e7}
@deffn {の関数} stringprep.in_table_c7 (code)

`code' がテーブル C.7 (標準表現:canonical representation  として不適切) かどうか判定します。
@end deffn

@geindex in_table_c8() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c8}@anchor{27e8}
@deffn {の関数} stringprep.in_table_c8 (code)

`code' がテーブル C.8 (表示プロパティの変更または撤廃) かどうか判定します。
@end deffn

@geindex in_table_c9() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_c9}@anchor{27e9}
@deffn {の関数} stringprep.in_table_c9 (code)

`code' がテーブル C.9 (タグ文字) かどうか判定します。
@end deffn

@geindex in_table_d1() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_d1}@anchor{27ea}
@deffn {の関数} stringprep.in_table_d1 (code)

`code' がテーブル D.1 (双方向プロパティ "R" または "AL"  を持つ文字) かどうか判定します。
@end deffn

@geindex in_table_d2() (stringprep モジュール)
@anchor{library/stringprep stringprep in_table_d2}@anchor{27eb}
@deffn {の関数} stringprep.in_table_d2 (code)

`code' がテーブル D.2 (双方向プロパティ "L" を持つ文字)  かどうか判定します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node readline --- GNU readline のインターフェース,rlcompleter --- GNU readline の補完機能,stringprep --- インターネットの文字列調製,テキスト処理サービス
@anchor{library/readline doc}@anchor{27ec}@anchor{library/readline module-readline}@anchor{bf}@anchor{library/readline readline-gnu-readline-interface}@anchor{27ed}@anchor{library/readline translation-repo}@anchor{27ee}
@subsection @code{readline} --- GNU readline のインターフェース


@geindex module; readline


__________________________________________________________________


The @code{readline} module defines a number of functions to facilitate
completion and reading/writing of history files from the Python interpreter.
This module can be used directly, or via the @ref{c2,,rlcompleter} module, which
supports completion of Python identifiers at the interactive prompt.  Settings
made using  this module affect the behaviour of both the interpreter's
interactive prompt  and the prompts offered by the built-in @ref{14f0,,input()}
function.

readline のキーバインディングは初期化ファイルで設定できます。
このファイルは、たいていはホームディレクトリに @code{.inputrc} という名前で置いてあります。
GNU Readline マニュアルの  Readline Init File@footnote{https://tiswww.cwru.edu/php/chet/readline/rluserman.html#Readline-Init-File} を参照して、そのファイルの形式や可能な構成、 Readline ライブラリ全体の機能を知ってください。

@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@ref{213f,,Availability}: Unix.

@cartouche
@quotation 注釈 
The underlying Readline library API may be implemented by
the @code{editline} (@code{libedit}) library instead of GNU readline.
On macOS the @code{readline} module detects which library is being used
at run time.

The configuration file for @code{editline} is different from that
of GNU readline. If you programmatically load configuration strings
you can use @ref{1a27,,backend} to determine which library is being used.

If you use @code{editline}/@code{libedit} readline emulation on macOS, the
initialization file located in your home directory is named
@code{.editrc}. For example, the following content in @code{~/.editrc} will
turn ON `vi' keybindings and TAB completion:

@example
python:bind -v
python:bind ^I rl_complete
@end example

Also note that different libraries may use different history file formats.
When switching the underlying library, existing history files may become
unusable.
@end quotation
@end cartouche

@geindex backend (readline モジュール)
@anchor{library/readline readline backend}@anchor{1a27}
@deffn {データ} readline.backend

The name of the underlying Readline library being used, either
@code{"readline"} or @code{"editline"}.


Added in version 3.13.

@end deffn

@menu
* 初期化ファイル:: 
* 行バッファ:: 
* 履歴ファイル:: 
* 履歴リスト:: 
* 開始フック:: 
* 補完:: 
* 使用例: 使用例<2>. 

@end menu

@node 初期化ファイル,行バッファ,,readline --- GNU readline のインターフェース
@anchor{library/readline init-file}@anchor{27ef}
@subsubsection 初期化ファイル


以下の関数は初期化ファイルならびにユーザ設定関連のものです:

@geindex parse_and_bind() (readline モジュール)
@anchor{library/readline readline parse_and_bind}@anchor{27f0}
@deffn {の関数} readline.parse_and_bind (string)

Execute the init line provided in the `string' argument. This calls
@code{rl_parse_and_bind()} in the underlying library.
@end deffn

@geindex read_init_file() (readline モジュール)
@anchor{library/readline readline read_init_file}@anchor{17da}
@deffn {の関数} readline.read_init_file ([filename])

Execute a readline initialization file. The default filename is the last filename
used. This calls @code{rl_read_init_file()} in the underlying library.
It raises an @ref{1c6e,,auditing event} @code{open} with the file name
if given, and @code{"<readline_init_file>"} otherwise, regardless of
which file the library resolves.


バージョン 3.14 で変更: The auditing event was added.

@end deffn

@node 行バッファ,履歴ファイル,初期化ファイル,readline --- GNU readline のインターフェース
@anchor{library/readline line-buffer}@anchor{27f1}
@subsubsection 行バッファ


以下の関数は行バッファを操作します:

@geindex get_line_buffer() (readline モジュール)
@anchor{library/readline readline get_line_buffer}@anchor{27f2}
@deffn {の関数} readline.get_line_buffer ()

Return the current contents of the line buffer (@code{rl_line_buffer}
in the underlying library).
@end deffn

@geindex insert_text() (readline モジュール)
@anchor{library/readline readline insert_text}@anchor{27f3}
@deffn {の関数} readline.insert_text (string)

Insert text into the line buffer at the cursor position.  This calls
@code{rl_insert_text()} in the underlying library, but ignores
the return value.
@end deffn

@geindex redisplay() (readline モジュール)
@anchor{library/readline readline redisplay}@anchor{16de}
@deffn {の関数} readline.redisplay ()

Change what's displayed on the screen to reflect the current contents of the
line buffer.  This calls @code{rl_redisplay()} in the underlying library.
@end deffn

@node 履歴ファイル,履歴リスト,行バッファ,readline --- GNU readline のインターフェース
@anchor{library/readline history-file}@anchor{27f4}
@subsubsection 履歴ファイル


以下の関数は履歴ファイルを操作します:

@geindex read_history_file() (readline モジュール)
@anchor{library/readline readline read_history_file}@anchor{17db}
@deffn {の関数} readline.read_history_file ([filename])

Load a readline history file, and append it to the history list.
The default filename is @code{~/.history}.  This calls
@code{read_history()} in the underlying library
and raises an @ref{1c6e,,auditing event} @code{open} with the file
name if given and @code{"~/.history"} otherwise.


バージョン 3.14 で変更: The auditing event was added.

@end deffn

@geindex write_history_file() (readline モジュール)
@anchor{library/readline readline write_history_file}@anchor{17dc}
@deffn {の関数} readline.write_history_file ([filename])

Save the history list to a readline history file, overwriting any
existing file.  The default filename is @code{~/.history}.  This calls
@code{write_history()} in the underlying library and raises an
@ref{1c6e,,auditing event} @code{open} with the file name if given and
@code{"~/.history"} otherwise.


バージョン 3.14 で変更: The auditing event was added.

@end deffn

@geindex append_history_file() (readline モジュール)
@anchor{library/readline readline append_history_file}@anchor{1051}
@deffn {の関数} readline.append_history_file (nelements[, filename])

Append the last `nelements' items of history to a file.  The default filename is
@code{~/.history}.  The file must already exist.  This calls
@code{append_history()} in the underlying library.  This function
only exists if Python was compiled for a version of the library
that supports it. It raises an @ref{1c6e,,auditing event} @code{open}
with the file name if given and @code{"~/.history"} otherwise.


Added in version 3.5.



バージョン 3.14 で変更: The auditing event was added.

@end deffn

@geindex get_history_length() (readline モジュール)
@geindex set_history_length() (readline モジュール)
@anchor{library/readline readline get_history_length}@anchor{27f5}
@deffn {の関数} readline.get_history_length ()
@anchor{library/readline readline set_history_length}@anchor{1926}
@deffnx {の関数} readline.set_history_length (length)

Set or return the desired number of lines to save in the history file.
The @ref{17dc,,write_history_file()} function uses this value to truncate
the history file, by calling @code{history_truncate_file()} in
the underlying library.  Negative values imply
unlimited history file size.
@end deffn

@node 履歴リスト,開始フック,履歴ファイル,readline --- GNU readline のインターフェース
@anchor{library/readline history-list}@anchor{27f6}
@subsubsection 履歴リスト


以下の関数はグローバルな履歴リストを操作します:

@geindex clear_history() (readline モジュール)
@anchor{library/readline readline clear_history}@anchor{27f7}
@deffn {の関数} readline.clear_history ()

Clear the current history.  This calls @code{clear_history()} in the
underlying library.  The Python function only exists if Python was
compiled for a version of the library that supports it.
@end deffn

@geindex get_current_history_length() (readline モジュール)
@anchor{library/readline readline get_current_history_length}@anchor{16dd}
@deffn {の関数} readline.get_current_history_length ()

履歴に現在ある項目の数を返します。 (@ref{27f5,,get_history_length()} は履歴ファイルに書かれる最大行数を返します。)
@end deffn

@geindex get_history_item() (readline モジュール)
@anchor{library/readline readline get_history_item}@anchor{16dc}
@deffn {の関数} readline.get_history_item (index)

Return the current contents of history item at `index'.  The item index
is one-based.  This calls @code{history_get()} in the underlying library.
@end deffn

@geindex remove_history_item() (readline モジュール)
@anchor{library/readline readline remove_history_item}@anchor{27f8}
@deffn {の関数} readline.remove_history_item (pos)

Remove history item specified by its position from the history.
The position is zero-based.  This calls @code{remove_history()} in
the underlying library.
@end deffn

@geindex replace_history_item() (readline モジュール)
@anchor{library/readline readline replace_history_item}@anchor{27f9}
@deffn {の関数} readline.replace_history_item (pos, line)

Replace history item specified by its position with `line'.
The position is zero-based.  This calls @code{replace_history_entry()}
in the underlying library.
@end deffn

@geindex add_history() (readline モジュール)
@anchor{library/readline readline add_history}@anchor{27fa}
@deffn {の関数} readline.add_history (line)

Append `line' to the history buffer, as if it was the last line typed.
This calls @code{add_history()} in the underlying library.
@end deffn

@geindex set_auto_history() (readline モジュール)
@anchor{library/readline readline set_auto_history}@anchor{ec5}
@deffn {の関数} readline.set_auto_history (enabled)

Enable or disable automatic calls to @code{add_history()} when reading
input via readline.  The `enabled' argument should be a Boolean value
that when true, enables auto history, and that when false, disables
auto history.


Added in version 3.6.


`CPython 実装の詳細:' Auto history is enabled by default, and changes to this do not persist
across multiple sessions.
@end deffn

@node 開始フック,補完,履歴リスト,readline --- GNU readline のインターフェース
@anchor{library/readline startup-hooks}@anchor{27fb}
@subsubsection 開始フック


@geindex set_startup_hook() (readline モジュール)
@anchor{library/readline readline set_startup_hook}@anchor{27fc}
@deffn {の関数} readline.set_startup_hook ([function])

Set or remove the function invoked by the @code{rl_startup_hook}
callback of the underlying library.  If `function' is specified, it will
be used as the new hook function; if omitted or @code{None}, any function
already installed is removed.  The hook is called with no
arguments just before readline prints the first prompt.
@end deffn

@geindex set_pre_input_hook() (readline モジュール)
@anchor{library/readline readline set_pre_input_hook}@anchor{27fd}
@deffn {の関数} readline.set_pre_input_hook ([function])

Set or remove the function invoked by the @code{rl_pre_input_hook}
callback of the underlying library.  If `function' is specified, it will
be used as the new hook function; if omitted or @code{None}, any
function already installed is removed.  The hook is called
with no arguments after the first prompt has been printed and just before
readline starts reading input characters.  This function only exists
if Python was compiled for a version of the library that supports it.
@end deffn

@node 補完,使用例<2>,開始フック,readline --- GNU readline のインターフェース
@anchor{library/readline completion}@anchor{27fe}@anchor{library/readline readline-completion}@anchor{27ff}
@subsubsection 補完


The following functions relate to implementing a custom word completion
function.  This is typically operated by the Tab key, and can suggest and
automatically complete a word being typed.  By default, Readline is set up
to be used by @ref{c2,,rlcompleter} to complete Python identifiers for
the interactive interpreter.  If the @code{readline} module is to be used
with a custom completer, a different set of word delimiters should be set.

@geindex set_completer() (readline モジュール)
@anchor{library/readline readline set_completer}@anchor{2800}
@deffn {の関数} readline.set_completer ([function])

completer 関数を設定または削除します。`function' が指定された場合、新たな completer 関数として用いられます;  省略された場合や @code{None} の場合、現在インストールされている completer 関数は削除されます。completer 関数は @code{function(text, state)} の形式で、関数が文字列でない値を返すまで `state' を @code{0}, @code{1}, @code{2}, ..., にして呼び出します。この関数は `text' から始まる補完結果として次に来そうなものを返さなければなりません。

The installed completer function is invoked by the `entry_func' callback
passed to @code{rl_completion_matches()} in the underlying library.
The `text' string comes from the first parameter to the
@code{rl_attempted_completion_function} callback of the
underlying library.
@end deffn

@geindex get_completer() (readline モジュール)
@anchor{library/readline readline get_completer}@anchor{2801}
@deffn {の関数} readline.get_completer ()

completer 関数を取得します。completer 関数が設定されていなければ @code{None} を返します。
@end deffn

@geindex get_completion_type() (readline モジュール)
@anchor{library/readline readline get_completion_type}@anchor{2802}
@deffn {の関数} readline.get_completion_type ()

Get the type of completion being attempted.  This returns the
@code{rl_completion_type} variable in the underlying library as
an integer.
@end deffn

@geindex get_begidx() (readline モジュール)
@geindex get_endidx() (readline モジュール)
@anchor{library/readline readline get_begidx}@anchor{1ca4}
@deffn {の関数} readline.get_begidx ()
@anchor{library/readline readline get_endidx}@anchor{1ca5}
@deffnx {の関数} readline.get_endidx ()

Get the beginning or ending index of the completion scope.
These indexes are the `start' and `end' arguments passed to the
@code{rl_attempted_completion_function} callback of the
underlying library.  The values may be different in the same
input editing scenario based on the underlying C readline implementation.
Ex: libedit is known to behave differently than libreadline.
@end deffn

@geindex set_completer_delims() (readline モジュール)
@geindex get_completer_delims() (readline モジュール)
@anchor{library/readline readline set_completer_delims}@anchor{1a2a}
@deffn {の関数} readline.set_completer_delims (string)
@anchor{library/readline readline get_completer_delims}@anchor{2803}
@deffnx {の関数} readline.get_completer_delims ()

Set or get the word delimiters for completion.  These determine the
start of the word to be considered for completion (the completion scope).
These functions access the @code{rl_completer_word_break_characters}
variable in the underlying library.
@end deffn

@geindex set_completion_display_matches_hook() (readline モジュール)
@anchor{library/readline readline set_completion_display_matches_hook}@anchor{2804}
@deffn {の関数} readline.set_completion_display_matches_hook ([function])

Set or remove the completion display function.  If `function' is
specified, it will be used as the new completion display function;
if omitted or @code{None}, any completion display function already
installed is removed.  This sets or clears the
@code{rl_completion_display_matches_hook} callback in the
underlying library.  The completion display function is called as
@code{function(substitution, [matches], longest_match_length)} once
each time matches need to be displayed.
@end deffn

@node 使用例<2>,,補完,readline --- GNU readline のインターフェース
@anchor{library/readline example}@anchor{2805}@anchor{library/readline readline-example}@anchor{2806}
@subsubsection 使用例


The following example demonstrates how to use the @code{readline} module's
history reading and writing functions to automatically load and save a history
file named @code{.python_history} from the user's home directory.  The code
below would normally be executed automatically during interactive sessions
from the user's 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} file.

@example
import atexit
import os
import readline

histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
    readline.read_history_file(histfile)
    # default history len is -1 (infinite), which may grow unruly
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)
@end example

Python が @ref{443,,対話モード} で実行される時、このコードは実際には自動的に実行されます ( @ref{11cb,,readline の設定} を参照してください)。

次の例では上記と同じ目的を達成できますが、ここでは新規の履歴のみを追加することで、並行して対話セッションがサポートされます:

@example
import atexit
import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".python_history")

try:
    readline.read_history_file(histfile)
    h_len = readline.get_current_history_length()
except FileNotFoundError:
    open(histfile, 'wb').close()
    h_len = 0

def save(prev_h_len, histfile):
    new_h_len = readline.get_current_history_length()
    readline.set_history_length(1000)
    readline.append_history_file(new_h_len - prev_h_len, histfile)
atexit.register(save, h_len, histfile)
@end example

次の例では @ref{2807,,code.InteractiveConsole} クラスを拡張し、履歴の保存・復旧をサポートします。

@example
import atexit
import code
import os
import readline

class HistoryConsole(code.InteractiveConsole):
    def __init__(self, locals=None, filename="<console>",
                 histfile=os.path.expanduser("~/.console-history")):
        code.InteractiveConsole.__init__(self, locals, filename)
        self.init_history(histfile)

    def init_history(self, histfile):
        readline.parse_and_bind("tab: complete")
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(histfile)
            except FileNotFoundError:
                pass
            atexit.register(self.save_history, histfile)

    def save_history(self, histfile):
        readline.set_history_length(1000)
        readline.write_history_file(histfile)
@end example

@cartouche
@quotation 注釈 
The new @ref{491,,REPL} introduced in version 3.13 doesn't support readline.
However, readline can still be used by setting the 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL}
environment variable.
@end quotation
@end cartouche

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node rlcompleter --- GNU readline の補完機能,,readline --- GNU readline のインターフェース,テキスト処理サービス
@anchor{library/rlcompleter doc}@anchor{2808}@anchor{library/rlcompleter module-rlcompleter}@anchor{c2}@anchor{library/rlcompleter rlcompleter-completion-function-for-gnu-readline}@anchor{2809}@anchor{library/rlcompleter translation-repo}@anchor{280a}
@subsection @code{rlcompleter} --- GNU readline の補完機能


@geindex module; rlcompleter

`ソースコード:' Lib/rlcompleter.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/rlcompleter.py}


__________________________________________________________________


The @code{rlcompleter} module defines a completion function suitable to be
passed to @ref{2800,,set_completer()} in the @ref{bf,,readline} module.

When this module is imported on a Unix platform with the @ref{bf,,readline} module
available, an instance of the @ref{1d2b,,Completer} class is automatically created
and its @ref{280b,,complete()} method is set as the
@ref{27ff,,readline completer}. The method provides
completion of valid Python @ref{22a0,,identifiers and keywords}.

以下はプログラム例です:

@example
>>> import rlcompleter
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> readline. <TAB PRESSED>
readline.__doc__          readline.get_line_buffer(  readline.read_init_file(
readline.__file__         readline.insert_text(      readline.set_completer(
readline.__name__         readline.parse_and_bind(
>>> readline.
@end example

The @code{rlcompleter} module is designed for use with Python's
@ref{443,,interactive mode}.  Unless Python is run with the
@ref{13c0,,-S} option, the module is automatically imported and configured
(see @ref{11cb,,readline の設定}).

@ref{bf,,readline} のないプラットフォームでも、このモジュールで定義される @ref{1d2b,,Completer} クラスは独自の目的に使えます。

@geindex Completer (rlcompleter のクラス)
@anchor{library/rlcompleter completer-objects}@anchor{280c}@anchor{library/rlcompleter rlcompleter Completer}@anchor{1d2b}
@deffn {クラス} rlcompleter.Completer

Completerオブジェクトは以下のメソッドを持っています:

@geindex complete() (rlcompleter.Completer のメソッド)
@anchor{library/rlcompleter rlcompleter Completer complete}@anchor{280b}
@deffn {メソッド} complete (text, state)

Return the next possible completion for `text'.

When called by the @ref{bf,,readline} module, this method is called
successively with @code{state == 0, 1, 2, ...} until the method returns
@code{None}.

もし `text' がピリオド(@code{'.'})を含まない場合、 @ref{1,,__main__} 、 @ref{13,,builtins} で定義されている名前か、キーワード (@ref{88,,keyword} モジュールで定義されている) から補完されます。

If called for a dotted name, it will try to evaluate anything without obvious
side-effects (functions will not be evaluated, but it can generate calls to
@ref{6fa,,__getattr__()}) up to the last part, and find matches for the
rest via the @ref{844,,dir()} function.  Any exception raised during the
evaluation of the expression is caught, silenced and @ref{885,,None} is
returned.
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node バイナリデータ処理,データ型,テキスト処理サービス,Python 標準ライブラリ
@anchor{library/binary doc}@anchor{280d}@anchor{library/binary binary-data-services}@anchor{280e}@anchor{library/binary binaryservices}@anchor{271c}@anchor{library/binary translation-repo}@anchor{280f}
@section バイナリデータ処理


この章で紹介されているモジュールはバイナリデータを扱うための基本的な処理を提供しています。ファイルフォーマットやネットワークプロトコルなど、その他のバイナリデータ処理については、それぞれの節で解説されています。

@ref{2652,,テキスト処理サービス} で紹介する一部のライブラリには、 ASCII 互換のバイナリフォーマットで利用できるもの (例: @ref{be,,re}) や 、すべてのバイナリデータで利用できるもの (例: @ref{3b,,difflib}) があります。

加えて、 @ref{25c4,,バイナリシーケンス型 --- bytes@comma{} bytearray@comma{} memoryview} に書かれているPythonビルトインデータ型についても参照してください。

@menu
* struct: struct --- バイト列をパックされたバイナリデータとして解釈する. バイト列をパックされたバイナリデータとして解釈する
* codecs: codecs --- codec レジストリと基底クラス. codec レジストリと基底クラス

@end menu

@node struct --- バイト列をパックされたバイナリデータとして解釈する,codecs --- codec レジストリと基底クラス,,バイナリデータ処理
@anchor{library/struct doc}@anchor{2810}@anchor{library/struct struct-interpret-bytes-as-packed-binary-data}@anchor{2811}
@subsection @code{struct} --- バイト列をパックされたバイナリデータとして解釈する


@c from struct import *

@geindex module; struct
@anchor{library/struct module-struct}@anchor{db}
`ソースコード:' Lib/struct.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/struct.py}

@geindex C;構造体
@geindex パック;2進数;データ


__________________________________________________________________


This module converts between Python values and C structs represented
as Python @ref{192,,bytes} objects.  Compact @ref{2812,,format strings}
describe the intended conversions to/from Python values.
The module's functions and objects can be used for two largely
distinct applications, data exchange with external sources (files or
network connections), or data transfer between the Python application
and the C layer.

@cartouche
@quotation 注釈 
When no prefix character is given, native mode is the default. It
packs or unpacks data based on the platform and compiler on which
the Python interpreter was built.
The result of packing a given C struct includes pad bytes which
maintain proper alignment for the C types involved; similarly,
alignment is taken into account when unpacking.  In contrast, when
communicating data between external sources, the programmer is
responsible for defining byte ordering and padding between elements.
See @ref{2813,,バイトオーダ、サイズ、アラインメント} for details.
@end quotation
@end cartouche

Several @code{struct} functions (and methods of @ref{1778,,Struct}) take a `buffer'
argument.  This refers to objects that implement the @ref{260,,バッファプロトコル (buffer Protocol)} and
provide either a readable or read-writable buffer.  The most common types used
for that purpose are @ref{192,,bytes} and @ref{344,,bytearray}, but many other types
that can be viewed as an array of bytes implement the buffer protocol, so that
they can be read/filled without additional copying from a @ref{192,,bytes} object.

@menu
* 関数と例外:: 
* 書式文字列:: 
* アプリケーション:: 
* クラス: クラス<3>. 

@end menu

@node 関数と例外,書式文字列,,struct --- バイト列をパックされたバイナリデータとして解釈する
@anchor{library/struct functions-and-exceptions}@anchor{2814}
@subsubsection 関数と例外


このモジュールは以下の例外と関数を定義しています:

@geindex error
@anchor{library/struct struct error}@anchor{153b}
@deffn {例外} struct.error

様々な状況で送出される例外です。引数は何が問題なのかを記述する文字列です。
@end deffn

@geindex pack() (struct モジュール)
@anchor{library/struct struct pack}@anchor{148e}
@deffn {の関数} struct.pack (format, v1, v2, ...)

フォーマット文字列 `format' に従い値 `v1', `v2', ...  をパックして、バイト列オブジェクトを返します。引数は指定したフォーマットが要求する型と正確に一致していなければなりません。
@end deffn

@geindex pack_into() (struct モジュール)
@anchor{library/struct struct pack_into}@anchor{2815}
@deffn {の関数} struct.pack_into (format, buffer, offset, v1, v2, ...)

フォーマット文字列 `format' に従い値 `v1', `v2', ...  をパックしてバイト列にし、書き込み可能な `buffer' のオフセット `offset' 位置より書き込みます。オフセットは省略出来ません。
@end deffn

@geindex unpack() (struct モジュール)
@anchor{library/struct struct unpack}@anchor{185a}
@deffn {の関数} struct.unpack (format, buffer)

(@code{pack(format, ...)} でパックされたであろう) バッファ `buffer' を、書式文字列 `format' に従ってアンパックします。
値が一つしかない場合を含め、結果はタプルで返されます。
バッファのバイトサイズは、 @ref{1da9,,calcsize()} の返り値である書式文字列が要求するサイズと一致しなければなりません。
@end deffn

@geindex unpack_from() (struct モジュール)
@anchor{library/struct struct unpack_from}@anchor{2816}
@deffn {の関数} struct.unpack_from (format, /, buffer, offset=0)

バッファ `buffer' を、 `offset' の位置から書式文字列 `format' に従ってアンパックします。
値が一つしかない場合を含め、結果はタプルで返されます。
`offset' を始点とするバッファのバイトサイズは、少なくとも @ref{1da9,,calcsize()} の返り値である書式文字列が要求するサイズでなければなりません。
@end deffn

@geindex iter_unpack() (struct モジュール)
@anchor{library/struct struct iter_unpack}@anchor{11c1}
@deffn {の関数} struct.iter_unpack (format, buffer)

バッファ `buffer' を、書式文字列 `format' に従ってイテレータ形式でアンパックします。
この関数が返すイテレータは、すべての内容を読み終わるまでバッファから一定の大きさのチャンクを読み取ります。
バッファのバイトサイズは、 @ref{1da9,,calcsize()} の返り値である書式文字列が要求するサイズの倍数でなければなりません。

イテレーション毎に書式文字列で指定されたタプルを yield します。


Added in version 3.4.

@end deffn

@geindex calcsize() (struct モジュール)
@anchor{library/struct struct calcsize}@anchor{1da9}
@deffn {の関数} struct.calcsize (format)

書式文字列 `format' に従って、構造体 (それと @code{pack(format, ...)} によって作成されるバイト列オブジェクト) のサイズを返します。
@end deffn

@node 書式文字列,アプリケーション,関数と例外,struct --- バイト列をパックされたバイナリデータとして解釈する
@anchor{library/struct format-strings}@anchor{2817}@anchor{library/struct struct-format-strings}@anchor{2812}
@subsubsection 書式文字列


Format strings describe the data layout when
packing and unpacking data.  They are built up from @ref{124b,,format characters},
which specify the type of data being packed/unpacked.  In addition,
special characters control the @ref{2813,,byte order@comma{} size and alignment}.
Each format string consists of an optional prefix character which
describes the overall properties of the data and one or more format
characters which describe the actual data values and padding.

@menu
* バイトオーダ、サイズ、アラインメント:: 
* 書式指定文字:: 
* 使用例: 使用例<3>. 

@end menu

@node バイトオーダ、サイズ、アラインメント,書式指定文字,,書式文字列
@anchor{library/struct byte-order-size-and-alignment}@anchor{2818}@anchor{library/struct struct-alignment}@anchor{2813}
@subsubsection バイトオーダ、サイズ、アラインメント


By default, C types are represented in the machine's native format and byte
order, and properly aligned by skipping pad bytes if necessary (according to the
rules used by the C compiler).
This behavior is chosen so
that the bytes of a packed struct correspond exactly to the memory layout
of the corresponding C struct.
Whether to use native byte ordering
and padding or standard formats depends on the application.

@geindex @@ (at);in struct format strings
@geindex = (等号);in struct format strings
@geindex < (小さい);in struct format strings
@geindex > (大きい);in struct format strings
@geindex ! (エクスクラメーション);in struct format strings

これに代わって、フォーマット文字列の最初の文字を使って、バイトオーダやサイズ、アラインメントを指定することができます。指定できる文字を以下のテーブルに示します:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxxxxx} 
@headitem

文字

@tab

バイトオーダ

@tab

サイズ

@tab

アラインメント

@item

@code{@@}

@tab

native

@tab

native

@tab

native

@item

@code{=}

@tab

native

@tab

standard

@tab

none

@item

@code{<}

@tab

リトルエンディアン

@tab

standard

@tab

none

@item

@code{>}

@tab

ビッグエンディアン

@tab

standard

@tab

none

@item

@code{!}

@tab

ネットワーク (= ビッグエンディアン)

@tab

standard

@tab

none

@end multitable


フォーマット文字列の最初の文字が上のいずれかでない場合、@code{'@@'} であるとみなされます。

@cartouche
@quotation 注釈 
The number 1023 (@code{0x3ff} in hexadecimal) has the following byte representations:


@itemize *

@item 
@code{03 ff} in big-endian (@code{>})

@item 
@code{ff 03} in little-endian (@code{<})
@end itemize

Python の例:

@example
>>> import struct
>>> struct.pack('>h', 1023)
b'\x03\xff'
>>> struct.pack('<h', 1023)
b'\xff\x03'
@end example
@end quotation
@end cartouche

ネイティブのバイトオーダはビッグエンディアンかリトルエンディアンで、ホストシステムに依存します。例えば、Intel x86、AMD64 (x86-64) および Apple M1 はリトルエンディアンです。IBM z および多くの古いアーキテクチャはビッグエンディアンです。使っているシステムでのエンディアンは @ref{25f7,,sys.byteorder} を使って調べて下さい。

ネイティブのサイズおよびアラインメントは C コンパイラの @code{sizeof} 式で決定されます。ネイティブのサイズおよびアラインメントはネイティブのバイトオーダと同時に使われます。

標準のサイズはフォーマット文字だけで決まります。 @ref{124b,,書式指定文字} の表を参照して下さい。

@code{'@@'} と @code{'='} の違いに注意してください: 両方ともネイティブのバイトオーダですが、後者のバイトサイズとアラインメントは標準のものに合わせてあります。

The form @code{'!'} represents the network byte order which is always big-endian
as defined in IETF RFC 1700@footnote{https://datatracker.ietf.org/doc/html/rfc1700}.

バイトオーダに関して、「(強制的にバイトスワップを行う)ネイティブの逆」を指定する方法はありません。@code{'<'} または @code{'>'} のうちふさわしい方を選んでください。

注釈:


@enumerate 

@item 
パディングは構造体のメンバの並びの中にだけ自動で追加されます。最初や最後にパディングが追加されることはありません。

@item 
ネイティブでないサイズおよびアラインメントが使われる場合にはパディングは行われません (たとえば '<', '>', '=', '!' を使った場合です)。

@item 
特定の型によるアラインメント要求に従うように構造体の末端をそろえるには、繰り返し回数をゼロにした特定の型でフォーマットを終端します。 @ref{2819,,使用例} を参照して下さい。
@end enumerate

@node 書式指定文字,使用例<3>,バイトオーダ、サイズ、アラインメント,書式文字列
@anchor{library/struct format-characters}@anchor{124b}@anchor{library/struct id1}@anchor{281a}
@subsubsection 書式指定文字


フォーマット文字 (format character) は以下の意味を持っています; C と Python の間の変換では、値は正確に以下に指定された型でなくてはなりません: 「標準のサイズ」列は standard サイズ使用時にパックされた値が何バイトかを示します。つまり、フォーマット文字列が @code{'<'}, @code{'>'}, @code{'!'}, @code{'='} のいずれかで始まっている場合のものです。native サイズ使用時にはパックされた値の大きさはプラットフォーム依存です。


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

フォーマット

@tab

C の型

@tab

Python の型

@tab

標準のサイズ

@tab

注釈

@item

@code{x}

@tab

パディングバイト

@tab

値なし

@tab

@tab

(7)

@item

@code{c}

@tab

char

@tab

長さ 1 のバイト列

@tab

1

@tab

@item

@code{b}

@tab

signed char

@tab

整数

@tab

1

@tab

(1), (2)

@item

@code{B}

@tab

unsigned char

@tab

整数

@tab

1

@tab

(2)

@item

@code{?}

@tab

_Bool

@tab

真偽値型(bool)

@tab

1

@tab

(1)

@item

@code{h}

@tab

short

@tab

整数

@tab

2

@tab

(2)

@item

@code{H}

@tab

unsigned short

@tab

整数

@tab

2

@tab

(2)

@item

@code{i}

@tab

int

@tab

整数

@tab

4

@tab

(2)

@item

@code{I}

@tab

unsigned int

@tab

整数

@tab

4

@tab

(2)

@item

@code{l}

@tab

long

@tab

整数

@tab

4

@tab

(2)

@item

@code{L}

@tab

unsigned long

@tab

整数

@tab

4

@tab

(2)

@item

@code{q}

@tab

long long

@tab

整数

@tab

8

@tab

(2)

@item

@code{Q}

@tab

unsigned long long

@tab

整数

@tab

8

@tab

(2)

@item

@code{n}

@tab

@code{ssize_t}

@tab

整数

@tab

@tab

(3)

@item

@code{N}

@tab

@code{size_t}

@tab

整数

@tab

@tab

(3)

@item

@code{e}

@tab

(6)

@tab

浮動小数点数

@tab

2

@tab

(4)

@item

@code{f}

@tab

float

@tab

浮動小数点数

@tab

4

@tab

(4)

@item

@code{d}

@tab

double

@tab

浮動小数点数

@tab

8

@tab

(4)

@item

@code{F}

@tab

float complex

@tab

複素数

@tab

8

@tab

(10)

@item

@code{D}

@tab

double complex

@tab

複素数

@tab

16

@tab

(10)

@item

@code{s}

@tab

char[]

@tab

bytes

@tab

@tab

(9)

@item

@code{p}

@tab

char[]

@tab

bytes

@tab

@tab

(8)

@item

@code{P}

@tab

void*

@tab

整数

@tab

@tab

(5)

@end multitable



バージョン 3.3 で変更: @code{'n'} および @code{'N'} フォーマットのサポートが追加されました。



バージョン 3.6 で変更: @code{'e'} フォーマットのサポートが追加されました。



バージョン 3.14 で変更: Added support for the @code{'F'} and @code{'D'} formats.


注釈:


@enumerate 

@item 
@geindex ? (クエスチョンマーク);in struct format strings

The @code{'?'} conversion code corresponds to the _Bool type
defined by C standards since C99.  In standard mode, it is
represented by one byte.

@item 
When attempting to pack a non-integer using any of the integer conversion
codes, if the non-integer has a @ref{19e,,__index__()} method then that method is
called to convert the argument to an integer before packing.


バージョン 3.2 で変更: Added use of the @ref{19e,,__index__()} method for non-integers.


@item 
@code{'n'} および @code{'N'} 変換コードは (デフォルトもしくはバイトオーダ文字 @code{'@@'} 付きで選択される) native サイズ使用時のみ利用できます。standard サイズ使用時には、自身のアプリケーションに適する他の整数フォーマットを使うことができます。

@item 
@code{'f'} 、 @code{'d'} および @code{'e'} 変換コードについて、パックされた表現は IEEE 754 binary32 (@code{'f'} の場合) 、 binary64 (@code{'d'} の場合) 、またはbinary16(@code{'e'} の場合) フォーマットが、プラットフォームにおける浮動小数点数のフォーマットに関係なく使われます。

@item 
@code{'P'} フォーマット文字はネイティブバイトオーダでのみ利用可能です (デフォルトのネットワークバイトオーダに設定するか、@code{'@@'} バイトオーダ指定文字を指定しなければなりません)。@code{'='} を指定した場合、ホスト計算機のバイトオーダに基づいてリトルエンディアンとビッグエンディアンのどちらを使うかを決めます。struct モジュールはこの設定をネイティブのオーダ設定として解釈しないので、@code{'P'} を使うことはできません。

@item 
IEEE 754 の binary16 "半精度" 型は、 IEEE 754 standard@footnote{https://en.wikipedia.org/wiki/IEEE_754-2008_revision} の2008 年の改訂で導入されました。
半精度型は、符号 bit 、5 bit の指数部、 11 bit の精度 (明示的には 10 bit が保存される) を持ち、おおよそ @code{6.1e-05} から @code{6.5e+04} までの数を完全な精度で表現できます。
この型は C コンパイラでは広くはサポートされていません: たいていのマシンでは、保存するのに unsigned short が使えますが、数学の演算には使えません。
詳しいことは Wikipedia の half-precision floating-point format@footnote{https://en.wikipedia.org/wiki/Half-precision_floating-point_format} のページを参照してください。

@item 
When packing, @code{'x'} inserts one NUL byte.

@item 
フォーマット文字 @code{'p'} は "Pascal 文字列 (pascal string)"  をコードします。Pascal 文字列は count で与えられる `固定長のバイト列' に収められた短い可変長の文字列です。このデータの先頭の 1 バイトには文字列の長さか255 のうち、小さい方の数が収められます。その後に文字列のバイトデータが続きます。 @ref{148e,,pack()} に渡された Pascal 文字列の長さが長すぎた (count-1 よりも長い) 場合、先頭の @code{count-1} バイトが書き込まれます。文字列が @code{count-1} よりも短い場合、指定した count バイトに達するまでの残りの部分はヌルで埋められます。 @ref{185a,,unpack()} では、フォーマット文字 @code{'p'} は指定された @code{count} バイトだけデータを読み込みますが、返される文字列は決して 255 文字を超えることはないので注意してください。

@item 
For the @code{'s'} format character, the count is interpreted as the length of the
bytes, not a repeat count like for the other format characters; for example,
@code{'10s'} means a single 10-byte string mapping to or from a single
Python byte string, while @code{'10c'} means 10
separate one byte character elements (e.g., @code{cccccccccc}) mapping
to or from ten different Python byte objects. (See @ref{2819,,使用例}
for a concrete demonstration of the difference.)
If a count is not given, it defaults to 1.  For packing, the string is
truncated or padded with null bytes as appropriate to make it fit. For
unpacking, the resulting bytes object always has exactly the specified number
of bytes.  As a special case, @code{'0s'} means a single, empty string (while
@code{'0c'} means 0 characters).

@item 
For the @code{'F'} and @code{'D'} format characters, the packed representation uses
the IEEE 754 binary32 and binary64 format for components of the complex
number, regardless of the floating-point format used by the platform.
Note that complex types (@code{F} and @code{D}) are available unconditionally,
despite complex types being an optional feature in C.
As specified in the C11 standard, each complex type is represented by a
two-element C array containing, respectively, the real and imaginary parts.
@end enumerate

フォーマット文字の前に整数をつけ、繰り返し回数 (count) を指定することができます。例えば、フォーマット文字列 @code{'4h'} は @code{'hhhh'} と全く同じ意味です。

フォーマット文字間の空白文字は無視されます; count とフォーマット文字の間にはスペースを入れてはいけません。

整数フォーマット (@code{'b'}, @code{'B'}, @code{'h'}, @code{'H'}, @code{'i'}, @code{'I'}, @code{'l'}, @code{'L'}, @code{'q'}, @code{'Q'}) のいずれかを使って値 @code{x} をパックするとき @code{x} がフォーマットの適切な値の範囲に無い場合、 @ref{153b,,struct.error} が送出されます。


バージョン 3.1 で変更: 以前は、いくつかの整数フォーマットが適切な範囲にない値を覆い隠して、 @ref{153b,,struct.error} の代わりに @ref{1a3,,DeprecationWarning} を送出していました。


@geindex ? (クエスチョンマーク);in struct format strings

@code{'?'} フォーマット文字では、返り値は @ref{e07,,True} または @ref{d2b,,False} です。パックするときには、引数オブジェクトの論理値としての値が使われます。 0 または 1 のネイティブや標準の真偽値表現でパックされ、アンパックされるときはゼロでない値は @code{True} になります。

@node 使用例<3>,,書式指定文字,書式文字列
@anchor{library/struct examples}@anchor{281b}@anchor{library/struct struct-examples}@anchor{2819}
@subsubsection 使用例


@cartouche
@quotation 注釈 
Native byte order examples (designated by the @code{'@@'} format prefix or
lack of any prefix character) may not match what the reader's
machine produces as
that depends on the platform and compiler.
@end quotation
@end cartouche

Pack and unpack integers of three different sizes, using big endian
ordering:

@example
>>> from struct import *
>>> pack(">bhl", 1, 2, 3)
b'\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('>bhl', b'\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('>bhl')
7
@end example

Attempt to pack an integer which is too large for the defined field:

@example
>>> pack(">h", 99999)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: 'h' format requires -32768 <= number <= 32767
@end example

Demonstrate the difference between @code{'s'} and @code{'c'} format
characters:

@example
>>> pack("@@ccc", b'1', b'2', b'3')
b'123'
>>> pack("@@3s", b'123')
b'123'
@end example

アンパックした結果のフィールドは、変数に割り当てるか named tuple でラップすることによって名前を付けることができます:

@example
>>> record = b'raymond   \x32\x12\x08\x01\x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)
@end example

The ordering of format characters may have an impact on size in native
mode since padding is implicit. In standard mode, the user is
responsible for inserting any desired padding.
Note in
the first @code{pack} call below that three NUL bytes were added after the
packed @code{'#'} to align the following integer on a four-byte boundary.
In this example, the output was produced on a little endian machine:

@example
>>> pack('@@ci', b'#', 0x12131415)
b'#\x00\x00\x00\x15\x14\x13\x12'
>>> pack('@@ic', 0x12131415, b'#')
b'\x15\x14\x13\x12#'
>>> calcsize('@@ci')
8
>>> calcsize('@@ic')
5
@end example

The following format @code{'llh0l'} results in two pad bytes being added
at the end, assuming the platform's longs are aligned on 4-byte boundaries:

@example
>>> pack('@@llh0l', 1, 2, 3)
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
@end example


@subsubheading 参考



@table @asis

@item @ref{8,,array} モジュール

一様なデータ型からなるバイナリ記録データのパック。

@item @ref{86,,json} モジュール

JSON encoder and decoder.

@item @ref{ab,,pickle} モジュール

Python object serialization.
@end table


@node アプリケーション,クラス<3>,書式文字列,struct --- バイト列をパックされたバイナリデータとして解釈する
@anchor{library/struct applications}@anchor{281c}@anchor{library/struct id2}@anchor{281d}
@subsubsection アプリケーション


Two main applications for the @code{struct} module exist, data
interchange between Python and C code within an application or another
application compiled using the same compiler (@ref{281e,,native formats}), and
data interchange between applications using agreed upon data layout
(@ref{281f,,standard formats}).  Generally speaking, the format strings
constructed for these two domains are distinct.

@menu
* Native Formats:: 
* Standard Formats:: 

@end menu

@node Native Formats,Standard Formats,,アプリケーション
@anchor{library/struct native-formats}@anchor{2820}@anchor{library/struct struct-native-formats}@anchor{281e}
@subsubsection Native Formats


When constructing format strings which mimic native layouts, the
compiler and machine architecture determine byte ordering and padding.
In such cases, the @code{@@} format character should be used to specify
native byte ordering and data sizes.  Internal pad bytes are normally inserted
automatically.  It is possible that a zero-repeat format code will be
needed at the end of a format string to round up to the correct
byte boundary for proper alignment of consecutive chunks of data.

Consider these two simple examples (on a 64-bit, little-endian
machine):

@example
>>> calcsize('@@lhl')
24
>>> calcsize('@@llh')
18
@end example

Data is not padded to an 8-byte boundary at the end of the second
format string without the use of extra padding.  A zero-repeat format
code solves that problem:

@example
>>> calcsize('@@llh0l')
24
@end example

The @code{'x'} format code can be used to specify the repeat, but for
native formats it is better to use a zero-repeat format like @code{'0l'}.

By default, native byte ordering and alignment is used, but it is
better to be explicit and use the @code{'@@'} prefix character.

@node Standard Formats,,Native Formats,アプリケーション
@anchor{library/struct standard-formats}@anchor{2821}@anchor{library/struct struct-standard-formats}@anchor{281f}
@subsubsection Standard Formats


When exchanging data beyond your process such as networking or storage,
be precise.  Specify the exact byte order, size, and alignment.  Do
not assume they match the native order of a particular machine.
For example, network byte order is big-endian, while many popular CPUs
are little-endian.  By defining this explicitly, the user need not
care about the specifics of the platform their code is running on.
The first character should typically be @code{<} or @code{>}
(or @code{!}).  Padding is the responsibility of the programmer.  The
zero-repeat format character won't work.  Instead, the user must
explicitly add @code{'x'} pad bytes where needed.  Revisiting the
examples from the previous section, we have:

@example
>>> calcsize('<qh6xq')
24
>>> pack('<qh6xq', 1, 2, 3) == pack('@@lhl', 1, 2, 3)
True
>>> calcsize('@@llh')
18
>>> pack('@@llh', 1, 2, 3) == pack('<qqh', 1, 2, 3)
True
>>> calcsize('<qqh6x')
24
>>> calcsize('@@llh0l')
24
>>> pack('@@llh0l', 1, 2, 3) == pack('<qqh6x', 1, 2, 3)
True
@end example

The above results (executed on a 64-bit machine) aren't guaranteed to
match when executed on different machines.  For example, the examples
below were executed on a 32-bit machine:

@example
>>> calcsize('<qqh6x')
24
>>> calcsize('@@llh0l')
12
>>> pack('@@llh0l', 1, 2, 3) == pack('<qqh6x', 1, 2, 3)
False
@end example

@node クラス<3>,,アプリケーション,struct --- バイト列をパックされたバイナリデータとして解釈する
@anchor{library/struct classes}@anchor{2822}@anchor{library/struct struct-objects}@anchor{2823}
@subsubsection クラス


The @code{struct} module also defines the following type:

@geindex Struct (struct のクラス)
@anchor{library/struct struct Struct}@anchor{1778}
@deffn {クラス} struct.Struct (format)

フォーマット文字列 `format' に従ってバイナリデータを読み書きする、新しい Struct オブジェクトを返します。 @code{Struct} オブジェクトを一度作ってからそのメソッドを呼び出すと、フォーマット文字列のコンパイルが一度だけになるので、モジュールレベルの関数を同じフォーマットで呼び出すよりも効率的です。

@cartouche
@quotation 注釈 
The compiled versions of the most recent format strings passed to
the module-level functions are cached, so programs that use only a few
format strings needn't worry about reusing a single @ref{1778,,Struct}
instance.
@end quotation
@end cartouche

コンパイルされた Struct オブジェクトは以下のメソッドと属性をサポートします:

@geindex pack() (struct.Struct のメソッド)
@anchor{library/struct struct Struct pack}@anchor{2824}
@deffn {メソッド} pack (v1, v2, ...)

@ref{148e,,pack()} 関数と同じ、コンパイルされたフォーマットを利用するメソッドです。 (@code{len(result)} は @ref{2825,,size} と等しいでしょう)
@end deffn

@geindex pack_into() (struct.Struct のメソッド)
@anchor{library/struct struct Struct pack_into}@anchor{2826}
@deffn {メソッド} pack_into (buffer, offset, v1, v2, ...)

@ref{2815,,pack_into()} 関数と同じ、コンパイルされたフォーマットを利用するメソッドです。
@end deffn

@geindex unpack() (struct.Struct のメソッド)
@anchor{library/struct struct Struct unpack}@anchor{2827}
@deffn {メソッド} unpack (buffer)

@ref{185a,,unpack()} 関数と同じ、コンパイルされたフォーマットを利用するメソッドです。 (buffer のバイト数は @ref{2825,,size} と等しくなければなりません)。
@end deffn

@geindex unpack_from() (struct.Struct のメソッド)
@anchor{library/struct struct Struct unpack_from}@anchor{2828}
@deffn {メソッド} unpack_from (buffer, offset=0)

@ref{2816,,unpack_from()} 関数と同じ、コンパイルされたフォーマットを利用するメソッドです。 (`offset' を始点とする buffer のバイト数は少なくとも @ref{2825,,size} 以上でなければなりません)。
@end deffn

@geindex iter_unpack() (struct.Struct のメソッド)
@anchor{library/struct struct Struct iter_unpack}@anchor{11c2}
@deffn {メソッド} iter_unpack (buffer)

@ref{11c1,,iter_unpack()} 関数と同じ、コンパイルされたフォーマットを利用するメソッドです。 (buffer のバイト数は @ref{2825,,size} の倍数でなければなりません)。


Added in version 3.4.

@end deffn

@geindex format (struct.Struct の属性)
@anchor{library/struct struct Struct format}@anchor{e00}
@deffn {の属性} format

この Struct オブジェクトを作成する時に利用されたフォーマット文字列です。


バージョン 3.7 で変更: The format string type is now @ref{169,,str} instead of @ref{192,,bytes}.

@end deffn

@geindex size (struct.Struct の属性)
@anchor{library/struct struct Struct size}@anchor{2825}
@deffn {の属性} size

@ref{199,,format} 属性に対応する構造体の (従って @ref{148e,,pack()} メソッドによって作成されるバイト列オブジェクトの) サイズです。
@end deffn


バージョン 3.13 で変更: The `repr()' of structs has changed.  It
is now:

@example
>>> Struct('i')
Struct('i')
@end example

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node codecs --- codec レジストリと基底クラス,,struct --- バイト列をパックされたバイナリデータとして解釈する,バイナリデータ処理
@anchor{library/codecs doc}@anchor{2829}@anchor{library/codecs codecs-codec-registry-and-base-classes}@anchor{282a}@anchor{library/codecs module-codecs}@anchor{1c}@anchor{library/codecs translation-repo}@anchor{282b}
@subsection @code{codecs} --- codec レジストリと基底クラス


@geindex module; codecs

`ソースコード:' Lib/codecs.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/codecs.py}

@geindex Unicode 文字列型
@geindex Codecs
@geindex Codecs;encode
@geindex Codecs;decode
@geindex ストリーム
@geindex スタック可能;ストリーム


__________________________________________________________________


このモジュールは、標準的な Python codec (エンコーダとデコーダ) 用の基底クラスを定義し、codec とエラー処理検索プロセスを管理する内部の Python codec レジストリへのアクセスを提供します。多くの codec はテキストをバイトにエンコードする (そしてバイトをテキストにデコードする) @ref{25db,,テキストエンコーディング} ですが、テキストをテキストに、またはバイトをバイトにエンコードする codec も提供されています。カスタムの codec は任意の型間でエンコードとデコードを行えますが、一部のモジュール機能は @ref{25db,,テキストエンコーディング} か @ref{192,,bytes} へのエンコードのみに制限されています。

このモジュールでは、任意の codec でエンコードやデコードを行うための、以下の関数が定義されています。

@geindex encode() (codecs モジュール)
@anchor{library/codecs codecs encode}@anchor{1104}
@deffn {の関数} codecs.encode (obj, encoding='utf-8', errors='strict')

`encoding' に記載された codec を使用して `obj' をエンコードします。

希望のエラー処理スキームを `errors' に設定することができます。デフォルトのエラーハンドラ (エラー処理関数) は @code{'strict'} です。これはエンコードエラーは @ref{2ec,,ValueError} (もしくは @ref{887,,UnicodeEncodeError} のような、より codec に固有のサブクラス) を送出することを意味します。codec エラー処理についてのより詳しい情報は @ref{282c,,Codec 基底クラス} を参照してください。
@end deffn

@geindex decode() (codecs モジュール)
@anchor{library/codecs codecs decode}@anchor{1105}
@deffn {の関数} codecs.decode (obj, encoding='utf-8', errors='strict')

`encoding' に記載された codec を使用して `obj' をデコードします。

希望のエラー処理スキームを `errors' に設定することができます。デフォルトのエラーハンドラは @code{'strict'} です。これはデコードエラーは @ref{2ec,,ValueError} (もしくは @ref{c08,,UnicodeDecodeError} のような、より codec に固有のサブクラス) を送出することを意味します。codec エラー処理についてのより詳しい情報は @ref{282c,,Codec 基底クラス} を参照してください。
@end deffn

@geindex charmap_build() (codecs モジュール)
@anchor{library/codecs codecs charmap_build}@anchor{282d}
@deffn {の関数} codecs.charmap_build (string)

Return a mapping suitable for encoding with a custom single-byte encoding.
Given a @ref{169,,str} `string' of up to 256 characters representing a
decoding table, returns either a compact internal mapping object
@code{EncodingMap} or a @ref{183,,dictionary} mapping character ordinals
to byte values. Raises a @ref{198,,TypeError} on invalid input.
@end deffn

各 codec についての詳細も、次のようにして直接調べることができます。

@geindex lookup() (codecs モジュール)
@anchor{library/codecs codecs lookup}@anchor{b5c}
@deffn {の関数} codecs.lookup (encoding, /)

Python codec レジストリから codec 情報を探し、以下で定義するような @ref{1a6c,,CodecInfo} オブジェクトを返します。

エンコーディングの検索は、まずレジストリのキャッシュから行います。見つからなければ、登録されている検索関数のリストから探します。 @ref{1a6c,,CodecInfo} オブジェクトが一つも見つからなければ @ref{23e5,,LookupError} を送出します。見つかったら、その @ref{1a6c,,CodecInfo} オブジェクトはキャッシュに保存され、呼び出し側に返されます。
@end deffn

@geindex CodecInfo (codecs のクラス)
@anchor{library/codecs codecs CodecInfo}@anchor{1a6c}
@deffn {クラス} codecs.CodecInfo (encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None)

codec レジストリ内を検索する場合の、codec の詳細です。コントラクタ引数は、次の同名の属性に保存されます。

@geindex name (codecs.CodecInfo の属性)
@anchor{library/codecs codecs CodecInfo name}@anchor{282e}
@deffn {の属性} name

エンコーディングの名前です。
@end deffn

@geindex encode (codecs.CodecInfo の属性)
@geindex decode (codecs.CodecInfo の属性)
@anchor{library/codecs codecs CodecInfo encode}@anchor{282f}
@deffn {の属性} encode
@anchor{library/codecs codecs CodecInfo decode}@anchor{2830}
@deffnx {の属性} decode

ステートレスなエンコーディングとデコーディングの関数です。これらは、Codec インスタンスの @ref{2831,,encode()} メソッドと @ref{2832,,decode()} メソッドと同じインターフェースを持っている必要があります (see @ref{2833,,Codec のインターフェース} を参照)。この関数またはメソッドは、ステートレスモードで動作することが想定されています。
@end deffn

@geindex incrementalencoder (codecs.CodecInfo の属性)
@geindex incrementaldecoder (codecs.CodecInfo の属性)
@anchor{library/codecs codecs CodecInfo incrementalencoder}@anchor{2834}
@deffn {の属性} incrementalencoder
@anchor{library/codecs codecs CodecInfo incrementaldecoder}@anchor{2835}
@deffnx {の属性} incrementaldecoder

インクリメンタル・エンコーダとデコーダのクラスまたはファクトリ関数です。これらは、基底クラスの @ref{2836,,IncrementalEncoder} と @ref{2837,,IncrementalDecoder} が定義するインターフェースをそれぞれ提供する必要があります。インクリメンタルな codec は、ステート (内部状態) を保持することができます。
@end deffn

@geindex streamwriter (codecs.CodecInfo の属性)
@geindex streamreader (codecs.CodecInfo の属性)
@anchor{library/codecs codecs CodecInfo streamwriter}@anchor{2838}
@deffn {の属性} streamwriter
@anchor{library/codecs codecs CodecInfo streamreader}@anchor{2839}
@deffnx {の属性} streamreader

ストリームライターとリーダーのクラスまたはファクトリ関数です。これらは、基底クラスの  @ref{283a,,StreamWriter} と @ref{283b,,StreamReader} が定義するインターフェースをそれぞれ提供する必要があります。ストリーム codec は、ステートを保持することができます。
@end deffn
@end deffn

さまざまな codec 構成要素へのアクセスを簡便化するために、このモジュールは以下のような関数を提供しています。これらの関数は、 codec の検索に @ref{b5c,,lookup()} を使います:

@geindex getencoder() (codecs モジュール)
@anchor{library/codecs codecs getencoder}@anchor{283c}
@deffn {の関数} codecs.getencoder (encoding)

与えられたエンコーディングに対する codec を検索し、エンコーダ関数を返します。

エンコーディングが見つからなければ @ref{23e5,,LookupError} を送出します。
@end deffn

@geindex getdecoder() (codecs モジュール)
@anchor{library/codecs codecs getdecoder}@anchor{283d}
@deffn {の関数} codecs.getdecoder (encoding)

与えられたエンコーディングに対する codec を検索し、デコーダ関数を返します。

エンコーディングが見つからなければ @ref{23e5,,LookupError} を送出します。
@end deffn

@geindex getincrementalencoder() (codecs モジュール)
@anchor{library/codecs codecs getincrementalencoder}@anchor{283e}
@deffn {の関数} codecs.getincrementalencoder (encoding)

与えられたエンコーディングに対する codec を検索し、インクリメンタル・エンコーダクラスまたはファクトリ関数を返します。

エンコーディングが見つからないか、 codec がインクリメンタル・エンコーダをサポートしなければ @ref{23e5,,LookupError} を送出します。
@end deffn

@geindex getincrementaldecoder() (codecs モジュール)
@anchor{library/codecs codecs getincrementaldecoder}@anchor{283f}
@deffn {の関数} codecs.getincrementaldecoder (encoding)

与えられたエンコーディングに対する codec を検索し、インクリメンタル・デコーダクラスまたはファクトリ関数を返します。

エンコーディングが見つからないか、 codec がインクリメンタル・デコーダをサポートしなければ @ref{23e5,,LookupError} を送出します。
@end deffn

@geindex getreader() (codecs モジュール)
@anchor{library/codecs codecs getreader}@anchor{2840}
@deffn {の関数} codecs.getreader (encoding)

与えられたエンコーディングに対する codec を検索し、@ref{283b,,StreamReader} クラスまたはファクトリ関数を返します。

エンコーディングが見つからなければ @ref{23e5,,LookupError} を送出します。
@end deffn

@geindex getwriter() (codecs モジュール)
@anchor{library/codecs codecs getwriter}@anchor{2841}
@deffn {の関数} codecs.getwriter (encoding)

与えられたエンコーディングに対する codec を検索し、@ref{283a,,StreamWriter} クラスまたはファクトリ関数を返します。

エンコーディングが見つからなければ @ref{23e5,,LookupError} を送出します。
@end deffn

次のように、適切な codec 検索関数を登録することで、カスタムの codecs を利用することができます。

@geindex register() (codecs モジュール)
@anchor{library/codecs codecs register}@anchor{2842}
@deffn {の関数} codecs.register (search_function, /)

Register a codec search function. Search functions are expected to take one
argument, being the encoding name in all lower case letters with hyphens
and spaces converted to underscores, and return a @ref{1a6c,,CodecInfo} object.
In case a search function cannot find a given encoding, it should return
@code{None}.


バージョン 3.9 で変更: Hyphens and spaces are converted to underscore.

@end deffn

@geindex unregister() (codecs モジュール)
@anchor{library/codecs codecs unregister}@anchor{9e9}
@deffn {の関数} codecs.unregister (search_function, /)

Unregister a codec search function and clear the registry's cache.
If the search function is not registered, do nothing.


Added in version 3.10.

@end deffn

エンコードされたテキストファイルを処理する場合、組み込みの @ref{316,,open()} とそれに関連付けられた @ref{83,,io} モジュールの使用が推奨されていますが、このモジュールは追加のユーティリティ関数とクラスを提供し、バイナリファイルを処理する場合に幅広い codecs を利用できるようにします。

@geindex open() (codecs モジュール)
@anchor{library/codecs codecs open}@anchor{315}
@deffn {の関数} codecs.open (filename, mode='r', encoding=None, errors='strict', buffering=-1)

エンコードされたファイルを `mode' を使って開き、透過的なエンコード/デコードを提供する @ref{2843,,StreamReaderWriter} のインスタンスを返します。デフォルトのファイルモードは @code{'r'} 、つまり、読み出しモードでファイルを開きます。

@cartouche
@quotation 注釈 
`encoding' が @code{None} でなければ、下層のエンコードされたファイルは、常にバイナリモードで開きます。読み書き時に、 @code{'\n'} の自動変換は行われません。`mode' 引数は、組み込みの @ref{316,,open()} 関数が受け入れる任意のバイナリモードにすることができます。@code{'b'} が自動的に付加されます。
@end quotation
@end cartouche

`encoding' は、そのファイルに対して使用されるエンコーディングを指定します。バイトにエンコードする、あるいはバイトからデコードするすべてのエンコーディングが許可されます。ファイルメソッドがサポートするデータ型は、使用される codec によって異なります。

エラーハンドリングのために `errors' を渡すことができます。これはデフォルトでは @code{'strict'} で、エンコード時にエラーがあれば @ref{2ec,,ValueError} を送出します。

`buffering' has the same meaning as for the built-in @ref{316,,open()} function.
It defaults to -1 which means that the default buffer size will be used.


バージョン 3.11 で変更: @code{'U'} モードは削除されました。



バージョン 3.14 で非推奨: @ref{315,,codecs.open()} has been superseded by @ref{316,,open()}.

@end deffn

@geindex EncodedFile() (codecs モジュール)
@anchor{library/codecs codecs EncodedFile}@anchor{2844}
@deffn {の関数} codecs.EncodedFile (file, data_encoding, file_encoding=None, errors='strict')

透過的なエンコード変換を行うファイルのラップされたバージョンである、@ref{1dd4,,StreamRecoder} インスタンスを返します。元のファイルは、ラップされたバージョンが閉じられる時に、閉じられます。

ラップされたファイルに書き込まれたデータは、指定された `data_encoding' に従ってデコードされ、次に `file_encoding' を使用して元のファイルにバイトとして書き出されます。元のファイルから読み出されたバイトは、`file_encoding' に従ってデコードされ、結果は `data_encoding' を使用してエンコードされます。

`file_encoding' が与えられなければ、`data_encoding' がデフォルトになります。

エラーハンドリングのために `errors' を渡すことができます。これはデフォルトでは @code{'strict'} で、エンコード時にエラーがあれば @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex iterencode() (codecs モジュール)
@anchor{library/codecs codecs iterencode}@anchor{2845}
@deffn {の関数} codecs.iterencode (iterator, encoding, errors='strict', **kwargs)

Uses an incremental encoder to iteratively encode the input provided by
`iterator'. `iterator' must yield @ref{169,,str} objects.
This function is a @ref{126c,,generator}. The `errors' argument (as well as any
other keyword argument) is passed through to the incremental encoder.

この関数では、コーデックはエンコードするテキストの @ref{169,,str} オブジェクトを受け付ける必要があります。
従って、 @code{base64_codec} のようなバイトからバイトへのエンコーダはサポートしていません。
@end deffn

@geindex iterdecode() (codecs モジュール)
@anchor{library/codecs codecs iterdecode}@anchor{2846}
@deffn {の関数} codecs.iterdecode (iterator, encoding, errors='strict', **kwargs)

Uses an incremental decoder to iteratively decode the input provided by
`iterator'. `iterator' must yield @ref{192,,bytes} objects.
This function is a @ref{126c,,generator}. The `errors' argument (as well as any
other keyword argument) is passed through to the incremental decoder.

この関数では、コーデックはエンコードする @ref{192,,bytes} オブジェクトを受け付ける必要があります。
従って、 @code{rot_13} のようなテキストからテキストへのエンコーダが @ref{2845,,iterencode()} で同等に使えるとしても、この関数ではサポートしていません。
@end deffn

@geindex readbuffer_encode() (codecs モジュール)
@anchor{library/codecs codecs readbuffer_encode}@anchor{2847}
@deffn {の関数} codecs.readbuffer_encode (buffer, errors=None, /)

Return a @ref{614,,tuple} containing the raw bytes of `buffer', a
@ref{260,,buffer-compatible object} or @ref{169,,str}
(encoded to UTF-8 before processing), and their length in bytes.

The `errors' argument is ignored.

@example
>>> codecs.readbuffer_encode(b"Zito")
(b'Zito', 4)
@end example
@end deffn

このモジュールは以下のような定数も定義しています。プラットフォーム依存なファイルを読み書きするのに役立ちます:

@geindex BOM (codecs モジュール)
@geindex BOM_BE (codecs モジュール)
@geindex BOM_LE (codecs モジュール)
@geindex BOM_UTF8 (codecs モジュール)
@geindex BOM_UTF16 (codecs モジュール)
@geindex BOM_UTF16_BE (codecs モジュール)
@geindex BOM_UTF16_LE (codecs モジュール)
@geindex BOM_UTF32 (codecs モジュール)
@geindex BOM_UTF32_BE (codecs モジュール)
@geindex BOM_UTF32_LE (codecs モジュール)
@anchor{library/codecs codecs BOM}@anchor{2848}
@deffn {データ} codecs.BOM
@anchor{library/codecs codecs BOM_BE}@anchor{2849}
@deffnx {データ} codecs.BOM_BE
@anchor{library/codecs codecs BOM_LE}@anchor{284a}
@deffnx {データ} codecs.BOM_LE
@anchor{library/codecs codecs BOM_UTF8}@anchor{284b}
@deffnx {データ} codecs.BOM_UTF8
@anchor{library/codecs codecs BOM_UTF16}@anchor{284c}
@deffnx {データ} codecs.BOM_UTF16
@anchor{library/codecs codecs BOM_UTF16_BE}@anchor{284d}
@deffnx {データ} codecs.BOM_UTF16_BE
@anchor{library/codecs codecs BOM_UTF16_LE}@anchor{284e}
@deffnx {データ} codecs.BOM_UTF16_LE
@anchor{library/codecs codecs BOM_UTF32}@anchor{284f}
@deffnx {データ} codecs.BOM_UTF32
@anchor{library/codecs codecs BOM_UTF32_BE}@anchor{2850}
@deffnx {データ} codecs.BOM_UTF32_BE
@anchor{library/codecs codecs BOM_UTF32_LE}@anchor{2851}
@deffnx {データ} codecs.BOM_UTF32_LE

これらの定数は、いくつかのエンコーディングの Unicode のバイトオーダマーク (BOM) で、様々なバイトシーケンスを定義します。これらは、UTF-16 と UTF-32 のデータストリームで使用するバイトオーダを指定したり、 UTF-8 で Unicode シグネチャとして使われます。 @ref{284c,,BOM_UTF16} は、プラットフォームのネイティブバイトオーダによって @ref{284d,,BOM_UTF16_BE} または @ref{284e,,BOM_UTF16_LE} です。 @ref{2848,,BOM} は @ref{284c,,BOM_UTF16} のエイリアスです。同様に、 @ref{284a,,BOM_LE} は @ref{284e,,BOM_UTF16_LE} の、 @ref{2849,,BOM_BE} は @ref{284d,,BOM_UTF16_BE} のエイリアスです。その他の定数は UTF-8 と UTF-32 エンコーディングの BOM を表します。
@end deffn

@menu
* Codec 基底クラス:: 
* エンコーディングと Unicode:: 
* 標準エンコーディング:: 
* Python 特有のエンコーディング:: 
* encodings: encodings --- Encodings package. Encodings package
* encodings.idna: encodings idna --- Internationalized Domain Names in Applications. Internationalized Domain Names in Applications
* encodings.mbcs: encodings mbcs --- Windows ANSI codepage. Windows ANSI codepage
* encodings.utf_8_sig: encodings utf_8_sig --- UTF-8 codec with BOM signature. UTF-8 codec with BOM signature

@end menu

@node Codec 基底クラス,エンコーディングと Unicode,,codecs --- codec レジストリと基底クラス
@anchor{library/codecs codec-base-classes}@anchor{282c}@anchor{library/codecs id1}@anchor{2852}
@subsubsection Codec 基底クラス


The @code{codecs} module defines a set of base classes which define the
interfaces for working with codec objects, and can also be used as the basis
for custom codec implementations.

Python で codec として使えるようにするには、ステートレスエンコーダ、ステートレスデコーダ、ストリームリーダ、ストリームライタの 4 つのインターフェースを定義する必要があります。通常は、ストリームリーダとライタはステートレスエンコーダとデコーダを再利用して、ファイルプロトコルを実装します。codec の作者は、codec がエンコードとデコードのエラーの処理方法も定義する必要があります。
@anchor{library/codecs surrogateescape}@anchor{2853}
@menu
* エラーハンドラ:: 
* ステートレスなエンコードとデコード:: 
* インクリメンタルなエンコードとデコード:: 
* ストリームのエンコードとデコード:: 

@end menu

@node エラーハンドラ,ステートレスなエンコードとデコード,,Codec 基底クラス
@anchor{library/codecs error-handlers}@anchor{1b6f}@anchor{library/codecs id2}@anchor{2854}
@subsubsection エラーハンドラ


エラー処理の簡便化と標準化のため、コーデックは、`errors' 文字列引数を指定した場合に別のエラー処理を行うような仕組みを実装してもかまいません:

@example
>>> 'German ß, ♬'.encode(encoding='ascii', errors='backslashreplace')
b'German \\xdf, \\u266c'
>>> 'German ß, ♬'.encode(encoding='ascii', errors='xmlcharrefreplace')
b'German &#223;, &#9836;'
@end example

@geindex strict;error handler's name
@geindex ignore;error handler's name
@geindex replace;error handler's name
@geindex backslashreplace;error handler's name
@geindex surrogateescape;error handler's name
@geindex ? (クエスチョンマーク);replacement character
@geindex \ (backslash);エスケープシーケンス
@geindex \x;エスケープシーケンス
@geindex \u;エスケープシーケンス
@geindex \U;エスケープシーケンス

The following error handlers can be used with all Python
@ref{fb8,,標準エンコーディング} codecs:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

値

@tab

意味

@item

@code{'strict'}

@tab

@ref{462,,UnicodeError} (または、そのサブクラス) を送出します。これがデフォルトの動作です。 @ref{2855,,strict_errors()} で実装されています。

@item

@code{'ignore'}

@tab

不正な形式のデータを無視し、何も通知することなく処理を継続します。@ref{2856,,ignore_errors()} で実装されています。

@item

@code{'replace'}

@tab

Replace with a replacement marker. On
encoding, use @code{?} (ASCII character). On
decoding, use @code{�} (U+FFFD, the official
REPLACEMENT CHARACTER). Implemented in
@ref{18c2,,replace_errors()}.

@item

@code{'backslashreplace'}

@tab

Replace with backslashed escape sequences.
On encoding, use hexadecimal form of Unicode
code point with formats @code{\x@var{hh}}
@code{\u@var{xxxx}} @code{\U@var{xxxxxxxx}}.
On decoding, use hexadecimal form of byte
value with format @code{\x@var{hh}}.
Implemented in
@ref{18c3,,backslashreplace_errors()}.

@item

@code{'surrogateescape'}

@tab

デコード時には、バイト列を @code{U+DC80} から @code{U+DCFF} の範囲の個々のサロゲートコードで置き換えます。データのエンコード時に @code{'surrogateescape'} エラーハンドラが使用されると、このコードは同じバイト列に戻されます。 (詳しくは 
@geindex Python Enhancement Proposals; PEP 383
PEP 383@footnote{https://peps.python.org/pep-0383/} を参照。)

@end multitable


@geindex xmlcharrefreplace;error handler's name
@geindex namereplace;error handler's name
@geindex \N;エスケープシーケンス

The following error handlers are only applicable to encoding (within
@ref{25db,,text encodings}):


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

値

@tab

意味

@item

@code{'xmlcharrefreplace'}

@tab

Replace with XML/HTML numeric character
reference, which is a decimal form of Unicode
code point with format @code{&#@var{num};}.
Implemented in
@ref{18c4,,xmlcharrefreplace_errors()}.

@item

@code{'namereplace'}

@tab

Replace with @code{\N@{...@}} escape sequences,
what appears in the braces is the Name
property from Unicode Character Database.
Implemented in @ref{2857,,namereplace_errors()}.

@end multitable


@geindex surrogatepass;error handler's name

さらに、次のエラーハンドラは与えられた codec に特有です:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

値

@tab

Codecs

@tab

意味

@item

@code{'surrogatepass'}

@tab

utf-8, utf-16, utf-32,
utf-16-be, utf-16-le,
utf-32-be, utf-32-le

@tab

Allow encoding and decoding surrogate code
point (@code{U+D800} - @code{U+DFFF}) as normal
code point. Otherwise these codecs treat
the presence of surrogate code point in
@ref{169,,str} as an error.

@end multitable



Added in version 3.1: @code{'surrogateescape'} および @code{'surrogatepass'} エラーハンドラ。



バージョン 3.4 で変更: The @code{'surrogatepass'} error handler now works with utf-16* and utf-32*
codecs.



Added in version 3.5: @code{'namereplace'} エラーハンドラです。



バージョン 3.5 で変更: The @code{'backslashreplace'} error handler now works with decoding and
translating.


次のように、名前付きの新しいエラーハンドラを登録することで、許可される値の集合を拡張することができます。

@geindex register_error() (codecs モジュール)
@anchor{library/codecs codecs register_error}@anchor{16b4}
@deffn {の関数} codecs.register_error (name, error_handler, /)

エラーハンドラ `error_handler' を名前 `name' で登録します。エンコード中およびデコード中にエラーが送出された場合、`name' が errors 引数として指定されていれば `error_handler' が呼び出されます。

`error_handler' はエラーの場所に関する情報の入った @ref{887,,UnicodeEncodeError} インスタンスとともに呼び出されます。エラー処理関数はこの例外を送出するか、別の例外を送出するか、入力のエンコードできなかった部分の代替文字列とエンコードを再開する場所が入ったタプルを返す必要があります。代替文字列は @ref{169,,str} または @ref{192,,bytes} のいずれかにすることができます。代替文字列がバイト列である場合、エンコーダは単に出力バッファにそれをコピーします。代替文字列が文字列である場合、エンコーダは代替文字列をエンコードします。元の入力中の指定位置からエンコードが再開されます。位置を負の値にすると、入力文字列の末端からの相対位置として扱われます。境界の外側にある位置を返した場合には @ref{174e,,IndexError} が送出されます。

デコードと翻訳の動作は似ていますが、エラーハンドラに渡されるのが @ref{c08,,UnicodeDecodeError} か @ref{18fd,,UnicodeTranslateError} である点と、エラーハンドラの置換した内容が直接出力されるという点が異なります。
@end deffn

登録済みのエラーハンドラ (標準エラーハンドラを含む) は、次のようにその名前で検索することができます。

@geindex lookup_error() (codecs モジュール)
@anchor{library/codecs codecs lookup_error}@anchor{16b5}
@deffn {の関数} codecs.lookup_error (name, /)

名前 `name' で登録済みのエラーハンドラを返します。

エラーハンドラが見つからなければ @ref{23e5,,LookupError} を送出します。
@end deffn

以下の標準エラーハンドラも、モジュールレベルの関数として利用できます。

@geindex strict_errors() (codecs モジュール)
@anchor{library/codecs codecs strict_errors}@anchor{2855}
@deffn {の関数} codecs.strict_errors (exception)

Implements the @code{'strict'} error handling.

Each encoding or decoding error raises a @ref{462,,UnicodeError}.
@end deffn

@geindex ignore_errors() (codecs モジュール)
@anchor{library/codecs codecs ignore_errors}@anchor{2856}
@deffn {の関数} codecs.ignore_errors (exception)

Implements the @code{'ignore'} error handling.

Malformed data is ignored; encoding or decoding is continued without
further notice.
@end deffn

@geindex replace_errors() (codecs モジュール)
@anchor{library/codecs codecs replace_errors}@anchor{18c2}
@deffn {の関数} codecs.replace_errors (exception)

Implements the @code{'replace'} error handling.

Substitutes @code{?} (ASCII character) for encoding errors or @code{�} (U+FFFD,
the official REPLACEMENT CHARACTER) for decoding errors.
@end deffn

@geindex backslashreplace_errors() (codecs モジュール)
@anchor{library/codecs codecs backslashreplace_errors}@anchor{18c3}
@deffn {の関数} codecs.backslashreplace_errors (exception)

Implements the @code{'backslashreplace'} error handling.

Malformed data is replaced by a backslashed escape sequence.
On encoding, use the hexadecimal form of Unicode code point with formats
@code{\x@var{hh}} @code{\u@var{xxxx}} @code{\U@var{xxxxxxxx}}.
On decoding, use the hexadecimal form of
byte value with format @code{\x@var{hh}}.


バージョン 3.5 で変更: Works with decoding and translating.

@end deffn

@geindex xmlcharrefreplace_errors() (codecs モジュール)
@anchor{library/codecs codecs xmlcharrefreplace_errors}@anchor{18c4}
@deffn {の関数} codecs.xmlcharrefreplace_errors (exception)

Implements the @code{'xmlcharrefreplace'} error handling (for encoding within
@ref{25db,,text encoding} only).

The unencodable character is replaced by an appropriate XML/HTML numeric
character reference, which is a decimal form of Unicode code point with
format @code{&#@var{num};} .
@end deffn

@geindex namereplace_errors() (codecs モジュール)
@anchor{library/codecs codecs namereplace_errors}@anchor{2857}
@deffn {の関数} codecs.namereplace_errors (exception)

Implements the @code{'namereplace'} error handling (for encoding within
@ref{25db,,text encoding} only).

The unencodable character is replaced by a @code{\N@{...@}} escape sequence. The
set of characters that appear in the braces is the Name property from
Unicode Character Database. For example, the German lowercase letter @code{'ß'}
will be converted to byte sequence @code{\N@{LATIN SMALL LETTER SHARP S@}} .


Added in version 3.5.

@end deffn

@node ステートレスなエンコードとデコード,インクリメンタルなエンコードとデコード,エラーハンドラ,Codec 基底クラス
@anchor{library/codecs codec-objects}@anchor{2833}@anchor{library/codecs stateless-encoding-and-decoding}@anchor{2858}
@subsubsection ステートレスなエンコードとデコード


基底の @ref{2859,,Codec} クラスは以下のメソッドを定義します。これらのメソッドは、内部状態を持たないエンコーダ／デコーダ関数のインターフェースを定義します:

@geindex Codec (codecs のクラス)
@anchor{library/codecs codecs Codec}@anchor{2859}
@deffn {クラス} codecs.Codec

@geindex encode() (codecs.Codec のメソッド)
@anchor{library/codecs codecs Codec encode}@anchor{2831}
@deffn {メソッド} encode (input, errors='strict')

オブジェクト `input' エンコードし、(出力オブジェクト, 消費した長さ) のタプルを返します。例えば、 @ref{25db,,テキストエンコーディング} は文字列オブジェクトを特有の文字セット (例えば @code{cp1252} や @code{iso-8859-1}) を用いてバイト列オブジェクトに変換します。

`errors' 引数は適用するエラー処理を定義します。@code{'strict'} 処理がデフォルトです。

このメソッドは @ref{2859,,Codec} に内部状態を保存してはなりません。効率よくエンコードするために状態を保持しなければならないような codecs には @ref{283a,,StreamWriter} を使ってください。

エンコーダは長さが 0 の入力を処理できなければなりません。この場合、空のオブジェクトを出力オブジェクトとして返さなければなりません。
@end deffn

@geindex decode() (codecs.Codec のメソッド)
@anchor{library/codecs codecs Codec decode}@anchor{2832}
@deffn {メソッド} decode (input, errors='strict')

オブジェクト `input' をデコードし、(出力オブジェクト, 消費した長さ) のタプルを返します。例えば、 @ref{25db,,テキストエンコーディング} は、特定の文字集合エンコーディングでエンコードされたバイト列オブジェクトを文字列オブジェクトに変換します。

テキストエンコーディングとバイト列からバイト列への codec では、`input' は bytes オブジェクト、または読み出し専用のバッファインターフェースを提供するオブジェクトである必要があります。例えば、buffer オブジェクトやメモリマップドファイルでなければなりません。

`errors' 引数は適用するエラー処理を定義します。@code{'strict'} 処理がデフォルトです。

このメソッドは、 @ref{2859,,Codec} インスタンスに内部状態を保存してはなりません。効率よくエンコード／デコードするために状態を保持しなければならないような codecs には @ref{283b,,StreamReader} を使ってください。

デコーダは長さが 0 の入力を処理できなければなりません。この場合、空のオブジェクトを出力オブジェクトとして返さなければなりません。
@end deffn
@end deffn

@node インクリメンタルなエンコードとデコード,ストリームのエンコードとデコード,ステートレスなエンコードとデコード,Codec 基底クラス
@anchor{library/codecs incremental-encoding-and-decoding}@anchor{285a}
@subsubsection インクリメンタルなエンコードとデコード


@ref{2836,,IncrementalEncoder} クラスおよび @ref{2837,,IncrementalDecoder} クラスはそれぞれインクリメンタル・エンコードおよびデコードのための基本的なインターフェースを提供します。エンコード／デコードは内部状態を持たないエンコーダ／デコーダを一度呼び出すことで行なわれるのではなく、インクリメンタル・エンコーダ／デコーダの @ref{285b,,encode()}/@ref{285c,,decode()} メソッドを複数回呼び出すことで行なわれます。インクリメンタル・エンコーダ／デコーダはメソッド呼び出しの間エンコード／デコード処理の進行を管理します。

@ref{285b,,encode()}/@ref{285c,,decode()} メソッド呼び出しの出力結果をまとめたものは、入力をひとまとめにして内部状態を持たないエンコーダ／デコーダでエンコード／デコードしたものと同じになります。

@menu
* IncrementalEncoder オブジェクト:: 
* IncrementalDecoder オブジェクト:: 

@end menu

@node IncrementalEncoder オブジェクト,IncrementalDecoder オブジェクト,,インクリメンタルなエンコードとデコード
@anchor{library/codecs incremental-encoder-objects}@anchor{285d}@anchor{library/codecs incrementalencoder-objects}@anchor{285e}
@subsubsection IncrementalEncoder オブジェクト


@ref{2836,,IncrementalEncoder} クラスは入力を複数ステップでエンコードするのに使われます。全てのインクリメンタル・エンコーダが Python codec レジストリと互換性を持つために定義すべきメソッドとして、このクラスには以下のメソッドが定義されています。

@geindex IncrementalEncoder (codecs のクラス)
@anchor{library/codecs codecs IncrementalEncoder}@anchor{2836}
@deffn {クラス} codecs.IncrementalEncoder (errors='strict')

@ref{2836,,IncrementalEncoder} インスタンスのコンストラクタ。

全てのインクリメンタル・エンコーダはこのコンストラクタインターフェースを提供しなければなりません。さらにキーワード引数を付け加えるのは構いませんが、Python codec レジストリで利用されるのはここで定義されているものだけです。

@ref{2836,,IncrementalEncoder} は、 `errors' キーワード引数を提供することで、様々なエラー取扱方法を実装することができます。取り得る値については @ref{1b6f,,エラーハンドラ} を参照してください。

`errors' 引数は、同名の属性に代入されます。この属性を変更すると、 @ref{2836,,IncrementalEncoder} オブジェクトが生きている間に、異なるエラー処理方法に切り替えることができるようになります。

@geindex encode() (codecs.IncrementalEncoder のメソッド)
@anchor{library/codecs codecs IncrementalEncoder encode}@anchor{285b}
@deffn {メソッド} encode (object, final=False)

`object' を(エンコーダの現在の状態を考慮に入れて)エンコードし、得られたエンコードされたオブジェクトを返します。 @ref{1104,,encode()} 呼び出しがこれで最後という時には `final' は真でなければなりません(デフォルトは偽です)。
@end deffn

@geindex reset() (codecs.IncrementalEncoder のメソッド)
@anchor{library/codecs codecs IncrementalEncoder reset}@anchor{285f}
@deffn {メソッド} reset ()

エンコーダを初期状態にリセットします。出力は破棄されます。@code{.encode(object, final=True)} を呼び出して、必要に応じて空バイト列またはテキスト文字列を渡すことにより、エンコーダをリセットし、出力を取得します。
@end deffn

@geindex getstate() (codecs.IncrementalEncoder のメソッド)
@anchor{library/codecs codecs IncrementalEncoder getstate}@anchor{2860}
@deffn {メソッド} getstate ()

エンコーダの現在の状態を返します。それは必ず整数でなければなりません。実装は、@code{0} が最も一般的な状態であることを保証すべきです。 (整数より複雑な状態は、状態を marshal/pickle して生じた文字列のバイトを整数にコード化することによって整数に変換することができます。)
@end deffn

@geindex setstate() (codecs.IncrementalEncoder のメソッド)
@anchor{library/codecs codecs IncrementalEncoder setstate}@anchor{2861}
@deffn {メソッド} setstate (state)

エンコーダの状態を `state' にセットします。 `state' は @ref{2860,,getstate()} によって返されたエンコーダ状態でなければなりません。
@end deffn
@end deffn

@node IncrementalDecoder オブジェクト,,IncrementalEncoder オブジェクト,インクリメンタルなエンコードとデコード
@anchor{library/codecs incremental-decoder-objects}@anchor{2862}@anchor{library/codecs incrementaldecoder-objects}@anchor{2863}
@subsubsection IncrementalDecoder オブジェクト


@ref{2837,,IncrementalDecoder} クラスは入力を複数ステップでデコードするのに使われます。全てのインクリメンタル・デコーダが Python codec レジストリと互換性を持つために定義すべきメソッドとして、このクラスには以下のメソッドが定義されています。

@geindex IncrementalDecoder (codecs のクラス)
@anchor{library/codecs codecs IncrementalDecoder}@anchor{2837}
@deffn {クラス} codecs.IncrementalDecoder (errors='strict')

@ref{2837,,IncrementalDecoder} インスタンスのコンストラクタ。

全てのインクリメンタル・デコーダはこのコンストラクタインターフェースを提供しなければなりません。さらにキーワード引数を付け加えるのは構いませんが、Python codec レジストリで利用されるのはここで定義されているものだけです。

@ref{2837,,IncrementalDecoder} は、 `errors' キーワード引数を提供することで、様々なエラー取扱方法を実装することができます。取り得る値については @ref{1b6f,,エラーハンドラ} を参照してください。

`errors' 引数は、同名の属性に代入されます。この属性を変更すると、 @ref{2837,,IncrementalDecoder} オブジェクトが生きている間に、異なるエラー処理方法に切り替えることができるようになります。

@geindex decode() (codecs.IncrementalDecoder のメソッド)
@anchor{library/codecs codecs IncrementalDecoder decode}@anchor{285c}
@deffn {メソッド} decode (object, final=False)

`object' を(デコーダの現在の状態を考慮に入れて)デコードし、得られたデコードされたオブジェクトを返します。 @ref{1105,,decode()} 呼び出しがこれで最後という時には `final' は真でなければなりません(デフォルトは偽です)。もし `final' が真ならばデコーダは入力をデコードし切り全てのバッファをフラッシュしなければなりません。そうできない場合(たとえば入力の最後に不完全なバイト列があるから)、デコーダは内部状態を持たない場合と同じようにエラーの取り扱いを開始しなければなりません(例外を送出するかもしれません)。
@end deffn

@geindex reset() (codecs.IncrementalDecoder のメソッド)
@anchor{library/codecs codecs IncrementalDecoder reset}@anchor{2864}
@deffn {メソッド} reset ()

デコーダを初期状態にリセットします。
@end deffn

@geindex getstate() (codecs.IncrementalDecoder のメソッド)
@anchor{library/codecs codecs IncrementalDecoder getstate}@anchor{2865}
@deffn {メソッド} getstate ()

デコーダの現在の状態を返します。これは2要素を含むタプルでなければなりません。1番目はまだデコードされていない入力を含むバッファです。2番目は整数で、付加的な状態情報です (実装は @code{0} が最も一般的な付加的な状態情報であることを保証すべきです)。この付加的な状態情報が @code{0} である場合、デコーダを入力がバッファされていない状態に戻して、付加的な状態情報を @code{0} にセットすることが可能でなければなりません。その結果、以前バッファされた入力をデコーダに与えることで、何の出力もせずにデコーダを前の状態に戻します。 (整数より複雑な付加的な状態情報は、情報を marshal/pickle して、結果として生じる文字列のバイト列を整数にエンコードすることで、整数に変換することができます。)
@end deffn

@geindex setstate() (codecs.IncrementalDecoder のメソッド)
@anchor{library/codecs codecs IncrementalDecoder setstate}@anchor{2866}
@deffn {メソッド} setstate (state)

デコーダの状態を `state' にセットします。
`state' は @ref{2865,,getstate()} によって返されたデコーダの状態でなければなりません。
@end deffn
@end deffn

@node ストリームのエンコードとデコード,,インクリメンタルなエンコードとデコード,Codec 基底クラス
@anchor{library/codecs stream-encoding-and-decoding}@anchor{2867}
@subsubsection ストリームのエンコードとデコード


The @ref{283a,,StreamWriter} and @ref{283b,,StreamReader} classes provide generic
working interfaces which can be used to implement new encoding submodules very
easily. See @code{encodings.utf_8} for an example of how this is done.

@menu
* StreamWriter オブジェクト:: 
* StreamReader オブジェクト:: 
* StreamReaderWriter オブジェクト:: 
* StreamRecoder オブジェクト:: 

@end menu

@node StreamWriter オブジェクト,StreamReader オブジェクト,,ストリームのエンコードとデコード
@anchor{library/codecs stream-writer-objects}@anchor{2868}@anchor{library/codecs streamwriter-objects}@anchor{2869}
@subsubsection StreamWriter オブジェクト


@ref{283a,,StreamWriter} クラスは @ref{2859,,Codec} のサブクラスで、以下のメソッドを定義しています。全てのストリームライタは、 Python の codec レジストリとの互換性を保つために、これらのメソッドを定義する必要があります。

@geindex StreamWriter (codecs のクラス)
@anchor{library/codecs codecs StreamWriter}@anchor{283a}
@deffn {クラス} codecs.StreamWriter (stream, errors='strict')

@ref{283a,,StreamWriter} インスタンスのコンストラクタです。

全てのストリームライタはコンストラクタとしてこのインターフェースを提供しなければなりません。キーワード引数を追加しても構いませんが、Python の codec レジストリはここで定義されている引数だけを使います。

`stream' 引数は、特定の codec に対応して、テキストまたはバイナリデータの書き込みが可能なファイルライクオブジェクトである必要があります。

@ref{283a,,StreamWriter} は、 `errors' キーワード引数を提供することで、様々なエラー取扱方法を実装することができます。下層のストリーム codec がサポートできる標準エラーハンドラについては @ref{1b6f,,エラーハンドラ} を参照してください。

`errors' 引数は、同名の属性に代入されます。この属性を変更すると、 @ref{283a,,StreamWriter} オブジェクトが生きている間に、異なるエラー処理に変更できます。

@geindex write() (codecs.StreamWriter のメソッド)
@anchor{library/codecs codecs StreamWriter write}@anchor{286a}
@deffn {メソッド} write (object)

`object' の内容をエンコードしてストリームに書き出します。
@end deffn

@geindex writelines() (codecs.StreamWriter のメソッド)
@anchor{library/codecs codecs StreamWriter writelines}@anchor{286b}
@deffn {メソッド} writelines (list)

Writes the concatenated iterable of strings to the stream (possibly by reusing
the @ref{286a,,write()} method). Infinite or
very large iterables are not supported. The standard bytes-to-bytes codecs
do not support this method.
@end deffn

@geindex reset() (codecs.StreamWriter のメソッド)
@anchor{library/codecs codecs StreamWriter reset}@anchor{286c}
@deffn {メソッド} reset ()

内部状態保持に使われた codec のバッファをリセットします。

このメソッドが呼び出された場合、出力先データをきれいな状態にし、わざわざストリーム全体を再スキャンして状態を元に戻さなくても新しくデータを追加できるようにしなければなりません。
@end deffn
@end deffn

ここまでで挙げたメソッドの他にも、 @ref{283a,,StreamWriter} では背後にあるストリームの他の全てのメソッドや属性を継承しなければなりません。

@node StreamReader オブジェクト,StreamReaderWriter オブジェクト,StreamWriter オブジェクト,ストリームのエンコードとデコード
@anchor{library/codecs stream-reader-objects}@anchor{286d}@anchor{library/codecs streamreader-objects}@anchor{286e}
@subsubsection StreamReader オブジェクト


@ref{283b,,StreamReader} クラスは @ref{2859,,Codec} のサブクラスで、以下のメソッドを定義しています。全てのストリームリーダは、 Python の codec レジストリとの互換性を保つために、これらのメソッドを定義する必要があります。

@geindex StreamReader (codecs のクラス)
@anchor{library/codecs codecs StreamReader}@anchor{283b}
@deffn {クラス} codecs.StreamReader (stream, errors='strict')

@ref{283b,,StreamReader} インスタンスのコンストラクタです。

全てのストリームリーダはコンストラクタとしてこのインターフェースを提供しなければなりません。キーワード引数を追加しても構いませんが、Python の codec レジストリはここで定義されている引数だけを使います。

`stream' 引数は、特定の codec に対応して、テキストまたはバイナリデータの読み出しが可能なファイルライクオブジェクトである必要があります。

@ref{283b,,StreamReader} は、 `errors' キーワード引数を提供することで、様々なエラー取扱方法を実装することができます。下層のストリーム codec がサポートできる標準エラーハンドラについては @ref{1b6f,,エラーハンドラ} を参照してください。

`errors' 引数は、同名の属性に代入されます。この属性を変更すると、 @ref{283b,,StreamReader} オブジェクトが生きている間に、異なるエラー処理に変更できます。

`errors' 引数に許される値の集合は @ref{16b4,,register_error()} で拡張できます。

@geindex read() (codecs.StreamReader のメソッド)
@anchor{library/codecs codecs StreamReader read}@anchor{286f}
@deffn {メソッド} read (size=-1, chars=-1, firstline=False)

ストリームからのデータをデコードし、デコード済のオブジェクトを返します。

`chars' 引数は、いくつのデコードされたコードポイントまたはバイト列を返すかを表します。 @ref{286f,,read()} メソッドは、要求された数以上のデータを返すことはありませんが、データがそれより少ない場合には要求された数未満のデータを返す場合があります。

`size' 引数は、デコード用に読み込むエンコードされたバイト列またはコードポイントの、およその最大バイト数を表します。デコーダはこの値を適切な値に変更できます。デフォルト値 -1 の場合、可能な限り多くのデータを読み込みます。この引数の目的は、巨大なファイルの一括デコードを防ぐことにあります。

`firstline' フラグは、1行目さえ返せばその後の行でデコードエラーがあっても無視して十分だ、ということを示します。

このメソッドは貪欲な読み込み戦略を取るべきです。すなわち、エンコーディング定義と size の値が許す範囲で、できるだけ多くのデータを読むべきだということです。たとえば、ストリーム上にエンコーディングの終端や状態の目印があれば、それも読み込みます。
@end deffn

@geindex readline() (codecs.StreamReader のメソッド)
@anchor{library/codecs codecs StreamReader readline}@anchor{2870}
@deffn {メソッド} readline (size=None, keepends=True)

入力ストリームから1行読み込み、デコード済みのデータを返します。

`size' が与えられた場合、ストリームの @ref{286f,,read()} メソッドに size 引数として渡されます。

`keepends' が偽の場合には行末の改行が削除された行が返ります。
@end deffn

@geindex readlines() (codecs.StreamReader のメソッド)
@anchor{library/codecs codecs StreamReader readlines}@anchor{2871}
@deffn {メソッド} readlines (sizehint=None, keepends=True)

入力ストリームから全ての行を読み込み、行のリストとして返します。

`keepends' が真なら、改行は、codec の @ref{1105,,decode()} メソッドを使って実装され、リスト要素の中に含まれます。

`sizehint' が与えられた場合、ストリームの @ref{286f,,read()} メソッドに `size' 引数として渡されます。
@end deffn

@geindex reset() (codecs.StreamReader のメソッド)
@anchor{library/codecs codecs StreamReader reset}@anchor{2872}
@deffn {メソッド} reset ()

内部状態保持に使われた codec のバッファをリセットします。

ストリームの読み位置を再設定してはならないので注意してください。このメソッドはデコードの際にエラーから復帰できるようにするためのものです。
@end deffn
@end deffn

ここまでで挙げたメソッドの他にも、 @ref{283b,,StreamReader} では背後にあるストリームの他の全てのメソッドや属性を継承しなければなりません。

@node StreamReaderWriter オブジェクト,StreamRecoder オブジェクト,StreamReader オブジェクト,ストリームのエンコードとデコード
@anchor{library/codecs stream-reader-writer}@anchor{2873}@anchor{library/codecs streamreaderwriter-objects}@anchor{2874}
@subsubsection StreamReaderWriter オブジェクト


@ref{2843,,StreamReaderWriter} は、読み書き両方に使えるストリームをラップできる便利なクラスです。

@ref{b5c,,lookup()} 関数が返すファクトリ関数を使って、インスタンスを生成するという設計です。

@geindex StreamReaderWriter (codecs のクラス)
@anchor{library/codecs codecs StreamReaderWriter}@anchor{2843}
@deffn {クラス} codecs.StreamReaderWriter (stream, Reader, Writer, errors='strict')

@ref{2843,,StreamReaderWriter} インスタンスを生成します。 `stream' はファイル類似のオブジェクトです。 `Reader' と `Writer' は、それぞれ @ref{283b,,StreamReader} と @ref{283a,,StreamWriter} インターフェースを提供するファクトリ関数かファクトリクラスでなければなりません。エラー処理は、ストリームリーダとライタで定義したものと同じように行われます。
@end deffn

@ref{2843,,StreamReaderWriter} インスタンスは、 @ref{283b,,StreamReader} クラスと @ref{283a,,StreamWriter} クラスを合わせたインターフェースを継承します。元になるストリームからは、他のメソッドや属性を継承します。

@node StreamRecoder オブジェクト,,StreamReaderWriter オブジェクト,ストリームのエンコードとデコード
@anchor{library/codecs stream-recoder-objects}@anchor{2875}@anchor{library/codecs streamrecoder-objects}@anchor{2876}
@subsubsection StreamRecoder オブジェクト


@ref{1dd4,,StreamRecoder} はデータをあるエンコーディングから別のエンコーディングに変換します。異なるエンコーディング環境を扱うとき、便利な場合があります。

@ref{b5c,,lookup()} 関数が返すファクトリ関数を使って、インスタンスを生成するという設計です。

@geindex StreamRecoder (codecs のクラス)
@anchor{library/codecs codecs StreamRecoder}@anchor{1dd4}
@deffn {クラス} codecs.StreamRecoder (stream, encode, decode, Reader, Writer, errors='strict')

Creates a @ref{1dd4,,StreamRecoder} instance which implements a two-way conversion:
`encode' and `decode' work on the frontend — the data visible to
code calling @ref{286f,,read()} and @ref{286a,,write()},
while `Reader' and `Writer'
work on the backend — the data in `stream'.

これらのオブジェクトを使って、たとえば、 Latin-1 から UTF-8 への変換、あるいは逆向きの変換を、透過的に行うことができます。

`stream' 引数はファイルライクオブジェクトでなくてはなりません。

`encode' 引数と `decode' 引数は @ref{2859,,Codec} のインターフェースに忠実でなくてはなりません。`Reader' と `Writer' は、それぞれ @ref{283b,,StreamReader} と @ref{283a,,StreamWriter} のインターフェースを提供するオブジェクトのファクトリ関数かクラスでなくてはなりません。

エラー処理はストリーム・リーダやライタで定義されている方法と同じように行われます。
@end deffn

@ref{1dd4,,StreamRecoder} インスタンスは、 @ref{283b,,StreamReader} と @ref{283a,,StreamWriter} クラスを合わせたインターフェースを定義します。また、元のストリームのメソッドと属性も継承します。

@node エンコーディングと Unicode,標準エンコーディング,Codec 基底クラス,codecs --- codec レジストリと基底クラス
@anchor{library/codecs encodings-and-unicode}@anchor{2877}@anchor{library/codecs encodings-overview}@anchor{2878}
@subsubsection エンコーディングと Unicode


文字列は内部的に @code{U+0000}--@code{U+10FFFF} の範囲のコードポイントのシーケンスとして格納されます (実装に関する詳細については 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} を参照してください)。
文字列オブジェクトが CPU とメモリの外で使用されるようになると、エンディアンやこれらの配列をバイト列として格納する方法が問題になります。
他のコーデックでも同様ですが、文字列オブジェクトをバイト列に変換することは `エンコード' と呼ばれます。
また、バイト列から文字列オブジェクトを再生成することは `デコード' と呼ばれます。
テキストをシリアライズするコーデックには多くの種類があります。
それらは、集合的に term:@cite{テキストエンコーディング <text encoding>} と呼ばれます。

最も単純なテキストエンコーディング (@code{'latin-1'} または @code{'iso-8859-1'}) では、0--255 の範囲にあるコードポイントを @code{0x0}--@code{0xff} のバイトにマップします。
つまり、この codec では @code{U+00FF} 以上のコードポイントを含む文字列オブジェクトをエンコードすることはできません。
このようなエンコード処理をしようとすると、次のように @ref{887,,UnicodeEncodeError} が送出されます (エラーメッセージの細かところは異なる場合があります。): @code{UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in position 3: ordinal not in range(256)} 。

他のエンコーディングの一群 (charmap エンコーディングと呼ばれます) があり、 Unicode コードポイントの別の部分集合と、それらから @code{0x0}--@code{0xff} のバイトへの対応付けを選択したものです。
これがどのように行なわれるかを知るには、単にたとえば @code{encodings/cp1252.py} (主に Windows で使われるエンコーディングです) を開いてみてください。
256 文字のひとつの文字列定数があり、どの文字がどのバイト値へ対応付けられるかが示されています。

All of these encodings can only encode 256 of the 1114112 code points
defined in Unicode. A simple and straightforward way that can store each Unicode
code point, is to store each code point as four consecutive bytes. There are two
possibilities: store the bytes in big endian or in little endian order. These
two encodings are called @code{UTF-32-BE} and @code{UTF-32-LE} respectively. Their
disadvantage is that if, for example, you use @code{UTF-32-BE} on a little endian
machine you will always have to swap bytes on encoding and decoding.
Python's @code{UTF-16} and @code{UTF-32} codecs avoid this problem by using the
platform's native byte order when no BOM is present.
Python follows prevailing platform
practice, so native-endian data round-trips without redundant byte swapping,
even though the Unicode Standard defaults to big-endian when the byte order is
unspecified. When these bytes are read by a CPU with a different endianness,
the bytes have to be swapped. To be able to detect the endianness of a
@code{UTF-16} or @code{UTF-32} byte sequence, a BOM ("Byte Order Mark") is used.
This is the Unicode character @code{U+FEFF}. This character can be prepended to every
@code{UTF-16} or @code{UTF-32} byte sequence. The byte swapped version of this character
(@code{0xFFFE}) is an illegal character that may not appear in a Unicode text.
When the first character of a @code{UTF-16} or @code{UTF-32} byte sequence is
@code{U+FFFE}, the bytes have to be swapped on decoding.

Unfortunately the character @code{U+FEFF} had a second purpose as
a @code{ZERO WIDTH NO-BREAK SPACE}: a character that has no width and doesn't allow
a word to be split. It can e.g. be used to give hints to a ligature algorithm.
With Unicode 4.0 using @code{U+FEFF} as a @code{ZERO WIDTH NO-BREAK SPACE} has been
deprecated (with @code{U+2060} (@code{WORD JOINER}) assuming this role). Nevertheless
Unicode software still must be able to handle @code{U+FEFF} in both roles: as a BOM
it's a device to determine the storage layout of the encoded bytes, and vanishes
once the byte sequence has been decoded into a string; as a @code{ZERO WIDTH
NO-BREAK SPACE} it's a normal character that will be decoded like any other.

さらにもう一つ Unicode 文字全てをエンコードできるエンコーディングがあり、UTF-8 と呼ばれています。UTF-8 は8ビットエンコーディングで、したがって UTF-8 にはバイト順の問題はありません。UTF-8 バイト列の各バイトは二つのパートから成ります。二つはマーカ(上位数ビット)とペイロードです。マーカは0ビットから4ビットの @code{1} の列に @code{0} のビットが一つ続いたものです。Unicode 文字は次のようにエンコードされます (x はペイロードを表わし、連結されると一つの Unicode 文字を表わします):


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

範囲

@tab

エンコーディング

@item

@code{U-00000000} ... @code{U-0000007F}

@tab

0xxxxxxx

@item

@code{U-00000080} ... @code{U-000007FF}

@tab

110xxxxx 10xxxxxx

@item

@code{U-00000800} ... @code{U-0000FFFF}

@tab

1110xxxx 10xxxxxx 10xxxxxx

@item

@code{U-00010000} ... @code{U-0010FFFF}

@tab

11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

@end multitable


Unicode 文字の最下位ビットとは最も右にある x のビットです。

UTF-8 は8ビットエンコーディングなので BOM は必要とせず、デコードされた文字列中の @code{U+FEFF} は(たとえ最初の文字であったとしても) @code{ZERO WIDTH NO-BREAK SPACE} として扱われます。

外部からの情報無しには、文字列のエンコーディングにどのエンコーディングが使われたのか信頼できる形で決定することは不可能です。どの charmap エンコーディングもどんなランダムなバイト列でもデコードできます。しかし UTF-8 ではそれは可能ではありません。任意のバイト列を許さないような構造を持っているからです。UTF-8 エンコーディングであることを検知する信頼性を向上させるために、Microsoft は Notepad プログラム用に UTF-8 の変種 (Python では @code{"utf-8-sig"} と呼んでいます) を考案しました。Unicode 文字がファイルに書き込まれる前に UTF-8 でエンコードした BOM (バイト列では @code{0xef}, @code{0xbb}, @code{0xbf} のように見えます) が書き込まれます。このようなバイト値で charmap エンコードされたファイルが始まることはほとんどあり得ない (たとえば iso-8859-1 では

@quotation


@display
LATIN SMALL LETTER I WITH DIAERESIS@w{ }
RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK@w{ }
INVERTED QUESTION MARK@w{ }
@end display


@end quotation

のようになる)ので、@code{utf-8-sig} エンコーディングがバイト列から正しく推測される確率を高めます。つまりここでは BOM はバイト列を生成する際のバイト順を決定できるように使われているのではなく、エンコーディングを推測する助けになる印として使われているのです。@code{utf-8-sig} codec はエンコーディングの際ファイルに最初の3文字として @code{0xef}, @code{0xbb}, @code{0xbf} を書き込みます。デコーディングの際はファイルの先頭に現れたこれら3バイトはスキップします。UTF-8 では BOM の使用は推奨されておらず、一般的には避けるべきです。

@node 標準エンコーディング,Python 特有のエンコーディング,エンコーディングと Unicode,codecs --- codec レジストリと基底クラス
@anchor{library/codecs id3}@anchor{2879}@anchor{library/codecs standard-encodings}@anchor{fb8}
@subsubsection 標準エンコーディング


Python comes with a number of codecs built-in, either implemented as C functions
or with dictionaries as mapping tables. The following table lists the codecs by
name, together with a few common aliases, and the languages for which the
encoding is likely used. Neither the list of aliases nor the list of languages
is meant to be exhaustive. Notice that spelling alternatives that only differ in
case or use a hyphen instead of an underscore are also valid aliases
because they are equivalent when normalized by
@ref{9fd,,normalize_encoding()}. For example, @code{'utf-8'} is a valid
alias for the @code{'utf_8'} codec.

@cartouche
@quotation 注釈 
The below table lists the most common aliases, for a complete list
refer to the source aliases.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/encodings/aliases.py} file.
@end quotation
@end cartouche

On Windows, @code{cpXXX} codecs are available for all code pages.
But only codecs listed in the following table are guarantead to exist on
other platforms.

いくつかの一般的なエンコーディングは、パフォーマンスを改善するために codec の検索機構を回避することがあります。
このような最適化の機会を認識するのは、 CPython の限定された (大文字小文字を区別しない) 別名に対してのみです: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs (Windows のみ), ascii, us-ascii, utf-16, utf16, utf-32, utf32 およびダッシュの代わりにアンダースコアを用いたもの。
これらのエンコーディングの別のつづりを使用すると実行時間の低下を招くかもしれません。


バージョン 3.6 で変更: us-ascii に対して最適化の機会が認識されるようになりました。


多くの文字セットは同じ言語をサポートしています。これらの文字セットは個々の文字 (例えば、EURO SIGN がサポートされているかどうか) や、文字のコード部分への割り付けが異なります。特に欧州言語では、典型的に以下の変種が存在します:


@itemize *

@item 
ISO 8859 コードセット

@item 
Microsoft Windows コードページで、8859 コード形式から導出されているが、制御文字を追加のグラフィック文字と置き換えたもの

@item 
IBM EBCDIC コードページ

@item 
ASCII 互換の IBM PC コードページ
@end itemize


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Codec

@tab

別名

@tab

言語

@item

ascii

@tab

646, us-ascii

@tab

英語

@item

big5

@tab

big5-tw, csbig5

@tab

繁体字中国語

@item

big5hkscs

@tab

big5-hkscs, hkscs

@tab

繁体字中国語

@item

cp037

@tab

IBM037, IBM039

@tab

英語

@item

cp273

@tab

273, IBM273, csIBM273

@tab

ドイツ語


Added in version 3.4.


@item

cp424

@tab

EBCDIC-CP-HE, IBM424

@tab

ヘブライ語

@item

cp437

@tab

437, IBM437

@tab

英語

@item

cp500

@tab

EBCDIC-CP-BE, EBCDIC-CP-CH,
IBM500

@tab

西ヨーロッパ言語

@item

cp720

@tab

@tab

アラビア語

@item

cp737

@tab

@tab

ギリシャ語

@item

cp775

@tab

IBM775

@tab

バルト沿岸国

@item

cp850

@tab

850, IBM850

@tab

西ヨーロッパ言語

@item

cp852

@tab

852, IBM852

@tab

中央および東ヨーロッパ

@item

cp855

@tab

855, IBM855

@tab

Belarusian, Bulgarian,
Macedonian, Russian, Serbian

@item

cp856

@tab

@tab

ヘブライ語

@item

cp857

@tab

857, IBM857

@tab

トルコ語

@item

cp858

@tab

858, IBM858

@tab

西ヨーロッパ言語

@item

cp860

@tab

860, IBM860

@tab

ポルトガル語

@item

cp861

@tab

861, CP-IS, IBM861

@tab

アイスランド語

@item

cp862

@tab

862, IBM862

@tab

ヘブライ語

@item

cp863

@tab

863, IBM863

@tab

カナダ

@item

cp864

@tab

IBM864

@tab

アラビア語

@item

cp865

@tab

865, IBM865

@tab

デンマーク、ノルウェー

@item

cp866

@tab

866, IBM866

@tab

ロシア語

@item

cp869

@tab

869, CP-GR, IBM869

@tab

ギリシャ語

@item

cp874

@tab

@tab

タイ語

@item

cp875

@tab

@tab

ギリシャ語

@item

cp932

@tab

932, ms932, mskanji, ms-kanji,
windows-31j

@tab

日本語

@item

cp949

@tab

949, ms949, uhc

@tab

韓国語

@item

cp950

@tab

950, ms950

@tab

繁体字中国語

@item

cp1006

@tab

@tab

Urdu

@item

cp1026

@tab

ibm1026

@tab

トルコ語

@item

cp1125

@tab

1125, ibm1125, cp866u, ruscii

@tab

ウクライナ語


Added in version 3.4.


@item

cp1140

@tab

ibm1140

@tab

西ヨーロッパ言語

@item

cp1250

@tab

windows-1250

@tab

中央および東ヨーロッパ

@item

cp1251

@tab

windows-1251

@tab

Belarusian, Bulgarian,
Macedonian, Russian, Serbian

@item

cp1252

@tab

windows-1252

@tab

西ヨーロッパ言語

@item

cp1253

@tab

windows-1253

@tab

ギリシャ語

@item

cp1254

@tab

windows-1254

@tab

トルコ語

@item

cp1255

@tab

windows-1255

@tab

ヘブライ語

@item

cp1256

@tab

windows-1256

@tab

アラビア語

@item

cp1257

@tab

windows-1257

@tab

バルト沿岸国

@item

cp1258

@tab

windows-1258

@tab

ベトナム

@item

euc_jp

@tab

eucjp, ujis, u-jis

@tab

日本語

@item

euc_jis_2004

@tab

jisx0213, eucjis2004

@tab

日本語

@item

euc_jisx0213

@tab

eucjisx0213

@tab

日本語

@item

euc_kr

@tab

euckr, korean, ksc5601,
ks_c-5601, ks_c-5601-1987,
ksx1001, ks_x-1001

@tab

韓国語

@item

gb2312

@tab

chinese, csiso58gb231280,
euc-cn, euccn, eucgb2312-cn,
gb2312-1980, gb2312-80,
iso-ir-58

@tab

簡体字中国語

@item

gbk

@tab

936, cp936, ms936

@tab

Unified Chinese

@item

gb18030

@tab

gb18030-2000

@tab

Unified Chinese

@item

hz

@tab

hzgb, hz-gb, hz-gb-2312

@tab

簡体字中国語

@item

iso2022_jp

@tab

csiso2022jp, iso2022jp,
iso-2022-jp

@tab

日本語

@item

iso2022_jp_1

@tab

iso2022jp-1, iso-2022-jp-1

@tab

日本語

@item

iso2022_jp_2

@tab

iso2022jp-2, iso-2022-jp-2

@tab

日本語, 韓国語, 簡体字中国語, 西欧, ギリシャ語

@item

iso2022_jp_2004

@tab

iso2022jp-2004,
iso-2022-jp-2004

@tab

日本語

@item

iso2022_jp_3

@tab

iso2022jp-3, iso-2022-jp-3

@tab

日本語

@item

iso2022_jp_ext

@tab

iso2022jp-ext, iso-2022-jp-ext

@tab

日本語

@item

iso2022_kr

@tab

csiso2022kr, iso2022kr,
iso-2022-kr

@tab

韓国語

@item

latin_1

@tab

iso-8859-1, iso8859-1, 8859,
cp819, latin, latin1, L1

@tab

西ヨーロッパ言語

@item

iso8859_2

@tab

iso-8859-2, latin2, L2

@tab

中央および東ヨーロッパ

@item

iso8859_3

@tab

iso-8859-3, latin3, L3

@tab

エスペラント、マルタ

@item

iso8859_4

@tab

iso-8859-4, latin4, L4

@tab

Northern Europe

@item

iso8859_5

@tab

iso-8859-5, cyrillic

@tab

Belarusian, Bulgarian,
Macedonian, Russian, Serbian

@item

iso8859_6

@tab

iso-8859-6, arabic

@tab

アラビア語

@item

iso8859_7

@tab

iso-8859-7, greek, greek8

@tab

ギリシャ語

@item

iso8859_8

@tab

iso-8859-8, hebrew

@tab

ヘブライ語

@item

iso8859_9

@tab

iso-8859-9, latin5, L5

@tab

トルコ語

@item

iso8859_10

@tab

iso-8859-10, latin6, L6

@tab

北欧語

@item

iso8859_11

@tab

iso-8859-11, thai

@tab

タイ語

@item

iso8859_13

@tab

iso-8859-13, latin7, L7

@tab

バルト沿岸国

@item

iso8859_14

@tab

iso-8859-14, latin8, L8

@tab

ケルト語

@item

iso8859_15

@tab

iso-8859-15, latin9, L9

@tab

西ヨーロッパ言語

@item

iso8859_16

@tab

iso-8859-16, latin10, L10

@tab

南東ヨーロッパ

@item

johab

@tab

cp1361, ms1361

@tab

韓国語

@item

koi8_r

@tab

@tab

ロシア語

@item

koi8_t

@tab

@tab

タジク


Added in version 3.5.


@item

koi8_u

@tab

@tab

ウクライナ語

@item

kz1048

@tab

kz_1048, strk1048_2002, rk1048

@tab

カザフ


Added in version 3.5.


@item

mac_cyrillic

@tab

maccyrillic

@tab

Belarusian, Bulgarian,
Macedonian, Russian, Serbian

@item

mac_greek

@tab

macgreek

@tab

ギリシャ語

@item

mac_iceland

@tab

maciceland

@tab

アイスランド語

@item

mac_latin2

@tab

maclatin2, maccentraleurope,
mac_centeuro

@tab

中央および東ヨーロッパ

@item

mac_roman

@tab

macroman, macintosh

@tab

西ヨーロッパ言語

@item

mac_turkish

@tab

macturkish

@tab

トルコ語

@item

ptcp154

@tab

csptcp154, pt154, cp154,
cyrillic-asian

@tab

カザフ

@item

shift_jis

@tab

csshiftjis, shiftjis, sjis,
s_jis

@tab

日本語

@item

shift_jis_2004

@tab

shiftjis2004, sjis_2004,
sjis2004

@tab

日本語

@item

shift_jisx0213

@tab

shiftjisx0213, sjisx0213,
s_jisx0213

@tab

日本語

@item

utf_32

@tab

U32, utf32

@tab

全ての言語

@item

utf_32_be

@tab

UTF-32BE

@tab

全ての言語

@item

utf_32_le

@tab

UTF-32LE

@tab

全ての言語

@item

utf_16

@tab

U16, utf16

@tab

全ての言語

@item

utf_16_be

@tab

UTF-16BE

@tab

全ての言語

@item

utf_16_le

@tab

UTF-16LE

@tab

全ての言語

@item

utf_7

@tab

U7, unicode-1-1-utf-7

@tab

全ての言語

@item

utf_8

@tab

U8, UTF, utf8, cp65001

@tab

全ての言語

@item

utf_8_sig

@tab

@tab

全ての言語

@end multitable



バージョン 3.4 で変更: utf-16* と utf-32* のエンコーダは、サロゲートコードポイント (@code{U+D800}--@code{U+DFFF})  がエンコードされることを許可しなくなりました。utf-32* デコーダは、サロゲートコードポイントに対応するバイト列をデコードしなくなりました。



バージョン 3.8 で変更: @code{cp65001} is now an alias to @code{utf_8}.



バージョン 3.14 で変更: On Windows, @code{cpXXX} codecs are now available for all code pages.


@node Python 特有のエンコーディング,encodings --- Encodings package,標準エンコーディング,codecs --- codec レジストリと基底クラス
@anchor{library/codecs python-specific-encodings}@anchor{287a}
@subsubsection Python 特有のエンコーディング


予め定義された codec のいくつかは Python 特有のものなので、それらの codec 名は Python の外では無意味なものとなります。以下に、想定されている入出力のタイプに基づいて、それらを表にしました（テキストエンコーディングは codec の最も一般的な使用例ですが、その根底にある codec 基盤は、ただのテキストエンコーディングというよりも、任意のデータの変換をサポートしていることに注意してください）。非対称的な codec については、記載された意味がエンコーディングの方向を説明しています。

@menu
* テキストエンコーディング:: 
* バイナリ変換 (Binary Transforms): バイナリ変換 Binary Transforms. 
* Standalone Codec Functions:: 
* テキスト変換 (Text Transforms): テキスト変換 Text Transforms. 

@end menu

@node テキストエンコーディング,バイナリ変換 Binary Transforms,,Python 特有のエンコーディング
@anchor{library/codecs text-encodings}@anchor{287b}
@subsubsection テキストエンコーディング


次の codec では、 Unicode におけるテキストエンコーディングと同様に、 @ref{169,,str} から @ref{192,,bytes} へのエンコードと、 @ref{193,,bytes-like object} から @ref{169,,str} へのデコードを提供します。


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Codec

@tab

別名

@tab

意味

@item

idna

@tab

@tab

@geindex RFC; RFC 3490
RFC 3490@footnote{https://datatracker.ietf.org/doc/html/rfc3490.html} の実装です。 @ref{56,,encodings.idna} も参照してください。 @code{errors='strict'} のみがサポートされています。

@item

mbcs

@tab

ansi,
dbcs

@tab

Windows のみ: 被演算子を ANSI コードページ (CP_ACP) に従ってエンコードします。

@item

oem

@tab

@tab

Windows のみ: 被演算子を OEM コードページ (CP_OEMCP) に従ってエンコードします。


Added in version 3.6.


@item

palmos

@tab

@tab

PalmOS 3.5 のエンコーディングです。

@item

punycode

@tab

@tab

@geindex RFC; RFC 3492
RFC 3492@footnote{https://datatracker.ietf.org/doc/html/rfc3492.html} の実装です。ステートフル codecs は、サポートされません。

@item

raw_unicode_escape

@tab

@tab

Latin-1 encoding with
@code{\u@var{XXXX}} and
@code{\U@var{XXXXXXXX}}
for other code points.
Existing
backslashes are not
escaped in any way.
It is used in the Python
pickle protocol.

@item

undefined

@tab

@tab

This Codec should only
be used for testing
purposes.

空文字列を含む全ての変換に対して例外を送出します。エラーハンドラは無視されます。

@item

unicode_escape

@tab

@tab

ASCII でエンコードされた Python ソースコード内の、Unicode リテラルに適したエンコーディングです。ただし、引用符はエスケープされません。Latin-1 ソースコードからデコードします。実際には、Python のソースコードはデフォルトでは UTF-8 を使用することに注意してください。

@end multitable



バージョン 3.8 で変更: "unicode_internal" codec is removed.


@node バイナリ変換 Binary Transforms,Standalone Codec Functions,テキストエンコーディング,Python 特有のエンコーディング
@anchor{library/codecs binary-transforms}@anchor{1106}@anchor{library/codecs id4}@anchor{287c}
@subsubsection バイナリ変換 (Binary Transforms)


以下の codec は、@ref{193,,bytes-like object} から @ref{192,,bytes} マッピングへのバイナリ変換を提供します。@ref{ad3,,bytes.decode()} はこの変換をサポートしておらず、 @ref{169,,str}  を出力するだけです。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Codec

@tab

別名

@tab

意味

@tab

エンコーダ / デコーダ

@item

base64_codec @footnote{
@ref{193,,バイト様オブジェクト} に加えて、@code{'base64_codec'} も @ref{169,,str} の ASCII のみのインスタンスをデコード用に受け入れるようになりました
}

@tab

base64, base_64

@tab

被演算子をマルチラインの MIME base64 に変換します (結果は常に末尾の @code{'\n'} を含みます)。


バージョン 3.4 で変更: 任意の @ref{193,,bytes-like object} をエンコードとデコード用の入力として受け取ります。


@tab

@ref{b4c,,base64.encodebytes()} /
@ref{b4d,,base64.decodebytes()}

@item

bz2_codec

@tab

bz2

@tab

被演算子をbz2を使って圧縮します。

@tab

@ref{287d,,bz2.compress()} /
@ref{12a0,,bz2.decompress()}

@item

hex_codec

@tab

hex

@tab

被演算子をバイトあたり 2 桁の 16 進数の表現に変換します。

@tab

@ref{287e,,binascii.b2a_hex()} /
@ref{287f,,binascii.a2b_hex()}

@item

quopri_codec

@tab

quopri,
quotedprintable,
quoted_printable

@tab

被演算子を MIME quoted printable 形式に変換します。

@tab

@code{quotetabs=True} を指定した @ref{2880,,quopri.encode()} / @ref{2881,,quopri.decode()}

@item

uu_codec

@tab

uu

@tab

被演算子を uuencode を用いて変換します。

@tab

@item

zlib_codec

@tab

zip, zlib

@tab

被演算子を gzip を用いて圧縮します。

@tab

@ref{84f,,zlib.compress()} /
@ref{f09,,zlib.decompress()}

@end multitable



Added in version 3.2: バイナリ変換が復活しました。(訳注: 2.x にはあったものが 3.0 で削除されていた。)



バージョン 3.4 で変更: バイナリ変換のエイリアスが復活しました。(訳注: 2.x にはあったエイリアス。3.2 でエイリアスは復活しなかった。)


@node Standalone Codec Functions,テキスト変換 Text Transforms,バイナリ変換 Binary Transforms,Python 特有のエンコーディング
@anchor{library/codecs id6}@anchor{2882}@anchor{library/codecs standalone-codec-functions}@anchor{2883}
@subsubsection Standalone Codec Functions


The following functions provide encoding and decoding functionality similar to codecs,
but are not available as named codecs through @ref{1104,,codecs.encode()} or @ref{1105,,codecs.decode()}.
They are used internally (for example, by @ref{ab,,pickle}) and behave similarly to the
@code{string_escape} codec that was removed in Python 3.

@geindex codecs.escape_encode() (codecs モジュール)
@anchor{library/codecs codecs codecs escape_encode}@anchor{2884}
@deffn {の関数} codecs.escape_encode (input, errors=None)

Encode `input' using escape sequences. Similar to how @ref{1c1,,repr()} on bytes
produces escaped byte values.

`input' must be a @ref{192,,bytes} object.

Returns a tuple @code{(output, length)} where `output' is a @ref{192,,bytes}
object and `length' is the number of bytes consumed.
@end deffn

@geindex codecs.escape_decode() (codecs モジュール)
@anchor{library/codecs codecs codecs escape_decode}@anchor{2885}
@deffn {の関数} codecs.escape_decode (input, errors=None)

Decode `input' from escape sequences back to the original bytes.

`input' must be a @ref{193,,bytes-like object}.

Returns a tuple @code{(output, length)} where `output' is a @ref{192,,bytes}
object and `length' is the number of bytes consumed.
@end deffn

@node テキスト変換 Text Transforms,,Standalone Codec Functions,Python 特有のエンコーディング
@anchor{library/codecs id7}@anchor{2886}@anchor{library/codecs text-transforms}@anchor{1107}
@subsubsection テキスト変換 (Text Transforms)


以下の codec は、@ref{169,,str} から @ref{169,,str} マッピングへのテキスト変換を提供します。@ref{ad2,,str.encode()} はこの変換をサポートしておらず、 @ref{192,,bytes}  を出力するだけです。


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Codec

@tab

別名

@tab

意味

@item

rot_13

@tab

rot13

@tab

被演算子のシーザー暗号 (Caesar-cypher) を返します。

@end multitable



Added in version 3.2: @code{rot_13} テキスト変換が復活しました。(訳注: 2.x にはあったものが 3.0 で削除されていた。)



バージョン 3.4 で変更: @code{rot13} エイリアスが復活しました。(訳注: 2.x にはあったエイリアス。3.2 でエイリアスは復活しなかった。)


@node encodings --- Encodings package,encodings idna --- Internationalized Domain Names in Applications,Python 特有のエンコーディング,codecs --- codec レジストリと基底クラス
@anchor{library/codecs encodings-encodings-package}@anchor{2887}@anchor{library/codecs module-encodings}@anchor{55}
@subsubsection @code{encodings} --- Encodings package


@geindex module; encodings

This module implements the following functions:

@geindex normalize_encoding() (encodings モジュール)
@anchor{library/codecs encodings normalize_encoding}@anchor{9fd}
@deffn {の関数} encodings.normalize_encoding (encoding)

Normalize encoding name `encoding'.

Normalization works as follows: all non-alphanumeric characters except the
dot used for Python package names are collapsed and replaced with a single
underscore, leading and trailing underscores are removed.
For example, @code{'  -;#'} becomes @code{'_'}.

Note that `encoding' should be ASCII only.
@end deffn

@cartouche
@quotation 注釈 
The following functions should not be used directly, except for testing
purposes; @ref{b5c,,codecs.lookup()} should be used instead.
@end quotation
@end cartouche

@geindex search_function() (encodings モジュール)
@anchor{library/codecs encodings search_function}@anchor{2888}
@deffn {の関数} encodings.search_function (encoding)

Search for the codec module corresponding to the given encoding name
`encoding'.

This function first normalizes the `encoding' using
@ref{9fd,,normalize_encoding()}, then looks for a corresponding alias.
It attempts to import a codec module from the encodings package using either
the alias or the normalized name. If the module is found and defines a valid
@code{getregentry()} function that returns a @ref{1a6c,,codecs.CodecInfo} object,
the codec is cached and returned.

If the codec module defines a @code{getaliases()} function any returned aliases
are registered for future use.
@end deffn

@geindex win32_code_page_search_function() (encodings モジュール)
@anchor{library/codecs encodings win32_code_page_search_function}@anchor{2889}
@deffn {の関数} encodings.win32_code_page_search_function (encoding)

Search for a Windows code page encoding `encoding' of the form @code{cpXXXX}.

If the code page is valid and supported, return a @ref{1a6c,,codecs.CodecInfo}
object for it.

@ref{213f,,Availability}: Windows.


Added in version 3.14.

@end deffn

This module implements the following exception:

@geindex CodecRegistryError
@anchor{library/codecs encodings CodecRegistryError}@anchor{288a}
@deffn {例外} encodings.CodecRegistryError

Raised when a codec is invalid or incompatible.
@end deffn

@node encodings idna --- Internationalized Domain Names in Applications,encodings mbcs --- Windows ANSI codepage,encodings --- Encodings package,codecs --- codec レジストリと基底クラス
@anchor{library/codecs encodings-idna-internationalized-domain-names-in-applications}@anchor{288b}@anchor{library/codecs module-encodings idna}@anchor{56}
@subsubsection @code{encodings.idna} --- Internationalized Domain Names in Applications


@geindex module; encodings.idna

このモジュールでは 
@geindex RFC; RFC 3490
RFC 3490@footnote{https://datatracker.ietf.org/doc/html/rfc3490.html} (アプリケーションにおける国際化ドメイン名、 IDNA: Internationalized Domain Names in Applications) および 
@geindex RFC; RFC 3492
RFC 3492@footnote{https://datatracker.ietf.org/doc/html/rfc3492.html} (Nameprep: 国際化ドメイン名 (IDN) のための stringprep プロファイル) を実装しています。このモジュールは @code{punycode} エンコーディングおよび @ref{da,,stringprep} の上に構築されています。

If you need the IDNA 2008 standard from 
@geindex RFC; RFC 5891
RFC 5891@footnote{https://datatracker.ietf.org/doc/html/rfc5891.html} and 
@geindex RFC; RFC 5895
RFC 5895@footnote{https://datatracker.ietf.org/doc/html/rfc5895.html}, use the
third-party idna@footnote{https://pypi.org/project/idna/} module.

これらの RFC はともに、非 ASCII 文字の入ったドメイン名をサポートするためのプロトコルを定義しています。 (@code{www.Alliancefrançaise.nu} のような) 非 ASCII 文字を含むドメイン名は、 ASCII と互換性のあるエンコーディング (ACE、 @code{www.xn--alliancefranaise-npb.nu} のような形式) に変換されます。ドメイン名の ACE 形式は、 DNS クエリ、 HTTP @code{Host} フィールドなどといった、プロトコル中で任意の文字を使えないような全ての局面で用いられます。この変換はアプリケーション内で行われます; 可能ならユーザからは不可視となります: アプリケーションは Unicode ドメインラベルをネットワークに載せる際に IDNA に、 ACE ドメインラベルをユーザに提供する前に Unicode に、それぞれ透過的に変換しなければなりません。

Python ではこの変換をいくつかの方法でサポートします: @code{idna} codec は Unicode と ACE 間の変換を行い、入力文字列を 
@geindex RFC; RFC 3490 Section 3.1
RFC 3490 の section 3.1@footnote{https://datatracker.ietf.org/doc/html/rfc3490.html#section-3.1} で定義されている区切り文字に基づいてラベルに分解し、各ラベルを要求通りに ACE に変換します。逆に、入力のバイト文字列を @code{.} 区切り文字でラベルに分解し、 ACE ラベルを Unicode に変換します。さらに、 @ref{d1,,socket} モジュールは Unicode ホスト名を ACE に透過的に変換するため、アプリケーションはホスト名を @ref{d1,,socket} モジュールに渡す際にホスト名の変換に煩わされることがありません。その上で、ホスト名を関数パラメタとして持つ、 @ref{73,,http.client} や @ref{62,,ftplib} のようなモジュールでは Unicode ホスト名を受理します (@ref{73,,http.client} でもまた、 @code{Host} フィールドにある IDNA ホスト名を、フィールド全体を送信する場合に透過的に送信します)。

(逆引きなどによって) ネットワーク越しにホスト名を受信する際、Unicode への自動変換は行われません: こうしたホスト名をユーザに提供したいアプリケーションでは、Unicode にデコードしてやる必要があります。

The module @code{encodings.idna} also implements the nameprep procedure, which
performs certain normalizations on host names, to achieve case-insensitivity of
international domain names, and to unify similar characters. The nameprep
functions can be used directly if desired.

@geindex nameprep() (encodings.idna モジュール)
@anchor{library/codecs encodings idna nameprep}@anchor{288c}
@deffn {の関数} encodings.idna.nameprep (label)

`label' を nameprep したバージョンを返します。現在の実装ではクエリ文字列を仮定しているので、@code{AllowUnassigned} は真です。
@end deffn

@geindex ToASCII() (encodings.idna モジュール)
@anchor{library/codecs encodings idna ToASCII}@anchor{288d}
@deffn {の関数} encodings.idna.ToASCII (label)

@geindex RFC; RFC 3490
RFC 3490@footnote{https://datatracker.ietf.org/doc/html/rfc3490.html} 仕様に従ってラベルを ASCIIに変換します。 @code{UseSTD3ASCIIRules} は偽であると仮定します。
@end deffn

@geindex ToUnicode() (encodings.idna モジュール)
@anchor{library/codecs encodings idna ToUnicode}@anchor{288e}
@deffn {の関数} encodings.idna.ToUnicode (label)

@geindex RFC; RFC 3490
RFC 3490@footnote{https://datatracker.ietf.org/doc/html/rfc3490.html} 仕様に従ってラベルを Unicode に変換します。
@end deffn

@node encodings mbcs --- Windows ANSI codepage,encodings utf_8_sig --- UTF-8 codec with BOM signature,encodings idna --- Internationalized Domain Names in Applications,codecs --- codec レジストリと基底クラス
@anchor{library/codecs encodings-mbcs-windows-ansi-codepage}@anchor{288f}@anchor{library/codecs module-encodings mbcs}@anchor{57}
@subsubsection @code{encodings.mbcs} --- Windows ANSI codepage


@geindex module; encodings.mbcs

This module implements the ANSI codepage (CP_ACP).

@ref{213f,,Availability}: Windows.


バージョン 3.2 で変更: 3.2 以前は `errors' 引数は無視されました; エンコードには常に @code{'replace'} が、デコードには @code{'ignore'} が使われました。



バージョン 3.3 で変更: 任意のエラーハンドラのサポート。


@node encodings utf_8_sig --- UTF-8 codec with BOM signature,,encodings mbcs --- Windows ANSI codepage,codecs --- codec レジストリと基底クラス
@anchor{library/codecs encodings-utf-8-sig-utf-8-codec-with-bom-signature}@anchor{2890}@anchor{library/codecs module-encodings utf_8_sig}@anchor{58}
@subsubsection @code{encodings.utf_8_sig} --- UTF-8 codec with BOM signature


@geindex module; encodings.utf_8_sig

このモジュールは UTF-8 codec の変種を実装します。エンコーディング時は、UTF-8 でエンコードしたバイト列の前に UTF-8 でエンコードした BOM を追加します。これは内部状態を持つエンコーダで、この動作は (バイトストリームの最初の書き込み時に) 一度だけ行なわれます。デコーディング時は、データの最初に UTF-8 でエンコードされた BOM があれば、それをスキップします。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node データ型,数値と数学モジュール,バイナリデータ処理,Python 標準ライブラリ
@anchor{library/datatypes doc}@anchor{2891}@anchor{library/datatypes data-types}@anchor{2892}@anchor{library/datatypes datatypes}@anchor{2893}@anchor{library/datatypes translation-repo}@anchor{2894}
@section データ型


この章で解説されるモジュールは日付や時間、型が固定された配列、ヒープキュー、両端キュー、列挙型のような種々の特殊なデータ型を提供します。

Python にはその他にもいくつかの組み込みデータ型があります。特に、 @ref{183,,dict} 、 @ref{24d,,list} 、 @ref{184,,set} 、 @ref{7f2,,frozenset} 、そして @ref{614,,tuple} があります。 @ref{169,,str} クラスは Unicode データを扱うことができ、 @ref{192,,bytes} と @ref{344,,bytearray} クラスはバイナリデータを扱うことができます。

この章では以下のモジュールが記述されています:

@menu
* datetime: datetime --- 基本的な日付と時間の型. 基本的な日付と時間の型
* zoneinfo: zoneinfo --- IANA タイムゾーンのサポート. IANA タイムゾーンのサポート
* calendar: calendar --- 一般的なカレンダーに関係する機能群. 一般的なカレンダーに関係する機能群
* collections: collections --- コンテナデータ型. コンテナデータ型
* collections.abc: collections abc --- コンテナの抽象基底クラス. コンテナの抽象基底クラス
* heapq: heapq --- ヒープキューアルゴリズム. ヒープキューアルゴリズム
* bisect: bisect --- 配列二分法アルゴリズム. 配列二分法アルゴリズム
* array: array --- 効率的な数値配列. 効率的な数値配列
* weakref: weakref --- Weak references. Weak references
* types: types --- 動的な型生成と組み込み型の名前. 動的な型生成と組み込み型の名前
* copy: copy --- 浅いコピーおよび深いコピー操作. 浅いコピーおよび深いコピー操作
* pprint: pprint --- データの整形表示. データの整形表示
* reprlib: reprlib --- もう一つの repr の実装. もう一つの repr() の実装
* enum: enum --- 列挙型のサポート. 列挙型のサポート
* graphlib: graphlib --- グラフ構造を操作する機能. グラフ構造を操作する機能

@end menu

@node datetime --- 基本的な日付と時間の型,zoneinfo --- IANA タイムゾーンのサポート,,データ型
@anchor{library/datetime doc}@anchor{2895}@anchor{library/datetime datetime-basic-date-and-time-types}@anchor{2896}@anchor{library/datetime module-datetime}@anchor{34}
@subsection @code{datetime} --- 基本的な日付と時間の型


@geindex module; datetime

`ソースコード:' Lib/datetime.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/datetime.py}


__________________________________________________________________


@code{datetime} モジュールは、日付や時刻を操作するためのクラスを提供しています。

日付や時刻に対する算術がサポートされている一方、実装では出力のフォーマットや操作のための効率的な属性の抽出に重点を置いています。

@cartouche
@quotation Tip 
@ref{2897,,書式コード} に飛ぶ。
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@item @ref{15,,calendar} モジュール

汎用のカレンダー関連関数。

@item @ref{f4,,time} モジュール

時刻へのアクセスと変換。

@item @ref{13a,,zoneinfo} モジュール

IANAタイムゾーンデータベースを表す具体的なタイムゾーン。

@item dateutil@footnote{https://dateutil.readthedocs.io/en/stable/} パッケージ

拡張タイムゾーンと構文解析サポートのあるサードパーティーライブラリ。

@item DateType@footnote{https://pypi.org/project/DateType/} パッケージ

Third-party library that introduces distinct static types to for example,
allow @ref{574,,static type checkers}
to differentiate between naive and aware datetimes.
@end table


@menu
* Aware and naive objects:: 
* 定数:: 
* Available types:: 
* timedelta objects:: 
* date objects:: 
* datetime objects:: 
* time objects:: 
* tzinfo objects:: 
* timezone objects:: 
* strftime() and strptime() behavior: strftime and strptime behavior. 

@end menu

@node Aware and naive objects,定数,,datetime --- 基本的な日付と時間の型
@anchor{library/datetime aware-and-naive-objects}@anchor{2898}@anchor{library/datetime datetime-naive-aware}@anchor{2899}
@subsubsection Aware and naive objects


日時のオブジェクトは、それらがタイムゾーンの情報を含んでいるかどうかによって "aware" あるいは "naive" に分類されます。

タイムゾーンや夏時間の情報のような、アルゴリズム的で政治的な適用可能な時間調節に関する知識を持っているため、 `aware' オブジェクトは他の aware オブジェクトとの相対関係を特定できます。
aware オブジェクトは解釈の余地のない特定の実時刻を表現します。 @footnote{
もし相対性理論の効果を無視するならば、ですが
}

`naive' オブジェクトには他の日付時刻オブジェクトとの相対関係を把握するのに足る情報が含まれません。あるプログラム内の数字がメートルを表わしているのか、マイルなのか、それとも質量なのかがプログラムによって異なるように、naive オブジェクトが協定世界時 (UTC) なのか、現地時間なのか、それとも他のタイムゾーンなのかはそのプログラムに依存します。Naive オブジェクトはいくつかの現実的な側面を無視してしまうというコストを無視すれば、簡単に理解でき、うまく利用することができます。

aware オブジェクトを必要とするアプリケーションのために、 @ref{4e2,,datetime} と @ref{1fb,,time} オブジェクトは追加のタイムゾーン情報の属性 @code{tzinfo} を持ちます。
@ref{7f6,,tzinfo} には抽象クラス @ref{7f6,,tzinfo} のサブクラスのインスタンスを設定できます。
これらの @ref{7f6,,tzinfo} オブジェクトは UTC 時間からのオフセットやタイムゾーンの名前、夏時間が実施されるかどうかの情報を保持しています。

ただ一つの具象 @ref{7f6,,tzinfo} クラスである @ref{12d5,,timezone} クラスが @code{datetime} モジュールで提供されています。 @code{timezone} クラスは、UTCからのオフセットが固定である単純なタイムゾーン（例えばUTCそれ自体）、および北アメリカにおける東部標準時（EST）／東部夏時間（EDT）のような単純ではないタイムゾーンの両方を表現できます。より深く詳細までタイムゾーンをサポートするかはアプリケーションに依存します。世界中の時刻の調整を決めるルールは合理的というよりかは政治的なもので、頻繁に変わり、UTC を除くと都合のよい基準というものはありません。

@node 定数,Available types,Aware and naive objects,datetime --- 基本的な日付と時間の型
@anchor{library/datetime constants}@anchor{289a}
@subsubsection 定数


@code{datetime} モジュールでは以下の定数を公開しています:

@geindex MINYEAR (datetime モジュール)
@anchor{library/datetime datetime MINYEAR}@anchor{289b}
@deffn {データ} datetime.MINYEAR

@ref{1fa,,date} や @ref{4e2,,datetime} オブジェクトで許されている、年を表現する最小の数字です。 @ref{289b,,MINYEAR} は1です。
@end deffn

@geindex MAXYEAR (datetime モジュール)
@anchor{library/datetime datetime MAXYEAR}@anchor{289c}
@deffn {データ} datetime.MAXYEAR

@ref{1fa,,date} や @ref{4e2,,datetime} オブジェクトで許されている、年を表現する最大の数字です。 @ref{289c,,MAXYEAR} は9999です。
@end deffn

@geindex UTC (datetime モジュール)
@anchor{library/datetime datetime UTC}@anchor{713}
@deffn {データ} datetime.UTC

UTCタイムゾーンシングルトン @ref{827,,datetime.timezone.utc} の別名。


Added in version 3.11.

@end deffn

@node Available types,timedelta objects,定数,datetime --- 基本的な日付と時間の型
@anchor{library/datetime available-types}@anchor{289d}
@subsubsection Available types



@deffn {クラス} datetime.date

理想的な naive な日付で、これまでもこれからも現在のグレゴリオ暦 (Gregorian calender) が有効であることを仮定しています。
属性は @ref{289e,,year}, @ref{289f,,month},および @ref{28a0,,day} です。
@end deffn


@deffn {クラス} datetime.time

理想的な時刻で、特定の日から独立しており、毎日が厳密に 24*60*60 秒であると仮定しています。("うるう秒: leap seconds" の概念はありません。)
属性は @ref{28a1,,hour}, @ref{28a2,,minute}, @ref{28a3,,second}, @ref{28a4,,microsecond}, および @ref{28a5,,tzinfo} です。
@end deffn


@deffn {クラス} datetime.datetime

日付と時刻を組み合わせたものです。
属性は @ref{28a6,,year}, @ref{28a7,,month}, @ref{28a8,,day}, @ref{28a9,,hour}, @ref{28aa,,minute}, @ref{28ab,,second}, @ref{28ac,,microsecond}, および @ref{28ad,,tzinfo} です。
@end deffn


@deffn {クラス} datetime.timedelta

@ref{4e2,,datetime} あるいは @ref{1fa,,date} クラスの二つのインスタンス間の時間差をマイクロ秒精度で表す経過時間値です。
@end deffn


@deffn {クラス} datetime.tzinfo

タイムゾーン情報オブジェクトの抽象基底クラスです。
@ref{4e2,,datetime} および @ref{1fb,,time} クラスで用いられ、カスタマイズ可能な時刻修正の概念 (たとえばタイムゾーンや夏時間の計算) を提供します。
@end deffn


@deffn {クラス} datetime.timezone

@ref{7f6,,tzinfo} 抽象基底クラスを UTC からの固定オフセットとして実装するクラスです。


Added in version 3.2.

@end deffn

これらの型のオブジェクトは変更不可能 (immutable) です。

Subclass relationships:


@float Figure

@image{python-figures/datetime-inheritance,,,timedelta@comma{} tzinfo@comma{} time@comma{} and date inherit from object; timezone inherits from tzinfo; and datetime inherits from date.,svg}

@end float


@menu
* Common properties:: 
* Determining if an object is aware or naive:: 

@end menu

@node Common properties,Determining if an object is aware or naive,,Available types
@anchor{library/datetime common-properties}@anchor{28ae}
@subsubsection Common properties


@ref{1fa,,date} 型、@ref{4e2,,datetime} 型、@ref{1fb,,time} 型、@ref{12d5,,timezone} 型には共通する特徴があります:


@itemize -

@item 
これらの型のオブジェクトは変更不可能 (immutable) です。

@item 
これらの型のオブジェクトは @ref{824,,ハッシュ可能} であり、辞書のキーとして使えることになります。

@item 
これらの型のオブジェクトは @ref{ab,,pickle} モジュールを利用して効率的な pickle 化をサポートしています。
@end itemize

@node Determining if an object is aware or naive,,Common properties,Available types
@anchor{library/datetime determining-if-an-object-is-aware-or-naive}@anchor{28af}
@subsubsection Determining if an object is aware or naive


@ref{1fa,,date} 型のオブジェクトは常に naive です。

@ref{1fb,,time} 型あるいは @ref{4e2,,datetime} 型のオブジェクトは aware か naive のどちらかです。

次の条件を両方とも満たす場合、 @ref{4e2,,datetime} オブジェクト @code{d} は aware です:


@enumerate 

@item 
@code{d.tzinfo} が @code{None} でない

@item 
@code{d.tzinfo.utcoffset(d)} が @code{None} を返さない
@end enumerate

どちらかを満たさない場合は、 @code{d} は naive です。

次の条件を両方とも満たす場合、 @ref{1fb,,time} オブジェクト @code{t} は aware です:


@enumerate 

@item 
@code{t.tzinfo} が @code{None} でない

@item 
@code{t.tzinfo.utcoffset(None)} が @code{None} を返さない
@end enumerate

どちらかを満たさない場合は、 @code{t} は naive です。

aware なオブジェクトと naive なオブジェクトの区別は @ref{bc3,,timedelta} オブジェクトにはあてはまりません。

@node timedelta objects,date objects,Available types,datetime --- 基本的な日付と時間の型
@anchor{library/datetime datetime-timedelta}@anchor{28b0}@anchor{library/datetime timedelta-objects}@anchor{28b1}
@subsubsection @code{timedelta} objects


@ref{bc3,,timedelta} オブジェクトは経過時間、すなわち二つの @ref{4e2,,datetime} または @ref{1fa,,date} のインスタンスの差を表します。

@geindex timedelta (datetime のクラス)
@anchor{library/datetime datetime timedelta}@anchor{bc3}
@deffn {クラス} datetime.timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

全ての引数がオプションで、デフォルト値は0です。
引数は整数、浮動小数点数でもよく、正でも負でもかまいません。

`days', `seconds', `microseconds' だけが内部的に保持されます。
引数は以下のようにして変換されます:


@itemize *

@item 
1 ミリ秒は 1000 マイクロ秒に変換されます。

@item 
1 分は 60 秒に変換されます。

@item 
1 時間は 3600 秒に変換されます。

@item 
1 週間は 7 日に変換されます。
@end itemize

さらに、値が一意に表されるように days, seconds, microseconds が以下のように正規化されます


@itemize *

@item 
@code{0 <= microseconds < 1000000}

@item 
@code{0 <= seconds < 3600*24} (一日中の秒数)

@item 
@code{-999999999 <= days <= 999999999}
@end itemize

次の例は、 `days', `seconds', `microseconds' に加えて任意の引数がどう "集約" され、最終的に3つの属性に正規化されるかの説明をしています:

@example
>>> from datetime import timedelta
>>> delta = timedelta(
...     days=50,
...     seconds=27,
...     microseconds=10,
...     milliseconds=29000,
...     minutes=5,
...     hours=8,
...     weeks=2
... )
>>> # Only days, seconds, and microseconds remain
>>> delta
datetime.timedelta(days=64, seconds=29156, microseconds=10)
@end example

引数のいずれかが浮動小数点であり、小数のマイクロ秒が存在する場合、小数のマイクロ秒は全ての引数から一度取り置かれ、それらの和は最近接偶数のマイクロ秒に丸められます。浮動小数点の引数がない場合、値の変換と正規化の過程は厳密な (失われる情報がない) ものとなります。

日の値を正規化した結果、指定された範囲の外側になった場合には、 @ref{a81,,OverflowError} が送出されます。

負の値を正規化すると、最初は混乱するような値になります。例えば:

@example
>>> from datetime import timedelta
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
@end example

Since the string representation of @code{timedelta} objects can be confusing,
use the following recipe to produce a more readable format:

@example
>>> def pretty_timedelta(td):
...     if td.days >= 0:
...         return str(td)
...     return f'-(@{-td!s@})'
...
>>> d = timedelta(hours=-1)
>>> str(d)  # not human-friendly
'-1 day, 23:00:00'
>>> pretty_timedelta(d)
'-(1:00:00)'
@end example
@end deffn

以下にクラス属性を示します:

@geindex min (datetime.timedelta の属性)
@anchor{library/datetime datetime timedelta min}@anchor{28b2}
@deffn {の属性} timedelta.min

最小の値を表す @ref{bc3,,timedelta} オブジェクトで、 @code{timedelta(-999999999)} です。
@end deffn

@geindex max (datetime.timedelta の属性)
@anchor{library/datetime datetime timedelta max}@anchor{28b3}
@deffn {の属性} timedelta.max

最大の値を表す @ref{bc3,,timedelta} オブジェクトで、 @code{timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)} です。
@end deffn

@geindex resolution (datetime.timedelta の属性)
@anchor{library/datetime datetime timedelta resolution}@anchor{28b4}
@deffn {の属性} timedelta.resolution

@ref{bc3,,timedelta} オブジェクトが等しくならない最小の時間差で、 @code{timedelta(microseconds=1)} です。
@end deffn

正規化のために、 @code{timedelta.max} は @code{-timedelta.min} より大きいことに注意してください。 @code{-timedelta.max} は @ref{bc3,,timedelta} オブジェクトとして表現することができません。

インスタンスの属性 (読み出しのみ):

@geindex days (datetime.timedelta の属性)
@anchor{library/datetime datetime timedelta days}@anchor{28b5}
@deffn {の属性} timedelta.days

両端値を含む-999,999,999 から 999,999,999 の間
@end deffn

@geindex seconds (datetime.timedelta の属性)
@anchor{library/datetime datetime timedelta seconds}@anchor{28b6}
@deffn {の属性} timedelta.seconds

両端値を含む 0 から 86,399 の間

@cartouche
@quotation 注意 
It is a somewhat common bug for code to unintentionally use this attribute
when it is actually intended to get a @ref{151d,,total_seconds()}
value instead:

@example
>>> from datetime import timedelta
>>> duration = timedelta(seconds=11235813)
>>> duration.days, duration.seconds
(130, 3813)
>>> duration.total_seconds()
11235813.0
@end example
@end quotation
@end cartouche
@end deffn

@geindex microseconds (datetime.timedelta の属性)
@anchor{library/datetime datetime timedelta microseconds}@anchor{28b7}
@deffn {の属性} timedelta.microseconds

両端値を含む 0 から 999,999 の間
@end deffn

サポートされている演算を以下に示します:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@item

@code{t1 = t2 + t3}

@tab

@code{t2} と @code{t3} の和。演算後、@code{t1 - t2 == t3} および @code{t1 - t3 == t2} は真になります。(1)

@item

@code{t1 = t2 - t3}

@tab

@code{t2} と @code{t3} の差。演算後、@code{t1 == t2 - t3} および @code{t2 == t1 + t3} は真になります。 (1)(6)

@item

@code{t1 = t2 * i または t1 = i * t2}

@tab

時間差と整数の積。演算後、@code{t1 // i == t2} は @code{i != 0} であれば真となります。

@item

@tab

一般的に、@code{t1 * i == t1 * (i-1) + t1} は真となります。(1)

@item

@code{t1 = t2 * f} または @code{t1 = f * t2}

@tab

時間差と浮動小数点の積。結果は最近接偶数への丸めを利用して最も近い timedelta.resolution の倍数に丸められます。

@item

@code{f = t2 / t3}

@tab

@code{t2} を @code{t3} で除算 (3) したもの。@ref{196,,float} オブジェクトを返します。

@item

@code{t1 = t2 / f} または @code{t1 = t2 / i}

@tab

時間差を浮動小数点や整数で除したもの。結果は最近接偶数への丸めを利用して最も近い timedelta.resolution の倍数に丸められます。

@item

@code{t1 = t2 // i} または @code{t1 = t2 // t3}

@tab

floor が計算され、余りは (もしあれば) 捨てられます。後者の場合、整数が返されます。(3)

@item

@code{t1 = t2 % t3}

@tab

剰余が @ref{bc3,,timedelta} オブジェクトとして計算されます。(3)

@item

@code{q, r = divmod(t1, t2)}

@tab

商と剰余が計算されます: @code{q = t1 // t2} (3) と @code{r = t1 % t2} 。@code{q} は整数で @code{r} は @ref{bc3,,timedelta} オブジェクトです。

@item

@code{+t1}

@tab

同じ値を持つ @ref{bc3,,timedelta} オブジェクトを返します。(2)

@item

@code{-t1}

@tab

@code{timedelta(-t1.days, -t1.seconds, -t1.microseconds)}、および @code{t1 * -1} と同じです。 (1)(4)

@item

@code{abs(t)}

@tab

@code{t.days >= 0} のときには @code{+t}, @code{t.days < 0} のときには @code{-t} となります。(2)

@item

@code{str(t)}

@tab

@code{[D day[s], ][H]H:MM:SS[.UUUUUU]} という形式の文字列を返します。@code{t} が負の値の場合は @code{D} は負の値となります。(5)

@item

@code{repr(t)}

@tab

@ref{bc3,,timedelta} オブジェクトの文字列表現を返します。その文字列は、正規の属性値を持つコンストラクタ呼び出しのコードになっています。

@end multitable


注釈:


@enumerate 

@item 
この演算は正確ですが、オーバフローするかもしれません。

@item 
この演算は正確であり、オーバフローし得ません。

@item 
0 による除算は @ref{b3f,,ZeroDivisionError} を送出します。

@item 
@code{-timedelta.max} は @ref{bc3,,timedelta} オブジェクトで表現することができません。

@item 
@ref{bc3,,timedelta} オブジェクトの文字列表現は内部表現に類似した形に正規化されます。そのため負の timedelta は少し変な結果になります。例えば:

@example
>>> timedelta(hours=-5)
datetime.timedelta(days=-1, seconds=68400)
>>> print(_)
-1 day, 19:00:00
@end example

@item 
t3 が @code{timedelta.max} のときを除けば、式 @code{t2 - t3} は常に、式 @code{t2 + (-t3)} と同等です。t3 が @code{timedelta.max} の場合、前者の式は結果の値が出ますが、後者はオーバーフローを起こします。
@end enumerate

上に列挙した操作に加え @ref{bc3,,timedelta} オブジェクトは @ref{1fa,,date} および @ref{4e2,,datetime} オブジェクトとの間で加減算をサポートしています (下を参照してください)。


バージョン 3.2 で変更: @ref{bc3,,timedelta} オブジェクトの別の @ref{bc3,,timedelta} オブジェクトによる、切り捨て除算と真の除算、および剰余演算と @ref{b99,,divmod()} 関数がサポートされるようになりました。 @ref{bc3,,timedelta} オブジェクトと @ref{196,,float} オブジェクトの真の除算と掛け算がサポートされるようになりました。


@ref{bc3,,timedelta} オブジェクトは等価性と順序の比較をサポートします。

ブール演算コンテキストでは、 @ref{bc3,,timedelta} オブジェクトは @code{timedelta(0)} に等しくない場合かつそのときに限り真となります。

インスタンスメソッド:

@geindex total_seconds() (datetime.timedelta のメソッド)
@anchor{library/datetime datetime timedelta total_seconds}@anchor{151d}
@deffn {メソッド} timedelta.total_seconds ()

Return the total number of seconds contained in the duration. Equivalent to
@code{td / timedelta(seconds=1)}. For interval units other than seconds, use the
division form directly (for example, @code{td / timedelta(microseconds=1)}).

非常に長い期間 (多くのプラットフォームでは270年以上) については、このメソッドはマイクロ秒の精度を失うことがあることに注意してください。


Added in version 3.2.

@end deffn

@menu
* Examples of usage; timedelta: Examples of usage timedelta. 

@end menu

@node Examples of usage timedelta,,,timedelta objects
@anchor{library/datetime examples-of-usage-timedelta}@anchor{28b8}
@subsubsection Examples of usage: @code{timedelta}


正規化の追加の例です:

@example
>>> # Components of another_year add up to exactly 365 days
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
...                          minutes=50, seconds=600)
>>> year == another_year
True
>>> year.total_seconds()
31536000.0
@end example

@ref{bc3,,timedelta} の計算の例です:

@example
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> ten_years = 10 * year
>>> ten_years
datetime.timedelta(days=3650)
>>> ten_years.days // 365
10
>>> nine_years = ten_years - year
>>> nine_years
datetime.timedelta(days=3285)
>>> three_years = nine_years // 3
>>> three_years, three_years.days // 365
(datetime.timedelta(days=1095), 3)
@end example

@node date objects,datetime objects,timedelta objects,datetime --- 基本的な日付と時間の型
@anchor{library/datetime date-objects}@anchor{28b9}@anchor{library/datetime datetime-date}@anchor{28ba}
@subsubsection @code{date} objects


@ref{1fa,,date} オブジェクトは、両方向に無期限に拡張された現在のグレゴリオ暦という理想化された暦の日付 (年月日) を表します。

1 年 1 月 1 日は日番号 1、1 年 1 月 2 日は日番号 2 と呼ばれ、他も同様です。 @footnote{
この暦法は、全ての計算における基本カレンダーである、 Dershowitz と Reingold の書籍 `Calendrical Calculations' における先発グレゴリオ暦 ("proleptic Gregorian") の定義に一致します。
先発グレゴリオ暦の序数とその他多くの暦法どうしの変換アルゴリズムについては、この書籍を参照してください。
}

@geindex date (datetime のクラス)
@anchor{library/datetime datetime date}@anchor{1fa}
@deffn {クラス} datetime.date (year, month, day)

全ての引数が必須です。
引数は整数で、次の範囲に収まっていなければなりません:


@itemize *

@item 
@code{MINYEAR <= year <= MAXYEAR}

@item 
@code{1 <= month <= 12}

@item 
@code{1 <= day <= 指定された月と年における日数}
@end itemize

範囲を超えた引数を与えた場合、 @ref{2ec,,ValueError} が送出されます。
@end deffn

他のコンストラクタ、および全てのクラスメソッドを以下に示します:

@geindex today() (datetime.date のクラスメソッド)
@anchor{library/datetime datetime date today}@anchor{16e3}
@deffn {メソッド} classmethod date.today ()

現在のローカルな日付を返します。

@code{date.fromtimestamp(time.time())} と等価です。
@end deffn

@geindex fromtimestamp() (datetime.date のクラスメソッド)
@anchor{library/datetime datetime date fromtimestamp}@anchor{dcd}
@deffn {メソッド} classmethod date.fromtimestamp (timestamp)

Return the local date corresponding to the POSIX `timestamp', such as is
returned by @ref{55d,,time.time()}.

timestamp がプラットフォームの C 関数 @code{localtime()} がサポートする値の範囲から外れていた場合、 @ref{a81,,OverflowError} を送出するかもしれません。また @code{localtime()} 呼び出しが失敗した場合には @ref{2c0,,OSError} を送出するかもしれません。この範囲は通常は 1970 年から 2038 年までに制限されています。タイムスタンプの表記にうるう秒を含める非 POSIX なシステムでは、うるう秒は @ref{dcd,,fromtimestamp()} では無視されます。


バージョン 3.3 で変更: timestamp がプラットフォームの C 関数 @code{localtime()} のサポートする値の範囲から外れていた場合、 @ref{2ec,,ValueError} ではなく @ref{a81,,OverflowError} を送出するようになりました。 @code{localtime()} の呼び出し失敗で @ref{2ec,,ValueError} ではなく @ref{2c0,,OSError} を送出するようになりました。

@end deffn

@geindex fromordinal() (datetime.date のクラスメソッド)
@anchor{library/datetime datetime date fromordinal}@anchor{dcc}
@deffn {メソッド} classmethod date.fromordinal (ordinal)

Return the date corresponding to the proleptic Gregorian `ordinal', where
January 1 of year 1 has ordinal 1.

@code{1 <= ordinal <= date.max.toordinal()} でない場合、 @ref{2ec,,ValueError} が送出されます。
任意の日付 @code{d} に対し、 @code{date.fromordinal(d.toordinal()) == d} となります。
@end deffn

@geindex fromisoformat() (datetime.date のクラスメソッド)
@anchor{library/datetime datetime date fromisoformat}@anchor{828}
@deffn {メソッド} classmethod date.fromisoformat (date_string)

以下の例外を除く、有効な ISO 8601 フォーマットで与えられた `date_string' に対応する @ref{1fa,,date} を返します :


@enumerate 

@item 
精度の低い日付は現在サポートされていません(@code{YYYY-MM}, @code{YYYY})。

@item 
拡張された日付表現は現在サポートされていません(@code{±YYYYYY-MM-DD})。

@item 
序数の日付は現在サポートされていません(@code{YYYY-OOO})。
@end enumerate

例:

@example
>>> from datetime import date
>>> date.fromisoformat('2019-12-04')
datetime.date(2019, 12, 4)
>>> date.fromisoformat('20191204')
datetime.date(2019, 12, 4)
>>> date.fromisoformat('2021-W01-1')
datetime.date(2021, 1, 4)
@end example


Added in version 3.7.



バージョン 3.11 で変更: 以前はこのメソッドは @code{YYYY-MM-DD} フォーマットのみをサポートしていました。

@end deffn

@geindex fromisocalendar() (datetime.date のクラスメソッド)
@anchor{library/datetime datetime date fromisocalendar}@anchor{bdf}
@deffn {メソッド} classmethod date.fromisocalendar (year, week, day)

Return a @ref{1fa,,date} corresponding to the ISO calendar date specified by
`year', `week' and `day'. This is the inverse of the function @ref{af1,,date.isocalendar()}.


Added in version 3.8.

@end deffn

@geindex strptime() (datetime.date のクラスメソッド)
@anchor{library/datetime datetime date strptime}@anchor{1f9}
@deffn {メソッド} classmethod date.strptime (date_string, format)

Return a @ref{1fa,,date} corresponding to `date_string', parsed according to
`format'. This is equivalent to:

@example
date(*(time.strptime(date_string, format)[0:3]))
@end example

date_string と format が @ref{1646,,time.strptime()} で構文解析できない場合や、この関数が時刻タプルを返してこない場合には @ref{2ec,,ValueError} を送出します。@ref{1b54,,strftime() and strptime() behavior} および @ref{828,,date.fromisoformat()} も参照してください。

@cartouche
@quotation 注釈 
If `format' specifies a day of month without a year a
@ref{1a3,,DeprecationWarning} is emitted.  This is to avoid a quadrennial
leap year bug in code seeking to parse only a month and day as the
default year used in absence of one in the format is not a leap year.
Such `format' values may raise an error as of Python 3.15.  The
workaround is to always include a year in your `format'.  If parsing
`date_string' values that do not have a year, explicitly add a year that
is a leap year before parsing:

@example
>>> from datetime import date
>>> date_string = "02/29"
>>> when = date.strptime(f"@{date_string@};1984", "%m/%d;%Y")  # Avoids leap year bug.
>>> when.strftime("%B %d")
'February 29'
@end example
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

以下にクラス属性を示します:

@geindex min (datetime.date の属性)
@anchor{library/datetime datetime date min}@anchor{28bb}
@deffn {の属性} date.min

表現できる最も古い日付で、@code{date(MINYEAR, 1, 1)} です。
@end deffn

@geindex max (datetime.date の属性)
@anchor{library/datetime datetime date max}@anchor{28bc}
@deffn {の属性} date.max

表現できる最も新しい日付で、@code{date(MAXYEAR, 12, 31)} です。
@end deffn

@geindex resolution (datetime.date の属性)
@anchor{library/datetime datetime date resolution}@anchor{28bd}
@deffn {の属性} date.resolution

等しくない日付オブジェクト間の最小の差で、@code{timedelta(days=1)} です。
@end deffn

インスタンスの属性 (読み出しのみ):

@geindex year (datetime.date の属性)
@anchor{library/datetime datetime date year}@anchor{289e}
@deffn {の属性} date.year

両端値を含む @ref{289b,,MINYEAR} から @ref{289c,,MAXYEAR} までの値です。
@end deffn

@geindex month (datetime.date の属性)
@anchor{library/datetime datetime date month}@anchor{289f}
@deffn {の属性} date.month

両端値を含む 1 から 12 までの値です。
@end deffn

@geindex day (datetime.date の属性)
@anchor{library/datetime datetime date day}@anchor{28a0}
@deffn {の属性} date.day

1 から与えられた月と年における日数までの値です。
@end deffn

サポートされている演算を以下に示します:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@item

@code{date2 = date1 + timedelta}

@tab

@code{date2} は @code{date1} の @code{timedelta.days} 日後になります。(1)

@item

@code{date2 = date1 - timedelta}

@tab

@code{date2 + timedelta == date1} であるような日付 @code{date2} を計算します。(2)

@item

@code{timedelta = date1 - date2}

@tab

(3)

@item


@display
@code{date1 == date2}@w{ }
@code{date1 != date2}@w{ }
@end display



@tab

等価性の比較。(4)

@item


@display
@code{date1 < date2}@w{ }
@code{date1 > date2}@w{ }
@code{date1 <= date2}@w{ }
@code{date1 >= date2}@w{ }
@end display



@tab

順序の比較。(5)

@end multitable


注釈:


@enumerate 

@item 
`date2' は、 @code{timedelta.days > 0} の場合は進む方向に、 @code{timedelta.days < 0} の場合は戻る方向に移動します。
演算後は @code{date2 - date1 == timedelta.days} が成立します。
@code{timedelta.seconds} および @code{timedelta.microseconds} は無視されます。
@code{date2.year} が @ref{289b,,MINYEAR} になってしまったり、 @ref{289c,,MAXYEAR} より大きくなってしまう場合には @ref{a81,,OverflowError} が送出されます。

@item 
@code{timedelta.seconds} と @code{timedelta.microseconds} は無視されます。

@item 
この演算は厳密で、オーバフローしません。@code{timedelta.seconds} および @code{timedelta.microseconds} は 0 で、演算後には @code{date2 + timedelta == date1} となります。

@item 
同じ日を表す @ref{1fa,,date} オブジェクトは等しいです。

@ref{4e2,,datetime} のインスタンスではない @code{date} オブジェクトは、同じ日を表していても、@code{datetime} オブジェクトとは決して等価にはなりません。

@item 
`date1' is considered less than `date2' when `date1' precedes `date2' in time.
In other words, @code{date1 < date2} if and only if @code{date1.toordinal() <
date2.toordinal()}.

Order comparison between a @code{date} object that is not also a
@ref{4e2,,datetime} instance and a @code{datetime} object raises
@ref{198,,TypeError}.
@end enumerate


バージョン 3.13 で変更: Comparison between @ref{4e2,,datetime} object and an instance of
the @ref{1fa,,date} subclass that is not a @code{datetime} subclass
no longer converts the latter to @code{date}, ignoring the time part
and the time zone.
The default behavior can be changed by overriding the special comparison
methods in subclasses.


ブール演算コンテキストでは、全ての @ref{1fb,,time} オブジェクトは真とみなされます。

インスタンスメソッド:

@geindex replace() (datetime.date のメソッド)
@anchor{library/datetime datetime date replace}@anchor{19f9}
@deffn {メソッド} date.replace (year=self.year, month=self.month, day=self.day)

Return a new @ref{1fa,,date} object with the same values, but with specified
parameters updated.

以下はプログラム例です:

@example
>>> from datetime import date
>>> d = date(2002, 12, 31)
>>> d.replace(day=26)
datetime.date(2002, 12, 26)
@end example

The generic function @ref{1c0,,copy.replace()} also supports @ref{1fa,,date}
objects.
@end deffn

@geindex timetuple() (datetime.date のメソッド)
@anchor{library/datetime datetime date timetuple}@anchor{28be}
@deffn {メソッド} date.timetuple ()

@ref{1712,,time.localtime()} が返すような @ref{ee6,,time.struct_time} を返します。

時分秒が 0 で、 DST フラグが -1 です。

@code{d.timetuple()} は次の式と等価です:

@example
time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
@end example

ここで、 @code{yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1} は本年の 1 月 1 日を 1 としたときの日付番号です。
@end deffn

@geindex toordinal() (datetime.date のメソッド)
@anchor{library/datetime datetime date toordinal}@anchor{28bf}
@deffn {メソッド} date.toordinal ()

先発グレゴリオ暦における日付序数を返します。 1 年の 1 月 1 日が序数 1 となります。任意の @ref{1fa,,date} オブジェクト @code{d} について、 @code{date.fromordinal(d.toordinal()) == d} となります。
@end deffn

@geindex weekday() (datetime.date のメソッド)
@anchor{library/datetime datetime date weekday}@anchor{28c0}
@deffn {メソッド} date.weekday ()

月曜日を 0、日曜日を 6 として、曜日を整数で返します。例えば、 @code{date(2002, 12, 4).weekday() == 2} であり、水曜日を示します。 @ref{28c1,,isoweekday()} も参照してください。
@end deffn

@geindex isoweekday() (datetime.date のメソッド)
@anchor{library/datetime datetime date isoweekday}@anchor{28c1}
@deffn {メソッド} date.isoweekday ()

月曜日を 1,日曜日を 7 として、曜日を整数で返します。例えば、 @code{date(2002, 12, 4).isoweekday() == 3} であり、水曜日を示します。 @ref{28c0,,weekday()}, @ref{af1,,isocalendar()} も参照してください。
@end deffn

@geindex isocalendar() (datetime.date のメソッド)
@anchor{library/datetime datetime date isocalendar}@anchor{af1}
@deffn {メソッド} date.isocalendar ()

@code{year}、@code{week}、@code{weekday} の3つで構成された @ref{85e,,named tuple} を返します。

ISO 暦はグレゴリオ暦の変種として広く用いられています。 @footnote{
優れた説明は R. H. van Gent の @uref{https://web.archive.org/web/20220531051136/https://webspace.science.uu.nl/~gent0113/calendar/isocalendar.htm,guide to the mathematics of the ISO 8601 calendar} を参照してください。
}

ISO 年は完全な週が 52 週または 53 週あり、週は月曜から始まって日曜に終わります。ISO 年でのある年における最初の週は、その年の木曜日を含む最初の (グレゴリオ暦での) 週となります。この週は週番号 1 と呼ばれ、この木曜日での ISO 年はグレゴリオ暦における年と等しくなります。

例えば、2004 年は木曜日から始まるため、ISO 年の最初の週は 2003 年 12 月 29 日、月曜日から始まり、2004 年 1 月 4 日、日曜日に終わります

@example
>>> from datetime import date
>>> date(2003, 12, 29).isocalendar()
datetime.IsoCalendarDate(year=2004, week=1, weekday=1)
>>> date(2004, 1, 4).isocalendar()
datetime.IsoCalendarDate(year=2004, week=1, weekday=7)
@end example


バージョン 3.9 で変更: 結果が タプル から @ref{85e,,named tuple} へ変更されました。

@end deffn

@geindex isoformat() (datetime.date のメソッド)
@anchor{library/datetime datetime date isoformat}@anchor{28c2}
@deffn {メソッド} date.isoformat ()

日付を ISO 8601 書式の @code{YYYY-MM-DD} で表した文字列を返します:

@example
>>> from datetime import date
>>> date(2002, 12, 4).isoformat()
'2002-12-04'
@end example
@end deffn

@geindex __str__() (datetime.date のメソッド)
@anchor{library/datetime datetime date __str__}@anchor{28c3}
@deffn {メソッド} date.__str__ ()

For a date @code{d}, @code{str(d)} is equivalent to @code{d.isoformat()}.
@end deffn

@geindex ctime() (datetime.date のメソッド)
@anchor{library/datetime datetime date ctime}@anchor{28c4}
@deffn {メソッド} date.ctime ()

日付を表す文字列を返します:

@example
>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'
@end example

@code{d.ctime()} は次の式と等価です:

@example
time.ctime(time.mktime(d.timetuple()))
@end example

これが等価になるのは、 (@ref{28c5,,time.ctime()} に呼び出され、 @ref{28c4,,date.ctime()} に呼び出されない) ネイティブの C 関数 @code{ctime()} が C 標準に準拠しているプラットフォーム上でです。
@end deffn

@geindex strftime() (datetime.date のメソッド)
@anchor{library/datetime datetime date strftime}@anchor{e8f}
@deffn {メソッド} date.strftime (format)

明示的な書式文字列で制御された、日付を表現する文字列を返します。
時間、分、秒を表す書式コードは値 0 になります。
@ref{1b54,,strftime() and strptime() behavior} および @ref{28c2,,date.isoformat()} も参照してください。
@end deffn

@geindex __format__() (datetime.date のメソッド)
@anchor{library/datetime datetime date __format__}@anchor{28c6}
@deffn {メソッド} date.__format__ (format)

@ref{e8f,,date.strftime()} と等価です。
これにより、 @ref{19a,,フォーマット済み文字列リテラル} の中や @ref{833,,str.format()} を使っているときに @ref{1fa,,date} オブジェクトの書式文字列を指定できます。
@ref{1b54,,strftime() and strptime() behavior} および @ref{28c2,,date.isoformat()} も参照してください。
@end deffn

@menu
* Examples of usage; date: Examples of usage date. 

@end menu

@node Examples of usage date,,,date objects
@anchor{library/datetime examples-of-usage-date}@anchor{28c7}
@subsubsection Examples of usage: @code{date}


イベントまでの日数を数える例を示します:

@example
>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> today == date.fromtimestamp(time.time())
True
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
...     my_birthday = my_birthday.replace(year=today.year + 1)
...
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)
>>> time_to_birthday.days
202
@end example

さらなる @ref{1fa,,date} を使う例:

@example
>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
>>> d
datetime.date(2002, 3, 11)

>>> # Methods related to formatting string output
>>> d.isoformat()
'2002-03-11'
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
>>> d.ctime()
'Mon Mar 11 00:00:00 2002'
>>> 'The @{1@} is @{0:%d@}, the @{2@} is @{0:%B@}.'.format(d, "day", "month")
'The day is 11, the month is March.'

>>> # Methods for extracting 'components' under different calendars
>>> t = d.timetuple()
>>> for i in t:
...     print(i)
2002                # year
3                   # month
11                  # day
0
0
0
0                   # weekday (0 = Monday)
70                  # 70th day in the year
-1
>>> ic = d.isocalendar()
>>> for i in ic:
...     print(i)
2002                # ISO year
11                  # ISO week number
1                   # ISO day number ( 1 = Monday )

>>> # A date object is immutable; all operations produce a new object
>>> d.replace(year=2005)
datetime.date(2005, 3, 11)
@end example

@node datetime objects,time objects,date objects,datetime --- 基本的な日付と時間の型
@anchor{library/datetime datetime-datetime}@anchor{28c8}@anchor{library/datetime datetime-objects}@anchor{28c9}
@subsubsection @code{datetime} objects


@ref{4e2,,datetime} オブジェクトは @ref{1fa,,date} オブジェクトおよび @ref{1fb,,time} オブジェクトの全ての情報が入っている単一のオブジェクトです。

@ref{1fa,,date} オブジェクトと同様に、 @ref{4e2,,datetime} は現在のグレゴリオ暦が両方向に延長されているものと仮定します。また、 @ref{1fb,,time} オブジェクトと同様に、 @ref{4e2,,datetime} は毎日が厳密に 3600*24 秒であると仮定します。

以下にコンストラクタを示します:

@geindex datetime (datetime のクラス)
@anchor{library/datetime datetime datetime}@anchor{4e2}
@deffn {クラス} datetime.datetime (year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

`year', `month', `day' 引数は必須です。
`tzinfo' は @code{None} または @ref{7f6,,tzinfo} サブクラスのインスタンスです。
残りの引数は次の範囲の整数でなければなりません:


@itemize *

@item 
@code{MINYEAR <= year <= MAXYEAR},

@item 
@code{1 <= month <= 12},

@item 
@code{1 <= day <= 指定された月と年における日数},

@item 
@code{0 <= hour < 24},

@item 
@code{0 <= minute < 60},

@item 
@code{0 <= second < 60},

@item 
@code{0 <= microsecond < 1000000},

@item 
@code{fold in [0, 1]}.
@end itemize

範囲を超えた引数を与えた場合、 @ref{2ec,,ValueError} が送出されます。


バージョン 3.6 で変更: `fold' パラメータが追加されました。

@end deffn

他のコンストラクタ、および全てのクラスメソッドを以下に示します:

@geindex today() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime today}@anchor{28ca}
@deffn {メソッド} classmethod datetime.today ()

@ref{28ad,,tzinfo} が @code{None} である現在のローカルの日付および時刻を返します。

次と等価です:

@example
datetime.fromtimestamp(time.time())
@end example

@ref{711,,now()}, @ref{712,,fromtimestamp()} も参照してください。

このメソッドの機能は @ref{711,,now()} と等価ですが、 @code{tz} 引数はありません。
@end deffn

@geindex now() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime now}@anchor{711}
@deffn {メソッド} classmethod datetime.now (tz=None)

現在のローカルな日時を返します。

オプションの引数 `tz' が @code{None} であるか指定されていない場合、このメソッドは @ref{28ca,,today()} と同様ですが、可能ならば @ref{55d,,time.time()} タイムスタンプを通じて得ることができる、より高い精度で時刻を提供します (例えば、プラットフォームが C  関数 @code{gettimeofday()} をサポートする場合には可能なことがあります)。

`tz' が @code{None} でない場合、 `tz' は @ref{7f6,,tzinfo} のサブクラスのインスタンスでなければならず、現在の日付および時刻は `tz' のタイムゾーンに変換されます。

@ref{28ca,,today()} および @ref{351,,utcnow()} よりもこの関数を使う方が好ましいです。

@cartouche
@quotation 注釈 
Subsequent calls to @code{datetime.now()} may return the same
instant depending on the precision of the underlying clock.
@end quotation
@end cartouche
@end deffn

@geindex utcnow() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime utcnow}@anchor{351}
@deffn {メソッド} classmethod datetime.utcnow ()

@ref{28ad,,tzinfo} が @code{None} である現在の UTC の日付および時刻を返します。

このメソッドは @ref{711,,now()} と似ていますが、 naive な @ref{4e2,,datetime} オブジェクトとして現在の UTC 日付および時刻を返します。
aware な現在の UTC datetime は @code{datetime.now(timezone.utc)} を呼び出すことで取得できます。
@ref{711,,now()} も参照してください。

@cartouche
@quotation 警告 
naive な @code{datetime} オブジェクトは多くの @code{datetime} メソッドでローカルな時間として扱われるため、 aware な datetime を使って UTC の時刻を表すのが好ましいです。
そのため、 UTC での現在の時刻を表すオブジェクトの作成では @code{datetime.now(timezone.utc)} を呼び出す方法が推奨されます。
@end quotation
@end cartouche


バージョン 3.12 で非推奨: Use @ref{711,,datetime.now()} with @ref{713,,UTC} instead.

@end deffn

@geindex fromtimestamp() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime fromtimestamp}@anchor{712}
@deffn {メソッド} classmethod datetime.fromtimestamp (timestamp, tz=None)

@ref{55d,,time.time()} が返すような、 POSIX タイムスタンプに対応するローカルな日付と時刻を返します。オプションの引数 `tz' が @code{None} であるか、指定されていない場合、タイムスタンプはプラットフォームのローカルな日付および時刻に変換され、返される @ref{4e2,,datetime} オブジェクトは naive なものになります。

`tz' が @code{None} でない場合、 `tz' は @ref{7f6,,tzinfo} のサブクラスのインスタンスでなければならず、タイムスタンプは `tz' のタイムゾーンに変換されます。

タイムスタンプがプラットフォームの C 関数 @code{localtime()} や @code{gmtime()} でサポートされている範囲を超えた場合、 @ref{712,,fromtimestamp()} は @ref{a81,,OverflowError} を送出することがあります。この範囲はよく 1970 年から 2038 年に制限されています。
また @code{localtime()} や @code{gmtime()} が失敗した際は @ref{2c0,,OSError} を送出します。
うるう秒がタイムスタンプの概念に含まれている非 POSIX システムでは、 @ref{712,,fromtimestamp()} はうるう秒を無視します。
このため、秒の異なる二つのタイムスタンプが同一の @ref{4e2,,datetime} オブジェクトとなることが起こり得ます。
@ref{352,,utcfromtimestamp()} よりも、このメソッドの方が好ましいです。


バージョン 3.3 で変更: timestamp がプラットフォームの C 関数 @code{localtime()} もしくは @code{gmtime()} のサポートする値の範囲から外れていた場合、 @ref{2ec,,ValueError} ではなく @ref{a81,,OverflowError} を送出するようになりました。 @code{localtime()} もしくは @code{gmtime()} の呼び出し失敗で @ref{2ec,,ValueError} ではなく @ref{2c0,,OSError} を送出するようになりました。



バージョン 3.6 で変更: @ref{712,,fromtimestamp()} は @ref{e51,,fold} を1にしてインスタンスを返します。

@end deffn

@geindex utcfromtimestamp() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime utcfromtimestamp}@anchor{352}
@deffn {メソッド} classmethod datetime.utcfromtimestamp (timestamp)

POSIX タイムスタンプに対応する、@ref{28ad,,tzinfo} が @code{None} の UTC での @ref{4e2,,datetime} を返します。(返されるオブジェクトは naive です。)

タイムスタンプがプラットフォームにおける C 関数 @code{localtime()} でサポートされている範囲を超えている場合には @ref{a81,,OverflowError} を、@code{gmtime()} が失敗した場合には @ref{2c0,,OSError} を送出します。
これはたいてい 1970 年から 2038 年に制限されています。

aware な @ref{4e2,,datetime} オブジェクトを得るには @ref{712,,fromtimestamp()} を呼んでください:

@example
datetime.fromtimestamp(timestamp, timezone.utc)
@end example

POSIX 互換プラットフォームでは、これは以下の表現と等価です:

@example
datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
@end example

後者を除き、式は常に年の全範囲 (@ref{289b,,MINYEAR} から @ref{289c,,MAXYEAR} を含みます) をサポートします。

@cartouche
@quotation 警告 
naive な @code{datetime} オブジェクトは多くの @code{datetime} メソッドでローカルな時間として扱われるため、 aware な datetime を使って UTC の時刻を表すのが好ましいです。
そのため、 UTC でのある特定のタイムスタンプを表すオブジェクトの作成では @code{datetime.fromtimestamp(timestamp, tz=timezone.utc)} を呼び出す方法が推奨されます。
@end quotation
@end cartouche


バージョン 3.3 で変更: timestamp がプラットフォームの C 関数 @code{gmtime()} のサポートする値の範囲から外れていた場合、 @ref{2ec,,ValueError} ではなく @ref{a81,,OverflowError} を送出するようになりました。 @code{gmtime()} の呼び出し失敗で @ref{2ec,,ValueError} ではなく @ref{2c0,,OSError} を送出するようになりました。



バージョン 3.15 で変更: Accepts any real number as `timestamp', not only integer or float.



バージョン 3.12 で非推奨: Use @ref{712,,datetime.fromtimestamp()} with @ref{713,,UTC} instead.

@end deffn

@geindex fromordinal() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime fromordinal}@anchor{28cb}
@deffn {メソッド} classmethod datetime.fromordinal (ordinal)

1 年 1 月 1 日を序数 1 とする早期グレゴリオ暦序数に対応する @ref{4e2,,datetime} オブジェクトを返します。
@code{1 <= ordinal <= datetime.max.toordinal()} でなければ @ref{2ec,,ValueError} が送出されます。
返されるオブジェクトの時間、分、秒、およびマイクロ秒はすべて 0 で、 @ref{28ad,,tzinfo} は @code{None} となっています。
@end deffn

@geindex combine() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime combine}@anchor{e90}
@deffn {メソッド} classmethod datetime.combine (date, time, tzinfo=time.tzinfo)

日付部分と与えられた @ref{1fa,,date} オブジェクトとが等しく、時刻部分と与えられた @ref{1fb,,time} オブジェクトとが等しい、新しい @ref{4e2,,datetime} オブジェクトを返します。
`tzinfo' 引数が与えられた場合、その値は返り値の @ref{28ad,,tzinfo} 属性に設定するのに使われます。そうでない場合、 `time' 引数の @ref{28a5,,tzinfo} 属性が使われます。`date' 引数に @ref{4e2,,datetime} オブジェクトが与えられた場合、その時刻部分と @ref{28ad,,tzinfo} 属性は無視されます。

For any @ref{4e2,,datetime} object @code{d},
@code{d == datetime.combine(d.date(), d.time(), d.tzinfo)}.


バージョン 3.6 で変更: `tzinfo' 引数が追加されました。

@end deffn

@geindex fromisoformat() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime fromisoformat}@anchor{82a}
@deffn {メソッド} classmethod datetime.fromisoformat (date_string)

以下の例外を除く、有効な ISO 8601 フォーマットで与えられた `date_string' に対応する @ref{4e2,,datetime} を返します :


@enumerate 

@item 
小数の秒があるタイムゾーンオフセット。

@item 
@code{T} セパレーターを他の1文字のユニコードに置き換えたもの。

@item 
少数の時と分はサポートされていません。

@item 
精度の低い日付は現在サポートされていません(@code{YYYY-MM}, @code{YYYY})。

@item 
拡張された日付表現は現在サポートされていません(@code{±YYYYYY-MM-DD})。

@item 
序数の日付は現在サポートされていません(@code{YYYY-OOO})。
@end enumerate

例:

@example
>>> from datetime import datetime
>>> datetime.fromisoformat('2011-11-04')
datetime.datetime(2011, 11, 4, 0, 0)
>>> datetime.fromisoformat('20111104')
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-04T00:05:23Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('20111104T000523')
datetime.datetime(2011, 11, 4, 0, 5, 23)
>>> datetime.fromisoformat('2011-W01-2T00:05:23.283')
datetime.datetime(2011, 1, 4, 0, 5, 23, 283000)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('2011-11-04T00:05:23+04:00')
datetime.datetime(2011, 11, 4, 0, 5, 23,
    tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
@end example


Added in version 3.7.



バージョン 3.11 で変更: Previously, this method only supported formats that could be emitted by
@ref{28c2,,date.isoformat()} or @ref{d25,,datetime.isoformat()}.

@end deffn

@geindex fromisocalendar() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime fromisocalendar}@anchor{be0}
@deffn {メソッド} classmethod datetime.fromisocalendar (year, week, day)

Return a @ref{4e2,,datetime} corresponding to the ISO calendar date specified
by `year', `week' and `day'. The non-date components of the datetime are populated
with their normal default values. This is the inverse of the function
@ref{af2,,datetime.isocalendar()}.


Added in version 3.8.

@end deffn

@geindex strptime() (datetime.datetime のクラスメソッド)
@anchor{library/datetime datetime datetime strptime}@anchor{1950}
@deffn {メソッド} classmethod datetime.strptime (date_string, format)

`date_string' に対応した @ref{4e2,,datetime} を返します。 `format' にしたがって構文解析されます。

`format' がマイクロ秒やタイムゾーン情報を含まない場合は、以下と等価です:

@example
datetime(*(time.strptime(date_string, format)[0:6]))
@end example

date_string と format が @ref{1646,,time.strptime()} で構文解析できない場合や、この関数が時刻タプルを返してこない場合には @ref{2ec,,ValueError} を送出します。@ref{1b54,,strftime() and strptime() behavior} および @ref{82a,,datetime.fromisoformat()} も参照してください。


バージョン 3.13 で変更: If `format' specifies a day of month without a year a
@ref{1a3,,DeprecationWarning} is now emitted.  This is to avoid a quadrennial
leap year bug in code seeking to parse only a month and day as the
default year used in absence of one in the format is not a leap year.
Such `format' values may raise an error as of Python 3.15.  The
workaround is to always include a year in your `format'.  If parsing
`date_string' values that do not have a year, explicitly add a year that
is a leap year before parsing:

@example
>>> from datetime import datetime
>>> date_string = "02/29"
>>> when = datetime.strptime(f"@{date_string@};1984", "%m/%d;%Y")  # Avoids leap year bug.
>>> when.strftime("%B %d")
'February 29'
@end example

@end deffn

以下にクラス属性を示します:

@geindex min (datetime.datetime の属性)
@anchor{library/datetime datetime datetime min}@anchor{1b65}
@deffn {の属性} datetime.min

表現できる最も古い @ref{4e2,,datetime} で、 @code{datetime(MINYEAR, 1, 1, tzinfo=None)} です。
@end deffn

@geindex max (datetime.datetime の属性)
@anchor{library/datetime datetime datetime max}@anchor{28cc}
@deffn {の属性} datetime.max

表現できる最も新しい @ref{4e2,,datetime} で、 @code{datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)} です。
@end deffn

@geindex resolution (datetime.datetime の属性)
@anchor{library/datetime datetime datetime resolution}@anchor{28cd}
@deffn {の属性} datetime.resolution

等しくない @ref{4e2,,datetime} オブジェクト間の最小の差で、 @code{timedelta(microseconds=1)} です。
@end deffn

インスタンスの属性 (読み出しのみ):

@geindex year (datetime.datetime の属性)
@anchor{library/datetime datetime datetime year}@anchor{28a6}
@deffn {の属性} datetime.year

両端値を含む @ref{289b,,MINYEAR} から @ref{289c,,MAXYEAR} までの値です。
@end deffn

@geindex month (datetime.datetime の属性)
@anchor{library/datetime datetime datetime month}@anchor{28a7}
@deffn {の属性} datetime.month

両端値を含む 1 から 12 までの値です。
@end deffn

@geindex day (datetime.datetime の属性)
@anchor{library/datetime datetime datetime day}@anchor{28a8}
@deffn {の属性} datetime.day

1 から与えられた月と年における日数までの値です。
@end deffn

@geindex hour (datetime.datetime の属性)
@anchor{library/datetime datetime datetime hour}@anchor{28a9}
@deffn {の属性} datetime.hour

in @code{range(24)} を満たします。
@end deffn

@geindex minute (datetime.datetime の属性)
@anchor{library/datetime datetime datetime minute}@anchor{28aa}
@deffn {の属性} datetime.minute

in @code{range(60)} を満たします。
@end deffn

@geindex second (datetime.datetime の属性)
@anchor{library/datetime datetime datetime second}@anchor{28ab}
@deffn {の属性} datetime.second

in @code{range(60)} を満たします。
@end deffn

@geindex microsecond (datetime.datetime の属性)
@anchor{library/datetime datetime datetime microsecond}@anchor{28ac}
@deffn {の属性} datetime.microsecond

in @code{range(1000000)} を満たします。
@end deffn

@geindex tzinfo (datetime.datetime の属性)
@anchor{library/datetime datetime datetime tzinfo}@anchor{28ad}
@deffn {の属性} datetime.tzinfo

@ref{4e2,,datetime} コンストラクタに `tzinfo' 引数として与えられたオブジェクトになり、何も渡されなかった場合には @code{None} になります。
@end deffn

@geindex fold (datetime.datetime の属性)
@anchor{library/datetime datetime datetime fold}@anchor{e51}
@deffn {の属性} datetime.fold

@code{[0, 1]} のどちらかです。
繰り返し期間中の実時間の曖昧さ除去に使われます。
(繰り返し期間は、夏時間の終わりに時計が巻き戻るときや、現在のゾーンの UTC オフセットが政治的な理由で減少するときに発生します。)
0または1という値は、同じ実時間で表現される 2 つの時刻のうちのそれぞれ早い方または遅い方を表します。


Added in version 3.6.

@end deffn

サポートされている演算を以下に示します:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

結果

@item

@code{datetime2 = datetime1 + timedelta}

@tab

(1)

@item

@code{datetime2 = datetime1 - timedelta}

@tab

(2)

@item

@code{timedelta = datetime1 - datetime2}

@tab

(3)

@item


@display
@code{datetime1 == datetime2}@w{ }
@code{datetime1 != datetime2}@w{ }
@end display



@tab

等価性の比較。(4)

@item


@display
@code{datetime1 < datetime2}@w{ }
@code{datetime1 > datetime2}@w{ }
@code{datetime1 <= datetime2}@w{ }
@code{datetime1 >= datetime2}@w{ }
@end display



@tab

順序の比較。(5)

@end multitable



@enumerate 

@item 
@code{datetime2} は @code{datetime1} から時間 @code{timedelta} 移動したもので、@code{timedelta.days > 0} の場合未来へ、@code{timedelta.days < 0} の場合過去へ移動します。
結果は入力の datetime と同じ @ref{28ad,,tzinfo} 属性を持ち、演算後には @code{datetime2 - datetime1 == timedelta} となります。
@code{datetime2.year} が @ref{289b,,MINYEAR} よりも小さいか、 @ref{289c,,MAXYEAR} より大きい場合には @ref{a81,,OverflowError} が送出されます。
入力が aware なオブジェクトの場合でもタイムゾーン修正は全く行われません。

@item 
@code{datetime2 + timedelta == datetime1} となるような @code{datetime2} を計算します。
ちなみに、結果は入力の datetime と同じ @ref{28ad,,tzinfo} 属性を持ち、入力が aware だとしてもタイムゾーン修正は全く行われません。

@item 
@ref{4e2,,datetime} から @ref{4e2,,datetime} の減算は両方の被演算子が naive であるか、両方とも aware である場合にのみ定義されています。片方が aware でもう一方が naive の場合、 @ref{198,,TypeError} が送出されます。

If both are naive, or both are aware and have the same @ref{28ad,,tzinfo} attribute,
the @ref{28ad,,tzinfo} attributes are ignored, and the result is a @ref{bc3,,timedelta}
object @code{t} such that @code{datetime2 + t == datetime1}. No time zone adjustments
are done in this case.

If both are aware and have different @ref{28ad,,tzinfo} attributes, @code{a-b} acts
as if @code{a} and @code{b} were first converted to naive UTC datetimes. The
result is @code{(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
- b.utcoffset())} except that the implementation never overflows.

@item 
@ref{4e2,,datetime} オブジェクトはタイムゾーンを考慮して同じ日付と時刻を表す場合、等しいです。

Naive and aware @code{datetime} objects are never equal.

If both comparands are aware, and have the same @code{tzinfo} attribute,
the @code{tzinfo} and @ref{e51,,fold} attributes are ignored and
the base datetimes are compared.
If both comparands are aware and have different @ref{28ad,,tzinfo}
attributes, the comparison acts as comparands were first converted to UTC
datetimes except that the implementation never overflows.
@code{datetime} instances in a repeated interval are never equal to
@code{datetime} instances in other time zone.

@item 
タイムゾーンを考慮して、`datetime1' が時刻として `datetime2' よりも前を表す場合に、`datetime1' は `datetime2' よりも小さいと見なされます。

Order comparison between naive and aware @ref{4e2,,datetime} objects
raises @ref{198,,TypeError}.

If both comparands are aware, and have the same @code{tzinfo} attribute,
the @code{tzinfo} and @ref{e51,,fold} attributes are ignored and
the base datetimes are compared.
If both comparands are aware and have different @ref{28ad,,tzinfo}
attributes, the comparison acts as comparands were first converted to UTC
datetimes except that the implementation never overflows.
@end enumerate


バージョン 3.3 で変更: aware な @ref{4e2,,datetime} インスタンスと naive な @ref{4e2,,datetime} インスタンスの等価比較では @ref{198,,TypeError} は送出されません。



バージョン 3.13 で変更: Comparison between @ref{4e2,,datetime} object and an instance of
the @ref{1fa,,date} subclass that is not a @code{datetime} subclass
no longer converts the latter to @code{date}, ignoring the time part
and the time zone.
The default behavior can be changed by overriding the special comparison
methods in subclasses.


インスタンスメソッド:

@geindex date() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime date}@anchor{28ce}
@deffn {メソッド} datetime.date ()

同じ年、月、日の @ref{1fa,,date} オブジェクトを返します。
@end deffn

@geindex time() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime time}@anchor{28cf}
@deffn {メソッド} datetime.time ()

同じhour、minute、second、microsecond 及び foldを持つ @ref{1fb,,time} オブジェクトを返します。 @ref{28ad,,tzinfo} は @code{None} です。 @ref{28d0,,timetz()} も参照してください。


バージョン 3.6 で変更: 値 foldは返される @ref{1fb,,time} オブジェクトにコピーされます。

@end deffn

@geindex timetz() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime timetz}@anchor{28d0}
@deffn {メソッド} datetime.timetz ()

同じhour、minute、second、microsecond、fold および tzinfo 属性を持つ @ref{1fb,,time} オブジェクトを返します。  @ref{f4,,time()} メソッドも参照してください。


バージョン 3.6 で変更: 値 foldは返される @ref{1fb,,time} オブジェクトにコピーされます。

@end deffn

@geindex replace() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime replace}@anchor{16e4}
@deffn {メソッド} datetime.replace (year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)

Return a new @ref{34,,datetime} object with the same attributes, but with
specified parameters updated. Note that @code{tzinfo=None} can be specified to
create a naive datetime from an aware datetime with no conversion of date
and time data.

@ref{4e2,,datetime} オブジェクトは汎用的な関数 @ref{1c0,,copy.replace()} にもサポートされています。


バージョン 3.6 で変更: `fold' パラメータが追加されました。

@end deffn

@geindex astimezone() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime astimezone}@anchor{bc4}
@deffn {メソッド} datetime.astimezone (tz=None)

`tz' を新たに @ref{28ad,,tzinfo} 属性 として持つ @ref{4e2,,datetime} オブジェクトを返します。
日付および時刻データを調整して、返り値が `self' と同じ UTC 時刻を持ち、 `tz' におけるローカルな時刻を表すようにします。

もし与えられた場合、 `tz' は @ref{7f6,,tzinfo} のサブクラスのインスタンスでなければならず、 インスタンスの @ref{28d1,,utcoffset()} および @ref{28d2,,dst()} メソッドは @code{None} を返してはなりません。もし `self' が naive ならば、おそらくシステムのタイムゾーンで時間を表現します。

引数無し (もしくは @code{tz=None} の形 ) で呼び出された場合、システムのローカルなタイムゾーンが変更先のタイムゾーンだと仮定されます。
変換後の datetime インスタンスの @code{.tzinfo} 属性には、 OS から取得したゾーン名とオフセットを持つ @ref{12d5,,timezone} インスタンスが設定されます。

@code{self.tzinfo} が `tz' の場合、 @code{self.astimezone(tz)} は `self' に等しくなります。つまり、date および time に対する調整は行われません。そうでない場合、結果はタイムゾーン `tz' におけるローカル時刻で、 `self' と同じ UTC 時刻を表すようになります。これは、@code{astz = dt.astimezone(tz)} とした後、 @code{astz - astz.utcoffset()} は通常 @code{dt - dt.utcoffset()} と同じ date および time を持つことを示します。

単に @ref{12d5,,timezone} オブジェクト `tz' を @ref{34,,datetime} オブジェクト `dt' に追加したいだけで、日付や時刻データへの調整を行わないのなら、@code{dt.replace(tzinfo=tz)} を使ってください。単に aware な @ref{34,,datetime} オブジェクト `dt' から @code{timezone} オブジェクトを除去したいだけで、日付や時刻データの変換を行わないのなら、@code{dt.replace(tzinfo=None)} を使ってください。

デフォルトの @ref{28d3,,tzinfo.fromutc()} メソッドを @ref{7f6,,tzinfo} のサブクラスで上書きして, @ref{bc4,,astimezone()} が返す結果に影響を及ぼすことができます。エラーの場合を無視すると、 @ref{bc4,,astimezone()} は以下のように動作します:

@example
def astimezone(self, tz):
    if self.tzinfo is tz:
        return self
    # Convert self to UTC, and attach the new timezone object.
    utc = (self - self.utcoffset()).replace(tzinfo=tz)
    # Convert from UTC to tz's local time.
    return tz.fromutc(utc)
@end example


バージョン 3.3 で変更: `tz' が省略可能になりました。



バージョン 3.6 で変更: @ref{bc4,,datetime.datetime.astimezone()} メソッドを naive なインスタンスに対して呼び出せるようになりました。これは、システムのローカルな時間を表現していると想定されます。

@end deffn

@geindex utcoffset() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime utcoffset}@anchor{28d1}
@deffn {メソッド} datetime.utcoffset ()

@ref{28ad,,tzinfo} が @code{None} の場合、 @code{None} を返し、そうでない場合には @code{self.tzinfo.utcoffset(self)} を返します。
後者の式が @code{None} あるいは 1 日以下の大きさを持つ @ref{bc3,,timedelta} オブジェクトのいずれかを返さない場合には例外を送出します。


バージョン 3.7 で変更: UTC オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex dst() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime dst}@anchor{28d2}
@deffn {メソッド} datetime.dst ()

@ref{28ad,,tzinfo} が @code{None} の場合 @code{None} を返し、そうでない場合には @code{self.tzinfo.dst(self)} を返します。
後者の式が @code{None} もしくは、1 日未満の大きさを持つ @ref{bc3,,timedelta} オブジェクトのいずれかを返さない場合には例外を送出します。


バージョン 3.7 で変更: DST オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex tzname() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime tzname}@anchor{28d4}
@deffn {メソッド} datetime.tzname ()

@ref{28ad,,tzinfo} が @code{None} の場合 @code{None} を返し、そうでない場合には @code{self.tzinfo.tzname(self)} を返します。
後者の式が @code{None} か文字列オブジェクトのいずれかを返さない場合には例外を送出します。
@end deffn

@geindex timetuple() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime timetuple}@anchor{28d5}
@deffn {メソッド} datetime.timetuple ()

@ref{1712,,time.localtime()} が返すような @ref{ee6,,time.struct_time} を返します。

@code{d.timetuple()} は次の式と等価です:

@example
time.struct_time((d.year, d.month, d.day,
                  d.hour, d.minute, d.second,
                  d.weekday(), yday, dst))
@end example

ここで @code{yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1} はその年の1月1日を 1 としたときのその日の位置です。
返されるタプルの @ref{28d6,,tm_isdst} フラグは @ref{28d2,,dst()} メソッドに従って設定されます: @ref{28ad,,tzinfo} が @code{None} か @ref{28d2,,dst()} が @code{None} を返す場合、 @code{tm_isdst} は @code{-1} に設定されます; そうでない場合、 @ref{28d2,,dst()} がゼロでない値を返すと @code{tm_isdst} は1となります; それ以外の場合には @code{tm_isdst} は0に設定されます。
@end deffn

@geindex utctimetuple() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime utctimetuple}@anchor{28d7}
@deffn {メソッド} datetime.utctimetuple ()

If @ref{4e2,,datetime} instance @code{d} is naive, this is the same as
@code{d.timetuple()} except that @ref{28d6,,tm_isdst} is forced to 0 regardless of what
@code{d.dst()} returns. DST is never in effect for a UTC time.

If @code{d} is aware, @code{d} is normalized to UTC time, by subtracting
@code{d.utcoffset()}, and a @ref{ee6,,time.struct_time} for the
normalized time is returned. @code{tm_isdst} is forced to 0. Note
that an @ref{a81,,OverflowError} may be raised if @code{d.year} was
@code{MINYEAR} or @code{MAXYEAR} and UTC adjustment spills over a year
boundary.

@cartouche
@quotation 警告 
naive な @code{datetime} オブジェクトは多くの @code{datetime} メソッドでローカルな時間として扱われるため、 aware な datetime を使って UTC の時刻を表すのが好ましいです。結果として、 @ref{28d7,,datetime.utctimetuple()} は誤解を招きやすい返り値を返すかもしれません。
UTC を表す naive な @code{datetime} があった場合、 @ref{28d5,,datetime.timetuple()} が使えるところでは @code{datetime.replace(tzinfo=timezone.utc)} で aware にします。
@end quotation
@end cartouche
@end deffn

@geindex toordinal() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime toordinal}@anchor{28d8}
@deffn {メソッド} datetime.toordinal ()

先発グレゴリオ暦における日付序数を返します。@code{self.date().toordinal()} と同じです。
@end deffn

@geindex timestamp() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime timestamp}@anchor{12ac}
@deffn {メソッド} datetime.timestamp ()

@ref{4e2,,datetime} インスタンスに対応する POSIX タイムスタンプを返します。
返り値は @ref{55d,,time.time()} で返される値に近い @ref{196,,float} です。

このメソッドでは naive な @ref{4e2,,datetime} インスタンスはローカル時刻とし、プラットフォームの C 関数 @code{mktime()} に頼って変換を行います。
@ref{4e2,,datetime} は多くのプラットフォームの @code{mktime()} より広い範囲の値をサポートしているので、遥か過去の時刻や遥か未来の時刻に対し、このメソッドは @ref{a81,,OverflowError} または @ref{2c0,,OSError} を送出するかもしれません。

aware な @ref{4e2,,datetime} インスタンスに対しては以下のように返り値が計算されます:

@example
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
@end example

@cartouche
@quotation 注釈 
UTC 時刻を表す naive な @ref{4e2,,datetime} インスタンスから直接 POSIX タイムスタンプを取得するメソッドはありません。
アプリケーションがその変換を使っており、システムのタイムゾーンが UTC に設定されていなかった場合、 @code{tzinfo=timezone.utc} を引数に与えることで POSIX タイムスタンプを取得できます:

@example
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
@end example

もしくは直接タイムスタンプを計算することもできます:

@example
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
@end example
@end quotation
@end cartouche


Added in version 3.3.



バージョン 3.6 で変更: The @ref{12ac,,timestamp()} method uses the @ref{e51,,fold} attribute to
disambiguate the times during a repeated interval.

@end deffn

@geindex weekday() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime weekday}@anchor{28d9}
@deffn {メソッド} datetime.weekday ()

月曜日を 0、日曜日を 6 として、曜日を整数で返します。 @code{self.date().weekday()} と同じです。 @ref{28da,,isoweekday()} も参照してください。
@end deffn

@geindex isoweekday() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime isoweekday}@anchor{28da}
@deffn {メソッド} datetime.isoweekday ()

月曜日を 1、日曜日を 7 として、曜日を整数で返します。 @code{self.date().isoweekday()} と等価です。 @ref{28d9,,weekday()} 、 @ref{af2,,isocalendar()} も参照してください。
@end deffn

@geindex isocalendar() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime isocalendar}@anchor{af2}
@deffn {メソッド} datetime.isocalendar ()

@code{year}、@code{week}、@code{weekday} の3つで構成された @ref{85e,,named tuple} を返します。 @code{self.date().isocalendar()} と等価です。
@end deffn

@geindex isoformat() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime isoformat}@anchor{d25}
@deffn {メソッド} datetime.isoformat (sep='T', timespec='auto')

日時を ISO 8601 書式で表した文字列で返します:


@itemize -

@item 
@ref{28ac,,microsecond} が 0 でない場合は @code{YYYY-MM-DDTHH:MM:SS.ffffff}

@item 
@ref{28ac,,microsecond} が 0 の場合は @code{YYYY-MM-DDTHH:MM:SS}
@end itemize

@ref{28d1,,utcoffset()} が @code{None} を返さない場合は、文字列の後ろに UTC オフセットが追記されます:


@itemize -

@item 
@ref{28ac,,microsecond} が 0 でない場合は @code{YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]}

@item 
@ref{28ac,,microsecond} が 0 の場合は @code{YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]}
@end itemize

例:

@example
>>> from datetime import datetime, timezone
>>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
'2019-05-18T15:17:08.132263'
>>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
'2019-05-18T15:17:00+00:00'
@end example

オプションの引数 `sep' (デフォルトでは @code{'T'} です)  は 1 文字のセパレータで、結果の文字列の日付と時刻の間に置かれます。例えば:

@example
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
...     """A time zone with an arbitrary, constant -06:39 offset."""
...     def utcoffset(self, dt):
...         return timedelta(hours=-6, minutes=-39)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
>>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
'2009-11-27T00:00:00.000100-06:39'
@end example

オプション引数 `timespec' は、含める追加の時間の要素の数を指定します(デフォルトでは @code{'auto'} です)。以下の内一つを指定してください。


@itemize -

@item 
@code{'auto'}: @ref{28ac,,microsecond} が0である場合 @code{'seconds'} と等しく、そうでない場合は @code{'microseconds'} と等しくなります。

@item 
@code{'hours'}:  @ref{28a9,,hour} を2桁の @code{HH} 書式で含めます。

@item 
@code{'minutes'}: @ref{28a9,,hour} および @ref{28aa,,minute} を @code{HH:MM} の書式で含めます。

@item 
@code{'seconds'}: @ref{28a9,,hour} 、 @ref{28aa,,minute} 、 @ref{28ab,,second}  を @code{HH:MM:SS} の書式で含めます。

@item 
@code{'milliseconds'}: 全ての時刻を含みますが、小数第二位をミリ秒に切り捨てます。
@code{HH:MM:SS.sss} の書式で表現します。

@item 
@code{'microseconds'}: 全ての時刻を @code{HH:MM:SS.mmmmmm} の書式で含めます。
@end itemize

@cartouche
@quotation 注釈 
除外された要素は丸め込みではなく、切り捨てされます。
@end quotation
@end cartouche

不正な `timespec' 引数には @ref{2ec,,ValueError} があげられます:

@example
>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes')
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> dt.isoformat(timespec='microseconds')
'2015-01-01T12:30:59.000000'
@end example


バージョン 3.6 で変更: `timespec' パラメータを追加しました.

@end deffn

@geindex __str__() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime __str__}@anchor{28db}
@deffn {メソッド} datetime.__str__ ()

For a @ref{4e2,,datetime} instance @code{d}, @code{str(d)} is equivalent to
@code{d.isoformat(' ')}.
@end deffn

@geindex ctime() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime ctime}@anchor{28dc}
@deffn {メソッド} datetime.ctime ()

日付および時刻を表す文字列を返します:

@example
>>> from datetime import datetime
>>> datetime(2002, 12, 4, 20, 30, 40).ctime()
'Wed Dec  4 20:30:40 2002'
@end example

出力文字列は入力が aware であれ naive であれ、タイムゾーン情報を含み `ません'。

@code{d.ctime()} は次の式と等価です:

@example
time.ctime(time.mktime(d.timetuple()))
@end example

これが等価になるのは、 (@ref{28c5,,time.ctime()} に呼び出され、 @ref{28dc,,datetime.ctime()} に呼び出されない) ネイティブの C 関数 @code{ctime()} が C 標準に準拠しているプラットフォーム上でです。
@end deffn

@geindex strftime() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime strftime}@anchor{e8e}
@deffn {メソッド} datetime.strftime (format)

明示的な書式文字列で制御された、日付および時刻を表現する文字列を返します。@ref{1b54,,strftime() and strptime() behavior} および @ref{d25,,datetime.isoformat()} も参照してください。
@end deffn

@geindex __format__() (datetime.datetime のメソッド)
@anchor{library/datetime datetime datetime __format__}@anchor{28dd}
@deffn {メソッド} datetime.__format__ (format)

@ref{e8e,,datetime.strftime()} と等価です。
これにより、 @ref{19a,,フォーマット済み文字列リテラル} の中や @ref{833,,str.format()} を使っているときに @ref{4e2,,datetime} オブジェクトの書式文字列を指定できます。
@ref{1b54,,strftime() and strptime() behavior} および @ref{d25,,datetime.isoformat()} も参照してください。
@end deffn

@menu
* Examples of usage; datetime: Examples of usage datetime. 

@end menu

@node Examples of usage datetime,,,datetime objects
@anchor{library/datetime examples-of-usage-datetime}@anchor{28de}
@subsubsection Examples of usage: @code{datetime}


@ref{4e2,,datetime} オブジェクトを使う例:

@example
>>> from datetime import datetime, date, time, timezone

>>> # Using datetime.combine()
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)

>>> # Using datetime.now()
>>> datetime.now()
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
>>> datetime.now(timezone.utc)
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)

>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)

>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:
...     print(it)
...
2006    # year
11      # month
21      # day
16      # hour
30      # minute
0       # second
1       # weekday (0 = Monday)
325     # number of days since 1st January
-1      # dst - method tzinfo.dst() returned None

>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:
...     print(it)
...
2006    # ISO year
47      # ISO week
2       # ISO weekday

>>> # Formatting a datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The @{1@} is @{0:%d@}, the @{2@} is @{0:%B@}, the @{3@} is @{0:%I:%M%p@}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'
@end example

下にある例では、1945年までは +4 UTC 、それ以降は +4:30 UTC を使用しているアフガニスタンのカブールのタイムゾーン情報を表現する @ref{7f6,,tzinfo} のサブクラスを定義しています:

@example
from datetime import timedelta, datetime, tzinfo, timezone

class KabulTz(tzinfo):
    # Kabul used +4 until 1945, when they moved to +4:30
    UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)

    def utcoffset(self, dt):
        if dt.year < 1945:
            return timedelta(hours=4)
        elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
            # An ambiguous ("imaginary") half-hour range representing
            # a 'fold' in time due to the shift from +4 to +4:30.
            # If dt falls in the imaginary range, use fold to decide how
            # to resolve. See PEP495.
            return timedelta(hours=4, minutes=(30 if dt.fold else 0))
        else:
            return timedelta(hours=4, minutes=30)

    def fromutc(self, dt):
        # Follow same validations as in datetime.tzinfo
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")
        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        # A custom implementation is required for fromutc as
        # the input to this function is a datetime with utc values
        # but with a tzinfo set to self.
        # See datetime.astimezone or fromtimestamp.
        if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
            return dt + timedelta(hours=4, minutes=30)
        else:
            return dt + timedelta(hours=4)

    def dst(self, dt):
        # Kabul does not observe daylight saving time.
        return timedelta(0)

    def tzname(self, dt):
        if dt >= self.UTC_MOVE_DATE:
            return "+04:30"
        return "+04"
@end example

上に出てきた @code{KabulTz} の使い方:

@example
>>> tz1 = KabulTz()

>>> # Datetime before the change
>>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
>>> print(dt1.utcoffset())
4:00:00

>>> # Datetime after the change
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
>>> print(dt2.utcoffset())
4:30:00

>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(timezone.utc)
>>> dt3
datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
>>> dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
>>> dt2 == dt3
True
@end example

@node time objects,tzinfo objects,datetime objects,datetime --- 基本的な日付と時間の型
@anchor{library/datetime datetime-time}@anchor{28df}@anchor{library/datetime time-objects}@anchor{28e0}
@subsubsection @code{time} objects


@ref{1fb,,time} オブジェクトは (ローカルの) 日中時刻を表現します。
この時刻表現は特定の日の影響を受けず、 @ref{7f6,,tzinfo} オブジェクトを介した修正の対象となります。

@geindex time (datetime のクラス)
@anchor{library/datetime datetime time}@anchor{1fb}
@deffn {クラス} datetime.time (hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

全ての引数はオプションです。 `tzinfo' は @code{None} または @ref{7f6,,tzinfo} クラスのサブクラスのインスタンスにすることができます。残りの引数は整数で、以下のような範囲に入らなければなりません:


@itemize *

@item 
@code{0 <= hour < 24},

@item 
@code{0 <= minute < 60},

@item 
@code{0 <= second < 60},

@item 
@code{0 <= microsecond < 1000000},

@item 
@code{fold in [0, 1]}.
@end itemize

引数がこれらの範囲外にある場合、 @ref{2ec,,ValueError} が送出されます。 `tzinfo' のデフォルト値が @code{None} である以外のデフォルト値は0です。
@end deffn

以下にクラス属性を示します:

@geindex min (datetime.time の属性)
@anchor{library/datetime datetime time min}@anchor{28e1}
@deffn {の属性} time.min

表現できる最も古い @ref{1fb,,time} で、 @code{time(0, 0, 0, 0)} です。
@end deffn

@geindex max (datetime.time の属性)
@anchor{library/datetime datetime time max}@anchor{28e2}
@deffn {の属性} time.max

表現できる最も新しい @ref{1fb,,time} で、 @code{time(23, 59, 59, 999999)} です。
@end deffn

@geindex resolution (datetime.time の属性)
@anchor{library/datetime datetime time resolution}@anchor{28e3}
@deffn {の属性} time.resolution

等しくない @ref{1fb,,time} オブジェクト間の最小の差で、 @code{timedelta(microseconds=1)} ですが, @ref{1fb,,time} オブジェクト間の四則演算はサポートされていないので注意してください。
@end deffn

インスタンスの属性 (読み出しのみ):

@geindex hour (datetime.time の属性)
@anchor{library/datetime datetime time hour}@anchor{28a1}
@deffn {の属性} time.hour

in @code{range(24)} を満たします。
@end deffn

@geindex minute (datetime.time の属性)
@anchor{library/datetime datetime time minute}@anchor{28a2}
@deffn {の属性} time.minute

in @code{range(60)} を満たします。
@end deffn

@geindex second (datetime.time の属性)
@anchor{library/datetime datetime time second}@anchor{28a3}
@deffn {の属性} time.second

in @code{range(60)} を満たします。
@end deffn

@geindex microsecond (datetime.time の属性)
@anchor{library/datetime datetime time microsecond}@anchor{28a4}
@deffn {の属性} time.microsecond

in @code{range(1000000)} を満たします。
@end deffn

@geindex tzinfo (datetime.time の属性)
@anchor{library/datetime datetime time tzinfo}@anchor{28a5}
@deffn {の属性} time.tzinfo

@ref{1fb,,time} コンストラクタに `tzinfo' 引数として与えられたオブジェクトになり、何も渡されなかった場合には @code{None} になります。
@end deffn

@geindex fold (datetime.time の属性)
@anchor{library/datetime datetime time fold}@anchor{e8d}
@deffn {の属性} time.fold

@code{[0, 1]} のどちらかです。
繰り返し期間中の実時間の曖昧さ除去に使われます。
(繰り返し期間は、夏時間の終わりに時計が巻き戻るときや、現在のゾーンの UTC オフセットが政治的な理由で減少するときに発生します。)
0または1という値は、同じ実時間で表現される 2 つの時刻のうちのそれぞれ早い方または遅い方を表します。


Added in version 3.6.

@end deffn

@ref{1fb,,time} objects support equality and order comparisons,
where @code{a} is considered less than @code{b} when @code{a} precedes @code{b} in time.

Naive and aware @code{time} objects are never equal.
Order comparison between naive and aware @code{time} objects raises
@ref{198,,TypeError}.

比較対象が両方とも aware であり、同じ @ref{28a5,,tzinfo} 属性を持つ場合、 @code{tzinfo} と @code{fold} 属性は無視され時間だけで比較が行われます。比較対象が両方とも aware であり、異なる @code{tzinfo} 属性を持つ場合、まず最初に (@code{self.utcoffset()} で取得できる) それぞれの UTC オフセットを引く調整が行われます。


バージョン 3.3 で変更: aware な  インスタンスと naive な @ref{1fb,,time} インスタンスの等価比較では @ref{198,,TypeError} は送出されません。


ブール値の文脈では、 @ref{1fb,,time} オブジェクトは常に真とみなされます。


バージョン 3.5 で変更: Before Python 3.5, a @ref{1fb,,time} object was considered to be false if it
represented midnight in UTC. This behavior was considered obscure and
error-prone and has been removed in Python 3.5. See bpo-13936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13936} for more
information.


Other constructors:

@geindex fromisoformat() (datetime.time のクラスメソッド)
@anchor{library/datetime datetime time fromisoformat}@anchor{829}
@deffn {メソッド} classmethod time.fromisoformat (time_string)

以下の例外を除く、有効な ISO 8601 フォーマットで与えられた `time_string' に対応する @ref{1fb,,time} を返します :


@enumerate 

@item 
小数の秒があるタイムゾーンオフセット。

@item 
The leading @code{T}, normally required in cases where there may be ambiguity between
a date and a time, is not required.

@item 
Fractional seconds may have any number of digits (anything beyond 6 will
be truncated).

@item 
少数の時と分はサポートされていません。
@end enumerate

例:

@example
>>> from datetime import time
>>> time.fromisoformat('04:23:01')
datetime.time(4, 23, 1)
>>> time.fromisoformat('T04:23:01')
datetime.time(4, 23, 1)
>>> time.fromisoformat('T042301')
datetime.time(4, 23, 1)
>>> time.fromisoformat('04:23:01.000384')
datetime.time(4, 23, 1, 384)
>>> 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)))
>>> time.fromisoformat('04:23:01Z')
datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)
>>> time.fromisoformat('04:23:01+00:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)
@end example


Added in version 3.7.



バージョン 3.11 で変更: Previously, this method only supported formats that could be emitted by
@ref{28e4,,time.isoformat()}.

@end deffn

@geindex strptime() (datetime.time のクラスメソッド)
@anchor{library/datetime datetime time strptime}@anchor{194c}
@deffn {メソッド} classmethod time.strptime (date_string, format)

Return a @ref{1fb,,time} corresponding to `date_string', parsed according to
`format'.

`format' がマイクロ秒やタイムゾーン情報を含まない場合は、以下と等価です:

@example
time(*(time.strptime(date_string, format)[3:6]))
@end example

@ref{2ec,,ValueError} is raised if the `date_string' and `format'
cannot be parsed by @ref{1646,,time.strptime()} or if it returns a value which is not a
time tuple.  See also @ref{1b54,,strftime() and strptime() behavior} and
@ref{829,,time.fromisoformat()}.


Added in version 3.14.

@end deffn

インスタンスメソッド:

@geindex replace() (datetime.time のメソッド)
@anchor{library/datetime datetime time replace}@anchor{19fa}
@deffn {メソッド} time.replace (hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)

Return a new @ref{1fb,,time} with the same values, but with specified
parameters updated. Note that @code{tzinfo=None} can be specified to create a
naive @ref{1fb,,time} from an aware @ref{1fb,,time}, without conversion of the
time data.

@ref{1fb,,time} オブジェクトは汎用的な関数 @ref{1c0,,copy.replace()} にもサポートされています。


バージョン 3.6 で変更: `fold' パラメータが追加されました。

@end deffn

@geindex isoformat() (datetime.time のメソッド)
@anchor{library/datetime datetime time isoformat}@anchor{28e4}
@deffn {メソッド} time.isoformat (timespec='auto')

時刻を ISO 8601 書式で表した次の文字列のうち1つを返します:


@itemize -

@item 
@ref{28a4,,microsecond} が 0 でない場合は @code{HH:MM:SS.ffffff}

@item 
@ref{28a4,,microsecond} が 0 の場合は @code{HH:MM:SS}

@item 
@ref{28e5,,utcoffset()} が @code{None} を返さない場合、 @code{HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]}

@item 
@ref{28a4,,microsecond} が 0 で @ref{28e5,,utcoffset()} が @code{None} を返さない場合、 @code{HH:MM:SS+HH:MM[:SS[.ffffff]]}
@end itemize

オプション引数 `timespec' は、含める追加の時間の要素の数を指定します(デフォルトでは @code{'auto'} です)。以下の内一つを指定してください。


@itemize -

@item 
@code{'auto'}: @ref{28a4,,microsecond} が0である場合 @code{'seconds'} と等しく、そうでない場合は @code{'microseconds'} と等しくなります。

@item 
@code{'hours'}:  @ref{28a1,,hour} を2桁の @code{HH} 書式で含めます。

@item 
@code{'minutes'}: @ref{28a1,,hour} および @ref{28a2,,minute} を @code{HH:MM} の書式で含めます。

@item 
@code{'seconds'}: @ref{28a1,,hour} 、 @ref{28a2,,minute} 、 @ref{28a3,,second}  を @code{HH:MM:SS} の書式で含めます。

@item 
@code{'milliseconds'}: 全ての時刻を含みますが、小数第二位をミリ秒に切り捨てます。
@code{HH:MM:SS.sss} の書式で表現します。

@item 
@code{'microseconds'}: 全ての時刻を @code{HH:MM:SS.mmmmmm} の書式で含めます。
@end itemize

@cartouche
@quotation 注釈 
除外された要素は丸め込みではなく、切り捨てされます。
@end quotation
@end cartouche

不正な `timespec' 引数には @ref{2ec,,ValueError} があげられます。

以下はプログラム例です:

@example
>>> from datetime import time
>>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
'12:34'
>>> dt = time(hour=12, minute=34, second=56, microsecond=0)
>>> dt.isoformat(timespec='microseconds')
'12:34:56.000000'
>>> dt.isoformat(timespec='auto')
'12:34:56'
@end example


バージョン 3.6 で変更: `timespec' パラメータを追加しました.

@end deffn

@geindex __str__() (datetime.time のメソッド)
@anchor{library/datetime datetime time __str__}@anchor{28e6}
@deffn {メソッド} time.__str__ ()

For a time @code{t}, @code{str(t)} is equivalent to @code{t.isoformat()}.
@end deffn

@geindex strftime() (datetime.time のメソッド)
@anchor{library/datetime datetime time strftime}@anchor{1af8}
@deffn {メソッド} time.strftime (format)

明示的な書式文字列で制御された、時刻を表現する文字列を返します。@ref{1b54,,strftime() and strptime() behavior} および @ref{28e4,,time.isoformat()} も参照してください。
@end deffn

@geindex __format__() (datetime.time のメソッド)
@anchor{library/datetime datetime time __format__}@anchor{28e7}
@deffn {メソッド} time.__format__ (format)

@ref{1af8,,time.strftime()} と等価です。
これにより、 @ref{19a,,フォーマット済み文字列リテラル} の中や @ref{833,,str.format()} を使っているときに @ref{1fb,,time} オブジェクトの書式文字列を指定できます。
@ref{1b54,,strftime() and strptime() behavior} および @ref{28e4,,time.isoformat()} も参照してください。
@end deffn

@geindex utcoffset() (datetime.time のメソッド)
@anchor{library/datetime datetime time utcoffset}@anchor{28e5}
@deffn {メソッド} time.utcoffset ()

@ref{28a5,,tzinfo} が @code{None} の場合、 @code{None} を返し、そうでない場合には @code{self.tzinfo.utcoffset(None)} を返します。
後者の式が @code{None} あるいは 1 日以下の大きさを持つ @ref{bc3,,timedelta} オブジェクトのいずれかを返さない場合には例外を送出します。


バージョン 3.7 で変更: UTC オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex dst() (datetime.time のメソッド)
@anchor{library/datetime datetime time dst}@anchor{28e8}
@deffn {メソッド} time.dst ()

@ref{28a5,,tzinfo} が @code{None} の場合 @code{None} を返し、そうでない場合には @code{self.tzinfo.dst(None)} を返します。
後者の式が @code{None} もしくは、1 日未満の大きさを持つ @ref{bc3,,timedelta} オブジェクトのいずれかを返さない場合には例外を送出します。


バージョン 3.7 で変更: DST オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex tzname() (datetime.time のメソッド)
@anchor{library/datetime datetime time tzname}@anchor{28e9}
@deffn {メソッド} time.tzname ()

@ref{28a5,,tzinfo} が @code{None} の場合 @code{None} を返し、そうでない場合には @code{self.tzinfo.tzname(None)} を返します。
後者の式が @code{None} か文字列オブジェクトのいずれかを返さない場合には例外を送出します。
@end deffn

@menu
* Examples of usage; time: Examples of usage time. 

@end menu

@node Examples of usage time,,,time objects
@anchor{library/datetime examples-of-usage-time}@anchor{28ea}
@subsubsection Examples of usage: @code{time}


@ref{1fb,,time} オブジェクトを使う例:

@example
>>> from datetime import time, tzinfo, timedelta
>>> class TZ1(tzinfo):
...     def utcoffset(self, dt):
...         return timedelta(hours=1)
...     def dst(self, dt):
...         return timedelta(0)
...     def tzname(self,dt):
...         return "+01:00"
...     def  __repr__(self):
...         return f"@{self.__class__.__name__@}()"
...
>>> t = time(12, 10, 30, tzinfo=TZ1())
>>> t
datetime.time(12, 10, 30, tzinfo=TZ1())
>>> t.isoformat()
'12:10:30+01:00'
>>> t.dst()
datetime.timedelta(0)
>>> t.tzname()
'+01:00'
>>> t.strftime("%H:%M:%S %Z")
'12:10:30 +01:00'
>>> 'The @{@} is @{:%H:%M@}.'.format("time", t)
'The time is 12:10.'
@end example

@node tzinfo objects,timezone objects,time objects,datetime --- 基本的な日付と時間の型
@anchor{library/datetime datetime-tzinfo}@anchor{28eb}@anchor{library/datetime tzinfo-objects}@anchor{28ec}
@subsubsection @code{tzinfo} objects


@geindex tzinfo (datetime のクラス)
@anchor{library/datetime datetime tzinfo}@anchor{7f6}
@deffn {クラス} datetime.tzinfo

This is an @ref{13ce,,abstract base class}, meaning that this class should not be
instantiated directly.  Define a subclass of @ref{7f6,,tzinfo} to capture
information about a particular time zone.

@ref{7f6,,tzinfo} (の具体的なサブクラス) のインスタンスは @ref{4e2,,datetime} および @ref{1fb,,time} オブジェクトのコンストラクタに渡すことができます。後者のオブジェクトでは、データ属性をローカル時刻におけるものとして見ており、 @ref{7f6,,tzinfo} オブジェクトはローカル時刻の UTC からのオフセット、タイムゾーンの名前、 DST オフセットを、渡された日付および時刻オブジェクトからの相対で示すためのメソッドを提供します。

具象サブクラスを作成し、(少なくとも) 使いたい @ref{4e2,,datetime} のメソッドが必要とする @ref{7f6,,tzinfo} のメソッドを実装する必要があります。
@code{datetime} モジュールは @ref{7f6,,tzinfo} のシンプルな具象サブクラス @ref{12d5,,timezone} を提供します。
これは UTC そのものか北アメリカの EST と EDT のような UTC からの固定されたオフセットを持つタイムゾーンを表せます。

pickle 化についての特殊な要求事項: @ref{7f6,,tzinfo} のサブクラスは引数なしで呼び出すことのできる @ref{8bf,,__init__()} メソッドを持たなければなりません。そうでなければ、 pickle 化することはできますがおそらく unpickle 化することはできないでしょう。これは技術的な側面からの要求であり、将来緩和されるかもしれません。

@ref{7f6,,tzinfo} の具体的なサブクラスでは、以下のメソッドを実装する必要があります。厳密にどのメソッドが必要なのかは、 aware な @code{datetime} オブジェクトがこのサブクラスのインスタンスをどのように使うかに依存します。不確かならば、単に全てを実装してください。
@end deffn

@geindex utcoffset() (datetime.tzinfo のメソッド)
@anchor{library/datetime datetime tzinfo utcoffset}@anchor{28ed}
@deffn {メソッド} tzinfo.utcoffset (dt)

ローカル時間の UTC からのオフセットを、 UTC から東向きを正とした @ref{bc3,,timedelta} オブジェクトで返します。ローカル時間が UTC の西側にある場合、この値は負になります。

このメソッドは UTC からのオフセットの `総計' を表しています。例えば、 @ref{7f6,,tzinfo} オブジェクトがタイムゾーンと DST 修正の両方を表現する場合、 @ref{28ed,,utcoffset()} はそれらの合計を返さなければなりません。
UTC オフセットが未知である場合、 @code{None} を返します。
そうでない場合には、返される値は @code{-timedelta(hours=24)} から @code{timedelta(hours=24)} までの @ref{bc3,,timedelta} 境界を含まないオブジェクトでなければなりません (オフセットの大きさは 1 日より短くなければなりません)。
ほとんどの @ref{28ed,,utcoffset()} 実装は、おそらく以下の二つのうちの一つに似たものになるでしょう:

@example
return CONSTANT                 # fixed-offset class
return CONSTANT + self.dst(dt)  # daylight-aware class
@end example

@ref{28ed,,utcoffset()} が @code{None} を返さない場合、 @ref{28ee,,dst()} も @code{None} を返してはなりません。

@ref{28ed,,utcoffset()} のデフォルトの実装は @ref{36b,,NotImplementedError} を送出します。


バージョン 3.7 で変更: UTC オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex dst() (datetime.tzinfo のメソッド)
@anchor{library/datetime datetime tzinfo dst}@anchor{28ee}
@deffn {メソッド} tzinfo.dst (dt)

夏時間 (DST) 修正を、 @ref{bc3,,timedelta}  オブジェクトで返します。
DST 情報が未知の場合、 @code{None} が返されます。

DST が有効でない場合には @code{timedelta(0)} を返します。
DST が有効の場合、オフセットは @ref{bc3,,timedelta} オブジェクトで返します (詳細は @ref{28ed,,utcoffset()} を参照してください)。
DST オフセットが利用可能な場合、この値は @ref{28ed,,utcoffset()} が返す UTC からのオフセットには既に加算されているため、 DST を個別に取得する必要がない限り @ref{28ee,,dst()} を使って問い合わせる必要はないので注意してください。
例えば、 @ref{28d5,,datetime.timetuple()} は @ref{28ad,,tzinfo} 属性の @ref{28ee,,dst()} メソッドを呼んで @ref{28d6,,tm_isdst} フラグがセットされているかどうか判断し、 @ref{28d3,,tzinfo.fromutc()} は @ref{28ee,,dst()} タイムゾーンを移動する際に DST による変更があるかどうかを調べます。

標準および夏時間の両方をモデル化している @ref{7f6,,tzinfo} サブクラスのインスタンス `tz' は以下の式:

@code{tz.utcoffset(dt) - tz.dst(dt)}

が、 @code{dt.tzinfo == tz} 全ての @ref{4e2,,datetime} オブジェクト `dt' について常に同じ結果を返さなければならないという点で、一貫性を持っていなければなりません。正常に実装された @ref{7f6,,tzinfo} のサブクラスでは、この式はタイムゾーンにおける "標準オフセット (standard offset)" を表し、特定の日や時刻の事情ではなく地理的な位置にのみ依存していなくてはなりません。 @ref{bc4,,datetime.astimezone()} の実装はこの事実に依存していますが、違反を検出することができません; 正しく実装するのはプログラマの責任です。 @ref{7f6,,tzinfo} のサブクラスでこれを保証することができない場合、 @ref{28d3,,tzinfo.fromutc()} の実装をオーバライドして、 @code{astimezone()} に関わらず正しく動作するようにしてもかまいません。

ほとんどの @ref{28ee,,dst()} 実装は、おそらく以下の二つのうちの一つに似たものになるでしょう:

@example
def dst(self, dt):
    # a fixed-offset class:  doesn't account for DST
    return timedelta(0)
@end example

もしくは:

@example
def dst(self, dt):
    # Code to set dston and dstoff to the time zone's DST
    # transition times based on the input dt.year, and expressed
    # in standard local time.

    if dston <= dt.replace(tzinfo=None) < dstoff:
        return timedelta(hours=1)
    else:
        return timedelta(0)
@end example

デフォルトの @ref{28ee,,dst()} 実装は @ref{36b,,NotImplementedError} を送出します。


バージョン 3.7 で変更: DST オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex tzname() (datetime.tzinfo のメソッド)
@anchor{library/datetime datetime tzinfo tzname}@anchor{28ef}
@deffn {メソッド} tzinfo.tzname (dt)

@ref{4e2,,datetime} オブジェクト `dt' に対応するタイムゾーン名を文字列で返します。 @code{datetime} モジュールでは文字列名について何も定義しておらず、特に何かを意味するといった要求仕様もまったくありません。例えば、@code{"GMT"}, @code{"UTC"}, @code{"-500"}, @code{"-5:00"}, @code{"EDT"}, @code{"US/Eastern"}, @code{"America/New York"} は全て有効な応答となります。文字列名が未知の場合には @code{None} を返してください。 @ref{7f6,,tzinfo} のサブクラスでは、特に, @ref{7f6,,tzinfo} クラスが夏時間について記述している場合のように、渡された `dt' の特定の値によって異なった名前を返したい場合があるため、文字列値ではなくメソッドとなっていることに注意してください。

デフォルトの @ref{28ef,,tzname()} 実装は @ref{36b,,NotImplementedError} を送出します。
@end deffn

以下のメソッドは @ref{4e2,,datetime} や @ref{1fb,,time} オブジェクトにおいて、同名のメソッドが呼び出された際に応じて呼び出されます。 @ref{4e2,,datetime} オブジェクトは自身を引数としてメソッドに渡し、 @ref{1fb,,time} オブジェクトは引数として @code{None} をメソッドに渡します。従って、 @ref{7f6,,tzinfo} のサブクラスにおけるメソッドは引数 `dt' が @code{None} の場合と、 @ref{4e2,,datetime} の場合を受理するように用意しなければなりません。

@code{None} が渡された場合、最良の応答方法を決めるのはクラス設計者次第です。例えば、このクラスが @ref{7f6,,tzinfo} プロトコルと関係をもたないということを表明させたければ、 @code{None} が適切です。標準時のオフセットを見つける他の手段がない場合には、標準 UTC オフセットを返すために @code{utcoffset(None)} を使うともっと便利かもしれません。

@ref{4e2,,datetime} オブジェクトが @code{datetime()} メソッドの応答として返された場合、 @code{dt.tzinfo} は `self' と同じオブジェクトになります。ユーザが直接 @ref{7f6,,tzinfo} メソッドを呼び出さないかぎり、 @ref{7f6,,tzinfo} メソッドは @code{dt.tzinfo} と `self' が同じであることに依存します。その結果 @ref{7f6,,tzinfo} メソッドは `dt' がローカル時間であると解釈するので、他のタイムゾーンでのオブジェクトの振る舞いについて心配する必要がありません。

サブクラスでオーバーライドすると良い、もう 1 つの @ref{7f6,,tzinfo} のメソッドがあります:

@geindex fromutc() (datetime.tzinfo のメソッド)
@anchor{library/datetime datetime tzinfo fromutc}@anchor{28d3}
@deffn {メソッド} tzinfo.fromutc (dt)

デフォルトの  実装で呼び出されます。 @ref{bc4,,datetime.astimezone()} から呼ばれた場合、 @code{dt.tzinfo} は `self' であり、 `dt' の日付および時刻データは UTC 時刻を表しているものとして見えます。 @ref{28d3,,fromutc()} の目的は、 `self' のローカル時刻に等しい @ref{34,,datetime} オブジェクトを返すことにより日付と時刻データメンバを修正することにあります。

ほとんどの @ref{7f6,,tzinfo} サブクラスではデフォルトの @ref{28d3,,fromutc()} 実装を問題なく継承できます。デフォルトの実装は、固定オフセットのタイムゾーンや、標準時と夏時間の両方について記述しているタイムゾーン、そして DST 移行時刻が年によって異なる場合でさえ、扱えるくらい強力なものです。デフォルトの @ref{28d3,,fromutc()} 実装が全ての場合に対して正しく扱うことができないような例は、標準時の (UTCからの) オフセットが引数として渡された特定の日や時刻に依存するもので、これは政治的な理由によって起きることがあります。デフォルトの @ref{bc4,,astimezone()} や @ref{28d3,,fromutc()} の実装は、結果が標準時オフセットの変化にまたがる何時間かの中にある場合、期待通りの結果を生成しないかもしれません。

エラーの場合のためのコードを除き、デフォルトの @ref{28d3,,fromutc()} の実装は以下のように動作します:

@example
def fromutc(self, dt):
    # raise ValueError error if dt.tzinfo is not self
    dtoff = dt.utcoffset()
    dtdst = dt.dst()
    # raise ValueError if dtoff is None or dtdst is None
    delta = dtoff - dtdst  # this is self's standard offset
    if delta:
        dt += delta   # convert to standard local time
        dtdst = dt.dst()
        # raise ValueError if dtdst is None
    if dtdst:
        return dt + dtdst
    else:
        return dt
@end example
@end deffn

次の @code{tzinfo_examples.py} ファイルには、 @ref{7f6,,tzinfo} クラスの例がいくつか載っています:

@example
from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)
HOUR = timedelta(hours=1)
SECOND = timedelta(seconds=1)

# A class capturing the platform's idea of local time.
# (May result in wrong values on historical times in
#  timezones where UTC offset and/or the DST rules had
#  changed in the past.)
import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
    DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

class LocalTimezone(tzinfo):

    def fromutc(self, dt):
        assert dt.tzinfo is self
        stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
        args = _time.localtime(stamp)[:6]
        dst_diff = DSTDIFF // SECOND
        # Detect fold
        fold = (args == _time.localtime(stamp - dst_diff))
        return datetime(*args, microsecond=dt.microsecond,
                        tzinfo=self, fold=fold)

    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            return ZERO

    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]

    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, 0)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0

Local = LocalTimezone()


# A complete implementation of current DST rules for major US time zones.

def first_sunday_on_or_after(dt):
    days_to_go = 6 - dt.weekday()
    if days_to_go:
        dt += timedelta(days_to_go)
    return dt


# US DST Rules
#
# This is a simplified (i.e., wrong for a few cases) set of rules for US
# DST start and end times. For a complete and up-to-date set of DST rules
# and timezone definitions, visit the Olson Database (or try pytz):
# http://www.twinsun.com/tz/tz-link.htm
# https://sourceforge.net/projects/pytz/ (might not be up-to-date)
#
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
DSTSTART_2007 = datetime(1, 3, 8, 2)
# and ends at 2am (DST time) on the first Sunday of Nov.
DSTEND_2007 = datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
DSTEND_1987_2006 = datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006

def us_dst_range(year):
    # Find start and end times for US DST. For years before 1967, return
    # start = end for no DST.
    if 2006 < year:
        dststart, dstend = DSTSTART_2007, DSTEND_2007
    elif 1986 < year < 2007:
        dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
    elif 1966 < year < 1987:
        dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
    else:
        return (datetime(year, 1, 1), ) * 2

    start = first_sunday_on_or_after(dststart.replace(year=year))
    end = first_sunday_on_or_after(dstend.replace(year=year))
    return start, end


class USTimeZone(tzinfo):

    def __init__(self, hours, reprname, stdname, dstname):
        self.stdoffset = timedelta(hours=hours)
        self.reprname = reprname
        self.stdname = stdname
        self.dstname = dstname

    def __repr__(self):
        return self.reprname

    def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname

    def utcoffset(self, dt):
        return self.stdoffset + self.dst(dt)

    def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        dt = dt.replace(tzinfo=None)
        if start + HOUR <= dt < end - HOUR:
            # DST is in effect.
            return HOUR
        if end - HOUR <= dt < end:
            # Fold (an ambiguous hour): use dt.fold to disambiguate.
            return ZERO if dt.fold else HOUR
        if start <= dt < start + HOUR:
            # Gap (a non-existent hour): reverse the fold rule.
            return HOUR if dt.fold else ZERO
        # DST is off.
        return ZERO

    def fromutc(self, dt):
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        start = start.replace(tzinfo=self)
        end = end.replace(tzinfo=self)
        std_time = dt + self.stdoffset
        dst_time = std_time + HOUR
        if end <= dst_time < end + HOUR:
            # Repeated hour
            return std_time.replace(fold=1)
        if std_time < start or dst_time >= end:
            # Standard time
            return std_time
        if start <= std_time < end - HOUR:
            # Daylight saving time
            return dst_time


Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
Central  = USTimeZone(-6, "Central",  "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")
@end example

標準時および夏時間の両方を記述している @ref{7f6,,tzinfo} のサブクラスでは、夏時間の移行のときに、回避不能の難解な問題が年に 2 度あるので注意してください。
具体的な例として、東部アメリカ時刻 (US Eastern, UTC -0500) を考えます。
EDT は 3 月の第二日曜日の 1:59 (EST) の 1 分後に開始し、11 月の最初の日曜日の (EDTの) 1:59 に終了します:

@example
  UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
  EST  22:MM 23:MM  0:MM  1:MM  2:MM  3:MM
  EDT  23:MM  0:MM  1:MM  2:MM  3:MM  4:MM

start  22:MM 23:MM  0:MM  1:MM  3:MM  4:MM

  end  23:MM  0:MM  1:MM  1:MM  2:MM  3:MM
@end example

DSTの開始 ("start" ライン) で、ローカルの実時間は 1:59 から 3:00 に飛びます。
この日には、 2:MM という形式の実時間は意味をなさないので、 DST が始まった日に @code{astimezone(Eastern)} は @code{hour == 2} となる結果を返すことはありません。
例として、 2016 年の春方向の移行では、次のような結果になります:

@example
>>> from datetime import datetime, timezone
>>> from tzinfo_examples import HOUR, Eastern
>>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname())
...
05:00:00 UTC = 00:00:00 EST
06:00:00 UTC = 01:00:00 EST
07:00:00 UTC = 03:00:00 EDT
08:00:00 UTC = 04:00:00 EDT
@end example

DST が終了 ("end" ライン) で、更なる問題が潜んでいます: ローカルの実時間で、曖昧さ無しに時を綴れない 1 時間が存在します: それは夏時間の最後の 1 時間です。
東部では、夏時間が終了する日の UTC での 5:MM 形式の時間がそれです。
ローカルの実時間は (夏時間の) 1:59 から (標準時の) 1:00 に再び巻き戻されます。
ローカルの時刻における 1:MM は曖昧です。
そして @ref{bc4,,astimezone()} は 2 つの隣り合う UTC 時間を同じローカルの時間に対応付けて、ローカルの時計の振る舞いを真似ます。
東部の例では、 5:MM および 6:MM という形式の UTC 時刻は両方とも東部時刻に変換された際に 1:MM に対応付けられますが、それ以前の時間は @ref{e51,,fold} 属性を 0 にし、以降の時間では 1 にします。例えば、 2016 年での秋方向の移行では、次のような結果になります:

@example
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
@end example

@ref{e51,,fold} 属性が異なるだけの @ref{4e2,,datetime} インスタンスは比較において等しいとみなされることに注意してください。

壁時間に関する曖昧さは、明示的に @ref{e51,,fold} 属性を検証するか、 @ref{12d5,,timezone} が使用されたハイブリッドな @ref{7f6,,tzinfo} サブクラスか、そのほかの絶対時間差を示す @ref{7f6,,tzinfo} サブクラス(EST (-5 時間の絶対時間差) のみを表すクラスや、 EDT (-4 時間の絶対時間差) のみを表すクラス)を使用すると回避できます。
このような曖昧さを許容できないアプリケーションは、このような手法によって回避すべきです。


@subsubheading 参考


@quotation


@table @asis

@item @ref{13a,,zoneinfo}

@code{datetime} モジュールには (UTC からの任意の固定オフセットを扱う) 基本的な @ref{12d5,,timezone} クラスと、(UTC  @code{timezone} のインスタンスである) @ref{827,,timezone.utc} 属性があります。

@code{zoneinfo} は Python に `IANA タイムゾーンデータベース' (オルソンデータベースとしても知られています) を導入するもので、これを使うことが推奨されています。
@end table
@end quotation


@table @asis

@item IANA タイムゾーンデータベース@footnote{https://www.iana.org/time-zones}

(しばしば tz、tzdata や zoneinfo と呼ばれる) タイムゾーンデータベースはコードとデータを保持しており、それらは地球全体にわたる多くの代表的な場所のローカル時刻の履歴を表しています。政治団体によるタイムゾーンの境界、UTC オフセット、夏時間のルールの変更を反映するため、定期的にデータベースが更新されます。
@end table


@node timezone objects,strftime and strptime behavior,tzinfo objects,datetime --- 基本的な日付と時間の型
@anchor{library/datetime datetime-timezone}@anchor{28f0}@anchor{library/datetime timezone-objects}@anchor{28f1}
@subsubsection @code{timezone} objects


@ref{12d5,,timezone} クラスは @ref{7f6,,tzinfo} のサブクラスで、各インスタンスは UTC からの固定されたオフセットで定義されたタイムゾーンを表しています。

このクラスのオブジェクトは、一年のうち異なる日に異なるオフセットが使われていたり、常用時 (civil time) に歴史的な変化が起きた場所のタイムゾーン情報を表すのには使えないので注意してください。

@geindex timezone (datetime のクラス)
@anchor{library/datetime datetime timezone}@anchor{12d5}
@deffn {クラス} datetime.timezone (offset, name=None)

ローカル時刻と UTC の差分を表す @ref{bc3,,timedelta} オブジェクトを `offset' 引数に指定しなくてはいけません。これは @code{-timedelta(hours=24)} から @code{timedelta(hours=24)} までの両端を含まない範囲に収まっていなくてはなりません。そうでない場合 @ref{2ec,,ValueError} が送出されます。

`name' 引数は必須ではありません。もし指定された場合、その値は @ref{28d4,,datetime.tzname()} メソッドの返り値として使われる文字列でなければなりません。


Added in version 3.2.



バージョン 3.7 で変更: UTC オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex utcoffset() (datetime.timezone のメソッド)
@anchor{library/datetime datetime timezone utcoffset}@anchor{28f2}
@deffn {メソッド} timezone.utcoffset (dt)

@ref{12d5,,timezone} インスタンスが構築されたときに指定された固定値を返します。

`dt' 引数は無視されます。
返り値は、ローカル時刻と UTC の差分に等しい @ref{bc3,,timedelta} インスタンスです。


バージョン 3.7 で変更: UTC オフセットが分単位でなければならない制限が無くなりました。

@end deffn

@geindex tzname() (datetime.timezone のメソッド)
@anchor{library/datetime datetime timezone tzname}@anchor{28f3}
@deffn {メソッド} timezone.tzname (dt)

@ref{12d5,,timezone} インスタンスが構築されたときに指定された固定値を返します。

`name' が構築時に与えられなかった場合、 @code{tzname(dt)} によって返される name は以下の様に @code{offset} の値から生成されます。
`offset' が @code{timedelta(0)} であった場合、 name は "UTC"になります。
それ以外の場合、 'UTC±HH:MM' という書式の文字列になり、± は @code{offset} を、HH と MM はそれぞれ二桁の @code{offset.hours} と @code{offset.minutes} を表現します。


バージョン 3.6 で変更: @code{offset=timedelta(0)} によって生成される名前はプレーンな @cite{'UTC'} であり @code{'UTC+00:00'} ではありません。

@end deffn

@geindex dst() (datetime.timezone のメソッド)
@anchor{library/datetime datetime timezone dst}@anchor{28f4}
@deffn {メソッド} timezone.dst (dt)

常に @code{None} を返します。
@end deffn

@geindex fromutc() (datetime.timezone のメソッド)
@anchor{library/datetime datetime timezone fromutc}@anchor{28f5}
@deffn {メソッド} timezone.fromutc (dt)

@code{dt + offset} を返します。 `dt' 引数は @code{tzinfo} が @code{self} になっている aware な @ref{4e2,,datetime} インスタンスでなければなりません。
@end deffn

以下にクラス属性を示します:

@geindex utc (datetime.timezone の属性)
@anchor{library/datetime datetime timezone utc}@anchor{827}
@deffn {の属性} timezone.utc

UTC タイムゾーン @code{timezone(timedelta(0))} です。
@end deffn

@geindex % (パーセント);datetime format

@node strftime and strptime behavior,,timezone objects,datetime --- 基本的な日付と時間の型
@anchor{library/datetime strftime-and-strptime-behavior}@anchor{28f6}@anchor{library/datetime strftime-strptime-behavior}@anchor{1b54}
@subsubsection @code{strftime()} and @code{strptime()} behavior


@ref{1fa,,date}, @ref{4e2,,datetime}, @ref{1fb,,time} オブジェクトは全て @code{strftime(format)} メソッドをサポートし、時刻を表現する文字列を明示的な書式文字列で統制して作成しています。

Conversely, the @ref{1f9,,date.strptime()}, @ref{1950,,datetime.strptime()} and
@ref{1646,,time.strptime()} class methods create an object from a string
representing the time and a corresponding format string.

下の表は @ref{e8e,,strftime()} と @ref{1950,,strptime()} との高レベルの対比を表しています。


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@tab

@code{strftime}

@tab

@code{strptime}

@item

使用法

@tab

オブジェクトを与えられた書式に従って文字列に変換する

@tab

Parse a string into an object given a corresponding format

@item

メソッドの種類

@tab

インスタンスメソッド

@tab

クラスメソッド

@item

シグネチャ

@tab

@code{strftime(format)}

@tab

@code{strptime(date_string, format)}

@end multitable


@quotation
@anchor{library/datetime format-codes}@anchor{2897}
@end quotation

@menu
* strftime() and strptime() format codes: strftime and strptime format codes. 
* Technical detail:: 

@end menu

@node strftime and strptime format codes,Technical detail,,strftime and strptime behavior
@anchor{library/datetime strftime-and-strptime-format-codes}@anchor{28f7}
@subsubsection @code{strftime()} and @code{strptime()} format codes


These methods accept format codes that can be used to parse and format dates:

@example
>>> datetime.strptime('31/01/22 23:59:59.999999',
...                   '%d/%m/%y %H:%M:%S.%f')
datetime.datetime(2022, 1, 31, 23, 59, 59, 999999)
>>> _.strftime('%a %d %b %Y, %I:%M%p')
'Mon 31 Jan 2022, 11:59PM'
@end example

以下のリストは 1989 C 標準が要求する全ての書式コードで、標準 C 実装があれば全ての環境で動作します。


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

ディレクティブ

@tab

意味

@tab

使用例

@tab

注釈

@item

@code{%a}

@tab

ロケールの曜日名を短縮形で表示します。

@tab


@display
Sun, Mon, ..., Sat (en_US);@w{ }
So, Mo, ..., Sa (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%A}

@tab

ロケールの曜日名を表示します。

@tab


@display
Sunday, Monday, ..., Saturday (en_US);@w{ }
Sonntag, Montag, ..., Samstag (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%w}

@tab

曜日を10進表記した文字列を表示します。0 が日曜日で、6 が土曜日を表します。

@tab

0, 1, ..., 6

@tab

@item

@code{%d}

@tab

0埋めした10進数で表記した月中の日にち。

@tab

01, 02, ..., 31

@tab

(9)

@item

@code{%b}

@tab

ロケールの月名を短縮形で表示します。

@tab


@display
Jan, Feb, ..., Dec (en_US);@w{ }
Jan, Feb, ..., Dez (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%B}

@tab

ロケールの月名を表示します。

@tab


@display
January, February, ..., December (en_US);@w{ }
Januar, Februar, ..., Dezember (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%m}

@tab

0埋めした10進数で表記した月。

@tab

01, 02, ..., 12

@tab

(9)

@item

@code{%y}

@tab

0埋めした10進数で表記した世紀無しの年。

@tab

00, 01, ..., 99

@tab

(9)

@item

@code{%Y}

@tab

西暦 ( 4桁) の 10 進表記を表します。

@tab

0001, 0002, ..., 2013,
2014, ..., 9998, 9999

@tab

(2)

@item

@code{%H}

@tab

0埋めした10進数で表記した時 (24時間表記)。

@tab

00, 01, ..., 23

@tab

(9)

@item

@code{%I}

@tab

0埋めした10進数で表記した時 (12時間表記)。

@tab

01, 02, ..., 12

@tab

(9)

@item

@code{%p}

@tab

ロケールの AM もしくは PM と等価な文字列になります。

@tab


@display
AM, PM (en_US);@w{ }
am, pm (de_DE)@w{ }
@end display



@tab

(1),
(3)

@item

@code{%M}

@tab

0埋めした10進数で表記した分。

@tab

00, 01, ..., 59

@tab

(9)

@item

@code{%S}

@tab

0埋めした10進数で表記した秒。

@tab

00, 01, ..., 59

@tab

(4),
(9)

@item

@code{%f}

@tab

10進数で表記したマイクロ秒 (6桁に0埋めされます)。

@tab

000000, 000001, ...,
999999

@tab

(5)

@item

@code{%z}

@tab

UTCオフセットを @code{±HHMM[SS[.ffffff]]} の形式で表示します (オブジェクトがnaiveであれば空文字列)。

@tab

(空文字列), +0000, -0400, +1030, +063415, -030712.345216

@tab

(6)

@item

@code{%Z}

@tab

タイムゾーンの名前を表示します (オブジェクトがnaiveであれば空文字列)。

@tab

(空文字列), UTC, GMT

@tab

(6)

@item

@code{%j}

@tab

0埋めした10進数で表記した年中の日にち。

@tab

001, 002, ..., 366

@tab

(9)

@item

@code{%U}

@tab

0埋めした10進数で表記した年中の週番号 (週の始まりは日曜日とする)。新年の最初の日曜日に先立つ日は 0週に属するとします。

@tab

00, 01, ..., 53

@tab

(7),
(9)

@item

@code{%W}

@tab

0埋めした10進数で表記した年中の週番号 (週の始まりは月曜日とする)。新年の最初の月曜日に先立つ日は 0週に属するとします。

@tab

00, 01, ..., 53

@tab

(7),
(9)

@item

@code{%c}

@tab

ロケールの日時を適切な形式で表します。

@tab


@display
Tue Aug 16 21:30:00 1988 (en_US);@w{ }
Di 16 Aug 21:30:00 1988 (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%x}

@tab

ロケールの日付を適切な形式で表します。

@tab


@display
08/16/88 (None);@w{ }
08/16/1988 (en_US);@w{ }
16.08.1988 (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%X}

@tab

ロケールの時間を適切な形式で表します。

@tab


@display
21:30:00 (en_US);@w{ }
21:30:00 (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%%}

@tab

文字 @code{'%'} を表します。

@tab

%

@tab

@end multitable


C89規格により要求されない幾つかの追加のコードが便宜上含まれています。これらのパラメータはすべてISO 8601の日付値に対応しています。


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

ディレクティブ

@tab

意味

@tab

使用例

@tab

注釈

@item

@code{%G}

@tab

ISO week(@code{%V})の内過半数を含む西暦表記の ISO 8601 year です。

@tab

0001, 0002, ..., 2013,
2014, ..., 9998, 9999

@tab

(8)

@item

@code{%u}

@tab

1 を月曜日を表す 10進数表記の ISO 8601 weekday です。

@tab

1, 2, ..., 7

@tab

@item

@code{%V}

@tab

週で最初の月曜日を始めとする ISO 8601 week です。Week 01 は 1月4日を含みます。

@tab

01, 02, ..., 53

@tab

(8),
(9)

@item

@code{%:z}

@tab

UTCオフセットを @code{±HH:MM[:SS[.ffffff]]} の形式で表示します (オブジェクトがnaiveであれば空文字列)。

@tab

(空文字列), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216

@tab

(6)

@end multitable


これらが @ref{e8e,,strftime()} メソッドと一緒に使用された場合、すべてのプラットフォームで利用できるわけではありません。 ISO 8601 year 指定子およびISO 8601 week 指定子は、上記のyear および week number 指定子と互換性がありません。不完全またはあいまいなISO 8601 指定子で @ref{1950,,strptime()} を呼び出すと、 @ref{2ec,,ValueError} が送出されます。

Python はプラットフォームの C ライブラリの @code{strftime()} 関数を呼び出していて、プラットフォームごとにその実装が異なるのはよくあることなので、サポートされる書式コード全体はプラットフォームごとに様々です。
手元のプラットフォームでサポートされているフォーマット記号全体を見るには、 @code{strftime(3)@footnote{https://manpages.debian.org/strftime(3)}} のドキュメントを参照してください。
サポートされていないフォーマット指定子の扱いもプラットフォーム間で差異があります。


Added in version 3.6: @code{%G}, @code{%u} および @code{%V} が追加されました。



Added in version 3.12: @code{%:z} が追加されました。


@node Technical detail,,strftime and strptime format codes,strftime and strptime behavior
@anchor{library/datetime technical-detail}@anchor{28f8}
@subsubsection Technical detail


大雑把にいうと、 @code{d.strftime(fmt)} は @ref{f4,,time} モジュールの @code{time.strftime(fmt, d.timetuple())} のように動作します。ただし全てのオブジェクトが @ref{28be,,timetuple()} メソッドをサポートしているわけではありません。

For the @ref{1950,,datetime.strptime()} and @ref{1f9,,date.strptime()} class methods,
the default value is @code{1900-01-01T00:00:00.000}: any components not specified
in the format string will be pulled from the default value.

@cartouche
@quotation 注釈 
Format strings without separators can be ambiguous for parsing. For
example, with @code{%Y%m%d}, the string @code{2026111} may be parsed either as
@code{2026-11-01} or as @code{2026-01-11}.
Use separators to ensure the input is parsed as intended.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
When used to parse partial dates lacking a year, @ref{1950,,datetime.strptime()}
and @ref{1f9,,date.strptime()} will raise when encountering February 29 because
the default year of 1900 is `not' a leap year.  Always add a default leap
year to partial date strings before parsing.
@end quotation
@end cartouche

@c # doctest seems to turn the warning into an error which makes it
@c # show up and require matching and prevents the actual interesting
@c # exception from being raised.
@c # Manually apply the catch_warnings context manager
@c import warnings
@c catch_warnings = warnings.catch_warnings()
@c catch_warnings.__enter__()
@c warnings.simplefilter("ignore")

@c catch_warnings.__exit__()

@example
>>> from datetime import datetime
>>> value = "2/29"
>>> datetime.strptime(value, "%m/%d")
Traceback (most recent call last):
...
ValueError: day 29 must be in range 1..28 for month 2 in year 1900
>>> datetime.strptime(f"1904 @{value@}", "%Y %m/%d")
datetime.datetime(1904, 2, 29, 0, 0)
@end example

@code{datetime.strptime(date_string, format)} は次の式と等価です:

@example
datetime(*(time.strptime(date_string, format)[0:6]))
@end example

ただし、 @code{datetime.strptime} はサポートしているが @code{time.strptime} には無い、秒未満の単位やタイムゾーンオフセットの情報が format に 含まれているときは除きます。

@ref{1fb,,time} オブジェクトには、年、月、日の値がないため、それらを書式コードを使うことができません。
無理矢理使った場合、年は1900に置き換えられ、月と日は1に置き換えられます。

@ref{1fa,,date} オブジェクトには、時、分、秒、マイクロ秒の値がないため、それらの書式コードを使うことができません。
無理矢理使った場合、これらの値は0に置き換えられます。

同じ理由で、現在のロケールの文字集合で表現できない Unicode コードポイントを含む書式文字列の対処もプラットフォーム依存です。
あるプラットフォームではそういったコードポイントはそのまま出力に出される一方、他のプラットフォームでは @code{strftime} が @ref{462,,UnicodeError} を送出したり、その代わりに空文字列を返したりするかもしれません。

注釈:


@enumerate 

@item 
Because the format depends on the current locale, care should be taken when
making assumptions about the output value. Field orderings will vary (for
example, "month/day/year" versus "day/month/year"), and the output may
contain non-ASCII characters.

@item 
@ref{1950,,strptime()} メソッドは [1, 9999] の範囲の年数全てを構文解析できますが、 year < 1000 の範囲の年数は 0 埋めされた 4 桁の数字でなければなりません。


バージョン 3.2 で変更: 以前のバージョンでは、 @ref{e8e,,strftime()} メソッドは years >= 1900 の範囲の年数しか扱えませんでした。



バージョン 3.3 で変更: バージョン 3.2 では、 @ref{e8e,,strftime()} メソッドは years >= 1000 の範囲の年数しか扱えませんでした。


@item 
@ref{1950,,strptime()} メソッドと共に使われた場合、 @code{%p} 指定子は出力の時間フィールドのみに影響し、 @code{%I} 指定子が使われたかのように振る舞います。

@item 
@ref{f4,,time} モジュールと違い、 @code{datetime} モジュールはうるう秒をサポートしていません。

@item 
@ref{1950,,strptime()} メソッドと共に使われた場合、 @code{%f} 指定子は 1 桁から 6 桁の数字を受け付け、右側から0埋めされます。
@code{%f} は C 標準規格の書式文字セットの拡張です (とは言え、 datetime モジュールのオブジェクトそれぞれに実装されているので、どれででも使えます)。

@item 
naive オブジェクトでは、書式コード @code{%z}、@code{%:z} および @code{%Z} は空文字列に置き換えられます。

aware オブジェクトでは次のようになります:


@table @asis

@item @code{%z}

@ref{28d1,,utcoffset()} は @code{±HHMM[SS[.ffffff]]} 形式の文字列に変換されます。ここで、 @code{HH} は UTC オフセットの時間を表す 2 桁の文字列、 @code{MM} は UTC オフセットの分数を表す 2 桁の文字列、 @code{SS} は UTC オフセットの秒数を表す 2 桁の文字列、 @code{ffffff} は UTC オフセットのマイクロ秒数を表す 6 桁の文字列です。
オフセットに秒未満の端数が無いときは @code{ffffff} 部分は省略され、オフセットに分未満の端数が無いときは @code{ffffff} 部分も @code{SS} 部分も省略されます。
例えば、 @ref{28d1,,utcoffset()} が @code{timedelta(hours=-3, minutes=-30)} を返す場合、 @code{%z} は文字列 @code{'-0330'} に置き換えられます。
@end table


バージョン 3.7 で変更: UTC オフセットが分単位でなければならない制限が無くなりました。



バージョン 3.7 で変更: @code{%z} 指定子が @ref{1950,,strptime()} メソッドに渡されたときは、時分秒のセパレータとしてコロンが UTC オフセットで使えます。
例えば、 @code{'+01:00:00'} は 1 時間のオフセットだと構文解析されます。
加えて、 @code{'Z'} を渡すことは @code{'+00:00'} を渡すことと同等です。



@table @asis

@item @code{%:z}

Behaves exactly as @code{%z}, but has a colon separator added between
hours, minutes and seconds.

@item @code{%Z}

In @ref{e8e,,strftime()}, @code{%Z} is replaced by an empty string if
@ref{28d4,,tzname()} returns @code{None}; otherwise @code{%Z} is replaced by the
returned value, which must be a string.

@ref{1950,,strptime()} は @code{%Z} に特定の値のみを受け入れます:


@enumerate 

@item 
使用しているマシンのロケールによる @code{time.tzname} の任意の値

@item 
ハードコードされた値 @code{UTC} または @code{GMT}
@end enumerate

つまり、日本に住んでいる場合は @code{JST}, @code{UTC} と @code{GMT} が有効な値であり、 @code{EST} はおそらく無効な値となります。無効な値の場合は @code{ValueError} を送出します。
@end table


バージョン 3.2 で変更: @code{%z} 指定子が @ref{1950,,strptime()} メソッドに与えられた場合、 aware な @ref{4e2,,datetime} オブジェクトが作成されます。返り値の @code{tzinfo} は @ref{12d5,,timezone} インスタンスになっています。


@item 
@ref{1950,,strptime()} メソッドと共に使われた場合、 @code{%U} と @code{%W} 指定子は、曜日と年(@code{%Y})が指定された場合の計算でのみ使われます。

@item 
@code{%U} および @code{%W} と同様に、 @code{%V} は曜日と ISO 年 (@code{%G}) が @ref{1950,,strptime()} の書式文字列の中で指定された場合に計算でのみ使われます。
@code{%G} と @code{%Y} は互いに完全な互換性を持たないことにも注意してください。

@item 
@ref{1950,,strptime()} メソッドと共に使われるとき、書式 @code{%d}, @code{%m}, @code{%H}, @code{%I}, @code{%M}, @code{%S}, @code{%j}, @code{%U}, @code{%W}, @code{%V} では先行ゼロは任意です。
書式 @code{%y} では先行ゼロは必須です。

@item 
When parsing a month and day using @ref{1950,,strptime()}, always
include a year in the format.  If the value you need to parse lacks a year,
append an explicit dummy leap year.  Otherwise your code will raise an
exception when it encounters leap day because the default year used by the
parser (1900) is not a leap year.  Users run into that bug every leap year.

@example
>>> month_day = "02/29"
>>> datetime.strptime(f"@{month_day@};1984", "%m/%d;%Y")  # No leap year bug.
datetime.datetime(1984, 2, 29, 0, 0)
@end example


Deprecated since version 3.13, will be removed in version 3.15: @ref{1950,,strptime()} calls using a format string containing
a day of month without a year now emit a
@ref{1a3,,DeprecationWarning}. In 3.15 or later we may change this into
an error or change the default year to a leap year. See gh-70647@footnote{https://github.com/python/cpython/issues/70647}.

@end enumerate

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node zoneinfo --- IANA タイムゾーンのサポート,calendar --- 一般的なカレンダーに関係する機能群,datetime --- 基本的な日付と時間の型,データ型
@anchor{library/zoneinfo doc}@anchor{28f9}@anchor{library/zoneinfo module-zoneinfo}@anchor{13a}@anchor{library/zoneinfo translation-repo}@anchor{28fa}@anchor{library/zoneinfo zoneinfo-iana-time-zone-support}@anchor{28fb}
@subsection @code{zoneinfo} --- IANA タイムゾーンのサポート


@geindex module; zoneinfo


Added in version 3.9.


`ソースコード:' Lib/zoneinfo@footnote{https://github.com/python/cpython/tree/3.14/Lib/zoneinfo}


__________________________________________________________________


The @code{zoneinfo} module provides a concrete time zone implementation to
support the IANA time zone database as originally specified in 
@geindex Python Enhancement Proposals; PEP 615
PEP 615@footnote{https://peps.python.org/pep-0615/}. By
default, @code{zoneinfo} uses the system's time zone data if available; if no
system time zone data is available, the library will fall back to using the
first-party tzdata@footnote{https://pypi.org/project/tzdata/} package available on PyPI.


@subsubheading 参考



@table @asis

@item モジュール: @ref{34,,datetime}

@ref{adc,,ZoneInfo} クラスを使用するように設計されたデータ型 @ref{1fb,,time} と @ref{4e2,,datetime} を提供します。

@item tzdata@footnote{https://pypi.org/project/tzdata/} パッケージ

CPythonコアデベロッパーによってメンテナンスされているファーストパーティーのパッケージ。タイムゾーンデータを供給し、PyPIで配布されている。
@end table


@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@menu
* ZoneInfo を使用する:: 
* データソース:: 
* ZoneInfo クラス:: 
* 関数: 関数<3>. 
* Globals:: 
* 例外と警告:: 

@end menu

@node ZoneInfo を使用する,データソース,,zoneinfo --- IANA タイムゾーンのサポート
@anchor{library/zoneinfo using-zoneinfo}@anchor{28fc}
@subsubsection @code{ZoneInfo} を使用する


@ref{adc,,ZoneInfo} は @ref{7f6,,datetime.tzinfo} 抽象基底クラスの具体的な実装であり、@code{tzinfo} に指定することを想定しています。コンストラクタ、@ref{16e4,,datetime.replace} メソッド、@ref{bc4,,datetime.astimezone} メソッドのいずれかで指定します。

@example
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta

>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00

>>> dt.tzname()
'PDT'
@end example

Datetimes constructed in this way are compatible with datetime arithmetic and
handle daylight saving time transitions with no further intervention:

@example
>>> dt_add = dt + timedelta(days=1)

>>> print(dt_add)
2020-11-01 12:00:00-08:00

>>> dt_add.tzname()
'PST'
@end example

These time zones also support the @ref{e51,,fold} attribute
introduced in 
@geindex Python Enhancement Proposals; PEP 495
PEP 495@footnote{https://peps.python.org/pep-0495/}.  During offset transitions which induce ambiguous
times (such as a daylight saving time to standard time transition), the offset
from `before' the transition is used when @code{fold=0}, and the offset `after'
the transition is used when @code{fold=1}, for example:

@example
>>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-11-01 01:00:00-07:00

>>> print(dt.replace(fold=1))
2020-11-01 01:00:00-08:00
@end example

When converting from another time zone, the fold will be set to the correct
value:

@example
>>> from datetime import timezone
>>> LOS_ANGELES = ZoneInfo("America/Los_Angeles")
>>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)

>>> # Before the PDT -> PST transition
>>> print(dt_utc.astimezone(LOS_ANGELES))
2020-11-01 01:00:00-07:00

>>> # After the PDT -> PST transition
>>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))
2020-11-01 01:00:00-08:00
@end example

@node データソース,ZoneInfo クラス,ZoneInfo を使用する,zoneinfo --- IANA タイムゾーンのサポート
@anchor{library/zoneinfo data-sources}@anchor{28fd}
@subsubsection データソース


The @code{zoneinfo} module does not directly provide time zone data, and instead
pulls time zone information from the system time zone database or the
first-party PyPI package tzdata@footnote{https://pypi.org/project/tzdata/}, if available. Some systems, including
notably Windows systems, do not have an IANA database available, and so for
projects targeting cross-platform compatibility that require time zone data, it
is recommended to declare a dependency on tzdata. If neither system data nor
tzdata are available, all calls to @ref{adc,,ZoneInfo} will raise
@ref{1816,,ZoneInfoNotFoundError}.

@menu
* Configuring the data sources:: 

@end menu

@node Configuring the data sources,,,データソース
@anchor{library/zoneinfo configuring-the-data-sources}@anchor{28fe}@anchor{library/zoneinfo zoneinfo-data-configuration}@anchor{28ff}
@subsubsection Configuring the data sources


When @code{ZoneInfo(key)} is called, the constructor first searches the
directories specified in @ref{2166,,TZPATH} for a file matching @code{key}, and on
failure looks for a match in the tzdata package. This behavior can be
configured in three ways:


@enumerate 

@item 
The default @ref{2166,,TZPATH} when not otherwise specified can be configured at
@ref{2167,,compile time}.

@item 
@ref{2166,,TZPATH} can be configured using @ref{2900,,an environment variable}.

@item 
At @ref{2901,,runtime}, the search path can be
manipulated using the @ref{17c0,,reset_tzpath()} function.
@end enumerate

@menu
* Compile-time configuration:: 
* Environment configuration:: 
* Runtime configuration:: 

@end menu

@node Compile-time configuration,Environment configuration,,Configuring the data sources
@anchor{library/zoneinfo compile-time-configuration}@anchor{2902}@anchor{library/zoneinfo zoneinfo-data-compile-time-config}@anchor{2167}
@subsubsection Compile-time configuration


The default @ref{2166,,TZPATH} includes several common deployment locations for the
time zone database (except on Windows, where there are no "well-known"
locations for time zone data). On POSIX systems, downstream distributors and
those building Python from source who know where their system
time zone data is deployed may change the default time zone path by specifying
the compile-time option @code{TZPATH} (or, more likely, the @ref{2165,,configure flag --with-tzpath}), which should be a string delimited by
@ref{2134,,os.pathsep}.

On all platforms, the configured value is available as the @code{TZPATH} key in
@ref{174,,sysconfig.get_config_var()}.

@node Environment configuration,Runtime configuration,Compile-time configuration,Configuring the data sources
@anchor{library/zoneinfo environment-configuration}@anchor{2903}@anchor{library/zoneinfo zoneinfo-data-environment-var}@anchor{2900}
@subsubsection Environment configuration


When initializing @ref{2166,,TZPATH} (either at import time or whenever
@ref{17c0,,reset_tzpath()} is called with no arguments), the @code{zoneinfo} module will
use the environment variable @code{PYTHONTZPATH}, if it exists, to set the search
path.

@geindex 環境変数; PYTHONTZPATH
@anchor{library/zoneinfo envvar-PYTHONTZPATH}@anchor{2904}
@deffn {環境変数} PYTHONTZPATH

This is an @ref{2134,,os.pathsep}-separated string containing the time zone
search path to use. It must consist of only absolute rather than relative
paths. Relative components specified in @code{PYTHONTZPATH} will not be used,
but otherwise the behavior when a relative path is specified is
implementation-defined; CPython will raise @ref{2905,,InvalidTZPathWarning}, but
other implementations are free to silently ignore the erroneous component
or raise an exception.
@end deffn

To set the system to ignore the system data and use the tzdata package
instead, set @code{PYTHONTZPATH=""}.

@node Runtime configuration,,Environment configuration,Configuring the data sources
@anchor{library/zoneinfo runtime-configuration}@anchor{2906}@anchor{library/zoneinfo zoneinfo-data-runtime-config}@anchor{2901}
@subsubsection Runtime configuration


The TZ search path can also be configured at runtime using the
@ref{17c0,,reset_tzpath()} function. This is generally not an advisable operation,
though it is reasonable to use it in test functions that require the use of a
specific time zone path (or require disabling access to the system time zones).

@node ZoneInfo クラス,関数<3>,データソース,zoneinfo --- IANA タイムゾーンのサポート
@anchor{library/zoneinfo the-zoneinfo-class}@anchor{2907}
@subsubsection @code{ZoneInfo} クラス


@geindex ZoneInfo (zoneinfo のクラス)
@anchor{library/zoneinfo zoneinfo ZoneInfo}@anchor{adc}
@deffn {クラス} zoneinfo.ZoneInfo (key)

文字列 @code{key} でIANAタイムゾーンを指定した、具体的な @ref{7f6,,datetime.tzinfo} のサブクラス。Calls to the primary constructor will always return objects that compare identically; put another way, barring cache invalidation via @ref{2908,,ZoneInfo.clear_cache()}, for all values of @code{key}, the following assertion will always be true:

@example
a = ZoneInfo(key)
b = ZoneInfo(key)
assert a is b
@end example

@code{key} must be in the form of a relative, normalized POSIX path, with no
up-level references. The constructor will raise @ref{2ec,,ValueError} if a
non-conforming key is passed.

@code{key} に一致するファイルが見つからない場合、コンストラクタは @ref{1816,,ZoneInfoNotFoundError} を送出します。
@end deffn

@code{ZoneInfo} クラスには2つの別のコンストラクターがあります:

@geindex from_file() (zoneinfo.ZoneInfo のクラスメソッド)
@anchor{library/zoneinfo zoneinfo ZoneInfo from_file}@anchor{177c}
@deffn {メソッド} classmethod ZoneInfo.from_file (file_obj, /, key=None)

file-like オブジェクトが返すbytes（バイナリーモードで開いたファイルや @ref{10a4,,io.BytesIO} オブジェクト）から @code{ZoneInfo}  オブジェクトを構築します。一次コンストラクタと異なり、常に新規オブジェクトを構築します。

The @code{key} parameter sets the name of the zone for the purposes of
@ref{830,,__str__()} and @ref{82f,,__repr__()}.

このコンストラクタで生成したオブジェクトはpickle化できません（@ref{2909,,pickling} を参照）。

@ref{2ec,,ValueError} is raised if the data read from `file_obj' is not a valid
TZif file.
@end deffn

@geindex no_cache() (zoneinfo.ZoneInfo のクラスメソッド)
@anchor{library/zoneinfo zoneinfo ZoneInfo no_cache}@anchor{290a}
@deffn {メソッド} classmethod ZoneInfo.no_cache (key)

An alternate constructor that bypasses the constructor's cache. It is
identical to the primary constructor, but returns a new object on each
call. This is most likely to be useful for testing or demonstration
purposes, but it can also be used to create a system with a different cache
invalidation strategy.

Objects created via this constructor will also bypass the cache of a
deserializing process when unpickled.

@c TODO: Add "See `cache_behavior`_" reference when that section is ready.

@cartouche
@quotation 注意 
Using this constructor may change the semantics of your datetimes in
surprising ways, only use it if you know that you need to.
@end quotation
@end cartouche
@end deffn

次のクラスメソッドもサポートされています:

@geindex clear_cache() (zoneinfo.ZoneInfo のクラスメソッド)
@anchor{library/zoneinfo zoneinfo ZoneInfo clear_cache}@anchor{2908}
@deffn {メソッド} classmethod ZoneInfo.clear_cache (*, only_keys=None)

A method for invalidating the cache on the @code{ZoneInfo} class. If no
arguments are passed, all caches are invalidated and the next call to
the primary constructor for each key will return a new instance.

If an iterable of key names is passed to the @code{only_keys} parameter, only
the specified keys will be removed from the cache. Keys passed to
@code{only_keys} but not found in the cache are ignored.

@c TODO: Add "See `cache_behavior`_" reference when that section is ready.

@cartouche
@quotation 警告 
Invoking this function may change the semantics of datetimes using
@code{ZoneInfo} in surprising ways; this modifies module state
and thus may have wide-ranging effects. Only use it if you know that you
need to.
@end quotation
@end cartouche
@end deffn

The class has one attribute:

@geindex key (zoneinfo.ZoneInfo の属性)
@anchor{library/zoneinfo zoneinfo ZoneInfo key}@anchor{290b}
@deffn {の属性} ZoneInfo.key

This is a read-only @ref{290c,,attribute} that returns the value of @code{key}
passed to the constructor, which should be a lookup key in the IANA time
zone database (e.g. @code{America/New_York}, @code{Europe/Paris} or
@code{Asia/Tokyo}).

For zones constructed from file without specifying a @code{key} parameter,
this will be set to @code{None}.

@cartouche
@quotation 注釈 
Although it is a somewhat common practice to expose these to end users,
these values are designed to be primary keys for representing the
relevant zones and not necessarily user-facing elements.  Projects like
CLDR (the Unicode Common Locale Data Repository) can be used to get
more user-friendly strings from these keys.
@end quotation
@end cartouche
@end deffn

@menu
* 文字列表現:: 
* Pickle serialization:: 

@end menu

@node 文字列表現,Pickle serialization,,ZoneInfo クラス
@anchor{library/zoneinfo string-representations}@anchor{290d}
@subsubsection 文字列表現


The string representation returned when calling @ref{169,,str} on a
@ref{adc,,ZoneInfo} object defaults to using the @ref{290b,,ZoneInfo.key} attribute (see
the note on usage in the attribute documentation):

@example
>>> zone = ZoneInfo("Pacific/Kwajalein")
>>> str(zone)
'Pacific/Kwajalein'

>>> dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone)
>>> f"@{dt.isoformat()@} [@{dt.tzinfo@}]"
'2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]'
@end example

For objects constructed from a file without specifying a @code{key} parameter,
@code{str} falls back to calling @ref{1c1,,repr()}. @code{ZoneInfo}'s @code{repr} is
implementation-defined and not necessarily stable between versions, but it is
guaranteed not to be a valid @code{ZoneInfo} key.

@node Pickle serialization,,文字列表現,ZoneInfo クラス
@anchor{library/zoneinfo pickle-serialization}@anchor{290e}@anchor{library/zoneinfo pickling}@anchor{2909}
@subsubsection Pickle serialization


Rather than serializing all transition data, @code{ZoneInfo} objects are
serialized by key, and @code{ZoneInfo} objects constructed from files (even those
with a value for @code{key} specified) cannot be pickled.

The behavior of a @code{ZoneInfo} file depends on how it was constructed:


@enumerate 

@item 
@code{ZoneInfo(key)}: When constructed with the primary constructor, a
@code{ZoneInfo} object is serialized by key, and when deserialized, the
deserializing process uses the primary and thus it is expected that these
are the same object as other references to the same time
zone.  For example, if @code{europe_berlin_pkl} is a string containing a pickle
constructed from @code{ZoneInfo("Europe/Berlin")}, one would expect the
following behavior:

@example
>>> a = ZoneInfo("Europe/Berlin")
>>> b = pickle.loads(europe_berlin_pkl)
>>> a is b
True
@end example

@item 
@code{ZoneInfo.no_cache(key)}: When constructed from the cache-bypassing
constructor, the @code{ZoneInfo} object is also serialized by key, but when
deserialized, the deserializing process uses the cache bypassing
constructor. If @code{europe_berlin_pkl_nc} is a string containing a pickle
constructed from @code{ZoneInfo.no_cache("Europe/Berlin")}, one would expect
the following behavior:

@example
>>> a = ZoneInfo("Europe/Berlin")
>>> b = pickle.loads(europe_berlin_pkl_nc)
>>> a is b
False
@end example

@item 
@code{ZoneInfo.from_file(file_obj, /, key=None)}: When constructed from a file, the
@code{ZoneInfo} object raises an exception on pickling. If an end user wants to
pickle a @code{ZoneInfo} constructed from a file, it is recommended that they
use a wrapper type or a custom serialization function: either serializing by
key or storing the contents of the file object and serializing that.
@end enumerate

This method of serialization requires that the time zone data for the required
key be available on both the serializing and deserializing side, similar to the
way that references to classes and functions are expected to exist in both the
serializing and deserializing environments. It also means that no guarantees
are made about the consistency of results when unpickling a @code{ZoneInfo}
pickled in an environment with a different version of the time zone data.

@node 関数<3>,Globals,ZoneInfo クラス,zoneinfo --- IANA タイムゾーンのサポート
@anchor{library/zoneinfo functions}@anchor{290f}
@subsubsection 関数


@geindex available_timezones() (zoneinfo モジュール)
@anchor{library/zoneinfo zoneinfo available_timezones}@anchor{1d48}
@deffn {の関数} zoneinfo.available_timezones ()

Get a set containing all the valid keys for IANA time zones available
anywhere on the time zone path. This is recalculated on every call to the
function.

This function only includes canonical zone names and does not include
"special" zones such as those under the @code{posix/} and @code{right/}
directories, or the @code{posixrules} zone.

@cartouche
@quotation 注意 
This function may open a large number of files, as the best way to
determine if a file on the time zone path is a valid time zone is to
read the "magic string" at the beginning.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
These values are not designed to be exposed to end-users; for user
facing elements, applications should use something like CLDR (the
Unicode Common Locale Data Repository) to get more user-friendly
strings. See also the cautionary note on @ref{290b,,ZoneInfo.key}.
@end quotation
@end cartouche
@end deffn

@geindex reset_tzpath() (zoneinfo モジュール)
@anchor{library/zoneinfo zoneinfo reset_tzpath}@anchor{17c0}
@deffn {の関数} zoneinfo.reset_tzpath (to=None)

Sets or resets the time zone search path (@ref{2166,,TZPATH}) for the module.
When called with no arguments, @ref{2166,,TZPATH} is set to the default value.

Calling @code{reset_tzpath} will not invalidate the @ref{adc,,ZoneInfo} cache,
and so calls to the primary @code{ZoneInfo} constructor will only use the new
@code{TZPATH} in the case of a cache miss.

The @code{to} parameter must be a @ref{716,,sequence} of strings or
@ref{e4b,,os.PathLike} and not a string, all of which must be absolute paths.
@ref{2ec,,ValueError} will be raised if something other than an absolute path
is passed.
@end deffn

@node Globals,例外と警告,関数<3>,zoneinfo --- IANA タイムゾーンのサポート
@anchor{library/zoneinfo globals}@anchor{2910}
@subsubsection Globals


@geindex TZPATH (zoneinfo モジュール)
@anchor{library/zoneinfo zoneinfo TZPATH}@anchor{2166}
@deffn {データ} zoneinfo.TZPATH

A read-only sequence representing the time zone search path -- when
constructing a @code{ZoneInfo} from a key, the key is joined to each entry in
the @code{TZPATH}, and the first file found is used.

@code{TZPATH} may contain only absolute paths, never relative paths,
regardless of how it is configured.

The object that @code{zoneinfo.TZPATH} points to may change in response to a
call to @ref{17c0,,reset_tzpath()}, so it is recommended to use
@code{zoneinfo.TZPATH} rather than importing @code{TZPATH} from @code{zoneinfo} or
assigning a long-lived variable to @code{zoneinfo.TZPATH}.

For more information on configuring the time zone search path, see
@ref{28ff,,Configuring the data sources}.
@end deffn

@node 例外と警告,,Globals,zoneinfo --- IANA タイムゾーンのサポート
@anchor{library/zoneinfo exceptions-and-warnings}@anchor{2911}
@subsubsection 例外と警告


@geindex ZoneInfoNotFoundError
@anchor{library/zoneinfo zoneinfo ZoneInfoNotFoundError}@anchor{1816}
@deffn {例外} zoneinfo.ZoneInfoNotFoundError

Raised when construction of a @ref{adc,,ZoneInfo} object fails because the
specified key could not be found on the system. This is a subclass of
@ref{5e7,,KeyError}.
@end deffn

@geindex InvalidTZPathWarning
@anchor{library/zoneinfo zoneinfo InvalidTZPathWarning}@anchor{2905}
@deffn {例外} zoneinfo.InvalidTZPathWarning

Raised when 
@geindex PYTHONTZPATH
@geindex 環境変数; PYTHONTZPATH
@ref{2904,,PYTHONTZPATH} contains an invalid component that will
be filtered out, such as a relative path.
@end deffn

@c Links and references:

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node calendar --- 一般的なカレンダーに関係する機能群,collections --- コンテナデータ型,zoneinfo --- IANA タイムゾーンのサポート,データ型
@anchor{library/calendar doc}@anchor{2912}@anchor{library/calendar calendar-general-calendar-related-functions}@anchor{2913}@anchor{library/calendar module-calendar}@anchor{15}@anchor{library/calendar translation-repo}@anchor{2914}
@subsection @code{calendar} --- 一般的なカレンダーに関係する機能群


@geindex module; calendar

`ソースコード:' Lib/calendar.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/calendar.py}


__________________________________________________________________


このモジュールは Unix の @code{cal} プログラムのようなカレンダー出力を行い、それに加えてカレンダーに関する有益な関数群を提供します。標準ではこれらのカレンダーは（ヨーロッパの慣例に従って）月曜日を週の始まりとし、日曜日を最後の日としています。 @ref{2915,,setfirstweekday()} を用いることで、日曜日(6)や他の曜日を週の始まりに設定することができます。日付を表す引数は整数値で与えます。関連する機能として、 @ref{34,,datetime} と @ref{f4,,time} モジュールも参照してください。

このモジュールに定義された関数やクラスは理想化されたカレンダー、つまり現在のグレゴリオ暦を過去と未来両方に無限に拡張したものを使っています。これはすべての計算の基礎のカレンダーとなっている、 Dershowitz と Reingold の本 "Calendrical Calculations" 中の "proleptic Gregorian" のカレンダーの定義に合致します。ゼロと負の年は ISO 8601 の基準に定められている通りに扱われます。0 年は 1 BC、-1 年は 2 BC、のように続きます。

@geindex Calendar (calendar のクラス)
@anchor{library/calendar calendar Calendar}@anchor{2916}
@deffn {クラス} calendar.Calendar (firstweekday=0)

@ref{2916,,Calendar} オブジェクトを作ります。 `firstweekday' は整数で週の始まりの曜日を指定するものです。@ref{2917,,MONDAY} が @code{0} (デフォルト)、@ref{2918,,SUNDAY} なら @code{6} です。

@ref{2916,,Calendar} オブジェクトは整形されるカレンダーのデータを準備するために使えるいくつかのメソッドを提供しています。しかし整形機能そのものは提供していません。それはサブクラスの仕事なのです。

@ref{2916,,Calendar} instances have the following methods and attributes:

@geindex firstweekday (calendar.Calendar の属性)
@anchor{library/calendar calendar Calendar firstweekday}@anchor{2919}
@deffn {の属性} firstweekday

The first weekday as an integer (0--6).

This property can also be set and read using
@ref{291a,,setfirstweekday()} and
@ref{291b,,getfirstweekday()} respectively.
@end deffn

@geindex getfirstweekday() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar getfirstweekday}@anchor{291b}
@deffn {メソッド} getfirstweekday ()

Return an @ref{19b,,int} for the current first weekday (0--6).

Identical to reading the @ref{2919,,firstweekday} property.
@end deffn

@geindex setfirstweekday() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar setfirstweekday}@anchor{291a}
@deffn {メソッド} setfirstweekday (firstweekday)

Set the first weekday to `firstweekday', passed as an @ref{19b,,int} (0--6)

Identical to setting the @ref{2919,,firstweekday} property.
@end deffn

@geindex iterweekdays() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar iterweekdays}@anchor{291c}
@deffn {メソッド} iterweekdays ()

Return an iterator for the week day numbers that will be used for one
week.  The first value from the iterator will be the same as the value of
the @ref{2919,,firstweekday} property.
@end deffn

@geindex itermonthdates() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar itermonthdates}@anchor{e13}
@deffn {メソッド} itermonthdates (year, month)

`year' 年 `month' (1--12) 月に対するイテレータを返します。
このイテレータはその月の全ての日、およびその月が始まる前の日とその月が終わった後の日のうち、週の欠けを埋めるために必要な日を (@ref{1fa,,datetime.date} オブジェクトとして) 返します。
@end deffn

@geindex itermonthdays() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar itermonthdays}@anchor{291d}
@deffn {メソッド} itermonthdays (year, month)

Return an iterator for the month `month' in the year `year' similar to
@ref{e13,,itermonthdates()}, but not restricted by the @ref{1fa,,datetime.date}
range. Days returned will simply be day of the month numbers.  For the
days outside of the specified month, the day number is @code{0}.
@end deffn

@geindex itermonthdays2() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar itermonthdays2}@anchor{291e}
@deffn {メソッド} itermonthdays2 (year, month)

Return an iterator for the month `month' in the year `year' similar to
@ref{e13,,itermonthdates()}, but not restricted by the @ref{1fa,,datetime.date}
range. Days returned will be tuples consisting of a day of the month
number and a week day number.
@end deffn

@geindex itermonthdays3() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar itermonthdays3}@anchor{e14}
@deffn {メソッド} itermonthdays3 (year, month)

Return an iterator for the month `month' in the year `year' similar to
@ref{e13,,itermonthdates()}, but not restricted by the @ref{1fa,,datetime.date}
range. Days returned will be tuples consisting of a year, a month and a day
of the month numbers.


Added in version 3.7.

@end deffn

@geindex itermonthdays4() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar itermonthdays4}@anchor{e15}
@deffn {メソッド} itermonthdays4 (year, month)

Return an iterator for the month `month' in the year `year' similar to
@ref{e13,,itermonthdates()}, but not restricted by the @ref{1fa,,datetime.date}
range. Days returned will be tuples consisting of a year, a month, a day
of the month, and a day of the week numbers.


Added in version 3.7.

@end deffn

@geindex monthdatescalendar() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar monthdatescalendar}@anchor{291f}
@deffn {メソッド} monthdatescalendar (year, month)

`year' 年 `month' 月の週のリストを返します。週は全て七つの @ref{1fa,,datetime.date} オブジェクトからなるリストです。
@end deffn

@geindex monthdays2calendar() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar monthdays2calendar}@anchor{2920}
@deffn {メソッド} monthdays2calendar (year, month)

`year' 年 `month' 月の週のリストを返します。週は全て七つの日付の数字と曜日を表す数字のタプルからなるリストです。
@end deffn

@geindex monthdayscalendar() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar monthdayscalendar}@anchor{2921}
@deffn {メソッド} monthdayscalendar (year, month)

`year' 年 `month' 月の週のリストを返します。週は全て七つの日付の数字からなるリストです。
@end deffn

@geindex yeardatescalendar() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar yeardatescalendar}@anchor{2922}
@deffn {メソッド} yeardatescalendar (year, width=3)

指定された年のデータを整形に向く形で返します。返される値は月の並びのリストです。月の並びは最大で `width' ヶ月(デフォルトは3ヶ月)分です。各月は4ないし6週からなり、各週は1ないし7日からなります。各日は @ref{1fa,,datetime.date} オブジェクトです。
@end deffn

@geindex yeardays2calendar() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar yeardays2calendar}@anchor{2923}
@deffn {メソッド} yeardays2calendar (year, width=3)

指定された年のデータを整形に向く形で返します (@ref{2922,,yeardatescalendar()} と同様です)。週のリストの中が日付の数字と曜日の数字のタプルになります。月の範囲外の部分の日付はゼロです。
@end deffn

@geindex yeardayscalendar() (calendar.Calendar のメソッド)
@anchor{library/calendar calendar Calendar yeardayscalendar}@anchor{2924}
@deffn {メソッド} yeardayscalendar (year, width=3)

指定された年のデータを整形に向く形で返します (@ref{2922,,yeardatescalendar()} と同様です)。週のリストの中が日付の数字になります。月の範囲外の日付はゼロです。
@end deffn
@end deffn

@geindex TextCalendar (calendar のクラス)
@anchor{library/calendar calendar TextCalendar}@anchor{18aa}
@deffn {クラス} calendar.TextCalendar (firstweekday=0)

このクラスはプレインテキストのカレンダーを生成するのに使えます。

@ref{18aa,,TextCalendar} インスタンスには以下のメソッドがあります:

@geindex formatday() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar formatday}@anchor{2925}
@deffn {メソッド} formatday (theday, weekday, width)

Return a string representing a single day formatted with the given `width'.
If `theday' is @code{0}, return a string of spaces of
the specified width, representing an empty day. The `weekday' parameter
is unused.
@end deffn

@geindex formatweek() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar formatweek}@anchor{2926}
@deffn {メソッド} formatweek (theweek, w=0)

Return a single week in a string with no newline. If `w' is provided, it
specifies the width of the date columns, which are centered. Depends
on the first weekday as specified in the constructor or set by the
@ref{2915,,setfirstweekday()} method.
@end deffn

@geindex formatweekday() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar formatweekday}@anchor{2927}
@deffn {メソッド} formatweekday (weekday, width)

Return a string representing the name of a single weekday formatted to
the specified `width'. The `weekday' parameter is an integer representing
the day of the week, where @code{0} is Monday and @code{6} is Sunday.
@end deffn

@geindex formatweekheader() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar formatweekheader}@anchor{2928}
@deffn {メソッド} formatweekheader (width)

Return a string containing the header row of weekday names, formatted
with the given `width' for each column. The names depend on the locale
settings and are padded to the specified width.
@end deffn

@geindex formatmonth() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar formatmonth}@anchor{2929}
@deffn {メソッド} formatmonth (theyear, themonth, w=0, l=0)

ひと月分のカレンダーを複数行の文字列で返します。 `w' により日の列幅を変えることができ、それらは中央揃えされます。 `l' により各週の表示される行数を変えることができます。 @ref{2915,,setfirstweekday()} メソッドでセットされた週の最初の曜日に依存します。
@end deffn

@geindex formatmonthname() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar formatmonthname}@anchor{292a}
@deffn {メソッド} formatmonthname (theyear, themonth, width=0, withyear=True)

Return a string representing the month's name centered within the
specified `width'. If `withyear' is @code{True}, include the year in the
output. The `theyear' and `themonth' parameters specify the year
and month for the name to be formatted respectively.
@end deffn

@geindex prmonth() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar prmonth}@anchor{292b}
@deffn {メソッド} prmonth (theyear, themonth, w=0, l=0)

@ref{2929,,formatmonth()} で返されるひと月分のカレンダーを出力します。
@end deffn

@geindex formatyear() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar formatyear}@anchor{292c}
@deffn {メソッド} formatyear (theyear, w=2, l=1, c=6, m=3)

`m' 列からなる一年間のカレンダーを複数行の文字列で返します。任意の引数 `w', `l', `c' はそれぞれ、日付列の表示幅、各週の行数及び月と月の間のスペースの数を変更するためのものです。 @ref{2915,,setfirstweekday()} メソッドでセットされた週の最初の曜日に依存します。カレンダーを出力できる最初の年はプラットフォームに依存します。
@end deffn

@geindex pryear() (calendar.TextCalendar のメソッド)
@anchor{library/calendar calendar TextCalendar pryear}@anchor{292d}
@deffn {メソッド} pryear (theyear, w=2, l=1, c=6, m=3)

@ref{292c,,formatyear()} で返される一年間のカレンダーを出力します。
@end deffn
@end deffn

@geindex HTMLCalendar (calendar のクラス)
@anchor{library/calendar calendar HTMLCalendar}@anchor{d18}
@deffn {クラス} calendar.HTMLCalendar (firstweekday=0)

このクラスは HTML のカレンダーを生成するのに使えます。

@code{HTMLCalendar} インスタンスには以下のメソッドがあります:

@geindex formatmonth() (calendar.HTMLCalendar のメソッド)
@anchor{library/calendar calendar HTMLCalendar formatmonth}@anchor{292e}
@deffn {メソッド} formatmonth (theyear, themonth, withyear=True)

ひと月分のカレンダーを HTML のテーブルとして返します。`withyear' が真であればヘッダには年も含まれます。そうでなければ月の名前だけが使われます。
@end deffn

@geindex formatyear() (calendar.HTMLCalendar のメソッド)
@anchor{library/calendar calendar HTMLCalendar formatyear}@anchor{292f}
@deffn {メソッド} formatyear (theyear, width=3)

一年分のカレンダーを HTML のテーブルとして返します。`width' の値 (デフォルトでは 3 です) は何ヶ月分を一行に収めるかを指定します。
@end deffn

@geindex formatyearpage() (calendar.HTMLCalendar のメソッド)
@anchor{library/calendar calendar HTMLCalendar formatyearpage}@anchor{2930}
@deffn {メソッド} formatyearpage (theyear, width=3, css='calendar.css', encoding=None)

一年分のカレンダーを一つの完全な HTML ページとして返します。 `width' の値(デフォルトでは 3 です) は何ヶ月分を一行に収めるかを指定します。 `css' は使われるカスケーディングスタイルシートの名前です。スタイルシートを使わないようにするために @ref{885,,None} を渡すこともできます。 `encoding' には出力に使うエンコーディングを指定します (デフォルトではシステムデフォルトのエンコーディングです)。
@end deffn

@geindex formatmonthname() (calendar.HTMLCalendar のメソッド)
@anchor{library/calendar calendar HTMLCalendar formatmonthname}@anchor{2931}
@deffn {メソッド} formatmonthname (theyear, themonth, withyear=True)

Return a month name as an HTML table row. If `withyear' is true the year
will be included in the row, otherwise just the month name will be
used.
@end deffn

@code{HTMLCalendar} has the following attributes you can override to
customize the CSS classes used by the calendar:

@geindex cssclasses (calendar.HTMLCalendar の属性)
@anchor{library/calendar calendar HTMLCalendar cssclasses}@anchor{2932}
@deffn {の属性} cssclasses

A list of CSS classes used for each weekday. The default class list is:

@example
cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
@end example

more styles can be added for each day:

@example
cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
@end example

Note that the length of this list must be seven items.
@end deffn

@geindex cssclass_noday (calendar.HTMLCalendar の属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_noday}@anchor{2933}
@deffn {の属性} cssclass_noday

The CSS class for a weekday occurring in the previous or coming month.


Added in version 3.7.

@end deffn

@geindex cssclasses_weekday_head (calendar.HTMLCalendar の属性)
@anchor{library/calendar calendar HTMLCalendar cssclasses_weekday_head}@anchor{2934}
@deffn {の属性} cssclasses_weekday_head

A list of CSS classes used for weekday names in the header row.
The default is the same as @ref{2932,,cssclasses}.


Added in version 3.7.

@end deffn

@geindex cssclass_month_head (calendar.HTMLCalendar の属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_month_head}@anchor{2935}
@deffn {の属性} cssclass_month_head

The month's head CSS class (used by @ref{2931,,formatmonthname()}).
The default value is @code{"month"}.


Added in version 3.7.

@end deffn

@geindex cssclass_month (calendar.HTMLCalendar の属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_month}@anchor{2936}
@deffn {の属性} cssclass_month

The CSS class for the whole month's table (used by @ref{292e,,formatmonth()}).
The default value is @code{"month"}.


Added in version 3.7.

@end deffn

@geindex cssclass_year (calendar.HTMLCalendar の属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_year}@anchor{2937}
@deffn {の属性} cssclass_year

The CSS class for the whole year's table of tables (used by
@ref{292f,,formatyear()}). The default value is @code{"year"}.


Added in version 3.7.

@end deffn

@geindex cssclass_year_head (calendar.HTMLCalendar の属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_year_head}@anchor{2938}
@deffn {の属性} cssclass_year_head

The CSS class for the table head for the whole year (used by
@ref{292f,,formatyear()}). The default value is @code{"year"}.


Added in version 3.7.

@end deffn

Note that although the naming for the above described class attributes is
singular (e.g. @code{cssclass_month} @code{cssclass_noday}), one can replace the
single CSS class with a space separated list of CSS classes, for example:

@example
"text-bold text-red"
@end example

Here is an example how @code{HTMLCalendar} can be customized:

@example
class CustomHTMLCal(calendar.HTMLCalendar):
    cssclasses = [style + " text-nowrap" for style in
                  calendar.HTMLCalendar.cssclasses]
    cssclass_month_head = "text-center month-head"
    cssclass_month = "text-center month"
    cssclass_year = "text-italic lead"
@end example
@end deffn

@geindex LocaleTextCalendar (calendar のクラス)
@anchor{library/calendar calendar LocaleTextCalendar}@anchor{94b}
@deffn {クラス} calendar.LocaleTextCalendar (firstweekday=0, locale=None)

This subclass of @ref{18aa,,TextCalendar} can be passed a locale name in the
constructor and will return month and weekday names in the specified locale.
@end deffn

@geindex LocaleHTMLCalendar (calendar のクラス)
@anchor{library/calendar calendar LocaleHTMLCalendar}@anchor{94c}
@deffn {クラス} calendar.LocaleHTMLCalendar (firstweekday=0, locale=None)

This subclass of @ref{d18,,HTMLCalendar} can be passed a locale name in the
constructor and will return month and weekday names in the specified
locale.
@end deffn

@cartouche
@quotation 注釈 
The constructor, @code{formatweekday()} and @code{formatmonthname()} methods
of these two classes temporarily change the @code{LC_TIME} locale to the given
`locale'. Because the current locale is a process-wide setting, they are
not thread-safe.
@end quotation
@end cartouche

単純なテキストのカレンダーに関して、このモジュールには以下のような関数が提供されています。

@geindex setfirstweekday() (calendar モジュール)
@anchor{library/calendar calendar setfirstweekday}@anchor{2915}
@deffn {の関数} calendar.setfirstweekday (weekday)

週の最初の曜日(@code{0} は月曜日, @code{6} は日曜日)を設定します。定数 @ref{2917,,MONDAY}, @ref{2939,,TUESDAY}, @ref{293a,,WEDNESDAY}, @ref{293b,,THURSDAY}, @ref{293c,,FRIDAY}, @ref{293d,,SATURDAY} 及び @ref{2918,,SUNDAY} は便宜上提供されています。例えば、日曜日を週の開始日に設定するときは:

@example
import calendar
calendar.setfirstweekday(calendar.SUNDAY)
@end example
@end deffn

@geindex firstweekday() (calendar モジュール)
@anchor{library/calendar calendar firstweekday}@anchor{293e}
@deffn {の関数} calendar.firstweekday ()

現在設定されている週の最初の曜日を返します。
@end deffn

@geindex isleap() (calendar モジュール)
@anchor{library/calendar calendar isleap}@anchor{293f}
@deffn {の関数} calendar.isleap (year)

`year' が閏年なら @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex leapdays() (calendar モジュール)
@anchor{library/calendar calendar leapdays}@anchor{2940}
@deffn {の関数} calendar.leapdays (y1, y2)

範囲(`y1' ... `y2')指定された期間の閏年の回数を返します。ここで `y1' や `y2' は年を表します。

この関数は、世紀の境目をまたぐ範囲でも正しく動作します。
@end deffn

@geindex weekday() (calendar モジュール)
@anchor{library/calendar calendar weekday}@anchor{2941}
@deffn {の関数} calendar.weekday (year, month, day)

`year' (@code{1970}--...), `month' (@code{1}--@code{12}), `day' (@code{1}--@code{31}) で与えられた日の曜日(@code{0} は月曜日)を返します。
@end deffn

@geindex weekheader() (calendar モジュール)
@anchor{library/calendar calendar weekheader}@anchor{2942}
@deffn {の関数} calendar.weekheader (n)

短縮された曜日名を含むヘッダを返します。`n' は各曜日を何文字で表すかを指定します。
@end deffn

@geindex monthrange() (calendar モジュール)
@anchor{library/calendar calendar monthrange}@anchor{2943}
@deffn {の関数} calendar.monthrange (year, month)

`year' と `month' で指定された月の一日の曜日と日数を返します。
@end deffn

@geindex monthcalendar() (calendar モジュール)
@anchor{library/calendar calendar monthcalendar}@anchor{2944}
@deffn {の関数} calendar.monthcalendar (year, month)

月のカレンダーを行列で返します。各行が週を表し、月の範囲外の日は0になります。それぞれの週は @ref{2915,,setfirstweekday()} で設定をしていない限り月曜日から始まります。
@end deffn

@geindex prmonth() (calendar モジュール)
@anchor{library/calendar calendar prmonth}@anchor{2945}
@deffn {の関数} calendar.prmonth (theyear, themonth, w=0, l=0)

@ref{190b,,month()} 関数によって返される月のカレンダーを出力します。
@end deffn

@geindex month() (calendar モジュール)
@anchor{library/calendar calendar month}@anchor{190b}
@deffn {の関数} calendar.month (theyear, themonth, w=0, l=0)

Returns a month's calendar in a multi-line string using the @ref{2929,,formatmonth()}
of the @ref{18aa,,TextCalendar} class.
@end deffn

@geindex prcal() (calendar モジュール)
@anchor{library/calendar calendar prcal}@anchor{2946}
@deffn {の関数} calendar.prcal (year, w=0, l=0, c=6, m=3)

@ref{15,,calendar()} 関数で返される一年間のカレンダーを出力します。
@end deffn

@geindex calendar() (calendar モジュール)
@anchor{library/calendar calendar calendar}@anchor{2947}
@deffn {の関数} calendar.calendar (year, w=2, l=1, c=6, m=3)

Returns a 3-column calendar for an entire year as a multi-line string using
the @ref{292c,,formatyear()} of the @ref{18aa,,TextCalendar} class.
@end deffn

@geindex timegm() (calendar モジュール)
@anchor{library/calendar calendar timegm}@anchor{2948}
@deffn {の関数} calendar.timegm (tuple)

カレンダーと直接は関係無いが、 @ref{f4,,time} モジュールの @ref{13d8,,gmtime()} 関数が返す形式の時刻を表すタプルを引数に取り、1970 を基点とするエポック時刻で POSIX エンコーディングであると仮定して、対応する Unix タイムスタンプの値を返します。実際には、 @ref{13d8,,time.gmtime()} と @ref{2948,,timegm()} はお互いの逆関数です。
@end deffn

The @code{calendar} module exports the following data attributes:

@geindex day_name (calendar モジュール)
@anchor{library/calendar calendar day_name}@anchor{2949}
@deffn {データ} calendar.day_name

A sequence that represents the days of the week in the current locale,
where Monday is day number 0.

@example
>>> import calendar
>>> list(calendar.day_name)
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
@end example
@end deffn

@geindex day_abbr (calendar モジュール)
@anchor{library/calendar calendar day_abbr}@anchor{294a}
@deffn {データ} calendar.day_abbr

A sequence that represents the abbreviated days of the week in the current locale,
where Mon is day number 0.

@example
>>> import calendar
>>> list(calendar.day_abbr)
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
@end example
@end deffn

@geindex MONDAY (calendar モジュール)
@geindex TUESDAY (calendar モジュール)
@geindex WEDNESDAY (calendar モジュール)
@geindex THURSDAY (calendar モジュール)
@geindex FRIDAY (calendar モジュール)
@geindex SATURDAY (calendar モジュール)
@geindex SUNDAY (calendar モジュール)
@anchor{library/calendar calendar MONDAY}@anchor{2917}
@deffn {データ} calendar.MONDAY
@anchor{library/calendar calendar TUESDAY}@anchor{2939}
@deffnx {データ} calendar.TUESDAY
@anchor{library/calendar calendar WEDNESDAY}@anchor{293a}
@deffnx {データ} calendar.WEDNESDAY
@anchor{library/calendar calendar THURSDAY}@anchor{293b}
@deffnx {データ} calendar.THURSDAY
@anchor{library/calendar calendar FRIDAY}@anchor{293c}
@deffnx {データ} calendar.FRIDAY
@anchor{library/calendar calendar SATURDAY}@anchor{293d}
@deffnx {データ} calendar.SATURDAY
@anchor{library/calendar calendar SUNDAY}@anchor{2918}
@deffnx {データ} calendar.SUNDAY

Aliases for the days of the week,
where @code{MONDAY} is @code{0} and @code{SUNDAY} is @code{6}.


Added in version 3.12.

@end deffn

@geindex Day (calendar のクラス)
@anchor{library/calendar calendar Day}@anchor{6aa}
@deffn {クラス} calendar.Day

Enumeration defining days of the week as integer constants.
The members of this enumeration are exported to the module scope as
@ref{2917,,MONDAY} through @ref{2918,,SUNDAY}.


Added in version 3.12.

@end deffn

@geindex month_name (calendar モジュール)
@anchor{library/calendar calendar month_name}@anchor{294b}
@deffn {データ} calendar.month_name

A sequence that represents the months of the year in the current locale.  This
follows normal convention of January being month number 1, so it has a length of
13 and @code{month_name[0]} is the empty string.

@example
>>> import calendar
>>> list(calendar.month_name)
['@w{'}, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
@end example
@end deffn

@geindex month_abbr (calendar モジュール)
@anchor{library/calendar calendar month_abbr}@anchor{294c}
@deffn {データ} calendar.month_abbr

A sequence that represents the abbreviated months of the year in the current
locale.  This follows normal convention of January being month number 1, so it
has a length of 13 and  @code{month_abbr[0]} is the empty string.

@example
>>> import calendar
>>> list(calendar.month_abbr)
['@w{'}, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
@end example
@end deffn

@geindex JANUARY (calendar モジュール)
@geindex FEBRUARY (calendar モジュール)
@geindex MARCH (calendar モジュール)
@geindex APRIL (calendar モジュール)
@geindex MAY (calendar モジュール)
@geindex JUNE (calendar モジュール)
@geindex JULY (calendar モジュール)
@geindex AUGUST (calendar モジュール)
@geindex SEPTEMBER (calendar モジュール)
@geindex OCTOBER (calendar モジュール)
@geindex NOVEMBER (calendar モジュール)
@geindex DECEMBER (calendar モジュール)
@anchor{library/calendar calendar JANUARY}@anchor{34e}
@deffn {データ} calendar.JANUARY
@anchor{library/calendar calendar FEBRUARY}@anchor{34f}
@deffnx {データ} calendar.FEBRUARY
@anchor{library/calendar calendar MARCH}@anchor{294d}
@deffnx {データ} calendar.MARCH
@anchor{library/calendar calendar APRIL}@anchor{294e}
@deffnx {データ} calendar.APRIL
@anchor{library/calendar calendar MAY}@anchor{294f}
@deffnx {データ} calendar.MAY
@anchor{library/calendar calendar JUNE}@anchor{2950}
@deffnx {データ} calendar.JUNE
@anchor{library/calendar calendar JULY}@anchor{2951}
@deffnx {データ} calendar.JULY
@anchor{library/calendar calendar AUGUST}@anchor{2952}
@deffnx {データ} calendar.AUGUST
@anchor{library/calendar calendar SEPTEMBER}@anchor{2953}
@deffnx {データ} calendar.SEPTEMBER
@anchor{library/calendar calendar OCTOBER}@anchor{2954}
@deffnx {データ} calendar.OCTOBER
@anchor{library/calendar calendar NOVEMBER}@anchor{2955}
@deffnx {データ} calendar.NOVEMBER
@anchor{library/calendar calendar DECEMBER}@anchor{2956}
@deffnx {データ} calendar.DECEMBER

Aliases for the months of the year,
where @code{JANUARY} is @code{1} and @code{DECEMBER} is @code{12}.


Added in version 3.12.

@end deffn

@geindex Month (calendar のクラス)
@anchor{library/calendar calendar Month}@anchor{6a9}
@deffn {クラス} calendar.Month

Enumeration defining months of the year as integer constants.
The members of this enumeration are exported to the module scope as
@ref{34e,,JANUARY} through @ref{2956,,DECEMBER}.


Added in version 3.12.

@end deffn

The @code{calendar} module defines the following exceptions:

@geindex IllegalMonthError
@anchor{library/calendar calendar IllegalMonthError}@anchor{190a}
@deffn {例外} calendar.IllegalMonthError (month)

A subclass of @ref{2ec,,ValueError},
raised when the given month number is outside of the range 1-12 (inclusive).

@geindex month (calendar.IllegalMonthError の属性)
@anchor{library/calendar calendar IllegalMonthError month}@anchor{2957}
@deffn {の属性} month

The invalid month number.
@end deffn
@end deffn

@geindex IllegalWeekdayError
@anchor{library/calendar calendar IllegalWeekdayError}@anchor{2958}
@deffn {例外} calendar.IllegalWeekdayError (weekday)

A subclass of @ref{2ec,,ValueError},
raised when the given weekday number is outside of the range 0-6 (inclusive).

@geindex weekday (calendar.IllegalWeekdayError の属性)
@anchor{library/calendar calendar IllegalWeekdayError weekday}@anchor{2959}
@deffn {の属性} weekday

The invalid weekday number.
@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item @ref{34,,datetime} モジュール

@ref{f4,,time} モジュールと似た機能を持った日付と時間用のオブジェクト指向インターフェース。

@item @ref{f4,,time} モジュール

時間に関連した低水準の関数群。
@end table


@menu
* コマンドラインでの使用:: 

@end menu

@node コマンドラインでの使用,,,calendar --- 一般的なカレンダーに関係する機能群
@anchor{library/calendar calendar-cli}@anchor{1d0}@anchor{library/calendar command-line-usage}@anchor{295a}
@subsubsection コマンドラインでの使用



Added in version 2.5.


The @code{calendar} module can be executed as a script from the command line
to interactively print a calendar.

@example
python -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t @{text,html@}]
                   [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]
                   [-f FIRST_WEEKDAY] [year] [month]
@end example

For example, to print a calendar for the year 2000:

@example
$ python -m calendar 2000
                                  2000

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                1  2          1  2  3  4  5  6             1  2  3  4  5
 3  4  5  6  7  8  9       7  8  9 10 11 12 13       6  7  8  9 10 11 12
10 11 12 13 14 15 16      14 15 16 17 18 19 20      13 14 15 16 17 18 19
17 18 19 20 21 22 23      21 22 23 24 25 26 27      20 21 22 23 24 25 26
24 25 26 27 28 29 30      28 29                     27 28 29 30 31
31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                1  2       1  2  3  4  5  6  7                1  2  3  4
 3  4  5  6  7  8  9       8  9 10 11 12 13 14       5  6  7  8  9 10 11
10 11 12 13 14 15 16      15 16 17 18 19 20 21      12 13 14 15 16 17 18
17 18 19 20 21 22 23      22 23 24 25 26 27 28      19 20 21 22 23 24 25
24 25 26 27 28 29 30      29 30 31                  26 27 28 29 30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                1  2          1  2  3  4  5  6                   1  2  3
 3  4  5  6  7  8  9       7  8  9 10 11 12 13       4  5  6  7  8  9 10
10 11 12 13 14 15 16      14 15 16 17 18 19 20      11 12 13 14 15 16 17
17 18 19 20 21 22 23      21 22 23 24 25 26 27      18 19 20 21 22 23 24
24 25 26 27 28 29 30      28 29 30 31               25 26 27 28 29 30
31

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                   1             1  2  3  4  5                   1  2  3
 2  3  4  5  6  7  8       6  7  8  9 10 11 12       4  5  6  7  8  9 10
 9 10 11 12 13 14 15      13 14 15 16 17 18 19      11 12 13 14 15 16 17
16 17 18 19 20 21 22      20 21 22 23 24 25 26      18 19 20 21 22 23 24
23 24 25 26 27 28 29      27 28 29 30               25 26 27 28 29 30 31
30 31
@end example

以下のオプションが使用できます:

@geindex calendar コマンドラインオプション; --help
@geindex calendar コマンドラインオプション; -h
@anchor{library/calendar cmdoption-calendar-help}@anchor{295b}@anchor{library/calendar cmdoption-calendar-h}@anchor{295c}
@deffn {Option} @w{-}@w{-}help, @w{-}h

ヘルプメッセージを表示して終了します。
@end deffn

@geindex calendar コマンドラインオプション; --locale
@geindex calendar コマンドラインオプション; -L
@anchor{library/calendar cmdoption-calendar-locale}@anchor{295d}@anchor{library/calendar cmdoption-calendar-L}@anchor{295e}
@deffn {Option} @w{-}@w{-}locale LOCALE, @w{-}L LOCALE

The locale to use for month and weekday names.
Defaults to English.
@end deffn

@geindex calendar コマンドラインオプション; --encoding
@geindex calendar コマンドラインオプション; -e
@anchor{library/calendar cmdoption-calendar-encoding}@anchor{295f}@anchor{library/calendar cmdoption-calendar-e}@anchor{2960}
@deffn {Option} @w{-}@w{-}encoding ENCODING, @w{-}e ENCODING

The encoding to use for output.
@ref{295f,,--encoding} is required if @ref{295d,,--locale} is set.
@end deffn

@geindex calendar コマンドラインオプション; --type
@geindex calendar コマンドラインオプション; -t
@anchor{library/calendar cmdoption-calendar-type}@anchor{2961}@anchor{library/calendar cmdoption-calendar-t}@anchor{2962}
@deffn {Option} @w{-}@w{-}type @{text,html@}, @w{-}t @{text,html@}

Print the calendar to the terminal as text,
or as an HTML document.
@end deffn

@geindex calendar コマンドラインオプション; --first-weekday
@geindex calendar コマンドラインオプション; -f
@anchor{library/calendar cmdoption-calendar-first-weekday}@anchor{2963}@anchor{library/calendar cmdoption-calendar-f}@anchor{2964}
@deffn {Option} @w{-}@w{-}first@w{-}weekday FIRST_WEEKDAY, @w{-}f FIRST_WEEKDAY

The weekday to start each week.
Must be a number between 0 (Monday) and 6 (Sunday).
Defaults to 0.


Added in version 3.13.

@end deffn

@geindex calendar コマンドラインオプション; year
@anchor{library/calendar cmdoption-calendar-arg-year}@anchor{2965}
@deffn {Option} year

The year to print the calendar for.
Defaults to the current year.
@end deffn

@geindex calendar コマンドラインオプション; month
@anchor{library/calendar cmdoption-calendar-arg-month}@anchor{2966}
@deffn {Option} month

The month of the specified @ref{2965,,year} to print the calendar for.
Must be a number between 1 and 12,
and may only be used in text mode.
Defaults to printing a calendar for the full year.
@end deffn

`Text-mode options:'

@geindex calendar コマンドラインオプション; --width
@geindex calendar コマンドラインオプション; -w
@anchor{library/calendar cmdoption-calendar-width}@anchor{2967}@anchor{library/calendar cmdoption-calendar-w}@anchor{2968}
@deffn {Option} @w{-}@w{-}width WIDTH, @w{-}w WIDTH

The width of the date column in terminal columns.
The date is printed centred in the column.
Any value lower than 2 is ignored.
Defaults to 2.
@end deffn

@geindex calendar コマンドラインオプション; --lines
@geindex calendar コマンドラインオプション; -l
@anchor{library/calendar cmdoption-calendar-lines}@anchor{2969}@anchor{library/calendar cmdoption-calendar-l}@anchor{296a}
@deffn {Option} @w{-}@w{-}lines LINES, @w{-}l LINES

The number of lines for each week in terminal rows.
The date is printed top-aligned.
Any value lower than 1 is ignored.
Defaults to 1.
@end deffn

@geindex calendar コマンドラインオプション; --spacing
@geindex calendar コマンドラインオプション; -s
@anchor{library/calendar cmdoption-calendar-spacing}@anchor{296b}@anchor{library/calendar cmdoption-calendar-s}@anchor{296c}
@deffn {Option} @w{-}@w{-}spacing SPACING, @w{-}s SPACING

The space between months in columns.
Any value lower than 2 is ignored.
Defaults to 6.
@end deffn

@geindex calendar コマンドラインオプション; --months
@geindex calendar コマンドラインオプション; -m
@anchor{library/calendar cmdoption-calendar-months}@anchor{296d}@anchor{library/calendar cmdoption-calendar-m}@anchor{296e}
@deffn {Option} @w{-}@w{-}months MONTHS, @w{-}m MONTHS

The number of months printed per row.
Defaults to 3.
@end deffn


バージョン 3.14 で変更: By default, today's date is highlighted in color and can be
@ref{1b7,,controlled using environment variables}.


`HTML-mode options:'

@geindex calendar コマンドラインオプション; --css
@geindex calendar コマンドラインオプション; -c
@anchor{library/calendar cmdoption-calendar-css}@anchor{296f}@anchor{library/calendar cmdoption-calendar-c}@anchor{2970}
@deffn {Option} @w{-}@w{-}css CSS, @w{-}c CSS

The path of a CSS stylesheet to use for the calendar.
This must either be relative to the generated HTML,
or an absolute HTTP or @code{file:///} URL.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node collections --- コンテナデータ型,collections abc --- コンテナの抽象基底クラス,calendar --- 一般的なカレンダーに関係する機能群,データ型
@anchor{library/collections doc}@anchor{2971}@anchor{library/collections collections-container-datatypes}@anchor{2972}@anchor{library/collections module-collections}@anchor{1e}@anchor{library/collections translation-repo}@anchor{2973}
@subsection @code{collections} --- コンテナデータ型


@geindex module; collections

`ソースコード:' Lib/collections/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/collections/__init__.py}

@c from collections import *
@c import itertools
@c __name__ = '<doctest>'


__________________________________________________________________


このモジュールは、汎用の Python 組み込みコンテナ @ref{183,,dict}, @ref{24d,,list}, @ref{184,,set}, および @ref{614,,tuple} に代わる、特殊なコンテナデータ型を実装しています。


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{4e0,,namedtuple()}

@tab

名前付きフィールドを持つタプルのサブクラスを作成するファクトリ関数

@item

@ref{7f4,,deque}

@tab

両端における append や pop を高速に行えるリスト風のコンテナ

@item

@ref{e16,,ChainMap}

@tab

複数のマッピングの一つのビューを作成する辞書風のクラス

@item

@ref{12a3,,Counter}

@tab

@ref{824,,ハッシュ可能} なオブジェクトを数え上げる辞書のサブクラス

@item

@ref{7f3,,OrderedDict}

@tab

項目が追加された順序を記憶する辞書のサブクラス

@item

@ref{13d4,,defaultdict}

@tab

ファクトリ関数を呼び出して存在しない値を供給する辞書のサブクラス

@item

@ref{1d7d,,UserDict}

@tab

辞書のサブクラス化を簡単にする辞書オブジェクトのラッパ

@item

@ref{16fd,,UserList}

@tab

リストのサブクラス化を簡単にするリストオブジェクトのラッパ

@item

@ref{fd3,,UserString}

@tab

文字列のサブクラス化を簡単にする文字列オブジェクトのラッパ

@end multitable


@menu
* ChainMap オブジェクト:: 
* Counter オブジェクト:: 
* deque オブジェクト:: 
* defaultdict オブジェクト:: 
* namedtuple() 名前付きフィールドを持つタプルのファクトリ関数: namedtuple 名前付きフィールドを持つタプルのファクトリ関数. 
* OrderedDict オブジェクト:: 
* UserDict オブジェクト:: 
* UserList オブジェクト:: 
* UserString オブジェクト:: 

@end menu

@node ChainMap オブジェクト,Counter オブジェクト,,collections --- コンテナデータ型
@anchor{library/collections chainmap-objects}@anchor{2974}
@subsubsection @code{ChainMap} オブジェクト



Added in version 3.3.


@ref{e16,,ChainMap} クラスは、複数のマッピングを素早く連結し、一つの単位として扱うために提供されています。これはたいてい、新しい辞書を作成して @ref{167e,,update()} を繰り返すよりも早いです。

このクラスはネストされたスコープをシミュレートするのに使え、テンプレート化に便利です。

@geindex ChainMap (collections のクラス)
@anchor{library/collections collections ChainMap}@anchor{e16}
@deffn {クラス} collections.ChainMap (*maps)

@ref{e16,,ChainMap} は、複数の辞書やその他のマッピングをまとめて、一つの、更新可能なビューを作成します。 `maps' が指定されないなら、一つの空辞書が与えられますから、新しいチェーンは必ず一つ以上のマッピングをもちます。

根底のマッピングはリストに保存されます。このリストはパブリックで、 `maps' 属性を使ってアクセスや更新できます。それ以外に状態はありません。

探索は、根底のマッピングをキーが見つかるまで引き続き探します。対して、書き込み、更新、削除は、最初のマッピングのみ操作します。

@ref{e16,,ChainMap} は、根底のマッピングを参照によって組み込みます。ですから、根底のマッピングの一つが更新されると、その変更は @ref{e16,,ChainMap} に反映されます。

通常の辞書のメソッドすべてがサポートされています。さらに、`maps' 属性、新しいサブコンテキストを作成するメソッド、最初のマッピング以外のすべてにアクセスするためのプロパティがあります:

@geindex maps (collections.ChainMap の属性)
@anchor{library/collections collections ChainMap maps}@anchor{2975}
@deffn {の属性} maps

マッピングのユーザがアップデートできるリストです。このリストは最初に探されるものから最後に探されるものの順に並んでいます。これが唯一のソートされた状態であり、変更してマッピングが探される順番を変更できます。このリストは常に一つ以上のマッピングを含んでいなければなりません。
@end deffn

@geindex new_child() (collections.ChainMap のメソッド)
@anchor{library/collections collections ChainMap new_child}@anchor{1126}
@deffn {メソッド} new_child (m=None, **kwargs)

新しいマッピングに現在のインスタンスが持つ全てのマッピングを追加したものを持つ新しい @ref{e16,,ChainMap} インスタンスを返します。 @code{m} が指定された場合、新しいマッピングのリストの先頭部分になります; 指定されない場合は空の辞書が使われます。すなわち @code{d.new_child()} は @code{ChainMap(@{@}, *d.maps)} と等価になります。キーワード引数が指定された場合、それらによって指定されたマッピングまたは空の辞書が更新されます。このメソッドは、元のマッピングに変更を加えることなく値を更新できるサブコンテキストを生成するのに使われます。


バージョン 3.4 で変更: オプションの @code{m} 引数が追加されました。



バージョン 3.10 で変更: キーワード引数のサポートが追加されました。

@end deffn

@geindex parents (collections.ChainMap の属性)
@anchor{library/collections collections ChainMap parents}@anchor{2976}
@deffn {の属性} parents

現在のインスタンスの最初のマッピング以外のすべてのマッピングを含む新しい @ref{e16,,ChainMap} を返すプロパティです。これは最初のマッピングを検索から飛ばすのに便利です。使用例は @ref{14bf,,nonlocal} キーワードを @ref{238d,,ネストされたスコープ} に使う例と似ています。この使用例はまた、組み込み @ref{1a6,,super()} 関数にも似ています。 @code{d.parents} への参照は @code{ChainMap(*d.maps[1:])} と等価です。
@end deffn

@ref{e16,,ChainMap} の反復順序は、マッピングを最後から最初へスキャンして決定されることに注意してください。

@example
>>> baseline = @{'music': 'bach', 'art': 'rembrandt'@}
>>> adjustments = @{'art': 'van gogh', 'opera': 'carmen'@}
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']
@end example

これは、末尾のマッピングオブジェクトから始めた一連の @ref{167e,,dict.update()} の呼び出しと同じ順序になります。

@example
>>> combined = baseline.copy()
>>> combined.update(adjustments)
>>> list(combined)
['music', 'art', 'opera']
@end example


バージョン 3.9 で変更: 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} で規定されている @code{|} 演算子と @code{|=} 演算子のサポートを追加しました。

@end deffn


@subsubheading 参考



@itemize *

@item 
Enthought 社の CodeTools パッケージ@footnote{https://github.com/enthought/codetools} に含まれる MultiContext クラス@footnote{https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py} は、チェーン内のすべてのマッピングへの書き込みをサポートするオプションを持ちます。

@item 
Django のテンプレート用の Context class@footnote{https://github.com/django/django/blob/main/django/template/context.py} は、読み出し専用のマッピングのチェーンです。 @ref{1126,,new_child()} メソッドや @ref{2976,,parents} プロパティに似た push や pop の機能もあります。

@item 
Nested Contexts recipe@footnote{https://code.activestate.com/recipes/577434-nested-contexts-a-chain-of-mapping-objects/} は、書き込み・その他の変更が最初のマッピングにのみ適用されるか、チェーンのすべてのマッピングに適用されるか、制御するオプションを持ちます。

@item 
非常に単純化した読み出し専用バージョンの Chainmap@footnote{https://code.activestate.com/recipes/305268/}。
@end itemize


@menu
* ChainMap の例とレシピ:: 

@end menu

@node ChainMap の例とレシピ,,,ChainMap オブジェクト
@anchor{library/collections chainmap-examples-and-recipes}@anchor{2977}
@subsubsection @code{ChainMap} の例とレシピ


この節では、チェーンされたマッピングを扱う様々な手法を示します。

Python の内部探索チェーンをシミュレートする例:

@example
import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))
@end example

ユーザ指定のコマンドライン引数、環境変数、デフォルト値、の順に優先させる例:

@example
import os, argparse

defaults = @{'color': 'red', 'user': 'guest'@}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = @{k: v for k, v in vars(namespace).items() if v is not None@}

combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])
@end example

@ref{e16,,ChainMap} を使ってネストされたコンテキストをシミュレートするパターンの例:

@example
c = ChainMap()        # Create root context
d = c.new_child()     # Create nested child context
e = c.new_child()     # Child of c, independent from d
e.maps[0]             # Current context dictionary -- like Python's locals()
e.maps[-1]            # Root context -- like Python's globals()
e.parents             # Enclosing context chain -- like Python's nonlocals

d['x'] = 1            # Set value in current context
d['x']                # Get first key in the chain of contexts
del d['x']            # Delete from current context
list(d)               # All nested values
k in d                # Check all nested values
len(d)                # Number of nested values
d.items()             # All nested items
dict(d)               # Flatten into a regular dictionary
@end example

@ref{e16,,ChainMap} クラスは、探索はチェーン全体に対して行いますが、更新 (書き込みと削除) は最初のマッピングに対してのみ行います。しかし、深い書き込みと削除を望むなら、チェーンの深いところで見つかったキーを更新するサブクラスを簡単に作れます:

@example
class DeepChainMap(ChainMap):
    'Variant of ChainMap that allows direct updates to inner scopes'

    def __setitem__(self, key, value):
        for mapping in self.maps:
            if key in mapping:
                mapping[key] = value
                return
        self.maps[0][key] = value

    def __delitem__(self, key):
        for mapping in self.maps:
            if key in mapping:
                del mapping[key]
                return
        raise KeyError(key)

>>> d = DeepChainMap(@{'zebra': 'black'@}, @{'elephant': 'blue'@}, @{'lion': 'yellow'@})
>>> d['lion'] = 'orange'         # update an existing key two levels down
>>> d['snake'] = 'red'           # new keys get added to the topmost dict
>>> del d['elephant']            # remove an existing key one level down
>>> d                            # display result
DeepChainMap(@{'zebra': 'black', 'snake': 'red'@}, @{@}, @{'lion': 'orange'@})
@end example

@node Counter オブジェクト,deque オブジェクト,ChainMap オブジェクト,collections --- コンテナデータ型
@anchor{library/collections counter-objects}@anchor{2978}
@subsubsection @code{Counter} オブジェクト


便利で迅速な検数をサポートするカウンタツールが提供されています。例えば:

@example
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
...
>>> cnt
Counter(@{'blue': 3, 'red': 2, 'green': 1@})

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
@end example

@geindex Counter (collections のクラス)
@anchor{library/collections collections Counter}@anchor{12a3}
@deffn {クラス} collections.Counter ([iterable-or-mapping])

@ref{12a3,,Counter} は @ref{824,,ハッシュ可能} なオブジェクトをカウントする @ref{183,,dict} のサブクラスです。これは、要素を辞書のキーとして保存し、そのカウントを辞書の値として保存するコレクションです。カウントは、0 や負のカウントを含む整数値をとれます。 @ref{12a3,,Counter} クラスは、他の言語のバッグや多重集合のようなものです。

要素は、 `iterable' から数え上げられたり、他の `mapping' (やカウンタ) から初期化されます:

@example
>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter(@{'red': 4, 'blue': 2@})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args
@end example

カウンタオブジェクトは辞書のインターフェースを持ちますが、存在しない要素に対して @ref{5e7,,KeyError} を送出する代わりに 0 を返すという違いがあります:

@example
>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0
@end example

カウントを 0 に設定しても、要素はカウンタから取り除かれません。完全に取り除くには、 @code{del} を使ってください:

@example
>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry
@end example


Added in version 3.1.



バージョン 3.7 で変更: @ref{12a3,,Counter} は @ref{183,,dict} のサブクラスとして要素の挿入順を維持する機能を継承しました。 `Counter' オブジェクトに対する数学演算も順序を維持します。結果の順序はまず左の被演算子における要素の出現順に従い、その後右の被演算子において要素が出現する順序になります。


カウンタオブジェクトは全ての辞書で利用できるメソッドに加えて、以下に示す追加のメソッドをサポートしています。

@geindex elements() (collections.Counter のメソッド)
@anchor{library/collections collections Counter elements}@anchor{151b}
@deffn {メソッド} elements ()

それぞれの要素を、そのカウント分の回数だけ繰り返すイテレータを返します。要素は挿入した順番で返されます。ある要素のカウントが 1 未満なら、 @ref{151b,,elements()} はそれを無視します。

@example
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
@end example
@end deffn

@geindex most_common() (collections.Counter のメソッド)
@anchor{library/collections collections Counter most_common}@anchor{151a}
@deffn {メソッド} most_common ([n])

最も多い `n' 要素を、カウントが多いものから少ないものまで順に並べたリストを返します。 `n' が省略されるか @code{None} であれば、 @ref{151a,,most_common()} はカウンタの `すべての' 要素を返します。等しいカウントの要素は挿入順に並べられます:

@example
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
@end example
@end deffn

@geindex subtract() (collections.Counter のメソッド)
@anchor{library/collections collections Counter subtract}@anchor{13f7}
@deffn {メソッド} subtract ([iterable-or-mapping])

要素から `iterable' の要素または `mapping' の要素が引かれます。 @ref{167e,,dict.update()} に似ていますが、カウントを置き換えるのではなく引きます。入力も出力も、 0 や負になりえます。

@example
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter(@{'a': 3, 'b': 0, 'c': -3, 'd': -6@})
@end example


Added in version 3.2.

@end deffn

@geindex total() (collections.Counter のメソッド)
@anchor{library/collections collections Counter total}@anchor{2979}
@deffn {メソッド} total ()

カウントの合計を計算します。

@example
>>> c = Counter(a=10, b=5, c=0)
>>> c.total()
15
@end example


Added in version 3.10.

@end deffn

普通の辞書のメソッドは、以下の 2 つのメソッドがカウンタに対して異なる振る舞いをするのを除き、 @ref{12a3,,Counter} オブジェクトにも利用できます。

@geindex fromkeys() (collections.Counter のメソッド)
@anchor{library/collections collections Counter fromkeys}@anchor{297a}
@deffn {メソッド} fromkeys (iterable)

このクラスメソッドは @ref{12a3,,Counter} オブジェクトには実装されていません。
@end deffn

@geindex update() (collections.Counter のメソッド)
@anchor{library/collections collections Counter update}@anchor{177d}
@deffn {メソッド} update ([iterable-or-mapping])

要素が `iterable' からカウントされるか、別の `mapping' (やカウンタ) が追加されます。 @ref{167e,,dict.update()} に似ていますが、カウントを置き換えるのではなく追加します。また、 `iterable' には @code{(key, value)} 対のシーケンスではなく、要素のシーケンスが求められます。
@end deffn
@end deffn

カウンタオブジェクトは等価、部分集合、上位集合のための次の拡張比較 (rich comparison) 演算子をサポートします: @code{==}, @code{!=}, @code{<}, @code{<=}, @code{>}, @code{>=}。これらの比較は、存在しない要素をカウントがゼロであるとみなします。すなわち、 @code{Counter(a=1) == Counter(a=1, b=0)} は真を返します。


バージョン 3.10 で変更: 拡張比較 (rich comparison) 演算が追加されました。



バージョン 3.10 で変更: 等価比較において、存在しない要素はカウントがゼロであるとみなされるようになりました。かつては @code{Counter(a=3)} と @code{Counter(a=3, b=0)} は異なるとみなされていました。


@ref{12a3,,Counter} オブジェクトを使ったよくあるパターン:

@example
c.total()                       # 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()                       # access the (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts
@end example

@ref{12a3,,Counter} オブジェクトを組み合わせて多重集合 (0より大きいカウントを持つカウンタ) を作るためのいくつかの数学演算が提供されています。加算と減算はそれぞれの要素のカウンタを加算または減算することによりカウンタオブジェクトを組み合わせます。積集合と和集合は、それぞれのカウントの最大値と最小値を返します。等価と包含はそれぞれのカウントを比較します。それぞれの演算は符号付きカウントを持った入力を受け付けますが、カウントが0以下の要素は結果から取り除かれます。

@example
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter(@{'a': 4, 'b': 3@})
>>> c - d                       # subtract (keeping only positive counts)
Counter(@{'a': 2@})
>>> c & d                       # intersection:  min(c[x], d[x])
Counter(@{'a': 1, 'b': 1@})
>>> c | d                       # union:  max(c[x], d[x])
Counter(@{'a': 3, 'b': 2@})
>>> c == d                      # equality:  c[x] == d[x]
False
>>> c <= d                      # inclusion:  c[x] <= d[x]
False
@end example

単項加算および減算は、空カウンタの加算や空カウンタからの減算へのショートカットです。

@example
>>> c = Counter(a=2, b=-4)
>>> +c
Counter(@{'a': 2@})
>>> -c
Counter(@{'b': 4@})
@end example


Added in version 3.3: 単項加算、単項減算、in-place の多重集合操作のサポートが追加されました。


@cartouche
@quotation 注釈 
カウンタはもともと、推移するカウントを正の整数で表すために設計されました。しかし、他の型や負の値を必要とするユースケースを不必要に排除することがないように配慮されています。このようなユースケースの助けになるように、この節で最低限の範囲と型の制限について記述します。


@itemize *

@item 
@ref{12a3,,Counter} クラス自体は辞書のサブクラスで、キーと値に制限はありません。値はカウントを表す数であることを意図していますが、値フィールドに任意のものを保存 `できます' 。

@item 
@ref{151a,,most_common()} メソッドが要求するのは、値が順序付け可能なことだけです。

@item 
@code{c[key] += 1} のようなインプレース演算では、値の型に必要なのは 足し算と引き算ができることだけです。よって分数、浮動小数点数、 小数も使え、負の値がサポートされています。これと同じことが、 負や 0 の値を入力と出力に許す @ref{177d,,update()} と @ref{13f7,,subtract()} メソッド にも言えます。

@item 
多重集合メソッドは正の値を扱うユースケースに対してのみ設計されています。入力は負や 0 に出来ますが、正の値の出力のみが生成されます。型の制限はありませんが、値の型は足し算、引き算、比較をサポートしている必要があります。

@item 
@ref{151b,,elements()} メソッドは整数のカウントを要求します。これは 0 と負のカウントを無視します。
@end itemize
@end quotation
@end cartouche


@subsubheading 参考



@itemize *

@item 
Smalltalk の Bag class@footnote{https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html} 。

@item 
Wikipedia の Multisets@footnote{https://en.wikipedia.org/wiki/Multiset} の項目。

@item 
C++ multisets@footnote{http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm} の例を交えたチュートリアル。

@item 
数学的な多重集合の演算とそのユースケースは、 `Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19' を参照してください。

@item 
与えられた要素の集まりからなる与えられた大きさの相違なる多重集合をすべて数え上げるには、 @ref{1499,,itertools.combinations_with_replacement()} を参照してください:

@example
map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC
@end example
@end itemize


@node deque オブジェクト,defaultdict オブジェクト,Counter オブジェクト,collections --- コンテナデータ型
@anchor{library/collections deque-objects}@anchor{297b}
@subsubsection @code{deque} オブジェクト


@geindex deque (collections のクラス)
@anchor{library/collections collections deque}@anchor{7f4}
@deffn {クラス} collections.deque ([iterable[, maxlen]])

`iterable' で与えられるデータから、新しい deque オブジェクトを (@ref{297c,,append()} をつかって) 左から右に初期化して返します。 `iterable' が指定されない場合、新しい deque オブジェクトは空になります。

Deque とは、スタックとキューを一般化したものです (この名前は「デック」と発音され、これは「double-ended queue」の省略形です)。Deque はどちらの側からも append と pop が可能で、スレッドセーフでメモリ効率がよく、どちらの方向からもおよそ `O'(1) のパフォーマンスで実行できます。

@ref{24d,,list} オブジェクトでも同様の操作を実現できますが、これは高速な固定長の操作に特化されており、基礎のデータ表現形式のサイズと位置を両方変えるような @code{pop(0)} や @code{insert(0, v)} などの操作ではメモリ移動のために `O'(`n') のコストを必要とします。

`maxlen' が指定されなかったり @code{None} だった場合、 deque は任意のサイズまで大きくなります。
そうでない場合、 deque のサイズは指定された最大長に制限されます。
長さが制限された deque がいっぱいになると、新しい要素を追加するときに追加した要素数分だけ追加したのと反対側から要素が捨てられます。
長さが制限された deque は Unix における @code{tail} フィルタと似た機能を提供します。
トランザクションの tracking や最近使った要素だけを残したいデータプール (pool of data) などにも便利です。

Deque オブジェクトは以下のようなメソッドをサポートしています:

@geindex append() (collections.deque のメソッド)
@anchor{library/collections collections deque append}@anchor{297c}
@deffn {メソッド} append (x)

`x' を deque の右側につけ加えます。
@end deffn

@geindex appendleft() (collections.deque のメソッド)
@anchor{library/collections collections deque appendleft}@anchor{297d}
@deffn {メソッド} appendleft (x)

`x' を deque の左側につけ加えます。
@end deffn

@geindex clear() (collections.deque のメソッド)
@anchor{library/collections collections deque clear}@anchor{297e}
@deffn {メソッド} clear ()

deque からすべての要素を削除し、長さを 0 にします。
@end deffn

@geindex copy() (collections.deque のメソッド)
@anchor{library/collections collections deque copy}@anchor{fd2}
@deffn {メソッド} copy ()

deque の浅いコピーを作成します。


Added in version 3.5.

@end deffn

@geindex count() (collections.deque のメソッド)
@anchor{library/collections collections deque count}@anchor{13f9}
@deffn {メソッド} count (x)

deque の `x' に等しい要素を数え上げます。


Added in version 3.2.

@end deffn

@geindex extend() (collections.deque のメソッド)
@anchor{library/collections collections deque extend}@anchor{297f}
@deffn {メソッド} extend (iterable)

イテラブルな引数 iterable から得られる要素を deque の右側に追加し拡張します。
@end deffn

@geindex extendleft() (collections.deque のメソッド)
@anchor{library/collections collections deque extendleft}@anchor{2980}
@deffn {メソッド} extendleft (iterable)

イテラブルな引数 iterable から得られる要素を deque の左側に追加し拡張します。注意: 左から追加した結果は、イテラブルな引数の順序とは逆になります。
@end deffn

@geindex index() (collections.deque のメソッド)
@anchor{library/collections collections deque index}@anchor{fd0}
@deffn {メソッド} index (x[, start[, stop]])

deque 内の `x' の位置を返します (インデックス `start' からインデックス `stop' の両端を含む範囲で)。最初のマッチを返すか、見つからない場合には @ref{2ec,,ValueError} を発生させます。


Added in version 3.5.

@end deffn

@geindex insert() (collections.deque のメソッド)
@anchor{library/collections collections deque insert}@anchor{fd1}
@deffn {メソッド} insert (i, x)

`x' を deque の位置 `i' に挿入します。

挿入によって、長さに制限のある deque の長さが `maxlen' を超える場合、@ref{174e,,IndexError} が発生します。


Added in version 3.5.

@end deffn

@geindex pop() (collections.deque のメソッド)
@anchor{library/collections collections deque pop}@anchor{2981}
@deffn {メソッド} pop ()

deque の右側から要素をひとつ削除し、その要素を返します。要素がひとつも存在しない場合は @ref{174e,,IndexError} を発生させます。
@end deffn

@geindex popleft() (collections.deque のメソッド)
@anchor{library/collections collections deque popleft}@anchor{2982}
@deffn {メソッド} popleft ()

deque の左側から要素をひとつ削除し、その要素を返します。要素がひとつも存在しない場合は @ref{174e,,IndexError} を発生させます。
@end deffn

@geindex remove() (collections.deque のメソッド)
@anchor{library/collections collections deque remove}@anchor{1ccf}
@deffn {メソッド} remove (value)

`value' の最初に現れるものを削除します。要素が見付からないない場合は @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex reverse() (collections.deque のメソッド)
@anchor{library/collections collections deque reverse}@anchor{13fa}
@deffn {メソッド} reverse ()

deque の要素をインプレースに反転し、@code{None} を返します。


Added in version 3.2.

@end deffn

@geindex rotate() (collections.deque のメソッド)
@anchor{library/collections collections deque rotate}@anchor{1c90}
@deffn {メソッド} rotate (n=1)

deque の要素を全体で `n' ステップだけ右にローテートします。`n' が負の値の場合は、左にローテートします。

deque が空でないときは、 deque をひとつ右にローテートすることは @code{d.appendleft(d.pop())} と同じで、 deque をひとつ左にローテートすることは @code{d.append(d.popleft())} と同じです。
@end deffn

deque オブジェクトは読み出し専用属性も 1 つ提供しています:

@geindex maxlen (collections.deque の属性)
@anchor{library/collections collections deque maxlen}@anchor{151c}
@deffn {の属性} maxlen

deque の最大長で、制限されていなければ @code{None} です。


Added in version 3.1.

@end deffn
@end deffn

上記に加え、 deque はイテレーション, pickle 化, @code{len(d)}, @code{reversed(d)}, @code{copy.copy(d)}, @code{copy.deepcopy(d)}, @ref{34b,,in} 演算子による包含の検査,  @code{d[0]} のような添字による参照をサポートしています。添字によるアクセスは、両端の要素では `O'(1) ですが、中央部分の要素では `O'(`n') と遅くなります。高速なランダムアクセスのためには、代わりにリストを使ってください。

バージョン 3.5 から deque は @code{__add__()}, @code{__mul__()}, @code{__imul__()} をサポートしました。

例:

@example
>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
...     print(elem.upper())
G
H
I

>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque
['g', 'h', 'i']
>>> d[0]                             # peek at leftmost item
'g'
>>> d[-1]                            # peek at rightmost item
'i'

>>> list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in -toplevel-
        d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])
@end example

@menu
* deque のレシピ:: 

@end menu

@node deque のレシピ,,,deque オブジェクト
@anchor{library/collections deque-recipes}@anchor{2983}
@subsubsection @code{deque} のレシピ


この節では deque を使った様々なアプローチを紹介します。

長さが制限された deque は Unix における @code{tail} フィルタに相当する機能を提供します:

@example
def tail(filename, n=10):
    'Return the last n lines of a file'
    with open(filename) as f:
        return deque(f, n)
@end example

deque  を使用する別のアプローチは、右に要素を追加し左から要素を取り出すことで最近追加した要素のシーケンスを保持することです:

@example
def moving_average(iterable, n=3):
    # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
    # https://en.wikipedia.org/wiki/Moving_average
    it = iter(iterable)
    d = deque(itertools.islice(it, n-1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / n
@end example

ラウンドロビンスケジューラ@footnote{https://en.wikipedia.org/wiki/Round-robin_scheduling} は、入力されたイテレータを @ref{7f4,,deque} に格納することで実装できます。
値は、位置0にある選択中のイテレータから取り出されます。
そのイテレータが値を出し切った場合は、 @ref{2982,,popleft()} で除去できます; そうでない場合は、 @ref{1c90,,rotate()} メソッドで末尾に回せます:

@example
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    iterators = deque(map(iter, iterables))
    while iterators:
        try:
            while True:
                yield next(iterators[0])
                iterators.rotate(-1)
        except StopIteration:
            # Remove an exhausted iterator.
            iterators.popleft()
@end example

@ref{1c90,,rotate()} メソッドは、 @ref{7f4,,deque} のスライスや削除の機能を提供します。
例えば、 純粋な Python 実装の @code{del d[n]} は @code{rotate()} メソッドを頼りに、pop される要素の位置を割り出します:

@example
def delete_nth(d, n):
    d.rotate(-n)
    d.popleft()
    d.rotate(n)
@end example

@ref{7f4,,deque} のスライスの実装でも、同様のアプローチを使います。まず対象となる要素を @ref{1c90,,rotate()} によって deque の左端まで移動させてから、 @ref{2982,,popleft()} で古い要素を削除します。そして、 @ref{297f,,extend()} で新しい要素を追加したのち、循環を逆にします。このアプローチをやや変えたものとして、Forth スタイルのスタック操作、つまり @code{dup}, @code{drop}, @code{swap}, @code{over}, @code{pick}, @code{rot}, および @code{roll} を実装するのも簡単です。

@node defaultdict オブジェクト,namedtuple 名前付きフィールドを持つタプルのファクトリ関数,deque オブジェクト,collections --- コンテナデータ型
@anchor{library/collections defaultdict-objects}@anchor{2984}
@subsubsection @code{defaultdict} オブジェクト


@geindex defaultdict (collections のクラス)
@anchor{library/collections collections defaultdict}@anchor{13d4}
@deffn {クラス} collections.defaultdict (default_factory=None, /[, ...])

新しい辞書に似たオブジェクトを返します。 @ref{13d4,,defaultdict} は組み込みの @ref{183,,dict} クラスのサブクラスです。これはメソッドをひとつオーバーライドし、書き込み可能なインスタンス変数をひとつ追加しています。それ以外の機能は @ref{183,,dict} クラスと同じですので、ここでは説明しません。

1つ目の引数は @ref{2985,,default_factory} 属性の初期値です。デフォルトは @code{None} です。残りの引数はキーワード引数も含め、 @ref{183,,dict} のコンストラクタに与えられた場合と同様に扱われます。

@ref{13d4,,defaultdict} オブジェクトは標準の @ref{183,,dict} に加えて、以下のメソッドを実装しています:

@geindex __missing__() (collections.defaultdict のメソッド)
@anchor{library/collections collections defaultdict __missing__}@anchor{2986}
@deffn {メソッド} __missing__ (key)

もし @ref{2985,,default_factory} 属性が @code{None} であれば、このメソッドは @ref{5e7,,KeyError} 例外を、 `key' を引数として発生させます。

もし @ref{2985,,default_factory} 属性が @code{None} でない場合、このメソッドは引数なしで呼び出され、与えらえた `key' に対応するデフォルト値を提供します。この値は、辞書内に `key' に対応して登録され、最後に返されます。

もし @ref{2985,,default_factory} の呼出が例外を発生させた場合には、変更せずそのまま例外を投げます。

このメソッドは @ref{183,,dict} クラスの @ref{588,,__getitem__()} メソッドで、キーが存在しなかった場合によびだされます。値を返すか例外を発生させるのどちらにしても、 @ref{588,,__getitem__()} からもそのまま値が返るか例外が発生します。

なお、 @ref{2986,,__missing__()} は @ref{588,,__getitem__()} 以外のいかなる演算に対しても呼び出され `ません' 。よって @ref{2034,,get()} は、普通の辞書と同様に、 @ref{2985,,default_factory} を使うのではなくデフォルトとして @code{None} を返します。
@end deffn

@ref{13d4,,defaultdict} オブジェクトは以下のインスタンス変数をサポートしています:

@geindex default_factory (collections.defaultdict の属性)
@anchor{library/collections collections defaultdict default_factory}@anchor{2985}
@deffn {の属性} default_factory

この属性は @ref{2986,,__missing__()} メソッドによって使われます。これは存在すればコンストラクタの第1引数によって初期化され、そうでなければ @code{None} になります。
@end deffn


バージョン 3.9 で変更: 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} で規定されている合成演算子 (@code{|}) と更新演算子 (@code{|=})が追加されました。

@end deffn

@menu
* defaultdict の使用例:: 

@end menu

@node defaultdict の使用例,,,defaultdict オブジェクト
@anchor{library/collections defaultdict-examples}@anchor{2987}
@subsubsection @code{defaultdict} の使用例


@ref{24d,,list} を @ref{2985,,default_factory} とすることで、キー=値ペアのシーケンスをリストの辞書へ簡単にグループ化できます。:

@example
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
@end example

それぞれのキーが最初に登場したとき、マッピングにはまだ存在しません。そのためエントリは @ref{2985,,default_factory} 関数が返す空の @ref{24d,,list} を使って自動的に作成されます。 @ref{8dc,,list.append()} 操作は新しいリストに紐付けられます。キーが再度出現した場合には、通常の参照動作が行われます(そのキーに対応するリストが返ります)。そして @ref{8dc,,list.append()} 操作で別の値をリストに追加します。このテクニックは @ref{1285,,dict.setdefault()} を使った等価なものよりシンプルで速いです:

@example
>>> d = @{@}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
@end example

@ref{2985,,default_factory} を @ref{19b,,int} にすると、 @ref{13d4,,defaultdict} を(他の言語の bag や multisetのように)要素の数え上げに便利に使うことができます:

@example
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]
@end example

最初に文字が出現したときは、マッピングが存在しないので @ref{2985,,default_factory} 関数が @ref{19b,,int()} を呼んでデフォルトのカウント0を生成します。インクリメント操作が各文字を数え上げます。

常に0を返す @ref{19b,,int()} は特殊な関数でした。定数を生成するより速くて柔軟な方法は、 0に限らず何でも定数を生成するラムダ関数を使うことです:

@example
>>> def constant_factory(value):
...     return lambda: value
...
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to <missing>'
@end example

@ref{2985,,default_factory} を @ref{184,,set} に設定することで、 @ref{13d4,,defaultdict} をセットの辞書を作るために利用することができます:

@example
>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
...     d[k].add(v)
...
>>> sorted(d.items())
[('blue', @{2, 4@}), ('red', @{1, 3@})]
@end example

@node namedtuple 名前付きフィールドを持つタプルのファクトリ関数,OrderedDict オブジェクト,defaultdict オブジェクト,collections --- コンテナデータ型
@anchor{library/collections namedtuple-factory-function-for-tuples-with-named-fields}@anchor{2988}
@subsubsection @code{namedtuple()} 名前付きフィールドを持つタプルのファクトリ関数


名前付きタプルは、タプルの中のすべての場所に意味を割り当てて、より読みやすく自己解説的なコードを書けるようにします。通常のタプルが利用される場所ならどこでも利用でき、場所に対するインデックスの代わりに名前を使ってフィールドにアクセスできるようになります。

@geindex namedtuple() (collections モジュール)
@anchor{library/collections collections namedtuple}@anchor{4e0}
@deffn {の関数} collections.namedtuple (typename, field_names, *, rename=False, defaults=None, module=None)

`typename' という名前の tuple の新しいサブクラスを返します。新しいサブクラスは、 tuple に似ているけれどもインデックスやイテレータだけでなく属性名によるアクセスもできるオブジェクトを作るのに使います。このサブクラスのインスタンスは、わかりやすい docstring (型名と属性名が入っています) や、 tuple の内容を @code{name=value} という形のリストで返す使いやすい @ref{82f,,__repr__()} も持っています。

`field_names' は @code{['x', 'y']} のような文字列のシーケンスです。 `field_names' には、代わりに各属性名を空白文字 (whitespace) および/またはカンマ (,) で区切った文字列を渡すこともできます。例えば、 @code{'x y'} や @code{'x, y'} です。

アンダースコア (_) で始まる名前を除いて、 Python の正しい識別子 (identifier) ならなんでも属性名として使うことができます。正しい識別子とはアルファベット(letters), 数字(digits), アンダースコア(_) を含みますが、数字やアンダースコアで始まる名前や、 `class', `for', `return', `global', `pass', `raise' などといった @ref{88,,keyword} は使えません。

`rename' が真の場合、不適切なフィールド名は自動的に位置を示す名前に置き換えられます。例えば @code{['abc', 'def', 'ghi', 'abc']} は、予約語の @code{def} と、重複しているフィールド名の @code{abc} が除去され、@code{['abc', '_1', 'ghi', '_3']} に変換されます。

`defaults' には @code{None} あるいはデフォルト値の @ref{12f1,,iterable} が指定できます。
デフォルト値を持つフィールドはデフォルト値を持たないフィールドより後ろに来なければならないので、 `defaults' は最も右にある変数に適用されます。
例えば、 field_names が @code{['x', 'y', 'z']} で defaults が @code{(1, 2)} の場合、 @code{x} は必須の引数、 @code{y} は @code{1} がデフォルト、 @code{z} は @code{2} がデフォルトとなります。

もし `module' が指定されていれば、名前付きタプルの @ref{617,,__module__} 属性は、指定された値に設定されます

名前付きタプルのインスタンスはインスタンスごとの辞書を持たないので、軽量で、普通のタプル以上のメモリを使用しません。

pickle 化をサポートするには、名前付きタプルのクラス定義は `typename' と同じ名前の変数に割り当てなければなりません。


バージョン 3.1 で変更: `rename' のサポートが追加されました。



バージョン 3.6 で変更: `verbose' と `rename' 引数が @ref{5a5,,キーワード専用引数} になりました.



バージョン 3.6 で変更: `module' 引数が追加されました。



バージョン 3.7 で変更: `verbose' 引数と @code{_source} 属性が削除されました。



バージョン 3.7 で変更: `defaults' 引数と @ref{2989,,_field_defaults} 属性が追加されました。

@end deffn

@example
>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
@end example

名前付きタプルは @ref{2d,,csv} や @ref{d4,,sqlite3} モジュールが返すタプルのフィールドに名前を付けるときにとても便利です:

@example
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
    print(emp.name, emp.title)
@end example

タプルから継承したメソッドに加えて、名前付きタプルは3つの追加メソッドと2つの属性をサポートしています。フィールド名との衝突を避けるために、メソッド名と属性名はアンダースコアで始まります。

@geindex _make() (collections.somenamedtuple のクラスメソッド)
@anchor{library/collections collections somenamedtuple _make}@anchor{298a}
@deffn {メソッド} classmethod somenamedtuple._make (iterable)

既存の sequence や Iterable から新しいインスタンスを作るクラスメソッド.

@example
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)
@end example
@end deffn

@geindex _asdict() (collections.somenamedtuple のメソッド)
@anchor{library/collections collections somenamedtuple _asdict}@anchor{bd4}
@deffn {メソッド} somenamedtuple._asdict ()

フィールド名を対応する値にマッピングする新しい @ref{183,,dict} を返します:

@example
>>> p = Point(x=11, y=22)
>>> p._asdict()
@{'x': 11, 'y': 22@}
@end example


バージョン 3.1 で変更: 通常の @ref{183,,dict} の代わりに @ref{7f3,,OrderedDict} を返すようになりました。



バージョン 3.8 で変更: @ref{7f3,,collections.OrderedDict} ではなく @ref{183,,dict} を返すようになりました。Python 3.7以降は、通常の辞書で順番が保証されています。 @ref{7f3,,OrderedDict} 特有の機能を使いたい場合は、結果を @code{OrderedDict(nt._asdict())} 型にキャストして使用することを推奨します。

@end deffn

@geindex _replace() (collections.somenamedtuple のメソッド)
@anchor{library/collections collections somenamedtuple _replace}@anchor{298b}
@deffn {メソッド} somenamedtuple._replace (**kwargs)

指定されたフィールドを新しい値で置き換えた、新しい名前付きタプルを作って返します:

@example
>>> p = Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)

>>> for partnum, record in inventory.items():
...     inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
@end example

名前付きタプルは汎用的な関数 @ref{1c0,,copy.replace()} にもサポートされています。


バージョン 3.13 で変更: キーワード引数が無効な場合は @ref{2ec,,ValueError} のかわりに @ref{198,,TypeError} が発生します。

@end deffn

@geindex _fields (collections.somenamedtuple の属性)
@anchor{library/collections collections somenamedtuple _fields}@anchor{298c}
@deffn {の属性} somenamedtuple._fields

フィールド名をリストにしたタプルです。内省 (introspection) したり、既存の名前付きタプルをもとに新しい名前つきタプルを作成する時に便利です。

@example
>>> p._fields            # view the field names
('x', 'y')

>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)
@end example
@end deffn

@geindex _field_defaults (collections.somenamedtuple の属性)
@anchor{library/collections collections somenamedtuple _field_defaults}@anchor{2989}
@deffn {の属性} somenamedtuple._field_defaults

フィールド名からデフォルト値への対応を持つ辞書です。

@example
>>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
>>> Account._field_defaults
@{'balance': 0@}
>>> Account('premium')
Account(type='premium', balance=0)
@end example
@end deffn

文字列に格納された名前を使って名前つきタプルから値を取得するには @ref{dca,,getattr()} 関数を使います:

@example
>>> getattr(p, 'x')
11
@end example

辞書を名前付きタプルに変換するには、 @code{**} 演算子 (double-star-operator, @ref{2011,,引数リストのアンパック} で説明しています) を使います。:

@example
>>> d = @{'x': 11, 'y': 22@}
>>> Point(**d)
Point(x=11, y=22)
@end example

名前付きタプルは通常の Python クラスなので、継承して機能を追加したり変更するのは容易です。次の例では計算済みフィールドと固定幅の print format を追加しています:

@example
>>> class Point(namedtuple('Point', ['x', 'y'])):
...     __slots__ = ()
...     @@property
...     def hypot(self):
...         return (self.x ** 2 + self.y ** 2) ** 0.5
...     def __str__(self):
...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

>>> for p in Point(3, 4), Point(14, 5/7):
...     print(p)
Point: x= 3.000  y= 4.000  hypot= 5.000
Point: x=14.000  y= 0.714  hypot=14.018
@end example

このサブクラスは @code{__slots__} に空のタプルをセットしています。これにより、インスタンス辞書の作成を抑制してメモリ使用量を低く保つのに役立ちます。

サブクラス化は新しいフィールドを追加するのには適していません。代わりに、新しい名前付きタプルを @ref{298c,,_fields} 属性を元に作成してください:

@example
>>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
@end example

@code{__doc__} フィールドに直接代入することでドックストリングをカスタマイズすることが出来ます:

@example
>>> Book = namedtuple('Book', ['id', 'title', 'authors'])
>>> Book.__doc__ += ': Hardcover book in active collection'
>>> Book.id.__doc__ = '13-digit ISBN'
>>> Book.title.__doc__ = 'Title of first printing'
>>> Book.authors.__doc__ = 'List of authors sorted by last name'
@end example


バージョン 3.5 で変更: 属性ドックストリングが書き込み可能になりました。



@subsubheading 参考



@itemize *

@item 
名前付きタプルに型ヒントを追加する方法については、 @ref{331,,typing.NamedTuple} を参照してください。
@ref{14ef,,class} キーワードを使った洗練された記法も紹介されています:

@example
class Component(NamedTuple):
    part_number: int
    weight: float
    description: Optional[str] = None
@end example

@item 
タプルではなく、辞書をもとにした変更可能な名前空間を作成するには @ref{4e5,,types.SimpleNamespace()} を参照してください。

@item 
@ref{33,,dataclasses} モジュールは、生成される特殊メソッドをユーザー定義クラスに自動的に追加するためのデコレータや関数を提供しています。
@end itemize


@node OrderedDict オブジェクト,UserDict オブジェクト,namedtuple 名前付きフィールドを持つタプルのファクトリ関数,collections --- コンテナデータ型
@anchor{library/collections ordereddict-objects}@anchor{298d}
@subsubsection @code{OrderedDict} オブジェクト


順序付き辞書は普通の辞書のようですが、順序操作に関係する追加の機能があります。
組み込みの @ref{183,,dict} クラスが挿入順序を記憶しておく機能 (この新しい振る舞いは Python 3.7 で保証されるようになりました) を獲得した今となっては、順序付き辞書の重要性は薄れました。

いまだ残っている @ref{183,,dict} との差分:


@itemize *

@item 
通常の @ref{183,,dict} は対応付けに向いているように設計されました。
挿入順序の追跡は二の次です。

@item 
@ref{7f3,,OrderedDict} は並べ替え操作に向いているように設計されました。
空間効率、反復処理の速度、更新操作のパフォーマンスは二の次です。

@item 
@ref{7f3,,OrderedDict} のアルゴリズムは、頻繁な並べ替え処理を @ref{183,,dict} よりもうまく扱うことができます。後述のレシピに示されている通り、この性質はさまざまな種類の LRU キャッシュの実装に適しています。

@item 
@ref{7f3,,OrderedDict} に対する等価演算は突き合わせ順序もチェックします。

組み込みの @ref{183,,dict} では、順序を考慮した等価演算は @code{p == q and all(k1 == k2 for k1, k2 in zip(p, q))} で実現することができます。

@item 
@ref{7f3,,OrderedDict} の @ref{1505,,popitem()} メソッドはシグネチャが異なります。
どの要素を取り出すかを指定するオプション引数を受け付けます。

組み込みの @ref{183,,dict} の場合、 OrderedDict の @code{od.popitem(last=True)} と同じ機能は、最も右側の (最後の) 要素を取り出すことが保証されている @code{d.popitem()} が果たします。

組み込みの @ref{183,,dict} の場合、 OrderedDict の @code{od.popitem(last=False)} は @code{(k := next(iter(d)), d.pop(k))} で実現できます。これにより、該当する要素のうちで最も左側の (先頭の) ものを辞書から削除して返すことができます。

@item 
@ref{7f3,,OrderedDict} には、 効率的に要素を末尾に置き直す @ref{13f8,,move_to_end()} メソッドがあります。

組み込みの @ref{183,,dict} の場合、キーと値のペアを最も右側 (末尾) に移動する OrderedDict の @code{od.move_to_end(k, last=True)} は @code{d[k] = d.pop(k)} で実現できます。

組み込みの @ref{183,,dict} では、キーと値のペアを最も左側 (先頭) に移動する OrderedDict の @code{od.move_to_end(k, last=False)} を実現する効率の良い方法はありません。

@item 
Python 3.8 以前は、 @ref{183,,dict} には @ref{e86,,__reversed__()} メソッドが欠けています。
@end itemize

@geindex OrderedDict (collections のクラス)
@anchor{library/collections collections OrderedDict}@anchor{7f3}
@deffn {クラス} collections.OrderedDict ([items])

辞書の順序を並べ直すためのメソッドを持つ @ref{183,,dict} のサブクラスのインスタンスを返します。


Added in version 3.1.


@geindex popitem() (collections.OrderedDict のメソッド)
@anchor{library/collections collections OrderedDict popitem}@anchor{1505}
@deffn {メソッド} popitem (last=True)

順序付き辞書の @ref{1505,,popitem()} メソッドは、(key, value) 対を返して消去します。この対は `last' が真なら @abbr{LIFO} で、偽なら @abbr{FIFO,first-in@comma{} first-out@comma{} 先入先出}  で返されます。
@end deffn

@geindex move_to_end() (collections.OrderedDict のメソッド)
@anchor{library/collections collections OrderedDict move_to_end}@anchor{13f8}
@deffn {メソッド} move_to_end (key, last=True)

存在する `key' を順序付き辞書の先頭または末尾に移動します。要素は `last' が真 (デフォルト) の場合に最も右側すなわち末尾に移動します。また `last' が偽の場合には先頭に移動します。指定した `key' が存在しない場合は @ref{5e7,,KeyError} を送出します。

@example
>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> '@w{'}.join(d)
'acdeb'
>>> d.move_to_end('b', last=False)
>>> '@w{'}.join(d)
'bacde'
@end example


Added in version 3.2.

@end deffn
@end deffn

通常のマッピングのメソッドに加え、順序付き辞書は @ref{a65,,reversed()} による逆順の反復もサポートしています。
@anchor{library/collections collections-ordereddict-eq}@anchor{1949}
Equality tests between @ref{7f3,,OrderedDict} objects are order-sensitive
and are roughly equivalent to @code{list(od1.items())==list(od2.items())}.

Equality tests between @ref{7f3,,OrderedDict} objects and other
@ref{ac7,,Mapping} objects are order-insensitive like regular
dictionaries.  This allows @ref{7f3,,OrderedDict} objects to be substituted
anywhere a regular dictionary is used.


バージョン 3.5 で変更: @ref{7f3,,OrderedDict} の項目、キー、値の @ref{298e,,ビュー} が @ref{a65,,reversed()} による逆順の反復をサポートするようになりました。



バージョン 3.6 で変更: 
@geindex Python Enhancement Proposals; PEP 468
PEP 468@footnote{https://peps.python.org/pep-0468/} の受理によって、@ref{7f3,,OrderedDict} のコンストラクタと、@ref{167e,,update()} メソッドに渡したキーワード引数の順序は保持されます。



バージョン 3.9 で変更: 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} で規定されている合成演算子 (@code{|}) と更新演算子 (@code{|=})が追加されました。


@menu
* OrderedDict の例とレシピ:: 

@end menu

@node OrderedDict の例とレシピ,,,OrderedDict オブジェクト
@anchor{library/collections ordereddict-examples-and-recipes}@anchor{298f}
@subsubsection @code{OrderedDict} の例とレシピ


キーが `最後に' 追加されたときの順序を記憶する、順序付き辞書の変種を作るのは簡単です。
新しい値が既存の値を上書きする場合、元々の挿入位置が最後尾へ変更されます:

@example
class LastUpdatedOrderedDict(OrderedDict):
    'Store items in the order the keys were last added'

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self.move_to_end(key)
@end example

@ref{7f3,,OrderedDict} は @ref{be2,,functools.lru_cache()} の変種を実装するのにも役に立ちます:

@example
from collections import OrderedDict
from time import time

class TimeBoundedLRU:
    "LRU Cache that invalidates and refreshes old entries."

    def __init__(self, func, maxsize=128, maxage=30):
        self.cache = OrderedDict()      # @{ args : (timestamp, result)@}
        self.func = func
        self.maxsize = maxsize
        self.maxage = maxage

    def __call__(self, *args):
        if args in self.cache:
            self.cache.move_to_end(args)
            timestamp, result = self.cache[args]
            if time() - timestamp <= self.maxage:
                return result
        result = self.func(*args)
        self.cache[args] = time(), result
        if len(self.cache) > self.maxsize:
            self.cache.popitem(last=False)
        return result
@end example

@example
class MultiHitLRUCache:
    """ LRU cache that defers caching a result until
        it has been requested multiple times.

        To avoid flushing the LRU cache with one-time requests,
        we don't cache until a request has been made more than once.

    """

    def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):
        self.requests = OrderedDict()   # @{ uncached_key : request_count @}
        self.cache = OrderedDict()      # @{ cached_key : function_result @}
        self.func = func
        self.maxrequests = maxrequests  # max number of uncached requests
        self.maxsize = maxsize          # max number of stored return values
        self.cache_after = cache_after

    def __call__(self, *args):
        if args in self.cache:
            self.cache.move_to_end(args)
            return self.cache[args]
        result = self.func(*args)
        self.requests[args] = self.requests.get(args, 0) + 1
        if self.requests[args] <= self.cache_after:
            self.requests.move_to_end(args)
            if len(self.requests) > self.maxrequests:
                self.requests.popitem(last=False)
        else:
            self.requests.pop(args, None)
            self.cache[args] = result
            if len(self.cache) > self.maxsize:
                self.cache.popitem(last=False)
        return result
@end example

@c >>> def square(x):
@c ...     return x * x
@c ...
@c >>> f = MultiHitLRUCache(square, maxsize=4, maxrequests=6)
@c >>> list(map(f, range(10)))  # First requests, don't cache
@c [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
@c >>> f(4)  # Cache the second request
@c 16
@c >>> f(6)  # Cache the second request
@c 36
@c >>> f(2)  # The first request aged out, so don't cache
@c 4
@c >>> f(6)  # Cache hit
@c 36
@c >>> f(4)  # Cache hit and move to front
@c 16
@c >>> list(f.cache.values())
@c [36, 16]
@c >>> set(f.requests).isdisjoint(f.cache)
@c True
@c >>> list(map(f, [9, 8, 7]))   # Cache these second requests
@c [81, 64, 49]
@c >>> list(map(f, [7, 9]))  # Cache hits
@c [49, 81]
@c >>> list(f.cache.values())
@c [16, 64, 49, 81]
@c >>> set(f.requests).isdisjoint(f.cache)
@c True

@node UserDict オブジェクト,UserList オブジェクト,OrderedDict オブジェクト,collections --- コンテナデータ型
@anchor{library/collections userdict-objects}@anchor{2990}
@subsubsection @code{UserDict} オブジェクト


クラス @ref{1d7d,,UserDict} は、辞書オブジェクトのラッパとしてはたらきます。このクラスの必要性は、 @ref{183,,dict} から直接的にサブクラス化できる能力に部分的に取って代わられました; しかし、根底の辞書に属性としてアクセスできるので、このクラスを使った方が簡単になることもあります。

@geindex UserDict (collections のクラス)
@anchor{library/collections collections UserDict}@anchor{1d7d}
@deffn {クラス} collections.UserDict ([initialdata])

辞書をシミュレートするクラスです。インスタンスの内容は通常の辞書に保存され、 @ref{1d7d,,UserDict} インスタンスの @ref{2991,,data} 属性を通してアクセスできます。 `initialdata' が与えられれば、 @ref{2991,,data} はその内容で初期化されます。他の目的のために使えるように、 `initialdata' への参照が保存されないことに注意してください。

マッピングのメソッドと演算をサポートするのに加え、 @ref{1d7d,,UserDict} インスタンスは以下の属性を提供します:

@geindex data (collections.UserDict の属性)
@anchor{library/collections collections UserDict data}@anchor{2991}
@deffn {の属性} data

@ref{1d7d,,UserDict} クラスの内容を保存するために使われる実際の辞書です。
@end deffn
@end deffn

@node UserList オブジェクト,UserString オブジェクト,UserDict オブジェクト,collections --- コンテナデータ型
@anchor{library/collections userlist-objects}@anchor{2992}
@subsubsection @code{UserList} オブジェクト


このクラスはリストオブジェクトのラッパとしてはたらきます。これは独自のリスト風クラスの基底クラスとして便利で、既存のメソッドをオーバーライドしたり新しいメソッドを加えたりできます。こうして、リストに新しい振る舞いを加えられます。

このクラスの必要性は、 @ref{24d,,list} から直接的にサブクラス化できる能力に部分的に取って代わられました; しかし、根底のリストに属性としてアクセスできるので、このクラスを使った方が簡単になることもあります。

@geindex UserList (collections のクラス)
@anchor{library/collections collections UserList}@anchor{16fd}
@deffn {クラス} collections.UserList ([list])

リストをシミュレートするクラスです。インスタンスの内容は通常のリストに保存され、 @ref{16fd,,UserList} インスタンスの @ref{2993,,data} 属性を通してアクセスできます。インスタンスの内容は最初に `list' のコピーに設定されますが、デフォルトでは空リスト @code{[]} です。 `list' は何らかのイテラブル、例えば通常の Python リストや @ref{16fd,,UserList} オブジェクト、です。

ミュータブルシーケンスのメソッドと演算をサポートするのに加え、 @ref{16fd,,UserList} インスタンスは以下の属性を提供します:

@geindex data (collections.UserList の属性)
@anchor{library/collections collections UserList data}@anchor{2993}
@deffn {の属性} data

@ref{16fd,,UserList} クラスの内容を保存するために使われる実際の @ref{24d,,list} オブジェクトです。
@end deffn
@end deffn

`サブクラス化の要件:' @ref{16fd,,UserList} のサブクラスは引数なしか、あるいは一つの引数のどちらかとともに呼び出せるコンストラクタを提供することが期待されています。新しいシーケンスを返すリスト演算は現在の実装クラスのインスタンスを作成しようとします。そのために、データ元として使われるシーケンスオブジェクトである一つのパラメータとともにコンストラクタを呼び出せると想定しています。

派生クラスがこの要求に従いたくないならば、このクラスがサポートしているすべての特殊メソッドはオーバーライドされる必要があります。その場合に提供される必要のあるメソッドについての情報は、ソースを参考にしてください。

@node UserString オブジェクト,,UserList オブジェクト,collections --- コンテナデータ型
@anchor{library/collections userstring-objects}@anchor{2994}
@subsubsection @code{UserString} オブジェクト


クラス @ref{fd3,,UserString} は、文字列オブジェクトのラッパとしてはたらきます。このクラスの必要性は、 @ref{169,,str} から直接的にサブクラス化できる能力に部分的に取って代わられました; しかし、根底の文字列に属性としてアクセスできるので、このクラスを使った方が簡単になることもあります。

@geindex UserString (collections のクラス)
@anchor{library/collections collections UserString}@anchor{fd3}
@deffn {クラス} collections.UserString (seq)

文字列オブジェクトをシミュレートするクラスです。
インスタンスの内容は通常の文字列に保存され、 @ref{fd3,,UserString} インスタンスの @ref{2995,,data} 属性を通してアクセスできます。
インスタンスの内容には最初に `seq' のコピーが設定されます。
`seq' 引数は、組み込みの @ref{169,,str()} 関数で文字列に変換できる任意のオブジェクトです。

文字列のメソッドと演算をサポートするのに加え、 @ref{fd3,,UserString} インスタンスは次の属性を提供します:

@geindex data (collections.UserString の属性)
@anchor{library/collections collections UserString data}@anchor{2995}
@deffn {の属性} data

@ref{fd3,,UserString} クラスの内容を保存するために使われる実際の @ref{169,,str} オブジェクトです。
@end deffn


バージョン 3.5 で変更: 新たなメソッド @code{__getnewargs__}, @code{__rmod__}, @code{casefold}, @code{format_map}, @code{isprintable}, @code{maketrans}。

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node collections abc --- コンテナの抽象基底クラス,heapq --- ヒープキューアルゴリズム,collections --- コンテナデータ型,データ型
@anchor{library/collections abc doc}@anchor{2996}@anchor{library/collections abc collections-abc-abstract-base-classes-for-containers}@anchor{2997}@anchor{library/collections abc module-collections abc}@anchor{1f}@anchor{library/collections abc translation-repo}@anchor{2998}
@subsection @code{collections.abc} --- コンテナの抽象基底クラス


@geindex module; collections.abc


Added in version 3.3: 以前はこのモジュールは @ref{1e,,collections} モジュールの一部でした。


`ソースコード:' Lib/_collections_abc.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/_collections_abc.py}

@c from collections.abc import *
@c import itertools
@c __name__ = '<doctest>'


__________________________________________________________________


このモジュールは、 @ref{13ce,,抽象基底クラス} を提供します。抽象基底クラスは、クラスが特定のインターフェースを提供しているか、例えば @ref{824,,ハッシュ可能} であるかや @ref{13d3,,マッピング} であるかを判定します。

@ref{9c4,,issubclass()} や @ref{2ad,,isinstance()} を使ったインターフェースに対するテストは、以下の3つのいずれかの方法で動作します。


@enumerate 

@item 
A newly written class can inherit directly from one of the
abstract base classes.  The class must supply the required abstract
methods.  The remaining mixin methods come from inheritance and can be
overridden if desired.  Other methods may be added as needed:

@example
class C(Sequence):                      # Direct inheritance
    def __init__(self): ...             # Extra method not required by the ABC
    def __getitem__(self, index):  ...  # Required abstract method
    def __len__(self):  ...             # Required abstract method
    def count(self, value): ...         # Optionally override a mixin method
@end example

@example
>>> issubclass(C, Sequence)
True
>>> isinstance(C(), Sequence)
True
@end example

@item 
Existing classes and built-in classes can be registered as "virtual
subclasses" of the ABCs.  Those classes should define the full API
including all of the abstract methods and all of the mixin methods.
This lets users rely on @ref{9c4,,issubclass()} or @ref{2ad,,isinstance()} tests
to determine whether the full interface is supported.  The exception to
this rule is for methods that are automatically inferred from the rest
of the API:

@example
class D:                                 # No inheritance
    def __init__(self): ...              # Extra method not required by the ABC
    def __getitem__(self, index):  ...   # Abstract method
    def __len__(self):  ...              # Abstract method
    def count(self, value): ...          # Mixin method
    def index(self, value): ...          # Mixin method

Sequence.register(D)                     # Register instead of inherit
@end example

@example
>>> issubclass(D, Sequence)
True
>>> isinstance(D(), Sequence)
True
@end example

この例では、クラス @code{D} は @code{__contains__}, @code{__iter__}, @code{__reversed__} を定義する必要がありません。なぜなら @ref{24d0,,in 演算子}, the @ref{12f1,,反復} ロジック, および @ref{a65,,reversed()} 関数は自動的に @code{__getitem__} と @code{__len__} を使うようにフォールバックするからです。

@item 
Some simple interfaces are directly recognizable by the presence of
the required methods (unless those methods have been set to @ref{885,,None}):

@example
class E:
    def __iter__(self): ...
    def __next__(self): ...
@end example

@example
>>> issubclass(E, Iterable)
True
>>> isinstance(E(), Iterable)
True
@end example

複雑なインターフェースは、単に特定のメソッドが存在すること以上の定義を持つため、3番目のテクニックをサポートしていません。それらのインターフェースはメソッドの意味やメソッド間の関係まで指定するので、特定のメソッド名の存在からだけではインターフェースの推測ができません。たとえば、あるクラスが @code{__getitem__}, @code{__len__}, および @code{__iter__} を提供するというだけでは、 @ref{13dc,,Sequence} と @ref{ac7,,Mapping} を区別するには不十分です。
@end enumerate


Added in version 3.9: これらの抽象クラスは @code{[]} をサポートするようになりました。 @ref{8c1,,ジェネリックエイリアス型} および 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} を参照してください。


@menu
* コレクション抽象基底クラス:: 
* コレクションの抽象基底クラス: コレクションの抽象基底クラス -- 詳細な説明. 詳細な説明
* 例とレシピ:: 

@end menu

@node コレクション抽象基底クラス,コレクションの抽象基底クラス -- 詳細な説明,,collections abc --- コンテナの抽象基底クラス
@anchor{library/collections abc collections-abstract-base-classes}@anchor{a78}@anchor{library/collections abc id1}@anchor{2999}
@subsubsection コレクション抽象基底クラス


collections モジュールは以下の @ref{13ce,,ABC (抽象基底クラス)} を提供します:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ABC

@tab

継承しているクラス

@tab

抽象メソッド

@tab

mixin メソッド

@item

@ref{26b0,,Container} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@tab

@code{__contains__}

@tab

@item

@ref{719,,Hashable} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@tab

@code{__hash__}

@tab

@item

@ref{26ae,,Iterable} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
} @footnote{
@code{isinstance(obj, Iterable)} によるチェックは @ref{26ae,,Iterable} として登録されたクラスや @ref{20aa,,__iter__()} メソッドを持つクラスを検出しますが、 @ref{588,,__getitem__()} メソッドにより反復処理を行うクラスは検出しません。オブジェクトがイテラブル (@ref{12f1,,iterable}) かどうかを確認する唯一の信頼できる方法は @code{iter(obj)} を呼び出すことです。
}

@tab

@tab

@code{__iter__}

@tab

@item

@ref{26af,,Iterator} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@ref{26ae,,Iterable}

@tab

@code{__next__}

@tab

@code{__iter__}

@item

@ref{e85,,Reversible} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@ref{26ae,,Iterable}

@tab

@code{__reversed__}

@tab

@item

@ref{fdb,,Generator}  @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@ref{26af,,Iterator}

@tab

@code{send}, @code{throw}

@tab

@code{close}, @code{__iter__}, @code{__next__}

@item

@ref{71a,,Sized}  @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@tab

@code{__len__}

@tab

@item

@ref{9eb,,Callable}  @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@tab

@code{__call__}

@tab

@item

@ref{e84,,Collection}  @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@ref{71a,,Sized},
@ref{26ae,,Iterable},
@ref{26b0,,Container}

@tab

@code{__contains__},
@code{__iter__},
@code{__len__}

@tab

@item

@ref{13dc,,Sequence}

@tab

@ref{e85,,Reversible},
@ref{e84,,Collection}

@tab

@code{__getitem__},
@code{__len__}

@tab

@code{__contains__}, @code{__iter__}, @code{__reversed__}, @code{index}, @code{count}

@item

@ref{4bf,,MutableSequence}

@tab

@ref{13dc,,Sequence}

@tab

@code{__getitem__},
@code{__setitem__},
@code{__delitem__},
@code{__len__},
@code{insert}

@tab

@ref{13dc,,Sequence} から継承したメソッドと、 @code{append}, @code{clear}, @code{reverse}, @code{extend}, @code{pop}, @code{remove}, @code{__iadd__}

@item

@ref{342,,ByteString}

@tab

@ref{13dc,,Sequence}

@tab

@code{__getitem__},
@code{__len__}

@tab

@ref{13dc,,Sequence} から継承したメソッド

@item

@ref{26a6,,Set}

@tab

@ref{e84,,Collection}

@tab

@code{__contains__},
@code{__iter__},
@code{__len__}

@tab

@code{__le__}, @code{__lt__}, @code{__eq__}, @code{__ne__},
@code{__gt__}, @code{__ge__}, @code{__and__}, @code{__or__},
@code{__sub__}, @code{__rsub__}, @code{__xor__}, @code{__rxor__}
and @code{isdisjoint}

@item

@ref{26b1,,MutableSet}

@tab

@ref{26a6,,Set}

@tab

@code{__contains__},
@code{__iter__},
@code{__len__},
@code{add},
@code{discard}

@tab

@ref{26a6,,Set} から継承したメソッドと、 @code{clear}, @code{pop}, @code{remove}, @code{__ior__}, @code{__iand__}, @code{__ixor__}, @code{__isub__}

@item

@ref{ac7,,Mapping}

@tab

@ref{e84,,Collection}

@tab

@code{__getitem__},
@code{__iter__},
@code{__len__}

@tab

@code{__contains__}, @code{keys}, @code{items}, @code{values}, @code{get}, @code{__eq__}, @code{__ne__}

@item

@ref{12c0,,MutableMapping}

@tab

@ref{ac7,,Mapping}

@tab

@code{__getitem__},
@code{__setitem__},
@code{__delitem__},
@code{__iter__},
@code{__len__}

@tab

@ref{ac7,,Mapping} から継承したメソッドと、 @code{pop}, @code{popitem}, @code{clear}, @code{update}, @code{setdefault}

@item

@ref{26b2,,MappingView}

@tab

@ref{71a,,Sized}

@tab

@tab

@code{__init__}, @code{__len__} and @code{__repr__}

@item

@ref{26b4,,ItemsView}

@tab

@ref{26b2,,MappingView},
@ref{26a6,,Set}

@tab

@tab

@code{__contains__},
@code{__iter__}

@item

@ref{26b3,,KeysView}

@tab

@ref{26b2,,MappingView},
@ref{26a6,,Set}

@tab

@tab

@code{__contains__},
@code{__iter__}

@item

@ref{26b5,,ValuesView}

@tab

@ref{26b2,,MappingView},
@ref{e84,,Collection}

@tab

@tab

@code{__contains__}, @code{__iter__}

@item

@ref{fdc,,Awaitable} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@tab

@code{__await__}

@tab

@item

@ref{fdd,,Coroutine} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@ref{fdc,,Awaitable}

@tab

@code{send}, @code{throw}

@tab

@code{close}

@item

@ref{fdf,,AsyncIterable} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@tab

@code{__aiter__}

@tab

@item

@ref{fde,,AsyncIterator} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@ref{fdf,,AsyncIterable}

@tab

@code{__anext__}

@tab

@code{__aiter__}

@item

@ref{e87,,AsyncGenerator} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@ref{fde,,AsyncIterator}

@tab

@code{asend}, @code{athrow}

@tab

@code{aclose}, @code{__aiter__}, @code{__anext__}

@item

@ref{343,,Buffer} @footnote{
これらの抽象基底クラスは @ref{299a,,__subclasshook__()} をオーバーライドして、必要なメソッドが存在し、かつ @ref{885,,None} に指定されていないことを確かめることによってインターフェースをテストすることをサポートします。このテストは単純なインターフェースに対してのみ有効に働きます。より複雑なインターフェースは基底クラスへの登録や直接派生することが必要になります。
}

@tab

@tab

@code{__buffer__}

@tab

@end multitable


@subsubheading 脚注


@node コレクションの抽象基底クラス -- 詳細な説明,例とレシピ,コレクション抽象基底クラス,collections abc --- コンテナの抽象基底クラス
@anchor{library/collections abc collections-abstract-base-classes-detailed-descriptions}@anchor{299b}
@subsubsection コレクションの抽象基底クラス -- 詳細な説明


@geindex Container (collections.abc のクラス)
@anchor{library/collections abc collections abc Container}@anchor{26b0}
@deffn {クラス} collections.abc.Container

@ref{15d3,,__contains__()} メソッドを提供するクラスの ABC です。
@end deffn

@geindex Hashable (collections.abc のクラス)
@anchor{library/collections abc collections abc Hashable}@anchor{719}
@deffn {クラス} collections.abc.Hashable

@ref{cf3,,__hash__()} メソッドを提供するクラスの ABC です。
@end deffn

@geindex Sized (collections.abc のクラス)
@anchor{library/collections abc collections abc Sized}@anchor{71a}
@deffn {クラス} collections.abc.Sized

@ref{178f,,__len__()} メソッドを提供するクラスの ABC です。
@end deffn

@geindex Callable (collections.abc のクラス)
@anchor{library/collections abc collections abc Callable}@anchor{9eb}
@deffn {クラス} collections.abc.Callable

@ref{77a,,__call__()} メソッドを提供するクラスの ABC です。

@code{Callable} を型アノテーションで使う方法の詳細は、 @ref{26cf,,呼び出し可能オブジェクトのアノテーション} を参照してください。
@end deffn

@geindex Iterable (collections.abc のクラス)
@anchor{library/collections abc collections abc Iterable}@anchor{26ae}
@deffn {クラス} collections.abc.Iterable

@ref{20aa,,__iter__()} メソッドを提供するクラスの ABC です。

@code{isinstance(obj, Iterable)} によるチェックは @ref{26ae,,Iterable} として登録されたクラスや @ref{20aa,,__iter__()} メソッドを持つクラスを検出しますが、 @ref{588,,__getitem__()} メソッドにより反復処理を行うクラスは検出しません。オブジェクトがイテラブル (@ref{12f1,,iterable}) かどうかを確認する唯一の信頼できる方法は @code{iter(obj)} を呼び出すことです。
@end deffn

@geindex Collection (collections.abc のクラス)
@anchor{library/collections abc collections abc Collection}@anchor{e84}
@deffn {クラス} collections.abc.Collection

サイズ付きのイテラブルなコンテナクラスの ABC です。


Added in version 3.6.

@end deffn

@geindex Iterator (collections.abc のクラス)
@anchor{library/collections abc collections abc Iterator}@anchor{26af}
@deffn {クラス} collections.abc.Iterator

@ref{20ad,,__iter__()} メソッドと @ref{14e5,,__next__()} メソッドを提供するクラスの ABC です。 @ref{4c8,,iterator} の定義も参照してください。
@end deffn

@geindex Reversible (collections.abc のクラス)
@anchor{library/collections abc collections abc Reversible}@anchor{e85}
@deffn {クラス} collections.abc.Reversible

@ref{e86,,__reversed__()} メソッドを提供するイテラブルクラスの ABC です。


Added in version 3.6.

@end deffn

@geindex Generator (collections.abc のクラス)
@anchor{library/collections abc collections abc Generator}@anchor{fdb}
@deffn {クラス} collections.abc.Generator

@geindex Python Enhancement Proposals; PEP 342
PEP 342@footnote{https://peps.python.org/pep-0342/} で定義された、@ref{4c8,,イテレータ} を @ref{126d,,send()}, @ref{71c,,throw()}, @ref{1793,,close()} の各メソッドに拡張するプロトコルを実装する、@ref{126c,,ジェネレータ} クラスの ABC です。

@code{Generator} を型アノテーションで使う方法の詳細は、 @ref{299c,,Annotating generators and coroutines} を参照してください。


Added in version 3.5.

@end deffn

@geindex Sequence (collections.abc のクラス)
@geindex MutableSequence (collections.abc のクラス)
@geindex ByteString (collections.abc のクラス)
@anchor{library/collections abc collections abc Sequence}@anchor{13dc}
@deffn {クラス} collections.abc.Sequence
@anchor{library/collections abc collections abc MutableSequence}@anchor{4bf}
@deffnx {クラス} collections.abc.MutableSequence
@anchor{library/collections abc collections abc ByteString}@anchor{342}
@deffnx {クラス} collections.abc.ByteString

読み出し専用の @ref{716,,シーケンス} およびミュータブルな @ref{716,,シーケンス} の ABC です。

Implementation note: Some of the mixin methods, such as
@ref{20aa,,__iter__()}, @ref{e86,,__reversed__()},
and @ref{1979,,index()} make repeated calls to the underlying
@ref{588,,__getitem__()} method.
Consequently, if @ref{588,,__getitem__()} is implemented with constant
access speed, the mixin methods will have linear performance;
however, if the underlying method is linear (as it would be with a
linked list), the mixins will have quadratic performance and will
likely need to be overridden.

@geindex index() (collections.abc.ByteString のメソッド)
@anchor{library/collections abc collections abc ByteString index}@anchor{299d}
@deffn {メソッド} index (value, start=0, stop=None)

Return first index of `value'.

Raises @ref{2ec,,ValueError} if the value is not present.

Supporting the `start' and `stop' arguments is optional, but recommended.


バージョン 3.5 で変更: The @ref{1979,,index()} method gained support for
the `stop' and `start' arguments.

@end deffn


Deprecated since version 3.12, will be removed in version 3.17: The @ref{342,,ByteString} ABC has been deprecated.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union that
explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was
an instance of @code{ByteString} never actually told you anything
useful about the object. Other common buffer types such as
@ref{165,,memoryview} were also never understood as subtypes of
@code{ByteString} (either at runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.

@end deffn

@geindex Set (collections.abc のクラス)
@geindex MutableSet (collections.abc のクラス)
@anchor{library/collections abc collections abc Set}@anchor{26a6}
@deffn {クラス} collections.abc.Set
@anchor{library/collections abc collections abc MutableSet}@anchor{26b1}
@deffnx {クラス} collections.abc.MutableSet

読み出し専用でミュータブルな @ref{2031,,集合} の ABC です。
@end deffn

@geindex Mapping (collections.abc のクラス)
@geindex MutableMapping (collections.abc のクラス)
@anchor{library/collections abc collections abc Mapping}@anchor{ac7}
@deffn {クラス} collections.abc.Mapping
@anchor{library/collections abc collections abc MutableMapping}@anchor{12c0}
@deffnx {クラス} collections.abc.MutableMapping

読み出し専用の @ref{13d3,,マッピング} およびミュータブルな @ref{13d3,,マッピング} の ABC です。
@end deffn

@geindex MappingView (collections.abc のクラス)
@geindex ItemsView (collections.abc のクラス)
@geindex KeysView (collections.abc のクラス)
@geindex ValuesView (collections.abc のクラス)
@anchor{library/collections abc collections abc MappingView}@anchor{26b2}
@deffn {クラス} collections.abc.MappingView
@anchor{library/collections abc collections abc ItemsView}@anchor{26b4}
@deffnx {クラス} collections.abc.ItemsView
@anchor{library/collections abc collections abc KeysView}@anchor{26b3}
@deffnx {クラス} collections.abc.KeysView
@anchor{library/collections abc collections abc ValuesView}@anchor{26b5}
@deffnx {クラス} collections.abc.ValuesView

マッピング、要素、キー、値の @ref{298e,,ビュー} の ABC です。
@end deffn

@geindex Awaitable (collections.abc のクラス)
@anchor{library/collections abc collections abc Awaitable}@anchor{fdc}
@deffn {クラス} collections.abc.Awaitable

@ref{18d,,await} で使用できる @ref{4c9,,awaitable} オブジェクトの ABC です。カスタムの実装は、@ref{f75,,__await__()} メソッドを提供しなければなりません。

@ref{fdd,,Coroutine} ABC の @ref{6b9,,Coroutine} オブジェクトとインスタンスは、すべてこの ABC のインスタンスです。

@cartouche
@quotation 注釈 
In CPython, generator-based coroutines (@ref{126c,,generators}
decorated with @ref{1088,,@@types.coroutine}) are
`awaitables', even though they do not have an @ref{f75,,__await__()} method.
Using @code{isinstance(gencoro, Awaitable)} for them will return @code{False}.
Use @ref{1018,,inspect.isawaitable()} to detect them.
@end quotation
@end cartouche


Added in version 3.5.

@end deffn

@geindex Coroutine (collections.abc のクラス)
@anchor{library/collections abc collections abc Coroutine}@anchor{fdd}
@deffn {クラス} collections.abc.Coroutine

@ref{6b9,,コルーチン} と互換性のあるクラスの ABC です。これらは、@ref{2356,,コルーチンオブジェクト} で定義された @ref{2419,,send()}, @ref{71b,,throw()}, @ref{241a,,close()} のメソッドを実装します。カスタムの実装は、@ref{f75,,__await__()} も実装しなければなりません。@ref{fdd,,Coroutine} のすべてのインスタンスは、 @ref{fdc,,Awaitable} のインスタンスでもあります。

@cartouche
@quotation 注釈 
In CPython, generator-based coroutines (@ref{126c,,generators}
decorated with @ref{1088,,@@types.coroutine}) are
`awaitables', even though they do not have an @ref{f75,,__await__()} method.
Using @code{isinstance(gencoro, Coroutine)} for them will return @code{False}.
Use @ref{1018,,inspect.isawaitable()} to detect them.
@end quotation
@end cartouche

@code{Coroutine} を型アノテーションで使う方法の詳細は、 @ref{299c,,Annotating generators and coroutines} を参照してください。型パラメータの意味と順序は @ref{fdb,,Generator} と同様です。


Added in version 3.5.

@end deffn

@geindex AsyncIterable (collections.abc のクラス)
@anchor{library/collections abc collections abc AsyncIterable}@anchor{fdf}
@deffn {クラス} collections.abc.AsyncIterable

@code{__aiter__} メソッドを提供するクラスの ABC です。@ref{f74,,asynchronous iterable} の定義も参照してください。


Added in version 3.5.

@end deffn

@geindex AsyncIterator (collections.abc のクラス)
@anchor{library/collections abc collections abc AsyncIterator}@anchor{fde}
@deffn {クラス} collections.abc.AsyncIterator

@code{__aiter__} および @code{__anext__} メソッドを提供するクラスの ABC です。@ref{4c7,,asynchronous iterator} の定義も参照してください。


Added in version 3.5.

@end deffn

@geindex AsyncGenerator (collections.abc のクラス)
@anchor{library/collections abc collections abc AsyncGenerator}@anchor{e87}
@deffn {クラス} collections.abc.AsyncGenerator

@geindex Python Enhancement Proposals; PEP 525
PEP 525@footnote{https://peps.python.org/pep-0525/} と 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} に定義されているプロトコルを実装した @ref{249b,,非同期ジェネレータ}  クラスの ABC です。

@code{AsyncGenerator} を型アノテーションで使う方法の詳細は、 @ref{299c,,Annotating generators and coroutines} を参照してください。


Added in version 3.6.

@end deffn

@geindex Buffer (collections.abc のクラス)
@anchor{library/collections abc collections abc Buffer}@anchor{343}
@deffn {クラス} collections.abc.Buffer

@ref{260,,buffer protocol} を実装する @ref{68c,,__buffer__()} メソッドを提供するクラスのABCです。
@geindex Python Enhancement Proposals; PEP 688
PEP 688@footnote{https://peps.python.org/pep-0688/} を参照してください。


Added in version 3.12.

@end deffn

@node 例とレシピ,,コレクションの抽象基底クラス -- 詳細な説明,collections abc --- コンテナの抽象基底クラス
@anchor{library/collections abc examples-and-recipes}@anchor{299e}
@subsubsection 例とレシピ


抽象基底クラスは、クラスやインスタンスが特定の機能を提供しているかどうかを調べることを可能にします。例えば:

@example
size = None
if isinstance(myvar, collections.abc.Sized):
    size = len(myvar)
@end example

幾つかの ABC はコンテナ型 API を提供するクラスを開発するのを助ける mixin 型としても使えます。例えば、 @ref{26a6,,Set} API を提供するクラスを作る場合、3つの基本になる抽象メソッド @ref{15d3,,__contains__()}, @ref{20aa,,__iter__()}, @ref{178f,,__len__()} だけが必要です。ABC が残りの @code{__and__()} や @ref{2692,,isdisjoint()} といったメソッドを提供します:

@example
class ListBasedSet(collections.abc.Set):
    '@w{'}' Alternate set implementation favoring space over speed
        and not requiring the set elements to be hashable. '@w{'}'
    def __init__(self, iterable):
        self.elements = lst = []
        for value in iterable:
            if value not in lst:
                lst.append(value)

    def __iter__(self):
        return iter(self.elements)

    def __contains__(self, value):
        return value in self.elements

    def __len__(self):
        return len(self.elements)

s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2            # The __and__() method is supported automatically
@end example

@ref{26a6,,Set} と @ref{26b1,,MutableSet} を mixin 型として利用するときの注意点:


@enumerate 

@item 
幾つかの set の操作は新しい set を作るので、デフォルトの mixin メソッドは @ref{12f1,,イテラブル} から新しいインスタンスを作成する方法を必要とします。クラスのコンストラクタは @code{ClassName(iterable)} の形のシグネチャを持つと仮定されます。内部の @code{_from_iterable()} という @ref{48e,,classmethod} が @code{cls(iterable)} を呼び出して新しい set を作る部分でこの仮定が使われています。コンストラクタのシグネチャが異なるクラスで @ref{26a6,,Set} を使う場合は、 iterable 引数から新しいインスタンスを生成できるクラスメソッドあるいは仕様に沿ったメソッドで @code{_from_iterable()} をオーバーライドする必要があります。

@item 
(たぶん意味はそのままに速度を向上する目的で)比較をオーバーライドする場合、 @ref{1522,,__le__()} と @ref{1524,,__ge__()} だけを再定義すれば、その他の演算は自動的に追随します。

@item 
@ref{26a6,,Set} mixin型は set のハッシュ値を計算する @code{_hash()} メソッドを提供しますが、すべての set が @ref{824,,hashable} や immutable とは限らないので、 @ref{cf3,,__hash__()} は提供しません。 mixin を使ってハッシュ可能な set を作る場合は、 @ref{26a6,,Set} と @ref{719,,Hashable()} の両方を継承して、 @code{__hash__ = Set._hash} と定義してください。
@end enumerate


@subsubheading 参考



@itemize *

@item 
@ref{26b1,,MutableSet} を使った例として OrderedSet recipe@footnote{https://code.activestate.com/recipes/576694/}。

@item 
ABCs についての詳細は、 @ref{4,,abc} モジュールと 
@geindex Python Enhancement Proposals; PEP 3119
PEP 3119@footnote{https://peps.python.org/pep-3119/} を参照してください。
@end itemize


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node heapq --- ヒープキューアルゴリズム,bisect --- 配列二分法アルゴリズム,collections abc --- コンテナの抽象基底クラス,データ型
@anchor{library/heapq doc}@anchor{299f}@anchor{library/heapq heapq-heap-queue-algorithm}@anchor{29a0}@anchor{library/heapq module-heapq}@anchor{6d}@anchor{library/heapq translation-repo}@anchor{29a1}
@subsection @code{heapq} --- ヒープキューアルゴリズム


@geindex module; heapq

`ソースコード:' Lib/heapq.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/heapq.py}


__________________________________________________________________


このモジュールではヒープキューアルゴリズムの一実装を提供しています。優先度キューアルゴリズムとしても知られています。

Min-heaps are binary trees for which every parent node has a value less than
or equal to any of its children.
We refer to this condition as the heap invariant.

For min-heaps, this implementation uses lists for which
@code{heap[k] <= heap[2*k+1]} and @code{heap[k] <= heap[2*k+2]} for all `k' for which
the compared elements exist.  Elements are counted from zero.  The interesting
property of a min-heap is that its smallest element is always the root,
@code{heap[0]}.

Max-heaps satisfy the reverse invariant: every parent node has a value
`greater' than any of its children.  These are implemented as lists for which
@code{maxheap[2*k+1] <= maxheap[k]} and @code{maxheap[2*k+2] <= maxheap[k]} for all
`k' for which the compared elements exist.
The root, @code{maxheap[0]}, contains the `largest' element;
@code{heap.sort(reverse=True)} maintains the max-heap invariant.

The @code{heapq} API differs from textbook heap algorithms in two aspects: (a)
We use zero-based indexing.  This makes the relationship between the index for
a node and the indexes for its children slightly less obvious, but is more
suitable since Python uses zero-based indexing. (b) Textbooks often focus on
max-heaps, due to their suitability for in-place sorting. Our implementation
favors min-heaps as they better correspond to Python @ref{24d,,lists}.

These two aspects make it possible to view the heap as a regular Python list
without surprises: @code{heap[0]} is the smallest item, and @code{heap.sort()}
maintains the heap invariant!

Like @ref{dc8,,list.sort()}, this implementation uses only the @code{<} operator
for comparisons, for both min-heaps and max-heaps.

In the API below, and in this documentation, the unqualified term `heap'
generally refers to a min-heap.
The API for max-heaps is named using a @code{_max}  suffix.

To create a heap, use a list initialized as @code{[]}, or transform an existing list
into a min-heap or max-heap using the @ref{29a2,,heapify()} or @ref{221,,heapify_max()}
functions, respectively.

The following functions are provided for min-heaps:

@geindex heapify() (heapq モジュール)
@anchor{library/heapq heapq heapify}@anchor{29a2}
@deffn {の関数} heapq.heapify (x)

Transform list `x' into a min-heap, in-place, in linear time.
@end deffn

@geindex heappush() (heapq モジュール)
@anchor{library/heapq heapq heappush}@anchor{16d5}
@deffn {の関数} heapq.heappush (heap, item)

Push the value `item' onto the `heap', maintaining the min-heap invariant.
@end deffn

@geindex heappop() (heapq モジュール)
@anchor{library/heapq heapq heappop}@anchor{16d6}
@deffn {の関数} heapq.heappop (heap)

Pop and return the smallest item from the `heap', maintaining the min-heap
invariant.  If the heap is empty, @ref{174e,,IndexError} is raised.  To access the
smallest item without popping it, use @code{heap[0]}.
@end deffn

@geindex heappushpop() (heapq モジュール)
@anchor{library/heapq heapq heappushpop}@anchor{29a3}
@deffn {の関数} heapq.heappushpop (heap, item)

`item' を `heap' に push した後、pop を行って `heap' から最初の要素を返します。この一続きの動作を @ref{16d5,,heappush()} に引き続いて @ref{16d6,,heappop()} を別々に呼び出すよりも効率的に実行します。
@end deffn

@geindex heapreplace() (heapq モジュール)
@anchor{library/heapq heapq heapreplace}@anchor{29a4}
@deffn {の関数} heapq.heapreplace (heap, item)

`heap' から最小の要素を pop して返し、新たに `item' を push します。ヒープのサイズは変更されません。ヒープが空の場合、 @ref{174e,,IndexError} が送出されます。

この一息の演算は @ref{16d6,,heappop()} に次いで @ref{16d5,,heappush()} を送出するよりも効率的で、固定サイズのヒープを用いている場合にはより適しています。 pop/push の組み合わせは必ずヒープから要素を一つ返し、それを `item' と置き換えます。

返される値は加えられた `item' よりも大きくなるかもしれません。それを望まないなら、代わりに @ref{29a3,,heappushpop()} を使うことを考えてください。この push/pop の組み合わせは二つの値の小さい方を返し、大きい方の値をヒープに残します。
@end deffn

For max-heaps, the following functions are provided:

@geindex heapify_max() (heapq モジュール)
@anchor{library/heapq heapq heapify_max}@anchor{221}
@deffn {の関数} heapq.heapify_max (x)

Transform list `x' into a max-heap, in-place, in linear time.


Added in version 3.14.

@end deffn

@geindex heappush_max() (heapq モジュール)
@anchor{library/heapq heapq heappush_max}@anchor{222}
@deffn {の関数} heapq.heappush_max (heap, item)

Push the value `item' onto the max-heap `heap', maintaining the max-heap
invariant.


Added in version 3.14.

@end deffn

@geindex heappop_max() (heapq モジュール)
@anchor{library/heapq heapq heappop_max}@anchor{223}
@deffn {の関数} heapq.heappop_max (heap)

Pop and return the largest item from the max-heap `heap', maintaining the
max-heap invariant.  If the max-heap is empty, @ref{174e,,IndexError} is raised.
To access the largest item without popping it, use @code{maxheap[0]}.


Added in version 3.14.

@end deffn

@geindex heappushpop_max() (heapq モジュール)
@anchor{library/heapq heapq heappushpop_max}@anchor{225}
@deffn {の関数} heapq.heappushpop_max (heap, item)

Push `item' on the max-heap `heap', then pop and return the largest item
from `heap'.
The combined action runs more efficiently than @ref{222,,heappush_max()}
followed by a separate call to @ref{223,,heappop_max()}.


Added in version 3.14.

@end deffn

@geindex heapreplace_max() (heapq モジュール)
@anchor{library/heapq heapq heapreplace_max}@anchor{224}
@deffn {の関数} heapq.heapreplace_max (heap, item)

Pop and return the largest item from the max-heap `heap' and also push the
new `item'.
The max-heap size doesn't change. If the max-heap is empty,
@ref{174e,,IndexError} is raised.

The value returned may be smaller than the `item' added.  Refer to the
analogous function @ref{29a4,,heapreplace()} for detailed usage notes.


Added in version 3.14.

@end deffn

このモジュールではさらに3つのヒープに基く汎用関数を提供します。

@geindex merge() (heapq モジュール)
@anchor{library/heapq heapq merge}@anchor{1005}
@deffn {の関数} heapq.merge (*iterables, key=None, reverse=False)

複数のソートされた入力をマージ(merge)して一つのソートされた出力にします (たとえば、複数のログファイルの時刻の入ったエントリーをマージします)。ソートされた値にわたる @ref{4c8,,iterator} を返します。

@code{sorted(itertools.chain(*iterables))} と似ていますが、イテレータを返し、一度にはデータをメモリに読み込まず、それぞれの入力ストリームが予め(最小から最大へ)ソートされていることを仮定します。

2 つのオプション引数があり、これらはキーワード引数として指定されなければなりません。

`key' は 1 つの引数からなる @ref{1006,,key function} を指定します。この関数は、入力の各要素から比較のキーを取り出すのに使われます。デフォルト値は @code{None} です (要素を直接比較します)。

`reverse' は真偽値です。 @code{True} を設定した場合、挿入要素は逆向きに比較されたかのように結合されます。  @code{sorted(itertools.chain(*iterables), reverse=True)} でこれに似た挙動を実現するには、全てのイテラブルは降順で並んでいなければなりません。


バージョン 3.5 で変更: オプションの `key' 引数および `reverse' 引数を追加.

@end deffn

@geindex nlargest() (heapq モジュール)
@anchor{library/heapq heapq nlargest}@anchor{29a5}
@deffn {の関数} heapq.nlargest (n, iterable, key=None)

`iterable' で定義されるデータセットのうち、最大値から降順に `n' 個の値のリストを返します。(あたえられた場合) `key' は、引数を一つとる、`iterable' のそれぞれの要素から比較キーを生成する関数を指定します(例 @code{key=str.lower})。以下のコードと同等です: @code{sorted(iterable, key=key, reverse=True)[:n]}
@end deffn

@geindex nsmallest() (heapq モジュール)
@anchor{library/heapq heapq nsmallest}@anchor{29a6}
@deffn {の関数} heapq.nsmallest (n, iterable, key=None)

`iterable' で定義されるデータセットのうち、最小値から昇順に `n' 個の値のリストを返します。(あたえられた場合) `key' は、引数を一つとる、`iterable' のそれぞれの要素から比較キーを生成する関数を指定します(例 @code{key=str.lower})。以下のコードと同等です: @code{sorted(iterable, key=key)[:n]}
@end deffn

後ろ二つの関数は `n' の値が小さな場合に最適な動作をします。大きな値の時には @ref{dc7,,sorted()} 関数の方が効率的です。さらに、 @code{n==1} の時には @ref{110b,,min()} および @ref{110c,,max()} 関数の方が効率的です。この関数を繰り返し使うことが必要なら、iterable を実際のヒープに変えることを考えてください。

@menu
* 基本的な例:: 
* Other Applications:: 
* 優先度キュー実装の注釈:: 
* 理論:: 

@end menu

@node 基本的な例,Other Applications,,heapq --- ヒープキューアルゴリズム
@anchor{library/heapq basic-examples}@anchor{29a7}
@subsubsection 基本的な例


すべての値をヒープに push してから最小値を 1 つずつ pop することで、ヒープソート@footnote{https://ja.wikipedia.org/wiki/%E3%83%92%E3%83%BC%E3%83%97%E3%82%BD%E3%83%BC%E3%83%88} を実装できます:

@example
>>> def heapsort(iterable):
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@end example

これは @code{sorted(iterable)} に似ていますが、 @ref{dc7,,sorted()} とは異なり、この実装はステーブルソートではありません。

ヒープの要素はタプルに出来ます。これは、追跡される主レコードとは別に (タスクの優先度のような) 比較値を指定するときに便利です:

@example
>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')
@end example

@node Other Applications,優先度キュー実装の注釈,基本的な例,heapq --- ヒープキューアルゴリズム
@anchor{library/heapq other-applications}@anchor{29a8}
@subsubsection Other Applications


Medians@footnote{https://en.wikipedia.org/wiki/Median} are a measure of
central tendency for a set of numbers.  In distributions skewed by
outliers, the median provides a more stable estimate than an average
(arithmetic mean).  A running median is an online algorithm@footnote{https://en.wikipedia.org/wiki/Online_algorithm} that updates
continuously as new data arrives.

A running median can be efficiently implemented by balancing two heaps,
a max-heap for values at or below the midpoint and a min-heap for values
above the midpoint.  When the two heaps have the same size, the new
median is the average of the tops of the two heaps; otherwise, the
median is at the top of the larger heap:

@example
def running_median(iterable):
    "Yields the cumulative median of values seen so far."

    lo = []  # max-heap
    hi = []  # min-heap (same size as or one smaller than lo)

    for x in iterable:
        if len(lo) == len(hi):
            heappush_max(lo, heappushpop(hi, x))
            yield lo[0]
        else:
            heappush(hi, heappushpop_max(lo, x))
            yield (lo[0] + hi[0]) / 2
@end example

例えば:

@example
>>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0]))
[5.0, 7.0, 5.0, 7.0, 8.0, 8.5]
@end example

@node 優先度キュー実装の注釈,理論,Other Applications,heapq --- ヒープキューアルゴリズム
@anchor{library/heapq priority-queue-implementation-notes}@anchor{29a9}
@subsubsection 優先度キュー実装の注釈


優先度つきキュー@footnote{https://ja.wikipedia.org/wiki/%E5%84%AA%E5%85%88%E5%BA%A6%E3%81%A4%E3%81%8D%E3%82%AD%E3%83%A5%E3%83%BC} は、ヒープの一般的な使い方で、実装にはいくつか困難な点があります:


@itemize *

@item 
ソート安定性: 優先度が等しい二つのタスクが、もともと追加された順序で返されるためにはどうしたらいいでしょうか？

@item 
(priority, task) ペアに対するタプルの比較は、priority が同じで task がデフォルトの比較順を持たないときに破綻します。

@item 
あるタスクの優先度が変化したら、どうやってそれをヒープの新しい位置に移動させるのでしょうか？

@item 
未解決のタスクが削除される必要があるとき、どのようにそれをキューから探して削除するのでしょうか？
@end itemize

最初の二つの困難の解決策は、項目を優先度、項目番号、そしてタスクを含む 3 要素のリストとして保存することです。この項目番号は、同じ優先度の二つのタスクが、追加された順序で返されるようにするための同点決勝戦として働きます。そして二つの項目番号が等しくなることはありませんので、タプルの比較が二つのタスクを直接比べようとすることはありえません。

比較できないタスク問題のもう一つの解決法は、タスクアイテムを無視して優先順序フィールドだけで比較するラッパークラスです:

@example
from dataclasses import dataclass, field
from typing import Any

@@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)
@end example

残りの困難は主に、未解決のタスクを探して、その優先度を変更したり、完全に削除することです。タスクを探すことは、キュー内の項目を指し示す辞書によってなされます。

項目を削除したり、優先度を変更することは、ヒープ構造の不変関係を壊すことになるので、もっと難しいです。ですから、可能な解決策は、その項目が無効であるものとしてマークし、必要なら変更された優先度の項目を加えることです:

@example
pq = []                         # list of entries arranged in a heap
entry_finder = @{@}               # mapping of tasks to entries
REMOVED = '<removed-task>'      # placeholder for a removed task
counter = itertools.count()     # unique sequence count

def add_task(task, priority=0):
    'Add a new task or update the priority of an existing task'
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heappush(pq, entry)

def remove_task(task):
    'Mark an existing task as REMOVED.  Raise KeyError if not found.'
    entry = entry_finder.pop(task)
    entry[-1] = REMOVED

def pop_task():
    'Remove and return the lowest priority task. Raise KeyError if empty.'
    while pq:
        priority, count, task = heappop(pq)
        if task is not REMOVED:
            del entry_finder[task]
            return task
    raise KeyError('pop from an empty priority queue')
@end example

@node 理論,,優先度キュー実装の注釈,heapq --- ヒープキューアルゴリズム
@anchor{library/heapq theory}@anchor{29aa}
@subsubsection 理論


ヒープとは、全ての `k' について、要素を 0 から数えたときに、@code{a[k] <= a[2*k+1]} かつ  @code{a[k] <= a[2*k+2]} となる配列です。比較のために、存在しない要素を無限大と考えます。ヒープの興味深い属性は @code{a[0]} が常に最小の要素になることです。

上記の奇妙な不変式は、勝ち抜き戦判定の際に効率的なメモリ表現を行うためのものです。以下の番号は @code{a[k]} ではなく `k' とします:

@example
                               0

              1                                 2

      3               4                5               6

  7       8       9       10      11      12      13      14

15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30
@end example

上の木構造では、各セル `k' は @code{2*k+1} および @code{2*k+2} を最大値としています。スポーツに見られるような通常の 2 つ組勝ち抜き戦では、各セルはその下にある二つのセルに対する勝者となっていて、個々のセルの勝者を追跡していくことにより、そのセルに対する全ての相手を見ることができます。しかしながら、このような勝ち抜き戦を使う計算機アプリケーションの多くでは、勝歴を追跡する必要はりません。メモリ効率をより高めるために、勝者が上位に進級した際、下のレベルから持ってきて置き換えることにすると、あるセルとその下位にある二つのセルは異なる三つの要素を含み、かつ上位のセルは二つの下位のセルに対して "勝者と" なります。

このヒープ不変式が常に守られれば、インデックス 0 は明らかに最勝者となります。最勝者の要素を除去し、"次の" 勝者を見つけるための最も単純なアルゴリズム的手法は、ある敗者要素 (ここでは上図のセル 30 とします) を 0 の場所に持っていき、この新しい 0 を濾過するようにしてツリーを下らせて値を交換してゆきます。不変関係が再構築されるまでこれを続けます。この操作は明らかに、ツリー内の全ての要素数に対して対数的な計算量となります。全ての要素について繰り返すと、 `O'(`n' log `n') のソートになります。

このソートの良い点は、新たに挿入する要素が、最後に取り出された 0 番目の要素よりも "良い値" でない限り、ソートを行っている最中に新たな要素を効率的に追加できるというところです。この性質は、シミュレーション的な状況で、ツリーで全ての入力イベントを保持し、"勝者" の状況を最小のスケジュール時刻にするような場合に特に便利です。あるイベントが他のイベント群の実行をスケジュールする際、それらは未来にスケジュールされることになるので、それらのイベント群を容易にヒープに積むことができます。すなわち、ヒープはスケジューラを実装する上で良いデータ構造であるといえます (私はこれを MIDI シーケンサで使っています :-)。

これまで、スケジューラを実装するための様々なデータ構造が広範に研究されてきました。ヒープは、十分高速で、速度はおおむね一定であり、最悪の場合でも平均的な速度とさほど変わらないため、良いデータ構造といえます。しかし、最悪の場合にひどい速度になるとしても、全体的にはより効率の高い他のデータ構造表現も存在します。

ヒープはまた、巨大なディスクのソートでも非常に有用です。おそらくご存知のように、巨大なソートを行うと、複数の "ラン (run)" (予めソートされた配列で、そのサイズは通常 CPU メモリの量に関係しています) が生成され、続いて統合処理 (merging) がこれらのランを判定します。この統合処理はしばしば非常に巧妙に組織されています @footnote{
現在使われているディスクバランス化アルゴリズムは、最近ではもはや巧妙というよりも目障りになっています。これは、ディスクのシーク機能が向上した結果です。巨大な容量を持つテープドライブなど、シーク不能なデバイスでは、事情は全く異なります。テープの 1 つ 1 つの動きが可能な限り効率的に行われるように非常に巧妙な処理を (相当前もって) 確保しなければなりません (統合処理の "進行" に最も多く使用させます)。テープによっては逆方向に読むことさえでき、巻き戻しに時間を取られるのを避けるために使うこともできます。正直、本当に良いテープソートは見ていて素晴らしく驚異的なものです！ソートというのは常に偉大な芸術なのです！:-)
}。重要なのは、最初のソートが可能な限り長いランを生成することです。勝ち抜き戦はこれを達成するための良い方法です。もし利用可能な全てのメモリを使って勝ち抜き戦を行い、要素を置換および濾過処理して現在のランに収めれば、ランダムな入力に対してメモリの二倍のサイズのランを生成することになり、大体順序づけがなされている入力に対してはもっと高い効率になります。

さらに、ディスク上の 0 番目の要素を出力して、現在の勝ち抜き戦に (最後に出力した値に "勝って" しまうために) 収められない入力を得たなら、ヒープには収まらないため、ヒープのサイズは減少します。解放されたメモリは二つ目のヒープを段階的に構築するために巧妙に再利用することができ、この二つ目のヒープは最初のヒープが崩壊していくのと同じ速度で成長します。最初のヒープが完全に消滅したら、ヒープを切り替えて新たなランを開始します。なんと巧妙で効率的なのでしょう！

一言で言うと、ヒープは知って得するメモリ構造です。私はいくつかのアプリケーションでヒープを使っていて、'ヒープ' モジュールを常備するのはいい事だと考えています。:-)

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node bisect --- 配列二分法アルゴリズム,array --- 効率的な数値配列,heapq --- ヒープキューアルゴリズム,データ型
@anchor{library/bisect doc}@anchor{29ab}@anchor{library/bisect bisect-array-bisection-algorithm}@anchor{29ac}@anchor{library/bisect module-bisect}@anchor{12}@anchor{library/bisect translation-repo}@anchor{29ad}
@subsection @code{bisect} --- 配列二分法アルゴリズム


@geindex module; bisect

@c example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com>

`ソースコード:' Lib/bisect.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/bisect.py}


__________________________________________________________________


このモジュールは、挿入のたびにリストをソートすることなく、ソートされた順序でリストを維持するためのサポートを提供します。 コストのかかる比較演算を伴う長いリストの場合、これは線形検索や頻繁な並べ替えよりも改善される可能性があります。

The module is called @code{bisect} because it uses a basic bisection
algorithm to do its work.  Unlike other bisection tools that search for a
specific value, the functions in this module are designed to locate an
insertion point. Accordingly, the functions never call an @ref{cf2,,__eq__()}
method to determine whether a value has been found.  Instead, the
functions only call the @ref{14b8,,__lt__()} method and will return an insertion
point between values in an array.

@cartouche
@quotation 注釈 
The functions in this module are not thread-safe. If multiple threads
concurrently use @code{bisect} functions on the same sequence, this
may result in undefined behaviour. Likewise, if the provided sequence
is mutated by a different thread while a @code{bisect} function
is operating on it, the result is undefined. For example, using
@ref{29ae,,insort_left()} on the same list from multiple threads
may result in the list becoming unsorted.
@end quotation
@end cartouche
@anchor{library/bisect bisect-functions}@anchor{29af}
次の関数が用意されています:

@geindex bisect_left() (bisect モジュール)
@anchor{library/bisect bisect bisect_left}@anchor{29b0}
@deffn {の関数} bisect.bisect_left (a, x, lo=0, hi=len(a), *, key=None)

ソートされた順序を保ったまま `x' を `a' に挿入できる点を探し当てます。リストの中から検索する部分集合を指定するには、パラメータの `lo' と `hi' を使います。デフォルトでは、リスト全体が使われます。`x' がすでに `a' に含まれている場合、挿入点は既存のどのエントリーよりも前(左)になります。戻り値は、@code{list.insert()} の第一引数として使うのに適しています。`a' はすでにソートされているものとします。

返された挿入点 `ip' パーティションは、左のスライスでは @code{all(elem < x for elem in a[lo : ip])} が真となり、右のスライスでは @code{all(elem >= x for elem in a[ip : hi])} が真となるように、配列 `a' を2つのスライスに分割します。

`key' specifies a @ref{1006,,key function} of one argument that is used to
extract a comparison key from each element in the array.  To support
searching complex records, the key function is not applied to the `x' value.

If `key' is @code{None}, the elements are compared directly and
no key function is called.


バージョン 3.10 で変更: `key' パラメータが追加されました。

@end deffn

@geindex bisect_right() (bisect モジュール)
@geindex bisect() (bisect モジュール)
@anchor{library/bisect bisect bisect_right}@anchor{29b1}
@deffn {の関数} bisect.bisect_right (a, x, lo=0, hi=len(a), *, key=None)
@anchor{library/bisect bisect bisect}@anchor{29b2}
@deffnx {の関数} bisect.bisect (a, x, lo=0, hi=len(a), *, key=None)

@ref{29b0,,bisect_left()} と似ていますが、 `a' に含まれる `x' のうち、どのエントリーよりも後ろ(右)にくるような挿入点を返します。

返された挿入点 `ip' パーティションは、左のスライスでは @code{all(elem <= x for elem in a[lo : ip])} が真となり、右のスライスでは @code{all(elem > x for elem in a[ip : hi])} が真となるように、配列 `a' を2つのスライスに分割します。


バージョン 3.10 で変更: `key' パラメータが追加されました。

@end deffn

@geindex insort_left() (bisect モジュール)
@anchor{library/bisect bisect insort_left}@anchor{29ae}
@deffn {の関数} bisect.insort_left (a, x, lo=0, hi=len(a), *, key=None)

`x' を `a' にソート順で挿入します。

This function first runs @ref{29b0,,bisect_left()} to locate an insertion point.
Next, it runs the @ref{23da,,insert()} method on `a' to insert `x' at the
appropriate position to maintain sort order.

To support inserting records in a table, the `key' function (if any) is
applied to `x' for the search step but not for the insertion step.

Keep in mind that the `O'(log `n') search is dominated by the slow `O'(`n')
insertion step.


バージョン 3.10 で変更: `key' パラメータが追加されました。

@end deffn

@geindex insort_right() (bisect モジュール)
@geindex insort() (bisect モジュール)
@anchor{library/bisect bisect insort_right}@anchor{29b3}
@deffn {の関数} bisect.insort_right (a, x, lo=0, hi=len(a), *, key=None)
@anchor{library/bisect bisect insort}@anchor{29b4}
@deffnx {の関数} bisect.insort (a, x, lo=0, hi=len(a), *, key=None)

@ref{29ae,,insort_left()} と似ていますが、 `a' に含まれる `x' のうち、どのエントリーよりも後ろに `x' を挿入します。

This function first runs @ref{29b1,,bisect_right()} to locate an insertion point.
Next, it runs the @ref{23da,,insert()} method on `a' to insert `x' at the
appropriate position to maintain sort order.

To support inserting records in a table, the `key' function (if any) is
applied to `x' for the search step but not for the insertion step.

Keep in mind that the `O'(log `n') search is dominated by the slow `O'(`n')
insertion step.


バージョン 3.10 で変更: `key' パラメータが追加されました。

@end deffn

@menu
* パフォーマンスに関するメモ:: 
* ソート済みリストの探索:: 
* 使用例: 使用例<4>. 

@end menu

@node パフォーマンスに関するメモ,ソート済みリストの探索,,bisect --- 配列二分法アルゴリズム
@anchor{library/bisect performance-notes}@anchor{29b5}
@subsubsection パフォーマンスに関するメモ


`bisect()' と `insort()' を使って時間的制約のあるコードを書くときは、以下のことを念頭に置いてください:


@itemize *

@item 
二分法は、値の範囲を検索するのに有効です。 特定の値を検索する場合は、辞書の方が効率的です。

@item 
The `insort()' functions are `O'(`n') because the logarithmic search step
is dominated by the linear time insertion step.

@item 
The search functions are stateless and discard key function results after
they are used.  Consequently, if the search functions are used in a loop,
the key function may be called again and again on the same array elements.
If the key function isn't fast, consider wrapping it with
@ref{17c8,,functools.cache()} to avoid duplicate computations.  Alternatively,
consider searching an array of precomputed keys to locate the insertion
point (as shown in the examples section below).
@end itemize


@subsubheading 参考



@itemize *

@item 
Sorted Collections@footnote{https://grantjenks.com/docs/sortedcollections/} is a high performance
module that uses `bisect' to managed sorted collections of data.

@item 
bisect を利用して、直接の探索ができ、キー関数をサポートする、完全な機能を持つコレクションクラスを組み立てる SortedCollection recipe@footnote{https://code.activestate.com/recipes/577197-sortedcollection/}。キーは、探索中に不必要な呼び出しをさせないために、予め計算しておきます。
@end itemize


@node ソート済みリストの探索,使用例<4>,パフォーマンスに関するメモ,bisect --- 配列二分法アルゴリズム
@anchor{library/bisect searching-sorted-lists}@anchor{29b6}
@subsubsection ソート済みリストの探索


上記の @ref{29af,,bisect 関数} は挿入点を見つけるには便利ですが、一般的な検索タスクに使うには厄介であったり、使いにくい場合があります。 以下の5つの関数は、それらをソートされたリストの標準的な検索に変換する方法を示しています:

@example
def index(a, x):
    'xにちょうど等しい左端の値を見つける'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

def find_lt(a, x):
    'xより小さい右端の値を見つける'
    i = bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_le(a, x):
    'x以下の右端の値を見つける'
    i = bisect_right(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'xより大きい左端の値を見つける'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

def find_ge(a, x):
    '左端の項目がx以上であることを確認する'
    i = bisect_left(a, x)
    if i != len(a):
        return a[i]
    raise ValueError
@end example

@node 使用例<4>,,ソート済みリストの探索,bisect --- 配列二分法アルゴリズム
@anchor{library/bisect examples}@anchor{29b7}
@subsubsection 使用例

@anchor{library/bisect bisect-example}@anchor{29b8}
@ref{29b2,,bisect()} 関数は数値テーブルの探索に役に立ちます。この例では、 @ref{29b2,,bisect()} を使って、(たとえば)順序のついた数値の区切り点の集合に基づいて、試験の成績の等級を表す文字を調べます。区切り点は 90 以上は 'A'、 80 から 89 は 'B'、などです:

@example
>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
...     i = bisect(breakpoints, score)
...     return grades[i]
...
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
@end example

@ref{29b2,,bisect()} と @ref{29b4,,insort()} 関数もタプルのリストで動作します。 引数 `key' はテーブルのレコードの順序付けに使用されるフィールドを抽出します:

@example
>>> from collections import namedtuple
>>> from operator import attrgetter
>>> from bisect import bisect, insort
>>> from pprint import pprint

>>> Movie = namedtuple('Movie', ('name', 'released', 'director'))

>>> movies = [
...     Movie('Jaws', 1975, 'Spielberg'),
...     Movie('Titanic', 1997, 'Cameron'),
...     Movie('The Birds', 1963, 'Hitchcock'),
...     Movie('Aliens', 1986, 'Cameron')
... ]

>>> # Find the first movie released after 1960
>>> by_year = attrgetter('released')
>>> movies.sort(key=by_year)
>>> movies[bisect(movies, 1960, key=by_year)]
Movie(name='The Birds', released=1963, director='Hitchcock')

>>> # Insert a movie while maintaining sort order
>>> romance = Movie('Love Story', 1970, 'Hiller')
>>> insort(movies, romance, key=by_year)
>>> pprint(movies)
[Movie(name='The Birds', released=1963, director='Hitchcock'),
 Movie(name='Love Story', released=1970, director='Hiller'),
 Movie(name='Jaws', released=1975, director='Spielberg'),
 Movie(name='Aliens', released=1986, director='Cameron'),
 Movie(name='Titanic', released=1997, director='Cameron')]
@end example

キー関数がコストがかかる場合は、レコードのインデックスを見つけるために事前に計算されたキーのリストを検索することにより、関数呼び出しの繰り返しを回避することが可能です:

@example
>>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambda r: r[1])       # Or use operator.itemgetter(1).
>>> keys = [r[1] for r in data]         # Precompute a list of keys.
>>> data[bisect_left(keys, 0)]
('black', 0)
>>> data[bisect_left(keys, 1)]
('blue', 1)
>>> data[bisect_left(keys, 5)]
('red', 5)
>>> data[bisect_left(keys, 8)]
('yellow', 8)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node array --- 効率的な数値配列,weakref --- Weak references,bisect --- 配列二分法アルゴリズム,データ型
@anchor{library/array doc}@anchor{29b9}@anchor{library/array array-efficient-arrays-of-numeric-values}@anchor{29ba}@anchor{library/array module-array}@anchor{8}@anchor{library/array translation-repo}@anchor{29bb}
@subsection @code{array} --- 効率的な数値配列


@geindex module; array

@geindex arrays


__________________________________________________________________


This module defines an object type which can compactly represent an array of
basic values: characters, integers, floating-point numbers.  Arrays are mutable @ref{716,,sequence}
types and behave very much like lists, except that the type of objects stored in
them is constrained.  The type is specified at object creation time by using a
`type code', which is a single character.  The following type codes are
defined:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

型コード

@tab

C の型

@tab

Python の型

@tab

最小サイズ (バイト単位)

@tab

注釈

@item

@code{'b'}

@tab

signed char

@tab

int

@tab

1

@tab

@item

@code{'B'}

@tab

unsigned char

@tab

int

@tab

1

@tab

@item

@code{'u'}

@tab

wchar_t

@tab

Unicode文字(unicode型)

@tab

2

@tab

(1)

@item

@code{'w'}

@tab

Py_UCS4

@tab

Unicode文字(unicode型)

@tab

4

@tab

(2)

@item

@code{'h'}

@tab

signed short

@tab

int

@tab

2

@tab

@item

@code{'H'}

@tab

unsigned short

@tab

int

@tab

2

@tab

@item

@code{'i'}

@tab

signed int

@tab

int

@tab

2

@tab

@item

@code{'I'}

@tab

unsigned int

@tab

int

@tab

2

@tab

@item

@code{'l'}

@tab

signed long

@tab

int

@tab

4

@tab

@item

@code{'L'}

@tab

unsigned long

@tab

int

@tab

4

@tab

@item

@code{'q'}

@tab

signed long long

@tab

int

@tab

8

@tab

@item

@code{'Q'}

@tab

unsigned long long

@tab

int

@tab

8

@tab

@item

@code{'f'}

@tab

浮動小数点数

@tab

浮動小数点数

@tab

4

@tab

@item

@code{'d'}

@tab

double

@tab

浮動小数点数

@tab

8

@tab

@end multitable


注釈:


@enumerate 

@item 
It can be 16 bits or 32 bits depending on the platform.


バージョン 3.9 で変更: @code{array('u')} now uses @code{wchar_t} as C type instead of deprecated
@code{Py_UNICODE}. This change doesn't affect its behavior because
@code{Py_UNICODE} is alias of @code{wchar_t} since Python 3.3.



Deprecated since version 3.3, will be removed in version 3.16: Please migrate to @code{'w'} typecode.


@item 

Added in version 3.13.

@end enumerate

値の実際の表現はマシンアーキテクチャ (厳密に言うとCの実装) によって決まります。値の実際のサイズは @ref{29bc,,array.itemsize} 属性から得られます。

このモジュールは以下の項目を定義しています:

@geindex typecodes (array モジュール)
@anchor{library/array array typecodes}@anchor{29bd}
@deffn {データ} array.typecodes

すべての利用可能なタイプコードを含む文字列
@end deffn

このモジュールでは次の型を定義しています:

@geindex array (array のクラス)
@anchor{library/array array array}@anchor{4be}
@deffn {クラス} array.array (typecode[, initializer])

A new array whose items are restricted by `typecode', and initialized
from the optional `initializer' value, which must be a @ref{192,,bytes}
or @ref{344,,bytearray} object, a Unicode string, or iterable over elements
of the appropriate type.

If given a @ref{192,,bytes} or @ref{344,,bytearray} object, the initializer
is passed to the new array's @ref{1489,,frombytes()} method;
if given a Unicode string, the initializer is passed to the
@ref{29be,,fromunicode()} method;
otherwise, the initializer's iterator is passed to the @ref{29bf,,extend()} method
to add initial items to the array.

Array objects support the ordinary @ref{25c2,,mutable} @ref{716,,sequence} operations of indexing, slicing,
concatenation, and multiplication.  When using slice assignment, the assigned
value must be an array object with the same type code; in all other cases,
@ref{198,,TypeError} is raised. Array objects also implement the buffer interface,
and may be used wherever @ref{193,,bytes-like objects} are supported.

引数 @code{typecode}, @code{initializer} 付きで @ref{1c6e,,監査イベント} @code{array.__new__} を送出します。

@geindex typecode (array.array の属性)
@anchor{library/array array array typecode}@anchor{29c0}
@deffn {の属性} typecode

アレイを作るときに使う型コード文字です。
@end deffn

@geindex itemsize (array.array の属性)
@anchor{library/array array array itemsize}@anchor{29bc}
@deffn {の属性} itemsize

アレイの要素 1 つの内部表現に使われるバイト長です。
@end deffn

@geindex append() (array.array のメソッド)
@anchor{library/array array array append}@anchor{29c1}
@deffn {メソッド} append (x)

値 `x' の新たな要素をアレイの末尾に追加します。
@end deffn

@geindex buffer_info() (array.array のメソッド)
@anchor{library/array array array buffer_info}@anchor{29c2}
@deffn {メソッド} buffer_info ()

アレイの内容を記憶するために使っているバッファの、現在のメモリアドレスと要素数の入ったタプル @code{(address, length)} を返します。バイト単位で表したメモリバッファの大きさは @code{array.buffer_info()[1] * array.itemsize} で計算できます。例えば @code{ioctl()} 操作のような、メモリアドレスを必要とする低レベルな (そして、本質的に危険な) I/Oインターフェースを使って作業する場合に、ときどき便利です。アレイ自体が存在し、長さを変えるような演算を適用しない限り、有効な値を返します。

@cartouche
@quotation 注釈 
C やC++ で書いたコードからアレイオブジェクトを使う場合 (@code{buffer_info()} の情報を使う意味のある唯一の方法です) は、アレイオブジェクトでサポートしているバッファインターフェースを使う方がより理にかなっています。このメソッドは後方互換性のために保守されており、新しいコードでの使用は避けるべきです。バッファインターフェースの説明は @ref{260,,バッファプロトコル (buffer Protocol)} にあります。
@end quotation
@end cartouche
@end deffn

@geindex byteswap() (array.array のメソッド)
@anchor{library/array array array byteswap}@anchor{29c3}
@deffn {メソッド} byteswap ()

アレイのすべての要素に対して「バイトスワップ」 (リトルエンディアンとビッグエンディアンの変換) を行います。このメソッドは大きさが 1、2、4 および 8 バイトの値のみをサポートしています。他の種類の値に使うと @ref{244,,RuntimeError} を送出します。異なるバイトオーダを使うマシンで書かれたファイルからデータを読み込むときに役に立ちます。
@end deffn

@geindex count() (array.array のメソッド)
@anchor{library/array array array count}@anchor{29c4}
@deffn {メソッド} count (x)

シーケンス中の `x' の出現回数を返します。
@end deffn

@geindex extend() (array.array のメソッド)
@anchor{library/array array array extend}@anchor{29bf}
@deffn {メソッド} extend (iterable)

`iterable' から要素を取り出し、アレイの末尾に要素を追加します。 `iterable' が別のアレイ型である場合、二つのアレイは `全く' 同じ型コードでなければなりません。それ以外の場合には @ref{198,,TypeError} を送出します。 `iterable' がアレイでない場合、アレイに値を追加できるような正しい型の要素からなるイテレーション可能オブジェクトでなければなりません。
@end deffn

@geindex frombytes() (array.array のメソッド)
@anchor{library/array array array frombytes}@anchor{1489}
@deffn {メソッド} frombytes (buffer)

Appends items from the @ref{193,,bytes-like object}, interpreting
its content as an array of machine values (as if it had been read
from a file using the @ref{14d8,,fromfile()} method).


Added in version 3.2: 明確化のため @code{fromstring()} の名前が @ref{1489,,frombytes()} に変更されました。

@end deffn

@geindex fromfile() (array.array のメソッド)
@anchor{library/array array array fromfile}@anchor{14d8}
@deffn {メソッド} fromfile (f, n)

@ref{13db,,ファイルオブジェクト} `f' から (マシンのデータ形式そのままで) `n' 個の要素を読み出し、アレイの末尾に要素を追加します。 `n' 個未満の要素しか読めなかった場合は @ref{14f1,,EOFError} を送出しますが、それまでに読み出せた値はアレイに追加されます。
@end deffn

@geindex fromlist() (array.array のメソッド)
@anchor{library/array array array fromlist}@anchor{29c5}
@deffn {メソッド} fromlist (list)

リストから要素を追加します。型に関するエラーが発生した場合にアレイが変更されないことを除き、 @code{for x in list: a.append(x)} と同じです。
@end deffn

@geindex fromunicode() (array.array のメソッド)
@anchor{library/array array array fromunicode}@anchor{29be}
@deffn {メソッド} fromunicode (s)

Extends this array with data from the given Unicode string.
The array must have type code @code{'u'} or @code{'w'}; otherwise a @ref{2ec,,ValueError} is raised.
Use @code{array.frombytes(unicodestring.encode(enc))} to append Unicode data to an
array of some other type.
@end deffn

@geindex index() (array.array のメソッド)
@anchor{library/array array array index}@anchor{9e1}
@deffn {メソッド} index (x[, start[, stop]])

Return the smallest `i' such that `i' is the index of the first occurrence of
`x' in the array.  The optional arguments `start' and `stop' can be
specified to search for `x' within a subsection of the array.  Raise
@ref{2ec,,ValueError} if `x' is not found.


バージョン 3.10 で変更: Added optional `start' and `stop' parameters.

@end deffn

@geindex insert() (array.array のメソッド)
@anchor{library/array array array insert}@anchor{29c6}
@deffn {メソッド} insert (i, x)

アレイ中の位置 `i' の前に値 `x' をもつ新しい要素を挿入します。 `i' の値が負の場合、アレイの末尾からの相対位置として扱います。
@end deffn

@geindex pop() (array.array のメソッド)
@anchor{library/array array array pop}@anchor{29c7}
@deffn {メソッド} pop ([i])

アレイからインデクスが `i' の要素を取り除いて返します。オプションの引数はデフォルトで @code{-1} になっていて、最後の要素を取り除いて返すようになっています。
@end deffn

@geindex remove() (array.array のメソッド)
@anchor{library/array array array remove}@anchor{29c8}
@deffn {メソッド} remove (x)

アレイ中の `x' のうち、最初に現れたものを取り除きます。
@end deffn

@geindex clear() (array.array のメソッド)
@anchor{library/array array array clear}@anchor{4c0}
@deffn {メソッド} clear ()

Remove all elements from the array.


Added in version 3.13.

@end deffn

@geindex reverse() (array.array のメソッド)
@anchor{library/array array array reverse}@anchor{29c9}
@deffn {メソッド} reverse ()

アレイの要素の順番を逆にします。
@end deffn

@geindex tobytes() (array.array のメソッド)
@anchor{library/array array array tobytes}@anchor{1488}
@deffn {メソッド} tobytes ()

array をマシンの値の array に変換して、 bytes の形で返します (@ref{14d9,,tofile()} メソッドを使ってファイルに書かれるバイト列と同じです)。


Added in version 3.2: @code{tostring()} is renamed to @ref{1488,,tobytes()} for clarity.

@end deffn

@geindex tofile() (array.array のメソッド)
@anchor{library/array array array tofile}@anchor{14d9}
@deffn {メソッド} tofile (f)

すべての要素を (マシンの値の形式で) @ref{13db,,file object} `f' に書き込みます。
@end deffn

@geindex tolist() (array.array のメソッド)
@anchor{library/array array array tolist}@anchor{29ca}
@deffn {メソッド} tolist ()

アレイを同じ要素を持つ普通のリストに変換します。
@end deffn

@geindex tounicode() (array.array のメソッド)
@anchor{library/array array array tounicode}@anchor{29cb}
@deffn {メソッド} tounicode ()

Convert the array to a Unicode string.  The array must have a type @code{'u'} or @code{'w'};
otherwise a @ref{2ec,,ValueError} is raised. Use @code{array.tobytes().decode(enc)} to
obtain a Unicode string from an array of some other type.
@end deffn
@end deffn

The string representation of array objects has the form
@code{array(typecode, initializer)}.
The `initializer' is omitted if the array is empty, otherwise it is
a Unicode string if the `typecode' is @code{'u'} or @code{'w'}, otherwise it is
a list of numbers.
The string representation is guaranteed to be able to be converted back to an
array with the same type and value using @ref{4a3,,eval()}, so long as the
@ref{4be,,array} class has been imported using @code{from array import array}.
Variables @code{inf} and @code{nan} must also be defined if it contains
corresponding floating-point values.
Examples:

@example
array('l')
array('w', 'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14, -inf, nan])
@end example


@subsubheading 参考



@table @asis

@item @ref{db,,struct} モジュール

異なる種類のバイナリデータのパックおよびアンパック。

@item NumPy@footnote{https://numpy.org/}

NumPy パッケージは、別の配列型を定義しています。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node weakref --- Weak references,types --- 動的な型生成と組み込み型の名前,array --- 効率的な数値配列,データ型
@anchor{library/weakref doc}@anchor{29cc}@anchor{library/weakref mod-weakref}@anchor{110d}@anchor{library/weakref module-weakref}@anchor{11a}@anchor{library/weakref translation-repo}@anchor{29cd}@anchor{library/weakref weakref-weak-references}@anchor{29ce}
@subsection @code{weakref} --- Weak references


@geindex module; weakref

`ソースコード:' Lib/weakref.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/weakref.py}


__________________________________________________________________


The @code{weakref} module allows the Python programmer to create `weak
references' to objects.

@c When making changes to the examples in this file, be sure to update
@c Lib/test/test_weakref.py::libreftest too!

以下では、用語リファレント(`referent') は弱参照が参照するオブジェクトを意味します。

オブジェクトへの弱参照があることは、そのオブジェクトを生かしておくのには不十分です。リファレントへの参照が弱参照しか残っていない場合、 @ref{17d8,,garbage collection} はリファレントを自由に破棄し、メモリを別のものに再利用することができます。しかし、オブジェクトへの強参照がなくても、オブジェクトが実際に破棄されるまでは、弱参照はオブジェクトを返す場合があります。

弱参照の主な用途は、巨大なオブジェクトを保持するキャッシュやマッピングを実装することです。ここで、キャッシュやマッピングに保持されているからという理由だけで、巨大なオブジェクトが生き続けることは望ましくありません。

For example, if you have a number of large binary image objects, you may wish to
associate a name with each.  If you used a Python dictionary to map names to
images, or images to names, the image objects would remain alive just because
they appeared as values or keys in the dictionaries.  The
@ref{1929,,WeakKeyDictionary} and @ref{192a,,WeakValueDictionary} classes supplied by
the @code{weakref} module are an alternative, using weak references to construct
mappings that don't keep objects alive solely because they appear in the mapping
objects.  If, for example, an image object is a value in a
@ref{192a,,WeakValueDictionary}, then when the last remaining references to that
image object are the weak references held by weak mappings, garbage collection
can reclaim the object, and its corresponding entries in weak mappings are
simply deleted.

@ref{1929,,WeakKeyDictionary} と @ref{192a,,WeakValueDictionary} はその実装に弱参照を使用しており、キーや値がガーベジコレクションによって回収されたことを弱参照辞書に通知するコールバック関数を設定しています。 @ref{7f5,,WeakSet} は @ref{184,,set} インターフェースを実装していますが、 @ref{1929,,WeakKeyDictionary} のように要素への弱参照を持ちます。

@ref{c6f,,finalize} は、オブジェクトのガベージコレクションの実行時にクリーンアップ関数が呼び出されるように登録する、単純な方法を提供します。これは、未加工の弱参照上にコールバック関数を設定するよりも簡単です。なぜなら、オブジェクトのコレクションが完了するまでファイナライザが生き続けることを、モジュールが自動的に保証するからです。

Most programs should find that using one of these weak container types
or @ref{c6f,,finalize} is all they need -- it's not usually necessary to
create your own weak references directly.  The low-level machinery is
exposed by the @code{weakref} module for the benefit of advanced uses.

全てのオブジェクトが弱参照で参照できるわけではありません。弱参照をサポートするオブジェクトは、クラスインスタンス、(C ではなく) Python で書かれた関数、インスタンスメソッド、set オブジェクト、frozenset オブジェクト、 @ref{13db,,file オブジェクト} 、 @ref{126c,,generators} 型のオブジェクト、socket オブジェクト、array オジェクト、deque オブジェクト、正規表現パターンオブジェクト、code オブジェクトです。


バージョン 3.2 で変更: thread.lock, threading.Lock, code オブジェクトのサポートが追加されました。


@ref{24d,,list} や @ref{183,,dict} など、いくつかの組み込み型は弱参照を直接サポートしませんが、以下のようにサブクラス化を行えばサポートを追加できます:

@example
class Dict(dict):
    pass

obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable
@end example

@ref{614,,tuple} や @ref{19b,,int} など、他の組み込み型はサブクラス化しても弱参照をサポートしません。

拡張型は、簡単に弱参照をサポートできます。詳細については、 @ref{29cf,,弱参照(Weak Reference)のサポート} を参照してください。

When @code{__slots__} are defined for a given type, weak reference support is
disabled unless a @code{'__weakref__'} string is also present in the sequence of
strings in the @code{__slots__} declaration.
See @ref{237f,,__slots__ documentation} for details.

@geindex ref (weakref のクラス)
@anchor{library/weakref weakref ref}@anchor{11f2}
@deffn {クラス} weakref.ref (object[, callback])

`object' への弱参照を返します。リファレントがまだ生きているならば、元のオブジェクトは参照オブジェクトの呼び出しで取り出せす。リファレントがもはや生きていないならば、参照オブジェクトを呼び出したときに @ref{885,,None} を返します。 `callback' に @ref{885,,None} 以外の値を与えた場合、オブジェクトをまさに後始末処理しようとするときに呼び出します。このとき弱参照オブジェクトは `callback' の唯一のパラメタとして渡されます。リファレントはもはや利用できません。

同じオブジェクトに対してたくさんの弱参照を作れます。それぞれの弱参照に対して登録されたコールバックは、もっとも新しく登録されたコールバックからもっとも古いものへと呼び出されます。

Exceptions raised by the callback will be noted on the standard error output,
but cannot be propagated; they are handled in exactly the same way as exceptions
raised from an object's @ref{11ff,,__del__()} method.

`object' が @ref{824,,ハッシュ可能} ならば、弱参照はハッシュ可能です。それらは `object' が削除された後でもそれらのハッシュ値を保持します。 `object' が削除されてから初めて @ref{801,,hash()} が呼び出された場合に、その呼び出しは @ref{198,,TypeError} を発生させます。

弱参照は等価性のテストをサポートしていますが、順序をサポートしていません。参照がまだ生きているならば、 `callback' に関係なく二つの参照はそれらのリファレントと同じ等価関係を持ちます。リファレントのどちらか一方が削除された場合、参照オブジェクトが同一である場合に限り、その参照は等価です。

これはサブクラス化可能な型というよりファクトリ関数です。

@geindex __callback__ (weakref.ref の属性)
@anchor{library/weakref weakref ref __callback__}@anchor{11f3}
@deffn {の属性} __callback__

この読み出し専用の属性は、現在弱参照に関連付けられているコールバックを返します。コールバックが存在しないか、弱参照のリファレントが生きていない場合、この属性の値は @code{None}  になります。
@end deffn


バージョン 3.4 で変更: @ref{11f3,,__callback__} 属性が追加されました。

@end deffn

@geindex proxy() (weakref モジュール)
@anchor{library/weakref weakref proxy}@anchor{c46}
@deffn {の関数} weakref.proxy (object[, callback])

弱参照を使う `object' へのプロキシを返します。弱参照オブジェクトを明示的な参照外しをしながら利用する代わりに、多くのケースでプロキシを利用することができます。返されるオブジェクトは、 `object' が呼び出し可能かどうかによって、 @code{ProxyType} または @code{CallableProxyType} のどちらかの型を持ちます。プロキシオブジェクトはリファレントに関係なく @ref{824,,ハッシュ可能} ではありません。これによって、それらの基本的な変更可能という性質による多くの問題を避けています。そして、辞書のキーとしての利用を妨げます。 `callback' は @ref{11f2,,ref()} 関数の同じ名前のパラメータと同じものです。(--- 訳注: リファレントが変更不能型であっても、プロキシはリファレントが消えるという状態の変更があるために、変更可能型です。---)

Accessing an attribute of the proxy object after the referent is
garbage collected raises @ref{1726,,ReferenceError}.


バージョン 3.8 で変更: Extended the operator support on proxy objects to include the matrix
multiplication operators @code{@@} and @code{@@=}.

@end deffn

@geindex getweakrefcount() (weakref モジュール)
@anchor{library/weakref weakref getweakrefcount}@anchor{29d0}
@deffn {の関数} weakref.getweakrefcount (object)

`object' を参照する弱参照とプロキシの数を返します。
@end deffn

@geindex getweakrefs() (weakref モジュール)
@anchor{library/weakref weakref getweakrefs}@anchor{29d1}
@deffn {の関数} weakref.getweakrefs (object)

`object' を参照するすべての弱参照とプロキシオブジェクトのリストを返します。
@end deffn

@geindex WeakKeyDictionary (weakref のクラス)
@anchor{library/weakref weakref WeakKeyDictionary}@anchor{1929}
@deffn {クラス} weakref.WeakKeyDictionary ([dict])

キーを弱参照するマッピングクラス。キーへの強参照がなくなったときに、辞書のエントリは捨てられます。アプリケーションの他の部分が所有するオブジェクトへ属性を追加することもなく、それらのオブジェクトに追加データを関連づけるために使うことができます。これは属性へのアクセスをオーバーライドするオブジェクトに特に便利です。

Note that when a key with equal value to an existing key (but not equal identity)
is inserted into the dictionary, it replaces the value but does not replace the
existing key. Due to this, when the reference to the original key is deleted, it
also deletes the entry in the dictionary:

@example
>>> class T(str): pass
...
>>> k1, k2 = T(), T()
>>> d = weakref.WeakKeyDictionary()
>>> d[k1] = 1   # d = @{k1: 1@}
>>> d[k2] = 2   # d = @{k1: 2@}
>>> del k1      # d = @{@}
@end example

A workaround would be to remove the key prior to reassignment:

@example
>>> class T(str): pass
...
>>> k1, k2 = T(), T()
>>> d = weakref.WeakKeyDictionary()
>>> d[k1] = 1   # d = @{k1: 1@}
>>> del d[k1]
>>> d[k2] = 2   # d = @{k2: 2@}
>>> del k1      # d = @{k2: 2@}
@end example


バージョン 3.9 で変更: 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} で規定されている @code{|} 演算子と @code{|=} 演算子のサポートを追加しました。

@end deffn

@ref{1929,,WeakKeyDictionary} オブジェクトは、追加のメソッドを持ちます。このメソッドは、内部の参照を直接公開します。その参照は、利用される時に生存しているとは限りません。なので、参照を利用する前に、その参照をチェックする必要があります。これにより、必要なくなったキーの参照が残っているために、ガベージコレクタがそのキーを削除できなくなる事態を避ける事ができます。

@geindex keyrefs() (weakref.WeakKeyDictionary のメソッド)
@anchor{library/weakref weakref WeakKeyDictionary keyrefs}@anchor{29d2}
@deffn {メソッド} WeakKeyDictionary.keyrefs ()

キーへの弱参照を持つ iterable オブジェクトを返します。
@end deffn

@geindex WeakValueDictionary (weakref のクラス)
@anchor{library/weakref weakref WeakValueDictionary}@anchor{192a}
@deffn {クラス} weakref.WeakValueDictionary ([dict])

値を弱参照するマッピングクラス。値への強参照が存在しなくなったときに、辞書のエントリは捨てられます。


バージョン 3.9 で変更: 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} で規定されている @code{|} 演算子と @code{|=} 演算子のサポートを追加しました。

@end deffn

@ref{192a,,WeakValueDictionary} objects have an additional method that has the
same issues as the @ref{29d2,,WeakKeyDictionary.keyrefs()} method.

@geindex valuerefs() (weakref.WeakValueDictionary のメソッド)
@anchor{library/weakref weakref WeakValueDictionary valuerefs}@anchor{29d3}
@deffn {メソッド} WeakValueDictionary.valuerefs ()

値への弱参照を持つ iterable オブジェクトを返します。
@end deffn

@geindex WeakSet (weakref のクラス)
@anchor{library/weakref weakref WeakSet}@anchor{7f5}
@deffn {クラス} weakref.WeakSet ([elements])

要素への弱参照を持つ集合型。要素への強参照が無くなったときに、その要素は削除されます。
@end deffn

@geindex WeakMethod (weakref のクラス)
@anchor{library/weakref weakref WeakMethod}@anchor{11f1}
@deffn {クラス} weakref.WeakMethod (method[, callback])

拡張された @ref{11f2,,ref} のサブクラスで、束縛されたメソッドへの弱参照をシミュレートします (つまり、クラスで定義され、インスタンスにあるメソッド)。
束縛されたメソッドは短命なので、標準の弱参照では保持し続けられません。
@ref{11f1,,WeakMethod} には、オブジェクトと元々の関数が死ぬまで束縛されたメソッドを再作成する特別なコードがあります:

@example
>>> class C:
...     def method(self):
...         print("method called!")
...
>>> c = C()
>>> r = weakref.ref(c.method)
>>> r()
>>> r = weakref.WeakMethod(c.method)
>>> r()
<bound method C.method of <__main__.C object at 0x7fc859830220>>
>>> r()()
method called!
>>> del c
>>> gc.collect()
0
>>> r()
>>>
@end example

`callback' is the same as the parameter of the same name to the @ref{11f2,,ref()} function.


Added in version 3.4.

@end deffn

@geindex finalize (weakref のクラス)
@anchor{library/weakref weakref finalize}@anchor{c6f}
@deffn {クラス} weakref.finalize (obj, func, /, *args, **kwargs)

`obj' がガベージコレクションで回収されるときに呼び出される、呼び出し可能なファイナライザオブジェクトを返します。
通常の弱参照とは異なり、ファイナライザは参照しているオブジェクトが回収されるまで必ず生き残り、そのおかげでライフサイクル管理が大いに簡単になります。

ファイナライザは (直接もしくはガベージコレクションのときに) 呼び出されるまで `生きている' と見なされ、呼び出された後には `死んでいます' 。
生きているファイナライザを呼び出すと、 @code{func(*arg, **kwargs)} を評価した結果を返します。一方、死んでいるファイナライザを呼び出すと @ref{885,,None} を返します。

Exceptions raised by finalizer callbacks during garbage collection
will be shown on the standard error output, but cannot be
propagated.  They are handled in the same way as exceptions raised
from an object's @ref{11ff,,__del__()} method or a weak reference's
callback.

プログラムが終了するとき、生き残ったそれぞれのファイナライザは、自身の @ref{d,,atexit} 属性が偽に設定されるまで呼び出され続けます。
ファイナライザは生成された順序の逆順で呼び出されます。

A finalizer will never invoke its callback during the later part of
the @ref{479,,interpreter shutdown} when module globals are liable to have
been replaced by @ref{885,,None}.

@geindex __call__() (weakref.finalize のメソッド)
@anchor{library/weakref weakref finalize __call__}@anchor{29d4}
@deffn {メソッド} __call__ ()

If `self' is alive then mark it as dead and return the result of
calling @code{func(*args, **kwargs)}.  If `self' is dead then return
@ref{885,,None}.
@end deffn

@geindex detach() (weakref.finalize のメソッド)
@anchor{library/weakref weakref finalize detach}@anchor{29d5}
@deffn {メソッド} detach ()

If `self' is alive then mark it as dead and return the tuple
@code{(obj, func, args, kwargs)}.  If `self' is dead then return
@ref{885,,None}.
@end deffn

@geindex peek() (weakref.finalize のメソッド)
@anchor{library/weakref weakref finalize peek}@anchor{29d6}
@deffn {メソッド} peek ()

If `self' is alive then return the tuple @code{(obj, func, args,
kwargs)}.  If `self' is dead then return @ref{885,,None}.
@end deffn

@geindex alive (weakref.finalize の属性)
@anchor{library/weakref weakref finalize alive}@anchor{29d7}
@deffn {の属性} alive

ファイナライザが生きている場合には真、そうでない場合には偽のプロパティです。
@end deffn

@geindex atexit (weakref.finalize の属性)
@anchor{library/weakref weakref finalize atexit}@anchor{29d8}
@deffn {の属性} atexit

A writable boolean property which by default is true.  When the
program exits, it calls all remaining live finalizers for which
@ref{29d8,,atexit} is true.  They are called in reverse order of
creation.
@end deffn

@cartouche
@quotation 注釈 
It is important to ensure that `func', `args' and `kwargs' do
not own any references to `obj', either directly or indirectly,
since otherwise `obj' will never be garbage collected.  In
particular, `func' should not be a bound method of `obj'.
@end quotation
@end cartouche


Added in version 3.4.

@end deffn

@geindex ReferenceType (weakref モジュール)
@anchor{library/weakref weakref ReferenceType}@anchor{1b5d}
@deffn {データ} weakref.ReferenceType

弱参照オブジェクトのための型オブジェクト。
@end deffn

@geindex ProxyType (weakref モジュール)
@anchor{library/weakref weakref ProxyType}@anchor{1b5e}
@deffn {データ} weakref.ProxyType

呼び出し可能でないオブジェクトのプロキシのための型オブジェクト。
@end deffn

@geindex CallableProxyType (weakref モジュール)
@anchor{library/weakref weakref CallableProxyType}@anchor{1b5f}
@deffn {データ} weakref.CallableProxyType

呼び出し可能なオブジェクトのプロキシのための型オブジェクト。
@end deffn

@geindex ProxyTypes (weakref モジュール)
@anchor{library/weakref weakref ProxyTypes}@anchor{29d9}
@deffn {データ} weakref.ProxyTypes

プロキシのためのすべての型オブジェクトを含むシーケンス。これは両方のプロキシ型の名前付けに依存しないで、オブジェクトがプロキシかどうかのテストをより簡単にできます。
@end deffn


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 205

@item PEP 205@footnote{https://peps.python.org/pep-0205/} - 弱参照

この機能の提案と理論的根拠。初期の実装と他の言語における類似の機能についての情報へのリンクを含んでいます。
@end table


@menu
* 弱参照オブジェクト:: 
* 使用例: 使用例<5>. 
* ファイナライザオブジェクト:: 
* Comparing finalizers with __del__() methods: Comparing finalizers with __del__ methods. 

@end menu

@node 弱参照オブジェクト,使用例<5>,,weakref --- Weak references
@anchor{library/weakref weak-reference-objects}@anchor{29da}@anchor{library/weakref weakref-objects}@anchor{29db}
@subsubsection 弱参照オブジェクト


Weak reference objects have no methods and no attributes besides
@ref{11f3,,ref.__callback__}. A weak reference object allows the referent to be
obtained, if it still exists, by calling it:

@example
>>> import weakref
>>> class Object:
...     pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> o2 = r()
>>> o is o2
True
@end example

リファレントがもはや存在しないならば、参照オブジェクトの呼び出しは @ref{885,,None} を返します:

@example
>>> del o, o2
>>> print(r())
None
@end example

弱参照オブジェクトがまだ生きているかどうかのテストは、式 @code{ref() is not None} を用いて行われます。通常、参照オブジェクトを使う必要があるアプリケーションコードはこのパターンに従います:

@example
# r is a weak reference object
o = r()
if o is None:
    # referent has been garbage collected
    print("Object has been deallocated; can't frobnicate.")
else:
    print("Object is still live!")
    o.do_something_useful()
@end example

"生存性(liveness)"のテストを分割すると、スレッド化されたアプリケーションにおいて競合状態を作り出します。 (訳注:@code{if r() is not None: r().do_something()} では、2度目のr()がNoneを返す可能性があります) 弱参照が呼び出される前に、他のスレッドは弱参照が無効になる原因となり得ます。上で示したイディオムは、シングルスレッドのアプリケーションと同じくマルチスレッド化されたアプリケーションにおいても安全です。

サブクラス化を行えば、 @ref{11f2,,ref} オブジェクトの特殊なバージョンを作成できます。これは @ref{192a,,WeakValueDictionary} の実装で使われており、マップ内の各エントリによるメモリのオーバヘッドを減らしています。こうした実装は、ある参照に追加情報を関連付けたい場合に便利ですし、リファレントを取り出すための呼び出し時に何らかの追加処理を行いたい場合にも使えます。

以下の例では、 @ref{11f2,,ref} のサブクラスを使って、あるオブジェクトに追加情報を保存し、リファレントがアクセスされたときにその値に作用をできるようにするための方法を示しています:

@example
import weakref

class ExtendedRef(weakref.ref):
    def __init__(self, ob, callback=None, /, **annotations):
        super().__init__(ob, callback)
        self.__counter = 0
        for k, v in annotations.items():
            setattr(self, k, v)

    def __call__(self):
        """Return a pair containing the referent and the number of
        times the reference has been called.
        """
        ob = super().__call__()
        if ob is not None:
            self.__counter += 1
            ob = (ob, self.__counter)
        return ob
@end example

@node 使用例<5>,ファイナライザオブジェクト,弱参照オブジェクト,weakref --- Weak references
@anchor{library/weakref example}@anchor{29dc}@anchor{library/weakref weakref-example}@anchor{29dd}
@subsubsection 使用例


この簡単な例では、アプリケーションが以前に参照したオブジェクトを取り出すためにオブジェクトIDを利用する方法を示します。オブジェクトに生きたままであることを強制することなく、オブジェクトの IDを他のデータ構造の中で使うことができ、必要に応じてIDからオブジェクトを取り出せます。

@c Example contributed by Tim Peters.

@example
import weakref

_id2obj_dict = weakref.WeakValueDictionary()

def remember(obj):
    oid = id(obj)
    _id2obj_dict[oid] = obj
    return oid

def id2obj(oid):
    return _id2obj_dict[oid]
@end example

@node ファイナライザオブジェクト,Comparing finalizers with __del__ methods,使用例<5>,weakref --- Weak references
@anchor{library/weakref finalize-examples}@anchor{29de}@anchor{library/weakref finalizer-objects}@anchor{29df}
@subsubsection ファイナライザオブジェクト


The main benefit of using @ref{c6f,,finalize} is that it makes it simple
to register a callback without needing to preserve the returned finalizer
object.  For instance

@example
>>> import weakref
>>> class Object:
...     pass
...
>>> kenny = Object()
>>> weakref.finalize(kenny, print, "You killed Kenny!")
<finalize object at ...; for 'Object' at ...>
>>> del kenny
You killed Kenny!
@end example

ファイナライザは直接呼び出すこともできます。ただし、ファイナライザはコールバックを最大でも一度しか呼び出しません。

@example
>>> def callback(x, y, z):
...     print("CALLBACK")
...     return x + y + z
...
>>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> assert f.alive
>>> assert f() == 6
CALLBACK
>>> assert not f.alive
>>> f()                     # callback not called because finalizer dead
>>> del obj                 # callback not called because finalizer dead
@end example

You can unregister a finalizer using its @ref{29d5,,detach()}
method.  This kills the finalizer and returns the arguments passed to
the constructor when it was created.

@example
>>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> f.detach()
(<...Object object ...>, <function callback ...>, (1, 2), @{'z': 3@})
>>> newobj, func, args, kwargs = _
>>> assert not f.alive
>>> assert newobj is obj
>>> assert func(*args, **kwargs) == 6
CALLBACK
@end example

Unless you set the @ref{29d8,,atexit} attribute to
@ref{d2b,,False}, a finalizer will be called when the program exits if it
is still alive.  For instance

@example
>>> obj = Object()
>>> weakref.finalize(obj, print, "obj dead or exiting")
<finalize object at ...; for 'Object' at ...>
>>> exit()
obj dead or exiting
@end example

@node Comparing finalizers with __del__ methods,,ファイナライザオブジェクト,weakref --- Weak references
@anchor{library/weakref comparing-finalizers-with-del-methods}@anchor{29e0}
@subsubsection Comparing finalizers with @code{__del__()} methods


インスタンスが一時ディレクトリを表す、クラスを作成するとします。そのディレクトリは、次のイベントのいずれかが起きた時に、そのディレクトリの内容とともに削除されるべきです。


@itemize *

@item 
オブジェクトのガベージコレクションが行われた場合

@item 
the object's @code{remove()} method is called, or

@item 
プログラムが終了した場合
@end itemize

We might try to implement the class using a @ref{11ff,,__del__()} method as
follows:

@example
class TempDir:
    def __init__(self):
        self.name = tempfile.mkdtemp()

    def remove(self):
        if self.name is not None:
            shutil.rmtree(self.name)
            self.name = None

    @@property
    def removed(self):
        return self.name is None

    def __del__(self):
        self.remove()
@end example

Starting with Python 3.4, @ref{11ff,,__del__()} methods no longer prevent
reference cycles from being garbage collected, and module globals are
no longer forced to @ref{885,,None} during @ref{479,,interpreter shutdown}.
So this code should work without any issues on CPython.

However, handling of @ref{11ff,,__del__()} methods is notoriously implementation
specific, since it depends on internal details of the interpreter's garbage
collector implementation.

A more robust alternative can be to define a finalizer which only references
the specific functions and objects that it needs, rather than having access
to the full state of the object:

@example
class TempDir:
    def __init__(self):
        self.name = tempfile.mkdtemp()
        self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)

    def remove(self):
        self._finalizer()

    @@property
    def removed(self):
        return not self._finalizer.alive
@end example

Defined like this, our finalizer only receives a reference to the details
it needs to clean up the directory appropriately. If the object never gets
garbage collected the finalizer will still be called at exit.

The other advantage of weakref based finalizers is that they can be used to
register finalizers for classes where the definition is controlled by a
third party, such as running code when a module is unloaded:

@example
import weakref, sys
def unloading_module():
    # implicit reference to the module globals from the function body
weakref.finalize(sys.modules[__name__], unloading_module)
@end example

@cartouche
@quotation 注釈 
If you create a finalizer object in a daemonic thread just as the program
exits then there is the possibility that the finalizer
does not get called at exit.  However, in a daemonic thread
@ref{a7e,,atexit.register()}, @code{try: ... finally: ...} and @code{with: ...}
do not guarantee that cleanup occurs either.
@end quotation
@end cartouche

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node types --- 動的な型生成と組み込み型の名前,copy --- 浅いコピーおよび深いコピー操作,weakref --- Weak references,データ型
@anchor{library/types doc}@anchor{29e1}@anchor{library/types module-types}@anchor{109}@anchor{library/types translation-repo}@anchor{29e2}@anchor{library/types types-dynamic-type-creation-and-names-for-built-in-types}@anchor{29e3}
@subsection @code{types} --- 動的な型生成と組み込み型の名前


@geindex module; types

`ソースコード:' Lib/types.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/types.py}


__________________________________________________________________


このモジュールは新しい型の動的な生成を支援するユーティリティ関数を定義します。

さらに、標準の Python インタプリタによって使用されているものの、 @ref{19b,,int} や @ref{169,,str} のように組み込みとして公開されていないようないくつかのオブジェクト型の名前を定義しています。

最後に、組み込みになるほど基本的でないような追加の型関連のユーティリティと関数をいくつか提供しています。

@menu
* 動的な型生成:: 
* 標準的なインタプリタ型:: 
* 追加のユーティリティクラスと関数:: 
* コルーチンユーティリティ関数:: 

@end menu

@node 動的な型生成,標準的なインタプリタ型,,types --- 動的な型生成と組み込み型の名前
@anchor{library/types dynamic-type-creation}@anchor{29e4}
@subsubsection 動的な型生成


@geindex new_class() (types モジュール)
@anchor{library/types types new_class}@anchor{1379}
@deffn {の関数} types.new_class (name, bases=(), kwds=None, exec_body=None)

適切なメタクラスを使用して動的にクラスオブジェクトを生成します。

最初の3つの引数はクラス定義ヘッダーを構成する—クラス名、基底クラス (順番に)、キーワード引数 (例えば @code{metaclass})—です。

`exec_body' 引数は、新規に生成されたクラスの名前空間を構築するために使用されるコールバックです。それは唯一の引数としてクラスの名前空間を受け取り、クラスの内容で名前空間を直接更新します。コールバックが渡されない場合、それは @code{lambda ns: None} を渡すことと同じ効果があります。


Added in version 3.3.

@end deffn

@geindex prepare_class() (types モジュール)
@anchor{library/types types prepare_class}@anchor{137a}
@deffn {の関数} types.prepare_class (name, bases=(), kwds=None)

適切なメタクラスを計算してクラスの名前空間を生成します。

引数はクラス定義ヘッダーを構成する要素—クラス名、基底クラス (順番に)、キーワード引数 (例えば @code{metaclass})—です。

返り値は @code{metaclass, namespace, kwds} の3要素のタプルです

`metaclass' は適切なメタクラスです。`namespace' は用意されたクラスの名前空間です。また `kwds' は、@code{'metaclass'} エントリが削除された、渡された `kwds' 引数の更新されたコピーです。`kwds' 引数が渡されなければ、これは空の dict になります。


Added in version 3.3.



バージョン 3.6 で変更: 返されるタプルの @code{namespace} 要素のデフォルト値が変更されました。
現在では、メタクラスが @code{__prepare__} メソッドを持っていないときは、挿入順序を保存するマッピングが使われます。

@end deffn


@subsubheading 参考



@table @asis

@item @ref{23be,,メタクラス}

これらの関数によってサポートされるクラス生成プロセスの完全な詳細

@geindex Python Enhancement Proposals; PEP 3115

@item PEP 3115@footnote{https://peps.python.org/pep-3115/} - Metaclasses in Python 3000

@code{__prepare__} 名前空間フックの導入
@end table


@geindex resolve_bases() (types モジュール)
@anchor{library/types types resolve_bases}@anchor{d95}
@deffn {の関数} types.resolve_bases (bases)

Resolve MRO entries dynamically as specified by 
@geindex Python Enhancement Proposals; PEP 560
PEP 560@footnote{https://peps.python.org/pep-0560/}.

This function looks for items in `bases' that are not instances of
@ref{f44,,type}, and returns a tuple where each such object that has
an @ref{ce3,,__mro_entries__()} method is replaced with an unpacked result of
calling this method.  If a `bases' item is an instance of @ref{f44,,type},
or it doesn't have an @code{__mro_entries__()} method, then it is included in
the return tuple unchanged.


Added in version 3.7.

@end deffn

@geindex get_original_bases() (types モジュール)
@anchor{library/types types get_original_bases}@anchor{6f5}
@deffn {の関数} types.get_original_bases (cls, /)

Return the tuple of objects originally given as the bases of `cls' before
the @ref{ce3,,__mro_entries__()} method has been called on any bases
(following the mechanisms laid out in 
@geindex Python Enhancement Proposals; PEP 560
PEP 560@footnote{https://peps.python.org/pep-0560/}). This is useful for
introspecting @ref{6f6,,Generics}.

For classes that have an @code{__orig_bases__} attribute, this
function returns the value of @code{cls.__orig_bases__}.
For classes without the @code{__orig_bases__} attribute,
@ref{16c5,,cls.__bases__} is returned.

例:

@example
from typing import TypeVar, Generic, NamedTuple, TypedDict

T = TypeVar("T")
class Foo(Generic[T]): ...
class Bar(Foo[int], float): ...
class Baz(list[str]): ...
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
Spam = TypedDict("Spam", @{"a": int, "b": str@})

assert Bar.__bases__ == (Foo, float)
assert get_original_bases(Bar) == (Foo[int], float)

assert Baz.__bases__ == (list,)
assert get_original_bases(Baz) == (list[str],)

assert Eggs.__bases__ == (tuple,)
assert get_original_bases(Eggs) == (NamedTuple,)

assert Spam.__bases__ == (dict,)
assert get_original_bases(Spam) == (TypedDict,)

assert int.__bases__ == (object,)
assert get_original_bases(int) == (object,)
@end example


Added in version 3.12.

@end deffn


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 560
PEP 560@footnote{https://peps.python.org/pep-0560/} - typing モジュールとジェネリック型に対する言語コアによるサポート


@node 標準的なインタプリタ型,追加のユーティリティクラスと関数,動的な型生成,types --- 動的な型生成と組み込み型の名前
@anchor{library/types standard-interpreter-types}@anchor{29e5}
@subsubsection 標準的なインタプリタ型


このモジュールは、Python インタプリタを実装するために必要な多くの型に対して名前を提供します。それは、@code{listiterator} 型のような、単に処理中に付随的に発生するいくつかの型が含まれることを意図的に避けています。

これらの名前は典型的に @ref{2ad,,isinstance()} や @ref{9c4,,issubclass()} によるチェックに使われます。

これらのタイプのいずれかをインスタンス化する場合、シグネチャは Python のバージョンによって異なる可能性があることに注意してください。

以下の型に対して標準的な名前が定義されています:

@geindex NoneType (types モジュール)
@anchor{library/types types NoneType}@anchor{a52}
@deffn {データ} types.NoneType

@ref{885,,None} の型です。


Added in version 3.10.

@end deffn

@geindex FunctionType (types モジュール)
@geindex LambdaType (types モジュール)
@anchor{library/types types FunctionType}@anchor{a83}
@deffn {データ} types.FunctionType
@anchor{library/types types LambdaType}@anchor{29e6}
@deffnx {データ} types.LambdaType

ユーザ定義の関数と @ref{14b5,,lambda} 式によって生成された関数の型です。

引数 @code{code} を指定して @ref{1c6e,,監査イベント} @code{function.__new__} を送出します。

この監査イベントは、関数オブジェクトを直接インスタンス化した場合にのみ発生し、通常のコンパイル時には発生しません。
@end deffn

@geindex GeneratorType (types モジュール)
@anchor{library/types types GeneratorType}@anchor{19ab}
@deffn {データ} types.GeneratorType

ジェネレータ関数によって生成された @ref{126c,,ジェネレータ} イテレータオブジェクトの型です。
@end deffn

@geindex CoroutineType (types モジュール)
@anchor{library/types types CoroutineType}@anchor{1089}
@deffn {データ} types.CoroutineType

@ref{7ed,,async def} 関数に生成される @ref{6b9,,コルーチン} オブジェクトです。


Added in version 3.5.

@end deffn

@geindex AsyncGeneratorType (types モジュール)
@anchor{library/types types AsyncGeneratorType}@anchor{29e7}
@deffn {データ} types.AsyncGeneratorType

非同期ジェネレータ関数によって作成された @ref{249b,,非同期ジェネレータ} イテレータオブジェクトの型です。


Added in version 3.6.

@end deffn

@geindex CodeType (types のクラス)
@anchor{library/types types CodeType}@anchor{32f}
@deffn {クラス} types.CodeType (**kwargs)

@geindex 組み込み関数;コンパイル

The type of @ref{4e6,,code objects} such as returned by @ref{4b1,,compile()}.

引数 @code{code}, @code{filename}, @code{name}, @code{argcount}, @code{posonlyargcount}, @code{kwonlyargcount}, @code{nlocals}, @code{stacksize}, @code{flags} を指定して @ref{1c6e,,監査イベント} @code{code.__new__} を送出します。

Note that the audited arguments may not match the names or positions
required by the initializer.  The audit event only occurs for direct
instantiation of code objects, and is not raised for normal compilation.
@end deffn

@geindex CellType (types モジュール)
@anchor{library/types types CellType}@anchor{29e8}
@deffn {データ} types.CellType

The type for cell objects: such objects are used as containers for
a function's @ref{1893,,closure variables}.


Added in version 3.8.

@end deffn

@geindex MethodType (types モジュール)
@anchor{library/types types MethodType}@anchor{1b83}
@deffn {データ} types.MethodType

ユーザー定義のクラスのインスタンスのメソッドの型です。
@end deffn

@geindex BuiltinFunctionType (types モジュール)
@geindex BuiltinMethodType (types モジュール)
@anchor{library/types types BuiltinFunctionType}@anchor{29e9}
@deffn {データ} types.BuiltinFunctionType
@anchor{library/types types BuiltinMethodType}@anchor{29ea}
@deffnx {データ} types.BuiltinMethodType

@ref{840,,len()} や @ref{277,,sys.exit()} のような組み込み関数や、組み込み型のメソッドの型です。 (ここでは "組み込み" という単語を "Cで書かれた" という意味で使っています)
@end deffn

@geindex WrapperDescriptorType (types モジュール)
@anchor{library/types types WrapperDescriptorType}@anchor{d92}
@deffn {データ} types.WrapperDescriptorType

The type of methods of some built-in data types and base classes such as
@ref{8bf,,object.__init__()} or @ref{14b8,,object.__lt__()}.


Added in version 3.7.

@end deffn

@geindex MethodWrapperType (types モジュール)
@anchor{library/types types MethodWrapperType}@anchor{85b}
@deffn {データ} types.MethodWrapperType

The type of `bound' methods of some built-in data types and base classes.
For example it is the type of @code{object().__str__}.


Added in version 3.7.

@end deffn

@geindex NotImplementedType (types モジュール)
@anchor{library/types types NotImplementedType}@anchor{a53}
@deffn {データ} types.NotImplementedType

@ref{1a2,,NotImplemented} の型です。


Added in version 3.10.

@end deffn

@geindex MethodDescriptorType (types モジュール)
@anchor{library/types types MethodDescriptorType}@anchor{d93}
@deffn {データ} types.MethodDescriptorType

The type of methods of some built-in data types such as @ref{2609,,str.join()}.


Added in version 3.7.

@end deffn

@geindex ClassMethodDescriptorType (types モジュール)
@anchor{library/types types ClassMethodDescriptorType}@anchor{d94}
@deffn {データ} types.ClassMethodDescriptorType

The type of `unbound' class methods of some built-in data types such as
@code{dict.__dict__['fromkeys']}.


Added in version 3.7.

@end deffn

@geindex ModuleType (types のクラス)
@anchor{library/types types ModuleType}@anchor{1014}
@deffn {クラス} types.ModuleType (name, doc=None)

@ref{19de,,module} の型です。コンストラクタは生成するモジュールの名前と任意でその @ref{22ec,,docstring} を受け取ります。


@subsubheading 参考



@table @asis

@item @ref{235e,,Documentation on module objects}

Provides details on the special attributes that can be found on
instances of @code{ModuleType}.

@item @ref{1013,,importlib.util.module_from_spec()}

Modules created using the @code{ModuleType} constructor are
created with many of their special attributes unset or set to default
values. @code{module_from_spec()} provides a more robust way of
creating @code{ModuleType} instances which ensures the various
attributes are set appropriately.
@end table

@end deffn

@geindex EllipsisType (types モジュール)
@anchor{library/types types EllipsisType}@anchor{a51}
@deffn {データ} types.EllipsisType

@ref{2328,,Ellipsis} の型です。


Added in version 3.10.

@end deffn

@geindex GenericAlias (types のクラス)
@anchor{library/types types GenericAlias}@anchor{9ec}
@deffn {クラス} types.GenericAlias (t_origin, t_args)

The type of @ref{8c1,,parameterized generics} such as
@code{list[int]}.

@code{t_origin} should be a non-parameterized generic class, such as @code{list},
@code{tuple} or @code{dict}.  @code{t_args} should be a @ref{614,,tuple} (possibly of
length 1) of types which parameterize @code{t_origin}:

@example
>>> from types import GenericAlias

>>> list[int] == GenericAlias(list, (int,))
True
>>> dict[str, int] == GenericAlias(dict, (str, int))
True
@end example


Added in version 3.9.



バージョン 3.9.2 で変更: This type can now be subclassed.



@subsubheading 参考



@table @asis

@item @ref{8c1,,Generic Alias Types}

In-depth documentation on instances of @code{types.GenericAlias}

@geindex Python Enhancement Proposals; PEP 585

@item PEP 585@footnote{https://peps.python.org/pep-0585/} - 標準コレクション型の型ヒントにおける総称型 (generics) の使用

Introducing the @code{types.GenericAlias} class
@end table

@end deffn

@geindex UnionType (types のクラス)
@anchor{library/types types UnionType}@anchor{2a7}
@deffn {クラス} types.UnionType

The type of @ref{9c5,,union type expressions}.


Added in version 3.10.



バージョン 3.14 で変更: This is now an alias for @ref{2a8,,typing.Union}.

@end deffn

@geindex TracebackType (types のクラス)
@anchor{library/types types TracebackType}@anchor{cea}
@deffn {クラス} types.TracebackType (tb_next, tb_frame, tb_lasti, tb_lineno)

@code{sys.exception().__traceback__} に含まれるようなトレースバックオブジェクトの型です。

See @ref{cec,,the language reference} for details of the
available attributes and operations, and guidance on creating tracebacks
dynamically.
@end deffn

@geindex FrameType (types モジュール)
@anchor{library/types types FrameType}@anchor{1bee}
@deffn {データ} types.FrameType

The type of @ref{8ef,,frame objects} such as found in
@ref{23a1,,tb.tb_frame} if @code{tb} is a traceback object.
@end deffn

@geindex GetSetDescriptorType (types モジュール)
@anchor{library/types types GetSetDescriptorType}@anchor{29eb}
@deffn {データ} types.GetSetDescriptorType

The type of objects defined in extension modules with @code{PyGetSetDef}, such
as @ref{4a5,,FrameType.f_locals} or @code{array.array.typecode}.
This type is used as
descriptor for object attributes; it has the same purpose as the
@ref{4b3,,property} type, but for classes defined in extension modules.
@end deffn

@geindex MemberDescriptorType (types モジュール)
@anchor{library/types types MemberDescriptorType}@anchor{29ec}
@deffn {データ} types.MemberDescriptorType

@code{datetime.timedelta.days} のような、拡張モジュールにおいて @code{PyMemberDef} によって定義されたオブジェクトの型です。この型は、標準の変換関数を利用するような、Cのシンプルなデータメンバで利用されます。 @ref{4b3,,property} 型と同じ目的を持った型ですが、こちらは拡張モジュールで定義された型のためのものです。

In addition, when a class is defined with a @ref{1704,,__slots__} attribute, then for
each slot, an instance of @code{MemberDescriptorType} will be added as an attribute
on the class. This allows the slot to appear in the class's @ref{e57,,__dict__}.

Pythonの他の実装では、この型は @code{GetSetDescriptorType} と同じかもしれません。
@end deffn

@geindex MappingProxyType (types のクラス)
@anchor{library/types types MappingProxyType}@anchor{698}
@deffn {クラス} types.MappingProxyType (mapping)

読み出し専用のマッピングのプロキシです。マッピングのエントリーに関する動的なビューを提供します。つまり、マッピングが変わった場合にビューがこれらの変更を反映するということです。


Added in version 3.3.



バージョン 3.9 で変更: Updated to support the new union (@code{|}) operator from 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/}, which
simply delegates to the underlying mapping.



@deffn {Describe} key in proxy

元になったマッピングが `key' というキーを持っている場合 @code{True} を返します。そうでなければ @code{False} を返します。
@end deffn


@deffn {Describe} proxy[key]

元になったマッピングの `key' というキーに対応するアイテムを返します。 `key' が存在しなければ、 @ref{5e7,,KeyError} が発生します。
@end deffn


@deffn {Describe} iter(proxy)

元になったマッピングのキーを列挙するイテレータを返します。これは @code{iter(proxy.keys())} のショートカットです。
@end deffn


@deffn {Describe} len(proxy)

元になったマッピングに含まれるアイテムの数を返します。
@end deffn

@geindex copy() (types.MappingProxyType のメソッド)
@anchor{library/types types MappingProxyType copy}@anchor{29ed}
@deffn {メソッド} copy ()

元になったマッピングの浅いコピーを返します。
@end deffn

@geindex get() (types.MappingProxyType のメソッド)
@anchor{library/types types MappingProxyType get}@anchor{29ee}
@deffn {メソッド} get (key[, default])

`key' が元になったマッピングに含まれている場合 `key' に対する値を返し、そうでなければ `default' を返します。もし `default' が与えられない場合は、デフォルト値の @code{None} になります。そのため、このメソッドが @ref{5e7,,KeyError} を発生させることはありません。
@end deffn

@geindex items() (types.MappingProxyType のメソッド)
@anchor{library/types types MappingProxyType items}@anchor{29ef}
@deffn {メソッド} items ()

元になったマッピングの items (@code{(key, value)} ペアの列) に対する新しいビューを返します。
@end deffn

@geindex keys() (types.MappingProxyType のメソッド)
@anchor{library/types types MappingProxyType keys}@anchor{29f0}
@deffn {メソッド} keys ()

元になったマッピングの keys に対する新しいビューを返します。
@end deffn

@geindex values() (types.MappingProxyType のメソッド)
@anchor{library/types types MappingProxyType values}@anchor{29f1}
@deffn {メソッド} values ()

元になったマッピングの values に対する新しいビューを返します。
@end deffn


@deffn {Describe} reversed(proxy)

Return a reverse iterator over the keys of the underlying mapping.


Added in version 3.9.

@end deffn


@deffn {Describe} hash(proxy)

Return a hash of the underlying mapping.


Added in version 3.12.

@end deffn
@end deffn

@geindex CapsuleType (types のクラス)
@anchor{library/types types CapsuleType}@anchor{29f2}
@deffn {クラス} types.CapsuleType

The type of @ref{29f3,,capsule objects}.


Added in version 3.13.

@end deffn

@node 追加のユーティリティクラスと関数,コルーチンユーティリティ関数,標準的なインタプリタ型,types --- 動的な型生成と組み込み型の名前
@anchor{library/types additional-utility-classes-and-functions}@anchor{29f4}
@subsubsection 追加のユーティリティクラスと関数


@geindex SimpleNamespace (types のクラス)
@anchor{library/types types SimpleNamespace}@anchor{4e5}
@deffn {クラス} types.SimpleNamespace

名前空間への属性アクセスに加えて意味のある repr を提供するための、単純な @ref{c7e,,object} サブクラスです。

Unlike @ref{c7e,,object}, with @code{SimpleNamespace} you can add and remove
attributes.

@ref{4e5,,SimpleNamespace} objects may be initialized
in the same way as @ref{183,,dict}: either with keyword arguments,
with a single positional argument, or with both.
When initialized with keyword arguments,
those are directly added to the underlying namespace.
Alternatively, when initialized with a positional argument,
the underlying namespace will be updated with key-value pairs
from that argument (either a mapping object or
an @ref{12f1,,iterable} object producing key-value pairs).
All such keys must be strings.

この型は以下のコードとほぼ等価です:

@example
class SimpleNamespace:
    def __init__(self, mapping_or_iterable=(), /, **kwargs):
        self.__dict__.update(mapping_or_iterable)
        self.__dict__.update(kwargs)

    def __repr__(self):
        items = (f"@{k@}=@{v!r@}" for k, v in self.__dict__.items())
        return "@{@}(@{@})".format(type(self).__name__, ", ".join(items))

    def __eq__(self, other):
        if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
           return self.__dict__ == other.__dict__
        return NotImplemented
@end example

@code{SimpleNamespace} は @code{class NS: pass} を置き換えるものとして有用かもしれません。ですが、構造化されたレコード型に対しては、これよりはむしろ @ref{4e0,,namedtuple()} を使用してください。

@code{SimpleNamespace} objects are supported by @ref{1c0,,copy.replace()}.


Added in version 3.3.



バージョン 3.9 で変更: Attribute order in the repr changed from alphabetical to insertion (like
@code{dict}).



バージョン 3.13 で変更: Added support for an optional positional argument.

@end deffn

@geindex DynamicClassAttribute() (types モジュール)
@anchor{library/types types DynamicClassAttribute}@anchor{83c}
@deffn {の関数} types.DynamicClassAttribute (fget=None, fset=None, fdel=None, doc=None)

クラスの属性アクセスを __getattr__ に振り替えます。

これは記述子で、インスタンス経由のアクセスとクラス経由のアクセスで振る舞いが異なる属性を定義するのに使います。インスタンスアクセスは通常通りですが、クラス経由の属性アクセスはクラスの __getattr__ メソッドに振り替えられます。これは AttributeError の送出により行われます。

これによって、インスタンス上で有効なプロパティを持ち、クラス上で同名の仮想属性を持つことができます (例については @ref{842,,enum.Enum} を参照してください)。


Added in version 3.4.

@end deffn

@node コルーチンユーティリティ関数,,追加のユーティリティクラスと関数,types --- 動的な型生成と組み込み型の名前
@anchor{library/types coroutine-utility-functions}@anchor{29f5}
@subsubsection コルーチンユーティリティ関数


@geindex coroutine() (types モジュール)
@anchor{library/types types coroutine}@anchor{1088}
@deffn {の関数} types.coroutine (gen_func)

この関数は、 @ref{126c,,generator} 関数を、ジェネレータベースのコルーチンを返す @ref{f73,,coroutine function} に変換します。返されるジェネレータベースのコルーチンは依然として @ref{dd9,,generator iterator} ですが、同時に @ref{6b9,,coroutine} オブジェクトかつ @ref{4c9,,awaitable} であるとみなされます。ただし、必ずしも @ref{f75,,__await__()} メソッドを実装する必要はありません。

`gen_func' はジェネレータ関数で、インプレースに変更されます。

`gen_func' がジェネレータ関数でない場合、この関数はラップされます。この関数が @ref{fdb,,collections.abc.Generator} のインスタンスを返す場合、このインスタンスは `awaitable' なプロキシオブジェクトにラップされます。それ以外のすべての型のオブジェクトは、そのまま返されます。


Added in version 3.5.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node copy --- 浅いコピーおよび深いコピー操作,pprint --- データの整形表示,types --- 動的な型生成と組み込み型の名前,データ型
@anchor{library/copy doc}@anchor{29f6}@anchor{library/copy copy-shallow-and-deep-copy-operations}@anchor{29f7}@anchor{library/copy module-copy}@anchor{29}@anchor{library/copy translation-repo}@anchor{29f8}
@subsection @code{copy} --- 浅いコピーおよび深いコピー操作


@geindex module; copy

`ソースコード:' Lib/copy.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/copy.py}


__________________________________________________________________


Python において代入文はオブジェクトをコピーしません。代入はターゲットとオブジェクトの間に束縛を作ります。ミュータブルなコレクションまたはミュータブルなアイテムを含むコレクションについては、元のオブジェクトを変更せずにコピーを変更できるように、コピーが必要になることが時々あります。このモジュールは、汎用的な浅い (shallow) コピーと深い (deep) コピーの操作 (以下で説明されます) を提供します。

以下にインターフェースをまとめます:

@geindex copy() (copy モジュール)
@anchor{library/copy copy copy}@anchor{757}
@deffn {の関数} copy.copy (obj)

`obj' の浅い (shallow) コピーを返します。
@end deffn

@geindex deepcopy() (copy モジュール)
@anchor{library/copy copy deepcopy}@anchor{d65}
@deffn {の関数} copy.deepcopy (obj[, memo])

`obj' の深い (deep) コピーを返します。
@end deffn

@geindex replace() (copy モジュール)
@anchor{library/copy copy replace}@anchor{1c0}
@deffn {の関数} copy.replace (obj, /, **changes)

Creates a new object of the same type as `obj', replacing fields with values
from `changes'.


Added in version 3.13.

@end deffn

@geindex Error
@anchor{library/copy copy Error}@anchor{29f9}
@deffn {例外} copy.Error

モジュール特有のエラーを送出します。
@end deffn
@anchor{library/copy shallow-vs-deep-copy}@anchor{1fe4}
浅い (shallow) コピーと深い (deep) コピーの違いが関係するのは、複合オブジェクト (リストやクラスインスタンスのような他のオブジェクトを含むオブジェクト) だけです:


@itemize *

@item 
`浅いコピー (shallow copy)' は新たな複合オブジェクトを作成し、その後 (可能な限り) 元のオブジェクト中に見つかったオブジェクトに対する `参照' を挿入します。

@item 
`深いコピー (deep copy)' は新たな複合オブジェクトを作成し、その後元のオブジェクト中に見つかったオブジェクトの `コピー' を挿入します。
@end itemize

深いコピー操作には、しばしば浅いコピー操作の時には存在しない 2 つの問題がついてまわります:


@itemize *

@item 
再帰的なオブジェクト (直接、間接に関わらず、自分自身に対する参照を持つ複合オブジェクト) は再帰ループを引き起こします。

@item 
深いコピーは何もかもコピーしてしまうため、例えば複数のコピー間で共有するつもりだったデータも余分にコピーしてしまいます。
@end itemize

@ref{d65,,deepcopy()} 関数では、これらの問題を以下のようにして回避しています:


@itemize *

@item 
現時点でのコピー過程ですでにコピーされたオブジェクトの @code{memo} 辞書を保持する。

@item 
ユーザ定義のクラスでコピー操作やコピーされる内容の集合を上書きできるようにする。
@end itemize

このモジュールでは、モジュール、メソッド、スタックトレース、スタックフレーム、ファイル、ソケット、ウィンドウ、その他これらに類似の型をコピーしません。このモジュールでは元のオブジェクトを変更せずに返すことで関数とクラスを (浅くまたは深く)「コピー」します。これは @ref{ab,,pickle} モジュールでの扱われかたと同じです。

辞書型の浅いコピーは @ref{dc9,,dict.copy()} で、リストの浅いコピーはリスト全体を指すスライス (例えば @code{copied_list = original_list[:]}) でできます。

@geindex module;pickle

Classes can use the same interfaces to control copying that they use to control
pickling.  See the description of module @ref{ab,,pickle} for information on these
methods.  In fact, the @code{copy} module uses the registered
pickle functions from the @ref{2a,,copyreg} module.

@geindex __copy__() (コピープロトコル)
@geindex __deepcopy__() (コピープロトコル)

In order for a class to define its own copy implementation, it can define
special methods @ref{17e0,,__copy__()} and @ref{17e1,,__deepcopy__()}.

@anchor{library/copy object __copy__}@anchor{17e0}
@deffn {メソッド} object.__copy__ (self)

Called to implement the shallow copy operation;
no additional arguments are passed.
@end deffn

@anchor{library/copy object __deepcopy__}@anchor{17e1}
@deffn {メソッド} object.__deepcopy__ (self, memo)

Called to implement the deep copy operation; it is passed one
argument, the `memo' dictionary.  If the @code{__deepcopy__} implementation needs
to make a deep copy of a component, it should call the @ref{d65,,deepcopy()} function
with the component as first argument and the `memo' dictionary as second argument.
The `memo' dictionary should be treated as an opaque object.
@end deffn

@geindex __replace__() (replace protocol)

Function @code{copy.replace()} is more limited
than @ref{757,,copy()} and @ref{d65,,deepcopy()},
and only supports named tuples created by @ref{4e0,,namedtuple()},
@ref{33,,dataclasses}, and other classes which define method @ref{47d,,__replace__()}.

@anchor{library/copy object __replace__}@anchor{47d}
@deffn {メソッド} object.__replace__ (self, /, **changes)

This method should create a new object of the same type,
replacing fields with values from `changes'.


Added in version 3.13.

@end deffn


@subsubheading 参考



@table @asis

@item @ref{ab,,pickle} モジュール

オブジェクト状態の取得と復元をサポートするために使われる特殊メソッドについて議論されています。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pprint --- データの整形表示,reprlib --- もう一つの repr の実装,copy --- 浅いコピーおよび深いコピー操作,データ型
@anchor{library/pprint doc}@anchor{29fa}@anchor{library/pprint module-pprint}@anchor{b3}@anchor{library/pprint pprint-data-pretty-printer}@anchor{29fb}@anchor{library/pprint translation-repo}@anchor{29fc}
@subsection @code{pprint} --- データの整形表示


@geindex module; pprint

`ソースコード:' Lib/pprint.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pprint.py}


__________________________________________________________________


The @code{pprint} module provides a capability to "pretty-print" arbitrary
Python data structures in a form which can be used as input to the interpreter.
If the formatted structures include objects which are not fundamental Python
types, the representation may not be loadable.  This may be the case if objects
such as files, sockets or classes are included, as well as many other
objects which are not representable as Python literals.

The formatted representation keeps objects on a single line if it can, and
breaks them onto multiple lines if they don't fit within the allowed width,
adjustable by the `width' parameter defaulting to 80 characters.


バージョン 3.9 で変更: @ref{4e5,,types.SimpleNamespace} の pretty-print サポートが追加されました。



バージョン 3.10 で変更: @ref{4e1,,dataclasses.dataclass} の pretty-print サポートが追加されました。


@menu
* 関数: 関数<4>. 
* PrettyPrinter オブジェクト:: 
* 使用例: 使用例<6>. 

@end menu

@node 関数<4>,PrettyPrinter オブジェクト,,pprint --- データの整形表示
@anchor{library/pprint functions}@anchor{29fd}@anchor{library/pprint pprint-functions}@anchor{29fe}
@subsubsection 関数


@geindex pp() (pprint モジュール)
@anchor{library/pprint pprint pp}@anchor{c18}
@deffn {の関数} pprint.pp (object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=False, underscore_numbers=False)

`object' のフォーマットされた表現を出力して、その後に newline を続けます。この関数は、対話型インタプリタの中で値を調査するために @ref{1177,,print()} 関数の代わりに使用されることがあります。Tips： さらに、スコープ内で使用するために @code{print = pprint.pp} を再代入することができます)。

@*パラメータ: 

@itemize *

@item 
@code{object} -- The object to be printed.

@item 
@code{stream} (@ref{17ac,,file-like object} | None) -- A file-like object to which the output will be written
by calling its @code{write()} method.
If @code{None} (the default), @ref{ccd,,sys.stdout} is used.

@item 
@code{indent} (@ref{19b,,int}) -- 入れ子レベルごとに追加されるインデントの量を指定します。

@item 
@code{width} (@ref{19b,,int}) -- 出力の1行あたり最大文字数を指定します。構造が幅の制約の中で整形できない場合、最善の努力がなされます。

@item 
@code{depth} (@ref{19b,,int}@code{ | }@code{None}) -- 表示される入れ子レベルの数を制御します。表示されるデータ構造が深すぎる場合、含まれる次のレベルは`@w{`}...`@w{`}で置き換えられます。@code{None} （デフォルト）の場合、フォーマットされるオブジェクトの深さに制約はありません。

@item 
@code{compact} (@ref{3c3,,bool}) -- Control the way long @ref{716,,sequences} are formatted.
If @code{False} (the default),
each item of a sequence will be formatted on a separate line,
otherwise as many items as will fit within the `width'
will be formatted on each output line.

@item 
@code{sort_dicts} (@ref{3c3,,bool}) -- Trueの場合、辞書は辞書のキー順にソートされて整形されます。そうでなければ挿入順に表示されます（デフォルト）。

@item 
@code{underscore_numbers} (@ref{3c3,,bool}) -- Trueの場合、整数は`@w{`}_`@w{`}で3桁区切りされて表示されます。そうでなければアンダースコアは表示されません（デフォルト）。
@end itemize


@example
>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff)
>>> pprint.pp(stuff)
[<Recursion on list with id=...>,
 'spam',
 'eggs',
 'lumberjack',
 'knights',
 'ni']
@end example


Added in version 3.8.

@end deffn

@geindex pprint() (pprint モジュール)
@anchor{library/pprint pprint pprint}@anchor{a29}
@deffn {の関数} pprint.pprint (object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)

Alias for @ref{c18,,pp()} with `sort_dicts' set to @code{True} by default,
which would automatically sort the dictionaries' keys,
you might want to use @ref{c18,,pp()} instead where it is @code{False} by default.
@end deffn

@geindex pformat() (pprint モジュール)
@anchor{library/pprint pprint pformat}@anchor{1182}
@deffn {の関数} pprint.pformat (object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)

Return the formatted representation of `object' as a string.  `indent',
`width', `depth', `compact', `sort_dicts' and `underscore_numbers' are
passed to the @ref{1181,,PrettyPrinter} constructor as formatting parameters
and their meanings are as described in the documentation above.
@end deffn

@geindex isreadable() (pprint モジュール)
@anchor{library/pprint pprint isreadable}@anchor{29ff}
@deffn {の関数} pprint.isreadable (object)

@geindex 組み込み関数;eval

`object' を書式化して出力できる("readable") か、あるいは @ref{4a3,,eval()} を使って値を再構成できるかを返します。再帰的なオブジェクトに対しては常に @code{False} を返します。

@example
>>> pprint.isreadable(stuff)
False
@end example
@end deffn

@geindex isrecursive() (pprint モジュール)
@anchor{library/pprint pprint isrecursive}@anchor{2a00}
@deffn {の関数} pprint.isrecursive (object)

Determine if `object' requires a recursive representation.  This function is
subject to the same limitations as noted in @ref{2a01,,saferepr()} below and may raise an
@ref{f68,,RecursionError} if it fails to detect a recursive object.
@end deffn

@geindex saferepr() (pprint モジュール)
@anchor{library/pprint pprint saferepr}@anchor{2a01}
@deffn {の関数} pprint.saferepr (object)

Return a string representation of `object', protected against recursion in
some common data structures, namely instances of @ref{183,,dict}, @ref{24d,,list}
and @ref{614,,tuple} or subclasses whose @code{__repr__} has not been overridden.  If the
representation of object exposes a recursive entry, the recursive reference
will be represented as @code{<Recursion on typename with id=number>}.  The
representation is not otherwise formatted.

@example
>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
@end example
@end deffn

@node PrettyPrinter オブジェクト,使用例<6>,関数<4>,pprint --- データの整形表示
@anchor{library/pprint id1}@anchor{2a02}@anchor{library/pprint prettyprinter-objects}@anchor{2a03}
@subsubsection PrettyPrinter オブジェクト


@geindex ...;placeholder

@geindex PrettyPrinter (pprint のクラス)
@anchor{library/pprint pprint PrettyPrinter}@anchor{1181}
@deffn {クラス} pprint.PrettyPrinter (indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True, underscore_numbers=False)

Construct a @ref{1181,,PrettyPrinter} instance.

Arguments have the same meaning as for @ref{c18,,pp()}.
Note that they are in a different order, and that `sort_dicts' defaults to @code{True}.

@example
>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberjack', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
@end example


バージョン 3.4 で変更: `compact' 引数が追加されました。



バージョン 3.8 で変更: `sort_dicts' 引数が追加されました。



バージョン 3.10 で変更: `underscore_numbers' 引数が追加されました。



バージョン 3.11 で変更: No longer attempts to write to @code{sys.stdout} if it is @code{None}.

@end deffn

@ref{1181,,PrettyPrinter} インスタンスには以下のメソッドがあります:

@geindex pformat() (pprint.PrettyPrinter のメソッド)
@anchor{library/pprint pprint PrettyPrinter pformat}@anchor{2a04}
@deffn {メソッド} PrettyPrinter.pformat (object)

`object' の書式化した表現を返します。これは @ref{1181,,PrettyPrinter} のコンストラクタに渡されたオプションを考慮して書式化されます。
@end deffn

@geindex pprint() (pprint.PrettyPrinter のメソッド)
@anchor{library/pprint pprint PrettyPrinter pprint}@anchor{2a05}
@deffn {メソッド} PrettyPrinter.pprint (object)

`object' の書式化した表現を指定したストリームに出力し、最後に改行します。
@end deffn

以下のメソッドは、対応する同じ名前の関数と同じ機能を持っています。以下のメソッドをインスタンスに対して使うと、新たに @ref{1181,,PrettyPrinter} オブジェクトを作る必要がないのでちょっぴり効果的です。

@geindex isreadable() (pprint.PrettyPrinter のメソッド)
@anchor{library/pprint pprint PrettyPrinter isreadable}@anchor{2a06}
@deffn {メソッド} PrettyPrinter.isreadable (object)

@geindex 組み込み関数;eval

`object' を書式化して出力できる（"readable"）か、あるいは @ref{4a3,,eval()} を使って値を再構成できるかを返します。これは再帰的なオブジェクトに対して @code{False} を返すことに注意して下さい。もし @ref{1181,,PrettyPrinter} の `depth' 引数が設定されていて、オブジェクトのレベルが設定よりも深かったら、 @code{False} を返します。
@end deffn

@geindex isrecursive() (pprint.PrettyPrinter のメソッド)
@anchor{library/pprint pprint PrettyPrinter isrecursive}@anchor{2a07}
@deffn {メソッド} PrettyPrinter.isrecursive (object)

オブジェクトが再帰的な表現かどうかを返します。
@end deffn

このメソッドをフックとして、サブクラスがオブジェクトを文字列に変換する方法を修正するのが可能になっています。デフォルトの実装では、内部で @ref{2a01,,saferepr()} を呼び出しています。

@geindex format() (pprint.PrettyPrinter のメソッド)
@anchor{library/pprint pprint PrettyPrinter format}@anchor{1ce7}
@deffn {メソッド} PrettyPrinter.format (object, context, maxlevels, level)

次の3つの値を返します。`object' をフォーマット化して文字列にしたもの、その結果が読み込み可能かどうかを示すフラグ、再帰が含まれているかどうかを示すフラグ。最初の引数は表示するオブジェクトです。 2つめの引数はオブジェクトの @ref{163c,,id()} をキーとして含むディクショナリで、オブジェクトを含んでいる現在の（直接、間接に `object' のコンテナとして表示に影響を与える）環境です。ディクショナリ `context' の中でどのオブジェクトが表示されたか表示する必要があるなら、3つめの返り値は @code{True} になります。 @ref{1ce7,,format()} メソッドの再帰呼び出しではこのディクショナリのコンテナに対してさらにエントリを加えます。 3つめの引数 `maxlevels' で再帰呼び出しのレベルを制限します。制限しない場合、 @code{0} になります。この引数は再帰呼び出しでそのまま渡されます。 4つめの引数 `level' で現在のレベルを設定します。再帰呼び出しでは、現在の呼び出しより小さい値が渡されます。
@end deffn

@node 使用例<6>,,PrettyPrinter オブジェクト,pprint --- データの整形表示
@anchor{library/pprint example}@anchor{2a08}@anchor{library/pprint pprint-example}@anchor{2a09}
@subsubsection 使用例


@ref{c18,,pp()} 関数のいくつかの用途とそのパラメータを実証するために、PyPI@footnote{https://pypi.org} からプロジェクトに関する情報を取って来ましょう:

@example
>>> import json
>>> import pprint
>>> from urllib.request import urlopen
>>> with urlopen('https://pypi.org/pypi/sampleproject/1.2.0/json') as resp:
...     project_info = json.load(resp)['info']
@end example

その基本形式では、 @ref{c18,,pp()} はオブジェクト全体を表示します:

@example
>>> pprint.pp(project_info)
@{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': ['Development Status :: 3 - Alpha',
                 'Intended Audience :: Developers',
                 'License :: OSI Approved :: MIT License',
                 'Programming Language :: Python :: 2',
                 'Programming Language :: Python :: 2.6',
                 'Programming Language :: Python :: 2.7',
                 'Programming Language :: Python :: 3',
                 'Programming Language :: Python :: 3.2',
                 'Programming Language :: Python :: 3.3',
                 'Programming Language :: Python :: 3.4',
                 'Topic :: Software Development :: Build Tools'],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': @{'last_day': -1, 'last_month': -1, 'last_week': -1@},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': @{'Download': 'UNKNOWN',
                  'Homepage': 'https://github.com/pypa/sampleproject'@},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'@}
@end example

結果をある深さ `depth' に制限することができます (より深い内容には省略記号が使用されます):

@example
>>> pprint.pp(project_info, depth=1)
@{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': @{...@},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': @{...@},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'@}
@end example

それに加えて、最大の文字幅 `width' を指示することもできます。長いオブジェクトを分離することができなければ、指定された幅を超過します:

@example
>>> pprint.pp(project_info, depth=1, width=60)
@{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the '
                'project.\n'
                '\n'
                'The file should use UTF-8 encoding and be '
                'written using ReStructured Text. It\n'
                'will be used to generate the project '
                'webpage on PyPI, and should be written '
                'for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would '
                'include an overview of the project, '
                'basic\n'
                'usage examples, etc. Generally, including '
                'the project changelog in here is not\n'
                'a good idea, although a simple "What\'s '
                'New" section for the most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': @{...@},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': @{...@},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'@}
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node reprlib --- もう一つの repr の実装,enum --- 列挙型のサポート,pprint --- データの整形表示,データ型
@anchor{library/reprlib doc}@anchor{2a0a}@anchor{library/reprlib module-reprlib}@anchor{c0}@anchor{library/reprlib reprlib-alternate-repr-implementation}@anchor{2a0b}@anchor{library/reprlib translation-repo}@anchor{2a0c}
@subsection @code{reprlib} --- もう一つの @code{repr()} の実装


@geindex module; reprlib

`ソースコード:' Lib/reprlib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/reprlib.py}


__________________________________________________________________


@code{reprlib} モジュールは、結果の文字列のサイズに対する制限付きでオブジェクト表現を生成するための手段を提供します。これは Python デバッガの中で使用されており、他の文脈でも同様に役に立つかもしれません。

このモジュールはクラスとインスタンス、それに関数を提供します:

@geindex Repr (reprlib のクラス)
@anchor{library/reprlib reprlib Repr}@anchor{2a0d}
@deffn {クラス} reprlib.Repr (*, maxlevel=6, maxtuple=6, maxlist=6, maxarray=5, maxdict=4, maxset=6, maxfrozenset=6, maxdeque=6, maxstring=30, maxlong=40, maxother=30, fillvalue='...', indent=None)

組み込み関数 @ref{1c1,,repr()} に似た関数を実装するために役に立つフォーマット用サービスを提供します。
過度に長い表現を作り出さないようにするための大きさの制限をオブジェクト型ごとに設定できます。

The keyword arguments of the constructor can be used as a shortcut to set the
attributes of the @ref{2a0d,,Repr} instance. Which means that the following
initialization:

@example
aRepr = reprlib.Repr(maxlevel=3)
@end example

は、次のコードと等しいです:

@example
aRepr = reprlib.Repr()
aRepr.maxlevel = 3
@end example

See section @ref{2a0e,,Repr Objects} for more information about @ref{2a0d,,Repr}
attributes.


バージョン 3.12 で変更: Allow attributes to be set via keyword arguments.

@end deffn

@geindex aRepr (reprlib モジュール)
@anchor{library/reprlib reprlib aRepr}@anchor{2a0f}
@deffn {データ} reprlib.aRepr

これは下で説明される @ref{2a10,,repr()} 関数を提供するために使われる @ref{2a0d,,Repr} のインスタンスです。このオブジェクトの属性を変更すると、 @ref{2a10,,repr()} と Python デバッガが使うサイズ制限に影響します。
@end deffn

@geindex repr() (reprlib モジュール)
@anchor{library/reprlib reprlib repr}@anchor{2a10}
@deffn {の関数} reprlib.repr (obj)

これは @code{aRepr} の @ref{2a11,,repr()} メソッドです。同じ名前の組み込み関数が返す文字列と似ていますが、最大サイズに制限のある文字列を返します。
@end deffn

In addition to size-limiting tools, the module also provides a decorator for
detecting recursive calls to @ref{82f,,__repr__()} and substituting a
placeholder string instead.

@geindex ...;placeholder

@geindex recursive_repr() (reprlib モジュール)
@anchor{library/reprlib reprlib recursive_repr}@anchor{140c}
@deffn {の関数} @@reprlib.recursive_repr (fillvalue='...')

Decorator for @ref{82f,,__repr__()} methods to detect recursive calls within the
same thread.  If a recursive call is made, the `fillvalue' is returned,
otherwise, the usual @code{__repr__()} call is made.  For example:

@example
>>> from reprlib import recursive_repr
>>> class MyList(list):
...     @@recursive_repr()
...     def __repr__(self):
...         return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
@end example


Added in version 3.2.

@end deffn

@menu
* Reprオブジェクト:: 
* Reprオブジェクトをサブクラス化する:: 

@end menu

@node Reprオブジェクト,Reprオブジェクトをサブクラス化する,,reprlib --- もう一つの repr の実装
@anchor{library/reprlib id1}@anchor{2a0e}@anchor{library/reprlib repr-objects}@anchor{2a12}
@subsubsection Reprオブジェクト


@ref{2a0d,,Repr} インスタンスはオブジェクト型毎に表現する文字列のサイズを制限するために使えるいくつかの属性と、特定のオブジェクト型をフォーマットするメソッドを提供します。

@geindex fillvalue (reprlib.Repr の属性)
@anchor{library/reprlib reprlib Repr fillvalue}@anchor{2a13}
@deffn {の属性} Repr.fillvalue

This string is displayed for recursive references. It defaults to
@code{...}.


Added in version 3.11.

@end deffn

@geindex maxlevel (reprlib.Repr の属性)
@anchor{library/reprlib reprlib Repr maxlevel}@anchor{2a14}
@deffn {の属性} Repr.maxlevel

再帰的な表現を作る場合の深さ制限。デフォルトは @code{6} です。
@end deffn

@geindex maxdict (reprlib.Repr の属性)
@geindex maxlist (reprlib.Repr の属性)
@geindex maxtuple (reprlib.Repr の属性)
@geindex maxset (reprlib.Repr の属性)
@geindex maxfrozenset (reprlib.Repr の属性)
@geindex maxdeque (reprlib.Repr の属性)
@geindex maxarray (reprlib.Repr の属性)
@anchor{library/reprlib reprlib Repr maxdict}@anchor{2a15}
@deffn {の属性} Repr.maxdict
@anchor{library/reprlib reprlib Repr maxlist}@anchor{2a16}
@deffnx {の属性} Repr.maxlist
@anchor{library/reprlib reprlib Repr maxtuple}@anchor{2a17}
@deffnx {の属性} Repr.maxtuple
@anchor{library/reprlib reprlib Repr maxset}@anchor{2a18}
@deffnx {の属性} Repr.maxset
@anchor{library/reprlib reprlib Repr maxfrozenset}@anchor{2a19}
@deffnx {の属性} Repr.maxfrozenset
@anchor{library/reprlib reprlib Repr maxdeque}@anchor{2a1a}
@deffnx {の属性} Repr.maxdeque
@anchor{library/reprlib reprlib Repr maxarray}@anchor{2a1b}
@deffnx {の属性} Repr.maxarray

指定されたオブジェクト型に対するエントリ表現の数についての制限。 @ref{2a15,,maxdict} に対するデフォルトは @code{4} で、 @ref{2a1b,,maxarray} は @code{5} 、その他に対しては @code{6} です。
@end deffn

@geindex maxlong (reprlib.Repr の属性)
@anchor{library/reprlib reprlib Repr maxlong}@anchor{2a1c}
@deffn {の属性} Repr.maxlong

整数の表現のおける文字数の最大値。中央の数字が抜け落ちます。デフォルトは @code{40} です。
@end deffn

@geindex maxstring (reprlib.Repr の属性)
@anchor{library/reprlib reprlib Repr maxstring}@anchor{2a1d}
@deffn {の属性} Repr.maxstring

文字列の表現における文字数の制限。文字列の"通常の"表現は文字の「元」として使われることに注意してください。表現にエスケープシーケンスが必要とされる場合、表現が短縮されるときにこれらのエスケープシーケンスの形式は崩れます。デフォルトは @code{30} です。
@end deffn

@geindex maxother (reprlib.Repr の属性)
@anchor{library/reprlib reprlib Repr maxother}@anchor{2a1e}
@deffn {の属性} Repr.maxother

この制限は @ref{2a0d,,Repr} オブジェクトに利用できる特定のフォーマットメソッドがないオブジェクト型のサイズをコントロールするために使われます。 @ref{2a1d,,maxstring} と同じようなやり方で適用されます。デフォルトは @code{20} です。
@end deffn

@geindex indent (reprlib.Repr の属性)
@anchor{library/reprlib reprlib Repr indent}@anchor{2a1f}
@deffn {の属性} Repr.indent

If this attribute is set to @code{None} (the default), the output is formatted
with no line breaks or indentation, like the standard @ref{1c1,,repr()}.
For example:

@example
>>> example = [
...     1, 'spam', @{'a': 2, 'b': 'spam eggs', 'c': @{3: 4.5, 6: []@}@}, 'ham']
>>> import reprlib
>>> aRepr = reprlib.Repr()
>>> print(aRepr.repr(example))
[1, 'spam', @{'a': 2, 'b': 'spam eggs', 'c': @{3: 4.5, 6: []@}@}, 'ham']
@end example

If @ref{2a1f,,indent} is set to a string, each recursion level
is placed on its own line, indented by that string:

@example
>>> aRepr.indent = '-->'
>>> print(aRepr.repr(example))
[
-->1,
-->'spam',
-->@{
-->-->'a': 2,
-->-->'b': 'spam eggs',
-->-->'c': @{
-->-->-->3: 4.5,
-->-->-->6: [],
-->-->@},
-->@},
-->'ham',
]
@end example

Setting @ref{2a1f,,indent} to a positive integer value behaves as if it
was set to a string with that number of spaces:

@example
>>> aRepr.indent = 4
>>> print(aRepr.repr(example))
[
    1,
    'spam',
    @{
        'a': 2,
        'b': 'spam eggs',
        'c': @{
            3: 4.5,
            6: [],
        @},
    @},
    'ham',
]
@end example


Added in version 3.12.

@end deffn

@geindex repr() (reprlib.Repr のメソッド)
@anchor{library/reprlib reprlib Repr repr}@anchor{2a11}
@deffn {メソッド} Repr.repr (obj)

このインスタンスで設定されたフォーマットを使う、組み込み @ref{1c1,,repr()} と等価なもの。
@end deffn

@geindex repr1() (reprlib.Repr のメソッド)
@anchor{library/reprlib reprlib Repr repr1}@anchor{2a20}
@deffn {メソッド} Repr.repr1 (obj, level)

@ref{2a11,,repr()} が使う再帰的な実装。
`obj' の型を使ってどのフォーマットメソッドを呼び出すかを決定し、それに `obj' と `level' を渡します。
再帰呼び出しにおいて `level' の値に対して @code{level - 1} を与える再帰的なフォーマットを実行するために、型に固有のメソッドは @ref{2a20,,repr1()} を呼び出します。
@end deffn


@deffn {メソッド} Repr.repr_TYPE (obj, level)

型名に基づく名前をもつメソッドとして、特定の型に対するフォーマットメソッドは実装されます。メソッド名では、 `TYPE' は @code{'_'.join(type(obj).__name__.split())} に置き換えられます。これらのメソッドへのディスパッチは @ref{2a20,,repr1()} によって処理されます。再帰的に値をフォーマットする必要がある型固有のメソッドは、 @code{self.repr1(subobj, level - 1)} を呼び出します。
@end deffn

@node Reprオブジェクトをサブクラス化する,,Reprオブジェクト,reprlib --- もう一つの repr の実装
@anchor{library/reprlib subclassing-repr-objects}@anchor{2a21}@anchor{library/reprlib subclassing-reprs}@anchor{2a22}
@subsubsection Reprオブジェクトをサブクラス化する


The use of dynamic dispatching by @ref{2a20,,Repr.repr1()} allows subclasses of
@ref{2a0d,,Repr} to add support for additional built-in object types or to modify
the handling of types already supported. This example shows how special support
for file objects could be added:

@example
import reprlib
import sys

class MyRepr(reprlib.Repr):

    def repr_TextIOWrapper(self, obj, level):
        if obj.name in @{'<stdin>', '<stdout>', '<stderr>'@}:
            return obj.name
        return repr(obj)

aRepr = MyRepr()
print(aRepr.repr(sys.stdin))         # prints '<stdin>'
@end example

@example
<stdin>
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node enum --- 列挙型のサポート,graphlib --- グラフ構造を操作する機能,reprlib --- もう一つの repr の実装,データ型
@anchor{library/enum doc}@anchor{2a23}@anchor{library/enum enum-support-for-enumerations}@anchor{2a24}@anchor{library/enum module-enum}@anchor{5a}@anchor{library/enum translation-repo}@anchor{2a25}
@subsection @code{enum} --- 列挙型のサポート


@geindex module; enum


Added in version 3.4.


`ソースコード:' Lib/enum.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/enum.py}

@subsubheading Important



このページには、リファレンス情報だけが含まれています。チュートリアルは、以下のページを参照してください


@itemize *

@item 
@ref{2a26,,基本チュートリアル}

@item 
@ref{2a27,,上級チュートリアル}

@item 
@ref{2a28,,Enum クックブック}
@end itemize


__________________________________________________________________


列挙型とは:


@itemize *

@item 
一意の値に紐付けられたシンボリックな名前の集合です

@item 
反復可能であり、定義順にその正規の（エイリアスでない）メンバーを返します

@item 
値を渡してメンバーを返すために、 `呼び出し' 構文を使用します

@item 
名前を受け取ってメンバーを返すために、 `インデックス' 構文を使用します
@end itemize

列挙型は、@ref{14ef,,class} 構文を使用するか、関数呼び出し構文を使用して作成されます:

@example
>>> from enum import Enum

>>> # class syntax
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3

>>> # functional syntax
>>> Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)])
@end example

Enum の作成に @ref{14ef,,class} 文を使用できるものの、Enum は通常の Python クラスではありません。詳細は @ref{2a29,,Enum はどう違うのか?} を参照してください。

@cartouche
@quotation 注釈 
用語


@itemize -

@item 
クラス @code{Color} は `列挙型' (または `Enum') です

@item 
属性 @code{Color.RED}, @code{Color.GREEN} などは `列挙型のメンバー' (または `メンバー') で、機能的には定数です。

@item 
列挙型のメンバーは `名前' と `値' を持ちます (@code{Color.RED} の名前は @code{RED} 、 @code{Color.BLUE} の値は @code{3} など。)
@end itemize
@end quotation
@end cartouche


__________________________________________________________________


@menu
* モジュールコンテンツ: モジュールコンテンツ<2>. 
* データ型: データ型<2>. 
* ユーティリティとデコレータ:: 
* 注釈:: 

@end menu

@node モジュールコンテンツ<2>,データ型<2>,,enum --- 列挙型のサポート
@anchor{library/enum module-contents}@anchor{2a2a}
@subsubsection モジュールコンテンツ


@quotation

@ref{4f7,,EnumType}

@quotation

Enumおよびそのサブクラスのための @code{type} です。
@end quotation

@ref{842,,Enum}

@quotation

列挙型定数を作成する基底クラスです。
@end quotation

@ref{edb,,IntEnum}

@quotation

@ref{19b,,int} のサブクラスでもある列挙型定数を作成する基底クラスです。(@ref{2a2b,,Notes})
@end quotation

@ref{82d,,StrEnum}

@quotation

@ref{169,,str} のサブクラスでもある列挙型定数を作成する基底クラスです。(@ref{2a2b,,Notes})
@end quotation

@ref{835,,Flag}

@quotation

列挙型定数を作成する基底クラスで、ビット演算を使って組み合わせられ、その結果も @ref{e9a,,IntFlag} メンバーになります。
@end quotation

@ref{e9a,,IntFlag}

@quotation

列挙型定数を作成する基底クラスで、ビット演算子を使って組み合わせられ、その結果も @ref{e9a,,IntFlag} メンバーになります。
@ref{e9a,,IntFlag} は @ref{19b,,int} のサブクラスでもあります。(@ref{2a2b,,Notes})
@end quotation

@ref{82e,,ReprEnum}

@quotation

@ref{edb,,IntEnum}、@ref{82d,,StrEnum}、および @ref{e9a,,IntFlag} によって使用され、mix-inされた型の @ref{169,,str()} を保持します。
@end quotation

@ref{838,,EnumCheck}

@quotation

@code{CONTINUOUS}、@code{NAMED_FLAGS}、@code{UNIQUE} の値を持つ列挙型です。 @ref{837,,verify()} と共に使用して、指定された列挙型がさまざまな制約を満たしていることを確認します。
@end quotation

@ref{836,,FlagBoundary}

@quotation

An enumeration with the values @code{STRICT}, @code{CONFORM}, @code{EJECT}, and
@code{KEEP} which allows for more fine-grained control over how invalid values
are dealt with in an enumeration.
@end quotation

@ref{4f6,,EnumDict}

@quotation

A subclass of @ref{183,,dict} for use when subclassing @ref{4f7,,EnumType}.
@end quotation

@ref{e9b,,auto}

@quotation

インスタンスは列挙型のメンバーに適切な値で置き換えられます。@ref{82d,,StrEnum} ではデフォルトの値がメンバー名を小文字にしたものですが、その他の列挙型のデフォルトは1から連番で増加する値となります。
@end quotation

@ref{83b,,property()}

@quotation

メンバー名との競合を避けながら @ref{842,,Enum} メンバーに属性を持たせます。@code{value} 属性と @code{name} 属性はこの方法で実装されます。
@end quotation

@ref{2a2c,,unique()}

@quotation

一つの名前だけがひとつの値に束縛されていることを保証する Enum クラスのデコレーターです。
@end quotation

@ref{837,,verify()}

@quotation

Enum class decorator that checks user-selectable constraints on an
enumeration.
@end quotation

@ref{839,,member()}

@quotation

@code{obj} をメンバーにします。デコレータとして使用できます。
@end quotation

@ref{83a,,nonmember()}

@quotation

@code{obj} をメンバーにしません。デコレータとして使用できます。
@end quotation

@ref{83d,,global_enum()}

@quotation

Modify the @ref{169,,str()} and @ref{1c1,,repr()} of an enum
to show its members as belonging to the module instead of its class,
and export the enum members to the global namespace.
@end quotation

@ref{2a2d,,show_flag_values()}

@quotation

フラグに含まれる、全ての2の累乗の整数のリストを返します。
@end quotation

@ref{178d,,enum.bin()}

@quotation

Like built-in @ref{14c0,,bin()}, except negative values are represented in
two's complement, and the leading bit always indicates sign
(@code{0} implies positive, @code{1} implies negative).
@end quotation
@end quotation


Added in version 3.6: @code{Flag}, @code{IntFlag}, @code{auto}



Added in version 3.11: @code{StrEnum}, @code{EnumCheck}, @code{ReprEnum}, @code{FlagBoundary}, @code{property}, @code{member}, @code{nonmember}, @code{global_enum}, @code{show_flag_values}



Added in version 3.13: @code{EnumDict}



__________________________________________________________________


@node データ型<2>,ユーティリティとデコレータ,モジュールコンテンツ<2>,enum --- 列挙型のサポート
@anchor{library/enum data-types}@anchor{2a2e}
@subsubsection データ型


@geindex EnumType (enum のクラス)
@anchor{library/enum enum EnumType}@anchor{4f7}
@deffn {クラス} enum.EnumType

`EnumType' は `enum' 列挙型の @ref{23d0,,メタクラス} です。 `EnumType' のサブクラスを作成することが可能です -- 詳細は @ref{2a2f,,EnumTypeのサブクラスを作る} を参照してください。

@code{EnumType} is responsible for setting the correct @code{__repr__()},
@code{__str__()}, @code{__format__()}, and @code{__reduce__()} methods on the
final `enum', as well as creating the enum members, properly handling
duplicates, providing iteration over the enum class, etc.


Added in version 3.11: Before 3.11 @code{EnumType} was called @code{EnumMeta}, which is still available as an alias.


@geindex __call__() (enum.EnumType のメソッド)
@anchor{library/enum enum EnumType __call__}@anchor{2a30}
@deffn {メソッド} __call__ (cls, value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

このメソッドは2つの異なる方法で呼び出されます。


@itemize *

@item 
既存のメンバーを検索する:

@quotation

@*cls: 
呼び出されるenumクラス。


@*value: 
検索する値。

@end quotation

@item 
@code{cls} を使って新しい列挙型を作成する（既存の列挙型がメンバーを持たない場合のみ）:

@quotation

@*cls: 
呼び出されるenumクラス。


@*value: 
新しく作成するEnumの名前。


@*names: 
新しく作成するEnumのメンバーの名前/値のリスト。


@*module: 
新しく作成するEnumの属するモジュール名。


@*qualname: 
The actual location in the module where this Enum can be found.


@*type: 
新しく作成するEnumのmix-in型。


@*start: 
Enumの最初の整数値（@ref{e9b,,auto} で使用されます）。


@*boundary: 
bit演算での範囲外の値の扱い方（@ref{835,,Flag} のみ）。

@end quotation
@end itemize
@end deffn

@geindex __contains__() (enum.EnumType のメソッド)
@anchor{library/enum enum EnumType __contains__}@anchor{2a31}
@deffn {メソッド} __contains__ (cls, member)

メンバーが @code{cls} に属している場合は @code{True} を返します:

@example
>>> some_var = Color.RED
>>> some_var in Color
True
>>> Color.RED.value in Color
True
@end example


バージョン 3.12 で変更: Python 3.12 以前では、非Enumメンバーの包含判定が行われた場合、@code{TypeError} が送出されます。

@end deffn

@geindex __dir__() (enum.EnumType のメソッド)
@anchor{library/enum enum EnumType __dir__}@anchor{2a32}
@deffn {メソッド} __dir__ (cls)

@code{['__class__', '__doc__', '__members__', '__module__']} と、 `cls' に属するメンバー名を返します:

@example
>>> dir(Color)
['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', '__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', '__module__', '__name__', '__qualname__']
@end example
@end deffn

@geindex __getitem__() (enum.EnumType のメソッド)
@anchor{library/enum enum EnumType __getitem__}@anchor{2a33}
@deffn {メソッド} __getitem__ (cls, name)

`cls' 内の一致するメンバーを返すか、@ref{5e7,,KeyError} を送出します:

@example
>>> Color['BLUE']
<Color.BLUE: 3>
@end example
@end deffn

@geindex __iter__() (enum.EnumType のメソッド)
@anchor{library/enum enum EnumType __iter__}@anchor{2a34}
@deffn {メソッド} __iter__ (cls)

Returns each member in `cls' in definition order:

@example
>>> list(Color)
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
@end example
@end deffn

@geindex __len__() (enum.EnumType のメソッド)
@anchor{library/enum enum EnumType __len__}@anchor{2a35}
@deffn {メソッド} __len__ (cls)

`cls' 内のメンバーの数を返します。:

@example
>>> len(Color)
3
@end example
@end deffn

@geindex __members__ (enum.EnumType の属性)
@anchor{library/enum enum EnumType __members__}@anchor{2a36}
@deffn {の属性} __members__

Returns a mapping of every enum name to its member, including aliases
@end deffn

@geindex __reversed__() (enum.EnumType のメソッド)
@anchor{library/enum enum EnumType __reversed__}@anchor{2a37}
@deffn {メソッド} __reversed__ (cls)

`cls' 内の各メンバー を定義順の逆順で返します:

@example
>>> list(reversed(Color))
[<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>]
@end example
@end deffn
@end deffn

@geindex Enum (enum のクラス)
@anchor{library/enum enum Enum}@anchor{842}
@deffn {クラス} enum.Enum

`Enum' は全ての `enum' 列挙型の基底クラスです。

@geindex name (enum.Enum の属性)
@anchor{library/enum enum Enum name}@anchor{2a38}
@deffn {の属性} name

@code{Enum} メンバーを定義するために使用される名前:

@example
>>> Color.BLUE.name
'BLUE'
@end example
@end deffn

@geindex value (enum.Enum の属性)
@anchor{library/enum enum Enum value}@anchor{2a39}
@deffn {の属性} value

@code{Enum} メンバーに与えられた値:

@example
>>> Color.RED.value
1
@end example

Value of the member, can be set in @ref{2a3a,,__new__()}.

@cartouche
@quotation 注釈 
列挙型のメンバー値

メンバー値は何であっても構いません: @ref{19b,,int}, @ref{169,,str} などなど。
正確な値が重要でない場合は、 @ref{e9b,,auto} インスタンスを使っておくと、適切な値が選ばれます。
詳細は @ref{e9b,,auto} を参照してください。

While mutable/unhashable values, such as @ref{183,,dict}, @ref{24d,,list} or
a mutable @ref{4e1,,dataclass}, can be used, they will have a
quadratic performance impact during creation relative to the
total number of mutable/unhashable values in the enum.
@end quotation
@end cartouche
@end deffn

@geindex _name_ (enum.Enum の属性)
@anchor{library/enum enum Enum _name_}@anchor{2a3b}
@deffn {の属性} _name_

Name of the member.
@end deffn

@geindex _value_ (enum.Enum の属性)
@anchor{library/enum enum Enum _value_}@anchor{2a3c}
@deffn {の属性} _value_

Value of the member, can be set in @ref{2a3a,,__new__()}.
@end deffn

@geindex _order_ (enum.Enum の属性)
@anchor{library/enum enum Enum _order_}@anchor{2a3d}
@deffn {の属性} _order_

No longer used, kept for backward compatibility.
(class attribute, removed during class creation).
@end deffn

@geindex _ignore_ (enum.Enum の属性)
@anchor{library/enum enum Enum _ignore_}@anchor{2a3e}
@deffn {の属性} _ignore_

@code{_ignore_} は列挙の作成中にのみ使用され、作成が完了すると削除されます。

@code{_ignore_} は、メンバーにならず、作成された列挙から削除される名前のリストです。例については、@ref{2a3f,,TimePeriod} を参照してください。
@end deffn

@geindex __dir__() (enum.Enum のメソッド)
@anchor{library/enum enum Enum __dir__}@anchor{1c04}
@deffn {メソッド} __dir__ (self)

Returns @code{['__class__', '__doc__', '__module__', 'name', 'value']} and
any public methods defined on `self.__class__':

@example
>>> from enum import Enum
>>> from datetime import date
>>> class Weekday(Enum):
...     MONDAY = 1
...     TUESDAY = 2
...     WEDNESDAY = 3
...     THURSDAY = 4
...     FRIDAY = 5
...     SATURDAY = 6
...     SUNDAY = 7
...     @@classmethod
...     def today(cls):
...         print('today is %s' % cls(date.today().isoweekday()).name)
...
>>> dir(Weekday.SATURDAY)
['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', 'today', 'value']
@end example
@end deffn

@geindex _generate_next_value_() (enum.Enum のメソッド)
@anchor{library/enum enum Enum _generate_next_value_}@anchor{2a40}
@deffn {メソッド} _generate_next_value_ (name, start, count, last_values)

@quotation

@*name: 
定義されているメンバーの名前（例：'RED'）。


@*start: 
Enumの開始値。デフォルトは1です。


@*count: 
定義済みのメンバーの数。現在のメンバーを含めない。


@*last_values: 
定義済みの値のリスト。

@end quotation

@ref{e9b,,auto} によって返される次の値を決定するために使用される `staticmethod'  です:

@example
>>> from enum import auto, Enum
>>> class PowersOfThree(Enum):
...     @@staticmethod
...     def _generate_next_value_(name, start, count, last_values):
...         return 3 ** (count + 1)
...     FIRST = auto()
...     SECOND = auto()
...
>>> PowersOfThree.SECOND.value
9
@end example
@end deffn

@geindex __init__() (enum.Enum のメソッド)
@anchor{library/enum enum Enum __init__}@anchor{2a41}
@deffn {メソッド} __init__ (self, *args, **kwds)

デフォルトでは何もしません。メンバーに複数の値が指定されている場合、それらの値は @code{__init__} の別々の引数となります。例えば、

@example
>>> from enum import Enum
>>> class Weekday(Enum):
...     MONDAY = 1, 'Mon'
@end example

@code{Weekday.__init__()} は @code{Weekday.__init__(self, 1, 'Mon')} として呼び出されます。
@end deffn

@geindex __init_subclass__() (enum.Enum のメソッド)
@anchor{library/enum enum Enum __init_subclass__}@anchor{2a42}
@deffn {メソッド} __init_subclass__ (cls, **kwds)

サブクラスを更に設定するために使用される `classmethod' です。デフォルトでは何も行いません。
@end deffn

@geindex _missing_() (enum.Enum のメソッド)
@anchor{library/enum enum Enum _missing_}@anchor{2a43}
@deffn {メソッド} _missing_ (cls, value)

`cls' で見つからない値を検索するための `classmethod' です。デフォルトでは何もしませんが、カスタムの検索の振る舞いを実装するためにオーバーライドすることができます:

@example
>>> from enum import auto, StrEnum
>>> class Build(StrEnum):
...     DEBUG = auto()
...     OPTIMIZED = auto()
...     @@classmethod
...     def _missing_(cls, value):
...         value = value.lower()
...         for member in cls:
...             if member.value == value:
...                 return member
...         return None
...
>>> Build.DEBUG.value
'debug'
>>> Build('deBUG')
<Build.DEBUG: 'debug'>
@end example
@end deffn

@geindex __new__() (enum.Enum のメソッド)
@anchor{library/enum enum Enum __new__}@anchor{2a3a}
@deffn {メソッド} __new__ (cls, *args, **kwds)

デフォルトでは存在しません。指定された場合、列挙型のクラス定義またはmix-inクラス（例えば @code{int} など）のいずれかで、メンバーに代入されたすべての値が渡されます。例:

@example
>>> from enum import Enum
>>> class MyIntEnum(int, Enum):
...     TWENTYSIX = '1a', 16
@end example

results in the call @code{int('1a', 16)} and a value of @code{26} for the member.

@cartouche
@quotation 注釈 
When writing a custom @code{__new__}, do not use @code{super().__new__} --
call the appropriate @code{__new__} instead.
@end quotation
@end cartouche
@end deffn

@geindex __repr__() (enum.Enum のメソッド)
@anchor{library/enum enum Enum __repr__}@anchor{1afa}
@deffn {メソッド} __repr__ (self)

`repr()' の呼び出しに使用される文字列を返します。デフォルトでは、 `Enum' 名、メンバー名、および値を返しますが、オーバーライドすることもできます:

@example
>>> from enum import auto, Enum
>>> class OtherStyle(Enum):
...     ALTERNATE = auto()
...     OTHER = auto()
...     SOMETHING_ELSE = auto()
...     def __repr__(self):
...         cls_name = self.__class__.__name__
...         return f'@{cls_name@}.@{self.name@}'
...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"@{OtherStyle.ALTERNATE@}"
(OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE')
@end example
@end deffn

@geindex __str__() (enum.Enum のメソッド)
@anchor{library/enum enum Enum __str__}@anchor{834}
@deffn {メソッド} __str__ (self)

`str()' の呼び出しに使用される文字列を返します。デフォルトでは、 `Enum' の名前とメンバーの名前を返しますが、オーバーライドすることもできます:

@example
>>> from enum import auto, Enum
>>> class OtherStyle(Enum):
...     ALTERNATE = auto()
...     OTHER = auto()
...     SOMETHING_ELSE = auto()
...     def __str__(self):
...         return f'@{self.name@}'
...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"@{OtherStyle.ALTERNATE@}"
(<OtherStyle.ALTERNATE: 1>, 'ALTERNATE', 'ALTERNATE')
@end example
@end deffn

@geindex __format__() (enum.Enum のメソッド)
@anchor{library/enum enum Enum __format__}@anchor{832}
@deffn {メソッド} __format__ (self)

`format()' および `f-string' の呼び出しに使用される文字列を返します。デフォルトでは、@ref{834,,__str__()} の戻り値を返しますが、オーバーライドすることもできます。:

@example
>>> from enum import auto, Enum
>>> class OtherStyle(Enum):
...     ALTERNATE = auto()
...     OTHER = auto()
...     SOMETHING_ELSE = auto()
...     def __format__(self, spec):
...         return f'@{self.name@}'
...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"@{OtherStyle.ALTERNATE@}"
(<OtherStyle.ALTERNATE: 1>, 'OtherStyle.ALTERNATE', 'ALTERNATE')
@end example
@end deffn

@cartouche
@quotation 注釈 
@ref{842,,Enum} で @ref{e9b,,auto} を使用すると、 @code{1} から始まりインクリメントする整数が値となります。
@end quotation
@end cartouche


バージョン 3.12 で変更: @ref{1af9,,データクラスのサポート} の追加


@geindex _add_alias_() (enum.Enum のメソッド)
@anchor{library/enum enum Enum _add_alias_}@anchor{2a44}
@deffn {メソッド} _add_alias_ ()

Adds a new name as an alias to an existing member:

@example
>>> Color.RED._add_alias_("ERROR")
>>> Color.ERROR
<Color.RED: 1>
@end example

Raises a @ref{452,,NameError} if the name is already assigned to a different member.


Added in version 3.13.

@end deffn

@geindex _add_value_alias_() (enum.Enum のメソッド)
@anchor{library/enum enum Enum _add_value_alias_}@anchor{2a45}
@deffn {メソッド} _add_value_alias_ ()

Adds a new value as an alias to an existing member:

@example
>>> Color.RED._add_value_alias_(42)
>>> Color(42)
<Color.RED: 1>
@end example

Raises a @ref{2ec,,ValueError} if the value is already linked with a different member.


Added in version 3.13.

@end deffn
@end deffn

@geindex IntEnum (enum のクラス)
@anchor{library/enum enum IntEnum}@anchor{edb}
@deffn {クラス} enum.IntEnum

`IntEnum' is the same as @ref{842,,Enum}, but its members are also integers and can be
used anywhere that an integer can be used.  If any integer operation is performed
with an `IntEnum' member, the resulting value loses its enumeration status.

@example
>>> from enum import IntEnum
>>> class Number(IntEnum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...
>>> Number.THREE
<Number.THREE: 3>
>>> Number.ONE + Number.TWO
3
>>> Number.THREE + 5
8
>>> Number.THREE == 3
True
@end example

@cartouche
@quotation 注釈 
@ref{edb,,IntEnum} で @ref{e9b,,auto} を使用すると、 @code{1} から始まりインクリメントする整数が値となります。
@end quotation
@end cartouche


バージョン 3.11 で変更: @ref{830,,__str__()} は、既存の定数を置き換えるユースケースをより良くサポートするために @code{int.__str__()} に変更されました。同じ理由で、@ref{831,,__format__()} は既に @code{int.__format__()} に変更されています。

@end deffn

@geindex StrEnum (enum のクラス)
@anchor{library/enum enum StrEnum}@anchor{82d}
@deffn {クラス} enum.StrEnum

`StrEnum' is the same as @ref{842,,Enum}, but its members are also strings and
can be used in most of the same places that a string can be used. The result
of any string operation performed on or with a `StrEnum' member is not part
of the enumeration.

@example
>>> from enum import StrEnum, auto
>>> class Color(StrEnum):
...     RED = 'r'
...     GREEN = 'g'
...     BLUE = 'b'
...     UNKNOWN = auto()
...
>>> Color.RED
<Color.RED: 'r'>
>>> Color.UNKNOWN
<Color.UNKNOWN: 'unknown'>
>>> str(Color.UNKNOWN)
'unknown'
@end example

@cartouche
@quotation 注釈 
There are places in the stdlib that check for an exact @ref{169,,str}
instead of a @ref{169,,str} subclass (i.e. @code{type(unknown) == str}
instead of @code{isinstance(unknown, str)}), and in those locations you
will need to use @code{str(MyStrEnum.MY_MEMBER)}.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
@ref{82d,,StrEnum} で @ref{e9b,,auto} を使用すると、メンバー名を小文字に変換したものが値となります。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
@ref{830,,__str__()} は `既存の定数の置換' ユースケースをより良くサポートするために @code{str.__str__()} となりました。 @ref{831,,__format__()} も同様に、同じ理由で @code{str.__format__()} となりました。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex Flag (enum のクラス)
@anchor{library/enum enum Flag}@anchor{835}
@deffn {クラス} enum.Flag

@code{Flag} is the same as @ref{842,,Enum}, but its members support the bitwise
operators @code{&} (`AND'), @code{|} (`OR'), @code{^} (`XOR'), and @code{~} (`INVERT');
the results of those operations are (aliases of) members of the enumeration.

@geindex __contains__() (enum.Flag のメソッド)
@anchor{library/enum enum Flag __contains__}@anchor{2a46}
@deffn {メソッド} __contains__ (self, value)

値を含む場合に `True' を返します:

@example
>>> from enum import Flag, auto
>>> class Color(Flag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> purple = Color.RED | Color.BLUE
>>> white = Color.RED | Color.GREEN | Color.BLUE
>>> Color.GREEN in purple
False
>>> Color.GREEN in white
True
>>> purple in white
True
>>> white in purple
False
@end example
@end deffn


@deffn {メソッド} __iter__(self):

エイリアスでない、全てのメンバーを返します:

@example
>>> list(Color.RED)
[<Color.RED: 1>]
>>> list(purple)
[<Color.RED: 1>, <Color.BLUE: 4>]
@end example


Added in version 3.11.

@end deffn


@deffn {メソッド} __len__(self):

flag 内のメンバーの数を返します:

@example
>>> len(Color.GREEN)
1
>>> len(white)
3
@end example


Added in version 3.11.

@end deffn


@deffn {メソッド} __bool__(self):

メンバーがflagに含まれている場合は `True' を返し、それ以外の場合は `False' を返します:

@example
>>> bool(Color.GREEN)
True
>>> bool(white)
True
>>> black = Color(0)
>>> bool(black)
False
@end example
@end deffn

@geindex __or__() (enum.Flag のメソッド)
@anchor{library/enum enum Flag __or__}@anchor{2a47}
@deffn {メソッド} __or__ (self, other)

現在のフラグと他のフラグの論理和となるフラグを返します:

@example
>>> Color.RED | Color.GREEN
<Color.RED|GREEN: 3>
@end example
@end deffn

@geindex __and__() (enum.Flag のメソッド)
@anchor{library/enum enum Flag __and__}@anchor{2a48}
@deffn {メソッド} __and__ (self, other)

現在のフラグと他のフラグの論理積となるフラグを返します:

@example
>>> purple & white
<Color.RED|BLUE: 5>
>>> purple & Color.GREEN
<Color: 0>
@end example
@end deffn

@geindex __xor__() (enum.Flag のメソッド)
@anchor{library/enum enum Flag __xor__}@anchor{2a49}
@deffn {メソッド} __xor__ (self, other)

現在のフラグと他のフラグの排他的論理和となるフラグを返します:

@example
>>> purple ^ white
<Color.GREEN: 2>
>>> purple ^ Color.GREEN
<Color.RED|GREEN|BLUE: 7>
@end example
@end deffn


@deffn {メソッド} __invert__(self):

Returns all the flags in `type(self)' that are not in `self':

@example
>>> ~white
<Color: 0>
>>> ~purple
<Color.GREEN: 2>
>>> ~Color.RED
<Color.GREEN|BLUE: 6>
@end example
@end deffn

@geindex _numeric_repr_() (enum.Flag のメソッド)
@anchor{library/enum enum Flag _numeric_repr_}@anchor{2a4a}
@deffn {メソッド} _numeric_repr_ ()

Function used to format any remaining unnamed numeric values.  Default is
the value's repr; common choices are @ref{14e7,,hex()} and @ref{14e6,,oct()}.
@end deffn

@cartouche
@quotation 注釈 
@ref{e9b,,auto} と @ref{835,,Flag} を一緒に使うと、@code{1} から始まる2の累乗の整数になります。
@end quotation
@end cartouche


バージョン 3.11 で変更: The `repr()' of zero-valued flags has changed.  It
is now:

@example
>>> Color(0)
<Color: 0>
@end example

@end deffn

@geindex IntFlag (enum のクラス)
@anchor{library/enum enum IntFlag}@anchor{e9a}
@deffn {クラス} enum.IntFlag

@code{IntFlag} is the same as @ref{835,,Flag}, but its members are also integers and can be
used anywhere that an integer can be used.

@example
>>> from enum import IntFlag, auto
>>> class Color(IntFlag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> Color.RED & 2
<Color: 0>
>>> Color.RED | 2
<Color.RED|GREEN: 3>
@end example

`IntFlag' のメンバーと整数の演算が行われた場合、結果は `IntFlag' ではありません:

@example
>>> Color.RED + 2
3
@end example

If a @ref{835,,Flag} operation is performed with an `IntFlag' member and:


@itemize *

@item 
結果が有効な `IntFlag': `IntFlag' が返されます

@item 
the result is not a valid `IntFlag': the result depends on the @ref{836,,FlagBoundary} setting
@end itemize

The @ref{1c1,,repr()} of unnamed zero-valued flags has changed.  It is now:

@example
>>> Color(0)
<Color: 0>
@end example

@cartouche
@quotation 注釈 
@ref{e9b,,auto} と @ref{e9a,,IntFlag} を一緒に使うと、@code{1} から始まる2の累乗の整数になります。
@end quotation
@end cartouche


バージョン 3.11 で変更: @ref{830,,__str__()} は、既存の定数を置き換えるユースケースをより良くサポートするために @code{int.__str__()} に変更されました。同じ理由で、@ref{831,,__format__()} は既に @code{int.__format__()} に変更されています。

@code{IntFlag} の反転は、与えられたフラグ以外のすべてのフラグの結合となる正の値を返すようになりました。これは既存の @ref{835,,Flag} の振る舞いに一致します。

@end deffn

@geindex ReprEnum (enum のクラス)
@anchor{library/enum enum ReprEnum}@anchor{82e}
@deffn {クラス} enum.ReprEnum

@code{ReprEnum} uses the @ref{1afa,,repr()} of @ref{842,,Enum},
but the @ref{169,,str()} of the mixed-in data type:


@itemize *

@item 
@code{int.__str__()} for @ref{edb,,IntEnum} and @ref{e9a,,IntFlag}

@item 
@code{str.__str__()} for @ref{82d,,StrEnum}
@end itemize

@code{ReprEnum} を継承することで、@ref{842,,Enum} デフォルトの @ref{834,,str()}  を使用する代わりに、mix-inされたデータ型の @ref{169,,str()}  /  @ref{199,,format()} を使用します。


Added in version 3.11.

@end deffn

@geindex EnumCheck (enum のクラス)
@anchor{library/enum enum EnumCheck}@anchor{838}
@deffn {クラス} enum.EnumCheck

`EnumCheck' には @ref{837,,verify()} デコレータやさまざまな制約を保証するために使用されるオプションが含まれています。制約に違反すると @ref{2ec,,ValueError} が発生します。

@geindex UNIQUE (enum.EnumCheck の属性)
@anchor{library/enum enum EnumCheck UNIQUE}@anchor{2a4b}
@deffn {の属性} UNIQUE

それぞれの値が1つの名前しか持たないことを確認します:

@example
>>> from enum import Enum, verify, UNIQUE
>>> @@verify(UNIQUE)
... class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...     CRIMSON = 1
Traceback (most recent call last):
...
ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED
@end example
@end deffn

@geindex CONTINUOUS (enum.EnumCheck の属性)
@anchor{library/enum enum EnumCheck CONTINUOUS}@anchor{2a4c}
@deffn {の属性} CONTINUOUS

最小値のメンバーと最大値のメンバーの間に欠損値がないことを確認します:

@example
>>> from enum import Enum, verify, CONTINUOUS
>>> @@verify(CONTINUOUS)
... class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 5
Traceback (most recent call last):
...
ValueError: invalid enum 'Color': missing values 3, 4
@end example
@end deffn

@geindex NAMED_FLAGS (enum.EnumCheck の属性)
@anchor{library/enum enum EnumCheck NAMED_FLAGS}@anchor{2a4d}
@deffn {の属性} NAMED_FLAGS

任意のフラググループ/マスクが、名前付きフラグのみを含むことを確認します -- 値を指定するのではなく、@ref{e9b,,auto()} によって生成される場合に便利です:

@example
>>> from enum import Flag, verify, NAMED_FLAGS
>>> @@verify(NAMED_FLAGS)
... class Color(Flag):
...     RED = 1
...     GREEN = 2
...     BLUE = 4
...     WHITE = 15
...     NEON = 31
Traceback (most recent call last):
...
ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing combined values of 0x18 [use enum.show_flag_values(value) for details]
@end example
@end deffn

@cartouche
@quotation 注釈 
CONTINUOUSとNAMED_FLAGSは整数値のメンバーとともに動作するように設計されています。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex FlagBoundary (enum のクラス)
@anchor{library/enum enum FlagBoundary}@anchor{836}
@deffn {クラス} enum.FlagBoundary

@code{FlagBoundary} controls how out-of-range values are handled in @ref{835,,Flag} and its
subclasses.

@geindex STRICT (enum.FlagBoundary の属性)
@anchor{library/enum enum FlagBoundary STRICT}@anchor{2a4e}
@deffn {の属性} STRICT

範囲外の値は @ref{2ec,,ValueError} を送出します。これは @ref{835,,Flag} のデフォルトです:

@example
>>> from enum import Flag, STRICT, auto
>>> class StrictFlag(Flag, boundary=STRICT):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> StrictFlag(2**2 + 2**4)
Traceback (most recent call last):
...
ValueError: <flag 'StrictFlag'> invalid value 20
    given 0b0 10100
  allowed 0b0 00111
@end example
@end deffn

@geindex CONFORM (enum.FlagBoundary の属性)
@anchor{library/enum enum FlagBoundary CONFORM}@anchor{2a4f}
@deffn {の属性} CONFORM

Out-of-range values have invalid values removed, leaving a valid @ref{835,,Flag}
value:

@example
>>> from enum import Flag, CONFORM, auto
>>> class ConformFlag(Flag, boundary=CONFORM):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> ConformFlag(2**2 + 2**4)
<ConformFlag.BLUE: 4>
@end example
@end deffn

@geindex EJECT (enum.FlagBoundary の属性)
@anchor{library/enum enum FlagBoundary EJECT}@anchor{2a50}
@deffn {の属性} EJECT

Out-of-range values lose their @ref{835,,Flag} membership and revert to @ref{19b,,int}.

@example
>>> from enum import Flag, EJECT, auto
>>> class EjectFlag(Flag, boundary=EJECT):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> EjectFlag(2**2 + 2**4)
20
@end example
@end deffn

@geindex KEEP (enum.FlagBoundary の属性)
@anchor{library/enum enum FlagBoundary KEEP}@anchor{2a51}
@deffn {の属性} KEEP

Out-of-range values are kept, and the @ref{835,,Flag} membership is kept.
This is the default for @ref{e9a,,IntFlag}:

@example
>>> from enum import Flag, KEEP, auto
>>> class KeepFlag(Flag, boundary=KEEP):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> KeepFlag(2**2 + 2**4)
<KeepFlag.BLUE|16: 20>
@end example
@end deffn


Added in version 3.11.

@end deffn

@geindex EnumDict (enum のクラス)
@anchor{library/enum enum EnumDict}@anchor{4f6}
@deffn {クラス} enum.EnumDict

`EnumDict' is a subclass of @ref{183,,dict} that is used as the namespace
for defining enum classes (see @ref{e58,,クラスの名前空間の準備}).
It is exposed to allow subclasses of @ref{4f7,,EnumType} with advanced
behavior like having multiple values per member.
It should be called with the name of the enum class being created, otherwise
private names and internal classes will not be handled correctly.

Note that only the @ref{12c0,,MutableMapping} interface
(@ref{14e3,,__setitem__()} and @ref{167e,,update()}) is overridden.
It may be possible to bypass the checks using other @code{dict}
operations like @ref{2401,,|=}.

@geindex member_names (enum.EnumDict の属性)
@anchor{library/enum enum EnumDict member_names}@anchor{2a52}
@deffn {の属性} member_names

A list of member names.
@end deffn


Added in version 3.13.

@end deffn


__________________________________________________________________


@menu
* __dunder__ 名のサポート:: 
* _sunder_ 名のサポート:: 

@end menu

@node __dunder__ 名のサポート,_sunder_ 名のサポート,,データ型<2>
@anchor{library/enum supported-dunder-names}@anchor{2a53}
@subsubsection @code{__dunder__} 名のサポート


@ref{2a36,,__members__} は読み込み専用の、 @code{member_name}:@code{member}  を要素とする順序付きマッピングです。これはクラスでのみ利用可能です。

@ref{2a3a,,__new__()}, if specified, must create and return the enum members;
it is also a very good idea to set the member's @code{_value_} appropriately.
Once all the members are created it is no longer used.

@node _sunder_ 名のサポート,,__dunder__ 名のサポート,データ型<2>
@anchor{library/enum supported-sunder-names}@anchor{2a54}
@subsubsection @code{_sunder_} 名のサポート



@itemize -

@item 
@ref{2a3b,,_name_} -- メンバー名

@item 
@ref{2a3c,,_value_} -- メンバーの値; @code{__new__} で設定できます

@item 
@ref{2a43,,_missing_()} -- 値が見付からなかったときに使われる検索関数; オーバーライドされていることがあります

@item 
@ref{2a3e,,_ignore_} -- 名前のリストで、 @ref{24d,,list} もしくは @ref{169,,str} です。この名前の要素はメンバーへの変換が行われず、最終的なクラスから削除されます。

@item 
@ref{2a3d,,_order_} -- no longer used, kept for backward
compatibility (class attribute, removed during class creation)

@item 
@ref{2a40,,_generate_next_value_()} -- 列挙型のメンバーの適切な値を取得するのに使われます。オーバーライドされます。

@cartouche
@quotation 注釈 
標準の @ref{842,,Enum} クラスの場合、次の値として選択されるのは、定義された最大の値に1を加えたものです。

@ref{835,,Flag} クラスでは、次に選ばれる値は、次の最大の2のべき乗となります。
@end quotation
@end cartouche

@item 
@ref{2a44,,_add_alias_()} -- adds a new name as an alias to an existing
member.

@item 
@ref{2a45,,_add_value_alias_()} -- adds a new value as an alias to an
existing member.

@item 
While @code{_sunder_} names are generally reserved for the further development
of the @ref{842,,Enum} class and can not be used, some are explicitly allowed:


@itemize -

@item 
@code{_repr_*} (e.g. @code{_repr_html_}), as used in IPython's rich display@footnote{https://ipython.readthedocs.io/en/stable/config/integrating.html#rich-display}
@end itemize
@end itemize


Added in version 3.6: @code{_missing_}, @code{_order_}, @code{_generate_next_value_}



Added in version 3.7: @code{_ignore_}



Added in version 3.13: @code{_add_alias_}, @code{_add_value_alias_}, @code{_repr_*}



__________________________________________________________________


@node ユーティリティとデコレータ,注釈,データ型<2>,enum --- 列挙型のサポート
@anchor{library/enum ipython-s-rich-display}@anchor{2a55}@anchor{library/enum utilities-and-decorators}@anchor{2a56}
@subsubsection ユーティリティとデコレータ


@geindex auto (enum のクラス)
@anchor{library/enum enum auto}@anchor{e9b}
@deffn {クラス} enum.auto

`auto' can be used in place of a value.  If used, the `Enum' machinery will
call an @ref{842,,Enum}'s @ref{2a40,,_generate_next_value_()} to get an appropriate value.
For @ref{842,,Enum} and @ref{edb,,IntEnum} that appropriate value will be the last value plus
one; for @ref{835,,Flag} and @ref{e9a,,IntFlag} it will be the first power-of-two greater
than the highest value; for @ref{82d,,StrEnum} it will be the lower-cased version of
the member's name.  Care must be taken if mixing `auto()' with manually
specified values.

`auto' instances are only resolved when at the top level of an assignment, either by
itself or as part of a tuple:


@itemize *

@item 
@code{FIRST = auto()} は動作します（auto() は @code{1} に置き換えられます）

@item 
@code{SECOND = auto(), -2} は動作します（auto は @code{2} に置き換えられるため、 @code{SECOND} 列挙型のメンバーには @code{2, -2} が使用されます）

@item 
@code{THREE = [auto(), -3]} will `not' work (@code{[<auto instance>, -3]} is used to
create the @code{THREE} enum member)
@end itemize


バージョン 3.11.1 で変更: 以前のバージョンでは、 @code{auto()} は、代入行に他のものがあると正しく動作しませんでした。


@code{_generate_next_value_} は、 `auto' が使用する値をカスタマイズするためにオーバーライドすることができる。

@cartouche
@quotation 注釈 
3.13では、デフォルトの @code{_generate_next_value_} は常に最も高いメンバーの値に1を加えたものを返し、メンバーのいずれかが比較できない型である場合には失敗します。
@end quotation
@end cartouche
@end deffn

@geindex property() (enum モジュール)
@anchor{library/enum enum property}@anchor{83b}
@deffn {の関数} @@enum.property

A decorator similar to the built-in `property', but specifically for
enumerations.  It allows member attributes to have the same names as members
themselves.

@cartouche
@quotation 注釈 
the `property' and the member must be defined in separate classes;
for example, the `value' and `name' attributes are defined in the
`Enum' class, and `Enum' subclasses can define members with the
names @code{value} and @code{name}.
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex unique() (enum モジュール)
@anchor{library/enum enum unique}@anchor{2a2c}
@deffn {の関数} @@enum.unique

列挙型専用の @ref{14ef,,class} デコレーターです。列挙型の @ref{2a36,,__members__} に別名がないかどうか検索します; 見つかった場合、@ref{2ec,,ValueError} が詳細情報とともに送出されます:

@example
>>> from enum import Enum, unique
>>> @@unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
@end example
@end deffn

@geindex verify() (enum モジュール)
@anchor{library/enum enum verify}@anchor{837}
@deffn {の関数} @@enum.verify

列挙型専用の @ref{14ef,,class} デコレーターです。対象の列挙型に対してチェックを行う制約の指定には @ref{838,,EnumCheck} のメンバーが使用されます。


Added in version 3.11.

@end deffn

@geindex member() (enum モジュール)
@anchor{library/enum enum member}@anchor{839}
@deffn {の関数} @@enum.member

列挙型で使用するデコレータ: 対象は列挙型のメンバー になります。


Added in version 3.11.

@end deffn

@geindex nonmember() (enum モジュール)
@anchor{library/enum enum nonmember}@anchor{83a}
@deffn {の関数} @@enum.nonmember

列挙型で使用するデコレータ: 対象は列挙型のメンバー になりません。


Added in version 3.11.

@end deffn

@geindex global_enum() (enum モジュール)
@anchor{library/enum enum global_enum}@anchor{83d}
@deffn {の関数} @@enum.global_enum

A decorator to change the @ref{169,,str()} and @ref{1c1,,repr()} of an enum
to show its members as belonging to the module instead of its class.
Should only be used when the enum members are exported
to the module global namespace (see @ref{83f,,re.RegexFlag} for an example).


Added in version 3.11.

@end deffn

@geindex show_flag_values() (enum モジュール)
@anchor{library/enum enum show_flag_values}@anchor{2a2d}
@deffn {の関数} enum.show_flag_values (value)

フラグの `value' に含まれる全ての2の累乗の整数のリストを返します。


Added in version 3.11.

@end deffn

@geindex bin() (enum モジュール)
@anchor{library/enum enum bin}@anchor{178d}
@deffn {の関数} enum.bin (num, max_bits=None)

Like built-in @ref{14c0,,bin()}, except negative values are represented in
two's complement, and the leading bit always indicates sign
(@code{0} implies positive, @code{1} implies negative).

@example
>>> import enum
>>> enum.bin(10)
'0b0 1010'
>>> enum.bin(~10)   # ~10 is -11
'0b1 0101'
@end example


Added in version 3.11.

@end deffn


__________________________________________________________________


@node 注釈,,ユーティリティとデコレータ,enum --- 列挙型のサポート
@anchor{library/enum notes}@anchor{2a2b}
@subsubsection 注釈


@ref{edb,,IntEnum} 、 @ref{82d,,StrEnum} 、 @ref{e9a,,IntFlag}

@quotation

これらの3つの列挙型は、既存の整数ベースおよび文字列ベースの値の代替として設計されています。そのため、追加の制限があります:


@itemize -

@item 
@code{__str__} は、列挙型のメンバーの名前ではなく値を使用します

@item 
@code{__format__} は @code{__str__} を使用するため、列挙型のメンバーの名前ではなく値を使用します
@end itemize

もし、そのような制限が必要でない/望まない場合は、@code{int} または @code{str} タイプを継承して、カスタムの基底クラスを作成することができます:

@example
>>> from enum import Enum
>>> class MyIntEnum(int, Enum):
...     pass
@end example

または列挙型の中で適切な @ref{169,,str()} などを再代入することもできます:

@example
>>> from enum import Enum, IntEnum
>>> class MyIntEnum(IntEnum):
...     __str__ = Enum.__str__
@end example
@end quotation

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node graphlib --- グラフ構造を操作する機能,,enum --- 列挙型のサポート,データ型
@anchor{library/graphlib doc}@anchor{2a57}@anchor{library/graphlib graphlib-functionality-to-operate-with-graph-like-structures}@anchor{2a58}@anchor{library/graphlib module-graphlib}@anchor{69}@anchor{library/graphlib translation-repo}@anchor{2a59}
@subsection @code{graphlib} --- グラフ構造を操作する機能


@geindex module; graphlib

`ソースコード:' Lib/graphlib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/graphlib.py}

@c import graphlib
@c from graphlib import *


__________________________________________________________________


@geindex TopologicalSorter (graphlib のクラス)
@anchor{library/graphlib graphlib TopologicalSorter}@anchor{ade}
@deffn {クラス} graphlib.TopologicalSorter (graph=None)

@ref{824,,ハッシュ可能} な頂点のグラフをトポロジカルソートする機能を提供します。

トポロジカル順序はグラフの頂点の線形順序で、頂点 u から 頂点 v への有向辺 u-> v 全てについて、頂点 u が頂点 v よりも前にくるような順序です。例えば、グラフの頂点が実行するタスクを表し、その辺があるタスクが別のタスクよりも前に実行されなければならないという制約を表す場合、トポロジカル順序は制約を満たすタスクの実行順序のシーケンスになります。トポロジカル順序が得られるのは、グラフが有向閉路を持たない、つまり有向非巡回グラフである場合でかつその時に限ります。

もしオプションの `graph' 引数が与えられた場合、その値は有向非巡回グラフを表す辞書でなければならず、辞書はそのキーがノードで、その値はキーのノードの先行ノードのイテラブルとなります（言い換えると、辞書の値はそのキーのノードを指す辺を持つノードのイテラブルです） 辺 @ref{2a5a,,add()} メソッドを使うことで、さらにノードを追加することができます。

一般的に、与えられたグラフのソートの実行に必要なステップは以下のようになります:


@itemize *

@item 
@ref{ade,,TopologicalSorter} のインスタンスをオプションの初期グラフで生成します。

@item 
さらにノードをグラフに追加します。

@item 
@ref{21f,,prepare()} をグラフ上で呼び出します。

@item 
@ref{2a5b,,is_active()} が @code{True} の間、 @ref{2a5c,,get_ready()} によって返されたノード群をイテレートし、それらを処理します。ノードの処理が終わる都度、@ref{2a5d,,done()} を呼び出します。
@end itemize

すぐにグラフのノードをソートした結果が必要で、並行性が不要な場合、便利なメソッド @ref{2a5e,,TopologicalSorter.static_order()} を直接呼び出すことができます:

@example
>>> graph = @{"D": @{"B", "C"@}, "C": @{"A"@}, "B": @{"A"@}@}
>>> ts = TopologicalSorter(graph)
>>> tuple(ts.static_order())
('A', 'C', 'B', 'D')
@end example

このクラスは、簡単に準備が整ったノードの並列処理を行えるよう設計されています。例えば:

@example
topological_sorter = TopologicalSorter()

# Add nodes to 'topological_sorter'...

topological_sorter.prepare()
while topological_sorter.is_active():
    for node in topological_sorter.get_ready():
        # Worker threads or processes take nodes to work on off the
        # 'task_queue' queue.
        task_queue.put(node)

    # When the work for a node is done, workers put the node in
    # 'finalized_tasks_queue' so we can get more nodes to work on.
    # The definition of 'is_active()' guarantees that, at this point, at
    # least one node has been placed on 'task_queue' that hasn't yet
    # been passed to 'done()', so this blocking 'get()' must (eventually)
    # succeed.  After calling 'done()', we loop back to call 'get_ready()'
    # again, so put newly freed nodes on 'task_queue' as soon as
    # logically possible.
    node = finalized_tasks_queue.get()
    topological_sorter.done(node)
@end example

@geindex add() (graphlib.TopologicalSorter のメソッド)
@anchor{library/graphlib graphlib TopologicalSorter add}@anchor{2a5a}
@deffn {メソッド} add (node, *predecessors)

新しいノードとその先行ノードをグラフに追加します。 `node' と `predecessors' のすべての要素は @ref{824,,ハッシュ可能} でなければなりません。

同じ node 引数で複数回呼び出した場合、依存関係の集合は、それまでに指定した依存関係の和集合になります。

It is possible to add a node with no dependencies (`predecessors' is not
provided) or to provide a dependency twice. If a node that has not been
provided before is included among `predecessors' it will be automatically
added to the graph with no predecessors of its own.

@ref{21f,,prepare()} を呼び出した後にこのメソッドを呼び出すと、@ref{2ec,,ValueError} を送出します。
@end deffn

@geindex prepare() (graphlib.TopologicalSorter のメソッド)
@anchor{library/graphlib graphlib TopologicalSorter prepare}@anchor{21f}
@deffn {メソッド} prepare ()

Mark the graph as finished and check for cycles in the graph. If any cycle
is detected, @ref{2a5f,,CycleError} will be raised, but
@ref{2a5c,,get_ready()} can still be used to obtain as many
nodes as possible until cycles block more progress. After a call to this
function, the graph cannot be modified, and therefore no more nodes can be
added using @ref{2a5a,,add()}.

A @ref{2ec,,ValueError} will be raised if the sort has been started by
@ref{2a5e,,static_order()} or @ref{2a5c,,get_ready()}.


バージョン 3.14 で変更: @code{prepare()} can now be called more than once as long as the sort has
not started. Previously this raised @ref{2ec,,ValueError}.

@end deffn

@geindex is_active() (graphlib.TopologicalSorter のメソッド)
@anchor{library/graphlib graphlib TopologicalSorter is_active}@anchor{2a5b}
@deffn {メソッド} is_active ()

Returns @code{True} if more progress can be made and @code{False} otherwise.
Progress can be made if cycles do not block the resolution and either
there are still nodes ready that haven't yet been returned by
@ref{2a5c,,TopologicalSorter.get_ready()} or the number of nodes marked
@ref{2a5d,,TopologicalSorter.done()} is less than the number that have been
returned by @ref{2a5c,,TopologicalSorter.get_ready()}.

The @ref{14ed,,__bool__()} method of this class defers to
this function, so instead of:

@example
if ts.is_active():
    ...
@end example

このように簡単に記述できます:

@example
if ts:
    ...
@end example

前もって @ref{21f,,prepare()} を呼び出さずにこの関数を呼び出すと @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex done() (graphlib.TopologicalSorter のメソッド)
@anchor{library/graphlib graphlib TopologicalSorter done}@anchor{2a5d}
@deffn {メソッド} done (*nodes)

Marks a set of nodes returned by @ref{2a5c,,TopologicalSorter.get_ready()} as
processed, unblocking any successor of each node in `nodes' for being
returned in the future by a call to @ref{2a5c,,TopologicalSorter.get_ready()}.

Raises @ref{2ec,,ValueError} if any node in `nodes' has already been marked as
processed by a previous call to this method or if a node was not added to
the graph by using @ref{2a5a,,TopologicalSorter.add()}, if called without
calling @ref{21f,,prepare()} or if node has not yet been
returned by @ref{2a5c,,get_ready()}.
@end deffn

@geindex get_ready() (graphlib.TopologicalSorter のメソッド)
@anchor{library/graphlib graphlib TopologicalSorter get_ready}@anchor{2a5c}
@deffn {メソッド} get_ready ()

Returns a @code{tuple} with all the nodes that are ready. Initially it
returns all nodes with no predecessors, and once those are marked as
processed by calling @ref{2a5d,,TopologicalSorter.done()}, further calls will
return all new nodes that have all their predecessors already processed.
Once no more progress can be made, empty tuples are returned.

前もって @ref{21f,,prepare()} を呼び出さずにこの関数を呼び出すと @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex static_order() (graphlib.TopologicalSorter のメソッド)
@anchor{library/graphlib graphlib TopologicalSorter static_order}@anchor{2a5e}
@deffn {メソッド} static_order ()

Returns an iterator object which will iterate over nodes in a topological
order. When using this method, @ref{21f,,prepare()} and
@ref{2a5d,,done()} should not be called. This method is
equivalent to:

@example
def static_order(self):
    self.prepare()
    while self.is_active():
        node_group = self.get_ready()
        yield from node_group
        self.done(*node_group)
@end example

The particular order that is returned may depend on the specific order in
which the items were inserted in the graph. For example:

@example
>>> ts = TopologicalSorter()
>>> ts.add(3, 2, 1)
>>> ts.add(1, 0)
>>> print([*ts.static_order()])
[2, 0, 1, 3]

>>> ts2 = TopologicalSorter()
>>> ts2.add(1, 0)
>>> ts2.add(3, 2, 1)
>>> print([*ts2.static_order()])
[0, 2, 1, 3]
@end example

This is due to the fact that "0" and "2" are in the same level in the
graph (they would have been returned in the same call to
@ref{2a5c,,get_ready()}) and the order between them is
determined by the order of insertion.

If any cycle is detected, @ref{2a5f,,CycleError} will be raised.
@end deffn


Added in version 3.9.

@end deffn

@menu
* 例外: 例外<4>. 

@end menu

@node 例外<4>,,,graphlib --- グラフ構造を操作する機能
@anchor{library/graphlib exceptions}@anchor{2a60}
@subsubsection 例外


The @code{graphlib} module defines the following exception classes:

@geindex CycleError
@anchor{library/graphlib graphlib CycleError}@anchor{2a5f}
@deffn {例外} graphlib.CycleError

Subclass of @ref{2ec,,ValueError} raised by @ref{21f,,TopologicalSorter.prepare()} if cycles exist
in the working graph. If multiple cycles exist, only one undefined choice among them will
be reported and included in the exception.

The detected cycle can be accessed via the second element in the @ref{78d,,args}
attribute of the exception instance and consists in a list of nodes, such that each node is,
in the graph, an immediate predecessor of the next node in the list. In the reported list,
the first and the last node will be the same, to make it clear that it is cyclic.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 数値と数学モジュール,関数型プログラミング用モジュール,データ型,Python 標準ライブラリ
@anchor{library/numeric doc}@anchor{2a61}@anchor{library/numeric numeric}@anchor{2a62}@anchor{library/numeric numeric-and-mathematical-modules}@anchor{2a63}@anchor{library/numeric translation-repo}@anchor{2a64}
@section 数値と数学モジュール


この章で記述されているモジュールは、数値に関するあるいは数学関係の関数とデータ型を提供します。 @ref{a2,,numbers} モジュールは、数値の型の抽象的な階層を定義します。 @ref{92,,math} と @ref{19,,cmath} モジュールは、浮動小数点数と複素数のための様々な数学関数を含んでいます。 @ref{3a,,decimal} モジュールは、任意精度の計算を使用して、10進数の正確な表現をサポートします。

この章では以下のモジュールが記述されています:

@menu
* numbers: numbers --- 数の抽象基底クラス. 数の抽象基底クラス
* math: math --- 数学関数. 数学関数
* cmath: cmath --- 複素数用の数学関数. 複素数用の数学関数
* decimal: decimal --- 10進固定小数点と浮動小数点の演算. 10進固定小数点と浮動小数点の演算
* fractions: fractions --- 有理数. 有理数
* random: random --- 疑似乱数を生成する. 疑似乱数を生成する
* statistics: statistics --- 数学的統計関数. 数学的統計関数

@end menu

@node numbers --- 数の抽象基底クラス,math --- 数学関数,,数値と数学モジュール
@anchor{library/numbers doc}@anchor{2a65}@anchor{library/numbers module-numbers}@anchor{a2}@anchor{library/numbers numbers-numeric-abstract-base-classes}@anchor{2a66}
@subsection @code{numbers} --- 数の抽象基底クラス


@geindex module; numbers

`ソースコード:' Lib/numbers.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/numbers.py}


__________________________________________________________________


The @code{numbers} module (
@geindex Python Enhancement Proposals; PEP 3141
PEP 3141@footnote{https://peps.python.org/pep-3141/}) defines a hierarchy of numeric
@ref{13ce,,abstract base classes} which progressively define
more operations.  None of the types defined in this module are intended to be instantiated.

@geindex Number (numbers のクラス)
@anchor{library/numbers numbers Number}@anchor{2a67}
@deffn {クラス} numbers.Number

数の階層の根。引数 `x' が、種類は何であれ、数であるということだけチェックしたい場合、@code{isinstance(x, Number)} が使えます。
@end deffn

@menu
* 数値塔:: 
* Notes for type implementers:: 

@end menu

@node 数値塔,Notes for type implementers,,numbers --- 数の抽象基底クラス
@anchor{library/numbers the-numeric-tower}@anchor{2a68}
@subsubsection 数値塔


@geindex Complex (numbers のクラス)
@anchor{library/numbers numbers Complex}@anchor{25fc}
@deffn {クラス} numbers.Complex

この型のサブクラスは複素数を表し、組み込みの @ref{197,,complex} 型を受け付ける演算を含みます。それらは: @ref{197,,complex} および @ref{3c3,,bool} への変換、 @ref{2a69,,real}, @ref{2a6a,,imag}, @code{+}, @code{-}, @code{*}, @code{/}, @code{**}, @ref{208d,,abs()}, @ref{2a6b,,conjugate()}, @code{==}, @code{!=} です。 @code{-} と @code{!=} 以外の全てのものは抽象メソッドや抽象プロパティです。

@geindex real (numbers.Complex の属性)
@anchor{library/numbers numbers Complex real}@anchor{2a69}
@deffn {の属性} real

抽象プロパティ。この数の実部を取り出します。
@end deffn

@geindex imag (numbers.Complex の属性)
@anchor{library/numbers numbers Complex imag}@anchor{2a6a}
@deffn {の属性} imag

抽象プロパティ。この数の虚部を取り出します。
@end deffn

@geindex conjugate() (numbers.Complex のメソッド)
@anchor{library/numbers numbers Complex conjugate}@anchor{2a6b}
@deffn {メソッド} abstractmethod conjugate ()

抽象プロパティ。複素共役を返します。たとえば、@code{(1+3j).conjugate() == (1-3j)} です。
@end deffn
@end deffn

@geindex Real (numbers のクラス)
@anchor{library/numbers numbers Real}@anchor{25f2}
@deffn {クラス} numbers.Real

To @ref{25fc,,Complex}, @code{Real} adds the operations that work on real
numbers.

簡潔に言うとそれらは: @ref{196,,float} への変換, @ref{15d9,,math.trunc()}, @ref{14f2,,round()}, @ref{15d7,,math.floor()}, @ref{15d8,,math.ceil()}, @ref{b99,,divmod()}, @code{//}, @code{%}, @code{<}, @code{<=}, @code{>} および @code{>=} です。

Real はまた @ref{197,,complex()}, @ref{2a69,,real}, @ref{2a6a,,imag} および @ref{2a6b,,conjugate()} のデフォルトを提供します。
@end deffn

@geindex Rational (numbers のクラス)
@anchor{library/numbers numbers Rational}@anchor{14d6}
@deffn {クラス} numbers.Rational

@ref{25f2,,Real} をサブタイプ化し @ref{2a6c,,numerator} と @ref{2a6d,,denominator} のプロパティを加えたものです。これは @ref{196,,float()} のデフォルトも提供します。

The @ref{2a6c,,numerator} and @ref{2a6d,,denominator} values
should be instances of @ref{240a,,Integral} and should be in lowest terms with
@ref{2a6d,,denominator} positive.

@geindex numerator (numbers.Rational の属性)
@anchor{library/numbers numbers Rational numerator}@anchor{2a6c}
@deffn {の属性} numerator

Abstract.  The numerator of this rational number.
@end deffn

@geindex denominator (numbers.Rational の属性)
@anchor{library/numbers numbers Rational denominator}@anchor{2a6d}
@deffn {の属性} denominator

Abstract.  The denominator of this rational number.
@end deffn
@end deffn

@geindex Integral (numbers のクラス)
@anchor{library/numbers numbers Integral}@anchor{240a}
@deffn {クラス} numbers.Integral

@ref{14d6,,Rational} をサブタイプ化し @ref{19b,,int} への変換が加わります。 @ref{196,,float()}, @ref{2a6c,,numerator}, @ref{2a6d,,denominator} のデフォルトを提供します。法 (訳注: 割る数、除数のこと) を持つ @ref{1a4,,pow()} に対する抽象メソッドと、ビット列演算 @code{<<}, @code{>>}, @code{&}, @code{^}, @code{|}, @code{~} を追加します。
@end deffn

@node Notes for type implementers,,数値塔,numbers --- 数の抽象基底クラス
@anchor{library/numbers notes-for-type-implementers}@anchor{2a6e}
@subsubsection Notes for type implementers


Implementers should be careful to make equal numbers equal and hash
them to the same values. This may be subtle if there are two different
extensions of the real numbers. For example, @ref{213,,fractions.Fraction}
implements @ref{801,,hash()} as follows:

@example
def __hash__(self):
    if self.denominator == 1:
        # Get integers right.
        return hash(self.numerator)
    # Expensive check, but definitely correct.
    if self == float(self):
        return hash(float(self))
    else:
        # Use tuple's hash to avoid a high collision rate on
        # simple fractions.
        return hash((self.numerator, self.denominator))
@end example

@menu
* さらに数のABCを追加する:: 
* 算術演算の実装:: 

@end menu

@node さらに数のABCを追加する,算術演算の実装,,Notes for type implementers
@anchor{library/numbers adding-more-numeric-abcs}@anchor{2a6f}
@subsubsection さらに数のABCを追加する


数に対する ABC が他にも多く存在しうることは、言うまでもありません。それらの ABC を階層に追加する可能性が閉ざされるとしたら、その階層は貧相な階層でしかありません。たとえば、 @code{MyFoo} を @ref{25fc,,Complex} と @ref{25f2,,Real} の間に付け加えるには、次のようにします:

@example
class MyFoo(Complex): ...
MyFoo.register(Real)
@end example

@node 算術演算の実装,,さらに数のABCを追加する,Notes for type implementers
@anchor{library/numbers id1}@anchor{2a70}@anchor{library/numbers implementing-the-arithmetic-operations}@anchor{2332}
@subsubsection 算術演算の実装


We want to implement the arithmetic operations so that mixed-mode
operations either call an implementation whose author knew about the
types of both arguments, or convert both to the nearest built in type
and do the operation there. For subtypes of @ref{240a,,Integral}, this
means that @ref{23dd,,__add__()} and @ref{23de,,__radd__()} should be
defined as:

@example
class MyIntegral(Integral):

    def __add__(self, other):
        if isinstance(other, MyIntegral):
            return do_my_adding_stuff(self, other)
        elif isinstance(other, OtherTypeIKnowAbout):
            return do_my_other_adding_stuff(self, other)
        else:
            return NotImplemented

    def __radd__(self, other):
        if isinstance(other, MyIntegral):
            return do_my_adding_stuff(other, self)
        elif isinstance(other, OtherTypeIKnowAbout):
            return do_my_other_adding_stuff(other, self)
        elif isinstance(other, Integral):
            return int(other) + int(self)
        elif isinstance(other, Real):
            return float(other) + float(self)
        elif isinstance(other, Complex):
            return complex(other) + complex(self)
        else:
            return NotImplemented
@end example

ここには5つの異なる @ref{25fc,,Complex} のサブクラス間の混在型の演算があります。上のコードの中で @code{MyIntegral} と @code{OtherTypeIKnowAbout} に触れない部分を "ボイラープレート" と呼ぶことにしましょう。 @code{a} を @ref{25fc,,Complex} のサブタイプである @code{A} のインスタンス (@code{a : A <: Complex})、同様に @code{b : B <: Complex} として、 @code{a + b} を考えます:


@enumerate 

@item 
If @code{A} defines an @ref{23dd,,__add__()} which accepts @code{b}, all is
well.

@item 
If @code{A} falls back to the boilerplate code, and it were to
return a value from @ref{23dd,,__add__()}, we'd miss the possibility
that @code{B} defines a more intelligent @ref{23de,,__radd__()}, so the
boilerplate should return @ref{1a2,,NotImplemented} from
@code{__add__()}. (Or @code{A} may not implement @code{__add__()} at
all.)

@item 
Then @code{B}'s @ref{23de,,__radd__()} gets a chance. If it accepts
@code{a}, all is well.

@item 
ここでボイラープレートに落ち込むならば、もう他に試すべきメソッドはありませんので、デフォルト実装の出番です。

@item 
もし @code{B <: A} ならば、Python は @code{A.__add__} の前に @code{B.__radd__} を試します。これで良い理由は、 @code{A} についての知識を持って実装しており、 @ref{25fc,,Complex} に委ねる前にこれらのインスタンスを扱えるはずだからです。
@end enumerate

If @code{A <: Complex} and @code{B <: Real} without sharing any other knowledge,
then the appropriate shared operation is the one involving the built
in @ref{197,,complex}, and both @ref{23de,,__radd__()} s land there, so @code{a+b
== b+a}.

ほとんどの演算はどのような型についても非常に良く似ていますので、与えられた演算子について順結合(forward)および逆結合(reverse)のメソッドを生成する支援関数を定義することは役に立ちます。たとえば、 @ref{213,,fractions.Fraction} では次のようなものを利用しています:

@example
def _operator_fallbacks(monomorphic_operator, fallback_operator):
    def forward(a, b):
        if isinstance(b, (int, Fraction)):
            return monomorphic_operator(a, b)
        elif isinstance(b, float):
            return fallback_operator(float(a), b)
        elif isinstance(b, complex):
            return fallback_operator(complex(a), b)
        else:
            return NotImplemented
    forward.__name__ = '__' + fallback_operator.__name__ + '__'
    forward.__doc__ = monomorphic_operator.__doc__

    def reverse(b, a):
        if isinstance(a, Rational):
            # Includes ints.
            return monomorphic_operator(a, b)
        elif isinstance(a, Real):
            return fallback_operator(float(a), float(b))
        elif isinstance(a, Complex):
            return fallback_operator(complex(a), complex(b))
        else:
            return NotImplemented
    reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
    reverse.__doc__ = monomorphic_operator.__doc__

    return forward, reverse

def _add(a, b):
    """a + b"""
    return Fraction(a.numerator * b.denominator +
                    b.numerator * a.denominator,
                    a.denominator * b.denominator)

__add__, __radd__ = _operator_fallbacks(_add, operator.add)

# ...
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node math --- 数学関数,cmath --- 複素数用の数学関数,numbers --- 数の抽象基底クラス,数値と数学モジュール
@anchor{library/math doc}@anchor{2a71}@anchor{library/math math-mathematical-functions}@anchor{2a72}@anchor{library/math module-math}@anchor{92}@anchor{library/math translation-repo}@anchor{2a73}
@subsection @code{math} --- 数学関数


@geindex module; math

@c from math import fsum


__________________________________________________________________


This module provides access to common mathematical functions and constants,
including those defined by the C standard.

これらの関数で複素数を使うことはできません。複素数に対応する必要があるならば、 @ref{19,,cmath} モジュールにある同じ名前の関数を使ってください。ほとんどのユーザーは複素数を理解するのに必要なだけの数学を勉強したくないので、複素数に対応した関数と対応していない関数の区別がされています。これらの関数では複素数が利用できないため、引数に複素数を渡されると、複素数の結果が返るのではなく例外が発生します。その結果、どういった理由で例外が送出されたかに早い段階で気づく事ができます。

このモジュールでは次の関数を提供しています。明示的な注記のない限り、戻り値は全て浮動小数点数になります。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

`Number-theoretic functions'

@tab

@item

@ref{8df,,comb(n@comma{} k)}

@tab

Number of ways to choose `k' items from `n' items without repetition and without order

@item

@ref{b41,,factorial(n)}

@tab

`n' の階乗

@item

@ref{b0c,,gcd(*integers)}

@tab

整数引数の最大公約数

@item

@ref{bf8,,isqrt(n)}

@tab

Integer square root of a nonnegative integer `n'

@item

@ref{b0d,,lcm(*integers)}

@tab

Least common multiple of the integer arguments

@item

@ref{8e0,,perm(n@comma{} k)}

@tab

Number of ways to choose `k' items from `n' items without repetition and with order

@item

`Floating point arithmetic'

@tab

@item

@ref{15d8,,ceil(x)}

@tab

Ceiling of `x', the smallest integer greater than or equal to `x'

@item

@ref{2a74,,fabs(x)}

@tab

`x' の絶対値

@item

@ref{15d7,,floor(x)}

@tab

Floor of `x', the largest integer less than or equal to `x'

@item

@ref{514,,fma(x@comma{} y@comma{} z)}

@tab

Fused multiply-add operation: @code{(x * y) + z}

@item

@ref{24c8,,fmod(x@comma{} y)}

@tab

@code{x / y} の剰余

@item

@ref{2a75,,modf(x)}

@tab

Fractional and integer parts of `x'

@item

@ref{d4a,,remainder(x@comma{} y)}

@tab

Remainder of `x' with respect to `y'

@item

@ref{15d9,,trunc(x)}

@tab

`x' の整数部

@item

`Floating point manipulation functions'

@tab

@item

@ref{15ec,,copysign(x@comma{} y)}

@tab

Magnitude (absolute value) of `x' with the sign of `y'

@item

@ref{2a76,,frexp(x)}

@tab

Mantissa and exponent of `x'

@item

@ref{fb0,,isclose(a@comma{} b@comma{} rel_tol@comma{} abs_tol)}

@tab

Check if the values `a' and `b' are close to each other

@item

@ref{1404,,isfinite(x)}

@tab

Check if `x' is neither an infinity nor a NaN

@item

@ref{15ea,,isinf(x)}

@tab

Check if `x' is a positive or negative infinity

@item

@ref{15eb,,isnan(x)}

@tab

Check if `x' is a NaN  (not a number)

@item

@ref{1840,,ldexp(x@comma{} i)}

@tab

@code{x * (2**i)}, inverse of function @ref{2a76,,frexp()}

@item

@ref{6c0,,nextafter(x@comma{} y@comma{} steps)}

@tab

Floating-point value `steps' steps after `x' towards `y'

@item

@ref{b0e,,ulp(x)}

@tab

Value of the least significant bit of `x'

@item

`Power, exponential and logarithmic functions'

@tab

@item

@ref{871,,cbrt(x)}

@tab

`x' の立方根

@item

@ref{152b,,exp(x)}

@tab

`e' raised to the power `x'

@item

@ref{870,,exp2(x)}

@tab

`2' raised to the power `x'

@item

@ref{1405,,expm1(x)}

@tab

`e' raised to the power `x', minus 1

@item

@ref{16d9,,log(x@comma{} base)}

@tab

Logarithm of `x' to the given base (`e' by default)

@item

@ref{15f1,,log1p(x)}

@tab

Natural logarithm of `1+x' (base `e')

@item

@ref{12f3,,log2(x)}

@tab

2を底とする `x' の対数

@item

@ref{1948,,log10(x)}

@tab

10を底とする `x' の対数

@item

@ref{872,,pow(x@comma{} y)}

@tab

`x' の `y' 乗

@item

@ref{bf9,,sqrt(x)}

@tab

`x' の平方根

@item

`Summation and product functions'

@tab

@item

@ref{bf5,,dist(p@comma{} q)}

@tab

Euclidean distance between two points `p' and `q' given as an iterable of coordinates

@item

@ref{15ed,,fsum(iterable)}

@tab

Sum of values in the input `iterable'

@item

@ref{bf6,,hypot(*coordinates)}

@tab

Euclidean norm of an iterable of coordinates

@item

@ref{bf7,,prod(iterable@comma{} start)}

@tab

Product of elements in the input `iterable' with a `start' value

@item

@ref{6bf,,sumprod(p@comma{} q)}

@tab

Sum of products from two iterables `p' and `q'

@item

`Angular conversion'

@tab

@item

@ref{2a77,,degrees(x)}

@tab

Convert angle `x' from radians to degrees

@item

@ref{2a78,,radians(x)}

@tab

Convert angle `x' from degrees to radians

@item

`Trigonometric functions'

@tab

@item

@ref{2a79,,acos(x)}

@tab

`x' の逆余弦

@item

@ref{2a7a,,asin(x)}

@tab

`x' の逆正弦

@item

@ref{2a7b,,atan(x)}

@tab

`x' の逆正接

@item

@ref{2a7c,,atan2(y@comma{} x)}

@tab

@code{atan(y / x)}

@item

@ref{16d8,,cos(x)}

@tab

`x' の余弦

@item

@ref{16d7,,sin(x)}

@tab

`x' の正弦

@item

@ref{2a7d,,tan(x)}

@tab

`x' の正接

@item

`Hyperbolic functions'

@tab

@item

@ref{15ee,,acosh(x)}

@tab

Inverse hyperbolic cosine of `x'

@item

@ref{15ef,,asinh(x)}

@tab

Inverse hyperbolic sine of `x'

@item

@ref{15f0,,atanh(x)}

@tab

Inverse hyperbolic tangent of `x'

@item

@ref{2a7e,,cosh(x)}

@tab

Hyperbolic cosine of `x'

@item

@ref{2a7f,,sinh(x)}

@tab

Hyperbolic sine of `x'

@item

@ref{2a80,,tanh(x)}

@tab

Hyperbolic tangent of `x'

@item

`Special functions'

@tab

@item

@ref{dd3,,erf(x)}

@tab

Error function@footnote{https://en.wikipedia.org/wiki/Error_function} at `x'

@item

@ref{dd4,,erfc(x)}

@tab

Complementary error function@footnote{https://en.wikipedia.org/wiki/Error_function} at `x'

@item

@ref{1406,,gamma(x)}

@tab

Gamma function@footnote{https://en.wikipedia.org/wiki/Gamma_function} at `x'

@item

@ref{1407,,lgamma(x)}

@tab

Natural logarithm of the absolute value of the Gamma function@footnote{https://en.wikipedia.org/wiki/Gamma_function} at `x'

@item

`定数'

@tab

@item

@ref{2a81,,pi}

@tab

`π' = 3.141592...

@item

@ref{2a82,,e}

@tab

`e' = 2.718281...

@item

@ref{2a83,,tau}

@tab

`τ' = 2`π' = 6.283185...

@item

@ref{e7e,,inf}

@tab

正の無限大

@item

@ref{873,,nan}

@tab

非数 "Not a number" (NaN)

@end multitable


@menu
* Number-theoretic functions:: 
* Floating point arithmetic:: 
* Floating point manipulation functions:: 
* Power@comma{} exponential and logarithmic functions: Power exponential and logarithmic functions. 
* Summation and product functions:: 
* 角度変換:: 
* 三角関数:: 
* 双曲線関数:: 
* 特殊関数:: 
* 定数: 定数<2>. 

@end menu

@node Number-theoretic functions,Floating point arithmetic,,math --- 数学関数
@anchor{library/math number-theoretic-functions}@anchor{2a84}
@subsubsection Number-theoretic functions


@geindex comb() (math モジュール)
@anchor{library/math math comb}@anchor{8df}
@deffn {の関数} math.comb (n, k)

`n' 個の中から `k' 個を重複無く順序をつけずに選ぶ方法の数を返します。

@code{k <= n} のとき @code{n! / (k! * (n - k)!)} と評価し、@code{k > n} のとき 0 と評価します。

これは @code{(1 + x)ⁿ} の多項式展開における第 k 項の係数と等しいので、二項係数とも呼ばれます。

いずれかの引数が整数でないなら @ref{198,,TypeError} を送出します。いずれかの引数が負であれば @ref{2ec,,ValueError} を送出します。


Added in version 3.8.

@end deffn

@geindex factorial() (math モジュール)
@anchor{library/math math factorial}@anchor{b41}
@deffn {の関数} math.factorial (n)

Return factorial of the nonnegative integer `n'.


バージョン 3.10 で変更: Floats with integral values (like @code{5.0}) are no longer accepted.

@end deffn

@geindex gcd() (math モジュール)
@anchor{library/math math gcd}@anchor{b0c}
@deffn {の関数} math.gcd (*integers)

指定された整数引数の最大公約数を返します。0 でない引数があれば、返される値は全ての引数の約数である最大の正の整数です。全ての引数が 0 なら、返される値は @code{0} です。引数の無い @code{gcd()} は @code{0} を返します。


Added in version 3.5.



バージョン 3.9 で変更: 任意の数の引数のサポートが追加されました。以前は、二つの引数のみがサポートされていました。

@end deffn

@geindex isqrt() (math モジュール)
@anchor{library/math math isqrt}@anchor{bf8}
@deffn {の関数} math.isqrt (n)

非負整数 `n' の整数平方根を返します。これは `n' の正確な平方根の床であり、 `a'² ≤ `n' を満たす最大の整数 `a' と等価です。

少し応用すれば、`n' ≤ `a'² を満たす最小の整数 `a' 、言い換えれば `n' の正確な平方根の天井を効率的に得られます。正の `n' に対して、これは @code{a = 1 + isqrt(n - 1)} を使って計算できます。


Added in version 3.8.

@end deffn

@geindex lcm() (math モジュール)
@anchor{library/math math lcm}@anchor{b0d}
@deffn {の関数} math.lcm (*integers)

指定された整数引数の最小公倍数を返します。全ての引数が 0 でなければ、返される値は全ての引数の倍数である最小の正の整数です。引数に 0 があれば、返される値は @code{0} です。引数の無い @code{lcm()} は @code{1} を返します。


Added in version 3.9.

@end deffn

@geindex perm() (math モジュール)
@anchor{library/math math perm}@anchor{8e0}
@deffn {の関数} math.perm (n, k=None)

`n' 個の中から `k' 個を重複無く順序をつけて選ぶ方法の数を返します。

@code{k <= n} のとき @code{n! / (n - k)!} と評価し、@code{k > n} のとき 0 と評価します。

If `k' is not specified or is @code{None}, then `k' defaults to `n'
and the function returns @code{n!}.

いずれかの引数が整数でないなら @ref{198,,TypeError} を送出します。いずれかの引数が負であれば @ref{2ec,,ValueError} を送出します。


Added in version 3.8.

@end deffn

@node Floating point arithmetic,Floating point manipulation functions,Number-theoretic functions,math --- 数学関数
@anchor{library/math floating-point-arithmetic}@anchor{2a85}
@subsubsection Floating point arithmetic


@geindex ceil() (math モジュール)
@anchor{library/math math ceil}@anchor{15d8}
@deffn {の関数} math.ceil (x)

`x' の「天井」 (`x' 以上の最小の整数) を返します。 `x' が浮動小数点数でなければ、内部的に @ref{2409,,x.__ceil__} が実行され、 @ref{240a,,Integral} 値が返されます。
@end deffn

@geindex fabs() (math モジュール)
@anchor{library/math math fabs}@anchor{2a74}
@deffn {の関数} math.fabs (x)

`x' の絶対値を返します。
@end deffn

@geindex floor() (math モジュール)
@anchor{library/math math floor}@anchor{15d7}
@deffn {の関数} math.floor (x)

`x' の「床」 (`x' 以下の最大の整数) を返します。 `x' が浮動小数点数でなければ、内部的に @ref{2408,,x.__floor__} が実行され、 @ref{240a,,Integral} 値が返されます。
@end deffn

@geindex fma() (math モジュール)
@anchor{library/math math fma}@anchor{514}
@deffn {の関数} math.fma (x, y, z)

Fused multiply-add operation. Return @code{(x * y) + z}, computed as though with
infinite precision and range followed by a single round to the @code{float}
format. This operation often provides better accuracy than the direct
expression @code{(x * y) + z}.

This function follows the specification of the fusedMultiplyAdd operation
described in the IEEE 754 standard. The standard leaves one case
implementation-defined, namely the result of @code{fma(0, inf, nan)}
and @code{fma(inf, 0, nan)}. In these cases, @code{math.fma} returns a NaN,
and does not raise any exception.


Added in version 3.13.

@end deffn

@geindex fmod() (math モジュール)
@anchor{library/math math fmod}@anchor{24c8}
@deffn {の関数} math.fmod (x, y)

Return the floating-point remainder of @code{x / y},
as defined by the platform C library function @code{fmod(x, y)}. Note that the
Python expression @code{x % y} may not return the same result.  The intent of the C
standard is that @code{fmod(x, y)} be exactly (mathematically; to infinite
precision) equal to @code{x - n*y} for some integer `n' such that the result has
the same sign as `x' and magnitude less than @code{abs(y)}.  Python's @code{x % y}
returns a result with the sign of `y' instead, and may not be exactly computable
for float arguments. For example, @code{fmod(-1e-100, 1e100)} is @code{-1e-100}, but
the result of Python's @code{-1e-100 % 1e100} is @code{1e100-1e-100}, which cannot be
represented exactly as a float, and rounds to the surprising @code{1e100}.  For
this reason, function @ref{24c8,,fmod()} is generally preferred when working with
floats, while Python's @code{x % y} is preferred when working with integers.
@end deffn

@geindex modf() (math モジュール)
@anchor{library/math math modf}@anchor{2a75}
@deffn {の関数} math.modf (x)

`x' の小数部分と整数部分を返します。両方の結果は `x' の符号を受け継ぎます。整数部はfloat型で返されます。

Note that @ref{2a75,,modf()} has a different call/return pattern
than its C equivalents: it takes a single argument and return a pair of
values, rather than returning its second return value through an 'output
parameter' (there is no such thing in Python).
@end deffn

@geindex remainder() (math モジュール)
@anchor{library/math math remainder}@anchor{d4a}
@deffn {の関数} math.remainder (x, y)

IEEE 754 標準方式の `x' を `y' で割った剰余を返します。
有限な `x' と有限な `y' では、分数 @code{x / y} の厳密な値に最も近い整数を @code{n} として、 @code{x - n*y} がこの返り値となります。
@code{x / y} が隣り合う 2 つの整数のちょうど真ん中だった場合は、最も近い `偶数' が @code{n} として使われます。
従って、剰余 @code{r = remainder(x, y)} は常に @code{abs(r) <= 0.5 * abs(y)} を満たします。

特殊なケースについては IEEE 754 に従います: 任意の有限な `x' に対する @code{remainder(x, math.inf)} 、および任意の非 NaN の `x' に対する @code{remainder(x, 0)} と @code{remainder(math.inf, x)} は @ref{2ec,,ValueError} を送出します。
剰余演算の結果がゼロの場合、そのゼロは `x' と同じ符号を持ちます。

On platforms using IEEE 754 binary floating point, the result of this
operation is always exactly representable: no rounding error is introduced.


Added in version 3.7.

@end deffn

@geindex trunc() (math モジュール)
@anchor{library/math math trunc}@anchor{15d9}
@deffn {の関数} math.trunc (x)

`x' の小数部を取り除き、残った整数部を返します。これは 0 に向かって丸められます: @code{trunc()} は正の `x' に対しては @ref{15d7,,floor()} に等しく、負の `x' に対しては @ref{15d8,,ceil()} に等しいです。`x' が浮動小数点数でなければ、内部的に @ref{19c,,x.__trunc__} が実行され、 @ref{240a,,Integral} 値が返されます。
@end deffn

@ref{15d8,,ceil()} 、 @ref{15d7,,floor()} 、および @ref{2a75,,modf()} 関数については、非常に大きな浮動小数点数が `全て' 整数そのものになるということに注意してください。通常、Python の浮動小数点型は 53 ビット以上の精度をもたない (プラットフォームにおける C double 型と同じ) ので、結果的に @code{abs(x) >= 2**52} であるような浮動小数点型 `x' は小数部分を持たなくなるのです。

@node Floating point manipulation functions,Power exponential and logarithmic functions,Floating point arithmetic,math --- 数学関数
@anchor{library/math floating-point-manipulation-functions}@anchor{2a86}
@subsubsection Floating point manipulation functions


@geindex copysign() (math モジュール)
@anchor{library/math math copysign}@anchor{15ec}
@deffn {の関数} math.copysign (x, y)

`x' の大きさ (絶対値) で `y' と同じ符号の浮動小数点数を返します。符号付きのゼロをサポートしているプラットフォームでは、@code{copysign(1.0, -0.0)} は `-1.0' を返します。
@end deffn

@geindex frexp() (math モジュール)
@anchor{library/math math frexp}@anchor{2a76}
@deffn {の関数} math.frexp (x)

`x' の仮数と指数を @code{(m, e)} のペアとして返します。`m' はfloat型で、`e' は厳密に @code{x == m * 2**e} であるような整数型です。`x' がゼロの場合は、@code{(0.0, 0)} を返し、それ以外の場合は、@code{0.5 <= abs(m) < 1} です。これは浮動小数点型の内部表現を可搬性を保ったまま "分解 (pick apart)" するために使われます。

Note that @ref{2a76,,frexp()} has a different call/return pattern
than its C equivalents: it takes a single argument and return a pair of
values, rather than returning its second return value through an 'output
parameter' (there is no such thing in Python).
@end deffn

@geindex isclose() (math モジュール)
@anchor{library/math math isclose}@anchor{fb0}
@deffn {の関数} math.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

値 `a' と `b' が互いに近い場合 @code{True} を、そうでない場合は @code{False} を返します。

Whether or not two values are considered close is determined according to
given absolute and relative tolerances.  If no errors occur, the result will
be: @code{abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)}.

`rel_tol' is the relative tolerance -- it is the maximum allowed difference
between `a' and `b', relative to the larger absolute value of `a' or `b'.
For example, to set a tolerance of 5%, pass @code{rel_tol=0.05}.  The default
tolerance is @code{1e-09}, which assures that the two values are the same
within about 9 decimal digits.  `rel_tol' must be nonnegative and less
than @code{1.0}.

`abs_tol' is the absolute tolerance; it defaults to @code{0.0} and it must be
nonnegative.  When comparing @code{x} to @code{0.0}, @code{isclose(x, 0)} is computed
as @code{abs(x) <= rel_tol  * abs(x)}, which is @code{False} for any nonzero @code{x} and
`rel_tol' less than @code{1.0}.  So add an appropriate positive `abs_tol' argument
to the call.

IEEE 754 特殊値 @code{NaN}、@code{inf}、@code{-inf} は IEEE の規則に従って処理されます。
具体的には、@code{NaN} は自身を含めたあらゆる値に近いとは見なされません。
@code{inf} と @code{-inf} は自身とのみ近いと見なされます。


Added in version 3.5.



@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 485
PEP 485@footnote{https://peps.python.org/pep-0485/} -- A function for testing approximate equality

@end deffn

@geindex isfinite() (math モジュール)
@anchor{library/math math isfinite}@anchor{1404}
@deffn {の関数} math.isfinite (x)

`x' が無限でも NaN でもない場合に @code{True} を返します。それ以外の時には @code{False} を返します。 (注意: @code{0.0} は有限数と扱われます。)


Added in version 3.2.

@end deffn

@geindex isinf() (math モジュール)
@anchor{library/math math isinf}@anchor{15ea}
@deffn {の関数} math.isinf (x)

`x' が正ないし負の無限数ならば @code{True} を返します。それ以外の時には @code{False} を返します。
@end deffn

@geindex isnan() (math モジュール)
@anchor{library/math math isnan}@anchor{15eb}
@deffn {の関数} math.isnan (x)

`x' がNaN (not a number、非数) の時に @code{True} を返します。それ以外の場合には @code{False} を返します。
@end deffn

@geindex ldexp() (math モジュール)
@anchor{library/math math ldexp}@anchor{1840}
@deffn {の関数} math.ldexp (x, i)

@code{x * (2**i)} を返します。これは本質的に @ref{2a76,,frexp()} の逆関数です。
@end deffn

@geindex nextafter() (math モジュール)
@anchor{library/math math nextafter}@anchor{6c0}
@deffn {の関数} math.nextafter (x, y, steps=1)

Return the floating-point value `steps' steps after `x' towards `y'.

If `x' is equal to `y', return `y', unless `steps' is zero.

例:


@itemize *

@item 
@code{math.nextafter(x, math.inf)} goes up: towards positive infinity.

@item 
@code{math.nextafter(x, -math.inf)} goes down: towards minus infinity.

@item 
@code{math.nextafter(x, 0.0)} は 0 に近づきます。

@item 
@code{math.nextafter(x, math.copysign(math.inf, x))} は 0 から遠ざかります。
@end itemize

@ref{b0e,,math.ulp()} を参照してください。


Added in version 3.9.



バージョン 3.12 で変更: Added the `steps' argument.

@end deffn

@geindex ulp() (math モジュール)
@anchor{library/math math ulp}@anchor{b0e}
@deffn {の関数} math.ulp (x)

浮動小数点数 `x' の最下位ビットの値を返します:


@itemize *

@item 
`x' が NaN (非数) なら、`x' を返します。

@item 
`x' が負なら、@code{ulp(-x)} を返します。

@item 
`x' が正の無限大なら、`x' を返します。

@item 
`x' が 0 に等しければ、(最小の正の `正規化' 浮動小数点数 @ref{1dcf,,sys.float_info.min} よりも小さい) 最小の正の表現可能な `非正規化' 浮動小数点数を返します。

@item 
`x' が表現可能な最大の正の浮動小数点数に等しいなら、`x' より小さい最初の浮動小数点数が @code{x - ulp(x)} であるような、`x' の最下位ビットの値を返します。

@item 
それ以外 (`x' が正の有限な数) なら、`x' より大きい最初の浮動小数点数が @code{x + ulp(x)} であるような、`x' の最下位ビットの値を返します。
@end itemize

ULP は "Unit in the Last Place" の略です。

@ref{6c0,,math.nextafter()} および @ref{1dcf,,sys.float_info.epsilon} も参照してください。


Added in version 3.9.

@end deffn

@node Power exponential and logarithmic functions,Summation and product functions,Floating point manipulation functions,math --- 数学関数
@anchor{library/math power-exponential-and-logarithmic-functions}@anchor{2a87}
@subsubsection Power, exponential and logarithmic functions


@geindex cbrt() (math モジュール)
@anchor{library/math math cbrt}@anchor{871}
@deffn {の関数} math.cbrt (x)

`x' の立方根を返します。


Added in version 3.11.

@end deffn

@geindex exp() (math モジュール)
@anchor{library/math math exp}@anchor{152b}
@deffn {の関数} math.exp (x)

`e' = 2.718281... を自然対数の底として、 `e' の `x' 乗を返します。
この値は、通常は @code{math.e ** x} や @code{pow(math.e, x)} よりも精度が高いです。
@end deffn

@geindex exp2() (math モジュール)
@anchor{library/math math exp2}@anchor{870}
@deffn {の関数} math.exp2 (x)

`2' の `x' 乗を返します。


Added in version 3.11.

@end deffn

@geindex expm1() (math モジュール)
@anchor{library/math math expm1}@anchor{1405}
@deffn {の関数} math.expm1 (x)

Return `e' raised to the power `x', minus 1.  Here `e' is the base of natural
logarithms.  For small floats `x', the subtraction in @code{exp(x) - 1}
can result in a significant loss of precision@footnote{https://en.wikipedia.org/wiki/Loss_of_significance}; the @ref{1405,,expm1()}
function provides a way to compute this quantity to full precision:

@example
>>> from math import exp, expm1
>>> exp(1e-5) - 1  # gives result accurate to 11 places
1.0000050000069649e-05
>>> expm1(1e-5)    # result accurate to full precision
1.0000050000166668e-05
@end example


Added in version 3.2.

@end deffn

@geindex log() (math モジュール)
@anchor{library/math math log}@anchor{16d9}
@deffn {の関数} math.log (x[, base])

引数が1つの場合、`x' の (`e' を底とする)自然対数を返します。

引数が2つの場合、@code{log(x)/log(base)} として求められる `base' を底とした `x' の対数を返します。
@end deffn

@geindex log1p() (math モジュール)
@anchor{library/math math log1p}@anchor{15f1}
@deffn {の関数} math.log1p (x)

`1+x' の自然対数(つまり底 `e' の対数)を返します。結果はゼロに近い `x' に対して正確になるような方法で計算されます。
@end deffn

@geindex log2() (math モジュール)
@anchor{library/math math log2}@anchor{12f3}
@deffn {の関数} math.log2 (x)

2を底とする `x' の対数を返します。この関数は、一般に @code{log(x, 2)} よりも正確な値を返します。


Added in version 3.3.



@subsubheading 参考


@ref{25f6,,int.bit_length()} は、その整数を二進法で表すのに何ビット必要かを返す関数です。符号と先頭のゼロは無視されます。

@end deffn

@geindex log10() (math モジュール)
@anchor{library/math math log10}@anchor{1948}
@deffn {の関数} math.log10 (x)

`x' の10を底とした対数(常用対数)を返します。この関数は通常、@code{log(x, 10)} よりも高精度です。
@end deffn

@geindex pow() (math モジュール)
@anchor{library/math math pow}@anchor{872}
@deffn {の関数} math.pow (x, y)

Return `x' raised to the power `y'.  Exceptional cases follow
the IEEE 754 standard as far as possible.  In particular,
@code{pow(1.0, x)} and @code{pow(x, 0.0)} always return @code{1.0}, even
when `x' is a zero or a NaN.  If both `x' and `y' are finite,
`x' is negative, and `y' is not an integer then @code{pow(x, y)}
is undefined, and raises @ref{2ec,,ValueError}.

組み込みの @code{**} 演算子と違って、 @ref{872,,math.pow()} は両方の引数を @ref{196,,float} 型に変換します。正確な整数の冪乗を計算するには @code{**} もしくは組み込みの @ref{1a4,,pow()} 関数を使ってください。


バージョン 3.11 で変更: IEEE 754 との一貫性のため、特殊な例である @code{pow(0.0, -inf)} および @code{pow(-0.0, -inf)} は @ref{2ec,,ValueError} を送出する代わりに @code{inf} を返すように変更されました。

@end deffn

@geindex sqrt() (math モジュール)
@anchor{library/math math sqrt}@anchor{bf9}
@deffn {の関数} math.sqrt (x)

`x' の平方根を返します。
@end deffn

@node Summation and product functions,角度変換,Power exponential and logarithmic functions,math --- 数学関数
@anchor{library/math summation-and-product-functions}@anchor{2a88}
@subsubsection Summation and product functions


@geindex dist() (math モジュール)
@anchor{library/math math dist}@anchor{bf5}
@deffn {の関数} math.dist (p, q)

それぞれ座標のシーケンス (またはイテラブル) として与えられる点 `p' と `q' の間のユークリッド距離を返します。二点の次元は同じでなければなりません。

およそ次と等価です:

@example
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
@end example


Added in version 3.8.

@end deffn

@geindex fsum() (math モジュール)
@anchor{library/math math fsum}@anchor{15ed}
@deffn {の関数} math.fsum (iterable)

Return an accurate floating-point sum of values in the iterable.  Avoids
loss of precision by tracking multiple intermediate partial sums.

アルゴリズムの正確性は、 IEEE-754 演算の保証と、丸めモードが偶数丸め (half-even) である典型的な場合に依存します。Windows 以外のいくつかのビルドでは、下層の C ライブラリが拡張精度の加算を行い、時々計算途中の和を double 型へ丸めてしまうため、最下位ビットが消失することがあります。

For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floating-point summation@footnote{https://code.activestate.com/recipes/393090-binary-floating-point-summation-accurate-to-full-p/}.
@end deffn

@geindex hypot() (math モジュール)
@anchor{library/math math hypot}@anchor{bf6}
@deffn {の関数} math.hypot (*coordinates)

ユークリッドノルム @code{sqrt(sum(x**2 for x in coordinates))} を返します。これは原点から座標で与えられる点までのベクトルの長さです。

二次元の点 @code{(x, y)} では、これは直角三角形の斜辺をピタゴラスの定理 @code{sqrt(x*x + y*y)} を用いて計算することと等価です。


バージョン 3.8 で変更: n 次元の点のサポートが追加されました。以前は、二次元の場合しかサポートされていませんでした。



バージョン 3.10 で変更: アルゴリズムの精度を改良し、最大の誤差が 1 ulp (最終桁単位) 未満になりました。より一般的には、結果はほとんどの場合に 1/2 ulp 以内に正しく丸められます。

@end deffn

@geindex prod() (math モジュール)
@anchor{library/math math prod}@anchor{bf7}
@deffn {の関数} math.prod (iterable, *, start=1)

入力 `iterable' の全ての要素の積を計算します。積のデフォルト `start' 値は @code{1} です。

イテラブルが空のとき、初期値を返します。この関数は特に数値に使うことを意図されており、非数値を受け付けないことがあります。


Added in version 3.8.

@end deffn

@geindex sumprod() (math モジュール)
@anchor{library/math math sumprod}@anchor{6bf}
@deffn {の関数} math.sumprod (p, q)

Return the sum of products of values from two iterables `p' and `q'.

Raises @ref{2ec,,ValueError} if the inputs do not have the same length.

およそ次と等価です:

@example
sum(map(operator.mul, p, q, strict=True))
@end example

For float and mixed int/float inputs, the intermediate products
and sums are computed with extended precision.


Added in version 3.12.

@end deffn

@node 角度変換,三角関数,Summation and product functions,math --- 数学関数
@anchor{library/math angular-conversion}@anchor{2a89}
@subsubsection 角度変換


@geindex degrees() (math モジュール)
@anchor{library/math math degrees}@anchor{2a77}
@deffn {の関数} math.degrees (x)

角 `x' をラジアンから度に変換します。
@end deffn

@geindex radians() (math モジュール)
@anchor{library/math math radians}@anchor{2a78}
@deffn {の関数} math.radians (x)

角 `x' を度からラジアンに変換します。
@end deffn

@node 三角関数,双曲線関数,角度変換,math --- 数学関数
@anchor{library/math trigonometric-functions}@anchor{2a8a}
@subsubsection 三角関数


@geindex acos() (math モジュール)
@anchor{library/math math acos}@anchor{2a79}
@deffn {の関数} math.acos (x)

`x' の逆余弦を、ラジアンで返します。結果は @code{0} と @code{pi} の間です。
@end deffn

@geindex asin() (math モジュール)
@anchor{library/math math asin}@anchor{2a7a}
@deffn {の関数} math.asin (x)

`x' の逆正弦を、ラジアンで返します。結果は @code{-pi/2} と @code{pi/2} の間です。
@end deffn

@geindex atan() (math モジュール)
@anchor{library/math math atan}@anchor{2a7b}
@deffn {の関数} math.atan (x)

`x' の逆正接を、ラジアンで返します。結果は @code{-pi/2} と @code{pi/2} の間です。
@end deffn

@geindex atan2() (math モジュール)
@anchor{library/math math atan2}@anchor{2a7c}
@deffn {の関数} math.atan2 (y, x)

@code{atan(y / x)} を、ラジアンで返します。戻り値は @code{-pi} から @code{pi} の間になります。この角度は、極座標平面において原点から @code{(x, y)} へのベクトルが X 軸の正の方向となす角です。 @ref{2a7c,,atan2()} のポイントは、両方の入力の符号が既知であるために、位相角の正しい象限を計算できることにあります。例えば、 @code{atan(1)} と @code{atan2(1, 1)} はいずれも @code{pi/4} ですが、 @code{atan2(-1, -1)} は @code{-3*pi/4} になります。
@end deffn

@geindex cos() (math モジュール)
@anchor{library/math math cos}@anchor{16d8}
@deffn {の関数} math.cos (x)

`x' ラジアンの余弦を返します。
@end deffn

@geindex sin() (math モジュール)
@anchor{library/math math sin}@anchor{16d7}
@deffn {の関数} math.sin (x)

`x' ラジアンの正弦を返します。
@end deffn

@geindex tan() (math モジュール)
@anchor{library/math math tan}@anchor{2a7d}
@deffn {の関数} math.tan (x)

`x' ラジアンの正接を返します。
@end deffn

@node 双曲線関数,特殊関数,三角関数,math --- 数学関数
@anchor{library/math hyperbolic-functions}@anchor{2a8b}
@subsubsection 双曲線関数


Hyperbolic functions@footnote{https://en.wikipedia.org/wiki/Hyperbolic_functions}
are analogs of trigonometric functions that are based on hyperbolas
instead of circles.

@geindex acosh() (math モジュール)
@anchor{library/math math acosh}@anchor{15ee}
@deffn {の関数} math.acosh (x)

`x' の逆双曲線余弦を返します。
@end deffn

@geindex asinh() (math モジュール)
@anchor{library/math math asinh}@anchor{15ef}
@deffn {の関数} math.asinh (x)

`x' の逆双曲線正弦を返します。
@end deffn

@geindex atanh() (math モジュール)
@anchor{library/math math atanh}@anchor{15f0}
@deffn {の関数} math.atanh (x)

`x' の逆双曲線正接を返します。
@end deffn

@geindex cosh() (math モジュール)
@anchor{library/math math cosh}@anchor{2a7e}
@deffn {の関数} math.cosh (x)

`x' の双曲線余弦を返します。
@end deffn

@geindex sinh() (math モジュール)
@anchor{library/math math sinh}@anchor{2a7f}
@deffn {の関数} math.sinh (x)

`x' の双曲線正弦を返します。
@end deffn

@geindex tanh() (math モジュール)
@anchor{library/math math tanh}@anchor{2a80}
@deffn {の関数} math.tanh (x)

`x' の双曲線正接を返します。
@end deffn

@node 特殊関数,定数<2>,双曲線関数,math --- 数学関数
@anchor{library/math special-functions}@anchor{2a8c}
@subsubsection 特殊関数


@geindex erf() (math モジュール)
@anchor{library/math math erf}@anchor{dd3}
@deffn {の関数} math.erf (x)

`x' の 誤差関数@footnote{https://ja.wikipedia.org/wiki/%E8%AA%A4%E5%B7%AE%E9%96%A2%E6%95%B0} を返します。

The @ref{dd3,,erf()} function can be used to compute traditional statistical
functions such as the cumulative standard normal distribution@footnote{https://en.wikipedia.org/wiki/Cumulative_distribution_function}:

@example
def phi(x):
    'Cumulative distribution function for the standard normal distribution'
    return (1.0 + erf(x / sqrt(2.0))) / 2.0
@end example


Added in version 3.2.

@end deffn

@geindex erfc() (math モジュール)
@anchor{library/math math erfc}@anchor{dd4}
@deffn {の関数} math.erfc (x)

`x' の相補誤差関数を返します。相補誤差関数@footnote{https://ja.wikipedia.org/wiki/%E8%AA%A4%E5%B7%AE%E9%96%A2%E6%95%B0} は @code{1.0 - erf(x)} と定義されます。この関数は、1からの引き算が 桁落ち@footnote{https://ja.wikipedia.org/wiki/%E8%AA%A4%E5%B7%AE#.E6.A1.81.E8.90.BD.E3.81.A1} をするような大きな `x' に対し使われます。


Added in version 3.2.

@end deffn

@geindex gamma() (math モジュール)
@anchor{library/math math gamma}@anchor{1406}
@deffn {の関数} math.gamma (x)

`x' の ガンマ関数@footnote{https://ja.wikipedia.org/wiki/%E3%82%AC%E3%83%B3%E3%83%9E%E9%96%A2%E6%95%B0} を返します。


Added in version 3.2.

@end deffn

@geindex lgamma() (math モジュール)
@anchor{library/math math lgamma}@anchor{1407}
@deffn {の関数} math.lgamma (x)

`x' のガンマ関数の絶対値の自然対数を返します。


Added in version 3.2.

@end deffn

@node 定数<2>,,特殊関数,math --- 数学関数
@anchor{library/math constants}@anchor{2a8d}
@subsubsection 定数


@geindex pi (math モジュール)
@anchor{library/math math pi}@anchor{2a81}
@deffn {データ} math.pi

利用可能なだけの精度の数学定数 `π' = 3.141592... (円周率)。
@end deffn

@geindex e (math モジュール)
@anchor{library/math math e}@anchor{2a82}
@deffn {データ} math.e

利用可能なだけの精度の数学定数 `e' = 2.718281... (自然対数の底)。
@end deffn

@geindex tau (math モジュール)
@anchor{library/math math tau}@anchor{2a83}
@deffn {データ} math.tau

The mathematical constant `τ' = 6.283185..., to available precision.
Tau is a circle constant equal to 2`π', the ratio of a circle's circumference to
its radius. To learn more about Tau, check out Vi Hart's video Pi is (still) Wrong@footnote{https://vimeo.com/147792667}, and start celebrating
Tau day@footnote{https://tauday.com/} by eating twice as much pie!


Added in version 3.6.

@end deffn

@geindex inf (math モジュール)
@anchor{library/math math inf}@anchor{e7e}
@deffn {データ} math.inf

浮動小数の正の無限大です。(負の無限大には @code{-math.inf} を使います。) @code{float('inf')} の出力と等価です。


Added in version 3.5.

@end deffn

@geindex nan (math モジュール)
@anchor{library/math math nan}@anchor{873}
@deffn {データ} math.nan

A floating-point "not a number" (NaN) value. Equivalent to the output of
@code{float('nan')}. Due to the requirements of the IEEE-754 standard@footnote{https://en.wikipedia.org/wiki/IEEE_754}, @code{math.nan} and @code{float('nan')} are
not considered to equal to any other numeric value, including themselves. To check
whether a number is a NaN, use the @ref{15eb,,isnan()} function to test
for NaNs instead of @code{is} or @code{==}.
Example:

@example
>>> import math
>>> math.nan == math.nan
False
>>> float('nan') == float('nan')
False
>>> math.isnan(math.nan)
True
>>> math.isnan(float('nan'))
True
@end example


Added in version 3.5.



バージョン 3.11 で変更: 常に利用出来るようになりました。

@end deffn

`CPython 実装の詳細:' The @code{math} module consists mostly of thin wrappers around the platform C
math library functions.  Behavior in exceptional cases follows Annex F of
the C99 standard where appropriate.  The current implementation will raise
@ref{2ec,,ValueError} for invalid operations like @code{sqrt(-1.0)} or @code{log(0.0)}
(where C99 Annex F recommends signaling invalid operation or divide-by-zero),
and @ref{a81,,OverflowError} for results that overflow (for example,
@code{exp(1000.0)}).  A NaN will not be returned from any of the functions
above unless one or more of the input arguments was a NaN; in that case,
most functions will return a NaN, but (again following C99 Annex F) there
are some exceptions to this rule, for example @code{pow(float('nan'), 0.0)} or
@code{hypot(float('nan'), float('inf'))}.

Python は signaling NaN と quiet NaN を区別せず、signaling NaN に対する挙動は未定義とされていることに注意してください。典型的な挙動は、全ての NaN を quiet NaN として扱うことです。


@subsubheading 参考



@table @asis

@item @ref{19,,cmath} モジュール

これらの多くの関数の複素数版。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node cmath --- 複素数用の数学関数,decimal --- 10進固定小数点と浮動小数点の演算,math --- 数学関数,数値と数学モジュール
@anchor{library/cmath doc}@anchor{2a8e}@anchor{library/cmath cmath-mathematical-functions-for-complex-numbers}@anchor{2a8f}@anchor{library/cmath module-cmath}@anchor{19}@anchor{library/cmath translation-repo}@anchor{2a90}
@subsection @code{cmath} --- 複素数用の数学関数


@geindex module; cmath


__________________________________________________________________


このモジュールは、複素数を扱う数学関数へのアクセスを提供しています。
このモジュール中の関数は整数、浮動小数点数または複素数を引数にとります。
また、 @ref{7fd,,__complex__()} または @ref{bc1,,__float__()} どちらかのメソッドを提供している Python オブジェクトも受け付けます。
これらのメソッドはそのオブジェクトを複素数または浮動小数点数に変換するのにそれぞれ使われ、呼び出された関数はそうして変換された結果を利用します。

@cartouche
@quotation 注釈 
For functions involving branch cuts, we have the problem of deciding how to
define those functions on the cut itself. Following Kahan's "Branch cuts for
complex elementary functions" paper, as well as Annex G of C99 and later C
standards, we use the sign of zero to distinguish one side of the branch cut
from the other: for a branch cut along (a portion of) the real axis we look
at the sign of the imaginary part, while for a branch cut along the
imaginary axis we look at the sign of the real part.

For example, the @ref{2a91,,cmath.sqrt()} function has a branch cut along the
negative real axis. An argument of @code{-2-0j} is treated as
though it lies `below' the branch cut, and so gives a result on the negative
imaginary axis:

@example
>>> cmath.sqrt(-2-0j)
-1.4142135623730951j
@end example

But an argument of @code{-2+0j} is treated as though it lies above
the branch cut:

@example
>>> cmath.sqrt(-2+0j)
1.4142135623730951j
@end example
@end quotation
@end cartouche


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

`Conversions to and from polar coordinates'

@tab

@item

@ref{2a92,,phase(z)}

@tab

Return the phase of `z'

@item

@ref{2a93,,polar(z)}

@tab

Return the representation of `z' in polar coordinates

@item

@ref{2a94,,rect(r@comma{} phi)}

@tab

Return the complex number `z' with polar coordinates `r' and `phi'

@item

`Power and logarithmic functions'

@tab

@item

@ref{2a95,,exp(z)}

@tab

Return `e' raised to the power `z'

@item

@ref{2a96,,log(z[@comma{} base])}

@tab

Return the logarithm of `z' to the given `base' (`e' by default)

@item

@ref{2a97,,log10(z)}

@tab

Return the base-10 logarithm of `z'

@item

@ref{2a91,,sqrt(z)}

@tab

Return the square root of `z'

@item

`Trigonometric functions'

@tab

@item

@ref{2a98,,acos(z)}

@tab

Return the arc cosine of `z'

@item

@ref{2a99,,asin(z)}

@tab

Return the arc sine of `z'

@item

@ref{2a9a,,atan(z)}

@tab

Return the arc tangent of `z'

@item

@ref{2a9b,,cos(z)}

@tab

Return the cosine of `z'

@item

@ref{2a9c,,sin(z)}

@tab

Return the sine of `z'

@item

@ref{2a9d,,tan(z)}

@tab

Return the tangent of `z'

@item

`Hyperbolic functions'

@tab

@item

@ref{2a9e,,acosh(z)}

@tab

Return the inverse hyperbolic cosine of `z'

@item

@ref{2a9f,,asinh(z)}

@tab

Return the inverse hyperbolic sine of `z'

@item

@ref{2aa0,,atanh(z)}

@tab

Return the inverse hyperbolic tangent of `z'

@item

@ref{2aa1,,cosh(z)}

@tab

Return the hyperbolic cosine of `z'

@item

@ref{2aa2,,sinh(z)}

@tab

Return the hyperbolic sine of `z'

@item

@ref{2aa3,,tanh(z)}

@tab

Return the hyperbolic tangent of `z'

@item

`Classification functions'

@tab

@item

@ref{2aa4,,isfinite(z)}

@tab

Check if all components of `z' are finite

@item

@ref{2aa5,,isinf(z)}

@tab

Check if any component of `z' is infinite

@item

@ref{2aa6,,isnan(z)}

@tab

Check if any component of `z' is a NaN

@item

@ref{fb1,,isclose(a@comma{} b@comma{} *@comma{} rel_tol@comma{} abs_tol)}

@tab

Check if the values `a' and `b' are close to each other

@item

`定数'

@tab

@item

@ref{2aa7,,pi}

@tab

`π' = 3.141592...

@item

@ref{2aa8,,e}

@tab

`e' = 2.718281...

@item

@ref{e7d,,tau}

@tab

`τ' = 2`π' = 6.283185...

@item

@ref{e7f,,inf}

@tab

正の無限大

@item

@ref{e81,,infj}

@tab

Pure imaginary infinity

@item

@ref{e80,,nan}

@tab

非数 "Not a number" (NaN)

@item

@ref{e82,,nanj}

@tab

Pure imaginary NaN

@end multitable


@menu
* 極座標変換:: 
* 指数関数と対数関数:: 
* 三角関数: 三角関数<2>. 
* 双曲線関数: 双曲線関数<2>. 
* 類別関数:: 
* 定数: 定数<3>. 

@end menu

@node 極座標変換,指数関数と対数関数,,cmath --- 複素数用の数学関数
@anchor{library/cmath conversions-to-and-from-polar-coordinates}@anchor{2aa9}
@subsubsection 極座標変換


A Python complex number @code{z} is stored internally using `rectangular'
or `Cartesian' coordinates.  It is completely determined by its `real
part' @code{z.real} and its `imaginary part' @code{z.imag}.

`極座標' は複素数を表現する別の方法です。極座標では、複素数 `z' は半径 `r' と位相角 `phi' で定義されます。半径 `r' は `z' から原点までの距離です。位相 `phi' は x 軸の正の部分から原点と `z' を結んだ線分までの角度を反時計回りにラジアンで測った値です。

次の関数はネイティブの直交座標を極座標に変換したりその逆を行うのに使えます。

@geindex phase() (cmath モジュール)
@anchor{library/cmath cmath phase}@anchor{2a92}
@deffn {の関数} cmath.phase (z)

Return the phase of `z' (also known as the `argument' of `z'), as a float.
@code{phase(z)} is equivalent to @code{math.atan2(z.imag, z.real)}.  The result
lies in the range [-`π', `π'], and the branch cut for this operation lies
along the negative real axis.  The sign of the result is the same as the
sign of @code{z.imag}, even when @code{z.imag} is zero:

@example
>>> phase(-1+0j)
3.141592653589793
>>> phase(-1-0j)
-3.141592653589793
@end example
@end deffn

@cartouche
@quotation 注釈 
The modulus (absolute value) of a complex number `z' can be
computed using the built-in @ref{208d,,abs()} function.  There is no
separate @code{cmath} module function for this operation.
@end quotation
@end cartouche

@geindex polar() (cmath モジュール)
@anchor{library/cmath cmath polar}@anchor{2a93}
@deffn {の関数} cmath.polar (z)

Return the representation of `z' in polar coordinates.  Returns a
pair @code{(r, phi)} where `r' is the modulus of `z' and `phi' is the
phase of `z'.  @code{polar(z)} is equivalent to @code{(abs(z),
phase(z))}.
@end deffn

@geindex rect() (cmath モジュール)
@anchor{library/cmath cmath rect}@anchor{2a94}
@deffn {の関数} cmath.rect (r, phi)

Return the complex number `z' with polar coordinates `r' and `phi'.
Equivalent to @code{complex(r * math.cos(phi), r * math.sin(phi))}.
@end deffn

@node 指数関数と対数関数,三角関数<2>,極座標変換,cmath --- 複素数用の数学関数
@anchor{library/cmath power-and-logarithmic-functions}@anchor{2aaa}
@subsubsection 指数関数と対数関数


@geindex exp() (cmath モジュール)
@anchor{library/cmath cmath exp}@anchor{2a95}
@deffn {の関数} cmath.exp (z)

Return `e' raised to the power `z', where `e' is the base of natural
logarithms.
@end deffn

@geindex log() (cmath モジュール)
@anchor{library/cmath cmath log}@anchor{2a96}
@deffn {の関数} cmath.log (z[, base])

Return the logarithm of `z' to the given `base'. If the `base' is not
specified, returns the natural logarithm of `z'. There is one branch cut,
from 0 along the negative real axis to -∞.
@end deffn

@geindex log10() (cmath モジュール)
@anchor{library/cmath cmath log10}@anchor{2a97}
@deffn {の関数} cmath.log10 (z)

Return the base-10 logarithm of `z'. This has the same branch cut as
@ref{2a96,,log()}.
@end deffn

@geindex sqrt() (cmath モジュール)
@anchor{library/cmath cmath sqrt}@anchor{2a91}
@deffn {の関数} cmath.sqrt (z)

Return the square root of `z'. This has the same branch cut as @ref{2a96,,log()}.
@end deffn

@node 三角関数<2>,双曲線関数<2>,指数関数と対数関数,cmath --- 複素数用の数学関数
@anchor{library/cmath trigonometric-functions}@anchor{2aab}
@subsubsection 三角関数


@geindex acos() (cmath モジュール)
@anchor{library/cmath cmath acos}@anchor{2a98}
@deffn {の関数} cmath.acos (z)

Return the arc cosine of `z'. There are two branch cuts: One extends right
from 1 along the real axis to ∞. The other extends left from -1 along the
real axis to -∞.
@end deffn

@geindex asin() (cmath モジュール)
@anchor{library/cmath cmath asin}@anchor{2a99}
@deffn {の関数} cmath.asin (z)

Return the arc sine of `z'. This has the same branch cuts as @ref{2a98,,acos()}.
@end deffn

@geindex atan() (cmath モジュール)
@anchor{library/cmath cmath atan}@anchor{2a9a}
@deffn {の関数} cmath.atan (z)

Return the arc tangent of `z'. There are two branch cuts: One extends from
@code{1j} along the imaginary axis to @code{∞j}. The other extends from @code{-1j}
along the imaginary axis to @code{-∞j}.
@end deffn

@geindex cos() (cmath モジュール)
@anchor{library/cmath cmath cos}@anchor{2a9b}
@deffn {の関数} cmath.cos (z)

Return the cosine of `z'.
@end deffn

@geindex sin() (cmath モジュール)
@anchor{library/cmath cmath sin}@anchor{2a9c}
@deffn {の関数} cmath.sin (z)

Return the sine of `z'.
@end deffn

@geindex tan() (cmath モジュール)
@anchor{library/cmath cmath tan}@anchor{2a9d}
@deffn {の関数} cmath.tan (z)

Return the tangent of `z'.
@end deffn

@node 双曲線関数<2>,類別関数,三角関数<2>,cmath --- 複素数用の数学関数
@anchor{library/cmath hyperbolic-functions}@anchor{2aac}
@subsubsection 双曲線関数


@geindex acosh() (cmath モジュール)
@anchor{library/cmath cmath acosh}@anchor{2a9e}
@deffn {の関数} cmath.acosh (z)

Return the inverse hyperbolic cosine of `z'. There is one branch cut,
extending left from 1 along the real axis to -∞.
@end deffn

@geindex asinh() (cmath モジュール)
@anchor{library/cmath cmath asinh}@anchor{2a9f}
@deffn {の関数} cmath.asinh (z)

Return the inverse hyperbolic sine of `z'. There are two branch cuts:
One extends from @code{1j} along the imaginary axis to @code{∞j}.  The other
extends from @code{-1j} along the imaginary axis to @code{-∞j}.
@end deffn

@geindex atanh() (cmath モジュール)
@anchor{library/cmath cmath atanh}@anchor{2aa0}
@deffn {の関数} cmath.atanh (z)

Return the inverse hyperbolic tangent of `z'. There are two branch cuts: One
extends from @code{1} along the real axis to @code{∞}. The other extends from
@code{-1} along the real axis to @code{-∞}.
@end deffn

@geindex cosh() (cmath モジュール)
@anchor{library/cmath cmath cosh}@anchor{2aa1}
@deffn {の関数} cmath.cosh (z)

Return the hyperbolic cosine of `z'.
@end deffn

@geindex sinh() (cmath モジュール)
@anchor{library/cmath cmath sinh}@anchor{2aa2}
@deffn {の関数} cmath.sinh (z)

Return the hyperbolic sine of `z'.
@end deffn

@geindex tanh() (cmath モジュール)
@anchor{library/cmath cmath tanh}@anchor{2aa3}
@deffn {の関数} cmath.tanh (z)

Return the hyperbolic tangent of `z'.
@end deffn

@node 類別関数,定数<3>,双曲線関数<2>,cmath --- 複素数用の数学関数
@anchor{library/cmath classification-functions}@anchor{2aad}
@subsubsection 類別関数


@geindex isfinite() (cmath モジュール)
@anchor{library/cmath cmath isfinite}@anchor{2aa4}
@deffn {の関数} cmath.isfinite (z)

Return @code{True} if both the real and imaginary parts of `z' are finite, and
@code{False} otherwise.


Added in version 3.2.

@end deffn

@geindex isinf() (cmath モジュール)
@anchor{library/cmath cmath isinf}@anchor{2aa5}
@deffn {の関数} cmath.isinf (z)

Return @code{True} if either the real or the imaginary part of `z' is an
infinity, and @code{False} otherwise.
@end deffn

@geindex isnan() (cmath モジュール)
@anchor{library/cmath cmath isnan}@anchor{2aa6}
@deffn {の関数} cmath.isnan (z)

Return @code{True} if either the real or the imaginary part of `z' is a NaN,
and @code{False} otherwise.
@end deffn

@geindex isclose() (cmath モジュール)
@anchor{library/cmath cmath isclose}@anchor{fb1}
@deffn {の関数} cmath.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

値 `a' と `b' が互いに近い場合 @code{True} を、そうでない場合は @code{False} を返します。

Whether or not two values are considered close is determined according to
given absolute and relative tolerances.  If no errors occur, the result will
be: @code{abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)}.

`rel_tol' is the relative tolerance -- it is the maximum allowed difference
between `a' and `b', relative to the larger absolute value of `a' or `b'.
For example, to set a tolerance of 5%, pass @code{rel_tol=0.05}.  The default
tolerance is @code{1e-09}, which assures that the two values are the same
within about 9 decimal digits.  `rel_tol' must be nonnegative and less
than @code{1.0}.

`abs_tol' is the absolute tolerance; it defaults to @code{0.0} and it must be
nonnegative.  When comparing @code{x} to @code{0.0}, @code{isclose(x, 0)} is computed
as @code{abs(x) <= rel_tol  * abs(x)}, which is @code{False} for any @code{x} and
rel_tol less than @code{1.0}.  So add an appropriate positive abs_tol argument
to the call.

IEEE 754 特殊値 @code{NaN}、@code{inf}、@code{-inf} は IEEE の規則に従って処理されます。
具体的には、@code{NaN} は自身を含めたあらゆる値に近いとは見なされません。
@code{inf} と @code{-inf} は自身とのみ近いと見なされます。


Added in version 3.5.



@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 485
PEP 485@footnote{https://peps.python.org/pep-0485/} -- 近似的に等しいことを調べる関数

@end deffn

@node 定数<3>,,類別関数,cmath --- 複素数用の数学関数
@anchor{library/cmath constants}@anchor{2aae}
@subsubsection 定数


@geindex pi (cmath モジュール)
@anchor{library/cmath cmath pi}@anchor{2aa7}
@deffn {データ} cmath.pi

定数 `π' (円周率)で、浮動小数点数です。
@end deffn

@geindex e (cmath モジュール)
@anchor{library/cmath cmath e}@anchor{2aa8}
@deffn {データ} cmath.e

定数 `e' (自然対数の底)で、浮動小数点数です。
@end deffn

@geindex tau (cmath モジュール)
@anchor{library/cmath cmath tau}@anchor{e7d}
@deffn {データ} cmath.tau

数学定数 `τ' で、浮動小数点数です。


Added in version 3.6.

@end deffn

@geindex inf (cmath モジュール)
@anchor{library/cmath cmath inf}@anchor{e7f}
@deffn {データ} cmath.inf

浮動小数点数の正の無限大です。@code{float('inf')} と等価です。


Added in version 3.6.

@end deffn

@geindex infj (cmath モジュール)
@anchor{library/cmath cmath infj}@anchor{e81}
@deffn {データ} cmath.infj

実部がゼロ、虚部が正の無限大の複素数です。@code{complex(0.0, float('inf'))} と等価です。


Added in version 3.6.

@end deffn

@geindex nan (cmath モジュール)
@anchor{library/cmath cmath nan}@anchor{e80}
@deffn {データ} cmath.nan

A floating-point "not a number" (NaN) value.  Equivalent to
@code{float('nan')}. See also @ref{873,,math.nan}.


Added in version 3.6.

@end deffn

@geindex nanj (cmath モジュール)
@anchor{library/cmath cmath nanj}@anchor{e82}
@deffn {データ} cmath.nanj

実部がゼロ、虚部が NaN の複素数です。@code{complex(0.0, float('nan'))} と等価です。


Added in version 3.6.

@end deffn

@geindex module;math

Note that the selection of functions is similar, but not identical, to that in
module @ref{92,,math}.  The reason for having two modules is that some users aren't
interested in complex numbers, and perhaps don't even know what they are.  They
would rather have @code{math.sqrt(-1)} raise an exception than return a complex
number. Also note that the functions defined in @code{cmath} always return a
complex number, even if the answer can be expressed as a real number (in which
case the complex number has an imaginary part of zero).

分枝切断 (branch cut) に関する注釈: 分枝切断を持つ曲線上では、与えられた関数は連続ではなくなります。これらは多くの複素関数における必然的な特性です。複素関数を計算する必要がある場合、これらの分枝に関して理解しているものと仮定しています。悟りに至るために何らかの (到底基礎的とはいえない) 複素数に関する書をひもといてください。数値計算を目的とした分枝切断の正しい選択方法についての情報としては、以下がよい参考文献となります:


@subsubheading 参考


Kahan, W:  Branch cuts for complex elementary functions; or, Much ado about nothings's sign bit.  In Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165--211.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node decimal --- 10進固定小数点と浮動小数点の演算,fractions --- 有理数,cmath --- 複素数用の数学関数,数値と数学モジュール
@anchor{library/decimal doc}@anchor{2aaf}@anchor{library/decimal decimal-decimal-fixed-point-and-floating-point-arithmetic}@anchor{2ab0}@anchor{library/decimal module-decimal}@anchor{3a}@anchor{library/decimal translation-repo}@anchor{2ab1}
@subsection @code{decimal} --- 10進固定小数点と浮動小数点の演算


@geindex module; decimal

`ソースコード:' Lib/decimal.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/decimal.py}

@c import modules for testing inline doctests with the Sphinx doctest builder

@c import decimal
@c import math
@c from decimal import *
@c # make sure each group gets a fresh context
@c setcontext(Context())

@c # make sure other tests (outside this file) get a fresh context
@c setcontext(Context())


__________________________________________________________________


The @code{decimal} module provides support for fast correctly rounded
decimal floating-point arithmetic. It offers several advantages over the
@ref{196,,float} datatype:


@itemize *

@item 
Decimal "is based on a floating-point model@footnote{https://speleotrove.com/decimal/damodel.html#refnumber} which was designed
with people in mind, and necessarily has a paramount guiding principle --
computers must provide an arithmetic that works in the same way as the
arithmetic that people learn at school." -- excerpt from the decimal
arithmetic specification.

@item 
十進数を正確に表現できます。 @code{1.1} や @code{2.2} のような数は、二進数の浮動小数点型では正しく表現できません。エンドユーザは普通、 二進数における @code{1.1 + 2.2} の近似値が @code{3.3000000000000003} だからといって、そのように表示してほしいとは考えないものです。

@item 
値の正確さは算術にも及びます。十進の浮動小数点による計算では、 @code{0.1 + 0.1 + 0.1 - 0.3} は厳密にゼロに等しくなります。 二進浮動小数点では @code{5.5511151231257827e-017} になってしまいます。ゼロに近い値とはいえ、この誤差は数値間の等価性テストの信頼性を阻害します。また、誤差が蓄積されることもあります。こうした理由から、数値間の等価性を厳しく保たなければならないようなアプリケーションを考えるなら、十進数による数値表現が望ましいということになります。

@item 
@ref{3a,,decimal} モジュールでは、有効桁数の表記が取り入れられており、例えば @code{1.30 + 1.20} は @code{2.50} になります。すなわち、末尾のゼロは有効数字を示すために残されます。こうした仕様は通貨計算を行うアプリケーションでは慣例です。乗算の場合、「教科書的な」アプローチでは、乗算の被演算子すべての桁数を使います。例えば、 @code{1.3 * 1.2} は @code{1.56} になり、 @code{1.30 * 1.20} は @code{1.5600} になります。

@item 
ハードウェアによる 2 進浮動小数点表現と違い、@ref{3a,,decimal} モジュールでは計算精度をユーザが変更できます(デフォルトでは 28 桁です)。この桁数はほとんどの問題解決に十分な大きさです:

@example
>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')
@end example

@item 
二進と十進の浮動小数点は、いずれも広く公開されている標準仕様のもとに実装されています。組み込みの浮動小数点型では、標準仕様で提唱されている機能のほんのささやかな部分を利用できるにすぎませんが、@ref{3a,,decimal} では標準仕様が要求している全ての機能を利用できます。必要に応じて、プログラマは値の丸めやシグナル処理を完全に制御できます。この中には全ての不正確な操作を例外でブロックして正確な算術を遵守させるオプションもあります。

@item 
decimal モジュールは「偏見なく、正確な丸めなしの十進算術(固定小数点算術と呼ばれることもある)と丸めありの浮動小数点数算術」(十進数演算仕様より引用)をサポートするようにデザインされました。
@end itemize

このモジュールは、十進数型、算術コンテキスト (context for arithmetic)、そしてシグナル (signal) という三つの概念を中心に設計されています。

十進数型は変更不能です。これは符号、係数部、そして指数を持ちます。有効桁数を残すために、仮数部の末尾にあるゼロは切り詰められません。 @ref{3a,,decimal} では、 @code{Infinity}, @code{-Infinity}, および @code{NaN} といった特殊な値も定義されています。標準仕様では @code{-0} と @code{+0} も区別します。

算術コンテキストとは、精度や値丸めの規則、指数部の制限を決めている環境です。この環境では、演算結果を表すためのフラグや、演算上発生した特定のシグナルを例外として扱うかどうかを決めるトラップイネーブラも定義しています。丸め規則には @ref{2ab2,,ROUND_CEILING}, @ref{2ab3,,ROUND_DOWN}, @ref{2ab4,,ROUND_FLOOR}, @ref{2ab5,,ROUND_HALF_DOWN}, @ref{2ab6,,ROUND_HALF_EVEN}, @ref{2ab7,,ROUND_HALF_UP}, @ref{2ab8,,ROUND_UP}, および @ref{2ab9,,ROUND_05UP} があります。

シグナルとは、演算の過程で生じる例外的条件です。個々のシグナルは、アプリケーションそれぞれの要求に従って、無視されたり、単なる情報とみなされたり、例外として扱われたりします。 @ref{3a,,decimal} モジュールには、 @ref{2aba,,Clamped}, @ref{12bc,,InvalidOperation}, @ref{2abb,,DivisionByZero}, @ref{2abc,,Inexact}, @ref{2abd,,Rounded}, @ref{2abe,,Subnormal}, @ref{2abf,,Overflow}, @ref{2ac0,,Underflow}, および @ref{12af,,FloatOperation} といったシグナルがあります。

各シグナルには、フラグとトラップイネーブラがあります。演算上何らかのシグナルに遭遇すると、フラグは 1 にセットされます。このとき、もしトラップイネーブラが 1 にセットされていれば、例外を送出します。フラグの値は膠着型 (sticky) なので、演算によるフラグの変化をモニタしたければ、予めフラグをリセットしておかなければなりません。


@subsubheading 参考



@itemize *

@item 
IBM による汎用十進演算仕様、The General Decimal Arithmetic Specification@footnote{https://speleotrove.com/decimal/decarith.html}。
@end itemize


@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@menu
* Quick-start tutorial:: 
* Decimal オブジェクト:: 
* Context オブジェクト:: 
* 定数: 定数<4>. 
* 丸めモード:: 
* シグナル:: 
* Floating-point notes:: 
* スレッドを使った処理:: 
* レシピ:: 
* Decimal FAQ:: 

@end menu

@node Quick-start tutorial,Decimal オブジェクト,,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal decimal-tutorial}@anchor{12b1}@anchor{library/decimal quick-start-tutorial}@anchor{2ac1}
@subsubsection Quick-start tutorial


普通、 @ref{3a,,decimal} を使うときには、モジュールをインポートし、現在の演算コンテキストを @ref{1937,,getcontext()} で調べ、必要なら、精度、丸め、有効なトラップを設定します:

@example
>>> from decimal import *
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
        InvalidOperation])

>>> getcontext().prec = 7       # Set a new precision
@end example

@ref{1fe,,Decimal} インスタンスは、整数、文字列、浮動小数点数、またはタプルから構成できます。整数や浮動小数点数からの構成は、整数や浮動小数点数の値を正確に変換します。 @ref{1fe,,Decimal} は "非数 (Not a Number)" を表す @code{NaN} や正負の @code{Infinity} (無限大)、 @code{-0} といった特殊な値も表現できます:

@example
>>> getcontext().prec = 28
>>> Decimal(10)
Decimal('10')
>>> Decimal('3.14')
Decimal('3.14')
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
>>> Decimal((0, (3, 1, 4), -2))
Decimal('3.14')
>>> Decimal(str(2.0 ** 0.5))
Decimal('1.4142135623730951')
>>> Decimal(2) ** Decimal('0.5')
Decimal('1.414213562373095048801688724')
>>> Decimal('NaN')
Decimal('NaN')
>>> Decimal('-Infinity')
Decimal('-Infinity')
@end example

@ref{12af,,FloatOperation} シグナルがトラップされる場合、コンストラクタや順序比較において誤って decimal と float が混ざると、例外が送出されます:

@example
>>> c = getcontext()
>>> c.traps[FloatOperation] = True
>>> Decimal(3.14)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') < 3.7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') == 3.5
True
@end example


Added in version 3.3.


新たな @ref{1fe,,Decimal} の有効桁数は入力の桁数だけで決まります。演算コンテキストにおける精度や値丸めの設定が影響するのは算術演算の間だけです。

@example
>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')
@end example

C バージョンの内部制限を超えた場合、decimal の構成は @ref{12bc,,InvalidOperation} を送出します:

@example
>>> Decimal("1e9999999999999999999")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
@end example


バージョン 3.3 で変更.


Decimals interact well with much of the rest of Python.  Here is a small decimal
floating-point flying circus:

@example
>>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
>>> max(data)
Decimal('9.25')
>>> min(data)
Decimal('0.03')
>>> sorted(data)
[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
>>> sum(data)
Decimal('19.29')
>>> a,b,c = data[:3]
>>> str(a)
'1.34'
>>> float(a)
1.34
>>> round(a, 1)
Decimal('1.3')
>>> int(a)
1
>>> a * 5
Decimal('6.70')
>>> a * b
Decimal('2.5058')
>>> c % a
Decimal('0.77')
@end example

Decimals can be formatted (with @ref{199,,format()} built-in or @ref{19a,,f-strings}) in
fixed-point or scientific notation, using the same formatting syntax (see
@ref{4f9,,書式指定ミニ言語仕様}) as builtin @ref{196,,float} type:

@example
>>> format(Decimal('2.675'), "f")
'2.675'
>>> format(Decimal('2.675'), ".2f")
'2.68'
>>> f"@{Decimal('2.675'):.2f@}"
'2.68'
>>> format(Decimal('2.675'), ".2e")
'2.68e+0'
>>> with localcontext() as ctx:
...     ctx.rounding = ROUND_DOWN
...     print(format(Decimal('2.675'), ".2f"))
...
2.67
@end example

いくつかの数学的関数も Decimal には用意されています:

@example
>>> getcontext().prec = 28
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal('10').ln()
Decimal('2.302585092994045684017991455')
>>> Decimal('10').log10()
Decimal('1')
@end example

@ref{12c4,,quantize()} メソッドは位を固定して数値を丸めます。このメソッドは、結果を固定の桁数で丸めることがよくある、金融アプリケーションで便利です:

@example
>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')
@end example

前述のように、 @ref{1937,,getcontext()} 関数を使うと現在の演算コンテキストにアクセスでき、設定を変更できます。ほとんどのアプリケーションはこのアプローチで十分です。

For more advanced work, it may be useful to create alternate contexts using the
@ref{12c3,,Context()} constructor.  To make an alternate active, use the @ref{2ac2,,setcontext()}
function.

In accordance with the standard, the @code{decimal} module provides two ready to
use standard contexts, @ref{12b8,,BasicContext} and @ref{12b9,,ExtendedContext}. The
former is especially useful for debugging because many of the traps are
enabled:

@example
>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
>>> setcontext(myothercontext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857142857142857142857142857')

>>> ExtendedContext
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[])
>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857143')
>>> Decimal(42) / Decimal(0)
Decimal('Infinity')

>>> setcontext(BasicContext)
>>> Decimal(42) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#143>", line 1, in -toplevel-
    Decimal(42) / Decimal(0)
DivisionByZero: x / 0
@end example

演算コンテキストには、演算中に遭遇した例外的状況をモニタするためのシグナルフラグがあります。フラグが一度セットされると、明示的にクリアするまで残り続けます。そのため、フラグのモニタを行いたいような演算の前には @ref{2ac3,,clear_flags()} メソッドでフラグをクリアしておくのがベストです。

@example
>>> setcontext(ExtendedContext)
>>> getcontext().clear_flags()
>>> Decimal(355) / Decimal(113)
Decimal('3.14159292')
>>> getcontext()
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
@end example

`flags' エントリから、pi の有理数による近似値が丸められた (コンテキスト内で決められた精度を超えた桁数が捨てられた) ことと、計算結果が厳密でない (無視された桁の値に非ゼロのものがあった) ことがわかります。

コンテキストの @ref{12c2,,traps} 属性に入っている辞書を使うと、個々のトラップをセットできます:

@example
>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(0)
Decimal('Infinity')
>>> getcontext().traps[DivisionByZero] = 1
>>> Decimal(1) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#112>", line 1, in -toplevel-
    Decimal(1) / Decimal(0)
DivisionByZero: x / 0
@end example

ほとんどのプログラムでは、開始時に一度だけ現在の演算コンテキストを修正します。また、多くのアプリケーションでは、データから @ref{1fe,,Decimal} への変換はループ内で一度だけキャストして行います。コンテキストを設定し、 @ref{1fe,,Decimal} オブジェクトを生成できたら、ほとんどのプログラムは他の Python 数値型と全く変わらないかのように @ref{1fe,,Decimal} を操作できます。

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node Decimal オブジェクト,Context オブジェクト,Quick-start tutorial,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal decimal-decimal}@anchor{2ac4}@anchor{library/decimal decimal-objects}@anchor{2ac5}
@subsubsection Decimal オブジェクト


@geindex Decimal (decimal のクラス)
@anchor{library/decimal decimal Decimal}@anchor{1fe}
@deffn {クラス} decimal.Decimal (value='0', context=None)

`value' に基づいて新たな @ref{1fe,,Decimal} オブジェクトを構築します。

`value' は整数、文字列、タプル、 @ref{196,,float} および他の @ref{1fe,,Decimal} オブジェクトにできます。 `value' を指定しない場合、 @code{Decimal('0')} を返します。 `value' が文字列の場合、先頭と末尾の空白および全てのアンダースコアを取り除いた後には以下の 10進数文字列の文法に従わなければなりません:

@example
sign           ::=  '+' | '-'
digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
indicator      ::=  'e' | 'E'
digits         ::=  digit [digit]...
decimal-part   ::=  digits '.' [digits] | ['.'] digits
exponent-part  ::=  indicator [sign] digits
infinity       ::=  'Infinity' | 'Inf'
nan            ::=  'NaN' [digits] | 'sNaN' [digits]
numeric-value  ::=  decimal-part [exponent-part] | infinity
numeric-string ::=  [sign] numeric-value | [sign] nan
@end example

Other Unicode decimal digits are also permitted where @code{digit}
appears above.  These include decimal digits from various other
alphabets (for example, Arabic-Indic and Devanāgarī digits) along
with the fullwidth digits @code{'\uff10'} through @code{'\uff19'}.
Case is not significant, so, for example, @code{inf}, @code{Inf}, @code{INFINITY},
and @code{iNfINity} are all acceptable spellings for positive infinity.

`value' を @ref{614,,tuple} にする場合、タプルは三つの要素を持ち、それぞれ符号 (正なら @code{0} 、負なら @code{1})、仮数部を表す数字の @ref{614,,tuple} 、そして指数を表す整数でなければなりません。例えば、 @code{Decimal((0, (1, 4, 1, 4), -3))} は @code{Decimal('1.414')} を返します。

If `value' is a @ref{196,,float}, the binary floating-point value is losslessly
converted to its exact decimal equivalent.  This conversion can often require
53 or more digits of precision.  For example, @code{Decimal(float('1.1'))}
converts to
@code{Decimal('1.100000000000000088817841970012523233890533447265625')}.

`context' の精度 (precision) は、記憶される桁数には影響しません。桁数は `value' に指定した桁数だけから決定されます。例えば、演算コンテキストに指定された精度が 3 桁しかなくても、@code{Decimal('3.00000')} は 5 つのゼロを全て記憶します。

`context' 引数の目的は、 `value' が正しくない形式の文字列であった場合に行う処理を決めることにあります; 演算コンテキストが @ref{12bc,,InvalidOperation} をトラップするようになっていれば、例外を送出します。それ以外の場合には、コンストラクタは値が @code{NaN} の @ref{1fe,,Decimal} を返します。

一度生成すると、 @ref{1fe,,Decimal} オブジェクトは変更不能 (immutable) になります。


バージョン 3.2 で変更: コンストラクタに対する引数に @ref{196,,float} インスタンスも許されるようになりました。



バージョン 3.3 で変更: @ref{12af,,FloatOperation} トラップがセットされていた場合 @ref{196,,float} 引数は例外を送出します。デフォルトでトラップはオフです。



バージョン 3.6 で変更: コード中の整数リテラルや浮動小数点リテラルと同様に、アンダースコアを用いて桁をグルーピングできます。


Decimal floating-point objects share many properties with the other built-in
numeric types such as @ref{196,,float} and @ref{19b,,int}.  All of the usual math
operations and special methods apply.  Likewise, decimal objects can be
copied, pickled, printed, used as dictionary keys, used as set elements,
compared, sorted, and coerced to another type (such as @ref{196,,float} or
@ref{19b,,int}).

十進オブジェクトの算術演算と整数や浮動小数点数の算術演算には少々違いがあります。十進オブジェクトに対して剰余演算を適用すると、計算結果の符号は除数の符号ではなく `被除数' の符号と一致します:

@example
>>> (-7) % 4
1
>>> Decimal(-7) % Decimal(4)
Decimal('-3')
@end example

整数除算演算子 @code{//} も同様に、実際の商の切り捨てではなく (0に近付くように丸めた) 整数部分を返します。そのため通常の恒等式 @code{x == (x // y) * y + x % y} が維持されます:

@example
>>> -7 // 4
-2
>>> Decimal(-7) // Decimal(4)
Decimal('-1')
@end example

演算子 @code{%} と演算子 @code{//} は (それぞれ) 仕様にあるような @code{剰余} 操作と @code{整数除算} 操作を実装しています。

Decimal オブジェクトは一般に、算術演算で浮動小数点数や @ref{213,,fractions.Fraction} オブジェクトと組み合わせることができません。例えば、 @ref{1fe,,Decimal} に @ref{196,,float} を足そうとすると、 @ref{198,,TypeError} が送出されます。ただし、Python の比較演算子を使って @ref{1fe,,Decimal} インスタンス @code{x} と別の数 @code{y} を比較することができます。これにより、異なる型の数間の等価比較の際に、紛らわしい結果を避けます。


バージョン 3.2 で変更: @ref{1fe,,Decimal} インスタンスと他の数値型が混在する比較が完全にサポートされるようになりました。


In addition to the standard numeric properties, decimal floating-point
objects also have a number of specialized methods:

@geindex adjusted() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal adjusted}@anchor{2ac6}
@deffn {メソッド} adjusted ()

仮数の先頭の一桁だけが残るように右側の数字を追い出す桁シフトを行い、その結果の指数部を返します: @code{Decimal('321e+5').adjusted()} は 7 を返します。最上桁の小数点からの相対位置を調べる際に使います。
@end deffn

@geindex as_integer_ratio() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal as_integer_ratio}@anchor{e92}
@deffn {メソッド} as_integer_ratio ()

与えられた @ref{1fe,,Decimal} インスタンスを、既約分数で分母が正数の分数として表現した整数のペア @code{(n, d)} を返します。

@example
>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)
@end example

変換は正確に行われます。無限大に対してはOverflowErrorを、NaNに対してはValueError を送出します。
@end deffn


Added in version 3.6.


@geindex as_tuple() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal as_tuple}@anchor{2ac7}
@deffn {メソッド} as_tuple ()

数値を表現するための @ref{85e,,名前付きタプル}: @code{DecimalTuple(sign, digittuple, exponent)} を返します。
@end deffn

@geindex canonical() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal canonical}@anchor{2ac8}
@deffn {メソッド} canonical ()

引数の標準的(canonical)エンコーディングを返します。現在のところ、 @ref{1fe,,Decimal} インスタンスのエンコーディングは常に標準的なので、この操作は引数に手を加えずに返します。
@end deffn

@geindex compare() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal compare}@anchor{2ac9}
@deffn {メソッド} compare (other, context=None)

二つの Decimal インスタンスの値を比較します。 @ref{2ac9,,compare()} は Decimal インスタンスを返し、被演算子のどちらかが NaN ならば結果は NaN です:

@example
a or b is a NaN  ==> Decimal('NaN')
a < b            ==> Decimal('-1')
a == b           ==> Decimal('0')
a > b            ==> Decimal('1')
@end example
@end deffn

@geindex compare_signal() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal compare_signal}@anchor{2aca}
@deffn {メソッド} compare_signal (other, context=None)

この演算は @ref{2ac9,,compare()} とほとんど同じですが、全ての NaN がシグナルを送るところが異なります。すなわち、どちらの比較対象も発信 (signaling) NaN でないならば無言 (quiet) NaN である比較対象があたかも発信 NaN であるかのように扱われます。
@end deffn

@geindex compare_total() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal compare_total}@anchor{2acb}
@deffn {メソッド} compare_total (other, context=None)

二つの対象を数値によらず抽象表現によって比較します。 @ref{2ac9,,compare()} に似ていますが、結果は @ref{1fe,,Decimal} に全順序を与えます。この順序づけによると、数値的に等しくても異なった表現を持つ二つの @ref{1fe,,Decimal} インスタンスの比較は等しくなりません:

@example
>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')
@end example

無言 NaN と発信 NaN もこの全順序に位置付けられます。この関数の結果は、もし比較対象が同じ表現を持つならば @code{Decimal('0')} であり、一つめの比較対象が二つめより下位にあれば @code{Decimal('-1')}、上位にあれば @code{Decimal('1')} です。全順序の詳細については仕様を参照してください。

この演算はコンテキストに影響されず、静かです。すなわち、フラグは変更されず、丸めは行われません。例外として、2番目の比較対象の厳密な変換ができない場合、C バージョンのライブラリでは InvalidOperation 例外を送出するかもしれません。
@end deffn

@geindex compare_total_mag() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal compare_total_mag}@anchor{2acc}
@deffn {メソッド} compare_total_mag (other, context=None)

二つの対象を @ref{2acb,,compare_total()} のように数値によらず抽象表現によって比較しますが、両者の符号を無視します。 @code{x.compare_total_mag(y)} は @code{x.copy_abs().compare_total(y.copy_abs())} と等価です。

この演算はコンテキストに影響されず、静かです。すなわち、フラグは変更されず、丸めは行われません。例外として、2番目の比較対象の厳密な変換ができない場合、C バージョンのライブラリでは InvalidOperation 例外を送出するかもしれません。
@end deffn

@geindex conjugate() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal conjugate}@anchor{2acd}
@deffn {メソッド} conjugate ()

self を返すだけです。このメソッドは十進演算仕様に適合するためだけのものです。
@end deffn

@geindex copy_abs() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal copy_abs}@anchor{2ace}
@deffn {メソッド} copy_abs ()

引数の絶対値を返します。この演算はコンテキストに影響されず、静かです。すなわち、フラグは変更されず、丸めは行われません。
@end deffn

@geindex copy_negate() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal copy_negate}@anchor{2acf}
@deffn {メソッド} copy_negate ()

引数の符号を変えて返します。この演算はコンテキストに影響されず、静かです。すなわち、フラグは変更されず、丸めは行われません。
@end deffn

@geindex copy_sign() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal copy_sign}@anchor{2ad0}
@deffn {メソッド} copy_sign (other, context=None)

最初の演算対象のコピーに二つめと同じ符号を付けて返します。たとえば:

@example
>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')
@end example

この演算はコンテキストに影響されず、静かです。すなわち、フラグは変更されず、丸めは行われません。例外として、2番目の比較対象の厳密な変換ができない場合、C バージョンのライブラリでは InvalidOperation 例外を送出するかもしれません。
@end deffn

@geindex exp() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal exp}@anchor{12be}
@deffn {メソッド} exp (context=None)

与えられた数での(自然)指数関数 @code{e**x} の値を返します。結果は @ref{2ab6,,ROUND_HALF_EVEN} 丸めモードで正しく丸められます。

@example
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal(321).exp()
Decimal('2.561702493119680037517373933E+139')
@end example
@end deffn

@geindex from_float() (decimal.Decimal のクラスメソッド)
@anchor{library/decimal decimal Decimal from_float}@anchor{141d}
@deffn {メソッド} classmethod from_float (f, /)

Alternative constructor that only accepts instances of @ref{196,,float} or
@ref{19b,,int}.

なお、@code{Decimal.from_float(0.1)} は @code{Decimal('0.1')} と同じではありません。0.1 は二進浮動小数点数で正確に表せないので、その値は表現できる最も近い値、@code{0x1.999999999999ap-4} として記憶されます。浮動小数点数での等価な値は @code{0.1000000000000000055511151231257827021181583404541015625} です。

@cartouche
@quotation 注釈 
Python 3.2 以降では、 @ref{1fe,,Decimal} インスタンスは @ref{196,,float} から直接構成できるようになりました。
@end quotation
@end cartouche

@example
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')
@end example


Added in version 3.1.

@end deffn

@geindex from_number() (decimal.Decimal のクラスメソッド)
@anchor{library/decimal decimal Decimal from_number}@anchor{1fd}
@deffn {メソッド} classmethod from_number (number, /)

Alternative constructor that only accepts instances of
@ref{196,,float}, @ref{19b,,int} or @ref{1fe,,Decimal}, but not strings
or tuples.

@example
>>> Decimal.from_number(314)
Decimal('314')
>>> Decimal.from_number(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_number(Decimal('3.14'))
Decimal('3.14')
@end example


Added in version 3.14.

@end deffn

@geindex fma() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal fma}@anchor{2ad1}
@deffn {メソッド} fma (other, third, context=None)

融合積和(fused multiply-add)です。self*other+third を途中結果の積 self*other で丸めを行わずに計算して返します。

@example
>>> Decimal(2).fma(3, 5)
Decimal('11')
@end example
@end deffn

@geindex is_canonical() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_canonical}@anchor{2ad2}
@deffn {メソッド} is_canonical ()

引数が標準的(canonical)ならば @ref{e07,,True} を返し、そうでなければ @ref{d2b,,False} を返します。現在のところ、 @ref{1fe,,Decimal} のインスタンスは常に標準的なのでこのメソッドの結果はいつでも @ref{e07,,True} です。
@end deffn

@geindex is_finite() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_finite}@anchor{2ad3}
@deffn {メソッド} is_finite ()

引数が有限の数値ならば @ref{e07,,True} を、無限大か NaN ならば @ref{d2b,,False} を返します。
@end deffn

@geindex is_infinite() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_infinite}@anchor{2ad4}
@deffn {メソッド} is_infinite ()

引数が正または負の無限大ならば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex is_nan() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_nan}@anchor{2ad5}
@deffn {メソッド} is_nan ()

引数が (無言か発信かは問わず) NaN であれば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex is_normal() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_normal}@anchor{2ad6}
@deffn {メソッド} is_normal (context=None)

引数が `正規(normal)' の有限数値ならば @ref{e07,,True} を返します。引数がゼロ、非正規(subnormal)、無限大または NaN であれば @ref{d2b,,False} を返します。
@end deffn

@geindex is_qnan() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_qnan}@anchor{2ad7}
@deffn {メソッド} is_qnan ()

引数が無言 NaN であれば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex is_signed() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_signed}@anchor{2ad8}
@deffn {メソッド} is_signed ()

引数に負の符号がついていれば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。注意すべきはゼロや NaN なども符号を持ち得ることです。
@end deffn

@geindex is_snan() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_snan}@anchor{2ad9}
@deffn {メソッド} is_snan ()

引数が発信 NaN であれば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex is_subnormal() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_subnormal}@anchor{2ada}
@deffn {メソッド} is_subnormal (context=None)

引数が非正規数(subnormal)であれば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex is_zero() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal is_zero}@anchor{2adb}
@deffn {メソッド} is_zero ()

引数が(正または負の)ゼロであれば @ref{e07,,True} を、そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex ln() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal ln}@anchor{12bf}
@deffn {メソッド} ln (context=None)

演算対象の自然対数(底 e の対数)を返します。結果は @ref{2ab6,,ROUND_HALF_EVEN} 丸めモードで正しく丸められます。
@end deffn

@geindex log10() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal log10}@anchor{2adc}
@deffn {メソッド} log10 (context=None)

演算対象の底 10 の対数を返します。結果は @ref{2ab6,,ROUND_HALF_EVEN} 丸めモードで正しく丸められます。
@end deffn

@geindex logb() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal logb}@anchor{2add}
@deffn {メソッド} logb (context=None)

非零の数値については、 @ref{1fe,,Decimal} インスタンスとして調整された指数を返します。演算対象がゼロだった場合、 @code{Decimal('-Infinity')} が返され @ref{2abb,,DivisionByZero} フラグが送出されます。演算対象が無限大だった場合、 @code{Decimal('Infinity')} が返されます。
@end deffn

@geindex logical_and() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal logical_and}@anchor{2ade}
@deffn {メソッド} logical_and (other, context=None)

@ref{2ade,,logical_and()} は二つの `論理引数' (@ref{2adf,,論理引数} 参照)を取る論理演算です。結果は二つの引数の数字ごとの @code{and} です。
@end deffn

@geindex logical_invert() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal logical_invert}@anchor{2ae0}
@deffn {メソッド} logical_invert (context=None)

@ref{2ae0,,logical_invert()} は論理演算です。結果は引数の数字ごとの反転です。
@end deffn

@geindex logical_or() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal logical_or}@anchor{2ae1}
@deffn {メソッド} logical_or (other, context=None)

@ref{2ae1,,logical_or()} は二つの `論理引数' (@ref{2adf,,論理引数} 参照)を取る論理演算です。結果は二つの引数の数字ごとの @code{or} です。
@end deffn

@geindex logical_xor() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal logical_xor}@anchor{2ae2}
@deffn {メソッド} logical_xor (other, context=None)

@ref{2ae2,,logical_xor()} は二つの `論理引数' (@ref{2adf,,論理引数} 参照)を取る論理演算です。結果は二つの引数の数字ごとの排他的論理和です。
@end deffn

@geindex max() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal max}@anchor{2ae3}
@deffn {メソッド} max (other, context=None)

@code{max(self, other)} と同じですが、値を返す前に現在のコンテキストに即した丸め規則を適用します。また、 @code{NaN} に対して、(コンテキストの設定と、発信か無言どちらのタイプであるかに応じて) シグナルを発行するか無視します。
@end deffn

@geindex max_mag() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal max_mag}@anchor{2ae4}
@deffn {メソッド} max_mag (other, context=None)

@ref{2ae3,,max()} メソッドに似ていますが、比較は絶対値で行われます。
@end deffn

@geindex min() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal min}@anchor{2ae5}
@deffn {メソッド} min (other, context=None)

@code{min(self, other)} と同じですが、値を返す前に現在のコンテキストに即した丸め規則を適用します。また、 @code{NaN} に対して、(コンテキストの設定と、発信か無言どちらのタイプであるかに応じて) シグナルを発行するか無視します。
@end deffn

@geindex min_mag() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal min_mag}@anchor{2ae6}
@deffn {メソッド} min_mag (other, context=None)

@ref{2ae5,,min()} メソッドに似ていますが、比較は絶対値で行われます。
@end deffn

@geindex next_minus() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal next_minus}@anchor{2ae7}
@deffn {メソッド} next_minus (context=None)

与えられたコンテキスト(またはコンテキストが渡されなければ現スレッドのコンテキスト)において表現可能な、操作対象より小さい最大の数を返します。
@end deffn

@geindex next_plus() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal next_plus}@anchor{2ae8}
@deffn {メソッド} next_plus (context=None)

与えられたコンテキスト(またはコンテキストが渡されなければ現スレッドのコンテキスト)において表現可能な、操作対象より大きい最小の数を返します。
@end deffn

@geindex next_toward() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal next_toward}@anchor{2ae9}
@deffn {メソッド} next_toward (other, context=None)

二つの比較対象が等しくなければ、一つめの対象に最も近く二つめの対象へ近付く方向の数を返します。もし両者が数値的に等しければ、二つめの対象の符号を採った一つめの対象のコピーを返します。
@end deffn

@geindex normalize() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal normalize}@anchor{2aea}
@deffn {メソッド} normalize (context=None)

Used for producing canonical values of an equivalence
class within either the current context or the specified context.

This has the same semantics as the unary plus operation, except that if
the final result is finite it is reduced to its simplest form, with all
trailing zeros removed and its sign preserved. That is, while the
coefficient is non-zero and a multiple of ten the coefficient is divided
by ten and the exponent is incremented by 1. Otherwise (the coefficient is
zero) the exponent is set to 0. In all cases the sign is unchanged.

For example, @code{Decimal('32.100')} and @code{Decimal('0.321000e+2')} both
normalize to the equivalent value @code{Decimal('32.1')}.

Note that rounding is applied `before' reducing to simplest form.

In the latest versions of the specification, this operation is also known
as @code{reduce}.
@end deffn

@geindex number_class() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal number_class}@anchor{2aeb}
@deffn {メソッド} number_class (context=None)

操作対象の `クラス' を表す文字列を返します。返されるのは以下の10種類のいずれかです。


@itemize *

@item 
@code{"-Infinity"}, 負の無限大であることを示します。

@item 
@code{"-Normal"}, 負の通常数であることを示します。

@item 
@code{"-Subnormal"}, 負の非正規数であることを示します。

@item 
@code{"-Zero"}, 負のゼロであることを示します。

@item 
@code{"+Zero"}, 正のゼロであることを示します。

@item 
@code{"+Subnormal"}, 正の非正規数であることを示します。

@item 
@code{"+Normal"}, 正の通常数であることを示します。

@item 
@code{"+Infinity"}, 正の無限大であることを示します。

@item 
@code{"NaN"}, 無言 (quiet) NaN (Not a Number) であることを示します。

@item 
@code{"sNaN"}, 発信(signaling) NaN であることを示します。
@end itemize
@end deffn

@geindex quantize() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal quantize}@anchor{12c4}
@deffn {メソッド} quantize (exp, rounding=None, context=None)

二つ目の操作対象と同じ指数を持つように丸めを行った、一つめの操作対象と等しい値を返します。

@example
>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')
@end example

他の操作と違い、打ち切り(quantize)操作後の係数の長さが精度を越えた場合には、 @ref{12bc,,InvalidOperation} がシグナルされます。これによりエラー条件がない限り打ち切られた指数が常に右側の引数と同じになることが保証されます。

同様に、他の操作と違い、quantize は Underflow を、たとえ結果が非正規になったり不正確になったとしても、シグナルしません。

二つ目の演算対象の指数が一つ目のそれよりも大きければ丸めが必要かもしれません。この場合、丸めモードは以下のように決められます。@code{rounding} 引数が与えられていればそれが使われます。そうでなければ @code{context} 引数で決まります。どちらの引数も渡されなければ現在のスレッドのコンテキストの丸めモードが使われます。

処理結果の指数が @ref{12ba,,Emax} よりも大きい場合や @ref{2aec,,Etiny()} よりも小さい場合にエラーが返されます。
@end deffn

@geindex radix() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal radix}@anchor{2aed}
@deffn {メソッド} radix ()

@code{Decimal(10)} つまり @ref{1fe,,Decimal} クラスがその全ての算術を実行する基数を返します。仕様との互換性のために取り入れられています。
@end deffn

@geindex remainder_near() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal remainder_near}@anchor{2aee}
@deffn {メソッド} remainder_near (other, context=None)

`self' を `other' で割った剰余を返します。これは @code{self % other} とは違って、剰余の絶対値を小さくするように符号が選ばれます。より詳しく言うと、@code{n} を @code{self / other} の正確な値に最も近い整数としたときの @code{self - n * other} が返り値になります。最も近い整数が2つある場合には偶数のものが選ばれます。

結果が0になる場合の符号は `self' の符号と同じになります。

@example
>>> Decimal(18).remainder_near(Decimal(10))
Decimal('-2')
>>> Decimal(25).remainder_near(Decimal(10))
Decimal('5')
>>> Decimal(35).remainder_near(Decimal(10))
Decimal('-5')
@end example
@end deffn

@geindex rotate() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal rotate}@anchor{2aef}
@deffn {メソッド} rotate (other, context=None)

一つ目の演算対象の数字を二つ目で指定された量だけ巡回(rotate)した結果を返します。二つめの演算対象は -precision から precision までの範囲の整数でなければなりません。この二つ目の演算対象の絶対値を何桁ずらすかを決めます。そしてもし正の数ならば巡回の方向は左に、そうでなければ右になります。一つ目の演算対象の仮数部は必要ならば精度いっぱいまでゼロで埋められます。符号と指数は変えられません。
@end deffn

@geindex same_quantum() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal same_quantum}@anchor{2af0}
@deffn {メソッド} same_quantum (other, context=None)

`self' と `other' が同じ指数を持っているか、あるいは双方とも @code{NaN} である場合に真を返します。

この演算はコンテキストに影響されず、静かです。すなわち、フラグは変更されず、丸めは行われません。例外として、2番目の比較対象の厳密な変換ができない場合、C バージョンのライブラリでは InvalidOperation 例外を送出するかもしれません。
@end deffn

@geindex scaleb() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal scaleb}@anchor{2af1}
@deffn {メソッド} scaleb (other, context=None)

二つ目の演算対象で調整された指数の一つ目の演算対象を返します。同じことですが、一つめの演算対象を @code{10**other} 倍したものを返します。二つ目の演算対象は整数でなければなりません。
@end deffn

@geindex shift() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal shift}@anchor{2af2}
@deffn {メソッド} shift (other, context=None)

一つ目の演算対象の数字を二つ目で指定された量だけシフトした結果を返します。二つ目の演算対象は -precision から precision までの範囲の整数でなければなりません。この二つ目の演算対象の絶対値が何桁ずらすかを決めます。そしてもし正の数ならばシフトの方向は左に、そうでなければ右になります。一つ目の演算対象の係数は必要ならば精度いっぱいまでゼロで埋められます。符号と指数は変えられません。
@end deffn

@geindex sqrt() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal sqrt}@anchor{2af3}
@deffn {メソッド} sqrt (context=None)

引数の平方根を最大精度で求めます。
@end deffn

@geindex to_eng_string() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal to_eng_string}@anchor{2af4}
@deffn {メソッド} to_eng_string (context=None)

文字列に変換します。指数が必要なら工学表記が使われます。

工学表記法では指数は 3 の倍数になります。これにより、基数の小数部には最大で 3 桁までの数字が残されるとともに、末尾に 1 つまたは 2 つの 0 の付加が必要とされるかもしれません。

たとえば、@code{Decimal('123E+1')} は @code{Decimal('1.23E+3')} に変換されます。
@end deffn

@geindex to_integral() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal to_integral}@anchor{2af5}
@deffn {メソッド} to_integral (rounding=None, context=None)

@ref{2af6,,to_integral_value()} メソッドと同じです。@code{to_integral} の名前は古いバージョンとの互換性のために残されています。
@end deffn

@geindex to_integral_exact() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal to_integral_exact}@anchor{2af7}
@deffn {メソッド} to_integral_exact (rounding=None, context=None)

最近傍の整数に値を丸め、丸めが起こった場合には @ref{2abc,,Inexact} または @ref{2abd,,Rounded} のシグナルを適切に出します。丸めモードは以下のように決められます。 @code{rounding} 引数が与えられていればそれが使われます。そうでなければ @code{context} 引数で決まります。どちらの引数も渡されなければ現在のスレッドのコンテキストの丸めモードが使われます。
@end deffn

@geindex to_integral_value() (decimal.Decimal のメソッド)
@anchor{library/decimal decimal Decimal to_integral_value}@anchor{2af6}
@deffn {メソッド} to_integral_value (rounding=None, context=None)

@ref{2abc,,Inexact} や @ref{2abd,,Rounded} といったシグナルを出さずに最近傍の整数に値を丸めます。 `rounding' が指定されていれば適用されます; それ以外の場合、値丸めの方法は `context' の設定か現在のコンテキストの設定になります。
@end deffn

Decimal numbers can be rounded using the @ref{14f2,,round()} function:


@deffn {Describe} round(number)
@end deffn


@deffn {Describe} round(number, ndigits)

If `ndigits' is not given or @code{None},
returns the nearest @ref{19b,,int} to `number',
rounding ties to even, and ignoring the rounding mode of the
@ref{1fe,,Decimal} context.  Raises @ref{a81,,OverflowError} if `number' is an
infinity or @ref{2ec,,ValueError} if it is a (quiet or signaling) NaN.

If `ndigits' is an @ref{19b,,int}, the context's rounding mode is respected
and a @ref{1fe,,Decimal} representing `number' rounded to the nearest
multiple of @code{Decimal('1E-ndigits')} is returned; in this case,
@code{round(number, ndigits)} is equivalent to
@code{self.quantize(Decimal('1E-ndigits'))}.  Returns @code{Decimal('NaN')} if
`number' is a quiet NaN.  Raises @ref{12bc,,InvalidOperation} if `number'
is an infinity, a signaling NaN, or if the length of the coefficient after
the quantize operation would be greater than the current context's
precision.  In other words, for the non-corner cases:


@itemize *

@item 
if `ndigits' is positive, return `number' rounded to `ndigits' decimal
places;

@item 
if `ndigits' is zero, return `number' rounded to the nearest integer;

@item 
if `ndigits' is negative, return `number' rounded to the nearest
multiple of @code{10**abs(ndigits)}.
@end itemize

例えば:

@example
>>> from decimal import Decimal, getcontext, ROUND_DOWN
>>> getcontext().rounding = ROUND_DOWN
>>> round(Decimal('3.75'))     # context rounding ignored
4
>>> round(Decimal('3.5'))      # round-ties-to-even
4
>>> round(Decimal('3.75'), 0)  # uses the context rounding
Decimal('3')
>>> round(Decimal('3.75'), 1)
Decimal('3.7')
>>> round(Decimal('3.75'), -1)
Decimal('0E+1')
@end example
@end deffn
@end deffn

@menu
* 論理引数:: 

@end menu

@node 論理引数,,,Decimal オブジェクト
@anchor{library/decimal logical-operands}@anchor{2af8}@anchor{library/decimal logical-operands-label}@anchor{2adf}
@subsubsection 論理引数


@ref{2ade,,logical_and()}, @ref{2ae0,,logical_invert()}, @ref{2ae1,,logical_or()}, および @ref{2ae2,,logical_xor()} メソッドはその引数が `論理引数' であると想定しています。 `論理引数' とは @ref{1fe,,Decimal} インスタンスで指数と符号は共にゼロであり、各桁の数字が @code{0} か @code{1} であるものです。

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node Context オブジェクト,定数<4>,Decimal オブジェクト,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal context-objects}@anchor{2af9}@anchor{library/decimal decimal-context}@anchor{2747}
@subsubsection Context オブジェクト


コンテキスト (context) とは、算術演算における環境設定です。コンテキストは計算精度を決定し、値丸めの方法を設定し、シグナルのどれが例外になるかを決め、指数の範囲を制限しています。

多重スレッドで処理を行う場合には各スレッドごとに現在のコンテキストがあり、 @ref{1937,,getcontext()} や @ref{2ac2,,setcontext()} といった関数でアクセスしたり設定変更できます:

@geindex getcontext() (decimal モジュール)
@anchor{library/decimal decimal getcontext}@anchor{1937}
@deffn {の関数} decimal.getcontext ()

アクティブなスレッドの現在のコンテキストを返します。
@end deffn

@geindex setcontext() (decimal モジュール)
@anchor{library/decimal decimal setcontext}@anchor{2ac2}
@deffn {の関数} decimal.setcontext (c, /)

アクティブなスレッドのコンテキストを `c' に設定します。
@end deffn

@ref{186,,with} 文と @ref{159e,,localcontext()} 関数を使って実行するコンテキストを一時的に変更することもできます。

@geindex localcontext() (decimal モジュール)
@anchor{library/decimal decimal localcontext}@anchor{159e}
@deffn {の関数} decimal.localcontext (ctx=None, **kwargs)

with 文の入口でアクティブなスレッドのコンテキストを `ctx' のコピーに設定し、with 文を抜ける時に元のコンテキストに復旧する、コンテキストマネージャを返します。コンテキストが指定されなければ、現在のコンテキストのコピーが使われます。`kwargs' 引数は新しいコンテキストの属性を設定するのに使われます。

たとえば、以下のコードでは精度を42桁に設定し、計算を実行し、そして元のコンテキストに復帰します:

@example
from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision
@end example

Using keyword arguments, the code would be the following:

@example
from decimal import localcontext

with localcontext(prec=42) as ctx:
    s = calculate_something()
s = +s
@end example

Raises @ref{198,,TypeError} if `kwargs' supplies an attribute that @ref{12c3,,Context} doesn't
support.  Raises either @ref{198,,TypeError} or @ref{2ec,,ValueError} if `kwargs' supplies an
invalid value for an attribute.


バージョン 3.11 で変更: @ref{159e,,localcontext()} now supports setting context attributes through the use of keyword arguments.

@end deffn

@geindex IEEEContext() (decimal モジュール)
@anchor{library/decimal decimal IEEEContext}@anchor{1ff}
@deffn {の関数} decimal.IEEEContext (bits)

Return a context object initialized to the proper values for one of the
IEEE interchange formats.  The argument must be a multiple of 32 and less
than @ref{2afa,,IEEE_CONTEXT_MAX_BITS}.


Added in version 3.14.

@end deffn

新たなコンテキストは、以下で説明する @ref{12c3,,Context} コンストラクタを使って生成できます。その他にも、 @ref{3a,,decimal} モジュールでは作成済みのコンテキストを提供しています:

@geindex BasicContext (decimal モジュール)
@anchor{library/decimal decimal BasicContext}@anchor{12b8}
@deffn {データ} decimal.BasicContext

汎用十進演算仕様で定義されている標準コンテキストの一つです。精度は 9 桁に設定されています。丸め規則は @ref{2ab7,,ROUND_HALF_UP} です。すべての演算結果フラグはクリアされています。 @ref{2abc,,Inexact}, @ref{2abd,,Rounded}, @ref{2abe,,Subnormal} を除く全ての演算エラートラップが有効 (例外として扱う) になっています。

多くのトラップが有効になっているので、デバッグの際に便利なコンテキストです。
@end deffn

@geindex ExtendedContext (decimal モジュール)
@anchor{library/decimal decimal ExtendedContext}@anchor{12b9}
@deffn {データ} decimal.ExtendedContext

汎用十進演算仕様で定義されている標準コンテキストの一つです。精度は 9 桁に設定されています。丸め規則は @ref{2ab6,,ROUND_HALF_EVEN} です。すべての演算結果フラグはクリアされています。トラップは全て無効(演算中に一切例外を送出しない) になっています。

トラップが無効になっているので、エラーの伴う演算結果を @code{NaN} や @code{Infinity} にし、例外を送出しないようにしたいアプリケーションに向いたコンテキストです。このコンテキストを使うと、他の場合にはプログラムが停止してしまうような状況があっても実行を完了させられます。
@end deffn

@geindex DefaultContext (decimal モジュール)
@anchor{library/decimal decimal DefaultContext}@anchor{12b7}
@deffn {データ} decimal.DefaultContext

@ref{12c3,,Context} コンストラクタが新たなコンテキストを作成するさいに雛形にするコンテキストです。このコンテキストのフィールド (精度の設定など) を変更すると、 @ref{12c3,,Context} コンストラクタが生成する新たなコンテキストに影響を及ぼします。

このコンテキストは、主に多重スレッド環境で便利です。スレッドを開始する前に何らかのフィールドを変更しておくと、システム全体のデフォルト設定に効果を及ぼすことができます。スレッドを開始した後にフィールドを変更すると、競合条件を抑制するためにスレッドを同期化しなければならないので、推奨しません。

単一スレッドの環境では、このコンテキストを使わないよう薦めます。下で述べるように明示的にコンテキストを作成してください。

デフォルトの値は、 @ref{2afb,,Context.prec}=@code{28}, @ref{2afc,,Context.rounding}=@ref{2ab6,,ROUND_HALF_EVEN} で、トラップ @ref{2abf,,Overflow}, @ref{12bc,,InvalidOperation}, および @ref{2abb,,DivisionByZero} が有効になっています。
@end deffn

上に挙げた三つのコンテキストに加え、 @ref{12c3,,Context} コンストラクタを使って新たなコンテキストを生成できます。

@geindex Context (decimal のクラス)
@anchor{library/decimal decimal Context}@anchor{12c3}
@deffn {クラス} decimal.Context (prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)

新たなコンテキストを生成します。あるフィールドが定義されていないか @ref{885,,None} であれば、 @ref{12b7,,DefaultContext} からデフォルト値をコピーします。 `flags' フィールドが設定されていいか @ref{885,,None} の場合には、全てのフラグがクリアされます。

@geindex prec (decimal.Context の属性)
@anchor{library/decimal decimal Context prec}@anchor{2afb}
@deffn {の属性} prec

An integer in the range [@code{1}, @ref{12b4,,MAX_PREC}] that sets
the precision for arithmetic operations in the context.
@end deffn

@geindex rounding (decimal.Context の属性)
@anchor{library/decimal decimal Context rounding}@anchor{2afc}
@deffn {の属性} rounding

One of the constants listed in the section @ref{2afd,,Rounding Modes}.
@end deffn

@geindex traps (decimal.Context の属性)
@geindex flags (decimal.Context の属性)
@anchor{library/decimal decimal Context traps}@anchor{12c2}
@deffn {の属性} traps
@anchor{library/decimal decimal Context flags}@anchor{12c1}
@deffnx {の属性} flags

Lists of any signals to be set. Generally, new contexts should only set
traps and leave the flags clear.
@end deffn

@geindex Emin (decimal.Context の属性)
@geindex Emax (decimal.Context の属性)
@anchor{library/decimal decimal Context Emin}@anchor{12bb}
@deffn {の属性} Emin
@anchor{library/decimal decimal Context Emax}@anchor{12ba}
@deffnx {の属性} Emax

Integers specifying the outer limits allowable for exponents. `Emin' must
be in the range [@ref{12b6,,MIN_EMIN}, @code{0}], `Emax' in the range
[@code{0}, @ref{12b5,,MAX_EMAX}].
@end deffn

@geindex capitals (decimal.Context の属性)
@anchor{library/decimal decimal Context capitals}@anchor{2afe}
@deffn {の属性} capitals

Either @code{0} or @code{1} (the default). If set to
@code{1}, exponents are printed with a capital @code{E}; otherwise, a
lowercase @code{e} is used: @code{Decimal('6.02e+23')}.
@end deffn

@geindex clamp (decimal.Context の属性)
@anchor{library/decimal decimal Context clamp}@anchor{13b6}
@deffn {の属性} clamp

Either @code{0} (the default) or @code{1}.  If set to @code{1}, the exponent @code{e}
of a @ref{1fe,,Decimal} instance representable in this context is strictly
limited to the range @code{Emin - prec + 1 <= e <= Emax - prec + 1}.
If `clamp' is @code{0} then a weaker condition holds: the adjusted exponent of
the @ref{1fe,,Decimal} instance is at most @ref{12ba,,Emax}.  When `clamp' is
@code{1}, a large normal number will, where possible, have its
exponent reduced and a corresponding number of zeros added to its
coefficient, in order to fit the exponent constraints; this
preserves the value of the number but loses information about
significant trailing zeros.  For example:

@example
>>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
Decimal('1.23000E+999')
@end example

`clamp' の値 @code{1} は、IEEE 754 で規定された固定幅十進交換形式と互換にできます。
@end deffn

@ref{12c3,,Context} クラスでは、いくつかの汎用のメソッドの他、現在のコンテキストで算術演算を直接行うためのメソッドを数多く定義しています。加えて、 @ref{1fe,,Decimal} の各メソッドについて(@ref{2ac6,,adjusted()} および @ref{2ac7,,as_tuple()} メソッドを例外として)対応する @ref{12c3,,Context} のメソッドが存在します。たとえば、 @ref{12c3,,Context} インスタンス  @code{C} と @ref{1fe,,Decimal} インスタンス @code{x} に対して、 @code{C.exp(x)} は @code{x.exp(context=C)} と等価です。それぞれの @ref{12c3,,Context} メソッドは、Decimal インスタンスが受け付けられるところならどこでも、Python の整数 (@ref{19b,,int} のインスタンス) を受け付けます。

@geindex clear_flags() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context clear_flags}@anchor{2ac3}
@deffn {メソッド} clear_flags ()

フラグを全て @code{0} にリセットします。
@end deffn

@geindex clear_traps() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context clear_traps}@anchor{2aff}
@deffn {メソッド} clear_traps ()

トラップを全て @code{0} にリセットします。


Added in version 3.3.

@end deffn

@geindex copy() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context copy}@anchor{2b00}
@deffn {メソッド} copy ()

コンテキストの複製を返します。
@end deffn

@geindex copy_decimal() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context copy_decimal}@anchor{2b01}
@deffn {メソッド} copy_decimal (num, /)

Decimal インスタンス num のコピーを返します。
@end deffn

@geindex create_decimal() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context create_decimal}@anchor{12bd}
@deffn {メソッド} create_decimal (num='0', /)

`self' をコンテキストとする新たな Decimal インスタンスを `num' から生成します。 @ref{1fe,,Decimal} コンストラクタと違い、数値を変換する際にコンテキストの精度、値丸め方法、フラグ、トラップを適用します。

定数値はしばしばアプリケーションの要求よりも高い精度を持っているため、このメソッドが役に立ちます。また、値丸めを即座に行うため、例えば以下のように、入力値に値丸めを行わないために合計値にゼロの加算を追加するだけで結果が変わってしまうといった、現在の精度よりも細かい値の影響が紛れ込む問題を防げるという恩恵もあります。以下の例は、丸められていない入力を使うということは和にゼロを加えると結果が変わり得るという見本です:

@example
>>> getcontext().prec = 3
>>> Decimal('3.4445') + Decimal('1.0023')
Decimal('4.45')
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Decimal('4.44')
@end example

このメソッドは IBM 仕様の to-number 演算を実装したものです。引数が文字列の場合、前や後ろに余計な空白を付けたり、アンダースコアを含めたりすることは許されません。
@end deffn

@geindex create_decimal_from_float() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context create_decimal_from_float}@anchor{2b02}
@deffn {メソッド} create_decimal_from_float (f, /)

浮動小数点数 `f' から新しい Decimal インスタンスを生成しますが、 `self' をコンテキストとして丸めます。 @ref{141d,,Decimal.from_float()} クラスメソッドとは違い、変換にコンテキストの精度、丸めメソッド、フラグ、そしてトラップが適用されます。

@example
>>> context = Context(prec=5, rounding=ROUND_DOWN)
>>> context.create_decimal_from_float(math.pi)
Decimal('3.1415')
>>> context = Context(prec=5, traps=[Inexact])
>>> context.create_decimal_from_float(math.pi)
Traceback (most recent call last):
    ...
decimal.Inexact: None
@end example


Added in version 3.1.

@end deffn

@geindex Etiny() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context Etiny}@anchor{2aec}
@deffn {メソッド} Etiny ()

@code{Emin - prec + 1} に等しい値を返します。演算結果の劣化が起こる桁の最小値です。アンダーフローが起きた場合、指数は @ref{2aec,,Etiny} に設定されます。
@end deffn

@geindex Etop() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context Etop}@anchor{2b03}
@deffn {メソッド} Etop ()

@code{Emax - prec + 1} に等しい値を返します。
@end deffn

@ref{1fe,,Decimal} を使った処理を行う場合、通常は @ref{1fe,,Decimal} インスタンスを生成して、算術演算を適用するというアプローチをとります。演算はアクティブなスレッドにおける現在のコンテキストの下で行われます。もう一つのアプローチは、コンテキストのメソッドを使った特定のコンテキスト下での計算です。コンテキストのメソッドは @ref{1fe,,Decimal} クラスのメソッドに似ているので、ここでは簡単な説明にとどめます。

@geindex abs() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context abs}@anchor{2b04}
@deffn {メソッド} abs (x, /)

`x' の絶対値を返します。
@end deffn

@geindex add() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context add}@anchor{2b05}
@deffn {メソッド} add (x, y, /)

`x' と `y' の和を返します。
@end deffn

@geindex canonical() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context canonical}@anchor{151e}
@deffn {メソッド} canonical (x, /)

同じ Decimal オブジェクト `x' を返します。
@end deffn

@geindex compare() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context compare}@anchor{2b06}
@deffn {メソッド} compare (x, y, /)

`x' と `y' を数値として比較します。
@end deffn

@geindex compare_signal() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context compare_signal}@anchor{2b07}
@deffn {メソッド} compare_signal (x, y, /)

二つの演算対象の値を数値として比較します。
@end deffn

@geindex compare_total() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context compare_total}@anchor{2b08}
@deffn {メソッド} compare_total (x, y, /)

二つの演算対象を抽象的な表現を使って比較します。
@end deffn

@geindex compare_total_mag() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context compare_total_mag}@anchor{2b09}
@deffn {メソッド} compare_total_mag (x, y, /)

二つの演算対象を抽象的な表現を使い符号を無視して比較します。
@end deffn

@geindex copy_abs() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context copy_abs}@anchor{2b0a}
@deffn {メソッド} copy_abs (x, /)

`x' のコピーの符号を 0 にセットして返します。
@end deffn

@geindex copy_negate() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context copy_negate}@anchor{2b0b}
@deffn {メソッド} copy_negate (x, /)

`x' のコピーの符号を反転して返します。
@end deffn

@geindex copy_sign() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context copy_sign}@anchor{2b0c}
@deffn {メソッド} copy_sign (x, y, /)

`y' から `x' に符号をコピーします。
@end deffn

@geindex divide() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context divide}@anchor{2b0d}
@deffn {メソッド} divide (x, y, /)

`x' を `y' で除算した値を返します。
@end deffn

@geindex divide_int() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context divide_int}@anchor{2b0e}
@deffn {メソッド} divide_int (x, y, /)

`x' を `y' で除算した値を整数に切り捨てて返します。
@end deffn

@geindex divmod() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context divmod}@anchor{2b0f}
@deffn {メソッド} divmod (x, y, /)

二つの数値間の除算を行い、結果の整数部を返します。
@end deffn

@geindex exp() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context exp}@anchor{2b10}
@deffn {メソッド} exp (x, /)

@code{e ** x} を返します。
@end deffn

@geindex fma() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context fma}@anchor{2b11}
@deffn {メソッド} fma (x, y, z, /)

`x' を `y' 倍したものに `z' を加えて返します。
@end deffn

@geindex is_canonical() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_canonical}@anchor{151f}
@deffn {メソッド} is_canonical (x, /)

`x' が標準的(canonical)ならば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_finite() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_finite}@anchor{2b12}
@deffn {メソッド} is_finite (x, /)

`x' が有限ならば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_infinite() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_infinite}@anchor{2b13}
@deffn {メソッド} is_infinite (x, /)

`x' が無限ならば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_nan() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_nan}@anchor{2b14}
@deffn {メソッド} is_nan (x, /)

`x' が qNaN か sNaN であれば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_normal() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_normal}@anchor{2b15}
@deffn {メソッド} is_normal (x, /)

`x' が通常の数ならば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_qnan() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_qnan}@anchor{2b16}
@deffn {メソッド} is_qnan (x, /)

`x' が無言 NaN であれば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_signed() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_signed}@anchor{2b17}
@deffn {メソッド} is_signed (x, /)

`x' が負の数であれば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_snan() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_snan}@anchor{2b18}
@deffn {メソッド} is_snan (x, /)

`x' が発信 NaN であれば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_subnormal() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_subnormal}@anchor{2b19}
@deffn {メソッド} is_subnormal (x, /)

`x' が非正規数であれば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex is_zero() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context is_zero}@anchor{2b1a}
@deffn {メソッド} is_zero (x, /)

`x' がゼロであれば @code{True} を返します。そうでなければ @code{False} です。
@end deffn

@geindex ln() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context ln}@anchor{2b1b}
@deffn {メソッド} ln (x, /)

`x' の自然対数(底 e の対数)を返します。
@end deffn

@geindex log10() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context log10}@anchor{2b1c}
@deffn {メソッド} log10 (x, /)

`x' の底 10 の対数を返します。
@end deffn

@geindex logb() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context logb}@anchor{2b1d}
@deffn {メソッド} logb (x, /)

演算対象の MSD の大きさの指数部を返します。
@end deffn

@geindex logical_and() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context logical_and}@anchor{2b1e}
@deffn {メソッド} logical_and (x, y, /)

それぞれの桁に論理演算 `and' を当てはめます。
@end deffn

@geindex logical_invert() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context logical_invert}@anchor{2b1f}
@deffn {メソッド} logical_invert (x, /)

`x' の全ての桁を反転させます。
@end deffn

@geindex logical_or() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context logical_or}@anchor{2b20}
@deffn {メソッド} logical_or (x, y, /)

それぞれの桁に論理演算 `or' を当てはめます。
@end deffn

@geindex logical_xor() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context logical_xor}@anchor{2b21}
@deffn {メソッド} logical_xor (x, y, /)

それぞれの桁に論理演算 `xor' を当てはめます。
@end deffn

@geindex max() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context max}@anchor{2b22}
@deffn {メソッド} max (x, y, /)

二つの値を数値として比較し、大きいほうを返します。
@end deffn

@geindex max_mag() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context max_mag}@anchor{2b23}
@deffn {メソッド} max_mag (x, y, /)

値を符号を無視して数値として比較します。
@end deffn

@geindex min() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context min}@anchor{2b24}
@deffn {メソッド} min (x, y, /)

二つの値を数値として比較し、小さいほうを返します。
@end deffn

@geindex min_mag() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context min_mag}@anchor{2b25}
@deffn {メソッド} min_mag (x, y, /)

値を符号を無視して数値として比較します。
@end deffn

@geindex minus() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context minus}@anchor{2b26}
@deffn {メソッド} minus (x, /)

Python における単項マイナス演算子に対応する演算です。
@end deffn

@geindex multiply() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context multiply}@anchor{2b27}
@deffn {メソッド} multiply (x, y, /)

`x' と `y' の積を返します。
@end deffn

@geindex next_minus() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context next_minus}@anchor{2b28}
@deffn {メソッド} next_minus (x, /)

`x' より小さい最大の表現可能な数を返します。
@end deffn

@geindex next_plus() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context next_plus}@anchor{2b29}
@deffn {メソッド} next_plus (x, /)

`x' より大きい最小の表現可能な数を返します。
@end deffn

@geindex next_toward() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context next_toward}@anchor{2b2a}
@deffn {メソッド} next_toward (x, y, /)

`x' に `y' の方向に向かって最も近い数を返します。
@end deffn

@geindex normalize() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context normalize}@anchor{2b2b}
@deffn {メソッド} normalize (x, /)

`x' をもっとも単純な形にします。
@end deffn

@geindex number_class() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context number_class}@anchor{2b2c}
@deffn {メソッド} number_class (x, /)

`x' のクラスを指し示すものを返します。
@end deffn

@geindex plus() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context plus}@anchor{2b2d}
@deffn {メソッド} plus (x, /)

Python における単項のプラス演算子に対応する演算です。コンテキストにおける精度や値丸めを適用するので、等値 (identity) 演算とは `違います'。
@end deffn

@geindex power() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context power}@anchor{2b2e}
@deffn {メソッド} power (x, y, modulo=None)

@code{x} の @code{y} 乗を計算します。@code{modulo} が指定されていればモジュロを取ります。

引数が 2 つの場合、 @code{x**y} を計算します。@code{x} が負の場合、 @code{y} は整数でなければなりません。@code{y} が整数、結果が有限、結果が 'precision' 桁で正確に表現できる、という条件をすべて満たさない場合、結果は不正確になります。結果はコンテキストの丸めモードを使って丸められます。結果は常に、Python バージョンにおいて正しく丸められます。

@code{Decimal(0) ** Decimal(0)} results in @code{InvalidOperation}, and if @code{InvalidOperation}
is not trapped, then results in @code{Decimal('NaN')}.


バージョン 3.3 で変更: C モジュールは @ref{2b2e,,power()} を適切に丸められた @ref{2b10,,exp()} および @ref{2b1b,,ln()} 関数によって計算します。結果は well-defined ですが、「ほとんどの場合には適切に丸められる」だけです。


引数が 3 つの場合、 @code{(x**y) % modulo} を計算します。この 3 引数の形式の場合、引数には以下の制限が課せられます。


@itemize -

@item 
全ての引数は整数

@item 
@code{y} は非負でなければならない

@item 
@code{x} と @code{y} の少なくともどちらかはゼロでない

@item 
@code{modulo} は非零で大きくても 'precision' 桁
@end itemize

@code{Context.power(x, y, modulo)} で得られる値は @code{(x**y) % modulo} を精度無制限で計算して得られるものと同じ値ですが、より効率的に計算されます。結果の指数は @code{x}, @code{y}, @code{modulo} の指数に関係なくゼロです。この計算は常に正確です。
@end deffn

@geindex quantize() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context quantize}@anchor{2b2f}
@deffn {メソッド} quantize (x, y, /)

`x' に値丸めを適用し、指数を `y' にした値を返します。
@end deffn

@geindex radix() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context radix}@anchor{2b30}
@deffn {メソッド} radix ()

単に 10 を返します。何せ十進ですから :)
@end deffn

@geindex remainder() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context remainder}@anchor{2b31}
@deffn {メソッド} remainder (x, y, /)

整数除算の剰余を返します。

剰余がゼロでない場合、符号は割られる数の符号と同じになります。
@end deffn

@geindex remainder_near() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context remainder_near}@anchor{2b32}
@deffn {メソッド} remainder_near (x, y, /)

@code{x - y * n} を返します。ここで `n' は @code{x / y} の正確な値に一番近い整数です (この結果が 0 ならばその符号は `x' の符号と同じです)。
@end deffn

@geindex rotate() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context rotate}@anchor{2b33}
@deffn {メソッド} rotate (x, y, /)

`x' の `y' 回巡回したコピーを返します。
@end deffn

@geindex same_quantum() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context same_quantum}@anchor{2b34}
@deffn {メソッド} same_quantum (x, y, /)

2つの演算対象が同じ指数を持っている場合に @code{True} を返します。
@end deffn

@geindex scaleb() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context scaleb}@anchor{2b35}
@deffn {メソッド} scaleb (x, y, /)

一つめの演算対象の指数部に二つめの値を加えたものを返します。
@end deffn

@geindex shift() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context shift}@anchor{2b36}
@deffn {メソッド} shift (x, y, /)

`x' を `y' 回シフトしたコピーを返します。
@end deffn

@geindex sqrt() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context sqrt}@anchor{2b37}
@deffn {メソッド} sqrt (x, /)

`x' の平方根を精度いっぱいまで求めます。
@end deffn

@geindex subtract() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context subtract}@anchor{2b38}
@deffn {メソッド} subtract (x, y, /)

`x' と `y' の間の差を返します。
@end deffn

@geindex to_eng_string() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context to_eng_string}@anchor{2b39}
@deffn {メソッド} to_eng_string (x, /)

文字列に変換します。指数が必要なら工学表記が使われます。

工学表記法では指数は 3 の倍数になります。これにより、基数の小数部には最大で 3 桁までの数字が残されるとともに、末尾に 1 つまたは 2 つの 0 の付加が必要とされるかもしれません。
@end deffn

@geindex to_integral_exact() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context to_integral_exact}@anchor{2b3a}
@deffn {メソッド} to_integral_exact (x, /)

最近傍の整数に値を丸めます。
@end deffn

@geindex to_sci_string() (decimal.Context のメソッド)
@anchor{library/decimal decimal Context to_sci_string}@anchor{2b3b}
@deffn {メソッド} to_sci_string (x, /)

数値を科学表記で文字列に変換します。
@end deffn
@end deffn

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node 定数<4>,丸めモード,Context オブジェクト,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal constants}@anchor{2b3c}@anchor{library/decimal decimal-rounding-modes}@anchor{2b3d}
@subsubsection 定数


この節の定数は C モジュールにのみ意味があります。互換性のために、pure Python 版も含まれます。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@tab

32-bit

@tab

64-bit

@item

@geindex MAX_PREC (decimal モジュール)
@anchor{library/decimal decimal MAX_PREC}@anchor{12b4}
@deffn {データ} decimal.MAX_PREC
@end deffn

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@geindex MAX_EMAX (decimal モジュール)
@anchor{library/decimal decimal MAX_EMAX}@anchor{12b5}
@deffn {データ} decimal.MAX_EMAX
@end deffn

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@geindex MIN_EMIN (decimal モジュール)
@anchor{library/decimal decimal MIN_EMIN}@anchor{12b6}
@deffn {データ} decimal.MIN_EMIN
@end deffn

@tab

@code{-425000000}

@tab

@code{-999999999999999999}

@item

@geindex MIN_ETINY (decimal モジュール)
@anchor{library/decimal decimal MIN_ETINY}@anchor{2b3e}
@deffn {データ} decimal.MIN_ETINY
@end deffn

@tab

@code{-849999999}

@tab

@code{-1999999999999999997}

@item

@geindex IEEE_CONTEXT_MAX_BITS (decimal モジュール)
@anchor{library/decimal decimal IEEE_CONTEXT_MAX_BITS}@anchor{2afa}
@deffn {データ} decimal.IEEE_CONTEXT_MAX_BITS
@end deffn

@tab

@code{256}

@tab

@code{512}

@end multitable


@geindex HAVE_THREADS (decimal モジュール)
@anchor{library/decimal decimal HAVE_THREADS}@anchor{12b2}
@deffn {データ} decimal.HAVE_THREADS

値は @code{True} です。現在のPythonは常にスレッドを持っているので、非推奨になりました。


バージョン 3.9 で非推奨.

@end deffn

@geindex HAVE_CONTEXTVAR (decimal モジュール)
@anchor{library/decimal decimal HAVE_CONTEXTVAR}@anchor{2169}
@deffn {データ} decimal.HAVE_CONTEXTVAR

The default value is @code{True}. If Python is @ref{2168,,configured using the --without-decimal-contextvar option},
the C version uses a thread-local rather than a coroutine-local context and the value
is @code{False}.  This is slightly faster in some nested context scenarios.


Added in version 3.8.3.

@end deffn

@node 丸めモード,シグナル,定数<4>,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal rounding-modes}@anchor{2afd}
@subsubsection 丸めモード


@geindex ROUND_CEILING (decimal モジュール)
@anchor{library/decimal decimal ROUND_CEILING}@anchor{2ab2}
@deffn {データ} decimal.ROUND_CEILING

@code{Infinity} 方向に丸めます。
@end deffn

@geindex ROUND_DOWN (decimal モジュール)
@anchor{library/decimal decimal ROUND_DOWN}@anchor{2ab3}
@deffn {データ} decimal.ROUND_DOWN

ゼロ方向に丸めます。
@end deffn

@geindex ROUND_FLOOR (decimal モジュール)
@anchor{library/decimal decimal ROUND_FLOOR}@anchor{2ab4}
@deffn {データ} decimal.ROUND_FLOOR

@code{-Infinity} 方向に丸めます。
@end deffn

@geindex ROUND_HALF_DOWN (decimal モジュール)
@anchor{library/decimal decimal ROUND_HALF_DOWN}@anchor{2ab5}
@deffn {データ} decimal.ROUND_HALF_DOWN

近い方に、引き分けはゼロ方向に向けて丸めます。
@end deffn

@geindex ROUND_HALF_EVEN (decimal モジュール)
@anchor{library/decimal decimal ROUND_HALF_EVEN}@anchor{2ab6}
@deffn {データ} decimal.ROUND_HALF_EVEN

近い方に、引き分けは偶数整数方向に向けて丸めます。
@end deffn

@geindex ROUND_HALF_UP (decimal モジュール)
@anchor{library/decimal decimal ROUND_HALF_UP}@anchor{2ab7}
@deffn {データ} decimal.ROUND_HALF_UP

近い方に、引き分けはゼロから遠い方向に向けて丸めます。
@end deffn

@geindex ROUND_UP (decimal モジュール)
@anchor{library/decimal decimal ROUND_UP}@anchor{2ab8}
@deffn {データ} decimal.ROUND_UP

ゼロから遠い方向に丸めます。
@end deffn

@geindex ROUND_05UP (decimal モジュール)
@anchor{library/decimal decimal ROUND_05UP}@anchor{2ab9}
@deffn {データ} decimal.ROUND_05UP

ゼロ方向に丸めた後の最後の桁が 0 または 5 ならばゼロから遠い方向に、そうでなければゼロ方向に丸めます。
@end deffn

@node シグナル,Floating-point notes,丸めモード,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal decimal-signals}@anchor{12b0}@anchor{library/decimal signals}@anchor{2b3f}
@subsubsection シグナル


シグナルは、計算中に生じた様々なエラー条件を表現します。各々のシグナルは一つのコンテキストフラグと一つのトラップイネーブラに対応しています。

コンテキストフラグは、該当するエラー条件に遭遇するたびにセットされます。演算後にフラグを調べれば、演算に関する情報 (例えば計算が厳密だったかどうか) がわかります。フラグを調べたら、次の計算を始める前にフラグを全てクリアするようにしてください。

あるコンテキストのトラップイネーブラがあるシグナルに対してセットされている場合、該当するエラー条件が生じると Python の例外を送出します。例えば、 @ref{2abb,,DivisionByZero} が設定されていると、エラー条件が生じた際に @ref{2abb,,DivisionByZero} 例外を送出します。

@geindex Clamped (decimal のクラス)
@anchor{library/decimal decimal Clamped}@anchor{2aba}
@deffn {クラス} decimal.Clamped

値の表現上の制限に沿わせるために指数部が変更されたことを通知します。

通常、クランプ (clamp) は、指数部がコンテキストにおける指数桁の制限値 @ref{12bb,,Emin} および @ref{12ba,,Emax} を越えた場合に発生します。可能な場合には、係数部にゼロを加えた表現に合わせて指数部を減らします。
@end deffn

@geindex DecimalException (decimal のクラス)
@anchor{library/decimal decimal DecimalException}@anchor{2b40}
@deffn {クラス} decimal.DecimalException

他のシグナルの基底クラスで、 @ref{26e5,,ArithmeticError} のサブクラスです。
@end deffn

@geindex DivisionByZero (decimal のクラス)
@anchor{library/decimal decimal DivisionByZero}@anchor{2abb}
@deffn {クラス} decimal.DivisionByZero

有限値をゼロで除算したときのシグナルです。

除算やモジュロ除算、数を負の値で累乗した場合に起きることがあります。このシグナルをトラップしない場合、演算結果は @code{Infinity} または @code{-Infinity} になり、その符号は演算に使った入力に基づいて決まります。
@end deffn

@geindex Inexact (decimal のクラス)
@anchor{library/decimal decimal Inexact}@anchor{2abc}
@deffn {クラス} decimal.Inexact

値の丸めによって演算結果から厳密さが失われたことを通知します。

このシグナルは値丸め操作中にゼロでない桁を無視した際に生じます。演算結果は値丸め後の値です。シグナルのフラグやトラップは、演算結果の厳密さが失われたことを検出するために使えるだけです。
@end deffn

@geindex InvalidOperation (decimal のクラス)
@anchor{library/decimal decimal InvalidOperation}@anchor{12bc}
@deffn {クラス} decimal.InvalidOperation

無効な演算が実行されたことを通知します。

ユーザが有意な演算結果にならないような操作を要求したことを示します。このシグナルをトラップしない場合、 @code{NaN} を返します。このシグナルの発生原因として考えられるのは、以下のような状況です:

@example
Infinity - Infinity
0 * Infinity
Infinity / Infinity
x % 0
Infinity % x
sqrt(-x) and x > 0
0 ** 0
x ** (non-integer)
x ** Infinity
@end example
@end deffn

@geindex Overflow (decimal のクラス)
@anchor{library/decimal decimal Overflow}@anchor{2abf}
@deffn {クラス} decimal.Overflow

数値オーバフローを示すシグナルです。

このシグナルは、値丸めを行った後の指数部が @ref{12ba,,Context.Emax} より大きいことを示します。シグナルをトラップしない場合、演算結果は値丸めのモードにより、表現可能な最大の数値になるように内側へ引き込んで丸めを行った値か、 @code{Infinity} になるように外側に丸めた値のいずれかになります。いずれの場合も、 @ref{2abc,,Inexact} および @ref{2abd,,Rounded} が同時にシグナルされます。
@end deffn

@geindex Rounded (decimal のクラス)
@anchor{library/decimal decimal Rounded}@anchor{2abd}
@deffn {クラス} decimal.Rounded

情報が全く失われていない場合も含み、値丸めが起きたときのシグナルです。

このシグナルは、値丸めによって桁がなくなると常に発生します。なくなった桁がゼロ (例えば @code{5.00} を丸めて @code{5.0} になった場合) であってもです。このシグナルをトラップしなければ、演算結果をそのまま返します。このシグナルは有効桁数の減少を検出する際に使います。
@end deffn

@geindex Subnormal (decimal のクラス)
@anchor{library/decimal decimal Subnormal}@anchor{2abe}
@deffn {クラス} decimal.Subnormal

値丸めを行う前に指数部が @ref{12bb,,Emin} より小さかったことを示すシグナルです。

演算結果が微小である場合 (指数が小さすぎる場合) に発生します。このシグナルをトラップしなければ、演算結果をそのまま返します。
@end deffn

@geindex Underflow (decimal のクラス)
@anchor{library/decimal decimal Underflow}@anchor{2ac0}
@deffn {クラス} decimal.Underflow

演算結果が値丸めによってゼロになった場合に生じる数値アンダフローです。

演算結果が微小なため、値丸めによってゼロになった場合に発生します。 @ref{2abc,,Inexact} および @ref{2abe,,Subnormal} シグナルも同時に発生します。
@end deffn

@geindex FloatOperation (decimal のクラス)
@anchor{library/decimal decimal FloatOperation}@anchor{12af}
@deffn {クラス} decimal.FloatOperation

float と Decimal の混合の厳密なセマンティクスを有効にします。

シグナルがトラップされなかった場合 (デフォルト)、@ref{1fe,,Decimal} コンストラクタ、 @ref{12bd,,create_decimal()} 、およびすべての比較演算子において float と Decimal の混合が許されます。変換も比較も正確です。コンテキストフラグ内に @ref{12af,,FloatOperation} を設定することで、混合操作は現れるたびに暗黙に記録されます。 @ref{141d,,from_float()} や @ref{2b02,,create_decimal_from_float()} による明示的な変換はフラグを設定しません。

そうでなければ (シグナルがトラップされれば)、等価性比較および明示的な変換のみが静かにに行われ、その他の混合演算は @ref{12af,,FloatOperation} を送出します。
@end deffn

これらのシグナルの階層構造をまとめると、以下の表のようになります:

@example
exceptions.ArithmeticError(exceptions.Exception)
    DecimalException
        Clamped
        DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
        Inexact
            Overflow(Inexact, Rounded)
            Underflow(Inexact, Rounded, Subnormal)
        InvalidOperation
        Rounded
        Subnormal
        FloatOperation(DecimalException, exceptions.TypeError)
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node Floating-point notes,スレッドを使った処理,シグナル,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal decimal-notes}@anchor{2b41}@anchor{library/decimal floating-point-notes}@anchor{2b42}
@subsubsection Floating-point notes


@menu
* 精度を上げて丸め誤差を抑制する:: 
* 特殊値:: 

@end menu

@node 精度を上げて丸め誤差を抑制する,特殊値,,Floating-point notes
@anchor{library/decimal mitigating-round-off-error-with-increased-precision}@anchor{2b43}
@subsubsection 精度を上げて丸め誤差を抑制する


十進浮動小数点数を使うと、十進数表現による誤差を抑制できます (@code{0.1} を正確に表現できるようになります); しかし、ゼロでない桁が一定の精度を越えている場合には、演算によっては依然として値丸めによる誤差を引き起こします。

The effects of round-off error can be amplified by the addition or subtraction
of nearly offsetting quantities resulting in loss of significance.  Knuth
provides two instructive examples where rounded floating-point arithmetic with
insufficient precision causes the breakdown of the associative and distributive
properties of addition:

@example
# Examples from Seminumerical Algorithms, Section 4.2.2.
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 8

>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.5111111')
>>> u + (v + w)
Decimal('10')

>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.01')
>>> u * (v+w)
Decimal('0.0060000')
@end example

The @code{decimal} module makes it possible to restore the identities by
expanding the precision sufficiently to avoid loss of significance:

@example
>>> getcontext().prec = 20
>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.51111111')
>>> u + (v + w)
Decimal('9.51111111')
>>>
>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.0060000')
>>> u * (v+w)
Decimal('0.0060000')
@end example

@node 特殊値,,精度を上げて丸め誤差を抑制する,Floating-point notes
@anchor{library/decimal special-values}@anchor{2b44}
@subsubsection 特殊値


The number system for the @code{decimal} module provides special values
including @code{NaN}, @code{sNaN}, @code{-Infinity}, @code{Infinity},
and two zeros, @code{+0} and @code{-0}.

無限大 (Infinity) は @code{Decimal('Infinity')} で直接構築できます。また、 @ref{2abb,,DivisionByZero} をトラップせずにゼロで除算を行った場合にも出てきます。同様に、 @ref{2abf,,Overflow} シグナルをトラップしなければ、表現可能な最大の数値の制限を越えた値を丸めたときに出てきます。

無限大には符号があり (アフィン: affine であり)、算術演算に使用でき、非常に巨大で不確定の(indeterminate)値として扱われます。例えば、無限大に何らかの定数を加算すると、演算結果は別の無限大になります。

演算によっては結果が不確定になるものがあり、 @code{NaN} を返します。ただし、 @ref{12bc,,InvalidOperation} シグナルをトラップするようになっていれば例外を送出します。例えば、 @code{0/0} は @code{NaN} を返します。 @code{NaN} は「非数値 (not a number)」を表します。このような @code{NaN} は暗黙のうちに生成され、一度生成されるとそれを他の計算にも流れてゆき、関係する個々の演算全てが個別の @code{NaN} を返すようになります。この挙動は、たまに入力値が欠けるような状況で一連の計算を行う際に便利です --- 特定の計算に対しては無効な結果を示すフラグを立てつつ計算を進められるからです。

一方、 @code{NaN} の変種である @code{sNaN} は関係する全ての演算で演算後にシグナルを送出します。 @code{sNaN} は、無効な演算結果に対して特別な処理を行うために計算を停止する必要がある場合に便利です。

Python の比較演算は @code{NaN} が関わってくると少し驚くようなことがあります。等価性のテストの一方の対象が無言または発信 @code{NaN} である場合いつでも @ref{d2b,,False} を返し(たとえ @code{Decimal('NaN')==Decimal('NaN')} でも)、一方で不等価をテストするといつでも @ref{e07,,True} を返します。二つの Decimal を @code{<}, @code{<=}, @code{>} または @code{>=} を使って比較する試みは一方が @code{NaN} である場合には @ref{12bc,,InvalidOperation} シグナルを送出し、このシグナルをトラップしなければ結果は @ref{d2b,,False} に終わります。汎用十進演算仕様は直接の比較の振る舞いについて定めていないことに注意しておきましょう。ここでの @code{NaN} が関係する比較ルールは IEEE 854 標準から持ってきました (section 5.7 の Table 3 を見て下さい)。厳格に標準遵守を貫くなら、 @ref{2ac9,,compare()} および @ref{2aca,,compare_signal()} メソッドを代わりに使いましょう。

アンダフローの起きた計算は、符号付きのゼロ (signed zero) を返すことがあります。符号は、より高い精度で計算を行った結果の符号と同じになります。符号付きゼロの大きさはやはりゼロなので、正のゼロと負のゼロは等しいとみなされ、符号は単なる参考にすぎません。

In addition to the two signed zeros which are distinct yet equal, there are
various representations of zero with differing precisions yet equivalent in
value.  This takes a bit of getting used to.  For an eye accustomed to
normalized floating-point representations, it is not immediately obvious that
the following calculation returns a value equal to zero:

@example
>>> 1 / Decimal('Infinity')
Decimal('0E-1000026')
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node スレッドを使った処理,レシピ,Floating-point notes,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal decimal-threads}@anchor{2b45}@anchor{library/decimal working-with-threads}@anchor{2b46}
@subsubsection スレッドを使った処理


関数 @ref{1937,,getcontext()} は、スレッド毎に別々の @ref{12c3,,Context} オブジェクトにアクセスします。別のスレッドコンテキストを持つということは、複数のスレッドが互いに影響を及ぼさずに (@code{getcontext().prec=10} のような) 変更を適用できるということです。

同様に、@ref{2ac2,,setcontext()} 関数は自動的に引数のコンテキストを現在のスレッドのコンテキストに設定します。

If @ref{2ac2,,setcontext()} has not been called before @ref{1937,,getcontext()}, then
@ref{1937,,getcontext()} will automatically create a new context for use in the
current thread.  New context objects have default values set from the
@ref{12b7,,decimal.DefaultContext} object.

The @ref{175,,sys.flags.thread_inherit_context} flag affects the context for
new threads.  If the flag is false, new threads will start with an empty
context.  In this case, @ref{1937,,getcontext()} will create a new context object
when called and use the default values from `DefaultContext'.  If the flag
is true, new threads will start with a copy of context from the caller of
@ref{178,,threading.Thread.start()}.

To control the defaults so that each thread will use the same values throughout
the application, directly modify the `DefaultContext' object. This should be
done `before' any threads are started so that there won't be a race condition
between threads calling @ref{1937,,getcontext()}. For example:

@example
# Set applicationwide defaults for all threads about to be launched
DefaultContext.prec = 12
DefaultContext.rounding = ROUND_DOWN
DefaultContext.traps = ExtendedContext.traps.copy()
DefaultContext.traps[InvalidOperation] = 1
setcontext(DefaultContext)

# Afterwards, the threads can be started
t1.start()
t2.start()
t3.start()
 . . .
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node レシピ,Decimal FAQ,スレッドを使った処理,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal decimal-recipes}@anchor{2b47}@anchor{library/decimal recipes}@anchor{2b48}
@subsubsection レシピ


@ref{1fe,,Decimal} クラスの利用を実演している例をいくつか示します。これらはユーティリティ関数としても利用できます:

@example
def moneyfmt(value, places=2, curr='@w{'}, sep=',', dp='.',
             pos='@w{'}, neg='-', trailneg='@w{'}):
    """Convert Decimal to a money formatted string.

    places:  required number of places after the decimal point
    curr:    optional currency symbol before the sign (may be blank)
    sep:     optional grouping separator (comma, period, space, or blank)
    dp:      decimal point indicator (comma or period)
             only specify as blank when places is zero
    pos:     optional sign for positive numbers: '+', space or blank
    neg:     optional sign for negative numbers: '-', '(', space or blank
    trailneg:optional trailing minus indicator:  '-', ')', space or blank

    >>> d = Decimal('-1234567.8901')
    >>> moneyfmt(d, curr='$')
    '-$1,234,567.89'
    >>> moneyfmt(d, places=0, sep='.', dp='@w{'}, neg='@w{'}, trailneg='-')
    '1.234.568-'
    >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
    '($1,234,567.89)'
    >>> moneyfmt(Decimal(123456789), sep=' ')
    '123 456 789.00'
    >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
    '<0.02>'

    """
    q = Decimal(10) ** -places      # 2 places --> '0.01'
    sign, digits, exp = value.quantize(q).as_tuple()
    result = []
    digits = list(map(str, digits))
    build, next = result.append, digits.pop
    if sign:
        build(trailneg)
    for i in range(places):
        build(next() if digits else '0')
    if places:
        build(dp)
    if not digits:
        build('0')
    i = 0
    while digits:
        build(next())
        i += 1
        if i == 3 and digits:
            i = 0
            build(sep)
    build(curr)
    build(neg if sign else pos)
    return '@w{'}.join(reversed(result))

def pi():
    """Compute Pi to the current precision.

    >>> print(pi())
    3.141592653589793238462643383

    """
    getcontext().prec += 2  # extra digits for intermediate steps
    three = Decimal(3)      # substitute "three=3.0" for regular floats
    lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    getcontext().prec -= 2
    return +s               # unary plus applies the new precision

def exp(x):
    """Return e raised to the power of x.  Result type matches input type.

    >>> print(exp(Decimal(1)))
    2.718281828459045235360287471
    >>> print(exp(Decimal(2)))
    7.389056098930650227230427461
    >>> print(exp(2.0))
    7.38905609893
    >>> print(exp(2+0j))
    (7.38905609893+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num = 0, 0, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 1
        fact *= i
        num *= x
        s += num / fact
    getcontext().prec -= 2
    return +s

def cos(x):
    """Return the cosine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(cos(Decimal('0.5')))
    0.8775825618903727161162815826
    >>> print(cos(0.5))
    0.87758256189
    >>> print(cos(0.5+0j))
    (0.87758256189+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

def sin(x):
    """Return the sine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(sin(Decimal('0.5')))
    0.4794255386042030002732879352
    >>> print(sin(0.5))
    0.479425538604
    >>> print(sin(0.5+0j))
    (0.479425538604+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node Decimal FAQ,,レシピ,decimal --- 10進固定小数点と浮動小数点の演算
@anchor{library/decimal decimal-faq}@anchor{2b49}@anchor{library/decimal id1}@anchor{2b4a}
@subsubsection Decimal FAQ


Q: It is cumbersome to type @code{decimal.Decimal('1234.5')}.  Is there a way to
minimize typing when using the interactive interpreter?

A: Some users abbreviate the constructor to just a single letter:

@example
>>> D = decimal.Decimal
>>> D('1.23') + D('3.45')
Decimal('4.68')
@end example

Q: In a fixed-point application with two decimal places, some inputs have many
places and need to be rounded.  Others are not supposed to have excess digits
and need to be validated.  What methods should be used?

A: The @ref{12c4,,quantize()} method rounds to a fixed number of decimal places. If
the @ref{2abc,,Inexact} trap is set, it is also useful for validation:

@example
>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
@end example

@example
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
@end example

@example
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
@end example

@example
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None
@end example

Q: Once I have valid two place inputs, how do I maintain that invariant
throughout an application?

A: Some operations like addition, subtraction, and multiplication by an integer
will automatically preserve fixed point.  Others operations, like division and
non-integer multiplication, will change the number of decimal places and need to
be followed-up with a @ref{12c4,,quantize()} step:

@example
>>> a = Decimal('102.72')           # Initial fixed-point values
>>> b = Decimal('3.17')
>>> a + b                           # Addition preserves fixed-point
Decimal('105.89')
>>> a - b
Decimal('99.55')
>>> a * 42                          # So does integer multiplication
Decimal('4314.24')
>>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
Decimal('325.62')
>>> (b / a).quantize(TWOPLACES)     # And quantize division
Decimal('0.03')
@end example

固定小数点のアプリケーションを開発する際は、 @ref{12c4,,quantize()} の段階を扱う関数を定義しておくと便利です:

@example
>>> def mul(x, y, fp=TWOPLACES):
...     return (x * y).quantize(fp)
...
>>> def div(x, y, fp=TWOPLACES):
...     return (x / y).quantize(fp)
@end example

@example
>>> mul(a, b)                       # Automatically preserve fixed-point
Decimal('325.62')
>>> div(b, a)
Decimal('0.03')
@end example

Q: There are many ways to express the same value.  The numbers @code{200},
@code{200.000}, @code{2E2}, and @code{.02E+4} all have the same value at
various precisions. Is there a way to transform them to a single recognizable
canonical value?

A: The @ref{2aea,,normalize()} method maps all equivalent values to a single
representative:

@example
>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
>>> [v.normalize() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
@end example

Q: When does rounding occur in a computation?

A: It occurs `after' the computation.  The philosophy of the decimal
specification is that numbers are considered exact and are created
independent of the current context.  They can even have greater
precision than current context.  Computations process with those
exact inputs and then rounding (or other context operations) is
applied to the `result' of the computation:

@example
>>> getcontext().prec = 5
>>> pi = Decimal('3.1415926535')   # More than 5 digits
>>> pi                             # All digits are retained
Decimal('3.1415926535')
>>> pi + 0                         # Rounded after an addition
Decimal('3.1416')
>>> pi - Decimal('0.00005')        # Subtract unrounded numbers, then round
Decimal('3.1415')
>>> pi + 0 - Decimal('0.00005').   # Intermediate values are rounded
Decimal('3.1416')
@end example

Q: Some decimal values always print with exponential notation.  Is there a way
to get a non-exponential representation?

A: For some values, exponential notation is the only way to express the number
of significant places in the coefficient.  For example, expressing
@code{5.0E+3} as @code{5000} keeps the value constant but cannot show the
original's two-place significance.

もしアプリケーションが有効数字の追跡を等閑視するならば、指数部や末尾のゼロを取り除き、有効数字を忘れ、しかし値を変えずにおくことは容易です:

@example
>>> def remove_exponent(d):
...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
@end example

@example
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
@end example

Q: Is there a way to convert a regular float to a @ref{1fe,,Decimal}?

A: Yes, any binary floating-point number can be exactly expressed as a
Decimal though an exact conversion may take more precision than intuition would
suggest:

@example
>>> Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')
@end example

Q: Within a complex calculation, how can I make sure that I haven't gotten a
spurious result because of insufficient precision or rounding anomalies.

A: The decimal module makes it easy to test results.  A best practice is to
re-run calculations using greater precision and with various rounding modes.
Widely differing results indicate insufficient precision, rounding mode issues,
ill-conditioned inputs, or a numerically unstable algorithm.

Q: I noticed that context precision is applied to the results of operations but
not to the inputs.  Is there anything to watch out for when mixing values of
different precisions?

A: Yes.  The principle is that all values are considered to be exact and so is
the arithmetic on those values.  Only the results are rounded.  The advantage
for inputs is that "what you type is what you get".  A disadvantage is that the
results can look odd if you forget that the inputs haven't been rounded:

@example
>>> getcontext().prec = 3
>>> Decimal('3.104') + Decimal('2.104')
Decimal('5.21')
>>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Decimal('5.20')
@end example

解決策は、精度を増やすか、単項プラス演算子を使って入力の丸めを強制することです:

@example
>>> getcontext().prec = 3
>>> +Decimal('1.23456789')      # unary plus triggers rounding
Decimal('1.23')
@end example

もしくは、入力を @ref{12bd,,Context.create_decimal()} を使って生成時に丸めてしまうこともできます:

@example
>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')
@end example

Q: Is the CPython implementation fast for large numbers?

A: Yes.  In the CPython and PyPy3 implementations, the C/CFFI versions of
the decimal module integrate the high speed libmpdec@footnote{https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html} library for
arbitrary precision correctly rounded decimal floating-point arithmetic @footnote{

Added in version 3.3.

}.
@code{libmpdec} uses Karatsuba multiplication@footnote{https://en.wikipedia.org/wiki/Karatsuba_algorithm}
for medium-sized numbers and the Number Theoretic Transform@footnote{https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform}
for very large numbers.

The context must be adapted for exact arbitrary precision arithmetic. @ref{12bb,,Emin}
and @ref{12ba,,Emax} should always be set to the maximum values, @ref{13b6,,clamp}
should always be 0 (the default).  Setting @ref{2afb,,prec} requires some care.

The easiest approach for trying out bignum arithmetic is to use the maximum
value for @ref{2afb,,prec} as well @footnote{

バージョン 3.9 で変更: This approach now works for all exact results except for non-integer powers.

}:

@example
>>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
>>> x = Decimal(2) ** 256
>>> x / 128
Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')
@end example

For inexact results, @ref{12b4,,MAX_PREC} is far too large on 64-bit platforms and
the available memory will be insufficient:

@example
>>> Decimal(1) / 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError
@end example

On systems with overallocation (e.g. Linux), a more sophisticated approach is to
adjust @ref{2afb,,prec} to the amount of available RAM.  Suppose that you have 8GB of
RAM and expect 10 simultaneous operands using a maximum of 500MB each:

@example
>>> import sys
>>>
>>> # Maximum number of digits for a single operand using 500MB in 8-byte words
>>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
>>> maxdigits = 19 * ((500 * 1024**2) // 8)
>>>
>>> # Check that this works:
>>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
>>> c.traps[Inexact] = True
>>> setcontext(c)
>>>
>>> # Fill the available precision with nines:
>>> x = Decimal(0).logical_invert() * 9
>>> sys.getsizeof(x)
524288112
>>> x + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  decimal.Inexact: [<class 'decimal.Inexact'>]
@end example

In general (and especially on systems without overallocation), it is recommended
to estimate even tighter bounds and set the @ref{2abc,,Inexact} trap if all calculations
are expected to be exact.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node fractions --- 有理数,random --- 疑似乱数を生成する,decimal --- 10進固定小数点と浮動小数点の演算,数値と数学モジュール
@anchor{library/fractions doc}@anchor{2b4b}@anchor{library/fractions fractions-rational-numbers}@anchor{2b4c}@anchor{library/fractions module-fractions}@anchor{61}@anchor{library/fractions translation-repo}@anchor{2b4d}
@subsection @code{fractions} --- 有理数


@geindex module; fractions

`ソースコード:' Lib/fractions.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/fractions.py}


__________________________________________________________________


The @code{fractions} module provides support for rational number arithmetic.

A Fraction instance can be constructed from a pair of rational numbers, from
a single number, or from a string.

@geindex as_integer_ratio()

@geindex Fraction (fractions のクラス)
@anchor{library/fractions fractions Fraction}@anchor{213}
@deffn {クラス} fractions.Fraction (numerator=0, denominator=1)

@deffnx {クラス} fractions.Fraction (number)

@deffnx {クラス} fractions.Fraction (string)

The first version requires that `numerator' and `denominator' are instances
of @ref{14d6,,numbers.Rational} and returns a new @ref{213,,Fraction} instance
with a value equal to @code{numerator/denominator}.
If `denominator' is zero, it raises a @ref{b3f,,ZeroDivisionError}.

The second version requires that `number' is an instance of
@ref{14d6,,numbers.Rational} or has the @code{as_integer_ratio()} method
(this includes @ref{196,,float} and @ref{1fe,,decimal.Decimal}).
It returns a @ref{213,,Fraction} instance with exactly the same value.
Assumed, that the @code{as_integer_ratio()} method returns a pair
of coprime integers and last one is positive.
Note that due to the
usual issues with binary point (see @ref{2101,,浮動小数点演算、その問題と制限}), the
argument to @code{Fraction(1.1)} is not exactly equal to 11/10, and so
@code{Fraction(1.1)} does `not' return @code{Fraction(11, 10)} as one might expect.
(But see the documentation for the @ref{2b4e,,limit_denominator()} method below.)

The last version of the constructor expects a string.
The usual form for this instance is:

@example
[sign] numerator ['/' denominator]
@end example

ここで、オプションの @code{sign} は '+' か '-' のどちらかであり、@code{numerator} および (存在する場合) @code{denominator} は十進数の数字の文字列です (コード中の整数リテラルと同様、アンダースコアを使って桁を区切れます)。さらに、 @ref{196,,float} コンストラクタで受け付けられる有限の値を表す文字列は、@ref{213,,Fraction} コンストラクタでも受け付けられます。どちらの形式でも、入力される文字列は前後に空白があって構いません。以下に、いくつかの例を示します:

@example
>>> from fractions import Fraction
>>> Fraction(16, -10)
Fraction(-8, 5)
>>> Fraction(123)
Fraction(123, 1)
>>> Fraction()
Fraction(0, 1)
>>> Fraction('3/7')
Fraction(3, 7)
>>> Fraction(' -3/7 ')
Fraction(-3, 7)
>>> Fraction('1.414213 \t\n')
Fraction(1414213, 1000000)
>>> Fraction('-.125')
Fraction(-1, 8)
>>> Fraction('7e-6')
Fraction(7, 1000000)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)
@end example

@ref{213,,Fraction} クラスは抽象基底クラス @ref{14d6,,numbers.Rational} を継承し、その全てのメソッドと演算を実装します。 @ref{213,,Fraction} インスタンスは @ref{824,,ハッシュ可能} で、不変 (immutable) であるものとして扱われます。加えて、 @ref{213,,Fraction} には以下のプロパティとメソッドがあります:


バージョン 3.2 で変更: @ref{213,,Fraction} のコンストラクタが @ref{196,,float} および @ref{1fe,,decimal.Decimal} インスタンスを受け付けるようになりました。



バージョン 3.9 で変更: The @ref{b0c,,math.gcd()} function is now used to normalize the `numerator'
and `denominator'. @ref{b0c,,math.gcd()} always returns an @ref{19b,,int} type.
Previously, the GCD type depended on `numerator' and `denominator'.



バージョン 3.11 で変更: Underscores are now permitted when creating a @ref{213,,Fraction} instance
from a string, following 
@geindex Python Enhancement Proposals; PEP 515
PEP 515@footnote{https://peps.python.org/pep-0515/} rules.



バージョン 3.11 で変更: @ref{213,,Fraction} implements @code{__int__} now to satisfy
@code{typing.SupportsInt} instance checks.



バージョン 3.12 で変更: Space is allowed around the slash for string inputs: @code{Fraction('2 / 3')}.



バージョン 3.12 で変更: @ref{213,,Fraction} instances now support float-style formatting, with
presentation types @code{"e"}, @code{"E"}, @code{"f"}, @code{"F"}, @code{"g"}, @code{"G"}
and @code{"%""}.



バージョン 3.13 で変更: Formatting of @ref{213,,Fraction} instances without a presentation type
now supports fill, alignment, sign handling, minimum width and grouping.



バージョン 3.14 で変更: The @ref{213,,Fraction} constructor now accepts any objects with the
@code{as_integer_ratio()} method.


@geindex numerator (fractions.Fraction の属性)
@anchor{library/fractions fractions Fraction numerator}@anchor{2b4f}
@deffn {の属性} numerator

有理数を既約分数で表したときの分子。
@end deffn

@geindex denominator (fractions.Fraction の属性)
@anchor{library/fractions fractions Fraction denominator}@anchor{2b50}
@deffn {の属性} denominator

Denominator of the Fraction in lowest terms.
Guaranteed to be positive.
@end deffn

@geindex as_integer_ratio() (fractions.Fraction のメソッド)
@anchor{library/fractions fractions Fraction as_integer_ratio}@anchor{2b51}
@deffn {メソッド} as_integer_ratio ()

Return a tuple of two integers, whose ratio is equal
to the original Fraction.  The ratio is in lowest terms
and has a positive denominator.


Added in version 3.8.

@end deffn

@geindex is_integer() (fractions.Fraction のメソッド)
@anchor{library/fractions fractions Fraction is_integer}@anchor{2b52}
@deffn {メソッド} is_integer ()

Return @code{True} if the Fraction is an integer.


Added in version 3.12.

@end deffn

@geindex from_float() (fractions.Fraction のクラスメソッド)
@anchor{library/fractions fractions Fraction from_float}@anchor{141e}
@deffn {メソッド} classmethod from_float (f)

Alternative constructor which only accepts instances of
@ref{196,,float} or @ref{240a,,numbers.Integral}. Beware that
@code{Fraction.from_float(0.3)} is not the same value as @code{Fraction(3, 10)}.

@cartouche
@quotation 注釈 
Python 3.2 以降では、 @ref{196,,float} から直接 @ref{213,,Fraction} インスタンスを構築できるようになりました。
@end quotation
@end cartouche
@end deffn

@geindex from_decimal() (fractions.Fraction のクラスメソッド)
@anchor{library/fractions fractions Fraction from_decimal}@anchor{141f}
@deffn {メソッド} classmethod from_decimal (dec)

Alternative constructor which only accepts instances of
@ref{1fe,,decimal.Decimal} or @ref{240a,,numbers.Integral}.

@cartouche
@quotation 注釈 
Python 3.2 以降では、 @ref{1fe,,decimal.Decimal} インスタンスから直接 @ref{213,,Fraction} インスタンスを構築できるようになりました。
@end quotation
@end cartouche
@end deffn

@geindex from_number() (fractions.Fraction のクラスメソッド)
@anchor{library/fractions fractions Fraction from_number}@anchor{214}
@deffn {メソッド} classmethod from_number (number)

Alternative constructor which only accepts instances of
@ref{240a,,numbers.Integral}, @ref{14d6,,numbers.Rational},
@ref{196,,float} or @ref{1fe,,decimal.Decimal}, and objects with
the @code{as_integer_ratio()} method, but not strings.


Added in version 3.14.

@end deffn

@geindex limit_denominator() (fractions.Fraction のメソッド)
@anchor{library/fractions fractions Fraction limit_denominator}@anchor{2b4e}
@deffn {メソッド} limit_denominator (max_denominator=1000000)

分母が高々 max_denominator である、 @code{self} に最も近い @ref{213,,Fraction} を見付けて返します。このメソッドは与えられた浮動小数点数の有理数近似を見つけるのに役立ちます:

@example
>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355, 113)
@end example

あるいは float で表された有理数を元に戻すのにも使えます:

@example
>>> from math import pi, cos
>>> Fraction(cos(pi/3))
Fraction(4503599627370497, 9007199254740992)
>>> Fraction(cos(pi/3)).limit_denominator()
Fraction(1, 2)
>>> Fraction(1.1).limit_denominator()
Fraction(11, 10)
@end example
@end deffn

@geindex __floor__() (fractions.Fraction のメソッド)
@anchor{library/fractions fractions Fraction __floor__}@anchor{1af7}
@deffn {メソッド} __floor__ ()

最大の @ref{19b,,int} @code{<= self} を返します。このメソッドは @ref{15d7,,math.floor()} 関数からでもアクセスできます:

@example
>>> from math import floor
>>> floor(Fraction(355, 113))
3
@end example
@end deffn

@geindex __ceil__() (fractions.Fraction のメソッド)
@anchor{library/fractions fractions Fraction __ceil__}@anchor{1af6}
@deffn {メソッド} __ceil__ ()

最小の @ref{19b,,int} @code{>= self} を返します。このメソッドは @ref{15d8,,math.ceil()} 関数からでもアクセスできます。
@end deffn

@geindex __round__() (fractions.Fraction のメソッド)
@anchor{library/fractions fractions Fraction __round__}@anchor{1af5}
@deffn {メソッド} __round__ ()

@deffnx {メソッド} __round__ (ndigits)

第一のバージョンは、 @code{self} に最も近い @ref{19b,,int} を偶数丸めで返します。第二のバージョンは、このメソッドは @code{self} に最も近い @code{Fraction(1, 10**ndigits)} の倍数 (論理的に、 @code{ndigits} が負なら) を、これも偶数丸めで丸めます。 @ref{14f2,,round()} 関数からでもアクセスできます。
@end deffn

@geindex __format__() (fractions.Fraction のメソッド)
@anchor{library/fractions fractions Fraction __format__}@anchor{2b53}
@deffn {メソッド} __format__ (format_spec, /)

Provides support for formatting of @ref{213,,Fraction} instances via the
@ref{833,,str.format()} method, the @ref{199,,format()} built-in function, or
@ref{19a,,Formatted string literals}.

If the @code{format_spec} format specification string does not end with one
of the presentation types @code{'e'}, @code{'E'}, @code{'f'}, @code{'F'}, @code{'g'},
@code{'G'} or @code{'%'} then formatting follows the general rules for fill,
alignment, sign handling, minimum width, and grouping as described in the
@ref{4f9,,format specification mini-language}. The "alternate
form" flag @code{'#'} is supported: if present, it forces the output string
to always include an explicit denominator, even when the value being
formatted is an exact integer. The zero-fill flag @code{'0'} is not
supported.

If the @code{format_spec} format specification string ends with one of
the presentation types @code{'e'}, @code{'E'}, @code{'f'}, @code{'F'}, @code{'g'},
@code{'G'} or @code{'%'} then formatting follows the rules outlined for the
@ref{196,,float} type in the @ref{4f9,,書式指定ミニ言語仕様} section.

ここに例があります:

@example
>>> from fractions import Fraction
>>> format(Fraction(103993, 33102), '_')
'103_993/33_102'
>>> format(Fraction(1, 7), '.^+10')
'...+1/7...'
>>> format(Fraction(3, 1), '@w{'})
'3'
>>> format(Fraction(3, 1), '#')
'3/1'
>>> format(Fraction(1, 7), '.40g')
'0.1428571428571428571428571428571428571429'
>>> format(Fraction('1234567.855'), '_.2f')
'1_234_567.86'
>>> f"@{Fraction(355, 113):*>20.6e@}"
'********3.141593e+00'
>>> old_price, new_price = 499, 672
>>> "@{:.2%@} price increase".format(Fraction(new_price, old_price) - 1)
'34.67% price increase'
@end example
@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item @ref{a2,,numbers} モジュール

数値の塔を作り上げる抽象基底クラス。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node random --- 疑似乱数を生成する,statistics --- 数学的統計関数,fractions --- 有理数,数値と数学モジュール
@anchor{library/random doc}@anchor{2b54}@anchor{library/random module-random}@anchor{bd}@anchor{library/random random-generate-pseudo-random-numbers}@anchor{2b55}@anchor{library/random translation-repo}@anchor{2b56}
@subsection @code{random} --- 疑似乱数を生成する


@geindex module; random

`ソースコード:' Lib/random.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/random.py}


__________________________________________________________________


このモジュールでは様々な分布をもつ擬似乱数生成器を実装しています。

整数用に、ある範囲からの一様な選択があります。シーケンス用には、シーケンスからのランダムな要素の一様な選択、リストのランダムな置換をインプレースに生成する関数、順列を置換せずにランダムサンプリングする関数があります。

実数用としては、一様分布、正規分布 (ガウス分布)、対数正規分布、負の指数分布、ガンマおよびベータ分布を計算する関数があります。角度の分布を生成するにはフォン・ミーゼス分布が利用できます。

ほとんど全てのモジュール関数は、基礎となる関数 @ref{94f,,random()} に依存します。この関数はランダムな浮動小数点数を半開区間 @code{0.0 <= X < 1.0} 内に一様に生成します。Python は中心となる乱数生成器としてメルセンヌツイスタを使います。これは 53 ビット精度の浮動小数点を生成し、周期は 2**19937-1 です。本体は C で実装されていて、高速でスレッドセーフです。メルセンヌツイスタは、現存する中で最も広範囲にテストされた乱数生成器のひとつです。しかしながら、メルセンヌツイスタは完全に決定論的であるため、全ての目的に合致しているわけではなく、暗号化の目的には全く向いていません。

このモジュールで提供されている関数は、実際には @ref{1c5c,,random.Random} クラスの隠蔽されたインスタンスのメソッドに束縛されています。内部状態を共有しない生成器を取得するため、自分で @ref{1c5c,,Random} のインスタンスを生成することができます。

Class @ref{1c5c,,Random} can also be subclassed if you want to use a different
basic generator of your own devising: see the documentation on that class for
more details.

The @code{random} module also provides the @ref{2b57,,SystemRandom} class which
uses the system function @ref{746,,os.urandom()} to generate random numbers
from sources provided by the operating system.

@cartouche
@quotation 警告 
このモジュールの擬似乱数生成器をセキュリティ目的に使用してはいけません。セキュリティや暗号学的な用途については @ref{c5,,secrets} モジュールを参照してください。
@end quotation
@end cartouche


@subsubheading 参考


M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally
equidistributed uniform pseudorandom number generator", ACM Transactions on
Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998.

Complementary-Multiply-with-Carry recipe@footnote{https://code.activestate.com/recipes/576707-long-period-random-number-generator/}  長い周期と比較的シンプルな更新操作を備えた互換性のある別の乱数生成器。


@cartouche
@quotation 注釈 
The global random number generator and instances of @ref{1c5c,,Random} are thread-safe.
However, in the free-threaded build, concurrent calls to the global generator or
to the same instance of @ref{1c5c,,Random} may encounter contention and poor performance.
Consider using separate instances of @ref{1c5c,,Random} per thread instead.
@end quotation
@end cartouche

@menu
* 保守 (bookkeeping) 関数: 保守 bookkeeping 関数. 
* バイト列用の関数:: 
* 整数用の関数:: 
* シーケンス用の関数:: 
* Discrete distributions:: 
* 実数分布:: 
* 他の生成器:: 
* 再現性について:: 
* 使用例: 使用例<7>. 
* レシピ: レシピ<2>. 
* コマンドラインでの使用: コマンドラインでの使用<2>. 
* コマンドラインの例:: 

@end menu

@node 保守 bookkeeping 関数,バイト列用の関数,,random --- 疑似乱数を生成する
@anchor{library/random bookkeeping-functions}@anchor{2b58}
@subsubsection 保守 (bookkeeping) 関数


@geindex seed() (random モジュール)
@anchor{library/random random seed}@anchor{148b}
@deffn {の関数} random.seed (a=None, version=2)

乱数生成器を初期化します。

`a' が省略されるか @code{None} の場合、現在のシステム時刻が使用されます。乱数のソースがオペレーティングシステムによって提供される場合、システム時刻の代わりにそれが使用されます (利用可能性についての詳細は @ref{746,,os.urandom()} 関数を参照)。

`a' が int の場合は、その絶対値が直接使用されます。

バージョン2 (デフォルト) では、 @ref{169,,str}, @ref{192,,bytes}, @ref{344,,bytearray} オブジェクトは @ref{19b,,int} に変換され、そのビットがすべて使用されます。

バージョン1 (Python の古いバージョンでの乱数列を再現するために提供される) では、 @ref{169,,str} と @ref{192,,bytes} に対して適用されるアルゴリズムは、より狭い範囲のシードを生成します。


バージョン 3.2 で変更: 文字列シードのすべてのビットを使うバージョン2スキームに移行。



バージョン 3.11 で変更: `seed' は次の型の内のいずれかでなければなりません: @code{None}、@ref{19b,,int}、@ref{196,,float}、@ref{169,,str}、@ref{192,,bytes}、@ref{344,,bytearray}。

@end deffn

@geindex getstate() (random モジュール)
@anchor{library/random random getstate}@anchor{2b59}
@deffn {の関数} random.getstate ()

乱数生成器の現在の内部状態を記憶したオブジェクトを返します。このオブジェクトを @ref{2b5a,,setstate()} に渡して内部状態を復元することができます。
@end deffn

@geindex setstate() (random モジュール)
@anchor{library/random random setstate}@anchor{2b5a}
@deffn {の関数} random.setstate (state)

`state' は予め @ref{2b59,,getstate()} を呼び出して得ておかなくてはなりません。 @ref{2b5a,,setstate()} は @ref{2b59,,getstate()} が呼び出された時の乱数生成器の内部状態を復元します。
@end deffn

@node バイト列用の関数,整数用の関数,保守 bookkeeping 関数,random --- 疑似乱数を生成する
@anchor{library/random functions-for-bytes}@anchor{2b5b}
@subsubsection バイト列用の関数


@geindex randbytes() (random モジュール)
@anchor{library/random random randbytes}@anchor{1826}
@deffn {の関数} random.randbytes (n)

`n' バイトのランダムなバイト列を生成します。

セキュリティトークンを生成する目的で、このメソッドを使用しないでください。代わりに @ref{2b5c,,secrets.token_bytes()} を使用してください。


Added in version 3.9.

@end deffn

@node 整数用の関数,シーケンス用の関数,バイト列用の関数,random --- 疑似乱数を生成する
@anchor{library/random functions-for-integers}@anchor{2b5d}
@subsubsection 整数用の関数


@geindex randrange() (random モジュール)
@anchor{library/random random randrange}@anchor{a6b}
@deffn {の関数} random.randrange (stop)

@deffnx {の関数} random.randrange (start, stop[, step])

@code{range(start, stop, step)} の要素からランダムに選ばれた要素を返します。

This is roughly equivalent to @code{choice(range(start, stop, step))} but
supports arbitrarily large ranges and is optimized for common cases.

位置引数のパターンは @ref{b3d,,range()} 関数の引数と一致します。

Keyword arguments should not be used because they can be interpreted
in unexpected ways. For example @code{randrange(start=100)} is interpreted
as @code{randrange(0, 100, 1)}.


バージョン 3.2 で変更: 一様に分布した値の生成に関して @ref{a6b,,randrange()} がより洗練されました。以前は @code{int(random()*n)} のようなやや一様でない分布を生成するスタイルを使用していました。



バージョン 3.12 で変更: 整数以外の型の自動変換はサポートされなくなりました。@code{randrange(10.0)} や @code{randrange(Fraction(10, 1))} のような呼び出しは @ref{198,,TypeError} を送出します。

@end deffn

@geindex randint() (random モジュール)
@anchor{library/random random randint}@anchor{1447}
@deffn {の関数} random.randint (a, b)

@code{a <= N <= b} であるようなランダムな整数 `N' を返します。@code{randrange(a, b+1)} のエイリアスです。
@end deffn

@geindex getrandbits() (random モジュール)
@anchor{library/random random getrandbits}@anchor{120f}
@deffn {の関数} random.getrandbits (k)

`k' 桁の乱数ビットを持つ Python の整数を生成し、返します。このメソッドはメルセンヌツイスタ生成器で提供されており、その他の乱数生成器でもオプションの API として提供されている場合があります。@ref{120f,,getrandbits()} が使用可能な場合、@ref{a6b,,randrange()} は任意の範囲の乱数を生成できるようになります。


バージョン 3.9 で変更: `k' の値として 0 が許されるようになりました。

@end deffn

@node シーケンス用の関数,Discrete distributions,整数用の関数,random --- 疑似乱数を生成する
@anchor{library/random functions-for-sequences}@anchor{2b5e}
@subsubsection シーケンス用の関数


@geindex choice() (random モジュール)
@anchor{library/random random choice}@anchor{1448}
@deffn {の関数} random.choice (seq)

空でないシーケンス `seq' からランダムに要素を返します。 `seq' が空のときは、 @ref{174e,,IndexError} が送出されます。
@end deffn

@geindex choices() (random モジュール)
@anchor{library/random random choices}@anchor{ec1}
@deffn {の関数} random.choices (population, weights=None, *, cum_weights=None, k=1)

`population' から重複ありで選んだ要素からなる大きさ `k' のリストを返します。`population' が空の場合 @ref{174e,,IndexError} を送出します。

`weights' シーケンスが与えられた場合、相対的な重みに基づいて要素が選ばれます。あるいは、`cum_weights' シーケンスが与えられた場合、累積的な重み (@ref{bf0,,itertools.accumulate()} を用いて計算されるかもしれません) で要素が選ばれます。例えば、相対的な重み @code{[10, 5, 30, 5]} は累積的な重み @code{[10, 15, 45, 50]} と等価です。内部的には、相対的な重みは要素選択の前に累積的な重みに変換されるため、累積的な重みを渡すと手間を省けます。

`weights' および `cum_weights' が与えられなかった場合、要素は同じ確率で選択されます。重みのシーケンスが与えられた場合、その長さは `population' シーケンスと同じでなければなりません。`weights' と `cum_weights' を同時に与えると @ref{198,,TypeError} が送出されます。

`weights' や `cum_weights' には @ref{bd,,random()} が返す @ref{196,,float} 値と相互に変換できるような、任意の数値型を使用できます (int、float、fraction を含みますが、decimal は除きます)。重みには非負で有限の値を指定することが規定されます。全ての重みが 0 の場合、例外 @ref{2ec,,ValueError} が送出されます。

与えられた種に対して、同じ重みを持つ @ref{ec1,,choices()} 関数は、一般に @ref{1448,,choice()} を繰り返し呼び出す場合とは異なるシーケンスを生成します。 @ref{ec1,,choices()} で使用されるアルゴリズムは、内部の一貫性とスピードのために浮動小数点演算を使用します。 @ref{1448,,choice()} で使われるアルゴリズムは、丸め誤差による小さな偏りを避けるために、デフォルトでは選択を繰り返す整数演算になっています。


Added in version 3.6.



バージョン 3.9 で変更: 全ての重みが 0 の場合、例外 @ref{2ec,,ValueError} を送出します。

@end deffn

@geindex shuffle() (random モジュール)
@anchor{library/random random shuffle}@anchor{94e}
@deffn {の関数} random.shuffle (x)

シーケンス `x' をインプレースにシャッフルします。

イミュータブルなシーケンスをシャッフルしてシャッフルされたリストを新たに返すには、代わりに @code{sample(x, k=len(x))} を使用してください。

たとえ @code{len(x)} が小さくても、`x' の並べ替えの総数 (訳注: 要素数の階乗) は大半の乱数生成器の周期よりもすぐに大きくなることに注意してください。つまり、長いシーケンスの大半の並べ替えは決して生成されないだろう、ということです。例えば、長さ 2080 のシーケンスがメルセンヌツイスタ生成器の周期に収まる中で最大のものになります。


バージョン 3.11 で変更: オプション引数 `random' が削除されました。

@end deffn

@geindex sample() (random モジュール)
@anchor{library/random random sample}@anchor{94d}
@deffn {の関数} random.sample (population, k, *, counts=None)

母集団のシーケンスから選ばれた長さ `k' の一意な要素からなるリストを返します。値の置換を行わないランダムサンプリングに用いられます。

母集団自体を変更せずに、母集団内の要素を含む新たなリストを返します。返されたリストは選択された順に並んでいるので、このリストの部分スライスもランダムなサンプルになります。これにより、くじの当選者 (サンプル) を1等賞と2等賞（の部分スライス）に分けることも可能です。

母集団の要素は @ref{824,,ハッシュ可能} でなくても、ユニークでなくてもかまいません。母集団が繰り返しを含む場合、出現するそれぞれがサンプルに選択されえます。

母集団に重複がある場合はその分だけ1つずつ指定するか、キーワード専用オプション引数 `counts' で指定することができます。例えば、 @code{sample(['red', 'blue'], counts=[4, 2], k=5)} は @code{sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)} と等価になります。

ある範囲の整数からサンプルを取る場合、引数に @ref{b3d,,range()} オブジェクトを使用してください。大きな母集団の場合、これは特に速く、メモリ効率が良いです: @code{sample(range(10000000), k=60)}。

サンプルの大きさが母集団の大きさより大きい場合 @ref{2ec,,ValueError} が送出されます。


バージョン 3.9 で変更: `counts' 引数が追加されました。



バージョン 3.11 で変更: `population' 変数はシーケンスでなければなりません。
setsのリストへの暗黙の型変換はサポートされていません。

@end deffn

@node Discrete distributions,実数分布,シーケンス用の関数,random --- 疑似乱数を生成する
@anchor{library/random discrete-distributions}@anchor{2b5f}
@subsubsection Discrete distributions


The following function generates a discrete distribution.

@geindex binomialvariate() (random モジュール)
@anchor{library/random random binomialvariate}@anchor{6d7}
@deffn {の関数} random.binomialvariate (n=1, p=0.5)

Binomial distribution@footnote{https://mathworld.wolfram.com/BinomialDistribution.html}.
Return the number of successes for `n' independent trials with the
probability of success in each trial being `p':

Mathematically equivalent to:

@example
sum(random() < p for i in range(n))
@end example

The number of trials `n' should be a non-negative integer.
The probability of success `p' should be between @code{0.0 <= p <= 1.0}.
The result is an integer in the range @code{0 <= X <= n}.


Added in version 3.12.

@end deffn

@node 実数分布,他の生成器,Discrete distributions,random --- 疑似乱数を生成する
@anchor{library/random id1}@anchor{2b60}@anchor{library/random real-valued-distributions}@anchor{2b61}
@subsubsection 実数分布


以下の関数は特定の実数値分布を生成します。関数の引数の名前は、一般的な数学の慣例で使われている分布の公式の対応する変数から取られています; これらの公式のほとんどはどんな統計学のテキストにも載っています。

@geindex random() (random モジュール)
@anchor{library/random random random}@anchor{94f}
@deffn {の関数} random.random ()

ランダムな浮動小数点数（範囲は @code{0.0 <= X < 1.0}）を返します。
@end deffn

@geindex uniform() (random モジュール)
@anchor{library/random random uniform}@anchor{2b62}
@deffn {の関数} random.uniform (a, b)

@code{a <= b} であれば @code{a <= N <= b} 、@code{b < a} であれば @code{b <= N <= a} であるようなランダムな浮動小数点数 `N' を返します。

端点の値 @code{b} が範囲に含まれるかどうかは、式 @code{a + (b-a) * random()} における浮動小数点の丸めに依存します。
@end deffn

@geindex triangular() (random モジュール)
@anchor{library/random random triangular}@anchor{2b63}
@deffn {の関数} random.triangular (low, high, mode)

@code{low <= N <= high} でありこれら境界値の間に指定された最頻値 `mode' を持つようなランダムな浮動小数点数 `N' を返します。境界 `low' と `high' のデフォルトは 0 と 1 です。最頻値 `mode' 引数のデフォルトは両境界値の中点になり、対称な分布を与えます。
@end deffn

@geindex betavariate() (random モジュール)
@anchor{library/random random betavariate}@anchor{2b64}
@deffn {の関数} random.betavariate (alpha, beta)

ベータ分布です。引数の満たすべき条件は @code{alpha > 0} および @code{beta > 0} です。 0 から 1 の範囲の値を返します。
@end deffn

@geindex expovariate() (random モジュール)
@anchor{library/random random expovariate}@anchor{6d8}
@deffn {の関数} random.expovariate (lambd=1.0)

指数分布です。`lambd' は平均にしたい値の逆数です。(この引数は "lambda" と呼ぶべきなのですが、Python の予約語なので使えません。) 返す値の範囲は `lambd' が正なら 0 から正の無限大、`lambd' が負なら負の無限大から 0 です。


バージョン 3.12 で変更: @code{lambd} にデフォルト値を追加しました。

@end deffn

@geindex gammavariate() (random モジュール)
@anchor{library/random random gammavariate}@anchor{2b65}
@deffn {の関数} random.gammavariate (alpha, beta)

Gamma distribution.  (`Not' the gamma function!)  The shape and
scale parameters, `alpha' and `beta', must have positive values.
(Calling conventions vary and some sources define 'beta'
as the inverse of the scale).

確率分布関数は:

@example
          x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) =  --------------------------------------
            math.gamma(alpha) * beta ** alpha
@end example
@end deffn

@geindex gauss() (random モジュール)
@anchor{library/random random gauss}@anchor{1bd8}
@deffn {の関数} random.gauss (mu=0.0, sigma=1.0)

正規分布、またはガウス分布と呼ばれます。 `mu' は平均であり、 `sigma' は標準偏差です。この関数は後で定義する関数 @ref{1bd9,,normalvariate()} より少しだけ高速です。

Multithreading note:  When two threads call this function
simultaneously, it is possible that they will receive the
same return value.  This can be avoided in three ways.
1) Have each thread use a different instance of the random
number generator. 2) Put locks around all calls. 3) Use the
slower, but thread-safe @ref{1bd9,,normalvariate()} function instead.


バージョン 3.11 で変更: `mu' と `sigma' にデフォルト値を追加しました。

@end deffn

@geindex lognormvariate() (random モジュール)
@anchor{library/random random lognormvariate}@anchor{2b66}
@deffn {の関数} random.lognormvariate (mu, sigma)

対数正規分布です。この分布を自然対数を用いた分布にした場合、平均 `mu' で標準偏差 `sigma' の正規分布になります。 `mu' は任意の値を取ることができ、`sigma' はゼロより大きくなければなりません。
@end deffn

@geindex normalvariate() (random モジュール)
@anchor{library/random random normalvariate}@anchor{1bd9}
@deffn {の関数} random.normalvariate (mu=0.0, sigma=1.0)

正規分布です。 `mu' は平均で、 `sigma' は標準偏差です。


バージョン 3.11 で変更: `mu' と `sigma' にデフォルト値を追加しました。

@end deffn

@geindex vonmisesvariate() (random モジュール)
@anchor{library/random random vonmisesvariate}@anchor{2b67}
@deffn {の関数} random.vonmisesvariate (mu, kappa)

`mu' は平均の角度で、0 から 2*`pi' までのラジアンで表されます。 `kappa' は濃度パラメータで、ゼロ以上でなければなりません。`kappa' がゼロに等しい場合、この分布は範囲 0 から 2*`pi' の一様でランダムな角度の分布に退化します。
@end deffn

@geindex paretovariate() (random モジュール)
@anchor{library/random random paretovariate}@anchor{2b68}
@deffn {の関数} random.paretovariate (alpha)

パレート分布です。 `alpha' は形状パラメータです。
@end deffn

@geindex weibullvariate() (random モジュール)
@anchor{library/random random weibullvariate}@anchor{2b69}
@deffn {の関数} random.weibullvariate (alpha, beta)

ワイブル分布です。 `alpha' は尺度パラメタで、 `beta' は形状パラメータです。
@end deffn

@node 他の生成器,再現性について,実数分布,random --- 疑似乱数を生成する
@anchor{library/random alternative-generator}@anchor{2b6a}
@subsubsection 他の生成器


@geindex Random (random のクラス)
@anchor{library/random random Random}@anchor{1c5c}
@deffn {クラス} random.Random ([seed])

Class that implements the default pseudo-random number generator used by the
@code{random} module.


バージョン 3.11 で変更: 以前は `seed' は任意のハッシュ可能オブジェクトが設定可能でした。現在は @code{None}, @ref{19b,,int}, @ref{196,,float}, @ref{169,,str}, @ref{192,,bytes}, @ref{344,,bytearray} に制限されています。


Subclasses of @code{Random} should override the following methods if they
wish to make use of a different basic generator:

@geindex seed() (random.Random のメソッド)
@anchor{library/random random Random seed}@anchor{1d6a}
@deffn {メソッド} seed (a=None, version=2)

Override this method in subclasses to customise the @ref{148b,,seed()}
behaviour of @code{Random} instances.
@end deffn

@geindex getstate() (random.Random のメソッド)
@anchor{library/random random Random getstate}@anchor{2b6b}
@deffn {メソッド} getstate ()

Override this method in subclasses to customise the @ref{2b59,,getstate()}
behaviour of @code{Random} instances.
@end deffn

@geindex setstate() (random.Random のメソッド)
@anchor{library/random random Random setstate}@anchor{2b6c}
@deffn {メソッド} setstate (state)

Override this method in subclasses to customise the @ref{2b5a,,setstate()}
behaviour of @code{Random} instances.
@end deffn

@geindex random() (random.Random のメソッド)
@anchor{library/random random Random random}@anchor{2b6d}
@deffn {メソッド} random ()

Override this method in subclasses to customise the @ref{94f,,random()}
behaviour of @code{Random} instances.
@end deffn

Optionally, a custom generator subclass can also supply the following method:

@geindex getrandbits() (random.Random のメソッド)
@anchor{library/random random Random getrandbits}@anchor{2b6e}
@deffn {メソッド} getrandbits (k)

Override this method in subclasses to customise the
@ref{120f,,getrandbits()} behaviour of @code{Random} instances.
@end deffn

@geindex randbytes() (random.Random のメソッド)
@anchor{library/random random Random randbytes}@anchor{b23}
@deffn {メソッド} randbytes (n)

Override this method in subclasses to customise the
@ref{1826,,randbytes()} behaviour of @code{Random} instances.
@end deffn
@end deffn

@geindex SystemRandom (random のクラス)
@anchor{library/random random SystemRandom}@anchor{2b57}
@deffn {クラス} random.SystemRandom ([seed])

オペレーティングシステムの提供する発生源によって乱数を生成する @ref{746,,os.urandom()} 関数を使うクラスです。すべてのシステムで使えるメソッドではありません。ソフトウェアの状態に依存してはいけませんし、一連の操作は再現不能です。従って、 @ref{148b,,seed()} メソッドは何の影響も及ぼさず、無視されます。 @ref{2b59,,getstate()} と @ref{2b5a,,setstate()} メソッドが呼び出されると、例外 @ref{36b,,NotImplementedError} が送出されます。
@end deffn

@node 再現性について,使用例<7>,他の生成器,random --- 疑似乱数を生成する
@anchor{library/random notes-on-reproducibility}@anchor{2b6f}
@subsubsection 再現性について


疑似乱数生成器から与えられたシーケンスを再現できると便利なことがあります。シード値を再利用することで、複数のスレッドが実行されていない限り、実行ごとに同じシーケンスが再現できます。

random モジュールのアルゴリズムやシード処理関数のほとんどは、Python バージョン間で変更される対象となりますが、次の二点は変更されないことが保証されています:


@itemize *

@item 
新しいシード処理メソッドが追加されたら、後方互換なシード処理器が提供されます。

@item 
生成器の @ref{2b6d,,random()} メソッドは、互換なシード処理器に同じシードが与えられた場合、引き続き同じシーケンスを生成します。
@end itemize

@node 使用例<7>,レシピ<2>,再現性について,random --- 疑似乱数を生成する
@anchor{library/random examples}@anchor{2b70}@anchor{library/random random-examples}@anchor{13f5}
@subsubsection 使用例


基礎的な例:

@example
>>> random()                          # Random float:  0.0 <= x < 1.0
0.37444887175646646

>>> uniform(2.5, 10.0)                # Random float:  2.5 <= x <= 10.0
3.1800146073117523

>>> expovariate(1 / 5)                # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange(10)                     # Integer from 0 to 9 inclusive
7

>>> randrange(0, 101, 2)              # Even integer from 0 to 100 inclusive
26

>>> choice(['win', 'lose', 'draw'])   # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split()
>>> shuffle(deck)                     # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement
[40, 10, 50, 30]
@end example

シミュレーション:

@example
>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> deal = sample(['tens', 'low cards'], counts=[16, 36], k=20)
>>> deal.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.
>>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial():
...     return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500
...
>>> sum(trial() for i in range(10_000)) / 10_000
0.7958
@end example

サンプルの平均の信頼区間を推定するのに、重複ありでリサンプリングして 統計的ブートストラップ@footnote{https://ja.wikipedia.org/wiki/%E3%83%96%E3%83%BC%E3%83%88%E3%82%B9%E3%83%88%E3%83%A9%E3%83%83%E3%83%97%E6%B3%95} を行う例:

@example
# https://www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted(mean(choices(data, k=len(data))) for i in range(100))
print(f'The sample mean of @{mean(data):.1f@} has a 90% confidence '
      f'interval from @{means[5]:.1f@} to @{means[94]:.1f@}')
@end example

薬と偽薬の間に観察された効果の違いについて、統計的有意性、すなわち p 値@footnote{https://en.wikipedia.org/wiki/P-value} を決定するために、リサンプリング順列試験@footnote{https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests} を行う例:

@example
# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean(drug) - mean(placebo)

n = 10_000
count = 0
combined = drug + placebo
for i in range(n):
    shuffle(combined)
    new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
    count += (new_diff >= observed_diff)

print(f'@{n@} label reshufflings produced only @{count@} instances with a difference')
print(f'at least as extreme as the observed difference of @{observed_diff:.1f@}.')
print(f'The one-sided p-value of @{count / n:.4f@} leads us to reject the null')
print(f'hypothesis that there is no difference between the drug and the placebo.')
@end example

マルチサーバーキューにおける到達時間とサービス提供のシミュレーション:

@example
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

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@}   Max wait: @{max(waits):.1f@}')
print('Quartiles:', [round(q, 1) for q in quantiles(waits)])
@end example


@subsubheading 参考


Statistics for Hackers@footnote{https://www.youtube.com/watch?v=Iq9DzN6mvYA} Jake Vanderplas@footnote{https://us.pycon.org/2016/speaker/profile/295/} による統計解析のビデオ。シミュレーション、サンプリング、シャッフル、交差検定といった基本的な概念のみを用いています。

Economics Simulation@footnote{https://nbviewer.org/url/norvig.com/ipython/Economics.ipynb} Peter Norvig@footnote{https://norvig.com/bio.html} による市場価格のシミュレーション。このモジュールが提供する多くのツールや分布 (gauss, uniform, sample, betavariate, choice, triangular, randrange) の活用法を示しています。

A Concrete Introduction to Probability (using Python)@footnote{https://nbviewer.org/url/norvig.com/ipython/Probability.ipynb} Peter Norvig@footnote{https://norvig.com/bio.html} によるチュートリアル。確率論の基礎、シミュレーションの書き方、Python を使用したデータ解析法をカバーしています。


@node レシピ<2>,コマンドラインでの使用<2>,使用例<7>,random --- 疑似乱数を生成する
@anchor{library/random recipes}@anchor{2b71}
@subsubsection レシピ


These recipes show how to efficiently make random selections
from the combinatoric iterators in the @ref{85,,itertools} module:

@example
import random

def random_product(*iterables, repeat=1):
    "Random selection from itertools.product(*iterables, repeat=repeat)"
    pools = tuple(map(tuple, iterables)) * 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):
    "Choose r elements with replacement.  Order the result to match the iterable."
    # Result will be in set(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 random_derangement(iterable):
    "Choose a permutation where no element stays in its original position."
    seq = tuple(iterable)
    if len(seq) < 2:
        if not seq:
            return ()
        raise IndexError('No derangments to choose from')
    perm = list(range(len(seq)))
    start = tuple(perm)
    while True:
        random.shuffle(perm)
        if all(p != q for p, q in zip(start, perm)):
            return tuple([seq[i] for i in perm])
@end example

@c >>> import random
@c 
@c 
@c >>> random.seed(8675309)
@c >>> random_product('ABCDEFG', repeat=5)
@c ('D', 'B', 'E', 'F', 'E')
@c 
@c 
@c >>> random.seed(8675309)
@c >>> random_permutation('ABCDEFG')
@c ('D', 'B', 'E', 'C', 'G', 'A', 'F')
@c >>> random_permutation('ABCDEFG', 5)
@c ('A', 'G', 'D', 'C', 'B')
@c 
@c 
@c >>> random.seed(8675309)
@c >>> random_combination('ABCDEFG', 7)
@c ('A', 'B', 'C', 'D', 'E', 'F', 'G')
@c >>> random_combination('ABCDEFG', 6)
@c ('A', 'B', 'C', 'D', 'F', 'G')
@c >>> random_combination('ABCDEFG', 5)
@c ('A', 'B', 'C', 'E', 'F')
@c >>> random_combination('ABCDEFG', 4)
@c ('B', 'C', 'D', 'G')
@c >>> random_combination('ABCDEFG', 3)
@c ('B', 'E', 'G')
@c >>> random_combination('ABCDEFG', 2)
@c ('E', 'G')
@c >>> random_combination('ABCDEFG', 1)
@c ('C',)
@c >>> random_combination('ABCDEFG', 0)
@c ()
@c 
@c 
@c >>> random.seed(8675309)
@c >>> random_combination_with_replacement('ABCDEFG', 7)
@c ('B', 'C', 'D', 'E', 'E', 'E', 'G')
@c >>> random_combination_with_replacement('ABCDEFG', 3)
@c ('A', 'B', 'E')
@c >>> random_combination_with_replacement('ABCDEFG', 2)
@c ('A', 'G')
@c >>> random_combination_with_replacement('ABCDEFG', 1)
@c ('E',)
@c >>> random_combination_with_replacement('ABCDEFG', 0)
@c ()
@c 
@c 
@c >>> random.seed(8675309)
@c >>> random_derangement('')
@c ()
@c >>> random_derangement('A')
@c Traceback (most recent call last):
@c ...
@c IndexError: No derangments to choose from
@c >>> random_derangement('AB')
@c ('B', 'A')
@c >>> random_derangement('ABC')
@c ('C', 'A', 'B')
@c >>> random_derangement('ABCD')
@c ('B', 'A', 'D', 'C')
@c >>> random_derangement('ABCDE')
@c ('B', 'C', 'A', 'E', 'D')
@c >>> # Identical inputs treated as distinct
@c >>> identical = 20
@c >>> random_derangement((10, identical, 30, identical))
@c (20, 30, 10, 20)

The default @ref{94f,,random()} returns multiples of 2⁻⁵³ in the range
`0.0 ≤ x < 1.0'.  All such numbers are evenly spaced and are exactly
representable as Python floats.  However, many other representable
floats in that interval are not possible selections.  For example,
@code{0.05954861408025609} isn't an integer multiple of 2⁻⁵³.

The following recipe takes a different approach.  All floats in the
interval are possible selections.  The mantissa comes from a uniform
distribution of integers in the range `2⁵² ≤ mantissa < 2⁵³'.  The
exponent comes from a geometric distribution where exponents smaller
than `-53' occur half as often as the next larger exponent.

@example
from random import Random
from math import ldexp

class FullRandom(Random):

    def random(self):
        mantissa = 0x10_0000_0000_0000 | self.getrandbits(52)
        exponent = -53
        x = 0
        while not x:
            x = self.getrandbits(32)
            exponent += x.bit_length() - 32
        return ldexp(mantissa, exponent)
@end example

All @ref{2b61,,real valued distributions}
in the class will use the new method:

@example
>>> fr = FullRandom()
>>> fr.random()
0.05954861408025609
>>> fr.expovariate(0.25)
8.87925541791544
@end example

The recipe is conceptually equivalent to an algorithm that chooses from
all the multiples of 2⁻¹⁰⁷⁴ in the range `0.0 ≤ x < 1.0'.  All such
numbers are evenly spaced, but most have to be rounded down to the
nearest representable Python float.  (The value 2⁻¹⁰⁷⁴ is the smallest
positive unnormalized float and is equal to @code{math.ulp(0.0)}.)


@subsubheading 参考


Generating Pseudo-random Floating-Point Values@footnote{https://allendowney.com/research/rand/downey07randfloat.pdf} a
paper by Allen B. Downey describing ways to generate more
fine-grained floats than normally generated by @ref{94f,,random()}.


@node コマンドラインでの使用<2>,コマンドラインの例,レシピ<2>,random --- 疑似乱数を生成する
@anchor{library/random command-line-usage}@anchor{2b72}@anchor{library/random random-cli}@anchor{47f}
@subsubsection コマンドラインでの使用



Added in version 3.13.


@code{random} モジュールはコマンドラインから実行できます。

@example
python -m random [-h] [-c CHOICE [CHOICE ...] | -i N | -f N] [input ...]
@end example

以下のオプションが使用できます:

@geindex random コマンドラインオプション; -h
@geindex random コマンドラインオプション; --help
@anchor{library/random cmdoption-random-h}@anchor{2b73}@anchor{library/random cmdoption-random-help}@anchor{2b74}
@deffn {Option} @w{-}h, @w{-}@w{-}help

ヘルプメッセージを表示して終了します。
@end deffn

@geindex random コマンドラインオプション; -c
@geindex random コマンドラインオプション; --choice
@anchor{library/random cmdoption-random-c}@anchor{2b75}
@deffn {Option} @w{-}c CHOICE [CHOICE ...]
@anchor{library/random cmdoption-random-choice}@anchor{2b76}
@deffnx {Option} @w{-}@w{-}choice CHOICE [CHOICE ...]

@ref{1448,,choice()} を使用してランダムに選択して出力します。
@end deffn

@geindex random コマンドラインオプション; -i
@geindex random コマンドラインオプション; --integer
@anchor{library/random cmdoption-random-i}@anchor{2b77}
@deffn {Option} @w{-}i <N>
@anchor{library/random cmdoption-random-integer}@anchor{2b78}
@deffnx {Option} @w{-}@w{-}integer <N>

@ref{1447,,randint()} を使用して1からNの間(Nを含む)のランダムな整数を出力します。
@end deffn

@geindex random コマンドラインオプション; -f
@geindex random コマンドラインオプション; --float
@anchor{library/random cmdoption-random-f}@anchor{2b79}
@deffn {Option} @w{-}f <N>
@anchor{library/random cmdoption-random-float}@anchor{2b7a}
@deffnx {Option} @w{-}@w{-}float <N>

@ref{2b62,,uniform()} を使用して0からNの間(Nを含む)のランダムな浮動小数点数を出力します。
@end deffn

オプションが指定されない場合、出力は入力に依存します。


@itemize *

@item 
文字列または複数: @ref{2b76,,--choice} と同じ。

@item 
整数: @ref{2b78,,--integer} と同じ。

@item 
浮動小数点数: @ref{2b7a,,--float} と同じ。
@end itemize

@node コマンドラインの例,,コマンドラインでの使用<2>,random --- 疑似乱数を生成する
@anchor{library/random command-line-example}@anchor{2b7b}@anchor{library/random random-cli-example}@anchor{2b7c}
@subsubsection コマンドラインの例


以下は @code{random} のコマンドラインインターフェースの例です:

@example
$ # Choose one at random
$ python -m random egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce"
Lobster Thermidor aux crevettes with a Mornay sauce

$ # Random integer
$ python -m random 6
6

$ # Random floating-point number
$ python -m random 1.8
1.7080016272295635

$ # With explicit arguments
$ python  -m random --choice egg bacon sausage spam "Lobster Thermidor aux crevettes with a Mornay sauce"
egg

$ python -m random --integer 6
3

$ python -m random --float 1.8
1.5666339105010318

$ python -m random --integer 6
5

$ python -m random --float 6
3.1942323316565915
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node statistics --- 数学的統計関数,,random --- 疑似乱数を生成する,数値と数学モジュール
@anchor{library/statistics doc}@anchor{2b7d}@anchor{library/statistics module-statistics}@anchor{d7}@anchor{library/statistics statistics-mathematical-statistics-functions}@anchor{2b7e}@anchor{library/statistics translation-repo}@anchor{2b7f}
@subsection @code{statistics} --- 数学的統計関数


@geindex module; statistics


Added in version 3.4.


`ソースコード:' Lib/statistics.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/statistics.py}

@c from statistics import *
@c import math
@c __name__ = '<doctest>'


__________________________________________________________________


このモジュールは、数値 (@ref{25f2,,Real} 型) データを数学的に統計計算するための関数を提供します。

このモジュールは、 NumPy@footnote{https://numpy.org}, SciPy@footnote{https://scipy.org/} のような third-party ライブラリや、Minitab、SAS、Matlab のようなプロ統計家向けのフル装備なプロプライエタリ統計パッケージと競合することを意図していません。グラフ関数電卓のレベルを対象としています。

特に明記しない限り、これらの関数は @ref{19b,,int}, @ref{196,,float}, @ref{1fe,,Decimal} そして @ref{213,,Fraction} をサポートします。他の型 (算術型及びそれ以外) は現在サポートされていません。型が混ざったコレクションも未定義で実装依存です。入力データが複数の型からなる場合、@ref{19f,,map()} を使用すると正しい結果が得られるでしょう。 例: @code{map(float, input_data)}。

あるデータセットでは欠損値を表すために @code{NaN} (not a number) を使います。 NaNは通常と異なる比較セマンティクスを持つため、ソートやカウントを行う統計関数では、驚きや未定義の振る舞いを引き起こします。  影響を受ける関数は @code{median()}, @code{median_low()}, @code{median_high()}, @code{median_grouped()}, @code{mode()}, @code{multimode()}, そして @code{quantiles()} です。  これらの関数を呼ぶ前に、 @code{NaN} 値を取り除く必要があります:

@example
>>> from statistics import median
>>> from math import isnan
>>> from itertools import filterfalse

>>> data = [20.7, float('NaN'),19.2, 18.3, float('NaN'), 14.4]
>>> sorted(data)  # This has surprising behavior
[20.7, nan, 14.4, 18.3, 19.2, nan]
>>> median(data)  # This result is unexpected
16.35

>>> sum(map(isnan, data))    # Number of missing values
2
>>> clean = list(filterfalse(isnan, data))  # Strip NaN values
>>> clean
[20.7, 19.2, 18.3, 14.4]
>>> sorted(clean)  # Sorting now works as expected
[14.4, 18.3, 19.2, 20.7]
>>> median(clean)       # This result is now well defined
18.75
@end example

@menu
* 平均及び中心位置の測度:: 
* 分散の測度:: 
* 2入力間の関係の統計:: 
* 関数の詳細:: 
* 例外: 例外<5>. 
* NormalDist オブジェクト:: 
* 例とレシピ: 例とレシピ<2>. 

@end menu

@node 平均及び中心位置の測度,分散の測度,,statistics --- 数学的統計関数
@anchor{library/statistics averages-and-measures-of-central-location}@anchor{2b80}
@subsubsection 平均及び中心位置の測度


これらの関数は母集団または標本の平均値や標準値を計算します。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{8e1,,mean()}

@tab

データの算術平均 (いわゆる「平均」) 。

@item

@ref{c29,,fmean()}

@tab

Fast, floating-point arithmetic mean, with optional weighting.

@item

@ref{c2a,,geometric_mean()}

@tab

データの幾何平均。

@item

@ref{edd,,harmonic_mean()}

@tab

データの調和平均。

@item

@ref{553,,kde()}

@tab

Estimate the probability density distribution of the data.

@item

@ref{554,,kde_random()}

@tab

Random sampling from the PDF generated by kde().

@item

@ref{2b81,,median()}

@tab

データのメジアン(中央値)。

@item

@ref{2b82,,median_low()}

@tab

データの low median。

@item

@ref{2b83,,median_high()}

@tab

データの high median。

@item

@ref{2b84,,median_grouped()}

@tab

Median (50th percentile) of grouped data.

@item

@ref{c85,,mode()}

@tab

離散/名義尺度データの最頻値 (single mode) 。

@item

@ref{c2b,,multimode()}

@tab

離散/名義尺度データの最頻値 (list of modes) 。

@item

@ref{c2c,,quantiles()}

@tab

データの等確率での分割。

@end multitable


@node 分散の測度,2入力間の関係の統計,平均及び中心位置の測度,statistics --- 数学的統計関数
@anchor{library/statistics measures-of-spread}@anchor{2b85}
@subsubsection 分散の測度


これらの関数は母集団または標本が標準値や平均値からどれくらい離れているかについて計算します。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{17b0,,pstdev()}

@tab

データの母標準偏差。

@item

@ref{2b86,,pvariance()}

@tab

データの母分散。

@item

@ref{8e3,,stdev()}

@tab

データの標本標準偏差。

@item

@ref{8e2,,variance()}

@tab

データの標本標準分散。

@end multitable


@node 2入力間の関係の統計,関数の詳細,分散の測度,statistics --- 数学的統計関数
@anchor{library/statistics statistics-for-relations-between-two-inputs}@anchor{2b87}
@subsubsection 2入力間の関係の統計


これらの関数は、2つの入力間の関係について統計量を計算します。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{a31,,covariance()}

@tab

2変数の標本共分散。

@item

@ref{6e3,,correlation()}

@tab

ピアソンとスピアマンの相関係数。

@item

@ref{a32,,linear_regression()}

@tab

単回帰の傾きと切片。

@end multitable


@node 関数の詳細,例外<5>,2入力間の関係の統計,statistics --- 数学的統計関数
@anchor{library/statistics function-details}@anchor{2b88}
@subsubsection 関数の詳細


註釈: 関数の引数となるデータをソートしておく必要はありません。例の多くがソートされているのは見やすさのためです。

@geindex mean() (statistics モジュール)
@anchor{library/statistics statistics mean}@anchor{8e1}
@deffn {の関数} statistics.mean (data)

シーケンス型またはイテラブルになり得る `data' の標本算術平均を返します。

算術平均はデータの総和をデータ数で除したものです。単に「平均」と呼ばれることも多いですが、数学における平均の一種に過ぎません。データの中心位置の測度の一つです。

`data' が空の場合 @ref{2b89,,StatisticsError} を送出します。

使用例:

@example
>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625

>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)

>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
@end example

@cartouche
@quotation 注釈 
mean は 外れ値@footnote{https://ja.wikipedia.org/wiki/外れ値} (outliers@footnote{https://en.wikipedia.org/wiki/Outlier}) の影響を強く受け、必ずしもデータ点の典型例とはなりません。効率が悪いものの、より堅牢な、 中心的な傾向 (central tendency@footnote{https://en.wikipedia.org/wiki/Central_tendency}) の尺度については、 @ref{2b81,,median()} を参照してください。

標本平均は真の母平均の不偏推定量のため、出来る限り多くの標本から平均を求めると、@code{mean(sample)} は真の母平均に収束します (訳注: 大数の法則)。`data' が標本ではなく母集団全体の場合、@code{mean(data)} は真の母平均 μ を計算することと等価です。
@end quotation
@end cartouche
@end deffn

@geindex fmean() (statistics モジュール)
@anchor{library/statistics statistics fmean}@anchor{c29}
@deffn {の関数} statistics.fmean (data, weights=None)

`data' を float に変換し、算術平均を計算します。

This runs faster than the @ref{8e1,,mean()} function and it always returns a
@ref{196,,float}.  The `data' may be a sequence or iterable.  If the input
dataset is empty, raises a @ref{2b89,,StatisticsError}.

@example
>>> fmean([3.5, 4.0, 5.25])
4.25
@end example

Optional weighting is supported.  For example, a professor assigns a
grade for a course by weighting quizzes at 20%, homework at 20%, a
midterm exam at 30%, and a final exam at 30%:

@example
>>> grades = [85, 92, 83, 91]
>>> weights = [0.20, 0.20, 0.30, 0.30]
>>> fmean(grades, weights)
87.6
@end example

If `weights' is supplied, it must be the same length as the `data' or
a @ref{2ec,,ValueError} will be raised.


Added in version 3.8.



バージョン 3.11 で変更: `weights' のサポートが追加されました。

@end deffn

@geindex geometric_mean() (statistics モジュール)
@anchor{library/statistics statistics geometric_mean}@anchor{c2a}
@deffn {の関数} statistics.geometric_mean (data)

Convert `data' to floats and compute the geometric mean.

The geometric mean indicates the central tendency or typical value of the
`data' using the product of the values (as opposed to the arithmetic mean
which uses their sum).

Raises a @ref{2b89,,StatisticsError} if the input dataset is empty,
if it contains a zero, or if it contains a negative value.
The `data' may be a sequence or iterable.

No special efforts are made to achieve exact results.
(However, this may change in the future.)

@example
>>> round(geometric_mean([54, 24, 36]), 1)
36.0
@end example


Added in version 3.8.

@end deffn

@geindex harmonic_mean() (statistics モジュール)
@anchor{library/statistics statistics harmonic_mean}@anchor{edd}
@deffn {の関数} statistics.harmonic_mean (data, weights=None)

Return the harmonic mean of `data', a sequence or iterable of
real-valued numbers.  If `weights' is omitted or @code{None}, then
equal weighting is assumed.

調和平均（harmonic mean）は、データの逆数の算術平均 @ref{8e1,,mean()} の逆数です。例えば、3つの値 `a', `b', `c' の調和平均は`@w{`}3/(1/a + 1/b + 1/c)`@w{`} になります。いずれかの値が0の場合、結果は0になります。

調和平均は平均の一種で、データの中心位置の測度です。速度のような比(ratios)や率(rates)を平均するときにしばしば適切です。

Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr.
What is the average speed?

@example
>>> harmonic_mean([40, 60])
48.0
@end example

Suppose a car travels 40 km/hr for 5 km, and when traffic clears,
speeds-up to 60 km/hr for the remaining 30 km of the journey. What
is the average speed?

@example
>>> harmonic_mean([40, 60], weights=[5, 30])
56.0
@end example

@ref{2b89,,StatisticsError} is raised if `data' is empty, any element
is less than zero, or if the weighted sum isn't positive.

The current algorithm has an early-out when it encounters a zero
in the input.  This means that the subsequent inputs are not tested
for validity.  (This behavior may change in the future.)


Added in version 3.6.



バージョン 3.10 で変更: `weights' のサポートが追加されました。

@end deffn

@geindex kde() (statistics モジュール)
@anchor{library/statistics statistics kde}@anchor{553}
@deffn {の関数} statistics.kde (data, h, kernel='normal', *, cumulative=False)

Kernel Density Estimation (KDE)@footnote{https://www.itm-conferences.org/articles/itmconf/pdf/2018/08/itmconf_sam2018_00037.pdf}:
Create a continuous probability density function or cumulative
distribution function from discrete samples.

The basic idea is to smooth the data using a kernel function@footnote{https://en.wikipedia.org/wiki/Kernel_(statistics)}.
to help draw inferences about a population from a sample.

The degree of smoothing is controlled by the scaling parameter `h'
which is called the bandwidth.  Smaller values emphasize local
features while larger values give smoother results.

The `kernel' determines the relative weights of the sample data
points.  Generally, the choice of kernel shape does not matter
as much as the more influential bandwidth smoothing parameter.

Kernels that give some weight to every sample point include
`normal' (`gauss'), `logistic', and `sigmoid'.

Kernels that only give weight to sample points within the bandwidth
include `rectangular' (`uniform'), `triangular', `parabolic'
(`epanechnikov'), `quartic' (`biweight'), `triweight', and `cosine'.

If `cumulative' is true, will return a cumulative distribution function.

A @ref{2b89,,StatisticsError} will be raised if the `data' sequence is empty.

Wikipedia has an example@footnote{https://en.wikipedia.org/wiki/Kernel_density_estimation#Example}
where we can use @ref{553,,kde()} to generate and plot a probability
density function estimated from a small sample:

@example
>>> sample = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]
>>> f_hat = kde(sample, h=1.5)
>>> xarr = [i/100 for i in range(-750, 1100)]
>>> yarr = [f_hat(x) for x in xarr]
@end example

The points in @code{xarr} and @code{yarr} can be used to make a PDF plot:

@image{python-figures/kde_example,,,Scatter plot of the estimated probability density function.,png}


Added in version 3.13.

@end deffn

@geindex kde_random() (statistics モジュール)
@anchor{library/statistics statistics kde_random}@anchor{554}
@deffn {の関数} statistics.kde_random (data, h, kernel='normal', *, seed=None)

Return a function that makes a random selection from the estimated
probability density function produced by @code{kde(data, h, kernel)}.

Providing a `seed' allows reproducible selections. In the future, the
values may change slightly as more accurate kernel inverse CDF estimates
are implemented.  The seed may be an integer, float, str, or bytes.

A @ref{2b89,,StatisticsError} will be raised if the `data' sequence is empty.

Continuing the example for @ref{553,,kde()}, we can use
@ref{554,,kde_random()} to generate new random selections from an
estimated probability density function:

@example
>>> data = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]
>>> rand = kde_random(data, h=1.5, seed=8675309)
>>> new_selections = [rand() for i in range(10)]
>>> [round(x, 1) for x in new_selections]
[0.7, 6.2, 1.2, 6.9, 7.0, 1.8, 2.5, -0.5, -1.8, 5.6]
@end example


Added in version 3.13.

@end deffn

@geindex median() (statistics モジュール)
@anchor{library/statistics statistics median}@anchor{2b81}
@deffn {の関数} statistics.median (data)

一般的な「中央2つの平均をとる」方法を使用して、数値データの中央値（中間値）を返します。もし `data' が空の場合、例外 @ref{2b89,,StatisticsError} が送出されます。`data' はシーケンス型またはイテラブルにもなれます。

中央値は外れ値の影響を受けにくいため、中心位置のロバストな測度です。データ数が奇数の場合は中央の値を返します:

@example
>>> median([1, 3, 5])
3
@end example

データ数が偶数の場合は、中央値は中央に最も近い2値の算術平均で補間されます:

@example
>>> median([1, 3, 5, 7])
4.0
@end example

データが離散的で、中央値がデータ点にない値でも構わない場合に適しています。

もしあなたのデータが（注文操作をサポートする）序数で、（追加操作をサポートしない）数値でないならば、代わりに @ref{2b82,,median_low()} または @ref{2b83,,median_high()} の使用を検討してください。
@end deffn

@geindex median_low() (statistics モジュール)
@anchor{library/statistics statistics median_low}@anchor{2b82}
@deffn {の関数} statistics.median_low (data)

数値データの小さい方の中央値(low median)を返します。もし `data' が空の場合、@ref{2b89,,StatisticsError} が送出されます。`data' はシーケンス型またはイテラブルにもなれます。

low median は必ずデータに含まれています。データ数が奇数の場合は中央の値を返し、偶数の場合は中央の2値の小さい方を返します。

@example
>>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3
@end example

データが離散的で、中央値が補間値よりもデータ点にある値の方が良い場合に用いてください。
@end deffn

@geindex median_high() (statistics モジュール)
@anchor{library/statistics statistics median_high}@anchor{2b83}
@deffn {の関数} statistics.median_high (data)

データの大きい方の中央値(high median)を返します。もし `data' が空の場合、@ref{2b89,,StatisticsError} が送出されます。 `data' はシーケンス型やイテラブルにもなれます。

high median は必ずデータに含まれています。データ数が奇数の場合は中央の値を返し、偶数の場合は中央の2値の大きい方を返します。

@example
>>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5
@end example

データが離散的で、中央値が補間値よりもデータ点にある値の方が良い場合に用いてください。
@end deffn

@geindex median_grouped() (statistics モジュール)
@anchor{library/statistics statistics median_grouped}@anchor{2b84}
@deffn {の関数} statistics.median_grouped (data, interval=1.0)

Estimates the median for numeric data that has been grouped or binned@footnote{https://en.wikipedia.org/wiki/Data_binning} around the midpoints
of consecutive, fixed-width intervals.

The `data' can be any iterable of numeric data with each value being
exactly the midpoint of a bin.  At least one value must be present.

The `interval' is the width of each bin.

For example, demographic information may have been summarized into
consecutive ten-year age groups with each group being represented
by the 5-year midpoints of the intervals:

@example
>>> from collections import Counter
>>> demographics = Counter(@{
...    25: 172,   # 20 to 30 years old
...    35: 484,   # 30 to 40 years old
...    45: 387,   # 40 to 50 years old
...    55:  22,   # 50 to 60 years old
...    65:   6,   # 60 to 70 years old
... @})
...
@end example

The 50th percentile (median) is the 536th person out of the 1071
member cohort.  That person is in the 30 to 40 year old age group.

The regular @ref{2b81,,median()} function would assume that everyone in the
tricenarian age group was exactly 35 years old.  A more tenable
assumption is that the 484 members of that age group are evenly
distributed between 30 and 40.  For that, we use
@ref{2b84,,median_grouped()}:

@example
>>> data = list(demographics.elements())
>>> median(data)
35
>>> round(median_grouped(data, interval=10), 1)
37.5
@end example

The caller is responsible for making sure the data points are separated
by exact multiples of `interval'.  This is essential for getting a
correct result.  The function does not check this precondition.

Inputs may be any numeric type that can be coerced to a float during
the interpolation step.
@end deffn

@geindex mode() (statistics モジュール)
@anchor{library/statistics statistics mode}@anchor{c85}
@deffn {の関数} statistics.mode (data)

Return the single most common data point from discrete or nominal `data'.
The mode (when it exists) is the most typical value and serves as a
measure of central location.

If there are multiple modes with the same frequency, returns the first one
encountered in the `data'.  If the smallest or largest of those is
desired instead, use @code{min(multimode(data))} or @code{max(multimode(data))}.
If the input `data' is empty, @ref{2b89,,StatisticsError} is raised.

@code{mode} は離散データであることを想定していて、1つの値を返します。これは学校で教わるような最頻値の標準的な取扱いです:

@example
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
@end example

The mode is unique in that it is the only statistic in this package that
also applies to nominal (non-numeric) data:

@example
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
@end example

Only hashable inputs are supported.  To handle type @ref{184,,set},
consider casting to @ref{7f2,,frozenset}.  To handle type @ref{24d,,list},
consider casting to @ref{614,,tuple}.  For mixed or nested inputs, consider
using this slower quadratic algorithm that only depends on equality tests:
@code{max(data, key=data.count)}.


バージョン 3.8 で変更: Now handles multimodal datasets by returning the first mode encountered.
Formerly, it raised @ref{2b89,,StatisticsError} when more than one mode was
found.

@end deffn

@geindex multimode() (statistics モジュール)
@anchor{library/statistics statistics multimode}@anchor{c2b}
@deffn {の関数} statistics.multimode (data)

Return a list of the most frequently occurring values in the order they
were first encountered in the `data'.  Will return more than one result if
there are multiple modes or an empty list if the `data' is empty:

@example
>>> multimode('aabbbbccddddeeffffgg')
['b', 'd', 'f']
>>> multimode('@w{'})
[]
@end example


Added in version 3.8.

@end deffn

@geindex pstdev() (statistics モジュール)
@anchor{library/statistics statistics pstdev}@anchor{17b0}
@deffn {の関数} statistics.pstdev (data, mu=None)

母標準偏差 (母分散の平方根) を返します。引数や詳細は @ref{2b86,,pvariance()} を参照してください。

@example
>>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251
@end example
@end deffn

@geindex pvariance() (statistics モジュール)
@anchor{library/statistics statistics pvariance}@anchor{2b86}
@deffn {の関数} statistics.pvariance (data, mu=None)

`data' の母分散を返します。`data' は実数の空でないシーケンスまたはイテラブルです。分散、すなわち2次の中心化モーメントはデータの散らばり具合の測度です。分散が大きいデータはばらつきが大きく、分散が小さいデータは平均値のまわりに固まっています。

If the optional second argument `mu' is given, it should be the `population'
mean of the `data'.  It can also be used to compute the second moment around
a point that is not the mean.  If it is missing or @code{None} (the default),
the arithmetic mean is automatically calculated.

母集団全体から分散を計算する場合に用いてください。標本から分散を推定する場合は @ref{8e2,,variance()} を使いましょう。

`data' が空の場合 @ref{2b89,,StatisticsError} を送出します。

例:

@example
>>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25
@end example

既にデータの平均値を計算している場合、それを第2引数 `mu' に渡して再計算を避けることが出来ます:

@example
>>> mu = mean(data)
>>> pvariance(data, mu)
1.25
@end example

Decimal と Fraction がサポートされています:

@example
>>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')

>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)
@end example

@cartouche
@quotation 注釈 
母集団全体で呼んだ場合は母分散 σ² を返します。代わりに標本で呼んだ場合は biased variance s²、すなわち自由度 N の分散を返します。

If you somehow know the true population mean μ, you may use this
function to calculate the variance of a sample, giving the known
population mean as the second argument.  Provided the data points are a
random sample of the population, the result will be an unbiased estimate
of the population variance.
@end quotation
@end cartouche
@end deffn

@geindex stdev() (statistics モジュール)
@anchor{library/statistics statistics stdev}@anchor{8e3}
@deffn {の関数} statistics.stdev (data, xbar=None)

標本標準偏差 (標本分散の平方根) を返します。引数や詳細は @ref{8e2,,variance()} を参照してください。

@example
>>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827
@end example
@end deffn

@geindex variance() (statistics モジュール)
@anchor{library/statistics statistics variance}@anchor{8e2}
@deffn {の関数} statistics.variance (data, xbar=None)

`data' の標本分散を返します。`data' は少なくとも2つの実数の iterable です。分散、すなわち2次の中心化モーメントはデータの散らばり具合の測度です。分散が大きいデータはばらつきが大きく、分散が小さいデータは平均値のまわりに固まっています。

If the optional second argument `xbar' is given, it should be the `sample'
mean of `data'.  If it is missing or @code{None} (the default), the mean is
automatically calculated.

データが母集団の標本であるときに用いてください。母集団全体から分散を計算するには @ref{2b86,,pvariance()} を参照してください。

`data' の値が2より少ない場合 @ref{2b89,,StatisticsError} を送出します。

例:

@example
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095
@end example

If you have already calculated the sample mean of your data, you can pass it
as the optional second argument `xbar' to avoid recalculation:

@example
>>> m = mean(data)
>>> variance(data, m)
1.3720238095238095
@end example

この関数は引数として渡した `xbar' が実際の平均値かどうかチェックしません。任意の値を `xbar' に渡すと無効な結果やありえない結果が返ることがあります。

Decimal と Fraction がサポートされています:

@example
>>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')

>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)
@end example

@cartouche
@quotation 注釈 
Bessel 補正済みの標本分散 s²、すなわち自由度 N-1 の分散です。与えられたデータ点が代表的 (たとえば独立で均等に分布) な場合、戻り値は母分散の不偏推定量になります。

何らかの方法で真の母平均 μ を知っている場合、それを  @ref{2b86,,pvariance()}  の引数 `mu' に渡して標本の分散を計算することが出来ます。
@end quotation
@end cartouche
@end deffn

@geindex quantiles() (statistics モジュール)
@anchor{library/statistics statistics quantiles}@anchor{c2c}
@deffn {の関数} statistics.quantiles (data, *, n=4, method='exclusive')

Divide `data' into `n' continuous intervals with equal probability.
Returns a list of @code{n - 1} cut points separating the intervals.

Set `n' to 4 for quartiles (the default).  Set `n' to 10 for deciles.  Set
`n' to 100 for percentiles which gives the 99 cuts points that separate
`data' into 100 equal sized groups.  Raises @ref{2b89,,StatisticsError} if `n'
is not least 1.

The `data' can be any iterable containing sample data.  For meaningful
results, the number of data points in `data' should be larger than `n'.
Raises @ref{2b89,,StatisticsError} if there is not at least one data point.

The cut points are linearly interpolated from the
two nearest data points.  For example, if a cut point falls one-third
of the distance between two sample values, @code{100} and @code{112}, the
cut-point will evaluate to @code{104}.

The `method' for computing quantiles can be varied depending on
whether the `data' includes or excludes the lowest and
highest possible values from the population.

The default `method' is "exclusive" and is used for data sampled from
a population that can have more extreme values than found in the
samples.  The portion of the population falling below the `i-th' of
`m' sorted data points is computed as @code{i / (m + 1)}.  Given nine
sample values, the method sorts them and assigns the following
percentiles: 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%.

Setting the `method' to "inclusive" is used for describing population
data or for samples that are known to include the most extreme values
from the population.  The minimum value in `data' is treated as the 0th
percentile and the maximum value is treated as the 100th percentile.
The portion of the population falling below the `i-th' of `m' sorted
data points is computed as @code{(i - 1) / (m - 1)}.  Given 11 sample
values, the method sorts them and assigns the following percentiles:
0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%.

@example
# Decile cut points for empirically sampled data
>>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
...         100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
...         106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
...         111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
...         103, 107, 101, 81, 109, 104]
>>> [round(q, 1) for q in quantiles(data, n=10)]
[81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]
@end example


Added in version 3.8.



バージョン 3.13 で変更: No longer raises an exception for an input with only a single data point.
This allows quantile estimates to be built up one sample point
at a time becoming gradually more refined with each new data point.

@end deffn

@geindex covariance() (statistics モジュール)
@anchor{library/statistics statistics covariance}@anchor{a31}
@deffn {の関数} statistics.covariance (x, y, /)

Return the sample covariance of two inputs `x' and `y'. Covariance
is a measure of the joint variability of two inputs.

Both inputs must be of the same length (no less than two), otherwise
@ref{2b89,,StatisticsError} is raised.

例:

@example
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> covariance(x, y)
0.75
>>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> covariance(x, z)
-7.5
>>> covariance(z, x)
-7.5
@end example


Added in version 3.10.

@end deffn

@geindex correlation() (statistics モジュール)
@anchor{library/statistics statistics correlation}@anchor{6e3}
@deffn {の関数} statistics.correlation (x, y, /, *, method='linear')

Return the Pearson's correlation coefficient@footnote{https://en.wikipedia.org/wiki/Pearson_correlation_coefficient}
for two inputs. Pearson's correlation coefficient `r' takes values
between -1 and +1. It measures the strength and direction of a linear
relationship.

If `method' is "ranked", computes Spearman's rank correlation coefficient@footnote{https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient}
for two inputs. The data is replaced by ranks.  Ties are averaged so that
equal values receive the same rank.  The resulting coefficient measures the
strength of a monotonic relationship.

Spearman's correlation coefficient is appropriate for ordinal data or for
continuous data that doesn't meet the linear proportion requirement for
Pearson's correlation coefficient.

Both inputs must be of the same length (no less than two), and need
not to be constant, otherwise @ref{2b89,,StatisticsError} is raised.

Example with Kepler's laws of planetary motion@footnote{https://en.wikipedia.org/wiki/Kepler's_laws_of_planetary_motion}:

@example
>>> # Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and  Neptune
>>> orbital_period = [88, 225, 365, 687, 4331, 10_756, 30_687, 60_190]    # days
>>> dist_from_sun = [58, 108, 150, 228, 778, 1_400, 2_900, 4_500] # million km

>>> # Show that a perfect monotonic relationship exists
>>> correlation(orbital_period, dist_from_sun, method='ranked')
1.0

>>> # Observe that a linear relationship is imperfect
>>> round(correlation(orbital_period, dist_from_sun), 4)
0.9882

>>> # Demonstrate Kepler's third law: There is a linear correlation
>>> # between the square of the orbital period and the cube of the
>>> # distance from the sun.
>>> period_squared = [p * p for p in orbital_period]
>>> dist_cubed = [d * d * d for d in dist_from_sun]
>>> round(correlation(period_squared, dist_cubed), 4)
1.0
@end example


Added in version 3.10.



バージョン 3.12 で変更: Added support for Spearman's rank correlation coefficient.

@end deffn

@geindex linear_regression() (statistics モジュール)
@anchor{library/statistics statistics linear_regression}@anchor{a32}
@deffn {の関数} statistics.linear_regression (x, y, /, *, proportional=False)

Return the slope and intercept of simple linear regression@footnote{https://en.wikipedia.org/wiki/Simple_linear_regression}
parameters estimated using ordinary least squares. Simple linear
regression describes the relationship between an independent variable `x' and
a dependent variable `y' in terms of this linear function:

@quotation

`y = slope * x + intercept + noise'
@end quotation

where @code{slope} and @code{intercept} are the regression parameters that are
estimated, and @code{noise} represents the
variability of the data that was not explained by the linear regression
(it is equal to the difference between predicted and actual values
of the dependent variable).

Both inputs must be of the same length (no less than two), and
the independent variable `x' cannot be constant;
otherwise a @ref{2b89,,StatisticsError} is raised.

For example, we can use the release dates of the Monty Python films@footnote{https://en.wikipedia.org/wiki/Monty_Python#Films}
to predict the cumulative number of Monty Python films
that would have been produced by 2019
assuming that they had kept the pace.

@example
>>> year = [1971, 1975, 1979, 1982, 1983]
>>> films_total = [1, 2, 3, 4, 5]
>>> slope, intercept = linear_regression(year, films_total)
>>> round(slope * 2019 + intercept)
16
@end example

If `proportional' is true, the independent variable `x' and the
dependent variable `y' are assumed to be directly proportional.
The data is fit to a line passing through the origin.
Since the `intercept' will always be 0.0, the underlying linear
function simplifies to:

@quotation

`y = slope * x + noise'
@end quotation

Continuing the example from @ref{6e3,,correlation()}, we look to see
how well a model based on major planets can predict the orbital
distances for dwarf planets:

@example
>>> model = linear_regression(period_squared, dist_cubed, proportional=True)
>>> slope = model.slope

>>> # Dwarf planets:   Pluto,  Eris,    Makemake, Haumea, Ceres
>>> orbital_periods = [90_560, 204_199, 111_845, 103_410, 1_680]  # days
>>> predicted_dist = [math.cbrt(slope * (p * p)) for p in orbital_periods]
>>> list(map(round, predicted_dist))
[5912, 10166, 6806, 6459, 414]

>>> [5_906, 10_152, 6_796, 6_450, 414]  # actual distance in million km
[5906, 10152, 6796, 6450, 414]
@end example


Added in version 3.10.



バージョン 3.11 で変更: Added support for `proportional'.

@end deffn

@node 例外<5>,NormalDist オブジェクト,関数の詳細,statistics --- 数学的統計関数
@anchor{library/statistics exceptions}@anchor{2b8a}
@subsubsection 例外


例外が1つ定義されています:

@geindex StatisticsError
@anchor{library/statistics statistics StatisticsError}@anchor{2b89}
@deffn {例外} statistics.StatisticsError

統計関係の例外。@ref{2ec,,ValueError} の派生クラス。
@end deffn

@node NormalDist オブジェクト,例とレシピ<2>,例外<5>,statistics --- 数学的統計関数
@anchor{library/statistics normaldist-objects}@anchor{2b8b}
@subsubsection @code{NormalDist} オブジェクト


@ref{c2d,,NormalDist} is a tool for creating and manipulating normal
distributions of a random variable@footnote{http://www.stat.yale.edu/Courses/1997-98/101/ranvar.htm}.  It is a
class that treats the mean and standard deviation of data
measurements as a single entity.

Normal distributions arise from the Central Limit Theorem@footnote{https://en.wikipedia.org/wiki/Central_limit_theorem} and have a wide range
of applications in statistics.

@geindex NormalDist (statistics のクラス)
@anchor{library/statistics statistics NormalDist}@anchor{c2d}
@deffn {クラス} statistics.NormalDist (mu=0.0, sigma=1.0)

Returns a new `NormalDist' object where `mu' represents the arithmetic mean@footnote{https://en.wikipedia.org/wiki/Arithmetic_mean} and `sigma'
represents the standard deviation@footnote{https://en.wikipedia.org/wiki/Standard_deviation}.

`sigma' が負の数の場合 @ref{2b89,,StatisticsError} を送出します。

@geindex mean (statistics.NormalDist の属性)
@anchor{library/statistics statistics NormalDist mean}@anchor{2b8c}
@deffn {の属性} mean

A read-only property for the arithmetic mean@footnote{https://en.wikipedia.org/wiki/Arithmetic_mean} of a normal
distribution.
@end deffn

@geindex median (statistics.NormalDist の属性)
@anchor{library/statistics statistics NormalDist median}@anchor{2b8d}
@deffn {の属性} median

A read-only property for the median@footnote{https://en.wikipedia.org/wiki/Median} of a normal
distribution.
@end deffn

@geindex mode (statistics.NormalDist の属性)
@anchor{library/statistics statistics NormalDist mode}@anchor{2b8e}
@deffn {の属性} mode

A read-only property for the mode@footnote{https://en.wikipedia.org/wiki/Mode_(statistics)} of a normal
distribution.
@end deffn

@geindex stdev (statistics.NormalDist の属性)
@anchor{library/statistics statistics NormalDist stdev}@anchor{2b8f}
@deffn {の属性} stdev

A read-only property for the standard deviation@footnote{https://en.wikipedia.org/wiki/Standard_deviation} of a normal
distribution.
@end deffn

@geindex variance (statistics.NormalDist の属性)
@anchor{library/statistics statistics NormalDist variance}@anchor{2b90}
@deffn {の属性} variance

A read-only property for the variance@footnote{https://en.wikipedia.org/wiki/Variance} of a normal
distribution. Equal to the square of the standard deviation.
@end deffn

@geindex from_samples() (statistics.NormalDist のクラスメソッド)
@anchor{library/statistics statistics NormalDist from_samples}@anchor{2b91}
@deffn {メソッド} classmethod from_samples (data)

Makes a normal distribution instance with `mu' and `sigma' parameters
estimated from the `data' using @ref{c29,,fmean()} and @ref{8e3,,stdev()}.

The `data' can be any @ref{12f1,,iterable} and should consist of values
that can be converted to type @ref{196,,float}.  If `data' does not
contain at least two elements, raises @ref{2b89,,StatisticsError} because it
takes at least one point to estimate a central value and at least two
points to estimate dispersion.
@end deffn

@geindex samples() (statistics.NormalDist のメソッド)
@anchor{library/statistics statistics NormalDist samples}@anchor{2b92}
@deffn {メソッド} samples (n, *, seed=None)

Generates `n' random samples for a given mean and standard deviation.
Returns a @ref{24d,,list} of @ref{196,,float} values.

If `seed' is given, creates a new instance of the underlying random
number generator.  This is useful for creating reproducible results,
even in a multi-threading context.


バージョン 3.13 で変更.


Switched to a faster algorithm.  To reproduce samples from previous
versions, use @ref{148b,,random.seed()} and @ref{1bd8,,random.gauss()}.
@end deffn

@geindex pdf() (statistics.NormalDist のメソッド)
@anchor{library/statistics statistics NormalDist pdf}@anchor{2b93}
@deffn {メソッド} pdf (x)

Using a probability density function (pdf)@footnote{https://en.wikipedia.org/wiki/Probability_density_function}, compute
the relative likelihood that a random variable `X' will be near the
given value `x'.  Mathematically, it is the limit of the ratio @code{P(x <=
X < x+dx) / dx} as `dx' approaches zero.

The relative likelihood is computed as the probability of a sample
occurring in a narrow range divided by the width of the range (hence
the word "density").  Since the likelihood is relative to other points,
its value can be greater than @code{1.0}.
@end deffn

@geindex cdf() (statistics.NormalDist のメソッド)
@anchor{library/statistics statistics NormalDist cdf}@anchor{1852}
@deffn {メソッド} cdf (x)

Using a cumulative distribution function (cdf)@footnote{https://en.wikipedia.org/wiki/Cumulative_distribution_function},
compute the probability that a random variable `X' will be less than or
equal to `x'.  Mathematically, it is written @code{P(X <= x)}.
@end deffn

@geindex inv_cdf() (statistics.NormalDist のメソッド)
@anchor{library/statistics statistics NormalDist inv_cdf}@anchor{2b94}
@deffn {メソッド} inv_cdf (p)

Compute the inverse cumulative distribution function, also known as the
quantile function@footnote{https://en.wikipedia.org/wiki/Quantile_function}
or the percent-point@footnote{https://web.archive.org/web/20190203145224/https://www.statisticshowto.datasciencecentral.com/inverse-distribution-function/}
function.  Mathematically, it is written @code{x : P(X <= x) = p}.

Finds the value `x' of the random variable `X' such that the
probability of the variable being less than or equal to that value
equals the given probability `p'.
@end deffn

@geindex overlap() (statistics.NormalDist のメソッド)
@anchor{library/statistics statistics NormalDist overlap}@anchor{2b95}
@deffn {メソッド} overlap (other)

Measures the agreement between two normal probability distributions.
Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions@footnote{https://www.rasch.org/rmt/rmt101r.htm}.
@end deffn

@geindex quantiles() (statistics.NormalDist のメソッド)
@anchor{library/statistics statistics NormalDist quantiles}@anchor{2b96}
@deffn {メソッド} quantiles (n=4)

Divide the normal distribution into `n' continuous intervals with
equal probability.  Returns a list of (n - 1) cut points separating
the intervals.

Set `n' to 4 for quartiles (the default).  Set `n' to 10 for deciles.
Set `n' to 100 for percentiles which gives the 99 cuts points that
separate the normal distribution into 100 equal sized groups.
@end deffn

@geindex zscore() (statistics.NormalDist のメソッド)
@anchor{library/statistics statistics NormalDist zscore}@anchor{2b97}
@deffn {メソッド} zscore (x)

Compute the
Standard Score@footnote{https://www.statisticshowto.com/probability-and-statistics/z-score/}
describing `x' in terms of the number of standard deviations
above or below the mean of the normal distribution:
@code{(x - mean) / stdev}.


Added in version 3.9.

@end deffn

Instances of @ref{c2d,,NormalDist} support addition, subtraction,
multiplication and division by a constant.  These operations
are used for translation and scaling.  For example:

@example
>>> temperature_february = NormalDist(5, 2.5)             # Celsius
>>> temperature_february * (9/5) + 32                     # Fahrenheit
NormalDist(mu=41.0, sigma=4.5)
@end example

Dividing a constant by an instance of @ref{c2d,,NormalDist} is not supported
because the result wouldn't be normally distributed.

Since normal distributions arise from additive effects of independent
variables, it is possible to add and subtract two independent normally distributed random variables@footnote{https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables}
represented as instances of @ref{c2d,,NormalDist}.  For example:

@example
>>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])
>>> drug_effects = NormalDist(0.4, 0.15)
>>> combined = birth_weights + drug_effects
>>> round(combined.mean, 1)
3.1
>>> round(combined.stdev, 1)
0.5
@end example


Added in version 3.8.

@end deffn

@node 例とレシピ<2>,,NormalDist オブジェクト,statistics --- 数学的統計関数
@anchor{library/statistics examples-and-recipes}@anchor{2b98}
@subsubsection 例とレシピ


@menu
* Classic probability problems:: 
* Monte Carlo inputs for simulations:: 
* Approximating binomial distributions:: 
* Naive bayesian classifier:: 

@end menu

@node Classic probability problems,Monte Carlo inputs for simulations,,例とレシピ<2>
@anchor{library/statistics classic-probability-problems}@anchor{2b99}
@subsubsection Classic probability problems


@ref{c2d,,NormalDist} readily solves classic probability problems.

For example, given historical data for SAT exams@footnote{https://nces.ed.gov/programs/digest/d17/tables/dt17_226.40.asp} showing
that scores are normally distributed with a mean of 1060 and a standard
deviation of 195, determine the percentage of students with test scores
between 1100 and 1200, after rounding to the nearest whole number:

@example
>>> sat = NormalDist(1060, 195)
>>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)
>>> round(fraction * 100.0, 1)
18.4
@end example

Find the quartiles@footnote{https://en.wikipedia.org/wiki/Quartile} and deciles@footnote{https://en.wikipedia.org/wiki/Decile} for the SAT scores:

@example
>>> list(map(round, sat.quantiles()))
[928, 1060, 1192]
>>> list(map(round, sat.quantiles(n=10)))
[810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]
@end example

@node Monte Carlo inputs for simulations,Approximating binomial distributions,Classic probability problems,例とレシピ<2>
@anchor{library/statistics monte-carlo-inputs-for-simulations}@anchor{2b9a}
@subsubsection Monte Carlo inputs for simulations


To estimate the distribution for a model that isn't easy to solve
analytically, @ref{c2d,,NormalDist} can generate input samples for a Monte Carlo simulation@footnote{https://en.wikipedia.org/wiki/Monte_Carlo_method}:

@example
>>> def model(x, y, z):
...     return (3*x + 7*x*y - 5*y) / (11 * z)
...
>>> n = 100_000
>>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)
>>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)
>>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)
>>> quantiles(map(model, X, Y, Z))
[1.4591308524824727, 1.8035946855390597, 2.175091447274739]
@end example

@node Approximating binomial distributions,Naive bayesian classifier,Monte Carlo inputs for simulations,例とレシピ<2>
@anchor{library/statistics approximating-binomial-distributions}@anchor{2b9b}
@subsubsection Approximating binomial distributions


Normal distributions can be used to approximate Binomial distributions@footnote{https://mathworld.wolfram.com/BinomialDistribution.html}
when the sample size is large and when the probability of a successful
trial is near 50%.

For example, an open source conference has 750 attendees and two rooms with a
500 person capacity.  There is a talk about Python and another about Ruby.
In previous conferences, 65% of the attendees preferred to listen to Python
talks.  Assuming the population preferences haven't changed, what is the
probability that the Python room will stay within its capacity limits?

@example
>>> n = 750             # Sample size
>>> p = 0.65            # Preference for Python
>>> q = 1.0 - p         # Preference for Ruby
>>> k = 500             # Room capacity

>>> # Approximation using the cumulative normal distribution
>>> from math import sqrt
>>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)
0.8402

>>> # Exact 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, binomialvariate
>>> seed(8675309)
>>> mean(binomialvariate(n, p) <= k for i in range(10_000))
0.8406
@end example

@node Naive bayesian classifier,,Approximating binomial distributions,例とレシピ<2>
@anchor{library/statistics naive-bayesian-classifier}@anchor{2b9c}
@subsubsection Naive bayesian classifier


Normal distributions commonly arise in machine learning problems.

Wikipedia has a nice example of a Naive Bayesian Classifier@footnote{https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Person_classification}.
The challenge is to predict a person's gender from measurements of normally
distributed features including height, weight, and foot size.

We're given a training dataset with measurements for eight people.  The
measurements are assumed to be normally distributed, so we summarize the data
with @ref{c2d,,NormalDist}:

@example
>>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])
>>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])
>>> weight_male = NormalDist.from_samples([180, 190, 170, 165])
>>> weight_female = NormalDist.from_samples([100, 150, 130, 150])
>>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])
>>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])
@end example

Next, we encounter a new person whose feature measurements are known but whose
gender is unknown:

@example
>>> ht = 6.0        # height
>>> wt = 130        # weight
>>> fs = 8          # foot size
@end example

Starting with a 50% prior probability@footnote{https://en.wikipedia.org/wiki/Prior_probability} of being male or female,
we compute the posterior as the prior times the product of likelihoods for the
feature measurements given the gender:

@example
>>> prior_male = 0.5
>>> prior_female = 0.5
>>> posterior_male = (prior_male * height_male.pdf(ht) *
...                   weight_male.pdf(wt) * foot_size_male.pdf(fs))

>>> posterior_female = (prior_female * height_female.pdf(ht) *
...                     weight_female.pdf(wt) * foot_size_female.pdf(fs))
@end example

The final prediction goes to the largest posterior. This is known as the
maximum a posteriori@footnote{https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation} or MAP:

@example
>>> 'male' if posterior_male > posterior_female else 'female'
'female'
@end example

@c # This modelines must appear within the last ten lines of the file.
@c kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8;

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 関数型プログラミング用モジュール,ファイルとディレクトリへのアクセス,数値と数学モジュール,Python 標準ライブラリ
@anchor{library/functional doc}@anchor{2b9d}@anchor{library/functional functional-programming-modules}@anchor{2b9e}@anchor{library/functional translation-repo}@anchor{2b9f}
@section 関数型プログラミング用モジュール


この章では、関数型プログラミングスタイルをサポートする呼び出し可能で汎用な操作を実現する関数やクラスについて説明します。

この章では以下のモジュールが記述されています:

@menu
* itertools: itertools --- 効率的なループ用のイテレータ生成関数群. 効率的なループ用のイテレータ生成関数群
* functools: functools --- 高階関数と呼び出し可能オブジェクトの操作. 高階関数と呼び出し可能オブジェクトの操作
* operator: operator --- 関数形式の標準演算子. 関数形式の標準演算子

@end menu

@node itertools --- 効率的なループ用のイテレータ生成関数群,functools --- 高階関数と呼び出し可能オブジェクトの操作,,関数型プログラミング用モジュール
@anchor{library/itertools doc}@anchor{2ba0}@anchor{library/itertools itertools-functions-creating-iterators-for-efficient-looping}@anchor{2ba1}@anchor{library/itertools module-itertools}@anchor{85}
@subsection @code{itertools} --- 効率的なループ用のイテレータ生成関数群


@geindex module; itertools

@c from itertools import *
@c import collections
@c import math
@c import operator
@c import random


__________________________________________________________________


このモジュールは @ref{4c8,,イテレータ} を構築する部品を実装しています。プログラム言語 APL, Haskell, SML からアイデアを得ていますが、 Python に適した形に修正されています。

このモジュールは、高速でメモリ効率に優れ、単独でも組合せても使用することのできるツールを標準化したものです。同時に、このツール群は "イテレータの代数" を構成していて、pure Python で簡潔かつ効率的なツールを作れるようにしています。

例えば、SML の作表ツール @code{tabulate(f)} は @code{f(0), f(1), ...} のシーケンスを作成します。同じことを Python では @ref{19f,,map()} と @ref{149b,,count()} を組合せて @code{map(f, count())} という形で実現できます。

`無限イテレータ:'


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

イテレータ

@tab

引数

@tab

結果

@tab

使用例

@item

@ref{149b,,count()}

@tab

[start[, step]]

@tab

start, start+step, start+2*step, ...

@tab

@code{count(10) → 10 11 12 13 14 ...}

@item

@ref{2ba2,,cycle()}

@tab

p

@tab

p0, p1, ... plast, p0, p1, ...

@tab

@code{cycle('ABCD') → A B C D A B C D ...}

@item

@ref{1859,,repeat()}

@tab

elem [,n]

@tab

elem, elem, elem, ... 無限もしくは n 回

@tab

@code{repeat(10, 3) → 10 10 10}

@end multitable


`一番短い入力シーケンスで止まるイテレータ:'


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

イテレータ

@tab

引数

@tab

結果

@tab

使用例

@item

@ref{bf0,,accumulate()}

@tab

p [,func]

@tab

p0, p0+p1, p0+p1+p2, ...

@tab

@code{accumulate([1,2,3,4,5]) → 1 3 6 10 15}

@item

@ref{511,,batched()}

@tab

p, n

@tab

(p0, p1, ..., p_n-1), ...

@tab

@code{batched('ABCDEFG', n=3) → ABC DEF G}

@item

@ref{25de,,chain()}

@tab

p, q, ...

@tab

p0, p1, ... plast, q0, q1, ...

@tab

@code{chain('ABC', 'DEF') → A B C D E F}

@item

@ref{2ba3,,chain.from_iterable()}

@tab

iterable

@tab

p0, p1, ... plast, q0, q1, ...

@tab

@code{chain.from_iterable(['ABC', 'DEF']) → A B C D E F}

@item

@ref{149a,,compress()}

@tab

data, selectors

@tab

(d[0] if s[0]), (d[1] if s[1]), ...

@tab

@code{compress('ABCDEF', [1,0,1,0,1,1]) → A C E F}

@item

@ref{2ba4,,dropwhile()}

@tab

predicate, seq

@tab

seq[n], seq[n+1], starting when predicate fails

@tab

@code{dropwhile(lambda x: x<5, [1,4,6,3,8]) → 6 3 8}

@item

@ref{25ce,,filterfalse()}

@tab

predicate, seq

@tab

elements of seq where predicate(elem) fails

@tab

@code{filterfalse(lambda x: x<5, [1,4,6,3,8]) → 6 8}

@item

@ref{2ba5,,groupby()}

@tab

iterable[, key]

@tab

key(v) の値でグループ化したサブイテレータ

@tab

@code{groupby(['A','B','DEF'], len) → (1, A B) (3, DEF)}

@item

@ref{d43,,islice()}

@tab

seq, [start,] stop [, step]

@tab

seq[start:stop:step]

@tab

@code{islice('ABCDEFG', 2, None) → C D E F G}

@item

@ref{a16,,pairwise()}

@tab

iterable

@tab

(p[0], p[1]), (p[1], p[2])

@tab

@code{pairwise('ABCDEFG') → AB BC CD DE EF FG}

@item

@ref{12fa,,starmap()}

@tab

func, seq

@tab

func(*seq[0]), func(*seq[1]), ...

@tab

@code{starmap(pow, [(2,5), (3,2), (10,3)]) → 32 9 1000}

@item

@ref{2ba6,,takewhile()}

@tab

predicate, seq

@tab

seq[0], seq[1], until predicate fails

@tab

@code{takewhile(lambda x: x<5, [1,4,6,3,8]) → 1 4}

@item

@ref{2ba7,,tee()}

@tab

it, n

@tab

it1, it2 , ... itn 一つのイテレータを n 個に分ける

@tab

@code{tee('ABC', 2) → A B C, A B C}

@item

@ref{14b6,,zip_longest()}

@tab

p, q, ...

@tab

(p[0], q[0]), (p[1], q[1]), ...

@tab

@code{zip_longest('ABCD', 'xy', fillvalue='-') → Ax By C- D-}

@end multitable


`組合せイテレータ:'


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

イテレータ

@tab

引数

@tab

結果

@item

@ref{152a,,product()}

@tab

p, q, ... [repeat=1]

@tab

デカルト積、ネストしたforループと等価

@item

@ref{1cdd,,permutations()}

@tab

p[, r]

@tab

長さrのタプル列、重複なしのあらゆる並び

@item

@ref{1529,,combinations()}

@tab

p, r

@tab

長さrのタプル列、ソートされた順で重複なし

@item

@ref{1499,,combinations_with_replacement()}

@tab

p, r

@tab

長さrのタプル列、ソートされた順で重複あり

@end multitable



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

使用例

@tab

結果

@item

@code{product('ABCD', repeat=2)}

@tab

@code{AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD}

@item

@code{permutations('ABCD', 2)}

@tab

@code{AB AC AD BA BC BD CA CB CD DA DB DC}

@item

@code{combinations('ABCD', 2)}

@tab

@code{AB AC AD BC BD CD}

@item

@code{combinations_with_replacement('ABCD', 2)}

@tab

@code{AA AB AC AD BB BC BD CC CD DD}

@end multitable


@menu
* Itertool関数:: 
* Itertools レシピ:: 

@end menu

@node Itertool関数,Itertools レシピ,,itertools --- 効率的なループ用のイテレータ生成関数群
@anchor{library/itertools itertool-functions}@anchor{2ba8}@anchor{library/itertools itertools-functions}@anchor{2ba9}
@subsubsection Itertool関数


The following functions all construct and return iterators. Some provide
streams of infinite length, so they should only be accessed by functions or
loops that truncate the stream.

@geindex accumulate() (itertools モジュール)
@anchor{library/itertools itertools accumulate}@anchor{bf0}
@deffn {の関数} itertools.accumulate (iterable[, function, *, initial=None])

Make an iterator that returns accumulated sums or accumulated
results from other binary functions.

The `function' defaults to addition.  The `function' should accept
two arguments, an accumulated total and a value from the `iterable'.

If an `initial' value is provided, the accumulation will start with
that value and the output will have one more element than the input
iterable.

およそ次と等価です:

@example
def accumulate(iterable, function=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

    iterator = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(iterator)
        except StopIteration:
            return

    yield total
    for element in iterator:
        total = function(total, element)
        yield total
@end example

To compute a running minimum, set `function' to @ref{110b,,min()}.
For a running maximum, set `function' to @ref{110c,,max()}.
Or for a running product, set `function' to @ref{2baa,,operator.mul()}.
To build an amortization table@footnote{https://www.ramseysolutions.com/real-estate/amortization-schedule},
accumulate the interest and apply payments:

@example
>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]

# Amortize a 5% loan of 1000 with 10 annual payments of 90
>>> update = lambda balance, payment: round(balance * 1.05) - payment
>>> list(accumulate(repeat(90, 10), update, initial=1_000))
[1000, 960, 918, 874, 828, 779, 728, 674, 618, 559, 497]
@end example

最終的な累積値だけを返す類似の関数については @ref{21a,,functools.reduce()} を見てください。


Added in version 3.2.



バージョン 3.3 で変更: Added the optional `function' parameter.



バージョン 3.8 で変更: オプションの `initial' パラメータが追加されました。

@end deffn

@geindex batched() (itertools モジュール)
@anchor{library/itertools itertools batched}@anchor{511}
@deffn {の関数} itertools.batched (iterable, n, *, strict=False)

`iterable' から得られるデータを `n' 個ごとに一つのタプルにまとめます。
一番最後のバッチは `n' 個より少なくなる可能性があります。

If `strict' is true, will raise a @ref{2ec,,ValueError} if the final
batch is shorter than `n'.

入力の iterable から要素を一つづつ取り出し、サイズが `n' になるまでタプルに溜め込みます。
入力の iterable は遅延評価され、次のタプルを作るのに必要なだけ要素が取り出されます。
タプルは、個数が `n' に到達するか、入力の iterable が尽きるとすぐに出力されます:

@example
>>> flattened_data = ['roses', 'red', 'violets', 'blue', 'sugar', 'sweet']
>>> unflattened = list(batched(flattened_data, 2))
>>> unflattened
[('roses', 'red'), ('violets', 'blue'), ('sugar', 'sweet')]
@end example

およそ次と等価です:

@example
def batched(iterable, n, *, strict=False):
    # batched('ABCDEFG', 3) → ABC DEF G
    if n < 1:
        raise ValueError('n must be at least one')
    iterator = iter(iterable)
    while batch := tuple(islice(iterator, n)):
        if strict and len(batch) != n:
            raise ValueError('batched(): incomplete batch')
        yield batch
@end example


Added in version 3.12.



バージョン 3.13 で変更: Added the `strict' option.

@end deffn

@geindex chain() (itertools モジュール)
@anchor{library/itertools itertools chain}@anchor{25de}
@deffn {の関数} itertools.chain (*iterables)

Make an iterator that returns elements from the first iterable until
it is exhausted, then proceeds to the next iterable, until all of the
iterables are exhausted.  This combines multiple data sources into a
single iterator.  Roughly equivalent to:

@example
def chain(*iterables):
    # chain('ABC', 'DEF') → A B C D E F
    for iterable in iterables:
        yield from iterable
@end example
@end deffn

@geindex from_iterable() (itertools.chain のクラスメソッド)
@anchor{library/itertools itertools chain from_iterable}@anchor{2ba3}
@deffn {メソッド} classmethod chain.from_iterable (iterable)

@ref{25de,,chain()} のためのもう一つのコンストラクタです。遅延評価される iterable 引数一つから連鎖した入力を受け取ります。この関数は、以下のコードとほぼ等価です:

@example
def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) → A B C D E F
    for iterable in iterables:
        yield from iterable
@end example
@end deffn

@geindex combinations() (itertools モジュール)
@anchor{library/itertools itertools combinations}@anchor{1529}
@deffn {の関数} itertools.combinations (iterable, r)

入力 `iterable' の要素からなる長さ `r' の部分列を返します。

The output is a subsequence of @ref{152a,,product()} keeping only entries that
are subsequences of the `iterable'.  The length of the output is given
by @ref{8df,,math.comb()} which computes @code{n! / r! / (n - r)!} when @code{0 ≤ r
≤ n} or zero when @code{r > n}.

The combination tuples are emitted in lexicographic order according to
the order of the input `iterable'. If the input `iterable' is sorted,
the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their
value.  If the input elements are unique, there will be no repeated
values within each combination.

およそ次と等価です:

@example
def combinations(iterable, r):
    # combinations('ABCD', 2) → AB AC AD BC BD CD
    # combinations(range(4), 3) → 012 013 023 123

    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))

    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
@end example
@end deffn

@geindex combinations_with_replacement() (itertools モジュール)
@anchor{library/itertools itertools combinations_with_replacement}@anchor{1499}
@deffn {の関数} itertools.combinations_with_replacement (iterable, r)

入力 `iterable' から、それぞれの要素が複数回現れることを許して、長さ `r' の要素の部分列を返します。

The output is a subsequence of @ref{152a,,product()} that keeps only entries
that are subsequences (with possible repeated elements) of the
`iterable'.  The number of subsequence returned is @code{(n + r - 1)! / r! /
(n - 1)!} when @code{n > 0}.

The combination tuples are emitted in lexicographic order according to
the order of the input `iterable'. if the input `iterable' is sorted,
the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their
value.  If the input elements are unique, the generated combinations
will also be unique.

およそ次と等価です:

@example
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) → AA AB AC BB BC CC

    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r

    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
@end example


Added in version 3.1.

@end deffn

@geindex compress() (itertools モジュール)
@anchor{library/itertools itertools compress}@anchor{149a}
@deffn {の関数} itertools.compress (data, selectors)

Make an iterator that returns elements from `data' where the
corresponding element in `selectors' is true.  Stops when either the
`data' or `selectors' iterables have been exhausted.  Roughly
equivalent to:

@example
def compress(data, selectors):
    # compress('ABCDEF', [1,0,1,0,1,1]) → A C E F
    return (datum for datum, selector in zip(data, selectors) if selector)
@end example


Added in version 3.1.

@end deffn

@geindex count() (itertools モジュール)
@anchor{library/itertools itertools count}@anchor{149b}
@deffn {の関数} itertools.count (start=0, step=1)

Make an iterator that returns evenly spaced values beginning with
`start'. Can be used with @ref{19f,,map()} to generate consecutive data
points or with @ref{1a0,,zip()} to add sequence numbers.  Roughly
equivalent to:

@example
def count(start=0, step=1):
    # count(10) → 10 11 12 13 14 ...
    # count(2.5, 0.5) → 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step
@end example

When counting with floating-point numbers, better accuracy can sometimes be
achieved by substituting multiplicative code such as: @code{(start + step * i
for i in count())}.


バージョン 3.1 で変更: `step' 引数が追加され、非整数の引数が許されるようになりました。

@end deffn

@geindex cycle() (itertools モジュール)
@anchor{library/itertools itertools cycle}@anchor{2ba2}
@deffn {の関数} itertools.cycle (iterable)

Make an iterator returning elements from the `iterable' and saving a
copy of each.  When the iterable is exhausted, return elements from
the saved copy.  Repeats indefinitely.  Roughly equivalent to:

@example
def cycle(iterable):
    # cycle('ABCD') → A B C D A B C D A B C D ...

    saved = []
    for element in iterable:
        yield element
        saved.append(element)

    while saved:
        for element in saved:
            yield element
@end example

This itertool may require significant auxiliary storage (depending on
the length of the iterable).
@end deffn

@geindex dropwhile() (itertools モジュール)
@anchor{library/itertools itertools dropwhile}@anchor{2ba4}
@deffn {の関数} itertools.dropwhile (predicate, iterable)

Make an iterator that drops elements from the `iterable' while the
`predicate' is true and afterwards returns every element.  Roughly
equivalent to:

@example
def dropwhile(predicate, iterable):
    # dropwhile(lambda x: x<5, [1,4,6,3,8]) → 6 3 8

    iterator = iter(iterable)
    for x in iterator:
        if not predicate(x):
            yield x
            break

    for x in iterator:
        yield x
@end example

Note this does not produce `any' output until the predicate first
becomes false, so this itertool may have a lengthy start-up time.
@end deffn

@geindex filterfalse() (itertools モジュール)
@anchor{library/itertools itertools filterfalse}@anchor{25ce}
@deffn {の関数} itertools.filterfalse (predicate, iterable)

Make an iterator that filters elements from the `iterable' returning
only those for which the `predicate' returns a false value.  If
`predicate' is @code{None}, returns the items that are false.  Roughly
equivalent to:

@example
def filterfalse(predicate, iterable):
    # filterfalse(lambda x: x<5, [1,4,6,3,8]) → 6 8

    if predicate is None:
        predicate = bool

    for x in iterable:
        if not predicate(x):
            yield x
@end example
@end deffn

@geindex groupby() (itertools モジュール)
@anchor{library/itertools itertools groupby}@anchor{2ba5}
@deffn {の関数} itertools.groupby (iterable, key=None)

同じキーをもつような要素からなる `iterable' 中のグループに対して、キーとグループを返すようなイテレータを作成します。`key' は各要素に対するキー値を計算する関数です。キーを指定しない場合や @code{None} にした場合、`key' 関数のデフォルトは恒等関数になり要素をそのまま返します。通常、`iterable' は同じキー関数でソート済みである必要があります。

@ref{2ba5,,groupby()} の操作は Unix の @code{uniq} フィルターと似ています。 key 関数の値が変わるたびに休止または新しいグループを生成します (このために通常同じ key 関数でソートしておく必要があるのです)。この動作は SQL の入力順に関係なく共通の要素を集約する GROUP BY とは違います。

返されるグループはそれ自体がイテレータで、 @ref{2ba5,,groupby()} と `iterable' を共有しています。もととなる `iterable' を共有しているため、 @ref{2ba5,,groupby()} オブジェクトの要素取り出しを先に進めると、それ以前の要素であるグループは見えなくなってしまいます。従って、データが後で必要な場合にはリストの形で保存しておく必要があります:

@example
groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)
@end example

@ref{2ba5,,groupby()} はおよそ次と等価です:

@example
def groupby(iterable, key=None):
    # [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

    keyfunc = (lambda x: x) if key is None else key
    iterator = iter(iterable)
    exhausted = False

    def _grouper(target_key):
        nonlocal curr_value, curr_key, exhausted
        yield curr_value
        for curr_value in iterator:
            curr_key = keyfunc(curr_value)
            if curr_key != target_key:
                return
            yield curr_value
        exhausted = True

    try:
        curr_value = next(iterator)
    except StopIteration:
        return
    curr_key = keyfunc(curr_value)

    while not exhausted:
        target_key = curr_key
        curr_group = _grouper(target_key)
        yield curr_key, curr_group
        if curr_key == target_key:
            for _ in curr_group:
                pass
@end example
@end deffn

@geindex islice() (itertools モジュール)
@anchor{library/itertools itertools islice}@anchor{d43}
@deffn {の関数} itertools.islice (iterable, stop)

@deffnx {の関数} itertools.islice (iterable, start, stop[, step])

Make an iterator that returns selected elements from the iterable.
Works like sequence slicing but does not support negative values for
`start', `stop', or `step'.

If `start' is zero or @code{None}, iteration starts at zero.  Otherwise,
elements from the iterable are skipped until `start' is reached.

If `stop' is @code{None}, iteration continues until the input is
exhausted, if at all.  Otherwise, it stops at the specified position.

If `step' is @code{None}, the step defaults to one.  Elements are returned
consecutively unless `step' is set higher than one which results in
items being skipped.

およそ次と等価です:

@example
def islice(iterable, *args):
    # islice('ABCDEFG', 2) → A B
    # islice('ABCDEFG', 2, 4) → C D
    # islice('ABCDEFG', 2, None) → C D E F G
    # islice('ABCDEFG', 0, None, 2) → A C E G

    s = slice(*args)
    start = 0 if s.start is None else s.start
    stop = s.stop
    step = 1 if s.step is None else s.step
    if start < 0 or (stop is not None and stop < 0) or step <= 0:
        raise ValueError

    indices = count() if stop is None else range(max(start, stop))
    next_i = start
    for i, element in zip(indices, iterable):
        if i == next_i:
            yield element
            next_i += step
@end example

If the input is an iterator, then fully consuming the `islice'
advances the input iterator by @code{max(start, stop)} steps regardless
of the `step' value.
@end deffn

@geindex pairwise() (itertools モジュール)
@anchor{library/itertools itertools pairwise}@anchor{a16}
@deffn {の関数} itertools.pairwise (iterable)

Return successive overlapping pairs taken from the input `iterable'.

The number of 2-tuples in the output iterator will be one fewer than the
number of inputs.  It will be empty if the input iterable has fewer than
two values.

およそ次と等価です:

@example
def pairwise(iterable):
    # pairwise('ABCDEFG') → AB BC CD DE EF FG

    iterator = iter(iterable)
    a = next(iterator, None)

    for b in iterator:
        yield a, b
        a = b
@end example


Added in version 3.10.

@end deffn

@geindex permutations() (itertools モジュール)
@anchor{library/itertools itertools permutations}@anchor{1cdd}
@deffn {の関数} itertools.permutations (iterable, r=None)

Return successive `r' length permutations of elements@footnote{https://www.britannica.com/science/permutation} from the `iterable'.

`r' が指定されない場合や @code{None} の場合、`r' はデフォルトで `iterable' の長さとなり、可能な最長の順列の全てが生成されます。

The output is a subsequence of @ref{152a,,product()} where entries with
repeated elements have been filtered out.  The length of the output is
given by @ref{8e0,,math.perm()} which computes @code{n! / (n - r)!} when
@code{0 ≤ r ≤ n} or zero when @code{r > n}.

The permutation tuples are emitted in lexicographic order according to
the order of the input `iterable'.  If the input `iterable' is sorted,
the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their
value.  If the input elements are unique, there will be no repeated
values within a permutation.

およそ次と等価です:

@example
def permutations(iterable, r=None):
    # permutations('ABCD', 2) → AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) → 012 021 102 120 201 210

    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return

    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])

    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return
@end example
@end deffn

@geindex product() (itertools モジュール)
@anchor{library/itertools itertools product}@anchor{152a}
@deffn {の関数} itertools.product (*iterables, repeat=1)

Cartesian product@footnote{https://en.wikipedia.org/wiki/Cartesian_product}
of the input iterables.

ジェネレータ式の入れ子になった for ループとおよそ等価です。たとえば @code{product(A, B)} は @code{((x,y) for x in A for y in B)} と同じものを返します。

入れ子ループは走行距離計と同じように右端の要素がイテレーションごとに更新されていきます。このパターンは辞書式順序を作り出し、入力のイテレート可能オブジェクトたちがソートされていれば、直積タプルもソートされた順に出てきます。

イテラブル自身との直積を計算するためには、オプションの `repeat' キーワード引数に繰り返し回数を指定します。たとえば @code{product(A, repeat=4)} は  @code{product(A, A, A, A)} と同じ意味です。

この関数は以下のコードとおよそ等価ですが、実際の実装ではメモリ中に中間結果を作りません:

@example
def product(*iterables, 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

    if repeat < 0:
        raise ValueError('repeat argument cannot be negative')
    pools = [tuple(pool) for pool in iterables] * repeat

    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]

    for prod in result:
        yield tuple(prod)
@end example

@ref{152a,,product()} は動作する前に、入力のイテラブルを完全に読み取り、直積を生成するためにメモリ内に値を蓄えます。したがって、入力が有限の場合に限り有用です。
@end deffn

@geindex repeat() (itertools モジュール)
@anchor{library/itertools itertools repeat}@anchor{1859}
@deffn {の関数} itertools.repeat (object[, times])

Make an iterator that returns `object' over and over again. Runs indefinitely
unless the `times' argument is specified.

およそ次と等価です:

@example
def repeat(object, times=None):
    # repeat(10, 3) → 10 10 10
    if times is None:
        while True:
            yield object
    else:
        for i in range(times):
            yield object
@end example

`repeat' は `map' や `zip' に定数のストリームを与えるためによく利用されます:

@example
>>> list(map(pow, range(10), repeat(2)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
@end example
@end deffn

@geindex starmap() (itertools モジュール)
@anchor{library/itertools itertools starmap}@anchor{12fa}
@deffn {の関数} itertools.starmap (function, iterable)

Make an iterator that computes the `function' using arguments obtained
from the `iterable'.  Used instead of @ref{19f,,map()} when argument
parameters have already been "pre-zipped" into tuples.

The difference between @ref{19f,,map()} and @ref{12fa,,starmap()} parallels the
distinction between @code{function(a,b)} and @code{function(*c)}. Roughly
equivalent to:

@example
def starmap(function, iterable):
    # starmap(pow, [(2,5), (3,2), (10,3)]) → 32 9 1000
    for args in iterable:
        yield function(*args)
@end example
@end deffn

@geindex takewhile() (itertools モジュール)
@anchor{library/itertools itertools takewhile}@anchor{2ba6}
@deffn {の関数} itertools.takewhile (predicate, iterable)

Make an iterator that returns elements from the `iterable' as long as
the `predicate' is true.  Roughly equivalent to:

@example
def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,3,8]) → 1 4
    for x in iterable:
        if not predicate(x):
            break
        yield x
@end example

Note, the element that first fails the predicate condition is
consumed from the input iterator and there is no way to access it.
This could be an issue if an application wants to further consume the
input iterator after `takewhile' has been run to exhaustion.  To work
around this problem, consider using more-itertools before_and_after()@footnote{https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.before_and_after}
instead.
@end deffn

@geindex tee() (itertools モジュール)
@anchor{library/itertools itertools tee}@anchor{2ba7}
@deffn {の関数} itertools.tee (iterable, n=2)

一つの iterable から `n' 個の独立したイテレータを返します。

およそ次と等価です:

@example
def tee(iterable, n=2):
    if n < 0:
        raise ValueError
    if n == 0:
        return ()
    iterator = _tee(iterable)
    result = [iterator]
    for _ in range(n - 1):
        result.append(_tee(iterator))
    return tuple(result)

class _tee:

    def __init__(self, iterable):
        it = iter(iterable)
        if isinstance(it, _tee):
            self.iterator = it.iterator
            self.link = it.link
        else:
            self.iterator = it
            self.link = [None, None]

    def __iter__(self):
        return self

    def __next__(self):
        link = self.link
        if link[1] is None:
            link[0] = next(self.iterator)
            link[1] = [None, None]
        value, self.link = link
        return value
@end example

When the input `iterable' is already a tee iterator object, all
members of the return tuple are constructed as if they had been
produced by the upstream @ref{2ba7,,tee()} call.  This "flattening step"
allows nested @ref{2ba7,,tee()} calls to share the same underlying data
chain and to have a single update step rather than a chain of calls.

The flattening property makes tee iterators efficiently peekable:

@example
def lookahead(tee_iterator):
     "Return the next value without moving the input forward"
     [forked_iterator] = tee(tee_iterator, 1)
     return next(forked_iterator)
@end example

@example
>>> iterator = iter('abcdef')
>>> [iterator] = tee(iterator, 1)   # Make the input peekable
>>> next(iterator)                  # Move the iterator forward
'a'
>>> lookahead(iterator)             # Check next value
'b'
>>> next(iterator)                  # Continue moving forward
'b'
@end example

@code{tee} iterators are not threadsafe. A @ref{244,,RuntimeError} may be
raised when simultaneously using iterators returned by the same @ref{2ba7,,tee()}
call, even if the original `iterable' is threadsafe.

@ref{2ba7,,tee()} はかなり大きなメモリ領域を使用するかもしれません (使用するメモリ量はiterableの大きさに依存します)。一般には、一つのイテレータが他のイテレータよりも先にほとんどまたは全ての要素を消費するような場合には、 @ref{2ba7,,tee()} よりも @ref{24d,,list()} を使った方が高速です。
@end deffn

@geindex zip_longest() (itertools モジュール)
@anchor{library/itertools itertools zip_longest}@anchor{14b6}
@deffn {の関数} itertools.zip_longest (*iterables, fillvalue=None)

Make an iterator that aggregates elements from each of the
`iterables'.

If the iterables are of uneven length, missing values are filled-in
with `fillvalue'.  If not specified, `fillvalue' defaults to @code{None}.

Iteration continues until the longest iterable is exhausted.

およそ次と等価です:

@example
def zip_longest(*iterables, fillvalue=None):
    # zip_longest('ABCD', 'xy', fillvalue='-') → Ax By C- D-

    iterators = list(map(iter, iterables))
    num_active = len(iterators)
    if not num_active:
        return

    while True:
        values = []
        for i, iterator in enumerate(iterators):
            try:
                value = next(iterator)
            except StopIteration:
                num_active -= 1
                if not num_active:
                    return
                iterators[i] = repeat(fillvalue)
                value = fillvalue
            values.append(value)
        yield tuple(values)
@end example

If one of the iterables is potentially infinite, then the @ref{14b6,,zip_longest()}
function should be wrapped with something that limits the number of calls
(for example @ref{d43,,islice()} or @ref{2ba6,,takewhile()}).
@end deffn

@node Itertools レシピ,,Itertool関数,itertools --- 効率的なループ用のイテレータ生成関数群
@anchor{library/itertools id1}@anchor{2bab}@anchor{library/itertools itertools-recipes}@anchor{1476}
@subsubsection Itertools レシピ


この節では、既存の itertools を素材としてツールセットを拡張するためのレシピを示します。

The primary purpose of the itertools recipes is educational.  The recipes show
various ways of thinking about individual tools — for example, that
@code{chain.from_iterable} is related to the concept of flattening.  The recipes
also give ideas about ways that the tools can be combined — for example, how
@code{starmap()} and @code{repeat()} can work together.  The recipes also show patterns
for using itertools with the @ref{a3,,operator} and @ref{1e,,collections} modules as
well as with the built-in itertools such as @code{map()}, @code{filter()},
@code{reversed()}, and @code{enumerate()}.

A secondary purpose of the recipes is to serve as an incubator.  The
@code{accumulate()}, @code{compress()}, and @code{pairwise()} itertools started out as
recipes.  Currently, the @code{sliding_window()}, @code{derangements()}, and @code{sieve()}
recipes are being tested to see whether they prove their worth.

Substantially all of these recipes and many, many others can be installed from
the more-itertools@footnote{https://pypi.org/project/more-itertools/} project found
on the Python Package Index:

@example
python -m pip install more-itertools
@end example

Many of the recipes offer the same high performance as the underlying toolset.
Superior memory performance is kept by processing elements one at a time rather
than bringing the whole iterable into memory all at once. Code volume is kept
small by linking the tools together in a functional style@footnote{https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf}.  High speed
is retained by preferring "vectorized" building blocks over the use of for-loops
and @ref{126c,,generators} which incur interpreter overhead.

@example
from itertools import (accumulate, batched, chain, combinations, compress,
     count, cycle, filterfalse, groupby, islice, permutations, product,
     repeat, starmap, tee, zip_longest)
from collections import Counter, deque
from contextlib import suppress
from functools import reduce
from math import comb, isqrt, prod, sumprod
from operator import getitem, is_not, itemgetter, mul, neg, truediv


# ==== Basic one liners ====

def take(n, iterable):
    "Return first n items of the iterable as a list."
    return list(islice(iterable, n))

def prepend(value, iterable):
    "Prepend a single value in front of an iterable."
    # prepend(1, [2, 3, 4]) → 1 2 3 4
    return chain([value], iterable)

def running_mean(iterable):
    "Yield the average of all values seen so far."
    # running_mean([8.5, 9.5, 7.5, 6.5]) -> 8.5 9.0 8.5 8.0
    return map(truediv, accumulate(iterable), count(1))

def repeatfunc(function, times=None, *args):
    "Repeat calls to a function with specified arguments."
    if times is None:
        return starmap(function, repeat(args))
    return starmap(function, repeat(args, times))

def flatten(list_of_lists):
    "Flatten one level of nesting."
    return chain.from_iterable(list_of_lists)

def ncycles(iterable, n):
    "Returns the sequence elements n times."
    return chain.from_iterable(repeat(tuple(iterable), n))

def loops(n):
    "Loop n times. Like range(n) but without creating integers."
    # for _ in loops(100): ...
    return repeat(None, n)

def tail(n, iterable):
    "Return an iterator over the last n items."
    # tail(3, 'ABCDEFG') → E F G
    return iter(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:
        deque(iterator, maxlen=0)
    else:
        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 quantify(iterable, predicate=bool):
    "Given a predicate that returns True or False, count the True results."
    return sum(map(predicate, iterable))

def first_true(iterable, default=False, predicate=None):
    "Returns the first true value or the *default* if there is no true value."
    # 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(predicate, iterable), default)

def all_equal(iterable, key=None):
    "Returns True if all the elements are equal to each other."
    # all_equal('4٤௪౪໔', key=int) → True
    return len(take(2, groupby(iterable, key))) <= 1


# ==== Data pipelines ====

def unique_justseen(iterable, key=None):
    "Yield unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') → A B C D A B
    # unique_justseen('ABBcCAD', str.casefold) → A B c A D
    if key is None:
        return map(itemgetter(0), groupby(iterable))
    return map(next, map(itemgetter(1), groupby(iterable, key)))

def unique_everseen(iterable, key=None):
    "Yield unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') → A B C D
    # unique_everseen('ABBcCAD', str.casefold) → A B c D
    seen = set()
    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(iterable, key=None, reverse=False):
   "Yield unique elements in sorted order. Supports unhashable inputs."
   # unique([[1, 2], [3, 4], [1, 2]]) → [1, 2] [3, 4]
   sequenced = sorted(iterable, key=key, reverse=reverse)
   return unique_justseen(sequenced, key=key)

def sliding_window(iterable, n):
    "Collect data into overlapping fixed-length chunks or blocks."
    # sliding_window('ABCDEFG', 3) → ABC BCD CDE DEF EFG
    iterator = iter(iterable)
    window = deque(islice(iterator, n - 1), maxlen=n)
    for x in iterator:
        window.append(x)
        yield tuple(window)

def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
    "Collect data into non-overlapping fixed-length chunks or blocks."
    # grouper('ABCDEFG', 3, fillvalue='x')       → ABC DEF Gxx
    # grouper('ABCDEFG', 3, incomplete='strict') → ABC DEF ValueError
    # grouper('ABCDEFG', 3, incomplete='ignore') → ABC DEF
    iterators = [iter(iterable)] * n
    match incomplete:
        case 'fill':
            return zip_longest(*iterators, fillvalue=fillvalue)
        case 'strict':
            return zip(*iterators, strict=True)
        case 'ignore':
            return zip(*iterators)
        case _:
            raise ValueError('Expected fill, strict, or ignore')

def roundrobin(*iterables):
    "Visit input iterables in a cycle until each is exhausted."
    # roundrobin('ABC', 'D', 'EF') → A D E B F C
    # Algorithm credited to George Sakkis
    iterators = map(iter, iterables)
    for num_active in range(len(iterables), 0, -1):
        iterators = cycle(islice(iterators, num_active))
        yield from map(next, iterators)

def subslices(seq):
    "Return all contiguous non-empty subslices of a sequence."
    # subslices('ABCD') → A AB ABC ABCD B BC BCD C CD D
    slices = starmap(slice, combinations(range(len(seq) + 1), 2))
    return map(getitem, repeat(seq), slices)

def derangements(iterable, r=None):
    "Produce r length permutations without fixed points."
    # derangements('ABCD') → BADC BCDA BDAC CADB CDAB CDBA DABC DCAB DCBA
    # Algorithm credited to Stefan Pochmann
    seq = tuple(iterable)
    pos = tuple(range(len(seq)))
    have_moved = map(map, repeat(is_not), repeat(pos), permutations(pos, r=r))
    valid_derangements = map(all, have_moved)
    return compress(permutations(seq, r=r), valid_derangements)

def iter_index(iterable, value, start=0, stop=None):
    "Return indices where a value occurs in a sequence or iterable."
    # iter_index('AABCADEAF', 'A') → 0 1 4 7
    seq_index = getattr(iterable, 'index', None)
    if seq_index is None:
        iterator = islice(iterable, start, stop)
        for i, element in enumerate(iterator, start):
            if element is value or element == value:
                yield i
    else:
        stop = len(iterable) if stop is None else stop
        i = start
        with suppress(ValueError):
            while True:
                yield (i := seq_index(value, i, stop))
                i += 1

def iter_except(function, exception, first=None):
    "Convert a call-until-exception interface to an iterator interface."
    # iter_except(d.popitem, KeyError) → non-blocking dictionary iterator
    with suppress(exception):
        if first is not None:
            yield first()
        while True:
            yield function()


# ==== Mathematical operations ====

def multinomial(*counts):
    "Number of distinct arrangements of a multiset."
    # Counter('abracadabra').values() → 5 2 2 1 1
    # multinomial(5, 2, 2, 1, 1) → 83160
    return prod(map(comb, accumulate(counts), counts))

def powerset(iterable):
    "Subsequences of the iterable from shortest to longest."
    # 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 sum_of_squares(iterable):
    "Add up the squares of the input values."
    # sum_of_squares([10, 20, 30]) → 1400
    return sumprod(*tee(iterable))


# ==== Matrix operations ====

def reshape(matrix, columns):
    "Reshape a 2-D matrix to have a given number of columns."
    # reshape([(0, 1), (2, 3), (4, 5)], 3) →  (0, 1, 2) (3, 4, 5)
    return batched(chain.from_iterable(matrix), columns, strict=True)

def transpose(matrix):
    "Swap the rows and columns of a 2-D matrix."
    # transpose([(1, 2, 3), (11, 22, 33)]) → (1, 11) (2, 22) (3, 33)
    return zip(*matrix, strict=True)

def matmul(m1, m2):
    "Multiply two matrices."
    # matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)]) → (49, 80) (41, 60)
    n = len(m2[0])
    return batched(starmap(sumprod, product(m1, transpose(m2))), n)


# ==== Polynomial arithmetic ====

def convolve(signal, kernel):
    """Discrete linear convolution of two iterables.
    Equivalent to polynomial multiplication.

    Convolutions are mathematically commutative; however, the inputs are
    evaluated differently.  The signal is consumed lazily and can be
    infinite. The kernel is fully consumed before the calculations begin.

    Article:  https://betterexplained.com/articles/intuitive-convolution/
    Video:    https://www.youtube.com/watch?v=KuXjwB4LzSA
    """
    # convolve([1, -1, -20], [1, -3]) → 1 -4 -17 60
    # convolve(data, [0.25, 0.25, 0.25, 0.25]) → Moving average (blur)
    # convolve(data, [1/2, 0, -1/2]) → 1st derivative estimate
    # convolve(data, [1, -2, 1]) → 2nd derivative estimate
    kernel = tuple(kernel)[::-1]
    n = len(kernel)
    padded_signal = chain(repeat(0, n-1), signal, repeat(0, n-1))
    windowed_signal = sliding_window(padded_signal, n)
    return map(sumprod, repeat(kernel), windowed_signal)

def polynomial_from_roots(roots):
    """Compute a polynomial's coefficients from its roots.

       (x - 5) (x + 4) (x - 3)  expands to:   x³ -4x² -17x + 60
    """
    # polynomial_from_roots([5, -4, 3]) → [1, -4, -17, 60]
    factors = zip(repeat(1), map(neg, roots))
    return list(reduce(convolve, factors, [1]))

def polynomial_eval(coefficients, x):
    """Evaluate a polynomial at a specific value.

    Computes with better numeric stability than Horner's method.
    """
    # Evaluate x³ -4x² -17x + 60 at x = 5
    # polynomial_eval([1, -4, -17, 60], x=5) → 0
    n = len(coefficients)
    if not n:
        return type(x)(0)
    powers = map(pow, repeat(x), reversed(range(n)))
    return sumprod(coefficients, powers)

def polynomial_derivative(coefficients):
    """Compute the first derivative of a polynomial.

       f(x)  =  x³ -4x² -17x + 60
       f'(x) = 3x² -8x  -17
    """
    # polynomial_derivative([1, -4, -17, 60]) → [3, -8, -17]
    n = len(coefficients)
    powers = reversed(range(1, n))
    return list(map(mul, coefficients, powers))


# ==== Number theory ====

def sieve(n):
    "Primes less than n."
    # sieve(30) → 2 3 5 7 11 13 17 19 23 29
    if n > 2:
        yield 2
    data = bytearray((0, 1)) * (n // 2)
    for p in iter_index(data, 1, start=3, stop=isqrt(n) + 1):
        data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
    yield from iter_index(data, 1, start=3)

def factor(n):
    "Prime factors of n."
    # factor(99) → 3 3 11
    # factor(1_000_000_000_000_007) → 47 59 360620266859
    # factor(1_000_000_000_000_403) → 1000000000000403
    for prime in sieve(isqrt(n) + 1):
        while not n % prime:
            yield prime
            n //= prime
            if n == 1:
                return
    if n > 1:
        yield n

def is_prime(n):
    "Return True if n is prime."
    # is_prime(1_000_000_000_000_403) → True
    return n > 1 and next(factor(n)) == n

def totient(n):
    "Count of natural numbers up to n that are coprime to n."
    # https://mathworld.wolfram.com/TotientFunction.html
    # totient(12) → 4 because len([1, 5, 7, 11]) == 4
    for prime in set(factor(n)):
        n -= n // prime
    return n
@end example

@c These examples no longer appear in the docs but are guaranteed
@c to keep working.
@c 
@c >>> amounts = [120.15, 764.05, 823.14]
@c >>> for checknum, amount in zip(count(1200), amounts):
@c ...     print('Check %d is for $%.2f' % (checknum, amount))
@c ...
@c Check 1200 is for $120.15
@c Check 1201 is for $764.05
@c Check 1202 is for $823.14
@c 
@c >>> import operator
@c >>> for cube in map(operator.pow, range(1,4), repeat(3)):
@c ...    print(cube)
@c ...
@c 1
@c 8
@c 27
@c 
@c >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
@c >>> for name in islice(reportlines, 3, None, 2):
@c ...    print(name.title())
@c ...
@c Alex
@c Laura
@c Martin
@c Walter
@c Samuele
@c 
@c >>> from operator import itemgetter
@c >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
@c >>> di = sorted(sorted(d.items()), key=itemgetter(1))
@c >>> for k, g in groupby(di, itemgetter(1)):
@c ...     print(k, list(map(itemgetter(0), g)))
@c ...
@c 1 ['a', 'c', 'e']
@c 2 ['b', 'd', 'f']
@c 3 ['g']
@c 
@c # Find runs of consecutive numbers using groupby.  The key to the solution
@c # is differencing with a range so that consecutive numbers all appear in
@c # same group.
@c >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
@c >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
@c ...     print(list(map(operator.itemgetter(1), g)))
@c ...
@c [1]
@c [4, 5, 6]
@c [10]
@c [15, 16, 17, 18]
@c [22]
@c [25, 26, 27, 28]
@c 
@c Now, we test all of the itertool recipes
@c 
@c >>> take(10, count())
@c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@c >>> # Verify that the input is consumed lazily
@c >>> it = iter('abcdef')
@c >>> take(3, it)
@c ['a', 'b', 'c']
@c >>> list(it)
@c ['d', 'e', 'f']
@c 
@c 
@c >>> list(prepend(1, [2, 3, 4]))
@c [1, 2, 3, 4]
@c 
@c 
@c >>> list(enumerate('abc'))
@c [(0, 'a'), (1, 'b'), (2, 'c')]
@c 
@c 
@c >>> list(running_mean([8.5, 9.5, 7.5, 6.5]))
@c [8.5, 9.0, 8.5, 8.0]
@c 
@c 
@c >>> for _ in loops(5):
@c ...     print('hi')
@c ...
@c hi
@c hi
@c hi
@c hi
@c hi
@c 
@c 
@c >>> list(tail(3, 'ABCDEFG'))
@c ['E', 'F', 'G']
@c >>> # Verify the input is consumed greedily
@c >>> input_iterator = iter('ABCDEFG')
@c >>> output_iterator = tail(3, input_iterator)
@c >>> list(input_iterator)
@c []
@c 
@c 
@c >>> it = iter(range(10))
@c >>> consume(it, 3)
@c >>> # Verify the input is consumed lazily
@c >>> next(it)
@c 3
@c >>> # Verify the input is consumed completely
@c >>> consume(it)
@c >>> next(it, 'Done')
@c 'Done'
@c 
@c 
@c >>> nth('abcde', 3)
@c 'd'
@c >>> nth('abcde', 9) is None
@c True
@c >>> # Verify that the input is consumed lazily
@c >>> it = iter('abcde')
@c >>> nth(it, 2)
@c 'c'
@c >>> list(it)
@c ['d', 'e']
@c 
@c 
@c >>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
@c [True, True, True, False, False]
@c >>> [all_equal(s, key=str.casefold) for s in ('', 'A', 'AaAa', 'AAAB', 'AAABA')]
@c [True, True, True, False, False]
@c >>> # Verify that the input is consumed lazily and that only
@c >>> # one element of a second equivalence class is used to disprove
@c >>> # the assertion that all elements are equal.
@c >>> it = iter('aaabbbccc')
@c >>> all_equal(it)
@c False
@c >>> ''.join(it)
@c 'bbccc'
@c 
@c 
@c >>> quantify(range(99), lambda x: x%2==0)
@c 50
@c >>> quantify([True, False, False, True, True])
@c 3
@c >>> quantify(range(12), predicate=lambda x: x%2==1)
@c 6
@c 
@c 
@c >>> a = [[1, 2, 3], [4, 5, 6]]
@c >>> list(flatten(a))
@c [1, 2, 3, 4, 5, 6]
@c 
@c 
@c >>> list(ncycles('abc', 3))
@c ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
@c >>> # Verify greedy consumption of input iterator
@c >>> input_iterator = iter('abc')
@c >>> output_iterator = ncycles(input_iterator, 3)
@c >>> list(input_iterator)
@c []
@c 
@c 
@c >>> sum_of_squares([10, 20, 30])
@c 1400
@c 
@c 
@c >>> list(reshape([(0, 1), (2, 3), (4, 5)], 3))
@c [(0, 1, 2), (3, 4, 5)]
@c >>> M = [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
@c >>> list(reshape(M, 1))
@c [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,)]
@c >>> list(reshape(M, 2))
@c [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
@c >>> list(reshape(M, 3))
@c [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
@c >>> list(reshape(M, 4))
@c [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
@c >>> list(reshape(M, 5))
@c Traceback (most recent call last):
@c ...
@c ValueError: batched(): incomplete batch
@c >>> list(reshape(M, 6))
@c [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11)]
@c >>> list(reshape(M, 12))
@c [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)]
@c 
@c 
@c >>> list(transpose([(1, 2, 3), (11, 22, 33)]))
@c [(1, 11), (2, 22), (3, 33)]
@c >>> # Verify that the inputs are consumed lazily
@c >>> input1 = iter([1, 2, 3])
@c >>> input2 = iter([11, 22, 33])
@c >>> output_iterator = transpose([input1, input2])
@c >>> next(output_iterator)
@c (1, 11)
@c >>> list(zip(input1, input2))
@c [(2, 22), (3, 33)]
@c 
@c 
@c >>> list(matmul([(7, 5), (3, 5)], [[2, 5], [7, 9]]))
@c [(49, 80), (41, 60)]
@c >>> list(matmul([[2, 5], [7, 9], [3, 4]], [[7, 11, 5, 4, 9], [3, 5, 2, 6, 3]]))
@c [(29, 47, 20, 38, 33), (76, 122, 53, 82, 90), (33, 53, 23, 36, 39)]
@c 
@c 
@c >>> list(convolve([1, -1, -20], [1, -3])) == [1, -4, -17, 60]
@c True
@c >>> data = [20, 40, 24, 32, 20, 28, 16]
@c >>> list(convolve(data, [0.25, 0.25, 0.25, 0.25]))
@c [5.0, 15.0, 21.0, 29.0, 29.0, 26.0, 24.0, 16.0, 11.0, 4.0]
@c >>> list(convolve(data, [1, -1]))
@c [20, 20, -16, 8, -12, 8, -12, -16]
@c >>> list(convolve(data, [1, -2, 1]))
@c [20, 0, -36, 24, -20, 20, -20, -4, 16]
@c >>> # Verify signal is consumed lazily and the kernel greedily
@c >>> signal_iterator = iter([10, 20, 30, 40, 50])
@c >>> kernel_iterator = iter([1, 2, 3])
@c >>> output_iterator = convolve(signal_iterator, kernel_iterator)
@c >>> list(kernel_iterator)
@c []
@c >>> next(output_iterator)
@c 10
@c >>> next(output_iterator)
@c 40
@c >>> list(signal_iterator)
@c [30, 40, 50]
@c 
@c 
@c >>> from fractions import Fraction
@c >>> from decimal import Decimal
@c >>> polynomial_eval([1, -4, -17, 60], x=5)
@c 0
@c >>> x = 5; x**3 - 4*x**2 -17*x + 60
@c 0
@c >>> polynomial_eval([1, -4, -17, 60], x=2.5)
@c 8.125
@c >>> x = 2.5; x**3 - 4*x**2 -17*x + 60
@c 8.125
@c >>> polynomial_eval([1, -4, -17, 60], x=Fraction(2, 3))
@c Fraction(1274, 27)
@c >>> x = Fraction(2, 3); x**3 - 4*x**2 -17*x + 60
@c Fraction(1274, 27)
@c >>> polynomial_eval([1, -4, -17, 60], x=Decimal('1.75'))
@c Decimal('23.359375')
@c >>> x = Decimal('1.75'); x**3 - 4*x**2 -17*x + 60
@c Decimal('23.359375')
@c >>> polynomial_eval([], 2)
@c 0
@c >>> polynomial_eval([], 2.5)
@c 0.0
@c >>> polynomial_eval([], Fraction(2, 3))
@c Fraction(0, 1)
@c >>> polynomial_eval([], Decimal('1.75'))
@c Decimal('0')
@c >>> polynomial_eval([11], 7) == 11
@c True
@c >>> polynomial_eval([11, 2], 7) == 11 * 7 + 2
@c True
@c 
@c 
@c >>> polynomial_from_roots([5, -4, 3])
@c [1, -4, -17, 60]
@c >>> factored = lambda x: (x - 5) * (x + 4) * (x - 3)
@c >>> expanded = lambda x: x**3 -4*x**2 -17*x + 60
@c >>> all(factored(x) == expanded(x) for x in range(-10, 11))
@c True
@c 
@c 
@c >>> polynomial_derivative([1, -4, -17, 60])
@c [3, -8, -17]
@c 
@c 
@c >>> list(iter_index('AABCADEAF', 'A'))
@c [0, 1, 4, 7]
@c >>> list(iter_index('AABCADEAF', 'B'))
@c [2]
@c >>> list(iter_index('AABCADEAF', 'X'))
@c []
@c >>> list(iter_index('', 'X'))
@c []
@c >>> list(iter_index('AABCADEAF', 'A', 1))
@c [1, 4, 7]
@c >>> list(iter_index(iter('AABCADEAF'), 'A', 1))
@c [1, 4, 7]
@c >>> list(iter_index('AABCADEAF', 'A', 2))
@c [4, 7]
@c >>> list(iter_index(iter('AABCADEAF'), 'A', 2))
@c [4, 7]
@c >>> list(iter_index('AABCADEAF', 'A', 10))
@c []
@c >>> list(iter_index(iter('AABCADEAF'), 'A', 10))
@c []
@c >>> list(iter_index('AABCADEAF', 'A', 1, 7))
@c [1, 4]
@c >>> list(iter_index(iter('AABCADEAF'), 'A', 1, 7))
@c [1, 4]
@c >>> # Verify that ValueErrors not swallowed (gh-107208)
@c >>> def assert_no_value(iterable, forbidden_value):
@c ...     for item in iterable:
@c ...         if item == forbidden_value:
@c ...             raise ValueError
@c ...         yield item
@c ...
@c >>> list(iter_index(assert_no_value('AABCADEAF', 'B'), 'A'))
@c Traceback (most recent call last):
@c ...
@c ValueError
@c >>> # Verify that both paths can find identical NaN values
@c >>> x = float('NaN')
@c >>> y = float('NaN')
@c >>> list(iter_index([0, x, x, y, 0], x))
@c [1, 2]
@c >>> list(iter_index(iter([0, x, x, y, 0]), x))
@c [1, 2]
@c >>> # Test list input. Lists do not support None for the stop argument
@c >>> list(iter_index(list('AABCADEAF'), 'A'))
@c [0, 1, 4, 7]
@c >>> # Verify that input is consumed lazily
@c >>> input_iterator = iter('AABCADEAF')
@c >>> output_iterator = iter_index(input_iterator, 'A')
@c >>> next(output_iterator)
@c 0
@c >>> next(output_iterator)
@c 1
@c >>> next(output_iterator)
@c 4
@c >>> ''.join(input_iterator)
@c 'DEAF'
@c 
@c 
@c >>> # Verify that the target value can be a sequence.
@c >>> seq = [[10, 20], [30, 40], 30, 40, [30, 40], 50]
@c >>> target = [30, 40]
@c >>> list(iter_index(seq, target))
@c [1, 4]
@c 
@c 
@c >>> # Verify faithfulness to type specific index() method behaviors.
@c >>> # For example, bytes and str perform continuous-subsequence searches
@c >>> # that do not match the general behavior specified
@c >>> # in collections.abc.Sequence.index().
@c >>> seq = 'abracadabra'
@c >>> target = 'ab'
@c >>> list(iter_index(seq, target))
@c [0, 7]
@c 
@c 
@c >>> list(sieve(30))
@c [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
@c >>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
@c >>> all(list(sieve(n)) == [p for p in small_primes if p < n] for n in range(101))
@c True
@c >>> len(list(sieve(100)))
@c 25
@c >>> len(list(sieve(1_000)))
@c 168
@c >>> len(list(sieve(10_000)))
@c 1229
@c >>> len(list(sieve(100_000)))
@c 9592
@c >>> len(list(sieve(1_000_000)))
@c 78498
@c >>> carmichael = {561, 1105, 1729, 2465, 2821, 6601, 8911}  # https://oeis.org/A002997
@c >>> set(sieve(10_000)).isdisjoint(carmichael)
@c True
@c 
@c 
@c >>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
@c >>> list(filter(is_prime, range(-100, 100))) == small_primes
@c True
@c >>> carmichael = {561, 1105, 1729, 2465, 2821, 6601, 8911}  # https://oeis.org/A002997
@c >>> any(map(is_prime, carmichael))
@c False
@c >>> # https://www.wolframalpha.com/input?i=is+128884753939+prime
@c >>> is_prime(128_884_753_939)           # large prime
@c True
@c >>> is_prime(999953 * 999983)           # large semiprime
@c False
@c >>> is_prime(1_000_000_000_000_007)     # factor() example
@c False
@c >>> is_prime(1_000_000_000_000_403)     # factor() example
@c True
@c 
@c 
@c >>> list(factor(99))                    # Code example 1
@c [3, 3, 11]
@c >>> list(factor(1_000_000_000_000_007)) # Code example 2
@c [47, 59, 360620266859]
@c >>> list(factor(1_000_000_000_000_403)) # Code example 3
@c [1000000000000403]
@c >>> list(factor(0))
@c []
@c >>> list(factor(1))
@c []
@c >>> list(factor(2))
@c [2]
@c >>> list(factor(3))
@c [3]
@c >>> list(factor(4))
@c [2, 2]
@c >>> list(factor(5))
@c [5]
@c >>> list(factor(6))
@c [2, 3]
@c >>> list(factor(7))
@c [7]
@c >>> list(factor(8))
@c [2, 2, 2]
@c >>> list(factor(9))
@c [3, 3]
@c >>> list(factor(10))
@c [2, 5]
@c >>> list(factor(128_884_753_939))       # large prime
@c [128884753939]
@c >>> list(factor(999953 * 999983))       # large semiprime
@c [999953, 999983]
@c >>> list(factor(6 ** 20)) == [2] * 20 + [3] * 20   # large power
@c True
@c >>> list(factor(909_909_090_909))       # large multiterm composite
@c [3, 3, 7, 13, 13, 751, 113797]
@c >>> math.prod([3, 3, 7, 13, 13, 751, 113797])
@c 909909090909
@c >>> all(math.prod(factor(n)) == n for n in range(1, 2_000))
@c True
@c >>> all(set(factor(n)) <= set(sieve(n+1)) for n in range(2_000))
@c True
@c >>> all(list(factor(n)) == sorted(factor(n)) for n in range(2_000))
@c True
@c 
@c 
@c >>> totient(0)  # https://www.wolframalpha.com/input?i=totient+0
@c 0
@c >>> first_totients = [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16, 6,
@c ... 18, 8, 12, 10, 22, 8, 20, 12, 18, 12, 28, 8, 30, 16, 20, 16, 24, 12, 36, 18,
@c ... 24, 16, 40, 12, 42, 20, 24, 22, 46, 16, 42, 20, 32, 24, 52, 18, 40, 24, 36,
@c ... 28, 58, 16, 60, 30, 36, 32, 48, 20, 66, 32, 44]  # https://oeis.org/A000010
@c ...
@c >>> list(map(totient, range(1, 70))) == first_totients
@c True
@c >>> reference_totient = lambda n: sum(math.gcd(t, n) == 1 for t in range(1, n+1))
@c >>> all(totient(n) == reference_totient(n) for n in range(1000))
@c True
@c >>> totient(128_884_753_939) == 128_884_753_938  # large prime
@c True
@c >>> totient(999953 * 999983) == 999952 * 999982  # large semiprime
@c True
@c >>> totient(6 ** 20) == 1 * 2**19 * 2 * 3**19    # repeated primes
@c True
@c 
@c 
@c >>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
@c ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
@c 
@c 
@c >>> list(repeatfunc(pow, 5, 2, 3))
@c [8, 8, 8, 8, 8]
@c >>> take(5, map(int, repeatfunc(random.random)))
@c [0, 0, 0, 0, 0]
@c >>> random.seed(85753098575309)
@c >>> list(repeatfunc(random.random, 3))
@c [0.16370491282496968, 0.45889608687313455, 0.3747076837820118]
@c >>> list(repeatfunc(chr, 3, 65))
@c ['A', 'A', 'A']
@c >>> list(repeatfunc(pow, 3, 2, 5))
@c [32, 32, 32]
@c 
@c 
@c >>> list(grouper('abcdefg', 3, fillvalue='x'))
@c [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
@c 
@c 
@c >>> it = grouper('abcdefg', 3, incomplete='strict')
@c >>> next(it)
@c ('a', 'b', 'c')
@c >>> next(it)
@c ('d', 'e', 'f')
@c >>> next(it)
@c Traceback (most recent call last):
@c   ...
@c ValueError: zip() argument 2 is shorter than argument 1
@c 
@c >>> list(grouper('abcdefg', n=3, incomplete='ignore'))
@c [('a', 'b', 'c'), ('d', 'e', 'f')]
@c 
@c 
@c >>> list(sliding_window('ABCDEFG', 1))
@c [('A',), ('B',), ('C',), ('D',), ('E',), ('F',), ('G',)]
@c >>> list(sliding_window('ABCDEFG', 2))
@c [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
@c >>> list(sliding_window('ABCDEFG', 3))
@c [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
@c >>> list(sliding_window('ABCDEFG', 4))
@c [('A', 'B', 'C', 'D'), ('B', 'C', 'D', 'E'), ('C', 'D', 'E', 'F'), ('D', 'E', 'F', 'G')]
@c >>> list(sliding_window('ABCDEFG', 5))
@c [('A', 'B', 'C', 'D', 'E'), ('B', 'C', 'D', 'E', 'F'), ('C', 'D', 'E', 'F', 'G')]
@c >>> list(sliding_window('ABCDEFG', 6))
@c [('A', 'B', 'C', 'D', 'E', 'F'), ('B', 'C', 'D', 'E', 'F', 'G')]
@c >>> list(sliding_window('ABCDEFG', 7))
@c [('A', 'B', 'C', 'D', 'E', 'F', 'G')]
@c >>> list(sliding_window('ABCDEFG', 8))
@c []
@c >>> try:
@c ...     list(sliding_window('ABCDEFG', -1))
@c ... except ValueError:
@c ...     'zero or negative n not supported'
@c ...
@c 'zero or negative n not supported'
@c >>> try:
@c ...     list(sliding_window('ABCDEFG', 0))
@c ... except ValueError:
@c ...     'zero or negative n not supported'
@c ...
@c 'zero or negative n not supported'
@c 
@c 
@c >>> list(roundrobin('abc', 'd', 'ef'))
@c ['a', 'd', 'e', 'b', 'f', 'c']
@c >>> ranges = [range(5, 1000), range(4, 3000), range(0), range(3, 2000), range(2, 5000), range(1, 3500)]
@c >>> collections.Counter(roundrobin(*ranges)) == collections.Counter(chain(*ranges))
@c True
@c >>> # Verify that the inputs are consumed lazily
@c >>> input_iterators = list(map(iter, ['abcd', 'ef', '', 'ghijk', 'l', 'mnopqr']))
@c >>> output_iterator = roundrobin(*input_iterators)
@c >>> ''.join(islice(output_iterator, 10))
@c 'aeglmbfhnc'
@c >>> ''.join(chain(*input_iterators))
@c 'dijkopqr'
@c 
@c 
@c >>> list(subslices('ABCD'))
@c ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D']
@c 
@c 
@c >>> ' '.join(map(''.join, derangements('ABCD')))
@c 'BADC BCDA BDAC CADB CDAB CDBA DABC DCAB DCBA'
@c >>> ' '.join(map(''.join, derangements('ABCD', 3)))
@c 'BAD BCA BCD BDA CAB CAD CDA CDB DAB DCA DCB'
@c >>> ' '.join(map(''.join, derangements('ABCD', 2)))
@c 'BA BC BD CA CD DA DC'
@c >>> ' '.join(map(''.join, derangements('ABCD', 1)))
@c 'B C D'
@c >>> ' '.join(map(''.join, derangements('ABCD', 0)))
@c ''
@c >>> # Compare number of derangements to https://oeis.org/A000166
@c >>> [len(list(derangements(range(n)))) for n in range(10)]
@c [1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496]
@c >>> # Verify that identical objects are treated as unique by position
@c >>> identical = 'X'
@c >>> distinct = 'x'
@c >>> seq1 = ('A', identical, 'B', identical)
@c >>> result1 = ' '.join(map(''.join, derangements(seq1)))
@c >>> result1
@c 'XAXB XBXA XXAB BAXX BXAX BXXA XAXB XBAX XBXA'
@c >>> seq2 = ('A', identical, 'B', distinct)
@c >>> result2 = ' '.join(map(''.join, derangements(seq2)))
@c >>> result2
@c 'XAxB XBxA XxAB BAxX BxAX BxXA xAXB xBAX xBXA'
@c >>> result1 == result2
@c False
@c >>> result1.casefold() == result2.casefold()
@c True
@c 
@c 
@c >>> list(powerset([1,2,3]))
@c [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
@c >>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
@c True
@c >>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
@c True
@c 
@c 
@c >>> list(unique_everseen('AAAABBBCCDAABBB'))
@c ['A', 'B', 'C', 'D']
@c >>> list(unique_everseen('ABBCcAD', str.casefold))
@c ['A', 'B', 'C', 'D']
@c >>> list(unique_everseen('ABBcCAD', str.casefold))
@c ['A', 'B', 'c', 'D']
@c >>> # Verify that the input is consumed lazily
@c >>> input_iterator = iter('AAAABBBCCDAABBB')
@c >>> output_iterator = unique_everseen(input_iterator)
@c >>> next(output_iterator)
@c 'A'
@c >>> ''.join(input_iterator)
@c 'AAABBBCCDAABBB'
@c 
@c 
@c >>> list(unique_justseen('AAAABBBCCDAABBB'))
@c ['A', 'B', 'C', 'D', 'A', 'B']
@c >>> list(unique_justseen('ABBCcAD', str.casefold))
@c ['A', 'B', 'C', 'A', 'D']
@c >>> list(unique_justseen('ABBcCAD', str.casefold))
@c ['A', 'B', 'c', 'A', 'D']
@c >>> # Verify that the input is consumed lazily
@c >>> input_iterator = iter('AAAABBBCCDAABBB')
@c >>> output_iterator = unique_justseen(input_iterator)
@c >>> next(output_iterator)
@c 'A'
@c >>> ''.join(input_iterator)
@c 'AAABBBCCDAABBB'
@c 
@c 
@c >>> list(unique([[1, 2], [3, 4], [1, 2]]))
@c [[1, 2], [3, 4]]
@c >>> list(unique('ABBcCAD', str.casefold))
@c ['A', 'B', 'c', 'D']
@c >>> list(unique('ABBcCAD', str.casefold, reverse=True))
@c ['D', 'c', 'B', 'A']
@c 
@c 
@c >>> d = dict(a=1, b=2, c=3)
@c >>> it = iter_except(d.popitem, KeyError)
@c >>> d['d'] = 4
@c >>> next(it)
@c ('d', 4)
@c >>> next(it)
@c ('c', 3)
@c >>> next(it)
@c ('b', 2)
@c >>> d['e'] = 5
@c >>> next(it)
@c ('e', 5)
@c >>> next(it)
@c ('a', 1)
@c >>> next(it, 'empty')
@c 'empty'
@c 
@c 
@c >>> first_true('ABC0DEF1', '9', str.isdigit)
@c '0'
@c >>> # Verify that inputs are consumed lazily
@c >>> it = iter('ABC0DEF1')
@c >>> first_true(it, predicate=str.isdigit)
@c '0'
@c >>> ''.join(it)
@c 'DEF1'
@c 
@c >>> multinomial(5, 2, 2, 1, 1)
@c 83160
@c >>> word = 'coffee'
@c >>> multinomial(*Counter(word).values()) == len(set(permutations(word)))
@c True

@c # Old recipes and their tests which are guaranteed to continue to work.
@c 
@c def tabulate(function, start=0):
@c     "Return function(0), function(1), ..."
@c     return map(function, count(start))
@c 
@c def old_sumprod_recipe(vec1, vec2):
@c     "Compute a sum of products."
@c     return sum(starmap(operator.mul, zip(vec1, vec2, strict=True)))
@c 
@c def dotproduct(vec1, vec2):
@c     return sum(map(operator.mul, vec1, vec2))
@c 
@c def pad_none(iterable):
@c     """Returns the sequence elements and then returns None indefinitely.
@c 
@c     Useful for emulating the behavior of the built-in map() function.
@c     """
@c     return chain(iterable, repeat(None))
@c 
@c def triplewise(iterable):
@c     "Return overlapping triplets from an iterable"
@c     # triplewise('ABCDEFG') → ABC BCD CDE DEF EFG
@c     for (a, _), (b, c) in pairwise(pairwise(iterable)):
@c         yield a, b, c
@c 
@c def nth_combination(iterable, r, index):
@c     "Equivalent to list(combinations(iterable, r))[index]"
@c     pool = tuple(iterable)
@c     n = len(pool)
@c     c = math.comb(n, r)
@c     if index < 0:
@c         index += c
@c     if index < 0 or index >= c:
@c         raise IndexError
@c     result = []
@c     while r:
@c         c, n, r = c*r//n, n-1, r-1
@c         while index >= c:
@c             index -= c
@c             c, n = c*(n-r)//n, n-1
@c         result.append(pool[-1-n])
@c     return tuple(result)
@c 
@c def before_and_after(predicate, it):
@c    """ Variant of takewhile() that allows complete
@c        access to the remainder of the iterator.
@c 
@c        >>> it = iter('ABCdEfGhI')
@c        >>> all_upper, remainder = before_and_after(str.isupper, it)
@c        >>> ''.join(all_upper)
@c        'ABC'
@c        >>> ''.join(remainder)     # takewhile() would lose the 'd'
@c        'dEfGhI'
@c 
@c        Note that the true iterator must be fully consumed
@c        before the remainder iterator can generate valid results.
@c    """
@c    it = iter(it)
@c    transition = []
@c 
@c    def true_iterator():
@c        for elem in it:
@c            if predicate(elem):
@c                yield elem
@c            else:
@c                transition.append(elem)
@c                return
@c 
@c    return true_iterator(), chain(transition, it)
@c 
@c def partition(predicate, iterable):
@c     """Partition entries into false entries and true entries.
@c 
@c     If *predicate* is slow, consider wrapping it with functools.lru_cache().
@c     """
@c     # partition(is_odd, range(10)) → 0 2 4 6 8   and  1 3 5 7 9
@c     t1, t2 = tee(iterable)
@c     return filterfalse(predicate, t1), filter(predicate, t2)

@c >>> list(islice(tabulate(lambda x: 2*x), 4))
@c [0, 2, 4, 6]
@c 
@c 
@c >>> dotproduct([1,2,3], [4,5,6])
@c 32
@c 
@c 
@c >>> old_sumprod_recipe([1,2,3], [4,5,6])
@c 32
@c 
@c 
@c >>> list(islice(pad_none('abc'), 0, 6))
@c ['a', 'b', 'c', None, None, None]
@c 
@c 
@c >>> list(triplewise('ABCDEFG'))
@c [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
@c 
@c 
@c >>> population = 'ABCDEFGH'
@c >>> for r in range(len(population) + 1):
@c ...     seq = list(combinations(population, r))
@c ...     for i in range(len(seq)):
@c ...         assert nth_combination(population, r, i) == seq[i]
@c ...     for i in range(-len(seq), 0):
@c ...         assert nth_combination(population, r, i) == seq[i]
@c ...
@c >>> iterable = 'abcde'
@c >>> r = 3
@c >>> combos = list(combinations(iterable, r))
@c >>> all(nth_combination(iterable, r, i) == comb for i, comb in enumerate(combos))
@c True
@c 
@c 
@c >>> it = iter('ABCdEfGhI')
@c >>> all_upper, remainder = before_and_after(str.isupper, it)
@c >>> ''.join(all_upper)
@c 'ABC'
@c >>> ''.join(remainder)
@c 'dEfGhI'
@c 
@c 
@c >>> def is_odd(x):
@c ...     return x % 2 == 1
@c ...
@c >>> evens, odds = partition(is_odd, range(10))
@c >>> list(evens)
@c [0, 2, 4, 6, 8]
@c >>> list(odds)
@c [1, 3, 5, 7, 9]
@c >>> # Verify that the input is consumed lazily
@c >>> input_iterator = iter(range(10))
@c >>> evens, odds = partition(is_odd, input_iterator)
@c >>> next(odds)
@c 1
@c >>> next(odds)
@c 3
@c >>> next(evens)
@c 0
@c >>> list(input_iterator)
@c [4, 5, 6, 7, 8, 9]

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node functools --- 高階関数と呼び出し可能オブジェクトの操作,operator --- 関数形式の標準演算子,itertools --- 効率的なループ用のイテレータ生成関数群,関数型プログラミング用モジュール
@anchor{library/functools doc}@anchor{2bac}@anchor{library/functools functools-higher-order-functions-and-operations-on-callable-objects}@anchor{2bad}@anchor{library/functools module-functools}@anchor{63}@anchor{library/functools translation-repo}@anchor{2bae}
@subsection @code{functools} --- 高階関数と呼び出し可能オブジェクトの操作


@geindex module; functools

`ソースコード:' Lib/functools.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/functools.py}

@c import functools
@c from functools import *


__________________________________________________________________


The @code{functools} module is for higher-order functions: functions that act on
or return other functions. In general, any callable object can be treated as a
function for the purposes of this module.

The @code{functools} module defines the following functions:

@geindex cache() (functools モジュール)
@anchor{library/functools functools cache}@anchor{17c8}
@deffn {の関数} @@functools.cache (user_function)

簡単で軽量な無制限の関数キャッシュです。 "メモ化 (memoize)"@footnote{https://en.wikipedia.org/wiki/Memoization} とも呼ばれることがあります。

Returns the same as @code{lru_cache(maxsize=None)}, creating a thin
wrapper around a dictionary lookup for the function arguments.  Because it
never needs to evict old values, this is smaller and faster than
@ref{be2,,lru_cache()} with a size limit.

例えば:

@example
@@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)   # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)    # no new calls, just returns the cached result
120
>>> factorial(12)   # two new recursive calls, factorial(10) is cached
479001600
@end example

The cache is threadsafe so that the wrapped function can be used in
multiple threads.  This means that the underlying data structure will
remain coherent during concurrent updates.

It is possible for the wrapped function to be called more than once if
another thread makes an additional call before the initial call has been
completed and cached.


Added in version 3.9.

@end deffn

@geindex cached_property() (functools モジュール)
@anchor{library/functools functools cached_property}@anchor{763}
@deffn {の関数} @@functools.cached_property (func)

クラスのメソッドを、値を一度だけ計算して通常の属性としてキャッシュするプロパティに変換します。キャッシュはインスタンスの生存期間にわたって有効です。@ref{4b3,,property()} に似ていて、さらにキャッシュを行います。計算コストが高く、一度計算すればその後は不変であるようなインスタンスのプロパティに対して有用です。

以下はプログラム例です:

@example
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @@cached_property
    def stdev(self):
        return statistics.stdev(self._data)
@end example

@ref{763,,cached_property()} のしくみは @ref{4b3,,property()} とやや異なります。通常のプロパティは、セッター (setter) が定義されない限り書き込みを禁止します。対照的に、 `cached_property' は書き込みを許します。

`cached_property' デコレータはルックアップテーブルで、同名の属性が存在しない場合のみ動作します。動作した場合、 `cached_property' は同名の属性に書き込みを行います。その後の属性の読み込みと書き込みは `cached_property' メソッドより優先され、通常の属性のように働きます。

キャッシュされた値は属性を削除することで取り除くことができます。これにより `cached_property' メソッドを再度実行することが可能になります。

The `cached_property' does not prevent a possible race condition in
multi-threaded usage. The getter function could run more than once on the
same instance, with the latest run setting the cached value. If the cached
property is idempotent or otherwise not harmful to run more than once on an
instance, this is fine. If synchronization is needed, implement the necessary
locking inside the decorated getter function or around the cached property
access.

このデコレータは 
@geindex Python Enhancement Proposals; PEP 412
PEP 412@footnote{https://peps.python.org/pep-0412/} のキー共有辞書のインターフェースを持ちます。これは、インスタンス辞書がより多くのスペースを使う可能性があることを意味します。

また、このデコレータは各インスタンスの @code{__dict__} 属性が可変のマッピングであることを要求します。すなわち、このデコレータはいくつかの型、たとえばメタクラス (型インスタンスの @code{__dict__} 属性はクラスの名前空間に対する読み込み専用のプロキシであるため) や、 @code{__slots__} を指定していてその中に @code{__dict__} を含まない型 (それ自体が @code{__dict__} 属性を提供しないため) に対しては動作しないことを意味します。

If a mutable mapping is not available or if space-efficient key sharing is
desired, an effect similar to @ref{763,,cached_property()} can also be achieved by
stacking @ref{4b3,,property()} on top of @ref{be2,,lru_cache()}. See
@ref{2baf,,メソッド呼び出しをキャッシュするには どうしたらいいですか？} for more details on how this differs from @ref{763,,cached_property()}.


Added in version 3.8.



バージョン 3.12 で変更: Prior to Python 3.12, @code{cached_property} included an undocumented lock to
ensure that in multi-threaded usage the getter function was guaranteed to
run only once per instance. However, the lock was per-property, not
per-instance, which could result in unacceptably high lock contention. In
Python 3.12+ this locking is removed.

@end deffn

@geindex cmp_to_key() (functools モジュール)
@anchor{library/functools functools cmp_to_key}@anchor{13f2}
@deffn {の関数} functools.cmp_to_key (func)

古いスタイルの比較関数を @ref{1006,,key function} に変換します。key 関数を受け取るツール (@ref{dc7,,sorted()}, @ref{110b,,min()}, @ref{110c,,max()}, @ref{29a5,,heapq.nlargest()}, @ref{29a6,,heapq.nsmallest()}, @ref{2ba5,,itertools.groupby()} など) と共に使用します。この関数は、主に比較関数を使っていた Python 2 からプログラムの移行のための変換ツールとして使われます。

比較関数は2つの引数を受け取り、それらを比較し、 "より小さい" 場合は負の数を、同値の場合には 0 を、 "より大きい" 場合には正の数を返す、あらゆる呼び出し可能オブジェクトです。key 関数は呼び出し可能オブジェクトで、1つの引数を受け取り、ソートキーとして使われる値を返します。

以下はプログラム例です:

@example
sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
@end example

ソートの例と簡単なチュートリアルは @ref{13f3,,ソートのテクニック} を参照して下さい。


Added in version 3.2.

@end deffn

@geindex lru_cache() (functools モジュール)
@anchor{library/functools functools lru_cache}@anchor{be2}
@deffn {の関数} @@functools.lru_cache (user_function)

@deffnx {の関数} @@functools.lru_cache (maxsize=128, typed=False)

関数をメモ化用の呼び出し可能オブジェクトでラップし、最近の呼び出し最大 `maxsize' 回まで保存するするデコレータです。高価な関数や I/O に束縛されている関数を定期的に同じ引数で呼び出すときに、時間を節約できます。

The cache is threadsafe so that the wrapped function can be used in
multiple threads.  This means that the underlying data structure will
remain coherent during concurrent updates.

It is possible for the wrapped function to be called more than once if
another thread makes an additional call before the initial call has been
completed and cached.

結果のキャッシュには辞書が使われるので、関数の位置引数およびキーワード引数は @ref{824,,ハッシュ可能} でなくてはなりません。

引数のパターンが異なる場合は、異なる呼び出しと見なされ別々のキャッシュエントリーとなります。
例えば、 @code{f(a=1, b=2)} と @code{f(b=2, a=1)} はキーワード引数の順序が異なっているので、2つの別個のキャッシュエントリーになります。

`user_function' が指定された場合、それは呼び出し可能でなければなりません。これにより `lru_cache' デコレータがユーザー関数に直接適用できるようになります。このとき `maxsize' の値はデフォルトの 128 となります:

@example
@@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
@end example

`maxsize' が @code{None} に設定された場合は、LRU 機能は無効化され、キャッシュは際限無く大きくなります。

If `typed' is set to true, function arguments of different types will be
cached separately.  If `typed' is false, the implementation will usually
regard them as equivalent calls and only cache a single result. (Some
types such as `str' and `int' may be cached separately even when `typed'
is false.)

Note, type specificity applies only to the function's immediate arguments
rather than their contents.  The scalar arguments, @code{Decimal(42)} and
@code{Fraction(42)} are be treated as distinct calls with distinct results.
In contrast, the tuple arguments @code{('answer', Decimal(42))} and
@code{('answer', Fraction(42))} are treated as equivalent.

The wrapped function is instrumented with a @code{cache_parameters()}
function that returns a new @ref{183,,dict} showing the values for `maxsize'
and `typed'.  This is for information purposes only.  Mutating the values
has no effect.

@geindex cache_info() (functools.lru_cache のメソッド)
@anchor{library/functools functools lru_cache cache_info}@anchor{2bb0}
To help measure the effectiveness of the cache and tune the `maxsize'
parameter, the wrapped function is instrumented with a @code{cache_info()}
function that returns a @ref{85e,,named tuple} showing `hits', `misses',
`maxsize' and `currsize'.

@geindex cache_clear() (functools.lru_cache のメソッド)
@anchor{library/functools functools lru_cache cache_clear}@anchor{2bb1}
The decorator also provides a @code{cache_clear()} function for clearing or
invalidating the cache.

元々の基底の関数には、 @code{__wrapped__} 属性を通してアクセスできます。これはキャッシュを回避して、または関数を別のキャッシュでラップして、内観するのに便利です。

The cache keeps references to the arguments and return values until they age
out of the cache or until the cache is cleared.

If a method is cached, the @code{self} instance argument is included in the
cache.  See @ref{2baf,,メソッド呼び出しをキャッシュするには どうしたらいいですか？}

An LRU (least recently used) cache@footnote{https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_(LRU)}
works best when the most recent calls are the best predictors of upcoming
calls (for example, the most popular articles on a news server tend to
change each day).  The cache's size limit assures that the cache does not
grow without bound on long-running processes such as web servers.

In general, the LRU cache should only be used when you want to reuse
previously computed values.  Accordingly, it doesn't make sense to cache
functions with side-effects, functions that need to create
distinct mutable objects on each call (such as generators and async functions),
or impure functions such as time() or random().

静的 web コンテンツ の LRU キャッシュの例:

@example
@@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = f'https://peps.python.org/pep-@{num:04d@}'
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
@end example

キャッシュを使って 動的計画法@footnote{https://ja.wikipedia.org/wiki/動的計画法} の技法を実装し、フィボナッチ数@footnote{https://ja.wikipedia.org/wiki/フィボナッチ数} を効率よく計算する例:

@example
@@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
@end example


Added in version 3.2.



バージョン 3.3 で変更: `typed' オプションが追加されました。



バージョン 3.8 で変更: `user_function' オプションが追加されました。



バージョン 3.9 で変更: Added the function @code{cache_parameters()}

@end deffn

@geindex total_ordering() (functools モジュール)
@anchor{library/functools functools total_ordering}@anchor{1144}
@deffn {の関数} @@functools.total_ordering

ひとつ以上の拡張順序比較メソッド (rich comparison ordering methods) を定義したクラスを受け取り、残りを実装するクラスデコレータです。このデコレータは全ての拡張順序比較演算をサポートするための労力を軽減します:

The class must define one of @ref{14b8,,__lt__()}, @ref{1522,,__le__()},
@ref{1523,,__gt__()}, or @ref{1524,,__ge__()}.
In addition, the class should supply an @ref{cf2,,__eq__()} method.

例えば:

@example
@@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
@end example

@cartouche
@quotation 注釈 
このデコレータにより、このデコレータにより、行儀の良い（well behaved）全順序型を簡単に作ることができますが、その代償として実行速度は遅く、比較メソッドの演繹によってのスタックトレースは複雑になります。性能ベンチマークにより、これがアプリケーションのボトルネックになっていることがわかった場合は、代わりに 6 つの拡張比較メソッドをすべて実装すれば、簡単にスピードアップを図れるでしょう。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
This decorator makes no attempt to override methods that have been
declared in the class `or its superclasses'. Meaning that if a
superclass defines a comparison operator, `total_ordering' will not
implement it again, even if the original method is abstract.
@end quotation
@end cartouche


Added in version 3.2.



バージョン 3.4 で変更: Returning @code{NotImplemented} from the underlying comparison function for
unrecognised types is now supported.

@end deffn

@geindex Placeholder (functools モジュール)
@anchor{library/functools functools Placeholder}@anchor{216}
@deffn {データ} functools.Placeholder

A singleton object used as a sentinel to reserve a place
for positional arguments when calling @ref{217,,partial()}
and @ref{218,,partialmethod()}.


Added in version 3.14.

@end deffn

@geindex partial() (functools モジュール)
@anchor{library/functools functools partial}@anchor{217}
@deffn {の関数} functools.partial (func, /, *args, **keywords)

新しい @ref{219,,partial オブジェクト} を返します。このオブジェクトは呼び出されると位置引数 `args' とキーワード引数 `keywords' 付きで呼び出された `func' のように振る舞います。呼び出しに際してさらなる引数が渡された場合、それらは `args' に付け加えられます。追加のキーワード引数が渡された場合には、それらで `keywords' を拡張または上書きします。おおよそ次のコードと等価です:

@example
def partial(func, /, *args, **keywords):
    def newfunc(*more_args, **more_keywords):
        return func(*args, *more_args, **(keywords | more_keywords))
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
@end example

The @code{partial()} function is used for partial function application which "freezes"
some portion of a function's arguments and/or keywords resulting in a new object
with a simplified signature.  For example, @ref{217,,partial()} can be used to create
a callable that behaves like the @ref{19b,,int()} function where the `base' argument
defaults to @code{2}:

@example
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
@end example

If @ref{216,,Placeholder} sentinels are present in `args', they will be filled first
when @code{partial()} is called. This makes it possible to pre-fill any positional
argument with a call to @code{partial()}; without @code{Placeholder},
only the chosen number of leading positional arguments can be pre-filled.

If any @code{Placeholder} sentinels are present, all must be filled at call time:

@example
>>> say_to_world = partial(print, Placeholder, Placeholder, "world!")
>>> say_to_world('Hello', 'dear')
Hello dear world!
@end example

Calling @code{say_to_world('Hello')} raises a @ref{198,,TypeError}, because
only one positional argument is provided, but there are two placeholders
that must be filled in.

If @code{partial()} is applied to an existing @code{partial()} object,
@code{Placeholder} sentinels of the input object are filled in with
new positional arguments.
A placeholder can be retained by inserting a new
@code{Placeholder} sentinel to the place held by a previous @code{Placeholder}:

@example
>>> from functools import partial, Placeholder as _
>>> remove = partial(str.replace, _, _, '@w{'})
>>> message = 'Hello, dear dear world!'
>>> remove(message, ' dear')
'Hello, world!'
>>> remove_dear = partial(remove, _, ' dear')
>>> remove_dear(message)
'Hello, world!'
>>> remove_first_dear = partial(remove_dear, _, 1)
>>> remove_first_dear(message)
'Hello, dear world!'
@end example

@code{Placeholder} cannot be passed to @code{partial()} as a keyword argument.


バージョン 3.14 で変更: Added support for @ref{216,,Placeholder} in positional arguments.

@end deffn

@geindex partialmethod (functools のクラス)
@anchor{library/functools functools partialmethod}@anchor{218}
@deffn {クラス} functools.partialmethod (func, /, *args, **keywords)

@ref{217,,partial} と似た動作をする新しい @ref{218,,partialmethod} 記述子 (デスクリプタ) を返します。直接呼び出しではなく、メソッド定義としての使用が目的であることのみが、partial とは異なります。

`func' は、@ref{1881,,descriptor} または呼び出し可能オブジェクトである必要があります (通常の関数など、両方の性質を持つオブジェクトは記述子として扱われます。)

When `func' is a descriptor (such as a normal Python function,
@ref{48e,,classmethod()}, @ref{453,,staticmethod()}, @ref{1297,,abstractmethod()} or
another instance of @ref{218,,partialmethod}), calls to @code{__get__} are
delegated to the underlying descriptor, and an appropriate
@ref{219,,partial object} returned as the result.

`func' が記述子以外の呼び出し可能オブジェクトである場合、適切な束縛メソッドが動的に作成されます。この func は、メソッドとして使用された場合、Python の通常の関数と同様に動作します。 @ref{218,,partialmethod} コンストラクタに `args' と `keywords' が渡されるよりも前に、 `self' 引数が最初の位置引数として挿入されます。

以下はプログラム例です:

@example
>>> class Cell:
...     def __init__(self):
...         self._alive = False
...     @@property
...     def alive(self):
...         return self._alive
...     def set_state(self, state):
...         self._alive = bool(state)
...     set_alive = partialmethod(set_state, True)
...     set_dead = partialmethod(set_state, False)
...
>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True
@end example


Added in version 3.4.

@end deffn

@geindex reduce() (functools モジュール)
@anchor{library/functools functools reduce}@anchor{21a}
@deffn {の関数} functools.reduce (function, iterable, /[, initial])

Apply `function' of two arguments cumulatively to the items of `iterable', from
left to right, so as to reduce the iterable to a single value.  For example,
@code{reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])} calculates @code{((((1+2)+3)+4)+5)}.
The left argument, `x', is the accumulated value and the right argument, `y', is
the update value from the `iterable'.  If the optional `initial' is present,
it is placed before the items of the iterable in the calculation, and serves as
a default when the iterable is empty.  If `initial' is not given and
`iterable' contains only one item, the first item is returned.

およそ次と等価です:

@example
initial_missing = object()

def reduce(function, iterable, /, initial=initial_missing):
    it = iter(iterable)
    if initial is initial_missing:
        value = next(it)
    else:
        value = initial
    for element in it:
        value = function(value, element)
    return value
@end example

全ての中間値を返すイテレータについては @ref{bf0,,itertools.accumulate()} を参照してください。


バージョン 3.14 で変更: `initial' is now supported as a keyword argument.

@end deffn

@geindex singledispatch() (functools モジュール)
@anchor{library/functools functools singledispatch}@anchor{84b}
@deffn {の関数} @@functools.singledispatch

関数を @ref{be3,,シングルディスパッチ} @ref{be4,,ジェネリック関数} に変換します。

To define a generic function, decorate it with the @code{@@singledispatch}
decorator. When defining a function using @code{@@singledispatch}, note that the
dispatch happens on the type of the first argument:

@example
>>> from functools import singledispatch
>>> @@singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)
@end example

@geindex register() (functools.singledispatch のメソッド)
@anchor{library/functools functools singledispatch register}@anchor{2bb2}
To add overloaded implementations to the function, use the @code{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:

@example
>>> @@fun.register
... def _(arg: int, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @@fun.register
... def _(arg: list, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)
@end example

@ref{2a8,,typing.Union} can also be used:

@example
>>> @@fun.register
... def _(arg: int | float, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> from typing import Union
>>> @@fun.register
... def _(arg: Union[list, set], verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)
...
@end example

型アノテーションを使っていないコードについては、デコレータに適切な型引数を明示的に渡せます:

@example
>>> @@fun.register(complex)
... def _(arg, verbose=False):
...     if verbose:
...         print("Better than complicated.", end=" ")
...     print(arg.real, arg.imag)
...
@end example

For code that dispatches on a collections type (e.g., @code{list}), but wants
to typehint the items of the collection (e.g., @code{list[int]}), the
dispatch type should be passed explicitly to the decorator itself with the
typehint going into the function definition:

@example
>>> @@fun.register(list)
... def _(arg: list[int], verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)
@end example

@cartouche
@quotation 注釈 
At runtime the function will dispatch on an instance of a list regardless
of the type contained within the list i.e. @code{[1,2,3]} will be
dispatched the same as @code{["foo", "bar", "baz"]}. The annotation
provided in this example is for static type checkers only and has no
runtime impact.
@end quotation
@end cartouche

To enable registering @ref{2bb3,,lambdas} and pre-existing functions,
the @ref{2bb2,,register()} attribute can also be used in a functional form:

@example
>>> def nothing(arg, verbose=False):
...     print("Nothing.")
...
>>> fun.register(type(None), nothing)
@end example

The @ref{2bb2,,register()} attribute returns the undecorated function. This
enables decorator stacking, @ref{ab,,pickling}, and the creation
of unit tests for each variant independently:

@example
>>> @@fun.register(float)
... @@fun.register(Decimal)
... def fun_num(arg, verbose=False):
...     if verbose:
...         print("Half of your number:", end=" ")
...     print(arg / 2)
...
>>> fun_num is fun
False
@end example

汎用関数は、呼び出されると 1 つ目の引数の型でディスパッチします:

@example
>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Strength in numbers, eh? 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam
>>> fun(None)
Nothing.
>>> fun(1.23)
0.615
@end example

特定の型について登録された実装が存在しない場合、その型のメソッド解決順序が、汎用の実装をさらに検索するために使用されます。@code{@@singledispatch} でデコレートされた元の関数は基底の @ref{c7e,,object} 型に登録されます。これは、他によりよい実装が見つからないことを意味します。

抽象基底クラス (@ref{13ce,,abstract base class}) に対して実装が登録されると、基底クラスの仮想サブクラスに対してもその実装がディスパッチされます:

@example
>>> from collections.abc import Mapping
>>> @@fun.register
... def _(arg: Mapping, verbose=False):
...     if verbose:
...         print("Keys & Values")
...     for key, value in arg.items():
...         print(key, "=>", value)
...
>>> fun(@{"a": "b"@})
a => b
@end example

指定された型に対して、汎用関数がどの実装を選択するかを確認するには、@code{dispatch()} 属性を使用します:

@example
>>> fun.dispatch(float)
<function fun_num at 0x1035a2840>
>>> fun.dispatch(dict)    # note: default implementation
<function fun at 0x103fe0000>
@end example

登録されたすべての実装にアクセスするには、読み出し専用の @code{registry} 属性を使用します:

@example
>>> fun.registry.keys()
dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
          <class 'decimal.Decimal'>, <class 'list'>,
          <class 'float'>])
>>> fun.registry[float]
<function fun_num at 0x1035a2840>
>>> fun.registry[object]
<function fun at 0x103fe0000>
@end example


Added in version 3.4.



バージョン 3.7 で変更: The @ref{2bb2,,register()} attribute now supports using type annotations.



バージョン 3.11 で変更: The @ref{2bb2,,register()} attribute now supports
@ref{2a8,,typing.Union} as a type annotation.

@end deffn

@geindex singledispatchmethod (functools のクラス)
@anchor{library/functools functools singledispatchmethod}@anchor{be5}
@deffn {クラス} functools.singledispatchmethod (func)

メソッドを @ref{be3,,シングルディスパッチ} @ref{be4,,ジェネリック関数} に変換します。

To define a generic method, decorate it with the @code{@@singledispatchmethod}
decorator. When defining a method using @code{@@singledispatchmethod}, note
that the dispatch happens on the type of the first non-`self' or non-`cls'
argument:

@example
class Negator:
    @@singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @@neg.register
    def _(self, arg: int):
        return -arg

    @@neg.register
    def _(self, arg: bool):
        return not arg
@end example

@code{@@singledispatchmethod} supports nesting with other decorators such as
@ref{48e,,@@classmethod}. Note that to allow for
@code{dispatcher.register}, @code{singledispatchmethod} must be the `outer most'
decorator. Here is the @code{Negator} class with the @code{neg} methods bound to
the class, rather than an instance of the class:

@example
class Negator:
    @@singledispatchmethod
    @@classmethod
    def neg(cls, arg):
        raise NotImplementedError("Cannot negate a")

    @@neg.register
    @@classmethod
    def _(cls, arg: int):
        return -arg

    @@neg.register
    @@classmethod
    def _(cls, arg: bool):
        return not arg
@end example

The same pattern can be used for other similar decorators:
@ref{453,,@@staticmethod}, @ref{1297,,@@~abc.abstractmethod}, and others.


Added in version 3.8.

@end deffn

@geindex update_wrapper() (functools モジュール)
@anchor{library/functools functools update_wrapper}@anchor{1223}
@deffn {の関数} functools.update_wrapper (wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Update a `wrapper' function to look like the `wrapped' function. The optional
arguments are tuples to specify which attributes of the original function are
assigned directly to the matching attributes on the wrapper function and which
attributes of the wrapper function are updated with the corresponding attributes
from the original function. The default values for these arguments are the
module level constants @code{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper
function's @ref{234a,,__module__}, @ref{14ec,,__name__},
@ref{2349,,__qualname__}, @ref{13f0,,__annotations__},
@ref{234d,,__type_params__}, and @ref{13f1,,__doc__}, the
documentation string) and @code{WRAPPER_UPDATES} (which updates the wrapper
function's @ref{14ea,,__dict__}, i.e. the instance dictionary).

内観や別の目的 (例えば、 @ref{be2,,lru_cache()} のようなキャッシュするデコレータの回避) のために元の関数にアクセスできるように、この関数はラップされている関数を参照するラッパーに自動的に @code{__wrapped__} 属性を追加します。

この関数は主に関数を包んでラッパーを返す @ref{93a,,デコレータ} 関数の中で使われるよう意図されています。もしラッパー関数がアップデートされないとすると、返される関数のメタデータは元の関数の定義ではなくラッパー関数の定義を反映してしまい、これは通常あまり有益ではありません。

@ref{1223,,update_wrapper()} は、関数以外の呼び出し可能オブジェクトにも使えます。 `assigned' または `updated' で指名され、ラップされるオブジェクトに存在しない属性は、すべて無視されます (すなわち、ラッパー関数にそれらの属性を設定しようとは試みられません)。しかし、 `updated' で指名された属性がラッパー関数自身に存在しないなら @ref{5f0,,AttributeError} が送出されます。


バージョン 3.2 で変更: The @code{__wrapped__} attribute is now automatically added.
The @ref{13f0,,__annotations__} attribute is now copied by default.
Missing attributes no longer trigger an @ref{5f0,,AttributeError}.



バージョン 3.4 で変更: ラップされた関数が @code{__wrapped__} を定義していない場合でも、 @code{__wrapped__} が常にラップされた関数を参照するようになりました。(bpo-17482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17482} を参照)



バージョン 3.12 で変更: The @ref{234d,,__type_params__} attribute is now copied by default.

@end deffn

@geindex wraps() (functools モジュール)
@anchor{library/functools functools wraps}@anchor{115f}
@deffn {の関数} @@functools.wraps (wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

これはラッパー関数を定義するときに @ref{1223,,update_wrapper()} を関数デコレータとして呼び出す便宜関数です。これは @code{partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)} と等価です。例えば:

@example
>>> from functools import wraps
>>> def my_decorator(f):
...     @@wraps(f)
...     def wrapper(*args, **kwds):
...         print('Calling decorated function')
...         return f(*args, **kwds)
...     return wrapper
...
>>> @@my_decorator
... def example():
...     """Docstring"""
...     print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
@end example

Without the use of this decorator factory, the name of the example function
would have been @code{'wrapper'}, and the docstring of the original @code{example()}
would have been lost.
@end deffn

@menu
* partial オブジェクト:: 

@end menu

@node partial オブジェクト,,,functools --- 高階関数と呼び出し可能オブジェクトの操作
@anchor{library/functools id1}@anchor{2bb4}@anchor{library/functools partial-objects}@anchor{219}
@subsubsection @code{partial} オブジェクト


@ref{217,,partial} オブジェクトは、 @ref{217,,partial()} 関数によって作られる呼び出し可能オブジェクトです。オブジェクトには読み出し専用の属性が三つあります:

@geindex func (functools.partial の属性)
@anchor{library/functools functools partial func}@anchor{2bb5}
@deffn {の属性} partial.func

呼び出し可能オブジェクトまたは関数です。 @ref{217,,partial} オブジェクトの呼び出しは新しい引数とキーワードと共に @ref{2bb5,,func} に転送されます。
@end deffn

@geindex args (functools.partial の属性)
@anchor{library/functools functools partial args}@anchor{2bb6}
@deffn {の属性} partial.args

最左の位置引数で、 @ref{217,,partial} オブジェクトの呼び出し時にその呼び出しの際の位置引数の前に追加されます。
@end deffn

@geindex keywords (functools.partial の属性)
@anchor{library/functools functools partial keywords}@anchor{2bb7}
@deffn {の属性} partial.keywords

@ref{217,,partial} オブジェクトの呼び出し時に渡されるキーワード引数です。
@end deffn

@ref{217,,partial} objects are like @ref{59c,,function objects} in that they are
callable, weak referenceable, and can have attributes.  There are some important
differences.  For instance, the @ref{1272,,__name__} and @ref{b21,,__doc__} attributes
are not created automatically.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node operator --- 関数形式の標準演算子,,functools --- 高階関数と呼び出し可能オブジェクトの操作,関数型プログラミング用モジュール
@anchor{library/operator doc}@anchor{2bb8}@anchor{library/operator module-operator}@anchor{a3}@anchor{library/operator operator-standard-operators-as-functions}@anchor{2bb9}@anchor{library/operator translation-repo}@anchor{2bba}
@subsection @code{operator} --- 関数形式の標準演算子


@geindex module; operator

`ソースコード:' Lib/operator.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/operator.py}

@c import operator
@c from operator import itemgetter, iadd


__________________________________________________________________


The @code{operator} module exports a set of efficient functions corresponding to
the intrinsic operators of Python.  For example, @code{operator.add(x, y)} is
equivalent to the expression @code{x+y}. Many function names are those used for
special methods, without the double underscores.  For backward compatibility,
many of these have a variant with the double underscores kept. The variants
without the double underscores are preferred for clarity.

これらの関数は、オブジェクト比較、論理演算、数学演算、シーケンス演算をするものに分類されます。

オブジェクト比較関数は全てのオブジェクトで有効で、関数の名前はサポートする拡張比較演算子からとられています:

@geindex lt() (operator モジュール)
@geindex le() (operator モジュール)
@geindex eq() (operator モジュール)
@geindex ne() (operator モジュール)
@geindex ge() (operator モジュール)
@geindex gt() (operator モジュール)
@geindex __lt__() (operator モジュール)
@geindex __le__() (operator モジュール)
@geindex __eq__() (operator モジュール)
@geindex __ne__() (operator モジュール)
@geindex __ge__() (operator モジュール)
@geindex __gt__() (operator モジュール)
@anchor{library/operator operator lt}@anchor{2bbb}
@deffn {の関数} operator.lt (a, b)
@anchor{library/operator operator le}@anchor{2bbc}
@deffnx {の関数} operator.le (a, b)
@anchor{library/operator operator eq}@anchor{2bbd}
@deffnx {の関数} operator.eq (a, b)
@anchor{library/operator operator ne}@anchor{2bbe}
@deffnx {の関数} operator.ne (a, b)
@anchor{library/operator operator ge}@anchor{2bbf}
@deffnx {の関数} operator.ge (a, b)
@anchor{library/operator operator gt}@anchor{2bc0}
@deffnx {の関数} operator.gt (a, b)
@anchor{library/operator operator __lt__}@anchor{2bc1}
@deffnx {の関数} operator.__lt__ (a, b)
@anchor{library/operator operator __le__}@anchor{2bc2}
@deffnx {の関数} operator.__le__ (a, b)
@anchor{library/operator operator __eq__}@anchor{2bc3}
@deffnx {の関数} operator.__eq__ (a, b)
@anchor{library/operator operator __ne__}@anchor{2bc4}
@deffnx {の関数} operator.__ne__ (a, b)
@anchor{library/operator operator __ge__}@anchor{2bc5}
@deffnx {の関数} operator.__ge__ (a, b)
@anchor{library/operator operator __gt__}@anchor{2bc6}
@deffnx {の関数} operator.__gt__ (a, b)

`a' と `b' の "拡張比較 (rich comparisons)" を行います。具体的には、 @code{lt(a, b)} は @code{a < b} 、 @code{le(a, b)} は @code{a <= b} 、 @code{eq(a, b)} は @code{a == b} 、 @code{ne(a, b)} は @code{a != b} 、 @code{gt(a, b)} は @code{a > b} 、そして @code{ge(a, b)} は @code{a >= b} と等価です。これらの関数はどのような値を返してもよく、ブール値として解釈できてもできなくてもかまいません。拡張比較の詳細については @ref{24d0,,比較} を参照してください。
@end deffn

論理演算もまた全てのオブジェクトに対して適用でき、真理値判定、同一性判定およびブール演算をサポートします:

@geindex not_() (operator モジュール)
@geindex __not__() (operator モジュール)
@anchor{library/operator operator not_}@anchor{2bc7}
@deffn {の関数} operator.not_ (obj)
@anchor{library/operator operator __not__}@anchor{2bc8}
@deffnx {の関数} operator.__not__ (obj)

@ref{24da,,not} `obj' の結果を返します。(オブジェクトインスタンスには @code{__not__()} メソッドは無いので注意してください; インタープリターコアがこの演算を定義しているだけです。結果は @ref{14ed,,__bool__()} および @ref{178f,,__len__()} メソッドに影響されます。)
@end deffn

@geindex truth() (operator モジュール)
@anchor{library/operator operator truth}@anchor{2bc9}
@deffn {の関数} operator.truth (obj)

`obj' が真の場合 @ref{e07,,True}  を返し、そうでない場合 @ref{d2b,,False} を返します。この関数は @ref{3c3,,bool} のコンストラクタ呼び出しと同等です。
@end deffn

@geindex is_() (operator モジュール)
@anchor{library/operator operator is_}@anchor{2bca}
@deffn {の関数} operator.is_ (a, b)

@code{a is b} を返します。オブジェクトの同一性を判定します。
@end deffn

@geindex is_not() (operator モジュール)
@anchor{library/operator operator is_not}@anchor{2bcb}
@deffn {の関数} operator.is_not (a, b)

@code{a is not b} を返します。オブジェクトの同一性を判定します。
@end deffn

@geindex is_none() (operator モジュール)
@anchor{library/operator operator is_none}@anchor{255}
@deffn {の関数} operator.is_none (a)

Return @code{a is None}.  Tests object identity.


Added in version 3.14.

@end deffn

@geindex is_not_none() (operator モジュール)
@anchor{library/operator operator is_not_none}@anchor{256}
@deffn {の関数} operator.is_not_none (a)

Return @code{a is not None}.  Tests object identity.


Added in version 3.14.

@end deffn

演算子で最も多いのは数学演算およびビット単位の演算です:

@geindex abs() (operator モジュール)
@geindex __abs__() (operator モジュール)
@anchor{library/operator operator abs}@anchor{2bcc}
@deffn {の関数} operator.abs (obj)
@anchor{library/operator operator __abs__}@anchor{2bcd}
@deffnx {の関数} operator.__abs__ (obj)

`obj' の絶対値を返します。
@end deffn

@geindex add() (operator モジュール)
@geindex __add__() (operator モジュール)
@anchor{library/operator operator add}@anchor{2bce}
@deffn {の関数} operator.add (a, b)
@anchor{library/operator operator __add__}@anchor{2bcf}
@deffnx {の関数} operator.__add__ (a, b)

数値 `a' および `b' について @code{a + b} を返します。
@end deffn

@geindex and_() (operator モジュール)
@geindex __and__() (operator モジュール)
@anchor{library/operator operator and_}@anchor{2bd0}
@deffn {の関数} operator.and_ (a, b)
@anchor{library/operator operator __and__}@anchor{2bd1}
@deffnx {の関数} operator.__and__ (a, b)

`a' と `b' のビット単位論理積を返します。
@end deffn

@geindex floordiv() (operator モジュール)
@geindex __floordiv__() (operator モジュール)
@anchor{library/operator operator floordiv}@anchor{2bd2}
@deffn {の関数} operator.floordiv (a, b)
@anchor{library/operator operator __floordiv__}@anchor{2bd3}
@deffnx {の関数} operator.__floordiv__ (a, b)

@code{a // b} を返します。
@end deffn

@geindex index() (operator モジュール)
@geindex __index__() (operator モジュール)
@anchor{library/operator operator index}@anchor{1cd2}
@deffn {の関数} operator.index (a)
@anchor{library/operator operator __index__}@anchor{2bd4}
@deffnx {の関数} operator.__index__ (a)

整数に変換された `a' を返します。@code{a.__index__()} と同等です。


バージョン 3.10 で変更: 結果は常に厳密な @ref{19b,,int} 型です。
以前は、結果は @code{int} のサブクラスのインスタンスのこともありました。

@end deffn

@geindex inv() (operator モジュール)
@geindex invert() (operator モジュール)
@geindex __inv__() (operator モジュール)
@geindex __invert__() (operator モジュール)
@anchor{library/operator operator inv}@anchor{2bd5}
@deffn {の関数} operator.inv (obj)
@anchor{library/operator operator invert}@anchor{2bd6}
@deffnx {の関数} operator.invert (obj)
@anchor{library/operator operator __inv__}@anchor{2bd7}
@deffnx {の関数} operator.__inv__ (obj)
@anchor{library/operator operator __invert__}@anchor{2bd8}
@deffnx {の関数} operator.__invert__ (obj)

`obj' のビット単位反転を返します。@code{~obj} と同じです。
@end deffn

@geindex lshift() (operator モジュール)
@geindex __lshift__() (operator モジュール)
@anchor{library/operator operator lshift}@anchor{2bd9}
@deffn {の関数} operator.lshift (a, b)
@anchor{library/operator operator __lshift__}@anchor{2bda}
@deffnx {の関数} operator.__lshift__ (a, b)

`a' の `b' ビット左シフトを返します。
@end deffn

@geindex mod() (operator モジュール)
@geindex __mod__() (operator モジュール)
@anchor{library/operator operator mod}@anchor{2bdb}
@deffn {の関数} operator.mod (a, b)
@anchor{library/operator operator __mod__}@anchor{2bdc}
@deffnx {の関数} operator.__mod__ (a, b)

@code{a % b} を返します。
@end deffn

@geindex mul() (operator モジュール)
@geindex __mul__() (operator モジュール)
@anchor{library/operator operator mul}@anchor{2baa}
@deffn {の関数} operator.mul (a, b)
@anchor{library/operator operator __mul__}@anchor{2bdd}
@deffnx {の関数} operator.__mul__ (a, b)

数値 `a' および `b' について @code{a * b} を返します。
@end deffn

@geindex matmul() (operator モジュール)
@geindex __matmul__() (operator モジュール)
@anchor{library/operator operator matmul}@anchor{1035}
@deffn {の関数} operator.matmul (a, b)
@anchor{library/operator operator __matmul__}@anchor{2bde}
@deffnx {の関数} operator.__matmul__ (a, b)

@code{a @@ b} を返します。


Added in version 3.5.

@end deffn

@geindex neg() (operator モジュール)
@geindex __neg__() (operator モジュール)
@anchor{library/operator operator neg}@anchor{2bdf}
@deffn {の関数} operator.neg (obj)
@anchor{library/operator operator __neg__}@anchor{2be0}
@deffnx {の関数} operator.__neg__ (obj)

負の `obj' (@code{-obj}) を返します。
@end deffn

@geindex or_() (operator モジュール)
@geindex __or__() (operator モジュール)
@anchor{library/operator operator or_}@anchor{2be1}
@deffn {の関数} operator.or_ (a, b)
@anchor{library/operator operator __or__}@anchor{2be2}
@deffnx {の関数} operator.__or__ (a, b)

`a' と `b' のビット単位論理和を返します。
@end deffn

@geindex pos() (operator モジュール)
@geindex __pos__() (operator モジュール)
@anchor{library/operator operator pos}@anchor{2be3}
@deffn {の関数} operator.pos (obj)
@anchor{library/operator operator __pos__}@anchor{2be4}
@deffnx {の関数} operator.__pos__ (obj)

正の `obj' (@code{+obj}) を返します。
@end deffn

@geindex pow() (operator モジュール)
@geindex __pow__() (operator モジュール)
@anchor{library/operator operator pow}@anchor{2be5}
@deffn {の関数} operator.pow (a, b)
@anchor{library/operator operator __pow__}@anchor{2be6}
@deffnx {の関数} operator.__pow__ (a, b)

数値 `a' および `b' について @code{a ** b} を返します。
@end deffn

@geindex rshift() (operator モジュール)
@geindex __rshift__() (operator モジュール)
@anchor{library/operator operator rshift}@anchor{2be7}
@deffn {の関数} operator.rshift (a, b)
@anchor{library/operator operator __rshift__}@anchor{2be8}
@deffnx {の関数} operator.__rshift__ (a, b)

`a' の `b' ビット右シフトを返します。
@end deffn

@geindex sub() (operator モジュール)
@geindex __sub__() (operator モジュール)
@anchor{library/operator operator sub}@anchor{2be9}
@deffn {の関数} operator.sub (a, b)
@anchor{library/operator operator __sub__}@anchor{2bea}
@deffnx {の関数} operator.__sub__ (a, b)

@code{a - b} を返します。
@end deffn

@geindex truediv() (operator モジュール)
@geindex __truediv__() (operator モジュール)
@anchor{library/operator operator truediv}@anchor{2beb}
@deffn {の関数} operator.truediv (a, b)
@anchor{library/operator operator __truediv__}@anchor{2bec}
@deffnx {の関数} operator.__truediv__ (a, b)

2/3 が 0 ではなく 0.66 となるような @code{a / b}  を返します。
"真の" 除算としても知られています。
@end deffn

@geindex xor() (operator モジュール)
@geindex __xor__() (operator モジュール)
@anchor{library/operator operator xor}@anchor{2bed}
@deffn {の関数} operator.xor (a, b)
@anchor{library/operator operator __xor__}@anchor{2bee}
@deffnx {の関数} operator.__xor__ (a, b)

`a' および `b' のビット単位排他的論理和を返します。
@end deffn

シーケンスを扱う演算子（いくつかの演算子はマッピングも扱います）には以下のようなものがあります:

@geindex concat() (operator モジュール)
@geindex __concat__() (operator モジュール)
@anchor{library/operator operator concat}@anchor{2bef}
@deffn {の関数} operator.concat (a, b)
@anchor{library/operator operator __concat__}@anchor{2bf0}
@deffnx {の関数} operator.__concat__ (a, b)

シーケンス `a' および `b' について @code{a + b} を返します。
@end deffn

@geindex contains() (operator モジュール)
@geindex __contains__() (operator モジュール)
@anchor{library/operator operator contains}@anchor{ad7}
@deffn {の関数} operator.contains (a, b)
@anchor{library/operator operator __contains__}@anchor{2bf1}
@deffnx {の関数} operator.__contains__ (a, b)

@code{b in a} の判定結果を返します。被演算子が左右反転しているので注意してください。
@end deffn

@geindex countOf() (operator モジュール)
@anchor{library/operator operator countOf}@anchor{ad9}
@deffn {の関数} operator.countOf (a, b)

`a' の中に `b' が出現する回数を返します。
@end deffn

@geindex delitem() (operator モジュール)
@geindex __delitem__() (operator モジュール)
@anchor{library/operator operator delitem}@anchor{2bf2}
@deffn {の関数} operator.delitem (a, b)
@anchor{library/operator operator __delitem__}@anchor{2bf3}
@deffnx {の関数} operator.__delitem__ (a, b)

`a' でインデクスが `b' の値を削除します。
@end deffn

@geindex getitem() (operator モジュール)
@geindex __getitem__() (operator モジュール)
@anchor{library/operator operator getitem}@anchor{2bf4}
@deffn {の関数} operator.getitem (a, b)
@anchor{library/operator operator __getitem__}@anchor{2bf5}
@deffnx {の関数} operator.__getitem__ (a, b)

`a' でインデクスが `b' の値を返します。
@end deffn

@geindex indexOf() (operator モジュール)
@anchor{library/operator operator indexOf}@anchor{ad8}
@deffn {の関数} operator.indexOf (a, b)

`a' で最初に `b' が出現する場所のインデクスを返します。
@end deffn

@geindex setitem() (operator モジュール)
@geindex __setitem__() (operator モジュール)
@anchor{library/operator operator setitem}@anchor{2bf6}
@deffn {の関数} operator.setitem (a, b, c)
@anchor{library/operator operator __setitem__}@anchor{2bf7}
@deffnx {の関数} operator.__setitem__ (a, b, c)

`a' でインデクスが `b' の値を `c' に設定します。
@end deffn

@geindex length_hint() (operator モジュール)
@anchor{library/operator operator length_hint}@anchor{116f}
@deffn {の関数} operator.length_hint (obj, default=0)

オブジェクト `obj' の概算の長さを返します。最初に実際の長さを、次に @ref{110f,,object.__length_hint__()} を使って概算の長さを、そして最後にデフォルトの値を返そうとします。


Added in version 3.4.

@end deffn

次の操作は呼び出し可能オブジェクト (callable) で動作します。

@geindex call() (operator モジュール)
@geindex __call__() (operator モジュール)
@anchor{library/operator operator call}@anchor{1c22}
@deffn {の関数} operator.call (obj, /, *args, **kwargs)
@anchor{library/operator operator __call__}@anchor{2bf8}
@deffnx {の関数} operator.__call__ (obj, /, *args, **kwargs)

@code{obj(*args, **kwargs)} を返します。


Added in version 3.11.

@end deffn

The @code{operator} module also defines tools for generalized attribute and item
lookups.  These are useful for making fast field extractors as arguments for
@ref{19f,,map()}, @ref{dc7,,sorted()}, @ref{2ba5,,itertools.groupby()}, or other functions that
expect a function argument.

@geindex attrgetter() (operator モジュール)
@anchor{library/operator operator attrgetter}@anchor{1033}
@deffn {の関数} operator.attrgetter (attr)

@deffnx {の関数} operator.attrgetter (*attrs)

演算対象から `attr' を取得する呼び出し可能なオブジェクトを返します。二つ以上の属性を要求された場合には、属性のタプルを返します。属性名はドットを含むこともできます。例えば:


@itemize *

@item 
@code{f = attrgetter('name')} とした後で、@code{f(b)} を呼び出すと @code{b.name} を返します。

@item 
@code{f = attrgetter('name', 'date')} とした後で、@code{f(b)} を呼び出すと @code{(b.name, b.date)} を返します。

@item 
@code{f = attrgetter('name.first', 'name.last')} とした後で、@code{f(b)} を呼び出すと @code{(b.name.first, b.name.last)} を返します。
@end itemize

次と等価です:

@example
def attrgetter(*items):
    if any(not isinstance(item, str) for item in items):
        raise TypeError('attribute name must be a string')
    if len(items) == 1:
        attr = items[0]
        def g(obj):
            return resolve_attr(obj, attr)
    else:
        def g(obj):
            return tuple(resolve_attr(obj, attr) for attr in items)
    return g

def resolve_attr(obj, attr):
    for name in attr.split("."):
        obj = getattr(obj, name)
    return obj
@end example
@end deffn

@geindex itemgetter() (operator モジュール)
@anchor{library/operator operator itemgetter}@anchor{c57}
@deffn {の関数} operator.itemgetter (item)

@deffnx {の関数} operator.itemgetter (*items)

演算対象からその @ref{588,,__getitem__()} メソッドを使って `item' を取得する呼び出し可能なオブジェクトを返します。 二つ以上のアイテムを要求された場合には、アイテムのタプルを返します。例えば:


@itemize *

@item 
@code{f = itemgetter(2)} とした後で、@code{f(r)} を呼び出すと @code{r[2]} を返します。

@item 
@code{g = itemgetter(2, 5, 3)} とした後で、@code{g(r)} を呼び出すと @code{(r[2], r[5], r[3])} を返します。
@end itemize

次と等価です:

@example
def itemgetter(*items):
    if len(items) == 1:
        item = items[0]
        def g(obj):
            return obj[item]
    else:
        def g(obj):
            return tuple(obj[item] for item in items)
    return g
@end example

アイテムは被演算子の @ref{588,,__getitem__()} メソッドが受け付けるどんな型でも構いません。辞書ならば任意の @ref{824,,ハッシュ可能} な値を受け付けます。リスト、タプル、文字列などはインデックスかスライスを受け付けます:

@example
>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1, 3, 5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2, None))('ABCDEFG')
'CDEFG'
>>> soldier = dict(rank='captain', name='dotterbart')
>>> itemgetter('rank')(soldier)
'captain'
@end example

@ref{c57,,itemgetter()} を使って特定のフィールドをタプルレコードから取り出す例:

@example
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> list(map(getcount, inventory))
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
@end example
@end deffn

@geindex methodcaller() (operator モジュール)
@anchor{library/operator operator methodcaller}@anchor{1034}
@deffn {の関数} operator.methodcaller (name, /, *args, **kwargs)

引数の `name' メソッドを呼び出す呼び出し可能オブジェクトを返します。追加の引数および/またはキーワード引数が与えられると、これらもそのメソッドに引き渡されます。例えば:


@itemize *

@item 
@code{f = methodcaller('name')} とした後で、@code{f(b)} を呼び出すと @code{b.name()} を返します。

@item 
@code{f = methodcaller('name', 'foo', bar=1)} とした後で、@code{f(b)} を呼び出すと @code{b.name('foo', bar=1)} を返します。
@end itemize

次と等価です:

@example
def methodcaller(name, /, *args, **kwargs):
    def caller(obj):
        return getattr(obj, name)(*args, **kwargs)
    return caller
@end example
@end deffn

@menu
* 演算子から関数への対応表:: 
* インプレース (in-place) 演算子: インプレース in-place 演算子. 

@end menu

@node 演算子から関数への対応表,インプレース in-place 演算子,,operator --- 関数形式の標準演算子
@anchor{library/operator mapping-operators-to-functions}@anchor{2bf9}@anchor{library/operator operator-map}@anchor{2bfa}
@subsubsection 演算子から関数への対応表


This table shows how abstract operations correspond to operator symbols in the
Python syntax and the functions in the @code{operator} module.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

演算

@tab

操作

@tab

関数

@item

加算

@tab

@code{a + b}

@tab

@code{add(a, b)}

@item

結合

@tab

@code{seq1 + seq2}

@tab

@code{concat(seq1, seq2)}

@item

包含判定

@tab

@code{obj in seq}

@tab

@code{contains(seq, obj)}

@item

除算

@tab

@code{a / b}

@tab

@code{truediv(a, b)}

@item

除算

@tab

@code{a // b}

@tab

@code{floordiv(a, b)}

@item

ビット単位論理積

@tab

@code{a & b}

@tab

@code{and_(a, b)}

@item

ビット単位排他的論理和

@tab

@code{a ^ b}

@tab

@code{xor(a, b)}

@item

ビット単位反転

@tab

@code{~ a}

@tab

@code{invert(a)}

@item

ビット単位論理和

@tab

@code{a | b}

@tab

@code{or_(a, b)}

@item

冪乗

@tab

@code{a ** b}

@tab

@code{pow(a, b)}

@item

同一性

@tab

@code{a is b}

@tab

@code{is_(a, b)}

@item

同一性

@tab

@code{a is not b}

@tab

@code{is_not(a, b)}

@item

同一性

@tab

@code{a is None}

@tab

@code{is_none(a)}

@item

同一性

@tab

@code{a is not None}

@tab

@code{is_not_none(a)}

@item

インデクス指定の代入

@tab

@code{obj[k] = v}

@tab

@code{setitem(obj, k, v)}

@item

インデクス指定の削除

@tab

@code{del obj[k]}

@tab

@code{delitem(obj, k)}

@item

インデクス指定

@tab

@code{obj[k]}

@tab

@code{getitem(obj, k)}

@item

左シフト

@tab

@code{a << b}

@tab

@code{lshift(a, b)}

@item

剰余

@tab

@code{a % b}

@tab

@code{mod(a, b)}

@item

乗算

@tab

@code{a * b}

@tab

@code{mul(a, b)}

@item

行列の乗算

@tab

@code{a @@ b}

@tab

@code{matmul(a, b)}

@item

(算術) 負

@tab

@code{- a}

@tab

@code{neg(a)}

@item

(論理) 否

@tab

@code{not a}

@tab

@code{not_(a)}

@item

正

@tab

@code{+ a}

@tab

@code{pos(a)}

@item

右シフト

@tab

@code{a >> b}

@tab

@code{rshift(a, b)}

@item

スライス指定の代入

@tab

@code{seq[i:j] = values}

@tab

@code{setitem(seq, slice(i, j), values)}

@item

スライス指定の削除

@tab

@code{del seq[i:j]}

@tab

@code{delitem(seq, slice(i, j))}

@item

スライス指定

@tab

@code{seq[i:j]}

@tab

@code{getitem(seq, slice(i, j))}

@item

文字列書式化

@tab

@code{s % obj}

@tab

@code{mod(s, obj)}

@item

減算

@tab

@code{a - b}

@tab

@code{sub(a, b)}

@item

真理値判定

@tab

@code{obj}

@tab

@code{truth(obj)}

@item

順序付け

@tab

@code{a < b}

@tab

@code{lt(a, b)}

@item

順序付け

@tab

@code{a <= b}

@tab

@code{le(a, b)}

@item

等価性

@tab

@code{a == b}

@tab

@code{eq(a, b)}

@item

不等性

@tab

@code{a != b}

@tab

@code{ne(a, b)}

@item

順序付け

@tab

@code{a >= b}

@tab

@code{ge(a, b)}

@item

順序付け

@tab

@code{a > b}

@tab

@code{gt(a, b)}

@end multitable


@node インプレース in-place 演算子,,演算子から関数への対応表,operator --- 関数形式の標準演算子
@anchor{library/operator in-place-operators}@anchor{2bfb}
@subsubsection インプレース (in-place) 演算子


多くの演算に「インプレース」版があります。 以下の関数はそうした演算子の通常の文法に比べてより素朴な呼び出し方を提供します。たとえば、 @ref{2bfc,,文} @code{x += y} は @code{x = operator.iadd(x, y)} と等価です。別の言い方をすると、 @code{z = operator.iadd(x, y)} は複合文 @code{z = x; z += y} と等価です。

なお、これらの例では、インプレースメソッドが呼び出されたとき、計算と代入は二段階に分けて行われます。以下に挙げるインプレース関数は、インプレースメソッドを呼び出してその第一段階だけを行います。第二段階の代入は扱われません。

文字列、数、タプルのようなイミュータブルなターゲットでは、更新された値が計算されますが、入力変数に代入し返されはしません。

@example
>>> a = 'hello'
>>> iadd(a, ' world')
'hello world'
>>> a
'hello'
@end example

リストや辞書のようなミュータブルなターゲットでは、インプレースメソッドは更新を行うので、その後に代入をする必要はありません。

@example
>>> s = ['h', 'e', 'l', 'l', 'o']
>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> s
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
@end example

@geindex iadd() (operator モジュール)
@geindex __iadd__() (operator モジュール)
@anchor{library/operator operator iadd}@anchor{2bfd}
@deffn {の関数} operator.iadd (a, b)
@anchor{library/operator operator __iadd__}@anchor{2bfe}
@deffnx {の関数} operator.__iadd__ (a, b)

@code{a = iadd(a, b)} は @code{a += b} と等価です。
@end deffn

@geindex iand() (operator モジュール)
@geindex __iand__() (operator モジュール)
@anchor{library/operator operator iand}@anchor{2bff}
@deffn {の関数} operator.iand (a, b)
@anchor{library/operator operator __iand__}@anchor{2c00}
@deffnx {の関数} operator.__iand__ (a, b)

@code{a = iand(a, b)} は @code{a &= b} と等価です。
@end deffn

@geindex iconcat() (operator モジュール)
@geindex __iconcat__() (operator モジュール)
@anchor{library/operator operator iconcat}@anchor{2c01}
@deffn {の関数} operator.iconcat (a, b)
@anchor{library/operator operator __iconcat__}@anchor{2c02}
@deffnx {の関数} operator.__iconcat__ (a, b)

@code{a = iconcat(a, b)} は二つのシーケンス `a' と `b' に対し @code{a += b} と等価です。
@end deffn

@geindex ifloordiv() (operator モジュール)
@geindex __ifloordiv__() (operator モジュール)
@anchor{library/operator operator ifloordiv}@anchor{2c03}
@deffn {の関数} operator.ifloordiv (a, b)
@anchor{library/operator operator __ifloordiv__}@anchor{2c04}
@deffnx {の関数} operator.__ifloordiv__ (a, b)

@code{a = ifloordiv(a, b)} は @code{a //= b} と等価です。
@end deffn

@geindex ilshift() (operator モジュール)
@geindex __ilshift__() (operator モジュール)
@anchor{library/operator operator ilshift}@anchor{2c05}
@deffn {の関数} operator.ilshift (a, b)
@anchor{library/operator operator __ilshift__}@anchor{2c06}
@deffnx {の関数} operator.__ilshift__ (a, b)

@code{a = ilshift(a, b)} は @code{a <<= b} と等価です。
@end deffn

@geindex imod() (operator モジュール)
@geindex __imod__() (operator モジュール)
@anchor{library/operator operator imod}@anchor{2c07}
@deffn {の関数} operator.imod (a, b)
@anchor{library/operator operator __imod__}@anchor{2c08}
@deffnx {の関数} operator.__imod__ (a, b)

@code{a = imod(a, b)} は @code{a %= b} と等価です。
@end deffn

@geindex imul() (operator モジュール)
@geindex __imul__() (operator モジュール)
@anchor{library/operator operator imul}@anchor{2c09}
@deffn {の関数} operator.imul (a, b)
@anchor{library/operator operator __imul__}@anchor{2c0a}
@deffnx {の関数} operator.__imul__ (a, b)

@code{a = imul(a, b)} は @code{a *= b} と等価です。
@end deffn

@geindex imatmul() (operator モジュール)
@geindex __imatmul__() (operator モジュール)
@anchor{library/operator operator imatmul}@anchor{1036}
@deffn {の関数} operator.imatmul (a, b)
@anchor{library/operator operator __imatmul__}@anchor{2c0b}
@deffnx {の関数} operator.__imatmul__ (a, b)

@code{a = imatmul(a, b)} は @code{a @@= b} と等価です。


Added in version 3.5.

@end deffn

@geindex ior() (operator モジュール)
@geindex __ior__() (operator モジュール)
@anchor{library/operator operator ior}@anchor{2c0c}
@deffn {の関数} operator.ior (a, b)
@anchor{library/operator operator __ior__}@anchor{2c0d}
@deffnx {の関数} operator.__ior__ (a, b)

@code{a = ior(a, b)} は @code{a |= b} と等価です。
@end deffn

@geindex ipow() (operator モジュール)
@geindex __ipow__() (operator モジュール)
@anchor{library/operator operator ipow}@anchor{2c0e}
@deffn {の関数} operator.ipow (a, b)
@anchor{library/operator operator __ipow__}@anchor{2c0f}
@deffnx {の関数} operator.__ipow__ (a, b)

@code{a = ipow(a, b)} は @code{a **= b} と等価です。
@end deffn

@geindex irshift() (operator モジュール)
@geindex __irshift__() (operator モジュール)
@anchor{library/operator operator irshift}@anchor{2c10}
@deffn {の関数} operator.irshift (a, b)
@anchor{library/operator operator __irshift__}@anchor{2c11}
@deffnx {の関数} operator.__irshift__ (a, b)

@code{a = irshift(a, b)} は @code{a >>= b} と等価です。
@end deffn

@geindex isub() (operator モジュール)
@geindex __isub__() (operator モジュール)
@anchor{library/operator operator isub}@anchor{2c12}
@deffn {の関数} operator.isub (a, b)
@anchor{library/operator operator __isub__}@anchor{2c13}
@deffnx {の関数} operator.__isub__ (a, b)

@code{a = isub(a, b)} は @code{a -= b} と等価です。
@end deffn

@geindex itruediv() (operator モジュール)
@geindex __itruediv__() (operator モジュール)
@anchor{library/operator operator itruediv}@anchor{2c14}
@deffn {の関数} operator.itruediv (a, b)
@anchor{library/operator operator __itruediv__}@anchor{2c15}
@deffnx {の関数} operator.__itruediv__ (a, b)

@code{a = itruediv(a, b)} は @code{a /= b} と等価です。
@end deffn

@geindex ixor() (operator モジュール)
@geindex __ixor__() (operator モジュール)
@anchor{library/operator operator ixor}@anchor{2c16}
@deffn {の関数} operator.ixor (a, b)
@anchor{library/operator operator __ixor__}@anchor{2c17}
@deffnx {の関数} operator.__ixor__ (a, b)

@code{a = ixor(a, b)} は @code{a ^= b} と等価です。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ファイルとディレクトリへのアクセス,データの永続化,関数型プログラミング用モジュール,Python 標準ライブラリ
@anchor{library/filesys doc}@anchor{2c18}@anchor{library/filesys file-and-directory-access}@anchor{2c19}@anchor{library/filesys filesys}@anchor{2c1a}@anchor{library/filesys translation-repo}@anchor{2c1b}
@section ファイルとディレクトリへのアクセス


この章で説明されるモジュールはディスクのファイルやディレクトリを扱います。たとえば、ファイルの属性を読むためのモジュール、ファイルパスを移植可能な方式で操作する、テンポラリファイルを作成するためのモジュールです。この章の完全な一覧は:

@menu
* pathlib: pathlib --- オブジェクト指向のファイルシステムパス. オブジェクト指向のファイルシステムパス
* os.path: os path --- 一般的なパス名操作. 一般的なパス名操作
* stat: stat --- stat の結果を解釈する. stat() の結果を解釈する
* filecmp: filecmp --- ファイルとディレクトリの比較. ファイルとディレクトリの比較
* tempfile: tempfile --- 一時ファイルやディレクトリの作成. 一時ファイルやディレクトリの作成
* glob: glob --- Unix 形式のパス名のパターン展開. Unix 形式のパス名のパターン展開
* fnmatch: fnmatch --- Unix のファイル名パターンマッチ. Unix のファイル名パターンマッチ
* linecache: linecache --- テキストラインへのランダムアクセス. テキストラインへのランダムアクセス
* shutil: shutil --- 高水準のファイル操作. 高水準のファイル操作

@end menu

@node pathlib --- オブジェクト指向のファイルシステムパス,os path --- 一般的なパス名操作,,ファイルとディレクトリへのアクセス
@anchor{library/pathlib doc}@anchor{2c1c}@anchor{library/pathlib module-pathlib}@anchor{a8}@anchor{library/pathlib pathlib-object-oriented-filesystem-paths}@anchor{2c1d}
@subsection @code{pathlib} --- オブジェクト指向のファイルシステムパス


@geindex module; pathlib


Added in version 3.4.


`ソースコード:' Lib/pathlib/@footnote{https://github.com/python/cpython/tree/3.14/Lib/pathlib/}

@geindex パス;操作


__________________________________________________________________


このモジュールはファイルシステムのパスを表すクラスを提供していて、様々なオペレーティングシステムについての適切な意味論をそれらのクラスに持たせています。
Path クラスは @ref{2c1e,,純粋パス} と @ref{2c1f,,具象パス} からなります。
純粋パスは I/O を伴わない純粋な計算操作を提供します。
具象パスは純粋パスを継承していますが、 I/O 操作も提供しています。

@image{python-figures/pathlib-inheritance,,,Inheritance diagram showing the classes available in pathlib. The most basic class is PurePath@comma{} which has three direct subclasses: PurePosixPath@comma{} PureWindowsPath@comma{} and Path. Further to these four classes@comma{} there are two classes that use multiple inheritance: PosixPath subclasses PurePosixPath and Path@comma{} and WindowsPath subclasses PureWindowsPath and Path.,png}

あなたが今までこのモジュールを使用したことがない場合や、タスクに適しているのがどのクラスかわからない場合は、 @ref{266,,Path} はきっとあなたに必要なものでしょう。
@ref{266,,Path} はコードが実行されているプラットフォーム用の @ref{2c1f,,具象パス} のインスタンスを作成します。

純粋パスは、以下のようないくつかの特殊なケースで有用です:


@enumerate 

@item 
Unix マシン上で Windows のパスを扱いたいとき (またはその逆)。Unix 上で実行しているときに @ref{2c20,,WindowsPath} のインスタンスを作成することはできませんが、@ref{1a75,,PureWindowsPath} なら可能になります。

@item 
実際に OS にアクセスすることなしにパスを操作するだけのコードを確認したいとき。この場合、純粋クラスのインスタンスを一つ作成すれば、それが OS にアクセスすることはないので便利です。
@end enumerate


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 428
PEP 428@footnote{https://peps.python.org/pep-0428/}: The pathlib module -- オブジェクト指向のファイルシステムパス。



@subsubheading 参考


文字列による低水準のパス操作の場合は @ref{a6,,os.path} も使用できます。


@menu
* 基本的な使い方: 基本的な使い方<2>. 
* 例外: 例外<6>. 
* 純粋パス:: 
* 具象パス:: 
* Pattern language:: 
* glob モジュールとの比較:: 
* os と os.path モジュールの比較: os と os path モジュールの比較. 
* プロトコル:: 

@end menu

@node 基本的な使い方<2>,例外<6>,,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib basic-use}@anchor{2c21}
@subsubsection 基本的な使い方


メインクラスをインポートします:

@example
>>> from pathlib import Path
@end example

サブディレクトリの一覧を取得します:

@example
>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]
@end example

このディレクトリツリー内の Python ソースファイルの一覧を取得します:

@example
>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]
@end example

ディレクトリツリー内を移動します:

@example
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
@end example

パスのプロパティを問い合わせます:

@example
>>> q.exists()
True
>>> q.is_dir()
False
@end example

ファイルを開きます:

@example
>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'
@end example

@node 例外<6>,純粋パス,基本的な使い方<2>,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib exceptions}@anchor{2c22}
@subsubsection 例外


@geindex UnsupportedOperation
@anchor{library/pathlib pathlib UnsupportedOperation}@anchor{533}
@deffn {例外} pathlib.UnsupportedOperation

@ref{36b,,NotImplementedError} を継承した例外です。パスオブジェクトがサポートしていない操作を行おうとした時に送出されます。


Added in version 3.13.

@end deffn

@node 純粋パス,具象パス,例外<6>,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib id1}@anchor{2c23}@anchor{library/pathlib pure-paths}@anchor{2c1e}
@subsubsection 純粋パス


純粋パスオブジェクトは実際にファイルシステムにアクセスしないパス操作処理を提供します。これらのクラスにアクセスするには 3 つの方法があり、それらを `フレーバー' と呼んでいます:

@geindex PurePath (pathlib のクラス)
@anchor{library/pathlib pathlib PurePath}@anchor{6cd}
@deffn {クラス} pathlib.PurePath (*pathsegments)

システムのパスのフレーバーを表すジェネリッククラスです (インスタンスを作成することで @ref{2c24,,PurePosixPath} または @ref{1a75,,PureWindowsPath} のどちらかが作成されます):

@example
>>> PurePath('setup.py')      # Running on a Unix machine
PurePosixPath('setup.py')
@end example

`pathsegments' の各要素は、パスの構成要素を表す文字列か、パスオブジェクトなどの、 @ref{e4b,,os.PathLike} インターフェースを実装するオブジェクトである必要があります。
@ref{e4b,,os.PathLike} インターフェースでは、 @ref{e4c,,__fspath__()} メソッドが文字列を返します:

@example
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')
@end example

`pathsegments' が空のとき、現在のディレクトリとみなされます:

@example
>>> PurePath()
PurePosixPath('.')
@end example

あるパス構成要素が絶対パスである場合、それより前の要素はすべて無視されます (@ref{19a9,,os.path.join()} と同様):

@example
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
@end example

Windowsの場合、ルート相対パス (例えば @code{r'\foo'}) があってもドライブ名はそのまま変わりません:

@example
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
@end example

単一スラッシュと等価な複数スラッシュやシングルドットは簡略化されますが、ダブルドット (@code{'..'}) や先頭に位置するダブルスラッシュ (@code{'//'}) は簡略化されません。
これは、様々な理由でパスの意味が簡略化した場合と異なってしまうからです (例: シンボリックリンク、UNCパス):

@example
>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> PurePath('//foo/bar')
PurePosixPath('//foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('foo/../bar')
@end example

(通常 @code{PurePosixPath('foo/../bar')} は @code{PurePosixPath('bar')} と等価になりますが、@code{foo} が他のディレクトリへのシンボリックリンクの場合は等価になりません)

純粋パスオブジェクトは @ref{e4b,,os.PathLike} インターフェースを実装しており、そのインターフェースを受理する箇所ならどこでも使用することができます。


バージョン 3.6 で変更: @ref{e4b,,os.PathLike} インターフェースがサポートされました。

@end deffn

@geindex PurePosixPath (pathlib のクラス)
@anchor{library/pathlib pathlib PurePosixPath}@anchor{2c24}
@deffn {クラス} pathlib.PurePosixPath (*pathsegments)

@ref{6cd,,PurePath} のサブクラスです。このパスフレーバーは非 Windows パスを表します:

@example
>>> PurePosixPath('/etc/hosts')
PurePosixPath('/etc/hosts')
@end example

`pathsegments' の指定は @ref{6cd,,PurePath} と同じです。
@end deffn

@geindex PureWindowsPath (pathlib のクラス)
@anchor{library/pathlib pathlib PureWindowsPath}@anchor{1a75}
@deffn {クラス} pathlib.PureWindowsPath (*pathsegments)

@ref{6cd,,PurePath} のサブクラスです。このパスフレーバー UNC paths@footnote{https://en.wikipedia.org/wiki/Path_(computing)#UNC} を含む Windows ファイルシステムパスを表します:

@example
>>> PureWindowsPath('c:/', 'Users', 'Ximénez')
PureWindowsPath('c:/Users/Ximénez')
>>> PureWindowsPath('//server/share/file')
PureWindowsPath('//server/share/file')
@end example

`pathsegments' の指定は @ref{6cd,,PurePath} と同じです。
@end deffn

これらクラスはあらゆるシステムコールを行わないため、起動しているシステムにかかわらずインスタンスを作成できます。

@menu
* 全般的な性質:: 
* 演算子:: 
* 個別の構成要素へのアクセス:: 
* メソッドとプロパティ:: 

@end menu

@node 全般的な性質,演算子,,純粋パス
@anchor{library/pathlib general-properties}@anchor{2c25}
@subsubsection 全般的な性質


パスオブジェクトはイミュータブルで @ref{824,,ハッシュ可能} です。同じフレーバーのパスオブジェクトは比較ならびに順序付け可能です。これらのプロパティは、フレーバーのケースフォールディング (訳注: 比較のために正規化すること、例えば全て大文字にする) のセマンティクスに従います。

@example
>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in @{ PureWindowsPath('foo') @}
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True
@end example

異なるフレーバーのパスオブジェクト同士の比較は等価になることはなく、順序付けもできません:

@example
>>> PureWindowsPath('foo') == PurePosixPath('foo')
False
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
@end example

@node 演算子,個別の構成要素へのアクセス,全般的な性質,純粋パス
@anchor{library/pathlib operators}@anchor{2c26}
@subsubsection 演算子


スラッシュ演算子を使って、 @ref{19a9,,os.path.join()} のように子パスを作成することができます。
スラッシュの右側が絶対パスである場合、左側のパスは無視されます。
Windows環境で、右側のパスがルート相対パス (例: @code{r'\foo'}) である場合、ドライブ名はリセットされません:

@example
>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')
>>> p / '/an_absolute_path'
PurePosixPath('/an_absolute_path')
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
@end example

@ref{e4b,,os.PathLike} を実装したオブジェクトが受理できる箇所ならどこでも、パスオブジェクトが使用できます:

@example
>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'
@end example

パスオブジェクトの文字列表現はそのシステム自身の Raw ファイルシステムパス (ネイティブの形式、例えば Windows では区切り文字がバックスラッシュ) になり、文字列としてファイルパスを取るあらゆる関数に渡すことができます:

@example
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'
@end example

同様に、パスオブジェクトを @ref{192,,bytes} で呼び出すと、Raw ファイルシステムパスを @ref{e4f,,os.fsencode()} でエンコードされたバイト列オブジェクトで返します:

@example
>>> bytes(p)
b'/etc'
@end example

@cartouche
@quotation 注釈 
@ref{192,,bytes} での呼び出しは Unix 上での使用のみ推奨します。Windows では Unicode 形式が標準的なファイルシステムパス表現になります。
@end quotation
@end cartouche

@node 個別の構成要素へのアクセス,メソッドとプロパティ,演算子,純粋パス
@anchor{library/pathlib accessing-individual-parts}@anchor{2c27}
@subsubsection 個別の構成要素へのアクセス


パスの個別の "構成要素" へアクセスするには、以下のプロパティを使用します:

@geindex parts (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath parts}@anchor{2c28}
@deffn {の属性} PurePath.parts

パスのさまざまな構成要素へのアクセス手段を提供するタプルになります:

@example
>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')
@end example

(ドライブ名とローカルルートは単一要素にまとめられます)
@end deffn

@node メソッドとプロパティ,,個別の構成要素へのアクセス,純粋パス
@anchor{library/pathlib methods-and-properties}@anchor{2c29}
@subsubsection メソッドとプロパティ


@c from pathlib import PurePath, PurePosixPath, PureWindowsPath

純粋パスは以下のメソッドとプロパティを提供します:

@geindex parser (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath parser}@anchor{536}
@deffn {の属性} PurePath.parser

低レベルのパスのパースと結合に使用される @ref{a6,,os.path} モジュールの実装。@code{posixpath} または @code{ntpath}。


Added in version 3.13.

@end deffn

@geindex drive (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath drive}@anchor{2c2a}
@deffn {の属性} PurePath.drive

ドライブ文字または名前を表す文字列があればそれになります:

@example
>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
'@w{'}
>>> PurePosixPath('/etc').drive
'@w{'}
@end example

UNC 共有名もドライブとみなされます:

@example
>>> PureWindowsPath('//host/share/foo.txt').drive
'\\\\host\\share'
@end example
@end deffn

@geindex root (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath root}@anchor{2c2b}
@deffn {の属性} PurePath.root

ローカルまたはグローバルルートを表す文字列があればそれになります:

@example
>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
'@w{'}
>>> PurePosixPath('/etc').root
'/'
@end example

UNC 共有名は常にルートを持ちます:

@example
>>> PureWindowsPath('//host/share').root
'\\'
@end example

@ref{2c24,,PurePosixPath} でパスの先頭が３つ以上の連続したスラッシュである場合、 余分なスラッシュは除去されます:

@example
>>> PurePosixPath('//etc').root
'//'
>>> PurePosixPath('///etc').root
'/'
>>> PurePosixPath('////etc').root
'/'
@end example

@cartouche
@quotation 注釈 
この挙動は、以下に示す、 `The Open Group Base Specifications Issue 6' の 4.11 Pathname Resolution@footnote{https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11} に沿ったものです:

`"A pathname that begins with two successive slashes may be interpreted in
an implementation-defined manner, although more than two leading slashes
shall be treated as a single slash."'
@end quotation
@end cartouche
@end deffn

@geindex anchor (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath anchor}@anchor{2c2c}
@deffn {の属性} PurePath.anchor

ドライブとルートを結合した文字列になります:

@example
>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
>>> PureWindowsPath('//host/share').anchor
'\\\\host\\share\\'
@end example
@end deffn

@geindex parents (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath parents}@anchor{a21}
@deffn {の属性} PurePath.parents

パスの論理的な上位パスにアクセスできるイミュータブルなシーケンスになります:

@example
>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')
@end example


バージョン 3.10 で変更: parents シーケンスが、@ref{24ae,,スライス} と負のインデックスをサポートするようになりました。

@end deffn

@geindex parent (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath parent}@anchor{1a9d}
@deffn {の属性} PurePath.parent

パスの論理的な上位パスになります:

@example
>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')
@end example

アンカーの位置を超えることや空のパスになる位置には対応していません:

@example
>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')
@end example

@cartouche
@quotation 注釈 
これは純粋な字句操作であるため、以下のような挙動になります:

@example
>>> p = PurePosixPath('foo/..')
>>> p.parent
PurePosixPath('foo')
@end example

任意のファイルシステムパスを上位方向に移動したい場合、シンボリックリンクの解決や @code{".."} 要素の除去のため、最初に @ref{1a6d,,Path.resolve()} を呼ぶことを推奨します。
@end quotation
@end cartouche
@end deffn

@geindex name (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath name}@anchor{2c2d}
@deffn {の属性} PurePath.name

パス要素の末尾を表す文字列があればそれになります。ドライブやルートは含まれません:

@example
>>> PurePosixPath('my/library/setup.py').name
'setup.py'
@end example

UNC ドライブ名は考慮されません:

@example
>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
'@w{'}
@end example
@end deffn

@geindex suffix (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath suffix}@anchor{1957}
@deffn {の属性} PurePath.suffix

末尾の要素をドットで分割した最後の部分があれば、それになります:

@example
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
'@w{'}
@end example

一般的にはファイル拡張子と呼ばれています。


バージョン 3.14 で変更: A single dot ("@code{.}") is considered a valid suffix.

@end deffn

@geindex suffixes (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath suffixes}@anchor{1958}
@deffn {の属性} PurePath.suffixes

パスのサフィックス(ファイル拡張子)のリストです:

@example
>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]
@end example


バージョン 3.14 で変更: A single dot ("@code{.}") is considered a valid suffix.

@end deffn

@geindex stem (pathlib.PurePath の属性)
@anchor{library/pathlib pathlib PurePath stem}@anchor{2c2e}
@deffn {の属性} PurePath.stem

パス要素の末尾から拡張子を除いたものになります:

@example
>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'
@end example


バージョン 3.14 で変更: A single dot ("@code{.}") is considered a valid suffix.

@end deffn

@geindex as_posix() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath as_posix}@anchor{2c2f}
@deffn {メソッド} PurePath.as_posix ()

フォワードスラッシュ (@code{/}) を使用したパスを表す文字列を返します:

@example
>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
@end example
@end deffn

@geindex is_absolute() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath is_absolute}@anchor{1a9c}
@deffn {メソッド} PurePath.is_absolute ()

パスが絶対パスかどうかを返します。パスが絶対パスとみなされるのは、ルートと (フレーバーが許す場合) ドライブとの両方が含まれる場合です:

@example
>>> PurePosixPath('/a/b').is_absolute()
True
>>> PurePosixPath('a/b').is_absolute()
False

>>> PureWindowsPath('c:/a/b').is_absolute()
True
>>> PureWindowsPath('/a/b').is_absolute()
False
>>> PureWindowsPath('c:').is_absolute()
False
>>> PureWindowsPath('//some/share').is_absolute()
True
@end example
@end deffn

@geindex is_relative_to() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath is_relative_to}@anchor{2fe}
@deffn {メソッド} PurePath.is_relative_to (other)

このパスが `other' パスに対して相対なのかそうでないのかの結果を返します。

@example
>>> p = PurePath('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
False
@end example

This method is string-based; it neither accesses the filesystem nor treats
"@code{..}" segments specially. The following code is equivalent:

@example
>>> u = PurePath('/usr')
>>> u == p or u in p.parents
False
@end example


Added in version 3.9.



Deprecated since version 3.12, removed in version 3.14: 追加の引数指定は非推奨となりました。指定された場合は `other' と連結されます。

@end deffn

@geindex is_reserved() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath is_reserved}@anchor{32a}
@deffn {メソッド} PurePath.is_reserved ()

@ref{1a75,,PureWindowsPath} の場合はパスが Windows 上で予約されていれば @code{True} を返し、そうでなければ @code{False} を返します。@ref{2c24,,PurePosixPath} の場合は常に @code{False} を返します。


バージョン 3.13 で変更: Windows path names that contain a colon, or end with a dot or a space,
are considered reserved. UNC paths may be reserved.



Deprecated since version 3.13, will be removed in version 3.15: This method is deprecated; use @ref{32b,,os.path.isreserved()} to detect
reserved paths on Windows.

@end deffn

@geindex joinpath() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath joinpath}@anchor{2c30}
@deffn {メソッド} PurePath.joinpath (*pathsegments)

このメソッドの呼び出しは、与えられた `pathsegments' のパスを順番に結合することと等価です。

@example
>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')
@end example
@end deffn

@geindex full_match() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath full_match}@anchor{535}
@deffn {メソッド} PurePath.full_match (pattern, *, case_sensitive=None)

現在のパスが glob 形式で与えられたパターンと一致したら @code{True} を、一致しなければ @code{False} を返します。例:

@example
>>> PurePath('a/b.py').full_match('a/*.py')
True
>>> PurePath('a/b.py').full_match('*.py')
False
>>> PurePath('/a/b/c.py').full_match('/a/**')
True
>>> PurePath('/a/b/c.py').full_match('**/*.py')
True
@end example


@subsubheading 参考


@ref{2c31,,Pattern language} ドキュメント。


他のメソッドと同様に、大文字小文字の区別はプラットフォームの設定に従います:

@example
>>> PurePosixPath('b.py').full_match('*.PY')
False
>>> PureWindowsPath('b.py').full_match('*.PY')
True
@end example

Set `case_sensitive' to @code{True} or @code{False} to override this behaviour.


Added in version 3.13.

@end deffn

@geindex match() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath match}@anchor{6d3}
@deffn {メソッド} PurePath.match (pattern, *, case_sensitive=None)

現在のパスが非再帰の glob 形式で与えられたパターンと一致したら @code{True} を、一致しなければ @code{False} を返します。

This method is similar to @ref{535,,full_match()}, but empty patterns
aren't allowed (@ref{2ec,,ValueError} is raised), the recursive wildcard
"@code{**}" isn't supported (it acts like non-recursive "@code{*}"), and if a
relative pattern is provided, then matching is done from the right:

@example
>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False
@end example


バージョン 3.12 で変更: `pattern' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.12 で変更: `case_sensitive' 引数が追加されました。

@end deffn

@geindex relative_to() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath relative_to}@anchor{2fd}
@deffn {メソッド} PurePath.relative_to (other, walk_up=False)

`other' で表されたパスから現在のパスへの相対パスを返します。それが不可能だった場合は @ref{2ec,,ValueError} が送出されます:

@example
>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 941, in relative_to
    raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other is absolute.
@end example

`walk_up' がFalseの場合（デフォルト）、パスは `other' から始まる必要があります。引数に True を指定すると @code{..} を追加して相対パスを作成する場合があります。異なるドライブを参照するなど、それ以外のケースでは @ref{2ec,,ValueError} が送出されます。:

@example
>>> p.relative_to('/usr', walk_up=True)
PurePosixPath('../etc/passwd')
>>> p.relative_to('foo', walk_up=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 941, in relative_to
    raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not on the same drive as 'foo' OR one path is relative and the other is absolute.
@end example

@cartouche
@quotation 警告 
This function is part of @ref{6cd,,PurePath} and works with strings.
It does not check or access the underlying file structure.
This can impact the `walk_up' option as it assumes that no symlinks
are present in the path; call @ref{1a6d,,resolve()} first if
necessary to resolve symlinks.
@end quotation
@end cartouche


バージョン 3.12 で変更: `walk_up' 引数が追加されました（@code{walk_up=False} を指定すると以前の動作と同じになります）。



Deprecated since version 3.12, removed in version 3.14: 追加の位置引数の指定は非推奨となりました。指定された場合は `other' と連結されます。

@end deffn

@geindex with_name() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath with_name}@anchor{1a68}
@deffn {メソッド} PurePath.with_name (name)

現在のパスの @ref{2c2d,,name} 部分を変更したパスを返します。オリジナルパスに @ref{2c2d,,name} 部分がない場合は ValueError が送出されます:

@example
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
>>> p = PureWindowsPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
@end example
@end deffn

@geindex with_stem() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath with_stem}@anchor{19dc}
@deffn {メソッド} PurePath.with_stem (stem)

現在のパスの @ref{2c2e,,stem} 部分を変更したパスを返します。オリジナルパスに @ref{2c2e,,stem} 部分がない場合は ValueError が送出されます:

@example
>>> p = PureWindowsPath('c:/Downloads/draft.txt')
>>> p.with_stem('final')
PureWindowsPath('c:/Downloads/final.txt')
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_stem('lib')
PureWindowsPath('c:/Downloads/lib.gz')
>>> p = PureWindowsPath('c:/')
>>> p.with_stem('@w{'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
    return self.with_name(stem + self.suffix)
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
@end example


Added in version 3.9.

@end deffn

@geindex with_suffix() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath with_suffix}@anchor{1956}
@deffn {メソッド} PurePath.with_suffix (suffix)

@ref{1957,,suffix} を変更した新しいパスを返します。
元のパスに suffix が無かった場合、代わりに新しい `suffix' が追加されます。
`suffix' が空文字列だった場合、元の suffix は除去されます:

@example
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
>>> p = PureWindowsPath('README.txt')
>>> p.with_suffix('@w{'})
PureWindowsPath('README')
@end example


バージョン 3.14 で変更: A single dot ("@code{.}") is considered a valid suffix. In previous
versions, @ref{2ec,,ValueError} is raised if a single dot is supplied.

@end deffn

@geindex with_segments() (pathlib.PurePath のメソッド)
@anchor{library/pathlib pathlib PurePath with_segments}@anchor{6ce}
@deffn {メソッド} PurePath.with_segments (*pathsegments)

Create a new path object of the same type by combining the given
`pathsegments'. This method is called whenever a derivative path is created,
such as from @ref{1a9d,,parent} and @ref{2fd,,relative_to()}. Subclasses may
override this method to pass information to derivative paths, for example:

@example
from pathlib import PurePosixPath

class MyPath(PurePosixPath):
    def __init__(self, *pathsegments, session_id):
        super().__init__(*pathsegments)
        self.session_id = session_id

    def with_segments(self, *pathsegments):
        return type(self)(*pathsegments, session_id=self.session_id)

etc = MyPath('/etc', session_id=42)
hosts = etc / 'hosts'
print(hosts.session_id)  # 42
@end example


Added in version 3.12.

@end deffn

@node 具象パス,Pattern language,純粋パス,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib concrete-paths}@anchor{2c1f}@anchor{library/pathlib id2}@anchor{2c32}
@subsubsection 具象パス


具象パスは純粋パスクラスのサブクラスです。純粋パスが提供する操作に加え、パスオブジェクト上でシステムコールを呼ぶメソッドも提供しています。具象パスのインスタンスを作成するには 3 つの方法があります:

@geindex Path (pathlib のクラス)
@anchor{library/pathlib pathlib Path}@anchor{266}
@deffn {クラス} pathlib.Path (*pathsegments)

@ref{6cd,,PurePath} のサブクラスであり、システムのパスフレーバーの具象パスを表します (このインスタンスの作成で @ref{2c33,,PosixPath} か @ref{2c20,,WindowsPath} のどちらかが作成されます):

@example
>>> Path('setup.py')
PosixPath('setup.py')
@end example

`pathsegments' の指定は @ref{6cd,,PurePath} と同じです。
@end deffn

@geindex PosixPath (pathlib のクラス)
@anchor{library/pathlib pathlib PosixPath}@anchor{2c33}
@deffn {クラス} pathlib.PosixPath (*pathsegments)

@ref{266,,Path} および @ref{2c24,,PurePosixPath} のサブクラスで、非 Windows ファイルシステムの具象パスを表します:

@example
>>> PosixPath('/etc/hosts')
PosixPath('/etc/hosts')
@end example

`pathsegments' の指定は @ref{6cd,,PurePath} と同じです。


バージョン 3.13 で変更: Windows では @ref{533,,UnsupportedOperation} を送出します。以前のバージョンでは代わりに @ref{36b,,NotImplementedError} を送出していました。

@end deffn

@geindex WindowsPath (pathlib のクラス)
@anchor{library/pathlib pathlib WindowsPath}@anchor{2c20}
@deffn {クラス} pathlib.WindowsPath (*pathsegments)

@ref{266,,Path} および @ref{1a75,,PureWindowsPath} のサブクラスで、Windows ファイルシステムの具象パスを表します:

@example
>>> WindowsPath('c:/', 'Users', 'Ximénez')
WindowsPath('c:/Users/Ximénez')
@end example

`pathsegments' の指定は @ref{6cd,,PurePath} と同じです。


バージョン 3.13 で変更: Windows 以外のプラットフォームでは @ref{533,,UnsupportedOperation} を送出します。以前のバージョンでは代わりに @ref{36b,,NotImplementedError} を送出していました。

@end deffn

インスタンスを作成できるのはシステムと一致するフレーバーのみです (互換性のないパスフレーバーでのシステムコールの許可はバグやアプリケーションの異常終了の原因になります):

@example
>>> import os
>>> os.name
'posix'
>>> Path('setup.py')
PosixPath('setup.py')
>>> PosixPath('setup.py')
PosixPath('setup.py')
>>> WindowsPath('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 798, in __new__
    % (cls.__name__,))
UnsupportedOperation: cannot instantiate 'WindowsPath' on your system
@end example

Some concrete path methods can raise an @ref{2c0,,OSError} if a system call fails
(for example because the path doesn't exist).

@menu
* URIのパースと生成:: 
* パスの展開と解決:: 
* ファイルの種類とステータスを問い合わせる:: 
* ファイルを読み書きする: ファイルを読み書きする<2>. 
* ディレクトリを読む:: 
* ファイルとディレクトリの作成:: 
* Copying@comma{} moving and deleting: Copying moving and deleting. 
* パーミッションと所有者:: 

@end menu

@node URIのパースと生成,パスの展開と解決,,具象パス
@anchor{library/pathlib parsing-and-generating-uris}@anchor{2c34}
@subsubsection URIのパースと生成


Concrete path objects can be created from, and represented as, 'file' URIs
conforming to 
@geindex RFC; RFC 8089
RFC 8089@footnote{https://datatracker.ietf.org/doc/html/rfc8089.html}.

@cartouche
@quotation 注釈 
File URIs are not portable across machines with different
@ref{2c35,,filesystem encodings}.
@end quotation
@end cartouche

@geindex from_uri() (pathlib.Path のクラスメソッド)
@anchor{library/pathlib pathlib Path from_uri}@anchor{534}
@deffn {メソッド} classmethod Path.from_uri (uri)

'file' URIをパースして新しいパスオブジェクトを返します。例:

@example
>>> p = Path.from_uri('file:///etc/hosts')
PosixPath('/etc/hosts')
@end example

On Windows, DOS device and UNC paths may be parsed from URIs:

@example
>>> p = Path.from_uri('file:///c:/windows')
WindowsPath('c:/windows')
>>> p = Path.from_uri('file://server/share')
WindowsPath('//server/share')
@end example

Several variant forms are supported:

@example
>>> p = Path.from_uri('file:////server/share')
WindowsPath('//server/share')
>>> p = Path.from_uri('file://///server/share')
WindowsPath('//server/share')
>>> p = Path.from_uri('file:c:/windows')
WindowsPath('c:/windows')
>>> p = Path.from_uri('file:/c|/windows')
WindowsPath('c:/windows')
@end example

@ref{2ec,,ValueError} is raised if the URI does not start with @code{file:}, or
the parsed path isn't absolute.


Added in version 3.13.



バージョン 3.14 で変更: The URL authority is discarded if it matches the local hostname.
Otherwise, if the authority isn't empty or @code{localhost}, then on
Windows a UNC path is returned (as before), and on other platforms a
@ref{2ec,,ValueError} is raised.

@end deffn

@geindex as_uri() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path as_uri}@anchor{31c}
@deffn {メソッド} Path.as_uri ()

 'file' URI で表したパスを返します。絶対パスではない場合に @ref{2ec,,ValueError} を送出します。

@example
>>> p = PosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = WindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
@end example


Deprecated since version 3.14, will be removed in version 3.19: Calling this method from @ref{6cd,,PurePath} rather than @ref{266,,Path} is
possible but deprecated. The method's use of @ref{e4f,,os.fsencode()} makes
it strictly impure.

@end deffn

@node パスの展開と解決,ファイルの種類とステータスを問い合わせる,URIのパースと生成,具象パス
@anchor{library/pathlib expanding-and-resolving-paths}@anchor{2c36}
@subsubsection パスの展開と解決


@geindex home() (pathlib.Path のクラスメソッド)
@anchor{library/pathlib pathlib Path home}@anchor{1043}
@deffn {メソッド} classmethod Path.home ()

ユーザーのホームディレクトリ (@ref{c09,,os.path.expanduser()} での @code{~} の返り値) を表す新しいパスオブジェクトを返します。ホームディレクトリが解決できない場合は、 @ref{244,,RuntimeError} を送出します。

@example
>>> Path.home()
PosixPath('/home/antoine')
@end example


Added in version 3.5.

@end deffn

@geindex expanduser() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path expanduser}@anchor{1042}
@deffn {メソッド} Path.expanduser ()

パス要素 @code{~} および @code{~user} を @ref{c09,,os.path.expanduser()} が返すように展開した新しいパスオブジェクトを返します。ホームディレクトリが解決できない場合は、 @ref{244,,RuntimeError} を送出します。

@example
>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')
@end example


Added in version 3.5.

@end deffn

@geindex cwd() (pathlib.Path のクラスメソッド)
@anchor{library/pathlib pathlib Path cwd}@anchor{1a9b}
@deffn {メソッド} classmethod Path.cwd ()

(@ref{1909,,os.getcwd()} が返す) 現在のディレクトリを表す新しいパスオブジェクトを返します:

@example
>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
@end example
@end deffn

@geindex absolute() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path absolute}@anchor{1a26}
@deffn {メソッド} Path.absolute ()

正規化やシンボリックリンクの解決をせずに、パスを絶対パスにします。新しいパスオブジェクトを返します:

@example
>>> p = Path('tests')
>>> p
PosixPath('tests')
>>> p.absolute()
PosixPath('/home/antoine/pathlib/tests')
@end example
@end deffn

@geindex resolve() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path resolve}@anchor{1a6d}
@deffn {メソッド} Path.resolve (strict=False)

パスを絶対パスにし、あらゆるシンボリックリンクを解決します。新しいパスオブジェクトが返されます:

@example
>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')
@end example

"@code{..}" 要素は除去されます (このような挙動を示すのはこのメソッドだけです):

@example
>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
@end example

If a path doesn't exist or a symlink loop is encountered, and `strict' is
@code{True}, @ref{2c0,,OSError} is raised.  If `strict' is @code{False}, the path is
resolved as far as possible and any remainder is appended without checking
whether it exists.


バージョン 3.6 で変更: `strict' 引数を追加しました(3.6以前の挙動は strict です)。



バージョン 3.13 で変更: Symlink loops are treated like other errors: @ref{2c0,,OSError} is raised in
strict mode, and no exception is raised in non-strict mode. In previous
versions, @ref{244,,RuntimeError} is raised no matter the value of `strict'.

@end deffn

@geindex readlink() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path readlink}@anchor{b19}
@deffn {メソッド} Path.readlink ()

( @ref{b1a,,os.readlink()} が返す) シンボリックリンクが指すパスを返します:

@example
>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.readlink()
PosixPath('setup.py')
@end example


Added in version 3.9.



バージョン 3.13 で変更: @ref{b1a,,os.readlink()} が利用できない場合 @ref{533,,UnsupportedOperation} を送出します。以前のバージョンでは @ref{36b,,NotImplementedError} を送出していました。

@end deffn

@node ファイルの種類とステータスを問い合わせる,ファイルを読み書きする<2>,パスの展開と解決,具象パス
@anchor{library/pathlib querying-file-type-and-status}@anchor{2c37}
@subsubsection ファイルの種類とステータスを問い合わせる



バージョン 3.8 で変更: @ref{c0b,,exists()}, @ref{53a,,is_dir()}, @ref{539,,is_file()}, @ref{c0c,,is_mount()}, @ref{c0d,,is_symlink()}, @ref{c0e,,is_block_device()}, @ref{c0f,,is_char_device()}, @ref{c11,,is_socket()} は、OSレベルで表現不能な文字を含むパスに対して、例外を送出する代わりに @code{False} を返すようになりました。



バージョン 3.14 で変更: The methods given above now return @code{False} instead of raising any
@ref{2c0,,OSError} exception from the operating system. In previous versions,
some kinds of @ref{2c0,,OSError} exception are raised, and others suppressed.
The new behaviour is consistent with @ref{c03,,os.path.exists()},
@ref{c05,,os.path.isdir()}, etc. Use @ref{a24,,stat()} to retrieve the file
status without suppressing exceptions.


@geindex stat() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path stat}@anchor{a24}
@deffn {メソッド} Path.stat (*, follow_symlinks=True)

(@ref{26d,,os.stat()} と同様の) 現在のパスについて @ref{16da,,os.stat_result} オブジェクトが含む情報を返します。値はそれぞれのメソッドを呼び出した時点のものになります。

このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクに対して stat したい場合は @code{follow_symlinks=False} とするか、 @ref{2c38,,lstat()} を利用してください。

@example
>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554
@end example


バージョン 3.10 で変更: `follow_symlinks' パラメータが追加されました。

@end deffn

@geindex lstat() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path lstat}@anchor{2c38}
@deffn {メソッド} Path.lstat ()

@ref{a24,,Path.stat()} のように振る舞いますが、パスがシンボリックリンクを指していた場合、リンク先ではなくシンボリックリンク自身の情報を返します。
@end deffn

@geindex exists() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path exists}@anchor{c0b}
@deffn {メソッド} Path.exists (*, follow_symlinks=True)

Return @code{True} if the path points to an existing file or directory.
@code{False} will be returned if the path is invalid, inaccessible or missing.
Use @ref{a24,,Path.stat()} to distinguish between these cases.

このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクが存在するかを確認したい場合は @code{follow_symlinks=False} 引数を追加してください。

@example
>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False
@end example


バージョン 3.12 で変更: `follow_symlinks' パラメータが追加されました。

@end deffn

@geindex is_file() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_file}@anchor{539}
@deffn {メソッド} Path.is_file (*, follow_symlinks=True)

Return @code{True} if the path points to a regular file. @code{False} will be
returned if the path is invalid, inaccessible or missing, or if it points
to something other than a regular file. Use @ref{a24,,Path.stat()} to
distinguish between these cases.

このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクを除外するには @code{follow_symlinks=False} 引数を追加してください。


バージョン 3.13 で変更: `follow_symlinks' パラメータが追加されました。

@end deffn

@geindex is_dir() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_dir}@anchor{53a}
@deffn {メソッド} Path.is_dir (*, follow_symlinks=True)

Return @code{True} if the path points to a directory. @code{False} will be
returned if the path is invalid, inaccessible or missing, or if it points
to something other than a directory. Use @ref{a24,,Path.stat()} to distinguish
between these cases.

このメソッドは通常はシンボリックリンクをたどります。ディレクトリへのシンボリックリンクを除外するには @code{follow_symlinks=False} 引数を追加してください。


バージョン 3.13 で変更: `follow_symlinks' パラメータが追加されました。

@end deffn

@geindex is_symlink() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_symlink}@anchor{c0d}
@deffn {メソッド} Path.is_symlink ()

Return @code{True} if the path points to a symbolic link, even if that symlink
is broken. @code{False} will be returned if the path is invalid, inaccessible
or missing, or if it points to something other than a symbolic link. Use
@ref{a24,,Path.stat()} to distinguish between these cases.
@end deffn

@geindex is_junction() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_junction}@anchor{6d2}
@deffn {メソッド} Path.is_junction ()

パスがジャンクションを指している場合は @code{True} を返し、それ以外の場合は @code{False} を返します。現在はWindowsのみジャンクションをサポートしています。


Added in version 3.12.

@end deffn

@geindex is_mount() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_mount}@anchor{c0c}
@deffn {メソッド} Path.is_mount ()

パスがマウントポイント `mount point' (ファイルシステムの中で異なるファイルシステムがマウントされているところ) なら、 @code{True} を返します。POSIX では、この関数は `path' の親ディレクトリである @code{path/..} が `path' と異なるデバイス上にあるか、あるいは @code{path/..} と `path' が同じデバイス上の同じ i-node を指しているかをチェックします --- これによって全ての Unix 系システムと POSIX 標準でマウントポイントが検出できます。Windowsでは、マウントポイントはドライブレターを持つルート(e.g. @code{c:\})、共有 UNC(e.g. @code{\\server\share})またはマウントされたファイルシステムのディレクトリです。


Added in version 3.7.



バージョン 3.12 で変更: Windows のサポートが追加されました。

@end deffn

@geindex is_socket() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_socket}@anchor{c11}
@deffn {メソッド} Path.is_socket ()

Return @code{True} if the path points to a Unix socket. @code{False} will be
returned if the path is invalid, inaccessible or missing, or if it points
to something other than a Unix socket. Use @ref{a24,,Path.stat()} to
distinguish between these cases.
@end deffn

@geindex is_fifo() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_fifo}@anchor{c10}
@deffn {メソッド} Path.is_fifo ()

Return @code{True} if the path points to a FIFO. @code{False} will be returned if
the path is invalid, inaccessible or missing, or if it points to something
other than a FIFO. Use @ref{a24,,Path.stat()} to distinguish between these
cases.
@end deffn

@geindex is_block_device() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_block_device}@anchor{c0e}
@deffn {メソッド} Path.is_block_device ()

Return @code{True} if the path points to a block device. @code{False} will be
returned if the path is invalid, inaccessible or missing, or if it points
to something other than a block device. Use @ref{a24,,Path.stat()} to
distinguish between these cases.
@end deffn

@geindex is_char_device() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path is_char_device}@anchor{c0f}
@deffn {メソッド} Path.is_char_device ()

Return @code{True} if the path points to a character device. @code{False} will be
returned if the path is invalid, inaccessible or missing, or if it points
to something other than a character device. Use @ref{a24,,Path.stat()} to
distinguish between these cases.
@end deffn

@geindex samefile() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path samefile}@anchor{1040}
@deffn {メソッド} Path.samefile (other_path)

このパスが参照するファイルが `other_path' (Path オブジェクトか文字列) と同じであれば @code{True} を、異なるファイルであれば @code{False} を返します。意味的には @ref{1173,,os.path.samefile()} および @ref{1172,,os.path.samestat()} と同じです。

なんらかの理由でどちらかのファイルにアクセスできない場合は @ref{2c0,,OSError} が送出されます。

@example
>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
True
@end example


Added in version 3.5.

@end deffn

@geindex info (pathlib.Path の属性)
@anchor{library/pathlib pathlib Path info}@anchor{26b}
@deffn {の属性} Path.info

A @ref{26c,,PathInfo} object that supports querying file type
information. The object exposes methods that cache their results, which can
help reduce the number of system calls needed when switching on file type.
For example:

@example
>>> p = Path('src')
>>> if p.info.is_symlink():
...     print('symlink')
... elif p.info.is_dir():
...     print('directory')
... elif p.info.exists():
...     print('something else')
... else:
...     print('not found')
...
directory
@end example

If the path was generated from @ref{26e,,Path.iterdir()} then this attribute is
initialized with some information about the file type gleaned from scanning
the parent directory. Merely accessing @ref{26b,,Path.info} does not perform
any filesystem queries.

To fetch up-to-date information, it's best to call @ref{53a,,Path.is_dir()},
@ref{539,,is_file()} and @ref{c0d,,is_symlink()} rather than methods of
this attribute. There is no way to reset the cache; instead you can create
a new path object with an empty info cache via @code{p = Path(p)}.


Added in version 3.14.

@end deffn

@node ファイルを読み書きする<2>,ディレクトリを読む,ファイルの種類とステータスを問い合わせる,具象パス
@anchor{library/pathlib reading-and-writing-files}@anchor{2c39}
@subsubsection ファイルを読み書きする


@geindex open() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path open}@anchor{2c3a}
@deffn {メソッド} Path.open (mode='r', buffering=-1, encoding=None, errors=None, newline=None)

組み込み関数 @ref{316,,open()} のようにパスが指しているファイルを開きます:

@example
>>> p = Path('setup.py')
>>> with p.open() as f:
...     f.readline()
...
'#!/usr/bin/env python3\n'
@end example
@end deffn

@geindex read_text() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path read_text}@anchor{1045}
@deffn {メソッド} Path.read_text (encoding=None, errors=None, newline=None)

指定されたファイルの内容を文字列としてデコードして返します:

@example
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'
@end example

ファイルを開いた後に閉じます。
オプションのパラメーターの意味は @ref{316,,open()} と同じです。


Added in version 3.5.



バージョン 3.13 で変更: `newline' パラメータが追加されました。

@end deffn

@geindex read_bytes() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path read_bytes}@anchor{2df}
@deffn {メソッド} Path.read_bytes ()

指定されたファイルの内容をバイナリオブジェクトで返します:

@example
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'
@end example


Added in version 3.5.

@end deffn

@geindex write_text() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path write_text}@anchor{1044}
@deffn {メソッド} Path.write_text (data, encoding=None, errors=None, newline=None)

指定されたファイルをテキストモードで開き、`data' を書き込み、ファイルを閉じます:

@example
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'
@end example

同じ名前のファイルが存在する場合は上書きされます。オプションのパラメーターの意味は @ref{316,,open()} と同じです。


Added in version 3.5.



バージョン 3.10 で変更: `newline' パラメータが追加されました。

@end deffn

@geindex write_bytes() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path write_bytes}@anchor{1046}
@deffn {メソッド} Path.write_bytes (data)

指定されたファイルをバイトモードで開き、`data' を書き込み、ファイルを閉じます:

@example
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'
@end example

同じ名前のファイルがすでにあれば上書きされます。


Added in version 3.5.

@end deffn

@node ディレクトリを読む,ファイルとディレクトリの作成,ファイルを読み書きする<2>,具象パス
@anchor{library/pathlib reading-directories}@anchor{2c3b}
@subsubsection ディレクトリを読む


@geindex iterdir() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path iterdir}@anchor{26e}
@deffn {メソッド} Path.iterdir ()

パスがディレクトリを指していた場合、ディレクトリの内容のパスオブジェクトを yield します:

@example
>>> p = Path('docs')
>>> for child in p.iterdir(): child
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')
@end example

子の要素は任意の順番で yield されます。特殊なパスの @code{'.'} と @code{'..'} は含まれません。イテレーターを生成したあとにディレクトリにファイルを削除または追加した場合に、そのファイルのパスオブジェクトが含まれるかは定義されていません。

パスがディレクトリでないかアクセスできない場合は @ref{2c0,,OSError} を送出します。
@end deffn

@geindex glob() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path glob}@anchor{537}
@deffn {メソッド} Path.glob (pattern, *, case_sensitive=None, recurse_symlinks=False)

現在のパスが表すディレクトリ内で相対 `pattern' に一致する (あらゆる種類の) すべてのファイルを yield します:

@example
>>> 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')]
@end example

@cartouche
@quotation 注釈 
The paths are returned in no particular order.
If you need a specific order, sort the results.
@end quotation
@end cartouche


@subsubheading 参考


@ref{2c31,,Pattern language} ドキュメント。


デフォルトまたは `case_sensitive' キーワード専用引数に @code{None} を指定した場合、このメソッドはパスの一致判定にプラットフォームに依存した大文字小文字のルールを使用します。一般的にPOSIXは大文字と小文字を区別し、Windowsは区別しません。`case_sensitive' を @code{True} または @code{False} に設定するとこの動作を上書きします。

デフォルトまたは  `recurse_symlinks' キーワード専用引数が @code{False} に設定された場合、このメソッドは "@code{**}" ワイルドカードの展開時にシンボリックリンクをたどりません。`recurse_symlinks' を @code{True} に設定すると、つねにシンボリックリンクをたどります。

引数 @code{self}, @code{pattern} を指定して @ref{1c6e,,監査イベント} @code{pathlib.Path.glob} を送出します。


バージョン 3.12 で変更: `case_sensitive' 引数が追加されました。



バージョン 3.13 で変更: `recurse_symlinks' パラメータが追加されました。



バージョン 3.13 で変更: `pattern' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.13 で変更: Any @ref{2c0,,OSError} exceptions raised from scanning the filesystem are
suppressed. In previous versions, such exceptions are suppressed in many
cases, but not all.

@end deffn

@geindex rglob() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path rglob}@anchor{538}
@deffn {メソッド} Path.rglob (pattern, *, case_sensitive=None, recurse_symlinks=False)

与えられた相対  `pattern' で再帰的に Glob します。@ref{537,,Path.glob()} で `pattern' の前に "@code{**/}" をつけ呼び出した場合と似ています。

@cartouche
@quotation 注釈 
The paths are returned in no particular order.
If you need a specific order, sort the results.
@end quotation
@end cartouche


@subsubheading 参考


@ref{2c31,,Pattern language} と @ref{537,,Path.glob()} のドキュメント。


引数 @code{self}, @code{pattern} を指定して @ref{1c6e,,監査イベント} @code{pathlib.Path.rglob} を送出します。


バージョン 3.12 で変更: `case_sensitive' 引数が追加されました。



バージョン 3.13 で変更: `recurse_symlinks' パラメータが追加されました。



バージョン 3.13 で変更: `pattern' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex walk() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path walk}@anchor{6cf}
@deffn {メソッド} Path.walk (top_down=True, on_error=None, follow_symlinks=False)

Generate the file names in a directory tree by walking the tree
either top-down or bottom-up.

For each directory in the directory tree rooted at `self' (including
`self' but excluding '.' and '..'), the method yields a 3-tuple of
@code{(dirpath, dirnames, filenames)}.

`dirpath' is a @ref{266,,Path} to the directory currently being walked,
`dirnames' is a list of strings for the names of subdirectories in `dirpath'
(excluding @code{'.'} and @code{'..'}), and `filenames' is a list of strings for
the names of the non-directory files in `dirpath'. To get a full path
(which begins with `self') to a file or directory in `dirpath', do
@code{dirpath / name}. Whether or not the lists are sorted is file
system-dependent.

If the optional argument `top_down' is true (which is the default), the triple for a
directory is generated before the triples for any of its subdirectories
(directories are walked top-down).  If `top_down' is false, the triple
for a directory is generated after the triples for all of its subdirectories
(directories are walked bottom-up). No matter the value of `top_down', the
list of subdirectories is retrieved before the triples for the directory and
its subdirectories are walked.

When `top_down' is true, the caller can modify the `dirnames' list in-place
(for example, using @ref{1b1f,,del} or slice assignment), and @ref{6cf,,Path.walk()}
will only recurse into the subdirectories whose names remain in `dirnames'.
This can be used to prune the search, or to impose a specific order of visiting,
or even to inform @ref{6cf,,Path.walk()} about directories the caller creates or
renames before it resumes @ref{6cf,,Path.walk()} again. Modifying `dirnames' when
`top_down' is false has no effect on the behavior of @ref{6cf,,Path.walk()} since the
directories in `dirnames' have already been generated by the time `dirnames'
is yielded to the caller.

By default, errors from @ref{c54,,os.scandir()} are ignored.  If the optional
argument `on_error' is specified, it should be a callable; it will be
called with one argument, an @ref{2c0,,OSError} instance. The callable can handle the
error to continue the walk or re-raise it to stop the walk. Note that the
filename is available as the @code{filename} attribute of the exception object.

By default, @ref{6cf,,Path.walk()} does not follow symbolic links, and instead adds them
to the `filenames' list. Set `follow_symlinks' to true to resolve symlinks
and place them in `dirnames' and `filenames' as appropriate for their targets, and
consequently visit directories pointed to by symlinks (where supported).

@cartouche
@quotation 注釈 
`follow_symlinks' に True を指定すると、シンボリックリンクが親ディレクトリを指していた場合に、無限ループになることに注意してください。 @ref{6cf,,Path.walk()} はすでにたどったディレクトリを管理したりはしません。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
@ref{6cf,,Path.walk()} assumes the directories it walks are not modified during
execution. For example, if a directory from `dirnames' has been replaced
with a symlink and `follow_symlinks' is false, @ref{6cf,,Path.walk()} will
still try to descend into it. To prevent such behavior, remove directories
from `dirnames' as appropriate.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
Unlike @ref{6d0,,os.walk()}, @ref{6cf,,Path.walk()} lists symlinks to directories in
`filenames' if `follow_symlinks' is false.
@end quotation
@end cartouche

This example displays the number of bytes used by all files in each directory,
while ignoring @code{__pycache__} directories:

@example
from pathlib import Path
for root, dirs, files in Path("cpython/Lib/concurrent").walk(on_error=print):
  print(
      root,
      "consumes",
      sum((root / file).stat().st_size for file in files),
      "bytes in",
      len(files),
      "non-directory files"
  )
  if '__pycache__' in dirs:
        dirs.remove('__pycache__')
@end example

This next example is a simple implementation of @ref{356,,shutil.rmtree()}.
Walking the tree bottom-up is essential as @ref{2c3c,,rmdir()} doesn't allow
deleting a directory before it is empty:

@example
# Delete everything reachable from the directory "top".
# CAUTION:  This is dangerous! For example, if top == Path('/'),
# it could delete all of your files.
for root, dirs, files in top.walk(top_down=False):
    for name in files:
        (root / name).unlink()
    for name in dirs:
        (root / name).rmdir()
@end example


Added in version 3.12.

@end deffn

@node ファイルとディレクトリの作成,Copying moving and deleting,ディレクトリを読む,具象パス
@anchor{library/pathlib creating-files-and-directories}@anchor{2c3d}
@subsubsection ファイルとディレクトリの作成


@geindex touch() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path touch}@anchor{2c3e}
@deffn {メソッド} Path.touch (mode=0o666, exist_ok=True)

与えられたパスにファイルを作成します。`mode' が与えられた場合、プロセスの @code{umask} 値と組み合わせてファイルのモードとアクセスフラグが決定されます。ファイルがすでに存在した場合、`exist_ok' が真ならばこの関数は正常に終了します (そしてファイルの更新日付が現在の日時に変更されます)。その他の場合は @ref{1221,,FileExistsError} が送出されます。


@subsubheading 参考


The @ref{2c3a,,open()}, @ref{1044,,write_text()} and
@ref{1046,,write_bytes()} methods are often used to create files.

@end deffn

@geindex mkdir() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path mkdir}@anchor{1041}
@deffn {メソッド} Path.mkdir (mode=0o777, parents=False, exist_ok=False)

与えられたパスに新しくディレクトリを作成します。`mode' が与えられていた場合、プロセスの @code{umask} 値と組み合わせてファイルのモードとアクセスフラグを決定します。パスがすでに存在していた場合 @ref{1221,,FileExistsError} が送出されます。

`parents' の値が真の場合、このパスの親ディレクトリを必要に応じて作成します; それらのアクセス制限はデフォルト値が取られ、`mode' は使用されません (POSIX の @code{mkdir -p} コマンドを真似ています)。

`parents' の値が偽の場合 (デフォルト)、親ディレクトリがないと @ref{264,,FileNotFoundError} を送出します。

`exist_ok' の値が (デフォルトの) 偽の場合、対象のディレクトリがすでに存在すると @ref{1221,,FileExistsError} を送出します。

If `exist_ok' is true, @ref{1221,,FileExistsError} will not be raised unless the given
path already exists in the file system and is not a directory (same
behavior as the POSIX @code{mkdir -p} command).


バージョン 3.5 で変更: `exist_ok' 引数が追加されました。

@end deffn

@geindex symlink_to() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path symlink_to}@anchor{a23}
@deffn {メソッド} Path.symlink_to (target, target_is_directory=False)

Make this path a symbolic link pointing to `target'.

Windows では、シンボリックリンクはファイルかディレクトリのどちらかを表しますが、ターゲットに合わせて動的に変化することはありません。ターゲットが存在する場合、シンボリックリンクの種類は対象に合わせて作成されます。ターゲットが存在せず `target_is_directory' が真である場合、シンボリックリンクはディレクトリのリンクとして作成され、偽である場合 (デフォルト) はファイルのリンクになります。Windows 以外のプラットフォームでは `target_is_directory' は無視されます。

@example
>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
>>> p.stat().st_size
956
>>> p.lstat().st_size
8
@end example

@cartouche
@quotation 注釈 
引数の並び (link, target) は @ref{130c,,os.symlink()} とは逆です。
@end quotation
@end cartouche


バージョン 3.13 で変更: @ref{130c,,os.symlink()} が利用できない場合 @ref{533,,UnsupportedOperation} を送出します。以前のバージョンでは @ref{36b,,NotImplementedError} を送出していました。

@end deffn

@geindex hardlink_to() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path hardlink_to}@anchor{a22}
@deffn {メソッド} Path.hardlink_to (target)

このパスを `target' と同じファイルへのハードリンクにします。

@cartouche
@quotation 注釈 
引数の並び (link, target) は @ref{1307,,os.link()} とは逆です。
@end quotation
@end cartouche


Added in version 3.10.



バージョン 3.13 で変更: @ref{1307,,os.link()} が利用できない場合 @ref{533,,UnsupportedOperation} を送出します。以前のバージョンでは @ref{36b,,NotImplementedError} を送出していました。

@end deffn

@node Copying moving and deleting,パーミッションと所有者,ファイルとディレクトリの作成,具象パス
@anchor{library/pathlib copying-moving-and-deleting}@anchor{2c3f}
@subsubsection Copying, moving and deleting


@geindex copy() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path copy}@anchor{267}
@deffn {メソッド} Path.copy (target, *, follow_symlinks=True, preserve_metadata=False)

Copy this file or directory tree to the given `target', and return a new
@code{Path} instance pointing to `target'.

If the source is a file, the target will be replaced if it is an existing
file. If the source is a symlink and `follow_symlinks' is true (the
default), the symlink's target is copied. Otherwise, the symlink is
recreated at the destination.

If `preserve_metadata' is false (the default), only directory structures
and file data are guaranteed to be copied. Set `preserve_metadata' to true
to ensure that file and directory permissions, flags, last access and
modification times, and extended attributes are copied where supported.
This argument has no effect when copying files on Windows (where
metadata is always preserved).

@cartouche
@quotation 注釈 
Where supported by the operating system and file system, this method
performs a lightweight copy, where data blocks are only copied when
modified. This is known as copy-on-write.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@geindex copy_into() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path copy_into}@anchor{268}
@deffn {メソッド} Path.copy_into (target_dir, *, follow_symlinks=True, preserve_metadata=False)

Copy this file or directory tree into the given `target_dir', which should
be an existing directory. Other arguments are handled identically to
@ref{267,,Path.copy()}. Returns a new @code{Path} instance pointing to the
copy.


Added in version 3.14.

@end deffn

@geindex rename() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path rename}@anchor{1891}
@deffn {メソッド} Path.rename (target)

このファイルかディレクトリを与えられた `target' にリネームし、 `target' を指す新しい @code{Path} のインスタンスを返します。
Unix では `target' が存在するファイルの場合、ユーザにパーミッションがあれば静かに置換されます。
Windows では `target' が存在する場合、@ref{1221,,FileExistsError} が送出されます。
`target' は文字列か別のパスオブジェクトです:

@example
>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'
@end example

targetパスは絶対または相対で指定できます。相対パスは現在の作業ディレクトリからの相対パスとして解釈し、@code{Path} オブジェクトのディレクトリ `ではありません'。

It is implemented in terms of @ref{1309,,os.rename()} and gives the same guarantees.


バージョン 3.8 で変更: 戻り値を追加し、新しい @code{Path} インスタンスを返します。

@end deffn

@geindex replace() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path replace}@anchor{2c40}
@deffn {メソッド} Path.replace (target)

現在のファイルまたはディレクトリの名前を `target' に変更し、 `target' を指す新しい @code{Path} のインスタンスを返します。`target' が既存のファイルか空のディレクトリを指していた場合、無条件に置き換えられます。

targetパスは絶対または相対で指定できます。相対パスは現在の作業ディレクトリからの相対パスとして解釈し、@code{Path} オブジェクトのディレクトリ `ではありません'。


バージョン 3.8 で変更: 戻り値を追加し、新しい @code{Path} インスタンスを返します。

@end deffn

@geindex move() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path move}@anchor{269}
@deffn {メソッド} Path.move (target)

Move this file or directory tree to the given `target', and return a new
@code{Path} instance pointing to `target'.

If the `target' doesn't exist it will be created. If both this path and the
`target' are existing files, then the target is overwritten. If both paths
point to the same file or directory, or the `target' is a non-empty
directory, then @ref{2c0,,OSError} is raised.

If both paths are on the same filesystem, the move is performed with
@ref{130a,,os.replace()}. Otherwise, this path is copied (preserving metadata and
symlinks) and then deleted.


Added in version 3.14.

@end deffn

@geindex move_into() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path move_into}@anchor{26a}
@deffn {メソッド} Path.move_into (target_dir)

Move this file or directory tree into the given `target_dir', which should
be an existing directory. Returns a new @code{Path} instance pointing to
the moved path.


Added in version 3.14.

@end deffn

@geindex unlink() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path unlink}@anchor{1dd5}
@deffn {メソッド} Path.unlink (missing_ok=False)

このファイルまたはシンボリックリンクを削除します。パスがディレクトリを指している場合は @ref{2c3c,,Path.rmdir()} を使用してください。

`missing_ok' の値が (デフォルトの) 偽の場合、対象のファイルが存在しないと @ref{264,,FileNotFoundError} を送出します。

`missing_ok' の値が真の場合、 @ref{1221,,FileExistsError} 例外を送出しません (POSIX の @code{rm -f} コマンドの挙動と同じ)。


バージョン 3.8 で変更: `missing_ok' 引数が追加されました。

@end deffn

@geindex rmdir() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path rmdir}@anchor{2c3c}
@deffn {メソッド} Path.rmdir ()

現在のディレクトリを削除します。ディレクトリは空でなければなりません。
@end deffn

@node パーミッションと所有者,,Copying moving and deleting,具象パス
@anchor{library/pathlib permissions-and-ownership}@anchor{2c41}
@subsubsection パーミッションと所有者


@geindex owner() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path owner}@anchor{53b}
@deffn {メソッド} Path.owner (*, follow_symlinks=True)

ファイルの所有者のユーザー名を返します。ファイルのユーザーID(UID)がシステムのデータベースに見つからない場合 @ref{5e7,,KeyError} が送出されます。

このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクの所有者を取得するには @code{follow_symlinks=False} 引数を追加してください。


バージョン 3.13 で変更: @ref{b7,,pwd} モジュールが利用できない場合 @ref{533,,UnsupportedOperation} を送出します。以前のバージョンでは @ref{36b,,NotImplementedError} を送出していました。



バージョン 3.13 で変更: `follow_symlinks' パラメータが追加されました。

@end deffn

@geindex group() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path group}@anchor{53c}
@deffn {メソッド} Path.group (*, follow_symlinks=True)

ファイルの所有者のグループ名を返します。ファイルのグループID(GID)がシステムのデータベースに見つからない場合 @ref{5e7,,KeyError} が送出されます。

このメソッドは通常はシンボリックリンクをたどります。シンボリックリンクのグループを取得するには @code{follow_symlinks=False} 引数を追加してください。


バージョン 3.13 で変更: @ref{6a,,grp} モジュールが利用できない場合 @ref{533,,UnsupportedOperation} を送出します。以前のバージョンでは @ref{36b,,NotImplementedError} を送出していました。



バージョン 3.13 で変更: `follow_symlinks' パラメータが追加されました。

@end deffn

@geindex chmod() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path chmod}@anchor{a25}
@deffn {メソッド} Path.chmod (mode, *, follow_symlinks=True)

@ref{529,,os.chmod()} のようにファイルのモードとアクセス権限を変更します。

このメソッドは通常シンボリックリンクをたどります。一部のUnixではシンボリックリンク自体のパーミッション変更をサポートしています。そのようなプラットフォームでは引数に`@w{`}follow_symlinks=False`@w{`} を追加するか、@ref{2c42,,lchmod()} を使用してください。

@example
>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060
@end example


バージョン 3.10 で変更: `follow_symlinks' パラメータが追加されました。

@end deffn

@geindex lchmod() (pathlib.Path のメソッド)
@anchor{library/pathlib pathlib Path lchmod}@anchor{2c42}
@deffn {メソッド} Path.lchmod (mode)

@ref{a25,,Path.chmod()} のように振る舞いますが、パスがシンボリックリンクを指していた場合、リンク先ではなくシンボリックリンク自身のモードが変更されます。
@end deffn

@node Pattern language,glob モジュールとの比較,具象パス,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib pathlib-pattern-language}@anchor{2c31}@anchor{library/pathlib pattern-language}@anchor{2c43}
@subsubsection Pattern language


The following wildcards are supported in patterns for
@ref{535,,full_match()}, @ref{537,,glob()} and @ref{538,,rglob()}:


@table @asis

@item @code{**} (entire segment)

Matches any number of file or directory segments, including zero.

@item @code{*} (entire segment)

Matches one file or directory segment.

@item @code{*} (part of a segment)

Matches any number of non-separator characters, including zero.

@item @code{?}

Matches one non-separator character.

@item @code{[seq]}

Matches one character in `seq', where `seq' is a sequence of characters.
Range expressions are supported; for example, @code{[a-z]} matches any lowercase ASCII letter.
Multiple ranges can be combined: @code{[a-zA-Z0-9_]} matches any ASCII letter, digit, or underscore.

@item @code{[!seq]}

Matches one character not in `seq', where `seq' follows the same rules as above.
@end table

リテラルにマッチさせるには、メタ文字を括弧に入れてください。例えば、@code{"[?]"} は文字 @code{"?"} にマッチします。

The "@code{**}" wildcard enables recursive globbing. A few examples:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Pattern

@tab

意味

@item

"@code{**/*}"

@tab

1つ以上の要素がある任意のパス。

@item

"@code{**/*.py}"

@tab

最後の要素が "@code{.py}" で終わる任意のパス。

@item

"@code{assets/**}"

@tab

"@code{assets/}" で始まる任意のパス。

@item

"@code{assets/**/*}"

@tab

"@code{assets/}" で始まる任意のパス("@code{assets/}" 自身を除く)。

@end multitable


@cartouche
@quotation 注釈 
Globbing with the "@code{**}" wildcard visits every directory in the tree.
Large directory trees may take a long time to search.
@end quotation
@end cartouche


バージョン 3.13 で変更: Globbing with a pattern that ends with "@code{**}" returns both files and
directories. In previous versions, only directories were returned.


In @ref{537,,Path.glob()} and @ref{538,,rglob()}, a trailing slash may be added to
the pattern to match only directories.


バージョン 3.11 で変更: Globbing with a pattern that ends with a pathname components separator
(@ref{87a,,sep} or @ref{87b,,altsep}) returns only directories.


@node glob モジュールとの比較,os と os path モジュールの比較,Pattern language,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib comparison-to-the-glob-module}@anchor{2c44}
@subsubsection @code{glob} モジュールとの比較


The patterns accepted and results generated by @ref{537,,Path.glob()} and
@ref{538,,Path.rglob()} differ slightly from those by the @ref{68,,glob} module:


@enumerate 

@item 
Files beginning with a dot are not special in pathlib. This is
like passing @code{include_hidden=True} to @ref{5a0,,glob.glob()}.

@item 
"@code{**}" pattern components are always recursive in pathlib. This is like
passing @code{recursive=True} to @ref{5a0,,glob.glob()}.

@item 
"@code{**}" pattern components do not follow symlinks by default in pathlib.
This behaviour has no equivalent in @ref{5a0,,glob.glob()}, but you can pass
@code{recurse_symlinks=True} to @ref{537,,Path.glob()} for compatible behaviour.

@item 
Like all @ref{6cd,,PurePath} and @ref{266,,Path} objects, the values returned
from @ref{537,,Path.glob()} and @ref{538,,Path.rglob()} don't include trailing
slashes.

@item 
The values returned from pathlib's @code{path.glob()} and @code{path.rglob()}
include the `path' as a prefix, unlike the results of
@code{glob.glob(root_dir=path)}.

@item 
The values returned from pathlib's @code{path.glob()} and @code{path.rglob()}
may include `path' itself, for example when globbing "@code{**}", whereas the
results of @code{glob.glob(root_dir=path)} never include an empty string that
would correspond to `path'.
@end enumerate

@node os と os path モジュールの比較,プロトコル,glob モジュールとの比較,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib comparison-to-the-os-and-os-path-modules}@anchor{2c45}
@subsubsection @code{os} と @code{os.path} モジュールの比較


pathlib implements path operations using @ref{6cd,,PurePath} and @ref{266,,Path}
objects, and so it's said to be `object-oriented'. On the other hand, the
@ref{a5,,os} and @ref{a6,,os.path} modules supply functions that work with low-level
@code{str} and @code{bytes} objects, which is a more `procedural' approach. Some
users consider the object-oriented style to be more readable.

Many functions in @ref{a5,,os} and @ref{a6,,os.path} support @code{bytes} paths and
@ref{1302,,paths relative to directory descriptors}. These features aren't
available in pathlib.

Python's @code{str} and @code{bytes} types, and portions of the @ref{a5,,os} and
@ref{a6,,os.path} modules, are written in C and are very speedy. pathlib is
written in pure Python and is often slower, but rarely slow enough to matter.

pathlib's path normalization is slightly more opinionated and consistent than
@ref{a6,,os.path}. For example, whereas @ref{1532,,os.path.abspath()} eliminates
"@code{..}" segments from a path, which may change its meaning if symlinks are
involved, @ref{1a26,,Path.absolute()} preserves these segments for greater safety.

pathlib's path normalization may render it unsuitable for some applications:


@enumerate 

@item 
pathlib normalizes @code{Path("my_folder/")} to @code{Path("my_folder")}, which
changes a path's meaning when supplied to various operating system APIs and
command-line utilities. Specifically, the absence of a trailing separator
may allow the path to be resolved as either a file or directory, rather
than a directory only.

@item 
pathlib normalizes @code{Path("./my_program")} to @code{Path("my_program")},
which changes a path's meaning when used as an executable search path, such
as in a shell or when spawning a child process. Specifically, the absence
of a separator in the path may force it to be looked up in 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}
rather than the current directory.
@end enumerate

As a consequence of these differences, pathlib is not a drop-in replacement
for @ref{a6,,os.path}.

@menu
* 対応するツール:: 

@end menu

@node 対応するツール,,,os と os path モジュールの比較
@anchor{library/pathlib corresponding-tools}@anchor{2c46}
@subsubsection 対応するツール


下にあるのは、様々な @ref{a5,,os} 関数とそれに相当する @ref{6cd,,PurePath} あるいは @ref{266,,Path} の同等のものとの対応表です。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@ref{a5,,os} と @ref{a6,,os.path}

@tab

@code{pathlib}

@item

@ref{2c47,,os.path.dirname()}

@tab

@ref{1a9d,,PurePath.parent}

@item

@ref{2c48,,os.path.basename()}

@tab

@ref{2c2d,,PurePath.name}

@item

@ref{1959,,os.path.splitext()}

@tab

@ref{2c2e,,PurePath.stem}, @ref{1957,,PurePath.suffix}

@item

@ref{19a9,,os.path.join()}

@tab

@ref{2c30,,PurePath.joinpath()}

@item

@ref{531,,os.path.isabs()}

@tab

@ref{1a9c,,PurePath.is_absolute()}

@item

@ref{6d1,,os.path.relpath()}

@tab

@ref{2fd,,PurePath.relative_to()} @footnote{
@ref{6d1,,os.path.relpath()} calls @ref{1532,,abspath()} to make paths
absolute and remove "@code{..}" parts, whereas @ref{2fd,,PurePath.relative_to()}
is a lexical operation that raises @ref{2ec,,ValueError} when its inputs'
anchors differ (e.g. if one path is absolute and the other relative.)
}

@item

@ref{c09,,os.path.expanduser()}

@tab

@ref{1042,,Path.expanduser()} @footnote{
@ref{c09,,os.path.expanduser()} returns the path unchanged if the home
directory can't be resolved, whereas @ref{1042,,Path.expanduser()} raises
@ref{244,,RuntimeError}.
}

@item

@ref{262,,os.path.realpath()}

@tab

@ref{1a6d,,Path.resolve()}

@item

@ref{1532,,os.path.abspath()}

@tab

@ref{1a26,,Path.absolute()} @footnote{
@ref{1532,,os.path.abspath()} removes "@code{..}" components without resolving
symlinks, which may change the meaning of the path, whereas
@ref{1a26,,Path.absolute()} leaves any "@code{..}" components in the path.
}

@item

@ref{c03,,os.path.exists()}

@tab

@ref{c0b,,Path.exists()}

@item

@ref{c06,,os.path.isfile()}

@tab

@ref{539,,Path.is_file()}

@item

@ref{c05,,os.path.isdir()}

@tab

@ref{53a,,Path.is_dir()}

@item

@ref{c01,,os.path.islink()}

@tab

@ref{c0d,,Path.is_symlink()}

@item

@ref{6ca,,os.path.isjunction()}

@tab

@ref{6d2,,Path.is_junction()}

@item

@ref{c07,,os.path.ismount()}

@tab

@ref{c0c,,Path.is_mount()}

@item

@ref{1173,,os.path.samefile()}

@tab

@ref{1040,,Path.samefile()}

@item

@ref{1909,,os.getcwd()}

@tab

@ref{1a9b,,Path.cwd()}

@item

@ref{26d,,os.stat()}

@tab

@ref{a24,,Path.stat()}

@item

@ref{6c8,,os.lstat()}

@tab

@ref{2c38,,Path.lstat()}

@item

@ref{1312,,os.listdir()}

@tab

@ref{26e,,Path.iterdir()}

@item

@ref{6d0,,os.walk()}

@tab

@ref{6cf,,Path.walk()} @footnote{
@ref{6d0,,os.walk()} always follows symlinks when categorizing paths into
`dirnames' and `filenames', whereas @ref{6cf,,Path.walk()} categorizes all
symlinks into `filenames' when `follow_symlinks' is false (the default.)
}

@item

@ref{52b,,os.mkdir()}, @ref{52c,,os.makedirs()}

@tab

@ref{1041,,Path.mkdir()}

@item

@ref{1307,,os.link()}

@tab

@ref{a22,,Path.hardlink_to()}

@item

@ref{130c,,os.symlink()}

@tab

@ref{a23,,Path.symlink_to()}

@item

@ref{b1a,,os.readlink()}

@tab

@ref{b19,,Path.readlink()}

@item

@ref{1309,,os.rename()}

@tab

@ref{1891,,Path.rename()}

@item

@ref{130a,,os.replace()}

@tab

@ref{2c40,,Path.replace()}

@item

@ref{1308,,os.remove()}, @ref{130d,,os.unlink()}

@tab

@ref{1dd5,,Path.unlink()}

@item

@ref{130b,,os.rmdir()}

@tab

@ref{2c3c,,Path.rmdir()}

@item

@ref{529,,os.chmod()}

@tab

@ref{a25,,Path.chmod()}

@item

@ref{528,,os.lchmod()}

@tab

@ref{2c42,,Path.lchmod()}

@end multitable


@subsubheading 脚注


@node プロトコル,,os と os path モジュールの比較,pathlib --- オブジェクト指向のファイルシステムパス
@anchor{library/pathlib module-pathlib types}@anchor{a9}@anchor{library/pathlib protocols}@anchor{2c49}
@subsubsection プロトコル


@geindex module; pathlib.types

The @code{pathlib.types} module provides types for static type checking.


Added in version 3.14.


@geindex PathInfo (pathlib.types のクラス)
@anchor{library/pathlib pathlib types PathInfo}@anchor{26c}
@deffn {クラス} pathlib.types.PathInfo

A @ref{56b,,typing.Protocol} describing the
@ref{26b,,Path.info} attribute. Implementations may
return cached results from their methods.

@geindex exists() (pathlib.types.PathInfo のメソッド)
@anchor{library/pathlib pathlib types PathInfo exists}@anchor{2c4a}
@deffn {メソッド} exists (*, follow_symlinks=True)

Return @code{True} if the path is an existing file or directory, or any
other kind of file; return @code{False} if the path doesn't exist.

If `follow_symlinks' is @code{False}, return @code{True} for symlinks without
checking if their targets exist.
@end deffn

@geindex is_dir() (pathlib.types.PathInfo のメソッド)
@anchor{library/pathlib pathlib types PathInfo is_dir}@anchor{2c4b}
@deffn {メソッド} is_dir (*, follow_symlinks=True)

Return @code{True} if the path is a directory, or a symbolic link pointing
to a directory; return @code{False} if the path is (or points to) any other
kind of file, or if it doesn't exist.

If `follow_symlinks' is @code{False}, return @code{True} only if the path
is a directory (without following symlinks); return @code{False} if the
path is any other kind of file, or if it doesn't exist.
@end deffn

@geindex is_file() (pathlib.types.PathInfo のメソッド)
@anchor{library/pathlib pathlib types PathInfo is_file}@anchor{2c4c}
@deffn {メソッド} is_file (*, follow_symlinks=True)

Return @code{True} if the path is a file, or a symbolic link pointing to
a file; return @code{False} if the path is (or points to) a directory or
other non-file, or if it doesn't exist.

If `follow_symlinks' is @code{False}, return @code{True} only if the path
is a file (without following symlinks); return @code{False} if the path
is a directory or other non-file, or if it doesn't exist.
@end deffn

@geindex is_symlink() (pathlib.types.PathInfo のメソッド)
@anchor{library/pathlib pathlib types PathInfo is_symlink}@anchor{2c4d}
@deffn {メソッド} is_symlink ()

Return @code{True} if the path is a symbolic link (even if broken); return
@code{False} if the path is a directory or any kind of file, or if it
doesn't exist.
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node os path --- 一般的なパス名操作,stat --- stat の結果を解釈する,pathlib --- オブジェクト指向のファイルシステムパス,ファイルとディレクトリへのアクセス
@anchor{library/os path doc}@anchor{2c4e}@anchor{library/os path module-os path}@anchor{a6}@anchor{library/os path os-path-common-pathname-manipulations}@anchor{2c4f}@anchor{library/os path translation-repo}@anchor{2c50}
@subsection @code{os.path} --- 一般的なパス名操作


@geindex module; os.path

`ソースコード:' Lib/genericpath.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/genericpath.py}, Lib/posixpath.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/posixpath.py} (POSIX) 、 Lib/ntpath.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/ntpath.py} (Windows) 。

@geindex パス;操作


__________________________________________________________________


このモジュールはパス名を扱う際に便利な関数を実装しています。ファイルの読み書きをする際は @ref{316,,open()} を、ファイルシステムにアクセスするには @ref{a5,,os} モジュールをご参照ください。パスの引数は文字列、バイト列、あるいは @ref{e4b,,os.PathLike} プロトコルを実装するあらゆるオブジェクトとして渡すことができます。

Unix シェルとは異なり、Python はあらゆるパス展開を `自動的には' 行いません。アプリケーションがシェルのようなパス展開を必要とした場合は、 @ref{c09,,expanduser()} や @ref{15f2,,expandvars()} といった関数を明示的に呼び出すことで行えます。(@ref{68,,glob} モジュールも参照してください)


@subsubheading 参考


@ref{a8,,pathlib} モジュールは高水準のパスオブジェクトを提供します。


@cartouche
@quotation 注釈 
以下のすべての関数は、そのパラメータにバイト列のみ、あるいは文字列のみ受け付けます。パスまたはファイル名を返す場合、返り値は同じ型のオブジェクトになります。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
Since different operating systems have different path name conventions, there
are several versions of this module in the standard library.  The
@code{os.path} module is always the path module suitable for the operating
system Python is running on, and therefore usable for local paths.  However,
you can also import and use the individual modules if you want to manipulate
a path that is `always' in one of the different formats.  They all have the
same interface:


@itemize *

@item 
UNIX 形式のパスを扱う @code{posixpath}

@item 
Windows のパスを扱う @code{ntpath}
@end itemize
@end quotation
@end cartouche


バージョン 3.8 で変更: @ref{c03,,exists()}、 @ref{c04,,lexists()}、 @ref{c05,,isdir()}、 @ref{c06,,isfile()}、 @ref{c01,,islink()}、および @ref{c07,,ismount()} は、OS レベルで表現できない文字列を含む可能性がある例外を送出する代わりに @code{False} を返すようになりました。


@geindex abspath() (os.path モジュール)
@anchor{library/os path os path abspath}@anchor{1532}
@deffn {の関数} os.path.abspath (path)

Return a normalized absolutized version of the pathname `path'. On most
platforms, this is equivalent to calling @code{normpath(join(os.getcwd(), path))}.


@subsubheading 参考


@ref{19a9,,os.path.join()} and @ref{1531,,os.path.normpath()}.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex basename() (os.path モジュール)
@anchor{library/os path os path basename}@anchor{2c48}
@deffn {の関数} os.path.basename (path, /)

パス名 `path' の末尾のファイル名部分を返します。これは関数 @ref{2c51,,split()} に `path' を渡した時に返されるペアの 2 番めの要素です。この関数が返すのは Unix の @code{basename} とは異なります; Unix の @code{basename} は @code{'/foo/bar/'} に対して @code{'bar'} を返しますが、関数 @ref{2c48,,basename()} は空文字列 (@code{'@w{'}}) を返します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex commonpath() (os.path モジュール)
@anchor{library/os path os path commonpath}@anchor{103d}
@deffn {の関数} os.path.commonpath (paths)

Return the longest common sub-path of each pathname in the iterable
`paths'.  Raise @ref{2ec,,ValueError} if `paths' contain both absolute
and relative pathnames, if `paths' are on different drives, or
if `paths' is empty.  Unlike @ref{103e,,commonprefix()}, this returns a
valid path.


Added in version 3.5.



バージョン 3.6 で変更: @ref{5a1,,path-like objects} のシーケンスを受け入れるようになりました。



バージョン 3.13 で変更: Any iterable can now be passed, rather than just sequences.

@end deffn

@geindex commonprefix() (os.path モジュール)
@anchor{library/os path os path commonprefix}@anchor{103e}
@deffn {の関数} os.path.commonprefix (list, /)

Return the longest string prefix (taken character-by-character) that is a
prefix of all strings in `list'.  If `list' is empty, return the empty string
(@code{'@w{'}}).

@cartouche
@quotation 警告 
This function may return invalid paths because it works a
character at a time.
If you need a `common path prefix', then the algorithm
implemented in this function is not secure. Use
@ref{103d,,commonpath()} for finding a common path prefix.

@example
>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'
@end example
@end quotation
@end cartouche


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex dirname() (os.path モジュール)
@anchor{library/os path os path dirname}@anchor{2c47}
@deffn {の関数} os.path.dirname (path, /)

パス名 `path' のディレクトリ名を返します。これは関数 @ref{2c51,,split()} に `path' を渡した時に返されるペアの 1 番めの要素です。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex exists() (os.path モジュール)
@anchor{library/os path os path exists}@anchor{c03}
@deffn {の関数} os.path.exists (path)

`path' が実在するパスかオープンしているファイル記述子を参照している場合 @code{True} を返します。壊れたシンボリックリンクについては @code{False} を返します。一部のプラットフォームでは、たとえ `path' が物理的に存在していたとしても、要求されたファイルに対する @ref{26d,,os.stat()} の実行権がなければこの関数が @code{False} を返すことがあります。


バージョン 3.3 で変更: `path' は整数でも可能になりました: それがオープンしているファイル記述子なら @code{True} が返り、それ以外なら @code{False} が返ります。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex lexists() (os.path モジュール)
@anchor{library/os path os path lexists}@anchor{c04}
@deffn {の関数} os.path.lexists (path)

Return @code{True} if `path' refers to an existing path, including
broken symbolic links.   Equivalent to @ref{c03,,exists()} on platforms lacking
@ref{6c8,,os.lstat()}.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex ~ (チルダ);home directory expansion

@geindex expanduser() (os.path モジュール)
@anchor{library/os path os path expanduser}@anchor{c09}
@deffn {の関数} os.path.expanduser (path)

Unix および Windows では、与えられた引数の先頭のパス要素 @code{~} 、または @code{~user} を、 `user' のホームディレクトリのパスに置き換えて返します。

@geindex module;pwd

Unix では、先頭の @code{~} は、環境変数 
@geindex HOME
@geindex 環境変数; HOME
@code{HOME} が設定されているならその値に置き換えられます。設定されていない場合は、現在のユーザのホームディレクトリをビルトインモジュール @ref{b7,,pwd} を使ってパスワードディレクトリから探して置き換えます。先頭の @code{~user} については、直接パスワードディレクトリから探します。

On Windows, 
@geindex USERPROFILE
@geindex 環境変数; USERPROFILE
@code{USERPROFILE} will be used if set, otherwise a combination
of 
@geindex HOMEPATH
@geindex 環境変数; HOMEPATH
@code{HOMEPATH} and 
@geindex HOMEDRIVE
@geindex 環境変数; HOMEDRIVE
@code{HOMEDRIVE} will be used.  An initial
@code{~user} is handled by checking that the last directory component of the current
user's home directory matches 
@geindex USERNAME
@geindex 環境変数; USERNAME
@code{USERNAME}, and replacing it if so.

置き換えに失敗したり、引数のパスがチルダで始まっていなかった場合は、パスをそのまま返します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.8 で変更: Windowsで  
@geindex HOME
@geindex 環境変数; HOME
@code{HOME} は参照しなくなりました。

@end deffn

@geindex $ (ダラー);environment variables expansion
@geindex % (パーセント);environment variables expansion (Windows)

@geindex expandvars() (os.path モジュール)
@anchor{library/os path os path expandvars}@anchor{15f2}
@deffn {の関数} os.path.expandvars (path)

引数のパスの環境変数を展開して返します。引数の中の @code{$name} または @code{$@{name@}} のような形式の文字列は環境変数、 `name' の値に置き換えられます。不正な変数名や存在しない変数名の場合には変換されず、そのまま返します。

Windows では、 @code{$name} や @code{$@{name@}} の形式に加えて、 @code{%name%} の形式もサポートされています。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex getatime() (os.path モジュール)
@anchor{library/os path os path getatime}@anchor{2c52}
@deffn {の関数} os.path.getatime (path, /)

Return the time of last access of `path'.  The return value is a floating-point number giving
the number of seconds since the epoch (see the  @ref{f4,,time} module).  Raise
@ref{2c0,,OSError} if the file does not exist or is inaccessible.
@end deffn

@geindex getmtime() (os.path モジュール)
@anchor{library/os path os path getmtime}@anchor{2c53}
@deffn {の関数} os.path.getmtime (path, /)

Return the time of last modification of `path'.  The return value is a floating-point number
giving the number of seconds since the epoch (see the  @ref{f4,,time} module).
Raise @ref{2c0,,OSError} if the file does not exist or is inaccessible.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex getctime() (os.path モジュール)
@anchor{library/os path os path getctime}@anchor{2c54}
@deffn {の関数} os.path.getctime (path, /)

システムの ctime、Unix系など一部のシステムでは最後にメタデータが変更された時刻、Windows などその他のシステムでは `path' の作成時刻を返します。返り値はエポック (@ref{f4,,time} モジュールを参照) からの経過時間を示す秒数になります。ファイルが存在しない、あるいはアクセスできなかった場合は @ref{2c0,,OSError} を送出します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex getsize() (os.path モジュール)
@anchor{library/os path os path getsize}@anchor{2c55}
@deffn {の関数} os.path.getsize (path, /)

`path' のサイズをバイト数で返します。ファイルが存在しない、あるいはアクセスできなかった場合は @ref{2c0,,OSError} を送出します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex isabs() (os.path モジュール)
@anchor{library/os path os path isabs}@anchor{531}
@deffn {の関数} os.path.isabs (path, /)

Return @code{True} if `path' is an absolute pathname.  On Unix, that means it
begins with a slash, on Windows that it begins with two (back)slashes, or a
drive letter, colon, and (back)slash together.


@subsubheading 参考


@ref{1532,,abspath()}



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.13 で変更: On Windows, returns @code{False} if the given path starts with exactly one
(back)slash.

@end deffn

@geindex isfile() (os.path モジュール)
@anchor{library/os path os path isfile}@anchor{c06}
@deffn {の関数} os.path.isfile (path)

`path' が @ref{c03,,存在する} 一般ファイルなら @code{True} を返します。
この関数はシンボリックリンクの先を辿るので、同じパスに対して @ref{c01,,islink()} と @ref{c06,,isfile()} の両方が真を返すことがあります。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex isdir() (os.path モジュール)
@anchor{library/os path os path isdir}@anchor{c05}
@deffn {の関数} os.path.isdir (path, /)

`path' が @ref{c03,,存在する} ディレクトリなら @code{True} を返します。
この関数はシンボリックリンクの先を辿るので、同じパスに対して @ref{c01,,islink()} と @ref{c05,,isdir()} の両方が真を返すことがあります。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex isjunction() (os.path モジュール)
@anchor{library/os path os path isjunction}@anchor{6ca}
@deffn {の関数} os.path.isjunction (path)

Return @code{True} if `path' refers to an @ref{c04,,existing} directory
entry that is a junction.  Always return @code{False} if junctions are not
supported on the current platform.


Added in version 3.12.

@end deffn

@geindex islink() (os.path モジュール)
@anchor{library/os path os path islink}@anchor{c01}
@deffn {の関数} os.path.islink (path)

`path' が @ref{c03,,存在する} ディレクトリを指すシンボリックリンクなら @code{True} を返します。
Python ランタイムがシンボリックリンクをサポートしていないプラットフォームでは、常に @code{False} を返します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex ismount() (os.path モジュール)
@anchor{library/os path os path ismount}@anchor{c07}
@deffn {の関数} os.path.ismount (path)

Return @code{True} if pathname `path' is a `mount point': a point in a
file system where a different file system has been mounted.  On POSIX, the
function checks whether `path''s parent, @code{`path'/..}, is on a different
device than `path', or whether @code{`path'/..} and `path' point to the same
i-node on the same device --- this should detect mount points for all Unix
and POSIX variants.  It is not able to reliably detect bind mounts on the
same filesystem. On Linux systems, it will always return @code{True} for btrfs
subvolumes, even if they aren't mount points. On Windows, a drive letter root
and a share UNC are always mount points, and for any other path
@code{GetVolumePathName} is called to see if it is different from the input path.


バージョン 3.4 で変更: Added support for detecting non-root mount points on Windows.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex isdevdrive() (os.path モジュール)
@anchor{library/os path os path isdevdrive}@anchor{19c2}
@deffn {の関数} os.path.isdevdrive (path)

Return @code{True} if pathname `path' is located on a Windows Dev Drive.
A Dev Drive is optimized for developer scenarios, and offers faster
performance for reading and writing files. It is recommended for use for
source code, temporary build directories, package caches, and other
IO-intensive operations.

May raise an error for an invalid path, for example, one without a
recognizable drive, but returns @code{False} on platforms that do not support
Dev Drives. See the Windows documentation@footnote{https://learn.microsoft.com/windows/dev-drive/}
for information on enabling and creating Dev Drives.


Added in version 3.12.



バージョン 3.13 で変更: The function is now available on all platforms, and will always return @code{False} on those that have no support for Dev Drives

@end deffn

@geindex isreserved() (os.path モジュール)
@anchor{library/os path os path isreserved}@anchor{32b}
@deffn {の関数} os.path.isreserved (path)

Return @code{True} if `path' is a reserved pathname on the current system.

On Windows, reserved filenames include those that end with a space or dot;
those that contain colons (i.e. file streams such as "name:stream"),
wildcard characters (i.e. @code{'*?"<>'}), pipe, or ASCII control characters;
as well as DOS device names such as "NUL", "CON", "CONIN$", "CONOUT$",
"AUX", "PRN", "COM1", and "LPT1".

@cartouche
@quotation 注釈 
This function approximates rules for reserved paths on most Windows
systems. These rules change over time in various Windows releases.
This function may be updated in future Python releases as changes to
the rules become broadly available.
@end quotation
@end cartouche

@ref{213f,,Availability}: Windows.


Added in version 3.13.

@end deffn

@geindex join() (os.path モジュール)
@anchor{library/os path os path join}@anchor{19a9}
@deffn {の関数} os.path.join (path, /, *paths)

Join one or more path segments intelligently.  The return value is the
concatenation of `path' and all members of `*paths', with exactly one
directory separator following each non-empty part, except the last. That is,
the result will only end in a separator if the last part is either empty or
ends in a separator.

If a segment is an absolute path (which on Windows requires both a drive and
a root), then all previous segments are ignored and joining continues from the
absolute path segment. On Linux, for example:

@example
>>> os.path.join('/home/foo', 'bar')
'/home/foo/bar'
>>> os.path.join('/home/foo', '/home/bar')
'/home/bar'
@end example

On Windows, the drive is not reset when a rooted path segment (e.g.,
@code{r'\foo'}) is encountered. If a segment is on a different drive or is an
absolute path, all previous segments are ignored and the drive is reset. For
example:

@example
>>> os.path.join('c:\\', 'foo')
'c:\\foo'
>>> os.path.join('c:\\foo', 'd:\\bar')
'd:\\bar'
@end example

Note that since there is a current directory for each drive,
@code{os.path.join("c:", "foo")} represents a path relative to the current
directory on drive @code{C:} (@code{c:foo}), not @code{c:\foo}.


バージョン 3.6 で変更: `path' と `paths' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex normcase() (os.path モジュール)
@anchor{library/os path os path normcase}@anchor{2c56}
@deffn {の関数} os.path.normcase (path, /)

パス名の大文字・小文字を正規化します。
Windowsでは、パス名にある文字を全て小文字に、スラッシュをバックスラッシュに変換します。
他のオペレーティングシステムでは、パスを変更せずに返します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex normpath() (os.path モジュール)
@anchor{library/os path os path normpath}@anchor{1531}
@deffn {の関数} os.path.normpath (path)

パスを正規化します。余分な区切り文字や上位レベル参照を除去し、@code{A//B}、@code{A/B/}、@code{A/./B} や @code{A/foo/../B} などはすべて @code{A/B} になります。この文字列操作は、シンボリックリンクを含むパスの意味を変えてしまう場合があります。Windows では、スラッシュをバックスラッシュに変換します。大文字小文字の正規化には @ref{2c56,,normcase()} を使用してください。

@cartouche
@quotation 注釈 
On POSIX systems, in accordance with IEEE Std 1003.1 2013 Edition; 4.13 Pathname Resolution@footnote{https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13},
if a pathname begins with exactly two slashes, the first component
following the leading characters may be interpreted in an implementation-defined
manner, although more than two leading characters shall be treated as a
single character.
@end quotation
@end cartouche


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex realpath() (os.path モジュール)
@anchor{library/os path os path realpath}@anchor{262}
@deffn {の関数} os.path.realpath (path, /, *, strict=False)

Return the canonical path of the specified filename, eliminating any symbolic
links encountered in the path (if they are supported by the operating
system). On Windows, this function will also resolve MS-DOS (also called 8.3)
style names such as @code{C:\\PROGRA~1} to @code{C:\\Program Files}.

By default, the path is evaluated up to the first component that does not
exist, is a symlink loop, or whose evaluation raises @ref{2c0,,OSError}.
All such components are appended unchanged to the existing part of the path.

Some errors that are handled this way include "access denied", "not a
directory", or "bad argument to internal function". Thus, the
resulting path may be missing or inaccessible, may still contain
links or loops, and may traverse non-directories.

This behavior can be modified by keyword arguments:

If `strict' is @code{True}, the first error encountered when evaluating the path is
re-raised.
In particular, @ref{264,,FileNotFoundError} is raised if `path' does not exist,
or another @ref{2c0,,OSError} if it is otherwise inaccessible.

If `strict' is @ref{263,,os.path.ALLOW_MISSING}, errors other than
@ref{264,,FileNotFoundError} are re-raised (as with @code{strict=True}).
Thus, the returned path will not contain any symbolic links, but the named
file and some of its parent directories may be missing.

@cartouche
@quotation 注釈 
This function emulates the operating system's procedure for making a path
canonical, which differs slightly between Windows and UNIX with respect
to how links and subsequent path components interact.

Operating system APIs make paths canonical as needed, so it's not
normally necessary to call this function.
@end quotation
@end cartouche


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.8 で変更: Windows においてシンボリックリンクとジャンクションが解決されるようになりました。



バージョン 3.10 で変更: `strict' 引数が追加されました。



バージョン 3.14 で変更: The @ref{263,,ALLOW_MISSING} value for the `strict' parameter
was added.

@end deffn

@geindex ALLOW_MISSING (os.path モジュール)
@anchor{library/os path os path ALLOW_MISSING}@anchor{263}
@deffn {データ} os.path.ALLOW_MISSING

Special value used for the `strict' argument in @ref{262,,realpath()}.


Added in version 3.14.

@end deffn

@geindex relpath() (os.path モジュール)
@anchor{library/os path os path relpath}@anchor{6d1}
@deffn {の関数} os.path.relpath (path, start=os.curdir)

カレントディレクトリあるいはオプションの `start' ディレクトリからの `path' への相対パスを返します。これはパス計算で行っており、ファイルシステムにアクセスして `path' や `start' の存在や性質を確認することはありません。Windowsでは、 `path' と `start' が異なるドライブの場合、 @ref{2ec,,ValueError} を送出します。

`start' defaults to @ref{2c57,,os.curdir}.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex samefile() (os.path モジュール)
@anchor{library/os path os path samefile}@anchor{1173}
@deffn {の関数} os.path.samefile (path1, path2, /)

引数の両パス名が同じファイルまたはディレクトリを参照している場合、 @code{True} を返します。これは、デバイス番号と i-node 番号で決定されます。どちらかのパス名への @ref{26d,,os.stat()} 呼び出しが失敗した場合、例外が送出されます。


バージョン 3.2 で変更: Windows サポートを追加しました。



バージョン 3.4 で変更: Windows が他のプラットフォームと同じ実装を使用するようになりました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex sameopenfile() (os.path モジュール)
@anchor{library/os path os path sameopenfile}@anchor{2c58}
@deffn {の関数} os.path.sameopenfile (fp1, fp2)

ファイル記述子 `fp1' と `fp2' が同じファイルを参照していたら @code{True} を返します。


バージョン 3.2 で変更: Windows サポートを追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex samestat() (os.path モジュール)
@anchor{library/os path os path samestat}@anchor{1172}
@deffn {の関数} os.path.samestat (stat1, stat2, /)

stat タプル `stat1' と `stat2' が同じファイルを参照していれば @code{True} を返します。これらのタプルは @ref{f8c,,os.fstat()} 、 @ref{6c8,,os.lstat()} あるいは @ref{26d,,os.stat()} の返り値で構いません。この関数は @ref{1173,,samefile()} と @ref{2c58,,sameopenfile()} を使用した比較に基いて実装しています。


バージョン 3.4 で変更: Windows サポートを追加しました。

@end deffn

@geindex split() (os.path モジュール)
@anchor{library/os path os path split}@anchor{2c51}
@deffn {の関数} os.path.split (path, /)

Split the pathname `path' into a pair, @code{(head, tail)} where `tail' is the
last pathname component and `head' is everything leading up to that.  The
`tail' part will never contain a slash; if `path' ends in a slash, `tail'
will be empty.  If there is no slash in `path', `head' will be empty.  If
`path' is empty, both `head' and `tail' are empty.  Trailing slashes are
stripped from `head' unless it is the root (one or more slashes only).  In
all cases, @code{join(head, tail)} returns a path to the same location as `path'
(but the strings may differ).  Also see the functions @ref{19a9,,join()},
@ref{2c47,,dirname()} and @ref{2c48,,basename()}.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex splitdrive() (os.path モジュール)
@anchor{library/os path os path splitdrive}@anchor{def}
@deffn {の関数} os.path.splitdrive (path, /)

パス名 `path' を @code{(drive, tail)} のペアに分割します。`drive' はマウントポイントか空文字列になります。ドライブ指定をサポートしていないシステムでは、`drive' は常に空文字になります。どの場合でも、@code{drive + tail} は `path' と等しくなります。

Windows では、パス名はドライブ名/UNC 共有ポイントと相対パスに分割されます。

パスがドライブレターを含む場合、ドライブレターにはコロンまでが含まれます:

@example
>>> splitdrive("c:/dir")
("c:", "/dir")
@end example

If the path contains a UNC path, drive will contain the host name
and share:

@example
>>> splitdrive("//host/computer/dir")
("//host/computer", "/dir")
@end example


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex splitroot() (os.path モジュール)
@anchor{library/os path os path splitroot}@anchor{6cb}
@deffn {の関数} os.path.splitroot (path, /)

Split the pathname `path' into a 3-item tuple @code{(drive, root, tail)} where
`drive' is a device name or mount point, `root' is a string of separators
after the drive, and `tail' is everything after the root. Any of these
items may be the empty string. In all cases, @code{drive + root + tail} will
be the same as `path'.

On POSIX systems, `drive' is always empty. The `root' may be empty (if `path' is
relative), a single forward slash (if `path' is absolute), or two forward slashes
(implementation-defined per IEEE Std 1003.1-2017; 4.13 Pathname Resolution@footnote{https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13}.)
For example:

@example
>>> splitroot('/home/sam')
('@w{'}, '/', 'home/sam')
>>> splitroot('//home/sam')
('@w{'}, '//', 'home/sam')
>>> splitroot('///home/sam')
('@w{'}, '/', '//home/sam')
@end example

On Windows, `drive' may be empty, a drive-letter name, a UNC share, or a device
name. The `root' may be empty, a forward slash, or a backward slash. For
example:

@example
>>> splitroot('C:/Users/Sam')
('C:', '/', 'Users/Sam')
>>> splitroot('//Server/Share/Users/Sam')
('//Server/Share', '/', 'Users/Sam')
@end example


Added in version 3.12.

@end deffn

@geindex splitext() (os.path モジュール)
@anchor{library/os path os path splitext}@anchor{1959}
@deffn {の関数} os.path.splitext (path, /)

Split the pathname `path' into a pair @code{(root, ext)}  such that @code{root + ext ==
path}, and the extension, `ext', is empty or begins with a period and contains at
most one period.

If the path contains no extension, `ext' will be @code{'@w{'}}:

@example
>>> splitext('bar')
('bar', '@w{'})
@end example

If the path contains an extension, then `ext' will be set to this extension,
including the leading period. Note that previous periods will be ignored:

@example
>>> splitext('foo.bar.exe')
('foo.bar', '.exe')
>>> splitext('/foo/bar.exe')
('/foo/bar', '.exe')
@end example

Leading periods of the last component of the path are considered to
be part of the root:

@example
>>> splitext('.cshrc')
('.cshrc', '@w{'})
>>> splitext('/foo/....jpg')
('/foo/....jpg', '@w{'})
@end example


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex supports_unicode_filenames (os.path モジュール)
@anchor{library/os path os path supports_unicode_filenames}@anchor{16a7}
@deffn {データ} os.path.supports_unicode_filenames

ファイル名に任意の Unicode 文字列を (システムの制限内で) 使用できる場合は @code{True} になります。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node stat --- stat の結果を解釈する,filecmp --- ファイルとディレクトリの比較,os path --- 一般的なパス名操作,ファイルとディレクトリへのアクセス
@anchor{library/stat doc}@anchor{2c59}@anchor{library/stat module-stat}@anchor{d6}@anchor{library/stat stat-interpreting-stat-results}@anchor{2c5a}@anchor{library/stat translation-repo}@anchor{2c5b}
@subsection @code{stat} --- @code{stat()} の結果を解釈する


@geindex module; stat

`ソースコード:' Lib/stat.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/stat.py}


__________________________________________________________________


The @code{stat} module defines constants and functions for interpreting the
results of @ref{26d,,os.stat()}, @ref{f8c,,os.fstat()} and @ref{6c8,,os.lstat()} (if they
exist).  For complete details about the @code{stat()}, @code{fstat()} and
@code{lstat()} calls, consult the documentation for your system.


バージョン 3.4 で変更: stat モジュールは、C 実装に裏付けされるようになりました。


The @code{stat} module defines the following functions to test for specific file
types:

@geindex S_ISDIR() (stat モジュール)
@anchor{library/stat stat S_ISDIR}@anchor{2c5c}
@deffn {の関数} stat.S_ISDIR (mode)

ファイルのモードがディレクトリの場合にゼロでない値を返します。
@end deffn

@geindex S_ISCHR() (stat モジュール)
@anchor{library/stat stat S_ISCHR}@anchor{2c5d}
@deffn {の関数} stat.S_ISCHR (mode)

ファイルのモードがキャラクタ型の特殊デバイスファイルの場合にゼロでない値を返します。
@end deffn

@geindex S_ISBLK() (stat モジュール)
@anchor{library/stat stat S_ISBLK}@anchor{2c5e}
@deffn {の関数} stat.S_ISBLK (mode)

ファイルのモードがブロック型の特殊デバイスファイルの場合にゼロでない値を返します。
@end deffn

@geindex S_ISREG() (stat モジュール)
@anchor{library/stat stat S_ISREG}@anchor{2c5f}
@deffn {の関数} stat.S_ISREG (mode)

ファイルのモードが通常ファイルの場合にゼロでない値を返します。
@end deffn

@geindex S_ISFIFO() (stat モジュール)
@anchor{library/stat stat S_ISFIFO}@anchor{2c60}
@deffn {の関数} stat.S_ISFIFO (mode)

ファイルのモードが FIFO (名前つきパイプ) の場合にゼロでない値を返します。
@end deffn

@geindex S_ISLNK() (stat モジュール)
@anchor{library/stat stat S_ISLNK}@anchor{2c61}
@deffn {の関数} stat.S_ISLNK (mode)

ファイルのモードがシンボリックリンクの場合にゼロでない値を返します。
@end deffn

@geindex S_ISSOCK() (stat モジュール)
@anchor{library/stat stat S_ISSOCK}@anchor{2c62}
@deffn {の関数} stat.S_ISSOCK (mode)

ファイルのモードがソケットの場合にゼロでない値を返します。
@end deffn

@geindex S_ISDOOR() (stat モジュール)
@anchor{library/stat stat S_ISDOOR}@anchor{1dab}
@deffn {の関数} stat.S_ISDOOR (mode)

ファイルのモードがドアの場合にゼロでない値を返します。


Added in version 3.4.

@end deffn

@geindex S_ISPORT() (stat モジュール)
@anchor{library/stat stat S_ISPORT}@anchor{1dac}
@deffn {の関数} stat.S_ISPORT (mode)

ファイルのモードがイベントポートの場合にゼロでない値を返します。


Added in version 3.4.

@end deffn

@geindex S_ISWHT() (stat モジュール)
@anchor{library/stat stat S_ISWHT}@anchor{1dad}
@deffn {の関数} stat.S_ISWHT (mode)

ファイルのモードがホワイトアウトの場合にゼロでない値を返します。


Added in version 3.4.

@end deffn

より一般的なファイルのモードを操作するための二つの関数が定義されています:

@geindex S_IMODE() (stat モジュール)
@anchor{library/stat stat S_IMODE}@anchor{2c63}
@deffn {の関数} stat.S_IMODE (mode)

@ref{529,,os.chmod()} で設定することのできる一部のファイルモード --- すなわち、ファイルの許可ビット (permission bits) に加え、 (サポートされているシステムでは) スティッキービット (sticky bit)、実行グループ ID 設定 (set-group-id) および実行ユーザ ID 設定 (set-user-id) ビット --- を返します。
@end deffn

@geindex S_IFMT() (stat モジュール)
@anchor{library/stat stat S_IFMT}@anchor{2c64}
@deffn {の関数} stat.S_IFMT (mode)

Return the portion of the file's mode that describes the file type (used by the
@code{S_IS*()} functions above).
@end deffn

Normally, you would use the @code{os.path.is*()} functions for testing the type
of a file; the functions here are useful when you are doing multiple tests of
the same file and wish to avoid the overhead of the @code{stat()} system call
for each test.  These are also useful when checking for information about a file
that isn't handled by @ref{a6,,os.path}, like the tests for block and character
devices.

以下はプログラム例です:

@example
import os, sys
from stat import *

def walktree(top, callback):
    '@w{'}'recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'@w{'}'

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.lstat(pathname).st_mode
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print('Skipping %s' % pathname)

def visitfile(file):
    print('visiting', file)

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)
@end example

ファイルのモードを人間が可読な文字列に変換するために、追加のユーティリティ関数が提供されています。

@geindex filemode() (stat モジュール)
@anchor{library/stat stat filemode}@anchor{1363}
@deffn {の関数} stat.filemode (mode)

ファイルのモードを '-rwxrwxrwx' 形式の文字列に変換します。


Added in version 3.3.



バージョン 3.4 で変更: この関数は、@ref{11bd,,S_IFDOOR} 、 @ref{11be,,S_IFPORT} 、 @ref{11bf,,S_IFWHT} をサポートしています。

@end deffn

以下の全ての変数は、 @ref{26d,,os.stat()} 、 @ref{f8c,,os.fstat()} 、または @ref{6c8,,os.lstat()} が返す 10 要素のタプルにおけるインデクスを単にシンボル定数化したものです。

@geindex ST_MODE (stat モジュール)
@anchor{library/stat stat ST_MODE}@anchor{11bc}
@deffn {データ} stat.ST_MODE

Iノードの保護モード。
@end deffn

@geindex ST_INO (stat モジュール)
@anchor{library/stat stat ST_INO}@anchor{2c65}
@deffn {データ} stat.ST_INO

Iノード番号。
@end deffn

@geindex ST_DEV (stat モジュール)
@anchor{library/stat stat ST_DEV}@anchor{2c66}
@deffn {データ} stat.ST_DEV

Iノードが存在するデバイス。
@end deffn

@geindex ST_NLINK (stat モジュール)
@anchor{library/stat stat ST_NLINK}@anchor{2c67}
@deffn {データ} stat.ST_NLINK

該当する Iノードへのリンク数。
@end deffn

@geindex ST_UID (stat モジュール)
@anchor{library/stat stat ST_UID}@anchor{2c68}
@deffn {データ} stat.ST_UID

ファイルの所持者のユーザ ID。
@end deffn

@geindex ST_GID (stat モジュール)
@anchor{library/stat stat ST_GID}@anchor{2c69}
@deffn {データ} stat.ST_GID

ファイルの所持者のグループ ID。
@end deffn

@geindex ST_SIZE (stat モジュール)
@anchor{library/stat stat ST_SIZE}@anchor{2c6a}
@deffn {データ} stat.ST_SIZE

通常ファイルではバイトサイズ; いくつかの特殊ファイルでは処理待ちのデータ量。
@end deffn

@geindex ST_ATIME (stat モジュール)
@anchor{library/stat stat ST_ATIME}@anchor{2c6b}
@deffn {データ} stat.ST_ATIME

最後にアクセスした時刻。
@end deffn

@geindex ST_MTIME (stat モジュール)
@anchor{library/stat stat ST_MTIME}@anchor{2c6c}
@deffn {データ} stat.ST_MTIME

最後に変更された時刻。
@end deffn

@geindex ST_CTIME (stat モジュール)
@anchor{library/stat stat ST_CTIME}@anchor{2c6d}
@deffn {データ} stat.ST_CTIME

オペレーティングシステムから返される"ctime"。あるOS(Unixなど)では最後にメタデータが更新された時間となり、別のOS(Windowsなど)では作成時間となります(詳細については各プラットフォームのドキュメントを参照してください)。
@end deffn

"ファイルサイズ" の解釈はファイルの型によって異なります。通常のファイルの場合、サイズはファイルの大きさをバイトで表したものです。ほとんどの Unix 系 (特に Linux) における FIFO やソケットの場合、"サイズ" は @ref{26d,,os.stat()} 、 @ref{f8c,,os.fstat()} 、あるいは @ref{6c8,,os.lstat()} を呼び出した時点で読み出し待ちであったデータのバイト数になります; この値は時に有用で、特に上記の特殊なファイルを非ブロックモードで開いた後にポーリングを行いたいといった場合に便利です。他のキャラクタ型およびブロック型デバイスにおけるサイズフィールドの意味はさらに異なっていて、背後のシステムコールの実装によります。

以下の変数は、 @ref{11bc,,ST_MODE} フィールドで使用されるフラグを定義しています。

最初に挙げる、以下のフラグを使うよりは、上記の関数を使うほうがポータブルです:

@geindex S_IFSOCK (stat モジュール)
@anchor{library/stat stat S_IFSOCK}@anchor{2c6e}
@deffn {データ} stat.S_IFSOCK

ソケット。
@end deffn

@geindex S_IFLNK (stat モジュール)
@anchor{library/stat stat S_IFLNK}@anchor{2c6f}
@deffn {データ} stat.S_IFLNK

シンボリックリンク。
@end deffn

@geindex S_IFREG (stat モジュール)
@anchor{library/stat stat S_IFREG}@anchor{2c70}
@deffn {データ} stat.S_IFREG

通常のファイル。
@end deffn

@geindex S_IFBLK (stat モジュール)
@anchor{library/stat stat S_IFBLK}@anchor{2c71}
@deffn {データ} stat.S_IFBLK

ブロックデバイス。
@end deffn

@geindex S_IFDIR (stat モジュール)
@anchor{library/stat stat S_IFDIR}@anchor{2c72}
@deffn {データ} stat.S_IFDIR

ディレクトリ。
@end deffn

@geindex S_IFCHR (stat モジュール)
@anchor{library/stat stat S_IFCHR}@anchor{2c73}
@deffn {データ} stat.S_IFCHR

キャラクターデバイス。
@end deffn

@geindex S_IFIFO (stat モジュール)
@anchor{library/stat stat S_IFIFO}@anchor{2c74}
@deffn {データ} stat.S_IFIFO

FIFO。
@end deffn

@geindex S_IFDOOR (stat モジュール)
@anchor{library/stat stat S_IFDOOR}@anchor{11bd}
@deffn {データ} stat.S_IFDOOR

ドア。


Added in version 3.4.

@end deffn

@geindex S_IFPORT (stat モジュール)
@anchor{library/stat stat S_IFPORT}@anchor{11be}
@deffn {データ} stat.S_IFPORT

イベントポート。


Added in version 3.4.

@end deffn

@geindex S_IFWHT (stat モジュール)
@anchor{library/stat stat S_IFWHT}@anchor{11bf}
@deffn {データ} stat.S_IFWHT

ホワイトアウト。


Added in version 3.4.

@end deffn

@cartouche
@quotation 注釈 
@ref{11bd,,S_IFDOOR} 、 @ref{11be,,S_IFPORT} 、または @ref{11bf,,S_IFWHT} は、プラットフォームがこれらのファイルタイプをサポートしていない場合、0 として定義されます。
@end quotation
@end cartouche

以下のフラグは、 @ref{529,,os.chmod()} の `mode' 引数に使うこともできます:

@geindex S_ISUID (stat モジュール)
@anchor{library/stat stat S_ISUID}@anchor{2c75}
@deffn {データ} stat.S_ISUID

UID ビットを設定する。
@end deffn

@geindex S_ISGID (stat モジュール)
@anchor{library/stat stat S_ISGID}@anchor{2c76}
@deffn {データ} stat.S_ISGID

グループIDビットを設定する。このビットには幾つかの特殊ケースがあります。ディレクトリに対して設定されていた場合、 BSD のセマンティクスが利用される事を示しています。すなわち、そこに作成されるファイルは、作成したプロセスの有効グループID (effective group ID) ではなくそのディレクトリのグループIDを継承し、そこに作成されるディレクトリにも @ref{2c76,,S_ISGID} ビットが設定されます。グループ実行ビット (@ref{2c77,,S_IXGRP}) が設定されていないファイルに対してこのビットが設定されていた場合、強制ファイル/レコードロックを意味します (@ref{2c78,,S_ENFMT} も参照してください)。
@end deffn

@geindex S_ISVTX (stat モジュール)
@anchor{library/stat stat S_ISVTX}@anchor{2c79}
@deffn {データ} stat.S_ISVTX

スティッキービット。このビットがディレクトリに対して設定されているとき、そのディレクトリ内のファイルは、そのファイルのオーナー、あるいはそのディレクトリのオーナーか特権プロセスのみが、リネームや削除をすることが出来ることを意味しています。
@end deffn

@geindex S_IRWXU (stat モジュール)
@anchor{library/stat stat S_IRWXU}@anchor{2c7a}
@deffn {データ} stat.S_IRWXU

ファイルオーナーの権限に対するマスク。
@end deffn

@geindex S_IRUSR (stat モジュール)
@anchor{library/stat stat S_IRUSR}@anchor{2c7b}
@deffn {データ} stat.S_IRUSR

オーナーがリード権限を持っている。
@end deffn

@geindex S_IWUSR (stat モジュール)
@anchor{library/stat stat S_IWUSR}@anchor{2c7c}
@deffn {データ} stat.S_IWUSR

オーナーがライト権限を持っている。
@end deffn

@geindex S_IXUSR (stat モジュール)
@anchor{library/stat stat S_IXUSR}@anchor{2c7d}
@deffn {データ} stat.S_IXUSR

オーナーが実行権限を持っている。
@end deffn

@geindex S_IRWXG (stat モジュール)
@anchor{library/stat stat S_IRWXG}@anchor{2c7e}
@deffn {データ} stat.S_IRWXG

グループの権限に対するマスク。
@end deffn

@geindex S_IRGRP (stat モジュール)
@anchor{library/stat stat S_IRGRP}@anchor{2c7f}
@deffn {データ} stat.S_IRGRP

グループがリード権限を持っている。
@end deffn

@geindex S_IWGRP (stat モジュール)
@anchor{library/stat stat S_IWGRP}@anchor{2c80}
@deffn {データ} stat.S_IWGRP

グループがライト権限を持っている。
@end deffn

@geindex S_IXGRP (stat モジュール)
@anchor{library/stat stat S_IXGRP}@anchor{2c77}
@deffn {データ} stat.S_IXGRP

グループが実行権限を持っている。
@end deffn

@geindex S_IRWXO (stat モジュール)
@anchor{library/stat stat S_IRWXO}@anchor{2c81}
@deffn {データ} stat.S_IRWXO

その他 (グループ外) の権限に対するマスク。
@end deffn

@geindex S_IROTH (stat モジュール)
@anchor{library/stat stat S_IROTH}@anchor{2c82}
@deffn {データ} stat.S_IROTH

その他はリード権限を持っている。
@end deffn

@geindex S_IWOTH (stat モジュール)
@anchor{library/stat stat S_IWOTH}@anchor{2c83}
@deffn {データ} stat.S_IWOTH

その他はライト権限を持っている。
@end deffn

@geindex S_IXOTH (stat モジュール)
@anchor{library/stat stat S_IXOTH}@anchor{2c84}
@deffn {データ} stat.S_IXOTH

その他は実行権限を持っている。
@end deffn

@geindex S_ENFMT (stat モジュール)
@anchor{library/stat stat S_ENFMT}@anchor{2c78}
@deffn {データ} stat.S_ENFMT

System V ファイルロック強制。このフラグは @ref{2c76,,S_ISGID} と共有されています。グループ実行ビット (@ref{2c77,,S_IXGRP}) が設定されていないファイルでは、ファイル/レコードのロックが強制されます。
@end deffn

@geindex S_IREAD (stat モジュール)
@anchor{library/stat stat S_IREAD}@anchor{2c85}
@deffn {データ} stat.S_IREAD

@ref{2c7b,,S_IRUSR} の、 Unix V7 のシノニム。
@end deffn

@geindex S_IWRITE (stat モジュール)
@anchor{library/stat stat S_IWRITE}@anchor{2c86}
@deffn {データ} stat.S_IWRITE

@ref{2c7c,,S_IWUSR} の、 Unix V7 のシノニム。
@end deffn

@geindex S_IEXEC (stat モジュール)
@anchor{library/stat stat S_IEXEC}@anchor{2c87}
@deffn {データ} stat.S_IEXEC

@ref{2c7d,,S_IXUSR} の、 Unix V7 のシノニム。
@end deffn

以下のフラグを @ref{1305,,os.chflags()} の `flags' 引数として利用できます:

@geindex UF_SETTABLE (stat モジュール)
@anchor{library/stat stat UF_SETTABLE}@anchor{2c88}
@deffn {データ} stat.UF_SETTABLE

All user settable flags.


Added in version 3.13.

@end deffn

@geindex UF_NODUMP (stat モジュール)
@anchor{library/stat stat UF_NODUMP}@anchor{2c89}
@deffn {データ} stat.UF_NODUMP

ファイルをダンプしない。
@end deffn

@geindex UF_IMMUTABLE (stat モジュール)
@anchor{library/stat stat UF_IMMUTABLE}@anchor{2c8a}
@deffn {データ} stat.UF_IMMUTABLE

ファイルは変更されない。
@end deffn

@geindex UF_APPEND (stat モジュール)
@anchor{library/stat stat UF_APPEND}@anchor{2c8b}
@deffn {データ} stat.UF_APPEND

ファイルは追記しかされない。
@end deffn

@geindex UF_OPAQUE (stat モジュール)
@anchor{library/stat stat UF_OPAQUE}@anchor{2c8c}
@deffn {データ} stat.UF_OPAQUE

ユニオンファイルシステムのスタックを通したとき、このディレクトリは不透明です。
@end deffn

@geindex UF_NOUNLINK (stat モジュール)
@anchor{library/stat stat UF_NOUNLINK}@anchor{2c8d}
@deffn {データ} stat.UF_NOUNLINK

ファイルはリネームや削除されない。
@end deffn

@geindex UF_COMPRESSED (stat モジュール)
@anchor{library/stat stat UF_COMPRESSED}@anchor{2c8e}
@deffn {データ} stat.UF_COMPRESSED

ファイルは圧縮して保存される (macOS 10.6+)。
@end deffn

@geindex UF_TRACKED (stat モジュール)
@anchor{library/stat stat UF_TRACKED}@anchor{2c8f}
@deffn {データ} stat.UF_TRACKED

Used for handling document IDs (macOS)


Added in version 3.13.

@end deffn

@geindex UF_DATAVAULT (stat モジュール)
@anchor{library/stat stat UF_DATAVAULT}@anchor{2c90}
@deffn {データ} stat.UF_DATAVAULT

The file needs an entitlement for reading or writing (macOS 10.13+)


Added in version 3.13.

@end deffn

@geindex UF_HIDDEN (stat モジュール)
@anchor{library/stat stat UF_HIDDEN}@anchor{2c91}
@deffn {データ} stat.UF_HIDDEN

ファイルは GUI で表示されるべきでない (macOS 10.5+)。
@end deffn

@geindex SF_SETTABLE (stat モジュール)
@anchor{library/stat stat SF_SETTABLE}@anchor{2c92}
@deffn {データ} stat.SF_SETTABLE

All super-user changeable flags


Added in version 3.13.

@end deffn

@geindex SF_SUPPORTED (stat モジュール)
@anchor{library/stat stat SF_SUPPORTED}@anchor{2c93}
@deffn {データ} stat.SF_SUPPORTED

All super-user supported flags

@ref{213f,,Availability}: macOS


Added in version 3.13.

@end deffn

@geindex SF_SYNTHETIC (stat モジュール)
@anchor{library/stat stat SF_SYNTHETIC}@anchor{2c94}
@deffn {データ} stat.SF_SYNTHETIC

All super-user read-only synthetic flags

@ref{213f,,Availability}: macOS


Added in version 3.13.

@end deffn

@geindex SF_ARCHIVED (stat モジュール)
@anchor{library/stat stat SF_ARCHIVED}@anchor{2c95}
@deffn {データ} stat.SF_ARCHIVED

ファイルはアーカイブされているかもしれません。
@end deffn

@geindex SF_IMMUTABLE (stat モジュール)
@anchor{library/stat stat SF_IMMUTABLE}@anchor{2c96}
@deffn {データ} stat.SF_IMMUTABLE

ファイルは変更されない。
@end deffn

@geindex SF_APPEND (stat モジュール)
@anchor{library/stat stat SF_APPEND}@anchor{2c97}
@deffn {データ} stat.SF_APPEND

ファイルは追記しかされない。
@end deffn

@geindex SF_RESTRICTED (stat モジュール)
@anchor{library/stat stat SF_RESTRICTED}@anchor{2c98}
@deffn {データ} stat.SF_RESTRICTED

The file needs an entitlement to write to (macOS 10.13+)


Added in version 3.13.

@end deffn

@geindex SF_NOUNLINK (stat モジュール)
@anchor{library/stat stat SF_NOUNLINK}@anchor{2c99}
@deffn {データ} stat.SF_NOUNLINK

ファイルはリネームや削除されない。
@end deffn

@geindex SF_SNAPSHOT (stat モジュール)
@anchor{library/stat stat SF_SNAPSHOT}@anchor{2c9a}
@deffn {データ} stat.SF_SNAPSHOT

このファイルはスナップショットファイルです。
@end deffn

@geindex SF_FIRMLINK (stat モジュール)
@anchor{library/stat stat SF_FIRMLINK}@anchor{2c9b}
@deffn {データ} stat.SF_FIRMLINK

The file is a firmlink (macOS 10.15+)


Added in version 3.13.

@end deffn

@geindex SF_DATALESS (stat モジュール)
@anchor{library/stat stat SF_DATALESS}@anchor{2c9c}
@deffn {データ} stat.SF_DATALESS

The file is a dataless object (macOS 10.15+)


Added in version 3.13.

@end deffn

詳しい情報は *BSD か macOS システムの man page @code{chflags(2)@footnote{https://manpages.debian.org/chflags(2)}} を参照してください。

Windows では、@ref{26d,,os.stat()} が返す @code{st_file_attributes} メンバー内のビットを検証する際に、以下のファイル属性定数を使用できます。これらの定数の意味について詳しくは、Windows API documentation@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117.aspx} を参照してください。

@geindex FILE_ATTRIBUTE_ARCHIVE (stat モジュール)
@geindex FILE_ATTRIBUTE_COMPRESSED (stat モジュール)
@geindex FILE_ATTRIBUTE_DEVICE (stat モジュール)
@geindex FILE_ATTRIBUTE_DIRECTORY (stat モジュール)
@geindex FILE_ATTRIBUTE_ENCRYPTED (stat モジュール)
@geindex FILE_ATTRIBUTE_HIDDEN (stat モジュール)
@geindex FILE_ATTRIBUTE_INTEGRITY_STREAM (stat モジュール)
@geindex FILE_ATTRIBUTE_NORMAL (stat モジュール)
@geindex FILE_ATTRIBUTE_NOT_CONTENT_INDEXED (stat モジュール)
@geindex FILE_ATTRIBUTE_NO_SCRUB_DATA (stat モジュール)
@geindex FILE_ATTRIBUTE_OFFLINE (stat モジュール)
@geindex FILE_ATTRIBUTE_READONLY (stat モジュール)
@geindex FILE_ATTRIBUTE_REPARSE_POINT (stat モジュール)
@geindex FILE_ATTRIBUTE_SPARSE_FILE (stat モジュール)
@geindex FILE_ATTRIBUTE_SYSTEM (stat モジュール)
@geindex FILE_ATTRIBUTE_TEMPORARY (stat モジュール)
@geindex FILE_ATTRIBUTE_VIRTUAL (stat モジュール)
@anchor{library/stat stat FILE_ATTRIBUTE_ARCHIVE}@anchor{2c9d}
@deffn {データ} stat.FILE_ATTRIBUTE_ARCHIVE
@anchor{library/stat stat FILE_ATTRIBUTE_COMPRESSED}@anchor{2c9e}
@deffnx {データ} stat.FILE_ATTRIBUTE_COMPRESSED
@anchor{library/stat stat FILE_ATTRIBUTE_DEVICE}@anchor{2c9f}
@deffnx {データ} stat.FILE_ATTRIBUTE_DEVICE
@anchor{library/stat stat FILE_ATTRIBUTE_DIRECTORY}@anchor{2ca0}
@deffnx {データ} stat.FILE_ATTRIBUTE_DIRECTORY
@anchor{library/stat stat FILE_ATTRIBUTE_ENCRYPTED}@anchor{2ca1}
@deffnx {データ} stat.FILE_ATTRIBUTE_ENCRYPTED
@anchor{library/stat stat FILE_ATTRIBUTE_HIDDEN}@anchor{2ca2}
@deffnx {データ} stat.FILE_ATTRIBUTE_HIDDEN
@anchor{library/stat stat FILE_ATTRIBUTE_INTEGRITY_STREAM}@anchor{2ca3}
@deffnx {データ} stat.FILE_ATTRIBUTE_INTEGRITY_STREAM
@anchor{library/stat stat FILE_ATTRIBUTE_NORMAL}@anchor{2ca4}
@deffnx {データ} stat.FILE_ATTRIBUTE_NORMAL
@anchor{library/stat stat FILE_ATTRIBUTE_NOT_CONTENT_INDEXED}@anchor{2ca5}
@deffnx {データ} stat.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
@anchor{library/stat stat FILE_ATTRIBUTE_NO_SCRUB_DATA}@anchor{2ca6}
@deffnx {データ} stat.FILE_ATTRIBUTE_NO_SCRUB_DATA
@anchor{library/stat stat FILE_ATTRIBUTE_OFFLINE}@anchor{2ca7}
@deffnx {データ} stat.FILE_ATTRIBUTE_OFFLINE
@anchor{library/stat stat FILE_ATTRIBUTE_READONLY}@anchor{2ca8}
@deffnx {データ} stat.FILE_ATTRIBUTE_READONLY
@anchor{library/stat stat FILE_ATTRIBUTE_REPARSE_POINT}@anchor{2ca9}
@deffnx {データ} stat.FILE_ATTRIBUTE_REPARSE_POINT
@anchor{library/stat stat FILE_ATTRIBUTE_SPARSE_FILE}@anchor{2caa}
@deffnx {データ} stat.FILE_ATTRIBUTE_SPARSE_FILE
@anchor{library/stat stat FILE_ATTRIBUTE_SYSTEM}@anchor{2cab}
@deffnx {データ} stat.FILE_ATTRIBUTE_SYSTEM
@anchor{library/stat stat FILE_ATTRIBUTE_TEMPORARY}@anchor{2cac}
@deffnx {データ} stat.FILE_ATTRIBUTE_TEMPORARY
@anchor{library/stat stat FILE_ATTRIBUTE_VIRTUAL}@anchor{2cad}
@deffnx {データ} stat.FILE_ATTRIBUTE_VIRTUAL


Added in version 3.5.

@end deffn

Windows では、@ref{6c8,,os.lstat()} が返す @code{st_reparse_tag} メンバーとの比較に次の定数が 使えます。
これらはよく知られている定数ですが、全てを網羅したリストではありません。

@geindex IO_REPARSE_TAG_SYMLINK (stat モジュール)
@geindex IO_REPARSE_TAG_MOUNT_POINT (stat モジュール)
@geindex IO_REPARSE_TAG_APPEXECLINK (stat モジュール)
@anchor{library/stat stat IO_REPARSE_TAG_SYMLINK}@anchor{2cae}
@deffn {データ} stat.IO_REPARSE_TAG_SYMLINK
@anchor{library/stat stat IO_REPARSE_TAG_MOUNT_POINT}@anchor{2caf}
@deffnx {データ} stat.IO_REPARSE_TAG_MOUNT_POINT
@anchor{library/stat stat IO_REPARSE_TAG_APPEXECLINK}@anchor{2cb0}
@deffnx {データ} stat.IO_REPARSE_TAG_APPEXECLINK


Added in version 3.8.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node filecmp --- ファイルとディレクトリの比較,tempfile --- 一時ファイルやディレクトリの作成,stat --- stat の結果を解釈する,ファイルとディレクトリへのアクセス
@anchor{library/filecmp doc}@anchor{2cb1}@anchor{library/filecmp filecmp-file-and-directory-comparisons}@anchor{2cb2}@anchor{library/filecmp module-filecmp}@anchor{5e}@anchor{library/filecmp translation-repo}@anchor{2cb3}
@subsection @code{filecmp} --- ファイルとディレクトリの比較


@geindex module; filecmp

`ソースコード:' Lib/filecmp.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/filecmp.py}


__________________________________________________________________


The @code{filecmp} module defines functions to compare files and directories,
with various optional time/correctness trade-offs. For comparing files,
see also the @ref{3b,,difflib} module.

The @code{filecmp} module defines the following functions:

@geindex cmp() (filecmp モジュール)
@anchor{library/filecmp filecmp cmp}@anchor{19dd}
@deffn {の関数} filecmp.cmp (f1, f2, shallow=True)

名前が `f1' および `f2' のファイルを比較し、二つのファイルが同じらしければ @code{True} を返し、そうでなければ @code{False} を返します。

If `shallow' is true and the @ref{26d,,os.stat()} signatures (file type, size, and
modification time) of both files are identical, the files are taken to be
equal.

Otherwise, the files are treated as different if their sizes or contents differ.

可搬性と効率のために、この関数は外部プログラムを一切呼び出さないので注意してください。

この関数は過去の比較と結果のキャッシュを使用します。ファイルの @ref{26d,,os.stat()} 情報が変更された場合、キャッシュの項目は無効化されます。@ref{1140,,clear_cache()} を使用して全キャッシュを削除することが出来ます。
@end deffn

@geindex cmpfiles() (filecmp モジュール)
@anchor{library/filecmp filecmp cmpfiles}@anchor{1945}
@deffn {の関数} filecmp.cmpfiles (dir1, dir2, common, shallow=True)

`dir1' と `dir2' ディレクトリの中の、`common' で指定されたファイルを比較します。

ファイル名からなる3つのリスト: `match', `mismatch', `errors' を返します。`match' には双方のディレクトリで一致したファイルのリストが含まれ、`mismatch' にはそうでないファイル名のリストが入ります。そして `errors' は比較されなかったファイルが列挙されます。`errors' になるのは、片方あるいは両方のディレクトリに存在しなかった、ユーザーにそのファイルを読む権限がなかった、その他何らかの理由で比較を完了することができなかった場合です。

引数 `shallow' はその意味も標準の設定も @ref{19dd,,filecmp.cmp()} と同じです。

例えば、@code{cmpfiles('a', 'b', ['c', 'd/e'])} は @code{a/c} を @code{b/c} と、@code{a/d/e} を @code{b/d/e} と、それぞれ比較します。@code{'c'} と @code{'d/e'} はそれぞれ、返される3つのリストのいずれかに登録されます。
@end deffn

@geindex clear_cache() (filecmp モジュール)
@anchor{library/filecmp filecmp clear_cache}@anchor{1140}
@deffn {の関数} filecmp.clear_cache ()

filecmp のキャッシュをクリアします。背後のファイルシステムの mtime 分解能未満でのファイル変更後にすぐに比較するような場合に有用です。


Added in version 3.4.

@end deffn

@menu
* dircmp クラス:: 

@end menu

@node dircmp クラス,,,filecmp --- ファイルとディレクトリの比較
@anchor{library/filecmp dircmp-objects}@anchor{2cb4}@anchor{library/filecmp the-dircmp-class}@anchor{2cb5}
@subsubsection @code{dircmp} クラス


@geindex dircmp (filecmp のクラス)
@anchor{library/filecmp filecmp dircmp}@anchor{1142}
@deffn {クラス} filecmp.dircmp (a, b, ignore=None, hide=None, *, shallow=True)

Construct a new directory comparison object, to compare the directories `a'
and `b'.  `ignore' is a list of names to ignore, and defaults to
@ref{1141,,filecmp.DEFAULT_IGNORES}.  `hide' is a list of names to hide, and
defaults to @code{[os.curdir, os.pardir]}.

The @ref{1142,,dircmp} class compares files by doing `shallow' comparisons
as described for @ref{19dd,,filecmp.cmp()} by default using the `shallow'
parameter.


バージョン 3.13 で変更: Added the `shallow' parameter.


@ref{1142,,dircmp} クラスは以下のメソッドを提供しています:

@geindex report() (filecmp.dircmp のメソッド)
@anchor{library/filecmp filecmp dircmp report}@anchor{2cb6}
@deffn {メソッド} report ()

`a' と `b' の比較を (@ref{ccd,,sys.stdout} に) 表示します。
@end deffn

@geindex report_partial_closure() (filecmp.dircmp のメソッド)
@anchor{library/filecmp filecmp dircmp report_partial_closure}@anchor{2cb7}
@deffn {メソッド} report_partial_closure ()

`a' および `b' およびそれらの直下にある共通のサブディレクトリ間での比較結果を出力します。
@end deffn

@geindex report_full_closure() (filecmp.dircmp のメソッド)
@anchor{library/filecmp filecmp dircmp report_full_closure}@anchor{2cb8}
@deffn {メソッド} report_full_closure ()

`a' および `b' およびそれらの共通のサブディレクトリ間での比較結果を (再帰的に比較して) 出力します。
@end deffn

@ref{1142,,dircmp} クラスは、比較されているディレクトリ階層に関する様々な情報のビットを得るために使用することのできる、興味深い属性を数多く提供しています。

Note that via @ref{6fa,,__getattr__()} hooks, all attributes are computed lazily,
so there is no speed penalty if only those attributes which are lightweight
to compute are used.

@geindex left (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp left}@anchor{2cb9}
@deffn {の属性} left

ディレクトリ `a'  です。
@end deffn

@geindex right (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp right}@anchor{2cba}
@deffn {の属性} right

ディレクトリ `b'  です。
@end deffn

@geindex left_list (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp left_list}@anchor{2cbb}
@deffn {の属性} left_list

`a' にあるファイルおよびサブディレクトリです。`hide' および `ignore' でフィルタされています。
@end deffn

@geindex right_list (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp right_list}@anchor{2cbc}
@deffn {の属性} right_list

`b' にあるファイルおよびサブディレクトリです。`hide' および `ignore' でフィルタされています。
@end deffn

@geindex common (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp common}@anchor{2cbd}
@deffn {の属性} common

`a' および `b' の両方にあるファイルおよびサブディレクトリです。
@end deffn

@geindex left_only (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp left_only}@anchor{2cbe}
@deffn {の属性} left_only

`a' だけにあるファイルおよびサブディレクトリです。
@end deffn

@geindex right_only (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp right_only}@anchor{2cbf}
@deffn {の属性} right_only

`b' だけにあるファイルおよびサブディレクトリです。
@end deffn

@geindex common_dirs (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp common_dirs}@anchor{2cc0}
@deffn {の属性} common_dirs

`a' および `b' の両方にあるサブディレクトリです。
@end deffn

@geindex common_files (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp common_files}@anchor{2cc1}
@deffn {の属性} common_files

`a' および `b' の両方にあるファイルです。
@end deffn

@geindex common_funny (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp common_funny}@anchor{2cc2}
@deffn {の属性} common_funny

`a' および `b' の両方にあり、ディレクトリ間でタイプが異なるか、 @ref{26d,,os.stat()} がエラーを報告するような名前です。
@end deffn

@geindex same_files (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp same_files}@anchor{2cc3}
@deffn {の属性} same_files

クラスのファイル比較オペレータを用いて `a' と `b' の両方において同一のファイルです。
@end deffn

@geindex diff_files (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp diff_files}@anchor{2cc4}
@deffn {の属性} diff_files

`a' と `b' の両方に存在し、クラスのファイル比較オペレータに基づいて内容が異なるファイルです。
@end deffn

@geindex funny_files (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp funny_files}@anchor{2cc5}
@deffn {の属性} funny_files

`a' および `b' 両方にあるが、比較されなかったファイルです。
@end deffn

@geindex subdirs (filecmp.dircmp の属性)
@anchor{library/filecmp filecmp dircmp subdirs}@anchor{1ce5}
@deffn {の属性} subdirs

A dictionary mapping names in @ref{2cc0,,common_dirs} to @ref{1142,,dircmp}
instances (or MyDirCmp instances if this instance is of type MyDirCmp, a
subclass of @ref{1142,,dircmp}).


バージョン 3.10 で変更: Previously entries were always @ref{1142,,dircmp} instances. Now entries
are the same type as `self', if `self' is a subclass of
@ref{1142,,dircmp}.

@end deffn
@end deffn

@geindex DEFAULT_IGNORES (filecmp モジュール)
@anchor{library/filecmp filecmp DEFAULT_IGNORES}@anchor{1141}
@deffn {データ} filecmp.DEFAULT_IGNORES


Added in version 3.4.


デフォルトで @ref{1142,,dircmp} に無視されるディレクトリのリストです。
@end deffn

これは @code{subdirs} 属性を使用して 2 つのディレクトリを再帰的に探索して、共通の異なるファイルを示すための単純化された例です:

@example
>>> from filecmp import dircmp
>>> def print_diff_files(dcmp):
...     for name in dcmp.diff_files:
...         print("diff_file %s found in %s and %s" % (name, dcmp.left,
...               dcmp.right))
...     for sub_dcmp in dcmp.subdirs.values():
...         print_diff_files(sub_dcmp)
...
>>> dcmp = dircmp('dir1', 'dir2')
>>> print_diff_files(dcmp)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tempfile --- 一時ファイルやディレクトリの作成,glob --- Unix 形式のパス名のパターン展開,filecmp --- ファイルとディレクトリの比較,ファイルとディレクトリへのアクセス
@anchor{library/tempfile doc}@anchor{2cc6}@anchor{library/tempfile module-tempfile}@anchor{e6}@anchor{library/tempfile tempfile-generate-temporary-files-and-directories}@anchor{2cc7}@anchor{library/tempfile translation-repo}@anchor{2cc8}
@subsection @code{tempfile} --- 一時ファイルやディレクトリの作成


@geindex module; tempfile

`ソースコード:' Lib/tempfile.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tempfile.py}

@geindex テンポラリ;ファイル名
@geindex テンポラリ;ファイル


__________________________________________________________________


このモジュールは一時ファイルやディレクトリを作成します。
サポートされている全てのプラットフォームで動作します。
@ref{2cc9,,TemporaryFile}、@ref{6ed,,NamedTemporaryFile}、@ref{144c,,TemporaryDirectory}、 @ref{8a2,,SpooledTemporaryFile} は自動的に後始末をし、@ref{1e1,,context managers コンテキストマネージャ} として使うことの出来る高水準のインターフェイスです。
@ref{2cca,,mkstemp()} と @ref{52d,,mkdtemp()} は手動で後始末をしなければならない低水準の関数です。

ユーザが呼び出し可能な全ての関数とコンストラクタは追加の引数を受け取ります。
その引数によって一時ファイルやディレクトリの場所と名前を直接操作することが出来ます。
このモジュールに使用されるファイル名はランダムな文字を含みます。そのためファイルは共有された一時ディレクトリに安全に作成されます。
後方互換性を保つために引数の順序は若干奇妙です。
分かりやすさのためにキーワード引数を使用してください。

このモジュールではユーザが呼び出し可能な以下の項目を定義しています:

@geindex TemporaryFile() (tempfile モジュール)
@anchor{library/tempfile tempfile TemporaryFile}@anchor{2cc9}
@deffn {の関数} tempfile.TemporaryFile (mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

一時的な記憶領域として使うことの出来る @ref{17ac,,file-like object} を返します。
ファイルは @ref{2cca,,mkstemp()} と同じルールにより安全に作成されます。
オブジェクトは閉じられる (オブジェクトのガベージコレクションによる暗黙的なものも含みます) とすぐに破壊されます。
Unix では、そのファイルのディレクトリエントリは全く作成されないか、ファイル作成後すぐに削除されます。
これは他のプラットフォームではサポートされません。
よって、この関数で作成された一時ファイルがファイルシステムで可視な名前を持つかどうかをコードで当てにすべきではありません。

返されたオブジェクトを :term:コンテキストマネージャ <context manager>`として使うことができます （@ref{2ccb,,使用例} を参照してください）。
コンテキストの完了やファイルオブジェクトの破壊で、一時ファイルはファイルシステムから削除されます。

作成されたファイルを閉じることなく読み書きできるように、 `mode' 引数のデフォルトは @code{'w+b'} です。
保存されるデータに関わらず全てのプラットフォーム上で一貫して動作するようにバイナリモードが使用されます。
`buffering'、`encoding'、`errors'、`newline' は、 @ref{316,,open()} に対する引数として解釈されます。

`dir'、`prefix'、`suffix' 引数の意味とデフォルトは @ref{2cca,,mkstemp()} のものと同じです。

返されたオブジェクトは、POSIXプラットフォームでは本物のファイルオブジェクトです。
それ以外のプラットフォームでは、@code{file} 属性が下層の本物のファイルであるファイル様オブジェクトです。

@ref{1175,,os.O_TMPFILE} フラグは、利用可能で動作する場合に用いられます (Linux 固有で、Linux kernel 3.11 以降)。

プラットフォームが Posix でも Cygwin でもない場合は、TemporaryFile は NamedTemporaryFile の別名です。

引数 @code{fullpath} を指定して @ref{1c6e,,監査イベント} @code{tempfile.mkstemp} を送出します。


バージョン 3.5 で変更: 利用可能であれば @ref{1175,,os.O_TMPFILE} フラグが使用されます。



バージョン 3.8 で変更: `errors' 引数が追加されました。

@end deffn

@geindex NamedTemporaryFile() (tempfile モジュール)
@anchor{library/tempfile tempfile NamedTemporaryFile}@anchor{6ed}
@deffn {の関数} tempfile.NamedTemporaryFile (mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None, delete_on_close=True)

This function operates exactly as @ref{2cc9,,TemporaryFile()} does, except the
following differences:


@itemize *

@item 
This function returns a file that is guaranteed to have a visible name in
the file system.

@item 
To manage the named file, it extends the parameters of
@ref{2cc9,,TemporaryFile()} with `delete' and `delete_on_close' parameters that
determine whether and how the named file should be automatically deleted.
@end itemize

The returned object is always a @ref{17ac,,file-like object} whose @code{file}
attribute is the underlying true file object. This file-like object
can be used in a @ref{186,,with} statement, just like a normal file.  The
name of the temporary file can be retrieved from the @code{name} attribute
of the returned file-like object. On Unix, unlike with the
@ref{2cc9,,TemporaryFile()}, the directory entry does not get unlinked immediately
after the file creation.

If `delete' is true (the default) and `delete_on_close' is true (the
default), the file is deleted as soon as it is closed. If `delete' is true
and `delete_on_close' is false, the file is deleted on context manager exit
only, or else when the @ref{17ac,,file-like object} is finalized. Deletion is not
always guaranteed in this case (see @ref{11ff,,object.__del__()}). If `delete' is
false, the value of `delete_on_close' is ignored.

Therefore to use the name of the temporary file to reopen the file after
closing it, either make sure not to delete the file upon closure (set the
`delete' parameter to be false) or, in case the temporary file is created in
a @ref{186,,with} statement, set the `delete_on_close' parameter to be false.
The latter approach is recommended as it provides assistance in automatic
cleaning of the temporary file upon the context manager exit.

Opening the temporary file again by its name while it is still open works as
follows:


@itemize *

@item 
On POSIX the file can always be opened again.

@item 
On Windows, make sure that at least one of the following conditions are
fulfilled:


@itemize *

@item 
`delete' is false

@item 
additional open shares delete access (e.g. by calling @ref{f92,,os.open()}
with the flag @code{O_TEMPORARY})

@item 
`delete' is true but `delete_on_close' is false. Note, that in this
case the additional opens that do not share delete access (e.g.
created via builtin @ref{316,,open()}) must be closed before exiting the
context manager, else the @ref{130d,,os.unlink()} call on context manager
exit will fail with a @ref{f3e,,PermissionError}.
@end itemize
@end itemize

On Windows, if `delete_on_close' is false, and the file is created in a
directory for which the user lacks delete access, then the @ref{130d,,os.unlink()}
call on exit of the context manager will fail with a @ref{f3e,,PermissionError}.
This cannot happen when `delete_on_close' is true because delete access is
requested by the open, which fails immediately if the requested access is not
granted.

On POSIX (only), a process that is terminated abruptly with SIGKILL
cannot automatically delete any NamedTemporaryFiles it created.

引数 @code{fullpath} を指定して @ref{1c6e,,監査イベント} @code{tempfile.mkstemp} を送出します。


バージョン 3.8 で変更: `errors' 引数が追加されました。



バージョン 3.12 で変更: `delete_on_close' 引数が追加されました。

@end deffn

@geindex SpooledTemporaryFile (tempfile のクラス)
@anchor{library/tempfile tempfile SpooledTemporaryFile}@anchor{8a2}
@deffn {クラス} tempfile.SpooledTemporaryFile (max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

このクラスはファイルサイズが `max_size' を超えるかファイルの @ref{17ad,,fileno()} メソッドが呼ばれるまで、データがメモリにスプールされる点以外は @ref{2cc9,,TemporaryFile()} と正確に同じことを行います。
上記条件を満たすと内容はディスクに書き込まれ、操作は @ref{2cc9,,TemporaryFile()} と同様に進みます。

@geindex rollover() (tempfile.SpooledTemporaryFile のメソッド)
@anchor{library/tempfile tempfile SpooledTemporaryFile rollover}@anchor{2ccc}
@deffn {メソッド} rollover ()

この関数が返すファイルは、追加で1つのメソッド @code{rollover()} を持っています。このメソッドが呼ばれると、(サイズに関係なく)メモリからディスクへのロールオーバーが実行されます。
@end deffn

返されたオブジェクトはファイル様オブジェクトで、その @code{_file} 属性は (バイナリかテキスト `mode' が指定されたかどうかに依存して) @ref{10a4,,io.BytesIO} か @ref{9be,,io.TextIOWrapper} オブジェクト、あるいは @ref{2ccc,,rollover()} が呼ばれたかどうかに依存して本物のファイルオブジェクトになります。
このファイル様オブジェクトは、通常のファイルオブジェクトと同じように @ref{186,,with} 文中で使用することが出来ます。


バージョン 3.3 で変更: truncate メソッドが `size' 引数を受け取るようになりました。



バージョン 3.8 で変更: `errors' 引数が追加されました。



バージョン 3.11 で変更: Fully implements the @ref{8a3,,io.BufferedIOBase} and
@ref{8a4,,io.TextIOBase} abstract base classes (depending on whether binary
or text `mode' was specified).

@end deffn

@geindex TemporaryDirectory (tempfile のクラス)
@anchor{library/tempfile tempfile TemporaryDirectory}@anchor{144c}
@deffn {クラス} tempfile.TemporaryDirectory (suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True)

このクラスは @ref{52d,,mkdtemp()} と同じルールを使用して安全に一時ディレクトリを作成します。返されたオブジェクトは、@ref{1e1,,コンテキストマネージャ} として使用することができます (@ref{2ccb,,使用例} を参照)。コンテキストの完了や一時ディレクトリオブジェクトを破壊すると、新規作成された一時ディレクトリとその中身はファイルシステムから削除されます。

@geindex name (tempfile.TemporaryDirectory の属性)
@anchor{library/tempfile tempfile TemporaryDirectory name}@anchor{2ccd}
@deffn {の属性} name

ディレクトリ名は返されたオブジェクトの @code{name} 属性から取得できます。返されたオブジェクトが @ref{1e1,,コンテキストマネージャ} として使用された場合、 @code{name} は @ref{186,,with} 文内の @code{as} 節のターゲットがあればそれに割り当てられます。
@end deffn

@geindex cleanup() (tempfile.TemporaryDirectory のメソッド)
@anchor{library/tempfile tempfile TemporaryDirectory cleanup}@anchor{2cce}
@deffn {メソッド} cleanup ()

The directory can be explicitly cleaned up by calling the
@code{cleanup()} method. If `ignore_cleanup_errors' is true, any unhandled
exceptions during explicit or implicit cleanup (such as a
@ref{f3e,,PermissionError} removing open files on Windows) will be ignored,
and the remaining removable items deleted on a "best-effort" basis.
Otherwise, errors will be raised in whatever context cleanup occurs
(the @code{cleanup()} call, exiting the context manager, when the object
is garbage-collected or during interpreter shutdown).
@end deffn

The `delete' parameter can be used to disable cleanup of the directory tree
upon exiting the context.  While it may seem unusual for a context manager
to disable the action taken when exiting the context, it can be useful during
debugging or when you need your cleanup behavior to be conditional based on
other logic.

引数 @code{fullpath} を指定して @ref{1c6e,,監査イベント} @code{tempfile.mkdtemp} を送出します。


Added in version 3.2.



バージョン 3.10 で変更: `ignore_cleanup_errors' 引数が追加されました。



バージョン 3.12 で変更: `delete' パラメータが追加されました。

@end deffn

@geindex mkstemp() (tempfile モジュール)
@anchor{library/tempfile tempfile mkstemp}@anchor{2cca}
@deffn {の関数} tempfile.mkstemp (suffix=None, prefix=None, dir=None, text=False)

可能な限り最も安全な手段で一時ファイルを生成します。
プラットフォームが @ref{f92,,os.open()} の @ref{2ccf,,os.O_EXCL} フラグを正しく実装している限り、ファイルの作成で競合が起こることはありません。
作成したユーザのユーザ ID からのみファイルを読み書き出来ます。
プラットフォームがファイルが実行可能かどうかを示す許可ビットを使用している場合、ファイルは誰からも実行不可です。

このファイル記述子は @ref{10fc,,子プロセスに継承されません}。

@ref{2cc9,,TemporaryFile()} と違って、 @ref{2cca,,mkstemp()} のユーザは用済みになった時に一時ファイルを削除しなければなりません。

`suffix' が @code{None} でない場合、ファイル名はその接尾辞で終わります。
そうでない場合、接尾辞はありません。
@ref{2cca,,mkstemp()} はファイル名と接尾辞の間にドットを追加しません。
必要であれば `suffix' の先頭につけてください。

`prefix' が @code{None} でない場合、ファイル名はその接頭辞で始まります。
そうでない場合、デフォルトの接頭辞が使われます。
必要に応じ、デフォルトは @ref{2cd0,,gettempprefix()} または @ref{2cd1,,gettempprefixb()} の返り値です。

`dir' が @code{None} でない場合、ファイルはそのディレクトリ下に作成されます。 @code{None} の場合、デフォルトのディレクトリが使われます。デフォルトのディレクトリはプラットフォームに依存するリストから選ばれますが、アプリケーションのユーザは `TMPDIR'、`TEMP'、または `TMP' 環境変数を設定することでディレクトリの場所を管理することができます。そのため、生成されるファイル名が、@code{os.popen()} で外部コマンドにクォーティング無しで渡すことができるなどといった、扱いやすい性質を持つ保証はありません。

`suffix'、`prefix'、`dir' のいずれかが @code{None} でない場合、それらは同じ型でなければなりません。
bytes の場合、返された名前は str でなはく bytes です。
他の挙動はデフォルトで返り値を bytes に強制的にしたい場合は @code{suffix=b'@w{'}} を渡してください。

`text' に真を指定した場合は、ファイルはテキストモードで開かれます。そうでない場合(デフォルト)は、ファイルはバイナリモードで開かれます。

@ref{2cca,,mkstemp()} は開かれたファイルを扱うための OS レベルのハンドル (@ref{f92,,os.open()} が返すものと同じ) とファイルの絶対パス名が順番に並んだタプルを返します。

引数 @code{fullpath} を指定して @ref{1c6e,,監査イベント} @code{tempfile.mkstemp} を送出します。


バージョン 3.5 で変更: `suffix'、`prefix'、`dir' は bytes の返り値を得るために bytes で渡すことが出来ます。
それ以前は str のみ許されていました。
適切なデフォルト値を使用するよう、`suffix' と `prefix' は @code{None} を受け入れ、デフォルトにするようになりました。



バージョン 3.6 で変更: `dir' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex mkdtemp() (tempfile モジュール)
@anchor{library/tempfile tempfile mkdtemp}@anchor{52d}
@deffn {の関数} tempfile.mkdtemp (suffix=None, prefix=None, dir=None)

可能な限り安全な方法で一時ディレクトリを作成します。
ディレクトリの生成で競合は発生しません。
ディレクトリを作成したユーザ ID だけが、このディレクトリに対して内容を読み出したり、書き込んだり、検索したりすることができます。

@ref{52d,,mkdtemp()} のユーザは用済みになった時に一時ディレクトリとその中身を削除しなければなりません。

`prefix', `suffix', `dir' 引数は @ref{2cca,,mkstemp()} 関数のものと同じです。

@ref{52d,,mkdtemp()} は新たに生成されたディレクトリの絶対パス名を返します。

引数 @code{fullpath} を指定して @ref{1c6e,,監査イベント} @code{tempfile.mkdtemp} を送出します。


バージョン 3.5 で変更: `suffix'、`prefix'、`dir' は bytes の返り値を得るために bytes で渡すことが出来ます。
それ以前は str のみ許されていました。
適切なデフォルト値を使用するよう、`suffix' と `prefix' は @code{None} を受け入れ、デフォルトにするようになりました。



バージョン 3.6 で変更: `dir' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.12 で変更: @ref{52d,,mkdtemp()} now always returns an absolute path, even if `dir' is relative.

@end deffn

@geindex gettempdir() (tempfile モジュール)
@anchor{library/tempfile tempfile gettempdir}@anchor{1c93}
@deffn {の関数} tempfile.gettempdir ()

一時ファイルに用いられるディレクトリの名前を返します。
これはモジュール内の全ての関数の `dir' 引数のデフォルト値を定義します。

Python は呼び出したユーザがファイルを作ることの出来るディレクトリを検索するのに標準的なリストを使用します。
そのリストは:


@enumerate 

@item 
環境変数 
@geindex TMPDIR
@geindex 環境変数; TMPDIR
@code{TMPDIR} で与えられているディレクトリ名。

@item 
環境変数 
@geindex TEMP
@geindex 環境変数; TEMP
@code{TEMP} で与えられているディレクトリ名。

@item 
環境変数 
@geindex TMP
@geindex 環境変数; TMP
@code{TMP} で与えられているディレクトリ名。

@item 
プラットフォーム依存の場所:


@itemize *

@item 
Windows ではディレクトリ @code{C:\TEMP} 、 @code{C:\TMP} 、 @code{\TEMP} 、および @code{\TMP} の順。

@item 
その他の全てのプラットフォームでは、 @code{/tmp} 、 @code{/var/tmp} 、および @code{/usr/tmp} の順。
@end itemize

@item 
最後の手段として、現在の作業ディレクトリ。
@end enumerate

この検索の結果はキャッシュされます。以下の @ref{1c92,,tempdir} の記述を参照してください。


バージョン 3.10 で変更: Always returns a str.  Previously it would return any @ref{1c92,,tempdir}
value regardless of type so long as it was not @code{None}.

@end deffn

@geindex gettempdirb() (tempfile モジュール)
@anchor{library/tempfile tempfile gettempdirb}@anchor{1c94}
@deffn {の関数} tempfile.gettempdirb ()

@ref{1c93,,gettempdir()} と同じですが返り値は bytesです。


Added in version 3.5.

@end deffn

@geindex gettempprefix() (tempfile モジュール)
@anchor{library/tempfile tempfile gettempprefix}@anchor{2cd0}
@deffn {の関数} tempfile.gettempprefix ()

一時ファイルを生成する際に使われるファイル名の接頭辞を返します。
これにはディレクトリ部は含まれません。
@end deffn

@geindex gettempprefixb() (tempfile モジュール)
@anchor{library/tempfile tempfile gettempprefixb}@anchor{2cd1}
@deffn {の関数} tempfile.gettempprefixb ()

@ref{2cd0,,gettempprefix()} と同じですが返り値は bytes です。


Added in version 3.5.

@end deffn

The module uses a global variable to store the name of the directory
used for temporary files returned by @ref{1c93,,gettempdir()}.  It can be
set directly to override the selection process, but this is discouraged.
All functions in this module take a `dir' argument which can be used
to specify the directory. This is the recommended approach that does
not surprise other unsuspecting code by changing global API behavior.

@geindex tempdir (tempfile モジュール)
@anchor{library/tempfile tempfile tempdir}@anchor{1c92}
@deffn {データ} tempfile.tempdir

When set to a value other than @code{None}, this variable defines the
default value for the `dir' argument to the functions defined in this
module, including its type, bytes or str.  It cannot be a
@ref{5a1,,path-like object}.

@code{tempdir} が (デフォルトの) @code{None} の場合、 @ref{2cd0,,gettempprefix()} を除く上記のいずれかの関数を呼び出す際は常に @ref{1c93,,gettempdir()} で述べられているアルゴリズムによって初期化されます。

@cartouche
@quotation 注釈 
Beware that if you set @code{tempdir} to a bytes value, there is a
nasty side effect: The global default return type of
@ref{2cca,,mkstemp()} and @ref{52d,,mkdtemp()} changes to bytes when no
explicit @code{prefix}, @code{suffix}, or @code{dir} arguments of type
str are supplied. Please do not write code expecting or
depending on this. This awkward behavior is maintained for
compatibility with the historical implementation.
@end quotation
@end cartouche
@end deffn

@menu
* 使用例: 使用例<8>. 
* 非推奨の関数と変数:: 

@end menu

@node 使用例<8>,非推奨の関数と変数,,tempfile --- 一時ファイルやディレクトリの作成
@anchor{library/tempfile examples}@anchor{2cd2}@anchor{library/tempfile tempfile-examples}@anchor{2ccb}
@subsubsection 使用例


Here are some examples of typical usage of the @code{tempfile} module:

@example
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary file using a context manager
# close the file, use the name to open the file again
>>> with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:
...     fp.write(b'Hello world!')
...     fp.close()
... # the file is closed, but not removed
... # open the file again by using its name
...     with open(fp.name, mode='rb') as f:
...         f.read()
b'Hello world!'
>>>
# file is now removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
@end example

@node 非推奨の関数と変数,,使用例<8>,tempfile --- 一時ファイルやディレクトリの作成
@anchor{library/tempfile deprecated-functions-and-variables}@anchor{2cd3}@anchor{library/tempfile tempfile-mktemp-deprecated}@anchor{2cd4}
@subsubsection 非推奨の関数と変数


一時ファイルを作成する歴史的な手法は、まず @ref{1c30,,mktemp()} 関数でファイル名を作り、その名前を使ってファイルを作成するというものでした。
残念ながらこの方法は安全ではありません。
なぜなら、@ref{1c30,,mktemp()} の呼び出しと最初のプロセスが続いてファイル作成を試みる間に、異なるプロセスがその名前でファイルを同時に作成するかもしれないからです。
解決策は二つのステップを同時に行い、ファイルをすぐに作成するというものです。
この方法は @ref{2cca,,mkstemp()} や上述している他の関数で使用されています。

@geindex mktemp() (tempfile モジュール)
@anchor{library/tempfile tempfile mktemp}@anchor{1c30}
@deffn {の関数} tempfile.mktemp (suffix='@w{'}, prefix='tmp', dir=None)


バージョン 2.3 で非推奨: 代わりに @ref{2cca,,mkstemp()} を使って下さい。


呼び出し時には存在しなかった、ファイルの絶対パス名を返します。
`prefix'、`suffix'、`dir' 引数は @ref{2cca,,mkstemp()} のものと似ていますが、bytes のファイル名、@code{suffix=None}、そして @code{prefix=None} がサポートされていない点で異なります。

@cartouche
@quotation 警告 
この関数を使うとプログラムのセキュリティホールになる可能性があります。この関数がファイル名を返した後、あなたがそのファイル名を使って次に何かをしようとする段階に至る前に、誰か他の人間があなたを出し抜くことができてしまいます。 @ref{1c30,,mktemp()} の利用は、 @ref{6ed,,NamedTemporaryFile()} に @code{delete=False} 引数を渡すことで、簡単に置き換えることができます:

@example
>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False
@end example
@end quotation
@end cartouche
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node glob --- Unix 形式のパス名のパターン展開,fnmatch --- Unix のファイル名パターンマッチ,tempfile --- 一時ファイルやディレクトリの作成,ファイルとディレクトリへのアクセス
@anchor{library/glob doc}@anchor{2cd5}@anchor{library/glob glob-unix-style-pathname-pattern-expansion}@anchor{2cd6}@anchor{library/glob module-glob}@anchor{68}@anchor{library/glob translation-repo}@anchor{2cd7}
@subsection @code{glob} --- Unix 形式のパス名のパターン展開


@geindex module; glob

`ソースコード:' Lib/glob.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/glob.py}

@geindex filenames;pathname expansion


__________________________________________________________________


@geindex * (アスタリスク);glob 形式のワイルドカード
@geindex ? (クエスチョンマーク);glob 形式のワイルドカード
@geindex [] (角カッコ);glob 形式のワイルドカード
@geindex ! (エクスクラメーション);glob 形式のワイルドカード
@geindex - (負符号);glob 形式のワイルドカード
@geindex . (ドット);glob 形式のワイルドカード

The @code{glob} module finds pathnames
using pattern matching rules similar to the Unix shell.
No tilde expansion is done, but @code{*}, @code{?}, and character
ranges expressed with @code{[]} will be correctly matched.  This is done by using
the @ref{c54,,os.scandir()} and @ref{1c54,,fnmatch.fnmatch()} functions in concert, and
not by actually invoking a subshell.

@cartouche
@quotation 注釈 
The pathnames are returned in no particular order.  If you need a specific
order, sort the results.
@end quotation
@end cartouche

Files beginning with a dot (@code{.}) can only be matched by
patterns that also start with a dot,
unlike @ref{1c54,,fnmatch.fnmatch()} or @ref{537,,pathlib.Path.glob()}.
For tilde and shell variable expansion, use @ref{c09,,os.path.expanduser()} and
@ref{15f2,,os.path.expandvars()}.

リテラルにマッチさせるには、メタ文字を括弧に入れてください。例えば、@code{'[?]'} は文字 @code{'?'} にマッチします。

The @code{glob} module defines the following functions:

@geindex glob() (glob モジュール)
@anchor{library/glob glob glob}@anchor{5a0}
@deffn {の関数} glob.glob (pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)

パスの仕様を含む文字列 `pathname' にマッチするパス名のリストを返します。戻り値のリストは空になる可能性があります。 `pathname' は (@code{/usr/src/Python-1.5/Makefile} のような) 絶対パスも、 (@code{../../Tools/*/*.gif} のような) 相対パスもどちらも指定可能で、シェル形式のワイルドカードを含めることもできます。参照先が存在しない、壊れたシンボリックリンクも (シェルの場合と同様に) 結果に含まれます。結果がソートされているかどうかはファイルシステムによります。条件を満たすファイルがこの関数の呼び出し中に追加または削除された場合、それらのファイルに対するパス名が結果に含まれるかどうかはの動作は不定です。

If `root_dir' is not @code{None}, it should be a @ref{5a1,,path-like object}
specifying the root directory for searching.  It has the same effect on
@code{glob()} as changing the current directory before calling it.  If
`pathname' is relative, the result will contain paths relative to
`root_dir'.

この関数は `dir_fd' パラメタで @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

@geindex **;glob 形式のワイルドカード

`recursive' が真の場合、パターン "@code{**}" はあらゆるファイルや0個以上のディレクトリ、サブディレクトリおよびディレクトリへのシンボリックリンクにマッチします。パターンの末尾が @ref{87a,,os.sep} または @ref{87b,,os.altsep} の場合、ファイルは一致しません。

`include_hidden' が真の場合、パターン "@code{**}" は隠しディレクトリにマッチします。

引数 @code{pathname}, @code{recursive} を指定して @ref{1c6e,,監査イベント} @code{glob.glob} を送出します。

引数 @code{pathname}, @code{recursive}, @code{root_dir}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{glob.glob/2} を送出します。

@cartouche
@quotation 注釈 
パターン "@code{**}" を大きなディレクトリツリーで使用するととてつもなく時間がかかるかもしれません。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
`pathname' が複数の "@code{**}" パターンを含み、かつ `recursive' が真の場合、この関数は同じパスを重複して返す可能性があります。
@end quotation
@end cartouche


バージョン 3.5 で変更: "@code{**}" を使った再帰的な glob がサポートされました。



バージョン 3.10 で変更: `root_dir' と `dir_fd' 引数が追加されました。



バージョン 3.11 で変更: `include_hidden' パラメータが追加されました。

@end deffn

@geindex iglob() (glob モジュール)
@anchor{library/glob glob iglob}@anchor{a08}
@deffn {の関数} glob.iglob (pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)

実際には一度にすべてを格納せずに、@ref{68,,glob()} と同じ値を順に生成する @ref{4c8,,イテレーター} を返します。

引数 @code{pathname}, @code{recursive} を指定して @ref{1c6e,,監査イベント} @code{glob.glob} を送出します。

引数 @code{pathname}, @code{recursive}, @code{root_dir}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{glob.glob/2} を送出します。

@cartouche
@quotation 注釈 
`pathname' が複数の "@code{**}" パターンを含み、かつ `recursive' が真の場合、この関数は同じパスを重複して返す可能性があります。
@end quotation
@end cartouche


バージョン 3.5 で変更: "@code{**}" を使った再帰的な glob がサポートされました。



バージョン 3.10 で変更: `root_dir' と `dir_fd' 引数が追加されました。



バージョン 3.11 で変更: `include_hidden' パラメータが追加されました。

@end deffn

@geindex escape() (glob モジュール)
@anchor{library/glob glob escape}@anchor{1147}
@deffn {の関数} glob.escape (pathname)

すべての特殊文字 (@code{'?'} 、 @code{'*'} 、 @code{'['}) をエスケープします。特殊文字を含んでいる可能性のある任意のリテラル文字列をマッチさせたいときに便利です。drive/UNC sharepoints の特殊文字はエスケープされません。たとえば Windows では @code{escape('//?/c:/Quo vadis?.txt')} は @code{'//?/c:/Quo vadis[?].txt'} を返します。


Added in version 3.4.

@end deffn

@geindex translate() (glob モジュール)
@anchor{library/glob glob translate}@anchor{4fb}
@deffn {の関数} glob.translate (pathname, *, recursive=False, include_hidden=False, seps=None)

与えられたパスの仕様を @ref{1445,,re.match()} で利用するための正規表現に変換します。シェル形式のワイルドカードを含めることもできます。

例えば:

@example
>>> import glob, re
>>>
>>> regex = glob.translate('**/*.txt', recursive=True, include_hidden=True)
>>> regex
'(?s:(?:.+/)?[^/]*\\.txt)\\z'
>>> reobj = re.compile(regex)
>>> reobj.match('foo/bar/baz.txt')
<re.Match object; span=(0, 15), match='foo/bar/baz.txt'>
@end example

@ref{184f,,fnmatch.translate()} と違って、この関数ではパスの要素を区切るセパレータとセグメントには意味があります。デフォルトでは、ワイルドカードはパスのセパレータにはマッチしません。また @code{*} パターンのセグメントは厳密に単一のパスのセグメントにマッチします。

`recursive' が真の場合、パターンセグメント "@code{**}" は任意の数のパスセグメントにマッチします。

`include_hidden' が真の場合、ワイルドカードはドット (@code{.}) で始まるパスセグメントにもマッチします。

パスの要素を区切るセパレータのシーケンスを `seps' 引数に渡すことができます。渡さない場合は @ref{87a,,os.sep} と (もしあれば) @ref{87b,,altsep} が使われます。


@subsubheading 参考


@ref{535,,pathlib.PurePath.full_match()} と @ref{537,,pathlib.Path.glob()} の2つのメソッドは、それぞれパターンマッチと glob 相当の操作を実装するためにこの関数を呼んでいます。



Added in version 3.13.

@end deffn

@menu
* 使用例: 使用例<9>. 

@end menu

@node 使用例<9>,,,glob --- Unix 形式のパス名のパターン展開
@anchor{library/glob examples}@anchor{2cd8}
@subsubsection 使用例


次のファイルを含むディレクトリを考えます: @code{1.gif}, @code{2.txt}, @code{card.gif} および:file:@cite{3.txt} だけを含む @code{sub} サブディレクトリ。このとき、  @ref{68,,glob()} は以下の結果を返します。パスにおける先頭の要素がどのように保持されるかに注意してください:

@example
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']
@end example

ディレクトリが @code{.} で始まるファイルを含んでいる場合、デフォルトでそれらはマッチしません。例えば、 @code{card.gif} と @code{.card.gif} を含むディレクトリを考えてください:

@example
>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']
@end example


@subsubheading 参考


@ref{60,,fnmatch} モジュールは、シェル形式の (パスではなく) ファイル名の展開機能を提供します。



@subsubheading 参考


@ref{a8,,pathlib} モジュールは高水準のパスオブジェクトを提供します。


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node fnmatch --- Unix のファイル名パターンマッチ,linecache --- テキストラインへのランダムアクセス,glob --- Unix 形式のパス名のパターン展開,ファイルとディレクトリへのアクセス
@anchor{library/fnmatch doc}@anchor{2cd9}@anchor{library/fnmatch fnmatch-unix-filename-pattern-matching}@anchor{2cda}@anchor{library/fnmatch module-fnmatch}@anchor{60}@anchor{library/fnmatch translation-repo}@anchor{2cdb}
@subsection @code{fnmatch} --- Unix のファイル名パターンマッチ


@geindex module; fnmatch

`ソースコード:' Lib/fnmatch.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/fnmatch.py}

@geindex filenames;ワイルドカード展開

@geindex module;re


__________________________________________________________________


このモジュールは Unix のシェル形式のワイルドカードに対応しています。これらは、 (@ref{be,,re} モジュールでドキュメント化されている) 正規表現とは `異なります' 。シェル形式のワイルドカードで使われる特殊文字は、次のとおりです。

@geindex * (アスタリスク);glob 形式のワイルドカード
@geindex ? (クエスチョンマーク);glob 形式のワイルドカード
@geindex [] (角カッコ);glob 形式のワイルドカード
@geindex ! (エクスクラメーション);glob 形式のワイルドカード
@geindex - (負符号);glob 形式のワイルドカード


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Pattern

@tab

意味

@item

@code{*}

@tab

すべてにマッチします

@item

@code{?}

@tab

任意の一文字にマッチします

@item

@code{[seq]}

@tab

`seq' にある任意の文字にマッチします

@item

@code{[!seq]}

@tab

`seq' にない任意の文字にマッチします

@end multitable


リテラルにマッチさせるには、メタ文字を括弧に入れてください。例えば、@code{'[?]'} は文字 @code{'?'} にマッチします。

@geindex module;glob

ファイル名の区切り文字 (Unixでは @code{'/'}) はこのモジュールに固有なものでは `ない' ことに注意してください。パス名展開については、 @ref{68,,glob} モジュールを参照してください (@ref{68,,glob} はパス名の部分にマッチさせるのに @ref{1c56,,filter()} を使っています)。同様に、ピリオドで始まるファイル名はこのモジュールに固有ではなくて、 @code{*} と @code{?} のパターンでマッチします。

Unless stated otherwise, "filename string" and "pattern string" either refer to
@ref{169,,str} or @code{ISO-8859-1} encoded @ref{192,,bytes} objects. Note that the
functions documented below do not allow to mix a @code{bytes} pattern with
a @code{str} filename, and vice-versa.

Finally, note that @ref{be2,,functools.lru_cache()} with a `maxsize' of 32768
is used to cache the (typed) compiled regex patterns in the following
functions: @ref{60,,fnmatch()}, @ref{1c55,,fnmatchcase()}, @ref{1c56,,filter()}, @ref{211,,filterfalse()}.

@geindex fnmatch() (fnmatch モジュール)
@anchor{library/fnmatch fnmatch fnmatch}@anchor{1c54}
@deffn {の関数} fnmatch.fnmatch (name, pat)

ファイルの文字列 `name' がパターン文字列 `pat' にマッチするかテストして、 @code{True} または @code{False} のいずれかを返します。どちらの引数とも @ref{2c56,,os.path.normcase()} を使って、大文字、小文字が正規化されます。オペレーティングシステムが標準でどうなっているかに関係なく、大文字、小文字を区別して比較する場合には、 @ref{1c55,,fnmatchcase()} が使用できます。

次の例では、カレントディレクトリにある、拡張子が @code{.txt} である全てのファイルを表示しています:

@example
import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
@end example
@end deffn

@geindex fnmatchcase() (fnmatch モジュール)
@anchor{library/fnmatch fnmatch fnmatchcase}@anchor{1c55}
@deffn {の関数} fnmatch.fnmatchcase (name, pat)

ファイル名の文字列 `name' がパターン文字列 `pat' にマッチするかテストして、 @code{True} または @code{False} を返します。比較は大文字、小文字を区別し、 @ref{2c56,,os.path.normcase()} は適用しません。
@end deffn

@geindex filter() (fnmatch モジュール)
@anchor{library/fnmatch fnmatch filter}@anchor{1c56}
@deffn {の関数} fnmatch.filter (names, pat)

Construct a list from those elements of the @ref{12f1,,iterable} of filename
strings `names' that match the pattern string `pat'.
It is the same as @code{[n for n in names if fnmatch(n, pat)]},
but implemented more efficiently.
@end deffn

@geindex filterfalse() (fnmatch モジュール)
@anchor{library/fnmatch fnmatch filterfalse}@anchor{211}
@deffn {の関数} fnmatch.filterfalse (names, pat)

Construct a list from those elements of the @ref{12f1,,iterable} of filename
strings `names' that do not match the pattern string `pat'.
It is the same as @code{[n for n in names if not fnmatch(n, pat)]},
but implemented more efficiently.


Added in version 3.14.

@end deffn

@geindex translate() (fnmatch モジュール)
@anchor{library/fnmatch fnmatch translate}@anchor{184f}
@deffn {の関数} fnmatch.translate (pat)

Return the shell-style pattern `pat' converted to a regular expression for
using with @ref{1445,,re.match()}. The pattern is expected to be a @ref{169,,str}.

例:

@example
>>> import fnmatch, re
>>>
>>> regex = fnmatch.translate('*.txt')
>>> regex
'(?s:.*\\.txt)\\z'
>>> reobj = re.compile(regex)
>>> reobj.match('foobar.txt')
<re.Match object; span=(0, 10), match='foobar.txt'>
@end example
@end deffn


@subsubheading 参考



@table @asis

@item @ref{68,,glob} モジュール

Unix シェル形式のパス展開。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node linecache --- テキストラインへのランダムアクセス,shutil --- 高水準のファイル操作,fnmatch --- Unix のファイル名パターンマッチ,ファイルとディレクトリへのアクセス
@anchor{library/linecache doc}@anchor{2cdc}@anchor{library/linecache linecache-random-access-to-text-lines}@anchor{2cdd}@anchor{library/linecache module-linecache}@anchor{89}@anchor{library/linecache translation-repo}@anchor{2cde}
@subsection @code{linecache} --- テキストラインへのランダムアクセス


@geindex module; linecache

`ソースコード:' Lib/linecache.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/linecache.py}


__________________________________________________________________


The @code{linecache} module allows one to get any line from a Python source file, while
attempting to optimize internally, using a cache, the common case where many
lines are read from a single file.  This is used by the @ref{104,,traceback} module
to retrieve source lines for inclusion in  the formatted traceback.

@ref{2cdf,,tokenize.open()} 関数は、ファイルを開くために使用されます。この関数は、 @ref{17b8,,tokenize.detect_encoding()} を使用してファイルのエンコーディングを取得します。エンコーディングトークンが存在しない場合、デフォルトの UTF-8 になります。

The @code{linecache} module defines the following functions:

@geindex getline() (linecache モジュール)
@anchor{library/linecache linecache getline}@anchor{240}
@deffn {の関数} linecache.getline (filename, lineno, module_globals=None)

`filename' という名前のファイルから `lineno' 行目を取得します。この関数は決して例外を発生させません --- エラーの際には @code{'@w{'}} を返します (行末の改行文字は、見つかった行に含まれます)。

@geindex module;検索;パス

If `filename' indicates a frozen module (starting with @code{'<frozen '}), the function
will attempt to get the real file name from @code{module_globals['__file__']} if
`module_globals' is not @code{None}.

`filename' という名前のファイルが見付からなかった場合、この関数は最初に `module_globals' にある 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} @code{__loader__} を確認します。
ローダーが存在していて、 @code{get_source} メソッドが実装されていた場合、ソースコードの行を決定します (@code{get_source()} が @code{None} を返した場合は、 @code{'@w{'}} が返ります)。
最後に、 `filename' が相対ファイル名だった場合、モジュール検索パス @code{sys.path} のエントリからの相対パスを探します。


バージョン 3.14 で変更: Support `filename' of frozen modules.

@end deffn

@geindex clearcache() (linecache モジュール)
@anchor{library/linecache linecache clearcache}@anchor{2ce0}
@deffn {の関数} linecache.clearcache ()

キャッシュをクリアします。それまでに @ref{240,,getline()} を使って読み込んだファイルの行が必要でなくなったら、この関数を使ってください。
@end deffn

@geindex checkcache() (linecache モジュール)
@anchor{library/linecache linecache checkcache}@anchor{18eb}
@deffn {の関数} linecache.checkcache (filename=None)

キャッシュが有効かどうかを確認します。キャッシュしたファイルがディスク上で変更された可能性があり、更新後のバージョンが必要な場合にこの関数を使用します。 `filename' が与えられない場合、全てのキャッシュエントリを確認します。
@end deffn

@geindex lazycache() (linecache モジュール)
@anchor{library/linecache linecache lazycache}@anchor{1024}
@deffn {の関数} linecache.lazycache (filename, module_globals)

後々の呼び出しで `module_globals' が @code{None} となっていても、ファイルの形式でないモジュールの行を後から @ref{240,,getline()} で取得するのに十分な詳細を把握しておきます。この関数により、モジュールの globals を無限に持ち運ぶ必要無しに、実際に必要な行まで I/O を行う必要がなくなります。


Added in version 3.5.

@end deffn

以下はプログラム例です:

@example
>>> import linecache
>>> linecache.getline(linecache.__file__, 8)
'import sys\n'
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node shutil --- 高水準のファイル操作,,linecache --- テキストラインへのランダムアクセス,ファイルとディレクトリへのアクセス
@anchor{library/shutil doc}@anchor{2ce1}@anchor{library/shutil module-shutil}@anchor{ca}@anchor{library/shutil shutil-high-level-file-operations}@anchor{2ce2}@anchor{library/shutil translation-repo}@anchor{2ce3}
@subsection @code{shutil} --- 高水準のファイル操作


@geindex module; shutil

@c partly based on the docstrings

`ソースコード:' Lib/shutil.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/shutil.py}

@geindex ファイル;コピー
@geindex ファイルのコピー


__________________________________________________________________


The @code{shutil} module offers a number of high-level operations on files and
collections of files.  In particular, functions are provided  which support file
copying and removal. For operations on individual files, see also the
@ref{a5,,os} module.

@cartouche
@quotation 警告 
高水準のファイルコピー関数 (@ref{c4f,,shutil.copy()}, @ref{c50,,shutil.copy2()}) でも、ファイルのメタデータの全てをコピーすることはできません。

POSIXプラットフォームでは、これはACLやファイルのオーナー、グループが失われることを意味しています。 Mac OSでは、リソースフォーク(resource fork)やその他のメタデータが利用されません。これは、リソースが失われ、ファイルタイプや生成者コード(creator code)が正しくなくなることを意味しています。 Windowsでは、ファイルオーナー、ACL、代替データストリームがコピーされません。
@end quotation
@end cartouche

@menu
* ディレクトリとファイルの操作:: 
* アーカイブ化操作:: 
* 出力ターミナルのサイズの取得:: 

@end menu

@node ディレクトリとファイルの操作,アーカイブ化操作,,shutil --- 高水準のファイル操作
@anchor{library/shutil directory-and-files-operations}@anchor{2ce4}@anchor{library/shutil file-operations}@anchor{2ce5}
@subsubsection ディレクトリとファイルの操作


@geindex copyfileobj() (shutil モジュール)
@anchor{library/shutil shutil copyfileobj}@anchor{c52}
@deffn {の関数} shutil.copyfileobj (fsrc, fdst[, length])

:term::@cite{file-like object <file object>} `fsrc' の内容を `fdst' へコピーします。整数値 `length' は与えられた場合バッファサイズを表します。特に `length' が負の場合、チャンク内のソースデータを繰り返し操作することなくデータをコピーします。デフォルトでは、制御不能なメモリ消費を避けるためにデータはチャンク内に読み込まれます。 `fsrc' オブジェクトの現在のファイル位置が0でない場合、現在の位置からファイル終端までの内容のみがコピーされることに注意してください。

@ref{c52,,copyfileobj()} will `not' guarantee that the destination stream has
been flushed on completion of the copy. If you want to read from the
destination at the completion of the copy operation (for example, reading
the contents of a temporary file that has been copied from a HTTP stream),
you must ensure that you have called @ref{2ce6,,flush()} or
@ref{506,,close()} on the file-like object before attempting to read
the destination file.
@end deffn

@geindex copyfile() (shutil モジュール)
@anchor{library/shutil shutil copyfile}@anchor{c4e}
@deffn {の関数} shutil.copyfile (src, dst, *, follow_symlinks=True)

`src' という名前のファイルの内容 (メタデータを含まない) を `dst' という名前のファイルにコピーし、最も効率的な方法で `dst' を返します。 `src' と `dst' は @ref{5a1,,path-like object} または文字列でパス名を指定します。

`dst' は完全な対象ファイル名でなければなりません。対象としてディレクトリ名を指定したい場合は @ref{c4f,,copy()} を参照してください。 `src' と `dst' が同じファイルだった場合、 @ref{11a0,,SameFileError} を送出します。

`dst' は書き込み可能でなければなりません。そうでない場合、 @ref{2c0,,OSError} 例外を送出します。 `dst' がすでに存在する場合、そのファイルは置き換えられます。キャラクタデバイスやブロックデバイスなどの特殊なファイルとパイプをこの関数でコピーすることはできません。

`follow_symlinks' が偽で `src' がシンボリックリンクの場合、 `src' のリンク先をコピーする代わりに新しいシンボリックリンクを作成します。

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copyfile} を送出します。


バージョン 3.3 で変更: 以前は @ref{2c0,,OSError} の代わりに @ref{125e,,IOError} が送出されていました。 `follow_symlinks' 引数が追加されました。 `dst' を返すようになりました。



バージョン 3.4 で変更: @ref{119f,,Error} の代わりに @ref{11a0,,SameFileError} を送出します。後者は前者のサブクラスなのでこの変更は後方互換です。



バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 @ref{c53,,プラットフォーム依存の効率的なコピー操作} を参照してください。

@end deffn

@geindex SpecialFileError
@anchor{library/shutil shutil SpecialFileError}@anchor{1533}
@deffn {例外} shutil.SpecialFileError

This exception is raised when @ref{c4e,,copyfile()} or @ref{c1e,,copytree()} attempt
to copy a named pipe.


Added in version 2.7.

@end deffn

@geindex SameFileError
@anchor{library/shutil shutil SameFileError}@anchor{11a0}
@deffn {例外} shutil.SameFileError

@ref{c4e,,copyfile()} のコピー元と先が同じファイルの場合送出されます。


Added in version 3.4.

@end deffn

@geindex copymode() (shutil モジュール)
@anchor{library/shutil shutil copymode}@anchor{1a24}
@deffn {の関数} shutil.copymode (src, dst, *, follow_symlinks=True)

パーミッションを `src' から `dst' にコピーします。ファイルの内容、オーナー、グループには影響しません。 `src' と `dst' は :term`path-like object <path-like object>` または文字列でファイルのパス名を指定します。 `follow_symlinks' が偽で、`src' および `dst' がシンボリックリンクの場合、 @ref{1a24,,copymode()} は (リンク先ではなく)  `dst' 自体のモードを変更します。この機能は全てのプラットフォームで使えるわけではありません。詳しくは @ref{1346,,copystat()} を参照してください。シンボリックリンクの変更をしようとした時、 @ref{1a24,,copymode()} がローカルのプラットフォームでシンボリックリンクを変更できない場合は何もしません。

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copymode} を送出します。


バージョン 3.3 で変更: `follow_symlinks' 引数が追加されました。

@end deffn

@geindex copystat() (shutil モジュール)
@anchor{library/shutil shutil copystat}@anchor{1346}
@deffn {の関数} shutil.copystat (src, dst, *, follow_symlinks=True)

パーミッション、最終アクセス時間、最終変更時間、その他のフラグを `src' から `dst' にコピーします。 Linux では、 @ref{1346,,copystat()} は可能なら "拡張属性" もコピーします。ファイルの内容、オーナー、グループには影響しません。 `src' と `dst' は @ref{5a1,,path-like object} または文字列でファイルのパス名を指定します。

`follow_symlinks' が偽の場合、 `src' と `dst' の両方がシンボリックリンクであれば、 @ref{1346,,copystat()} はリンク先ではなくてシンボリックリンク自体を操作します。 `src' からシンボリックリンクの情報を読み込み、 `dst' のシンボリックリンクにその情報を書き込みます。

@cartouche
@quotation 注釈 
すべてのプラットフォームでシンボリックリンクの検査と変更ができるわけではありません。 Python はその機能が利用かどうかを調べる方法を用意しています。


@itemize *

@item 
@code{os.chmod in os.supports_follow_symlinks} が @code{True} の場合 @ref{1346,,copystat()} はシンボリックリンクのパーミッションを変更できます。

@item 
@code{os.utime in os.supports_follow_symlinks} が @code{True} の場合 @ref{1346,,copystat()} はシンボリックリンクの最終アクセス時間と最終変更時間を変更できます。

@item 
@code{os.chflags in os.supports_follow_symlinks} が @code{True} の場合 @ref{1346,,copystat()} はシンボリックリンクのフラグを変更できます。 (@code{os.chflags} がないプラットフォームもあります。)
@end itemize

機能の幾つか、もしくは全てが利用できないプラットフォームでシンボリックリンクを変更しようとした場合、 @ref{1346,,copystat()} は可能な限り全てをコピーします。@ref{1346,,copystat()} が失敗を返すことはありません。

より詳しい情報は @ref{1310,,os.supports_follow_symlinks} を参照して下さい。
@end quotation
@end cartouche

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copystat} を送出します。


バージョン 3.3 で変更: `follow_symlinks' 引数と Linux の拡張属性がサポートされました。

@end deffn

@geindex copy() (shutil モジュール)
@anchor{library/shutil shutil copy}@anchor{c4f}
@deffn {の関数} shutil.copy (src, dst, *, follow_symlinks=True)

ファイル `src' をファイルまたはディレクトリ `dst' にコピーします。 `src' と `dst' は両方共 @ref{5a1,,path-like object} または文字列でなければなりません。 `dst' がディレクトリを指定している場合、ファイルは `dst' の中に、 `src' のベースファイル名を使ってコピーされます。`dst' が既に存在するファイルを指定している場合、それは置き換えられます。新しく作成したファイルのパスを返します。

`follow_symlinks' が偽で、 `src' がシンボリックリンクの場合、 `dst' はシンボリックリンクとして作成されます。 `follow_symlinks' が真で `src' がシンボリックリンクの場合、 `dst' には `src' のリンク先のファイルがコピーされます。

@ref{c4f,,copy()} はファイルのデータとパーミッションをコピーします。 (@ref{529,,os.chmod()} を参照)
その他の、ファイルの作成時間や変更時間などのメタデータはコピーしません。
コピー元のファイルのメタデータを保存したい場合は、 @code{copy2()} を利用してください。

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copyfile} を送出します。

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copymode} を送出します。


バージョン 3.3 で変更: `follow_symlinks' 引数が追加されました。新しく作成されたファイルのパスを返すようになりました。



バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 @ref{c53,,プラットフォーム依存の効率的なコピー操作} を参照してください。

@end deffn

@geindex copy2() (shutil モジュール)
@anchor{library/shutil shutil copy2}@anchor{c50}
@deffn {の関数} shutil.copy2 (src, dst, *, follow_symlinks=True)

@ref{c50,,copy2()} はファイルのメタデータを保持しようとすることを除けば @ref{c4f,,copy()} と等価です。

`follow_symlinks' が偽でかつ `src' がシンボリックリンクの場合、 @ref{c50,,copy2()} は `src' シンボリックリンク全てのメタデータを新たに作成される `dst' シンボリックリンクにコピーしようとします。しかし、この機能は全てのプラットフォームで利用可能なわけではありません。この機能の全部または一部が利用可能でないプラットフォームにおいては、 @ref{c50,,copy2()} は可能な限りのメタデータを保存しようとしますが、一方で @ref{c50,,copy2()}　はメタデータを保存できないことを理由とする例外を送出しません。

@ref{c50,,copy2()} はファイルのメタデータをコピーするために @ref{1346,,copystat()} を利用します。シンボリックリンクのメタデータを変更するためのプラットフォームサポートについては @ref{1346,,copystat()} を参照して下さい。

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copyfile} を送出します。

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copystat} を送出します。


バージョン 3.3 で変更: `follow_symlinks' 引数が追加されました。 拡張ファイルシステム属性もコピーしようと試みます (現在は Linux のみ)。新しく作成されたファイルへのパスを返すようになりました。



バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 @ref{c53,,プラットフォーム依存の効率的なコピー操作} を参照してください。

@end deffn

@geindex ignore_patterns() (shutil モジュール)
@anchor{library/shutil shutil ignore_patterns}@anchor{2ce7}
@deffn {の関数} shutil.ignore_patterns (*patterns)

このファクトリ関数は、 @ref{c1e,,copytree()} 関数の `ignore' 引数に渡すための呼び出し可能オブジェクトを作成します。 glob形式の `patterns' にマッチするファイルやディレクトリが無視されます。下の例を参照してください。
@end deffn

@geindex copytree() (shutil モジュール)
@anchor{library/shutil shutil copytree}@anchor{c1e}
@deffn {の関数} shutil.copytree (src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)

Recursively copy an entire directory tree rooted at `src' to a directory
named `dst' and return the destination directory.  All intermediate
directories needed to contain `dst' will also be created by default.

各ディレクトリのパーミッション、最終アクセス時間、最終変更時間は @ref{1346,,copystat()} でコピーされます。それぞれのファイルは @ref{c50,,copy2()} でコピーされます。

`symlinks' が真の場合、ソースツリー内のシンボリックリンクは新しいツリーでもシンボリックになり、元のシンボリックリンクのメタデータはプラットフォームが許す限りコピーされます。偽の場合や省略された場合、リンク先のファイルの内容とメタデータが新しいツリーにコピーされます。

`symlinks' が偽の場合、リンク先のファイルが存在しなければ、コピー処理終了時に送出される @ref{119f,,Error} 例外のエラーリストに例外が追加されます。オプションの `ignore_dangling_symlinks' フラグを真に設定してこのエラーを送出させないこともできます。このオプションは @ref{130c,,os.symlink()} をサポートしていないプラットフォーム上では効果がないことに注意してください。

`ignore' は @ref{c1e,,copytree()} が走査しているディレクトリと @ref{1312,,os.listdir()} が返すその内容のリストを引数として受け取ることのできる呼び出し可能オブジェクトでなければなりません。 @ref{c1e,,copytree()} は再帰的に呼び出されるので、 `ignore' はコピーされる各ディレクトリ毎に呼び出されます。 `ignore' の戻り値はカレントディレクトリに相対的なディレクトリ名およびファイル名のシーケンス（すなわち第二引数の項目のサブセット）でなければなりません。それらの名前はコピー中に無視されます。 @ref{2ce7,,ignore_patterns()} を用いて glob 形式のパターンによって無視する呼び出し可能オブジェクトを作成することが出来ます。

例外が発生した場合、理由のリストとともに @ref{119f,,Error} を送出します。

`copy_function' は各ファイルをコピーするために利用される呼び出し可能オブジェクトでなければなりません。`copy_function' はコピー元のパスとコピー先のパスを引数に呼び出されます。デフォルトでは @ref{c50,,copy2()} が利用されますが、同じ特徴を持つ関数 (@ref{c4f,,shutil.copy()} など) ならどれでも利用可能です。

If `dirs_exist_ok' is false (the default) and `dst' already exists, a
@ref{1221,,FileExistsError} is raised. If `dirs_exist_ok' is true, the copying
operation will continue if it encounters existing directories, and files
within the `dst' tree will be overwritten by corresponding files from the
`src' tree.

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.copytree} を送出します。


バージョン 3.2 で変更: Added the `copy_function' argument to be able to provide a custom copy
function.
Added the `ignore_dangling_symlinks' argument to silence dangling symlinks
errors when `symlinks' is false.



バージョン 3.3 で変更: `symlinks' が偽の場合メタデータをコピーします。 `dst' を返すようになりました。



バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 @ref{c53,,プラットフォーム依存の効率的なコピー操作} を参照してください。



バージョン 3.8 で変更: 引数 `dirs_exist_ok' が追加されました。

@end deffn

@geindex rmtree() (shutil モジュール)
@anchor{library/shutil shutil rmtree}@anchor{356}
@deffn {の関数} shutil.rmtree (path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)

@geindex ディレクトリ;削除

Delete an entire directory tree; `path' must point to a directory (but not a
symbolic link to a directory).  If `ignore_errors' is true, errors resulting
from failed removals will be ignored; if false or omitted, such errors are
handled by calling a handler specified by `onexc' or `onerror' or, if both
are omitted, exceptions are propagated to the caller.

この関数は @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

@cartouche
@quotation 注釈 
必要な fd ベースの関数をサポートしているプラットフォームでは、 シンボリックリンク攻撃に耐性のあるバージョンの @ref{356,,rmtree()} がデフォルトで利用されます。それ以外のプラットフォームでは、 @ref{356,,rmtree()} の実装はシンボリックリンク攻撃の影響を受けます。適当なタイミングと環境で攻撃者はファイルシステム上のシンボリックリンクを操作して、それ以外の方法ではアクセス不可能なファイルを削除することが出来ます。アプリケーションは、どちらのバージョンの @ref{356,,rmtree()} が利用されているかを知るために関数のデータ属性 @ref{2ce8,,rmtree.avoids_symlink_attacks} を利用することができます。
@end quotation
@end cartouche

`onexc' を指定する場合、 `function', `path', `excinfo' の3つの引数を受け取る呼び出し可能オブジェクトでなければなりません。

The first parameter, `function', is the function which raised the exception;
it depends on the platform and implementation.  The second parameter,
`path', will be the path name passed to `function'.  The third parameter,
`excinfo', is the exception that was raised. Exceptions raised by `onexc'
will not be caught.

The deprecated `onerror' is similar to `onexc', except that the third
parameter it receives is the tuple returned from @ref{89a,,sys.exc_info()}.


@subsubheading 参考


@ref{2ce9,,rmtree の例} for an example of handling the removal
of a directory tree that contains read-only files.


引数 @code{path}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{shutil.rmtree} を送出します。


バージョン 3.3 で変更: プラットフォームが fd ベースの関数をサポートする場合に自動的に使用されるシンボリックリンク攻撃に耐性のあるバージョンが追加されました。



バージョン 3.8 で変更: Windows では、ディレクトリへのジャンクションを削除する際にリンク先ディレクトリにあるファイルを削除しなくなりました。



バージョン 3.11 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.12 で変更: Added the `onexc' parameter, deprecated `onerror'.



バージョン 3.13 で変更: @code{rmtree()} now ignores @ref{264,,FileNotFoundError} exceptions for all
but the top-level path.
Exceptions other than @ref{2c0,,OSError} and subclasses of @code{OSError}
are now always propagated to the caller.


@geindex avoids_symlink_attacks (shutil.rmtree の属性)
@anchor{library/shutil shutil rmtree avoids_symlink_attacks}@anchor{2ce8}
@deffn {の属性} rmtree.avoids_symlink_attacks

プラットフォームと実装がシンボリックリンク攻撃に耐性のあるバージョンの @ref{356,,rmtree()} を提供しているかどうかを示します。現在のところ、この属性は fd ベースのディレクトリアクセス関数をサポートしているプラットフォームでのみ真になります。


Added in version 3.3.

@end deffn
@end deffn

@geindex move() (shutil モジュール)
@anchor{library/shutil shutil move}@anchor{c51}
@deffn {の関数} shutil.move (src, dst, copy_function=copy2)

ファイルまたはディレクトリ (`src') を再帰的に別の場所に移動して、移動先を返します。

If `dst' is an existing directory or a symlink to a directory, then `src'
is moved inside that directory. The destination path in that directory must
not already exist.

If `dst' already exists but is not a directory, it may be overwritten
depending on @ref{1309,,os.rename()} semantics.

If the destination is on the current filesystem, then @ref{1309,,os.rename()} is
used. Otherwise, `src' is copied to the destination using `copy_function'
and then removed.  In case of symlinks, a new symlink pointing to the target
of `src' will be created as the destination and `src' will be removed.

If `copy_function' is given, it must be a callable that takes two arguments,
`src' and the destination, and will be used to copy `src' to the destination
if @ref{1309,,os.rename()} cannot be used.  If the source is a directory,
@ref{c1e,,copytree()} is called, passing it the `copy_function'. The
default `copy_function' is @ref{c50,,copy2()}.  Using @ref{c4f,,copy()} as the
`copy_function' allows the move to succeed when it is not possible to also
copy the metadata, at the expense of not copying any of the metadata.

引数 @code{src}, @code{dst} を指定して @ref{1c6e,,監査イベント} @code{shutil.move} を送出します。


バージョン 3.3 で変更: 異なるファイルシステムに対する明示的なシンボリックリンク処理が追加されました。これにより GNU @code{mv} の振る舞いに適応するようになります。 `dst' を返すようになりました。



バージョン 3.5 で変更: キーワード引数 `copy_function' が追加されました。



バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 @ref{c53,,プラットフォーム依存の効率的なコピー操作} を参照してください。



バージョン 3.9 で変更: `src' と `dst' が両方とも @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex disk_usage() (shutil モジュール)
@anchor{library/shutil shutil disk_usage}@anchor{1345}
@deffn {の関数} shutil.disk_usage (path)

指定されたパスについて、ディスクの利用状況を、名前付きタプル (@ref{85e,,named tuple}) で返します。このタプルには `total', `used', `free' という属性があり、それぞれトータル、使用中、空きの容量をバイト単位で示します。 `path' はファイルまたはディレクトリです。

@cartouche
@quotation 注釈 
On Unix filesystems, `path' must point to a path within a `mounted'
filesystem partition. On those platforms, CPython doesn't attempt to
retrieve disk usage information from non-mounted filesystems.
@end quotation
@end cartouche


Added in version 3.3.



バージョン 3.8 で変更: Windowsにおいても `path' にディレクトリだけでなくファイルを指定できるようになりました。


@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex chown() (shutil モジュール)
@anchor{library/shutil shutil chown}@anchor{548}
@deffn {の関数} shutil.chown (path, user=None, group=None, *, dir_fd=None, follow_symlinks=True)

指定された `path' のオーナー `user' と/または `group' を変更します。

`user' はシステムのユーザー名か uid です。 `group' も同じです。少なくともどちらかの引数を指定する必要があります。

内部で利用している @ref{1306,,os.chown()} も参照してください。

引数 @code{path}, @code{user}, @code{group} を指定して @ref{1c6e,,監査イベント} @code{shutil.chown} を送出します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.



バージョン 3.13 で変更: 引数 `dir_fd' および `follow_symlinks' が追加されました。

@end deffn

@geindex which() (shutil モジュール)
@anchor{library/shutil shutil which}@anchor{6db}
@deffn {の関数} shutil.which (cmd, mode=os.F_OK | os.X_OK, path=None)

`cmd' を実行しようとした時に実行される実行ファイルのパスを返します。 `cmd' を呼び出せない場合は @code{None} を返します。

`mode' は @ref{1304,,os.access()} に渡すパーミッションマスクで、デフォルトではファイルが存在して実行可能であることを確認します。

`path' is a "@code{PATH} string" specifying the directories to look in,
delimited by @ref{2134,,os.pathsep}. When no `path' is specified, the
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable is read from @ref{259,,os.environ},
falling back to @ref{1de4,,os.defpath} if it is not set.

If `cmd' contains a directory component, @code{which()} only checks the
specified path directly and does not search the directories listed in
`path' or in the system's 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable.

On Windows, the current directory is prepended to the `path' if `mode' does
not include @code{os.X_OK}. When the `mode' does include @code{os.X_OK}, the
Windows API @code{NeedCurrentDirectoryForExePathW} will be consulted to
determine if the current directory should be prepended to `path'. To avoid
consulting the current working directory for executables: set the environment
variable @code{NoDefaultCurrentDirectoryInExePath}.

Also on Windows, the 
@geindex PATHEXT
@geindex 環境変数; PATHEXT
@code{PATHEXT} environment variable is used to
resolve commands that may not already include an extension. For example,
if you call @code{shutil.which("python")}, @ref{6db,,which()} will search @code{PATHEXT}
to know that it should look for @code{python.exe} within the `path'
directories. For example, on Windows:

@example
>>> shutil.which("python")
'C:\\Python33\\python.EXE'
@end example

This is also applied when `cmd' is a path that contains a directory
component:

@example
>>> shutil.which("C:\\Python33\\python")
'C:\\Python33\\python.EXE'
@end example


Added in version 3.3.



バージョン 3.8 で変更: @ref{192,,bytes} 型も使用できるようになりました。 `cmd' が @ref{192,,bytes} 型の場合、戻り値も @ref{192,,bytes} 型です。



バージョン 3.12 で変更: On Windows, the current directory is no longer prepended to the search
path if `mode' includes @code{os.X_OK} and WinAPI
@code{NeedCurrentDirectoryForExePathW(cmd)} is false, else the current
directory is prepended even if it is already in the search path;
@code{PATHEXT} is used now even when `cmd' includes a directory component
or ends with an extension that is in @code{PATHEXT}; and filenames that
have no extension can now be found.

@end deffn

@geindex Error
@anchor{library/shutil shutil Error}@anchor{119f}
@deffn {例外} shutil.Error

この例外は複数ファイルの操作を行っているときに生じる例外をまとめたものです。 @ref{c1e,,copytree()} に対しては例外の引数は3つのタプル(`srcname', `dstname', `exception')からなるリストです。
@end deffn

@menu
* プラットフォーム依存の効率的なコピー操作:: 
* copytree の例:: 
* rmtree の例:: 

@end menu

@node プラットフォーム依存の効率的なコピー操作,copytree の例,,ディレクトリとファイルの操作
@anchor{library/shutil platform-dependent-efficient-copy-operations}@anchor{2cea}@anchor{library/shutil shutil-platform-dependent-efficient-copy-operations}@anchor{c53}
@subsubsection プラットフォーム依存の効率的なコピー操作


Python 3.8 から、ファイルのコピーを伴う全ての関数 (@ref{c4e,,copyfile()}, @ref{c4f,,copy()}, @ref{c50,,copy2()}, @ref{c1e,,copytree()}, および @ref{c51,,move()}) はより効率的なファイルのコピーのためにプラットフォーム特有の "高速なコピー" を行うことがあります (bpo-33671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33671} を参照してください). ここで "高速なコピー" とは、  "@code{outfd.write(infd.read())}" のようにPython が管理するユーザー空間のバッファを利用することを避け、コピー操作がカーネル空間内で行われることを意味します。

macOS では fcopyfile@footnote{http://www.manpagez.com/man/3/copyfile/} がファイルの内容（メタデータを除く）をコピーするために利用されます。

Linux では @ref{18b4,,os.copy_file_range()} または @ref{d05,,os.sendfile()} が利用されます。

Solaris では @ref{d05,,os.sendfile()} が利用されます。

Windows では @ref{c4e,,shutil.copyfile()} はより大きなバッファサイズをデフォルトとして使います (6 KiB の代わりに 1 MiB が使われます)。また、 @ref{165,,memoryview()} ベースの変形である @ref{c52,,shutil.copyfileobj()} が使われます。

If the fast-copy operation fails and no data was written in the destination
file then shutil will silently fall back to less efficient
@ref{c52,,copyfileobj()} function internally.


バージョン 3.8 で変更.



バージョン 3.14 で変更: Solaris now uses @ref{d05,,os.sendfile()}.



バージョン 3.14 で変更: Copy-on-write or server-side copy may be used internally via
@ref{18b4,,os.copy_file_range()} on supported Linux filesystems.


@node copytree の例,rmtree の例,プラットフォーム依存の効率的なコピー操作,ディレクトリとファイルの操作
@anchor{library/shutil copytree-example}@anchor{2ceb}@anchor{library/shutil shutil-copytree-example}@anchor{2cec}
@subsubsection copytree の例


@ref{2ce7,,ignore_patterns()} ヘルパ関数を利用する例です:

@example
from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
@end example

この例では、 @code{.pyc} ファイルと、 @code{tmp} で始まる全てのファイルやディレクトリを除いて、全てをコピーします。

`ignore' 引数にロギングさせる別の例です。

@example
from shutil import copytree
import logging

def _logpath(path, names):
    logging.info('Working in %s', path)
    return []   # nothing will be ignored

copytree(source, destination, ignore=_logpath)
@end example

@node rmtree の例,,copytree の例,ディレクトリとファイルの操作
@anchor{library/shutil rmtree-example}@anchor{2ced}@anchor{library/shutil shutil-rmtree-example}@anchor{2ce9}
@subsubsection rmtree の例


次の例は、Windows で一部のファイルが読み取り専用のビットセットを含む場合に、ディレクトリツリーを削除する方法を示します。onexc コールバックを使用して、読み取り専用のビットを消去し、削除を再試行します。結果として失敗が発生した場合、それらは伝搬されます:

@example
import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onexc=remove_readonly)
@end example

@node アーカイブ化操作,出力ターミナルのサイズの取得,ディレクトリとファイルの操作,shutil --- 高水準のファイル操作
@anchor{library/shutil archiving-operations}@anchor{1431}@anchor{library/shutil id1}@anchor{2cee}
@subsubsection アーカイブ化操作



Added in version 3.2.



バージョン 3.5 で変更: `xztar' 形式のサポートが追加されました。


圧縮とアーカイブ化されているファイルの読み書きの高水準なユーティリティも提供されています。これらは @ref{137,,zipfile} 、 @ref{e4,,tarfile} モジュールに依拠しています。

@geindex make_archive() (shutil モジュール)
@anchor{library/shutil shutil make_archive}@anchor{6da}
@deffn {の関数} shutil.make_archive (base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

アーカイブファイル (zip や tar) を作成してその名前を返します。

`base_name' is the name of the file to create, including the path, minus
any format-specific extension.

`format' is the archive format: one of
"zip" (if the @ref{139,,zlib} module is available), "tar", "gztar" (if the
@ref{139,,zlib} module is available), "bztar" (if the @ref{14,,bz2} module is
available), "xztar" (if the @ref{8e,,lzma} module is available), or "zstdtar"
(if the @ref{23,,compression.zstd} module is available).

`root_dir' はアーカイブファイルのルートとなるディレクトリです。アーカイブに含まれる全てのパスは `root_dir' からの相対パスになります。これは、アーカイブファイルを生成する前に `root_dir' へ移動することに相当します。

`base_dir' はアーカイブを開始するディレクトリです。すなわち、 `base_dir' アーカイブに含まれるファイルとディレクトリに対する共通のプレフィックスになります。 `base_dir' は `root_dir' からの相対パスでなければなりません。 `base_dir' と `root_dir' を組み合わせて使う方法については @ref{2cef,,base_dir を使ったアーカイブ化の例} を参照してください。

`root_dir' と `base_dir' のどちらも、デフォルトはカレントディレクトリです。

`dry_run' が真の場合、アーカイブは作成されませんが実行される操作は `logger' に記録されます。

`owner' と `group' は、tar アーカイブを作成するときに使われます。デフォルトでは、カレントのオーナーとグループを使います。

`logger' は 
@geindex Python Enhancement Proposals; PEP 282
PEP 282@footnote{https://peps.python.org/pep-0282/} に互換なオブジェクトでなければなりません。これは普通は @ref{d46,,logging.Logger} のインスタンスです。

`verbose' 引数は使用されず、非推奨です。

引数 @code{base_name}, @code{format}, @code{root_dir}, @code{base_dir} を指定して @ref{1c6e,,監査イベント} @code{shutil.make_archive} を送出します。

@cartouche
@quotation 注釈 
This function is not thread-safe when custom archivers registered
with @ref{2cf0,,register_archive_format()} do not support the `root_dir'
argument.  In this case it
temporarily changes the current working directory of the process
to `root_dir' to perform archiving.
@end quotation
@end cartouche


バージョン 3.8 で変更: @code{format="tar"} で作成されたアーカイブでは、レガシーなGNU形式に代わってモダンな pax (POSIX.1-2001) 形式が使われます。



バージョン 3.10.6 で変更: This function is now made thread-safe during creation of standard
@code{.zip} and tar archives.

@end deffn

@geindex get_archive_formats() (shutil モジュール)
@anchor{library/shutil shutil get_archive_formats}@anchor{2cf1}
@deffn {の関数} shutil.get_archive_formats ()

アーカイブ化をサポートしているフォーマットのリストを返します。返されるシーケンスのそれぞれの要素は、タプル @code{(name, description)} です。

By default @code{shutil} provides these formats:


@itemize -

@item 
`zip': ZIP ファイル (@ref{139,,zlib} モジュールが利用可能な場合)。

@item 
`tar': 非圧縮の tar ファイル。 POSIX.1-2001 pax 形式が使われます。

@item 
`gztar': gzip で圧縮された tar ファイル (@ref{139,,zlib} モジュールが利用可能な場合)。

@item 
`bztar': bzip2 で圧縮された tar ファイル (@ref{14,,bz2} モジュールが利用可能な場合)。

@item 
`xztar': xz で圧縮された tar ファイル (@ref{8e,,lzma} モジュールが利用可能な場合)。

@item 
`zstdtar': Zstandard で圧縮された tar ファイル (@ref{23,,compression.zstd} モジュールが利用可能な場合)。
@end itemize

@ref{2cf0,,register_archive_format()} を使って、新しいフォーマットを登録したり、既存のフォーマットに独自のアーカイバを提供したりできます。
@end deffn

@geindex register_archive_format() (shutil モジュール)
@anchor{library/shutil shutil register_archive_format}@anchor{2cf0}
@deffn {の関数} shutil.register_archive_format (name, function[, extra_args[, description]])

アーカイバをフォーマット `name' に登録します。

`function' はアーカイブのアンパックに使用される呼び出し可能オブジェクトです。`funciton' は作成するファイルの `base_name'、続いてアーカイブを開始する元の `base_dir' (デフォルトは @ref{2c57,,os.curdir}) を受け取ります。さらなる引数は、次のキーワード引数として渡されます: `owner', `group', `dry_run' ならびに `logger' (@ref{6da,,make_archive()} に渡されます)。

If `function' has the custom attribute @code{function.supports_root_dir} set to @code{True},
the `root_dir' argument is passed as a keyword argument.
Otherwise the current working directory of the process is temporarily
changed to `root_dir' before calling `function'.
In this case @ref{6da,,make_archive()} is not thread-safe.

`extra_args' は、与えられた場合、 @code{(name, value)} の対のシーケンスで、アーカイバ呼び出し可能オブジェクトが使われるときに追加のキーワード引数として使われます。

`description' は、アーカイバのリストを返す @ref{2cf1,,get_archive_formats()} で使われます。デフォルトでは空の文字列です。


バージョン 3.12 で変更: Added support for functions supporting the `root_dir' argument.

@end deffn

@geindex unregister_archive_format() (shutil モジュール)
@anchor{library/shutil shutil unregister_archive_format}@anchor{2cf2}
@deffn {の関数} shutil.unregister_archive_format (name)

アーカイブフォーマット `name' を、サポートされているフォーマットのリストから取り除きます。
@end deffn

@geindex unpack_archive() (shutil モジュール)
@anchor{library/shutil shutil unpack_archive}@anchor{696}
@deffn {の関数} shutil.unpack_archive (filename[, extract_dir[, format[, filter]]])

アーカイブをアンパックします。 `filename' はアーカイブのフルパスです。

`extract_dir' はアーカイブをアンパックする先のディレクトリ名です。指定されなかった場合は現在の作業ディレクトリを利用します。

`format' はアーカイブフォーマットで、 "zip", "tar", "gztar", "bztar", "xztar", "zstdtar" あるいは @ref{2cf3,,register_unpack_format()} で登録したその他のフォーマットのどれかです。
指定されなかった場合、 @ref{696,,unpack_archive()} はアーカイブファイル名の拡張子に対して登録されたアンパッカーを利用します。
アンパッカーが見つからなかった場合、 @ref{2ec,,ValueError} を発生させます。

The keyword-only `filter' argument is passed to the underlying unpacking
function. For zip files, `filter' is not accepted.
For tar files, it is recommended to use @code{'data'} (default since Python
3.14), unless using features specific to tar and UNIX-like filesystems.
(See @ref{697,,Extraction filters} for details.)

引数 @code{filename}, @code{extract_dir}, @code{format} を指定して @ref{1c6e,,監査イベント} @code{shutil.unpack_archive} を送出します。

@cartouche
@quotation 警告 
Never extract archives from untrusted sources without prior inspection.
It is possible that files are created outside of the path specified in
the `extract_dir' argument, e.g. members that have absolute filenames
starting with "/" or filenames with two dots "..".

Since Python 3.14, the defaults for both built-in formats (zip and tar
files) will prevent the most dangerous of such security issues,
but will not prevent `all' unintended behavior.
Read the @ref{2cf4,,Hints for further verification}
section for tar-specific details.
@end quotation
@end cartouche


バージョン 3.7 で変更: `filename' と `extract_dir' が @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.12 で変更: `filter' 引数が追加されました。

@end deffn

@geindex register_unpack_format() (shutil モジュール)
@anchor{library/shutil shutil register_unpack_format}@anchor{2cf3}
@deffn {の関数} shutil.register_unpack_format (name, extensions, function[, extra_args[, description]])

アンパック用のフォーマットを登録します。 `name' はフォーマット名で、 `extensions' はそのフォーマットに対応する拡張子 (例えば Zip ファイルに対して @code{.zip}) のリストです。

`function' is the callable that will be used to unpack archives. The
callable will receive:


@itemize -

@item 
the path of the archive, as a positional argument;

@item 
the directory the archive must be extracted to, as a positional argument;

@item 
possibly a `filter' keyword argument, if it was given to
@ref{696,,unpack_archive()};

@item 
additional keyword arguments, specified by `extra_args' as a sequence
of @code{(name, value)} tuples.
@end itemize

フォーマットの説明として `description' を指定することができます。これは @ref{2cf5,,get_unpack_formats()} 関数によって返されます。
@end deffn

@geindex unregister_unpack_format() (shutil モジュール)
@anchor{library/shutil shutil unregister_unpack_format}@anchor{2cf6}
@deffn {の関数} shutil.unregister_unpack_format (name)

アンパックフォーマットを登録解除します。 `name' はフォーマットの名前です。
@end deffn

@geindex get_unpack_formats() (shutil モジュール)
@anchor{library/shutil shutil get_unpack_formats}@anchor{2cf5}
@deffn {の関数} shutil.get_unpack_formats ()

登録されているすべてのアンパックフォーマットをリストで返します。戻り値のリストの各要素は @code{(name, extensions, description)} の形のタプルです。

By default @code{shutil} provides these formats:


@itemize -

@item 
`zip': ZIP ファイル (対応するモジュールが利用可能な場合にのみ圧縮ファイルはアンパックされます)。

@item 
`tar': 圧縮されていない tar ファイル。

@item 
`gztar': gzip で圧縮された tar ファイル (@ref{139,,zlib} モジュールが利用可能な場合)。

@item 
`bztar': bzip2 で圧縮された tar ファイル (@ref{14,,bz2} モジュールが利用可能な場合)。

@item 
`xztar': xz で圧縮された tar ファイル (@ref{8e,,lzma} モジュールが利用可能な場合)。

@item 
`zstdtar': Zstandard で圧縮された tar ファイル (@ref{23,,compression.zstd} モジュールが利用可能な場合)。
@end itemize

@ref{2cf3,,register_unpack_format()} を使って新しいフォーマットや既存のフォーマットに対する別のアンパッカーを登録することができます。
@end deffn

@menu
* アーカイブ化の例:: 
* base_dir を使ったアーカイブ化の例:: 

@end menu

@node アーカイブ化の例,base_dir を使ったアーカイブ化の例,,アーカイブ化操作
@anchor{library/shutil archiving-example}@anchor{2cf7}@anchor{library/shutil shutil-archiving-example}@anchor{2cf8}
@subsubsection アーカイブ化の例


この例では、ユーザの @code{.ssh} ディレクトリにあるすべてのファイルを含む、 gzip された tar ファイルアーカイブを作成します:

@example
>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
>>> make_archive(archive_name, 'gztar', root_dir)
'/Users/tarek/myarchive.tar.gz'
@end example

結果のアーカイブは、以下のものを含みます:

@example
$ tar -tzvf /Users/tarek/myarchive.tar.gz
drwx------ tarek/staff       0 2010-02-01 16:23:40 ./
-rw-r--r-- tarek/staff     609 2008-06-09 13:26:54 ./authorized_keys
-rwxr-xr-x tarek/staff      65 2008-06-09 13:26:54 ./config
-rwx------ tarek/staff     668 2008-06-09 13:26:54 ./id_dsa
-rwxr-xr-x tarek/staff     609 2008-06-09 13:26:54 ./id_dsa.pub
-rw------- tarek/staff    1675 2008-06-09 13:26:54 ./id_rsa
-rw-r--r-- tarek/staff     397 2008-06-09 13:26:54 ./id_rsa.pub
-rw-r--r-- tarek/staff   37192 2010-02-06 18:23:10 ./known_hosts
@end example

@node base_dir を使ったアーカイブ化の例,,アーカイブ化の例,アーカイブ化操作
@anchor{library/shutil archiving-example-with-base-dir}@anchor{2cf9}@anchor{library/shutil shutil-archiving-example-with-basedir}@anchor{2cef}
@subsubsection `base_dir' を使ったアーカイブ化の例


この例では、 @ref{2cf8,,上記の例} と同じく @ref{6da,,make_archive()} の使い方を示しますが、ここでは特に `base_dir' の使い方を説明します。以下のようなディレクトリ構造があるとします。

@example
$ tree tmp
tmp
└── root
    └── structure
        ├── content
            └── please_add.txt
        └── do_not_add.txt
@end example

作成するアーカイブには @code{please_add.txt} が含まれますが、いっぽう @code{do_not_add.txt} は含まないようにします。この場合以下のようにします。

@example
>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> make_archive(
...     archive_name,
...     'tar',
...     root_dir='tmp/root',
...     base_dir='structure/content',
... )
'/Users/tarek/myarchive.tar'
@end example

アーカイブに含まれるファイルをリストすると、以下のようになります。

@example
$ python -m tarfile -l /Users/tarek/myarchive.tar
structure/content/
structure/content/please_add.txt
@end example

@node 出力ターミナルのサイズの取得,,アーカイブ化操作,shutil --- 高水準のファイル操作
@anchor{library/shutil querying-the-size-of-the-output-terminal}@anchor{2cfa}
@subsubsection 出力ターミナルのサイズの取得


@geindex get_terminal_size() (shutil モジュール)
@anchor{library/shutil shutil get_terminal_size}@anchor{131b}
@deffn {の関数} shutil.get_terminal_size (fallback=(columns, lines))

ターミナルウィンドウのサイズを取得します。

幅と高さについて、それぞれ @code{COLUMNS} と @code{LINES} という環境変数をチェックします。その変数が定義されていて値が正の整数であればそれを利用します。

典型的な @code{COLUMNS} や @code{LINES} が定義されていない場合には、 @ref{2cfb,,sys.__stdout__} に接続されているターミナルに @ref{131a,,os.get_terminal_size()} を呼び出して問い合わせます。

システムが対応していない場合やターミナルに接続していないなどの理由でターミナルサイズの問い合わせに失敗した場合、 @code{fallback} 引数に与えられた値を利用します。 @code{fallback} のデフォルト値は @code{(80, 24)} で、これは多くのターミナルエミュレーターが利用しているデフォルトサイズです。

戻り値は @ref{2cfc,,os.terminal_size} 型の名前付きタプルです。

参考: The Single UNIX Specification, Version 2, Other Environment Variables@footnote{https://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003}.


Added in version 3.3.



バージョン 3.11 で変更: The @code{fallback} values are also used if @ref{131a,,os.get_terminal_size()}
returns zeroes.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)


@subsubheading 参考



@table @asis

@item @ref{a5,,os} モジュール

オペレーティングシステムのインターフェース、Python の @ref{13db,,ファイルオブジェクト} より低レベルでのファイル操作を含みます。

@item @ref{83,,io} モジュール

Python 組み込みの I/O ライブラリで、抽象クラスとファイル I/O のようないくつかの具象クラスを含みます。

@item @ref{316,,open()} 組み込み関数

Python で読み書きのためにファイルを開く標準的な方法です。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node データの永続化,データ圧縮とアーカイブ,ファイルとディレクトリへのアクセス,Python 標準ライブラリ
@anchor{library/persistence doc}@anchor{2cfd}@anchor{library/persistence data-persistence}@anchor{2cfe}@anchor{library/persistence persistence}@anchor{2cff}@anchor{library/persistence translation-repo}@anchor{2d00}
@section データの永続化


この章で解説されるモジュール群は Python データをディスクに永続的な形式で保存します。モジュール @ref{ab,,pickle} とモジュール @ref{91,,marshal} は多くの Python データ型をバイト列に変換し、バイト列から再生成します。様々な DBM 関連モジュールはハッシュを基にした、文字列から他の文字列へのマップを保存するファイルフォーマット群をサポートします。

この章で解説されるモジュールのリスト:

@menu
* pickle: pickle --- Python オブジェクトの直列化. Python オブジェクトの直列化
* copyreg: copyreg --- pickle サポート関数を登録する. pickle サポート関数を登録する
* shelve: shelve --- Python オブジェクトの永続化. Python オブジェクトの永続化
* marshal: marshal --- 内部使用向けの Python オブジェクト直列化. 内部使用向けの Python オブジェクト直列化
* dbm: dbm --- Unix "データベース" へのインターフェース. Unix "データベース" へのインターフェース
* sqlite3: sqlite3 --- SQLite データベース用の DB-API 2 0 インターフェース. SQLite データベース用の DB-API 2.0 インターフェース

@end menu

@node pickle --- Python オブジェクトの直列化,copyreg --- pickle サポート関数を登録する,,データの永続化
@anchor{library/pickle doc}@anchor{2d01}@anchor{library/pickle module-pickle}@anchor{ab}@anchor{library/pickle pickle-python-object-serialization}@anchor{2d02}
@subsection @code{pickle} --- Python オブジェクトの直列化


@geindex module; pickle

`ソースコード:' Lib/pickle.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pickle.py}

@geindex 永続化
@geindex 永続化;オブジェクト
@geindex 直列化;オブジェクト
@geindex 整列化;オブジェクト
@geindex 平坦化;オブジェクト
@geindex pickle 化;オブジェクト


__________________________________________________________________


The @code{pickle} module implements binary protocols for serializing and
de-serializing a Python object structure.  `"Pickling"' is the process
whereby a Python object hierarchy is converted into a byte stream, and
`"unpickling"' is the inverse operation, whereby a byte stream
(from a @ref{206e,,binary file} or @ref{193,,bytes-like object}) is converted
back into an object hierarchy.  Pickling (and unpickling) is alternatively
known as "serialization", "marshalling," @footnote{
@ref{91,,marshal} モジュールと間違えないように注意してください。
} or "flattening"; however, to
avoid confusion, the terms used here are "pickling" and "unpickling".

@cartouche
@quotation 警告 
@code{pickle} モジュールは `安全ではありません' 。信頼できるデータのみを非 pickle 化してください。

`非 pickle 化の過程で任意のコードを実行する' ような、悪意ある pickle オブジェクトを生成することが可能です。信頼できない提供元からのデータや、改竄された可能性のあるデータの非 pickle 化は絶対に行わないでください。

データが改竄されていないことを保証したい場合は、 @ref{6e,,hmac} による鍵付きハッシュ化を検討してください。

信頼できないデータを処理する場合 @ref{86,,json} のようなより安全な直列化形式の方が適切でしょう。 @ref{2d03,,json との比較} を参照してください。
@end quotation
@end cartouche

@menu
* 他の Python モジュールとの関係:: 
* データストリームの形式:: 
* モジュールインターフェース:: 
* pickle 化、非 pickle 化できるもの:: 
* クラスインスタンスの pickle 化:: 
* 型、関数、その他のオブジェクトに対するリダクションのカスタマイズ:: 
* アウトオブバウンドバッファ:: 
* グローバル変数を制限する:: 
* 性能: 性能<2>. 
* 使用例: 使用例<11>. 
* コマンドライン・インターフェース:: 

@end menu

@node 他の Python モジュールとの関係,データストリームの形式,,pickle --- Python オブジェクトの直列化
@anchor{library/pickle relationship-to-other-python-modules}@anchor{2d04}
@subsubsection 他の Python モジュールとの関係


@menu
* marshal との比較:: 
* json との比較:: 

@end menu

@node marshal との比較,json との比較,,他の Python モジュールとの関係
@anchor{library/pickle comparison-with-marshal}@anchor{2d05}
@subsubsection @code{marshal} との比較


Python has a more primitive serialization module called @ref{91,,marshal}, but in
general @code{pickle} should always be the preferred way to serialize Python
objects.  @ref{91,,marshal} exists primarily to support Python's @code{.pyc}
files.

The @code{pickle} module differs from @ref{91,,marshal} in several significant ways:


@itemize *

@item 
@ref{91,,marshal} cannot be used to serialize user-defined classes and their
instances.  @code{pickle} can save and restore class instances transparently,
however the class definition must be importable and live in the same module as
when the object was stored.

@item 
The @ref{91,,marshal} serialization format is not guaranteed to be portable
across Python versions.  Because its primary job in life is to support
@code{.pyc} files, the Python implementers reserve the right to change the
serialization format in non-backwards compatible ways should the need arise.
The @code{pickle} serialization format is guaranteed to be backwards compatible
across Python releases provided a compatible pickle protocol is chosen and
pickling and unpickling code deals with Python 2 to Python 3 type differences
if your data is crossing that unique breaking change language boundary.
@end itemize

@node json との比較,,marshal との比較,他の Python モジュールとの関係
@anchor{library/pickle comparison-with-json}@anchor{2d03}@anchor{library/pickle id2}@anchor{2d06}
@subsubsection @code{json} との比較


pickle プロトコルと JSON (JavaScript Object Notation)@footnote{https://json.org} との基本的な違いは以下のとおりです:


@itemize *

@item 
JSON はテキストの直列化フォーマット (大抵の場合 @code{utf-8} にエンコードされますが、その出力は Unicode 文字列です) で、pickle はバイナリの直列化フォーマットです;

@item 
JSON は人間が読める形式ですが、pickle はそうではありません;

@item 
JSON は相互運用可能で Python 以外でも広く使用されていますが、pickle は Python 固有です;

@item 
JSON は、デフォルトでは Python の組み込み型の一部しか表現することができず、カスタムクラスに対しても行えません; pickle は極めて多くの Python 組み込み型を表現できます (その多くは賢い Python 内省機構によって自動的に行われます; 複雑なケースでは @ref{2d07,,固有のオブジェクト API} によって対応できます)。

@item 
pickleとは異なり、信頼できないJSONを復元するだけでは、任意のコードを実行できる脆弱性は発生しません。
@end itemize


@subsubheading 参考


@ref{86,,json} モジュール: JSON への直列化および復元を行うための標準ライブラリモジュール。


@node データストリームの形式,モジュールインターフェース,他の Python モジュールとの関係,pickle --- Python オブジェクトの直列化
@anchor{library/pickle data-stream-format}@anchor{2d08}@anchor{library/pickle pickle-protocols}@anchor{27b}
@subsubsection データストリームの形式


@geindex 外部データ表現

The data format used by @code{pickle} is Python-specific.  This has the
advantage that there are no restrictions imposed by external standards such as
JSON (which can't represent pointer sharing); however it means that
non-Python programs may not be able to reconstruct pickled Python objects.

By default, the @code{pickle} data format uses a relatively compact binary
representation.  If you need optimal size characteristics, you can efficiently
@ref{2d09,,compress} pickled data.

The module @ref{ac,,pickletools} contains tools for analyzing data streams
generated by @code{pickle}.  @ref{ac,,pickletools} source code has extensive
comments about opcodes used by pickle protocols.

現在 pickle 化には 6 種類のプロトコルを使用できます。より高いプロトコルを使用するほど、作成された pickle を読み込むためにより高い Python のバージョンが必要になります。


@itemize *

@item 
プロトコルバージョン 0 はオリジナルの「人間に判読可能な」プロトコルで、Python の初期のバージョンとの後方互換性を持ちます。

@item 
プロトコルバージョン 1 は旧形式のバイナリフォーマットで、これも Python の初期バージョンと互換性があります。

@item 
プロトコルバージョン 2 は Python 2.3 で導入されました。このバージョンでは @ref{2d0a,,新方式のクラス} のより効率的な pickle 化を提供しました。プロトコル 2 による改良に関する情報は 
@geindex Python Enhancement Proposals; PEP 307
PEP 307@footnote{https://peps.python.org/pep-0307/} を参照してください。

@item 
プロトコルバージョン 3 は Python 3 で追加されました。 @ref{192,,bytes} オブジェクトを明示的にサポートしており、 Python 2.x で unpickle することはできません。これは Python 3.0から3.7のデフォルトプロトコルでした。

@item 
プロトコルバージョン 4 は Python 3.4 で追加されました。このバージョンでは巨大なオブジェクトのサポート、より多くの種類のオブジェクトの pickle 化、および一部のデータ形式の最適化が行われました。これはPython 3.8から3.13 までのデフォルトプロトコルでした。プロトコル 4 による改良に関する情報は 
@geindex Python Enhancement Proposals; PEP 3154
PEP 3154@footnote{https://peps.python.org/pep-3154/} を参照してください。

@item 
プロトコルバージョン 5 は Python 3.8 で追加されました。このバージョンでは帯域外データのサポートが追加され、また帯域内データに対するパフォーマンスが向上します。これはPython 3.14からのデフォルトプロトコルです。プロトコルバージョン 5 によってもたらされる改善についての情報は 
@geindex Python Enhancement Proposals; PEP 574
PEP 574@footnote{https://peps.python.org/pep-0574/} を参照してください。
@end itemize

@cartouche
@quotation 注釈 
Serialization is a more primitive notion than persistence; although
@code{pickle} reads and writes file objects, it does not handle the issue of
naming persistent objects, nor the (even more complicated) issue of concurrent
access to persistent objects.  The @code{pickle} module can transform a complex
object into a byte stream and it can transform the byte stream into an object
with the same internal structure.  Perhaps the most obvious thing to do with
these byte streams is to write them onto a file, but it is also conceivable to
send them across a network or store them in a database.  The @ref{c8,,shelve}
module provides a simple interface to pickle and unpickle objects on
DBM-style database files.
@end quotation
@end cartouche

@node モジュールインターフェース,pickle 化、非 pickle 化できるもの,データストリームの形式,pickle --- Python オブジェクトの直列化
@anchor{library/pickle module-interface}@anchor{2d0b}
@subsubsection モジュールインターフェース


オブジェクト階層を直列化するには、@ref{16bd,,dumps()} 関数を呼ぶだけです。同様に、データストリームを復元するには、@ref{f0d,,loads()} 関数を呼びます。しかし、直列化および復元に対してより多くのコントロールを行いたい場合、それぞれ @ref{c13,,Pickler} または @ref{1777,,Unpickler} オブジェクトを作成することができます。

The @code{pickle} module provides the following constants:

@geindex HIGHEST_PROTOCOL (pickle モジュール)
@anchor{library/pickle pickle HIGHEST_PROTOCOL}@anchor{16be}
@deffn {データ} pickle.HIGHEST_PROTOCOL

利用可能なうち最も高い @ref{27b,,プロトコルバージョン} (整数)。この値は `protocol' 値として関数 @ref{2d0c,,dump()}  および @ref{16bd,,dumps()} と、@ref{c13,,Pickler} コンストラクターに渡すことができます。
@end deffn

@geindex DEFAULT_PROTOCOL (pickle モジュール)
@anchor{library/pickle pickle DEFAULT_PROTOCOL}@anchor{a2f}
@deffn {データ} pickle.DEFAULT_PROTOCOL

An integer, the default @ref{27b,,protocol version} used
for pickling.  May be less than @ref{16be,,HIGHEST_PROTOCOL}.  Currently the
default protocol is 5, introduced in Python 3.8 and incompatible
with previous versions. This version introduces support for out-of-band
buffers, where 
@geindex Python Enhancement Proposals; PEP 3118
PEP 3118@footnote{https://peps.python.org/pep-3118/}-compatible data can be transmitted separately
from the main pickle stream.


バージョン 3.0 で変更: デフォルトプロトコルは 3 です。



バージョン 3.8 で変更: デフォルトプロトコルは 4 です。



バージョン 3.14 で変更: デフォルトプロトコルは 5 です。

@end deffn

The @code{pickle} module provides the following functions to make the pickling
process more convenient:

@geindex dump() (pickle モジュール)
@anchor{library/pickle pickle dump}@anchor{2d0c}
@deffn {の関数} pickle.dump (obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)

オブジェクト `obj' を pickle 化し、すでにオープンしている @ref{13db,,ファイルオブジェクト} `file' に書き込みます。@code{Pickler(file, protocol).dump(obj)} と等価です。

引数 `file', `protocol', `fix_imports' および `buffer_callback' は @ref{c13,,Pickler} のコンストラクタと同じ意味になります。


バージョン 3.8 で変更: `buffer_callback' 引数が追加されました。

@end deffn

@geindex dumps() (pickle モジュール)
@anchor{library/pickle pickle dumps}@anchor{16bd}
@deffn {の関数} pickle.dumps (obj, protocol=None, *, fix_imports=True, buffer_callback=None)

ファイルに書く代わりに、@ref{192,,bytes} オブジェクトとしてオブジェクト `obj' の pickle 表現を返します。

引数 `protocol', `fix_imports' および `buffer_callback' は @ref{c13,,Pickler} のコンストラクタと同じ意味になります。


バージョン 3.8 で変更: `buffer_callback' 引数が追加されました。

@end deffn

@geindex load() (pickle モジュール)
@anchor{library/pickle pickle load}@anchor{f0c}
@deffn {の関数} pickle.load (file, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=None)

あるオブジェクトの pickle 化表現を、オープンしている @ref{13db,,ファイルオブジェクト} `file' から読み込み、その中で指定されているオブジェクト階層に再構成して返します。これは @code{Unpickler(file).load()} と等価です。

pickle のプロトコルバージョンは自動的に検出されます。したがって protocol 引数は必要ありません。pickle 化オブジェクト表現より後のバイト列は無視されます。

引数 `file', `fix_imports', `encoding', `errors', `strict' および `buffers' は @ref{1777,,Unpickler} のコンストラクタと同じ意味になります。


バージョン 3.8 で変更: `buffers' 引数が追加されました。

@end deffn

@geindex loads() (pickle モジュール)
@anchor{library/pickle pickle loads}@anchor{f0d}
@deffn {の関数} pickle.loads (data, /, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=None)

オブジェクトのピックル化表現 `data' から再構成されたオブジェクト階層を返します。 `data' は バイトライクオブジェクト (@ref{193,,bytes-like object}) でなければなりません。

pickle のプロトコルバージョンは自動的に検出されます。したがって protocol 引数は必要ありません。pickle 化オブジェクト表現より後のバイト列は無視されます。

引数 `fix_imports', `encoding', `errors', `strict' および `buffers' は @ref{1777,,Unpickler} のコンストラクタと同じ意味になります。


バージョン 3.8 で変更: `buffers' 引数が追加されました。

@end deffn

The @code{pickle} module defines three exceptions:

@geindex PickleError
@anchor{library/pickle pickle PickleError}@anchor{2d0d}
@deffn {例外} pickle.PickleError

他の pickle 化例外の共通基底クラス。@ref{bcd,,Exception} を継承しています。
@end deffn

@geindex PicklingError
@anchor{library/pickle pickle PicklingError}@anchor{1942}
@deffn {例外} pickle.PicklingError

@ref{c13,,Pickler} が pickle 化不可能なオブジェクトに遭遇したときに送出されるエラー。@ref{2d0d,,PickleError} を継承しています。

どんな種類のオブジェクトが pickle 化できるのか確認するには @ref{2d0e,,pickle 化、非 pickle 化できるもの} を参照してください。
@end deffn

@geindex UnpicklingError
@anchor{library/pickle pickle UnpicklingError}@anchor{2d0f}
@deffn {例外} pickle.UnpicklingError

データ破損やセキュリティ違反のような、オブジェクトを非 pickle 化するのに問題がある場合に送出されるエラー。@ref{2d0d,,PickleError} を継承します。

非 picke 化の最中に他の例外が送出されることもあるので注意してください。これには AttributeError, EOFError, ImportError, IndexError が含まれます (ただし必ずしもこれらに限定されません)。
@end deffn

The @code{pickle} module exports three classes, @ref{c13,,Pickler},
@ref{1777,,Unpickler} and @ref{177b,,PickleBuffer}:

@geindex Pickler (pickle のクラス)
@anchor{library/pickle pickle Pickler}@anchor{c13}
@deffn {クラス} pickle.Pickler (file, protocol=None, *, fix_imports=True, buffer_callback=None)

pickle 化されたオブジェクトのデータストリームを書き込むためのバイナリファイルを引数にとります。

任意の引数 `protocol' は、整数で、pickle 化で使用するプロトコルを指定します; サポートされているプロトコルは 0 から @ref{16be,,HIGHEST_PROTOCOL} までになります。指定されない場合、@ref{a2f,,DEFAULT_PROTOCOL} が使用されます。負数が与えられた場合、@ref{16be,,HIGHEST_PROTOCOL} が使用されます。

引数 `file' は、1 バイトの引数一つを受け付ける write() メソッドを持たなければなりません。すなわち、`file' には、バイナリの書き込み用にオープンされたファイルオブジェクト、@ref{10a4,,io.BytesIO} オブジェクト、このインターフェースに適合するその他のカスタムオブジェクトをとることができます。

`fix_imports' が真であり、かつ、`protocol' が 3 未満の場合、pickle は新しい Python 3 の名前と Python 2 で使用されていた古いモジュール名との対応付けを試みるので、pickle データストリームは Python 2 でも読み込み可能です。

`buffer_callback' が @code{None} (デフォルト) の場合、バッファビューはストリームの一部として*file* 中に直列化されます。

`buffer_callback' が @code{None} でない場合、バッファビューを引数として何度でも呼び出すことができる関数です。コールバック関数が偽値 (@code{None} など) を返すと、与えられたバッファは @ref{2d10,,アウトオブバウンド管理 (out-of-band)} となります; そうでない場合はインバンドで、すなわち pickle ストリーム内で、直列化されます。

`buffer_callback' が @code{None} でなく、かつ `protocol' が @code{None} または 5 より小さい場合はエラーとなります。


バージョン 3.8 で変更: `buffer_callback' 引数が追加されました。


@geindex dump() (pickle.Pickler のメソッド)
@anchor{library/pickle pickle Pickler dump}@anchor{1e25}
@deffn {メソッド} dump (obj)

`obj' の pickle 化表現を、コンストラクターで与えられた、すでにオープンしているファイルオブジェクトに書き込みます。
@end deffn

@geindex persistent_id() (pickle.Pickler のメソッド)
@anchor{library/pickle pickle Pickler persistent_id}@anchor{190c}
@deffn {メソッド} persistent_id (obj)

デフォルトでは何もしません。このメソッドはサブクラスがオーバーライドできるように存在します。

@ref{190c,,persistent_id()} が @code{None} を返す場合、通常通り `obj' が pickle 化されます。それ以外の値を返した場合、@ref{c13,,Pickler} がその値を `obj' のために永続的な ID として出力するようになります。この永続的な ID の意味は @ref{1914,,Unpickler.persistent_load()} によって定義されています。@ref{190c,,persistent_id()} によって返された値自身は永続的な ID を持つことができないことに注意してください。

詳細および使用例については @ref{2d11,,外部オブジェクトの永続化} を参照してください。


バージョン 3.13 で変更: Add the default implementation of this method in the C implementation
of @code{Pickler}.

@end deffn

@geindex dispatch_table (pickle.Pickler の属性)
@anchor{library/pickle pickle Pickler dispatch_table}@anchor{133a}
@deffn {の属性} dispatch_table

pickler オブジェクトのディスパッチテーブルは @ref{2d12,,copyreg.pickle()} を使用して宣言できる種類の `reduction functions' のレジストリです。これはキーがクラスでその値が減少関数のマッピング型オブジェクトです。減少関数は関連するクラスの引数を 1 個とり、@ref{bc6,,__reduce__()} メソッドと同じインターフェースでなければなりません。

デフォルトでは、pickler オブジェクトは @ref{133a,,dispatch_table} 属性を持たず、代わりに @ref{2a,,copyreg} モジュールによって管理されるグローバルなディスパッチテーブルを使用します。しかし、特定の pickler オブジェクトによる pickle 化をカスタマイズするために @ref{133a,,dispatch_table} 属性に dict-like オブジェクトを設定することができます。あるいは、@ref{c13,,Pickler} のサブクラスが @ref{133a,,dispatch_table} 属性を持てば、そのクラスのインスタンスに対するデフォルトのディスパッチテーブルとして使用されます。

使用例については @ref{2d13,,ディスパッチテーブル} を参照してください。


Added in version 3.3.

@end deffn

@geindex reducer_override() (pickle.Pickler のメソッド)
@anchor{library/pickle pickle Pickler reducer_override}@anchor{c14}
@deffn {メソッド} reducer_override (obj)

@ref{c13,,Pickler} のサブクラスで定義可能な特殊なリデューサ (reducer) です。このメソッドは @ref{133a,,dispatch_table} 内のいかなるリデューサよりも優先されます。このメソッドは @ref{bc6,,__reduce__()} メソッドのインターフェースと適合していなければなりません。また、メソッドが @ref{1a2,,NotImplemented} を返すことにより、 @ref{133a,,dispatch_table} に登録されたリデューサにフォールバックして @code{obj} を直列化することもできます。

詳細な例については、 @ref{2d14,,型、関数、その他のオブジェクトに対するリダクションのカスタマイズ} を参照してください。


Added in version 3.8.

@end deffn

@geindex fast (pickle.Pickler の属性)
@anchor{library/pickle pickle Pickler fast}@anchor{2d15}
@deffn {の属性} fast

廃止予定です。真値が設定されれば高速モードを有効にします。高速モードは、メモの使用を無効にします。それにより余分な PUT 命令コードを生成しなくなるので pickle 化処理が高速化します。自己参照オブジェクトに対しては使用すべきではありません。さもなければ @ref{c13,,Pickler} に無限再帰を起こさせるでしょう。

よりコンパクトな pickle 化を必要とする場合は、@ref{2d16,,pickletools.optimize()} を使用してください。
@end deffn

@geindex clear_memo() (pickle.Pickler のメソッド)
@anchor{library/pickle pickle Pickler clear_memo}@anchor{2d17}
@deffn {メソッド} clear_memo ()

Clears the pickler's "memo".

The memo is the data structure that remembers which objects the
pickler has already seen, so that shared or recursive objects
are pickled by reference and not by value.  This method is
useful when re-using picklers.
@end deffn
@end deffn

@geindex Unpickler (pickle のクラス)
@anchor{library/pickle pickle Unpickler}@anchor{1777}
@deffn {クラス} pickle.Unpickler (file, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=None)

これは pickle データストリームの読み込みのためにバイナリファイルをとります。

pickle のプロトコルバージョンは自動的に検出されます。したがって protocol 引数は必要ありません。

引数 `file' は @ref{8a3,,io.BufferedIOBase} のインターフェースと同様に、整数を引数にとる read() 、バッファを引数にとる readinto() 、引数を取らない readline() の3つのメソッドを持たなければなりません。したがって、 `file' はバイナリ読み込みモードでオープンされたディスク上のファイル、 @ref{10a4,,io.BytesIO} オブジェクト、または上記インターフェース要件を満たす任意のカスタムオブジェクトのいずれかです。

オプション引数 `fix_imports', `encoding' および `errors' はPython 2で生成された pickle ストリームに対する互換性サポートを制御するために使われます。 `fix_imports' が真の場合、 pickle は古い Python 2 の名前を Python 3 の新しい名前に対応づけようとします。 `encoding' と `errors' は pickle に Python 2 で  pickle 化された 8 ビット文字列をデコードする方法を指定します; これらの引数のデフォルト値はそれぞれ 'ASCII' と 'strict' です。 `encoding' は 8 ビット文字列インスタンスをバイトオブジェクトとして読み込む場合は 'bytes' を指定します。  Python 2 で pickle 化された NumPy 配列および @ref{4e2,,datetime}, @ref{1fa,,date}, @ref{1fb,,time} の各インスタンスを非 pickle 化するためには @code{encoding='latin1'} を使う必要があります。

`buffers' が @code{None} (デフォルト値) の場合、非直列化に必要な全てのデータは pickle ストリームに含まれている必要があります。これは @ref{c13,,Pickler} がインスタンス化されたとき (または @ref{2d0c,,dump()} や @ref{16bd,,dumps()} が呼び出されたとき) に `buffer_callback' 引数に @code{None} を指定したことに相当します。

`buffers' が @code{None} でない場合、各イテレーションで @ref{2d10,,アウトオブバウンド (out-of-band)} のバッファビューを参照する pickle ストリームを消費する、バッファ対応のイテラブルでなければなりません。ここに指定するバッファは Pickler オブジェクトの `buffer_callback' に順番に渡されたものです。


バージョン 3.8 で変更: `buffers' 引数が追加されました。


@geindex load() (pickle.Unpickler のメソッド)
@anchor{library/pickle pickle Unpickler load}@anchor{2d18}
@deffn {メソッド} load ()

コンストラクターで与えられたオープンしたファイルオブジェクトからオブジェクトの pickle 化表現を読み込み、その中で指定されたオブジェクト階層に再構成して返します。オブジェクトの pickle 化表現より後のバイト列は無視されます。
@end deffn

@geindex persistent_load() (pickle.Unpickler のメソッド)
@anchor{library/pickle pickle Unpickler persistent_load}@anchor{1914}
@deffn {メソッド} persistent_load (pid)

デフォルトで @ref{2d0f,,UnpicklingError} を送出します。

もし定義されていれば、@ref{1914,,persistent_load()} は永続的な ID `pid' によって指定されたオブジェクトを返す必要があります。永続的な ID が無効な場合、@ref{2d0f,,UnpicklingError} を送出しなければなりません。

詳細および使用例については @ref{2d11,,外部オブジェクトの永続化} を参照してください。


バージョン 3.13 で変更: Add the default implementation of this method in the C implementation
of @code{Unpickler}.

@end deffn

@geindex find_class() (pickle.Unpickler のメソッド)
@anchor{library/pickle pickle Unpickler find_class}@anchor{2d19}
@deffn {メソッド} find_class (module, name)

必要なら `module' をインポートして、そこから `name' という名前のオブジェクトを返します。ここで `module' および `name' 引数は @ref{169,,str} オブジェクトです。その名前が示唆することに反して @ref{2d19,,find_class()} は関数を探すためにも使われることに注意してください。

サブクラスは、どんな型のオブジェクトを、どのようにロードするか (潜在的にはセキュリティリスクの減少) に関する制御を得るためにこれをオーバーライドすることができます。詳細に関しては @ref{2d1a,,グローバル変数を制限する} を参照してください。

引数 @code{modulet}, @code{name} を指定して @ref{1c6e,,監査イベント} @code{pickle.find_class} を送出します。
@end deffn
@end deffn

@geindex PickleBuffer (pickle のクラス)
@anchor{library/pickle pickle PickleBuffer}@anchor{177b}
@deffn {クラス} pickle.PickleBuffer (buffer)

pickle 可能なデータをあらわすバッファのラッパーです。 `buffer' はバッファライクなオブジェクト (@ref{193,,bytes-like object}) や N 次元配列のような @ref{260,,バッファ機能を提供する} オブジェクトでなければなりません。

@ref{177b,,PickleBuffer} はそれ自身バッファ機能を提供します。したがってこのクラスのインスタンスを、バッファ機能を提供するオブジェクトを期待する @ref{165,,memoryview} など他の API に渡すことが可能です。

@ref{177b,,PickleBuffer} オブジェクトはプロトコル 5 以上でのみ直列化可能で、 @ref{2d10,,アウトオブバウンド (out-of-band) の直列化} に対応しています。


Added in version 3.8.


@geindex raw() (pickle.PickleBuffer のメソッド)
@anchor{library/pickle pickle PickleBuffer raw}@anchor{2d1b}
@deffn {メソッド} raw ()

このバッファの背後にあるメモリ領域への @ref{165,,memoryview} を返します。戻り値のオブジェクトはフォーマット @code{B} (符号なしバイト) の C-連続な1次元のメモリビューです。バッファが C-連続でも Fortran-連続でもない場合 @ref{1797,,BufferError} 例外が送出されます。
@end deffn

@geindex release() (pickle.PickleBuffer のメソッド)
@anchor{library/pickle pickle PickleBuffer release}@anchor{2d1c}
@deffn {メソッド} release ()

PickleBuffer オブジェクトを通じてアクセスされる背後のバッファを解放します。
@end deffn
@end deffn

@node pickle 化、非 pickle 化できるもの,クラスインスタンスの pickle 化,モジュールインターフェース,pickle --- Python オブジェクトの直列化
@anchor{library/pickle pickle-picklable}@anchor{2d0e}@anchor{library/pickle what-can-be-pickled-and-unpickled}@anchor{2d1d}
@subsubsection pickle 化、非 pickle 化できるもの


以下の型は pickle 化できます:


@itemize *

@item 
組み込み定数(@code{None}, @code{True}, @code{False}, @code{Ellipsis}, と @ref{1a2,,NotImplemented})

@item 
整数、浮動小数点数、複素数

@item 
文字列、バイト列、バイト配列

@item 
pickle 化可能なオブジェクトからなるタプル、リスト、集合および辞書

@item 
モジュールのトップレベルで定義された関数 (@ref{1673,,def} で定義されたもののみで @ref{14b5,,lambda} で定義されたものは含まない)

@item 
モジュールのトップレベルで定義されているクラス

@item 
instances of such classes for which the result of calling @ref{7f1,,__getstate__()}
is picklable  (see section @ref{2d07,,クラスインスタンスの pickle 化} for details).
@end itemize

pickle 化できないオブジェクトを pickle 化しようとすると、@ref{1942,,PicklingError} 例外が送出されます。この例外が起きたとき、すでに元のファイルには未知の長さのバイト列が書き込まれている場合があります。極端に再帰的なデータ構造を pickle 化しようとした場合には再帰の深さ制限を越えてしまうかもしれず、この場合には @ref{f68,,RecursionError} が送出されます。この制限は、@ref{6ea,,sys.setrecursionlimit()} で慎重に上げていくことは可能です。

関数 (組込みおよびユーザー定義) は、値ではなく、完全 @ref{1d24,,修飾名} で pickle 化されます。@footnote{
なぜ @ref{14b5,,lambda} 関数を pickle 化できないかというと、すべての @code{lambda} 関数は同じ名前: @code{<lambda>} を共有しているからです。
}  これは、関数名のみがそれを含んでいるモジュールおよびクラスの名前をともなって pickle 化されることを意味します。関数のコードやその属性は pickle 化されません。すなわち、非 pickle 化する環境で定義したモジュールがインポート可能な状態になっており、そのモジュール内に関数名のオブジェクトが含まれていなければなりません。この条件を満たさなかった場合は例外が送出されます。@footnote{
送出される例外は @ref{65b,,ImportError} や @ref{5f0,,AttributeError} になるはずですが、他の例外も起こりえます。
}

クラスも同様に完全修飾名で pickle 化されるので、unpickle 化環境には同じ制限が課せられます。クラス中のコードやデータは何も pickle 化されないので、以下の例ではクラス属性 @code{attr} が unpickle 化環境で復元されないことに注意してください:

@example
class Foo:
    attr = 'A class attribute'

picklestring = pickle.dumps(Foo)
@end example

pickle 化可能な関数やクラスがモジュールのトップレベルで定義されていなければならないのはこれらの制限のためです。

同様に、クラスのインスタンスが pickle 化された際、そのクラスのコードおよびデータはオブジェクトと一緒に pickle 化されることはありません。インスタンスのデータのみが pickle 化されます。この仕様は、クラス内のバグを修正したりメソッドを追加した後でも、そのクラスの以前のバージョンで作られたオブジェクトを読み出せるように意図的に行われています。あるクラスの多くのバージョンで使われるような長命なオブジェクトを作ろうと計画しているなら、そのクラスの @ref{bc7,,__setstate__()} メソッドによって適切な変換が行われるようにオブジェクトのバージョン番号を入れておくとよいかもしれません。

@node クラスインスタンスの pickle 化,型、関数、その他のオブジェクトに対するリダクションのカスタマイズ,pickle 化、非 pickle 化できるもの,pickle --- Python オブジェクトの直列化
@anchor{library/pickle pickle-inst}@anchor{2d07}@anchor{library/pickle pickling-class-instances}@anchor{2d1e}
@subsubsection クラスインスタンスの pickle 化


この節では、クラスインスタンスがどのように pickle 化または非 pickle 化されるのかを定義したり、カスタマイズしたり、コントロールしたりするのに利用可能な一般的機構について説明します。

ほとんどの場合、インスタンスを pickle 化できるようにするために追加のコードは必要ありません。デフォルトで、pickle はインスタンスのクラスと属性を内省によって検索します。クラスインスタンスが非 pickle 化される場合、通常その @ref{8bf,,__init__()} メソッドは実行 `されません' 。デフォルトの振る舞いは、最初に初期化されていないインスタンスを作成して、次に保存された属性を復元します。次のコードはこの振る舞いの実装を示しています:

@example
def save(obj):
    return (obj.__class__, obj.__dict__)

def restore(cls, attributes):
    obj = cls.__new__(cls)
    obj.__dict__.update(attributes)
    return obj
@end example

クラスは、いくつかの特殊メソッドを提供することによって、デフォルトの振る舞いを変更することができます:

@geindex __getnewargs_ex__() (object のメソッド)
@anchor{library/pickle object __getnewargs_ex__}@anchor{2d1f}
@deffn {メソッド} object.__getnewargs_ex__ ()

In protocols 2 and newer, classes that implement the
@ref{2d1f,,__getnewargs_ex__()} method can dictate the values passed to the
@ref{7a0,,__new__()} method upon unpickling.  The method must return a pair
@code{(args, kwargs)} where `args' is a tuple of positional arguments
and `kwargs' a dictionary of named arguments for constructing the
object.  Those will be passed to the @ref{7a0,,__new__()} method upon
unpickling.

クラスの @ref{7a0,,__new__()} メソッドがキーワード専用引数を求める場合はこのメソッドを実装すべきです。
そうしない場合、互換性のため @ref{fd4,,__getnewargs__()} メソッドの実装を推奨します。


バージョン 3.6 で変更: @ref{2d1f,,__getnewargs_ex__()} がプロトコル 2 と 3 でも使われるようになりました。

@end deffn

@geindex __getnewargs__() (object のメソッド)
@anchor{library/pickle object __getnewargs__}@anchor{fd4}
@deffn {メソッド} object.__getnewargs__ ()

このメソッドは @ref{2d1f,,__getnewargs_ex__()} と同じような機能を提供しますが、位置引数のみをサポートします。このメソッドは引数のタプル @code{args} を返さなければならず、戻り値は非 pickle 化に際して @ref{7a0,,__new__()} メソッドに渡されます。

@ref{2d1f,,__getnewargs_ex__()} が定義されていると @ref{fd4,,__getnewargs__()} は呼び出しません。


バージョン 3.6 で変更: Python 3.6以前のプロトコル 2 と 3 では、@ref{2d1f,,__getnewargs_ex__()} の代わりに @ref{fd4,,__getnewargs__()} が呼び出されていました。

@end deffn

@geindex __getstate__() (object のメソッド)
@anchor{library/pickle object __getstate__}@anchor{7f1}
@deffn {メソッド} object.__getstate__ ()

Classes can further influence how their instances are pickled by overriding
the method @ref{7f1,,__getstate__()}.  It is called and the returned object
is pickled as the contents for the instance, instead of a default state.
There are several cases:


@itemize *

@item 
For a class that has no instance @ref{77d,,__dict__} and no
@ref{1704,,__slots__}, the default state is @code{None}.

@item 
For a class that has an instance @ref{77d,,__dict__} and no
@ref{1704,,__slots__}, the default state is @code{self.__dict__}.

@item 
For a class that has an instance @ref{77d,,__dict__} and
@ref{1704,,__slots__}, the default state is a tuple consisting of two
dictionaries:  @code{self.__dict__}, and a dictionary mapping slot
names to slot values.  Only slots that have a value are
included in the latter.

@item 
For a class that has @ref{1704,,__slots__} and no instance
@ref{77d,,__dict__}, the default state is a tuple whose first item
is @code{None} and whose second item is a dictionary mapping slot names
to slot values described in the previous bullet.
@end itemize


バージョン 3.11 で変更: Added the default implementation of the @code{__getstate__()} method in the
@ref{c7e,,object} class.

@end deffn

@geindex __setstate__() (object のメソッド)
@anchor{library/pickle object __setstate__}@anchor{bc7}
@deffn {メソッド} object.__setstate__ (state)

非 pickle 化に際して、クラスが @ref{bc7,,__setstate__()} を定義している場合、それは非 pickle 化された状態とともに呼び出されます。その場合、状態オブジェクトが辞書でなければならないという要求はありません。そうでなければ、 pickle された状態は辞書で、その要素は新しいインスタンスの辞書に割り当てられます。

@cartouche
@quotation 注釈 
If @ref{bc6,,__reduce__()} returns a state with value @code{None} at pickling,
the @ref{bc7,,__setstate__()} method will not be called upon unpickling.
@end quotation
@end cartouche
@end deffn

@ref{7f1,,__getstate__()} および @ref{bc7,,__setstate__()} メソッドの使い方に関する詳細な情報については @ref{2d20,,状態を持つオブジェクトの扱い} 節を参照してください。

@cartouche
@quotation 注釈 
非 pickle 化に際しては、 @ref{6fa,,__getattr__()}, @ref{dcb,,__getattribute__()}, または @ref{237c,,__setattr__()} といったメソッドがインスタンスに対して呼ばれることがあります。これらのメソッドが何らかの内部の不変な条件が真であることを必要とする場合、その型は @ref{7a0,,__new__()} メソッドを実装してそのような不変な条件を構築すべきです。なぜならばインスタンスの非 pickle 化においては @ref{8bf,,__init__()} メソッドは呼ばれないからです。
@end quotation
@end cartouche

@geindex copy;プロトコル

これらから見るように、pickle は上記のメソッドを直接使用しません。実際には、これらのメソッドは @ref{bc6,,__reduce__()} 特殊メソッドを実装するコピープロトコルの一部です。コピープロトコルは、pickle 化とオブジェクトのコピーに必要な、データを取得するための統一されたインターフェースを提供します。 @footnote{
@ref{29,,copy} モジュールは、浅いコピーと深いコピーの操作にこのプロトコルを使用します。
}

強力ですが、クラスに @ref{bc6,,__reduce__()} メソッドを直接実装することはエラーを起こしやすくなります。この理由のため、クラスの設計者は可能なかぎり高レベルインターフェース (@ref{2d1f,,__getnewargs_ex__()}、@ref{7f1,,__getstate__()} および @ref{bc7,,__setstate__()}) を使用するべきです。公開はしているものの、@code{__reduce__()} の使用は、あくまでオプションとして、より効果的な pickle 化につながる場合、あるいはその両方の場合のみにしてください。

@geindex __reduce__() (object のメソッド)
@anchor{library/pickle object __reduce__}@anchor{bc6}
@deffn {メソッド} object.__reduce__ ()

このインターフェースは現在、以下のように定義されています。 @ref{bc6,,__reduce__()} メソッドは引数を取らず、文字列あるいは (こちらの方が好まれますが) タプルのいずれかを返すべきです (返されたオブジェクトは、しばしば "reduce value" と呼ばれます)。

文字列が返された場合、その文字列はグローバル変数の名前として解釈されます。それはオブジェクトのモジュールから見たローカル名であるべきです; pickle モジュールは、オブジェクトのモジュールを決定するためにモジュールの名前空間を検索します。この振る舞いは、典型的にシングルトンで便利です。

タプルが返された場合、それは 2〜6 要素長でなければなりません。オプションのアイテムは省略することができます。あるいはそれらの値として @code{None} を渡すことができます。各要素の意味は順に:

@c XXX Mention __newobj__ special-case?


@itemize *

@item 
オブジェクトの初期バージョンを作成するために呼ばれる呼び出し可能オブジェクト。

@item 
呼出し可能オブジェクトに対する引数のタプル。呼出し可能オブジェクトが引数を受け取らない場合、空のタプルが与えられなければなりません。

@item 
任意で、前述のオブジェクトの @ref{bc7,,__setstate__()} メソッドに渡されるオブジェクトの状態。オブジェクトがそのようなメソッドを持たない場合、値は辞書でなければならず、それはオブジェクトの @ref{77d,,__dict__} 属性に追加されます。

@item 
任意で、連続した要素を yield する (シーケンスではなく) イテレーター。これらの要素は @code{obj.append(item)} を使用して、あるいはバッチでは @code{obj.extend(list_of_items)} を使用して、オブジェクトに追加されます。これは主としてリストのサブクラスに対して使用されますが、適切なシグネチャを持つ @ref{23d6,,append()} および @ref{23d9,,extend()} メソッドがあるかぎり、他のクラスで使用することもできます。 (@code{append()} または @code{extend()} のどちらが使用されるかは、どの pickle プロトコルバージョンが使われるかに加えて追加されるアイテムの数にも依存します。したがって、両方をサポートする必要があります)

@item 
任意で、連続する key-value ペアを yield する (シーケンスでなく) イテレーター。これらの要素は @code{obj[key] = value} を使用して、オブジェクトに格納されます。これは主として辞書のサブクラスに対して使用されますが、@ref{14e3,,__setitem__()} を実装しているかぎり他のクラスで使用することもできます。

@item 
任意で、シグネチャが @code{(obj, state)} である呼び出し可能オブジェクト。このオブジェクトは、 @code{obj} のスタティックな @ref{bc7,,__setstate__()} メソッドの代わりに、ユーザーがオブジェクトの状態を更新する方法をプログラム的に制御することを許します。 @code{None} 以外の場合、この呼び出し可能オブジェクトは @code{obj} の @ref{bc7,,__setstate__()} メソッドに優先します。


Added in version 3.8: 任意の6番目のタプル要素 @code{(obj, state)} が追加されました。

@end itemize
@end deffn

@geindex __reduce_ex__() (object のメソッド)
@anchor{library/pickle object __reduce_ex__}@anchor{196b}
@deffn {メソッド} object.__reduce_ex__ (protocol)

別の方法として、@ref{196b,,__reduce_ex__()} メソッドを定義することもできます。唯一の違いは、このメソッドは単一の整数引数、プロトコルバージョンを取る必要があるということです。もし定義された場合、pickle は @ref{bc6,,__reduce__()} メソッドよりもこのメソッドを優先します。さらに、@ref{bc6,,__reduce__()} は自動的に拡張版の同義語になります。このメソッドの主な用途は、古い Python リリースに対して後方互換性のある reduce value を提供することです。
@end deffn

@menu
* 外部オブジェクトの永続化:: 
* ディスパッチテーブル:: 
* 状態を持つオブジェクトの扱い:: 

@end menu

@node 外部オブジェクトの永続化,ディスパッチテーブル,,クラスインスタンスの pickle 化
@anchor{library/pickle persistence-of-external-objects}@anchor{2d21}@anchor{library/pickle pickle-persistent}@anchor{2d11}
@subsubsection 外部オブジェクトの永続化


@geindex persistent_id (pickle プロトコル)
@geindex persistent_load (pickle プロトコル)

For the benefit of object persistence, the @code{pickle} module supports the
notion of a reference to an object outside the pickled data stream.  Such
objects are referenced by a persistent ID, which should be either a string of
alphanumeric characters (for protocol 0) @footnote{
英数文字に関する制限は、プロトコル 0 では永続的な ID が改行文字によって区切られるという事実によります。そのため、永続的な ID に何らかの改行文字が含まれると、結果として生じる pickle 化されたデータは判読不能になります。
} or just an arbitrary object (for
any newer protocol).

The resolution of such persistent IDs is not defined by the @code{pickle}
module; it will delegate this resolution to the user-defined methods on the
pickler and unpickler, @ref{190c,,persistent_id()} and
@ref{1914,,persistent_load()} respectively.

外部の永続的 ID を持つ pickle オブジェクトの pickler は、引数にオブジェクトを取り、@code{None} かオブジェクトの永続的 ID を返すカスタム @ref{190c,,persistent_id()} メソッドを持たなくてはなりません。@code{None} を返す場合、pickler は通常通りマーカーとともにオブジェクトを pickle 化するため、unpickler はそれを永続的 ID として認識します。

外部オブジェクトを非 pickle 化するには、unpickler は永続的 ID オブジェクトを取り被参照オブジェクトを返すカスタム @ref{1914,,persistent_load()} メソッドを持たなくてはなりません。

これは、外部のオブジェクトを参照によって pickle 化するために永続的 ID をどのように使用するかを示す包括的な例です。

@example
# Simple example presenting how persistent ID can be used to pickle
# external objects by reference.

import pickle
import sqlite3
from collections import namedtuple

# Simple class representing a record in our database.
MemoRecord = namedtuple("MemoRecord", "key, task")

class DBPickler(pickle.Pickler):

    def persistent_id(self, obj):
        # Instead of pickling MemoRecord as a regular class instance, we emit a
        # persistent ID.
        if isinstance(obj, MemoRecord):
            # Here, our persistent ID is simply a tuple, containing a tag and a
            # key, which refers to a specific record in the database.
            return ("MemoRecord", obj.key)
        else:
            # If obj does not have a persistent ID, return None. This means obj
            # needs to be pickled as usual.
            return None


class DBUnpickler(pickle.Unpickler):

    def __init__(self, file, connection):
        super().__init__(file)
        self.connection = connection

    def persistent_load(self, pid):
        # This method is invoked whenever a persistent ID is encountered.
        # Here, pid is the tuple returned by DBPickler.
        cursor = self.connection.cursor()
        type_tag, key_id = pid
        if type_tag == "MemoRecord":
            # Fetch the referenced record from the database and return it.
            cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),))
            key, task = cursor.fetchone()
            return MemoRecord(key, task)
        else:
            # Always raises an error if you cannot return the correct object.
            # Otherwise, the unpickler will think None is the object referenced
            # by the persistent ID.
            raise pickle.UnpicklingError("unsupported persistent object")


def main():
    import io
    import pprint

    # Initialize and populate our database.
    conn = sqlite3.connect(":memory:")
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
    tasks = (
        'give food to fish',
        'prepare group meeting',
        'fight with a zebra',
        )
    for task in tasks:
        cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,))

    # Fetch the records to be pickled.
    cursor.execute("SELECT * FROM memos")
    memos = [MemoRecord(key, task) for key, task in cursor]
    # Save the records using our custom DBPickler.
    file = io.BytesIO()
    DBPickler(file).dump(memos)

    print("Pickled records:")
    pprint.pprint(memos)

    # Update a record, just for good measure.
    cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1")

    # Load the records from the pickle data stream.
    file.seek(0)
    memos = DBUnpickler(file, conn).load()

    print("Unpickled records:")
    pprint.pprint(memos)


if __name__ == '__main__':
    main()
@end example

@node ディスパッチテーブル,状態を持つオブジェクトの扱い,外部オブジェクトの永続化,クラスインスタンスの pickle 化
@anchor{library/pickle dispatch-tables}@anchor{2d22}@anchor{library/pickle pickle-dispatch}@anchor{2d13}
@subsubsection ディスパッチテーブル


pickle 化に依存する他のコードの邪魔をせずに、一部のクラスの pickle 化だけをカスタマイズしたい場合、プライベートのディスパッチテーブルを持つ pickler を作成することができます。

@ref{2a,,copyreg} モジュールによって管理されるグローバルなディスパッチテーブルは @code{copyreg.dispatch_table} として利用可能です。したがって、@code{copyreg.dispatch_table} の修正済のコピーをプライベートのディスパッチテーブルとして使用することを選択できます。

例えば

@example
f = io.BytesIO()
p = pickle.Pickler(f)
p.dispatch_table = copyreg.dispatch_table.copy()
p.dispatch_table[SomeClass] = reduce_SomeClass
@end example

これは @code{SomeClass} クラスを特別に扱うプライベートのディスパッチテーブルを持つ @ref{c13,,pickle.Pickler} のインスタンスを作成します。あるいは、次のコード

@example
class MyPickler(pickle.Pickler):
    dispatch_table = copyreg.dispatch_table.copy()
    dispatch_table[SomeClass] = reduce_SomeClass
f = io.BytesIO()
p = MyPickler(f)
@end example

does the same but all instances of @code{MyPickler} will by default
share the private dispatch table.  On the other hand, the code

@example
copyreg.pickle(SomeClass, reduce_SomeClass)
f = io.BytesIO()
p = pickle.Pickler(f)
@end example

modifies the global dispatch table shared by all users of the @ref{2a,,copyreg} module.

@node 状態を持つオブジェクトの扱い,,ディスパッチテーブル,クラスインスタンスの pickle 化
@anchor{library/pickle handling-stateful-objects}@anchor{2d23}@anchor{library/pickle pickle-state}@anchor{2d20}
@subsubsection 状態を持つオブジェクトの扱い


@geindex __getstate__() (copy プロトコル)
@geindex __setstate__() (copy プロトコル)

Here's an example that shows how to modify pickling behavior for a class.
The @code{TextReader} class below opens a text file, and returns the line number and
line contents each time its @code{readline()} method is called. If a
@code{TextReader} instance is pickled, all attributes `except' the file object
member are saved. When the instance is unpickled, the file is reopened, and
reading resumes from the last location. The @code{__setstate__()} and
@code{__getstate__()} methods are used to implement this behavior.

@example
class TextReader:
    """Print and number lines in a text file."""

    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename)
        self.lineno = 0

    def readline(self):
        self.lineno += 1
        line = self.file.readline()
        if not line:
            return None
        if line.endswith('\n'):
            line = line[:-1]
        return "%i: %s" % (self.lineno, line)

    def __getstate__(self):
        # Copy the object's state from self.__dict__ which contains
        # all our instance attributes. Always use the dict.copy()
        # method to avoid modifying the original state.
        state = self.__dict__.copy()
        # Remove the unpicklable entries.
        del state['file']
        return state

    def __setstate__(self, state):
        # Restore instance attributes (i.e., filename and lineno).
        self.__dict__.update(state)
        # Restore the previously opened file's state. To do so, we need to
        # reopen it and read from it until the line count is restored.
        file = open(self.filename)
        for _ in range(self.lineno):
            file.readline()
        # Finally, save the file.
        self.file = file
@end example

使用例は以下のようになるでしょう:

@example
>>> reader = TextReader("hello.txt")
>>> reader.readline()
'1: Hello world!'
>>> reader.readline()
'2: I am line number two.'
>>> new_reader = pickle.loads(pickle.dumps(reader))
>>> new_reader.readline()
'3: Goodbye!'
@end example

@node 型、関数、その他のオブジェクトに対するリダクションのカスタマイズ,アウトオブバウンドバッファ,クラスインスタンスの pickle 化,pickle --- Python オブジェクトの直列化
@anchor{library/pickle custom-reduction-for-types-functions-and-other-objects}@anchor{2d24}@anchor{library/pickle reducer-override}@anchor{2d14}
@subsubsection 型、関数、その他のオブジェクトに対するリダクションのカスタマイズ



Added in version 3.8.


@ref{133a,,dispatch_table} は、ときにその柔軟性が十分でないがことあります。特に、オブジェクトの型以外の別の条件で pickle 化をカスタマイズしたい場合や、関数やクラスを使って pickle 化をカスタマイズしたい場合などです。

そのような場合、 @ref{c13,,Pickler} クラスから派生したサブクラスで @ref{c14,,reducer_override()} メソッドを実装することができます。このメソッドは任意のリダクション用タプルを返すことができます  (@ref{bc6,,__reduce__()} を参照してください)。もしくは、従来の振る舞いにフォールバックするために @ref{1a2,,NotImplemented} を返すこともできます。

@ref{133a,,dispatch_table} と @ref{c14,,reducer_override()} の両方が定義されている場合、 @ref{c14,,reducer_override()} メソッドが優先されます。

@cartouche
@quotation 注釈 
パフォーマンス上の理由により、次に挙げるオブジェクトに対しては @ref{c14,,reducer_override()} が呼ばれないことがあります: @code{None}, @code{True}, @code{False}, および @ref{19b,,int}, @ref{196,,float}, @ref{192,,bytes}, @ref{169,,str}, @ref{183,,dict}, @ref{184,,set}, @ref{7f2,,frozenset}, @ref{24d,,list}, @ref{614,,tuple} の厳密なインスタンス。
@end quotation
@end cartouche

以下は特定のクラスを pickle 化して再構成する単純な例です:

@example
import io
import pickle

class MyClass:
    my_attribute = 1

class MyPickler(pickle.Pickler):
    def reducer_override(self, obj):
        """Custom reducer for MyClass."""
        if getattr(obj, "__name__", None) == "MyClass":
            return type, (obj.__name__, obj.__bases__,
                          @{'my_attribute': obj.my_attribute@})
        else:
            # For any other object, fallback to usual reduction
            return NotImplemented

f = io.BytesIO()
p = MyPickler(f)
p.dump(MyClass)

del MyClass

unpickled_class = pickle.loads(f.getvalue())

assert isinstance(unpickled_class, type)
assert unpickled_class.__name__ == "MyClass"
assert unpickled_class.my_attribute == 1
@end example

@node アウトオブバウンドバッファ,グローバル変数を制限する,型、関数、その他のオブジェクトに対するリダクションのカスタマイズ,pickle --- Python オブジェクトの直列化
@anchor{library/pickle out-of-band-buffers}@anchor{2d25}@anchor{library/pickle pickle-oob}@anchor{2d10}
@subsubsection アウトオブバウンドバッファ



Added in version 3.8.


In some contexts, the @code{pickle} module is used to transfer massive amounts
of data.  Therefore, it can be important to minimize the number of memory
copies, to preserve performance and resource consumption.  However, normal
operation of the @code{pickle} module, as it transforms a graph-like structure
of objects into a sequential stream of bytes, intrinsically involves copying
data to and from the pickle stream.

この制約は、生産者 `provider' (変換されるオブジェクトの型の実装) と消費者 `consumer' (通信システムの実装) が pickle プロトコル5以上で提供されるアウトオブバウンドのデータ転送機能をサポートしていれば回避できます。

@menu
* 生産者 API:: 
* 消費者 API:: 
* 使用例: 使用例<10>. 

@end menu

@node 生産者 API,消費者 API,,アウトオブバウンドバッファ
@anchor{library/pickle provider-api}@anchor{2d26}
@subsubsection 生産者 API


pickle 化される大きなサイズのデータオブジェクトは、プロトコル5以上でサポートされた @ref{196b,,__reduce_ex__()} メソッドを実装しなければなりません。このメソッドは大きなデータに対して (@ref{192,,bytes} オブジェクトなどの代わりに) @ref{177b,,PickleBuffer} インスタンスを返します。

A @ref{177b,,PickleBuffer} object `signals' that the underlying buffer is
eligible for out-of-band data transfer.  Those objects remain compatible
with normal usage of the @code{pickle} module.  However, consumers can also
opt-in to tell @code{pickle} that they will handle those buffers by
themselves.

@node 消費者 API,使用例<10>,生産者 API,アウトオブバウンドバッファ
@anchor{library/pickle consumer-api}@anchor{2d27}
@subsubsection 消費者 API


通信システムは、オブジェクトグラフを直列化するときに生成された @ref{177b,,PickleBuffer} オブジェクトのカスタマイズされた処理を有効化することができます。

送信側は `buffer_callback' 引数を @ref{c13,,Pickler} (または @ref{2d0c,,dump()} や @ref{16bd,,dumps()} 関数) に渡す必要があります。この関数はオブジェクトグラフを pickle 化するときに生成されるそれぞれの @ref{177b,,PickleBuffer} を引数として呼ばれます。 `buffer_callback' によって蓄積されたバッファは、それが保持するデータのコピーを pickle ストリームに送らず、軽量なマーカーが挿入されるだけです。

受信側は `buffers' 引数を @ref{1777,,Unpickler} (または @ref{f0c,,load()} や @ref{f0d,,loads()} 関数) に渡す必要があります。これは `buffer_callback' に渡されたバッファのイテラブルです。このイテラブルは  `buffer_callback' に渡されたのと同じ順番でバッファを返さなければなりません。これらのバッファは、pickle 化処理によって @ref{177b,,PickleBuffer} オブジェクトを生成したオブジェクトの再構築処理で期待されるデータを提供します。

送信側と受信側の間で、通信システムはアウトオブバウンドバッファの独自の転送メカニズムを自由に実装することができます。見込みのある最適化としては、共有メモリの利用や、データタイプ依存のデータ圧縮などが考えられます。

@node 使用例<10>,,消費者 API,アウトオブバウンドバッファ
@anchor{library/pickle example}@anchor{2d28}
@subsubsection 使用例


以下は、アウトオブバウンドのバッファを使った pickle 処理に関与することができるサブクラス @ref{344,,bytearray} を実装したささいな例です:

@example
class ZeroCopyByteArray(bytearray):

    def __reduce_ex__(self, protocol):
        if protocol >= 5:
            return type(self)._reconstruct, (PickleBuffer(self),), None
        else:
            # PickleBuffer is forbidden with pickle protocols <= 4.
            return type(self)._reconstruct, (bytearray(self),)

    @@classmethod
    def _reconstruct(cls, obj):
        with memoryview(obj) as m:
            # Get a handle over the original buffer object
            obj = m.obj
            if type(obj) is cls:
                # Original buffer object is a ZeroCopyByteArray, return it
                # as-is.
                return obj
            else:
                return cls(obj)
@end example

再構成関数 (@code{_reconstruct} クラスメソッド) は、受け取ったバッファが持っているオブジェクトを、それが正しい型であれば、そのまま返します。これは、このおもちゃのような例において、ゼロコピーの挙動を模擬的に行う簡単な方法です。

消費者側では、これらのオブジェクトを通常の方法で pickle 化することができます。この場合非直列化処理は元のオブジェクトのコピーを返します:

@example
b = ZeroCopyByteArray(b"abc")
data = pickle.dumps(b, protocol=5)
new_b = pickle.loads(data)
print(b == new_b)  # True
print(b is new_b)  # False: a copy was made
@end example

いっぽう直列化において `buffer_callback' を設定し、非直列化において蓄積されたバッファを渡した場合、コピーではなく元のオブジェクトを得ることができます:

@example
b = ZeroCopyByteArray(b"abc")
buffers = []
data = pickle.dumps(b, protocol=5, buffer_callback=buffers.append)
new_b = pickle.loads(data, buffers=buffers)
print(b == new_b)  # True
print(b is new_b)  # True: no copy was made
@end example

この例では @ref{344,,bytearray} がそれ自身メモリを割り当てるという性質による制限があります: すなわち、他のオブジェクトのメモリを参照する @ref{344,,bytearray} を生成することはできません。しかし、 NumPy 配列のようなサードパーティのデータ型ではそのような制限はなく、異なるプロセス間または異なるシステム間で、ゼロコピー (または最小限のコピー) でのpickle 処理の利用が可能です。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 574
PEP 574@footnote{https://peps.python.org/pep-0574/} -- Pickle プロトコルバージョン 5 による帯域外データ


@node グローバル変数を制限する,性能<2>,アウトオブバウンドバッファ,pickle --- Python オブジェクトの直列化
@anchor{library/pickle pickle-restrict}@anchor{2d1a}@anchor{library/pickle restricting-globals}@anchor{2d29}
@subsubsection グローバル変数を制限する


@geindex find_class() (pickle プロトコル)

デフォルトで、非 pickle 化は pickle データ内で見つけたあらゆるクラスや関数をインポートします。多くのアプリケーションでは、この振る舞いは受け入れられません。なぜなら、それによって unpickler が任意のコードをインポートして実行することが可能になるからです。この手の巧妙に作られた pickle データストリームがロードされたときに何を行うかをちょっと考えてみてください:

@example
>>> import pickle
>>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
hello world
0
@end example

この例において、unpickler は @ref{1676,,os.system()} 関数をインポートして、次に文字列の引数 "echo hello world" を適用しています。この例は無害ですが、システムを破壊する例を想像するのは難しくありません。

この理由のため、@ref{2d19,,Unpickler.find_class()} をカスタマイズすることで非 pickle 化で何を得るかを制御したくなるかもしれません。その名前が示唆するのと異なり、@ref{2d19,,Unpickler.find_class()} はグローバル (クラスや関数) が必要とした時にはいつでも呼びだされます。したがって、グローバルを完全に禁止することも安全なサブセットに制限することも可能です。

これは、一部の安全なクラスについてのみ @ref{13,,builtins} モジュールからロードすることを許可する unpickler の例です:

@example
import builtins
import io
import pickle

safe_builtins = @{
    'range',
    'complex',
    'set',
    'frozenset',
    'slice',
@}

class RestrictedUnpickler(pickle.Unpickler):

    def find_class(self, module, name):
        # Only allow safe classes from builtins.
        if module == "builtins" and name in safe_builtins:
            return getattr(builtins, name)
        # Forbid everything else.
        raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
                                     (module, name))

def restricted_loads(s):
    """Helper function analogous to pickle.loads()."""
    return RestrictedUnpickler(io.BytesIO(s)).load()
@end example

この unpickler が働く使用例は次のように意図されます:

@example
>>> restricted_loads(pickle.dumps([1, 2, range(15)]))
[1, 2, range(0, 15)]
>>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
Traceback (most recent call last):
  ...
pickle.UnpicklingError: global 'os.system' is forbidden
>>> restricted_loads(b'cbuiltins\neval\n'
...                  b'(S\'getattr(__import__("os"), "system")'
...                  b'("echo hello world")\'\ntR.')
Traceback (most recent call last):
  ...
pickle.UnpicklingError: global 'builtins.eval' is forbidden
@end example

@c XXX Add note about how extension codes could evade our protection
@c mechanism (e.g. cached classes do not invokes find_class()).

この例が示すように、非 pickle 化を認めるものに注意しなければなりません。したがって、セキュリティが重要な場合は @ref{134,,xmlrpc.client} の marshal API や、サードパーティのソリューションのような別の選択肢を考慮した方がよいでしょう。

@node 性能<2>,使用例<11>,グローバル変数を制限する,pickle --- Python オブジェクトの直列化
@anchor{library/pickle performance}@anchor{2d2a}
@subsubsection 性能


Recent versions of the pickle protocol (from protocol 2 and upwards) feature
efficient binary encodings for several common features and built-in types.
Also, the @code{pickle} module has a transparent optimizer written in C.

@node 使用例<11>,コマンドライン・インターフェース,性能<2>,pickle --- Python オブジェクトの直列化
@anchor{library/pickle examples}@anchor{2d2b}@anchor{library/pickle pickle-example}@anchor{2d2c}
@subsubsection 使用例


最も単純なコードでは、@ref{2d0c,,dump()} および @ref{f0c,,load()} 関数を使用してください。

@example
import pickle

# An arbitrary collection of objects supported by pickle.
data = @{
    'a': [1, 2.0, 3+4j],
    'b': ("character string", b"byte string"),
    'c': @{None, True, False@}
@}

with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
@end example

次の例は、pickle 化されたデータを読み込みます。

@example
import pickle

with open('data.pickle', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)
@end example

@c XXX: Add examples showing how to optimize pickles for size (like using

@c pickletools.optimize() or the gzip module).

@node コマンドライン・インターフェース,,使用例<11>,pickle --- Python オブジェクトの直列化
@anchor{library/pickle command-line-interface}@anchor{2d2d}@anchor{library/pickle pickle-cli}@anchor{2d2e}
@subsubsection コマンドライン・インターフェース


The @code{pickle} module can be invoked as a script from the command line,
it will display contents of the pickle files. However, when the pickle file
that you want to examine comes from an untrusted source, @code{-m pickletools}
is a safer option because it does not execute pickle bytecode, see
@ref{2d2f,,pickletools CLI usage}.

@example
python -m pickle pickle_file [pickle_file ...]
@end example

The following option is accepted:

@geindex pickle コマンドラインオプション; pickle_file
@anchor{library/pickle cmdoption-pickle-arg-pickle_file}@anchor{2d30}
@deffn {Option} pickle_file

A pickle file to read, or @code{-} to indicate reading from standard input.
@end deffn


@subsubheading 参考



@table @asis

@item @ref{2a,,copyreg} モジュール

拡張型を登録するための Pickle インターフェース構成機構。

@item @ref{ac,,pickletools} モジュール

pickle データの処理や分析を行うためのツール。

@item @ref{c8,,shelve} モジュール

Indexed databases of objects; uses @code{pickle}.

@item @ref{29,,copy} モジュール

オブジェクトの浅いコピーおよび深いコピー。

@item @ref{91,,marshal} モジュール

組み込み型の高性能な直列化。
@end table


@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node copyreg --- pickle サポート関数を登録する,shelve --- Python オブジェクトの永続化,pickle --- Python オブジェクトの直列化,データの永続化
@anchor{library/copyreg doc}@anchor{2d31}@anchor{library/copyreg copyreg-register-pickle-support-functions}@anchor{2d32}@anchor{library/copyreg module-copyreg}@anchor{2a}@anchor{library/copyreg translation-repo}@anchor{2d33}
@subsection @code{copyreg} --- @code{pickle} サポート関数を登録する


@geindex module; copyreg

`ソースコード:' Lib/copyreg.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/copyreg.py}

@geindex module;pickle
@geindex module;copy


__________________________________________________________________


The @code{copyreg} module offers a way to define functions used while pickling
specific objects.  The @ref{ab,,pickle} and @ref{29,,copy} modules use those functions
when pickling/copying those objects.  The module provides configuration
information about object constructors which are not classes.
Such constructors may be factory functions or class instances.

@geindex constructor() (copyreg モジュール)
@anchor{library/copyreg copyreg constructor}@anchor{2d34}
@deffn {の関数} copyreg.constructor (object)

`object' を有効なコンストラクタであると宣言します。 `object' が呼び出し可能でなければ(したがってコンストラクタとして有効でなければ)、 @ref{198,,TypeError} を発生します。
@end deffn

@geindex pickle() (copyreg モジュール)
@anchor{library/copyreg copyreg pickle}@anchor{2d12}
@deffn {の関数} copyreg.pickle (type, function, constructor_ob=None)

`function' が型 `type' のオブジェクトに対する"リダクション"関数として使われるように宣言します。 `function' は文字列か、2要素から6要素を含んだタプルを返さなければなりません。 `function' のインターフェースについての詳細は @ref{133a,,dispatch_table} を参照してください。

`constructor_ob' は古い機能で、現在は無視されますが、値を渡す場合は呼び出し可能 (callable) でなければなりません。

pickler オブジェクトまたは @ref{c13,,pickle.Pickler} のサブクラスの @ref{133a,,dispatch_table} 属性を、リダクション関数の宣言のために使うこともできるということは覚えておいてください。
@end deffn

@menu
* 使用例: 使用例<12>. 

@end menu

@node 使用例<12>,,,copyreg --- pickle サポート関数を登録する
@anchor{library/copyreg example}@anchor{2d35}
@subsubsection 使用例


下記の例は、pickle 関数を登録する方法と、それがどのように使用されるかを示そうとしています:

@example
>>> import copyreg, copy, pickle
>>> class C:
...     def __init__(self, a):
...         self.a = a
...
>>> def pickle_c(c):
...     print("pickling a C instance...")
...     return C, (c.a,)
...
>>> copyreg.pickle(C, pickle_c)
>>> c = C(1)
>>> d = copy.copy(c)
pickling a C instance...
>>> p = pickle.dumps(c)
pickling a C instance...
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node shelve --- Python オブジェクトの永続化,marshal --- 内部使用向けの Python オブジェクト直列化,copyreg --- pickle サポート関数を登録する,データの永続化
@anchor{library/shelve doc}@anchor{2d36}@anchor{library/shelve module-shelve}@anchor{c8}@anchor{library/shelve shelve-python-object-persistence}@anchor{2d37}@anchor{library/shelve translation-repo}@anchor{2d38}
@subsection @code{shelve} --- Python オブジェクトの永続化


@geindex module; shelve

`ソースコード:' Lib/shelve.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/shelve.py}

@geindex module;pickle


__________________________________________________________________


"シェルフ (shelf, 棚)" は辞書に似た永続性を持つオブジェクトです。 "dbm" データベースとの違いは、シェルフの値 (キーではありません！) は実質上どんな Python オブジェクトにも --- @ref{ab,,pickle} モジュールが扱えるなら何でも --- できるということです。これにはほとんどのクラスインスタンス、再帰的なデータ型、沢山の共有されたサブオブジェクトを含むオブジェクトが含まれます。キーは通常の文字列です。

@geindex open() (shelve モジュール)
@anchor{library/shelve shelve open}@anchor{1a71}
@deffn {の関数} shelve.open (filename, flag='c', protocol=None, writeback=False)

永続的な辞書を開きます。指定された `filename' は、根底にあるデータベースの基本ファイル名となります。副作用として、 `filename' には拡張子がつけられる場合があり、ひとつ以上のファイルが生成される可能性もあります。デフォルトでは、根底にあるデータベースファイルは読み書き可能なように開かれます。オプションの `flag' パラメータは @ref{112d,,dbm.open()} における `flag' パラメータと同様に解釈されます。

By default, pickles created with @ref{a2f,,pickle.DEFAULT_PROTOCOL} are used
to serialize values.  The version of the pickle protocol can be specified
with the `protocol' parameter.

Python の意味論により、シェルフには永続的な辞書の可変エントリがいつ変更されたかを知る術がありません。
デフォルトでは、変更されたオブジェクトはシェルフに代入されたとき `だけ' 書き込まれます (@ref{2d39,,使用例} 参照)。
オプションの `writeback' パラメータが  @code{True} に設定されている場合は、アクセスされたすべてのエントリはメモリ上にキャッシュされ、 @ref{2d3a,,sync()} および @ref{2d3b,,close()} を呼び出した際に書き戻されます;
この機能は永続的な辞書上の可変の要素に対する変更を容易にしますが、多数のエントリがアクセスされた場合、膨大な量のメモリがキャッシュのために消費され、アクセスされた全てのエントリを書き戻す (アクセスされたエントリが可変であるか、あるいは実際に変更されたかを決定する方法は存在しないのです) ために、ファイルを閉じる操作が非常に低速になります。


バージョン 3.10 で変更: @ref{a2f,,pickle.DEFAULT_PROTOCOL} is now used as the default pickle
protocol.



バージョン 3.11 で変更: Accepts @ref{5a1,,path-like object} for filename.


@cartouche
@quotation 注釈 
シェルフが自動的に閉じることに依存しないでください; それがもう必要ない場合は常に @ref{2d3b,,close()} を明示的に呼ぶか、 @ref{1a71,,shelve.open()} をコンテキストマネージャとして使用してください:

@example
with shelve.open('spam') as db:
    db['eggs'] = 'eggs'
@end example
@end quotation
@end cartouche
@end deffn
@anchor{library/shelve shelve-security}@anchor{2d3c}
@cartouche
@quotation 警告 
Because the @code{shelve} module is backed by @ref{ab,,pickle}, it is insecure
to load a shelf from an untrusted source.  Like with pickle, loading a shelf
can execute arbitrary code.
@end quotation
@end cartouche

Shelf objects support most of the methods and operations supported by dictionaries
(except copying, constructors and operators @code{|} and @code{|=}).  This eases the
transition from dictionary based scripts to those requiring persistent storage.

追加でサポートされるメソッドが二つあります:

@geindex sync() (shelve.Shelf のメソッド)
@anchor{library/shelve shelve Shelf sync}@anchor{2d3a}
@deffn {メソッド} Shelf.sync ()

シェルフが `writeback' を @ref{e07,,True} にセットして開かれている場合に、キャッシュ中の全てのエントリを書き戻します。また可能な場合は、キャッシュを空にしてディスク上の永続的な辞書を同期します。このメソッドはシェルフを @ref{2d3b,,close()} によって閉じるとき自動的に呼び出されます。
@end deffn

@geindex close() (shelve.Shelf のメソッド)
@anchor{library/shelve shelve Shelf close}@anchor{2d3b}
@deffn {メソッド} Shelf.close ()

永続的な `辞書' オブジェクトを同期して閉じます。既に閉じられているシェルフに対して呼び出すと @ref{2ec,,ValueError} を出し失敗します。
@end deffn


@subsubheading 参考


Persistent dictionary recipe@footnote{https://code.activestate.com/recipes/576642-persistent-dict-with-multiple-standard-file-format/}
with widely supported storage formats and having the speed of native
dictionaries.


@menu
* 制限事項:: 
* 使用例: 使用例<13>. 

@end menu

@node 制限事項,使用例<13>,,shelve --- Python オブジェクトの永続化
@anchor{library/shelve restrictions}@anchor{2d3d}
@subsubsection 制限事項


@geindex module;dbm.ndbm
@geindex module;dbm.gnu


@itemize *

@item 
どのデータベースパッケージが使われるか (例えば @ref{38,,dbm.ndbm} 、 @ref{37,,dbm.gnu}) は、どのインターフェースが利用可能かに依存します。従って、データベースを @ref{35,,dbm}  を使って直接開く方法は安全ではありません。データベースはまた、 @ref{35,,dbm} が使われた場合 (不幸なことに) その制約に縛られます --- これはデータベースに記録されたオブジェクト (の pickle 化された表現) はかなり小さくなければならず、キー衝突が生じた場合に、稀にデータベースを更新することができなくなることを意味します。

@item 
The @code{shelve} module does not support `concurrent' read/write access to
shelved objects.  (Multiple simultaneous read accesses are safe.)  When a
program has a shelf open for writing, no other program should have it open for
reading or writing.  Unix file locking can be used to solve this, but this
differs across Unix versions and requires knowledge about the database
implementation used.

@item 
On macOS @ref{38,,dbm.ndbm} can silently corrupt the database file on updates,
which can cause hard crashes when trying to read from the database.
@end itemize

@geindex Shelf (shelve のクラス)
@anchor{library/shelve shelve Shelf}@anchor{119d}
@deffn {クラス} shelve.Shelf (dict, protocol=None, writeback=False, keyencoding='utf-8')

@ref{12c0,,collections.abc.MutableMapping} のサブクラスで、 `dict' オブジェクト内にpickle化された値を保持します。

By default, pickles created with @ref{a2f,,pickle.DEFAULT_PROTOCOL} are used
to serialize values.  The version of the pickle protocol can be specified
with the `protocol' parameter.  See the @ref{ab,,pickle} documentation for a
discussion of the pickle protocols.

`writeback' パラメータが @code{True} に設定されていれば、アクセスされたすべてのエントリはメモリ上にキャッシュされ、ファイルを閉じる際に `dict' に書き戻されます; この機能により、可変のエントリに対して自然な操作が可能になりますが、さらに多くのメモリを消費し、辞書をファイルと同期して閉じる際に長い時間がかかるようになります。

`keyencoding' パラメータは、shelf の背後にある dict に対して使われる前にキーをエンコードするのに使用されるエンコーディングです。

@ref{119d,,Shelf} オブジェクトは、コンテキストマネージャとしても使用できます。この場合、 @ref{186,,with} ブロックが終了する際に、自動的に閉じられます。


バージョン 3.2 で変更: `keyencoding' パラメータを追加; 以前はキーは常に UTF-8 でエンコードされていました。



バージョン 3.4 で変更: コンテキストマネージャーサポートが追加されました。



バージョン 3.10 で変更: @ref{a2f,,pickle.DEFAULT_PROTOCOL} is now used as the default pickle
protocol.

@end deffn

@geindex BsdDbShelf (shelve のクラス)
@anchor{library/shelve shelve BsdDbShelf}@anchor{26b8}
@deffn {クラス} shelve.BsdDbShelf (dict, protocol=None, writeback=False, keyencoding='utf-8')

A subclass of @ref{119d,,Shelf} which exposes @code{first()}, @code{next()},
@code{previous()}, @code{last()} and @code{set_location()} methods.
These are available
in the third-party @code{bsddb} module from pybsddb@footnote{https://www.jcea.es/programacion/pybsddb.htm} but not in other database
modules.  The `dict' object passed to the constructor must support those
methods.  This is generally accomplished by calling one of
@code{bsddb.hashopen()}, @code{bsddb.btopen()} or @code{bsddb.rnopen()}.  The
optional `protocol', `writeback', and `keyencoding' parameters have the same
interpretation as for the @ref{119d,,Shelf} class.
@end deffn

@geindex DbfilenameShelf (shelve のクラス)
@anchor{library/shelve shelve DbfilenameShelf}@anchor{26b9}
@deffn {クラス} shelve.DbfilenameShelf (filename, flag='c', protocol=None, writeback=False)

@ref{119d,,Shelf} のサブクラスで、辞書に似たオブジェクトの代わりに `filename' を受理します。根底にあるファイルは @ref{112d,,dbm.open()} を使って開かれます。デフォルトでは、ファイルは読み書き可能な状態で開かれます。オプションの `flag' パラメータは @ref{1a71,,open()} 関数におけるパラメータと同様に解釈されます。オプションの `protocol' および `writeback' パラメータは @ref{119d,,Shelf} クラスにおけるパラメータと同様に解釈されます。
@end deffn

@node 使用例<13>,,制限事項,shelve --- Python オブジェクトの永続化
@anchor{library/shelve example}@anchor{2d3e}@anchor{library/shelve shelve-example}@anchor{2d39}
@subsubsection 使用例


インターフェースは以下のコードに集約されています (@code{key} は文字列で、@code{data} は任意のオブジェクトです):

@example
import shelve

d = shelve.open(filename)  # open -- file may get suffix added by low-level
                           # library

d[key] = data              # store data at key (overwrites old data if
                           # using an existing key)
data = d[key]              # retrieve a COPY of data at key (raise KeyError
                           # if no such key)
del d[key]                 # delete data stored at key (raises KeyError
                           # if no such key)

flag = key in d            # true if the key exists
klist = list(d.keys())     # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2]        # this works as expected, but...
d['xx'].append(3)          # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']             # extracts the copy
temp.append(5)             # mutates the copy
d['xx'] = temp             # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()                  # close it
@end example


@subsubheading 参考



@table @asis

@item @ref{35,,dbm} モジュール

@code{dbm} スタイルのデータベースに対する共通インターフェース。

@item @ref{ab,,pickle} モジュール

Object serialization used by @code{shelve}.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node marshal --- 内部使用向けの Python オブジェクト直列化,dbm --- Unix "データベース" へのインターフェース,shelve --- Python オブジェクトの永続化,データの永続化
@anchor{library/marshal doc}@anchor{2d3f}@anchor{library/marshal marshal-internal-python-object-serialization}@anchor{2d40}@anchor{library/marshal module-marshal}@anchor{91}@anchor{library/marshal translation-repo}@anchor{2d41}
@subsection @code{marshal} --- 内部使用向けの Python オブジェクト直列化


@geindex module; marshal


__________________________________________________________________


This module contains functions that can read and write Python values in a binary
format.  The format is specific to Python, but independent of machine
architecture issues (e.g., you can write a Python value to a file on a PC,
transport the file to a Mac, and read it back there).  Details of the format are
undocumented on purpose; it may change between Python versions (although it
rarely does). @footnote{
このモジュールの名前は (特に) Modula-3 の設計者の間で使われていた用語の一つに由来しています。彼らはデータを自己充足的な形式で輸送する操作に "整列化 (marshalling)" という用語を使いました。厳密に言えば、"整列させる (to marshal)" とは、あるデータを (例えば RPC バッファのように) 内部表現形式から外部表現形式に変換することを意味し、"非整列化 (unmarshalling)" とはその逆を意味します。
}

@geindex module;pickle
@geindex module;shelve

This is not a general "persistence" module.  For general persistence and
transfer of Python objects through RPC calls, see the modules @ref{ab,,pickle} and
@ref{c8,,shelve}.  The @code{marshal} module exists mainly to support reading and
writing the "pseudo-compiled" code for Python modules of @code{.pyc} files.
Therefore, the Python maintainers reserve the right to modify the marshal format
in backward incompatible ways should the need arise.
The format of code objects is not compatible between Python versions,
even if the version of the format is the same.
De-serializing a code object in the incorrect Python version has undefined behavior.
If you're serializing and
de-serializing Python objects, use the @ref{ab,,pickle} module instead -- the
performance is comparable, version independence is guaranteed, and pickle
supports a substantially wider range of objects than marshal.

@cartouche
@quotation 警告 
The @code{marshal} module is not intended to be secure against erroneous or
maliciously constructed data.  Never unmarshal data received from an
untrusted or unauthenticated source.
@end quotation
@end cartouche

bytes-like オブジェクトを操作する関数と同様に、ファイルの読み書きを行う関数が提供されています。

@geindex object;コード
@geindex コードオブジェクト

Not all Python object types are supported; in general, only objects whose value
is independent from a particular invocation of Python can be written and read by
this module.  The following types are supported:


@itemize *

@item 
Numeric types: @ref{19b,,int}, @ref{3c3,,bool}, @ref{196,,float}, @ref{197,,complex}.

@item 
Strings (@ref{169,,str}) and @ref{192,,bytes}.
@ref{193,,Bytes-like objects} like @ref{344,,bytearray} are
marshalled as @code{bytes}.

@item 
Containers: @ref{614,,tuple}, @ref{24d,,list}, @ref{184,,set}, @ref{7f2,,frozenset},
and (since @ref{2d42,,version} 5), @ref{694,,slice}.
It should be understood that these are supported only if the values contained
therein are themselves supported.
Recursive containers are supported since @ref{2d42,,version} 3.

@item 
The singletons @ref{885,,None}, @ref{2328,,Ellipsis} and @ref{df5,,StopIteration}.

@item 
@ref{1b,,code} objects, if `allow_code' is true. See note above about
version dependence.
@end itemize


バージョン 3.4 で変更: 


@itemize *

@item 
Added format version 3, which supports marshalling recursive lists, sets
and dictionaries.

@item 
Added format version 4, which supports efficient representations
of short strings.
@end itemize



バージョン 3.14 で変更: Added format version 5, which allows marshalling slices.


このモジュールでは、以下の関数が定義されています。

@geindex dump() (marshal モジュール)
@anchor{library/marshal marshal dump}@anchor{2d43}
@deffn {の関数} marshal.dump (value, file, version=version, /, *, allow_code=True)

開かれたファイルに値を書き込みます。値はサポートされている型でなくてはなりません。file は書き込み可能な  @ref{206e,,バイナリファイル} である必要があります。

If the value has (or contains an object that has) an unsupported type, a
@ref{2ec,,ValueError} exception is raised --- but garbage data will also be written
to the file.  The object will not be properly read back by @ref{1df6,,load()}.
@ref{4e6,,Code objects} are only supported if `allow_code' is true.

`version' 引数は @code{dump} が使用するデータフォーマットを指定します (下記を参照してください)。

引数 @code{value}, @code{version} を指定して @ref{1c6e,,監査イベント} @code{marshal.dumps} を送出します。


バージョン 3.13 で変更: Added the `allow_code' parameter.

@end deffn

@geindex load() (marshal モジュール)
@anchor{library/marshal marshal load}@anchor{1df6}
@deffn {の関数} marshal.load (file, /, *, allow_code=True)

Read one value from the open file and return it.  If no valid value is read
(e.g. because the data has a different Python version's incompatible marshal
format), raise @ref{14f1,,EOFError}, @ref{2ec,,ValueError} or @ref{198,,TypeError}.
@ref{4e6,,Code objects} are only supported if `allow_code' is true.
The file must be a readable @ref{206e,,binary file}.

引数無しで @ref{1c6e,,監査イベント} @code{marshal.load} を送出します。

@cartouche
@quotation 注釈 
サポートされていない型を含むオブジェクトが @ref{2d43,,dump()} で整列化されている場合、 @ref{1df6,,load()} は整列化不能な値を @code{None} で置き換えます。
@end quotation
@end cartouche


バージョン 3.10 で変更: This call used to raise a @code{code.__new__} audit event for each code object. Now
it raises a single @code{marshal.load} event for the entire load operation.



バージョン 3.13 で変更: Added the `allow_code' parameter.

@end deffn

@geindex dumps() (marshal モジュール)
@anchor{library/marshal marshal dumps}@anchor{10a5}
@deffn {の関数} marshal.dumps (value, version=version, /, *, allow_code=True)

Return the bytes object that would be written to a file by @code{dump(value, file)}.  The
value must be a supported type.  Raise a @ref{2ec,,ValueError} exception if value
has (or contains an object that has) an unsupported type.
@ref{4e6,,Code objects} are only supported if `allow_code' is true.

`version' 引数は @code{dumps} が使用するデータフォーマットを指定します (下記を参照してください)。

引数 @code{value}, @code{version} を指定して @ref{1c6e,,監査イベント} @code{marshal.dumps} を送出します。


バージョン 3.13 で変更: Added the `allow_code' parameter.

@end deffn

@geindex loads() (marshal モジュール)
@anchor{library/marshal marshal loads}@anchor{2d44}
@deffn {の関数} marshal.loads (bytes, /, *, allow_code=True)

Convert the @ref{193,,bytes-like object} to a value.  If no valid value is found, raise
@ref{14f1,,EOFError}, @ref{2ec,,ValueError} or @ref{198,,TypeError}.
@ref{4e6,,Code objects} are only supported if `allow_code' is true.
Extra bytes in the input are ignored.

引数 @code{bytes} を指定して @ref{1c6e,,監査イベント} @code{marshal.loads} を送出します。


バージョン 3.10 で変更: This call used to raise a @code{code.__new__} audit event for each code object. Now
it raises a single @code{marshal.loads} event for the entire load operation.



バージョン 3.13 で変更: Added the `allow_code' parameter.

@end deffn

これに加えて、以下の定数が定義されています:

@geindex version (marshal モジュール)
@anchor{library/marshal marshal version}@anchor{2d42}
@deffn {データ} marshal.version

Indicates the format that the module uses.
Version 0 is the historical first version; subsequent versions
add new features.
Generally, a new version becomes the default when it is introduced.


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Version

@tab

Available since

@tab

新しい機能

@item

1

@tab

Python 2.4

@tab

Sharing interned strings

@item

2

@tab

Python 2.5

@tab

Binary representation of floats

@item

3

@tab

Python 3.4

@tab

Support for object instancing and recursion

@item

4

@tab

Python 3.4

@tab

Efficient representation of short strings

@item

5

@tab

Python 3.14

@tab

Support for @ref{694,,slice} objects

@end multitable

@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node dbm --- Unix "データベース" へのインターフェース,sqlite3 --- SQLite データベース用の DB-API 2 0 インターフェース,marshal --- 内部使用向けの Python オブジェクト直列化,データの永続化
@anchor{library/dbm doc}@anchor{2d45}@anchor{library/dbm dbm-interfaces-to-unix-databases}@anchor{2d46}@anchor{library/dbm module-dbm}@anchor{35}@anchor{library/dbm translation-repo}@anchor{2d47}
@subsection @code{dbm} --- Unix "データベース" へのインターフェース


@geindex module; dbm

`ソースコード:' Lib/dbm/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/dbm/__init__.py}


__________________________________________________________________


@code{dbm} is a generic interface to variants of the DBM database:


@itemize *

@item 
@ref{39,,dbm.sqlite3}

@item 
@ref{37,,dbm.gnu}

@item 
@ref{38,,dbm.ndbm}
@end itemize

If none of these modules are installed, the
slow-but-simple implementation in module @ref{36,,dbm.dumb} will be used.  There
is a third party interface@footnote{https://www.jcea.es/programacion/pybsddb.htm} to
the Oracle Berkeley DB.

@geindex error
@anchor{library/dbm dbm error}@anchor{2d48}
@deffn {例外} dbm.error

サポートされているモジュールそれぞれによって送出される可能性のある例外を含むタプル。これにはユニークな例外があり、最初の要素として同じく @ref{2d48,,dbm.error} という名前の例外が含まれます --- @ref{2d48,,dbm.error} が送出される場合、後者(訳注:タプルの @code{dbm.error} ではなく例外 @ref{2d48,,dbm.error})が使用されます。
@end deffn

@geindex whichdb() (dbm モジュール)
@anchor{library/dbm dbm whichdb}@anchor{2d49}
@deffn {の関数} dbm.whichdb (filename)

This function attempts to guess which of the several simple database modules
available --- @ref{39,,dbm.sqlite3}, @ref{37,,dbm.gnu}, @ref{38,,dbm.ndbm},
or @ref{36,,dbm.dumb} --- should be used to open a given file.

Return one of the following values:


@itemize *

@item 
@code{None} if the file can't be opened because it's unreadable or doesn't exist

@item 
the empty string (@code{'@w{'}}) if the file's format can't be guessed

@item 
a string containing the required module name, such as @code{'dbm.ndbm'} or @code{'dbm.gnu'}
@end itemize


バージョン 3.11 で変更: `filename' accepts a @ref{5a1,,path-like object}.

@end deffn

@c Substitutions for the open() flag param docs;
@c all submodules use the same text.

@geindex open() (dbm モジュール)
@anchor{library/dbm dbm open}@anchor{112d}
@deffn {の関数} dbm.open (file, flag='r', mode=0o666)

Open a database and return the corresponding database object.

@*パラメータ: 

@itemize *

@item 
@code{file} (@ref{5a1,,path-like object}) -- 
The database file to open.

If the database file already exists, the @ref{2d49,,whichdb()} function is used to
determine its type and the appropriate module is used; if it does not exist,
the first submodule listed above that can be imported is used.


@item 
@code{flag} (@ref{169,,str}) -- 

@itemize *

@item 
@code{'r'} (default): Open existing database for reading only.

@item 
@code{'w'}: Open existing database for reading and writing.

@item 
@code{'c'}: Open database for reading and writing, creating it if it doesn't exist.

@item 
@code{'n'}: Always create a new, empty database, open for reading and writing.
@end itemize


@item 
@code{mode} (@ref{19b,,int}) -- The Unix file access mode of the file (default: octal @code{0o666}),
used only when the database has to be created.
@end itemize



バージョン 3.11 で変更: `file' accepts a @ref{5a1,,path-like object}.

@end deffn

The object returned by @ref{112d,,open()} supports the basic
functionality of mutable @ref{13d3,,mappings};
keys and their corresponding values can be stored, retrieved, and
deleted, and iteration, the @ref{34b,,in} operator and methods @code{keys()},
@code{get()}, @code{setdefault()} and @code{clear()} are available.
The @code{keys()} method returns a list instead of a view object.
The @code{setdefault()} method requires two arguments.

Key and values are always stored as @ref{192,,bytes}. This means that when
strings are used they are implicitly converted to the default encoding before
being stored.

これらのオブジェクトは、 @ref{186,,with} 文での使用にも対応しています。with 文を使用した場合、終了時に自動的に閉じられます。


バージョン 3.2 で変更: @code{get()} and @code{setdefault()} methods are now available for all
@code{dbm} backends.



バージョン 3.4 で変更: Added native support for the context management protocol to the objects
returned by @ref{112d,,open()}.



バージョン 3.8 で変更: Deleting a key from a read-only database raises a database module specific exception
instead of @ref{5e7,,KeyError}.



バージョン 3.13 で変更: @code{clear()} methods are now available for all @code{dbm} backends.


以下の例ではホスト名と対応するタイトルをいくつか記録し、データベースの内容を出力します:

@example
import dbm

# Open database, creating it if necessary.
with dbm.open('cache', 'c') as db:

    # Record some values
    db[b'hello'] = b'there'
    db['www.python.org'] = 'Python Website'
    db['www.cnn.com'] = 'Cable News Network'

    # Note that the keys are considered bytes now.
    assert db[b'www.python.org'] == b'Python Website'
    # Notice how the value is now in bytes.
    assert db['www.cnn.com'] == b'Cable News Network'

    # Often-used methods of the dict interface work too.
    print(db.get('python.org', b'not present'))

    # Storing a non-string key or value will raise an exception (most
    # likely a TypeError).
    db['www.yahoo.com'] = 4

# db is automatically closed when leaving the with statement.
@end example


@subsubheading 参考



@table @asis

@item @ref{c8,,shelve} モジュール

非文字列データを記録する永続化モジュール。
@end table


個々のサブモジュールは以降の節で説明されます。

@menu
* dbm.sqlite3: dbm sqlite3 --- SQLite backend for dbm. SQLite backend for dbm
* dbm.gnu: dbm gnu --- GNU database manager. GNU database manager
* dbm.ndbm: dbm ndbm --- New Database Manager. New Database Manager
* dbm.dumb: dbm dumb --- Portable DBM implementation. Portable DBM implementation

@end menu

@node dbm sqlite3 --- SQLite backend for dbm,dbm gnu --- GNU database manager,,dbm --- Unix "データベース" へのインターフェース
@anchor{library/dbm dbm-sqlite3-sqlite-backend-for-dbm}@anchor{2d4a}@anchor{library/dbm module-dbm sqlite3}@anchor{39}
@subsubsection @code{dbm.sqlite3} --- SQLite backend for dbm


@geindex module; dbm.sqlite3


Added in version 3.13.


`Source code:' Lib/dbm/sqlite3.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/dbm/sqlite3.py}


__________________________________________________________________


This module uses the standard library @ref{d4,,sqlite3} module to provide an
SQLite backend for the @code{dbm} module.
The files created by @code{dbm.sqlite3} can thus be opened by @ref{d4,,sqlite3},
or any other SQLite browser, including the SQLite CLI.

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@geindex open() (dbm.sqlite3 モジュール)
@anchor{library/dbm dbm sqlite3 open}@anchor{2d4b}
@deffn {の関数} dbm.sqlite3.open (filename, /, flag='r', mode=0o666)

Open an SQLite database.

@*パラメータ: 

@itemize *

@item 
@code{filename} (@ref{5a1,,path-like object}) -- The path to the database to be opened.

@item 
@code{flag} (@ref{169,,str}) -- 

@itemize *

@item 
@code{'r'} (default): Open existing database for reading only.

@item 
@code{'w'}: Open existing database for reading and writing.

@item 
@code{'c'}: Open database for reading and writing, creating it if it doesn't exist.

@item 
@code{'n'}: Always create a new, empty database, open for reading and writing.
@end itemize


@item 
@code{mode} -- The Unix file access mode of the file (default: octal @code{0o666}),
used only when the database has to be created.
@end itemize


The returned database object behaves similar to a mutable @ref{13d3,,mapping},
but the @code{keys()} method returns a list, and
the @code{setdefault()} method requires two arguments.
It also supports a "closing" context manager via the @ref{186,,with} keyword.

次のメソッドを提供しています:

@geindex close() (dbm.sqlite3.sqlite3 のメソッド)
@anchor{library/dbm dbm sqlite3 sqlite3 close}@anchor{2d4c}
@deffn {メソッド} sqlite3.close ()

Close the SQLite database.
@end deffn
@end deffn

@node dbm gnu --- GNU database manager,dbm ndbm --- New Database Manager,dbm sqlite3 --- SQLite backend for dbm,dbm --- Unix "データベース" へのインターフェース
@anchor{library/dbm dbm-gnu-gnu-database-manager}@anchor{2d4d}@anchor{library/dbm module-dbm gnu}@anchor{37}
@subsubsection @code{dbm.gnu} --- GNU database manager


@geindex module; dbm.gnu

`ソースコード:' Lib/dbm/gnu.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/dbm/gnu.py}


__________________________________________________________________


The @code{dbm.gnu} module provides an interface to the @abbr{GDBM,GNU dbm}
library, similar to the @ref{38,,dbm.ndbm} module, but with additional
functionality like crash tolerance.

@cartouche
@quotation 注釈 
The file formats created by @code{dbm.gnu} and @ref{38,,dbm.ndbm} are incompatible
and can not be used interchangeably.
@end quotation
@end cartouche

@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

@ref{213f,,Availability}: Unix.

@geindex error
@anchor{library/dbm dbm gnu error}@anchor{c91}
@deffn {例外} dbm.gnu.error

Raised on @code{dbm.gnu}-specific errors, such as I/O errors. @ref{5e7,,KeyError} is
raised for general mapping errors like specifying an incorrect key.
@end deffn

@geindex open_flags (dbm.gnu モジュール)
@anchor{library/dbm dbm gnu open_flags}@anchor{2d4e}
@deffn {データ} dbm.gnu.open_flags

A string of characters the `flag' parameter of @ref{1e20,,open()} supports.
@end deffn

@geindex open() (dbm.gnu モジュール)
@anchor{library/dbm dbm gnu open}@anchor{1e20}
@deffn {の関数} dbm.gnu.open (filename, flag='r', mode=0o666, /)

Open a GDBM database and return a @code{gdbm} object.

@*パラメータ: 

@itemize *

@item 
@code{filename} (@ref{5a1,,path-like object}) -- The database file to open.

@item 
@code{flag} (@ref{169,,str}) -- 

@itemize *

@item 
@code{'r'} (default): Open existing database for reading only.

@item 
@code{'w'}: Open existing database for reading and writing.

@item 
@code{'c'}: Open database for reading and writing, creating it if it doesn't exist.

@item 
@code{'n'}: Always create a new, empty database, open for reading and writing.
@end itemize

The following additional characters may be appended
to control how the database is opened:


@itemize *

@item 
@code{'f'}: Open the database in fast mode.
Writes to the database will not be synchronized.

@item 
@code{'s'}: Synchronized mode.
Changes to the database will be written immediately to the file.

@item 
@code{'u'}: Do not lock database.
@end itemize

Not all flags are valid for all versions of GDBM.
See the @ref{2d4e,,open_flags} member for a list of supported flag characters.


@item 
@code{mode} (@ref{19b,,int}) -- The Unix file access mode of the file (default: octal @code{0o666}),
used only when the database has to be created.
@end itemize


@*例外: 
@ref{c91,,error} -- If an invalid `flag' argument is passed.



バージョン 3.11 で変更: `filename' accepts a @ref{5a1,,path-like object}.


@code{gdbm} objects behave similar to mutable @ref{13d3,,mappings},
but methods @code{items()}, @code{values()}, @code{pop()}, @code{popitem()},
and @code{update()} are not supported,
the @code{keys()} method returns a list, and
the @code{setdefault()} method requires two arguments.
It also supports a "closing" context manager via the @ref{186,,with} keyword.


バージョン 3.2 で変更: Added the @code{get()} and @code{setdefault()} methods.



バージョン 3.13 で変更: Added the @code{clear()} method.


The following methods are also provided:

@geindex close() (dbm.gnu.gdbm のメソッド)
@anchor{library/dbm dbm gnu gdbm close}@anchor{2d4f}
@deffn {メソッド} gdbm.close ()

Close the GDBM database.
@end deffn

@geindex firstkey() (dbm.gnu.gdbm のメソッド)
@anchor{library/dbm dbm gnu gdbm firstkey}@anchor{2d50}
@deffn {メソッド} gdbm.firstkey ()

It's possible to loop over every key in the database using this method  and the
@ref{2d51,,nextkey()} method.  The traversal is ordered by GDBM's internal
hash values, and won't be sorted by the key values.  This method returns
the starting key.
@end deffn

@geindex nextkey() (dbm.gnu.gdbm のメソッド)
@anchor{library/dbm dbm gnu gdbm nextkey}@anchor{2d51}
@deffn {メソッド} gdbm.nextkey (key)

データベースの順方向探索において、`key' よりも後に来るキーを返します。以下のコードはデータベース @code{db} について、キー全てを含むリストをメモリ上に生成することなく全てのキーを出力します:

@example
k = db.firstkey()
while k is not None:
    print(k)
    k = db.nextkey(k)
@end example
@end deffn

@geindex reorganize() (dbm.gnu.gdbm のメソッド)
@anchor{library/dbm dbm gnu gdbm reorganize}@anchor{2d52}
@deffn {メソッド} gdbm.reorganize ()

If you have carried out a lot of deletions and would like to shrink the space
used by the GDBM file, this routine will reorganize the database.  @code{gdbm}
objects will not shorten the length of a database file except by using this
reorganization; otherwise, deleted file space will be kept and reused as new
(key, value) pairs are added.
@end deffn

@geindex sync() (dbm.gnu.gdbm のメソッド)
@anchor{library/dbm dbm gnu gdbm sync}@anchor{2d53}
@deffn {メソッド} gdbm.sync ()

データベースが高速モードで開かれていた場合、このメソッドはディスクにまだ書き込まれていないデータを全て書き込ませます。
@end deffn
@end deffn

@node dbm ndbm --- New Database Manager,dbm dumb --- Portable DBM implementation,dbm gnu --- GNU database manager,dbm --- Unix "データベース" へのインターフェース
@anchor{library/dbm dbm-ndbm-new-database-manager}@anchor{2d54}@anchor{library/dbm module-dbm ndbm}@anchor{38}
@subsubsection @code{dbm.ndbm} --- New Database Manager


@geindex module; dbm.ndbm

`ソースコード:' Lib/dbm/ndbm.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/dbm/ndbm.py}


__________________________________________________________________


The @code{dbm.ndbm} module provides an interface to the
@abbr{NDBM,New Database Manager} library.
This module can be used with the "classic" NDBM interface or the
@abbr{GDBM} compatibility interface.

@cartouche
@quotation 注釈 
The file formats created by @ref{37,,dbm.gnu} and @code{dbm.ndbm} are incompatible
and can not be used interchangeably.
@end quotation
@end cartouche

@cartouche
@quotation 警告 
The NDBM library shipped as part of macOS has an undocumented limitation on the
size of values, which can result in corrupted database files
when storing values larger than this limit. Reading such corrupted files can
result in a hard crash (segmentation fault).
@end quotation
@end cartouche

@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

@ref{213f,,Availability}: Unix.

@geindex error
@anchor{library/dbm dbm ndbm error}@anchor{c92}
@deffn {例外} dbm.ndbm.error

Raised on @code{dbm.ndbm}-specific errors, such as I/O errors. @ref{5e7,,KeyError} is raised
for general mapping errors like specifying an incorrect key.
@end deffn

@geindex library (dbm.ndbm モジュール)
@anchor{library/dbm dbm ndbm library}@anchor{2d55}
@deffn {データ} dbm.ndbm.library

Name of the NDBM implementation library used.
@end deffn

@geindex open() (dbm.ndbm モジュール)
@anchor{library/dbm dbm ndbm open}@anchor{1e21}
@deffn {の関数} dbm.ndbm.open (filename, flag='r', mode=0o666, /)

Open an NDBM database and return an @code{ndbm} object.

@*パラメータ: 

@itemize *

@item 
@code{filename} (@ref{5a1,,path-like object}) -- The basename of the database file
(without the @code{.dir} or @code{.pag} extensions).

@item 
@code{flag} (@ref{169,,str}) -- 

@itemize *

@item 
@code{'r'} (default): Open existing database for reading only.

@item 
@code{'w'}: Open existing database for reading and writing.

@item 
@code{'c'}: Open database for reading and writing, creating it if it doesn't exist.

@item 
@code{'n'}: Always create a new, empty database, open for reading and writing.
@end itemize


@item 
@code{mode} (@ref{19b,,int}) -- The Unix file access mode of the file (default: octal @code{0o666}),
used only when the database has to be created.
@end itemize



バージョン 3.11 で変更: Accepts @ref{5a1,,path-like object} for filename.


@code{ndbm} objects behave similar to mutable @ref{13d3,,mappings},
but methods @code{items()}, @code{values()}, @code{pop()}, @code{popitem()},
and @code{update()} are not supported,
the @code{keys()} method returns a list, and
the @code{setdefault()} method requires two arguments.
It also supports a "closing" context manager via the @ref{186,,with} keyword.


バージョン 3.2 で変更: Added the @code{get()} and @code{setdefault()} methods.



バージョン 3.13 で変更: Added the @code{clear()} method.


次のメソッドを提供しています:

@geindex close() (dbm.ndbm.ndbm のメソッド)
@anchor{library/dbm dbm ndbm ndbm close}@anchor{2d56}
@deffn {メソッド} ndbm.close ()

Close the NDBM database.
@end deffn
@end deffn

@node dbm dumb --- Portable DBM implementation,,dbm ndbm --- New Database Manager,dbm --- Unix "データベース" へのインターフェース
@anchor{library/dbm dbm-dumb-portable-dbm-implementation}@anchor{2d57}@anchor{library/dbm module-dbm dumb}@anchor{36}
@subsubsection @code{dbm.dumb} --- Portable DBM implementation


@geindex module; dbm.dumb

`ソースコード:' Lib/dbm/dumb.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/dbm/dumb.py}

@geindex データベース

@cartouche
@quotation 注釈 
The @code{dbm.dumb} module is intended as a last resort fallback for the
@code{dbm} module when a more robust module is not available. The @code{dbm.dumb}
module is not written for speed and is not nearly as heavily used as the other
database modules.
@end quotation
@end cartouche


__________________________________________________________________


The @code{dbm.dumb} module provides a persistent @ref{183,,dict}-like
interface which is written entirely in Python.
Unlike other @code{dbm} backends, such as @ref{37,,dbm.gnu}, no
external library is required.

The @code{dbm.dumb} module defines the following:

@geindex error
@anchor{library/dbm dbm dumb error}@anchor{c90}
@deffn {例外} dbm.dumb.error

Raised on @code{dbm.dumb}-specific errors, such as I/O errors.  @ref{5e7,,KeyError} is
raised for general mapping errors like specifying an incorrect key.
@end deffn

@geindex open() (dbm.dumb モジュール)
@anchor{library/dbm dbm dumb open}@anchor{c8d}
@deffn {の関数} dbm.dumb.open (filename, flag='c', mode=0o666)

Open a @code{dbm.dumb} database.

@*パラメータ: 

@itemize *

@item 
@code{filename} -- 
The basename of the database file (without extensions).
A new database creates the following files:


@itemize -

@item 
@code{`filename'.dat}

@item 
@code{`filename'.dir}
@end itemize


@item 
@code{flag} (@ref{169,,str}) -- 

@itemize *

@item 
@code{'r'}: Open existing database for reading only.

@item 
@code{'w'}: Open existing database for reading and writing.

@item 
@code{'c'} (default): Open database for reading and writing, creating it if it doesn't exist.

@item 
@code{'n'}: Always create a new, empty database, open for reading and writing.
@end itemize


@item 
@code{mode} (@ref{19b,,int}) -- The Unix file access mode of the file (default: octal @code{0o666}),
used only when the database has to be created.
@end itemize


@cartouche
@quotation 警告 
十分に大きかったり複雑だったりするエントリーのあるデータベースを読み込んでいるときに、 Python の抽象構文木コンパイラのスタックの深さの限界を越えるせいで、 Python インタプリタをクラッシュさせることができます。
@end quotation
@end cartouche


バージョン 3.5 で変更: @ref{c8d,,open()} always creates a new database when `flag' is @code{'n'}.



バージョン 3.8 で変更: A database opened read-only if `flag' is @code{'r'}.
A database is not created if it does not exist if `flag' is @code{'r'} or @code{'w'}.



バージョン 3.11 で変更: `filename' accepts a @ref{5a1,,path-like object}.


The returned database object behaves similar to a mutable @ref{13d3,,mapping},
but the @code{keys()} and @code{items()} methods return lists, and
the @code{setdefault()} method requires two arguments.
It also supports a "closing" context manager via the @ref{186,,with} keyword.

The following methods are also provided:

@geindex close() (dbm.dumb.dumbdbm のメソッド)
@anchor{library/dbm dbm dumb dumbdbm close}@anchor{2d58}
@deffn {メソッド} dumbdbm.close ()

Close the database.
@end deffn

@geindex sync() (dbm.dumb.dumbdbm のメソッド)
@anchor{library/dbm dbm dumb dumbdbm sync}@anchor{2d59}
@deffn {メソッド} dumbdbm.sync ()

Synchronize the on-disk directory and data files.  This method is called
by the @ref{2d3a,,shelve.Shelf.sync()} method.
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node sqlite3 --- SQLite データベース用の DB-API 2 0 インターフェース,,dbm --- Unix "データベース" へのインターフェース,データの永続化
@anchor{library/sqlite3 doc}@anchor{2d5a}@anchor{library/sqlite3 module-sqlite3}@anchor{d4}@anchor{library/sqlite3 sqlite3-db-api-2-0-interface-for-sqlite-databases}@anchor{2d5b}@anchor{library/sqlite3 translation-repo}@anchor{2d5c}
@subsection @code{sqlite3} --- SQLite データベース用の DB-API 2.0 インターフェース


@geindex module; sqlite3

`ソースコード:' Lib/sqlite3/@footnote{https://github.com/python/cpython/tree/3.14/Lib/sqlite3/}

@c Make sure we always doctest the tutorial with an empty database.

@c import sqlite3
@c src = sqlite3.connect(":memory:", isolation_level=None)
@c dst = sqlite3.connect("tutorial.db", isolation_level=None)
@c src.backup(dst)
@c src.close()
@c dst.close()
@c del src, dst
@anchor{library/sqlite3 sqlite3-intro}@anchor{2d5d}
SQLite は、軽量なディスク上のデータベースを提供する C ライブラリです。別のサーバプロセスを用意する必要なく、 SQL クエリー言語の非標準的な一種を使用してデータベースにアクセスできます。一部のアプリケーションは内部データ保存に SQLite を使えます。また、SQLite を使ってアプリケーションのプロトタイプを作り、その後そのコードを PostgreSQL や Oracle のような大規模データベースに移植するということも可能です。

The @code{sqlite3} module was written by Gerhard Häring.  It provides an SQL interface
compliant with the DB-API 2.0 specification described by 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/}, and
requires the third-party SQLite@footnote{https://sqlite.org/} library.

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

この文書には大きく分けて 4 つの節があります:


@itemize *

@item 
@ref{2d5e,,チュートリアル} @code{sqlite3} モジュールの使い方を学びます。

@item 
@ref{2d5f,,リファレンス} このモジュールが定義するクラスと関数について説明します。

@item 
@ref{2d60,,ハウツー・ガイド} 特定のタスクの処理方法について詳しく説明します。

@item 
@ref{2d61,,説明} トランザクション制御の背景をより深く掘り下げて説明します。
@end itemize


@subsubheading 参考



@table @asis

@item @indicateurl{https://www.sqlite.org}

SQLite のウェブページ。ここの文書ではサポートされる SQL 方言の文法と使えるデータ型を説明しています。

@item @indicateurl{https://www.w3schools.com/sql/}

SQL 学習に効くチュートリアル、リファレンス、実例集。

@geindex Python Enhancement Proposals; PEP 249

@item PEP 249@footnote{https://peps.python.org/pep-0249/} - Database API Specification 2.0

Marc-Andre Lemburg により書かれた PEP。
@end table


@c We use the following practises for SQL code:
@c - UPPERCASE for keywords
@c - snake_case for schema
@c - single quotes for string literals
@c - singular for table names
@c - if needed, use double quotes for table and column names

@menu
* チュートリアル:: 
* リファレンス:: 
* ハウツー・ガイド:: 
* 説明:: 

@end menu

@node チュートリアル,リファレンス,,sqlite3 --- SQLite データベース用の DB-API 2 0 インターフェース
@anchor{library/sqlite3 sqlite3-tutorial}@anchor{2d5e}@anchor{library/sqlite3 tutorial}@anchor{2d62}
@subsubsection チュートリアル


このチュートリアルでは、あなたは基本的な @code{sqlite3} 機能を使用して、 例としてモンティ・パイソンの映画のデータベースを作成します。 あなたがカーソル(cursors@footnote{https://en.wikipedia.org/wiki/Cursor_(databases)})やトランザクション(transactions@footnote{https://en.wikipedia.org/wiki/Database_transaction})を含むデータベースの基本概念を理解していることを前提としています。

最初に、新しいデータベースを作成し、データベース接続(connection)を開いて @code{sqlite3} が動作できるようにする必要があります。 @ref{5a6,,sqlite3.connect()} を呼び出して、データベース @code{tutorial.db} への接続を現在の作業ディレクトリに作成します。存在しない場合は暗黙的に作成します。

@example
import sqlite3
con = sqlite3.connect("tutorial.db")
@end example

返された @ref{54d,,Connection} オブジェクト @code{con} は、ディスク上のデータベースへの接続を表します。

SQL 文を実行し、SQL クエリから結果を取得するには、データベース・カーソルを使用する必要があります。 @ref{2d63,,con.cursor()} を呼び出して @ref{2d64,,Cursor} を作成してください:

@example
cur = con.cursor()
@end example

さて、今やデータベース接続とカーソルを取得したので、タイトル(title)とリリース年(year)と、レビュー・スコア(score)の列(columns)を持つデータベース・テーブル @code{movie} を作成できます。 簡単にするために、テーブル宣言では列名だけを使用できます。SQLite の 柔軟な型付け(flexible typing@footnote{https://www.sqlite.org/flextypegood.html})機能のおかげで、データ型の指定はオプションになっています。 @ref{5b0,,cur.execute(...)} を呼び出して @code{CREATE TABLE} 文を実行してください:

@example
cur.execute("CREATE TABLE movie(title, year, score)")
@end example

@c Ideally, we'd use sqlite_schema instead of sqlite_master below,
@c but SQLite versions older than 3.33.0 do not recognise that variant.

SQLite に組み込みの @code{sqlite_master} テーブルに対してクエリを実行することで、新しいテーブルが作成されたことを確認できます。このテーブルには、 @code{movie} テーブル定義のエントリが含まれているはずです(詳細は The Schema Table@footnote{https://www.sqlite.org/schematab.html} 参照)。 @ref{5b0,,cur.execute(...)} を呼び出してクエリを実行して、その結果を @code{res} に代入し、結果の行(row)を取得するために @ref{2d65,,res.fetchone()} を呼び出します:

@example
>>> res = cur.execute("SELECT name FROM sqlite_master")
>>> res.fetchone()
('movie',)
@end example

We can see that the table has been created,
as the query returns a @ref{614,,tuple} containing the table's name.
If we query @code{sqlite_master} for a non-existent table @code{spam},
@code{res.fetchone()} will return @code{None}:

@example
>>> res = cur.execute("SELECT name FROM sqlite_master WHERE name='spam'")
>>> res.fetchone() is None
True
@end example

ここで、 INSERT 文を実行して SQL のリテラルとして提供された 2 行のデータを追加し、 再度 @ref{5b0,,cur.execute(...)} を呼び出して追加します:

@example
cur.execute("""
    INSERT INTO movie VALUES
        ('Monty Python and the Holy Grail', 1975, 8.2),
        ('And Now for Something Completely Different', 1971, 7.5)
""")
@end example

@code{INSERT} 文は、変更がデータベースに保存される前にコミットする必要がある、トランザクションを暗黙的に開きます(詳細は、 @ref{2d66,,トランザクション制御} 参照)。 トランザクションをコミットするために接続オブジェクト(connection object)の @ref{2d67,,con.commit()} を呼び出して下さい:

@example
con.commit()
@end example

@code{SELECT} クエリを実行することで、データが正しく挿入されたことを確認できます。 結果のすべての行を返すには、おなじみの @ref{5b0,,cur.execute(...)} を使用して結果を @code{res} に代入し、 @ref{2d68,,res.fetchall()} を呼び出して下さい:

@example
>>> res = cur.execute("SELECT score FROM movie")
>>> res.fetchall()
[(8.2,), (7.5,)]
@end example

結果は、2 つの @code{タプル} の @ref{24d,,リスト} で、 それぞれのタプルにその行の @code{score} 値が含まれています。

ここで、 @ref{5b1,,cur.executemany(...)} を呼び出して、さらに 3 行挿入します:

@example
data = [
    ("Monty Python Live at the Hollywood Bowl", 1982, 7.9),
    ("Monty Python's The Meaning of Life", 1983, 7.5),
    ("Monty Python's Life of Brian", 1979, 8.0),
]
cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
con.commit()  # Remember to commit the transaction after executing INSERT.
@end example

@code{data} をクエリに結び付け(bind)するために @code{?} プレースホルダが使用されていることに注意してください。 SQL インジェクション攻撃(SQL injection attacks@footnote{https://en.wikipedia.org/wiki/SQL_injection})を避けるために、Python の値を SQL 文に結び付けするには、常に @ref{205a,,文字列フォーマット} の代わりにプレースホルダを使用してください(詳細は @ref{5b2,,プレースホルダを使用して SQL クエリに値を結び付ける方法} 参照)。

@code{SELECT} クエリを実行することで、新しい行が挿入されたことを確認できます。今回は、クエリの結果を反復処理します:

@example
>>> for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):
...     print(row)
(1971, 'And Now for Something Completely Different')
(1975, 'Monty Python and the Holy Grail')
(1979, "Monty Python's Life of Brian")
(1982, 'Monty Python Live at the Hollywood Bowl')
(1983, "Monty Python's The Meaning of Life")
@end example

各行(row)は @ref{614,,タプル} の @code{(year, title)} の 2 つの項目であり、クエリで選択された列(columns)にマッチします。

最後に、 @ref{54e,,con.close()} を呼び出して既存の接続(connection)を閉じ、新しい接続を開き、新しいカーソルを作成してから、データベースに対してクエリを実行して、データベースがディスクに書き込まれたことを確認します:

@example
>>> con.close()
>>> new_con = sqlite3.connect("tutorial.db")
>>> new_cur = new_con.cursor()
>>> res = new_cur.execute("SELECT title, year FROM movie ORDER BY score DESC")
>>> title, year = res.fetchone()
>>> print(f'The highest scoring Monty Python movie is @{title!r@}, released in @{year@}')
The highest scoring Monty Python movie is 'Monty Python and the Holy Grail', released in 1975
>>> new_con.close()
@end example

これで、あなたは、 @code{sqlite3} モジュールを使用して SQLite データベースを作成し、複数の方法でデータを挿入し、そこから値を取得することができるようになりました。


@subsubheading 参考



@itemize *

@item 
@ref{2d60,,ハウツー・ガイド} も参考にしてください:


@itemize *

@item 
@ref{5b2,,プレースホルダを使用して SQL クエリに値を結び付ける方法}

@item 
@ref{2d69,,カスタム Python 型を SQLite 値に適合させる方法}

@item 
@ref{2d6a,,SQLite 値をカスタム Python 型に変換する方法}

@item 
@ref{1b6c,,接続(connection)コンテキストマネージャの使い方}

@item 
@ref{2d6b,,行工場(row factories)の作成方法と使用方法}
@end itemize

@item 
@ref{2d61,,トランザクション制御} トランザクション制御の背景についてより深く掘り下げた説明。
@end itemize


@node リファレンス,ハウツー・ガイド,チュートリアル,sqlite3 --- SQLite データベース用の DB-API 2 0 インターフェース
@anchor{library/sqlite3 reference}@anchor{2d6c}@anchor{library/sqlite3 sqlite3-reference}@anchor{2d5f}
@subsubsection リファレンス


@c We keep the old sqlite3-module-contents ref to prevent breaking links.
@anchor{library/sqlite3 sqlite3-module-contents}@anchor{2d6d}
@menu
* モジュール関数:: 
* モジュール定数:: 
* Connection オブジェクト:: 
* Cursor オブジェクト:: 
* Row オブジェクト:: 
* Blob オブジェクト:: 
* PrepareProtocol オブジェクト:: 
* 例外: 例外<7>. 
* SQLite と Python の型:: 
* デフォルトの適合関数(adapters)とデフォルトの変換関数(converters)(非推奨): デフォルトの適合関数 adapters とデフォルトの変換関数 converters 非推奨. 
* コマンドライン・インターフェース: コマンドライン・インターフェース<2>. 

@end menu

@node モジュール関数,モジュール定数,,リファレンス
@anchor{library/sqlite3 module-functions}@anchor{2d6e}@anchor{library/sqlite3 sqlite3-module-functions}@anchor{2d6f}
@subsubsection モジュール関数


@geindex connect() (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 connect}@anchor{5a6}
@deffn {の関数} sqlite3.connect (database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread=True, factory=sqlite3.Connection, cached_statements=128, uri=False, *, autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)

SQLite データベースとの接続(connection)を開きます。

@*パラメータ: 

@itemize *

@item 
@code{database} (@ref{5a1,,path-like object}) -- The path to the database file to be opened.
You can pass @code{":memory:"} to create an SQLite database existing only in memory@footnote{https://sqlite.org/inmemorydb.html}, and open a connection
to it.

@item 
@code{timeout} (@ref{196,,float}) -- テーブルがロックされている場合、 @ref{1c52,,OperationalError} を送出する前に接続を待機する秒数。 別の接続がテーブルを変更するためにトランザクションを開くと、そのテーブルはトランザクションがコミットされるまでロックされます。 デフォルトは 5 秒です。

@item 
@code{detect_types} (@ref{19b,,int}) -- Control whether and how data types not
@ref{2d70,,natively supported by SQLite}
are looked up to be converted to Python types,
using the converters registered with @ref{2d71,,register_converter()}.
Set it to any combination (using @code{|}, bitwise or) of
@ref{2d72,,PARSE_DECLTYPES} and @ref{2d73,,PARSE_COLNAMES}
to enable this.
Column names take precedence over declared types if both flags are set.
By default (@code{0}), type detection is disabled.

@item 
@code{isolation_level} (@ref{169,,str}@code{ | }@code{None}) -- Control legacy transaction handling behaviour.
See @ref{2d74,,Connection.isolation_level} and
@ref{2d75,,isolation_level 属性に依るトランザクション制御} for more information.
Can be @code{"DEFERRED"} (default), @code{"EXCLUSIVE"} or @code{"IMMEDIATE"};
or @code{None} to disable opening transactions implicitly.
Has no effect unless @ref{6dd,,Connection.autocommit} is set to
@ref{2d76,,LEGACY_TRANSACTION_CONTROL} (the default).

@item 
@code{check_same_thread} (@ref{3c3,,bool}) -- @code{True} (これがデフォルトです)なら、データベース接続を作成したスレッド以外のスレッドがデータベース接続を使用すると、 @ref{305,,ProgrammingError} が送出されます。 @code{False} なら、接続は複数のスレッドからアクセスできます。ただし、データの破損を避けるために、ユーザーによる書き込み操作の直列化が必要になることがあります。詳細は @ref{88c,,threadsafety}  を参照してください。

@item 
@code{factory} (@ref{54d,,Connection}) -- デフォルトの @ref{54d,,Connection} クラスでない場合に接続(connection)を作成する @ref{54d,,Connection} のカスタム・サブクラスです。

@item 
@code{cached_statements} (@ref{19b,,int}) -- @code{sqlite3} がこの接続(connection)のために内部的にキャッシュするSQL文(statements)の数で、 パース時のオーバーヘッドを回避します。 デフォルトでは、128 文(statements)です。

@item 
@code{uri} (@ref{3c3,,bool}) -- @code{True} に設定すると、 `database' は、ファイル・パス(path)とオプションのクエリ文字列を含む @abbr{URI,Uniform Resource Identifier} として解釈されます。 スキームの部分は @code{"file:"} でなければならず、パス(path)は相対パスまたは絶対パスにすることができます。 クエリ文字列により、 パラメーターを SQLite に渡すことができ、さまざまな @ref{2d77,,SQLite URI の操作方法} が有効になります。

@item 
@code{autocommit} (@ref{3c3,,bool}) -- Control 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} transaction handling behaviour.
See @ref{6dd,,Connection.autocommit} and
@ref{6de,,autocommit 属性に依るトランザクション制御} for more information.
`autocommit' currently defaults to
@ref{2d76,,LEGACY_TRANSACTION_CONTROL}.
The default will change to @code{False} in a future Python release.
@end itemize


@*戻り値の型: 
@ref{54d,,Connection}


引数 @code{database} を指定して @ref{1c6e,,監査イベント} @code{sqlite3.connect} を送出します。

引数 @code{connection_handle} を指定して @ref{1c6e,,監査イベント} @code{sqlite3.connect/handle} を送出します。


バージョン 3.4 で変更: @code{uri} パラメータが追加されました。



バージョン 3.7 で変更: `database' は、文字列だけでなく、 @ref{5a1,,path-like object} にすることもできるようになりました。



バージョン 3.10 で変更: Added the @code{sqlite3.connect/handle} auditing event.



バージョン 3.12 で変更: Added the `autocommit' parameter.



バージョン 3.13 で変更: Positional use of the parameters `timeout', `detect_types',
`isolation_level', `check_same_thread', `factory', `cached_statements',
and `uri' is deprecated.
They will become keyword-only parameters in Python 3.15.

@end deffn

@geindex complete_statement() (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 complete_statement}@anchor{2d78}
@deffn {の関数} sqlite3.complete_statement (statement)

文字列 `statement' が 1 つ以上の完全な SQL 文を含んでいるように見える場合、 @code{True} を返します。 閉じられていない文字列リテラルがないことと、文がセミコロンで終了していることを確認する以外の、構文の検証やパースは行われません。

例えば:

@example
>>> sqlite3.complete_statement("SELECT foo FROM bar;")
True
>>> sqlite3.complete_statement("SELECT foo")
False
@end example

この関数は、コマンドライン入力時に便利で、入力されたテキストが完全な SQL 文を形成しているように見えるかどうか、または @ref{5b0,,execute()} を呼び出す前に追加の入力が必要かどうかを判断するのに使えます。

実際の使用例については、 Lib/sqlite3/__main__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/sqlite3/__main__.py} の @code{runsource()} を参照してください。
@end deffn

@geindex enable_callback_tracebacks() (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 enable_callback_tracebacks}@anchor{2d79}
@deffn {の関数} sqlite3.enable_callback_tracebacks (flag, /)

コールバックのトレースバックを有効または無効にします。  デフォルトでは、ユーザー定義関数や集計関数や変換関数や authorizer コールバックなどではトレースバックを取得しません。それらをデバッグしたい場合は、 `flag' を @code{True} に設定してこの関数を呼び出し。その後、 @ref{b33,,sys.stderr} のコールバックからトレースバックを取得します。 機能を再び無効にするには @code{False} を使用します。

@cartouche
@quotation 注釈 
Errors in user-defined function callbacks are logged as unraisable exceptions.
Use an @ref{507,,unraisable hook handler} for
introspection of the failed callback.
@end quotation
@end cartouche
@end deffn

@geindex register_adapter() (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 register_adapter}@anchor{2d7a}
@deffn {の関数} sqlite3.register_adapter (type, adapter, /)

`adapter' @ref{2d7b,,呼び出し可能オブジェクト} を登録して、 Python 型の `type' を SQLite の型に適合させます。適合関数(adapter)アダプターは、 Python 型 `type' の Python オブジェクトを唯一の引数として使用して呼び出され、 @ref{2d70,,SQLite がネイティブに理解する型} の値を返す必要があります。
@end deffn

@geindex register_converter() (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 register_converter}@anchor{2d71}
@deffn {の関数} sqlite3.register_converter (typename, converter, /)

`converter' @ref{2d7b,,呼び出し可能オブジェクト} を登録して、 `typename' 型の SQLite オブジェクトを指定の型の Python オブジェクトに変換します。変換関数(converter)、 `typename' 型のすべての SQLite 値に対して呼び出されます。 変換関数には @ref{192,,bytes} オブジェクトが渡され、目的の Python 型のオブジェクトを返す必要があります。型検出の仕組みについては、 @ref{5a6,,connect()} のパラメーター `detect_types' を参照してください。

注釈: `typename' とクエリ内の型の名前は、大文字小文字を区別せずにマッチングされます。
@end deffn

@node モジュール定数,Connection オブジェクト,モジュール関数,リファレンス
@anchor{library/sqlite3 module-constants}@anchor{2d7c}@anchor{library/sqlite3 sqlite3-module-constants}@anchor{2d7d}
@subsubsection モジュール定数


@geindex LEGACY_TRANSACTION_CONTROL (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 LEGACY_TRANSACTION_CONTROL}@anchor{2d76}
@deffn {データ} sqlite3.LEGACY_TRANSACTION_CONTROL

古いスタイル (Python 3.12 より前) のトランザクション制御の振る舞いを選択するには、 @ref{6dd,,autocommit} に、この定数を設定します。詳細については @ref{2d75,,isolation_level 属性に依るトランザクション制御} を参照してください。
@end deffn

@geindex PARSE_DECLTYPES (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 PARSE_DECLTYPES}@anchor{2d72}
@deffn {データ} sqlite3.PARSE_DECLTYPES

このフラグ値を @ref{5a6,,connect()} の `detect_types' パラメーターに渡して、各列(column)で宣言した型を使用して変換関数を探します。型は、データベース・テーブルの作成時に宣言します。 @code{sqlite3} は、宣言された型の、最初の単語を、変換関数辞書(converter dictionary)のキーとして使用して、変換関数を探します。例えば:

@example
CREATE TABLE test(
   i integer primary key,  ! will look up a converter named "integer"
   p point,                ! will look up a converter named "point"
   n number(10)            ! will look up a converter named "number"
 )
@end example

このフラグは @code{|} (ビット論理和)演算子を使用して @ref{2d73,,PARSE_COLNAMES} と組み合わせることができます。

@cartouche
@quotation 注釈 
Generated fields (for example @code{MAX(p)}) are returned as @ref{169,,str}.
Use @code{PARSE_COLNAMES} to enforce types for such queries.
@end quotation
@end cartouche
@end deffn

@geindex PARSE_COLNAMES (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 PARSE_COLNAMES}@anchor{2d73}
@deffn {データ} sqlite3.PARSE_COLNAMES

Pass this flag value to the `detect_types' parameter of
@ref{5a6,,connect()} to look up a converter function by
using the type name, parsed from the query column name,
as the converter dictionary key.
The query column name must be wrapped in double quotes (@code{"})
and the type name must be wrapped in square brackets (@code{[]}).

@example
SELECT MAX(p) as "p [point]" FROM test;  ! will look up converter "point"
@end example

このフラグは @code{|} (ビット論理和)演算子を使用して @ref{2d72,,PARSE_DECLTYPES} と組み合わせることができます。
@end deffn

@geindex SQLITE_OK (sqlite3 モジュール)
@geindex SQLITE_DENY (sqlite3 モジュール)
@geindex SQLITE_IGNORE (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 SQLITE_OK}@anchor{2d7e}
@deffn {データ} sqlite3.SQLITE_OK
@anchor{library/sqlite3 sqlite3 SQLITE_DENY}@anchor{2d7f}
@deffnx {データ} sqlite3.SQLITE_DENY
@anchor{library/sqlite3 sqlite3 SQLITE_IGNORE}@anchor{2d80}
@deffnx {データ} sqlite3.SQLITE_IGNORE

@ref{5a9,,Connection.set_authorizer()} に渡す @ref{2d7b,,呼び出し可能オブジェクト} が返す必要のあるフラグ。これらは以下の意味です:


@itemize *

@item 
アクセスは許可されました(@code{SQLITE_OK})

@item 
当該SQL文全体の実行をエラーで中止(abort)する必要があります(@code{SQLITE_DENY})

@item 
列(column)は @code{NULL} 値として扱う必要がありますが、当該SQL文の実行は続行する必要があります(@code{SQLITE_IGNORE})
@end itemize
@end deffn

@geindex apilevel (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 apilevel}@anchor{2d81}
@deffn {データ} sqlite3.apilevel

サポートされている DB-API レベルを示す文字列定数。 DB-API で必要です。 @code{"2.0"} とハードコーディングされています。
@end deffn

@geindex paramstyle (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 paramstyle}@anchor{2d82}
@deffn {データ} sqlite3.paramstyle

@code{sqlite3} モジュールが期待するパラメータ・マーカーのフォーマットの種類をあらわす文字列定数です。 DB-API で必要です。 @code{"qmark"} とハードコーディングされています。

@cartouche
@quotation 注釈 
@code{named} DB-API パラメータ・スタイルもサポートされています。
@end quotation
@end cartouche
@end deffn

@geindex sqlite_version (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 sqlite_version}@anchor{303}
@deffn {データ} sqlite3.sqlite_version

@ref{169,,文字列} としての、ランタイム SQLite ライブラリのバージョン番号。
@end deffn

@geindex sqlite_version_info (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 sqlite_version_info}@anchor{304}
@deffn {データ} sqlite3.sqlite_version_info

@ref{19b,,整数} の @ref{614,,タプル} としての、ランタイム SQLite ライブラリのバージョン番号。
@end deffn

@geindex threadsafety (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3 threadsafety}@anchor{88c}
@deffn {データ} sqlite3.threadsafety

@code{sqlite3} モジュールがサポートするスレッドセーフのレベルを示す、DB-API 2.0 で必要な整数定数。 この属性は、背後の SQLite ライブラリのコンパイル時のデフォルトの SQLite スレッド・モード (threading mode@footnote{https://sqlite.org/threadsafe.html})に基づいて設定されます。 SQLite のスレッド・モードは以下のとおりです:


@enumerate 

@item 
`シングル・スレッド': このモードでは、すべてのミューテックスが無効になり、一度に複数のスレッドで SQLite を使用するのは安全ではありません。

@item 
`マルチ・スレッド': このモードでは、 1 つのデータベース接続が 2 つ以上のスレッドで同時に使用されない限り、複数のスレッドで SQLite を安全に使用できます。

@item 
`直列化': 直列化(serialized)モードでは、 SQLite を複数のスレッドで制限なく安全に使用できます。
@end enumerate

SQLite スレッド・モードと、 DB-API 2.0 のスレッドセーフ・レベルとの対応は以下のとおりです:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

SQLite スレッド・モード

@tab

@geindex Python Enhancement Proposals; PEP 0249#threadsafety
threadsafety@footnote{https://peps.python.org/pep-0249/#threadsafety}

@tab

SQLITE_THREADSAFE@footnote{https://sqlite.org/compile.html#threadsafe}

@tab

DB-API 2.0 での意味

@item

シングル・スレッド

@tab

0

@tab

0

@tab

スレッドはモジュールを共有できません

@item

マルチ・スレッド

@tab

1

@tab

2

@tab

スレッドはモジュールを共有できますが、接続は共有できません

@item

直列化

@tab

3

@tab

1

@tab

スレッドは、モジュールや接続やカーソルを共有できます

@end multitable



バージョン 3.11 で変更: @code{1} とハード・コーディングする代わりに `threadsafety' を動的に設定します。

@end deffn

@geindex SQLITE_DBCONFIG_DEFENSIVE (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_DQS_DDL (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_DQS_DML (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_ENABLE_FKEY (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_ENABLE_QPSG (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_ENABLE_TRIGGER (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_ENABLE_VIEW (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_LEGACY_ALTER_TABLE (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_LEGACY_FILE_FORMAT (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_RESET_DATABASE (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_TRIGGER_EQP (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_TRUSTED_SCHEMA (sqlite3 モジュール)
@geindex SQLITE_DBCONFIG_WRITABLE_SCHEMA (sqlite3 モジュール)
@anchor{library/sqlite3 sqlite3-dbconfig-constants}@anchor{2d83}@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_DEFENSIVE}@anchor{2d84}
@deffn {データ} sqlite3.SQLITE_DBCONFIG_DEFENSIVE
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_DQS_DDL}@anchor{2d85}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_DQS_DDL
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_DQS_DML}@anchor{2d86}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_DQS_DML
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_ENABLE_FKEY}@anchor{2d87}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_ENABLE_FKEY
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER}@anchor{2d88}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION}@anchor{2d89}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_ENABLE_QPSG}@anchor{2d8a}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_ENABLE_QPSG
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_ENABLE_TRIGGER}@anchor{2d8b}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_ENABLE_TRIGGER
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_ENABLE_VIEW}@anchor{2d8c}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_ENABLE_VIEW
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_LEGACY_ALTER_TABLE}@anchor{2d8d}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_LEGACY_FILE_FORMAT}@anchor{2d8e}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE}@anchor{2d8f}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_RESET_DATABASE}@anchor{2d90}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_RESET_DATABASE
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_TRIGGER_EQP}@anchor{2d91}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_TRIGGER_EQP
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_TRUSTED_SCHEMA}@anchor{2d92}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_TRUSTED_SCHEMA
@anchor{library/sqlite3 sqlite3 SQLITE_DBCONFIG_WRITABLE_SCHEMA}@anchor{2d93}
@deffnx {データ} sqlite3.SQLITE_DBCONFIG_WRITABLE_SCHEMA

これらの定数は、 @ref{6e1,,Connection.setconfig()} メソッド や @ref{6e0,,getconfig()} メソッドで使用されます。

これらの定数が利用できるかどうかは、 Python にコンパイルされた SQLite のバージョンによって異なります。


Added in version 3.12.



@subsubheading 参考



@table @asis

@item @indicateurl{https://www.sqlite.org/c3ref/c_dbconfig_defensive.html}

SQLite docs: Database Connection Configuration Options
@end table

@end deffn


Deprecated since version 3.12, removed in version 3.14: The @code{version} and @code{version_info} constants.


@node Connection オブジェクト,Cursor オブジェクト,モジュール定数,リファレンス
@anchor{library/sqlite3 connection-objects}@anchor{2d94}@anchor{library/sqlite3 sqlite3-connection-objects}@anchor{2d95}
@subsubsection Connection オブジェクト


@geindex Connection (sqlite3 のクラス)
@anchor{library/sqlite3 sqlite3 Connection}@anchor{54d}
@deffn {クラス} sqlite3.Connection

開いた SQLite データベースの各々は、 @ref{5a6,,sqlite3.connect()} を使用して作成される @code{Connection} オブジェクトによって表されます。@code{Connection} オブジェクトの主な目的は @ref{2d64,,Cursor} オブジェクトの作成と @ref{2d66,,トランザクション制御} です。


@subsubheading 参考



@itemize *

@item 
@ref{2d96,,接続(connection)ショートカット・メソッドの使い方}

@item 
@ref{1b6c,,接続(connection)コンテキストマネージャの使い方}
@end itemize



バージョン 3.13 で変更: A @ref{54c,,ResourceWarning} is emitted if @ref{54e,,close()} is not called before
a @code{Connection} object is deleted.


SQLite データベース接続(connection)には、以下の属性とメソッドがあります:

@geindex cursor() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection cursor}@anchor{2d63}
@deffn {メソッド} cursor (factory=Cursor)

@ref{2d64,,Cursor} オブジェクトを作成して返します。 cursor メソッドは、単一のオプション・パラメーター `factory' を受け入れます。 `factory' を指定する場合、これは @ref{2d64,,Cursor} またはそのサブクラスのインスタンスを返す @ref{2d7b,,呼び出し可能オブジェクト} である必要があります。
@end deffn

@geindex blobopen() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection blobopen}@anchor{891}
@deffn {メソッド} blobopen (table, column, rowid, /, *, readonly=False, name='main')

既存の @abbr{BLOB,Binary Large OBject} への @ref{892,,Blob} ハンドルを開きます。

@*パラメータ: 

@itemize *

@item 
@code{table} (@ref{169,,str}) -- 当該 BLOB が配置されているテーブルの名前。

@item 
@code{column} (@ref{169,,str}) -- 当該 BLOB が配置されている列(column)の名前。

@item 
@code{rowid} (@ref{19b,,int}) -- The row id where the blob is located.

@item 
@code{readonly} (@ref{3c3,,bool}) -- 書き込み権限なしで BLOB を開く必要がある場合は、 @code{True} に設定します。 デフォルトは @code{False} です。

@item 
@code{name} (@ref{169,,str}) -- 当該 BLOB が配置されているデータベース名。 デフォルトは @code{"main"} です。
@end itemize


@*例外: 
@ref{1c52,,OperationalError} -- @code{WITHOUT ROWID} テーブルで BLOB を開こうとしたとき。


@*戻り値の型: 
@ref{892,,Blob}


@cartouche
@quotation 注釈 
@ref{892,,Blob} クラスを使用して BLOB のサイズを変更することはできません。 SQL 関数 @code{zeroblob} を使用すると、固定サイズのブロブを作成します。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex commit() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection commit}@anchor{2d67}
@deffn {メソッド} commit ()

保留中のトランザクションをデータベースにコミットします。  @ref{6dd,,autocommit} が @code{True} または開いているトランザクションがない場合、このメソッドは何も行いません。 @code{autocommit} が @code{False} の場合に保留中のトランザクションがこのメソッドによってコミットされた場合、新しいトランザクションが暗黙に開かれます。
@end deffn

@geindex rollback() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection rollback}@anchor{2d97}
@deffn {メソッド} rollback ()

保留中のトランザクションの先頭にロールバックします。 @ref{6dd,,autocommit} が @code{True} または開いているトランザクションがない場合、このメソッドは何も行いません。 @code{autocommit} が @code{False} の場合に保留中のトランザクションがこのメソッドによってロールバックされた場合、新しいトランザクションが暗黙に開かれます。
@end deffn

@geindex close() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection close}@anchor{54e}
@deffn {メソッド} close ()

データベース接続を閉じます。 @ref{6dd,,autocommit} が @code{False} の場合、保留中のトランザクションは暗黙にロールバックされます。 @code{autocommit} が @code{True} または @ref{2d76,,LEGACY_TRANSACTION_CONTROL} の場合、暗黙のトランザクション制御は実行されませんので、保留中の変更が失われないように、データベース接続を閉じる前に必ず @ref{2d67,,commit()} を行ってください。
@end deffn

@geindex execute() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection execute}@anchor{2d98}
@deffn {メソッド} execute (sql, parameters=(), /)

新しい @ref{2d64,,Cursor} オブジェクトを作成し、指定の `sql' と `parameters' で @ref{5b0,,execute()} を呼び出します。新しいカーソル・オブジェクトを返します。
@end deffn

@geindex executemany() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection executemany}@anchor{2d99}
@deffn {メソッド} executemany (sql, parameters, /)

新しい @ref{2d64,,Cursor} オブジェクトを作成し、与えられた `sql' と `parameters' で @ref{5b1,,executemany()} を呼び出します。新しいカーソル・オブジェクトを返します。
@end deffn

@geindex executescript() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection executescript}@anchor{2d9a}
@deffn {メソッド} executescript (sql_script, /)

新しい @ref{2d64,,Cursor} オブジェクトを作成し、指定された `sql_script' で @ref{2d9b,,executescript()} を呼び出します。新しいカーソル・オブジェクトを返します。
@end deffn

@geindex create_function() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection create_function}@anchor{5a7}
@deffn {メソッド} create_function (name, narg, func, *, deterministic=False)

ユーザ定義 SQL 関数を作成または削除します。

@*パラメータ: 

@itemize *

@item 
@code{name} (@ref{169,,str}) -- SQL 関数の名前。

@item 
@code{narg} (@ref{19b,,int}) -- SQL 関数が受け入れることができる引数の数。 @code{-1} を指定すると、任意の数の引数を取ることができます。

@item 
@code{func} (@ref{2d9c,,callback} | None) -- この SQL 関数が呼び出されたときに起動される @ref{2d7b,,呼び出し可能オブジェクト} 。 この呼び出し可能オブジェクトは、 @ref{2d70,,SQLite によってネイティブにサポートされる型} を返すす必要があります。 既存の SQL 関数を削除するには、 @code{None} に設定します。

@item 
@code{deterministic} (@ref{3c3,,bool}) -- @code{True} の場合、作成された SQL 関数は決定論的(deterministic@footnote{https://sqlite.org/deterministic.html} : 入力が同一なら常に同一の答えを返す)としてマークされ、SQLite が追加の最適化を実行できるようになります。
@end itemize



バージョン 3.8 で変更: Added the `deterministic' parameter.


例:

@example
>>> import hashlib
>>> def md5sum(t):
...     return hashlib.md5(t).hexdigest()
>>> con = sqlite3.connect(":memory:")
>>> con.create_function("md5", 1, md5sum)
>>> for row in con.execute("SELECT md5(?)", (b"foo",)):
...     print(row)
('acbd18db4cc2f85cedef654fccc4a4d8',)
>>> con.close()
@end example


バージョン 3.13 で変更: Passing `name', `narg', and `func' as keyword arguments is deprecated.
These parameters will become positional-only in Python 3.15.

@end deffn

@geindex create_aggregate() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection create_aggregate}@anchor{5a8}
@deffn {メソッド} create_aggregate (name, n_arg, aggregate_class)

ユーザ定義集計関数を作成または削除します。

@*パラメータ: 

@itemize *

@item 
@code{name} (@ref{169,,str}) -- SQL 集計関数の名前。

@item 
@code{n_arg} (@ref{19b,,int}) -- SQL 集計関数が受け入れることができる引数の数。 @code{-1} を指定すると、任意の数の引数を取ることができます。

@item 
@code{aggregate_class} (@ref{1cfd,,class} | None) -- 
クラスは以下のメソッドを実装する必要があります:


@itemize *

@item 
@code{step()}: 集計に行(row)を足し込みます。

@item 
@code{finalize()}: 集計の最終結果を @ref{2d70,,SQLite でネイティブにサポートされている型} として返します。
@end itemize

@code{step()} メソッドが受け入れなければならない引数の数は `n_arg' によって制御されます。

既存の SQL 集計関数を削除するには、 @code{None} に設定します。

@end itemize


例:

@example
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.execute("CREATE TABLE test(i)")
cur.execute("INSERT INTO test(i) VALUES(1)")
cur.execute("INSERT INTO test(i) VALUES(2)")
cur.execute("SELECT mysum(i) FROM test")
print(cur.fetchone()[0])

con.close()
@end example

@c 3


バージョン 3.13 で変更: Passing `name', `n_arg', and `aggregate_class' as keyword arguments is deprecated.
These parameters will become positional-only in Python 3.15.

@end deffn

@geindex create_window_function() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection create_window_function}@anchor{890}
@deffn {メソッド} create_window_function (name, num_params, aggregate_class, /)

ユーザー定義の集計ウインドウ関数を作成または削除します。

@*パラメータ: 

@itemize *

@item 
@code{name} (@ref{169,,str}) -- 作成または削除する SQL 集計ウインドウ関数の名前。

@item 
@code{num_params} (@ref{19b,,int}) -- SQL 集計ウィンドウ関数が受け入れることができる引数の数。 @code{-1} を指定した場合、任意の数の引数を取ることができます。

@item 
@code{aggregate_class} (@ref{1cfd,,class} | None) -- 
クラスは以下のメソッドを実装する必要があります:


@itemize *

@item 
@code{step()}: 現在のウィンドウに行を足し込みます。

@item 
@code{value()}: 集計の現在の値を返します。

@item 
@code{inverse()}: 現在のウインドウから指定の行(row)の分を削除します。

@item 
@code{finalize()}: 集計の最終結果を @ref{2d70,,SQLite でネイティブにサポートされている型} として返します。
@end itemize

@code{step()} メソッドと @code{value()} メソッドが受け入れなければならない引数の数は `num_params' によって制御されます。

@code{None} に設定すると、既存の SQL 集計ウィンドウ関数が削除されます。

@end itemize


@*例外: 
@ref{2d9d,,NotSupportedError} -- 集計ウィンドウ関数をサポートしていない 3.25.0 より古いバージョンの SQLite で使用した場合に送出されます。



Added in version 3.11.


例:

@example
# Example taken from https://www.sqlite.org/windowfunctions.html#udfwinfunc
class WindowSumInt:
    def __init__(self):
        self.count = 0

    def step(self, value):
        """Add a row to the current window."""
        self.count += value

    def value(self):
        """Return the current value of the aggregate."""
        return self.count

    def inverse(self, value):
        """Remove a row from the current window."""
        self.count -= value

    def finalize(self):
        """Return the final value of the aggregate.

        Any clean-up actions should be placed here.
        """
        return self.count


con = sqlite3.connect(":memory:")
cur = con.execute("CREATE TABLE test(x, y)")
values = [
    ("a", 4),
    ("b", 5),
    ("c", 3),
    ("d", 8),
    ("e", 1),
]
cur.executemany("INSERT INTO test VALUES(?, ?)", values)
con.create_window_function("sumint", 1, WindowSumInt)
cur.execute("""
    SELECT x, sumint(y) OVER (
        ORDER BY x ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
    ) AS sum_y
    FROM test ORDER BY x
""")
print(cur.fetchall())
con.close()
@end example

@c [('a', 9), ('b', 12), ('c', 16), ('d', 12), ('e', 9)]
@end deffn

@geindex create_collation() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection create_collation}@anchor{886}
@deffn {メソッド} create_collation (name, callable, /)

照合関数(collating function) `callable' を使用して `name' という名前の照合(collation)を作成します。 `callable' には 2 つの @ref{169,,文字列} 引数が渡され、@ref{19b,,整数} を返す必要があります:


@itemize *

@item 
1 番目の文字列が 2 番目の文字列よりも高い順位ならば @code{1} を返す

@item 
1 番目の文字列が 2 番目の文字列よりも低い順位ならば @code{-1}  を返す

@item 
1 番目の文字列と 2 番目の文字列が同じ順位ならば @code{0}  を返す
@end itemize

以下は逆順での照合例です:

@example
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.execute("CREATE TABLE test(x)")
cur.executemany("INSERT INTO test(x) VALUES(?)", [("a",), ("b",)])
cur.execute("SELECT x FROM test ORDER BY x COLLATE reverse")
for row in cur:
    print(row)
con.close()
@end example

@c ('b',)
@c ('a',)

照合関数を削除するには `callable' を @code{None} に設定します。


バージョン 3.11 で変更: 照合の名前には任意のユニコード文字を含めることができます。 以前は ASCII 文字のみが許可されていました。

@end deffn

@geindex interrupt() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection interrupt}@anchor{2d9e}
@deffn {メソッド} interrupt ()

このメソッドを別のスレッドから呼び出して、この接続(connection)で、実行中のすべてのクエリを中止(abort)させます。 中止(abort)させられたクエリは @ref{1c52,,OperationalError} を送出します。
@end deffn

@geindex set_authorizer() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection set_authorizer}@anchor{5a9}
@deffn {メソッド} set_authorizer (authorizer_callback)

データベース内のテーブルの列(column)にアクセスしようとするたびに起動される @ref{2d7b,,呼び出し可能オブジェクト} `authorizer_callback' を登録します。 このコールバックは背後の SQLite ライブラリによって列(column)へのアクセスがどのように処理されるかを通知するために、 @ref{2d7e,,SQLITE_OK} または @ref{2d7f,,SQLITE_DENY} または @ref{2d80,,SQLITE_IGNORE} のいずれかを返さなければなりません。

コールバックの最初の引数は、承認(authorize)される操作の種類を示します。 2 番目と 3 番目の引数は、最初の引数に応じて、引数または @code{None} になります。 4 番目の引数は、該当する場合、データベースの名前("main" や "temp" 等)です。 5 番目の引数は、 アクセス試行を担当する最も内側のトリガーまたはビューの名前です。このアクセス試行が入力 SQL コードから直接行われた場合は @code{None} です。

最初の引数に指定可能な値と、 最初の引数に応じた 2 番目と 3 番目の引数の意味については、 SQLite のドキュメントを参照してください。 必要なすべての定数は @code{sqlite3} モジュールで利用できます。

`authorizer_callback' として @code{None} を渡すと、承認機構(authorizer)が無効になります。


バージョン 3.11 で変更: @code{None} を使用して承認機構(authorizer)を無効にするサポートが追加されました。



バージョン 3.13 で変更: Passing `authorizer_callback' as a keyword argument is deprecated.
The parameter will become positional-only in Python 3.15.

@end deffn

@geindex set_progress_handler() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection set_progress_handler}@anchor{5aa}
@deffn {メソッド} set_progress_handler (progress_handler, n)

SQLite 仮想マシンの命令を `n' 個実行するごとに呼び出されるように、 @ref{2d7b,,呼び出し可能オブジェクト} `progress_handler' を登録します。これは、 GUI の更新など、長時間実行される操作中に SQLite から呼び出されるようにしたい場合に便利です。

以前にインストールした progress ハンドラーをクリアしたい場合は、 `progress_handler' に @code{None} を指定してメソッドを呼び出します。

ハンドラー関数からゼロ以外の値を返すと、現在実行中のクエリを終了(terminate)し、 @ref{2d9f,,DatabaseError} 例外を送出します。


バージョン 3.13 で変更: Passing `progress_handler' as a keyword argument is deprecated.
The parameter will become positional-only in Python 3.15.

@end deffn

@geindex set_trace_callback() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection set_trace_callback}@anchor{5ab}
@deffn {メソッド} set_trace_callback (trace_callback)

SQLite バックエンドによって実際に実行される SQL 文ごとに起動される @ref{2d7b,,呼び出し可能オブジェクト} `trace_callback' を登録します。

コールバックに渡される唯一の引数は、(@ref{169,,str} として渡される)実行中のSQL文です。 コールバックの戻り値は無視されます。 バックエンドは、 @ref{5b0,,Cursor.execute()} メソッドに渡されたSQL文を実行するだけではないことに注意してください。 @code{sqlite3} モジュールの @ref{2d66,,トランザクション管理} や、現在のデータベース内で定義されたトリガーの実行その他も行います。

`trace_callback' として @code{None} を渡すと、トレース・コールバックが無効になります。

@cartouche
@quotation 注釈 
トレース・コールバックで送出した例外は伝播されません。 開発およびデバッグの補助として、 @ref{2d79,,enable_callback_tracebacks()} を使用して、トレース・コールバックで送出した例外からのトレースバックの出力を有効にします。
@end quotation
@end cartouche


Added in version 3.3.



バージョン 3.13 で変更: Passing `trace_callback' as a keyword argument is deprecated.
The parameter will become positional-only in Python 3.15.

@end deffn

@geindex enable_load_extension() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection enable_load_extension}@anchor{a3f}
@deffn {メソッド} enable_load_extension (enabled, /)

`enabled' が @code{True} の場合、 SQLite エンジンが共有ライブラリから SQLite 拡張機能をロードできるようにします。 @code{True} 以外の場合は、 SQLite 拡張機能の読み込みを許可しません。 SQLite 拡張機能では、新しい関数の定義、または集計の定義、またはまったく新しい仮想テーブルの実装を定義できます。 よく知られている拡張機能の 1 つは、SQLite と共に配布される全文検索拡張機能です。

@cartouche
@quotation 注釈 
@code{sqlite3} モジュールは、デフォルトではロード可能な拡張機能をサポートするようにビルドされていません。一部のプラットフォーム(特に macOS)には、この機能なしでコンパイルされた SQLite ライブラリがあるためです。 ロード可能な拡張機能のサポートを得るには、 @code{configure} に @ref{2162,,--enable-loadable-sqlite-extensions} オプションを渡す必要があります。
@end quotation
@end cartouche

引数 @code{connection}, @code{enabled} を指定して @ref{1c6e,,監査イベント} @code{sqlite3.enable_load_extension} を送出します。


Added in version 3.2.



バージョン 3.10 で変更: @code{sqlite3.enable_load_extension} 監査イベントを追加しました。


@c We cannot doctest the load extension API, since there is no convenient
@c way to skip it.

@example
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)
@end example
@end deffn

@geindex load_extension() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection load_extension}@anchor{6df}
@deffn {メソッド} load_extension (path, /, *, entrypoint=None)

共有ライブラリから SQLite 拡張機能(extension)をロードします。このメソッドを呼び出す前に @ref{a3f,,enable_load_extension()} で拡張機能の読み込みを有効にしてください。

@*パラメータ: 

@itemize *

@item 
@code{path} (@ref{169,,str}) -- SQLite 拡張機能(extension)へのパス(path)。

@item 
@code{entrypoint} (@ref{169,,str}@code{ | }@code{None}) -- エントリ・ポイント名。 @code{None} (デフォルト) の場合、 SQLite は自分自身でエントリ・ポイント名を推測します。 詳細については、SQLite ドキュメント Loading an Extension@footnote{https://www.sqlite.org/loadext.html#loading_an_extension} を参照してください。
@end itemize


引数 @code{connection}, @code{path} を指定して @ref{1c6e,,監査イベント} @code{sqlite3.load_extension} を送出します。


Added in version 3.2.



バージョン 3.10 で変更: @code{sqlite3.load_extension} 監査イベントを追加しました。



バージョン 3.12 で変更: Added the `entrypoint' parameter.

@end deffn

@geindex iterdump() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection iterdump}@anchor{54f}
@deffn {メソッド} iterdump (*, filter=None)

データベースを SQL ソース・コードとしてダンプする @ref{4c8,,iterator} を返します。 後で復元するためにメモリ内データベースを保存する場合に便利です。 @code{sqlite3} シェルの @code{.dump} コマンドに似ています。

@*パラメータ: 
@code{filter} (@ref{169,,str}@code{ | }@code{None}) -- An optional @code{LIKE} pattern for database objects to dump, e.g. @code{prefix_%}.
If @code{None} (the default), all database objects will be included.


例:

@example
# Convert file example.db to SQL dump file dump.sql
con = sqlite3.connect('example.db')
with open('dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%s\n' % line)
con.close()
@end example


@subsubheading 参考


@ref{2da0,,How to handle non-UTF-8 text encodings}



バージョン 3.13 で変更: `filter' パラメータが追加されました。

@end deffn

@geindex backup() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection backup}@anchor{d73}
@deffn {メソッド} backup (target, *, pages=-1, progress=None, name='main', sleep=0.250)

SQLite データベースのバックアップを作成します。

データベースが他のクライアントによってアクセスされている場合、または同一の接続によって並行にアクセスされている場合でも機能します。

@*パラメータ: 

@itemize *

@item 
@code{target} (@ref{54d,,Connection}) -- バックアップ先のデータベース接続(connection)。

@item 
@code{pages} (@ref{19b,,int}) -- 一度にコピーするページ数。 @code{0} 以下の場合、データベース全体がワンステップでコピーされます。 デフォルトは @code{-1} です。

@item 
@code{progress} (@ref{2d9c,,callback} | None) -- @ref{2d7b,,呼び出し可能オブジェクト} を設定すると、バックアップの指定ページ数単位の反復ごとに 3 つの整数引数で呼び出されます。 `status' は、最後の反復時のステータスで、 `remaining' はまだコピーされていない残りのページ数で、 `total' はコピーされるページの合計です。 デフォルトは @code{None} です。

@item 
@code{name} (@ref{169,,str}) -- バックアップするデータベース名。 @code{"main"} (メイン・データベース。これがデフォルトです)、または @code{"temp"} (一時データベース)、 または @code{ATTACH DATABASE} SQL文を使用して取り付けられたカスタム・データベース名の、いずれかです。

@item 
@code{sleep} (@ref{196,,float}) -- バックアップの指定ページ数単位の反復ごとにスリープする秒数。
@end itemize


例 1. 既存のデータベースを別のデータベースにコピーします:

@example
def progress(status, remaining, total):
    print(f'Copied @{total-remaining@} of @{total@} pages...')

src = sqlite3.connect('example.db')
dst = sqlite3.connect('backup.db')
with dst:
    src.backup(dst, pages=1, progress=progress)
dst.close()
src.close()
@end example

@c Copied 0 of 0 pages...

例 2. 既存のデータベースを臨時コピー(transient copy)にコピーします。

@example
src = sqlite3.connect('example.db')
dst = sqlite3.connect(':memory:')
src.backup(dst)
dst.close()
src.close()
@end example


Added in version 3.7.



@subsubheading 参考


@ref{2da0,,How to handle non-UTF-8 text encodings}

@end deffn

@geindex getlimit() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection getlimit}@anchor{88b}
@deffn {メソッド} getlimit (category, /)

接続(connection)の実行時制限を取得します。

@*パラメータ: 
@code{category} (@ref{19b,,int}) -- 問い合わせを行う実行時制限カテゴリー(SQLite limit category@footnote{https://www.sqlite.org/c3ref/c_limit_attached.html})。


@*戻り値の型: 
@ref{19b,,int}


@*例外: 
@ref{305,,ProgrammingError} -- `category' に、 背後の SQLite ライブラリが認識できないカテゴリーを指定した場合に送出されます。


例: @ref{54d,,Connection} の @code{con} の SQL 文の最大長を照会します (デフォルトは 1000000000 です):

@c import sqlite3
@c con = sqlite3.connect(":memory:")
@c con.setlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH, 1_000_000_000)
@c con.setlimit(sqlite3.SQLITE_LIMIT_ATTACHED, 10)

@example
>>> con.getlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH)
1000000000
@end example


Added in version 3.11.

@end deffn

@geindex setlimit() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection setlimit}@anchor{88a}
@deffn {メソッド} setlimit (category, limit, /)

接続の実行時制限を設定します。 コンパイル時上限を超えて制限を増やそうとすると、 暗黙のうちにコンパイル時上限に切り捨てられます。 制限が変更されたかどうかに関係なく、 制限の以前の値が返されます。

@*パラメータ: 

@itemize *

@item 
@code{category} (@ref{19b,,int}) -- SQLite limit category@footnote{https://www.sqlite.org/c3ref/c_limit_attached.html} を設定する。

@item 
@code{limit} (@ref{19b,,int}) -- 新しい制限の値。 負数の場合、 現在の制限は変更されません。
@end itemize


@*戻り値の型: 
@ref{19b,,int}


@*例外: 
@ref{305,,ProgrammingError} -- `category' に、 背後の SQLite ライブラリが認識できないカテゴリーを指定した場合に送出されます。


@ref{54d,,Connection} の @code{con} に対して、取り付けられるデータベース(attached databases)の数を 1 に制限します (デフォルトの制限は 10 です):

@example
>>> con.setlimit(sqlite3.SQLITE_LIMIT_ATTACHED, 1)
10
>>> con.getlimit(sqlite3.SQLITE_LIMIT_ATTACHED)
1
@end example

@c con.close()


Added in version 3.11.

@end deffn

@geindex getconfig() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection getconfig}@anchor{6e0}
@deffn {メソッド} getconfig (op, /)

ブール値の接続構成オプションを問い合わせます。

@*パラメータ: 
@code{op} (@ref{19b,,int}) -- @ref{2d83,,SQLITE_DBCONFIG code} を指定します。


@*戻り値の型: 
@ref{3c3,,bool}



Added in version 3.12.

@end deffn

@geindex setconfig() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection setconfig}@anchor{6e1}
@deffn {メソッド} setconfig (op, enable=True, /)

ブール値の接続構成オプションを設定します。

@*パラメータ: 

@itemize *

@item 
@code{op} (@ref{19b,,int}) -- @ref{2d83,,SQLITE_DBCONFIG code} を指定します。

@item 
@code{enable} (@ref{3c3,,bool}) -- 設定オプションを有効にする必要がある場合は @code{True} (デフォルト)。 無効にする場合は @code{False} を指定します。
@end itemize



Added in version 3.12.

@end deffn

@geindex serialize() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection serialize}@anchor{88e}
@deffn {メソッド} serialize (*, name='main')

データベースを @ref{192,,bytes} オブジェクトに直列化(serialize)します。 通常のディスク上のデータベース・ファイルの場合、 直列化はディスク・ファイルの単なるコピーです。 インメモリ・データベースまたは "temp" データベースの場合、 直列化は、 そのデータベースがディスクにバックアップされた場合にディスクに書き込まれるバイト・シーケンスと同じです。

@*パラメータ: 
@code{name} (@ref{169,,str}) -- 直列化するデータベース名。 デフォルトは @code{"main"} です。


@*戻り値の型: 
@ref{192,,bytes}


@cartouche
@quotation 注釈 
このメソッドは、 背後の SQLite ライブラリに直列化 API がある場合にのみ使用できます。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex deserialize() (sqlite3.Connection のメソッド)
@anchor{library/sqlite3 sqlite3 Connection deserialize}@anchor{88f}
@deffn {メソッド} deserialize (data, /, *, name='main')

@ref{88e,,直列化} されたデータベースを @ref{54d,,Connection} に、 脱直列化(deserialize)します。 このメソッドにより、 データベース接続はデータベース `name' から切断され、そして、  `data' に含まれる直列化データに基づいて、 データベース `name' がインメモリ・データベースとして再度開かれます。

@*パラメータ: 

@itemize *

@item 
@code{data} (@ref{192,,bytes}) -- 直列化されたデータベース。

@item 
@code{name} (@ref{169,,str}) -- 脱直列化(deserialize)したデータを入れるデータベース名。 デフォルトは @code{"main"} です。
@end itemize


@*例外: 

@itemize *

@item 
@ref{1c52,,OperationalError} -- データベース接続が読み取りトランザクションやバックアップ操作中の場合。

@item 
@ref{2d9f,,DatabaseError} -- `data' に有効な SQLite データベースが含まれていない場合。

@item 
@ref{a81,,OverflowError} -- @ref{840,,len(data)} が @code{2**63 - 1} より大きい場合。
@end itemize


@cartouche
@quotation 注釈 
このメソッドは、 背後の SQLite ライブラリに脱直列化 API がある場合にのみ使用できます。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex autocommit (sqlite3.Connection の属性)
@anchor{library/sqlite3 sqlite3 Connection autocommit}@anchor{6dd}
@deffn {の属性} autocommit

この属性は、 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} 対応のトランザクションの振る舞いを制御します。 @code{auto​​commit} には以下の 3 つの値が指定できます:


@itemize *

@item 
@code{False}: 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} 対応のトランザクションの振る舞いを選びます。 これは、 @code{sqlite3} が、 トランザクションが常に開いていることを保証することを意味します。トランザクションを閉じるには、 @ref{2d67,,commit()} や @ref{2d97,,rollback()} を使用します。

これが @code{auto​​commit} の推奨値です。

@item 
@code{True}: SQLite の autocommit mode@footnote{https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions} を使用します。このモードでは @ref{2d67,,commit()} や @ref{2d97,,rollback()} は効果がありません。

@item 
@ref{2d76,,LEGACY_TRANSACTION_CONTROL}: Python 3.12 より前(
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} 非対応)のトランザクション制御。 詳細については @ref{2d74,,isolation_level} を参照してください。

これが、今のところは、 @code{auto​​commit} のデフォルト値です。
@end itemize

@code{auto​​commit} を @code{False} に変更すると新しいトランザクションが開き、 @code{True} に変更すると保留中のトランザクションがコミットされます。

詳細は @ref{6de,,autocommit 属性に依るトランザクション制御} を参照してください。

@cartouche
@quotation 注釈 
@ref{2d74,,isolation_level} 属性は、 @ref{6dd,,autocommit} の値が @ref{2d76,,LEGACY_TRANSACTION_CONTROL} でない限り、効果がありません。
@end quotation
@end cartouche


Added in version 3.12.

@end deffn

@geindex in_transaction (sqlite3.Connection の属性)
@anchor{library/sqlite3 sqlite3 Connection in_transaction}@anchor{2da1}
@deffn {の属性} in_transaction

この読み取り専用属性は、低レベルの SQLite autocommit mode@footnote{https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions} に対応します。

トランザクションがアクティブな場合 (コミットされていない変更がある場合) は @code{True} 、それ以外の場合は @code{False} です。


Added in version 3.2.

@end deffn

@geindex isolation_level (sqlite3.Connection の属性)
@anchor{library/sqlite3 sqlite3 Connection isolation_level}@anchor{2d74}
@deffn {の属性} isolation_level

@code{sqlite3} の @ref{2d75,,旧来のトランザクション処理モード} を制御します。 @code{None} に設定すると、トランザクションは暗黙に開かれることはありません。背後の SQLite の SQLite transaction behaviour@footnote{https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions} に対応する @code{"DEFERRED"} または @code{"IMMEDIATE"} または @code{"EXCLUSIVE"} のいずれかに設定すると、 @ref{2d75,,暗黙のトランザクション管理} が実行されます。

@ref{5a6,,connect()} の `isolation_level' パラメーターでオーバーライドされない場合、 デフォルトは @code{""} で、 これは @code{"DEFERRED"} の別名です。

@cartouche
@quotation 注釈 
トランザクション処理を制御するには、 @code{isolation_level} を使用するよりも @ref{6dd,,autocommit} を使用することをお勧めします。 @ref{6dd,,autocommit} が @ref{2d76,,LEGACY_TRANSACTION_CONTROL} (これがデフォルトです)に設定されていない限り、 @code{isolation_level} は効果がありません。
@end quotation
@end cartouche
@end deffn

@geindex row_factory (sqlite3.Connection の属性)
@anchor{library/sqlite3 sqlite3 Connection row_factory}@anchor{19a5}
@deffn {の属性} row_factory

この接続から作成された @ref{2d64,,Cursor} オブジェクトの初期 @ref{2da2,,row_factory} 。この属性に割り当てを行っても、 この接続に属する、すでに存在するカーソルの @code{row_factory} には影響せず、 この属性に割り当てを行った後に作成する新しいカーソルのみに影響します。 デフォルトでは @code{None} です。つまり、各行は @ref{614,,タプル} として返されます。

詳細は @ref{2d6b,,行工場(row factories)の作成方法と使用方法} をご覧下さい。
@end deffn

@geindex text_factory (sqlite3.Connection の属性)
@anchor{library/sqlite3 sqlite3 Connection text_factory}@anchor{2da3}
@deffn {の属性} text_factory

@ref{192,,bytes} のパラメータを受け取り、そのテキスト表現を返す @ref{2d7b,,呼び出し可能オブジェクト} です。呼び出し可能オブジェクトは @code{TEXT} データ型である SQLite 値に対して呼び出されます。 デフォルトでは、 この属性は @ref{169,,str} に設定されています。

See @ref{2da0,,How to handle non-UTF-8 text encodings} for more details.
@end deffn

@geindex total_changes (sqlite3.Connection の属性)
@anchor{library/sqlite3 sqlite3 Connection total_changes}@anchor{2da4}
@deffn {の属性} total_changes

データベース接続が開かれてから、変更または挿入または削除されたデータベース行の総数を返します。
@end deffn
@end deffn

@node Cursor オブジェクト,Row オブジェクト,Connection オブジェクト,リファレンス
@anchor{library/sqlite3 cursor-objects}@anchor{2da5}@anchor{library/sqlite3 sqlite3-cursor-objects}@anchor{2da6}
@subsubsection Cursor オブジェクト


@quotation

@code{Cursor} オブジェクトは、 SQL 文を実行し、 取得操作(fetch operation)のコンテキストを管理するために使用されるデータベース・カーソル(database cursor@footnote{https://en.wikipedia.org/wiki/Cursor_(databases)})を表します。カーソルは、 @ref{2d63,,Connection.cursor()} または @ref{2d96,,接続(connection)ショートカット・メソッド} の、いずれかを使用して作成されます。

カーソル・オブジェクトは @ref{4c8,,イテレータ} です。つまり、 @code{SELECT} クエリに対して @ref{5b0,,execute()} した場合、結果の行(rows)を取得するためには、カーソルを単純に反復(iterate)できます:

@c import sqlite3
@c con = sqlite3.connect(":memory:", isolation_level=None)
@c cur = con.execute("CREATE TABLE data(t)")
@c cur.execute("INSERT INTO data VALUES(1)")

@example
for row in cur.execute("SELECT t FROM data"):
    print(row)
@end example

@c (1,)
@end quotation

@geindex Cursor (sqlite3 のクラス)
@anchor{library/sqlite3 sqlite3 Cursor}@anchor{2d64}
@deffn {クラス} sqlite3.Cursor

@ref{2d64,,Cursor} インスタンスは以下の属性やメソッドを持ちます。

@geindex ? (クエスチョンマーク);in SQL statements

@geindex ; (コロン);in SQL statements

@geindex execute() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor execute}@anchor{5b0}
@deffn {メソッド} execute (sql, parameters=(), /)

Execute a single SQL statement,
optionally binding Python values using
@ref{5b2,,placeholders}.

@*パラメータ: 

@itemize *

@item 
@code{sql} (@ref{169,,str}) -- 単一の SQL 文。

@item 
@code{parameters} (@ref{183,,dict} | @ref{716,,sequence}) -- `sql' のプレースホルダに結び付け(bind)する Python 値。 名前付きプレースホルダが使用されている場合は @code{dict} です。 名前のないプレースホルダが使用されている場合は sequence です。 @ref{5b2,,プレースホルダを使用して SQL クエリに値を結び付ける方法} を参照してください。
@end itemize


@*例外: 
@ref{305,,ProgrammingError} -- When `sql' contains more than one SQL statement.
When @ref{5b2,,named placeholders} are used
and `parameters' is a sequence instead of a @ref{183,,dict}.


@ref{6dd,,autocommit} が @ref{2d76,,LEGACY_TRANSACTION_CONTROL} で、かつ、 @ref{2d74,,isolation_level} が @code{None} で無く、 かつ、 `sql' が @code{INSERT} または @code{UPDATE} または @code{DELETE} または @code{REPLACE} 文で、かつ、開いているトランザクションがない場合、 `sql' を実行する前にトランザクションが暗黙に開かれます。


バージョン 3.14 で変更: @ref{305,,ProgrammingError} is emitted if
@ref{5b2,,named placeholders} are used
and `parameters' is a sequence instead of a @ref{183,,dict}.


複数の SQL 文を実行するには @ref{2d9b,,executescript()} を使用します。
@end deffn

@geindex executemany() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor executemany}@anchor{5b1}
@deffn {メソッド} executemany (sql, parameters, /)

`parameters' のすべての item に対して、 @ref{5b2,,パラメーター化} された @abbr{DML,Data Manipulation Language} SQL 文である `sql' を繰り返し実行します。

@ref{5b0,,execute()} と同一の暗黙のトランザクション処理を使用します。

@*パラメータ: 

@itemize *

@item 
@code{sql} (@ref{169,,str}) -- 単一の DML 文。

@item 
@code{parameters} (@ref{12f1,,iterable}) -- `sql' のプレースホルダに結び付け(bind)するためのパラメータの iterable 。 @ref{5b2,,プレースホルダを使用して SQL クエリに値を結び付ける方法} 参照。
@end itemize


@*例外: 
@ref{305,,ProgrammingError} -- When `sql' contains more than one SQL statement
or is not a DML statement,
When @ref{5b2,,named placeholders} are used
and the items in `parameters' are sequences instead of @ref{183,,dict}s.


例:

@example
rows = [
    ("row1",),
    ("row2",),
]
# cur is an sqlite3.Cursor object
cur.executemany("INSERT INTO data VALUES(?)", rows)
@end example

@c con.close()

@cartouche
@quotation 注釈 
RETURNING 句(RETURNING clauses@footnote{https://www.sqlite.org/lang_returning.html})を含むDML文を含め、結果の行はすべて破棄されます。
@end quotation
@end cartouche


バージョン 3.14 で変更: @ref{305,,ProgrammingError} is emitted if
@ref{5b2,,named placeholders} are used
and the items in `parameters' are sequences
instead of @ref{183,,dict}s.

@end deffn

@geindex executescript() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor executescript}@anchor{2d9b}
@deffn {メソッド} executescript (sql_script, /)

`sql_script' 内の複数のSQL文を実行します。 @ref{6dd,,autocommit} が @ref{2d76,,LEGACY_TRANSACTION_CONTROL} で、かつ、保留中のトランザクションがある場合、暗黙の @code{COMMIT} 文が最初に実行されます。その他の暗黙のトランザクション制御は実行されませんので、トランザクション制御を `sql_script' に追加しなければなりません。

`sql_script' は @ref{169,,文字列} でなければなりません。

例:

@example
# cur is an sqlite3.Cursor object
cur.executescript("""
    BEGIN;
    CREATE TABLE person(firstname, lastname, age);
    CREATE TABLE book(title, author, published);
    CREATE TABLE publisher(name, address);
    COMMIT;
""")
@end example
@end deffn

@geindex fetchone() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor fetchone}@anchor{2d65}
@deffn {メソッド} fetchone ()

@ref{2da2,,row_factory} が @code{None} の場合、 次の行のクエリ結果セットを @ref{614,,タプル} として返します。それ以外の場合は、 それを行工場(row factory)に渡し、 その結果を返します。 これ以上データが無い場合は @code{None} を返します。
@end deffn

@geindex fetchmany() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor fetchmany}@anchor{17a7}
@deffn {メソッド} fetchmany (size=cursor.arraysize)

クエリ結果の次の行セットを @ref{24d,,list} として返します。行がそれ以上ない場合は、空のリストを返します。

呼び出しごとに取得する行数は、`size' パラメーターで指定されます。 `size' が指定されていない場合、 @ref{17a8,,arraysize} が取得する行数を決定します。有効な行の数が `size' 未満の場合は、有効な数の行が返されます。

`size' 引数とパフォーマンスの関係についての注意です。パフォーマンスを最適化するためには、大抵、 arraysize 属性を利用するのがベストです。 `size' 引数を利用したのであれば、次回の @ref{17a7,,fetchmany()} の呼び出しでも `size' 引数に同一の値を指定するのがのがベストです。


バージョン 3.14.1 で変更: Negative `size' values are rejected by raising @ref{2ec,,ValueError}.

@end deffn

@geindex fetchall() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor fetchall}@anchor{2d68}
@deffn {メソッド} fetchall ()

クエリ結果の(残りの)すべての行を @ref{24d,,list} として返します。 有効な行がない場合は、空のリストを返します。 @ref{17a8,,arraysize} 属性は、この操作のパフォーマンスに影響を与える可能性があることに注意してください。
@end deffn

@geindex close() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor close}@anchor{2da7}
@deffn {メソッド} close ()

(@code{__del__} が呼び出される時ではなく、) 今すぐカーソルを閉じます。

この時点から、このカーソルは使用できなくなります。今後、このカーソルで何らかの操作を試みると、 @ref{305,,ProgrammingError} 例外が送出されます。
@end deffn

@geindex setinputsizes() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor setinputsizes}@anchor{2da8}
@deffn {メソッド} setinputsizes (sizes, /)

DB-API で必要です。 @code{sqlite3} では何もしません。
@end deffn

@geindex setoutputsize() (sqlite3.Cursor のメソッド)
@anchor{library/sqlite3 sqlite3 Cursor setoutputsize}@anchor{2da9}
@deffn {メソッド} setoutputsize (size, column=None, /)

DB-API で必要です。 @code{sqlite3} では何もしません。
@end deffn

@geindex arraysize (sqlite3.Cursor の属性)
@anchor{library/sqlite3 sqlite3 Cursor arraysize}@anchor{17a8}
@deffn {の属性} arraysize

@ref{17a7,,fetchmany()} によって返される行(row)数を制御する、読み取りと書き込みが可能な属性。 デフォルト値は 1 で、これは呼び出しごとに 1 行が取得されることを意味します。


バージョン 3.14.1 で変更: Negative values are rejected by raising @ref{2ec,,ValueError}.

@end deffn

@geindex connection (sqlite3.Cursor の属性)
@anchor{library/sqlite3 sqlite3 Cursor connection}@anchor{2daa}
@deffn {の属性} connection

カーソルが属する SQLite データベース @ref{54d,,Connection} を提供する読み取り専用属性。 @ref{2d63,,con.cursor()} と呼び出して作成した @ref{2d64,,Cursor} オブジェクトには、`con' を参照する @ref{2daa,,connection} 属性があります:

@example
>>> con = sqlite3.connect(":memory:")
>>> cur = con.cursor()
>>> cur.connection == con
True
>>> con.close()
@end example
@end deffn

@geindex description (sqlite3.Cursor の属性)
@anchor{library/sqlite3 sqlite3 Cursor description}@anchor{18ab}
@deffn {の属性} description

最後のクエリの列(column)名を提供する読み取り専用属性。 Python DB API との互換性を維持するために、各列ごとに 7 項目のタプルで、先頭の項目が列名、残りの6項目が @code{None} です。

この属性は @code{SELECT} 文にマッチする行(row)が1つもなかった場合でもセットされます。
@end deffn

@geindex lastrowid (sqlite3.Cursor の属性)
@anchor{library/sqlite3 sqlite3 Cursor lastrowid}@anchor{ecc}
@deffn {の属性} lastrowid

最後に挿入された行の行 ID (row id) を提供する読み取り専用属性。 @ref{5b0,,execute()}  で @code{INSERT} または @code{REPLACE} 文が成功した後にのみ更新されます。他のSQL文や、 @ref{5b1,,executemany()} の後や、 @ref{2d9b,,executescript()} の後や、 挿入が失敗した場合、 @code{lastrowid} の値は変更されません。@code{lastrowid} の初期値は @code{None} です。

@cartouche
@quotation 注釈 
@code{WITHOUT ROWID} テーブルへの挿入(insert)は記録されません。
@end quotation
@end cartouche


バージョン 3.6 で変更: @code{REPLACE} 文のサポートが追加されました。

@end deffn

@geindex rowcount (sqlite3.Cursor の属性)
@anchor{library/sqlite3 sqlite3 Cursor rowcount}@anchor{1b60}
@deffn {の属性} rowcount

@code{INSERT} や @code{UPDATE} や @code{DELETE} や @code{REPLACE} 文で変更された行数を提供する読み取り専用属性。 @abbr{CTE,共通テーブル式} クエリを含む他のSQL文は @code{-1} です。 @ref{5b0,,execute()} と @ref{5b1,,executemany()} メソッドのみにおいて、 SQL文(statement)実行の完了後に更新されます。 なぜなら @code{rowcount} を更新するためには、結果の行を取得(fetch)しなければならないからです。
@end deffn

@geindex row_factory (sqlite3.Cursor の属性)
@anchor{library/sqlite3 sqlite3 Cursor row_factory}@anchor{2da2}
@deffn {の属性} row_factory

この @code{カーソル} から取得された行の表現方法を制御します。 @code{None} の場合、行は @ref{614,,タプル} として表されます。 @ref{1071,,sqlite3.Row} に設定することもできます。 そしてまた、 @ref{2d64,,Cursor} オブジェクトと、 行の値の @code{タプル} の、 2 つの引数を受け取り、 SQLite の行(row)を表すカスタム・オブジェクトを返す、 @ref{2d7b,,呼び出し可能オブジェクト} に設定することもできます。

@code{カーソル・オブジェクト} の作成時に @ref{19a5,,Connection.row_factory} の値をこの属性のデフォルト値として設定します。この属性に割り当てても、親接続(parent connection)の @ref{19a5,,Connection.row_factory} には影響しません。

詳細は @ref{2d6b,,行工場(row factories)の作成方法と使用方法} をご覧下さい。
@end deffn
@end deffn

@c The sqlite3.Row example used to be a how-to. It has now been incorporated
@c into the Row reference. We keep the anchor here in order not to break
@c existing links.
@anchor{library/sqlite3 sqlite3-columns-by-name}@anchor{2dab}
@node Row オブジェクト,Blob オブジェクト,Cursor オブジェクト,リファレンス
@anchor{library/sqlite3 row-objects}@anchor{2dac}@anchor{library/sqlite3 sqlite3-row-objects}@anchor{2dad}
@subsubsection Row オブジェクト


@geindex Row (sqlite3 のクラス)
@anchor{library/sqlite3 sqlite3 Row}@anchor{1071}
@deffn {クラス} sqlite3.Row

@code{Row} インスタンスは、 @ref{54d,,Connection} オブジェクトの、高度に最適化された @ref{19a5,,row_factory} の役割をします。 反復(iteration)や、等しいかどうかのテスト(equality testing)や、 @ref{840,,len()} 関数や 、 列名(column name)とインデックスによる @ref{13d3,,マッピング} のアクセスを、サポートします。

列名(column names)と値(values)が全く同一である 2 つの @code{Row}  オブジェクトを比較すると、等しいと見なされます。

詳細は @ref{2d6b,,行工場(row factories)の作成方法と使用方法} をご覧下さい。

@geindex keys() (sqlite3.Row のメソッド)
@anchor{library/sqlite3 sqlite3 Row keys}@anchor{2dae}
@deffn {メソッド} keys ()

列名(column names)の @ref{24d,,リスト} を @ref{169,,文字列} として返します。 クエリの直後であれば、それは @ref{18ab,,Cursor.description} の各タプルの最初のメンバーです。
@end deffn


バージョン 3.5 で変更: スライスがサポートされました。

@end deffn

@node Blob オブジェクト,PrepareProtocol オブジェクト,Row オブジェクト,リファレンス
@anchor{library/sqlite3 blob-objects}@anchor{2daf}@anchor{library/sqlite3 sqlite3-blob-objects}@anchor{2db0}
@subsubsection Blob オブジェクト


@geindex Blob (sqlite3 のクラス)
@anchor{library/sqlite3 sqlite3 Blob}@anchor{892}
@deffn {クラス} sqlite3.Blob


Added in version 3.11.


@ref{892,,Blob} インスタンスは、 SQLite の @abbr{BLOB} とデータを読み書きできる @ref{17ac,,file-like object} です。 @ref{840,,len(blob)} を呼び出して、 Blob のサイズ (バイト数) を取得します。 Blob データに直接アクセスするには、インデックスと @ref{24ae,,スライス} を使用します。

@ref{892,,Blob} を @ref{1e1,,コンテキストマネージャ} として使用して、 使用後に Blob ハンドルが確実に閉じられるようにします。

@example
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE test(blob_col blob)")
con.execute("INSERT INTO test(blob_col) VALUES(zeroblob(13))")

# Write to our blob, using two write operations:
with con.blobopen("test", "blob_col", 1) as blob:
    blob.write(b"hello, ")
    blob.write(b"world.")
    # Modify the first and last bytes of our blob
    blob[0] = ord("H")
    blob[-1] = ord("!")

# Read the contents of our blob
with con.blobopen("test", "blob_col", 1) as blob:
    greeting = blob.read()

print(greeting)  # outputs "b'Hello, world!'"
con.close()
@end example

@c b'Hello, world!'

@geindex close() (sqlite3.Blob のメソッド)
@anchor{library/sqlite3 sqlite3 Blob close}@anchor{2db1}
@deffn {メソッド} close ()

Blob を閉じます。

この時点から、 BLOB は使用できなくなります。 BLOB に対してさらに操作を試みると、 @ref{1c25,,Error} (またはそのサブクラスの) 例外を送出します。
@end deffn

@geindex read() (sqlite3.Blob のメソッド)
@anchor{library/sqlite3 sqlite3 Blob read}@anchor{2db2}
@deffn {メソッド} read (length=-1, /)

BLOB の現在のオフセット位置から `length' バイトのデータを読み取り返ます。 BLOB の現在のオフセット位置から末尾までの残りが `length' バイトよりも少ない場合、末尾までのデータを読み取ります。 `length' が指定されていない場合、 または負数の場合、 @ref{2db2,,read()} は BLOB の現在のオフセット位置から末尾までのデータを読み取ります。
@end deffn

@geindex write() (sqlite3.Blob のメソッド)
@anchor{library/sqlite3 sqlite3 Blob write}@anchor{2db3}
@deffn {メソッド} write (data, /)

BLOB の現在のオフセット位置から `data' を書き込みます。 この関数では BLOB の長さを変更できません。 BLOB の末尾を超えて書き込もうとすると @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex tell() (sqlite3.Blob のメソッド)
@anchor{library/sqlite3 sqlite3 Blob tell}@anchor{2db4}
@deffn {メソッド} tell ()

BLOBの現在のオフセット位置(current access position)を返します。
@end deffn

@geindex seek() (sqlite3.Blob のメソッド)
@anchor{library/sqlite3 sqlite3 Blob seek}@anchor{2db5}
@deffn {メソッド} seek (offset, origin=os.SEEK_SET, /)

Set the current access position of the blob to `offset'.  The `origin'
argument defaults to @ref{14a5,,os.SEEK_SET} (absolute blob positioning).
Other values for `origin' are @ref{14a6,,os.SEEK_CUR} (seek relative to the
current position) and @ref{14a7,,os.SEEK_END} (seek relative to the blob’s
end).
@end deffn
@end deffn

@node PrepareProtocol オブジェクト,例外<7>,Blob オブジェクト,リファレンス
@anchor{library/sqlite3 prepareprotocol-objects}@anchor{2db6}
@subsubsection PrepareProtocol オブジェクト


@geindex PrepareProtocol (sqlite3 のクラス)
@anchor{library/sqlite3 sqlite3 PrepareProtocol}@anchor{1b6b}
@deffn {クラス} sqlite3.PrepareProtocol

PrepareProtocol 型の唯一の目的は、 @ref{2d70,,SQLite でネイティブにサポートされている型} に @ref{2db7,,オブジェクト自身で適合(adapt)} できるオブジェクトの  
@geindex Python Enhancement Proposals; PEP 246
PEP 246@footnote{https://peps.python.org/pep-0246/} スタイルの適合プロトコルとして機能することです。
@end deffn

@node 例外<7>,SQLite と Python の型,PrepareProtocol オブジェクト,リファレンス
@anchor{library/sqlite3 exceptions}@anchor{2db8}@anchor{library/sqlite3 sqlite3-exceptions}@anchor{2db9}
@subsubsection 例外


例外の階層は DB-API 2.0 (
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/}) で定義されています。

@geindex Warning
@anchor{library/sqlite3 sqlite3 Warning}@anchor{1bb6}
@deffn {例外} sqlite3.Warning

この例外は、現在 @code{sqlite3} モジュールでは送出しませんが、ユーザー定義関数が挿入処理中にデータを切り捨てる場合など、@code{sqlite3} を使用するアプリケーションによって送出されるる可能性があります。 @code{Warning} は @ref{bcd,,Exception} のサブクラスです。
@end deffn

@geindex Error
@anchor{library/sqlite3 sqlite3 Error}@anchor{1c25}
@deffn {例外} sqlite3.Error

このモジュールの他の例外の基底となるクラス。 これを使用すると、1 つの @ref{1ab,,except} 文ですべてのエラーをキャッチできます。 @code{Error} は @ref{bcd,,Exception} のサブクラスです。

例外が SQLite ライブラリ内で発生した場合、 以下の 2 つの属性が例外に追加されます:

@geindex sqlite_errorcode (sqlite3.Error の属性)
@anchor{library/sqlite3 sqlite3 Error sqlite_errorcode}@anchor{888}
@deffn {の属性} sqlite_errorcode

SQLite API@footnote{https://sqlite.org/rescode.html} からの数値エラー・コード


Added in version 3.11.

@end deffn

@geindex sqlite_errorname (sqlite3.Error の属性)
@anchor{library/sqlite3 sqlite3 Error sqlite_errorname}@anchor{889}
@deffn {の属性} sqlite_errorname

SQLite API@footnote{https://sqlite.org/rescode.html} からの数値エラー・コードの記号名


Added in version 3.11.

@end deffn
@end deffn

@geindex InterfaceError
@anchor{library/sqlite3 sqlite3 InterfaceError}@anchor{88d}
@deffn {例外} sqlite3.InterfaceError

低レベルの SQLite C API の誤用により送出される例外。 つまり、この例外が送出された場合、おそらく @code{sqlite3} モジュールのバグを示しています。 @code{InterfaceError} は @ref{1c25,,Error} のサブクラスです。
@end deffn

@geindex DatabaseError
@anchor{library/sqlite3 sqlite3 DatabaseError}@anchor{2d9f}
@deffn {例外} sqlite3.DatabaseError

データベースに関連するエラーに対して送出される例外。 これは、いくつかの種類のデータベース・エラーの基底の例外として機能します。 これを特殊化(specialise)したサブクラスを介して暗黙的にのみ送出されます。 @code{DatabaseError} は @ref{1c25,,Error} のサブクラスです。
@end deffn

@geindex DataError
@anchor{library/sqlite3 sqlite3 DataError}@anchor{1c51}
@deffn {例外} sqlite3.DataError

範囲外の数値や長すぎる文字列など、処理されたデータの問題によって発生したエラーに対して送出される例外。 @code{DataError} は @ref{2d9f,,DatabaseError} のサブクラスです。
@end deffn

@geindex OperationalError
@anchor{library/sqlite3 sqlite3 OperationalError}@anchor{1c52}
@deffn {例外} sqlite3.OperationalError

データベースの操作に関連し、必ずしもプログラマの制御下にないエラーに対して発生する例外。 たとえば、データベース・パスが見つからないとか、トランザクションを処理できませんでした等。 @code{OperationalError} は @ref{2d9f,,DatabaseError} のサブクラスです。
@end deffn

@geindex IntegrityError
@anchor{library/sqlite3 sqlite3 IntegrityError}@anchor{2dba}
@deffn {例外} sqlite3.IntegrityError

データベースの参照整合性が影響を受ける場合に発生する例外。 たとえば外部キーのチェック(foreign key check)が失敗したとき。 @ref{2d9f,,DatabaseError} のサブクラスです。
@end deffn

@geindex InternalError
@anchor{library/sqlite3 sqlite3 InternalError}@anchor{2dbb}
@deffn {例外} sqlite3.InternalError

SQLite が内部エラーに遭遇したときに発生する例外。 これが送出された場合、ランタイム SQLite ライブラリに問題があることを示している可能性があります。 @code{InternalError} は @ref{2d9f,,DatabaseError} のサブクラスです。
@end deffn

@geindex ProgrammingError
@anchor{library/sqlite3 sqlite3 ProgrammingError}@anchor{305}
@deffn {例外} sqlite3.ProgrammingError

@code{sqlite3} API プログラミング・エラーに対して送出される例外。たとえば、クエリに間違った数のバインディング(結び付け)を指定したり、閉じた後の @ref{54d,,Connection} を操作しようとしたりしたとき。 @code{ProgrammingError} は @ref{2d9f,,DatabaseError} のサブクラスです。
@end deffn

@geindex NotSupportedError
@anchor{library/sqlite3 sqlite3 NotSupportedError}@anchor{2d9d}
@deffn {例外} sqlite3.NotSupportedError

メソッドまたはデータベース API が 背後の SQLite ライブラリでサポートしていない場合に送出される例外。たとえば、背後の SQLite ライブラリが決定論的関数(deterministic functions)をサポートしていない場合に、@ref{5a7,,create_function()} で `deterministic' を @code{True} に設定したとき。 @code{NotSupportedError}  は @ref{2d9f,,DatabaseError} のサブクラスです。
@end deffn

@node SQLite と Python の型,デフォルトの適合関数 adapters とデフォルトの変換関数 converters 非推奨,例外<7>,リファレンス
@anchor{library/sqlite3 sqlite-and-python-types}@anchor{2dbc}@anchor{library/sqlite3 sqlite3-types}@anchor{2d70}
@subsubsection SQLite と Python の型


SQLite は以下の型をネイティブにサポートします: @code{NULL}, @code{INTEGER}, @code{REAL}, @code{TEXT}, @code{BLOB}。

したがって、次の Python の型は問題なく SQLite に送り込めます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} 
@headitem

Python の型

@tab

SQLite の型

@item

@code{None}

@tab

@code{NULL}

@item

@ref{19b,,int}

@tab

@code{INTEGER}

@item

@ref{196,,float}

@tab

@code{REAL}

@item

@ref{169,,str}

@tab

@code{TEXT}

@item

@ref{192,,bytes}

@tab

@code{BLOB}

@end multitable


SQLite の型から Python の型へのデフォルトでの変換は以下の通りです:


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

SQLite の型

@tab

Python の型

@item

@code{NULL}

@tab

@code{None}

@item

@code{INTEGER}

@tab

@ref{19b,,int}

@item

@code{REAL}

@tab

@ref{196,,float}

@item

@code{TEXT}

@tab

@ref{2da3,,text_factory} に依存する。デフォルトでは @ref{169,,str} 。

@item

@code{BLOB}

@tab

@ref{192,,bytes}

@end multitable


@code{sqlite3} モジュールの型システムは 2 つの方法で拡張可能です。 @ref{2d69,,オブジェクト適合関数(adapter)} を介して SQLite データベースに追加の Python 型を格納できます。 または、 @ref{2d6a,,変換関数(converter)} を介して @code{sqlite3} モジュールが SQLite 型を Python 型に変換できます。

@node デフォルトの適合関数 adapters とデフォルトの変換関数 converters 非推奨,コマンドライン・インターフェース<2>,SQLite と Python の型,リファレンス
@anchor{library/sqlite3 default-adapters-and-converters-deprecated}@anchor{2dbd}@anchor{library/sqlite3 sqlite3-default-converters}@anchor{714}
@subsubsection デフォルトの適合関数(adapters)とデフォルトの変換関数(converters)(非推奨)


@cartouche
@quotation 注釈 
デフォルトの適合関数(adapters)とデフォルトの変換関数(converters)は、 Python 3.12 以降非推奨になりました。代わりに、 @ref{715,,適合関数と変換関数のレシピ集} を利用して、あなたのニーズに合わせて仕立てて下さい。
@end quotation
@end cartouche

非推奨の、デフォルトの適合関数(adapters)とデフォルトの変換関数(converters)は以下のもので構成されています:


@itemize *

@item 
@ref{1fa,,datetime.date} オブジェクトを ISO 8601@footnote{https://en.wikipedia.org/wiki/ISO_8601} 形式の @ref{169,,文字列} にする適合関数(adapter)。

@item 
@ref{4e2,,datetime.datetime} オブジェクトを ISO 8601 形式の文字列にする適合関数(adapter)。

@item 
"date" と @ref{2d6a,,宣言された} 型を @ref{1fa,,datetime.date} オブジェクトにする変換関数(converter)。

@item 
"timestamp" と宣言された型を @ref{4e2,,datetime.datetime} オブジェクトにする変換関数(converter)。小数部分は 6 桁 (マイクロ秒の精度) に切り捨てられます。
@end itemize

@cartouche
@quotation 注釈 
デフォルトの "timestamp" 変換関数は、データベース内の UTC オフセットを無視し、常に素朴(naive)な @ref{4e2,,datetime.datetime} オブジェクトを返します。 timestamp で UTC オフセットを保持するには、変換関数を無効のままにするか、あるいは、オフセット対応の変換関数を @ref{2d71,,register_converter()} に登録します。
@end quotation
@end cartouche


バージョン 3.12 で非推奨.


@node コマンドライン・インターフェース<2>,,デフォルトの適合関数 adapters とデフォルトの変換関数 converters 非推奨,リファレンス
@anchor{library/sqlite3 command-line-interface}@anchor{2dbe}@anchor{library/sqlite3 sqlite3-cli}@anchor{674}
@subsubsection コマンドライン・インターフェース


@code{sqlite3} モジュールは、単純な SQLite シェルを提供するために、インタプリタで @ref{23c,,-m} スイッチを使用してスクリプトとして呼び出すことができます。引数は以下のとおりです:

@example
python -m sqlite3 [-h] [-v] [filename] [sql]
@end example

@code{.quit} または CTRL-D を入力するとシェルを終了(exit)します。

@geindex python--m-sqlite3-[-h]-[-v]-[filename]-[sql] コマンドラインオプション; -h
@geindex python--m-sqlite3-[-h]-[-v]-[filename]-[sql] コマンドラインオプション; --help
@anchor{library/sqlite3 cmdoption-python-m-sqlite3-h-v-filename-sql-h}@anchor{2dbf}@anchor{library/sqlite3 cmdoption-python-m-sqlite3-h-v-filename-sql-help}@anchor{2dc0}
@deffn {Option} @w{-}h, @w{-}@w{-}help

CLI ヘルプを表示。
@end deffn

@geindex python--m-sqlite3-[-h]-[-v]-[filename]-[sql] コマンドラインオプション; -v
@geindex python--m-sqlite3-[-h]-[-v]-[filename]-[sql] コマンドラインオプション; --version
@anchor{library/sqlite3 cmdoption-python-m-sqlite3-h-v-filename-sql-v}@anchor{2dc1}@anchor{library/sqlite3 cmdoption-python-m-sqlite3-h-v-filename-sql-version}@anchor{2dc2}
@deffn {Option} @w{-}v, @w{-}@w{-}version

背後の SQLite ライブラリのバージョンを出力します。
@end deffn


Added in version 3.12.


@node ハウツー・ガイド,説明,リファレンス,sqlite3 --- SQLite データベース用の DB-API 2 0 インターフェース
@anchor{library/sqlite3 how-to-guides}@anchor{2dc3}@anchor{library/sqlite3 sqlite3-howtos}@anchor{2d60}
@subsubsection ハウツー・ガイド


@menu
* プレースホルダを使用して SQL クエリに値を結び付ける方法:: 
* カスタム Python 型を SQLite 値に適合させる方法:: 
* SQLite 値をカスタム Python 型に変換する方法:: 
* 適合関数と変換関数のレシピ集:: 
* 接続(connection)ショートカット・メソッドの使い方: 接続 connection ショートカット・メソッドの使い方. 
* 接続(connection)コンテキストマネージャの使い方: 接続 connection コンテキストマネージャの使い方. 
* SQLite URI の操作方法:: 
* 行工場(row factories)の作成方法と使用方法: 行工場 row factories の作成方法と使用方法. 
* How to handle non-UTF-8 text encodings:: 

@end menu

@node プレースホルダを使用して SQL クエリに値を結び付ける方法,カスタム Python 型を SQLite 値に適合させる方法,,ハウツー・ガイド
@anchor{library/sqlite3 how-to-use-placeholders-to-bind-values-in-sql-queries}@anchor{2dc4}@anchor{library/sqlite3 sqlite3-placeholders}@anchor{5b2}
@subsubsection プレースホルダを使用して SQL クエリに値を結び付ける方法


たいてい、SQL 操作は Python 変数の値を使う必要があります。しかし、 Python の文字列操作を使用してクエリを組み立てるのはSQLインジェクション攻撃(SQL injection attacks@footnote{https://en.wikipedia.org/wiki/SQL_injection})に対して脆弱なので注意が必要です。たとえば、攻撃者は以下のように単純にシングルクォートを閉じて @code{OR TRUE} を挿入してすべての行を選択できます:

@example
>>> # Never do this -- insecure!
>>> symbol = input()
' OR TRUE; --
>>> sql = "SELECT * FROM stocks WHERE symbol = '%s'" % symbol
>>> print(sql)
SELECT * FROM stocks WHERE symbol = '@w{'} OR TRUE; --'
>>> cur.execute(sql)
@end example

代わりに、DB-API のパラメータ割り当てを使います。クエリ文字列にPythonの変数を挿入するには、クエリ文字列中でプレースホルダを使用し、 かつ、 カーソルの @ref{5b0,,execute()} メソッドの 2 番目の引数にPythonの変数を値の @ref{614,,タプル} として指定することにより、 実際の値をクエリに割り当てます。

SQL 文では、疑問符 (qmark スタイル) または名前付きプレースホルダー (名前付きスタイル) の 2 種類のプレースホルダーのいずれかを使用できます。 qmark スタイルの場合、`parameters' は、 @ref{716,,シーケンス} でなければならず、シーケンスの長さがプレースホルダーの数と一致する必要があります。そうでなければ、 @ref{305,,ProgrammingError} を送出します。名前付きスタイルの場合、 `parameters' は @ref{183,,dict} (またはそのサブクラス) のインスタンスである必要があり、すべての名前付きパラメーターのキーが含まれている必要があります。余分な項目は無視されます。両方のスタイルの例を以下に示します。

@example
con = sqlite3.connect(":memory:")
cur = con.execute("CREATE TABLE lang(name, first_appeared)")

# This is the named style used with executemany():
data = (
    @{"name": "C", "year": 1972@},
    @{"name": "Fortran", "year": 1957@},
    @{"name": "Python", "year": 1991@},
    @{"name": "Go", "year": 2009@},
)
cur.executemany("INSERT INTO lang VALUES(:name, :year)", data)

# This is the qmark style used in a SELECT query:
params = (1972,)
cur.execute("SELECT * FROM lang WHERE first_appeared = ?", params)
print(cur.fetchall())
con.close()
@end example

@c [('C', 1972)]

@cartouche
@quotation 注釈 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} numeric プレースホルダは `サポートされていません' 。 使用すると、名前付きプレースホルダとして解釈されます。
@end quotation
@end cartouche

@node カスタム Python 型を SQLite 値に適合させる方法,SQLite 値をカスタム Python 型に変換する方法,プレースホルダを使用して SQL クエリに値を結び付ける方法,ハウツー・ガイド
@anchor{library/sqlite3 how-to-adapt-custom-python-types-to-sqlite-values}@anchor{2dc5}@anchor{library/sqlite3 sqlite3-adapters}@anchor{2d69}
@subsubsection カスタム Python 型を SQLite 値に適合させる方法


SQLite は、 限られたデータ型のみをネイティブにサポートします。 カスタム Python 型を SQLite データベースに保存するには、 @ref{2d70,,SQLite がネイティブに理解できる Python 型} のいずれかに `適合' (adapt)させます。

Python オブジェクトを SQLite の型に適合させる方法は 2 つあります。それは、オブジェクト自体を適合させる方法と、 `adapter callable' を使用する方法です。 後者は前者よりも優先されます。 カスタム型をエクスポートするライブラリの場合、 その型がそれ自体を適合させる事ができるようにすることが理にかなっている場合があります。 アプリケーション開発者としては、カスタム適合関数を登録して直接制御する方が理にかなっている場合もあります。

@menu
* 適合可能オブジェクトの書き方:: 
* 適合用呼び出し可能オブジェクト(adapter callables)の登録方法: 適合用呼び出し可能オブジェクト adapter callables の登録方法. 

@end menu

@node 適合可能オブジェクトの書き方,適合用呼び出し可能オブジェクト adapter callables の登録方法,,カスタム Python 型を SQLite 値に適合させる方法
@anchor{library/sqlite3 how-to-write-adaptable-objects}@anchor{2dc6}@anchor{library/sqlite3 sqlite3-conform}@anchor{2db7}
@subsubsection 適合可能オブジェクトの書き方


直交座標系(Cartesian coordinate system)で @code{x} と @code{y} のペアで座標を表す、 @code{Point} クラスがあるとします。 この @code{x} と @code{y} のペアはセミコロンで区切られたテキスト文字列としてデータベースに保存されます。 これは、適合した値を返す @code{__conform__(self, protocol)} メソッドを追加することで実装できます。 `protocol'  に渡されるオブジェクトは、 @ref{1b6b,,PrepareProtocol} 型になります。

@example
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __conform__(self, protocol):
        if protocol is sqlite3.PrepareProtocol:
            return f"@{self.x@};@{self.y@}"

con = sqlite3.connect(":memory:")
cur = con.cursor()

cur.execute("SELECT ?", (Point(4.0, -3.2),))
print(cur.fetchone()[0])
con.close()
@end example

@c 4.0;-3.2

@node 適合用呼び出し可能オブジェクト adapter callables の登録方法,,適合可能オブジェクトの書き方,カスタム Python 型を SQLite 値に適合させる方法
@anchor{library/sqlite3 how-to-register-adapter-callables}@anchor{2dc7}
@subsubsection 適合用呼び出し可能オブジェクト(adapter callables)の登録方法


別の策としては、Python オブジェクトを SQLite 互換の型に変換する関数を作成することが挙げられます。 この関数は、 @ref{2d7a,,register_adapter()} を使用して登録できます。

@example
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

def adapt_point(point):
    return f"@{point.x@};@{point.y@}"

sqlite3.register_adapter(Point, adapt_point)

con = sqlite3.connect(":memory:")
cur = con.cursor()

cur.execute("SELECT ?", (Point(1.0, 2.5),))
print(cur.fetchone()[0])
con.close()
@end example

@c 1.0;2.5

@node SQLite 値をカスタム Python 型に変換する方法,適合関数と変換関数のレシピ集,カスタム Python 型を SQLite 値に適合させる方法,ハウツー・ガイド
@anchor{library/sqlite3 how-to-convert-sqlite-values-to-custom-python-types}@anchor{2dc8}@anchor{library/sqlite3 sqlite3-converters}@anchor{2d6a}
@subsubsection SQLite 値をカスタム Python 型に変換する方法


適合関数(adapter)を使用すると、カスタム Python 型から SQLite 値に変換できます。SQLite 値 から カスタム Python 型に変換できるようにするためには、 `変換関数' (converters)を使用します。

それでは @code{Point} クラスの話に戻るとしましょう。 先程は x 座標と y 座標をセミコロンで区切られた文字列として SQLite に格納しました。

まず、 文字列をパラメーターとして受け取り、そこから @code{Point} オブジェクトを構築する変換関数を定義します。

@cartouche
@quotation 注釈 
変換関数には、基になる SQLite データ型に関係なく、 `常に' @ref{192,,bytes} オブジェクトで渡されます。
@end quotation
@end cartouche

@example
def convert_point(s):
    x, y = map(float, s.split(b";"))
    return Point(x, y)
@end example

与えられた SQLite 値をどの時点で変換すべきかを @code{sqlite3} に伝える必要があります。これは、 @ref{5a6,,connect()} の `detect_types' パラメータを使用して、データベースに接続する際に行います。 以下の 3 つの選択肢があります:


@itemize *

@item 
暗黙的: `detect_types' に @ref{2d72,,PARSE_DECLTYPES} と設定。

@item 
明示的: `detect_types' に @ref{2d73,,PARSE_COLNAMES} と設定。

@item 
両方: `detect_types' に @code{sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES} を設定。列名での指定は、宣言時の型よりも優先されます。
@end itemize

以下の例では、暗黙的なアプローチと明示的なアプローチについて表しています:

@example
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Point(@{self.x@}, @{self.y@})"

def adapt_point(point):
    return f"@{point.x@};@{point.y@}"

def convert_point(s):
    x, y = list(map(float, s.split(b";")))
    return Point(x, y)

# Register the adapter and converter
sqlite3.register_adapter(Point, adapt_point)
sqlite3.register_converter("point", convert_point)

# 1) Parse using declared types
p = Point(4.0, -3.2)
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.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()

# 2) Parse using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.execute("CREATE TABLE test(p)")

cur.execute("INSERT INTO test(p) VALUES(?)", (p,))
cur.execute('SELECT p AS "p [point]" FROM test')
print("with column names:", cur.fetchone()[0])
cur.close()
con.close()
@end example

@c with declared types: Point(4.0, -3.2)
@c with column names: Point(4.0, -3.2)

@node 適合関数と変換関数のレシピ集,接続 connection ショートカット・メソッドの使い方,SQLite 値をカスタム Python 型に変換する方法,ハウツー・ガイド
@anchor{library/sqlite3 adapter-and-converter-recipes}@anchor{2dc9}@anchor{library/sqlite3 sqlite3-adapter-converter-recipes}@anchor{715}
@subsubsection 適合関数と変換関数のレシピ集


この節では一般的な適合関数と変換関数のレシピを紹介します。

@example
import datetime
import sqlite3

def adapt_date_iso(val):
    """Adapt datetime.date to ISO 8601 date."""
    return val.isoformat()

def adapt_datetime_iso(val):
    """Adapt datetime.datetime to timezone-naive ISO 8601 date."""
    return val.replace(tzinfo=None).isoformat()

def adapt_datetime_epoch(val):
    """Adapt datetime.datetime to Unix timestamp."""
    return int(val.timestamp())

sqlite3.register_adapter(datetime.date, adapt_date_iso)
sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)
sqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)

def convert_date(val):
    """Convert ISO 8601 date to datetime.date object."""
    return datetime.date.fromisoformat(val.decode())

def convert_datetime(val):
    """Convert ISO 8601 datetime to datetime.datetime object."""
    return datetime.datetime.fromisoformat(val.decode())

def convert_timestamp(val):
    """Convert Unix epoch timestamp to datetime.datetime object."""
    return datetime.datetime.fromtimestamp(int(val))

sqlite3.register_converter("date", convert_date)
sqlite3.register_converter("datetime", convert_datetime)
sqlite3.register_converter("timestamp", convert_timestamp)
@end example

@c dt = datetime.datetime(2019, 5, 18, 15, 17, 8, 123456)
@c 
@c assert adapt_date_iso(dt.date()) == "2019-05-18"
@c assert convert_date(b"2019-05-18") == dt.date()
@c 
@c assert adapt_datetime_iso(dt) == "2019-05-18T15:17:08.123456"
@c assert convert_datetime(b"2019-05-18T15:17:08.123456") == dt
@c 
@c # Using current time as fromtimestamp() returns local date/time.
@c # Dropping microseconds as adapt_datetime_epoch truncates fractional second part.
@c now = datetime.datetime.now().replace(microsecond=0)
@c current_timestamp = int(now.timestamp())
@c 
@c assert adapt_datetime_epoch(now) == current_timestamp
@c assert convert_timestamp(str(current_timestamp).encode()) == now

@node 接続 connection ショートカット・メソッドの使い方,接続 connection コンテキストマネージャの使い方,適合関数と変換関数のレシピ集,ハウツー・ガイド
@anchor{library/sqlite3 how-to-use-connection-shortcut-methods}@anchor{2dca}@anchor{library/sqlite3 sqlite3-connection-shortcuts}@anchor{2d96}
@subsubsection 接続(connection)ショートカット・メソッドの使い方


@ref{54d,,Connection} クラスのメソッド @ref{2d98,,execute()} と @ref{2d99,,executemany()} と @ref{2d9a,,executescript()} を使うことで、 (しばしば余計な) @ref{2d64,,Cursor} オブジェクトをわざわざ作り出さずに済むので、コードをより簡潔に書くことができます。 @ref{2d64,,Cursor} オブジェクトは暗黙裡に生成され、ショートカット・メソッドの戻り値として受け取ることができます。この方法を使えば、 @code{SELECT} 文を実行してその結果について反復することが、 @ref{54d,,Connection} オブジェクトに対する呼び出し一つで行なえます。

@example
# Create and fill the table.
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE lang(name, first_appeared)")
data = [
    ("C++", 1985),
    ("Objective-C", 1984),
]
con.executemany("INSERT INTO lang(name, first_appeared) VALUES(?, ?)", data)

# 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;
# the connection object should be closed manually
con.close()
@end example

@c ('C++', 1985)
@c ('Objective-C', 1984)
@c I just deleted 2 rows

@node 接続 connection コンテキストマネージャの使い方,SQLite URI の操作方法,接続 connection ショートカット・メソッドの使い方,ハウツー・ガイド
@anchor{library/sqlite3 how-to-use-the-connection-context-manager}@anchor{2dcb}@anchor{library/sqlite3 sqlite3-connection-context-manager}@anchor{1b6c}
@subsubsection 接続(connection)コンテキストマネージャの使い方


@ref{54d,,Connection} オブジェクトは、コンテキスト・マネージャーとして使用でき、コンテキスト・マネージャーとして使用すると、 @ref{186,,with} ブロックを離れるときに、開いているトランザクションを自動的にコミットまたはロールバックします。 @ref{186,,with} 文のブロックが例外なく終了すると、トランザクションはコミットされます。このコミットが失敗した、または、 @code{with} 文のブロックでキャッチされなかった例外が発生した場合、トランザクションはロールバックされます。 @ref{6dd,,autocommit} が @code{False} の場合、コミット後またはロールバック後に新しいトランザクションが暗黙に開かれます。

@code{with} 文のブロックを離れるときに開いているトランザクションがない、または、 @ref{6dd,,autocommit} が @code{True} の場合、コンテキスト・マネージャは何も行いません。

@cartouche
@quotation 注釈 
The context manager neither implicitly opens a new transaction
nor closes the connection. If you need a closing context manager, consider
using @ref{15a1,,contextlib.closing()}.
@end quotation
@end cartouche

@example
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")

# Successful, con.commit() is called automatically afterwards
with con:
    con.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))

# con.rollback() is called after the with block finishes with an exception,
# the exception is still raised and must be caught
try:
    with con:
        con.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))
except sqlite3.IntegrityError:
    print("couldn't add Python twice")

# Connection object used as context manager only commits or rollbacks transactions,
# so the connection object should be closed manually
con.close()
@end example

@c couldn't add Python twice

@node SQLite URI の操作方法,行工場 row factories の作成方法と使用方法,接続 connection コンテキストマネージャの使い方,ハウツー・ガイド
@anchor{library/sqlite3 how-to-work-with-sqlite-uris}@anchor{2dcc}@anchor{library/sqlite3 sqlite3-uri-tricks}@anchor{2d77}
@subsubsection SQLite URI の操作方法


URI の小技をいくつか紹介します:


@itemize *

@item 
データベースを読み取り専用で開きます:
@end itemize

@example
>>> con = sqlite3.connect("file:tutorial.db?mode=ro", uri=True)
>>> con.execute("CREATE TABLE readonly(data)")
Traceback (most recent call last):
OperationalError: attempt to write a readonly database
>>> con.close()
@end example


@itemize *

@item 
まだ存在しない場合、新しいデータベース・ファイルを暗黙に作成しません。なお、新しいファイルが作成できない場合には @ref{1c52,,OperationalError} が送出されます:
@end itemize

@example
>>> con = sqlite3.connect("file:nosuchdb.db?mode=rw", uri=True)
Traceback (most recent call last):
OperationalError: unable to open database file
@end example


@itemize *

@item 
共有の名前付きインメモリ・データベースを作成します:
@end itemize

@example
db = "file:mem1?mode=memory&cache=shared"
con1 = sqlite3.connect(db, uri=True)
con2 = sqlite3.connect(db, uri=True)
with con1:
    con1.execute("CREATE TABLE shared(data)")
    con1.execute("INSERT INTO shared VALUES(28)")
res = con2.execute("SELECT data FROM shared")
assert res.fetchone() == (28,)

con1.close()
con2.close()
@end example

パラメータのリストを含む、この機能の詳細については、 SQLite URI documentation@footnote{https://www.sqlite.org/uri.html} を参照してください。

@node 行工場 row factories の作成方法と使用方法,How to handle non-UTF-8 text encodings,SQLite URI の操作方法,ハウツー・ガイド
@anchor{library/sqlite3 how-to-create-and-use-row-factories}@anchor{2dcd}@anchor{library/sqlite3 sqlite3-howto-row-factory}@anchor{2d6b}
@subsubsection 行工場(row factories)の作成方法と使用方法


デフォルトでは、 @code{sqlite3} は各行(row)を @ref{614,,タプル} として表します。 @code{タプル} があなたのニーズと合わない場合は、 @ref{1071,,sqlite3.Row} クラスまたはカスタム @ref{2da2,,row_factory} を使用できます。

@code{row_factory} は @ref{2d64,,Cursor} と @ref{54d,,Connection} の両方に属性として存在しますが、 その接続(connection)から作成されたすべてのカーソルが同一の行工場(row factory)を使用するようにするために、 @ref{19a5,,Connection.row_factory} を設定することをお勧めします。

@code{Row} は、 @code{タプル} に対してメモリ・オーバーヘッドとパフォーマンスへの影響を最小限に抑えながら、列(row)へのインデックスによるアクセスと、列への(大文字と小文字を区別しない)名前によるアクセスを提供します。 @code{Row} を行工場(row factory)として使用するには、 @code{row_factory} 属性に割り当てます:

@example
>>> con = sqlite3.connect(":memory:")
>>> con.row_factory = sqlite3.Row
@end example

このように設定すると、クエリは @code{Row} オブジェクトを返すようになります:

@example
>>> res = con.execute("SELECT 'Earth' AS name, 6378 AS radius")
>>> row = res.fetchone()
>>> row.keys()
['name', 'radius']
>>> row[0]         # Access by index.
'Earth'
>>> row["name"]    # Access by name.
'Earth'
>>> row["RADIUS"]  # Column names are case-insensitive.
6378
>>> con.close()
@end example

@cartouche
@quotation 注釈 
The @code{FROM} clause can be omitted in the @code{SELECT} statement, as in the
above example. In such cases, SQLite returns a single row with columns
defined by expressions, e.g. literals, with the given aliases
@code{expr AS alias}.
@end quotation
@end cartouche

各列名が各値にマップされた @ref{183,,dict} として行を返す、カスタム @ref{2da2,,row_factory} を作成することもできます:

@example
def dict_factory(cursor, row):
    fields = [column[0] for column in cursor.description]
    return @{key: value for key, value in zip(fields, row)@}
@end example

これを使うと、クエリは @code{タプル} の代わりに @code{dict} を返すようになります:

@example
>>> con = sqlite3.connect(":memory:")
>>> con.row_factory = dict_factory
>>> for row in con.execute("SELECT 1 AS a, 2 AS b"):
...     print(row)
@{'a': 1, 'b': 2@}
>>> con.close()
@end example

以下の行工場(row factory)は @ref{85e,,名前付きタプル} を返します:

@example
from collections import namedtuple

def namedtuple_factory(cursor, row):
    fields = [column[0] for column in cursor.description]
    cls = namedtuple("Row", fields)
    return cls._make(row)
@end example

@code{namedtuple_factory()} は以下のようにして使う事ができます:

@example
>>> con = sqlite3.connect(":memory:")
>>> con.row_factory = namedtuple_factory
>>> cur = con.execute("SELECT 1 AS a, 2 AS b")
>>> row = cur.fetchone()
>>> row
Row(a=1, b=2)
>>> row[0]  # Indexed access.
1
>>> row.b   # Attribute access.
2
>>> con.close()
@end example

上記レシピをチューニングすれば、 @ref{4e0,,namedtuple} の代わりに @ref{4e1,,dataclass} または、その他のカスタム・クラスを使用するように適合(adapt)させることができます。

@node How to handle non-UTF-8 text encodings,,行工場 row factories の作成方法と使用方法,ハウツー・ガイド
@anchor{library/sqlite3 how-to-handle-non-utf-8-text-encodings}@anchor{2dce}@anchor{library/sqlite3 sqlite3-howto-encoding}@anchor{2da0}
@subsubsection How to handle non-UTF-8 text encodings


By default, @code{sqlite3} uses @ref{169,,str} to adapt SQLite values
with the @code{TEXT} data type.
This works well for UTF-8 encoded text, but it might fail for other encodings
and invalid UTF-8.
You can use a custom @ref{2da3,,text_factory} to handle such cases.

Because of SQLite's flexible typing@footnote{https://www.sqlite.org/flextypegood.html}, it is not uncommon to encounter table
columns with the @code{TEXT} data type containing non-UTF-8 encodings,
or even arbitrary data.
To demonstrate, let's assume we have a database with ISO-8859-2 (Latin-2)
encoded text, for example a table of Czech-English dictionary entries.
Assuming we now have a @ref{54d,,Connection} instance @code{con}
connected to this database,
we can decode the Latin-2 encoded text using this @ref{2da3,,text_factory}:

@example
con.text_factory = lambda data: str(data, encoding="latin2")
@end example

For invalid UTF-8 or arbitrary data in stored in @code{TEXT} table columns,
you can use the following technique, borrowed from the @ref{14bc,,Unicode HOWTO}:

@example
con.text_factory = lambda data: str(data, errors="surrogateescape")
@end example

@cartouche
@quotation 注釈 
The @code{sqlite3} module API does not support strings
containing surrogates.
@end quotation
@end cartouche


@subsubheading 参考


@ref{14bc,,Unicode HOWTO}


@node 説明,,ハウツー・ガイド,sqlite3 --- SQLite データベース用の DB-API 2 0 インターフェース
@anchor{library/sqlite3 explanation}@anchor{2dcf}@anchor{library/sqlite3 sqlite3-explanation}@anchor{2d61}
@subsubsection 説明

@anchor{library/sqlite3 sqlite3-transaction-control}@anchor{2dd0}
@menu
* トランザクション制御:: 

@end menu

@node トランザクション制御,,,説明
@anchor{library/sqlite3 sqlite3-controlling-transactions}@anchor{2d66}@anchor{library/sqlite3 transaction-control}@anchor{2dd1}
@subsubsection トランザクション制御


@code{sqlite3} は、データベース・トランザクションを開くかどうか、いつ、どのように開くかを制御する複数の方法を提供します。 @ref{6de,,autocommit 属性に依るトランザクション制御} が推奨されますが、@ref{2d75,,isolation_level 属性に依るトランザクション制御} は Python 3.12 より前の動作を保持します。

@menu
* autocommit 属性に依るトランザクション制御:: 
* isolation_level 属性に依るトランザクション制御:: 

@end menu

@node autocommit 属性に依るトランザクション制御,isolation_level 属性に依るトランザクション制御,,トランザクション制御
@anchor{library/sqlite3 sqlite3-transaction-control-autocommit}@anchor{6de}@anchor{library/sqlite3 transaction-control-via-the-autocommit-attribute}@anchor{2dd2}
@subsubsection @code{autocommit} 属性に依るトランザクション制御


トランザクションの動作を制御する推奨方法は、 @ref{6dd,,Connection.autocommit} 属性を使用することです。 この属性は @ref{5a6,,connect()} の `autocommit' パラメータを使用して設定して頂けるとありがたいです。

`autocommit' を @code{False} に設定することをお勧めします。そうすると 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} 対応のトランザクション制御を行います。これは以下のことを意味します:


@itemize *

@item 
@code{sqlite3} はトランザクションが常に開いていることを保証します。そのため、 @ref{5a6,,connect()} や @ref{2d67,,Connection.commit()} や @ref{2d97,,Connection.rollback()} は暗黙に新しいトランザクションを開きます(1つ目については保留中のトランザクションを閉じた直後で、後の2つについてはその直後に、です)。 @code{sqlite3} はトランザクションを開くときに @code{BEGIN DEFERRED} 文を使用します。

@item 
トランザクションは、 @code{commit()} を使用して明示的にコミットする必要があります。

@item 
トランザクションは、 @code{rollback()} を使用して明示的にロールバックする必要があります。

@item 
データベースの保留中に行った変更は @ref{54e,,close()} された場合、暗黙のロールバックが実行されます。
@end itemize

`autocommit' を @code{True} に設定して、SQLite の autocommit mode@footnote{https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions} を有効にします。このモードでは、 @ref{2d67,,Connection.commit()} と @ref{2d97,,Connection.rollback()} は効果がありません。 SQLite の自動コミット・モード(autocommit mode)は、 
@geindex Python Enhancement Proposals; PEP 249
PEP 249@footnote{https://peps.python.org/pep-0249/} 対応の @ref{6dd,,Connection.autocommit} 属性とは異なることに注意してください。 @ref{2da1,,Connection.in_transaction} を使用して、低レベル SQLite 自動コミット・モードを問い合わせします。

`autocommit' を @ref{2d76,,LEGACY_TRANSACTION_CONTROL} に設定して、トランザクション制御の振る舞いを @ref{2d74,,Connection.isolation_level} 属性に任せます。詳細については @ref{2d75,,isolation_level 属性に依るトランザクション制御} を参照してください。

@node isolation_level 属性に依るトランザクション制御,,autocommit 属性に依るトランザクション制御,トランザクション制御
@anchor{library/sqlite3 sqlite3-transaction-control-isolation-level}@anchor{2d75}@anchor{library/sqlite3 transaction-control-via-the-isolation-level-attribute}@anchor{2dd3}
@subsubsection @code{isolation_level} 属性に依るトランザクション制御


@cartouche
@quotation 注釈 
推奨のトランザクション制御方法は、 @ref{6dd,,autocommit} 属性を使用することです。 @ref{6de,,autocommit 属性に依るトランザクション制御} を参照してください。
@end quotation
@end cartouche

@ref{6dd,,Connection.autocommit} が @ref{2d76,,LEGACY_TRANSACTION_CONTROL} (これがデフォルトです)に設定されている場合、トランザクションの振る舞いは @ref{2d74,,Connection.isolation_level} 属性を使用して制御されます。 @ref{2d76,,LEGACY_TRANSACTION_CONTROL} 以外の場合、 @code{isolation_level} は効果がありません。

接続属性 @ref{2d74,,isolation_level} が @code{None} で無いのなら、 @ref{5b0,,execute()} や @ref{5b1,,executemany()} が  @code{INSERT} または @code{UPDATE} または @code{DELETE} または @code{REPLACE} 文を実行する前に新しいトランザクションが暗黙に開かれます。それ以外のSQL文では暗黙のトランザクション処理は行われません。 @ref{2d67,,commit()} メソッドや @ref{2d97,,rollback()} メソッドを使用して、 保留中のトランザクションをそれぞれコミットおよびロールバックします。あなたは、背後にある SQLite ライブラリのトランザクションの振る舞い(SQLite transaction behaviour@footnote{https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions}) — つまり、 sqlite3 が暗黙に実行する @code{BEGIN} 文の有無とその種類 – を、 @ref{2d74,,isolation_level} 属性を介して選択できます。

@ref{2d74,,isolation_level} が @code{None} に設定されていると、トランザクションは暗黙に開かれません。これにより、背後にある SQLite ライブラリを自動コミット・モード(autocommit mode@footnote{https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions})にしたまま、 明示的な SQL 文を使用して、 ユーザが独自のトランザクション処理を行えるようにします。背後にある SQLite ライブラリの自動コミット・モードは、 @ref{2da1,,in_transaction} 属性を使用して問い合わせできます。

@ref{2d9b,,executescript()} メソッドは、 @ref{2d74,,isolation_level} の値に関係なく、与えられた SQL スクリプトの実行前に、保留中のトランザクションを暗黙にコミットします。


バージョン 3.6 で変更: @code{sqlite3} は、 DDL文の前に、開いているトランザクションを暗黙にコミットしていました。これはもはや当てはまりません。



バージョン 3.12 で変更: 推奨のトランザクションを制御方法は、 @ref{6dd,,autocommit} 属性を使用することです。


@c import os
@c os.remove("backup.db")
@c os.remove("dump.sql")
@c os.remove("example.db")
@c os.remove("tutorial.db")

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node データ圧縮とアーカイブ,ファイルフォーマット,データの永続化,Python 標準ライブラリ
@anchor{library/archiving doc}@anchor{2d09}@anchor{library/archiving archiving}@anchor{2dd4}@anchor{library/archiving data-compression-and-archiving}@anchor{2dd5}@anchor{library/archiving translation-repo}@anchor{2dd6}
@section データ圧縮とアーカイブ


The modules described in this chapter support data compression with the zlib,
gzip, bzip2, lzma, and zstd algorithms, and the creation of ZIP- and tar-format
archives.  See also @ref{1431,,アーカイブ化操作} provided by the @ref{ca,,shutil}
module.

@menu
* compression パッケージ:: 
* compression.zstd: compression zstd --- Compression compatible with the Zstandard format. Compression compatible with the Zstandard format
* zlib: zlib --- gzip 互換の圧縮. gzip 互換の圧縮
* gzip: gzip --- gzip ファイルのサポート. gzip ファイルのサポート
* bz2: bz2 --- bzip2 圧縮のサポート. bzip2 圧縮のサポート
* lzma: lzma --- LZMA アルゴリズムを使用した圧縮. LZMA アルゴリズムを使用した圧縮
* zipfile: zipfile --- ZIP アーカイブの処理. ZIP アーカイブの処理
* tarfile: tarfile --- tar アーカイブファイルの読み書き. tar アーカイブファイルの読み書き

@end menu

@node compression パッケージ,compression zstd --- Compression compatible with the Zstandard format,,データ圧縮とアーカイブ
@anchor{library/compression doc}@anchor{2dd7}@anchor{library/compression module-compression}@anchor{22}@anchor{library/compression the-compression-package}@anchor{2dd8}
@subsection @code{compression} パッケージ


@geindex module; compression


Added in version 3.14.


The @code{compression} package contains the canonical compression modules
containing interfaces to several different compression algorithms. Some of
these modules have historically been available as separate modules; those will
continue to be available under their original names for compatibility reasons,
and will not be removed without a deprecation cycle. The use of modules in
@code{compression} is encouraged where practical.


@itemize *

@item 
@code{compression.bz2} -- Re-exports @ref{14,,bz2}

@item 
@code{compression.gzip} -- Re-exports @ref{6b,,gzip}

@item 
@code{compression.lzma} -- Re-exports @ref{8e,,lzma}

@item 
@code{compression.zlib} -- Re-exports @ref{139,,zlib}

@item 
@ref{23,,compression.zstd} -- Wrapper for the Zstandard compression library
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node compression zstd --- Compression compatible with the Zstandard format,zlib --- gzip 互換の圧縮,compression パッケージ,データ圧縮とアーカイブ
@anchor{library/compression zstd doc}@anchor{2dd9}@anchor{library/compression zstd compression-zstd-compression-compatible-with-the-zstandard-format}@anchor{2dda}@anchor{library/compression zstd module-compression zstd}@anchor{23}@anchor{library/compression zstd translation-repo}@anchor{2ddb}
@subsection @code{compression.zstd} --- Compression compatible with the Zstandard format


@geindex module; compression.zstd


Added in version 3.14.


`Source code:' Lib/compression/zstd/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/compression/zstd/__init__.py}


__________________________________________________________________


This module provides classes and functions for compressing and decompressing
data using the Zstandard (or `zstd') compression algorithm. The
zstd manual@footnote{https://facebook.github.io/zstd/doc/api_manual_latest.html}
describes Zstandard as "a fast lossless compression algorithm, targeting
real-time compression scenarios at zlib-level and better compression ratios."
Also included is a file interface that supports reading and writing the
contents of @code{.zst} files created by the @code{zstd} utility, as well as
raw zstd compressed streams.

The @code{compression.zstd} module contains:


@itemize *

@item 
The @ref{2ddc,,open()} function and @ref{2ddd,,ZstdFile} class for reading and
writing compressed files.

@item 
The @ref{2dde,,ZstdCompressor} and @ref{2ddf,,ZstdDecompressor} classes for
incremental (de)compression.

@item 
一度に圧縮・展開を行う @ref{2de0,,compress()} および @ref{2de1,,decompress()} 関数。

@item 
The @ref{2de2,,train_dict()} and @ref{2de3,,finalize_dict()} functions and the
@ref{2de4,,ZstdDict} class to train and manage Zstandard dictionaries.

@item 
The @ref{2de5,,CompressionParameter}, @ref{2de6,,DecompressionParameter}, and
@ref{2de7,,Strategy} classes for setting advanced (de)compression parameters.
@end itemize

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@menu
* 例外: 例外<8>. 
* 圧縮ファイルへの読み書き:: 
* メモリ上での圧縮と展開:: 
* Zstandard dictionaries:: 
* Advanced parameter control:: 
* その他: その他<3>. 
* 使用例: 使用例<14>. 

@end menu

@node 例外<8>,圧縮ファイルへの読み書き,,compression zstd --- Compression compatible with the Zstandard format
@anchor{library/compression zstd exceptions}@anchor{2de8}
@subsubsection 例外


@geindex ZstdError
@anchor{library/compression zstd compression zstd ZstdError}@anchor{2de9}
@deffn {例外} compression.zstd.ZstdError

This exception is raised when an error occurs during compression or
decompression, or while initializing the (de)compressor state.
@end deffn

@node 圧縮ファイルへの読み書き,メモリ上での圧縮と展開,例外<8>,compression zstd --- Compression compatible with the Zstandard format
@anchor{library/compression zstd reading-and-writing-compressed-files}@anchor{2dea}
@subsubsection 圧縮ファイルへの読み書き


@geindex open() (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd open}@anchor{2ddc}
@deffn {の関数} compression.zstd.open (file, /, mode='rb', *, level=None, options=None, zstd_dict=None, encoding=None, errors=None, newline=None)

Open a Zstandard-compressed file in binary or text mode, returning a
@ref{13db,,file object}.

The `file' argument can be either a file name (given as a
@ref{169,,str}, @ref{192,,bytes} or @ref{5a1,,path-like}
object), in which case the named file is opened, or it can be an existing
file object to read from or write to.

The mode argument can be either @code{'rb'} for reading (default), @code{'wb'} for
overwriting, @code{'ab'} for appending, or @code{'xb'} for exclusive creation.
These can equivalently be given as @code{'r'}, @code{'w'}, @code{'a'}, and @code{'x'}
respectively. You may also open in text mode with @code{'rt'}, @code{'wt'},
@code{'at'}, and @code{'xt'} respectively.

When reading, the `options' argument can be a dictionary providing advanced
decompression parameters; see @ref{2de6,,DecompressionParameter} for detailed
information about supported
parameters. The `zstd_dict' argument is a @ref{2de4,,ZstdDict} instance to be
used during decompression. When reading, if the `level'
argument is not None, a @code{TypeError} will be raised.

When writing, the `options' argument can be a dictionary
providing advanced compression parameters; see
@ref{2de5,,CompressionParameter} for detailed information about supported
parameters. The `level' argument is the compression level to use when
writing compressed data. Only one of `level' or `options' may be non-None.
The `zstd_dict' argument is a @ref{2de4,,ZstdDict} instance to be used during
compression.

In binary mode, this function is equivalent to the @ref{2ddd,,ZstdFile}
constructor: @code{ZstdFile(file, mode, ...)}. In this case, the
`encoding', `errors', and `newline' parameters must not be provided.

In text mode, a @ref{2ddd,,ZstdFile} object is created, and wrapped in an
@ref{9be,,io.TextIOWrapper} instance with the specified encoding, error
handling behavior, and line endings.
@end deffn

@geindex ZstdFile (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd ZstdFile}@anchor{2ddd}
@deffn {クラス} compression.zstd.ZstdFile (file, /, mode='rb', *, level=None, options=None, zstd_dict=None)

Open a Zstandard-compressed file in binary mode.

A @ref{2ddd,,ZstdFile} can wrap an already-open @ref{13db,,file object}, or operate
directly on a named file. The `file' argument specifies either the file
object to wrap, or the name of the file to open (as a @ref{169,,str},
@ref{192,,bytes} or @ref{5a1,,path-like} object). If
wrapping an existing file object, the wrapped file will not be closed when
the @ref{2ddd,,ZstdFile} is closed.

The `mode' argument can be either @code{'rb'} for reading (default), @code{'wb'}
for overwriting, @code{'xb'} for exclusive creation, or @code{'ab'} for appending.
These can equivalently be given as @code{'r'}, @code{'w'}, @code{'x'} and @code{'a'}
respectively.

If `file' is a file object (rather than an actual file name), a mode of
@code{'w'} does not truncate the file, and is instead equivalent to @code{'a'}.

When reading, the `options' argument can be a dictionary
providing advanced decompression parameters; see
@ref{2de6,,DecompressionParameter} for detailed information about supported
parameters. The `zstd_dict' argument is a @ref{2de4,,ZstdDict} instance to be
used during decompression. When reading, if the `level'
argument is not None, a @code{TypeError} will be raised.

When writing, the `options' argument can be a dictionary
providing advanced compression parameters; see
@ref{2de5,,CompressionParameter} for detailed information about supported
parameters. The `level' argument is the compression level to use when
writing compressed data. Only one of `level' or `options' may be passed. The
`zstd_dict' argument is a @ref{2de4,,ZstdDict} instance to be used during
compression.

@code{ZstdFile} supports all the members specified by
@ref{8a3,,io.BufferedIOBase}, except for @ref{2deb,,detach()}
and @ref{1528,,truncate()}.
Iteration and the @ref{186,,with} statement are supported.

以下のメソッドと属性も提供されています:

@geindex peek() (compression.zstd.ZstdFile のメソッド)
@anchor{library/compression zstd compression zstd ZstdFile peek}@anchor{2dec}
@deffn {メソッド} peek (size=-1)

ファイル上の現在位置を変更せずにバッファのデータを返します。EOF に達しない限り、少なくとも 1 バイトが返されます。返される正確なバイト数は規定されていません (引数 `size' は無視されます)。

@cartouche
@quotation 注釈 
While calling @ref{2dec,,peek()} does not change the file position of
the @ref{2ddd,,ZstdFile}, it may change the position of the underlying
file object (for example, if the @ref{2ddd,,ZstdFile} was constructed by
passing a file object for `file').
@end quotation
@end cartouche
@end deffn

@geindex mode (compression.zstd.ZstdFile の属性)
@anchor{library/compression zstd compression zstd ZstdFile mode}@anchor{2ded}
@deffn {の属性} mode

@code{'rb'} は読み込み用、 @code{'wb'} は書き込み用です。
@end deffn

@geindex name (compression.zstd.ZstdFile の属性)
@anchor{library/compression zstd compression zstd ZstdFile name}@anchor{2dee}
@deffn {の属性} name

The name of the Zstandard file. Equivalent to the @ref{2def,,name}
attribute of the underlying @ref{13db,,file object}.
@end deffn
@end deffn

@node メモリ上での圧縮と展開,Zstandard dictionaries,圧縮ファイルへの読み書き,compression zstd --- Compression compatible with the Zstandard format
@anchor{library/compression zstd compressing-and-decompressing-data-in-memory}@anchor{2df0}
@subsubsection メモリ上での圧縮と展開


@geindex compress() (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd compress}@anchor{2de0}
@deffn {の関数} compression.zstd.compress (data, level=None, options=None, zstd_dict=None)

Compress `data' (a @ref{193,,bytes-like object}), returning the compressed
data as a @ref{192,,bytes} object.

The `level' argument is an integer controlling the level of
compression. `level' is an alternative to setting
@ref{2df1,,CompressionParameter.compression_level} in `options'. Use
@ref{2df2,,bounds()} on
@ref{2df1,,compression_level} to get the values that can
be passed for `level'. If advanced compression options are needed, the
`level' argument must be omitted and in the `options' dictionary the
@code{CompressionParameter.compression_level} parameter should be set.

The `options' argument is a Python dictionary containing advanced
compression parameters. The valid keys and values for compression parameters
are documented as part of the @ref{2de5,,CompressionParameter} documentation.

The `zstd_dict' argument is an instance of @ref{2de4,,ZstdDict}
containing trained data to improve compression efficiency. The
function @ref{2de2,,train_dict()} can be used to generate a Zstandard dictionary.
@end deffn

@geindex decompress() (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd decompress}@anchor{2de1}
@deffn {の関数} compression.zstd.decompress (data, zstd_dict=None, options=None)

Decompress `data' (a @ref{193,,bytes-like object}), returning the uncompressed
data as a @ref{192,,bytes} object.

The `options' argument is a Python dictionary containing advanced
decompression parameters. The valid keys and values for compression
parameters are documented as part of the @ref{2de6,,DecompressionParameter}
documentation.

The `zstd_dict' argument is an instance of @ref{2de4,,ZstdDict}
containing trained data used during compression. This must be
the same Zstandard dictionary used during compression.

If `data' is the concatenation of multiple distinct compressed frames,
decompress all of these frames, and return the concatenation of the results.
@end deffn

@geindex ZstdCompressor (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd ZstdCompressor}@anchor{2dde}
@deffn {クラス} compression.zstd.ZstdCompressor (level=None, options=None, zstd_dict=None)

データをインクリメンタルに圧縮する圧縮オブジェクトを作成します。

For a more convenient way of compressing a single chunk of data, see the
module-level function @ref{2de0,,compress()}.

The `level' argument is an integer controlling the level of
compression. `level' is an alternative to setting
@ref{2df1,,CompressionParameter.compression_level} in `options'. Use
@ref{2df2,,bounds()} on
@ref{2df1,,compression_level} to get the values that can
be passed for `level'. If advanced compression options are needed, the
`level' argument must be omitted and in the `options' dictionary the
@code{CompressionParameter.compression_level} parameter should be set.

The `options' argument is a Python dictionary containing advanced
compression parameters. The valid keys and values for compression parameters
are documented as part of the @ref{2de5,,CompressionParameter} documentation.

The `zstd_dict' argument is an optional instance of @ref{2de4,,ZstdDict}
containing trained data to improve compression efficiency. The
function @ref{2de2,,train_dict()} can be used to generate a Zstandard dictionary.

@geindex compress() (compression.zstd.ZstdCompressor のメソッド)
@anchor{library/compression zstd compression zstd ZstdCompressor compress}@anchor{2df3}
@deffn {メソッド} compress (data, mode=ZstdCompressor.CONTINUE)

Compress `data' (a @ref{193,,bytes-like object}), returning a @ref{192,,bytes}
object with compressed data if possible, or otherwise an empty
@code{bytes} object. Some of `data' may be buffered internally, for
use in later calls to @code{compress()} and @ref{2df4,,flush()}. The returned
data should be concatenated with the output of any previous calls to
@ref{2df3,,compress()}.

The `mode' argument is a @ref{2dde,,ZstdCompressor} attribute, either
@ref{2df5,,CONTINUE}, @ref{2df6,,FLUSH_BLOCK},
or @ref{2df7,,FLUSH_FRAME}.

When all data has been provided to the compressor, call the
@ref{2df4,,flush()} method to finish the compression process. If
@ref{2df3,,compress()} is called with `mode' set to @ref{2df7,,FLUSH_FRAME},
@ref{2df4,,flush()} should not be called, as it would write out a new empty
frame.
@end deffn

@geindex flush() (compression.zstd.ZstdCompressor のメソッド)
@anchor{library/compression zstd compression zstd ZstdCompressor flush}@anchor{2df4}
@deffn {メソッド} flush (mode=ZstdCompressor.FLUSH_FRAME)

圧縮処理を終了し、コンプレッサの内部バッファにあるあらゆるデータを格納する @ref{192,,bytes} オブジェクトを返します。

The `mode' argument is a @ref{2dde,,ZstdCompressor} attribute, either
@ref{2df6,,FLUSH_BLOCK}, or @ref{2df7,,FLUSH_FRAME}.
@end deffn

@geindex set_pledged_input_size() (compression.zstd.ZstdCompressor のメソッド)
@anchor{library/compression zstd compression zstd ZstdCompressor set_pledged_input_size}@anchor{2df8}
@deffn {メソッド} set_pledged_input_size (size)

Specify the amount of uncompressed data `size' that will be provided for
the next frame. `size' will be written into the frame header of the next
frame unless @ref{2df9,,CompressionParameter.content_size_flag} is @code{False}
or @code{0}. A size of @code{0} means that the frame is empty. If `size' is
@code{None}, the frame header will omit the frame size. Frames that include
the uncompressed data size require less memory to decompress, especially
at higher compression levels.

If @ref{2dfa,,last_mode} is not @ref{2df7,,FLUSH_FRAME}, a
@ref{2ec,,ValueError} is raised as the compressor is not at the start of
a frame. If the pledged size does not match the actual size of data
provided to @ref{2df3,,compress()}, future calls to @code{compress()} or
@ref{2df4,,flush()} may raise @ref{2de9,,ZstdError} and the last chunk of data may
be lost.

After @ref{2df4,,flush()} or @ref{2df3,,compress()} are called with mode
@ref{2df7,,FLUSH_FRAME}, the next frame will not include the frame size into
the header unless @code{set_pledged_input_size()} is called again.
@end deffn

@geindex CONTINUE (compression.zstd.ZstdCompressor の属性)
@anchor{library/compression zstd compression zstd ZstdCompressor CONTINUE}@anchor{2df5}
@deffn {の属性} CONTINUE

Collect more data for compression, which may or may not generate output
immediately. This mode optimizes the compression ratio by maximizing the
amount of data per block and frame.
@end deffn

@geindex FLUSH_BLOCK (compression.zstd.ZstdCompressor の属性)
@anchor{library/compression zstd compression zstd ZstdCompressor FLUSH_BLOCK}@anchor{2df6}
@deffn {の属性} FLUSH_BLOCK

Complete and write a block to the data stream. The data returned so far
can be immediately decompressed. Past data can still be referenced in
future blocks generated by calls to @ref{2df3,,compress()},
improving compression.
@end deffn

@geindex FLUSH_FRAME (compression.zstd.ZstdCompressor の属性)
@anchor{library/compression zstd compression zstd ZstdCompressor FLUSH_FRAME}@anchor{2df7}
@deffn {の属性} FLUSH_FRAME

Complete and write out a frame. Future data provided to
@ref{2df3,,compress()} will be written into a new frame and
`cannot' reference past data.
@end deffn

@geindex last_mode (compression.zstd.ZstdCompressor の属性)
@anchor{library/compression zstd compression zstd ZstdCompressor last_mode}@anchor{2dfa}
@deffn {の属性} last_mode

The last mode passed to either @ref{2df3,,compress()} or @ref{2df4,,flush()}.
The value can be one of @ref{2df5,,CONTINUE}, @ref{2df6,,FLUSH_BLOCK}, or
@ref{2df7,,FLUSH_FRAME}. The initial value is @ref{2df7,,FLUSH_FRAME},
signifying that the compressor is at the start of a new frame.
@end deffn
@end deffn

@geindex ZstdDecompressor (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd ZstdDecompressor}@anchor{2ddf}
@deffn {クラス} compression.zstd.ZstdDecompressor (zstd_dict=None, options=None)

データをインクリメンタルに展開するために使用できる展開オブジェクトを作成します。

For a more convenient way of decompressing an entire compressed stream at
once, see the module-level function @ref{2de1,,decompress()}.

The `options' argument is a Python dictionary containing advanced
decompression parameters. The valid keys and values for compression
parameters are documented as part of the @ref{2de6,,DecompressionParameter}
documentation.

The `zstd_dict' argument is an instance of @ref{2de4,,ZstdDict}
containing trained data used during compression. This must be
the same Zstandard dictionary used during compression.

@cartouche
@quotation 注釈 
This class does not transparently handle inputs containing multiple
compressed frames, unlike the @ref{2de1,,decompress()} function and
@ref{2ddd,,ZstdFile} class. To decompress a multi-frame input, you should
use @ref{2de1,,decompress()}, @ref{2ddd,,ZstdFile} if working with a
@ref{13db,,file object}, or multiple @code{ZstdDecompressor} instances.
@end quotation
@end cartouche

@geindex decompress() (compression.zstd.ZstdDecompressor のメソッド)
@anchor{library/compression zstd compression zstd ZstdDecompressor decompress}@anchor{2dfb}
@deffn {メソッド} decompress (data, max_length=-1)

Decompress `data' (a @ref{193,,bytes-like object}), returning
uncompressed data as bytes. Some of `data' may be buffered
internally, for use in later calls to @code{decompress()}.
The returned data should be concatenated with the output of any previous
calls to @code{decompress()}.

If `max_length' is non-negative, the method returns at most `max_length'
bytes of decompressed data. If this limit is reached and further
output can be produced, the @ref{2dfc,,needs_input} attribute will
be set to @code{False}. In this case, the next call to
@ref{2dfb,,decompress()} may provide `data' as @code{b'@w{'}} to obtain
more of the output.

入力データの全てが圧縮され返された (`max_length' バイトより少ないためか `max_length' が負のため) 場合、
@ref{2dfc,,needs_input} 属性は @code{True} になります。

Attempting to decompress data after the end of a frame will raise a
@ref{2de9,,ZstdError}. Any data found after the end of the frame is ignored
and saved in the @ref{2dfd,,unused_data} attribute.
@end deffn

@geindex eof (compression.zstd.ZstdDecompressor の属性)
@anchor{library/compression zstd compression zstd ZstdDecompressor eof}@anchor{2dfe}
@deffn {の属性} eof

ストリーム終端記号に到達した場合 @code{True} を返します。
@end deffn

@geindex unused_data (compression.zstd.ZstdDecompressor の属性)
@anchor{library/compression zstd compression zstd ZstdDecompressor unused_data}@anchor{2dfd}
@deffn {の属性} unused_data

圧縮ストリームの末尾以降に存在したデータを表します。

Before the end of the stream is reached, this will be @code{b'@w{'}}.
@end deffn

@geindex needs_input (compression.zstd.ZstdDecompressor の属性)
@anchor{library/compression zstd compression zstd ZstdDecompressor needs_input}@anchor{2dfc}
@deffn {の属性} needs_input

@code{False} if the @ref{2dfb,,decompress()} method can provide more
decompressed data before requiring new compressed input.
@end deffn
@end deffn

@node Zstandard dictionaries,Advanced parameter control,メモリ上での圧縮と展開,compression zstd --- Compression compatible with the Zstandard format
@anchor{library/compression zstd zstandard-dictionaries}@anchor{2dff}
@subsubsection Zstandard dictionaries


@geindex train_dict() (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd train_dict}@anchor{2de2}
@deffn {の関数} compression.zstd.train_dict (samples, dict_size)

Train a Zstandard dictionary, returning a @ref{2de4,,ZstdDict} instance.
Zstandard dictionaries enable more efficient compression of smaller sizes
of data, which is traditionally difficult to compress due to less
repetition. If you are compressing multiple similar groups of data (such as
similar files), Zstandard dictionaries can improve compression ratios and
speed significantly.

The `samples' argument (an iterable of @ref{192,,bytes} objects), is the
population of samples used to train the Zstandard dictionary.

The `dict_size' argument, an integer, is the maximum size (in bytes) the
Zstandard dictionary should be. The Zstandard documentation suggests an
absolute maximum of no more than 100 KB, but the maximum can often be smaller
depending on the data. Larger dictionaries generally slow down compression,
but improve compression ratios. Smaller dictionaries lead to faster
compression, but reduce the compression ratio.
@end deffn

@geindex finalize_dict() (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd finalize_dict}@anchor{2de3}
@deffn {の関数} compression.zstd.finalize_dict (zstd_dict, /, samples, dict_size, level)

An advanced function for converting a "raw content" Zstandard dictionary into
a regular Zstandard dictionary. "Raw content" dictionaries are a sequence of
bytes that do not need to follow the structure of a normal Zstandard
dictionary.

The `zstd_dict' argument is a @ref{2de4,,ZstdDict} instance with
the @ref{2e00,,dict_content} containing the raw dictionary contents.

The `samples' argument (an iterable of @ref{192,,bytes} objects), contains
sample data for generating the Zstandard dictionary.

The `dict_size' argument, an integer, is the maximum size (in bytes) the
Zstandard dictionary should be. See @ref{2de2,,train_dict()} for
suggestions on the maximum dictionary size.

The `level' argument (an integer) is the compression level expected to be
passed to the compressors using this dictionary. The dictionary information
varies for each compression level, so tuning for the proper compression
level can make compression more efficient.
@end deffn

@geindex ZstdDict (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd ZstdDict}@anchor{2de4}
@deffn {クラス} compression.zstd.ZstdDict (dict_content, /, *, is_raw=False)

A wrapper around Zstandard dictionaries. Dictionaries can be used to improve
the compression of many small chunks of data. Use @ref{2de2,,train_dict()} if you
need to train a new dictionary from sample data.

The `dict_content' argument (a @ref{193,,bytes-like object}), is the already
trained dictionary information.

The `is_raw' argument, a boolean, is an advanced parameter controlling the
meaning of `dict_content'. @code{True} means `dict_content' is a "raw content"
dictionary, without any format restrictions. @code{False} means `dict_content'
is an ordinary Zstandard dictionary, created from Zstandard functions,
for example, @ref{2de2,,train_dict()} or the external @code{zstd} CLI.

When passing a @code{ZstdDict} to a function, the
@code{as_digested_dict} and @code{as_undigested_dict} attributes can
control how the dictionary is loaded by passing them as the @code{zstd_dict}
argument, for example, @code{compress(data, zstd_dict=zd.as_digested_dict)}.
Digesting a dictionary is a costly operation that occurs when loading a
Zstandard dictionary. When making multiple calls to compression or
decompression, passing a digested dictionary will reduce the overhead of
loading the dictionary.

@quotation
Difference for compression



@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

@tab

Digested dictionary

@tab

Undigested dictionary

@item

Advanced parameters of the compressor which may be overridden by
the dictionary's parameters

@tab

@code{window_log}, @code{hash_log}, @code{chain_log}, @code{search_log},
@code{min_match}, @code{target_length}, @code{strategy},
@code{enable_long_distance_matching}, @code{ldm_hash_log},
@code{ldm_min_match}, @code{ldm_bucket_size_log}, @code{ldm_hash_rate_log},
and some non-public parameters.

@tab

None

@item

@code{ZstdDict} internally caches the dictionary

@tab

Yes. It's faster when loading a digested dictionary again with the
same compression level.

@tab

No. If you wish to load an undigested dictionary multiple times,
consider reusing a compressor object.

@end multitable

@end quotation

If passing a @code{ZstdDict} without any attribute, an undigested
dictionary is passed by default when compressing and a digested dictionary
is generated if necessary and passed by default when decompressing.

@quotation

@geindex dict_content (compression.zstd.ZstdDict の属性)
@anchor{library/compression zstd compression zstd ZstdDict dict_content}@anchor{2e00}
@deffn {の属性} dict_content

The content of the Zstandard dictionary, a @code{bytes} object. It's the
same as the `dict_content' argument in the @code{__init__} method. It can
be used with other programs, such as the @code{zstd} CLI program.
@end deffn

@geindex dict_id (compression.zstd.ZstdDict の属性)
@anchor{library/compression zstd compression zstd ZstdDict dict_id}@anchor{2e01}
@deffn {の属性} dict_id

Identifier of the Zstandard dictionary, a non-negative int value.

Non-zero means the dictionary is ordinary, created by Zstandard
functions and following the Zstandard format.

@code{0} means a "raw content" dictionary, free of any format restriction,
used for advanced users.

@cartouche
@quotation 注釈 
The meaning of @code{0} for @code{ZstdDict.dict_id} is different
from the @code{dictionary_id} attribute to the @ref{2e02,,get_frame_info()}
function.
@end quotation
@end cartouche
@end deffn

@geindex as_digested_dict (compression.zstd.ZstdDict の属性)
@anchor{library/compression zstd compression zstd ZstdDict as_digested_dict}@anchor{2e03}
@deffn {の属性} as_digested_dict

Load as a digested dictionary.
@end deffn

@geindex as_undigested_dict (compression.zstd.ZstdDict の属性)
@anchor{library/compression zstd compression zstd ZstdDict as_undigested_dict}@anchor{2e04}
@deffn {の属性} as_undigested_dict

Load as an undigested dictionary.
@end deffn
@end quotation
@end deffn

@node Advanced parameter control,その他<3>,Zstandard dictionaries,compression zstd --- Compression compatible with the Zstandard format
@anchor{library/compression zstd advanced-parameter-control}@anchor{2e05}
@subsubsection Advanced parameter control


@geindex CompressionParameter (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd CompressionParameter}@anchor{2de5}
@deffn {クラス} compression.zstd.CompressionParameter

An @ref{edb,,IntEnum} containing the advanced compression parameter
keys that can be used when compressing data.

The @ref{2df2,,bounds()} method can be used on any attribute to get the valid
values for that parameter.

Parameters are optional; any omitted parameter will have it's value selected
automatically.

Example getting the lower and upper bound of @ref{2df1,,compression_level}:

@example
lower, upper = CompressionParameter.compression_level.bounds()
@end example

Example setting the @ref{2e06,,window_log} to the maximum size:

@example
_lower, upper = CompressionParameter.window_log.bounds()
options = @{CompressionParameter.window_log: upper@}
compress(b'venezuelan beaver cheese', options=options)
@end example

@geindex bounds() (compression.zstd.CompressionParameter のメソッド)
@anchor{library/compression zstd compression zstd CompressionParameter bounds}@anchor{2df2}
@deffn {メソッド} bounds ()

Return the tuple of int bounds, @code{(lower, upper)}, of a compression
parameter. This method should be called on the attribute you wish to
retrieve the bounds of. For example, to get the valid values for
@ref{2df1,,compression_level}, one may check the result of
@code{CompressionParameter.compression_level.bounds()}.

Both the lower and upper bounds are inclusive.
@end deffn

@geindex compression_level (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter compression_level}@anchor{2df1}
@deffn {の属性} compression_level

A high-level means of setting other compression parameters that affect
the speed and ratio of compressing data.

Regular compression levels are greater than @code{0}. Values greater than
@code{20} are considered "ultra" compression and require more memory than
other levels. Negative values can be used to trade off faster compression
for worse compression ratios.

Setting the level to zero uses @ref{2e07,,COMPRESSION_LEVEL_DEFAULT}.
@end deffn

@geindex window_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter window_log}@anchor{2e06}
@deffn {の属性} window_log

Maximum allowed back-reference distance the compressor can use when
compressing data, expressed as power of two, @code{1 << window_log} bytes.
This parameter greatly influences the memory usage of compression. Higher
values require more memory but gain better compression values.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex hash_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter hash_log}@anchor{2e08}
@deffn {の属性} hash_log

Size of the initial probe table, as a power of two. The resulting memory
usage is @code{1 << (hash_log+2)} bytes. Larger tables improve compression
ratio of strategies <= @ref{2e09,,dfast}, and improve compression
speed of strategies > @ref{2e09,,dfast}.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex chain_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter chain_log}@anchor{2e0a}
@deffn {の属性} chain_log

Size of the multi-probe search table, as a power of two. The resulting
memory usage is @code{1 << (chain_log+2)} bytes. Larger tables result in
better and slower compression. This parameter has no effect for the
@ref{2e0b,,fast} strategy. It's still useful when using
@ref{2e09,,dfast} strategy, in which case it defines a secondary
probe table.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex search_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter search_log}@anchor{2e0c}
@deffn {の属性} search_log

Number of search attempts, as a power of two. More attempts result in
better and slower compression. This parameter is useless for
@ref{2e0b,,fast} and @ref{2e09,,dfast} strategies.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex min_match (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter min_match}@anchor{2e0d}
@deffn {の属性} min_match

Minimum size of searched matches. Larger values increase compression and
decompression speed, but decrease ratio. Note that Zstandard can still
find matches of smaller size, it just tweaks its search algorithm to look
for this size and larger. For all strategies < @ref{2e0e,,btopt},
the effective minimum is @code{4}; for all strategies
> @ref{2e0b,,fast}, the effective maximum is @code{6}.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex target_length (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter target_length}@anchor{2e0f}
@deffn {の属性} target_length

The impact of this field depends on the selected @ref{2de7,,Strategy}.

For strategies @ref{2e0e,,btopt}, @ref{2e10,,btultra} and
@ref{2e11,,btultra2}, the value is the length of a match
considered "good enough" to stop searching. Larger values make
compression ratios better, but compresses slower.

For strategy @ref{2e0b,,fast}, it is the distance between match
sampling. Larger values make compression faster, but with a worse
compression ratio.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex strategy (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter strategy}@anchor{2e12}
@deffn {の属性} strategy

The higher the value of selected strategy, the more complex the
compression technique used by zstd, resulting in higher compression
ratios but slower compression.


@subsubheading 参考


@ref{2de7,,Strategy}

@end deffn

@geindex enable_long_distance_matching (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter enable_long_distance_matching}@anchor{2e13}
@deffn {の属性} enable_long_distance_matching

Long distance matching can be used to improve compression for large
inputs by finding large matches at greater distances. It increases memory
usage and window size.

@code{True} or @code{1} enable long distance matching while @code{False} or @code{0}
disable it.

Enabling this parameter increases default
@ref{2e06,,window_log} to 128 MiB except when expressly
set to a different value. This setting is enabled by default if
@code{window_log} >= 128 MiB and the compression
strategy >= @ref{2e0e,,btopt} (compression level 16+).
@end deffn

@geindex ldm_hash_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter ldm_hash_log}@anchor{2e14}
@deffn {の属性} ldm_hash_log

Size of the table for long distance matching, as a power of two. Larger
values increase memory usage and compression ratio, but decrease
compression speed.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex ldm_min_match (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter ldm_min_match}@anchor{2e15}
@deffn {の属性} ldm_min_match

Minimum match size for long distance matcher. Larger or too small values
can often decrease the compression ratio.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex ldm_bucket_size_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter ldm_bucket_size_log}@anchor{2e16}
@deffn {の属性} ldm_bucket_size_log

Log size of each bucket in the long distance matcher hash table for
collision resolution. Larger values improve collision resolution but
decrease compression speed.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex ldm_hash_rate_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter ldm_hash_rate_log}@anchor{2e17}
@deffn {の属性} ldm_hash_rate_log

Frequency of inserting/looking up entries into the long distance matcher
hash table. Larger values improve compression speed. Deviating far from
the default value will likely result in a compression ratio decrease.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex content_size_flag (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter content_size_flag}@anchor{2df9}
@deffn {の属性} content_size_flag

Write the size of the data to be compressed into the Zstandard frame
header when known prior to compressing.

This flag only takes effect under the following scenarios:


@itemize *

@item 
Calling @ref{2de0,,compress()} for one-shot compression

@item 
Providing all of the data to be compressed in the frame in a single
@ref{2df3,,ZstdCompressor.compress()} call, with the
@ref{2df7,,ZstdCompressor.FLUSH_FRAME} mode.

@item 
Calling @ref{2df8,,ZstdCompressor.set_pledged_input_size()} with the exact
amount of data that will be provided to the compressor prior to any
calls to @ref{2df3,,ZstdCompressor.compress()} for the current frame.
@code{ZstdCompressor.set_pledged_input_size()} must be called for each
new frame.
@end itemize

All other compression calls may not write the size information into the
frame header.

@code{True} or @code{1} enable the content size flag while @code{False} or @code{0}
disable it.
@end deffn

@geindex checksum_flag (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter checksum_flag}@anchor{2e18}
@deffn {の属性} checksum_flag

A four-byte checksum using XXHash64 of the uncompressed content is
written at the end of each frame. Zstandard's decompression code verifies
the checksum. If there is a mismatch a @ref{2de9,,ZstdError} exception is
raised.

@code{True} or @code{1} enable checksum generation while @code{False} or @code{0}
disable it.
@end deffn

@geindex dict_id_flag (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter dict_id_flag}@anchor{2e19}
@deffn {の属性} dict_id_flag

When compressing with a @ref{2de4,,ZstdDict}, the dictionary's ID is written
into the frame header.

@code{True} or @code{1} enable storing the dictionary ID while @code{False} or
@code{0} disable it.
@end deffn

@geindex nb_workers (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter nb_workers}@anchor{2e1a}
@deffn {の属性} nb_workers

Select how many threads will be spawned to compress in parallel. When
@code{nb_workers} > 0, enables multi-threaded compression, a value of
@code{1} means "one-thread multi-threaded mode". More workers improve speed,
but also increase memory usage and slightly reduce compression ratio.

A value of zero disables multi-threading.
@end deffn

@geindex job_size (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter job_size}@anchor{2e1b}
@deffn {の属性} job_size

Size of a compression job, in bytes. This value is enforced only when
@ref{2e1a,,nb_workers} >= 1. Each compression job is
completed in parallel, so this value can indirectly impact the number of
active threads.

A value of zero causes the value to be selected automatically.
@end deffn

@geindex overlap_log (compression.zstd.CompressionParameter の属性)
@anchor{library/compression zstd compression zstd CompressionParameter overlap_log}@anchor{2e1c}
@deffn {の属性} overlap_log

Sets how much data is reloaded from previous jobs (threads) for new jobs
to be used by the look behind window during compression. This value is
only used when @ref{2e1a,,nb_workers} >= 1. Acceptable
values vary from 0 to 9.

@quotation


@itemize *

@item 
0 means dynamically set the overlap amount

@item 
1 means no overlap

@item 
9 means use a full window size from the previous job
@end itemize
@end quotation

Each increment halves/doubles the overlap size. "8" means an overlap of
@code{window_size/2}, "7" means an overlap of @code{window_size/4}, etc.
@end deffn
@end deffn

@geindex DecompressionParameter (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd DecompressionParameter}@anchor{2de6}
@deffn {クラス} compression.zstd.DecompressionParameter

An @ref{edb,,IntEnum} containing the advanced decompression parameter
keys that can be used when decompressing data. Parameters are optional; any
omitted parameter will have it's value selected automatically.

The @ref{2e1d,,bounds()} method can be used on any attribute to get the valid
values for that parameter.

Example setting the @ref{2e1e,,window_log_max} to the maximum size:

@example
data = compress(b'Some very long buffer of bytes...')

_lower, upper = DecompressionParameter.window_log_max.bounds()

options = @{DecompressionParameter.window_log_max: upper@}
decompress(data, options=options)
@end example

@geindex bounds() (compression.zstd.DecompressionParameter のメソッド)
@anchor{library/compression zstd compression zstd DecompressionParameter bounds}@anchor{2e1d}
@deffn {メソッド} bounds ()

Return the tuple of int bounds, @code{(lower, upper)}, of a decompression
parameter. This method should be called on the attribute you wish to
retrieve the bounds of.

Both the lower and upper bounds are inclusive.
@end deffn

@geindex window_log_max (compression.zstd.DecompressionParameter の属性)
@anchor{library/compression zstd compression zstd DecompressionParameter window_log_max}@anchor{2e1e}
@deffn {の属性} window_log_max

The base-two logarithm of the maximum size of the window used during
decompression. This can be useful to limit the amount of memory used when
decompressing data. A larger maximum window size leads to faster
decompression.

A value of zero causes the value to be selected automatically.
@end deffn
@end deffn

@geindex Strategy (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd Strategy}@anchor{2de7}
@deffn {クラス} compression.zstd.Strategy

An @ref{edb,,IntEnum} containing strategies for compression.
Higher-numbered strategies correspond to more complex and slower
compression.

@cartouche
@quotation 注釈 
The values of attributes of @code{Strategy} are not necessarily stable
across zstd versions. Only the ordering of the attributes may be relied
upon. The attributes are listed below in order.
@end quotation
@end cartouche

The following strategies are available:

@geindex fast (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy fast}@anchor{2e0b}
@deffn {の属性} fast
@end deffn

@geindex dfast (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy dfast}@anchor{2e09}
@deffn {の属性} dfast
@end deffn

@geindex greedy (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy greedy}@anchor{2e1f}
@deffn {の属性} greedy
@end deffn

@geindex lazy (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy lazy}@anchor{2e20}
@deffn {の属性} lazy
@end deffn

@geindex lazy2 (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy lazy2}@anchor{2e21}
@deffn {の属性} lazy2
@end deffn

@geindex btlazy2 (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy btlazy2}@anchor{2e22}
@deffn {の属性} btlazy2
@end deffn

@geindex btopt (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy btopt}@anchor{2e0e}
@deffn {の属性} btopt
@end deffn

@geindex btultra (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy btultra}@anchor{2e10}
@deffn {の属性} btultra
@end deffn

@geindex btultra2 (compression.zstd.Strategy の属性)
@anchor{library/compression zstd compression zstd Strategy btultra2}@anchor{2e11}
@deffn {の属性} btultra2
@end deffn
@end deffn

@node その他<3>,使用例<14>,Advanced parameter control,compression zstd --- Compression compatible with the Zstandard format
@anchor{library/compression zstd miscellaneous}@anchor{2e23}
@subsubsection その他


@geindex get_frame_info() (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd get_frame_info}@anchor{2e02}
@deffn {の関数} compression.zstd.get_frame_info (frame_buffer)

Retrieve a @ref{2e24,,FrameInfo} object containing metadata about a Zstandard
frame. Frames contain metadata related to the compressed data they hold.
@end deffn

@geindex FrameInfo (compression.zstd のクラス)
@anchor{library/compression zstd compression zstd FrameInfo}@anchor{2e24}
@deffn {クラス} compression.zstd.FrameInfo

Metadata related to a Zstandard frame.

@geindex decompressed_size (compression.zstd.FrameInfo の属性)
@anchor{library/compression zstd compression zstd FrameInfo decompressed_size}@anchor{2e25}
@deffn {の属性} decompressed_size

The size of the decompressed contents of the frame.
@end deffn

@geindex dictionary_id (compression.zstd.FrameInfo の属性)
@anchor{library/compression zstd compression zstd FrameInfo dictionary_id}@anchor{2e26}
@deffn {の属性} dictionary_id

An integer representing the Zstandard dictionary ID needed for
decompressing the frame. @code{0} means the dictionary ID was not
recorded in the frame header. This may mean that a Zstandard dictionary
is not needed, or that the ID of a required dictionary was not recorded.
@end deffn
@end deffn

@geindex COMPRESSION_LEVEL_DEFAULT (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd COMPRESSION_LEVEL_DEFAULT}@anchor{2e07}
@deffn {の属性} compression.zstd.COMPRESSION_LEVEL_DEFAULT

The default compression level for Zstandard: @code{3}.
@end deffn

@geindex zstd_version_info (compression.zstd モジュール)
@anchor{library/compression zstd compression zstd zstd_version_info}@anchor{2e27}
@deffn {の属性} compression.zstd.zstd_version_info

Version number of the runtime zstd library as a tuple of integers
(major, minor, release).
@end deffn

@node 使用例<14>,,その他<3>,compression zstd --- Compression compatible with the Zstandard format
@anchor{library/compression zstd examples}@anchor{2e28}
@subsubsection 使用例


Reading in a compressed file:

@example
from compression import zstd

with zstd.open("file.zst") as f:
    file_content = f.read()
@end example

Creating a compressed file:

@example
from compression import zstd

data = b"Insert Data Here"
with zstd.open("file.zst", "w") as f:
    f.write(data)
@end example

Compressing data in memory:

@example
from compression import zstd

data_in = b"Insert Data Here"
data_out = zstd.compress(data_in)
@end example

Incremental compression:

@example
from compression import zstd

comp = zstd.ZstdCompressor()
out1 = comp.compress(b"Some data\n")
out2 = comp.compress(b"Another piece of data\n")
out3 = comp.compress(b"Even more data\n")
out4 = comp.flush()
# Concatenate all the partial results:
result = b"".join([out1, out2, out3, out4])
@end example

Writing compressed data to an already-open file:

@example
from compression import zstd

with open("myfile", "wb") as f:
    f.write(b"This data will not be compressed\n")
    with zstd.open(f, "w") as zstf:
        zstf.write(b"This *will* be compressed\n")
    f.write(b"Not compressed\n")
@end example

Creating a compressed file using compression parameters:

@example
from compression import zstd

options = @{
   zstd.CompressionParameter.checksum_flag: 1
@}
with zstd.open("file.zst", "w", options=options) as f:
    f.write(b"Mind if I squeeze in?")
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node zlib --- gzip 互換の圧縮,gzip --- gzip ファイルのサポート,compression zstd --- Compression compatible with the Zstandard format,データ圧縮とアーカイブ
@anchor{library/zlib doc}@anchor{2e29}@anchor{library/zlib module-zlib}@anchor{139}@anchor{library/zlib translation-repo}@anchor{2e2a}@anchor{library/zlib zlib-compression-compatible-with-gzip}@anchor{2e2b}
@subsection @code{zlib} --- @code{gzip} 互換の圧縮


@geindex module; zlib


__________________________________________________________________


For applications that require data compression, the functions in this module
allow compression and decompression, using the zlib library@footnote{https://www.zlib.net}.

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

zlib's functions have many options and often need to be used in a particular
order.  This documentation doesn't attempt to cover all of the permutations;
consult the zlib manual@footnote{https://www.zlib.net/manual.html} for authoritative
information.

@code{.gz} ファイルの読み書きのためには、 @ref{6b,,gzip} モジュールを参照してください。

このモジュールで利用可能な例外と関数を以下に示します:

@geindex error
@anchor{library/zlib zlib error}@anchor{2e2c}
@deffn {例外} zlib.error

圧縮および展開時のエラーによって送出される例外です。
@end deffn

@geindex adler32() (zlib モジュール)
@anchor{library/zlib zlib adler32}@anchor{1bba}
@deffn {の関数} zlib.adler32 (data[, value])

`data' の Adler-32 チェックサムを計算します (Adler-32 チェックサムは、おおむね CRC32 と同等の信頼性を持ちながら、はるかに高速に計算できます)。結果は、符号のない 32 ビットの整数です。 `value' が与えられている場合、チェックサム計算の初期値として使われます。与えられていない場合、デフォルト値の 1 が使われます。 `value' を与えることで、複数の入力を結合したデータ全体にわたり、通しのチェックサムを計算できます。このアルゴリズムは暗号論的には強力ではなく、認証やデジタル署名などに用いるべきではありません。また、チェックサムアルゴリズムとして設計されているため、汎用のハッシュアルゴリズムには向きません。


バージョン 3.0 で変更: The result is always unsigned.

@end deffn

@geindex compress() (zlib モジュール)
@anchor{library/zlib zlib compress}@anchor{84f}
@deffn {の関数} zlib.compress (data, /, level=Z_DEFAULT_COMPRESSION, wbits=MAX_WBITS)

Compresses the bytes in `data', returning a bytes object containing compressed data.
`level' is an integer from @code{0} to @code{9} or @code{-1} controlling the level of compression;
See @ref{2e2d,,Z_BEST_SPEED} (@code{1}), @ref{2e2e,,Z_BEST_COMPRESSION} (@code{9}),
@ref{2e2f,,Z_NO_COMPRESSION} (@code{0}), and the default,
@ref{2e30,,Z_DEFAULT_COMPRESSION} (@code{-1}) for more information about these values.
@anchor{library/zlib compress-wbits}@anchor{2e31}
The `wbits' argument controls the size of the history buffer (or the
"window size") used when compressing data, and whether a header and
trailer is included in the output.  It can take several ranges of values,
defaulting to @code{15} (@ref{2e32,,MAX_WBITS}):


@itemize *

@item 
+9 to +15: The base-two logarithm of the window size, which
therefore ranges between 512 and 32768.  Larger values produce
better compression at the expense of greater memory usage.  The
resulting output will include a zlib-specific header and trailer.

@item 
−9 to −15: Uses the absolute value of `wbits' as the
window size logarithm, while producing a raw output stream with no
header or trailing checksum.

@item 
+25 to +31 = 16 + (9 to 15): Uses the low 4 bits of the value as the
window size logarithm, while including a basic @code{gzip} header
and trailing checksum in the output.
@end itemize

Raises the @ref{2e2c,,error} exception if any error occurs.


バージョン 3.6 で変更: `level' can now be used as a keyword parameter.



バージョン 3.11 で変更: The `wbits' parameter is now available to set window bits and
compression type.

@end deffn

@geindex compressobj() (zlib モジュール)
@anchor{library/zlib zlib compressobj}@anchor{2e33}
@deffn {の関数} zlib.compressobj (level=Z_DEFAULT_COMPRESSION, method=DEFLATED, wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict])

一度にメモリ上に置くことができないようなデータストリームを圧縮するための圧縮オブジェクトを返します。

`level' is the compression level -- an integer from @code{0} to @code{9} or @code{-1}.
See @ref{2e2d,,Z_BEST_SPEED} (@code{1}), @ref{2e2e,,Z_BEST_COMPRESSION} (@code{9}),
@ref{2e2f,,Z_NO_COMPRESSION} (@code{0}), and the default,
@ref{2e30,,Z_DEFAULT_COMPRESSION} (@code{-1}) for more information about these values.

`method' は圧縮アルゴリズムです。現在、 @ref{2e34,,DEFLATED} のみサポートされています。

The `wbits' parameter controls the size of the history buffer (or the
"window size"), and what header and trailer format will be used. It has
the same meaning as @ref{2e31,,described for compress()}.

`memLevel' 引数は内部圧縮状態用に使用されるメモリ量を制御します。有効な値は @code{1} から @code{9} です。大きい値ほど多くのメモリを消費しますが、より速く、より小さな出力を作成します。

`strategy' is used to tune the compression algorithm. Possible values are
@ref{2e35,,Z_DEFAULT_STRATEGY}, @ref{2e36,,Z_FILTERED}, @ref{2e37,,Z_HUFFMAN_ONLY},
@ref{2e38,,Z_RLE} and @ref{2e39,,Z_FIXED}.

`zdict' は定義済み圧縮辞書です。これは圧縮されるデータ内で繰り返し現れると予想されるサブシーケンスを含む (@ref{192,,bytes} オブジェクトのような) バイト列のシーケンスです。最も一般的と思われるサブシーケンスは辞書の末尾に来なければなりません。


バージョン 3.3 で変更: `zdict' パラメータとキーワード引数のサポートが追加されました。

@end deffn

@geindex crc32() (zlib モジュール)
@anchor{library/zlib zlib crc32}@anchor{1a10}
@deffn {の関数} zlib.crc32 (data[, value])

@geindex CRC
@geindex チェックサム;CRC

`data' の CRC (Cyclic Redundancy Check, 巡回冗長検査) チェックサムを計算します。結果は、符号のない 32 ビットの整数です。 `value' が与えられている場合、チェックサム計算の初期値として使われます。与えられていない場合、デフォルト値の 0 が使われます。 `value' を与えることで、複数の入力を結合したデータ全体にわたり、通しのチェックサムを計算できます。このアルゴリズムは暗号論的には強力ではなく、認証やデジタル署名などに用いるべきではありません。また、チェックサムアルゴリズムとして設計されているため、汎用のハッシュアルゴリズムには向きません。


バージョン 3.0 で変更: The result is always unsigned.

@end deffn

@geindex decompress() (zlib モジュール)
@anchor{library/zlib zlib decompress}@anchor{f09}
@deffn {の関数} zlib.decompress (data, /, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE)

Decompresses the bytes in `data', returning a bytes object containing the
uncompressed data.  The `wbits' parameter depends on
the format of `data', and is discussed further below.
If `bufsize' is given, it is used as the initial size of the output
buffer.  Raises the @ref{2e2c,,error} exception if any error occurs.
@anchor{library/zlib decompress-wbits}@anchor{2e3a}
The `wbits' parameter controls the size of the history buffer
(or "window size"), and what header and trailer format is expected.
It is similar to the parameter for @ref{2e33,,compressobj()}, but accepts
more ranges of values:


@itemize *

@item 
+8 to +15: The base-two logarithm of the window size.  The input
must include a zlib header and trailer.

@item 
0: Automatically determine the window size from the zlib header.
Only supported since zlib 1.2.3.5.

@item 
−8 to −15: Uses the absolute value of `wbits' as the window size
logarithm.  The input must be a raw stream with no header or trailer.

@item 
+24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as
the window size logarithm.  The input must include a gzip header and
trailer.

@item 
+40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as
the window size logarithm, and automatically accepts either
the zlib or gzip format.
@end itemize

When decompressing a stream, the window size must not be smaller
than the size originally used to compress the stream; using a too-small
value may result in an @ref{2e2c,,error} exception. The default `wbits' value
corresponds to the largest window size and requires a zlib header and
trailer to be included.

`bufsize' は展開されたデータを保持するためのバッファサイズの初期値です。バッファの空きは必要に応じて必要なだけ増加するので、必ずしも正確な値を指定する必要はありません。この値のチューニングでできることは、@code{malloc()} が呼ばれる回数を数回減らすことぐらいです。


バージョン 3.6 で変更: `wbits' and `bufsize' can be used as keyword arguments.

@end deffn

@geindex decompressobj() (zlib モジュール)
@anchor{library/zlib zlib decompressobj}@anchor{2e3b}
@deffn {の関数} zlib.decompressobj (wbits=MAX_WBITS[, zdict])

一度にメモリ上に置くことができないようなデータストリームを展開するための展開オブジェクトを返します。

The `wbits' parameter controls the size of the history buffer (or the
"window size"), and what header and trailer format is expected.  It has
the same meaning as @ref{2e3a,,described for decompress()}.

`zdict' パラメータには定義済み圧縮辞書を指定します。このパラメータを指定する場合、展開するデータを圧縮した際に使用した辞書と同じものでなければなりません。

@cartouche
@quotation 注釈 
`zdict' が (@ref{344,,bytearray} のような) 変更可能オブジェクトの場合、@ref{2e3b,,decompressobj()} の呼び出しとデコンプレッサの @code{decompress()} メソッドの最初の呼び出しの間に辞書の内容を変更してはいけません。
@end quotation
@end cartouche


バージョン 3.3 で変更: パラメータに `zdict' を追加しました。

@end deffn

圧縮オブジェクトは以下のメソッドをサポートしています:

@geindex compress() (zlib.Compress のメソッド)
@anchor{library/zlib zlib Compress compress}@anchor{2e3c}
@deffn {メソッド} Compress.compress (data)

`data' を圧縮し、圧縮されたデータを含むバイト列オブジェクトを返します。この文字列は少なくとも `data' の一部分のデータに対する圧縮データを含みます。このデータは以前に呼んだ @ref{84f,,compress()} が返した出力と結合することができます。入力の一部は以後の処理のために内部バッファに保存されることもあります。
@end deffn

@geindex flush() (zlib.Compress のメソッド)
@anchor{library/zlib zlib Compress flush}@anchor{2e3d}
@deffn {メソッド} Compress.flush ([mode])

All pending input is processed, and a bytes object containing the remaining compressed
output is returned.  `mode' can be selected from the constants
@ref{2e3e,,Z_NO_FLUSH}, @ref{2e3f,,Z_PARTIAL_FLUSH}, @ref{2e40,,Z_SYNC_FLUSH},
@ref{2e41,,Z_FULL_FLUSH}, @ref{2e42,,Z_BLOCK}, or @ref{2e43,,Z_FINISH},
defaulting to @ref{2e43,,Z_FINISH}.  Except @ref{2e43,,Z_FINISH}, all constants
allow compressing further bytestrings of data, while @ref{2e43,,Z_FINISH} finishes the
compressed stream and prevents compressing any more data.  After calling @ref{2e3d,,flush()}
with `mode' set to @ref{2e43,,Z_FINISH}, the @ref{84f,,compress()} method cannot be called again;
the only realistic action is to delete the object.
@end deffn

@geindex copy() (zlib.Compress のメソッド)
@anchor{library/zlib zlib Compress copy}@anchor{2e44}
@deffn {メソッド} Compress.copy ()

圧縮オブジェクトのコピーを返します。これを使うと先頭部分が共通している複数のデータを効率的に圧縮することができます。
@end deffn


バージョン 3.8 で変更: Added @ref{757,,copy.copy()} and @ref{d65,,copy.deepcopy()} support to compression
objects.


展開オブジェクトは以下のメソッドと属性をサポートしています:

@geindex unused_data (zlib.Decompress の属性)
@anchor{library/zlib zlib Decompress unused_data}@anchor{2e45}
@deffn {の属性} Decompress.unused_data

圧縮データの末尾より後のバイト列が入ったバイト列オブジェクトです。すなわち、この値は圧縮データの入っているバイト列の最後の文字が利用可能になるまでは @code{b""} のままとなります。入力バイト文字列すべてが圧縮データを含んでいた場合、この属性は @code{b""} 、すなわち空バイト列になります。
@end deffn

@geindex unconsumed_tail (zlib.Decompress の属性)
@anchor{library/zlib zlib Decompress unconsumed_tail}@anchor{2e46}
@deffn {の属性} Decompress.unconsumed_tail

展開されたデータを収めるバッファの長さ制限を超えたために、直近の @ref{f09,,decompress()} 呼び出しで処理しきれなかったデータを含むバイト列オブジェクトです。このデータはまだ zlib 側からは見えていないので、正しい展開出力を得るには以降の @ref{f09,,decompress()} メソッド呼び出しに (場合によっては後続のデータが追加された) データを差し戻さなければなりません。
@end deffn

@geindex eof (zlib.Decompress の属性)
@anchor{library/zlib zlib Decompress eof}@anchor{1385}
@deffn {の属性} Decompress.eof

圧縮データストリームの終了に達したかどうかを示すブール値です。

これは、正常な形式の圧縮ストリームと、不完全あるいは切り詰められたストリームとを区別することを可能にします。


Added in version 3.3.

@end deffn

@geindex decompress() (zlib.Decompress のメソッド)
@anchor{library/zlib zlib Decompress decompress}@anchor{2e47}
@deffn {メソッド} Decompress.decompress (data, max_length=0)

`data' を展開し、少なくとも `string' の一部分に対応する展開されたデータを含むバイト列オブジェクトを返します。このデータは以前に @ref{f09,,decompress()} メソッドを呼んだ時に返された出力と結合することができます。入力データの一部分が以後の処理のために内部バッファに保存されることもあります。

オプションパラメータ `max_length' が非ゼロの場合、返される展開データの長さが `max_length' 以下に制限されます。このことは入力した圧縮データの全てが処理されるとは限らないことを意味し、処理されなかったデータは @ref{2e46,,unconsumed_tail} 属性に保存されます。展開処理を継続する場合、この保存されたバイト文字列を以降の @ref{f09,,decompress()} 呼び出しに渡さなくてはなりません。 `max_length' が 0 の場合、全ての入力が展開され、 @ref{2e46,,unconsumed_tail} 属性は空になります。


バージョン 3.6 で変更: `max_length' can be used as a keyword argument.

@end deffn

@geindex flush() (zlib.Decompress のメソッド)
@anchor{library/zlib zlib Decompress flush}@anchor{2e48}
@deffn {メソッド} Decompress.flush ([length])

未処理の入力データをすべて処理し、最終的に圧縮されなかった残りの出力バイト列オブジェクトを返します。@ref{2e48,,flush()} を呼んだ後、@ref{f09,,decompress()} を再度呼ぶべきではありません。このときできる唯一の現実的な操作はオブジェクトの削除だけです。

オプション引数 `length' には出力バッファの初期サイズを指定します。
@end deffn

@geindex copy() (zlib.Decompress のメソッド)
@anchor{library/zlib zlib Decompress copy}@anchor{2e49}
@deffn {メソッド} Decompress.copy ()

展開オブジェクトのコピーを返します。これを使うとデータストリームの途中にある展開オブジェクトの状態を保存でき、未来のある時点で行なわれるストリームのランダムなシークをスピードアップするのに利用できます。
@end deffn


バージョン 3.8 で変更: Added @ref{757,,copy.copy()} and @ref{d65,,copy.deepcopy()} support to decompression
objects.


The following constants are available to configure compression and decompression
behavior:

@geindex DEFLATED (zlib モジュール)
@anchor{library/zlib zlib DEFLATED}@anchor{2e34}
@deffn {データ} zlib.DEFLATED

The deflate compression method.
@end deffn

@geindex MAX_WBITS (zlib モジュール)
@anchor{library/zlib zlib MAX_WBITS}@anchor{2e32}
@deffn {データ} zlib.MAX_WBITS

The maximum window size, expressed as a power of 2.
For example, if @code{MAX_WBITS} is @code{15} it results in a window size
of @code{32 KiB}.
@end deffn

@geindex DEF_MEM_LEVEL (zlib モジュール)
@anchor{library/zlib zlib DEF_MEM_LEVEL}@anchor{2e4a}
@deffn {データ} zlib.DEF_MEM_LEVEL

The default memory level for compression objects.
@end deffn

@geindex DEF_BUF_SIZE (zlib モジュール)
@anchor{library/zlib zlib DEF_BUF_SIZE}@anchor{2e4b}
@deffn {データ} zlib.DEF_BUF_SIZE

The default buffer size for decompression operations.
@end deffn

@geindex Z_NO_COMPRESSION (zlib モジュール)
@anchor{library/zlib zlib Z_NO_COMPRESSION}@anchor{2e2f}
@deffn {データ} zlib.Z_NO_COMPRESSION

Compression level @code{0}; no compression.


Added in version 3.6.

@end deffn

@geindex Z_BEST_SPEED (zlib モジュール)
@anchor{library/zlib zlib Z_BEST_SPEED}@anchor{2e2d}
@deffn {データ} zlib.Z_BEST_SPEED

Compression level @code{1}; fastest and produces the least compression.
@end deffn

@geindex Z_BEST_COMPRESSION (zlib モジュール)
@anchor{library/zlib zlib Z_BEST_COMPRESSION}@anchor{2e2e}
@deffn {データ} zlib.Z_BEST_COMPRESSION

Compression level @code{9}; slowest and produces the most compression.
@end deffn

@geindex Z_DEFAULT_COMPRESSION (zlib モジュール)
@anchor{library/zlib zlib Z_DEFAULT_COMPRESSION}@anchor{2e30}
@deffn {データ} zlib.Z_DEFAULT_COMPRESSION

Default compression level (@code{-1}); a compromise between speed and
compression. Currently equivalent to compression level @code{6}.
@end deffn

@geindex Z_DEFAULT_STRATEGY (zlib モジュール)
@anchor{library/zlib zlib Z_DEFAULT_STRATEGY}@anchor{2e35}
@deffn {データ} zlib.Z_DEFAULT_STRATEGY

Default compression strategy, for normal data.
@end deffn

@geindex Z_FILTERED (zlib モジュール)
@anchor{library/zlib zlib Z_FILTERED}@anchor{2e36}
@deffn {データ} zlib.Z_FILTERED

Compression strategy for data produced by a filter (or predictor).
@end deffn

@geindex Z_HUFFMAN_ONLY (zlib モジュール)
@anchor{library/zlib zlib Z_HUFFMAN_ONLY}@anchor{2e37}
@deffn {データ} zlib.Z_HUFFMAN_ONLY

Compression strategy that forces Huffman coding only.
@end deffn

@geindex Z_RLE (zlib モジュール)
@anchor{library/zlib zlib Z_RLE}@anchor{2e38}
@deffn {データ} zlib.Z_RLE

Compression strategy that limits match distances to one (run-length encoding).

This constant is only available if Python was compiled with zlib
1.2.0.1 or greater.


Added in version 3.6.

@end deffn

@geindex Z_FIXED (zlib モジュール)
@anchor{library/zlib zlib Z_FIXED}@anchor{2e39}
@deffn {データ} zlib.Z_FIXED

Compression strategy that prevents the use of dynamic Huffman codes.

This constant is only available if Python was compiled with zlib
1.2.2.2 or greater.


Added in version 3.6.

@end deffn

@geindex Z_NO_FLUSH (zlib モジュール)
@anchor{library/zlib zlib Z_NO_FLUSH}@anchor{2e3e}
@deffn {データ} zlib.Z_NO_FLUSH

Flush mode @code{0}. No special flushing behavior.


Added in version 3.6.

@end deffn

@geindex Z_PARTIAL_FLUSH (zlib モジュール)
@anchor{library/zlib zlib Z_PARTIAL_FLUSH}@anchor{2e3f}
@deffn {データ} zlib.Z_PARTIAL_FLUSH

Flush mode @code{1}. Flush as much output as possible.
@end deffn

@geindex Z_SYNC_FLUSH (zlib モジュール)
@anchor{library/zlib zlib Z_SYNC_FLUSH}@anchor{2e40}
@deffn {データ} zlib.Z_SYNC_FLUSH

Flush mode @code{2}. All output is flushed and the output is aligned to a byte boundary.
@end deffn

@geindex Z_FULL_FLUSH (zlib モジュール)
@anchor{library/zlib zlib Z_FULL_FLUSH}@anchor{2e41}
@deffn {データ} zlib.Z_FULL_FLUSH

Flush mode @code{3}. All output is flushed and the compression state is reset.
@end deffn

@geindex Z_FINISH (zlib モジュール)
@anchor{library/zlib zlib Z_FINISH}@anchor{2e43}
@deffn {データ} zlib.Z_FINISH

Flush mode @code{4}. All pending input is processed, no more input is expected.
@end deffn

@geindex Z_BLOCK (zlib モジュール)
@anchor{library/zlib zlib Z_BLOCK}@anchor{2e42}
@deffn {データ} zlib.Z_BLOCK

Flush mode @code{5}. A deflate block is completed and emitted.

This constant is only available if Python was compiled with zlib
1.2.2.2 or greater.


Added in version 3.6.

@end deffn

@geindex Z_TREES (zlib モジュール)
@anchor{library/zlib zlib Z_TREES}@anchor{2e4c}
@deffn {データ} zlib.Z_TREES

Flush mode @code{6}, for inflate operations. Instructs inflate to return when
it gets to the next deflate block boundary.

This constant is only available if Python was compiled with zlib
1.2.3.4 or greater.


Added in version 3.6.

@end deffn

使用している zlib ライブラリのバージョン情報を以下の定数で確認できます:

@geindex ZLIB_VERSION (zlib モジュール)
@anchor{library/zlib zlib ZLIB_VERSION}@anchor{2e4d}
@deffn {データ} zlib.ZLIB_VERSION

モジュールのビルド時に使用された zlib ライブラリのバージョン文字列です。これは @ref{1386,,ZLIB_RUNTIME_VERSION} で確認できる、実行時に使用している実際の zlib ライブラリのバージョンとは異なる場合があります。
@end deffn

@geindex ZLIB_RUNTIME_VERSION (zlib モジュール)
@anchor{library/zlib zlib ZLIB_RUNTIME_VERSION}@anchor{1386}
@deffn {データ} zlib.ZLIB_RUNTIME_VERSION

インタプリタが読み込んだ実際の zlib ライブラリのバージョン文字列です。


Added in version 3.3.

@end deffn

@geindex ZLIBNG_VERSION (zlib モジュール)
@anchor{library/zlib zlib ZLIBNG_VERSION}@anchor{2e4e}
@deffn {データ} zlib.ZLIBNG_VERSION

The version string of the zlib-ng library that was used for building the
module if zlib-ng was used. When present, the @ref{2e4d,,ZLIB_VERSION} and
@ref{1386,,ZLIB_RUNTIME_VERSION} constants reflect the version of the zlib API
provided by zlib-ng.

If zlib-ng was not used to build the module, this constant will be absent.


Added in version 3.14.

@end deffn


@subsubheading 参考



@table @asis

@item @ref{6b,,gzip} モジュール

@code{gzip} 形式ファイルへの読み書きを行うモジュール。

@item @indicateurl{https://www.zlib.net}

zlib ライブラリホームページ。

@item @indicateurl{https://www.zlib.net/manual.html}

zlib ライブラリの多くの関数の意味と使い方を解説したマニュアル。
@end table

In case gzip (de)compression is a bottleneck, the python-isal@footnote{https://github.com/pycompression/python-isal}
package speeds up (de)compression with a mostly compatible API.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node gzip --- gzip ファイルのサポート,bz2 --- bzip2 圧縮のサポート,zlib --- gzip 互換の圧縮,データ圧縮とアーカイブ
@anchor{library/gzip doc}@anchor{2e4f}@anchor{library/gzip gzip-support-for-gzip-files}@anchor{2e50}@anchor{library/gzip module-gzip}@anchor{6b}@anchor{library/gzip translation-repo}@anchor{2e51}
@subsection @code{gzip} --- @code{gzip} ファイルのサポート


@geindex module; gzip

`ソースコード:' Lib/gzip.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/gzip.py}


__________________________________________________________________


このモジュールは、GNU の @code{gzip} や @code{gunzip} のようにファイルを圧縮、展開するシンプルなインターフェイスを提供しています。

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

データ圧縮は @ref{139,,zlib} モジュールで提供されています。

The @code{gzip} module provides the @ref{65c,,GzipFile} class, as well as the
@ref{2e52,,open()}, @ref{84e,,compress()} and @ref{1426,,decompress()} convenience functions.
The @ref{65c,,GzipFile} class reads and writes @code{gzip}-format files,
automatically compressing or decompressing the data so that it looks like an
ordinary @ref{13db,,file object}.

@code{compress} や @code{pack} 等によって作成され、@code{gzip} や @code{gunzip} が展開できる他のファイル形式についてはこのモジュールは対応していないので注意してください。

このモジュールは以下の項目を定義しています:

@geindex open() (gzip モジュール)
@anchor{library/gzip gzip open}@anchor{2e52}
@deffn {の関数} gzip.open (filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

gzip 圧縮ファイルをバイナリまたはテキストモードで開き、@ref{13db,,ファイルオブジェクト} を返します。

引数 `filename' には実際のファイル名 (@ref{169,,str} または @ref{192,,bytes} オブジェクト) か、既存のファイルオブジェクトを指定します。

引数 `mode' には、バイナリモード用に @code{'r'}、@code{'rb'}、@code{'a'}、@code{'ab'}、@code{'w'}、@code{'wb'}、@code{'x'}、または @code{'xb'}、テキストモード用に @code{'rt'}、@code{'at'}、@code{'wt'}、または @code{'xt'} を指定できます。デフォルトは @code{'rb'} です。

引数 `compresslevel' は @ref{65c,,GzipFile} コンストラクタと同様に 0 から 9 の整数を取ります。

バイナリモードでは、この関数は @ref{65c,,GzipFile} コンストラクタ @code{GzipFile(filename, mode, compresslevel)} と等価です。この時、引数 `encoding'、`errors'、および `newline' を指定してはいけません。

テキストモードでは、@ref{65c,,GzipFile} オブジェクトが作成され、指定されたエンコーディング、エラーハンドラの挙動、および改行文字で @ref{9be,,io.TextIOWrapper} インスタンスにラップされます。


バージョン 3.3 で変更: `filename' にファイルオブジェクト指定のサポート、テキストモードのサポート、および引数に `encoding'、`errors'、および `newline' を追加しました。



バージョン 3.4 で変更: Added support for the @code{'x'}, @code{'xb'} and @code{'xt'} modes.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex BadGzipFile
@anchor{library/gzip gzip BadGzipFile}@anchor{bea}
@deffn {例外} gzip.BadGzipFile

An exception raised for invalid gzip files.  It inherits from @ref{2c0,,OSError}.
@ref{14f1,,EOFError} and @ref{2e2c,,zlib.error} can also be raised for invalid gzip
files.


Added in version 3.8.

@end deffn

@geindex GzipFile (gzip のクラス)
@anchor{library/gzip gzip GzipFile}@anchor{65c}
@deffn {クラス} gzip.GzipFile (filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)

@ref{65c,,GzipFile} クラスのコンストラクタです。@ref{65c,,GzipFile} オブジェクトは @ref{1528,,truncate()} メソッドを除くほとんどの @ref{13db,,ファイルオブジェクト} のメソッドをシミュレートします。少なくとも `fileobj' および `filename' は有効な値でなければなりません。

クラスの新しいインスタンスは、 `fileobj' に基づいて作成されます。 `fileobj' は通常のファイル、 @ref{10a4,,io.BytesIO} オブジェクト、 そしてその他ファイルをシミュレートできるオブジェクトでかまいません。 値はデフォルトでは `None' で、その場合ファイルオブジェクトを生成するために `filename' を開きます。

`fileobj' が @code{None} でない場合、`filename' 引数は @code{gzip} ファイルヘッダにインクルードされることのみに使用されます。@code{gzip} ファイルヘッダは圧縮されていないファイルの元の名前をインクルードするかもしれません。認識可能な場合、規定値は `fileobj' のファイル名です。そうでない場合、規定値は空の文字列で、元のファイル名はヘッダにはインクルードされません。

The `mode' argument can be any of @code{'r'}, @code{'rb'}, @code{'a'}, @code{'ab'}, @code{'w'},
@code{'wb'}, @code{'x'}, or @code{'xb'}, depending on whether the file will be read or
written.  The default is the mode of `fileobj' if discernible; otherwise, the
default is @code{'rb'}.  In future Python releases the mode of `fileobj' will
not be used.  It is better to always specify `mode' for writing.

ファイルは常にバイナリモードで開かれることに注意してください。圧縮ファイルをテキストモードで開く場合、@ref{2e52,,open()} (または @ref{65c,,GzipFile} を @ref{9be,,io.TextIOWrapper} でラップしたオブジェクト) を使ってください。

引数 `compresslevel' は @code{0} から @code{9} の整数を取り、圧縮レベルを制御します; @code{1} は最も高速で最小限の圧縮を行い、@code{9} は最も低速ですが最大限の圧縮を行います。@code{0} は圧縮しません。デフォルトは @code{9} です。

The optional `mtime' argument is the timestamp requested by gzip. The time
is in Unix format, i.e., seconds since 00:00:00 UTC, January 1, 1970.
If `mtime' is omitted or @code{None}, the current time is used. Use `mtime' = 0
to generate a compressed stream that does not depend on creation time.

See below for the @ref{2e53,,mtime} attribute that is set when decompressing.

圧縮したデータの後ろにさらに何か追加したい場合もあるので、@ref{65c,,GzipFile} オブジェクトの @code{close()} メソッド呼び出しは `fileobj' を閉じません。
このため、書き込みのためにオープンした @ref{10a4,,io.BytesIO} オブジェクトを `fileobj' として渡し、(@ref{65c,,GzipFile} を @code{close()} した後に) @ref{10a4,,io.BytesIO} オブジェクトの @ref{2e54,,getvalue()} メソッドを使って書き込んだデータの入っているメモリバッファを取得することができます。

@ref{65c,,GzipFile} は、イテレーションと @ref{186,,with} 文を含む @ref{8a3,,io.BufferedIOBase} インターフェイスをサポートしています。@ref{1528,,truncate()} メソッドのみ実装されていません。

@ref{65c,,GzipFile} は以下のメソッドと属性も提供しています:

@geindex peek() (gzip.GzipFile のメソッド)
@anchor{library/gzip gzip GzipFile peek}@anchor{1425}
@deffn {メソッド} peek (n)

ファイル内の位置を移動せずに展開した `n' バイトを読み込みます。返されるバイト数はほぼ要求した値になります。

@cartouche
@quotation 注釈 
@ref{1425,,peek()} の呼び出しでは @ref{65c,,GzipFile} のファイル位置は変わりませんが、下層のファイルオブジェクトの位置が変わる惧れがあります。(e.g. @ref{65c,,GzipFile} が `fileobj' 引数で作成された場合)
@end quotation
@end cartouche


Added in version 3.2.

@end deffn

@geindex mode (gzip.GzipFile の属性)
@anchor{library/gzip gzip GzipFile mode}@anchor{2e55}
@deffn {の属性} mode

@code{'rb'} は読み込み用、 @code{'wb'} は書き込み用です。


バージョン 3.13 で変更: In previous versions it was an integer @code{1} or @code{2}.

@end deffn

@geindex mtime (gzip.GzipFile の属性)
@anchor{library/gzip gzip GzipFile mtime}@anchor{2e53}
@deffn {の属性} mtime

When decompressing, this attribute is set to the last timestamp in the most
recently read header.  It is an integer, holding the number of seconds
since the Unix epoch (00:00:00 UTC, January 1, 1970).
The initial value before reading any headers is @code{None}.
@end deffn

@geindex name (gzip.GzipFile の属性)
@anchor{library/gzip gzip GzipFile name}@anchor{731}
@deffn {の属性} name

The path to the gzip file on disk, as a @ref{169,,str} or @ref{192,,bytes}.
Equivalent to the output of @ref{e4d,,os.fspath()} on the original input path,
with no other normalization, resolution or expansion.
@end deffn


バージョン 3.1 で変更: @ref{186,,with} 文がサポートされました。`mtime' コンストラクタ引数と @ref{2e53,,mtime} 属性が追加されました。



バージョン 3.2 で変更: ゼロパディングされたファイルやシーク出来ないファイルがサポートされました。



バージョン 3.3 で変更: @ref{2e56,,io.BufferedIOBase.read1()} メソッドを実装しました。



バージョン 3.4 で変更: @code{'x'} ならびに @code{'xb'} モードがサポートされました。



バージョン 3.5 で変更: 任意の @ref{193,,バイトライクオブジェクト} の書き込みがサポートされました。 @ref{1540,,read()} メソッドが @code{None} を引数として受け取るようになりました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.9 で非推奨: Opening @ref{65c,,GzipFile} for writing without specifying the `mode'
argument is deprecated.



バージョン 3.12 で変更: Remove the @code{filename} attribute, use the @ref{731,,name}
attribute instead.

@end deffn

@geindex compress() (gzip モジュール)
@anchor{library/gzip gzip compress}@anchor{84e}
@deffn {の関数} gzip.compress (data, compresslevel=9, *, mtime=0)

Compress the `data', returning a @ref{192,,bytes} object containing
the compressed data.  `compresslevel' and `mtime' have the same meaning as in
the @ref{65c,,GzipFile} constructor above,
but `mtime' defaults to 0 for reproducible output.


Added in version 3.2.



バージョン 3.8 で変更: Added the `mtime' parameter for reproducible output.



バージョン 3.11 で変更: Speed is improved by compressing all data at once instead of in a
streamed fashion. Calls with `mtime' set to @code{0} are delegated to
@ref{84f,,zlib.compress()} for better speed. In this situation the
output may contain a gzip header "OS" byte value other than 255
"unknown" as supplied by the underlying zlib implementation.



バージョン 3.13 で変更: The gzip header OS byte is guaranteed to be set to 255 when this function
is used as was the case in 3.10 and earlier.



バージョン 3.14 で変更: The `mtime' parameter now defaults to 0 for reproducible output.
For the previous behaviour of using the current time,
pass @code{None} to `mtime'.

@end deffn

@geindex decompress() (gzip モジュール)
@anchor{library/gzip gzip decompress}@anchor{1426}
@deffn {の関数} gzip.decompress (data)

Decompress the `data', returning a @ref{192,,bytes} object containing the
uncompressed data. This function is capable of decompressing multi-member
gzip data (multiple gzip blocks concatenated together). When the data is
certain to contain only one member the @ref{f09,,zlib.decompress()} function with
`wbits' set to 31 is faster.


Added in version 3.2.



バージョン 3.11 で変更: Speed is improved by decompressing members at once in memory instead of in
a streamed fashion.

@end deffn

@menu
* 使い方の例:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<3>. 

@end menu

@node 使い方の例,コマンドライン・インターフェース<3>,,gzip --- gzip ファイルのサポート
@anchor{library/gzip examples-of-usage}@anchor{2e57}@anchor{library/gzip gzip-usage-examples}@anchor{2e58}
@subsubsection 使い方の例


圧縮されたファイルを読み込む例:

@example
import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
    file_content = f.read()
@end example

GZIP 圧縮されたファイルを作成する例:

@example
import gzip
content = b"Lots of content here"
with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
    f.write(content)
@end example

既存のファイルを GZIP 圧縮する例:

@example
import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)
@end example

バイナリ文字列を GZIP 圧縮する例:

@example
import gzip
s_in = b"Lots of content here"
s_out = gzip.compress(s_in)
@end example


@subsubheading 参考



@table @asis

@item @ref{139,,zlib} モジュール

@code{gzip} ファイル形式のサポートを行うために必要な基本ライブラリモジュール。
@end table

In case gzip (de)compression is a bottleneck, the python-isal@footnote{https://github.com/pycompression/python-isal}
package speeds up (de)compression with a mostly compatible API.


@node コマンドライン・インターフェース<3>,,使い方の例,gzip --- gzip ファイルのサポート
@anchor{library/gzip command-line-interface}@anchor{2e59}@anchor{library/gzip gzip-cli}@anchor{2e5a}
@subsubsection コマンドライン・インターフェース


The @code{gzip} module provides a simple command line interface to compress or
decompress files.

Once executed the @code{gzip} module keeps the input file(s).


バージョン 3.8 で変更: Add a new command line interface with a usage.
By default, when you will execute the CLI, the default compression level is 6.


@menu
* コマンドラインオプション:: 

@end menu

@node コマンドラインオプション,,,コマンドライン・インターフェース<3>
@anchor{library/gzip command-line-options}@anchor{2e5b}
@subsubsection コマンドラインオプション


@geindex gzip コマンドラインオプション; file
@anchor{library/gzip cmdoption-gzip-arg-file}@anchor{2e5c}
@deffn {Option} file

If `file' is not specified, read from @ref{75f,,sys.stdin}.
@end deffn

@geindex gzip コマンドラインオプション; --fast
@anchor{library/gzip cmdoption-gzip-fast}@anchor{2e5d}
@deffn {Option} @w{-}@w{-}fast

Indicates the fastest compression method (less compression).
@end deffn

@geindex gzip コマンドラインオプション; --best
@anchor{library/gzip cmdoption-gzip-best}@anchor{2e5e}
@deffn {Option} @w{-}@w{-}best

Indicates the slowest compression method (best compression).
@end deffn

@geindex gzip コマンドラインオプション; -d
@geindex gzip コマンドラインオプション; --decompress
@anchor{library/gzip cmdoption-gzip-d}@anchor{2e5f}@anchor{library/gzip cmdoption-gzip-decompress}@anchor{2e60}
@deffn {Option} @w{-}d, @w{-}@w{-}decompress

Decompress the given file.
@end deffn

@geindex gzip コマンドラインオプション; -h
@geindex gzip コマンドラインオプション; --help
@anchor{library/gzip cmdoption-gzip-h}@anchor{2e61}@anchor{library/gzip cmdoption-gzip-help}@anchor{2e62}
@deffn {Option} @w{-}h, @w{-}@w{-}help

ヘルプメッセージを出力します
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node bz2 --- bzip2 圧縮のサポート,lzma --- LZMA アルゴリズムを使用した圧縮,gzip --- gzip ファイルのサポート,データ圧縮とアーカイブ
@anchor{library/bz2 doc}@anchor{2e63}@anchor{library/bz2 bz2-support-for-bzip2-compression}@anchor{2e64}@anchor{library/bz2 module-bz2}@anchor{14}@anchor{library/bz2 translation-repo}@anchor{2e65}
@subsection @code{bz2} --- @code{bzip2} 圧縮のサポート


@geindex module; bz2

`ソースコード:' Lib/bz2.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/bz2.py}


__________________________________________________________________


このモジュールは、bzip2 アルゴリズムを用いて圧縮・展開を行う包括的なインターフェイスを提供します。

The @code{bz2} module contains:


@itemize *

@item 
圧縮ファイルを読み書きするための @ref{129f,,open()} 関数と @ref{a66,,BZ2File} クラス。

@item 
インクリメンタルにデータを圧縮・展開するための @ref{1ace,,BZ2Compressor} および @ref{1acc,,BZ2Decompressor} クラス。

@item 
一度に圧縮・展開を行う @ref{287d,,compress()} および @ref{12a0,,decompress()} 関数。
@end itemize

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@menu
* ファイルの圧縮/解凍:: 
* 逐次圧縮および展開:: 
* 一括圧縮/解凍:: 
* 使い方の例: 使い方の例<2>. 

@end menu

@node ファイルの圧縮/解凍,逐次圧縮および展開,,bz2 --- bzip2 圧縮のサポート
@anchor{library/bz2 de-compression-of-files}@anchor{2e66}
@subsubsection ファイルの圧縮/解凍


@geindex open() (bz2 モジュール)
@anchor{library/bz2 bz2 open}@anchor{129f}
@deffn {の関数} bz2.open (filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

bzip2 圧縮されたファイルを、バイナリモードかテキストモードでオープンし、@ref{13db,,ファイルオブジェクト} を返します。

@ref{a66,,BZ2File} のコンストラクタと同様に、引数 `filename' には実際のファイル名 (@ref{169,,str} または @ref{192,,bytes} オブジェクト) か、読み書きする既存のファイルオブジェクトを指定します。

引数 `mode' には、バイナリモード用に @code{'r'}、@code{'rb'}、@code{'w'}、@code{'wb'}、@code{'x'}、@code{'xb'}、@code{'a'}、あるいは @code{'ab'}、テキストモード用に @code{'rt'}、@code{'wt'}、@code{'xt'}、あるいは @code{'at'} を指定できます。デフォルトは @code{'rb'} です。

引数 `compresslevel' には @ref{a66,,BZ2File} コンストラクタと同様に 1 から 9 の整数を指定します。

バイナリモードでは、この関数は @ref{a66,,BZ2File} コンストラクタ @code{BZ2File(filename, mode, compresslevel=compresslevel)} と等価です。この時、引数 `encoding'、`errors'、および `newline' を指定してはいけません。

テキストモードでは、@ref{a66,,BZ2File} オブジェクトが作成され、指定されたエンコーディング、エラーハンドラの挙動、および改行文字で @ref{9be,,io.TextIOWrapper} にラップされます。


Added in version 3.3.



バージョン 3.4 で変更: @code{'x'} (排他的作成) モードが追加されました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex BZ2File (bz2 のクラス)
@anchor{library/bz2 bz2 BZ2File}@anchor{a66}
@deffn {クラス} bz2.BZ2File (filename, mode='r', *, compresslevel=9)

bzip2 圧縮ファイルをバイナリモードでオープンします。

`filename' が @ref{169,,str} あるいは @ref{192,,bytes} オブジェクトの場合、それを名前とするファイルを直接開きます。そうでない場合、`filename' は圧縮データを読み書きする @ref{13db,,ファイルオブジェクト} でなくてはなりません。

引数 `mode' は読み込みモードの @code{'r'} (デフォルト)、上書きモードの @code{'w'}、排他的作成モードの @code{'x'}、あるいは追記モードの @code{'a'} のいずれかを指定できます。これらはそれぞれ @code{'rb'}、@code{'wb'}、@code{'xb'} および @code{'ab'} と等価です。

`filename' が (実際のファイル名でなく) ファイルオブジェクトの場合、@code{'w'} はファイルを上書きせず、@code{'a'} と等価になります。

`mode' が @code{'w'} あるいは @code{'a'} の場合、`compresslevel' に圧縮レベルを @code{1} から @code{9} の整数で指定できます。
圧縮率は @code{1} が最低で、@code{9} (デフォルト値) が最高です。

`mode' の値が @code{'r'} の場合、入力ファイルは複数の圧縮ストリームでも構いません。

@ref{a66,,BZ2File} には、 @ref{8a3,,io.BufferedIOBase} で規定されているメソッドや属性のうち、 @ref{2deb,,detach()} と @ref{1528,,truncate()} を除くすべてが備わっています。イテレーションと @ref{186,,with} 文をサポートしています。

@ref{a66,,BZ2File} also provides the following methods and attributes:

@geindex peek() (bz2.BZ2File のメソッド)
@anchor{library/bz2 bz2 BZ2File peek}@anchor{2e67}
@deffn {メソッド} peek ([n])

ファイル上の現在位置を変更せずにバッファのデータを返します。このメソッドは少なくとも 1 バイトのデータを返します (EOF の場合を除く)。返される正確なバイト数は規定されていません。

@cartouche
@quotation 注釈 
@ref{2e67,,peek()} の呼び出しでは @ref{a66,,BZ2File} のファイル位置は変わりませんが、下層のファイルオブジェクトの位置が変わる惧れがあります(e.g. @ref{a66,,BZ2File} を `filename' にファイルオブジェクトを渡して作成した場合)。
@end quotation
@end cartouche


Added in version 3.3.

@end deffn

@geindex fileno() (bz2.BZ2File のメソッド)
@anchor{library/bz2 bz2 BZ2File fileno}@anchor{2e68}
@deffn {メソッド} fileno ()

Return the file descriptor for the underlying file.


Added in version 3.3.

@end deffn

@geindex readable() (bz2.BZ2File のメソッド)
@anchor{library/bz2 bz2 BZ2File readable}@anchor{2e69}
@deffn {メソッド} readable ()

Return whether the file was opened for reading.


Added in version 3.3.

@end deffn

@geindex seekable() (bz2.BZ2File のメソッド)
@anchor{library/bz2 bz2 BZ2File seekable}@anchor{2e6a}
@deffn {メソッド} seekable ()

Return whether the file supports seeking.


Added in version 3.3.

@end deffn

@geindex writable() (bz2.BZ2File のメソッド)
@anchor{library/bz2 bz2 BZ2File writable}@anchor{2e6b}
@deffn {メソッド} writable ()

Return whether the file was opened for writing.


Added in version 3.3.

@end deffn

@geindex read1() (bz2.BZ2File のメソッド)
@anchor{library/bz2 bz2 BZ2File read1}@anchor{2e6c}
@deffn {メソッド} read1 (size=-1)

Read up to `size' uncompressed bytes, while trying to avoid
making multiple reads from the underlying stream. Reads up to a
buffer's worth of data if size is negative.

Returns @code{b'@w{'}} if the file is at EOF.


Added in version 3.3.

@end deffn

@geindex readinto() (bz2.BZ2File のメソッド)
@anchor{library/bz2 bz2 BZ2File readinto}@anchor{2e6d}
@deffn {メソッド} readinto (b)

Read bytes into `b'.

Returns the number of bytes read (0 for EOF).


Added in version 3.3.

@end deffn

@geindex mode (bz2.BZ2File の属性)
@anchor{library/bz2 bz2 BZ2File mode}@anchor{2e6e}
@deffn {の属性} mode

@code{'rb'} は読み込み用、 @code{'wb'} は書き込み用です。


Added in version 3.13.

@end deffn

@geindex name (bz2.BZ2File の属性)
@anchor{library/bz2 bz2 BZ2File name}@anchor{2e6f}
@deffn {の属性} name

The bzip2 file name.  Equivalent to the @ref{2def,,name}
attribute of the underlying @ref{13db,,file object}.


Added in version 3.13.

@end deffn


バージョン 3.1 で変更: @ref{186,,with} 構文のサポートが追加されました。



バージョン 3.3 で変更: `filename' が実際のファイル名でなく @ref{13db,,ファイルオブジェクト} だった場合のサポートが追加されました。

@code{'a'} (追記) モードが追加され、複数のストリームの読み込みがサポートされました。



バージョン 3.4 で変更: @code{'x'} (排他的作成) モードが追加されました。



バージョン 3.5 で変更: @ref{1540,,read()} メソッドが @code{None} を引数として受け取るようになりました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.9 で変更: `buffering' パラメータは削除されました。 Python 3.0 からは無視され非推奨となっています。開かれたファイルオブジェクトを渡し、ファイルの開きかたを制御します。

`compresslevel' パラメータはキーワード専用になりました。



バージョン 3.10 で変更: このクラスは、複数の同時読み出しや書き込みにおいては、既存の @ref{6b,,gzip} や @ref{8e,,lzma}  などの同等のクラスのように、スレッド安全ではありません。

@end deffn

@node 逐次圧縮および展開,一括圧縮/解凍,ファイルの圧縮/解凍,bz2 --- bzip2 圧縮のサポート
@anchor{library/bz2 incremental-de-compression}@anchor{2e70}
@subsubsection 逐次圧縮および展開


@geindex BZ2Compressor (bz2 のクラス)
@anchor{library/bz2 bz2 BZ2Compressor}@anchor{1ace}
@deffn {クラス} bz2.BZ2Compressor (compresslevel=9)

新しくコンプレッサオブジェクトを作成します。このオブジェクトはデータの逐次的な圧縮に使用できます。一度に圧縮したい場合は、@ref{287d,,compress()} 関数を使ってください。

引数 `compresslevel' を指定する場合は、@code{1} から @code{9} までの整数を与えてください。
デフォルト値は @code{9} です。

@geindex compress() (bz2.BZ2Compressor のメソッド)
@anchor{library/bz2 bz2 BZ2Compressor compress}@anchor{2e71}
@deffn {メソッド} compress (data)

データをコンプレッサオブジェクトに渡します。戻り値は圧縮されたデータですが、圧縮データを返すことができない場合は空のバイト文字列を返します。

コンプレッサオブジェクトにデータをすべて渡し終えたら、@ref{2e72,,flush()} メソッドを呼び出し、圧縮プロセスを完了させてください。
@end deffn

@geindex flush() (bz2.BZ2Compressor のメソッド)
@anchor{library/bz2 bz2 BZ2Compressor flush}@anchor{2e72}
@deffn {メソッド} flush ()

圧縮プロセスを完了させ、内部バッファに残っている圧縮済みデータを返します。

このメソッドを呼び出すと、それ以後コンプレッサオブジェクトは使用できなくなります。
@end deffn
@end deffn

@geindex BZ2Decompressor (bz2 のクラス)
@anchor{library/bz2 bz2 BZ2Decompressor}@anchor{1acc}
@deffn {クラス} bz2.BZ2Decompressor

新しくデコンプレッサオブジェクトを作成します。このオブジェクトは逐次的なデータ展開に使用できます。一度に展開したい場合は、@ref{12a0,,decompress()} 関数を使ってください。

@cartouche
@quotation 注釈 
このクラスは、@ref{12a0,,decompress()} や @ref{a66,,BZ2File} とは異なり、複数の圧縮レベルが混在しているデータを透過的に扱うことができません。 @ref{1acc,,BZ2Decompressor} クラスを用いて、複数のストリームからなるデータを展開する場合は、それぞれのストリームについてデコンプレッサオブジェクトを用意してください。
@end quotation
@end cartouche

@geindex decompress() (bz2.BZ2Decompressor のメソッド)
@anchor{library/bz2 bz2 BZ2Decompressor decompress}@anchor{fca}
@deffn {メソッド} decompress (data, max_length=-1)

`data' (@ref{193,,bytes-like object}) を展開し、未圧縮のデータを bytes で返します。
`data' の一部は、後で @ref{12a0,,decompress()} の呼び出しに使用するため内部でバッファされている場合があります。
返されたデータは、以前の @ref{12a0,,decompress()} の呼び出しの出力に連結する必要があります。

`max_length' が非負の場合、最大 `max_length' バイトの展開データを返します。この制限に達して、出力がさらに生成できる場合、 @ref{2e73,,needs_input} が @code{False} に設定されます。この場合、 @ref{fca,,decompress()} を次に呼び出すと、`data' を @code{b'@w{'}} として提供し、出力をさらに取得することができます。

入力データの全てが圧縮され返された (`max_length' バイトより少ないためか `max_length' が負のため) 場合、
@ref{2e73,,needs_input} 属性は @code{True} になります。

ストリームの終端に到達した後にデータを展開しようとすると @ref{14f1,,EOFError} が送出されます。
ストリームの終端の後ろの全てのデータは無視され、その部分は @ref{2e74,,unused_data} 属性に保存されます。


バージョン 3.5 で変更: @code{max_length} パラメータが追加されました。

@end deffn

@geindex eof (bz2.BZ2Decompressor の属性)
@anchor{library/bz2 bz2 BZ2Decompressor eof}@anchor{2e75}
@deffn {の属性} eof

ストリーム終端記号に到達した場合 @code{True} を返します。


Added in version 3.3.

@end deffn

@geindex unused_data (bz2.BZ2Decompressor の属性)
@anchor{library/bz2 bz2 BZ2Decompressor unused_data}@anchor{2e74}
@deffn {の属性} unused_data

圧縮ストリームの末尾以降に存在したデータを表します。

ストリームの末尾に達する前には、この属性には @code{b'@w{'}} という値が収められています。
@end deffn

@geindex needs_input (bz2.BZ2Decompressor の属性)
@anchor{library/bz2 bz2 BZ2Decompressor needs_input}@anchor{2e73}
@deffn {の属性} needs_input

@ref{fca,,decompress()} メソッドが、新しい非圧縮入力を必要とせずにさらに展開データを提供できる場合、 @code{False} です。


Added in version 3.5.

@end deffn
@end deffn

@node 一括圧縮/解凍,使い方の例<2>,逐次圧縮および展開,bz2 --- bzip2 圧縮のサポート
@anchor{library/bz2 one-shot-de-compression}@anchor{2e76}
@subsubsection 一括圧縮/解凍


@geindex compress() (bz2 モジュール)
@anchor{library/bz2 bz2 compress}@anchor{287d}
@deffn {の関数} bz2.compress (data, compresslevel=9)

@ref{193,,バイト類オブジェクト} の `data' を圧縮します。

引数 `compresslevel' を指定する場合は、@code{1} から @code{9} までの整数を与えてください。
デフォルト値は @code{9} です。

逐次的にデータを圧縮したい場合は、@ref{1ace,,BZ2Compressor} を使ってください。
@end deffn

@geindex decompress() (bz2 モジュール)
@anchor{library/bz2 bz2 decompress}@anchor{12a0}
@deffn {の関数} bz2.decompress (data)

@ref{193,,バイト類オブジェクト} の `data' を展開します。

`data' が複数の圧縮ストリームから成る場合、そのすべてを展開します。

逐次的に展開を行う場合は、@ref{1acc,,BZ2Decompressor} を使ってください。


バージョン 3.3 で変更: 複数ストリームの入力をサポートしました。

@end deffn

@node 使い方の例<2>,,一括圧縮/解凍,bz2 --- bzip2 圧縮のサポート
@anchor{library/bz2 bz2-usage-examples}@anchor{2e77}@anchor{library/bz2 examples-of-usage}@anchor{2e78}
@subsubsection 使い方の例


Below are some examples of typical usage of the @code{bz2} module.

@ref{287d,,compress()} と @ref{12a0,,decompress()} を使い、圧縮して展開する実演をしています:

@example
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> c = bz2.compress(data)
>>> len(data) / len(c)  # Data compression ratio
1.513595166163142
>>> d = bz2.decompress(c)
>>> data == d  # Check equality to original object after round-trip
True
@end example

@ref{1ace,,BZ2Compressor} を使い、逐次圧縮をしています:

@example
>>> import bz2
>>> def gen_data(chunks=10, chunksize=1000):
...     """Yield incremental blocks of chunksize bytes."""
...     for _ in range(chunks):
...         yield b"z" * chunksize
...
>>> comp = bz2.BZ2Compressor()
>>> out = b""
>>> for chunk in gen_data():
...     # Provide data to the compressor object
...     out = out + comp.compress(chunk)
...
>>> # Finish the compression process.  Call this once you have
>>> # finished providing data to the compressor.
>>> out = out + comp.flush()
@end example

上の例は、非常に "ランダムでない" データストリーム (チャンク @code{b"z"} のストリーム) です。
ランダムなデータは圧縮率が低い傾向にある一方、揃っていて、繰り返しのあるデータは通常は高い圧縮率を叩き出します。

bzip2 圧縮されたファイルをバイナリモードで読み書きしています:

@example
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> with bz2.open("myfile.bz2", "wb") as f:
...     # Write compressed data to file
...     unused = f.write(data)
...
>>> with bz2.open("myfile.bz2", "rb") as f:
...     # Decompress data from file
...     content = f.read()
...
>>> content == data  # Check equality to original object after round-trip
True
@end example

@c import os
@c os.remove("myfile.bz2")

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node lzma --- LZMA アルゴリズムを使用した圧縮,zipfile --- ZIP アーカイブの処理,bz2 --- bzip2 圧縮のサポート,データ圧縮とアーカイブ
@anchor{library/lzma doc}@anchor{2e79}@anchor{library/lzma lzma-compression-using-the-lzma-algorithm}@anchor{2e7a}@anchor{library/lzma module-lzma}@anchor{8e}@anchor{library/lzma translation-repo}@anchor{2e7b}
@subsection @code{lzma} --- LZMA アルゴリズムを使用した圧縮


@geindex module; lzma


Added in version 3.3.


`ソースコード:' Lib/lzma.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/lzma.py}


__________________________________________________________________


このモジュールは LZMA 圧縮アルゴリズムを使用したデータ圧縮および展開のためのクラスや便利な関数を提供しています。また、@code{xz} ユーティリティを使用した @code{.xz} およびレガシーな @code{.lzma} ファイル形式へのファイルインターフェイスの他、RAW 圧縮ストリームもサポートしています。

このモジュールが提供するインターフェイスは @ref{14,,bz2} モジュールと非常によく似ています。
@ref{120e,,LZMAFile} と @ref{a66,,bz2.BZ2File} はスレッドセーフでは `ない' 点に注意してください。
そのため、単一の @ref{120e,,LZMAFile} インスタンスを複数スレッドから使用する場合は、ロックで保護する必要があります。

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@geindex LZMAError
@anchor{library/lzma lzma LZMAError}@anchor{2e7c}
@deffn {例外} lzma.LZMAError

この例外は圧縮あるいは展開中にエラーが発生した場合、または圧縮/展開状態の初期化中に送出されます。
@end deffn

@menu
* 圧縮ファイルへの読み書き: 圧縮ファイルへの読み書き<2>. 
* メモリ上での圧縮と展開: メモリ上での圧縮と展開<2>. 
* その他: その他<4>. 
* カスタムフィルタチェインの指定:: 
* 使用例: 使用例<15>. 

@end menu

@node 圧縮ファイルへの読み書き<2>,メモリ上での圧縮と展開<2>,,lzma --- LZMA アルゴリズムを使用した圧縮
@anchor{library/lzma reading-and-writing-compressed-files}@anchor{2e7d}
@subsubsection 圧縮ファイルへの読み書き


@geindex open() (lzma モジュール)
@anchor{library/lzma lzma open}@anchor{2e7e}
@deffn {の関数} lzma.open (filename, mode='rb', *, format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None)

LZMA 圧縮ファイルをバイナリまたはテキストモードでオープンし、@ref{13db,,ファイルオブジェクト} を返します。

`filename' 引数には、ファイルをオープンする際には実際のファイル名 (@ref{169,,str}、 @ref{192,,bytes}、または @ref{5a1,,path-like} オブジェクトとして指定します)か、読み込みまたは書き込むためであれば、すでに存在するファイルオブジェクトを指定できます。

引数 `mode' は、バイナリモードでは @code{"r"}、@code{"rb"}、@code{"w"}、@code{"wb"}、@code{"x"}、@code{"xb"}、@code{"a"}、あるいは @code{"ab"} の、テキストモードでは @code{"rt"}、@code{"wt"}、@code{"xt"}、あるいは @code{"at"} のいずれかになります。デフォルトは @code{"rb"} です。

読み込み用にファイルをオープンした場合、引数 `format' および `filters' は @ref{1acb,,LZMADecompressor} と同じ意味になります。この時、引数 `check' および `preset' は使用しないでください。

書き出し用にオープンした場合、引数 `format'、`check'、`preset'、および `filters' は @ref{1acd,,LZMACompressor} と同じ意味になります。

バイナリモードでは、この関数は @ref{120e,,LZMAFile} コンストラクタと等価になります (@code{LZMAFile(filename, mode, ...)})。この場合、引数 `encoding'、`errors'、および `newline' を指定しなければなりません。

テキストモードでは、@ref{120e,,LZMAFile} オブジェクトが生成され、指定したエンコーディング、エラーハンドラの挙動、および改行コードで @ref{9be,,io.TextIOWrapper} にラップされます。


バージョン 3.4 で変更: @code{"x"}, @code{"xb"}, @code{"xt"} モードのサポートが追加されました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex LZMAFile (lzma のクラス)
@anchor{library/lzma lzma LZMAFile}@anchor{120e}
@deffn {クラス} lzma.LZMAFile (filename=None, mode='r', *, format=None, check=-1, preset=None, filters=None)

LZMA 圧縮ファイルをバイナリモードで開きます。

@ref{120e,,LZMAFile} はすでにオープンしている @ref{13db,,file object} をラップ、または名前付きファイルを直接操作できます。引数 `filename' にはラップするファイルオブジェクトかオープンするファイル名 (@ref{169,,str} オブジェクトま、@ref{192,,bytes} オブジェクト、または @ref{5a1,,path-like} オブジェクト) を指定します。既存のファイルオブジェクトをラップした場合、@ref{120e,,LZMAFile} をクローズしてもラップしたファイルはクローズされません。

引数 `mode' は読み込みモードの @code{"r"} (デフォルト)、上書きモードの @code{"w"}、排他的生成モードの @code{"x"}、あるいは追記モードの @code{"a"} のいずれかを指定できます。これらはそれぞれ @code{"rb"}、@code{"wb"}、@code{"xb"}、および @code{"ab"} と等価です。

`filename' が (実際のファイル名でなく) ファイルオブジェクトの場合、@code{"w"} モードはファイルを上書きせず、@code{"a"} と等価になります。

読み込みモードでファイルをオープンした時、入力ファイルは複数に分割された圧縮ストリームを連結したものでもかまいません。これらは透過的に単一論理ストリームとしてデコードされます。

読み込み用にファイルをオープンした場合、引数 `format' および `filters' は @ref{1acb,,LZMADecompressor} と同じ意味になります。この時、引数 `check' および `preset' は使用しないでください。

書き出し用にオープンした場合、引数 `format'、`check'、`preset'、および `filters' は @ref{1acd,,LZMACompressor} と同じ意味になります。

@ref{120e,,LZMAFile} には、 @ref{8a3,,io.BufferedIOBase} で規定されているメソッドや属性のうち、 @ref{2deb,,detach()} と @ref{1528,,truncate()} を除くすべてが備わっています。イテレーションと @ref{186,,with} 文をサポートしています。

以下のメソッドと属性も提供されています:

@geindex peek() (lzma.LZMAFile のメソッド)
@anchor{library/lzma lzma LZMAFile peek}@anchor{2e7f}
@deffn {メソッド} peek (size=-1)

ファイル上の現在位置を変更せずにバッファのデータを返します。EOF に達しない限り、少なくとも 1 バイトが返されます。返される正確なバイト数は規定されていません (引数 `size' は無視されます)。

@cartouche
@quotation 注釈 
@ref{2e7f,,peek()} の呼び出しでは @ref{120e,,LZMAFile} のファイル位置は変わりませんが、下層のファイルオブジェクトの位置が変わる惧れがあります。(e.g. @ref{120e,,LZMAFile} を `filename' にファイルオブジェクトを渡して作成した場合)
@end quotation
@end cartouche
@end deffn

@geindex mode (lzma.LZMAFile の属性)
@anchor{library/lzma lzma LZMAFile mode}@anchor{2e80}
@deffn {の属性} mode

@code{'rb'} は読み込み用、 @code{'wb'} は書き込み用です。


Added in version 3.13.

@end deffn

@geindex name (lzma.LZMAFile の属性)
@anchor{library/lzma lzma LZMAFile name}@anchor{2e81}
@deffn {の属性} name

lzma ファイルの名前。基礎である @ref{13db,,file object} の @ref{2def,,name} 属性と同様です。


Added in version 3.13.

@end deffn


バージョン 3.4 で変更: @code{'x'}, @code{'xb'} モードがサポートが追加されました。



バージョン 3.5 で変更: @ref{1540,,read()} メソッドが @code{None} を引数として受け取るようになりました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@node メモリ上での圧縮と展開<2>,その他<4>,圧縮ファイルへの読み書き<2>,lzma --- LZMA アルゴリズムを使用した圧縮
@anchor{library/lzma compressing-and-decompressing-data-in-memory}@anchor{2e82}
@subsubsection メモリ上での圧縮と展開


@geindex LZMACompressor (lzma のクラス)
@anchor{library/lzma lzma LZMACompressor}@anchor{1acd}
@deffn {クラス} lzma.LZMACompressor (format=FORMAT_XZ, check=-1, preset=None, filters=None)

データをインクリメンタルに圧縮する圧縮オブジェクトを作成します。

大量の単一データを圧縮する、より便利な方法については @ref{2e83,,compress()} を参照してください。

引数 `format' には使用するコンテナフォーマットを指定します。以下の値が指定できます:


@itemize *

@item 

@table @asis

@item @code{FORMAT_XZ}: The @code{.xz} コンテナフォーマット。

デフォルトのフォーマットです。
@end table

@item 

@table @asis

@item @code{FORMAT_ALONE}: レガシーな @code{.lzma} コンテナフォーマット。

このフォーマットは @code{.xz} より制限があります -- インテグリティチェックや複数フィルタをサポートしていません。
@end table

@item 

@table @asis

@item @code{FORMAT_RAW}: 特定のコンテナフォーマットを使わない、生のデータストリーム。

このフォーマット指定子はインテグリティチェックをサポートしておらず、(圧縮および展開双方のために) 常にカスタムフィルタチェインを指定する必要があります。さらに、この方法で圧縮されたデータは @code{FORMAT_AUTO} を使っても展開できません (@ref{1acb,,LZMADecompressor} を参照)。
@end table
@end itemize

引数 `check' には圧縮データに組み込むインテグリティチェックのタイプを指定します。このチェックは展開時に使用され、データが破損していないことを保証します。以下の値が指定できます:


@itemize *

@item 
@code{CHECK_NONE}: インテグリティチェックなし。@code{FORMAT_ALONE} および @code{FORMAT_RAW} のデフォルト (かつ唯一指定可能な値) です。

@item 
@code{CHECK_CRC32}: 32-bit 巡回冗長検査。

@item 
@code{CHECK_CRC64}: 64-bit 巡回冗長検査。@code{FORMAT_XZ} のデフォルトです。

@item 
@code{CHECK_SHA256}: 256-bit セキュアハッシュアルゴリズム (SHA)。
@end itemize

指定したチェック方法がサポートされていない場合、@ref{2e7c,,LZMAError} が送出されます。

圧縮設定はプリセット圧縮レベル (引数 `preset' で指定) またはカスタムフィルタチェイン (引数 `filters' で指定) のどちらかを指定します。

引数 `preset' を指定する場合、@code{0} から @code{9} までの整数値でなければならず、オプションで定数 @code{PRESET_EXTREME} を論理和指定できます。`preset' も `filters' も指定されなかった場合、デフォルトの挙動として @code{PRESET_DEFAULT} (プリセットレベル @code{6}) が使用されます。高いプリセット値を指定すると圧縮率が上がりますが、圧縮にかかる時間が長くなります。

@cartouche
@quotation 注釈 
CPU の使用量が多いのに加えて、高いプリセットで圧縮を行うには、メモリをずっと多く必要とします (さらに、生成される出力も展開により多くのメモリを必要とします)。例えば、プリセットが @code{9} の場合、@ref{1acd,,LZMACompressor} オブジェクトのオーバーヘッドは 800 MiB にまで高くなる場合があります。このため、通常はデフォルトのプリセットを使用するのがよいでしょう。
@end quotation
@end cartouche

引数 `filters' を指定する場合、フィルタチェイン指定子でなければなりません。詳しくは @ref{2e84,,カスタムフィルタチェインの指定} を参照してください。

@geindex compress() (lzma.LZMACompressor のメソッド)
@anchor{library/lzma lzma LZMACompressor compress}@anchor{2e85}
@deffn {メソッド} compress (data)

`data' (@ref{192,,bytes} オブジェクト) を圧縮し、少なくともその一部が圧縮されたデータを格納する @ref{192,,bytes} オブジェクトを返します。`data' の一部は、後で @ref{2e83,,compress()} および @ref{2e86,,flush()} の呼び出しに使用するため内部でバッファされている場合があります。返すデータは以前の @ref{2e83,,compress()} 呼び出しの出力を連結したものです。
@end deffn

@geindex flush() (lzma.LZMACompressor のメソッド)
@anchor{library/lzma lzma LZMACompressor flush}@anchor{2e86}
@deffn {メソッド} flush ()

圧縮処理を終了し、コンプレッサの内部バッファにあるあらゆるデータを格納する @ref{192,,bytes} オブジェクトを返します。

コンプレッサはこのメソッドが呼び出された後は使用できません。
@end deffn
@end deffn

@geindex LZMADecompressor (lzma のクラス)
@anchor{library/lzma lzma LZMADecompressor}@anchor{1acb}
@deffn {クラス} lzma.LZMADecompressor (format=FORMAT_AUTO, memlimit=None, filters=None)

データをインクリメンタルに展開するために使用できる展開オブジェクトを作成します。

圧縮されたストリーム全体を一度に展開にする、より便利な方法については、@ref{2e87,,decompress()} を参照してください。

引数 `format' には使用するコンテナフォーマットを指定します。デフォルトは @code{FORMAT_AUTO} で、@code{.xz} および @code{.lzma} ファイルを展開できます。その他に指定できる値は、@code{FORMAT_XZ}、@code{FORMAT_ALONE}、および @code{FORMAT_RAW} です。

引数 `memlimit' にはデコンプレッサが使用できるメモリ量をバイトで指定します。この引数を指定した場合、そのメモリ量で展開ができないと @ref{2e7c,,LZMAError} を送出します。

引数 `filters' には展開されるストリームの作成に使用するフィルタチェインを指定します。この引数を使用する際は、引数 `format' に @code{FORMAT_RAW} を指定しなければなりません。フィルタチェインについての詳細は @ref{2e84,,カスタムフィルタチェインの指定} を参照してください。

@cartouche
@quotation 注釈 
このクラスは @ref{2e87,,decompress()} および @ref{120e,,LZMAFile} と異なり、複数の圧縮ストリームを含む入力を透過的に扱いません。 @ref{1acb,,LZMADecompressor} で複数ストリーム入力を展開するには、各ストリームごとに新しいデコンプレッサを作成しなければなりません。
@end quotation
@end cartouche

@geindex decompress() (lzma.LZMADecompressor のメソッド)
@anchor{library/lzma lzma LZMADecompressor decompress}@anchor{102e}
@deffn {メソッド} decompress (data, max_length=-1)

`data' (@ref{193,,bytes-like object}) を展開し、未圧縮のデータを bytes で返します。
`data' の一部は、後で @ref{2e87,,decompress()} の呼び出しに使用するため内部でバッファされている場合があります。
返されたデータは、以前の @ref{2e87,,decompress()} の呼び出しの出力に連結する必要があります。

`max_length' が非負の場合、最大 `max_length' バイトの展開データを返します。この制限に達して、出力がさらに生成できる場合、 @ref{2e88,,needs_input} が @code{False} に設定されます。この場合、 @ref{102e,,decompress()} を次に呼び出すと、`data' を @code{b'@w{'}} として提供し、出力をさらに取得することができます。

入力データの全てが圧縮され返された (`max_length' バイトより少ないためか `max_length' が負のため) 場合、
@ref{2e88,,needs_input} 属性は @code{True} になります。

ストリームの終端に到達した後にデータを展開しようとすると @ref{14f1,,EOFError} が送出されます。
ストリームの終端の後ろの全てのデータは無視され、その部分は @ref{2e89,,unused_data} 属性に保存されます。


バージョン 3.5 で変更: @code{max_length} パラメータが追加されました。

@end deffn

@geindex check (lzma.LZMADecompressor の属性)
@anchor{library/lzma lzma LZMADecompressor check}@anchor{2e8a}
@deffn {の属性} check

入力ストリームに使用されるインテグリティチェックの ID です。これは何のインテグリティチェックが使用されているか決定するために十分な入力がデコードされるまでは @code{CHECK_UNKNOWN} になることがあります。
@end deffn

@geindex eof (lzma.LZMADecompressor の属性)
@anchor{library/lzma lzma LZMADecompressor eof}@anchor{2e8b}
@deffn {の属性} eof

ストリーム終端記号に到達した場合 @code{True} を返します。
@end deffn

@geindex unused_data (lzma.LZMADecompressor の属性)
@anchor{library/lzma lzma LZMADecompressor unused_data}@anchor{2e89}
@deffn {の属性} unused_data

圧縮ストリームの末尾以降に存在したデータを表します。

ストリームの末尾に達する前は、これは @code{b""} になります。
@end deffn

@geindex needs_input (lzma.LZMADecompressor の属性)
@anchor{library/lzma lzma LZMADecompressor needs_input}@anchor{2e88}
@deffn {の属性} needs_input

@ref{102e,,decompress()} メソッドが、新しい非圧縮入力を必要とせずにさらに展開データを提供できる場合、 @code{False} です。


Added in version 3.5.

@end deffn
@end deffn

@geindex compress() (lzma モジュール)
@anchor{library/lzma lzma compress}@anchor{2e83}
@deffn {の関数} lzma.compress (data, format=FORMAT_XZ, check=-1, preset=None, filters=None)

`data' (@ref{192,,bytes} オブジェクト) を圧縮し、圧縮データを @ref{192,,bytes} オブジェクトとして返します。

引数 `format'、`check'、`preset'、および `filters' についての説明は上記の @ref{1acd,,LZMACompressor} を参照してください。
@end deffn

@geindex decompress() (lzma モジュール)
@anchor{library/lzma lzma decompress}@anchor{2e87}
@deffn {の関数} lzma.decompress (data, format=FORMAT_AUTO, memlimit=None, filters=None)

`data' (@ref{192,,bytes} オブジェクト) を展開し、展開データを @ref{192,,bytes} オブジェクトとして返します。

`data' が複数の明確な圧縮ストリームの連結だった場合、すべてのストリームを展開し、結果の連結を返します。

引数 `format'、`memlimit'、および `filters' の説明は、上記 @ref{1acb,,LZMADecompressor} を参照してください。
@end deffn

@node その他<4>,カスタムフィルタチェインの指定,メモリ上での圧縮と展開<2>,lzma --- LZMA アルゴリズムを使用した圧縮
@anchor{library/lzma miscellaneous}@anchor{2e8c}
@subsubsection その他


@geindex is_check_supported() (lzma モジュール)
@anchor{library/lzma lzma is_check_supported}@anchor{2e8d}
@deffn {の関数} lzma.is_check_supported (check)

指定したインテグリティチェックがシステムでサポートされていれば @code{True} を返します。

@code{CHECK_NONE} および @code{CHECK_CRC32} は常にサポートされています。@code{CHECK_CRC64} および @code{CHECK_SHA256} は @code{liblzma} が機能制限セットでコンパイルされている場合利用できないことがあります。
@end deffn

@node カスタムフィルタチェインの指定,使用例<15>,その他<4>,lzma --- LZMA アルゴリズムを使用した圧縮
@anchor{library/lzma filter-chain-specs}@anchor{2e84}@anchor{library/lzma specifying-custom-filter-chains}@anchor{2e8e}
@subsubsection カスタムフィルタチェインの指定


フィルタチェイン指定子は、辞書のシーケンスで、各辞書は ID と単一フィルタのオプションからなります。各辞書はキー @code{"id"} を持たなければならず、フィルタ依存のオプションを指定する追加キーを持つ場合もあります。有効なフィルタ ID は以下のとおりです:


@itemize *

@item 
圧縮フィルタ:


@itemize *

@item 
@code{FILTER_LZMA1} (@code{FORMAT_ALONE} と共に使用)

@item 
@code{FILTER_LZMA2} (@code{FORMAT_XZ} および @code{FORMAT_RAW} と共に使用)
@end itemize

@item 
デルタフィルター:


@itemize *

@item 
@code{FILTER_DELTA}
@end itemize

@item 
ブランチコールジャンプ (BCJ) フィルター:


@itemize *

@item 
@code{FILTER_X86}

@item 
@code{FILTER_IA64}

@item 
@code{FILTER_ARM}

@item 
@code{FILTER_ARMTHUMB}

@item 
@code{FILTER_POWERPC}

@item 
@code{FILTER_SPARC}
@end itemize
@end itemize

一つのフィルタチェインは 4 個までのフィルタを定義することができ、空にはできません。チェインの最後は圧縮フィルタでなくてはならず、その他のフィルタはデルタまたは BCJ フィルタでなければなりません。

圧縮フィルタは以下のオプション (追加エントリとしてフィルタを表す辞書に指定) をサポートしています:


@itemize *

@item 
@code{preset}: 明示されていないオプションのデフォルト値のソースとして使用する圧縮プリセット。

@item 
@code{dict_size}: 辞書のサイズのバイト数。これは、 4 KiB から 1.5 GiB の間にしてください (両端を含みます)。

@item 
@code{lc}: リテラルコンテキストビットの数。

@item 
@code{lp}: リテラル位置ビットの数。@code{lc + lp} で最大 4 までです。

@item 
@code{pb}: 位置ビットの数。最大で 4 までです。

@item 
@code{mode}: @code{MODE_FAST} または @code{MODE_NORMAL}。

@item 
@code{nice_len}: マッチに "良い" とみなす長さ。273 以下でなければなりません。

@item 
@code{mf}: 使用するマッチファインダ -- @code{MF_HC3}、@code{MF_HC4}、@code{MF_BT2}、@code{MF_BT3}、または @code{MF_BT4}。

@item 
@code{depth}: マッチファインダが使用する検索の最大深度。0 (デフォルト) では他のフィルタオプションをベースに自動選択します。
@end itemize

デルタフィルターは、バイト間の差異を保存し、特定の状況で、コンプレッサーに対してさらに反復的な入力を生成します。
デルタフィルターは、1 つのオプション @code{dist} のみをサポートします。
これは差し引くバイトどうしの距離を示します。
デフォルトは 1 で、隣接するバイトの差異を扱います。

The BCJ filters are intended to be applied to machine code. They convert
relative branches, calls and jumps in the code to use absolute addressing, with
the aim of increasing the redundancy that can be exploited by the compressor.
These filters support one option, @code{start_offset}. This specifies the address
that should be mapped to the beginning of the input data. The default is 0.

@node 使用例<15>,,カスタムフィルタチェインの指定,lzma --- LZMA アルゴリズムを使用した圧縮
@anchor{library/lzma examples}@anchor{2e8f}
@subsubsection 使用例


圧縮ファイルからの読み込み:

@example
import lzma
with lzma.open("file.xz") as f:
    file_content = f.read()
@end example

圧縮ファイルの作成:

@example
import lzma
data = b"Insert Data Here"
with lzma.open("file.xz", "w") as f:
    f.write(data)
@end example

メモリ上でデータを圧縮:

@example
import lzma
data_in = b"Insert Data Here"
data_out = lzma.compress(data_in)
@end example

逐次圧縮:

@example
import lzma
lzc = lzma.LZMACompressor()
out1 = lzc.compress(b"Some data\n")
out2 = lzc.compress(b"Another piece of data\n")
out3 = lzc.compress(b"Even more data\n")
out4 = lzc.flush()
# Concatenate all the partial results:
result = b"".join([out1, out2, out3, out4])
@end example

すでにオープンしているファイルへの圧縮データの書き出し:

@example
import lzma
with open("file.xz", "wb") as f:
    f.write(b"This data will not be compressed\n")
    with lzma.open(f, "w") as lzf:
        lzf.write(b"This *will* be compressed\n")
    f.write(b"Not compressed\n")
@end example

カスタムフィルタチェインを使った圧縮ファイルの作成:

@example
import lzma
my_filters = [
    @{"id": lzma.FILTER_DELTA, "dist": 5@},
    @{"id": lzma.FILTER_LZMA2, "preset": 7 | lzma.PRESET_EXTREME@},
]
with lzma.open("file.xz", "w", filters=my_filters) as f:
    f.write(b"blah blah blah")
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node zipfile --- ZIP アーカイブの処理,tarfile --- tar アーカイブファイルの読み書き,lzma --- LZMA アルゴリズムを使用した圧縮,データ圧縮とアーカイブ
@anchor{library/zipfile doc}@anchor{2e90}@anchor{library/zipfile module-zipfile}@anchor{137}@anchor{library/zipfile translation-repo}@anchor{2e91}@anchor{library/zipfile zipfile-work-with-zip-archives}@anchor{2e92}
@subsection @code{zipfile} --- ZIP アーカイブの処理


@geindex module; zipfile

`Source code:' Lib/zipfile/@footnote{https://github.com/python/cpython/tree/3.14/Lib/zipfile/}


__________________________________________________________________


ZIP は一般によく知られているアーカイブ (書庫化) および圧縮の標準ファイルフォーマットです。このモジュールでは ZIP 形式のファイルの作成、読み書き、追記、書庫内のファイル一覧の作成を行うためのツールを提供します。より高度な使い方でこのモジュールを利用したいのであれば、 PKZIP Application Note@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT} に定義されている ZIP ファイルフォーマットの理解が必要になるでしょう。

This module does not handle multipart ZIP files.
It can handle ZIP files that use the ZIP64 extensions
(that is ZIP files that are more than 4 GiB in size).  It supports
decryption of encrypted files in ZIP archives, but it cannot
create an encrypted file.  Decryption is extremely slow as it is
implemented in native Python rather than C.

@c The following paragraph should be similar to ../includes/optional-module.rst

Handling compressed archives requires @ref{215a,,optional modules}
such as @ref{139,,zlib}, @ref{14,,bz2}, @ref{8e,,lzma}, and @ref{23,,compression.zstd}.
If any of them are missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

このモジュールは以下の項目を定義しています:

@geindex BadZipFile
@anchor{library/zipfile zipfile BadZipFile}@anchor{1b68}
@deffn {例外} zipfile.BadZipFile

正常ではない ZIP ファイルに対して送出されるエラーです。


Added in version 3.2.

@end deffn

@geindex BadZipfile
@anchor{library/zipfile zipfile BadZipfile}@anchor{2e93}
@deffn {例外} zipfile.BadZipfile

@ref{1b68,,BadZipFile} の別名です。過去のバージョンの Python との互換性のために用意されています。


バージョン 3.2 で非推奨.

@end deffn

@geindex LargeZipFile
@anchor{library/zipfile zipfile LargeZipFile}@anchor{2e94}
@deffn {例外} zipfile.LargeZipFile

ZIP ファイルが ZIP64 の機能を必要としているが、その機能が有効化されていない場合に送出されるエラーです。
@end deffn


@deffn {クラス} zipfile.ZipFile

ZIP ファイルの読み書きのためのクラスです。コンストラクタの詳細については、@ref{2e95,,ZipFile objects} 節を参照してください。
@end deffn


@deffn {クラス} zipfile.Path

@ref{266,,pathlib.Path} インターフェースの一部を実装したクラスです。
@ref{2fa,,importlib.resources.abc.Traversable} インターフェースは完全に実装しています。


Added in version 3.8.

@end deffn


@deffn {クラス} zipfile.PyZipFile

Python ライブラリを含む、ZIP アーカイブを作成するためのクラスです。
@end deffn

@geindex ZipInfo (zipfile のクラス)
@anchor{library/zipfile zipfile ZipInfo}@anchor{2cb}
@deffn {クラス} zipfile.ZipInfo (filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))

Class used to represent information about a member of an archive. Instances
of this class are returned by the @ref{2e96,,getinfo()} and @ref{2e97,,infolist()}
methods of @ref{8d3,,ZipFile} objects.  Most users of the @code{zipfile} module
will not need to create these, but only use those created by this
module. `filename' should be the full name of the archive member, and
`date_time' should be a tuple containing six fields which describe the time
of the last modification to the file; the fields are described in section
@ref{2e98,,ZipInfo objects}.


バージョン 3.13 で変更: A public @code{compress_level} attribute has been added to expose the
formerly protected @code{_compresslevel}.  The older protected name
continues to work as a property for backwards compatibility.


@geindex _for_archive() (zipfile.ZipInfo のメソッド)
@anchor{library/zipfile zipfile ZipInfo _for_archive}@anchor{2ca}
@deffn {メソッド} _for_archive (archive)

Resolve the date_time, compression attributes, and external attributes
to suitable defaults as used by @ref{2cc,,ZipFile.writestr()}.

Returns self for chaining.


Added in version 3.14.

@end deffn
@end deffn

@geindex is_zipfile() (zipfile モジュール)
@anchor{library/zipfile zipfile is_zipfile}@anchor{1542}
@deffn {の関数} zipfile.is_zipfile (filename)

`filename' が正しいマジックナンバをもつ ZIP ファイルの時に @code{True} を返し、そうでない場合 @code{False} を返します。`filename' にはファイルやファイルライクオブジェクトを渡すこともできます。


バージョン 3.1 で変更: ファイルおよびファイルライクオブジェクトをサポートしました。

@end deffn

@geindex ZIP_STORED (zipfile モジュール)
@anchor{library/zipfile zipfile ZIP_STORED}@anchor{2e99}
@deffn {データ} zipfile.ZIP_STORED

アーカイブメンバを圧縮しない (複数ファイルを一つにまとめるだけ) ことを表す数値定数です。
@end deffn

@geindex ZIP_DEFLATED (zipfile モジュール)
@anchor{library/zipfile zipfile ZIP_DEFLATED}@anchor{2e9a}
@deffn {データ} zipfile.ZIP_DEFLATED

通常の ZIP 圧縮方法を表す数値定数です。これには @ref{139,,zlib} モジュールが必要です。
@end deffn

@geindex ZIP_BZIP2 (zipfile モジュール)
@anchor{library/zipfile zipfile ZIP_BZIP2}@anchor{2e9b}
@deffn {データ} zipfile.ZIP_BZIP2

BZIP2 圧縮方法を表す数値定数です。これには @ref{14,,bz2} モジュールが必要です。


Added in version 3.3.

@end deffn

@geindex ZIP_LZMA (zipfile モジュール)
@anchor{library/zipfile zipfile ZIP_LZMA}@anchor{2e9c}
@deffn {データ} zipfile.ZIP_LZMA

LZMA 圧縮方法を表す数値定数です。これには @ref{8e,,lzma} モジュールが必要です。


Added in version 3.3.

@end deffn

@geindex ZIP_ZSTANDARD (zipfile モジュール)
@anchor{library/zipfile zipfile ZIP_ZSTANDARD}@anchor{2e9d}
@deffn {データ} zipfile.ZIP_ZSTANDARD

The numeric constant for Zstandard compression. This requires the
@ref{23,,compression.zstd} module.

@cartouche
@quotation 注釈 
In APPNOTE 6.3.7, the method ID @code{20} was assigned to Zstandard
compression. This was changed in APPNOTE 6.3.8 to method ID @code{93} to
avoid conflicts, with method ID @code{20} being deprecated. For
compatibility, the @code{zipfile} module reads both method IDs but will
only write data with method ID @code{93}.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@cartouche
@quotation 注釈 
The ZIP file format specification has included support for bzip2 compression
since 2001, for LZMA compression since 2006, and Zstandard compression since
2020. However, some tools (including older Python releases) do not support
these compression methods, and may either refuse to process the ZIP file
altogether, or fail to extract individual files.
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@item PKZIP Application Note@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT}

ZIP ファイルフォーマットおよびアルゴリズムを作成した Phil Katz によるドキュメント。

@item Info-ZIP Home Page@footnote{https://infozip.sourceforge.net/}

Info-ZIP プロジェクトによる ZIP アーカイブプログラムおよびプログラム開発ライブラリに関する情報。
@end table


@menu
* ZipFile objects:: 
* Path objects:: 
* PyZipFile objects:: 
* ZipInfo objects:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<4>. 
* Decompression pitfalls:: 

@end menu

@node ZipFile objects,Path objects,,zipfile --- ZIP アーカイブの処理
@anchor{library/zipfile id1}@anchor{2e9e}@anchor{library/zipfile zipfile-objects}@anchor{2e95}
@subsubsection ZipFile objects


@geindex ZipFile (zipfile のクラス)
@anchor{library/zipfile zipfile ZipFile}@anchor{8d3}
@deffn {クラス} zipfile.ZipFile (file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True, metadata_encoding=None)

ZIP ファイルを開きます。 `file' はファイルのパス (文字列) か、ファイルライクオブジェクト、 @ref{5a1,,path-like object} のいずれかです。

`mode' パラメータには、既存のファイルを読み込む場合は @code{'r'} 、内容を消去して新しいファイルに書き込む場合は  @code{'w'} 、既存のファイルの末尾に追加する場合は  @code{'a'} 、ファイルが存在しない場合にのみファイルを作成して書き込む場合は @code{'x'} を指定します。
`mode' が @code{'x'} で `file' が既存のファイルを指している場合、 @ref{1221,,FileExistsError} が発生します。
`mode' が @code{'a'} で `file' が既存の ZIP ファイルを指している場合、新しい ZIP アーカイブがそのファイルに追加されます。
`file' が ZIP ファイルでない場合は、ファイルの末尾にあたらしい ZIP アーカイブが追加されます。
これは、既存のファイル (例えば @code{python.exe}) に ZIP アーカイブを付け加える用途を想定したものです。
`mode' が @code{'a'} で `file' が存在しない場合は、ファイルが作成されます。
`mode' が @code{'r'} か @code{'a'} の場合、ファイルはシーク可能である必要があります。

`compression' is the ZIP compression method to use when writing the archive,
and should be @ref{2e99,,ZIP_STORED}, @ref{2e9a,,ZIP_DEFLATED},
@ref{2e9b,,ZIP_BZIP2}, @ref{2e9c,,ZIP_LZMA}, or @ref{2e9d,,ZIP_ZSTANDARD};
unrecognized values will cause @ref{36b,,NotImplementedError} to be raised.  If
@ref{2e9a,,ZIP_DEFLATED}, @ref{2e9b,,ZIP_BZIP2}, @ref{2e9c,,ZIP_LZMA}, or
@ref{2e9d,,ZIP_ZSTANDARD} is specified but the corresponding module
(@ref{139,,zlib}, @ref{14,,bz2}, @ref{8e,,lzma}, or @ref{23,,compression.zstd}) is not
available, @ref{244,,RuntimeError} is raised. The default is @ref{2e99,,ZIP_STORED}.

If `allowZip64' is @code{True} (the default) zipfile will create ZIP files that
use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is
@code{false} @code{zipfile} will raise an exception when the ZIP file would
require ZIP64 extensions.

The `compresslevel' parameter controls the compression level to use when
writing files to the archive.
When using @ref{2e99,,ZIP_STORED} or @ref{2e9c,,ZIP_LZMA} it has no effect.
When using @ref{2e9a,,ZIP_DEFLATED} integers @code{0} through @code{9} are accepted
(see @ref{2e33,,zlib} for more information).
When using @ref{2e9b,,ZIP_BZIP2} integers @code{1} through @code{9} are accepted
(see @ref{a66,,bz2} for more information).
When using @ref{2e9d,,ZIP_ZSTANDARD} integers @code{-131072} through @code{22} are
commonly accepted (see
@ref{2df1,,CompressionParameter.compression_level}
for more on retrieving valid values and their meaning).

The `strict_timestamps' argument, when set to @code{False}, allows to
zip files older than 1980-01-01 at the cost of setting the
timestamp to 1980-01-01.
Similar behavior occurs with files newer than 2107-12-31,
the timestamp is also set to the limit.

When mode is @code{'r'}, `metadata_encoding' may be set to the name of a codec,
which will be used to decode metadata such as the names of members and ZIP
comments.

ファイルがモード @code{'w'}、 @code{'x'} または @code{'a'} で作成され、その後そのアーカイブにファイルを追加することなく @ref{2e9f,,クローズ} された場合、空のアーカイブのための適切な ZIP 構造がファイルに書き込まれます。

ZipFile はコンテキストマネージャにもなっているので、@ref{186,,with} 文をサポートしています。次の例では、`myzip' は @code{with} 文のブロックが終了したときに、(たとえ例外が発生したとしても) クローズされます:

@example
with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')
@end example

@cartouche
@quotation 注釈 
`metadata_encoding' is an instance-wide setting for the ZipFile.
It is not possible to set this on a per-member basis.

This attribute is a workaround for legacy implementations which produce
archives with names in the current locale encoding or code page (mostly
on Windows).  According to the .ZIP standard, the encoding of metadata
may be specified to be either IBM code page (default) or UTF-8 by a flag
in the archive header.
That flag takes precedence over `metadata_encoding', which is
a Python-specific extension.
@end quotation
@end cartouche


バージョン 3.2 で変更: @ref{8d3,,ZipFile} をコンテキストマネージャとして使用できるようになりました。



バージョン 3.3 で変更: @ref{14,,bzip2} および @ref{8e,,lzma} 圧縮をサポートしました。



バージョン 3.4 で変更: ZIP64 拡張がデフォルトで有効になりました。



バージョン 3.5 で変更: seek 出来ないストリームのサポートが追加されました。@code{'x'} モードのサポートが追加されました。



バージョン 3.6 で変更: Previously, a plain @ref{244,,RuntimeError} was raised for unrecognized
compression values.



バージョン 3.6.2 で変更: `file' 引数が @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.7 で変更: `compresslevel' パラメータが追加されました。



バージョン 3.8 で変更: The `strict_timestamps' keyword-only parameter.



バージョン 3.11 で変更: Added support for specifying member name encoding for reading
metadata in the zipfile's directory and file headers.

@end deffn

@geindex close() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile close}@anchor{2e9f}
@deffn {メソッド} ZipFile.close ()

アーカイブファイルをクローズします。@ref{2e9f,,close()} はプログラムを終了する前に必ず呼び出さなければなりません。さもないとアーカイブ上の重要なレコードが書き込まれません。
@end deffn

@geindex getinfo() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile getinfo}@anchor{2e96}
@deffn {メソッド} ZipFile.getinfo (name)

アーカイブメンバ `name' に関する情報を持つ @ref{2cb,,ZipInfo} オブジェクトを返します。アーカイブに含まれないファイル名に対して @ref{2e96,,getinfo()} を呼び出すと、@ref{5e7,,KeyError} が送出されます。
@end deffn

@geindex infolist() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile infolist}@anchor{2e97}
@deffn {メソッド} ZipFile.infolist ()

アーカイブに含まれる各メンバの @ref{2cb,,ZipInfo} オブジェクトからなるリストを返します。既存のアーカイブファイルを開いている場合、リストの順番は実際の ZIP ファイル中のメンバの順番と同じになります。
@end deffn

@geindex namelist() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile namelist}@anchor{2ea0}
@deffn {メソッド} ZipFile.namelist ()

アーカイブメンバの名前のリストを返します。
@end deffn

@geindex open() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile open}@anchor{65d}
@deffn {メソッド} ZipFile.open (name, mode='r', pwd=None, *, force_zip64=False)

Access a member of the archive as a binary file-like object.  `name'
can be either the name of a file within the archive or a @ref{2cb,,ZipInfo}
object.  The `mode' parameter, if included, must be @code{'r'} (the default)
or @code{'w'}.  `pwd' is the password used to decrypt encrypted ZIP files as a
@ref{192,,bytes} object.

@ref{65d,,open()} はコンテキストマネージャでもあるので @ref{186,,with} 文をサポートしています:

@example
with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:
        print(myfile.read())
@end example

With `mode' @code{'r'} the file-like object
(@code{ZipExtFile}) is read-only and provides the following methods:
@ref{1540,,read()}, @ref{1541,,readline()},
@ref{27a1,,readlines()}, @ref{14a4,,seek()},
@ref{15c6,,tell()}, @ref{20aa,,__iter__()}, @ref{14e5,,__next__()}.
These objects can operate independently of the ZipFile.

With @code{mode='w'}, a writable file handle is returned, which supports the
@ref{ed7,,write()} method.  While a writable file handle is open,
attempting to read or write other files in the ZIP file will raise a
@ref{2ec,,ValueError}.

In both cases the file-like object has also attributes @code{name},
which is equivalent to the name of a file within the archive, and
@code{mode}, which is @code{'rb'} or @code{'wb'} depending on the input mode.

When writing a file, if the file size is not known in advance but may exceed
2 GiB, pass @code{force_zip64=True} to ensure that the header format is
capable of supporting large files.  If the file size is known in advance,
construct a @ref{2cb,,ZipInfo} object with @ref{2ea1,,file_size} set, and
use that as the `name' parameter.

@cartouche
@quotation 注釈 
@ref{65d,,open()}、@ref{2ea2,,read()}、および @ref{2ea3,,extract()} メソッドには、ファイル名または @ref{2cb,,ZipInfo} オブジェクトを指定できます。これは重複する名前のメンバを含む ZIP ファイルを読み込むときにそのメリットを享受できるでしょう。
@end quotation
@end cartouche


バージョン 3.6 で変更: Removed support of @code{mode='U'}.  Use @ref{9be,,io.TextIOWrapper} for reading
compressed text files in @ref{f35,,universal newlines} mode.



バージョン 3.6 で変更: @ref{65d,,ZipFile.open()} can now be used to write files into the archive with the
@code{mode='w'} option.



バージョン 3.6 で変更: Calling @ref{65d,,open()} on a closed ZipFile will raise a @ref{2ec,,ValueError}.
Previously, a @ref{244,,RuntimeError} was raised.



バージョン 3.13 で変更: Added attributes @code{name} and @code{mode} for the writeable
file-like object.
The value of the @code{mode} attribute for the readable file-like
object was changed from @code{'r'} to @code{'rb'}.

@end deffn

@geindex extract() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile extract}@anchor{2ea3}
@deffn {メソッド} ZipFile.extract (member, path=None, pwd=None)

Extract a member from the archive to the current working directory; `member'
must be its full name or a @ref{2cb,,ZipInfo} object.  Its file information is
extracted as accurately as possible.  `path' specifies a different directory
to extract to.  `member' can be a filename or a @ref{2cb,,ZipInfo} object.
`pwd' is the password used for encrypted files as a @ref{192,,bytes} object.

作成された (ディレクトリか新ファイルの) 正規化されたパスを返します。

@cartouche
@quotation 注釈 
メンバのファイル名が絶対パスなら、ドライブ/UNC sharepoint および先頭の (バック) スラッシュは取り除かれます。例えば、Unix で @code{///foo/bar} は @code{foo/bar} となり、Window で @code{C:\foo\bar} は @code{foo\bar} となります。また、メンバのファイル名に含まれる全ての @code{".."} は取り除かれます。例えば、@code{../../foo../../ba..r} は @code{foo../ba..r} となります。Windows では、不正な文字 (@code{:}, @code{<}, @code{>}, @code{|}, @code{"}, @code{?}, および @code{*}) はアンダースコア (@code{_}) で置き換えられます。
@end quotation
@end cartouche


バージョン 3.6 で変更: Calling @ref{2ea3,,extract()} on a closed ZipFile will raise a
@ref{2ec,,ValueError}.  Previously, a @ref{244,,RuntimeError} was raised.



バージョン 3.6.2 で変更: `path' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex extractall() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile extractall}@anchor{2ea4}
@deffn {メソッド} ZipFile.extractall (path=None, members=None, pwd=None)

Extract all members from the archive to the current working directory.  `path'
specifies a different directory to extract to.  `members' is optional and must
be a subset of the list returned by @ref{2ea0,,namelist()}.  `pwd' is the password
used for encrypted files as a @ref{192,,bytes} object.

@cartouche
@quotation 警告 
信頼できないソースからきた Zip ファイルを、事前に中身をチェックせずに展開してはいけません。ファイルを `path' の外側に作成することができるからです。例えば、 @code{"/"}  で始まる絶対パスを持ったメンバーや、 2 つのドット @code{".."} を持つファイル名などの場合です。このモジュールはそれを避けようとします。 @ref{2ea3,,extract()} の注釈を参照してください。
@end quotation
@end cartouche


バージョン 3.6 で変更: Calling @ref{2ea4,,extractall()} on a closed ZipFile will raise a
@ref{2ec,,ValueError}.  Previously, a @ref{244,,RuntimeError} was raised.



バージョン 3.6.2 で変更: `path' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex printdir() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile printdir}@anchor{2ea5}
@deffn {メソッド} ZipFile.printdir ()

アーカイブの内容の一覧を @code{sys.stdout} に出力します。
@end deffn

@geindex setpassword() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile setpassword}@anchor{2ea6}
@deffn {メソッド} ZipFile.setpassword (pwd)

Set `pwd' (a @ref{192,,bytes} object) as default password to extract encrypted files.
@end deffn

@geindex read() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile read}@anchor{2ea2}
@deffn {メソッド} ZipFile.read (name, pwd=None)

Return the bytes of the file `name' in the archive.  `name' is the name of the
file in the archive, or a @ref{2cb,,ZipInfo} object.  The archive must be open for
read or append. `pwd' is the password used for encrypted files as a @ref{192,,bytes}
object and, if specified, overrides the default password set with @ref{2ea6,,setpassword()}.
Calling @ref{2ea2,,read()} on a ZipFile that uses a compression method other than
@ref{2e99,,ZIP_STORED}, @ref{2e9a,,ZIP_DEFLATED}, @ref{2e9b,,ZIP_BZIP2},
@ref{2e9c,,ZIP_LZMA}, or @ref{2e9d,,ZIP_ZSTANDARD} will raise a
@ref{36b,,NotImplementedError}. An error will also be raised if the
corresponding compression module is not available.


バージョン 3.6 で変更: Calling @ref{2ea2,,read()} on a closed ZipFile will raise a @ref{2ec,,ValueError}.
Previously, a @ref{244,,RuntimeError} was raised.

@end deffn

@geindex testzip() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile testzip}@anchor{2ea7}
@deffn {メソッド} ZipFile.testzip ()

Read all the files in the archive and check their CRC's and file headers.
Return the name of the first bad file, or else return @code{None}.


バージョン 3.6 で変更: Calling @ref{2ea7,,testzip()} on a closed ZipFile will raise a
@ref{2ec,,ValueError}.  Previously, a @ref{244,,RuntimeError} was raised.

@end deffn

@geindex write() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile write}@anchor{f49}
@deffn {メソッド} ZipFile.write (filename, arcname=None, compress_type=None, compresslevel=None)

Write the file named `filename' to the archive, giving it the archive name
`arcname' (by default, this will be the same as `filename', but without a drive
letter and with leading path separators removed).  If given, `compress_type'
overrides the value given for the `compression' parameter to the constructor for
the new entry. Similarly, `compresslevel' will override the constructor if
given.
The archive must be open with mode @code{'w'}, @code{'x'} or @code{'a'}.

@cartouche
@quotation 注釈 
The ZIP file standard historically did not specify a metadata encoding,
but strongly recommended CP437 (the original IBM PC encoding) for
interoperability.  Recent versions allow use of UTF-8 (only).  In this
module, UTF-8 will automatically be used to write the member names if
they contain any non-ASCII characters.  It is not possible to write
member names in any encoding other than ASCII or UTF-8.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
アーカイブ名はアーカイブルートに対する相対パスでなければなりません。言い換えると、アーカイブ名はパスセパレータで始まってはいけません。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
もし、@code{arcname} (@code{arcname} が与えられない場合は、@code{filename}) が null byte を含むなら、アーカイブ中のファイルのファイル名は、null byte までで切り詰められます。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
A leading slash in the filename may lead to the archive being impossible to
open in some zip programs on Windows systems.
@end quotation
@end cartouche


バージョン 3.6 で変更: Calling @ref{f49,,write()} on a ZipFile created with mode @code{'r'} or
a closed ZipFile will raise a @ref{2ec,,ValueError}.  Previously,
a @ref{244,,RuntimeError} was raised.

@end deffn

@geindex writestr() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile writestr}@anchor{2cc}
@deffn {メソッド} ZipFile.writestr (zinfo_or_arcname, data, compress_type=None, compresslevel=None)

Write a file into the archive.  The contents is `data', which may be either
a @ref{169,,str} or a @ref{192,,bytes} instance; if it is a @ref{169,,str},
it is encoded as UTF-8 first.  `zinfo_or_arcname' is either the file
name it will be given in the archive, or a @ref{2cb,,ZipInfo} instance.  If it's
an instance, at least the filename, date, and time must be given.  If it's a
name, the date and time is set to the current date and time.
The archive must be opened with mode @code{'w'}, @code{'x'} or @code{'a'}.

If given, `compress_type' overrides the value given for the `compression'
parameter to the constructor for the new entry, or in the `zinfo_or_arcname'
(if that is a @ref{2cb,,ZipInfo} instance). Similarly, `compresslevel' will
override the constructor if given.

@cartouche
@quotation 注釈 
@ref{2cb,,ZipInfo} インスタンスを引数 `zinfo_or_arcname' として与えた場合、与えられた @ref{2cb,,ZipInfo} インスタンスのメンバーである `compress_type' で指定された圧縮方法が使われます。デフォルトでは、@ref{2cb,,ZipInfo} コンストラクターが、このメンバーを @ref{2e99,,ZIP_STORED} に設定します。
@end quotation
@end cartouche


バージョン 3.2 で変更: 引数 `compress_type' を追加しました。



バージョン 3.6 で変更: Calling @ref{2cc,,writestr()} on a ZipFile created with mode @code{'r'} or
a closed ZipFile will raise a @ref{2ec,,ValueError}.  Previously,
a @ref{244,,RuntimeError} was raised.

@end deffn

@geindex mkdir() (zipfile.ZipFile のメソッド)
@anchor{library/zipfile zipfile ZipFile mkdir}@anchor{8d4}
@deffn {メソッド} ZipFile.mkdir (zinfo_or_directory, mode=511)

Create a directory inside the archive.  If `zinfo_or_directory' is a string,
a directory is created inside the archive with the mode that is specified in
the `mode' argument. If, however, `zinfo_or_directory' is
a @ref{2cb,,ZipInfo} instance then the `mode' argument is ignored.

The archive must be opened with mode @code{'w'}, @code{'x'} or @code{'a'}.


Added in version 3.11.

@end deffn

以下のデータ属性も利用することができます:

@geindex filename (zipfile.ZipFile の属性)
@anchor{library/zipfile zipfile ZipFile filename}@anchor{2ea8}
@deffn {の属性} ZipFile.filename

ZIP ファイルの名前です。
@end deffn

@geindex debug (zipfile.ZipFile の属性)
@anchor{library/zipfile zipfile ZipFile debug}@anchor{2ea9}
@deffn {の属性} ZipFile.debug

使用するデバッグ出力レベルです。この属性は @code{0} (デフォルト、何も出力しない) から @code{3} (最も多く出力する) までの値に設定することができます。デバッグ情報は @code{sys.stdout} に出力されます。
@end deffn

@geindex comment (zipfile.ZipFile の属性)
@anchor{library/zipfile zipfile ZipFile comment}@anchor{2eaa}
@deffn {の属性} ZipFile.comment

ZIP ファイルに @ref{192,,bytes} オブジェクトとして関連付けられたコメントです。モード @code{'w'} 、 @code{'x'} または @code{'a'} で作成された @ref{8d3,,ZipFile} インスタンスへコメントを割り当てる場合、文字列長は 65535 バイトまでにしてください。その長さを超えたコメントは切り捨てられます。
@end deffn

@node Path objects,PyZipFile objects,ZipFile objects,zipfile --- ZIP アーカイブの処理
@anchor{library/zipfile id2}@anchor{2eab}@anchor{library/zipfile path-objects}@anchor{2eac}
@subsubsection Path objects


@geindex Path (zipfile のクラス)
@anchor{library/zipfile zipfile Path}@anchor{8d8}
@deffn {クラス} zipfile.Path (root, at='@w{'})

Construct a Path object from a @code{root} zipfile (which may be a
@ref{8d3,,ZipFile} instance or @code{file} suitable for passing to
the @ref{8d3,,ZipFile} constructor).

@code{at} specifies the location of this Path within the zipfile,
e.g. 'dir/file.txt', 'dir/', or '@w{'}. Defaults to the empty string,
indicating the root.

@cartouche
@quotation 注釈 
The @ref{8d8,,Path} class does not sanitize filenames within the ZIP archive. Unlike
the @ref{2ea3,,ZipFile.extract()} and @ref{2ea4,,ZipFile.extractall()} methods, it is the
caller's responsibility to validate or sanitize filenames to prevent path traversal
vulnerabilities (e.g., filenames containing ".." or absolute paths). When handling
untrusted archives, consider resolving filenames using @ref{1532,,os.path.abspath()}
and checking against the target directory with @ref{103d,,os.path.commonpath()}.
@end quotation
@end cartouche
@end deffn

Path objects expose the following features of @ref{266,,pathlib.Path}
objects:

Path objects are traversable using the @code{/} operator or @code{joinpath}.

@geindex name (zipfile.Path の属性)
@anchor{library/zipfile zipfile Path name}@anchor{2ead}
@deffn {の属性} Path.name

The final path component.
@end deffn

@geindex open() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path open}@anchor{1907}
@deffn {メソッド} Path.open (mode='r', *, pwd, **)

Invoke @ref{65d,,ZipFile.open()} on the current path.
Allows opening for read or write, text or binary
through supported modes: 'r', 'w', 'rb', 'wb'.
Positional and keyword arguments are passed through to
@ref{9be,,io.TextIOWrapper} when opened as text and
ignored otherwise.
@code{pwd} is the @code{pwd} parameter to
@ref{65d,,ZipFile.open()}.


バージョン 3.9 で変更: Added support for text and binary modes for open. Default
mode is now text.



バージョン 3.11.2 で変更: The @code{encoding} parameter can be supplied as a positional argument
without causing a @ref{198,,TypeError}. As it could in 3.9. Code needing to
be compatible with unpatched 3.10 and 3.11 versions must pass all
@ref{9be,,io.TextIOWrapper} arguments, @code{encoding} included, as keywords.

@end deffn

@geindex iterdir() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path iterdir}@anchor{2eae}
@deffn {メソッド} Path.iterdir ()

Enumerate the children of the current directory.
@end deffn

@geindex is_dir() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path is_dir}@anchor{2eaf}
@deffn {メソッド} Path.is_dir ()

Return @code{True} if the current context references a directory.
@end deffn

@geindex is_file() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path is_file}@anchor{2eb0}
@deffn {メソッド} Path.is_file ()

Return @code{True} if the current context references a file.
@end deffn

@geindex is_symlink() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path is_symlink}@anchor{2eb1}
@deffn {メソッド} Path.is_symlink ()

Return @code{True} if the current context references a symbolic link.


Added in version 3.12.



バージョン 3.13 で変更: Previously, @code{is_symlink} would unconditionally return @code{False}.

@end deffn

@geindex exists() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path exists}@anchor{2eb2}
@deffn {メソッド} Path.exists ()

Return @code{True} if the current context references a file or
directory in the zip file.
@end deffn

@geindex Path.suffix (zipfile モジュール)
@anchor{library/zipfile zipfile Path suffix}@anchor{8d6}
@deffn {データ} Path.suffix

The last dot-separated portion of the final component, if any.
This is commonly called the file extension.


Added in version 3.11: Added @ref{8d6,,Path.suffix} property.

@end deffn

@geindex Path.stem (zipfile モジュール)
@anchor{library/zipfile zipfile Path stem}@anchor{8d5}
@deffn {データ} Path.stem

The final path component, without its suffix.


Added in version 3.11: Added @ref{8d5,,Path.stem} property.

@end deffn

@geindex Path.suffixes (zipfile モジュール)
@anchor{library/zipfile zipfile Path suffixes}@anchor{8d7}
@deffn {データ} Path.suffixes

A list of the path’s suffixes, commonly called file extensions.


Added in version 3.11: Added @ref{8d7,,Path.suffixes} property.

@end deffn

@geindex read_text() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path read_text}@anchor{1ade}
@deffn {メソッド} Path.read_text (*, **)

Read the current file as unicode text. Positional and
keyword arguments are passed through to
@ref{9be,,io.TextIOWrapper} (except @code{buffer}, which is
implied by the context).


バージョン 3.11.2 で変更: The @code{encoding} parameter can be supplied as a positional argument
without causing a @ref{198,,TypeError}. As it could in 3.9. Code needing to
be compatible with unpatched 3.10 and 3.11 versions must pass all
@ref{9be,,io.TextIOWrapper} arguments, @code{encoding} included, as keywords.

@end deffn

@geindex read_bytes() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path read_bytes}@anchor{2eb3}
@deffn {メソッド} Path.read_bytes ()

Read the current file as bytes.
@end deffn

@geindex joinpath() (zipfile.Path のメソッド)
@anchor{library/zipfile zipfile Path joinpath}@anchor{2eb4}
@deffn {メソッド} Path.joinpath (*other)

Return a new Path object with each of the `other' arguments
joined. The following are equivalent:

@example
>>> Path(...).joinpath('child').joinpath('grandchild')
>>> Path(...).joinpath('child', 'grandchild')
>>> Path(...) / 'child' / 'grandchild'
@end example


バージョン 3.10 で変更: Prior to 3.10, @code{joinpath} was undocumented and accepted
exactly one parameter.

@end deffn

The zipp@footnote{https://pypi.org/project/zipp/} project provides backports
of the latest path object functionality to older Pythons. Use
@code{zipp.Path} in place of @code{zipfile.Path} for early access to
changes.

@node PyZipFile objects,ZipInfo objects,Path objects,zipfile --- ZIP アーカイブの処理
@anchor{library/zipfile id3}@anchor{2eb5}@anchor{library/zipfile pyzipfile-objects}@anchor{2eb6}
@subsubsection PyZipFile objects


@ref{11fa,,PyZipFile} コンストラクタは @ref{8d3,,ZipFile} コンストラクタと同じパラメータに加え、`optimize' パラメータをとります。

@geindex PyZipFile (zipfile のクラス)
@anchor{library/zipfile zipfile PyZipFile}@anchor{11fa}
@deffn {クラス} zipfile.PyZipFile (file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1)


バージョン 3.2 で変更: Added the `optimize' parameter.



バージョン 3.4 で変更: ZIP64 拡張がデフォルトで有効になりました。


インスタンスは @ref{8d3,,ZipFile} オブジェクトのメソッドの他に、追加のメソッドを 1 個持ちます:

@geindex writepy() (zipfile.PyZipFile のメソッド)
@anchor{library/zipfile zipfile PyZipFile writepy}@anchor{11fb}
@deffn {メソッド} writepy (pathname, basename='@w{'}, filterfunc=None)

@code{*.py} ファイルを探し、一致するファイルをアーカイブに追加します。

@ref{11fa,,PyZipFile} に `optimize' 引数が与えられない場合、あるいは @code{-1} が指定された場合、対応するファイルは @code{*.pyc} ファイルで、必要に応じてコンパイルします。

@ref{11fa,,PyZipFile} の `optimize' パラメータが @code{0}、@code{1}、あるいは @code{2} の場合、それを最適化レベル (@ref{4b1,,compile()} 参照) とするファイルのみが、必要に応じてコンパイルされアーカイブに追加されます。

If `pathname' is a file, the filename must end with @code{.py}, and
just the (corresponding @code{*.pyc}) file is added at the top level
(no path information).  If `pathname' is a file that does not end with
@code{.py}, a @ref{244,,RuntimeError} will be raised.  If it is a directory,
and the directory is not a package directory, then all the files
@code{*.pyc} are added at the top level.  If the directory is a
package directory, then all @code{*.pyc} are added under the package
name as a file path, and if any subdirectories are package directories,
all of these are added recursively in sorted order.

`basename' は内部が使用するためだけのものです。

`filterfunc' を与える場合、単一の文字列引数を取る関数を渡してください。これには(個々のフルパスを含む)それぞれのパスがアーカイブに加えられる前に渡されます。 `filterfunc' が偽を返せば、そのパスはアーカイブに追加されず、ディレクトリだった場合はその中身が無視されます。例として、私たちのテストファイルが全て @code{test} ディレクトリの中にあるか、 @code{test} 文字列で始まるとしましょう。 `filterfunc' を使ってそれらを除外出来ます:

@example
>>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
...     fn = os.path.basename(s)
...     return (not (fn == 'test' or fn.startswith('test_')))
...
>>> zf.writepy('myprog', filterfunc=notests)
@end example

@ref{11fb,,writepy()} メソッドは以下のようなファイル名でアーカイブを作成します:

@example
string.pyc                   # Top level name
test/__init__.pyc            # Package directory
test/testall.pyc             # Module test.testall
test/bogus/__init__.pyc      # Subpackage directory
test/bogus/myfile.pyc        # Submodule test.bogus.myfile
@end example


バージョン 3.4 で変更: Added the `filterfunc' parameter.



バージョン 3.6.2 で変更: `pathname' 引数が @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.7 で変更: Recursion sorts directory entries.

@end deffn
@end deffn

@node ZipInfo objects,コマンドライン・インターフェース<4>,PyZipFile objects,zipfile --- ZIP アーカイブの処理
@anchor{library/zipfile id4}@anchor{2eb7}@anchor{library/zipfile zipinfo-objects}@anchor{2e98}
@subsubsection ZipInfo objects


@ref{2cb,,ZipInfo} クラスのインスタンスは、@ref{8d3,,ZipFile} オブジェクトの @ref{2e96,,getinfo()} および @ref{2e97,,infolist()} メソッドによって返されます。各オブジェクトは ZIP アーカイブ内の 1 個のメンバに関する情報を格納します。

There is one classmethod to make a @ref{2cb,,ZipInfo} instance for a filesystem
file:

@geindex from_file() (zipfile.ZipInfo のクラスメソッド)
@anchor{library/zipfile zipfile ZipInfo from_file}@anchor{f06}
@deffn {メソッド} classmethod ZipInfo.from_file (filename, arcname=None, *, strict_timestamps=True)

Construct a @ref{2cb,,ZipInfo} instance for a file on the filesystem, in
preparation for adding it to a zip file.

`filename' should be the path to a file or directory on the filesystem.

If `arcname' is specified, it is used as the name within the archive.
If `arcname' is not specified, the name will be the same as `filename', but
with any drive letter and leading path separators removed.

The `strict_timestamps' argument, when set to @code{False}, allows to
zip files older than 1980-01-01 at the cost of setting the
timestamp to 1980-01-01.
Similar behavior occurs with files newer than 2107-12-31,
the timestamp is also set to the limit.


Added in version 3.6.



バージョン 3.6.2 で変更: `filename' 引数が @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.8 で変更: Added the `strict_timestamps' keyword-only parameter.

@end deffn

インスタンスは以下のメソッドと属性を持ちます:

@geindex is_dir() (zipfile.ZipInfo のメソッド)
@anchor{library/zipfile zipfile ZipInfo is_dir}@anchor{f07}
@deffn {メソッド} ZipInfo.is_dir ()

アーカイブのメンバーがディレクトリの場合に @code{True} を返します。

This uses the entry's name: directories should always end with @code{/}.


Added in version 3.6.

@end deffn

@geindex filename (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo filename}@anchor{2eb8}
@deffn {の属性} ZipInfo.filename

アーカイブ中のファイル名。
@end deffn

@geindex date_time (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo date_time}@anchor{2eb9}
@deffn {の属性} ZipInfo.date_time

The time and date of the last modification to the archive member.  This is a
tuple of six values representing the "last [modified] file time" and "last [modified] file date"
fields from the ZIP file's central directory.

The tuple contains:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

値

@item

@code{0}

@tab

西暦年 (>= 1980)

@item

@code{1}

@tab

月 (1 から始まる)

@item

@code{2}

@tab

日 (1 から始まる)

@item

@code{3}

@tab

時 (0 から始まる)

@item

@code{4}

@tab

分 (0 から始まる)

@item

@code{5}

@tab

秒 (0 から始まる)

@end multitable


@cartouche
@quotation 注釈 
The ZIP format supports multiple timestamp fields in different locations
(central directory, extra fields for NTFS/UNIX systems, etc.). This attribute
specifically returns the timestamp from the central directory. The central
directory timestamp format in ZIP files does not support timestamps before
1980. While some extra field formats (such as UNIX timestamps) can represent
earlier dates, this attribute only returns the central directory timestamp.

The central directory timestamp is interpreted as representing local
time, rather than UTC time, to match the behavior of other zip tools.
@end quotation
@end cartouche
@end deffn

@geindex compress_type (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo compress_type}@anchor{2eba}
@deffn {の属性} ZipInfo.compress_type

アーカイブメンバの圧縮形式。
@end deffn

@geindex comment (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo comment}@anchor{2ebb}
@deffn {の属性} ZipInfo.comment

Comment for the individual archive member as a @ref{192,,bytes} object.
@end deffn

@geindex extra (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo extra}@anchor{2ebc}
@deffn {の属性} ZipInfo.extra

拡張フィールドデータ。この @ref{192,,bytes} オブジェクトに含まれているデータの内部構成については、PKZIP Application Note@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT} でコメントされています。
@end deffn

@geindex create_system (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo create_system}@anchor{2ebd}
@deffn {の属性} ZipInfo.create_system

ZIP アーカイブを作成したシステムを記述する文字列。
@end deffn

@geindex create_version (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo create_version}@anchor{2ebe}
@deffn {の属性} ZipInfo.create_version

このアーカイブを作成した PKZIP のバージョン。
@end deffn

@geindex extract_version (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo extract_version}@anchor{2ebf}
@deffn {の属性} ZipInfo.extract_version

このアーカイブを展開する際に必要な PKZIP のバージョン。
@end deffn

@geindex reserved (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo reserved}@anchor{2ec0}
@deffn {の属性} ZipInfo.reserved

予約領域。ゼロでなくてはなりません。
@end deffn

@geindex flag_bits (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo flag_bits}@anchor{2ec1}
@deffn {の属性} ZipInfo.flag_bits

ZIP フラグビット列。
@end deffn

@geindex volume (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo volume}@anchor{2ec2}
@deffn {の属性} ZipInfo.volume

ファイルヘッダのボリューム番号。
@end deffn

@geindex internal_attr (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo internal_attr}@anchor{2ec3}
@deffn {の属性} ZipInfo.internal_attr

内部属性。
@end deffn

@geindex external_attr (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo external_attr}@anchor{2ec4}
@deffn {の属性} ZipInfo.external_attr

外部ファイル属性。
@end deffn

@geindex header_offset (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo header_offset}@anchor{2ec5}
@deffn {の属性} ZipInfo.header_offset

ファイルヘッダへのバイトオフセット。
@end deffn

@geindex CRC (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo CRC}@anchor{2ec6}
@deffn {の属性} ZipInfo.CRC

圧縮前のファイルの CRC-32 チェックサム。
@end deffn

@geindex compress_size (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo compress_size}@anchor{2ec7}
@deffn {の属性} ZipInfo.compress_size

圧縮後のデータのサイズ。
@end deffn

@geindex file_size (zipfile.ZipInfo の属性)
@anchor{library/zipfile zipfile ZipInfo file_size}@anchor{2ea1}
@deffn {の属性} ZipInfo.file_size

圧縮前のファイルのサイズ。
@end deffn

@node コマンドライン・インターフェース<4>,Decompression pitfalls,ZipInfo objects,zipfile --- ZIP アーカイブの処理
@anchor{library/zipfile command-line-interface}@anchor{2ec8}@anchor{library/zipfile zipfile-commandline}@anchor{2ec9}
@subsubsection コマンドライン・インターフェース


The @code{zipfile} module provides a simple command-line interface to interact
with ZIP archives.

ZIP アーカイブを新規に作成したい場合、@ref{2eca,,-c} オプションの後にまとめたいファイルを列挙してください:

@example
$ python -m zipfile -c monty.zip spam.txt eggs.txt
@end example

ディレクトリを渡すこともできます:

@example
$ python -m zipfile -c monty.zip life-of-brian_1979/
@end example

ZIP アーカイブを特定のディレクトリに展開したい場合、@ref{2ecb,,-e} オプションを使用してください:

@example
$ python -m zipfile -e monty.zip target-dir/
@end example

ZIP アーカイブ内のファイル一覧を表示するには @ref{2ecc,,-l} を使用してください:

@example
$ python -m zipfile -l monty.zip
@end example

@menu
* コマンドラインオプション: コマンドラインオプション<2>. 

@end menu

@node コマンドラインオプション<2>,,,コマンドライン・インターフェース<4>
@anchor{library/zipfile command-line-options}@anchor{2ecd}
@subsubsection コマンドラインオプション


@geindex zipfile コマンドラインオプション; -l
@geindex zipfile コマンドラインオプション; --list
@anchor{library/zipfile cmdoption-zipfile-l}@anchor{2ecc}
@deffn {Option} @w{-}l <zipfile>
@anchor{library/zipfile cmdoption-zipfile-list}@anchor{2ece}
@deffnx {Option} @w{-}@w{-}list <zipfile>

zipfile 内のファイル一覧を表示します。
@end deffn

@geindex zipfile コマンドラインオプション; -c
@geindex zipfile コマンドラインオプション; --create
@anchor{library/zipfile cmdoption-zipfile-c}@anchor{2eca}
@deffn {Option} @w{-}c <zipfile> <source1> ... <sourceN>
@anchor{library/zipfile cmdoption-zipfile-create}@anchor{2ecf}
@deffnx {Option} @w{-}@w{-}create <zipfile> <source1> ... <sourceN>

ソースファイルから zipfile を作成します。
@end deffn

@geindex zipfile コマンドラインオプション; -e
@geindex zipfile コマンドラインオプション; --extract
@anchor{library/zipfile cmdoption-zipfile-e}@anchor{2ecb}
@deffn {Option} @w{-}e <zipfile> <output_dir>
@anchor{library/zipfile cmdoption-zipfile-extract}@anchor{2ed0}
@deffnx {Option} @w{-}@w{-}extract <zipfile> <output_dir>

zipfile を対象となるディレクトリに展開します。
@end deffn

@geindex zipfile コマンドラインオプション; -t
@geindex zipfile コマンドラインオプション; --test
@anchor{library/zipfile cmdoption-zipfile-t}@anchor{2ed1}
@deffn {Option} @w{-}t <zipfile>
@anchor{library/zipfile cmdoption-zipfile-test}@anchor{2ed2}
@deffnx {Option} @w{-}@w{-}test <zipfile>

zipfile が有効かどうか調べます。
@end deffn

@geindex zipfile コマンドラインオプション; --metadata-encoding
@anchor{library/zipfile cmdoption-zipfile-metadata-encoding}@anchor{2ed3}
@deffn {Option} @w{-}@w{-}metadata@w{-}encoding <encoding>

Specify encoding of member names for @ref{2ecc,,-l}, @ref{2ecb,,-e} and
@ref{2ed1,,-t}.


Added in version 3.11.

@end deffn

@node Decompression pitfalls,,コマンドライン・インターフェース<4>,zipfile --- ZIP アーカイブの処理
@anchor{library/zipfile decompression-pitfalls}@anchor{2ed4}
@subsubsection Decompression pitfalls


The extraction in zipfile module might fail due to some pitfalls listed below.

@menu
* From file itself:: 
* File system limitations:: 
* Resources limitations:: 
* Interruption:: 
* Default behaviors of extraction:: 

@end menu

@node From file itself,File system limitations,,Decompression pitfalls
@anchor{library/zipfile from-file-itself}@anchor{2ed5}
@subsubsection From file itself


Decompression may fail due to incorrect password / CRC checksum / ZIP format or
unsupported compression method / decryption.

@node File system limitations,Resources limitations,From file itself,Decompression pitfalls
@anchor{library/zipfile file-system-limitations}@anchor{2ed6}
@subsubsection File system limitations


Exceeding limitations on different file systems can cause decompression failed.
Such as allowable characters in the directory entries, length of the file name,
length of the pathname, size of a single file, and number of files, etc.

@node Resources limitations,Interruption,File system limitations,Decompression pitfalls
@anchor{library/zipfile resources-limitations}@anchor{2ed7}@anchor{library/zipfile zipfile-resources-limitations}@anchor{2ed8}
@subsubsection Resources limitations


The lack of memory or disk volume would lead to decompression
failed. For example, decompression bombs (aka ZIP bomb@footnote{https://en.wikipedia.org/wiki/Zip_bomb})
apply to zipfile library that can cause disk volume exhaustion.

@node Interruption,Default behaviors of extraction,Resources limitations,Decompression pitfalls
@anchor{library/zipfile interruption}@anchor{2ed9}
@subsubsection Interruption


Interruption during the decompression, such as pressing control-C or killing the
decompression process may result in incomplete decompression of the archive.

@node Default behaviors of extraction,,Interruption,Decompression pitfalls
@anchor{library/zipfile default-behaviors-of-extraction}@anchor{2eda}
@subsubsection Default behaviors of extraction


Not knowing the default extraction behaviors
can cause unexpected decompression results.
For example, when extracting the same archive twice,
it overwrites files without asking.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tarfile --- tar アーカイブファイルの読み書き,,zipfile --- ZIP アーカイブの処理,データ圧縮とアーカイブ
@anchor{library/tarfile doc}@anchor{2edb}@anchor{library/tarfile module-tarfile}@anchor{e4}@anchor{library/tarfile tarfile-read-and-write-tar-archive-files}@anchor{2edc}@anchor{library/tarfile translation-repo}@anchor{2edd}
@subsection @code{tarfile} --- tar アーカイブファイルの読み書き


@geindex module; tarfile

`ソースコード:' Lib/tarfile.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tarfile.py}


__________________________________________________________________


The @code{tarfile} module makes it possible to read and write tar
archives, including those using gzip, bz2 and lzma compression.
Use the @ref{137,,zipfile} module to read or write @code{.zip} files, or the
higher-level functions in @ref{1431,,shutil}.

いくつかの事実と形態:


@itemize *

@item 
モジュールが利用可能な場合、@ref{6b,,gzip}、@ref{14,,bz2}、@ref{23,,compression.zstd} ならびに @ref{8e,,lzma} で圧縮されたアーカイブを読み書きします。

@c The following paragraph should be similar to ../includes/optional-module.rst

If any of these @ref{215a,,optional modules} are missing from
your copy of CPython, look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@item 
POSIX.1-1988 (ustar) フォーマットの読み書きをサポートしています。

@item 
`longname' および `longlink' 拡張を含む GNU tar フォーマットの読み書きをサポートしています。スパースファイルの復元を含む `sparse' 拡張は読み込みのみサポートしています。

@item 
POSIX.1-2001 (pax) フォーマットの読み書きをサポートしています。

@item 
ディレクトリ、一般ファイル、ハードリンク、シンボリックリンク、fifo、キャラクターデバイスおよびブロックデバイスを処理します。また、タイムスタンプ、アクセス許可や所有者のようなファイル情報の取得および保存が可能です。
@end itemize


バージョン 3.3 で変更: @ref{8e,,lzma} 圧縮をサポートしました。



バージョン 3.12 で変更: Archives are extracted using a @ref{697,,filter},
which makes it possible to either limit surprising/dangerous features,
or to acknowledge that they are expected and the archive is fully trusted.



バージョン 3.14 で変更: Set the default extraction filter to @ref{29a,,data},
which disallows some dangerous features such as links to absolute paths
or paths outside of the destination. Previously, the filter strategy
was equivalent to @ref{2ede,,fully_trusted}.



バージョン 3.14 で変更: Added support for Zstandard compression using @ref{23,,compression.zstd}.


@geindex open() (tarfile モジュール)
@anchor{library/tarfile tarfile open}@anchor{1077}
@deffn {の関数} tarfile.open (name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

パス名 `name' の @ref{1429,,TarFile} オブジェクトを返します。@ref{1429,,TarFile} オブジェクトと、利用できるキーワード引数に関する詳細な情報については、@ref{2edf,,TarFile オブジェクト} 節を参照してください。

`mode' は @code{'filemode[:compression]'} の形式をとる文字列でなければなりません。デフォルトの値は @code{'r'} です。以下に `mode' のとりうる組み合わせすべてを示します:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

mode

@tab

action

@item

@code{'r'} または @code{'r:*'}

@tab

圧縮方法に関して透過的に、読み込み用にオープンします (推奨)。

@item

@code{'r:'}

@tab

非圧縮で読み込み用に排他的にオープンします。

@item

@code{'r:gz'}

@tab

gzip 圧縮で読み込み用にオープンします。

@item

@code{'r:bz2'}

@tab

bzip2 圧縮で読み込み用にオープンします。

@item

@code{'r:xz'}

@tab

lzma 圧縮で読み込み用にオープンします。

@item

@code{'r:zst'}

@tab

Zstandard 圧縮で読み込み用にオープンします。

@item

@code{'x'} or
@code{'x:'}

@tab

圧縮せずに tarfile を排他的に作成します。tarfile が既存の場合 @ref{1221,,FileExistsError} 例外を送出します。

@item

@code{'x:gz'}

@tab

gzip 圧縮で tarfile を作成します。tarfile が既存の場合 @ref{1221,,FileExistsError} 例外を送出します。

@item

@code{'x:bz2'}

@tab

bzip2 圧縮で tarfile を作成します。tarfile が既存の場合 @ref{1221,,FileExistsError} 例外を送出します。

@item

@code{'x:xz'}

@tab

lzma 圧縮で tarfile を作成します。tarfile が既存の場合 @ref{1221,,FileExistsError} 例外を送出します。

@item

@code{'x:zst'}

@tab

Zstandard 圧縮で tarfile を作成します。tarfile が既存の場合 @ref{1221,,FileExistsError} 例外を送出します。

@item

@code{'a'} または @code{'a:'}

@tab

非圧縮で追記用にオープンします。ファイルが存在しない場合は新たに作成されます。

@item

@code{'w'} または @code{'w:'}

@tab

非圧縮で書き込み用にオープンします。

@item

@code{'w:gz'}

@tab

gzip 圧縮で書き込み用にオープンします。

@item

@code{'w:bz2'}

@tab

bzip2 圧縮で書き込み用にオープンします。

@item

@code{'w:xz'}

@tab

lzma 圧縮で書き込み用にオープンします。

@item

@code{'w:zst'}

@tab

Zstandard 圧縮で書き込み用にオープンします。

@end multitable


@code{'a:gz'}、@code{'a:bz2'}、@code{'a:xz'} は利用できないことに注意して下さい。もし `mode' が、ある (圧縮した) ファイルを読み込み用にオープンするのに適していないなら、@ref{1c4f,,ReadError} が送出されます。これを防ぐには `mode' @code{'r'} を使って下さい。もし圧縮方式がサポートされていなければ、@ref{2ee0,,CompressionError} が送出されます。

もし `fileobj' が指定されていれば、それは `name' でバイナリモードでオープンされた @ref{13db,,ファイルオブジェクト} の代替として使うことができます。そのファイルオブジェクトの位置が 0 であることを前提に動作します。

@code{'w:gz'}、@code{'x:gz'}、@code{'w|gz'}、@code{'w:bz2'}、@code{'x:bz2'}、@code{'w|bz2'} モードの場合、@ref{1077,,tarfile.open()} はファイルの圧縮レベルを指定するキーワード引数 `compresslevel' (デフォルトは @code{9}) を受け付けます。

@code{'w:xz'}、@code{'x:xz'} および @code{'w|xz'} モードの場合、@ref{1077,,tarfile.open()} はファイルの圧縮レベルを指定するキーワード引数 `preset' を受け付けます。

For modes @code{'w:zst'}, @code{'x:zst'} and @code{'w|zst'}, @ref{1077,,tarfile.open()}
accepts the keyword argument `level' to specify the compression level of
the file. The keyword argument `options' may also be passed, providing
advanced Zstandard compression parameters described by
@ref{2de5,,CompressionParameter}. The keyword argument
`zstd_dict' can be passed to provide a @ref{2de4,,ZstdDict},
a Zstandard dictionary used to improve compression of smaller amounts of
data.

For special purposes, there is a second format for `mode':
@code{'filemode|[compression]'}.  @ref{1077,,tarfile.open()} will return a @ref{1429,,TarFile}
object that processes its data as a stream of blocks.  No random seeking will
be done on the file. If given, `fileobj' may be any object that has a
@ref{101d,,read()} or @ref{15c5,,write()} method
(depending on the `mode') that works with bytes.
`bufsize' specifies the blocksize and defaults to @code{20 * 512} bytes.
Use this variant in combination with e.g. @code{sys.stdin.buffer}, a socket
@ref{13db,,file object} or a tape device.
However, such a @ref{1429,,TarFile} object is limited in that it does
not allow random access, see @ref{2ee1,,使用例}.  The currently
possible modes:


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

モード

@tab

動作

@item

@code{'r|*'}

@tab

tar ブロックの `stream' を圧縮方法に関して透過的に読み込み用にオープンします。

@item

@code{'r|'}

@tab

非圧縮 tar ブロックの `stream' を読み込み用にオープンします。

@item

@code{'r|gz'}

@tab

gzip 圧縮の `stream' を読み込み用にオープンします。

@item

@code{'r|bz2'}

@tab

bzip2 圧縮の `stream' を読み込み用にオープンします。

@item

@code{'r|xz'}

@tab

lzma 圧縮の `stream' を読み込み用にオープンします。

@item

@code{'r|zst'}

@tab

Zstandard 圧縮の `stream' を読み込み用にオープンします。

@item

@code{'w|'}

@tab

非圧縮の `stream' を書き込み用にオープンします。

@item

@code{'w|gz'}

@tab

gzip 圧縮の `stream' を書き込み用にオープンします。

@item

@code{'w|bz2'}

@tab

bzip2 圧縮の `stream' を書き込み用にオープンします。

@item

@code{'w|xz'}

@tab

lzma 圧縮の `stream' を書き込み用にオープンします。

@item

@code{'w|zst'}

@tab

Zstandard 圧縮の `stream' を書き込み用にオープンします。

@end multitable



バージョン 3.5 で変更: @code{'x'} (排他的作成) モードが追加されました。



バージョン 3.6 で変更: `name' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.12 で変更: The `compresslevel' keyword argument also works for streams.



バージョン 3.14 で変更: The `preset' keyword argument also works for streams.

@end deffn


@deffn {クラス} tarfile.TarFile

tar アーカイブを読み書きするためのクラスです。このクラスを直接使わないこと: 代わりに @ref{1077,,tarfile.open()} を使ってください。@ref{2edf,,TarFile オブジェクト} を参照してください。
@end deffn

@geindex is_tarfile() (tarfile モジュール)
@anchor{library/tarfile tarfile is_tarfile}@anchor{1bdb}
@deffn {の関数} tarfile.is_tarfile (name)

Return @ref{e07,,True} if `name' is a tar archive file, that the @code{tarfile}
module can read. `name' may be a @ref{169,,str}, file, or file-like object.


バージョン 3.9 で変更: ファイルおよびファイルライクオブジェクトをサポートしました。

@end deffn

The @code{tarfile} module defines the following exceptions:

@geindex TarError
@anchor{library/tarfile tarfile TarError}@anchor{2ee2}
@deffn {例外} tarfile.TarError

Base class for all @code{tarfile} exceptions.
@end deffn

@geindex ReadError
@anchor{library/tarfile tarfile ReadError}@anchor{1c4f}
@deffn {例外} tarfile.ReadError

Is raised when a tar archive is opened, that either cannot be handled by the
@code{tarfile} module or is somehow invalid.
@end deffn

@geindex CompressionError
@anchor{library/tarfile tarfile CompressionError}@anchor{2ee0}
@deffn {例外} tarfile.CompressionError

圧縮方法がサポートされていないか、あるいはデータを正しくデコードできない時に送出されます。
@end deffn

@geindex StreamError
@anchor{library/tarfile tarfile StreamError}@anchor{2ee3}
@deffn {例外} tarfile.StreamError

ストリームのような @ref{1429,,TarFile} オブジェクトで典型的な制限のために送出されます。
@end deffn

@geindex ExtractError
@anchor{library/tarfile tarfile ExtractError}@anchor{2ee4}
@deffn {例外} tarfile.ExtractError

@ref{29c,,TarFile.extract()} を使った時に `致命的でない' エラーに対して送出されます。ただし @ref{29e,,TarFile.errorlevel}@code{== 2} の場合に限ります。
@end deffn

@geindex HeaderError
@anchor{library/tarfile tarfile HeaderError}@anchor{2ee5}
@deffn {例外} tarfile.HeaderError

@ref{2ee6,,TarInfo.frombuf()} メソッドが取得したバッファーが不正だったときに送出されます。
@end deffn

@geindex FilterError
@anchor{library/tarfile tarfile FilterError}@anchor{2ee7}
@deffn {例外} tarfile.FilterError

Base class for members @ref{2ee8,,refused} by
filters.

@geindex tarinfo (tarfile.FilterError の属性)
@anchor{library/tarfile tarfile FilterError tarinfo}@anchor{2ee9}
@deffn {の属性} tarinfo

Information about the member that the filter refused to extract,
as @ref{2eea,,TarInfo}.
@end deffn
@end deffn

@geindex AbsolutePathError
@anchor{library/tarfile tarfile AbsolutePathError}@anchor{2eeb}
@deffn {例外} tarfile.AbsolutePathError

Raised to refuse extracting a member with an absolute path.
@end deffn

@geindex OutsideDestinationError
@anchor{library/tarfile tarfile OutsideDestinationError}@anchor{2eec}
@deffn {例外} tarfile.OutsideDestinationError

Raised to refuse extracting a member outside the destination directory.
@end deffn

@geindex SpecialFileError
@anchor{library/tarfile tarfile SpecialFileError}@anchor{2eed}
@deffn {例外} tarfile.SpecialFileError

Raised to refuse extracting a special file (e.g. a device or pipe).
@end deffn

@geindex AbsoluteLinkError
@anchor{library/tarfile tarfile AbsoluteLinkError}@anchor{2eee}
@deffn {例外} tarfile.AbsoluteLinkError

Raised to refuse extracting a symbolic link with an absolute path.
@end deffn

@geindex LinkOutsideDestinationError
@anchor{library/tarfile tarfile LinkOutsideDestinationError}@anchor{2eef}
@deffn {例外} tarfile.LinkOutsideDestinationError

Raised to refuse extracting a symbolic link pointing outside the destination
directory.
@end deffn

@geindex LinkFallbackError
@anchor{library/tarfile tarfile LinkFallbackError}@anchor{29d}
@deffn {例外} tarfile.LinkFallbackError

Raised to refuse emulating a link (hard or symbolic) by extracting another
archive member, when that member would be rejected by the filter location.
The exception that was raised to reject the replacement member is available
as @code{BaseException.__context__}.


Added in version 3.14.

@end deffn

モジュールレベルで以下の定数が利用できます。

@geindex ENCODING (tarfile モジュール)
@anchor{library/tarfile tarfile ENCODING}@anchor{2ef0}
@deffn {データ} tarfile.ENCODING

既定の文字エンコーディング。Windows では @code{'utf-8'} 、それ以外では @ref{e53,,sys.getfilesystemencoding()} の返り値です。
@end deffn

@geindex REGTYPE (tarfile モジュール)
@geindex AREGTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile REGTYPE}@anchor{2ef1}
@deffn {データ} tarfile.REGTYPE
@anchor{library/tarfile tarfile AREGTYPE}@anchor{2ef2}
@deffnx {データ} tarfile.AREGTYPE

A regular file @ref{2ef3,,type}.
@end deffn

@geindex LNKTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile LNKTYPE}@anchor{2ef4}
@deffn {データ} tarfile.LNKTYPE

A link (inside tarfile) @ref{2ef3,,type}.
@end deffn

@geindex SYMTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile SYMTYPE}@anchor{2ef5}
@deffn {データ} tarfile.SYMTYPE

A symbolic link @ref{2ef3,,type}.
@end deffn

@geindex CHRTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile CHRTYPE}@anchor{2ef6}
@deffn {データ} tarfile.CHRTYPE

A character special device @ref{2ef3,,type}.
@end deffn

@geindex BLKTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile BLKTYPE}@anchor{2ef7}
@deffn {データ} tarfile.BLKTYPE

A block special device @ref{2ef3,,type}.
@end deffn

@geindex DIRTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile DIRTYPE}@anchor{2ef8}
@deffn {データ} tarfile.DIRTYPE

A directory @ref{2ef3,,type}.
@end deffn

@geindex FIFOTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile FIFOTYPE}@anchor{2ef9}
@deffn {データ} tarfile.FIFOTYPE

A FIFO special device @ref{2ef3,,type}.
@end deffn

@geindex CONTTYPE (tarfile モジュール)
@anchor{library/tarfile tarfile CONTTYPE}@anchor{2efa}
@deffn {データ} tarfile.CONTTYPE

A contiguous file @ref{2ef3,,type}.
@end deffn

@geindex GNUTYPE_LONGNAME (tarfile モジュール)
@anchor{library/tarfile tarfile GNUTYPE_LONGNAME}@anchor{2efb}
@deffn {データ} tarfile.GNUTYPE_LONGNAME

A GNU tar longname @ref{2ef3,,type}.
@end deffn

@geindex GNUTYPE_LONGLINK (tarfile モジュール)
@anchor{library/tarfile tarfile GNUTYPE_LONGLINK}@anchor{2efc}
@deffn {データ} tarfile.GNUTYPE_LONGLINK

A GNU tar longlink @ref{2ef3,,type}.
@end deffn

@geindex GNUTYPE_SPARSE (tarfile モジュール)
@anchor{library/tarfile tarfile GNUTYPE_SPARSE}@anchor{2efd}
@deffn {データ} tarfile.GNUTYPE_SPARSE

A GNU tar sparse file @ref{2ef3,,type}.
@end deffn

Each of the following constants defines a tar archive format that the
@code{tarfile} module is able to create. See section @ref{2efe,,サポートしている tar フォーマット} for
details.

@geindex USTAR_FORMAT (tarfile モジュール)
@anchor{library/tarfile tarfile USTAR_FORMAT}@anchor{2eff}
@deffn {データ} tarfile.USTAR_FORMAT

POSIX.1-1988 (ustar) フォーマット。
@end deffn

@geindex GNU_FORMAT (tarfile モジュール)
@anchor{library/tarfile tarfile GNU_FORMAT}@anchor{2f00}
@deffn {データ} tarfile.GNU_FORMAT

GNU tar フォーマット。
@end deffn

@geindex PAX_FORMAT (tarfile モジュール)
@anchor{library/tarfile tarfile PAX_FORMAT}@anchor{2f01}
@deffn {データ} tarfile.PAX_FORMAT

POSIX.1-2001 (pax) フォーマット。
@end deffn

@geindex DEFAULT_FORMAT (tarfile モジュール)
@anchor{library/tarfile tarfile DEFAULT_FORMAT}@anchor{2f02}
@deffn {データ} tarfile.DEFAULT_FORMAT

アーカイブを作成する際のデフォルトのフォーマット。現在は @ref{2f01,,PAX_FORMAT} です。


バージョン 3.8 で変更: 新しいアーカイブのデフォルトフォーマットが @ref{2f00,,GNU_FORMAT} から @ref{2f01,,PAX_FORMAT} に変更されました。

@end deffn


@subsubheading 参考



@table @asis

@item @ref{137,,zipfile} モジュール

@ref{137,,zipfile} 標準モジュールのドキュメント。

@item @ref{1431,,アーカイブ化操作}

@ref{ca,,shutil} が提供するより高水準のアーカイブ機能についてのドキュメント。

@item GNU tar manual@comma{} Basic Tar Format@footnote{https://www.gnu.org/software/tar/manual/html_node/Standard.html}

GNU tar 拡張機能を含む、tar アーカイブファイルのためのドキュメント。
@end table


@menu
* TarFile オブジェクト:: 
* TarInfo オブジェクト:: 
* Extraction filters:: 
* コマンドラインインターフェイス:: 
* 使用例: 使用例<16>. 
* サポートしている tar フォーマット:: 
* Unicode に関する問題:: 

@end menu

@node TarFile オブジェクト,TarInfo オブジェクト,,tarfile --- tar アーカイブファイルの読み書き
@anchor{library/tarfile id1}@anchor{2f03}@anchor{library/tarfile tarfile-objects}@anchor{2edf}
@subsubsection TarFile オブジェクト


@ref{1429,,TarFile} オブジェクトは、tar アーカイブへのインターフェースを提供します。tar アーカイブは一連のブロックです。アーカイブメンバー (保存されたファイル) は、ヘッダーブロックとそれに続くデータブロックで構成されています。一つの tar アーカイブにファイルを何回も保存することができます。各アーカイブメンバーは、@ref{142a,,TarInfo} オブジェクトで確認できます。詳細については @ref{2eea,,TarInfo オブジェクト} を参照してください。

@ref{1429,,TarFile} オブジェクトは @ref{186,,with} 文のコンテキストマネージャーとして利用できます。with ブロックが終了したときにオブジェクトはクローズされます。例外が発生した時、内部で利用されているファイルオブジェクトのみがクローズされ、書き込み用にオープンされたアーカイブのファイナライズは行われないことに注意してください。@ref{2ee1,,使用例} 節のユースケースを参照してください。


Added in version 3.2: コンテキスト管理のプロトコルがサポートされました。


@geindex TarFile (tarfile のクラス)
@anchor{library/tarfile tarfile TarFile}@anchor{1429}
@deffn {クラス} tarfile.TarFile (name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=1, stream=False)

以下のすべての引数はオプションで、インスタンス属性としてもアクセスできます。

`name' is the pathname of the archive. `name' may be a @ref{5a1,,path-like object}.
It can be omitted if `fileobj' is given.
In this case, the file object's @code{name} attribute is used if it exists.

`mode' は、既存のアーカイブから読み込むための @code{'r'}、既存のアーカイブに追記するための @code{'a'}、既存のファイルがあれば上書きして新しいファイルを作成する @code{'w'} 、あるいは存在しない場合にのみ新しいファイルを作成する @code{'x'} のいずれかです。

`fileobj' が与えられていれば、それを使ってデータを読み書きします。もしそれが決定できれば、`mode' は `fileobj' のモードで上書きされます。`fileobj' は位置 0 から利用されます。

@cartouche
@quotation 注釈 
@ref{1429,,TarFile} をクローズした時、`fileobj' はクローズされません。
@end quotation
@end cartouche

`format' はアーカイブの書き込みフォーマットを制御します。モジュールレベルで定義されている、@ref{2eff,,USTAR_FORMAT}、@ref{2f00,,GNU_FORMAT}、あるいは @ref{2f01,,PAX_FORMAT} のいずれかである必要があります。
読み出しのときは、1 つのアーカイブに異なるフォーマットが混在していたとしても、フォーマットは自動的に検知されます。

`tarinfo' 引数を利用して、デフォルトの @ref{142a,,TarInfo} クラスを別のクラスで置き換えることができます。

`dereference' が @ref{d2b,,False} だった場合、シンボリックリンクやハードリンクがアーカイブに追加されます。@ref{e07,,True} だった場合、リンクのターゲットとなるファイルの内容がアーカイブに追加されます。シンボリックリンクをサポートしていないシステムでは効果がありません。

`ignore_zeros' が @ref{d2b,,False} だった場合、空ブロックをアーカイブの終端として扱います。@ref{e07,,True} だった場合、空の (無効な) ブロックをスキップして、可能な限り多くのメンバーを取得しようとします。このオプションは、連結されたり、壊れたアーカイブファイルを扱うときにのみ、意味があります。

`debug' は @code{0} (デバッグメッセージ無し) から @code{3} (全デバッグメッセージ) まで設定できます。このメッセージは @code{sys.stderr} に書き込まれます。

`errorlevel' controls how extraction errors are handled,
see @ref{29e,,the corresponding attribute}.

引数 `encoding' および `errors' にはアーカイブの読み書きやエラー文字列の変換に使用する文字エンコーディングを指定します。ほとんどのユーザーはデフォルト設定のままで動作します。詳細に関しては @ref{2f04,,Unicode に関する問題} 節を参照してください。

引数 `pax_headers' は、オプションの文字列辞書で、`format' が @ref{2f01,,PAX_FORMAT} だった場合に pax グローバルヘッダーに追加されます。

If `stream' is set to @ref{e07,,True} then while reading the archive info about files
in the archive are not cached, saving memory.


バージョン 3.2 で変更: 引数 `errors' のデフォルトが @code{'surrogateescape'} になりました。



バージョン 3.5 で変更: @code{'x'} (排他的作成) モードが追加されました。



バージョン 3.6 で変更: `name' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.13 で変更: Add the `stream' parameter.

@end deffn

@geindex open() (tarfile.TarFile のクラスメソッド)
@anchor{library/tarfile tarfile TarFile open}@anchor{1bdc}
@deffn {メソッド} classmethod TarFile.open (...)

代替コンストラクターです。モジュールレベルでの @ref{1077,,tarfile.open()} 関数は、実際はこのクラスメソッドへのショートカットです。
@end deffn

@geindex getmember() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile getmember}@anchor{1bf0}
@deffn {メソッド} TarFile.getmember (name)

メンバー `name' に対する @ref{142a,,TarInfo} オブジェクトを返します。`name' がアーカイブに見つからなければ、@ref{5e7,,KeyError} が送出されます。

@cartouche
@quotation 注釈 
アーカイブ内にメンバーが複数ある場合は、最後に出現するものが最新のバージョンとみなされます。
@end quotation
@end cartouche
@end deffn

@geindex getmembers() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile getmembers}@anchor{1079}
@deffn {メソッド} TarFile.getmembers ()

@ref{142a,,TarInfo} アーカイブのメンバーをオブジェクトのリストとして返します。このリストはアーカイブ内のメンバーと同じ順番です。
@end deffn

@geindex getnames() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile getnames}@anchor{2f05}
@deffn {メソッド} TarFile.getnames ()

メンバーをその名前のリストを返します。これは @ref{1079,,getmembers()} で返されるリストと同じ順番です。
@end deffn

@geindex list() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile list}@anchor{1078}
@deffn {メソッド} TarFile.list (verbose=True, *, members=None)

内容の一覧を @code{sys.stdout} に出力します。`verbose' が @ref{d2b,,False} の場合、メンバー名のみ表示します。@ref{e07,,True} の場合、 @code{ls -l} に似た出力を生成します。オプションの `members' を与える場合、 @ref{1079,,getmembers()} が返すリストのサブセットである必要があります。


バージョン 3.5 で変更: `members' 引数が追加されました。.

@end deffn

@geindex next() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile next}@anchor{2f06}
@deffn {メソッド} TarFile.next ()

@ref{1429,,TarFile} が読み込み用にオープンされている時、アーカイブの次のメンバーを @ref{142a,,TarInfo} オブジェクトとして返します。もしそれ以上利用可能なものがなければ、@ref{885,,None} を返します。
@end deffn

@geindex extractall() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile extractall}@anchor{29b}
@deffn {メソッド} TarFile.extractall (path='.', members=None, *, numeric_owner=False, filter=None)

すべてのメンバーをアーカイブから現在の作業ディレクトリまたは `path' に抽出します。オプションの `members' が与えられるときには、@ref{1079,,getmembers()} で返されるリストの一部でなければなりません。所有者、変更時刻、アクセス権限のようなディレクトリ情報はすべてのメンバーが抽出された後にセットされます。これは二つの問題を回避するためです。一つはディレクトリの変更時刻はその中にファイルが作成されるたびにリセットされるということ、もう一つはディレクトリに書き込み許可がなければその中のファイル抽出は失敗してしまうということです。

`numeric_owner' が @ref{e07,,True} の場合、tarfile の uid と gid 数値が抽出されたファイルのオーナー/グループを設定するために使用されます。False の場合、tarfile の名前付きの値が使用されます。

The `filter' argument specifies how @code{members} are modified or rejected
before extraction.
See @ref{697,,Extraction filters} for details.
It is recommended to set this explicitly only if specific `tar' features
are required, or as @code{filter='data'} to support Python versions with a less
secure default (3.13 and lower).

@cartouche
@quotation 警告 
Never extract archives from untrusted sources without prior inspection.

Since Python 3.14, the default (@ref{29a,,data}) will prevent
the most dangerous security issues.
However, it will not prevent `all' unintended or insecure behavior.
Read the @ref{697,,Extraction filters} section for details.
@end quotation
@end cartouche


バージョン 3.5 で変更: `numeric_owner' 引数が追加されました。



バージョン 3.6 で変更: `path' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.12 で変更: `filter' パラメータが追加されました。



バージョン 3.14 で変更: The `filter' parameter now defaults to @code{'data'}.

@end deffn

@geindex extract() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile extract}@anchor{29c}
@deffn {メソッド} TarFile.extract (member, path='@w{'}, set_attrs=True, *, numeric_owner=False, filter=None)

アーカイブからメンバーの完全な名前を使って、現在のディレクトリに展開します。ファイル情報はできる限り正確に展開されます。 `member' はファイル名もしくは @ref{142a,,TarInfo} オブジェクトです。 `path' を使って別のディレクトリを指定することもできます。 `path' は　@ref{5a1,,path-like object} でも構いません。`set_attrs' が false でない限り、ファイルの属性 (所有者、最終更新時刻、モード) は設定されます。

The `numeric_owner' and `filter' arguments are the same as
for @ref{29b,,extractall()}.

@cartouche
@quotation 注釈 
@ref{29c,,extract()} メソッドはいくつかの展開に関する問題を扱いません。ほとんどの場合、@ref{29b,,extractall()} メソッドの利用を考慮するべきです。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
Never extract archives from untrusted sources without prior inspection.
See the warning for @ref{29b,,extractall()} for details.
@end quotation
@end cartouche


バージョン 3.2 で変更: パラメーターに `set_attrs' を追加しました。



バージョン 3.5 で変更: `numeric_owner' 引数が追加されました。



バージョン 3.6 で変更: `path' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.12 で変更: `filter' パラメータが追加されました。

@end deffn

@geindex extractfile() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile extractfile}@anchor{2f07}
@deffn {メソッド} TarFile.extractfile (member)

アーカイブからメンバーをファイルオブジェクトとして抽出します。
`member' はファイル名でも @ref{142a,,TarInfo} オブジェクトでも構いません。`member' が一般ファイルまたはリンクの場合、@ref{1427,,io.BufferedReader} オブジェクトが返されます。
存在するそれ以外のメンバーでは、 @ref{885,,None} が返されます。
それ以外の場合、@ref{885,,None} が返されます。
アーカイブに `member' が存在しない場合は @ref{5e7,,KeyError} が送出されます。


バージョン 3.3 で変更: 戻り値が @ref{1427,,io.BufferedReader} オブジェクトになりました。



バージョン 3.13 で変更: The returned @ref{1427,,io.BufferedReader} object has the @code{mode}
attribute which is always equal to @code{'rb'}.

@end deffn

@geindex errorlevel (tarfile.TarFile の属性)
@anchor{library/tarfile tarfile TarFile errorlevel}@anchor{29e}
@deffn {の属性} TarFile.errorlevel: @ref{19b,,int}

If `errorlevel' is @code{0}, errors are ignored when using @ref{29c,,TarFile.extract()}
and @ref{29b,,TarFile.extractall()}.
Nevertheless, they appear as error messages in the debug output when
`debug' is greater than 0.
If @code{1} (the default), all `fatal' errors are raised as @ref{2c0,,OSError} or
@ref{2ee7,,FilterError} exceptions. If @code{2}, all `non-fatal' errors are raised
as @ref{2ee2,,TarError} exceptions as well.

Some exceptions, e.g. ones caused by wrong argument types or data
corruption, are always raised.

Custom @ref{697,,extraction filters}
should raise @ref{2ee7,,FilterError} for `fatal' errors
and @ref{2ee4,,ExtractError} for `non-fatal' ones.

Note that when an exception is raised, the archive may be partially
extracted. It is the user’s responsibility to clean up.
@end deffn

@geindex extraction_filter (tarfile.TarFile の属性)
@anchor{library/tarfile tarfile TarFile extraction_filter}@anchor{2f08}
@deffn {の属性} TarFile.extraction_filter


Added in version 3.12.


The @ref{697,,extraction filter} used
as a default for the `filter' argument of @ref{29c,,extract()}
and @ref{29b,,extractall()}.

The attribute may be @code{None} or a callable.
String names are not allowed for this attribute, unlike the `filter'
argument to @ref{29c,,extract()}.

If @code{extraction_filter} is @code{None} (the default), extraction methods
will use the @ref{29a,,data} filter by default.

The attribute may be set on instances or overridden in subclasses.
It also is possible to set it on the @code{TarFile} class itself to set a
global default, although, since it affects all uses of `tarfile',
it is best practice to only do so in top-level applications or
@ref{cc,,site configuration}.
To set a global default this way, a filter function needs to be wrapped in
@ref{453,,staticmethod()} to prevent injection of a @code{self} argument.


バージョン 3.14 で変更: The default filter is set to @ref{29a,,data},
which disallows some dangerous features such as links to absolute paths
or paths outside of the destination.
Previously, the default was equivalent to
@ref{2ede,,fully_trusted}.

@end deffn

@geindex add() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile add}@anchor{dee}
@deffn {メソッド} TarFile.add (name, arcname=None, recursive=True, *, filter=None)

ファイル `name' をアーカイブに追加します。
`name' は、任意のファイルタイプ (ディレクトリ、fifo、シンボリックリンク等)です。
`arcname' が与えられている場合は、それはアーカイブ内のファイルの代替名を指定します。
デフォルトではディレクトリは再帰的に追加されます。
これは、 `recursive' を @ref{d2b,,False} に設定すると避けられます。
再帰処理はソートされた順序でエントリーを追加します。
`filter' が与えられた場合、それは @ref{142a,,TarInfo} オブジェクトを引数として受け取り、操作した @ref{142a,,TarInfo} オブジェクトを返す関数でなければなりません。
代わりに @ref{885,,None} を返した場合、 @ref{142a,,TarInfo} オブジェクトはアーカイブから除外されます。
@ref{2ee1,,使用例} にある例を参照してください。


バージョン 3.2 で変更: `filter' パラメータが追加されました。



バージョン 3.7 で変更: 再帰処理はソートされた順序でエントリーを追加するようになりました。

@end deffn

@geindex addfile() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile addfile}@anchor{19a7}
@deffn {メソッド} TarFile.addfile (tarinfo, fileobj=None)

Add the @ref{142a,,TarInfo} object `tarinfo' to the archive. If `tarinfo' represents
a non zero-size regular file, the `fileobj' argument should be a @ref{206e,,binary file},
and @code{tarinfo.size} bytes are read from it and added to the archive.  You can
create @ref{142a,,TarInfo} objects directly, or by using @ref{2f09,,gettarinfo()}.


バージョン 3.13 で変更: `fileobj' must be given for non-zero-sized regular files.

@end deffn

@geindex gettarinfo() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile gettarinfo}@anchor{2f09}
@deffn {メソッド} TarFile.gettarinfo (name=None, arcname=None, fileobj=None)

@ref{26d,,os.stat()} の結果か、既存のファイルに相当するものから、@ref{142a,,TarInfo} オブジェクトを作成します。このファイルは、`name' で名付けられるか、ファイル記述子を持つ @ref{13db,,file object} `fileobj' として指定されます。`name' は @ref{5a1,,path-like object} でも構いません。 `arcname' が与えられた場合、アーカイブ内のファイルに対して代替名を指定します。与えられない場合、名前は `fileobj' の @ref{2def,,name} 属性 `name' 属性から取られます。名前はテキスト文字列にしてください。

@ref{142a,,TarInfo} の属性の一部は、@ref{19a7,,addfile()} を使用して追加する前に修正できます。ファイルオブジェクトが、ファイルの先頭にある通常のファイルオブジェクトでない場合、 @ref{2f0a,,size} などの属性は修正が必要かもしれません。これは、 @ref{65c,,GzipFile} などの属性に当てはまります。@ref{2f0b,,name} も修正できるかもしれず、この場合、`arcname' はダミーの文字列にすることができます。


バージョン 3.6 で変更: `name' パラメタが @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex close() (tarfile.TarFile のメソッド)
@anchor{library/tarfile tarfile TarFile close}@anchor{2f0c}
@deffn {メソッド} TarFile.close ()

@ref{1429,,TarFile} をクローズします。書き込みモードでは、完了ゼロブロックが 2 個アーカイブに追加されます。
@end deffn

@geindex pax_headers (tarfile.TarFile の属性)
@anchor{library/tarfile tarfile TarFile pax_headers}@anchor{2f0d}
@deffn {の属性} TarFile.pax_headers: @ref{183,,dict}

pax グローバルヘッダーに含まれる key-value ペアの辞書です。
@end deffn

@node TarInfo オブジェクト,Extraction filters,TarFile オブジェクト,tarfile --- tar アーカイブファイルの読み書き
@anchor{library/tarfile id2}@anchor{2f0e}@anchor{library/tarfile tarinfo-objects}@anchor{2eea}
@subsubsection TarInfo オブジェクト


@ref{142a,,TarInfo} オブジェクトは @ref{1429,,TarFile} の一つのメンバーを表します。ファイルに必要なすべての属性 (ファイルタイプ、ファイルサイズ、時刻、アクセス権限、所有者等のような) を保存する他に、そのタイプを決定するのに役に立ついくつかのメソッドを提供します。これにはファイルのデータそのものは `含まれません' 。

@ref{142a,,TarInfo} objects are returned by @ref{1429,,TarFile}'s methods
@ref{1bf0,,getmember()}, @ref{1079,,getmembers()} and
@ref{2f09,,gettarinfo()}.

Modifying the objects returned by @ref{1bf0,,getmember()} or
@ref{1079,,getmembers()} will affect all subsequent
operations on the archive.
For cases where this is unwanted, you can use @ref{29,,copy.copy()} or
call the @ref{2f0f,,replace()} method to create a modified copy in one step.

Several attributes can be set to @code{None} to indicate that a piece of metadata
is unused or unknown.
Different @ref{142a,,TarInfo} methods handle @code{None} differently:


@itemize -

@item 
The @ref{29c,,extract()} or @ref{29b,,extractall()} methods will
ignore the corresponding metadata, leaving it set to a default.

@item 
@ref{19a7,,addfile()} will fail.

@item 
@ref{1078,,list()} will print a placeholder string.
@end itemize

@geindex TarInfo (tarfile のクラス)
@anchor{library/tarfile tarfile TarInfo}@anchor{142a}
@deffn {クラス} tarfile.TarInfo (name='@w{'})

@ref{142a,,TarInfo} オブジェクトを作成します。
@end deffn

@geindex frombuf() (tarfile.TarInfo のクラスメソッド)
@anchor{library/tarfile tarfile TarInfo frombuf}@anchor{2ee6}
@deffn {メソッド} classmethod TarInfo.frombuf (buf, encoding, errors)

@ref{142a,,TarInfo} オブジェクトを文字列バッファー `buf' から作成して返します。

バッファーが不正な場合 @ref{2ee5,,HeaderError} を送出します。
@end deffn

@geindex fromtarfile() (tarfile.TarInfo のクラスメソッド)
@anchor{library/tarfile tarfile TarInfo fromtarfile}@anchor{2f10}
@deffn {メソッド} classmethod TarInfo.fromtarfile (tarfile)

@ref{1429,,TarFile} オブジェクトの `tarfile' から、次のメンバーを読み込んで、それを @ref{142a,,TarInfo} オブジェクトとして返します。
@end deffn

@geindex tobuf() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo tobuf}@anchor{2f11}
@deffn {メソッド} TarInfo.tobuf (format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape')

@ref{142a,,TarInfo} オブジェクトから文字列バッファーを作成します。引数についての情報は、@ref{1429,,TarFile} クラスのコンストラクターを参照してください。


バージョン 3.2 で変更: 引数 `errors' のデフォルトが @code{'surrogateescape'} になりました。

@end deffn

@code{TarInfo} オブジェクトには以下のデータ属性があります:

@geindex name (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo name}@anchor{2f0b}
@deffn {の属性} TarInfo.name: @ref{169,,str}

アーカイブメンバーの名前。
@end deffn

@geindex size (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo size}@anchor{2f0a}
@deffn {の属性} TarInfo.size: @ref{19b,,int}

バイト単位でのサイズ。
@end deffn

@geindex mtime (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo mtime}@anchor{2f12}
@deffn {の属性} TarInfo.mtime: @ref{19b,,int} | @ref{196,,float}

Time of last modification in seconds since the @ref{2f13,,epoch},
as in @ref{2f14,,os.stat_result.st_mtime}.


バージョン 3.12 で変更: Can be set to @code{None} for @ref{29c,,extract()} and
@ref{29b,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex mode (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo mode}@anchor{2f15}
@deffn {の属性} TarInfo.mode: @ref{19b,,int}

Permission bits, as for @ref{529,,os.chmod()}.


バージョン 3.12 で変更: Can be set to @code{None} for @ref{29c,,extract()} and
@ref{29b,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex type (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo type}@anchor{2ef3}
@deffn {の属性} TarInfo.type

ファイルタイプ。`type' は通常、定数 @ref{2ef1,,REGTYPE}、@ref{2ef2,,AREGTYPE}、@ref{2ef4,,LNKTYPE}、@ref{2ef5,,SYMTYPE}、@ref{2ef8,,DIRTYPE}、@ref{2ef9,,FIFOTYPE}、@ref{2efa,,CONTTYPE}、@ref{2ef6,,CHRTYPE}、@ref{2ef7,,BLKTYPE}、あるいは @ref{2efd,,GNUTYPE_SPARSE} のいずれかです。@ref{142a,,TarInfo} オブジェクトのタイプをもっと簡単に解決するには、下記の @code{is*()} メソッドを使って下さい。
@end deffn

@geindex linkname (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo linkname}@anchor{2f16}
@deffn {の属性} TarInfo.linkname: @ref{169,,str}

リンク先ファイルの名前。これはタイプ @ref{2ef4,,LNKTYPE} と @ref{2ef5,,SYMTYPE} の @ref{142a,,TarInfo} オブジェクトにだけ存在します。

For symbolic links (@code{SYMTYPE}), the `linkname' is relative to the directory
that contains the link.
For hard links (@code{LNKTYPE}), the `linkname' is relative to the root of
the archive.
@end deffn

@geindex uid (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo uid}@anchor{2f17}
@deffn {の属性} TarInfo.uid: @ref{19b,,int}

ファイルメンバーを保存した元のユーザーのユーザー ID。


バージョン 3.12 で変更: Can be set to @code{None} for @ref{29c,,extract()} and
@ref{29b,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex gid (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo gid}@anchor{2f18}
@deffn {の属性} TarInfo.gid: @ref{19b,,int}

ファイルメンバーを保存した元のユーザーのグループ ID。


バージョン 3.12 で変更: Can be set to @code{None} for @ref{29c,,extract()} and
@ref{29b,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex uname (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo uname}@anchor{2f19}
@deffn {の属性} TarInfo.uname: @ref{169,,str}

ファイルメンバーを保存した元のユーザーのユーザー名。


バージョン 3.12 で変更: Can be set to @code{None} for @ref{29c,,extract()} and
@ref{29b,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex gname (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo gname}@anchor{2f1a}
@deffn {の属性} TarInfo.gname: @ref{169,,str}

ファイルメンバーを保存した元のユーザーのグループ名。


バージョン 3.12 で変更: Can be set to @code{None} for @ref{29c,,extract()} and
@ref{29b,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex chksum (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo chksum}@anchor{2f1b}
@deffn {の属性} TarInfo.chksum: @ref{19b,,int}

Header checksum.
@end deffn

@geindex devmajor (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo devmajor}@anchor{2f1c}
@deffn {の属性} TarInfo.devmajor: @ref{19b,,int}

Device major number.
@end deffn

@geindex devminor (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo devminor}@anchor{2f1d}
@deffn {の属性} TarInfo.devminor: @ref{19b,,int}

Device minor number.
@end deffn

@geindex offset (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo offset}@anchor{2f1e}
@deffn {の属性} TarInfo.offset: @ref{19b,,int}

The tar header starts here.
@end deffn

@geindex offset_data (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo offset_data}@anchor{2f1f}
@deffn {の属性} TarInfo.offset_data: @ref{19b,,int}

The file's data starts here.
@end deffn

@geindex sparse (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo sparse}@anchor{2f20}
@deffn {の属性} TarInfo.sparse

Sparse member information.
@end deffn

@geindex pax_headers (tarfile.TarInfo の属性)
@anchor{library/tarfile tarfile TarInfo pax_headers}@anchor{2f21}
@deffn {の属性} TarInfo.pax_headers: @ref{183,,dict}

pax 拡張ヘッダーに関連付けられた、key-value ペアの辞書。
@end deffn

@geindex replace() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo replace}@anchor{2f0f}
@deffn {メソッド} TarInfo.replace (name=..., mtime=..., mode=..., linkname=..., uid=..., gid=..., uname=..., gname=..., deep=True)


Added in version 3.12.


Return a `new' copy of the @code{TarInfo} object with the given attributes
changed. For example, to return a @code{TarInfo} with the group name set to
@code{'staff'}, use:

@example
new_tarinfo = old_tarinfo.replace(gname='staff')
@end example

By default, a deep copy is made.
If `deep' is false, the copy is shallow, i.e. @code{pax_headers}
and any custom attributes are shared with the original @code{TarInfo} object.
@end deffn

@ref{142a,,TarInfo} オブジェクトは便利な照会用のメソッドもいくつか提供しています:

@geindex isfile() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo isfile}@anchor{2f22}
@deffn {メソッド} TarInfo.isfile ()

Return @ref{e07,,True} if the @ref{142a,,TarInfo} object is a regular file.
@end deffn

@geindex isreg() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo isreg}@anchor{2f23}
@deffn {メソッド} TarInfo.isreg ()

@ref{2f22,,isfile()} と同じです。
@end deffn

@geindex isdir() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo isdir}@anchor{2f24}
@deffn {メソッド} TarInfo.isdir ()

ディレクトリの場合に @ref{e07,,True} を返します。
@end deffn

@geindex issym() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo issym}@anchor{2f25}
@deffn {メソッド} TarInfo.issym ()

シンボリックリンクの場合に @ref{e07,,True} を返します。
@end deffn

@geindex islnk() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo islnk}@anchor{2f26}
@deffn {メソッド} TarInfo.islnk ()

ハードリンクの場合に @ref{e07,,True} を返します。
@end deffn

@geindex ischr() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo ischr}@anchor{2f27}
@deffn {メソッド} TarInfo.ischr ()

キャラクターデバイスの場合に @ref{e07,,True} を返します。
@end deffn

@geindex isblk() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo isblk}@anchor{2f28}
@deffn {メソッド} TarInfo.isblk ()

ブロックデバイスの場合に @ref{e07,,True} を返します。
@end deffn

@geindex isfifo() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo isfifo}@anchor{2f29}
@deffn {メソッド} TarInfo.isfifo ()

FIFO の場合に @ref{e07,,True} を返します。
@end deffn

@geindex isdev() (tarfile.TarInfo のメソッド)
@anchor{library/tarfile tarfile TarInfo isdev}@anchor{2f2a}
@deffn {メソッド} TarInfo.isdev ()

キャラクターデバイス、ブロックデバイスあるいは FIFO のいずれかの場合に @ref{e07,,True} を返します。
@end deffn

@node Extraction filters,コマンドラインインターフェイス,TarInfo オブジェクト,tarfile --- tar アーカイブファイルの読み書き
@anchor{library/tarfile extraction-filters}@anchor{2f2b}@anchor{library/tarfile tarfile-extraction-filter}@anchor{697}
@subsubsection Extraction filters



Added in version 3.12.


The `tar' format is designed to capture all details of a UNIX-like filesystem,
which makes it very powerful.
Unfortunately, the features make it easy to create tar files that have
unintended -- and possibly malicious -- effects when extracted.
For example, extracting a tar file can overwrite arbitrary files in various
ways (e.g.  by using absolute paths, @code{..} path components, or symlinks that
affect later members).

In most cases, the full functionality is not needed.
Therefore, `tarfile' supports extraction filters: a mechanism to limit
functionality, and thus mitigate some of the security issues.

@cartouche
@quotation 警告 
None of the available filters blocks `all' dangerous archive features.
Never extract archives from untrusted sources without prior inspection.
See also @ref{2cf4,,Hints for further verification}.
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 706

@item PEP 706@footnote{https://peps.python.org/pep-0706/}

Contains further motivation and rationale behind the design.
@end table


The `filter' argument to @ref{29c,,TarFile.extract()} or @ref{29b,,extractall()}
can be:


@itemize *

@item 
the string @code{'fully_trusted'}: Honor all metadata as specified in the
archive.
Should be used if the user trusts the archive completely, or implements
their own complex verification.

@item 
the string @code{'tar'}: Honor most `tar'-specific features (i.e. features of
UNIX-like filesystems), but block features that are very likely to be
surprising or malicious. See @ref{2f2c,,tar_filter()} for details.

@item 
the string @code{'data'}: Ignore or block most features specific to UNIX-like
filesystems. Intended for extracting cross-platform data archives.
See @ref{29a,,data_filter()} for details.

@item 
@code{None} (default): Use @ref{2f08,,TarFile.extraction_filter}.

If that is also @code{None} (the default), the @code{'data'} filter will be used.

@quotation


バージョン 3.14 で変更: The default filter is set to @ref{29a,,data}.
Previously, the default was equivalent to
@ref{2ede,,fully_trusted}.

@end quotation

@item 
A callable which will be called for each extracted member with a
@ref{2eea,,TarInfo} describing the member and the destination
path to where the archive is extracted (i.e. the same path is used for all
members):

@example
filter(member: TarInfo, path: str, /) -> TarInfo | None
@end example

The callable is called just before each member is extracted, so it can
take the current state of the disk into account.
It can:


@itemize -

@item 
return a @ref{142a,,TarInfo} object which will be used instead of the metadata
in the archive, or

@item 
return @code{None}, in which case the member will be skipped, or

@item 
raise an exception to abort the operation or skip the member,
depending on @ref{29e,,errorlevel}.
Note that when extraction is aborted, @ref{29b,,extractall()} may leave
the archive partially extracted. It does not attempt to clean up.
@end itemize
@end itemize

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

@end menu

@node Default named filters,Filter errors,,Extraction filters
@anchor{library/tarfile default-named-filters}@anchor{2f2d}
@subsubsection Default named filters


The pre-defined, named filters are available as functions, so they can be
reused in custom filters:

@geindex fully_trusted_filter() (tarfile モジュール)
@anchor{library/tarfile tarfile fully_trusted_filter}@anchor{2ede}
@deffn {の関数} tarfile.fully_trusted_filter (member, path)

Return `member' unchanged.

This implements the @code{'fully_trusted'} filter.
@end deffn

@geindex tar_filter() (tarfile モジュール)
@anchor{library/tarfile tarfile tar_filter}@anchor{2f2c}
@deffn {の関数} tarfile.tar_filter (member, path)

Implements the @code{'tar'} filter.


@itemize -

@item 
Strip leading slashes (@code{/} and @ref{87a,,os.sep}) from filenames.

@item 
@ref{2ee8,,Refuse} to extract files with absolute
paths (in case the name is absolute
even after stripping slashes, e.g. @code{C:/foo} on Windows).
This raises @ref{2eeb,,AbsolutePathError}.

@item 
@ref{2ee8,,Refuse} to extract files whose absolute
path (after following symlinks) would end up outside the destination.
This raises @ref{2eec,,OutsideDestinationError}.

@item 
Clear high mode bits (setuid, setgid, sticky) and group/other write bits
(@ref{2c80,,S_IWGRP} | @ref{2c83,,S_IWOTH}).
@end itemize

Return the modified @code{TarInfo} member.
@end deffn

@geindex data_filter() (tarfile モジュール)
@anchor{library/tarfile tarfile data_filter}@anchor{29a}
@deffn {の関数} tarfile.data_filter (member, path)

Implements the @code{'data'} filter.
In addition to what @code{tar_filter} does:


@itemize -

@item 
Normalize link targets (@ref{2f16,,TarInfo.linkname}) using
@ref{1531,,os.path.normpath()}.
Note that this removes internal @code{..} components, which may change the
meaning of the link if the path in @code{TarInfo.linkname} traverses
symbolic links.

@item 
@ref{2ee8,,Refuse} to extract links (hard or soft)
that link to absolute paths, or ones that link outside the destination.

This raises @ref{2eee,,AbsoluteLinkError} or
@ref{2eef,,LinkOutsideDestinationError}.

Note that such files are refused even on platforms that do not support
symbolic links.

@item 
@ref{2ee8,,Refuse} to extract device files
(including pipes).
This raises @ref{2eed,,SpecialFileError}.

@item 
For regular files, including hard links:


@itemize -

@item 
Set the owner read and write permissions
(@ref{2c7b,,S_IRUSR} | @ref{2c7c,,S_IWUSR}).

@item 
Remove the group & other executable permission
(@ref{2c77,,S_IXGRP} | @ref{2c84,,S_IXOTH})
if the owner doesn’t have it (@ref{2c7d,,S_IXUSR}).
@end itemize

@item 
For other files (directories), set @code{mode} to @code{None}, so
that extraction methods skip applying permission bits.

@item 
Set user and group info (@code{uid}, @code{gid}, @code{uname}, @code{gname})
to @code{None}, so that extraction methods skip setting it.
@end itemize

Return the modified @code{TarInfo} member.

Note that this filter does not block `all' dangerous archive features.
See @ref{2cf4,,Hints for further verification}  for details.


バージョン 3.14 で変更: Link targets are now normalized.

@end deffn

@node Filter errors,Hints for further verification,Default named filters,Extraction filters
@anchor{library/tarfile filter-errors}@anchor{2f2e}@anchor{library/tarfile tarfile-extraction-refuse}@anchor{2ee8}
@subsubsection Filter errors


When a filter refuses to extract a file, it will raise an appropriate exception,
a subclass of @ref{2ee7,,FilterError}.
This will abort the extraction if @ref{29e,,TarFile.errorlevel} is 1 or more.
With @code{errorlevel=0} the error will be logged and the member will be skipped,
but extraction will continue.

@node Hints for further verification,Supporting older Python versions,Filter errors,Extraction filters
@anchor{library/tarfile hints-for-further-verification}@anchor{2f2f}@anchor{library/tarfile tarfile-further-verification}@anchor{2cf4}
@subsubsection Hints for further verification


Even with @code{filter='data'}, `tarfile' is not suited for extracting untrusted
files without prior inspection.
Among other issues, the pre-defined filters do not prevent denial-of-service
attacks. Users should do additional checks.

Here is an incomplete list of things to consider:


@itemize *

@item 
Extract to a @ref{52d,,new temporary directory}
to prevent e.g. exploiting pre-existing links, and to make it easier to
clean up after a failed extraction.

@item 
Disallow symbolic links if you do not need the functionality.

@item 
When working with untrusted data, use external (e.g. OS-level) limits on
disk, memory and CPU usage.

@item 
Check filenames against an allow-list of characters
(to filter out control characters, confusables, foreign path separators,
and so on).

@item 
Check that filenames have expected extensions (discouraging files that
execute when you “click on them”, or extension-less files like Windows
special device names).

@item 
Limit the number of extracted files, total size of extracted data,
filename length (including symlink length), and size of individual files.

@item 
Check for files that would be shadowed on case-insensitive filesystems.
@end itemize

Also note that:


@itemize *

@item 
Tar files may contain multiple versions of the same file.
Later ones are expected to overwrite any earlier ones.
This feature is crucial to allow updating tape archives, but can be abused
maliciously.

@item 
`tarfile' does not protect against issues with “live” data,
e.g. an attacker tinkering with the destination (or source) directory while
extraction (or archiving) is in progress.
@end itemize

@node Supporting older Python versions,Stateful extraction filter example,Hints for further verification,Extraction filters
@anchor{library/tarfile supporting-older-python-versions}@anchor{2f30}
@subsubsection Supporting older Python versions


Extraction filters were added to Python 3.12, but may be backported to older
versions as security updates.
To check whether the feature is available, use e.g.
@code{hasattr(tarfile, 'data_filter')} rather than checking the Python version.

The following examples show how to support Python versions with and without
the feature.
Note that setting @code{extraction_filter} will affect any subsequent operations.


@itemize *

@item 
Fully trusted archive:

@example
my_tarfile.extraction_filter = (lambda member, path: member)
my_tarfile.extractall()
@end example

@item 
Use the @code{'data'} filter if available, but revert to Python 3.11 behavior
(@code{'fully_trusted'}) if this feature is not available:

@example
my_tarfile.extraction_filter = getattr(tarfile, 'data_filter',
                                       (lambda member, path: member))
my_tarfile.extractall()
@end example

@item 
Use the @code{'data'} filter; `fail' if it is not available:

@example
my_tarfile.extractall(filter=tarfile.data_filter)
@end example

もしくは:

@example
my_tarfile.extraction_filter = tarfile.data_filter
my_tarfile.extractall()
@end example

@item 
Use the @code{'data'} filter; `warn' if it is not available:

@example
if hasattr(tarfile, 'data_filter'):
    my_tarfile.extractall(filter='data')
else:
    # remove this when no longer needed
    warn_the_user('Extracting may be unsafe; consider updating Python')
    my_tarfile.extractall()
@end example
@end itemize

@node Stateful extraction filter example,,Supporting older Python versions,Extraction filters
@anchor{library/tarfile stateful-extraction-filter-example}@anchor{2f31}
@subsubsection Stateful extraction filter example


While `tarfile''s extraction methods take a simple `filter' callable,
custom filters may be more complex objects with an internal state.
It may be useful to write these as context managers, to be used like this:

@example
with StatefulFilter() as filter_func:
    tar.extractall(path, filter=filter_func)
@end example

Such a filter can be written as, for example:

@example
class StatefulFilter:
    def __init__(self):
        self.file_count = 0

    def __enter__(self):
        return self

    def __call__(self, member, path):
        self.file_count += 1
        return member

    def __exit__(self, *exc_info):
        print(f'@{self.file_count@} files extracted')
@end example

@node コマンドラインインターフェイス,使用例<16>,Extraction filters,tarfile --- tar アーカイブファイルの読み書き
@anchor{library/tarfile command-line-interface}@anchor{2f32}@anchor{library/tarfile tarfile-commandline}@anchor{11cd}
@subsubsection コマンドラインインターフェイス



Added in version 3.4.


The @code{tarfile} module provides a simple command-line interface to interact
with tar archives.

tar アーカイブを新規に作成したい場合、@ref{2f33,,-c} オプションの後にまとめたいファイル名のリストを指定してください:

@example
$ python -m tarfile -c monty.tar  spam.txt eggs.txt
@end example

ディレクトリを渡すこともできます:

@example
$ python -m tarfile -c monty.tar life-of-brian_1979/
@end example

tar アーカイブをカレントディレクトリに展開したい場合、@ref{2f34,,-e} オプションを使用してください:

@example
$ python -m tarfile -e monty.tar
@end example

ディレクトリ名を渡すことで tar アーカイブを別のディレクトリに取り出すこともできます:

@example
$ python -m tarfile -e monty.tar  other-dir/
@end example

tar アーカイブ内のファイル一覧を表示するには @ref{2f35,,-l} を使用してください:

@example
$ python -m tarfile -l monty.tar
@end example

@menu
* コマンドラインオプション: コマンドラインオプション<3>. 

@end menu

@node コマンドラインオプション<3>,,,コマンドラインインターフェイス
@anchor{library/tarfile command-line-options}@anchor{2f36}
@subsubsection コマンドラインオプション


@geindex tarfile コマンドラインオプション; -l
@geindex tarfile コマンドラインオプション; --list
@anchor{library/tarfile cmdoption-tarfile-l}@anchor{2f35}
@deffn {Option} @w{-}l <tarfile>
@anchor{library/tarfile cmdoption-tarfile-list}@anchor{2f37}
@deffnx {Option} @w{-}@w{-}list <tarfile>

tarfile 内のファイル一覧を表示します。
@end deffn

@geindex tarfile コマンドラインオプション; -c
@geindex tarfile コマンドラインオプション; --create
@anchor{library/tarfile cmdoption-tarfile-c}@anchor{2f33}
@deffn {Option} @w{-}c <tarfile> <source1> ... <sourceN>
@anchor{library/tarfile cmdoption-tarfile-create}@anchor{2f38}
@deffnx {Option} @w{-}@w{-}create <tarfile> <source1> ... <sourceN>

ソースファイルから tarfile を作成します。
@end deffn

@geindex tarfile コマンドラインオプション; -e
@geindex tarfile コマンドラインオプション; --extract
@anchor{library/tarfile cmdoption-tarfile-e}@anchor{2f34}
@deffn {Option} @w{-}e <tarfile> [<output_dir>]
@anchor{library/tarfile cmdoption-tarfile-extract}@anchor{2f39}
@deffnx {Option} @w{-}@w{-}extract <tarfile> [<output_dir>]

`output_dir' が指定されていない場合、カレントディレクトリに tarfile を展開します。
@end deffn

@geindex tarfile コマンドラインオプション; -t
@geindex tarfile コマンドラインオプション; --test
@anchor{library/tarfile cmdoption-tarfile-t}@anchor{2f3a}
@deffn {Option} @w{-}t <tarfile>
@anchor{library/tarfile cmdoption-tarfile-test}@anchor{2f3b}
@deffnx {Option} @w{-}@w{-}test <tarfile>

tarfile が有効かどうか調べます。
@end deffn

@geindex tarfile コマンドラインオプション; -v
@geindex tarfile コマンドラインオプション; --verbose
@anchor{library/tarfile cmdoption-tarfile-v}@anchor{2f3c}@anchor{library/tarfile cmdoption-tarfile-verbose}@anchor{2f3d}
@deffn {Option} @w{-}v, @w{-}@w{-}verbose

詳細も出力します。
@end deffn

@geindex tarfile コマンドラインオプション; --filter
@anchor{library/tarfile cmdoption-tarfile-filter}@anchor{2f3e}
@deffn {Option} @w{-}@w{-}filter <filtername>

Specifies the `filter' for @code{--extract}.
See @ref{697,,Extraction filters} for details.
Only string names are accepted (that is, @code{fully_trusted}, @code{tar},
and @code{data}).
@end deffn

@node 使用例<16>,サポートしている tar フォーマット,コマンドラインインターフェイス,tarfile --- tar アーカイブファイルの読み書き
@anchor{library/tarfile examples}@anchor{2f3f}@anchor{library/tarfile tar-examples}@anchor{2ee1}
@subsubsection 使用例


@menu
* Reading examples:: 
* Writing examples:: 

@end menu

@node Reading examples,Writing examples,,使用例<16>
@anchor{library/tarfile reading-examples}@anchor{2f40}
@subsubsection Reading examples


tar アーカイブから現在のディレクトリにすべて抽出する方法:

@example
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall(filter='data')
tar.close()
@end example

tar アーカイブの一部を、リストの代わりにジェネレーター関数を利用して @ref{29b,,TarFile.extractall()} で展開する方法:

@example
import os
import tarfile

def py_files(members):
    for tarinfo in members:
        if os.path.splitext(tarinfo.name)[1] == ".py":
            yield tarinfo

tar = tarfile.open("sample.tar.gz")
tar.extractall(members=py_files(tar))
tar.close()
@end example

gzip 圧縮 tar アーカイブを作成してメンバー情報のいくつかを表示する方法:

@example
import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
    print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
    if tarinfo.isreg():
        print("a regular file.")
    elif tarinfo.isdir():
        print("a directory.")
    else:
        print("something else.")
tar.close()
@end example

@node Writing examples,,Reading examples,使用例<16>
@anchor{library/tarfile writing-examples}@anchor{2f41}
@subsubsection Writing examples


非圧縮 tar アーカイブをファイル名のリストから作成する方法:

@example
import tarfile
tar = tarfile.open("sample.tar", "w")
for name in ["foo", "bar", "quux"]:
    tar.add(name)
tar.close()
@end example

@ref{186,,with} 文を利用した同じ例:

@example
import tarfile
with tarfile.open("sample.tar", "w") as tar:
    for name in ["foo", "bar", "quux"]:
        tar.add(name)
@end example

How to create and write an archive to stdout using
@ref{ccd,,sys.stdout.buffer} in the `fileobj' parameter
in @ref{dee,,TarFile.add()}:

@example
import sys
import tarfile
with tarfile.open("sample.tar.gz", "w|gz", fileobj=sys.stdout.buffer) as tar:
    for name in ["foo", "bar", "quux"]:
        tar.add(name)
@end example

@ref{dee,,TarFile.add()} 関数の `filter' 引数を利用してユーザー情報をリセットしながらアーカイブを作成する方法:

@example
import tarfile
def reset(tarinfo):
    tarinfo.uid = tarinfo.gid = 0
    tarinfo.uname = tarinfo.gname = "root"
    return tarinfo
tar = tarfile.open("sample.tar.gz", "w:gz")
tar.add("foo", filter=reset)
tar.close()
@end example

@node サポートしている tar フォーマット,Unicode に関する問題,使用例<16>,tarfile --- tar アーカイブファイルの読み書き
@anchor{library/tarfile supported-tar-formats}@anchor{2f42}@anchor{library/tarfile tar-formats}@anchor{2efe}
@subsubsection サポートしている tar フォーマット


There are three tar formats that can be created with the @code{tarfile} module:


@itemize *

@item 
POSIX.1-1988 ustar format (@ref{2eff,,USTAR_FORMAT}). ファイル名の長さは256文字までで、リンク名の長さは100文字までです。最大のファイルサイズは8GiBです。このフォーマットは古くて制限が多いですが、広くサポートされています。

@item 
The GNU tar format (@ref{2f00,,GNU_FORMAT}). It supports long filenames and
linknames, files bigger than 8 GiB and sparse files. It is the de facto
standard on GNU/Linux systems. @code{tarfile} fully supports the GNU tar
extensions for long names, sparse file support is read-only.

@item 
The POSIX.1-2001 pax format (@ref{2f01,,PAX_FORMAT}). It is the most flexible
format with virtually no limits. It supports long filenames and linknames, large
files and stores pathnames in a portable way. Modern tar implementations,
including GNU tar, bsdtar/libarchive and star, fully support extended `pax'
features; some old or unmaintained libraries may not, but should treat
`pax' archives as if they were in the universally supported `ustar' format.
It is the current default format for new archives.

It extends the existing `ustar' format with extra headers for information
that cannot be stored otherwise. There are two flavours of pax headers:
Extended headers only affect the subsequent file header, global
headers are valid for the complete archive and affect all following files.
All the data in a pax header is encoded in `UTF-8' for portability reasons.
@end itemize

他にも、読み込みのみサポートしている tar フォーマットがいくつかあります:


@itemize *

@item 
ancient V7 フォーマット。これは Unix 7th Edition から存在する、最初の tar フォーマットです。通常のファイルとディレクトリのみ保存します。名前は 100 文字を超えてはならず、ユーザー/グループ名に関する情報は保存されません。いくつかのアーカイブは、フィールドが ASCII でない文字を含む場合に、ヘッダーのチェックサムの計算を誤ります。

@item 
SunOS tar 拡張フォーマット。POSIX.1-2001 pax フォーマットの亜流ですが、互換性がありません。
@end itemize

@node Unicode に関する問題,,サポートしている tar フォーマット,tarfile --- tar アーカイブファイルの読み書き
@anchor{library/tarfile tar-unicode}@anchor{2f04}@anchor{library/tarfile unicode-issues}@anchor{2f43}
@subsubsection Unicode に関する問題


tar フォーマットは、もともとテープドライブにファイルシステムのバックアップをとる目的で設計されました。現在、tarアーカイブはファイルを配布する際に一般的に用いられ、ネットワーク上で交換されています。オリジナルフォーマットが抱える一つの問題は (他の多くのフォーマットでも同じですが)、様々な文字エンコーディングのサポートについて考慮していないことです。例えば、`UTF-8' システム上で作成された通常の tar アーカイブは、非 `ASCII' 文字を含んでいた場合、`Latin-1' システムでは正しく読み取ることができません。テキストのメタデータ (ファイル名、リンク名、ユーザー/グループ名など) は破壊されます。残念なことに、アーカイブのエンコーディングを自動検出する方法はありません。pax フォーマットはこの問題を解決するために設計されました。これは非 ASCII メタデータをユニバーサル文字エンコーディング `UTF-8' を使用して格納します。

The details of character conversion in @code{tarfile} are controlled by the
`encoding' and `errors' keyword arguments of the @ref{1429,,TarFile} class.

`encoding' はアーカイブのメタデータに使用する文字エンコーディングを指定します。デフォルト値は @ref{e53,,sys.getfilesystemencoding()} で、フォールバックとして @code{'ascii'} が使用されます。アーカイブの読み書き時に、メタデータはそれぞれデコードまたはエンコードしなければなりません。`encoding' に適切な値が設定されていない場合、その変換は失敗することがあります。

引数 `errors' は文字を変換できない時の扱いを指定します。指定できる値は @ref{1b6f,,エラーハンドラ} 節を参照してください。デフォルトのスキームは @code{'surrogateescape'} で、Python はそのファイルシステムの呼び出しも使用します。@ref{2f44,,ファイル名、コマンドライン引数、および環境変数} を参照してください。

デフォルトの @ref{2f01,,PAX_FORMAT} アーカイブでは、メタデータはすべて `UTF-8' で格納されるため、`encoding' は通常指定する必要はありません。`encoding' は、まれにある、バイナリの pax ヘッダーがデコードされた場合、あるいはサロゲート文字を含む文字列が格納されていた場合に使用されます。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ファイルフォーマット,暗号関連のサービス,データ圧縮とアーカイブ,Python 標準ライブラリ
@anchor{library/fileformats doc}@anchor{2f45}@anchor{library/fileformats file-formats}@anchor{2f46}@anchor{library/fileformats fileformats}@anchor{2f47}@anchor{library/fileformats translation-repo}@anchor{2f48}
@section ファイルフォーマット


この章で説明されるモジュールはマークアップやEメールでない様々なファイルフォーマットを構文解析します。

@menu
* csv: csv --- CSV ファイルの読み書き. CSV ファイルの読み書き
* configparser: configparser --- 設定ファイルのパーサー. 設定ファイルのパーサー
* tomllib: tomllib --- TOML ファイルの解析. TOML ファイルの解析
* netrc: netrc --- netrc ファイルの処理. netrc ファイルの処理
* plistlib: plistlib --- Apple plist ファイルを生成・解析する. Apple .plist ファイルを生成・解析する

@end menu

@node csv --- CSV ファイルの読み書き,configparser --- 設定ファイルのパーサー,,ファイルフォーマット
@anchor{library/csv doc}@anchor{2f49}@anchor{library/csv csv-csv-file-reading-and-writing}@anchor{2f4a}@anchor{library/csv module-csv}@anchor{2d}
@subsection @code{csv} --- CSV ファイルの読み書き


@geindex module; csv

`ソースコード:' Lib/csv.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/csv.py}

@geindex csv
@geindex データ;表形式


__________________________________________________________________


CSV (Comma Separated Values、カンマ区切り値列) と呼ばれる形式は、 スプレッドシートやデータベース間でのデータのインポートやエクスポートにおける最も一般的な形式です。 CSVフォーマットは、 
@geindex RFC; RFC 4180
RFC 4180@footnote{https://datatracker.ietf.org/doc/html/rfc4180.html} によって標準的な方法でフォーマットを記述する試みが行われる以前から長年使用されました。明確に定義された標準がないということは、異なるアプリケーション によって生成されたり取り込まれたりするデータ間では、しばしば微妙な違いが発生するということを意味します。こうした違いのために、複数のデータ源から得られた CSV ファイルを処理する作業が鬱陶しいものになることがあります。とはいえ、デリミタ (delimiter) やクオート文字の 相違はあっても、全体的な形式は十分似通っているため、こうしたデータを効率的に操作し、データの読み書きにおける細々としたことをプログラマ から隠蔽するような単一のモジュールを書くことは可能です。

The @code{csv} module implements classes to read and write tabular data in CSV
format.  It allows programmers to say, "write this data in the format preferred
by Excel," or "read data from this file which was generated by Excel," without
knowing the precise details of the CSV format used by Excel.  Programmers can
also describe the CSV formats understood by other applications or define their
own special-purpose CSV formats.

The @code{csv} module's @ref{6ae,,reader} and @ref{6af,,writer} objects read and
write sequences.  Programmers can also read and write data in dictionary form
using the @ref{bd8,,DictReader} and @ref{1417,,DictWriter} classes.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 305

@item PEP 305@footnote{https://peps.python.org/pep-0305/} - CSV File API

Python へのこのモジュールの追加を提案している Python 改良案 (PEP: Python Enhancement Proposal)。
@end table


@menu
* モジュールコンテンツ: モジュールコンテンツ<3>. 
* Dialect クラスと書式化パラメータ:: 
* reader オブジェクト:: 
* writer オブジェクト:: 
* 使用例: 使用例<17>. 

@end menu

@node モジュールコンテンツ<3>,Dialect クラスと書式化パラメータ,,csv --- CSV ファイルの読み書き
@anchor{library/csv csv-contents}@anchor{2f4b}@anchor{library/csv module-contents}@anchor{2f4c}
@subsubsection モジュールコンテンツ


The @code{csv} module defines the following functions:

@geindex universal newlines;csv.reader 関数

@geindex reader() (csv モジュール)
@anchor{library/csv csv reader}@anchor{6ae}
@deffn {の関数} csv.reader (csvfile, /, dialect='excel', **fmtparams)

Return a @ref{2f4d,,reader object} that will process
lines from the given `csvfile'.  A csvfile must be an iterable of
strings, each in the reader's defined csv format.
A csvfile is most commonly a file-like object or list.
If `csvfile' is a file object,
it should be opened with @code{newline='@w{'}}. @footnote{
If @code{newline='@w{'}} is not specified, newlines embedded inside quoted fields
will not be interpreted correctly, and on platforms that use @code{\r\n} line endings
on write an extra @code{\r} will be added.  It should always be safe to specify
@code{newline='@w{'}}, since the csv module does its own
(@ref{f35,,universal}) newline handling.
}  An optional
`dialect' parameter can be given which is used to define a set of parameters
specific to a particular CSV dialect.  It may be an instance of a subclass of
the @ref{1827,,Dialect} class or one of the strings returned by the
@ref{1b94,,list_dialects()} function.  The other optional `fmtparams' keyword arguments
can be given to override individual formatting parameters in the current
dialect.  For full details about the dialect and formatting parameters, see
section @ref{2f4e,,Dialect クラスと書式化パラメータ}.

csv ファイルから読み込まれた各行は、文字列のリストとして返されます。@ref{1947,,QUOTE_NONNUMERIC} フォーマットオプションが指定された場合を除き、データ型の変換が自動的に行われることはありません (このオプションが指定された場合、クォートされていないフィールドは浮動小数点数に変換されます)。

短い利用例:

@example
>>> import csv
>>> with open('eggs.csv', newline='@w{'}) as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
@end example
@end deffn

@geindex writer() (csv モジュール)
@anchor{library/csv csv writer}@anchor{6af}
@deffn {の関数} csv.writer (csvfile, /, dialect='excel', **fmtparams)

ユーザが与えたデータをデリミタで区切られた文字列に変換し、与えられたファイルオブジェクトに書き込むための writer オブジェクトを返します。 `csvfile' は @ref{205b,,write()} メソッドを持つ任意のオブジェクトです。 `csvfile' がファイルオブジェクトの場合、 @code{newline='@w{'}} として開くべきです @footnote{
If @code{newline='@w{'}} is not specified, newlines embedded inside quoted fields
will not be interpreted correctly, and on platforms that use @code{\r\n} line endings
on write an extra @code{\r} will be added.  It should always be safe to specify
@code{newline='@w{'}}, since the csv module does its own
(@ref{f35,,universal}) newline handling.
} 。オプションとして `dialect' 引数を与えることができ、利用するCSV表現形式(dialect)を指定することができます。 `dialect' パラメータは @ref{1827,,Dialect} クラスのサブクラスのインスタンスか、 @ref{1b94,,list_dialects()} 関数が返す文字列の1つにすることができます。別のオプション引数である `fmtparams' キーワード引数は、現在の表現形式における個々の書式パラメータを上書きするために与えることができます。dialect と書式パラメータについての詳細は、 @ref{2f4e,,Dialect クラスと書式化パラメータ} 節を参照してください。 DB API を実装するモジュールとのインターフェースを可能な限り容易にするために、 @ref{885,,None} は空文字列として書き込まれます。この処理は可逆な変換ではありませんが、SQL で NULL データ値を CSV にダンプする処理を、 @code{cursor.fetch*} 呼び出しによって返されたデータを前処理することなく簡単に行うことができます。他の非文字列データは、書き出される前に @ref{169,,str()} を使って文字列に変換されます。

短い利用例:

@example
import csv
with open('eggs.csv', 'w', newline='@w{'}) as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
@end example
@end deffn

@geindex register_dialect() (csv モジュール)
@anchor{library/csv csv register_dialect}@anchor{1939}
@deffn {の関数} csv.register_dialect (name, /, dialect='excel', **fmtparams)

`dialect' を `name' と関連付けます。 `name' は文字列でなければなりません。表現形式(dialect)は @ref{1827,,Dialect} のサブクラスを渡すか、またはキーワード引数 `fmtparams' 、もしくは両方で指定できますが、キーワード引数の方が優先されます。表現形式と書式化パラメータについての詳細は、 @ref{2f4e,,Dialect クラスと書式化パラメータ} 節を参照してください。
@end deffn

@geindex unregister_dialect() (csv モジュール)
@anchor{library/csv csv unregister_dialect}@anchor{1b93}
@deffn {の関数} csv.unregister_dialect (name)

`name' に関連づけられた表現形式を表現形式レジストリから削除します。 `name' が表現形式名でない場合には @ref{2f4f,,Error} を送出します。
@end deffn

@geindex get_dialect() (csv モジュール)
@anchor{library/csv csv get_dialect}@anchor{1b92}
@deffn {の関数} csv.get_dialect (name)

`name' に関連づけられた表現形式を返します。 `name' が表現形式名でない場合には @ref{2f4f,,Error} を送出します。この関数は不変の @ref{1827,,Dialect} を返します。
@end deffn

@geindex list_dialects() (csv モジュール)
@anchor{library/csv csv list_dialects}@anchor{1b94}
@deffn {の関数} csv.list_dialects ()

登録されている全ての表現形式を返します。
@end deffn

@geindex field_size_limit() (csv モジュール)
@anchor{library/csv csv field_size_limit}@anchor{1b91}
@deffn {の関数} csv.field_size_limit ()

@deffnx {の関数} csv.field_size_limit (new_limit)

パーサが許容する現在の最大フィールドサイズを返します。 `new_limit' が渡されたときは、その値が新しい上限になります。
@end deffn

The @code{csv} module defines the following classes:

@geindex DictReader (csv のクラス)
@anchor{library/csv csv DictReader}@anchor{bd8}
@deffn {クラス} csv.DictReader (f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

通常の reader のように動作しますが、個々の行の情報を @ref{183,,dict} にマップするオブジェクトを生成します。マップのキーは省略可能な `fieldnames' パラメータで与えられます。

The `fieldnames' parameter is a @ref{716,,sequence}.  If `fieldnames' is
omitted, the values in the first row of file `f' will be used as the
fieldnames and will be omitted from the results. If
`fieldnames' is provided, they will be used and the first row will be
included in the results.  Regardless of how the fieldnames are determined,
the dictionary preserves their original ordering.

行がフィールド名より多くのフィールドを持っていた場合、残りのデータはリストに入れられて、 `restkey' により指定されたフィールド名 (デフォルトでは @code{None}) で保存されます。空白でない行がフィールド名よりも少ないフィールドしか持たない場合、足りない値は `restval' の値 (デフォルトは @code{None} ) によって埋められます。

その他の省略可能またはキーワード形式のパラメータは、ベースになっている @ref{6ae,,reader} インスタンスに渡されます。

`fieldnames' に渡された引数がイテレータの場合、 @ref{24d,,list} に変換されます。


バージョン 3.6 で変更: 返される行の型は @code{OrderedDict} になりました。



バージョン 3.8 で変更: 返される行の型は @ref{183,,dict} になりました。


短い利用例:

@example
>>> import csv
>>> with open('names.csv', newline='@w{'}) as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese

>>> print(row)
@{'first_name': 'John', 'last_name': 'Cleese'@}
@end example
@end deffn

@geindex DictWriter (csv のクラス)
@anchor{library/csv csv DictWriter}@anchor{1417}
@deffn {クラス} csv.DictWriter (f, fieldnames, restval='@w{'}, extrasaction='raise', dialect='excel', *args, **kwds)

通常の writer のように動作しますが、辞書を出力行にマップするオブジェクトを生成します。 `fieldnames' パラメータは、@ref{fe9,,writerow()} メソッドに渡された辞書の値がどのような順番でファイル `f' に書かれるかを指定するキーの @ref{1f,,sequence} です。 @ref{fe9,,writerow()} メソッドに渡された辞書に `fieldnames' には存在しないキーが含まれている場合、オプションの `extrasaction' パラメータによってどんな動作を行うかが指定されます。この値がデフォルト値である @code{'raise'} に設定されている場合、 @ref{2ec,,ValueError} が送出されます。 @code{'ignore'} に設定されている場合、辞書の余分な値は無視されます。その他のパラメータはベースになっている @ref{6af,,writer} インスタンスに渡されます。

@ref{bd8,,DictReader} クラスとは異なり、 @ref{1417,,DictWriter} の `fieldnames' パラメータは省略可能ではありません。

`fieldnames' に渡された引数がイテレータの場合、 @ref{24d,,list} に変換されます。

短い利用例:

@example
import csv

with open('names.csv', 'w', newline='@w{'}) as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow(@{'first_name': 'Baked', 'last_name': 'Beans'@})
    writer.writerow(@{'first_name': 'Lovely', 'last_name': 'Spam'@})
    writer.writerow(@{'first_name': 'Wonderful', 'last_name': 'Spam'@})
@end example
@end deffn

@geindex Dialect (csv のクラス)
@anchor{library/csv csv Dialect}@anchor{1827}
@deffn {クラス} csv.Dialect

@ref{1827,,Dialect} クラスはコンテナクラスです。その属性に、ダブルクォート、空白文字、デリミタなどの扱い方に関する情報を含みます。CSV には厳密な規格がないため、アプリケーションによって生成される CSV データはそれぞれ僅かに異なります。 @ref{1827,,Dialect} クラスのインスタンスは @ref{6ae,,reader} と @ref{6af,,writer} のインスタンスの挙動を定義します。

All available @ref{1827,,Dialect} names are returned by @ref{1b94,,list_dialects()},
and they can be registered with specific @ref{6ae,,reader} and @ref{6af,,writer}
classes through their initializer (@code{__init__}) functions like this:

@example
import csv

with open('students.csv', 'w', newline='@w{'}) as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
@end example
@end deffn

@geindex excel (csv のクラス)
@anchor{library/csv csv excel}@anchor{2f50}
@deffn {クラス} csv.excel

@ref{2f50,,excel} クラスは Excel で生成される CSV ファイルの通常のプロパティを定義します。これは @code{'excel'} という名前の dialect として登録されています。
@end deffn

@geindex excel_tab (csv のクラス)
@anchor{library/csv csv excel_tab}@anchor{2f51}
@deffn {クラス} csv.excel_tab

@ref{2f51,,excel_tab} クラスは Excel で生成されるタブ分割ファイルの通常のプロパティを定義します。これは @code{'excel-tab'} という名前の dialect として登録されています。
@end deffn

@geindex unix_dialect (csv のクラス)
@anchor{library/csv csv unix_dialect}@anchor{1416}
@deffn {クラス} csv.unix_dialect

@ref{1416,,unix_dialect} クラスは UNIX システムで生成される CSV ファイルの通常のプロパティ (行終端記号として @code{'\n'} を用い全てのフィールドをクォートするもの) を定義します。これは @code{'unix'} という名前の dialect として登録されています。


Added in version 3.2.

@end deffn

@geindex Sniffer (csv のクラス)
@anchor{library/csv csv Sniffer}@anchor{2f52}
@deffn {クラス} csv.Sniffer

@ref{2f52,,Sniffer} クラスは CSV ファイルの書式を推理するために用いられるクラスです。

@ref{2f52,,Sniffer} クラスではメソッドを二つ提供しています:

@geindex sniff() (csv.Sniffer のメソッド)
@anchor{library/csv csv Sniffer sniff}@anchor{2f53}
@deffn {メソッド} sniff (sample, delimiters=None)

与えられた `sample' を解析し、発見されたパラメータを反映した @ref{1827,,Dialect} サブクラスを返します。オプションの `delimiters' パラメータを与えた場合、有効なデリミタ文字を含んでいるはずの文字列として解釈されます。
@end deffn

@geindex has_header() (csv.Sniffer のメソッド)
@anchor{library/csv csv Sniffer has_header}@anchor{1c57}
@deffn {メソッド} has_header (sample)

Analyze the sample text (presumed to be in CSV format) and return
@ref{e07,,True} if the first row appears to be a series of column headers.
Inspecting each column, one of two key criteria will be considered to
estimate if the sample contains a header:


@itemize -

@item 
2番目からn番目の行は数値を含みます。

@item 
the second through n-th rows contain strings where at least one value's
length differs from that of the putative header of that column.
@end itemize

Twenty-one rows after the header are sampled; if more than half of the
columns + rows meet the criteria, @ref{e07,,True} is returned.
@end deffn

@cartouche
@quotation 注釈 
このメソッドは大雑把なヒューリスティックであり、結果が偽陽性や偽陰性である可能性があります。
@end quotation
@end cartouche
@end deffn

@ref{2f52,,Sniffer} の利用例:

@example
with open('example.csv', newline='@w{'}) as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...
@end example
@anchor{library/csv csv-constants}@anchor{2f54}
The @code{csv} module defines the following constants:

@geindex QUOTE_ALL (csv モジュール)
@anchor{library/csv csv QUOTE_ALL}@anchor{2f55}
@deffn {データ} csv.QUOTE_ALL

@ref{6af,,writer} オブジェクトに対し、全てのフィールドをクオートするように指示します。
@end deffn

@geindex QUOTE_MINIMAL (csv モジュール)
@anchor{library/csv csv QUOTE_MINIMAL}@anchor{2f56}
@deffn {データ} csv.QUOTE_MINIMAL

@ref{6af,,writer} オブジェクトに対し、 `delimiter' 、 `quotechar'、@code{'\r'}、@code{'\n'} または `lineterminator' に含まれる任意の文字のような特別な文字を含むフィールドだけをクオートするように指示します。
@end deffn

@geindex QUOTE_NONNUMERIC (csv モジュール)
@anchor{library/csv csv QUOTE_NONNUMERIC}@anchor{1947}
@deffn {データ} csv.QUOTE_NONNUMERIC

@ref{6af,,writer} オブジェクトに対し、全ての非数値フィールドをクオートするように指示します。

@ref{6ae,,reader} オブジェクトに、クォーテーションで囲まれていないすべてのフィールドを @ref{196,,float} 型に変換するよう指示します。

@cartouche
@quotation 注釈 
Some numeric types, such as @ref{3c3,,bool}, @ref{213,,Fraction},
or @ref{edb,,IntEnum}, have a string representation that cannot be
converted to @ref{196,,float}.
They cannot be read in the @ref{1947,,QUOTE_NONNUMERIC} and
@ref{6ad,,QUOTE_STRINGS} modes.
@end quotation
@end cartouche
@end deffn

@geindex QUOTE_NONE (csv モジュール)
@anchor{library/csv csv QUOTE_NONE}@anchor{2f57}
@deffn {データ} csv.QUOTE_NONE

Instructs @ref{6af,,writer} objects to never quote fields.
When the current `delimiter', `quotechar', `escapechar', @code{'\r'}, @code{'\n'}
or any of the characters in `lineterminator' occurs in output data
it is preceded by the current `escapechar' character.
If `escapechar' is not set, the writer will raise @ref{2f4f,,Error} if
any characters that require escaping are encountered.
Set `quotechar' to @code{None} to prevent its escaping.

@ref{6ae,,reader} オブジェクトに、クオート文字に対する特殊処理を行わないよう指示します。
@end deffn

@geindex QUOTE_NOTNULL (csv モジュール)
@anchor{library/csv csv QUOTE_NOTNULL}@anchor{6ac}
@deffn {データ} csv.QUOTE_NOTNULL

Instructs @ref{6af,,writer} objects to quote all fields which are not
@code{None}.  This is similar to @ref{2f55,,QUOTE_ALL}, except that if a
field value is @code{None} an empty (unquoted) string is written.

Instructs @ref{6ae,,reader} objects to interpret an empty (unquoted) field
as @code{None} and to otherwise behave as @ref{2f55,,QUOTE_ALL}.


Added in version 3.12.

@end deffn

@geindex QUOTE_STRINGS (csv モジュール)
@anchor{library/csv csv QUOTE_STRINGS}@anchor{6ad}
@deffn {データ} csv.QUOTE_STRINGS

Instructs @ref{6af,,writer} objects to always place quotes around fields
which are strings.  This is similar to @ref{1947,,QUOTE_NONNUMERIC}, except that if a
field value is @code{None} an empty (unquoted) string is written.

Instructs @ref{6ae,,reader} objects to interpret an empty (unquoted) string as @code{None} and
to otherwise behave as @ref{1947,,QUOTE_NONNUMERIC}.


Added in version 3.12.

@end deffn

The @code{csv} module defines the following exception:

@geindex Error
@anchor{library/csv csv Error}@anchor{2f4f}
@deffn {例外} csv.Error

全ての関数において、エラーが検出された際に送出される例外です。
@end deffn

@node Dialect クラスと書式化パラメータ,reader オブジェクト,モジュールコンテンツ<3>,csv --- CSV ファイルの読み書き
@anchor{library/csv csv-fmt-params}@anchor{2f4e}@anchor{library/csv dialects-and-formatting-parameters}@anchor{2f58}
@subsubsection Dialect クラスと書式化パラメータ


To make it easier to specify the format of input and output records, specific
formatting parameters are grouped together into dialects.  A dialect is a
subclass of the @ref{1827,,Dialect} class containing various attributes
describing the format of the CSV file.  When creating @ref{6ae,,reader} or
@ref{6af,,writer} objects, the programmer can specify a string or a subclass of
the @ref{1827,,Dialect} class as the dialect parameter.  In addition to, or instead
of, the `dialect' parameter, the programmer can also specify individual
formatting parameters, which have the same names as the attributes defined below
for the @ref{1827,,Dialect} class.

Dialect は以下の属性をサポートしています:

@geindex delimiter (csv.Dialect の属性)
@anchor{library/csv csv Dialect delimiter}@anchor{2f59}
@deffn {の属性} Dialect.delimiter

フィールド間を分割するのに用いられる 1 文字からなる文字列です。デフォルトでは @code{','} です。
@end deffn

@geindex doublequote (csv.Dialect の属性)
@anchor{library/csv csv Dialect doublequote}@anchor{2f5a}
@deffn {の属性} Dialect.doublequote

フィールド内に現れた `quotechar' のインスタンスで、クオートではないその文字自身でなければならない文字をどのようにクオートするかを制御します。 @ref{e07,,True} の場合、この文字は二重化されます。 @ref{d2b,,False} の場合、 `escapechar' は `quotechar' の前に置かれます。デフォルトでは @ref{e07,,True} です。

出力においては、 `doublequote' が @ref{d2b,,False} で `escapechar' がセットされていない場合、フィールド内に `quotechar' が現れると @ref{2f4f,,Error} が送出されます。
@end deffn

@geindex escapechar (csv.Dialect の属性)
@anchor{library/csv csv Dialect escapechar}@anchor{2f5b}
@deffn {の属性} Dialect.escapechar

A one-character string used by the writer to escape characters that
require escaping:

@quotation


@itemize *

@item 
the `delimiter', the `quotechar', @code{'\r'}, @code{'\n'} and any of the
characters in `lineterminator' are escaped if `quoting' is set to
@ref{2f57,,QUOTE_NONE};

@item 
the `quotechar' is escaped if `doublequote' is @ref{d2b,,False};

@item 
the `escapechar' itself.
@end itemize
@end quotation

On reading, the `escapechar' removes any special meaning from
the following character. It defaults to @ref{885,,None}, which disables escaping.


バージョン 3.11 で変更: 空の `escapechar' は許可されていません。

@end deffn

@geindex lineterminator (csv.Dialect の属性)
@anchor{library/csv csv Dialect lineterminator}@anchor{2f5c}
@deffn {の属性} Dialect.lineterminator

@ref{6af,,writer} が作り出す各行を終端する際に用いられる文字列です。デフォルトでは @code{'\r\n'} です。

@cartouche
@quotation 注釈 
@ref{6ae,,reader} は @code{'\r'} または @code{'\n'} のどちらかを行末と認識するようにハードコードされており、 `lineterminator' を無視します。この振る舞いは将来変更されるかもしれません。
@end quotation
@end cartouche
@end deffn

@geindex quotechar (csv.Dialect の属性)
@anchor{library/csv csv Dialect quotechar}@anchor{2f5d}
@deffn {の属性} Dialect.quotechar

A one-character string used to quote fields containing special characters,
such as the `delimiter' or the `quotechar', or which contain new-line
characters (@code{'\r'}, @code{'\n'} or any of the characters in `lineterminator').
It defaults to @code{'"'}.
Can be set to @code{None} to prevent escaping @code{'"'} if `quoting' is set
to @ref{2f57,,QUOTE_NONE}.


バージョン 3.11 で変更: 空の `quotechar' は許可されていません。

@end deffn

@geindex quoting (csv.Dialect の属性)
@anchor{library/csv csv Dialect quoting}@anchor{2f5e}
@deffn {の属性} Dialect.quoting

Controls when quotes should be generated by the writer and recognised by the
reader.  It can take on any of the @ref{2f54,,QUOTE_* constants}
and defaults to @ref{2f56,,QUOTE_MINIMAL} if `quotechar' is not @code{None},
and @ref{2f57,,QUOTE_NONE} otherwise.
@end deffn

@geindex skipinitialspace (csv.Dialect の属性)
@anchor{library/csv csv Dialect skipinitialspace}@anchor{2f5f}
@deffn {の属性} Dialect.skipinitialspace

When @ref{e07,,True}, spaces immediately following the `delimiter' are ignored.
The default is @ref{d2b,,False}.  When combining @code{delimiter=' '} with
@code{skipinitialspace=True}, unquoted empty fields are not allowed.
@end deffn

@geindex strict (csv.Dialect の属性)
@anchor{library/csv csv Dialect strict}@anchor{2f60}
@deffn {の属性} Dialect.strict

@code{True} の場合、 不正な CSV 入力に対して @ref{2f4f,,Error} を送出します。デフォルトでは @code{False} です。
@end deffn

@node reader オブジェクト,writer オブジェクト,Dialect クラスと書式化パラメータ,csv --- CSV ファイルの読み書き
@anchor{library/csv id3}@anchor{2f61}@anchor{library/csv reader-objects}@anchor{2f4d}
@subsubsection reader オブジェクト


reader オブジェクト(@ref{bd8,,DictReader} インスタンス、および @ref{6ae,,reader()} 関数によって返されたオブジェクト) は、以下の public なメソッドを持っています:

@geindex __next__() (csv.csvreader のメソッド)
@anchor{library/csv csv csvreader __next__}@anchor{2f62}
@deffn {メソッド} csvreader.__next__ ()

reader の反復可能なオブジェクトから、現在の表現形式 (@ref{1827,,Dialect}) に基づいて次の行を解析してリスト（オブジェクトが @ref{6ae,,reader()} から返された場合）または辞書 （ @ref{bd8,,DictReader} のインスタンスの場合）として返します。通常は @code{next(reader)} のようにして呼び出すことになります。
@end deffn

reader オブジェクトには以下の公開属性があります:

@geindex dialect (csv.csvreader の属性)
@anchor{library/csv csv csvreader dialect}@anchor{2f63}
@deffn {の属性} csvreader.dialect

パーサで使われる表現形式の読み出し専用の記述です。
@end deffn

@geindex line_num (csv.csvreader の属性)
@anchor{library/csv csv csvreader line_num}@anchor{2f64}
@deffn {の属性} csvreader.line_num

ソースイテレータから読んだ行数です。この数は返されるレコードの数とは、レコードが複数行に亘ることがあるので、一致しません。
@end deffn

DictReader オブジェクトは、以下の public な属性を持っています:

@geindex fieldnames (csv.DictReader の属性)
@anchor{library/csv csv DictReader fieldnames}@anchor{2f65}
@deffn {の属性} DictReader.fieldnames

オブジェクトを生成するときに渡されなかった場合、この属性は最初のアクセス時か、ファイルから最初のレコードを読み出したときに初期化されます。
@end deffn

@node writer オブジェクト,使用例<17>,reader オブジェクト,csv --- CSV ファイルの読み書き
@anchor{library/csv writer-objects}@anchor{2f66}
@subsubsection writer オブジェクト


@ref{6af,,writer} オブジェクト(@ref{1417,,DictWriter} インスタンス、および  @ref{6af,,writer()} 関数によって返されたオブジェクト) は、以下の public なメソッドを持っています: `row' には、 @ref{6af,,writer} オブジェクトの場合には文字列か数値のイテラブルを指定し、 @ref{1417,,DictWriter} オブジェクトの場合はフィールド名をキーとして対応する文字列か数値を格納した辞書オブジェクトを指定します(数値は @ref{169,,str()} で変換されます)。複素数を出力する場合、値をかっこで囲んで出力します。このため、CSV ファイルを読み込むアプリケーションで（そのアプリケーションが複素数をサポートしていたとしても）問題が発生する場合があります。

@geindex writerow() (csv.csvwriter のメソッド)
@anchor{library/csv csv csvwriter writerow}@anchor{fe9}
@deffn {メソッド} csvwriter.writerow (row, /)

現在の表現形式 (@ref{1827,,Dialect}.)に沿ってフォーマットされた `row' パラメータを writer のファイルオブジェクトに書き込みます。ファイルオブジェクトの `write' メソッドを呼び出した際の戻り値を返します。


バージョン 3.5 で変更: 任意のイテラブルのサポートの追加。

@end deffn

@geindex writerows() (csv.csvwriter のメソッド)
@anchor{library/csv csv csvwriter writerows}@anchor{2f67}
@deffn {メソッド} csvwriter.writerows (rows, /)

`rows' 引数 (上で解説した `row' オブジェクトのイテラブル) の全ての要素を現在の表現形式に基づいて書式化し、writer のファイルオブジェクトに書き込みます。
@end deffn

writer オブジェクトには以下の公開属性があります:

@geindex dialect (csv.csvwriter の属性)
@anchor{library/csv csv csvwriter dialect}@anchor{2f68}
@deffn {の属性} csvwriter.dialect

writer で使われる表現形式の読み出し専用の記述です。
@end deffn

DictWriter のオブジェクトは以下の public メソッドを持っています:

@geindex writeheader() (csv.DictWriter のメソッド)
@anchor{library/csv csv DictWriter writeheader}@anchor{1418}
@deffn {メソッド} DictWriter.writeheader ()

Write a row with the field names (as specified in the constructor) to
the writer's file object, formatted according to the current dialect. Return
the return value of the @ref{fe9,,csvwriter.writerow()} call used internally.


Added in version 3.2.



バージョン 3.8 で変更: @ref{1418,,writeheader()} は内部的に利用している @ref{fe9,,csvwriter.writerow()} メソッドの返り値を返すようになりました。

@end deffn

@node 使用例<17>,,writer オブジェクト,csv --- CSV ファイルの読み書き
@anchor{library/csv csv-examples}@anchor{2f69}@anchor{library/csv examples}@anchor{2f6a}
@subsubsection 使用例


最も簡単な CSV ファイル読み込みの例です:

@example
import csv
with open('some.csv', newline='@w{'}) as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
@end example

別の書式での読み込み:

@example
import csv
with open('passwd', newline='@w{'}) as f:
    reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(row)
@end example

上に対して、単純な書き込みのプログラム例は以下のようになります。

@example
import csv
with open('some.csv', 'w', newline='@w{'}) as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)
@end example

@ref{316,,open()} が CSV ファイルの読み込みに使われるため、ファイルはデフォルトではシステムのデフォルトエンコーディングでユニコード文字列にデコードされます (@ref{329,,locale.getencoding()} を参照)。他のエンコーディングを用いてデコードするには、open の引数 @code{encoding} を設定して、以下のようにします:

@example
import csv
with open('some.csv', newline='@w{'}, encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
@end example

システムのデフォルトエンコーディング以外で書き込む場合も同様です。出力ファイルを開く際に引数 @code{encoding} を明示してください。

新しい表現形式の登録:

@example
import csv
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', newline='@w{'}) as f:
    reader = csv.reader(f, 'unixpwd')
@end example

もう少し手の込んだ reader の使い方 --- エラーを捉えてレポートします。

@example
import csv, sys
filename = 'some.csv'
with open(filename, newline='@w{'}) as f:
    reader = csv.reader(f)
    try:
        for row in reader:
            print(row)
    except csv.Error as e:
        sys.exit(f'file @{filename@}, line @{reader.line_num@}: @{e@}')
@end example

このモジュールは文字列の解析は直接サポートしませんが、簡単にできます。

@example
import csv
for row in csv.reader(['one,two,three']):
    print(row)
@end example

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node configparser --- 設定ファイルのパーサー,tomllib --- TOML ファイルの解析,csv --- CSV ファイルの読み書き,ファイルフォーマット
@anchor{library/configparser doc}@anchor{2f6b}@anchor{library/configparser configparser-configuration-file-parser}@anchor{2f6c}@anchor{library/configparser module-configparser}@anchor{26}@anchor{library/configparser translation-repo}@anchor{2f6d}
@subsection @code{configparser} --- 設定ファイルのパーサー


@geindex module; configparser

`ソースコード:' Lib/configparser.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/configparser.py}

@geindex .ini;ファイル
@geindex 設定;ファイル
@geindex ini ファイル
@geindex Windows ini ファイル


__________________________________________________________________


このモジュールは、 Microsoft Windows の INI ファイルに似た構造を持ったベーシックな設定用言語を実装した @ref{4de,,ConfigParser} クラスを提供します。このクラスを使ってユーザーが簡単にカスタマイズできる Python プログラムを作ることができます。

@cartouche
@quotation 注釈 
このライブラリでは、Windowsのレジストリ用に拡張された INI 文法はサポート `していません' 。
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@item モジュール @ref{102,,tomllib}

TOML is a well-specified format for application configuration files.
It is specifically designed to be an improved version of INI.

@item @ref{c9,,shlex} モジュール

アプリケーション設定ファイルにも使える、Unix シェルに似たミニ言語の作成を支援します。

@item @ref{86,,json} モジュール

The @code{json} module implements a subset of JavaScript syntax which is
sometimes used for configuration, but does not support comments.
@end table


@c import configparser

@c import os
@c os.remove("example.ini")
@c os.remove("override.ini")

@menu
* クイックスタート:: 
* サポートされるデータ型:: 
* 代替値:: 
* サポートするINI ファイルの構造:: 
* Unnamed Sections:: 
* 値の補間:: 
* マップ型プロトコルアクセス:: 
* パーサーの振る舞いをカスタマイズする:: 
* レガシーな API の例:: 
* ConfigParser オブジェクト:: 
* RawConfigParser オブジェクト:: 
* 例外: 例外<9>. 

@end menu

@node クイックスタート,サポートされるデータ型,,configparser --- 設定ファイルのパーサー
@anchor{library/configparser quick-start}@anchor{2f6e}
@subsubsection クイックスタート


次のような、非常に簡単な設定ファイルを例に考えましょう:

@example
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[forge.example]
User = hg

[topsecret.server.example]
Port = 50022
ForwardX11 = no
@end example

The structure of INI files is described @ref{2f6f,,in the following section}.  Essentially, the file
consists of sections, each of which contains keys with values.
@code{configparser} classes can read and write such files.  Let's start by
creating the above configuration file programmatically.

@example
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = @{'ServerAliveInterval': '45',
...                      'Compression': 'yes',
...                      'CompressionLevel': '9'@}
>>> config['forge.example'] = @{@}
>>> config['forge.example']['User'] = 'hg'
>>> config['topsecret.server.example'] = @{@}
>>> topsecret = config['topsecret.server.example']
>>> topsecret['Port'] = '50022'     # mutates the parser
>>> topsecret['ForwardX11'] = 'no'  # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
...   config.write(configfile)
...
@end example

この例でわかるように、config parser は辞書のように扱うことができます。辞書との違いは @ref{2f70,,後に} 説明しますが、このインターフェイスは辞書に対して期待するのととても近い動作をします。

これで設定ファイルを作成して保存できました。次はこれを読み込み直して、中のデータを取り出してみましょう。

@example
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['forge.example', 'topsecret.server.example']
>>> 'forge.example' in config
True
>>> 'python.org' in config
False
>>> config['forge.example']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.example']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['forge.example']:
...     print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['forge.example']['ForwardX11']
'yes'
@end example

上の例からわかるように、API はとても直感的です。唯一の魔術は、@code{DEFAULT} セクションが他の全てのセクションのためのデフォルト値を提供していることです @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}。 また、セクション内の各キーは大文字小文字を区別せず、全て小文字で保存されていることにも注意してください @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}。

It is possible to read several configurations into a single
@ref{4de,,ConfigParser}, where the most recently added configuration has the
highest priority. Any conflicting keys are taken from the more recent
configuration while the previously existing keys are retained. The example
below reads in an @code{override.ini} file, which will override any conflicting
keys from the @code{example.ini} file.

@example
[DEFAULT]
ServerAliveInterval = -1
@end example

@example
>>> config_override = configparser.ConfigParser()
>>> config_override['DEFAULT'] = @{'ServerAliveInterval': '-1'@}
>>> with open('override.ini', 'w') as configfile:
...     config_override.write(configfile)
...
>>> config_override = configparser.ConfigParser()
>>> config_override.read(['example.ini', 'override.ini'])
['example.ini', 'override.ini']
>>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))
-1
@end example

This behaviour is equivalent to a @ref{1681,,ConfigParser.read()} call with several
files passed to the `filenames' parameter.

@node サポートされるデータ型,代替値,クイックスタート,configparser --- 設定ファイルのパーサー
@anchor{library/configparser supported-datatypes}@anchor{2f72}
@subsubsection サポートされるデータ型


Config parser は値のデータ型について何も推論せず、常に文字列のまま内部に保存します。他のデータ型が必要な場合は自分で変換する必要があります:

@example
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
@end example

このタスクはとても一般的なため、設定パーサーでは整数、浮動小数点数、真偽値を扱うための手頃なゲッターメソッドが提供されています。真偽値の扱いは一筋縄ではいきません。文字列を @code{bool()} に渡しても、 @code{bool('False')} が @code{True} になってしまいます。そこで config parser は @ref{2f73,,getboolean()} を提供しています。このメソッドは大文字小文字を区別せず、 @code{'yes'}/@code{'no'}、@code{'on'}/@code{'off'}、@code{'true'}/@code{'false'}、@code{'1'}/@code{'0'} を真偽値として認識します @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}。例えば:

@example
>>> topsecret.getboolean('ForwardX11')
False
>>> config['forge.example'].getboolean('ForwardX11')
True
>>> config.getboolean('forge.example', 'Compression')
True
@end example

config parser では、 @ref{2f73,,getboolean()} 以外に @ref{2f74,,getint()} と @ref{2f75,,getfloat()} メソッドも提供されています。独自のコンバーターの登録、提供されたメソッドのカスタマイズもできます。 @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}

@node 代替値,サポートするINI ファイルの構造,サポートされるデータ型,configparser --- 設定ファイルのパーサー
@anchor{library/configparser fallback-values}@anchor{2f76}
@subsubsection 代替値


As with a dictionary, you can use a section's @ref{1483,,get()} method to
provide fallback values:

@example
>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'
@end example

デフォルト値は代替値よりも優先されることに注意してください。例えば上の例では、@code{'CompressionLevel'} キーは @code{'DEFAULT'} セクションにしか存在しません。その値を @code{'topsecret.server.example'} から取得しようとした場合、代替値を指定しても常にデフォルト値を返します:

@example
>>> topsecret.get('CompressionLevel', '3')
'9'
@end example

One more thing to be aware of is that the parser-level @ref{1483,,get()} method
provides a custom, more complex interface, maintained for backwards
compatibility.  When using this method, a fallback value can be provided via
the @code{fallback} keyword-only argument:

@example
>>> config.get('forge.example', 'monster',
...            fallback='No such things as monsters')
'No such things as monsters'
@end example

同様の @code{fallback} 引数を、@ref{2f74,,getint()} 、 @ref{2f75,,getfloat()} と @ref{2f73,,getboolean()} メソッドでも使えます。例えば:

@example
>>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False
@end example

@node サポートするINI ファイルの構造,Unnamed Sections,代替値,configparser --- 設定ファイルのパーサー
@anchor{library/configparser supported-ini-file-structure}@anchor{2f6f}
@subsubsection サポートするINI ファイルの構造


A configuration file consists of sections, each led by a @code{[section]} header,
followed by key/value entries separated by a specific string (@code{=} or @code{:} by
default @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}).  By default, section names are case sensitive but keys are not
@footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}.  Leading and trailing whitespace is removed from keys and values.
Values can be omitted if the parser is configured to allow it @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
},
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.

By default, a valid section name can be any string that does not contain '\n'.
To change this, see @ref{2f77,,ConfigParser.SECTCRE}.

The first section name may be omitted if the parser is configured to allow an
unnamed top level section with @code{allow_unnamed_section=True}. In this case,
the keys/values may be retrieved by @ref{178a,,UNNAMED_SECTION} as in
@code{config[UNNAMED_SECTION]}.

設定ファイルには先頭に特定の文字 (デフォルトでは @code{#} および @code{;} @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}) をつけてコメントをつけることができます。コメントは、他の内容がない行に置くことができ、インデントされていても構いません。@footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}

例えば:

@example
[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true

[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
    I sleep all night and I work all day

[No Values]
key_without_value
empty string value here =

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

    [Sections Can Be Indented]
        can_values_be_as_well = True
        does_that_mean_anything_special = False
        purpose = formatting for readability
        multiline_values = are
            handled just fine as
            long as they are indented
            deeper than the first line
            of a value
        # Did I mention we can indent comments, too?
@end example

@node Unnamed Sections,値の補間,サポートするINI ファイルの構造,configparser --- 設定ファイルのパーサー
@anchor{library/configparser id10}@anchor{2f78}@anchor{library/configparser unnamed-sections}@anchor{2f79}
@subsubsection Unnamed Sections


The name of the first section (or unique) may be omitted and values
retrieved by the @ref{178a,,UNNAMED_SECTION} attribute.

@example
>>> config = """
... option = value
...
... [  Section 2  ]
... another = val
... """
>>> unnamed = configparser.ConfigParser(allow_unnamed_section=True)
>>> unnamed.read_string(config)
>>> unnamed.get(configparser.UNNAMED_SECTION, 'option')
'value'
@end example

@node 値の補間,マップ型プロトコルアクセス,Unnamed Sections,configparser --- 設定ファイルのパーサー
@anchor{library/configparser interpolation-of-values}@anchor{2f7a}
@subsubsection 値の補間


コア機能に加えて、 @ref{4de,,ConfigParser} は補間(interpolation, 内挿とも)をサポートします。これは @code{get()} コールが値を返す前に、その値に対して前処理を行えることを意味します。

@geindex % (パーセント);interpolation in configuration files

@geindex BasicInterpolation (configparser のクラス)
@anchor{library/configparser configparser BasicInterpolation}@anchor{92c}
@deffn {クラス} configparser.BasicInterpolation

@ref{4de,,ConfigParser} が使用するデフォルト実装です。値に、同じセクションか特別なデフォルトセクション中 @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
} の他の値を参照するフォーマット文字列を含めることができます。追加のデフォルト値を初期化時に提供できます。

例えば:

@example
[Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

[Escape]
# use a %% to escape the % sign (% is the only character that needs to be escaped):
gain: 80%%
@end example

上の例では、 `interpolation' に @code{BasicInterpolation()} を設定した @ref{4de,,ConfigParser} が @code{%(home_dir)s} を @code{home_dir} の値(このケースでは @code{/Users} )として解決しています、その結果 @code{%(my_dir)s} は @code{/Users/lumberjack} になります。全ての補間は必要に応じて実行されるため、設定ファイル中で参照の連鎖をもつキーを特定の順序で記述する必要はありません。

@code{interpolation} に @code{None} を設定すれば、パーサーは単に @code{my_pictures} の値として  @code{%(my_dir)s/Pictures} を返し、@code{my_dir} の値として @code{%(home_dir)s/lumberjack} を返します。
@end deffn

@geindex $ (ダラー);interpolation in configuration files

@geindex ExtendedInterpolation (configparser のクラス)
@anchor{library/configparser configparser ExtendedInterpolation}@anchor{92d}
@deffn {クラス} configparser.ExtendedInterpolation

@code{zc.buildout} で使用されるような、より高度な文法を実装した補間ハンドラの別の選択肢です。拡張された補間は、他のセクション中の値を示すのに @code{$@{section:option@}} と書けます。補間は複数のレベルに及べます、利便性のために、もし @code{section:} の部分が省略されると、現在のセクションがデフォルト値となります(スペシャルセクション中のデフォルト値を使用することもできます)。

たとえば、上記の basic interpolation で指定した設定は、extended interpolation を使うと下記のようになります:

@example
[Paths]
home_dir: /Users
my_dir: $@{home_dir@}/lumberjack
my_pictures: $@{my_dir@}/Pictures

[Escape]
# use a $$ to escape the $ sign ($ is the only character that needs to be escaped):
cost: $$80
@end example

他のセクションから値を持ってくることもできます:

@example
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local

[Frameworks]
Python: 3.2
path: $@{Common:system_dir@}/Library/Frameworks/

[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: $@{Common:home_dir@}/twosheds
my_pictures: $@{my_dir@}/Pictures
python_dir: $@{Frameworks:path@}/Python/Versions/$@{Frameworks:Python@}
@end example
@end deffn

@node マップ型プロトコルアクセス,パーサーの振る舞いをカスタマイズする,値の補間,configparser --- 設定ファイルのパーサー
@anchor{library/configparser mapping-protocol-access}@anchor{2f70}
@subsubsection マップ型プロトコルアクセス



Added in version 3.2.


Mapping protocol access is a generic name for functionality that enables using
custom objects as if they were dictionaries.  In case of @code{configparser},
the mapping interface implementation is using the
@code{parser['section']['option']} notation.

とくに、@code{parser['section']} はパーサー内のそのセクションのデータへのプロキシを返します。つまり、値はコピーされるのではなく必要に応じてオリジナルのパーサーから取られます。さらに重要なことに、セクションのプロキシの値が変更されると、オリジナルのパーサー中の値が実際に変更されます。

@code{configparser} objects behave as close to actual dictionaries as possible.
The mapping interface is complete and adheres to the
@ref{12c0,,MutableMapping} ABC.
However, there are a few differences that should be taken into account:


@itemize *

@item 
デフォルトでは、セクション内の全てのキーは大文字小文字の区別なくアクセスできます @footnote{
設定パーサーは大々的にカスタマイズできます。脚注の参照で概説された挙動の変更に関心がある場合、@ref{2f71,,Customizing Parser Behaviour} セクションを参照してください。
}。例えば、@code{for option in parser["section"]} は @code{optionxform} されたオプションキー名のみを yield します。つまり小文字のキーがデフォルトです。同時に、キー @code{'a'} を含むセクションにおいて、どちらの式も @code{True} を返します:

@example
"a" in parser["section"]
"A" in parser["section"]
@end example

@item 
全てのセクションは @code{DEFAULTSECT} 値を持ち、すなわちセクションで @code{.clear()} してもセクションは見た目上空になりません。これは、デフォルト値は (技術的にはそこにないので) セクションから削除できないためです。デフォルト値が上書きされた場合、それが削除されるとデフォルト値が再び見えるようになります。デフォルト値を削除しようとすると @ref{5e7,,KeyError} が発生します。

@item 
@code{DEFAULTSECT} はパーサーから取り除けません:


@itemize *

@item 
削除しようとすると @ref{2ec,,ValueError} が発生します。

@item 
@code{parser.clear()} はこれをそのまま残し、

@item 
@code{parser.popitem()} がこれを返すことはありません。
@end itemize

@item 
@code{parser.get(section, option, **kwargs)} - 第二引数は代替値では `ありません'。ただし、セクションごとの @code{get()} メソッドはマップ型プロトコルと旧式の configparser API の両方に互換です。

@item 
@code{parser.items()} はマップ型プロトコルと互換です (DEFAULTSECT を含む `section_name', `section_proxy' 対のリストを返します)。ただし、このメソッドは @code{parser.items(section, raw, vars)} のようにして引数を与えることでも呼び出せます。後者の呼び出しは指定された @code{section} の  `option', `value' 対のリストを、(@code{raw=True} が与えられない限り) 全ての補間を展開して返します。
@end itemize

マップ型プロトコルは、既存のレガシーな API の上に実装されているので、オリジナルのインターフェースを上書きする派生クラスもまたは期待どおりにはたらきます。

@node パーサーの振る舞いをカスタマイズする,レガシーな API の例,マップ型プロトコルアクセス,configparser --- 設定ファイルのパーサー
@anchor{library/configparser customizing-parser-behaviour}@anchor{2f71}
@subsubsection パーサーの振る舞いをカスタマイズする


There are nearly as many INI format variants as there are applications using it.
@code{configparser} goes a long way to provide support for the largest sensible
set of INI styles available.  The default functionality is mainly dictated by
historical background and it's very likely that you will want to customize some
of the features.

The most common way to change the way a specific config parser works is to use
the @code{__init__()} options:


@itemize *

@item 
`defaults', デフォルト値: @code{None}

このオプションは最初に @code{DEFAULT} セクションに加えられるキー-値の対の辞書を受け付けます。

Hint: if you want to specify default values for a specific section, use
@ref{2f7b,,read_dict()} before you read the actual file.

@item 
`dict_type', デフォルト値: @ref{183,,dict}

このオプションはマップ型プロトコルの振る舞い方や書き込まれる設定ファイルの見た目に大きく影響します。標準の辞書では、全てのセクションはパーサーに加えられた順に並びます。同じことがセクション内のオプションにも言えます。

セクションとオプションをライトバック時にソートするためなどに、別の辞書型も使えます。

注意: 一度の操作でキー-値の対を複数追加する方法もあります。そのような操作に普通の辞書を使うと、キーの並びは挿入順になります。例えば:

@example
>>> parser = configparser.ConfigParser()
>>> parser.read_dict(@{'section1': @{'key1': 'value1',
...                                'key2': 'value2',
...                                'key3': 'value3'@},
...                   'section2': @{'keyA': 'valueA',
...                                'keyB': 'valueB',
...                                'keyC': 'valueC'@},
...                   'section3': @{'foo': 'x',
...                                'bar': 'y',
...                                'baz': 'z'@}
... @})
>>> parser.sections()
['section1', 'section2', 'section3']
>>> [option for option in parser['section3']]
['foo', 'bar', 'baz']
@end example

@item 
`allow_no_value', デフォルト値: @code{False}

Some configuration files are known to include settings without values, but
which otherwise conform to the syntax supported by @code{configparser}.  The
`allow_no_value' parameter to the constructor can be used to
indicate that such values should be accepted:

@example
>>> import configparser

>>> sample_config = """
... [mysqld]
...   user = mysql
...   pid-file = /var/run/mysqld/mysqld.pid
...   skip-external-locking
...   old_passwords = 1
...   skip-bdb
...   # we don't need ACID today
...   skip-innodb
... """
>>> config = configparser.ConfigParser(allow_no_value=True)
>>> config.read_string(sample_config)

>>> # Settings with values are treated as before:
>>> config["mysqld"]["user"]
'mysql'

>>> # Settings without values provide None:
>>> config["mysqld"]["skip-bdb"]

>>> # Settings which aren't specified still raise an error:
>>> config["mysqld"]["does-not-exist"]
Traceback (most recent call last):
  ...
KeyError: 'does-not-exist'
@end example

@item 
`delimiters', デフォルト値: @code{('=', ':')}

デリミタはセクション内でキーを値から区切る部分文字列です。行中で最初に現れた区切り部分文字列がデリミタと見なされます。つまり値にはデリミタを含めることができます (キーには含めることができません)。

@ref{1de,,ConfigParser.write()} の `space_around_delimiters' 引数も参照してください。

@item 
`comment_prefixes', デフォルト値: @code{('#', ';')}

@item 
`inline_comment_prefixes', デフォルト値: @code{None}

コメント接頭辞は設定ファイル中で有効なコメントの開始を示す文字列です。`comment_prefixes' は他の内容がない行 (インデントは自由) にのみ使用でき、`inline_comment_prefixes' は任意の有効な値 (例えば、セクション名、オプション、空行も可能) の後に使えます。デフォルトではインラインコメントは無効化されていて、@code{'#'} と @code{';'} を行全体のコメントに使用します。


バージョン 3.2 で変更: In previous versions of @code{configparser} behaviour matched
@code{comment_prefixes=('#',';')} and @code{inline_comment_prefixes=(';',)}.


設定パーサーはコメント接頭辞のエスケープをサポートしないので、`inline_comment_prefixes' はユーザーがコメント接頭辞として使われる文字を含むオプション値を指定するのを妨げる可能性があります。疑わしい場合には、`inline_comment_prefixes' を設定しないようにしてください。どのような状況でも、複数行にわたる値で、行の先頭にコメント接頭辞文字を保存する唯一の方法は、次の例のように接頭辞を補間することです:

@example
>>> from configparser import ConfigParser, ExtendedInterpolation
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> # the default BasicInterpolation could be used as well
>>> parser.read_string("""
... [DEFAULT]
... hash = #
...
... [hashes]
... shebang =
...   $@{hash@}!/usr/bin/env python
...   $@{hash@} -*- coding: utf-8 -*-
...
... extensions =
...   enabled_extension
...   another_extension
...   #disabled_by_comment
...   yet_another_extension
...
... interpolation not necessary = if # is not at line start
... even in multiline values = line #1
...   line #2
...   line #3
... """)
>>> print(parser['hashes']['shebang'])

#!/usr/bin/env python
# -*- coding: utf-8 -*-
>>> print(parser['hashes']['extensions'])

enabled_extension
another_extension
yet_another_extension
>>> print(parser['hashes']['interpolation not necessary'])
if # is not at line start
>>> print(parser['hashes']['even in multiline values'])
line #1
line #2
line #3
@end example

@item 
`strict', デフォルト値: @code{True}

When set to @code{True}, the parser will not allow for any section or option
duplicates while reading from a single source (using @ref{72a,,read_file()},
@ref{2f7c,,read_string()} or @ref{2f7b,,read_dict()}).  It is recommended to use strict
parsers in new applications.


バージョン 3.2 で変更: In previous versions of @code{configparser} behaviour matched
@code{strict=False}.


@item 
`empty_lines_in_values', デフォルト値: @code{True}

設定パーサーでは、キーよりもその値を深くインデントするかぎり、複数行にまたがる値を使えます。デフォルトのパーサーはさらにその値の間に空行を置けます。同時に、キーは読みやすくするため任意にインデントできます。結果として、設定ファイルが大きく複雑になったとき、ユーザーがファイル構造を見失いやすいです。この例をご覧ください:

@example
[Section]
key = multiline
  value with a gotcha

 this = is still a part of the multiline value of 'key'
@end example

これは特にプロポーショナルフォントを使ってファイルを編集しているユーザーにとって問題になることがあります。だから、アプリケーションの値に空行が必要ないなら、空行を認めないべきです。これによって空行で必ずキーが分かれます。上の例では、2 つのキー、@code{key} および @code{this} が作られます。

@item 
`default_section', デフォルト値: @code{configparser.DEFAULTSECT} (すなわち: @code{"DEFAULT"})

他のセクションのデフォルト値や補間目的での特別なセクションを認める慣行はこのライブラリの明確なコンセプトの一つで、ユーザーは複雑で宣言的な設定を作成できます。このセクションは通常 @code{"DEFAULT"} と呼ばれますが、任意の有効なセクション名を指すようにカスタマイズできます。典型的な値には @code{"general"} や @code{"common"} があります。与えられた名前はソースを読み込む際にデフォルトセクションを認識するのに使われ、設定をファイルに書き戻すときにも使われます。現在の値は @code{parser_instance.default_section} 属性から取り出すことができ、実行時 (すなわちファイルを別のフォーマットに変換するとき) に変更することもできます。

@item 
`interpolation', デフォルト値: @code{configparser.BasicInterpolation}

補間の振る舞いは、 `interpolation' 引数を通してカスタムハンドラを与えることでカスタマイズできます。 @code{None} 引数を使うと補間を完全に無効にできます。 @code{ExtendedInterpolation()} は、 @code{zc.buildout} に影響を受けたより高度な補間を提供します。この話題に @ref{2f7a,,特化したドキュメントのセクション} をご覧ください。 @ref{1166,,RawConfigParser} のデフォルト値は @code{None} です。

@item 
`converters', デフォルト値: 未設定

Config parsers provide option value getters that perform type conversion.  By
default @ref{2f74,,getint()}, @ref{2f75,,getfloat()}, and
@ref{2f73,,getboolean()} are implemented.  Should other getters be
desirable, users may define them in a subclass or pass a dictionary where each
key is a name of the converter and each value is a callable implementing said
conversion.  For instance, passing @code{@{'decimal': decimal.Decimal@}} would add
@code{getdecimal()} on both the parser object and all section proxies.  In
other words, it will be possible to write both
@code{parser_instance.getdecimal('section', 'key', fallback=0)} and
@code{parser_instance['section'].getdecimal('key', 0)}.

コンバーターがパーサーの状態にアクセスする必要がある場合、設定パーサーサブクラスでメソッドとして実装することができます。このメソッドの名前が @code{get} から始まる場合、すべてのセクションプロキシで、辞書と互換性のある形式で利用できます (上記の @code{getdecimal()}  の例を参照)。
@end itemize

これらのパーサー引数のデフォルト値を上書きすれば、さらに進んだカスタマイズができます。デフォルトはクラスで定義されているので、派生クラスや属性の代入で上書きできます。

@geindex BOOLEAN_STATES (configparser.ConfigParser の属性)
@anchor{library/configparser configparser ConfigParser BOOLEAN_STATES}@anchor{2f7d}
@deffn {の属性} ConfigParser.BOOLEAN_STATES

デフォルトでは、 @ref{2f73,,getboolean()} を使うことで、設定パーサーは以下の値を @code{True} と見なします: @code{'1'}, @code{'yes'}, @code{'true'}, @code{'on'} 。以下の値を @code{False} と見なします: @code{'0'}, @code{'no'}, @code{'false'}, @code{'off'} 。文字列と対応するブール値のカスタム辞書を指定することでこれを上書きできます。たとえば:

@example
>>> custom = configparser.ConfigParser()
>>> custom['section1'] = @{'funky': 'nope'@}
>>> custom['section1'].getboolean('funky')
Traceback (most recent call last):
...
ValueError: Not a boolean: nope
>>> custom.BOOLEAN_STATES = @{'sure': True, 'nope': False@}
>>> custom['section1'].getboolean('funky')
False
@end example

ほかの典型的なブール値ペアには @code{accept}/@code{reject} や @code{enabled}/@code{disabled} などがあります。
@end deffn


@deffn {メソッド} ConfigParser.optionxform (option)

このメソッドは読み込み、取得、設定操作のたびにオプション名を変換します。デフォルトでは名前を小文字に変換します。従って設定ファイルが書き込まれるとき、すべてのキーは小文字になります。それがふさわしくなければ、このメソッドを上書きしてください。例えば:

@example
>>> config = """
... [Section1]
... Key = Value
...
... [Section2]
... AnotherKey = Value
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> list(typical['Section1'].keys())
['key']
>>> list(typical['Section2'].keys())
['anotherkey']
>>> custom = configparser.RawConfigParser()
>>> custom.optionxform = lambda option: option
>>> custom.read_string(config)
>>> list(custom['Section1'].keys())
['Key']
>>> list(custom['Section2'].keys())
['AnotherKey']
@end example

@cartouche
@quotation 注釈 
The optionxform function transforms option names to a canonical form.
This should be an idempotent function: if the name is already in
canonical form, it should be returned unchanged.
@end quotation
@end cartouche
@end deffn

@geindex SECTCRE (configparser.ConfigParser の属性)
@anchor{library/configparser configparser ConfigParser SECTCRE}@anchor{2f77}
@deffn {の属性} ConfigParser.SECTCRE

セクションヘッダを解析するのに使われる、コンパイルされた正規表現です。デフォルトでは @code{[section]} が @code{"section"} という名前にマッチします。空白はセクション名の一部と見なされるので、@code{[  larch  ]} は @code{"  larch  "} という名のセクションとして読み込まれます。これがふさわしくない場合、このメソッドを上書きしてください。例えば:

@example
>>> import re
>>> config = """
... [Section 1]
... option = value
...
... [  Section 2  ]
... another = val
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> typical.sections()
['Section 1', '  Section 2  ']
>>> custom = configparser.ConfigParser()
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
>>> custom.read_string(config)
>>> custom.sections()
['Section 1', 'Section 2']
@end example

@cartouche
@quotation 注釈 
ConfigParser オブジェクトはオプション行の認識に @code{OPTCRE} 属性も使いますが、これを上書きすることは推奨されません。上書きするとコンストラクタオプション `allow_no_value' および `delimiters' に干渉します。
@end quotation
@end cartouche
@end deffn

@node レガシーな API の例,ConfigParser オブジェクト,パーサーの振る舞いをカスタマイズする,configparser --- 設定ファイルのパーサー
@anchor{library/configparser legacy-api-examples}@anchor{2f7e}
@subsubsection レガシーな API の例


Mainly because of backwards compatibility concerns, @code{configparser}
provides also a legacy API with explicit @code{get}/@code{set} methods.  While there
are valid use cases for the methods outlined below, mapping protocol access is
preferred for new projects.  The legacy API is at times more advanced,
low-level and downright counterintuitive.

設定ファイルを書き出す例:

@example
import configparser

config = configparser.RawConfigParser()

# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
    config.write(configfile)
@end example

設定ファイルを読み込む例:

@example
import configparser

config = configparser.RawConfigParser()
config.read('example.cfg')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)

# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
    print(config.get('Section1', 'foo'))
@end example

補間するには、 @ref{4de,,ConfigParser} を使ってください:

@example
import configparser

cfg = configparser.ConfigParser()
cfg.read('example.cfg')

# Set the optional *raw* argument of get() to True if you wish to disable
# interpolation in a single get operation.
print(cfg.get('Section1', 'foo', raw=False))  # -> "Python is fun!"
print(cfg.get('Section1', 'foo', raw=True))   # -> "%(bar)s is %(baz)s!"

# The optional *vars* argument is a dict with members that will take
# precedence in interpolation.
print(cfg.get('Section1', 'foo', vars=@{'bar': 'Documentation',
                                       'baz': 'evil'@}))

# The optional *fallback* argument can be used to provide a fallback value
print(cfg.get('Section1', 'foo'))
      # -> "Python is fun!"

print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
      # -> "Python is fun!"

print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
      # -> "No such things as monsters."

# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
# but we can also use:

print(cfg.get('Section1', 'monster', fallback=None))
      # -> None
@end example

どちらの型の ConfigParsers でもデフォルト値が利用できます。使われているオプションがどこにも定義されていなければ、そのデフォルト値が補間に使われます。

@example
import configparser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser(@{'bar': 'Life', 'baz': 'hard'@})
config.read('example.cfg')

print(config.get('Section1', 'foo'))     # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo'))     # -> "Life is hard!"
@end example

@node ConfigParser オブジェクト,RawConfigParser オブジェクト,レガシーな API の例,configparser --- 設定ファイルのパーサー
@anchor{library/configparser configparser-objects}@anchor{2f7f}@anchor{library/configparser id13}@anchor{2f80}
@subsubsection ConfigParser オブジェクト


@geindex ConfigParser (configparser のクラス)
@anchor{library/configparser configparser ConfigParser}@anchor{4de}
@deffn {クラス} configparser.ConfigParser (defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters=@{@}, allow_unnamed_section=False)

主要な設定パーサーです。`defaults' が与えられれば、その辞書の持つ初期値で初期化されます。`dict_type' が与えられれば、それがセクションの一覧、セクション中のオプション、およびデフォルト値の辞書オブジェクトを作成するのに使われます。

`delimiters' が与えられた場合、キーと値を分割する部分文字列の組み合わせとして使われます。`comment_prefixes' が与えられた場合、他の内容がない行のコメントに接頭する部分文字列の組み合わせとして使われます。コメントはインデントできます。`inline_comment_prefixes' が与えられた場合、非空行のコメントに接頭する部分文字列としての組み合わせとして使われます。

`strict' が @code{True} (デフォルト) であれば、パーサーは単一のソース (ファイル、文字列、辞書) 中にセクションやオプションの重複を認めず、 @ref{1486,,DuplicateSectionError} や @ref{1487,,DuplicateOptionError} を送出します。 `empty_lines_in_values' が @code{False} (デフォルト: @code{True}) なら、空行はそれぞれオプションの終わりを示します。 `allow_no_value' が @code{True} (デフォルト: @code{False}) なら、値のないオプションが受け付けられます。そのオプションの値は @code{None} となり、後端のデリミタを除いてシリアル化されます。

When `default_section' is given, it specifies the name for the special
section holding default values for other sections and interpolation purposes
(normally named @code{"DEFAULT"}).  This value can be retrieved and changed at
runtime using the @code{default_section} instance attribute. This won't
re-evaluate an already parsed config file, but will be used when writing
parsed settings to a new config file.

補間の動作は、 `interpolation' 引数を通してカスタムハンドラを与えることでカスタマイズできます。 @code{None} 引数を使うと補間を完全に無効にできます。 @code{ExtendedInterpolation()} は、 @code{zc.buildout} に影響を受けたより高度な補間を提供します。この件に @ref{2f7a,,特化したドキュメントのセクション} を参照してください。

補間に使われるすべてのオプション名は、他のオプション名参照と同様に、 @ref{2f81,,optionxform()} メソッドを通して渡されます。例えば、 @ref{2f81,,optionxform()} のデフォルトの実装を使うと、値 @code{foo %(bar)s} と @code{foo %(BAR)s} は等しくなります。

When `converters' is given, it should be a dictionary where each key
represents the name of a type converter and each value is a callable
implementing the conversion from string to the desired datatype.  Every
converter gets its own corresponding @code{get*()} method on the parser
object and section proxies.

When `allow_unnamed_section' is @code{True} (default: @code{False}),
the first section name can be omitted. See the
@ref{2f79,,"Unnamed Sections" section}.

It is possible to read several configurations into a single
@ref{4de,,ConfigParser}, where the most recently added configuration has the
highest priority. Any conflicting keys are taken from the more recent
configuration while the previously existing keys are retained. The example
below reads in an @code{override.ini} file, which will override any conflicting
keys from the @code{example.ini} file.

@example
[DEFAULT]
ServerAliveInterval = -1
@end example

@example
>>> config_override = configparser.ConfigParser()
>>> config_override['DEFAULT'] = @{'ServerAliveInterval': '-1'@}
>>> with open('override.ini', 'w') as configfile:
...     config_override.write(configfile)
...
>>> config_override = configparser.ConfigParser()
>>> config_override.read(['example.ini', 'override.ini'])
['example.ini', 'override.ini']
>>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))
-1
@end example


バージョン 3.1 で変更: デフォルトの `dict_type' は @ref{7f3,,collections.OrderedDict} です。



バージョン 3.2 で変更: `allow_no_value', `delimiters', `comment_prefixes', `strict', `empty_lines_in_values', `default_section' および `interpolation' が追加されました。



バージョン 3.5 で変更: `converters' 引数が追加されました。



バージョン 3.7 で変更: The `defaults' argument is read with @ref{2f7b,,read_dict()},
providing consistent behavior across the parser: non-string
keys and values are implicitly converted to strings.



バージョン 3.8 で変更: The default `dict_type' is @ref{183,,dict}, since it now preserves
insertion order.



バージョン 3.13 で変更: Raise a @ref{2f82,,MultilineContinuationError} when `allow_no_value' is
@code{True}, and a key without a value is continued with an indented line.



バージョン 3.13 で変更: The `allow_unnamed_section' argument was added.


@geindex defaults() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser defaults}@anchor{2f83}
@deffn {メソッド} defaults ()

インスタンス全体で使われるデフォルト値の辞書を返します。
@end deffn

@geindex sections() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser sections}@anchor{2f84}
@deffn {メソッド} sections ()

利用できるセクションのリストを返します。`default section' はリストに含まれません。
@end deffn

@geindex add_section() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser add_section}@anchor{1485}
@deffn {メソッド} add_section (section)

`section' という名のセクションをインスタンスに追加します。与えられた名前のセクション名がすでに存在したら、 @ref{1486,,DuplicateSectionError} が送出されます。 `default section' 名が渡されたら、 @ref{2ec,,ValueError} が送出されます。セクションの名前は文字列でなければなりません。そうでなければ、 @ref{198,,TypeError} が送出されます。


バージョン 3.2 で変更: 文字列でないセクション名は @ref{198,,TypeError} を送出します。

@end deffn

@geindex has_section() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser has_section}@anchor{2f85}
@deffn {メソッド} has_section (section)

指名された `section' が設定中に存在するかを示します。`default section' は認識されません。
@end deffn

@geindex options() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser options}@anchor{2f86}
@deffn {メソッド} options (section)

指定された `section' 中で利用できるオプションのリストを返します。
@end deffn

@geindex has_option() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser has_option}@anchor{2f87}
@deffn {メソッド} has_option (section, option)

与えられた `section' が存在し、与えられた `option' を含む場合、 @ref{e07,,True} を返します。それ以外の場合には、 @ref{d2b,,False} を返します。指定された `section' が @ref{885,,None} または空文字列の場合、 DEFAULT が仮定されます。
@end deffn

@geindex read() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser read}@anchor{1681}
@deffn {メソッド} read (filenames, encoding=None)

ファイル名の iterable を読み込んでパースしようと試みます。正常にパースできたファイル名のリストを返します。

もし `filenames' が文字列か @ref{192,,bytes} オブジェクトか @ref{5a1,,path-like object} なら、この引数は1つのファイル名として扱われます。 `filenames' 中に開けないファイルがある場合、そのファイルは無視されます。この挙動は、設定ファイルが置かれる可能性のある場所(例えば、 カレントディレクトリ、ホームディレクトリ、システム全体の設定を行うディレクトリ)のイテラブルを指定して、イテラブルの中で存在する全ての設定ファイルを読むことを想定して設計されています。

どの設定ファイルも存在しなかった場合、 @ref{4de,,ConfigParser} のインスタンスは 空のデータセットを持ちます。初期値の設定ファイルを先に読み込んでおく必要があるアプリケーションでは、 オプションのファイルを読み込むために @ref{1681,,read()} を呼ぶ前に 、まず @ref{72a,,read_file()} を用いて必要なファイルを読み込んでください:

@example
import configparser, os

config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
            encoding='cp1250')
@end example


バージョン 3.2 で変更: Added the `encoding' parameter.
Previously, all files were read using the default encoding for @ref{316,,open()}.



バージョン 3.6.1 で変更: `filenames' 引数が @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.7 で変更: `filenames' 引数が @ref{192,,bytes} オブジェクトを受け入れるようになりました。

@end deffn

@geindex read_file() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser read_file}@anchor{72a}
@deffn {メソッド} read_file (f, source=None)

設定データを `f' から読み込んで解析します。`f' は Unicode 文字列を yield するイテラブル (例えばテキストモードで開かれたファイル) です。

Optional argument `source' specifies the name of the file being read.  If
not given and `f' has a @code{name} attribute, that is used for
`source'; the default is @code{'<???>'}.


Added in version 3.2: @code{readfp()} を置き換えます。

@end deffn

@geindex read_string() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser read_string}@anchor{2f7c}
@deffn {メソッド} read_string (string, source='<string>')

設定データを文字列から解析します。

オプションの引数 `source' はコンテキストにおける渡された文字列の名前を指定します。与えられなければ、@code{'<string>'} が使われます。これは一般にファイルシステムパスや URL にします。


Added in version 3.2.

@end deffn

@geindex read_dict() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser read_dict}@anchor{2f7b}
@deffn {メソッド} read_dict (dictionary, source='<dict>')

辞書的な @code{items()} メソッドを提供する任意のオブジェクトから設定を読み込みます。キーはセクション名で、値はそのセクションに現れるキーと値をもつ辞書です。使われた辞書型が順序を保存するなら、セクションおよびそのキーは順に加えられます。値は自動で文字列に変換されます。

オプションの引数 `source' はコンテキストにおける渡された辞書の名前を指定します。与えられなければ、@code{<dict>} が使われます。

このメソッドを使ってパーサー間で状態をコピーできます。


Added in version 3.2.

@end deffn

@geindex get() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser get}@anchor{1483}
@deffn {メソッド} get (section, option, *, raw=False, vars=None[, fallback])

指名された `section' の `option' の値を取得します。`vars' が提供されるなら、それは辞書でなければならず、(与えられたなら) `vars', `section', `DEFAULTSECT' 内からこの順で `option' が探索されます。`fallback' の値として @code{None} を与えられます。

`raw' が真でない時には、全ての @code{'%'} 置換は展開されてから返されます。置換後の値はオプションと同じ順序で探されます。


バージョン 3.2 で変更: 引数 `raw', `vars' および `fallback' は、(特にマッピングプロトコルを使用するときに) ユーザーが第 3 引数を `fallback' フォールバックとして使おうとしないように、キーワード専用となりました。

@end deffn

@geindex getint() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser getint}@anchor{2f74}
@deffn {メソッド} getint (section, option, *, raw=False, vars=None[, fallback])

指定された `section' 中の `option' を整数に型強制する補助メソッドです。 `raw', `vars' および `fallback' の説明は @ref{1483,,get()} を参照してください。
@end deffn

@geindex getfloat() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser getfloat}@anchor{2f75}
@deffn {メソッド} getfloat (section, option, *, raw=False, vars=None[, fallback])

A convenience method which coerces the `option' in the specified `section'
to a floating-point number.  See @ref{1483,,get()} for explanation of `raw',
`vars' and `fallback'.
@end deffn

@geindex getboolean() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser getboolean}@anchor{2f73}
@deffn {メソッド} getboolean (section, option, *, raw=False, vars=None[, fallback])

指定された `section' 中の `option' をブール値に型強制する補助メソッドです。なお、このオプションで受け付けられる値はこのメソッドが @code{True} を返す @code{'1'}, @code{'yes'}, @code{'true'}, および @code{'on'},と、このメソッドが @code{False} を返す @code{'0'}, @code{'no'}, @code{'false'}, and @code{'off'} です。その他のいかなる値も @ref{2ec,,ValueError} を送出します。 `raw', `vars' および `fallback' の説明は @ref{1483,,get()} を参照してください。
@end deffn

@geindex items() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser items}@anchor{2f88}
@deffn {メソッド} items (raw=False, vars=None)

@deffnx {メソッド} items (section, raw=False, vars=None)

`section' が与えられなければ、DEFAULTSECT を含めた `section_name', `section_proxy' の対のリストを返します。

与えられれば、与えられた `section' 中のオプションの `name', `value' の対のリストを返します。オプションの引数は @ref{1483,,get()} メソッドに与えるものと同じ意味を持ちます。


バージョン 3.8 で変更: `vars' に現れる項目は結果に表れなくなりました。以前の挙動は、実際のパーサーオプションを補間のために与えられた変数と混合していました。

@end deffn

@geindex set() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser set}@anchor{1484}
@deffn {メソッド} set (section, option, value)

与えられたセクションが存在すれば、与えられたオプションを指定された値に設定します。そうでなければ @ref{2f89,,NoSectionError} を送出します。 `option' および `value' は文字列でなければなりません。そうでなければ @ref{198,,TypeError} が送出されます。
@end deffn

@geindex write() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser write}@anchor{1de}
@deffn {メソッド} write (fileobject, space_around_delimiters=True)

設定の表現を指定された @ref{13db,,file object} に書き込みます。 `fileobject' は (文字列を受け付ける) テキストモードで開かれていなければなりません。この表現は後で @ref{1681,,read()} を呼び出すことでパースできます。 `space_around_delimiters' が真なら、キーと値の間のデリミタはスペースで囲まれます。


バージョン 3.14 で変更: Raises InvalidWriteError if this would write a representation which cannot
be accurately parsed by a future @ref{1681,,read()} call from this parser.

@end deffn

@cartouche
@quotation 注釈 
Comments in the original configuration file are not preserved when
writing the configuration back.
What is considered a comment, depends on the given values for
`comment_prefix' and `inline_comment_prefix'.
@end quotation
@end cartouche

@geindex remove_option() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser remove_option}@anchor{2f8a}
@deffn {メソッド} remove_option (section, option)

指定された `option' を指定された `section' から削除します。セクションが存在しなければ、 @ref{2f89,,NoSectionError} を送出します。オプションが存在して削除されれば、 @ref{e07,,True} を返します。そうでなければ @ref{d2b,,False} を返します。
@end deffn

@geindex remove_section() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser remove_section}@anchor{2f8b}
@deffn {メソッド} remove_section (section)

指定された `section' を設定から削除します。セクションが実際に存在すれば、@code{True} を返します。そうでなければ @code{False} を返します。
@end deffn

@geindex optionxform() (configparser.ConfigParser のメソッド)
@anchor{library/configparser configparser ConfigParser optionxform}@anchor{2f81}
@deffn {メソッド} optionxform (option)

入力ファイルに現れた、またはクライアントコードで渡されたオプション名 `option' を内部構造で実際に使われる形式に変換します。デフォルトの実装では `option' の小文字版を返します。派生クラスでこれを上書きするか、クライアントコードでインスタンス上のこの名前の属性を設定して、この動作に影響を与えることができます。

このメソッドを使うためにパーサーを派生クラス化させる必要はなく、インスタンス上で、これを文字列引数をとって文字列を返す関数に設定できます。例えば、これを @code{str} に設定すると、オプション名に大文字小文字の区別をつけられます:

@example
cfgparser = ConfigParser()
cfgparser.optionxform = str
@end example

なお、設定ファイルを読み込むとき、オプション名の周りの空白は @ref{2f81,,optionxform()} が呼び出される前に取り除かれます。
@end deffn
@end deffn

@geindex UNNAMED_SECTION (configparser モジュール)
@anchor{library/configparser configparser UNNAMED_SECTION}@anchor{178a}
@deffn {データ} configparser.UNNAMED_SECTION

A special object representing a section name used to reference the unnamed section (see @ref{2f79,,Unnamed Sections}).
@end deffn

@geindex MAX_INTERPOLATION_DEPTH (configparser モジュール)
@anchor{library/configparser configparser MAX_INTERPOLATION_DEPTH}@anchor{2f8c}
@deffn {データ} configparser.MAX_INTERPOLATION_DEPTH

The maximum depth for recursive interpolation for @ref{1483,,get()} when the `raw'
parameter is false.  This is relevant only when the default `interpolation'
is used.
@end deffn

@node RawConfigParser オブジェクト,例外<9>,ConfigParser オブジェクト,configparser --- 設定ファイルのパーサー
@anchor{library/configparser id15}@anchor{2f8d}@anchor{library/configparser rawconfigparser-objects}@anchor{2f8e}
@subsubsection RawConfigParser オブジェクト


@geindex RawConfigParser (configparser のクラス)
@anchor{library/configparser configparser RawConfigParser}@anchor{1166}
@deffn {クラス} configparser.RawConfigParser (defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters=@{@}, allow_unnamed_section=False)

Legacy variant of the @ref{4de,,ConfigParser}.  It has interpolation
disabled by default and allows for non-string section names, option
names, and values via its unsafe @code{add_section} and @code{set} methods,
as well as the legacy @code{defaults=} keyword argument handling.


バージョン 3.2 で変更: `allow_no_value', `delimiters', `comment_prefixes', `strict', `empty_lines_in_values', `default_section' および `interpolation' が追加されました。



バージョン 3.5 で変更: `converters' 引数が追加されました。



バージョン 3.8 で変更: The default `dict_type' is @ref{183,,dict}, since it now preserves
insertion order.



バージョン 3.13 で変更: The `allow_unnamed_section' argument was added.


@cartouche
@quotation 注釈 
代わりに内部に保存する値の型を検査する @ref{4de,,ConfigParser} を使うことを検討してください。補間を望まない場合、  @code{ConfigParser(interpolation=None)} を使用できます。
@end quotation
@end cartouche

@geindex add_section() (configparser.RawConfigParser のメソッド)
@anchor{library/configparser configparser RawConfigParser add_section}@anchor{2f8f}
@deffn {メソッド} add_section (section)

Add a section named `section' or @ref{178a,,UNNAMED_SECTION} to the instance.

If the given section already exists, @ref{1486,,DuplicateSectionError} is
raised. If the `default section' name is passed, @ref{2ec,,ValueError} is
raised. If @ref{178a,,UNNAMED_SECTION} is passed and support is disabled,
@ref{2f90,,UnnamedSectionDisabledError} is raised.

`section' の型は検査されないため、ユーザーは非文字列の名前付きセクションを作ることができます。この振る舞いはサポートされておらず、内部エラーを起こす可能性があります。
@end deffn


バージョン 3.14 で変更: Added support for @ref{178a,,UNNAMED_SECTION}.


@geindex set() (configparser.RawConfigParser のメソッド)
@anchor{library/configparser configparser RawConfigParser set}@anchor{2f91}
@deffn {メソッド} set (section, option, value)

与えられたセクションが存在していれば、オプションを指定された値に設定します。セクションが存在しなければ @ref{2f89,,NoSectionError} を発生させます。 @ref{1166,,RawConfigParser} (あるいは `raw' パラメータをセットした @ref{4de,,ConfigParser}) を文字列型でない値の `内部的な' 格納場所として使うことは可能ですが、すべての機能 (置換やファイルへの出力を含む) がサポートされるのは文字列を値として使った場合だけです。

ユーザーは、このメソッドを使って非文字列の値をキーに代入できます。この振る舞いはサポートされておらず、非rawモードでの値の取得や、ファイルへの書き出しを試みた際にエラーの原因となりえます。このような代入を許さない  `マッピングプロトコルAPIを使用してください'。
@end deffn
@end deffn

@node 例外<9>,,RawConfigParser オブジェクト,configparser --- 設定ファイルのパーサー
@anchor{library/configparser exceptions}@anchor{2f92}
@subsubsection 例外


@geindex Error
@anchor{library/configparser configparser Error}@anchor{2f93}
@deffn {例外} configparser.Error

Base class for all other @code{configparser} exceptions.
@end deffn

@geindex NoSectionError
@anchor{library/configparser configparser NoSectionError}@anchor{2f89}
@deffn {例外} configparser.NoSectionError

指定したセクションが見つからなかった時に起きる例外です。
@end deffn

@geindex DuplicateSectionError
@anchor{library/configparser configparser DuplicateSectionError}@anchor{1486}
@deffn {例外} configparser.DuplicateSectionError

Exception raised if @ref{1485,,add_section()} is called with the name of a section
that is already present or in strict parsers when a section if found more
than once in a single input file, string or dictionary.


バージョン 3.2 で変更: Added the optional `source' and `lineno' attributes and parameters to
@code{__init__()}.

@end deffn

@geindex DuplicateOptionError
@anchor{library/configparser configparser DuplicateOptionError}@anchor{1487}
@deffn {例外} configparser.DuplicateOptionError

strict なパーサーで、単一の入力ファイル、文字列、辞書中に同じオプションが複数回現れたときに送出される例外です。これはミススペルや大文字小文字の区別に関係するエラー、例えば辞書の二つのキーが同じ大文字小文字の区別のない設定キーを表すこと、を捕捉します。
@end deffn

@geindex NoOptionError
@anchor{library/configparser configparser NoOptionError}@anchor{2f94}
@deffn {例外} configparser.NoOptionError

指定されたオプションが指定されたセクションに見つからないときに送出される例外です。
@end deffn

@geindex InterpolationError
@anchor{library/configparser configparser InterpolationError}@anchor{2f95}
@deffn {例外} configparser.InterpolationError

文字列の補間中に問題が起きた時に発生する例外の基底クラスです。
@end deffn

@geindex InterpolationDepthError
@anchor{library/configparser configparser InterpolationDepthError}@anchor{2f96}
@deffn {例外} configparser.InterpolationDepthError

繰り返しの回数が @ref{2f8c,,MAX_INTERPOLATION_DEPTH} を超えたために文字列補間が完了しなかったときに送出される例外です。 @ref{2f95,,InterpolationError} の派生クラスです。
@end deffn

@geindex InterpolationMissingOptionError
@anchor{library/configparser configparser InterpolationMissingOptionError}@anchor{2f97}
@deffn {例外} configparser.InterpolationMissingOptionError

@ref{2f95,,InterpolationError} の派生クラスで、値が参照しているオプションが見つからない場合に発生する例外です。
@end deffn

@geindex InterpolationSyntaxError
@anchor{library/configparser configparser InterpolationSyntaxError}@anchor{2f98}
@deffn {例外} configparser.InterpolationSyntaxError

置換がなされるソーステキストが要求された文法を満たさないときに送出される例外です。 @ref{2f95,,InterpolationError} の派生クラスです。
@end deffn

@geindex MissingSectionHeaderError
@anchor{library/configparser configparser MissingSectionHeaderError}@anchor{2f99}
@deffn {例外} configparser.MissingSectionHeaderError

セクションヘッダを持たないファイルを構文解析しようとした時に起きる例外です。
@end deffn

@geindex ParsingError
@anchor{library/configparser configparser ParsingError}@anchor{729}
@deffn {例外} configparser.ParsingError

ファイルの構文解析中にエラーが起きた場合に発生する例外です。


バージョン 3.12 で変更: The @code{filename} attribute and @code{__init__()} constructor argument were
removed.  They have been available using the name @code{source} since 3.2.

@end deffn

@geindex MultilineContinuationError
@anchor{library/configparser configparser MultilineContinuationError}@anchor{2f82}
@deffn {例外} configparser.MultilineContinuationError

Exception raised when a key without a corresponding value is continued with
an indented line.


Added in version 3.13.

@end deffn

@geindex UnnamedSectionDisabledError
@anchor{library/configparser configparser UnnamedSectionDisabledError}@anchor{2f90}
@deffn {例外} configparser.UnnamedSectionDisabledError

Exception raised when attempting to use the
@ref{178a,,UNNAMED_SECTION} without enabling it.

@quotation


Added in version 3.14.

@end quotation
@end deffn

@geindex InvalidWriteError
@anchor{library/configparser configparser InvalidWriteError}@anchor{1df}
@deffn {例外} configparser.InvalidWriteError

Exception raised when an attempted @ref{1de,,ConfigParser.write()} would not be parsed
accurately with a future @ref{1681,,ConfigParser.read()} call.

Ex: Writing a key beginning with the @ref{2f77,,ConfigParser.SECTCRE} pattern
would parse as a section header when read. Attempting to write this will raise
this exception.


Added in version 3.14.

@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tomllib --- TOML ファイルの解析,netrc --- netrc ファイルの処理,configparser --- 設定ファイルのパーサー,ファイルフォーマット
@anchor{library/tomllib doc}@anchor{2f9a}@anchor{library/tomllib module-tomllib}@anchor{102}@anchor{library/tomllib tomllib-parse-toml-files}@anchor{2f9b}@anchor{library/tomllib translation-repo}@anchor{2f9c}
@subsection @code{tomllib} --- TOML ファイルの解析


@geindex module; tomllib


Added in version 3.11.


`ソースコード:' Lib/tomllib@footnote{https://github.com/python/cpython/tree/3.14/Lib/tomllib}


__________________________________________________________________


このモジュールはTOML 1.0.0（Tom's Obvious Minimal Language, https://toml.io@footnote{https://toml.io/en/}）を解析するインターフェースを提供します。このモジュールはTOMLの書き出しはサポートしません。


@subsubheading 参考


Tomli-W パッケージ@footnote{https://pypi.org/project/tomli-w/} はTOMLの書き込み用にこのモジュールと組み合わせて使用でき、標準ライブラリの @ref{91,,marshal} や @ref{ab,,pickle} モジュールなどでユーザーによく知られている書き込みAPIを提供します。



@subsubheading 参考


TOML Kit パッケージ@footnote{https://pypi.org/project/tomlkit/} は、スタイルを保持した読み書きに対応したTOMLライブラリです。存在するTOMLファイルを編集するときにこのモジュールの代わりに使用することを推奨します。


このモジュールは以下の関数を定義しています:

@geindex load() (tomllib モジュール)
@anchor{library/tomllib tomllib load}@anchor{2f9d}
@deffn {の関数} tomllib.load (fp, /, *, parse_float=float)

TOMLファイルを読み込みます。第1引数には読み込み可能なバイナリのファイルオブジェクトを指定します。戻り値は @ref{183,,dict} です。TOMLの型は @ref{2f9e,,conversion table} を使用してPythonのデータ型に変換されます。

`parse_float' は、全てのデコードされる TOML の浮動小数点数文字列に対して呼ばれます。デフォルトでは、 @code{float(num_str)} と等価です。これは TOML 浮動小数点数に対して他のデータ型やパーサ (たとえば @ref{1fe,,decimal.Decimal}) を使うのに使えます。呼び出し可能オブジェクトは @ref{183,,dict} や @ref{24d,,list} 以外を返す必要があり、そうでない場合は @ref{2ec,,ValueError} が送出されます。

無効なTOMLドキュメントの場合は @ref{190d,,TOMLDecodeError} が送出されます。
@end deffn

@geindex loads() (tomllib モジュール)
@anchor{library/tomllib tomllib loads}@anchor{192c}
@deffn {の関数} tomllib.loads (s, /, *, parse_float=float)

@ref{169,,str} からTOMLを読み込みます。戻り値は @ref{183,,dict} です。TOMLの型は @ref{2f9e,,conversion table} を使用してPythonのデータ型に変換されます。`parse_float'  引数は @ref{2f9d,,load()} と同じ意味を持ちます。

無効なTOMLドキュメントの場合は @ref{190d,,TOMLDecodeError} が送出されます。
@end deffn

次の例外がサポートされています:

@geindex TOMLDecodeError
@anchor{library/tomllib tomllib TOMLDecodeError}@anchor{190d}
@deffn {例外} tomllib.TOMLDecodeError (msg, doc, pos)

@ref{2ec,,ValueError} のサブクラスで、以下の追加の属性を持ちます:

@geindex msg (tomllib.TOMLDecodeError の属性)
@anchor{library/tomllib tomllib TOMLDecodeError msg}@anchor{2f9f}
@deffn {の属性} msg

フォーマットされていないエラーメッセージです。
@end deffn

@geindex doc (tomllib.TOMLDecodeError の属性)
@anchor{library/tomllib tomllib TOMLDecodeError doc}@anchor{2fa0}
@deffn {の属性} doc

パース対象の TOML ドキュメントです。
@end deffn

@geindex pos (tomllib.TOMLDecodeError の属性)
@anchor{library/tomllib tomllib TOMLDecodeError pos}@anchor{2fa1}
@deffn {の属性} pos

`doc' の解析に失敗したインデクスです。
@end deffn

@geindex lineno (tomllib.TOMLDecodeError の属性)
@anchor{library/tomllib tomllib TOMLDecodeError lineno}@anchor{2fa2}
@deffn {の属性} lineno

`pos' に対応する行です。
@end deffn

@geindex colno (tomllib.TOMLDecodeError の属性)
@anchor{library/tomllib tomllib TOMLDecodeError colno}@anchor{2fa3}
@deffn {の属性} colno

`pos' に対応する列です。
@end deffn


バージョン 3.14 で変更: Added the `msg', `doc' and `pos' parameters.
Added the @ref{2f9f,,msg}, @ref{2fa0,,doc}, @ref{2fa1,,pos}, @ref{2fa2,,lineno} and @ref{2fa3,,colno} attributes.



バージョン 3.14 で非推奨: Passing free-form positional arguments is deprecated.

@end deffn

@menu
* 使用例: 使用例<18>. 
* 変換表:: 

@end menu

@node 使用例<18>,変換表,,tomllib --- TOML ファイルの解析
@anchor{library/tomllib examples}@anchor{2fa4}
@subsubsection 使用例


TOMLファイルを解析します:

@example
import tomllib

with open("pyproject.toml", "rb") as f:
    data = tomllib.load(f)
@end example

TOMLの文字列を解析します:

@example
import tomllib

toml_str = """
python-version = "3.11.0"
python-implementation = "CPython"
"""

data = tomllib.loads(toml_str)
@end example

@node 変換表,,使用例<18>,tomllib --- TOML ファイルの解析
@anchor{library/tomllib conversion-table}@anchor{2fa5}
@subsubsection 変換表

@anchor{library/tomllib toml-to-py-table}@anchor{2f9e}

@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

TOML

@tab

Python

@item

TOMLドキュメント

@tab

辞書

@item

文字列

@tab

文字列

@item

整数

@tab

整数

@item

浮動小数点数

@tab

浮動小数点数（`parse_float' で設定可能）

@item

ブール値

@tab

真偽値型(bool)

@item

オフセット付きの日時

@tab

datetime.datetime（@code{tzinfo} 属性は @code{datetime.timezone} のインスタンスが設定される）

@item

ローカルの日時

@tab

datetime.datetime（@code{tzinfo} 属性は @code{None} に設定される）

@item

ローカルの日付

@tab

datetime.date

@item

ローカルの時刻

@tab

datetime.time

@item

配列

@tab

リスト

@item

テーブル

@tab

辞書

@item

インラインテーブル

@tab

辞書

@item

テーブルの配列

@tab

辞書のリスト

@end multitable


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node netrc --- netrc ファイルの処理,plistlib --- Apple plist ファイルを生成・解析する,tomllib --- TOML ファイルの解析,ファイルフォーマット
@anchor{library/netrc doc}@anchor{2fa6}@anchor{library/netrc module-netrc}@anchor{9f}@anchor{library/netrc netrc-netrc-file-processing}@anchor{2fa7}@anchor{library/netrc translation-repo}@anchor{2fa8}
@subsection @code{netrc} --- netrc ファイルの処理


@geindex module; netrc

`ソースコード:' Lib/netrc.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/netrc.py}


__________________________________________________________________


@ref{1c79,,netrc} クラスは、Unix @code{ftp} プログラムや他の FTP クライアントで用いられる netrc ファイル形式を解析し、カプセル化 (encapsulate) します。

@geindex netrc (netrc のクラス)
@anchor{library/netrc netrc netrc}@anchor{1c79}
@deffn {クラス} netrc.netrc ([file])

A @ref{1c79,,netrc} instance or subclass instance encapsulates data from  a netrc
file.  The initialization argument, if present, specifies the file to parse.  If
no argument is given, the file @code{.netrc} in the user's home directory --
as determined by @ref{c09,,os.path.expanduser()} -- will be read.  Otherwise,
a @ref{264,,FileNotFoundError} exception will be raised.
Parse errors will raise @ref{2fa9,,NetrcParseError} with diagnostic
information including the file name, line number, and terminating token.

If no argument is specified on a POSIX system, the presence of passwords in
the @code{.netrc} file will raise a @ref{2fa9,,NetrcParseError} if the file
ownership or permissions are insecure (owned by a user other than the user
running the process, or accessible for read or write by any other user).
This implements security behavior equivalent to that of ftp and other
programs that use @code{.netrc}. Such security checks are not available
on platforms that do not support @ref{1817,,os.getuid()}.


バージョン 3.4 で変更: POSIX パーミッションのチェックが追加されました。



バージョン 3.7 で変更: 引数で `file' が渡されなかったときは、 @code{.netrc} ファイルの場所を探すのに @ref{c09,,os.path.expanduser()} が使われるようになりました。



バージョン 3.10 で変更: @ref{9f,,netrc} は、ロケール固有のエンコーディングを使用する前に、 UTF-8 でのエンコーディングを試みます。 netrc ファイルのエントリがすべてのトークンを含む必要はなくなりました。欠落したトークンのデフォルト値は空文字列です。すべてのトークンとその値は空白や非 ASCII 文字のような任意の文字を使用できるようになりました。ログイン名が匿名の場合、セキュリティチェックはトリガーしません。

@end deffn

@geindex NetrcParseError
@anchor{library/netrc netrc NetrcParseError}@anchor{2fa9}
@deffn {例外} netrc.NetrcParseError

ソーステキストに構文上のエラーがある場合に、 @ref{1c79,,netrc} クラスで発生する例外。この例外のインスタンスは3つの興味深い属性を提供します:

@geindex msg (netrc.NetrcParseError の属性)
@anchor{library/netrc netrc NetrcParseError msg}@anchor{2faa}
@deffn {の属性} msg

エラーのテキストによる説明。
@end deffn

@geindex filename (netrc.NetrcParseError の属性)
@anchor{library/netrc netrc NetrcParseError filename}@anchor{2fab}
@deffn {の属性} filename

ソースファイルの名前。
@end deffn

@geindex lineno (netrc.NetrcParseError の属性)
@anchor{library/netrc netrc NetrcParseError lineno}@anchor{2fac}
@deffn {の属性} lineno

エラーが見つかった行番号。
@end deffn
@end deffn

@menu
* netrc オブジェクト:: 

@end menu

@node netrc オブジェクト,,,netrc --- netrc ファイルの処理
@anchor{library/netrc id1}@anchor{2fad}@anchor{library/netrc netrc-objects}@anchor{2fae}
@subsubsection netrc オブジェクト


@ref{1c79,,netrc} インスタンスは以下のメソッドを持っています:

@geindex authenticators() (netrc.netrc のメソッド)
@anchor{library/netrc netrc netrc authenticators}@anchor{2faf}
@deffn {メソッド} netrc.authenticators (host)

`host' の認証情報として、三要素のタプル  @code{(login, account, password)} を返します。与えられた host に対するエントリが netrc ファイルにない場合、'default' エントリに関連付けられたタプルが返されます。host に対応するエントリがなく、default エントリもない場合、@code{None} を返します。
@end deffn

@geindex __repr__() (netrc.netrc のメソッド)
@anchor{library/netrc netrc netrc __repr__}@anchor{2fb0}
@deffn {メソッド} netrc.__repr__ ()

クラスの持っているデータを netrc ファイルの書式に従った文字列で出力します。(コメントは無視され、エントリが並べ替えられる可能性があります。)
@end deffn

@ref{1c79,,netrc} のインスタンスは以下の public なインスタンス変数を持っています:

@geindex hosts (netrc.netrc の属性)
@anchor{library/netrc netrc netrc hosts}@anchor{2fb1}
@deffn {の属性} netrc.hosts

ホスト名を @code{(login, account, password)} からなるタプルに対応づけている辞書です。'default' エントリがある場合、その名前の擬似ホスト名として表現されます。
@end deffn

@geindex macros (netrc.netrc の属性)
@anchor{library/netrc netrc netrc macros}@anchor{2fb2}
@deffn {の属性} netrc.macros

マクロ名を文字列のリストに対応付けている辞書です。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node plistlib --- Apple plist ファイルを生成・解析する,,netrc --- netrc ファイルの処理,ファイルフォーマット
@anchor{library/plistlib doc}@anchor{2fb3}@anchor{library/plistlib module-plistlib}@anchor{b0}@anchor{library/plistlib plistlib-generate-and-parse-apple-plist-files}@anchor{2fb4}@anchor{library/plistlib translation-repo}@anchor{2fb5}
@subsection @code{plistlib} --- Apple @code{.plist} ファイルを生成・解析する


@geindex module; plistlib

@c (harvested from docstrings in the original file)

`ソースコード:' Lib/plistlib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/plistlib.py}

@geindex plist;ファイル
@geindex property list


__________________________________________________________________


このモジュールは Apple (主に macOS と iOS) で使われる「プロパティーリスト」ファイルを読み書きするインターフェイスを提供します。このモジュールはバイナリと XML の plist ファイルの両方をサポートします。

プロパティーリスト (@code{.plist}) ファイル形式は基本的型のオブジェクト、たとえば辞書やリスト、数、文字列など、に対する単純な直列化です。たいてい、トップレベルのオブジェクトは辞書です。

plist ファイルを書き出したり解析したりするには @ref{b4a,,dump()} や @ref{b48,,load()} 関数を利用します。

バイトオブジェクトや文字列オブジェクトの plist データを扱うためには @ref{b4b,,dumps()} や @ref{b49,,loads()} を利用します。

値は文字列、整数、浮動小数点数、ブール型、タプル、リスト、辞書 (ただし文字列だけがキーになれます)、 @ref{192,,bytes}、@ref{344,,bytearray} または @ref{4e2,,datetime.datetime} のオブジェクトです。


バージョン 3.4 で変更: 新しい API となり、古い API は非推奨となりました。バイナリ形式の plist がサポートされました。



バージョン 3.8 で変更: バイナリの plist で NSKeyedArchiver や NSKeyedUnarchiver によって使用される @ref{c16,,UID} トークンの読み込み・書き込みのサポートが追加されました。



バージョン 3.9 で変更: 古い API が削除されました。



@subsubheading 参考



@table @asis

@item PList マニュアルページ@footnote{https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/PropertyLists/}

このファイル形式の Apple の文書。
@end table


このモジュールは以下の関数を定義しています:

@geindex load() (plistlib モジュール)
@anchor{library/plistlib plistlib load}@anchor{b48}
@deffn {の関数} plistlib.load (fp, *, fmt=None, dict_type=dict, aware_datetime=False)

plist ファイルを読み込みます。`fp' は読み込み可能かつバイナリのファイルオブジェクトです。展開されたルートオブジェクト (通常は辞書です) を返します。

`fmt' はファイルの形式で、次の値が有効です。


@itemize *

@item 
@ref{885,,None}: ファイル形式を自動検出します

@item 
@ref{117b,,FMT_XML}: XML ファイル形式です

@item 
@ref{117c,,FMT_BINARY}: バイナリの plist 形式です
@end itemize

`dict_type' は、 plist ファイルから読み出された辞書に使われる型です。

When `aware_datetime' is true, fields with type @code{datetime.datetime} will
be created as @ref{2899,,aware object}, with
@code{tzinfo} as @ref{713,,datetime.UTC}.

@ref{117b,,FMT_XML} 形式の XML データは @ref{12c,,xml.parsers.expat} にある Expat パーサーを使って解析されます。不正な形式の XML に対して送出される可能性のある例外については、そちらの文書を参照してください。plist 解析器では、未知の要素は単純に無視されます。

The parser raises @ref{1cfa,,InvalidFileException} when the file cannot be parsed.


Added in version 3.4.



バージョン 3.13 で変更: キーワード専用引数 `aware_datetime' が追加されました。

@end deffn

@geindex loads() (plistlib モジュール)
@anchor{library/plistlib plistlib loads}@anchor{b49}
@deffn {の関数} plistlib.loads (data, *, fmt=None, dict_type=dict, aware_datetime=False)

バイナリまたは文字列オブジェクトから plist をロードします。キーワード引数の説明については、 @ref{b48,,load()} を参照してください。


Added in version 3.4.



バージョン 3.13 で変更: `fmt' が @ref{117b,,FMT_XML} の場合、 `data' は文字列たり得ます。

@end deffn

@geindex dump() (plistlib モジュール)
@anchor{library/plistlib plistlib dump}@anchor{b4a}
@deffn {の関数} plistlib.dump (value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False, aware_datetime=False)

Write `value' to a plist file. `fp' should be a writable, binary
file object.

`fmt' 引数は plist ファイルの形式を指定し、次のいずれかの値をとることができます。


@itemize *

@item 
@ref{117b,,FMT_XML}: XML 形式の plist ファイルです

@item 
@ref{117c,,FMT_BINARY}: バイナリ形式の plist ファイルです
@end itemize

`sort_keys' が真 (デフォルト) の場合、辞書内のキーは、plist にソートされた順序で書き込まれます。偽の場合、ディクショナリのイテレートの順序で書き込まれます。

`skipkeys' が偽 (デフォルト) の場合、この関数は辞書のキーが文字列でない場合に @ref{198,,TypeError} を送出します。真の場合、そのようなキーは読み飛ばされます。

When `aware_datetime' is true and any field with type @code{datetime.datetime}
is set as an @ref{2899,,aware object}, it will convert to
UTC timezone before writing it.

@ref{198,,TypeError} が、オブジェクトがサポート外の型のものであったりサポート外の型のオブジェクトを含むコンテナだった場合に、送出されます。

(バイナリの) plist ファイル内で表現できない整数値に対しては、 @ref{a81,,OverflowError} が送出されます。


Added in version 3.4.



バージョン 3.13 で変更: キーワード専用引数 `aware_datetime' が追加されました。

@end deffn

@geindex dumps() (plistlib モジュール)
@anchor{library/plistlib plistlib dumps}@anchor{b4b}
@deffn {の関数} plistlib.dumps (value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False, aware_datetime=False)

`value' を plist 形式のバイトオブジェクトとして返します。この関数のキーワード引数の説明については、 @ref{b4a,,dump()} を参照してください。


Added in version 3.4.

@end deffn

以下のクラスが使用可能です:

@geindex UID (plistlib のクラス)
@anchor{library/plistlib plistlib UID}@anchor{c16}
@deffn {クラス} plistlib.UID (data)

@ref{19b,,int} をラップします。これは NSKeyedArchiver でエンコードされた UID を含むデータ、の読み込みや書き込みに使用されます (PList マニュアルを参照) 。

@geindex data (plistlib.UID の属性)
@anchor{library/plistlib plistlib UID data}@anchor{2fb6}
@deffn {の属性} data

Int value of the UID.  It must be in the range @code{0 <= data < 2**64}.
@end deffn


Added in version 3.8.

@end deffn

以下の定数が利用可能です:

@geindex FMT_XML (plistlib モジュール)
@anchor{library/plistlib plistlib FMT_XML}@anchor{117b}
@deffn {データ} plistlib.FMT_XML

plist ファイルの XML 形式です


Added in version 3.4.

@end deffn

@geindex FMT_BINARY (plistlib モジュール)
@anchor{library/plistlib plistlib FMT_BINARY}@anchor{117c}
@deffn {データ} plistlib.FMT_BINARY

plist ファイルのバイナリ形式です


Added in version 3.4.

@end deffn

The module defines the following exceptions:

@geindex InvalidFileException
@anchor{library/plistlib plistlib InvalidFileException}@anchor{1cfa}
@deffn {例外} plistlib.InvalidFileException

Raised when a file cannot be parsed.


Added in version 3.4.

@end deffn

@menu
* 使用例: 使用例<19>. 

@end menu

@node 使用例<19>,,,plistlib --- Apple plist ファイルを生成・解析する
@anchor{library/plistlib examples}@anchor{2fb7}
@subsubsection 使用例


plist を作ります:

@example
import datetime
import plistlib

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.now()
)
print(plistlib.dumps(pl).decode())
@end example

plist を解析します:

@example
import plistlib

plist = b"""<plist version="1.0">
<dict>
    <key>foo</key>
    <string>bar</string>
</dict>
</plist>"""
pl = plistlib.loads(plist)
print(pl["foo"])
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 暗号関連のサービス,汎用オペレーティングシステムサービス,ファイルフォーマット,Python 標準ライブラリ
@anchor{library/crypto doc}@anchor{2fb8}@anchor{library/crypto crypto}@anchor{2fb9}@anchor{library/crypto cryptographic-services}@anchor{2fba}@anchor{library/crypto translation-repo}@anchor{2fbb}
@section 暗号関連のサービス


@geindex cryptography

この章で記述されているモジュールでは、暗号の本質に関わる様々なアルゴリズムを実装しています。 これらは必要に応じてインストールすることで使用できます。概要を以下に示します:

@menu
* hashlib: hashlib --- セキュアハッシュとメッセージダイジェスト. セキュアハッシュとメッセージダイジェスト
* hmac: hmac --- メッセージ認証のための鍵付きハッシュ化. メッセージ認証のための鍵付きハッシュ化
* secrets: secrets --- 機密を扱うために安全な乱数を生成する. 機密を扱うために安全な乱数を生成する

@end menu

@node hashlib --- セキュアハッシュとメッセージダイジェスト,hmac --- メッセージ認証のための鍵付きハッシュ化,,暗号関連のサービス
@anchor{library/hashlib doc}@anchor{2fbc}@anchor{library/hashlib hashlib-secure-hashes-and-message-digests}@anchor{2fbd}@anchor{library/hashlib module-hashlib}@anchor{6c}
@subsection @code{hashlib} --- セキュアハッシュとメッセージダイジェスト


@geindex module; hashlib

`ソースコード:' Lib/hashlib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/hashlib.py}

@geindex message digest@comma{} MD5
@geindex secure hash algorithm@comma{} SHA1@comma{} SHA2@comma{} SHA224@comma{} SHA256@comma{} SHA384@comma{} SHA512@comma{} SHA3@comma{} Shake@comma{} Blake2

@c import hashlib


__________________________________________________________________


This module implements a common interface to many different hash algorithms.
Included are the FIPS secure hash algorithms SHA224, SHA256, SHA384, SHA512,
(defined in the FIPS 180-4 standard@footnote{https://csrc.nist.gov/pubs/fips/180-4/upd1/final}), the SHA-3 series (defined in the FIPS 202 standard@footnote{https://csrc.nist.gov/pubs/fips/202/final}) as well as the legacy algorithms SHA1 (formerly part of FIPS@footnote{https://csrc.nist.gov/news/2023/decision-to-revise-fips-180-4})
and the MD5 algorithm (defined in internet 
@geindex RFC; RFC 1321
RFC 1321@footnote{https://datatracker.ietf.org/doc/html/rfc1321.html}).

@cartouche
@quotation 注釈 
adler32 や crc32 ハッシュ関数は @ref{139,,zlib} モジュールで提供されています。
@end quotation
@end cartouche

@menu
* ハッシュアルゴリズム:: 
* 使用法:: 
* コンストラクタ:: 
* 属性:: 
* Hash Objects:: 
* SHAKE 可変長ダイジェスト:: 
* ファイルのハッシュ化:: 
* 鍵導出:: 
* BLAKE2:: 

@end menu

@node ハッシュアルゴリズム,使用法,,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib hash-algorithms}@anchor{2fbe}@anchor{library/hashlib id1}@anchor{2fbf}
@subsubsection ハッシュアルゴリズム


各 `hash' の名前が付いたコンストラクタがあります。いずれも同一で簡単なインターフェイスのあるハッシュオブジェクトを返します。例えば、SHA-256 ハッシュオブジェクトを作るには @ref{18ae,,sha256()} を使います。このオブジェクトには @ref{2fc0,,update} メソッドを用いて @ref{193,,bytes-like オブジェクト} (通常 @ref{192,,bytes}) を渡すことができます。@ref{2fc1,,digest()} や @ref{2fc2,,hexdigest()} メソッドを用いて、それまでに渡したデータを連結したものの `digest' をいつでも要求することができます。

To allow multithreading, the Python @ref{164,,GIL} is released while computing a
hash supplied more than 2047 bytes of data at once in its constructor or
@ref{2fc0,,.update} method.

@geindex OpenSSL;(use in module hashlib)

Constructors for hash algorithms that are always present in this module are
@ref{2fc3,,sha1()}, @ref{2fc4,,sha224()}, @ref{18ae,,sha256()}, @ref{2fc5,,sha384()}, @ref{2fc6,,sha512()},
@ref{ea0,,sha3_224()}, @ref{ea1,,sha3_256()}, @ref{ea2,,sha3_384()}, @ref{ea3,,sha3_512()},
@ref{ea4,,shake_128()}, @ref{ea5,,shake_256()}, @ref{852,,blake2b()}, and @ref{853,,blake2s()}.
@ref{1823,,md5()} is normally available as well, though it may be missing or blocked
if you are using a rare "FIPS compliant" build of Python.
These correspond to @ref{158b,,algorithms_guaranteed}.

Additional algorithms may also be available if your Python distribution's
@code{hashlib} was linked against a build of OpenSSL that provides others.
Others `are not guaranteed available' on all installations and will only be
accessible by name via @ref{1d2e,,new()}.  See @ref{158c,,algorithms_available}.

@cartouche
@quotation 警告 
Some algorithms have known hash collision weaknesses (including MD5 and
SHA1). Refer to Attacks on cryptographic hash algorithms@footnote{https://en.wikipedia.org/wiki/Cryptographic_hash_function#Attacks_on_cryptographic_hash_algorithms} and the
@ref{2fc7,,hashlib-seealso} section at the end of this document.
@end quotation
@end cartouche


Added in version 3.6: SHA3 (Keccak) and SHAKE constructors @ref{ea0,,sha3_224()}, @ref{ea1,,sha3_256()},
@ref{ea2,,sha3_384()}, @ref{ea3,,sha3_512()}, @ref{ea4,,shake_128()}, @ref{ea5,,shake_256()}
were added.
@ref{852,,blake2b()} and @ref{853,,blake2s()} were added.

@anchor{library/hashlib hashlib-usedforsecurity}@anchor{2fc8}

バージョン 3.9 で変更: All hashlib constructors take a keyword-only argument `usedforsecurity'
with default value @code{True}. A false value allows the use of insecure and
blocked hashing algorithms in restricted environments. @code{False} indicates
that the hashing algorithm is not used in a security context, e.g. as a
non-cryptographic one-way compression function.



バージョン 3.9 で変更: Hashlib now uses SHA3 and SHAKE from OpenSSL if it provides it.



バージョン 3.12 で変更: For any of the MD5, SHA1, SHA2, or SHA3 algorithms that the linked
OpenSSL does not provide we fall back to a verified implementation from
the HACL* project@footnote{https://github.com/hacl-star/hacl-star}.


@node 使用法,コンストラクタ,ハッシュアルゴリズム,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib usage}@anchor{2fc9}
@subsubsection 使用法


>>`@w{`}<<b"Nobody inspects the spammish repetition">>`@w{`}<<というバイト文字列のダイジェストを取得するには次のようにします:

@example
>>> import hashlib
>>> m = hashlib.sha256()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\x03\x1e\xdd@}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06'
>>> m.hexdigest()
'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'
@end example

もっと簡潔に書くと、このようになります:

@example
>>> hashlib.sha256(b"Nobody inspects the spammish repetition").hexdigest()
'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'
@end example

@node コンストラクタ,属性,使用法,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib constructors}@anchor{2fca}
@subsubsection コンストラクタ


@geindex new() (hashlib モジュール)
@anchor{library/hashlib hashlib new}@anchor{1d2e}
@deffn {の関数} hashlib.new (name[, data], *, usedforsecurity=True)

一般的なコンストラクタで、第一引数にアルゴリズム名を文字列 `name' で受け取ります。他にも、前述のハッシュアルゴリズムだけでなく OpenSSL ライブラリーが提供するような他のアルゴリズムにアクセスすることができます。
@end deffn

Using @ref{1d2e,,new()} with an algorithm name:

@example
>>> h = hashlib.new('sha256')
>>> h.update(b"Nobody inspects the spammish repetition")
>>> h.hexdigest()
'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'
@end example

@geindex md5() (hashlib モジュール)
@anchor{library/hashlib hashlib md5}@anchor{1823}
@deffn {の関数} hashlib.md5 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha1() (hashlib モジュール)
@anchor{library/hashlib hashlib sha1}@anchor{2fc3}
@deffn {の関数} hashlib.sha1 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha224() (hashlib モジュール)
@anchor{library/hashlib hashlib sha224}@anchor{2fc4}
@deffn {の関数} hashlib.sha224 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha256() (hashlib モジュール)
@anchor{library/hashlib hashlib sha256}@anchor{18ae}
@deffn {の関数} hashlib.sha256 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha384() (hashlib モジュール)
@anchor{library/hashlib hashlib sha384}@anchor{2fc5}
@deffn {の関数} hashlib.sha384 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha512() (hashlib モジュール)
@anchor{library/hashlib hashlib sha512}@anchor{2fc6}
@deffn {の関数} hashlib.sha512 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha3_224() (hashlib モジュール)
@anchor{library/hashlib hashlib sha3_224}@anchor{ea0}
@deffn {の関数} hashlib.sha3_224 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha3_256() (hashlib モジュール)
@anchor{library/hashlib hashlib sha3_256}@anchor{ea1}
@deffn {の関数} hashlib.sha3_256 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha3_384() (hashlib モジュール)
@anchor{library/hashlib hashlib sha3_384}@anchor{ea2}
@deffn {の関数} hashlib.sha3_384 ([data], *, usedforsecurity=True)
@end deffn

@geindex sha3_512() (hashlib モジュール)
@anchor{library/hashlib hashlib sha3_512}@anchor{ea3}
@deffn {の関数} hashlib.sha3_512 ([data], *, usedforsecurity=True)
@end deffn

Named constructors such as these are faster than passing an algorithm name to
@ref{1d2e,,new()}.

@node 属性,Hash Objects,コンストラクタ,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib attributes}@anchor{2fcb}
@subsubsection 属性


Hashlib provides the following constant module attributes:

@geindex algorithms_guaranteed (hashlib モジュール)
@anchor{library/hashlib hashlib algorithms_guaranteed}@anchor{158b}
@deffn {データ} hashlib.algorithms_guaranteed

このモジュールによってすべてのプラットフォームでサポートされていることが保証されるハッシュアルゴリズムの名前を含む集合です。一部のアップストリームのベンダーが提供する奇妙な "FIPS準拠の" Pythonビルドではmd5のサポートを除外していますが、その場合であっても 'md5' がリストに含まれることに注意してください。


Added in version 3.2.

@end deffn

@geindex algorithms_available (hashlib モジュール)
@anchor{library/hashlib hashlib algorithms_available}@anchor{158c}
@deffn {データ} hashlib.algorithms_available

実行中の Python インタープリタで利用可能なハッシュアルゴリズム名の set です。これらの名前は @ref{1d2e,,new()} に渡すことができます。@ref{158b,,algorithms_guaranteed} は常にサブセットです。この set の中に同じアルゴリズムが違う名前で複数回現れることがあります (OpenSSL 由来)。


Added in version 3.2.

@end deffn

@node Hash Objects,SHAKE 可変長ダイジェスト,属性,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib hash-objects}@anchor{2fcc}
@subsubsection Hash Objects


コンストラクタが返すハッシュオブジェクトには、次のような定数属性が用意されています:

@geindex hash.digest_size (hashlib モジュール)
@anchor{library/hashlib hashlib hash digest_size}@anchor{2fcd}
@deffn {データ} hash.digest_size

生成されたハッシュのバイト数。
@end deffn

@geindex hash.block_size (hashlib モジュール)
@anchor{library/hashlib hashlib hash block_size}@anchor{2fce}
@deffn {データ} hash.block_size

内部で使われるハッシュアルゴリズムのブロックのバイト数。
@end deffn

ハッシュオブジェクトには次のような属性があります:

@geindex name (hashlib.hash の属性)
@anchor{library/hashlib hashlib hash name}@anchor{1149}
@deffn {の属性} hash.name

このハッシュの正規名です。常に小文字で、@ref{1d2e,,new()} の引数として渡してこのタイプの別のハッシュを生成することができます。


バージョン 3.4 で変更: name 属性は CPython には最初からありましたが、Python 3.4 までは正式に明記されていませんでした。そのため、プラットフォームによっては存在しないかもしれません。

@end deffn

ハッシュオブジェクトには次のようなメソッドがあります:

@geindex update() (hashlib.hash のメソッド)
@anchor{library/hashlib hashlib hash update}@anchor{2fc0}
@deffn {メソッド} hash.update (data)

hash オブジェクトを @ref{193,,bytes-like object} で更新します。このメソッドの呼出しの繰り返しは、それらの引数を全て結合した引数で単一の呼び出しをした際と同じになります。すなわち @code{m.update(a); m.update(b)}  は @code{m.update(a + b)} と等価です。
@end deffn

@geindex digest() (hashlib.hash のメソッド)
@anchor{library/hashlib hashlib hash digest}@anchor{2fc1}
@deffn {メソッド} hash.digest ()

これまで @ref{2fc0,,update()} メソッドに渡されたデータのダイジェスト値を返します。これは @ref{2fcd,,digest_size} と同じ長さの、0 から 255 の範囲全てを含み得るバイトの列です。
@end deffn

@geindex hexdigest() (hashlib.hash のメソッド)
@anchor{library/hashlib hashlib hash hexdigest}@anchor{2fc2}
@deffn {メソッド} hash.hexdigest ()

@ref{2fc1,,digest()} と似ていますが、倍の長さの、16進形式文字列を返します。これは、電子メールなどの非バイナリ環境で値を交換する場合に便利です。
@end deffn

@geindex copy() (hashlib.hash のメソッド)
@anchor{library/hashlib hashlib hash copy}@anchor{2fcf}
@deffn {メソッド} hash.copy ()

ハッシュオブジェクトのコピー ("クローン") を返します。これは、最初の部分文字列が共通なデータのダイジェストを効率的に計算するために使用します。
@end deffn

@node SHAKE 可変長ダイジェスト,ファイルのハッシュ化,Hash Objects,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib shake-variable-length-digests}@anchor{2fd0}
@subsubsection SHAKE 可変長ダイジェスト


@geindex shake_128() (hashlib モジュール)
@anchor{library/hashlib hashlib shake_128}@anchor{ea4}
@deffn {の関数} hashlib.shake_128 ([data], *, usedforsecurity=True)
@end deffn

@geindex shake_256() (hashlib モジュール)
@anchor{library/hashlib hashlib shake_256}@anchor{ea5}
@deffn {の関数} hashlib.shake_256 ([data], *, usedforsecurity=True)
@end deffn

The @ref{ea4,,shake_128()} and @ref{ea5,,shake_256()} algorithms provide variable
length digests with length_in_bits//2 up to 128 or 256 bits of security.
As such, their digest methods require a length. Maximum length is not limited
by the SHAKE algorithm.

@geindex digest() (hashlib.shake のメソッド)
@anchor{library/hashlib hashlib shake digest}@anchor{1e1a}
@deffn {メソッド} shake.digest (length)

これまで @ref{2fc0,,update()} メソッドに渡されたデータのダイジェスト値を返します。これは `length' と同じ長さの、0 から 255 の範囲全てを含み得るバイトの列です。
@end deffn

@geindex hexdigest() (hashlib.shake のメソッド)
@anchor{library/hashlib hashlib shake hexdigest}@anchor{1e1b}
@deffn {メソッド} shake.hexdigest (length)

@ref{1e1a,,digest()} と似ていますが、倍の長さの、16進形式文字列を返します。これは、電子メールなどの非バイナリ環境で値を交換する場合に便利です。
@end deffn

使用例:

@example
>>> h = hashlib.shake_256(b'Nobody inspects the spammish repetition')
>>> h.hexdigest(20)
'44709d6fcb83d92a76dcb0b668c98e1b1d3dafe7'
@end example

@node ファイルのハッシュ化,鍵導出,SHAKE 可変長ダイジェスト,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib file-hashing}@anchor{2fd1}
@subsubsection ファイルのハッシュ化


The hashlib module provides a helper function for efficient hashing of
a file or file-like object.

@geindex file_digest() (hashlib モジュール)
@anchor{library/hashlib hashlib file_digest}@anchor{854}
@deffn {の関数} hashlib.file_digest (fileobj, digest, /)

Return a digest object that has been updated with contents of file object.

`fileobj' must be a file-like object opened for reading in binary mode.
It accepts file objects from  builtin @ref{316,,open()}, @ref{10a4,,BytesIO}
instances, SocketIO objects from @ref{13b7,,socket.socket.makefile()}, and
similar. `fileobj' must be opened in blocking mode, otherwise a
@ref{235,,BlockingIOError} may be raised.

The function may bypass Python's I/O and use the file descriptor
from @ref{17ad,,fileno()} directly. `fileobj' must be assumed to be
in an unknown state after this function returns or raises. It is up to
the caller to close `fileobj'.

`digest' must either be a hash algorithm name as a `str', a hash
constructor, or a callable that returns a hash object.

例:

@example
>>> import io, hashlib, hmac
>>> with open("library/hashlib.rst", "rb") as f:
...     digest = hashlib.file_digest(f, "sha256")
...
>>> digest.hexdigest()
'...'
@end example

@example
>>> buf = io.BytesIO(b"somedata")
>>> mac1 = hmac.HMAC(b"key", digestmod=hashlib.sha512)
>>> digest = hashlib.file_digest(buf, lambda: mac1)
@end example

@example
>>> digest is mac1
True
>>> mac2 = hmac.HMAC(b"key", b"somedata", digestmod=hashlib.sha512)
>>> mac1.digest() == mac2.digest()
True
@end example


Added in version 3.11.



バージョン 3.14 で変更: Now raises a @ref{235,,BlockingIOError} if the file is opened in non-blocking
mode. Previously, spurious null bytes were added to the digest.

@end deffn

@node 鍵導出,BLAKE2,ファイルのハッシュ化,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib key-derivation}@anchor{2fd2}
@subsubsection 鍵導出


鍵の導出 (derivation) と引き伸ばし (stretching) のアルゴリズムはセキュアなパスワードのハッシュ化のために設計されました。 @code{sha1(password)} のような甘いアルゴリズムは、ブルートフォース攻撃に抵抗できません。良いパスワードハッシュ化は調節可能で、遅くて、 salt@footnote{https://en.wikipedia.org/wiki/Salt_%28cryptography%29} を含まなければなりません。

@geindex pbkdf2_hmac() (hashlib モジュール)
@anchor{library/hashlib hashlib pbkdf2_hmac}@anchor{733}
@deffn {の関数} hashlib.pbkdf2_hmac (hash_name, password, salt, iterations, dklen=None)

この関数は PKCS#5 のパスワードに基づいた鍵導出関数 2 を提供しています。疑似乱数関数として HMAC を使用しています。

文字列 `hash_name' は、HMAC のハッシュダイジェストアルゴリズムの望ましい名前で、例えば 'sha1' や 'sha256' です。 `password' と `salt' はバイト列のバッファとして解釈されます。アプリケーションとライブラリは、 `password' を適切な長さ (例えば 1024) に制限すべきです。 `salt' は @ref{746,,os.urandom()} のような適切なソースからの、およそ 16 バイトかそれ以上のバイト列にするべきです。

The number of `iterations' should be chosen based on the hash algorithm and
computing power. As of 2022, hundreds of thousands of iterations of SHA-256
are suggested. For rationale as to why and how to choose what is best for
your application, read `Appendix A.2.2' of NIST-SP-800-132@footnote{https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf}. The answers
on the stackexchange pbkdf2 iterations question@footnote{https://security.stackexchange.com/questions/3959/recommended-of-iterations-when-using-pbkdf2-sha256/} explain in detail.

`dklen' は、導出されたバイト列の鍵の長さです。 `dklen' が @code{None} の場合、ハッシュアルゴリズム `hash_name' のダイジェストサイズが使われます。例えば SHA-512 では 64 です。

@example
>>> from hashlib import pbkdf2_hmac
>>> our_app_iters = 500_000  # Application specific, read above.
>>> dk = pbkdf2_hmac('sha256', b'password', b'bad salt' * 2, our_app_iters)
>>> dk.hex()
'15530bba69924174860db778f2c6f8104d3aaf9d26241840c8c4a641c8d000a9'
@end example

Function only available when Python is compiled with OpenSSL.


Added in version 3.4.



バージョン 3.12 で変更: Function now only available when Python is built with OpenSSL. The slow
pure Python implementation has been removed.

@end deffn

@geindex scrypt() (hashlib モジュール)
@anchor{library/hashlib hashlib scrypt}@anchor{e38}
@deffn {の関数} hashlib.scrypt (password, *, salt, n, r, p, maxmem=0, dklen=64)

この関数は、 
@geindex RFC; RFC 7914
RFC 7914@footnote{https://datatracker.ietf.org/doc/html/rfc7914.html} で定義されるscrypt のパスワードに基づいた鍵導出関数を提供します。

`password' と `salt' は @ref{193,,bytes-like object} でなければなりません。アプリケーションとライブラリは、 `password' を適切な長さ (例えば 1024) に制限すべきです。 `salt' は @ref{746,,os.urandom()} のような適切なソースからの、およそ 16 バイトかそれ以上のバイト列にするべきです。

`n' is the CPU/Memory cost factor, `r' the block size, `p' parallelization
factor and `maxmem' limits memory (OpenSSL 1.1.0 defaults to 32 MiB).
`dklen' is the length of the derived key in bytes.


Added in version 3.6.

@end deffn

@node BLAKE2,,鍵導出,hashlib --- セキュアハッシュとメッセージダイジェスト
@anchor{library/hashlib blake2}@anchor{2fd3}@anchor{library/hashlib hashlib-blake2}@anchor{2fd4}
@subsubsection BLAKE2


@geindex blake2b@comma{} blake2s

BLAKE2@footnote{https://www.blake2.net} is a cryptographic hash function defined in 
@geindex RFC; RFC 7693
RFC 7693@footnote{https://datatracker.ietf.org/doc/html/rfc7693.html} that comes in two
flavors:


@itemize *

@item 
`BLAKE2b', optimized for 64-bit platforms and produces digests of any size
between 1 and 64 bytes,

@item 
`BLAKE2s', optimized for 8- to 32-bit platforms and produces digests of any
size between 1 and 32 bytes.
@end itemize

BLAKE2 supports `keyed mode' (a faster and simpler replacement for HMAC@footnote{https://en.wikipedia.org/wiki/Hash-based_message_authentication_code}),
`salted hashing', `personalization', and `tree hashing'.

Hash objects from this module follow the API of standard library's
@code{hashlib} objects.

@menu
* ハッシュオブジェクトの作成:: 
* 定数: 定数<5>. 
* 使用例: 使用例<20>. 
* クレジット;: クレジット. 

@end menu

@node ハッシュオブジェクトの作成,定数<5>,,BLAKE2
@anchor{library/hashlib creating-hash-objects}@anchor{2fd5}
@subsubsection ハッシュオブジェクトの作成


新しいハッシュオブジェクトは、コンストラクタ関数を呼び出すことで生成されます:

@geindex blake2b() (hashlib モジュール)
@anchor{library/hashlib hashlib blake2b}@anchor{852}
@deffn {の関数} hashlib.blake2b (data=b'@w{'}, *, digest_size=64, key=b'@w{'}, salt=b'@w{'}, person=b'@w{'}, fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, usedforsecurity=True)
@end deffn

@geindex blake2s() (hashlib モジュール)
@anchor{library/hashlib hashlib blake2s}@anchor{853}
@deffn {の関数} hashlib.blake2s (data=b'@w{'}, *, digest_size=32, key=b'@w{'}, salt=b'@w{'}, person=b'@w{'}, fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, usedforsecurity=True)
@end deffn

These functions return the corresponding hash objects for calculating
BLAKE2b or BLAKE2s. They optionally take these general parameters:


@itemize *

@item 
`data': initial chunk of data to hash, which must be
@ref{193,,bytes-like object}.  It can be passed only as positional argument.

@item 
`digest_size': 出力するダイジェストのバイト数。

@item 
`key': key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for
BLAKE2s).

@item 
`salt': salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8
bytes for BLAKE2s).

@item 
`person': personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes
for BLAKE2s).
@end itemize

下の表は一般的なパラメータの上限 (バイト単位) です:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxx} 
@headitem

Hash

@tab

digest_size

@tab

len(key)

@tab

len(salt)

@tab

len(person)

@item

BLAKE2b

@tab

64

@tab

64

@tab

16

@tab

16

@item

BLAKE2s

@tab

32

@tab

32

@tab

8

@tab

8

@end multitable


@cartouche
@quotation 注釈 
BLAKE2 specification defines constant lengths for salt and personalization
parameters, however, for convenience, this implementation accepts byte
strings of any size up to the specified length. If the length of the
parameter is less than specified, it is padded with zeros, thus, for
example, @code{b'salt'} and @code{b'salt\x00'} is the same value. (This is not
the case for `key'.)
@end quotation
@end cartouche

これらのサイズは以下に述べるモジュール @ref{2fd6,,constants} で利用できます。

コンストラクタ関数は以下のツリーハッシングパラメタを受け付けます:


@itemize *

@item 
`fanout': fanout (0 to 255, 0 if unlimited, 1 in sequential mode).

@item 
`depth': ツリーの深さの最大値（1から255までの値で、無制限であれば255、シーケンスモードでは1）。

@item 
`leaf_size': maximal byte length of leaf (0 to @code{2**32-1}, 0 if unlimited or in
sequential mode).

@item 
`node_offset': node offset (0 to @code{2**64-1} for BLAKE2b, 0 to @code{2**48-1} for
BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode).

@item 
`node_depth': node depth (0 to 255, 0 for leaves, or in sequential mode).

@item 
`inner_size': inner digest size (0 to 64 for BLAKE2b, 0 to 32 for
BLAKE2s, 0 in sequential mode).

@item 
`last_node': boolean indicating whether the processed node is the last
one (@code{False} for sequential mode).
@end itemize


@float Figure

@image{python-figures/hashlib-blake2-tree,,,Explanation of tree mode parameters.,png}

@end float


See section 2.10 in BLAKE2 specification@footnote{https://www.blake2.net/blake2_20130129.pdf} for comprehensive review of tree
hashing.

@node 定数<5>,使用例<20>,ハッシュオブジェクトの作成,BLAKE2
@anchor{library/hashlib constants}@anchor{2fd6}
@subsubsection 定数


@geindex blake2b.SALT_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2b SALT_SIZE}@anchor{2fd7}
@deffn {データ} blake2b.SALT_SIZE
@end deffn

@geindex blake2s.SALT_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2s SALT_SIZE}@anchor{2fd8}
@deffn {データ} blake2s.SALT_SIZE
@end deffn

ソルト長（コンストラクタが受け付けれる最大長）

@geindex blake2b.PERSON_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2b PERSON_SIZE}@anchor{2fd9}
@deffn {データ} blake2b.PERSON_SIZE
@end deffn

@geindex blake2s.PERSON_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2s PERSON_SIZE}@anchor{2fda}
@deffn {データ} blake2s.PERSON_SIZE
@end deffn

Personalization string length (maximum length accepted by constructors).

@geindex blake2b.MAX_KEY_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2b MAX_KEY_SIZE}@anchor{2fdb}
@deffn {データ} blake2b.MAX_KEY_SIZE
@end deffn

@geindex blake2s.MAX_KEY_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2s MAX_KEY_SIZE}@anchor{2fdc}
@deffn {データ} blake2s.MAX_KEY_SIZE
@end deffn

最大キー長

@geindex blake2b.MAX_DIGEST_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2b MAX_DIGEST_SIZE}@anchor{2fdd}
@deffn {データ} blake2b.MAX_DIGEST_SIZE
@end deffn

@geindex blake2s.MAX_DIGEST_SIZE (hashlib モジュール)
@anchor{library/hashlib hashlib blake2s MAX_DIGEST_SIZE}@anchor{2fde}
@deffn {データ} blake2s.MAX_DIGEST_SIZE
@end deffn

ハッシュ関数が出力しうるダイジェストの最大長

@node 使用例<20>,クレジット,定数<5>,BLAKE2
@anchor{library/hashlib examples}@anchor{2fdf}
@subsubsection 使用例


@menu
* 簡単なハッシュ化:: 
* Using different digest sizes:: 
* Keyed hashing:: 
* Randomized hashing:: 
* Personalization:: 
* ツリーモード:: 

@end menu

@node 簡単なハッシュ化,Using different digest sizes,,使用例<20>
@anchor{library/hashlib simple-hashing}@anchor{2fe0}
@subsubsection 簡単なハッシュ化


To calculate hash of some data, you should first construct a hash object by
calling the appropriate constructor function (@ref{852,,blake2b()} or
@ref{853,,blake2s()}), then update it with the data by calling @ref{2fc0,,update()} on the
object, and, finally, get the digest out of the object by calling
@ref{2fc1,,digest()} (or @ref{2fc2,,hexdigest()} for hex-encoded string).

@example
>>> from hashlib import blake2b
>>> h = blake2b()
>>> h.update(b'Hello world')
>>> h.hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
@end example

As a shortcut, you can pass the first chunk of data to update directly to the
constructor as the positional argument:

@example
>>> from hashlib import blake2b
>>> blake2b(b'Hello world').hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
@end example

You can call @ref{2fc0,,hash.update()} as many times as you need to iteratively
update the hash:

@example
>>> from hashlib import blake2b
>>> items = [b'Hello', b' ', b'world']
>>> h = blake2b()
>>> for item in items:
...     h.update(item)
...
>>> h.hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
@end example

@node Using different digest sizes,Keyed hashing,簡単なハッシュ化,使用例<20>
@anchor{library/hashlib using-different-digest-sizes}@anchor{2fe1}
@subsubsection Using different digest sizes


BLAKE2 はダイジェストの長さを、BLAKE2bでは64バイトまで、BLAKE2sでは32バイトまでのダイジェスト長を指定できます。例えばSHA-1を、出力を同じ長さのままでBLAKE2bで置き換えるには、BLAKE2bに20バイトのダイジェストを生成するように指示できます:

@example
>>> from hashlib import blake2b
>>> h = blake2b(digest_size=20)
>>> h.update(b'Replacing SHA1 with the more secure function')
>>> h.hexdigest()
'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c'
>>> h.digest_size
20
>>> len(h.digest())
20
@end example

Hash objects with different digest sizes have completely different outputs
(shorter hashes are `not' prefixes of longer hashes); BLAKE2b and BLAKE2s
produce different outputs even if the output length is the same:

@example
>>> from hashlib import blake2b, blake2s
>>> blake2b(digest_size=10).hexdigest()
'6fa1d8fcfd719046d762'
>>> blake2b(digest_size=11).hexdigest()
'eb6ec15daf9546254f0809'
>>> blake2s(digest_size=10).hexdigest()
'1bf21a98c78a1c376ae9'
>>> blake2s(digest_size=11).hexdigest()
'567004bf96e4a25773ebf4'
@end example

@node Keyed hashing,Randomized hashing,Using different digest sizes,使用例<20>
@anchor{library/hashlib keyed-hashing}@anchor{2fe2}
@subsubsection Keyed hashing


Keyed hashing can be used for authentication as a faster and simpler
replacement for Hash-based message authentication code@footnote{https://en.wikipedia.org/wiki/HMAC} (HMAC).
BLAKE2 can be securely used in prefix-MAC mode thanks to the
indifferentiability property inherited from BLAKE.

This example shows how to get a (hex-encoded) 128-bit authentication code for
message @code{b'message data'} with key @code{b'pseudorandom key'}:

@example
>>> from hashlib import blake2b
>>> h = blake2b(key=b'pseudorandom key', digest_size=16)
>>> h.update(b'message data')
>>> h.hexdigest()
'3d363ff7401e02026f4a4687d4863ced'
@end example

As a practical example, a web application can symmetrically sign cookies sent
to users and later verify them to make sure they weren't tampered with:

@example
>>> from hashlib import blake2b
>>> from hmac import compare_digest
>>>
>>> SECRET_KEY = b'pseudorandomly generated server secret key'
>>> AUTH_SIZE = 16
>>>
>>> def sign(cookie):
...     h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY)
...     h.update(cookie)
...     return h.hexdigest().encode('utf-8')
>>>
>>> def verify(cookie, sig):
...     good_sig = sign(cookie)
...     return compare_digest(good_sig, sig)
>>>
>>> cookie = b'user-alice'
>>> sig = sign(cookie)
>>> print("@{0@},@{1@}".format(cookie.decode('utf-8'), sig))
user-alice,b'43b3c982cf697e0c5ab22172d1ca7421'
>>> verify(cookie, sig)
True
>>> verify(b'user-bob', sig)
False
>>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00')
False
@end example

Even though there's a native keyed hashing mode, BLAKE2 can, of course, be used
in HMAC construction with @ref{6e,,hmac} module:

@example
>>> import hmac, hashlib
>>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)
>>> m.update(b'message')
>>> m.hexdigest()
'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'
@end example

@node Randomized hashing,Personalization,Keyed hashing,使用例<20>
@anchor{library/hashlib randomized-hashing}@anchor{2fe3}
@subsubsection Randomized hashing


By setting `salt' parameter users can introduce randomization to the hash
function. Randomized hashing is useful for protecting against collision attacks
on the hash function used in digital signatures.

@quotation

Randomized hashing is designed for situations where one party, the message
preparer, generates all or part of a message to be signed by a second
party, the message signer. If the message preparer is able to find
cryptographic hash function collisions (i.e., two messages producing the
same hash value), then they might prepare meaningful versions of the message
that would produce the same hash value and digital signature, but with
different results (e.g., transferring $1,000,000 to an account, rather than
$10). Cryptographic hash functions have been designed with collision
resistance as a major goal, but the current concentration on attacking
cryptographic hash functions may result in a given cryptographic hash
function providing less collision resistance than expected. Randomized
hashing offers the signer additional protection by reducing the likelihood
that a preparer can generate two or more messages that ultimately yield the
same hash value during the digital signature generation process --- even if
it is practical to find collisions for the hash function. However, the use
of randomized hashing may reduce the amount of security provided by a
digital signature when all portions of the message are prepared
by the signer.

(NIST SP-800-106 "Randomized Hashing for Digital Signatures"@footnote{https://csrc.nist.gov/pubs/sp/800/106/final})
@end quotation

In BLAKE2 the salt is processed as a one-time input to the hash function during
initialization, rather than as an input to each compression function.

@cartouche
@quotation 警告 
`Salted hashing' (or just hashing) with BLAKE2 or any other general-purpose
cryptographic hash function, such as SHA-256, is not suitable for hashing
passwords.  See BLAKE2 FAQ@footnote{https://www.blake2.net/#qa} for more
information.
@end quotation
@end cartouche


@example
>>> import os
>>> from hashlib import blake2b
>>> msg = b'some message'
>>> # Calculate the first hash with a random salt.
>>> salt1 = os.urandom(blake2b.SALT_SIZE)
>>> h1 = blake2b(salt=salt1)
>>> h1.update(msg)
>>> # Calculate the second hash with a different random salt.
>>> salt2 = os.urandom(blake2b.SALT_SIZE)
>>> h2 = blake2b(salt=salt2)
>>> h2.update(msg)
>>> # The digests are different.
>>> h1.digest() != h2.digest()
True
@end example

@node Personalization,ツリーモード,Randomized hashing,使用例<20>
@anchor{library/hashlib personalization}@anchor{2fe4}
@subsubsection Personalization


Sometimes it is useful to force hash function to produce different digests for
the same input for different purposes. Quoting the authors of the Skein hash
function:

@quotation

We recommend that all application designers seriously consider doing this;
we have seen many protocols where a hash that is computed in one part of
the protocol can be used in an entirely different part because two hash
computations were done on similar or related data, and the attacker can
force the application to make the hash inputs the same. Personalizing each
hash function used in the protocol summarily stops this type of attack.

(The Skein Hash Function Family@footnote{https://www.schneier.com/wp-content/uploads/2016/02/skein.pdf},
p. 21)
@end quotation

BLAKE2は `person' 引数にバイト列を渡すことでパーソナライズできます:

@example
>>> from hashlib import blake2b
>>> FILES_HASH_PERSON = b'MyApp Files Hash'
>>> BLOCK_HASH_PERSON = b'MyApp Block Hash'
>>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)
>>> h.update(b'the same content')
>>> h.hexdigest()
'20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4'
>>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)
>>> h.update(b'the same content')
>>> h.hexdigest()
'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3'
@end example

Personalization together with the keyed mode can also be used to derive different
keys from a single one.

@example
>>> from hashlib import blake2s
>>> from base64 import b64decode, b64encode
>>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=')
>>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest()
>>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest()
>>> print(b64encode(enc_key).decode('utf-8'))
rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw=
>>> print(b64encode(mac_key).decode('utf-8'))
G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o=
@end example

@node ツリーモード,,Personalization,使用例<20>
@anchor{library/hashlib tree-mode}@anchor{2fe5}
@subsubsection ツリーモード


これが二つの葉ノードからなる最小の木をハッシュする例です:

@example
  10
 /  \
00  01
@end example

次の例では、64バイトの内部桁が使われ、32バイトの最終的なダイジェストを返しています:

@example
>>> from hashlib import blake2b
>>>
>>> FANOUT = 2
>>> DEPTH = 2
>>> LEAF_SIZE = 4096
>>> INNER_SIZE = 64
>>>
>>> buf = bytearray(6000)
>>>
>>> # Left leaf
... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=0, node_depth=0, last_node=False)
>>> # Right leaf
... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=1, node_depth=0, last_node=True)
>>> # Root node
... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=0, node_depth=1, last_node=True)
>>> h10.update(h00.digest())
>>> h10.update(h01.digest())
>>> h10.hexdigest()
'3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa'
@end example

@node クレジット,,使用例<20>,BLAKE2
@anchor{library/hashlib credits}@anchor{2fe6}
@subsubsection クレジット:


BLAKE2@footnote{https://www.blake2.net} は*Jean-Philippe Aumasson*、 `Luca Henzen'、 `Willi Meier' そして `Raphael C.-W. Phan' によって作成された SHA-3@footnote{https://en.wikipedia.org/wiki/Secure_Hash_Algorithms} の最終候補である BLAKE@footnote{https://web.archive.org/web/20200918190133/https://131002.net/blake/}  を元に、`Jean-Philippe Aumasson'、 `Samuel Neves'、 `Zooko Wilcox-O'Hearn', そして `Christian Winnerlein' によって設計されました。

それは、 `Daniel J.  Bernstein' によって設計されたChaCha@footnote{https://cr.yp.to/chacha.html} 暗号由来のアルゴリズムを用いています。

標準ライブラリは pyblake2@footnote{https://pythonhosted.org/pyblake2/} モジュールを基礎として実装されています。
このモジュールは `Dmitry Chestnykh' によって、`Samuel Neves' が作成した C実装を元に書かれました。
このドキュメントは、pyblake2@footnote{https://pythonhosted.org/pyblake2/} からコピーされ、`Dmitry Chestnykh' によって書かれました。

`Christian Heimes' によって、一部のCコードがPython向けに書き直されました。

以下の public domain dedicationが、Cのハッシュ関数実装と、拡張コードと、このドキュメントに適用されます:

@quotation

To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.

You should have received a copy of the CC0 Public Domain Dedication along
with this software. If not, see
@indicateurl{https://creativecommons.org/publicdomain/zero/1.0/}.
@end quotation

The following people have helped with development or contributed their changes
to the project and the public domain according to the Creative Commons Public
Domain Dedication 1.0 Universal:


@itemize *

@item 
`Alexandr Sokolovskiy'
@end itemize
@anchor{library/hashlib hashlib-seealso}@anchor{2fc7}

@subsubheading 参考



@table @asis

@item @ref{6e,,hmac} モジュール

ハッシュを用いてメッセージ認証コードを生成するモジュールです。

@item @ref{f,,base64} モジュール

バイナリハッシュを非バイナリ環境用にエンコードするもうひとつの方法です。

@item @indicateurl{https://nvlpubs.nist.gov/nistpubs/fips/nist.fips.180-4.pdf}

The FIPS 180-4 publication on Secure Hash Algorithms.

@item @indicateurl{https://csrc.nist.gov/pubs/fips/202/final}

The FIPS 202 publication on the SHA-3 Standard.

@item @indicateurl{https://www.blake2.net/}

BLAKE2 の公式ウェブサイト

@item @indicateurl{https://en.wikipedia.org/wiki/Cryptographic_hash_function}

どのアルゴリズムにどんな既知の問題があって、それが実際に利用する際にどう影響するかについての Wikipedia の記事。

@item @indicateurl{https://www.ietf.org/rfc/rfc8018.txt}

PKCS #5: Password-Based Cryptography Specification Version 2.1

@item @indicateurl{https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf}

NIST Recommendation for Password-Based Key Derivation.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node hmac --- メッセージ認証のための鍵付きハッシュ化,secrets --- 機密を扱うために安全な乱数を生成する,hashlib --- セキュアハッシュとメッセージダイジェスト,暗号関連のサービス
@anchor{library/hmac doc}@anchor{2fe7}@anchor{library/hmac hmac-keyed-hashing-for-message-authentication}@anchor{2fe8}@anchor{library/hmac module-hmac}@anchor{6e}@anchor{library/hmac translation-repo}@anchor{2fe9}
@subsection @code{hmac} --- メッセージ認証のための鍵付きハッシュ化


@geindex module; hmac

`ソースコード:' Lib/hmac.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/hmac.py}


__________________________________________________________________


This module implements the HMAC algorithm as described by 
@geindex RFC; RFC 2104
RFC 2104@footnote{https://datatracker.ietf.org/doc/html/rfc2104.html}.
The interface allows to use any hash function with a `fixed' digest size.
In particular, extendable output functions such as SHAKE-128 or SHAKE-256
cannot be used with HMAC.

@geindex new() (hmac モジュール)
@anchor{library/hmac hmac new}@anchor{c96}
@deffn {の関数} hmac.new (key, msg=None, digestmod)

Return a new hmac object.  `key' is a bytes or bytearray object giving the
secret key.  If `msg' is present, the method call @code{update(msg)} is made.
`digestmod' is the digest name, digest constructor or module for the HMAC
object to use.  It may be any name suitable to @ref{1d2e,,hashlib.new()}.
Despite its argument position, it is required.


バージョン 3.4 で変更: 引数 `key' に bytes または bytearray オブジェクトを渡せるようになりました。引数 `msg' に @ref{6c,,hashlib} がサポートする全てのタイプを渡せるようになりました。引数 `digestmod' にハッシュアルゴリズム名を渡せるようになりました。



バージョン 3.8 で変更: The `digestmod' argument is now required.  Pass it as a keyword
argument to avoid awkwardness when you do not have an initial `msg'.

@end deffn

@geindex digest() (hmac モジュール)
@anchor{library/hmac hmac digest}@anchor{d32}
@deffn {の関数} hmac.digest (key, msg, digest)

与えられたsecret `key' と `digest' の `msg' のダイジェストを返します。この関数は @code{HMAC(key, msg, digest).digest()} に似ていますが、最適化されたCやインラインの実装を使用しており、メモリに収まるメッセージに対しては高速です。パラメータ `key' 、 `msg' 、および `digest' は、 @ref{c96,,new()} と同じ意味を持ちます。

CPython実装の詳細、最適化されたC実装は、OpenSSLがサポートするダイジェストアルゴリズムの文字列と名前が `digest' の場合にのみ使用されます。


Added in version 3.7.

@end deffn

@geindex HMAC (hmac のクラス)
@anchor{library/hmac hmac HMAC}@anchor{d33}
@deffn {クラス} hmac.HMAC

HMAC オブジェクトは以下のメソッドを持っています:
@end deffn

@geindex update() (hmac.HMAC のメソッド)
@anchor{library/hmac hmac HMAC update}@anchor{114b}
@deffn {メソッド} HMAC.update (msg)

hmac オブジェクトを `msg' で更新します。このメソッドの呼出の繰り返しは、それらの引数を全て結合した引数で単一の呼び出しをした際と同じになります。すなわち @code{m.update(a); m.update(b)}  は @code{m.update(a + b)} と等価です。


バージョン 3.4 で変更: 引数 `msg' は @ref{6c,,hashlib} がサポートしているあらゆる型のいずれかです。

@end deffn

@geindex digest() (hmac.HMAC のメソッド)
@anchor{library/hmac hmac HMAC digest}@anchor{2fea}
@deffn {メソッド} HMAC.digest ()

これまで @ref{114b,,update()} メソッドに渡されたバイト列のダイジェスト値を返します。これはコンストラクタに与えられた `digest_size' と同じ長さのバイト列で、 NUL バイトを含む非 ASCII 文字が含まれることがあります。

@cartouche
@quotation 警告 
When comparing the output of @ref{d32,,digest()} to an externally supplied
digest during a verification routine, it is recommended to use the
@ref{12e0,,compare_digest()} function instead of the @code{==} operator
to reduce the vulnerability to timing attacks.
@end quotation
@end cartouche
@end deffn

@geindex hexdigest() (hmac.HMAC のメソッド)
@anchor{library/hmac hmac HMAC hexdigest}@anchor{2feb}
@deffn {メソッド} HMAC.hexdigest ()

@ref{d32,,digest()} と似ていますが、返される文字列は倍の長さとなり、16進形式となります。これは、電子メールなどの非バイナリ環境で値を交換する場合に便利です。

@cartouche
@quotation 警告 
When comparing the output of @ref{2feb,,hexdigest()} to an externally supplied
digest during a verification routine, it is recommended to use the
@ref{12e0,,compare_digest()} function instead of the @code{==} operator
to reduce the vulnerability to timing attacks.
@end quotation
@end cartouche
@end deffn

@geindex copy() (hmac.HMAC のメソッド)
@anchor{library/hmac hmac HMAC copy}@anchor{1782}
@deffn {メソッド} HMAC.copy ()

hmac オブジェクトのコピー ("クローン") を返します。このコピーは最初の部分文字列が共通になっている文字列のダイジェスト値を効率よく計算するために使うことができます。
@end deffn

ハッシュオブジェクトには次のような属性があります:

@geindex digest_size (hmac.HMAC の属性)
@anchor{library/hmac hmac HMAC digest_size}@anchor{114e}
@deffn {の属性} HMAC.digest_size

生成された HMAC ダイジェストのバイト数。
@end deffn

@geindex block_size (hmac.HMAC の属性)
@anchor{library/hmac hmac HMAC block_size}@anchor{114c}
@deffn {の属性} HMAC.block_size

内部で使われるハッシュアルゴリズムのブロックのバイト数。


Added in version 3.4.

@end deffn

@geindex name (hmac.HMAC の属性)
@anchor{library/hmac hmac HMAC name}@anchor{114d}
@deffn {の属性} HMAC.name

このHMAC の正規名で、例えば @code{hmac-md5} のように常に小文字です。


Added in version 3.4.

@end deffn


バージョン 3.10 で変更: Removed the undocumented attributes @code{HMAC.digest_cons}, @code{HMAC.inner},
and @code{HMAC.outer}.


このモジュールは以下のヘルパ関数も提供しています:

@geindex compare_digest() (hmac モジュール)
@anchor{library/hmac hmac compare_digest}@anchor{12e0}
@deffn {の関数} hmac.compare_digest (a, b)

@code{a == b} を返します。この関数は、内容ベースの短絡的な振る舞いを避けることによってタイミング分析を防ぐよう設計されたアプローチを用い、暗号化に用いるのに相応しいものとしています。 `a' と `b' は両方が同じ型でなければなりません: (例えば @ref{2feb,,HMAC.hexdigest()} が返したような ASCII のみの) @ref{169,,str} または @ref{193,,bytes-like object} のどちらか一方。

@cartouche
@quotation 注釈 
`a' と `b' が異なる長さであったりエラーが発生した場合には、タイミング攻撃で理論上 `a' と `b' の型と長さについての情報が暴露されますが、その値は明らかになりません。
@end quotation
@end cartouche


Added in version 3.3.



バージョン 3.10 で変更: The function uses OpenSSL's @code{CRYPTO_memcmp()} internally when
available.

@end deffn


@subsubheading 参考



@table @asis

@item @ref{6c,,hashlib} モジュール

セキュアハッシュ関数を提供する Python モジュールです。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node secrets --- 機密を扱うために安全な乱数を生成する,,hmac --- メッセージ認証のための鍵付きハッシュ化,暗号関連のサービス
@anchor{library/secrets doc}@anchor{2fec}@anchor{library/secrets module-secrets}@anchor{c5}@anchor{library/secrets secrets-generate-secure-random-numbers-for-managing-secrets}@anchor{2fed}@anchor{library/secrets translation-repo}@anchor{2fee}
@subsection @code{secrets} --- 機密を扱うために安全な乱数を生成する


@geindex module; secrets


Added in version 3.6.


@c from secrets import *
@c __name__ = '<doctest>'

`ソースコード:' Lib/secrets.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/secrets.py}


__________________________________________________________________


The @code{secrets} module is used for generating cryptographically strong
random numbers suitable for managing data such as passwords, account
authentication, security tokens, and related secrets.

In particular, @code{secrets} should be used in preference to the
default pseudo-random number generator in the @ref{bd,,random} module, which
is designed for modelling and simulation, not security or cryptography.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 506
PEP 506@footnote{https://peps.python.org/pep-0506/}


@menu
* 乱数:: 
* トークンの生成:: 
* その他の関数:: 
* レシピとベストプラクティス:: 

@end menu

@node 乱数,トークンの生成,,secrets --- 機密を扱うために安全な乱数を生成する
@anchor{library/secrets random-numbers}@anchor{2fef}
@subsubsection 乱数


The @code{secrets} module provides access to the most secure source of
randomness that your operating system provides.

@geindex SystemRandom (secrets のクラス)
@anchor{library/secrets secrets SystemRandom}@anchor{2ff0}
@deffn {クラス} secrets.SystemRandom

OS が提供する最も高品質なソースを用いて乱数を生成するためのクラスです。更に詳しいことについては @ref{2b57,,random.SystemRandom} を参照してください。
@end deffn

@geindex choice() (secrets モジュール)
@anchor{library/secrets secrets choice}@anchor{2ff1}
@deffn {の関数} secrets.choice (seq)

空でないシーケンスから要素をランダムに選択して返します。
@end deffn

@geindex randbelow() (secrets モジュール)
@anchor{library/secrets secrets randbelow}@anchor{2ff2}
@deffn {の関数} secrets.randbelow (exclusive_upper_bound)

[0, `exclusive_upper_bound') の範囲のランダムな整数を返します。
@end deffn

@geindex randbits() (secrets モジュール)
@anchor{library/secrets secrets randbits}@anchor{2ff3}
@deffn {の関数} secrets.randbits (k)

ランダムな `k' ビットの非負の整数を返します。
@end deffn

@node トークンの生成,その他の関数,乱数,secrets --- 機密を扱うために安全な乱数を生成する
@anchor{library/secrets generating-tokens}@anchor{2ff4}
@subsubsection トークンの生成


The @code{secrets} module provides functions for generating secure
tokens, suitable for applications such as password resets,
hard-to-guess URLs, and similar.

@geindex token_bytes() (secrets モジュール)
@anchor{library/secrets secrets token_bytes}@anchor{2b5c}
@deffn {の関数} secrets.token_bytes (nbytes=None)

Return a random byte string containing `nbytes' number of bytes.

If `nbytes' is not specified or @code{None}, @ref{2ff5,,DEFAULT_ENTROPY}
is used instead.

@example
>>> token_bytes(16)
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
@end example
@end deffn

@geindex token_hex() (secrets モジュール)
@anchor{library/secrets secrets token_hex}@anchor{1b26}
@deffn {の関数} secrets.token_hex (nbytes=None)

Return a random text string, in hexadecimal.  The string has `nbytes'
random bytes, each byte converted to two hex digits.

If `nbytes' is not specified or @code{None}, @ref{2ff5,,DEFAULT_ENTROPY}
is used instead.

@example
>>> token_hex(16)
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
@end example
@end deffn

@geindex token_urlsafe() (secrets モジュール)
@anchor{library/secrets secrets token_urlsafe}@anchor{2ff6}
@deffn {の関数} secrets.token_urlsafe (nbytes=None)

Return a random URL-safe text string, containing `nbytes' random
bytes.  The text is Base64 encoded, so on average each byte results
in approximately 1.3 characters.

If `nbytes' is not specified or @code{None}, @ref{2ff5,,DEFAULT_ENTROPY}
is used instead.

@example
>>> token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'
@end example
@end deffn

@menu
* トークンは何バイト使うべきか？:: 

@end menu

@node トークンは何バイト使うべきか？,,,トークンの生成
@anchor{library/secrets how-many-bytes-should-tokens-use}@anchor{2ff7}
@subsubsection トークンは何バイト使うべきか？


To be secure against
brute-force attacks@footnote{https://en.wikipedia.org/wiki/Brute-force_attack},
tokens need to have sufficient randomness.  Unfortunately, what is
considered sufficient will necessarily increase as computers get more
powerful and able to make more guesses in a shorter period.  As of 2015,
it is believed that 32 bytes (256 bits) of randomness is sufficient for
the typical use-case expected for the @code{secrets} module.

独自の長さのトークンを扱いたい場合、様々な @code{token_*} 関数に @ref{19b,,int} 引数で渡すことで、トークンに使用するランダムさを明示的に指定することができます。引数はランダムさのバイト数として使用されます。

Otherwise, if no argument is provided, or if the argument is @code{None},
the @code{token_*} functions use @ref{2ff5,,DEFAULT_ENTROPY} instead.

@geindex DEFAULT_ENTROPY (secrets モジュール)
@anchor{library/secrets secrets DEFAULT_ENTROPY}@anchor{2ff5}
@deffn {データ} secrets.DEFAULT_ENTROPY

Default number of bytes of randomness used by the @code{token_*} functions.

The exact value is subject to change at any time, including during
maintenance releases.
@end deffn

@node その他の関数,レシピとベストプラクティス,トークンの生成,secrets --- 機密を扱うために安全な乱数を生成する
@anchor{library/secrets other-functions}@anchor{2ff8}
@subsubsection その他の関数


@geindex compare_digest() (secrets モジュール)
@anchor{library/secrets secrets compare_digest}@anchor{2ff9}
@deffn {の関数} secrets.compare_digest (a, b)

文字列または @ref{193,,bytes-like オブジェクト} `a' と `b' が等しければ @code{True} を、そうでなければ @code{False} を返します。比較は タイミング攻撃@footnote{https://codahale.com/a-lesson-in-timing-attacks/} のリスクを減らす "定数時間比較" の方法で行われます。詳細については @ref{12e0,,hmac.compare_digest()} を参照してください。
@end deffn

@node レシピとベストプラクティス,,その他の関数,secrets --- 機密を扱うために安全な乱数を生成する
@anchor{library/secrets recipes-and-best-practices}@anchor{2ffa}
@subsubsection レシピとベストプラクティス


This section shows recipes and best practices for using @code{secrets}
to manage a basic level of security.

8文字のアルファベットと数字を含むパスワードを生成するには:

@example
import string
import secrets
alphabet = string.ascii_letters + string.digits
password = '@w{'}.join(secrets.choice(alphabet) for i in range(8))
@end example

@cartouche
@quotation 注釈 
アプリケーションは、平文であろうと暗号化されていようと、 
@geindex Common Weakness Enumeration; CWE 257
復元可能な形式でパスワードを保存@footnote{https://cwe.mitre.org/data/definitions/257.html} してはいけません。パスワードは暗号学的に強い一方向 (非可逆) ハッシュ関数を用いてソルトしハッシュしなければなりません。
@end quotation
@end cartouche

アルファべットと数字からなり、小文字を少なくとも1つと数字を少なくとも3つ含む、10文字のパスワードを生成するには:

@example
import string
import secrets
alphabet = string.ascii_letters + string.digits
while True:
    password = '@w{'}.join(secrets.choice(alphabet) for i in range(10))
    if (any(c.islower() for c in password)
            and any(c.isupper() for c in password)
            and sum(c.isdigit() for c in password) >= 3):
        break
@end example

XKCD スタイルのパスフレーズ@footnote{https://xkcd.com/936/} を生成するには:

@example
import secrets
# On standard Linux systems, use a convenient dictionary file.
# Other platforms may need to provide their own word-list.
with open('/usr/share/dict/words') as f:
    words = [word.strip() for word in f]
    password = ' '.join(secrets.choice(words) for i in range(4))
@end example

パスワードの復元用途に適したセキュリティトークンを含む、推測しにくい一時 URL を生成するには:

@example
import secrets
url = 'https://example.com/reset=' + secrets.token_urlsafe()
@end example

@c # This modeline must appear within the last ten lines of the file.
@c kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8;

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 汎用オペレーティングシステムサービス,コマンドラインインターフェースライブラリ,暗号関連のサービス,Python 標準ライブラリ
@anchor{library/allos doc}@anchor{2ffb}@anchor{library/allos allos}@anchor{2ffc}@anchor{library/allos generic-operating-system-services}@anchor{2ffd}@anchor{library/allos translation-repo}@anchor{2ffe}
@section 汎用オペレーティングシステムサービス


本章に記述されたモジュールは、ファイルの取り扱いや時間計測のような (ほぼ)すべてのオペレーティングシステムで利用可能な機能にインターフェースを提供します。これらのインターフェースは、Unix もしくは C のインターフェースを基に作られますが、ほとんどの他のシステムで同様に利用可能です。概要を以下に記述します:

@menu
* os: os --- 雑多なオペレーティングシステムインターフェース. 雑多なオペレーティングシステムインターフェース
* io: io --- ストリームを扱うコアツール. ストリームを扱うコアツール
* time: time --- 時刻データへのアクセスと変換. 時刻データへのアクセスと変換
* logging: logging --- Python 用のログ記録手段. Python 用のログ記録手段
* logging.config: logging config --- ログ記録の環境設定. ログ記録の環境設定
* logging.handlers: logging handlers --- ログ記録ハンドラー. ログ記録ハンドラー
* platform: platform --- 実行中プラットフォームの固有情報を参照する. 実行中プラットフォームの固有情報を参照する
* errno: errno --- 標準の errno システムシンボル. 標準の errno システムシンボル
* ctypes: ctypes --- Python 用の外部関数ライブラリ. Python 用の外部関数ライブラリ

@end menu

@node os --- 雑多なオペレーティングシステムインターフェース,io --- ストリームを扱うコアツール,,汎用オペレーティングシステムサービス
@anchor{library/os doc}@anchor{2fff}@anchor{library/os module-os}@anchor{a5}@anchor{library/os os-miscellaneous-operating-system-interfaces}@anchor{3000}
@subsection @code{os} --- 雑多なオペレーティングシステムインターフェース


@geindex module; os

`ソースコード:' Lib/os.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/os.py}


__________________________________________________________________


このモジュールは、 OS 依存の機能を利用するポータブルな方法を提供します。単純なファイルの読み書きについては、 @ref{316,,open()} を参照してください。パス操作については、 @ref{a6,,os.path} モジュールを参照してください。コマンドラインに与えられたすべてのファイルから行を読み込んでいくには、 @ref{5f,,fileinput} モジュールを参照してください。一時ファイルや一時ディレクトリの作成については、 @ref{e6,,tempfile} モジュールを参照してください。高水準のファイルとディレクトリの操作については、 @ref{ca,,shutil} モジュールを参照してください。

利用可能性に関する注意 :


@itemize *

@item 
Python の、すべての OS 依存モジュールの設計方針は、可能な限り同一のインターフェースで同一の機能を利用できるようにする、というものです。例えば、 @code{os.stat(path)} は `path' に関する stat 情報を、 (POSIX を元にした ) 同じフォーマットで返します。

@item 
Extensions peculiar to a particular operating system are also available
through the @code{os} module, but using them is of course a threat to
portability.

@item 
パスやファイル名を受け付けるすべての関数は、バイト列型および文字列型両方のオブジェクトを受け付け、パスやファイル名を返す時は、同じ型のオブジェクトを返します。

@item 
VxWorks では、os.popen, os.fork, os.execv および os.spawn*p* はサポートされていません。

@item 
On WebAssembly platforms, Android and iOS, large parts of the @code{os} module are
not available or behave differently. APIs related to processes (e.g.
@ref{4b5,,fork()}, @ref{1311,,execve()}) and resources (e.g. @ref{1319,,nice()})
are not available. Others like @ref{1817,,getuid()} and @ref{3001,,getpid()} are
emulated or stubs. WebAssembly platforms also lack support for signals (e.g.
@ref{157f,,kill()}, @ref{f98,,wait()}).
@end itemize

@cartouche
@quotation 注釈 
このモジュール内のすべての関数は、間違った、あるいはアクセス出来ないファイル名やファイルパス、その他型が合っていても OS が受理しない引数に対して、 @ref{2c0,,OSError} (またはそのサブクラス)を送出します。
@end quotation
@end cartouche

@geindex error
@anchor{library/os os error}@anchor{3002}
@deffn {例外} os.error

組み込みの @ref{2c0,,OSError} 例外に対するエイリアスです。
@end deffn

@geindex name (os モジュール)
@anchor{library/os os name}@anchor{3003}
@deffn {データ} os.name

import されているオペレーティングシステムに依存するモジュールの名前です。現在次の名前が登録されています: @code{'posix'}, @code{'nt'}, @code{'java'}。


@subsubheading 参考


@ref{291,,sys.platform} はより細かな粒度を持っています。 @ref{132e,,os.uname()} はシステム依存のバージョン情報を提供します。

@ref{af,,platform} モジュールはシステムの詳細な識別情報をチェックする機能を提供しています。

@end deffn
@anchor{library/os os-filenames}@anchor{2f44}
@menu
* ファイル名、コマンドライン引数、および環境変数:: 
* Python UTF-8 Mode:: 
* プロセスのパラメーター:: 
* ファイルオブジェクトの生成:: 
* ファイル記述子の操作:: 
* ファイルとディレクトリ:: 
* プロセス管理:: 
* スケジューラーへのインターフェイス:: 
* 雑多なシステム情報:: 
* 乱数: 乱数<2>. 

@end menu

@node ファイル名、コマンドライン引数、および環境変数,Python UTF-8 Mode,,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os file-names-command-line-arguments-and-environment-variables}@anchor{3004}@anchor{library/os filesystem-encoding}@anchor{2c35}
@subsubsection ファイル名、コマンドライン引数、および環境変数


Python では、ファイル名、コマンドライン引数、および環境変数を表すのに文字列型を使用します。一部のシステムでは、これらをオペレーティングシステムに渡す前に、文字列からバイト列へ、またはその逆のデコードが必要です。Python はこの変換を行うために @ref{75d,,filesystem encoding and error handler} を使用します (@ref{e53,,sys.getfilesystemencoding()} 参照)。

term:@cite{ファイルシステムのエンコーディングとエラーハンドラ <filesystem encoding and error handler>} は、Pythonの開始時に:c:func:@cite{PyConfig_Read} 関数により設定されます。 @ref{3f7,,PyConfig} のメンバー @ref{41b,,filesystem_encoding} と @ref{41c,,filesystem_errors} を参照してください。


バージョン 3.1 で変更: 一部のシステムでは、ファイルシステムのエンコーディングを使用して変換すると失敗する場合があります。この場合、Python は  @ref{2853,,surrogateescape エンコーディングエラーハンドラー} を使用します。これは、デコード時にデコードできないバイト列は Unicode 文字 U+DC`xx' に置き換えられ、それらはエンコード時に再び元のバイト列に変換されることを意味します。


@ref{75d,,file system encoding} では、すべてが 128 バイト以下に正常にデコードされることが保証されなくてはなりません。ファイルシステムのエンコーディングでこれが保証されなかった場合は、API 関数が @ref{462,,UnicodeError} を送出します。

See also the @ref{54a,,locale encoding}.

@node Python UTF-8 Mode,プロセスのパラメーター,ファイル名、コマンドライン引数、および環境変数,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os python-utf-8-mode}@anchor{3005}@anchor{library/os utf8-mode}@anchor{866}
@subsubsection Python UTF-8 Mode



Added in version 3.7: より詳しくは 
@geindex Python Enhancement Proposals; PEP 540
PEP 540@footnote{https://peps.python.org/pep-0540/} を参照してください。


The Python UTF-8 Mode ignores the @ref{54a,,locale encoding} and forces the usage
of the UTF-8 encoding:


@itemize *

@item 
Use UTF-8 as the @ref{75d,,filesystem encoding}.

@item 
@ref{e53,,sys.getfilesystemencoding()} returns @code{'utf-8'}.

@item 
@ref{75c,,locale.getpreferredencoding()} returns @code{'utf-8'} (the `do_setlocale'
argument has no effect).

@item 
@ref{75f,,sys.stdin}, @ref{ccd,,sys.stdout}, and @ref{b33,,sys.stderr} all use
UTF-8 as their text encoding, with the @code{surrogateescape}
@ref{1b6f,,error handler} being enabled for @ref{75f,,sys.stdin}
and @ref{ccd,,sys.stdout} (@ref{b33,,sys.stderr} continues to use
@code{backslashreplace} as it does in the default locale-aware mode)

@item 
On Unix, @ref{1c35,,os.device_encoding()} returns @code{'utf-8'} rather than the
device encoding.
@end itemize

Note that the standard stream settings in UTF-8 mode can be overridden by
@geindex PYTHONIOENCODING
@geindex 環境変数; PYTHONIOENCODING
@ref{120c,,PYTHONIOENCODING} (just as they can be in the default locale-aware
mode).

As a consequence of the changes in those lower level APIs, other higher
level APIs also exhibit different default behaviours:


@itemize *

@item 
Command line arguments, environment variables and filenames are decoded
to text using the UTF-8 encoding.

@item 
@ref{e4e,,os.fsdecode()} and @ref{e4f,,os.fsencode()} use the UTF-8 encoding.

@item 
@ref{316,,open()}, @ref{740,,io.open()}, and @ref{315,,codecs.open()} use the UTF-8
encoding by default. However, they still use the strict error handler by
default so that attempting to open a binary file in text mode is likely
to raise an exception rather than producing nonsense data.
@end itemize

The @ref{866,,Python UTF-8 Mode} is enabled if the LC_CTYPE locale is
@code{C} or @code{POSIX} at Python startup (see the @ref{993,,PyConfig_Read()}
function).

It can be enabled or disabled using the @ref{16f,,-X utf8} command line
option and the 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8} environment variable.

If the 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8} environment variable is not set at all, then the
interpreter defaults to using the current locale settings, `unless' the current
locale is identified as a legacy ASCII-based locale (as described for
@geindex PYTHONCOERCECLOCALE
@geindex 環境変数; PYTHONCOERCECLOCALE
@ref{ccc,,PYTHONCOERCECLOCALE}), and locale coercion is either disabled or
fails. In such legacy locales, the interpreter will default to enabling UTF-8
mode unless explicitly instructed not to do so.

The Python UTF-8 Mode can only be enabled at the Python startup. Its value
can be read from @ref{89c,,sys.flags.utf8_mode}.

See also the @ref{221d,,UTF-8 mode on Windows}
and the @ref{75d,,filesystem encoding and error handler}.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 686

@item PEP 686@footnote{https://peps.python.org/pep-0686/}

Python 3.15 will make @ref{866,,Python UTF-8 Mode} default.
@end table


@node プロセスのパラメーター,ファイルオブジェクトの生成,Python UTF-8 Mode,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os os-procinfo}@anchor{3006}@anchor{library/os process-parameters}@anchor{3007}
@subsubsection プロセスのパラメーター


これらの関数とデータアイテムは、現在のプロセスおよびユーザーに対する情報提供および操作のための機能を提供しています。

@geindex ctermid() (os モジュール)
@anchor{library/os os ctermid}@anchor{3008}
@deffn {の関数} os.ctermid ()

プロセスの制御端末に対応するファイル名を返します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex environ (os モジュール)
@anchor{library/os os environ}@anchor{259}
@deffn {データ} os.environ

A @ref{13d3,,mapping} object where keys and values are strings that represent
the process environment.  For example, @code{environ['HOME']} is the pathname
of your home directory (on some platforms), and is equivalent to
@code{getenv("HOME")} in C.

This mapping is captured the first time the @code{os} module is imported,
typically during Python startup as part of processing @code{site.py}.  Changes
to the environment made after this time are not reflected in @ref{259,,os.environ},
except for changes made by modifying @ref{259,,os.environ} directly.

このマップ型オブジェクトは環境変数に対する変更に使うこともできます。 @ref{25b,,putenv()} はマップ型オブジェクトが修正される時に、自動的に呼ばれることになります。

Unix では、キーと値に @ref{e53,,sys.getfilesystemencoding()}、エラーハンドラーに @code{'surrogateescape'} を使用します。異なるエンコーディングを使用したい場合は @ref{25a,,environb} を使用します。

On Windows, the keys are converted to uppercase. This also applies when
getting, setting, or deleting an item. For example,
@code{environ['monty'] = 'python'} maps the key @code{'MONTY'} to the value
@code{'python'}.

@cartouche
@quotation 注釈 
@ref{25b,,putenv()} を直接呼び出しても @ref{259,,os.environ} の内容は変わらないので、 @ref{259,,os.environ} を直接変更する方が良いです。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
FreeBSD や macOS など一部のプラットフォームでは @code{environ} の値を変更するとメモリリークが発生する可能性があります。各システムのドキュメントで @code{putenv()} の項目を参照してください。
@end quotation
@end cartouche

このマップ型オブジェクトからアイテムを削除することで環境変数を消すことができます。 @ref{25c,,unsetenv()} は @ref{259,,os.environ} からアイテムが取り除かれた時に自動的に呼ばれます。 @code{pop()} または @code{clear()} が呼ばれた時も同様です。


@subsubheading 参考


The @ref{258,,os.reload_environ()} function.



バージョン 3.9 で変更: 更新され 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} の合成演算子 (@code{|}) と更新演算子 (@code{|=}) がサポートされました。

@end deffn

@geindex environb (os モジュール)
@anchor{library/os os environb}@anchor{25a}
@deffn {データ} os.environb

Bytes version of @ref{259,,environ}: a @ref{13d3,,mapping} object where both keys
and values are @ref{192,,bytes} objects representing the process environment.
@ref{259,,environ} and @ref{25a,,environb} are synchronized (modifying
@ref{25a,,environb} updates @ref{259,,environ}, and vice versa).

@ref{25a,,environb} は @ref{142e,,supports_bytes_environ} が @code{True} の場合のみ利用可能です。


Added in version 3.2.



バージョン 3.9 で変更: 更新され 
@geindex Python Enhancement Proposals; PEP 584
PEP 584@footnote{https://peps.python.org/pep-0584/} の合成演算子 (@code{|}) と更新演算子 (@code{|=}) がサポートされました。

@end deffn

@geindex reload_environ() (os モジュール)
@anchor{library/os os reload_environ}@anchor{258}
@deffn {の関数} os.reload_environ ()

The @ref{259,,os.environ} and @ref{25a,,os.environb} mappings are a cache of
environment variables at the time that Python started.
As such, changes to the current process environment are not reflected
if made outside Python, or by @ref{25b,,os.putenv()} or @ref{25c,,os.unsetenv()}.
Use @code{os.reload_environ()} to update @ref{259,,os.environ} and @ref{25a,,os.environb}
with any such changes to the current process environment.

@cartouche
@quotation 警告 
This function is not thread-safe. Calling it while the environment is
being modified in another thread is an undefined behavior. Reading from
@ref{259,,os.environ} or @ref{25a,,os.environb}, or calling @ref{3009,,os.getenv()}
while reloading, may return an empty result.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn


@deffn {の関数} os.chdir (path)

@deffnx {の関数} os.fchdir (fd)

@deffnx {の関数} os.getcwd ()

これらの関数は、 @ref{300a,,ファイルとディレクトリ} 節で説明されています。
@end deffn

@geindex fsencode() (os モジュール)
@anchor{library/os os fsencode}@anchor{e4f}
@deffn {の関数} os.fsencode (filename)

@ref{5a1,,path-like} な `filename' を @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} にエンコードします。未変更の @ref{192,,bytes} オブジェクトを返します。

@ref{e4e,,fsdecode()} はこの逆変換を行う関数です。


Added in version 3.2.



バージョン 3.6 で変更: @ref{e4b,,os.PathLike} インターフェースを実装したオブジェクトを受け入れるようになりました。

@end deffn

@geindex fsdecode() (os モジュール)
@anchor{library/os os fsdecode}@anchor{e4e}
@deffn {の関数} os.fsdecode (filename)

@ref{5a1,,path-like} な `filename' を @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} からデコードします。未変更の @ref{169,,str} オブジェクトを返します。

@ref{e4f,,fsencode()} はこの逆変換を行う関数です。


Added in version 3.2.



バージョン 3.6 で変更: @ref{e4b,,os.PathLike} インターフェースを実装したオブジェクトを受け入れるようになりました。

@end deffn

@geindex fspath() (os モジュール)
@anchor{library/os os fspath}@anchor{e4d}
@deffn {の関数} os.fspath (path)

path のファイルシステム表現を返します。

もし @ref{169,,str} か @code{bytes:} のオブジェクトが渡された場合は、変更せずにそのまま返します。さもなければ、 @ref{e4c,,__fspath__()} が呼び出され、その戻り値が @ref{169,,str} か @ref{192,,bytes} のオブジェクトであれば、その値を返します。他のすべてのケースでは @ref{198,,TypeError} が送出されます。


Added in version 3.6.

@end deffn

@geindex PathLike (os のクラス)
@anchor{library/os os PathLike}@anchor{e4b}
@deffn {クラス} os.PathLike

ファイルシステムパスを表すオブジェクト(例: @ref{6cd,,pathlib.PurePath}) 向けの @ref{13ce,,abstract base class} です。


Added in version 3.6.


@geindex __fspath__() (os.PathLike のメソッド)
@anchor{library/os os PathLike __fspath__}@anchor{e4c}
@deffn {メソッド} abstractmethod __fspath__ ()

このオブジェクトが表現するファイルシステムパスを返します。

このメソッドは @ref{169,,str} か @ref{192,,bytes} のオブジェクトのみを返す必要があります(@ref{169,,str} が好まれます)。
@end deffn
@end deffn

@geindex getenv() (os モジュール)
@anchor{library/os os getenv}@anchor{3009}
@deffn {の関数} os.getenv (key, default=None)

環境変数 `key' が存在する場合はその値を文字列として返し、存在しなければ `default' を返します。`key' は文字列です。注意すべき点として、@ref{3009,,getenv()} は内部的に @ref{259,,os.environ} を使用するため、@ref{3009,,getenv()} のマップ型オブジェクトはインポート時に取得されます。そのため、それ以降に環境変数が変更されても、この関数の値にそれが反映されない可能性があります。

Unix では、キーと値は @ref{e53,,sys.getfilesystemencoding()}、エラーハンドラー @code{'surrogateescape'} でデコードされます。異なるエンコーディングを使用したい場合は @ref{142f,,os.getenvb()} を使用します。

@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex getenvb() (os モジュール)
@anchor{library/os os getenvb}@anchor{142f}
@deffn {の関数} os.getenvb (key, default=None)

環境変数 `key' が存在する場合はその値を bytes として返し、存在しなければ `default' を返します。`key' はbytes である必要があります。注意すべき点として、@ref{142f,,getenvb()} は内部的に @ref{25a,,os.environb} を使用するため、@ref{142f,,getenvb()} のマップ型オブジェクトはインポート時に取得されます。そのため、それ以降に環境変数が変更されても、この関数の値にそれが反映されない可能性があります。

@ref{142f,,getenvb()} は @ref{142e,,supports_bytes_environ} が @code{True} の場合のみ利用可能です。

@ref{213f,,Availability}: Unix.


Added in version 3.2.

@end deffn

@geindex get_exec_path() (os モジュール)
@anchor{library/os os get_exec_path}@anchor{300b}
@deffn {の関数} os.get_exec_path (env=None)

プロセスを起動する時に名前付き実行ファイルを検索するディレクトリのリストを返します。
`env' が指定されると、それを環境変数の辞書とみなし、その辞書からキー PATH の値を探します。
デフォルトでは `env' は @code{None} であり、@ref{259,,environ} が使用されます。


Added in version 3.2.

@end deffn

@geindex getegid() (os モジュール)
@anchor{library/os os getegid}@anchor{300c}
@deffn {の関数} os.getegid ()

現在のプロセスの実効グループ id を返します。この id は現在のプロセスで実行されているファイルの "set id" ビットに対応します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex geteuid() (os モジュール)
@anchor{library/os os geteuid}@anchor{1b72}
@deffn {の関数} os.geteuid ()

@geindex ユーザー;実効 ID

現在のプロセスの実効ユーザー id を返します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex getgid() (os モジュール)
@anchor{library/os os getgid}@anchor{300d}
@deffn {の関数} os.getgid ()

@geindex process;グループ

現在のプロセスの実グループ id を返します。

@ref{213f,,Availability}: Unix.

The function is a stub on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.
@end deffn

@geindex getgrouplist() (os モジュール)
@anchor{library/os os getgrouplist}@anchor{132c}
@deffn {の関数} os.getgrouplist (user, group, /)

Return list of group ids that `user' belongs to. If `group' is not in the
list, it is included; typically, `group' is specified as the group ID
field from the password record for `user', because that group ID will
otherwise be potentially omitted.

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.3.

@end deffn

@geindex getgroups() (os モジュール)
@anchor{library/os os getgroups}@anchor{300e}
@deffn {の関数} os.getgroups ()

現在のプロセスに関連付けられた従属グループ id のリストを返します。

@ref{213f,,Availability}: Unix, not WASI.

@cartouche
@quotation 注釈 
macOS では @ref{300e,,getgroups()} の挙動は他の Unix プラットフォームとはいくぶん異なります。 Python のインタープリタが @code{10.5} 以前の Deployment Target でビルドされている場合、 @ref{300e,,getgroups()} は現在のユーザープロセスに関連付けられている実効グループ id を返します。このリストはシステムで定義されたエントリ数 ( 通常は 16) に制限され、適切な特権があれば @ref{300f,,setgroups()} の呼び出しによって変更することができます。 @code{10.5} より新しい Deployment Target でビルドされている場合、 @ref{300e,,getgroups()} はプロセスの実効ユーザー id に関連付けられたユーザーの現在のグループアクセスリストを返します。このグループアクセスリストは、プロセスのライフタイムで変更される可能性があり、 @ref{300f,,setgroups()} の呼び出しの影響を受けず、長さ 16 の制限を受けません。 Deployment Target の値 @code{MACOSX_DEPLOYMENT_TARGET} は、 @ref{174,,sysconfig.get_config_var()} で取得することができます。
@end quotation
@end cartouche
@end deffn

@geindex getlogin() (os モジュール)
@anchor{library/os os getlogin}@anchor{1822}
@deffn {の関数} os.getlogin ()

プロセスの制御端末にログインしているユーザー名を返します。ほとんどの場合、@ref{65a,,getpass.getuser()} を使う方が便利です。なぜなら、@ref{65a,,getpass.getuser()} は、ユーザーを見つけるために、環境変数 
@geindex LOGNAME
@geindex 環境変数; LOGNAME
@code{LOGNAME} や 
@geindex USERNAME
@geindex 環境変数; USERNAME
@code{USERNAME} を調べ、さらには @code{pwd.getpwuid(os.getuid())[0]} まで調べに行くからです。

@ref{213f,,Availability}: Unix, Windows, not WASI.
@end deffn

@geindex getpgid() (os モジュール)
@anchor{library/os os getpgid}@anchor{3010}
@deffn {の関数} os.getpgid (pid)

プロセス id `pid' のプロセスのプロセスグループ id を返します。 `pid' が 0 の場合、現在のプロセスのプロセスグループ id を返します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex getpgrp() (os モジュール)
@anchor{library/os os getpgrp}@anchor{3011}
@deffn {の関数} os.getpgrp ()

@geindex process;グループ

現在のプロセスグループの id を返します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex getpid() (os モジュール)
@anchor{library/os os getpid}@anchor{3001}
@deffn {の関数} os.getpid ()

@geindex process;id

現在のプロセス id を返します。

The function is a stub on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.
@end deffn

@geindex getppid() (os モジュール)
@anchor{library/os os getppid}@anchor{19cc}
@deffn {の関数} os.getppid ()

@geindex process;親の ID

親プロセスのプロセス id を返します。親プロセスが終了していた場合、Unix では init プロセスの id (1) が返され、Windows では親のプロセス id だったもの (別のプロセスで再利用されているかもしれない) がそのまま返されます。

@ref{213f,,Availability}: Unix, Windows, not WASI.


バージョン 3.2 で変更: Windows サポートが追加されました。

@end deffn

@geindex getpriority() (os モジュール)
@anchor{library/os os getpriority}@anchor{1317}
@deffn {の関数} os.getpriority (which, who)

@geindex process;スケジューリング優先度

プログラムのスケジューリング優先度を取得します。`which' の値は @ref{3012,,PRIO_PROCESS}、@ref{3013,,PRIO_PGRP}、あるいは @ref{3014,,PRIO_USER} のいずれか一つで、`who' の値は `which' に応じて解釈されます (@ref{3012,,PRIO_PROCESS} であればプロセス識別子、@ref{3013,,PRIO_PGRP} であればプロセスグループ識別子、そして @ref{3014,,PRIO_USER} であればユーザー ID)。`who' の値がゼロの場合、呼び出したプロセス、呼び出したプロセスのプロセスグループ、および呼び出したプロセスの実ユーザー id を (それぞれ) 意味します。

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.3.

@end deffn

@geindex PRIO_PROCESS (os モジュール)
@geindex PRIO_PGRP (os モジュール)
@geindex PRIO_USER (os モジュール)
@anchor{library/os os PRIO_PROCESS}@anchor{3012}
@deffn {データ} os.PRIO_PROCESS
@anchor{library/os os PRIO_PGRP}@anchor{3013}
@deffnx {データ} os.PRIO_PGRP
@anchor{library/os os PRIO_USER}@anchor{3014}
@deffnx {データ} os.PRIO_USER

@ref{1317,,getpriority()} と @ref{1318,,setpriority()} 用のパラメータです。

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.3.

@end deffn

@geindex PRIO_DARWIN_THREAD (os モジュール)
@geindex PRIO_DARWIN_PROCESS (os モジュール)
@geindex PRIO_DARWIN_BG (os モジュール)
@geindex PRIO_DARWIN_NONUI (os モジュール)
@anchor{library/os os PRIO_DARWIN_THREAD}@anchor{3015}
@deffn {データ} os.PRIO_DARWIN_THREAD
@anchor{library/os os PRIO_DARWIN_PROCESS}@anchor{3016}
@deffnx {データ} os.PRIO_DARWIN_PROCESS
@anchor{library/os os PRIO_DARWIN_BG}@anchor{3017}
@deffnx {データ} os.PRIO_DARWIN_BG
@anchor{library/os os PRIO_DARWIN_NONUI}@anchor{3018}
@deffnx {データ} os.PRIO_DARWIN_NONUI

@ref{1317,,getpriority()} と @ref{1318,,setpriority()} 用のパラメータです。

@ref{213f,,Availability}: macOS


Added in version 3.12.

@end deffn

@geindex getresuid() (os モジュール)
@anchor{library/os os getresuid}@anchor{152d}
@deffn {の関数} os.getresuid ()

現在のプロセスの実ユーザー id 、実効ユーザー id 、および保存ユーザー id を示す、 (ruid, euid, suid) のタプルを返します。

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.2.

@end deffn

@geindex getresgid() (os モジュール)
@anchor{library/os os getresgid}@anchor{152c}
@deffn {の関数} os.getresgid ()

現在のプロセスの実グループ id 、実効グループ id 、および保存グループ id を示す、 (rgid, egid, sgid) のタプルを返します。

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.2.

@end deffn

@geindex getuid() (os モジュール)
@anchor{library/os os getuid}@anchor{1817}
@deffn {の関数} os.getuid ()

@geindex ユーザー;id

現在のプロセスの実ユーザー id を返します。

@ref{213f,,Availability}: Unix.

The function is a stub on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.
@end deffn

@geindex initgroups() (os モジュール)
@anchor{library/os os initgroups}@anchor{1530}
@deffn {の関数} os.initgroups (username, gid, /)

Call the system @code{initgroups()} to initialize the group access list with all of
the groups of which the specified username is a member, plus the specified
group id.

@ref{213f,,Availability}: Unix, not WASI, not Android.


Added in version 3.2.

@end deffn

@geindex putenv() (os モジュール)
@anchor{library/os os putenv}@anchor{25b}
@deffn {の関数} os.putenv (key, value, /)

@geindex 環境変数;設定

`key' という名前の環境変数に文字列 `value' を設定します。このような環境変数の変更は、@ref{1676,,os.system()}、@ref{31a,,popen()}、または @ref{4b5,,fork()} と @ref{3019,,execv()} で起動されたサブプロセスに影響を与えます。

@ref{259,,os.environ} の要素に代入すると、それは @ref{25b,,putenv()} の呼び出しに自動変換されます。
しかし、直接 @ref{25b,,putenv()} を呼び出しても @ref{259,,os.environ} には反映されないため、@ref{259,,os.environ} の要素に代入する方がベターです。
@ref{3009,,getenv()} と @ref{142f,,getenvb()} についても、実装上それぞれ @ref{259,,os.environ} と @ref{25a,,os.environb} を使用するので、同様に注意が必要です。

See also the @ref{258,,os.reload_environ()} function.

@cartouche
@quotation 注釈 
FreeBSD や macOS など一部のプラットフォームでは @code{environ} の値を変更するとメモリリークが発生する可能性があります。
各システムのドキュメントで @code{putenv()} の項目を参照してください。
@end quotation
@end cartouche

引数 @code{key}, @code{value} を指定して @ref{1c6e,,監査イベント} @code{os.putenv} を送出します。


バージョン 3.9 で変更: 常に利用出来るようになりました。

@end deffn

@geindex setegid() (os モジュール)
@anchor{library/os os setegid}@anchor{301a}
@deffn {の関数} os.setegid (egid, /)

現在のプロセスに実効グループ id をセットします。

@ref{213f,,Availability}: Unix, not WASI, not Android.
@end deffn

@geindex seteuid() (os モジュール)
@anchor{library/os os seteuid}@anchor{301b}
@deffn {の関数} os.seteuid (euid, /)

現在のプロセスに実効ユーザー id をセットします。

@ref{213f,,Availability}: Unix, not WASI, not Android.
@end deffn

@geindex setgid() (os モジュール)
@anchor{library/os os setgid}@anchor{301c}
@deffn {の関数} os.setgid (gid, /)

現在のプロセスにグループ id をセットします。

@ref{213f,,Availability}: Unix, not WASI, not Android.
@end deffn

@geindex setgroups() (os モジュール)
@anchor{library/os os setgroups}@anchor{300f}
@deffn {の関数} os.setgroups (groups, /)

現在のグループに関連付けられた従属グループ id のリストを `groups' に設定します。 `groups' はシーケンス型でなくてはならず、各要素はグループを特定する整数でなくてはなりません。通常、この操作はスーパユーザーしか利用できません。

@ref{213f,,Availability}: Unix, not WASI.

@cartouche
@quotation 注釈 
macOS では、 `groups' の長さはシステムで定義された実効グループ id の最大数 ( 通常は 16) を超えない場合があります。 setgroups() 呼び出しで設定されたものと同じグループリストが返されないケースについては、 @ref{300e,,getgroups()} のドキュメントを参照してください。
@end quotation
@end cartouche
@end deffn

@geindex setns() (os モジュール)
@anchor{library/os os setns}@anchor{1b41}
@deffn {の関数} os.setns (fd, nstype=0)

Reassociate the current thread with a Linux namespace.
See the @code{setns(2)@footnote{https://manpages.debian.org/setns(2)}} and @code{namespaces(7)@footnote{https://manpages.debian.org/namespaces(7)}} man pages for more
details.

If `fd' refers to a @code{/proc/`pid'/ns/} link, @code{setns()} reassociates the
calling thread with the namespace associated with that link,
and `nstype' may be set to one of the
@ref{301d,,CLONE_NEW* constants}
to impose constraints on the operation
(@code{0} means no constraints).

Since Linux 5.8, `fd' may refer to a PID file descriptor obtained from
@ref{6a4,,pidfd_open()}. In this case, @code{setns()} reassociates the calling thread
into one or more of the same namespaces as the thread referred to by `fd'.
This is subject to any constraints imposed by `nstype',
which is a bit mask combining one or more of the
@ref{301d,,CLONE_NEW* constants},
e.g. @code{setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID)}.
The caller's memberships in unspecified namespaces are left unchanged.

`fd' can be any object with a @ref{17ad,,fileno()} method, or a raw file descriptor.

This example reassociates the thread with the @code{init} process's network namespace:

@example
fd = os.open("/proc/1/ns/net", os.O_RDONLY)
os.setns(fd, os.CLONE_NEWNET)
os.close(fd)
@end example

@ref{213f,,Availability}: Linux >= 3.0 with glibc >= 2.14.


Added in version 3.12.



@subsubheading 参考


The @ref{1b42,,unshare()} function.

@end deffn

@geindex setpgrp() (os モジュール)
@anchor{library/os os setpgrp}@anchor{301e}
@deffn {の関数} os.setpgrp ()

システムコール @code{setpgrp()} か @code{setpgrp(0, 0)} のどちらか(実装されているもの)を呼び出します。機能については UNIX マニュアルを参照して下さい。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex setpgid() (os モジュール)
@anchor{library/os os setpgid}@anchor{301f}
@deffn {の関数} os.setpgid (pid, pgrp, /)

システムコール @code{setpgid()} を呼び出してプロセス id `pid' のプロセスのプロセスグループ id を `pgrp' に設定します。この動作に関しては Unix のマニュアルを参照してください。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex setpriority() (os モジュール)
@anchor{library/os os setpriority}@anchor{1318}
@deffn {の関数} os.setpriority (which, who, priority)

@geindex process;スケジューリング優先度

プログラムのスケジューリング優先度を設定します。`which' は @ref{3012,,PRIO_PROCESS}、@ref{3013,,PRIO_PGRP}、あるいは @ref{3014,,PRIO_USER} のいずれか一つで、`who' の値は `which' に応じて解釈されます (@ref{3012,,PRIO_PROCESS} であればプロセス識別子、@ref{3013,,PRIO_PGRP} であればプロセスグループ識別子、そして @ref{3014,,PRIO_USER} であればユーザー ID)。`who' の値がゼロの場合、呼び出したプロセス、呼び出したプロセスのプロセスグループ、および呼び出したプロセスの実ユーザー id を (それぞれ) 意味します。`priority' は -20 から 19 の整数値で、デフォルトの優先度は 0 です。小さい数値ほど優先されるスケジューリングとなります。

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.3.

@end deffn

@geindex setregid() (os モジュール)
@anchor{library/os os setregid}@anchor{3020}
@deffn {の関数} os.setregid (rgid, egid, /)

現在のプロセスの実グループ id および実効グループ id を設定します。

@ref{213f,,Availability}: Unix, not WASI, not Android.
@end deffn

@geindex setresgid() (os モジュール)
@anchor{library/os os setresgid}@anchor{152e}
@deffn {の関数} os.setresgid (rgid, egid, sgid, /)

現在のプロセスの、実グループ id 、実効グループ id 、および保存グループ id を設定します。

@ref{213f,,Availability}: Unix, not WASI, not Android.


Added in version 3.2.

@end deffn

@geindex setresuid() (os モジュール)
@anchor{library/os os setresuid}@anchor{152f}
@deffn {の関数} os.setresuid (ruid, euid, suid, /)

現在のプロセスの実ユーザー id 、実効ユーザー id 、および保存ユーザー id を設定します。

@ref{213f,,Availability}: Unix, not WASI, not Android.


Added in version 3.2.

@end deffn

@geindex setreuid() (os モジュール)
@anchor{library/os os setreuid}@anchor{3021}
@deffn {の関数} os.setreuid (ruid, euid, /)

現在のプロセスの実ユーザー id および実効ユーザー id を設定します。

@ref{213f,,Availability}: Unix, not WASI, not Android.
@end deffn

@geindex getsid() (os モジュール)
@anchor{library/os os getsid}@anchor{3022}
@deffn {の関数} os.getsid (pid, /)

@code{getsid()} システムコールを呼び出します。機能については Unix のマニュアルを参照してください。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex setsid() (os モジュール)
@anchor{library/os os setsid}@anchor{1dba}
@deffn {の関数} os.setsid ()

@code{setsid()} システムコールを呼び出します。機能については Unix のマニュアルを参照してください。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex setuid() (os モジュール)
@anchor{library/os os setuid}@anchor{3023}
@deffn {の関数} os.setuid (uid, /)

@geindex ユーザー;ID、設定

現在のプロセスのユーザー id を設定します。

@ref{213f,,Availability}: Unix, not WASI, not Android.
@end deffn

@c placed in this section since it relates to errno.... a little weak

@geindex strerror() (os モジュール)
@anchor{library/os os strerror}@anchor{3024}
@deffn {の関数} os.strerror (code, /)

エラーコード `code' に対応するエラーメッセージを返します。未知のエラーコードの対して @code{strerror()} が @code{NULL} を返すプラットフォームでは、 @ref{2ec,,ValueError} が送出されます。
@end deffn

@geindex supports_bytes_environ (os モジュール)
@anchor{library/os os supports_bytes_environ}@anchor{142e}
@deffn {データ} os.supports_bytes_environ

環境のネイティブ OS タイプがバイト型の場合、 @code{True} です (例: Windows では、 @code{False} です)。


Added in version 3.2.

@end deffn

@geindex umask() (os モジュール)
@anchor{library/os os umask}@anchor{3025}
@deffn {の関数} os.umask (mask, /)

現在の数値 umask を設定し、以前の umask 値を返します。

The function is a stub on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.
@end deffn

@geindex uname() (os モジュール)
@anchor{library/os os uname}@anchor{132e}
@deffn {の関数} os.uname ()

@geindex gethostname() (socket モジュール)
@geindex gethostbyaddr() (socket モジュール)

現在のオペレーティングシステムを識別する情報を返します。返り値は 5 個の属性を持つオブジェクトです:


@itemize *

@item 
@code{sysname} - OS の名前

@item 
@code{nodename} - (実装時に定義された) ネットワーク上でのマシン名

@item 
@code{release} - OS のリリース

@item 
@code{version} - OS のバージョン

@item 
@code{machine} - ハードウェア識別子
@end itemize

後方互換性のため、このオブジェクトはイテラブルでもあり、@code{sysname}、@code{nodename}、@code{release}、@code{version}、および @code{machine} の 5 個の要素をこの順序で持つタプルのように振る舞います。

一部のシステムでは、@code{nodename} はコンポーネントを読み込むために 8 文字または先頭の要素だけに切り詰められます; ホスト名を取得する方法としては、@ref{3026,,socket.gethostname()} を使う方がよいでしょう。あるいは @code{socket.gethostbyaddr(socket.gethostname())} でもかまいません。

On macOS, iOS and Android, this returns the `kernel' name and version (i.e.,
@code{'Darwin'} on macOS and iOS; @code{'Linux'} on Android). @ref{1e13,,platform.uname()}
can be used to get the user-facing operating system name and version on iOS and
Android.

@ref{213f,,Availability}: Unix.


バージョン 3.3 で変更: 返り値の型が、タプルから属性名のついたタプルライクオブジェクトに変更されました。

@end deffn

@geindex unsetenv() (os モジュール)
@anchor{library/os os unsetenv}@anchor{25c}
@deffn {の関数} os.unsetenv (key, /)

@geindex 環境変数;削除

`key' という名前の環境変数を unset (削除) します。このような環境変数の変更は、@ref{1676,,os.system()}、@ref{31a,,popen()}、または @ref{4b5,,fork()} と @ref{3019,,execv()} で起動されたサブプロセスに影響を与えます。

@ref{259,,os.environ} のアイテムの削除を行うと、自動的に @ref{25c,,unsetenv()} の対応する呼び出しに変換されます。直接 @ref{25c,,unsetenv()} を呼び出した場合 @ref{259,,os.environ} は更新されないため、実際には @ref{259,,os.environ} のアイテムを削除する方が望ましい操作です。

See also the @ref{258,,os.reload_environ()} function.

引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{os.unsetenv} を送出します。


バージョン 3.9 で変更: 常に関数は利用出来るようになりました。

@end deffn

@geindex unshare() (os モジュール)
@anchor{library/os os unshare}@anchor{1b42}
@deffn {の関数} os.unshare (flags)

Disassociate parts of the process execution context, and move them into a
newly created namespace.
See the @code{unshare(2)@footnote{https://manpages.debian.org/unshare(2)}}
man page for more details.
The `flags' argument is a bit mask, combining zero or more of the
@ref{301d,,CLONE_* constants},
that specifies which parts of the execution context should be
unshared from their existing associations and moved to a new namespace.
If the `flags' argument is @code{0}, no changes are made to the calling process's
execution context.

@ref{213f,,Availability}: Linux >= 2.6.16.


Added in version 3.12.



@subsubheading 参考


@ref{1b41,,setns()} 関数。

@end deffn
@anchor{library/os os-unshare-clone-flags}@anchor{301d}
Flags to the @ref{1b42,,unshare()} function, if the implementation supports them.
See @code{unshare(2)@footnote{https://manpages.debian.org/unshare(2)}} in the Linux manual
for their exact effect and availability.

@geindex CLONE_FILES (os モジュール)
@geindex CLONE_FS (os モジュール)
@geindex CLONE_NEWCGROUP (os モジュール)
@geindex CLONE_NEWIPC (os モジュール)
@geindex CLONE_NEWNET (os モジュール)
@geindex CLONE_NEWNS (os モジュール)
@geindex CLONE_NEWPID (os モジュール)
@geindex CLONE_NEWTIME (os モジュール)
@geindex CLONE_NEWUSER (os モジュール)
@geindex CLONE_NEWUTS (os モジュール)
@geindex CLONE_SIGHAND (os モジュール)
@geindex CLONE_SYSVSEM (os モジュール)
@geindex CLONE_THREAD (os モジュール)
@geindex CLONE_VM (os モジュール)
@anchor{library/os os CLONE_FILES}@anchor{3027}
@deffn {データ} os.CLONE_FILES
@anchor{library/os os CLONE_FS}@anchor{3028}
@deffnx {データ} os.CLONE_FS
@anchor{library/os os CLONE_NEWCGROUP}@anchor{3029}
@deffnx {データ} os.CLONE_NEWCGROUP
@anchor{library/os os CLONE_NEWIPC}@anchor{302a}
@deffnx {データ} os.CLONE_NEWIPC
@anchor{library/os os CLONE_NEWNET}@anchor{302b}
@deffnx {データ} os.CLONE_NEWNET
@anchor{library/os os CLONE_NEWNS}@anchor{302c}
@deffnx {データ} os.CLONE_NEWNS
@anchor{library/os os CLONE_NEWPID}@anchor{302d}
@deffnx {データ} os.CLONE_NEWPID
@anchor{library/os os CLONE_NEWTIME}@anchor{302e}
@deffnx {データ} os.CLONE_NEWTIME
@anchor{library/os os CLONE_NEWUSER}@anchor{302f}
@deffnx {データ} os.CLONE_NEWUSER
@anchor{library/os os CLONE_NEWUTS}@anchor{3030}
@deffnx {データ} os.CLONE_NEWUTS
@anchor{library/os os CLONE_SIGHAND}@anchor{3031}
@deffnx {データ} os.CLONE_SIGHAND
@anchor{library/os os CLONE_SYSVSEM}@anchor{3032}
@deffnx {データ} os.CLONE_SYSVSEM
@anchor{library/os os CLONE_THREAD}@anchor{3033}
@deffnx {データ} os.CLONE_THREAD
@anchor{library/os os CLONE_VM}@anchor{3034}
@deffnx {データ} os.CLONE_VM
@end deffn

@node ファイルオブジェクトの生成,ファイル記述子の操作,プロセスのパラメーター,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os file-object-creation}@anchor{3035}@anchor{library/os os-newstreams}@anchor{3036}
@subsubsection ファイルオブジェクトの生成


以下の関数は新しい @ref{13db,,ファイルオブジェクト} を作成します。(ファイル記述子のオープンについては @ref{f92,,open()} も参照してください)

@geindex fdopen() (os モジュール)
@anchor{library/os os fdopen}@anchor{2381}
@deffn {の関数} os.fdopen (fd, *args, **kwargs)

ファイル記述子 `fd' に接続し、オープンしたファイルオブジェクトを返します。これは組み込み関数 @ref{316,,open()} の別名であり、同じ引数を受け取ります。唯一の違いは @ref{2381,,fdopen()} の第一引数が常に整数でなければならないことです。
@end deffn

@node ファイル記述子の操作,ファイルとディレクトリ,ファイルオブジェクトの生成,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os file-descriptor-operations}@anchor{3037}@anchor{library/os os-fd-ops}@anchor{3038}
@subsubsection ファイル記述子の操作


これらの関数は、ファイル記述子を使って参照されている I/O ストリームを操作します。

ファイル記述子とは現在のプロセスで開かれたファイルに対応する小さな整数です。例えば、標準入力のファイル記述子は通常 0 で、標準出力は 1 、標準エラーは 2 です。プロセスから開かれたその他のファイルには 3 、 4 、 5 と割り振られていきます。「ファイル記述子」という名称は少し誤解を与えるものかもしれません。Unix プラットフォームでは、ソケットやパイプもファイル記述子によって参照されます。

@ref{17ad,,fileno()} メソッドを使用して、必要な場合に @ref{13db,,file object} に関連付けられているファイル記述子を取得することができます。ファイル記述子を直接使用すると、ファイルオブジェクトのメソッドが使用されないため、データの内部バッファなどの性質は無視されることに注意してください。

@geindex close() (os モジュール)
@anchor{library/os os close}@anchor{d6b}
@deffn {の関数} os.close (fd)

ファイル記述子 `fd' をクローズします。

@cartouche
@quotation 注釈 
この関数は低水準の I/O 向けのもので、 @ref{f92,,os.open()} や @ref{1b64,,pipe()} が返すファイル記述子に対して使用しなければなりません。
組み込み関数 @ref{316,,open()} や @ref{31a,,popen()} 、 @ref{2381,,fdopen()} が返す "ファイルオブジェクト" を閉じるには、オブジェクトの @ref{506,,close()} メソッドを使用してください。
@end quotation
@end cartouche
@end deffn

@geindex closerange() (os モジュール)
@anchor{library/os os closerange}@anchor{3039}
@deffn {の関数} os.closerange (fd_low, fd_high, /)

`fd_low' 以上 `fd_high' 未満のすべてのファイル記述子をエラーを無視してクローズします。以下のコードと等価です:

@example
for fd in range(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass
@end example
@end deffn

@geindex copy_file_range() (os モジュール)
@anchor{library/os os copy_file_range}@anchor{18b4}
@deffn {の関数} os.copy_file_range (src, dst, count, offset_src=None, offset_dst=None)

Copy `count' bytes from file descriptor `src', starting from offset
`offset_src', to file descriptor `dst', starting from offset `offset_dst'.
If `offset_src' is @code{None}, then `src' is read from the current position;
respectively for `offset_dst'.

In Linux kernel older than 5.3, the files pointed to by `src' and `dst'
must reside in the same filesystem, otherwise an @ref{2c0,,OSError} is
raised with @ref{17b3,,errno} set to @ref{303a,,errno.EXDEV}.

This copy is done without the additional cost of transferring data
from the kernel to user space and then back into the kernel. Additionally,
some filesystems could implement extra optimizations, such as the use of
reflinks (i.e., two or more inodes that share pointers to the same
copy-on-write disk blocks; supported file systems include btrfs and XFS)
and server-side copy (in the case of NFS).

The function copies bytes between two file descriptors. Text options, like
the encoding and the line ending, are ignored.

返り値はコピーされたバイトの量です。
この値は、要求した量より少なくなることもあります。

@cartouche
@quotation 注釈 
On Linux, @ref{18b4,,os.copy_file_range()} should not be used for copying a
range of a pseudo file from a special filesystem like procfs and sysfs.
It will always copy no bytes and return 0 as if the file was empty
because of a known Linux kernel issue.
@end quotation
@end cartouche

@ref{213f,,Availability}: Linux >= 4.5 with glibc >= 2.27.


Added in version 3.8.

@end deffn

@geindex device_encoding() (os モジュール)
@anchor{library/os os device_encoding}@anchor{1c35}
@deffn {の関数} os.device_encoding (fd)

`fd' に関連付けられたデバイスが端末 (ターミナル) に接続されている場合に、そのデバイスのエンコーディングを表す文字列を返します。端末に接続されていない場合、 @ref{885,,None} を返します。

On Unix, if the @ref{866,,Python UTF-8 Mode} is enabled, return
@code{'UTF-8'} rather than the device encoding.


バージョン 3.10 で変更: On Unix, the function now implements the Python UTF-8 Mode.

@end deffn

@geindex dup() (os モジュール)
@anchor{library/os os dup}@anchor{1dc2}
@deffn {の関数} os.dup (fd, /)

ファイル記述子 `fd' の複製を返します。新しいファイル記述子は @ref{10fc,,継承不可} です。

Windows では、標準ストリーム (0: 標準入力、1: 標準出力、2: 標準エラー出力) を複製する場合、新しいファイル記述子は @ref{10fc,,継承可能} です。

@ref{213f,,Availability}: not WASI.


バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。

@end deffn

@geindex dup2() (os モジュール)
@anchor{library/os os dup2}@anchor{d5a}
@deffn {の関数} os.dup2 (fd, fd2, inheritable=True)

ファイル記述子 `fd' を `fd2' に複製し、必要な場合には後者を先に閉じます。
`fd2' が返ります。
新しいファイル記述子はデフォルトでは @ref{10fc,,継承可能} で、`inheritable' が @code{False} の場合は継承不可です。

@ref{213f,,Availability}: not WASI.


バージョン 3.4 で変更: オプションの `inheritable' 引数が追加されました。



バージョン 3.7 で変更: 成功したときは `fd2' が返ります。
以前は常に @code{None} が返っていました。

@end deffn

@geindex fchmod() (os モジュール)
@anchor{library/os os fchmod}@anchor{52a}
@deffn {の関数} os.fchmod (fd, mode)

`fd' で指定されたファイルのモードを `mode' に変更します。`mode' に指定できる値については、@ref{529,,chmod()} のドキュメントを参照してください。Python 3.3 以降では @code{os.chmod(fd, mode)} と等価です。

引数 @code{path}, @code{mode}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.chmod} を送出します。

@ref{213f,,Availability}: Unix, Windows.

The function is limited on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.


バージョン 3.13 で変更: Added support on Windows.

@end deffn

@geindex fchown() (os モジュール)
@anchor{library/os os fchown}@anchor{f8a}
@deffn {の関数} os.fchown (fd, uid, gid)

`fd' で指定されたファイルの所有者 id およびグループ id を数値 `uid' および `gid' に変更します。いずれかの id を変更せずにおくにはその値として -1 を指定します。@ref{1306,,chown()} を参照してください。Python 3.3 以降では @code{os.chown(fd, uid, gid)} と等価です。

引数 @code{path}, @code{uid}, @code{gid}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.chown} を送出します。

@ref{213f,,Availability}: Unix.

The function is limited on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.
@end deffn

@geindex fdatasync() (os モジュール)
@anchor{library/os os fdatasync}@anchor{f8b}
@deffn {の関数} os.fdatasync (fd)

ファイル記述子 `fd' を持つファイルのディスクへの書き込みを強制します。メタデータの更新は強制しません。

@ref{213f,,Availability}: Unix.

@cartouche
@quotation 注釈 
この関数は MacOS では利用できません。
@end quotation
@end cartouche
@end deffn

@geindex fpathconf() (os モジュール)
@anchor{library/os os fpathconf}@anchor{303b}
@deffn {の関数} os.fpathconf (fd, name, /)

開いているファイルに関連するシステム設定情報を返します。 `name' は取得する設定名を指定します。これは、いくつかの標準 (POSIX.1 、 Unix 95 、 Unix 98 その他 ) で定義された定義済みのシステム値名の文字列である場合があります。プラットフォームによっては別の名前も定義されています。ホストオペレーティングシステムの関知する名前は @code{pathconf_names} 辞書で与えられています。このマップ型オブジェクトに含まれていない構成変数については、 `name' に整数を渡してもかまいません。

`name' が不明の文字列である場合、 @ref{2ec,,ValueError} を送出します。 `name' の特定の値がホストシステムでサポートされていない場合、 @code{pathconf_names} に含まれていたとしても、 @ref{1dd2,,errno.EINVAL} をエラー番号として @ref{2c0,,OSError} を送出します。

Python 3.3 以降では @code{os.pathconf(fd, name)} と等価です。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex fstat() (os モジュール)
@anchor{library/os os fstat}@anchor{f8c}
@deffn {の関数} os.fstat (fd)

ファイル記述子 `fd' の状態を取得します。@ref{16da,,stat_result} オブジェクトを返します。

Python 3.3 以降では @code{os.stat(fd)} と等価です。


@subsubheading 参考


@ref{26d,,stat()} 関数。

@end deffn

@geindex fstatvfs() (os モジュール)
@anchor{library/os os fstatvfs}@anchor{f8d}
@deffn {の関数} os.fstatvfs (fd, /)

@ref{1314,,statvfs()} と同様に、ファイル記述子 `fd' に関連付けられたファイルが格納されているファイルシステムに関する情報を返します。Python 3.3 以降では @code{os.statvfs(fd)} と等価です。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex fsync() (os モジュール)
@anchor{library/os os fsync}@anchor{f8e}
@deffn {の関数} os.fsync (fd)

ファイル記述子 `fd' を持つファイルのディスクへの書き込みを強制します。 Unix では、ネイティブの @code{fsync()} 関数を、 Windows では @code{_commit()} 関数を呼び出します。

Python の @ref{13db,,ファイルオブジェクト} `f' を使う場合、`f' の内部バッファを確実にディスクに書き込むために、まず @code{f.flush()} を、その後 @code{os.fsync(f.fileno())} を実行してください。

@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex ftruncate() (os モジュール)
@anchor{library/os os ftruncate}@anchor{f8f}
@deffn {の関数} os.ftruncate (fd, length, /)

ファイル記述子 `fd' に対応するファイルを、サイズが最長で `length' バイトになるように切り詰めます。Python 3.3 以降では @code{os.truncate(fd, length)} と等価です。

引数 @code{fd}, @code{length} を指定して @ref{1c6e,,監査イベント} @code{os.truncate} を送出します。

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.5 で変更: Windows サポートを追加しました。

@end deffn

@geindex get_blocking() (os モジュール)
@anchor{library/os os get_blocking}@anchor{1039}
@deffn {の関数} os.get_blocking (fd, /)

記述子のブロッキングモードを取得します。
@ref{103b,,O_NONBLOCK} フラグが設定されている場合は @code{False} で、フラグがクリアされている場合は @code{True} です。

@ref{103a,,set_blocking()} および @ref{303c,,socket.socket.setblocking()} も参照してください。

@ref{213f,,Availability}: Unix, Windows.

The function is limited on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.

On Windows, this function is limited to pipes.


Added in version 3.5.



バージョン 3.12 で変更: Added support for pipes on Windows.

@end deffn

@geindex grantpt() (os モジュール)
@anchor{library/os os grantpt}@anchor{19fe}
@deffn {の関数} os.grantpt (fd, /)

Grant access to the slave pseudo-terminal device associated with the
master pseudo-terminal device to which the file descriptor `fd' refers.
The file descriptor `fd' is not closed upon failure.

Calls the C standard library function @code{grantpt()}.

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.13.

@end deffn

@geindex isatty() (os モジュール)
@anchor{library/os os isatty}@anchor{1c34}
@deffn {の関数} os.isatty (fd, /)

ファイル記述子 `fd' がオープンされていて、 tty (のような) デバイスに接続されている場合、 @code{True} を返します。そうでない場合は @code{False} を返します。
@end deffn

@geindex lockf() (os モジュール)
@anchor{library/os os lockf}@anchor{132b}
@deffn {の関数} os.lockf (fd, cmd, len, /)

オープンされたファイル記述子に対して、POSIX ロックの適用、テスト、解除を行います。`fd' はオープンされたファイル記述子です。`cmd' には使用するコマンド (@ref{303d,,F_LOCK}、@ref{303e,,F_TLOCK}、@ref{303f,,F_ULOCK}、あるいは @ref{3040,,F_TEST} のいずれか一つ) を指定します。`len' にはロックするファイルのセクションを指定します。

引数 @code{fd}, @code{cmd}, @code{len} を指定して @ref{1c6e,,監査イベント} @code{os.lockf} を送出します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex F_LOCK (os モジュール)
@geindex F_TLOCK (os モジュール)
@geindex F_ULOCK (os モジュール)
@geindex F_TEST (os モジュール)
@anchor{library/os os F_LOCK}@anchor{303d}
@deffn {データ} os.F_LOCK
@anchor{library/os os F_TLOCK}@anchor{303e}
@deffnx {データ} os.F_TLOCK
@anchor{library/os os F_ULOCK}@anchor{303f}
@deffnx {データ} os.F_ULOCK
@anchor{library/os os F_TEST}@anchor{3040}
@deffnx {データ} os.F_TEST

@ref{132b,,lockf()} がとる動作を指定するフラグです。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex login_tty() (os モジュール)
@anchor{library/os os login_tty}@anchor{1aca}
@deffn {の関数} os.login_tty (fd, /)

Prepare the tty of which fd is a file descriptor for a new login session.
Make the calling process a session leader; make the tty the controlling tty,
the stdin, the stdout, and the stderr of the calling process; close fd.

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.11.

@end deffn

@geindex lseek() (os モジュール)
@anchor{library/os os lseek}@anchor{132f}
@deffn {の関数} os.lseek (fd, pos, whence, /)

Set the current position of file descriptor `fd' to position `pos', modified
by `whence', and return the new position in bytes relative to
the start of the file.
Valid values for `whence' are:


@itemize *

@item 
@ref{14a5,,SEEK_SET} or @code{0} -- set `pos' relative to the beginning of the file

@item 
@ref{14a6,,SEEK_CUR} or @code{1} -- set `pos' relative to the current file position

@item 
@ref{14a7,,SEEK_END} or @code{2} -- set `pos' relative to the end of the file

@item 
@ref{3041,,SEEK_HOLE} -- set `pos' to the next data location, relative to `pos'

@item 
@ref{3042,,SEEK_DATA} -- set `pos' to the next data hole, relative to `pos'
@end itemize


バージョン 3.3 で変更: Add support for @code{SEEK_HOLE} and @code{SEEK_DATA}.

@end deffn

@geindex SEEK_SET (os モジュール)
@geindex SEEK_CUR (os モジュール)
@geindex SEEK_END (os モジュール)
@anchor{library/os os SEEK_SET}@anchor{14a5}
@deffn {データ} os.SEEK_SET
@anchor{library/os os SEEK_CUR}@anchor{14a6}
@deffnx {データ} os.SEEK_CUR
@anchor{library/os os SEEK_END}@anchor{14a7}
@deffnx {データ} os.SEEK_END

Parameters to the @ref{132f,,lseek()} function and the @ref{14a4,,seek()}
method on @ref{13db,,file-like objects},
for whence to adjust the file position indicator.


@table @asis

@item @ref{14a5,,SEEK_SET}

Adjust the file position relative to the beginning of the file.

@item @ref{14a6,,SEEK_CUR}

Adjust the file position relative to the current file position.

@item @ref{14a7,,SEEK_END}

Adjust the file position relative to the end of the file.
@end table

Their values are 0, 1, and 2, respectively.
@end deffn

@geindex SEEK_HOLE (os モジュール)
@geindex SEEK_DATA (os モジュール)
@anchor{library/os os SEEK_HOLE}@anchor{3041}
@deffn {データ} os.SEEK_HOLE
@anchor{library/os os SEEK_DATA}@anchor{3042}
@deffnx {データ} os.SEEK_DATA

Parameters to the @ref{132f,,lseek()} function and the @ref{14a4,,seek()}
method on @ref{13db,,file-like objects},
for seeking file data and holes on sparsely allocated files.


@table @asis

@item @code{SEEK_DATA}

Adjust the file offset to the next location containing data,
relative to the seek position.

@item @code{SEEK_HOLE}

Adjust the file offset to the next location containing a hole,
relative to the seek position.
A hole is defined as a sequence of zeros.
@end table

@cartouche
@quotation 注釈 
These operations only make sense for filesystems that support them.
@end quotation
@end cartouche

@ref{213f,,Availability}: Linux >= 3.1, macOS, Unix


Added in version 3.3.

@end deffn

@geindex open() (os モジュール)
@anchor{library/os os open}@anchor{f92}
@deffn {の関数} os.open (path, flags, mode=0o777, *, dir_fd=None)

ファイル `path' を開き、`flag' に従って様々なフラグを設定し、可能なら `mode' に従ってファイルモードを設定します。`mode' を計算する際、まず現在の umask 値でマスクされます。新たに開いたファイルのファイル記述子を返します。新しいファイル記述子は @ref{10fc,,継承不可} です。

For a description of the flag and mode values, see the C run-time documentation;
flag constants (like @ref{3043,,O_RDONLY} and @ref{3044,,O_WRONLY}) are defined in
the @code{os} module.  In particular, on Windows adding
@ref{3045,,O_BINARY} is needed to open files in binary mode.

この関数は `dir_fd' パラメタで @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

引数 @code{path}, @code{mode}, @code{flags} を指定して @ref{1c6e,,監査イベント} @code{open} を送出します。


バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。


@cartouche
@quotation 注釈 
この関数は低水準の I/O 向けのものです。
通常の利用では、組み込み関数 @ref{316,,open()} を使用してください。
@ref{316,,open()} は @code{read()} や @code{write()} (そしてさらに多くの) メソッドを持つ @ref{13db,,ファイルオブジェクト} を返します。
ファイル記述子をファイルオブジェクトでラップするには @ref{2381,,fdopen()} を使用してください。
@end quotation
@end cartouche


バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、この関数は @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

以下の定数は @ref{f92,,open()} 関数の `flags' 引数に利用します。これらの定数は、ビット単位に OR 演算子 @code{|} で組み合わせることができます。一部、すべてのプラットフォームでは使用できない定数があります。利用可能かどうかや使い方については、Unix では @code{open(2)@footnote{https://manpages.debian.org/open(2)}}、Windows では MSDN@footnote{https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx} を参照してください。

@geindex O_RDONLY (os モジュール)
@geindex O_WRONLY (os モジュール)
@geindex O_RDWR (os モジュール)
@geindex O_APPEND (os モジュール)
@geindex O_CREAT (os モジュール)
@geindex O_EXCL (os モジュール)
@geindex O_TRUNC (os モジュール)
@anchor{library/os os O_RDONLY}@anchor{3043}
@deffn {データ} os.O_RDONLY
@anchor{library/os os O_WRONLY}@anchor{3044}
@deffnx {データ} os.O_WRONLY
@anchor{library/os os O_RDWR}@anchor{3046}
@deffnx {データ} os.O_RDWR
@anchor{library/os os O_APPEND}@anchor{3047}
@deffnx {データ} os.O_APPEND
@anchor{library/os os O_CREAT}@anchor{3048}
@deffnx {データ} os.O_CREAT
@anchor{library/os os O_EXCL}@anchor{2ccf}
@deffnx {データ} os.O_EXCL
@anchor{library/os os O_TRUNC}@anchor{3049}
@deffnx {データ} os.O_TRUNC

上記の定数は Unix および Windows で利用可能です。
@end deffn

@geindex O_DSYNC (os モジュール)
@geindex O_RSYNC (os モジュール)
@geindex O_SYNC (os モジュール)
@geindex O_NDELAY (os モジュール)
@geindex O_NONBLOCK (os モジュール)
@geindex O_NOCTTY (os モジュール)
@geindex O_CLOEXEC (os モジュール)
@anchor{library/os os O_DSYNC}@anchor{304a}
@deffn {データ} os.O_DSYNC
@anchor{library/os os O_RSYNC}@anchor{304b}
@deffnx {データ} os.O_RSYNC
@anchor{library/os os O_SYNC}@anchor{304c}
@deffnx {データ} os.O_SYNC
@anchor{library/os os O_NDELAY}@anchor{304d}
@deffnx {データ} os.O_NDELAY
@anchor{library/os os O_NONBLOCK}@anchor{103b}
@deffnx {データ} os.O_NONBLOCK
@anchor{library/os os O_NOCTTY}@anchor{304e}
@deffnx {データ} os.O_NOCTTY
@anchor{library/os os O_CLOEXEC}@anchor{1288}
@deffnx {データ} os.O_CLOEXEC

上記の定数は Unix でのみ利用可能です。


バージョン 3.3 で変更: 定数 @ref{1288,,O_CLOEXEC} が追加されました。

@end deffn

@geindex O_BINARY (os モジュール)
@geindex O_NOINHERIT (os モジュール)
@geindex O_SHORT_LIVED (os モジュール)
@geindex O_TEMPORARY (os モジュール)
@geindex O_RANDOM (os モジュール)
@geindex O_SEQUENTIAL (os モジュール)
@geindex O_TEXT (os モジュール)
@anchor{library/os os O_BINARY}@anchor{3045}
@deffn {データ} os.O_BINARY
@anchor{library/os os O_NOINHERIT}@anchor{304f}
@deffnx {データ} os.O_NOINHERIT
@anchor{library/os os O_SHORT_LIVED}@anchor{3050}
@deffnx {データ} os.O_SHORT_LIVED
@anchor{library/os os O_TEMPORARY}@anchor{3051}
@deffnx {データ} os.O_TEMPORARY
@anchor{library/os os O_RANDOM}@anchor{3052}
@deffnx {データ} os.O_RANDOM
@anchor{library/os os O_SEQUENTIAL}@anchor{3053}
@deffnx {データ} os.O_SEQUENTIAL
@anchor{library/os os O_TEXT}@anchor{3054}
@deffnx {データ} os.O_TEXT

上記の定数は Windows でのみ利用可能です。
@end deffn

@geindex O_EVTONLY (os モジュール)
@geindex O_FSYNC (os モジュール)
@geindex O_SYMLINK (os モジュール)
@geindex O_NOFOLLOW_ANY (os モジュール)
@anchor{library/os os O_EVTONLY}@anchor{a1b}
@deffn {データ} os.O_EVTONLY
@anchor{library/os os O_FSYNC}@anchor{a1c}
@deffnx {データ} os.O_FSYNC
@anchor{library/os os O_SYMLINK}@anchor{a1d}
@deffnx {データ} os.O_SYMLINK
@anchor{library/os os O_NOFOLLOW_ANY}@anchor{a1e}
@deffnx {データ} os.O_NOFOLLOW_ANY

上記の定数は macOS でのみ利用可能です。


バージョン 3.10 で変更: Add @ref{a1b,,O_EVTONLY}, @ref{a1c,,O_FSYNC}, @ref{a1d,,O_SYMLINK}
and @ref{a1e,,O_NOFOLLOW_ANY} constants.

@end deffn

@geindex O_ASYNC (os モジュール)
@geindex O_DIRECT (os モジュール)
@geindex O_DIRECTORY (os モジュール)
@geindex O_NOFOLLOW (os モジュール)
@geindex O_NOATIME (os モジュール)
@geindex O_PATH (os モジュール)
@geindex O_TMPFILE (os モジュール)
@geindex O_SHLOCK (os モジュール)
@geindex O_EXLOCK (os モジュール)
@anchor{library/os os O_ASYNC}@anchor{3055}
@deffn {データ} os.O_ASYNC
@anchor{library/os os O_DIRECT}@anchor{3056}
@deffnx {データ} os.O_DIRECT
@anchor{library/os os O_DIRECTORY}@anchor{3057}
@deffnx {データ} os.O_DIRECTORY
@anchor{library/os os O_NOFOLLOW}@anchor{3058}
@deffnx {データ} os.O_NOFOLLOW
@anchor{library/os os O_NOATIME}@anchor{3059}
@deffnx {データ} os.O_NOATIME
@anchor{library/os os O_PATH}@anchor{1174}
@deffnx {データ} os.O_PATH
@anchor{library/os os O_TMPFILE}@anchor{1175}
@deffnx {データ} os.O_TMPFILE
@anchor{library/os os O_SHLOCK}@anchor{1648}
@deffnx {データ} os.O_SHLOCK
@anchor{library/os os O_EXLOCK}@anchor{1649}
@deffnx {データ} os.O_EXLOCK

上記の定数は拡張仕様であり、Cライブラリで定義されていない場合は利用できません。


バージョン 3.4 で変更: @ref{1174,,O_PATH} を、それをサポートするシステムで追加しました。また、 @ref{1175,,O_TMPFILE} を追加しました (Linux Kernel 3.11 以降でのみ利用可能です)。

@end deffn

@geindex openpty() (os モジュール)
@anchor{library/os os openpty}@anchor{305a}
@deffn {の関数} os.openpty ()

@geindex module;pty

新しい擬似端末のペアを開きます。pty および tty を表すファイル記述子のペア @code{(master, slave)} を返します。新しいファイル記述子は @ref{10fc,,継承不可} です。(若干) 可搬性の高いアプローチには @ref{b6,,pty} を使用してください。

@ref{213f,,Availability}: Unix, not WASI.


バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。

@end deffn

@geindex pipe() (os モジュール)
@anchor{library/os os pipe}@anchor{1b64}
@deffn {の関数} os.pipe ()

パイプを作成します。読み込み、書き込みに使うことの出来るファイル記述子のペア @code{(r, w)}  を返します。新しいファイル記述子は @ref{10fc,,継承不可} です。

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。

@end deffn

@geindex pipe2() (os モジュール)
@anchor{library/os os pipe2}@anchor{1301}
@deffn {の関数} os.pipe2 (flags, /)

`flags' を設定したパイプをアトミックに作成します。`flags' には値 @ref{103b,,O_NONBLOCK} と @ref{1288,,O_CLOEXEC} を一つ以上論理和指定できます。読み込み、書き込みに使うことの出来るファイル記述子のペア @code{(r, w)}  を返します。

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.3.

@end deffn

@geindex posix_fallocate() (os モジュール)
@anchor{library/os os posix_fallocate}@anchor{f94}
@deffn {の関数} os.posix_fallocate (fd, offset, len, /)

`fd' で指定されたファイルに対し、開始位置 `offset' から `len' バイト分割り当てるに十分なディスクスペースを確保します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex posix_fadvise() (os モジュール)
@anchor{library/os os posix_fadvise}@anchor{f93}
@deffn {の関数} os.posix_fadvise (fd, offset, len, advice, /)

データへアクセスする意思を、パターンを指定して宣言します。これによりカーネルが最適化を行えるようになります。`advice' は `fd' で指定されたファイルに対し、開始位置 `offset' から `len' バイト分の領域に適用されます。`advice' には @ref{305b,,POSIX_FADV_NORMAL}、@ref{305c,,POSIX_FADV_SEQUENTIAL}、@ref{305d,,POSIX_FADV_RANDOM}、@ref{305e,,POSIX_FADV_NOREUSE}、@ref{305f,,POSIX_FADV_WILLNEED}、または @ref{3060,,POSIX_FADV_DONTNEED} のいずれか一つを指定します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex POSIX_FADV_NORMAL (os モジュール)
@geindex POSIX_FADV_SEQUENTIAL (os モジュール)
@geindex POSIX_FADV_RANDOM (os モジュール)
@geindex POSIX_FADV_NOREUSE (os モジュール)
@geindex POSIX_FADV_WILLNEED (os モジュール)
@geindex POSIX_FADV_DONTNEED (os モジュール)
@anchor{library/os os POSIX_FADV_NORMAL}@anchor{305b}
@deffn {データ} os.POSIX_FADV_NORMAL
@anchor{library/os os POSIX_FADV_SEQUENTIAL}@anchor{305c}
@deffnx {データ} os.POSIX_FADV_SEQUENTIAL
@anchor{library/os os POSIX_FADV_RANDOM}@anchor{305d}
@deffnx {データ} os.POSIX_FADV_RANDOM
@anchor{library/os os POSIX_FADV_NOREUSE}@anchor{305e}
@deffnx {データ} os.POSIX_FADV_NOREUSE
@anchor{library/os os POSIX_FADV_WILLNEED}@anchor{305f}
@deffnx {データ} os.POSIX_FADV_WILLNEED
@anchor{library/os os POSIX_FADV_DONTNEED}@anchor{3060}
@deffnx {データ} os.POSIX_FADV_DONTNEED

@ref{f93,,posix_fadvise()} において、使われるであろうアクセスパターンを指定する `advice' に使用できるフラグです。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex pread() (os モジュール)
@anchor{library/os os pread}@anchor{d56}
@deffn {の関数} os.pread (fd, n, offset, /)

ファイル記述子の位置 `offset' から最大で `n' バイトを読み出します。
ファイルオフセットは変化しません。

読み込んだバイト分のバイト列を返します。
`fd' が参照しているファイルの終端に達した場合、空のバイト列が返されます。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex posix_openpt() (os モジュール)
@anchor{library/os os posix_openpt}@anchor{19fd}
@deffn {の関数} os.posix_openpt (oflag, /)

Open and return a file descriptor for a master pseudo-terminal device.

Calls the C standard library function @code{posix_openpt()}. The `oflag'
argument is used to set file status flags and file access modes as
specified in the manual page of @code{posix_openpt()} of your system.

The returned file descriptor is @ref{10fc,,non-inheritable}.
If the value @ref{1288,,O_CLOEXEC} is available on the system, it is added to
`oflag'.

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.13.

@end deffn

@geindex preadv() (os モジュール)
@anchor{library/os os preadv}@anchor{d54}
@deffn {の関数} os.preadv (fd, buffers, offset, flags=0, /)

ファイル記述子 `fd' の `offset' の位置から、可変な @ref{193,,bytes-like オブジェクト} `buffers' にオフセットを変更せずに読み込みます。
データをそれぞれのバッファがいっぱいになるまで移し、いっぱいになったらシーケンスの次のバッファに処理を移し、残りのデータを読み込ませます。

flags 引数にはゼロあるいは次のフラグのバイトごとの OR を取った結果が保持されています。


@itemize -

@item 
@ref{3061,,RWF_HIPRI}

@item 
@ref{3062,,RWF_NOWAIT}
@end itemize

実際に読み込んだ合計バイト数を返します。この値は、すべてのオブジェクトの容量の総量よりも小さくなることがあります。

オペレーティングシステムは、使用可能なバッファの個数に基づいて上限 (@ref{18ed,,sysconf()} の @code{'SC_IOV_MAX'} の値) を設定することがあります。

@ref{d55,,os.readv()} と @ref{d56,,os.pread()} の機能を統合します。

@ref{213f,,Availability}: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.

Using flags requires Linux >= 4.6.


Added in version 3.7.

@end deffn

@geindex RWF_NOWAIT (os モジュール)
@anchor{library/os os RWF_NOWAIT}@anchor{3062}
@deffn {データ} os.RWF_NOWAIT

即座に利用できないデータを待ちません。このフラグを指定すると、バックエンドのストレージからデータを読む必要があるか、ロックを待機する場合、システムコールは即座にリターンします。

If some data was successfully read, it will return the number of bytes read.
If no bytes were read, it will return @code{-1} and set errno to
@ref{26fd,,errno.EAGAIN}.

@ref{213f,,Availability}: Linux >= 4.14.


Added in version 3.7.

@end deffn

@geindex RWF_HIPRI (os モジュール)
@anchor{library/os os RWF_HIPRI}@anchor{3061}
@deffn {データ} os.RWF_HIPRI

優先度の高い読み込み・書き込み (read/write) フラグです。ブロックストレージに対して、追加のリソースを必要とする一方で低レイテンシなデバイスのポーリングを使うことを許可します。

現状、Linuxでは、ファイル記述子を @ref{3056,,O_DIRECT} フラグを指定したオープンした場合でのみ、この機能を利用できます。

@ref{213f,,Availability}: Linux >= 4.6.


Added in version 3.7.

@end deffn

@geindex ptsname() (os モジュール)
@anchor{library/os os ptsname}@anchor{1a00}
@deffn {の関数} os.ptsname (fd, /)

Return the name of the slave pseudo-terminal device associated with the
master pseudo-terminal device to which the file descriptor `fd' refers.
The file descriptor `fd' is not closed upon failure.

Calls the reentrant C standard library function @code{ptsname_r()} if
it is available; otherwise, the C standard library function
@code{ptsname()}, which is not guaranteed to be thread-safe, is called.

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.13.

@end deffn

@geindex pwrite() (os モジュール)
@anchor{library/os os pwrite}@anchor{d59}
@deffn {の関数} os.pwrite (fd, str, offset, /)

`str' 中のバイト文字列をファイル記述子 `fd' の `offset' の位置に書き込みます。ファイルオフセットを変化しません。

実際に書き込まれたバイト数を返します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex pwritev() (os モジュール)
@anchor{library/os os pwritev}@anchor{d57}
@deffn {の関数} os.pwritev (fd, buffers, offset, flags=0, /)

Write the `buffers' contents to file descriptor `fd' at an offset `offset',
leaving the file offset unchanged.  `buffers' must be a sequence of
@ref{193,,bytes-like objects}. Buffers are processed in
array order. Entire contents of the first buffer is written before
proceeding to the second, and so on.

flags 引数にはゼロあるいは次のフラグのバイトごとの OR を取った結果が保持されています。


@itemize -

@item 
@ref{3063,,RWF_DSYNC}

@item 
@ref{3064,,RWF_SYNC}

@item 
@ref{1d2d,,RWF_APPEND}
@end itemize

実際に書き込まれた合計バイト数を返します。

オペレーティングシステムは、使用可能なバッファの個数に基づいて上限 (@ref{18ed,,sysconf()} の @code{'SC_IOV_MAX'} の値) を設定することがあります。

@ref{d58,,os.writev()} と @ref{d59,,os.pwrite()} の機能を統合します。

@ref{213f,,Availability}: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.

Using flags requires Linux >= 4.6.


Added in version 3.7.

@end deffn

@geindex RWF_DSYNC (os モジュール)
@anchor{library/os os RWF_DSYNC}@anchor{3063}
@deffn {データ} os.RWF_DSYNC

書き込みごとに @ref{f92,,os.open()} の @ref{304a,,O_DSYNC} と同等の効果を提供するフラグです。このフラグはシステムコールによって書き込まれたデータ範囲に対してのみ適用されます。

@ref{213f,,Availability}: Linux >= 4.7.


Added in version 3.7.

@end deffn

@geindex RWF_SYNC (os モジュール)
@anchor{library/os os RWF_SYNC}@anchor{3064}
@deffn {データ} os.RWF_SYNC

書き込みごとに @ref{f92,,os.open()} の @ref{304c,,O_SYNC} と同等の効果を提供するフラグです。このフラグはシステムコールによって書き込まれたデータ範囲に対してのみ適用されます。

@ref{213f,,Availability}: Linux >= 4.7.


Added in version 3.7.

@end deffn

@geindex RWF_APPEND (os モジュール)
@anchor{library/os os RWF_APPEND}@anchor{1d2d}
@deffn {データ} os.RWF_APPEND

Provide a per-write equivalent of the @ref{3047,,O_APPEND} @ref{f92,,os.open()}
flag. This flag is meaningful only for @ref{d57,,os.pwritev()}, and its
effect applies only to the data range written by the system call. The
`offset' argument does not affect the write operation; the data is always
appended to the end of the file. However, if the `offset' argument is
@code{-1}, the current file `offset' is updated.

@ref{213f,,Availability}: Linux >= 4.16.


Added in version 3.10.

@end deffn

@geindex read() (os モジュール)
@anchor{library/os os read}@anchor{f95}
@deffn {の関数} os.read (fd, n, /)

ファイル記述子 `fd' から 最大 `n' バイトを読み込みます。

読み込んだバイト分のバイト列を返します。
`fd' が参照しているファイルの終端に達した場合、空のバイト列が返されます。

@cartouche
@quotation 注釈 
この関数は低水準の I/O 向けのもので、 @ref{f92,,os.open()} や @ref{1b64,,pipe()} が返すファイル記述子に対して使用されなければなりません。
組み込み関数 @ref{316,,open()} や @ref{31a,,popen()} 、 @ref{2381,,fdopen()} 、あるいは @ref{75f,,sys.stdin} が返す "ファイルオブジェクト" を読み込むには、オブジェクトの @code{read()} か @code{readline()} メソッドを使用してください。
@end quotation
@end cartouche


バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、この関数は @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex readinto() (os モジュール)
@anchor{library/os os readinto}@anchor{25f}
@deffn {の関数} os.readinto (fd, buffer, /)

Read from a file descriptor `fd' into a mutable
@ref{260,,buffer object} `buffer'.

The `buffer' should be mutable and @ref{193,,bytes-like}. On
success, returns the number of bytes read. Less bytes may be read than the
size of the buffer. The underlying system call will be retried when
interrupted by a signal, unless the signal handler raises an exception.
Other errors will not be retried and an error will be raised.

Returns 0 if `fd' is at end of file or if the provided `buffer' has
length 0 (which can be used to check for errors without reading data).
Never returns negative.

@cartouche
@quotation 注釈 
This function is intended for low-level I/O and must be applied to a file
descriptor as returned by @ref{f92,,os.open()} or @ref{1b64,,os.pipe()}.  To read a
"file object" returned by the built-in function @ref{316,,open()}, or
@ref{75f,,sys.stdin}, use its member functions, for example
@ref{1895,,io.BufferedIOBase.readinto()}, @ref{1540,,io.BufferedIOBase.read()}, or
@ref{206c,,io.TextIOBase.read()}
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@geindex sendfile() (os モジュール)
@anchor{library/os os sendfile}@anchor{d05}
@deffn {の関数} os.sendfile (out_fd, in_fd, offset, count)

@deffnx {の関数} os.sendfile (out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)

ファイル記述子 `in_fd' からファイル記述子 `out_fd' への開始位置 `offset' へ `count' バイトコピーします。
送信バイト数を返します。
EOF に達した場合は @code{0} を返します。

前者の関数表記は @ref{d05,,sendfile()} が定義されているすべてのプラットフォームでサポートされています。

Linux では、`offset' に @code{None} が与えられると、バイト列は `in_fd' の現在の位置から読み込まれ、`in_fd' の位置は更新されます。

後者は macOS および FreeBSD で使用される場合があります。`headers' および `trailers' は任意のバッファのシーケンス型オブジェクトで、`in_fd' からのデータが書き出される前と後に書き出されます。返り値は前者と同じです。

macOS と FreeBSD では、`count' の値に @code{0} を指定すると、 `in_fd' の末尾に達するまで送信します。

全てのプラットフォームはソケットをファイル記述子 `out_fd' としてサポートし、あるプラットフォームは他の種類 (例えば、通常のファイル、パイプ) も同様にサポートします。

クロスプラットフォームのアプリケーションは `headers'、`trailers' ならびに `flags' 引数を使用するべきではありません。

@ref{213f,,Availability}: Unix, not WASI.

@cartouche
@quotation 注釈 
@ref{d05,,sendfile()} のより高水準のラッパについては @ref{105d,,socket.socket.sendfile()} を参照してください。
@end quotation
@end cartouche


Added in version 3.3.



バージョン 3.9 で変更: 引数 `out' と `in' は `out_fd' と `in_fd' に名前が変更されました。

@end deffn

@geindex SF_NODISKIO (os モジュール)
@geindex SF_MNOWAIT (os モジュール)
@geindex SF_SYNC (os モジュール)
@anchor{library/os os SF_NODISKIO}@anchor{3065}
@deffn {データ} os.SF_NODISKIO
@anchor{library/os os SF_MNOWAIT}@anchor{3066}
@deffnx {データ} os.SF_MNOWAIT
@anchor{library/os os SF_SYNC}@anchor{3067}
@deffnx {データ} os.SF_SYNC

実装がサポートしている場合 @ref{d05,,sendfile()} 関数に渡すパラメーターです。

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.3.

@end deffn

@geindex SF_NOCACHE (os モジュール)
@anchor{library/os os SF_NOCACHE}@anchor{3068}
@deffn {データ} os.SF_NOCACHE

Parameter to the @ref{d05,,sendfile()} function, if the implementation supports
it. The data won't be cached in the virtual memory and will be freed afterwards.

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.11.

@end deffn

@geindex set_blocking() (os モジュール)
@anchor{library/os os set_blocking}@anchor{103a}
@deffn {の関数} os.set_blocking (fd, blocking, /)

指定されたファイル記述子のブロッキングモードを設定します。
ブロッキングが @code{False} の場合 @ref{103b,,O_NONBLOCK} フラグを設定し、そうでない場合はクリアします。

@ref{1039,,get_blocking()} および @ref{303c,,socket.socket.setblocking()} も参照してください。

@ref{213f,,Availability}: Unix, Windows.

The function is limited on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.

On Windows, this function is limited to pipes.


Added in version 3.5.



バージョン 3.12 で変更: Added support for pipes on Windows.

@end deffn

@geindex splice() (os モジュール)
@anchor{library/os os splice}@anchor{a1a}
@deffn {の関数} os.splice (src, dst, count, offset_src=None, offset_dst=None, flags=0)

Transfer `count' bytes from file descriptor `src', starting from offset
`offset_src', to file descriptor `dst', starting from offset `offset_dst'.

The splicing behaviour can be modified by specifying a `flags' value.
Any of the following variables may used, combined using bitwise OR
(the @code{|} operator):


@itemize *

@item 
If @ref{3069,,SPLICE_F_MOVE} is specified,
the kernel is asked to move pages instead of copying,
but pages may still be copied if the kernel cannot move the pages from the pipe.

@item 
If @ref{306a,,SPLICE_F_NONBLOCK} is specified,
the kernel is asked to not block on I/O.
This makes the splice pipe operations nonblocking,
but splice may nevertheless block because the spliced file descriptors may block.

@item 
If @ref{306b,,SPLICE_F_MORE} is specified,
it hints to the kernel that more data will be coming in a subsequent splice.
@end itemize

At least one of the file descriptors must refer to a pipe. If `offset_src'
is @code{None}, then `src' is read from the current position; respectively for
`offset_dst'. The offset associated to the file descriptor that refers to a
pipe must be @code{None}. The files pointed to by `src' and `dst' must reside in
the same filesystem, otherwise an @ref{2c0,,OSError} is raised with
@ref{17b3,,errno} set to @ref{303a,,errno.EXDEV}.

このコピーは、カーネルからユーザースペースにデータを転送した後カーネルに戻すという追加のコスト無しに完了します。
加えて、追加の最適化ができるファイルシステムもあります。
このコピーはファイルが両方ともバイナリファイルとして開かれたかのように行われます。

Upon successful completion, returns the number of bytes spliced to or from
the pipe. A return value of 0 means end of input. If `src' refers to a
pipe, then this means that there was no data to transfer, and it would not
make sense to block because there are no writers connected to the write end
of the pipe.


@subsubheading 参考


The @code{splice(2)@footnote{https://manpages.debian.org/splice(2)}} man page.


@ref{213f,,Availability}: Linux >= 2.6.17 with glibc >= 2.5


Added in version 3.10.

@end deffn

@geindex SPLICE_F_MOVE (os モジュール)
@geindex SPLICE_F_NONBLOCK (os モジュール)
@geindex SPLICE_F_MORE (os モジュール)
@anchor{library/os os SPLICE_F_MOVE}@anchor{3069}
@deffn {データ} os.SPLICE_F_MOVE
@anchor{library/os os SPLICE_F_NONBLOCK}@anchor{306a}
@deffnx {データ} os.SPLICE_F_NONBLOCK
@anchor{library/os os SPLICE_F_MORE}@anchor{306b}
@deffnx {データ} os.SPLICE_F_MORE


Added in version 3.10.

@end deffn

@geindex readv() (os モジュール)
@anchor{library/os os readv}@anchor{d55}
@deffn {の関数} os.readv (fd, buffers, /)

Read from a file descriptor `fd' into a number of mutable @ref{193,,bytes-like objects} `buffers'. Transfer data into each buffer until
it is full and then move on to the next buffer in the sequence to hold the
rest of the data.

実際に読み込んだ合計バイト数を返します。この値は、すべてのオブジェクトの容量の総量よりも小さくなることがあります。

オペレーティングシステムは、使用可能なバッファの個数に基づいて上限 (@ref{18ed,,sysconf()} の @code{'SC_IOV_MAX'} の値) を設定することがあります。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex tcgetpgrp() (os モジュール)
@anchor{library/os os tcgetpgrp}@anchor{306c}
@deffn {の関数} os.tcgetpgrp (fd, /)

`fd' (@ref{f92,,os.open()} が返すオープンしたファイル記述子 ) で与えられる端末に関連付けられたプロセスグループを返します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex tcsetpgrp() (os モジュール)
@anchor{library/os os tcsetpgrp}@anchor{306d}
@deffn {の関数} os.tcsetpgrp (fd, pg, /)

`fd' (@ref{f92,,os.open()} が返すオープンしたファイル記述子 ) で与えられる端末に関連付けられたプロセスグループを `pg' に設定します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex ttyname() (os モジュール)
@anchor{library/os os ttyname}@anchor{306e}
@deffn {の関数} os.ttyname (fd, /)

ファイル記述子 `fd' に関連付けられている端末デバイスを特定する文字列を返します。 `fd' が端末に関連付けられていない場合、例外が送出されます。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex unlockpt() (os モジュール)
@anchor{library/os os unlockpt}@anchor{19ff}
@deffn {の関数} os.unlockpt (fd, /)

Unlock the slave pseudo-terminal device associated with the master
pseudo-terminal device to which the file descriptor `fd' refers.
The file descriptor `fd' is not closed upon failure.

Calls the C standard library function @code{unlockpt()}.

@ref{213f,,Availability}: Unix, not WASI.


Added in version 3.13.

@end deffn

@geindex write() (os モジュール)
@anchor{library/os os write}@anchor{f9b}
@deffn {の関数} os.write (fd, str, /)

`str' のバイト列をファイル記述子 `fd' に書き出します。

実際に書き込まれたバイト数を返します。

@cartouche
@quotation 注釈 
この関数は低水準の I/O 向けのもので、 @ref{f92,,os.open()} や @ref{1b64,,pipe()} が返すファイル記述子に対して使用しなければなりません。
組み込み関数 @ref{316,,open()} や @ref{31a,,popen()} 、 @ref{2381,,fdopen()} 、あるいは @ref{ccd,,sys.stdout} や @ref{b33,,sys.stderr} が返す "ファイルオブジェクト" に書き込むには、オブジェクトの @code{write()} メソッドを使用してください。
@end quotation
@end cartouche


バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、この関数は @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex writev() (os モジュール)
@anchor{library/os os writev}@anchor{d58}
@deffn {の関数} os.writev (fd, buffers, /)

`buffers' の内容をファイル記述子 `fd' へ書き出します。 `buffers' は @ref{193,,bytes-like オブジェクト} のシーケンスでなければなりません。バッファは配列の順番で処理されます。最初のバッファの内容全体は 2 番目のバッファに進む前に書き込まれ、その次も同様です。

実際に書き込まれた合計バイト数を返します。

オペレーティングシステムは、使用可能なバッファの個数に基づいて上限 (@ref{18ed,,sysconf()} の @code{'SC_IOV_MAX'} の値) を設定することがあります。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@menu
* ターミナルのサイズの問い合わせ:: 
* ファイル記述子の継承:: 

@end menu

@node ターミナルのサイズの問い合わせ,ファイル記述子の継承,,ファイル記述子の操作
@anchor{library/os querying-the-size-of-a-terminal}@anchor{306f}@anchor{library/os terminal-size}@anchor{3070}
@subsubsection ターミナルのサイズの問い合わせ



Added in version 3.3.


@geindex get_terminal_size() (os モジュール)
@anchor{library/os os get_terminal_size}@anchor{131a}
@deffn {の関数} os.get_terminal_size (fd=STDOUT_FILENO, /)

ターミナル (端末) のサイズ @code{(columns, lines)} を、@ref{2cfc,,terminal_size} 型のタプルで返します。

オプションの引数 @code{fd} には問い合わせるファイル記述子を指定します (デフォルトは @code{STDOUT_FILENO}、または標準出力)。

ファイル記述子が接続されていなかった場合、 @ref{2c0,,OSError} が送出されます。

通常は高水準関数である @ref{131b,,shutil.get_terminal_size()} を使用してください。@code{os.get_terminal_size} は低水準の実装です。

@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex terminal_size (os のクラス)
@anchor{library/os os terminal_size}@anchor{2cfc}
@deffn {クラス} os.terminal_size

ターミナルウィンドウのサイズ @code{(columns, lines)} を保持するタプルのサブクラスです。

@geindex columns (os.terminal_size の属性)
@anchor{library/os os terminal_size columns}@anchor{3071}
@deffn {の属性} columns

ターミナルウィンドウの横幅 (文字数) です。
@end deffn

@geindex lines (os.terminal_size の属性)
@anchor{library/os os terminal_size lines}@anchor{3072}
@deffn {の属性} lines

ターミナルウィンドウの高さ (文字数) です。
@end deffn
@end deffn

@node ファイル記述子の継承,,ターミナルのサイズの問い合わせ,ファイル記述子の操作
@anchor{library/os fd-inheritance}@anchor{10fc}@anchor{library/os inheritance-of-file-descriptors}@anchor{3073}
@subsubsection ファイル記述子の継承



Added in version 3.4.


ファイル記述子には「継承可能 (inheritable)」フラグというものがあって、これにより子プロセスにファイル記述子が引き継がれるかどうかが決定されます。Python 3.4 より、 Python によって作成されるファイル記述子はデフォルトで継承不可 (non-inheritable) となりました。

On UNIX, non-inheritable file descriptors are closed in child processes at the
execution of a new program, other file descriptors are inherited. Note that
non-inheritable file descriptors are still `inherited' by child processes on @ref{4b5,,os.fork()}.

Windows の場合は、標準ストリームを除き、継承不可のハンドルと継承不可のファイル記述子は子プロセスでクローズされます。標準ストリーム (ファイル記述子の 0, 1, 2: 標準入力, 標準出力, 標準エラー出力) は常に引き継がれます。 @ref{31b,,spawn*} 関数を使う場合、全ての継承可能なハンドルと全ての継承可能なファイル記述子は引き継がれます。 @ref{dc,,subprocess} モジュールを使う場合、標準ストリームを除く全てのファイル記述子はクローズされ、継承可能なハンドルは `close_fds' 引数が @code{False} の場合にのみ引き継がれます。

On WebAssembly platforms, the file descriptor cannot be modified.

@geindex get_inheritable() (os モジュール)
@anchor{library/os os get_inheritable}@anchor{10fd}
@deffn {の関数} os.get_inheritable (fd, /)

指定したファイル記述子の「継承可能 (inheritable)」フラグを取得します (boolean)。
@end deffn

@geindex set_inheritable() (os モジュール)
@anchor{library/os os set_inheritable}@anchor{10fe}
@deffn {の関数} os.set_inheritable (fd, inheritable, /)

指定したファイル記述子の「継承可能 (inheritable)」フラグをセットします。
@end deffn

@geindex get_handle_inheritable() (os モジュール)
@anchor{library/os os get_handle_inheritable}@anchor{10ff}
@deffn {の関数} os.get_handle_inheritable (handle, /)

指定したハンドルの「継承可能 (inheritable)」フラグを取得します (boolean)。

@ref{213f,,Availability}: Windows.
@end deffn

@geindex set_handle_inheritable() (os モジュール)
@anchor{library/os os set_handle_inheritable}@anchor{1100}
@deffn {の関数} os.set_handle_inheritable (handle, inheritable, /)

指定したハンドルの「継承可能 (inheritable)」フラグをセットします。

@ref{213f,,Availability}: Windows.
@end deffn

@node ファイルとディレクトリ,プロセス管理,ファイル記述子の操作,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os files-and-directories}@anchor{3074}@anchor{library/os os-file-dir}@anchor{300a}
@subsubsection ファイルとディレクトリ


一部の Unix プラットフォームでは、このセクションの関数の多くが以下の機能を一つ以上サポートしています。
@anchor{library/os path-fd}@anchor{d53}

@itemize *

@item 
`specifying a file descriptor:'
Normally the `path' argument provided to functions in the @code{os} module
must be a string specifying a file path.  However, some functions now
alternatively accept an open file descriptor for their `path' argument.
The function will then operate on the file referred to by the descriptor.
For POSIX systems, Python will call the variant of the function prefixed
with @code{f} (e.g. call @code{fchdir} instead of @code{chdir}).

@ref{1315,,os.supports_fd} を使うことで、そのプラットフォーム上で `path' にファイル記述子を指定できるかどうかを確認することができます。この機能が利用可能でない場合、 @ref{1315,,os.supports_fd} の利用は @ref{36b,,NotImplementedError} 例外を送出します。

その関数が引数に `dir_fd' または `follow_symlinks' もサポートしている場合、`path' にファイル記述子を指定した時にそれらのいずれかを指定するとエラーになります。
@end itemize
@anchor{library/os dir-fd}@anchor{1302}

@itemize *

@item 
`paths relative to directory descriptors:' If `dir_fd' is not @code{None}, it
should be a file descriptor referring to a directory, and the path to operate
on should be relative; path will then be relative to that directory.  If the
path is absolute, `dir_fd' is ignored.  For POSIX systems, Python will call
the variant of the function with an @code{at} suffix and possibly prefixed with
@code{f} (e.g. call @code{faccessat} instead of @code{access}).

そのプラットフォーム上で特別な関数に `dir_fd' がサポートされているかどうかは、@ref{130f,,os.supports_dir_fd} で確認できます。利用できない場合 @ref{36b,,NotImplementedError} が送出されます。
@end itemize
@anchor{library/os follow-symlinks}@anchor{1303}

@itemize *

@item 
`not following symlinks:' If `follow_symlinks' is
@code{False}, and the last element of the path to operate on is a symbolic link,
the function will operate on the symbolic link itself rather than the file
pointed to by the link.  For POSIX systems, Python will call the @code{l...}
variant of the function.

そのプラットフォーム上で特別な関数に `follow_symlinks' がサポートされているかどうかは、@ref{1310,,os.supports_follow_symlinks} で確認できます。利用できない場合 @ref{36b,,NotImplementedError} が送出されます。
@end itemize

@geindex access() (os モジュール)
@anchor{library/os os access}@anchor{1304}
@deffn {の関数} os.access (path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)

実 uid/gid を使って `path' に対するアクセスが可能か調べます。ほとんどのオペレーティングシステムは実効 uid/gid を使うため、このルーチンは suid/sgid 環境において、プログラムを起動したユーザーが `path' に対するアクセス権をもっているかを調べるために使われます。 `path' が存在するかどうかを調べるには `mode' を @ref{3075,,F_OK} にします。ファイルアクセス権限 ( パーミッション ) を調べるには、 @ref{3076,,R_OK}, @ref{3077,,W_OK}, @ref{3078,,X_OK} から一つまたはそれ以上のフラグを論理和指定でとることもできます。アクセスが許可されている場合 @ref{e07,,True} を、そうでない場合 @ref{d2b,,False} を返します。詳細は @code{access(2)@footnote{https://manpages.debian.org/access(2)}} の Unix マニュアルページを参照してください。

この関数は @ref{1302,,ディレクトリ記述子への相対パス} および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

`effective_ids' が @code{True} の場合、@ref{1304,,access()} は実 uid/gid ではなく実効 uid/gid を使用してアクセス権を調べます。プラットフォームによっては `effective_ids' がサポートされていない場合があります; サポートされているかどうかは @ref{1316,,os.supports_effective_ids} で確認できます。利用できない場合 @ref{36b,,NotImplementedError} が送出されます。

@cartouche
@quotation 注釈 
ユーザーが、例えばファイルを開く権限を持っているかどうかを調べるために実際に @ref{316,,open()} を行う前に @ref{1304,,access()} を使用することはセキュリティホールの原因になります。なぜなら、調べた時点とオープンした時点との時間差を利用してそのユーザーがファイルを不当に操作してしまうかもしれないからです。その場合は @ref{3079,,EAFP} テクニックを利用するのが望ましいやり方です。例えば

@example
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
@end example

このコードは次のように書いたほうが良いです

@example
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
@end example
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
I/O 操作は @ref{1304,,access()} が成功を示した時でも失敗することがあります。特にネットワークファイルシステムが通常の POSIX のパーミッションビットモデルをはみ出すアクセス権限操作を備える場合にはそのようなことが起こりえます。
@end quotation
@end cartouche


バージョン 3.3 で変更: 引数 `dir_fd'、`effective_ids'、および `follow_symlinks' が追加されました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex F_OK (os モジュール)
@geindex R_OK (os モジュール)
@geindex W_OK (os モジュール)
@geindex X_OK (os モジュール)
@anchor{library/os os F_OK}@anchor{3075}
@deffn {データ} os.F_OK
@anchor{library/os os R_OK}@anchor{3076}
@deffnx {データ} os.R_OK
@anchor{library/os os W_OK}@anchor{3077}
@deffnx {データ} os.W_OK
@anchor{library/os os X_OK}@anchor{3078}
@deffnx {データ} os.X_OK

@ref{1304,,access()} で `path' をテストする時に `mode' 引数に渡す値です。上からそれぞれ、ファイルの存在、読み込み許可、書き込み許可、および実行許可になります。
@end deffn

@geindex chdir() (os モジュール)
@anchor{library/os os chdir}@anchor{821}
@deffn {の関数} os.chdir (path)

@geindex ディレクトリ;変更

現在の作業ディレクトリを `path' に設定します。

この関数は @ref{d53,,ファイル記述子の指定} をサポートしています。記述子は、オープンしているファイルではなく、オープンしているディレクトリを参照していなければなりません。

この関数は @ref{2c0,,OSError} やそのサブクラスである @ref{264,,FileNotFoundError}, @ref{f3e,,PermissionError}, @ref{1265,,NotADirectoryError} などの例外を送出することがあります。

引数 @code{path} を指定して @ref{1c6e,,監査イベント} @code{os.chdir} を送出します。


バージョン 3.3 で変更: 一部のプラットフォームで、`path' にファイル記述子の指定をサポートしました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex chflags() (os モジュール)
@anchor{library/os os chflags}@anchor{1305}
@deffn {の関数} os.chflags (path, flags, *, follow_symlinks=True)

`path' のフラグを `flags' に変更します。 `flags' は、以下の値 (@ref{d6,,stat} モジュールで定義されているもの ) をビット単位の論理和で組み合わせることができます :


@itemize *

@item 
@ref{2c89,,stat.UF_NODUMP}

@item 
@ref{2c8a,,stat.UF_IMMUTABLE}

@item 
@ref{2c8b,,stat.UF_APPEND}

@item 
@ref{2c8c,,stat.UF_OPAQUE}

@item 
@ref{2c8d,,stat.UF_NOUNLINK}

@item 
@ref{2c8e,,stat.UF_COMPRESSED}

@item 
@ref{2c91,,stat.UF_HIDDEN}

@item 
@ref{2c95,,stat.SF_ARCHIVED}

@item 
@ref{2c96,,stat.SF_IMMUTABLE}

@item 
@ref{2c97,,stat.SF_APPEND}

@item 
@ref{2c99,,stat.SF_NOUNLINK}

@item 
@ref{2c9a,,stat.SF_SNAPSHOT}
@end itemize

この関数は @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

引数 @code{path}, @code{flags} を指定して @ref{1c6e,,監査イベント} @code{os.chflags} を送出します。

@ref{213f,,Availability}: Unix, not WASI.


バージョン 3.3 で変更: Added the `follow_symlinks' parameter.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex chmod() (os モジュール)
@anchor{library/os os chmod}@anchor{529}
@deffn {の関数} os.chmod (path, mode, *, dir_fd=None, follow_symlinks=True)

`path' のモードを数値 `mode' に変更します。 `mode' は、 (@ref{d6,,stat} モジュールで定義されている ) 以下の値のいずれかまたはビット単位の論理和で組み合わせた値を取り得ます :


@itemize *

@item 
@ref{2c75,,stat.S_ISUID}

@item 
@ref{2c76,,stat.S_ISGID}

@item 
@ref{2c78,,stat.S_ENFMT}

@item 
@ref{2c79,,stat.S_ISVTX}

@item 
@ref{2c85,,stat.S_IREAD}

@item 
@ref{2c86,,stat.S_IWRITE}

@item 
@ref{2c87,,stat.S_IEXEC}

@item 
@ref{2c7a,,stat.S_IRWXU}

@item 
@ref{2c7b,,stat.S_IRUSR}

@item 
@ref{2c7c,,stat.S_IWUSR}

@item 
@ref{2c7d,,stat.S_IXUSR}

@item 
@ref{2c7e,,stat.S_IRWXG}

@item 
@ref{2c7f,,stat.S_IRGRP}

@item 
@ref{2c80,,stat.S_IWGRP}

@item 
@ref{2c77,,stat.S_IXGRP}

@item 
@ref{2c81,,stat.S_IRWXO}

@item 
@ref{2c82,,stat.S_IROTH}

@item 
@ref{2c83,,stat.S_IWOTH}

@item 
@ref{2c84,,stat.S_IXOTH}
@end itemize

この関数は @ref{d53,,ファイル記述子の指定} 、 @ref{1302,,ディレクトリ記述子への相対パス} 、および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

@cartouche
@quotation 注釈 
Although Windows supports @ref{529,,chmod()}, you can only set the file's
read-only flag with it (via the @code{stat.S_IWRITE} and @code{stat.S_IREAD}
constants or a corresponding integer value).  All other bits are ignored.
The default value of `follow_symlinks' is @code{False} on Windows.

The function is limited on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.
@end quotation
@end cartouche

引数 @code{path}, @code{mode}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.chmod} を送出します。


バージョン 3.3 で変更: `path' にオープンしているファイル記述子の指定のサポート、および引数 `dir_fd' と `follow_symlinks' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.13 で変更: Added support for a file descriptor and the `follow_symlinks' argument
on Windows.

@end deffn

@geindex chown() (os モジュール)
@anchor{library/os os chown}@anchor{1306}
@deffn {の関数} os.chown (path, uid, gid, *, dir_fd=None, follow_symlinks=True)

`path' の所有者 id およびグループ id を、数値 `uid' および `gid' に変更します。いずれかの id を変更せずにおくには、その値として -1 を指定します。

この関数は @ref{d53,,ファイル記述子の指定} 、 @ref{1302,,ディレクトリ記述子への相対パス} 、および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

数値 id の他に名前でも受け取る高水準関数の @ref{548,,shutil.chown()} を参照してください。

引数 @code{path}, @code{uid}, @code{gid}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.chown} を送出します。

@ref{213f,,Availability}: Unix.

The function is limited on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.


バージョン 3.3 で変更: `path' にオープンしているファイル記述子の指定のサポート、および引数 `dir_fd' と `follow_symlinks' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex chroot() (os モジュール)
@anchor{library/os os chroot}@anchor{1d7c}
@deffn {の関数} os.chroot (path)

現在のプロセスのルートディレクトリを `path' に変更します。

@ref{213f,,Availability}: Unix, not WASI, not Android.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex fchdir() (os モジュール)
@anchor{library/os os fchdir}@anchor{f89}
@deffn {の関数} os.fchdir (fd)

現在の作業ディレクトリをファイル記述子 `fd' が表すディレクトリに変更します。記述子はオープンしているファイルではなく、オープンしたディレクトリを参照していなければなりません。Python 3.3 以降では @code{os.chdir(fd)} と等価です。

引数 @code{path} を指定して @ref{1c6e,,監査イベント} @code{os.chdir} を送出します。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex getcwd() (os モジュール)
@anchor{library/os os getcwd}@anchor{1909}
@deffn {の関数} os.getcwd ()

現在の作業ディレクトリを表す文字列を返します。
@end deffn

@geindex getcwdb() (os モジュール)
@anchor{library/os os getcwdb}@anchor{c82}
@deffn {の関数} os.getcwdb ()

現在の作業ディレクトリを表すバイト列を返します。


バージョン 3.8 で変更: この関数は Windows において ANSI コードページ ではなく UTF-8 エンコーディングを使うようになりました: 変更の背景については 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} をご覧ください。この関数は Windows において非推奨になりません。

@end deffn

@geindex lchflags() (os モジュール)
@anchor{library/os os lchflags}@anchor{307a}
@deffn {の関数} os.lchflags (path, flags)

`path' のフラグを数値 `flags' に設定します。@ref{1305,,chflags()} に似ていますが、シンボリックリンクをたどりません。Python 3.3 以降では @code{os.chflags(path, flags, follow_symlinks=False)} と等価です。

引数 @code{path}, @code{flags} を指定して @ref{1c6e,,監査イベント} @code{os.chflags} を送出します。

@ref{213f,,Availability}: Unix, not WASI.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex lchmod() (os モジュール)
@anchor{library/os os lchmod}@anchor{528}
@deffn {の関数} os.lchmod (path, mode)

`path' のモードを数値 `mode' に変更します。パスがシンボリックリンクの場合はそのリンク先ではなくシンボリックリンクそのものに対して作用します。`mode' に指定できる値については @ref{529,,chmod()} のドキュメントを参照してください。Python 3.3 以降では @code{os.chmod(path, mode, follow_symlinks=False)} と等価です。

@code{lchmod()} is not part of POSIX, but Unix implementations may have it if
changing the mode of symbolic links is supported.

引数 @code{path}, @code{mode}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.chmod} を送出します。

@ref{213f,,Availability}: Unix, Windows, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.13 で変更: Added support on Windows.

@end deffn

@geindex lchown() (os モジュール)
@anchor{library/os os lchown}@anchor{307b}
@deffn {の関数} os.lchown (path, uid, gid)

`path' の所有者 id およびグループ id を、数値 `uid' および `gid' に変更します。この関数はシンボリックリンクをたどりません。Python 3.3 以降では @code{os.chown(path, uid, gid, follow_symlinks=False)} と等価です。

引数 @code{path}, @code{uid}, @code{gid}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.chown} を送出します。

@ref{213f,,Availability}: Unix.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex link() (os モジュール)
@anchor{library/os os link}@anchor{1307}
@deffn {の関数} os.link (src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)

`src' を指し示すハードリンク `dst' を作成します。

This function can support specifying `src_dir_fd' and/or `dst_dir_fd' to
supply @ref{1302,,paths relative to directory descriptors}, and @ref{1303,,not following symlinks}.
The default value of `follow_symlinks' is @code{False} on Windows.

引数 @code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.link} を送出します。

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.2 で変更: Windows サポートを追加しました。



バージョン 3.3 で変更: Added the `src_dir_fd', `dst_dir_fd', and `follow_symlinks' parameters.



バージョン 3.6 で変更: `src' と `dst' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex listdir() (os モジュール)
@anchor{library/os os listdir}@anchor{1312}
@deffn {の関数} os.listdir (path='.')

`path' に指定したディレクトリに含まれるエントリ名のリストを返します。リストの順番は不定です。特別なエントリ @code{'.'} と @code{'..'} はリストに含まれません。この関数の呼び出し中にディレクトリからファイルが削除されたり、ディレクトリにファイルが追加されたりした場合、それらのファイルがリストに含まれるかどうかは不定です。

`path' に @ref{5a1,,path-like オブジェクト} を指定することもできます。  `path' が  (直接的または間接的に @ref{e4b,,PathLike} インターフェースを介した) @code{bytes} 型の場合、戻り値のファイル名も @code{bytes} 型になります; それ以外の場合、ファイル名は @code{str} 型です。

この関数は @ref{d53,,ファイル記述子の指定} もサポートしています; ファイル記述子はディレクトリを参照していなくてはなりません。

引数 @code{path} を指定して @ref{1c6e,,監査イベント} @code{os.listdir} を送出します。

@cartouche
@quotation 注釈 
@code{文字列型} のファイル名を @code{バイト列型} にエンコードするには、@ref{e4f,,fsencode()} を使用します。
@end quotation
@end cartouche


@subsubheading 参考


ディレクトリエントリに加えてファイル属性情報も返す @ref{c54,,scandir()} 関数の方が、多くの一般的な用途では使い勝手が良くなります。



バージョン 3.2 で変更: 引数 `path' は任意になりました。



バージョン 3.3 で変更: `path' へのオープン・ファイル記述子の指定をサポートしました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex listdrives() (os モジュール)
@anchor{library/os os listdrives}@anchor{6c5}
@deffn {の関数} os.listdrives ()

Return a list containing the names of drives on a Windows system.

A drive name typically looks like @code{'C:\\'}. Not every drive name
will be associated with a volume, and some may be inaccessible for
a variety of reasons, including permissions, network connectivity
or missing media. This function does not test for access.

May raise @ref{2c0,,OSError} if an error occurs collecting the drive
names.

Raises an @ref{1c6e,,auditing event} @code{os.listdrives} with no arguments.

@ref{213f,,Availability}: Windows


Added in version 3.12.

@end deffn

@geindex listmounts() (os モジュール)
@anchor{library/os os listmounts}@anchor{6c7}
@deffn {の関数} os.listmounts (volume)

Return a list containing the mount points for a volume on a Windows
system.

`volume' must be represented as a GUID path, like those returned by
@ref{6c6,,os.listvolumes()}. Volumes may be mounted in multiple locations
or not at all. In the latter case, the list will be empty. Mount
points that are not associated with a volume will not be returned by
this function.

The mount points return by this function will be absolute paths, and
may be longer than the drive name.

Raises @ref{2c0,,OSError} if the volume is not recognized or if an error
occurs collecting the paths.

Raises an @ref{1c6e,,auditing event} @code{os.listmounts} with argument @code{volume}.

@ref{213f,,Availability}: Windows


Added in version 3.12.

@end deffn

@geindex listvolumes() (os モジュール)
@anchor{library/os os listvolumes}@anchor{6c6}
@deffn {の関数} os.listvolumes ()

Return a list containing the volumes in the system.

Volumes are typically represented as a GUID path that looks like
@code{\\?\Volume@{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx@}\}. Files can
usually be accessed through a GUID path, permissions allowing.
However, users are generally not familiar with them, and so the
recommended use of this function is to retrieve mount points
using @ref{6c7,,os.listmounts()}.

May raise @ref{2c0,,OSError} if an error occurs collecting the volumes.

Raises an @ref{1c6e,,auditing event} @code{os.listvolumes} with no arguments.

@ref{213f,,Availability}: Windows


Added in version 3.12.

@end deffn

@geindex lstat() (os モジュール)
@anchor{library/os os lstat}@anchor{6c8}
@deffn {の関数} os.lstat (path, *, dir_fd=None)

Perform the equivalent of an @code{lstat()} system call on the given path.
Similar to @ref{26d,,stat()}, but does not follow symbolic links. Return a
@ref{16da,,stat_result} object.

シンボリックリンクをサポートしていないプラットフォームでは @ref{26d,,stat()} の別名です。

Python 3.3 以降では @code{os.stat(path, dir_fd=dir_fd, follow_symlinks=False)} と等価です。

この関数は @ref{1302,,ディレクトリ記述子への相対パス} もサポートすることができます。


@subsubheading 参考


@ref{26d,,stat()} 関数。



バージョン 3.2 で変更: Windows 6.0 (Vista) のシンボリックリンクをサポートしました。



バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.8 で変更: On Windows, now opens reparse points that represent another path
(name surrogates), including symbolic links and directory junctions.
Other kinds of reparse points are resolved by the operating system as
for @ref{26d,,stat()}.

@end deffn

@geindex mkdir() (os モジュール)
@anchor{library/os os mkdir}@anchor{52b}
@deffn {の関数} os.mkdir (path, mode=0o777, *, dir_fd=None)

ディレクトリ `path' を数値モード `mode' で作成します。

If the directory already exists, @ref{1221,,FileExistsError} is raised. If a parent
directory in the path does not exist, @ref{264,,FileNotFoundError} is raised.
@anchor{library/os mkdir-modebits}@anchor{307c}
いくつかのシステムにおいては `mode' は無視されます。それが使われる時には、最初に現在の umask 値でマスクされます。もし最後の 9 ビット (つまり `mode' の8進法表記の最後の3桁) を除いたビットが設定されていたら、それらの意味はプラットフォームに依存します。いくつかのプラットフォームではそれらは無視され、それらを設定するためには明示的に @ref{529,,chmod()} を呼ぶ必要があるでしょう。

On Windows, a `mode' of @code{0o700} is specifically handled to apply access
control to the new directory such that only the current user and
administrators have access. Other values of `mode' are ignored.

この関数は @ref{1302,,ディレクトリ記述子への相対パス} もサポートすることができます。

一時ディレクトリを作成することもできます : @ref{e6,,tempfile} モジュールの @ref{52d,,tempfile.mkdtemp()} 関数を参照してください。

引数 @code{path}, @code{mode}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.mkdir} を送出します。


バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.13 で変更: Windows now handles a `mode' of @code{0o700}.

@end deffn

@geindex makedirs() (os モジュール)
@anchor{library/os os makedirs}@anchor{52c}
@deffn {の関数} os.makedirs (name, mode=0o777, exist_ok=False)

@geindex ディレクトリ;作成
@geindex UNC パス;os.makedirs()

再帰的にディレクトリを作成する関数です。@ref{52b,,mkdir()} と似ていますが、末端ディレクトリを作成するために必要なすべての中間ディレクトリも作成します。

The `mode' parameter is passed to @ref{52b,,mkdir()} for creating the leaf
directory; see @ref{307c,,the mkdir() description} for how it
is interpreted.  To set the file permission bits of any newly created parent
directories you can set the umask before invoking @ref{52c,,makedirs()}.  The
file permission bits of existing parent directories are not changed.

`exist_ok' の値が @code{False} の場合 (デフォルト)、対象のディレクトリがすでに存在すると @ref{1221,,FileExistsError} を送出します。

@cartouche
@quotation 注釈 
作成するパス要素に @ref{307d,,pardir} (UNIX では "..") が含まれる場合、@ref{52c,,makedirs()} は混乱します。
@end quotation
@end cartouche

この関数は UNC パスを正しく扱えるようになりました。

引数 @code{path}, @code{mode}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.mkdir} を送出します。


バージョン 3.2 で変更: Added the `exist_ok' parameter.



バージョン 3.4.1 で変更: Python 3.4.1 より前、 `exist_ok' が @code{True} でそのディレクトリが既存の場合でも、 @ref{52c,,makedirs()} は `mode' が既存ディレクトリのモードと合わない場合にはエラーにしようとしていました。このモードチェックの振る舞いを安全に実装することが出来なかったため、 Python 3.4.1 でこのチェックは削除されました。 bpo-21082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21082} を参照してください。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.7 で変更: The `mode' argument no longer affects the file permission bits of
newly created intermediate-level directories.

@end deffn

@geindex mkfifo() (os モジュール)
@anchor{library/os os mkfifo}@anchor{f90}
@deffn {の関数} os.mkfifo (path, mode=0o666, *, dir_fd=None)

FIFO (名前付きパイプ) `path' を数値モード `mode' で作成します。先に現在の umask 値でマスクされます。

この関数は @ref{1302,,ディレクトリ記述子への相対パス} もサポートすることができます。

FIFO は通常のファイルのようにアクセスできるパイプです。 FIFO は ( 例えば @ref{130d,,os.unlink()} を使って ) 削除されるまで存在しつづけます。一般的に、 FIFO は " クライアント " と " サーバー " 形式のプロセス間でランデブーを行うために使われます : この時、サーバーは FIFO を読み込み用に、クライアントは書き出し用にオープンします。 @ref{f90,,mkfifo()} は FIFO をオープンしない --- 単にランデブーポイントを作成するだけ --- なので注意してください。

@ref{213f,,Availability}: Unix, not WASI.


バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex mknod() (os モジュール)
@anchor{library/os os mknod}@anchor{f91}
@deffn {の関数} os.mknod (path, mode=0o600, device=0, *, dir_fd=None)

`path' という名前で、ファイルシステムノード (ファイル、デバイス特殊ファイル、または名前つきパイプ) を作成します。`mode' は、作成するノードのアクセス権限とタイプの両方を @code{stat.S_IFREG}、@code{stat.S_IFCHR}、@code{stat.S_IFBLK}、および @code{stat.S_IFIFO} の組み合わせ (ビット単位の論理和) で指定します (これらの定数は @ref{d6,,stat} で利用可能です)。@code{stat.S_IFCHR} と @code{stat.S_IFBLK} を指定した場合、`devide' は新しく作成されたデバイス特殊ファイルを (おそらく @ref{1960,,os.makedev()} を使って) 定義し、それ以外の定数を指定した場合は無視されます。

この関数は @ref{1302,,ディレクトリ記述子への相対パス} もサポートすることができます。

@ref{213f,,Availability}: Unix, not WASI.


バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex major() (os モジュール)
@anchor{library/os os major}@anchor{195e}
@deffn {の関数} os.major (device, /)

Extract the device major number from a raw device number (usually the
@code{st_dev} or @code{st_rdev} field from @code{stat}).
@end deffn

@geindex minor() (os モジュール)
@anchor{library/os os minor}@anchor{195f}
@deffn {の関数} os.minor (device, /)

Extract the device minor number from a raw device number (usually the
@code{st_dev} or @code{st_rdev} field from @code{stat}).
@end deffn

@geindex makedev() (os モジュール)
@anchor{library/os os makedev}@anchor{1960}
@deffn {の関数} os.makedev (major, minor, /)

メジャーおよびマイナーデバイス番号から、新しく RAW デバイス番号を作成します。
@end deffn

@geindex pathconf() (os モジュール)
@anchor{library/os os pathconf}@anchor{1313}
@deffn {の関数} os.pathconf (path, name)

名前付きファイルに関連するシステム設定情報を返します。 `name' には取得したい設定名を指定します ; これは定義済みのシステム値名の文字列で、多くの標準 (POSIX.1 、 Unix 95 、 Unix 98 その他 ) で定義されています。プラットフォームによっては別の名前も定義しています。ホストオペレーティングシステムの関知する名前は @code{pathconf_names} 辞書で与えられています。このマップ型オブジェクトに入っていない設定変数については、 `name' に整数を渡してもかまいません。

`name' が不明の文字列である場合、 @ref{2ec,,ValueError} を送出します。 `name' の特定の値がホストシステムでサポートされていない場合、 @code{pathconf_names} に含まれていたとしても、 @ref{1dd2,,errno.EINVAL} をエラー番号として @ref{2c0,,OSError} を送出します。

この関数は @ref{d53,,ファイル記述子の指定} をサポートしています。

@ref{213f,,Availability}: Unix.


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex pathconf_names (os モジュール)
@anchor{library/os os pathconf_names}@anchor{307e}
@deffn {データ} os.pathconf_names

@ref{1313,,pathconf()} および @ref{303b,,fpathconf()} が受理するシステム設定名を、ホストオペレーティングシステムで定義されている整数値に対応付けている辞書です。この辞書はシステムでどの設定名が定義されているかを知るために利用できます。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex readlink() (os モジュール)
@anchor{library/os os readlink}@anchor{b1a}
@deffn {の関数} os.readlink (path, *, dir_fd=None)

シンボリックリンクが指しているパスを表す文字列を返します。返される値は絶対パスにも、相対パスにもなり得ます ; 相対パスの場合、 @code{os.path.join(os.path.dirname(path), result)} を使って絶対パスに変換することができます。

If the `path' is a string object (directly or indirectly through a
@ref{e4b,,PathLike} interface), the result will also be a string object,
and the call may raise a UnicodeDecodeError. If the `path' is a bytes
object (direct or indirectly), the result will be a bytes object.

この関数は @ref{1302,,ディレクトリ記述子への相対パス} もサポートすることができます。

When trying to resolve a path that may contain links, use
@ref{262,,realpath()} to properly handle recursion and platform
differences.

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.2 で変更: Windows 6.0 (Vista) のシンボリックリンクをサポートしました。



バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: Unixで、 @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.8 で変更: Windowsで、 @ref{5a1,,path-like object} と bytes オブジェクトを受け入れるようになりました。

Added support for directory junctions, and changed to return the
substitution path (which typically includes @code{\\?\} prefix) rather
than the optional "print name" field that was previously returned.

@end deffn

@geindex remove() (os モジュール)
@anchor{library/os os remove}@anchor{1308}
@deffn {の関数} os.remove (path, *, dir_fd=None)

Remove (delete) the file `path'.  If `path' is a directory, an
@ref{2c0,,OSError} is raised.  Use @ref{130b,,rmdir()} to remove directories.
If the file does not exist, a @ref{264,,FileNotFoundError} is raised.

この関数は @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

Windows では、使用中のファイルを削除しようとすると例外を送出します; Unixでは、ディレクトリエントリは削除されますが、記憶装置上に割り当てられたファイル領域は元のファイルが使われなくなるまで残されます。

この関数は意味論的に @ref{130d,,unlink()} と同一です。

引数 @code{path}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.remove} を送出します。


バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex removedirs() (os モジュール)
@anchor{library/os os removedirs}@anchor{307f}
@deffn {の関数} os.removedirs (name)

@geindex ディレクトリ;削除

再帰的なディレクトリ削除関数です。 @ref{130b,,rmdir()} と同じように動作しますが、末端ディレクトリがうまく削除できるかぎり、 @ref{307f,,removedirs()} は `path' に現れる親ディレクトリをエラーが送出されるまで ( このエラーは通常、指定したディレクトリの親ディレクトリが空でないことを意味するだけなので無視されます ) 順に削除することを試みます。例えば、 @code{os.removedirs('foo/bar/baz')} では最初にディレクトリ @code{'foo/bar/baz'} を削除し、次に @code{'foo/bar'} さらに @code{'foo'} をそれらが空ならば削除します。末端のディレクトリが削除できなかった場合には @ref{2c0,,OSError} が送出されます。

引数 @code{path}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.remove} を送出します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex rename() (os モジュール)
@anchor{library/os os rename}@anchor{1309}
@deffn {の関数} os.rename (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename the file or directory `src' to `dst'. If `dst' exists, the operation
will fail with an @ref{2c0,,OSError} subclass in a number of cases:

On Windows, if `dst' exists a @ref{1221,,FileExistsError} is always raised.
The operation may fail if `src' and `dst' are on different filesystems. Use
@ref{c51,,shutil.move()} to support moves to a different filesystem.

On Unix, if `src' is a file and `dst' is a directory or vice-versa, an
@ref{1264,,IsADirectoryError} or a @ref{1265,,NotADirectoryError} will be raised
respectively.  If both are directories and `dst' is empty, `dst' will be
silently replaced.  If `dst' is a non-empty directory, an @ref{2c0,,OSError}
is raised. If both are files, `dst' will be replaced silently if the user
has permission.  The operation may fail on some Unix flavors if `src' and
`dst' are on different filesystems.  If successful, the renaming will be an
atomic operation (this is a POSIX requirement).

この関数は `src_dir_fd' と `dst_dir_fd' のどちらかまたは両方の指定に @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

対象の上書きがクロスプラットフォームになる場合は @ref{130a,,replace()} を使用してください。

引数 @code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.rename} を送出します。


バージョン 3.3 で変更: Added the `src_dir_fd' and `dst_dir_fd' parameters.



バージョン 3.6 で変更: `src' と `dst' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex renames() (os モジュール)
@anchor{library/os os renames}@anchor{3080}
@deffn {の関数} os.renames (old, new)

再帰的にディレクトリやファイル名を変更する関数です。 @ref{1309,,rename()} のように動作しますが、新たなパス名を持つファイルを配置するために必要な途中のディレクトリ構造をまず作成しようと試みます。名前変更の後、元のファイル名のパス要素は @ref{307f,,removedirs()} を使って右側から順に削除されます。

@cartouche
@quotation 注釈 
この関数はコピー元の末端のディレクトリまたはファイルを削除する権限がない場合には失敗します。
@end quotation
@end cartouche

引数 @code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.rename} を送出します。


バージョン 3.6 で変更: `old' と `new' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex replace() (os モジュール)
@anchor{library/os os replace}@anchor{130a}
@deffn {の関数} os.replace (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

ファイルまたはディレクトリ `src' の名前を `dst' へ変更します。`dst' が空でないディレクトリの場合 @ref{2c0,,OSError} が送出されます。`dst' が存在し、かつファイルの場合、ユーザーの権限がある限り暗黙のうちに置き換えられます。`src' と `dst' が異なるファイルシステム上にあると失敗することがあります。ファイル名の変更が成功する場合はアトミック操作となります (これは POSIX 要求仕様です)。

この関数は `src_dir_fd' と `dst_dir_fd' のどちらかまたは両方の指定に @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

引数 @code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.rename} を送出します。


Added in version 3.3.



バージョン 3.6 で変更: `src' と `dst' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex rmdir() (os モジュール)
@anchor{library/os os rmdir}@anchor{130b}
@deffn {の関数} os.rmdir (path, *, dir_fd=None)

Remove (delete) the directory `path'.  If the directory does not exist or is
not empty, a @ref{264,,FileNotFoundError} or an @ref{2c0,,OSError} is raised
respectively.  In order to remove whole directory trees,
@ref{356,,shutil.rmtree()} can be used.

この関数は @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

引数 @code{path}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.rmdir} を送出します。


バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex scandir() (os モジュール)
@anchor{library/os os scandir}@anchor{c54}
@deffn {の関数} os.scandir (path='.')

Return an iterator of @ref{6c3,,os.DirEntry} objects corresponding to the
entries in the directory given by `path'. The entries are yielded in
arbitrary order, and the special entries @code{'.'} and @code{'..'} are not
included.  If a file is removed from or added to the directory after
creating the iterator, whether an entry for that file be included is
unspecified.

@ref{1312,,listdir()} の代わりに @ref{c54,,scandir()} を使用すると、ファイルタイプや属性情報も必要とするコードのパフォーマンスが大幅に向上します。これは、オペレーティングシステムがディレクトリのスキャン中にこの情報を提供した場合、@ref{6c3,,os.DirEntry} オブジェクトがその情報を公開するからです。すべての @ref{6c3,,os.DirEntry} メソッドはシステムコールを実行する場合がありますが、@ref{3081,,is_dir()} と @ref{f84,,is_file()} は、通常はシンボリックリンクにしかシステムコールを必要としません。@ref{1a6b,,os.DirEntry.stat()} は、Unix 上では常にシステムコールを必要としますが、Windows ではシンボリックリンク用にシステムコールを一つ必要とするだけです。

`path' may be a @ref{5a1,,path-like object}.  If `path' is of type @code{bytes}
(directly or indirectly through the @ref{e4b,,PathLike} interface),
the type of the @ref{3082,,name} and @ref{19f8,,path}
attributes of each @ref{6c3,,os.DirEntry} will be @code{bytes}; in all other
circumstances, they will be of type @code{str}.

この関数は @ref{d53,,ファイル記述子の指定} もサポートしています; ファイル記述子はディレクトリを参照していなくてはなりません。

引数 @code{path} を指定して @ref{1c6e,,監査イベント} @code{os.scandir} を送出します。

@ref{c54,,scandir()} イテレータは、 @ref{1e1,,コンテキストマネージャ} プロトコルをサポートし、次のメソッドを持ちます。

@geindex close() (os.scandir のメソッド)
@anchor{library/os os scandir close}@anchor{eb8}
@deffn {メソッド} scandir.close ()

イテレータを閉じ、獲得した資源を開放します。

この関数は、イテレータがすべて消費されるか、ガーベージコレクトされた、もしくはイテレート中にエラーが発生した際に自動的に呼び出されます。しかし、 @ref{186,,with} 文を用いるか、明示的に呼び出すことを推奨します。


Added in version 3.6.

@end deffn

次の単純な例では、@ref{c54,,scandir()} を使用して、指定した `path' 内の先頭が @code{'.'} でないすべてのファイル (ディレクトリを除く) をすべて表示します。@code{entry.is_file()} を呼び出しても、通常は追加のシステムコールは行われません:

@example
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
@end example

@cartouche
@quotation 注釈 
On Unix-based systems, @ref{c54,,scandir()} uses the system's
opendir()@footnote{https://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html}
and
readdir()@footnote{https://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html}
functions. On Windows, it uses the Win32
FindFirstFileW@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx}
and
FindNextFileW@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx}
functions.
@end quotation
@end cartouche


Added in version 3.5.



バージョン 3.6 で変更: Added support for the @ref{1e1,,context manager} protocol and the
@ref{eb8,,close()} method.  If a @ref{c54,,scandir()} iterator is neither
exhausted nor explicitly closed a @ref{54c,,ResourceWarning} will be emitted
in its destructor.

関数が @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.7 で変更: Unix で @ref{d53,,ファイル記述子の指定} のサポートが追加されました。

@end deffn

@geindex DirEntry (os のクラス)
@anchor{library/os os DirEntry}@anchor{6c3}
@deffn {クラス} os.DirEntry

ディレクトリエントリのファイルパスとその他のファイル属性を公開するために、@ref{c54,,scandir()} が yield するオブジェクトです。

@ref{c54,,scandir()} は、追加のシステムコールを実行することなく、この情報をできるだけ多く提供します。@code{stat()} または @code{lstat()} システムコールが実行された場合、@code{os.DirEntry} オブジェクトは結果をキャッシュします。

@code{os.DirEntry} インスタンスは、寿命の長いデータ構造に保存されることは想定されていません。ファイルメタデータが変更された場合や、 @ref{c54,,scandir()} が呼び出されてから長時間が経過した場合は、 @code{os.stat(entry.path)} を呼び出して最新の情報を取得してください。

@code{os.DirEntry} のメソッドはオペレーティングシステムコールを実行する場合があるため、それらは @ref{2c0,,OSError} も送出する場合があります。エラーを細かく制御する必要がある場合、 @code{os.DirEntry} のメソッドの一つの呼び出し時に @ref{2c0,,OSError} を捕捉して、適切な処理を行うことができます。

To be directly usable as a @ref{5a1,,path-like object}, @code{os.DirEntry}
implements the @ref{e4b,,PathLike} interface.

@code{os.DirEntry} インスタンスの属性とメソッドは以下の通りです:

@geindex name (os.DirEntry の属性)
@anchor{library/os os DirEntry name}@anchor{3082}
@deffn {の属性} name

@ref{c54,,scandir()} の `path' 引数に対して相対的な、エントリのベースファイル名です。

The @ref{3003,,name} attribute will be @code{bytes} if the @ref{c54,,scandir()}
`path' argument is of type @code{bytes} and @code{str} otherwise.  Use
@ref{e4e,,fsdecode()} to decode byte filenames.
@end deffn

@geindex path (os.DirEntry の属性)
@anchor{library/os os DirEntry path}@anchor{19f8}
@deffn {の属性} path

The entry's full path name: equivalent to @code{os.path.join(scandir_path,
entry.name)} where `scandir_path' is the @ref{c54,,scandir()} `path'
argument.  The path is only absolute if the @ref{c54,,scandir()} `path'
argument was absolute.  If the @ref{c54,,scandir()} `path'
argument was a @ref{d53,,file descriptor}, the @ref{a6,,path}
attribute is the same as the @ref{3003,,name} attribute.

The @ref{a6,,path} attribute will be @code{bytes} if the @ref{c54,,scandir()}
`path' argument is of type @code{bytes} and @code{str} otherwise.  Use
@ref{e4e,,fsdecode()} to decode byte filenames.
@end deffn

@geindex inode() (os.DirEntry のメソッド)
@anchor{library/os os DirEntry inode}@anchor{1a4d}
@deffn {メソッド} inode ()

項目の inode 番号を返します。

結果は @code{os.DirEntry} オブジェクトにキャッシュされます。最新の情報を取得するには @code{os.stat(entry.path, follow_symlinks=False).st_ino} を使用してください。

Windows 上では、最初のキャッシュされていない呼び出しでシステムコールが必要ですが、 Unix 上では必要ありません。
@end deffn

@geindex is_dir() (os.DirEntry のメソッド)
@anchor{library/os os DirEntry is_dir}@anchor{3081}
@deffn {メソッド} is_dir (*, follow_symlinks=True)

この項目がディレクトリまたはディレクトリへのシンボリックリンクである場合、 @code{True} を返します。項目がそれ以外のファイルやそれ以外のファイルへのシンボリックリンクである場合や、もはや存在しない場合は @code{False} を返します。

`follow_symlinks' が @code{False} の場合、項目がディレクトリ (シンボリックリンクはたどりません) の場合にのみ @code{True} を返します。項目がディレクトリ以外のファイルである場合や、項目がもはや存在しない場合は @code{False} を返します。

結果は @code{os.DirEntry} オブジェクトにキャッシュされます。`follow_symlinks' が @code{True} の場合と @code{False} の場合とでは、別のオブジェクトにキャッシュされます。最新の情報を取得するには @ref{2c5c,,stat.S_ISDIR()} と共に @ref{26d,,os.stat()} を呼び出してください。

多くの場合、最初のキャッシュされない呼び出しでは、システムコールは必要とされません。具体的には、シンボリックリンク以外では、Windows も Unix もシステムコールを必要としません。ただし、@code{dirent.d_type == DT_UNKNOWN} を返す、ネットワークファイルシステムなどの特定の Unix ファイルシステムは例外です。項目がシンボリックリンクの場合、`follow_symlinks' が @code{False} の場合を除き、シンボリックリンクをたどるためにシステムコールが必要となります。

このメソッドは @ref{f3e,,PermissionError} のような @ref{2c0,,OSError} を送出することがありますが、 @ref{264,,FileNotFoundError} は捕捉され送出されません。
@end deffn

@geindex is_file() (os.DirEntry のメソッド)
@anchor{library/os os DirEntry is_file}@anchor{f84}
@deffn {メソッド} is_file (*, follow_symlinks=True)

この項目がファイルまたはファイルへのシンボリックリンクである場合、 @code{True} を返します。項目がディレクトリやファイル以外の項目へのシンボリックリンクである場合や、もはや存在しない場合は @code{False} を返します。

`follow_symlinks' が @code{False} の場合、項目がファイル (シンボリックリンクはたどりません) の場合にのみ @code{True} を返します。項目がディレクトリやその他のファイル以外の項目である場合や、項目がもはや存在しない場合は @code{False} を返します。

結果は @code{os.DirEntry} オブジェクトにキャッシュされます。キャッシュ、システムコール、例外は、@ref{3081,,is_dir()} と同様に行われます。
@end deffn

@geindex is_symlink() (os.DirEntry のメソッド)
@anchor{library/os os DirEntry is_symlink}@anchor{3083}
@deffn {メソッド} is_symlink ()

この項目がシンボリックリンクの場合 (たとえ破損していても)、@code{True} を返します。項目がディレクトリやあらゆる種類のファイルの場合、またはもはや存在しない場合は @code{False} を返します。

結果は @code{os.DirEntry} オブジェクトにキャッシュされます。
最新の情報をフェッチするには @ref{c01,,os.path.islink()} を呼び出してください。

多くの場合、最初のキャッシュされない呼び出しでは、システムコールは必要とされません。具体的には、Windows も Unix もシステムコールを必要としません。ただし、@code{dirent.d_type == DT_UNKNOWN} を返す、ネットワークファイルシステムなどの特定の Unix ファイルシステムは例外です。

このメソッドは @ref{f3e,,PermissionError} のような @ref{2c0,,OSError} を送出することがありますが、 @ref{264,,FileNotFoundError} は捕捉され送出されません。
@end deffn

@geindex is_junction() (os.DirEntry のメソッド)
@anchor{library/os os DirEntry is_junction}@anchor{6c4}
@deffn {メソッド} is_junction ()

Return @code{True} if this entry is a junction (even if broken);
return @code{False} if the entry points to a regular directory, any kind
of file, a symlink, or if it doesn't exist anymore.

The result is cached on the @code{os.DirEntry} object. Call
@ref{6ca,,os.path.isjunction()} to fetch up-to-date information.


Added in version 3.12.

@end deffn

@geindex stat() (os.DirEntry のメソッド)
@anchor{library/os os DirEntry stat}@anchor{1a6b}
@deffn {メソッド} stat (*, follow_symlinks=True)

この項目の @ref{16da,,stat_result} オブジェクトを返します。このメソッドは、デフォルトでシンボリックリンクをたどります。シンボリックリンクを開始するには、 @code{follow_symlinks=False} 引数を追加します。

On Unix, this method always requires a system call. On Windows, it
only requires a system call if `follow_symlinks' is @code{True} and the
entry is a reparse point (for example, a symbolic link or directory
junction).

Windows では、@ref{16da,,stat_result} の @code{st_ino} 、 @code{st_dev} 、 @code{st_nlink} 属性は常にゼロに設定されます。これらの属性を取得するには、 @ref{26d,,os.stat()} を呼び出します。

結果は @code{os.DirEntry} オブジェクトにキャッシュされます。`follow_symlinks' が @code{True} の場合と @code{False} の場合とでは、別のオブジェクトにキャッシュされます。最新の情報を取得するには、 @ref{26d,,os.stat()} を呼び出してください。
@end deffn

Note that there is a nice correspondence between several attributes
and methods of @code{os.DirEntry} and of @ref{266,,pathlib.Path}.  In
particular, the @code{name} attribute has the same
meaning, as do the @code{is_dir()}, @code{is_file()}, @code{is_symlink()},
@code{is_junction()}, and @code{stat()} methods.


Added in version 3.5.



バージョン 3.6 で変更: @ref{e4b,,PathLike} インターフェースをサポートしました。Windowsで @ref{192,,bytes} パスをサポートしました。



バージョン 3.12 で変更: The @code{st_ctime} attribute of a stat result is deprecated on Windows.
The file creation time is properly available as @code{st_birthtime}, and
in the future @code{st_ctime} may be changed to return zero or the
metadata change time, if available.

@end deffn

@geindex stat() (os モジュール)
@anchor{library/os os stat}@anchor{26d}
@deffn {の関数} os.stat (path, *, dir_fd=None, follow_symlinks=True)

Get the status of a file or a file descriptor. Perform the equivalent of a
@code{stat()} system call on the given path. `path' may be specified as
either a string or bytes -- directly or indirectly through the @ref{e4b,,PathLike}
interface -- or as an open file descriptor. Return a @ref{16da,,stat_result}
object.

この関数は通常はシンボリックリンクをたどります。シンボリックリンクに対して stat したい場合は @code{follow_symlinks=False} とするか、 @ref{6c8,,lstat()} を利用してください。

この関数は @ref{d53,,ファイル記述子の指定} および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

On Windows, passing @code{follow_symlinks=False} will disable following all
name-surrogate reparse points, which includes symlinks and directory
junctions. Other types of reparse points that do not resemble links or that
the operating system is unable to follow will be opened directly. When
following a chain of multiple links, this may result in the original link
being returned instead of the non-link that prevented full traversal. To
obtain stat results for the final path in this case, use the
@ref{262,,os.path.realpath()} function to resolve the path name as far as
possible and call @ref{6c8,,lstat()} on the result. This does not apply to
dangling symlinks or junction points, which will raise the usual exceptions.

@geindex module;stat

以下はプログラム例です:

@example
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
@end example


@subsubheading 参考


@ref{f8c,,fstat()} と @ref{6c8,,lstat()}。



バージョン 3.3 で変更: Added the `dir_fd' and `follow_symlinks' parameters,
specifying a file descriptor instead of a path.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.8 で変更: On Windows, all reparse points that can be resolved by the operating
system are now followed, and passing @code{follow_symlinks=False}
disables following all name surrogate reparse points. If the operating
system reaches a reparse point that it is not able to follow, `stat' now
returns the information for the original path as if
@code{follow_symlinks=False} had been specified instead of raising an error.

@end deffn

@geindex stat_result (os のクラス)
@anchor{library/os os stat_result}@anchor{16da}
@deffn {クラス} os.stat_result

Object whose attributes correspond roughly to the members of the
@code{stat} structure. It is used for the result of @ref{26d,,os.stat()},
@ref{f8c,,os.fstat()} and @ref{6c8,,os.lstat()}.

属性:

@geindex st_mode (os.stat_result の属性)
@anchor{library/os os stat_result st_mode}@anchor{bff}
@deffn {の属性} st_mode

ファイルモード。ファイルタイプとファイルモードのビット （権限）。
@end deffn

@geindex st_ino (os.stat_result の属性)
@anchor{library/os os stat_result st_ino}@anchor{3084}
@deffn {の属性} st_ino

Platform dependent, but if non-zero, uniquely identifies the
file for a given value of @code{st_dev}. Typically:


@itemize *

@item 
the inode number on Unix,

@item 
the file index@footnote{https://msdn.microsoft.com/en-us/library/aa363788} on
Windows
@end itemize
@end deffn

@geindex st_dev (os.stat_result の属性)
@anchor{library/os os stat_result st_dev}@anchor{3085}
@deffn {の属性} st_dev

このファイルが存在するデバイスの識別子。
@end deffn

@geindex st_nlink (os.stat_result の属性)
@anchor{library/os os stat_result st_nlink}@anchor{3086}
@deffn {の属性} st_nlink

ハードリンクの数。
@end deffn

@geindex st_uid (os.stat_result の属性)
@anchor{library/os os stat_result st_uid}@anchor{3087}
@deffn {の属性} st_uid

ファイル所有者のユーザ識別子。
@end deffn

@geindex st_gid (os.stat_result の属性)
@anchor{library/os os stat_result st_gid}@anchor{3088}
@deffn {の属性} st_gid

ファイル所有者のグループ識別子。
@end deffn

@geindex st_size (os.stat_result の属性)
@anchor{library/os os stat_result st_size}@anchor{3089}
@deffn {の属性} st_size

ファイルが通常のファイルまたはシンボリックリンクの場合、そのファイルのバイト単位でのサイズです。シンボリックリンクのサイズは、含まれるパス名の長さで、null バイトで終わることはありません。
@end deffn

タイムスタンプ:

@geindex st_atime (os.stat_result の属性)
@anchor{library/os os stat_result st_atime}@anchor{308a}
@deffn {の属性} st_atime

秒で表した最終アクセス時刻。
@end deffn

@geindex st_mtime (os.stat_result の属性)
@anchor{library/os os stat_result st_mtime}@anchor{2f14}
@deffn {の属性} st_mtime

秒で表した最終内容更新時刻。
@end deffn

@geindex st_ctime (os.stat_result の属性)
@anchor{library/os os stat_result st_ctime}@anchor{308b}
@deffn {の属性} st_ctime

Time of most recent metadata change expressed in seconds.


バージョン 3.12 で変更: @code{st_ctime} is deprecated on Windows. Use @code{st_birthtime} for
the file creation time. In the future, @code{st_ctime} will contain
the time of the most recent metadata change, as for other platforms.

@end deffn

@geindex st_atime_ns (os.stat_result の属性)
@anchor{library/os os stat_result st_atime_ns}@anchor{308c}
@deffn {の属性} st_atime_ns

ナノ秒 (整数) で表した最終アクセス時刻。


Added in version 3.3.

@end deffn

@geindex st_mtime_ns (os.stat_result の属性)
@anchor{library/os os stat_result st_mtime_ns}@anchor{308d}
@deffn {の属性} st_mtime_ns

ナノ秒 (整数) で表した最終内容更新時刻。


Added in version 3.3.

@end deffn

@geindex st_ctime_ns (os.stat_result の属性)
@anchor{library/os os stat_result st_ctime_ns}@anchor{308e}
@deffn {の属性} st_ctime_ns

Time of most recent metadata change expressed in nanoseconds as an
integer.


Added in version 3.3.



バージョン 3.12 で変更: @code{st_ctime_ns} is deprecated on Windows. Use @code{st_birthtime_ns}
for the file creation time. In the future, @code{st_ctime} will contain
the time of the most recent metadata change, as for other platforms.

@end deffn

@geindex st_birthtime (os.stat_result の属性)
@anchor{library/os os stat_result st_birthtime}@anchor{308f}
@deffn {の属性} st_birthtime

Time of file creation expressed in seconds. This attribute is not
always available, and may raise @ref{5f0,,AttributeError}.


バージョン 3.12 で変更: @code{st_birthtime} is now available on Windows.

@end deffn

@geindex st_birthtime_ns (os.stat_result の属性)
@anchor{library/os os stat_result st_birthtime_ns}@anchor{3090}
@deffn {の属性} st_birthtime_ns

Time of file creation expressed in nanoseconds as an integer.
This attribute is not always available, and may raise
@ref{5f0,,AttributeError}.


Added in version 3.12.

@end deffn

@cartouche
@quotation 注釈 
The exact meaning and resolution of the @ref{308a,,st_atime},
@ref{2f14,,st_mtime}, @ref{308b,,st_ctime} and @ref{308f,,st_birthtime} attributes
depend on the operating system and the file system. For example, on
Windows systems using the FAT32 file systems, @ref{2f14,,st_mtime} has
2-second resolution, and @ref{308a,,st_atime} has only 1-day resolution.
See your operating system documentation for details.

Similarly, although @ref{308c,,st_atime_ns}, @ref{308d,,st_mtime_ns},
@ref{308e,,st_ctime_ns} and @ref{3090,,st_birthtime_ns} are always expressed in
nanoseconds, many systems do not provide nanosecond precision.  On
systems that do provide nanosecond precision, the floating-point object
used to store @ref{308a,,st_atime}, @ref{2f14,,st_mtime}, @ref{308b,,st_ctime} and
@ref{308f,,st_birthtime} cannot preserve all of it, and as such will be
slightly inexact. If you need the exact timestamps you should always use
@ref{308c,,st_atime_ns}, @ref{308d,,st_mtime_ns}, @ref{308e,,st_ctime_ns} and
@ref{3090,,st_birthtime_ns}.
@end quotation
@end cartouche

(Linux のような ) 一部の Unix システムでは、以下の属性が利用できる場合があります :

@geindex st_blocks (os.stat_result の属性)
@anchor{library/os os stat_result st_blocks}@anchor{3091}
@deffn {の属性} st_blocks

ファイルに対して割り当てられている 512 バイトのブロックの数です。ファイルにホール (hole) が含まれている場合、@ref{3089,,st_size}/512 より小さくなる場合があります。
@end deffn

@geindex st_blksize (os.stat_result の属性)
@anchor{library/os os stat_result st_blksize}@anchor{3092}
@deffn {の属性} st_blksize

効率的なファイルシステム I/O のための「推奨される」ブロックサイズです。ファイルに、これより小さいチャンクで書き込むと、非効率的な読み込み、編集、再書き込みが起こる場合があります。
@end deffn

@geindex st_rdev (os.stat_result の属性)
@anchor{library/os os stat_result st_rdev}@anchor{17bf}
@deffn {の属性} st_rdev

inode デバイスの場合デバイスタイプ
@end deffn

@geindex st_flags (os.stat_result の属性)
@anchor{library/os os stat_result st_flags}@anchor{3093}
@deffn {の属性} st_flags

ファイルのユーザ定義フラグ
@end deffn

他の (FreeBSD のような ) Unix システムでは、以下の属性が利用できる場合があります ( ただし root ユーザ以外が使うと値が入っていない場合があります ):

@geindex st_gen (os.stat_result の属性)
@anchor{library/os os stat_result st_gen}@anchor{3094}
@deffn {の属性} st_gen

ファイル生成番号
@end deffn

On Solaris and derivatives, the following attributes may also be
available:

@geindex st_fstype (os.stat_result の属性)
@anchor{library/os os stat_result st_fstype}@anchor{d5b}
@deffn {の属性} st_fstype

String that uniquely identifies the type of the filesystem that
contains the file.
@end deffn

On macOS systems, the following attributes may also be available:

@geindex st_rsize (os.stat_result の属性)
@anchor{library/os os stat_result st_rsize}@anchor{3095}
@deffn {の属性} st_rsize

ファイルの実際のサイズ
@end deffn

@geindex st_creator (os.stat_result の属性)
@anchor{library/os os stat_result st_creator}@anchor{3096}
@deffn {の属性} st_creator

ファイルの作成者
@end deffn

@geindex st_type (os.stat_result の属性)
@anchor{library/os os stat_result st_type}@anchor{3097}
@deffn {の属性} st_type

ファイルタイプ
@end deffn

On Windows systems, the following attributes are also available:

@geindex st_file_attributes (os.stat_result の属性)
@anchor{library/os os stat_result st_file_attributes}@anchor{1038}
@deffn {の属性} st_file_attributes

Windows file attributes: @code{dwFileAttributes} member of the
@code{BY_HANDLE_FILE_INFORMATION} structure returned by
@code{GetFileInformationByHandle()}.
See the @code{FILE_ATTRIBUTE_* <stat.FILE_ATTRIBUTE_ARCHIVE>}
constants in the @ref{d6,,stat} module.


Added in version 3.5.

@end deffn

@geindex st_reparse_tag (os.stat_result の属性)
@anchor{library/os os stat_result st_reparse_tag}@anchor{c00}
@deffn {の属性} st_reparse_tag

When @ref{1038,,st_file_attributes} has the @ref{2ca9,,FILE_ATTRIBUTE_REPARSE_POINT}
set, this field contains the tag identifying the type of reparse point.
See the @ref{2cae,,IO_REPARSE_TAG_*}
constants in the @ref{d6,,stat} module.
@end deffn

The standard module @ref{d6,,stat} defines functions and constants that are
useful for extracting information from a @code{stat} structure. (On
Windows, some items are filled with dummy values.)

For backward compatibility, a @ref{16da,,stat_result} instance is also
accessible as a tuple of at least 10 integers giving the most important (and
portable) members of the @code{stat} structure, in the order
@ref{bff,,st_mode}, @ref{3084,,st_ino}, @ref{3085,,st_dev}, @ref{3086,,st_nlink},
@ref{3087,,st_uid}, @ref{3088,,st_gid}, @ref{3089,,st_size}, @ref{308a,,st_atime},
@ref{2f14,,st_mtime}, @ref{308b,,st_ctime}. More items may be added at the end by
some implementations. For compatibility with older Python versions,
accessing @ref{16da,,stat_result} as a tuple always returns integers.


バージョン 3.5 で変更: Windows now returns the file index as @ref{3084,,st_ino} when
available.



バージョン 3.7 で変更: Added the @ref{d5b,,st_fstype} member to Solaris/derivatives.



バージョン 3.8 で変更: Added the @ref{c00,,st_reparse_tag} member on Windows.



バージョン 3.8 で変更: On Windows, the @ref{bff,,st_mode} member now identifies special
files as @code{S_IFCHR}, @code{S_IFIFO} or @code{S_IFBLK}
as appropriate.



バージョン 3.12 で変更: On Windows, @ref{308b,,st_ctime} is deprecated. Eventually, it will
contain the last metadata change time, for consistency with other
platforms, but for now still contains creation time.
Use @ref{308f,,st_birthtime} for the creation time.

On Windows, @ref{3084,,st_ino} may now be up to 128 bits, depending
on the file system. Previously it would not be above 64 bits, and
larger file identifiers would be arbitrarily packed.

On Windows, @ref{17bf,,st_rdev} no longer returns a value. Previously
it would contain the same as @ref{3085,,st_dev}, which was incorrect.

Added the @ref{308f,,st_birthtime} member on Windows.

@end deffn

@geindex statvfs() (os モジュール)
@anchor{library/os os statvfs}@anchor{1314}
@deffn {の関数} os.statvfs (path)

Perform a @code{statvfs()} system call on the given path.  The return value is
an object whose attributes describe the filesystem on the given path, and
correspond to the members of the @code{statvfs} structure, namely:
@code{f_bsize}, @code{f_frsize}, @code{f_blocks}, @code{f_bfree},
@code{f_bavail}, @code{f_files}, @code{f_ffree}, @code{f_favail},
@code{f_flag}, @code{f_namemax}, @code{f_fsid}.

@code{f_flag} 属性のビットフラグ用に 2 つのモジュールレベル定数が定義されています: @code{ST_RDONLY} が設定されるとファイルシステムは読み出し専用でマウントされ、@code{ST_NOSUID} が設定されると setuid/setgid ビットの動作は無効になるか、サポートされません。

GNU/glibc ベースのシステム用に、追加のモジュールレベルの定数が次のように定義されています。 @code{ST_NODEV} (デバイス特殊ファイルへのアクセスを許可しない) 、  @code{ST_NOEXEC} (プログラムの実行を許可しない) 、 @code{ST_SYNCHRONOUS} (書き込みが一度に同期される) 、@code{ST_MANDLOCK} (ファイルシステムで強制的なロックを許可する) 、 @code{ST_WRITE} (ファイル/ディレクトリ/シンボリックリンクに書き込む) 、 @code{ST_APPEND} (追記のみのファイル) 、@code{ST_IMMUTABLE} (変更不能なファイル) 、 @code{ST_NOATIME} (アクセス時刻を更新しない) 、@code{ST_NODIRATIME} (ディレクトリアクセス時刻を更新しない) 、@code{ST_RELATIME} (mtime/ctimeに対して相対的に atime を更新する)。

この関数は @ref{d53,,ファイル記述子の指定} をサポートしています。

@ref{213f,,Availability}: Unix.


バージョン 3.2 で変更: 定数 @code{ST_RDONLY} および @code{ST_NOSUID} が追加されました。



バージョン 3.3 で変更: `path' へのオープン・ファイル記述子の指定をサポートしました。



バージョン 3.4 で変更: @code{ST_NODEV}, @code{ST_NOEXEC}, @code{ST_SYNCHRONOUS}, @code{ST_MANDLOCK}, @code{ST_WRITE}, @code{ST_APPEND}, @code{ST_IMMUTABLE}, @code{ST_NOATIME}, @code{ST_NODIRATIME}, @code{ST_RELATIME} 定数が追加されました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.7 で変更: Added the @code{f_fsid} attribute.

@end deffn

@geindex supports_dir_fd (os モジュール)
@anchor{library/os os supports_dir_fd}@anchor{130f}
@deffn {データ} os.supports_dir_fd

A @ref{184,,set} object indicating which functions in the @code{os}
module accept an open file descriptor for their `dir_fd' parameter.
Different platforms provide different features, and the underlying
functionality Python uses to implement the `dir_fd' parameter is not
available on all platforms Python supports.  For consistency's sake,
functions that may support `dir_fd' always allow specifying the
parameter, but will throw an exception if the functionality is used
when it's not locally available. (Specifying @code{None} for `dir_fd'
is always supported on all platforms.)

To check whether a particular function accepts an open file descriptor
for its `dir_fd' parameter, use the @code{in} operator on @code{supports_dir_fd}.
As an example, this expression evaluates to @code{True} if @ref{26d,,os.stat()}
accepts open file descriptors for `dir_fd' on the local platform:

@example
os.stat in os.supports_dir_fd
@end example

現在 `dir_fd' 引数は Unix プラットフォームでのみ動作します。Windows で動作する関数はありません。


Added in version 3.3.

@end deffn

@geindex supports_effective_ids (os モジュール)
@anchor{library/os os supports_effective_ids}@anchor{1316}
@deffn {データ} os.supports_effective_ids

A @ref{184,,set} object indicating whether @ref{1304,,os.access()} permits
specifying @code{True} for its `effective_ids' parameter on the local platform.
(Specifying @code{False} for `effective_ids' is always supported on all
platforms.)  If the local platform supports it, the collection will contain
@ref{1304,,os.access()}; otherwise it will be empty.

This expression evaluates to @code{True} if @ref{1304,,os.access()} supports
@code{effective_ids=True} on the local platform:

@example
os.access in os.supports_effective_ids
@end example

現在 `effective_ids' は Unix プラットフォームでのみサポートされています。Windows では動作しません。


Added in version 3.3.

@end deffn

@geindex supports_fd (os モジュール)
@anchor{library/os os supports_fd}@anchor{1315}
@deffn {データ} os.supports_fd

A @ref{184,,set} object indicating which functions in the
@code{os} module permit specifying their `path' parameter as an open file
descriptor on the local platform.  Different platforms provide different
features, and the underlying functionality Python uses to accept open file
descriptors as `path' arguments is not available on all platforms Python
supports.

To determine whether a particular function permits specifying an open file
descriptor for its `path' parameter, use the @code{in} operator on
@code{supports_fd}. As an example, this expression evaluates to @code{True} if
@ref{821,,os.chdir()} accepts open file descriptors for `path' on your local
platform:

@example
os.chdir in os.supports_fd
@end example


Added in version 3.3.

@end deffn

@geindex supports_follow_symlinks (os モジュール)
@anchor{library/os os supports_follow_symlinks}@anchor{1310}
@deffn {データ} os.supports_follow_symlinks

A @ref{184,,set} object indicating which functions in the @code{os} module
accept @code{False} for their `follow_symlinks' parameter on the local platform.
Different platforms provide different features, and the underlying
functionality Python uses to implement `follow_symlinks' is not available
on all platforms Python supports.  For consistency's sake, functions that
may support `follow_symlinks' always allow specifying the parameter, but
will throw an exception if the functionality is used when it's not locally
available.  (Specifying @code{True} for `follow_symlinks' is always supported
on all platforms.)

To check whether a particular function accepts @code{False} for its
`follow_symlinks' parameter, use the @code{in} operator on
@code{supports_follow_symlinks}.  As an example, this expression evaluates
to @code{True} if you may specify @code{follow_symlinks=False} when calling
@ref{26d,,os.stat()} on the local platform:

@example
os.stat in os.supports_follow_symlinks
@end example


Added in version 3.3.

@end deffn

@geindex symlink() (os モジュール)
@anchor{library/os os symlink}@anchor{130c}
@deffn {の関数} os.symlink (src, dst, target_is_directory=False, *, dir_fd=None)

`src' を指し示すシンボリックリンク `dst' を作成します。

The `src' parameter refers to the target of the link (the file or directory being linked to),
and `dst' is the name of the link being created.

Windows では、シンボリックリンクはファイルかディレクトリのどちらかを表しますが、ターゲットに合わせて動的に変化することはありません。ターゲットが存在する場合、シンボリックリンクの種類は対象に合わせて作成されます。ターゲットが存在せず `target_is_directory' に @code{True} が設定された場合、シンボリックリンクはディレクトリのリンクとして作成され、@code{False} に設定された場合 (デフォルト) はファイルのリンクになります。Windows 以外のプラットフォームでは `target_is_directory' は無視されます。

この関数は @ref{1302,,ディレクトリ記述子への相対パス} をサポートしています。

@cartouche
@quotation 注釈 
On newer versions of Windows 10, unprivileged accounts can create symlinks
if Developer Mode is enabled. When Developer Mode is not available/enabled,
the `SeCreateSymbolicLinkPrivilege' privilege is required, or the process
must be run as an administrator.

この関数が特権を持たないユーザーに呼び出されると、@ref{2c0,,OSError} が送出されます。
@end quotation
@end cartouche

引数 @code{src}, @code{dst}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.symlink} を送出します。

@ref{213f,,Availability}: Unix, Windows.

The function is limited on WASI, see @ref{1b6a,,WebAssembly プラットフォーム} for more
information.


バージョン 3.2 で変更: Windows 6.0 (Vista) のシンボリックリンクをサポートしました。



バージョン 3.3 で変更: Added the `dir_fd' parameter, and now allow `target_is_directory'
on non-Windows platforms.



バージョン 3.6 で変更: `src' と `dst' が @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.8 で変更: Added support for unelevated symlinks on Windows with Developer Mode.

@end deffn

@geindex sync() (os モジュール)
@anchor{library/os os sync}@anchor{132a}
@deffn {の関数} os.sync ()

ディスクキャッシュのディスクへの書き出しを強制します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex truncate() (os モジュール)
@anchor{library/os os truncate}@anchor{103c}
@deffn {の関数} os.truncate (path, length)

`path' に対応するファイルを、サイズが最大で `length' バイトになるよう切り詰めます。

この関数は @ref{d53,,ファイル記述子の指定} をサポートしています。

引数 @code{path}, @code{length} を指定して @ref{1c6e,,監査イベント} @code{os.truncate} を送出します。

@ref{213f,,Availability}: Unix, Windows.


Added in version 3.3.



バージョン 3.5 で変更: Windows サポートを追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex unlink() (os モジュール)
@anchor{library/os os unlink}@anchor{130d}
@deffn {の関数} os.unlink (path, *, dir_fd=None)

ファイル `path' を削除します。意味上は @ref{1308,,remove()} と等価です。@code{unlink} の名前は伝統的な Unix の関数名です。詳細は @ref{1308,,remove()} のドキュメントを参照してください。

引数 @code{path}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.remove} を送出します。


バージョン 3.3 で変更: 引数 `dir_fd' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex utime() (os モジュール)
@anchor{library/os os utime}@anchor{130e}
@deffn {の関数} os.utime (path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)

`path' で指定されたファイルに最終アクセス時刻および最終修正時刻を設定します。

@ref{130e,,utime()} は 2 つの任意引数 `times' と `ns' をとります。これらは `path' に設定する時刻を指定し、以下のように使用されます:


@itemize -

@item 
`ns' を指定する場合、ナノ秒を表す整数値をメンバーとして使用して、 @code{(atime_ns, mtime_ns)} の形式の 2 要素タプルを指定する必要があります。

@item 
`times' が @code{None} ではない場合、@code{(atime, mtime)} の形式で各メンバーは単位を秒で表す整数か浮動小数点値のタプルを指定しなければなりません。

@item 
`times' が @code{None} で、 `ns' が指定されていない場合、これは両方の時間を現在時刻として @code{ns=(atime_ns, mtime_ns)} を指定することと等価です。
@end itemize

`times' と `ns' の両方にタプルが指定されるとエラーになります。

ここで設定した時刻が、後に @ref{26d,,stat()} の呼び出し時正確に返されない場合があります。これはオペレーティングシステムが記録するアクセスおよび修正時刻の精度に依存しています; @ref{26d,,stat()} を参照してください。正確な時刻を保持する最善の方法は、@ref{130e,,utime()} で `ns' 引数を指定し、@ref{26d,,os.stat()} の返り値オブジェクトから `st_atime_ns' および `st_mtime_ns' フィールドを使用することです。

この関数は @ref{d53,,ファイル記述子の指定} 、 @ref{1302,,ディレクトリ記述子への相対パス} 、および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

引数 @code{path}, @code{times}, @code{ns}, @code{dir_fd} を指定して @ref{1c6e,,監査イベント} @code{os.utime} を送出します。


バージョン 3.3 で変更: `path' にオープンしているファイル記述子の指定のサポート、および引数 `dir_fd', `follow_symlinks', `ns' を追加しました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex walk() (os モジュール)
@anchor{library/os os walk}@anchor{6d0}
@deffn {の関数} os.walk (top, topdown=True, onerror=None, followlinks=False)

@geindex ディレクトリ;走査
@geindex ディレクトリ;トラバース

ディレクトリツリー以下のファイル名を、ツリーをトップダウンもしくはボトムアップに走査することで作成します。ディレクトリ `top' を根に持つディレクトリツリーに含まれる、各ディレクトリ (`top' 自身を含む ) ごとに、タプル @code{(dirpath, dirnames, filenames)} を yield します。

`dirpath' is a string, the path to the directory.  `dirnames' is a list of the
names of the subdirectories in `dirpath' (including symlinks to directories,
and excluding @code{'.'} and @code{'..'}).
`filenames' is a list of the names of the non-directory files in `dirpath'.
Note that the names in the lists contain no path components.  To get a full path
(which begins with `top') to a file or directory in `dirpath', do
@code{os.path.join(dirpath, name)}.  Whether or not the lists are sorted
depends on the file system.  If a file is removed from or added to the
`dirpath' directory during generating the lists, whether a name for that
file be included is unspecified.

オプション引数 `topdown' が @code{True} であるか、指定されなかった場合、各ディレクトリからタプルを生成した後で、サブディレクトリからタプルを生成します。( ディレクトリはトップダウンで生成 ) 。 `topdown' が @code{False} の場合、ディレクトリに対応するタプルは、そのディレクトリ以下の全てのサブディレクトリに対応するタプルの後で ( ボトムアップで ) 生成されます。 `topdown' の値によらず、サブディレクトリのリストは、ディレクトリとそのサブディレクトリのタプルを生成する前に取り出されます。

`topdown' が @code{True} のとき、呼び出し側は `dirnames' リストを、インプレースで ( たとえば、 @ref{1b1f,,del} やスライスを使った代入で ) 変更でき、 @ref{6d0,,walk()} は `dirnames' に残っているサブディレクトリ内のみを再帰します。これにより、検索を省略したり、特定の訪問順序を強制したり、呼び出し側が @ref{6d0,,walk()} を再開する前に、呼び出し側が作った、または名前を変更したディレクトリを、 @ref{6d0,,walk()} に知らせたりすることができます。 `topdown' が @code{False} のときに `dirnames' を変更しても効果はありません。ボトムアップモードでは `dirpath' 自身が生成される前に `dirnames' 内のディレクトリの情報が生成されるからです。

デフォルトでは、 @ref{c54,,scandir()} 呼び出しからのエラーは無視されます。オプション引数の `onerror' を指定する場合は関数でなければなりません ; この関数は単一の引数として @ref{2c0,,OSError} インスタンスを伴って呼び出されます。この関数でエラーを報告して走査を継続したり、例外を送出して走査を中止したりできます。ファイル名は例外オブジェクトの @code{filename} 属性として利用できます。

デフォルトでは、 @ref{6d0,,walk()} はディレクトリへのシンボリックリンクをたどりません。 `followlinks' に @code{True} を指定すると、ディレクトリへのシンボリックリンクをサポートしているシステムでは、シンボリックリンクの指しているディレクトリを走査します。

@cartouche
@quotation 注釈 
`followlinks' に @code{True} を指定すると、シンボリックリンクが親ディレクトリを指していた場合に、無限ループになることに注意してください。 @ref{6d0,,walk()} はすでにたどったディレクトリを管理したりはしません。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
相対パスを渡した場合、 @ref{6d0,,walk()} が再開されるまでの間に現在の作業ディレクトリを変更しないでください。 @ref{6d0,,walk()} はカレントディレクトリを変更しませんし、呼び出し側もカレントディレクトリを変更しないと仮定しています。
@end quotation
@end cartouche

This example displays the number of bytes taken by non-directory files in each
directory under the starting directory, except that it doesn't look under any
@code{__pycache__} subdirectory:

@example
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/xml'):
    print(root, "consumes", end=" ")
    print(sum(getsize(join(root, name)) for name in files), end=" ")
    print("bytes in", len(files), "non-directory files")
    if '__pycache__' in dirs:
        dirs.remove('__pycache__')  # don't visit __pycache__ directories
@end example

次の例 (@ref{356,,shutil.rmtree()} の単純な実装) では、ツリーをボトムアップで走査することが不可欠になります; @ref{130b,,rmdir()} はディレクトリが空になるまで削除を許さないからです:

@example
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))
os.rmdir(top)
@end example

引数 @code{top}, @code{topdown}, @code{onerror}, @code{followlinks} を指定して @ref{1c6e,,監査イベント} @code{os.walk} を送出します。


バージョン 3.5 で変更: この関数は、今では @ref{1312,,os.listdir()} ではなく @ref{c54,,os.scandir()} を呼び出します。これにより、 @ref{26d,,os.stat()} の呼び出し回数を削減でき、動作が高速化します。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex fwalk() (os モジュール)
@anchor{library/os os fwalk}@anchor{d52}
@deffn {の関数} os.fwalk (top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)

@geindex ディレクトリ;走査
@geindex ディレクトリ;トラバース

挙動は @ref{6d0,,walk()} と同じですが、@code{dir_fd} をサポートし、タプル @code{(dirpath, dirnames, filenames, dirfd)} を yield します。

`dirpath'、`dirnames'、および `filenames' は @ref{6d0,,walk()} の出力と同じで、`dirfd' は `dirpath' を参照するファイル記述子です。

この関数は常に @ref{1302,,ディレクトリ記述子への相対パス} および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。ただし、他の関数と異なり、@ref{d52,,fwalk()} での `follow_symlinks' のデフォルト値は @code{False} になることに注意してください。

@cartouche
@quotation 注釈 
@ref{d52,,fwalk()} はファイル記述子を yield するため、それらが有効なのは次のイテレートステップまでです。それ以後も保持したい場合は @ref{1dc2,,dup()} などを使って複製して使用してください。
@end quotation
@end cartouche

This example displays the number of bytes taken by non-directory files in each
directory under the starting directory, except that it doesn't look under any
@code{__pycache__} subdirectory:

@example
import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/xml'):
    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 '__pycache__' in dirs:
        dirs.remove('__pycache__')  # don't visit __pycache__ directories
@end example

次の例では、ツリーをボトムアップで走査することが不可欠になります ; @ref{130b,,rmdir()} はディレクトリが空になるまで削除を許さないからです

@example
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
    for name in files:
        os.unlink(name, dir_fd=rootfd)
    for name in dirs:
        os.rmdir(name, dir_fd=rootfd)
@end example

引数 @code{top}, @code{topdown}, @code{onerror}, @code{follow_symlinks} を指定して @ref{1c6e,,監査イベント} @code{os.fwalk} を送出します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.7 で変更: Added support for @ref{192,,bytes} paths.

@end deffn

@geindex memfd_create() (os モジュール)
@anchor{library/os os memfd_create}@anchor{bfe}
@deffn {の関数} os.memfd_create (name[, flags=os.MFD_CLOEXEC])

Create an anonymous file and return a file descriptor that refers to it.
`flags' must be one of the @code{os.MFD_*} constants available on the system
(or a bitwise ORed combination of them).  By default, the new file
descriptor is @ref{10fc,,non-inheritable}.

The name supplied in `name' is used as a filename and will be displayed as
the target of the corresponding symbolic link in the directory
@code{/proc/self/fd/}. The displayed name is always prefixed with @code{memfd:}
and serves only for debugging purposes. Names do not affect the behavior of
the file descriptor, and as such multiple files can have the same name
without any side effects.

@ref{213f,,Availability}: Linux >= 3.17 with glibc >= 2.27.


Added in version 3.8.

@end deffn

@geindex MFD_CLOEXEC (os モジュール)
@geindex MFD_ALLOW_SEALING (os モジュール)
@geindex MFD_HUGETLB (os モジュール)
@geindex MFD_HUGE_SHIFT (os モジュール)
@geindex MFD_HUGE_MASK (os モジュール)
@geindex MFD_HUGE_64KB (os モジュール)
@geindex MFD_HUGE_512KB (os モジュール)
@geindex MFD_HUGE_1MB (os モジュール)
@geindex MFD_HUGE_2MB (os モジュール)
@geindex MFD_HUGE_8MB (os モジュール)
@geindex MFD_HUGE_16MB (os モジュール)
@geindex MFD_HUGE_32MB (os モジュール)
@geindex MFD_HUGE_256MB (os モジュール)
@geindex MFD_HUGE_512MB (os モジュール)
@geindex MFD_HUGE_1GB (os モジュール)
@geindex MFD_HUGE_2GB (os モジュール)
@geindex MFD_HUGE_16GB (os モジュール)
@anchor{library/os os MFD_CLOEXEC}@anchor{3098}
@deffn {データ} os.MFD_CLOEXEC
@anchor{library/os os MFD_ALLOW_SEALING}@anchor{3099}
@deffnx {データ} os.MFD_ALLOW_SEALING
@anchor{library/os os MFD_HUGETLB}@anchor{309a}
@deffnx {データ} os.MFD_HUGETLB
@anchor{library/os os MFD_HUGE_SHIFT}@anchor{309b}
@deffnx {データ} os.MFD_HUGE_SHIFT
@anchor{library/os os MFD_HUGE_MASK}@anchor{309c}
@deffnx {データ} os.MFD_HUGE_MASK
@anchor{library/os os MFD_HUGE_64KB}@anchor{309d}
@deffnx {データ} os.MFD_HUGE_64KB
@anchor{library/os os MFD_HUGE_512KB}@anchor{309e}
@deffnx {データ} os.MFD_HUGE_512KB
@anchor{library/os os MFD_HUGE_1MB}@anchor{309f}
@deffnx {データ} os.MFD_HUGE_1MB
@anchor{library/os os MFD_HUGE_2MB}@anchor{30a0}
@deffnx {データ} os.MFD_HUGE_2MB
@anchor{library/os os MFD_HUGE_8MB}@anchor{30a1}
@deffnx {データ} os.MFD_HUGE_8MB
@anchor{library/os os MFD_HUGE_16MB}@anchor{30a2}
@deffnx {データ} os.MFD_HUGE_16MB
@anchor{library/os os MFD_HUGE_32MB}@anchor{30a3}
@deffnx {データ} os.MFD_HUGE_32MB
@anchor{library/os os MFD_HUGE_256MB}@anchor{30a4}
@deffnx {データ} os.MFD_HUGE_256MB
@anchor{library/os os MFD_HUGE_512MB}@anchor{30a5}
@deffnx {データ} os.MFD_HUGE_512MB
@anchor{library/os os MFD_HUGE_1GB}@anchor{30a6}
@deffnx {データ} os.MFD_HUGE_1GB
@anchor{library/os os MFD_HUGE_2GB}@anchor{30a7}
@deffnx {データ} os.MFD_HUGE_2GB
@anchor{library/os os MFD_HUGE_16GB}@anchor{30a8}
@deffnx {データ} os.MFD_HUGE_16GB

These flags can be passed to @ref{bfe,,memfd_create()}.

@ref{213f,,Availability}: Linux >= 3.17 with glibc >= 2.27

The @code{MFD_HUGE*} flags are only available since Linux 4.14.


Added in version 3.8.

@end deffn

@geindex eventfd() (os モジュール)
@anchor{library/os os eventfd}@anchor{a19}
@deffn {の関数} os.eventfd (initval[, flags=os.EFD_CLOEXEC])

Create and return an event file descriptor. The file descriptors supports
raw @ref{f95,,read()} and @ref{f9b,,write()} with a buffer size of 8,
@ref{fa0,,select()}, @ref{30a9,,poll()} and similar. See man page
@code{eventfd(2)@footnote{https://manpages.debian.org/eventfd(2)}} for more information.  By default, the
new file descriptor is @ref{10fc,,non-inheritable}.

`initval' is the initial value of the event counter. The initial value
must be a 32 bit unsigned integer. Please note that the initial value is
limited to a 32 bit unsigned int although the event counter is an unsigned
64 bit integer with a maximum value of 2@w{^64}-2.

`flags' can be constructed from @ref{1b58,,EFD_CLOEXEC},
@ref{1b59,,EFD_NONBLOCK}, and @ref{1b5a,,EFD_SEMAPHORE}.

If @ref{1b5a,,EFD_SEMAPHORE} is specified and the event counter is non-zero,
@ref{30aa,,eventfd_read()} returns 1 and decrements the counter by one.

If @ref{1b5a,,EFD_SEMAPHORE} is not specified and the event counter is
non-zero, @ref{30aa,,eventfd_read()} returns the current event counter value and
resets the counter to zero.

If the event counter is zero and @ref{1b59,,EFD_NONBLOCK} is not
specified, @ref{30aa,,eventfd_read()} blocks.

@ref{30ab,,eventfd_write()} increments the event counter. Write blocks if the
write operation would increment the counter to a value larger than
2@w{^64}-2.

以下はプログラム例です:

@example
import os

# semaphore with start value '1'
fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFD_CLOEXEC)
try:
    # acquire semaphore
    v = os.eventfd_read(fd)
    try:
        do_work()
    finally:
        # release semaphore
        os.eventfd_write(fd, v)
finally:
    os.close(fd)
@end example

@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.10.

@end deffn

@geindex eventfd_read() (os モジュール)
@anchor{library/os os eventfd_read}@anchor{30aa}
@deffn {の関数} os.eventfd_read (fd)

Read value from an @ref{a19,,eventfd()} file descriptor and return a 64 bit
unsigned int. The function does not verify that `fd' is an @ref{a19,,eventfd()}.

@ref{213f,,Availability}: Linux >= 2.6.27


Added in version 3.10.

@end deffn

@geindex eventfd_write() (os モジュール)
@anchor{library/os os eventfd_write}@anchor{30ab}
@deffn {の関数} os.eventfd_write (fd, value)

Add value to an @ref{a19,,eventfd()} file descriptor. `value' must be a 64 bit
unsigned int. The function does not verify that `fd' is an @ref{a19,,eventfd()}.

@ref{213f,,Availability}: Linux >= 2.6.27


Added in version 3.10.

@end deffn

@geindex EFD_CLOEXEC (os モジュール)
@anchor{library/os os EFD_CLOEXEC}@anchor{1b58}
@deffn {データ} os.EFD_CLOEXEC

Set close-on-exec flag for new @ref{a19,,eventfd()} file descriptor.

@ref{213f,,Availability}: Linux >= 2.6.27


Added in version 3.10.

@end deffn

@geindex EFD_NONBLOCK (os モジュール)
@anchor{library/os os EFD_NONBLOCK}@anchor{1b59}
@deffn {データ} os.EFD_NONBLOCK

Set @ref{103b,,O_NONBLOCK} status flag for new @ref{a19,,eventfd()} file
descriptor.

@ref{213f,,Availability}: Linux >= 2.6.27


Added in version 3.10.

@end deffn

@geindex EFD_SEMAPHORE (os モジュール)
@anchor{library/os os EFD_SEMAPHORE}@anchor{1b5a}
@deffn {データ} os.EFD_SEMAPHORE

Provide semaphore-like semantics for reads from an @ref{a19,,eventfd()} file
descriptor. On read the internal counter is decremented by one.

@ref{213f,,Availability}: Linux >= 2.6.30


Added in version 3.10.

@end deffn

@menu
* Timer File Descriptors:: 
* Linux 拡張属性:: 

@end menu

@node Timer File Descriptors,Linux 拡張属性,,ファイルとディレクトリ
@anchor{library/os os-timerfd}@anchor{47e}@anchor{library/os timer-file-descriptors}@anchor{30ac}
@subsubsection Timer File Descriptors



Added in version 3.13.


These functions provide support for Linux's `timer file descriptor' API.
Naturally, they are all only available on Linux.

@geindex timerfd_create() (os モジュール)
@anchor{library/os os timerfd_create}@anchor{51f}
@deffn {の関数} os.timerfd_create (clockid, /, *, flags=0)

Create and return a timer file descriptor (`timerfd').

The file descriptor returned by @ref{51f,,timerfd_create()} supports:


@itemize -

@item 
@ref{f95,,read()}

@item 
@ref{fa0,,select()}

@item 
@ref{30a9,,poll()}
@end itemize

The file descriptor's @ref{f95,,read()} method can be called with a buffer size
of 8. If the timer has already expired one or more times, @ref{f95,,read()}
returns the number of expirations with the host's endianness, which may be
converted to an @ref{19b,,int} by @code{int.from_bytes(x, byteorder=sys.byteorder)}.

@ref{fa0,,select()} and @ref{30a9,,poll()} can be used to wait until
timer expires and the file descriptor is readable.

`clockid' must be a valid @ref{30ad,,clock ID},
as defined in the @ref{f4,,time} module:


@itemize -

@item 
@ref{8a9,,time.CLOCK_REALTIME}

@item 
@ref{8a8,,time.CLOCK_MONOTONIC}

@item 
@ref{d87,,time.CLOCK_BOOTTIME} (Since Linux 3.15 for timerfd_create)
@end itemize

If `clockid' is @ref{8a9,,time.CLOCK_REALTIME}, a settable system-wide
real-time clock is used. If system clock is changed, timer setting need
to be updated. To cancel timer when system clock is changed, see
@ref{527,,TFD_TIMER_CANCEL_ON_SET}.

If `clockid' is @ref{8a8,,time.CLOCK_MONOTONIC}, a non-settable monotonically
increasing clock is used. Even if the system clock is changed, the timer
setting will not be affected.

If `clockid' is @ref{d87,,time.CLOCK_BOOTTIME}, same as @ref{8a8,,time.CLOCK_MONOTONIC}
except it includes any time that the system is suspended.

The file descriptor's behaviour can be modified by specifying a `flags' value.
Any of the following variables may be used, combined using bitwise OR
(the @code{|} operator):


@itemize -

@item 
@ref{524,,TFD_NONBLOCK}

@item 
@ref{525,,TFD_CLOEXEC}
@end itemize

If @ref{524,,TFD_NONBLOCK} is not set as a flag, @ref{f95,,read()} blocks until
the timer expires. If it is set as a flag, @ref{f95,,read()} doesn't block, but
If there hasn't been an expiration since the last call to read,
@ref{f95,,read()} raises @ref{2c0,,OSError} with @code{errno} is set to
@ref{26fd,,errno.EAGAIN}.

@ref{525,,TFD_CLOEXEC} is always set by Python automatically.

The file descriptor must be closed with @ref{d6b,,os.close()} when it is no
longer needed, or else the file descriptor will be leaked.


@subsubheading 参考


The @code{timerfd_create(2)@footnote{https://manpages.debian.org/timerfd_create(2)}} man page.


@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex timerfd_settime() (os モジュール)
@anchor{library/os os timerfd_settime}@anchor{520}
@deffn {の関数} os.timerfd_settime (fd, /, *, flags=flags, initial=0.0, interval=0.0)

Alter a timer file descriptor's internal timer.
This function operates the same interval timer as @ref{521,,timerfd_settime_ns()}.

`fd' must be a valid timer file descriptor.

The timer's behaviour can be modified by specifying a `flags' value.
Any of the following variables may be used, combined using bitwise OR
(the @code{|} operator):


@itemize -

@item 
@ref{526,,TFD_TIMER_ABSTIME}

@item 
@ref{527,,TFD_TIMER_CANCEL_ON_SET}
@end itemize

The timer is disabled by setting `initial' to zero (@code{0}).
If `initial' is equal to or greater than zero, the timer is enabled.
If `initial' is less than zero, it raises an @ref{2c0,,OSError} exception
with @code{errno} set to @ref{1dd2,,errno.EINVAL}

By default the timer will fire when `initial' seconds have elapsed.
(If `initial' is zero, timer will fire immediately.)

However, if the @ref{526,,TFD_TIMER_ABSTIME} flag is set,
the timer will fire when the timer's clock
(set by `clockid' in @ref{51f,,timerfd_create()}) reaches `initial' seconds.

The timer's interval is set by the `interval' @ref{196,,float}.
If `interval' is zero, the timer only fires once, on the initial expiration.
If `interval' is greater than zero, the timer fires every time `interval'
seconds have elapsed since the previous expiration.
If `interval' is less than zero, it raises @ref{2c0,,OSError} with @code{errno}
set to @ref{1dd2,,errno.EINVAL}

If the @ref{527,,TFD_TIMER_CANCEL_ON_SET} flag is set along with
@ref{526,,TFD_TIMER_ABSTIME} and the clock for this timer is
@ref{8a9,,time.CLOCK_REALTIME}, the timer is marked as cancelable if the
real-time clock is changed discontinuously. Reading the descriptor is
aborted with the error ECANCELED.

Linux manages system clock as UTC. A daylight-savings time transition is
done by changing time offset only and doesn't cause discontinuous system
clock change.

Discontinuous system clock change will be caused by the following events:


@itemize -

@item 
@code{settimeofday}

@item 
@code{clock_settime}

@item 
set the system date and time by @code{date} command
@end itemize

Return a two-item tuple of (@code{next_expiration}, @code{interval}) from
the previous timer state, before this function executed.


@subsubheading 参考


@code{timerfd_create(2)@footnote{https://manpages.debian.org/timerfd_create(2)}}, @code{timerfd_settime(2)@footnote{https://manpages.debian.org/timerfd_settime(2)}},
@code{settimeofday(2)@footnote{https://manpages.debian.org/settimeofday(2)}}, @code{clock_settime(2)@footnote{https://manpages.debian.org/clock_settime(2)}},
and @code{date(1)@footnote{https://manpages.debian.org/date(1)}}.


@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex timerfd_settime_ns() (os モジュール)
@anchor{library/os os timerfd_settime_ns}@anchor{521}
@deffn {の関数} os.timerfd_settime_ns (fd, /, *, flags=0, initial=0, interval=0)

Similar to @ref{520,,timerfd_settime()}, but use time as nanoseconds.
This function operates the same interval timer as @ref{520,,timerfd_settime()}.

@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex timerfd_gettime() (os モジュール)
@anchor{library/os os timerfd_gettime}@anchor{522}
@deffn {の関数} os.timerfd_gettime (fd, /)

Return a two-item tuple of floats (@code{next_expiration}, @code{interval}).

@code{next_expiration} denotes the relative time until the timer next fires,
regardless of if the @ref{526,,TFD_TIMER_ABSTIME} flag is set.

@code{interval} denotes the timer's interval.
If zero, the timer will only fire once, after @code{next_expiration} seconds
have elapsed.


@subsubheading 参考


@code{timerfd_gettime(2)@footnote{https://manpages.debian.org/timerfd_gettime(2)}}


@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex timerfd_gettime_ns() (os モジュール)
@anchor{library/os os timerfd_gettime_ns}@anchor{523}
@deffn {の関数} os.timerfd_gettime_ns (fd, /)

Similar to @ref{522,,timerfd_gettime()}, but return time as nanoseconds.

@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex TFD_NONBLOCK (os モジュール)
@anchor{library/os os TFD_NONBLOCK}@anchor{524}
@deffn {データ} os.TFD_NONBLOCK

A flag for the @ref{51f,,timerfd_create()} function,
which sets the @ref{103b,,O_NONBLOCK} status flag for the new timer file
descriptor. If @ref{524,,TFD_NONBLOCK} is not set as a flag, @ref{f95,,read()} blocks.

@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex TFD_CLOEXEC (os モジュール)
@anchor{library/os os TFD_CLOEXEC}@anchor{525}
@deffn {データ} os.TFD_CLOEXEC

A flag for the @ref{51f,,timerfd_create()} function,
If @ref{525,,TFD_CLOEXEC} is set as a flag, set close-on-exec flag for new file
descriptor.

@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex TFD_TIMER_ABSTIME (os モジュール)
@anchor{library/os os TFD_TIMER_ABSTIME}@anchor{526}
@deffn {データ} os.TFD_TIMER_ABSTIME

A flag for the @ref{520,,timerfd_settime()} and @ref{521,,timerfd_settime_ns()} functions.
If this flag is set, `initial' is interpreted as an absolute value on the
timer's clock (in UTC seconds or nanoseconds since the Unix Epoch).

@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@geindex TFD_TIMER_CANCEL_ON_SET (os モジュール)
@anchor{library/os os TFD_TIMER_CANCEL_ON_SET}@anchor{527}
@deffn {データ} os.TFD_TIMER_CANCEL_ON_SET

A flag for the @ref{520,,timerfd_settime()} and @ref{521,,timerfd_settime_ns()}
functions along with @ref{526,,TFD_TIMER_ABSTIME}.
The timer is cancelled when the time of the underlying clock changes
discontinuously.

@ref{213f,,Availability}: Linux >= 2.6.27 with glibc >= 2.8


Added in version 3.13.

@end deffn

@node Linux 拡張属性,,Timer File Descriptors,ファイルとディレクトリ
@anchor{library/os linux-extended-attributes}@anchor{30ae}
@subsubsection Linux 拡張属性



Added in version 3.3.


以下の関数はすべて Linux でのみ使用可能です。

@geindex getxattr() (os モジュール)
@anchor{library/os os getxattr}@anchor{131c}
@deffn {の関数} os.getxattr (path, attribute, *, follow_symlinks=True)

Return the value of the extended filesystem attribute `attribute' for
`path'. `attribute' can be bytes or str (directly or indirectly through the
@ref{e4b,,PathLike} interface). If it is str, it is encoded with the filesystem
encoding.

この関数は @ref{d53,,ファイル記述子の指定} および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

引数 @code{path}, @code{attribute} を指定して @ref{1c6e,,監査イベント} @code{os.getxattr} を送出します。


バージョン 3.6 で変更: `path' と `attribute' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex listxattr() (os モジュール)
@anchor{library/os os listxattr}@anchor{131d}
@deffn {の関数} os.listxattr (path=None, *, follow_symlinks=True)

`path' の拡張ファイルシステム属性のリストを返します。リスト内の属性はファイルシステムのエンコーディングでデコードされた文字列で表されます。`path' が @code{None} の場合、@ref{131d,,listxattr()} はカレントディレクトリを調べます。

この関数は @ref{d53,,ファイル記述子の指定} および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

引数 @code{path} を指定して @ref{1c6e,,監査イベント} @code{os.listxattr} を送出します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex removexattr() (os モジュール)
@anchor{library/os os removexattr}@anchor{131e}
@deffn {の関数} os.removexattr (path, attribute, *, follow_symlinks=True)

Removes the extended filesystem attribute `attribute' from `path'.
`attribute' should be bytes or str (directly or indirectly through the
@ref{e4b,,PathLike} interface). If it is a string, it is encoded
with the @ref{75d,,filesystem encoding and error handler}.

この関数は @ref{d53,,ファイル記述子の指定} および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

引数 @code{path}, @code{attribute} を指定して @ref{1c6e,,監査イベント} @code{os.removexattr} を送出します。


バージョン 3.6 で変更: `path' と `attribute' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex setxattr() (os モジュール)
@anchor{library/os os setxattr}@anchor{131f}
@deffn {の関数} os.setxattr (path, attribute, value, flags=0, *, follow_symlinks=True)

Set the extended filesystem attribute `attribute' on `path' to `value'.
`attribute' must be a bytes or str with no embedded NULs (directly or
indirectly through the @ref{e4b,,PathLike} interface). If it is a str,
it is encoded with the @ref{75d,,filesystem encoding and error handler}.  `flags' may be
@ref{30af,,XATTR_REPLACE} or @ref{30b0,,XATTR_CREATE}. If @ref{30af,,XATTR_REPLACE} is
given and the attribute does not exist, @code{ENODATA} will be raised.
If @ref{30b0,,XATTR_CREATE} is given and the attribute already exists, the
attribute will not be created and @code{EEXISTS} will be raised.

この関数は @ref{d53,,ファイル記述子の指定} および @ref{1303,,シンボリックリンクをたどらない} をサポートしています。

@cartouche
@quotation 注釈 
Linux カーネル 2.6.39 以前では、バグのため一部のファイルシステムで引数 flags が無視されます。
@end quotation
@end cartouche

引数 @code{path}, @code{attribute}, @code{value}, @code{flags} を指定して @ref{1c6e,,監査イベント} @code{os.setxattr} を送出します。


バージョン 3.6 で変更: `path' と `attribute' が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex XATTR_SIZE_MAX (os モジュール)
@anchor{library/os os XATTR_SIZE_MAX}@anchor{30b1}
@deffn {データ} os.XATTR_SIZE_MAX

拡張属性の値にできる最大サイズです。現在、Linux では 64 キロバイトです。
@end deffn

@geindex XATTR_CREATE (os モジュール)
@anchor{library/os os XATTR_CREATE}@anchor{30b0}
@deffn {データ} os.XATTR_CREATE

@ref{131f,,setxattr()} の引数 flags に指定できる値です。その操作で属性を作成しなければならないことを意味します。
@end deffn

@geindex XATTR_REPLACE (os モジュール)
@anchor{library/os os XATTR_REPLACE}@anchor{30af}
@deffn {データ} os.XATTR_REPLACE

@ref{131f,,setxattr()} の引数 flags に指定できる値です。その操作で既存の属性を置き換えなければならないことを意味します。
@end deffn

@node プロセス管理,スケジューラーへのインターフェイス,ファイルとディレクトリ,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os os-process}@anchor{30b2}@anchor{library/os process-management}@anchor{30b3}
@subsubsection プロセス管理


以下の関数はプロセスの生成や管理に利用できます。

さまざまな @ref{30b4,,exec*} 関数は、プロセス内にロードされる新しいプログラムに与えるための、引数のリストを取ります。どの関数の場合でも、新しいプログラムに渡されるリストの最初の引数は、ユーザがコマンドラインで入力する引数ではなく、そのプログラム自体の名前です。 C プログラマならば、プログラムの @code{main()} に渡される @code{argv[0]} だと考えれば良いでしょう。たとえば、 @code{os.execv('/bin/echo', ['foo', 'bar'])} が標準出力に出力するのは @code{bar} だけで、 @code{foo} は無視されたかのように見えることになります。

@geindex abort() (os モジュール)
@anchor{library/os os abort}@anchor{30b5}
@deffn {の関数} os.abort ()

@code{SIGABRT} シグナルを現在のプロセスに対して生成します。 Unix では、デフォルトの動作はコアダンプの生成です ; Windows では、プロセスは即座に終了コード @code{3} を返します。この関数の呼び出しは @ref{134c,,signal.signal()} を使って @code{SIGABRT} に対し登録された Python シグナルハンドラーを呼び出さないことに注意してください。
@end deffn

@geindex add_dll_directory() (os モジュール)
@anchor{library/os os add_dll_directory}@anchor{bdd}
@deffn {の関数} os.add_dll_directory (path)

Add a path to the DLL search path.

This search path is used when resolving dependencies for imported
extension modules (the module itself is resolved through
@ref{3e4,,sys.path}), and also by @ref{2e,,ctypes}.

Remove the directory by calling `close()' on the returned object
or using it in a @ref{186,,with} statement.

See the Microsoft documentation@footnote{https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5}
for more information about how DLLs are loaded.

引数 @code{path} を指定して @ref{1c6e,,監査イベント} @code{os.add_dll_directory} を送出します。

@ref{213f,,Availability}: Windows.


Added in version 3.8: Previous versions of CPython would resolve DLLs using the default
behavior for the current process. This led to inconsistencies,
such as only sometimes searching 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} or the current
working directory, and OS functions such as @code{AddDllDirectory}
having no effect.

In 3.8, the two primary ways DLLs are loaded now explicitly
override the process-wide behavior to ensure consistency. See the
@ref{c95,,porting notes} for information on
updating libraries.

@end deffn

@geindex execl() (os モジュール)
@geindex execle() (os モジュール)
@geindex execlp() (os モジュール)
@geindex execlpe() (os モジュール)
@geindex execv() (os モジュール)
@geindex execve() (os モジュール)
@geindex execvp() (os モジュール)
@geindex execvpe() (os モジュール)
@anchor{library/os os execl}@anchor{30b4}
@deffn {の関数} os.execl (path, arg0, arg1, ...)
@anchor{library/os os execle}@anchor{30b6}
@deffnx {の関数} os.execle (path, arg0, arg1, ..., env)
@anchor{library/os os execlp}@anchor{30b7}
@deffnx {の関数} os.execlp (file, arg0, arg1, ...)
@anchor{library/os os execlpe}@anchor{30b8}
@deffnx {の関数} os.execlpe (file, arg0, arg1, ..., env)
@anchor{library/os os execv}@anchor{3019}
@deffnx {の関数} os.execv (path, args)
@anchor{library/os os execve}@anchor{1311}
@deffnx {の関数} os.execve (path, args, env)
@anchor{library/os os execvp}@anchor{30b9}
@deffnx {の関数} os.execvp (file, args)
@anchor{library/os os execvpe}@anchor{30ba}
@deffnx {の関数} os.execvpe (file, args, env)

これらの関数はすべて、現在のプロセスを置き換える形で新たなプログラムを実行します ; 現在のプロセスは返り値を返しません。 Unix では、新たに実行される実行コードは現在のプロセス内に読み込まれ、呼び出し側と同じプロセス ID を持つことになります。エラーは @ref{2c0,,OSError} 例外として報告されます。

現在のプロセスは瞬時に置き換えられます。開かれているファイルオブジェクトやファイル記述子はフラッシュされません。そのため、バッファ内にデータが残っているかもしれない場合、 @ref{30b4,,exec*} 関数を実行する前に @code{sys.stdout.flush()} か @ref{f8e,,os.fsync()} を利用してバッファをフラッシュしておく必要があります。

The "l" and "v" variants of the @ref{30b4,,exec*} functions differ in how
command-line arguments are passed.  The "l" variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the @code{execl*()}
functions.  The "v" variants are good when the number of parameters is
variable, with the arguments being passed in a list or tuple as the `args'
parameter.  In either case, the arguments to the child process should start with
the name of the command being run, but this is not enforced.

The variants which include a "p" near the end (@ref{30b7,,execlp()},
@ref{30b8,,execlpe()}, @ref{30b9,,execvp()}, and @ref{30ba,,execvpe()}) will use the
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable to locate the program `file'.  When the
environment is being replaced (using one of the @ref{30b4,,exec*e} variants,
discussed in the next paragraph), the new environment is used as the source of
the 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} variable. The other variants, @ref{30b4,,execl()}, @ref{30b6,,execle()},
@ref{3019,,execv()}, and @ref{1311,,execve()}, will not use the 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} variable to
locate the executable; `path' must contain an appropriate absolute or relative
path. Relative paths must include at least one slash, even on Windows, as
plain names will not be resolved.

@ref{30b6,,execle()} 、 @ref{30b8,,execlpe()} 、 @ref{1311,,execve()} 、および @ref{30ba,,execvpe()} (すべて末尾に "e" がついています) では、 `env' 引数は新たなプロセスで利用される環境変数を定義するためのマップ型でなくてはなりません ( 現在のプロセスの環境変数の代わりに利用されます ); @ref{30b4,,execl()} 、 @ref{30b7,,execlp()} 、 @ref{3019,,execv()} 、および @ref{30b9,,execvp()} では、すべて新たなプロセスは現在のプロセスの環境を引き継ぎます。

一部のプラットフォームの @ref{1311,,execve()} では、`path' はオープンしているファイル記述子で指定することもできます。この機能をサポートしていないプラットフォームもあります; @ref{1315,,os.supports_fd} を使うことで利用可能かどうか調べることができます。利用できない場合、@ref{36b,,NotImplementedError} が送出されます。

引数 @code{path}, @code{args}, @code{env} を指定して @ref{1c6e,,監査イベント} @code{os.exec} を送出します。

@ref{213f,,Availability}: Unix, Windows, not WASI, not Android, not iOS.


バージョン 3.3 で変更: Added support for specifying `path' as an open file descriptor
for @ref{1311,,execve()}.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex _exit() (os モジュール)
@anchor{library/os os _exit}@anchor{26f9}
@deffn {の関数} os._exit (n)

終了ステータス `n' でプロセスを終了します。この時クリーンアップハンドラーの呼び出しや、標準入出力バッファのフラッシュなどは行いません。

@cartouche
@quotation 注釈 
The standard way to exit is @ref{277,,sys.exit(n)}.  @code{_exit()} should
normally only be used in the child process after a @ref{4b5,,fork()}.
@end quotation
@end cartouche
@end deffn

以下の終了コードは必須ではありませんが @ref{26f9,,_exit()} で使うことができます。一般に、メールサーバーの外部コマンド配送プログラムのような、 Python で書かれたシステムプログラムに使います。

@cartouche
@quotation 注釈 
いくつかのバリエーションがあって、これらのすべてがすべての Unix プラットフォームで使えるわけではありません。以下の定数は下層のプラットフォームで定義されていれば定義されます。
@end quotation
@end cartouche

@geindex EX_OK (os モジュール)
@anchor{library/os os EX_OK}@anchor{30bb}
@deffn {データ} os.EX_OK

Exit code that means no error occurred. May be taken from the defined value of
@code{EXIT_SUCCESS} on some platforms. Generally has a value of zero.

@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex EX_USAGE (os モジュール)
@anchor{library/os os EX_USAGE}@anchor{30bc}
@deffn {データ} os.EX_USAGE

誤った個数の引数が渡された時など、コマンドが間違って使われたことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_DATAERR (os モジュール)
@anchor{library/os os EX_DATAERR}@anchor{30bd}
@deffn {データ} os.EX_DATAERR

入力データが誤っていたことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_NOINPUT (os モジュール)
@anchor{library/os os EX_NOINPUT}@anchor{30be}
@deffn {データ} os.EX_NOINPUT

入力ファイルが存在しなかった、または、読み込み不可だったことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_NOUSER (os モジュール)
@anchor{library/os os EX_NOUSER}@anchor{30bf}
@deffn {データ} os.EX_NOUSER

指定されたユーザーが存在しなかったことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_NOHOST (os モジュール)
@anchor{library/os os EX_NOHOST}@anchor{30c0}
@deffn {データ} os.EX_NOHOST

指定されたホストが存在しなかったことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_UNAVAILABLE (os モジュール)
@anchor{library/os os EX_UNAVAILABLE}@anchor{30c1}
@deffn {データ} os.EX_UNAVAILABLE

要求されたサービスが利用できないことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_SOFTWARE (os モジュール)
@anchor{library/os os EX_SOFTWARE}@anchor{30c2}
@deffn {データ} os.EX_SOFTWARE

内部ソフトウェアエラーが検出されたことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_OSERR (os モジュール)
@anchor{library/os os EX_OSERR}@anchor{30c3}
@deffn {データ} os.EX_OSERR

fork できない、 pipe の作成ができないなど、オペレーティングシステムのエラーが検出されたことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_OSFILE (os モジュール)
@anchor{library/os os EX_OSFILE}@anchor{30c4}
@deffn {データ} os.EX_OSFILE

システムファイルが存在しなかった、開けなかった、あるいはその他のエラーが起きたことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_CANTCREAT (os モジュール)
@anchor{library/os os EX_CANTCREAT}@anchor{30c5}
@deffn {データ} os.EX_CANTCREAT

ユーザーには作成できない出力ファイルを指定したことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_IOERR (os モジュール)
@anchor{library/os os EX_IOERR}@anchor{30c6}
@deffn {データ} os.EX_IOERR

ファイルの I/O を行っている途中にエラーが発生した時の終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_TEMPFAIL (os モジュール)
@anchor{library/os os EX_TEMPFAIL}@anchor{30c7}
@deffn {データ} os.EX_TEMPFAIL

一時的な失敗が発生したことを表す終了コード。これは、再試行可能な操作の途中に、ネットワークに接続できないというような、実際にはエラーではないかも知れないことを意味します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_PROTOCOL (os モジュール)
@anchor{library/os os EX_PROTOCOL}@anchor{30c8}
@deffn {データ} os.EX_PROTOCOL

プロトコル交換が不正、不適切、または理解不能なことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_NOPERM (os モジュール)
@anchor{library/os os EX_NOPERM}@anchor{30c9}
@deffn {データ} os.EX_NOPERM

操作を行うために十分な許可がなかった（ファイルシステムの問題を除く）ことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_CONFIG (os モジュール)
@anchor{library/os os EX_CONFIG}@anchor{30ca}
@deffn {データ} os.EX_CONFIG

設定エラーが起こったことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex EX_NOTFOUND (os モジュール)
@anchor{library/os os EX_NOTFOUND}@anchor{30cb}
@deffn {データ} os.EX_NOTFOUND

"an entry was not found" のようなことを表す終了コード。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex fork() (os モジュール)
@anchor{library/os os fork}@anchor{4b5}
@deffn {の関数} os.fork ()

子プロセスを fork します。子プロセスでは @code{0} が返り、親プロセスでは子プロセスの id が返ります。エラーが発生した場合は、 @ref{2c0,,OSError} を送出します。

FreeBSD 6.3 以下、Cygwinを含む一部のプラットフォームにおいて、 @code{fork()} をスレッド内から利用した場合に既知の問題があることに注意してください。

引数無しで @ref{1c6e,,監査イベント} @code{os.fork} を送出します。

@cartouche
@quotation 警告 
If you use TLS sockets in an application calling @code{fork()}, see
the warning in the @ref{d5,,ssl} documentation.
@end quotation
@end cartouche

@cartouche
@quotation 警告 
On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using @ref{111,,urllib.request}.
@end quotation
@end cartouche


バージョン 3.8 で変更: Calling @code{fork()} in a subinterpreter is no longer supported
(@ref{244,,RuntimeError} is raised).



バージョン 3.12 で変更: If Python is able to detect that your process has multiple
threads, @ref{4b5,,os.fork()} now raises a @ref{1a3,,DeprecationWarning}.

We chose to surface this as a warning, when detectable, to better
inform developers of a design problem that the POSIX platform
specifically notes as not supported. Even in code that
`appears' to work, it has never been safe to mix threading with
@ref{4b5,,os.fork()} on POSIX platforms. The CPython runtime itself has
always made API calls that are not safe for use in the child
process when threads existed in the parent (such as @code{malloc} and
@code{free}).

Users of macOS or users of libc or malloc implementations other
than those typically found in glibc to date are among those
already more likely to experience deadlocks running such code.

See this discussion on fork being incompatible with threads@footnote{https://discuss.python.org/t/33555}
for technical details of why we're surfacing this longstanding
platform compatibility problem to developers.


@ref{213f,,Availability}: POSIX, not WASI, not Android, not iOS.
@end deffn

@geindex forkpty() (os モジュール)
@anchor{library/os os forkpty}@anchor{4b6}
@deffn {の関数} os.forkpty ()

子プロセスを fork します。この時新しい擬似端末を子プロセスの制御端末として使います。親プロセスでは @code{(pid, fd)} からなるペアが返り、 `fd' は擬似端末のマスター側のファイル記述子となります。可搬性のあるアプローチを取るには、 @ref{b6,,pty} モジュールを利用してください。エラーが発生した場合は、 @ref{2c0,,OSError} を送出します。

引数無しで @ref{1c6e,,監査イベント} @code{os.forkpty} を送出します。

@cartouche
@quotation 警告 
On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using @ref{111,,urllib.request}.
@end quotation
@end cartouche


バージョン 3.8 で変更: Calling @code{forkpty()} in a subinterpreter is no longer supported
(@ref{244,,RuntimeError} is raised).



バージョン 3.12 で変更: If Python is able to detect that your process has multiple
threads, this now raises a @ref{1a3,,DeprecationWarning}. See the
longer explanation on @ref{4b5,,os.fork()}.


@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex kill() (os モジュール)
@anchor{library/os os kill}@anchor{157f}
@deffn {の関数} os.kill (pid, sig, /)

@geindex process;kill
@geindex process;シグナル

プロセス `pid' にシグナル `sig' を送ります。ホストプラットフォームで利用可能なシグナルを特定する定数は @ref{cb,,signal} モジュールで定義されています。

Windows: The @ref{1580,,signal.CTRL_C_EVENT} and
@ref{1581,,signal.CTRL_BREAK_EVENT} signals are special signals which can
only be sent to console processes which share a common console window,
e.g., some subprocesses. Any other value for `sig' will cause the process
to be unconditionally killed by the TerminateProcess API, and the exit code
will be set to `sig'.

@ref{1349,,signal.pthread_kill()} も参照してください。

引数 @code{pid}, @code{sig} を指定して @ref{1c6e,,監査イベント} @code{os.kill} を送出します。

@ref{213f,,Availability}: Unix, Windows, not WASI, not iOS.


バージョン 3.2 で変更: Windows サポートを追加しました。

@end deffn

@geindex killpg() (os モジュール)
@anchor{library/os os killpg}@anchor{1dbb}
@deffn {の関数} os.killpg (pgid, sig, /)

@geindex process;kill
@geindex process;シグナル

プロセスグループ `pgid' にシグナル `sig' を送ります。

引数 @code{pgid}, @code{sig} を指定して @ref{1c6e,,監査イベント} @code{os.killpg} を送出します。

@ref{213f,,Availability}: Unix, not WASI, not iOS.
@end deffn

@geindex nice() (os モジュール)
@anchor{library/os os nice}@anchor{1319}
@deffn {の関数} os.nice (increment, /)

プロセスの "nice 値 " に `increment' を加えます。新たな nice 値を返します。

@ref{213f,,Availability}: Unix, not WASI.
@end deffn

@geindex pidfd_open() (os モジュール)
@anchor{library/os os pidfd_open}@anchor{6a4}
@deffn {の関数} os.pidfd_open (pid, flags=0)

Return a file descriptor referring to the process `pid' with `flags' set.
This descriptor can be used to perform process management without races
and signals.

See the @code{pidfd_open(2)@footnote{https://manpages.debian.org/pidfd_open(2)}} man page for more details.

@ref{213f,,Availability}: Linux >= 5.3, Android >= @ref{d83,,build-time} API level 31


Added in version 3.9.


@geindex PIDFD_NONBLOCK (os モジュール)
@anchor{library/os os PIDFD_NONBLOCK}@anchor{6c2}
@deffn {データ} os.PIDFD_NONBLOCK

This flag indicates that the file descriptor will be non-blocking.
If the process referred to by the file descriptor has not yet terminated,
then an attempt to wait on the file descriptor using @code{waitid(2)@footnote{https://manpages.debian.org/waitid(2)}}
will immediately return the error @ref{26fd,,EAGAIN} rather than blocking.
@end deffn

@ref{213f,,Availability}: Linux >= 5.10


Added in version 3.12.

@end deffn

@geindex plock() (os モジュール)
@anchor{library/os os plock}@anchor{30cc}
@deffn {の関数} os.plock (op, /)

プログラムのセグメントをメモリ内にロックします。 `op' (@code{<sys/lock.h>} で定義されています ) にはどのセグメントをロックするかを指定します。

@ref{213f,,Availability}: Unix, not WASI, not iOS.
@end deffn

@geindex popen() (os モジュール)
@anchor{library/os os popen}@anchor{31a}
@deffn {の関数} os.popen (cmd, mode='r', buffering=-1)

コマンド `cmd' への、または `cmd' からのパイプ入出力を開きます。戻り値はパイプに接続されている開かれたファイルオブジェクトで、 `mode' が @code{'r'} (デフォルト) または @code{'w'} かによって読み出しまたは書き込みを行うことができます。引数 `bufsize' は、組み込み関数 @ref{316,,open()} における対応する引数と同じ意味を持ちます。 返されるファイルオブジェクトは、バイトではなくテキスト文字列を読み書きします。

@code{close} メソッドは、サブプロセスが正常に終了した場合は @ref{885,,None} を返し、エラーが発生した場合にはサブプロセスの返りコードを返します。POSIX システムでは、返りコードが正の場合、そのコードは1バイト左にシフトしてプロセスが終了したことを示します。返りコードが負の場合、プロセスは返りコードの符号を変えた信号により終了します 。 (例えば、サブプロセスが kill された場合、返り値は @code{- signal.SIGKILL} となる場合があります。) Windows システムでは、返り値には子プロセスからの符号のついた整数の返りコードを含まれます。

On Unix, @ref{b17,,waitstatus_to_exitcode()} can be used to convert the @code{close}
method result (exit status) into an exit code if it is not @code{None}. On
Windows, the @code{close} method result is directly the exit code
(or @code{None}).

これは、@ref{4b7,,subprocess.Popen} を使用して実装されています。サブプロセスを管理し、サブプロセスと通信を行うためのより強力な方法については、クラスのドキュメンテーションを参照してください。

@ref{213f,,Availability}: not WASI, not Android, not iOS.

@cartouche
@quotation 注釈 
The @ref{866,,Python UTF-8 Mode} affects encodings used
for `cmd' and pipe contents.

@ref{31a,,popen()} is a simple wrapper around @ref{4b7,,subprocess.Popen}.
Use @ref{4b7,,subprocess.Popen} or @ref{d7f,,subprocess.run()} to
control options like encodings.
@end quotation
@end cartouche


バージョン 3.14 で非推奨: The function is @ref{23d,,soft deprecated} and should no longer be used to
write new code. The @ref{dc,,subprocess} module is recommended instead.

@end deffn

@geindex posix_spawn() (os モジュール)
@anchor{library/os os posix_spawn}@anchor{52e}
@deffn {の関数} os.posix_spawn (path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

Wraps the @code{posix_spawn()} C library API for use from Python.

大部分のユーザーは @ref{52e,,posix_spawn()} ではなく、 @ref{d7f,,subprocess.run()} を使うべきです。

The positional-only arguments `path', `args', and `env' are similar to
@ref{1311,,execve()}. `env' is allowed to be @code{None}, in which case current
process' environment is used.

`path' には実行ファイルへのパスを指定します。 `path' はディレクトリを含む形（実行ファイルへの絶対パスまたは相対パス）で指定する必要があります。実行ファイル名のみを指定したい場合は @ref{1e11,,posix_spawnp()} を使ってください。

`file_actions' 引数はCライブラリ実装の @code{fork()} と @code{exec()} の間で子プロセスが持つファイルデスクリプタに対して行うアクションを記述するタプルのシーケンスです。各タプルの最初の要素は、残りのタプル要素の解釈方法を指定する以下の3つの型指定子のうちのひとつでなければなりません。

@geindex POSIX_SPAWN_OPEN (os モジュール)
@anchor{library/os os POSIX_SPAWN_OPEN}@anchor{30cd}
@deffn {データ} os.POSIX_SPAWN_OPEN

(@code{os.POSIX_SPAWN_OPEN}, `fd', `path', `flags', `mode')

@code{os.dup2(os.open(path, flags, mode), fd)} を実行します。
@end deffn

@geindex POSIX_SPAWN_CLOSE (os モジュール)
@anchor{library/os os POSIX_SPAWN_CLOSE}@anchor{30ce}
@deffn {データ} os.POSIX_SPAWN_CLOSE

(@code{os.POSIX_SPAWN_CLOSE}, `fd')

@code{os.close(fd)} を実行します。
@end deffn

@geindex POSIX_SPAWN_DUP2 (os モジュール)
@anchor{library/os os POSIX_SPAWN_DUP2}@anchor{30cf}
@deffn {データ} os.POSIX_SPAWN_DUP2

(@code{os.POSIX_SPAWN_DUP2}, `fd', `new_fd')

@code{os.dup2(fd, new_fd)} を実行します。
@end deffn

@geindex POSIX_SPAWN_CLOSEFROM (os モジュール)
@anchor{library/os os POSIX_SPAWN_CLOSEFROM}@anchor{52f}
@deffn {データ} os.POSIX_SPAWN_CLOSEFROM

(@code{os.POSIX_SPAWN_CLOSEFROM}, `fd')

Performs @code{os.closerange(fd, INF)}.
@end deffn

These tuples correspond to the C library
@code{posix_spawn_file_actions_addopen()},
@code{posix_spawn_file_actions_addclose()},
@code{posix_spawn_file_actions_adddup2()}, and
@code{posix_spawn_file_actions_addclosefrom_np()} API calls used to prepare
for the @code{posix_spawn()} call itself.

The `setpgroup' argument will set the process group of the child to the value
specified. If the value specified is 0, the child's process group ID will be
made the same as its process ID. If the value of `setpgroup' is not set, the
child will inherit the parent's process group ID. This argument corresponds
to the C library @code{POSIX_SPAWN_SETPGROUP} flag.

If the `resetids' argument is @code{True} it will reset the effective UID and
GID of the child to the real UID and GID of the parent process. If the
argument is @code{False}, then the child retains the effective UID and GID of
the parent. In either case, if the set-user-ID and set-group-ID permission
bits are enabled on the executable file, their effect will override the
setting of the effective UID and GID. This argument corresponds to the C
library @code{POSIX_SPAWN_RESETIDS} flag.

If the `setsid' argument is @code{True}, it will create a new session ID
for @code{posix_spawn}. `setsid' requires @code{POSIX_SPAWN_SETSID}
or @code{POSIX_SPAWN_SETSID_NP} flag. Otherwise, @ref{36b,,NotImplementedError}
is raised.

The `setsigmask' argument will set the signal mask to the signal set
specified. If the parameter is not used, then the child inherits the
parent's signal mask. This argument corresponds to the C library
@code{POSIX_SPAWN_SETSIGMASK} flag.

The `sigdef' argument will reset the disposition of all signals in the set
specified. This argument corresponds to the C library
@code{POSIX_SPAWN_SETSIGDEF} flag.

The `scheduler' argument must be a tuple containing the (optional) scheduler
policy and an instance of @ref{1910,,sched_param} with the scheduler parameters.
A value of @code{None} in the place of the scheduler policy indicates that is
not being provided. This argument is a combination of the C library
@code{POSIX_SPAWN_SETSCHEDPARAM} and @code{POSIX_SPAWN_SETSCHEDULER}
flags.

引数 @code{path}, @code{argv}, @code{env} を指定して @ref{1c6e,,監査イベント} @code{os.posix_spawn} を送出します。


Added in version 3.8.



バージョン 3.13 で変更: `env' parameter accepts @code{None}.
@code{os.POSIX_SPAWN_CLOSEFROM} is available on platforms where
@code{posix_spawn_file_actions_addclosefrom_np()} exists.


@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex posix_spawnp() (os モジュール)
@anchor{library/os os posix_spawnp}@anchor{1e11}
@deffn {の関数} os.posix_spawnp (path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

Wraps the @code{posix_spawnp()} C library API for use from Python.

Similar to @ref{52e,,posix_spawn()} except that the system searches
for the `executable' file in the list of directories specified by the
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} environment variable (in the same way as for @code{execvp(3)}).

引数 @code{path}, @code{argv}, @code{env} を指定して @ref{1c6e,,監査イベント} @code{os.posix_spawn} を送出します。


Added in version 3.8.


@ref{213f,,Availability}: POSIX, not WASI, not Android, not iOS.

See @ref{52e,,posix_spawn()} documentation.
@end deffn

@geindex register_at_fork() (os モジュール)
@anchor{library/os os register_at_fork}@anchor{355}
@deffn {の関数} os.register_at_fork (*, before=None, after_in_parent=None, after_in_child=None)

Register callables to be executed when a new child process is forked
using @ref{4b5,,os.fork()} or similar process cloning APIs.
The parameters are optional and keyword-only.
Each specifies a different call point.


@itemize *

@item 
`before' is a function called before forking a child process.

@item 
`after_in_parent' is a function called from the parent process
after forking a child process.

@item 
`after_in_child' is a function called from the child process.
@end itemize

These calls are only made if control is expected to return to the
Python interpreter.  A typical @ref{dc,,subprocess} launch will not
trigger them as the child is not going to re-enter the interpreter.

Functions registered for execution before forking are called in
reverse registration order.  Functions registered for execution
after forking (either in the parent or in the child) are called
in registration order.

Note that @code{fork()} calls made by third-party C code may not
call those functions, unless it explicitly calls @ref{db8,,PyOS_BeforeFork()},
@ref{db9,,PyOS_AfterFork_Parent()} and @ref{430,,PyOS_AfterFork_Child()}.

There is no way to unregister a function.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.


Added in version 3.7.

@end deffn

@geindex spawnl() (os モジュール)
@geindex spawnle() (os モジュール)
@geindex spawnlp() (os モジュール)
@geindex spawnlpe() (os モジュール)
@geindex spawnv() (os モジュール)
@geindex spawnve() (os モジュール)
@geindex spawnvp() (os モジュール)
@geindex spawnvpe() (os モジュール)
@anchor{library/os os spawnl}@anchor{31b}
@deffn {の関数} os.spawnl (mode, path, ...)
@anchor{library/os os spawnle}@anchor{30d0}
@deffnx {の関数} os.spawnle (mode, path, ..., env)
@anchor{library/os os spawnlp}@anchor{30d1}
@deffnx {の関数} os.spawnlp (mode, file, ...)
@anchor{library/os os spawnlpe}@anchor{30d2}
@deffnx {の関数} os.spawnlpe (mode, file, ..., env)
@anchor{library/os os spawnv}@anchor{30d3}
@deffnx {の関数} os.spawnv (mode, path, args)
@anchor{library/os os spawnve}@anchor{30d4}
@deffnx {の関数} os.spawnve (mode, path, args, env)
@anchor{library/os os spawnvp}@anchor{30d5}
@deffnx {の関数} os.spawnvp (mode, file, args)
@anchor{library/os os spawnvpe}@anchor{30d6}
@deffnx {の関数} os.spawnvpe (mode, file, args, env)

新たなプロセス内でプログラム `path' を実行します。

(@ref{dc,,subprocess} モジュールが、新しいプロセスを実行して結果を取得するための、より強力な機能を提供しています。この関数の代わりに @ref{dc,,subprocess} モジュールを利用することが推奨されています。 @ref{dc,,subprocess} モジュールのドキュメントの、 @ref{13a0,,Replacing Older Functions with the subprocess Module} セクションを参照してください )

`mode' が @ref{30d7,,P_NOWAIT} の場合、この関数は新たなプロセスのプロセス ID を返します ; `mode' が @ref{30d8,,P_WAIT} の場合、子プロセスが正常に終了するとその終了コードが返ります。そうでない場合にはプロセスを kill したシグナル `signal' に対して @code{-signal} が返ります。 Windows では、プロセス ID は実際にはプロセスハンドル値になるので、 @ref{f9a,,waitpid()} 関数で使えます。

Note on VxWorks, this function doesn't return @code{-signal} when the new process is
killed. Instead it raises OSError exception.

The "l" and "v" variants of the @ref{31b,,spawn*} functions differ in how
command-line arguments are passed.  The "l" variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the
@code{spawnl*()} functions.  The "v" variants are good when the number of
parameters is variable, with the arguments being passed in a list or tuple as
the `args' parameter.  In either case, the arguments to the child process must
start with the name of the command being run.

末尾近くに "p" をもつ型 (@ref{30d1,,spawnlp()}, @ref{30d2,,spawnlpe()}, @ref{30d5,,spawnvp()}, @ref{30d6,,spawnvpe()}) は、プログラム `file' を探すために環境変数 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} を利用します。環境変数が ( 次の段で述べる @ref{31b,,spawn*e} 型関数で ) 置き換えられる場合、環境変数は 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} を決定する上の情報源として使われます。その他の型、 @ref{31b,,spawnl()}, @ref{30d0,,spawnle()}, @ref{30d3,,spawnv()}, および @ref{30d4,,spawnve()} では、実行コードを探すために 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} を使いません。 `path' には適切に設定された絶対パスまたは相対パスが入っていなくてはなりません。

@ref{30d0,,spawnle()}, @ref{30d2,,spawnlpe()}, @ref{30d4,,spawnve()}, および @ref{30d6,,spawnvpe()} (すべて末尾に "e" がついています) では、 `env' 引数は新たなプロセスで利用される環境変数を定義するためのマップ型でなくてはなりません ; @ref{31b,,spawnl()} 、 @ref{30d1,,spawnlp()} 、 @ref{30d3,,spawnv()} 、および @ref{30d5,,spawnvp()} では、すべて新たなプロセスは現在のプロセスの環境を引き継ぎます。 `env' 辞書のキーと値はすべて文字列である必要があります。不正なキーや値を与えると関数が失敗し、 @code{127} を返します。

例えば、以下の @ref{30d1,,spawnlp()} および @ref{30d6,,spawnvpe()} 呼び出しは等価です

@example
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
@end example

引数 @code{mode}, @code{path}, @code{args}, @code{env} を指定して @ref{1c6e,,監査イベント} @code{os.spawn} を送出します。

@ref{213f,,Availability}: Unix, Windows, not WASI, not Android, not iOS.

@ref{30d1,,spawnlp()} 、 @ref{30d2,,spawnlpe()} 、 @ref{30d5,,spawnvp()} 、および @ref{30d6,,spawnvpe()} は Windows では利用できません。 @ref{30d0,,spawnle()} および @ref{30d4,,spawnve()} は Windows においてスレッドセーフではありません ; 代わりに @ref{dc,,subprocess} モジュールの利用を推奨します。


バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.14 で非推奨: These functions are @ref{23d,,soft deprecated} and should no longer be used
to write new code. The @ref{dc,,subprocess} module is recommended instead.

@end deffn

@geindex P_NOWAIT (os モジュール)
@geindex P_NOWAITO (os モジュール)
@anchor{library/os os P_NOWAIT}@anchor{30d7}
@deffn {データ} os.P_NOWAIT
@anchor{library/os os P_NOWAITO}@anchor{30d9}
@deffnx {データ} os.P_NOWAITO

Possible values for the `mode' parameter to the @ref{31b,,spawn*} family of
functions.  If either of these values is given, the @ref{31b,,spawn*} functions
will return as soon as the new process has been created, with the process id as
the return value.

@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex P_WAIT (os モジュール)
@anchor{library/os os P_WAIT}@anchor{30d8}
@deffn {データ} os.P_WAIT

Possible value for the `mode' parameter to the @ref{31b,,spawn*} family of
functions.  If this is given as `mode', the @ref{31b,,spawn*} functions will not
return until the new process has run to completion and will return the exit code
of the process the run is successful, or @code{-signal} if a signal kills the
process.

@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex P_DETACH (os モジュール)
@geindex P_OVERLAY (os モジュール)
@anchor{library/os os P_DETACH}@anchor{30da}
@deffn {データ} os.P_DETACH
@anchor{library/os os P_OVERLAY}@anchor{30db}
@deffnx {データ} os.P_OVERLAY

@ref{31b,,spawn*} 関数ファミリに対する `mode' パラメタとして取れる値です。これらの値は上の値よりもやや可搬性において劣っています。 @ref{30da,,P_DETACH} は @ref{30d7,,P_NOWAIT} に似ていますが、新たなプロセスは呼び出しプロセスのコンソールから切り離され (detach) ます。 @ref{30db,,P_OVERLAY} が使われた場合、現在のプロセスは置き換えられます。したがって @ref{31b,,spawn*} は返りません。

@ref{213f,,Availability}: Windows.
@end deffn

@geindex startfile() (os モジュール)
@anchor{library/os os startfile}@anchor{1c83}
@deffn {の関数} os.startfile (path[, operation][, arguments][, cwd][, show_cmd])

ファイルを関連付けられたアプリケーションを使ってスタートします。

When `operation' is not specified, this acts like double-clicking
the file in Windows Explorer, or giving the file name as an argument to the
@code{start} command from the interactive command shell: the file is opened
with whatever application (if any) its extension is associated.

When another `operation' is given, it must be a "command verb" that specifies
what should be done with the file. Common verbs documented by Microsoft are @code{'open'},
@code{'print'} and  @code{'edit'} (to be used on files) as well as @code{'explore'} and
@code{'find'} (to be used on directories).

When launching an application, specify `arguments' to be passed as a single
string. This argument may have no effect when using this function to launch a
document.

The default working directory is inherited, but may be overridden by the `cwd'
argument. This should be an absolute path. A relative `path' will be resolved
against this argument.

Use `show_cmd' to override the default window style. Whether this has any
effect will depend on the application being launched. Values are integers as
supported by the Win32 @code{ShellExecute()} function.

@ref{1c83,,startfile()} returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way to retrieve
the application's exit status.  The `path' parameter is relative to the current
directory or `cwd'.  If you want to use an absolute path, make sure the first
character is not a slash (@code{'/'})  Use @ref{a8,,pathlib} or the
@ref{1531,,os.path.normpath()} function to ensure that paths are properly encoded for
Win32.

To reduce interpreter startup overhead, the Win32 @code{ShellExecute()}
function is not resolved until this function is first called.  If the function
cannot be resolved, @ref{36b,,NotImplementedError} will be raised.

引数 @code{path}, @code{operation} を指定して @ref{1c6e,,監査イベント} @code{os.startfile} を送出します。

Raises an @ref{1c6e,,auditing event} @code{os.startfile/2} with arguments @code{path}, @code{operation}, @code{arguments}, @code{cwd}, @code{show_cmd}.

@ref{213f,,Availability}: Windows.


バージョン 3.10 で変更: Added the `arguments', `cwd' and `show_cmd' arguments, and the
@code{os.startfile/2} audit event.

@end deffn

@geindex system() (os モジュール)
@anchor{library/os os system}@anchor{1676}
@deffn {の関数} os.system (command)

Execute the command (a string) in a subshell.  This is implemented by calling
the Standard C function @code{system()}, and has the same limitations.
Changes to @ref{75f,,sys.stdin}, etc. are not reflected in the environment of
the executed command. If `command' generates any output, it will be sent to
the interpreter standard output stream. The C standard does not
specify the meaning of the return value of the C function, so the return
value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the
format specified for @ref{f98,,wait()}.

Windows では、返り値は `command' を実行した後にシステムシェルから返される値です。シェルは通常 @code{cmd.exe} であり、返す値は実行したコマンドの終了ステータスになります。シェルの種類は Windows の環境変数 
@geindex COMSPEC
@geindex 環境変数; COMSPEC
@code{COMSPEC}: に指定されています。ネイティブでないシェルを使用している場合は、そのドキュメントを参照してください。

The @ref{dc,,subprocess} module provides more powerful facilities for spawning
new processes and retrieving their results; using that module is recommended
to using this function.  See the @ref{13a0,,Replacing Older Functions with the subprocess Module} section in
the @ref{dc,,subprocess} documentation for some helpful recipes.

On Unix, @ref{b17,,waitstatus_to_exitcode()} can be used to convert the result
(exit status) into an exit code. On Windows, the result is directly the exit
code.

引数 @code{command} を指定して @ref{1c6e,,監査イベント} @code{os.system} を送出します。

@ref{213f,,Availability}: Unix, Windows, not WASI, not Android, not iOS.
@end deffn

@geindex times() (os モジュール)
@anchor{library/os os times}@anchor{132d}
@deffn {の関数} os.times ()

現在の全体的なプロセス時間を返します。返り値は 5 個の属性を持つオブジェクトになります:


@itemize *

@item 
@code{user} - user time

@item 
@code{system} - system time

@item 
@code{children_user} - user time of all child processes

@item 
@code{children_system} - system time of all child processes

@item 
@code{elapsed} - elapsed real time since a fixed point in the past
@end itemize

後方互換性のため、このオブジェクトは 5 個のアイテム @code{user} 、 @code{system} 、 @code{children_user} 、 @code{children_system} 、および @code{elapsed} を持つタプルのようにも振る舞います。

See the Unix manual page
@code{times(2)@footnote{https://manpages.debian.org/times(2)}} and times(3)@footnote{https://man.freebsd.org/cgi/man.cgi?time(3)} manual page on Unix or the GetProcessTimes MSDN@footnote{https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes}
on Windows. On Windows, only @code{user} and @code{system} are known; the other attributes are zero.

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.3 で変更: 返り値の型が、タプルから属性名のついたタプルライクオブジェクトに変更されました。

@end deffn

@geindex wait() (os モジュール)
@anchor{library/os os wait}@anchor{f98}
@deffn {の関数} os.wait ()

子プロセスの実行完了を待機し、子プロセスの pid と終了コードインジケーター --- 16 ビットの数値で、下位バイトがプロセスを kill したシグナル番号、上位バイトが終了ステータス ( シグナル番号がゼロの場合 ) --- の入ったタプルを返します ; コアダンプファイルが生成された場合、下位バイトの最上桁ビットが立てられます。

If there are no children that could be waited for, @ref{1263,,ChildProcessError}
is raised.

戻り値の終了ステータスを終了コードに変換するために @ref{b17,,waitstatus_to_exitcode()} を使うことができます。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.


@subsubheading 参考


The other @code{wait*()} functions documented below can be used to wait for the
completion of a specific child process and have more options.
@ref{f9a,,waitpid()} is the only one also available on Windows.

@end deffn

@geindex waitid() (os モジュール)
@anchor{library/os os waitid}@anchor{f99}
@deffn {の関数} os.waitid (idtype, id, options, /)

Wait for the completion of a child process.

`idtype' can be @ref{30dc,,P_PID}, @ref{30dd,,P_PGID}, @ref{30de,,P_ALL}, or (on Linux) @ref{b16,,P_PIDFD}.
The interpretation of `id' depends on it; see their individual descriptions.

`options' is an OR combination of flags.  At least one of @ref{30df,,WEXITED},
@ref{30e0,,WSTOPPED} or @ref{30e1,,WCONTINUED} is required;
@ref{30e2,,WNOHANG} and @ref{30e3,,WNOWAIT} are additional optional flags.

The return value is an object representing the data contained in the
@code{siginfo_t} structure with the following attributes:


@itemize *

@item 
@code{si_pid} (process ID)

@item 
@code{si_uid} (real user ID of the child)

@item 
@code{si_signo} (always @ref{30e4,,SIGCHLD})

@item 
@code{si_status} (the exit status or signal number, depending on @code{si_code})

@item 
@code{si_code} (see @ref{30e5,,CLD_EXITED} for possible values)
@end itemize

If @ref{30e2,,WNOHANG} is specified and there are no matching children in the
requested state, @code{None} is returned.
Otherwise, if there are no matching children
that could be waited for, @ref{1263,,ChildProcessError} is raised.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.


Added in version 3.3.



バージョン 3.13 で変更: This function is now available on macOS as well.

@end deffn

@geindex waitpid() (os モジュール)
@anchor{library/os os waitpid}@anchor{f9a}
@deffn {の関数} os.waitpid (pid, options, /)

この関数の詳細は Unix と Windows で異なります。

Unix の場合 : プロセス id `pid' で与えられた子プロセスの完了を待機し、子プロセスのプロセス id と (@ref{f98,,wait()} と同様にコード化された ) 終了ステータスインジケーターからなるタプルを返します。この関数の動作は `options' によって変わります。通常の操作では @code{0} にします。

`pid' が @code{0} よりも大きい場合、 @ref{f9a,,waitpid()} は特定のプロセスのステータス情報を要求します。 `pid' が @code{0} の場合、現在のプロセスグループ内の任意の子プロセスの状態に対する要求です。 `pid' が @code{-1} の場合、現在のプロセスの任意の子プロセスに対する要求です。 `pid' が @code{-1} よりも小さい場合、プロセスグループ @code{-pid} ( すなわち `pid' の絶対値 ) 内の任意のプロセスに対する要求です。

`options' is an OR combination of flags.  If it contains @ref{30e2,,WNOHANG} and
there are no matching children in the requested state, @code{(0, 0)} is
returned.  Otherwise, if there are no matching children that could be waited
for, @ref{1263,,ChildProcessError} is raised.  Other options that can be used are
@ref{30e6,,WUNTRACED} and @ref{30e1,,WCONTINUED}.

Windows では、プロセスハンドル `pid' を指定してプロセスの終了を待って、 `pid' と、終了ステータスを 8bit 左シフトした値のタプルを返します。 ( シフトは、この関数をクロスプラットフォームで利用しやすくするために行われます ) @code{0} 以下の `pid' は Windows では特別な意味を持っておらず、例外を発生させます。 `options' の値は効果がありません。 `pid' は、子プロセスで無くても、プロセス ID を知っているどんなプロセスでも参照することが可能です。 @ref{31b,,spawn*} 関数を @ref{30d7,,P_NOWAIT} と共に呼び出した場合、適切なプロセスハンドルが返されます。

戻り値の終了ステータスを終了コードに変換するために @ref{b17,,waitstatus_to_exitcode()} を使うことができます。

@ref{213f,,Availability}: Unix, Windows, not WASI, not Android, not iOS.


バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、この関数は @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex wait3() (os モジュール)
@anchor{library/os os wait3}@anchor{f96}
@deffn {の関数} os.wait3 (options)

@ref{f9a,,waitpid()} に似ていますが、プロセス id を引数に取らず、子プロセス id 、終了ステータスインジケータ、リソース使用情報の 3 要素からなるタプルを返します。リソース使用情報の詳しい情報は @ref{164a,,resource.getrusage()} を参照してください。`options' 引数は @ref{f9a,,waitpid()} および @ref{f97,,wait4()} に渡されるものと同じです。

戻り値の終了ステータスを終了コードに変換するために @ref{b17,,waitstatus_to_exitcode()} を使うことができます。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex wait4() (os モジュール)
@anchor{library/os os wait4}@anchor{f97}
@deffn {の関数} os.wait4 (pid, options)

@ref{f9a,,waitpid()} に似ていますが、子プロセス id 、終了ステータスインジケータ、リソース使用情報の 3 要素からなるタプルを返します。リソース使用情報の詳しい情報は @ref{164a,,resource.getrusage()} を参照してください。 @ref{f97,,wait4()} の引数は @ref{f9a,,waitpid()} に与えられるものと同じです。

戻り値の終了ステータスを終了コードに変換するために @ref{b17,,waitstatus_to_exitcode()} を使うことができます。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex P_PID (os モジュール)
@geindex P_PGID (os モジュール)
@geindex P_ALL (os モジュール)
@geindex P_PIDFD (os モジュール)
@anchor{library/os os P_PID}@anchor{30dc}
@deffn {データ} os.P_PID
@anchor{library/os os P_PGID}@anchor{30dd}
@deffnx {データ} os.P_PGID
@anchor{library/os os P_ALL}@anchor{30de}
@deffnx {データ} os.P_ALL
@anchor{library/os os P_PIDFD}@anchor{b16}
@deffnx {データ} os.P_PIDFD

@ref{f99,,waitid()} の `idtype' に指定できる値です。これらは `id' がどう解釈されるかに影響します:


@itemize *

@item 
@code{P_PID} - wait for the child whose PID is `id'.

@item 
@code{P_PGID} - wait for any child whose progress group ID is `id'.

@item 
@code{P_ALL} - wait for any child; `id' is ignored.

@item 
@code{P_PIDFD} - wait for the child identified by the file descriptor
`id' (a process file descriptor created with @ref{6a4,,pidfd_open()}).
@end itemize

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.

@cartouche
@quotation 注釈 
@code{P_PIDFD} is only available on Linux >= 5.4.
@end quotation
@end cartouche


Added in version 3.3.



Added in version 3.9: The @code{P_PIDFD} constant.

@end deffn

@geindex WCONTINUED (os モジュール)
@anchor{library/os os WCONTINUED}@anchor{30e1}
@deffn {データ} os.WCONTINUED

This `options' flag for @ref{f9a,,waitpid()}, @ref{f96,,wait3()}, @ref{f97,,wait4()}, and
@ref{f99,,waitid()} causes child processes to be reported if they have been
continued from a job control stop since they were last reported.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WEXITED (os モジュール)
@anchor{library/os os WEXITED}@anchor{30df}
@deffn {データ} os.WEXITED

This `options' flag for @ref{f99,,waitid()} causes child processes that have terminated to
be reported.

The other @code{wait*} functions always report children that have terminated,
so this option is not available for them.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.


Added in version 3.3.

@end deffn

@geindex WSTOPPED (os モジュール)
@anchor{library/os os WSTOPPED}@anchor{30e0}
@deffn {データ} os.WSTOPPED

This `options' flag for @ref{f99,,waitid()} causes child processes that have been stopped
by the delivery of a signal to be reported.

This option is not available for the other @code{wait*} functions.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.


Added in version 3.3.

@end deffn

@geindex WUNTRACED (os モジュール)
@anchor{library/os os WUNTRACED}@anchor{30e6}
@deffn {データ} os.WUNTRACED

This `options' flag for @ref{f9a,,waitpid()}, @ref{f96,,wait3()}, and @ref{f97,,wait4()} causes
child processes to also be reported if they have been stopped but their
current state has not been reported since they were stopped.

This option is not available for @ref{f99,,waitid()}.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WNOHANG (os モジュール)
@anchor{library/os os WNOHANG}@anchor{30e2}
@deffn {データ} os.WNOHANG

This `options' flag causes @ref{f9a,,waitpid()}, @ref{f96,,wait3()}, @ref{f97,,wait4()}, and
@ref{f99,,waitid()} to return right away if no child process status is available
immediately.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WNOWAIT (os モジュール)
@anchor{library/os os WNOWAIT}@anchor{30e3}
@deffn {データ} os.WNOWAIT

This `options' flag causes @ref{f99,,waitid()} to leave the child in a waitable state, so that
a later @code{wait*()} call can be used to retrieve the child status information again.

This option is not available for the other @code{wait*} functions.

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex CLD_EXITED (os モジュール)
@geindex CLD_KILLED (os モジュール)
@geindex CLD_DUMPED (os モジュール)
@geindex CLD_TRAPPED (os モジュール)
@geindex CLD_STOPPED (os モジュール)
@geindex CLD_CONTINUED (os モジュール)
@anchor{library/os os CLD_EXITED}@anchor{30e5}
@deffn {データ} os.CLD_EXITED
@anchor{library/os os CLD_KILLED}@anchor{b14}
@deffnx {データ} os.CLD_KILLED
@anchor{library/os os CLD_DUMPED}@anchor{30e7}
@deffnx {データ} os.CLD_DUMPED
@anchor{library/os os CLD_TRAPPED}@anchor{30e8}
@deffnx {データ} os.CLD_TRAPPED
@anchor{library/os os CLD_STOPPED}@anchor{b15}
@deffnx {データ} os.CLD_STOPPED
@anchor{library/os os CLD_CONTINUED}@anchor{30e9}
@deffnx {データ} os.CLD_CONTINUED

@ref{f99,,waitid()} の返り値の @code{si_code} に設定され得る値です。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.


Added in version 3.3.



バージョン 3.9 で変更: @ref{b14,,CLD_KILLED} と @ref{b15,,CLD_STOPPED} が追加されました。

@end deffn

@geindex waitstatus_to_exitcode() (os モジュール)
@anchor{library/os os waitstatus_to_exitcode}@anchor{b17}
@deffn {の関数} os.waitstatus_to_exitcode (status)

待機ステータスを終了コードに変換します。

Unix の場合:


@itemize *

@item 
子プロセスが正常終了した場合 (@code{WIFEXITED(status)`@w{`}が真の場合)、子プロセスの終了ステータス (`@w{`}WEXITSTATUS(status)}) を返します: 戻り値は0または正の整数です。

@item 
子プロセスがシグナルによって終了した場合 (@code{WIFSIGNALED(status)`@w{`}が真の場合)、子プロセスを終了したシグナルの番号に負符号をつけた `@w{`}-signum} (@code{-WTERMSIG(status)}) を返します: 戻り値は負の整数です。

@item 
それ以外の場合、 @ref{2ec,,ValueError} 例外を送出します。
@end itemize

Windows の場合、 `status' を8ビット右にシフトした値を返します。

Unix の場合、プロセスがトレースされているか @ref{f9a,,waitpid()} が @ref{30e6,,WUNTRACED} オプションをつけて実行されている場合、呼び出しもとは最初に @code{WIFSTOPPED(status)} が真であるかを確認しなければなりません。この関数は @code{WIFSTOPPED(status)} が真の場合呼び出してはいけません。


@subsubheading 参考


@ref{30ea,,WIFEXITED()}, @ref{30eb,,WEXITSTATUS()}, @ref{30ec,,WIFSIGNALED()}, @ref{30ed,,WTERMSIG()}, @ref{30ee,,WIFSTOPPED()}, @ref{30ef,,WSTOPSIG()} 関数。


@ref{213f,,Availability}: Unix, Windows, not WASI, not Android, not iOS.


Added in version 3.9.

@end deffn

以下の関数は @ref{1676,,system()} 、 @ref{f98,,wait()} 、あるいは @ref{f9a,,waitpid()} が返すプロセス状態コードを引数にとります。これらの関数はプロセスの配置を決めるために利用できます。

@geindex WCOREDUMP() (os モジュール)
@anchor{library/os os WCOREDUMP}@anchor{30f0}
@deffn {の関数} os.WCOREDUMP (status, /)

プロセスに対してコアダンプが生成されていた場合には @code{True} を、それ以外の場合は @code{False} を返します。

この関数は @ref{30ec,,WIFSIGNALED()} が真である場合のみ使用されるべきです。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WIFCONTINUED() (os モジュール)
@anchor{library/os os WIFCONTINUED}@anchor{30f1}
@deffn {の関数} os.WIFCONTINUED (status)

Return @code{True} if a stopped child has been resumed by delivery of
@ref{30f2,,SIGCONT} (if the process has been continued from a job
control stop), otherwise return @code{False}.

@ref{30e1,,WCONTINUED} オプションを参照してください。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WIFSTOPPED() (os モジュール)
@anchor{library/os os WIFSTOPPED}@anchor{30ee}
@deffn {の関数} os.WIFSTOPPED (status)

プロセスがシグナルの送信によって中断させられた場合に @code{True} を返します。それ以外の場合は @code{False} を返します。

@ref{30ee,,WIFSTOPPED()} は @ref{f9a,,waitpid()} が @ref{30e6,,WUNTRACED} オプションを使って実行されたか、もしくはプロセスがトレースされている場合 (@code{ptrace(2)@footnote{https://manpages.debian.org/ptrace(2)}} を参照してください) にのみ @code{True} を返します。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WIFSIGNALED() (os モジュール)
@anchor{library/os os WIFSIGNALED}@anchor{30ec}
@deffn {の関数} os.WIFSIGNALED (status)

プロセスがシグナルによって終了させられた場合に @code{True} を返します。そうでない場合は @code{False} を返します。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WIFEXITED() (os モジュール)
@anchor{library/os os WIFEXITED}@anchor{30ea}
@deffn {の関数} os.WIFEXITED (status)

プロセスが正常終了した場合、すなわち @code{exit()} や @code{_exit()} を呼び出したか、もしくは @code{main()} から戻ることにより終了した場合に @code{True} を返します。それ以外は @code{False} を返します。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WEXITSTATUS() (os モジュール)
@anchor{library/os os WEXITSTATUS}@anchor{30eb}
@deffn {の関数} os.WEXITSTATUS (status)

プロセスの終了ステータスを返します。

この関数は @ref{30ea,,WIFEXITED()} が真である場合のみ使用されるべきです。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WSTOPSIG() (os モジュール)
@anchor{library/os os WSTOPSIG}@anchor{30ef}
@deffn {の関数} os.WSTOPSIG (status)

プロセスを停止させたシグナル番号を返します。

この関数は @ref{30ee,,WIFSTOPPED()} が真である場合のみ使用されるべきです。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@geindex WTERMSIG() (os モジュール)
@anchor{library/os os WTERMSIG}@anchor{30ed}
@deffn {の関数} os.WTERMSIG (status)

プロセスを終了させたシグナルの番号を返します。

この関数は @ref{30ec,,WIFSIGNALED()} が真である場合のみ使用されるべきです。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.
@end deffn

@node スケジューラーへのインターフェイス,雑多なシステム情報,プロセス管理,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os interface-to-the-scheduler}@anchor{30f3}
@subsubsection スケジューラーへのインターフェイス


以下の関数は、オペレーティングシステムがプロセスに CPU 時間を割り当てる方法を制御します。これらは一部の Unix プラットフォームでのみ利用可能です。詳しくは Unix マニュアルページを参照してください。


Added in version 3.3.


次のスケジューリングポリシーは、オペレーティングシステムでサポートされていれば公開されます。

@geindex SCHED_OTHER (os モジュール)
@anchor{library/os os-scheduling-policy}@anchor{30f4}@anchor{library/os os SCHED_OTHER}@anchor{30f5}
@deffn {データ} os.SCHED_OTHER

デフォルトのスケジューリングポリシーです。
@end deffn

@geindex SCHED_BATCH (os モジュール)
@anchor{library/os os SCHED_BATCH}@anchor{30f6}
@deffn {データ} os.SCHED_BATCH

常にCPUに負荷のかかる (CPU-intensive) プロセス用のポリシーです。他の対話式プロセスなどの応答性を維持するよう試みます。
@end deffn

@geindex SCHED_DEADLINE (os モジュール)
@anchor{library/os os SCHED_DEADLINE}@anchor{25d}
@deffn {データ} os.SCHED_DEADLINE

Scheduling policy for tasks with deadline constraints.


Added in version 3.14.

@end deffn

@geindex SCHED_IDLE (os モジュール)
@anchor{library/os os SCHED_IDLE}@anchor{30f7}
@deffn {データ} os.SCHED_IDLE

非常に優先度の低いバックグラウンドタスク用のスケジューリングポリシーです。
@end deffn

@geindex SCHED_NORMAL (os モジュール)
@anchor{library/os os SCHED_NORMAL}@anchor{25e}
@deffn {データ} os.SCHED_NORMAL

Alias for @ref{30f5,,SCHED_OTHER}.


Added in version 3.14.

@end deffn

@geindex SCHED_SPORADIC (os モジュール)
@anchor{library/os os SCHED_SPORADIC}@anchor{30f8}
@deffn {データ} os.SCHED_SPORADIC

散発的なサーバープログラム用のスケジューリングポリシーです。
@end deffn

@geindex SCHED_FIFO (os モジュール)
@anchor{library/os os SCHED_FIFO}@anchor{30f9}
@deffn {データ} os.SCHED_FIFO

FIFO (First In, First Out) 型のスケジューリングポリシーです。
@end deffn

@geindex SCHED_RR (os モジュール)
@anchor{library/os os SCHED_RR}@anchor{30fa}
@deffn {データ} os.SCHED_RR

ラウンドロビン型のスケジューリングポリシーです。
@end deffn

@geindex SCHED_RESET_ON_FORK (os モジュール)
@anchor{library/os os SCHED_RESET_ON_FORK}@anchor{30fb}
@deffn {データ} os.SCHED_RESET_ON_FORK

このフラグは他のスケジューリングポリシーとともに論理和指定できます。このフラグが与えられたプロセスが fork されると、その子プロセスのスケジューリングポリシーおよび優先度はデフォルトにリセットされます。
@end deffn

@geindex sched_param (os のクラス)
@anchor{library/os os sched_param}@anchor{1910}
@deffn {クラス} os.sched_param (sched_priority)

このクラスは、@ref{1327,,sched_setparam()}、@ref{1328,,sched_setscheduler()}、および @ref{1323,,sched_getparam()} で使用される、調節可能なスケジューリングパラメーターを表します。これはイミュータブルです。

現在、一つの引数のみ指定できます:

@geindex sched_priority (os.sched_param の属性)
@anchor{library/os os sched_param sched_priority}@anchor{30fc}
@deffn {の属性} sched_priority

スケジューリングポリシーのスケジューリング優先度です。
@end deffn
@end deffn

@geindex sched_get_priority_min() (os モジュール)
@anchor{library/os os sched_get_priority_min}@anchor{1321}
@deffn {の関数} os.sched_get_priority_min (policy)

`policy' の最小優先度値を取得します。`policy' には上記のスケジューリングポリシー定数の一つを指定します。
@end deffn

@geindex sched_get_priority_max() (os モジュール)
@anchor{library/os os sched_get_priority_max}@anchor{1320}
@deffn {の関数} os.sched_get_priority_max (policy)

`policy' の最大優先度値を取得します。`policy' には上記のスケジューリングポリシー定数の一つを指定します。
@end deffn

@geindex sched_setscheduler() (os モジュール)
@anchor{library/os os sched_setscheduler}@anchor{1328}
@deffn {の関数} os.sched_setscheduler (pid, policy, param, /)

PID `pid' のプロセスのスケジューリングポリシーを設定します。`pid' が 0 の場合、呼び出しプロセスを意味します。`policy' には上記のスケジューリングポリシー定数の一つを指定します。`param' は @ref{1910,,sched_param} のインスタンスです。
@end deffn

@geindex sched_getscheduler() (os モジュール)
@anchor{library/os os sched_getscheduler}@anchor{1324}
@deffn {の関数} os.sched_getscheduler (pid, /)

PID `pid' のプロセスのスケジューリングポリシーを返します。`pid' が 0 の場合、呼び出しプロセスを意味します。返り値は上記のスケジューリングポリシー定数の一つになります。
@end deffn

@geindex sched_setparam() (os モジュール)
@anchor{library/os os sched_setparam}@anchor{1327}
@deffn {の関数} os.sched_setparam (pid, param, /)

PID `pid' を持つプロセスのスケジューリングパラメータを設定します。 `pid' を 0 とした場合呼び出しプロセスを意味します。 `param' は @ref{1910,,sched_param} インスタンスです。
@end deffn

@geindex sched_getparam() (os モジュール)
@anchor{library/os os sched_getparam}@anchor{1323}
@deffn {の関数} os.sched_getparam (pid, /)

PID `pid' のプロセスのスケジューリングパラメーターを @ref{1910,,sched_param} のインスタンスとして返します。`pid' が 0 の場合、呼び出しプロセスを意味します。
@end deffn

@geindex sched_rr_get_interval() (os モジュール)
@anchor{library/os os sched_rr_get_interval}@anchor{1325}
@deffn {の関数} os.sched_rr_get_interval (pid, /)

PID `pid' のプロセスのラウンドロビンクォンタム (秒) を返します。`pid' が 0 の場合、呼び出しプロセスを意味します。
@end deffn

@geindex sched_yield() (os モジュール)
@anchor{library/os os sched_yield}@anchor{1329}
@deffn {の関数} os.sched_yield ()

Voluntarily relinquish the CPU. See @code{sched_yield(2)@footnote{https://manpages.debian.org/sched_yield(2)}} for details.
@end deffn

@geindex sched_setaffinity() (os モジュール)
@anchor{library/os os sched_setaffinity}@anchor{1326}
@deffn {の関数} os.sched_setaffinity (pid, mask, /)

PID `pid' のプロセス (0 であれば現在のプロセス) を CPU の集合に制限します。`mask' はプロセスを制限する CPU の集合を表す整数のイテラブルなオブジェクトです。
@end deffn

@geindex sched_getaffinity() (os モジュール)
@anchor{library/os os sched_getaffinity}@anchor{1322}
@deffn {の関数} os.sched_getaffinity (pid, /)

Return the set of CPUs the process with PID `pid' is restricted to.

If `pid' is zero, return the set of CPUs the calling thread of the current
process is restricted to.

See also the @ref{4da,,process_cpu_count()} function.
@end deffn

@node 雑多なシステム情報,乱数<2>,スケジューラーへのインターフェイス,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os miscellaneous-system-information}@anchor{30fd}@anchor{library/os os-path}@anchor{30fe}
@subsubsection 雑多なシステム情報


@geindex confstr() (os モジュール)
@anchor{library/os os confstr}@anchor{18ec}
@deffn {の関数} os.confstr (name, /)

システム設定値を文字列で返します。 `name' には取得したい設定名を指定します ; この値は定義済みのシステム値名を表す文字列にすることができます ; 名前は多くの標準 (POSIX.1 、 Unix 95 、 Unix 98 その他 ) で定義されています。ホストオペレーティングシステムの関知する名前は @code{confstr_names} 辞書のキーとして与えられています。このマップ型オブジェクトに入っていない設定変数については、 `name' に整数を渡してもかまいません。

`name' に指定された設定値が定義されていない場合、 @code{None} を返します。

`name' が文字列で、かつ不明の場合、 @ref{2ec,,ValueError} を送出します。 `name' の指定値がホストシステムでサポートされておらず、 @code{confstr_names} にも入っていない場合、 @ref{1dd2,,errno.EINVAL} をエラー番号として @ref{2c0,,OSError} を送出します。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex confstr_names (os モジュール)
@anchor{library/os os confstr_names}@anchor{30ff}
@deffn {データ} os.confstr_names

@ref{18ec,,confstr()} が受理する名前を、ホストオペレーティングシステムで定義されている整数値に対応付けている辞書です。この辞書はシステムでどの設定名が定義されているかを決定するために利用できます。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex cpu_count() (os モジュール)
@anchor{library/os os cpu_count}@anchor{4db}
@deffn {の関数} os.cpu_count ()

Return the number of logical CPUs in the `system'. Returns @code{None} if
undetermined.

The @ref{4da,,process_cpu_count()} function can be used to get the number of
logical CPUs usable by the calling thread of the `current process'.


Added in version 3.4.



バージョン 3.13 で変更: If @ref{16f,,-X cpu_count} is given or 
@geindex PYTHON_CPU_COUNT
@geindex 環境変数; PYTHON_CPU_COUNT
@ref{51e,,PYTHON_CPU_COUNT} is set,
@ref{4db,,cpu_count()} returns the override value `n'.

@end deffn

@geindex getloadavg() (os モジュール)
@anchor{library/os os getloadavg}@anchor{1925}
@deffn {の関数} os.getloadavg ()

過去 1 分、 5 分、および 15 分間の、システムの実行キューの平均プロセス数を返します。平均負荷が得られない場合には @ref{2c0,,OSError} を送出します。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex process_cpu_count() (os モジュール)
@anchor{library/os os process_cpu_count}@anchor{4da}
@deffn {の関数} os.process_cpu_count ()

Get the number of logical CPUs usable by the calling thread of the `current
process'. Returns @code{None} if undetermined. It can be less than
@ref{4db,,cpu_count()} depending on the CPU affinity.

The @ref{4db,,cpu_count()} function can be used to get the number of logical CPUs
in the `system'.

If @ref{16f,,-X cpu_count} is given or 
@geindex PYTHON_CPU_COUNT
@geindex 環境変数; PYTHON_CPU_COUNT
@ref{51e,,PYTHON_CPU_COUNT} is set,
@ref{4da,,process_cpu_count()} returns the override value `n'.

See also the @ref{1322,,sched_getaffinity()} function.


Added in version 3.13.

@end deffn

@geindex sysconf() (os モジュール)
@anchor{library/os os sysconf}@anchor{18ed}
@deffn {の関数} os.sysconf (name, /)

整数値のシステム設定値を返します。 `name' で指定された設定値が定義されていない場合、 @code{-1} が返されます。 `name' に関するコメントとしては、 @ref{18ec,,confstr()} で述べた内容が同様に当てはまります ; 既知の設定名についての情報を与える辞書は @code{sysconf_names} で与えられています。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex sysconf_names (os モジュール)
@anchor{library/os os sysconf_names}@anchor{3100}
@deffn {データ} os.sysconf_names

@ref{18ed,,sysconf()} が受理する名前を、ホストオペレーティングシステムで定義されている整数値に対応付けている辞書です。この辞書はシステムでどの設定名が定義されているかを決定するために利用できます。

@ref{213f,,Availability}: Unix.


バージョン 3.11 で変更: Add @code{'SC_MINSIGSTKSZ'} name.

@end deffn

以下のデータ値はパス名編集操作をサポートするために利用されます。これらの値はすべてのプラットフォームで定義されています。

パス名に対する高水準の操作は @ref{a6,,os.path} モジュールで定義されています。

@geindex . (ドット);in pathnames

@geindex curdir (os モジュール)
@anchor{library/os os curdir}@anchor{2c57}
@deffn {データ} os.curdir

現在のディレクトリ参照するためにオペレーティングシステムで使われる文字列定数です。 POSIX と Windows では @code{'.'} になります。 @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex ..;in pathnames

@geindex pardir (os モジュール)
@anchor{library/os os pardir}@anchor{307d}
@deffn {データ} os.pardir

親ディレクトリを参照するためにオペレーティングシステムで使われる文字列定数です。 POSIX と Windows では @code{'..'} になります。 @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex / (スラッシュ);in pathnames

@geindex \ (backslash);in pathnames (Windows)

@geindex sep (os モジュール)
@anchor{library/os os sep}@anchor{87a}
@deffn {データ} os.sep

パス名を要素に分割するためにオペレーティングシステムで利用されている文字です。例えば POSIX では @code{'/'} で、 Windows では @code{'\\'} です。しかし、このことを知っているだけではパス名を解析したり、パス名同士を結合したりするには不十分です --- こうした操作には @ref{2c51,,os.path.split()} や @ref{19a9,,os.path.join()} を使用してください --- が、たまに便利なこともあります。 @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex / (スラッシュ);in pathnames

@geindex altsep (os モジュール)
@anchor{library/os os altsep}@anchor{87b}
@deffn {データ} os.altsep

文字パス名を要素に分割する際にオペレーティングシステムで利用されるもう一つの文字で、分割文字が一つしかない場合には @code{None} になります。この値は @code{sep} がバックスラッシュとなっている DOS や Windows システムでは @code{'/'} に設定されています。 @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex . (ドット);in pathnames

@geindex extsep (os モジュール)
@anchor{library/os os extsep}@anchor{3101}
@deffn {データ} os.extsep

ベースのファイル名と拡張子を分ける文字です。例えば、 @code{os.py} であれば @code{'.'} です。 @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex ; (コロン);path separator (POSIX)
@geindex ; (semicolon)

@geindex pathsep (os モジュール)
@anchor{library/os os pathsep}@anchor{2134}
@deffn {データ} os.pathsep

(
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} のような ) サーチパス内の要素を分割するためにオペレーティングシステムが慣習的に用いる文字で、 POSIX における @code{':'} や DOS および Windows における @code{';'} に相当します。 @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex defpath (os モジュール)
@anchor{library/os os defpath}@anchor{1de4}
@deffn {データ} os.defpath

@ref{30b4,,exec*p*} や @ref{31b,,spawn*p*} において、環境変数辞書内に @code{'PATH'} キーがない場合に使われる標準設定のサーチパスです。 @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex linesep (os モジュール)
@anchor{library/os os linesep}@anchor{25dc}
@deffn {データ} os.linesep

現在のプラットフォーム上で行を分割 ( あるいは終端 ) するために用いられている文字列です。この値は例えば POSIX での @code{'\n'} や Mac OS での @code{'\r'} のように、単一の文字にもなりますし、例えば Windows での @code{'\r\n'} のように複数の文字列にもなります。テキストモードで開いたファイルに書き込む時には、 `os.linesep' を利用しないでください。すべてのプラットフォームで、単一の @code{'\n'} を使用してください。
@end deffn

@geindex devnull (os モジュール)
@anchor{library/os os devnull}@anchor{1e14}
@deffn {データ} os.devnull

ヌルデバイスのファイルパスです。例えば POSIX では @code{'/dev/null'} で、 Windows では @code{'nul'} です。この値は @ref{a6,,os.path} からも利用できます。
@end deffn

@geindex RTLD_LAZY (os モジュール)
@geindex RTLD_NOW (os モジュール)
@geindex RTLD_GLOBAL (os モジュール)
@geindex RTLD_LOCAL (os モジュール)
@geindex RTLD_NODELETE (os モジュール)
@geindex RTLD_NOLOAD (os モジュール)
@geindex RTLD_DEEPBIND (os モジュール)
@anchor{library/os os RTLD_LAZY}@anchor{1330}
@deffn {データ} os.RTLD_LAZY
@anchor{library/os os RTLD_NOW}@anchor{1331}
@deffnx {データ} os.RTLD_NOW
@anchor{library/os os RTLD_GLOBAL}@anchor{1332}
@deffnx {データ} os.RTLD_GLOBAL
@anchor{library/os os RTLD_LOCAL}@anchor{1333}
@deffnx {データ} os.RTLD_LOCAL
@anchor{library/os os RTLD_NODELETE}@anchor{1334}
@deffnx {データ} os.RTLD_NODELETE
@anchor{library/os os RTLD_NOLOAD}@anchor{1335}
@deffnx {データ} os.RTLD_NOLOAD
@anchor{library/os os RTLD_DEEPBIND}@anchor{1336}
@deffnx {データ} os.RTLD_DEEPBIND

@ref{1337,,setdlopenflags()} 関数と @ref{1727,,getdlopenflags()} 関数と一緒に使用するフラグ。それぞれのフラグの意味については、Unix マニュアルの @code{dlopen(3)@footnote{https://manpages.debian.org/dlopen(3)}} ページを参照してください。


Added in version 3.3.

@end deffn

@node 乱数<2>,,雑多なシステム情報,os --- 雑多なオペレーティングシステムインターフェース
@anchor{library/os random-numbers}@anchor{3102}
@subsubsection 乱数


@geindex getrandom() (os モジュール)
@anchor{library/os os getrandom}@anchor{eb9}
@deffn {の関数} os.getrandom (size, flags=0)

最大で `size' バイトからなるランダムなバイト列を返します。この関数は要求されたバイト数よりも少ないバイト数を返すことがあります。

バイト列は、ユーザー空間の乱数生成器や暗号目的ののシードとして利用できます。

@code{getrandom()} はデバイスドライバや他の環境ノイズ源から収集されたエントロピーに頼っています。不必要な大量のデータの読出しは、@code{/dev/random} と @code{/dev/urandom} デバイスの他のユーザーに負の影響を与えるでしょう。

The flags argument is a bit mask that can contain zero or more of the
following values ORed together: @ref{3103,,os.GRND_RANDOM} and
@ref{3104,,GRND_NONBLOCK}.

Linux getrandom() manual page@footnote{https://man7.org/linux/man-pages/man2/getrandom.2.html} も参照してください。

@ref{213f,,Availability}: Linux >= 3.17.


Added in version 3.6.

@end deffn

@geindex urandom() (os モジュール)
@anchor{library/os os urandom}@anchor{746}
@deffn {の関数} os.urandom (size, /)

暗号に関する用途に適した `size' バイトからなるランダムなバイト文字列を返します。

この関数は OS 固有の乱数発生源からランダムなバイト列を生成して返します。この関数の返すデータは暗号を用いたアプリケーションで十分利用できる程度に予測不能ですが、実際のクオリティは OS の実装によって異なります。

Linux では、 @code{getrandom()} システムコールが利用可能ならブロッキングモードで呼び出されます: すなわちシステムの urandom エントロピープールが初期化されるまで (128 ビットのエントロピーがカーネルにより収集されるまで) 処理がブロックされます。論拠については 
@geindex Python Enhancement Proposals; PEP 524
PEP 524@footnote{https://peps.python.org/pep-0524/} を参照してください。 Linux では、 (@ref{3104,,GRND_NONBLOCK} フラグを使って) 非ブロッキングモードでランダムなバイトを取得したり、システムの urandom エントロピープールが初期化されるまでポーリングするために @ref{eb9,,getrandom()} 関数を利用することができます。

Unix ライクなシステムでは、ランダムなバイトは @code{/dev/urandom} デバイスから読み込みます。 @code{/dev/urandom} デバイスが利用できないか、もしくは読み取り不可のときは、 @ref{36b,,NotImplementedError} 例外が送出されます。

Windowsで、 @code{BCryptGenRandom()} を使用します。


@subsubheading 参考


@ref{c5,,secrets} モジュールは高レベルの乱数生成機能を提供します。プラットフォームが提供する乱数生成器に対する簡便なインターフェースについては、 @ref{2b57,,random.SystemRandom} を参照してください。



バージョン 3.5 で変更: Linux 3.17 以降では、使用可能な場合に @code{getrandom()}  システムコールが使用されるようになりました。OpenBSD 5.6 以降では、C @code{getentropy()} 関数が使用されるようになりました。これらの関数は、内部ファイル記述子を使用しません。



バージョン 3.5.2 で変更: Linux において、 @code{getrandom()} システムコールがブロックするなら (urandom エントロピープールが初期化されていなければ) 、 @code{/dev/urandom} を読む方法にフォールバックします。



バージョン 3.6 で変更: Linuxで、 セキュリティを高めるために、@code{getrandom()} をブロッキングモードで使用するようになりました。



バージョン 3.11 で変更: On Windows, @code{BCryptGenRandom()} is used instead of @code{CryptGenRandom()}
which is deprecated.

@end deffn

@geindex GRND_NONBLOCK (os モジュール)
@anchor{library/os os GRND_NONBLOCK}@anchor{3104}
@deffn {データ} os.GRND_NONBLOCK

デフォルトでは、@ref{eb9,,getrandom()} は @code{/dev/random} から読み込んだときにランダムなバイトが存在しない場合や、 @code{/dev/urandom} から読み込んだときにエントロピープールが初期化されていない場合に処理をブロックします。

@ref{3104,,GRND_NONBLOCK} フラグがセットされると、 @ref{eb9,,getrandom()} はこれらの場合に処理をブロックせず、ただちに @ref{235,,BlockingIOError} 例外を送出します。


Added in version 3.6.

@end deffn

@geindex GRND_RANDOM (os モジュール)
@anchor{library/os os GRND_RANDOM}@anchor{3103}
@deffn {データ} os.GRND_RANDOM

このビットがセットされた場合、 ランダムバイトは @code{/dev/urandom} プールの代わりに  @code{/dev/random} プールから取り出されます。


Added in version 3.6.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node io --- ストリームを扱うコアツール,time --- 時刻データへのアクセスと変換,os --- 雑多なオペレーティングシステムインターフェース,汎用オペレーティングシステムサービス
@anchor{library/io doc}@anchor{3105}@anchor{library/io io-core-tools-for-working-with-streams}@anchor{3106}@anchor{library/io module-io}@anchor{83}@anchor{library/io translation-repo}@anchor{3107}
@subsection @code{io} --- ストリームを扱うコアツール


@geindex module; io

`ソースコード:' Lib/io.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/io.py}


__________________________________________________________________


@menu
* 概要: 概要<2>. 
* Text Encoding:: 
* 高水準のモジュールインターフェイス:: 
* クラス階層:: 
* Static Typing:: 
* 性能: 性能<3>. 

@end menu

@node 概要<2>,Text Encoding,,io --- ストリームを扱うコアツール
@anchor{library/io io-overview}@anchor{25da}@anchor{library/io overview}@anchor{3108}
@subsubsection 概要


@geindex file object;io module

The @code{io} module provides Python's main facilities for dealing with various
types of I/O.  There are three main types of I/O: `text I/O', `binary I/O'
and `raw I/O'.  These are generic categories, and various backing stores can
be used for each of them.  A concrete object belonging to any of these
categories is called a @ref{13db,,file object}.  Other common terms are `stream'
and `file-like object'.

それぞれの具象ストリームオブジェクトは、カテゴリに応じた機能を持ちます。ストリームは読み込み専用、書き込み専用、読み書き可能のいずかになります。任意のランダムアクセス（前方、後方の任意の場所にシークする）が可能かもしれませんし、シーケンシャルアクセスしかできないかもしれません（例えばソケットやパイプなど）。

All streams are careful about the type of data you give to them.  For example
giving a @ref{169,,str} object to the @code{write()} method of a binary stream
will raise a @ref{198,,TypeError}.  So will giving a @ref{192,,bytes} object to the
@code{write()} method of a text stream.


バージョン 3.3 で変更: 以前 @ref{125e,,IOError} を送出していた操作が @ref{2c0,,OSError} を送出するようになりました。 @ref{125e,,IOError} は今は @ref{2c0,,OSError} の別名です。


@menu
* テキスト I/O:: 
* バイナリ I/O:: 
* Raw I/O:: 

@end menu

@node テキスト I/O,バイナリ I/O,,概要<2>
@anchor{library/io text-i-o}@anchor{3109}
@subsubsection テキスト I/O


テキスト I/O は、 @ref{169,,str} オブジェクトを受け取り、生成します。すなわち、背後にあるストレージがバイト列 (例えばファイルなど) を格納するときは常に、透過的にデータのエンコード・デコードを行ない、オプションでプラットフォーム依存の改行文字変換を行います。

テキストストリームを作る一番簡単な方法は、オプションでエンコーディングを指定して、 @ref{316,,open()} を利用することです:

@example
f = open("myfile.txt", "r", encoding="utf-8")
@end example

@ref{112a,,StringIO} オブジェクトはインメモリーのテキストストリームです:

@example
f = io.StringIO("some initial text data")
@end example

@cartouche
@quotation 注釈 
When working with a non-blocking stream, be aware that read operations on text I/O objects
might raise a @ref{235,,BlockingIOError} if the stream cannot perform the operation
immediately.
@end quotation
@end cartouche

テキストストリームの API は @ref{8a4,,TextIOBase} のドキュメントで詳しく解説します。

@node バイナリ I/O,Raw I/O,テキスト I/O,概要<2>
@anchor{library/io binary-i-o}@anchor{310a}
@subsubsection バイナリ I/O


バイナリー I/O (`buffered I/O' とも呼ばれます) は @ref{193,,bytes-like オブジェクト} を受け取り @ref{192,,bytes} オブジェクトを生成します。エンコード、デコード、改行文字変換は一切行いません。このカテゴリのストリームは全ての非テキストデータや、テキストデータの扱いを手動で管理したい場合に利用することができます。

バイナリーストリームを生成する一番簡単な方法は、 @ref{316,,open()} の mode 文字列に @code{'b'} を指定することです:

@example
f = open("myfile.jpg", "rb")
@end example

@ref{10a4,,BytesIO} はインメモリーのバイナリストリームです:

@example
f = io.BytesIO(b"some initial binary data: \x00\x01")
@end example

バイナリーストリーム API は @ref{8a3,,BufferedIOBase} のドキュメントで詳しく解説します。

他のライブラリモジュールが、別のテキスト・バイナリーストリームを生成する方法を提供しています。例えば @ref{13b7,,socket.socket.makefile()} などです。

@node Raw I/O,,バイナリ I/O,概要<2>
@anchor{library/io raw-i-o}@anchor{310b}
@subsubsection Raw I/O


Raw I/O (`unbuffered I/O' とも呼ばれます) は、バイナリーストリームやテキストストリームの低水準の部品としてよく利用されます。ユーザーコードで直接 raw ストリームを扱うべき場面は滅多にありません。とはいえ、バッファリングを無効にしてファイルをバイナリーモードで開くことで raw ストリームを作ることができます:

@example
f = open("myfile.jpg", "rb", buffering=0)
@end example

raw ストリーム API は @ref{12e7,,RawIOBase} のドキュメントで詳しく解説します。

@node Text Encoding,高水準のモジュールインターフェイス,概要<2>,io --- ストリームを扱うコアツール
@anchor{library/io io-text-encoding}@anchor{9c0}@anchor{library/io text-encoding}@anchor{310c}
@subsubsection Text Encoding


The default encoding of @ref{9be,,TextIOWrapper} and @ref{316,,open()} is
locale-specific (@ref{329,,locale.getencoding()}).

However, many developers forget to specify the encoding when opening text files
encoded in UTF-8 (e.g. JSON, TOML, Markdown, etc...) since most Unix
platforms use UTF-8 locale by default. This causes bugs because the locale
encoding is not UTF-8 for most Windows users. For example:

@example
# May not work on Windows when non-ASCII characters in the file.
with open("README.md") as f:
    long_description = f.read()
@end example

Accordingly, it is highly recommended that you specify the encoding
explicitly when opening text files. If you want to use UTF-8, pass
@code{encoding="utf-8"}. To use the current locale encoding,
@code{encoding="locale"} is supported since Python 3.10.


@subsubheading 参考



@table @asis

@item @ref{866,,Python UTF-8 Mode}

Python UTF-8 Mode can be used to change the default encoding to
UTF-8 from locale-specific encoding.

@geindex Python Enhancement Proposals; PEP 686

@item PEP 686@footnote{https://peps.python.org/pep-0686/}

Python 3.15 will make @ref{866,,Python UTF-8 Mode} default.
@end table


@menu
* Opt-in EncodingWarning:: 

@end menu

@node Opt-in EncodingWarning,,,Text Encoding
@anchor{library/io io-encoding-warning}@anchor{2140}@anchor{library/io opt-in-encodingwarning}@anchor{310d}
@subsubsection Opt-in EncodingWarning



Added in version 3.10: See 
@geindex Python Enhancement Proposals; PEP 597
PEP 597@footnote{https://peps.python.org/pep-0597/} for more details.


To find where the default locale encoding is used, you can enable
the @ref{16f,,-X warn_default_encoding} command line option or set the
@geindex PYTHONWARNDEFAULTENCODING
@geindex 環境変数; PYTHONWARNDEFAULTENCODING
@ref{9bf,,PYTHONWARNDEFAULTENCODING} environment variable, which will
emit an @ref{212e,,EncodingWarning} when the default encoding is used.

If you are providing an API that uses @ref{316,,open()} or
@ref{9be,,TextIOWrapper} and passes @code{encoding=None} as a parameter, you
can use @ref{1a3c,,text_encoding()} so that callers of the API will emit an
@ref{212e,,EncodingWarning} if they don't pass an @code{encoding}. However,
please consider using UTF-8 by default (i.e. @code{encoding="utf-8"}) for
new APIs.

@node 高水準のモジュールインターフェイス,クラス階層,Text Encoding,io --- ストリームを扱うコアツール
@anchor{library/io high-level-module-interface}@anchor{310e}
@subsubsection 高水準のモジュールインターフェイス


@geindex DEFAULT_BUFFER_SIZE (io モジュール)
@anchor{library/io io DEFAULT_BUFFER_SIZE}@anchor{1a3d}
@deffn {データ} io.DEFAULT_BUFFER_SIZE

このモジュールの buffered I/O クラスで利用されるデフォルトのバッファーサイズを表す整数です。可能であれば、@ref{316,,open()} は file の blksize (@ref{26d,,os.stat()} で取得される) を利用します。
@end deffn

@geindex open() (io モジュール)
@anchor{library/io io open}@anchor{740}
@deffn {の関数} io.open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

組み込みの @ref{316,,open()} 関数のエイリアスです。


This function raises an @ref{1c6e,,auditing event} @code{open} with
arguments `path', `mode' and `flags'. The `mode' and `flags'
arguments may have been modified or inferred from the original call.

@end deffn

@geindex open_code() (io モジュール)
@anchor{library/io io open_code}@anchor{1a98}
@deffn {の関数} io.open_code (path)

@code{'rb'} モードでファイルを開きます。この関数はファイルの中身を実行可能なコードとして扱いたい場合にのみ使用します。

`path' should be a @ref{169,,str} and an absolute path.

The behavior of this function may be overridden by an earlier call to the
@ref{1a9a,,PyFile_SetOpenCodeHook()}. However, assuming that `path' is a
@ref{169,,str} and an absolute path, @code{open_code(path)} should always behave
the same as @code{open(path, 'rb')}. Overriding the behavior is intended for
additional validation or preprocessing of the file.


Added in version 3.8.

@end deffn

@geindex text_encoding() (io モジュール)
@anchor{library/io io text_encoding}@anchor{1a3c}
@deffn {の関数} io.text_encoding (encoding, stacklevel=2, /)

This is a helper function for callables that use @ref{316,,open()} or
@ref{9be,,TextIOWrapper} and have an @code{encoding=None} parameter.

This function returns `encoding' if it is not @code{None}.
Otherwise, it returns @code{"locale"} or @code{"utf-8"} depending on
@ref{866,,UTF-8 Mode}.

This function emits an @ref{212e,,EncodingWarning} if
@ref{89c,,sys.flags.warn_default_encoding} is true and `encoding'
is @code{None}. `stacklevel' specifies where the warning is emitted.
For example:

@example
def read_text(path, encoding=None):
    encoding = io.text_encoding(encoding)  # stacklevel=2
    with open(path, encoding) as f:
        return f.read()
@end example

In this example, an @ref{212e,,EncodingWarning} is emitted for the caller of
@code{read_text()}.

See @ref{9c0,,Text Encoding} for more information.


Added in version 3.10.



バージョン 3.11 で変更: @ref{1a3c,,text_encoding()} returns "utf-8" when UTF-8 mode is enabled and
`encoding' is @code{None}.

@end deffn

@geindex BlockingIOError
@anchor{library/io io BlockingIOError}@anchor{310f}
@deffn {例外} io.BlockingIOError

互換性のための、組み込みの @ref{235,,BlockingIOError} 例外のエイリアスです。
@end deffn

@geindex UnsupportedOperation
@anchor{library/io io UnsupportedOperation}@anchor{1d7f}
@deffn {例外} io.UnsupportedOperation

@ref{2c0,,OSError} と @ref{2ec,,ValueError} を継承した例外です。ストリームがサポートしていない操作を行おうとした時に送出されます。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{df,,sys}

標準 IO ストリームを持っています: @ref{75f,,sys.stdin}, @ref{ccd,,sys.stdout}, @ref{b33,,sys.stderr}。
@end table


@node クラス階層,Static Typing,高水準のモジュールインターフェイス,io --- ストリームを扱うコアツール
@anchor{library/io class-hierarchy}@anchor{3110}
@subsubsection クラス階層


I/O ストリームの実装はクラス階層に分けて整理されています。まずストリームのカテゴリを分類するための @ref{13ce,,抽象基底クラス} (ABC) があり、続いて標準のストリーム実装を行う具象クラス群があります。

@cartouche
@quotation 注釈 
The abstract base classes also provide default implementations of some
methods in order to help implementation of concrete stream classes.  For
example, @ref{8a3,,BufferedIOBase} provides unoptimized implementations of
@code{readinto()} and @code{readline()}.
@end quotation
@end cartouche

I/O 階層の最上位には抽象基底クラスの @ref{505,,IOBase} があります。 @ref{505,,IOBase} ではストリームに対して基本的なインターフェースを定義しています。 しかしながら、ストリームに対する読み込みと書き込みが分離されていないことに注意してください。 実装においては与えられた操作をサポートしない場合は @ref{1d7f,,UnsupportedOperation} を送出することが許されています。

@ref{12e7,,RawIOBase} ABC は @ref{505,,IOBase} を拡張します。このクラスはストリームからの bytes の読み書きを扱います。 @ref{1527,,FileIO} は、 @ref{12e7,,RawIOBase} を継承してマシンのファイルシステム中のファイルへのインターフェースを提供します。

The @ref{8a3,,BufferedIOBase} ABC extends @ref{505,,IOBase}.  It deals with
buffering on a raw binary stream (@ref{12e7,,RawIOBase}).  Its subclasses,
@ref{15cb,,BufferedWriter}, @ref{1427,,BufferedReader}, and @ref{15cd,,BufferedRWPair}
buffer raw binary streams that are writable, readable, and both readable and writable,
respectively. @ref{15cc,,BufferedRandom} provides a buffered interface to seekable streams.
Another @ref{8a3,,BufferedIOBase} subclass, @ref{10a4,,BytesIO}, is a stream of
in-memory bytes.

@ref{8a4,,TextIOBase} ABC は @ref{505,,IOBase} を拡張します。このクラスはテキストをあらわすバイトストリームを対象とし、バイトデータと文字列の間のエンコーディングやデコーディングを適切に行います。 @ref{9be,,TextIOWrapper} は @ref{8a4,,TextIOBase} を拡張し、バッファリングされた生のストリーム (@ref{8a3,,BufferedIOBase}) に対するバッファリングされたテキストのインターフェースです。最後に、 @ref{112a,,StringIO} はメモリ上のテキストデータに対するストリームです。

引数名は規約に含まれていません。 そして @ref{316,,open()} の引数だけがキーワード引数として用いられることが意図されています。

The following table summarizes the ABCs provided by the @code{io} module:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ABC

@tab

継承元

@tab

スタブメソッド

@tab

Mixin するメソッドとプロパティ

@item

@ref{505,,IOBase}

@tab

@tab

@code{fileno}, @code{seek}, @code{truncate}

@tab

@code{close}, @code{closed}, @code{__enter__}, @code{__exit__}, @code{flush}, @code{isatty}, @code{__iter__}, @code{__next__}, @code{readable}, @code{readline}, @code{readlines}, @code{seekable}, @code{tell}, @code{writable}, @code{writelines}

@item

@ref{12e7,,RawIOBase}

@tab

@ref{505,,IOBase}

@tab

@code{readinto}, @code{write}

@tab

@ref{505,,IOBase} から継承したメソッド、 @code{read}, @code{readall}

@item

@ref{8a3,,BufferedIOBase}

@tab

@ref{505,,IOBase}

@tab

@code{detach}, @code{read}, @code{read1}, @code{write}

@tab

@ref{505,,IOBase} から継承したメソッド、 @code{readinto}, @code{readinto1}

@item

@ref{8a4,,TextIOBase}

@tab

@ref{505,,IOBase}

@tab

@code{detach}, @code{read}, @code{readline}, @code{write}

@tab

@ref{505,,IOBase} から継承したメソッド、 @code{encoding}, @code{errors}, @code{newlines}

@end multitable


@menu
* I/O 基底クラス:: 
* 生ファイルI/O:: 
* バッファ付きストリーム:: 
* テキスト I/O: テキスト I/O<2>. 

@end menu

@node I/O 基底クラス,生ファイルI/O,,クラス階層
@anchor{library/io i-o-base-classes}@anchor{3111}
@subsubsection I/O 基底クラス


@geindex IOBase (io のクラス)
@anchor{library/io io IOBase}@anchor{505}
@deffn {クラス} io.IOBase

The abstract base class for all I/O classes.

継承先のクラスが選択的にオーバライドできるように、このクラスは多くのメソッドに空の抽象実装をしています。デフォルトの実装では、読み込み、書き込み、シークができないファイルを表現します。

Even though @ref{505,,IOBase} does not declare @code{read()}
or @code{write()} because their signatures will vary, implementations and
clients should consider those methods part of the interface.  Also,
implementations may raise a @ref{2ec,,ValueError} (or @ref{1d7f,,UnsupportedOperation})
when operations they do not support are called.

ファイルへのバイナリデータの読み書きに用いられる基本型は @ref{192,,bytes} です。
他の @ref{193,,bytes-like オブジェクト} もメソッドの引数として受け付けられます。
テキスト I/O クラスは @ref{169,,str} データを扱います。

閉じられたストリームに対するメソッド呼び出しは (問い合わせであっても) 未定義です。この場合、実装は @ref{2ec,,ValueError} を送出することがあります。

@ref{505,,IOBase} (とそのサブクラス) はイテレータプロトコルをサポートします。 @ref{505,,IOBase} オブジェクトをイテレートすると、ストリーム内の行が yield されます。ストリーム内の行の定義は、そのストリームが (バイト列を yield する) バイナリストリームか (文字列を yield する) テキストストリームかによって、 少し異なります。下の @ref{1541,,readline()} を参照してください。

@ref{505,,IOBase} はコンテキストマネージャでもあります。そのため @ref{186,,with} 構文をサポートします。 次の例では、 @code{with} 構文が終わった後で---たとえ例外が発生した場合でも、 `file' は閉じられます。

@example
with open('spam.txt', 'w') as file:
    file.write('Spam and eggs!')
@end example

@ref{505,,IOBase} は以下のデータ属性とメソッドを提供します:

@geindex close() (io.IOBase のメソッド)
@anchor{library/io io IOBase close}@anchor{506}
@deffn {メソッド} close ()

このストリームをフラッシュして閉じます。このメソッドはファイルが既に閉じられていた場合は特に何の効果もありません。いったんファイルが閉じられると、すべてのファイルに対する操作 (例えば読み込みや書き込み) で @ref{2ec,,ValueError} が発生します。

利便性のためにこのメソッドを複数回呼ぶことは許されています。しかし、効果があるのは最初の1回だけです。
@end deffn

@geindex closed (io.IOBase の属性)
@anchor{library/io io IOBase closed}@anchor{1e0e}
@deffn {の属性} closed

ストリームが閉じられていた場合 @code{True} になります。
@end deffn

@geindex fileno() (io.IOBase のメソッド)
@anchor{library/io io IOBase fileno}@anchor{17ad}
@deffn {メソッド} fileno ()

ストリームが保持しているファイル記述子 (整数値) が存在する場合はそれを返します。もし IO オブジェクトがファイル記述子を使っていない場合は @ref{2c0,,OSError} が発生します。
@end deffn

@geindex flush() (io.IOBase のメソッド)
@anchor{library/io io IOBase flush}@anchor{2ce6}
@deffn {メソッド} flush ()

適用可能であればストリームの書き込みバッファをフラッシュします。読み出し専用や非ブロッキングストリームでは何もしません。
@end deffn

@geindex isatty() (io.IOBase のメソッド)
@anchor{library/io io IOBase isatty}@anchor{2069}
@deffn {メソッド} isatty ()

ストリームが対話的であれば (つまりターミナルや tty デバイスにつながっている場合) @code{True} を返します。
@end deffn

@geindex readable() (io.IOBase のメソッド)
@anchor{library/io io IOBase readable}@anchor{15c7}
@deffn {メソッド} readable ()

Return @code{True} if the stream can be read from.
If @code{False}, @code{read()} will raise @ref{2c0,,OSError}.
@end deffn

@geindex readline() (io.IOBase のメソッド)
@anchor{library/io io IOBase readline}@anchor{1541}
@deffn {メソッド} readline (size=-1, /)

ストリームから 1 行読み込んで返します。もし `size' が指定された場合、最大で `size' バイトが読み込まれます。

バイナリファイルでは行末文字は常に @code{b'\n'} となります。テキストファイルでは、認識される行末文字を選択するために @ref{316,,open()} に対する `newline' 引数が使われます。
@end deffn

@geindex readlines() (io.IOBase のメソッド)
@anchor{library/io io IOBase readlines}@anchor{27a1}
@deffn {メソッド} readlines (hint=-1, /)

ストリームから行のリストを読み込んで返します。 `hint' を指定することで、読み込む行数を制御できます。もし読み込んだすべての行のサイズ (バイト数、もしくは文字数) が `hint' の値を超えた場合、それ以上の行は読み込まれません。

引数 `hint' の値が @code{0} 以下、および  @code{None} の場合は、ヒントがないものとして取り扱われます。

Note that it's already possible to iterate on file objects using @code{for
line in file: ...} without calling @code{file.readlines()}.
@end deffn

@geindex seek() (io.IOBase のメソッド)
@anchor{library/io io IOBase seek}@anchor{14a4}
@deffn {メソッド} seek (offset, whence=os.SEEK_SET, /)

Change the stream position to the given byte `offset',
interpreted relative to the position indicated by `whence',
and return the new absolute position.
Values for `whence' are:


@itemize *

@item 
@ref{14a5,,os.SEEK_SET} or @code{0} -- start of the stream (the default);
`offset' should be zero or positive

@item 
@ref{14a6,,os.SEEK_CUR} or @code{1} -- current stream position;
`offset' may be negative

@item 
@ref{14a7,,os.SEEK_END} or @code{2} -- end of the stream;
`offset' is usually negative
@end itemize


Added in version 3.1: The @code{SEEK_*} constants.



Added in version 3.3: Some operating systems could support additional values, like
@ref{3041,,os.SEEK_HOLE} or @ref{3042,,os.SEEK_DATA}. The valid values
for a file could depend on it being open in text or binary mode.

@end deffn

@geindex seekable() (io.IOBase のメソッド)
@anchor{library/io io IOBase seekable}@anchor{15c9}
@deffn {メソッド} seekable ()

ストリームがランダムアクセスをサポートしている場合、 @code{True} を返します。 @code{False} の場合、 @ref{14a4,,seek()}、 @ref{15c6,,tell()}、 @ref{1528,,truncate()} を使用すると @ref{2c0,,OSError} を発生させます。
@end deffn

@geindex tell() (io.IOBase のメソッド)
@anchor{library/io io IOBase tell}@anchor{15c6}
@deffn {メソッド} tell ()

現在のストリーム位置を返します。
@end deffn

@geindex truncate() (io.IOBase のメソッド)
@anchor{library/io io IOBase truncate}@anchor{1528}
@deffn {メソッド} truncate (size=None, /)

ストリームのサイズを、指定された `size' バイト (または `size' が指定されていない場合、現在位置) に変更します。現在のストリーム位置は変更されません。このサイズ変更により、現在のファイルサイズを拡大または縮小させることができます。拡大の場合には、新しいファイル領域の内容はプラットホームによって異なります (ほとんどのシステムでは、追加のバイトが 0 で埋められます)。新しいファイルサイズが返されます。


バージョン 3.5 で変更: Windows で、拡大時に追加領域を 0 で埋めるようになりました。

@end deffn

@geindex writable() (io.IOBase のメソッド)
@anchor{library/io io IOBase writable}@anchor{15c8}
@deffn {メソッド} writable ()

Return @code{True} if the stream supports writing.  If @code{False},
@code{write()} and @ref{1528,,truncate()} will raise @ref{2c0,,OSError}.
@end deffn

@geindex writelines() (io.IOBase のメソッド)
@anchor{library/io io IOBase writelines}@anchor{177a}
@deffn {メソッド} writelines (lines, /)

ストリームに行のリストを書き込みます。行区切り文字は追加されないので、書き込む各行の行末に行区切り文字を含ませるのが一般的です。
@end deffn

@geindex __del__() (io.IOBase のメソッド)
@anchor{library/io io IOBase __del__}@anchor{3112}
@deffn {メソッド} __del__ ()

オブジェクトの破壊の用意をします。このメソッドはインスタンスの @ref{506,,close()} メソッドを呼びます。 @ref{505,,IOBase} はこのメソッドのデフォルトの実装を提供します
@end deffn
@end deffn

@geindex RawIOBase (io のクラス)
@anchor{library/io io RawIOBase}@anchor{12e7}
@deffn {クラス} io.RawIOBase

Base class for raw binary streams.  It inherits from @ref{505,,IOBase}.

生のバイナリストリームは典型的に、背後にある OS デバイスや API への低水準なアクセスを提供し、それらを高水準の基本要素へカプセル化しようとはしません (そのような機能は後述するバッファされたバイナリストリームやテキストストリームのような高水準のクラスで行われます)。

@ref{12e7,,RawIOBase} は @ref{505,,IOBase} が提供するメソッドに加えて、以下のメソッドを提供します:

@geindex read() (io.RawIOBase のメソッド)
@anchor{library/io io RawIOBase read}@anchor{101d}
@deffn {メソッド} read (size=-1, /)

オブジェクトを `size' バイトまで読み込み、それを返します。
簡単のため、 `size' が指定されていないか -1 の場合は、 EOF までの全てのバイトを返します。
そうでない場合は、システムコール呼び出しが一度だけ行われます。
オペレーティングシステムコールから返ってきたものが `size' バイトより少なければ、 `size' バイトより少ない返り値になることがあります。

`size' が 0 でないのに 0 バイトが返った場合、それはファイルの終端を表します。オブジェクトがノンブロッキングモードで、1 バイトも読み込めなければ、@code{None} が返されます。

デフォルトの実装は @ref{3113,,readall()} と @ref{101e,,readinto()} に従います。
@end deffn

@geindex readall() (io.RawIOBase のメソッド)
@anchor{library/io io RawIOBase readall}@anchor{3113}
@deffn {メソッド} readall ()

EOF までストリームからすべてのバイトを読み込みます。必要な場合はストリームに対して複数の呼び出しをします。
@end deffn

@geindex readinto() (io.RawIOBase のメソッド)
@anchor{library/io io RawIOBase readinto}@anchor{101e}
@deffn {メソッド} readinto (b, /)

あらかじめ確保された書き込み可能な @ref{193,,bytes 類オブジェクト} `b' にバイト列を読み込み、読み込んだバイト数を返します。
例えば、 `b' は @ref{344,,bytearray} です。
オブジェクトがノンブロッキングモードで、 1 バイトも読み込めなければ、 @code{None} が返されます。
@end deffn

@geindex write() (io.RawIOBase のメソッド)
@anchor{library/io io RawIOBase write}@anchor{15c5}
@deffn {メソッド} write (b, /)

与えられた @ref{193,,bytes-like オブジェクト} `b' を生ストリームに書き込み、書き込んだバイト数を返します。これは、根底の生ストリームの性質や、特にノンブロッキングである場合に、 `b' のバイト数より小さくなることがあります。生ストリームがブロックされないように設定されていて、かつ1バイトも即座に書き込むことができなければ、 @code{None} が返されます。このメソッドから返った後で呼び出し元は `b' を解放したり変更したりするかもしれないので、実装はメソッド呼び出しの間だけ `b' にアクセスすべきです。
@end deffn
@end deffn

@geindex BufferedIOBase (io のクラス)
@anchor{library/io io BufferedIOBase}@anchor{8a3}
@deffn {クラス} io.BufferedIOBase

Base class for binary streams that support some kind of buffering.
It inherits from @ref{505,,IOBase}.

The main difference with @ref{12e7,,RawIOBase} is that methods @ref{1540,,read()},
@ref{1895,,readinto()} and @ref{ed7,,write()} will try (respectively) to read
as much input as requested or to emit all provided data.

In addition, if the underlying raw stream is in non-blocking mode, when the
system returns would block @ref{ed7,,write()} will raise @ref{235,,BlockingIOError}
with @ref{2701,,BlockingIOError.characters_written} and @ref{1540,,read()} will return
data read so far or @code{None} if no data is available.

さらに、 @ref{1540,,read()} メソッドは、 @ref{1895,,readinto()} に従うデフォルト実装を持ちません。

通常の @ref{8a3,,BufferedIOBase} 実装は @ref{12e7,,RawIOBase} 実装を継承せずに、 @ref{15cb,,BufferedWriter} と @ref{1427,,BufferedReader} がするようにこれをラップすべきです。

@ref{8a3,,BufferedIOBase} は @ref{505,,IOBase} から継承した属性とメソッドに加えて、以下のデータ属性とメソッドを提供またはオーバーライドします:

@geindex raw (io.BufferedIOBase の属性)
@anchor{library/io io BufferedIOBase raw}@anchor{15ca}
@deffn {の属性} raw

@ref{8a3,,BufferedIOBase} が扱う根底の生ストリーム (@ref{12e7,,RawIOBase} インスタンス) を返します。これは @ref{8a3,,BufferedIOBase} API には含まれず、よって実装に含まれないことがあります。
@end deffn

@geindex detach() (io.BufferedIOBase のメソッド)
@anchor{library/io io BufferedIOBase detach}@anchor{2deb}
@deffn {メソッド} detach ()

根底の生ストリームをバッファから分離して返します。

生ストリームが取り外された後、バッファは使用不能状態になります。

バッファには、 @ref{10a4,,BytesIO} など、このメソッドで返される単体のストリームという概念を持たないものがあります。これらは @ref{1d7f,,UnsupportedOperation} を送出します。


Added in version 3.1.

@end deffn

@geindex read() (io.BufferedIOBase のメソッド)
@anchor{library/io io BufferedIOBase read}@anchor{1540}
@deffn {メソッド} read (size=-1, /)

Read and return up to `size' bytes. If the argument is omitted, @code{None},
or negative read as much as possible.

Fewer bytes may be returned than requested. An empty @ref{192,,bytes} object
is returned if the stream is already at EOF. More than one read may be
made and calls may be retried if specific errors are encountered, see
@ref{f95,,os.read()} and 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} for more details. Less than size bytes
being returned does not imply that EOF is imminent.

When reading as much as possible the default implementation will use
@code{raw.readall} if available (which should implement
@ref{3113,,RawIOBase.readall()}), otherwise will read in a loop until read
returns @code{None}, an empty @ref{192,,bytes}, or a non-retryable error. For
most streams this is to EOF, but for non-blocking streams more data may
become available.

@cartouche
@quotation 注釈 
When the underlying raw stream is non-blocking, implementations may
either raise @ref{235,,BlockingIOError} or return @code{None} if no data is
available. @code{io} implementations return @code{None}.
@end quotation
@end cartouche
@end deffn

@geindex read1() (io.BufferedIOBase のメソッド)
@anchor{library/io io BufferedIOBase read1}@anchor{2e56}
@deffn {メソッド} read1 (size=-1, /)

Read and return up to `size' bytes, calling @ref{101e,,readinto()}
which may retry if @ref{f87,,EINTR} is encountered per
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/}. If `size' is @code{-1} or not provided, the implementation will
choose an arbitrary value for `size'.

@cartouche
@quotation 注釈 
When the underlying raw stream is non-blocking, implementations may
either raise @ref{235,,BlockingIOError} or return @code{None} if no data is
available. @code{io} implementations return @code{None}.
@end quotation
@end cartouche
@end deffn

@geindex readinto() (io.BufferedIOBase のメソッド)
@anchor{library/io io BufferedIOBase readinto}@anchor{1895}
@deffn {メソッド} readinto (b, /)

あらかじめ確保された書き込み可能な @ref{193,,bytes 類オブジェクト} `b' にバイト列を読み込み、読み込んだバイト数を返します。
例えば、 `b' は @ref{344,,bytearray} です。

@ref{1540,,read()} と同様に、下層の raw ストリームが対話的でない限り、複数の読み込みは下層の raw ストリームに与えられるかもしれません。

元になる生ストリームがノンブロッキングモードで、呼び出された時点でデータを持っていなければ、 @ref{235,,BlockingIOError} が送出されます。
@end deffn

@geindex readinto1() (io.BufferedIOBase のメソッド)
@anchor{library/io io BufferedIOBase readinto1}@anchor{101c}
@deffn {メソッド} readinto1 (b, /)

根底の raw ストリームの @ref{101d,,read()} (または @ref{101e,,readinto()}) メソッドを高々 1 回呼び出し、あらかじめ確保された書き込み可能な @ref{193,,bytes-like オブジェクト} `b' にバイト列を読み込みます。読み込んだバイト数を返します。

元になる生ストリームがノンブロッキングモードで、呼び出された時点でデータを持っていなければ、 @ref{235,,BlockingIOError} が送出されます。


Added in version 3.5.

@end deffn

@geindex write() (io.BufferedIOBase のメソッド)
@anchor{library/io io BufferedIOBase write}@anchor{ed7}
@deffn {メソッド} write (b, /)

与えられた @ref{193,,bytes-like オブジェクト} `b' を書き込み、書き込んだバイト数を返します (これは常に `b' のバイト数と等しくなります。なぜなら、もし書き込みに失敗した場合は @ref{2c0,,OSError} が発生するからです)。実際の実装に依存して、これらのバイト列は根底のストリームに即座に書き込まれることもあれば、パフォーマンスやレイテンシの関係でバッファに保持されることもあります。

ノンブロッキングモードであるとき、バッファが満杯で根底の生ストリームが書き込み時点でさらなるデータを受け付けられない場合 @ref{235,,BlockingIOError} が送出されます。

このメソッドが戻った後で、呼び出し元は `b' を解放、または変更するかもしれないので、実装はメソッド呼び出しの間だけ `b' にアクセスすべきです。
@end deffn
@end deffn

@node 生ファイルI/O,バッファ付きストリーム,I/O 基底クラス,クラス階層
@anchor{library/io raw-file-i-o}@anchor{3114}
@subsubsection 生ファイルI/O


@geindex FileIO (io のクラス)
@anchor{library/io io FileIO}@anchor{1527}
@deffn {クラス} io.FileIO (name, mode='r', closefd=True, opener=None)

A raw binary stream representing an OS-level file containing bytes data.  It
inherits from @ref{12e7,,RawIOBase}.

`name' は、次の 2 つのいずれかです。


@itemize *

@item 
開くファイルへのパスを表す文字列または @ref{192,,bytes} オブジェクト。
この場合、closefd は @code{True} (デフォルト) でなければなりません。
@code{True} でない場合、エラーが送出されます。

@item 
結果の @ref{1527,,FileIO} オブジェクトがアクセスを与える、既存の OS レベルファイル記述子の数を表す整数。FileIO オブジェクトが閉じられると、`closefd' が @code{False} に設定されていない場合、この fd も閉じられます。
@end itemize

`mode' は 読み込み（デフォルト）、書き込み、排他的作成、追記に対し @code{'r'} 、 @code{'w'} 、 @code{'x'} 、 @code{'a'} です。ファイルは書き込みや追記で開かれたときに存在しない場合作成されます。書き込みのときにファイルの内容は破棄されます。作成時に既に存在する場合は @ref{1221,,FileExistsError} が送出されます。作成のためにファイルを開くのは暗黙的に書き込みなので、このモードは @code{'w'} と同じように振る舞います。読み込みと書き込みを同時に許可するにはモードに @code{'+'} を加えてください。

The @ref{101d,,read()} (when called with a positive argument),
@ref{101e,,readinto()} and @ref{15c5,,write()} methods on this
class will only make one system call.

呼び出し可能オブジェクトを `opener' として与えることで、カスタムのオープナーが使えます。そしてファイルオブジェクトの基底のファイルディスクリプタは、`opener' を (`name', `flags') で呼び出して得られます。`opener' は開いたファイルディスクリプタを返さなければなりません。 (@ref{f92,,os.open} を `opener' として渡すと、@code{None} を渡したのと同様の機能になります。)

新たに作成されたファイルは @ref{10fc,,継承不可}  です。

`opener' 引数を使う例については @ref{316,,open()} 組み込み関数を参照してください。


バージョン 3.3 で変更: `opener' 引数が追加されました。@code{'x'} モードが追加されました。



バージョン 3.4 で変更: ファイルが継承不可になりました。


@ref{1527,,FileIO} は @ref{12e7,,RawIOBase} と @ref{505,,IOBase} から継承したデータ属性に加えて以下のデータ属性を提供します:

@geindex mode (io.FileIO の属性)
@anchor{library/io io FileIO mode}@anchor{3115}
@deffn {の属性} mode

コンストラクタに渡されたモードです。
@end deffn

@geindex name (io.FileIO の属性)
@anchor{library/io io FileIO name}@anchor{2def}
@deffn {の属性} name

ファイル名。コンストラクタに名前が渡されなかったときはファイル記述子になります。
@end deffn
@end deffn

@node バッファ付きストリーム,テキスト I/O<2>,生ファイルI/O,クラス階層
@anchor{library/io buffered-streams}@anchor{3116}
@subsubsection バッファ付きストリーム


バッファ付き I/O ストリームは、I/O デバイスに生 I/O より高レベルなインターフェースを提供します。

@geindex BytesIO (io のクラス)
@anchor{library/io io BytesIO}@anchor{10a4}
@deffn {クラス} io.BytesIO (initial_bytes=b'@w{'})

A binary stream using an in-memory bytes buffer.  It inherits from
@ref{8a3,,BufferedIOBase}.  The buffer is discarded when the
@ref{506,,close()} method is called.

省略可能な引数 `initial_bytes' は、初期データを含んだ @ref{193,,bytes-like オブジェクト} です。

@ref{10a4,,BytesIO} は @ref{8a3,,BufferedIOBase} または @ref{505,,IOBase} からのメソッドに加えて、以下のメソッドを提供もしくはオーバーライドします:

@geindex getbuffer() (io.BytesIO のメソッド)
@anchor{library/io io BytesIO getbuffer}@anchor{140a}
@deffn {メソッド} getbuffer ()

バッファの内容をコピーすることなく、その内容の上に、読み込み及び書き込みが可能なビューを返します。また、このビューを変更すると、バッファの内容は透過的に更新されます:

@example
>>> b = io.BytesIO(b"abcdef")
>>> view = b.getbuffer()
>>> view[2:4] = b"56"
>>> b.getvalue()
b'ab56ef'
@end example

@cartouche
@quotation 注釈 
ビューが存在する限り、@ref{10a4,,BytesIO} オブジェクトはリサイズやクローズされません。
@end quotation
@end cartouche


Added in version 3.2.

@end deffn

@geindex getvalue() (io.BytesIO のメソッド)
@anchor{library/io io BytesIO getvalue}@anchor{2e54}
@deffn {メソッド} getvalue ()

バッファの全内容を含む @ref{192,,bytes} を返します。
@end deffn

@geindex read1() (io.BytesIO のメソッド)
@anchor{library/io io BytesIO read1}@anchor{3117}
@deffn {メソッド} read1 (size=-1, /)

@ref{10a4,,BytesIO} においては、このメソッドは @ref{1540,,read()} と同じです。


バージョン 3.7 で変更: `size' 引数が任意になりました。

@end deffn

@geindex readinto1() (io.BytesIO のメソッド)
@anchor{library/io io BytesIO readinto1}@anchor{3118}
@deffn {メソッド} readinto1 (b, /)

@ref{10a4,,BytesIO} においては、このメソッドは @ref{1895,,readinto()} と同じです。


Added in version 3.5.

@end deffn
@end deffn

@geindex BufferedReader (io のクラス)
@anchor{library/io io BufferedReader}@anchor{1427}
@deffn {クラス} io.BufferedReader (raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffered binary stream providing higher-level access to a readable, non
seekable @ref{12e7,,RawIOBase} raw binary stream.  It inherits from
@ref{8a3,,BufferedIOBase}.

このオブジェクトからデータを読み出した時、背後にある生のストリームからはより大きな量のデータの読み出しがリクエストされ、内部バッファに読み出したデータが保持されることがあります。バッファされたデータはその後の読み出し処理で直接返すことができます。

このコンストラクタは与えられた `raw' ストリームと `buffer_size' に対し @ref{1427,,BufferedReader} を生成します。 `buffer_size' が省略された場合、代わりに @ref{1a3d,,DEFAULT_BUFFER_SIZE} が使われます。

@ref{1427,,BufferedReader} は @ref{8a3,,BufferedIOBase} または @ref{505,,IOBase} からのメソッドに加えて、以下のメソッドを提供もしくはオーバーライドします:

@geindex peek() (io.BufferedReader のメソッド)
@anchor{library/io io BufferedReader peek}@anchor{3119}
@deffn {メソッド} peek (size=0, /)

Return bytes from the stream without advancing the position. The number of
bytes returned may be less or more than requested. If the underlying raw
stream is non-blocking and the operation would block, returns empty bytes.
@end deffn

@geindex read() (io.BufferedReader のメソッド)
@anchor{library/io io BufferedReader read}@anchor{311a}
@deffn {メソッド} read (size=-1, /)

In @ref{1427,,BufferedReader} this is the same as @ref{1540,,io.BufferedIOBase.read()}
@end deffn

@geindex read1() (io.BufferedReader のメソッド)
@anchor{library/io io BufferedReader read1}@anchor{311b}
@deffn {メソッド} read1 (size=-1, /)

In @ref{1427,,BufferedReader} this is the same as @ref{2e56,,io.BufferedIOBase.read1()}


バージョン 3.7 で変更: `size' 引数が任意になりました。

@end deffn
@end deffn

@geindex BufferedWriter (io のクラス)
@anchor{library/io io BufferedWriter}@anchor{15cb}
@deffn {クラス} io.BufferedWriter (raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffered binary stream providing higher-level access to a writeable, non
seekable @ref{12e7,,RawIOBase} raw binary stream.  It inherits from
@ref{8a3,,BufferedIOBase}.

このオブジェクトに対して書き込みを行なったとき、データは通常内部バッファに配置されます。バッファは以下に示すさまざまな条件で背後にある @ref{12e7,,RawIOBase} オブジェクトに書き込まれます:


@itemize *

@item 
保留中の全データに対してバッファが足りなくなったとき;

@item 
when @ref{311c,,flush()} is called;

@item 
when a @ref{14a4,,seek()} is requested (for @ref{15cc,,BufferedRandom} objects);

@item 
@ref{15cb,,BufferedWriter} オブジェクトが閉じられたり破棄されたりしたとき。
@end itemize

このコンストラクタは与えられた書き込み可能な `raw' ストリームに対し @ref{15cb,,BufferedWriter} を生成します。 `buffer_size' が省略された場合、 @ref{1a3d,,DEFAULT_BUFFER_SIZE} がデフォルトになります。

@ref{15cb,,BufferedWriter} は @ref{8a3,,BufferedIOBase} または @ref{505,,IOBase} からのメソッドに加えて、以下のメソッドを提供もしくはオーバーライドします:

@geindex flush() (io.BufferedWriter のメソッド)
@anchor{library/io io BufferedWriter flush}@anchor{311c}
@deffn {メソッド} flush ()

バッファに保持されたバイト列を生ストリームに強制的に流し込みます。生ストリームがブロックした場合 @ref{235,,BlockingIOError} が送出されます。
@end deffn

@geindex write() (io.BufferedWriter のメソッド)
@anchor{library/io io BufferedWriter write}@anchor{311d}
@deffn {メソッド} write (b, /)

Write the @ref{193,,bytes-like object}, `b', and return the
number of bytes written.  When in non-blocking mode, a
@ref{235,,BlockingIOError} with @ref{2701,,BlockingIOError.characters_written} set
is raised if the buffer needs to be written out but the raw stream blocks.
@end deffn
@end deffn

@geindex BufferedRandom (io のクラス)
@anchor{library/io io BufferedRandom}@anchor{15cc}
@deffn {クラス} io.BufferedRandom (raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffered binary stream providing higher-level access to a seekable
@ref{12e7,,RawIOBase} raw binary stream.  It inherits from @ref{1427,,BufferedReader}
and @ref{15cb,,BufferedWriter}.

このコンストラクタは第一引数として与えられるシーク可能な生ストリームに対し、リーダーおよびライターを作成します。 `buffer_size' が省略された場合、 @ref{1a3d,,DEFAULT_BUFFER_SIZE} がデフォルトになります。

@ref{15cc,,BufferedRandom} is capable of anything @ref{1427,,BufferedReader} or
@ref{15cb,,BufferedWriter} can do.  In addition, @ref{14a4,,seek()} and
@ref{15c6,,tell()} are guaranteed to be implemented.
@end deffn

@geindex BufferedRWPair (io のクラス)
@anchor{library/io io BufferedRWPair}@anchor{15cd}
@deffn {クラス} io.BufferedRWPair (reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, /)

A buffered binary stream providing higher-level access to two non seekable
@ref{12e7,,RawIOBase} raw binary streams---one readable, the other writeable.
It inherits from @ref{8a3,,BufferedIOBase}.

`reader' と `writer' はそれぞれ読み込み可能、書き込み可能な @ref{12e7,,RawIOBase} オブジェクトです。 `buffer_size' が省略された場合 @ref{1a3d,,DEFAULT_BUFFER_SIZE} がデフォルトになります。

@ref{15cd,,BufferedRWPair} は、 @ref{1d7f,,UnsupportedOperation} を送出する @ref{2deb,,detach()} を除く、 @ref{8a3,,BufferedIOBase} の全てのメソッドを実装します。

@cartouche
@quotation 警告 
@ref{15cd,,BufferedRWPair} は下層の生ストリームのアクセスを同期しようとはしません。同じオブジェクトをリーダとライタとして渡してはいけません。その場合は代わりに @ref{15cc,,BufferedRandom} を使用してください。
@end quotation
@end cartouche
@end deffn

@node テキスト I/O<2>,,バッファ付きストリーム,クラス階層
@anchor{library/io id1}@anchor{311e}
@subsubsection テキスト I/O


@geindex TextIOBase (io のクラス)
@anchor{library/io io TextIOBase}@anchor{8a4}
@deffn {クラス} io.TextIOBase

Base class for text streams.  This class provides a character and line based
interface to stream I/O.  It inherits from @ref{505,,IOBase}.

@ref{505,,IOBase} から継承した属性とメソッドに加えて、 @ref{8a4,,TextIOBase} は以下のデータ属性とメソッドを提供しています:

@geindex encoding (io.TextIOBase の属性)
@anchor{library/io io TextIOBase encoding}@anchor{311f}
@deffn {の属性} encoding

エンコーディング名で、ストリームのバイト列を文字列にデコードするとき、また文字列をバイト列にエンコードするときに使われます。
@end deffn

@geindex errors (io.TextIOBase の属性)
@anchor{library/io io TextIOBase errors}@anchor{1526}
@deffn {の属性} errors

このエンコーダやデコーダのエラー設定です。
@end deffn

@geindex newlines (io.TextIOBase の属性)
@anchor{library/io io TextIOBase newlines}@anchor{3120}
@deffn {の属性} newlines

文字列、文字列のタプル、または @code{None} で、改行がどのように読み換えられるかを指定します。実装や内部コンストラクタのフラグに依って、これは利用できないことがあります。
@end deffn

@geindex buffer (io.TextIOBase の属性)
@anchor{library/io io TextIOBase buffer}@anchor{14bb}
@deffn {の属性} buffer

The underlying binary buffer (a @ref{8a3,,BufferedIOBase}
or @ref{12e7,,RawIOBase} instance) that @ref{8a4,,TextIOBase} deals with.
This is not part of the @ref{8a4,,TextIOBase} API and may not exist
in some implementations.
@end deffn

@geindex detach() (io.TextIOBase のメソッド)
@anchor{library/io io TextIOBase detach}@anchor{1781}
@deffn {メソッド} detach ()

根底のバイナリバッファを @ref{8a4,,TextIOBase} から分離して返します。

根底のバッファが取り外された後、 @ref{8a4,,TextIOBase} は使用不能状態になります。

@ref{8a4,,TextIOBase} 実装には、 @ref{112a,,StringIO} など、根底のバッファという概念を持たないものがあります。これらを呼び出すと @ref{1d7f,,UnsupportedOperation} を送出します。


Added in version 3.1.

@end deffn

@geindex read() (io.TextIOBase のメソッド)
@anchor{library/io io TextIOBase read}@anchor{206c}
@deffn {メソッド} read (size=-1, /)

最大 `size' 文字をストリームから読み込み、一つの @ref{169,,str} にして返します。 `size' が負の値または @code{None} ならば、 EOF まで読みます。
@end deffn

@geindex readline() (io.TextIOBase のメソッド)
@anchor{library/io io TextIOBase readline}@anchor{20a6}
@deffn {メソッド} readline (size=-1, /)

Read until newline or EOF and return a single @ref{169,,str}.  If the stream is
already at EOF, an empty string is returned.

`size' が指定された場合、最大 `size' 文字が読み込まれます。
@end deffn

@geindex seek() (io.TextIOBase のメソッド)
@anchor{library/io io TextIOBase seek}@anchor{3121}
@deffn {メソッド} seek (offset, whence=SEEK_SET, /)

Change the stream position to the given `offset'.  Behaviour depends on
the `whence' parameter.  The default value for `whence' is
@code{SEEK_SET}.


@itemize *

@item 
@code{SEEK_SET} or @code{0}: seek from the start of the stream
(the default); `offset' must either be a number returned by
@ref{3122,,TextIOBase.tell()}, or zero.  Any other `offset' value
produces undefined behaviour.

@item 
@code{SEEK_CUR} or @code{1}: "seek" to the current position;
`offset' must be zero, which is a no-operation (all other values
are unsupported).

@item 
@code{SEEK_END} or @code{2}: seek to the end of the stream;
`offset' must be zero (all other values are unsupported).
@end itemize

新しい絶対位置を、不透明な数値で返します。


Added in version 3.1: The @code{SEEK_*} constants.

@end deffn

@geindex tell() (io.TextIOBase のメソッド)
@anchor{library/io io TextIOBase tell}@anchor{3122}
@deffn {メソッド} tell ()

ストリームの現在位置を不透明な数値で返します。この値は根底のバイナリストレージ内でのバイト数を表すとは限りません。
@end deffn

@geindex write() (io.TextIOBase のメソッド)
@anchor{library/io io TextIOBase write}@anchor{205b}
@deffn {メソッド} write (s, /)

文字列 `s' をストリームに書き出し、書き出された文字数を返します。
@end deffn
@end deffn

@geindex TextIOWrapper (io のクラス)
@anchor{library/io io TextIOWrapper}@anchor{9be}
@deffn {クラス} io.TextIOWrapper (buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)

A buffered text stream providing higher-level access to a
@ref{8a3,,BufferedIOBase} buffered binary stream.  It inherits from
@ref{8a4,,TextIOBase}.

`encoding' gives the name of the encoding that the stream will be decoded or
encoded with.  In @ref{866,,UTF-8 Mode}, this defaults to UTF-8.
Otherwise, it defaults to @ref{329,,locale.getencoding()}.
@code{encoding="locale"} can be used to specify the current locale's encoding
explicitly. See @ref{9c0,,Text Encoding} for more information.

`errors' はオプションの文字列で、エンコードやデコードの際のエラーをどのように扱うかを指定します。エンコードエラーがあったときに @ref{2ec,,ValueError} 例外を送出させるには @code{'strict'} を渡します (デフォルトの @code{None} でも同じです)。エラーを無視させるには @code{'ignore'} を渡します。 (エンコーディングエラーを無視するとデータを喪失する可能性があることに注意してください。) @code{'replace'} は不正な形式の文字の代わりにマーカ (たとえば @code{'?'}) を挿入させます。@code{'backslashreplace'} を指定すると、不正な形式のデータをバックスラッシュ付きのエスケープシーケンスに置換します。書き込み時には @code{'xmlcharrefreplace'} (適切な XML 文字参照に置換) や @code{'namereplace'} (@code{\N@{...@}} エスケープシーケンスに置換) も使えます。他にも @ref{16b4,,codecs.register_error()} で登録されたエラー処理名が有効です。

@geindex universal newlines;io.TextIOWrapper class

`newline' は行末をどのように処理するかを制御します 。@code{None}, @code{'@w{'}}, @code{'\n'}, @code{'\r'}, @code{'\r\n'} のいずれかです。これは以下のように動作します:


@itemize *

@item 
ストリームからの入力を読み込んでいるとき、もし `newline' が @code{None} ならば @ref{f35,,universal newlines} モードが有効になります。入力中の行は @code{'\n'}, @code{'\r'}, または @code{'\r\n'} のいずれで終わってもよく、それらは呼び出し元に返される前に`@w{`}'n'`@w{`} に変換されます。 `newline' が @code{'@w{'}} の場合、 universal newlines モードは有効になりますが、行末のコードは変換されずに呼び出し元に返されます。 `newline' がその他の有効な値の場合は、入力行は与えられた文字列のみで終端され、行末は変換されずに呼び出し元に返されます。

@item 
ストリームへの出力の書き込み時、`newline' が @code{None} の場合、全ての @code{'\n'} 文字はシステムのデフォルトの行セパレータ @ref{25dc,,os.linesep} に変換されます。 `newline' が @code{'@w{'}} または @code{'\n'} の場合は変換されません。`newline' がその他の正当な値の場合、全ての @code{'\n'} 文字は与えられた文字列に変換されます。
@end itemize

If `line_buffering' is @code{True}, @ref{2ce6,,flush()} is implied when a call to
write contains a newline character or a carriage return.

If `write_through' is @code{True}, calls to @ref{ed7,,write()} are guaranteed
not to be buffered: any data written on the @ref{9be,,TextIOWrapper}
object is immediately handled to its underlying binary `buffer'.


バージョン 3.3 で変更: `write_through' 引数が追加されました。



バージョン 3.3 で変更: `encoding' の規定値が @code{locale.getpreferredencoding()} から @code{locale.getpreferredencoding(False)} になりました。
@ref{328,,locale.setlocale()} を用いてロケールのエンコーディングを一時的に変更してはいけません。ユーザが望むエンコーディングではなく現在のロケールのエンコーディングを使用してください。



バージョン 3.10 で変更: The `encoding' argument now supports the @code{"locale"} dummy encoding name.


@cartouche
@quotation 注釈 
When the underlying raw stream is non-blocking, a @ref{235,,BlockingIOError}
may be raised if a read operation cannot be completed immediately.
@end quotation
@end cartouche

@ref{9be,,TextIOWrapper} は @ref{8a4,,TextIOBase} と @ref{505,,IOBase} から継承したものに加えて以下のデータ属性をメソッドを提供します:

@geindex line_buffering (io.TextIOWrapper の属性)
@anchor{library/io io TextIOWrapper line_buffering}@anchor{3123}
@deffn {の属性} line_buffering

行バッファリングが有効かどうか。
@end deffn

@geindex write_through (io.TextIOWrapper の属性)
@anchor{library/io io TextIOWrapper write_through}@anchor{3124}
@deffn {の属性} write_through

書き込みが、根柢のバイナリバッファに即座に渡されるかどうか。


Added in version 3.7.

@end deffn

@geindex reconfigure() (io.TextIOWrapper のメソッド)
@anchor{library/io io TextIOWrapper reconfigure}@anchor{d40}
@deffn {メソッド} reconfigure (*, encoding=None, errors=None, newline=None, line_buffering=None, write_through=None)

このテキストストリームを `encoding', `errors', `newline', `line_buffering' と `write_through' を新しい設定として再設定します。

`encoding' が指定されており、`errors' が指定されていないときに、 @code{errors='strict'} が使われている場合を除き、指定されなかったパラメータは現在の設定が保持されます。

ストリームからすでにデータが読み出されていた場合、encodingとnewlineは変更できません。一方で、書き込み後にencodingを変更することはできます。

このメソッドは、新しい設定を適用するまえにストリームをフラッシュします。


Added in version 3.7.



バージョン 3.11 で変更: The method supports @code{encoding="locale"} option.

@end deffn

@geindex seek() (io.TextIOWrapper のメソッド)
@anchor{library/io io TextIOWrapper seek}@anchor{3125}
@deffn {メソッド} seek (cookie, whence=os.SEEK_SET, /)

Set the stream position.
Return the new stream position as an @ref{19b,,int}.

Four operations are supported,
given by the following argument combinations:


@itemize *

@item 
@code{seek(0, SEEK_SET)}: Rewind to the start of the stream.

@item 
@code{seek(cookie, SEEK_SET)}: Restore a previous position;
`cookie' `must be' a number returned by @ref{17b1,,tell()}.

@item 
@code{seek(0, SEEK_END)}: Fast-forward to the end of the stream.

@item 
@code{seek(0, SEEK_CUR)}: Leave the current stream position unchanged.
@end itemize

Any other argument combinations are invalid,
and may raise exceptions.


@subsubheading 参考


@ref{14a5,,os.SEEK_SET}, @ref{14a6,,os.SEEK_CUR}, and @ref{14a7,,os.SEEK_END}.

@end deffn

@geindex tell() (io.TextIOWrapper のメソッド)
@anchor{library/io io TextIOWrapper tell}@anchor{17b1}
@deffn {メソッド} tell ()

Return the stream position as an opaque number.
The return value of @code{tell()} can be given as input to @ref{3125,,seek()},
to restore a previous stream position.
@end deffn
@end deffn

@geindex StringIO (io のクラス)
@anchor{library/io io StringIO}@anchor{112a}
@deffn {クラス} io.StringIO (initial_value='@w{'}, newline='\n')

A text stream using an in-memory text buffer.  It inherits from
@ref{8a4,,TextIOBase}.

テキストバッファは @ref{506,,close()} メソッドが呼び出されたときに破棄されます。

The initial value of the buffer can be set by providing `initial_value'.
If newline translation is enabled, newlines will be encoded as if by
@ref{205b,,write()}.  The stream is positioned at the start of the
buffer which emulates opening an existing file in a @code{w+} mode, making it
ready for an immediate write from the beginning or for a write that
would overwrite the initial value.  To emulate opening a file in an @code{a+}
mode ready for appending, use @code{f.seek(0, io.SEEK_END)} to reposition the
stream at the end of the buffer.

`newline' 引数は @ref{9be,,TextIOWrapper} の同名の引数と同じように働きます。ただし、出力をストリームに書き込む時に `newline' が @code{None} の場合には、改行は全てのプラットフォームで @code{\n} になります。

@ref{8a4,,TextIOBase} と @ref{505,,IOBase} から継承したメソッドに加えて @ref{112a,,StringIO} は以下のメソッドを提供しています:

@geindex getvalue() (io.StringIO のメソッド)
@anchor{library/io io StringIO getvalue}@anchor{3126}
@deffn {メソッド} getvalue ()

Return a @ref{169,,str} containing the entire contents of the buffer.
Newlines are decoded as if by @ref{206c,,read()}, although
the stream position is not changed.
@end deffn

使用例:

@example
import io

output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()
@end example
@end deffn

@geindex universal newlines;io.IncrementalNewlineDecoder class

@geindex IncrementalNewlineDecoder (io のクラス)
@anchor{library/io io IncrementalNewlineDecoder}@anchor{1a3e}
@deffn {クラス} io.IncrementalNewlineDecoder

A helper codec that decodes newlines for @ref{f35,,universal newlines} mode.
It inherits from @ref{2837,,codecs.IncrementalDecoder}.
@end deffn

@node Static Typing,性能<3>,クラス階層,io --- ストリームを扱うコアツール
@anchor{library/io static-typing}@anchor{3127}
@subsubsection Static Typing


The following protocols can be used for annotating function and method
arguments for simple stream reading or writing operations. They are decorated
with @ref{675,,@@typing.runtime_checkable}.

@geindex Reader (io のクラス)
@anchor{library/io io Reader}@anchor{236}
@deffn {クラス} io.Reader [T]

Generic protocol for reading from a file or other input stream. @code{T} will
usually be @ref{169,,str} or @ref{192,,bytes}, but can be any type that is
read from the stream.


Added in version 3.14.


@geindex read() (io.Reader のメソッド)
@anchor{library/io io Reader read}@anchor{3128}
@deffn {メソッド} read ()

@deffnx {メソッド} read (size, /)

Read data from the input stream and return it. If `size' is
specified, it should be an integer, and at most `size' items
(bytes/characters) will be read.
@end deffn

例えば:

@example
def read_it(reader: Reader[str]):
    data = reader.read(11)
    assert isinstance(data, str)
@end example
@end deffn

@geindex Writer (io のクラス)
@anchor{library/io io Writer}@anchor{237}
@deffn {クラス} io.Writer [T]

Generic protocol for writing to a file or other output stream. @code{T} will
usually be @ref{169,,str} or @ref{192,,bytes}, but can be any type that can be
written to the stream.


Added in version 3.14.


@geindex write() (io.Writer のメソッド)
@anchor{library/io io Writer write}@anchor{3129}
@deffn {メソッド} write (data, /)

Write `data' to the output stream and return the number of items
(bytes/characters) written.
@end deffn

例えば:

@example
def write_binary(writer: Writer[bytes]):
    writer.write(b"Hello world!\n")
@end example
@end deffn

See @ref{312a,,ABCs and Protocols for working with I/O} for other I/O related protocols and classes that can be
used for static type checking.

@node 性能<3>,,Static Typing,io --- ストリームを扱うコアツール
@anchor{library/io performance}@anchor{312b}
@subsubsection 性能


このセクションでは与えられた具体的な I/O 実装の性能について議論します。

@menu
* バイナリ I/O: バイナリ I/O<2>. 
* テキスト I/O: テキスト I/O<3>. 
* マルチスレッディング: マルチスレッディング<3>. 
* リエントラント性:: 

@end menu

@node バイナリ I/O<2>,テキスト I/O<3>,,性能<3>
@anchor{library/io id2}@anchor{312c}
@subsubsection バイナリ I/O


バッファ付き I/O は、ユーザが 1 バイトだけ要求した場合でさえ、データを大きな塊でのみ読み書きします。これにより、オペレーティングシステムのバッファ無し I/O ルーチンを呼び出して実行する非効率性はすべて隠されます。その成果は、OS と、実行される I/O の種類によって異なります。例えば、Linux のような現行の OS では、バッファ無しディスク I/O がバッファ付き I/O と同じくらい早いことがあります。しかし、どのプラットフォームとデバイスにおいても、バッファ付き I/O は最低でも予測可能なパフォーマンスを提供します。ですから、バイナリデータに対しては、バッファ無し I/O を使用するより、バッファ付きの I/O を使用するほうが望ましい場合がほとんどです。

@node テキスト I/O<3>,マルチスレッディング<3>,バイナリ I/O<2>,性能<3>
@anchor{library/io id3}@anchor{312d}
@subsubsection テキスト I/O


Text I/O over a binary storage (such as a file) is significantly slower than
binary I/O over the same storage, because it requires conversions between
unicode and binary data using a character codec.  This can become noticeable
handling huge amounts of text data like large log files.  Also,
@ref{3122,,tell()} and @ref{3121,,seek()} are both quite slow
due to the reconstruction algorithm used.

しかし @ref{112a,,StringIO} は、ネイティブなインメモリ Unicode コンテナで、 @ref{10a4,,BytesIO} と同程度の速度を示します。

@node マルチスレッディング<3>,リエントラント性,テキスト I/O<3>,性能<3>
@anchor{library/io multi-threading}@anchor{312e}
@subsubsection マルチスレッディング


@ref{1527,,FileIO} objects are thread-safe to the extent that the operating system
calls (such as @code{read(2)@footnote{https://manpages.debian.org/read(2)}} under Unix) they wrap are thread-safe too.

バイナリバッファ付きオブジェクト (@ref{1427,,BufferedReader}, @ref{15cb,,BufferedWriter}, @ref{15cc,,BufferedRandom} および @ref{15cd,,BufferedRWPair} のインスタンス) は、その内部構造をロックを使って保護します。このため、これらを複数のスレッドから同時に呼び出しても安全です。

@ref{9be,,TextIOWrapper} オブジェクトはスレッドセーフではありません。

@node リエントラント性,,マルチスレッディング<3>,性能<3>
@anchor{library/io reentrancy}@anchor{312f}
@subsubsection リエントラント性


バイナリバッファ付きオブジェクト (@ref{1427,,BufferedReader}, @ref{15cb,,BufferedWriter}, @ref{15cc,,BufferedRandom} および @ref{15cd,,BufferedRWPair} のインスタンス) は、リエントラント (再入可能) ではありません。リエントラントな呼び出しは普通の状況では起こりませんが、 I/O を @ref{cb,,signal} ハンドラで行なっているときに起こりえます。スレッドが、すでにアクセスしているバッファ付きオブジェクトに再び入ろうとすると @ref{244,,RuntimeError} が送出されます。これは、バッファ付きオブジェクトに複数のスレッドから入ることを禁止するわけではありません。

The above implicitly extends to text files, since the @ref{316,,open()} function
will wrap a buffered object inside a @ref{9be,,TextIOWrapper}.  This includes
standard streams and therefore affects the built-in @ref{1177,,print()} function as
well.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node time --- 時刻データへのアクセスと変換,logging --- Python 用のログ記録手段,io --- ストリームを扱うコアツール,汎用オペレーティングシステムサービス
@anchor{library/time doc}@anchor{3130}@anchor{library/time module-time}@anchor{f4}@anchor{library/time time-time-access-and-conversions}@anchor{3131}@anchor{library/time translation-repo}@anchor{3132}
@subsection @code{time} --- 時刻データへのアクセスと変換


@geindex module; time


__________________________________________________________________


このモジュールでは、時刻に関するさまざまな関数を提供します。関連した機能について、@ref{34,,datetime}, @ref{15,,calendar} モジュールも参照してください。

このモジュールは常に利用可能ですが、すべての関数がすべてのプラットフォームで利用可能なわけではありません。このモジュールで定義されているほとんどの関数は、プラットフォーム上の同名の C ライブラリ関数を呼び出します。これらの関数に対する意味付けはプラットフォーム間で異なるため、プラットフォーム提供のドキュメントを読んでおくと便利でしょう。

まずいくつかの用語の説明と慣習について整理します。

@geindex エポック
@anchor{library/time epoch}@anchor{2f13}

@itemize *

@item 
The `epoch' is the point where the time starts, the return value of
@code{time.gmtime(0)}. It is January 1, 1970, 00:00:00 (UTC) on all platforms.
@end itemize

@geindex エポックからの秒数


@itemize *

@item 
`エポック秒' (`seconds since the epoch') は、エポックからの総経過秒数を示していますが、たいていはうるう秒 (leap seconds@footnote{https://en.wikipedia.org/wiki/Leap_second}) は含まれていません。
全ての POSIX 互換のプラットフォームで、うるう秒はこの総秒数には含まれません。
@end itemize

@geindex 2038年


@itemize *

@item 
このモジュールの中の関数は、エポック (@ref{2f13,,epoch}) 以前あるいは遠い未来の日付や時刻を扱うことができません。将来カットオフ（関数が正しく日付や時刻を扱えなくなる）が起きる時点は、C ライブラリによって決まります。32-bit システムではカットオフは通常 2038 年です。
@end itemize

@geindex 2-digit years


@itemize *

@item 
関数 @ref{1646,,strptime()} は @code{%y} 書式コードが与えられた時に 2 桁の年表記を解析できます。2 桁の年を解析する場合、それらは POSIX および ISO C 標準に従って変換されます: 69-99 の西暦年は 1969-1999 となり、0–68 の西暦年は 2000–2068 になります。
@end itemize

@geindex UTC
@geindex 協定世界時
@geindex グリニッジ標準時


@itemize *

@item 
UTC is Coordinated Universal Time@footnote{https://en.wikipedia.org/wiki/Coordinated_Universal_Time} and superseded Greenwich Mean Time@footnote{https://en.wikipedia.org/wiki/Greenwich_Mean_Time} or
GMT as the basis of international timekeeping. The acronym UTC is not a
mistake but conforms to an earlier, language-agnostic naming scheme for time
standards such as UT0, UT1, and UT2.
@end itemize

@geindex 夏時間


@itemize *

@item 
DST は夏時間 (Daylight Saving Time) のことで、一年のうちの一定期間に 1 時間タイムゾーンを修正することです。DST のルールは不可思議で (地域ごとに法律で定められています)、年ごとに変わることもあります。C ライブラリはローカルルールを記したテーブルを持っており (柔軟に対応するため、たいていはシステムファイルから読み込まれます)、この点に関しては唯一の真実の知識の源です。

@item 
多くの現時刻を返す関数 (real-time functions) の精度は、値や引数を表現するために使う単位から想像されるよりも低いかも知れません。例えば、ほとんどの Unix システムにおいて、クロックの 1 ティックの精度は 50 から 100 分の 1 秒に過ぎません。

@item 
一方、@ref{55d,,time()} および @ref{8ac,,sleep()} は Unix の同等の関数よりましな精度を持っています。時刻は浮動小数点数で表され、@ref{55d,,time()} は可能なかぎり最も正確な時刻を (Unix の @code{gettimeofday()} があればそれを使って) 返します。また @ref{8ac,,sleep()} にはゼロでない端数を与えることができます (Unix の @code{select()} があれば、それを使って実装しています)。

@item 
@ref{13d8,,gmtime()}, @ref{1712,,localtime()}, @ref{1646,,strptime()} が返す時刻値、および @ref{1400,,asctime()}, @ref{1401,,mktime()}, @ref{1402,,strftime()} がとる時刻値は 9 個の整数からなるシーケンスです。@ref{13d8,,gmtime()}, @ref{1712,,localtime()}, @ref{1646,,strptime()} の戻り値は個々の値を属性名で取得することもできます。

これらのオブジェクトについての解説は @ref{ee6,,struct_time} を参照してください。


バージョン 3.3 で変更: @ref{ee6,,struct_time} オブジェクトは、プラットフォームが、対応する @code{struct tm} メンバーをサポートしている場合、@ref{3133,,tm_gmtoff} および @ref{3134,,tm_zone} 属性が拡張されるようになりました。



バージョン 3.6 で変更: @ref{ee6,,struct_time} の属性 @ref{3133,,tm_gmtoff} および @ref{3134,,tm_zone} が全てのプラットフォームで利用できるようになりました。


@item 
時間の表現を変換するには、以下の関数を利用してください:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

対象

@tab

変換先

@tab

関数

@item

エポックからの秒数

@tab

UTC の @ref{ee6,,struct_time}

@tab

@ref{13d8,,gmtime()}

@item

エポックからの秒数

@tab

ローカル時間の @ref{ee6,,struct_time}

@tab

@ref{1712,,localtime()}

@item

UTC の @ref{ee6,,struct_time}

@tab

エポックからの秒数

@tab

@ref{2948,,calendar.timegm()}

@item

ローカル時間の @ref{ee6,,struct_time}

@tab

エポックからの秒数

@tab

@ref{1401,,mktime()}

@end multitable

@end itemize

@menu
* 関数: 関数<5>. 
* Clock ID Constants:: 
* Timezone Constants:: 

@end menu

@node 関数<5>,Clock ID Constants,,time --- 時刻データへのアクセスと変換
@anchor{library/time functions}@anchor{3135}@anchor{library/time time-functions}@anchor{3136}
@subsubsection 関数


@geindex asctime() (time モジュール)
@anchor{library/time time asctime}@anchor{1400}
@deffn {の関数} time.asctime ([t])

Convert a tuple or @ref{ee6,,struct_time} representing a time as returned by
@ref{13d8,,gmtime()} or @ref{1712,,localtime()} to a string of the following
form: @code{'Sun Jun 20 23:21:05 1993'}. The day field is two characters long
and is space padded if the day is a single digit,
e.g.: @code{'Wed Jun  9 04:26:40 1993'}.

If `t' is not provided, the current time as returned by @ref{1712,,localtime()}
is used. Locale information is not used by @ref{1400,,asctime()}.

@cartouche
@quotation 注釈 
同名の C の関数と違って、@ref{1400,,asctime()} は末尾に改行文字を加えません。
@end quotation
@end cartouche
@end deffn

@geindex pthread_getcpuclockid() (time モジュール)
@anchor{library/time time pthread_getcpuclockid}@anchor{d8b}
@deffn {の関数} time.pthread_getcpuclockid (thread_id)

Return the `clk_id' of the thread-specific CPU-time clock for the specified `thread_id'.

Use @ref{1372,,threading.get_ident()} or the @ref{3137,,ident}
attribute of @ref{176,,threading.Thread} objects to get a suitable value
for `thread_id'.

@cartouche
@quotation 警告 
Passing an invalid or expired `thread_id' may result in
undefined behavior, such as segmentation fault.
@end quotation
@end cartouche

@ref{213f,,Availability}: Unix

更なる情報については @code{pthread_getcpuclockid(3)@footnote{https://manpages.debian.org/pthread_getcpuclockid(3)}} の man を参照してください。


Added in version 3.7.

@end deffn

@geindex clock_getres() (time モジュール)
@anchor{library/time time clock_getres}@anchor{1375}
@deffn {の関数} time.clock_getres (clk_id)

指定された `clk_id' クロックの分解能(精度)を返します。 `clk_id' として受け付けられる値の一覧は @ref{30ad,,Clock ID Constants} を参照してください。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex clock_gettime() (time モジュール)
@anchor{library/time time clock_gettime}@anchor{1376}
@deffn {の関数} time.clock_gettime (clk_id) -> float

指定された `clk_id' クロックの時刻を返します。 `clk_id' として受け付けられる値の一覧は @ref{30ad,,Clock ID Constants} を参照してください。

Use @ref{cdb,,clock_gettime_ns()} to avoid the precision loss caused by the
@ref{196,,float} type.

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex clock_gettime_ns() (time モジュール)
@anchor{library/time time clock_gettime_ns}@anchor{cdb}
@deffn {の関数} time.clock_gettime_ns (clk_id) -> int

@ref{1376,,clock_gettime()} に似ていますが、ナノ秒単位の時刻を返します。

@ref{213f,,Availability}: Unix.


Added in version 3.7.

@end deffn

@geindex clock_settime() (time モジュール)
@anchor{library/time time clock_settime}@anchor{1377}
@deffn {の関数} time.clock_settime (clk_id, time: float)

指定された `clk_id' クロックの時刻を設定します。
現在、 @ref{8a9,,CLOCK_REALTIME} は `clk_id' が受け付ける唯一の値です。

Use @ref{cdc,,clock_settime_ns()} to avoid the precision loss caused by the
@ref{196,,float} type.

@ref{213f,,Availability}: Unix, not Android, not iOS.


Added in version 3.3.

@end deffn

@geindex clock_settime_ns() (time モジュール)
@anchor{library/time time clock_settime_ns}@anchor{cdc}
@deffn {の関数} time.clock_settime_ns (clk_id, time: int)

@ref{1377,,clock_settime()} に似ていますが、ナノ秒単位の時刻を設定します。

@ref{213f,,Availability}: Unix, not Android, not iOS.


Added in version 3.7.

@end deffn

@geindex ctime() (time モジュール)
@anchor{library/time time ctime}@anchor{28c5}
@deffn {の関数} time.ctime ([secs])

Convert a time expressed in seconds since the @ref{2f13,,epoch} to a string of a form:
@code{'Sun Jun 20 23:21:05 1993'} representing local time. The day field
is two characters long and is space padded if the day is a single digit,
e.g.: @code{'Wed Jun  9 04:26:40 1993'}.

`secs' を指定しないか @ref{885,,None} を指定した場合、@ref{55d,,time()} が返す値を現在の時刻として使用します。@code{ctime(secs)} は @code{asctime(localtime(secs))} と等価です。ローカル情報は @ref{28c5,,ctime()} には使用されません。
@end deffn

@geindex get_clock_info() (time モジュール)
@anchor{library/time time get_clock_info}@anchor{1374}
@deffn {の関数} time.get_clock_info (name)

指定されたクロックの情報を名前空間オブジェクトとして取得します。サポートされているクロック名およびそれらの値を取得する関数は以下の通りです:


@itemize *

@item 
@code{'monotonic'}: @ref{55c,,time.monotonic()}

@item 
@code{'perf_counter'}: @ref{c7a,,time.perf_counter()}

@item 
@code{'process_time'}: @ref{c7b,,time.process_time()}

@item 
@code{'thread_time'}: @ref{b30,,time.thread_time()}

@item 
@code{'time'}: @ref{55d,,time.time()}
@end itemize

結果は以下の属性をもちます:


@itemize -

@item 
`adjustable': @code{True} if the clock can be set to jump forward or backward
in time, @code{False} otherwise. Does not refer to gradual NTP rate adjustments.

@item 
`implementation': クロック値を取得するために内部で使用している C 関数の名前です。
使える値については @ref{30ad,,Clock ID Constants} を参照してください。

@item 
`monotonic': クロック値が後戻りすることがない場合 @code{True} が、そうでない場合は @code{False} になります。

@item 
`resolution': クロックの分解能を秒 (@ref{196,,float}) で表します。
@end itemize


Added in version 3.3.

@end deffn

@geindex gmtime() (time モジュール)
@anchor{library/time time gmtime}@anchor{13d8}
@deffn {の関数} time.gmtime ([secs])

エポック (@ref{2f13,,epoch}) からの経過時間で表現された時刻を、UTC で @ref{ee6,,struct_time} に変換します。このとき dst フラグは常にゼロとして扱われます。`secs' を指定しないか @ref{885,,None} を指定した場合、@ref{55d,,time()} が返す値を現在の時刻として使用します。秒の端数は無視されます。@ref{ee6,,struct_time} オブジェクトについては前述の説明を参照してください。@ref{2948,,calendar.timegm()} はこの関数と逆の変換を行います。
@end deffn

@geindex localtime() (time モジュール)
@anchor{library/time time localtime}@anchor{1712}
@deffn {の関数} time.localtime ([secs])

@ref{13d8,,gmtime()} に似ていますが、ローカル時間に変換します。`secs' を指定しないか @ref{885,,None} を指定した場合、@ref{55d,,time()} が返す値を現在の時刻として使用します。DST が適用されている場合は dst フラグには @code{1} が設定されます。

@ref{1712,,localtime()} may raise @ref{a81,,OverflowError}, if the timestamp is
outside the range of values supported by the platform C @code{localtime()}
or @code{gmtime()} functions, and @ref{2c0,,OSError} on @code{localtime()} or
@code{gmtime()} failure. It's common for this to be restricted to years
between 1970 and 2038.
@end deffn

@geindex mktime() (time モジュール)
@anchor{library/time time mktime}@anchor{1401}
@deffn {の関数} time.mktime (t)

@ref{1712,,localtime()} の逆を行う関数です。引数は @ref{ee6,,struct_time} か 9 個の要素すべての値を持つ完全なタプル (dst フラグも必要です; 時刻に DST が適用されるか不明の場合は @code{-1} を使用してください) で、UTC ではなく `ローカル' 時間を指定します。戻り値は @ref{55d,,time()} との互換性のために浮動小数点数になります。入力した値を正しい時刻として表現できない場合、例外 @ref{a81,,OverflowError} または @ref{2ec,,ValueError} が送出されます (どちらが送出されるかは、無効な値を受け取ったのが Python と下層の C ライブラリのどちらなのかによって決まります)。この関数で時刻を生成できる最も古い日付はプラットフォームに依存します。
@end deffn

@geindex monotonic() (time モジュール)
@anchor{library/time time monotonic}@anchor{55c}
@deffn {の関数} time.monotonic () -> float

モノトニッククロック、すなわち後戻りしないクロックの値を (小数秒で) 返します。このクロックはシステムクロックの更新の影響を受けません。戻り値の基準点は定義されていないので、二回の呼び出しの結果の差だけが有効です。

Clock:


@itemize *

@item 
On Windows, call @code{QueryPerformanceCounter()} and
@code{QueryPerformanceFrequency()}.

@item 
On macOS, call @code{mach_absolute_time()} and @code{mach_timebase_info()}.

@item 
On HP-UX, call @code{gethrtime()}.

@item 
Call @code{clock_gettime(CLOCK_HIGHRES)} if available.

@item 
Otherwise, call @code{clock_gettime(CLOCK_MONOTONIC)}.
@end itemize

Use @ref{cdd,,monotonic_ns()} to avoid the precision loss caused by the
@ref{196,,float} type.


Added in version 3.3.



バージョン 3.5 で変更: The function is now always available and the clock is now the same for
all processes.



バージョン 3.10 で変更: On macOS, the clock is now the same for all processes.

@end deffn

@geindex monotonic_ns() (time モジュール)
@anchor{library/time time monotonic_ns}@anchor{cdd}
@deffn {の関数} time.monotonic_ns () -> int

@ref{55c,,monotonic()} に似ていますが、ナノ秒単位の時刻を返します。


Added in version 3.7.

@end deffn

@geindex perf_counter() (time モジュール)
@anchor{library/time time perf_counter}@anchor{c7a}
@deffn {の関数} time.perf_counter () -> float

@geindex ベンチマーク

Return the value (in fractional seconds) of a performance counter, i.e. a
clock with the highest available resolution to measure a short duration.  It
does include time elapsed during sleep. The clock is the same for all
processes. The reference
point of the returned value is undefined, so that only the difference between
the results of two calls is valid.

`CPython 実装の詳細:' On CPython, use the same clock as @ref{55c,,time.monotonic()} and is a
monotonic clock, i.e. a clock that cannot go backwards.

Use @ref{cde,,perf_counter_ns()} to avoid the precision loss caused by the
@ref{196,,float} type.


Added in version 3.3.



バージョン 3.10 で変更: On Windows, the clock is now the same for all processes.



バージョン 3.13 で変更: Use the same clock as @ref{55c,,time.monotonic()}.

@end deffn

@geindex perf_counter_ns() (time モジュール)
@anchor{library/time time perf_counter_ns}@anchor{cde}
@deffn {の関数} time.perf_counter_ns () -> int

@ref{c7a,,perf_counter()} に似ていますが、ナノ秒単位の時刻を返します。


Added in version 3.7.

@end deffn

@geindex process_time() (time モジュール)
@anchor{library/time time process_time}@anchor{c7b}
@deffn {の関数} time.process_time () -> float

@geindex CPU 時間
@geindex プロセッサー時間
@geindex ベンチマーク

現在のプロセスのシステムおよびユーザー CPU 時間の値を (小数秒で) 返します。これはスリープ中の経過時間を含みません。これは定義上プロセスワイドです。戻り値の基準点は定義されていないので、二回の呼び出しの結果の差だけが有効です。

Use @ref{cdf,,process_time_ns()} to avoid the precision loss caused by the
@ref{196,,float} type.


Added in version 3.3.

@end deffn

@geindex process_time_ns() (time モジュール)
@anchor{library/time time process_time_ns}@anchor{cdf}
@deffn {の関数} time.process_time_ns () -> int

@ref{c7b,,process_time()} に似ていますが、ナノ秒単位の時刻を返します。


Added in version 3.7.

@end deffn

@geindex sleep() (time モジュール)
@anchor{library/time time sleep}@anchor{8ac}
@deffn {の関数} time.sleep (secs)

Suspend execution of the calling thread for the given number of seconds.
The argument may be a floating-point number to indicate a more precise sleep
time.

If the sleep is interrupted by a signal and no exception is raised by the
signal handler, the sleep is restarted with a recomputed timeout.

The suspension time may be longer than requested by an arbitrary amount,
because of the scheduling of other activity in the system.

@subsubheading Windows implementation


On Windows, if `secs' is zero, the thread relinquishes the remainder of its
time slice to any other thread that is ready to run. If there are no other
threads ready to run, the function returns immediately, and the thread
continues execution.  On Windows 10 and newer the implementation uses
a high-resolution timer@footnote{https://learn.microsoft.com/windows/win32/api/synchapi/nf-synchapi-createwaitabletimerexw}
which provides resolution of 100 nanoseconds. If `secs' is zero, @code{Sleep(0)} is used.

@subsubheading Unix implementation



@itemize *

@item 
Use @code{clock_nanosleep()} if available (resolution: 1 nanosecond);

@item 
Or use @code{nanosleep()} if available (resolution: 1 nanosecond);

@item 
Or use @code{select()} (resolution: 1 microsecond).
@end itemize

@cartouche
@quotation 注釈 
To emulate a "no-op", use @ref{17e,,pass} instead of @code{time.sleep(0)}.

To voluntarily relinquish the CPU, specify a real-time @ref{30f4,,scheduling policy} and use @ref{1329,,os.sched_yield()} instead.
@end quotation
@end cartouche

引数 @code{secs} を指定して @ref{1c6e,,監査イベント} @code{time.sleep} を送出します。


バージョン 3.5 で変更: スリープがシグナルに中断されてもシグナルハンドラが例外を送出しない限り、少なくとも `secs' だけスリープするようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。



バージョン 3.11 で変更: On Unix, the @code{clock_nanosleep()} and @code{nanosleep()} functions are now
used if available. On Windows, a waitable timer is now used.



バージョン 3.13 で変更: Raises an auditing event.

@end deffn

@geindex % (パーセント);datetime format

@geindex strftime() (time モジュール)
@anchor{library/time time strftime}@anchor{1402}
@deffn {の関数} time.strftime (format[, t])

@ref{13d8,,gmtime()} や @ref{1712,,localtime()} が返す時刻値タプルまたは @ref{ee6,,struct_time} を、`format' で指定した文字列形式に変換します。`t' が与えられていない場合、@ref{1712,,localtime()} が返す値を現在の時刻として使用します。`format' は文字列でなくてはなりません。`t' のいずれかのフィールドが許容範囲外の数値であった場合、@ref{2ec,,ValueError} を送出します。

0 は時刻タプル内のいずれの位置の引数にも使用できます; それが一般に不正な値であれば、正しい値に強制的に置き換えられます。

`format' 文字列には以下のディレクティブ (指示語) を埋め込むことができます。これらはフィールド長や精度のオプションを付けずに表され、@ref{1402,,strftime()} の結果の対応する文字列に置き換えられます:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

ディレクティブ

@tab

意味

@tab

注釈

@item

@code{%a}

@tab

ロケールの短縮された曜日名になります。

@tab

@item

@code{%A}

@tab

ロケールの曜日名になります。

@tab

@item

@code{%b}

@tab

ロケールの短縮された月名になります。

@tab

@item

@code{%B}

@tab

ロケールの月名になります。

@tab

@item

@code{%c}

@tab

ロケールの日時を適切な形式で表します。

@tab

@item

@code{%d}

@tab

月中の日にちの 10 進表記になります [01,31]。

@tab

@item

@code{%f}

@tab


@table @asis

@item Microseconds as a decimal number

[000000,999999].
@end table

@tab

(1)

@item

@code{%H}

@tab

時 (24 時間表記) の 10 進表記になります [00,23]。

@tab

@item

@code{%I}

@tab

時 (12 時間表記) の 10 進表記になります [01,12]。

@tab

@item

@code{%j}

@tab

年中の日にちの 10 進表記になります [001,366]。

@tab

@item

@code{%m}

@tab

月の 10 進表記になります [01,12]。

@tab

@item

@code{%M}

@tab

分の 10 進表記になります [00,59]。

@tab

@item

@code{%p}

@tab

ロケールの AM もしくは PM と等価な文字列になります。

@tab

(2)

@item

@code{%S}

@tab

秒の 10 進表記になります [00,61]。

@tab

(3)

@item

@code{%U}

@tab

年の初めから何週目か (日曜を週の始まりとします) を表す 10 進数になります [00,53]。年が明けてから最初の日曜日までのすべての曜日は 0 週目に属すると見なされます。

@tab

(4)

@item

@code{%u}

@tab

Day of the week (Monday is 1; Sunday is 7)
as a decimal number [1, 7].

@tab

@item

@code{%w}

@tab

曜日の 10 進表記になります [0 (日曜日),6]。

@tab

@item

@code{%W}

@tab

年の初めから何週目か (月曜を週の始まりとします) を表す 10 進数になります [00,53]。年が明けてから最初の月曜日までの全ての曜日は 0 週目に属すると見なされます。

@tab

(4)

@item

@code{%x}

@tab

ロケールの日付を適切な形式で表します。

@tab

@item

@code{%X}

@tab

ロケールの時間を適切な形式で表します。

@tab

@item

@code{%y}

@tab

西暦の下 2 桁の 10 進表記になります [00,99]。

@tab

@item

@code{%Y}

@tab

西暦 ( 4桁) の 10 進表記を表します。

@tab

@item

@code{%z}

@tab

タイムゾーンと UTC/GMT との時差を表す正または負の時間を +HHMM、-HHMM で表します。H は時間の、M は分の 10 進表記になります [-23:59, +23:59]。 @footnote{
The use of @code{%Z} is now deprecated, but the @code{%z} escape that expands to the
preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 
@geindex RFC; RFC 822
@uref{https://datatracker.ietf.org/doc/html/rfc822.html,RFC 822} standard calls for a two-digit
year (@code{%y} rather than @code{%Y}), but practice moved to 4-digit years long before the
year 2000.  After that, 
@geindex RFC; RFC 822
@uref{https://datatracker.ietf.org/doc/html/rfc822.html,RFC 822} became obsolete and the 4-digit year has
been first recommended by 
@geindex RFC; RFC 1123
@uref{https://datatracker.ietf.org/doc/html/rfc1123.html,RFC 1123} and then mandated by 
@geindex RFC; RFC 2822
@uref{https://datatracker.ietf.org/doc/html/rfc2822.html,RFC 2822},
with 
@geindex RFC; RFC 5322
@uref{https://datatracker.ietf.org/doc/html/rfc5322.html,RFC 5322} continuing this requirement.
}

@tab

@item

@code{%Z}

@tab

タイムゾーンの名前を表します (タイムゾーンがない場合には空文字列)。非推奨です。 @footnote{
The use of @code{%Z} is now deprecated, but the @code{%z} escape that expands to the
preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 
@geindex RFC; RFC 822
@uref{https://datatracker.ietf.org/doc/html/rfc822.html,RFC 822} standard calls for a two-digit
year (@code{%y} rather than @code{%Y}), but practice moved to 4-digit years long before the
year 2000.  After that, 
@geindex RFC; RFC 822
@uref{https://datatracker.ietf.org/doc/html/rfc822.html,RFC 822} became obsolete and the 4-digit year has
been first recommended by 
@geindex RFC; RFC 1123
@uref{https://datatracker.ietf.org/doc/html/rfc1123.html,RFC 1123} and then mandated by 
@geindex RFC; RFC 2822
@uref{https://datatracker.ietf.org/doc/html/rfc2822.html,RFC 2822},
with 
@geindex RFC; RFC 5322
@uref{https://datatracker.ietf.org/doc/html/rfc5322.html,RFC 5322} continuing this requirement.
}

@tab

@item

@code{%G}

@tab

ISO 8601 year (similar to @code{%Y} but follows
the rules for the ISO 8601 calendar year).
The year starts with the week that contains
the first Thursday of the calendar year.

@tab

@item

@code{%V}

@tab

ISO 8601 week number (as a decimal number
[01,53]). The first week of the year is the
one that contains the first Thursday of the
year. Weeks start on Monday.

@tab

@item

@code{%%}

@tab

文字 @code{'%'} を表します。

@tab

@end multitable


注釈:


@enumerate 

@item 
The @code{%f} format directive only applies to @ref{1646,,strptime()},
not to @ref{1402,,strftime()}. However, see also @ref{1950,,datetime.datetime.strptime()} and
@ref{e8e,,datetime.datetime.strftime()} where the @code{%f} format directive
@ref{2897,,applies to microseconds}.

@item 
@ref{1646,,strptime()} 関数で使う場合、@code{%p} ディレクティブが出力結果の時刻フィールドに影響を及ぼすのは、時刻を解釈するために @code{%I} を使ったときのみです。
@end enumerate
@anchor{library/time leap-second}@anchor{3138}

@enumerate 3

@item 
値の幅は実際に @code{0} から @code{61} です; @code{60} は うるう秒<leap seconds>@footnote{https://en.wikipedia.org/wiki/Leap_second} を表し、 @code{61} は歴史的理由によりサポートされています。

@item 
@ref{1646,,strptime()} 関数で使う場合、@code{%U} および @code{%W} を計算に使うのは曜日と年を指定したときだけです。
@end enumerate

以下に 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} インターネット電子メール標準で定義されている日付表現と互換の書式の例を示します。  @footnote{
The use of @code{%Z} is now deprecated, but the @code{%z} escape that expands to the
preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 
@geindex RFC; RFC 822
@uref{https://datatracker.ietf.org/doc/html/rfc822.html,RFC 822} standard calls for a two-digit
year (@code{%y} rather than @code{%Y}), but practice moved to 4-digit years long before the
year 2000.  After that, 
@geindex RFC; RFC 822
@uref{https://datatracker.ietf.org/doc/html/rfc822.html,RFC 822} became obsolete and the 4-digit year has
been first recommended by 
@geindex RFC; RFC 1123
@uref{https://datatracker.ietf.org/doc/html/rfc1123.html,RFC 1123} and then mandated by 
@geindex RFC; RFC 2822
@uref{https://datatracker.ietf.org/doc/html/rfc2822.html,RFC 2822},
with 
@geindex RFC; RFC 5322
@uref{https://datatracker.ietf.org/doc/html/rfc5322.html,RFC 5322} continuing this requirement.
}

@example
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'
@end example

一部のプラットフォームではさらにいくつかのディレクティブがサポートされていますが、標準 ANSI C で意味のある値はここで列挙したものだけです。あなたのプラットフォームでサポートされている書式コードの全一覧については、@code{strftime(3)@footnote{https://manpages.debian.org/strftime(3)}} のドキュメントを参照してください。

一部のプラットフォームでは、フィールドの幅や精度を指定するオプションがディレクティブの先頭の文字 @code{'%'} の直後に付けられるようになっていました; この機能も移植性はありません。フィールドの幅は通常 2 ですが、@code{%j} は例外で 3 です。
@end deffn

@geindex % (パーセント);datetime format

@geindex strptime() (time モジュール)
@anchor{library/time time strptime}@anchor{1646}
@deffn {の関数} time.strptime (string[, format])

時刻を表現する文字列を書式に従って解釈します。返される値は @ref{13d8,,gmtime()} や @ref{1712,,localtime()} が返すような @ref{ee6,,struct_time} です。

`format' パラメーターは @ref{1402,,strftime()} で使うものと同じディレクティブを使います; このパラメーターの値はデフォルトでは @code{"%a %b %d %H:%M:%S %Y"} で、@ref{28c5,,ctime()} が返すフォーマットに一致します。`string' が `format' に従って解釈できなかった場合、例外 @ref{2ec,,ValueError} が送出されます。解析しようとする `string' が解析後に余分なデータを持っていた場合、@ref{2ec,,ValueError} が送出されます。欠落したデータについて、適切な値を推測できない場合はデフォルトの値で埋められ、その値は @code{(1900, 1, 1, 0, 0, 0, 0, 1, -1)} です。`string' も `format' も文字列でなければなりません。

例えば:

@example
>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
@end example

@code{%Z} ディレクティブへのサポートは @code{tzname} に収められている値と @code{daylight} が真かどうかで決められます。このため、常に既知の (かつ夏時間でないと考えられている) UTC や GMT を認識する時以外はプラットフォーム固有の動作になります。

ドキュメント内で説明されているディレクティブだけがサポートされています。@code{strftime()} はプラットフォームごとに実装されているので、説明されていないディレクティブも利用できるかもしれません。しかし、@code{strptime()} はプラットフォーム非依存なので、ドキュメント内でサポートされているとされているディレクティブ以外は利用できません。
@end deffn

@geindex struct_time (time のクラス)
@anchor{library/time time struct_time}@anchor{ee6}
@deffn {クラス} time.struct_time

@ref{13d8,,gmtime()}, @ref{1712,,localtime()} および @ref{1646,,strptime()} が返す時刻値シーケンスの型です。これは @ref{85e,,名前付きタプル} のインターフェースをもったオブジェクトです。値はインデックスでも属性名でもアクセス可能です。以下の値があります:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

インデックス

@tab

属性

@tab

値

@item

0

@tab

@geindex tm_year (time.struct_time の属性)
@anchor{library/time time struct_time tm_year}@anchor{1711}
@deffn {の属性} tm_year
@end deffn

@tab

(例えば 1993)

@item

1

@tab

@geindex tm_mon (time.struct_time の属性)
@anchor{library/time time struct_time tm_mon}@anchor{3139}
@deffn {の属性} tm_mon
@end deffn

@tab

[1,12] の間の数

@item

2

@tab

@geindex tm_mday (time.struct_time の属性)
@anchor{library/time time struct_time tm_mday}@anchor{313a}
@deffn {の属性} tm_mday
@end deffn

@tab

[1,31] の間の数

@item

3

@tab

@geindex tm_hour (time.struct_time の属性)
@anchor{library/time time struct_time tm_hour}@anchor{313b}
@deffn {の属性} tm_hour
@end deffn

@tab

[0,23] の間の数

@item

4

@tab

@geindex tm_min (time.struct_time の属性)
@anchor{library/time time struct_time tm_min}@anchor{313c}
@deffn {の属性} tm_min
@end deffn

@tab

[0,59] の間の数

@item

5

@tab

@geindex tm_sec (time.struct_time の属性)
@anchor{library/time time struct_time tm_sec}@anchor{313d}
@deffn {の属性} tm_sec
@end deffn

@tab

range [0, 61]; see @ref{3138,,Note (2)} in @ref{1402,,strftime()}

@item

6

@tab

@geindex tm_wday (time.struct_time の属性)
@anchor{library/time time struct_time tm_wday}@anchor{313e}
@deffn {の属性} tm_wday
@end deffn

@tab

range [0, 6]; Monday is 0

@item

7

@tab

@geindex tm_yday (time.struct_time の属性)
@anchor{library/time time struct_time tm_yday}@anchor{313f}
@deffn {の属性} tm_yday
@end deffn

@tab

[1,366] の間の数

@item

8

@tab

@geindex tm_isdst (time.struct_time の属性)
@anchor{library/time time struct_time tm_isdst}@anchor{28d6}
@deffn {の属性} tm_isdst
@end deffn

@tab

0, 1 または -1; 以下を参照してください

@item

N/A

@tab

@geindex tm_zone (time.struct_time の属性)
@anchor{library/time time struct_time tm_zone}@anchor{3134}
@deffn {の属性} tm_zone
@end deffn

@tab

タイムゾーンの短縮名

@item

N/A

@tab

@geindex tm_gmtoff (time.struct_time の属性)
@anchor{library/time time struct_time tm_gmtoff}@anchor{3133}
@deffn {の属性} tm_gmtoff
@end deffn

@tab

UTC から東方向へのオフセット (秒)

@end multitable


C の構造体とは異なり、月の値は [0, 11] ではなく [1, 12] であることに注意してください。

@ref{1401,,mktime()} の呼び出し時に、@ref{28d6,,tm_isdst} は夏時間が有効な場合は 1、そうでない場合は 0 に設定されることがあります。
値が -1 の場合は夏時間について不明なことを表していて、普通 @ref{28d6,,tm_isdst} は正しい状態に設定されます。

@ref{ee6,,struct_time} を引数とする関数に正しくない長さの @ref{ee6,,struct_time} や要素の型が正しくない @ref{ee6,,struct_time} を与えた場合には、 @ref{198,,TypeError} が送出されます。
@end deffn

@geindex time() (time モジュール)
@anchor{library/time time time}@anchor{55d}
@deffn {の関数} time.time () -> float

エポック (@ref{2f13,,epoch}) からの秒数を浮動小数点数で返します。
うるう秒 (leap seconds@footnote{https://en.wikipedia.org/wiki/Leap_second}) の扱いはプラットフォーム依存です。
Windows とほとんどの Unix システムでは、うるう秒はエポック (@ref{2f13,,epoch}) 秒の時間の勘定には入りません。
これは一般に Unix 時間@footnote{https://en.wikipedia.org/wiki/Unix_time} と呼ばれています。

時刻は常に浮動小数点数で返されますが、すべてのシステムが 1 秒より高い精度で時刻を提供するとは限らないので注意してください。
この関数が返す値は通常減少していくことはありませんが、この関数を 2 回呼び出し、その呼び出しの間にシステムクロックの時刻を巻き戻して設定した場合には、以前の呼び出しよりも低い値が返ることがあります。

@ref{55d,,time()} が返す数値は、 @ref{13d8,,gmtime()} 関数に渡されて UTC の、あるいは @ref{1712,,localtime()} 関数に渡されて現地時間の、より一般的な時間のフォーマット (つまり、年、月、日、時間など) に変換されているかもしれません。
どちらの場合でも @ref{ee6,,struct_time} オブジェクトが返され、このオブジェクトの属性としてカレンダー日付の構成要素へアクセスできます。

Clock:


@itemize *

@item 
On Windows, call @code{GetSystemTimePreciseAsFileTime()}.

@item 
Call @code{clock_gettime(CLOCK_REALTIME)} if available.

@item 
Otherwise, call @code{gettimeofday()}.
@end itemize

Use @ref{ce0,,time_ns()} to avoid the precision loss caused by the @ref{196,,float}
type.
@end deffn


バージョン 3.13 で変更: On Windows, calls @code{GetSystemTimePreciseAsFileTime()} instead of
@code{GetSystemTimeAsFileTime()}.


@geindex time_ns() (time モジュール)
@anchor{library/time time time_ns}@anchor{ce0}
@deffn {の関数} time.time_ns () -> int

@ref{55d,,time()} に似ていますが、時刻を @ref{2f13,,epoch} を基点としたナノ秒単位の整数で返します。


Added in version 3.7.

@end deffn

@geindex thread_time() (time モジュール)
@anchor{library/time time thread_time}@anchor{b30}
@deffn {の関数} time.thread_time () -> float

@geindex CPU 時間
@geindex プロセッサー時間
@geindex ベンチマーク

現在のスレッドのシステムおよびユーザー CPU 時間の値を (小数秒で) 返します。これはスリープ中の経過時間を含みません。これは定義上スレッド固有です。戻り値の基準点は定義されていないので、同一スレッドにおける二回の呼び出しの結果の差だけが有効です。

Use @ref{d8a,,thread_time_ns()} to avoid the precision loss caused by the
@ref{196,,float} type.

@ref{213f,,Availability}: Linux, Unix, Windows.

Unix systems supporting @code{CLOCK_THREAD_CPUTIME_ID}.


Added in version 3.7.

@end deffn

@geindex thread_time_ns() (time モジュール)
@anchor{library/time time thread_time_ns}@anchor{d8a}
@deffn {の関数} time.thread_time_ns () -> int

@ref{b30,,thread_time()} に似ていますが、ナノ秒単位の時刻を返します。


Added in version 3.7.

@end deffn

@geindex tzset() (time モジュール)
@anchor{library/time time tzset}@anchor{3140}
@deffn {の関数} time.tzset ()

Reset the time conversion rules used by the library routines. The environment
variable 
@geindex TZ
@geindex 環境変数; TZ
@code{TZ} specifies how this is done. It will also set the variables
@code{tzname} (from the 
@geindex TZ
@geindex 環境変数; TZ
@code{TZ} environment variable), @code{timezone} (non-DST
seconds West of UTC), @code{altzone} (DST seconds west of UTC) and @code{daylight}
(to 0 if this timezone does not have any daylight saving time rules, or to
nonzero if there is a time, past, present or future when daylight saving time
applies).

@ref{213f,,Availability}: Unix.

@cartouche
@quotation 注釈 
多くの場合、環境変数 
@geindex TZ
@geindex 環境変数; TZ
@code{TZ} を変更すると、 @ref{3140,,tzset()} を呼ばない限り @ref{1712,,localtime()} のような関数の出力に影響を及ぼすため、値が信頼できなくなってしまいます。

@geindex TZ
@geindex 環境変数; TZ
@code{TZ} 環境変数には空白文字を含めてはなりません。
@end quotation
@end cartouche

環境変数 
@geindex TZ
@geindex 環境変数; TZ
@code{TZ} の標準的な書式は以下の通りです (分かりやすいように空白を入れています):

@example
std offset [dst [offset [,start[/time], end[/time]]]]
@end example

各値は以下のようになっています:


@table @asis

@item @code{std} と @code{dst}

三文字またはそれ以上の英数字で、タイムゾーンの略称を与えます。この値は time.tzname になります。

@item @code{offset}

オフセットは形式: @code{± hh[:mm[:ss]]} をとります。この表現は、UTC 時刻にするためにローカルな時間に加算する必要のある時間値を示します。'-' が先頭につく場合、そのタイムゾーンは本初子午線 (Prime Meridian) より東側にあります。それ以外の場合は本初子午線の西側です。オフセットが dst の後ろに続かない場合、夏時間は標準時より一時間先行しているものと仮定します。

@item @code{start[/time], end[/time]}

いつ DST に移動し、DST から戻ってくるかを示します。開始および終了日時の形式は以下のいずれかです:


@table @asis

@item @code{J@var{n}}

ユリウス日 (Julian day) `n' (1 <= `n' <= 365) を表します。うるう日は計算に含められないため、2 月 28 日は常に 59 で、3 月 1 日は 60 になります。

@item @code{@var{n}}

ゼロから始まるユリウス日 (0 <= `n' <= 365) です。うるう日は計算に含められるため、2 月 29 日を参照することができます。

@item @code{M@var{m}.@var{n}.@var{d}}

`m' 月の週 `n' における `d' 番目の日 (0 <= `d' <= 6, 1 <= `n' <= 5, 1 <= `m' <= 12) を表します。週 5 は月 `m' における最終週の `d' 番目の日を表し、第 4 週か第 5 週のどちらかになります。週 1 は日 `d' が最初に現れる日を指します。日 0 は日曜日です。
@end table

@code{time} は @code{offset} とほぼ同じで、先頭に符号 ('-' や '+') を付けてはいけないところだけが違います。時刻が指定されていなければ、デフォルトの値 02:00:00 になります。
@end table

@example
>>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'02:07:36 05/08/03 EDT'
>>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'
@end example

多くの Unix システム (*BSD, Linux, Solaris, および Darwin を含む) では、システムの zoneinfo (@code{tzfile(5)@footnote{https://manpages.debian.org/tzfile(5)}}) データベースを使ったほうが、タイムゾーンごとの規則を指定する上で便利です。これを行うには、必要なタイムゾーンデータファイルへのパスをシステムの 'zoneinfo' タイムゾーンデータベースからの相対で表した値を環境変数 
@geindex TZ
@geindex 環境変数; TZ
@code{TZ} に設定します。システムの 'zoneinfo' は通常 @code{/usr/share/zoneinfo} にあります。例えば、 @code{'US/Eastern'} 、 @code{'Australia/Melbourne'} 、 @code{'Egypt'}  ないし @code{'Europe/Amsterdam'} と指定します。

@example
>>> os.environ['TZ'] = 'US/Eastern'
>>> time.tzset()
>>> time.tzname
('EST', 'EDT')
>>> os.environ['TZ'] = 'Egypt'
>>> time.tzset()
>>> time.tzname
('EET', 'EEST')
@end example
@end deffn

@node Clock ID Constants,Timezone Constants,関数<5>,time --- 時刻データへのアクセスと変換
@anchor{library/time clock-id-constants}@anchor{3141}@anchor{library/time time-clock-id-constants}@anchor{30ad}
@subsubsection Clock ID Constants


These constants are used as parameters for @ref{1375,,clock_getres()} and
@ref{1376,,clock_gettime()}.

@geindex CLOCK_BOOTTIME (time モジュール)
@anchor{library/time time CLOCK_BOOTTIME}@anchor{d87}
@deffn {データ} time.CLOCK_BOOTTIME

Identical to @ref{8a8,,CLOCK_MONOTONIC}, except it also includes any time that
the system is suspended.

This allows applications to get a suspend-aware monotonic  clock  without
having to deal with the complications of @ref{8a9,,CLOCK_REALTIME}, which may
have  discontinuities if the time is changed using @code{settimeofday()} or
similar.

@ref{213f,,Availability}: Linux >= 2.6.39.


Added in version 3.7.

@end deffn

@geindex CLOCK_HIGHRES (time モジュール)
@anchor{library/time time CLOCK_HIGHRES}@anchor{3142}
@deffn {データ} time.CLOCK_HIGHRES

Solaris OS は任意のハードウェアソースの使用を試み、ナノ秒レベルの分解能を提供する @code{CLOCK_HIGHRES} タイマーを具備しています。@code{CLOCK_HIGHRES} は変更不可で、高分解能のクロックです。

@ref{213f,,Availability}: Solaris.


Added in version 3.3.

@end deffn

@geindex CLOCK_MONOTONIC (time モジュール)
@anchor{library/time time CLOCK_MONOTONIC}@anchor{8a8}
@deffn {データ} time.CLOCK_MONOTONIC

設定不可で、モノトニック時刻 (不特定のエポックからの単調増加な時刻) を表します。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex CLOCK_MONOTONIC_RAW (time モジュール)
@anchor{library/time time CLOCK_MONOTONIC_RAW}@anchor{3143}
@deffn {データ} time.CLOCK_MONOTONIC_RAW

@ref{8a8,,CLOCK_MONOTONIC} と似ていますが、NTP の影響を受けていない、ハードウェアベースの時刻へのアクセスを提供します。

@ref{213f,,Availability}: Linux >= 2.6.28, macOS >= 10.12.


Added in version 3.3.

@end deffn

@geindex CLOCK_MONOTONIC_RAW_APPROX (time モジュール)
@anchor{library/time time CLOCK_MONOTONIC_RAW_APPROX}@anchor{3144}
@deffn {データ} time.CLOCK_MONOTONIC_RAW_APPROX

Similar to @ref{3143,,CLOCK_MONOTONIC_RAW}, but reads a value cached by
the system at context switch and hence has less accuracy.

@ref{213f,,Availability}: macOS >= 10.12.


Added in version 3.13.

@end deffn

@geindex CLOCK_PROCESS_CPUTIME_ID (time モジュール)
@anchor{library/time time CLOCK_PROCESS_CPUTIME_ID}@anchor{3145}
@deffn {データ} time.CLOCK_PROCESS_CPUTIME_ID

CPU による高分解能のプロセスごとのタイマーです。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex CLOCK_PROF (time モジュール)
@anchor{library/time time CLOCK_PROF}@anchor{d88}
@deffn {データ} time.CLOCK_PROF

CPU による高分解能のプロセスごとのタイマーです。

@ref{213f,,Availability}: FreeBSD, NetBSD >= 7, OpenBSD.


Added in version 3.7.

@end deffn

@geindex CLOCK_TAI (time モジュール)
@anchor{library/time time CLOCK_TAI}@anchor{1d57}
@deffn {データ} time.CLOCK_TAI

International Atomic Time@footnote{https://www.nist.gov/pml/time-and-frequency-division/how-utcnist-related-coordinated-universal-time-utc-international}

The system must have a current leap second table in order for this to give
the correct answer.  PTP or NTP software can maintain a leap second table.

@ref{213f,,Availability}: Linux.


Added in version 3.9.

@end deffn

@geindex CLOCK_THREAD_CPUTIME_ID (time モジュール)
@anchor{library/time time CLOCK_THREAD_CPUTIME_ID}@anchor{3146}
@deffn {データ} time.CLOCK_THREAD_CPUTIME_ID

スレッド固有の CPU タイムクロックです。

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@geindex CLOCK_UPTIME (time モジュール)
@anchor{library/time time CLOCK_UPTIME}@anchor{d89}
@deffn {データ} time.CLOCK_UPTIME

Time whose absolute value is the time the system has been running and not
suspended, providing accurate uptime measurement, both absolute and
interval.

@ref{213f,,Availability}: FreeBSD, OpenBSD >= 5.5.


Added in version 3.7.

@end deffn

@geindex CLOCK_UPTIME_RAW (time モジュール)
@anchor{library/time time CLOCK_UPTIME_RAW}@anchor{c37}
@deffn {データ} time.CLOCK_UPTIME_RAW

Clock that increments monotonically, tracking the time since an arbitrary
point, unaffected by frequency or time adjustments and not incremented while
the system is asleep.

@ref{213f,,Availability}: macOS >= 10.12.


Added in version 3.8.

@end deffn

@geindex CLOCK_UPTIME_RAW_APPROX (time モジュール)
@anchor{library/time time CLOCK_UPTIME_RAW_APPROX}@anchor{3147}
@deffn {データ} time.CLOCK_UPTIME_RAW_APPROX

Like @ref{c37,,CLOCK_UPTIME_RAW}, but the value is cached by the system
at context switches and therefore has less accuracy.

@ref{213f,,Availability}: macOS >= 10.12.


Added in version 3.13.

@end deffn

The following constant is the only parameter that can be sent to
@ref{1377,,clock_settime()}.

@geindex CLOCK_REALTIME (time モジュール)
@anchor{library/time time CLOCK_REALTIME}@anchor{8a9}
@deffn {データ} time.CLOCK_REALTIME

Real-time clock.  Setting this clock requires appropriate privileges.
The clock is the same for all processes.

@ref{213f,,Availability}: Unix.


Added in version 3.3.

@end deffn

@node Timezone Constants,,Clock ID Constants,time --- 時刻データへのアクセスと変換
@anchor{library/time time-timezone-constants}@anchor{3148}@anchor{library/time timezone-constants}@anchor{3149}
@subsubsection Timezone Constants


@geindex altzone (time モジュール)
@anchor{library/time time altzone}@anchor{314a}
@deffn {データ} time.altzone

ローカルの夏時間タイムゾーンにおける UTC からの時刻オフセットで、西に行くほど増加する、秒で表した値です (ほとんどの西ヨーロッパでは負になり、アメリカでは正、イギリスではゼロになります)。@code{daylight} がゼロでないときのみ使用してください。以下の注釈を参照してください。
@end deffn

@geindex daylight (time モジュール)
@anchor{library/time time daylight}@anchor{314b}
@deffn {データ} time.daylight

DST タイムゾーンが定義されている場合ゼロでない値になります。以下の注釈を参照してください。
@end deffn

@geindex timezone (time モジュール)
@anchor{library/time time timezone}@anchor{314c}
@deffn {データ} time.timezone

(DST でない) ローカルタイムゾーンの UTC からの時刻オフセットで、西に行くほど増加する秒で表した値です (ほとんどの西ヨーロッパでは負になり、アメリカでは正、イギリスではゼロになります)。以下の注釈を参照してください。
@end deffn

@geindex tzname (time モジュール)
@anchor{library/time time tzname}@anchor{314d}
@deffn {データ} time.tzname

二つの文字列からなるタプルです。最初の要素は DST でないローカルのタイムゾーン名です。ふたつめの要素は DST のタイムゾーンです。DST のタイムゾーンが定義されていない場合。二つ目の文字列を使うべきではありません。以下の注釈を参照してください。
@end deffn

@cartouche
@quotation 注釈 
For the above Timezone constants (@ref{314a,,altzone}, @ref{314b,,daylight}, @ref{314c,,timezone},
and @ref{314d,,tzname}), the value is determined by the timezone rules in effect
at module load time or the last time @ref{3140,,tzset()} is called and may be incorrect
for times in the past.  It is recommended to use the @ref{3133,,tm_gmtoff} and
@ref{3134,,tm_zone} results from @ref{1712,,localtime()} to obtain timezone information.
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@item @ref{34,,datetime} モジュール

日付と時刻に対する、よりオブジェクト指向のインターフェースです。

@item @ref{8a,,locale} モジュール

国際化サービスです。ロケールの設定は @ref{1402,,strftime()} および @ref{1646,,strptime()} の多くの書式指定子の解釈に影響を及ぼします。

@item @ref{15,,calendar} モジュール

一般的なカレンダーに関する関数群です。@ref{2948,,timegm()} はこのモジュールの @ref{13d8,,gmtime()} の逆を行う関数です。
@end table


@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node logging --- Python 用のログ記録手段,logging config --- ログ記録の環境設定,time --- 時刻データへのアクセスと変換,汎用オペレーティングシステムサービス
@anchor{library/logging doc}@anchor{314e}@anchor{library/logging logging-logging-facility-for-python}@anchor{314f}@anchor{library/logging module-logging}@anchor{8b}@anchor{library/logging translation-repo}@anchor{3150}
@subsection @code{logging} --- Python 用のログ記録手段


@geindex module; logging

`ソースコード:' Lib/logging/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/logging/__init__.py}

@geindex エラー;logging

@subsubheading Important



このページには、リファレンス情報だけが含まれています。チュートリアルは、以下のページを参照してください


@itemize *

@item 
@ref{140e,,基本チュートリアル}

@item 
@ref{140f,,上級チュートリアル}

@item 
@ref{1410,,ロギングクックブック}
@end itemize


__________________________________________________________________


このモジュールは、アプリケーションやライブラリのための柔軟なエラーログ記録 (logging) システムを実装するための関数やクラスを定義しています。

標準ライブラリモジュールとしてログ記録 API が提供される利点は、すべての Python モジュールがログ記録に参加できることであり、これによってあなたが書くアプリケーションのログにサードパーティーのモジュールが出力するメッセージを含ませることができます。

以下は慣用的な使い方の単純な例です:

@example
# myapp.py
import logging
import mylib
logger = logging.getLogger(__name__)

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logger.info('Started')
    mylib.do_something()
    logger.info('Finished')

if __name__ == '__main__':
    main()
@end example

@example
# mylib.py
import logging
logger = logging.getLogger(__name__)

def do_something():
    logger.info('Doing something')
@end example

`myapp.py' を実行すれば、`myapp.log' でログが確認できます:

@example
INFO:__main__:Started
INFO:mylib:Doing something
INFO:__main__:Finished
@end example

この慣用的な使い方における重要な特色は、大部分のコードは @code{getLogger(__name__)} で単にモジュールレベルのロガーを作るだけで、そのロガーを必要なロギングに使えるということです。これは簡潔であると同時に、下位のコードにおいて、必要に応じてきめ細やかな制御を可能にしています。モジュールレベルのロガーに対するログメッセージは、最終的にルートロガーとして知られる最上位のロガーに達するまで順次転送されます。ロギングに対するこのようなアプローチは、階層的ロギングとして知られています。

ロギングを有用なものとするためには、用途に応じて構成する必要があります: ログレベルの設定や各ロガーの出力先から、潜在的には特定のモジュールに対する振る舞いの変更などを、しばしばコマンドライン引数かアプリケーションの構成の一部として。上記の例を含めて、ほとんどの場合ではルートロガーのみを構成するだけで十分です。なぜならモジュールレベルの全ての下位のロガーは、全てのメッセージを最終的にルートロガーのハンドラに転送するからです。 @ref{bf3,,basicConfig()} は、多くのユースケースを上手に扱うことのできる簡便なルートロガーの構成方法を提供します。

このモジュールは、多くの機能性と柔軟性を提供します。ロギングに慣れていないなら、使い方を理解する最良の方法はチュートリアルを読むことです (`右上のリンクを参照してください')。

モジュールで定義されている基本的なクラスと、その属性およびメソッドを以下に列挙します。


@itemize *

@item 
ロガーは、アプリケーションコードが直接使うインターフェースを公開します。

@item 
ハンドラは、(ロガーによって生成された) ログ記録を適切な送信先に送ります。

@item 
フィルタは、どのログ記録を出力するかを決定する、きめ細かい機能を提供します。

@item 
フォーマッタは、ログ記録が最終的に出力されるレイアウトを指定します。
@end itemize

@menu
* ロガーオブジェクト:: 
* ロギングレベル:: 
* ハンドラオブジェクト:: 
* フォーマッタオブジェクト:: 
* フィルタオブジェクト:: 
* LogRecord オブジェクト:: 
* LogRecord 属性:: 
* LoggerAdapter オブジェクト:: 
* スレッドセーフ性:: 
* モジュールレベルの関数:: 
* モジュールレベル属性:: 
* warnings モジュールとの統合:: 

@end menu

@node ロガーオブジェクト,ロギングレベル,,logging --- Python 用のログ記録手段
@anchor{library/logging logger}@anchor{3151}@anchor{library/logging logger-objects}@anchor{3152}
@subsubsection ロガーオブジェクト


ロガーには以下のような属性とメソッドがあります。
ロガーを直接インスタンス化することは `絶対に' してはならず、常にモジュール関数 @code{logging.getLogger(name)} を介してインスタンス化することに注意してください。
同じ name で @ref{b59,,getLogger()} を複数回呼び出すと、常に同じロガー・オブジェクトへの参照が返されます。

@code{name} は、潜在的に @code{foo.bar.baz} のようなピリオドで区切られた階層的な値です (ただし、たとえば @code{foo} のような単純な値も可能です)。階層構造の下位にあるロガーは、上位のロガーの子になります。たとえば @code{foo} という名前のロガーに対して、 @code{foo.bar}、 @code{foo.bar.baz}、 @code{foo.bam} という名前のロガーは全て @code{foo} の子孫です。さらに、全てのロガーはルートロガーの子孫です。ロガー名の階層構造は Python パッケージの階層構造に類似しています。また、推奨される構築方法である @code{logging.getLogger(__name__)} を使ってモジュール単位でロガーを構築すれば、パッケージの階層構造とロガーの階層構造は同一になります。なぜなら、モジュールの中で、 @code{__name__} は Python パッケージの名前空間におけるモジュール名だからです。

@geindex Logger (logging のクラス)
@anchor{library/logging logging Logger}@anchor{d46}
@deffn {クラス} logging.Logger

@geindex name (logging.Logger の属性)
@anchor{library/logging logging Logger name}@anchor{3153}
@deffn {の属性} name

ロガーの名前です。また、ロガーを取得するために @ref{b59,,getLogger()} を呼び出すときに渡された値です。

@cartouche
@quotation 注釈 
この属性は読み出し専用として扱われるべきです。
@end quotation
@end cartouche
@end deffn

@geindex level (logging.Logger の属性)
@anchor{library/logging logging Logger level}@anchor{3154}
@deffn {の属性} level

@ref{16ac,,setLevel()} メソッドで設定された、このロガーのしきい値です。

@cartouche
@quotation 注釈 
この属性を直接設定しないでください -  @ref{16ac,,setLevel()} は渡されたレベルをチェックする機能を持っていますので、常にこのメソッドを使うようにしてください。
@end quotation
@end cartouche
@end deffn

@geindex parent (logging.Logger の属性)
@anchor{library/logging logging Logger parent}@anchor{3155}
@deffn {の属性} parent

このロガーの親にあたるロガーです。名前空間の階層構造で上位にあたるロガーのインスタンス化により、親ロガーは変わる可能性があります。

@cartouche
@quotation 注釈 
この値は読み出し専用として取り扱われるべきです。
@end quotation
@end cartouche
@end deffn

@geindex propagate (logging.Logger の属性)
@anchor{library/logging logging Logger propagate}@anchor{16ae}
@deffn {の属性} propagate

この属性が真と評価された場合、このロガーに記録されたイベントは、このロガーに取り付けられた全てのハンドラに加え、上位 (祖先) ロガーのハンドラにも渡されます。
メッセージは、祖先ロガーのハンドラに直接渡されます - 今問題にしている祖先ロガーのレベルもフィルタも、どちらも考慮されません。

この値の評価結果が偽になる場合、ロギングメッセージは祖先ロガーのハンドラに渡されません。

具体的な例で説明します: @code{A.B.C} という名前のロガーの propagate 属性が真と評価された場合、 @code{logging.getLogger('A.B.C').error(...)} のようなメソッドの呼び出しを通じて @code{A.B.C} に記録された全てのイベントは、 [ログレベルとフィルタの設定を満たした場合に限り] 最初に @code{A.B.C} に接続されたハンドラに渡され、その後 @code{A.B}, @code{A} という名前のロガー、そしてルートロガーという順番で各ロガーに接続されたハンドラに渡されます。この連鎖構造において @code{A.B.C}, @code{A.B}, @code{A} のいずれかの @code{propagate} 属性が偽に設定された場合、そのロガーがイベントを処理する最後のロガーとなり、その時点でイベントの伝播は止まります。

コンストラクタはこの属性を @code{True} に設定します。

@cartouche
@quotation 注釈 
ハンドラを、あるロガー `と' その祖先のロガーに接続した場合、同一レコードが複数回発行される場合があります。一般的に、ハンドラを複数のロガーに接続する必要はありません。propagate 設定が @code{True} のままになっていれば、ロガーの階層において最上位にある適切なロガーにハンドラを接続するだけで、そのハンドラは全ての子孫ロガーが記録する全てのイベントを確認することができます。一般的なシナリオでは、ハンドラをルートロガーに対してのみ接続し、残りは propagate にすべて委ねます。
@end quotation
@end cartouche
@end deffn

@geindex handlers (logging.Logger の属性)
@anchor{library/logging logging Logger handlers}@anchor{3156}
@deffn {の属性} handlers

このロガーインスタンスに直接接続されているハンドラのリストです。

@cartouche
@quotation 注釈 
この属性は読み出し専用として取り扱われるべきです; 通常この属性は @ref{3157,,addHandler()} と @ref{3158,,removeHandler()} の2つのメソッドを介して変更されます。これらのメソッドはスレッドセーフな処理を保証するためにロックを活用します。
@end quotation
@end cartouche
@end deffn

@geindex disabled (logging.Logger の属性)
@anchor{library/logging logging Logger disabled}@anchor{3159}
@deffn {の属性} disabled

この属性は、いかなるイベントの処理も作動しないようにします。イニシャライザはこの属性に @code{False} を設定します。また、この属性はロギングを設定するコードによってのみ変更されます。

@cartouche
@quotation 注釈 
この属性は読み出し専用として扱われるべきです。
@end quotation
@end cartouche
@end deffn

@geindex setLevel() (logging.Logger のメソッド)
@anchor{library/logging logging Logger setLevel}@anchor{16ac}
@deffn {メソッド} setLevel (level)

このロガーの閾値を `level' に設定します。
`level' よりも深刻でないログメッセージは無視されます; 深刻さが `level' 以上のログメッセージは、ハンドラのレベルが `level' より上に設定されていない限り、このロガーに取り付けられているハンドラによって投げられます。

ロガーが生成された際、レベルは @ref{315a,,NOTSET} (これによりすべてのメッセージについて、ロガーがルートロガーであれば処理される、そうでなくてロガーが非ルートロガーの場合には親ロガーに委譲させる) に設定されます。
ルートロガーは @ref{20e0,,WARNING} レベルで生成されることに注意してください。

「親ロガーに委譲」という用語の意味は、もしロガーのレベルが NOTSET ならば、祖先ロガーの系列の中を NOTSET 以外のレベルの祖先を見つけるかルートに到達するまで辿っていく、ということです。

もし NOTSET 以外のレベルの祖先が見つかったなら、その祖先のレベルが探索を開始したロガーの実効レベルとして扱われ、ログイベントがどのように処理されるかを決めるのに使われます。

ルートに到達した場合、ルートのレベルが NOTSET ならばすべてのメッセージは処理されます。そうでなければルートのレベルが実効レベルとして使われます。

レベルの一覧については @ref{86a,,ロギングレベル} を参照してください。


バージョン 3.2 で変更: `level' パラメータは、 @ref{20df,,INFO} のような整数定数の代わりに 'INFO' のようなレベルの文字列表現も受け付けるようになりました。ただし、レベルは内部で整数として保存されますし、 @ref{315b,,getEffectiveLevel()} や @ref{150e,,isEnabledFor()} といったメソッドは、整数を返し、また渡されるものと期待します。

@end deffn

@geindex isEnabledFor() (logging.Logger のメソッド)
@anchor{library/logging logging Logger isEnabledFor}@anchor{150e}
@deffn {メソッド} isEnabledFor (level)

深刻度が `lvl' のメッセージが、このロガーで処理されることになっているかどうかを示します。このメソッドはまず、 @code{logging.disable(level)} で設定されるモジュールレベルの深刻度レベルを調べ、次にロガーの実効レベルを @ref{315b,,getEffectiveLevel()} で調べます。
@end deffn

@geindex getEffectiveLevel() (logging.Logger のメソッド)
@anchor{library/logging logging Logger getEffectiveLevel}@anchor{315b}
@deffn {メソッド} getEffectiveLevel ()

このロガーの実効レベルを示します。 @ref{315a,,NOTSET} 以外の値が @ref{16ac,,setLevel()} で設定されていた場合、その値が返されます。そうでない場合、 @ref{315a,,NOTSET} 以外の値が見つかるまでロガーの階層をルートロガーの方向に追跡します。見つかった場合、その値が返されます。返される値は整数で、典型的には @ref{20de,,logging.DEBUG}, @ref{20df,,logging.INFO} 等のうち一つです。
@end deffn

@geindex getChild() (logging.Logger のメソッド)
@anchor{library/logging logging Logger getChild}@anchor{150c}
@deffn {メソッド} getChild (suffix)

このロガーの子であるロガーを、接頭辞によって決定し、返します。従って、@code{logging.getLogger('abc').getChild('def.ghi')} は、@code{logging.getLogger('abc.def.ghi')} によって返されるのと同じロガーを返すことになります。これは簡便なメソッドで、親ロガーがリテラルでなく @code{__name__} などを使って名付けられているときに便利です。


Added in version 3.2.

@end deffn

@geindex getChildren() (logging.Logger のメソッド)
@anchor{library/logging logging Logger getChildren}@anchor{1b52}
@deffn {メソッド} getChildren ()

このロガーの直接の子であるロガーの集合を返します。したがって、たとえば @code{logging.getLogger().getChildren()} は @code{foo} や @code{bar} といった名前のロガーを含む集合を返すかもしれませんが、 @code{foo.bar} という名前のロガーは戻り値の集合には含まれません。同様に、 @code{logging.getLogger('foo').getChildren()} は @code{foo.bar} という名前のロガーを含む集合を返すかもしれませんが、 @code{foo.bar.baz} のような名前のロガーは戻り値の集合には含まれません。


Added in version 3.12.

@end deffn

@geindex debug() (logging.Logger のメソッド)
@anchor{library/logging logging Logger debug}@anchor{102b}
@deffn {メソッド} debug (msg, *args, **kwargs)

レベル @ref{20de,,DEBUG} のメッセージをこのロガーで記録します。 `msg' はメッセージの書式文字列で、 `args' は `msg' に文字列書式化演算子を使って取り込むための引数です。 (これは、書式化文字列の中でキーワードを使い、引数として単一の辞書を渡すことができる、ということを意味します。) `args' が提供されない場合は `msg' の%フォーマットは実行されません。

`kwargs' のうち、 `exc_info', `stack_info', `stacklevel', `extra' という4つのキーワード引数の中身を調べます。

`exc_info' は、この値の評価値が false でない場合、例外情報がロギングメッセージに追加されます。もし例外情報をあらわすタプル(@ref{89a,,sys.exc_info()} 関数によって戻されるフォーマットにおいて)、または、例外情報をあらわすインスタンスが与えられていれば、それが使用されることになります。それ以外の場合には、 @ref{89a,,sys.exc_info()} を呼び出して例外情報を取得します。

2つ目の省略可能なキーワード引数は `stack_info' で、デフォルトは @code{False} です。真の場合、実際のロギング呼び出しを含むスタック情報がロギングメッセージに追加されます。これは `exc_info' 指定によって表示されるスタック情報と同じものではないことに注意してください: 前者はカレントスレッド内での、一番下からロギング呼び出しまでのスタックフレームですが、後者は例外に呼応して、例外ハンドラが見つかるところまで巻き戻されたスタックフレームの情報です。

`exc_info' とは独立に `stack_info' を指定することもできます (例えば、例外が上げられなかった場合でも、コード中のある地点にどのように到着したかを単に示すために)。スタックフレームは、次のようなヘッダー行に続いて表示されます:

@example
Stack (most recent call last):
@end example

これは、例外フレームを表示する場合に使用される @code{Traceback (most recent call last):} を模倣します。

3番目のオプションキーワード引数は `stacklevel' で、デフォルトは @code{1} です。もしこれが1よりも大きい場合は、 @ref{11e8,,LogRecord} 内で行番号と関数名を算出する時に、指定されたスタックフレームの数をスキップします。これはログヘルパー内部で使われる場合、関数名、ファイル名、行番号はそのヘルパーの情報ではなく、そのヘルパーを呼び出した呼び出し元のものになります。このパラメータの名前は @ref{118,,warnings} モジュールと同じものになります。

4番目のキーワード引数は `extra' で、ロギングイベントの際に作られる @ref{11e8,,LogRecord} の @ref{77d,,__dict__} 属性に、ユーザー定義の属性を追加するための辞書を渡すのに使うことができます。これら追加の属性は、好きなように使うことができます。たとえば、それらをログメッセージに埋め込むことができます。使用例:

@example
FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = @{'clientip': '192.168.0.1', 'user': 'fbloggs'@}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)
@end example

これは以下のような出力を行います

@example
2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
@end example

`extra' に渡される辞書のキーはロギングシステムで使われているものと衝突してはいけません。 (ロギングシステムが使うキーの詳細については @ref{315c,,LogRecord 属性} の節を参照してください。)

これらの属性をログメッセージに使うことにしたなら、少し注意が必要です。上の例では、 'clientip' と 'user' が @ref{11e8,,LogRecord} の属性辞書に含まれていることを期待した書式文字列で @ref{16b0,,Formatter} がセットアップされています。もしこれらが欠けていると、書式化例外が発生してしまうためメッセージはログに残りません。したがってこの場合、常にこれらのキーを含む `extra' 辞書を渡す必要があります。

このようなことは煩わしいかもしれませんが、この機能は限定された場面で使われるように意図しているものなのです。たとえば同じコードがいくつものコンテキストで実行されるマルチスレッドのサーバで、興味のある条件が現れるのがそのコンテキストに依存している (上の例で言えば、リモートのクライアント IP アドレスや認証されたユーザ名など)、というような場合です。そういった場面では、それ用の @ref{16b0,,Formatter} が特定の @ref{16af,,Handler} と共に使われるというのはよくあることです。

このロガー (および @ref{16ae,,Logger.propagate} 属性を考慮した上で実効的にイベントが伝播する祖先のロガー) にハンドラが接続されていない場合、メッセージは @ref{1413,,lastResort} に設定されたハンドラーに送られます。


バージョン 3.2 で変更: `stack_info' パラメータが追加されました。



バージョン 3.5 で変更: `exc_info' パラメータは例外インスタンスを受け入れることが可能です。



バージョン 3.8 で変更: `stacklevel' 引数が追加されました。

@end deffn

@geindex info() (logging.Logger のメソッド)
@anchor{library/logging logging Logger info}@anchor{20dd}
@deffn {メソッド} info (msg, *args, **kwargs)

レベル @ref{20df,,INFO} のメッセージをこのロガーで記録します。引数は @ref{315d,,debug()} と同じように解釈されます。
@end deffn

@geindex warning() (logging.Logger のメソッド)
@anchor{library/logging logging Logger warning}@anchor{1a74}
@deffn {メソッド} warning (msg, *args, **kwargs)

レベル @ref{20e0,,WARNING} のメッセージをこのロガーで記録します。引数は @ref{315d,,debug()} と同じように解釈されます。

@cartouche
@quotation 注釈 
@code{warning} と機能的に等価な古いメソッド @code{warn} があります。@code{warn} は廃止予定なので使わないでください - 代わりに @code{warning} を使ってください。
@end quotation
@end cartouche
@end deffn

@geindex error() (logging.Logger のメソッド)
@anchor{library/logging logging Logger error}@anchor{315e}
@deffn {メソッド} error (msg, *args, **kwargs)

レベル @ref{20e1,,ERROR} のメッセージをこのロガーで記録します。引数は @ref{315d,,debug()} と同じように解釈されます。
@end deffn

@geindex critical() (logging.Logger のメソッド)
@anchor{library/logging logging Logger critical}@anchor{102a}
@deffn {メソッド} critical (msg, *args, **kwargs)

レベル @ref{20e2,,CRITICAL} のメッセージをこのロガーで記録します。引数は @ref{315d,,debug()} と同じように解釈されます。
@end deffn

@geindex log() (logging.Logger のメソッド)
@anchor{library/logging logging Logger log}@anchor{1028}
@deffn {メソッド} log (level, msg, *args, **kwargs)

整数で表したレベル `level' のメッセージをこのロガーで記録します。その他の引数は @ref{315d,,debug()} と同じように解釈されます。
@end deffn

@geindex exception() (logging.Logger のメソッド)
@anchor{library/logging logging Logger exception}@anchor{1029}
@deffn {メソッド} exception (msg, *args, **kwargs)

レベル @ref{20e1,,ERROR} のメッセージをこのロガーで記録します。引数は @ref{315d,,debug()} と同じように解釈されます。例外情報がログメッセージに追加されます。このメソッドは例外ハンドラからのみ呼び出されるべきです。
@end deffn

@geindex addFilter() (logging.Logger のメソッド)
@anchor{library/logging logging Logger addFilter}@anchor{315f}
@deffn {メソッド} addFilter (filter)

指定されたフィルタ `filter' をこのロガーに追加します。
@end deffn

@geindex removeFilter() (logging.Logger のメソッド)
@anchor{library/logging logging Logger removeFilter}@anchor{3160}
@deffn {メソッド} removeFilter (filter)

指定されたフィルタ `filter' をこのロガーから取り除きます。
@end deffn

@geindex filter() (logging.Logger のメソッド)
@anchor{library/logging logging Logger filter}@anchor{3161}
@deffn {メソッド} filter (record)

レコードに対してこのロガーのフィルタを適用し、レコードが処理されるべき場合に @code{True} を返します。フィルタのいずれかの値が偽を返すまで、それらは順番に試されていきます。いずれも偽を返さなければ、レコードは処理される(ハンドラに渡される)ことになります。ひとつでも偽を返せば、発生したレコードはもはや処理されることはありません。
@end deffn

@geindex addHandler() (logging.Logger のメソッド)
@anchor{library/logging logging Logger addHandler}@anchor{3157}
@deffn {メソッド} addHandler (hdlr)

指定されたハンドラ `hdlr' をこのロガーに追加します。
@end deffn

@geindex removeHandler() (logging.Logger のメソッド)
@anchor{library/logging logging Logger removeHandler}@anchor{3158}
@deffn {メソッド} removeHandler (hdlr)

指定されたハンドラ `hdlr' をこのロガーから取り除きます。
@end deffn

@geindex findCaller() (logging.Logger のメソッド)
@anchor{library/logging logging Logger findCaller}@anchor{3162}
@deffn {メソッド} findCaller (stack_info=False, stacklevel=1)

呼び出し元のソースファイル名と行番号を調べます。ファイル名と行番号、関数名、スタック情報を 4 要素のタプルで返します。`stack_info' が @code{True} でなければ、スタック情報は @code{None} が返されます。

`stacklevel' パラメータは @ref{315d,,debug()} や他のAPIを呼び出すコードから渡されます。もしこれが1よりも大きい場合は、その超過分は返す値を決定する前にスタックフレームをスキップする数として利用されます。これは通常、ログAPIをヘルパーやラッパー経由で呼び出す場合に便利です。こうすることで、イベントログに記録される情報はヘルパーやラッパーのコードではなく、それらを呼び出しているコードのものとなります。
@end deffn

@geindex handle() (logging.Logger のメソッド)
@anchor{library/logging logging Logger handle}@anchor{3163}
@deffn {メソッド} handle (record)

レコードを、このロガーおよびその上位ロガー (ただし `propagate' の値が false になったところまで) に関連付けられているすべてのハンドラに渡して処理します。このメソッドは、ローカルで生成されたレコードだけでなく、ソケットから受信した unpickle されたレコードに対しても同様に用いられます。 @ref{3161,,filter()} によって、ロガーレベルでのフィルタが適用されます。
@end deffn

@geindex makeRecord() (logging.Logger のメソッド)
@anchor{library/logging logging Logger makeRecord}@anchor{3164}
@deffn {メソッド} makeRecord (name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

このメソッドは、特殊な @ref{11e8,,LogRecord} インスタンスを生成するためにサブクラスでオーバライドできるファクトリメソッドです。
@end deffn

@geindex hasHandlers() (logging.Logger のメソッド)
@anchor{library/logging logging Logger hasHandlers}@anchor{3165}
@deffn {メソッド} hasHandlers ()

このロガーにハンドラが設定されているかどうかを調べます。
そのために、このロガーとロガー階層における祖先からハンドラを探します。
ハンドラが見つかれば @code{True} 、そうでなければ @code{False} を返します。
このメソッドは、'propagate' 属性が偽に設定されたロガーを見つけると、さらに上位の探索をやめます。そのロガーが、ハンドラが存在するかどうかチェックされる最後のロガーになります。


Added in version 3.2.

@end deffn


バージョン 3.7 で変更: ロガーの pickle 化と unpickle 化ができるようになりました。

@end deffn

@node ロギングレベル,ハンドラオブジェクト,ロガーオブジェクト,logging --- Python 用のログ記録手段
@anchor{library/logging levels}@anchor{86a}@anchor{library/logging logging-levels}@anchor{3166}
@subsubsection ロギングレベル


ログレベルの数値は以下の表のように与えられています。これらは基本的に自分でレベルを定義したい人のためのもので、定義するレベルを既存のレベルの間に位置づけるためには具体的な値が必要になります。もし数値が他のレベルと同じだったら、既存の値は上書きされその名前は失われます。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

レベル

@tab

数値

@tab

どういう意味か / いつ使用するべきか

@item

@geindex NOTSET (logging モジュール)
@anchor{library/logging logging NOTSET}@anchor{315a}
@deffn {データ} logging.NOTSET
@end deffn

@tab

0

@tab

ロガーに対してこのレベルが設定された場合、実際のログレベルは祖先のロガーを参照して決めることを意味します。実効ログレベルも @code{NOTSET} となった場合は、全てのイベントが記録されます。ハンドラーに対してこのレベルが設定された場合、全てのイベントが処理されます。

@item

@geindex DEBUG (logging モジュール)
@anchor{library/logging logging DEBUG}@anchor{20de}
@deffn {データ} logging.DEBUG
@end deffn

@tab

10

@tab

詳細情報。典型的には、問題が発生した際に原因を突き止めようとする開発者向けの情報。

@item

@geindex INFO (logging モジュール)
@anchor{library/logging logging INFO}@anchor{20df}
@deffn {データ} logging.INFO
@end deffn

@tab

20

@tab

想定された通りのことが起こったことの確認。

@item

@geindex WARNING (logging モジュール)
@anchor{library/logging logging WARNING}@anchor{20e0}
@deffn {データ} logging.WARNING
@end deffn

@tab

30

@tab

想定外の事象、または近い将来に問題が起きる可能性 (たとえば 'disk space low' すなわちディスク空き容量の低下) の表示。ソフトウエアは引き続き期待通りに動作している状態。

@item

@geindex ERROR (logging モジュール)
@anchor{library/logging logging ERROR}@anchor{20e1}
@deffn {データ} logging.ERROR
@end deffn

@tab

40

@tab

より重大な問題により、ソフトウェアがある機能を実行できないこと。

@item

@geindex CRITICAL (logging モジュール)
@anchor{library/logging logging CRITICAL}@anchor{20e2}
@deffn {データ} logging.CRITICAL
@end deffn

@tab

50

@tab

プログラム自体が実行を続けられないことを表す、重大なエラー。

@end multitable


@node ハンドラオブジェクト,フォーマッタオブジェクト,ロギングレベル,logging --- Python 用のログ記録手段
@anchor{library/logging handler}@anchor{3167}@anchor{library/logging handler-objects}@anchor{3168}
@subsubsection ハンドラオブジェクト


ハンドラ (Handler) は以下の属性とメソッドを持ちます。 @ref{16af,,Handler} は直接インスタンス化されることはありません; このクラスはより便利なサブクラスの基底クラスとして働きます。しかしながら、サブクラスにおける @code{__init__()} メソッドでは、 @ref{3169,,Handler.__init__()} を呼び出す必要があります。

@geindex Handler (logging のクラス)
@anchor{library/logging logging Handler}@anchor{16af}
@deffn {クラス} logging.Handler

@geindex __init__() (logging.Handler のメソッド)
@anchor{library/logging logging Handler __init__}@anchor{3169}
@deffn {メソッド} __init__ (level=NOTSET)

レベルを設定して、 @ref{16af,,Handler} インスタンスを初期化します。空のリストを使ってフィルタを設定し、 I/O 機構へのアクセスを直列化するために (@ref{316a,,createLock()} を使って) ロックを生成します。
@end deffn

@geindex createLock() (logging.Handler のメソッド)
@anchor{library/logging logging Handler createLock}@anchor{316a}
@deffn {メソッド} createLock ()

スレッドセーフでない背後の I/O 機能に対するアクセスを直列化するために用いられるスレッドロック (thread lock) を初期化します。
@end deffn

@geindex acquire() (logging.Handler のメソッド)
@anchor{library/logging logging Handler acquire}@anchor{316b}
@deffn {メソッド} acquire ()

@ref{316a,,createLock()} で生成されたスレッドロックを獲得します。
@end deffn

@geindex release() (logging.Handler のメソッド)
@anchor{library/logging logging Handler release}@anchor{316c}
@deffn {メソッド} release ()

@ref{316b,,acquire()} で獲得したスレッドロックを解放します。
@end deffn

@geindex setLevel() (logging.Handler のメソッド)
@anchor{library/logging logging Handler setLevel}@anchor{316d}
@deffn {メソッド} setLevel (level)

このハンドラに対する閾値を `level' に設定します。
`level' よりも深刻でないログメッセージは無視されます。
ハンドラが生成された際、レベルは @ref{315a,,NOTSET} (すべてのメッセージが処理される) に設定されます。

レベルの一覧については @ref{86a,,ロギングレベル} を参照してください。


バージョン 3.2 で変更: `level' パラメータは、 @ref{20df,,INFO} のような整数定数の代わりに 'INFO' のようなレベルの文字列表現も受け付けるようになりました。

@end deffn

@geindex setFormatter() (logging.Handler のメソッド)
@anchor{library/logging logging Handler setFormatter}@anchor{316e}
@deffn {メソッド} setFormatter (fmt)

Sets the formatter for this handler to `fmt'.
The `fmt' argument must be a @ref{16b0,,Formatter} instance or @code{None}.
@end deffn

@geindex addFilter() (logging.Handler のメソッド)
@anchor{library/logging logging Handler addFilter}@anchor{316f}
@deffn {メソッド} addFilter (filter)

指定されたフィルタ `filter' をこのハンドラに追加します。
@end deffn

@geindex removeFilter() (logging.Handler のメソッド)
@anchor{library/logging logging Handler removeFilter}@anchor{3170}
@deffn {メソッド} removeFilter (filter)

指定されたフィルタ `filter' をこのハンドラから除去します。
@end deffn

@geindex filter() (logging.Handler のメソッド)
@anchor{library/logging logging Handler filter}@anchor{3171}
@deffn {メソッド} filter (record)

レコードに対してこのハンドラのフィルタを適用し、レコードが処理されるべき場合に @code{True} を返します。フィルタのいずれかの値が偽を返すまで、それらは順番に試されていきます。いずれも偽を返さなければ、レコードは発行されることになります。ひとつでも偽を返せば、ハンドラはレコードを発行しません。
@end deffn

@geindex flush() (logging.Handler のメソッド)
@anchor{library/logging logging Handler flush}@anchor{3172}
@deffn {メソッド} flush ()

すべてのログ出力がフラッシュされるようにします。このクラスのバージョンではなにも行わず、サブクラスで実装するためのものです。
@end deffn

@geindex close() (logging.Handler のメソッド)
@anchor{library/logging logging Handler close}@anchor{3173}
@deffn {メソッド} close ()

Tidy up any resources used by the handler. This version does no output
but removes the handler from an internal map of handlers, which is used
for handler lookup by name.

Subclasses should ensure that this gets called from overridden @ref{3173,,close()}
methods.
@end deffn

@geindex handle() (logging.Handler のメソッド)
@anchor{library/logging logging Handler handle}@anchor{3174}
@deffn {メソッド} handle (record)

ハンドラに追加されたフィルタの条件に応じて、指定されたログレコードを出力します。このメソッドは I/O スレッドロックの獲得/解放を伴う実際のログ出力をラップします。
@end deffn

@geindex handleError() (logging.Handler のメソッド)
@anchor{library/logging logging Handler handleError}@anchor{3175}
@deffn {メソッド} handleError (record)

このメソッドは、 @ref{3176,,emit()} の呼び出し中に例外に遭遇した際にハンドラから呼び出されることを想定しています。モジュールレベルの属性 @ref{1412,,raiseExceptions} が @code{False} の場合、例外は静かに無視されます。これは、ほとんどの場合でロギングシステムに期待される挙動です - なぜなら、ほとんどのユーザーはロギングシステムの中で起こったエラーなどに興味はなく、アプリケーションエラーの方により関心があるからです。しかし、必要ならばこの挙動を自作のハンドラで置き換えることができます。引数に指定されたレコードは例外発生時に処理されるものです。 (@ref{1412,,raiseExceptions} のデフォルト値は、開発中にはその方が便利なので、 @code{True} です)。
@end deffn

@geindex format() (logging.Handler のメソッド)
@anchor{library/logging logging Handler format}@anchor{3177}
@deffn {メソッド} format (record)

レコードに対する書式化を行います - フォーマッタが設定されていれば、それを使います。そうでない場合、モジュールにデフォルト指定されたフォーマッタを使います。
@end deffn

@geindex emit() (logging.Handler のメソッド)
@anchor{library/logging logging Handler emit}@anchor{3176}
@deffn {メソッド} emit (record)

指定されたログ記録レコードを実際にログ記録する際のすべての処理を行います。このメソッドはサブクラスで実装されることを意図しており、そのためこのクラスのバージョンは @ref{36b,,NotImplementedError} を送出します。

@cartouche
@quotation 警告 
このメソッドはハンドラレベルのロックを取得した後で呼び出されます。また、ロックはこのメソッドがリターンした後で解放されます。このメソッドをオーバーライドする場合、ロックを取得する可能性のある logging API の他の関数やメソッドの呼び出しに注意してください。そのような実装はデッドロックを引き起こす可能性があります。特に以下の点に注意してください:


@itemize *

@item 
ロギングを構成するための API はモジュールレベルのロックを取得し、その後ハンドラを構成する際に個々のハンドラに対してハンドラレベルのロックを取得します。

@item 
多くのロギング API はモジュールレベルのロックを取得します。そのような API がこのメソッドから呼ばれた場合、他のスレッドからロギングを構成するための API 呼び出しが行われたときにデッドロックに陥る可能性があります。これは他のスレッドがハンドラレベルのロックを取得する `前に' モジュールレベルのロックを取得しようとする一方で、 (このメソッドはハンドラレベルのロックが既に取得された状態で呼び出されているため) このメソッドを呼び出したスレッドはハンドラレベルのロックを取得した `後で' モジュールレベルのロックを取得しようとするためです。
@end itemize
@end quotation
@end cartouche
@end deffn
@end deffn

標準として含まれているハンドラについては、 @ref{8d,,logging.handlers} を参照してください。

@node フォーマッタオブジェクト,フィルタオブジェクト,ハンドラオブジェクト,logging --- Python 用のログ記録手段
@anchor{library/logging formatter-objects}@anchor{3178}@anchor{library/logging id1}@anchor{3179}
@subsubsection フォーマッタオブジェクト


@geindex Formatter (logging のクラス)
@anchor{library/logging logging Formatter}@anchor{16b0}
@deffn {クラス} logging.Formatter (fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)

@ref{11e8,,LogRecord} を、人間または外部のシステムが解釈可能な出力文字列に変換する責任を持ちます。

@*パラメータ: 

@itemize *

@item 
@code{fmt} (@ref{169,,str}) -- `style' で指定された書式にもとづく、出力ログ全体に対する書式文字列です。マッピングのキーは @ref{11e8,,LogRecord} オブジェクトの @ref{315c,,LogRecord 属性} から取り出されます。特に指定がない場合は、ログメッセージをあらわす @code{'%(message)s'} が使われます。

@item 
@code{datefmt} (@ref{169,,str}) -- A format string for the date/time portion of the logged output.
If not specified, the default described in @ref{317a,,formatTime()} is used.

@item 
@code{style} (@ref{169,,str}) -- @code{'%'},  または @code{'$'} のいずれかで、書式文字列がログデータとどのようにマージされるかを決めます: @ref{8db,,printf 形式の文字列書式化} (@code{%}), @ref{833,,str.format()} (@code{@{}) または @ref{897,,string.Template} () のいずれかを使います。この引数は `fmt' だけに適用されます (たとえば @code{'%(message)s'} に対して @code{'@{message@}'}) が、ロギングメソッドに渡された実際のログメッセージには適用されません。いっぽう、 @code{'@{'} や @code{$} を使ってログメッセージをフォーマットする @ref{317b,,他の方法} も存在します。

@item 
@code{validate} (@ref{3c3,,bool}) -- @code{True} が指定されると (デフォルト) 、 `fmt' と `style' が不正な場合や、それらが不適切な組み合わせだった場合に @ref{2ec,,ValueError} 例外を送出します; たとえば @code{logging.Formatter('%(asctime)s - %(message)s', style='@{')} は例外となります。

@item 
@code{defaults} (@ref{183,,dict}@code{[}@ref{169,,str}@code{, }@code{Any}@code{]}) -- カスタムフィールドに使用されるデフォルト値を指定する辞書です。例えば @code{logging.Formatter('%(ip)s %(message)s', defaults=@{"ip": None@})} のように使います。
@end itemize



バージョン 3.2 で変更: `style' パラメータが追加されました。



バージョン 3.8 で変更: `validate' パラメータが追加されました。



バージョン 3.10 で変更: `defaults' パラメータが追加されました。


@geindex format() (logging.Formatter のメソッド)
@anchor{library/logging logging Formatter format}@anchor{317c}
@deffn {メソッド} format (record)

レコードの属性辞書が、文字列を書式化する演算で被演算子として使われます。書式化された結果の文字列を返します。辞書を書式化する前に、二つの準備段階を経ます。レコードの `message' 属性が `msg' % `args' を使って処理されます。書式化された文字列が @code{'(asctime)'} を含むなら、 @ref{317a,,formatTime()} が呼び出され、イベントの発生時刻を書式化します。例外情報が存在する場合、 @ref{317d,,formatException()} を使って書式化され、メッセージに追加されます。ここで注意していただきたいのは、書式化された例外情報は `exc_text' にキャッシュされるという点です。これが有用なのは例外情報がピックル化されて回線上を送ることができるからですが、しかし二つ以上の @ref{16b0,,Formatter} サブクラスで例外情報の書式化をカスタマイズしている場合には注意が必要になります。この場合、フォーマッタが書式化を終えるごとにキャッシュをクリアして（ `ext_text' 属性に @code{None} を設定して）、次のフォーマッタがキャッシュされた値を使わずに新鮮な状態で再計算するようにしなければならないことになります。

スタック情報が利用可能な場合、(必要ならば @ref{317e,,formatStack()} を使って整形した上で) スタック情報が例外情報の後に追加されます。
@end deffn

@geindex formatTime() (logging.Formatter のメソッド)
@anchor{library/logging logging Formatter formatTime}@anchor{317a}
@deffn {メソッド} formatTime (record, datefmt=None)

このメソッドは、フォーマッタが書式化された時間を利用したい際に、 @ref{199,,format()} から呼び出されます。
このメソッドは特定の要求を提供するためにフォーマッタで上書きすることができますが、基本的な振る舞いは以下のようになります: `datefmt' (文字列) が指定された場合、レコードが生成された時刻を書式化するために @ref{1402,,time.strftime()} で使われます。
そうでない場合、 '%Y-%m-%d %H:%M:%S,uuu' というフォーマットが使われます。 uuu 部分はミリ秒値で、それ以外の文字は @ref{1402,,time.strftime()} ドキュメントに従います。
このフォーマットの時刻の例は @code{2003-01-23 00:29:50,411} です。
結果の文字列が返されます。

この関数は、ユーザが設定できる関数を使って、生成時刻をタプルに変換します。デフォルトでは、 @ref{1712,,time.localtime()} が使われます。特定のフォーマッタインスタンスに対してこれを変更するには、 @code{converter} 属性を @ref{1712,,time.localtime()} や @ref{13d8,,time.gmtime()} と同じ署名をもつ関数に設定してください。すべてのフォーマッタインスタンスに対してこれを変更するには、例えば全てのロギング時刻を GMT で表示するには、 @code{Formatter} クラスの @code{converter} 属性を設定してください。


バージョン 3.3 で変更: 以前は、デフォルトのフォーマットがこの例のようにハードコーディングされていました: @code{2010-09-06 22:38:15,292} ここで、コンマの前の部分は strptime フォーマット文字列 (@code{'%Y-%m-%d %H:%M:%S'}) によって扱われる部分で、コンマの後の部分はミリ秒値です。strptime にミリ秒のフォーマットプレースホルダーがないので、ミリ秒値は別のフォーマット文字列 @code{'%s,%03d'} を使用して追加されます。そして、これらのフォーマット文字列は両方ともこのメソッドでハードコーディングされていました。変更後は、これらの文字列はクラスレベル属性として定義され、必要ならインスタンスレベルでオーバーライドすることができます。属性の名前は @code{default_time_format} (strptime 書式文字列用) と @code{default_msec_format} (ミリ秒値の追加用) です。



バージョン 3.9 で変更: @code{default_msec_format} 引数が @code{None} であることを許容します。

@end deffn

@geindex formatException() (logging.Formatter のメソッド)
@anchor{library/logging logging Formatter formatException}@anchor{317d}
@deffn {メソッド} formatException (exc_info)

指定された例外情報 (@ref{89a,,sys.exc_info()} が返すような標準例外のタプル) を文字列として書式化します。デフォルトの実装は単に @ref{a4f,,traceback.print_exception()} を使います。結果の文字列が返されます。
@end deffn

@geindex formatStack() (logging.Formatter のメソッド)
@anchor{library/logging logging Formatter formatStack}@anchor{317e}
@deffn {メソッド} formatStack (stack_info)

指定されたスタック情報を文字列としてフォーマットします (@ref{1086,,traceback.print_stack()} によって返される文字列ですが、最後の改行が取り除かれています)。このデフォルト実装は、単に入力値をそのまま返します。
@end deffn
@end deffn

@geindex BufferingFormatter (logging のクラス)
@anchor{library/logging logging BufferingFormatter}@anchor{317f}
@deffn {クラス} logging.BufferingFormatter (linefmt=None)

複数のレコードをまとめてフォーマットしたい場合のクラス定義に適した基底クラスです。各行 (単一のレコードに相当します) をフォーマットするために使う @ref{16b0,,Formatter} インスタンスを渡すことができます。特に指定がない場合はデフォルトのフォーマッタ (イベントのメッセージだけを出力するフォーマッタ) が使われます。

@geindex formatHeader() (logging.BufferingFormatter のメソッド)
@anchor{library/logging logging BufferingFormatter formatHeader}@anchor{3180}
@deffn {メソッド} formatHeader (records)

`複数のレコード' のリストに対するヘッダを返します。基底クラスの実装は単に空の文字列を返すだけです。レコード数やタイトルを表示したり、あるいはセパレータ行したいなど、ヘッダに対して特別な振る舞いが必要な場合はこのメソッドをオーバーライドする必要があります。
@end deffn

@geindex formatFooter() (logging.BufferingFormatter のメソッド)
@anchor{library/logging logging BufferingFormatter formatFooter}@anchor{3181}
@deffn {メソッド} formatFooter (records)

`複数のレコード' のリストに対するフッタを返します。基底クラスの実装は単に空の文字列を返すだけです。レコード数やセパレータ行の表示など、フッタに対して特別な振る舞いが必要な場合はこのメソッドをオーバーライドする必要があります。
@end deffn

@geindex format() (logging.BufferingFormatter のメソッド)
@anchor{library/logging logging BufferingFormatter format}@anchor{3182}
@deffn {メソッド} format (records)

`複数のレコード' のリストに対するフォーマット済みテキストを返します。基底クラスの実装は、レコードがなければ空の文字列を返し、レコードがある場合はヘッダ、単一のレコードをフォーマットするためのラインフォーマッタで各レコードをフォーマットした文字列、そしてフッタを全て連結したものを返します。
@end deffn
@end deffn

@node フィルタオブジェクト,LogRecord オブジェクト,フォーマッタオブジェクト,logging --- Python 用のログ記録手段
@anchor{library/logging filter}@anchor{3183}@anchor{library/logging filter-objects}@anchor{3184}
@subsubsection フィルタオブジェクト


@code{フィルタ (Filter)} は、@code{ハンドラ} や @code{ロガー} によって使われ、レベルによって提供されるのよりも洗練されたフィルタリングを実現します。基底のフィルタクラスは、ロガー階層構造内の特定地点の配下にあるイベントだけを許可します。例えば、'A.B' で初期化されたフィルタは、ロガー 'A.B', 'A.B.C', 'A.B.C.D', 'A.B.D' 等によって記録されたイベントは許可しますが、'A.BB', 'B.A.B' などは許可しません。空の文字列で初期化された場合、すべてのイベントを通過させます。

@geindex Filter (logging のクラス)
@anchor{library/logging logging Filter}@anchor{1414}
@deffn {クラス} logging.Filter (name='@w{'})

@ref{1414,,Filter} クラスのインスタンスを返します。 `name' が指定されていれば、 `name' はロガーの名前を表します。指定されたロガーとその子ロガーのイベントがフィルタを通過できるようになります。 `name' が指定されなければ、すべてのイベントを通過させます。

@geindex filter() (logging.Filter のメソッド)
@anchor{library/logging logging Filter filter}@anchor{3185}
@deffn {メソッド} filter (record)

指定されたログレコードは記録されるでしょうか？答えが「いいえ」なら false を、「はい」なら true を返します。フィルタは受け取ったログレコードそのものを編集したり、その後のイベント処理において元のログレコードに取って代わる、まったく異なるログレコードインスタンスを返す可能性があります。
@end deffn
@end deffn

ハンドラに対するフィルタはハンドラがイベントを発行する前に試され、一方ではロガーに対するフィルタは、イベントが(@ref{315d,,debug()}, @ref{3186,,info()} などによって)ロギングされる際には、ハンドラにイベントが送信される前にはいつでも試されることに注意してください。そのフィルタがそれら子孫ロガーにも適用されていない限り、子孫ロガーによって生成されたイベントはロガーのフィルタ設定によってフィルタされることはありません。

実際には、@code{Filter} をサブクラス化する必要はありません。同じ意味の @code{filter} メソッドを持つ、すべてのインスタンスを通せます。


バージョン 3.2 で変更: 特殊な @code{Filter} クラスを作ったり、 @code{filter} メソッドを持つ他のクラスを使う必要はありません: 関数 (あるいは他の callable) をフィルタとして使用することができます。フィルタロジックは、フィルタオブジェクトが @code{filter} 属性を持っているかどうかチェックします: もし @code{filter} 属性を持っていたら、それは @code{Filter} であると仮定され、その @ref{3185,,filter()} メソッドが呼び出されます。そうでなければ、それは callable であると仮定され、レコードを単一のパラメータとして呼び出されます。返される値は @ref{3185,,filter()} によって返されるものと一致すべきです。



バージョン 3.12 で変更: 受け取ったログレコード自体を編集する代わりに、元のログレコードに取って代わる別の @ref{11e8,,LogRecord} インスタンスを返すことができるようになりました。これにより、 @ref{16af,,Handler} にアタッチされたフィルタが、他のハンドラへの副作用を伴うことなく、発行前にログレコードを編集することが可能になります。


フィルタは本来、レコードをレベルよりも洗練された基準に基づいてフィルタするために使われますが、それが取り付けられたハンドラやロガーによって処理されるレコードをすべて監視します。これは、特定のロガーやハンドラに処理されたレコードの数を数えたり、処理されている @ref{11e8,,LogRecord} の属性を追加、変更、削除したりするときに便利です。もちろん、LogRecord を変更するには注意が必要ですが、これにより、ログにコンテキスト情報を注入できます (@ref{3187,,Filter を使ったコンテキスト情報の伝達} を参照してください)。

@node LogRecord オブジェクト,LogRecord 属性,フィルタオブジェクト,logging --- Python 用のログ記録手段
@anchor{library/logging log-record}@anchor{3188}@anchor{library/logging logrecord-objects}@anchor{3189}
@subsubsection LogRecord オブジェクト


@ref{11e8,,LogRecord} インスタンスは、何かをログ記録するたびに @ref{d46,,Logger} によって生成されます。また、 @ref{318a,,makeLogRecord()} を通して (例えば、ワイヤを通して受け取られた pickle 化されたイベントから) 手動で生成することも出来ます。

@geindex LogRecord (logging のクラス)
@anchor{library/logging logging LogRecord}@anchor{11e8}
@deffn {クラス} logging.LogRecord (name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)

ロギングされているイベントに適切なすべての情報を含みます。

もっとも重要な情報は `msg' と `args' に渡され、 @code{msg % args} で結合されてレコードの @code{message} 属性を生成します。

@*パラメータ: 

@itemize *

@item 
@code{name} (@ref{169,,str}) -- この @code{LogRecord} であらわされるイベントを記録したロガーの名前です。 @code{LogRecord} が持つロガーの名前は、たとえ異なる (祖先の) ロガーに接続されたハンドラから出力されたとしても、常に同じ値を持つことに注意してください。

@item 
@code{level} (@ref{19b,,int}) -- 記録されたイベントの @ref{86a,,数値であらわしたロギングレベル}  (@code{10} が @code{DEBUG}, @code{20} が @code{INFO} など) です。このパラメータは LogRecord の `2つの' 属性に変換されることに注意してください: 数値は @code{levelno} に、また対応するログレベルの名前は @code{levelname} に保持されます。

@item 
@code{pathname} (@ref{169,,str}) -- ロギングの呼び出しが行われたソースファイルへの完全なパス名をあらわす文字列です。

@item 
@code{lineno} (@ref{19b,,int}) -- ロギングの呼び出しが発せられたソース行番号。

@item 
@code{msg} (@ref{8bb,,Any}) -- イベントの説明メッセージ。様々なデータのプレースホルダを含んだ %フォーマット文字列か、任意のオブジェクト (@ref{318b,,任意のオブジェクトをメッセージに使用する} を参照)。

@item 
@code{args} (@ref{614,,tuple}@code{ | }@ref{183,,dict}@code{[}@ref{169,,str}@code{, }@ref{8bb,,Any}@code{]}) -- `msg' 引数と組み合わせてイベント記述を得るための変数データです。

@item 
@code{exc_info} (@ref{614,,tuple}@code{[}@ref{f44,,type}@code{[}@ref{7d6,,BaseException}@code{]}@code{, }@ref{7d6,,BaseException}@code{, }@ref{cea,,types.TracebackType}@code{] }@code{| }@code{None}) -- @ref{89a,,sys.exc_info()} によって返される現在の例外情報を含む例外タプルです。例外情報がない場合は @code{None} です。

@item 
@code{func} (@ref{169,,str}@code{ | }@code{None}) -- ロギングの呼び出しを行った関数またはメソッドの名前です。

@item 
@code{sinfo} (@ref{169,,str}@code{ | }@code{None}) -- 現在のスレッドのスタックベースからログ呼び出しまでの間のスタック情報を表わすテキスト文字列。
@end itemize


@geindex getMessage() (logging.LogRecord のメソッド)
@anchor{library/logging logging LogRecord getMessage}@anchor{318c}
@deffn {メソッド} getMessage ()

ユーザが提供した引数をメッセージに交ぜた後、この @ref{11e8,,LogRecord} インスタンスへのメッセージを返します。ユーザがロギングの呼び出しに与えた引数が文字列でなければ、その引数に @ref{169,,str()} が呼ばれ、文字列に変換されます。これにより、 @code{__str__} メソッドが実際のフォーマット文字列を返せるようなユーザ定義のクラスをメッセージとして使えます。
@end deffn


バージョン 3.2 で変更: @ref{11e8,,LogRecord} の生成は、レコードを生成するために使用されるファクトリを提供することにより、さらに設定可能になりました。ファクトリは @ref{318d,,getLogRecordFactory()} と @ref{318e,,setLogRecordFactory()} を使用して設定することができます (ファクトリのシグネチャに関しては @ref{318e,,setLogRecordFactory()} を参照)。


この機能を使うと @ref{11e8,,LogRecord} の生成時に独自の値を注入することができます。次のパターンが使えます:

@example
old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)
@end example

このパターンでは複数のファクトリをつなぐこともできます。それらが互いの属性を上書きしたりせず、また上にリストされた標準属性を意図せず上書きしたりしない限り、驚くようなことは何も起こりません (there should be no surprises)。
@end deffn

@node LogRecord 属性,LoggerAdapter オブジェクト,LogRecord オブジェクト,logging --- Python 用のログ記録手段
@anchor{library/logging id2}@anchor{318f}@anchor{library/logging logrecord-attributes}@anchor{315c}
@subsubsection LogRecord 属性


LogRecord には幾つかの属性があり、そのほとんどはコンストラクタの引数から得られます。(なお、LogRecord コンストラクタの引数と LogRecord 属性が常に厳密に対応するわけではありません。) これらの属性は、レコードからのデータをフォーマット文字列に統合するのに使えます。以下のテーブルに、属性名、意味、そして % 形式フォーマット文字列における対応するプレースホルダを (アルファベット順に) 列挙します。

@{@}-フォーマット (@ref{833,,str.format()}) を使用していれば、書式文字列の中でプレースホールダーとして @code{@{attrname@}} を使うことができます。 $-フォーマット (@ref{897,,string.Template}) を使用している場合は、 @code{$@{attrname@}} 形式にしてください。もちろん、両方の場合で @code{attrname} は使用したい実際の属性名に置き換えてください。

@{@}-フォーマットの場合には、属性名の後にフォーマットフラグを指定することができます。属性名とフォーマットフラグの間はコロンで分割します。例: プレースホールダー @code{@{msecs:03.0f@}} は、ミリセカンド値 @code{4} を @code{004} としてフォーマットします。利用可能なオプション上の全詳細に関しては @ref{833,,str.format()} ドキュメンテーションを参照してください。


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性名

@tab

フォーマット

@tab

説明

@item

@code{args}

@tab

このフォーマットを自分で使う必要はないでしょう。

@tab

@code{msg} に組み合わせて @code{message} を生成するための引数のタプル、または、マージに用いられる辞書(引数が一つしかなく、かつそれが辞書の場合)。

@item

asctime

@tab

@code{%(asctime)s}

@tab

@ref{11e8,,LogRecord} が生成された時刻を人間が読める書式で表したもの。デフォルトでは "2003-07-08 16:49:45,896" 形式 (コンマ以降の数字は時刻のミリ秒部分) です。

@item

created

@tab

@code{%(created)f}

@tab

@ref{11e8,,LogRecord} が生成された時刻です (@ref{ce0,,time.time_ns()} / 1e9 で返される形式で)。

@item

exc_info

@tab

このフォーマットを自分で使う必要はないでしょう。

@tab

(@code{sys.exc_info} 風の) 例外タプルか、例外が起こっていない場合は @code{None}。

@item

exc_text

@tab

このフォーマットを自分で使う必要はないでしょう。

@tab

Exception information formatted as a string.
This is set when @ref{317c,,Formatter.format()} is
invoked, or @code{None} if no exception has
occurred.

@item

ファイル名

@tab

@code{%(filename)s}

@tab

@code{pathname} のファイル名部分。

@item

funcName

@tab

@code{%(funcName)s}

@tab

ロギングの呼び出しを含む関数の名前。

@item

levelname

@tab

@code{%(levelname)s}

@tab

メッセージのための文字のロギングレベル (@code{'DEBUG'}, @code{'INFO'}, @code{'WARNING'}, @code{'ERROR'}, @code{'CRITICAL'})。

@item

levelno

@tab

@code{%(levelno)s}

@tab

メッセージのための数値のロギングレベル (@ref{20de,,DEBUG}, @ref{20df,,INFO}, @ref{20e0,,WARNING}, @ref{20e1,,ERROR}, @ref{20e2,,CRITICAL})。

@item

lineno

@tab

@code{%(lineno)d}

@tab

ロギングの呼び出しが発せられたソース行番号 (利用できる場合のみ)。

@item

message

@tab

@code{%(message)s}

@tab

@code{msg % args} として求められた、ログメッセージ。 @ref{317c,,Formatter.format()} が呼び出されたときに設定されます。

@item

module

@tab

@code{%(module)s}

@tab

モジュール (@code{filename} の名前部分)。

@item

msecs

@tab

@code{%(msecs)d}

@tab

@ref{11e8,,LogRecord} が生成された時刻のミリ秒部分。

@item

msg

@tab

このフォーマットを自分で使う必要はないでしょう。

@tab

元のロギングの呼び出しで渡されたフォーマット文字列。 @code{args} と合わせて、 @code{message} 、または任意のオブジェクトを生成します (@ref{318b,,任意のオブジェクトをメッセージに使用する} 参照)。

@item

name

@tab

@code{%(name)s}

@tab

ロギングに使われたロガーの名前。

@item

pathname

@tab

@code{%(pathname)s}

@tab

ロギングの呼び出しが発せられたファイルの完全なパス名 (利用できる場合のみ)。

@item

process

@tab

@code{%(process)d}

@tab

プロセス ID (利用可能な場合のみ)。

@item

processName

@tab

@code{%(processName)s}

@tab

プロセス名 (利用可能な場合のみ)。

@item

relativeCreated

@tab

@code{%(relativeCreated)d}

@tab

logging モジュールが読み込まれた時刻に対する、LogRecord が生成された時刻を、ミリ秒で表したもの。

@item

stack_info

@tab

このフォーマットを自分で使う必要はないでしょう。

@tab

現在のスレッドでのスタックの底からこのレコードの生成に帰着したログ呼び出しまでのスタックフレーム情報 (利用可能な場合)。

@item

thread

@tab

@code{%(thread)d}

@tab

スレッド ID (利用可能な場合のみ)。

@item

threadName

@tab

@code{%(threadName)s}

@tab

スレッド名 (利用可能な場合のみ)。

@item

taskName

@tab

@code{%(taskName)s}

@tab

@ref{1c7,,asyncio.Task} 名 (利用可能な場合のみ)。

@end multitable



バージョン 3.1 で変更: `processName' が追加されました。



バージョン 3.12 で変更: `taskName' が追加されました。


@node LoggerAdapter オブジェクト,スレッドセーフ性,LogRecord 属性,logging --- Python 用のログ記録手段
@anchor{library/logging logger-adapter}@anchor{3190}@anchor{library/logging loggeradapter-objects}@anchor{3191}
@subsubsection LoggerAdapter オブジェクト


@ref{150d,,LoggerAdapter} インスタンスは文脈情報をログ記録呼び出しに渡すのを簡単にするために使われます。使い方の例は @ref{3192,,コンテキスト情報をログ記録出力に付加する} を参照してください。

@geindex LoggerAdapter (logging のクラス)
@anchor{library/logging logging LoggerAdapter}@anchor{150d}
@deffn {クラス} logging.LoggerAdapter (logger, extra=None, merge_extra=False)

Returns an instance of @ref{150d,,LoggerAdapter} initialized with an
underlying @ref{d46,,Logger} instance, an optional dict-like object (`extra'),
and an optional boolean (`merge_extra') indicating whether or not
the `extra' argument of individual log calls should be merged with
the @ref{150d,,LoggerAdapter} extra.
The default behavior is to ignore the `extra' argument of individual log
calls and only use the one of the @ref{150d,,LoggerAdapter} instance

@geindex process() (logging.LoggerAdapter のメソッド)
@anchor{library/logging logging LoggerAdapter process}@anchor{3193}
@deffn {メソッド} process (msg, kwargs)

文脈情報を挿入するために、ログ記録呼び出しに渡されたメッセージおよび/またはキーワード引数に変更を加えます。ここでの実装は `extra' としてコンストラクタに渡されたオブジェクトを取り、'extra' キーを使って `kwargs' に加えます。返り値は (`msg', `kwargs') というタプルで、(変更されているはずの) 渡された引数を含みます。
@end deffn

@geindex manager (logging.LoggerAdapter の属性)
@anchor{library/logging logging LoggerAdapter manager}@anchor{3194}
@deffn {の属性} manager

背後にある `logger' の @code{manager} メソッドを代理で呼び出します。
@end deffn

@geindex _log (logging.LoggerAdapter の属性)
@anchor{library/logging logging LoggerAdapter _log}@anchor{3195}
@deffn {の属性} _log

背後にある `logger' の @code{_log()} メソッドを代理で呼び出します。
@end deffn

@ref{150d,,LoggerAdapter} は上記に加え @ref{d46,,Logger} のメソッド @ref{102b,,debug()}, @ref{20dd,,info()}, @ref{1a74,,warning()}, @ref{315e,,error()}, @ref{1029,,exception()}, @ref{102a,,critical()}, @ref{1028,,log()}, @ref{150e,,isEnabledFor()}, @ref{315b,,getEffectiveLevel()}, @ref{16ac,,setLevel()}, @ref{3165,,hasHandlers()} をサポートします。これらは @ref{d46,,Logger} の対応するメソッドと同じシグニチャを持つため、2つのインスタンスは区別せずに利用出来ます。


バージョン 3.2 で変更: @ref{150e,,isEnabledFor()}, @ref{315b,,getEffectiveLevel()}, @ref{16ac,,setLevel()}, @ref{3165,,hasHandlers()} が @ref{150d,,LoggerAdapter} に追加されました。これらメソッドは元のロガーに処理を委譲します。



バージョン 3.6 で変更: 基底のロガーに移譲し、アダプターをネストできるようにするために @code{manager} 属性と @code{_log()} メソッドが追加されました。



バージョン 3.10 で変更: `extra' 引数が任意になりました。



バージョン 3.13 で変更: `merge_extra' 引数が追加されました。

@end deffn

@node スレッドセーフ性,モジュールレベルの関数,LoggerAdapter オブジェクト,logging --- Python 用のログ記録手段
@anchor{library/logging thread-safety}@anchor{3196}
@subsubsection スレッドセーフ性


logging モジュールは、クライアントで特殊な作業を必要としない限りスレッドセーフになっています。このスレッドセーフ性はスレッドロックによって達成されています; モジュールの共有データへのアクセスを直列化するためのロックが一つ存在し、各ハンドラでも背後にある I/O へのアクセスを直列化するためにロックを生成します。

@ref{cb,,signal} モジュールを使用して非同期シグナルハンドラを実装している場合、そのようなハンドラからはログ記録を使用できないかもしれません。これは、 @ref{f3,,threading} モジュールにおけるロック実装が常にリエントラントではなく、そのようなシグナルハンドラから呼び出すことができないからです。

@node モジュールレベルの関数,モジュールレベル属性,スレッドセーフ性,logging --- Python 用のログ記録手段
@anchor{library/logging module-level-functions}@anchor{3197}
@subsubsection モジュールレベルの関数


上で述べたクラスに加えて、いくつかのモジュールレベルの関数が存在します。

@geindex getLogger() (logging モジュール)
@anchor{library/logging logging getLogger}@anchor{b59}
@deffn {の関数} logging.getLogger (name=None)

指定された名前のロガーを返します。名前が @code{None} であれば、ロガーの階層構造におけるルートロガーを返します。名前を指定する場合は、典型的には `'a''、 `'a.b'' または `'a.b.c.d'' のようなドット区切りの階層的な名前にします。名前の付け方は完全にログ機能を使う開発者次第ですが、 @ref{3151,,ロガーオブジェクト} で言及されている通り、特に理由がなければ @code{__name__} を使うことが推奨されます。

与えられた名前に対して、この関数はどの呼び出しでも同じロガーインスタンスを返します。したがって、ロガーインスタンスをアプリケーションの各部でやりとりする必要はありません。
@end deffn

@geindex getLoggerClass() (logging モジュール)
@anchor{library/logging logging getLoggerClass}@anchor{3198}
@deffn {の関数} logging.getLoggerClass ()

標準の @ref{d46,,Logger} クラスか、最後に @ref{3199,,setLoggerClass()} に渡したクラスを返します。この関数は、新たなクラス定義の中で呼び出して、カスタマイズした @ref{d46,,Logger} クラスのインストールが既に他のコードで適用したカスタマイズを取り消さないことを保証するために使われることがあります。例えば以下のようにします:

@example
class MyLogger(logging.getLoggerClass()):
    # ... override behaviour here
@end example
@end deffn

@geindex getLogRecordFactory() (logging モジュール)
@anchor{library/logging logging getLogRecordFactory}@anchor{318d}
@deffn {の関数} logging.getLogRecordFactory ()

@ref{11e8,,LogRecord} を生成するのに使われる callable を返します。


Added in version 3.2: この関数は、ログイベントを表現する @ref{11e8,,LogRecord} の構築方法に関して開発者により多くのコントロールを与えるため、 @ref{318e,,setLogRecordFactory()} とともに提供されました。


このファクトリがどのように呼ばれるかに関する詳細は @ref{318e,,setLogRecordFactory()} を参照してください。
@end deffn

@geindex debug() (logging モジュール)
@anchor{library/logging logging debug}@anchor{315d}
@deffn {の関数} logging.debug (msg, *args, **kwargs)

ルートロガーの @ref{102b,,Logger.debug()} メソッドを呼び出す便利関数です。引数の取り扱いはあらゆる点で当該メソッドと同じです。

唯一の違いはルートロガーがハンドラを持たない場合で、この場合はルートロガーの @code{debug} メソッドを呼び出す前に @ref{bf3,,basicConfig()} が呼ばれます。

非常に短いスクリプトや @code{logging} の機能についての簡単なデモに対しては、 @code{debug} やその他のモジュールレベル関数は便利でしょう。しかしながら、ほとんどのプログラムはロギングの設定を慎重かつ明示的に制御したいはずです。したがって、このドキュメントの最初に書かれているとおり、モジュールレベルのロガーを生成してそのロガーに対する @ref{102b,,Logger.debug()} メソッド (または他のログレベル固有のメソッド) を呼び出す方を好むでしょう。
@end deffn

@geindex info() (logging モジュール)
@anchor{library/logging logging info}@anchor{3186}
@deffn {の関数} logging.info (msg, *args, **kwargs)

ルートロガーに対してログレベル @ref{20df,,INFO} でメッセージを記録します。引数と振る舞いは、ログレベルを除けば @ref{315d,,debug()} と同じです。
@end deffn

@geindex warning() (logging モジュール)
@anchor{library/logging logging warning}@anchor{354}
@deffn {の関数} logging.warning (msg, *args, **kwargs)

ルートロガーに対してログレベル @ref{20e0,,WARNING} でメッセージを記録します。引数と振る舞いは、ログレベルを除けば @ref{315d,,debug()} と同じです。

@cartouche
@quotation 注釈 
@code{warning} と機能的に等価な古い関数 @code{warn} があります。@code{warn} は廃止予定なので使わないでください - 代わりに @code{warning} を使ってください。
@end quotation
@end cartouche
@end deffn

@geindex error() (logging モジュール)
@anchor{library/logging logging error}@anchor{319a}
@deffn {の関数} logging.error (msg, *args, **kwargs)

ルートロガーに対してログレベル @ref{20e1,,ERROR} でメッセージを記録します。引数と振る舞いは、ログレベルを除けば @ref{315d,,debug()} と同じです。
@end deffn

@geindex critical() (logging モジュール)
@anchor{library/logging logging critical}@anchor{319b}
@deffn {の関数} logging.critical (msg, *args, **kwargs)

ルートロガーに対してログレベル @ref{20e2,,CRITICAL} でメッセージを記録します。引数と振る舞いは、ログレベルを除けば @ref{315d,,debug()} と同じです。
@end deffn

@geindex exception() (logging モジュール)
@anchor{library/logging logging exception}@anchor{16ad}
@deffn {の関数} logging.exception (msg, *args, **kwargs)

ルートロガーに対してログレベル @ref{20e1,,ERROR} でメッセージを記録します。引数と振る舞いは、ログレベルを除けば @ref{315d,,debug()} と同じです。例外情報がログメッセージに追加されます。この関数は例外ハンドラからのみ呼び出されるべきです。
@end deffn

@geindex log() (logging モジュール)
@anchor{library/logging logging log}@anchor{319c}
@deffn {の関数} logging.log (level, msg, *args, **kwargs)

ルートロガーに対して `level' で指定したログレベルでメッセージを記録します。引数と振る舞いは、ログレベルを除けば @ref{315d,,debug()} と同じです。
@end deffn

@geindex disable() (logging モジュール)
@anchor{library/logging logging disable}@anchor{319d}
@deffn {の関数} logging.disable (level=CRITICAL)

全てのロガーのレベル `level' を上書きし、これはロガー自身の出力レベルよりも優先されます。アプリケーション全体を横断するログ出力を一時的に調整する必要が生じたら、この関数は便利でしょう。これの効果は重大度 `level' 以下の全てのロギング呼び出しを無効にすることですので、INFO で呼び出しをすれば、INFO と DEBUG イベントが捨てられる一方で、重大度 WARNING 以上のものは、ロガーの有効レベルに基いて処理されます。 @code{logging.disable(logging.NOTSET)} が呼び出されると、この上書きレベルは削除され、ログ出力は再び個々のロガーの有効レベルに依存するようになります。

@code{CRITICAL} より高い独自のログレベル (これは推奨されません) を定義した場合は、 `level' 引数のデフォルト値を当てにできなくなり、適切な値を明示的に与える必要があります。


バージョン 3.7 で変更: `level' 引数のデフォルトが @code{CRITICAL} レベルになりました。この変更についてのより詳しいことは bpo-28524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28524} を参照してください。

@end deffn

@geindex addLevelName() (logging モジュール)
@anchor{library/logging logging addLevelName}@anchor{319e}
@deffn {の関数} logging.addLevelName (level, levelName)

内部的な辞書の中でレベル `level' をテキスト `levelName' に関連付けます。これは例えば @ref{16b0,,Formatter} でメッセージを書式化する際のように、数字のレベルをテキスト表現に対応付ける際に用いられます。この関数は自作のレベルを定義するために使うこともできます。使われるレベルに対する唯一の制限は、レベルは正の整数でなくてはならず、メッセージの深刻度が上がるに従ってレベルの数も上がらなくてはならないということです。

@cartouche
@quotation 注釈 
独自のレベルを定義したい場合、 @ref{319f,,カスタムレベル} のセクションを参照してください。
@end quotation
@end cartouche
@end deffn

@geindex getLevelNamesMapping() (logging モジュール)
@anchor{library/logging logging getLevelNamesMapping}@anchor{869}
@deffn {の関数} logging.getLevelNamesMapping ()

ログレベルの名前と対応するログレベルのマッピングを返します。例えば、文字列 "CRITICAL" は @ref{20e2,,CRITICAL} にマップされます。この関数が返すマッピングオブジェクトは、関数呼び出しのたびに内部のマッピングをコピーしたものです。


Added in version 3.11.

@end deffn

@geindex getLevelName() (logging モジュール)
@anchor{library/logging logging getLevelName}@anchor{31a0}
@deffn {の関数} logging.getLevelName (level)

テキストまたは数値表現でログレベル `level' を返してください。

`level' が定義済みのレベル @ref{20e2,,CRITICAL}, @ref{20e1,,ERROR}, @ref{20e0,,WARNING}, @ref{20df,,INFO}, @ref{20de,,DEBUG} のいずれかである場合、対応する文字列が返されます。 @ref{319e,,addLevelName()} を使ってレベルに名前を関連付けていた場合、 `level' に関連付けられた名前が返されます。定義済みのレベルに対応する数値を指定した場合、レベルに対応した文字列表現を返します。

`level' パラメータは、 @ref{20df,,INFO} のような整数定数の代わりに 'INFO' のようなレベルの文字列表現も受け付けます。この場合、この関数は関連するレベルの数値表現を返します。

もし渡された数値や文字列がマッチしなければ、 'Level %s' % level が返されます。

@cartouche
@quotation 注釈 
レベルは内部的には整数です(これはロギングのロジックが大小比較をする必要があるからです)。この関数は、数値のレベルを、書式記述子 @code{%(levelname)s} (@ref{315c,,LogRecord 属性} 参照)によって書式化されるログ出力の表示用レベル名に変換するなどの用途に使用されます。
@end quotation
@end cartouche


バージョン 3.4 で変更: Python 3.4以前のバージョンでは、この関数にはテキストのレベルも渡すことが出来、これは対応する数字レベルに読み替えられていました。このドキュメントされていなかった振る舞いは誤りであると判断され、Python 3.4 で一度削除されました。ただし後方互換性のために、これは 3.4.2 で元に戻されました。

@end deffn

@geindex getHandlerByName() (logging モジュール)
@anchor{library/logging logging getHandlerByName}@anchor{1b62}
@deffn {の関数} logging.getHandlerByName (name)

`name' に指定した名前のハンドラを返します。指定した名前のハンドラがない場合は @code{None} を返します。


Added in version 3.12.

@end deffn

@geindex getHandlerNames() (logging モジュール)
@anchor{library/logging logging getHandlerNames}@anchor{1a6e}
@deffn {の関数} logging.getHandlerNames ()

全ての既知のハンドラ名の、イミュータブルな集合を返します。


Added in version 3.12.

@end deffn

@geindex makeLogRecord() (logging モジュール)
@anchor{library/logging logging makeLogRecord}@anchor{318a}
@deffn {の関数} logging.makeLogRecord (attrdict)

属性が `attrdict' で定義された、新しい @ref{11e8,,LogRecord} インスタンスを生成して返します。この関数は、 pickle された @ref{11e8,,LogRecord} 属性の辞書をソケットを介して送信し、受信端で @ref{11e8,,LogRecord} インスタンスとして再構成する場合に便利です。
@end deffn

@geindex basicConfig() (logging モジュール)
@anchor{library/logging logging basicConfig}@anchor{bf3}
@deffn {の関数} logging.basicConfig (**kwargs)

デフォルトの @ref{16b0,,Formatter} を持つ @ref{1411,,StreamHandler} を生成してルートロガーに追加し、ロギングシステムの基本的な環境設定を行います。関数 @ref{315d,,debug()}, @ref{3186,,info()}, @ref{354,,warning()}, @ref{319a,,error()}, @ref{319b,,critical()} は、ルートロガーにハンドラが定義されていない場合に自動的に @ref{bf3,,basicConfig()} を呼び出します。

この関数は `force' キーワード引数に @code{True} が設定されない限り、ルートロガーに設定されたハンドラがあれば何もしません。

@cartouche
@quotation 注釈 
この関数は、他のスレッドが開始される前にメインスレッドから呼び出されるべきです。Python の 2.7.1 や 3.2 以前のバージョンでは、この関数が複数のスレッドから呼ばれると(珍しい状況下とはいえ)ハンドラがルートロガーに複数回加えられることがあり、ログ内のメッセージが重複するという予期しない結果をもたらすことがあります。
@end quotation
@end cartouche

以下のキーワード引数がサポートされます。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

フォーマット

@tab

説明

@item

`filename'

@tab

@ref{1411,,StreamHandler} ではなく指定された名前で  @ref{1c53,,FileHandler} が作られます。

@item

`filemode'

@tab

`filename' が指定された場合、この @ref{25d9,,モード} でファイルが開かれます。
デフォルトは  @code{'a'} です。

@item

`format'

@tab

ハンドラーで指定されたフォーマット文字列を使います。デフォルトは @code{levelname}, @code{name}, @code{message} 属性をコロン区切りにしたものです。

@item

`datefmt'

@tab

指定された日時の書式で @ref{1402,,time.strftime()} が受け付けるものを使います。

@item

`style'

@tab

`format' が指定された場合、書式文字列にこのスタイルを仕様します。
@code{'%'}, @code{'@{'}, @code{'$'} のうち1つで、それぞれ @ref{8db,,printf-style}, @ref{833,,str.format()}, @ref{897,,string.Template} に対応します。
デフォルトは @code{'%'} です。

@item

`level'

@tab

ルートロガーのレベルを指定された @ref{86a,,レベル} に設定します。

@item

`stream'

@tab

指定されたストリームを @ref{1411,,StreamHandler} の初期化に使います。
この引数は `filename' と同時には使えないことに注意してください。
両方が指定されたときには @code{ValueError} が送出されます。

@item

`handlers'

@tab

もし指定されれば、 これは root ロガーに追加される既に作られたハンドラのイテラブルになります。まだフォーマッタがセットされていないすべてのハンドラは、この関数で作られたデフォルトフォーマッタが割り当てられることになります。この引数は `filename' や `stream' と互換性がないことに注意してください。両方が存在する場合 @code{ValueError} が上げられます。

@item

`force'

@tab

このキーワード引数が真に設定されている場合、ルートのロガーに取り付けられたハンドラは全て取り除かれ、他の引数によって指定された設定が有効になる前に閉じられます。

@item

`encoding'

@tab

もしこのキーワード引数が `filename' とともに指定された場合、 @ref{1c53,,FileHandler} が作成されるときにこの値が利用され、出力ファイルを開く時に使用されます。

@item

`errors'

@tab

もしこのキーワード引数が `filename' とともに指定された場合、 @ref{1c53,,FileHandler} が作成されるときのこの値が使用され、出力ファイルを開く時に使われます。もし指定されなかった場合、 'backslashreplace' が使用されます。もし @code{None} が指定されると @ref{316,,open()} のように渡され、'errors' を渡したのと同じように扱われます。

@end multitable



バージョン 3.2 で変更: `style' 引数が追加されました。



バージョン 3.3 で変更: 互換性のない引数が指定された状況 (例えば `handlers' が `stream' や `filename' と一緒に指定されたり、`stream' が `filename' と一緒に指定された場合) を捕捉するために、追加のチェックが加えられました。



バージョン 3.8 で変更: `force' 引数が追加されました。



バージョン 3.9 で変更: `encoding' と `errors' 引数が追加されました。

@end deffn

@geindex shutdown() (logging モジュール)
@anchor{library/logging logging shutdown}@anchor{31a1}
@deffn {の関数} logging.shutdown ()

ロギングシステムに対して、バッファのフラッシュを行い、すべてのハンドラを閉じることで順次シャットダウンを行うように告知します。この関数はアプリケーションの終了時に呼ばれるべきであり、また呼び出し以降はそれ以上ロギングシステムを使ってはなりません。

loggingモジュールがインポートされると、この関数が終了ハンドラーとして登録されます（ @ref{d,,atexit} 参照）。そのため、通常はこれを手動で行う必要はありません。
@end deffn

@geindex setLoggerClass() (logging モジュール)
@anchor{library/logging logging setLoggerClass}@anchor{3199}
@deffn {の関数} logging.setLoggerClass (klass)

ロギングシステムに対して、ロガーをインスタンス化する際にクラス `klass' を使うように指示します。
指定するクラスは引数として名前だけをとるようなメソッド @code{__init__()} を定義していなければならず、 @code{__init__()} では @code{Logger.__init__()} を呼び出さなければなりません。
この関数が呼び出されるのはたいてい、独自の振る舞いをするロガーを使う必要のあるアプリケーションでロガーがインスタンス化される前です。
呼び出された後は、いつでもそのサブクラスを使ってロガーのインスタンス化をしてはいけません: 引き続き @ref{b59,,logging.getLogger()} API を使用してロガーを取得してください。
@end deffn

@geindex setLogRecordFactory() (logging モジュール)
@anchor{library/logging logging setLogRecordFactory}@anchor{318e}
@deffn {の関数} logging.setLogRecordFactory (factory)

@ref{11e8,,LogRecord} を生成するのに使われる callable をセットします。

@*パラメータ: 
@code{factory} -- ログレコードを生成するファクトリとして振舞う callable。



Added in version 3.2: この関数は、ログイベントを表現する @ref{11e8,,LogRecord} の構築方法に関して開発者により多くのコントロールを与えるため、 @ref{318d,,getLogRecordFactory()} とともに提供されました。


ファクトリは以下のようなシグネチャを持っています:

@code{factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)}

@quotation

@*name: 
ロガーの名前。


@*level: 
ログレベル (数値)。


@*fn: 
ログ呼び出しが行われたファイルのフルパス名。


@*lno: 
ログ呼び出しが行われたファイルの行数。


@*msg: 
ログメッセージ。


@*@code{args}: 
ログメッセージに対する引数。


@*exc_info: 
例外タプルまたは @code{None}。


@*func: 
ログ呼び出しを起動した関数またはメソッドの名前。


@*sinfo: 
@ref{1086,,traceback.print_stack()} で提供されるような、呼び出し階層を示すスタックトレースバック。


@*@code{kwargs}: 
追加のキーワード引数。

@end quotation
@end deffn

@node モジュールレベル属性,warnings モジュールとの統合,モジュールレベルの関数,logging --- Python 用のログ記録手段
@anchor{library/logging module-level-attributes}@anchor{31a2}
@subsubsection モジュールレベル属性


@geindex lastResort (logging モジュール)
@anchor{library/logging logging lastResort}@anchor{1413}
@deffn {データ} logging.lastResort

「最後の手段のハンドラ」が、この属性で利用可能です。これは @ref{1411,,StreamHandler} が @code{sys.stderr} に @code{WARNING} レベルで書き出しているのがそうですし、ロギングの設定がなにか不在のロギングイベントを扱う場合に使われます。最終的な結果は、メッセージを単に @code{sys.stderr} に出力することです。これはかつて「logger XYZ についてのハンドラが見つかりません」と言っていたエラーメッセージを置き換えています。もしも何らかの理由でその昔の振る舞いが必要な場合は、 @code{lastResort} に @code{None} をセットすれば良いです。


Added in version 3.2.

@end deffn

@geindex raiseExceptions (logging モジュール)
@anchor{library/logging logging raiseExceptions}@anchor{1412}
@deffn {データ} logging.raiseExceptions

ログメッセージの処理中に発生した例外を伝播させるかどうかを調べるために使われます。

デフォルト: @code{True}.

@ref{1412,,raiseExceptions} が @code{False} の場合、発生した例外は静かに無視されます。これはほとんどのログシステムにおいて望ましい動作です - ほとんどのユーザーはログシステムのエラーには興味がなく、アプリケーションのエラーにより強い関心を持つでしょう。
@end deffn

@node warnings モジュールとの統合,,モジュールレベル属性,logging --- Python 用のログ記録手段
@anchor{library/logging integration-with-the-warnings-module}@anchor{31a3}
@subsubsection warnings モジュールとの統合


The @ref{31a4,,captureWarnings()} function can be used to integrate @code{logging}
with the @ref{118,,warnings} module.

@geindex captureWarnings() (logging モジュール)
@anchor{library/logging logging captureWarnings}@anchor{31a4}
@deffn {の関数} logging.captureWarnings (capture)

この関数は、logging による警告の補足を、有効にまたは無効にします。

`capture' が @code{True} なら、 @ref{118,,warnings} モジュールに発せられた警告は、ロギングシステムにリダイレクトされるようになります。具体的には、警告が @ref{1df8,,warnings.formatwarning()} でフォーマット化され、結果の文字列が @code{'py.warnings'} という名のロガーに、 @ref{20e0,,WARNING} の重大度でロギングされるようになります。

`capture' が @code{False} なら、警告のロギングシステムに対するリダイレクトは止められ、警告は元の (すなわち、@code{captureWarnings(True)} が呼び出される前に有効だった) 送信先にリダイレクトされるようになります。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{8c,,logging.config} モジュール

logging モジュールの環境設定 API です。

@item @ref{8d,,logging.handlers} モジュール

logging モジュールに含まれる、便利なハンドラです。

@geindex Python Enhancement Proposals; PEP 282

@item PEP 282@footnote{https://peps.python.org/pep-0282/} - ログシステム

この機能を Python 標準ライブラリに含めることを述べた提案です。

@item Python の最初のロギングパッケージ@footnote{https://old.red-dove.com/python_logging.html}

This is the original source for the @code{logging} package.  The version of the
package available from this site is suitable for use with Python 1.5.2, 2.1.x
and 2.2.x, which do not include the @code{logging} package in the standard
library.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node logging config --- ログ記録の環境設定,logging handlers --- ログ記録ハンドラー,logging --- Python 用のログ記録手段,汎用オペレーティングシステムサービス
@anchor{library/logging config doc}@anchor{31a5}@anchor{library/logging config logging-config-logging-configuration}@anchor{31a6}@anchor{library/logging config module-logging config}@anchor{8c}@anchor{library/logging config translation-repo}@anchor{31a7}
@subsection @code{logging.config} --- ログ記録の環境設定


@geindex module; logging.config

`ソースコード:' Lib/logging/config.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/logging/config.py}

@subsubheading Important



このページには、リファレンス情報だけが含まれています。チュートリアルは、以下のページを参照してください


@itemize *

@item 
@ref{140e,,基本チュートリアル}

@item 
@ref{140f,,上級チュートリアル}

@item 
@ref{1410,,ロギングクックブック}
@end itemize


__________________________________________________________________


この節は、logging モジュールを設定するための API を解説します。

@menu
* 環境設定のための関数:: 
* セキュリティで考慮すべき点:: 
* 環境設定辞書スキーマ:: 
* 環境設定ファイルの書式:: 

@end menu

@node 環境設定のための関数,セキュリティで考慮すべき点,,logging config --- ログ記録の環境設定
@anchor{library/logging config configuration-functions}@anchor{31a8}@anchor{library/logging config logging-config-api}@anchor{1509}
@subsubsection 環境設定のための関数


The following functions configure the logging module. They are located in the
@code{logging.config} module.  Their use is optional --- you can configure the
logging module using these functions or by making calls to the main API (defined
in @ref{8b,,logging} itself) and defining handlers which are declared either in
@ref{8b,,logging} or @ref{8d,,logging.handlers}.

@geindex dictConfig() (logging.config モジュール)
@anchor{library/logging config logging config dictConfig}@anchor{13c8}
@deffn {の関数} logging.config.dictConfig (config)

辞書からロギング環境設定を取得します。この辞書の内容は、以下の @ref{31a9,,環境設定辞書スキーマ} で記述されています。

環境設定中にエラーに遭遇すると、この関数は適宜メッセージを記述しつつ @ref{2ec,,ValueError}, @ref{198,,TypeError}, @ref{5f0,,AttributeError} または @ref{65b,,ImportError} を送出します。例外を送出する条件を (不完全かもしれませんが) 以下に列挙します:


@itemize *

@item 
文字列でなかったり、実際のロギングレベルと関係ない文字列であったりする @code{level}。

@item 
ブール値でない @code{propagate} の値。

@item 
対応する行き先を持たない id。

@item 
インクリメンタルな呼び出しの中で見つかった存在しないハンドラ id。

@item 
無効なロガー名。

@item 
内部や外部のオブジェクトに関わる不可能性。
@end itemize

Parsing is performed by the @code{DictConfigurator} class, whose
constructor is passed the dictionary used for configuration, and
has a @code{configure()} method.  The @code{logging.config} module
has a callable attribute @code{dictConfigClass}
which is initially set to @code{DictConfigurator}.
You can replace the value of @code{dictConfigClass} with a
suitable implementation of your own.

@ref{13c8,,dictConfig()} は @code{dictConfigClass} を、指定された辞書を渡して呼び出し、それから返されたオブジェクトの @code{configure()} メソッドを呼び出して、環境設定を作用させます:

@example
def dictConfig(config):
    dictConfigClass(config).configure()
@end example

For example, a subclass of @code{DictConfigurator} could call
@code{DictConfigurator.__init__()} in its own @code{__init__()}, then
set up custom prefixes which would be usable in the subsequent
@code{configure()} call. @code{dictConfigClass} would be bound to
this new subclass, and then @ref{13c8,,dictConfig()} could be called exactly as
in the default, uncustomized state.


Added in version 3.2.

@end deffn

@geindex fileConfig() (logging.config モジュール)
@anchor{library/logging config logging config fileConfig}@anchor{d48}
@deffn {の関数} logging.config.fileConfig (fname, defaults=None, disable_existing_loggers=True, encoding=None)

ログ記録の環境設定を @ref{26,,configparser} 形式ファイルから読み出します。そのファイルの形式は @ref{31aa,,環境設定ファイルの書式} で記述されているとおりにしなければなりません。この関数はアプリケーションから何度も呼び出すことができ、これによって、 (設定を選択し、選択された設定を読み出す機構をデベロッパが提供していれば) 複数の準備済みの設定からエンドユーザが選択するようにできます。

It will raise @ref{264,,FileNotFoundError} if the file
doesn't exist and @ref{244,,RuntimeError} if the file is invalid or
empty.

@*パラメータ: 

@itemize *

@item 
@code{fname} -- A filename, or a file-like object, or an instance derived
from @ref{1166,,RawConfigParser}. If a
@code{RawConfigParser}-derived instance is passed, it is used as
is. Otherwise, a @ref{4de,,ConfigParser} is
instantiated, and the configuration read by it from the
object passed in @code{fname}. If that has a @ref{bf,,readline()}
method, it is assumed to be a file-like object and read using
@ref{72a,,read_file()}; otherwise,
it is assumed to be a filename and passed to
@ref{1681,,read()}.

@item 
@code{defaults} -- Defaults to be passed to the @code{ConfigParser} can be specified
in this argument.

@item 
@code{disable_existing_loggers} -- @code{False} が指定された場合は、この呼び出しが行われたときに存在するロガーは有効のまま残されます。後方互換性のあるやり方で古い振る舞いを保つので、デフォルト値は @code{True} になっています。そのような振る舞いでは、既存の非ルートロガーまたはそれらのロガーの先祖がロギング設定の中で明示的に名付けられていない限り、既存のロガーを無効にします。

@item 
@code{encoding} -- `fname' がファイル名の場合に、ファイルをオープンする時のエンコーディングです。
@end itemize



バージョン 3.4 で変更: @code{fname} として @ref{1166,,RawConfigParser} のサブクラスのインスタンスが渡せ得るようになっています。これによってこのようなことが容易になります:

@quotation


@itemize *

@item 
ロギングの設定が、アプリケーション全体の設定における単なる一部であるような設定ファイルの使用。

@item 
ファイルから設定を読み込み、 @code{fileConfig} に通す前に(例えばコマンドラインパラメータやランタイム環境の他のなにかで)アプリケーションによって修正するようなこと。
@end itemize
@end quotation


バージョン 3.10 で変更: Added the `encoding' parameter.



バージョン 3.12 で変更: An exception will be thrown if the provided file
doesn't exist or is invalid or empty.


@end deffn

@geindex listen() (logging.config モジュール)
@anchor{library/logging config logging config listen}@anchor{1167}
@deffn {の関数} logging.config.listen (port=DEFAULT_LOGGING_CONFIG_PORT, verify=None)

指定されたポートでソケットサーバを起動し、新しい設定を待ち受けます。ポートが指定されなかった場合は、モジュールのデフォルトの @code{DEFAULT_LOGGING_CONFIG_PORT} が使用されます。ロギング設定は @ref{13c8,,dictConfig()} あるいは @ref{d48,,fileConfig()} で処理できるファイルとして送信されます。 @ref{176,,Thread} インスタンスを返し、このインスタンスの @ref{178,,start()} を呼び出してサーバを起動し、適切なところで @ref{13fd,,join()} を呼び出すことができます。サーバを停止するには、 @ref{31ab,,stopListening()} を呼び出します。

@code{verify} 引数を指定する場合は、これはソケットを通して受け取ったバイト文字列が妥当であるか、処理すべきであるかどうかを検査する callable である必要があります。ソケットを通じて、暗号化または署名あるいはその両方を受け取ることがあります。そのような場合に、 @code{verify} callable が署名の正当性検査または暗号化の復号あるいはその両方を実施することが出来ます。 @code{verify} callable は単一引数で呼び出されます - ソケットを通じて受け取ったバイト文字列です - そして処理すべきバイト文字列、または捨て去られるべきであることを示すための @code{None} を返す必要があります。返却されるバイト文字列は(たとえば正当性検査だけが行われて)渡されたものと同じかもしれませんし、あるいは(おそらく暗号化の復号が行われて)まったく異なるものかもしれません。

ソケットに設定を送るには、まず設定ファイルを読み、それを @code{struct.pack('>L', n)} を使って長さ 4 バイトのバイナリにパックしたものを前に付けたバイト列としてソケットに送ります。
@anchor{library/logging config logging-eval-security}@anchor{31ac}
@cartouche
@quotation 注釈 
設定の一部は @ref{4a3,,eval()} を通じて渡されるため、この関数を利用することはユーザーをセキュリティ上のリスクにさらす可能性があります。この関数は @code{localhost} のソケットだけにバインドされており、リモートマシンからの接続を受け付けませんが、それでも @ref{1167,,listen()} を呼び出したプロセスのアカウントのもとで信頼できないコードが実行されうるシナリオが存在します。特に、 @ref{1167,,listen()} を呼び出したプロセスが複数のユーザーが利用するマシン上で実行されており、ユーザー同士が互いに信頼できない場合、悪意あるユーザーが被害者ユーザーのプロセス上で本質的に任意のコードを実行するように計画する可能性があります。攻撃は、単に被害者ユーザーの @ref{1167,,listen()} ソケットに接続して、被害者ユーザーのプロセス上で攻撃者が実行したいコードが実行されるような設定を送り込むだけです。この攻撃はデフォルトのポートが使われている場合きわめて容易であり、異なるポートが使われている場合でもそれほど難しくはありません。このような事象が発生するリスクを回避するためには、 @ref{1167,,listen()} の @code{verify} 引数を使って不正な設定が適用されるのを防ぐようにしてください。
@end quotation
@end cartouche


バージョン 3.4 で変更: @code{verify} 引数が追加されました。


@cartouche
@quotation 注釈 
既存のロガーを無効にしない構成をリスナーに送信する場合は、設定にはJSONフォーマットを使用する必要があります。これは、設定に @ref{13c8,,dictConfig()} を使用します。 このメソッドを使用すると、 @code{disable_existing_loggers} に @code{False} を指定した設定を送信できます。
@end quotation
@end cartouche
@end deffn

@geindex stopListening() (logging.config モジュール)
@anchor{library/logging config logging config stopListening}@anchor{31ab}
@deffn {の関数} logging.config.stopListening ()

@ref{1167,,listen()} を呼び出して作成された、待ち受け中のサーバを停止します。通常 @ref{1167,,listen()} の戻り値に対して @code{join()} が呼ばれる前に呼び出します。
@end deffn

@node セキュリティで考慮すべき点,環境設定辞書スキーマ,環境設定のための関数,logging config --- ログ記録の環境設定
@anchor{library/logging config security-considerations}@anchor{31ad}
@subsubsection セキュリティで考慮すべき点


logging の設定機能は便利さを提供します。その便利さの一部は設定ファイル内のテキストを logging の設定に使われる Python オブジェクトに変換する機能を提供することによって実現されています - たとえば、 @ref{31ae,,ユーザ定義オブジェクト} で説明されているような機能です。しかし、まさにこのメカニズム (実行可能オブジェクトをユーザー定義モジュールからインポートし、設定ファイルから読み込んだパラメータを使ってそれらを呼び出すこと) が任意のコードを呼び出すことに利用できる可能性があります。そして、この理由により、信頼できない情報源から取得した設定ファイルは `細心の注意' を払って取り扱わなければなりません。そのようなファイルをロードする場合、そのファイルがいかなる問題も起こさないと確認した上で実際にファイルをロードしてください。

@node 環境設定辞書スキーマ,環境設定ファイルの書式,セキュリティで考慮すべき点,logging config --- ログ記録の環境設定
@anchor{library/logging config configuration-dictionary-schema}@anchor{31af}@anchor{library/logging config logging-config-dictschema}@anchor{31a9}
@subsubsection 環境設定辞書スキーマ


ロギング設定を記述するには、生成するさまざまなオブジェクトと、それらのつながりを列挙しなければなりません。例えば、 'console' という名前のハンドラを生成し、'startup' という名前のロガーがメッセージを 'console' ハンドラに送るというようなことを記述します。これらのオブジェクトは、 @ref{8b,,logging} モジュールによって提供されるものに限らず、独自のフォーマッタやハンドラクラスを書くことも出来ます。このクラスへのパラメータは、 @code{sys.stderr} のような外部オブジェクトを必要とすることもあります。これらのオブジェクトとつながりを記述する構文は、以下の @ref{31b0,,オブジェクトの接続} で定義されています。

@menu
* 辞書スキーマの詳細:: 
* 増分設定:: 
* オブジェクトの接続:: 
* ユーザ定義オブジェクト:: 
* ハンドラの設定順序:: 
* 外部オブジェクトへのアクセス:: 
* 内部オブジェクトへのアクセス:: 
* インポート解決とカスタムインポーター:: 
* Configuring QueueHandler and QueueListener:: 

@end menu

@node 辞書スキーマの詳細,増分設定,,環境設定辞書スキーマ
@anchor{library/logging config dictionary-schema-details}@anchor{31b1}
@subsubsection 辞書スキーマの詳細


@ref{13c8,,dictConfig()} に渡される辞書は、以下のキーを含んでいなければなりません:


@itemize *

@item 
`version' - スキーマのバージョンを表す整数値に設定されます。現在有効な値は 1 だけですが、このキーがあることで、このスキーマは後方互換性を保ちながら発展できます。
@end itemize

その他すべてのキーは省略可能ですが、与えられたなら以下に記述するように解釈されます。以下のすべての場合において、 '環境設定辞書' と記載されている所では、その辞書に特殊な @code{'()'} キーがあるかを調べることで、カスタムのインスタンス化が必要であるか判断されます。その場合は、以下の @ref{31ae,,ユーザ定義オブジェクト} で記述されている機構がインスタンス生成に使われます。そうでなければ、インスタンス化するべきものを決定するのにコンテキストが使われます。
@anchor{library/logging config logging-config-dictschema-formatters}@anchor{31b2}

@itemize *

@item 
`formatters' - 対応する値は辞書で、そのそれぞれのキーがフォーマッタ id になり、それぞれの値が対応する @ref{16b0,,Formatter} インスタンスをどのように環境設定するかを記述する辞書になります。

設定辞書は @ref{16b0,,Formatter}  オブジェクトを作成するときの引数に対応する、次のようなオプションキーがないか探索されます。


@itemize *

@item 
@code{format}

@item 
@code{datefmt}

@item 
@code{style}

@item 
@code{validate} (バージョン3.8以降)

@item 
@code{defaults} (since version >=3.12)
@end itemize

オプションの @code{class} キーはフォーマッタークラスの名前を表します（モジュールとクラス名をドットで繋げる）。インスタンス化時の引数は @ref{16b0,,Formatter} と同じであるため、このキーは @ref{16b0,,Formatter} をカスタマイズしたサブクラスのインスタンス化に使うのがもっとも便利です。例えばトレースバックにさらに情報を付加したり、情報を要約代替クラスを実装するといったことが想定されます。もし、自作のフォーマッターが異なる引数や追加の設定引数を持つ場合は、 @ref{31ae,,ユーザ定義オブジェクト} を使うべきです。

@item 
`filters' - 対応する値は辞書で、そのそれぞれのキーがフィルタ id になり、それぞれの値が対応する Filter インスタンスをどのように環境設定するかを記述する辞書になります。

環境設定辞書は、(デフォルトが空文字列の) キー @code{name} を検索され、それらが @ref{1414,,logging.Filter} インスタンスを構成するのに使われます。

@item 
`handlers' - 対応する値は辞書で、そのそれぞれのキーがハンドラ id になり、それぞれの値が対応する Handler インスタンスをどのように環境設定するかを記述する辞書になります。

環境設定辞書は、以下のキーを検索されます:


@itemize *

@item 
@code{class} (必須)。これはハンドラクラスの完全に修飾された名前です。

@item 
@code{level} (任意)。ハンドラのレベルです。

@item 
@code{formatter} (任意)。このハンドラへのフォーマッタの id です。

@item 
@code{filters} (任意)。このハンドラへのフィルタの id のリストです。


バージョン 3.11 で変更: @code{filters} は id に加えてフィルタのインスタンスを受け取ることができるようになりました。

@end itemize

その他の `すべての' キーは、ハンドラのコンストラクタにキーワード引数として渡されます。例えば、以下のコード片が与えられたとすると:

@example
handlers:
  console:
    class : logging.StreamHandler
    formatter: brief
    level   : INFO
    filters: [allow_foo]
    stream  : ext://sys.stdout
  file:
    class : logging.handlers.RotatingFileHandler
    formatter: precise
    filename: logconfig.log
    maxBytes: 1024
    backupCount: 3
@end example

id が @code{console} であるハンドラが、 @code{sys.stdout} を根底のストリームにして、 @ref{1411,,logging.StreamHandler} としてインスタンス化されます。id が @code{file} であるハンドラが、 @code{filename='logconfig.log', maxBytes=1024, backupCount=3} をキーワード引数にして、 @ref{1941,,logging.handlers.RotatingFileHandler} としてインスタンス化されます。

@item 
`loggers' - 対応する値は辞書で、そのそれぞれのキーがロガー名になり、それぞれの値が対応する Logger インスタンスをどのように環境設定するかを記述する辞書になります。

環境設定辞書は、以下のキーを検索されます:


@itemize *

@item 
@code{level} (任意)。ロガーのレベルです。

@item 
@code{propagate} (任意)。ロガーの伝播の設定です。

@item 
@code{filters} (任意)。このロガーへのフィルタの id のリストです。


バージョン 3.11 で変更: @code{filters} は id に加えてフィルタのインスタンスを受け取ることができるようになりました。


@item 
@code{handlers} (任意)。このロガーへのハンドラの id のリストです。
@end itemize

指定されたロガーは、指定されたレベル、伝播、ハンドラに従って環境設定されます。

@item 
`root' - これは、ルートロガーへの設定になります。この環境設定の進行は、@code{propagate} 設定が適用されないことを除き、他のロガーと同じです。

@item 
`incremental' - この環境設定が既存の環境設定に対する増分として解釈されるかどうかです。この値のデフォルトは @code{False} で、指定された環境設定は、既存の @ref{d48,,fileConfig()} API によって使われているのと同じ意味上で、既存の環境設定を置き換えます。

指定された値が @code{True} なら、環境設定は @ref{31b3,,増分設定} の節で記述されているように進行します。

@item 
`disable_existing_loggers' - 既存の非ルートロガーをすべて無効にするべきかどうかです。この設定は、 @ref{d48,,fileConfig()} における同じ名前のパラメータと同じです。設定されていなければ、このパラメータのデフォルトは @code{True} です。この値は、 `incremental' が @code{True} なら無視されます。
@end itemize

@node 増分設定,オブジェクトの接続,辞書スキーマの詳細,環境設定辞書スキーマ
@anchor{library/logging config incremental-configuration}@anchor{31b4}@anchor{library/logging config logging-config-dict-incremental}@anchor{31b3}
@subsubsection 増分設定


増分設定に完全な柔軟性を提供するのは難しいです。例えば、フィルタやフォーマッタのようなオブジェクトは匿名なので、一旦環境設定がなされると、設定を拡張するときにそのような匿名オブジェクトを参照することができません。

さらに、一旦環境設定がなされた後、実行時にロガー、ハンドラ、フィルタ、フォーマッタのオブジェクトグラフを任意に変えなければならない例もありません。ロガーとハンドラの冗長性は、レベル (または、ロガーの場合には、伝播フラグ) を設定することによってのみ制御できます。安全な方法でオブジェクトグラフを任意に変えることは、マルチスレッド環境で問題となります。不可能ではないですが、その効用は実装に加えられる複雑さに見合いません。

従って、環境設定辞書の @code{incremental} キーが与えられ、これが @code{True} であるとき、システムは @code{formatters} と @code{filters} の項目を完全に無視し、@code{handlers} の項目の @code{level} 設定と、@code{loggers} と @code{root} の項目の @code{level} と @code{propagate} 設定のみを処理します。

環境設定辞書の値を使うことで、設定は pickle 化された辞書としてネットワークを通してソケットリスナに送ることができます。これにより、長時間起動するアプリケーションのロギングの冗長性を、アプリケーションを止めて再起動する必要なしに、いつでも変更することができます。

@node オブジェクトの接続,ユーザ定義オブジェクト,増分設定,環境設定辞書スキーマ
@anchor{library/logging config logging-config-dict-connections}@anchor{31b0}@anchor{library/logging config object-connections}@anchor{31b5}
@subsubsection オブジェクトの接続


このスキーマは、ロギングオブジェクトの一揃い - ロガー、ハンドラ、フォーマッタ、フィルタ - について記述します。これらは、オブジェクトグラフ上でお互い接続されます。従って、このスキーマは、オブジェクト間の接続を表現しなければなりません。例えば、環境設定で、特定のロガーが特定のハンドラに取り付けられたとします。この議論では、ロガーとハンドラが、これら 2 つの接続のそれぞれ送信元と送信先であるといえます。もちろん、この設定オブジェクト中では、これはハンドラへの参照を保持しているロガーで表されます。設定辞書中で、これは次のようになされます。まず、送信先オブジェクトを曖昧さなく指定する id を与えます。そして、その id を送信元オブジェクトの環境設定で使い、送信元とその id をもつ送信先が接続されていることを示します。

ですから、例えば、以下の YAML のコード片を例にとると:

@example
formatters:
  brief:
    # configuration for formatter with id 'brief' goes here
  precise:
    # configuration for formatter with id 'precise' goes here
handlers:
  h1: #This is an id
   # configuration of handler with id 'h1' goes here
   formatter: brief
  h2: #This is another id
   # configuration of handler with id 'h2' goes here
   formatter: precise
loggers:
  foo.bar.baz:
    # other configuration for logger 'foo.bar.baz'
    handlers: [h1, h2]
@end example

(注釈: YAML がここで使われているのは、辞書の等価な Python 形式よりもこちらのほうが少し読みやすいからです。)

ロガーの id は、プログラム上でロガーへの参照を得るために使われるロガー名で、たとえば @code{foo.bar.baz} です。フォーマッタとフィルタの id は、(上の @code{brief}, @code{precise} のような) 任意の文字列値にできます。これらは一時的なもので、環境設定辞書の処理にのみ意味があり、オブジェクト間の接続を決定するのに使われます。また、これらは設定の呼び出しが完了したとき、どこにも残りません。

上記のコード片は、@code{foo.bar.baz} という名のロガーに、ハンドラ id @code{h1} と @code{h2} で表される 2 つのハンドラを接続することを示します。@code{h1} のフォーマッタは id @code{brief} で記述されるもので、@code{h2} のフォーマッタは id @code{precise} で記述されるものです。

@node ユーザ定義オブジェクト,ハンドラの設定順序,オブジェクトの接続,環境設定辞書スキーマ
@anchor{library/logging config logging-config-dict-userdef}@anchor{31ae}@anchor{library/logging config user-defined-objects}@anchor{31b6}
@subsubsection ユーザ定義オブジェクト


このスキーマは、ハンドラ、フィルタ、フォーマッタのための、ユーザ定義オブジェクトをサポートします。(ロガーは、異なるインスタンスに対して異なる型を持つ必要はないので、この環境設定スキーマは、ユーザ定義ロガークラスをサポートしていません。)

設定されるオブジェクトは、それらの設定を詳述する辞書によって記述されます。場所によっては、あるオブジェクトがどのようにインスタンス化されるかというコンテキストを、ロギングシステムが推測できます。しかし、ユーザ定義オブジェクトがインスタンス化されるとき、システムはどのようにこれを行うかを知りません。ユーザ定義オブジェクトのインスタンス化を完全に柔軟なものにするため、ユーザは 'ファクトリ' - 設定辞書を引数として呼ばれ、インスタンス化されたオブジェクトを返す呼び出し可能オブジェクト - を提供する必要があります。これは特殊キー @code{'()'} で利用できる、ファクトリへの絶対インポートパスによって合図されます。ここに具体的な例を挙げます:

@example
formatters:
  brief:
    format: '%(message)s'
  default:
    format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
    datefmt: '%Y-%m-%d %H:%M:%S'
  custom:
      (): my.package.customFormatterFactory
      bar: baz
      spam: 99.9
      answer: 42
@end example

上記の YAML コード片は 3 つのフォーマッタを定義します。 1 つ目は、id が @code{brief} で、指定されたフォーマット文字列をもつ、標準 @ref{16b0,,logging.Formatter} インスタンスです。 2 つ目は、id が @code{default} で、長いフォーマットを持ち、時間フォーマットも定義していて、結果はその 2 つのフォーマット文字列で初期化された @ref{16b0,,logging.Formatter} になります。Python ソース形式で見ると、 @code{brief} と @code{default} フォーマッタは、それぞれ設定の部分辞書:

@example
@{
  'format' : '%(message)s'
@}
@end example

および:

@example
@{
  'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
  'datefmt' : '%Y-%m-%d %H:%M:%S'
@}
@end example

を持ち、これらの辞書が特殊キー @code{'()'} を持たないので、インスタンス化はコンテキストから推測され、結果として標準の @ref{16b0,,logging.Formatter} インスタンスが生成されます。id が @code{custom} である、3 つ目のフォーマッタの設定をする部分辞書は:

@example
@{
  '()' : 'my.package.customFormatterFactory',
  'bar' : 'baz',
  'spam' : 99.9,
  'answer' : 42
@}
@end example

で、ユーザ定義のインスタンス化が望まれることを示す特殊キー @code{'()'} を含みます。この場合、指定された呼び出し可能ファクトリオブジェクトが使われます。これが実際の呼び出し可能オブジェクトであれば、それが直接使われます - そうではなく、(この例でのように) 文字列を指定したなら、実際の呼び出し可能オブジェクトは、通常のインポート機構を使って検索されます。その呼び出し可能オブジェクトは、環境設定の部分辞書の、`残りの' 要素をキーワード引数として呼ばれます。上記の例では、id が @code{custom} のフォーマッタは、以下の呼び出しによって返されるものとみなされます:

@example
my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
@end example

@cartouche
@quotation 警告 
上記の例で @code{bar}, @code{spam} または @code{answer} のようなキーワード引数に指定する値は、設定作業の途中で処理されることなくそのまま呼び出し可能オブジェクトに渡されるため、 @code{cfg://foo} や @code{ext://bar} のような設定用の辞書や参照であってはいけません。
@end quotation
@end cartouche

キー @code{'()'} が特殊キーとして使われるのは、キーワードパラメータ名として不正で、呼び出しに使われるキーワード引数と衝突し得ないからです。@code{'()'} はまた、対応する値が呼び出し可能オブジェクトであると覚えやすくします。


バージョン 3.11 で変更: @code{handlers} と @code{loggers} の @code{filters} メンバーは id に加えてフィルタのインスタンスを受け取ることができるようになりました。


You can also specify a special key @code{'.'} whose value is a
mapping of attribute names to values. If found, the specified attributes will
be set on the user-defined object before it is returned. Thus, with the
following configuration:

@example
@{
  '()' : 'my.package.customFormatterFactory',
  'bar' : 'baz',
  'spam' : 99.9,
  'answer' : 42,
  '.' @{
    'foo': 'bar',
    'baz': 'bozz'
  @}
@}
@end example

戻り値のフォーマッタは属性 @code{foo} と @code{baz} をもち、それぞれの値は @code{'bar'} と @code{'bozz'} に設定されます。

@cartouche
@quotation 警告 
上記の例で @code{foo} や @code{baz} のような属性に設定する値は、フォーマッタの設定作業の途中で処理されることなくそのまま属性値として設定されるため、 @code{cfg://foo} や @code{ext://bar} のような設定用の辞書や参照であってはいけません。
@end quotation
@end cartouche

@node ハンドラの設定順序,外部オブジェクトへのアクセス,ユーザ定義オブジェクト,環境設定辞書スキーマ
@anchor{library/logging config handler-config-dict-order}@anchor{31b7}@anchor{library/logging config handler-configuration-order}@anchor{31b8}
@subsubsection ハンドラの設定順序


Handlers are configured in alphabetical order of their keys, and a configured
handler replaces the configuration dictionary in (a working copy of) the
@code{handlers} dictionary in the schema. If you use a construct such as
@code{cfg://handlers.foo}, then initially @code{handlers['foo']} points to the
configuration dictionary for the handler named @code{foo}, and later (once that
handler has been configured) it points to the configured handler instance.
Thus, @code{cfg://handlers.foo} could resolve to either a dictionary or a handler
instance. In general, it is wise to name handlers in a way such that dependent
handlers are configured `after' any handlers they depend on; that allows
something like @code{cfg://handlers.foo} to be used in configuring a handler that
depends on handler @code{foo}. If that dependent handler were named @code{bar},
problems would result, because the configuration of @code{bar} would be attempted
before that of @code{foo}, and @code{foo} would not yet have been configured.
However, if the dependent handler were named @code{foobar}, it would be configured
after @code{foo}, with the result that @code{cfg://handlers.foo} would resolve to
configured handler @code{foo}, and not its configuration dictionary.

@node 外部オブジェクトへのアクセス,内部オブジェクトへのアクセス,ハンドラの設定順序,環境設定辞書スキーマ
@anchor{library/logging config access-to-external-objects}@anchor{31b9}@anchor{library/logging config logging-config-dict-externalobj}@anchor{31ba}
@subsubsection 外部オブジェクトへのアクセス


環境設定が、例えば @code{sys.stderr} のような、設定の外部のオブジェクトへの参照を必要とすることがあります。設定辞書が Python コードで構成されていれば話は簡単ですが、これがテキストファイル (JSON, YAML 等) を通して提供されていると問題となります。テキストファイルでは、@code{sys.stderr} をリテラル文字列 @code{'sys.stderr'} と区別する標準の方法がありません。この区別を容易にするため、環境設定システムは、文字列中の特定の特殊接頭辞を見つけ、それらを特殊に扱います。例えば、リテラル文字列 @code{'ext://sys.stderr'} が設定中の値として与えられたら、この @code{ext://} は剥ぎ取られ、この値の残りが普通のインポート機構で処理されます。

このような接頭辞の処理は、プロトコルの処理と同じようになされます。どちらの機構も、正規表現 @code{^(?P<prefix>[a-z]+)://(?P<suffix>.*)$} にマッチする接頭辞を検索し、それによって @code{prefix} が認識されたなら、接頭辞に応じたやり方で @code{suffix} が処理され、その処理の結果によって文字列値が置き換えられます。接頭辞が認識されなければ、その文字列値はそのまま残されます。

@node 内部オブジェクトへのアクセス,インポート解決とカスタムインポーター,外部オブジェクトへのアクセス,環境設定辞書スキーマ
@anchor{library/logging config access-to-internal-objects}@anchor{31bb}@anchor{library/logging config logging-config-dict-internalobj}@anchor{31bc}
@subsubsection 内部オブジェクトへのアクセス


外部オブジェクトと同様、環境設定内部のオブジェクトへのアクセスを必要とすることもあります。これは、その各オブジェクトを司る環境設定システムによって暗黙に行われます。例えば、ロガーやハンドラの @code{level} に対する文字列値 @code{'DEBUG'} は、自動的に値 @code{logging.DEBUG} に変換されますし、@code{handlers}, @code{filters} および @code{formatter} の項目は、オブジェクト id を取って、適切な送信先オブジェクトを決定します。

しかし、ユーザ定義モジュールには、 @ref{8b,,logging} モジュールには分からないような、より一般的な機構が必要です。例えば、 @ref{31bd,,logging.handlers.MemoryHandler} があって、委譲する先の別のハンドラである @code{target} 引数を取るとします。システムはこのクラスをすでに知っていますから、設定中で、与えられた @code{target} は関連するターゲットハンドラのオブジェクト id でさえあればよく、システムはその id からハンドラを決定します。しかし、ユーザが @code{my.package.MyHandler} を定義して、それが @code{alternate} ハンドラを持つなら、設定システムは @code{alternate} がハンドラを参照していることを知りません。これを知らせるのに、一般的な解析システムで、ユーザはこのように指定できます:

@example
handlers:
  file:
    # configuration of file handler goes here

  custom:
    (): my.package.MyHandler
    alternate: cfg://handlers.file
@end example

リテラル文字列 @code{'cfg://handlers.file'} は、@code{ext://} 接頭辞が付いた文字列と同じように分析されますが、インポート名前空間ではなく、環境設定自体が検索されます。この機構は @code{str.format} でできるのと同じようにドットやインデックスのアクセスができます。従って、環境設定において以下のコード片が与えられれば:

@example
handlers:
  email:
    class: logging.handlers.SMTPHandler
    mailhost: localhost
    fromaddr: my_app@@domain.tld
    toaddrs:
      - support_team@@domain.tld
      - dev_team@@domain.tld
    subject: Houston, we have a problem.
@end example

in the configuration, the string @code{'cfg://handlers'} would resolve to
the dict with key @code{handlers}, the string @code{'cfg://handlers.email}
would resolve to the dict with key @code{email} in the @code{handlers} dict,
and so on.  The string @code{'cfg://handlers.email.toaddrs[1]} would
resolve to @code{'dev_team@@domain.tld'} and the string
@code{'cfg://handlers.email.toaddrs[0]'} would resolve to the value
@code{'support_team@@domain.tld'}. The @code{subject} value could be accessed
using either @code{'cfg://handlers.email.subject'} or, equivalently,
@code{'cfg://handlers.email[subject]'}.  The latter form only needs to be
used if the key contains spaces or non-alphanumeric characters. Please note
that the characters @code{[} and @code{]} are not allowed in the keys. If an
index value consists only of decimal digits, access will be attempted
using the corresponding integer value, falling back to the string
value if needed.

文字列 @code{cfg://handlers.myhandler.mykey.123} が与えられると、これは @code{config_dict['handlers']['myhandler']['mykey']['123']} と分析されます。文字列が @code{cfg://handlers.myhandler.mykey[123]} と指定されたら、システムは @code{config_dict['handlers']['myhandler']['mykey'][123]} から値を引き出そうとし、失敗したら @code{config_dict['handlers']['myhandler']['mykey']['123']} で代替します。

@node インポート解決とカスタムインポーター,Configuring QueueHandler and QueueListener,内部オブジェクトへのアクセス,環境設定辞書スキーマ
@anchor{library/logging config import-resolution-and-custom-importers}@anchor{31be}@anchor{library/logging config logging-import-resolution}@anchor{31bf}
@subsubsection インポート解決とカスタムインポーター


インポート解決は、デフォルトではインポートを行うために @ref{ad1,,__import__()} 組み込み関数を使用します。これを独自のインポートメカニズムに置き換えたいと思うかもしれません: もしそうなら、 @code{DictConfigurator} あるいはその上位クラスである @code{BaseConfigurator} クラスの @code{importer} 属性を置換することができます。ただし、この関数はクラスからディスクリプタ経由でアクセスされる点に注意する必要があります。インポートを行うために Python callable を使用していて、それをインスタンスレベルではなくクラスレベルで定義したければ、 @ref{453,,staticmethod()} でそれをラップする必要があります。例えば:

@example
from importlib import import_module
from logging.config import BaseConfigurator

BaseConfigurator.importer = staticmethod(import_module)
@end example

configurator `インスタンス' に対してインポート callable をセットする場合は、 @ref{453,,staticmethod()} でラップする必要はありません。

@node Configuring QueueHandler and QueueListener,,インポート解決とカスタムインポーター,環境設定辞書スキーマ
@anchor{library/logging config configure-queue}@anchor{1946}@anchor{library/logging config configuring-queuehandler-and-queuelistener}@anchor{31c0}
@subsubsection Configuring QueueHandler and QueueListener


If you want to configure a @ref{1b61,,QueueHandler}, noting that this
is normally used in conjunction with a @ref{242,,QueueListener}, you
can configure both together. After the configuration, the @code{QueueListener} instance
will be available as the @ref{31c1,,listener} attribute of
the created handler, and that in turn will be available to you using
@ref{1b62,,getHandlerByName()} and passing the name you have used for the
@code{QueueHandler} in your configuration. The dictionary schema for configuring the pair
is shown in the example YAML snippet below.

@example
handlers:
  qhand:
    class: logging.handlers.QueueHandler
    queue: my.module.queue_factory
    listener: my.package.CustomListener
    handlers:
      - hand_name_1
      - hand_name_2
      ...
@end example

The @code{queue} and @code{listener} keys are optional.

If the @code{queue} key is present, the corresponding value can be one of the following:


@itemize *

@item 
An object implementing the @ref{31c2,,Queue.put_nowait}
and @ref{31c3,,Queue.get} public API. For instance, this may be
an actual instance of @ref{15ac,,queue.Queue} or a subclass thereof, or a proxy
obtained by @ref{31c4,,multiprocessing.managers.SyncManager.Queue()}.

This is of course only possible if you are constructing or modifying
the configuration dictionary in code.

@item 
A string that resolves to a callable which, when called with no arguments, returns
the queue instance to use. That callable could be a @ref{15ac,,queue.Queue} subclass
or a function which returns a suitable queue instance,
such as @code{my.module.queue_factory()}.

@item 
A dict with a @code{'()'} key which is constructed in the usual way as discussed in
@ref{31ae,,ユーザ定義オブジェクト}. The result of this construction should be a
@ref{15ac,,queue.Queue} instance.
@end itemize

If the  @code{queue} key is absent, a standard unbounded @ref{15ac,,queue.Queue} instance is
created and used.

If the @code{listener} key is present, the corresponding value can be one of the following:


@itemize *

@item 
A subclass of @ref{242,,logging.handlers.QueueListener}. This is of course only
possible if you are constructing or modifying the configuration dictionary in
code.

@item 
A string which resolves to a class which is a subclass of @code{QueueListener}, such as
@code{'my.package.CustomListener'}.

@item 
A dict with a @code{'()'} key which is constructed in the usual way as discussed in
@ref{31ae,,ユーザ定義オブジェクト}. The result of this construction should be a
callable with the same signature as the @code{QueueListener} initializer.
@end itemize

If the @code{listener} key is absent, @ref{242,,logging.handlers.QueueListener} is used.

The values under the @code{handlers} key are the names of other handlers in the
configuration (not shown in the above snippet) which will be passed to the queue
listener.

Any custom queue handler and listener classes will need to be defined with the same
initialization signatures as @ref{1b61,,QueueHandler} and
@ref{242,,QueueListener}.


Added in version 3.12.


@node 環境設定ファイルの書式,,環境設定辞書スキーマ,logging config --- ログ記録の環境設定
@anchor{library/logging config configuration-file-format}@anchor{31c5}@anchor{library/logging config logging-config-fileformat}@anchor{31aa}
@subsubsection 環境設定ファイルの書式


@ref{d48,,fileConfig()} が解釈できる環境設定ファイルの形式は、 @ref{26,,configparser} の機能に基づいています。ファイルには、 @code{[loggers]}, @code{[handlers]}, @code{[formatters]} といったセクションが入っていなければならず、各セクションではファイル中で定義されている各タイプのエンティティを名前で指定しています。こうしたエンティティの各々について、そのエンティティをどう設定するかを示した個別のセクションがあります。すなわち、 @code{log01} という名前の @code{[loggers]} セクションにあるロガーに対しては、対応する詳細設定がセクション @code{[logger_log01]} に収められています。同様に、 @code{hand01} という名前の @code{[handlers]} セクションにあるハンドラは @code{[handler_hand01]} と呼ばれるセクションに設定をもつことになり、 @code{[formatters]} セクションにある @code{form01} は @code{[formatter_form01]} というセクションで設定が指定されています。ルートロガーの設定は @code{[logger_root]} と呼ばれるセクションで指定されていなければなりません。

@cartouche
@quotation 注釈 
@ref{d48,,fileConfig()} API は @ref{13c8,,dictConfig()} API よりも古く、ロギングのある種の側面についてカバーする機能に欠けています。たとえば @ref{d48,,fileConfig()} では数値レベルを超えたメッセージを単に拾うフィルタリングを行う @ref{1414,,Filter} オブジェクトを構成出来ません。 @ref{1414,,Filter} のインスタンスをロギングの設定において持つ必要があるならば、 @ref{13c8,,dictConfig()} を使う必要があるでしょう。設定の機能における将来の拡張は @ref{13c8,,dictConfig()} に対して行われることに注意してください。ですから、そうするのが便利であるときに新しい API に乗り換えるのは良い考えです。
@end quotation
@end cartouche

ファイルにおけるこれらのセクションの例を以下に示します。

@example
[loggers]
keys=root,log02,log03,log04,log05,log06,log07

[handlers]
keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09

[formatters]
keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
@end example

ルートロガーでは、レベルとハンドラのリストを指定しなければなりません。ルートロガーのセクションの例を以下に示します。

@example
[logger_root]
level=NOTSET
handlers=hand01
@end example

@code{level} エントリは @code{DEBUG, INFO, WARNING, ERROR, CRITICAL} または @code{NOTSET} のいずれかの値を取ることができます。ルートロガーでのみ、 @code{NOTSET} は全てのメッセージがログとして記録されることを意味します。レベルの値は @code{logging} パッケージの名前空間のコンテキストで @ref{25cd,,評価} されます。

@code{handlers} エントリはコンマで区切られたハンドラ名からなるリストで、@code{[handlers]} セクションになくてはなりません。また、これらの各ハンドラの名前に対応するセクションが設定ファイルに存在しなければなりません。

ルートロガー以外のロガーでは、いくつか追加の情報が必要になります。これは以下の例のように表されます。

@example
[logger_parser]
level=DEBUG
handlers=hand01
propagate=1
qualname=compiler.parser
@end example

@code{level} および @code{handlers} エントリはルートロガーのエントリと同様に解釈されますが、非ルートロガーのレベルが @code{NOTSET} に指定された場合、ロギングシステムはロガー階層のより上位のロガーにロガーの実効レベルを問い合わせるところが違います。@code{propagate} エントリは、メッセージをロガー階層におけるこのロガーの上位のハンドラに伝播させることを示す 1 に設定されるか、メッセージを階層の上位に伝播 `しない' ことを示す 0 に設定されます。@code{qualname} エントリはロガーのチャネル名を階層的に表したもの、すなわちアプリケーションがこのロガーを取得する際に使う名前になります。

ハンドラの環境設定を指定しているセクションは以下の例のようになります。

@example
[handler_hand01]
class=StreamHandler
level=NOTSET
formatter=form01
args=(sys.stdout,)
@end example

@code{class} エントリはハンドラのクラス (@code{logging} パッケージの名前空間において @ref{4a3,,eval()} で決定されます) を示します。 @code{level} はロガーの場合と同じように解釈され、 @code{NOTSET} は "すべてを記録する (log everything)" と解釈されます。

@code{formatter} エントリはこのハンドラのフォーマッタに対するキー名を表します。空文字列の場合、デフォルトのフォーマッタ (@code{logging._defaultFormatter}) が使われます。名前が指定されている場合、その名前は @code{[formatters]} セクションになくてはならず、対応するセクションが設定ファイル中になければなりません。

@code{args} は、 @code{logging} パッケージの名前空間のコンテキストで @ref{25cd,,評価} される時点では、ハンドラークラスのコンストラクタのための引数のリストです。典型的なコンストラクタの引数が生成される方法については、各ハンドラのコンストラクタまたは下記の例を参照してください。指定されなければデフォルトは @code{()} になります。

オプションの @code{kwargs} は、 @code{logging} パッケージの名前空間のコンテキストで @ref{25cd,,評価} される時点では、ハンドラークラスのコンストラクタのためのキーワード引数の辞書です。指定されなければデフォルトは @code{@{@}} になります。

@example
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form02
args=('python.log', 'w')

[handler_hand03]
class=handlers.SocketHandler
level=INFO
formatter=form03
args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)

[handler_hand04]
class=handlers.DatagramHandler
level=WARN
formatter=form04
args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)

[handler_hand05]
class=handlers.SysLogHandler
level=ERROR
formatter=form05
args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)

[handler_hand06]
class=handlers.NTEventLogHandler
level=CRITICAL
formatter=form06
args=('Python Application', '@w{'}, 'Application')

[handler_hand07]
class=handlers.SMTPHandler
level=WARN
formatter=form07
args=('localhost', 'from@@abc', ['user1@@abc', 'user2@@xyz'], 'Logger Subject')
kwargs=@{'timeout': 10.0@}

[handler_hand08]
class=handlers.MemoryHandler
level=NOTSET
formatter=form08
target=
args=(10, ERROR)

[handler_hand09]
class=handlers.HTTPHandler
level=NOTSET
formatter=form09
args=('localhost:9022', '/log', 'GET')
kwargs=@{'secure': True@}
@end example

フォーマッタの環境設定を指定しているセクションは以下のような形式です。

@example
[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s %(customfield)s
datefmt=
style=%
validate=True
defaults=@{'customfield': 'defaultvalue'@}
class=logging.Formatter
@end example

@ref{31b2,,フォーマッターのセクション} の辞書スキーマと同じキーを持つ、フォーマッター設定の引数です。

The @code{defaults} entry, when @ref{25cd,,evaluated} in the context of
the @code{logging} package's namespace, is a dictionary of default values for
custom formatting fields. If not provided, it defaults to @code{None}.

@cartouche
@quotation 注釈 
@ref{4a3,,eval()} を使用していることで、上述のようにソケット経由で設定を送受信するために @ref{1167,,listen()} を使用していることに起因する潜在的なセキュリティリスクがあります。そのリスクは、相互に信頼できない多数のユーザが同じマシン上でコードを実行する場合に制限されています; 詳細は @ref{1167,,listen()} ドキュメンテーションを参照してください。
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@item @ref{8b,,logging} モジュール

logging モジュールの API リファレンス。

@item @ref{8d,,logging.handlers} モジュール

logging モジュールに含まれる、便利なハンドラです。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node logging handlers --- ログ記録ハンドラー,platform --- 実行中プラットフォームの固有情報を参照する,logging config --- ログ記録の環境設定,汎用オペレーティングシステムサービス
@anchor{library/logging handlers doc}@anchor{31c6}@anchor{library/logging handlers logging-handlers-logging-handlers}@anchor{31c7}@anchor{library/logging handlers module-logging handlers}@anchor{8d}@anchor{library/logging handlers translation-repo}@anchor{31c8}
@subsection @code{logging.handlers} --- ログ記録ハンドラー


@geindex module; logging.handlers

`ソースコード:' Lib/logging/handlers.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/logging/handlers.py}

@subsubheading Important



このページには、リファレンス情報だけが含まれています。チュートリアルは、以下のページを参照してください


@itemize *

@item 
@ref{140e,,基本チュートリアル}

@item 
@ref{140f,,上級チュートリアル}

@item 
@ref{1410,,ロギングクックブック}
@end itemize


__________________________________________________________________


このパッケージでは、以下の便利なハンドラが提供されています。なお、これらのハンドラのうち、3 つ (@ref{1411,,StreamHandler}, @ref{1c53,,FileHandler} および @ref{149c,,NullHandler}) は、実際には @ref{8b,,logging} モジュール自身で定義されていますが、他のハンドラと一緒にここでドキュメント化します。

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

@end menu

@node StreamHandler,FileHandler,,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers stream-handler}@anchor{31c9}@anchor{library/logging handlers streamhandler}@anchor{31ca}
@subsubsection StreamHandler


@ref{8b,,logging} コアパッケージに含まれる @ref{1411,,StreamHandler} クラスは、ログ出力を `sys.stdout', `sys.stderr' あるいは何らかのファイル風 (file-like) オブジェクト (あるいは、より正確に言えば @code{write()} および @code{flush()} メソッドをサポートする何らかのオブジェクト) といったストリームに送信します。

@geindex StreamHandler (logging のクラス)
@anchor{library/logging handlers logging StreamHandler}@anchor{1411}
@deffn {クラス} logging.StreamHandler (stream=None)

@ref{1411,,StreamHandler} クラスの新たなインスタンスを返します。 `stream' が指定された場合、インスタンスはログ出力先として指定されたストリームを使います; そうでない場合、 `sys.stderr' が使われます。

@geindex emit() (logging.StreamHandler のメソッド)
@anchor{library/logging handlers logging StreamHandler emit}@anchor{31cb}
@deffn {メソッド} emit (record)

フォーマッタが指定されていれば、フォーマッタを使ってレコードを書式化します。 次に、レコードが @ref{31cc,,terminator} とともにストリームに書き込まれます。 例外情報が存在する場合、 @ref{a4f,,traceback.print_exception()} を使って書式化され、 ストリームの末尾につけられます。
@end deffn

@geindex flush() (logging.StreamHandler のメソッド)
@anchor{library/logging handlers logging StreamHandler flush}@anchor{31cd}
@deffn {メソッド} flush ()

ストリームの @ref{31cd,,flush()} メソッドを呼び出してバッファをフラッシュします。 @code{close()} メソッドは @ref{16af,,Handler} から継承しているため何も出力を行わないので、 @ref{31cd,,flush()} 呼び出しを明示的に行う必要があるかもしれません。
@end deffn

@geindex setStream() (logging.StreamHandler のメソッド)
@anchor{library/logging handlers logging StreamHandler setStream}@anchor{d47}
@deffn {メソッド} setStream (stream)

このインスタンスの stream と指定された値が異なる場合、指定された値に設定します。
新しい stream を設定する前に、古い stream はフラッシュされます。

@*パラメータ: 
@code{stream} -- ハンドラがこれから使う stream 。


@*戻り値: 
the old stream, if the stream was changed, or @code{None} if it wasn't.



Added in version 3.7.

@end deffn

@geindex terminator (logging.StreamHandler の属性)
@anchor{library/logging handlers logging StreamHandler terminator}@anchor{31cc}
@deffn {の属性} terminator

フォーマット済みのレコードをストリームに出力するときの終端として使われる文字列です。デフォルト値は @code{'\n'} です。

もし改行区切りにしたくない場合はハンドラーインスタンスの @code{terminator} 属性に空文字列を設定してください。

以前のバージョンでは、区切り文字は @code{'\n'} にハードコードされていました。


Added in version 3.2.

@end deffn
@end deffn

@node FileHandler,NullHandler,StreamHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers file-handler}@anchor{31ce}@anchor{library/logging handlers filehandler}@anchor{31cf}
@subsubsection FileHandler


@ref{8b,,logging} コアパッケージに含まれる @ref{1c53,,FileHandler} クラスは、ログ出力をディスク上のファイルに送信します。このクラスは出力機能を @ref{1411,,StreamHandler} から継承しています。

@geindex FileHandler (logging のクラス)
@anchor{library/logging handlers logging FileHandler}@anchor{1c53}
@deffn {クラス} logging.FileHandler (filename, mode='a', encoding=None, delay=False, errors=None)

Returns a new instance of the @ref{1c53,,FileHandler} class. The specified file is
opened and used as the stream for logging. If `mode' is not specified,
@code{'a'} is used.  If `encoding' is not @code{None}, it is used to open the file
with that encoding.  If `delay' is true, then file opening is deferred until the
first call to @ref{31d0,,emit()}. By default, the file grows indefinitely. If
`errors' is specified, it's used to determine how encoding errors are handled.


バージョン 3.6 で変更: 文字列値に加え、 @ref{266,,Path} オブジェクトも `filename' 引数が受け取るようになりました。



バージョン 3.9 で変更: `errors' 引数が追加されました。


@geindex close() (logging.FileHandler のメソッド)
@anchor{library/logging handlers logging FileHandler close}@anchor{31d1}
@deffn {メソッド} close ()

ファイルを閉じます。
@end deffn

@geindex emit() (logging.FileHandler のメソッド)
@anchor{library/logging handlers logging FileHandler emit}@anchor{31d0}
@deffn {メソッド} emit (record)

`record' をファイルに出力します。

終了時、ロギングがシャットダウンされたためにファイルがクローズされており、ファイルのモードが 'w' である場合、 record は出力されません (bpo-42378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42378} を参照してください)。
@end deffn
@end deffn

@node NullHandler,WatchedFileHandler,FileHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers null-handler}@anchor{31d2}@anchor{library/logging handlers nullhandler}@anchor{31d3}
@subsubsection NullHandler



Added in version 3.1.


@ref{8b,,logging} コアパッケージに含まれる @ref{149c,,NullHandler} クラスは、いかなる書式化も出力も行いません。これは本質的には、ライブラリ開発者に使われる 'no-op' ハンドラです。

@geindex NullHandler (logging のクラス)
@anchor{library/logging handlers logging NullHandler}@anchor{149c}
@deffn {クラス} logging.NullHandler

@ref{149c,,NullHandler} クラスの新しいインスタンスを返します。

@geindex emit() (logging.NullHandler のメソッド)
@anchor{library/logging handlers logging NullHandler emit}@anchor{31d4}
@deffn {メソッド} emit (record)

このメソッドは何もしません。
@end deffn

@geindex handle() (logging.NullHandler のメソッド)
@anchor{library/logging handlers logging NullHandler handle}@anchor{31d5}
@deffn {メソッド} handle (record)

このメソッドは何もしません。
@end deffn

@geindex createLock() (logging.NullHandler のメソッド)
@anchor{library/logging handlers logging NullHandler createLock}@anchor{31d6}
@deffn {メソッド} createLock ()

アクセスが特殊化される必要がある I/O が下にないので、このメソッドはロックに対して @code{None} を返します。
@end deffn
@end deffn

@ref{149c,,NullHandler} の使い方の詳しい情報は、 @ref{31d7,,ライブラリのためのロギングの設定} を参照してください。

@node WatchedFileHandler,BaseRotatingHandler,NullHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers watched-file-handler}@anchor{31d8}@anchor{library/logging handlers watchedfilehandler}@anchor{31d9}
@subsubsection WatchedFileHandler


The @ref{31da,,WatchedFileHandler} class, located in the @code{logging.handlers}
module, is a @code{FileHandler} which watches the file it is logging to. If
the file changes, it is closed and reopened using the file name.

ファイルはログファイルをローテーションさせる `newsyslog' や `logrotate' のようなプログラムを使うことで変更されることがあります。このハンドラは、 Unix/Linux で使われることを意図していますが、ファイルが最後にログを出力してから変わったかどうかを監視します。 (ファイルはデバイスや inode が変わることで変わったと判断します。) ファイルが変わったら古いファイルのストリームは閉じて、現在のファイルを新しいストリームを取得するために開きます。

このハンドラを Windows で使うことは適切ではありません。というのも Windows では開いているログファイルを移動したり削除したりできないからです - logging はファイルを排他的ロックを掛けて開きます - そのためこうしたハンドラは必要ないのです。さらに、 Windows では `ST_INO' がサポートされていません; @ref{26d,,stat()} はこの値として常に 0 を返します。

@geindex WatchedFileHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers WatchedFileHandler}@anchor{31da}
@deffn {クラス} logging.handlers.WatchedFileHandler (filename, mode='a', encoding=None, delay=False, errors=None)

Returns a new instance of the @ref{31da,,WatchedFileHandler} class. The specified
file is opened and used as the stream for logging. If `mode' is not specified,
@code{'a'} is used.  If `encoding' is not @code{None}, it is used to open the file
with that encoding.  If `delay' is true, then file opening is deferred until the
first call to @ref{31db,,emit()}.  By default, the file grows indefinitely. If
`errors' is provided, it determines how encoding errors are handled.


バージョン 3.6 で変更: 文字列値に加え、 @ref{266,,Path} オブジェクトも `filename' 引数が受け取るようになりました。



バージョン 3.9 で変更: `errors' 引数が追加されました。


@geindex reopenIfNeeded() (logging.handlers.WatchedFileHandler のメソッド)
@anchor{library/logging handlers logging handlers WatchedFileHandler reopenIfNeeded}@anchor{eb4}
@deffn {メソッド} reopenIfNeeded ()

ファイルが変更されていないかチェックします。
もし変更されていれば、手始めにレコードをファイルに出力し、既存のストリームはフラッシュして閉じられ、ファイルが再度開かれます。


Added in version 3.6.

@end deffn

@geindex emit() (logging.handlers.WatchedFileHandler のメソッド)
@anchor{library/logging handlers logging handlers WatchedFileHandler emit}@anchor{31db}
@deffn {メソッド} emit (record)

レコードをファイルに出力しますが、最初に @ref{eb4,,reopenIfNeeded()} を呼び出して、変更があった場合はファイルを再度開きます。
@end deffn
@end deffn

@node BaseRotatingHandler,RotatingFileHandler,WatchedFileHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers base-rotating-handler}@anchor{31dc}@anchor{library/logging handlers baserotatinghandler}@anchor{31dd}
@subsubsection BaseRotatingHandler


The @ref{31de,,BaseRotatingHandler} class, located in the @code{logging.handlers}
module, is the base class for the rotating file handlers,
@ref{1941,,RotatingFileHandler} and @ref{1163,,TimedRotatingFileHandler}. You should
not need to instantiate this class, but it has attributes and methods you may
need to override.

@geindex BaseRotatingHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers BaseRotatingHandler}@anchor{31de}
@deffn {クラス} logging.handlers.BaseRotatingHandler (filename, mode, encoding=None, delay=False, errors=None)

パラメータは @code{FileHandler} と同じです。属性は次の通りです:

@geindex namer (logging.handlers.BaseRotatingHandler の属性)
@anchor{library/logging handlers logging handlers BaseRotatingHandler namer}@anchor{31df}
@deffn {の属性} namer

この属性に callable がセットされた場合、 @ref{31e0,,rotation_filename()} メソッドはこの callable に委譲されます。 callable に渡されるパラメータは @ref{31e0,,rotation_filename()} に渡されたものです。

@cartouche
@quotation 注釈 
namer 関数はロールオーバー中にかなりの回数呼ばれます。そのため、できるだけ単純で、速くあるべきです。さらに、それは与えられた入力に対しては常に同じ出力を返すべきです。そうでなければ、ロールオーバーの振る舞いは期待通りに動かないかもしれません。

namer 属性にローテーションの際に使われるファイル名に埋め込むための特定の属性を保持しようとする場合に注意が必要なことは、注意喚起しておくべきでしょう。たとえば @ref{1941,,RotatingFileHandler} は、ローテーションが期待通りに動作するために、名前に連続した番号を含むようなファイル名のリストを持つことを期待します。また @ref{1163,,TimedRotatingFileHandler} は (ハンドラの初期化時に渡された @code{backupCount} にもとづいて) 削除すべき古いファイルを決定しながら、古いログファイルを削除します。この仕組みが動作するためには、ファイル名は名前に含まれる日付や時刻でソート可能である必要があり、 namer はそれを尊重しなければなりません (namer がこの規則を尊重したくない場合、そのような namer は @ref{31e1,,getFilesToDelete()} メソッドが特定の命名規則に適合するようにオーバーライドされた @ref{1163,,TimedRotatingFileHandler} の派生クラス内で使う必要があるでしょう)。
@end quotation
@end cartouche


Added in version 3.3.

@end deffn

@geindex rotator (logging.handlers.BaseRotatingHandler の属性)
@anchor{library/logging handlers logging handlers BaseRotatingHandler rotator}@anchor{31e2}
@deffn {の属性} rotator

この属性に callable がセットされた場合、 @ref{31e3,,rotate()} メソッドはこの callable に委譲されます。 callable に渡されるパラメータは @ref{31e3,,rotate()} に渡されたものです。


Added in version 3.3.

@end deffn

@geindex rotation_filename() (logging.handlers.BaseRotatingHandler のメソッド)
@anchor{library/logging handlers logging handlers BaseRotatingHandler rotation_filename}@anchor{31e0}
@deffn {メソッド} rotation_filename (default_name)

ローテートを行う際にログファイルのファイル名を変更します。

このメソッドは、ファイル名をカスタマイズするために提供されます。

デフォルト実装は、ハンドラの 'namer' 属性が callable だった場合、その callable を呼んでデフォルト名を渡します。属性が callable でない場合 (デフォルトは @code{None} です)、名前は変更せずに返されます。

@*パラメータ: 
@code{default_name} -- ログファイルのデフォルトのファイル名。



Added in version 3.3.

@end deffn

@geindex rotate() (logging.handlers.BaseRotatingHandler のメソッド)
@anchor{library/logging handlers logging handlers BaseRotatingHandler rotate}@anchor{31e3}
@deffn {メソッド} rotate (source, dest)

ローテートが行われる時、現在のログをローテートします。

デフォルト実装は、 ハンドラの 'rotator' 属性が callable だった場合、その callable を呼んで source と dest 引数を渡します。属性が callable でない場合 (デフォルトは @code{None} です)、単に source が destination に改名されます。

@*パラメータ: 

@itemize *

@item 
@code{source} -- ソースファイル名。これは通常ベースファイル名 、例えば 'test.log' となります。

@item 
@code{dest} -- 変更先ファイル名。これは通常ソースファイルをローテートしたもの (例えば 'test.log.1') です。
@end itemize



Added in version 3.3.

@end deffn
@end deffn

これらの属性が存在する理由は、サブクラス化を省略できるようにするためです。 @ref{1941,,RotatingFileHandler} と @ref{1163,,TimedRotatingFileHandler} のインスタンスに対して同じ callable が使えます。もし namer や rotator callable が例外を上げれば、 @code{emit()} 呼び出しで発生した他の例外と同じ方法で、つまりハンドラの @code{handleError()} メソッドによって扱われます。

ローテート処理に大幅な変更を加える必要があれば、メソッドをオーバーライドすることができます。

例えば、 @ref{31e4,,rotator と namer を使ってログローテートをカスタマイズする} を参照してください。

@node RotatingFileHandler,TimedRotatingFileHandler,BaseRotatingHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers rotating-file-handler}@anchor{31e5}@anchor{library/logging handlers rotatingfilehandler}@anchor{31e6}
@subsubsection RotatingFileHandler


The @ref{1941,,RotatingFileHandler} class, located in the @code{logging.handlers}
module, supports rotation of disk log files.

@geindex RotatingFileHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers RotatingFileHandler}@anchor{1941}
@deffn {クラス} logging.handlers.RotatingFileHandler (filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False, errors=None)

@ref{1941,,RotatingFileHandler} クラスの新たなインスタンスを返します。
指定されたファイルが開かれ、ログ記録のためのストリームとして使われます。
`mode' が指定されなかった場合、 @code{'a'} が使われます。
`encoding' が @code{None} でない場合、その値はファイルを開くときのエンコーディングとして使われます。
`delay' が真ならば、ファイルを開くのは最初の @ref{31e7,,emit()} 呼び出しまで遅らせられます。
デフォルトでは、ファイルは無制限に大きくなりつづけます。 `errors' が提供されると、エンコーディングエラーの処理方法を決定します。

`maxBytes' および `backupCount' 値を指定することで、あらかじめ決められたサイズでファイルをロールオーバ (`rollover') させることができます。
指定サイズを超えそうになると、ファイルは閉じられ、暗黙のうちに新たなファイルが開かれます。
ロールオーバは現在のログファイルの長さが `maxBytes' に近くなると常に起きますが、 `maxBytes' または `backupCount' がゼロならロールオーバは起きなくなってしまうので、一般的には `backupCount' を少なくとも 1 に設定し `maxBytes' を非ゼロにするのが良いでしょう。
`backupCount' が非ゼロのとき、システムは古いログファイルをファイル名に ".1", ".2" といった拡張子を追加して保存します。
例えば、 `backupCount' が 5 で、基本のファイル名が @code{app.log} なら、 @code{app.log}, @code{app.log.1}, @code{app.log.2} ... と続き、 @code{app.log.5} までを得ることになります。
ログの書き込み対象になるファイルは常に @code{app.log} です。このファイルが満杯になると、ファイルは閉じられ、 @code{app.log.1} に名前が変更されます。
@code{app.log.1}, @code{app.log.2} などが存在する場合、それらのファイルはそれぞれ @code{app.log.2}, @code{app.log.3} といった具合に名前が変更されます。


バージョン 3.6 で変更: 文字列値に加え、 @ref{266,,Path} オブジェクトも `filename' 引数が受け取るようになりました。



バージョン 3.9 で変更: `errors' 引数が追加されました。


@geindex doRollover() (logging.handlers.RotatingFileHandler のメソッド)
@anchor{library/logging handlers logging handlers RotatingFileHandler doRollover}@anchor{31e8}
@deffn {メソッド} doRollover ()

上述のような方法でロールオーバを行います。
@end deffn

@geindex emit() (logging.handlers.RotatingFileHandler のメソッド)
@anchor{library/logging handlers logging handlers RotatingFileHandler emit}@anchor{31e7}
@deffn {メソッド} emit (record)

上述のようなロールオーバを行いながら、レコードをファイルに出力します。
@end deffn

@geindex shouldRollover() (logging.handlers.RotatingFileHandler のメソッド)
@anchor{library/logging handlers logging handlers RotatingFileHandler shouldRollover}@anchor{31e9}
@deffn {メソッド} shouldRollover (record)

See if the supplied record would cause the file to exceed the configured size limit.
@end deffn
@end deffn

@node TimedRotatingFileHandler,SocketHandler,RotatingFileHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers timed-rotating-file-handler}@anchor{31ea}@anchor{library/logging handlers timedrotatingfilehandler}@anchor{31eb}
@subsubsection TimedRotatingFileHandler


The @ref{1163,,TimedRotatingFileHandler} class, located in the
@code{logging.handlers} module, supports rotation of disk log files at certain
timed intervals.

@geindex TimedRotatingFileHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler}@anchor{1163}
@deffn {クラス} logging.handlers.TimedRotatingFileHandler (filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None, errors=None)

@ref{1163,,TimedRotatingFileHandler} クラスの新たなインスタンスを返します。 `filename' に指定したファイルを開き、ログ出力先のストリームとして使います。ログファイルのローテーション時には、ファイル名に拡張子 (suffix) をつけます。ログファイルのローテーションは `when' および `interval' の積に基づいて行います。

`when' は `interval' の単位を指定するために使います。使える値は下表の通りです。大小文字の区別は行いません。


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

値

@tab

`interval' の単位

@tab

`atTime' の使用有無/使用方法

@item

@code{'S'}

@tab

秒

@tab

無視

@item

@code{'M'}

@tab

分

@tab

無視

@item

@code{'H'}

@tab

時間

@tab

無視

@item

@code{'D'}

@tab

日

@tab

無視

@item

@code{'W0'-'W6'}

@tab

曜日 (0=月曜)

@tab

初期のロールオーバー時刻の算出に使用

@item

@code{'midnight'}

@tab

`atTime' が指定されなかった場合は深夜に、そうでない場合は `atTime' の時刻にロールオーバーされます

@tab

初期のロールオーバー時刻の算出に使用

@end multitable


曜日ベースのローテーションを使う場合は、月曜として 'W0' を、火曜として 'W1' を、…、日曜として 'W6' を指定します。このケースの場合は、 `interval' は使われません。

古いログファイルの保存時、ロギングシステムによりファイル名に拡張子が付けられます。 ロールオーバ間隔によって、strftime の @code{%Y-%m-%d_%H-%M-%S} 形式またはその前方の一部を使って、日付と時間に基づいた拡張子が付けられます。

最初に次のロールオーバー時間を計算するとき (ハンドラが生成されるとき)、次のローテーションがいつ起こるかを計算するために、既存のログファイルの最終変更時刻または現在の時間が使用されます。

`utc' 引数が true の場合時刻は UTC になり、それ以外では現地時間が使われます。

`backupCount' がゼロでない場合、保存されるファイル数は高々 `backupCount' 個で、それ以上のファイルがロールオーバされる時に作られるならば、一番古いものが削除されます。削除のロジックは interval で決まるファイルを削除するので、 interval を変えると古いファイルが残ったままになることもあります。

`delay' が true なら、ファイルを開くのは @ref{31ec,,emit()} の最初の呼び出しまで延期されます。

`atTime' が @code{None} でない場合、それは @code{datetime.time} インスタンスでなければなりません。ロールオーバーが「夜中」「特定の曜日」に設定されていて、ロールが発生する時刻を指定します。 `atTime' の値は `初期' のロールオーバーの計算に使われますが、後続のロールオーバーは通常の間隔の計算で算出されます。

`errors' が指定されると、エンコーディングエラーの取り扱い方法を決定します。

@cartouche
@quotation 注釈 
最初のロールオーバーの計算はハンドラーが初期化されたときに行われます。後続のロールオーバーは、ロールオーバーが発生し、ロールオーバーが出力した時にのみ行われます。これを念頭に置いておかないと混乱する可能性があります。例えば、インターバルが `毎分' に設定されていて、1分ごとにログファイルが常に生成されるとは限りません。アプリケーションが実行されている間、1分に1回以上のログ出力されて `いるとすると' 毎分、分割されたログファイルが出力されますが、そうでなく、5分ごとに出力される場合は、出力されずにロールオーバーが実行されなかった時間分のギャップが生じます。
@end quotation
@end cartouche


バージョン 3.4 で変更: `atTime' パラメータが追加されました。



バージョン 3.6 で変更: 文字列値に加え、 @ref{266,,Path} オブジェクトも `filename' 引数が受け取るようになりました。



バージョン 3.9 で変更: `errors' 引数が追加されました。


@geindex doRollover() (logging.handlers.TimedRotatingFileHandler のメソッド)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler doRollover}@anchor{31ed}
@deffn {メソッド} doRollover ()

上述のような方法でロールオーバを行います。
@end deffn

@geindex emit() (logging.handlers.TimedRotatingFileHandler のメソッド)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler emit}@anchor{31ec}
@deffn {メソッド} emit (record)

上で説明した方法でロールオーバを行いながら、レコードをファイルに出力します。
@end deffn

@geindex getFilesToDelete() (logging.handlers.TimedRotatingFileHandler のメソッド)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler getFilesToDelete}@anchor{31e1}
@deffn {メソッド} getFilesToDelete ()

ロールオーバーの一環として削除されるファイル名のリストを返します。それらのファイルは、ハンドラによって書き込まれた最も古いバックアップログファイルの絶対パスです。
@end deffn

@geindex shouldRollover() (logging.handlers.TimedRotatingFileHandler のメソッド)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler shouldRollover}@anchor{31ee}
@deffn {メソッド} shouldRollover (record)

See if enough time has passed for a rollover to occur and if it has, compute
the next rollover time.
@end deffn
@end deffn

@node SocketHandler,DatagramHandler,TimedRotatingFileHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers socket-handler}@anchor{31ef}@anchor{library/logging handlers sockethandler}@anchor{31f0}
@subsubsection SocketHandler


The @ref{1164,,SocketHandler} class, located in the @code{logging.handlers} module,
sends logging output to a network socket. The base class uses a TCP socket.

@geindex SocketHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers SocketHandler}@anchor{1164}
@deffn {クラス} logging.handlers.SocketHandler (host, port)

アドレスが `host' および `port' で与えられた遠隔のマシンと通信するようにした @ref{1164,,SocketHandler} クラスのインスタンスを生成して返します。


バージョン 3.4 で変更: @code{port} に @code{None} を指定すると、Unix ドメインソケットが @code{host} 値を用いて作られます - そうでない場合は TCP ソケットが作られます。


@geindex close() (logging.handlers.SocketHandler のメソッド)
@anchor{library/logging handlers logging handlers SocketHandler close}@anchor{31f1}
@deffn {メソッド} close ()

ソケットを閉じます。
@end deffn

@geindex emit() (logging.handlers.SocketHandler のメソッド)
@anchor{library/logging handlers logging handlers SocketHandler emit}@anchor{31f2}
@deffn {メソッド} emit ()

レコードの属性辞書を pickle して、バイナリ形式でソケットに書き込みます。ソケット操作でエラーが生じた場合、暗黙のうちにパケットは捨てられます。事前に接続が失われていた場合、接続を再度確立します。受信端でレコードを unpickle して @ref{11e8,,LogRecord} にするには、 @ref{318a,,makeLogRecord()} 関数を使ってください。
@end deffn

@geindex handleError() (logging.handlers.SocketHandler のメソッド)
@anchor{library/logging handlers logging handlers SocketHandler handleError}@anchor{31f3}
@deffn {メソッド} handleError ()

@ref{31f2,,emit()} の処理中に発生したエラーを処理します。よくある原因は接続の消失です。次のイベント発生時に再試行できるようにソケットを閉じます。
@end deffn

@geindex makeSocket() (logging.handlers.SocketHandler のメソッド)
@anchor{library/logging handlers logging handlers SocketHandler makeSocket}@anchor{31f4}
@deffn {メソッド} makeSocket ()

サブクラスで必要なソケット形式を詳細に定義できるようにするためのファクトリメソッドです。デフォルトの実装では、 TCP ソケット (@ref{150b,,socket.SOCK_STREAM}) を生成します。
@end deffn

@geindex makePickle() (logging.handlers.SocketHandler のメソッド)
@anchor{library/logging handlers logging handlers SocketHandler makePickle}@anchor{31f5}
@deffn {メソッド} makePickle (record)

レコードの属性辞書をバイナリ形式に pickle したものの先頭に長さ情報を付け、ソケットを介して送信できるようにして返します。
この操作の詳細は次のコードと同等です:

@example
data = pickle.dumps(record_attr_dict, 1)
datalen = struct.pack('>L', len(data))
return datalen + data
@end example

pickle が完全に安全というわけではないことに注意してください。セキュリティに関して心配なら、より安全なメカニズムを実装するためにこのメソッドをオーバーライドすると良いでしょう。例えば、 HMAC を使って pickle に署名して、受け取る側ではそれを検証することができます。あるいはまた、受け取る側でグローバルなオブジェクトの unpickle を無効にすることができます。
@end deffn

@geindex send() (logging.handlers.SocketHandler のメソッド)
@anchor{library/logging handlers logging handlers SocketHandler send}@anchor{31f6}
@deffn {メソッド} send (packet)

pickle したバイト文字列 `packet' をソケットに送信します。
送信するバイト文字列のフォーマットは、 @ref{31f5,,makePickle()} のドキュメントで解説されています。

この関数はネットワークがビジーの時に発生する部分的送信に対応しています。
@end deffn

@geindex createSocket() (logging.handlers.SocketHandler のメソッド)
@anchor{library/logging handlers logging handlers SocketHandler createSocket}@anchor{86d}
@deffn {メソッド} createSocket ()

ソケットの生成を試みます。失敗時には、指数的な減速アルゴリズムを使います。最初の失敗時には、ハンドラは送ろうとしていたメッセージを落とします。続くメッセージが同じインスタンスで扱われたとき、幾らかの時間が経過するまで接続を試みません。デフォルトのパラメタは、最初の遅延時間が 1 秒で、その遅延時間の後でそれでも接続が確保できないなら、遅延時間は 2 倍づつになり、最大で 30 秒になります。

この働きは、以下のハンドラ属性で制御されます:


@itemize *

@item 
@code{retryStart} (最初の遅延時間、デフォルトは 1.0 秒)。

@item 
@code{retryFactor} (乗数、デフォルトは 2.0)。

@item 
@code{retryMax} (最大遅延時間、デフォルトは 30.0 秒)。
@end itemize

つまり、ハンドラが使われた `後に' リモートリスナが起動した場合、メッセージが失われてしまうことがあります (ハンドラは、遅延時間が経過するまで接続を試みようとさえせず、その遅延時間中に通知なくメッセージを捨てるので)。
@end deffn
@end deffn

@node DatagramHandler,SysLogHandler,SocketHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers datagram-handler}@anchor{31f7}@anchor{library/logging handlers datagramhandler}@anchor{31f8}
@subsubsection DatagramHandler


The @ref{1165,,DatagramHandler} class, located in the @code{logging.handlers}
module, inherits from @ref{1164,,SocketHandler} to support sending logging messages
over UDP sockets.

@geindex DatagramHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers DatagramHandler}@anchor{1165}
@deffn {クラス} logging.handlers.DatagramHandler (host, port)

アドレスが `host' および `port' で与えられた遠隔のマシンと通信するようにした @ref{1165,,DatagramHandler} クラスのインスタンスを生成して返します。

@cartouche
@quotation 注釈 
UDP はストリーミングプロトコルではないため、このハンドラのインスタンスと `host' に指定したホストとの間に持続的なコネクションはありません。この理由から、ネットワークソケットを使う場合、イベントがログされるごとに DNS のルックアップを行わなければならないかもしれず、それによりシステムにある程度の待ち時間をもたらす可能性があります。この待ち時間が問題になる場合、自身でルックアップを行い、ホスト名の代わりにルックアップの結果得られた IP アドレスを使ってハンドラを初期化することができます。
@end quotation
@end cartouche


バージョン 3.4 で変更: @code{port} に @code{None} を指定すると、Unix ドメインソケットが @code{host} 値を用いて作られます - そうでない場合は UDP ソケットが作られます。


@geindex emit() (logging.handlers.DatagramHandler のメソッド)
@anchor{library/logging handlers logging handlers DatagramHandler emit}@anchor{31f9}
@deffn {メソッド} emit ()

レコードの属性辞書を pickle して、バイナリ形式でソケットに書き込みます。ソケット操作でエラーが生じた場合、暗黙のうちにパケットは捨てられます。事前に接続が失われていた場合、接続を再度確立します。受信端でレコードを unpickle して @ref{11e8,,LogRecord} にするには、 @ref{318a,,makeLogRecord()} 関数を使ってください。
@end deffn

@geindex makeSocket() (logging.handlers.DatagramHandler のメソッド)
@anchor{library/logging handlers logging handlers DatagramHandler makeSocket}@anchor{31fa}
@deffn {メソッド} makeSocket ()

ここで @ref{1164,,SocketHandler} のファクトリメソッドをオーバライドして、 UDP ソケット (@ref{150a,,socket.SOCK_DGRAM}) を生成しています。
@end deffn

@geindex send() (logging.handlers.DatagramHandler のメソッド)
@anchor{library/logging handlers logging handlers DatagramHandler send}@anchor{31fb}
@deffn {メソッド} send (s)

pickle したバイト文字列をソケットに送信します。
送信するバイト文字列のフォーマットは、 @ref{31f5,,SocketHandler.makePickle()} のドキュメントで解説されています。
@end deffn
@end deffn

@node SysLogHandler,NTEventLogHandler,DatagramHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers syslog-handler}@anchor{31fc}@anchor{library/logging handlers sysloghandler}@anchor{31fd}
@subsubsection SysLogHandler


The @ref{86c,,SysLogHandler} class, located in the @code{logging.handlers} module,
supports sending logging messages to a remote or local Unix syslog.

@geindex SysLogHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers SysLogHandler}@anchor{86c}
@deffn {クラス} logging.handlers.SysLogHandler (address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM, timeout=None)

Returns a new instance of the @ref{86c,,SysLogHandler} class intended to
communicate with a remote Unix machine whose address is given by `address' in
the form of a @code{(host, port)} tuple.  If `address' is not specified,
@code{('localhost', 514)} is used.  The address is used to open a socket.  An
alternative to providing a @code{(host, port)} tuple is providing an address as a
string, for example '/dev/log'. In this case, a Unix domain socket is used to
send the message to the syslog. If `facility' is not specified,
@code{LOG_USER} is used. The type of socket opened depends on the
`socktype' argument, which defaults to @ref{150a,,socket.SOCK_DGRAM} and thus
opens a UDP socket. To open a TCP socket (for use with the newer syslog
daemons such as rsyslog), specify a value of @ref{150b,,socket.SOCK_STREAM}.
If `timeout' is specified, it sets a timeout (in seconds) for the socket operations.
This can help prevent the program from hanging indefinitely if the syslog server is
unreachable. By default, `timeout' is @code{None}, meaning no timeout is applied.

使用中のサーバが UDP ポート 514 を待機していない場合、 @ref{86c,,SysLogHandler} が正常に動作していないように見える場合があります。その場合、ドメインソケットに使うべきアドレスを調べてください。そのアドレスはシステムによって異なります。例えば、Linux システムでは通常 '/dev/log' ですが、 OS X では '/var/run/syslog' です。プラットフォームを確認し、適切なアドレスを使う必要があります (アプリケーションを複数のプラットフォーム上で動作させる必要がある場合、実行時に確認する必要があるかもしれません)。Windows では、多くの場合、UDP オプションを使用する必要があります。

@cartouche
@quotation 注釈 
macOS 12.x (Monterey) でApple社はsyslogデーモンの振る舞いを変更し、デーモンはドメインソケットを待ち受けなくなりました。したがってこのシステム上では @ref{86c,,SysLogHandler} が動作することは期待できません。

より詳細な情報は gh-91070@footnote{https://github.com/python/cpython/issues/91070} を参照して下さい。
@end quotation
@end cartouche


バージョン 3.2 で変更: `socktype' が追加されました。



バージョン 3.14 で変更: `timeout' が追加されました


@geindex close() (logging.handlers.SysLogHandler のメソッド)
@anchor{library/logging handlers logging handlers SysLogHandler close}@anchor{31fe}
@deffn {メソッド} close ()

遠隔ホストへのソケットを閉じます。
@end deffn

@geindex createSocket() (logging.handlers.SysLogHandler のメソッド)
@anchor{library/logging handlers logging handlers SysLogHandler createSocket}@anchor{86b}
@deffn {メソッド} createSocket ()

Tries to create a socket and, if it's not a datagram socket, connect it
to the other end. This method is called during handler initialization,
but it's not regarded as an error if the other end isn't listening at
this point - the method will be called again when emitting an event, if
there is no socket at that point.


Added in version 3.11.

@end deffn

@geindex emit() (logging.handlers.SysLogHandler のメソッド)
@anchor{library/logging handlers logging handlers SysLogHandler emit}@anchor{31ff}
@deffn {メソッド} emit (record)

レコードは書式化された後、 syslog サーバに送信されます。例外情報が存在しても、サーバには `送信されません' 。


バージョン 3.2.1 で変更: (参照: bpo-12168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12168}) 初期のバージョンでは、 syslog デーモンに送られるメッセージは常に NUL バイトで終端していました。初期のバージョンの syslog デーモンが NUL 終端されたメッセージを期待していたからです - たとえ、それが適切な仕様 (
@geindex RFC; RFC 5424
RFC 5424@footnote{https://datatracker.ietf.org/doc/html/rfc5424.html}) にはなかったとしても。 syslog デーモンの新しいバージョンは NUL バイトを期待せず、代わりにもしそれがある場合は削除します。さらに、より最近のデーモン (RFC 5424 により忠実なバージョン) は、メッセージの一部として NUL バイトを通します。

このような異なるデーモンの振る舞いすべてに対して syslog メッセージの取り扱いをより容易にするため、 NUL バイトの追加はクラスレベル属性 @code{append_nul} を使用して設定できるようになりました。これはデフォルトで @code{True} (既存の振る舞いを保持) ですが、 @code{SysLogHandler} インスタンスが NUL 終端文字を追加 `しない' ように @code{False} にセットすることができます。



バージョン 3.3 で変更: (参照: bpo-12419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12419}) 以前のバージョンでは、メッセージソースを識別するための "ident" あるいは "tag" プリフィックス機能はありませんでした。これは、今ではクラスレベル属性を使用して指定することができるようになりました。デフォルトでは既存の振る舞いを保持するために @code{""} ですが、特定の @code{SysLogHandler} インスタンスが扱うすべてのメッセージに識別子を前置するようにそれをオーバーライドすることができます。識別子はバイトではなくテキストでなければならず、正確にそのままメッセージに前置されることに注意してください。

@end deffn

@geindex encodePriority() (logging.handlers.SysLogHandler のメソッド)
@anchor{library/logging handlers logging handlers SysLogHandler encodePriority}@anchor{3200}
@deffn {メソッド} encodePriority (facility, priority)

ファシリティおよび優先度を整数に符号化します。値は文字列でも整数でも渡すことができます。文字列が渡された場合、内部の対応付け辞書が使われ、整数に変換されます。

シンボリックな @code{LOG_} 値は @ref{86c,,SysLogHandler} で定義されています。これは @code{sys/syslog.h} ヘッダーファイルで定義された値を反映しています。

`優先度'


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

名前 (文字列)

@tab

シンボル値

@item

@code{alert}

@tab

LOG_ALERT

@item

@code{crit} or @code{critical}

@tab

LOG_CRIT

@item

@code{debug}

@tab

LOG_DEBUG

@item

@code{emerg} or @code{panic}

@tab

LOG_EMERG

@item

@code{err} or @code{error}

@tab

LOG_ERR

@item

@code{info}

@tab

LOG_INFO

@item

@code{notice}

@tab

LOG_NOTICE

@item

@code{warn} or @code{warning}

@tab

LOG_WARNING

@end multitable


`ファシリティ'


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

名前 (文字列)

@tab

シンボル値

@item

@code{auth}

@tab

LOG_AUTH

@item

@code{authpriv}

@tab

LOG_AUTHPRIV

@item

@code{cron}

@tab

LOG_CRON

@item

@code{daemon}

@tab

LOG_DAEMON

@item

@code{ftp}

@tab

LOG_FTP

@item

@code{kern}

@tab

LOG_KERN

@item

@code{lpr}

@tab

LOG_LPR

@item

@code{mail}

@tab

LOG_MAIL

@item

@code{news}

@tab

LOG_NEWS

@item

@code{syslog}

@tab

LOG_SYSLOG

@item

@code{user}

@tab

LOG_USER

@item

@code{uucp}

@tab

LOG_UUCP

@item

@code{local0}

@tab

LOG_LOCAL0

@item

@code{local1}

@tab

LOG_LOCAL1

@item

@code{local2}

@tab

LOG_LOCAL2

@item

@code{local3}

@tab

LOG_LOCAL3

@item

@code{local4}

@tab

LOG_LOCAL4

@item

@code{local5}

@tab

LOG_LOCAL5

@item

@code{local6}

@tab

LOG_LOCAL6

@item

@code{local7}

@tab

LOG_LOCAL7

@end multitable

@end deffn

@geindex mapPriority() (logging.handlers.SysLogHandler のメソッド)
@anchor{library/logging handlers logging handlers SysLogHandler mapPriority}@anchor{3201}
@deffn {メソッド} mapPriority (levelname)

ログレベル名を syslog 優先度名に対応付けます。カスタムレベルを使用している場合や、デフォルトアルゴリズムがニーズに適していない場合には、このメソッドをオーバーライドする必要があるかもしれません。デフォルトアルゴリズムは、 @code{DEBUG}, @code{INFO}, @code{WARNING}, @code{ERROR}, @code{CRITICAL} を等価な syslog 名に、他のすべてのレベル名を "warning" に対応付けます。
@end deffn
@end deffn

@node NTEventLogHandler,SMTPHandler,SysLogHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers nt-eventlog-handler}@anchor{3202}@anchor{library/logging handlers nteventloghandler}@anchor{3203}
@subsubsection NTEventLogHandler


The @ref{3204,,NTEventLogHandler} class, located in the @code{logging.handlers}
module, supports sending logging messages to a local Windows NT, Windows 2000 or
Windows XP event log. Before you can use it, you need Mark Hammond's Win32
extensions for Python installed.

@geindex NTEventLogHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers NTEventLogHandler}@anchor{3204}
@deffn {クラス} logging.handlers.NTEventLogHandler (appname, dllname=None, logtype='Application')

@ref{3204,,NTEventLogHandler} クラスの新たなインスタンスを返します。 `appname' はイベントログに表示する際のアプリケーション名を定義するために使われます。この名前を使って適切なレジストリエントリが生成されます。 `dllname' はログに保存するメッセージ定義の入った .dll または .exe ファイルへの完全修飾パス名を与えなければなりません (指定されない場合、 @code{'win32service.pyd'} が使われます - このライブラリは Win32 拡張とともにインストールされ、いくつかのプレースホルダとなるメッセージ定義を含んでいます)。これらのプレースホルダを利用すると、メッセージの発信源全体がログに記録されるため、イベントログは巨大になるので注意してください。 `logtype' は @code{'Application'}, @code{'System'}, @code{'Security'} のいずれかで、デフォルトは @code{'Application'} です。

@geindex close() (logging.handlers.NTEventLogHandler のメソッド)
@anchor{library/logging handlers logging handlers NTEventLogHandler close}@anchor{3205}
@deffn {メソッド} close ()

現時点では、イベントログエントリの発信源としてのアプリケーション名をレジストリから除去することはできます。しかしこれを行うと、イベントログビューアで意図した通りにログが見えなくなるでしょう - これはイベントログが .dll 名を取得するためにレジストリにアクセスできなければならないからです。現在のバージョンではこの操作を行いません。
@end deffn

@geindex emit() (logging.handlers.NTEventLogHandler のメソッド)
@anchor{library/logging handlers logging handlers NTEventLogHandler emit}@anchor{3206}
@deffn {メソッド} emit (record)

メッセージ ID、イベントカテゴリ、イベント型を決定し、メッセージを NT イベントログに記録します。
@end deffn

@geindex getEventCategory() (logging.handlers.NTEventLogHandler のメソッド)
@anchor{library/logging handlers logging handlers NTEventLogHandler getEventCategory}@anchor{3207}
@deffn {メソッド} getEventCategory (record)

レコードに対するイベントカテゴリを返します。自作のカテゴリを指定したい場合、このメソッドをオーバライドしてください。このクラスのバージョンのメソッドは 0 を返します。
@end deffn

@geindex getEventType() (logging.handlers.NTEventLogHandler のメソッド)
@anchor{library/logging handlers logging handlers NTEventLogHandler getEventType}@anchor{3208}
@deffn {メソッド} getEventType (record)

レコードのイベント型を返します。自作の型を指定したい場合、このメソッドをオーバライドしてください。このクラスのバージョンのメソッドは、ハンドラの `typemap' 属性を使って対応付けを行います。この属性は @code{__init__()} で初期化され、 @code{DEBUG}, @code{INFO}, @code{WARNING}, @code{ERROR}, @code{CRITICAL} が入っています。自作のレベルを使っているのなら、このメソッドをオーバライドするか、ハンドラの `typemap' 属性に適切な辞書を配置する必要があるでしょう。
@end deffn

@geindex getMessageID() (logging.handlers.NTEventLogHandler のメソッド)
@anchor{library/logging handlers logging handlers NTEventLogHandler getMessageID}@anchor{3209}
@deffn {メソッド} getMessageID (record)

レコードのメッセージ ID を返します。自作のメッセージを使っているのなら、ロガーに渡される `msg' を書式化文字列ではなく ID にします。その上で、辞書参照を行ってメッセージ ID を得ます。このクラスのバージョンでは 1 を返します。この値は @code{win32service.pyd} における基本メッセージ ID です。
@end deffn
@end deffn

@node SMTPHandler,MemoryHandler,NTEventLogHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers smtp-handler}@anchor{320a}@anchor{library/logging handlers smtphandler}@anchor{320b}
@subsubsection SMTPHandler


The @ref{18b2,,SMTPHandler} class, located in the @code{logging.handlers} module,
supports sending logging messages to an email address via SMTP.

@geindex SMTPHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers SMTPHandler}@anchor{18b2}
@deffn {クラス} logging.handlers.SMTPHandler (mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)

新たな @ref{18b2,,SMTPHandler} クラスのインスタンスを返します。インスタンスは email の from および to アドレス行、および subject 行とともに初期化されます。 `toaddrs' は文字列からなるリストでなければなりません。非標準の SMTP ポートを指定するには、 `mailhost' 引数に (host, port) のタプル形式を指定します。文字列を使った場合、標準の SMTP ポートが使われます。もし SMTP サーバが認証を必要とするならば、 (username, password) のタプル形式を `credentials' 引数に指定することができます。

セキュアプロトコル (TLS) の使用を指定するには `secure' 引数にタプルを渡してください。これは認証情報が渡された場合のみ使用されます。タプルは、空のタプルか、キーファイルの名前を持つ1要素のタプルか、またはキーファイルと証明書ファイルの名前を持つ2要素のタプルのいずれかでなければなりません。 (このタプルは @ref{1350,,smtplib.SMTP.starttls()} メソッドに渡されます。)

SMTP サーバとのコミュニケーションのために、 `timeout' 引数を使用してタイムアウトを指定することができます。


バージョン 3.3 で変更: `timeout' 引数が追加されました。


@geindex emit() (logging.handlers.SMTPHandler のメソッド)
@anchor{library/logging handlers logging handlers SMTPHandler emit}@anchor{320c}
@deffn {メソッド} emit (record)

レコードを書式化し、指定されたアドレスに送信します。
@end deffn

@geindex getSubject() (logging.handlers.SMTPHandler のメソッド)
@anchor{library/logging handlers logging handlers SMTPHandler getSubject}@anchor{320d}
@deffn {メソッド} getSubject (record)

レコードに応じたサブジェクト行を指定したいなら、このメソッドをオーバライドしてください。
@end deffn
@end deffn

@node MemoryHandler,HTTPHandler,SMTPHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers memory-handler}@anchor{320e}@anchor{library/logging handlers memoryhandler}@anchor{320f}
@subsubsection MemoryHandler


The @ref{31bd,,MemoryHandler} class, located in the @code{logging.handlers} module,
supports buffering of logging records in memory, periodically flushing them to a
`target' handler. Flushing occurs whenever the buffer is full, or when an
event of a certain severity or greater is seen.

@ref{31bd,,MemoryHandler} はより一般的な抽象クラス、 @ref{3210,,BufferingHandler} のサブクラスです。この抽象クラスでは、ログ記録するレコードをメモリ上にバッファリングします。各レコードがバッファに追加される毎に、 @code{shouldFlush()} を呼び出してバッファをフラッシュすべきかどうか調べます。フラッシュする必要がある場合、 @code{flush()} がフラッシュ処理を行うものと想定されます。

@geindex BufferingHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers BufferingHandler}@anchor{3210}
@deffn {クラス} logging.handlers.BufferingHandler (capacity)

容量つきのバッファーを設定してハンドラーが初期化されます。 `capacity' はバッファ可能なログレコード数を意味します。

@geindex emit() (logging.handlers.BufferingHandler のメソッド)
@anchor{library/logging handlers logging handlers BufferingHandler emit}@anchor{3211}
@deffn {メソッド} emit (record)

レコードをバッファに追加します。 @ref{3212,,shouldFlush()} が true を返す場合、バッファを処理するために @ref{3213,,flush()} を呼び出します。
@end deffn

@geindex flush() (logging.handlers.BufferingHandler のメソッド)
@anchor{library/logging handlers logging handlers BufferingHandler flush}@anchor{3213}
@deffn {メソッド} flush ()

For a @ref{3210,,BufferingHandler} instance, flushing means that it sets the
buffer to an empty list. This method can be overwritten to implement more useful
flushing behavior.
@end deffn

@geindex shouldFlush() (logging.handlers.BufferingHandler のメソッド)
@anchor{library/logging handlers logging handlers BufferingHandler shouldFlush}@anchor{3212}
@deffn {メソッド} shouldFlush (record)

バッファが許容量に達している場合に @code{True} を返します。このメソッドは自作のフラッシュ処理方針を実装するためにオーバライドすることができます。
@end deffn
@end deffn

@geindex MemoryHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers MemoryHandler}@anchor{31bd}
@deffn {クラス} logging.handlers.MemoryHandler (capacity, flushLevel=ERROR, target=None, flushOnClose=True)

@ref{31bd,,MemoryHandler} クラスの新たなインスタンスを返します。
インスタンスはサイズ `capacity' （バッファされるレコード数）のバッファとともに初期化されます。
`flushLevel' が指定されていない場合、 @code{ERROR} が使われます。
`target' が指定されていない場合、ハンドラが何らかの意味のある処理を行う前に @ref{3214,,setTarget()} でターゲットを指定する必要があります。
`flushOnClose' が @code{False} に指定されていた場合、ハンドラが閉じられるときにバッファはフラッシュ `されません' 。
`flushOnClose' が指定されていないか @code{True} に指定されていた場合、ハンドラが閉じられるときのバッファのフラッシュは以前の挙動になります。


バージョン 3.6 で変更: `flushOnClose' パラメータが追加されました。


@geindex close() (logging.handlers.MemoryHandler のメソッド)
@anchor{library/logging handlers logging handlers MemoryHandler close}@anchor{3215}
@deffn {メソッド} close ()

@ref{3216,,flush()} を呼び出し、ターゲットを @code{None} に設定してバッファを消去します。
@end deffn

@geindex flush() (logging.handlers.MemoryHandler のメソッド)
@anchor{library/logging handlers logging handlers MemoryHandler flush}@anchor{3216}
@deffn {メソッド} flush ()

For a @ref{31bd,,MemoryHandler} instance, flushing means just sending the buffered
records to the target, if there is one. The buffer is also cleared when
buffered records are sent to the target. Override if you want different behavior.
@end deffn

@geindex setTarget() (logging.handlers.MemoryHandler のメソッド)
@anchor{library/logging handlers logging handlers MemoryHandler setTarget}@anchor{3214}
@deffn {メソッド} setTarget (target)

ターゲットハンドラをこのハンドラに設定します。
@end deffn

@geindex shouldFlush() (logging.handlers.MemoryHandler のメソッド)
@anchor{library/logging handlers logging handlers MemoryHandler shouldFlush}@anchor{3217}
@deffn {メソッド} shouldFlush (record)

バッファが一杯になっているか、 `flushLevel' またはそれ以上のレコードでないかを調べます。
@end deffn
@end deffn

@node HTTPHandler,QueueHandler,MemoryHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers http-handler}@anchor{3218}@anchor{library/logging handlers httphandler}@anchor{3219}
@subsubsection HTTPHandler


The @ref{102c,,HTTPHandler} class, located in the @code{logging.handlers} module,
supports sending logging messages to a web server, using either @code{GET} or
@code{POST} semantics.

@geindex HTTPHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers HTTPHandler}@anchor{102c}
@deffn {クラス} logging.handlers.HTTPHandler (host, url, method='GET', secure=False, credentials=None, context=None)

@ref{102c,,HTTPHandler} クラスの新たなインスタンスを返します。特別なポートを使う必要がある場合、`host' は @code{host:port} の形式で使うことができます。 `method' が指定されない場合、 @code{GET} が使われます。 `secure' が真の場合、HTTPS 接続が使われます。 HTTPS 接続で使用する SSL 設定のために `context' 引数を @ref{357,,ssl.SSLContext} のインスタンスに設定することができます。 `credentials' を指定する場合、BASIC 認証の際の HTTP 'Authorization' ヘッダに使われるユーザIDとパスワードからなる 2要素タプルを渡してください。 credentials を指定する場合、ユーザIDとパスワードが通信中に平文として剥き出しにならないよう、secure=True も指定すべきです。


バージョン 3.5 で変更: `context' パラメータが追加されました。


@geindex mapLogRecord() (logging.handlers.HTTPHandler のメソッド)
@anchor{library/logging handlers logging handlers HTTPHandler mapLogRecord}@anchor{321a}
@deffn {メソッド} mapLogRecord (record)

URL エンコードされて Web サーバに送信することになる、 @code{record} に基づく辞書を供給します。デフォルトの実装では単に @code{record.__dict__} を返します。例えば @ref{11e8,,LogRecord} のサブセットのみを Web サーバに送信する場合や、 サーバーに送信する内容を特別にカスタマイズする必要がある場合には、このメソッドをオーバライドできます。
@end deffn

@geindex emit() (logging.handlers.HTTPHandler のメソッド)
@anchor{library/logging handlers logging handlers HTTPHandler emit}@anchor{321b}
@deffn {メソッド} emit (record)

レコードを URL エンコードされた辞書形式で Web サーバに送信します。レコードを送信のために辞書に変換するために @ref{321a,,mapLogRecord()} が呼び出されます。
@end deffn

@cartouche
@quotation 注釈 
Web server に送信するためのレコードを準備することは一般的な書式化操作とは同じではありませんので、 @ref{316e,,setFormatter()} を使って @ref{16b0,,Formatter} を指定することは、 @ref{102c,,HTTPHandler} には効果はありません。 @ref{3177,,format()} を呼び出す代わりに、このハンドラは @ref{321a,,mapLogRecord()} を呼び出し、その後その返却辞書を Web server に送信するのに適した様式にエンコードするために @ref{1095,,urllib.parse.urlencode()}  を呼び出します。
@end quotation
@end cartouche
@end deffn

@node QueueHandler,QueueListener,HTTPHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers queue-handler}@anchor{321c}@anchor{library/logging handlers queuehandler}@anchor{321d}
@subsubsection QueueHandler



Added in version 3.2.


The @ref{1b61,,QueueHandler} class, located in the @code{logging.handlers} module,
supports sending logging messages to a queue, such as those implemented in the
@ref{bb,,queue} or @ref{98,,multiprocessing} modules.

@ref{242,,QueueListener} クラスとともに @ref{1b61,,QueueHandler} を使うと、ロギングを行うスレッドから分離されたスレッド上でハンドラを動かすことができます。これは、クライアントに対してサービスするスレッドができるだけ速く応答する必要がある一方、別のスレッド上で (@ref{18b2,,SMTPHandler} によって電子メールを送信するような) 潜在的に遅い操作が行われるような、ウェブアプリケーションおよびその他のサービスアプリケーションにおいて重要です。

@geindex QueueHandler (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers QueueHandler}@anchor{1b61}
@deffn {クラス} logging.handlers.QueueHandler (queue)

@ref{1b61,,QueueHandler} クラスの新しいインスタンスを返します。インスタンスは、キューにメッセージを送るように初期化されます。キューは任意のキューのようなオブジェクトが可能です; それはそのまま @ref{321e,,enqueue()} メソッドによって使用されます。そのメソッドはメッセージを送る方法を知っている必要があります。もしタスクのトラッキングAPIにキューが必要でない場合はキューとして @ref{d61,,SimpleQueue} のインスタンスが使用できます。

@cartouche
@quotation 注釈 
@ref{98,,multiprocessing} を使っている場合、 @ref{d61,,SimpleQueue} を使うことは避けてください。代わりに @ref{1b89,,multiprocessing.Queue} を使ってください。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
The @ref{98,,multiprocessing} module uses an internal logger created and
accessed via @ref{321f,,get_logger()}.
@ref{1b89,,multiprocessing.Queue} will log @code{DEBUG} level messages upon
items being queued. If those log messages are processed by a
@ref{1b61,,QueueHandler} using the same @ref{1b89,,multiprocessing.Queue} instance,
it will cause a deadlock or infinite recursion.
@end quotation
@end cartouche

@geindex emit() (logging.handlers.QueueHandler のメソッド)
@anchor{library/logging handlers logging handlers QueueHandler emit}@anchor{3220}
@deffn {メソッド} emit (record)

Enqueues the result of preparing the LogRecord. Should an exception
occur (e.g. because a bounded queue has filled up), the
@ref{3175,,handleError()} method is called to handle the
error. This can result in the record silently being dropped (if
@ref{1412,,logging.raiseExceptions} is @code{False}) or a message printed to
@code{sys.stderr} (if @ref{1412,,logging.raiseExceptions} is @code{True}).
@end deffn

@geindex prepare() (logging.handlers.QueueHandler のメソッド)
@anchor{library/logging handlers logging handlers QueueHandler prepare}@anchor{3221}
@deffn {メソッド} prepare (record)

キューに追加するためレコードを準備します。このメソッドが返したオブジェクトがキューに追加されます。

基底の実装はレコードがメッセージや引数と、またもし存在すれば、発生した例外およびスタック情報と統合されるようにフォーマットします。またこの実装では非 pickle 化不可能な要素をレコードから削除します。特に、この実装はレコードの @code{msg} と @code{message} 属性を (ハンドラの @ref{199,,format()} メソッドを呼び出すことによって得られる) 統合されたメッセージで上書きし、同時に @code{args}, @code{exc_info}, @code{exc_text} の3つの属性値をすべて @code{None} に設定します。

レコードを dict や JSON 文字列に変換したい場合や、オリジナルのレコードを変更せずに修正済のコピーを送りたい場合は、このメソッドをオーバーライドすると良いでしょう。

@cartouche
@quotation 注釈 
基底の実装は、レコードを pickle 化可能にしつつ、さらなるフォーマット処理を防ぐために、メッセージを引数でフォーマットしてフォーマットされたメッセージを @code{message} と @code{msg} 属性に設定し、同時に @code{args} と @code{exc_text} 属性を @code{None} に設定します。このことは、 @ref{242,,QueueListener} 側のハンドラが必要なフォーマット処理を行う、たとえば例外のフォーマット処理を行う、ための必要な情報が得られないかもしれないことを意味します。そのため、 @code{QueueHandler} の派生クラスにおいてこのメソッドを、たとえば @code{exc_text} 属性が @code{None} に設定されないように、オーバーライドしたいと考えるかもしれません。この場合、 @code{message} / @code{msg} / @code{args} といった属性の変更はレコードが pickle 化可能であることを保証することと関係しており、元の @code{args} の値が pickle 化可能かどうかによって、これらの属性の変更が避けられないかもしれないということに注意してください (この点については、自分のコードだけでなく依存するライブラリのコードも考慮しなければならないことにも注意してください)
@end quotation
@end cartouche
@end deffn

@geindex enqueue() (logging.handlers.QueueHandler のメソッド)
@anchor{library/logging handlers logging handlers QueueHandler enqueue}@anchor{321e}
@deffn {メソッド} enqueue (record)

キューにレコードを  @code{put_nowait()} を使ってエンキューします; ブロッキングやタイムアウト、あるいはなにか特別なキューの実装を使いたければ、これをオーバライドしてみてください。
@end deffn

@geindex listener (logging.handlers.QueueHandler の属性)
@anchor{library/logging handlers logging handlers QueueHandler listener}@anchor{31c1}
@deffn {の属性} listener

When created via configuration using @ref{13c8,,dictConfig()}, this
attribute will contain a @ref{242,,QueueListener} instance for use with this
handler. Otherwise, it will be @code{None}.


Added in version 3.12.

@end deffn
@end deffn

@node QueueListener,,QueueHandler,logging handlers --- ログ記録ハンドラー
@anchor{library/logging handlers queue-listener}@anchor{3222}@anchor{library/logging handlers queuelistener}@anchor{3223}
@subsubsection QueueListener



Added in version 3.2.


The @ref{242,,QueueListener} class, located in the @code{logging.handlers}
module, supports receiving logging messages from a queue, such as those
implemented in the @ref{bb,,queue} or @ref{98,,multiprocessing} modules. The
messages are received from a queue in an internal thread and passed, on
the same thread, to one or more handlers for processing. While
@ref{242,,QueueListener} is not itself a handler, it is documented here
because it works hand-in-hand with @ref{1b61,,QueueHandler}.

@ref{1b61,,QueueHandler} クラスとともに @ref{242,,QueueListener} を使うと、ロギングを行うスレッドから分離されたスレッド上でハンドラを動かすことができます。これは、クライアントに対してサービスするスレッドができるだけ速く応答する必要がある一方、別のスレッド上で (@ref{18b2,,SMTPHandler} によって電子メールを送信するような) 潜在的に遅い操作が行われるような、ウェブアプリケーションおよびその他のサービスアプリケーションにおいて重要です。

@geindex QueueListener (logging.handlers のクラス)
@anchor{library/logging handlers logging handlers QueueListener}@anchor{242}
@deffn {クラス} logging.handlers.QueueListener (queue, *handlers, respect_handler_level=False)

@ref{242,,QueueListener} クラスの新しいインスタンスを返します。インスタンスは、メッセージを送るためのキューと、キューに格納されたエントリーを処理するハンドラーのリストが設定されて初期化されます。キューは任意のキューのようなオブジェクトが可能です; それはそのまま @ref{3224,,dequeue()} メソッドによって使用されます。そのメソッドはメッセージを送る方法を知っている必要があります。もしタスクのトラッキングAPIにキューが必要でない場合はキューとして @ref{d61,,SimpleQueue} のインスタンスが使用できます（トラッキングAPIが使用可能な場合は使用されます）。

@cartouche
@quotation 注釈 
@ref{98,,multiprocessing} を使っている場合、 @ref{d61,,SimpleQueue} を使うことは避けてください。代わりに @ref{1b89,,multiprocessing.Queue} を使ってください。
@end quotation
@end cartouche

もし @code{respect_handler_level} が @code{True} なら、メッセージをハンドラーに渡すか決める時に（メッセージのレベルに比べて）ハンドラーのレベルが尊重されます。そうでない場合は依然のPythonバージョンと同様にすべてのメッセージは常にハンドラーに渡されます。


バージョン 3.5 で変更: The @code{respect_handler_level} argument was added.



バージョン 3.14 で変更: @ref{242,,QueueListener} can now be used as a context manager via
@ref{186,,with}. When entering the context, the listener is started. When
exiting the context, the listener is stopped.
@ref{26a8,,__enter__()} returns the
@ref{242,,QueueListener} object.


@geindex dequeue() (logging.handlers.QueueListener のメソッド)
@anchor{library/logging handlers logging handlers QueueListener dequeue}@anchor{3224}
@deffn {メソッド} dequeue (block)

キューからレコードを取り除き、それを返します。ブロッキングすることがあります。

ベース実装は @code{get()} を使用します。タイムアウトを有効にしたい場合や、カスタムのキュー実装を使いたい場合は、このメソッドをオーバーライドすると良いでしょう。
@end deffn

@geindex prepare() (logging.handlers.QueueListener のメソッド)
@anchor{library/logging handlers logging handlers QueueListener prepare}@anchor{3225}
@deffn {メソッド} prepare (record)

レコードを扱うための準備をします。

この実装は渡されたレコードをそのまま返します。その値をハンドラに渡す前に何らかのカスタムな整列化 (marshalling) あるいはレコードに対する操作を行う必要があれば、このメソッドをオーバーライドすると良いでしょう。
@end deffn

@geindex handle() (logging.handlers.QueueListener のメソッド)
@anchor{library/logging handlers logging handlers QueueListener handle}@anchor{3226}
@deffn {メソッド} handle (record)

レコードを処理します。

これは、ハンドラをループしてそれらに処理すべきレコードを渡します。ハンドラに渡される実際のオブジェクトは、 @ref{3225,,prepare()} から返されたものです。
@end deffn

@geindex start() (logging.handlers.QueueListener のメソッド)
@anchor{library/logging handlers logging handlers QueueListener start}@anchor{243}
@deffn {メソッド} start ()

リスナーを開始します。

これは、 LogRecord を処理するキューを監視するために、バックグラウンドスレッドを開始します。


バージョン 3.14 で変更: Raises @ref{244,,RuntimeError} if called and the listener is already
running.

@end deffn

@geindex stop() (logging.handlers.QueueListener のメソッド)
@anchor{library/logging handlers logging handlers QueueListener stop}@anchor{3227}
@deffn {メソッド} stop ()

リスナーを停止します。

スレッドに終了するように依頼し、終了するまで待ちます。アプリケーションの終了前にこのメソッドを呼ばないと、いくつかのレコードがキューに残り、処理されなくなるかもしれないことに注意してください。
@end deffn

@geindex enqueue_sentinel() (logging.handlers.QueueListener のメソッド)
@anchor{library/logging handlers logging handlers QueueListener enqueue_sentinel}@anchor{3228}
@deffn {メソッド} enqueue_sentinel ()

リスナーに停止するように指示するためキューに番兵を書き込みます。この実装は @code{put_nowait()} を使用します。タイムアウトを有効にしたい場合や、カスタムのキュー実装を使いたい場合は、このメソッドをオーバーライドすると良いでしょう。


Added in version 3.3.

@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item @ref{8b,,logging} モジュール

logging モジュールの API リファレンス。

@item @ref{8c,,logging.config} モジュール

logging モジュールの環境設定 API です。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node platform --- 実行中プラットフォームの固有情報を参照する,errno --- 標準の errno システムシンボル,logging handlers --- ログ記録ハンドラー,汎用オペレーティングシステムサービス
@anchor{library/platform doc}@anchor{3229}@anchor{library/platform module-platform}@anchor{af}@anchor{library/platform platform-access-to-underlying-platform-s-identifying-data}@anchor{322a}@anchor{library/platform translation-repo}@anchor{322b}
@subsection @code{platform} ---  実行中プラットフォームの固有情報を参照する


@geindex module; platform

`ソースコード:' Lib/platform.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/platform.py}


__________________________________________________________________


@cartouche
@quotation 注釈 
プラットフォーム毎にアルファベット順に並べています。Linuxについては Unixセクションを参照してください。
@end quotation
@end cartouche

@menu
* Cross platform:: 
* Java platform:: 
* Windows platform:: 
* macOS platform:: 
* iOS platform:: 
* Unix platforms:: 
* Linux platforms:: 
* Android platform:: 
* コマンドラインでの使用: コマンドラインでの使用<3>. 

@end menu

@node Cross platform,Java platform,,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform cross-platform}@anchor{322c}
@subsubsection Cross platform


@geindex architecture() (platform モジュール)
@anchor{library/platform platform architecture}@anchor{1a06}
@deffn {の関数} platform.architecture (executable=sys.executable, bits='@w{'}, linkage='@w{'})

`executable' で指定した実行可能ファイル（省略時はPythonインタープリタのバイナリ）の各種アーキテクチャ情報を調べます。

戻り値はタプル @code{(bits, linkage)} で、アーキテクチャのビット数と実行可能ファイルのリンク形式を示します。どちらの値も文字列で返ります。

値を決定できない場合はパラメータプリセットから与えられる値を返します。bits に @code{'@w{'}} を与えた場合、サポートされているポインタサイズを知るために @code{sizeof(pointer)} (Python バージョン < 1.5.2 では @code{sizeof(long)}) が使用されます。

この関数は、システムの @code{file} コマンドを使用します。 @code{file} はほとんどのUnixプラットフォームと一部の非Unixプラットフォームで利用可能ですが、 @code{file} コマンドが利用できず、かつ `executable' が Pythonインタープリタでない場合には適切なデフォルト値が返ります。

@cartouche
@quotation 注釈 
macOS (とひょっとすると他のプラットフォーム) では、実行可能ファイルは複数のアーキテクチャを含んだユニバーサル形式かもしれません。

現在のインタープリターが "64-bit" であるかどうかを調べるには、 @ref{13dd,,sys.maxsize} の方が信頼できます:

@example
is_64bits = sys.maxsize > 2**32
@end example
@end quotation
@end cartouche
@end deffn

@geindex machine() (platform モジュール)
@anchor{library/platform platform machine}@anchor{322d}
@deffn {の関数} platform.machine ()

@code{'AMD64'} のような、機種を返します。不明な場合は空文字列を返します。

The output is platform-dependent and may differ in casing and naming conventions.
@end deffn

@geindex node() (platform モジュール)
@anchor{library/platform platform node}@anchor{322e}
@deffn {の関数} platform.node ()

コンピュータのネットワーク名を返します。ネットワーク名は完全修飾名とは限りません。不明な場合は空文字列を返します。
@end deffn

@geindex platform() (platform モジュール)
@anchor{library/platform platform platform}@anchor{1ac6}
@deffn {の関数} platform.platform (aliased=False, terse=False)

実行中プラットフォームを識別する文字列を返します。この文字列には、有益な情報をできるだけ多く付加しています。

戻り値は機械で処理しやすい形式ではなく、`人間にとって読みやすい' 形式となっています。異なったプラットフォームでは異なった戻り値となるようになっています。

`aliased' が真なら、システムの名称として一般的な名称ではなく、別名を使用して結果を返します。たとえば、SunOS は Solaris となります。この機能は @ref{322f,,system_alias()} で実装されています。

`terse' が真なら、プラットフォームを特定するために最低限必要な情報だけを返します。


バージョン 3.8 で変更: macOSでは、 @ref{1e15,,mac_ver()} が空でないリリース文字列を返すとき、darwin のバージョンではなく macOS のバージョンを取得するために、この関数は @ref{1e15,,mac_ver()} を使うようになりました。

@end deffn

@geindex processor() (platform モジュール)
@anchor{library/platform platform processor}@anchor{3230}
@deffn {の関数} platform.processor ()

@code{'amdk6'} のような、（現実の）プロセッサ名を返します。

不明な場合は空文字列を返します。NetBSDのようにこの情報を提供しない、または @ref{322d,,machine()} と同じ値しか返さないプラットフォームも多く存在しますので、注意してください。
@end deffn

@geindex python_build() (platform モジュール)
@anchor{library/platform platform python_build}@anchor{3231}
@deffn {の関数} platform.python_build ()

Pythonのビルド番号と日付を、@code{(buildno, builddate)} のタプルで返します。
@end deffn

@geindex python_compiler() (platform モジュール)
@anchor{library/platform platform python_compiler}@anchor{3232}
@deffn {の関数} platform.python_compiler ()

Pythonをコンパイルする際に使用したコンパイラを示す文字列を返します。
@end deffn

@geindex python_branch() (platform モジュール)
@anchor{library/platform platform python_branch}@anchor{3233}
@deffn {の関数} platform.python_branch ()

Python実装のバージョン管理システム上のブランチを特定する文字列を返します。
@end deffn

@geindex python_implementation() (platform モジュール)
@anchor{library/platform platform python_implementation}@anchor{3234}
@deffn {の関数} platform.python_implementation ()

Python実装を指定する文字列を返します。戻り値は: 'CPython', 'IronPython', 'Jython', 'PyPy' のいずれかです。
@end deffn

@geindex python_revision() (platform モジュール)
@anchor{library/platform platform python_revision}@anchor{3235}
@deffn {の関数} platform.python_revision ()

Python実装のバージョン管理システム上のリビジョンを特定する文字列を返します。
@end deffn

@geindex python_version() (platform モジュール)
@anchor{library/platform platform python_version}@anchor{3236}
@deffn {の関数} platform.python_version ()

Python のバージョンを、@code{'major.minor.patchlevel'} 形式の文字列で返します。

@code{sys.version} と異なり、patchlevel（デフォルトでは0)も必ず含まれています。
@end deffn

@geindex python_version_tuple() (platform モジュール)
@anchor{library/platform platform python_version_tuple}@anchor{3237}
@deffn {の関数} platform.python_version_tuple ()

Pythonのバージョンを、文字列のタプル @code{(major, minor, patchlevel)} で返します。

@code{sys.version} と異なり、patchlevel（デフォルトでは @code{'0'})も必ず含まれています。
@end deffn

@geindex release() (platform モジュール)
@anchor{library/platform platform release}@anchor{3238}
@deffn {の関数} platform.release ()

@code{'2.2.0'} や @code{'NT'} のような、システムのリリース情報を返します。不明な場合は空文字列を返します。
@end deffn

@geindex system() (platform モジュール)
@anchor{library/platform platform system}@anchor{2267}
@deffn {の関数} platform.system ()

@code{'Linux'} 、 @code{'Darwin'} 、 @code{'Java'} 、 @code{'Windows'} のような、システム/OS 名を返します。不明な場合は空文字列を返します。

On iOS and Android, this returns the user-facing OS name (i.e, @code{'iOS},
@code{'iPadOS'} or @code{'Android'}). To obtain the kernel name (@code{'Darwin'} or
@code{'Linux'}), use @ref{132e,,os.uname()}.
@end deffn

@geindex system_alias() (platform モジュール)
@anchor{library/platform platform system_alias}@anchor{322f}
@deffn {の関数} platform.system_alias (system, release, version)

マーケティング目的で使われる一般的な別名に変換して @code{(system, release, version)} を返します。混乱を避けるために、情報を並べなおす場合があります。
@end deffn

@geindex version() (platform モジュール)
@anchor{library/platform platform version}@anchor{3239}
@deffn {の関数} platform.version ()

@code{'#3 on degas'} のような、システムのリリース情報を返します。不明な場合は空文字列を返します。

On iOS and Android, this is the user-facing OS version. To obtain the
Darwin or Linux kernel version, use @ref{132e,,os.uname()}.
@end deffn

@geindex uname() (platform モジュール)
@anchor{library/platform platform uname}@anchor{1e13}
@deffn {の関数} platform.uname ()

極めて可搬性の高い uname インターフェースです。 @ref{2267,,system}, @ref{322e,,node}, @ref{3238,,release}, @ref{3239,,version}, @ref{322d,,machine}, @ref{3230,,processor} の6つの属性を持った @ref{4e0,,namedtuple()} を返します。

@ref{3230,,processor} is resolved late, on demand.

Note: the first two attribute names differ from the names presented by
@ref{132e,,os.uname()}, where they are named @code{sysname} and
@code{nodename}.

不明な項目は @code{'@w{'}} となります。


バージョン 3.3 で変更: 結果が タプル から @ref{4e0,,namedtuple()} へ変更されました。



バージョン 3.9 で変更: @ref{3230,,processor} is resolved late instead of immediately.

@end deffn

@geindex invalidate_caches() (platform モジュール)
@anchor{library/platform platform invalidate_caches}@anchor{27d}
@deffn {の関数} platform.invalidate_caches ()

Clear out the internal cache of information, such as the @ref{1e13,,uname()}.
This is typically useful when the platform's @ref{322e,,node()} is changed
by an external process and one needs to retrieve the updated value.


Added in version 3.14.

@end deffn

@node Java platform,Windows platform,Cross platform,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform java-platform}@anchor{323a}
@subsubsection Java platform


@geindex java_ver() (platform モジュール)
@anchor{library/platform platform java_ver}@anchor{32c}
@deffn {の関数} platform.java_ver (release='@w{'}, vendor='@w{'}, vminfo=('@w{'}, '@w{'}, '@w{'}), osinfo=('@w{'}, '@w{'}, '@w{'}))

Jython用のバージョンインターフェースです。

タプル @code{(release, vendor, vminfo, osinfo)} を返します。`vminfo' はタプル @code{(vm_name, vm_release, vm_vendor)}、`osinfo' はタプル @code{(os_name, os_version, os_arch)} です。不明な項目は引数で指定した値(デフォルトは @code{'@w{'}}) となります。


Deprecated since version 3.13, will be removed in version 3.15: It was largely untested, had a confusing API,
and was only useful for Jython support.

@end deffn

@node Windows platform,macOS platform,Java platform,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform windows-platform}@anchor{323b}
@subsubsection Windows platform


@geindex win32_ver() (platform モジュール)
@anchor{library/platform platform win32_ver}@anchor{1d4a}
@deffn {の関数} platform.win32_ver (release='@w{'}, version='@w{'}, csd='@w{'}, ptype='@w{'})

Get additional version information from the Windows Registry and return a tuple
@code{(release, version, csd, ptype)} referring to OS release, version number,
CSD level (service pack) and OS type (multi/single processor). Values which
cannot be determined are set to the defaults given as parameters (which all
default to an empty string).

As a hint: `ptype' is @code{'Uniprocessor Free'} on single processor NT machines
and @code{'Multiprocessor Free'} on multi processor machines. The @code{'Free'} refers
to the OS version being free of debugging code. It could also state @code{'Checked'}
which means the OS version uses debugging code, i.e. code that checks arguments,
ranges, etc.
@end deffn

@geindex win32_edition() (platform モジュール)
@anchor{library/platform platform win32_edition}@anchor{323c}
@deffn {の関数} platform.win32_edition ()

Returns a string representing the current Windows edition, or @code{None} if the
value cannot be determined.  Possible values include but are not limited to
@code{'Enterprise'}, @code{'IoTUAP'}, @code{'ServerStandard'}, and @code{'nanoserver'}.


Added in version 3.8.

@end deffn

@geindex win32_is_iot() (platform モジュール)
@anchor{library/platform platform win32_is_iot}@anchor{323d}
@deffn {の関数} platform.win32_is_iot ()

@ref{323c,,win32_edition()} によって返された Windows のエディションが IoT エディションの時 @code{True} を返します。


Added in version 3.8.

@end deffn

@node macOS platform,iOS platform,Windows platform,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform macos-platform}@anchor{323e}
@subsubsection macOS platform


@geindex mac_ver() (platform モジュール)
@anchor{library/platform platform mac_ver}@anchor{1e15}
@deffn {の関数} platform.mac_ver (release='@w{'}, versioninfo=('@w{'}, '@w{'}, '@w{'}), machine='@w{'})

macOS のバージョン情報を、タプル @code{(release, versioninfo, machine)} で返します。`versioninfo' は、タプル @code{(version, dev_stage, non_release_version)} です。

不明な項目は @code{'@w{'}} となります。タプルの要素は全て文字列です。
@end deffn

@node iOS platform,Unix platforms,macOS platform,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform ios-platform}@anchor{323f}
@subsubsection iOS platform


@geindex ios_ver() (platform モジュール)
@anchor{library/platform platform ios_ver}@anchor{2266}
@deffn {の関数} platform.ios_ver (system='@w{'}, release='@w{'}, model='@w{'}, is_simulator=False)

iOS のバージョン情報を取得し、次の属性付きで @ref{4e0,,namedtuple()} として返します。


@itemize *

@item 
@code{system} は OS 名です。 @code{'iOS'} または @code{'iPadOS'} となります。

@item 
@code{release} は、 iOS のバージョン番号の文字列です。 (@code{'17.2'} など)

@item 
@code{model} はデバイスモデルの識別子です。これは物理デバイスでは @code{'iPhone13,2'} 、シミュレーターでは @code{'iPhone'} のような文字列になります。

@item 
@code{is_simulator} は、アプリがシミュレーター上で実行されているのか、物理デバイス上で実行されているのかを示す真偽値です。
@end itemize

決定不能な項目は、引数として指定されたデフォルトに設定されます。
@end deffn

@node Unix platforms,Linux platforms,iOS platform,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform unix-platforms}@anchor{3240}
@subsubsection Unix platforms


@geindex libc_ver() (platform モジュール)
@anchor{library/platform platform libc_ver}@anchor{17f5}
@deffn {の関数} platform.libc_ver (executable=sys.executable, lib='@w{'}, version='@w{'}, chunksize=16384)

executableで指定したファイル（省略時はPythonインタープリタ）がリンクしているlibcバージョンの取得を試みます。戻り値は文字列のタプル @code{(lib, version)} で、不明な項目は引数で指定した値となります。

この関数は、実行形式に追加されるシンボルの細かな違いによって、libcのバージョンを特定します。この違いは @code{gcc} でコンパイルされた実行可能ファイルでのみ有効だと思われます。

`chunksize' にはファイルから情報を取得するために読み込むバイト数を指定します。
@end deffn

@node Linux platforms,Android platform,Unix platforms,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform linux-platforms}@anchor{3241}
@subsubsection Linux platforms


@geindex freedesktop_os_release() (platform モジュール)
@anchor{library/platform platform freedesktop_os_release}@anchor{a27}
@deffn {の関数} platform.freedesktop_os_release ()

Get operating system identification from @code{os-release} file and return
it as a dict. The @code{os-release} file is a freedesktop.org standard@footnote{https://www.freedesktop.org/software/systemd/man/os-release.html} and
is available in most Linux distributions. A noticeable exception is
Android and Android-based distributions.

Raises @ref{2c0,,OSError} or subclass when neither @code{/etc/os-release} nor
@code{/usr/lib/os-release} can be read.

On success, the function returns a dictionary where keys and values are
strings. Values have their special characters like @code{"} and @code{$}
unquoted. The fields @code{NAME}, @code{ID}, and @code{PRETTY_NAME} are always
defined according to the standard. All other fields are optional. Vendors
may include additional fields.

Note that fields like @code{NAME}, @code{VERSION}, and @code{VARIANT} are strings
suitable for presentation to users. Programs should use fields like
@code{ID}, @code{ID_LIKE}, @code{VERSION_ID}, or @code{VARIANT_ID} to identify
Linux distributions.

以下はプログラム例です:

@example
def get_like_distro():
    info = platform.freedesktop_os_release()
    ids = [info["ID"]]
    if "ID_LIKE" in info:
        # ids are space separated and ordered by precedence
        ids.extend(info["ID_LIKE"].split())
    return ids
@end example


Added in version 3.10.

@end deffn

@node Android platform,コマンドラインでの使用<3>,Linux platforms,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform android-platform}@anchor{3242}
@subsubsection Android platform


@geindex android_ver() (platform モジュール)
@anchor{library/platform platform android_ver}@anchor{19c6}
@deffn {の関数} platform.android_ver (release='@w{'}, api_level=0, manufacturer='@w{'}, model='@w{'}, device='@w{'}, is_emulator=False)

Android のデバイス情報を取得し、次の属性付きで @ref{4e0,,namedtuple()} として返します。決定不能な値は、引数として指定されたデフォルトに設定されます。


@itemize *

@item 
@code{release} - Android バージョンの文字列 (@code{"14"} など) 。

@item 
@code{api_level} - API level of the running device, as an integer (e.g. @code{34}
for Android 14). To get the API level which Python was built against, see
@ref{d83,,sys.getandroidapilevel()}.

@item 
@code{manufacturer} - Manufacturer name@footnote{https://developer.android.com/reference/android/os/Build#MANUFACTURER}.

@item 
@code{model} - Model name@footnote{https://developer.android.com/reference/android/os/Build#MODEL} –
typically the marketing name or model number.

@item 
@code{device} - Device name@footnote{https://developer.android.com/reference/android/os/Build#DEVICE} –
typically the model number or a codename.

@item 
@code{is_emulator} - @code{True} if the device is an emulator; @code{False} if it's
a physical device.
@end itemize

Google maintains a list of known model and device names@footnote{https://storage.googleapis.com/play_public/supported_devices.html}.


Added in version 3.13.

@end deffn

@node コマンドラインでの使用<3>,,Android platform,platform --- 実行中プラットフォームの固有情報を参照する
@anchor{library/platform command-line-usage}@anchor{3243}@anchor{library/platform platform-cli}@anchor{3244}
@subsubsection コマンドラインでの使用


@code{platform} can also be invoked directly using the @ref{23c,,-m}
switch of the interpreter:

@example
python -m platform [--terse] [--nonaliased] [@{nonaliased,terse@} ...]
@end example

以下のオプションが使用できます:

@geindex platform コマンドラインオプション; --terse
@anchor{library/platform cmdoption-platform-terse}@anchor{3245}
@deffn {Option} @w{-}@w{-}terse

Print terse information about the platform. This is equivalent to
calling @ref{1ac6,,platform.platform()} with the `terse' argument set to @code{True}.
@end deffn

@geindex platform コマンドラインオプション; --nonaliased
@anchor{library/platform cmdoption-platform-nonaliased}@anchor{3246}
@deffn {Option} @w{-}@w{-}nonaliased

Print platform information without system/OS name aliasing. This is
equivalent to calling @ref{1ac6,,platform.platform()} with the `aliased' argument
set to @code{True}.
@end deffn

You can also pass one or more positional arguments (@code{terse}, @code{nonaliased})
to explicitly control the output format. These behave similarly to their
corresponding options.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node errno --- 標準の errno システムシンボル,ctypes --- Python 用の外部関数ライブラリ,platform --- 実行中プラットフォームの固有情報を参照する,汎用オペレーティングシステムサービス
@anchor{library/errno doc}@anchor{3247}@anchor{library/errno errno-standard-errno-system-symbols}@anchor{3248}@anchor{library/errno module-errno}@anchor{5b}@anchor{library/errno translation-repo}@anchor{3249}
@subsection @code{errno} --- 標準の errno システムシンボル


@geindex module; errno


__________________________________________________________________


このモジュールから標準の @code{errno} システムシンボルを取得することができます。個々のシンボルの値は @code{errno} に対応する整数値です。これらのシンボルの名前は、 @code{linux/include/errno.h} から借用されており、網羅的なはずです。

@geindex errorcode (errno モジュール)
@anchor{library/errno errno errorcode}@anchor{324a}
@deffn {データ} errno.errorcode

errno 値を背後のシステムにおける文字列表現に対応付ける辞書です。例えば、@code{errno.errorcode[errno.EPERM]} は @code{'EPERM'} に対応付けられます。
@end deffn

数値のエラーコードをエラーメッセージに変換するには、 @ref{3024,,os.strerror()} を使ってください。

以下のリストの内、現在のプラットフォームで使われていないシンボルはモジュール上で定義されていません。定義されているシンボルだけを挙げたリストは @code{errno.errorcode.keys()} として取得することができます。取得できるシンボルには以下のようなものがあります:

@geindex EPERM (errno モジュール)
@anchor{library/errno errno EPERM}@anchor{1b56}
@deffn {データ} errno.EPERM

Operation not permitted. This error is mapped to the exception
@ref{f3e,,PermissionError}.
@end deffn

@geindex ENOENT (errno モジュール)
@anchor{library/errno errno ENOENT}@anchor{2709}
@deffn {データ} errno.ENOENT

No such file or directory. This error is mapped to the exception
@ref{264,,FileNotFoundError}.
@end deffn

@geindex ESRCH (errno モジュール)
@anchor{library/errno errno ESRCH}@anchor{270d}
@deffn {データ} errno.ESRCH

No such process. This error is mapped to the exception
@ref{1266,,ProcessLookupError}.
@end deffn

@geindex EINTR (errno モジュール)
@anchor{library/errno errno EINTR}@anchor{f87}
@deffn {データ} errno.EINTR

Interrupted system call. This error is mapped to the exception
@ref{f88,,InterruptedError}.
@end deffn

@geindex EIO (errno モジュール)
@anchor{library/errno errno EIO}@anchor{324b}
@deffn {データ} errno.EIO

I/O エラーです (I/O error)
@end deffn

@geindex ENXIO (errno モジュール)
@anchor{library/errno errno ENXIO}@anchor{324c}
@deffn {データ} errno.ENXIO

そのようなデバイスまたはアドレスは存在しません (No such device or address)
@end deffn

@geindex E2BIG (errno モジュール)
@anchor{library/errno errno E2BIG}@anchor{324d}
@deffn {データ} errno.E2BIG

引数リストが長すぎます (Arg list too long)
@end deffn

@geindex ENOEXEC (errno モジュール)
@anchor{library/errno errno ENOEXEC}@anchor{324e}
@deffn {データ} errno.ENOEXEC

実行形式にエラーがあります (Exec format error)
@end deffn

@geindex EBADF (errno モジュール)
@anchor{library/errno errno EBADF}@anchor{b54}
@deffn {データ} errno.EBADF

ファイル番号が間違っています (Bad file number)
@end deffn

@geindex ECHILD (errno モジュール)
@anchor{library/errno errno ECHILD}@anchor{2702}
@deffn {データ} errno.ECHILD

No child processes. This error is mapped to the exception
@ref{1263,,ChildProcessError}.
@end deffn

@geindex EAGAIN (errno モジュール)
@anchor{library/errno errno EAGAIN}@anchor{26fd}
@deffn {データ} errno.EAGAIN

Try again. This error is mapped to the exception @ref{235,,BlockingIOError}.
@end deffn

@geindex ENOMEM (errno モジュール)
@anchor{library/errno errno ENOMEM}@anchor{324f}
@deffn {データ} errno.ENOMEM

空きメモリがありません (Out of memory)
@end deffn

@geindex EACCES (errno モジュール)
@anchor{library/errno errno EACCES}@anchor{270c}
@deffn {データ} errno.EACCES

Permission denied.  This error is mapped to the exception
@ref{f3e,,PermissionError}.
@end deffn

@geindex EFAULT (errno モジュール)
@anchor{library/errno errno EFAULT}@anchor{3250}
@deffn {データ} errno.EFAULT

不正なアドレスです (Bad address)
@end deffn

@geindex ENOTBLK (errno モジュール)
@anchor{library/errno errno ENOTBLK}@anchor{3251}
@deffn {データ} errno.ENOTBLK

ブロックデバイスが必要です (Block device required)
@end deffn

@geindex EBUSY (errno モジュール)
@anchor{library/errno errno EBUSY}@anchor{3252}
@deffn {データ} errno.EBUSY

そのデバイスまたはリソースは使用中です (Device or resource busy)
@end deffn

@geindex EEXIST (errno モジュール)
@anchor{library/errno errno EEXIST}@anchor{2708}
@deffn {データ} errno.EEXIST

File exists. This error is mapped to the exception
@ref{1221,,FileExistsError}.
@end deffn

@geindex EXDEV (errno モジュール)
@anchor{library/errno errno EXDEV}@anchor{303a}
@deffn {データ} errno.EXDEV

デバイスをまたいだリンクです (Cross-device link)
@end deffn

@geindex ENODEV (errno モジュール)
@anchor{library/errno errno ENODEV}@anchor{3253}
@deffn {データ} errno.ENODEV

そのようなデバイスはありません (No such device)
@end deffn

@geindex ENOTDIR (errno モジュール)
@anchor{library/errno errno ENOTDIR}@anchor{270b}
@deffn {データ} errno.ENOTDIR

Not a directory. This error is mapped to the exception
@ref{1265,,NotADirectoryError}.
@end deffn

@geindex EISDIR (errno モジュール)
@anchor{library/errno errno EISDIR}@anchor{270a}
@deffn {データ} errno.EISDIR

Is a directory. This error is mapped to the exception
@ref{1264,,IsADirectoryError}.
@end deffn

@geindex EINVAL (errno モジュール)
@anchor{library/errno errno EINVAL}@anchor{1dd2}
@deffn {データ} errno.EINVAL

無効な引数です (Invalid argument)
@end deffn

@geindex ENFILE (errno モジュール)
@anchor{library/errno errno ENFILE}@anchor{3254}
@deffn {データ} errno.ENFILE

ファイルテーブルがオーバフローしています (File table overflow)
@end deffn

@geindex EMFILE (errno モジュール)
@anchor{library/errno errno EMFILE}@anchor{3255}
@deffn {データ} errno.EMFILE

開かれたファイルが多すぎます (Too many open files)
@end deffn

@geindex ENOTTY (errno モジュール)
@anchor{library/errno errno ENOTTY}@anchor{3256}
@deffn {データ} errno.ENOTTY

タイプライタではありません (Not a typewriter)
@end deffn

@geindex ETXTBSY (errno モジュール)
@anchor{library/errno errno ETXTBSY}@anchor{3257}
@deffn {データ} errno.ETXTBSY

テキストファイルが使用中です (Text file busy)
@end deffn

@geindex EFBIG (errno モジュール)
@anchor{library/errno errno EFBIG}@anchor{3258}
@deffn {データ} errno.EFBIG

ファイルが大きすぎます (File too large)
@end deffn

@geindex ENOSPC (errno モジュール)
@anchor{library/errno errno ENOSPC}@anchor{3259}
@deffn {データ} errno.ENOSPC

デバイス上に空きがありません (No space left on device)
@end deffn

@geindex ESPIPE (errno モジュール)
@anchor{library/errno errno ESPIPE}@anchor{325a}
@deffn {データ} errno.ESPIPE

不正なシークです (Illegal seek)
@end deffn

@geindex EROFS (errno モジュール)
@anchor{library/errno errno EROFS}@anchor{325b}
@deffn {データ} errno.EROFS

リードオンリーのファイルシステムです (Read-only file system)
@end deffn

@geindex EMLINK (errno モジュール)
@anchor{library/errno errno EMLINK}@anchor{325c}
@deffn {データ} errno.EMLINK

リンクが多すぎます (Too many links)
@end deffn

@geindex EPIPE (errno モジュール)
@anchor{library/errno errno EPIPE}@anchor{2703}
@deffn {データ} errno.EPIPE

Broken pipe. This error is mapped to the exception
@ref{1267,,BrokenPipeError}.
@end deffn

@geindex EDOM (errno モジュール)
@anchor{library/errno errno EDOM}@anchor{325d}
@deffn {データ} errno.EDOM

数学引数が関数の定義域を越えています (Math argument out of domain of func)
@end deffn

@geindex ERANGE (errno モジュール)
@anchor{library/errno errno ERANGE}@anchor{325e}
@deffn {データ} errno.ERANGE

表現できない数学演算結果になりました (Math result not representable)
@end deffn

@geindex EDEADLK (errno モジュール)
@anchor{library/errno errno EDEADLK}@anchor{325f}
@deffn {データ} errno.EDEADLK

リソースのデッドロックが起きます (Resource deadlock would occur)
@end deffn

@geindex ENAMETOOLONG (errno モジュール)
@anchor{library/errno errno ENAMETOOLONG}@anchor{3260}
@deffn {データ} errno.ENAMETOOLONG

ファイル名が長すぎます (File name too long)
@end deffn

@geindex ENOLCK (errno モジュール)
@anchor{library/errno errno ENOLCK}@anchor{3261}
@deffn {データ} errno.ENOLCK

レコードロッキングが利用できません (No record locks available)
@end deffn

@geindex ENOSYS (errno モジュール)
@anchor{library/errno errno ENOSYS}@anchor{1b57}
@deffn {データ} errno.ENOSYS

実装されていない機能です (Function not implemented)
@end deffn

@geindex ENOTEMPTY (errno モジュール)
@anchor{library/errno errno ENOTEMPTY}@anchor{3262}
@deffn {データ} errno.ENOTEMPTY

ディレクトリが空ではありません (Directory not empty)
@end deffn

@geindex ELOOP (errno モジュール)
@anchor{library/errno errno ELOOP}@anchor{3263}
@deffn {データ} errno.ELOOP

これ以上シンボリックリンクを追跡できません (Too many symbolic links encountered)
@end deffn

@geindex EWOULDBLOCK (errno モジュール)
@anchor{library/errno errno EWOULDBLOCK}@anchor{26ff}
@deffn {データ} errno.EWOULDBLOCK

Operation would block. This error is mapped to the exception
@ref{235,,BlockingIOError}.
@end deffn

@geindex ENOMSG (errno モジュール)
@anchor{library/errno errno ENOMSG}@anchor{3264}
@deffn {データ} errno.ENOMSG

指定された型のメッセージはありません (No message of desired type)
@end deffn

@geindex EIDRM (errno モジュール)
@anchor{library/errno errno EIDRM}@anchor{3265}
@deffn {データ} errno.EIDRM

識別子が除去されました (Identifier removed)
@end deffn

@geindex ECHRNG (errno モジュール)
@anchor{library/errno errno ECHRNG}@anchor{3266}
@deffn {データ} errno.ECHRNG

チャネル番号が範囲を超えました (Channel number out of range)
@end deffn

@geindex EL2NSYNC (errno モジュール)
@anchor{library/errno errno EL2NSYNC}@anchor{3267}
@deffn {データ} errno.EL2NSYNC

レベル 2 で同期がとれていません (Level 2 not synchronized)
@end deffn

@geindex EL3HLT (errno モジュール)
@anchor{library/errno errno EL3HLT}@anchor{3268}
@deffn {データ} errno.EL3HLT

レベル 3 で終了しました (Level 3 halted)
@end deffn

@geindex EL3RST (errno モジュール)
@anchor{library/errno errno EL3RST}@anchor{3269}
@deffn {データ} errno.EL3RST

レベル 3 でリセットしました (Level 3 reset)
@end deffn

@geindex ELNRNG (errno モジュール)
@anchor{library/errno errno ELNRNG}@anchor{326a}
@deffn {データ} errno.ELNRNG

リンク番号が範囲を超えています (Link number out of range)
@end deffn

@geindex EUNATCH (errno モジュール)
@anchor{library/errno errno EUNATCH}@anchor{326b}
@deffn {データ} errno.EUNATCH

プロトコルドライバが接続されていません (Protocol driver not attached)
@end deffn

@geindex ENOCSI (errno モジュール)
@anchor{library/errno errno ENOCSI}@anchor{326c}
@deffn {データ} errno.ENOCSI

CSI 構造体がありません (No CSI structure available)
@end deffn

@geindex EL2HLT (errno モジュール)
@anchor{library/errno errno EL2HLT}@anchor{326d}
@deffn {データ} errno.EL2HLT

レベル 2 で終了しました (Level 2 halted)
@end deffn

@geindex EBADE (errno モジュール)
@anchor{library/errno errno EBADE}@anchor{326e}
@deffn {データ} errno.EBADE

無効な変換です (Invalid exchange)
@end deffn

@geindex EBADR (errno モジュール)
@anchor{library/errno errno EBADR}@anchor{326f}
@deffn {データ} errno.EBADR

無効な要求記述子です (Invalid request descriptor)
@end deffn

@geindex EXFULL (errno モジュール)
@anchor{library/errno errno EXFULL}@anchor{3270}
@deffn {データ} errno.EXFULL

変換テーブルが一杯です (Exchange full)
@end deffn

@geindex ENOANO (errno モジュール)
@anchor{library/errno errno ENOANO}@anchor{3271}
@deffn {データ} errno.ENOANO

陰極がありません (No anode)
@end deffn

@geindex EBADRQC (errno モジュール)
@anchor{library/errno errno EBADRQC}@anchor{3272}
@deffn {データ} errno.EBADRQC

無効なリクエストコードです (Invalid request code)
@end deffn

@geindex EBADSLT (errno モジュール)
@anchor{library/errno errno EBADSLT}@anchor{3273}
@deffn {データ} errno.EBADSLT

無効なスロットです (Invalid slot)
@end deffn

@geindex EDEADLOCK (errno モジュール)
@anchor{library/errno errno EDEADLOCK}@anchor{3274}
@deffn {データ} errno.EDEADLOCK

ファイルロックにおけるデッドロックエラーです (File locking deadlock error)
@end deffn

@geindex EBFONT (errno モジュール)
@anchor{library/errno errno EBFONT}@anchor{3275}
@deffn {データ} errno.EBFONT

フォントファイル形式が間違っています (Bad font file format)
@end deffn

@geindex ENOSTR (errno モジュール)
@anchor{library/errno errno ENOSTR}@anchor{3276}
@deffn {データ} errno.ENOSTR

ストリーム型でないデバイスです (Device not a stream)
@end deffn

@geindex ENODATA (errno モジュール)
@anchor{library/errno errno ENODATA}@anchor{3277}
@deffn {データ} errno.ENODATA

利用可能なデータがありません (No data available)
@end deffn

@geindex ETIME (errno モジュール)
@anchor{library/errno errno ETIME}@anchor{3278}
@deffn {データ} errno.ETIME

時間切れです (Timer expired)
@end deffn

@geindex ENOSR (errno モジュール)
@anchor{library/errno errno ENOSR}@anchor{3279}
@deffn {データ} errno.ENOSR

ストリームリソースを使い切りました (Out of streams resources)
@end deffn

@geindex ENONET (errno モジュール)
@anchor{library/errno errno ENONET}@anchor{327a}
@deffn {データ} errno.ENONET

計算機はネットワーク上にありません (Machine is not on the network)
@end deffn

@geindex ENOPKG (errno モジュール)
@anchor{library/errno errno ENOPKG}@anchor{327b}
@deffn {データ} errno.ENOPKG

パッケージがインストールされていません (Package not installed)
@end deffn

@geindex EREMOTE (errno モジュール)
@anchor{library/errno errno EREMOTE}@anchor{327c}
@deffn {データ} errno.EREMOTE

対象物は遠隔にあります (Object is remote)
@end deffn

@geindex ENOLINK (errno モジュール)
@anchor{library/errno errno ENOLINK}@anchor{327d}
@deffn {データ} errno.ENOLINK

リンクが切られました (Link has been severed)
@end deffn

@geindex EADV (errno モジュール)
@anchor{library/errno errno EADV}@anchor{327e}
@deffn {データ} errno.EADV

Advertise エラーです (Advertise error)
@end deffn

@geindex ESRMNT (errno モジュール)
@anchor{library/errno errno ESRMNT}@anchor{327f}
@deffn {データ} errno.ESRMNT

Srmount エラーです (Srmount error)
@end deffn

@geindex ECOMM (errno モジュール)
@anchor{library/errno errno ECOMM}@anchor{3280}
@deffn {データ} errno.ECOMM

送信時の通信エラーです (Communication error on send)
@end deffn

@geindex EPROTO (errno モジュール)
@anchor{library/errno errno EPROTO}@anchor{3281}
@deffn {データ} errno.EPROTO

プロトコルエラーです (Protocol error)
@end deffn

@geindex EMULTIHOP (errno モジュール)
@anchor{library/errno errno EMULTIHOP}@anchor{3282}
@deffn {データ} errno.EMULTIHOP

多重ホップを試みました (Multihop attempted)
@end deffn

@geindex EDOTDOT (errno モジュール)
@anchor{library/errno errno EDOTDOT}@anchor{3283}
@deffn {データ} errno.EDOTDOT

RFS 特有のエラーです (RFS specific error)
@end deffn

@geindex EBADMSG (errno モジュール)
@anchor{library/errno errno EBADMSG}@anchor{3284}
@deffn {データ} errno.EBADMSG

データメッセージではありません (Not a data message)
@end deffn

@geindex EOVERFLOW (errno モジュール)
@anchor{library/errno errno EOVERFLOW}@anchor{3285}
@deffn {データ} errno.EOVERFLOW

定義されたデータ型にとって大きすぎる値です (Value too large for defined data type)
@end deffn

@geindex ENOTUNIQ (errno モジュール)
@anchor{library/errno errno ENOTUNIQ}@anchor{3286}
@deffn {データ} errno.ENOTUNIQ

名前がネットワーク上で一意でありません (Name not unique on network)
@end deffn

@geindex EBADFD (errno モジュール)
@anchor{library/errno errno EBADFD}@anchor{3287}
@deffn {データ} errno.EBADFD

ファイル記述子の状態が不正です (File descriptor in bad state)
@end deffn

@geindex EREMCHG (errno モジュール)
@anchor{library/errno errno EREMCHG}@anchor{3288}
@deffn {データ} errno.EREMCHG

遠隔のアドレスが変更されました (Remote address changed)
@end deffn

@geindex ELIBACC (errno モジュール)
@anchor{library/errno errno ELIBACC}@anchor{3289}
@deffn {データ} errno.ELIBACC

必要な共有ライブラリにアクセスできません (Can not access a needed shared library)
@end deffn

@geindex ELIBBAD (errno モジュール)
@anchor{library/errno errno ELIBBAD}@anchor{328a}
@deffn {データ} errno.ELIBBAD

壊れた共有ライブラリにアクセスしています (Accessing a corrupted shared library)
@end deffn

@geindex ELIBSCN (errno モジュール)
@anchor{library/errno errno ELIBSCN}@anchor{328b}
@deffn {データ} errno.ELIBSCN

a.out の .lib セクションが壊れています (.lib section in a.out corrupted)
@end deffn

@geindex ELIBMAX (errno モジュール)
@anchor{library/errno errno ELIBMAX}@anchor{328c}
@deffn {データ} errno.ELIBMAX

リンクを試みる共有ライブラリが多すぎます (Attempting to link in too many shared libraries)
@end deffn

@geindex ELIBEXEC (errno モジュール)
@anchor{library/errno errno ELIBEXEC}@anchor{328d}
@deffn {データ} errno.ELIBEXEC

共有ライブラリを直接実行することができません (Cannot exec a shared library directly)
@end deffn

@geindex EILSEQ (errno モジュール)
@anchor{library/errno errno EILSEQ}@anchor{328e}
@deffn {データ} errno.EILSEQ

不正なバイト列です (Illegal byte sequence)
@end deffn

@geindex ERESTART (errno モジュール)
@anchor{library/errno errno ERESTART}@anchor{328f}
@deffn {データ} errno.ERESTART

割り込みシステムコールを復帰しなければなりません (Interrupted system call should be restarted)
@end deffn

@geindex ESTRPIPE (errno モジュール)
@anchor{library/errno errno ESTRPIPE}@anchor{3290}
@deffn {データ} errno.ESTRPIPE

ストリームパイプのエラーです (Streams pipe error)
@end deffn

@geindex EUSERS (errno モジュール)
@anchor{library/errno errno EUSERS}@anchor{3291}
@deffn {データ} errno.EUSERS

ユーザが多すぎます (Too many users)
@end deffn

@geindex ENOTSOCK (errno モジュール)
@anchor{library/errno errno ENOTSOCK}@anchor{3292}
@deffn {データ} errno.ENOTSOCK

非ソケットに対するソケット操作です (Socket operation on non-socket)
@end deffn

@geindex EDESTADDRREQ (errno モジュール)
@anchor{library/errno errno EDESTADDRREQ}@anchor{3293}
@deffn {データ} errno.EDESTADDRREQ

目的アドレスが必要です (Destination address required)
@end deffn

@geindex EMSGSIZE (errno モジュール)
@anchor{library/errno errno EMSGSIZE}@anchor{3294}
@deffn {データ} errno.EMSGSIZE

メッセージが長すぎます (Message too long)
@end deffn

@geindex EPROTOTYPE (errno モジュール)
@anchor{library/errno errno EPROTOTYPE}@anchor{3295}
@deffn {データ} errno.EPROTOTYPE

ソケットに対して不正なプロトコル型です (Protocol wrong type for socket)
@end deffn

@geindex ENOPROTOOPT (errno モジュール)
@anchor{library/errno errno ENOPROTOOPT}@anchor{3296}
@deffn {データ} errno.ENOPROTOOPT

利用できないプロトコルです (Protocol not available)
@end deffn

@geindex EPROTONOSUPPORT (errno モジュール)
@anchor{library/errno errno EPROTONOSUPPORT}@anchor{3297}
@deffn {データ} errno.EPROTONOSUPPORT

サポートされていないプロトコルです (Protocol not supported)
@end deffn

@geindex ESOCKTNOSUPPORT (errno モジュール)
@anchor{library/errno errno ESOCKTNOSUPPORT}@anchor{3298}
@deffn {データ} errno.ESOCKTNOSUPPORT

サポートされていないソケット型です (Socket type not supported)
@end deffn

@geindex EOPNOTSUPP (errno モジュール)
@anchor{library/errno errno EOPNOTSUPP}@anchor{3299}
@deffn {データ} errno.EOPNOTSUPP

通信端点に対してサポートされていない操作です (Operation not supported on transport endpoint)
@end deffn

@geindex ENOTSUP (errno モジュール)
@anchor{library/errno errno ENOTSUP}@anchor{329a}
@deffn {データ} errno.ENOTSUP

Operation not supported


Added in version 3.2.

@end deffn

@geindex EPFNOSUPPORT (errno モジュール)
@anchor{library/errno errno EPFNOSUPPORT}@anchor{329b}
@deffn {データ} errno.EPFNOSUPPORT

サポートされていないプロトコルファミリです (Protocol family not supported)
@end deffn

@geindex EAFNOSUPPORT (errno モジュール)
@anchor{library/errno errno EAFNOSUPPORT}@anchor{329c}
@deffn {データ} errno.EAFNOSUPPORT

プロトコルでサポートされていないアドレスファミリです (Address family not supported by protocol)
@end deffn

@geindex EADDRINUSE (errno モジュール)
@anchor{library/errno errno EADDRINUSE}@anchor{329d}
@deffn {データ} errno.EADDRINUSE

アドレスは使用中です (Address already in use)
@end deffn

@geindex EADDRNOTAVAIL (errno モジュール)
@anchor{library/errno errno EADDRNOTAVAIL}@anchor{329e}
@deffn {データ} errno.EADDRNOTAVAIL

要求されたアドレスを割り当てできません (Cannot assign requested address)
@end deffn

@geindex ENETDOWN (errno モジュール)
@anchor{library/errno errno ENETDOWN}@anchor{329f}
@deffn {データ} errno.ENETDOWN

ネットワークがダウンしています (Network is down)
@end deffn

@geindex ENETUNREACH (errno モジュール)
@anchor{library/errno errno ENETUNREACH}@anchor{1de9}
@deffn {データ} errno.ENETUNREACH

ネットワークに到達できません (Network is unreachable)
@end deffn

@geindex ENETRESET (errno モジュール)
@anchor{library/errno errno ENETRESET}@anchor{32a0}
@deffn {データ} errno.ENETRESET

リセットによってネットワーク接続が切られました (Network dropped connection because of reset)
@end deffn

@geindex ECONNABORTED (errno モジュール)
@anchor{library/errno errno ECONNABORTED}@anchor{2705}
@deffn {データ} errno.ECONNABORTED

Software caused connection abort. This error is mapped to the
exception @ref{1268,,ConnectionAbortedError}.
@end deffn

@geindex ECONNRESET (errno モジュール)
@anchor{library/errno errno ECONNRESET}@anchor{2707}
@deffn {データ} errno.ECONNRESET

Connection reset by peer. This error is mapped to the exception
@ref{126a,,ConnectionResetError}.
@end deffn

@geindex ENOBUFS (errno モジュール)
@anchor{library/errno errno ENOBUFS}@anchor{1b71}
@deffn {データ} errno.ENOBUFS

バッファに空きがありません (No buffer space available)
@end deffn

@geindex EISCONN (errno モジュール)
@anchor{library/errno errno EISCONN}@anchor{32a1}
@deffn {データ} errno.EISCONN

通信端点がすでに接続されています (Transport endpoint is already connected)
@end deffn

@geindex ENOTCONN (errno モジュール)
@anchor{library/errno errno ENOTCONN}@anchor{32a2}
@deffn {データ} errno.ENOTCONN

通信端点が接続されていません (Transport endpoint is not connected)
@end deffn

@geindex ESHUTDOWN (errno モジュール)
@anchor{library/errno errno ESHUTDOWN}@anchor{2704}
@deffn {データ} errno.ESHUTDOWN

Cannot send after transport endpoint shutdown. This error is mapped
to the exception @ref{1267,,BrokenPipeError}.
@end deffn

@geindex ETOOMANYREFS (errno モジュール)
@anchor{library/errno errno ETOOMANYREFS}@anchor{32a3}
@deffn {データ} errno.ETOOMANYREFS

参照が多すぎます: 接続できません (Too many references: cannot splice)
@end deffn

@geindex ETIMEDOUT (errno モジュール)
@anchor{library/errno errno ETIMEDOUT}@anchor{270e}
@deffn {データ} errno.ETIMEDOUT

Connection timed out. This error is mapped to the exception
@ref{a36,,TimeoutError}.
@end deffn

@geindex ECONNREFUSED (errno モジュール)
@anchor{library/errno errno ECONNREFUSED}@anchor{2706}
@deffn {データ} errno.ECONNREFUSED

Connection refused. This error is mapped to the exception
@ref{1269,,ConnectionRefusedError}.
@end deffn

@geindex EHOSTDOWN (errno モジュール)
@anchor{library/errno errno EHOSTDOWN}@anchor{32a4}
@deffn {データ} errno.EHOSTDOWN

ホストはシステムダウンしています (Host is down)
@end deffn

@geindex EHOSTUNREACH (errno モジュール)
@anchor{library/errno errno EHOSTUNREACH}@anchor{32a5}
@deffn {データ} errno.EHOSTUNREACH

ホストへの経路がありません (No route to host)
@end deffn

@geindex EHWPOISON (errno モジュール)
@anchor{library/errno errno EHWPOISON}@anchor{20b}
@deffn {データ} errno.EHWPOISON

Memory page has hardware error.


Added in version 3.14.

@end deffn

@geindex EALREADY (errno モジュール)
@anchor{library/errno errno EALREADY}@anchor{26fe}
@deffn {データ} errno.EALREADY

Operation already in progress. This error is mapped to the
exception @ref{235,,BlockingIOError}.
@end deffn

@geindex EINPROGRESS (errno モジュール)
@anchor{library/errno errno EINPROGRESS}@anchor{2700}
@deffn {データ} errno.EINPROGRESS

Operation now in progress. This error is mapped to the exception
@ref{235,,BlockingIOError}.
@end deffn

@geindex ESTALE (errno モジュール)
@anchor{library/errno errno ESTALE}@anchor{32a6}
@deffn {データ} errno.ESTALE

無効な NFS ファイルハンドルです (Stale NFS file handle)
@end deffn

@geindex EUCLEAN (errno モジュール)
@anchor{library/errno errno EUCLEAN}@anchor{32a7}
@deffn {データ} errno.EUCLEAN

構造のクリーニングが必要です (Structure needs cleaning)
@end deffn

@geindex ENOTNAM (errno モジュール)
@anchor{library/errno errno ENOTNAM}@anchor{32a8}
@deffn {データ} errno.ENOTNAM

XENIX 名前付きファイルではありません (Not a XENIX named type file)
@end deffn

@geindex ENAVAIL (errno モジュール)
@anchor{library/errno errno ENAVAIL}@anchor{32a9}
@deffn {データ} errno.ENAVAIL

XENIX セマフォは利用できません (No XENIX semaphores available)
@end deffn

@geindex EISNAM (errno モジュール)
@anchor{library/errno errno EISNAM}@anchor{32aa}
@deffn {データ} errno.EISNAM

名前付きファイルです (Is a named type file)
@end deffn

@geindex EREMOTEIO (errno モジュール)
@anchor{library/errno errno EREMOTEIO}@anchor{32ab}
@deffn {データ} errno.EREMOTEIO

遠隔側の I/O エラーです (Remote I/O error)
@end deffn

@geindex EDQUOT (errno モジュール)
@anchor{library/errno errno EDQUOT}@anchor{32ac}
@deffn {データ} errno.EDQUOT

ディスククオータを超えました (Quota exceeded)
@end deffn

@geindex EQFULL (errno モジュール)
@anchor{library/errno errno EQFULL}@anchor{32ad}
@deffn {データ} errno.EQFULL

Interface output queue is full


Added in version 3.11.

@end deffn

@geindex ENOMEDIUM (errno モジュール)
@anchor{library/errno errno ENOMEDIUM}@anchor{32ae}
@deffn {データ} errno.ENOMEDIUM

No medium found
@end deffn

@geindex EMEDIUMTYPE (errno モジュール)
@anchor{library/errno errno EMEDIUMTYPE}@anchor{32af}
@deffn {データ} errno.EMEDIUMTYPE

Wrong medium type
@end deffn

@geindex ENOKEY (errno モジュール)
@anchor{library/errno errno ENOKEY}@anchor{32b0}
@deffn {データ} errno.ENOKEY

Required key not available
@end deffn

@geindex EKEYEXPIRED (errno モジュール)
@anchor{library/errno errno EKEYEXPIRED}@anchor{32b1}
@deffn {データ} errno.EKEYEXPIRED

Key has expired
@end deffn

@geindex EKEYREVOKED (errno モジュール)
@anchor{library/errno errno EKEYREVOKED}@anchor{32b2}
@deffn {データ} errno.EKEYREVOKED

Key has been revoked
@end deffn

@geindex EKEYREJECTED (errno モジュール)
@anchor{library/errno errno EKEYREJECTED}@anchor{32b3}
@deffn {データ} errno.EKEYREJECTED

Key was rejected by service
@end deffn

@geindex ERFKILL (errno モジュール)
@anchor{library/errno errno ERFKILL}@anchor{32b4}
@deffn {データ} errno.ERFKILL

Operation not possible due to RF-kill
@end deffn

@geindex ELOCKUNMAPPED (errno モジュール)
@anchor{library/errno errno ELOCKUNMAPPED}@anchor{32b5}
@deffn {データ} errno.ELOCKUNMAPPED

Locked lock was unmapped
@end deffn

@geindex ENOTACTIVE (errno モジュール)
@anchor{library/errno errno ENOTACTIVE}@anchor{32b6}
@deffn {データ} errno.ENOTACTIVE

Facility is not active
@end deffn

@geindex EAUTH (errno モジュール)
@anchor{library/errno errno EAUTH}@anchor{32b7}
@deffn {データ} errno.EAUTH

Authentication error


Added in version 3.2.

@end deffn

@geindex EBADARCH (errno モジュール)
@anchor{library/errno errno EBADARCH}@anchor{32b8}
@deffn {データ} errno.EBADARCH

Bad CPU type in executable


Added in version 3.2.

@end deffn

@geindex EBADEXEC (errno モジュール)
@anchor{library/errno errno EBADEXEC}@anchor{32b9}
@deffn {データ} errno.EBADEXEC

Bad executable (or shared library)


Added in version 3.2.

@end deffn

@geindex EBADMACHO (errno モジュール)
@anchor{library/errno errno EBADMACHO}@anchor{32ba}
@deffn {データ} errno.EBADMACHO

Malformed Mach-o file


Added in version 3.2.

@end deffn

@geindex EDEVERR (errno モジュール)
@anchor{library/errno errno EDEVERR}@anchor{32bb}
@deffn {データ} errno.EDEVERR

Device error


Added in version 3.2.

@end deffn

@geindex EFTYPE (errno モジュール)
@anchor{library/errno errno EFTYPE}@anchor{32bc}
@deffn {データ} errno.EFTYPE

Inappropriate file type or format


Added in version 3.2.

@end deffn

@geindex ENEEDAUTH (errno モジュール)
@anchor{library/errno errno ENEEDAUTH}@anchor{32bd}
@deffn {データ} errno.ENEEDAUTH

Need authenticator


Added in version 3.2.

@end deffn

@geindex ENOATTR (errno モジュール)
@anchor{library/errno errno ENOATTR}@anchor{32be}
@deffn {データ} errno.ENOATTR

Attribute not found


Added in version 3.2.

@end deffn

@geindex ENOPOLICY (errno モジュール)
@anchor{library/errno errno ENOPOLICY}@anchor{32bf}
@deffn {データ} errno.ENOPOLICY

Policy not found


Added in version 3.2.

@end deffn

@geindex EPROCLIM (errno モジュール)
@anchor{library/errno errno EPROCLIM}@anchor{32c0}
@deffn {データ} errno.EPROCLIM

Too many processes


Added in version 3.2.

@end deffn

@geindex EPROCUNAVAIL (errno モジュール)
@anchor{library/errno errno EPROCUNAVAIL}@anchor{32c1}
@deffn {データ} errno.EPROCUNAVAIL

Bad procedure for program


Added in version 3.2.

@end deffn

@geindex EPROGMISMATCH (errno モジュール)
@anchor{library/errno errno EPROGMISMATCH}@anchor{32c2}
@deffn {データ} errno.EPROGMISMATCH

Program version wrong


Added in version 3.2.

@end deffn

@geindex EPROGUNAVAIL (errno モジュール)
@anchor{library/errno errno EPROGUNAVAIL}@anchor{32c3}
@deffn {データ} errno.EPROGUNAVAIL

RPC prog. not avail


Added in version 3.2.

@end deffn

@geindex EPWROFF (errno モジュール)
@anchor{library/errno errno EPWROFF}@anchor{32c4}
@deffn {データ} errno.EPWROFF

Device power is off


Added in version 3.2.

@end deffn

@geindex EBADRPC (errno モジュール)
@anchor{library/errno errno EBADRPC}@anchor{32c5}
@deffn {データ} errno.EBADRPC

RPC struct is bad


Added in version 3.2.

@end deffn

@geindex ERPCMISMATCH (errno モジュール)
@anchor{library/errno errno ERPCMISMATCH}@anchor{32c6}
@deffn {データ} errno.ERPCMISMATCH

RPC version wrong


Added in version 3.2.

@end deffn

@geindex ESHLIBVERS (errno モジュール)
@anchor{library/errno errno ESHLIBVERS}@anchor{32c7}
@deffn {データ} errno.ESHLIBVERS

Shared library version mismatch


Added in version 3.2.

@end deffn

@geindex ENOTCAPABLE (errno モジュール)
@anchor{library/errno errno ENOTCAPABLE}@anchor{1b3f}
@deffn {データ} errno.ENOTCAPABLE

Capabilities insufficient. This error is mapped to the exception
@ref{f3e,,PermissionError}.

@ref{213f,,Availability}: WASI, FreeBSD


Added in version 3.11.1.

@end deffn

@geindex ECANCELED (errno モジュール)
@anchor{library/errno errno ECANCELED}@anchor{17c2}
@deffn {データ} errno.ECANCELED

Operation canceled


Added in version 3.2.

@end deffn

@geindex EOWNERDEAD (errno モジュール)
@anchor{library/errno errno EOWNERDEAD}@anchor{32c8}
@deffn {データ} errno.EOWNERDEAD

Owner died


Added in version 3.2.

@end deffn

@geindex ENOTRECOVERABLE (errno モジュール)
@anchor{library/errno errno ENOTRECOVERABLE}@anchor{32c9}
@deffn {データ} errno.ENOTRECOVERABLE

State not recoverable


Added in version 3.2.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ctypes --- Python 用の外部関数ライブラリ,,errno --- 標準の errno システムシンボル,汎用オペレーティングシステムサービス
@anchor{library/ctypes doc}@anchor{32ca}@anchor{library/ctypes ctypes-a-foreign-function-library-for-python}@anchor{32cb}@anchor{library/ctypes module-ctypes}@anchor{2e}@anchor{library/ctypes translation-repo}@anchor{32cc}
@subsection @code{ctypes} --- Python 用の外部関数ライブラリ


@geindex module; ctypes

`ソースコード:' Lib/ctypes@footnote{https://github.com/python/cpython/tree/3.14/Lib/ctypes}


__________________________________________________________________


@code{ctypes} is a foreign function library for Python.  It provides C compatible
data types, and allows calling functions in DLLs or shared libraries.  It can be
used to wrap these libraries in pure Python.

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@menu
* ctypes チュートリアル:: 
* ctypesリファレンス:: 

@end menu

@node ctypes チュートリアル,ctypesリファレンス,,ctypes --- Python 用の外部関数ライブラリ
@anchor{library/ctypes ctypes-ctypes-tutorial}@anchor{32cd}@anchor{library/ctypes ctypes-tutorial}@anchor{32ce}
@subsubsection ctypes チュートリアル


注意: このチュートリアルのコードサンプルは動作確認のために @ref{3e,,doctest} を使います。コードサンプルの中には Linux、 Windows、あるいは macOS 上で異なる動作をするものがあるため、サンプルのコメントに doctest 命令を入れてあります。

注意: いくつかのコードサンプルで ctypes の @ref{32cf,,c_int} 型を参照しています。 @code{sizeof(long) == sizeof(int)} であるようなプラットフォームでは、この型は @ref{32d0,,c_long} のエイリアスです。そのため、 @ref{32cf,,c_int} 型を想定しているときに @ref{32d0,,c_long} が表示されたとしても、混乱しないようにしてください --- 実際には同じ型なのです。

@menu
* 動的リンクライブラリをロードする:: 
* ロードしたdllから関数にアクセスする:: 
* 関数を呼び出す:: 
* 基本データ型:: 
* 続・関数を呼び出す:: 
* Calling variadic functions:: 
* 自作のデータ型とともに関数を呼び出す:: 
* 要求される引数の型を指定する (関数プロトタイプ): 要求される引数の型を指定する 関数プロトタイプ. 
* 戻り値の型:: 
* ポインタを渡す(または、パラメータの参照渡し): ポインタを渡す または、パラメータの参照渡し. 
* 構造体と共用体:: 
* Structure/union layout@comma{} alignment and byte order: Structure/union layout alignment and byte order. 
* 構造体と共用体におけるビットフィールド:: 
* 配列: 配列<2>. 
* ポインタ:: 
* Thread safety without the GIL:: 
* 型変換:: 
* 不完全型:: 
* コールバック関数:: 
* dllからエクスポートされた値へアクセスする:: 
* びっくり仰天:: 
* 可変サイズのデータ型:: 

@end menu

@node 動的リンクライブラリをロードする,ロードしたdllから関数にアクセスする,,ctypes チュートリアル
@anchor{library/ctypes ctypes-loading-dynamic-link-libraries}@anchor{32d1}@anchor{library/ctypes loading-dynamic-link-libraries}@anchor{32d2}
@subsubsection 動的リンクライブラリをロードする


@code{ctypes} exports the `cdll', and on Windows `windll' and `oledll'
objects, for loading dynamic link libraries.

You load libraries by accessing them as attributes of these objects. `cdll'
loads libraries which export functions using the standard @code{cdecl} calling
convention, while `windll' libraries call functions using the @code{stdcall}
calling convention. `oledll' also uses the @code{stdcall} calling convention, and
assumes the functions return a Windows @code{HRESULT} error code. The error
code is used to automatically raise an @ref{2c0,,OSError} exception when the
function call fails.


バージョン 3.3 で変更: Windows エラーは以前は @ref{1260,,WindowsError} を送出していましたが、これは現在では @ref{2c0,,OSError} の別名になっています。


Here are some examples for Windows. Note that @code{msvcrt} is the MS standard C
library containing most standard C functions, and uses the @code{cdecl} calling
convention:

@example
>>> from ctypes import *
>>> print(windll.kernel32)
<WinDLL 'kernel32', handle ... at ...>
>>> print(cdll.msvcrt)
<CDLL 'msvcrt', handle ... at ...>
>>> libc = cdll.msvcrt
>>>
@end example

Windows では通常の @code{.dll} ファイル拡張子を自動的に追加します。

@cartouche
@quotation 注釈 
@code{cdll.msvcrt} 経由で標準 C ライブラリにアクセスすると、Python が使用しているライブラリとは互換性のない可能性のある、古いバージョンのライブラリが使用されます。可能な場合には、ネイティブ Python の機能を使用するか、@code{msvcrt} モジュールをインポートして使用してください。
@end quotation
@end cartouche

On Linux, it is required to specify the filename `including' the extension to
load a library, so attribute access can not be used to load libraries. Either the
@ref{32d3,,LoadLibrary()} method of the dll loaders should be used,
or you should load the library by creating an instance of CDLL by calling
the constructor:

@example
>>> cdll.LoadLibrary("libc.so.6")
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6")
>>> libc
<CDLL 'libc.so.6', handle ... at ...>
>>>
@end example

@c XXX Add section for macOS.

@node ロードしたdllから関数にアクセスする,関数を呼び出す,動的リンクライブラリをロードする,ctypes チュートリアル
@anchor{library/ctypes accessing-functions-from-loaded-dlls}@anchor{32d4}@anchor{library/ctypes ctypes-accessing-functions-from-loaded-dlls}@anchor{32d5}
@subsubsection ロードしたdllから関数にアクセスする


dll オブジェクトの属性として関数にアクセスします:

@example
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
@end example

Note that win32 system dlls like @code{kernel32} and @code{user32} often export ANSI
as well as UNICODE versions of a function. The UNICODE version is exported with
a @code{W} appended to the name, while the ANSI version is exported with an @code{A}
appended to the name. The win32 @code{GetModuleHandle} function, which returns a
`module handle' for a given module name, has the following C prototype, and a
macro is used to expose one of them as @code{GetModuleHandle} depending on whether
UNICODE is defined or not:

@example
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
@end example

`windll' は魔法を使ってどちらか一つを選ぶようなことはしません。@code{GetModuleHandleA} もしくは @code{GetModuleHandleW} を明示的に指定して必要とするバージョンにアクセスし、バイト列か文字列を使ってそれぞれ呼び出さなければなりません。

時には、 dll が関数を @code{"??2@@YAPAXI@@Z"} のような Python 識別子として有効でない名前でエクスポートすることがあります。このような場合に関数を取り出すには、 @ref{dca,,getattr()} を使わなければなりません。:

@example
>>> getattr(cdll.msvcrt, "??2@@YAPAXI@@Z")
<_FuncPtr object at 0x...>
>>>
@end example

Windows では、名前ではなく序数によって関数をエクスポートする dll もあります。こうした関数には序数を使って dll オブジェクトにインデックス指定することでアクセスします:

@example
>>> cdll.kernel32[1]
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
@end example

@node 関数を呼び出す,基本データ型,ロードしたdllから関数にアクセスする,ctypes チュートリアル
@anchor{library/ctypes calling-functions}@anchor{32d6}@anchor{library/ctypes ctypes-calling-functions}@anchor{32d7}
@subsubsection 関数を呼び出す


You can call these functions like any other Python callable. This example uses
the @code{rand()} function, which takes no arguments and returns a pseudo-random integer:

@example
>>> print(libc.rand())
1804289383
@end example

On Windows, you can call the @code{GetModuleHandleA()} function, which returns a win32 module
handle (passing @code{None} as single argument to call it with a @code{NULL} pointer):

@example
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))
0x1d000000
>>>
@end example

@code{cdecl} 呼び出し規約を使って @code{stdcall} 関数を呼び出したときには、 @ref{2ec,,ValueError} が送出されます。逆の場合も同様です:

@example
>>> cdll.kernel32.GetModuleHandleA(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
@end example

正しい呼び出し規約を知るためには、呼び出したい関数についての C ヘッダファイルもしくはドキュメントを見なければなりません。

On Windows, @code{ctypes} uses win32 structured exception handling to prevent
crashes from general protection faults when functions are called with invalid
argument values:

@example
>>> windll.kernel32.GetModuleHandleA(32)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>
@end example

There are, however, enough ways to crash Python with @code{ctypes}, so you
should be careful anyway.  The @ref{5c,,faulthandler} module can be helpful in
debugging crashes (e.g. from segmentation faults produced by erroneous C library
calls).

@code{None}, integers, bytes objects and (unicode) strings are the only native
Python objects that can directly be used as parameters in these function calls.
@code{None} is passed as a C @code{NULL} pointer, bytes objects and strings are passed
as pointer to the memory block that contains their data (char* or
wchar_t*).  Python integers are passed as the platform's default C
int type, their value is masked to fit into the C type.

Before we move on calling functions with other parameter types, we have to learn
more about @code{ctypes} data types.

@node 基本データ型,続・関数を呼び出す,関数を呼び出す,ctypes チュートリアル
@anchor{library/ctypes ctypes-fundamental-data-types}@anchor{32d8}@anchor{library/ctypes fundamental-data-types}@anchor{32d9}
@subsubsection 基本データ型


@code{ctypes} defines a number of primitive C compatible data types:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ctypes の型

@tab

C の型

@tab

Python の型

@item

@ref{32da,,c_bool}

@tab

_Bool

@tab

bool (1)

@item

@ref{32db,,c_char}

@tab

char

@tab

1文字のバイト列オブジェクト

@item

@ref{32dc,,c_wchar}

@tab

@code{wchar_t}

@tab

1文字の文字列

@item

@ref{1ae0,,c_byte}

@tab

char

@tab

int

@item

@ref{1ae1,,c_ubyte}

@tab

unsigned char

@tab

int

@item

@ref{32dd,,c_short}

@tab

short

@tab

int

@item

@ref{32de,,c_ushort}

@tab

unsigned short

@tab

int

@item

@ref{32cf,,c_int}

@tab

int

@tab

int

@item

@ref{32df,,c_int8}

@tab

@code{int8_t}

@tab

int

@item

@ref{32e0,,c_int16}

@tab

@code{int16_t}

@tab

int

@item

@ref{32e1,,c_int32}

@tab

@code{int32_t}

@tab

int

@item

@ref{32e2,,c_int64}

@tab

@code{int64_t}

@tab

int

@item

@ref{32e3,,c_uint}

@tab

unsigned int

@tab

int

@item

@ref{32e4,,c_uint8}

@tab

@code{uint8_t}

@tab

int

@item

@ref{32e5,,c_uint16}

@tab

@code{uint16_t}

@tab

int

@item

@ref{32e6,,c_uint32}

@tab

@code{uint32_t}

@tab

int

@item

@ref{32e7,,c_uint64}

@tab

@code{uint64_t}

@tab

int

@item

@ref{32d0,,c_long}

@tab

long

@tab

int

@item

@ref{32e8,,c_ulong}

@tab

unsigned long

@tab

int

@item

@ref{32e9,,c_longlong}

@tab

__int64 または long long

@tab

int

@item

@ref{32ea,,c_ulonglong}

@tab

unsigned __int64 または unsigned long long

@tab

int

@item

@ref{32eb,,c_size_t}

@tab

@code{size_t}

@tab

int

@item

@ref{1454,,c_ssize_t}

@tab

@code{ssize_t} or
@ref{c55,,Py_ssize_t}

@tab

int

@item

@ref{1b63,,c_time_t}

@tab

@code{time_t}

@tab

int

@item

@ref{32ec,,c_float}

@tab

float

@tab

浮動小数点数

@item

@ref{1cb8,,c_double}

@tab

double

@tab

浮動小数点数

@item

@ref{1cb9,,c_longdouble}

@tab

long double

@tab

浮動小数点数

@item

@ref{1a57,,c_char_p}

@tab

char* (NUL 終端)

@tab

バイト列オブジェクトまたは @code{None}

@item

@ref{1a58,,c_wchar_p}

@tab

wchar_t* (NUL 終端)

@tab

文字列または @code{None}

@item

@ref{1a59,,c_void_p}

@tab

void*

@tab

整数または @code{None}

@end multitable



@enumerate 

@item 
コンストラクタは任意のオブジェクトをその真偽値として受け取ります。
@end enumerate

Additionally, if IEC 60559 compatible complex arithmetic (Annex G) is supported
in both C and @code{libffi}, the following complex types are available:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} 
@headitem

ctypes の型

@tab

C の型

@tab

Python の型

@item

@ref{1ed,,c_float_complex}

@tab

float complex

@tab

複素数

@item

@ref{1ee,,c_double_complex}

@tab

double complex

@tab

複素数

@item

@ref{1ef,,c_longdouble_complex}

@tab

long double complex

@tab

複素数

@end multitable


これら全ての型はその型を呼び出すことによって作成でき、オプションとして型と値が合っている初期化子を指定することができます:

@example
>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
@end example

これらの型は変更可能であり、値を後で変更することもできます:

@example
>>> i = c_int(42)
>>> print(i)
c_long(42)
>>> print(i.value)
42
>>> i.value = -99
>>> print(i.value)
-99
>>>
@end example

Assigning a new value to instances of the pointer types @ref{1a57,,c_char_p},
@ref{1a58,,c_wchar_p}, and @ref{1a59,,c_void_p} changes the `memory location' they
point to, `not the contents' of the memory block (of course not, because Python
string objects are immutable):

@example
>>> s = "Hello, World"
>>> c_s = c_wchar_p(s)
>>> print(c_s)
c_wchar_p(139966785747344)
>>> print(c_s.value)
Hello World
>>> c_s.value = "Hi, there"
>>> print(c_s)              # the memory location has changed
c_wchar_p(139966783348904)
>>> print(c_s.value)
Hi, there
>>> print(s)                # first object is unchanged
Hello, World
>>>
@end example

しかし、変更可能なメモリを指すポインタであることを想定している関数へそれらを渡さないように注意すべきです。もし変更可能なメモリブロックが必要なら、 ctypes には @ref{32ed,,create_string_buffer()} 関数があり、いろいろな方法で作成することできます。現在のメモリブロックの内容は @code{raw} プロパティを使ってアクセス (あるいは変更) することができます。もし現在のメモリブロックに NUL 終端文字列としてアクセスしたいなら、 @code{value} プロパティを使ってください:

@example
>>> from ctypes import *
>>> p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
>>> print(sizeof(p), repr(p.raw))
3 b'\x00\x00\x00'
>>> p = create_string_buffer(b"Hello")     # create a buffer containing a NUL terminated string
>>> print(sizeof(p), repr(p.raw))
6 b'Hello\x00'
>>> print(repr(p.value))
b'Hello'
>>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
>>> print(sizeof(p), repr(p.raw))
10 b'Hello\x00\x00\x00\x00\x00'
>>> p.value = b"Hi"
>>> print(sizeof(p), repr(p.raw))
10 b'Hi\x00lo\x00\x00\x00\x00\x00'
>>>
@end example

The @ref{32ed,,create_string_buffer()} function replaces the old @code{c_buffer()}
function (which is still available as an alias).  To create a mutable memory
block containing unicode characters of the C type @code{wchar_t}, use the
@ref{1db4,,create_unicode_buffer()} function.

@node 続・関数を呼び出す,Calling variadic functions,基本データ型,ctypes チュートリアル
@anchor{library/ctypes calling-functions-continued}@anchor{32ee}@anchor{library/ctypes ctypes-calling-functions-continued}@anchor{32ef}
@subsubsection 続・関数を呼び出す


printf は @ref{ccd,,sys.stdout} では `なく' 、本物の標準出力チャンネルへプリントすることに注意してください。したがって、これらの例はコンソールプロンプトでのみ動作し、 `IDLE' や `PythonWin' では動作しません。:

@example
>>> printf = libc.printf
>>> printf(b"Hello, %s\n", b"World!")
Hello, World!
14
>>> printf(b"Hello, %S\n", "World!")
Hello, World!
14
>>> printf(b"%d bottles of beer\n", 42)
42 bottles of beer
19
>>> printf(b"%f bottles of beer\n", 42.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 2: TypeError: Don't know how to convert parameter 2
>>>
@end example

As has been mentioned before, all Python types except integers, strings, and
bytes objects have to be wrapped in their corresponding @code{ctypes} type, so
that they can be converted to the required C data type:

@example
>>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
An int 1234, a double 3.140000
31
>>>
@end example

@node Calling variadic functions,自作のデータ型とともに関数を呼び出す,続・関数を呼び出す,ctypes チュートリアル
@anchor{library/ctypes calling-variadic-functions}@anchor{32f0}@anchor{library/ctypes ctypes-calling-variadic-functions}@anchor{32f1}
@subsubsection Calling variadic functions


On a lot of platforms calling variadic functions through ctypes is exactly the same
as calling functions with a fixed number of parameters. On some platforms, and in
particular ARM64 for Apple Platforms, the calling convention for variadic functions
is different than that for regular functions.

On those platforms it is required to specify the @ref{17c1,,argtypes}
attribute for the regular, non-variadic, function arguments:

@example
libc.printf.argtypes = [ctypes.c_char_p]
@end example

Because specifying the attribute does not inhibit portability it is advised to always
specify @ref{17c1,,argtypes} for all variadic functions.

@node 自作のデータ型とともに関数を呼び出す,要求される引数の型を指定する 関数プロトタイプ,Calling variadic functions,ctypes チュートリアル
@anchor{library/ctypes calling-functions-with-your-own-custom-data-types}@anchor{32f2}@anchor{library/ctypes ctypes-calling-functions-with-own-custom-data-types}@anchor{32f3}
@subsubsection 自作のデータ型とともに関数を呼び出す


You can also customize @code{ctypes} argument conversion to allow instances of
your own classes be used as function arguments. @code{ctypes} looks for an
@code{_as_parameter_} attribute and uses this as the function argument. The
attribute must be an integer, string, bytes, a @code{ctypes} instance, or an
object with an @code{_as_parameter_} attribute:

@example
>>> class Bottles:
...     def __init__(self, number):
...         self._as_parameter_ = number
...
>>> bottles = Bottles(42)
>>> printf(b"%d bottles of beer\n", bottles)
42 bottles of beer
19
>>>
@end example

If you don't want to store the instance's data in the @code{_as_parameter_}
instance variable, you could define a @ref{4b3,,property} which makes the
attribute available on request.

@node 要求される引数の型を指定する 関数プロトタイプ,戻り値の型,自作のデータ型とともに関数を呼び出す,ctypes チュートリアル
@anchor{library/ctypes ctypes-specifying-required-argument-types}@anchor{32f4}@anchor{library/ctypes specifying-the-required-argument-types-function-prototypes}@anchor{32f5}
@subsubsection 要求される引数の型を指定する (関数プロトタイプ)


It is possible to specify the required argument types of functions exported from
DLLs by setting the @ref{17c1,,argtypes} attribute.

@ref{17c1,,argtypes} must be a sequence of C data types (the @code{printf()} function is
probably not a good example here, because it takes a variable number and
different types of parameters depending on the format string, on the other hand
this is quite handy to experiment with this feature):

@example
>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
>>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
String 'Hi', Int 10, Double 2.200000
37
>>>
@end example

(C の関数のプロトタイプのように) 書式を指定すると互換性のない引数型になるのを防ぎ、引数を有効な型へ変換しようとします。:

@example
>>> printf(b"%d %d %d", 1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 2: TypeError: 'int' object cannot be interpreted as ctypes.c_char_p
>>> printf(b"%s %d %f\n", b"X", 2, 3)
X 2 3.000000
13
>>>
@end example

If you have defined your own classes which you pass to function calls, you have
to implement a @ref{32f6,,from_param()} class method for them to be able to use them
in the @ref{17c1,,argtypes} sequence. The @ref{32f6,,from_param()} class method receives
the Python object passed to the function call, it should do a typecheck or
whatever is needed to make sure this object is acceptable, and then return the
object itself, its @code{_as_parameter_} attribute, or whatever you want to
pass as the C function argument in this case. Again, the result should be an
integer, string, bytes, a @code{ctypes} instance, or an object with an
@code{_as_parameter_} attribute.

@node 戻り値の型,ポインタを渡す または、パラメータの参照渡し,要求される引数の型を指定する 関数プロトタイプ,ctypes チュートリアル
@anchor{library/ctypes ctypes-return-types}@anchor{32f7}@anchor{library/ctypes return-types}@anchor{32f8}
@subsubsection 戻り値の型


@c from ctypes import CDLL, c_char, c_char_p
@c from ctypes.util import find_library
@c libc = CDLL(find_library('c'))
@c strchr = libc.strchr

By default functions are assumed to return the C int type.  Other
return types can be specified by setting the @ref{32f9,,restype} attribute of the
function object.

The C prototype of @code{time()} is @code{time_t time(time_t *)}. Because @code{time_t}
might be of a different type than the default return type int, you should
specify the @code{restype} attribute:

@example
>>> libc.time.restype = c_time_t
@end example

The argument types can be specified using @ref{17c1,,argtypes}:

@example
>>> libc.time.argtypes = (POINTER(c_time_t),)
@end example

To call the function with a @code{NULL} pointer as first argument, use @code{None}:

@example
>>> print(libc.time(None))
1150640792
@end example

Here is a more advanced example, it uses the @code{strchr()} function, which expects
a string pointer and a char, and returns a pointer to a string:

@example
>>> strchr = libc.strchr
>>> strchr(b"abcdef", ord("d"))
8059983
>>> strchr.restype = c_char_p    # c_char_p is a pointer to a string
>>> strchr(b"abcdef", ord("d"))
b'def'
>>> print(strchr(b"abcdef", ord("x")))
None
>>>
@end example

If you want to avoid the @ref{233b,,ord("x")} calls above, you can set the
@ref{17c1,,argtypes} attribute, and the second argument will be converted from a
single character Python bytes object into a C char:

@example
>>> strchr.restype = c_char_p
>>> strchr.argtypes = [c_char_p, c_char]
>>> strchr(b"abcdef", b"d")
b'def'
>>> strchr(b"abcdef", b"def")
Traceback (most recent call last):
ctypes.ArgumentError: argument 2: TypeError: one character bytes, bytearray or integer expected
>>> print(strchr(b"abcdef", b"x"))
None
>>> strchr(b"abcdef", b"d")
b'def'
>>>
@end example

You can also use a callable Python object (a function or a class for example) as
the @ref{32f9,,restype} attribute, if the foreign function returns an integer.  The
callable will be called with the `integer' the C function returns, and the
result of this call will be used as the result of your function call. This is
useful to check for error return values and automatically raise an exception:

@example
>>> GetModuleHandle = windll.kernel32.GetModuleHandleA
>>> def ValidHandle(value):
...     if value == 0:
...         raise WinError()
...     return value
...
>>>
>>> GetModuleHandle.restype = ValidHandle
>>> GetModuleHandle(None)
486539264
>>> GetModuleHandle("something silly")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in ValidHandle
OSError: [Errno 126] The specified module could not be found.
>>>
@end example

@code{WinError} はエラーコードの文字列表現を得るために Windows の @code{FormatMessage()} api を呼び出し、例外を `返す' 関数です。 @code{WinError} はオプションでエラーコードパラメータを取ります。このパラメータが使われない場合は、エラーコードを取り出すために @ref{32fa,,GetLastError()} を呼び出します。

Please note that a much more powerful error checking mechanism is available
through the @ref{32fb,,errcheck} attribute;
see the reference manual for details.

@node ポインタを渡す または、パラメータの参照渡し,構造体と共用体,戻り値の型,ctypes チュートリアル
@anchor{library/ctypes ctypes-passing-pointers}@anchor{32fc}@anchor{library/ctypes passing-pointers-or-passing-parameters-by-reference}@anchor{32fd}
@subsubsection ポインタを渡す(または、パラメータの参照渡し)


時には、 C api 関数がパラメータのデータ型として `ポインタ' を想定していることがあります。おそらくパラメータと同一の場所に書き込むためか、もしくはそのデータが大きすぎて値渡しできない場合です。これは `パラメータの参照渡し' としても知られています。

@code{ctypes} exports the @ref{32fe,,byref()} function which is used to pass parameters
by reference.  The same effect can be achieved with the @ref{1a56,,pointer()} function,
although @ref{1a56,,pointer()} does a lot more work since it constructs a real pointer
object, so it is faster to use @ref{32fe,,byref()} if you don't need the pointer
object in Python itself:

@example
>>> i = c_int()
>>> f = c_float()
>>> s = create_string_buffer(b'\000' * 32)
>>> print(i.value, f.value, repr(s.value))
0 0.0 b'@w{'}
>>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
...             byref(i), byref(f), s)
3
>>> print(i.value, f.value, repr(s.value))
1 3.1400001049 b'Hello'
>>>
@end example

@node 構造体と共用体,Structure/union layout alignment and byte order,ポインタを渡す または、パラメータの参照渡し,ctypes チュートリアル
@anchor{library/ctypes ctypes-structures-unions}@anchor{32ff}@anchor{library/ctypes structures-and-unions}@anchor{3300}
@subsubsection 構造体と共用体


Structures and unions must derive from the @ref{1e5,,Structure} and @ref{1e6,,Union}
base classes which are defined in the @code{ctypes} module. Each subclass must
define a @ref{1936,,_fields_} attribute.  @code{_fields_} must be a list of
`2-tuples', containing a `field name' and a `field type'.

The field type must be a @code{ctypes} type like @ref{32cf,,c_int}, or any other
derived @code{ctypes} type: structure, union, array, pointer.

以下は、 `x' と `y' という名前の二つの整数からなる簡単な POINT 構造体の例です。コンストラクタで構造体を初期化する方法も説明しています:

@example
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = [("x", c_int),
...                 ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print(point.x, point.y)
10 20
>>> point = POINT(y=5)
>>> print(point.x, point.y)
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: too many initializers
>>>
@end example

しかし、もっと複雑な構造体を構築することもできます。ある構造体は、他の構造体をフィールド型として使うことで、他の構造体を含むことができます。

`upperleft' と `lowerright' という名前の二つの POINT を持つ RECT 構造体です。:

@example
>>> class RECT(Structure):
...     _fields_ = [("upperleft", POINT),
...                 ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print(rc.upperleft.x, rc.upperleft.y)
0 5
>>> print(rc.lowerright.x, rc.lowerright.y)
0 0
>>>
@end example

入れ子になった構造体はいくつかの方法を用いてコンストラクタで初期化することができます。:

@example
>>> r = RECT(POINT(1, 2), POINT(3, 4))
>>> r = RECT((1, 2), (3, 4))
@end example

Field @ref{1881,,descriptor}s can be retrieved from the `class', they are useful
for debugging because they can provide useful information.
See @ref{1e8,,CField}:

@example
>>> POINT.x
<ctypes.CField 'x' type=c_int, ofs=0, size=4>
>>> POINT.y
<ctypes.CField 'y' type=c_int, ofs=4, size=4>
>>>
@end example
@anchor{library/ctypes ctypes-structureunion-alignment-byte-order}@anchor{3301}
@cartouche
@quotation 警告 
@code{ctypes} does not support passing unions or structures with bit-fields
to functions by value.  While this may work on 32-bit x86, it's not
guaranteed by the library to work in the general case.  Unions and
structures with bit-fields should always be passed to functions by pointer.
@end quotation
@end cartouche

@node Structure/union layout alignment and byte order,構造体と共用体におけるビットフィールド,構造体と共用体,ctypes チュートリアル
@anchor{library/ctypes structure-union-layout-alignment-and-byte-order}@anchor{3302}
@subsubsection Structure/union layout, alignment and byte order


By default, Structure and Union fields are laid out in the same way the C
compiler does it.  It is possible to override this behavior entirely by specifying a
@ref{1e7,,_layout_} class attribute in the subclass definition; see
the attribute documentation for details.

It is possible to specify the maximum alignment for the fields and/or for the
structure itself by setting the class attributes @ref{317,,_pack_}
and/or @ref{4e8,,_align_}, respectively.
See the attribute documentation for details.

@code{ctypes} uses the native byte order for Structures and Unions.  To build
structures with non-native byte order, you can use one of the
@ref{3303,,BigEndianStructure}, @ref{3304,,LittleEndianStructure},
@ref{1bb7,,BigEndianUnion}, and @ref{1bb8,,LittleEndianUnion} base classes.  These
classes cannot contain pointer fields.

@node 構造体と共用体におけるビットフィールド,配列<2>,Structure/union layout alignment and byte order,ctypes チュートリアル
@anchor{library/ctypes bit-fields-in-structures-and-unions}@anchor{3305}@anchor{library/ctypes ctypes-bit-fields-in-structures-unions}@anchor{1e4}
@subsubsection 構造体と共用体におけるビットフィールド


It is possible to create structures and unions containing bit fields. Bit fields
are only possible for integer fields, the bit width is specified as the third
item in the @ref{1936,,_fields_} tuples:

@example
>>> class Int(Structure):
...     _fields_ = [("first_16", c_int, 16),
...                 ("second_16", c_int, 16)]
...
>>> print(Int.first_16)
<ctypes.CField 'first_16' type=c_int, ofs=0, bit_size=16, bit_offset=0>
>>> print(Int.second_16)
<ctypes.CField 'second_16' type=c_int, ofs=0, bit_size=16, bit_offset=16>
@end example

It is important to note that bit field allocation and layout in memory are not
defined as a C standard; their implementation is compiler-specific.
By default, Python will attempt to match the behavior of a "native" compiler
for the current platform.
See the @ref{1e7,,_layout_} attribute for details on the default
behavior and how to change it.

@node 配列<2>,ポインタ,構造体と共用体におけるビットフィールド,ctypes チュートリアル
@anchor{library/ctypes arrays}@anchor{3306}@anchor{library/ctypes ctypes-arrays}@anchor{3307}
@subsubsection 配列


配列 (Array) はシーケンスであり、決まった数の同じ型のインスタンスを持ちます。

推奨されている配列の作成方法はデータ型に正の整数を掛けることです。:

@example
TenPointsArrayType = POINT * 10
@end example

ややわざとらしいデータ型の例になりますが、他のものに混ざって 4 個の POINT がある構造体です:

@example
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = ("x", c_int), ("y", c_int)
...
>>> class MyStruct(Structure):
...     _fields_ = [("a", c_int),
...                 ("b", c_float),
...                 ("point_array", POINT * 4)]
>>>
>>> print(len(MyStruct().point_array))
4
>>>
@end example

インスタンスはクラスを呼び出す通常の方法で作成します。:

@example
arr = TenPointsArrayType()
for pt in arr:
    print(pt.x, pt.y)
@end example

上記のコードは @code{0 0} という行が並んだものを表示します。配列の要素がゼロで初期化されているためです。

正しい型の初期化子を指定することもできます。:

@example
>>> from ctypes import *
>>> TenIntegers = c_int * 10
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> print(ii)
<c_long_Array_10 object at 0x...>
>>> for i in ii: print(i, end=" ")
...
1 2 3 4 5 6 7 8 9 10
>>>
@end example

@node ポインタ,Thread safety without the GIL,配列<2>,ctypes チュートリアル
@anchor{library/ctypes ctypes-pointers}@anchor{3308}@anchor{library/ctypes pointers}@anchor{3309}
@subsubsection ポインタ


Pointer instances are created by calling the @ref{1a56,,pointer()} function on a
@code{ctypes} type:

@example
>>> from ctypes import *
>>> i = c_int(42)
>>> pi = pointer(i)
>>>
@end example

次のように、ポインタインスタンスは、ポインタが指すオブジェクト (上の例では @code{i}) を返す @ref{330a,,contents} 属性を持ちます:

@example
>>> pi.contents
c_long(42)
>>>
@end example

Note that @code{ctypes} does not have OOR (original object return), it constructs a
new, equivalent object each time you retrieve an attribute:

@example
>>> pi.contents is i
False
>>> pi.contents is pi.contents
False
>>>
@end example

別の @ref{32cf,,c_int} インスタンスがポインタの contents 属性に代入されると、これが記憶されているメモリ位置を指すポインタに変化します。:

@example
>>> i = c_int(99)
>>> pi.contents = i
>>> pi.contents
c_long(99)
>>>
@end example

@c XXX Document dereferencing pointers, and that it is preferred over the
@c .contents attribute.

ポインタインスタンスは整数でインデックス指定することもできます。:

@example
>>> pi[0]
99
>>>
@end example

整数インデックスへ代入するとポインタが指す値が変更されます。:

@example
>>> print(i)
c_long(99)
>>> pi[0] = 22
>>> print(i)
c_long(22)
>>>
@end example

0 ではないインデックスを使うこともできますが、 C の場合と同じように自分が何をしているかを理解している必要があります。任意のメモリ位置にアクセスもしくは変更できるのです。一般的にこの機能を使うのは、 C 関数からポインタを受け取り、そのポインタが単一の要素ではなく実際に配列を指していると `分かっている' 場合だけです。

Behind the scenes, the @ref{1a56,,pointer()} function does more than simply create
pointer instances, it has to create pointer `types' first. This is done with the
@ref{1f1,,POINTER()} function, which accepts any @code{ctypes} type, and returns a
new type:

@example
>>> PI = POINTER(c_int)
>>> PI
<class 'ctypes.LP_c_long'>
>>> PI(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected c_long instead of int
>>> PI(c_int(42))
<ctypes.LP_c_long object at 0x...>
>>>
@end example

ポインタ型を引数なしで呼び出すと @code{NULL} ポインタを作成します。 @code{NULL} ポインタは @code{False} ブール値を持っています。:

@example
>>> null_ptr = POINTER(c_int)()
>>> print(bool(null_ptr))
False
>>>
@end example

@code{ctypes} checks for @code{NULL} when dereferencing pointers (but dereferencing
invalid non-@code{NULL} pointers would crash Python):

@example
>>> null_ptr[0]
Traceback (most recent call last):
    ....
ValueError: NULL pointer access
>>>

>>> null_ptr[0] = 1234
Traceback (most recent call last):
    ....
ValueError: NULL pointer access
>>>
@end example

@node Thread safety without the GIL,型変換,ポインタ,ctypes チュートリアル
@anchor{library/ctypes ctypes-thread-safety}@anchor{330b}@anchor{library/ctypes thread-safety-without-the-gil}@anchor{330c}
@subsubsection Thread safety without the GIL


From Python 3.13 onward, the @ref{164,,GIL} can be disabled on the @ref{176d,,free-threaded build}.
In ctypes, reads and writes to a single object concurrently is safe, but not across multiple objects:

@quotation

@example
>>> number = c_int(42)
>>> pointer_a = pointer(number)
>>> pointer_b = pointer(number)
@end example
@end quotation

In the above, it's only safe for one object to read and write to the address at once if the GIL is disabled.
So, @code{pointer_a} can be shared and written to across multiple threads, but only if @code{pointer_b}
is not also attempting to do the same. If this is an issue, consider using a @ref{19f4,,threading.Lock}
to synchronize access to memory:

@quotation

@example
>>> import threading
>>> lock = threading.Lock()
>>> # Thread 1
>>> with lock:
...    pointer_a.contents = 24
>>> # Thread 2
>>> with lock:
...    pointer_b.contents = 42
@end example
@end quotation

@node 型変換,不完全型,Thread safety without the GIL,ctypes チュートリアル
@anchor{library/ctypes ctypes-type-conversions}@anchor{330d}@anchor{library/ctypes type-conversions}@anchor{330e}
@subsubsection 型変換


Usually, ctypes does strict type checking.  This means, if you have
@code{POINTER(c_int)} in the @ref{17c1,,argtypes} list of a function or as the type of
a member field in a structure definition, only instances of exactly the same
type are accepted.  There are some exceptions to this rule, where ctypes accepts
other objects.  For example, you can pass compatible array instances instead of
pointer types.  So, for @code{POINTER(c_int)}, ctypes accepts an array of c_int:

@example
>>> class Bar(Structure):
...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
...
>>> bar = Bar()
>>> bar.values = (c_int * 3)(1, 2, 3)
>>> bar.count = 3
>>> for i in range(bar.count):
...     print(bar.values[i])
...
1
2
3
>>>
@end example

In addition, if a function argument is explicitly declared to be a pointer type
(such as @code{POINTER(c_int)}) in @ref{17c1,,argtypes}, an object of the pointed
type (@code{c_int} in this case) can be passed to the function.  ctypes will apply
the required @ref{32fe,,byref()} conversion in this case automatically.

POINTER型フィールドを @code{NULL} に設定するために、 @code{None} を代入してもかまいません。:

@example
>>> bar.values = None
>>>
@end example

@c XXX list other conversions...

Sometimes you have instances of incompatible types.  In C, you can cast one type
into another type.  @code{ctypes} provides a @ref{330f,,cast()} function which can be
used in the same way.  The @code{Bar} structure defined above accepts
@code{POINTER(c_int)} pointers or @ref{32cf,,c_int} arrays for its @code{values} field,
but not instances of other types:

@example
>>> bar.values = (c_byte * 4)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
>>>
@end example

このような場合には、 @ref{330f,,cast()} 関数が便利です。

@ref{330f,,cast()} 関数は ctypes インスタンスを異なる ctypes データ型を指すポインタへキャストするために使えます。 @ref{330f,,cast()} は二つのパラメータ、ある種のポインタかそのポインタへ変換できる ctypes オブジェクトと、 ctypes ポインタ型を取ります。そして、第二引数のインスタンスを返します。このインスタンスは第一引数と同じメモリブロックを参照しています:

@example
>>> a = (c_byte * 4)()
>>> cast(a, POINTER(c_int))
<ctypes.LP_c_long object at ...>
>>>
@end example

したがって、 @ref{330f,,cast()} を @code{Bar} 構造体の @code{values} フィールドへ代入するために使うことができます:

@example
>>> bar = Bar()
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
>>> print(bar.values[0])
0
>>>
@end example

@node 不完全型,コールバック関数,型変換,ctypes チュートリアル
@anchor{library/ctypes ctypes-incomplete-types}@anchor{318}@anchor{library/ctypes incomplete-types}@anchor{3310}
@subsubsection 不完全型


`不完全型' はメンバーがまだ指定されていない構造体、共用体もしくは配列です。 C では、前方宣言により指定され、後で定義されます。:

@example
struct cell; /* forward declaration */

struct cell @{
    char *name;
    struct cell *next;
@};
@end example

ctypes コードへの直接的な変換ではこうなるでしょう。しかし、動作しません:

@example
>>> class cell(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("next", POINTER(cell))]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in cell
NameError: name 'cell' is not defined
>>>
@end example

because the new @code{class cell} is not available in the class statement itself.
In @code{ctypes}, we can define the @code{cell} class and set the
@ref{1936,,_fields_} attribute later, after the class statement:

@example
>>> from ctypes import *
>>> class cell(Structure):
...     pass
...
>>> cell._fields_ = [("name", c_char_p),
...                  ("next", POINTER(cell))]
>>>
@end example

試してみましょう。 @code{cell} のインスタンスを二つ作り、互いに参照し合うようにします。最後に、つながったポインタを何度かたどります。:

@example
>>> c1 = cell()
>>> c1.name = b"foo"
>>> c2 = cell()
>>> c2.name = b"bar"
>>> c1.next = pointer(c2)
>>> c2.next = pointer(c1)
>>> p = c1
>>> for i in range(8):
...     print(p.name, end=" ")
...     p = p.next[0]
...
foo bar foo bar foo bar foo bar
>>>
@end example

@node コールバック関数,dllからエクスポートされた値へアクセスする,不完全型,ctypes チュートリアル
@anchor{library/ctypes callback-functions}@anchor{3311}@anchor{library/ctypes ctypes-callback-functions}@anchor{3312}
@subsubsection コールバック関数


@code{ctypes} allows creating C callable function pointers from Python callables.
These are sometimes called `callback functions'.

最初に、コールバック関数のためのクラスを作る必要があります。そのクラスには呼び出し規約、戻り値の型およびこの関数が受け取る引数の数と型についての情報があります。

@ref{3313,,CFUNCTYPE()} ファクトリ関数は通常の @code{cdecl} 呼び出し規約を用いてコールバック関数のための型を作成します。 Windows では、 @ref{3314,,WINFUNCTYPE()} ファクトリ関数が @code{stdcall} 呼び出し規約を用いてコールバック関数の型を作成します。

これらのファクトリ関数はともに最初の引数に戻り値の型、残りの引数としてコールバック関数が想定する引数の型を渡して呼び出されます。

I will present an example here which uses the standard C library's
@code{qsort()} function, that is used to sort items with the help of a callback
function.  @code{qsort()} will be used to sort an array of integers:

@example
>>> IntArray5 = c_int * 5
>>> ia = IntArray5(5, 1, 7, 33, 99)
>>> qsort = libc.qsort
>>> qsort.restype = None
>>>
@end example

@code{qsort()} must be called with a pointer to the data to sort, the number of
items in the data array, the size of one item, and a pointer to the comparison
function, the callback. The callback will then be called with two pointers to
items, and it must return a negative integer if the first item is smaller than
the second, a zero if they are equal, and a positive integer otherwise.

コールバック関数は整数へのポインタを受け取り、整数を返す必要があります。まず、コールバック関数のための @code{type} を作成します。:

@example
>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
>>>
@end example

まず初めに、これが受け取った変数を表示するだけのシンプルなコールバックです:

@example
>>> def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return 0
...
>>> cmp_func = CMPFUNC(py_cmp_func)
>>>
@end example

結果は以下の通りです:

@example
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func)
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 5 7
py_cmp_func 1 7
>>>
@end example

ここで 2 つの要素を実際に比較し、役に立つ結果を返します:

@example
>>> def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return a[0] - b[0]
...
>>>
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func))
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>
@end example

簡単に確認できるように、配列を次のようにソートしました:

@example
>>> for i in ia: print(i, end=" ")
...
1 5 7 33 99
>>>
@end example

関数ファクトリはデコレータファクトリとしても使えるので、次のようにも書けます:

@example
>>> @@CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
... def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return a[0] - b[0]
...
>>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>
@end example

@cartouche
@quotation 注釈 
Make sure you keep references to @ref{3313,,CFUNCTYPE()} objects as long as they
are used from C code. @code{ctypes} doesn't, and if you don't, they may be
garbage collected, crashing your program when a callback is made.

同様に、コールバック関数が Python の管理外 (例えば、コールバックを呼び出す外部のコード) で作られたスレッドで呼び出された場合、 ctypes は全ての呼び出しごとに新しいダミーの Python スレッドを作成することに注意してください。 この動作はほとんどの目的に対して正しいものですが、同じ C スレッドからの呼び出しだったとしても、 @ref{185f,,threading.local} で格納された値は異なるコールバックをまたいで生存は `しません' 。
@end quotation
@end cartouche

@node dllからエクスポートされた値へアクセスする,びっくり仰天,コールバック関数,ctypes チュートリアル
@anchor{library/ctypes accessing-values-exported-from-dlls}@anchor{3315}@anchor{library/ctypes ctypes-accessing-values-exported-from-dlls}@anchor{3316}
@subsubsection dllからエクスポートされた値へアクセスする


Some shared libraries not only export functions, they also export variables. An
example in the Python library itself is the @ref{381,,Py_Version}, Python
runtime version number encoded in a single constant integer.

@code{ctypes} can access values like this with the @ref{3317,,in_dll()} class methods of
the type.  `pythonapi' is a predefined symbol giving access to the Python C
api:

@example
>>> version = ctypes.c_int.in_dll(ctypes.pythonapi, "Py_Version")
>>> print(hex(version.value))
0x30c00a0
@end example

ポインタの使い方を説明する拡張例では、 Python がエクスポートする @ref{3318,,PyImport_FrozenModules} ポインタにアクセスします。

この値のドキュメントから引用すると:

@quotation

このポインタは @ref{979,,_frozen} のレコードからなり、終端の要素のメンバが @code{NULL} かゼロになっているような配列を指すよう初期化されます。
フリーズされたモジュールをインポートするとき、このテーブルを検索します。
サードパーティ製のコードからこのポインタに仕掛けを講じて、動的に生成されたフリーズ化モジュールの集合を提供するようにできます。
@end quotation

So manipulating this pointer could even prove useful. To restrict the example
size, we show only how this table can be read with @code{ctypes}:

@example
>>> from ctypes import *
>>>
>>> class struct_frozen(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("code", POINTER(c_ubyte)),
...                 ("size", c_int),
...                 ("get_code", POINTER(c_ubyte)),  # Function pointer
...                ]
...
>>>
@end example

私たちは @ref{979,,_frozen} データ型を定義済みなので、このテーブルを指すポインタを得ることができます。:

@example
>>> FrozenTable = POINTER(struct_frozen)
>>> table = FrozenTable.in_dll(pythonapi, "_PyImport_FrozenBootstrap")
>>>
@end example

@code{table} が @code{struct_frozen} レコードの配列への @code{pointer} なので、その配列に対して反復処理を行えます。しかし、ループが確実に終了するようにする必要があります。なぜなら、ポインタに大きさの情報がないからです。遅かれ早かれ、アクセス違反か何かでクラッシュすることになるでしょう。 @code{NULL} エントリに達したときはループを抜ける方が良いです:

@example
>>> for item in table:
...     if item.name is None:
...         break
...     print(item.name.decode("ascii"), item.size)
...
_frozen_importlib 31764
_frozen_importlib_external 41499
zipimport 12345
>>>
@end example

標準 Python はフローズンモジュールとフローズンパッケージ (負の @code{size} メンバーで表されています) を持っているという事実はあまり知られておらず、テストにだけ使われています。例えば、 @code{import __hello__} を試してみてください。

@node びっくり仰天,可変サイズのデータ型,dllからエクスポートされた値へアクセスする,ctypes チュートリアル
@anchor{library/ctypes ctypes-surprises}@anchor{3319}@anchor{library/ctypes surprises}@anchor{331a}
@subsubsection びっくり仰天


There are some edges in @code{ctypes} where you might expect something other
than what actually happens.

次に示す例について考えてみてください。:

@example
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = ("x", c_int), ("y", c_int)
...
>>> class RECT(Structure):
...     _fields_ = ("a", POINT), ("b", POINT)
...
>>> p1 = POINT(1, 2)
>>> p2 = POINT(3, 4)
>>> rc = RECT(p1, p2)
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1 2 3 4
>>> # now swap the two points
>>> rc.a, rc.b = rc.b, rc.a
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
3 4 3 4
>>>
@end example

うーん、最後の文に @code{3 4 1 2} と表示されることを期待していたはずです。何が起きたのでしょうか? 上の行の @code{rc.a, rc.b = rc.b, rc.a} の各段階はこのようになります。:

@example
>>> temp0, temp1 = rc.b, rc.a
>>> rc.a = temp0
>>> rc.b = temp1
>>>
@end example

@code{temp0} と @code{temp1} は前記の @code{rc} オブジェクトの内部バッファでまだ使われているオブジェクトです。したがって、 @code{rc.a = temp0} を実行すると @code{temp0} のバッファ内容が @code{rc} のバッファへコピーされます。さらに、これは @code{temp1} の内容を変更します。そのため、最後の代入 @code{rc.b = temp1} は、期待する結果にはならないのです。

Structure 、 Union および Array のサブオブジェクトを取り出しても、そのサブオブジェクトが `コピー' されるわけではなく、ルートオブジェクトの内部バッファにアクセスするラッパーオブジェクトを取り出すことを覚えておいてください。

期待とは違う振る舞いをする別の例はこれです:

@example
>>> s = c_char_p()
>>> s.value = b"abc def ghi"
>>> s.value
b'abc def ghi'
>>> s.value is s.value
False
>>>
@end example

@cartouche
@quotation 注釈 
@ref{1a57,,c_char_p} からインスタンス化されたオブジェクトは、bytes または整数に設定された値しか持てません。
@end quotation
@end cartouche

なぜ @code{False} と表示されるのでしょうか? ctypes インスタンスはメモリと、メモリの内容にアクセスするいくつかの @ref{1881,,descriptor} (記述子)を含むオブジェクトです。メモリブロックに Python オブジェクトを保存してもオブジェクト自身が保存される訳ではなく、オブジェクトの @code{contents} が保存されます。その contents に再アクセスすると新しい Python オブジェクトがその度に作られます。

@node 可変サイズのデータ型,,びっくり仰天,ctypes チュートリアル
@anchor{library/ctypes ctypes-variable-sized-data-types}@anchor{331b}@anchor{library/ctypes variable-sized-data-types}@anchor{331c}
@subsubsection 可変サイズのデータ型


@code{ctypes} provides some support for variable-sized arrays and structures.

@ref{331d,,resize()} 関数は既存の ctypes オブジェクトのメモリバッファのサイズを変更したい場合に使えます。この関数は第一引数にオブジェクト、第二引数に要求されたサイズをバイト単位で指定します。メモリブロックはオブジェクト型で指定される通常のメモリブロックより小さくすることはできません。これをやろうとすると、 @ref{2ec,,ValueError} が送出されます。:

@example
>>> short_array = (c_short * 4)()
>>> print(sizeof(short_array))
8
>>> resize(short_array, 4)
Traceback (most recent call last):
    ...
ValueError: minimum size is 8
>>> resize(short_array, 32)
>>> sizeof(short_array)
32
>>> sizeof(type(short_array))
8
>>>
@end example

これはこれで上手くいっていますが、この配列の追加した要素へどうやってアクセスするのでしょうか? この型は要素の数が 4 個であるとまだ認識しているので、他の要素にアクセスするとエラーになります。:

@example
>>> short_array[:]
[0, 0, 0, 0]
>>> short_array[7]
Traceback (most recent call last):
    ...
IndexError: invalid index
>>>
@end example

Another way to use variable-sized data types with @code{ctypes} is to use the
dynamic nature of Python, and (re-)define the data type after the required size
is already known, on a case by case basis.

@node ctypesリファレンス,,ctypes チュートリアル,ctypes --- Python 用の外部関数ライブラリ
@anchor{library/ctypes ctypes-ctypes-reference}@anchor{331e}@anchor{library/ctypes ctypes-reference}@anchor{331f}
@subsubsection ctypesリファレンス


@menu
* 共有ライブラリを見つける:: 
* Listing loaded shared libraries:: 
* 共有ライブラリをロードする:: 
* 外部関数:: 
* 関数プロトタイプ:: 
* ユーティリティー関数:: 
* データ型: データ型<3>. 
* 基本データ型: 基本データ型<2>. 
* 構造化データ型:: 
* 配列とポインタ:: 
* 例外: 例外<10>. 

@end menu

@node 共有ライブラリを見つける,Listing loaded shared libraries,,ctypesリファレンス
@anchor{library/ctypes ctypes-finding-shared-libraries}@anchor{3320}@anchor{library/ctypes finding-shared-libraries}@anchor{3321}
@subsubsection 共有ライブラリを見つける


コンパイルされる言語でプログラミングしている場合、共有ライブラリはプログラムをコンパイル/リンクしているときと、そのプログラムが動作しているときにアクセスされます。

The purpose of the @ref{f45,,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.

The @code{ctypes.util} module provides a function which can help to determine
the library to load.


@deffn {データ} ctypes.util.find_library (name)

ライブラリを見つけてパス名を返そうと試みます。 `name' は @code{lib} のような接頭辞、 @code{.so}, @code{.dylib} のような接尾辞、あるいは、バージョン番号が何も付いていないライブラリの名前です (これは posix リンカのオプション @code{-l} に使われている形式です)。
ライブラリが見つからないときは @code{None} を返します。
@end deffn

厳密な機能はシステムに依存します。

On Linux, @ref{f45,,find_library()} tries to run external programs
(@code{/sbin/ldconfig}, @code{gcc}, @code{objdump} and @code{ld}) to find the library file.
It returns the filename of the library file.

Note that if the output of these programs does not correspond to the dynamic
linker used by Python, the result of this function may be misleading.


バージョン 3.6 で変更: Linux では、ライブラリを検索する際に、他の方法でライブラリが見つけられない場合は、 @code{LD_LIBRARY_PATH} 環境変数の値が使われます


ここに例があります:

@example
>>> from ctypes.util import find_library
>>> find_library("m")
'libm.so.6'
>>> find_library("c")
'libc.so.6'
>>> find_library("bz2")
'libbz2.so.1.0'
>>>
@end example

On macOS and Android, @ref{f45,,find_library()} uses the system's
standard naming schemes and paths to locate the library, and returns a full
pathname if successful:

@example
>>> from ctypes.util import find_library
>>> find_library("c")
'/usr/lib/libc.dylib'
>>> find_library("m")
'/usr/lib/libm.dylib'
>>> find_library("bz2")
'/usr/lib/libbz2.dylib'
>>> find_library("AGL")
'/System/Library/Frameworks/AGL.framework/AGL'
>>>
@end example

On Windows, @ref{f45,,find_library()} searches along the system search path, and
returns the full pathname, but since there is no predefined naming scheme a call
like @code{find_library("c")} will fail and return @code{None}.

If wrapping a shared library with @code{ctypes}, it `may' be better to determine
the shared library name at development time, and hardcode that into the wrapper
module instead of using @ref{f45,,find_library()} to locate the library at runtime.

@node Listing loaded shared libraries,共有ライブラリをロードする,共有ライブラリを見つける,ctypesリファレンス
@anchor{library/ctypes ctypes-listing-loaded-shared-libraries}@anchor{3322}@anchor{library/ctypes listing-loaded-shared-libraries}@anchor{3323}
@subsubsection Listing loaded shared libraries


When writing code that relies on code loaded from shared libraries, it can be
useful to know which shared libraries have already been loaded into the current
process.

The @code{ctypes.util} module provides the @ref{1f0,,dllist()} function,
which calls the different APIs provided by the various platforms to help determine
which shared libraries have already been loaded into the current process.

The exact output of this function will be system dependent. On most platforms,
the first entry of this list represents the current process itself, which may
be an empty string.
For example, on glibc-based Linux, the return may look like:

@example
>>> from ctypes.util import dllist
>>> dllist()
['@w{'}, 'linux-vdso.so.1', '/lib/x86_64-linux-gnu/libm.so.6', '/lib/x86_64-linux-gnu/libc.so.6', ... ]
@end example

@node 共有ライブラリをロードする,外部関数,Listing loaded shared libraries,ctypesリファレンス
@anchor{library/ctypes ctypes-loading-shared-libraries}@anchor{3324}@anchor{library/ctypes loading-shared-libraries}@anchor{3325}
@subsubsection 共有ライブラリをロードする


共有ライブラリを Python プロセスへロードする方法はいくつかあります。一つの方法は下記のクラスの一つをインスタンス化することです:

@geindex CDLL (ctypes のクラス)
@anchor{library/ctypes ctypes CDLL}@anchor{bdc}
@deffn {クラス} ctypes.CDLL (name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

このクラスのインスタンスはロードされた共有ライブラリをあらわします。これらのライブラリの関数は標準 C 呼び出し規約を使用し、 int を返すと仮定されます。

On Windows creating a @ref{bdc,,CDLL} instance may fail even if the DLL name
exists. When a dependent DLL of the loaded DLL is not found, a
@ref{2c0,,OSError} error is raised with the message `"[WinError 126] The
specified module could not be found".' This error message does not contain
the name of the missing DLL because the Windows API does not return this
information making this error hard to diagnose. To resolve this error and
determine which DLL is not found, you need to find the list of dependent
DLLs and determine which one is not found using Windows debugging and
tracing tools.


バージョン 3.12 で変更: The `name' parameter can now be a @ref{5a1,,path-like object}.

@end deffn


@subsubheading 参考


Microsoft DUMPBIN tool@footnote{https://docs.microsoft.com/cpp/build/reference/dependents}
-- A tool to find DLL dependents.


@geindex OleDLL (ctypes のクラス)
@anchor{library/ctypes ctypes OleDLL}@anchor{1ae2}
@deffn {クラス} ctypes.OleDLL (name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

Instances of this class represent loaded shared libraries,
functions in these libraries use the @code{stdcall} calling convention, and are
assumed to return the windows specific @ref{3326,,HRESULT} code.  @ref{3326,,HRESULT}
values contain information specifying whether the function call failed or
succeeded, together with additional error code.  If the return value signals a
failure, an @ref{2c0,,OSError} is automatically raised.

@ref{213f,,Availability}: Windows


バージョン 3.3 で変更: @ref{1260,,WindowsError} used to be raised,
which is now an alias of @ref{2c0,,OSError}.



バージョン 3.12 で変更: The `name' parameter can now be a @ref{5a1,,path-like object}.

@end deffn

@geindex WinDLL (ctypes のクラス)
@anchor{library/ctypes ctypes WinDLL}@anchor{1ae3}
@deffn {クラス} ctypes.WinDLL (name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

Instances of this class represent loaded shared libraries,
functions in these libraries use the @code{stdcall} calling convention, and are
assumed to return int by default.

@ref{213f,,Availability}: Windows


バージョン 3.12 で変更: The `name' parameter can now be a @ref{5a1,,path-like object}.

@end deffn

これらのライブラリがエクスポートするどの関数でも呼び出す前に Python @ref{474,,global interpreter lock} は解放され、後でまた獲得されます。

@geindex PyDLL (ctypes のクラス)
@anchor{library/ctypes ctypes PyDLL}@anchor{1ae4}
@deffn {クラス} ctypes.PyDLL (name, mode=DEFAULT_MODE, handle=None)

Python GIL が関数呼び出しの間解放 `されず' 、関数実行の後に Python エラーフラグがチェックされるということを除けば、このクラスのインスタンスは @ref{bdc,,CDLL} インスタンスのように振る舞います。エラーフラグがセットされた場合、 Python 例外が送出されます。

要するに、これは Python C api 関数を直接呼び出すのに便利だというだけです。


バージョン 3.12 で変更: The `name' parameter can now be a @ref{5a1,,path-like object}.

@end deffn

All these classes can be instantiated by calling them with at least one
argument, the pathname of the shared library.  If you have an existing handle to
an already loaded shared library, it can be passed as the @code{handle} named
parameter, otherwise the underlying platform's @code{dlopen()} or
@code{LoadLibrary()} function is used to load the library into
the process, and to get a handle to it.

`mode' パラメータを使うと、ライブラリがどうやってロードされたかを特定できます。
詳細は @code{dlopen(3)@footnote{https://manpages.debian.org/dlopen(3)}} マニュアルページを参考にしてください。
Windows では `mode' は無視されます。
POSIX システムでは RTLD_NOW が常に追加され、設定変更はできません。

The `use_errno' parameter, when set to true, enables a ctypes mechanism that
allows accessing the system @ref{5b,,errno} error number in a safe way.
@code{ctypes} maintains a thread-local copy of the system's @ref{5b,,errno}
variable; if you call foreign functions created with @code{use_errno=True} then the
@ref{5b,,errno} value before the function call is swapped with the ctypes private
copy, the same happens immediately after the function call.

@ref{3327,,ctypes.get_errno()} 関数は ctypes のプライベートコピーの値を返します。そして、 @ref{3328,,ctypes.set_errno()} 関数は ctypes のプライベートコピーを置き換え、以前の値を返します。

The `use_last_error' parameter, when set to true, enables the same mechanism for
the Windows error code which is managed by the @ref{32fa,,GetLastError()} and
@code{SetLastError()} Windows API functions; @ref{3329,,ctypes.get_last_error()} and
@ref{332a,,ctypes.set_last_error()} are used to request and change the ctypes private
copy of the windows error code.

The `winmode' parameter is used on Windows to specify how the library is loaded
(since `mode' is ignored). It takes any value that is valid for the Win32 API
@code{LoadLibraryEx} flags parameter. When omitted, the default is to use the
flags that result in the most secure DLL load, which avoids issues such as DLL
hijacking. Passing the full path to the DLL is the safest way to ensure the
correct library and dependencies are loaded.


バージョン 3.8 で変更: `winmode' 引数が追加されました。



@deffn {データ} ctypes.RTLD_GLOBAL

`mode' パラメータとして使うフラグ。このフラグが利用できないプラットフォームでは、整数のゼロと定義されています。
@end deffn


@deffn {データ} ctypes.RTLD_LOCAL

`mode' パラメータとして使うフラグ。これが利用できないプラットフォームでは、 `RTLD_GLOBAL' と同様です。
@end deffn


@deffn {データ} ctypes.DEFAULT_MODE

共有ライブラリをロードするために使われるデフォルトモード。 OSX 10.3 では `RTLD_GLOBAL' であり、そうでなければ `RTLD_LOCAL' と同じです。
@end deffn

これらのクラスのインスタンスには公開メソッドはありません。
共有ライブラリからエクスポートされた関数は、属性として、もしくは添字でアクセスできます。
属性を通した関数へのアクセスは結果がキャッシュされ、従って繰り返しアクセスされると毎回同じオブジェクトを返すことに注意してください。
それとは反対に、添字を通したアクセスは毎回新しいオブジェクトを返します:

@example
>>> from ctypes import CDLL
>>> libc = CDLL("libc.so.6")  # On Linux
>>> libc.time == libc.time
True
>>> libc['time'] == libc['time']
False
@end example

次に述べる公開属性が利用できます。それらの名前はエクスポートされた関数名に衝突しないように下線で始まります。:

@geindex _handle (ctypes.PyDLL の属性)
@anchor{library/ctypes ctypes PyDLL _handle}@anchor{332b}
@deffn {の属性} PyDLL._handle

ライブラリへのアクセスに用いられるシステムハンドル。
@end deffn

@geindex _name (ctypes.PyDLL の属性)
@anchor{library/ctypes ctypes PyDLL _name}@anchor{332c}
@deffn {の属性} PyDLL._name

コンストラクタに渡されたライブラリの名前。
@end deffn

Shared libraries can also be loaded by using one of the prefabricated objects,
which are instances of the @ref{332d,,LibraryLoader} class, either by calling the
@ref{32d3,,LoadLibrary()} method, or by retrieving the library as
attribute of the loader instance.

@geindex LibraryLoader (ctypes のクラス)
@anchor{library/ctypes ctypes LibraryLoader}@anchor{332d}
@deffn {クラス} ctypes.LibraryLoader (dlltype)

共有ライブラリをロードするクラス。 `dlltype' は @ref{bdc,,CDLL} 、 @ref{1ae4,,PyDLL} 、 @ref{1ae3,,WinDLL} もしくは @ref{1ae2,,OleDLL} 型の一つであるべきです。

@code{__getattr__()} has special behavior: It allows loading a shared library by
accessing it as attribute of a library loader instance.  The result is cached,
so repeated attribute accesses return the same library each time.

@geindex LoadLibrary() (ctypes.LibraryLoader のメソッド)
@anchor{library/ctypes ctypes LibraryLoader LoadLibrary}@anchor{32d3}
@deffn {メソッド} LoadLibrary (name)

共有ライブラリをプロセスへロードし、それを返します。このメソッドはライブラリの新しいインスタンスを常に返します。
@end deffn
@end deffn

これらの前もって作られたライブラリローダーを利用することができます。:


@deffn {データ} ctypes.cdll

@ref{bdc,,CDLL} インスタンスを作ります。
@end deffn


@deffn {データ} ctypes.windll

Creates @ref{1ae3,,WinDLL} instances.

@ref{213f,,Availability}: Windows
@end deffn


@deffn {データ} ctypes.oledll

Creates @ref{1ae2,,OleDLL} instances.

@ref{213f,,Availability}: Windows
@end deffn


@deffn {データ} ctypes.pydll

@ref{1ae4,,PyDLL} インスタンスを作ります。
@end deffn

C Python api に直接アクセスするために、すぐに使用できる Python 共有ライブラリオブジェクトが次のように用意されています。


@deffn {データ} ctypes.pythonapi

An instance of @ref{1ae4,,PyDLL} that exposes Python C API functions as
attributes.  Note that all these functions are assumed to return C
int, which is of course not always the truth, so you have to assign
the correct @code{restype} attribute to use these functions.
@end deffn


Loading a library through any of these objects raises an
@ref{1c6e,,auditing event} @code{ctypes.dlopen} with string argument
@code{name}, the name used to load the library.



Accessing a function on a loaded library raises an auditing event
@code{ctypes.dlsym} with arguments @code{library} (the library object) and @code{name}
(the symbol's name as a string or integer).



In cases when only the library handle is available rather than the object,
accessing a function raises an auditing event @code{ctypes.dlsym/handle} with
arguments @code{handle} (the raw library handle) and @code{name}.


@node 外部関数,関数プロトタイプ,共有ライブラリをロードする,ctypesリファレンス
@anchor{library/ctypes ctypes-foreign-functions}@anchor{332e}@anchor{library/ctypes foreign-functions}@anchor{332f}
@subsubsection 外部関数


As explained in the previous section, foreign functions can be accessed as
attributes of loaded shared libraries.  The function objects created in this way
by default accept any number of arguments, accept any ctypes data instances as
arguments, and return the default result type specified by the library loader.

They are instances of a private local class @code{_FuncPtr} (not exposed
in @code{ctypes}) which inherits from the private @ref{18d2,,_CFuncPtr} class:

@example
>>> import ctypes
>>> lib = ctypes.CDLL(None)
>>> issubclass(lib._FuncPtr, ctypes._CFuncPtr)
True
>>> lib._FuncPtr is ctypes._CFuncPtr
False
@end example

@geindex _CFuncPtr (ctypes のクラス)
@anchor{library/ctypes ctypes _CFuncPtr}@anchor{18d2}
@deffn {クラス} ctypes._CFuncPtr

C の呼び出し可能外部関数のためのベースクラス。

外部関数のインスタンスも C 互換データ型です。それらは C の関数ポインタを表しています。

この振る舞いは外部関数オブジェクトの特別な属性に代入することによって、カスタマイズすることができます。

@geindex restype (ctypes._CFuncPtr の属性)
@anchor{library/ctypes ctypes _CFuncPtr restype}@anchor{32f9}
@deffn {の属性} restype

外部関数の結果の型を指定するために ctypes 型を代入する。何も返さない関数を表す void に対しては @code{None} を使います。

It is possible to assign a callable Python object that is not a ctypes
type, in this case the function is assumed to return a C int, and
the callable will be called with this integer, allowing further
processing or error checking.  Using this is deprecated, for more flexible
post processing or error checking use a ctypes data type as
@code{restype} and assign a callable to the @ref{32fb,,errcheck} attribute.
@end deffn

@geindex argtypes (ctypes._CFuncPtr の属性)
@anchor{library/ctypes ctypes _CFuncPtr argtypes}@anchor{17c1}
@deffn {の属性} argtypes

関数が受け取る引数の型を指定するために ctypes 型のタプルを代入します。@code{stdcall} 呼び出し規約を使う関数はこのタプルの長さと同じ数の引数で呼び出されます。C 呼び出し規約を使う関数は、追加の不特定の引数も取ります。

When a foreign function is called, each actual argument is passed to the
@ref{32f6,,from_param()} class method of the items in the @ref{17c1,,argtypes}
tuple, this method allows adapting the actual argument to an object that
the foreign function accepts.  For example, a @ref{1a57,,c_char_p} item in
the @ref{17c1,,argtypes} tuple will convert a string passed as argument into
a bytes object using ctypes conversion rules.

New: It is now possible to put items in argtypes which are not ctypes
types, but each item must have a @ref{32f6,,from_param()} method which returns a
value usable as argument (integer, string, ctypes instance).  This allows
defining adapters that can adapt custom objects as function parameters.
@end deffn

@geindex errcheck (ctypes._CFuncPtr の属性)
@anchor{library/ctypes ctypes _CFuncPtr errcheck}@anchor{32fb}
@deffn {の属性} errcheck

Python 関数または他の呼び出し可能オブジェクトをこの属性に代入します。呼び出し可能オブジェクトは三つ以上の引数とともに呼び出されます。


@deffn {の関数} callable (result, func, arguments)

`result' is what the foreign function returns, as specified by the
@code{restype} attribute.

`func' は外部関数オブジェクト自身で、これにより複数の関数の処理結果をチェックまたは後処理するために、同じ呼び出し可能オブジェクトを再利用できるようになります。

`arguments' は関数呼び出しに最初に渡されたパラメータが入ったタプルです。これにより使われた引数に基づいた特別な振る舞いをさせることができるようになります。
@end deffn

この関数が返すオブジェクトは外部関数呼び出しから返された値でしょう。しかし、戻り値をチェックして、外部関数呼び出しが失敗しているなら例外を送出させることもできます。
@end deffn
@end deffn


On Windows, when a foreign function call raises a system exception (for
example, due to an access violation), it will be captured and replaced with
a suitable Python exception. Further, an auditing event
@code{ctypes.set_exception} with argument @code{code} will be raised, allowing an
audit hook to replace the exception with its own.



Some ways to invoke foreign function calls as well as some of the
functions in this module may raise an auditing event
@code{ctypes.call_function} with arguments @code{function pointer} and @code{arguments}.


@node 関数プロトタイプ,ユーティリティー関数,外部関数,ctypesリファレンス
@anchor{library/ctypes ctypes-function-prototypes}@anchor{3330}@anchor{library/ctypes function-prototypes}@anchor{3331}
@subsubsection 関数プロトタイプ


外部関数は関数プロトタイプをインスタンス化することによって作成されます。
関数プロトタイプは C の関数プロトタイプと似ています。実装は定義せずに、関数 (返り値の型、引数の型、呼び出し規約) を記述します。
ファクトリ関数は、その関数に要求される返り値の型と引数の型とともに呼び出されます。そしてこの関数はデコレータファクトリとしても使え、 @code{@@wrapper} 構文で他の関数に適用できます。
例については @ref{3312,,コールバック関数} を参照してください。

@geindex CFUNCTYPE() (ctypes モジュール)
@anchor{library/ctypes ctypes CFUNCTYPE}@anchor{3313}
@deffn {の関数} ctypes.CFUNCTYPE (restype, *argtypes, use_errno=False, use_last_error=False)

返された関数プロトタイプは標準 C 呼び出し規約をつかう関数を作成します。関数は呼び出されている間 GIL を解放します。 `use_errno' が真に設定されれば、呼び出しの前後で System 変数 @ref{5b,,errno} の ctypesプライベートコピーは本当の @ref{5b,,errno} の値と交換されます。 `use_last_error' も Windows エラーコードに対するのと同様です。
@end deffn

@geindex WINFUNCTYPE() (ctypes モジュール)
@anchor{library/ctypes ctypes WINFUNCTYPE}@anchor{3314}
@deffn {の関数} ctypes.WINFUNCTYPE (restype, *argtypes, use_errno=False, use_last_error=False)

The returned function prototype creates functions that use the
@code{stdcall} calling convention.  The function will
release the GIL during the call.  `use_errno' and `use_last_error' have the
same meaning as above.

@ref{213f,,Availability}: Windows
@end deffn

@geindex PYFUNCTYPE() (ctypes モジュール)
@anchor{library/ctypes ctypes PYFUNCTYPE}@anchor{3332}
@deffn {の関数} ctypes.PYFUNCTYPE (restype, *argtypes)

返された関数プロトタイプは Python 呼び出し規約を使う関数を作成します。関数は呼び出されている間 GIL を解放 `しません'。
@end deffn

ファクトリ関数によって作られた関数プロトタイプは呼び出しのパラメータの型と数に依存した別の方法でインスタンス化することができます。 :


@deffn {の関数} prototype (address)

指定されたアドレス(整数でなくてはなりません)の外部関数を返します。
@end deffn


@deffn {の関数} prototype (callable)

Python の `callable' から C の呼び出し可能関数(コールバック関数) を作成します。
@end deffn


@deffn {の関数} prototype (func_spec[, paramflags])

共有ライブラリがエクスポートしている外部関数を返します。 `func_spec' は 2 要素タプル @code{(name_or_ordinal, library)} でなければなりません。第一要素はエクスポートされた関数の名前である文字列、またはエクスポートされた関数の序数である小さい整数です。第二要素は共有ライブラリインスタンスです。
@end deffn


@deffn {の関数} prototype (vtbl_index, name[, paramflags[, iid]])

COM メソッドを呼び出す外部関数を返します。 `vtbl_index' は仮想関数テーブルのインデックスで、非負の小さい整数です。 `name' は COM メソッドの名前です。 `iid' はオプションのインターフェイス識別子へのポインタで、拡張されたエラー情報の提供のために使われます。

If `iid' is not specified, an @ref{2c0,,OSError} is raised if the COM method
call fails. If `iid' is specified, a @ref{1e9,,COMError} is raised
instead.

COM methods use a special calling convention: They require a pointer to
the COM interface as first argument, in addition to those parameters that
are specified in the @code{argtypes} tuple.

@ref{213f,,Availability}: Windows
@end deffn

オプションの `paramflags' パラメータは上述した機能より多機能な外部関数ラッパーを作成します。

`paramflags' must be a tuple of the same length as @ref{17c1,,argtypes}.

このタプルの個々の要素はパラメータについてのより詳細な情報を持ち、 1 、 2 もしくは 3 要素を含むタプルでなければなりません。

第一要素はパラメータについてのフラグの組み合わせを含んだ整数です。

@quotation


@table @asis

@item 1

入力パラメータを関数に指定します。

@item 2

出力パラメータ。外部関数が値を書き込みます。

@item 4

デフォルトで整数ゼロになる入力パラメータ。
@end table
@end quotation

オプションの第二要素はパラメータ名の文字列です。これが指定された場合は、外部関数を名前付きパラメータで呼び出すことができます。

オプションの第三要素はこのパラメータのデフォルト値です。

The following example demonstrates how to wrap the Windows @code{MessageBoxW} function so
that it supports default parameters and named arguments. The C declaration from
the windows header file is this:

@example
WINUSERAPI int WINAPI
MessageBoxW(
    HWND hWnd,
    LPCWSTR lpText,
    LPCWSTR lpCaption,
    UINT uType);
@end example

Here is the wrapping with @code{ctypes}:

@example
>>> from ctypes import c_int, WINFUNCTYPE, windll
>>> from ctypes.wintypes import HWND, LPCWSTR, UINT
>>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
>>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
>>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)
@end example

これで外部関数の @code{MessageBox} を次のような方法で呼び出すことができるようになりました:

@example
>>> MessageBox()
>>> MessageBox(text="Spam, spam, spam")
>>> MessageBox(flags=2, text="foo bar")
@end example

二番目の例は出力パラメータについて説明します。 win32 の @code{GetWindowRect} 関数は、指定されたウィンドウの大きさを呼び出し側が与える @code{RECT} 構造体へコピーすることで取り出します。 C の宣言はこうです。:

@example
WINUSERAPI BOOL WINAPI
GetWindowRect(
     HWND hWnd,
     LPRECT lpRect);
@end example

Here is the wrapping with @code{ctypes}:

@example
>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
>>> from ctypes.wintypes import BOOL, HWND, RECT
>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
>>> paramflags = (1, "hwnd"), (2, "lprect")
>>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
>>>
@end example

出力パラメータを持つ関数は、単一のパラメータがある場合にはその出力パラメータ値を、複数のパラメータがある場合には出力パラメータ値が入ったタプルを、それぞれ自動的に返します。そのため、GetWindowRect 関数は呼び出されると RECT インスタンスを返します。

Output parameters can be combined with the @ref{32fb,,errcheck} protocol to do
further output processing and error checking.  The win32 @code{GetWindowRect} api
function returns a @code{BOOL} to signal success or failure, so this function could
do the error checking, and raises an exception when the api call failed:

@example
>>> def errcheck(result, func, args):
...     if not result:
...         raise WinError()
...     return args
...
>>> GetWindowRect.errcheck = errcheck
>>>
@end example

If the @ref{32fb,,errcheck} function returns the argument tuple it receives
unchanged, @code{ctypes} continues the normal processing it does on the output
parameters.  If you want to return a tuple of window coordinates instead of a
@code{RECT} instance, you can retrieve the fields in the function and return them
instead, the normal processing will no longer take place:

@example
>>> def errcheck(result, func, args):
...     if not result:
...         raise WinError()
...     rc = args[1]
...     return rc.left, rc.top, rc.bottom, rc.right
...
>>> GetWindowRect.errcheck = errcheck
>>>
@end example

@node ユーティリティー関数,データ型<3>,関数プロトタイプ,ctypesリファレンス
@anchor{library/ctypes ctypes-utility-functions}@anchor{3333}@anchor{library/ctypes utility-functions}@anchor{3334}
@subsubsection ユーティリティー関数


@geindex addressof() (ctypes モジュール)
@anchor{library/ctypes ctypes addressof}@anchor{3335}
@deffn {の関数} ctypes.addressof (obj)

メモリバッファのアドレスを示す整数を返します。 `obj' は ctypes 型のインスタンスでなければなりません。

引数 @code{obj} を指定して @ref{1c6e,,監査イベント} @code{ctypes.addressof} を送出します。
@end deffn

@geindex alignment() (ctypes モジュール)
@anchor{library/ctypes ctypes alignment}@anchor{3336}
@deffn {の関数} ctypes.alignment (obj_or_type)

ctypes 型のアライメントの必要条件を返します。 `obj_or_type' は ctypes 型またはインスタンスでなければなりません。
@end deffn

@geindex byref() (ctypes モジュール)
@anchor{library/ctypes ctypes byref}@anchor{32fe}
@deffn {の関数} ctypes.byref (obj[, offset])

`obj' (ctypes 型のインスタンスでなければならない) への軽量ポインタを返します。 `offset' はデフォルトでは 0 で、内部ポインターへ加算される整数です。

@code{byref(obj, offset)} は、 C コードとしては、以下のようにみなされます。:

@example
(((char *)&obj) + offset)
@end example

返されるオブジェクトは外部関数呼び出しのパラメータとしてのみ使用できます。@code{pointer(obj)} と似たふるまいをしますが、作成が非常に速く行えます。
@end deffn

@geindex CopyComPointer() (ctypes モジュール)
@anchor{library/ctypes ctypes CopyComPointer}@anchor{1ea}
@deffn {の関数} ctypes.CopyComPointer (src, dst)

Copies a COM pointer from `src' to `dst' and returns the Windows specific
@code{HRESULT} value.

If `src' is not @code{NULL}, its @code{AddRef} method is called, incrementing the
reference count.

In contrast, the reference count of `dst' will not be decremented before
assigning the new value. Unless `dst' is @code{NULL}, the caller is responsible
for decrementing the reference count by calling its @code{Release} method when
necessary.

@ref{213f,,Availability}: Windows


Added in version 3.14.

@end deffn

@geindex cast() (ctypes モジュール)
@anchor{library/ctypes ctypes cast}@anchor{330f}
@deffn {の関数} ctypes.cast (obj, type)

この関数は C のキャスト演算子に似ています。`obj' と同じメモリブロックを指している `type' の新しいインスタンスを返します。`type' はポインタ型でなければならず、`obj' はポインタとして解釈できるオブジェクトでなければなりません。
@end deffn

@geindex create_string_buffer() (ctypes モジュール)
@anchor{library/ctypes ctypes create_string_buffer}@anchor{32ed}
@deffn {の関数} ctypes.create_string_buffer (init, size=None)

@deffnx {の関数} ctypes.create_string_buffer (size)

この関数は変更可能な文字バッファを作成します。返されるオブジェクトは @ref{32db,,c_char} の ctypes 配列です。

If `size' is given (and not @code{None}), it must be an @ref{19b,,int}.
It specifies the size of the returned array.

If the `init' argument is given, it must be @ref{192,,bytes}. It is used
to initialize the array items. Bytes not initialized this way are
set to zero (NUL).

If `size' is not given (or if it is @code{None}), the buffer is made one element
larger than `init', effectively adding a NUL terminator.

If both arguments are given, `size' must not be less than @code{len(init)}.

@cartouche
@quotation 警告 
If `size' is equal to @code{len(init)}, a NUL terminator is
not added. Do not treat such a buffer as a C string.
@end quotation
@end cartouche

例えば:

@example
>>> bytes(create_string_buffer(2))
b'\x00\x00'
>>> bytes(create_string_buffer(b'ab'))
b'ab\x00'
>>> bytes(create_string_buffer(b'ab', 2))
b'ab'
>>> bytes(create_string_buffer(b'ab', 4))
b'ab\x00\x00'
>>> bytes(create_string_buffer(b'abcdef', 2))
Traceback (most recent call last):
   ...
ValueError: byte string too long
@end example

引数 @code{init}, @code{size} を指定して @ref{1c6e,,監査イベント} @code{ctypes.create_string_buffer} を送出します。
@end deffn

@geindex create_unicode_buffer() (ctypes モジュール)
@anchor{library/ctypes ctypes create_unicode_buffer}@anchor{1db4}
@deffn {の関数} ctypes.create_unicode_buffer (init, size=None)

@deffnx {の関数} ctypes.create_unicode_buffer (size)

この関数は変更可能な Unicode 文字バッファを作成します。返されるオブジェクトは @ref{32dc,,c_wchar} の ctypes 配列です。

The function takes the same arguments as @ref{32ed,,create_string_buffer()} except
`init' must be a string and `size' counts @ref{32dc,,c_wchar}.

引数 @code{init}, @code{size} を指定して @ref{1c6e,,監査イベント} @code{ctypes.create_unicode_buffer} を送出します。
@end deffn

@geindex DllCanUnloadNow() (ctypes モジュール)
@anchor{library/ctypes ctypes DllCanUnloadNow}@anchor{3337}
@deffn {の関数} ctypes.DllCanUnloadNow ()

This function is a hook which allows implementing in-process
COM servers with ctypes.  It is called from the DllCanUnloadNow function that
the _ctypes extension dll exports.

@ref{213f,,Availability}: Windows
@end deffn

@geindex DllGetClassObject() (ctypes モジュール)
@anchor{library/ctypes ctypes DllGetClassObject}@anchor{3338}
@deffn {の関数} ctypes.DllGetClassObject ()

This function is a hook which allows implementing in-process
COM servers with ctypes.  It is called from the DllGetClassObject function
that the @code{_ctypes} extension dll exports.

@ref{213f,,Availability}: Windows
@end deffn

@geindex find_library() (ctypes.util モジュール)
@anchor{library/ctypes ctypes util find_library}@anchor{f45}
@deffn {の関数} ctypes.util.find_library (name)

ライブラリを検索し、パス名を返します。 `name' は @code{lib} のような接頭辞、 @code{.so} や @code{.dylib} のような接尾辞、そして、バージョンナンバーを除くライブラリ名です (これは posix のリンカーオプション @code{-l} で使われる書式です) 。もしライブラリが見つからなければ、 @code{None} を返します。

厳密な機能はシステムに依存します。

See @ref{3320,,共有ライブラリを見つける} for complete documentation.
@end deffn

@geindex find_msvcrt() (ctypes.util モジュール)
@anchor{library/ctypes ctypes util find_msvcrt}@anchor{3339}
@deffn {の関数} ctypes.util.find_msvcrt ()

Returns the filename of the VC runtime library used by Python,
and by the extension modules.  If the name of the library cannot be
determined, @code{None} is returned.

もし、例えば拡張モジュールにより割り付けられたメモリを @code{free(void *)} で解放する必要があるなら、メモリ割り付けを行ったのと同じライブラリの関数を使うことが重要です。

@ref{213f,,Availability}: Windows
@end deffn

@geindex dllist() (ctypes.util モジュール)
@anchor{library/ctypes ctypes util dllist}@anchor{1f0}
@deffn {の関数} ctypes.util.dllist ()

Try to provide a list of paths of the shared libraries loaded into the current
process.  These paths are not normalized or processed in any way.  The function
can raise @ref{2c0,,OSError} if the underlying platform APIs fail.
The exact functionality is system dependent.

On most platforms, the first element of the list represents the current
executable file. It may be an empty string.

@ref{213f,,Availability}: Windows, macOS, iOS, glibc, BSD libc, musl


Added in version 3.14.

@end deffn

@geindex FormatError() (ctypes モジュール)
@anchor{library/ctypes ctypes FormatError}@anchor{333a}
@deffn {の関数} ctypes.FormatError ([code])

Returns a textual description of the error code `code'.  If no error code is
specified, the last error code is used by calling the Windows API function
@ref{32fa,,GetLastError()}.

@ref{213f,,Availability}: Windows
@end deffn

@geindex GetLastError() (ctypes モジュール)
@anchor{library/ctypes ctypes GetLastError}@anchor{32fa}
@deffn {の関数} ctypes.GetLastError ()

Returns the last error code set by Windows in the calling thread.
This function calls the Windows @code{GetLastError()} function directly,
it does not return the ctypes-private copy of the error code.

@ref{213f,,Availability}: Windows
@end deffn

@geindex get_errno() (ctypes モジュール)
@anchor{library/ctypes ctypes get_errno}@anchor{3327}
@deffn {の関数} ctypes.get_errno ()

システムの @ref{5b,,errno} 変数の、スレッドローカルなプライベートコピーを返します。

引数無しで @ref{1c6e,,監査イベント} @code{ctypes.get_errno} を送出します。
@end deffn

@geindex get_last_error() (ctypes モジュール)
@anchor{library/ctypes ctypes get_last_error}@anchor{3329}
@deffn {の関数} ctypes.get_last_error ()

Returns the current value of the ctypes-private copy of the system
@code{LastError} variable in the calling thread.

@ref{213f,,Availability}: Windows

引数無しで @ref{1c6e,,監査イベント} @code{ctypes.get_last_error} を送出します。
@end deffn

@geindex memmove() (ctypes モジュール)
@anchor{library/ctypes ctypes memmove}@anchor{333b}
@deffn {の関数} ctypes.memmove (dst, src, count)

標準 C の memmove ライブラリ関数と同じものです。: `count' バイトを `src' から `dst' へコピーします。 `dst' と `src' はポインタへ変換可能な整数または ctypes インスタンスでなければなりません。
@end deffn

@geindex memset() (ctypes モジュール)
@anchor{library/ctypes ctypes memset}@anchor{333c}
@deffn {の関数} ctypes.memset (dst, c, count)

標準 C の memset ライブラリ関数と同じものです。: アドレス `dst' のメモリブロックを値 `c' を `count' バイト分書き込みます。 `dst' はアドレスを指定する整数または ctypes インスタンスである必要があります。
@end deffn

@geindex POINTER() (ctypes モジュール)
@anchor{library/ctypes ctypes POINTER}@anchor{1f1}
@deffn {の関数} ctypes.POINTER (type, /)

Create or return a ctypes pointer type. Pointer types are cached and
reused internally, so calling this function repeatedly is cheap.
`type' must be a ctypes type.

`CPython 実装の詳細:' The resulting pointer type is cached in the @code{__pointer_type__}
attribute of `type'.
It is possible to set this attribute before the first call to
@code{POINTER} in order to set a custom pointer type.
However, doing this is discouraged: manually creating a suitable
pointer type is difficult without relying on implementation
details that may change in future Python versions.
@end deffn

@geindex pointer() (ctypes モジュール)
@anchor{library/ctypes ctypes pointer}@anchor{1a56}
@deffn {の関数} ctypes.pointer (obj, /)

Create a new pointer instance, pointing to `obj'.
The returned object is of the type @code{POINTER(type(obj))}.

注意: 外部関数呼び出しへオブジェクトへのポインタを渡したいだけなら、はるかに高速な @code{byref(obj)} を使うべきです。
@end deffn

@geindex resize() (ctypes モジュール)
@anchor{library/ctypes ctypes resize}@anchor{331d}
@deffn {の関数} ctypes.resize (obj, size)

この関数は `obj' の内部メモリバッファのサイズを変更します。 `obj' は ctypes 型のインスタンスでなければなりません。バッファを @code{sizeof(type(obj))} で与えられるオブジェクト型の本来のサイズより小さくすることはできませんが、バッファを拡大することはできます。
@end deffn

@geindex set_errno() (ctypes モジュール)
@anchor{library/ctypes ctypes set_errno}@anchor{3328}
@deffn {の関数} ctypes.set_errno (value)

システム変数 @ref{5b,,errno} の、呼び出し元スレッドでの ctypes のプライベートコピーの現在値を `value' に設定し、前の値を返します。

引数 @code{errno} を指定して @ref{1c6e,,監査イベント} @code{ctypes.set_errno} を送出します。
@end deffn

@geindex set_last_error() (ctypes モジュール)
@anchor{library/ctypes ctypes set_last_error}@anchor{332a}
@deffn {の関数} ctypes.set_last_error (value)

Sets the current value of the ctypes-private copy of the system
@code{LastError} variable in the calling thread to `value' and return the
previous value.

@ref{213f,,Availability}: Windows

引数 @code{error} を指定して @ref{1c6e,,監査イベント} @code{ctypes.set_last_error} を送出します。
@end deffn

@geindex sizeof() (ctypes モジュール)
@anchor{library/ctypes ctypes sizeof}@anchor{333d}
@deffn {の関数} ctypes.sizeof (obj_or_type)

ctypes の型やインスタンスのメモリバッファのサイズをバイト数で返します。C の @code{sizeof} 演算子と同様の動きをします。
@end deffn

@geindex string_at() (ctypes モジュール)
@anchor{library/ctypes ctypes string_at}@anchor{1ec}
@deffn {の関数} ctypes.string_at (ptr, size=-1)

Return the byte string at `void *ptr'.
If `size' is specified, it is used as size, otherwise the string is assumed
to be zero-terminated.

Raises an @ref{1c6e,,auditing event} @code{ctypes.string_at} with arguments @code{ptr}, @code{size}.
@end deffn

@geindex WinError() (ctypes モジュール)
@anchor{library/ctypes ctypes WinError}@anchor{333e}
@deffn {の関数} ctypes.WinError (code=None, descr=None)

Creates an instance of @ref{2c0,,OSError}.  If `code' is not specified,
@ref{32fa,,GetLastError()} is called to determine the error code. If `descr' is not
specified, @ref{333a,,FormatError()} is called to get a textual description of the
error.

@ref{213f,,Availability}: Windows


バージョン 3.3 で変更: An instance of @ref{1260,,WindowsError} used to be created, which is now an
alias of @ref{2c0,,OSError}.

@end deffn

@geindex wstring_at() (ctypes モジュール)
@anchor{library/ctypes ctypes wstring_at}@anchor{333f}
@deffn {の関数} ctypes.wstring_at (ptr, size=-1)

Return the wide-character string at `void *ptr'.
If `size' is specified, it is used as the number of
characters of the string, otherwise the string is assumed to be
zero-terminated.

Raises an @ref{1c6e,,auditing event} @code{ctypes.wstring_at} with arguments @code{ptr}, @code{size}.
@end deffn

@geindex memoryview_at() (ctypes モジュール)
@anchor{library/ctypes ctypes memoryview_at}@anchor{1eb}
@deffn {の関数} ctypes.memoryview_at (ptr, size, readonly=False)

Return a @ref{165,,memoryview} object of length `size' that references memory
starting at `void *ptr'.

If `readonly' is true, the returned @code{memoryview} object can
not be used to modify the underlying memory.
(Changes made by other means will still be reflected in the returned
object.)

This function is similar to @ref{1ec,,string_at()} with the key
difference of not making a copy of the specified memory.
It is a semantically equivalent (but more efficient) alternative to
@code{memoryview((c_byte * size).from_address(ptr))}.
(While @ref{3340,,from_address()} only takes integers, `ptr' can also
be given as a @ref{1f1,,ctypes.POINTER} or a @ref{32fe,,byref()} object.)

Raises an @ref{1c6e,,auditing event} @code{ctypes.memoryview_at} with arguments @code{address}, @code{size}, @code{readonly}.


Added in version 3.14.

@end deffn

@node データ型<3>,基本データ型<2>,ユーティリティー関数,ctypesリファレンス
@anchor{library/ctypes ctypes-data-types}@anchor{3341}@anchor{library/ctypes data-types}@anchor{3342}
@subsubsection データ型


@geindex _CData (ctypes のクラス)
@anchor{library/ctypes ctypes _CData}@anchor{3343}
@deffn {クラス} ctypes._CData

この非公開クラスはすべての ctypes データ型の共通のベースクラスです。他のことはさておき、すべての ctypes 型インスタンスは C 互換データを保持するメモリブロックを内部に持ちます。このメモリブロックのアドレスは @ref{3335,,addressof()} ヘルパー関数が返します。別のインスタンス変数が @ref{3344,,_objects} として公開されます。これはメモリブロックがポインタを含む場合に存続し続ける必要のある他の Python オブジェクトを含んでいます。

ctypes データ型の共通メソッド、すべてのクラスメソッドが存在します (正確には、 @ref{23d0,,メタクラス} のメソッドです):

@geindex from_buffer() (ctypes._CData のメソッド)
@anchor{library/ctypes ctypes _CData from_buffer}@anchor{3345}
@deffn {メソッド} from_buffer (source[, offset])

このメソッドは `source' オブジェクトのバッファを共有する ctypes のインスタンスを返します。 `source' オブジェクトは書き込み可能バッファインターフェースをサポートしている必要があります。オプションの `offset' 引数では `source' バッファのオフセットをバイト単位で指定します。デフォルトではゼロです。もし `source' バッファが十分に大きくなければ、 @ref{2ec,,ValueError} が送出されます。

引数 @code{pointer}, @code{size}, @code{offset} を指定して @ref{1c6e,,監査イベント} @code{ctypes.cdata/buffer} を送出します。
@end deffn

@geindex from_buffer_copy() (ctypes._CData のメソッド)
@anchor{library/ctypes ctypes _CData from_buffer_copy}@anchor{3346}
@deffn {メソッド} from_buffer_copy (source[, offset])

このメソッドは `source' オブジェクトの読み出し可能バッファをコピーすることで、ctypes のインスタンスを生成します。オプションの `offset' 引数では `source' バッファのオフセットをバイト単位で指定します。デフォルトではゼロです。もし `source' バッファが十分に大きくなければ、 @ref{2ec,,ValueError} が送出されます。

引数 @code{pointer}, @code{size}, @code{offset} を指定して @ref{1c6e,,監査イベント} @code{ctypes.cdata/buffer} を送出します。
@end deffn

@geindex from_address() (ctypes._CData のメソッド)
@anchor{library/ctypes ctypes _CData from_address}@anchor{3340}
@deffn {メソッド} from_address (address)

このメソッドは `address' で指定されたメモリを使って ctypes 型のインスタンスを返します。 `address' は整数でなければなりません。


This method, and others that indirectly call this method, raises an
@ref{1c6e,,auditing event} @code{ctypes.cdata} with argument
@code{address}.

@end deffn

@geindex from_param() (ctypes._CData のメソッド)
@anchor{library/ctypes ctypes _CData from_param}@anchor{32f6}
@deffn {メソッド} from_param (obj)

This method adapts `obj' to a ctypes type.  It is called with the actual
object used in a foreign function call when the type is present in the
foreign function's @ref{17c1,,argtypes} tuple;
it must return an object that can be used as a function call parameter.

すべての ctypes のデータ型は、それが型のインスタンスであれば、 `obj' を返すこのクラスメソッドのデフォルトの実装を持ちます。いくつかの型は、別のオブジェクトも受け付けます。
@end deffn

@geindex in_dll() (ctypes._CData のメソッド)
@anchor{library/ctypes ctypes _CData in_dll}@anchor{3317}
@deffn {メソッド} in_dll (library, name)

このメソッドは、共有ライブラリによってエクスポートされた ctypes 型のインスタンスを返します。 `name' はエクスポートされたデータの名前で、 `library' はロードされた共有ライブラリです。
@end deffn

Common class variables of ctypes data types:

@geindex __pointer_type__ (ctypes._CData の属性)
@anchor{library/ctypes ctypes _CData __pointer_type__}@anchor{1f2}
@deffn {の属性} __pointer_type__

The pointer type that was created by calling
@ref{1f1,,POINTER()} for corresponding ctypes data type. If a pointer type
was not yet created, the attribute is missing.


Added in version 3.14.

@end deffn

ctypes データ型共通のインスタンス変数:

@geindex _b_base_ (ctypes._CData の属性)
@anchor{library/ctypes ctypes _CData _b_base_}@anchor{3347}
@deffn {の属性} _b_base_

ctypes 型データのインスタンスは、それ自身のメモリブロックを持たず、基底オブジェクトのメモリブロックの一部を共有することがあります。 @ref{3347,,_b_base_} 読み出し専用属性は、メモリブロックを保持する ctypes の基底オブジェクトです。
@end deffn

@geindex _b_needsfree_ (ctypes._CData の属性)
@anchor{library/ctypes ctypes _CData _b_needsfree_}@anchor{3348}
@deffn {の属性} _b_needsfree_

この読み出し専用の変数は、 ctypes データインスタンスが、それ自身に割り当てられたメモリブロックを持つとき true になります。それ以外の場合は false になります。
@end deffn

@geindex _objects (ctypes._CData の属性)
@anchor{library/ctypes ctypes _CData _objects}@anchor{3344}
@deffn {の属性} _objects

このメンバは @code{None} 、または、メモリブロックの内容が正しく保つために、生存させておかなくてはならない Python オブジェクトを持つディクショナリです。このオブジェクトはデバッグでのみ使われます。決してディクショナリの内容を変更しないで下さい。
@end deffn
@end deffn

@node 基本データ型<2>,構造化データ型,データ型<3>,ctypesリファレンス
@anchor{library/ctypes ctypes-fundamental-data-types-2}@anchor{3349}@anchor{library/ctypes id1}@anchor{334a}
@subsubsection 基本データ型


@geindex _SimpleCData (ctypes のクラス)
@anchor{library/ctypes ctypes _SimpleCData}@anchor{334b}
@deffn {クラス} ctypes._SimpleCData

この非公開クラスは、全ての基本的な ctypes データ型の基底クラスです。これは基本的な ctypes データ型に共通の属性を持っているので、ここで触れておきます。 @ref{334b,,_SimpleCData} は @ref{3343,,_CData} の子クラスなので、そのメソッドと属性を継承しています。ポインタでないかポインタを含まない ctypes データ型は、現在は pickle 化できます。

インスタンスは一つだけ属性を持ちます:

@geindex value (ctypes._SimpleCData の属性)
@anchor{library/ctypes ctypes _SimpleCData value}@anchor{334c}
@deffn {の属性} value

この属性は、インスタンスの実際の値を持ちます。整数型とポインタ型に対しては整数型、文字型に対しては一文字のバイト列オブジェクト、文字へのポインタに対しては Python のバイト列オブジェクトもしくは文字列となります。

When the @code{value} attribute is retrieved from a ctypes instance, usually
a new object is returned each time.  @code{ctypes} does `not' implement
original object return, always a new object is constructed.  The same is
true for all other ctypes object instances.
@end deffn
@end deffn

Fundamental data types, when returned as foreign function call results, or, for
example, by retrieving structure field members or array items, are transparently
converted to native Python types.  In other words, if a foreign function has a
@ref{32f9,,restype} of @ref{1a57,,c_char_p}, you will always receive a Python bytes
object, `not' a @ref{1a57,,c_char_p} instance.

@c XXX above is false, it actually returns a Unicode string

Subclasses of fundamental data types do `not' inherit this behavior. So, if a
foreign functions @code{restype} is a subclass of @ref{1a59,,c_void_p}, you will
receive an instance of this subclass from the function call. Of course, you can
get the value of the pointer by accessing the @code{value} attribute.

これらが基本 ctypes データ型です:

@geindex c_byte (ctypes のクラス)
@anchor{library/ctypes ctypes c_byte}@anchor{1ae0}
@deffn {クラス} ctypes.c_byte

C の signed char データ型を表し、小整数として値を解釈します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。
@end deffn

@geindex c_char (ctypes のクラス)
@anchor{library/ctypes ctypes c_char}@anchor{32db}
@deffn {クラス} ctypes.c_char

C char データ型を表し、単一の文字として値を解釈します。コンストラクタはオプションの文字列初期化子を受け取り、その文字列の長さちょうど一文字である必要があります。
@end deffn

@geindex c_char_p (ctypes のクラス)
@anchor{library/ctypes ctypes c_char_p}@anchor{1a57}
@deffn {クラス} ctypes.c_char_p

C char* データ型を表し、ゼロ終端文字列へのポインタでなければなりません。バイナリデータを指す可能性のある一般的なポインタに対しては @code{POINTER(c_char)} を使わなければなりません。コンストラクタは整数のアドレスもしくはバイト列オブジェクトを受け取ります。
@end deffn

@geindex c_double (ctypes のクラス)
@anchor{library/ctypes ctypes c_double}@anchor{1cb8}
@deffn {クラス} ctypes.c_double

C double データ型を表します。コンストラクタはオプションの浮動小数点数初期化子を受け取ります。
@end deffn

@geindex c_longdouble (ctypes のクラス)
@anchor{library/ctypes ctypes c_longdouble}@anchor{1cb9}
@deffn {クラス} ctypes.c_longdouble

C long double データ型を表します。コンストラクタはオプションで浮動小数点数初期化子を受け取ります。 @code{sizeof(long double) == sizeof(double)} であるプラットフォームでは @ref{1cb8,,c_double} の別名です。
@end deffn

@geindex c_float (ctypes のクラス)
@anchor{library/ctypes ctypes c_float}@anchor{32ec}
@deffn {クラス} ctypes.c_float

C float データ型を表します。コンストラクタはオプションの浮動小数点数初期化子を受け取ります。
@end deffn

@geindex c_double_complex (ctypes のクラス)
@anchor{library/ctypes ctypes c_double_complex}@anchor{1ee}
@deffn {クラス} ctypes.c_double_complex

Represents the C double complex datatype, if available.  The
constructor accepts an optional @ref{197,,complex} initializer.


Added in version 3.14.

@end deffn

@geindex c_float_complex (ctypes のクラス)
@anchor{library/ctypes ctypes c_float_complex}@anchor{1ed}
@deffn {クラス} ctypes.c_float_complex

Represents the C float complex datatype, if available.  The
constructor accepts an optional @ref{197,,complex} initializer.


Added in version 3.14.

@end deffn

@geindex c_longdouble_complex (ctypes のクラス)
@anchor{library/ctypes ctypes c_longdouble_complex}@anchor{1ef}
@deffn {クラス} ctypes.c_longdouble_complex

Represents the C long double complex datatype, if available.  The
constructor accepts an optional @ref{197,,complex} initializer.


Added in version 3.14.

@end deffn

@geindex c_int (ctypes のクラス)
@anchor{library/ctypes ctypes c_int}@anchor{32cf}
@deffn {クラス} ctypes.c_int

C signed int データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。 @code{sizeof(int) == sizeof(long)} であるプラットフォームでは、 @ref{32d0,,c_long} の別名です。
@end deffn

@geindex c_int8 (ctypes のクラス)
@anchor{library/ctypes ctypes c_int8}@anchor{32df}
@deffn {クラス} ctypes.c_int8

Represents the C 8-bit signed int datatype.  It is an alias for
@ref{1ae0,,c_byte}.
@end deffn

@geindex c_int16 (ctypes のクラス)
@anchor{library/ctypes ctypes c_int16}@anchor{32e0}
@deffn {クラス} ctypes.c_int16

C 16-bit signed int データ型を表します。たいていは、 @ref{32dd,,c_short} の別名です。
@end deffn

@geindex c_int32 (ctypes のクラス)
@anchor{library/ctypes ctypes c_int32}@anchor{32e1}
@deffn {クラス} ctypes.c_int32

C 32-bit signed int データ型を表します。たいていは、 @ref{32cf,,c_int} の別名です。
@end deffn

@geindex c_int64 (ctypes のクラス)
@anchor{library/ctypes ctypes c_int64}@anchor{32e2}
@deffn {クラス} ctypes.c_int64

C 64-bit signed int データ型を表します。たいていは、 @ref{32e9,,c_longlong} の別名です。
@end deffn

@geindex c_long (ctypes のクラス)
@anchor{library/ctypes ctypes c_long}@anchor{32d0}
@deffn {クラス} ctypes.c_long

C signed long データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。
@end deffn

@geindex c_longlong (ctypes のクラス)
@anchor{library/ctypes ctypes c_longlong}@anchor{32e9}
@deffn {クラス} ctypes.c_longlong

C signed long long データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。
@end deffn

@geindex c_short (ctypes のクラス)
@anchor{library/ctypes ctypes c_short}@anchor{32dd}
@deffn {クラス} ctypes.c_short

C signed short データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。
@end deffn

@geindex c_size_t (ctypes のクラス)
@anchor{library/ctypes ctypes c_size_t}@anchor{32eb}
@deffn {クラス} ctypes.c_size_t

C @code{size_t} データ型を表します。
@end deffn

@geindex c_ssize_t (ctypes のクラス)
@anchor{library/ctypes ctypes c_ssize_t}@anchor{1454}
@deffn {クラス} ctypes.c_ssize_t

C @code{ssize_t} データ型を表します。


Added in version 3.2.

@end deffn

@geindex c_time_t (ctypes のクラス)
@anchor{library/ctypes ctypes c_time_t}@anchor{1b63}
@deffn {クラス} ctypes.c_time_t

Represents the C @code{time_t} datatype.


Added in version 3.12.

@end deffn

@geindex c_ubyte (ctypes のクラス)
@anchor{library/ctypes ctypes c_ubyte}@anchor{1ae1}
@deffn {クラス} ctypes.c_ubyte

C の unsigned char データ型を表し、小さな整数として値を解釈します。コンストラクタはオプションの整数初期化子を受け取ります; オーバーフローのチェックは行われません。
@end deffn

@geindex c_uint (ctypes のクラス)
@anchor{library/ctypes ctypes c_uint}@anchor{32e3}
@deffn {クラス} ctypes.c_uint

C の  unsigned int データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります; オーバーフローのチェックは行われません。これは、 @code{sizeof(int) == sizeof(long)} であるプラットフォームでは @ref{32e8,,c_ulong} の別名です。
@end deffn

@geindex c_uint8 (ctypes のクラス)
@anchor{library/ctypes ctypes c_uint8}@anchor{32e4}
@deffn {クラス} ctypes.c_uint8

Represents the C 8-bit unsigned int datatype.  It is an alias for
@ref{1ae1,,c_ubyte}.
@end deffn

@geindex c_uint16 (ctypes のクラス)
@anchor{library/ctypes ctypes c_uint16}@anchor{32e5}
@deffn {クラス} ctypes.c_uint16

C 16-bit unsigned int データ型を表します。たいていは、 @ref{32de,,c_ushort} の別名です。
@end deffn

@geindex c_uint32 (ctypes のクラス)
@anchor{library/ctypes ctypes c_uint32}@anchor{32e6}
@deffn {クラス} ctypes.c_uint32

C 32-bit unsigned int データ型を表します。たいていは、 @ref{32e3,,c_uint} の別名です。
@end deffn

@geindex c_uint64 (ctypes のクラス)
@anchor{library/ctypes ctypes c_uint64}@anchor{32e7}
@deffn {クラス} ctypes.c_uint64

C 64-bit unsigned int データ型を表します。たいていは、 @ref{32ea,,c_ulonglong} の別名です。
@end deffn

@geindex c_ulong (ctypes のクラス)
@anchor{library/ctypes ctypes c_ulong}@anchor{32e8}
@deffn {クラス} ctypes.c_ulong

C unsigned long データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。
@end deffn

@geindex c_ulonglong (ctypes のクラス)
@anchor{library/ctypes ctypes c_ulonglong}@anchor{32ea}
@deffn {クラス} ctypes.c_ulonglong

C unsigned long long データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。
@end deffn

@geindex c_ushort (ctypes のクラス)
@anchor{library/ctypes ctypes c_ushort}@anchor{32de}
@deffn {クラス} ctypes.c_ushort

C unsigned short データ型を表します。コンストラクタはオプションの整数初期化子を受け取ります。オーバーフローのチェックは行われません。
@end deffn

@geindex c_void_p (ctypes のクラス)
@anchor{library/ctypes ctypes c_void_p}@anchor{1a59}
@deffn {クラス} ctypes.c_void_p

C void* データ型を表します。値は整数として表されます。コンストラクタはオプションの整数初期化子を受け取ります。
@end deffn

@geindex c_wchar (ctypes のクラス)
@anchor{library/ctypes ctypes c_wchar}@anchor{32dc}
@deffn {クラス} ctypes.c_wchar

C @code{wchar_t} データ型を表し、値は Unicode 文字列の単一の文字として解釈されます。コンストラクタはオプションの文字列初期化子を受け取り、その文字列の長さはちょうど一文字である必要があります。
@end deffn

@geindex c_wchar_p (ctypes のクラス)
@anchor{library/ctypes ctypes c_wchar_p}@anchor{1a58}
@deffn {クラス} ctypes.c_wchar_p

C wchar_t* データ型を表し、ゼロ終端ワイド文字列へのポインタでなければなりません。コンストラクタは整数のアドレスもしくは文字列を受け取ります。
@end deffn

@geindex c_bool (ctypes のクラス)
@anchor{library/ctypes ctypes c_bool}@anchor{32da}
@deffn {クラス} ctypes.c_bool

C の bool データ型 (より正確には、 C99 以降の  _Bool) を表します。 @code{True} または @code{False} の値を持ち、コンストラクタは真偽値と解釈できるオブジェクトを受け取ります。
@end deffn

@geindex HRESULT (ctypes のクラス)
@anchor{library/ctypes ctypes HRESULT}@anchor{3326}
@deffn {クラス} ctypes.HRESULT

Represents a @code{HRESULT} value, which contains success or
error information for a function or method call.

@ref{213f,,Availability}: Windows
@end deffn

@geindex py_object (ctypes のクラス)
@anchor{library/ctypes ctypes py_object}@anchor{1f3}
@deffn {クラス} ctypes.py_object

C @ref{5df,,PyObject}* データ型を表します。引数なしでこれを呼び出すと @code{NULL} @ref{5df,,PyObject}* ポインタを作成します。


バージョン 3.14 で変更: @code{py_object} is now a @ref{1a1,,generic type}.

@end deffn

The @code{ctypes.wintypes} module provides quite some other Windows specific
data types, for example @code{HWND}, @code{WPARAM}, or @code{DWORD}.
Some useful structures like @code{MSG} or @code{RECT} are also defined.

@node 構造化データ型,配列とポインタ,基本データ型<2>,ctypesリファレンス
@anchor{library/ctypes ctypes-structured-data-types}@anchor{334d}@anchor{library/ctypes structured-data-types}@anchor{334e}
@subsubsection 構造化データ型


@geindex Union (ctypes のクラス)
@anchor{library/ctypes ctypes Union}@anchor{1e6}
@deffn {クラス} ctypes.Union (*args, **kw)

ネイティブのバイトオーダーでの共用体のための抽象ベースクラス。

Unions share common attributes and behavior with structures;
see @ref{1e5,,Structure} documentation for details.
@end deffn

@geindex BigEndianUnion (ctypes のクラス)
@anchor{library/ctypes ctypes BigEndianUnion}@anchor{1bb7}
@deffn {クラス} ctypes.BigEndianUnion (*args, **kw)

`ビックエンディアン' バイトオーダーでの共用体のための抽象ベースクラス。


Added in version 3.11.

@end deffn

@geindex LittleEndianUnion (ctypes のクラス)
@anchor{library/ctypes ctypes LittleEndianUnion}@anchor{1bb8}
@deffn {クラス} ctypes.LittleEndianUnion (*args, **kw)

`リトルエンディアン' バイトオーダーでの共用体のための抽象ベースクラス。


Added in version 3.11.

@end deffn

@geindex BigEndianStructure (ctypes のクラス)
@anchor{library/ctypes ctypes BigEndianStructure}@anchor{3303}
@deffn {クラス} ctypes.BigEndianStructure (*args, **kw)

`ビックエンディアン' バイトオーダーでの構造体のための抽象ベースクラス。
@end deffn

@geindex LittleEndianStructure (ctypes のクラス)
@anchor{library/ctypes ctypes LittleEndianStructure}@anchor{3304}
@deffn {クラス} ctypes.LittleEndianStructure (*args, **kw)

`リトルエンディアン' バイトオーダーでの構造体のための抽象ベースクラス。
@end deffn

ネイティブではないバイトオーダーを持つ構造体および共用体にポインタ型フィールドあるいはポインタ型フィールドを含む他のどんなデータ型をも入れることはできません。

@geindex Structure (ctypes のクラス)
@anchor{library/ctypes ctypes Structure}@anchor{1e5}
@deffn {クラス} ctypes.Structure (*args, **kw)

`ネイティブ' のバイトオーダーでの構造体のための抽象ベースクラス。

Concrete structure and union types must be created by subclassing one of these
types, and at least define a @ref{1936,,_fields_} class variable. @code{ctypes} will
create @ref{1881,,descriptor}s which allow reading and writing the fields by direct
attribute accesses.  These are the

@geindex _fields_ (ctypes.Structure の属性)
@anchor{library/ctypes ctypes Structure _fields_}@anchor{1936}
@deffn {の属性} _fields_

構造体のフィールドを定義するシーケンス。要素は2要素タプルか3要素タプルでなければなりません。第一要素はフィールドの名前です。第二要素はフィールドの型を指定します。それはどんな ctypes データ型でも構いません。

@ref{32cf,,c_int} のような整数型のために、オプションの第三要素を与えることができます。フィールドのビット幅を定義する正の小整数である必要があります。

一つの構造体と共用体の中で、フィールド名はただ一つである必要があります。これはチェックされません。名前が繰り返しでてきたときにアクセスできるのは一つのフィールドだけです。

Structure サブクラスを定義するクラス文の `後で' 、 @ref{1936,,_fields_} クラス変数を定義することができます。これにより、次のように自身を直接または間接的に参照するデータ型を作成できるようになります:

@example
class List(Structure):
    pass
List._fields_ = [("pnext", POINTER(List)),
                 ...
                ]
@end example

The @code{_fields_} class variable can only be set once.
Later assignments will raise an @ref{5f0,,AttributeError}.

Additionally, the @code{_fields_} class variable must be defined before
the structure or union type is first used: an instance or subclass is
created, @ref{333d,,sizeof()} is called on it, and so on.
Later assignments to @code{_fields_} will raise an @ref{5f0,,AttributeError}.
If @code{_fields_} has not been set before such use,
the structure or union will have no own fields, as if @code{_fields_}
was empty.

Sub-subclasses of structure types inherit the fields of the base class
plus the @ref{1936,,_fields_} defined in the sub-subclass, if any.
@end deffn

@geindex _pack_ (ctypes.Structure の属性)
@anchor{library/ctypes ctypes Structure _pack_}@anchor{317}
@deffn {の属性} _pack_

An optional small integer that allows overriding the alignment of
structure fields in the instance.

This is only implemented for the MSVC-compatible memory layout
(see @ref{1e7,,_layout_}).

Setting @code{_pack_} to 0 is the same as not setting it at all.
Otherwise, the value must be a positive power of two.
The effect is equivalent to @code{#pragma pack(N)} in C, except
@code{ctypes} may allow larger `n' than what the compiler accepts.

@code{_pack_} must already be defined
when @ref{1936,,_fields_} is assigned, otherwise it will have no effect.


Deprecated since version 3.14, will be removed in version 3.19: For historical reasons, if @code{_pack_} is non-zero,
the MSVC-compatible layout will be used by default.
On non-Windows platforms, this default is deprecated and is slated to
become an error in Python 3.19.
If it is intended, set @ref{1e7,,_layout_} to @code{'ms'}
explicitly.

@end deffn

@geindex _align_ (ctypes.Structure の属性)
@anchor{library/ctypes ctypes Structure _align_}@anchor{4e8}
@deffn {の属性} _align_

An optional small integer that allows increasing the alignment of
the structure when being packed or unpacked to/from memory.

The value must not be negative.
The effect is equivalent to @code{__attribute__((aligned(N)))} on GCC
or @code{#pragma align(N)} on MSVC, except @code{ctypes} may allow
values that the compiler would reject.

@code{_align_} can only `increase' a structure's alignment
requirements. Setting it to 0 or 1 has no effect.

Using values that are not powers of two is discouraged and may lead to
surprising behavior.

@code{_align_} must already be defined
when @ref{1936,,_fields_} is assigned, otherwise it will have no effect.


Added in version 3.13.

@end deffn

@geindex _layout_ (ctypes.Structure の属性)
@anchor{library/ctypes ctypes Structure _layout_}@anchor{1e7}
@deffn {の属性} _layout_

An optional string naming the struct/union layout. It can currently
be set to:


@itemize -

@item 
@code{"ms"}: the layout used by the Microsoft compiler (MSVC).
On GCC and Clang, this layout can be selected with
@code{__attribute__((ms_struct))}.

@item 
@code{"gcc-sysv"}: the layout used by GCC with the System V or “SysV-like”
data model, as used on Linux and macOS.
With this layout, @ref{317,,_pack_} must be unset or zero.
@end itemize

If not set explicitly, @code{ctypes} will use a default that
matches the platform conventions. This default may change in future
Python releases (for example, when a new platform gains official support,
or when a difference between similar platforms is found).
Currently the default will be:


@itemize -

@item 
On Windows: @code{"ms"}

@item 
When @ref{317,,_pack_} is specified: @code{"ms"}.
(This is deprecated; see @ref{317,,_pack_} documentation.)

@item 
Otherwise: @code{"gcc-sysv"}
@end itemize

@code{_layout_} must already be defined when
@ref{1936,,_fields_} is assigned, otherwise it will have no effect.


Added in version 3.14.

@end deffn

@geindex _anonymous_ (ctypes.Structure の属性)
@anchor{library/ctypes ctypes Structure _anonymous_}@anchor{334f}
@deffn {の属性} _anonymous_

無名 (匿名) フィールドの名前が並べあげられたオプションのシーケンス。 @ref{1936,,_fields_} が代入されたとき、 @ref{334f,,_anonymous_} がすでに定義されていなければなりません。そうでなければ、何ら影響はありません。

The fields listed in this variable must be structure or union type fields.
@code{ctypes} will create descriptors in the structure type that allows
accessing the nested fields directly, without the need to create the
structure or union field.

型の例です (Windows):

@example
class _U(Union):
    _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                ("lpadesc", POINTER(ARRAYDESC)),
                ("hreftype", HREFTYPE)]

class TYPEDESC(Structure):
    _anonymous_ = ("u",)
    _fields_ = [("u", _U),
                ("vt", VARTYPE)]
@end example

@code{TYPEDESC} 構造体はCOMデータ型を表現しており、 @code{vt} フィールドは共用体フィールドのどれが有効であるかを指定します。 @code{u} フィールドは匿名フィールドとして定義されているため、 TYPEDESC インスタンスから取り除かれてそのメンバーへ直接アクセスできます。 @code{td.lptdesc} と @code{td.u.lptdesc} は同等ですが、前者がより高速です。なぜなら一時的な共用体インスタンスを作る必要がないためです。:

@example
td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)
@end example
@end deffn

構造体のサブクラスのサブクラスを定義することができ、基底クラスのフィールドを継承します。
サブクラス定義に別の @ref{1936,,_fields_} 変数がある場合は、この中で指定されたフィールドは基底クラスのフィールドへ追加されます。

構造体と共用体のコンストラクタは位置引数とキーワード引数の両方を受け取ります。位置引数は @ref{1936,,_fields_} の中に現れたのと同じ順番でメンバーフィールドを初期化するために使われます。コンストラクタのキーワード引数は属性代入として解釈され、そのため、同じ名前をもつ @ref{1936,,_fields_} を初期化するか、 @ref{1936,,_fields_} に存在しない名前に対しては新しい属性を作ります。
@end deffn

@geindex CField (ctypes のクラス)
@anchor{library/ctypes ctypes CField}@anchor{1e8}
@deffn {クラス} ctypes.CField (*args, **kw)

Descriptor for fields of a @ref{1e5,,Structure} and @ref{1e6,,Union}.
For example:

@example
>>> class Color(Structure):
...     _fields_ = (
...         ('red', c_uint8),
...         ('green', c_uint8),
...         ('blue', c_uint8),
...         ('intense', c_bool, 1),
...         ('blinking', c_bool, 1),
...    )
...
>>> Color.red
<ctypes.CField 'red' type=c_ubyte, ofs=0, size=1>
>>> Color.green.type
<class 'ctypes.c_ubyte'>
>>> Color.blue.byte_offset
2
>>> Color.intense
<ctypes.CField 'intense' type=c_bool, ofs=3, bit_size=1, bit_offset=0>
>>> Color.blinking.bit_offset
1
@end example

All attributes are read-only.

@code{CField} objects are created via @ref{1936,,_fields_};
do not instantiate the class directly.


Added in version 3.14: Previously, descriptors only had @code{offset} and @code{size} attributes
and a readable string representation; the @code{CField} class was not
available directly.


@geindex name (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField name}@anchor{3350}
@deffn {の属性} name

Name of the field, as a string.
@end deffn

@geindex type (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField type}@anchor{3351}
@deffn {の属性} type

Type of the field, as a @ref{3341,,ctypes class}.
@end deffn

@geindex offset (ctypes.CField の属性)
@geindex byte_offset (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField offset}@anchor{3352}
@deffn {の属性} offset
@anchor{library/ctypes ctypes CField byte_offset}@anchor{3353}
@deffnx {の属性} byte_offset

Offset of the field, in bytes.

For bitfields, this is the offset of the underlying byte-aligned
`storage unit'; see @ref{3354,,bit_offset}.
@end deffn

@geindex byte_size (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField byte_size}@anchor{3355}
@deffn {の属性} byte_size

Size of the field, in bytes.

For bitfields, this is the size of the underlying `storage unit'.
Typically, it has the same size as the bitfield's type.
@end deffn

@geindex size (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField size}@anchor{3356}
@deffn {の属性} size

For non-bitfields, equivalent to @ref{3355,,byte_size}.

For bitfields, this contains a backwards-compatible bit-packed
value that combines @ref{3357,,bit_size} and
@ref{3354,,bit_offset}.
Prefer using the explicit attributes instead.
@end deffn

@geindex is_bitfield (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField is_bitfield}@anchor{3358}
@deffn {の属性} is_bitfield

True if this is a bitfield.
@end deffn

@geindex bit_offset (ctypes.CField の属性)
@geindex bit_size (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField bit_offset}@anchor{3354}
@deffn {の属性} bit_offset
@anchor{library/ctypes ctypes CField bit_size}@anchor{3357}
@deffnx {の属性} bit_size

The location of a bitfield within its `storage unit', that is, within
@ref{3355,,byte_size} bytes of memory starting at
@ref{3353,,byte_offset}.

To get the field's value, read the storage unit as an integer,
@ref{24c9,,shift left} by @code{bit_offset} and
take the @code{bit_size} least significant bits.

For non-bitfields, @code{bit_offset} is zero
and @code{bit_size} is equal to @code{byte_size * 8}.
@end deffn

@geindex is_anonymous (ctypes.CField の属性)
@anchor{library/ctypes ctypes CField is_anonymous}@anchor{3359}
@deffn {の属性} is_anonymous

True if this field is anonymous, that is, it contains nested sub-fields
that should be merged into a containing structure or union.
@end deffn
@end deffn

@node 配列とポインタ,例外<10>,構造化データ型,ctypesリファレンス
@anchor{library/ctypes arrays-and-pointers}@anchor{335a}@anchor{library/ctypes ctypes-arrays-pointers}@anchor{335b}
@subsubsection 配列とポインタ


@geindex Array (ctypes のクラス)
@anchor{library/ctypes ctypes Array}@anchor{1e0c}
@deffn {クラス} ctypes.Array (*args)

配列のための抽象基底クラスです。

The recommended way to create concrete array types is by multiplying any
@code{ctypes} data type with a non-negative integer.  Alternatively, you can subclass
this type and define @ref{335c,,_length_} and @ref{335d,,_type_} class variables.
Array elements can be read and written using standard
subscript and slice accesses; for slice reads, the resulting object is
`not' itself an @ref{1e0c,,Array}.

@geindex _length_ (ctypes.Array の属性)
@anchor{library/ctypes ctypes Array _length_}@anchor{335c}
@deffn {の属性} _length_

配列の要素数を指定する正の整数。範囲外の添え字を指定すると、 @ref{174e,,IndexError} が送出されます。@ref{840,,len()} がこの整数を返します。
@end deffn

@geindex _type_ (ctypes.Array の属性)
@anchor{library/ctypes ctypes Array _type_}@anchor{335d}
@deffn {の属性} _type_

配列内の各要素の型を指定します。
@end deffn

配列のサブクラスのコンストラクタは、位置引数を受け付けて、配列を順番に初期化するために使用します。
@end deffn

@geindex ARRAY() (ctypes モジュール)
@anchor{library/ctypes ctypes ARRAY}@anchor{59e}
@deffn {の関数} ctypes.ARRAY (type, length)

Create an array.
Equivalent to @code{type * length}, where `type' is a
@code{ctypes} data type and `length' an integer.

This function is @ref{23d,,soft deprecated} in favor of multiplication.
There are no plans to remove it.
@end deffn

@geindex _Pointer (ctypes のクラス)
@anchor{library/ctypes ctypes _Pointer}@anchor{335e}
@deffn {クラス} ctypes._Pointer

ポインタのためのプライベートな抽象基底クラスです。

具象ポインタ型は、ポイント先の型を持つ @ref{1f1,,POINTER()} を呼び出すことで、作成できます。これは、 @ref{1a56,,pointer()} により自動的に行われます。

ポインタが配列を指す場合、その配列の要素は、標準の添え字とスライスによるアクセスを使用して読み書きが行えます。ポインタオブジェクトには、サイズがないため、 @ref{840,,len()} 関数は @ref{198,,TypeError} を送出します。負の添え字は、(C と同様に) ポインタの `前' のメモリから読み込み、範囲外の添え字はおそらく (幸運な場合でも) アクセス違反によりクラッシュを起こします。

@geindex _type_ (ctypes._Pointer の属性)
@anchor{library/ctypes ctypes _Pointer _type_}@anchor{1850}
@deffn {の属性} _type_

ポイント先の型を指定します。
@end deffn

@geindex contents (ctypes._Pointer の属性)
@anchor{library/ctypes ctypes _Pointer contents}@anchor{330a}
@deffn {の属性} contents

ポインタが指すオブジェクトを返します。この属性に割り当てると、ポインタが割り当てられたオブジェクトを指すようになります。
@end deffn
@end deffn

@node 例外<10>,,配列とポインタ,ctypesリファレンス
@anchor{library/ctypes ctypes-exceptions}@anchor{335f}@anchor{library/ctypes exceptions}@anchor{3360}
@subsubsection 例外


@geindex ArgumentError
@anchor{library/ctypes ctypes ArgumentError}@anchor{3361}
@deffn {例外} ctypes.ArgumentError

この例外は外部関数呼び出しが渡された引数を変換できなかったときに送出されます。
@end deffn

@geindex COMError
@anchor{library/ctypes ctypes COMError}@anchor{1e9}
@deffn {例外} ctypes.COMError (hresult, text, details)

This exception is raised when a COM method call failed.

@geindex hresult (ctypes.COMError の属性)
@anchor{library/ctypes ctypes COMError hresult}@anchor{3362}
@deffn {の属性} hresult

The integer value representing the error code.
@end deffn

@geindex text (ctypes.COMError の属性)
@anchor{library/ctypes ctypes COMError text}@anchor{3363}
@deffn {の属性} text

The error message.
@end deffn

@geindex details (ctypes.COMError の属性)
@anchor{library/ctypes ctypes COMError details}@anchor{3364}
@deffn {の属性} details

The 5-tuple @code{(descr, source, helpfile, helpcontext, progid)}.

`descr' is the textual description.  `source' is the language-dependent
@code{ProgID} for the class or application that raised the error.  `helpfile'
is the path of the help file.  `helpcontext' is the help context
identifier.  `progid' is the @code{ProgID} of the interface that defined the
error.
@end deffn

@ref{213f,,Availability}: Windows


Added in version 3.14.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node コマンドラインインターフェースライブラリ,並行実行,汎用オペレーティングシステムサービス,Python 標準ライブラリ
@anchor{library/cmdlinelibs doc}@anchor{3365}@anchor{library/cmdlinelibs cmdlinelibs}@anchor{3366}@anchor{library/cmdlinelibs command-line-interface-libraries}@anchor{3367}@anchor{library/cmdlinelibs translation-repo}@anchor{3368}
@section コマンドラインインターフェースライブラリ


この章で説明されているモジュールは、アプリケーション向けのコマンドラインやターミナルインターフェースの実装を支援します。

概要は以下のとおりです:

@menu
* argparse: argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー. コマンドラインオプションや引数、サブコマンド向けのパーサー
* optparse: optparse --- Parser for command line options. Parser for command line options
* getpass: getpass --- 可搬性のあるパスワード入力機構. 可搬性のあるパスワード入力機構
* fileinput: fileinput --- 複数の入力ストリームをまたいだ行を反復する. 複数の入力ストリームをまたいだ行を反復する
* curses: curses --- 文字セル表示のターミナル処理. 文字セル表示のターミナル処理
* curses.textpad: curses textpad --- Text input widget for curses programs. Text input widget for curses programs
* curses.ascii: curses ascii --- ASCII 文字のユーティリティー. ASCII 文字のユーティリティー
* curses.panel: curses panel --- curses のためのパネルスタック拡張. curses のためのパネルスタック拡張
* cmd: cmd --- 行指向のコマンドインタープリターのサポート. 行指向のコマンドインタープリターのサポート

@end menu

@node argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー,optparse --- Parser for command line options,,コマンドラインインターフェースライブラリ
@anchor{library/argparse doc}@anchor{3369}@anchor{library/argparse argparse-parser-for-command-line-options-arguments-and-subcommands}@anchor{336a}@anchor{library/argparse module-argparse}@anchor{7}
@subsection @code{argparse} --- コマンドラインオプションや引数、サブコマンド向けのパーサー


@geindex module; argparse


Added in version 3.2.


`ソースコード:' Lib/argparse.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/argparse.py}

@cartouche
@quotation 注釈 
While @code{argparse} is the default recommended standard library module
for implementing basic command line applications, authors with more
exacting requirements for exactly how their command line applications
behave may find it doesn't provide the necessary level of control.
Refer to @ref{336b,,Choosing an argument parsing library} for alternatives to
consider when @code{argparse} doesn't support behaviors that the application
requires (such as entirely disabling support for interspersed options and
positional arguments, or accepting option parameter values that start
with @code{-} even when they correspond to another defined option).
@end quotation
@end cartouche


__________________________________________________________________


@subsubheading チュートリアル



このページは API のリファレンス情報が記載しています。@ref{336c,,argparse チュートリアル} では、コマンドラインの解析についてより優しく説明しています。

The @code{argparse} module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments it requires, and @code{argparse}
will figure out how to parse those out of @ref{147c,,sys.argv}.  The @code{argparse}
module also automatically generates help and usage messages.  The module
will also issue errors when users give the program invalid arguments.

The @code{argparse} module's support for command-line interfaces is built
around an instance of @ref{1bd,,argparse.ArgumentParser}.  It is a container for
argument specifications and has options that apply to the parser as whole:

@example
parser = argparse.ArgumentParser(
                    prog='ProgramName',
                    description='What the program does',
                    epilog='Text at the bottom of help')
@end example

@ref{4bc,,ArgumentParser.add_argument()} メソッドは各引数の仕様をパーサーに付属させます。このメソッドは位置引数、値を受け取るオプション、機能のオン／オフを切り替えるフラグをサポートします:

@example
parser.add_argument('filename')           # 位置引数
parser.add_argument('-c', '--count')      # 値を取るオプション
parser.add_argument('-v', '--verbose',
                    action='store_true')  # オン／オフフラグ
@end example

@ref{336d,,ArgumentParser.parse_args()} メソッドはパーサーを実行し、抽出したデータを @ref{336e,,argparse.Namespace} オブジェクト内に配置します:

@example
args = parser.parse_args()
print(args.filename, args.count, args.verbose)
@end example

@cartouche
@quotation 注釈 
If you're looking for a guide about how to upgrade @ref{a4,,optparse} code
to @code{argparse}, see @ref{13c6,,Upgrading Optparse Code}.
@end quotation
@end cartouche

@menu
* ArgumentParser オブジェクト:: 
* add_argument() メソッド: add_argument メソッド. 
* parse_args() メソッド: parse_args メソッド. 
* その他のユーティリティ:: 
* 例外: 例外<11>. 

@end menu

@node ArgumentParser オブジェクト,add_argument メソッド,,argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー
@anchor{library/argparse argumentparser-objects}@anchor{336f}
@subsubsection ArgumentParser オブジェクト


@geindex ArgumentParser (argparse のクラス)
@anchor{library/argparse argparse ArgumentParser}@anchor{1bd}
@deffn {クラス} argparse.ArgumentParser (prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True, *, suggest_on_error=False, color=True)

新しい @ref{1bd,,ArgumentParser} オブジェクトを生成します。すべての引数はキーワード引数として渡すべきです。各引数についてはあとで詳しく説明しますが、簡単に言うと:


@itemize *

@item 
@ref{1bc,,prog} - The name of the program (default: generated from the @code{__main__}
module attributes and @code{sys.argv[0]})

@item 
@ref{3370,,usage} - プログラムの利用方法を記述する文字列 (デフォルト: パーサーに追加された引数から生成されます)

@item 
@ref{3371,,description} - 引数のヘルプの前に表示されるテキスト (デフォルトはテキストなしです)

@item 
@ref{3372,,epilog} - 引数のヘルプの後に表示されるテキスト (デフォルトはテキストなしです)

@item 
@ref{3373,,parents} - @ref{1bd,,ArgumentParser} オブジェクトのリストで、このオブジェクトの引数が追加されます

@item 
@ref{3374,,formatter_class} - ヘルプ出力をカスタマイズするためのクラス

@item 
@ref{3375,,prefix_chars} - オプションの引数の prefix になる文字集合 (デフォルト: '-')

@item 
@ref{3376,,fromfile_prefix_chars} - 追加の引数を読み込むファイルの prefix になる文字集合 (デフォルト: @code{None})

@item 
@ref{3377,,argument_default} - 引数のグローバルなデフォルト値 (デフォルト: @code{None})

@item 
@ref{3378,,conflict_handler} - 衝突するオプションを解決する方法 (通常は不要)

@item 
@ref{3379,,add_help} - @code{-h/--help} オプションをパーサーに追加する (デフォルト: @code{True})

@item 
@ref{fbe,,allow_abbrev} - Allows long options to be abbreviated if the
abbreviation is unambiguous (default: @code{True})

@item 
@ref{337a,,exit_on_error} - Determines whether or not @code{ArgumentParser} exits with
error info when an error occurs. (default: @code{True})

@item 
@ref{337b,,suggest_on_error} - Enables suggestions for mistyped argument choices
and subparser names (default: @code{False})

@item 
@ref{337c,,color} - Allow color output (default: @code{True})
@end itemize


バージョン 3.5 で変更: `allow_abbrev' 引数が追加されました。



バージョン 3.8 で変更: 以前のバージョンでは、 `allow_abbrev' は、@code{-vv} が @code{-v -v} と等価になるような、短いフラグのグループ化を無効にしていました。



バージョン 3.9 で変更: `exit_on_error' 引数が追加されました。



バージョン 3.14 で変更: `suggest_on_error' and `color' parameters were added.

@end deffn

以下の節では各オプションの利用方法を説明します。

@menu
* prog:: 
* usage:: 
* description:: 
* epilog:: 
* parents:: 
* formatter_class:: 
* prefix_chars:: 
* fromfile_prefix_chars:: 
* argument_default:: 
* allow_abbrev:: 
* conflict_handler:: 
* add_help:: 
* exit_on_error:: 
* suggest_on_error:: 
* color:: 

@end menu

@node prog,usage,,ArgumentParser オブジェクト
@anchor{library/argparse id1}@anchor{337d}@anchor{library/argparse prog}@anchor{1bc}
@subsubsection @code{prog}


By default, @ref{1bd,,ArgumentParser} calculates the name of the program
to display in help messages depending on the way the Python interpreter was run:


@itemize *

@item 
The @ref{2c48,,base name} of @code{sys.argv[0]} if a file was
passed as argument.

@item 
The Python interpreter name followed by @code{sys.argv[0]} if a directory or
a zipfile was passed as argument.

@item 
The Python interpreter name followed by @code{-m} followed by the
module or package name if the @ref{23c,,-m} option was used.
@end itemize

This default is almost always desirable because it will make the help messages
match the string that was used to invoke the program on the command line.
However, to change this default behavior, another value can be supplied using
the @code{prog=} argument to @ref{1bd,,ArgumentParser}:

@example
>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]

options:
 -h, --help  show this help message and exit
@end example

Note that the program name, whether determined from @code{sys.argv[0]},
from the @code{__main__} module attributes or from the
@code{prog=} argument, is available to help messages using the @code{%(prog)s} format
specifier.

@example
>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]

options:
 -h, --help  show this help message and exit
 --foo FOO   foo of the myprogram program
@end example


バージョン 3.14 で変更: The default @code{prog} value now reflects how @code{__main__} was actually executed,
rather than always being @code{os.path.basename(sys.argv[0])}.


@node usage,description,prog,ArgumentParser オブジェクト
@anchor{library/argparse usage}@anchor{3370}
@subsubsection usage


By default, @ref{1bd,,ArgumentParser} calculates the usage message from the
arguments it contains. The default message can be overridden with the
@code{usage=} keyword argument:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

options:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help
@end example

@code{%(prog)s} フォーマット指定子を、使用法メッセージ内でプログラム名として利用できます。

When a custom usage message is specified for the main parser, you may also want to
consider passing  the @code{prog} argument to @ref{e11,,add_subparsers()}
or the @code{prog} and the @code{usage} arguments to
@code{add_parser()}, to ensure consistent command prefixes and
usage information across subparsers.

@node description,epilog,usage,ArgumentParser オブジェクト
@anchor{library/argparse description}@anchor{3371}@anchor{library/argparse id2}@anchor{337e}
@subsubsection description


Most calls to the @ref{1bd,,ArgumentParser} constructor will use the
@code{description=} keyword argument.  This argument gives a brief description of
what the program does and how it works.  In help messages, the description is
displayed between the command-line usage string and the help messages for the
various arguments.

デフォルトでは、説明は与えられたスペースに合わせて折り返されます。この挙動を変更するには、@ref{3374,,formatter_class} 引数を参照してください。

@node epilog,parents,description,ArgumentParser オブジェクト
@anchor{library/argparse epilog}@anchor{3372}
@subsubsection epilog


いくつかのプログラムは、プログラムについての追加の説明を引数の説明の後に表示します。このテキストは @ref{1bd,,ArgumentParser} の @code{epilog=} 引数に指定できます:

@example
>>> parser = argparse.ArgumentParser(
...     description='A foo that bars',
...     epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

options:
 -h, --help  show this help message and exit

And that's how you'd foo a bar
@end example

@ref{3371,,description} 引数と同じく、@code{epilog=} テキストもデフォルトで折り返され、@ref{1bd,,ArgumentParser} の @ref{3374,,formatter_class} 引数で動作を調整できます。

@node parents,formatter_class,epilog,ArgumentParser オブジェクト
@anchor{library/argparse parents}@anchor{3373}
@subsubsection parents


ときどき、いくつかのパーサーが共通の引数セットを共有することがあります。それらの引数を繰り返し定義する代わりに、すべての共通引数を持ったパーサーを @ref{1bd,,ArgumentParser} の @code{parents=} 引数に渡すことができます。 @code{parents=} 引数は @ref{1bd,,ArgumentParser} オブジェクトのリストを受け取り、すべての位置アクションとオプションのアクションをそれらから集め、そのアクションを構築中の @ref{1bd,,ArgumentParser} オブジェクトに追加します:

@example
>>> parent_parser = argparse.ArgumentParser(add_help=False)
>>> parent_parser.add_argument('--parent', type=int)

>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> foo_parser.add_argument('foo')
>>> foo_parser.parse_args(['--parent', '2', 'XXX'])
Namespace(foo='XXX', parent=2)

>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> bar_parser.add_argument('--bar')
>>> bar_parser.parse_args(['--bar', 'YYY'])
Namespace(bar='YYY', parent=None)
@end example

一番親になるパーサーに @code{add_help=False} を指定していることに注目してください。こうしないと、@ref{1bd,,ArgumentParser} は2つの @code{-h/--help} オプションを与えられる (1つは親から、もうひとつは子から) ことになり、エラーを発生します。

@cartouche
@quotation 注釈 
@code{parents=} に渡す前にパーサーを完全に初期化する必要があります。子パーサーを作成してから親パーサーを変更した場合、その変更は子パーサーに反映されません。
@end quotation
@end cartouche

@node formatter_class,prefix_chars,parents,ArgumentParser オブジェクト
@anchor{library/argparse formatter-class}@anchor{3374}@anchor{library/argparse id3}@anchor{337f}
@subsubsection formatter_class


@ref{1bd,,ArgumentParser} オブジェクトは代わりのフォーマットクラスを指定することでヘルプのフォーマットをカスタマイズできます。現在、4つのフォーマットクラスがあります:

@geindex RawDescriptionHelpFormatter (argparse のクラス)
@geindex RawTextHelpFormatter (argparse のクラス)
@geindex ArgumentDefaultsHelpFormatter (argparse のクラス)
@geindex MetavarTypeHelpFormatter (argparse のクラス)
@anchor{library/argparse argparse RawDescriptionHelpFormatter}@anchor{3380}
@deffn {クラス} argparse.RawDescriptionHelpFormatter
@anchor{library/argparse argparse RawTextHelpFormatter}@anchor{3381}
@deffnx {クラス} argparse.RawTextHelpFormatter
@anchor{library/argparse argparse ArgumentDefaultsHelpFormatter}@anchor{1c50}
@deffnx {クラス} argparse.ArgumentDefaultsHelpFormatter
@anchor{library/argparse argparse MetavarTypeHelpFormatter}@anchor{3382}
@deffnx {クラス} argparse.MetavarTypeHelpFormatter
@end deffn

@ref{3380,,RawDescriptionHelpFormatter} と @ref{3381,,RawTextHelpFormatter} はどのようにテキストの説明を表示するかを指定できます。デフォルトでは @ref{1bd,,ArgumentParser} オブジェクトはコマンドラインヘルプの中の @ref{3371,,description} と @ref{3372,,epilog} を折り返して表示します:

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     description='@w{'}'this description
...         was indented weird
...             but that is okay'@w{'}',
...     epilog='@w{'}'
...             likewise for this epilog whose whitespace will
...         be cleaned up and whose words will be wrapped
...         across a couple lines'@w{'}')
>>> parser.print_help()
usage: PROG [-h]

this description was indented weird but that is okay

options:
 -h, --help  show this help message and exit

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
@end example

@code{formatter_class=} に @ref{3380,,RawDescriptionHelpFormatter} を渡した場合、 @ref{3371,,description} と @ref{3372,,epilog} は整形済みとされ改行されません:

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.RawDescriptionHelpFormatter,
...     description=textwrap.dedent('@w{'}'\
...         Please do not mess up this text!
...         --------------------------------
...             I have indented it
...             exactly the way
...             I want it
...         '@w{'}'))
>>> parser.print_help()
usage: PROG [-h]

Please do not mess up this text!
--------------------------------
   I have indented it
   exactly the way
   I want it

options:
 -h, --help  show this help message and exit
@end example

@ref{3381,,RawTextHelpFormatter} maintains whitespace for all sorts of help text,
including argument descriptions. However, multiple newlines are replaced with
one. If you wish to preserve multiple blank lines, add spaces between the
newlines.

@ref{1c50,,ArgumentDefaultsHelpFormatter} は各引数のデフォルト値を自動的にヘルプに追加します:

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
>>> parser.print_help()
usage: PROG [-h] [--foo FOO] [bar ...]

positional arguments:
 bar         BAR! (default: [1, 2, 3])

options:
 -h, --help  show this help message and exit
 --foo FOO   FOO! (default: 42)
@end example

@ref{3382,,MetavarTypeHelpFormatter} は、各引数の値の表示名に @ref{3383,,type} 引数の値を使用します (通常は @ref{3384,,dest} の値が使用されます):

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.MetavarTypeHelpFormatter)
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', type=float)
>>> parser.print_help()
usage: PROG [-h] [--foo int] float

positional arguments:
  float

options:
  -h, --help  show this help message and exit
  --foo int
@end example

@node prefix_chars,fromfile_prefix_chars,formatter_class,ArgumentParser オブジェクト
@anchor{library/argparse prefix-chars}@anchor{3375}
@subsubsection prefix_chars


Most command-line options will use @code{-} as the prefix, e.g. @code{-f/--foo}.
Parsers that need to support different or additional prefix
characters, e.g. for options
like @code{+f} or @code{/foo}, may specify them using the @code{prefix_chars=} argument
to the @ref{1bd,,ArgumentParser} constructor:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
>>> parser.add_argument('+f')
>>> parser.add_argument('++bar')
>>> parser.parse_args('+f X ++bar Y'.split())
Namespace(bar='Y', f='X')
@end example

@code{prefix_chars=} 引数のデフォルトは @code{'-'} です。@code{-} を含まない文字セットを指定すると、@code{-f/--foo} オプションが使用できなくなります。

@node fromfile_prefix_chars,argument_default,prefix_chars,ArgumentParser オブジェクト
@anchor{library/argparse fromfile-prefix-chars}@anchor{3376}
@subsubsection fromfile_prefix_chars


ときどき、非常に長い引数リストを扱う場合に、その引数リストを毎回コマンドラインにタイプする代わりにファイルに置いておきたい場合があります。@ref{1bd,,ArgumentParser} のコンストラクターに @code{fromfile_prefix_chars=} 引数が渡された場合、指定された文字のいずれかで始まる引数はファイルとして扱われ、そのファイルに含まれる引数リストに置換されます。例えば:

@example
>>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:
...     fp.write('-f\nbar')
...
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@@args.txt'])
Namespace(f='bar')
@end example

Arguments read from a file must be one per line by default (but see also
@ref{3385,,convert_arg_line_to_args()}) and are treated as if they
were in the same place as the original file referencing argument on the command
line.  So in the example above, the expression @code{['-f', 'foo', '@@args.txt']}
is considered equivalent to the expression @code{['-f', 'foo', '-f', 'bar']}.

@cartouche
@quotation 注釈 
Empty lines are treated as empty strings (@code{'@w{'}}), which are allowed as values but
not as arguments. Empty lines that are read as arguments will result in an
"unrecognized arguments" error.
@end quotation
@end cartouche

@ref{1bd,,ArgumentParser} uses @ref{75d,,filesystem encoding and error handler}
to read the file containing arguments.

@code{fromfile_prefix_chars=} 引数のデフォルト値は @code{None} で、引数がファイル参照として扱われることがないことを意味しています。


バージョン 3.12 で変更: @ref{1bd,,ArgumentParser} changed encoding and errors to read arguments files
from default (e.g. @ref{75c,,locale.getpreferredencoding(False)}
and @code{"strict"}) to the @ref{75d,,filesystem encoding and error handler}.
Arguments file should be encoded in UTF-8 instead of ANSI Codepage on Windows.


@node argument_default,allow_abbrev,fromfile_prefix_chars,ArgumentParser オブジェクト
@anchor{library/argparse argument-default}@anchor{3377}
@subsubsection argument_default


一般的には、引数のデフォルト値は @ref{4bc,,add_argument()} メソッドにデフォルト値を渡すか、@ref{3386,,set_defaults()} メソッドに名前と値のペアを渡すことで指定します。しかしまれに、1つのパーサー全体に適用されるデフォルト引数が便利なことがあります。これを行うには、 @ref{1bd,,ArgumentParser} に @code{argument_default=} キーワード引数を渡します。例えば、全体で @ref{336d,,parse_args()} メソッド呼び出しの属性の生成を抑制するには、@code{argument_default=SUPPRESS} を指定します:

@example
>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar', nargs='?')
>>> parser.parse_args(['--foo', '1', 'BAR'])
Namespace(bar='BAR', foo='1')
>>> parser.parse_args([])
Namespace()
@end example

@node allow_abbrev,conflict_handler,argument_default,ArgumentParser オブジェクト
@anchor{library/argparse allow-abbrev}@anchor{fbe}@anchor{library/argparse id4}@anchor{3387}
@subsubsection allow_abbrev


通常、@ref{1bd,,ArgumentParser} の @ref{336d,,parse_args()} に引数のリストを渡すとき、長いオプションは @ref{fbf,,短縮しても認識されます}。

この機能は、@code{allow_abbrev} に @code{False} を指定することで無効にできます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
>>> parser.add_argument('--foobar', action='store_true')
>>> parser.add_argument('--foonley', action='store_false')
>>> parser.parse_args(['--foon'])
usage: PROG [-h] [--foobar] [--foonley]
PROG: error: unrecognized arguments: --foon
@end example


Added in version 3.5.


@node conflict_handler,add_help,allow_abbrev,ArgumentParser オブジェクト
@anchor{library/argparse conflict-handler}@anchor{3378}
@subsubsection conflict_handler


@ref{1bd,,ArgumentParser} オブジェクトは同じオプション文字列に対して複数のアクションを許可していません。
デフォルトでは、@ref{1bd,,ArgumentParser} オブジェクトは、すでに利用されているオプション文字列を使って新しい引数をつくろうとしたときに例外を送出します:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
Traceback (most recent call last):
 ..
ArgumentError: argument --foo: conflicting option string(s): --foo
@end example

ときどき (例えば @ref{3373,,parents} を利用する場合など)、古い引数を同じオプション文字列で上書きするほうが便利な場合があります。この動作をするには、@ref{1bd,,ArgumentParser} の @code{conflict_handler=} 引数に @code{'resolve'} を渡します:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
>>> parser.print_help()
usage: PROG [-h] [-f FOO] [--foo FOO]

options:
 -h, --help  show this help message and exit
 -f FOO      old foo help
 --foo FOO   new foo help
@end example

@ref{1bd,,ArgumentParser} オブジェクトは、すべてのオプション文字列が上書きされた場合にだけアクションを削除することに注目してください。上の例では、 @code{--foo} オプション文字列だけが上書きされているので、古い @code{-f/--foo} アクションは @code{-f} アクションとして残っています。

@node add_help,exit_on_error,conflict_handler,ArgumentParser オブジェクト
@anchor{library/argparse add-help}@anchor{3379}
@subsubsection add_help


By default, @ref{1bd,,ArgumentParser} objects add an option which simply displays
the parser's help message. If @code{-h} or @code{--help} is supplied at the command
line, the @code{ArgumentParser} help will be printed.

必要に応じて、この help オプションを無効にする場合があります。これは @ref{1bd,,ArgumentParser} の @code{add_help=} 引数に @code{False} を渡すことで可能です:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]

options:
 --foo FOO  foo help
@end example

ヘルプオプションは通常 @code{-h/--help} です。例外は @code{prefix_chars=} が指定されてその中に @code{-} が無かった場合で、その場合は @code{-h} と @code{--help} は有効なオプションではありません。この場合、@code{prefix_chars} の最初の文字がヘルプオプションの接頭辞として利用されます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
>>> parser.print_help()
usage: PROG [+h]

options:
  +h, ++help  show this help message and exit
@end example

@node exit_on_error,suggest_on_error,add_help,ArgumentParser オブジェクト
@anchor{library/argparse exit-on-error}@anchor{337a}
@subsubsection exit_on_error


Normally, when you pass an invalid argument list to the @ref{336d,,parse_args()}
method of an @ref{1bd,,ArgumentParser}, it will print a `message' to @ref{b33,,sys.stderr} and exit with a status
code of 2.

もしエラーを例外としてプログラム内でキャッチしたい場合は、@code{exit_on_error} を @code{False} に設定してください:

@example
>>> parser = argparse.ArgumentParser(exit_on_error=False)
>>> parser.add_argument('--integers', type=int)
_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)
>>> try:
...     parser.parse_args('--integers a'.split())
... except argparse.ArgumentError:
...     print('Catching an argumentError')
...
Catching an argumentError
@end example


Added in version 3.9.


@node suggest_on_error,color,exit_on_error,ArgumentParser オブジェクト
@anchor{library/argparse suggest-on-error}@anchor{337b}
@subsubsection suggest_on_error


By default, when a user passes an invalid argument choice or subparser name,
@ref{1bd,,ArgumentParser} will exit with error info and list the permissible
argument choices (if specified) or subparser names as part of the error message.

If the user would like to enable suggestions for mistyped argument choices and
subparser names, the feature can be enabled by setting @code{suggest_on_error} to
@code{True}. Note that this only applies for arguments when the choices specified
are strings:

@example
>>> parser = argparse.ArgumentParser(description='Process some integers.',
                                     suggest_on_error=True)
>>> parser.add_argument('--action', choices=['sum', 'max'])
>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')
>>> parser.parse_args(['--action', 'sumn', 1, 2, 3])
tester.py: error: argument --action: invalid choice: 'sumn', maybe you meant 'sum'? (choose from 'sum', 'max')
@end example

If you're writing code that needs to be compatible with older Python versions
and want to opportunistically use @code{suggest_on_error} when it's available, you
can set it as an attribute after initializing the parser instead of using the
keyword argument:

@example
>>> parser = argparse.ArgumentParser(description='Process some integers.')
>>> parser.suggest_on_error = True
@end example


Added in version 3.14.


@node color,,suggest_on_error,ArgumentParser オブジェクト
@anchor{library/argparse color}@anchor{337c}
@subsubsection color


By default, the help message is printed in color using ANSI escape sequences@footnote{https://en.wikipedia.org/wiki/ANSI_escape_code}.
If you want plain text help messages, you can disable this @ref{1b7,,in your local environment}, or in the argument parser itself
by setting @code{color} to @code{False}:

@example
>>> parser = argparse.ArgumentParser(description='Process some integers.',
...                                  color=False)
>>> parser.add_argument('--action', choices=['sum', 'max'])
>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')
>>> parser.parse_args(['--help'])
@end example

Note that when @code{color=True}, colored output depends on both environment
variables and terminal capabilities.  However, if @code{color=False}, colored
output is always disabled, even if environment variables like @code{FORCE_COLOR}
are set.

@cartouche
@quotation 注釈 
Error messages will include color codes when redirecting stderr to a
file. To avoid this, set the NO_COLOR@footnote{https://no-color.org/} or 
@geindex PYTHON_COLORS
@geindex 環境変数; PYTHON_COLORS
@ref{476,,PYTHON_COLORS}
environment variable (for example,
@code{NO_COLOR=1 python script.py 2> errors.txt}).
@end quotation
@end cartouche


Added in version 3.14.


@node add_argument メソッド,parse_args メソッド,ArgumentParser オブジェクト,argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー
@anchor{library/argparse the-add-argument-method}@anchor{3388}
@subsubsection add_argument() メソッド


@geindex add_argument() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser add_argument}@anchor{4bc}
@deffn {メソッド} ArgumentParser.add_argument (name or flags..., *[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest][, deprecated])

1つのコマンドライン引数がどう解析されるかを定義します。各引数についての詳細は後述しますが、簡単に言うと:


@itemize *

@item 
@ref{3389,,name or flags} - Either a name or a list of option strings, e.g. @code{'foo'}
or @code{'-f', '--foo'}.

@item 
@ref{192b,,action} - コマンドラインにこの引数があったときのアクション。

@item 
@ref{1931,,nargs} - 受け取るべきコマンドライン引数の数。

@item 
@ref{1933,,const} - 一部の @ref{192b,,action} と @ref{1931,,nargs} の組み合わせで利用される定数。

@item 
@ref{1932,,default} - コマンドラインに対応する引数が存在せず、さらに namespace オブジェクトにも存在しない場合に利用される値。

@item 
@ref{3383,,type} - コマンドライン引数が変換されるべき型。

@item 
@ref{192d,,choices} - 引数として許される値のシーケンス。

@item 
@ref{338a,,required} - コマンドラインオプションが省略可能かどうか (オプション引数のみ)。

@item 
@ref{338b,,help} - 引数が何なのかを示す簡潔な説明。

@item 
@ref{338c,,metavar} - 使用法メッセージの中で使われる引数の名前。

@item 
@ref{3384,,dest} - @ref{336d,,parse_args()} が返すオブジェクトに追加される属性名。

@item 
@ref{338d,,deprecated} - Whether or not use of the argument is deprecated.
@end itemize
@end deffn

以下の節では各オプションの利用方法を説明します。

@menu
* name または flags:: 
* action:: 
* nargs:: 
* const:: 
* default:: 
* type:: 
* choices:: 
* required:: 
* help:: 
* metavar:: 
* dest:: 
* deprecated:: 
* Action クラス:: 

@end menu

@node name または flags,action,,add_argument メソッド
@anchor{library/argparse id5}@anchor{338e}@anchor{library/argparse name-or-flags}@anchor{3389}
@subsubsection name または flags


@ref{4bc,,add_argument()} メソッドは、指定されている引数が @code{-f} や @code{--foo} のようなオプション引数なのか、ファイル名リストなどの位置引数なのかを知る必要があります。
そのため、 @ref{4bc,,add_argument()} に初めに渡される引数は、一連のフラグか、単一の引数名のどちらかになります。

たとえば、オプション引数は次のように作成します:

@example
>>> parser.add_argument('-f', '--foo')
@end example

一方、位置引数は次のように作成します:

@example
>>> parser.add_argument('bar')
@end example

@ref{336d,,parse_args()} が呼ばれたとき、オプション引数は接頭辞 @code{-} により識別され、それ以外の引数は位置引数として扱われます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args(['BAR'])
Namespace(bar='BAR', foo=None)
>>> parser.parse_args(['BAR', '--foo', 'FOO'])
Namespace(bar='BAR', foo='FOO')
>>> parser.parse_args(['--foo', 'FOO'])
usage: PROG [-h] [-f FOO] bar
PROG: error: the following arguments are required: bar
@end example

By default, @code{argparse} automatically handles the internal naming and
display names of arguments, simplifying the process without requiring
additional configuration.
As such, you do not need to specify the @ref{3384,,dest} and @ref{338c,,metavar} parameters.
The @ref{3384,,dest} parameter defaults to the argument name with underscores @code{_}
replacing hyphens @code{-} . The @ref{338c,,metavar} parameter defaults to the
upper-cased name. For example:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo-bar')
>>> parser.parse_args(['--foo-bar', 'FOO-BAR'])
Namespace(foo_bar='FOO-BAR')
>>> parser.print_help()
usage:  [-h] [--foo-bar FOO-BAR]

optional arguments:
 -h, --help  show this help message and exit
 --foo-bar FOO-BAR
@end example

@node action,nargs,name または flags,add_argument メソッド
@anchor{library/argparse action}@anchor{192b}@anchor{library/argparse id6}@anchor{338f}
@subsubsection action


@ref{1bd,,ArgumentParser} オブジェクトはコマンドライン引数にアクションを割り当てます。このアクションは、割り当てられたコマンドライン引数に関してどんな処理でもできますが、ほとんどのアクションは単に @ref{336d,,parse_args()} が返すオブジェクトに属性を追加するだけです。@code{action} キーワード引数は、コマンドライン引数がどう処理されるかを指定します。提供されているアクションは:


@itemize *

@item 
@code{'store'} - This just stores the argument's value.  This is the default
action.

@item 
@code{'store_const'} - このアクションは @ref{1933,,const} キーワード引数で指定された値を格納します。@ref{1933,,const} キーワード引数のデフォルト値は @code{None} であることに注意してください。@code{'store_const'} アクションは、何かの種類のフラグを指定するオプション引数によく使われます。例えば:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
Namespace(foo=42)
@end example

@item 
@code{'store_true'} and @code{'store_false'} - These are special cases of
@code{'store_const'} that respectively store the values @code{True} and @code{False}
with default values of @code{False} and
@code{True}:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)
@end example

@item 
@code{'append'} - This appends each argument value to a list.
It is useful for allowing an option to be specified multiple times.
If the default value is a non-empty list, the parsed value will start
with the default list's elements and any values from the command line
will be appended after those default values. Example usage:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append', default=['0'])
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['0', '1', '2'])
@end example

@item 
@code{'append_const'} - This appends the value specified by
the @ref{1933,,const} keyword argument to a list; note that the @ref{1933,,const} keyword
argument defaults to @code{None}. The @code{'append_const'} action is typically
useful when multiple arguments need to store constants to the same list. For
example:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
>>> parser.parse_args('--str --int'.split())
Namespace(types=[<class 'str'>, <class 'int'>])
@end example

@item 
@code{'extend'} - This appends each item from a multi-value
argument to a list.
The @code{'extend'} action is typically used with the @ref{1931,,nargs} keyword argument
value @code{'+'} or @code{'*'}.
Note that when @ref{1931,,nargs} is @code{None} (the default) or @code{'?'}, each
character of the argument string will be appended to the list.
Example usage:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
>>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
Namespace(foo=['f1', 'f2', 'f3', 'f4'])
@end example


Added in version 3.8.


@item 
@code{'count'} - This counts the number of times an argument occurs. For
example, this is useful for increasing verbosity levels:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count', default=0)
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)
@end example

`default' は明示的に `0' と指定されない場合は @code{None} であることに注意してください。

@item 
@code{'help'} - このアクションは現在のパーサー中のすべてのオプションのヘルプメッセージを表示し、終了します。出力の生成方法の詳細については @ref{1bd,,ArgumentParser} を参照してください。

@item 
@code{'version'} - このアクションは @ref{4bc,,add_argument()} の呼び出しに @code{version=} キーワード引数を期待します。指定されたときはバージョン情報を表示して終了します:

@example
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
>>> parser.parse_args(['--version'])
PROG 2.0
@end example
@end itemize

You may also specify an arbitrary action by passing an @ref{1b8c,,Action} subclass
(e.g. @ref{1bf2,,BooleanOptionalAction}) or other object that implements the same
interface. Only actions that consume command-line arguments (e.g. @code{'store'},
@code{'append'}, @code{'extend'}, or custom actions with non-zero @code{nargs}) can be used
with positional arguments.

The recommended way to create a custom action is to extend @ref{1b8c,,Action},
overriding the @code{__call__()} method and optionally the @code{__init__()} and
@code{format_usage()} methods. You can also register custom actions using the
@ref{3390,,register()} method and reference them by their registered name.

カスタムアクションの例です:

@example
>>> class FooAction(argparse.Action):
...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
...         if nargs is not None:
...             raise ValueError("nargs not allowed")
...         super().__init__(option_strings, dest, **kwargs)
...     def __call__(self, parser, namespace, values, option_string=None):
...         print('%r %r %r' % (namespace, values, option_string))
...         setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None
Namespace(bar='1', foo=None) '2' '--foo'
>>> args
Namespace(bar='1', foo='2')
@end example

詳細は @ref{1b8c,,Action} を参照してください。

@node nargs,const,action,add_argument メソッド
@anchor{library/argparse id7}@anchor{3391}@anchor{library/argparse nargs}@anchor{1931}
@subsubsection nargs


@ref{1bd,,ArgumentParser} objects usually associate a single command-line argument with a
single action to be taken.  The @code{nargs} keyword argument associates a
different number of command-line arguments with a single action.
See also @ref{3392,,多義性のある引数の指定}. The supported values are:


@itemize *

@item 
@code{N} (整数) -- @code{N} 個の引数がコマンドラインから集められ、リストに格納されます。例えば:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])
@end example

@code{nargs=1} は1要素のリストを作ることに注意してください。これはデフォルトの、要素がそのまま属性になる動作とは異なります。
@end itemize

@geindex ? (クエスチョンマーク);argparse モジュール内


@itemize *

@item 
@code{'?'} -- 可能なら1つの引数がコマンドラインから取られ、1つのアイテムを作ります。コマンドライン引数が存在しない場合、@ref{1932,,default} の値が生成されます。オプション引数の場合、さらにオプション引数が指定され、その後にコマンドライン引数がないというケースもありえます。この場合は @ref{1933,,const} の値が生成されます。この動作の例です:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args(['XX', '--foo', 'YY'])
Namespace(bar='XX', foo='YY')
>>> parser.parse_args(['XX', '--foo'])
Namespace(bar='XX', foo='c')
>>> parser.parse_args([])
Namespace(bar='d', foo='d')
@end example

@code{nargs='?'} のよくある利用例の1つは、入出力ファイルの指定オプションです:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', nargs='?')
>>> parser.add_argument('outfile', nargs='?')
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile='input.txt', outfile='output.txt')
>>> parser.parse_args(['input.txt'])
Namespace(infile='input.txt', outfile=None)
>>> parser.parse_args([])
Namespace(infile=None, outfile=None)
@end example
@end itemize

@geindex * (アスタリスク);argparse モジュール内


@itemize *

@item 
@code{'*'} -- すべてのコマンドライン引数がリストに集められます。複数の位置引数が @code{nargs='*'} を持つことにあまり意味はありませんが、複数のオプション引数が @code{nargs='*'} を持つことはありえます。例えば:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('baz', nargs='*')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
@end example
@end itemize

@geindex + (プラス記号);argparse モジュール内


@itemize *

@item 
@code{'+'}. Just like @code{'*'}, all command-line arguments present are gathered into a
list.  Additionally, an error message will be generated if there wasn't at
least one command-line argument present.  For example:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
>>> parser.parse_args(['a', 'b'])
Namespace(foo=['a', 'b'])
>>> parser.parse_args([])
usage: PROG [-h] foo [foo ...]
PROG: error: the following arguments are required: foo
@end example
@end itemize

If the @code{nargs} keyword argument is not provided, the number of arguments consumed
is determined by the @ref{192b,,action}.  Generally this means a single command-line argument
will be consumed and a single item (not a list) will be produced.
Actions that do not consume command-line arguments (e.g.
@code{'store_const'}) set @code{nargs=0}.

@node const,default,nargs,add_argument メソッド
@anchor{library/argparse const}@anchor{1933}@anchor{library/argparse id8}@anchor{3393}
@subsubsection const


@ref{4bc,,add_argument()} の @code{const} 引数は、コマンドライン引数から読み込まれないけれども @ref{1bd,,ArgumentParser} のいくつかのアクションで必要とされる値のために使われます。この引数のよくある2つの使用法は:


@itemize *

@item 
@ref{4bc,,add_argument()} が @code{action='store_const'} か @code{action='append_const'} で呼び出されたとき、これらのアクションは @code{const} の値を @ref{336d,,parse_args()} が返すオブジェクトの属性に追加します。サンプルは @ref{192b,,action} の説明を参照してください。@code{const} が @ref{4bc,,add_argument()} に与えられなければ、@code{None} のデフォルト値を受け取ります。

@item 
When @ref{4bc,,add_argument()} is called with option strings
(like @code{-f} or @code{--foo}) and @code{nargs='?'}.  This creates an optional
argument that can be followed by zero or one command-line arguments.
When parsing the command line, if the option string is encountered with no
command-line argument following it, the value from @code{const} will be used.
See the @ref{1931,,nargs} description for examples.
@end itemize


バージョン 3.11 で変更: @code{action='append_const'} や @code{action='store_const'} の場合も含め、デフォルトでは @code{const=None} です。


@node default,type,const,add_argument メソッド
@anchor{library/argparse default}@anchor{1932}@anchor{library/argparse id9}@anchor{3394}
@subsubsection default


すべてのオプション引数といくつかの位置引数はコマンドライン上で省略されることがあります。 @ref{4bc,,add_argument()} の @code{default} キーワード引数 (デフォルト: @code{None}) は、コマンドライン引数が存在しなかった場合に利用する値を指定します。オプション引数では、オプション文字列がコマンドライン上に存在しなかったときに @code{default} の値が利用されます:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args(['--foo', '2'])
Namespace(foo='2')
>>> parser.parse_args([])
Namespace(foo=42)
@end example

If the target namespace already has an attribute set, the action `default'
will not overwrite it:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
Namespace(foo=101)
@end example

@code{default} の値が文字列の場合、パーサーは値をコマンドライン引数のように解析します。具体的には、パーサーは返り値 @ref{336e,,Namespace} の属性を設定する前に、@ref{3383,,type} 変換引数が与えられていればそれらを適用します。そうでない場合、パーサーは値をそのまま使用します:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--length', default='10', type=int)
>>> parser.add_argument('--width', default=10.5, type=int)
>>> parser.parse_args()
Namespace(length=10, width=10.5)
@end example

@ref{1931,,nargs} が @code{?} か @code{*} である位置引数では、コマンドライン引数が指定されなかった場合 @code{default} の値が使われます。例えば:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='?', default=42)
>>> parser.parse_args(['a'])
Namespace(foo='a')
>>> parser.parse_args([])
Namespace(foo=42)
@end example

For @ref{338a,,required} arguments, the @code{default} value is ignored. For example, this
applies to positional arguments with @ref{1931,,nargs} values other than @code{?} or @code{*},
or optional arguments marked as @code{required=True}.

@code{default=argparse.SUPPRESS} を渡すと、コマンドライン引数が存在しないときに属性の追加をしなくなります:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=argparse.SUPPRESS)
>>> parser.parse_args([])
Namespace()
>>> parser.parse_args(['--foo', '1'])
Namespace(foo='1')
@end example

@node type,choices,default,add_argument メソッド
@anchor{library/argparse argparse-type}@anchor{3395}@anchor{library/argparse type}@anchor{3383}
@subsubsection type


デフォルトでは、パーサーはコマンドライン引数を単なる文字列として読み込みます。しかし、それらの文字列を @ref{196,,float}, @ref{19b,,int} など別の型として扱うべき事がよくあります。@ref{4bc,,add_argument()} の @code{type} キーワード引数に指定する type converter により、必要な型チェックと型変換を行うことができます。

もし @ref{3383,,type} キーワードが @ref{1932,,default} キーワードとともに使用された場合、@ref{1932,,default}  の値が文字列のときのみ、type converter による変換などが行われます。

The argument to @code{type} can be a callable that accepts a single string or
the name of a registered type (see @ref{3390,,register()})
If the function raises @ref{3396,,ArgumentTypeError}, @ref{198,,TypeError}, or
@ref{2ec,,ValueError}, the exception is caught and a nicely formatted error
message is displayed. Other exception types are not handled.

一般的なビルトインデータ型や関数を @code{type} 引数の値として直接指定できます:

@example
import argparse
import pathlib

parser = argparse.ArgumentParser()
parser.add_argument('count', type=int)
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('datapath', type=pathlib.Path)
@end example

ユーザが定義した関数も使用できます:

@example
>>> def hyphenated(string):
...     return '-'.join([word[:4] for word in string.casefold().split()])
...
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument('short_title', type=hyphenated)
>>> parser.parse_args(['"The Tale of Two Cities"'])
Namespace(short_title='"the-tale-of-two-citi')
@end example

Type converter として @ref{3c3,,bool()} 関数を使用することは推奨されません。なぜなら、これは空文字列を @code{False} に、それ以外の全てを @code{True} に変換しますが、これはおそらく望まれる動作ではないからです (訳注: 文字列 @code{'false'} を @code{False} に変換してくれたりはしません)。

一般論として、@code{type} キーワードに指定するものは、せいぜい上記の3種類の例外を発生するくらいの、お手軽な変換に限るべきです。より複雑な (interesting) エラー処理、またはリソース管理を伴うものは、引数を解析したあとに別個の処理として行うべきです。

たとえば、JSON または YAML からの変換は複雑なエラーケースを持つので、@code{type} がサポートする以上のエラー表示を必要とするでしょう。(JSON デコーダが発生しうる) @ref{1022,,JSONDecodeError} は適切に整形されて表示されません。また、@ref{264,,FileNotFoundError} が発生しても parser は何も処理しません。

Even @ref{30c,,FileType} has its limitations for use with the @code{type}
keyword.  If one argument uses @ref{30c,,FileType} and then a
subsequent argument fails, an error is reported but the file is not
automatically closed.  In this case, it would be better to wait until after
the parser has run and then use the @ref{186,,with}-statement to manage the
files.

なお、引数が、あらかじめ決められた値の候補のいずれかに一致するかをチェックしたいだけの場合には、代わりに @ref{192d,,choices} キーワードの使用を検討してください。

@node choices,required,type,add_argument メソッド
@anchor{library/argparse choices}@anchor{192d}@anchor{library/argparse id10}@anchor{3397}
@subsubsection choices


コマンドライン引数をいくつかの選択肢の中から選ばせたい場合があります。 これは @ref{4bc,,add_argument()} に シーケンスオブジェクトを `choices' キーワード引数として渡すことで可能です。コマンドラインを解析するとき、引数の値がチェックされ、その値が選択肢の中に含まれていない場合はエラーメッセージを表示します:

@example
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] @{rock,paper,scissors@}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
@end example

任意のシーケンスを `choices' に渡すことができます。すなわち、@ref{24d,,list} オブジェクト、 @ref{614,,tuple} オブジェクト、カスタムシーケンスはすべてサポートされています。

ただし、@ref{842,,enum.Enum} を渡すことは推奨されません。使用方法、ヘルプ、エラーメッセージなどでどのように表示されるかを制御することが難いからです。

Note that `choices' are checked after any @ref{3383,,type}
conversions have been performed, so objects in `choices'
should match the @ref{3383,,type} specified. This can make `choices'
appear unfamiliar in usage, help, or error messages.

To keep `choices' user-friendly, consider a custom type wrapper that
converts and formats values, or omit @ref{3383,,type} and handle conversion in
your application code.

ヘルプテキストにおいて整形された choices の値は、通常 `dest' から生成されるデフォルトの `metavar' に優先します。ユーザーは `dest' パラメータを目にすることがないため、この振る舞いは基本的には望ましいものです。もしこの表示方法が望ましくない場合 (おそらく多くの選択肢がある場合など) は、 @ref{338c,,metavar} を明示的に指定してください。

@node required,help,choices,add_argument メソッド
@anchor{library/argparse id11}@anchor{3398}@anchor{library/argparse required}@anchor{338a}
@subsubsection required


In general, the @code{argparse} module assumes that flags like @code{-f} and @code{--bar}
indicate `optional' arguments, which can always be omitted at the command line.
To make an option `required', @code{True} can be specified for the @code{required=}
keyword argument to @ref{4bc,,add_argument()}:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: [-h] --foo FOO
: error: the following arguments are required: --foo
@end example

上の例のように、引数が @code{required} と指定されると、@ref{336d,,parse_args()} はそのフラグがコマンドラインに存在しないときにエラーを表示します。

@cartouche
@quotation 注釈 
ユーザーは、通常 `フラグ' の指定は `任意' であると認識しているため、必須にするのは一般的には悪いやり方で、できる限り避けるべきです。
@end quotation
@end cartouche

@node help,metavar,required,add_argument メソッド
@anchor{library/argparse help}@anchor{338b}@anchor{library/argparse id12}@anchor{3399}
@subsubsection help


The @code{help} value is a string containing a brief description of the argument.
When a user requests help (usually by using @code{-h} or @code{--help} at the
command line), these @code{help} descriptions will be displayed with each
argument.

@code{help} 文字列には、プログラム名や引数の @ref{1932,,default} などを繰り返し記述するのを避けるためのフォーマット指定子を含めることができます。利用できる指定子には、プログラム名 @code{%(prog)s} と、 @code{%(default)s} や @code{%(type)s} など @ref{4bc,,add_argument()} のキーワード引数の多くが含まれます:

@example
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
...                     help='the bar to %(prog)s (default: %(default)s)')
>>> parser.print_help()
usage: frobble [-h] [bar]

positional arguments:
 bar     the bar to frobble (default: 42)

options:
 -h, --help  show this help message and exit
@end example

ヘルプ文字列は %-フォーマットをサポートしているので、ヘルプ文字列内にリテラル @code{%} を表示したい場合は @code{%%} のようにエスケープしなければなりません。

@code{argparse} supports silencing the help entry for certain options, by
setting the @code{help} value to @code{argparse.SUPPRESS}:

@example
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

options:
  -h, --help  show this help message and exit
@end example

@node metavar,dest,help,add_argument メソッド
@anchor{library/argparse id13}@anchor{339a}@anchor{library/argparse metavar}@anchor{338c}
@subsubsection metavar


When @ref{1bd,,ArgumentParser} generates help messages, it needs some way to refer
to each expected argument.  By default, @code{ArgumentParser} objects use the @ref{3384,,dest}
value as the "name" of each object.  By default, for positional argument
actions, the @ref{3384,,dest} value is used directly, and for optional argument actions,
the @ref{3384,,dest} value is uppercased.  So, a single positional argument with
@code{dest='bar'} will be referred to as @code{bar}. A single
optional argument @code{--foo} that should be followed by a single command-line argument
will be referred to as @code{FOO}.  An example:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo FOO] bar

positional arguments:
 bar

options:
 -h, --help  show this help message and exit
 --foo FOO
@end example

代わりの名前を、@code{metavar} として指定できます:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo YYY] XXX

positional arguments:
 XXX

options:
 -h, --help  show this help message and exit
 --foo YYY
@end example

@code{metavar} は `表示される' 名前だけを変更することに注意してください。@ref{336d,,parse_args()} の返すオブジェクトの属性名は @ref{3384,,dest} の値のままです。

@code{nargs} を指定した場合、metavar が複数回利用されるかもしれません。@code{metavar} にタプルを渡すと、各引数に対して異なる名前を指定できます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

options:
 -h, --help     show this help message and exit
 -x X X
 --foo bar baz
@end example

@node dest,deprecated,metavar,add_argument メソッド
@anchor{library/argparse dest}@anchor{3384}@anchor{library/argparse id14}@anchor{339b}
@subsubsection dest


ほとんどの @ref{1bd,,ArgumentParser} のアクションは @ref{336d,,parse_args()} が返すオブジェクトに対する属性として値を追加します。この属性の名前は @ref{4bc,,add_argument()} の @code{dest} キーワード引数によって決定されます。位置引数のアクションについては、 @code{dest} は通常 @ref{4bc,,add_argument()} の第一引数として渡します:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar')
>>> parser.parse_args(['XXX'])
Namespace(bar='XXX')
@end example

オプション引数のアクションについては、 @code{dest} の値は通常オプション文字列から生成されます。 @ref{1bd,,ArgumentParser} は最初の長いオプション文字列を選択し、先頭の @code{--} を除去することで @code{dest} の値を生成します。長いオプション文字列が指定されていない場合、最初の短いオプション文字列から先頭の @code{-} 文字を除去することで @code{dest} を生成します。先頭以外のすべての @code{-} 文字は、妥当な属性名になるように @code{_} 文字へ変換されます。次の例はこの動作を示しています:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')
@end example

@code{dest} にカスタムの属性名を与えることも可能です:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
@end example

@node deprecated,Action クラス,dest,add_argument メソッド
@anchor{library/argparse deprecated}@anchor{338d}@anchor{library/argparse id15}@anchor{339c}
@subsubsection deprecated


During a project's lifetime, some arguments may need to be removed from the
command line. Before removing them, you should inform
your users that the arguments are deprecated and will be removed.
The @code{deprecated} keyword argument of
@ref{4bc,,add_argument()}, which defaults to @code{False},
specifies if the argument is deprecated and will be removed
in the future.
For arguments, if @code{deprecated} is @code{True}, then a warning will be
printed to @ref{b33,,sys.stderr} when the argument is used:

@example
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='snake.py')
>>> parser.add_argument('--legs', default=0, type=int, deprecated=True)
>>> parser.parse_args([])
Namespace(legs=0)
>>> parser.parse_args(['--legs', '4'])
snake.py: warning: option '--legs' is deprecated
Namespace(legs=4)
@end example


Added in version 3.13.


@node Action クラス,,deprecated,add_argument メソッド
@anchor{library/argparse action-classes}@anchor{339d}
@subsubsection Action クラス


@code{Action} classes implement the Action API, a callable which returns a callable
which processes arguments from the command-line. Any object which follows
this API may be passed as the @code{action} parameter to
@ref{4bc,,add_argument()}.

@geindex Action (argparse のクラス)
@anchor{library/argparse argparse Action}@anchor{1b8c}
@deffn {クラス} argparse.Action (option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

@code{Action} objects are used by an @ref{1bd,,ArgumentParser} to represent the information
needed to parse a single argument from one or more strings from the
command line. The @code{Action} class must accept the two positional arguments
plus any keyword arguments passed to @ref{4bc,,ArgumentParser.add_argument()}
except for the @code{action} itself.

Instances of @code{Action} (or return value of any callable to the
@code{action} parameter) should have attributes @code{dest},
@code{option_strings}, @code{default}, @code{type}, @code{required},
@code{help}, etc. defined. The easiest way to ensure these attributes
are defined is to call @code{Action.__init__()}.

@geindex __call__() (argparse.Action のメソッド)
@anchor{library/argparse argparse Action __call__}@anchor{339e}
@deffn {メソッド} __call__ (parser, namespace, values, option_string=None)

@code{Action} instances should be callable, so subclasses must override the
@code{__call__()} method, which should accept four parameters:


@itemize *

@item 
`parser' - The @ref{1bd,,ArgumentParser} object which contains this action.

@item 
`namespace' - The @ref{336e,,Namespace} object that will be returned by
@ref{336d,,parse_args()}.  Most actions add an attribute to this
object using @ref{25be,,setattr()}.

@item 
`values' - The associated command-line arguments, with any type conversions
applied.  Type conversions are specified with the @ref{3383,,type} keyword argument to
@ref{4bc,,add_argument()}.

@item 
`option_string' - The option string that was used to invoke this action.
The @code{option_string} argument is optional, and will be absent if the action
is associated with a positional argument.
@end itemize

The @code{__call__()} method may perform arbitrary actions, but will typically set
attributes on the @code{namespace} based on @code{dest} and @code{values}.
@end deffn

@geindex format_usage() (argparse.Action のメソッド)
@anchor{library/argparse argparse Action format_usage}@anchor{339f}
@deffn {メソッド} format_usage ()

@code{Action} subclasses can define a @code{format_usage()} method that takes no argument
and return a string which will be used when printing the usage of the program.
If such method is not provided, a sensible default will be used.
@end deffn
@end deffn

@geindex BooleanOptionalAction (argparse のクラス)
@anchor{library/argparse argparse BooleanOptionalAction}@anchor{1bf2}
@deffn {クラス} argparse.BooleanOptionalAction

A subclass of @ref{1b8c,,Action} for handling boolean flags with positive
and negative options. Adding a single argument such as @code{--foo} automatically
creates both @code{--foo} and @code{--no-foo} options, storing @code{True} and @code{False}
respectively:

@example
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)
@end example


Added in version 3.9.

@end deffn

@node parse_args メソッド,その他のユーティリティ,add_argument メソッド,argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー
@anchor{library/argparse the-parse-args-method}@anchor{33a0}
@subsubsection parse_args() メソッド


@geindex parse_args() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser parse_args}@anchor{336d}
@deffn {メソッド} ArgumentParser.parse_args (args=None, namespace=None)

引数の文字列をオブジェクトに変換し、namespace オブジェクトの属性に代入します。結果の namespace オブジェクトを返します。

Previous calls to @ref{4bc,,add_argument()} determine exactly what objects are
created and how they are assigned. See the documentation for
@code{add_argument()} for details.


@itemize *

@item 
@ref{33a1,,args} - 解析する文字列のリスト。デフォルトでは @ref{147c,,sys.argv} から取得されます。

@item 
@ref{33a2,,namespace} - 属性を代入するオブジェクト。デフォルトでは、新しい空の @ref{336e,,Namespace} オブジェクトです。
@end itemize
@end deffn

@menu
* オプション値の文法:: 
* 不正な引数:: 
* - を含む引数:: 
* 引数の短縮形 (先頭文字でのマッチング): 引数の短縮形 先頭文字でのマッチング. 
* sys.argv 以外: sys argv 以外. 
* Namespace オブジェクト:: 

@end menu

@node オプション値の文法,不正な引数,,parse_args メソッド
@anchor{library/argparse option-value-syntax}@anchor{33a3}
@subsubsection オプション値の文法


@ref{336d,,parse_args()} メソッドは、オプションの値がある場合、そのオプションの値の指定に複数の方法をサポートしています。もっとも単純な場合には、オプションとその値は次のように2つの別々の引数として渡されます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('--foo')
>>> parser.parse_args(['-x', 'X'])
Namespace(foo=None, x='X')
>>> parser.parse_args(['--foo', 'FOO'])
Namespace(foo='FOO', x=None)
@end example

長いオプション (1文字よりも長い名前を持ったオプション) では、オプションとその値は次のように @code{=} で区切られた1つのコマンドライン引数として渡すこともできます:

@example
>>> parser.parse_args(['--foo=FOO'])
Namespace(foo='FOO', x=None)
@end example

短いオプション (1文字のオプション) では、オプションとその値は次のように連結して渡すことができます:

@example
>>> parser.parse_args(['-xX'])
Namespace(foo=None, x='X')
@end example

最後の1つのオプションだけが値を要求する場合、または値を要求するオプションがない場合、複数の短いオプションは次のように1つの接頭辞 @code{-} だけで連結できます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', action='store_true')
>>> parser.add_argument('-y', action='store_true')
>>> parser.add_argument('-z')
>>> parser.parse_args(['-xyzZ'])
Namespace(x=True, y=True, z='Z')
@end example

@node 不正な引数,- を含む引数,オプション値の文法,parse_args メソッド
@anchor{library/argparse invalid-arguments}@anchor{33a4}
@subsubsection 不正な引数


@ref{336d,,parse_args()} は、コマンドラインの解析中に、曖昧なオプション、不正な型、不正なオプション、位置引数の数の不一致などのエラーを検証します。それらのエラーが発生した場合、エラーメッセージと使用法メッセージを表示して終了します:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', nargs='?')

>>> # invalid type
>>> parser.parse_args(['--foo', 'spam'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: argument --foo: invalid int value: 'spam'

>>> # invalid option
>>> parser.parse_args(['--bar'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: no such option: --bar

>>> # wrong number of arguments
>>> parser.parse_args(['spam', 'badger'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: extra arguments found: badger
@end example

@node - を含む引数,引数の短縮形 先頭文字でのマッチング,不正な引数,parse_args メソッド
@anchor{library/argparse arguments-containing}@anchor{33a5}
@subsubsection @code{-} を含む引数


@ref{336d,,parse_args()} メソッドは、ユーザーが明らかなミスをした場合はエラーを表示しますが、いくつか本質的に曖昧な場面があります。例えば、コマンドライン引数 @code{-1} は、オプションの指定かもしれませんし位置引数かもしれません。@ref{336d,,parse_args()} メソッドはこれを次のように扱います: 負の数として解釈でき、パーサーに負の数のように解釈できるオプションが存在しない場合にのみ、@code{-} で始まる位置引数になりえます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('foo', nargs='?')

>>> # no negative number options, so -1 is a positional argument
>>> parser.parse_args(['-x', '-1'])
Namespace(foo=None, x='-1')

>>> # no negative number options, so -1 and -5 are positional arguments
>>> parser.parse_args(['-x', '-1', '-5'])
Namespace(foo='-5', x='-1')

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-1', dest='one')
>>> parser.add_argument('foo', nargs='?')

>>> # negative number options present, so -1 is an option
>>> parser.parse_args(['-1', 'X'])
Namespace(foo=None, one='X')

>>> # negative number options present, so -2 is an option
>>> parser.parse_args(['-2'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: no such option: -2

>>> # negative number options present, so both -1s are options
>>> parser.parse_args(['-1', '-1'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: argument -1: expected one argument
@end example

@code{-} で始まる位置引数があって、それが負の数として解釈できない場合、ダミーの引数 @code{'--'} を挿入して、@ref{336d,,parse_args()} にそれ以降のすべてが位置引数だと教えることができます:

@example
>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)
@end example

See also @ref{3392,,the argparse howto on ambiguous arguments}
for more details.

@node 引数の短縮形 先頭文字でのマッチング,sys argv 以外,- を含む引数,parse_args メソッド
@anchor{library/argparse argument-abbreviations-prefix-matching}@anchor{33a6}@anchor{library/argparse prefix-matching}@anchor{fbf}
@subsubsection 引数の短縮形 (先頭文字でのマッチング)


@ref{336d,,parse_args()} メソッドは、@ref{fbe,,デフォルトで}、長いオプションに曖昧さがない (先頭文字列が一意である) かぎり、先頭文字列に短縮して指定できます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-bacon')
>>> parser.add_argument('-badger')
>>> parser.parse_args('-bac MMM'.split())
Namespace(bacon='MMM', badger=None)
>>> parser.parse_args('-bad WOOD'.split())
Namespace(bacon=None, badger='WOOD')
>>> parser.parse_args('-ba BA'.split())
usage: PROG [-h] [-bacon BACON] [-badger BADGER]
PROG: error: ambiguous option: -ba could match -badger, -bacon
@end example

先頭の文字が同じ引数が複数ある場合に短縮指定を行うとエラーを発生させます。この機能は @ref{fbe,,allow_abbrev} に @code{False} を指定することで無効にできます。

@node sys argv 以外,Namespace オブジェクト,引数の短縮形 先頭文字でのマッチング,parse_args メソッド
@anchor{library/argparse args}@anchor{33a1}@anchor{library/argparse beyond-sys-argv}@anchor{33a7}
@subsubsection @code{sys.argv} 以外


Sometimes it may be useful to have an @ref{1bd,,ArgumentParser} parse arguments other than those
of @ref{147c,,sys.argv}.  This can be accomplished by passing a list of strings to
@ref{336d,,parse_args()}.  This is useful for testing at the
interactive prompt:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
...     'integers', metavar='int', type=int, choices=range(10),
...     nargs='+', help='an integer in the range 0..9')
>>> parser.add_argument(
...     '--sum', dest='accumulate', action='store_const', const=sum,
...     default=max, help='sum the integers (default: find the max)')
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
@end example

@node Namespace オブジェクト,,sys argv 以外,parse_args メソッド
@anchor{library/argparse namespace}@anchor{33a2}@anchor{library/argparse the-namespace-object}@anchor{33a8}
@subsubsection Namespace オブジェクト


@geindex Namespace (argparse のクラス)
@anchor{library/argparse argparse Namespace}@anchor{336e}
@deffn {クラス} argparse.Namespace

@ref{336d,,parse_args()} が属性を格納して返すためのオブジェクトにデフォルトで使用されるシンプルなクラスです。

このクラスはシンプルに設計されており、単に読みやすい文字列表現を持った @ref{c7e,,object} のサブクラスです。もし属性を辞書のように扱える方が良ければ、標準的な Python のイディオム @ref{1e23,,vars()} を利用できます:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
@{'foo': 'BAR'@}
@end example

@ref{1bd,,ArgumentParser} が、新しい @ref{336e,,Namespace} オブジェクトではなく、既存のオブジェクトに属性を設定する方が良い場合があります。これは @code{namespace=} キーワード引数を指定することで可能です:

@example
>>> class C:
...     pass
...
>>> c = C()
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
>>> c.foo
'BAR'
@end example
@end deffn

@node その他のユーティリティ,例外<11>,parse_args メソッド,argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー
@anchor{library/argparse other-utilities}@anchor{33a9}
@subsubsection その他のユーティリティ


@menu
* Subcommands:: 
* FileType オブジェクト:: 
* 引数グループ:: 
* 相互排他:: 
* パーサーのデフォルト値:: 
* ヘルプの表示:: 
* 部分解析:: 
* ファイル解析のカスタマイズ:: 
* 終了メソッド:: 
* 混在した引数の解析:: 
* Registering custom types or actions:: 

@end menu

@node Subcommands,FileType オブジェクト,,その他のユーティリティ
@anchor{library/argparse subcommands}@anchor{33aa}
@subsubsection Subcommands


@geindex add_subparsers() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser add_subparsers}@anchor{e11}
@deffn {メソッド} ArgumentParser.add_subparsers (*[, title][, description][, prog][, parser_class][, action][, dest][, required][, help][, metavar])

Many programs split up their functionality into a number of subcommands,
for example, the @code{svn} program can invoke subcommands like @code{svn
checkout}, @code{svn update}, and @code{svn commit}.  Splitting up functionality
this way can be a particularly good idea when a program performs several
different functions which require different kinds of command-line arguments.
@ref{1bd,,ArgumentParser} supports the creation of such subcommands with the
@code{add_subparsers()} method.  The @code{add_subparsers()} method is normally
called with no arguments and returns a special action object.  This object
has a single method, @code{add_parser()}, which takes a
command name and any @code{ArgumentParser} constructor arguments, and
returns an @code{ArgumentParser} object that can be modified as usual.

引数の説明:


@itemize *

@item 
`title' - title for the sub-parser group in help output; by default
"subcommands" if description is provided, otherwise uses title for
positional arguments

@item 
`description' - description for the sub-parser group in help output, by
default @code{None}

@item 
`prog' - usage information that will be displayed with subcommand help,
by default the name of the program and any positional arguments before the
subparser argument

@item 
`parser_class' - class which will be used to create sub-parser instances, by
default the class of the current parser (e.g. @ref{1bd,,ArgumentParser})

@item 
@ref{192b,,action} - コマンドラインにこの引数があったときの基本のアクション。

@item 
@ref{3384,,dest} - name of the attribute under which subcommand name will be
stored; by default @code{None} and no value is stored

@item 
@ref{338a,,required} - サブコマンドが必須であるかどうかを指定し、デフォルトは @code{False} です。(3.7 より追加)

@item 
@ref{338b,,help} - ヘルプ出力に表示されるサブパーサーグループのヘルプです。デフォルトは @code{None} です

@item 
@ref{338c,,metavar} - string presenting available subcommands in help; by default it
is @code{None} and presents subcommands in form @{cmd1, cmd2, ..@}
@end itemize

いくつかの使用例:

@example
>>> # create the top-level parser
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='subcommand 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=('X', 'Y', 'Z'), help='baz help')
>>>
>>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)
@end example

@ref{336d,,parse_args()} が返すオブジェクトにはメインパーサーとコマンドラインで選択されたサブパーサーによる属性だけが設定されており、選択されなかったサブコマンドのパーサーの属性が設定されていないことに注意してください。このため、上の例では、@code{a} コマンドが指定されたときは @code{foo}, @code{bar} 属性だけが存在し、@code{b} コマンドが指定されたときは @code{foo}, @code{baz} 属性だけが存在しています。

同じように、サブパーサーにヘルプメッセージが要求された場合は、そのパーサーに対するヘルプだけが表示されます。ヘルプメッセージには親パーサーや兄弟パーサーのヘルプメッセージを表示しません。 (ただし、各サブパーサーコマンドのヘルプメッセージは、上の例にもあるように @code{add_parser()} の @code{help=} 引数によって指定できます)

@example
>>> parser.parse_args(['--help'])
usage: PROG [-h] [--foo] @{a,b@} ...

positional arguments:
  @{a,b@}   subcommand help
    a     a help
    b     b help

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

options:
  -h, --help  show this help message and exit

>>> parser.parse_args(['b', '--help'])
usage: PROG b [-h] [--baz @{X,Y,Z@}]

options:
  -h, --help     show this help message and exit
  --baz @{X,Y,Z@}  baz help
@end example

@ref{e11,,add_subparsers()} メソッドは @code{title} と @code{description} キーワード引数もサポートしています。どちらかが存在する場合、サブパーサーのコマンドはヘルプ出力でそれぞれのグループの中に表示されます。例えば:

@example
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title='subcommands',
...                                    description='valid subcommands',
...                                    help='additional help')
>>> subparsers.add_parser('foo')
>>> subparsers.add_parser('bar')
>>> parser.parse_args(['-h'])
usage:  [-h] @{foo,bar@} ...

options:
  -h, --help  show this help message and exit

subcommands:
  valid subcommands

  @{foo,bar@}   additional help
@end example

Furthermore, @code{add_parser()} supports an additional
`aliases' argument,
which allows multiple strings to refer to the same subparser. This example,
like @code{svn}, aliases @code{co} as a shorthand for @code{checkout}:

@example
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>> checkout = subparsers.add_parser('checkout', aliases=['co'])
>>> checkout.add_argument('foo')
>>> parser.parse_args(['co', 'bar'])
Namespace(foo='bar')
@end example

@code{add_parser()} supports also an additional
`deprecated' argument, which allows to deprecate the subparser.

@example
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='chicken.py')
>>> subparsers = parser.add_subparsers()
>>> run = subparsers.add_parser('run')
>>> fly = subparsers.add_parser('fly', deprecated=True)
>>> parser.parse_args(['fly'])
chicken.py: warning: command 'fly' is deprecated
Namespace()
@end example


Added in version 3.13.


One particularly effective way of handling subcommands is to combine the use
of the @ref{e11,,add_subparsers()} method with calls to @ref{3386,,set_defaults()} so
that each subparser knows which Python function it should execute.  For
example:

@example
>>> # subcommand 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(required=True)
>>>
>>> # create the parser for the "foo" command
>>> parser_foo = subparsers.add_parser('foo')
>>> parser_foo.add_argument('-x', type=int, default=1)
>>> parser_foo.add_argument('y', type=float)
>>> parser_foo.set_defaults(func=foo)
>>>
>>> # create the parser for the "bar" command
>>> parser_bar = subparsers.add_parser('bar')
>>> parser_bar.add_argument('z')
>>> parser_bar.set_defaults(func=bar)
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('foo 1 -x 2'.split())
>>> args.func(args)
2.0
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('bar XYZYX'.split())
>>> args.func(args)
((XYZYX))
@end example

こうすると、@ref{336d,,parse_args()} が引数の解析が終わってから適切な関数を呼び出すようになります。このように関数をアクションに関連付けるのは一般的にサブパーサーごとに異なるアクションを扱うもっとも簡単な方法です。ただし、実行されたサブパーサーの名前を確認する必要がある場合は、@ref{e11,,add_subparsers()} を呼び出すときに @code{dest} キーワードを指定できます:

@example
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(dest='subparser_name')
>>> subparser1 = subparsers.add_parser('1')
>>> subparser1.add_argument('-x')
>>> subparser2 = subparsers.add_parser('2')
>>> subparser2.add_argument('y')
>>> parser.parse_args(['2', 'frobble'])
Namespace(subparser_name='2', y='frobble')
@end example


バージョン 3.7 で変更: New `required' keyword-only parameter.



バージョン 3.14 で変更: Subparser's `prog' is no longer affected by a custom usage message in
the main parser.

@end deffn

@node FileType オブジェクト,引数グループ,Subcommands,その他のユーティリティ
@anchor{library/argparse filetype-objects}@anchor{33ab}
@subsubsection FileType オブジェクト


@geindex FileType (argparse のクラス)
@anchor{library/argparse argparse FileType}@anchor{30c}
@deffn {クラス} argparse.FileType (mode='r', bufsize=-1, encoding=None, errors=None)

@ref{30c,,FileType} ファクトリは @ref{4bc,,ArgumentParser.add_argument()} の type 引数に渡すことができるオブジェクトを生成します。 type が @ref{30c,,FileType} オブジェクトである引数はコマンドライン引数を、指定されたモード、バッファーサイズ、エンコーディング、エラー処理でファイルとして開きます (詳細は @ref{316,,open()} 関数を参照してください。):

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)
@end example

FileType オブジェクトは擬似引数 @code{'-'} を識別し、読み込み用の @ref{30c,,FileType} であれば @ref{75f,,sys.stdin} を、書き込み用の @ref{30c,,FileType} であれば @ref{ccd,,sys.stdout} に変換します:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', type=argparse.FileType('r'))
>>> parser.parse_args(['-'])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
@end example

@cartouche
@quotation 注釈 
If one argument uses `FileType' and then a subsequent argument fails,
an error is reported but the file is not automatically closed.
This can also clobber the output files.
In this case, it would be better to wait until after the parser has
run and then use the @ref{186,,with}-statement to manage the files.
@end quotation
@end cartouche


バージョン 3.4 で変更: `encodings' と `errors' がパラメータに追加されました。



バージョン 3.14 で非推奨.

@end deffn

@node 引数グループ,相互排他,FileType オブジェクト,その他のユーティリティ
@anchor{library/argparse argument-groups}@anchor{33ac}
@subsubsection 引数グループ


@geindex add_argument_group() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser add_argument_group}@anchor{2eb}
@deffn {メソッド} ArgumentParser.add_argument_group (title=None, description=None, *[, argument_default][, conflict_handler])

By default, @ref{1bd,,ArgumentParser} groups command-line arguments into
"positional arguments" and "options" when displaying help
messages. When there is a better conceptual grouping of arguments than this
default one, appropriate groups can be created using the
@code{add_argument_group()} method:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group = parser.add_argument_group('group')
>>> group.add_argument('--foo', help='foo help')
>>> group.add_argument('bar', help='bar help')
>>> parser.print_help()
usage: PROG [--foo FOO] bar

group:
  bar    bar help
  --foo FOO  foo help
@end example

The @ref{2eb,,add_argument_group()} method returns an argument group object which
has an @ref{4bc,,add_argument()} method just like a regular
@ref{1bd,,ArgumentParser}.  When an argument is added to the group, the parser
treats it just like a normal argument, but displays the argument in a
separate group for help messages.  The @code{add_argument_group()} method
accepts `title' and `description' arguments which can be used to
customize this display:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group1 = parser.add_argument_group('group1', 'group1 description')
>>> group1.add_argument('foo', help='foo help')
>>> group2 = parser.add_argument_group('group2', 'group2 description')
>>> group2.add_argument('--bar', help='bar help')
>>> parser.print_help()
usage: PROG [--bar BAR] foo

group1:
  group1 description

  foo    foo help

group2:
  group2 description

  --bar BAR  bar help
@end example

The optional, keyword-only parameters @ref{3377,,argument_default} and @ref{3378,,conflict_handler}
allow for finer-grained control of the behavior of the argument group. These
parameters have the same meaning as in the @ref{1bd,,ArgumentParser} constructor,
but apply specifically to the argument group rather than the entire parser.

ユーザー定義グループにないすべての引数は通常の "位置引数" と "オプション引数" セクションに表示されます。


Deprecated since version 3.11, removed in version 3.14: Calling @ref{2eb,,add_argument_group()} on an argument group now raises an
exception. This nesting was never supported, often failed to work
correctly, and was unintentionally exposed through inheritance.



バージョン 3.14 で非推奨: Passing @ref{3375,,prefix_chars} to @ref{2eb,,add_argument_group()}
is now deprecated.

@end deffn

@node 相互排他,パーサーのデフォルト値,引数グループ,その他のユーティリティ
@anchor{library/argparse mutual-exclusion}@anchor{33ad}
@subsubsection 相互排他


@geindex add_mutually_exclusive_group() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser add_mutually_exclusive_group}@anchor{2ed}
@deffn {メソッド} ArgumentParser.add_mutually_exclusive_group (required=False)

Create a mutually exclusive group. @code{argparse} will make sure that only
one of the arguments in the mutually exclusive group was present on the
command line:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo
@end example

@ref{2ed,,add_mutually_exclusive_group()} メソッドの引数 `required' に True 値を指定すると、その相互排他引数のどれか1つを選ぶことが要求されます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args([])
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required
@end example

Note that currently mutually exclusive argument groups do not support the
`title' and `description' arguments of
@ref{2eb,,add_argument_group()}. However, a mutually exclusive
group can be added to an argument group that has a title and description.
For example:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_argument_group('Group title', 'Group description')
>>> exclusive_group = group.add_mutually_exclusive_group(required=True)
>>> exclusive_group.add_argument('--foo', help='foo help')
>>> exclusive_group.add_argument('--bar', help='bar help')
>>> parser.print_help()
usage: PROG [-h] (--foo FOO | --bar BAR)

options:
  -h, --help  show this help message and exit

Group title:
  Group description

  --foo FOO   foo help
  --bar BAR   bar help
@end example


Deprecated since version 3.11, removed in version 3.14: Calling @ref{2eb,,add_argument_group()} or @ref{2ed,,add_mutually_exclusive_group()}
on a mutually exclusive group now raises an exception. This nesting was
never supported, often failed to work correctly, and was unintentionally
exposed through inheritance.

@end deffn

@node パーサーのデフォルト値,ヘルプの表示,相互排他,その他のユーティリティ
@anchor{library/argparse parser-defaults}@anchor{33ae}
@subsubsection パーサーのデフォルト値


@geindex set_defaults() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser set_defaults}@anchor{3386}
@deffn {メソッド} ArgumentParser.set_defaults (**kwargs)

ほとんどの場合、 @ref{336d,,parse_args()} が返すオブジェクトの属性はコマンドライン引数の内容と引数のアクションによってのみ決定されます。 @ref{3386,,set_defaults()} を使うと与えられたコマンドライン引数の内容によらず追加の属性を決定することが可能です:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.set_defaults(bar=42, baz='badger')
>>> parser.parse_args(['736'])
Namespace(bar=42, baz='badger', foo=736)
@end example

Note that defaults can be set at both the parser level using @ref{3386,,set_defaults()}
and at the argument level using @ref{4bc,,add_argument()}. If both are called for the
same argument, the last default set for an argument is used:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='bar')
>>> parser.set_defaults(foo='spam')
>>> parser.parse_args([])
Namespace(foo='spam')
@end example

パーサーレベルの default は、複数のパーサーを扱うときに特に便利です。このタイプの例については @ref{e11,,add_subparsers()} メソッドを参照してください。
@end deffn

@geindex get_default() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser get_default}@anchor{33af}
@deffn {メソッド} ArgumentParser.get_default (dest)

@ref{4bc,,add_argument()} か @ref{3386,,set_defaults()} によって指定された、 namespace の属性のデフォルト値を取得します:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='badger')
>>> parser.get_default('foo')
'badger'
@end example
@end deffn

@node ヘルプの表示,部分解析,パーサーのデフォルト値,その他のユーティリティ
@anchor{library/argparse printing-help}@anchor{33b0}
@subsubsection ヘルプの表示


ほとんどの典型的なアプリケーションでは、@ref{336d,,parse_args()} が使用法やエラーメッセージのフォーマットと表示について面倒を見ます。しかし、いくつかのフォーマットメソッドが利用できます:

@geindex print_usage() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser print_usage}@anchor{33b1}
@deffn {メソッド} ArgumentParser.print_usage (file=None)

@ref{1bd,,ArgumentParser} がコマンドラインからどう実行されるべきかの短い説明を表示します。 `file' が @code{None} の時は、 @ref{ccd,,sys.stdout} に出力されます。
@end deffn

@geindex print_help() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser print_help}@anchor{33b2}
@deffn {メソッド} ArgumentParser.print_help (file=None)

プログラムの使用法と @ref{1bd,,ArgumentParser} に登録された引数についての情報を含むヘルプメッセージを表示します。 `file' が @code{None} の時は、 @ref{ccd,,sys.stdout} に出力されます。
@end deffn

これらのメソッドの、表示する代わりにシンプルに文字列を返すバージョンもあります:

@geindex format_usage() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser format_usage}@anchor{1db0}
@deffn {メソッド} ArgumentParser.format_usage ()

@ref{1bd,,ArgumentParser} がコマンドラインからどう実行されるべきかの短い説明を格納した文字列を返します。
@end deffn

@geindex format_help() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser format_help}@anchor{33b3}
@deffn {メソッド} ArgumentParser.format_help ()

プログラムの使用法と @ref{1bd,,ArgumentParser} に登録された引数についての情報を含むヘルプメッセージを格納した文字列を返します。
@end deffn

@node 部分解析,ファイル解析のカスタマイズ,ヘルプの表示,その他のユーティリティ
@anchor{library/argparse partial-parsing}@anchor{33b4}
@subsubsection 部分解析


@geindex parse_known_args() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser parse_known_args}@anchor{33b5}
@deffn {メソッド} ArgumentParser.parse_known_args (args=None, namespace=None)

Sometimes a script only needs to handle a specific set of command-line
arguments, leaving any unrecognized arguments for another script or program.
In these cases, the @ref{33b5,,parse_known_args()} method can be
useful.

This method works similarly to @ref{336d,,parse_args()}, but it does
not raise an error for extra, unrecognized arguments. Instead, it parses the
known arguments and returns a two item tuple that contains the populated
namespace and the list of any unrecognized arguments.

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('bar')
>>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
@end example
@end deffn

@cartouche
@quotation 警告 
@ref{fbf,,先頭文字でのマッチング} ルールは @ref{33b5,,parse_known_args()} にも適用されます。たとえ既知のオプションの先頭文字に過ぎない場合でも、パーサは引数リストに残さずに、オプションを受け取る場合があります。
@end quotation
@end cartouche

@node ファイル解析のカスタマイズ,終了メソッド,部分解析,その他のユーティリティ
@anchor{library/argparse customizing-file-parsing}@anchor{33b6}
@subsubsection ファイル解析のカスタマイズ


@geindex convert_arg_line_to_args() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser convert_arg_line_to_args}@anchor{3385}
@deffn {メソッド} ArgumentParser.convert_arg_line_to_args (arg_line)

ファイルから引数を読み込む場合 (@ref{1bd,,ArgumentParser} コンストラクターの `fromfile_prefix_chars' キーワード引数を参照)、1行につき1つの引数を読み込みます。 @ref{3385,,convert_arg_line_to_args()} を変更することでこの動作をカスタマイズできます。

このメソッドは、引数ファイルから読まれた文字列である1つの引数 `arg_line' を受け取ります。そしてその文字列を解析した結果の引数のリストを返します。このメソッドはファイルから1行読みこむごとに、順番に呼ばれます。

このメソッドをオーバーライドすると便利なこととして、スペースで区切られた行の単語1つ1つを別々の引数として扱えます。次の例でその方法を示します:

@example
class MyArgumentParser(argparse.ArgumentParser):
    def convert_arg_line_to_args(self, arg_line):
        return arg_line.split()
@end example
@end deffn

@node 終了メソッド,混在した引数の解析,ファイル解析のカスタマイズ,その他のユーティリティ
@anchor{library/argparse exiting-methods}@anchor{33b7}
@subsubsection 終了メソッド


@geindex exit() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser exit}@anchor{33b8}
@deffn {メソッド} ArgumentParser.exit (status=0, message=None)

This method terminates the program, exiting with the specified `status'
and, if given, it prints a `message' to @ref{b33,,sys.stderr} before that.
The user can override this method to handle these steps differently:

@example
class ErrorCatchingArgumentParser(argparse.ArgumentParser):
    def exit(self, status=0, message=None):
        if status:
            raise Exception(f'Exiting because of an error: @{message@}')
        exit(status)
@end example
@end deffn

@geindex error() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser error}@anchor{33b9}
@deffn {メソッド} ArgumentParser.error (message)

This method prints a usage message, including the `message', to
@ref{b33,,sys.stderr} and terminates the program with a status code of 2.
@end deffn

@node 混在した引数の解析,Registering custom types or actions,終了メソッド,その他のユーティリティ
@anchor{library/argparse intermixed-parsing}@anchor{33ba}
@subsubsection 混在した引数の解析


@geindex parse_intermixed_args() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser parse_intermixed_args}@anchor{cf7}
@deffn {メソッド} ArgumentParser.parse_intermixed_args (args=None, namespace=None)
@end deffn

@geindex parse_known_intermixed_args() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser parse_known_intermixed_args}@anchor{33bb}
@deffn {メソッド} ArgumentParser.parse_known_intermixed_args (args=None, namespace=None)

多くの Unix コマンドは、オプション引数と位置引数を混在させることを許しています。 @ref{cf7,,parse_intermixed_args()} と @ref{33bb,,parse_known_intermixed_args()} メソッドは、このような方法での解析をサポートしています。

These parsers do not support all the @code{argparse} features, and will raise
exceptions if unsupported features are used.  In particular, subparsers,
and mutually exclusive groups that include both
optionals and positionals are not supported.

この例は、@ref{33b5,,parse_known_args()} と @ref{cf7,,parse_intermixed_args()} の違いを表しています: 前者は @code{['2', '3']} を、解析されない引数として返し、後者は全ての位置引数を @code{rest} に入れて返しています:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('cmd')
>>> parser.add_argument('rest', nargs='*', type=int)
>>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
>>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])
@end example

@ref{33bb,,parse_known_intermixed_args()} は、解析した内容を含む名前空間と、残りの引数を含んだリストの、2つの要素を持つタプルを返します。
@ref{cf7,,parse_intermixed_args()} は、解析されない引数が残された場合にはエラーを送出します。


Added in version 3.7.

@end deffn

@node Registering custom types or actions,,混在した引数の解析,その他のユーティリティ
@anchor{library/argparse registering-custom-types-or-actions}@anchor{33bc}
@subsubsection Registering custom types or actions


@geindex register() (argparse.ArgumentParser のメソッド)
@anchor{library/argparse argparse ArgumentParser register}@anchor{3390}
@deffn {メソッド} ArgumentParser.register (registry_name, value, object)

Sometimes it's desirable to use a custom string in error messages to provide
more user-friendly output. In these cases, @code{register()} can be used to
register custom actions or types with a parser and allow you to reference the
type by their registered name instead of their callable name.

The @code{register()} method accepts three arguments - a `registry_name',
specifying the internal registry where the object will be stored (e.g.,
@code{action}, @code{type}), `value', which is the key under which the object will
be registered, and object, the callable to be registered.

The following example shows how to register a custom type with a parser:

@example
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.register('type', 'hexadecimal integer', lambda s: int(s, 16))
>>> parser.add_argument('--foo', type='hexadecimal integer')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type='hexadecimal integer', choices=None, required=False, help=None, metavar=None, deprecated=False)
>>> parser.parse_args(['--foo', '0xFA'])
Namespace(foo=250)
>>> parser.parse_args(['--foo', '1.2'])
usage: PROG [-h] [--foo FOO]
PROG: error: argument --foo: invalid 'hexadecimal integer' value: '1.2'
@end example
@end deffn

@node 例外<11>,,その他のユーティリティ,argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー
@anchor{library/argparse exceptions}@anchor{33bd}
@subsubsection 例外


@geindex ArgumentError
@anchor{library/argparse argparse ArgumentError}@anchor{33be}
@deffn {例外} argparse.ArgumentError

引数 (オプション引数または位置引数) の生成時または利用時のエラーです。

この例外の文字列表現は、エラーの原因となった引数についての情報を補足するメッセージです。
@end deffn

@geindex ArgumentTypeError
@anchor{library/argparse argparse ArgumentTypeError}@anchor{3396}
@deffn {例外} argparse.ArgumentTypeError

コマンドラインの文字列を、指定された型に変換するのに失敗した時に送出されます。
@end deffn

@subsubheading ガイドとチュートリアル


@menu
* Argparse チュートリアル:: 
* Migrating optparse code to argparse:: 

@end menu

@node Argparse チュートリアル,Migrating optparse code to argparse,,例外<11>
@anchor{howto/argparse doc}@anchor{33bf}@anchor{howto/argparse argparse-tutorial}@anchor{336c}@anchor{howto/argparse id1}@anchor{33c0}
@subsubsection Argparse チュートリアル


@*author: 
Tshepang Mbambo


このチュートリアルでは、@ref{7,,argparse} を丁寧に説明します。@ref{7,,argparse} は、Python 標準ライブラリの一部であり、おすすめのコマンドライン引数の解析モジュールです。

@cartouche
@quotation 注釈 
The standard library includes two other libraries directly related
to command-line parameter processing: the lower level @ref{a4,,optparse}
module (which may require more code to configure for a given application,
but also allows an application to request behaviors that @code{argparse}
doesn't support), and the very low level @ref{65,,getopt} (which specifically
serves as an equivalent to the @code{getopt()} family of functions
available to C programmers).
While neither of those modules is covered directly in this guide, many of
the core concepts in @code{argparse} first originated in @code{optparse}, so
some aspects of this tutorial will also be relevant to @code{optparse} users.
@end quotation
@end cartouche

@menu
* コンセプト:: 
* 基礎:: 
* 位置引数の入門:: 
* Optional引数の導入:: 
* 位置引数とOptional引数の併用:: 
* もうちょっとだけ学ぶ:: 
* argparse の出力を翻訳するには:: 
* Custom type converters:: 
* 結び:: 

@end menu

@node コンセプト,基礎,,Argparse チュートリアル
@anchor{howto/argparse concepts}@anchor{33c1}
@subsubsection コンセプト


@code{ls} コマンドを使って、このチュートリアルで私たちが学ぶ機能をいくつか見てみましょう:

@example
$ ls
cpython  devguide  prog.py  pypy  rm-unused-function.patch
$ ls pypy
ctypes_configure  demo  dotviewer  include  lib_pypy  lib-python ...
$ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x  4 wena wena 4096 Feb  8 12:04 devguide
-rwxr-xr-x  1 wena wena  535 Feb 19 00:05 prog.py
drwxr-xr-x 14 wena wena 4096 Feb  7 00:59 pypy
-rw-r--r--  1 wena wena  741 Feb 18 01:01 rm-unused-function.patch
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
...
@end example

上の４つの実行結果から、以下のことが分かります:


@itemize *

@item 
@code{ls} コマンドは、まったくオプションを指定せずに実行したとしても役に立ちます。デフォルトの動作は、カレントディレクトリの内容を表示することです。

@item 
デフォルトの動作で提供される以上のことをしたい場合、すこしだけオプションを指定する必要があります。別のディレクトリ @code{pypy} を表示したい場合、私たちがしたことは、位置引数として知られる引数を指定することです。これは、引数がコマンドラインのどの位置に現れたかということだけを基に、プログラムがその値について何をするのか分かるべきなので、このように名づけられています。このコンセプトは @code{cp} のようなコマンドで重要な意味があります。 @code{cp} コマンドのもっとも基本的な使い方は、 @code{cp SRC DEST} です。最初の引数は `何をコピーしたいか' であり、二つ目の引数は `どこにコピーしたいか' を意味します。

@item 
プログラムの振る舞いを変えましょう。例では、単にファイル名を表示する代わりにそれぞれのファイルに関する多くの情報を表示します。このケースでは、@code{-l} はoptional引数として知られます。

@item 
ヘルプテキストの抜粋です。この実行の仕方は、まだ使用したことがないプログラムにたいして行うと有用で、ヘルプテキストを読むことで、プログラムがどのように動作するかわかります。
@end itemize

@node 基礎,位置引数の入門,コンセプト,Argparse チュートリアル
@anchor{howto/argparse the-basics}@anchor{33c2}
@subsubsection 基礎


（ほとんど）何もしない、とても簡単な例から始めましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
@end example

下記がこのコードを実行した結果です:

@example
$ python prog.py
$ python prog.py --help
usage: prog.py [-h]

options:
  -h, --help  show this help message and exit
$ python prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo
@end example

こんなことが起こりました:


@itemize *

@item 
オプションなしでスクリプトを実行した結果、なにも標準出力に表示されませんでした。それほど便利ではありませんね。

@item 
二つ目の実行結果から @ref{7,,argparse} モジュールの有用性がわかります。ほとんど何もしていないのに、すてきなヘルプメッセージが手に入りました。

@item 
@code{--help} （これは @code{-h} と短縮できます）だけが無料のオプションです（つまりプログラムで指示する必要はありません）。他のオプションを指定するとエラーになります。エラー時の有用な用法メッセージも、プログラムで指示することなく出力できます。
@end itemize

@node 位置引数の入門,Optional引数の導入,基礎,Argparse チュートリアル
@anchor{howto/argparse introducing-positional-arguments}@anchor{33c3}
@subsubsection 位置引数の入門


以下に例を示します:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)
@end example

このコードを実行してみましょう:

@example
$ python prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
$ python prog.py --help
usage: prog.py [-h] echo

positional arguments:
  echo

options:
  -h, --help  show this help message and exit
$ python prog.py foo
foo
@end example

こんなことが起こりました:


@itemize *

@item 
プログラムが受け付けるコマンドラインオプションを指定するメソッドである @ref{4bc,,add_argument()} を追加しました。ここでは、その機能にあわせて引数名を @code{echo} としました。

@item 
プログラムを実行すると、オプションを指定するように要求されます。

@item 
@ref{336d,,parse_args()} メソッドは指定されたオプションを、この場合は @code{echo} として、返します。

@item 
この変数は @ref{7,,argparse} が自動的に行うある種の魔法です（つまり、値を格納する変数を指定する必要がありません）。変数の名前がメソッドに与えた文字列引数 @code{echo} と同じことに気付いたでしょう。
@end itemize

ヘルプメッセージは十分なように見えますが、それほど分かりやすくもありません。たとえば、@code{echo} は位置引数であることがわかりますが、それが何であるかを知るためには推測するかソースコードを見なけれなりません。もうすこしヘルプメッセージ分かりやすくしてみましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)
@end example

修正した結果は以下のようになります:

@example
$ python prog.py -h
usage: prog.py [-h] echo

positional arguments:
  echo        echo the string you use here

options:
  -h, --help  show this help message and exit
@end example

次は、もっと有益なことをしてみませんか？:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)
@end example

下記がこのコードを実行した結果です:

@example
$ python prog.py 4
Traceback (most recent call last):
  File "prog.py", line 5, in <module>
    print(args.square**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
@end example

上手くいきませんでした。 何も伝えなければ、@ref{7,,argparse} は与えられたオプションを文字列として扱います。 @ref{7,,argparse} にオプションの値を整数として扱うように伝えましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type=int)
args = parser.parse_args()
print(args.square**2)
@end example

下記がこのコードを実行した結果です:

@example
$ python prog.py 4
16
$ python prog.py four
usage: prog.py [-h] square
prog.py: error: argument square: invalid int value: 'four'
@end example

今度は上手くいきました。このプログラムは不正な入力が与えられるとそれを処理せずに、より親切なメッセージを表示して実行を終了します。

@node Optional引数の導入,位置引数とOptional引数の併用,位置引数の入門,Argparse チュートリアル
@anchor{howto/argparse introducing-optional-arguments}@anchor{33c4}
@subsubsection Optional引数の導入


ここまで位置引数を扱ってきました。optional引数を追加する方法についても見ていきましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
    print("verbosity turned on")
@end example

実行してみましょう:

@example
$ python prog.py --verbosity 1
verbosity turned on
$ python prog.py
$ python prog.py --help
usage: prog.py [-h] [--verbosity VERBOSITY]

options:
  -h, --help            show this help message and exit
  --verbosity VERBOSITY
                        increase output verbosity
$ python prog.py --verbosity
usage: prog.py [-h] [--verbosity VERBOSITY]
prog.py: error: argument --verbosity: expected one argument
@end example

こんなことが起こりました:


@itemize *

@item 
プログラムは、@code{--verbosity} が指定された場合はなにかしらを表示し、指定されなければ何も表示をしないように書かれています。

@item 
オプションの指定が実際に任意であることを示すために、プログラムをオプション指定なしで実行してもエラーにはなっていません。オプション引数が指定されなかった場合、関連する変数、この例では @code{args.verbosity} 、の値にはデフォルトで @code{None} がセットされます。これが @ref{181,,if} 文による真偽テストに失敗した理由です。

@item 
ヘルプメッセージが少し変わりました。

@item 
@code{--verbosity} オプションを使うには、そのオプションにひとつの値を指定しなければなりません。
@end itemize

上記の例では、@code{--verbosity} に任意の整数を取れます。この簡単なプログラムでは、実際には @code{True} または @code{False} の二つの値だけが有効です。そうなるようにコードを修正してみましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")
@end example

実行してみましょう:

@example
$ python prog.py --verbose
verbosity turned on
$ python prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python prog.py --help
usage: prog.py [-h] [--verbose]

options:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity
@end example

こんなことが起こりました:


@itemize *

@item 
オプションは値を必要とするのではなく、単なるフラグになりました。この考え方に沿うようにオプションの名前も変更しています。ここで新しいキーワード @code{action} を指定し、値として @code{"store_true"} を設定していることに注意してください。これは、オプションが指定された場合に値として @code{True} を @code{args.verbose} に設定するということを意味します。オプションの指定がない場合の値は @code{False} となることを意味します。

@item 
フラグは値を取るべきではないので、値を指定するとプログラムはエラーになります。

@item 
ヘルプテキストが変わっています。
@end itemize

@menu
* 短いオプション:: 

@end menu

@node 短いオプション,,,Optional引数の導入
@anchor{howto/argparse short-options}@anchor{33c5}
@subsubsection 短いオプション


コマンドラインになれていれば、オプションの短いバージョンの話題に触れていないことに気付いたでしょう。それはとても簡単です:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")
@end example

上記のプログラムを実行するとこうなります:

@example
$ python prog.py -v
verbosity turned on
$ python prog.py --help
usage: prog.py [-h] [-v]

options:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity
@end example

新しい機能がヘルプテキストにも反映されている点に気付いたでしょう。

@node 位置引数とOptional引数の併用,もうちょっとだけ学ぶ,Optional引数の導入,Argparse チュートリアル
@anchor{howto/argparse combining-positional-and-optional-arguments}@anchor{33c6}
@subsubsection 位置引数とOptional引数の併用


プログラムが複雑になってきました:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
    print(f"the square of @{args.square@} equals @{answer@}")
else:
    print(answer)
@end example

出力は以下のようになります:

@example
$ python prog.py
usage: prog.py [-h] [-v] square
prog.py: error: the following arguments are required: square
$ python prog.py 4
16
$ python prog.py 4 --verbose
the square of 4 equals 16
$ python prog.py --verbose 4
the square of 4 equals 16
@end example


@itemize *

@item 
位置引数を元に戻したので、引数を指定しないとエラーになりました。

@item 
２つのオプションの順序を考慮しないことに注意してください。
@end itemize

複数の詳細レベルを値にとれるようにプログラムを元に戻して、指定された値を使ってみましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print(f"the square of @{args.square@} equals @{answer@}")
elif args.verbosity == 1:
    print(f"@{args.square@}^2 == @{answer@}")
else:
    print(answer)
@end example

実行してみましょう:

@example
$ python prog.py 4
16
$ python prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py 4 -v 1
4^2 == 16
$ python prog.py 4 -v 2
the square of 4 equals 16
$ python prog.py 4 -v 3
16
@end example

プログラムのバグである最後の結果を除いて、上手く行っているようです。このバグを、@code{--verbosity} オプションが取れる値を制限することで修正しましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print(f"the square of @{args.square@} equals @{answer@}")
elif args.verbosity == 1:
    print(f"@{args.square@}^2 == @{answer@}")
else:
    print(answer)
@end example

実行してみましょう:

@example
$ python 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)
$ python prog.py 4 -h
usage: prog.py [-h] [-v @{0,1,2@}] square

positional arguments:
  square                display a square of a given number

options:
  -h, --help            show this help message and exit
  -v, --verbosity @{0,1,2@}
                        increase output verbosity
@end example

変更がエラーメッセージとヘルプメッセージの両方に反映されていることに注意してください。

詳細レベルついて、違ったアプローチを試してみましょう。これは CPython 実行可能ファイルがその詳細レベル引数を扱う方法と同じです。（ @code{python --help} の出力を確認してください）:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display the square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print(f"the square of @{args.square@} equals @{answer@}")
elif args.verbosity == 1:
    print(f"@{args.square@}^2 == @{answer@}")
else:
    print(answer)
@end example

もう一つの action である "count" を紹介します。これは指定されたオプションの出現回数を数えます:

@example
$ python prog.py 4
16
$ python prog.py 4 -v
4^2 == 16
$ python prog.py 4 -vv
the square of 4 equals 16
$ python prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python prog.py 4 -h
usage: prog.py [-h] [-v] square

positional arguments:
  square           display a square of a given number

options:
  -h, --help       show this help message and exit
  -v, --verbosity  increase output verbosity
$ python prog.py 4 -vvv
16
@end example


@itemize *

@item 
前のバージョンのスクリプトのようにフラグ (@code{action="store_true"} に似ています）になりました。エラーとなる理由がわかります。（訳注: ５つ目の例では @code{-v} オプションに引数を与えたため、エラーとなっています。）

@item 
これは"store_true" アクションによく似た動作をします。

@item 
では "count" アクションが何をもたらすかデモンストレーションをします。おそらくこのような使用方法を前に見たことがあるでしょう。

@item 
@code{-v} フラグを指定しなければ、フラグの値は @code{None} とみなされます。

@item 
期待通り、長い形式のフラグを指定しても同じ結果になります。

@item 
残念ながら、このヘルプ出力はプログラムが新しく得た機能についてそこまで有益ではありません。しかし、スクリプトのドキュメンテーションを改善することでいつでも修正することができます（例えば、@code{help} キーワード引数を使用することで）。

@item 
最後の出力はプログラムにバグがあることを示します。
@end itemize

修正しましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2

# bugfix: replace == with >=
if args.verbosity >= 2:
    print(f"the square of @{args.square@} equals @{answer@}")
elif args.verbosity >= 1:
    print(f"@{args.square@}^2 == @{answer@}")
else:
    print(answer)
@end example

これが結果です:

@example
$ python prog.py 4 -vvv
the square of 4 equals 16
$ python prog.py 4 -vvvv
the square of 4 equals 16
$ python prog.py 4
Traceback (most recent call last):
  File "prog.py", line 11, in <module>
    if args.verbosity >= 2:
TypeError: '>=' not supported between instances of 'NoneType' and 'int'
@end example


@itemize *

@item 
最初の出力は上手くいっていますし、以前のバグが修正されています。最も詳細な出力を得るには、2 以上の値が必要です。

@item 
三番目の結果は、よくありません。
@end itemize

このバグを修正しましょう:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity >= 2:
    print(f"the square of @{args.square@} equals @{answer@}")
elif args.verbosity >= 1:
    print(f"@{args.square@}^2 == @{answer@}")
else:
    print(answer)
@end example

もう一つのキーワード引数である @code{default} を導入しました。整数値と比較できるように、その値に @code{0} を設定しました。デフォルトでは、optional 引数が指定されていない場合 @code{None} となること、@code{None} が整数値と比較できない（よって @ref{198,,TypeError} 例外となる）ことを思い出してください。

こうなりました:

@example
$ python prog.py 4
16
@end example

ここまで学んできたことだけで、さまざまな事が実現できます。しかしまだ表面をなぞっただけです。 @ref{7,,argparse} モジュールはとても強力ですので、チュートリアルを終える前にもう少しだけ探検してみましょう.

@node もうちょっとだけ学ぶ,argparse の出力を翻訳するには,位置引数とOptional引数の併用,Argparse チュートリアル
@anchor{howto/argparse getting-a-little-more-advanced}@anchor{33c7}
@subsubsection もうちょっとだけ学ぶ


もし、この小さなプログラムを二乗以外の累乗が行えるように拡張するとどうなるでしょうか:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print(f"@{args.x@} to the power @{args.y@} equals @{answer@}")
elif args.verbosity >= 1:
    print(f"@{args.x@}^@{args.y@} == @{answer@}")
else:
    print(answer)
@end example

出力:

@example
$ python prog.py
usage: prog.py [-h] [-v] x y
prog.py: error: the following arguments are required: x, y
$ python prog.py -h
usage: prog.py [-h] [-v] x y

positional arguments:
  x                the base
  y                the exponent

options:
  -h, --help       show this help message and exit
  -v, --verbosity
$ python prog.py 4 2 -v
4^2 == 16
@end example

これまで、出力されるテキストを `変更する' ために詳細レベルを使ってきました。かわりに下記の例では、`追加の' テキストを出力するのに詳細レベルを使用します:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print(f"Running '@{__file__@}'")
if args.verbosity >= 1:
    print(f"@{args.x@}^@{args.y@} == ", end="")
print(answer)
@end example

出力:

@example
$ python prog.py 4 2
16
$ python prog.py 4 2 -v
4^2 == 16
$ python prog.py 4 2 -vv
Running 'prog.py'
4^2 == 16
@end example

@menu
* 多義性のある引数の指定:: 
* 競合するオプション:: 

@end menu

@node 多義性のある引数の指定,競合するオプション,,もうちょっとだけ学ぶ
@anchor{howto/argparse id2}@anchor{33c8}@anchor{howto/argparse specifying-ambiguous-arguments}@anchor{3392}
@subsubsection 多義性のある引数の指定


ある引数の解釈について、位置引数なのか、ある引数に対する追加の引数なのか、あいまいさがあるときは、 @code{--} を使うことで @ref{336d,,parse_args()} に対してこれ以降は位置引数であることを伝えることができます:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-n', nargs='+')
>>> parser.add_argument('args', nargs='*')

>>> # ambiguous, so parse_args assumes it's an option
>>> parser.parse_args(['-f'])
usage: PROG [-h] [-n N [N ...]] [args ...]
PROG: error: unrecognized arguments: -f

>>> parser.parse_args(['--', '-f'])
Namespace(args=['-f'], n=None)

>>> # ambiguous, so the -n option greedily accepts arguments
>>> parser.parse_args(['-n', '1', '2', '3'])
Namespace(args=[], n=['1', '2', '3'])

>>> parser.parse_args(['-n', '1', '--', '2', '3'])
Namespace(args=['2', '3'], n=['1'])
@end example

@node 競合するオプション,,多義性のある引数の指定,もうちょっとだけ学ぶ
@anchor{howto/argparse conflicting-options}@anchor{33c9}
@subsubsection 競合するオプション


これまでのところ、 @ref{1bd,,argparse.ArgumentParser} インスタンスの2つのメソッドについて学んできました。ここで3つめのメソッドとして @ref{2ed,,add_mutually_exclusive_group()} を導入しましょう。このメソッドは互いに対立する引数の指定を可能にします。また、新しい機能として理解しやすいように、プログラムの残りの部分を変更しましょう: 以下では @code{--quiet} オプションを @code{--verbose} と反対のオプションとして導入します:

@example
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print(f"@{args.x@} to the power @{args.y@} equals @{answer@}")
else:
    print(f"@{args.x@}^@{args.y@} == @{answer@}")
@end example

プログラムはより簡潔になりましたが、デモのための機能が失われました。ともかく下記が実行結果です:

@example
$ python prog.py 4 2
4^2 == 16
$ python prog.py 4 2 -q
16
$ python prog.py 4 2 -v
4 to the power 2 equals 16
$ python 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
$ python prog.py 4 2 -v --quiet
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
@end example

これは分かりやすいでしょう。ここで得たちょっとした柔軟性を示すために最後の出力を追加しました、つまり長い形式のオプションと短い形式のオプションの混在です。

結びの前に、恐らくあなたはプログラムの主な目的をユーザに伝えたいでしょう。万が一、彼らがそれを知らないときに備えて:

@example
import argparse

parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print(f"@{args.x@} to the power @{args.y@} equals @{answer@}")
else:
    print(f"@{args.x@}^@{args.y@} == @{answer@}")
@end example

使用方法のテキストが少し変化しました。@code{[-v | -q]} は @code{-v} または @code{-q} のどちらかを使用できるが、同時に両方を使用できないことを意味します:

@example
$ python 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

options:
  -h, --help     show this help message and exit
  -v, --verbose
  -q, --quiet
@end example

@node argparse の出力を翻訳するには,Custom type converters,もうちょっとだけ学ぶ,Argparse チュートリアル
@anchor{howto/argparse how-to-translate-the-argparse-output}@anchor{33ca}
@subsubsection argparse の出力を翻訳するには


ヘルプテキストやエラーメッセージなどの @ref{7,,argparse} モジュールの出力は、すべて @ref{67,,gettext} モジュールを使って訳せるように作られています。これにより、 @ref{7,,argparse} によって生成されたメッセージを簡単にローカライズできます。 @ref{33cb,,プログラムやモジュールを国際化する} も参照してください。

たとえば、この @ref{7,,argparse} の出力では:

@example
$ python 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

options:
  -h, --help     show this help message and exit
  -v, --verbose
  -q, --quiet
@end example

文字列 @code{usage:}, @code{positional arguments:}, @code{options:} と @code{show this help message and exit} はすべて訳せます。

これらの文字列を訳すには、それらをまず @code{.po} ファイルに抽出する必要があります。たとえば、 Babel@footnote{https://babel.pocoo.org/} を使い、次のコマンドを実行します。

@example
$ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py
@end example

このコマンドは @ref{7,,argparse} モジュールからすべての翻訳可能な文字列を抽出し、それらを @code{messages.po} という名前のファイルに出力します。このコマンドは Python のインストールが @code{/usr/lib} にあることを前提としています。

システム上の @ref{7,,argparse} モジュールの場所は、次のスクリプトで調べられます:

@example
import argparse
print(argparse.__file__)
@end example

@code{.po} ファイル内のメッセージが訳され、その訳が @ref{67,,gettext} を用いてインストールされると、 @ref{7,,argparse} は翻訳されたメッセージを表示できるようになります。

@ref{7,,argparse} 出力内のあなたの文字列を翻訳するには、 @ref{67,,gettext} を使います。

@node Custom type converters,結び,argparse の出力を翻訳するには,Argparse チュートリアル
@anchor{howto/argparse custom-type-converters}@anchor{33cc}
@subsubsection Custom type converters


The @ref{7,,argparse} module allows you to specify custom type converters for
your command-line arguments. This allows you to modify user input before it's
stored in the @ref{336e,,argparse.Namespace}. This can be useful when you need to
pre-process the input before it is used in your program.

When using a custom type converter, you can use any callable that takes a
single string argument (the argument value) and returns the converted value.
However, if you need to handle more complex scenarios, you can use a custom
action class with the `action' parameter instead.

For example, let's say you want to handle arguments with different prefixes and
process them accordingly:

@example
import argparse

parser = argparse.ArgumentParser(prefix_chars='-+')

parser.add_argument('-a', metavar='<value>', action='append',
                    type=lambda x: ('-', x))
parser.add_argument('+a', metavar='<value>', action='append',
                    type=lambda x: ('+', x))

args = parser.parse_args()
print(args)
@end example

出力:

@example
$ python prog.py -a value1 +a value2
Namespace(a=[('-', 'value1'), ('+', 'value2')])
@end example

In this example, we:


@itemize *

@item 
Created a parser with custom prefix characters using the @code{prefix_chars}
parameter.

@item 
Defined two arguments, @code{-a} and @code{+a}, which used the @code{type} parameter to
create custom type converters to store the value in a tuple with the prefix.
@end itemize

Without the custom type converters, the arguments would have treated the @code{-a}
and @code{+a} as the same argument, which would have been undesirable. By using custom
type converters, we were able to differentiate between the two arguments.

@node 結び,,Custom type converters,Argparse チュートリアル
@anchor{howto/argparse conclusion}@anchor{33cd}
@subsubsection 結び


@ref{7,,argparse} モジュールはここで学んだことより多くの機能を提供します。モジュールのドキュメントはとても詳細で、綿密で、そしてたくさんの例があります。このチュートリアルの体験したことで、気がめいることなくそれらの他の機能を会得できるに違いありません。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)
@anchor{howto/argparse-optparse upgrading-optparse-code}@anchor{13c6}
@node Migrating optparse code to argparse,,Argparse チュートリアル,例外<11>
@anchor{howto/argparse-optparse doc}@anchor{33ce}@anchor{howto/argparse-optparse migrating-optparse-code}@anchor{33cf}@anchor{howto/argparse-optparse migrating-optparse-code-to-argparse}@anchor{33d0}@anchor{howto/argparse-optparse translation-repo}@anchor{33d1}
@subsubsection Migrating @code{optparse} code to @code{argparse}


The @ref{7,,argparse} module offers several higher level features not natively
provided by the @ref{a4,,optparse} module, including:


@itemize *

@item 
位置引数を扱う

@item 
Supporting subcommands.

@item 
@code{+}, @code{/} のような代替オプションプレフィクスを許容する

@item 
zero-or-more スタイル、one-or-more スタイルの引数を扱う

@item 
より有益な使用方法メッセージの生成

@item 
カスタム @code{type}, カスタム @code{action} のために遥かに簡単なインターフェイスを提供する
@end itemize

Originally, the @ref{7,,argparse} module attempted to maintain compatibility
with @ref{a4,,optparse}.  However, the fundamental design differences between
supporting declarative command line option processing (while leaving positional
argument processing to application code), and supporting both named options
and positional arguments in the declarative interface mean that the
API has diverged from that of @code{optparse} over time.

As described in @ref{336b,,Choosing an argument parsing library}, applications that are
currently using @ref{a4,,optparse} and are happy with the way it works can
just continue to use @code{optparse}.

Application developers that are considering migrating should also review
the list of intrinsic behavioural differences described in that section
before deciding whether or not migration is desirable.

For applications that do choose to migrate from @ref{a4,,optparse} to @ref{7,,argparse},
the following suggestions should be helpful:


@itemize *

@item 
すべての @ref{33d2,,optparse.OptionParser.add_option()} の呼び出しを、@ref{4bc,,ArgumentParser.add_argument()} の呼び出しに置き換える。

@item 
@code{(options, args) = parser.parse_args()} を @code{args = parser.parse_args()} に置き換え、位置引数のために必要に応じて @ref{4bc,,ArgumentParser.add_argument()} の呼び出しを追加する。これまで @code{options} と呼ばれていたものが、@ref{7,,argparse} では @code{args} と呼ばれていることに留意してください。

@item 
@ref{33d3,,optparse.OptionParser.disable_interspersed_args()} を、@ref{336d,,parse_args()} ではなく @ref{cf7,,parse_intermixed_args()} で置き換える。

@item 
コールバック・アクションと @code{callback_*} キーワード引数を @code{type} や @code{action} 引数に置き換える。

@item 
@code{type} キーワード引数に渡していた文字列の名前を、それに応じたオブジェクト (例: int, float, complex, ...) に置き換える。

@item 
@ref{33d4,,optparse.Values} を @ref{336e,,Namespace} に置き換え、@ref{33d5,,optparse.OptionError} と @ref{33d6,,optparse.OptionValueError} を @ref{33be,,ArgumentError} に置き換える。

@item 
@code{%default} や @code{%prog} などの暗黙の引数を含む文字列を、@code{%(default)s} や @code{%(prog)s} などの、通常の Python で辞書を使う場合のフォーマット文字列に置き換える。

@item 
OptionParser のコンストラクターの @code{version} 引数を、@code{parser.add_argument('--version', action='version', version='<the version>')} に置き換える
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node optparse --- Parser for command line options,getpass --- 可搬性のあるパスワード入力機構,argparse --- コマンドラインオプションや引数、サブコマンド向けのパーサー,コマンドラインインターフェースライブラリ
@anchor{library/optparse doc}@anchor{33d7}@anchor{library/optparse module-optparse}@anchor{a4}@anchor{library/optparse optparse-parser-for-command-line-options}@anchor{33d8}@anchor{library/optparse translation-repo}@anchor{33d9}
@subsection @code{optparse} --- Parser for command line options


@geindex module; optparse

`ソースコード:' Lib/optparse.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/optparse.py}


__________________________________________________________________


@menu
* Choosing an argument parsing library:: 
* はじめに: はじめに<7>. 
* 背景:: 
* チュートリアル: チュートリアル<2>. 
* リファレンスガイド:: 
* オプション処理コールバック:: 
* Extending optparse:: 
* 例外: 例外<12>. 

@end menu

@node Choosing an argument parsing library,はじめに<7>,,optparse --- Parser for command line options
@anchor{library/optparse choosing-an-argument-parser}@anchor{336b}@anchor{library/optparse choosing-an-argument-parsing-library}@anchor{33da}
@subsubsection Choosing an argument parsing library


The standard library includes three argument parsing libraries:


@itemize *

@item 
@ref{65,,getopt}: a module that closely mirrors the procedural C @code{getopt} API.
Included in the standard library since before the initial Python 1.0 release.

@item 
@code{optparse}: a declarative replacement for @code{getopt} that
provides equivalent functionality without requiring each application
to implement its own procedural option parsing logic. Included
in the standard library since the Python 2.3 release.

@item 
@ref{7,,argparse}: a more opinionated alternative to @code{optparse} that
provides more functionality by default, at the expense of reduced application
flexibility in controlling exactly how arguments are processed. Included in
the standard library since the Python 2.7 and Python 3.2 releases.
@end itemize

In the absence of more specific argument parsing design constraints, @ref{7,,argparse}
is the recommended choice for implementing command line applications, as it offers
the highest level of baseline functionality with the least application level code.

@ref{65,,getopt} is retained almost entirely for backwards compatibility reasons.
However, it also serves a niche use case as a tool for prototyping and testing
command line argument handling in @code{getopt}-based C applications.

@code{optparse} should be considered as an alternative to @ref{7,,argparse} in the
following cases:


@itemize *

@item 
an application is already using @code{optparse} and doesn't want to risk the
subtle behavioural changes that may arise when migrating to @ref{7,,argparse}

@item 
the application requires additional control over the way options and
positional parameters are interleaved on the command line (including
the ability to disable the interleaving feature completely)

@item 
the application requires additional control over the incremental parsing
of command line elements (while @code{argparse} does support this, the
exact way it works in practice is undesirable for some use cases)

@item 
the application requires additional control over the handling of options
which accept parameter values that may start with @code{-} (such as delegated
options to be passed to invoked subprocesses)

@item 
the application requires some other command line parameter processing
behavior which @code{argparse} does not support, but which can be implemented
in terms of the lower level interface offered by @code{optparse}
@end itemize

These considerations also mean that @code{optparse} is likely to provide a
better foundation for library authors writing third party command line
argument processing libraries.

As a concrete example, consider the following two command line argument
parsing configurations, the first using @code{optparse}, and the second
using @code{argparse}:

@example
import optparse

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('-o', '--output')
    parser.add_option('-v', dest='verbose', action='store_true')
    opts, args = parser.parse_args()
    process(args, output=opts.output, verbose=opts.verbose)
@end example

@example
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output')
    parser.add_argument('-v', dest='verbose', action='store_true')
    parser.add_argument('rest', nargs='*')
    args = parser.parse_args()
    process(args.rest, output=args.output, verbose=args.verbose)
@end example

The most obvious difference is that in the @code{optparse} version, the non-option
arguments are processed separately by the application after the option processing
is complete. In the @code{argparse} version, positional arguments are declared and
processed in the same way as the named options.

However, the @code{argparse} version will also handle some parameter combination
differently from the way the @code{optparse} version would handle them.
For example (amongst other differences):


@itemize *

@item 
supplying @code{-o -v} gives @code{output="-v"} and @code{verbose=False}
when using @code{optparse}, but a usage error with @code{argparse}
(complaining that no value has been supplied for @code{-o/--output},
since @code{-v} is interpreted as meaning the verbosity flag)

@item 
similarly, supplying @code{-o --} gives @code{output="--"} and @code{args=()}
when using @code{optparse}, but a usage error with @code{argparse}
(also complaining that no value has been supplied for @code{-o/--output},
since @code{--} is interpreted as terminating the option processing
and treating all remaining values as positional arguments)

@item 
supplying @code{-o=foo} gives @code{output="=foo"} when using @code{optparse},
but gives @code{output="foo"} with @code{argparse} (since @code{=} is special
cased as an alternative separator for option parameter values)
@end itemize

Whether these differing behaviors in the @code{argparse} version are
considered desirable or a problem will depend on the specific command line
application use case.


@subsubheading 参考


click@footnote{https://pypi.org/project/click/} is a third party argument processing library (originally
based on @code{optparse}), which allows command line applications to be
developed as a set of decorated command implementation functions.

Other third party libraries, such as typer@footnote{https://pypi.org/project/typer/} or msgspec-click@footnote{https://pypi.org/project/msgspec-click/},
allow command line interfaces to be specified in ways that more effectively
integrate with static checking of Python type annotations.


@node はじめに<7>,背景,Choosing an argument parsing library,optparse --- Parser for command line options
@anchor{library/optparse introduction}@anchor{33db}
@subsubsection はじめに


@code{optparse} is a more convenient, flexible, and powerful library for parsing
command-line options than the minimalist @ref{65,,getopt} module.
@code{optparse} uses a more declarative style of command-line parsing:
you create an instance of @ref{16e6,,OptionParser},
populate it with options, and parse the command line.
@code{optparse} allows users to specify options in the conventional
GNU/POSIX syntax, and additionally generates usage and help messages for you.

Here's an example of using @code{optparse} in a simple script:

@example
from optparse import OptionParser
...
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()
@end example

このようにわずかな行数のコードによって、スクリプトのユーザはコマンドライン上で例えば以下のような「よくある使い方」を実行できるようになります:

@example
<yourscript> --file=outfile -q
@end example

As it parses the command line, @code{optparse} sets attributes of the
@code{options} object returned by @ref{16e7,,parse_args()} based on user-supplied
command-line values.  When @ref{16e7,,parse_args()} returns from parsing this command
line, @code{options.filename} will be @code{"outfile"} and @code{options.verbose} will be
@code{False}.  @code{optparse} 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:

@example
<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile
@end example

さらに、ユーザが以下のいずれかを実行すると

@example
<yourscript> -h
<yourscript> --help
@end example

and @code{optparse} will print out a brief summary of your script's options:

@example
Usage: <yourscript> [options]

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout
@end example

`yourscript' の中身は実行時に決まります (通常は @code{sys.argv[0]} になります)。

@node 背景,チュートリアル<2>,はじめに<7>,optparse --- Parser for command line options
@anchor{library/optparse background}@anchor{33dc}@anchor{library/optparse optparse-background}@anchor{33dd}
@subsubsection 背景


@code{optparse} was explicitly designed to encourage the creation of programs
with straightforward command-line interfaces that follow the conventions
established by the @code{getopt()} family of functions available to C developers.
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,
reading this section will allow you to acquaint yourself with them.

@menu
* 用語集:: 
* オプションとは何か:: 
* 位置引数とは何か:: 

@end menu

@node 用語集,オプションとは何か,,背景
@anchor{library/optparse optparse-terminology}@anchor{33de}@anchor{library/optparse terminology}@anchor{33df}
@subsubsection 用語集



@table @asis

@item 引数 (argument)

コマンドラインでユーザが入力するテキストの塊で、シェルが @code{execl} や @code{execv} に引き渡すものです。Python では、引数は @code{sys.argv[1:]} の要素となります。(@code{sys.argv[0]} は実行しようとしているプログラムの名前です。引数解析に関しては、この要素はあまり重要ではありません。) Unix シェルでは、「語 (word)」という用語も使います。

場合によっては @code{sys.argv[1:]} 以外の引数リストを代入する方が望ましいことがあるので、「引数」は「 @code{sys.argv[1:]} または @code{sys.argv[1:]} の代替として提供される別のリストの要素」と読むべきでしょう。

@item オプション (option)

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. @code{-x} or @code{-F}.  Also, traditional Unix syntax allows multiple
options to be merged into a single argument, e.g. @code{-x -F} is equivalent
to @code{-xF}.  The GNU project introduced @code{--} followed by a series of
hyphen-separated words, e.g. @code{--file} or @code{--dry-run}.  These are the
only two option syntaxes provided by @code{optparse}.

他に見られる他のオプション書法には以下のようなものがあります:


@itemize *

@item 
ハイフンの後ろに数個の文字が続くもので、例えば @code{-pf} (このオプションは複数のオプションを一つにまとめたものとは `違います')

@item 
ハイフンの後ろに語が続くもので、例えば @code{-file} (これは技術的には上の書式と同じですが、通常同じプログラム上で一緒に使うことはありません)

@item 
プラス記号の後ろに一文字、数個の文字、または語を続けたもので、例えば @code{+f}, @code{+rgb}

@item 
スラッシュ記号の後ろに一文字、数個の文字、または語を続けたもので、例えば @code{/f}, @code{/file}
@end itemize

These option syntaxes are not supported by @code{optparse}, 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
Windows or certain legacy platforms (e.g. VMS, MS-DOS).

@item オプション引数 (option argument)

an argument that follows an option, is closely associated with that option,
and is consumed from the argument list when that option is. With
@code{optparse}, option arguments may either be in a separate argument from
their option:

@example
-f foo
--file foo
@end example

また、一つの引数中にも入れられます:

@example
-ffoo
--file=foo
@end example

Typically, a given option either takes an argument or it doesn't. Lots of
people want an "optional option arguments" feature, meaning that some options
will take an argument if they see it, and won't if they don't.  This is
somewhat controversial, because it makes parsing ambiguous: if @code{-a} takes
an optional argument and @code{-b} is another option entirely, how do we
interpret @code{-ab}?  Because of this ambiguity, @code{optparse} does not
support this feature.

@item 位置引数 (positional argument)

他のオプションが解析される、すなわち他のオプションとその引数が解析されて引数リストから除去された後に引数リストに置かれているものです。

@item 必須のオプション (required option)

an option that must be supplied on the command-line; note that the phrase
"required option" is self-contradictory in English.  @code{optparse} doesn't
prevent you from implementing required options, but doesn't give you much
help at it either.
@end table

例えば、下記のような架空のコマンドラインを考えてみましょう:

@example
prog -v --report report.txt foo bar
@end example

@code{-v} と @code{--report} はどちらもオプションです。@code{--report} オプションが引数をとるとすれば、@code{report.txt} はオプションの引数です。@code{foo} と @code{bar} は位置引数になります。

@node オプションとは何か,位置引数とは何か,用語集,背景
@anchor{library/optparse optparse-what-options-for}@anchor{33e0}@anchor{library/optparse what-are-options-for}@anchor{33e1}
@subsubsection オプションとは何か


オプションはプログラムの実行を調整したり、カスタマイズしたりするための補助的な情報を与えるために使います。もっとはっきりいうと、オプションはあくまでもオプション (省略可能)であるということです。本来、プログラムはともかくもオプションなしでうまく実行できてしかるべきです。(Unix やGNU ツールセットのプログラムをランダムにピックアップしてみてください。オプションを全く指定しなくてもちゃんと動くでしょう？例外は @code{find}, @code{tar}, @code{dd} くらいです---これらの例外は、オプション文法が標準的でなく、インターフェースが混乱を招くと酷評されてきた変種のはみ出しものなのです)

多くの人が自分のプログラムに「必須のオプション」を持たせたいと考えます。しかしよく考えてください。必須なら、それは `オプション(省略可能) ではないのです！' プログラムを正しく動作させるのに絶対的に必要な情報があるとすれば、そこには位置引数を割り当てるべきなのです。

良くできたコマンドライン インターフェース設計として、ファイルのコピーに使われる @code{cp} ユーティリティのことを考えてみましょう。ファイルのコピーでは、コピー先を指定せずにファイルをコピーするのは無意味な操作ですし、少なくとも一つのコピー元が必要です。従って、@code{cp} は引数無しで実行すると失敗します。とはいえ、@code{cp} はオプションを全く必要としない柔軟で便利なコマンドライン文法を備えています:

@example
cp SOURCE DEST
cp SOURCE ... DEST-DIR
@end example

まだあります。ほとんどの @code{cp} の実装では、ファイルモードや変更時刻を変えずにコピーする、シンボリックリンクの追跡を行わない、すでにあるファイルを上書きする前にユーザに尋ねる、など、ファイルをコピーする方法をいじるための一連のオプションを実装しています。しかし、こうしたオプションは、一つのファイルを別の場所にコピーする、または複数のファイルを別のディレクトリにコピーするという、@code{cp} の中心的な処理を乱すことはないのです。

@node 位置引数とは何か,,オプションとは何か,背景
@anchor{library/optparse optparse-what-positional-arguments-for}@anchor{33e2}@anchor{library/optparse what-are-positional-arguments-for}@anchor{33e3}
@subsubsection 位置引数とは何か


位置引数とは、プログラムを動作させる上で絶対的に必要な情報となる引数です。

よいユーザインターフェースとは、絶対に必要だとされるものが可能な限り少ないものです。プログラムを正しく動作させるために 17 個もの別個の情報が必要だとしたら、その `方法' はさして問題にはなりません ---ユーザはプログラムを正しく動作させられないうちに諦め、立ち去ってしまうからです。ユーザインターフェースがコマンドラインでも、設定ファイルでも、GUI やその他の何であっても同じです: 多くの要求をユーザに押し付ければ、ほとんどのユーザはただ音をあげてしまうだけなのです。

要するに、ユーザが絶対に提供しなければならない情報だけに制限する --- そして可能な限りよく練られたデフォルト設定を使うよう試みてください。もちろん、プログラムには適度な柔軟性を持たせたいとも望むはずですが、それこそがオプションの果たす役割です。繰り返しますが、設定ファイルのエントリであろうが、GUI でできた「環境設定」ダイアログ上のウィジェットであろうが、コマンドラインオプションであろうが関係ありません --- より多くのオプションを実装すればプログラムはより柔軟性を持ちますが、実装はより難解になるのです。高すぎる柔軟性はユーザを閉口させ、コードの維持をより難しくするのです。

@node チュートリアル<2>,リファレンスガイド,背景,optparse --- Parser for command line options
@anchor{library/optparse optparse-tutorial}@anchor{33e4}@anchor{library/optparse tutorial}@anchor{33e5}
@subsubsection チュートリアル


While @code{optparse} is quite flexible and powerful, it's also straightforward
to use in most cases.  This section covers the code patterns that are common to
any @code{optparse}-based program.

まず、@ref{16e6,,OptionParser} クラスを import しておかなければなりません。次に、プログラムの冒頭で @ref{16e6,,OptionParser} インスタンスを生成しておきます:

@example
from optparse import OptionParser
...
parser = OptionParser()
@end example

これでオプションを定義できるようになりました。基本的な構文は以下の通りです:

@example
parser.add_option(opt_str, ...,
                  attr=value, ...)
@end example

Each option has one or more option strings, such as @code{-f} or @code{--file},
and several option attributes that tell @code{optparse} what to expect and what
to do when it encounters that option on the command line.

通常、各オプションには短いオプション文字列と長いオプション文字列があります。例えば:

@example
parser.add_option("-f", "--file", ...)
@end example

オプション文字列は、(ゼロ文字の場合も含め)いくらでも短く、またいくらでも長くできます。ただしオプション文字列は少なくとも一つなければなりません。

The option strings passed to @ref{33d2,,OptionParser.add_option()} 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, @code{optparse}
encounters `option strings' and looks up options from them.

Once all of your options are defined, instruct @code{optparse} to parse your
program's command line:

@example
(options, args) = parser.parse_args()
@end example

(お望みなら、 @ref{16e7,,parse_args()} に自作の引数リストを渡してもかまいません。とはいえ、実際にはそうした必要はほとんどないでしょう: @code{optionparser} はデフォルトで @code{sys.argv[1:]} を使うからです。)

@ref{16e7,,parse_args()} は二つの値を返します:


@itemize *

@item 
全てのオプションに対する値の入ったオブジェクト @code{options} --- 例えば、@code{--file} が単一の文字列引数をとる場合、@code{options.file} はユーザが指定したファイル名になります。オプションを指定しなかった場合には @code{None} になります

@item 
オプションの解析後に残った位置引数からなるリスト @code{args}
@end itemize

このチュートリアルの節では、最も重要な四つのオプション属性: @ref{33e6,,action}, @ref{33e7,,type}, @ref{33e8,,dest} (destination), @ref{33e9,,help} についてしか触れません。このうち最も重要なのは @ref{33e6,,action} です。

@menu
* オプション・アクションを理解する:: 
* store アクション:: 
* ブール値 (フラグ) オプションの処理: ブール値 フラグ オプションの処理. 
* その他のアクション:: 
* デフォルト値:: 
* ヘルプの生成:: 
* バージョン番号の出力:: 
* How optparse handles errors:: 
* 全てをつなぎ合わせる:: 

@end menu

@node オプション・アクションを理解する,store アクション,,チュートリアル<2>
@anchor{library/optparse optparse-understanding-option-actions}@anchor{33ea}@anchor{library/optparse understanding-option-actions}@anchor{33eb}
@subsubsection オプション・アクションを理解する


Actions tell @code{optparse} what to do when it encounters an option on the
command line.  There is a fixed set of actions hard-coded into @code{optparse};
adding new actions is an advanced topic covered in section
@ref{33ec,,Extending optparse}.  Most actions tell @code{optparse} to store
a value in some variable---for example, take a string from the command line and
store it in an attribute of @code{options}.

If you don't specify an option action, @code{optparse} defaults to @code{store}.

@node store アクション,ブール値 フラグ オプションの処理,オプション・アクションを理解する,チュートリアル<2>
@anchor{library/optparse optparse-store-action}@anchor{33ed}@anchor{library/optparse the-store-action}@anchor{33ee}
@subsubsection store アクション


The most common option action is @code{store}, which tells @code{optparse} to take
the next argument (or the remainder of the current argument), ensure that it is
of the correct type, and store it to your chosen destination.

例えば:

@example
parser.add_option("-f", "--file",
                  action="store", type="string", dest="filename")
@end example

Now let's make up a fake command line and ask @code{optparse} to parse it:

@example
args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)
@end example

When @code{optparse} sees the option string @code{-f}, it consumes the next
argument, @code{foo.txt}, and stores it in @code{options.filename}.  So, after this
call to @ref{16e7,,parse_args()}, @code{options.filename} is @code{"foo.txt"}.

Some other option types supported by @code{optparse} are @code{int} and @code{float}.
Here's an option that expects an integer argument:

@example
parser.add_option("-n", type="int", dest="num")
@end example

このオプションには長い形式のオプション文字列がないため、設定に問題がないということに注意してください。また、デフォルトのアクションは @code{store} なので、ここでは action を明示的に指定していません。

架空のコマンドラインをもう一つ解析してみましょう。今度は、オプション引数をオプションの右側にぴったりくっつけて一緒くたにします: @code{-n42} (一つの引数のみ) は @code{-n 42} (二つの引数からなる) と等価になるので

@example
(options, args) = parser.parse_args(["-n42"])
print(options.num)
@end example

は @code{42} を出力します。

If you don't specify a type, @code{optparse} assumes @code{string}.  Combined with
the fact that the default action is @code{store}, that means our first example can
be a lot shorter:

@example
parser.add_option("-f", "--file", dest="filename")
@end example

If you don't supply a destination, @code{optparse} figures out a sensible
default from the option strings: if the first long option string is
@code{--foo-bar}, then the default destination is @code{foo_bar}.  If there are no
long option strings, @code{optparse} looks at the first short option string: the
default destination for @code{-f} is @code{f}.

@code{optparse} also includes the built-in @code{complex} type.  Adding
types is covered in section @ref{33ec,,Extending optparse}.

@node ブール値 フラグ オプションの処理,その他のアクション,store アクション,チュートリアル<2>
@anchor{library/optparse handling-boolean-flag-options}@anchor{33ef}@anchor{library/optparse optparse-handling-boolean-options}@anchor{33f0}
@subsubsection ブール値 (フラグ) オプションの処理


Flag options---set a variable to true or false when a particular option is
seen---are quite common.  @code{optparse} supports them with two separate actions,
@code{store_true} and @code{store_false}.  For example, you might have a @code{verbose}
flag that is turned on with @code{-v} and off with @code{-q}:

@example
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")
@end example

ここでは二つのオプションに同じ保存先を指定していますが、全く問題ありません。(下記のように、デフォルト値の設定を少し注意深く行わなければならないだけです。)

When @code{optparse} encounters @code{-v} on the command line, it sets
@code{options.verbose} to @code{True}; when it encounters @code{-q},
@code{options.verbose} is set to @code{False}.

@node その他のアクション,デフォルト値,ブール値 フラグ オプションの処理,チュートリアル<2>
@anchor{library/optparse optparse-other-actions}@anchor{33f1}@anchor{library/optparse other-actions}@anchor{33f2}
@subsubsection その他のアクション


Some other actions supported by @code{optparse} are:


@table @asis

@item @code{"store_const"}

store a constant value, pre-set via @ref{33f3,,Option.const}

@item @code{"append"}

オプションの引数を指定のリストに追加します

@item @code{"count"}

指定のカウンタを 1 増やします

@item @code{"callback"}

指定の関数を呼び出します
@end table

これらのアクションについては、 @ref{33f4,,リファレンスガイド} 節および @ref{33f5,,オプション処理コールバック} 節で触れます。

@node デフォルト値,ヘルプの生成,その他のアクション,チュートリアル<2>
@anchor{library/optparse default-values}@anchor{33f6}@anchor{library/optparse optparse-default-values}@anchor{33f7}
@subsubsection デフォルト値


All of the above examples involve setting some variable (the "destination") when
certain command-line options are seen.  What happens if those options are never
seen?  Since we didn't supply any defaults, they are all set to @code{None}.  This
is usually fine, but sometimes you want more control.  @code{optparse} lets you
supply a default value for each destination, which is assigned before the
command line is parsed.

First, consider the verbose/quiet example.  If we want @code{optparse} to set
@code{verbose} to @code{True} unless @code{-q} is seen, then we can do this:

@example
parser.add_option("-v", action="store_true", dest="verbose", default=True)
parser.add_option("-q", action="store_false", dest="verbose")
@end example

デフォルトの値は特定のオプションではなく `保存先' に対して適用されます。また、これら二つのオプションはたまたま同じ保存先を持っているにすぎないため、上のコードは下のコードと全く等価になります:

@example
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose", default=True)
@end example

下のような場合を考えてみましょう:

@example
parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option("-q", action="store_false", dest="verbose", default=True)
@end example

やはり @code{verbose} のデフォルト値は @code{True} になります; 特定の目的変数に対するデフォルト値として有効なのは、最後に指定した値だからです。

デフォルト値をすっきりと指定するには、 @ref{16e6,,OptionParser} の @code{set_defaults()} メソッドを使います。このメソッドは @ref{16e7,,parse_args()} を呼び出す前ならいつでも使えます:

@example
parser.set_defaults(verbose=True)
parser.add_option(...)
(options, args) = parser.parse_args()
@end example

前の例と同様、あるオプションの値の保存先に対するデフォルトの値は最後に指定した値になります。コードを読みやすくするため、デフォルト値を設定するときには両方のやり方を混ぜるのではなく、片方だけを使うようにしましょう。

@node ヘルプの生成,バージョン番号の出力,デフォルト値,チュートリアル<2>
@anchor{library/optparse generating-help}@anchor{33f8}@anchor{library/optparse optparse-generating-help}@anchor{33f9}
@subsubsection ヘルプの生成


@code{optparse}'s ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces.  All you have to do
is supply a @ref{33e9,,help} value for each option, and optionally a short
usage message for your whole program.  Here's an OptionParser populated with
user-friendly (documented) options:

@example
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=True,
                  help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose",
                  help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
                  metavar="FILE", help="write output to FILE")
parser.add_option("-m", "--mode",
                  default="intermediate",
                  help="interaction mode: novice, intermediate, "
                       "or expert [default: %default]")
@end example

If @code{optparse} encounters either @code{-h} or @code{--help} on the
command-line, or if you just call @code{parser.print_help()}, it prints the
following to standard output:

@example
Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]
@end example

(If the help output is triggered by a help option, @code{optparse} exits after
printing the help text.)

There's a lot going on here to help @code{optparse} generate the best possible
help message:


@itemize *

@item 
スクリプト自体の利用法を表すメッセージを定義します:

@example
usage = "usage: %prog [options] arg1 arg2"
@end example

@code{optparse} expands @code{%prog} in the usage string to the name of the
current program, i.e. @code{os.path.basename(sys.argv[0])}.  The expanded string
is then printed before the detailed option help.

If you don't supply a usage string, @code{optparse} uses a bland but sensible
default: @code{"Usage: %prog [options]"}, which is fine if your script doesn't
take any positional arguments.

@item 
every option defines a help string, and doesn't worry about
line-wrapping---@code{optparse} takes care of wrapping lines and making
the help output look good.

@item 
オプションが値をとるということは自動的に生成されるヘルプメッセージの中で分かります。例えば、"mode" option の場合にはこのようになります:

@example
-m MODE, --mode=MODE
@end example

Here, "MODE" is called the meta-variable: it stands for the argument that the
user is expected to supply to @code{-m}/@code{--mode}.  By default,
@code{optparse} converts the destination variable name to uppercase and uses
that for the meta-variable.  Sometimes, that's not what you want---for
example, the @code{--filename} option explicitly sets @code{metavar="FILE"},
resulting in this automatically generated option description:

@example
-f FILE, --filename=FILE
@end example

この機能の重要さは、単に表示スペースを節約するといった理由にとどまりません: 上の例では、手作業で書いたヘルプテキストの中でメタ変数として @code{FILE} を使っています。その結果、ユーザに対してやや堅苦しい表現の書法 @code{-f FILE} と、より平易に意味付けを説明した "write output to FILE" との間に対応があるというヒントを与えています。これは、エンドユーザにとってより明解で便利なヘルプテキストを作成する単純でありながら効果的な手法なのです。

@item 
options that have a default value can include @code{%default} in the help
string---@code{optparse} will replace it with @ref{169,,str()} of the option's
default value.  If an option has no default value (or the default value is
@code{None}), @code{%default} expands to @code{none}.
@end itemize

@menu
* オプションをグループ化する:: 

@end menu

@node オプションをグループ化する,,,ヘルプの生成
@anchor{library/optparse grouping-options}@anchor{33fa}
@subsubsection オプションをグループ化する


たくさんのオプションを扱う場合、オプションをグループ分けするとヘルプ出力が見やすくなります。 @ref{16e6,,OptionParser} は、複数のオプションをまとめたオプショングループを複数持つことができます。

オプションのグループは、 @ref{33fb,,OptionGroup} を使って作成します:

@geindex OptionGroup (optparse のクラス)
@anchor{library/optparse optparse OptionGroup}@anchor{33fb}
@deffn {クラス} optparse.OptionGroup (parser, title, description=None)

ここでは:


@itemize *

@item 
`parser' は、このグループが属する @ref{16e6,,OptionParser} のインスタンスです

@item 
`title' はグループのタイトルです

@item 
`description' はオプションで、グループの長い説明です
@end itemize
@end deffn

@ref{33fb,,OptionGroup} は (@ref{16e6,,OptionParser} のように) @code{OptionContainer} を継承していて、オプションをグループに追加するために @code{add_option()} メソッドを利用できます。

全てのオプションを定義したら、 @ref{16e6,,OptionParser} の @code{add_option_group()} メソッドを使ってグループを定義済みのパーサーに追加します。

前のセクションで定義したパーサーに、続けて @ref{33fb,,OptionGroup} を追加します:

@example
group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
@end example

この結果のヘルプ出力は次のようになります:

@example
Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.
@end example

さらにサンプルを拡張して、複数のグループを使うようにしてみます:

@example
group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

group = OptionGroup(parser, "Debug Options")
group.add_option("-d", "--debug", action="store_true",
                 help="Print debug information")
group.add_option("-s", "--sql", action="store_true",
                 help="Print all SQL statements executed")
group.add_option("-e", action="store_true", help="Print every action done")
parser.add_option_group(group)
@end example

出力結果は次のようになります:

@example
Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                        [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.

  Debug Options:
    -d, --debug         Print debug information
    -s, --sql           Print all SQL statements executed
    -e                  Print every action done
@end example

もう1つの、特にオプショングループをプログラムから操作するときに利用できるメソッドがあります:

@geindex get_option_group() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser get_option_group}@anchor{33fc}
@deffn {メソッド} OptionParser.get_option_group (opt_str)

短いオプション文字列もしくは長いオプション文字列 `opt_str' (例。 @code{'-o'} 、 @code{'--option'}) が属する @ref{33fb,,OptionGroup} を返します。そのような @ref{33fb,,OptionGroup} が無い場合は、 @code{None} を返します。
@end deffn

@node バージョン番号の出力,How optparse handles errors,ヘルプの生成,チュートリアル<2>
@anchor{library/optparse optparse-printing-version-string}@anchor{33fd}@anchor{library/optparse printing-a-version-string}@anchor{33fe}
@subsubsection バージョン番号の出力


Similar to the brief usage string, @code{optparse} can also print a version
string for your program.  You have to supply the string as the @code{version}
argument to OptionParser:

@example
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
@end example

@code{%prog} is expanded just like it is in @code{usage}.  Apart from that,
@code{version} can contain anything you like.  When you supply it, @code{optparse}
automatically adds a @code{--version} option to your parser. If it encounters
this option on the command line, it expands your @code{version} string (by
replacing @code{%prog}), prints it to stdout, and exits.

例えば、@code{/usr/bin/foo} という名前のスクリプトなら:

@example
$ /usr/bin/foo --version
foo 1.0
@end example

以下の2つのメソッドを、@code{version} 文字列を表示するために利用できます:

@geindex print_version() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser print_version}@anchor{33ff}
@deffn {メソッド} OptionParser.print_version (file=None)

現在のプログラムのバージョン (@code{self.version}) を `file' (デフォルト: stdout) へ表示します。 @ref{3400,,print_usage()} と同じく、 @code{self.version} の中の全ての @code{%prog} が現在のプログラム名に置き換えられます。 @code{self.version} が空文字列だだったり未定義だったときは何もしません。
@end deffn

@geindex get_version() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser get_version}@anchor{3401}
@deffn {メソッド} OptionParser.get_version ()

@ref{33ff,,print_version()} と同じですが、バージョン文字列を表示する代わりに返します。
@end deffn

@node How optparse handles errors,全てをつなぎ合わせる,バージョン番号の出力,チュートリアル<2>
@anchor{library/optparse how-optparse-handles-errors}@anchor{3402}@anchor{library/optparse optparse-how-optparse-handles-errors}@anchor{3403}
@subsubsection How @code{optparse} handles errors


There are two broad classes of errors that @code{optparse} has to worry about:
programmer errors and user errors.  Programmer errors are usually erroneous
calls to @ref{33d2,,OptionParser.add_option()}, e.g. invalid option strings, unknown
option attributes, missing option attributes, etc.  These are dealt with in the
usual way: raise an exception (either @ref{33d5,,optparse.OptionError} or
@ref{198,,TypeError}) and let the program crash.

Handling user errors is much more important, since they are guaranteed to happen
no matter how stable your code is.  @code{optparse} can automatically detect
some user errors, such as bad option arguments (passing @code{-n 4x} where
@code{-n} takes an integer argument), missing arguments (@code{-n} at the end
of the command line, where @code{-n} takes an argument of any type).  Also,
you can call @code{OptionParser.error()} to signal an application-defined error
condition:

@example
(options, args) = parser.parse_args()
...
if options.a and options.b:
    parser.error("options -a and -b are mutually exclusive")
@end example

In either case, @code{optparse} handles the error the same way: it prints the
program's usage message and an error message to standard error and exits with
error status 2.

上に挙げた最初の例、すなわち整数を引数にとるオプションにユーザが @code{4x} を指定した場合を考えてみましょう:

@example
$ /usr/bin/foo -n 4x
Usage: foo [options]

foo: error: option -n: invalid integer value: '4x'
@end example

値を全く指定しない場合には、以下のようになります:

@example
$ /usr/bin/foo -n
Usage: foo [options]

foo: error: -n option requires an argument
@end example

@code{optparse}-generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
@code{OptionParser.error()} from your application code.

If @code{optparse}'s default error-handling behaviour does not suit your needs,
you'll need to subclass OptionParser and override its @code{exit()}
and/or @code{error()} methods.

@node 全てをつなぎ合わせる,,How optparse handles errors,チュートリアル<2>
@anchor{library/optparse optparse-putting-it-all-together}@anchor{3404}@anchor{library/optparse putting-it-all-together}@anchor{3405}
@subsubsection 全てをつなぎ合わせる


Here's what @code{optparse}-based scripts usually look like:

@example
from optparse import OptionParser
...
def main():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="filename",
                      help="read data from FILENAME")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose")
    ...
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    if options.verbose:
        print("reading %s..." % options.filename)
    ...

if __name__ == "__main__":
    main()
@end example

@node リファレンスガイド,オプション処理コールバック,チュートリアル<2>,optparse --- Parser for command line options
@anchor{library/optparse optparse-reference-guide}@anchor{33f4}@anchor{library/optparse reference-guide}@anchor{3406}
@subsubsection リファレンスガイド


@menu
* parserを作る:: 
* パーザへのオプション追加:: 
* オプションの定義:: 
* オプション属性:: 
* 標準的なオプション・アクション:: 
* 標準のオプション型:: 
* 引数を解析する:: 
* オプション解析器への問い合わせと操作:: 
* オプション間の衝突:: 
* クリーンアップ:: 
* その他のメソッド:: 

@end menu

@node parserを作る,パーザへのオプション追加,,リファレンスガイド
@anchor{library/optparse creating-the-parser}@anchor{3407}@anchor{library/optparse optparse-creating-parser}@anchor{3408}
@subsubsection parserを作る


The first step in using @code{optparse} is to create an OptionParser instance.

@geindex OptionParser (optparse のクラス)
@anchor{library/optparse optparse OptionParser}@anchor{16e6}
@deffn {クラス} optparse.OptionParser (...)

OptionParser のコンストラクタの引数はどれも必須ではありませんが、いくつものキーワード引数がオプションとして使えます。これらはキーワード引数として渡さなければなりません。すなわち、引数が宣言されている順番に頼ってはいけません。


@table @asis

@item @code{usage} (デフォルト: @code{"%prog [options]"})

The usage summary to print when your program is run incorrectly or with a
help option.  When @code{optparse} prints the usage string, it expands
@code{%prog} to @code{os.path.basename(sys.argv[0])} (or to @code{prog} if you
passed that keyword argument).  To suppress a usage message, pass the
special value @code{optparse.SUPPRESS_USAGE}.

@item @code{option_list} (デフォルト: @code{[]})

パーザに追加する Option オブジェクトのリストです。 @code{option_list} の中のオプションは @code{standard_option_list} (OptionParser のサブクラスでセットされる可能性のあるクラス属性) の後に追加されますが、バージョンやヘルプのオプションよりは前になります。このオプションの使用は推奨されません。パーザを作成した後で、 @ref{33d2,,add_option()} を使って追加してください。

@item @code{option_class} (デフォルト: optparse.Option)

@ref{33d2,,add_option()} でパーザにオプションを追加するときに使用されるクラス。

@item @code{version} (デフォルト: @code{None})

A version string to print when the user supplies a version option. If you
supply a true value for @code{version}, @code{optparse} automatically adds a
version option with the single option string @code{--version}.  The
substring @code{%prog} is expanded the same as for @code{usage}.

@item @code{conflict_handler} (デフォルト: @code{"error"})

オプション文字列が衝突するようなオプションがパーザに追加されたときにどうするかを指定します。 @ref{3409,,オプション間の衝突} 節を参照して下さい。

@item @code{description} (デフォルト: @code{None})

A paragraph of text giving a brief overview of your program.
@code{optparse} reformats this paragraph to fit the current terminal width
and prints it when the user requests help (after @code{usage}, but before the
list of options).

@item @code{formatter} (デフォルト: 新しい @code{IndentedHelpFormatter})

An instance of optparse.HelpFormatter that will be used for printing help
text.  @code{optparse} provides two concrete classes for this purpose:
IndentedHelpFormatter and TitledHelpFormatter.

@item @code{add_help_option} (デフォルト: @code{True})

If true, @code{optparse} will add a help option (with option strings @code{-h}
and @code{--help}) to the parser.

@item @code{prog}

@code{usage} や @code{version} の中の @code{%prog} を展開するときに @code{os.path.basename(sys.argv[0])} の代わりに使われる文字列です。

@item @code{epilog} (デフォルト: @code{None})

オプションのヘルプの後に表示されるヘルプテキスト.
@end table
@end deffn

@node パーザへのオプション追加,オプションの定義,parserを作る,リファレンスガイド
@anchor{library/optparse optparse-populating-parser}@anchor{340a}@anchor{library/optparse populating-the-parser}@anchor{340b}
@subsubsection パーザへのオプション追加


パーザにオプションを加えていくにはいくつか方法があります。推奨するのは @ref{33e4,,チュートリアル} 節で示したような @ref{33d2,,OptionParser.add_option()} を使う方法です。 @code{add_option()} は以下の二つのうちいずれかの方法で呼び出せます:


@itemize *

@item 
(@code{make_option()} などが返す) @ref{340c,,Option} インスタンスを渡します

@item 
@code{make_option()} に (すなわち @ref{340c,,Option} のコンストラクタに) 位置引数とキーワード引数の組み合わせを渡して、 @ref{340c,,Option} インスタンスを生成させます
@end itemize

もう一つの方法は、あらかじめ作成しておいた @ref{340c,,Option} インスタンスからなるリストを、以下のようにして @ref{16e6,,OptionParser} のコンストラクタに渡すというものです:

@example
option_list = [
    make_option("-f", "--filename",
                action="store", type="string", dest="filename"),
    make_option("-q", "--quiet",
                action="store_false", dest="verbose"),
    ]
parser = OptionParser(option_list=option_list)
@end example

(@code{make_option()} is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version of
@code{optparse} may split Option into several classes, and @code{make_option()}
will pick the right class to instantiate.  Do not instantiate Option directly.)

@node オプションの定義,オプション属性,パーザへのオプション追加,リファレンスガイド
@anchor{library/optparse defining-options}@anchor{340d}@anchor{library/optparse optparse-defining-options}@anchor{340e}
@subsubsection オプションの定義


各々の @ref{340c,,Option} インスタンス、は @code{-f} や @code{--file} といった同義のコマンドラインオプションからなる集合を表現しています。一つの @ref{340c,,Option} には任意の数のオプションを短い形式でも長い形式でも指定できます。ただし、少なくとも一つは指定しなければなりません。

正しい方法で @ref{340c,,Option} インスタンスを生成するには、 @ref{16e6,,OptionParser} の @code{add_option()} を使います。

@geindex add_option() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser add_option}@anchor{33d2}
@deffn {メソッド} OptionParser.add_option (option)

@deffnx {メソッド} OptionParser.add_option (*opt_str, attr=value, ...)

短い形式のオプション文字列を一つだけ持つようなオプションを生成するには次のようにします:

@example
parser.add_option("-f", attr=value, ...)
@end example

また、長い形式のオプション文字列を一つだけ持つようなオプションの定義は次のようになります:

@example
parser.add_option("--foo", attr=value, ...)
@end example

The keyword arguments define attributes of the new Option object.  The most
important option attribute is @ref{33e6,,action}, and it largely
determines which other attributes are relevant or required.  If you pass
irrelevant option attributes, or fail to pass required ones, @code{optparse}
raises an @ref{33d5,,OptionError} exception explaining your mistake.

An option's `action' determines what @code{optparse} does when it encounters
this option on the command-line.  The standard option actions hard-coded into
@code{optparse} are:


@table @asis

@item @code{"store"}

オプションの引数を保存します (デフォルトの動作です)

@item @code{"store_const"}

store a constant value, pre-set via @ref{33f3,,Option.const}

@item @code{"store_true"}

store @code{True}

@item @code{"store_false"}

store @code{False}

@item @code{"append"}

オプションの引数を指定のリストに追加します

@item @code{"append_const"}

append a constant value to a list, pre-set via @ref{33f3,,Option.const}

@item @code{"count"}

指定のカウンタを 1 増やします

@item @code{"callback"}

指定の関数を呼び出します

@item @code{"help"}

全てのオプションとそのドキュメントの入った使用法メッセージを出力します
@end table

(アクションを指定しない場合、デフォルトは @code{"store"} になります。このアクションでは、 @ref{33e7,,type} および @ref{33e8,,dest} オプション属性を指定できます。 @ref{340f,,標準的なオプション・アクション} を参照してください。)
@end deffn

As you can see, most actions involve storing or updating a value somewhere.
@code{optparse} always creates a special object for this, conventionally called
@code{options}, which is an instance of @ref{33d4,,optparse.Values}.

@geindex Values (optparse のクラス)
@anchor{library/optparse optparse Values}@anchor{33d4}
@deffn {クラス} optparse.Values

An object holding parsed argument names and values as attributes.
Normally created by calling when calling @ref{16e7,,OptionParser.parse_args()},
and can be overridden by a custom subclass passed to the `values' argument of
@ref{16e7,,OptionParser.parse_args()} (as described in @ref{3410,,引数を解析する}).
@end deffn

Option
arguments (and various other values) are stored as attributes of this object,
according to the @ref{33e8,,dest} (destination) option attribute.

例えばこれを呼び出した場合

@example
parser.parse_args()
@end example

one of the first things @code{optparse} does is create the @code{options} object:

@example
options = Values()
@end example

パーザ中で以下のようなオプションが定義されていて

@example
parser.add_option("-f", "--file", action="store", type="string", dest="filename")
@end example

パーズしたコマンドラインに以下のいずれかが入っていた場合:

@example
-ffoo
-f foo
--file=foo
--file foo
@end example

then @code{optparse}, on seeing this option, will do the equivalent of

@example
options.filename = "foo"
@end example

@ref{33e7,,type} および @ref{33e8,,dest} オプション属性は @ref{33e6,,action} と同じくらい重要ですが、 `全ての' オプションで意味をなすのは @ref{33e6,,action} だけなのです。

@node オプション属性,標準的なオプション・アクション,オプションの定義,リファレンスガイド
@anchor{library/optparse option-attributes}@anchor{3411}@anchor{library/optparse optparse-option-attributes}@anchor{3412}
@subsubsection オプション属性


@geindex Option (optparse のクラス)
@anchor{library/optparse optparse Option}@anchor{340c}
@deffn {クラス} optparse.Option

A single command line argument,
with various attributes passed by keyword to the constructor.
Normally created with @ref{33d2,,OptionParser.add_option()} rather than directly,
and can be overridden by a custom class via the `option_class' argument
to @ref{16e6,,OptionParser}.
@end deffn

The following option attributes may be passed as keyword arguments to
@ref{33d2,,OptionParser.add_option()}.  If you pass an option attribute that is not
relevant to a particular option, or fail to pass a required option attribute,
@code{optparse} raises @ref{33d5,,OptionError}.

@geindex action (optparse.Option の属性)
@anchor{library/optparse optparse Option action}@anchor{33e6}
@deffn {の属性} Option.action

(デフォルト: @code{"store"})

Determines @code{optparse}'s behaviour when this option is seen on the
command line; the available options are documented @ref{340f,,here}.
@end deffn

@geindex type (optparse.Option の属性)
@anchor{library/optparse optparse Option type}@anchor{33e7}
@deffn {の属性} Option.type

(デフォルト: @code{"string"})

このオプションに与えられる引数の型 (たとえば @code{"string"} や @code{"int"}) です。取りうるオプションについては @ref{3413,,こちら} を参照してください。
@end deffn

@geindex dest (optparse.Option の属性)
@anchor{library/optparse optparse Option dest}@anchor{33e8}
@deffn {の属性} Option.dest

(デフォルト: オプション文字列を使う)

If the option's action implies writing or modifying a value somewhere, this
tells @code{optparse} where to write it: @ref{33e8,,dest} names an
attribute of the @code{options} object that @code{optparse} builds as it parses
the command line.
@end deffn

@geindex default (optparse.Option の属性)
@anchor{library/optparse optparse Option default}@anchor{3414}
@deffn {の属性} Option.default

コマンドラインに指定がなかったときにこのオプションの対象に使われる値です。 @ref{3415,,OptionParser.set_defaults()} も参照してください。
@end deffn

@geindex nargs (optparse.Option の属性)
@anchor{library/optparse optparse Option nargs}@anchor{3416}
@deffn {の属性} Option.nargs

(デフォルト: 1)

How many arguments of type @ref{33e7,,type} should be consumed when this
option is seen.  If > 1, @code{optparse} will store a tuple of values to
@ref{33e8,,dest}.
@end deffn

@geindex const (optparse.Option の属性)
@anchor{library/optparse optparse Option const}@anchor{33f3}
@deffn {の属性} Option.const

定数を格納する動作のための、その定数です。
@end deffn

@geindex choices (optparse.Option の属性)
@anchor{library/optparse optparse Option choices}@anchor{3417}
@deffn {の属性} Option.choices

@code{"choice"} 型オプションに対してユーザが選べる選択肢となる文字列のリストです。
@end deffn

@geindex callback (optparse.Option の属性)
@anchor{library/optparse optparse Option callback}@anchor{3418}
@deffn {の属性} Option.callback

アクションが @code{"callback"} であるオプションに対し、このオプションがあったときに呼ばれる呼び出し可能オブジェクトです。呼び出し時に渡される引数の詳細については、 @ref{33f5,,オプション処理コールバック} を参照してください。
@end deffn

@geindex callback_args (optparse.Option の属性)
@geindex callback_kwargs (optparse.Option の属性)
@anchor{library/optparse optparse Option callback_args}@anchor{3419}
@deffn {の属性} Option.callback_args
@anchor{library/optparse optparse Option callback_kwargs}@anchor{341a}
@deffnx {の属性} Option.callback_kwargs

@code{callback} に渡される標準的な4つのコールバック引数の後ろに追加する、位置引数とキーワード引数。
@end deffn

@geindex help (optparse.Option の属性)
@anchor{library/optparse optparse Option help}@anchor{33e9}
@deffn {の属性} Option.help

ユーザが @ref{33e9,,help} オプション(@code{--help} のような)を指定したときに表示される、使用可能な全オプションのリストの中のこのオプションに関する説明文です。説明文を提供しておかなければ、オプションは説明文なしで表示されます。オプションを隠すには特殊な値 @code{optparse.SUPPRESS_HELP} を使います。
@end deffn

@geindex metavar (optparse.Option の属性)
@anchor{library/optparse optparse Option metavar}@anchor{341b}
@deffn {の属性} Option.metavar

(デフォルト: オプション文字列を使う)

説明文を表示する際にオプションの引数の身代わりになるものです。例は @ref{33e4,,チュートリアル} 節を参照してください。
@end deffn

@node 標準的なオプション・アクション,標準のオプション型,オプション属性,リファレンスガイド
@anchor{library/optparse optparse-standard-option-actions}@anchor{340f}@anchor{library/optparse standard-option-actions}@anchor{341c}
@subsubsection 標準的なオプション・アクション


The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to
guide @code{optparse}'s behaviour; a few have required attributes, which you
must specify for any option using that action.


@itemize *

@item 
@code{"store"} [関連: @ref{33e7,,type}, @ref{33e8,,dest}, @ref{3416,,nargs}, @ref{3417,,choices}]

オプションの後には必ず引数が続きます。引数は @ref{33e7,,type} に従って値に変換されて @ref{33e8,,dest} に保存されます。 @ref{3416,,nargs} > 1 の場合、複数の引数をコマンドラインから取り出します。引数は全て @ref{33e7,,type} に従って変換され、 @ref{33e8,,dest} にタプルとして保存されます。 @ref{3413,,標準のオプション型} 節を参照してください。

@ref{3417,,choices} を(文字列のリストかタプルで) 指定した場合、型のデフォルト値は @code{"choice"} になります。

@ref{33e7,,type} を指定しない場合、デフォルトの値は @code{"string"} です。

If @ref{33e8,,dest} is not supplied, @code{optparse} derives a destination
from the first long option string (e.g., @code{--foo-bar} implies
@code{foo_bar}). If there are no long option strings, @code{optparse} derives a
destination from the first short option string (e.g., @code{-f} implies @code{f}).

以下はプログラム例です:

@example
parser.add_option("-f")
parser.add_option("-p", type="float", nargs=3, dest="point")
@end example

とすると、以下のようなコマンドライン

@example
-f foo.txt -p 1 -3.5 4 -fbar.txt
@end example

@code{optparse} will set

@example
options.f = "foo.txt"
options.point = (1.0, -3.5, 4.0)
options.f = "bar.txt"
@end example

@item 
@code{"store_const"} [関連: @ref{33f3,,const}; 関連: @ref{33e8,,dest}]

値 @ref{33f3,,const} を @ref{33e8,,dest} に保存します。

以下はプログラム例です:

@example
parser.add_option("-q", "--quiet",
                  action="store_const", const=0, dest="verbose")
parser.add_option("-v", "--verbose",
                  action="store_const", const=1, dest="verbose")
parser.add_option("--noisy",
                  action="store_const", const=2, dest="verbose")
@end example

If @code{--noisy} is seen, @code{optparse} will set

@example
options.verbose = 2
@end example

@item 
@code{"store_true"} [関連: @ref{33e8,,dest}]

A special case of @code{"store_const"} that stores @code{True} to
@ref{33e8,,dest}.

@item 
@code{"store_false"} [関連: @ref{33e8,,dest}]

Like @code{"store_true"}, but stores @code{False}.

以下はプログラム例です:

@example
parser.add_option("--clobber", action="store_true", dest="clobber")
parser.add_option("--no-clobber", action="store_false", dest="clobber")
@end example

@item 
@code{"append"} [関連: @ref{33e7,,type}, @ref{33e8,,dest}, @ref{3416,,nargs}, @ref{3417,,choices}]

The option must be followed by an argument, which is appended to the list in
@ref{33e8,,dest}.  If no default value for @ref{33e8,,dest} is
supplied, an empty list is automatically created when @code{optparse} first
encounters this option on the command-line.  If @ref{3416,,nargs} > 1,
multiple arguments are consumed, and a tuple of length @ref{3416,,nargs}
is appended to @ref{33e8,,dest}.

@ref{33e7,,type} および @ref{33e8,,dest} のデフォルト値は @code{"store"} アクションと同じです。

以下はプログラム例です:

@example
parser.add_option("-t", "--tracks", action="append", type="int")
@end example

If @code{-t3} is seen on the command-line, @code{optparse} does the equivalent
of:

@example
options.tracks = []
options.tracks.append(int("3"))
@end example

その後、@code{--tracks=4} が見つかると以下を実行します:

@example
options.tracks.append(int("4"))
@end example

@code{append} アクションは、オプションの現在の値の @code{append} メソッドを呼び出します。これは、どのデフォルト値も @code{append} メソッドを持っていなければならないことを意味します。また、デフォルト値が空でない場合、オプションの解析結果は、そのデフォルトの要素の後ろにコマンドラインからの値が追加されたものになる、ということも意味します:

@example
>>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
>>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
>>> opts.files
['~/.mypkg/defaults', 'overrides.mypkg']
@end example

@item 
@code{"append_const"} [関連: @ref{33f3,,const}; 関連: @ref{33e8,,dest}]

@code{"store_const"} と同様ですが、 @ref{33f3,,const} の値は @ref{33e8,,dest} に追加(append)されます。 @code{"append"} の場合と同じように @ref{33e8,,dest} のデフォルトは @code{None} ですがこのオプションを最初にみつけた時点で空のリストを自動的に生成します。

@item 
@code{"count"} [関連: @ref{33e8,,dest}]

@ref{33e8,,dest} に保存されている整数値をインクリメントします。 @ref{33e8,,dest} は (デフォルトの値を指定しない限り) 最初にインクリメントを行う前にゼロに設定されます。

以下はプログラム例です:

@example
parser.add_option("-v", action="count", dest="verbosity")
@end example

The first time @code{-v} is seen on the command line, @code{optparse} does the
equivalent of:

@example
options.verbosity = 0
options.verbosity += 1
@end example

以後、@code{-v} が見つかるたびに

@example
options.verbosity += 1
@end example

@item 
@code{"callback"} [必須: @ref{3418,,callback}; 関連: @ref{33e7,,type}, @ref{3416,,nargs}, @ref{3419,,callback_args}, @ref{341a,,callback_kwargs}]

@ref{3418,,callback} に指定された関数を次のように呼び出します

@example
func(option, opt_str, value, parser, *args, **kwargs)
@end example

詳細は、 @ref{33f5,,オプション処理コールバック} 節を参照してください。

@item 
@code{"help"}

現在のオプションパーザ内の全てのオプションに対する完全なヘルプメッセージを出力します。ヘルプメッセージは @ref{16e6,,OptionParser} のコンストラクタに渡した @code{usage}  文字列と、各オプションに渡した @ref{33e9,,help} 文字列から生成します。

オプションに @ref{33e9,,help} 文字列が指定されていなくても、オプションはヘルプメッセージ中に列挙されます。オプションを完全に表示させないようにするには、特殊な値 @code{optparse.SUPPRESS_HELP} を使ってください。

@code{optparse} automatically adds a @ref{33e9,,help} option to all
OptionParsers, so you do not normally need to create one.

以下はプログラム例です:

@example
from optparse import OptionParser, SUPPRESS_HELP

# usually, a help option is added automatically, but that can
# be suppressed using the add_help_option argument
parser = OptionParser(add_help_option=False)

parser.add_option("-h", "--help", action="help")
parser.add_option("-v", action="store_true", dest="verbose",
                  help="Be moderately verbose")
parser.add_option("--file", dest="filename",
                  help="Input file to read data from")
parser.add_option("--secret", help=SUPPRESS_HELP)
@end example

If @code{optparse} sees either @code{-h} or @code{--help} on the command line,
it will print something like the following help message to stdout (assuming
@code{sys.argv[0]} is @code{"foo.py"}):

@example
Usage: foo.py [options]

Options:
  -h, --help        Show this help message and exit
  -v                Be moderately verbose
  --file=FILENAME   Input file to read data from
@end example

After printing the help message, @code{optparse} terminates your process with
@code{sys.exit(0)}.

@item 
@code{"version"}

Prints the version number supplied to the OptionParser to stdout and exits.
The version number is actually formatted and printed by the
@code{print_version()} method of OptionParser.  Generally only relevant if the
@code{version} argument is supplied to the OptionParser constructor.  As with
@ref{33e9,,help} options, you will rarely create @code{version} options,
since @code{optparse} automatically adds them when needed.
@end itemize

@node 標準のオプション型,引数を解析する,標準的なオプション・アクション,リファレンスガイド
@anchor{library/optparse optparse-standard-option-types}@anchor{3413}@anchor{library/optparse standard-option-types}@anchor{341d}
@subsubsection 標準のオプション型


@code{optparse} has five built-in option types: @code{"string"}, @code{"int"},
@code{"choice"}, @code{"float"} and @code{"complex"}.  If you need to add new
option types, see section @ref{33ec,,Extending optparse}.

文字列オプションの引数はチェックや変換を一切受けません: コマンドライン上のテキストは保存先にそのまま保存されます (またはコールバックに渡されます)。

整数引数 (@code{"int"} 型) は次のように解析されます:


@itemize *

@item 
数が @code{0x} から始まるならば、16進数として読み取られます

@item 
数が @code{0} から始まるならば、8進数として読み取られます

@item 
数が @code{0b} から始まるならば、2進数として読み取られます

@item 
それ以外の場合、数は10進数として読み取られます
@end itemize

The conversion is done by calling @ref{19b,,int()} with the appropriate base (2, 8,
10, or 16).  If this fails, so will @code{optparse}, although with a more useful
error message.

@code{"float"} および @code{"complex"} のオプション引数は直接 @ref{196,,float()} や @ref{197,,complex()} で変換されます。エラーは同様の扱いです。

@code{"choice"} オプションは @code{"string"} オプションのサブタイプです。 @ref{3417,,choices} オプションの属性 (文字列からなるシーケンス) には、利用できるオプション引数のセットを指定します。 @code{optparse.check_choice()} はユーザの指定したオプション引数とマスタリストを比較して、無効な文字列が指定された場合には @ref{33d6,,OptionValueError} を送出します。

@node 引数を解析する,オプション解析器への問い合わせと操作,標準のオプション型,リファレンスガイド
@anchor{library/optparse optparse-parsing-arguments}@anchor{3410}@anchor{library/optparse parsing-arguments}@anchor{341e}
@subsubsection 引数を解析する


OptionParser を作成してオプションを追加していく上で大事なポイントは、 @ref{16e7,,parse_args()} メソッドの呼び出しです。

@geindex parse_args() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser parse_args}@anchor{16e7}
@deffn {メソッド} OptionParser.parse_args (args=None, values=None)

Parse the command-line options found in `args'.

The input parameters are


@table @asis

@item @code{args}

処理する引数のリスト (デフォルト: @code{sys.argv[1:]})

@item @code{values}

オプション引数を格納する @ref{33d4,,Values} のオブジェクト (デフォルト: 新しい @ref{33d4,,Values} のインスタンス) -- 既存のオブジェクトを指定した場合、オプションのデフォルトは初期化されません
@end table

and the return value is a pair @code{(options, args)} where


@table @asis

@item @code{options}

the same object that was passed in as `values', or the @code{optparse.Values}
instance created by @code{optparse}

@item @code{args}

全てのオプションの処理が終わった後で残った位置引数
@end table
@end deffn

一番普通の使い方は一切キーワード引数を使わないというものです。 @code{values} を指定した場合、それは繰り返される @ref{25be,,setattr()} の呼び出し (大雑把に言うと保存される各オプション引数につき一回ずつ) で更新されていき、 @ref{16e7,,parse_args()} で返されます。

@ref{16e7,,parse_args()} が引数リストでエラーに遭遇した場合、 OptionParser の @code{error()} メソッドを適切なエンドユーザ向けのエラーメッセージとともに呼び出します。この呼び出しにより、最終的に終了ステータス 2 (伝統的な Unix におけるコマンドラインエラーの終了ステータス) でプロセスを終了させることになります。

@node オプション解析器への問い合わせと操作,オプション間の衝突,引数を解析する,リファレンスガイド
@anchor{library/optparse optparse-querying-manipulating-option-parser}@anchor{341f}@anchor{library/optparse querying-and-manipulating-your-option-parser}@anchor{3420}
@subsubsection オプション解析器への問い合わせと操作


オプションパーザのデフォルトの振る舞いは、ある程度カスタマイズすることができます。また、オプションパーザの中を調べることもできます。@ref{16e6,,OptionParser} は幾つかのヘルパーメソッドを提供しています:

@geindex disable_interspersed_args() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser disable_interspersed_args}@anchor{33d3}
@deffn {メソッド} OptionParser.disable_interspersed_args ()

Set parsing to stop on the first non-option.  For example, if @code{-a} and
@code{-b} are both simple options that take no arguments, @code{optparse}
normally accepts this syntax:

@example
prog -a arg1 -b arg2
@end example

それを次と同じように扱います

@example
prog -a -b arg1 arg2
@end example

この機能を無効にしたいときは、 @ref{33d3,,disable_interspersed_args()} メソッドを呼び出してください。古典的な Unix システムのように、最初のオプションでない引数を見つけたときにオプションの解析を止めるようになります。

別のコマンドを実行するコマンドをプロセッサを作成する際、別のコマンドのオプションと自身のオプションが混ざるのを防ぐために利用することができます。例えば、各コマンドがそれぞれ異なるオプションのセットを持つ場合などに有効です。
@end deffn

@geindex enable_interspersed_args() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser enable_interspersed_args}@anchor{3421}
@deffn {メソッド} OptionParser.enable_interspersed_args ()

オプションで無い最初の引数を見つけてもパースを止めないように設定します。オプションとコマンド引数の順序が混ざっても良いようになります。これはデフォルトの動作です。
@end deffn

@geindex get_option() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser get_option}@anchor{3422}
@deffn {メソッド} OptionParser.get_option (opt_str)

オプション文字列 `opt_str' に対する @ref{340c,,Option} インスタンスを返します。該当するオプションがなければ @code{None} を返します。
@end deffn

@geindex has_option() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser has_option}@anchor{3423}
@deffn {メソッド} OptionParser.has_option (opt_str)

@ref{16e6,,OptionParser} に(@code{-q} や @code{--verbose} のような) オプション `opt_str' がある場合、@code{True} を返します。
@end deffn

@geindex remove_option() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser remove_option}@anchor{3424}
@deffn {メソッド} OptionParser.remove_option (opt_str)

@ref{16e6,,OptionParser} に `opt_str' に対応するオプションがある場合、そのオプションを削除します。該当するオプションに他のオプション文字列が指定されていた場合、それらのオプション文字列は全て無効になります。 `opt_str' がこの @ref{16e6,,OptionParser} オブジェクトのどのオプションにも属さない場合、 @ref{2ec,,ValueError} を送出します。
@end deffn

@node オプション間の衝突,クリーンアップ,オプション解析器への問い合わせと操作,リファレンスガイド
@anchor{library/optparse conflicts-between-options}@anchor{3425}@anchor{library/optparse optparse-conflicts-between-options}@anchor{3409}
@subsubsection オプション間の衝突


注意が足りないと、衝突するオプションを定義してしまうことがあります:

@example
parser.add_option("-n", "--dry-run", ...)
...
parser.add_option("-n", "--noisy", ...)
@end example

(とりわけ、@ref{16e6,,OptionParser} から標準的なオプションを備えた自前のサブクラスを定義してしまった場合にはよく起きます。)

Every time you add an option, @code{optparse} checks for conflicts with existing
options.  If it finds any, it invokes the current conflict-handling mechanism.
You can set the conflict-handling mechanism either in the constructor:

@example
parser = OptionParser(..., conflict_handler=handler)
@end example

個別にも呼び出せます:

@example
parser.set_conflict_handler(handler)
@end example

衝突時の処理をおこなうハンドラ(handler)には、以下のものが利用できます:

@quotation


@table @asis

@item @code{"error"} (デフォルト)

オプション間の衝突をプログラム上のエラーとみなし、 @ref{3426,,OptionConflictError} を送出します

@item @code{"resolve"}

オプション間の衝突をインテリジェントに解決します (下記参照)
@end table
@end quotation

一例として、衝突をインテリジェントに解決する @ref{16e6,,OptionParser} を定義し、衝突を起こすようなオプションを追加してみましょう:

@example
parser = OptionParser(conflict_handler="resolve")
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option("-n", "--noisy", ..., help="be noisy")
@end example

At this point, @code{optparse} detects that a previously added option is already
using the @code{-n} option string.  Since @code{conflict_handler} is @code{"resolve"},
it resolves the situation by removing @code{-n} from the earlier option's list of
option strings.  Now @code{--dry-run} is the only way for the user to activate
that option.  If the user asks for help, the help message will reflect that:

@example
Options:
  --dry-run     do no harm
  ...
  -n, --noisy   be noisy
@end example

It's possible to whittle away the option strings for a previously added option
until there are none left, and the user has no way of invoking that option from
the command-line.  In that case, @code{optparse} removes that option completely,
so it doesn't show up in help text or anywhere else. Carrying on with our
existing OptionParser:

@example
parser.add_option("--dry-run", ..., help="new dry-run option")
@end example

At this point, the original @code{-n}/@code{--dry-run} option is no longer
accessible, so @code{optparse} removes it, leaving this help text:

@example
Options:
  ...
  -n, --noisy   be noisy
  --dry-run     new dry-run option
@end example

@node クリーンアップ,その他のメソッド,オプション間の衝突,リファレンスガイド
@anchor{library/optparse cleanup}@anchor{3427}@anchor{library/optparse optparse-cleanup}@anchor{3428}
@subsubsection クリーンアップ


OptionParser インスタンスはいくつかの循環参照を抱えています。このことは Python のガーベジコレクタにとって問題になるわけではありませんが、使い終わった OptionParser に対して @code{destroy()} を呼び出すことでこの循環参照を意図的に断ち切るという方法を選ぶこともできます。この方法は特に長時間実行するアプリケーションで OptionParser から大きなオブジェクトグラフが到達可能になっているような場合に有用です。

@node その他のメソッド,,クリーンアップ,リファレンスガイド
@anchor{library/optparse optparse-other-methods}@anchor{3429}@anchor{library/optparse other-methods}@anchor{342a}
@subsubsection その他のメソッド


OptionParser にはその他にも幾つかの公開されたメソッドがあります:

@geindex set_usage() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser set_usage}@anchor{342b}
@deffn {メソッド} OptionParser.set_usage (usage)

上で説明したコンストラクタの @code{usage} キーワード引数での規則に従った使用法の文字列をセットします。 @code{None} を渡すとデフォルトの使用法文字列が使われるようになり、 @code{optparse.SUPPRESS_USAGE} によって使用法メッセージを抑制できます。
@end deffn

@geindex print_usage() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser print_usage}@anchor{3400}
@deffn {メソッド} OptionParser.print_usage (file=None)

現在のプログラムの使用法メッセージ (@code{self.usage}) を `file' (デフォルト: stdout) に表示します。@code{self.usage} 内にある全ての @code{%prog} という文字列は現在のプログラム名に置換されます。@code{self.usage} が空もしくは未定義の時は何もしません。
@end deffn

@geindex get_usage() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser get_usage}@anchor{342c}
@deffn {メソッド} OptionParser.get_usage ()

@ref{3400,,print_usage()} と同じですが、使用法メッセージを表示する代わりに文字列として返します。
@end deffn

@geindex set_defaults() (optparse.OptionParser のメソッド)
@anchor{library/optparse optparse OptionParser set_defaults}@anchor{3415}
@deffn {メソッド} OptionParser.set_defaults (dest=value, ...)

幾つかの保存先に対してデフォルト値をまとめてセットします。 @ref{3415,,set_defaults()} を使うのは複数のオプションにデフォルト値をセットする好ましいやり方です。複数のオプションが同じ保存先を共有することがあり得るからです。たとえば幾つかの "mode" オプションが全て同じ保存先をセットするものだったとすると、どのオプションもデフォルトをセットすることができ、しかし最後に指定したものだけが有効になります:

@example
parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced",
                  default="novice")    # overridden below
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice",
                  default="advanced")  # overrides above setting
@end example

こうした混乱を避けるために @ref{3415,,set_defaults()} を使います:

@example
parser.set_defaults(mode="advanced")
parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced")
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice")
@end example
@end deffn

@node オプション処理コールバック,Extending optparse,リファレンスガイド,optparse --- Parser for command line options
@anchor{library/optparse option-callbacks}@anchor{342d}@anchor{library/optparse optparse-option-callbacks}@anchor{33f5}
@subsubsection オプション処理コールバック


When @code{optparse}'s built-in actions and types aren't quite enough for your
needs, you have two choices: extend @code{optparse} or define a callback option.
Extending @code{optparse} is more general, but overkill for a lot of simple
cases.  Quite often a simple callback is all you need.

@code{callback} オプションの定義は二つのステップからなります:


@itemize *

@item 
@code{"callback"} アクションを使ってオプション自体を定義する

@item 
コールバックを書く。コールバックは少なくとも後で説明する 4 つの引数をとる関数 (またはメソッド) でなければなりません
@end itemize

@menu
* callbackオプションの定義:: 
* コールバック関数はどのように呼び出されるか:: 
* コールバック中で例外を送出する:: 
* コールバックの例 1; ありふれたコールバック: コールバックの例 1 ありふれたコールバック. 
* コールバックの例 2; オプションの順番をチェックする: コールバックの例 2 オプションの順番をチェックする. 
* コールバックの例 3; オプションの順番をチェックする (汎用的): コールバックの例 3 オプションの順番をチェックする 汎用的. 
* コールバックの例 4; 任意の条件をチェックする: コールバックの例 4 任意の条件をチェックする. 
* コールバックの例5; 固定引数: コールバックの例5 固定引数. 
* コールバックの例6; 可変個の引数: コールバックの例6 可変個の引数. 

@end menu

@node callbackオプションの定義,コールバック関数はどのように呼び出されるか,,オプション処理コールバック
@anchor{library/optparse defining-a-callback-option}@anchor{342e}@anchor{library/optparse optparse-defining-callback-option}@anchor{342f}
@subsubsection callbackオプションの定義


callback オプションを最も簡単に定義するには、 @ref{33d2,,OptionParser.add_option()} メソッドを使います。 @ref{33e6,,action} の他に指定しなければならない属性は @code{callback} すなわちコールバックする関数自体です:

@example
parser.add_option("-c", action="callback", callback=my_callback)
@end example

@code{callback} is a function (or other callable object), so you must have already
defined @code{my_callback()} when you create this callback option. In this simple
case, @code{optparse} doesn't even know if @code{-c} takes any arguments,
which usually means that the option takes no arguments---the mere presence of
@code{-c} on the command-line is all it needs to know.  In some
circumstances, though, you might want your callback to consume an arbitrary
number of command-line arguments.  This is where writing callbacks gets tricky;
it's covered later in this section.

@code{optparse} always passes four particular arguments to your callback, and it
will only pass additional arguments if you specify them via
@ref{3419,,callback_args} and @ref{341a,,callback_kwargs}.  Thus, the
minimal callback function signature is:

@example
def my_callback(option, opt, value, parser):
@end example

コールバックの四つの引数については後で説明します。

callback オプションを定義する場合には、他にもいくつかオプション属性を指定できます:


@table @asis

@item @ref{33e7,,type}

has its usual meaning: as with the @code{"store"} or @code{"append"} actions, it
instructs @code{optparse} to consume one argument and convert it to
@ref{33e7,,type}.  Rather than storing the converted value(s) anywhere,
though, @code{optparse} passes it to your callback function.

@item @ref{3416,,nargs}

also has its usual meaning: if it is supplied and > 1, @code{optparse} will
consume @ref{3416,,nargs} arguments, each of which must be convertible to
@ref{33e7,,type}.  It then passes a tuple of converted values to your
callback.

@item @ref{3419,,callback_args}

その他の位置引数からなるタプルで、コールバックに渡されます

@item @ref{341a,,callback_kwargs}

その他のキーワード引数からなる辞書で、コールバックに渡されます
@end table

@node コールバック関数はどのように呼び出されるか,コールバック中で例外を送出する,callbackオプションの定義,オプション処理コールバック
@anchor{library/optparse how-callbacks-are-called}@anchor{3430}@anchor{library/optparse optparse-how-callbacks-called}@anchor{3431}
@subsubsection コールバック関数はどのように呼び出されるか


コールバックは全て以下の形式で呼び出されます:

@example
func(option, opt_str, value, parser, *args, **kwargs)
@end example

ここでは:


@table @asis

@item @code{option}

コールバックを呼び出している @ref{340c,,Option} のインスタンスです

@item @code{opt_str}

は、コールバック呼び出しのきっかけとなったコマンドライン上のオプション文字列です。(長い形式のオプションに対する省略形が使われている場合、@code{opt_str} は完全な、正式な形のオプション文字列となります --- 例えば、ユーザが @code{--foobar} の短縮形として @code{--foo} をコマンドラインに入力した時には、@code{opt_str} は @code{"--foobar"} となります。)

@item @code{value}

is the argument to this option seen on the command-line.  @code{optparse} will
only expect an argument if @ref{33e7,,type} is set; the type of @code{value} will be
the type implied by the option's type.  If @ref{33e7,,type} for this option is
@code{None} (no argument expected), then @code{value} will be @code{None}.  If @ref{3416,,nargs}
> 1, @code{value} will be a tuple of values of the appropriate type.

@item @code{parser}

現在のオプション解析の全てを駆動している @ref{16e6,,OptionParser} インスタンスです。この変数が有用なのは、この値を介してインスタンス属性としていくつかの興味深いデータにアクセスできるからです:


@table @asis

@item @code{parser.largs}

現在放置されている引数、すなわち、すでに消費されたものの、オプションでもオプション引数でもない引数からなるリストです。 @code{parser.largs} は自由に変更でき、たとえば引数を追加したりできます (このリストは @code{args} 、すなわち @ref{16e7,,parse_args()} の二つ目の戻り値になります)

@item @code{parser.rargs}

現在残っている引数、すなわち、@code{opt_str} および @code{value} があれば除き、それ以外の引数が残っているリストです。@code{parser.rargs} は自由に変更でき、例えばさらに引数を消費したりできます。

@item @code{parser.values}

the object where option values are by default stored (an instance of
optparse.OptionValues).  This lets callbacks use the same mechanism as the
rest of @code{optparse} for storing option values; you don't need to mess
around with globals or closures.  You can also access or modify the
value(s) of any options already encountered on the command-line.
@end table

@item @code{args}

@ref{3419,,callback_args} オプション属性で与えられた任意の位置引数からなるタプルです。

@item @code{kwargs}

@ref{341a,,callback_kwargs} オプション属性で与えられた任意のキーワード引数からなるタプルです。
@end table

@node コールバック中で例外を送出する,コールバックの例 1 ありふれたコールバック,コールバック関数はどのように呼び出されるか,オプション処理コールバック
@anchor{library/optparse optparse-raising-errors-in-callback}@anchor{3432}@anchor{library/optparse raising-errors-in-a-callback}@anchor{3433}
@subsubsection コールバック中で例外を送出する


The callback function should raise @ref{33d6,,OptionValueError} if there are any
problems with the option or its argument(s).  @code{optparse} catches this and
terminates the program, printing the error message you supply to stderr.  Your
message should be clear, concise, accurate, and mention the option at fault.
Otherwise, the user will have a hard time figuring out what they did wrong.

@node コールバックの例 1 ありふれたコールバック,コールバックの例 2 オプションの順番をチェックする,コールバック中で例外を送出する,オプション処理コールバック
@anchor{library/optparse callback-example-1-trivial-callback}@anchor{3434}@anchor{library/optparse optparse-callback-example-1}@anchor{3435}
@subsubsection コールバックの例 1: ありふれたコールバック


引数をとらず、発見したオプションを単に記録するだけのコールバックオプションの例を以下に示します:

@example
def record_foo_seen(option, opt_str, value, parser):
    parser.values.saw_foo = True

parser.add_option("--foo", action="callback", callback=record_foo_seen)
@end example

もちろん、@code{"store_true"} アクションを使っても実現できます。

@node コールバックの例 2 オプションの順番をチェックする,コールバックの例 3 オプションの順番をチェックする 汎用的,コールバックの例 1 ありふれたコールバック,オプション処理コールバック
@anchor{library/optparse callback-example-2-check-option-order}@anchor{3436}@anchor{library/optparse optparse-callback-example-2}@anchor{3437}
@subsubsection コールバックの例 2: オプションの順番をチェックする


もう少し面白みのある例を示します: この例では、@code{-b} を発見して、その後で @code{-a} がコマンドライン中に現れた場合にはエラーになります。

@example
def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use -a after -b")
    parser.values.a = 1
...
parser.add_option("-a", action="callback", callback=check_order)
parser.add_option("-b", action="store_true", dest="b")
@end example

@node コールバックの例 3 オプションの順番をチェックする 汎用的,コールバックの例 4 任意の条件をチェックする,コールバックの例 2 オプションの順番をチェックする,オプション処理コールバック
@anchor{library/optparse callback-example-3-check-option-order-generalized}@anchor{3438}@anchor{library/optparse optparse-callback-example-3}@anchor{3439}
@subsubsection コールバックの例 3: オプションの順番をチェックする (汎用的)


このコールバック (フラグを立てるが、@code{-b} が既に指定されていればエラーになる) を同様の複数のオプションに対して再利用したければ、もう少し作業する必要があります: エラーメッセージとセットされるフラグを一般化しなければなりません。

@example
def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use %s after -b" % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("-a", action="callback", callback=check_order, dest='a')
parser.add_option("-b", action="store_true", dest="b")
parser.add_option("-c", action="callback", callback=check_order, dest='c')
@end example

@node コールバックの例 4 任意の条件をチェックする,コールバックの例5 固定引数,コールバックの例 3 オプションの順番をチェックする 汎用的,オプション処理コールバック
@anchor{library/optparse callback-example-4-check-arbitrary-condition}@anchor{343a}@anchor{library/optparse optparse-callback-example-4}@anchor{343b}
@subsubsection コールバックの例 4: 任意の条件をチェックする


もちろん、単に定義済みのオプションの値を調べるだけにとどまらず、コールバックには任意の条件を入れられます。例えば、満月でなければ呼び出してはならないオプションがあるとしましょう。やらなければならないことはこれだけです:

@example
def check_moon(option, opt_str, value, parser):
    if is_moon_full():
        raise OptionValueError("%s option invalid when moon is full"
                               % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("--foo",
                  action="callback", callback=check_moon, dest="foo")
@end example

(@code{is_moon_full()} の定義は読者への課題としましょう。)

@node コールバックの例5 固定引数,コールバックの例6 可変個の引数,コールバックの例 4 任意の条件をチェックする,オプション処理コールバック
@anchor{library/optparse callback-example-5-fixed-arguments}@anchor{343c}@anchor{library/optparse optparse-callback-example-5}@anchor{343d}
@subsubsection コールバックの例5: 固定引数


決まった数の引数をとるようなコールパックオプションを定義するなら、問題はやや興味深くなってきます。引数をとるようコールバックに指定するのは、 @code{"store"} や @code{"append"} オプションの定義に似ています。 @ref{33e7,,type} を定義していれば、そのオプションは引数を受け取ったときに該当する型に変換できなければなりません。さらに @ref{3416,,nargs} を指定すれば、オプションは @ref{3416,,nargs} 個の引数を受け取ります。

標準の @code{"store"} アクションをエミュレートする例を以下に示します:

@example
def store_value(option, opt_str, value, parser):
    setattr(parser.values, option.dest, value)
...
parser.add_option("--foo",
                  action="callback", callback=store_value,
                  type="int", nargs=3, dest="foo")
@end example

Note that @code{optparse} takes care of consuming 3 arguments and converting
them to integers for you; all you have to do is store them.  (Or whatever;
obviously you don't need a callback for this example.)

@node コールバックの例6 可変個の引数,,コールバックの例5 固定引数,オプション処理コールバック
@anchor{library/optparse callback-example-6-variable-arguments}@anchor{343e}@anchor{library/optparse optparse-callback-example-6}@anchor{343f}
@subsubsection コールバックの例6: 可変個の引数


Things get hairy when you want an option to take a variable number of arguments.
For this case, you must write a callback, as @code{optparse} doesn't provide any
built-in capabilities for it.  And you have to deal with certain intricacies of
conventional Unix command-line parsing that @code{optparse} normally handles for
you.  In particular, callbacks should implement the conventional rules for bare
@code{--} and @code{-} arguments:


@itemize *

@item 
either @code{--} or @code{-} can be option arguments

@item 
裸の @code{--} (何らかのオプションの引数でない場合): コマンドライン処理を停止し、@code{--} を無視します

@item 
裸の @code{-} (何らかのオプションの引数でない場合): コマンドライン処理を停止しますが、@code{-} は残します (@code{parser.largs} に追加します)
@end itemize

If you want an option that takes a variable number of arguments, there are
several subtle, tricky issues to worry about.  The exact implementation you
choose will be based on which trade-offs you're willing to make for your
application (which is why @code{optparse} doesn't support this sort of thing
directly).

とはいえ、可変個の引数をもつオプションに対するスタブ (stub、仲介インターフェース) を以下に示しておきます:

@example
def vararg_callback(option, opt_str, value, parser):
    assert value is None
    value = []

    def floatable(str):
        try:
            float(str)
            return True
        except ValueError:
            return False

    for arg in parser.rargs:
        # stop on --foo like options
        if arg[:2] == "--" and len(arg) > 2:
            break
        # stop on -a, but not on -3 or -3.0
        if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
            break
        value.append(arg)

    del parser.rargs[:len(value)]
    setattr(parser.values, option.dest, value)

...
parser.add_option("-c", "--callback", dest="vararg_attr",
                  action="callback", callback=vararg_callback)
@end example

@node Extending optparse,例外<12>,オプション処理コールバック,optparse --- Parser for command line options
@anchor{library/optparse extending-optparse}@anchor{3440}@anchor{library/optparse optparse-extending-optparse}@anchor{33ec}
@subsubsection Extending @code{optparse}


Since the two major controlling factors in how @code{optparse} interprets
command-line options are the action and type of each option, the most likely
direction of extension is to add new actions and new types.

@menu
* 新しい型の追加:: 
* 新しいアクションの追加:: 

@end menu

@node 新しい型の追加,新しいアクションの追加,,Extending optparse
@anchor{library/optparse adding-new-types}@anchor{3441}@anchor{library/optparse optparse-adding-new-types}@anchor{3442}
@subsubsection 新しい型の追加


To add new types, you need to define your own subclass of @code{optparse}'s
@ref{340c,,Option} class.  This class has a couple of attributes that define
@code{optparse}'s types: @ref{3443,,TYPES} and @ref{3444,,TYPE_CHECKER}.

@geindex TYPES (optparse.Option の属性)
@anchor{library/optparse optparse Option TYPES}@anchor{3443}
@deffn {の属性} Option.TYPES

@ref{3443,,TYPES} は型名のタプルです。新しく作るサブクラスでは、タプル @ref{3443,,TYPES} を単純に標準のものを利用して新しく定義すると良いでしょう。
@end deffn

@geindex TYPE_CHECKER (optparse.Option の属性)
@anchor{library/optparse optparse Option TYPE_CHECKER}@anchor{3444}
@deffn {の属性} Option.TYPE_CHECKER

@code{TYPE_CHECKER} は辞書で型名を型チェック関数に対応付けるものです。型チェック関数は以下のようなシグネチャを持ちます:

@example
def check_mytype(option, opt, value)
@end example

ここで @code{option} は @ref{340c,,Option} のインスタンスであり、 @code{opt} はオプション文字列(たとえば @code{-f})で、 @code{value} は望みの型としてチェックされ変換されるべくコマンドラインで与えられる文字列です。 @code{check_mytype()} は想定されている型 @code{mytype} のオブジェクトを返さなければなりません。型チェック関数から返される値は @ref{16e7,,OptionParser.parse_args()} で返されるOptionValues インスタンスに収められるか、またはコールバックに @code{value} パラメータとして渡されます。

型チェック関数は何か問題に遭遇したら @ref{33d6,,OptionValueError} を送出しなければなりません。 @ref{33d6,,OptionValueError} は文字列一つを引数に取り、それはそのまま @ref{16e6,,OptionParser} の @code{error()} メソッドに渡され、そこでプログラム名と文字列 @code{"error:"} が前置されてプロセスが終了する前に stderr に出力されます。
@end deffn

Here's a silly example that demonstrates adding a @code{"complex"} option type to
parse Python-style complex numbers on the command line.  (This is even sillier
than it used to be, because @code{optparse} 1.3 added built-in support for
complex numbers, but never mind.)

最初に必要な import 文を書きます:

@example
from copy import copy
from optparse import Option, OptionValueError
@end example

まずは型チェック関数を定義しなければなりません。これは後で(これから定義する Option のサブクラスの @ref{3444,,TYPE_CHECKER} クラス属性の中で) 参照されることになります:

@example
def check_complex(option, opt, value):
    try:
        return complex(value)
    except ValueError:
        raise OptionValueError(
            "option %s: invalid complex value: %r" % (opt, value))
@end example

最後に Option のサブクラスです:

@example
class MyOption (Option):
    TYPES = Option.TYPES + ("complex",)
    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
    TYPE_CHECKER["complex"] = check_complex
@end example

(If we didn't make a @ref{29,,copy()} of @ref{3444,,Option.TYPE_CHECKER}, we would end
up modifying the @ref{3444,,TYPE_CHECKER} attribute of @code{optparse}'s
Option class.  This being Python, nothing stops you from doing that except good
manners and common sense.)

That's it!  Now you can write a script that uses the new option type just like
any other @code{optparse}-based script, except you have to instruct your
OptionParser to use MyOption instead of Option:

@example
parser = OptionParser(option_class=MyOption)
parser.add_option("-c", type="complex")
@end example

別のやり方として、オプションリストを構築して OptionParser に渡すという方法もあります。 @code{add_option()} を上でやったように使わないならば、OptionParser にどのクラスを使うのか教える必要はありません:

@example
option_list = [MyOption("-c", action="store", type="complex", dest="c")]
parser = OptionParser(option_list=option_list)
@end example

@node 新しいアクションの追加,,新しい型の追加,Extending optparse
@anchor{library/optparse adding-new-actions}@anchor{3445}@anchor{library/optparse optparse-adding-new-actions}@anchor{3446}
@subsubsection 新しいアクションの追加


Adding new actions is a bit trickier, because you have to understand that
@code{optparse} has a couple of classifications for actions:


@table @asis

@item "store" アクション

actions that result in @code{optparse} storing a value to an attribute of the
current OptionValues instance; these options require a @ref{33e8,,dest}
attribute to be supplied to the Option constructor.

@item "typed" アクション

コマンドラインから引数を受け取り、それがある型であることが期待されているアクションです。もう少しはっきり言えば、その型に変換される文字列を受け取るものです。この種類のオプションは Option のコンストラクタに @ref{33e7,,type} 属性を与えることが要求されます。
@end table

この分類には重複する部分があります。デフォルトの "store" アクションには @code{"store"}, @code{"store_const"}, @code{"append"}, @code{"count"} などがありますが、デフォルトの "typed" オプションは @code{"store"}, @code{"append"}, @code{"callback"} の三つです。

アクションを追加する際に、以下の Option のクラス属性(全て文字列のリストです) の中の少なくとも一つに付け加えることでそのアクションを分類する必要があります:

@geindex ACTIONS (optparse.Option の属性)
@anchor{library/optparse optparse Option ACTIONS}@anchor{3447}
@deffn {の属性} Option.ACTIONS

全てのアクションは ACTIONS にリストされていなければなりません。
@end deffn

@geindex STORE_ACTIONS (optparse.Option の属性)
@anchor{library/optparse optparse Option STORE_ACTIONS}@anchor{3448}
@deffn {の属性} Option.STORE_ACTIONS

"store" アクションはここにもリストされます。
@end deffn

@geindex TYPED_ACTIONS (optparse.Option の属性)
@anchor{library/optparse optparse Option TYPED_ACTIONS}@anchor{3449}
@deffn {の属性} Option.TYPED_ACTIONS

"typed" アクションはここにもリストされます。
@end deffn

@geindex ALWAYS_TYPED_ACTIONS (optparse.Option の属性)
@anchor{library/optparse optparse Option ALWAYS_TYPED_ACTIONS}@anchor{344a}
@deffn {の属性} Option.ALWAYS_TYPED_ACTIONS

Actions that always take a type (i.e. whose options always take a value) are
additionally listed here.  The only effect of this is that @code{optparse}
assigns the default type, @code{"string"}, to options with no explicit type
whose action is listed in @ref{344a,,ALWAYS_TYPED_ACTIONS}.
@end deffn

実際に新しいアクションを実装するには、Option の @code{take_action()} メソッドをオーバライドしてそのアクションを認識する場合分けを追加しなければなりません。

例えば、@code{"extend"} アクションというのを追加してみましょう。このアクションは標準的な @code{"append"} アクションと似ていますが、コマンドラインから一つだけ値を読み取って既存のリストに追加するのではなく、複数の値をコンマ区切りの文字列として読み取ってそれらで既存のリストを拡張します。すなわち、もし @code{--names} が @code{"string"} 型の @code{"extend"} オプションだとすると、次のコマンドライン

@example
--names=foo,bar --names blah --names ding,dong
@end example

の結果は次のリストになります

@example
["foo", "bar", "blah", "ding", "dong"]
@end example

再び Option のサブクラスを定義します:

@example
class MyOption(Option):

    ACTIONS = Option.ACTIONS + ("extend",)
    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
    ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            lvalue = value.split(",")
            values.ensure_value(dest, []).extend(lvalue)
        else:
            Option.take_action(
                self, action, dest, opt, value, values, parser)
@end example

注意すべきは次のようなところです:


@itemize *

@item 
@code{"extend"} はコマンドラインの値を予期していると同時にその値をどこかに格納しますので、 @ref{3448,,STORE_ACTIONS} と @ref{3449,,TYPED_ACTIONS} の両方に入ります。

@item 
to ensure that @code{optparse} assigns the default type of @code{"string"} to
@code{"extend"} actions, we put the @code{"extend"} action in
@ref{344a,,ALWAYS_TYPED_ACTIONS} as well.

@item 
@code{MyOption.take_action()} implements just this one new action, and passes
control back to @code{Option.take_action()} for the standard @code{optparse}
actions.

@item 
@code{values} は optparse_parser.Values クラスのインスタンスであり、非常に有用な @code{ensure_value()} メソッドを提供しています。 @code{ensure_value()} は本質的に安全弁付きの @ref{dca,,getattr()} です。次のように呼び出します

@example
values.ensure_value(attr, value)
@end example

@code{values} に @code{attr} 属性が無いか @code{None} だった場合に、 @code{ensure_value()} は最初に @code{value} をセットし、それから @code{value} を返します。この振る舞いは @code{"extend"}, @code{"append"}, @code{"count"} のように、データを変数に集積し、またその変数がある型 (最初の二つはリスト、最後のは整数) であると期待されるアクションを作るのにとても使い易いものです。 @code{ensure_value()} を使えば、作ったアクションを使うスクリプトはオプションに保存先にデフォルト値をセットすることに煩わされずに済みます。デフォルトを @code{None} にしておけば @code{ensure_value()} がそれが必要になったときに適当な値を返してくれます。
@end itemize

@node 例外<12>,,Extending optparse,optparse --- Parser for command line options
@anchor{library/optparse exceptions}@anchor{344b}
@subsubsection 例外


@geindex OptionError
@anchor{library/optparse optparse OptionError}@anchor{33d5}
@deffn {例外} optparse.OptionError

Raised if an @ref{340c,,Option} instance is created with invalid or
inconsistent arguments.
@end deffn

@geindex OptionConflictError
@anchor{library/optparse optparse OptionConflictError}@anchor{3426}
@deffn {例外} optparse.OptionConflictError

Raised if conflicting options are added to an @ref{16e6,,OptionParser}.
@end deffn

@geindex OptionValueError
@anchor{library/optparse optparse OptionValueError}@anchor{33d6}
@deffn {例外} optparse.OptionValueError

Raised if an invalid option value is encountered on the command line.
@end deffn

@geindex BadOptionError
@anchor{library/optparse optparse BadOptionError}@anchor{344c}
@deffn {例外} optparse.BadOptionError

Raised if an invalid option is passed on the command line.
@end deffn

@geindex AmbiguousOptionError
@anchor{library/optparse optparse AmbiguousOptionError}@anchor{344d}
@deffn {例外} optparse.AmbiguousOptionError

Raised if an ambiguous option is passed on the command line.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node getpass --- 可搬性のあるパスワード入力機構,fileinput --- 複数の入力ストリームをまたいだ行を反復する,optparse --- Parser for command line options,コマンドラインインターフェースライブラリ
@anchor{library/getpass doc}@anchor{344e}@anchor{library/getpass getpass-portable-password-input}@anchor{344f}@anchor{library/getpass module-getpass}@anchor{66}@anchor{library/getpass translation-repo}@anchor{3450}
@subsection @code{getpass} --- 可搬性のあるパスワード入力機構


@geindex module; getpass

@c Windows (& Mac?) support by Guido van Rossum.

`ソースコード:' Lib/getpass.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/getpass.py}


__________________________________________________________________


@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

The @code{getpass} module provides two functions:

@geindex getpass() (getpass モジュール)
@anchor{library/getpass getpass getpass}@anchor{21d}
@deffn {の関数} getpass.getpass (prompt='Password: ', stream=None, *, echo_char=None)

エコーなしでユーザーにパスワードを入力させるプロンプト。ユーザーは `prompt' の文字列をプロンプトに使え、デフォルトは @code{'Password: '} です。 Unixではプロンプトはファイルに似たオブジェクト `stream' へ、必要なら置き換えられたエラーハンドラを使って出力されます。 `stream' のデフォルトは、制御端末(@code{/dev/tty})か、それが利用できない場合は @code{sys.stderr} です (この引数は Windowsでは無視されます)。

The `echo_char' argument controls how user input is displayed while typing.
If `echo_char' is @code{None} (default), input remains hidden. Otherwise,
`echo_char' must be a single printable ASCII character and each
typed character is replaced by it. For example, @code{echo_char='*'} will
display asterisks instead of the actual input.

もしエコーなしで入力が利用できない場合は、 @code{getpass()} は `stream' に警告メッセージを出力し、 @code{sys.stdin} から読み込み、 @ref{3451,,GetPassWarning} 警告を発生させます。

@cartouche
@quotation 注釈 
IDLE から getpass を呼び出した場合、入力はIDLEのウィンドウではなく、IDLE を起動したターミナルから行われます。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
On Unix systems, when `echo_char' is set, the terminal will be
configured to operate in
@code{noncanonical mode@footnote{https://manpages.debian.org/termios(3)#Canonical_and_noncanonical_mode}}.
In particular, this means that line editing shortcuts such as
@code{Ctrl}+@code{U} will not work and may insert unexpected characters into
the input.
@end quotation
@end cartouche


バージョン 3.14 で変更: Added the `echo_char' parameter for keyboard feedback.

@end deffn

@geindex GetPassWarning
@anchor{library/getpass getpass GetPassWarning}@anchor{3451}
@deffn {例外} getpass.GetPassWarning

@ref{2713,,UserWarning} のサブクラスで、入力がエコーされてしまった場合に発生します。
@end deffn

@geindex getuser() (getpass モジュール)
@anchor{library/getpass getpass getuser}@anchor{65a}
@deffn {の関数} getpass.getuser ()

ユーザーの "ログイン名"を返します。

この関数は環境変数 
@geindex LOGNAME
@geindex 環境変数; LOGNAME
@code{LOGNAME} 
@geindex USER
@geindex 環境変数; USER
@code{USER} @code{LNAME} 
@geindex USERNAME
@geindex 環境変数; USERNAME
@code{USERNAME} の順序でチェックして、最初の空ではない文字列が設定された値を返します。もし、なにも設定されていない場合は @ref{b7,,pwd} モジュールが提供するシステム上のパスワードデータベースから返します。それ以外の場合は、 @ref{2c0,,OSError} が送出されます。

In general, this function should be preferred over @ref{1822,,os.getlogin()}.


バージョン 3.13 で変更: 以前は @ref{2c0,,OSError} だけでなく、様々な例外が送出されていました。

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node fileinput --- 複数の入力ストリームをまたいだ行を反復する,curses --- 文字セル表示のターミナル処理,getpass --- 可搬性のあるパスワード入力機構,コマンドラインインターフェースライブラリ
@anchor{library/fileinput doc}@anchor{3452}@anchor{library/fileinput fileinput-iterate-over-lines-from-multiple-input-streams}@anchor{3453}@anchor{library/fileinput module-fileinput}@anchor{5f}@anchor{library/fileinput translation-repo}@anchor{3454}
@subsection @code{fileinput} --- 複数の入力ストリームをまたいだ行を反復する


@geindex module; fileinput

`ソースコード:' Lib/fileinput.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/fileinput.py}


__________________________________________________________________


このモジュールは標準入力やファイルの並びにまたがるループを素早く書くためのヘルパークラスと関数を提供しています。単一のファイルを読み書きしたいだけなら、 @ref{316,,open()} を参照してください。

典型的な使い方は以下の通りです:

@example
import fileinput
for line in fileinput.input(encoding="utf-8"):
    process(line)
@end example

このスクリプトは @code{sys.argv[1:]} に列挙されている全てのファイルの行に渡って反復処理を行います。もし列挙されているものがなければ、 @code{sys.stdin} がデフォルトとして扱われます。
ファイル名として @code{'-'} が与えられた場合も、 @code{sys.stdin} に置き換えられ、 `mode' と `openhook' は無視されます。
別のファイル名リストを使いたい時には、そのリストを @ref{a00,,input()} の最初の引数に与えます。
ファイル名が 1 つでも受け付けます。

全てのファイルはデフォルトでテキストモードでオープンされます。しかし、 @ref{a00,,input()} や @ref{940,,FileInput} をコールする際に `mode' パラメータを指定すれば、これをオーバーライドすることができます。オープン中あるいは読み込み中にI/Oエラーが発生した場合には、 @ref{2c0,,OSError} が発生します。


バージョン 3.3 で変更: 以前は @ref{125e,,IOError} が送出されました; それは現在 @ref{2c0,,OSError} のエイリアスです。


@code{sys.stdin} が2回以上使われた場合は、2回目以降は行を返しません。ただしインタラクティブに利用している時や明示的にリセット (@code{sys.stdin.seek(0)} を使う) を行った場合はその限りではありません。

空のファイルは開いた後すぐ閉じられます。空のファイルはファイル名リストの最後にある場合にしか外部に影響を与えません。

ファイルの各行は、各種改行文字まで含めて返されます。ファイルの最後が改行文字で終っていない場合には、改行文字で終わらない行が返されます。

You can control how files are opened by providing an opening hook via the
`openhook' parameter to @ref{a00,,fileinput.input()} or @ref{940,,FileInput()}. The
hook must be a function that takes two arguments, `filename' and `mode', and
returns an accordingly opened file-like object. If `encoding' and/or `errors'
are specified, they will be passed to the hook as additional keyword arguments.
This module provides a @ref{a01,,hook_compressed()} to support compressed files.

以下の関数がこのモジュールの基本的なインターフェースです:

@geindex input() (fileinput モジュール)
@anchor{library/fileinput fileinput input}@anchor{a00}
@deffn {の関数} fileinput.input (files=None, inplace=False, backup='@w{'}, *, mode='r', openhook=None, encoding=None, errors=None)

@ref{940,,FileInput} クラスのインスタンスを作ります。生成されたインスタンスは、このモジュールの関数群が利用するグローバルな状態として利用されます。この関数への引数は @ref{940,,FileInput} クラスのコンストラクタへ渡されます。

@ref{940,,FileInput} のインスタンスは @ref{186,,with} 文の中でコンテキストマネージャーとして使用できます。
次の例では、仮に例外が生じたとしても @code{with} 文から抜けた後で `input' は閉じられます:

@example
with fileinput.input(files=('spam.txt', 'eggs.txt'), encoding="utf-8") as f:
    for line in f:
        process(line)
@end example


バージョン 3.2 で変更: コンテキストマネージャとして使うことができるようになりました。



バージョン 3.8 で変更: キーワード引数 `mode' と `openhook' は、キーワード専用引数になりました。



バージョン 3.10 で変更: The keyword-only parameter `encoding' and `errors' are added.

@end deffn

以下の関数は @ref{a00,,fileinput.input()} 関数によって作られたグローバルな状態を利用します。アクティブな状態が無い場合には、 @ref{244,,RuntimeError} が発生します。

@geindex filename() (fileinput モジュール)
@anchor{library/fileinput fileinput filename}@anchor{3455}
@deffn {の関数} fileinput.filename ()

現在読み込み中のファイル名を返します。一行目が読み込まれる前は @code{None} を返します。
@end deffn

@geindex fileno() (fileinput モジュール)
@anchor{library/fileinput fileinput fileno}@anchor{1647}
@deffn {の関数} fileinput.fileno ()

現在のファイルの "ファイル記述子" を整数値で返します。ファイルがオープンされていない場合 (最初の行の前、ファイルとファイルの間) は @code{-1} を返します。
@end deffn

@geindex lineno() (fileinput モジュール)
@anchor{library/fileinput fileinput lineno}@anchor{3456}
@deffn {の関数} fileinput.lineno ()

最後に読み込まれた行の、累積した行番号を返します。1行目が読み込まれる前は @code{0} を返します。最後のファイルの最終行が読み込まれた後には、その行の行番号を返します。
@end deffn

@geindex filelineno() (fileinput モジュール)
@anchor{library/fileinput fileinput filelineno}@anchor{3457}
@deffn {の関数} fileinput.filelineno ()

現在のファイル中での行番号を返します。1行目が読み込まれる前は @code{0} を返します。最後のファイルの最終行が読み込まれた後には、その行のファイル中での行番号を返します。
@end deffn

@geindex isfirstline() (fileinput モジュール)
@anchor{library/fileinput fileinput isfirstline}@anchor{3458}
@deffn {の関数} fileinput.isfirstline ()

最後に読み込まれた行がファイルの1行目なら @code{True} 、そうでなければ @code{False} を返します。
@end deffn

@geindex isstdin() (fileinput モジュール)
@anchor{library/fileinput fileinput isstdin}@anchor{3459}
@deffn {の関数} fileinput.isstdin ()

最後に読み込まれた行が @code{sys.stdin} から読み込まれていれば @code{True} 、そうでなければ  @code{False} を返します。
@end deffn

@geindex nextfile() (fileinput モジュール)
@anchor{library/fileinput fileinput nextfile}@anchor{345a}
@deffn {の関数} fileinput.nextfile ()

現在のファイルを閉じます。次の繰り返しでは(存在すれば)次のファイルの最初の行が読み込まれます。閉じたファイルの読み込まれなかった行は、累積の行数にカウントされません。ファイル名は次のファイルの最初の行が読み込まれるまで変更されません。最初の行の読み込みが行われるまでは、この関数は呼び出されても何もしませんので、最初のファイルをスキップするために利用することはできません。最後のファイルの最終行が読み込まれた後にも、この関数は呼び出されても何もしません。
@end deffn

@geindex close() (fileinput モジュール)
@anchor{library/fileinput fileinput close}@anchor{345b}
@deffn {の関数} fileinput.close ()

シーケンスを閉じます。
@end deffn

このモジュールのシーケンスの振舞いを実装しているクラスのサブクラスを作ることもできます:

@geindex FileInput (fileinput のクラス)
@anchor{library/fileinput fileinput FileInput}@anchor{940}
@deffn {クラス} fileinput.FileInput (files=None, inplace=False, backup='@w{'}, *, mode='r', openhook=None, encoding=None, errors=None)

@ref{940,,FileInput} クラスはモジュールの関数に対応するメソッド @ref{3455,,filename()} 、 @ref{1647,,fileno()} 、 @ref{3456,,lineno()} 、 @ref{3457,,filelineno()} 、 @ref{3458,,isfirstline()} 、 @ref{3459,,isstdin()} 、 @ref{345a,,nextfile()} および @ref{345b,,close()} を実装しています。@ref{12f1,,イテラブル} であることに加えて、次の入力行を返す @ref{20a6,,readline()} メソッドがあります。シーケンスはシーケンシャルに読み込むことしかできません。つまりランダムアクセスと @ref{20a6,,readline()} を混在させることはできません。

`mode' を使用すると、 @ref{316,,open()} に渡すファイルモードを指定することができます。これは @code{'r'} および @code{'rb'} のうちのいずれかとなります。

`openhook' を指定する場合は、ふたつの引数 `filename' と `mode' をとる関数でなければなりません。この関数の返り値は、オープンしたファイルオブジェクトとなります。`inplace' と `openhook' を同時に使うことはできません。

You can specify `encoding' and `errors' that is passed to @ref{316,,open()} or `openhook'.

@ref{940,,FileInput} のインスタンスは @ref{186,,with} 文の中でコンテキストマネージャーとして使用できます。
次の例では、仮に例外が生じたとしても @code{with} 文から抜けた後で `input' は閉じられます:

@example
with FileInput(files=('spam.txt', 'eggs.txt')) as input:
    process(input)
@end example


バージョン 3.2 で変更: コンテキストマネージャとして使うことができるようになりました。



バージョン 3.8 で変更: キーワード引数 `mode' と `openhook' は、キーワード専用引数になりました。



バージョン 3.10 で変更: The keyword-only parameter `encoding' and `errors' are added.



バージョン 3.11 で変更: The @code{'rU'} and @code{'U'} modes and the @code{__getitem__()} method have
been removed.

@end deffn

`インプレース(in-place)フィルタオプション:' キーワード引数 @code{inplace=True} が @ref{a00,,fileinput.input()} か @ref{940,,FileInput} クラスのコンストラクタに渡された場合には、入力ファイルはバックアップファイルに移動され、標準出力が入力ファイルに設定されます(バックアップファイルと同じ名前のファイルが既に存在していた場合には、警告無しに置き替えられます)。これによって入力ファイルをその場で書き替えるフィルタを書くことができます。キーワード引数 `backup' (通常は @code{backup='.<拡張子>'} という形で利用します)が与えられていた場合、バックアップファイルの拡張子として利用され、バックアップファイルは削除されずに残ります。デフォルトでは、拡張子は @code{'.bak'} になっていて、出力先のファイルが閉じられればバックアップファイルも消されます。インプレースフィルタ機能は、標準入力を読み込んでいる間は無効にされます。

このモジュールには、次のふたつのオープン時フックが用意されています:

@geindex hook_compressed() (fileinput モジュール)
@anchor{library/fileinput fileinput hook_compressed}@anchor{a01}
@deffn {の関数} fileinput.hook_compressed (filename, mode, *, encoding=None, errors=None)

gzip や bzip2 で圧縮された (拡張子が @code{'.gz'} や @code{'.bz2'} の) ファイルを、 @ref{6b,,gzip} モジュールや @ref{14,,bz2} モジュールを使って透過的にオープンします。ファイルの拡張子が @code{'.gz'} や @code{'.bz2'} でない場合は、通常通りファイルをオープンします (つまり、 @ref{316,,open()} をコールする際に伸長を行いません)。

The `encoding' and `errors' values are passed to @ref{9be,,io.TextIOWrapper}
for compressed files and open for normal files.

使用例: @code{fi = fileinput.FileInput(openhook=fileinput.hook_compressed, encoding="utf-8")}


バージョン 3.10 で変更: The keyword-only parameter `encoding' and `errors' are added.

@end deffn

@geindex hook_encoded() (fileinput モジュール)
@anchor{library/fileinput fileinput hook_encoded}@anchor{e9e}
@deffn {の関数} fileinput.hook_encoded (encoding, errors=None)

各ファイルを @ref{316,,open()} でオープンするフックを返します。指定した `encoding' および `errors' でファイルを読み込みます。

使用例: @code{fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", "surrogateescape"))}


バージョン 3.6 で変更: オプションの `errors' 引数が追加されました。



バージョン 3.10 で非推奨: This function is deprecated since @ref{a00,,fileinput.input()} and @ref{940,,FileInput}
now have `encoding' and `errors' parameters.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node curses --- 文字セル表示のターミナル処理,curses textpad --- Text input widget for curses programs,fileinput --- 複数の入力ストリームをまたいだ行を反復する,コマンドラインインターフェースライブラリ
@anchor{library/curses doc}@anchor{345c}@anchor{library/curses curses-terminal-handling-for-character-cell-displays}@anchor{345d}@anchor{library/curses module-curses}@anchor{2f}@anchor{library/curses translation-repo}@anchor{345e}
@subsection @code{curses} --- 文字セル表示のターミナル処理


@geindex module; curses

`ソースコード:' Lib/curses@footnote{https://github.com/python/cpython/tree/3.14/Lib/curses}


__________________________________________________________________


The @code{curses} module provides an interface to the curses library, the
de-facto standard for portable advanced terminal handling.

curses が最も広く用いられているのは Unix 環境ですが、Windows、DOS で利用できるバージョンもあり、おそらく他のシステムで利用できるバージョンもあります。この拡張モジュールは Linux および BSD 系の Unixで動作するオープンソースの curses ライブラリである ncurses の API に合致するように設計されています。

@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@ref{213f,,Availability}: Unix.

@cartouche
@quotation 注釈 
Whenever the documentation mentions a `character' it can be specified
as an integer, a one-character Unicode string or a one-byte byte string.

Whenever the documentation mentions a `character string' it can be specified
as a Unicode string or a byte string.
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@item @ref{30,,curses.ascii} モジュール

ロケール設定に関わらず ASCII 文字を扱うためのユーティリティ。

@item @ref{31,,curses.panel} モジュール

curses ウィンドウにデプス機能を追加するパネルスタック拡張。

@item @ref{32,,curses.textpad} モジュール

@code{Emacs} ライクなキーバインディングをサポートする編集可能な curses 用テキストウィジェット。

@item @ref{345f,,Python で Curses プログラミング}

Andrew Kuchling および Eric Raymond によって書かれた、curses を Python で使うためのチュートリアルです。
@end table


@menu
* 関数: 関数<6>. 
* Window オブジェクト:: 
* 定数: 定数<6>. 

@end menu

@node 関数<6>,Window オブジェクト,,curses --- 文字セル表示のターミナル処理
@anchor{library/curses curses-functions}@anchor{3460}@anchor{library/curses functions}@anchor{3461}
@subsubsection 関数


The module @code{curses} defines the following exception:

@geindex error
@anchor{library/curses curses error}@anchor{3462}
@deffn {例外} curses.error

curses ライブラリ関数がエラーを返した際に送出される例外です。
@end deffn

@cartouche
@quotation 注釈 
関数やメソッドにおけるオプションの引数 `x' および `y' がある場合、デフォルト値は常に現在のカーソルになります。オプションの `attr' がある場合、デフォルト値は @ref{3463,,A_NORMAL} です。
@end quotation
@end cartouche

The module @code{curses} defines the following functions:

@geindex assume_default_colors() (curses モジュール)
@anchor{library/curses curses assume_default_colors}@anchor{1f6}
@deffn {の関数} curses.assume_default_colors (fg, bg, /)

Allow use of default values for colors on terminals supporting this feature.
Use this to support transparency in your application.


@itemize *

@item 
Assign terminal default foreground/background colors to color number @code{-1}.
So @code{init_pair(x, COLOR_RED, -1)} will initialize pair `x' as red
on default background and @code{init_pair(x, -1, COLOR_BLUE)} will
initialize pair `x' as default foreground on blue.

@item 
Change the definition of the color-pair @code{0} to @code{(fg, bg)}.
@end itemize


Added in version 3.14.

@end deffn

@geindex baudrate() (curses モジュール)
@anchor{library/curses curses baudrate}@anchor{3464}
@deffn {の関数} curses.baudrate ()

端末の出力速度をビット/秒で返します。ソフトウェア端末エミュレータの場合、これは固定の高い値を持つことになります。この関数は歴史的な理由で入れられています; かつては、この関数は時間遅延を生成するための出力ループを書くために用いられたり、行速度に応じてインターフェースを切り替えたりするために用いられたりしていました。
@end deffn

@geindex beep() (curses モジュール)
@anchor{library/curses curses beep}@anchor{3465}
@deffn {の関数} curses.beep ()

注意を促す短い音を鳴らします。
@end deffn

@geindex can_change_color() (curses モジュール)
@anchor{library/curses curses can_change_color}@anchor{3466}
@deffn {の関数} curses.can_change_color ()

端末に表示される色をプログラマが変更できるか否かによって、@code{True} または @code{False} を返します。
@end deffn

@geindex cbreak() (curses モジュール)
@anchor{library/curses curses cbreak}@anchor{3467}
@deffn {の関数} curses.cbreak ()

cbreak モードに入ります。cbreak モード ("rare" モードと呼ばれることもあります) では、通常の tty 行バッファリングはオフにされ、文字を一文字一文字読むことができます。ただし、raw モードとは異なり、特殊文字 (割り込み:interrupt、終了:quit、一時停止:suspend、およびフロー制御) については、tty ドライバおよび呼び出し側のプログラムに対する通常の効果をもっています。まず @ref{3468,,raw()} を呼び出し、次いで @ref{3467,,cbreak()} を呼び出すと、端末を cbreak モードにします。
@end deffn

@geindex color_content() (curses モジュール)
@anchor{library/curses curses color_content}@anchor{9f2}
@deffn {の関数} curses.color_content (color_number)

色 `color_number' の赤、緑、および青 (RGB) 要素の強度を返します。`color_number' は @code{0} から @code{COLORS - 1} の間でなければなりません。与えられた色の R、G、B、の値からなる三要素のタプルが返されます。この値は @code{0} (その成分はない) から @code{1000} (その成分の最大強度) の範囲をとります。
@end deffn

@geindex color_pair() (curses モジュール)
@anchor{library/curses curses color_pair}@anchor{3469}
@deffn {の関数} curses.color_pair (pair_number)

Return the attribute value for displaying text in the specified color pair.
Only the first 256 color pairs are supported. This
attribute value can be combined with @ref{346a,,A_STANDOUT}, @ref{346b,,A_REVERSE},
and the other @code{A_*} attributes.  @ref{346c,,pair_number()} is the counterpart
to this function.
@end deffn

@geindex curs_set() (curses モジュール)
@anchor{library/curses curses curs_set}@anchor{346d}
@deffn {の関数} curses.curs_set (visibility)

カーソルの状態を設定します。`visibility' は @code{0} 、 @code{1`@w{`}または `@w{`}2} に設定され、それぞれ不可視、通常、または非常に可視、を意味します。要求された可視属性を端末がサポートしている場合、以前のカーソル状態が返されます; そうでなければ例外が送出されます。多くの端末では、"可視 (通常)" モードは下線カーソルで、"非常に可視" モードはブロックカーソルです。
@end deffn

@geindex def_prog_mode() (curses モジュール)
@anchor{library/curses curses def_prog_mode}@anchor{346e}
@deffn {の関数} curses.def_prog_mode ()

現在の端末属性を、稼動中のプログラムが curses を使う際のモードである "プログラム" モードとして保存します。(このモードの反対は、プログラムが curses を使わない "シェル" モードです。) その後 @ref{346f,,reset_prog_mode()} を呼ぶとこのモードを復旧します。
@end deffn

@geindex def_shell_mode() (curses モジュール)
@anchor{library/curses curses def_shell_mode}@anchor{3470}
@deffn {の関数} curses.def_shell_mode ()

現在の端末属性を、稼動中のプログラムが curses を使っていないときのモードである "シェル" モードとして保存します。(このモードの反対は、プログラムが curses 機能を利用している "プログラム" モードです。) その後 @ref{3471,,reset_shell_mode()} を呼ぶとこのモードを復旧します。
@end deffn

@geindex delay_output() (curses モジュール)
@anchor{library/curses curses delay_output}@anchor{3472}
@deffn {の関数} curses.delay_output (ms)

出力に `ms' ミリ秒の一時停止を入れます。
@end deffn

@geindex doupdate() (curses モジュール)
@anchor{library/curses curses doupdate}@anchor{3473}
@deffn {の関数} curses.doupdate ()

物理スクリーンを更新します。curses ライブラリは、現在の物理スクリーンの内容と、次の状態として要求されている仮想スクリーンをそれぞれ表す、2 つのデータ構造を保持しています。@ref{3473,,doupdate()} は更新を適用し、物理スクリーンを仮想スクリーンに一致させます。

仮想スクリーンは @ref{3474,,addstr()} のような書き込み操作をウィンドウに行った後に @ref{3475,,noutrefresh()} を呼び出して更新することができます。通常の:meth:@cite{~window.refresh} 呼び出しは、単に @code{noutrefresh()}  を呼んだ後に @code{doupdate`を呼ぶだけです; 複数のウィンドウを更新しなければならない場合、すべてのウィンドウに対して :meth:()}!noutrefresh` を呼び出した後、一度だけ @code{doupdate()} を呼ぶことで、パフォーマンスを向上させることができ、おそらくスクリーンのちらつきも押さえることができます。
@end deffn

@geindex echo() (curses モジュール)
@anchor{library/curses curses echo}@anchor{3476}
@deffn {の関数} curses.echo ()

echo モードに入ります。echo モードでは、各文字入力はスクリーン上に入力された通りにエコーバックされます。
@end deffn

@geindex endwin() (curses モジュール)
@anchor{library/curses curses endwin}@anchor{3477}
@deffn {の関数} curses.endwin ()

ライブラリの非初期化を行い、端末を通常の状態に戻します。
@end deffn

@geindex erasechar() (curses モジュール)
@anchor{library/curses curses erasechar}@anchor{3478}
@deffn {の関数} curses.erasechar ()

ユーザの現在の消去文字 (erase character) を1バイトの bytes オブジェクトで返します。Unix オペレーティングシステムでは、この値は curses プログラムが制御している端末の属性であり、curses ライブラリ自体では設定されません。
@end deffn

@geindex filter() (curses モジュール)
@anchor{library/curses curses filter}@anchor{3479}
@deffn {の関数} curses.filter ()

@ref{3479,,filter()} ルーチンを使う場合、@ref{190f,,initscr()} を呼ぶ前に呼び出さなくてはなりません。この手順のもたらす効果は以下の通りです: まず二つの関数の呼び出しの間は、
@geindex LINES
@geindex 環境変数; LINES
@code{LINES} は @code{1} に設定されます; @code{clear}, @code{cup}, @code{cud}, @code{cud1}, @code{cuu1}, @code{cuu}, @code{vpa} は無効化されます; @code{home} 文字列は @code{cr} の値に設定されます。これにより、カーソルは現在の行に制限されるので、スクリーンの更新も同様に制限されます。この関数は、スクリーンの他の部分に影響を及ぼさずに文字単位の行編集を行う場合に利用できます。
@end deffn

@geindex flash() (curses モジュール)
@anchor{library/curses curses flash}@anchor{347a}
@deffn {の関数} curses.flash ()

スクリーンを点滅します。すなわち、画面を色反転して、短時間でもとにもどします。人によっては、@ref{3465,,beep()} で生成される注意音よりも、このような "目に見えるベル" を好みます。
@end deffn

@geindex flushinp() (curses モジュール)
@anchor{library/curses curses flushinp}@anchor{347b}
@deffn {の関数} curses.flushinp ()

すべての入力バッファをフラッシュします。この関数は、ユーザによってすでに入力されているが、まだプログラムによって処理されていないすべての先行入力文字を破棄します。
@end deffn

@geindex getmouse() (curses モジュール)
@anchor{library/curses curses getmouse}@anchor{347c}
@deffn {の関数} curses.getmouse ()

@ref{1825,,getch()} が @ref{347d,,KEY_MOUSE} を返してマウスイベントを通知した後、この関数を呼んで待ち行列上に置かれているマウスイベントを取得しなければなりません。イベントは @code{(id, x, y, z, bstate)} の 5 要素のタプルで表現されています。`id' は複数のデバイスを区別するための ID 値で、`x', `y', `z' はイベントの座標値です。(現在 `z' は使われていません) `bstate' は整数値で、その各ビットはイベントのタイプを示す値に設定されています。この値は以下に示す定数のうち一つまたはそれ以上のビット単位 OR  になっています。以下の定数の `n' は 1 から 5 のボタン番号を示します: @ref{347e,,BUTTONn_PRESSED}, @ref{347f,,BUTTONn_RELEASED}, @ref{3480,,BUTTONn_CLICKED}, @ref{3481,,BUTTONn_DOUBLE_CLICKED}, @ref{3482,,BUTTONn_TRIPLE_CLICKED}, @ref{3483,,BUTTON_SHIFT}, @ref{3484,,BUTTON_CTRL}, @ref{3485,,BUTTON_ALT}。


バージョン 3.10 で変更: The @code{BUTTON5_*} constants are now exposed if they are provided by the
underlying curses library.

@end deffn

@geindex getsyx() (curses モジュール)
@anchor{library/curses curses getsyx}@anchor{3486}
@deffn {の関数} curses.getsyx ()

仮想スクリーンにおける現在のカーソル位置をタプル @code{(y, x)} で返します。 @code{leaveok()} が @code{True} に設定されていれば、 @code{(-1, -1)} が返されます。
@end deffn

@geindex getwin() (curses モジュール)
@anchor{library/curses curses getwin}@anchor{3487}
@deffn {の関数} curses.getwin (file)

Read window related data stored in the file by an earlier @ref{3488,,window.putwin()} call.
The routine then creates and initializes a new window using that data, returning
the new window object.
@end deffn

@geindex has_colors() (curses モジュール)
@anchor{library/curses curses has_colors}@anchor{3489}
@deffn {の関数} curses.has_colors ()

端末が色表示を行える場合には @code{True} を返します。そうでない場合には @code{False} を返します。
@end deffn

@geindex has_extended_color_support() (curses モジュール)
@anchor{library/curses curses has_extended_color_support}@anchor{9f6}
@deffn {の関数} curses.has_extended_color_support ()

Return @code{True} if the module supports extended colors; otherwise, return
@code{False}. Extended color support allows more than 256 color pairs for
terminals that support more than 16 colors (e.g. xterm-256color).

Extended color support requires ncurses version 6.1 or later.


Added in version 3.10.

@end deffn

@geindex has_ic() (curses モジュール)
@anchor{library/curses curses has_ic}@anchor{348a}
@deffn {の関数} curses.has_ic ()

端末が文字の挿入/削除機能を持つ場合に @code{True} を返します。最近の端末エミュレータはどれもこの機能を持っており、この関数は歴史的な理由のためだけに存在しています。
@end deffn

@geindex has_il() (curses モジュール)
@anchor{library/curses curses has_il}@anchor{348b}
@deffn {の関数} curses.has_il ()

端末が行の挿入/削除機能を持つ場合に @code{True} を返します。最近の端末エミュレータはどれもこの機能を持っていて、この関数は歴史的な理由のためだけに存在しています。
@end deffn

@geindex has_key() (curses モジュール)
@anchor{library/curses curses has_key}@anchor{348c}
@deffn {の関数} curses.has_key (ch)

キー値 `ch' をとり、現在の端末タイプがその値のキーを認識できる場合に @code{True} を返します。
@end deffn

@geindex halfdelay() (curses モジュール)
@anchor{library/curses curses halfdelay}@anchor{348d}
@deffn {の関数} curses.halfdelay (tenths)

半遅延モード、すなわち cbreak モードに似た、ユーザが打鍵した文字がすぐにプログラムで利用できるようになるモードで使われます。しかしながら、何も入力されなかった場合、十分の `tenths' 秒後に例外が送出されます。`tenths' の値は @code{1} から @code{255} の間でなければなりません。半遅延モードから抜けるには @ref{348e,,nocbreak()}  を使います。
@end deffn

@geindex init_color() (curses モジュール)
@anchor{library/curses curses init_color}@anchor{9f3}
@deffn {の関数} curses.init_color (color_number, r, g, b)

色の定義を変更します。変更したい色番号と、その後に 3 つ組みの RGB 値 (赤、緑、青の成分の大きさ) をとります。`color_number' の値は @code{0} から @code{COLORS - 1} の間でなければなりません。`r', `g', `b' の値は @code{0} から @code{1000} の間でなければなりません。@ref{9f3,,init_color()} を使うと、スクリーン上でカラーが使用されている部分はすべて新しい設定に即時変更されます。この関数はほとんどの端末で何も行いません; @ref{3466,,can_change_color()} が @code{True} を返す場合にのみ動作します。
@end deffn

@geindex init_pair() (curses モジュール)
@anchor{library/curses curses init_pair}@anchor{9f4}
@deffn {の関数} curses.init_pair (pair_number, fg, bg)

Change the definition of a color-pair.  It takes three arguments: the number of
the color-pair to be changed, the foreground color number, and the background
color number.  The value of `pair_number' must be between @code{1} and
@code{COLOR_PAIRS - 1} (the @code{0} color pair can only be changed by
@ref{1f7,,use_default_colors()} and @ref{1f6,,assume_default_colors()}).
The value of `fg' and `bg' arguments must be between @code{0} and
@code{COLORS - 1}, or, after calling @code{use_default_colors()} or
@code{assume_default_colors()}, @code{-1}.
If the color-pair was previously initialized, the screen is
refreshed and all occurrences of that color-pair are changed to the new
definition.
@end deffn

@geindex initscr() (curses モジュール)
@anchor{library/curses curses initscr}@anchor{190f}
@deffn {の関数} curses.initscr ()

ライブラリを初期化します。スクリーン全体をあらわす  @ref{1989,,ウィンドウ} オブジェクトを返します。

@cartouche
@quotation 注釈 
端末のオープン時にエラーが発生した場合、curses ライブラリによってインタープリタが終了される場合があります。
@end quotation
@end cartouche
@end deffn

@geindex is_term_resized() (curses モジュール)
@anchor{library/curses curses is_term_resized}@anchor{348f}
@deffn {の関数} curses.is_term_resized (nlines, ncols)

@ref{1930,,resize_term()} によってウィンドウ構造が変更されている場合に @code{True} を、そうでない場合は @code{False} を返します。
@end deffn

@geindex isendwin() (curses モジュール)
@anchor{library/curses curses isendwin}@anchor{3490}
@deffn {の関数} curses.isendwin ()

@ref{3477,,endwin()} がすでに呼び出されている (すなわち、curses ライブラリが非初期化されてしまっている) 場合に @code{True} を返します。
@end deffn

@geindex keyname() (curses モジュール)
@anchor{library/curses curses keyname}@anchor{3491}
@deffn {の関数} curses.keyname (k)

bytes オブジェクト `k' に番号付けされているキーの名前を返します。
印字可能な ASCII 文字を生成するキーの名前はそのキーの文字自体になります。
コントロールキーと組み合わせたキーの名前は、キャレット(@code{b'^'})の後に対応する ASCII 文字が続く 2 バイトの bytes オブジェクトになります。
Alt キーと組み合わせたキー (128--255) の名前は、先頭に @code{b'M-'} が付き、その後に対応する ASCII 文字が続く bytes オブジェクトになります。
@end deffn

@geindex killchar() (curses モジュール)
@anchor{library/curses curses killchar}@anchor{3492}
@deffn {の関数} curses.killchar ()

Return the user's current line kill character as a one-byte bytes object. Under Unix operating systems
this is a property of the controlling tty of the curses program, and is not set
by the curses library itself.
@end deffn

@geindex longname() (curses モジュール)
@anchor{library/curses curses longname}@anchor{3493}
@deffn {の関数} curses.longname ()

現在の端末について記述している terminfo の長形式 name フィールドが入った bytes オブジェクトを返します。verbose 形式記述の最大長は 128 文字です。この値は @ref{190f,,initscr()} 呼び出しの後でのみ定義されています。
@end deffn

@geindex meta() (curses モジュール)
@anchor{library/curses curses meta}@anchor{3494}
@deffn {の関数} curses.meta (flag)

`flag' が @code{True} の場合、8 ビット文字の入力を許可します。`flag' が @code{False} の場合、7 ビット文字だけを許可します。
@end deffn

@geindex mouseinterval() (curses モジュール)
@anchor{library/curses curses mouseinterval}@anchor{3495}
@deffn {の関数} curses.mouseinterval (interval)

ボタンが押されてから離されるまでの時間をマウスクリック一回として認識する最大の時間間隔をミリ秒で設定します。返り値は以前の内部設定値になります。デフォルトは 200 ミリ秒 (5 分の 1 秒) です。
@end deffn

@geindex mousemask() (curses モジュール)
@anchor{library/curses curses mousemask}@anchor{3496}
@deffn {の関数} curses.mousemask (mousemask)

報告すべきマウスイベントを設定し、@code{(availmask, oldmask)} の組からなるタプルを返します。`availmask' はどの指定されたマウスイベントのどれが報告されるかを示します; どのイベント指定も完全に失敗した場合には @code{0} が返ります。`oldmask' は与えられたウィンドウの以前のマウスイベントマスクです。この関数が呼ばれない限り、マウスイベントは何も報告されません。
@end deffn

@geindex napms() (curses モジュール)
@anchor{library/curses curses napms}@anchor{190e}
@deffn {の関数} curses.napms (ms)

`ms' ミリ秒間スリープします。
@end deffn

@geindex newpad() (curses モジュール)
@anchor{library/curses curses newpad}@anchor{3497}
@deffn {の関数} curses.newpad (nlines, ncols)

与えられた行とカラム数を持つパッド (pad) データ構造を生成し、そのポインタを返します。パッドはウィンドウオブジェクトとして返されます。

パッドはウィンドウと同じようなものですが、スクリーンのサイズによる制限をうけず、スクリーンの特定の部分に関連付けられていなくてもかまいません。大きなウィンドウが必要であり、スクリーンにはそのウィンドウの一部しか一度に表示しない場合に使えます。(スクロールや入力エコーなどによる) パッドに対する再描画は起こりません。パッドに対する @ref{3498,,refresh()} および @ref{3475,,noutrefresh()} メソッドは、パッド中の表示する部分と表示するために利用するスクリーン上の位置を指定する 6 つの引数が必要です。これらの引数は `pminrow'、`pmincol'、`sminrow'、`smincol'、`smaxrow'、`smaxcol' です; `p' で始まる引数はパッド中の表示領域の左上位置で、`s' で始まる引数はパッド領域を表示するスクリーン上のクリップ矩形を指定します。
@end deffn

@geindex newwin() (curses モジュール)
@anchor{library/curses curses newwin}@anchor{3499}
@deffn {の関数} curses.newwin (nlines, ncols)

@deffnx {の関数} curses.newwin (nlines, ncols, begin_y, begin_x)

左上の角が @code{(begin_y, begin_x)} で、高さ/幅が `nlines' / `ncols' の新規 @ref{1989,,ウィンドウ} を返します。

デフォルトでは、ウィンドウは指定された位置からスクリーンの右下まで広がります。
@end deffn

@geindex nl() (curses モジュール)
@anchor{library/curses curses nl}@anchor{349a}
@deffn {の関数} curses.nl ()

newlime モードに入ります。このモードはリターンキーを入力中の改行として変換し、出力時に改行文字を復帰 (return) と改行 (line-feed) に変換します。newline モードは初期化時にはオンになっています。
@end deffn

@geindex nocbreak() (curses モジュール)
@anchor{library/curses curses nocbreak}@anchor{348e}
@deffn {の関数} curses.nocbreak ()

cbreak モードを終了します。行バッファリングを行う通常の "cooked"  モードに戻ります。
@end deffn

@geindex noecho() (curses モジュール)
@anchor{library/curses curses noecho}@anchor{349b}
@deffn {の関数} curses.noecho ()

echo モードを終了します。入力のエコーバックはオフにされます。
@end deffn

@geindex nonl() (curses モジュール)
@anchor{library/curses curses nonl}@anchor{349c}
@deffn {の関数} curses.nonl ()

newline モードを終了します。入力時のリターンキーから改行への変換、および出力時の改行から復帰/改行への低レベル変換を無効化します (ただし、@code{addch('\n')} の振る舞いは変更せず、仮想スクリーン上では常に復帰と改行に等しくなります)。変換をオフにすることで、curses は水平方向の動きを少しだけ高速化できることがあります; また、入力中のリターンキーの検出ができるようになります。
@end deffn

@geindex noqiflush() (curses モジュール)
@anchor{library/curses curses noqiflush}@anchor{349d}
@deffn {の関数} curses.noqiflush ()

@code{noqiflush()} ルーチンを使うと、通常行われている @code{INTR} 、 @code{QUIT} および @code{SUSP} 文字による入力および出力キューのフラッシュが行われなくなります。シグナルハンドラが終了した際、割り込みが発生しなかったかのように出力を続たい場合、ハンドラ中で @code{noqiflush()} を呼び出すことができます。
@end deffn

@geindex noraw() (curses モジュール)
@anchor{library/curses curses noraw}@anchor{349e}
@deffn {の関数} curses.noraw ()

raw モードから離れます。行バッファリングを行う通常の "cooked" モードに戻ります。
@end deffn

@geindex pair_content() (curses モジュール)
@anchor{library/curses curses pair_content}@anchor{9f5}
@deffn {の関数} curses.pair_content (pair_number)

要求された色ペアの色を含むタプル @code{(fg, bg)} を返します。`pair_number' は @code{0} から @code{COLOR_PAIRS - 1} の間でなければなりません。
@end deffn

@geindex pair_number() (curses モジュール)
@anchor{library/curses curses pair_number}@anchor{346c}
@deffn {の関数} curses.pair_number (attr)

`attr' に対する色ペアセットの番号を返します。@ref{3469,,color_pair()} はこの関数の逆に相当します。
@end deffn

@geindex putp() (curses モジュール)
@anchor{library/curses curses putp}@anchor{349f}
@deffn {の関数} curses.putp (str)

@code{tputs(str, 1, putchar)} と等価です; 現在の端末における、指定された terminfo 機能の値を出力します。@ref{349f,,putp()} の出力は常に標準出力に送られるので注意して下さい。
@end deffn

@geindex qiflush() (curses モジュール)
@anchor{library/curses curses qiflush}@anchor{34a0}
@deffn {の関数} curses.qiflush ([flag])

`flag' が @code{False} なら、@ref{349d,,noqiflush()} を呼ぶのとと同じ効果です。`flag' が @code{True} か、引数が与えられていない場合、制御文字が読み出された最にキューはフラッシュされます。
@end deffn

@geindex raw() (curses モジュール)
@anchor{library/curses curses raw}@anchor{3468}
@deffn {の関数} curses.raw ()

raw モードに入ります。raw モードでは、通常の行バッファリングと割り込み (interrupt)、終了 (quit)、一時停止 (suspend)、およびフロー制御キーはオフになります; 文字は curses 入力関数に一文字づつ渡されます。
@end deffn

@geindex reset_prog_mode() (curses モジュール)
@anchor{library/curses curses reset_prog_mode}@anchor{346f}
@deffn {の関数} curses.reset_prog_mode ()

端末を "program" モードに復旧し、あらかじめ @ref{346e,,def_prog_mode()} で保存した内容に戻します。
@end deffn

@geindex reset_shell_mode() (curses モジュール)
@anchor{library/curses curses reset_shell_mode}@anchor{3471}
@deffn {の関数} curses.reset_shell_mode ()

端末を "shell" モードに復旧し、あらかじめ @ref{3470,,def_shell_mode()} で保存した内容に戻します。
@end deffn

@geindex resetty() (curses モジュール)
@anchor{library/curses curses resetty}@anchor{34a1}
@deffn {の関数} curses.resetty ()

端末モードの状態を最後に @ref{34a2,,savetty()} を呼び出した時の状態に戻します。
@end deffn

@geindex resize_term() (curses モジュール)
@anchor{library/curses curses resize_term}@anchor{1930}
@deffn {の関数} curses.resize_term (nlines, ncols)

@ref{192f,,resizeterm()} で使用されるバックエンド関数で、ウィンドウサイズを変更する時、@ref{1930,,resize_term()} は拡張された領域を埋めます。呼び出したアプリケーションはそれらの領域を適切なデータで埋めなくてはなりません。@code{resize_term()} 関数はすべてのウィンドウのサイズ変更を試みます。ただし、パッド呼び出しの慣例により、アプリケーションとの追加のやり取りを行わないサイズ変更は行えません。
@end deffn

@geindex resizeterm() (curses モジュール)
@anchor{library/curses curses resizeterm}@anchor{192f}
@deffn {の関数} curses.resizeterm (nlines, ncols)

現在の標準ウィンドウのサイズを指定された寸法に変更し、curses ライブラリが使用する、その他のウィンドウサイズを記憶しているデータ (特に SIGWINCH ハンドラ) を調整します。
@end deffn

@geindex savetty() (curses モジュール)
@anchor{library/curses curses savetty}@anchor{34a2}
@deffn {の関数} curses.savetty ()

@ref{34a1,,resetty()} で使用される、バッファ内の端末モードの現在の状態を保存します。
@end deffn

@geindex get_escdelay() (curses モジュール)
@anchor{library/curses curses get_escdelay}@anchor{aec}
@deffn {の関数} curses.get_escdelay ()

Retrieves the value set by @ref{aed,,set_escdelay()}.


Added in version 3.9.

@end deffn

@geindex set_escdelay() (curses モジュール)
@anchor{library/curses curses set_escdelay}@anchor{aed}
@deffn {の関数} curses.set_escdelay (ms)

Sets the number of milliseconds to wait after reading an escape character,
to distinguish between an individual escape character entered on the
keyboard from escape sequences sent by cursor and function keys.


Added in version 3.9.

@end deffn

@geindex get_tabsize() (curses モジュール)
@anchor{library/curses curses get_tabsize}@anchor{aee}
@deffn {の関数} curses.get_tabsize ()

Retrieves the value set by @ref{aef,,set_tabsize()}.


Added in version 3.9.

@end deffn

@geindex set_tabsize() (curses モジュール)
@anchor{library/curses curses set_tabsize}@anchor{aef}
@deffn {の関数} curses.set_tabsize (size)

Sets the number of columns used by the curses library when converting a tab
character to spaces as it adds the tab to a window.


Added in version 3.9.

@end deffn

@geindex setsyx() (curses モジュール)
@anchor{library/curses curses setsyx}@anchor{34a3}
@deffn {の関数} curses.setsyx (y, x)

仮想スクリーンのカーソルを `y', `x' に設定します。`y' および `x' がどちらも @code{-1} の場合、 @code{leaveok()} が に`@w{`}True`@w{`}に設定されます。
@end deffn

@geindex setupterm() (curses モジュール)
@anchor{library/curses curses setupterm}@anchor{34a4}
@deffn {の関数} curses.setupterm (term=None, fd=-1)

端末を初期化します。`term' は端末名となる文字列または @code{None} です。省略または @code{None} の場合、環境変数 
@geindex TERM
@geindex 環境変数; TERM
@code{TERM} の値が使用されます。`fd' は送信される初期化シーケンスへのファイル記述子です。指定されないまたは @code{-1} の場合、@code{sys.stdout} のファイル記述子が使用されます。
@end deffn

@geindex start_color() (curses モジュール)
@anchor{library/curses curses start_color}@anchor{34a5}
@deffn {の関数} curses.start_color ()

プログラマがカラーを利用したい場合で、かつ他の何らかのカラー操作ルーチンを呼び出す前に呼び出さなくてはなりません。この関数は @ref{190f,,initscr()} を呼んだ直後に呼ぶようにしておくとよいでしょう。

@ref{34a5,,start_color()} initializes eight basic colors (black, red,  green, yellow,
blue, magenta, cyan, and white), and two global variables in the @code{curses}
module, @ref{34a6,,COLORS} and @ref{34a7,,COLOR_PAIRS}, containing the maximum number
of colors and color-pairs the terminal can support.  It also restores the colors
on the terminal to the values they had when the terminal was just turned on.
@end deffn

@geindex termattrs() (curses モジュール)
@anchor{library/curses curses termattrs}@anchor{34a8}
@deffn {の関数} curses.termattrs ()

端末がサポートするすべてのビデオ属性を論理和した値を返します。この情報は、curses プログラムがスクリーンの見え方を完全に制御する必要がある場合に便利です。
@end deffn

@geindex termname() (curses モジュール)
@anchor{library/curses curses termname}@anchor{34a9}
@deffn {の関数} curses.termname ()

14 文字以下になるように切り詰められた環境変数 
@geindex TERM
@geindex 環境変数; TERM
@code{TERM} の値を bytes オブジェクトで返します。
@end deffn

@geindex tigetflag() (curses モジュール)
@anchor{library/curses curses tigetflag}@anchor{34aa}
@deffn {の関数} curses.tigetflag (capname)

terminfo 機能名 `capname' に対応する真偽値の機能値を整数で返します。`capname' が真偽値で表せる機能値でない場合 @code{-1} を返し、機能がキャンセルされているか、端末記述上に見つからない場合 @code{0} を返します。
@end deffn

@geindex tigetnum() (curses モジュール)
@anchor{library/curses curses tigetnum}@anchor{34ab}
@deffn {の関数} curses.tigetnum (capname)

terminfo 機能名 `capname' に対応する数値の機能値を整数で返します。`capname' が数値で表せる機能値でない場合 @code{-2} を返し、機能がキャンセルされているか、端末記述上に見つからない場合 @code{-1} を返します。
@end deffn

@geindex tigetstr() (curses モジュール)
@anchor{library/curses curses tigetstr}@anchor{34ac}
@deffn {の関数} curses.tigetstr (capname)

Return the value of the string capability corresponding to the terminfo
capability name `capname' as a bytes object.  Return @code{None} if `capname'
is not a terminfo "string capability", or is canceled or absent from the
terminal description.
@end deffn

@geindex tparm() (curses モジュール)
@anchor{library/curses curses tparm}@anchor{34ad}
@deffn {の関数} curses.tparm (str[, ...])

`str' を与えられたパラメタを使って bytes オブジェクトにインスタンス化します。`str' は terminfo データベースから得られたパラメタを持つ文字列でなければなりません。例えば、@code{tparm(tigetstr("cup"), 5, 3)} は @code{b'\033[6;4H'} のようになります。厳密には端末の形式によって異なる結果となります。
@end deffn

@geindex typeahead() (curses モジュール)
@anchor{library/curses curses typeahead}@anchor{34ae}
@deffn {の関数} curses.typeahead (fd)

先読みチェックに使うためのファイル記述子 `fd' を指定します。`fd' が @code{-1} の場合、先読みチェックは行われません。

curses ライブラリはスクリーンを更新する間、先読み文字列を定期的に検索することで "行はみ出し最適化 (line-breakout optimization)" を行います。入力が得られ、かつ入力は端末からのものである場合、現在行おうとしている更新は refresh や doupdate を再度呼び出すまで先送りにします。この関数は異なるファイル記述子で先読みチェックを行うように指定することができます。
@end deffn

@geindex unctrl() (curses モジュール)
@anchor{library/curses curses unctrl}@anchor{34af}
@deffn {の関数} curses.unctrl (ch)

Return a bytes object which is a printable representation of the character `ch'.
Control characters are represented as a caret followed by the character, for
example as @code{b'^C'}. Printing characters are left as they are.
@end deffn

@geindex ungetch() (curses モジュール)
@anchor{library/curses curses ungetch}@anchor{34b0}
@deffn {の関数} curses.ungetch (ch)

`ch' をプッシュし、次に @ref{1825,,getch()} を呼び出した時にその値が返るようにします。

@cartouche
@quotation 注釈 
@code{getch()} を呼び出すまでは `ch' は一つしかプッシュできません。
@end quotation
@end cartouche
@end deffn

@geindex update_lines_cols() (curses モジュール)
@anchor{library/curses curses update_lines_cols}@anchor{feb}
@deffn {の関数} curses.update_lines_cols ()

Update the @ref{fec,,LINES} and @ref{fed,,COLS} module variables.
Useful for detecting manual screen resize.


Added in version 3.5.

@end deffn

@geindex unget_wch() (curses モジュール)
@anchor{library/curses curses unget_wch}@anchor{12aa}
@deffn {の関数} curses.unget_wch (ch)

`ch' をプッシュし、次に @ref{12a9,,get_wch()} を呼び出した時にその値が返るようにします。

@cartouche
@quotation 注釈 
@code{get_wch()} を呼び出すまでは `ch' は一つしかプッシュできません。
@end quotation
@end cartouche


Added in version 3.3.

@end deffn

@geindex ungetmouse() (curses モジュール)
@anchor{library/curses curses ungetmouse}@anchor{34b1}
@deffn {の関数} curses.ungetmouse (id, x, y, z, bstate)

与えられた状態データが関連付けられた @ref{347d,,KEY_MOUSE} イベントを入力キューにプッシュします。
@end deffn

@geindex use_env() (curses モジュール)
@anchor{library/curses curses use_env}@anchor{34b2}
@deffn {の関数} curses.use_env (flag)

この関数を使う場合、@ref{190f,,initscr()} または newterm を呼ぶ前に呼び出さなくてはなりません。`flag' が @code{False} の場合、環境変数 
@geindex LINES
@geindex 環境変数; LINES
@code{LINES} および 
@geindex COLUMNS
@geindex 環境変数; COLUMNS
@code{COLUMNS} の値 (デフォルトで使用されます) の値が設定されていたり、curses がウィンドウ内で動作して (この場合 
@geindex LINES
@geindex 環境変数; LINES
@code{LINES} や 
@geindex COLUMNS
@geindex 環境変数; COLUMNS
@code{COLUMNS} が設定されていないとウィンドウのサイズを使います) いても、terminfo  データベースに指定された lines および columns の値を使います。
@end deffn

@geindex use_default_colors() (curses モジュール)
@anchor{library/curses curses use_default_colors}@anchor{1f7}
@deffn {の関数} curses.use_default_colors ()

Equivalent to @code{assume_default_colors(-1, -1)}.
@end deffn

@geindex wrapper() (curses モジュール)
@anchor{library/curses curses wrapper}@anchor{c73}
@deffn {の関数} curses.wrapper (func, /, *args, **kwargs)

curses を初期化し、呼び出し可能なオブジェクト `func' (その他の curses を使用するアプリケーション) を呼び出します。アプリケーションが例外を送出した場合、この関数は端末を例外を再送出する前に正常な状態に戻し、トレースバックを作成します。その後、呼び出し可能オブジェクト `func' には、第一引数としてメインウィンドウ 'stdscr' が、続いて @code{wrapper()} に渡されたその他の引数が渡されます。`func' を呼び出す前、@code{wrapper()} は cbreak モードをオンに、エコーをオフに、端末キーパッドを有効にし、端末が色表示をサポートしている場合は色を初期化します。終了時 (通常終了、例外による終了のどちらでも)、cooked モードに戻し、エコーをオンにし、端末キーパッドを無効にします。
@end deffn

@node Window オブジェクト,定数<6>,関数<6>,curses --- 文字セル表示のターミナル処理
@anchor{library/curses curses-window-objects}@anchor{1989}@anchor{library/curses window-objects}@anchor{34b3}
@subsubsection Window オブジェクト


@geindex window (curses のクラス)
@anchor{library/curses curses window}@anchor{12a7}
@deffn {クラス} curses.window

上記の @ref{190f,,initscr()} や @ref{3499,,newwin()} が返すウィンドウは、以下のメソッドと属性を持ちます:
@end deffn

@geindex addch() (curses.window のメソッド)
@anchor{library/curses curses window addch}@anchor{34b4}
@deffn {メソッド} window.addch (ch[, attr])

@deffnx {メソッド} window.addch (y, x, ch[, attr])

@code{(y, x)} にある文字 `ch' を属性 `attr' で描画します。このときその場所に以前描画された文字は上書きされます。デフォルトでは、文字の位置および属性はウィンドウオブジェクトにおける現在の設定になります。

@cartouche
@quotation 注釈 
Writing outside the window, subwindow, or pad raises a @ref{3462,,curses.error}.
Attempting to write to the lower right corner of a window, subwindow,
or pad will cause an exception to be raised after the character is printed.
@end quotation
@end cartouche
@end deffn

@geindex addnstr() (curses.window のメソッド)
@anchor{library/curses curses window addnstr}@anchor{34b5}
@deffn {メソッド} window.addnstr (str, n[, attr])

@deffnx {メソッド} window.addnstr (y, x, str, n[, attr])

文字列 `str' から最大で `n' 文字を @code{(y, x)}  に属性 `attr' で描画します。以前ディスプレイにあった内容はすべて上書きされます。
@end deffn

@geindex addstr() (curses.window のメソッド)
@anchor{library/curses curses window addstr}@anchor{3474}
@deffn {メソッド} window.addstr (str[, attr])

@deffnx {メソッド} window.addstr (y, x, str[, attr])

@code{(y, x)} に文字列 `str' を属性 `attr' で描画します。以前ディスプレイにあった内容はすべて上書きされます。

@cartouche
@quotation 注釈 

@itemize *

@item 
Writing outside the window, subwindow, or pad raises @ref{3462,,curses.error}.
Attempting to write to the lower right corner of a window, subwindow,
or pad will cause an exception to be raised after the string is printed.

@item 
A bug in ncurses@footnote{https://bugs.python.org/issue35924}, the backend
for this Python module, can cause SegFaults when resizing windows. This
is fixed in ncurses-6.1-20190511.  If you are stuck with an earlier
ncurses, you can avoid triggering this if you do not call @ref{3474,,addstr()}
with a `str' that has embedded newlines.  Instead, call @ref{3474,,addstr()}
separately for each line.
@end itemize
@end quotation
@end cartouche
@end deffn

@geindex attroff() (curses.window のメソッド)
@anchor{library/curses curses window attroff}@anchor{34b6}
@deffn {メソッド} window.attroff (attr)

現在のウィンドウに書き込まれたすべての内容に対し "バックグラウンド" に設定された属性 `attr' を除去します。
@end deffn

@geindex attron() (curses.window のメソッド)
@anchor{library/curses curses window attron}@anchor{34b7}
@deffn {メソッド} window.attron (attr)

Add attribute `attr' to the "background" set applied to all writes to the
current window.
@end deffn

@geindex attrset() (curses.window のメソッド)
@anchor{library/curses curses window attrset}@anchor{34b8}
@deffn {メソッド} window.attrset (attr)

"バックグラウンド" の属性セットを `attr' に設定します。初期値は @code{0} (属性なし) です。
@end deffn

@geindex bkgd() (curses.window のメソッド)
@anchor{library/curses curses window bkgd}@anchor{34b9}
@deffn {メソッド} window.bkgd (ch[, attr])

ウィンドウ上の背景プロパティを、`attr' を属性とする文字 `ch' に設定します。変更はそのウィンドウ中のすべての文字に以下のようにして適用されます:


@itemize *

@item 
ウィンドウ中のすべての文字の属性が新たな背景属性に変更されます。

@item 
以前の背景文字が出現すると、常に新たな背景文字に変更されます。
@end itemize
@end deffn

@geindex bkgdset() (curses.window のメソッド)
@anchor{library/curses curses window bkgdset}@anchor{34ba}
@deffn {メソッド} window.bkgdset (ch[, attr])

ウィンドウの背景を設定します。ウィンドウの背景は、文字と何らかの属性の組み合わせから成り立ちます。背景情報の属性の部分は、ウィンドウ上に描画されている空白でないすべての文字と組み合わされ (OR され) ます。空白文字には文字部分と属性部分の両方が組み合わされます。背景は文字のプロパティとなり、スクロールや行/文字の挿入/削除操作の際には文字と一緒に移動します。
@end deffn

@geindex border() (curses.window のメソッド)
@anchor{library/curses curses window border}@anchor{34bb}
@deffn {メソッド} window.border ([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])

ウィンドウの縁に境界線を描画します。各引数には境界の特定部分を表現するために使われる文字を指定します; 詳細は以下のテーブルを参照してください。

@cartouche
@quotation 注釈 
どの引数も、@code{0} を指定した場合デフォルトの文字が使われるようになります。キーワード引数は使うことが `できません'。デフォルトはテーブル内で示しています:
@end quotation
@end cartouche


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

引数

@tab

説明

@tab

デフォルト値

@item

`ls'

@tab

左側

@tab

@ref{34bc,,ACS_VLINE}

@item

`rs'

@tab

右側

@tab

@ref{34bc,,ACS_VLINE}

@item

`ts'

@tab

上側

@tab

@ref{34bd,,ACS_HLINE}

@item

`bs'

@tab

下側

@tab

@ref{34bd,,ACS_HLINE}

@item

`tl'

@tab

左上の角

@tab

@ref{34be,,ACS_ULCORNER}

@item

`tr'

@tab

右上の角

@tab

@ref{34bf,,ACS_URCORNER}

@item

`bl'

@tab

左下の角

@tab

@ref{34c0,,ACS_LLCORNER}

@item

`br'

@tab

右下の角

@tab

@ref{34c1,,ACS_LRCORNER}

@end multitable

@end deffn

@geindex box() (curses.window のメソッド)
@anchor{library/curses curses window box}@anchor{34c2}
@deffn {メソッド} window.box ([vertch, horch])

@ref{34bb,,border()} と同様ですが、`ls' および `rs' は共に `vertch' で、`ts' および `bs' は共に `horch' です。この関数では、角に使われるデフォルト文字が常に使用されます。
@end deffn

@geindex chgat() (curses.window のメソッド)
@anchor{library/curses curses window chgat}@anchor{34c3}
@deffn {メソッド} window.chgat (attr)

@deffnx {メソッド} window.chgat (num, attr)

@deffnx {メソッド} window.chgat (y, x, attr)

@deffnx {メソッド} window.chgat (y, x, num, attr)

Set the attributes of `num' characters at the current cursor position, or at
position @code{(y, x)} if supplied. If `num' is not given or is @code{-1},
the attribute will be set on all the characters to the end of the line.  This
function moves cursor to position @code{(y, x)} if supplied. The changed line
will be touched using the @ref{34c4,,touchline()} method so that the contents will
be redisplayed by the next window refresh.
@end deffn

@geindex clear() (curses.window のメソッド)
@anchor{library/curses curses window clear}@anchor{34c5}
@deffn {メソッド} window.clear ()

@ref{34c6,,erase()} に似ていますが、次に @ref{3498,,refresh()} が呼び出された際にすべてのウィンドウを再描画するようにします。
@end deffn

@geindex clearok() (curses.window のメソッド)
@anchor{library/curses curses window clearok}@anchor{34c7}
@deffn {メソッド} window.clearok (flag)

`flag' が @code{True} ならば、次の @ref{3498,,refresh()} はウィンドウを完全に消去します。
@end deffn

@geindex clrtobot() (curses.window のメソッド)
@anchor{library/curses curses window clrtobot}@anchor{34c8}
@deffn {メソッド} window.clrtobot ()

カーソルの位置からウィンドウの端までを消去します: カーソル以降のすべての行が削除されるため、@ref{34c9,,clrtoeol()} と等価です。
@end deffn

@geindex clrtoeol() (curses.window のメソッド)
@anchor{library/curses curses window clrtoeol}@anchor{34c9}
@deffn {メソッド} window.clrtoeol ()

カーソル位置から行末までを消去します。
@end deffn

@geindex cursyncup() (curses.window のメソッド)
@anchor{library/curses curses window cursyncup}@anchor{34ca}
@deffn {メソッド} window.cursyncup ()

ウィンドウのすべての親ウィンドウについて、現在のカーソル位置を反映するよう更新します。
@end deffn

@geindex delch() (curses.window のメソッド)
@anchor{library/curses curses window delch}@anchor{34cb}
@deffn {メソッド} window.delch ([y, x])

@code{(y, x)} にある文字を削除します。
@end deffn

@geindex deleteln() (curses.window のメソッド)
@anchor{library/curses curses window deleteln}@anchor{34cc}
@deffn {メソッド} window.deleteln ()

カーソルの下にある行を削除します。後続の行はすべて 1 行上に移動します。
@end deffn

@geindex derwin() (curses.window のメソッド)
@anchor{library/curses curses window derwin}@anchor{34cd}
@deffn {メソッド} window.derwin (begin_y, begin_x)

@deffnx {メソッド} window.derwin (nlines, ncols, begin_y, begin_x)

"derive window (ウィンドウを派生する)" の短縮形です。@ref{34cd,,derwin()} は @ref{34ce,,subwin()} と同じですが、`begin_y' および `begin_x' はスクリーン全体の原点ではなく、ウィンドウの原点からの相対位置です。派生したウィンドウオブジェクトが返されます。
@end deffn

@geindex echochar() (curses.window のメソッド)
@anchor{library/curses curses window echochar}@anchor{34cf}
@deffn {メソッド} window.echochar (ch[, attr])

文字 `ch' に属性 `attr' を付与し、即座に @ref{3498,,refresh()} をウィンドウに対して呼び出します。
@end deffn

@geindex enclose() (curses.window のメソッド)
@anchor{library/curses curses window enclose}@anchor{1c91}
@deffn {メソッド} window.enclose (y, x)

与えられた文字セル座標をスクリーン原点から相対的なものとし、ウィンドウの中に含まれるかを調べて、@code{True} または @code{False} を返します。スクリーン上のウィンドウの一部がマウスイベントの発生場所を含むかどうかを調べる上で便利です。


バージョン 3.10 で変更: Previously it returned @code{1} or @code{0} instead of @code{True} or @code{False}.

@end deffn

@geindex encoding (curses.window の属性)
@anchor{library/curses curses window encoding}@anchor{12a8}
@deffn {の属性} window.encoding

encode メソッドの引数 (Unicode 文字列および文字) で使用されるエンコーディングです。例えば @ref{34ce,,window.subwin()} などでサブウィンドウを生成した時、エンコーディング属性は親ウィンドウから継承します。デフォルトでは、現在のロケールのエンコーディングが使用されます (@ref{329,,locale.getencoding()} 参照)。


Added in version 3.3.

@end deffn

@geindex erase() (curses.window のメソッド)
@anchor{library/curses curses window erase}@anchor{34c6}
@deffn {メソッド} window.erase ()

ウィンドウをクリアします。
@end deffn

@geindex getbegyx() (curses.window のメソッド)
@anchor{library/curses curses window getbegyx}@anchor{34d0}
@deffn {メソッド} window.getbegyx ()

Return a tuple @code{(y, x)} of coordinates of upper-left corner.
@end deffn

@geindex getbkgd() (curses.window のメソッド)
@anchor{library/curses curses window getbkgd}@anchor{34d1}
@deffn {メソッド} window.getbkgd ()

与えられたウィンドウの現在の背景文字と属性のペアを返します。
@end deffn

@geindex getch() (curses.window のメソッド)
@anchor{library/curses curses window getch}@anchor{1825}
@deffn {メソッド} window.getch ([y, x])

文字を 1 個取得します。返される整数は ASCII の範囲の値となる `とは限らない' ので注意してください。ファンクションキー、キーパッドのキー等は 256 よりも大きな数字で表されます。無遅延 (no-delay) モードでは、入力がない場合 -1 を返し、そうでなければキーが押されるまで待ちます。
@end deffn

@geindex get_wch() (curses.window のメソッド)
@anchor{library/curses curses window get_wch}@anchor{12a9}
@deffn {メソッド} window.get_wch ([y, x])

ワイド文字を 1 個取得します。ほとんどのキー、ファンクションキーの数値、キーパッドのキー、およびその他の特殊キーの文字を返します。無遅延モードでは、入力がない場合例外を送出します。


Added in version 3.3.

@end deffn

@geindex getkey() (curses.window のメソッド)
@anchor{library/curses curses window getkey}@anchor{34d2}
@deffn {メソッド} window.getkey ([y, x])

文字を 1 個取得し、 @ref{1825,,getch()} が返すような整数ではなく文字列を返します。ファンクションキー、キーパッドのキー、およびその他特殊キーはキー名を含む複数文字を返します。無遅延モードでは、入力がない場合例外を送出します。
@end deffn

@geindex getmaxyx() (curses.window のメソッド)
@anchor{library/curses curses window getmaxyx}@anchor{34d3}
@deffn {メソッド} window.getmaxyx ()

ウィンドウの高さおよび幅を表すタプル @code{(y, x)} を返します。
@end deffn

@geindex getparyx() (curses.window のメソッド)
@anchor{library/curses curses window getparyx}@anchor{34d4}
@deffn {メソッド} window.getparyx ()

親ウィンドウ中におけるウィンドウの開始位置をタプル @code{(y, x)} で返します。ウィンドウに親ウィンドウがない場合 @code{(-1, -1)} を返します。
@end deffn

@geindex getstr() (curses.window のメソッド)
@anchor{library/curses curses window getstr}@anchor{183e}
@deffn {メソッド} window.getstr ()

@deffnx {メソッド} window.getstr (n)

@deffnx {メソッド} window.getstr (y, x)

@deffnx {メソッド} window.getstr (y, x, n)

Read a bytes object from the user, with primitive line editing capacity.
The maximum value for `n' is 2047.


バージョン 3.14 で変更: The maximum value for `n' was increased from 1023 to 2047.

@end deffn

@geindex getyx() (curses.window のメソッド)
@anchor{library/curses curses window getyx}@anchor{34d5}
@deffn {メソッド} window.getyx ()

ウィンドウの左上角からの相対で表した現在のカーソル位置をタプル @code{(y, x)} で返します。
@end deffn

@geindex hline() (curses.window のメソッド)
@anchor{library/curses curses window hline}@anchor{34d6}
@deffn {メソッド} window.hline (ch, n)

@deffnx {メソッド} window.hline (y, x, ch, n)

@code{(y, x)} から始まり、`n' の長さを持つ、文字 `ch' で作られる水平線を表示します。
@end deffn

@geindex idcok() (curses.window のメソッド)
@anchor{library/curses curses window idcok}@anchor{34d7}
@deffn {メソッド} window.idcok (flag)

`flag' が @code{False} の場合、curses は端末のハードウェアによる文字挿入/削除機能を使おうとしなくなります; `flag' が @code{True} ならば、文字挿入/削除は有効にされます。curses が最初に初期化された際には文字挿入/削除はデフォルトで有効になっています。
@end deffn

@geindex idlok() (curses.window のメソッド)
@anchor{library/curses curses window idlok}@anchor{34d8}
@deffn {メソッド} window.idlok (flag)

If `flag' is @code{True}, @code{curses} will try and use hardware line
editing facilities. Otherwise, line insertion/deletion are disabled.
@end deffn

@geindex immedok() (curses.window のメソッド)
@anchor{library/curses curses window immedok}@anchor{34d9}
@deffn {メソッド} window.immedok (flag)

`flag' が @code{True} ならば、ウィンドウイメージ内における何らかの変更があるとウィンドウを更新するようになります; すなわち、@ref{3498,,refresh()} を自分で呼ばなくても良くなります。とはいえ、wrefresh を繰り返し呼び出すことになるため、この操作はかなりパフォーマンスを低下させます。デフォルトでは無効になっています。
@end deffn

@geindex inch() (curses.window のメソッド)
@anchor{library/curses curses window inch}@anchor{34da}
@deffn {メソッド} window.inch ([y, x])

ウィンドウの指定の位置の文字を返します。下位 8 ビットが本来の文字で、それより上のビットは属性です。
@end deffn

@geindex insch() (curses.window のメソッド)
@anchor{library/curses curses window insch}@anchor{34db}
@deffn {メソッド} window.insch (ch[, attr])

@deffnx {メソッド} window.insch (y, x, ch[, attr])

@code{(y, x)} に文字 `ch' を属性 `attr' で描画し、行の `x' からの内容を 1 文字分右にずらします。
@end deffn

@geindex insdelln() (curses.window のメソッド)
@anchor{library/curses curses window insdelln}@anchor{34dc}
@deffn {メソッド} window.insdelln (nlines)

`nlines' 行を指定されたウィンドウの現在の行の上に挿入します。その下にある `nlines' 行は失われます。負の `nlines' を指定すると、カーソルのある行以降の `nlines' を削除し、削除された行の後ろに続く内容が上に来ます。その下にある `nlines' は消去されます。現在のカーソル位置はそのままです。
@end deffn

@geindex insertln() (curses.window のメソッド)
@anchor{library/curses curses window insertln}@anchor{34dd}
@deffn {メソッド} window.insertln ()

カーソルの下に空行を 1 行入れます。それ以降の行は 1 行づつ下に移動します。
@end deffn

@geindex insnstr() (curses.window のメソッド)
@anchor{library/curses curses window insnstr}@anchor{34de}
@deffn {メソッド} window.insnstr (str, n[, attr])

@deffnx {メソッド} window.insnstr (y, x, str, n[, attr])

文字列をカーソルの下にある文字の前に (一行に収まるだけ) 最大 `n' 文字挿入します。`n' がゼロまたは負の値の場合、文字列全体が挿入されます。カーソルの右にあるすべての文字は右に移動し、行の左端にある文字は失われます。カーソル位置は (`y', `x' が指定されていた場合はそこに移動しますが、その後は) 変化しません。
@end deffn

@geindex insstr() (curses.window のメソッド)
@anchor{library/curses curses window insstr}@anchor{34df}
@deffn {メソッド} window.insstr (str[, attr])

@deffnx {メソッド} window.insstr (y, x, str[, attr])

キャラクタ文字列を (行に収まるだけ) カーソルより前に挿入します。カーソルの右側にある文字はすべて右にシフトし、行の右端の文字は失われます。カーソル位置は (`y', `x' が指定されていた場合はそこに移動しますが、その後は) 変化しません。
@end deffn

@geindex instr() (curses.window のメソッド)
@anchor{library/curses curses window instr}@anchor{183d}
@deffn {メソッド} window.instr ([n])

@deffnx {メソッド} window.instr (y, x[, n])

Return a bytes object of characters, extracted from the window starting at the
current cursor position, or at `y', `x' if specified. Attributes are stripped
from the characters.  If `n' is specified, @ref{183d,,instr()} returns a string
at most `n' characters long (exclusive of the trailing NUL).
The maximum value for `n' is 2047.


バージョン 3.14 で変更: The maximum value for `n' was increased from 1023 to 2047.

@end deffn

@geindex is_linetouched() (curses.window のメソッド)
@anchor{library/curses curses window is_linetouched}@anchor{34e0}
@deffn {メソッド} window.is_linetouched (line)

指定した行が、最後に @ref{3498,,refresh()} を呼んだ時から変更されている場合に @code{True} を返します; そうでない場合には @code{False} を返します。`line' が現在のウィンドウ上の有効な行でない場合、@ref{3462,,curses.error} 例外を送出します。
@end deffn

@geindex is_wintouched() (curses.window のメソッド)
@anchor{library/curses curses window is_wintouched}@anchor{34e1}
@deffn {メソッド} window.is_wintouched ()

指定したウィンドウが、最後に @ref{3498,,refresh()} を呼んだ時から変更されている場合に @code{True} を返します; そうでない場合には @code{False} を返します。
@end deffn

@geindex keypad() (curses.window のメソッド)
@anchor{library/curses curses window keypad}@anchor{34e2}
@deffn {メソッド} window.keypad (flag)

If `flag' is @code{True}, escape sequences generated by some keys (keypad,  function keys)
will be interpreted by @code{curses}. If `flag' is @code{False}, escape sequences will be
left as is in the input stream.
@end deffn

@geindex leaveok() (curses.window のメソッド)
@anchor{library/curses curses window leaveok}@anchor{34e3}
@deffn {メソッド} window.leaveok (flag)

`flag' が @code{True} の場合、カーソルは "カーソル位置" に移動せず現在の場所にとどめます。これにより、カーソルの移動を減らせる可能性があります。この場合、カーソルは不可視にされます。

`flag' が @code{False} の場合、カーソルは更新の際に常に "カーソル位置" に移動します。
@end deffn

@geindex move() (curses.window のメソッド)
@anchor{library/curses curses window move}@anchor{34e4}
@deffn {メソッド} window.move (new_y, new_x)

カーソルを @code{(new_y, new_x)} に移動します。
@end deffn

@geindex mvderwin() (curses.window のメソッド)
@anchor{library/curses curses window mvderwin}@anchor{34e5}
@deffn {メソッド} window.mvderwin (y, x)

ウィンドウを親ウィンドウの中で移動します。ウィンドウのスクリーン相対となるパラメタ群は変化しません。このルーチンは親ウィンドウの一部をスクリーン上の同じ物理位置に表示する際に用いられます。
@end deffn

@geindex mvwin() (curses.window のメソッド)
@anchor{library/curses curses window mvwin}@anchor{34e6}
@deffn {メソッド} window.mvwin (new_y, new_x)

ウィンドウの左上角が @code{(new_y, new_x)} になるように移動します。
@end deffn

@geindex nodelay() (curses.window のメソッド)
@anchor{library/curses curses window nodelay}@anchor{34e7}
@deffn {メソッド} window.nodelay (flag)

`flag' が @code{True} の場合、@ref{1825,,getch()} は非ブロックで動作します。
@end deffn

@geindex notimeout() (curses.window のメソッド)
@anchor{library/curses curses window notimeout}@anchor{34e8}
@deffn {メソッド} window.notimeout (flag)

`flag' が @code{True} の場合、エスケープシーケンスはタイムアウトしなくなります。

`flag' が @code{False} の場合、数ミリ秒間の間エスケープシーケンスは解釈されず、入力ストリーム中にそのままの状態で残されます。
@end deffn

@geindex noutrefresh() (curses.window のメソッド)
@anchor{library/curses curses window noutrefresh}@anchor{3475}
@deffn {メソッド} window.noutrefresh ()

更新をマークはしますが待機します。この関数はウィンドウのデータ構造を表現したい内容を反映するように更新しますが、物理スクリーン上に反映させるための強制更新を行いません。更新を行うためには @ref{3473,,doupdate()} を呼び出します。
@end deffn

@geindex overlay() (curses.window のメソッド)
@anchor{library/curses curses window overlay}@anchor{34e9}
@deffn {メソッド} window.overlay (destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

ウィンドウを `destwin' の上に重ね書き (overlay) します。ウィンドウは同じサイズである必要はなく、重なっている領域だけが複写されます。この複写は非破壊的です。これは現在の背景文字が `destwin' の内容を上書きしないことを意味します。

複写領域をきめ細かく制御するために、@ref{34e9,,overlay()} の第二形式を使うことができます。`sminrow' および `smincol' は元のウィンドウの左上の座標で、他の変数は `destwin' 内の矩形を表します。
@end deffn

@geindex overwrite() (curses.window のメソッド)
@anchor{library/curses curses window overwrite}@anchor{34ea}
@deffn {メソッド} window.overwrite (destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

`destwin' の上にウィンドウの内容を上書き (overwrite) します。ウィンドウは同じサイズである必要はなく、重なっている領域だけが複写されます。この複写は破壊的です。これは現在の背景文字が `destwin' の内容を上書きすることを意味します。

複写領域をきめ細かく制御するために、@ref{34ea,,overwrite()} の第二形式を使うことができます。`sminrow' および `smincol' は元のウィンドウの左上の座標で、他の変数は `destwin' 内の矩形を表します。
@end deffn

@geindex putwin() (curses.window のメソッド)
@anchor{library/curses curses window putwin}@anchor{3488}
@deffn {メソッド} window.putwin (file)

ウィンドウに関連付けられているすべてのデータを与えられたファイルオブジェクトに書き込みます。この情報は後に @ref{3487,,getwin()} 関数を使って取得することができます。
@end deffn

@geindex redrawln() (curses.window のメソッド)
@anchor{library/curses curses window redrawln}@anchor{34eb}
@deffn {メソッド} window.redrawln (beg, num)

`beg' 行から始まる `num' スクリーン行の表示内容が壊れており、次の @ref{3498,,refresh()} 呼び出しで完全に再描画されなければならないことを通知します。
@end deffn

@geindex redrawwin() (curses.window のメソッド)
@anchor{library/curses curses window redrawwin}@anchor{34ec}
@deffn {メソッド} window.redrawwin ()

ウィンドウ全体を更新 (touch) し、次の @ref{3498,,refresh()} 呼び出しで完全に再描画されるようにします。
@end deffn

@geindex refresh() (curses.window のメソッド)
@anchor{library/curses curses window refresh}@anchor{3498}
@deffn {メソッド} window.refresh ([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])

ディスプレイを即時更新し (実際のウィンドウとこれまでの描画/削除メソッドの内容とを同期し) ます。

6 つのオプション引数はウィンドウが @ref{3497,,newpad()} で生成された場合にのみ指定することができます。追加の引数はパッドやスクリーンのどの部分が含まれるのかを示すために必要です。`pminrow' および `pmincol' にはパッドが表示されている矩形の左上角を指定します。`sminrow',  `smincol', `smaxrow', および `smaxcol' には、スクリーン上に表示される矩形の縁を指定します。パッド内に表示される矩形の右下角はスクリーン座標から計算されるので、矩形は同じサイズでなければなりません。矩形は両方とも、それぞれのウィンドウ構造内に完全に含まれていなければなりません。`pminrow', `pmincol', `sminrow', または `smincol'  に負の値を指定すると、ゼロを指定したものとして扱われます。
@end deffn

@geindex resize() (curses.window のメソッド)
@anchor{library/curses curses window resize}@anchor{34ed}
@deffn {メソッド} window.resize (nlines, ncols)

curses ウィンドウの記憶域を、指定値のサイズに調整するため再割当てします。サイズが現在の値より大きい場合、ウィンドウのデータは現在の背景設定 (@ref{34ba,,bkgdset()} で設定) で埋められマージされます。
@end deffn

@geindex scroll() (curses.window のメソッド)
@anchor{library/curses curses window scroll}@anchor{34ee}
@deffn {メソッド} window.scroll ([lines=1])

スクリーンまたはスクロール領域を上に `lines' 行スクロールします。
@end deffn

@geindex scrollok() (curses.window のメソッド)
@anchor{library/curses curses window scrollok}@anchor{34ef}
@deffn {メソッド} window.scrollok (flag)

ウィンドウのカーソルが、最下行で改行を行ったり最後の文字を入力したりした結果、ウィンドウやスクロール領域の縁からはみ出して移動した際の動作を制御します。`flag' が @code{False} の場合、カーソルは最下行にそのままにしておかれます。`flag' が @code{True} の場合、ウィンドウは 1 行上にスクロールします。端末の物理スクロール効果を得るためには @ref{34d8,,idlok()} も呼び出す必要があるので注意してください。
@end deffn

@geindex setscrreg() (curses.window のメソッド)
@anchor{library/curses curses window setscrreg}@anchor{34f0}
@deffn {メソッド} window.setscrreg (top, bottom)

スクロール領域を `top' から `bottom' に設定します。スクロール動作はすべてこの領域で行われます。
@end deffn

@geindex standend() (curses.window のメソッド)
@anchor{library/curses curses window standend}@anchor{34f1}
@deffn {メソッド} window.standend ()

`A_STANDOUT' 属性をオフにします。端末によっては、この操作ですべての属性をオフにする副作用が発生します。
@end deffn

@geindex standout() (curses.window のメソッド)
@anchor{library/curses curses window standout}@anchor{34f2}
@deffn {メソッド} window.standout ()

`A_STANDOUT' 属性をオンにします。
@end deffn

@geindex subpad() (curses.window のメソッド)
@anchor{library/curses curses window subpad}@anchor{34f3}
@deffn {メソッド} window.subpad (begin_y, begin_x)

@deffnx {メソッド} window.subpad (nlines, ncols, begin_y, begin_x)

左上の角が @code{(begin_y, begin_x)} にあり、幅/高さがそれぞれ `ncols' / `nlines' であるようなサブウィンドウを返します。
@end deffn

@geindex subwin() (curses.window のメソッド)
@anchor{library/curses curses window subwin}@anchor{34ce}
@deffn {メソッド} window.subwin (begin_y, begin_x)

@deffnx {メソッド} window.subwin (nlines, ncols, begin_y, begin_x)

左上の角が @code{(begin_y, begin_x)} にあり、幅/高さがそれぞれ `ncols' / `nlines' であるようなサブウィンドウを返します。

デフォルトでは、サブウィンドウは指定された場所からウィンドウの右下角まで広がります。
@end deffn

@geindex syncdown() (curses.window のメソッド)
@anchor{library/curses curses window syncdown}@anchor{34f4}
@deffn {メソッド} window.syncdown ()

このウィンドウの上位のウィンドウのいずれかで更新(touch)された各場所をこのウィンドウ内でも更新します。このルーチンは @ref{3498,,refresh()} から呼び出されるので、手動で呼び出す必要はほとんどないはずです。
@end deffn

@geindex syncok() (curses.window のメソッド)
@anchor{library/curses curses window syncok}@anchor{34f5}
@deffn {メソッド} window.syncok (flag)

`flag' が @code{True} の場合、ウィンドウが変更された際は常に @ref{34f6,,syncup()} を自動的に呼ぶようになります。
@end deffn

@geindex syncup() (curses.window のメソッド)
@anchor{library/curses curses window syncup}@anchor{34f6}
@deffn {メソッド} window.syncup ()

ウィンドウ内で更新 (touch) した場所を、上位のすべてのウィンドウ内でも更新します。
@end deffn

@geindex timeout() (curses.window のメソッド)
@anchor{library/curses curses window timeout}@anchor{34f7}
@deffn {メソッド} window.timeout (delay)

ウィンドウのブロックまたは非ブロック読み込み動作を設定します。`delay' が負の場合、ブロック読み出しが使われ、入力を無期限で待ち受けます。`delay' がゼロの場合、非ブロック読み出しが使われ、入力待ちの文字がない場合 @ref{1825,,getch()} は @code{-1} を返します。`delay' が正の値であれば、@ref{1825,,getch()} は `delay' ミリ秒間ブロックし、ブロック後の時点で入力がない場合には @code{-1} を返します。
@end deffn

@geindex touchline() (curses.window のメソッド)
@anchor{library/curses curses window touchline}@anchor{34c4}
@deffn {メソッド} window.touchline (start, count[, changed])

`start' から始まる `count' 行が変更されたかのように振舞わせます。もし `changed' が与えられた場合、その引数は指定された行が変更された(`changed'@code{=True})か、変更されていないか(`changed')を指定します。
@end deffn

@geindex touchwin() (curses.window のメソッド)
@anchor{library/curses curses window touchwin}@anchor{34f8}
@deffn {メソッド} window.touchwin ()

描画を最適化するために、すべてのウィンドウが変更されたかのように振舞わせます。
@end deffn

@geindex untouchwin() (curses.window のメソッド)
@anchor{library/curses curses window untouchwin}@anchor{34f9}
@deffn {メソッド} window.untouchwin ()

ウィンドウ内のすべての行を、最後に @ref{3498,,refresh()} を呼んだ際から変更されていないものとしてマークします。
@end deffn

@geindex vline() (curses.window のメソッド)
@anchor{library/curses curses window vline}@anchor{1afe}
@deffn {メソッド} window.vline (ch, n[, attr])

@deffnx {メソッド} window.vline (y, x, ch, n[, attr])

Display a vertical line starting at @code{(y, x)} with length `n' consisting of the
character `ch' with attributes `attr'.
@end deffn

@node 定数<6>,,Window オブジェクト,curses --- 文字セル表示のターミナル処理
@anchor{library/curses constants}@anchor{34fa}
@subsubsection 定数


The @code{curses} module defines the following data members:

@geindex ERR (curses モジュール)
@anchor{library/curses curses ERR}@anchor{34fb}
@deffn {データ} curses.ERR

@ref{1825,,getch()} のような整数を返す curses ルーチンのいくつかは、失敗した際に @ref{34fb,,ERR} を返します。
@end deffn

@geindex OK (curses モジュール)
@anchor{library/curses curses OK}@anchor{34fc}
@deffn {データ} curses.OK

@ref{190e,,napms()} のような整数を返す curses ルーチンのいくつかは、成功した際に @ref{34fc,,OK} を返します。
@end deffn

@geindex version (curses モジュール)
@anchor{library/curses curses version}@anchor{34fd}
@deffn {データ} curses.version

A bytes object representing the current version of the module.
@end deffn

@geindex ncurses_version (curses モジュール)
@anchor{library/curses curses ncurses_version}@anchor{bda}
@deffn {データ} curses.ncurses_version

A named tuple containing the three components of the ncurses library
version: `major', `minor', and `patch'.  All values are integers.  The
components can also be accessed by name,  so @code{curses.ncurses_version[0]}
is equivalent to @code{curses.ncurses_version.major} and so on.

Availability: if the ncurses library is used.


Added in version 3.8.

@end deffn

@geindex COLORS (curses モジュール)
@anchor{library/curses curses COLORS}@anchor{34a6}
@deffn {データ} curses.COLORS

The maximum number of colors the terminal can support.
It is defined only after the call to @ref{34a5,,start_color()}.
@end deffn

@geindex COLOR_PAIRS (curses モジュール)
@anchor{library/curses curses COLOR_PAIRS}@anchor{34a7}
@deffn {データ} curses.COLOR_PAIRS

The maximum number of color pairs the terminal can support.
It is defined only after the call to @ref{34a5,,start_color()}.
@end deffn

@geindex COLS (curses モジュール)
@anchor{library/curses curses COLS}@anchor{fed}
@deffn {データ} curses.COLS

The width of the screen, i.e., the number of columns.
It is defined only after the call to @ref{190f,,initscr()}.
Updated by @ref{feb,,update_lines_cols()}, @ref{192f,,resizeterm()} and
@ref{1930,,resize_term()}.
@end deffn

@geindex LINES (curses モジュール)
@anchor{library/curses curses LINES}@anchor{fec}
@deffn {データ} curses.LINES

The height of the screen, i.e., the number of lines.
It is defined only after the call to @ref{190f,,initscr()}.
Updated by @ref{feb,,update_lines_cols()}, @ref{192f,,resizeterm()} and
@ref{1930,,resize_term()}.
@end deffn

Some constants are available to specify character cell attributes.
The exact constants available are system dependent.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

意味

@item

@geindex A_ALTCHARSET (curses モジュール)
@anchor{library/curses curses A_ALTCHARSET}@anchor{34fe}
@deffn {データ} curses.A_ALTCHARSET
@end deffn

@tab

代替文字セットモード

@item

@geindex A_BLINK (curses モジュール)
@anchor{library/curses curses A_BLINK}@anchor{34ff}
@deffn {データ} curses.A_BLINK
@end deffn

@tab

点滅モード

@item

@geindex A_BOLD (curses モジュール)
@anchor{library/curses curses A_BOLD}@anchor{3500}
@deffn {データ} curses.A_BOLD
@end deffn

@tab

太字モード

@item

@geindex A_DIM (curses モジュール)
@anchor{library/curses curses A_DIM}@anchor{3501}
@deffn {データ} curses.A_DIM
@end deffn

@tab

低輝度モード

@item

@geindex A_INVIS (curses モジュール)
@anchor{library/curses curses A_INVIS}@anchor{3502}
@deffn {データ} curses.A_INVIS
@end deffn

@tab

Invisible or blank mode

@item

@geindex A_ITALIC (curses モジュール)
@anchor{library/curses curses A_ITALIC}@anchor{3503}
@deffn {データ} curses.A_ITALIC
@end deffn

@tab

イタリックモード

@item

@geindex A_NORMAL (curses モジュール)
@anchor{library/curses curses A_NORMAL}@anchor{3463}
@deffn {データ} curses.A_NORMAL
@end deffn

@tab

通常の属性

@item

@geindex A_PROTECT (curses モジュール)
@anchor{library/curses curses A_PROTECT}@anchor{3504}
@deffn {データ} curses.A_PROTECT
@end deffn

@tab

Protected mode

@item

@geindex A_REVERSE (curses モジュール)
@anchor{library/curses curses A_REVERSE}@anchor{346b}
@deffn {データ} curses.A_REVERSE
@end deffn

@tab

Reverse background and
foreground colors

@item

@geindex A_STANDOUT (curses モジュール)
@anchor{library/curses curses A_STANDOUT}@anchor{346a}
@deffn {データ} curses.A_STANDOUT
@end deffn

@tab

強調モード

@item

@geindex A_UNDERLINE (curses モジュール)
@anchor{library/curses curses A_UNDERLINE}@anchor{3505}
@deffn {データ} curses.A_UNDERLINE
@end deffn

@tab

下線モード

@item

@geindex A_HORIZONTAL (curses モジュール)
@anchor{library/curses curses A_HORIZONTAL}@anchor{3506}
@deffn {データ} curses.A_HORIZONTAL
@end deffn

@tab

Horizontal highlight

@item

@geindex A_LEFT (curses モジュール)
@anchor{library/curses curses A_LEFT}@anchor{3507}
@deffn {データ} curses.A_LEFT
@end deffn

@tab

Left highlight

@item

@geindex A_LOW (curses モジュール)
@anchor{library/curses curses A_LOW}@anchor{3508}
@deffn {データ} curses.A_LOW
@end deffn

@tab

Low highlight

@item

@geindex A_RIGHT (curses モジュール)
@anchor{library/curses curses A_RIGHT}@anchor{3509}
@deffn {データ} curses.A_RIGHT
@end deffn

@tab

Right highlight

@item

@geindex A_TOP (curses モジュール)
@anchor{library/curses curses A_TOP}@anchor{350a}
@deffn {データ} curses.A_TOP
@end deffn

@tab

Top highlight

@item

@geindex A_VERTICAL (curses モジュール)
@anchor{library/curses curses A_VERTICAL}@anchor{350b}
@deffn {データ} curses.A_VERTICAL
@end deffn

@tab

Vertical highlight

@end multitable



Added in version 3.7: @code{A_ITALIC} が追加されました。


Several constants are available to extract corresponding attributes returned
by some methods.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Bit-mask

@tab

意味

@item

@geindex A_ATTRIBUTES (curses モジュール)
@anchor{library/curses curses A_ATTRIBUTES}@anchor{350c}
@deffn {データ} curses.A_ATTRIBUTES
@end deffn

@tab

Bit-mask to extract
attributes

@item

@geindex A_CHARTEXT (curses モジュール)
@anchor{library/curses curses A_CHARTEXT}@anchor{350d}
@deffn {データ} curses.A_CHARTEXT
@end deffn

@tab

Bit-mask to extract a
character

@item

@geindex A_COLOR (curses モジュール)
@anchor{library/curses curses A_COLOR}@anchor{350e}
@deffn {データ} curses.A_COLOR
@end deffn

@tab

Bit-mask to extract
color-pair field information

@end multitable


キーは @code{KEY_} で始まる名前をもつ整数定数です。利用可能なキーキャップはシステムに依存します。

@c XXX this table is far too large! should it be alphabetized?


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

キー定数

@tab

キー

@item

@geindex KEY_MIN (curses モジュール)
@anchor{library/curses curses KEY_MIN}@anchor{350f}
@deffn {データ} curses.KEY_MIN
@end deffn

@tab

最小のキー値

@item

@geindex KEY_BREAK (curses モジュール)
@anchor{library/curses curses KEY_BREAK}@anchor{3510}
@deffn {データ} curses.KEY_BREAK
@end deffn

@tab

ブレークキー (Break, 信頼できません)

@item

@geindex KEY_DOWN (curses モジュール)
@anchor{library/curses curses KEY_DOWN}@anchor{3511}
@deffn {データ} curses.KEY_DOWN
@end deffn

@tab

下矢印

@item

@geindex KEY_UP (curses モジュール)
@anchor{library/curses curses KEY_UP}@anchor{3512}
@deffn {データ} curses.KEY_UP
@end deffn

@tab

上矢印

@item

@geindex KEY_LEFT (curses モジュール)
@anchor{library/curses curses KEY_LEFT}@anchor{3513}
@deffn {データ} curses.KEY_LEFT
@end deffn

@tab

左矢印

@item

@geindex KEY_RIGHT (curses モジュール)
@anchor{library/curses curses KEY_RIGHT}@anchor{3514}
@deffn {データ} curses.KEY_RIGHT
@end deffn

@tab

右矢印

@item

@geindex KEY_HOME (curses モジュール)
@anchor{library/curses curses KEY_HOME}@anchor{3515}
@deffn {データ} curses.KEY_HOME
@end deffn

@tab

ホームキー (Home, または上左矢印)

@item

@geindex KEY_BACKSPACE (curses モジュール)
@anchor{library/curses curses KEY_BACKSPACE}@anchor{3516}
@deffn {データ} curses.KEY_BACKSPACE
@end deffn

@tab

バックスペース (Backspace, 信頼できません)

@item

@geindex KEY_F0 (curses モジュール)
@anchor{library/curses curses KEY_F0}@anchor{3517}
@deffn {データ} curses.KEY_F0
@end deffn

@tab

ファンクションキー。64 個までサポートされています。

@item

@geindex KEY_Fn (curses モジュール)
@anchor{library/curses curses KEY_Fn}@anchor{3518}
@deffn {データ} curses.KEY_Fn
@end deffn

@tab

ファンクションキー `n' の値

@item

@geindex KEY_DL (curses モジュール)
@anchor{library/curses curses KEY_DL}@anchor{3519}
@deffn {データ} curses.KEY_DL
@end deffn

@tab

行削除 (Delete line)

@item

@geindex KEY_IL (curses モジュール)
@anchor{library/curses curses KEY_IL}@anchor{351a}
@deffn {データ} curses.KEY_IL
@end deffn

@tab

行挿入 (Insert line)

@item

@geindex KEY_DC (curses モジュール)
@anchor{library/curses curses KEY_DC}@anchor{351b}
@deffn {データ} curses.KEY_DC
@end deffn

@tab

文字削除 (Delete char)

@item

@geindex KEY_IC (curses モジュール)
@anchor{library/curses curses KEY_IC}@anchor{351c}
@deffn {データ} curses.KEY_IC
@end deffn

@tab

文字挿入、または文字挿入モードへ入る

@item

@geindex KEY_EIC (curses モジュール)
@anchor{library/curses curses KEY_EIC}@anchor{351d}
@deffn {データ} curses.KEY_EIC
@end deffn

@tab

文字挿入モードから抜ける

@item

@geindex KEY_CLEAR (curses モジュール)
@anchor{library/curses curses KEY_CLEAR}@anchor{351e}
@deffn {データ} curses.KEY_CLEAR
@end deffn

@tab

画面消去

@item

@geindex KEY_EOS (curses モジュール)
@anchor{library/curses curses KEY_EOS}@anchor{351f}
@deffn {データ} curses.KEY_EOS
@end deffn

@tab

画面の末端まで消去

@item

@geindex KEY_EOL (curses モジュール)
@anchor{library/curses curses KEY_EOL}@anchor{3520}
@deffn {データ} curses.KEY_EOL
@end deffn

@tab

行末端まで消去

@item

@geindex KEY_SF (curses モジュール)
@anchor{library/curses curses KEY_SF}@anchor{3521}
@deffn {データ} curses.KEY_SF
@end deffn

@tab

前に 1 行スクロール

@item

@geindex KEY_SR (curses モジュール)
@anchor{library/curses curses KEY_SR}@anchor{3522}
@deffn {データ} curses.KEY_SR
@end deffn

@tab

後ろ (逆方向) に 1 行スクロール

@item

@geindex KEY_NPAGE (curses モジュール)
@anchor{library/curses curses KEY_NPAGE}@anchor{3523}
@deffn {データ} curses.KEY_NPAGE
@end deffn

@tab

次のページ (Page Next)

@item

@geindex KEY_PPAGE (curses モジュール)
@anchor{library/curses curses KEY_PPAGE}@anchor{3524}
@deffn {データ} curses.KEY_PPAGE
@end deffn

@tab

前のページ (Page Prev)

@item

@geindex KEY_STAB (curses モジュール)
@anchor{library/curses curses KEY_STAB}@anchor{3525}
@deffn {データ} curses.KEY_STAB
@end deffn

@tab

タブ設定

@item

@geindex KEY_CTAB (curses モジュール)
@anchor{library/curses curses KEY_CTAB}@anchor{3526}
@deffn {データ} curses.KEY_CTAB
@end deffn

@tab

タブリセット

@item

@geindex KEY_CATAB (curses モジュール)
@anchor{library/curses curses KEY_CATAB}@anchor{3527}
@deffn {データ} curses.KEY_CATAB
@end deffn

@tab

すべてのタブをリセット

@item

@geindex KEY_ENTER (curses モジュール)
@anchor{library/curses curses KEY_ENTER}@anchor{3528}
@deffn {データ} curses.KEY_ENTER
@end deffn

@tab

入力または送信 (信頼できません)

@item

@geindex KEY_SRESET (curses モジュール)
@anchor{library/curses curses KEY_SRESET}@anchor{3529}
@deffn {データ} curses.KEY_SRESET
@end deffn

@tab

ソフトウェア (部分的) リセット (信頼できません)

@item

@geindex KEY_RESET (curses モジュール)
@anchor{library/curses curses KEY_RESET}@anchor{352a}
@deffn {データ} curses.KEY_RESET
@end deffn

@tab

リセットまたはハードリセット (信頼できません)

@item

@geindex KEY_PRINT (curses モジュール)
@anchor{library/curses curses KEY_PRINT}@anchor{352b}
@deffn {データ} curses.KEY_PRINT
@end deffn

@tab

印刷 (Print)

@item

@geindex KEY_LL (curses モジュール)
@anchor{library/curses curses KEY_LL}@anchor{352c}
@deffn {データ} curses.KEY_LL
@end deffn

@tab

下ホーム (Home down) または最下行 (左下)

@item

@geindex KEY_A1 (curses モジュール)
@anchor{library/curses curses KEY_A1}@anchor{352d}
@deffn {データ} curses.KEY_A1
@end deffn

@tab

キーパッドの左上キー

@item

@geindex KEY_A3 (curses モジュール)
@anchor{library/curses curses KEY_A3}@anchor{352e}
@deffn {データ} curses.KEY_A3
@end deffn

@tab

キーパッドの右上キー

@item

@geindex KEY_B2 (curses モジュール)
@anchor{library/curses curses KEY_B2}@anchor{352f}
@deffn {データ} curses.KEY_B2
@end deffn

@tab

キーパッドの中央キー

@item

@geindex KEY_C1 (curses モジュール)
@anchor{library/curses curses KEY_C1}@anchor{3530}
@deffn {データ} curses.KEY_C1
@end deffn

@tab

キーパッドの左下キー

@item

@geindex KEY_C3 (curses モジュール)
@anchor{library/curses curses KEY_C3}@anchor{3531}
@deffn {データ} curses.KEY_C3
@end deffn

@tab

キーパッドの右下キー

@item

@geindex KEY_BTAB (curses モジュール)
@anchor{library/curses curses KEY_BTAB}@anchor{3532}
@deffn {データ} curses.KEY_BTAB
@end deffn

@tab

Back tab

@item

@geindex KEY_BEG (curses モジュール)
@anchor{library/curses curses KEY_BEG}@anchor{3533}
@deffn {データ} curses.KEY_BEG
@end deffn

@tab

開始 (Beg)

@item

@geindex KEY_CANCEL (curses モジュール)
@anchor{library/curses curses KEY_CANCEL}@anchor{3534}
@deffn {データ} curses.KEY_CANCEL
@end deffn

@tab

キャンセル (Cancel)

@item

@geindex KEY_CLOSE (curses モジュール)
@anchor{library/curses curses KEY_CLOSE}@anchor{3535}
@deffn {データ} curses.KEY_CLOSE
@end deffn

@tab

Close [閉じる]

@item

@geindex KEY_COMMAND (curses モジュール)
@anchor{library/curses curses KEY_COMMAND}@anchor{3536}
@deffn {データ} curses.KEY_COMMAND
@end deffn

@tab

コマンド (Cmd)

@item

@geindex KEY_COPY (curses モジュール)
@anchor{library/curses curses KEY_COPY}@anchor{3537}
@deffn {データ} curses.KEY_COPY
@end deffn

@tab

Copy [コピー]

@item

@geindex KEY_CREATE (curses モジュール)
@anchor{library/curses curses KEY_CREATE}@anchor{3538}
@deffn {データ} curses.KEY_CREATE
@end deffn

@tab

生成 (Create)

@item

@geindex KEY_END (curses モジュール)
@anchor{library/curses curses KEY_END}@anchor{3539}
@deffn {データ} curses.KEY_END
@end deffn

@tab

終了 (End)

@item

@geindex KEY_EXIT (curses モジュール)
@anchor{library/curses curses KEY_EXIT}@anchor{353a}
@deffn {データ} curses.KEY_EXIT
@end deffn

@tab

Exit [終了]

@item

@geindex KEY_FIND (curses モジュール)
@anchor{library/curses curses KEY_FIND}@anchor{353b}
@deffn {データ} curses.KEY_FIND
@end deffn

@tab

検索 (Find)

@item

@geindex KEY_HELP (curses モジュール)
@anchor{library/curses curses KEY_HELP}@anchor{353c}
@deffn {データ} curses.KEY_HELP
@end deffn

@tab

ヘルプ (Help)

@item

@geindex KEY_MARK (curses モジュール)
@anchor{library/curses curses KEY_MARK}@anchor{353d}
@deffn {データ} curses.KEY_MARK
@end deffn

@tab

マーク (Mark)

@item

@geindex KEY_MESSAGE (curses モジュール)
@anchor{library/curses curses KEY_MESSAGE}@anchor{353e}
@deffn {データ} curses.KEY_MESSAGE
@end deffn

@tab

メッセージ (Message)

@item

@geindex KEY_MOVE (curses モジュール)
@anchor{library/curses curses KEY_MOVE}@anchor{353f}
@deffn {データ} curses.KEY_MOVE
@end deffn

@tab

移動 (Move)

@item

@geindex KEY_NEXT (curses モジュール)
@anchor{library/curses curses KEY_NEXT}@anchor{3540}
@deffn {データ} curses.KEY_NEXT
@end deffn

@tab

次へ (Next)

@item

@geindex KEY_OPEN (curses モジュール)
@anchor{library/curses curses KEY_OPEN}@anchor{3541}
@deffn {データ} curses.KEY_OPEN
@end deffn

@tab

開く (Open)

@item

@geindex KEY_OPTIONS (curses モジュール)
@anchor{library/curses curses KEY_OPTIONS}@anchor{3542}
@deffn {データ} curses.KEY_OPTIONS
@end deffn

@tab

オプション

@item

@geindex KEY_PREVIOUS (curses モジュール)
@anchor{library/curses curses KEY_PREVIOUS}@anchor{3543}
@deffn {データ} curses.KEY_PREVIOUS
@end deffn

@tab

前へ (Prev)

@item

@geindex KEY_REDO (curses モジュール)
@anchor{library/curses curses KEY_REDO}@anchor{3544}
@deffn {データ} curses.KEY_REDO
@end deffn

@tab

Redo [やり直し]

@item

@geindex KEY_REFERENCE (curses モジュール)
@anchor{library/curses curses KEY_REFERENCE}@anchor{3545}
@deffn {データ} curses.KEY_REFERENCE
@end deffn

@tab

参照 (Ref)

@item

@geindex KEY_REFRESH (curses モジュール)
@anchor{library/curses curses KEY_REFRESH}@anchor{3546}
@deffn {データ} curses.KEY_REFRESH
@end deffn

@tab

更新 (Refresh)

@item

@geindex KEY_REPLACE (curses モジュール)
@anchor{library/curses curses KEY_REPLACE}@anchor{3547}
@deffn {データ} curses.KEY_REPLACE
@end deffn

@tab

置換 (Replace)

@item

@geindex KEY_RESTART (curses モジュール)
@anchor{library/curses curses KEY_RESTART}@anchor{3548}
@deffn {データ} curses.KEY_RESTART
@end deffn

@tab

再起動 (Restart)

@item

@geindex KEY_RESUME (curses モジュール)
@anchor{library/curses curses KEY_RESUME}@anchor{3549}
@deffn {データ} curses.KEY_RESUME
@end deffn

@tab

再開 (Resume)

@item

@geindex KEY_SAVE (curses モジュール)
@anchor{library/curses curses KEY_SAVE}@anchor{354a}
@deffn {データ} curses.KEY_SAVE
@end deffn

@tab

Save [保存]

@item

@geindex KEY_SBEG (curses モジュール)
@anchor{library/curses curses KEY_SBEG}@anchor{354b}
@deffn {データ} curses.KEY_SBEG
@end deffn

@tab

シフト付き Beg

@item

@geindex KEY_SCANCEL (curses モジュール)
@anchor{library/curses curses KEY_SCANCEL}@anchor{354c}
@deffn {データ} curses.KEY_SCANCEL
@end deffn

@tab

シフト付き Cancel

@item

@geindex KEY_SCOMMAND (curses モジュール)
@anchor{library/curses curses KEY_SCOMMAND}@anchor{354d}
@deffn {データ} curses.KEY_SCOMMAND
@end deffn

@tab

シフト付き Command

@item

@geindex KEY_SCOPY (curses モジュール)
@anchor{library/curses curses KEY_SCOPY}@anchor{354e}
@deffn {データ} curses.KEY_SCOPY
@end deffn

@tab

シフト付き Copy

@item

@geindex KEY_SCREATE (curses モジュール)
@anchor{library/curses curses KEY_SCREATE}@anchor{354f}
@deffn {データ} curses.KEY_SCREATE
@end deffn

@tab

シフト付き Create

@item

@geindex KEY_SDC (curses モジュール)
@anchor{library/curses curses KEY_SDC}@anchor{3550}
@deffn {データ} curses.KEY_SDC
@end deffn

@tab

シフト付き Delete char

@item

@geindex KEY_SDL (curses モジュール)
@anchor{library/curses curses KEY_SDL}@anchor{3551}
@deffn {データ} curses.KEY_SDL
@end deffn

@tab

シフト付き Delete line

@item

@geindex KEY_SELECT (curses モジュール)
@anchor{library/curses curses KEY_SELECT}@anchor{3552}
@deffn {データ} curses.KEY_SELECT
@end deffn

@tab

選択 (Select)

@item

@geindex KEY_SEND (curses モジュール)
@anchor{library/curses curses KEY_SEND}@anchor{3553}
@deffn {データ} curses.KEY_SEND
@end deffn

@tab

シフト付き End

@item

@geindex KEY_SEOL (curses モジュール)
@anchor{library/curses curses KEY_SEOL}@anchor{3554}
@deffn {データ} curses.KEY_SEOL
@end deffn

@tab

シフト付き Clear line

@item

@geindex KEY_SEXIT (curses モジュール)
@anchor{library/curses curses KEY_SEXIT}@anchor{3555}
@deffn {データ} curses.KEY_SEXIT
@end deffn

@tab

シフト付き Exit

@item

@geindex KEY_SFIND (curses モジュール)
@anchor{library/curses curses KEY_SFIND}@anchor{3556}
@deffn {データ} curses.KEY_SFIND
@end deffn

@tab

シフト付き Find

@item

@geindex KEY_SHELP (curses モジュール)
@anchor{library/curses curses KEY_SHELP}@anchor{3557}
@deffn {データ} curses.KEY_SHELP
@end deffn

@tab

シフト付き Help

@item

@geindex KEY_SHOME (curses モジュール)
@anchor{library/curses curses KEY_SHOME}@anchor{3558}
@deffn {データ} curses.KEY_SHOME
@end deffn

@tab

シフト付き Home

@item

@geindex KEY_SIC (curses モジュール)
@anchor{library/curses curses KEY_SIC}@anchor{3559}
@deffn {データ} curses.KEY_SIC
@end deffn

@tab

シフト付き Input

@item

@geindex KEY_SLEFT (curses モジュール)
@anchor{library/curses curses KEY_SLEFT}@anchor{355a}
@deffn {データ} curses.KEY_SLEFT
@end deffn

@tab

シフト付き Left arrow

@item

@geindex KEY_SMESSAGE (curses モジュール)
@anchor{library/curses curses KEY_SMESSAGE}@anchor{355b}
@deffn {データ} curses.KEY_SMESSAGE
@end deffn

@tab

シフト付き Message

@item

@geindex KEY_SMOVE (curses モジュール)
@anchor{library/curses curses KEY_SMOVE}@anchor{355c}
@deffn {データ} curses.KEY_SMOVE
@end deffn

@tab

シフト付き Move

@item

@geindex KEY_SNEXT (curses モジュール)
@anchor{library/curses curses KEY_SNEXT}@anchor{355d}
@deffn {データ} curses.KEY_SNEXT
@end deffn

@tab

シフト付き Next

@item

@geindex KEY_SOPTIONS (curses モジュール)
@anchor{library/curses curses KEY_SOPTIONS}@anchor{355e}
@deffn {データ} curses.KEY_SOPTIONS
@end deffn

@tab

シフト付き Options

@item

@geindex KEY_SPREVIOUS (curses モジュール)
@anchor{library/curses curses KEY_SPREVIOUS}@anchor{355f}
@deffn {データ} curses.KEY_SPREVIOUS
@end deffn

@tab

シフト付き Prev

@item

@geindex KEY_SPRINT (curses モジュール)
@anchor{library/curses curses KEY_SPRINT}@anchor{3560}
@deffn {データ} curses.KEY_SPRINT
@end deffn

@tab

シフト付き Print

@item

@geindex KEY_SREDO (curses モジュール)
@anchor{library/curses curses KEY_SREDO}@anchor{3561}
@deffn {データ} curses.KEY_SREDO
@end deffn

@tab

シフト付き Redo

@item

@geindex KEY_SREPLACE (curses モジュール)
@anchor{library/curses curses KEY_SREPLACE}@anchor{3562}
@deffn {データ} curses.KEY_SREPLACE
@end deffn

@tab

シフト付き Replace

@item

@geindex KEY_SRIGHT (curses モジュール)
@anchor{library/curses curses KEY_SRIGHT}@anchor{3563}
@deffn {データ} curses.KEY_SRIGHT
@end deffn

@tab

シフト付き Right arrow

@item

@geindex KEY_SRSUME (curses モジュール)
@anchor{library/curses curses KEY_SRSUME}@anchor{3564}
@deffn {データ} curses.KEY_SRSUME
@end deffn

@tab

シフト付き Resume

@item

@geindex KEY_SSAVE (curses モジュール)
@anchor{library/curses curses KEY_SSAVE}@anchor{3565}
@deffn {データ} curses.KEY_SSAVE
@end deffn

@tab

シフト付き Save

@item

@geindex KEY_SSUSPEND (curses モジュール)
@anchor{library/curses curses KEY_SSUSPEND}@anchor{3566}
@deffn {データ} curses.KEY_SSUSPEND
@end deffn

@tab

シフト付き Suspend

@item

@geindex KEY_SUNDO (curses モジュール)
@anchor{library/curses curses KEY_SUNDO}@anchor{3567}
@deffn {データ} curses.KEY_SUNDO
@end deffn

@tab

シフト付き Undo

@item

@geindex KEY_SUSPEND (curses モジュール)
@anchor{library/curses curses KEY_SUSPEND}@anchor{3568}
@deffn {データ} curses.KEY_SUSPEND
@end deffn

@tab

一時停止 (Suspend)

@item

@geindex KEY_UNDO (curses モジュール)
@anchor{library/curses curses KEY_UNDO}@anchor{3569}
@deffn {データ} curses.KEY_UNDO
@end deffn

@tab

Undo [元に戻す]

@item

@geindex KEY_MOUSE (curses モジュール)
@anchor{library/curses curses KEY_MOUSE}@anchor{347d}
@deffn {データ} curses.KEY_MOUSE
@end deffn

@tab

マウスイベント通知

@item

@geindex KEY_RESIZE (curses モジュール)
@anchor{library/curses curses KEY_RESIZE}@anchor{356a}
@deffn {データ} curses.KEY_RESIZE
@end deffn

@tab

端末リサイズイベント

@item

@geindex KEY_MAX (curses モジュール)
@anchor{library/curses curses KEY_MAX}@anchor{356b}
@deffn {データ} curses.KEY_MAX
@end deffn

@tab

最大キー値

@end multitable


On VT100s and their software emulations, such as X terminal emulators, there are
normally at least four function keys (@ref{3518,,KEY_F1}, @ref{3518,,KEY_F2},
@ref{3518,,KEY_F3}, @ref{3518,,KEY_F4}) available, and the arrow keys mapped to
@ref{3512,,KEY_UP}, @ref{3511,,KEY_DOWN}, @ref{3513,,KEY_LEFT} and @ref{3514,,KEY_RIGHT} in
the obvious way.  If your machine has a PC keyboard, it is safe to expect arrow
keys and twelve function keys (older PC keyboards may have only ten function
keys); also, the following keypad mappings are standard:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
@headitem

キーキャップ

@tab

定数

@item

@code{Insert}

@tab

KEY_IC

@item

@code{Delete}

@tab

KEY_DC

@item

@code{Home}

@tab

KEY_HOME

@item

@code{End}

@tab

KEY_END

@item

@code{Page Up}

@tab

KEY_PPAGE

@item

@code{Page Down}

@tab

KEY_NPAGE

@end multitable

@anchor{library/curses curses-acs-codes}@anchor{356c}
代替文字セットを以下の表に列挙します。これらは VT100 端末から継承したものであり、X 端末のようなソフトウェアエミュレーション上で一般に利用可能なものです。グラフィックが利用できない場合、curses は印字可能 ASCII文字による粗雑な近似出力を行います。

@cartouche
@quotation 注釈 
これらは @ref{190f,,initscr()} が呼び出された後でしか利用できません。
@end quotation
@end cartouche


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ACS コード

@tab

意味

@item

@geindex ACS_BBSS (curses モジュール)
@anchor{library/curses curses ACS_BBSS}@anchor{356d}
@deffn {データ} curses.ACS_BBSS
@end deffn

@tab

右上角の別名

@item

@geindex ACS_BLOCK (curses モジュール)
@anchor{library/curses curses ACS_BLOCK}@anchor{356e}
@deffn {データ} curses.ACS_BLOCK
@end deffn

@tab

黒四角ブロック

@item

@geindex ACS_BOARD (curses モジュール)
@anchor{library/curses curses ACS_BOARD}@anchor{356f}
@deffn {データ} curses.ACS_BOARD
@end deffn

@tab

白四角ブロック

@item

@geindex ACS_BSBS (curses モジュール)
@anchor{library/curses curses ACS_BSBS}@anchor{3570}
@deffn {データ} curses.ACS_BSBS
@end deffn

@tab

水平線の別名

@item

@geindex ACS_BSSB (curses モジュール)
@anchor{library/curses curses ACS_BSSB}@anchor{3571}
@deffn {データ} curses.ACS_BSSB
@end deffn

@tab

左上角の別名

@item

@geindex ACS_BSSS (curses モジュール)
@anchor{library/curses curses ACS_BSSS}@anchor{3572}
@deffn {データ} curses.ACS_BSSS
@end deffn

@tab

上向き T 字罫線の別名

@item

@geindex ACS_BTEE (curses モジュール)
@anchor{library/curses curses ACS_BTEE}@anchor{3573}
@deffn {データ} curses.ACS_BTEE
@end deffn

@tab

下向き T 字罫線

@item

@geindex ACS_BULLET (curses モジュール)
@anchor{library/curses curses ACS_BULLET}@anchor{3574}
@deffn {データ} curses.ACS_BULLET
@end deffn

@tab

黒丸(bullet)

@item

@geindex ACS_CKBOARD (curses モジュール)
@anchor{library/curses curses ACS_CKBOARD}@anchor{3575}
@deffn {データ} curses.ACS_CKBOARD
@end deffn

@tab

チェッカーボードパタン (点描)

@item

@geindex ACS_DARROW (curses モジュール)
@anchor{library/curses curses ACS_DARROW}@anchor{3576}
@deffn {データ} curses.ACS_DARROW
@end deffn

@tab

下向き矢印

@item

@geindex ACS_DEGREE (curses モジュール)
@anchor{library/curses curses ACS_DEGREE}@anchor{3577}
@deffn {データ} curses.ACS_DEGREE
@end deffn

@tab

度記号

@item

@geindex ACS_DIAMOND (curses モジュール)
@anchor{library/curses curses ACS_DIAMOND}@anchor{3578}
@deffn {データ} curses.ACS_DIAMOND
@end deffn

@tab

ダイアモンド

@item

@geindex ACS_GEQUAL (curses モジュール)
@anchor{library/curses curses ACS_GEQUAL}@anchor{3579}
@deffn {データ} curses.ACS_GEQUAL
@end deffn

@tab

大なりイコール

@item

@geindex ACS_HLINE (curses モジュール)
@anchor{library/curses curses ACS_HLINE}@anchor{34bd}
@deffn {データ} curses.ACS_HLINE
@end deffn

@tab

水平線

@item

@geindex ACS_LANTERN (curses モジュール)
@anchor{library/curses curses ACS_LANTERN}@anchor{357a}
@deffn {データ} curses.ACS_LANTERN
@end deffn

@tab

ランタン(lantern) シンボル

@item

@geindex ACS_LARROW (curses モジュール)
@anchor{library/curses curses ACS_LARROW}@anchor{357b}
@deffn {データ} curses.ACS_LARROW
@end deffn

@tab

左向き矢印

@item

@geindex ACS_LEQUAL (curses モジュール)
@anchor{library/curses curses ACS_LEQUAL}@anchor{357c}
@deffn {データ} curses.ACS_LEQUAL
@end deffn

@tab

小なりイコール

@item

@geindex ACS_LLCORNER (curses モジュール)
@anchor{library/curses curses ACS_LLCORNER}@anchor{34c0}
@deffn {データ} curses.ACS_LLCORNER
@end deffn

@tab

左下角

@item

@geindex ACS_LRCORNER (curses モジュール)
@anchor{library/curses curses ACS_LRCORNER}@anchor{34c1}
@deffn {データ} curses.ACS_LRCORNER
@end deffn

@tab

右下角

@item

@geindex ACS_LTEE (curses モジュール)
@anchor{library/curses curses ACS_LTEE}@anchor{357d}
@deffn {データ} curses.ACS_LTEE
@end deffn

@tab

左向き T 字罫線

@item

@geindex ACS_NEQUAL (curses モジュール)
@anchor{library/curses curses ACS_NEQUAL}@anchor{357e}
@deffn {データ} curses.ACS_NEQUAL
@end deffn

@tab

不等号

@item

@geindex ACS_PI (curses モジュール)
@anchor{library/curses curses ACS_PI}@anchor{357f}
@deffn {データ} curses.ACS_PI
@end deffn

@tab

パイ記号

@item

@geindex ACS_PLMINUS (curses モジュール)
@anchor{library/curses curses ACS_PLMINUS}@anchor{3580}
@deffn {データ} curses.ACS_PLMINUS
@end deffn

@tab

プラスマイナス記号

@item

@geindex ACS_PLUS (curses モジュール)
@anchor{library/curses curses ACS_PLUS}@anchor{3581}
@deffn {データ} curses.ACS_PLUS
@end deffn

@tab

大プラス記号

@item

@geindex ACS_RARROW (curses モジュール)
@anchor{library/curses curses ACS_RARROW}@anchor{3582}
@deffn {データ} curses.ACS_RARROW
@end deffn

@tab

右向き矢印

@item

@geindex ACS_RTEE (curses モジュール)
@anchor{library/curses curses ACS_RTEE}@anchor{3583}
@deffn {データ} curses.ACS_RTEE
@end deffn

@tab

右向き T 字罫線

@item

@geindex ACS_S1 (curses モジュール)
@anchor{library/curses curses ACS_S1}@anchor{3584}
@deffn {データ} curses.ACS_S1
@end deffn

@tab

スキャンライン 1

@item

@geindex ACS_S3 (curses モジュール)
@anchor{library/curses curses ACS_S3}@anchor{3585}
@deffn {データ} curses.ACS_S3
@end deffn

@tab

スキャンライン 3

@item

@geindex ACS_S7 (curses モジュール)
@anchor{library/curses curses ACS_S7}@anchor{3586}
@deffn {データ} curses.ACS_S7
@end deffn

@tab

スキャンライン 7

@item

@geindex ACS_S9 (curses モジュール)
@anchor{library/curses curses ACS_S9}@anchor{3587}
@deffn {データ} curses.ACS_S9
@end deffn

@tab

スキャンライン 9

@item

@geindex ACS_SBBS (curses モジュール)
@anchor{library/curses curses ACS_SBBS}@anchor{3588}
@deffn {データ} curses.ACS_SBBS
@end deffn

@tab

右下角の別名

@item

@geindex ACS_SBSB (curses モジュール)
@anchor{library/curses curses ACS_SBSB}@anchor{3589}
@deffn {データ} curses.ACS_SBSB
@end deffn

@tab

垂直線の別名

@item

@geindex ACS_SBSS (curses モジュール)
@anchor{library/curses curses ACS_SBSS}@anchor{358a}
@deffn {データ} curses.ACS_SBSS
@end deffn

@tab

右向き T 字罫線の別名

@item

@geindex ACS_SSBB (curses モジュール)
@anchor{library/curses curses ACS_SSBB}@anchor{358b}
@deffn {データ} curses.ACS_SSBB
@end deffn

@tab

左下角の別名

@item

@geindex ACS_SSBS (curses モジュール)
@anchor{library/curses curses ACS_SSBS}@anchor{358c}
@deffn {データ} curses.ACS_SSBS
@end deffn

@tab

下向き T 字罫線の別名

@item

@geindex ACS_SSSB (curses モジュール)
@anchor{library/curses curses ACS_SSSB}@anchor{358d}
@deffn {データ} curses.ACS_SSSB
@end deffn

@tab

左向き T 字罫線の別名

@item

@geindex ACS_SSSS (curses モジュール)
@anchor{library/curses curses ACS_SSSS}@anchor{358e}
@deffn {データ} curses.ACS_SSSS
@end deffn

@tab

交差罫線または大プラス記号の別名

@item

@geindex ACS_STERLING (curses モジュール)
@anchor{library/curses curses ACS_STERLING}@anchor{358f}
@deffn {データ} curses.ACS_STERLING
@end deffn

@tab

ポンドスターリング記号

@item

@geindex ACS_TTEE (curses モジュール)
@anchor{library/curses curses ACS_TTEE}@anchor{3590}
@deffn {データ} curses.ACS_TTEE
@end deffn

@tab

上向き T 字罫線

@item

@geindex ACS_UARROW (curses モジュール)
@anchor{library/curses curses ACS_UARROW}@anchor{3591}
@deffn {データ} curses.ACS_UARROW
@end deffn

@tab

上向き矢印

@item

@geindex ACS_ULCORNER (curses モジュール)
@anchor{library/curses curses ACS_ULCORNER}@anchor{34be}
@deffn {データ} curses.ACS_ULCORNER
@end deffn

@tab

左上角

@item

@geindex ACS_URCORNER (curses モジュール)
@anchor{library/curses curses ACS_URCORNER}@anchor{34bf}
@deffn {データ} curses.ACS_URCORNER
@end deffn

@tab

右上角

@item

@geindex ACS_VLINE (curses モジュール)
@anchor{library/curses curses ACS_VLINE}@anchor{34bc}
@deffn {データ} curses.ACS_VLINE
@end deffn

@tab

垂直線

@end multitable


The following table lists mouse button constants used by @ref{347c,,getmouse()}:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Mouse button constant

@tab

意味

@item

@geindex BUTTONn_PRESSED (curses モジュール)
@anchor{library/curses curses BUTTONn_PRESSED}@anchor{347e}
@deffn {データ} curses.BUTTONn_PRESSED
@end deffn

@tab

Mouse button `n' pressed

@item

@geindex BUTTONn_RELEASED (curses モジュール)
@anchor{library/curses curses BUTTONn_RELEASED}@anchor{347f}
@deffn {データ} curses.BUTTONn_RELEASED
@end deffn

@tab

Mouse button `n' released

@item

@geindex BUTTONn_CLICKED (curses モジュール)
@anchor{library/curses curses BUTTONn_CLICKED}@anchor{3480}
@deffn {データ} curses.BUTTONn_CLICKED
@end deffn

@tab

Mouse button `n' clicked

@item

@geindex BUTTONn_DOUBLE_CLICKED (curses モジュール)
@anchor{library/curses curses BUTTONn_DOUBLE_CLICKED}@anchor{3481}
@deffn {データ} curses.BUTTONn_DOUBLE_CLICKED
@end deffn

@tab

Mouse button `n' double clicked

@item

@geindex BUTTONn_TRIPLE_CLICKED (curses モジュール)
@anchor{library/curses curses BUTTONn_TRIPLE_CLICKED}@anchor{3482}
@deffn {データ} curses.BUTTONn_TRIPLE_CLICKED
@end deffn

@tab

Mouse button `n' triple clicked

@item

@geindex BUTTON_SHIFT (curses モジュール)
@anchor{library/curses curses BUTTON_SHIFT}@anchor{3483}
@deffn {データ} curses.BUTTON_SHIFT
@end deffn

@tab

Shift was down during button state change

@item

@geindex BUTTON_CTRL (curses モジュール)
@anchor{library/curses curses BUTTON_CTRL}@anchor{3484}
@deffn {データ} curses.BUTTON_CTRL
@end deffn

@tab

Control was down during button state change

@item

@geindex BUTTON_ALT (curses モジュール)
@anchor{library/curses curses BUTTON_ALT}@anchor{3485}
@deffn {データ} curses.BUTTON_ALT
@end deffn

@tab

Control was down during button state change

@end multitable



バージョン 3.10 で変更: The @code{BUTTON5_*} constants are now exposed if they are provided by the
underlying curses library.


以下のテーブルは定義済みの色を列挙したものです:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

色

@item

@geindex COLOR_BLACK (curses モジュール)
@anchor{library/curses curses COLOR_BLACK}@anchor{3592}
@deffn {データ} curses.COLOR_BLACK
@end deffn

@tab

黒

@item

@geindex COLOR_BLUE (curses モジュール)
@anchor{library/curses curses COLOR_BLUE}@anchor{3593}
@deffn {データ} curses.COLOR_BLUE
@end deffn

@tab

青

@item

@geindex COLOR_CYAN (curses モジュール)
@anchor{library/curses curses COLOR_CYAN}@anchor{3594}
@deffn {データ} curses.COLOR_CYAN
@end deffn

@tab

シアン (薄く緑がかった青)

@item

@geindex COLOR_GREEN (curses モジュール)
@anchor{library/curses curses COLOR_GREEN}@anchor{3595}
@deffn {データ} curses.COLOR_GREEN
@end deffn

@tab

緑

@item

@geindex COLOR_MAGENTA (curses モジュール)
@anchor{library/curses curses COLOR_MAGENTA}@anchor{3596}
@deffn {データ} curses.COLOR_MAGENTA
@end deffn

@tab

マゼンタ (紫がかった赤)

@item

@geindex COLOR_RED (curses モジュール)
@anchor{library/curses curses COLOR_RED}@anchor{3597}
@deffn {データ} curses.COLOR_RED
@end deffn

@tab

赤

@item

@geindex COLOR_WHITE (curses モジュール)
@anchor{library/curses curses COLOR_WHITE}@anchor{3598}
@deffn {データ} curses.COLOR_WHITE
@end deffn

@tab

白

@item

@geindex COLOR_YELLOW (curses モジュール)
@anchor{library/curses curses COLOR_YELLOW}@anchor{3599}
@deffn {データ} curses.COLOR_YELLOW
@end deffn

@tab

黄色

@end multitable


@node curses textpad --- Text input widget for curses programs,curses ascii --- ASCII 文字のユーティリティー,curses --- 文字セル表示のターミナル処理,コマンドラインインターフェースライブラリ
@anchor{library/curses curses-textpad-text-input-widget-for-curses-programs}@anchor{359a}@anchor{library/curses module-curses textpad}@anchor{32}
@subsection @code{curses.textpad} --- Text input widget for curses programs


@geindex module; curses.textpad

The @code{curses.textpad} module provides a @ref{359b,,Textbox} class that handles
elementary text editing in a curses window, supporting a set of keybindings
resembling those of Emacs (thus, also of Netscape Navigator, BBedit 6.x,
FrameMaker, and many other programs).  The module also provides a
rectangle-drawing function useful for framing text boxes or for other purposes.

The module @code{curses.textpad} defines the following function:

@geindex rectangle() (curses.textpad モジュール)
@anchor{library/curses curses textpad rectangle}@anchor{359c}
@deffn {の関数} curses.textpad.rectangle (win, uly, ulx, lry, lrx)

矩形を描画します。最初の引数はウィンドウオブジェクトでなければなりません; 残りの引数はそのウィンドウからの相対座標になります。2 番目および 3 番目の引数は描画すべき矩形の左上角の y および x 座標です; 4 番目および 5 番目の引数は右下角の y および x 座標です。矩形は、VT100/IBM PC におけるフォーム文字を利用できる端末 (xterm やその他のほとんどのソフトウェア端末エミュレータを含む) ではそれを使って描画されます。そうでなければ ASCII 文字のダッシュ、垂直バー、およびプラス記号で描画されます。
@end deffn

@menu
* Textbox オブジェクト:: 

@end menu

@node Textbox オブジェクト,,,curses textpad --- Text input widget for curses programs
@anchor{library/curses curses-textpad-objects}@anchor{359d}@anchor{library/curses textbox-objects}@anchor{359e}
@subsubsection Textbox オブジェクト


以下のような @ref{359b,,Textbox} オブジェクトをインスタンス生成することができます:

@geindex Textbox (curses.textpad のクラス)
@anchor{library/curses curses textpad Textbox}@anchor{359b}
@deffn {クラス} curses.textpad.Textbox (win)

テキストボックスウィジェットオブジェクトを返します。`win' 引数は、テキストボックスを入れるための @ref{1989,,ウィンドウ} オブジェクトでなければなりません。テキストボックスの編集カーソルは、最初はテキストボックスが入っているウィンドウの左上角に配置され、その座標は @code{(0, 0)} です。インスタンスの @ref{359f,,stripspaces}  フラグの初期値はオンに設定されます。

@ref{359b,,Textbox} オブジェクトは以下のメソッドを持ちます:

@geindex edit() (curses.textpad.Textbox のメソッド)
@anchor{library/curses curses textpad Textbox edit}@anchor{35a0}
@deffn {メソッド} edit ([validator])

普段使うことになるエントリポイントです。終了キーストロークの一つが入力されるまで編集キーストロークを受け付けます。`validator' を与える場合、関数でなければなりません。`validator' はキーストロークが入力されるたびにそのキーストロークが引数となって呼び出されます; 返された値に対して、コマンドキーストロークとして解釈が行われます。このメソッドはウィンドウの内容を文字列として返します; ウィンドウ内の空白が含められるかどうかは @ref{359f,,stripspaces} 属性で決められます。
@end deffn

@geindex do_command() (curses.textpad.Textbox のメソッド)
@anchor{library/curses curses textpad Textbox do_command}@anchor{35a1}
@deffn {メソッド} do_command (ch)

単一のコマンドキーストロークを処理します。以下にサポートされている特殊キーストロークを示します:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

キーストローク

@tab

動作

@item

@code{Control}-@code{A}

@tab

ウィンドウの左端に移動します。

@item

@code{Control}-@code{B}

@tab

カーソルを左へ移動し、必要なら前の行に折り返します。

@item

@code{Control}-@code{D}

@tab

カーソル下の文字を削除します。

@item

@code{Control}-@code{E}

@tab

右端 (stripspaces がオフのとき) または行末 (stripspaces がオンのとき) に移動します。

@item

@code{Control}-@code{F}

@tab

カーソルを右に移動し、必要なら次の行に折り返します。

@item

@code{Control}-@code{G}

@tab

ウィンドウを終了し、その内容を返します。

@item

@code{Control}-@code{H}

@tab

逆方向に文字を削除します。

@item

@code{Control}-@code{J}

@tab

ウィンドウが 1 行であれば終了し、そうでなければ新しい行を挿入します。

@item

@code{Control}-@code{K}

@tab

行が空白行ならその行全体を削除し、そうでなければカーソル以降行末までを消去します。

@item

@code{Control}-@code{L}

@tab

スクリーンを更新します。

@item

@code{Control}-@code{N}

@tab

カーソルを下に移動します; 1 行下に移動します。

@item

@code{Control}-@code{O}

@tab

カーソルの場所に空行を 1 行挿入します。

@item

@code{Control}-@code{P}

@tab

カーソルを上に移動します; 1 行上に移動します。

@end multitable


移動操作は、カーソルがウィンドウの縁にあって移動ができない場合には何も行いません。場合によっては、以下のような同義のキーストロークがサポートされています:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

キーストローク

@item

@ref{3513,,KEY_LEFT}

@tab

@code{Control}-@code{B}

@item

@ref{3514,,KEY_RIGHT}

@tab

@code{Control}-@code{F}

@item

@ref{3512,,KEY_UP}

@tab

@code{Control}-@code{P}

@item

@ref{3511,,KEY_DOWN}

@tab

@code{Control}-@code{N}

@item

@ref{3516,,KEY_BACKSPACE}

@tab

@code{Control}-@code{h}

@end multitable


他のキーストロークは、与えられた文字を挿入し、(行折り返し付きで) 右に移動するコマンドとして扱われます。
@end deffn

@geindex gather() (curses.textpad.Textbox のメソッド)
@anchor{library/curses curses textpad Textbox gather}@anchor{35a2}
@deffn {メソッド} gather ()

ウィンドウの内容を文字列として返します; ウィンドウ内の空白が含められるかどうかは @ref{359f,,stripspaces} メンバ変数で決められます。
@end deffn

@geindex stripspaces (curses.textpad.Textbox の属性)
@anchor{library/curses curses textpad Textbox stripspaces}@anchor{359f}
@deffn {の属性} stripspaces

この属性はウィンドウ内の空白領域の解釈方法を制御するためのフラグです。フラグがオンに設定されている場合、各行の末端にある空白領域は無視されます; すなわち、末端空白領域にカーソルが入ると、その場所の代わりに行の末尾にカーソルが移動します。また、末端の空白領域はウィンドウの内容を取得する際に剥ぎ取られます。
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node curses ascii --- ASCII 文字のユーティリティー,curses panel --- curses のためのパネルスタック拡張,curses textpad --- Text input widget for curses programs,コマンドラインインターフェースライブラリ
@anchor{library/curses ascii doc}@anchor{35a3}@anchor{library/curses ascii curses-ascii-utilities-for-ascii-characters}@anchor{35a4}@anchor{library/curses ascii module-curses ascii}@anchor{30}@anchor{library/curses ascii translation-repo}@anchor{35a5}
@subsection @code{curses.ascii} --- ASCII 文字のユーティリティー


@geindex module; curses.ascii

`ソースコード:' Lib/curses/ascii.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/curses/ascii.py}


__________________________________________________________________


The @code{curses.ascii} module supplies name constants for ASCII characters and
functions to test membership in various ASCII character classes.  The constants
supplied are names for control characters as follows:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名前

@tab

意味

@item

@geindex NUL (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii NUL}@anchor{35a6}
@deffn {データ} curses.ascii.NUL
@end deffn

@tab

@item

@geindex SOH (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii SOH}@anchor{35a7}
@deffn {データ} curses.ascii.SOH
@end deffn

@tab

ヘディング開始、コンソール割り込み

@item

@geindex STX (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii STX}@anchor{35a8}
@deffn {データ} curses.ascii.STX
@end deffn

@tab

テキスト開始

@item

@geindex ETX (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ETX}@anchor{35a9}
@deffn {データ} curses.ascii.ETX
@end deffn

@tab

テキスト終了

@item

@geindex EOT (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii EOT}@anchor{35aa}
@deffn {データ} curses.ascii.EOT
@end deffn

@tab

テキスト伝送終了

@item

@geindex ENQ (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ENQ}@anchor{35ab}
@deffn {データ} curses.ascii.ENQ
@end deffn

@tab

問い合わせ、 @ref{35ac,,ACK} フロー制御時に使用

@item

@geindex ACK (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ACK}@anchor{35ac}
@deffn {データ} curses.ascii.ACK
@end deffn

@tab

肯定応答

@item

@geindex BEL (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii BEL}@anchor{35ad}
@deffn {データ} curses.ascii.BEL
@end deffn

@tab

ベル

@item

@geindex BS (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii BS}@anchor{35ae}
@deffn {データ} curses.ascii.BS
@end deffn

@tab

一文字後退

@item

@geindex TAB (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii TAB}@anchor{35af}
@deffn {データ} curses.ascii.TAB
@end deffn

@tab

タブ

@item

@geindex HT (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii HT}@anchor{35b0}
@deffn {データ} curses.ascii.HT
@end deffn

@tab

@ref{35af,,TAB} の別名: "水平タブ"

@item

@geindex LF (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii LF}@anchor{35b1}
@deffn {データ} curses.ascii.LF
@end deffn

@tab

改行

@item

@geindex NL (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii NL}@anchor{35b2}
@deffn {データ} curses.ascii.NL
@end deffn

@tab

@ref{35b1,,LF} の別名: "改行"

@item

@geindex VT (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii VT}@anchor{35b3}
@deffn {データ} curses.ascii.VT
@end deffn

@tab

垂直タブ

@item

@geindex FF (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii FF}@anchor{35b4}
@deffn {データ} curses.ascii.FF
@end deffn

@tab

改頁

@item

@geindex CR (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii CR}@anchor{35b5}
@deffn {データ} curses.ascii.CR
@end deffn

@tab

復帰

@item

@geindex SO (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii SO}@anchor{35b6}
@deffn {データ} curses.ascii.SO
@end deffn

@tab

シフトアウト、他の文字セットの開始

@item

@geindex SI (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii SI}@anchor{35b7}
@deffn {データ} curses.ascii.SI
@end deffn

@tab

シフトイン、標準の文字セットに復帰

@item

@geindex DLE (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii DLE}@anchor{35b8}
@deffn {データ} curses.ascii.DLE
@end deffn

@tab

データリンクでのエスケープ

@item

@geindex DC1 (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii DC1}@anchor{35b9}
@deffn {データ} curses.ascii.DC1
@end deffn

@tab

装置制御 1、フロー制御のための XON

@item

@geindex DC2 (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii DC2}@anchor{35ba}
@deffn {データ} curses.ascii.DC2
@end deffn

@tab

装置制御 2、ブロックモードフロー制御

@item

@geindex DC3 (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii DC3}@anchor{35bb}
@deffn {データ} curses.ascii.DC3
@end deffn

@tab

装置制御 3、フロー制御のための XOFF

@item

@geindex DC4 (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii DC4}@anchor{35bc}
@deffn {データ} curses.ascii.DC4
@end deffn

@tab

装置制御 4

@item

@geindex NAK (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii NAK}@anchor{35bd}
@deffn {データ} curses.ascii.NAK
@end deffn

@tab

否定応答

@item

@geindex SYN (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii SYN}@anchor{35be}
@deffn {データ} curses.ascii.SYN
@end deffn

@tab

同期信号

@item

@geindex ETB (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ETB}@anchor{35bf}
@deffn {データ} curses.ascii.ETB
@end deffn

@tab

ブロック転送終了

@item

@geindex CAN (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii CAN}@anchor{35c0}
@deffn {データ} curses.ascii.CAN
@end deffn

@tab

キャンセル (Cancel)

@item

@geindex EM (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii EM}@anchor{35c1}
@deffn {データ} curses.ascii.EM
@end deffn

@tab

媒体終端

@item

@geindex SUB (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii SUB}@anchor{35c2}
@deffn {データ} curses.ascii.SUB
@end deffn

@tab

代入文字

@item

@geindex ESC (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ESC}@anchor{35c3}
@deffn {データ} curses.ascii.ESC
@end deffn

@tab

エスケープ文字

@item

@geindex FS (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii FS}@anchor{35c4}
@deffn {データ} curses.ascii.FS
@end deffn

@tab

ファイル区切り文字

@item

@geindex GS (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii GS}@anchor{35c5}
@deffn {データ} curses.ascii.GS
@end deffn

@tab

グループ区切り文字

@item

@geindex RS (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii RS}@anchor{35c6}
@deffn {データ} curses.ascii.RS
@end deffn

@tab

レコード区切り文字、ブロックモード終了子

@item

@geindex US (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii US}@anchor{35c7}
@deffn {データ} curses.ascii.US
@end deffn

@tab

単位区切り文字

@item

@geindex SP (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii SP}@anchor{35c8}
@deffn {データ} curses.ascii.SP
@end deffn

@tab

空白文字

@item

@geindex DEL (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii DEL}@anchor{35c9}
@deffn {データ} curses.ascii.DEL
@end deffn

@tab

削除

@end multitable


これらの大部分は、最近は実際に定数の意味通りに使われることがほとんどないので注意してください。これらのニーモニック符号はデジタル計算機より前のテレプリンタにおける慣習から付けられたものです。

このモジュールでは、標準 C ライブラリの関数を雛型とする以下の関数をサポートしています:

@geindex isalnum() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isalnum}@anchor{35ca}
@deffn {の関数} curses.ascii.isalnum (c)

ASCII 英数文字かどうかを調べます; @code{isalpha(c) or isdigit(c)} と等価です。
@end deffn

@geindex isalpha() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isalpha}@anchor{35cb}
@deffn {の関数} curses.ascii.isalpha (c)

ASCII アルファベット文字かどうかを調べます; @code{isupper(c) or islower(c)} と等価です。
@end deffn

@geindex isascii() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isascii}@anchor{35cc}
@deffn {の関数} curses.ascii.isascii (c)

文字が 7 ビット ASCII 文字に合致するかどうかを調べます。
@end deffn

@geindex isblank() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isblank}@anchor{35cd}
@deffn {の関数} curses.ascii.isblank (c)

ASCII 余白文字、すなわち空白または水平タブかどうかを調べます。
@end deffn

@geindex iscntrl() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii iscntrl}@anchor{35ce}
@deffn {の関数} curses.ascii.iscntrl (c)

ASCII 制御文字 (0x00 から 0x1f の範囲または 0x7f) かどうかを調べます。
@end deffn

@geindex isdigit() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isdigit}@anchor{35cf}
@deffn {の関数} curses.ascii.isdigit (c)

ASCII 10 進数字、すなわち @code{'0'} から @code{'9'} までの文字かどうかを調べます。@code{c in string.digits} と等価です。
@end deffn

@geindex isgraph() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isgraph}@anchor{35d0}
@deffn {の関数} curses.ascii.isgraph (c)

空白以外の ASCII 印字可能文字かどうかを調べます。
@end deffn

@geindex islower() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii islower}@anchor{35d1}
@deffn {の関数} curses.ascii.islower (c)

ASCII 小文字かどうかを調べます。
@end deffn

@geindex isprint() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isprint}@anchor{35d2}
@deffn {の関数} curses.ascii.isprint (c)

空白文字を含め、ASCII 印字可能文字かどうかを調べます。
@end deffn

@geindex ispunct() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ispunct}@anchor{35d3}
@deffn {の関数} curses.ascii.ispunct (c)

空白または英数字以外の ASCII 印字可能文字かどうかを調べます。
@end deffn

@geindex isspace() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isspace}@anchor{35d4}
@deffn {の関数} curses.ascii.isspace (c)

ASCII 余白文字、すなわち空白、改行、復帰、改頁、水平タブ、垂直タブかどうかを調べます。
@end deffn

@geindex isupper() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isupper}@anchor{35d5}
@deffn {の関数} curses.ascii.isupper (c)

ASCII 大文字かどうかを調べます。
@end deffn

@geindex isxdigit() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isxdigit}@anchor{35d6}
@deffn {の関数} curses.ascii.isxdigit (c)

ASCII 16 進数字かどうかを調べます。@code{c in string.hexdigits} と等価です。
@end deffn

@geindex isctrl() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii isctrl}@anchor{35d7}
@deffn {の関数} curses.ascii.isctrl (c)

ASCII 制御文字 (0 から 31 までの値) かどうかを調べます。
@end deffn

@geindex ismeta() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ismeta}@anchor{35d8}
@deffn {の関数} curses.ascii.ismeta (c)

非 ASCII 文字 (0x80 またはそれ以上の値) かどうかを調べます。
@end deffn

これらの関数は数字も 1 文字の文字列も使えます; 引数を文字列にした場合、組み込み関数 @ref{233b,,ord()} を使って変換されます。

これらの関数は全て、関数に渡した文字列の文字から得られたビット値を調べるので注意してください; 関数はホスト計算機で使われている文字列エンコーディングについて何ら関知しません。

以下の 2 つの関数は、引数として 1 文字の文字列または整数で表したバイト値のどちらでもとり得ます; これらの関数は引数と同じ型で値を返します。

@geindex ascii() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ascii}@anchor{35d9}
@deffn {の関数} curses.ascii.ascii (c)

ASCII 値を返します。`c' の下位 7 ビットに対応します。
@end deffn

@geindex ctrl() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii ctrl}@anchor{35da}
@deffn {の関数} curses.ascii.ctrl (c)

与えた文字に対応する制御文字を返します (0x1f とビット単位で論理積を取ります)。
@end deffn

@geindex alt() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii alt}@anchor{35db}
@deffn {の関数} curses.ascii.alt (c)

与えた文字に対応する 8 ビット文字を返します (0x80 とビット単位で論理和を取ります)。
@end deffn

以下の関数は 1 文字からなる文字列値または整数値を引数に取り、文字列を返します。

@geindex ^ (キャレット);curses モジュール内
@geindex ! (エクスクラメーション);curses モジュール内

@geindex unctrl() (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii unctrl}@anchor{35dc}
@deffn {の関数} curses.ascii.unctrl (c)

ASCII 文字 `c' の文字列表現を返します。
もし `c' が印字可能文字であれば、返される文字列は `c' そのものになります。
もし `c' が制御文字 (0x00--0x1f) であれば、キャレット (@code{'^'}) と、その後ろに続く `c' に対応した大文字からなる文字列になります。
`c' が ASCII 削除文字 (0x7f) であれば、文字列は @code{'^?'} になります。
`c' のメタビット (0x80) がセットされていれば、メタビットは取り去られ、前述のルールが適用され、@code{'!'} が前につけられます。
@end deffn

@geindex controlnames (curses.ascii モジュール)
@anchor{library/curses ascii curses ascii controlnames}@anchor{35dd}
@deffn {データ} curses.ascii.controlnames

0 (NUL) から 0x1f (US) までの 32 の ASCII 制御文字と、空白文字 @code{SP} のニーモニック符号名からなる 33 要素の文字列によるシーケンスです。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node curses panel --- curses のためのパネルスタック拡張,cmd --- 行指向のコマンドインタープリターのサポート,curses ascii --- ASCII 文字のユーティリティー,コマンドラインインターフェースライブラリ
@anchor{library/curses panel doc}@anchor{35de}@anchor{library/curses panel curses-panel-a-panel-stack-extension-for-curses}@anchor{35df}@anchor{library/curses panel module-curses panel}@anchor{31}@anchor{library/curses panel translation-repo}@anchor{35e0}
@subsection @code{curses.panel} --- curses のためのパネルスタック拡張


@geindex module; curses.panel


__________________________________________________________________


パネルは深さ (depth) の機能が追加されたウィンドウです。これにより、ウィンドウをお互いに重ね合わせることができ、各ウィンドウの可視部分だけが表示されます。パネルはスタック中に追加したり、スタック内で上下移動させたり、スタックから除去することができます。

@menu
* 関数: 関数<7>. 
* Panel オブジェクト:: 

@end menu

@node 関数<7>,Panel オブジェクト,,curses panel --- curses のためのパネルスタック拡張
@anchor{library/curses panel cursespanel-functions}@anchor{35e1}@anchor{library/curses panel functions}@anchor{35e2}
@subsubsection 関数


The module @code{curses.panel} defines the following functions:

@geindex bottom_panel() (curses.panel モジュール)
@anchor{library/curses panel curses panel bottom_panel}@anchor{35e3}
@deffn {の関数} curses.panel.bottom_panel ()

パネルスタックの最下層のパネルを返します。
@end deffn

@geindex new_panel() (curses.panel モジュール)
@anchor{library/curses panel curses panel new_panel}@anchor{35e4}
@deffn {の関数} curses.panel.new_panel (win)

与えられたウィンドウ `win' に関連付けられたパネルオブジェクトを返します。返されたパネルオブジェクトを参照しておく必要があることに注意してください。もし参照しなければ、パネルオブジェクトはガベージコレクションされてパネルスタックから削除されます。
@end deffn

@geindex top_panel() (curses.panel モジュール)
@anchor{library/curses panel curses panel top_panel}@anchor{35e5}
@deffn {の関数} curses.panel.top_panel ()

パネルスタックの最上層のパネルを返します。
@end deffn

@geindex update_panels() (curses.panel モジュール)
@anchor{library/curses panel curses panel update_panels}@anchor{35e6}
@deffn {の関数} curses.panel.update_panels ()

仮想スクリーンをパネルスタック変更後の状態に更新します。この関数では @ref{3473,,curses.doupdate()} を呼ばないので、ユーザは自分で呼び出す必要があります。
@end deffn

@node Panel オブジェクト,,関数<7>,curses panel --- curses のためのパネルスタック拡張
@anchor{library/curses panel curses-panel-objects}@anchor{35e7}@anchor{library/curses panel panel-objects}@anchor{35e8}
@subsubsection Panel オブジェクト


上記の @ref{35e4,,new_panel()} が返す Panel オブジェクトはスタック順の概念を持つウィンドウです。ウィンドウはパネルに関連付けられており、表示する内容を決定している一方、パネルのメソッドはパネルスタック中のウィンドウの深さ管理を担います。

Panel オブジェクトは以下のメソッドを持っています:

@geindex above() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel above}@anchor{35e9}
@deffn {メソッド} Panel.above ()

現在のパネルの上にあるパネルを返します。
@end deffn

@geindex below() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel below}@anchor{35ea}
@deffn {メソッド} Panel.below ()

現在のパネルの下にあるパネルを返します。
@end deffn

@geindex bottom() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel bottom}@anchor{35eb}
@deffn {メソッド} Panel.bottom ()

パネルをスタックの最下層にプッシュします。
@end deffn

@geindex hidden() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel hidden}@anchor{35ec}
@deffn {メソッド} Panel.hidden ()

パネルが隠れている (不可視である) 場合に @code{True} を返し、そうでない場合 @code{False} を返します。
@end deffn

@geindex hide() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel hide}@anchor{35ed}
@deffn {メソッド} Panel.hide ()

パネルを隠します。この操作ではオブジェクトは消去されず、スクリーン上のウィンドウを不可視にするだけです。
@end deffn

@geindex move() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel move}@anchor{35ee}
@deffn {メソッド} Panel.move (y, x)

パネルをスクリーン座標 @code{(y, x)} に移動します。
@end deffn

@geindex replace() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel replace}@anchor{35ef}
@deffn {メソッド} Panel.replace (win)

パネルに関連付けられたウィンドウを `win' に変更します。
@end deffn

@geindex set_userptr() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel set_userptr}@anchor{35f0}
@deffn {メソッド} Panel.set_userptr (obj)

パネルのユーザポインタを `obj' に設定します。このメソッドは任意のデータをパネルに関連付けるために使われ、任意の Python オブジェクトにすることができます。
@end deffn

@geindex show() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel show}@anchor{35f1}
@deffn {メソッド} Panel.show ()

(隠れているはずの) パネルを表示します。
@end deffn

@geindex top() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel top}@anchor{35f2}
@deffn {メソッド} Panel.top ()

パネルをスタックの最上層にプッシュします。
@end deffn

@geindex userptr() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel userptr}@anchor{35f3}
@deffn {メソッド} Panel.userptr ()

パネルのユーザポインタを返します。任意の Python オブジェクトです。
@end deffn

@geindex window() (curses.panel.Panel のメソッド)
@anchor{library/curses panel curses panel Panel window}@anchor{35f4}
@deffn {メソッド} Panel.window ()

パネルに関連付けられているウィンドウオブジェクトを返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node cmd --- 行指向のコマンドインタープリターのサポート,,curses panel --- curses のためのパネルスタック拡張,コマンドラインインターフェースライブラリ
@anchor{library/cmd doc}@anchor{35f5}@anchor{library/cmd cmd-support-for-line-oriented-command-interpreters}@anchor{35f6}@anchor{library/cmd module-cmd}@anchor{1a}@anchor{library/cmd translation-repo}@anchor{35f7}
@subsection @code{cmd} --- 行指向のコマンドインタープリターのサポート


@geindex module; cmd

`ソースコード:' Lib/cmd.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/cmd.py}


__________________________________________________________________


@ref{184e,,Cmd} クラスでは、行指向のコマンドインタープリタを書くための簡単なフレームワークを提供します。テストハーネスや管理ツール、そして、後により洗練されたインターフェイスでラップするプロトタイプとして、こうしたインタープリタはよく役に立ちます。

@geindex Cmd (cmd のクラス)
@anchor{library/cmd cmd Cmd}@anchor{184e}
@deffn {クラス} cmd.Cmd (completekey='tab', stdin=None, stdout=None)

@ref{184e,,Cmd} インスタンス、あるいはサブクラスのインスタンスは、行指向のインタープリタ・フレームワークです。 @ref{184e,,Cmd} 自身をインスタンス化することはありません。むしろ、 @ref{184e,,Cmd} のメソッドを継承したり、アクションメソッドをカプセル化するために、あなたが自分で定義するインタープリタクラスのスーパークラスとしての便利です。

オプション引数 `completekey' は、補完キーの @ref{bf,,readline} 名です。デフォルトは @code{Tab} です。 `completekey' が @ref{885,,None} でなく、 @ref{bf,,readline} が利用できるならば、コマンド補完は自動的に行われます。

The default, @code{'tab'}, is treated specially, so that it refers to the
@code{Tab} key on every @ref{1a27,,readline.backend}.
Specifically, if @ref{1a27,,readline.backend} is @code{editline},
@code{Cmd} will use @code{'^I'} instead of @code{'tab'}.
Note that other values are not treated this way, and might only work
with a specific backend.

オプション引数の `stdin' と `stdout' には、Cmd またはそのサブクラスのインスタンスが入出力に使用するファイルオブジェクトを指定します。省略時には @ref{75f,,sys.stdin} と @ref{ccd,,sys.stdout} が使用されます。

引数に渡した `stdin' を使いたい場合は、インスタンスの @ref{35f8,,use_rawinput} 属性を @code{False} にセットしてください。そうしないと `stdin' は無視されます。


バージョン 3.13 で変更: @code{completekey='tab'} is replaced by @code{'^I'} for @code{editline}.

@end deffn

@menu
* Cmdオブジェクト:: 
* Cmd の例:: 

@end menu

@node Cmdオブジェクト,Cmd の例,,cmd --- 行指向のコマンドインタープリターのサポート
@anchor{library/cmd cmd-objects}@anchor{35f9}@anchor{library/cmd id1}@anchor{35fa}
@subsubsection Cmdオブジェクト


@ref{184e,,Cmd} インスタンスは、次のメソッドを持ちます:

@geindex cmdloop() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd cmdloop}@anchor{35fb}
@deffn {メソッド} Cmd.cmdloop (intro=None)

プロンプトを繰り返し出力し、入力を受け取り、受け取った入力から取り去った先頭の語を解析し、その行の残りを引数としてアクションメソッドへディスパッチします。

オプションの引数は、最初のプロンプトの前に表示されるバナーあるいはイントロ用の文字列です (これはクラス属性 @ref{35fc,,intro} をオーバーライドします)。

@ref{bf,,readline} モジュールがロードされているなら、入力は自動的に @code{bash} のような履歴リスト編集機能を受け継ぎます(例えば、 @code{Control}-@code{P} は直前のコマンドへのスクロールバック、 @code{Control}-@code{N} は次のものへ進む、 @code{Control}-@code{F} はカーソルを右へ非破壊的に進める、 @code{Control}-@code{B} はカーソルを非破壊的に左へ移動させる等)。

入力のファイル終端は、文字列 @code{'EOF'} として渡されます。

@geindex ? (クエスチョンマーク);in a command interpreter
@geindex ! (エクスクラメーション);in a command interpreter

An interpreter instance will recognize a command name @code{foo} if and only if it
has a method @code{do_foo()}.  As a special case, a line beginning with the
character @code{'?'} is dispatched to the method @ref{1a2b,,do_help()}.  As another
special case, a line beginning with the character @code{'!'} is dispatched to the
method @code{do_shell()} (if such a method is defined).

This method will return when the @ref{35fd,,postcmd()} method returns a true value.
The `stop' argument to @ref{35fd,,postcmd()} is the return value from the command's
corresponding @code{do_*()} method.

If completion is enabled, completing commands will be done automatically, and
completing of commands args is done by calling @code{complete_foo()} with
arguments `text', `line', `begidx', and `endidx'.  `text' is the string prefix
we are attempting to match: all returned matches must begin with it. `line' is
the current input line with leading whitespace removed, `begidx' and `endidx'
are the beginning and ending indexes of the prefix text, which could be used to
provide different completion depending upon which position the argument is in.
@end deffn

@geindex do_help() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd do_help}@anchor{1a2b}
@deffn {メソッド} Cmd.do_help (arg)

All subclasses of @ref{184e,,Cmd} inherit a predefined @code{do_help()}.  This
method, called with an argument @code{'bar'}, invokes the corresponding method
@code{help_bar()}, and if that is not present, prints the docstring of
@code{do_bar()}, if available.  With no argument, @code{do_help()} lists all
available help topics (that is, all commands with corresponding
@code{help_*()} methods or commands that have docstrings), and also lists any
undocumented commands.
@end deffn

@geindex onecmd() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd onecmd}@anchor{35fe}
@deffn {メソッド} Cmd.onecmd (str)

Interpret the argument as though it had been typed in response to the prompt.
This may be overridden, but should not normally need to be; see the
@ref{35ff,,precmd()} and @ref{35fd,,postcmd()} methods for useful execution hooks.  The
return value is a flag indicating whether interpretation of commands by the
interpreter should stop.  If there is a @code{do_*()} method for the command
`str', the return value of that method is returned, otherwise the return value
from the @ref{3600,,default()} method is returned.
@end deffn

@geindex emptyline() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd emptyline}@anchor{3601}
@deffn {メソッド} Cmd.emptyline ()

プロンプトに空行が入力されたときに呼び出されるメソッド。このメソッドがオーバーライドされていないなら、最後に入力された空行でないコマンドが繰り返されます。
@end deffn

@geindex default() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd default}@anchor{3600}
@deffn {メソッド} Cmd.default (line)

コマンドの先頭の語が認識されないときに、入力行に対して呼び出されます。このメソッドがオーバーライドされていないなら、エラーメッセージを表示して戻ります。
@end deffn

@geindex completedefault() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd completedefault}@anchor{3602}
@deffn {メソッド} Cmd.completedefault (text, line, begidx, endidx)

Method called to complete an input line when no command-specific
@code{complete_*()} method is available.  By default, it returns an empty list.
@end deffn

@geindex columnize() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd columnize}@anchor{1c09}
@deffn {メソッド} Cmd.columnize (list, displaywidth=80)

Method called to display a list of strings as a compact set of columns.
Each column is only as wide as necessary.
Columns are separated by two spaces for readability.
@end deffn

@geindex precmd() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd precmd}@anchor{35ff}
@deffn {メソッド} Cmd.precmd (line)

コマンド行 `line' が解釈実行される直前、しかし入力プロンプトが作られ表示された後に実行されるフックメソッド。このメソッドは @ref{184e,,Cmd} 内のスタブであって、サブクラスでオーバーライドされるために存在します。戻り値は @ref{35fe,,onecmd()} メソッドが実行するコマンドとして使われます。 @ref{35ff,,precmd()} の実装では、コマンドを書き換えるかもしれないし、あるいは単に変更していない `line' を返すかもしれません。
@end deffn

@geindex postcmd() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd postcmd}@anchor{35fd}
@deffn {メソッド} Cmd.postcmd (stop, line)

コマンドディスパッチが終わった直後に実行されるフックメソッド。このメソッドは @ref{184e,,Cmd} 内のスタブで、サブクラスでオーバーライドされるために存在します。 `line' は実行されたコマンド行で、 `stop' は @ref{35fd,,postcmd()} の呼び出しの後に実行を停止するかどうかを示すフラグです。これは @ref{35fe,,onecmd()} メソッドの戻り値です。このメソッドの戻り値は、 `stop' に対応する内部フラグの新しい値として使われます。偽を返すと、実行を続けます。
@end deffn

@geindex preloop() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd preloop}@anchor{3603}
@deffn {メソッド} Cmd.preloop ()

@ref{35fb,,cmdloop()} が呼び出されたときに一度だけ実行されるフックメソッド。このメソッドは @ref{184e,,Cmd} 内のスタブであって、サブクラスでオーバーライドされるために存在します。
@end deffn

@geindex postloop() (cmd.Cmd のメソッド)
@anchor{library/cmd cmd Cmd postloop}@anchor{3604}
@deffn {メソッド} Cmd.postloop ()

@ref{35fb,,cmdloop()} が戻る直前に一度だけ実行されるフックメソッド。このメソッドは @ref{184e,,Cmd} 内のスタブであって、サブクラスでオーバーライドされるために存在します。
@end deffn

@ref{184e,,Cmd} のサブクラスのインスタンスは、公開されたインスタンス変数をいくつか持っています:

@geindex prompt (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd prompt}@anchor{3605}
@deffn {の属性} Cmd.prompt

入力を求めるために表示されるプロンプト。
@end deffn

@geindex identchars (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd identchars}@anchor{3606}
@deffn {の属性} Cmd.identchars

コマンドの先頭の語として受け入れられる文字の文字列。
@end deffn

@geindex lastcmd (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd lastcmd}@anchor{3607}
@deffn {の属性} Cmd.lastcmd

最後の空でないコマンド接頭辞。
@end deffn

@geindex cmdqueue (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd cmdqueue}@anchor{3608}
@deffn {の属性} Cmd.cmdqueue

キューに入れられた入力行のリスト。cmdqueue リストは新たな入力が必要な際に @ref{35fb,,cmdloop()} 内でチェックされます; これが空でない場合、その要素は、あたかもプロンプトから入力されたかのように順に処理されます。
@end deffn

@geindex intro (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd intro}@anchor{35fc}
@deffn {の属性} Cmd.intro

イントロあるいはバナーとして表示される文字列。 @ref{35fb,,cmdloop()} メソッドに引数を与えるために、オーバーライドされるかもしれません。
@end deffn

@geindex doc_header (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd doc_header}@anchor{3609}
@deffn {の属性} Cmd.doc_header

ヘルプ出力に文書化されたコマンドのセクションがある場合に表示するヘッダ。
@end deffn

@geindex misc_header (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd misc_header}@anchor{360a}
@deffn {の属性} Cmd.misc_header

The header to issue if the help output has a section for miscellaneous  help
topics (that is, there are @code{help_*()} methods without corresponding
@code{do_*()} methods).
@end deffn

@geindex undoc_header (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd undoc_header}@anchor{360b}
@deffn {の属性} Cmd.undoc_header

The header to issue if the help output has a section for undocumented  commands
(that is, there are @code{do_*()} methods without corresponding @code{help_*()}
methods).
@end deffn

@geindex ruler (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd ruler}@anchor{360c}
@deffn {の属性} Cmd.ruler

ヘルプメッセージのヘッダの下に、区切り行を表示するために使われる文字。空のときは、ルーラ行が表示されません。デフォルトでは、@code{'='} です。
@end deffn

@geindex use_rawinput (cmd.Cmd の属性)
@anchor{library/cmd cmd Cmd use_rawinput}@anchor{35f8}
@deffn {の属性} Cmd.use_rawinput

A flag, defaulting to true.  If true, @ref{35fb,,cmdloop()} uses @ref{14f0,,input()} to
display a prompt and read the next command; if false, @ref{ccd,,sys.stdout.write()}
and @ref{75f,,sys.stdin.readline()} are used. (This means that by importing
@ref{bf,,readline}, on systems that support it, the interpreter will automatically
support @code{Emacs}-like line editing  and command-history keystrokes.)
@end deffn

@node Cmd の例,,Cmdオブジェクト,cmd --- 行指向のコマンドインタープリターのサポート
@anchor{library/cmd cmd-example}@anchor{360d}@anchor{library/cmd id2}@anchor{360e}
@subsubsection Cmd の例


The @code{cmd} module is mainly useful for building custom shells that let a
user work with a program interactively.

この節では、@ref{107,,turtle} モジュールのいくつかのコマンドを持ったシェルの作成方法の簡単な例を示します。

Basic turtle commands such as @ref{360f,,forward()} are added to a
@ref{184e,,Cmd} subclass with method named @code{do_forward()}.  The argument is
converted to a number and dispatched to the turtle module.  The docstring is
used in the help utility provided by the shell.

The example also includes a basic record and playback facility implemented with
the @ref{35ff,,precmd()} method which is responsible for converting the input to
lowercase and writing the commands to a file.  The @code{do_playback()} method
reads the file and adds the recorded commands to the @ref{3608,,cmdqueue} for
immediate playback:

@example
import cmd, sys
from turtle import *

class TurtleShell(cmd.Cmd):
    intro = 'Welcome to the turtle shell.   Type help or ? to list commands.\n'
    prompt = '(turtle) '
    file = None

    # ----- basic turtle commands -----
    def do_forward(self, arg):
        'Move the turtle forward by the specified distance:  FORWARD 10'
        forward(*parse(arg))
    def do_right(self, arg):
        'Turn turtle right by given number of degrees:  RIGHT 20'
        right(*parse(arg))
    def do_left(self, arg):
        'Turn turtle left by given number of degrees:  LEFT 90'
        left(*parse(arg))
    def do_goto(self, arg):
        'Move turtle to an absolute position with changing orientation.  GOTO 100 200'
        goto(*parse(arg))
    def do_home(self, arg):
        'Return turtle to the home position:  HOME'
        home()
    def do_circle(self, arg):
        'Draw circle with given radius an options extent and steps:  CIRCLE 50'
        circle(*parse(arg))
    def do_position(self, arg):
        'Print the current turtle position:  POSITION'
        print('Current position is %d %d\n' % position())
    def do_heading(self, arg):
        'Print the current turtle heading in degrees:  HEADING'
        print('Current heading is %d\n' % (heading(),))
    def do_color(self, arg):
        'Set the color:  COLOR BLUE'
        color(arg.lower())
    def do_undo(self, arg):
        'Undo (repeatedly) the last turtle action(s):  UNDO'
    def do_reset(self, arg):
        'Clear the screen and return turtle to center:  RESET'
        reset()
    def do_bye(self, arg):
        'Stop recording, close the turtle window, and exit:  BYE'
        print('Thank you for using Turtle')
        self.close()
        bye()
        return True

    # ----- record and playback -----
    def do_record(self, arg):
        'Save future commands to filename:  RECORD rose.cmd'
        self.file = open(arg, 'w')
    def do_playback(self, arg):
        'Playback commands from a file:  PLAYBACK rose.cmd'
        self.close()
        with open(arg) as f:
            self.cmdqueue.extend(f.read().splitlines())
    def precmd(self, line):
        line = line.lower()
        if self.file and 'playback' not in line:
            print(line, file=self.file)
        return line
    def close(self):
        if self.file:
            self.file.close()
            self.file = None

def parse(arg):
    'Convert a series of zero or more numbers to an argument tuple'
    return tuple(map(int, arg.split()))

if __name__ == '__main__':
    TurtleShell().cmdloop()
@end example

以下は、turtle シェルでの機能のヘルプ表示、空行によるコマンドの繰り返し、単純な記録と再実行のセッション例です:

@example
Welcome to the turtle shell.   Type help or ? to list commands.

(turtle) ?

Documented commands (type help <topic>):
========================================
bye     color    goto     home  playback  record  right
circle  forward  heading  left  position  reset   undo

(turtle) help forward
Move the turtle forward by the specified distance:  FORWARD 10
(turtle) record spiral.cmd
(turtle) position
Current position is 0 0

(turtle) heading
Current heading is 0

(turtle) reset
(turtle) circle 20
(turtle) right 30
(turtle) circle 40
(turtle) right 30
(turtle) circle 60
(turtle) right 30
(turtle) circle 80
(turtle) right 30
(turtle) circle 100
(turtle) right 30
(turtle) circle 120
(turtle) right 30
(turtle) circle 120
(turtle) heading
Current heading is 180

(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 500
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 300
(turtle) playback spiral.cmd
Current position is 0 0

Current heading is 0

Current heading is 180

(turtle) bye
Thank you for using Turtle
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 並行実行,ネットワーク通信とプロセス間通信,コマンドラインインターフェースライブラリ,Python 標準ライブラリ
@anchor{library/concurrency doc}@anchor{3610}@anchor{library/concurrency concurrency}@anchor{3611}@anchor{library/concurrency concurrent-execution}@anchor{3612}@anchor{library/concurrency translation-repo}@anchor{3613}
@section 並行実行


この章で記述されているモジュールは、コードの並行実行のサポートを提供します。ツールの適切な選択は、実行されるタスク(IO bound vs CPU bound) や推奨される開発スタイル (イベントドリブンな協調的マルチタスク vs プリエンプティブマルチタスク) に依存します。ここに概観を示します:

@menu
* threading: threading --- スレッドベースの並列処理. スレッドベースの並列処理
* multiprocessing: multiprocessing --- プロセスベースの並列処理. プロセスベースの並列処理
* multiprocessing.shared_memory: multiprocessing shared_memory --- プロセス間で直接アクセス可能な共有メモリ. プロセス間で直接アクセス可能な共有メモリ
* concurrent パッケージ:: 
* concurrent.futures: concurrent futures --- 並列タスク実行. 並列タスク実行
* concurrent.interpreters: concurrent interpreters --- Multiple interpreters in the same process. Multiple interpreters in the same process
* subprocess: subprocess --- サブプロセス管理. サブプロセス管理
* sched: sched --- イベントスケジューラー. イベントスケジューラー
* queue: queue --- 同期キュークラス. 同期キュークラス
* contextvars: contextvars --- コンテキスト変数. コンテキスト変数
* _thread: _thread --- 低水準なスレッド API. 低水準なスレッド API

@end menu

@node threading --- スレッドベースの並列処理,multiprocessing --- プロセスベースの並列処理,,並行実行
@anchor{library/threading doc}@anchor{3614}@anchor{library/threading module-threading}@anchor{f3}@anchor{library/threading threading-thread-based-parallelism}@anchor{3615}
@subsection @code{threading} --- スレッドベースの並列処理


@geindex module; threading

`ソースコード:' Lib/threading.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/threading.py}


__________________________________________________________________


このモジュールでは、高水準のスレッドインターフェースをより低水準 な @ref{2,,_thread} モジュールの上に構築しています。

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@menu
* はじめに: はじめに<8>. 
* GIL and performance considerations:: 
* リファレンス: リファレンス<2>. 
* with 文でのロック・条件変数・セマフォの使い方:: 

@end menu

@node はじめに<8>,GIL and performance considerations,,threading --- スレッドベースの並列処理
@anchor{library/threading introduction}@anchor{3616}
@subsubsection はじめに


The @code{threading} module provides a way to run multiple threads@footnote{https://en.wikipedia.org/wiki/Thread_(computing)} (smaller
units of a process) concurrently within a single process. It allows for the
creation and management of threads, making it possible to execute tasks in
parallel, sharing memory space. Threads are particularly useful when tasks are
I/O bound, such as file operations or making network requests,
where much of the time is spent waiting for external resources.

A typical use case for @code{threading} includes managing a pool of worker
threads that can process multiple tasks concurrently.  Here's a basic example of
creating and starting threads using @ref{176,,Thread}:

@example
import threading
import time

def crawl(link, delay=3):
    print(f"crawl started for @{link@}")
    time.sleep(delay)  # Blocking I/O (simulating a network request)
    print(f"crawl ended for @{link@}")

links = [
    "https://python.org",
    "https://docs.python.org",
    "https://peps.python.org",
]

# Start threads for each link
threads = []
for link in links:
    # Using `args` to pass positional arguments and `kwargs` for keyword arguments
    t = threading.Thread(target=crawl, args=(link,), kwargs=@{"delay": 2@})
    threads.append(t)

# Start each thread
for t in threads:
    t.start()

# Wait for all threads to finish
for t in threads:
    t.join()
@end example


バージョン 3.7 で変更: このモジュールは以前はオプションでしたが、常に利用可能なモジュールとなりました。



@subsubheading 参考


@ref{949,,concurrent.futures.ThreadPoolExecutor} offers a higher level interface
to push tasks to a background thread without blocking execution of the
calling thread, while still being able to retrieve their results when needed.

@ref{bb,,queue} provides a thread-safe interface for exchanging data between
running threads.

@ref{b,,asyncio} offers an alternative approach to achieving task level
concurrency without requiring the use of multiple operating system threads.


@cartouche
@quotation 注釈 
In the Python 2.x series, this module contained @code{camelCase} names
for some methods and functions. These are deprecated as of Python 3.10,
but they are still supported for compatibility with Python 2.5 and lower.
@end quotation
@end cartouche

CPython は @ref{474,,Global Interpreter Lock} のため、ある時点で Python コードを実行できるスレッドは1つに限られます (ただし、いくつかのパフォーマンスが強く求められるライブラリはこの制限を克服しています)。アプリケーションにマルチコアマシンの計算能力をより良く利用させたい場合は、 @ref{98,,multiprocessing} モジュールや @ref{1d6,,concurrent.futures.ProcessPoolExecutor} の利用をお勧めします。 ただし、I/Oバウンドなタスクを並行して複数走らせたい場合においては、 マルチスレッドは正しい選択肢です。

@node GIL and performance considerations,リファレンス<2>,はじめに<8>,threading --- スレッドベースの並列処理
@anchor{library/threading gil-and-performance-considerations}@anchor{3617}
@subsubsection GIL and performance considerations


Unlike the @ref{98,,multiprocessing} module, which uses separate processes to
bypass the @ref{474,,global interpreter lock} (GIL), the threading module operates
within a single process, meaning that all threads share the same memory space.
However, the GIL limits the performance gains of threading when it comes to
CPU-bound tasks, as only one thread can execute Python bytecode at a time.
Despite this, threads remain a useful tool for achieving concurrency in many
scenarios.

As of Python 3.13, @ref{1f4,,free-threaded} builds
can disable the GIL, enabling true parallel execution of threads, but this
feature is not available by default (see 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}).

@c TODO: At some point this feature will become available by default.

@node リファレンス<2>,with 文でのロック・条件変数・セマフォの使い方,GIL and performance considerations,threading --- スレッドベースの並列処理
@anchor{library/threading reference}@anchor{3618}
@subsubsection リファレンス


このモジュールは以下の関数を定義しています:

@geindex active_count() (threading モジュール)
@anchor{library/threading threading active_count}@anchor{35f}
@deffn {の関数} threading.active_count ()

生存中の @ref{176,,Thread} オブジェクトの数を返します。この数は @ref{1c5a,,enumerate()} の返すリストの長さと同じです。

関数`@w{`}activeCount`@w{`}はこの関数の非推奨エイリアスです。
@end deffn

@geindex current_thread() (threading モジュール)
@anchor{library/threading threading current_thread}@anchor{35e}
@deffn {の関数} threading.current_thread ()

Return the current @ref{176,,Thread} object, corresponding to the caller's thread
of control.  If the caller's thread of control was not created through the
@code{threading} module, a dummy thread object with limited functionality is
returned.

関数`@w{`}currentThread`@w{`}はこの関数の非推奨エイリアスです。
@end deffn

@geindex excepthook() (threading モジュール)
@anchor{library/threading threading excepthook}@anchor{a4b}
@deffn {の関数} threading.excepthook (args, /)

@ref{c31,,Thread.run()} で発生したキャッチされない例外を処理する。

(実) 引数*args*は以下の属性をもちます:


@itemize *

@item 
`exc_type': 例外の型

@item 
`exc_value': 例外の値、@code{None} の可能性がある。

@item 
`exc_traceback': Exception traceback, can be @code{None}.

@item 
`thread': Thread which raised the exception, can be @code{None}.
@end itemize

If `exc_type' is @ref{f3c,,SystemExit}, the exception is silently ignored.
Otherwise, the exception is printed out on @ref{b33,,sys.stderr}.

If  this function raises an exception, @ref{a0c,,sys.excepthook()} is called to
handle it.

@ref{a4b,,threading.excepthook()} can be overridden to control how uncaught
exceptions raised by @ref{c31,,Thread.run()} are handled.

Storing `exc_value' using a custom hook can create a reference cycle. It
should be cleared explicitly to break the reference cycle when the
exception is no longer needed.

Storing `thread' using a custom hook can resurrect it if it is set to an
object which is being finalized. Avoid storing `thread' after the custom
hook completes to avoid resurrecting objects.


@subsubheading 参考


@ref{a0c,,sys.excepthook()} handles uncaught exceptions.



Added in version 3.8.

@end deffn

@geindex __excepthook__ (threading モジュール)
@anchor{library/threading threading __excepthook__}@anchor{a4a}
@deffn {データ} threading.__excepthook__

Holds the original value of @ref{a4b,,threading.excepthook()}. It is saved so that the
original value can be restored in case they happen to get replaced with
broken or alternative objects.


Added in version 3.10.

@end deffn

@geindex get_ident() (threading モジュール)
@anchor{library/threading threading get_ident}@anchor{1372}
@deffn {の関数} threading.get_ident ()

現在のスレッドの 'スレッドID' を返します。非ゼロの整数です。この値は直接の意味を持っていません; 例えばスレッド特有のデータの辞書に索引をつけるためのような、マジッククッキーとして意図されています。スレッドが終了し、他のスレッドが作られたとき、スレッド ID は再利用されるかもしれません。


Added in version 3.3.

@end deffn

@geindex get_native_id() (threading モジュール)
@anchor{library/threading threading get_native_id}@anchor{c32}
@deffn {の関数} threading.get_native_id ()

Return the native integral Thread ID of the current thread assigned by the kernel.
This is a non-negative integer.
Its value may be used to uniquely identify this particular thread system-wide
(until the thread terminates, after which the value may be recycled by the OS).

@ref{213f,,Availability}: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD.


Added in version 3.8.



バージョン 3.13 で変更: Added support for GNU/kFreeBSD.

@end deffn

@geindex enumerate() (threading モジュール)
@anchor{library/threading threading enumerate}@anchor{1c5a}
@deffn {の関数} threading.enumerate ()

現在、アクティブな @ref{176,,Thread} オブジェクト全てのリストを返します。リストには、デーモンスレッド (daemonic thread)、 @ref{35e,,current_thread()} の生成するダミースレッドオブジェクトが入ります。終了したスレッドとまだ開始していないスレッドは入りません。しかし、主スレッドは、たとえ終了しても、常に結果に含まれます。
@end deffn

@geindex main_thread() (threading モジュール)
@anchor{library/threading threading main_thread}@anchor{11d4}
@deffn {の関数} threading.main_thread ()

main @ref{176,,Thread} オブジェクトを返します。通常の条件では、メインスレッドはPythonインタプリタが起動したスレッドを指します。


Added in version 3.4.

@end deffn

@geindex settrace() (threading モジュール)
@anchor{library/threading threading settrace}@anchor{a48}
@deffn {の関数} threading.settrace (func)

@geindex trace function

Set a trace function for all threads started from the @code{threading} module.
The `func' will be passed to  @ref{2e1,,sys.settrace()} for each thread, before its
@ref{c31,,run()} method is called.
@end deffn

@geindex settrace_all_threads() (threading モジュール)
@anchor{library/threading threading settrace_all_threads}@anchor{6ef}
@deffn {の関数} threading.settrace_all_threads (func)

Set a trace function for all threads started from the @code{threading} module
and all Python threads that are currently executing.

The `func' will be passed to  @ref{2e1,,sys.settrace()} for each thread, before its
@ref{c31,,run()} method is called.


Added in version 3.12.

@end deffn

@geindex gettrace() (threading モジュール)
@anchor{library/threading threading gettrace}@anchor{a46}
@deffn {の関数} threading.gettrace ()

@geindex trace function
@geindex debugger

@ref{a48,,settrace()} 関数で設定したトレース関数を取得します。


Added in version 3.10.

@end deffn

@geindex setprofile() (threading モジュール)
@anchor{library/threading threading setprofile}@anchor{a49}
@deffn {の関数} threading.setprofile (func)

@geindex profile function

Set a profile function for all threads started from the @code{threading} module.
The `func' will be passed to  @ref{1717,,sys.setprofile()} for each thread, before its
@ref{c31,,run()} method is called.
@end deffn

@geindex setprofile_all_threads() (threading モジュール)
@anchor{library/threading threading setprofile_all_threads}@anchor{6f0}
@deffn {の関数} threading.setprofile_all_threads (func)

Set a profile function for all threads started from the @code{threading} module
and all Python threads that are currently executing.

The `func' will be passed to  @ref{1717,,sys.setprofile()} for each thread, before its
@ref{c31,,run()} method is called.


Added in version 3.12.

@end deffn

@geindex getprofile() (threading モジュール)
@anchor{library/threading threading getprofile}@anchor{a47}
@deffn {の関数} threading.getprofile ()

@geindex profile function

@ref{a49,,setprofile()} 関数で設定したプロファイラ関数を取得します。


Added in version 3.10.

@end deffn

@geindex stack_size() (threading モジュール)
@anchor{library/threading threading stack_size}@anchor{3619}
@deffn {の関数} threading.stack_size ([size])

新しいスレッドを作るときのスレッドスタックサイズを返します。オプションの `size' 引数にはこれ以降に作成するスレッドのスタックサイズを指定し、0 (プラットフォームのデフォルト値または設定されたデフォルト値) か、 32,768 (32 KiB) 以上の正の整数でなければなりません。`size' が指定されない場合 0 が使われます。スレッドのスタックサイズの変更がサポートされていない場合、 @ref{244,,RuntimeError} を送出します。不正なスタックサイズが指定された場合、 @ref{2ec,,ValueError} を送出して、スタックサイズは変更されません。32 KiB は現在のインタープリタ自身のために十分であると保証された最小のスタックサイズです。いくつかのプラットフォームではスタックサイズに対して制限があることに注意してください。例えば最小のスタックサイズが 32 KiB より大きかったり、システムのメモリページサイズ の整数倍の必要があるなどです。この制限についてはプラットフォームのドキュメントを参照してください (一般的なページサイズは 4 KiB なので、プラットフォームに関する情報がない場合は 4096 の整数倍のスタックサイズを選ぶといいかもしれません)。

@ref{213f,,Availability}: Windows, pthreads.

Unix platforms with POSIX threads support.
@end deffn

このモジュールでは以下の定数も定義しています:

@geindex TIMEOUT_MAX (threading モジュール)
@anchor{library/threading threading TIMEOUT_MAX}@anchor{361a}
@deffn {データ} threading.TIMEOUT_MAX

ブロックする関数 (@ref{8a7,,Lock.acquire()}, @ref{107b,,RLock.acquire()}, @ref{1c66,,Condition.wait()} など) の `timeout' 引数に許される最大値。これ以上の値を timeout に指定すると @ref{a81,,OverflowError} が発生します。


Added in version 3.2.

@end deffn

このモジュールは多くのクラスを定義しています。それらは下記のセクションで詳しく説明されます。

このモジュールのおおまかな設計は Java のスレッドモデルに基づいています。とはいえ、 Java がロックと条件変数を全てのオブジェクトの基本的な挙動にしているのに対し、 Python ではこれらを別個のオブジェクトに分けています。 Python の @ref{176,,Thread} クラスがサポートしているのは Java の Thread クラスの挙動のサブセットにすぎません; 現状では、優先度 (priority)やスレッドグループがなく、スレッドの破壊 (destroy)、中断 (stop)、一時停止 (suspend)、復帰 (resume)、割り込み (interrupt) は行えません。 Java の Thread クラスにおける静的メソッドに対応する機能が実装されている場合にはモジュールレベルの関数になっています。

以下に説明するメソッドは全て原子的 (atomic) に実行されます。

@menu
* Thread-local data:: 
* Thread objects:: 
* Lock objects:: 
* RLock objects:: 
* Condition objects:: 
* Semaphore objects:: 
* Semaphore example:: 
* Event objects:: 
* Timer objects:: 
* Barrier objects:: 

@end menu

@node Thread-local data,Thread objects,,リファレンス<2>
@anchor{library/threading thread-local-data}@anchor{361b}
@subsubsection Thread-local data


Thread-local data is data whose values are thread specific. If you
have data that you want to be local to a thread, create a
@ref{185f,,local} object and use its attributes:

@example
>>> mydata = local()
>>> mydata.number = 42
>>> mydata.number
42
@end example

You can also access the @ref{185f,,local}-object's dictionary:

@example
>>> mydata.__dict__
@{'number': 42@}
>>> mydata.__dict__.setdefault('widgets', [])
[]
>>> mydata.widgets
[]
@end example

If we access the data in a different thread:

@example
>>> log = []
>>> def f():
...     items = sorted(mydata.__dict__.items())
...     log.append(items)
...     mydata.number = 11
...     log.append(mydata.number)

>>> import threading
>>> thread = threading.Thread(target=f)
>>> thread.start()
>>> thread.join()
>>> log
[[], 11]
@end example

we get different data.  Furthermore, changes made in the other thread
don't affect data seen in this thread:

@example
>>> mydata.number
42
@end example

Of course, values you get from a @ref{185f,,local} object, including their
@ref{77d,,__dict__} attribute, are for whatever thread was current
at the time the attribute was read.  For that reason, you generally
don't want to save these values across threads, as they apply only to
the thread they came from.

You can create custom @ref{185f,,local} objects by subclassing the
@ref{185f,,local} class:

@example
>>> class MyLocal(local):
...     number = 2
...     def __init__(self, /, **kw):
...         self.__dict__.update(kw)
...     def squared(self):
...         return self.number ** 2
@end example

This can be useful to support default values, methods and
initialization.  Note that if you define an @ref{8bf,,__init__()}
method, it will be called each time the @ref{185f,,local} object is used
in a separate thread.  This is necessary to initialize each thread's
dictionary.

Now if we create a @ref{185f,,local} object:

@example
>>> mydata = MyLocal(color='red')
@end example

we have a default number:

@example
>>> mydata.number
2
@end example

an initial color:

@example
>>> mydata.color
'red'
>>> del mydata.color
@end example

And a method that operates on the data:

@example
>>> mydata.squared()
4
@end example

As before, we can access the data in a separate thread:

@example
>>> log = []
>>> thread = threading.Thread(target=f)
>>> thread.start()
>>> thread.join()
>>> log
[[('color', 'red')], 11]
@end example

without affecting this thread's data:

@example
>>> mydata.number
2
>>> mydata.color
Traceback (most recent call last):
...
AttributeError: 'MyLocal' object has no attribute 'color'
@end example

Note that subclasses can define @ref{7f7,,__slots__}, but they are not
thread local. They are shared across threads:

@example
>>> class MyLocal(local):
...     __slots__ = 'number'

>>> mydata = MyLocal()
>>> mydata.number = 42
>>> mydata.color = 'red'
@end example

So, the separate thread:

@example
>>> thread = threading.Thread(target=f)
>>> thread.start()
>>> thread.join()
@end example

affects what we see:

@example
>>> mydata.number
11
@end example

@geindex local (threading のクラス)
@anchor{library/threading threading local}@anchor{185f}
@deffn {クラス} threading.local

スレッドローカルデータを表現するクラス。
@end deffn

@node Thread objects,Lock objects,Thread-local data,リファレンス<2>
@anchor{library/threading id1}@anchor{361c}@anchor{library/threading thread-objects}@anchor{361d}
@subsubsection Thread objects


The @ref{176,,Thread} class represents an activity that is run in a separate
thread of control.  There are two ways to specify the activity: by passing a
callable object to the constructor, or by overriding the @ref{c31,,run()}
method in a subclass.  No other methods (except for the constructor) should be
overridden in a subclass.  In other words, `only'  override the
@code{__init__()} and @ref{c31,,run()} methods of this class.

ひとたびスレッドオブジェクトを生成すると、スレッドの @ref{178,,start()} メソッドを呼び出して活動を開始しなければなりません。 @code{start()} メソッド はそれぞれのスレッドの @ref{c31,,run()} メソッドを起動します。

スレッドの活動が始まると、スレッドは '生存中 (alive)' とみなされます。 スレッドは、通常 @ref{c31,,run()} メソッドが終了するまで、もしくは捕捉されない例外が送出されるまで生存中となります。 @ref{b46,,is_alive()} メソッドは、スレッドが生存中であるかどうか調べます。

スレッドは他のスレッドの @ref{13fd,,join()} メソッドを呼び出すことができます。このメソッドは、 @ref{13fd,,join()} メソッドを呼ばれたスレッドが終了するまでメソッドの呼び出し元のスレッドをブロックします。

スレッドは名前を持っています。名前はコンストラクタに渡すことができ、 @ref{2a0,,name} 属性を通して読み出したり変更したりできます。

@ref{c31,,run()} メソッドが例外を発生させた場合、@ref{a4b,,threading.excepthook()} が呼び出され、例外を処理します。デフォルトでは、@ref{a4b,,threading.excepthook()} は @ref{f3c,,SystemExit} を黙殺します。

スレッドには "デーモンスレッド (daemon thread)" であるというフラグを立てられます。 このフラグには、残っているスレッドがデーモンスレッドだけになった時に Python プログラム全体を終了させるという意味があります。フラグの初期値はスレッドを生成したスレッドから継承します。フラグの値は @ref{35c,,daemon} プロパティまたは `daemon' コンストラクタ引数を通して設定できます。

@cartouche
@quotation 注釈 
デーモンスレッドは終了時にいきなり停止されます。デーモンスレッドで使われたリソース (開いているファイル、データベースのトランザクションなど) は適切に解放されないかもしれません。きちんと (gracefully) スレッドを停止したい場合は、スレッドを非デーモンスレッドにして、@ref{1370,,Event} のような適切なシグナル送信機構を使用してください。
@end quotation
@end cartouche

スレッドには "主スレッド (main thread)" オブジェクトがあります。主スレッドは Python プログラムを最初に制御していたスレッドです。主スレッドはデーモンスレッドではありません。

"ダミースレッドオブジェクト (dummy thread objects)" が作成される場合があります。ダミースレッドは、 "外来スレッド (alien thread)" に相当するスレッドオブジェクトです。ダミースレッドは、C コードから直接生成されたスレッドのような、 @ref{f3,,threading} モジュールの外で開始された処理スレッドです。ダミースレッドオブジェクトには限られた機能しかなく、常に生存中、かつデーモンスレッドであるとみなされ、 @ref{361e,,join} できません。また、外来スレッドの終了を検出するのは不可能なので、ダミースレッドは削除できません。

@geindex Thread (threading のクラス)
@anchor{library/threading threading Thread}@anchor{176}
@deffn {クラス} threading.Thread (group=None, target=None, name=None, args=(), kwargs=@{@}, *, daemon=None, context=None)

コンストラクタは常にキーワード引数を使って呼び出さなければなりません。各引数は以下の通りです:

`group' should be @code{None}; reserved for future extension when a
@code{ThreadGroup} class is implemented.

`target' は @ref{c31,,run()} メソッドによって起動される呼び出し可能オブジェクトです。デフォルトでは何も呼び出さないことを示す @code{None} になっています。

`name*はスレッド名です。デフォルトでは、"Thread-*N'"(`N*は小さな10進数)、または*target*引数が指定された場合"Thread-*N' (target)"("target"は`@w{`}target.__name__`@w{`})という形式でユニークな名前が構成される。

`args' は `target' を呼び出すときの引数のリストかタプルです。デフォルトは @code{()} です。

`kwargs' は `target' を呼び出すときのキーワード引数の辞書です。デフォルトは @code{@{@}} です。

@code{None} でない場合、`daemon' はスレッドがデーモンかどうかを明示的に設定します。@code{None} の場合 (デフォルト)、デーモン属性は現在のスレッドから継承されます。

`context' is the @ref{177,,Context} value to use when starting
the thread.  The default value is @code{None} which indicates that the
@ref{175,,sys.flags.thread_inherit_context} flag controls the behaviour.  If
the flag is true, threads will start with a copy of the context of the
caller of @ref{178,,start()}.  If false, they will start with an empty
context.  To explicitly start with an empty context, pass a new instance of
@ref{177,,Context()}.  To explicitly start with a copy of the
current context, pass the value from @ref{361f,,copy_context()}. The
flag defaults true on free-threaded builds and false otherwise.

サブクラスでコンストラクタをオーバライドした場合、必ずスレッドが何かを始める前に基底クラスのコンストラクタ (@code{Thread.__init__()}) を呼び出しておかなくてはなりません。


バージョン 3.3 で変更: Added the `daemon' parameter.



バージョン 3.10 で変更: `name' 引数が省略された場合、`target' 名を使用します。



バージョン 3.14 で変更: `context' パラメータを追加しました。


@geindex start() (threading.Thread のメソッド)
@anchor{library/threading threading Thread start}@anchor{178}
@deffn {メソッド} start ()

スレッドの活動を開始します。

このメソッドは、スレッドオブジェクトあたり一度しか呼び出してはなりません。 @ref{178,,start()} は、オブジェクトの @ref{c31,,run()} メソッドが個別の処理スレッド中で呼び出されるように調整します。

同じスレッドオブジェクトに対し、このメソッドを2回以上呼び出した場合、 @ref{244,,RuntimeError} を送出します。

If supported, set the operating system thread name to
@ref{2a0,,threading.Thread.name}. The name can be truncated depending on the
operating system thread name limits.


バージョン 3.14 で変更: Set the operating system thread name.

@end deffn

@geindex run() (threading.Thread のメソッド)
@anchor{library/threading threading Thread run}@anchor{c31}
@deffn {メソッド} run ()

スレッドの活動をもたらすメソッドです。

このメソッドはサブクラスでオーバライドできます。標準の @ref{c31,,run()} メソッドでは、オブジェクトのコンストラクタの `target' 引数に呼び出し可能オブジェクトを指定した場合、 `args' および `kwargs' の位置引数およびキーワード引数とともに呼び出します。

@ref{176,,Thread} に渡される `args' の引数にリストやタプルを使っても、同じ効果が得られます。

以下はプログラム例です:

@example
>>> from threading import Thread
>>> t = Thread(target=print, args=[1])
>>> t.run()
1
>>> t = Thread(target=print, args=(1,))
>>> t.run()
1
@end example
@end deffn

@geindex join() (threading.Thread のメソッド)
@anchor{library/threading meth-thread-join}@anchor{361e}@anchor{library/threading threading Thread join}@anchor{13fd}
@deffn {メソッド} join (timeout=None)

スレッドが終了するまで待機します。
このメソッドは、 @ref{13fd,,join()} を呼ばれたスレッドが正常終了あるいは処理されない例外によって終了するか、オプションのタイムアウトが発生するまで、メソッドの呼び出し元のスレッドをブロックします。

When the `timeout' argument is present and not @code{None}, it should be a
floating-point number specifying a timeout for the operation in seconds
(or fractions thereof). As @ref{13fd,,join()} always returns @code{None},
you must call @ref{b46,,is_alive()} after @ref{13fd,,join()} to
decide whether a timeout happened -- if the thread is still alive, the
@ref{13fd,,join()} call timed out.

`timeout' が指定されないかまたは @code{None} であるときは、この操作はスレッドが終了するまでブロックします。

1つのスレッドは何回も join されることができます。

現在のスレッドに対して @ref{13fd,,join()} を呼び出そうとすると、デッドロックを引き起こすため @ref{244,,RuntimeError} が送出されます。 スレッドが開始される前に @ref{13fd,,join()} を呼び出すことも同様のエラーのため、同じ例外が送出されます。

If an attempt is made to join a running daemonic thread in late stages
of @ref{479,,Python finalization} @code{join()}
raises a @ref{47a,,PythonFinalizationError}.


バージョン 3.14 で変更: May raise @ref{47a,,PythonFinalizationError}.

@end deffn

@geindex name (threading.Thread の属性)
@anchor{library/threading threading Thread name}@anchor{2a0}
@deffn {の属性} name

識別のためにのみ用いられる文字列です。名前には機能上の意味づけ (semantics) はありません。複数のスレッドに同じ名前をつけてもかまいません。名前の初期値はコンストラクタで設定されます。

On some platforms, the thread name is set at the operating system level
when the thread starts, so that it is visible in task managers.
This name may be truncated to fit in a system-specific limit (for example,
15 bytes on Linux or 63 bytes on macOS).

Changes to `name' are only reflected at the OS level when the currently
running thread is renamed. (Setting the `name' attribute of a
different thread only updates the Python Thread object.)
@end deffn

@geindex getName() (threading.Thread のメソッド)
@geindex setName() (threading.Thread のメソッド)
@anchor{library/threading threading Thread getName}@anchor{3620}
@deffn {メソッド} getName ()
@anchor{library/threading threading Thread setName}@anchor{35d}
@deffnx {メソッド} setName ()

@ref{2a0,,name} に対する非推奨 getter/setter API; 代わりにプロパティを直接使用してください。


バージョン 3.10 で非推奨.

@end deffn

@geindex ident (threading.Thread の属性)
@anchor{library/threading threading Thread ident}@anchor{3137}
@deffn {の属性} ident

'スレッド識別子' 、または、スレッドが開始されていなければ @code{None} です。非ゼロの整数です。 @ref{1372,,get_ident()} 関数を参照下さい。スレッド識別子は、スレッドが終了した後、新たなスレッドが生成された場合、再利用され得ます。スレッド識別子は、スレッドが終了した後でも利用できます。
@end deffn

@geindex native_id (threading.Thread の属性)
@anchor{library/threading threading Thread native_id}@anchor{c33}
@deffn {の属性} native_id

The Thread ID (@code{TID}) of this thread, as assigned by the OS (kernel).
This is a non-negative integer, or @code{None} if the thread has not
been started. See the @ref{c32,,get_native_id()} function.
This value may be used to uniquely identify this particular thread
system-wide (until the thread terminates, after which the value
may be recycled by the OS).

@cartouche
@quotation 注釈 
Similar to Process IDs, Thread IDs are only valid (guaranteed unique
system-wide) from the time the thread is created until the thread
has been terminated.
@end quotation
@end cartouche

@ref{213f,,Availability}: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD.


Added in version 3.8.

@end deffn

@geindex is_alive() (threading.Thread のメソッド)
@anchor{library/threading threading Thread is_alive}@anchor{b46}
@deffn {メソッド} is_alive ()

スレッドが生存中かどうかを返します。

このメソッドは、 @ref{c31,,run()} メソッドが起動する直前から @ref{c31,,run()} メソッドが終了する直後までの間 @code{True} を返します。モジュール関数 @ref{1c5a,,enumerate()} は、全ての生存中のスレッドのリストを返します。
@end deffn

@geindex daemon (threading.Thread の属性)
@anchor{library/threading threading Thread daemon}@anchor{35c}
@deffn {の属性} daemon

このスレッドがデーモンスレッドか (@code{True}) か否か (@code{False}) を示すブール値。この値は @ref{178,,start()} の呼び出し前に設定されなければなりません。さもなければ @ref{244,,RuntimeError} が送出されます。初期値は生成側のスレッドから継承されます; メインスレッドはデーモンスレッドではないので、メインスレッドで作成されたすべてのスレッドは、デフォルトで @ref{35c,,daemon} = @code{False} になります。

デーモンでない生存中のスレッドが全てなくなると、 Python プログラム全体が終了します。
@end deffn

@geindex isDaemon() (threading.Thread のメソッド)
@geindex setDaemon() (threading.Thread のメソッド)
@anchor{library/threading threading Thread isDaemon}@anchor{3621}
@deffn {メソッド} isDaemon ()
@anchor{library/threading threading Thread setDaemon}@anchor{35b}
@deffnx {メソッド} setDaemon ()

@ref{35c,,daemon} に対する非推奨 getter/setter API; 代わりにプロパティを直接使用してください。


バージョン 3.10 で非推奨.

@end deffn
@end deffn

@node Lock objects,RLock objects,Thread objects,リファレンス<2>
@anchor{library/threading id2}@anchor{3622}@anchor{library/threading lock-objects}@anchor{3623}
@subsubsection Lock objects


プリミティブロックとは、ロックが生じた際に特定のスレッドによって所有されない同期プリミティブです。 Python では現在のところ拡張モジュール @ref{2,,_thread} で直接実装されている最も低水準の同期プリミティブを使えます。

プリミティブロックは2つの状態、 "ロック" または "アンロック" があります。ロックはアンロック状態で作成されます。ロックには基本となる二つのメソッド、 @ref{8a7,,acquire()} と @ref{14da,,release()} があります。ロックの状態がアンロックである場合、 @ref{8a7,,acquire()} は状態をロックに変更して即座に処理を戻します。 状態がロックの場合、 @ref{8a7,,acquire()} は他のスレッドが @ref{14da,,release()} を呼び出してロックの状態をアンロックに変更するまでブロックします。その後、 @ref{8a7,,acquire()} 呼び出しは状態を再度ロックに設定してから処理を戻します。 @ref{14da,,release()} メソッドを呼び出すのはロック状態のときでなければなりません; このメソッドはロックの状態をアンロックに変更して、即座に処理を戻します。 アンロックの状態のロックを解放しようとすると @ref{244,,RuntimeError} が送出されます。

ロックは @ref{3624,,コンテキストマネージメントプロトコル} もサポートします。

複数のスレッドにおいて @ref{8a7,,acquire()} がアンロック状態への遷移を待っているためにブロックが起きている時に @ref{14da,,release()} を呼び出してロックの状態をアンロックにすると、一つのスレッドだけが処理を進行できます。 どのスレッドが処理を進行できるのかは定義されておらず、実装によって異なるかもしれません。

全てのメソッドはアトミックに実行されます。

@geindex Lock (threading のクラス)
@anchor{library/threading threading Lock}@anchor{19f4}
@deffn {クラス} threading.Lock

プリミティブロック (primitive lock) オブジェクトを実装しているクラスです。スレッドが一度ロックを獲得すると、それ以後のロック獲得の試みはロックが解放されるまでブロックします。どのスレッドでもロックを解放できます。


バージョン 3.13 で変更: @code{Lock} is now a class. In earlier Pythons, @code{Lock} was a factory
function which returned an instance of the underlying private lock
type.


@geindex acquire() (threading.Lock のメソッド)
@anchor{library/threading threading Lock acquire}@anchor{8a7}
@deffn {メソッド} acquire (blocking=True, timeout=-1)

ブロックあり、またはブロックなしでロックを獲得します。

引数 `blocking' を @code{True} (デフォルト) に設定して呼び出した場合、ロックがアンロック状態になるまでブロックします。そしてそれをロック状態にしてから @code{True} を返します。

引数 `blocking' の値を @code{False} にして呼び出すとブロックしません。`blocking' を @code{True} にして呼び出した場合にブロックするような状況では、直ちに @code{False} を返します。それ以外の場合には、ロックをロック状態にして @code{True} を返します。

正の値に設定された浮動小数点の `timeout' 引数とともに起動された場合、ロックを得られなければ最大で `timeout' によって指定された秒数だけブロックします。`timeout' 引数の @code{-1} は無制限の待機を指定します。`blocking' が @code{False} の場合に `timeout' を指定することは禁止されています。

ロックを獲得すると @code{True} を、ロックを獲得できなかったとき (例えば `timeout' が過ぎた場合) には @code{False} を返します。


バージョン 3.2 で変更: 新しい `timeout' 引数。



バージョン 3.2 で変更: Lock acquisition can now be interrupted by signals on POSIX if the
underlying threading implementation supports it.



バージョン 3.14 で変更: Lock acquisition can now be interrupted by signals on Windows.

@end deffn

@geindex release() (threading.Lock のメソッド)
@anchor{library/threading threading Lock release}@anchor{14da}
@deffn {メソッド} release ()

ロックを解放します。これはロックを獲得したスレッドだけでなく、任意のスレッドから呼ぶことができます。

ロックの状態がロックのとき、状態をアンロックにリセットして処理を戻します。他のスレッドがロックがアンロック状態になるのを待ってブロックしている場合、ただ一つのスレッドだけが処理を継続できるようにします。

アンロック状態のロックに対して呼び出された場合、@ref{244,,RuntimeError} が送出されます。

戻り値はありません。
@end deffn

@geindex locked() (threading.Lock のメソッド)
@anchor{library/threading threading Lock locked}@anchor{3625}
@deffn {メソッド} locked ()

ロック状態のとき @code{True} を返します。
@end deffn
@end deffn

@node RLock objects,Condition objects,Lock objects,リファレンス<2>
@anchor{library/threading id3}@anchor{3626}@anchor{library/threading rlock-objects}@anchor{3627}
@subsubsection RLock objects


再入可能ロック (reentrant lock) とは、同じスレッドが複数回獲得できるような同期プリミティブです。再入可能ロックの内部では、プリミティブロックの使うロック／アンロック状態に加え、 "所有スレッド (owning thread)" と "再帰レベル (recursion level)" という概念を用いています。ロック状態では何らかのスレッドがロックを所有しており、アンロック状態ではいかなるスレッドもロックを所有していません。

Threads call a lock's @ref{107b,,acquire()} method to lock it,
and its @ref{14da,,release()} method to unlock it.

@cartouche
@quotation 注釈 
Reentrant locks support the @ref{3624,,context management protocol},
so it is recommended to use @ref{186,,with} instead of manually calling
@ref{107b,,acquire()} and @ref{3628,,release()}
to handle acquiring and releasing the lock for a block of code.
@end quotation
@end cartouche

RLock's @ref{107b,,acquire()}/@ref{3628,,release()} call pairs may be nested,
unlike Lock's @ref{8a7,,acquire()}/@ref{14da,,release()}. Only the final
@ref{3628,,release()} (the @ref{14da,,release()} of the outermost pair) resets
the lock to an unlocked state and allows another thread blocked in
@ref{107b,,acquire()} to proceed.

@ref{107b,,acquire()}/@ref{3628,,release()} must be used in pairs: each acquire
must have a release in the thread that has acquired the lock. Failing to
call release as many times the lock has been acquired can lead to deadlock.

@geindex RLock (threading のクラス)
@anchor{library/threading threading RLock}@anchor{32e}
@deffn {クラス} threading.RLock

このクラスは再入可能ロックオブジェクトを実装します。再入可能ロックはそれを獲得したスレッドによって解放されなければなりません。いったんスレッドが再入可能ロックを獲得すると、同じスレッドはブロックされずにもう一度それを獲得できます ; そのスレッドは獲得した回数だけ解放しなければいけません。

@code{RLock} は実際にはファクトリ関数で、プラットフォームでサポートされる最も効率的なバージョンの具体的な RLock クラスのインスタンスを返すことに注意してください。

@geindex acquire() (threading.RLock のメソッド)
@anchor{library/threading threading RLock acquire}@anchor{107b}
@deffn {メソッド} acquire (blocking=True, timeout=-1)

ブロックあり、またはブロックなしでロックを獲得します。


@subsubheading 参考



@table @asis

@item @ref{3624,,Using RLock as a context manager}

Recommended over manual @code{acquire()} and @ref{3628,,release()} calls
whenever practical.
@end table


When invoked with the `blocking' argument set to @code{True} (the default):

@quotation


@itemize *

@item 
If no thread owns the lock, acquire the lock and return immediately.

@item 
If another thread owns the lock, block until we are able to acquire
lock, or `timeout', if set to a positive float value.

@item 
If the same thread owns the lock, acquire the lock again, and
return immediately. This is the difference between @ref{19f4,,Lock} and
@code{RLock}; @ref{19f4,,Lock} handles this case the same as the previous,
blocking until the lock can be acquired.
@end itemize
@end quotation

When invoked with the `blocking' argument set to @code{False}:

@quotation


@itemize *

@item 
If no thread owns the lock, acquire the lock and return immediately.

@item 
If another thread owns the lock, return immediately.

@item 
If the same thread owns the lock, acquire the lock again and return
immediately.
@end itemize
@end quotation

In all cases, if the thread was able to acquire the lock, return @code{True}.
If the thread was unable to acquire the lock (i.e. if not blocking or
the timeout was reached) return @code{False}.

If called multiple times, failing to call @ref{3628,,release()} as many times
may lead to deadlock. Consider using @code{RLock} as a context manager rather than
calling acquire/release directly.


バージョン 3.2 で変更: 新しい `timeout' 引数。

@end deffn

@geindex release() (threading.RLock のメソッド)
@anchor{library/threading threading RLock release}@anchor{3628}
@deffn {メソッド} release ()

再帰レベルをデクリメントしてロックを解放します。デクリメント後に再帰レベルがゼロになった場合、ロックの状態をアンロック (いかなるスレッドにも所有されていない状態) にリセットし、ロックの状態がアンロックになるのを待ってブロックしているスレッドがある場合にはその中のただ一つだけが処理を進行できるようにします。デクリメント後も再帰レベルがゼロでない場合、ロックの状態はロックのままで、呼び出し側のスレッドに所有されたままになります。

Only call this method when the calling thread owns the lock. A
@ref{244,,RuntimeError} is raised if this method is called when the lock is
not acquired.

戻り値はありません。
@end deffn

@geindex locked() (threading.RLock のメソッド)
@anchor{library/threading threading RLock locked}@anchor{183c}
@deffn {メソッド} locked ()

Return a boolean indicating whether this object is locked right now.


Added in version 3.14.

@end deffn
@end deffn

@node Condition objects,Semaphore objects,RLock objects,リファレンス<2>
@anchor{library/threading condition-objects}@anchor{3629}@anchor{library/threading id4}@anchor{362a}
@subsubsection Condition objects


条件変数 (condition variable) は、常にある種のロックに関連付けられています; このロックは明示的に渡すことも、デフォルトで生成させることもできます。複数の条件変数で同じロックを共有しなければならない場合には、引渡しによる関連付けが便利です。ロックは条件オブジェクトの一部です: それを別々に扱う必要はありません。

条件変数は @ref{3624,,コンテキスト管理プロトコル} に従います: @code{with} 文を使って囲まれたブロックの間だけ関連付けられたロックを獲得することができます。 @ref{362b,,acquire()} メソッドと @ref{362c,,release()} メソッドは、さらに関連付けられたロックの対応するメソッドを呼び出します。

他のメソッドは、関連付けられたロックを保持した状態で呼び出さなければなりません。 @ref{1c66,,wait()} メソッドはロックを解放します。そして別のスレッドが @ref{1b66,,notify()} または @ref{359,,notify_all()} を呼ぶことによってスレッドを起こすまでブロックします。一旦起こされたなら、 @ref{1c66,,wait()} は再びロックを得て戻ります。タイムアウトを指定することも可能です。

@ref{1b66,,notify()} メソッドは条件変数待ちのスレッドを1つ起こします。 @ref{359,,notify_all()} メソッドは条件変数待ちの全てのスレッドを起こします。

注意: @ref{1b66,,notify()} と @ref{359,,notify_all()} はロックを解放しません; 従って、スレッドが起こされたとき、 @ref{1c66,,wait()} の呼び出しは即座に処理を戻すわけではなく、 @ref{1b66,,notify()} または @ref{359,,notify_all()} を呼び出したスレッドが最終的にロックの所有権を放棄したときに初めて処理を返すのです。

条件変数を使う典型的なプログラミングスタイルでは、何らかの共有された状態変数へのアクセスを同期させるためにロックを使います; 状態変数が特定の状態に変化したことを知りたいスレッドは、自分の望む状態になるまで繰り返し @ref{1c66,,wait()} を呼び出します。その一方で、状態変更を行うスレッドは、前者のスレッドが待ち望んでいる状態であるかもしれないような状態へ変更を行ったときに @ref{1b66,,notify()} や @ref{359,,notify_all()} を呼び出します。例えば、以下のコードは無制限のバッファ容量のときの一般的な生産者-消費者問題です:

@example
# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
@end example

アプリケーションの条件をチェックする @code{while} ループは必須です。なぜなら、 @ref{1c66,,wait()} が任意の長時間の後で返り、 @ref{1b66,,notify()} 呼び出しを促した条件がもはや真でないことがありえるからです。これはマルチスレッドプログラミングに固有です。条件チェックを自動化するために @ref{362d,,wait_for()} メソッドを使うことができ、それはタイムアウトの計算を簡略化します:

@example
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
@end example

@ref{1b66,,notify()} と @ref{359,,notify_all()} のどちらを使うかは、その状態の変化に興味を持っている待ちスレッドが一つだけなのか、あるいは複数なのかで考えます。例えば、典型的な生産者-消費者問題では、バッファに1つの要素を加えた場合には消費者スレッドを 1 つしか起こさなくてかまいません。

@geindex Condition (threading のクラス)
@anchor{library/threading threading Condition}@anchor{136d}
@deffn {クラス} threading.Condition (lock=None)

このクラスは条件変数 (condition variable) オブジェクトを実装します。条件変数を使うと、1つ以上のスレッドを別のスレッドの通知があるまで待機させておけます。

`lock' に @code{None} でない値を指定した場合、その値は @ref{19f4,,Lock} または @ref{32e,,RLock} オブジェクトでなければなりません。
この場合、 `lock' は根底にあるロックオブジェクトとして使われます。
それ以外の場合には、 @ref{32e,,RLock} オブジェクトを新しく作成して使います。


バージョン 3.3 で変更: ファクトリ関数からクラスに変更されました。


@geindex acquire() (threading.Condition のメソッド)
@anchor{library/threading threading Condition acquire}@anchor{362b}
@deffn {メソッド} acquire (*args)

根底にあるロックを獲得します。このメソッドは根底にあるロックの対応するメソッドを呼び出します。そのメソッドの戻り値を返します。
@end deffn

@geindex release() (threading.Condition のメソッド)
@anchor{library/threading threading Condition release}@anchor{362c}
@deffn {メソッド} release ()

根底にあるロックを解放します。このメソッドは根底にあるロックの対応するメソッドを呼び出します。戻り値はありません。
@end deffn

@geindex locked() (threading.Condition のメソッド)
@anchor{library/threading threading Condition locked}@anchor{362e}
@deffn {メソッド} locked ()

Return a boolean indicating whether this object is locked right now.


Added in version 3.14.

@end deffn

@geindex wait() (threading.Condition のメソッド)
@anchor{library/threading threading Condition wait}@anchor{1c66}
@deffn {メソッド} wait (timeout=None)

通知 (notify) を受けるか、タイムアウトするまで待機します。呼び出し側のスレッドがロックを獲得していないときにこのメソッドを呼び出すと @ref{244,,RuntimeError} が送出されます。

このメソッドは根底にあるロックを解放し、他のスレッドが同じ条件変数に対して @ref{1b66,,notify()} または @ref{359,,notify_all()} を呼び出して現在のスレッドを起こすか、オプションのタイムアウトが発生するまでブロックします。一度スレッドが起こされると、再度ロックを獲得して処理を戻します。

When the `timeout' argument is present and not @code{None}, it should be a
floating-point number specifying a timeout for the operation in seconds
(or fractions thereof).

根底にあるロックが @ref{32e,,RLock} である場合、 @ref{362c,,release()} メソッドではロックは解放されません。というのも、ロックが再帰的に複数回獲得されている場合には、 @ref{362c,,release()} によって実際にアンロックが行われないかもしれないからです。その代わり、ロックが再帰的に複数回獲得されていても確実にアンロックを行える @ref{32e,,RLock} クラスの内部インターフェースを使います。その後ロックを再獲得する時に、もう一つの内部インターフェースを使ってロックの再帰レベルを復帰します。

与えられた `timeout' が過ぎていなければ返り値は @code{True} です。タイムアウトした場合には @code{False} が返ります。


バージョン 3.2 で変更: 以前は、このメソッドは常に @code{None} を返していました。

@end deffn

@geindex wait_for() (threading.Condition のメソッド)
@anchor{library/threading threading Condition wait_for}@anchor{362d}
@deffn {メソッド} wait_for (predicate, timeout=None)

条件が真と判定されるまで待ちます。
`predicate' は呼び出し可能オブジェクトでなければならず、その結果はブール値として解釈されます。
最大の待ち時間を指定する `timeout' を与えることができます。

このユーティリティメソッドは、述語が満たされるかタイムアウトが発生するまで @ref{1c66,,wait()} を繰り返し呼び出す場合があります。戻り値は述語の最後の戻り値で、もしメソッドがタイムアウトすれば、 @code{False} と評価されます。

タイムアウト機能を無視すれば、このメソッドの呼び出しは以下のように書くのとほぼ等価です:

@example
while not predicate():
    cv.wait()
@end example

したがって、 @ref{1c66,,wait()} と同じルールが適用されます: 呼び出された時にロックを保持していなければならず、戻るときにロックが再度獲得されます。述語はロックを保持した状態で評価されます。


Added in version 3.2.

@end deffn

@geindex notify() (threading.Condition のメソッド)
@anchor{library/threading threading Condition notify}@anchor{1b66}
@deffn {メソッド} notify (n=1)

デフォルトで、この条件変数を待っている1つのスレッドを起こします。 呼び出し側のスレッドがロックを獲得していないときにこのメソッドを呼び出すと @ref{244,,RuntimeError} が送出されます。

何らかの待機中スレッドがある場合、そのうち `n' スレッドを起こします。待機中のスレッドがなければ何もしません。

現在の実装では、少なくとも `n' スレッドが待機中であれば、ちょうど `n' スレッドを起こします。とはいえ、この挙動に依存するのは安全ではありません。将来、実装の最適化によって、複数のスレッドを起こすようになるかもしれないからです。

注意: 起こされたスレッドは実際にロックを再獲得できるまで @ref{1c66,,wait()} 呼び出しから戻りません。 @ref{1b66,,notify()} はロックを解放しないので、 @ref{1b66,,notify()} 呼び出し側は明示的にロックを解放しなければなりません。
@end deffn

@geindex notify_all() (threading.Condition のメソッド)
@anchor{library/threading threading Condition notify_all}@anchor{359}
@deffn {メソッド} notify_all ()

この条件を待っているすべてのスレッドを起こします。このメソッドは @ref{1b66,,notify()} のように動作しますが、 1 つではなくすべての待ちスレッドを起こします。呼び出し側のスレッドがロックを獲得していない場合、 @ref{244,,RuntimeError} が送出されます。

関数`@w{`}notifyAll`@w{`}はこの関数の非推奨エイリアスです。
@end deffn
@end deffn

@node Semaphore objects,Semaphore example,Condition objects,リファレンス<2>
@anchor{library/threading id5}@anchor{362f}@anchor{library/threading semaphore-objects}@anchor{3630}
@subsubsection Semaphore objects


セマフォ (semaphore) は、計算機科学史上最も古い同期プリミティブの一つ で、草創期のオランダ計算機科学者 Edsger W. Dijkstra によって発明されました (彼は @ref{146b,,acquire()} と @ref{3631,,release()} の代わりに @code{P()} と @code{V()} を使いました)。

セマフォは @ref{146b,,acquire()} でデクリメントされ @ref{3631,,release()} でインクリメントされるような内部カウンタを管理します。 カウンタは決してゼロより小さくはなりません; @ref{146b,,acquire()} は、カウンタがゼロになっている場合、他のスレッドが @ref{3631,,release()} を呼び出すまでブロックします。

セマフォは @ref{3624,,コンテキストマネージメントプロトコル} もサポートします。

@geindex Semaphore (threading のクラス)
@anchor{library/threading threading Semaphore}@anchor{136e}
@deffn {クラス} threading.Semaphore (value=1)

このクラスはセマフォ (semaphore) オブジェクトを実装します。セマフォは、 @ref{3631,,release()} を呼び出した数から @ref{146b,,acquire()} を呼び出した数を引き、初期値を足した値を表す極小のカウンタを管理します。 @ref{146b,,acquire()} メソッドは、カウンタの値を負にせずに処理を戻せるまで必要ならば処理をブロックします。 `value' を指定しない場合、デフォルトの値は 1 になります。

オプションの引数には、内部カウンタの初期値を指定します。デフォルトは @code{1} です。与えられた `value' が 0 より小さい場合、 @ref{2ec,,ValueError} が送出されます。


バージョン 3.3 で変更: ファクトリ関数からクラスに変更されました。


@geindex acquire() (threading.Semaphore のメソッド)
@anchor{library/threading threading Semaphore acquire}@anchor{146b}
@deffn {メソッド} acquire (blocking=True, timeout=None)

セマフォを獲得します。

When invoked without arguments:


@itemize *

@item 
If the internal counter is larger than zero on entry, decrement it by
one and return @code{True} immediately.

@item 
If the internal counter is zero on entry, block until awoken by a call to
@ref{3631,,release()}.  Once awoken (and the counter is greater
than 0), decrement the counter by 1 and return @code{True}.  Exactly one
thread will be awoken by each call to @ref{3631,,release()}.  The
order in which threads are awoken should not be relied on.
@end itemize

`blocking' を @code{False} にして呼び出すとブロックしません。引数なしで呼び出した場合にブロックするような状況であった場合には直ちに @code{False} を返します。それ以外の場合には、引数なしで呼び出したときと同じ処理を行い @code{True} を返します。

@code{None} 以外の `timeout' で起動された場合、最大で `timeout' 秒ブロックします。
acquire が その間隔の間で完了しなかった場合は @code{False} が返ります。そうでなければ @code{True} が返ります。


バージョン 3.2 で変更: 新しい `timeout' 引数。

@end deffn

@geindex release() (threading.Semaphore のメソッド)
@anchor{library/threading threading Semaphore release}@anchor{3631}
@deffn {メソッド} release (n=1)

内部カウンタを `n' インクリメントして、セマフォを解放します。 @code{release()} 処理に入ったときにカウンタがゼロであり、カウンタの値がゼロより大きくなるのを待っている別のスレッドがあった場合、それらのスレッドから `n' 個を起こします。


バージョン 3.9 で変更: 複数の待機中のスレッドを一度に解放する `n' パラメータを追加しました。

@end deffn
@end deffn

@geindex BoundedSemaphore (threading のクラス)
@anchor{library/threading threading BoundedSemaphore}@anchor{136f}
@deffn {クラス} threading.BoundedSemaphore (value=1)

有限セマフォ (bounded semaphore) オブジェクトを実装しているクラスです。有限セマフォは、現在の値が初期値を超過しないようチェックを行います。超過を起こした場合、 @ref{2ec,,ValueError} を送出します。たいていの場合、セマフォは限られた容量のリソースを保護するために使われるものです。従って、あまりにも頻繁なセマフォの解放はバグが生じているしるしです。 `value' を指定しない場合、デフォルトの値は 1 になります。


バージョン 3.3 で変更: ファクトリ関数からクラスに変更されました。

@end deffn

@node Semaphore example,Event objects,Semaphore objects,リファレンス<2>
@anchor{library/threading semaphore-example}@anchor{3632}@anchor{library/threading semaphore-examples}@anchor{3633}
@subsubsection @code{Semaphore} example


セマフォはしばしば、容量に限りのある資源、例えばデータベースサーバなどを保護するために使われます。リソースが固定の状況では、常に有限セマフォを使わなければなりません。主スレッドは、作業スレッドを立ち上げる前にセマフォを初期化します:

@example
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
@end example

作業スレッドは、ひとたび立ち上がると、サーバへ接続する必要が生じたときにセマフォの @code{acquire()} および @code{release()} メソッドを呼び出します:

@example
with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()
@end example

有限セマフォを使うと、セマフォを獲得回数以上に解放してしまうというプログラム上の間違いを見逃しにくくします。

@node Event objects,Timer objects,Semaphore example,リファレンス<2>
@anchor{library/threading event-objects}@anchor{3634}@anchor{library/threading id6}@anchor{3635}
@subsubsection Event objects


イベントは、あるスレッドがイベントを発信し、他のスレッドはそれを待つという、スレッド間で通信を行うための最も単純なメカニズムの一つです。

イベントオブジェクトは内部フラグを管理します。このフラグは @ref{3636,,set()} メソッドで値を true に、 @ref{3637,,clear()} メソッドで値を false にリセットします。 @ref{153e,,wait()} メソッドはフラグが true になるまでブロックします。

@geindex Event (threading のクラス)
@anchor{library/threading threading Event}@anchor{1370}
@deffn {クラス} threading.Event

イベントオブジェクトを実装しているクラスです。イベントは @ref{3636,,set()} メソッドを使うと @ref{e07,,True} に、 @ref{3637,,clear()} メソッドを使うと @ref{d2b,,False} にセットされるようなフラグを管理します。 @ref{153e,,wait()} メソッドは、全てのフラグが true になるまでブロックするようになっています。フラグの初期値は false です。


バージョン 3.3 で変更: ファクトリ関数からクラスに変更されました。


@geindex is_set() (threading.Event のメソッド)
@anchor{library/threading threading Event is_set}@anchor{35a}
@deffn {メソッド} is_set ()

内部フラグが真のとき @code{True} を返します。

メソッド @code{isSet} はこのメソッドの非推奨エイリアスです。
@end deffn

@geindex set() (threading.Event のメソッド)
@anchor{library/threading threading Event set}@anchor{3636}
@deffn {メソッド} set ()

内部フラグの値を true にセットします。フラグの値が true になるのを待っている全てのスレッドを起こします。一旦フラグが true になると、スレッドが @ref{153e,,wait()} を呼び出しても全くブロックしなくなります。
@end deffn

@geindex clear() (threading.Event のメソッド)
@anchor{library/threading threading Event clear}@anchor{3637}
@deffn {メソッド} clear ()

内部フラグの値を false にリセットします。以降は、 @ref{3636,,set()} を呼び出して再び内部フラグの値を true にセットするまで、 @ref{153e,,wait()} を呼び出したスレッドはブロックするようになります。
@end deffn

@geindex wait() (threading.Event のメソッド)
@anchor{library/threading threading Event wait}@anchor{153e}
@deffn {メソッド} wait (timeout=None)

Block as long as the internal flag is false and the timeout, if given,
has not expired. The return value represents the
reason that this blocking method returned; @code{True} if returning because
the internal flag is set to true, or @code{False} if a timeout is given and
the internal flag did not become true within the given wait time.

When the timeout argument is present and not @code{None}, it should be a
floating-point number specifying a timeout for the operation in seconds,
or fractions thereof.


バージョン 3.1 で変更: 以前は、このメソッドは常に @code{None} を返していました。

@end deffn
@end deffn

@node Timer objects,Barrier objects,Event objects,リファレンス<2>
@anchor{library/threading id7}@anchor{3638}@anchor{library/threading timer-objects}@anchor{3639}
@subsubsection Timer objects


このクラスは、一定時間経過後に実行される活動、すなわちタイマ活動を表現します。 @ref{1371,,Timer} は @ref{176,,Thread} のサブクラスであり、自作のスレッドを構築した一例でもあります。

Timers are started, as with threads, by calling their @ref{178,,Timer.start}
method.  The timer can be stopped (before its action has begun) by calling the
@ref{363a,,cancel()} method.  The interval the timer will wait before
executing its action may not be exactly the same as the interval specified by
the user.

例えば:

@example
def hello():
    print("hello, world")

t = Timer(30.0, hello)
t.start()  # after 30 seconds, "hello, world" will be printed
@end example

@geindex Timer (threading のクラス)
@anchor{library/threading threading Timer}@anchor{1371}
@deffn {クラス} threading.Timer (interval, function, args=None, kwargs=None)

`interval' 秒後に引数 `args' キーワード引数 `kwargs' で `function' を実行するようなタイマを生成します。`args*が `@w{`}None`@w{`} (デフォルト) なら空のリストが使用されます。*kwargs' が @code{None} (デフォルト) なら空の辞書が使用されます。


バージョン 3.3 で変更: ファクトリ関数からクラスに変更されました。


@geindex cancel() (threading.Timer のメソッド)
@anchor{library/threading threading Timer cancel}@anchor{363a}
@deffn {メソッド} cancel ()

タイマをストップして、その動作の実行をキャンセルします。このメソッドはタイマがまだ活動待ち状態にある場合にのみ動作します。
@end deffn
@end deffn

@node Barrier objects,,Timer objects,リファレンス<2>
@anchor{library/threading barrier-objects}@anchor{363b}
@subsubsection Barrier objects



Added in version 3.2.


このクラスは、互いを待つ必要のある固定の数のスレッドで使用するための単純な同期プリミティブを提供します。それぞれのスレッドは @ref{363c,,wait()} メソッドを呼ぶことによりバリアを通ろうとしてブロックします。すべてのスレッドがそれぞれの @ref{363c,,wait()} メソッドを呼び出した時点で、すべてのスレッドが同時に解放されます。

バリアは同じ数のスレッドに対して何度でも再利用することができます。

例として、クライアントとサーバの間でスレッドを同期させる単純な方法を紹介します:

@example
b = Barrier(2, timeout=5)

def server():
    start_server()
    b.wait()
    while True:
        connection = accept_connection()
        process_server_connection(connection)

def client():
    b.wait()
    while True:
        connection = make_connection()
        process_client_connection(connection)
@end example

@geindex Barrier (threading のクラス)
@anchor{library/threading threading Barrier}@anchor{13fc}
@deffn {クラス} threading.Barrier (parties, action=None, timeout=None)

`parties' 個のスレッドのためのバリアオブジェクトを作成します。 `action' は、もし提供されるなら呼び出し可能オブジェクトで、スレッドが解放される時にそのうちの1つによって呼ばれます。 `timeout' は、 @ref{363c,,wait()} メソッドに対して none が指定された場合のデフォルトのタイムアウト値です。

@geindex wait() (threading.Barrier のメソッド)
@anchor{library/threading threading Barrier wait}@anchor{363c}
@deffn {メソッド} wait (timeout=None)

バリアを通ります。バリアに対するすべてのスレッドがこの関数を呼んだ時に、それらは同時にすべて解放されます。`timeout' が提供される場合、それはクラスコンストラクタに渡された値に優先して使用されます。

返り値は 0 から `parties' -- 1 の範囲の整数で、それぞれのスレッドに対して異なります。これは、特別な後始末 (housekeeping) を行うスレッドを選択するために使用することができます。例えば:

@example
i = barrier.wait()
if i == 0:
    # Only one thread needs to print this
    print("passed the barrier")
@end example

`action' がコンストラクタに渡されていれば、スレッドのうちの1つが解放される前にそれを呼び出します。万一この呼び出しでエラーが発生した場合、バリアは broken な状態に陥ります。

この呼び出しがタイムアウトする場合、バリアは broken な状態に陥ります。

スレッドが待っている間にバリアが broken になるかリセットされた場合、このメソッドは @ref{13fe,,BrokenBarrierError} 例外を送出するかもしれません。
@end deffn

@geindex reset() (threading.Barrier のメソッド)
@anchor{library/threading threading Barrier reset}@anchor{363d}
@deffn {メソッド} reset ()

バリアをデフォルトの空の状態に戻します。そのバリアの上で待っているすべてのスレッドは @ref{13fe,,BrokenBarrierError} 例外を受け取ります。

状態が未知の他のスレッドがある場合、この関数を使用するのに何らかの外部同期を必要とするかもしれないことに注意してください。バリアが broken な場合、単にそれをそのままにして新しいものを作成する方がよいでしょう。
@end deffn

@geindex abort() (threading.Barrier のメソッド)
@anchor{library/threading threading Barrier abort}@anchor{363e}
@deffn {メソッド} abort ()

バリアを broken な状態にします。これによって、現在または将来の @ref{363c,,wait()} 呼び出しが @ref{13fe,,BrokenBarrierError} とともに失敗するようになります。これを使うと、例えばスレッドが異常終了する必要がある場合にアプリケーションがデッドロックするのを避けることができます。

スレッドのうちの1つが返ってこないことに対して自動的に保護するように、単純に常識的な `timeout' 値でバリアを作成することは望ましいかもしれません。
@end deffn

@geindex parties (threading.Barrier の属性)
@anchor{library/threading threading Barrier parties}@anchor{363f}
@deffn {の属性} parties

バリアを通るために要求されるスレッドの数。
@end deffn

@geindex n_waiting (threading.Barrier の属性)
@anchor{library/threading threading Barrier n_waiting}@anchor{3640}
@deffn {の属性} n_waiting

現在バリアの中で待っているスレッドの数。
@end deffn

@geindex broken (threading.Barrier の属性)
@anchor{library/threading threading Barrier broken}@anchor{3641}
@deffn {の属性} broken

バリアが broken な状態である場合に @code{True} となるブール値。
@end deffn
@end deffn

@geindex BrokenBarrierError
@anchor{library/threading threading BrokenBarrierError}@anchor{13fe}
@deffn {例外} threading.BrokenBarrierError

@ref{13fc,,Barrier} オブジェクトがリセットされるか broken な場合に、この例外 (@ref{244,,RuntimeError} のサブクラス) が送出されます。
@end deffn

@node with 文でのロック・条件変数・セマフォの使い方,,リファレンス<2>,threading --- スレッドベースの並列処理
@anchor{library/threading using-locks-conditions-and-semaphores-in-the-with-statement}@anchor{3642}@anchor{library/threading with-locks}@anchor{3624}
@subsubsection @code{with} 文でのロック・条件変数・セマフォの使い方


All of the objects provided by this module that have @code{acquire} and
@code{release} methods can be used as context managers for a @ref{186,,with}
statement.  The @code{acquire} method will be called when the block is
entered, and @code{release} will be called when the block is exited.  Hence,
the following snippet:

@example
with some_lock:
    # do something...
@end example

は、以下と同じです

@example
some_lock.acquire()
try:
    # do something...
finally:
    some_lock.release()
@end example

現在のところ、 @ref{19f4,,Lock} 、 @ref{32e,,RLock} 、 @ref{136d,,Condition} 、 @ref{136e,,Semaphore} 、 @ref{136f,,BoundedSemaphore} を @ref{186,,with} 文のコンテキストマネージャとして使うことができます。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node multiprocessing --- プロセスベースの並列処理,multiprocessing shared_memory --- プロセス間で直接アクセス可能な共有メモリ,threading --- スレッドベースの並列処理,並行実行
@anchor{library/multiprocessing doc}@anchor{3643}@anchor{library/multiprocessing module-multiprocessing}@anchor{98}@anchor{library/multiprocessing multiprocessing-process-based-parallelism}@anchor{3644}@anchor{library/multiprocessing translation-repo}@anchor{3645}
@subsection @code{multiprocessing} --- プロセスベースの並列処理


@geindex module; multiprocessing

`ソースコード:' Lib/multiprocessing/@footnote{https://github.com/python/cpython/tree/3.14/Lib/multiprocessing/}


__________________________________________________________________


@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

@menu
* はじめに: はじめに<9>. 
* リファレンス: リファレンス<3>. 
* プログラミングガイドライン:: 
* 使用例: 使用例<21>. 

@end menu

@node はじめに<9>,リファレンス<3>,,multiprocessing --- プロセスベースの並列処理
@anchor{library/multiprocessing introduction}@anchor{3646}
@subsubsection はじめに


@code{multiprocessing} is a package that supports spawning processes using an
API similar to the @ref{f3,,threading} module.  The @code{multiprocessing} package
offers both local and remote concurrency, effectively side-stepping the
@ref{474,,Global Interpreter Lock} by using
subprocesses instead of threads.  Due
to this, the @code{multiprocessing} module allows the programmer to fully
leverage multiple processors on a given machine.  It runs on both POSIX and
Windows.

The @code{multiprocessing} module also introduces the
@ref{116d,,Pool} object which offers a convenient means of
parallelizing the execution of a function across multiple input values,
distributing the input data across processes (data parallelism).  The following
example demonstrates the common practice of defining such functions in a module
so that child processes can successfully import that module.  This basic example
of data parallelism using @ref{116d,,Pool},

@example
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))
@end example

標準出力に以下が出力されます:

@example
[1, 4, 9]
@end example

The @code{multiprocessing} module also introduces APIs which do not have
analogs in the @ref{f3,,threading} module, like the ability to @ref{1857,,terminate}, @ref{251,,interrupt} or @ref{d4f,,kill} a running process.


@subsubheading 参考


@ref{1d6,,concurrent.futures.ProcessPoolExecutor} offers a higher level interface
to push tasks to a background process without blocking execution of the
calling process. Compared to using the @ref{116d,,Pool}
interface directly, the @ref{24,,concurrent.futures} API more readily allows
the submission of work to the underlying process pool to be separated from
waiting for the results.


@menu
* Process クラス:: 
* コンテキストと開始方式:: 
* プロセス間でのオブジェクト交換:: 
* プロセス間の同期:: 
* プロセス間での状態の共有:: 
* ワーカープロセスのプールを使用:: 

@end menu

@node Process クラス,コンテキストと開始方式,,はじめに<9>
@anchor{library/multiprocessing the-process-class}@anchor{3647}
@subsubsection @code{Process} クラス


In @code{multiprocessing}, processes are spawned by creating a @ref{252,,Process}
object and then calling its @ref{15a9,,start()} method.  @ref{252,,Process}
follows the API of @ref{176,,threading.Thread}.  A trivial example of a
multiprocess program is

@example
from multiprocessing import Process

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()
@end example

実行された個々のプロセス ID を表示するために拡張したサンプルコードを以下に示します:

@example
from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def f(name):
    info('function f')
    print('hello', name)

if __name__ == '__main__':
    info('main line')
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()
@end example

なぜ @code{if __name__ == '__main__'} という記述が必要かは @ref{3648,,プログラミングガイドライン} を参照してください。

The arguments to @ref{252,,Process} usually need to be unpickleable from within
the child process. If you tried typing the above example directly into a REPL it
could lead to an @ref{5f0,,AttributeError} in the child process trying to locate the
`f' function in the @code{__main__} module.

@node コンテキストと開始方式,プロセス間でのオブジェクト交換,Process クラス,はじめに<9>
@anchor{library/multiprocessing contexts-and-start-methods}@anchor{3649}@anchor{library/multiprocessing multiprocessing-start-methods}@anchor{1d5}
@subsubsection コンテキストと開始方式


Depending on the platform, @code{multiprocessing} supports three ways
to start a process.  These `start methods' are

@quotation
@anchor{library/multiprocessing multiprocessing-start-method-spawn}@anchor{1d8}

@table @asis

@item `spawn'

親プロセスは新たに Python インタープリタープロセスを開始します。子プロセスはプロセスオブジェクトの @ref{364a,,run()} メソッドの実行に必要なリソースのみ継承します。特に、親プロセスからの不要なファイル記述子とハンドルは継承されません。この方式を使用したプロセスの開始は `fork' や `forkserver' に比べ遅くなります。

Available on POSIX and Windows platforms.  The default on Windows and macOS.
@end table
@anchor{library/multiprocessing multiprocessing-start-method-fork}@anchor{1d7}

@table @asis

@item `fork'

親プロセスは @ref{4b5,,os.fork()} を使用して Python インタープリターをフォークします。子プロセスはそれが開始されるとき、事実上親プロセスと同一になります。親プロセスのリソースはすべて子プロセスに継承されます。マルチスレッドプロセスのフォークは安全性に問題があることに注意してください。

Available on POSIX systems.


バージョン 3.14 で変更: This is no longer the default start method on any platform.
Code that requires `fork' must explicitly specify that via
@ref{24a,,get_context()} or @ref{24b,,set_start_method()}.



バージョン 3.12 で変更: If Python is able to detect that your process has multiple threads, the
@ref{4b5,,os.fork()} function that this start method calls internally will
raise a @ref{1a3,,DeprecationWarning}. Use a different start method.
See the @ref{4b5,,os.fork()} documentation for further explanation.

@end table
@anchor{library/multiprocessing multiprocessing-start-method-forkserver}@anchor{1d4}

@table @asis

@item `forkserver'

When the program starts and selects the `forkserver' start method,
a server process is spawned.  From then on, whenever a new process
is needed, the parent process connects to the server and requests
that it fork a new process.  The fork server process is single threaded
unless system libraries or preloaded imports spawn threads as a
side-effect so it is generally safe for it to use @ref{4b5,,os.fork()}.
No unnecessary resources are inherited.

Available on POSIX platforms which support passing file descriptors over
Unix pipes such as Linux.  The default on those.


バージョン 3.14 で変更: This became the default start method on POSIX platforms.

@end table
@end quotation


バージョン 3.4 で変更: `spawn' added on all POSIX platforms, and `forkserver' added for
some POSIX platforms.
Child processes no longer inherit all of the parents inheritable
handles on Windows.



バージョン 3.8 で変更: On macOS, the `spawn' start method is now the default.  The `fork' start
method should be considered unsafe as it can lead to crashes of the
subprocess as macOS system libraries may start threads. See bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725}.



バージョン 3.14 で変更: On POSIX platforms the default start method was changed from `fork' to
`forkserver' to retain the performance but avoid common multithreaded
process incompatibilities. See gh-84559@footnote{https://github.com/python/cpython/issues/84559}.


On POSIX using the `spawn' or `forkserver' start methods will also
start a `resource tracker' process which tracks the unlinked named
system resources (such as named semaphores or
@ref{19d8,,SharedMemory} objects) created
by processes of the program.  When all processes
have exited the resource tracker unlinks any remaining tracked object.
Usually there should be none, but if a process was killed by a signal
there may be some "leaked" resources.  (Neither leaked semaphores nor shared
memory segments will be automatically unlinked until the next reboot. This is
problematic for both objects because the system allows only a limited number of
named semaphores, and shared memory segments occupy some space in the main
memory.)

開始方式はメインモジュールの @code{if __name__ == '__main__'} 節内で、関数 @ref{24b,,set_start_method()} によって指定します。以下に例を示します:

@example
import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    mp.set_start_method('spawn')
    q = mp.Queue()
    p = mp.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join()
@end example

関数 @ref{24b,,set_start_method()} はプログラム内で複数回使用してはいけません。

もうひとつの方法として、@ref{24a,,get_context()} を使用してコンテキストオブジェクトを取得することができます。コンテキストオブジェクトは multiprocessing モジュールと同じ API を持ち、同じプログラム内で複数の開始方式を使用できます。

@example
import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join()
@end example

あるコンテキストに関連したオブジェクトは、異なるコンテキストのプロセスとは互換性がない場合があることに注意してください。特に、`fork' コンテキストを使用して作成されたロックは、`spawn' あるいは `forkserver' を使用して開始されたプロセスに渡すことはできません。

Libraries using @code{multiprocessing} or
@ref{1d6,,ProcessPoolExecutor} should be designed to allow
their users to provide their own multiprocessing context.  Using a specific
context of your own within a library can lead to incompatibilities with the
rest of the library user's application.  Always document if your library
requires a specific start method.

@cartouche
@quotation 警告 
The @code{'spawn'} and @code{'forkserver'} start methods generally cannot
be used with "frozen" executables (i.e., binaries produced by
packages like `PyInstaller' and `cx_Freeze') on POSIX systems.
The @code{'fork'} start method may work if code does not use threads.
@end quotation
@end cartouche

@node プロセス間でのオブジェクト交換,プロセス間の同期,コンテキストと開始方式,はじめに<9>
@anchor{library/multiprocessing exchanging-objects-between-processes}@anchor{364b}
@subsubsection プロセス間でのオブジェクト交換


@code{multiprocessing} supports two types of communication channel between
processes:

`キュー (Queue)'

@quotation

@ref{1b89,,Queue} クラスは @ref{15ac,,queue.Queue} クラスとほとんど同じように使うことができます。以下に例を示します:

@example
from multiprocessing import Process, Queue

def f(q):
    q.put([42, None, 'hello'])

if __name__ == '__main__':
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print(q.get())    # prints "[42, None, 'hello']"
    p.join()
@end example

Queues are thread and process safe.
Any object put into a @code{multiprocessing} queue will be serialized.
@end quotation

`パイプ (Pipe)'

@quotation

@ref{364c,,Pipe()} 関数はパイプで繋がれたコネクションオブジェクトのペアを返します。デフォルトでは双方向性パイプを返します。以下に例を示します:

@example
from multiprocessing import Process, Pipe

def f(conn):
    conn.send([42, None, 'hello'])
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print(parent_conn.recv())   # prints "[42, None, 'hello']"
    p.join()
@end example

パイプのそれぞれの端を表す2つのコネクションオブジェクトが @ref{364c,,Pipe()} 関数から返されます。各コネクションオブジェクトには、 @code{send()}、 @code{recv()}、その他のメソッドがあります。2つのプロセス (またはスレッド) がパイプの `同じ' 端で同時に読み込みや書き込みを行うと、パイプ内のデータが破損してしまうかもしれないことに注意してください。もちろん、各プロセスがパイプの別々の端を同時に使用するならば、データが破壊される危険性はありません。

The @code{send()} method serializes the object and
@code{recv()} re-creates the object.
@end quotation

@node プロセス間の同期,プロセス間での状態の共有,プロセス間でのオブジェクト交換,はじめに<9>
@anchor{library/multiprocessing synchronization-between-processes}@anchor{364d}
@subsubsection プロセス間の同期


@code{multiprocessing} contains equivalents of all the synchronization
primitives from @ref{f3,,threading}.  For instance one can use a lock to ensure
that only one process prints to standard output at a time:

@example
from multiprocessing import Process, Lock

def f(l, i):
    l.acquire()
    try:
        print('hello world', i)
    finally:
        l.release()

if __name__ == '__main__':
    lock = Lock()

    for num in range(10):
        Process(target=f, args=(lock, num)).start()
@end example

ロックを使用しないで標準出力に書き込んだ場合は、各プロセスからの出力がごちゃまぜになってしまいます。

@node プロセス間での状態の共有,ワーカープロセスのプールを使用,プロセス間の同期,はじめに<9>
@anchor{library/multiprocessing sharing-state-between-processes}@anchor{364e}
@subsubsection プロセス間での状態の共有


これまでの話の流れで触れたとおり、並行プログラミングを行うときには、できるかぎり状態を共有しないのが定石です。複数のプロセスを使用するときは特にそうでしょう。

However, if you really do need to use some shared data then
@code{multiprocessing} provides a couple of ways of doing so.

`共有メモリ (Shared memory)'

@quotation

データを共有メモリ上に保持するために @ref{364f,,Value} クラス、もしくは @ref{3650,,Array} クラスを使用することができます。以下のサンプルコードを使って、この機能についてみていきましょう

@example
from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])
@end example

このサンプルコードを実行すると以下のように表示されます

@example
3.1415927
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
@end example

@code{num} と @code{arr} を生成するときに使用されている、引数 @code{'d'} と @code{'i'} は @ref{8,,array} モジュールにより使用される種別の型コードです。ここで使用されている @code{'d'} は倍精度浮動小数、 @code{'i'} は符号付整数を表します。これらの共有オブジェクトは、プロセスセーフでありスレッドセーフです。

共有メモリを使用して、さらに柔軟なプログラミングを行うには @ref{9e,,multiprocessing.sharedctypes} モジュールを使用します。このモジュールは共有メモリから割り当てられた任意の ctypes オブジェクトの生成をサポートします。
@end quotation

`サーバープロセス (Server process)'

@quotation

@ref{250,,Manager()} 関数により生成されたマネージャーオブジェクトはサーバープロセスを管理します。マネージャーオブジェクトは Python のオブジェクトを保持して、他のプロセスがプロキシ経由でその Python オブジェクトを操作することができます。

A manager returned by @ref{250,,Manager()} will support types
@ref{24d,,list}, @ref{183,,dict}, @ref{184,,set}, @ref{3651,,Namespace}, @ref{1853,,Lock},
@ref{1854,,RLock}, @ref{3652,,Semaphore}, @ref{3653,,BoundedSemaphore},
@ref{3654,,Condition}, @ref{1c06,,Event}, @ref{3655,,Barrier},
@ref{1b89,,Queue}, @ref{364f,,Value} and @ref{3650,,Array}.  For example,

@example
from multiprocessing import Process, Manager

def f(d, l, s):
    d[1] = '1'
    d['2'] = 2
    d[0.25] = None
    l.reverse()
    s.add('a')
    s.add('b')

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        l = manager.list(range(10))
        s = manager.set()

        p = Process(target=f, args=(d, l, s))
        p.start()
        p.join()

        print(d)
        print(l)
        print(s)
@end example

このサンプルコードを実行すると以下のように表示されます

@example
@{0.25: None, 1: '1', '2': 2@}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
@{'a', 'b'@}
@end example

サーバープロセスのマネージャーオブジェクトは共有メモリのオブジェクトよりも柔軟であるといえます。それは、どのような型のオブジェクトでも使えるからです。また、1つのマネージャーオブジェクトはネットワーク経由で他のコンピューター上のプロセスによって共有することもできます。しかし、共有メモリより動作が遅いという欠点があります。
@end quotation

@node ワーカープロセスのプールを使用,,プロセス間での状態の共有,はじめに<9>
@anchor{library/multiprocessing using-a-pool-of-workers}@anchor{3656}
@subsubsection ワーカープロセスのプールを使用


@ref{116d,,Pool} クラスは、ワーカープロセスをプールする機能を備えています。このクラスには、異なる方法でワーカープロセスへタスクを割り当てるいくつかのメソッドがあります。

例えば:

@example
from multiprocessing import Pool, TimeoutError
import time
import os

def f(x):
    return x*x

if __name__ == '__main__':
    # start 4 worker processes
    with Pool(processes=4) as pool:

        # print "[0, 1, 4,..., 81]"
        print(pool.map(f, range(10)))

        # print same numbers in arbitrary order
        for i in pool.imap_unordered(f, range(10)):
            print(i)

        # evaluate "f(20)" asynchronously
        res = pool.apply_async(f, (20,))      # runs in *only* one process
        print(res.get(timeout=1))             # prints "400"

        # evaluate "os.getpid()" asynchronously
        res = pool.apply_async(os.getpid, ()) # runs in *only* one process
        print(res.get(timeout=1))             # prints the PID of that process

        # launching multiple evaluations asynchronously *may* use more processes
        multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
        print([res.get(timeout=1) for res in multiple_results])

        # make a single worker sleep for 10 seconds
        res = pool.apply_async(time.sleep, (10,))
        try:
            print(res.get(timeout=1))
        except TimeoutError:
            print("We lacked patience and got a multiprocessing.TimeoutError")

        print("For the moment, the pool remains available for more work")

    # exiting the 'with'-block has stopped the pool
    print("Now the pool is closed and no longer available")
@end example

プールオブジェクトのメソッドは、そのプールを作成したプロセスのみが呼び出すべきです。

@cartouche
@quotation 注釈 
このパッケージに含まれる機能を使用するためには、子プロセスから @code{__main__} モジュールをインポートできる必要があります。このことについては @ref{3648,,プログラミングガイドライン} で触れていますが、ここであらためて強調しておきます。なぜかというと、いくつかのサンプルコード、例えば @ref{116d,,multiprocessing.pool.Pool} のサンプルはインタラクティブシェル上では動作しないからです。以下に例を示します:

@example
>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
...     return x*x
...
>>> with p:
...     p.map(f, [1,2,3])
Process PoolWorker-1:
Process PoolWorker-2:
Process PoolWorker-3:
Traceback (most recent call last):
Traceback (most recent call last):
Traceback (most recent call last):
AttributeError: Can't get attribute 'f' on <module '__main__' (<class '_frozen_importlib.BuiltinImporter'>)>
AttributeError: Can't get attribute 'f' on <module '__main__' (<class '_frozen_importlib.BuiltinImporter'>)>
AttributeError: Can't get attribute 'f' on <module '__main__' (<class '_frozen_importlib.BuiltinImporter'>)>
@end example

(もしこのコードを試すなら、実際には3つの完全なトレースバックがばらばらの順番で出力されますし、親プロセスを何らかの方法で止める必要があります。)
@end quotation
@end cartouche

@node リファレンス<3>,プログラミングガイドライン,はじめに<9>,multiprocessing --- プロセスベースの並列処理
@anchor{library/multiprocessing reference}@anchor{3657}
@subsubsection リファレンス


The @code{multiprocessing} package mostly replicates the API of the
@ref{f3,,threading} module.

@menu
* Global start method:: 
* Process クラスと例外:: 
* パイプ (Pipe) とキュー (Queue): パイプ Pipe とキュー Queue. 
* その他: その他<5>. 
* Connection オブジェクト: Connection オブジェクト<2>. 
* 同期プリミティブ:: 
* 共有 ctypes オブジェクト:: 
* マネージャー:: 
* Proxy オブジェクト:: 
* プロセスプール:: 
* リスナーとクライアント:: 
* 認証キー:: 
* ログ記録: ログ記録<2>. 
* The multiprocessing.dummy module: The multiprocessing dummy module. 

@end menu

@node Global start method,Process クラスと例外,,リファレンス<3>
@anchor{library/multiprocessing global-start-method}@anchor{3658}@anchor{library/multiprocessing id1}@anchor{3659}
@subsubsection Global start method


Python supports several ways to create and initialize a process.
The global start method sets the default mechanism for creating a process.

Several multiprocessing functions and methods that may also instantiate
certain objects will implicitly set the global start method to the system's default,
if it hasn’t been set already. The global start method can only be set once.
If you need to change the start method from the system default, you must
proactively set the global start method before calling functions or methods,
or creating these objects.

@node Process クラスと例外,パイプ Pipe とキュー Queue,Global start method,リファレンス<3>
@anchor{library/multiprocessing process-and-exceptions}@anchor{365a}
@subsubsection @code{Process} クラスと例外


@geindex Process (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing Process}@anchor{252}
@deffn {クラス} multiprocessing.Process (group=None, target=None, name=None, args=(), kwargs=@{@}, *, daemon=None)

Process オブジェクトは各プロセスの処理を表します。 @ref{252,,Process} クラスは @ref{176,,threading.Thread} クラスのすべてのメソッドと同じインターフェースを提供します。

The constructor should always be called with keyword arguments. `group'
should always be @code{None}; it exists solely for compatibility with
@ref{176,,threading.Thread}.  `target' is the callable object to be invoked by
the @ref{364a,,run()} method.  It defaults to @code{None}, meaning nothing is
called. `name' is the process name (see @ref{365b,,name} for more details).
`args' is the argument tuple for the target invocation.  `kwargs' is a
dictionary of keyword arguments for the target invocation.  If provided,
the keyword-only `daemon' argument sets the process @ref{365c,,daemon} flag
to @code{True} or @code{False}.  If @code{None} (the default), this flag will be
inherited from the creating process.

デフォルトでは、`target' に何の引数も与えられません。(実) 引数 `args' (デフォルトは`@w{`}()`@w{`})は、`target' に渡す引数のリストまたはタプルを指定するために使用されます。

If a subclass overrides the constructor, it must make sure it invokes the
base class constructor (@code{super().__init__()}) before doing anything else
to the process.

@cartouche
@quotation 注釈 
In general, all arguments to @ref{252,,Process} must be picklable.  This is
frequently observed when trying to create a @ref{252,,Process} or use a
@ref{1d6,,concurrent.futures.ProcessPoolExecutor} from a REPL with a
locally defined `target' function.

Passing a callable object defined in the current REPL session causes the
child process to die via an uncaught @ref{5f0,,AttributeError} exception when
starting as `target' must have been defined within an importable module
in order to be loaded during unpickling.

Example of this uncatchable error from the child:

@example
>>> import multiprocessing as mp
>>> def knigit():
...     print("Ni!")
...
>>> process = mp.Process(target=knigit)
>>> process.start()
>>> Traceback (most recent call last):
  File ".../multiprocessing/spawn.py", line ..., in spawn_main
  File ".../multiprocessing/spawn.py", line ..., in _main
AttributeError: module '__main__' has no attribute 'knigit'
>>> process
<SpawnProcess name='SpawnProcess-1' pid=379473 parent=378707 stopped exitcode=1>
@end example

See @ref{365d,,開始方式が spawn および forkserver の場合}.  While this restriction is
not true if using the @code{"fork"} start method, as of Python @code{3.14} that
is no longer the default on any platform.  See
@ref{1d5,,コンテキストと開始方式}.
See also gh-132898@footnote{https://github.com/python/cpython/issues/132898}.
@end quotation
@end cartouche


バージョン 3.3 で変更: Added the `daemon' parameter.


@geindex run() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process run}@anchor{364a}
@deffn {メソッド} run ()

プロセスが実行する処理を表すメソッドです。

このメソッドはサブクラスでオーバーライドすることができます。標準の @ref{364a,,run()} メソッドは、コンストラクターの target 引数として渡された呼び出し可能オブジェクトを呼び出します。もしコンストラクターに `args' もしくは `kwargs' 引数が渡されていれば、呼び出すオブジェクトにこれらの引数を渡します。

@ref{252,,Process} に渡される `args' の引数にリストやタプルを使っても、同じ効果が得られます。

以下はプログラム例です:

@example
>>> from multiprocessing import Process
>>> p = Process(target=print, args=[1])
>>> p.run()
1
>>> p = Process(target=print, args=(1,))
>>> p.run()
1
@end example
@end deffn

@geindex start() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process start}@anchor{15a9}
@deffn {メソッド} start ()

プロセスの処理を開始するためのメソッドです。

各 Process オブジェクトに対し、このメソッドが2回以上呼び出されてはいけません。各プロセスでオブジェクトの @ref{364a,,run()} メソッドを呼び出す準備を行います。
@end deffn

@geindex join() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process join}@anchor{15ab}
@deffn {メソッド} join ([timeout])

オプションの引数 `timeout' が @code{None} (デフォルト) の場合、 @ref{15ab,,join()} メソッドが呼ばれたプロセスは処理が終了するまでブロックします。
`timeout' が正の数である場合、最大 `timeout' 秒ブロックします。
プロセスが終了あるいはタイムアウトした場合、メソッドは @code{None} を返すことに注意してください。
プロセスの @ref{365e,,exitcode} を確認し終了したかどうかを判断してください。

1つのプロセスは何回も join されることができます。

プロセスは自分自身を join することはできません。それはデッドロックを引き起こすことがあるからです。プロセスが start される前に join しようとするとエラーが発生します。
@end deffn

@geindex name (multiprocessing.Process の属性)
@anchor{library/multiprocessing multiprocessing Process name}@anchor{365b}
@deffn {の属性} name

プロセスの名前。名前は識別のためだけに使用される文字列です。それ自体には特別な意味はありません。複数のプロセスに同じ名前が与えられても構いません。

最初の名前はコンストラクターによってセットされます。コンストラクターに明示的な名前が渡されない場合、 'Process-N@w{[1]}:N@w{[2]}:...:N@w{[k]}' 形式の名前が構築されます。ここでそれぞれの N@w{[k]} はその親のN番目の子供です。
@end deffn

@geindex is_alive() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process is_alive}@anchor{15aa}
@deffn {メソッド} is_alive ()

プロセスが実行中かを判別します。

おおまかに言って、プロセスオブジェクトは @ref{15a9,,start()} メソッドを呼び出してから子プロセス終了までの期間が実行中となります。
@end deffn

@geindex daemon (multiprocessing.Process の属性)
@anchor{library/multiprocessing multiprocessing Process daemon}@anchor{365c}
@deffn {の属性} daemon

デーモンプロセスであるかのフラグであり、ブール値です。この属性は @ref{15a9,,start()} が呼び出される前に設定されている必要があります。

初期値は作成するプロセスから継承します。

あるプロセスが終了するとき、そのプロセスはその子プロセスであるデーモンプロセスすべてを終了させようとします。

デーモンプロセスは子プロセスを作成できないことに注意してください。もし作成できてしまうと、そのデーモンプロセスの親プロセスが終了したときにデーモンプロセスの子プロセスが孤児になってしまう場合があるからです。さらに言えば、デーモンプロセスはUnix デーモンやサービスでは `なく' 通常のプロセスであり、非デーモンプロセスが終了すると終了されます (そして join されません)。
@end deffn

@ref{176,,threading.Thread} クラスの API に加えて @ref{252,,Process} クラスのオブジェクトには以下の属性およびメソッドがあります:

@geindex pid (multiprocessing.Process の属性)
@anchor{library/multiprocessing multiprocessing Process pid}@anchor{365f}
@deffn {の属性} pid

プロセスIDを返します。プロセスの生成前は @code{None} が設定されています。
@end deffn

@geindex exitcode (multiprocessing.Process の属性)
@anchor{library/multiprocessing multiprocessing Process exitcode}@anchor{365e}
@deffn {の属性} exitcode

The child's exit code.  This will be @code{None} if the process has not yet
terminated.

If the child's @ref{364a,,run()} method returned normally, the exit code
will be 0.  If it terminated via @ref{277,,sys.exit()} with an integer
argument `N', the exit code will be `N'.

If the child terminated due to an exception not caught within
@ref{364a,,run()}, the exit code will be 1.  If it was terminated by
signal `N', the exit code will be the negative value `-N'.
@end deffn

@geindex authkey (multiprocessing.Process の属性)
@anchor{library/multiprocessing multiprocessing Process authkey}@anchor{3660}
@deffn {の属性} authkey

プロセスの認証キーです (バイト文字列です)。

When @code{multiprocessing} is initialized the main process is assigned a
random string using @ref{746,,os.urandom()}.

@ref{252,,Process} クラスのオブジェクトの作成時にその親プロセスから認証キーを継承します。もしくは @ref{3660,,authkey} に別のバイト文字列を設定することもできます。

詳細は @ref{3661,,認証キー} を参照してください。
@end deffn

@geindex sentinel (multiprocessing.Process の属性)
@anchor{library/multiprocessing multiprocessing Process sentinel}@anchor{12f9}
@deffn {の属性} sentinel

プロセスが終了するときに "ready" となるシステムオブジェクトの数値ハンドル。

You can use this value if you want to wait on several events at
once using @ref{12f7,,multiprocessing.connection.wait()}.  Otherwise
calling @ref{15ab,,join()} is simpler.

On Windows, this is an OS handle usable with the @code{WaitForSingleObject}
and @code{WaitForMultipleObjects} family of API calls.  On POSIX, this is
a file descriptor usable with primitives from the @ref{c6,,select} module.


Added in version 3.3.

@end deffn

@geindex interrupt() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process interrupt}@anchor{251}
@deffn {メソッド} interrupt ()

Terminate the process. Works on POSIX using the @ref{253,,SIGINT} signal.
Behavior on Windows is undefined.

By default, this terminates the child process by raising @ref{bc5,,KeyboardInterrupt}.
This behavior can be altered by setting the respective signal handler in the child
process @ref{134c,,signal.signal()} for @ref{253,,SIGINT}.

Note: if the child process catches and discards @ref{bc5,,KeyboardInterrupt}, the
process will not be terminated.

Note: the default behavior will also set @ref{365e,,exitcode} to @code{1} as if an
uncaught exception was raised in the child process. To have a different
@ref{365e,,exitcode} you may simply catch @ref{bc5,,KeyboardInterrupt} and call
@code{exit(your_code)}.


Added in version 3.14.

@end deffn

@geindex terminate() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process terminate}@anchor{1857}
@deffn {メソッド} terminate ()

Terminate the process.  On POSIX this is done using the @ref{15f8,,SIGTERM} signal;
on Windows @code{TerminateProcess()} is used.  Note that exit handlers and
finally clauses, etc., will not be executed.

このメソッドにより終了するプロセスの子孫プロセスは、終了 `しません' 。そういった子孫プロセスは単純に孤児になります。

@cartouche
@quotation 警告 
このメソッドの使用時に、関連付けられたプロセスがパイプやキューを使用している場合には、使用中のパイプやキューが破損して他のプロセスから使用できなくなる可能性があります。同様に、プロセスがロックやセマフォなどを取得している場合には、このプロセスが終了してしまうと他のプロセスのデッドロックの原因になるでしょう。
@end quotation
@end cartouche
@end deffn

@geindex kill() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process kill}@anchor{d4f}
@deffn {メソッド} kill ()

Same as @ref{1857,,terminate()} but using the @code{SIGKILL} signal on POSIX.


Added in version 3.7.

@end deffn

@geindex close() (multiprocessing.Process のメソッド)
@anchor{library/multiprocessing multiprocessing Process close}@anchor{d4e}
@deffn {メソッド} close ()

@ref{252,,Process} オブジェクトを閉じ、関連付けられていたすべてのリソースを開放します。中のプロセスが実行中であった場合、@ref{2ec,,ValueError} を送出します。@ref{d4e,,close()} が成功した場合、@ref{252,,Process} オブジェクトの他のメソッドや属性は、ほとんどが @ref{2ec,,ValueError} を送出します。


Added in version 3.7.

@end deffn

プロセスオブジェクトが作成したプロセスのみが @ref{15a9,,start()}, @ref{15ab,,join()}, @ref{15aa,,is_alive()}, @ref{1857,,terminate()} と @ref{365e,,exitcode} のメソッドを呼び出すべきです。

以下の例では @ref{252,,Process} のメソッドの使い方を示しています:

@example
>>> import multiprocessing, time, signal
>>> mp_context = multiprocessing.get_context('spawn')
>>> p = mp_context.Process(target=time.sleep, args=(1000,))
>>> print(p, p.is_alive())
<...Process ... initial> False
>>> p.start()
>>> print(p, p.is_alive())
<...Process ... started> True
>>> p.terminate()
>>> time.sleep(0.1)
>>> print(p, p.is_alive())
<...Process ... stopped exitcode=-SIGTERM> False
>>> p.exitcode == -signal.SIGTERM
True
@end example
@end deffn

@geindex ProcessError
@anchor{library/multiprocessing multiprocessing ProcessError}@anchor{3662}
@deffn {例外} multiprocessing.ProcessError

The base class of all @code{multiprocessing} exceptions.
@end deffn

@geindex BufferTooShort
@anchor{library/multiprocessing multiprocessing BufferTooShort}@anchor{3663}
@deffn {例外} multiprocessing.BufferTooShort

Exception raised by @code{Connection.recv_bytes_into()} when the supplied
buffer object is too small for the message read.

@code{e} が @ref{3663,,BufferTooShort} のインスタンスであるとすると、 @code{e.args[0]} はそのメッセージをバイト文字列で与えるものです。
@end deffn

@geindex AuthenticationError
@anchor{library/multiprocessing multiprocessing AuthenticationError}@anchor{3664}
@deffn {例外} multiprocessing.AuthenticationError

認証エラーがあった場合に送出されます。
@end deffn

@geindex TimeoutError
@anchor{library/multiprocessing multiprocessing TimeoutError}@anchor{3665}
@deffn {例外} multiprocessing.TimeoutError

タイムアウトをサポートするメソッドでタイムアウトが過ぎたときに送出されます。
@end deffn

@node パイプ Pipe とキュー Queue,その他<5>,Process クラスと例外,リファレンス<3>
@anchor{library/multiprocessing pipes-and-queues}@anchor{3666}
@subsubsection パイプ (Pipe) とキュー (Queue)


複数のプロセスを使う場合、一般的にはメッセージパッシングをプロセス間通信に使用し、ロックのような同期プリミティブを使用しないようにします。

メッセージのやりとりのために @ref{364c,,Pipe()} (2つのプロセス間の通信用)、もしくはキュー (複数のメッセージ生成プロセス (producer)、消費プロセス (consumer) の実現用) を使うことができます。

@ref{1b89,,Queue}, @ref{b10,,SimpleQueue} と @ref{3667,,JoinableQueue} 型は複数プロセスから生成/消費を行う @abbr{FIFO} キューです。これらのキューは標準ライブラリの @ref{15ac,,queue.Queue} を模倣しています。 @ref{1b89,,Queue} には Python 2.5 の @ref{15ac,,queue.Queue} クラスで導入された @ref{3668,,task_done()} と @ref{3669,,join()} メソッドがないことが違う点です。

もし @ref{3667,,JoinableQueue} を使用するなら、キューから削除される各タスクのために @ref{366a,,JoinableQueue.task_done()} を呼び出さなければ `なりません' 。さもないと、いつか完了していないタスクを数えるためのセマフォがオーバーフローし、例外を発生させるでしょう。

One difference from other Python queue implementations, is that @code{multiprocessing}
queues serializes all objects that are put into them using @ref{ab,,pickle}.
The object returned by the get method is a re-created object that does not share
memory with the original object.

管理オブジェクトを使用することで共有キューを作成できることも覚えておいてください。詳細は @ref{366b,,マネージャー} を参照してください。

@cartouche
@quotation 注釈 
@code{multiprocessing} uses the usual @ref{366c,,queue.Empty} and
@ref{366d,,queue.Full} exceptions to signal a timeout.  They are not available in
the @code{multiprocessing} namespace so you need to import them from
@ref{bb,,queue}.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
オブジェクトがキューに追加される際、そのオブジェクトは pickle 化されています。そのため、バックグラウンドのスレッドが後になって下位層のパイプに pickle 化されたデータをフラッシュすることがあります。これにより、少し驚くような結果になりますが、実際に問題になることはないはずです。これが問題になるような状況では、かわりに @ref{366b,,manager} を使ってキューを作成することができるからです。


@enumerate 

@item 
空のキューの中にオブジェクトを追加した後、キューの @ref{1968,,empty()} メソッドが @ref{d2b,,False} を返すまでの間にごくわずかな遅延が起きることがあり、@ref{366e,,get_nowait()} が @ref{366c,,queue.Empty} を発生させることなく制御が呼び出し元に返ってしまうことがあります。

@item 
複数のプロセスがオブジェクトをキューに詰めている場合、キューの反対側ではオブジェクトが詰められたのとは違う順序で取得される可能性があります。ただし、同一のプロセスから詰め込まれたオブジェクトは、それらのオブジェクト間では、必ず期待どおりの順序になります。
@end enumerate
@end quotation
@end cartouche

@cartouche
@quotation 警告 
@ref{1b89,,Queue} を利用しようとしている最中にプロセスを @ref{1857,,Process.terminate()} や @ref{157f,,os.kill()} で終了させる場合、キューにあるデータは破損し易くなります。終了した後で他のプロセスがキューを利用しようとすると、例外を発生させる可能性があります。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
上述したように、もし子プロセスがキューへ要素を追加するなら (かつ @ref{366f,,JoinableQueue.cancel_join_thread} を使用しないなら) そのプロセスはバッファーされたすべての要素がパイプへフラッシュされるまで終了しません。

これは、そのプロセスを join しようとする場合、キューに追加されたすべての要素が消費されたことが確実でないかぎり、デッドロックを発生させる可能性があることを意味します。似たような現象で、子プロセスが非デーモンプロセスの場合、親プロセスは終了時に非デーモンのすべての子プロセスを join しようとしてハングアップする可能性があります。

マネージャーを使用して作成されたキューではこの問題はありません。詳細は @ref{3648,,プログラミングガイドライン} を参照してください。
@end quotation
@end cartouche

プロセス間通信におけるキューの使用例を知りたいなら @ref{3670,,使用例} を参照してください。

@geindex Pipe() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing Pipe}@anchor{364c}
@deffn {の関数} multiprocessing.Pipe (duplex=True)

パイプの両端を表す @ref{12f8,,Connection} オブジェクトのペア @code{(conn1, conn2)} を返します。

`duplex' が @code{True} (デフォルト) ならパイプは双方向性です。`duplex' が @code{False} ならパイプは一方向性で、@code{conn1} はメッセージの受信専用、@code{conn2} はメッセージの送信専用になります。

The @code{send()} method serializes the object using
@ref{ab,,pickle} and the @code{recv()} re-creates the object.
@end deffn

@geindex Queue (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing Queue}@anchor{1b89}
@deffn {クラス} multiprocessing.Queue ([maxsize])

パイプや2～3個のロック/セマフォを使用して実装されたプロセス共有キューを返します。あるプロセスが最初に要素をキューへ追加するとき、バッファーからパイプの中へオブジェクトを転送する供給スレッドが開始されます。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.

標準ライブラリの @ref{bb,,queue} モジュールの通常の @ref{366c,,queue.Empty} や @ref{366d,,queue.Full} 例外がタイムアウトを伝えるために送出されます。

@ref{1b89,,Queue} は @ref{3668,,task_done()} や @ref{3669,,join()} を除く @ref{15ac,,queue.Queue} のすべてのメソッドを実装します。

@geindex qsize() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue qsize}@anchor{3671}
@deffn {メソッド} qsize ()

おおよそのキューのサイズを返します。マルチスレッディング/マルチプロセスの特性上、この数値は信用できません。

Note that this may raise @ref{36b,,NotImplementedError} on platforms like
macOS where @code{sem_getvalue()} is not implemented.
@end deffn

@geindex empty() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue empty}@anchor{1968}
@deffn {メソッド} empty ()

キューが空っぽなら @code{True} を、そうでなければ @code{False} を返します。マルチスレッディング/マルチプロセシングの特性上、これは信用できません。

May raise an @ref{2c0,,OSError} on closed queues. (not guaranteed)
@end deffn

@geindex full() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue full}@anchor{3672}
@deffn {メソッド} full ()

キューがいっぱいなら @code{True} を、そうでなければ @code{False} を返します。マルチスレッディング/マルチプロセシングの特性上、これは信用できません。
@end deffn

@geindex put() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue put}@anchor{1e1d}
@deffn {メソッド} put (obj[, block[, timeout]])

キューの中へ obj を追加します。オプションの引数 `block' が @code{True} (デフォルト) 且つ `timeout' が @code{None} (デフォルト) なら、空きスロットが利用可能になるまで必要であればブロックします。 `timeout' が正の数なら、最大 `timeout' 秒ブロックして、その時間内に空きスロットが利用できなかったら @ref{366d,,queue.Full} 例外を発生させます。それ以外 (`block' が @code{False}) で、空きスロットがすぐに利用可能な場合はキューに要素を追加します。そうでなければ @ref{366d,,queue.Full} 例外が発生します(その場合 `timeout' は無視されます)。


バージョン 3.8 で変更: If the queue is closed, @ref{2ec,,ValueError} is raised instead of
@ref{8b8,,AssertionError}.

@end deffn

@geindex put_nowait() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue put_nowait}@anchor{3673}
@deffn {メソッド} put_nowait (obj)

@code{put(obj, False)} と等価です。
@end deffn

@geindex get() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue get}@anchor{1e1e}
@deffn {メソッド} get ([block[, timeout]])

キューから要素を取り出して削除します。オプションの引数 `block' が @code{True} (デフォルト) 且つ `timeout' が @code{None} (デフォルト) なら、要素が取り出せるまで必要であればブロックします。 `timeout' が正の数なら、最大 `timeout' 秒ブロックして、その時間内に要素が取り出せなかったら @ref{366c,,queue.Empty} 例外を発生させます。それ以外 (`block' が @code{False}) で、要素がすぐに取り出せる場合は要素を返します。そうでなければ @ref{366c,,queue.Empty} 例外が発生します(その場合 `timeout' は無視されます)。


バージョン 3.8 で変更: If the queue is closed, @ref{2ec,,ValueError} is raised instead of
@ref{2c0,,OSError}.

@end deffn

@geindex get_nowait() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue get_nowait}@anchor{366e}
@deffn {メソッド} get_nowait ()

@code{get(False)} と等価です。
@end deffn

@ref{1b89,,multiprocessing.Queue} は @ref{15ac,,queue.Queue} にはない追加メソッドがあります。 これらのメソッドは通常、ほとんどのコードに必要ありません:

@geindex close() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue close}@anchor{1b8a}
@deffn {メソッド} close ()

Close the queue: release internal resources.

A queue must not be used anymore after it is closed. For example,
@ref{1e1e,,get()}, @ref{1e1d,,put()} and @ref{1968,,empty()}
methods must no longer be called.

The background thread will quit once it has flushed all buffered
data to the pipe.  This is called automatically when the queue is garbage
collected.
@end deffn

@geindex join_thread() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue join_thread}@anchor{3674}
@deffn {メソッド} join_thread ()

バックグラウンドスレッドを join します。このメソッドは @ref{1b8a,,close()} が呼び出された後でのみ使用されます。バッファーされたすべてのデータがパイプへフラッシュされるのを保証するため、バックグラウンドスレッドが終了するまでブロックします。

デフォルトでは、あるプロセスがキューを作成していない場合、終了時にキューのバックグラウンドスレッドを join しようとします。そのプロセスは @ref{3674,,join_thread()} が何もしないように @ref{366f,,cancel_join_thread()} を呼び出すことができます。
@end deffn

@geindex cancel_join_thread() (multiprocessing.Queue のメソッド)
@anchor{library/multiprocessing multiprocessing Queue cancel_join_thread}@anchor{366f}
@deffn {メソッド} cancel_join_thread ()

@ref{3674,,join_thread()} がブロッキングするのを防ぎます。特にこれはバックグラウンドスレッドがそのプロセスの終了時に自動的に join されるのを防ぎます。詳細は @ref{3674,,join_thread()} を参照してください。

このメソッドは @code{allow_exit_without_flush()} という名前のほうがよかったかもしれません。キューに追加されたデータが失われてしまいがちなため、このメソッドを使う必要はほぼ確実にないでしょう。本当にこれが必要になるのは、キューに追加されたデータを下位層のパイプにフラッシュすることなくカレントプロセスを直ちに終了する必要があり、かつ失われるデータに関心がない場合です。
@end deffn

@cartouche
@quotation 注釈 
このクラスに含まれる機能には、ホストとなるオペレーティングシステム上で動作している共有セマフォ (shared semaphore) を使用しているものがあります。これが使用できない場合には、このクラスが無効になり、 @ref{1b89,,Queue} をインスタンス化する時に @ref{65b,,ImportError} が発生します。詳細は bpo-3770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3770} を参照してください。同様のことが、以下に列挙されている特殊なキューでも成り立ちます。
@end quotation
@end cartouche
@end deffn

@geindex SimpleQueue (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing SimpleQueue}@anchor{b10}
@deffn {クラス} multiprocessing.SimpleQueue

単純化された @ref{1b89,,Queue} 型です。ロックされた @ref{364c,,Pipe} と非常に似ています。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.

@geindex close() (multiprocessing.SimpleQueue のメソッド)
@anchor{library/multiprocessing multiprocessing SimpleQueue close}@anchor{b11}
@deffn {メソッド} close ()

Close the queue: release internal resources.

A queue must not be used anymore after it is closed. For example,
@ref{3675,,get()}, @ref{3676,,put()} and @ref{1969,,empty()} methods must no longer be
called.


Added in version 3.9.

@end deffn

@geindex empty() (multiprocessing.SimpleQueue のメソッド)
@anchor{library/multiprocessing multiprocessing SimpleQueue empty}@anchor{1969}
@deffn {メソッド} empty ()

キューが空ならば @code{True} を、そうでなければ @code{False} を返します。

Always raises an @ref{2c0,,OSError} if the SimpleQueue is closed.
@end deffn

@geindex get() (multiprocessing.SimpleQueue のメソッド)
@anchor{library/multiprocessing multiprocessing SimpleQueue get}@anchor{3675}
@deffn {メソッド} get ()

キューから要素を削除して返します。
@end deffn

@geindex put() (multiprocessing.SimpleQueue のメソッド)
@anchor{library/multiprocessing multiprocessing SimpleQueue put}@anchor{3676}
@deffn {メソッド} put (item)

`item' をキューに追加します。
@end deffn
@end deffn

@geindex JoinableQueue (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing JoinableQueue}@anchor{3667}
@deffn {クラス} multiprocessing.JoinableQueue ([maxsize])

@ref{3667,,JoinableQueue} は @ref{1b89,,Queue} のサブクラスであり、 @ref{366a,,task_done()} や @ref{3677,,join()} メソッドが追加されているキューです。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.

@geindex task_done() (multiprocessing.JoinableQueue のメソッド)
@anchor{library/multiprocessing multiprocessing JoinableQueue task_done}@anchor{366a}
@deffn {メソッド} task_done ()

以前にキューへ追加されたタスクが完了したことを表します。キューのコンシューマによって使用されます。 タスクをフェッチするために使用されるそれぞれの @ref{1e1e,,get()} に対して、 後続の @ref{366a,,task_done()} 呼び出しはタスクの処理が完了したことをキューへ伝えます。

もし @ref{3669,,join()} がブロッキング状態なら、 すべての要素が処理されたときに復帰します( @ref{366a,,task_done()} 呼び出しが すべての要素からキュー内へ @ref{1e1d,,put()} されたと受け取ったことを意味します)。

キューにある要素より多く呼び出された場合 @ref{2ec,,ValueError} が発生します。
@end deffn

@geindex join() (multiprocessing.JoinableQueue のメソッド)
@anchor{library/multiprocessing multiprocessing JoinableQueue join}@anchor{3677}
@deffn {メソッド} join ()

キューにあるすべてのアイテムが取り出されて処理されるまでブロックします。

キューに要素が追加されると未完了タスク数が増えます。コンシューマがキューの要素が取り出されてすべての処理が完了したことを表す @ref{366a,,task_done()} を呼び出すと数が減ります。 未完了タスク数がゼロになると @ref{3669,,join()} はブロッキングを解除します。
@end deffn
@end deffn

@node その他<5>,Connection オブジェクト<2>,パイプ Pipe とキュー Queue,リファレンス<3>
@anchor{library/multiprocessing miscellaneous}@anchor{3678}
@subsubsection その他


@geindex active_children() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing active_children}@anchor{3679}
@deffn {の関数} multiprocessing.active_children ()

カレントプロセスのすべてのアクティブな子プロセスのリストを返します。

これを呼び出すと "join" してすでに終了しているプロセスには副作用があります。
@end deffn

@geindex cpu_count() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing cpu_count}@anchor{1171}
@deffn {の関数} multiprocessing.cpu_count ()

システムの CPU 数を返します。

This number is not equivalent to the number of CPUs the current process can
use.  The number of usable CPUs can be obtained with
@ref{4da,,os.process_cpu_count()} (or @code{len(os.sched_getaffinity(0))}).

When the number of CPUs cannot be determined a @ref{36b,,NotImplementedError}
is raised.


@subsubheading 参考


@ref{4db,,os.cpu_count()}
@ref{4da,,os.process_cpu_count()}



バージョン 3.13 で変更: The return value can also be overridden using the
@ref{16f,,-X cpu_count} flag or 
@geindex PYTHON_CPU_COUNT
@geindex 環境変数; PYTHON_CPU_COUNT
@ref{51e,,PYTHON_CPU_COUNT} as this is
merely a wrapper around the @ref{a5,,os} cpu count APIs.

@end deffn

@geindex current_process() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing current_process}@anchor{367a}
@deffn {の関数} multiprocessing.current_process ()

カレントプロセスに対応する @ref{252,,Process} オブジェクトを返します。

@ref{35e,,threading.current_thread()} とよく似た関数です。
@end deffn

@geindex parent_process() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing parent_process}@anchor{367b}
@deffn {の関数} multiprocessing.parent_process ()

Return the @ref{252,,Process} object corresponding to the parent process of
the @ref{367a,,current_process()}. For the main process, @code{parent_process} will
be @code{None}.


Added in version 3.8.

@end deffn

@geindex freeze_support() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing freeze_support}@anchor{183b}
@deffn {の関数} multiprocessing.freeze_support ()

Add support for when a program which uses @code{multiprocessing} has been
frozen to produce an executable.  (Has been tested with `py2exe',
`PyInstaller' and `cx_Freeze'.)

メインモジュールの @code{if __name__ == '__main__'} の直後にこの関数を呼び出す必要があります。以下に例を示します:

@example
from multiprocessing import Process, freeze_support

def f():
    print('hello world!')

if __name__ == '__main__':
    freeze_support()
    Process(target=f).start()
@end example

もし @code{freeze_support()} の行がない場合、フリーズされた実行可能形式を実行しようとすると @ref{244,,RuntimeError} を発生させます。

Calling @code{freeze_support()} has no effect when the start method is not
`spawn'. In addition, if the module is being run normally by the Python
interpreter (the program has not been frozen), then @code{freeze_support()}
has no effect.
@end deffn

@geindex get_all_start_methods() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing get_all_start_methods}@anchor{116b}
@deffn {の関数} multiprocessing.get_all_start_methods ()

Returns a list of the supported start methods, the first of which
is the default.  The possible start methods are @code{'fork'},
@code{'spawn'} and @code{'forkserver'}.  Not all platforms support all
methods.  See @ref{1d5,,コンテキストと開始方式}.


Added in version 3.4.

@end deffn

@geindex get_context() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing get_context}@anchor{24a}
@deffn {の関数} multiprocessing.get_context (method=None)

Return a context object which has the same attributes as the
@code{multiprocessing} module.

If `method' is @code{None} then the default context is returned. Note that if
the global start method has not been set, this will set it to the system default
See @ref{3658,,Global start method} for more details.
Otherwise `method' should be @code{'fork'}, @code{'spawn'},
@code{'forkserver'}.  @ref{2ec,,ValueError} is raised if the specified
start method is not available.  See @ref{1d5,,コンテキストと開始方式}.


Added in version 3.4.

@end deffn

@geindex get_start_method() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing get_start_method}@anchor{116c}
@deffn {の関数} multiprocessing.get_start_method (allow_none=False)

開始するプロセスで使用する開始方式名を返します。

If the global start method is not set and `allow_none' is @code{False}, the global start
method is set to the default, and its name is returned. See
@ref{3658,,Global start method} for more details.

The return value can be @code{'fork'}, @code{'spawn'}, @code{'forkserver'}
or @code{None}.  See @ref{1d5,,コンテキストと開始方式}.


Added in version 3.4.



バージョン 3.8 で変更: macOS では、 `spawn' 開始方式がデフォルトになりました。 `fork' 開始方法は、サブプロセスのクラッシュを引き起こす可能性があるため、安全ではありません。 bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725} を参照。

@end deffn

@geindex set_executable() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing set_executable}@anchor{1b90}
@deffn {の関数} multiprocessing.set_executable (executable)

Set the path of the Python interpreter to use when starting a child process.
(By default @ref{3ed,,sys.executable} is used).  Embedders will probably need to
do something like

@example
set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
@end example

子プロセスを作成する前に行ってください。


バージョン 3.4 で変更: Now supported on POSIX when the @code{'spawn'} start method is used.



バージョン 3.11 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex set_forkserver_preload() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing set_forkserver_preload}@anchor{1908}
@deffn {の関数} multiprocessing.set_forkserver_preload (module_names)

Set a list of module names for the forkserver main process to attempt to
import so that their already imported state is inherited by forked
processes. Any @ref{65b,,ImportError} when doing so is silently ignored.
This can be used as a performance enhancement to avoid repeated work
in every process.

For this to work, it must be called before the forkserver process has been
launched (before creating a @code{Pool} or starting a @ref{252,,Process}).

Only meaningful when using the @code{'forkserver'} start method.
See @ref{1d5,,コンテキストと開始方式}.


Added in version 3.4.

@end deffn

@geindex set_start_method() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing set_start_method}@anchor{24b}
@deffn {の関数} multiprocessing.set_start_method (method, force=False)

Set the method which should be used to start child processes.
The `method' argument can be @code{'fork'}, @code{'spawn'} or @code{'forkserver'}.
Raises @ref{244,,RuntimeError} if the start method has already been set and `force'
is not @code{True}.  If `method' is @code{None} and `force' is @code{True} then the start
method is set to @code{None}.  If `method' is @code{None} and `force' is @code{False}
then the context is set to the default context.

これは一度しか呼び出すことができず、その場所もメインモジュールの @code{if __name__ == '__main__'} 節内で保護された状態でなければなりません。

See @ref{1d5,,コンテキストと開始方式}.


Added in version 3.4.

@end deffn

@cartouche
@quotation 注釈 
@code{multiprocessing} contains no analogues of
@ref{35f,,threading.active_count()}, @ref{1c5a,,threading.enumerate()},
@ref{a48,,threading.settrace()}, @ref{a49,,threading.setprofile()},
@ref{1371,,threading.Timer}, or @ref{185f,,threading.local}.
@end quotation
@end cartouche

@node Connection オブジェクト<2>,同期プリミティブ,その他<5>,リファレンス<3>
@anchor{library/multiprocessing connection-objects}@anchor{367c}
@subsubsection Connection オブジェクト


Connection オブジェクトは pickle でシリアライズ可能なオブジェクトか文字列を送ったり、受け取ったりします。そういったオブジェクトはメッセージ指向の接続ソケットと考えられます。

Connection オブジェクトは通常は @ref{364c,,Pipe} を使用して作成されます。 詳細は @ref{367d,,リスナーとクライアント} も参照してください。

@geindex Connection (multiprocessing.connection のクラス)
@anchor{library/multiprocessing multiprocessing connection Connection}@anchor{12f8}
@deffn {クラス} multiprocessing.connection.Connection

@geindex send() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection send}@anchor{367e}
@deffn {メソッド} send (obj)

コネクションの相手側へ @ref{367f,,recv()} を使用して読み込むオブジェクトを送ります。

オブジェクトは pickle でシリアライズ可能でなければなりません。 pickle が極端に大きすぎる (OS にも依りますが、およそ 32 MiB+) と、 @ref{2ec,,ValueError} 例外が送出されることがあります。
@end deffn

@geindex recv() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection recv}@anchor{367f}
@deffn {メソッド} recv ()

コネクションの相手側から @ref{367e,,send()} を使用して送られたオブジェクトを返します。 何か受け取るまでブロックします。何も受け取らずにコネクションの相手側でクローズされた場合 @ref{14f1,,EOFError} が発生します。
@end deffn

@geindex fileno() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection fileno}@anchor{3680}
@deffn {メソッド} fileno ()

コネクションが使用するハンドラーか、ファイル記述子を返します。
@end deffn

@geindex close() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection close}@anchor{3681}
@deffn {メソッド} close ()

コネクションをクローズします。

コネクションがガベージコレクトされるときに自動的に呼び出されます。
@end deffn

@geindex poll() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection poll}@anchor{3682}
@deffn {メソッド} poll ([timeout])

読み込み可能なデータがあるかどうかを返します。

`timeout' が指定されていなければすぐに返します。 `timeout' に数値を指定すると、最大指定した秒数をブロッキングします。 `timeout' に @code{None} を指定するとタイムアウトせずにずっとブロッキングします。

@ref{12f7,,multiprocessing.connection.wait()} を使って複数のコネクションオブジェクトを同時にポーリングできることに注意してください。
@end deffn

@geindex send_bytes() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection send_bytes}@anchor{3683}
@deffn {メソッド} send_bytes (buffer[, offset[, size]])

@ref{193,,bytes-like object} から完全なメッセージとしてバイトデータを送ります。

`offset' が指定されると `buffer' のその位置からデータが読み込まれます。 `size' が指定されるとバッファーからその量のデータが読み込まれます。非常に大きなバッファー (OS に依存しますが、およそ 32MiB+) を指定すると、 @ref{2ec,,ValueError} 例外が発生するかもしれません。
@end deffn

@geindex recv_bytes() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection recv_bytes}@anchor{3684}
@deffn {メソッド} recv_bytes ([maxlength])

コネクションの相手側から送られたバイトデータの完全なメッセージを文字列として返します。何か受け取るまでブロックします。受け取るデータが何も残っておらず、相手側がコネクションを閉じていた場合、 @ref{14f1,,EOFError} が送出されます。

`maxlength' を指定していて、かつメッセージが `maxlength' より長い場合、 @ref{2c0,,OSError} が発生してコネクションからそれ以上読めなくなります。


バージョン 3.3 で変更: この関数は以前は @ref{125e,,IOError} を送出していました。今では @ref{2c0,,OSError} の別名です。

@end deffn

@geindex recv_bytes_into() (multiprocessing.connection.Connection のメソッド)
@anchor{library/multiprocessing multiprocessing connection Connection recv_bytes_into}@anchor{3685}
@deffn {メソッド} recv_bytes_into (buffer[, offset])

コネクションの相手側から送られたバイトデータを `buffer' に読み込み、メッセージのバイト数を返します。 何か受け取るまでブロックします。何も受け取らずにコネクションの相手側でクローズされた場合 @ref{14f1,,EOFError} が発生します。

`buffer' は書き込み可能な @ref{193,,bytes-like object} でなければなりません。 `offset' が与えられたら、その位置からバッファーへメッセージが書き込まれます。 オフセットは `buffer' バイトよりも小さい正の数でなければなりません。

バッファーがあまりに小さいと @code{BufferTooShort} 例外が発生します。 @code{e} が例外インスタンスとすると完全なメッセージは @code{e.args[0]} で確認できます。
@end deffn


バージョン 3.3 で変更: @ref{367e,,Connection.send()} と @ref{367f,,Connection.recv()} を使用して Connection オブジェクト自体をプロセス間で転送できるようになりました。

Connection objects also now support the context management protocol -- see
@ref{240d,,コンテキストマネージャ型}.  @ref{26a8,,__enter__()} returns the
connection object, and @ref{26a9,,__exit__()} calls @ref{3681,,close()}.

@end deffn

例えば:

@example
>>> from multiprocessing import Pipe
>>> a, b = Pipe()
>>> a.send([1, 'hello', None])
>>> b.recv()
[1, 'hello', None]
>>> b.send_bytes(b'thank you')
>>> a.recv_bytes()
b'thank you'
>>> import array
>>> arr1 = array.array('i', range(5))
>>> arr2 = array.array('i', [0] * 10)
>>> a.send_bytes(arr1)
>>> count = b.recv_bytes_into(arr2)
>>> assert count == len(arr1) * arr1.itemsize
>>> arr2
array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
@end example
@anchor{library/multiprocessing multiprocessing-recv-pickle-security}@anchor{3686}
@cartouche
@quotation 警告 
@ref{367f,,Connection.recv()} メソッドは受信したデータを自動的に unpickle 化します。それはメッセージを送ったプロセスが信頼できる場合を除いてセキュリティリスクになります。

そのため @code{Pipe()} を使用してコネクションオブジェクトを生成する場合を除いて、何らかの認証処理を実行した後で @ref{367f,,recv()} や @ref{367e,,send()} メソッドのみを使用すべきです。詳細は @ref{3661,,認証キー} を参照してください。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
もしプロセスがパイプの読み込みまたは書き込み中に kill されると、メッセージの境界がどこなのか分からなくなってしまうので、そのパイプ内のデータは破損してしまいがちです。
@end quotation
@end cartouche

@node 同期プリミティブ,共有 ctypes オブジェクト,Connection オブジェクト<2>,リファレンス<3>
@anchor{library/multiprocessing synchronization-primitives}@anchor{3687}
@subsubsection 同期プリミティブ


一般的にマルチプロセスプログラムは、マルチスレッドプログラムほどは同期プリミティブを必要としません。詳細は @ref{f3,,threading} モジュールのドキュメントを参照してください。

マネージャーオブジェクトを使用して同期プリミティブを作成できることも覚えておいてください。詳細は @ref{366b,,マネージャー} を参照してください。

@geindex Barrier (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing Barrier}@anchor{3655}
@deffn {クラス} multiprocessing.Barrier (parties[, action[, timeout]])

バリアーオブジェクト: @ref{13fc,,threading.Barrier} のクローンです。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.


Added in version 3.3.

@end deffn

@geindex BoundedSemaphore (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing BoundedSemaphore}@anchor{3653}
@deffn {クラス} multiprocessing.BoundedSemaphore ([value])

有限セマフォオブジェクト: @ref{136f,,threading.BoundedSemaphore} の類似物です。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.

よく似た @ref{136f,,threading.BoundedSemaphore}  とは、次の一点だけ異なります。 @code{acquire} メソッドの第一引数名は `block' で、@ref{3688,,Lock.acquire()} と一致しています。

@geindex locked() (multiprocessing.BoundedSemaphore のメソッド)
@anchor{library/multiprocessing multiprocessing BoundedSemaphore locked}@anchor{3689}
@deffn {メソッド} locked ()

Return a boolean indicating whether this object is locked right now.


Added in version 3.14.

@end deffn

@cartouche
@quotation 注釈 
macOS では @code{sem_getvalue()} が実装されていないので @ref{3652,,Semaphore} と区別がつきません。
@end quotation
@end cartouche
@end deffn

@geindex Condition (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing Condition}@anchor{3654}
@deffn {クラス} multiprocessing.Condition ([lock])

状態変数: @ref{136d,,threading.Condition} の別名です。

If `lock' is specified then it should be a @ref{1853,,Lock} or @ref{1854,,RLock}
object from @code{multiprocessing}.

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.


バージョン 3.3 で変更: @ref{362d,,wait_for()} メソッドが追加されました。

@end deffn

@geindex Event (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing Event}@anchor{1c06}
@deffn {クラス} multiprocessing.Event

@ref{1370,,threading.Event} のクローンです。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.
@end deffn

@geindex Lock (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing Lock}@anchor{1853}
@deffn {クラス} multiprocessing.Lock

再帰しないロックオブジェクトで、 @ref{19f4,,threading.Lock} 相当のものです。プロセスやスレッドがロックをいったん獲得 (acquire) すると、それに続くほかのプロセスやスレッドが獲得しようとする際、それが解放 (release) されるまではブロックされます。解放はどのプロセス、スレッドからも行えます。スレッドに対して適用される @ref{19f4,,threading.Lock} のコンセプトと振る舞いは、特筆すべきものがない限り、プロセスとスレッドに適用される @ref{1853,,multiprocessing.Lock} に引き継がれています。

@ref{1853,,Lock} は実際にはファクトリ関数で、デフォルトコンテキストで初期化された @code{multiprocessing.synchronize.Lock} のインスタンスを返すことに注意してください。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.

@ref{1853,,Lock} は @ref{1e1,,context manager} プロトコルをサポートしています。つまり @ref{186,,with} 文で使うことができます。

@geindex acquire() (multiprocessing.Lock のメソッド)
@anchor{library/multiprocessing multiprocessing Lock acquire}@anchor{3688}
@deffn {メソッド} acquire (block=True, timeout=None)

ブロックあり、またはブロックなしでロックを獲得します。

引数 `block' を @code{True} (デフォルト) に設定して呼び出した場合、ロックがアンロック状態になるまでブロックします。ブロックから抜けるとそれをロック状態にしてから @code{True} を返します。 @ref{8a7,,threading.Lock.acquire()} の最初の引数とは名前が違っているので注意してください。

引数 `block' の値を @code{False} にして呼び出すとブロックしません。 現在ロック状態であれば、直ちに @code{False} を返します。それ以外の場合には、ロックをロック状態にして @code{True} を返します。

`timeout' として正の浮動小数点数を与えて呼び出すと、ロックが獲得できない限り、指定された秒数だけブロックします。 `timeout' 値に負数を与えると、ゼロを与えた場合と同じになります。 `timeout' 値の @code{None} (デフォルト) を与えると、無限にブロックします。 `timeout' 引数の負数と @code{None} の扱いは、 @ref{8a7,,threading.Lock.acquire()} に実装された動作と異なるので注意してください。 `block' が @code{False} の場合、 `timeout' は実際的な意味を持たなくなるので無視されます。ロックを獲得した場合は @code{True} 、タイムアウトした場合は @code{False} で戻ります。
@end deffn

@geindex release() (multiprocessing.Lock のメソッド)
@anchor{library/multiprocessing multiprocessing Lock release}@anchor{368a}
@deffn {メソッド} release ()

ロックを解放します。これはロックを獲得したプロセスやスレッドだけでなく、任意のプロセスやスレッドから呼ぶことができます。

@ref{14da,,threading.Lock.release()} と同じように振舞いますが、ロックされていない場合に呼び出すと @ref{2ec,,ValueError} となる点だけが違います。
@end deffn

@geindex locked() (multiprocessing.Lock のメソッド)
@anchor{library/multiprocessing multiprocessing Lock locked}@anchor{1877}
@deffn {メソッド} locked ()

Return a boolean indicating whether this object is locked right now.


Added in version 3.14.

@end deffn
@end deffn

@geindex RLock (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing RLock}@anchor{1854}
@deffn {クラス} multiprocessing.RLock

再帰ロックオブジェクトで、 @ref{32e,,threading.RLock} 相当のものです。再帰ロックオブジェクトはそれを獲得 (acquire) したプロセスやスレッドが解放 (release) しなければなりません。プロセスやスレッドがロックをいったん獲得すると、同じプロセスやスレッドはブロックされずに再度獲得出来ます。そのプロセスやスレッドは獲得した回数ぶん解放しなければなりません。

@ref{1854,,RLock} は実際にはファクトリ関数で、デフォルトコンテキストで初期化された @code{multiprocessing.synchronize.Lock} のインスタンスを返すことに注意してください。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.

@ref{1854,,RLock} は @ref{1e1,,context manager} プロトコルをサポートしています。つまり @ref{186,,with} 文で使うことができます。

@geindex acquire() (multiprocessing.RLock のメソッド)
@anchor{library/multiprocessing multiprocessing RLock acquire}@anchor{368b}
@deffn {メソッド} acquire (block=True, timeout=None)

ブロックあり、またはブロックなしでロックを獲得します。

`block' 引数を @code{True} にして呼び出した場合、ロックが既にカレントプロセスもしくはカレントスレッドが既に所有していない限りは、アンロック状態 (どのプロセス、スレッドも所有していない状態) になるまでブロックします。ブロックから抜けるとカレントプロセスもしくはカレントスレッドが (既に持っていなければ) 所有権を得て、再帰レベルをインクリメントし、 @code{True} で戻ります。 @ref{107b,,threading.RLock.acquire()} の実装とはこの最初の引数の振る舞いが、その名前自身を始めとしていくつか違うので注意してください。

`block' 引数を @code{False} にして呼び出した場合、ブロックしません。ロックが他のプロセスもしくはスレッドにより獲得済み (つまり所有されている) であれば、カレントプロセスまたはカレントスレッドは所有権を得ず、再帰レベルも変更せずに、 @code{False} で戻ります。ロックがアンロック状態の場合、カレントプロセスもしくはカレントスレッドは所有権を得て再帰レベルがインクリメントされ、 @code{True} で戻ります。(---訳注: `block' の True/False 関係なくここでの説明では「所有権を持っている場合の2度目以降の aquire」の説明が欠けています。2度目以降の acquire では再帰レベルがインクリメントされて即座に返ります。全体読めばわかるとは思いますが一応。---)

`timeout' 引数の使い方と振る舞いは @ref{3688,,Lock.acquire()} と同じです。 `timeout' 引数の振る舞いがいくつかの点で @ref{107b,,threading.RLock.acquire()} と異なるので注意してください。
@end deffn

@geindex release() (multiprocessing.RLock のメソッド)
@anchor{library/multiprocessing multiprocessing RLock release}@anchor{368c}
@deffn {メソッド} release ()

再帰レベルをデクリメントしてロックを解放します。デクリメント後に再帰レベルがゼロになった場合、ロックの状態をアンロック (いかなるプロセス、いかなるスレッドにも所有されていない状態) にリセットし、ロックの状態がアンロックになるのを待ってブロックしているプロセスもしくはスレッドがある場合にはその中のただ一つだけが処理を進行できるようにします。デクリメント後も再帰レベルがゼロでない場合、ロックの状態はロックのままで、呼び出し側のプロセスもしくはスレッドに所有されたままになります。

このメソッドは呼び出しプロセスあるいはスレッドがロックを所有している場合に限り呼び出してください。所有者でないプロセスもしくはスレッドによって呼ばれるか、あるいはアンロック (未所有) 状態で呼ばれた場合、 @ref{8b8,,AssertionError} が送出されます。同じ状況での @ref{3628,,threading.RLock.release()} 実装とは例外の型が異なるので注意してください。
@end deffn

@geindex locked() (multiprocessing.RLock のメソッド)
@anchor{library/multiprocessing multiprocessing RLock locked}@anchor{1878}
@deffn {メソッド} locked ()

Return a boolean indicating whether this object is locked right now.


Added in version 3.14.

@end deffn
@end deffn

@geindex Semaphore (multiprocessing のクラス)
@anchor{library/multiprocessing multiprocessing Semaphore}@anchor{3652}
@deffn {クラス} multiprocessing.Semaphore ([value])

セマフォオブジェクト: @ref{136e,,threading.Semaphore} のクローンです。

Instantiating this class may set the global start method. See
@ref{3658,,Global start method} for more details.

よく似た @ref{136f,,threading.BoundedSemaphore}  とは、次の一点だけ異なります。 @code{acquire} メソッドの第一引数名は `block' で、@ref{3688,,Lock.acquire()} と一致しています。

@geindex get_value() (multiprocessing.Semaphore のメソッド)
@anchor{library/multiprocessing multiprocessing Semaphore get_value}@anchor{368d}
@deffn {メソッド} get_value ()

Return the current value of semaphore.

Note that this may raise @ref{36b,,NotImplementedError} on platforms like
macOS where @code{sem_getvalue()} is not implemented.
@end deffn

@geindex locked() (multiprocessing.Semaphore のメソッド)
@anchor{library/multiprocessing multiprocessing Semaphore locked}@anchor{368e}
@deffn {メソッド} locked ()

Return a boolean indicating whether this object is locked right now.


Added in version 3.14.

@end deffn
@end deffn

@cartouche
@quotation 注釈 
macOS では @code{sem_timedwait} がサポートされていないので、@code{acquire()} にタイムアウトを与えて呼ぶと、ループ内でスリープすることでこの関数がエミュレートされます。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
このパッケージに含まれる機能には、ホストとなるオペレーティングシステム上で動作している共有セマフォを使用しているものがあります。これが使用できない場合には、@code{multiprocessing.synchronize} モジュールが無効になり、このモジュールのインポート時に @ref{65b,,ImportError} が発生します。詳細は bpo-3770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3770} を参照してください。
@end quotation
@end cartouche

@node 共有 ctypes オブジェクト,マネージャー,同期プリミティブ,リファレンス<3>
@anchor{library/multiprocessing shared-ctypes-objects}@anchor{368f}
@subsubsection 共有 @code{ctypes} オブジェクト


子プロセスにより継承される共有メモリを使用する共有オブジェクトを作成することができます。

@geindex Value() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing Value}@anchor{364f}
@deffn {の関数} multiprocessing.Value (typecode_or_type, *args, lock=True)

共有メモリから割り当てられた @ref{2e,,ctypes} オブジェクトを返します。 デフォルトでは、返り値は実際のオブジェクトの同期ラッパーです。オブジェクトそれ自身は、 @ref{364f,,Value} の `value' 属性によってアクセスできます。

`typecode_or_type' は返されるオブジェクトの型を決めます。それは ctypes の型か @ref{8,,array} モジュールで使用されるような1文字の型コードかのどちらか一方です。 `*args' は型のコンストラクターへ渡されます。

`lock' が @code{True} (デフォルト) なら、値へ同期アクセスするために新たに再帰的なロックオブジェクトが作成されます。 `lock' が @ref{1853,,Lock} か @ref{1854,,RLock} なら値への同期アクセスに使用されます。 `lock' が @code{False} なら、返されたオブジェクトへのアクセスはロックにより自動的に保護されません。そのため、必ずしも "プロセスセーフ" ではありません。

@code{+=} のような演算は、読み込みと書き込みを含むためアトミックでありません。このため、たとえば自動的に共有の値を増加させたい場合、以下のようにするのでは不十分です

@example
counter.value += 1
@end example

関連するロックが再帰的 (それがデフォルトです) なら、かわりに次のようにします

@example
with counter.get_lock():
    counter.value += 1
@end example

`lock' はキーワード専用引数であることに注意してください。
@end deffn

@geindex Array() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing Array}@anchor{3650}
@deffn {の関数} multiprocessing.Array (typecode_or_type, size_or_initializer, *, lock=True)

共有メモリから割り当てられた ctypes 配列を返します。デフォルトでは、返り値は実際の配列の同期ラッパーです。

`typecode_or_type' determines the type of the elements of the returned array:
it is either a @ref{32d8,,ctypes type} or a one
character typecode of the kind used by the @ref{8,,array} module with the
exception of @code{'w'}, which is not supported.  In addition, the @code{'c'}
typecode is an alias for @ref{32db,,ctypes.c_char}.  If `size_or_initializer'
is an integer, then it determines the length of the array, and the array
will be initially zeroed. Otherwise, `size_or_initializer' is a sequence
which is used to initialize the array and whose length determines the length
of the array.

`lock' が @code{True} (デフォルト) なら、値へ同期アクセスするために新たなロックオブジェクトが作成されます。 `lock' が @ref{1853,,Lock} か @ref{1854,,RLock} なら値への同期アクセスに使用されます。 `lock' が @code{False} なら、返されたオブジェクトへのアクセスはロックにより自動的に保護されません。そのため、必ずしも "プロセスセーフ" ではありません。

`lock' はキーワード引数としてのみ利用可能なことに注意してください。

@ref{32db,,ctypes.c_char} の配列は文字列を格納して取り出せる `value' と `raw' 属性を持っていることを覚えておいてください。
@end deffn

@menu
* The multiprocessing.sharedctypes module: The multiprocessing sharedctypes module. 

@end menu

@node The multiprocessing sharedctypes module,,,共有 ctypes オブジェクト
@anchor{library/multiprocessing module-multiprocessing sharedctypes}@anchor{9e}@anchor{library/multiprocessing the-multiprocessing-sharedctypes-module}@anchor{3690}
@subsubsection The @code{multiprocessing.sharedctypes} module


@geindex module; multiprocessing.sharedctypes

The @code{multiprocessing.sharedctypes} module provides functions for allocating
@ref{2e,,ctypes} objects from shared memory which can be inherited by child
processes.

@cartouche
@quotation 注釈 
共有メモリのポインターを格納することは可能ではありますが、特定プロセスのアドレス空間の位置を参照するということを覚えておいてください。しかし、そのポインターは別のプロセスのコンテキストにおいて無効になる確率が高いです。そして、別のプロセスからそのポインターを逆参照しようとするとクラッシュを引き起こす可能性があります。
@end quotation
@end cartouche

@geindex RawArray() (multiprocessing.sharedctypes モジュール)
@anchor{library/multiprocessing multiprocessing sharedctypes RawArray}@anchor{3691}
@deffn {の関数} multiprocessing.sharedctypes.RawArray (typecode_or_type, size_or_initializer)

共有メモリから割り当てられた ctypes 配列を返します。

`typecode_or_type' は返される配列の要素の型を決めます。それは ctypes の型か @ref{8,,array} モジュールで使用されるような1文字の型コードのどちらか一方です。 `size_or_initializer' が整数なら、それが配列の長さになり、その配列はゼロで初期化されます。別の使用方法として `size_or_initializer' には配列の初期化に使用されるシーケンスを設定することもでき、その場合はシーケンスの長さが配列の長さになります。

要素を取得したり設定したりすることは潜在的に非アトミックであることに注意してください。ロックを使用して自動的に同期化されたアクセスを保証するには @ref{3692,,Array()} を使用してください。
@end deffn

@geindex RawValue() (multiprocessing.sharedctypes モジュール)
@anchor{library/multiprocessing multiprocessing sharedctypes RawValue}@anchor{3693}
@deffn {の関数} multiprocessing.sharedctypes.RawValue (typecode_or_type, *args)

共有メモリから割り当てられた ctypes オブジェクトを返します。

`typecode_or_type' は返されるオブジェクトの型を決めます。それは ctypes の型か @ref{8,,array} モジュールで使用されるような1文字の型コードかのどちらか一方です。 `*args' は型のコンストラクターへ渡されます。

値を取得したり設定したりすることは潜在的に非アトミックであることに注意してください。ロックを使用して自動的に同期化されたアクセスを保証するには @ref{3694,,Value()} を使用してください。

@ref{32db,,ctypes.c_char} の配列は文字列を格納して取り出せる @code{value} と @code{raw} 属性を持っていることを覚えておいてください。詳細は @ref{2e,,ctypes} を参照してください。
@end deffn

@geindex Array() (multiprocessing.sharedctypes モジュール)
@anchor{library/multiprocessing multiprocessing sharedctypes Array}@anchor{3692}
@deffn {の関数} multiprocessing.sharedctypes.Array (typecode_or_type, size_or_initializer, *, lock=True, ctx=None)

@ref{3691,,RawArray()} と同様ですが、 `lock' の値によっては ctypes 配列をそのまま返す代わりに、プロセスセーフな同期ラッパーが返されます。

`lock' が @code{True} (デフォルト) なら、値へ同期アクセスするために新たな ロックオブジェクトが作成されます。 `lock' が @ref{1853,,Lock} か @ref{1854,,RLock} なら値への同期アクセスに使用されます。 `lock' が @code{False} なら、返された オブジェクトへのアクセスはロックにより自動的に保護されません。 そのため、必ずしも "プロセスセーフ" ではありません。

`ctx' is a context object, or @code{None} (use the current context). If @code{None},
calling this may set the global start method. See
@ref{3658,,Global start method} for more details.

Note that `lock' and `ctx' are keyword-only parameters.
@end deffn

@geindex Value() (multiprocessing.sharedctypes モジュール)
@anchor{library/multiprocessing multiprocessing sharedctypes Value}@anchor{3694}
@deffn {の関数} multiprocessing.sharedctypes.Value (typecode_or_type, *args, lock=True, ctx=None)

@ref{3693,,RawValue()} と同様ですが、 `lock' の値によっては ctypes オブジェクトをそのまま返す代わりに、プロセスセーフな同期ラッパーが返されます。

`lock' が @code{True} (デフォルト) なら、値へ同期アクセスするために新たな ロックオブジェクトが作成されます。 `lock' が @ref{1853,,Lock} か @ref{1854,,RLock} なら値への同期アクセスに使用されます。 `lock' が @code{False} なら、返された オブジェクトへのアクセスはロックにより自動的に保護されません。 そのため、必ずしも "プロセスセーフ" ではありません。

`ctx' is a context object, or @code{None} (use the current context). If @code{None},
calling this may set the global start method. See
@ref{3658,,Global start method} for more details.

Note that `lock' and `ctx' are keyword-only parameters.
@end deffn

@geindex copy() (multiprocessing.sharedctypes モジュール)
@anchor{library/multiprocessing multiprocessing sharedctypes copy}@anchor{3695}
@deffn {の関数} multiprocessing.sharedctypes.copy (obj)

共有メモリから割り当てられた ctypes オブジェクト `obj' をコピーしたオブジェクトを返します。
@end deffn

@geindex synchronized() (multiprocessing.sharedctypes モジュール)
@anchor{library/multiprocessing multiprocessing sharedctypes synchronized}@anchor{1031}
@deffn {の関数} multiprocessing.sharedctypes.synchronized (obj, lock=None, ctx=None)

同期アクセスに `lock' を使用する ctypes オブジェクトのためにプロセスセーフなラッパーオブジェクトを返します。 `lock' が @code{None} (デフォルト) なら、 @ref{1854,,multiprocessing.RLock} オブジェクトが自動的に作成されます。

`ctx' is a context object, or @code{None} (use the current context). If @code{None},
calling this may set the global start method. See
@ref{3658,,Global start method} for more details.

同期ラッパーがラップするオブジェクトに加えて2つのメソッドがあります。 @code{get_obj()} はラップされたオブジェクトを返します。 @code{get_lock()} は同期のために使用されるロックオブジェクトを返します。

ラッパー経由で ctypes オブジェクトにアクセスすることは raw ctypes オブジェクトへアクセスするよりずっと遅くなることに注意してください。


バージョン 3.5 で変更: synchronized オブジェクトは @ref{1e1,,コンテキストマネージャ} プロトコルをサポートしています。

@end deffn

次の表は通常の ctypes 構文で共有メモリから共有 ctypes オブジェクトを作成するための構文を比較します。 (@code{MyStruct} テーブル内には @ref{1e5,,ctypes.Structure} のサブクラスがあります。)


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ctypes

@tab

type を使用する sharedctypes

@tab

typecode を使用する sharedctypes

@item

c_double(2.4)

@tab

RawValue(c_double, 2.4)

@tab

RawValue('d', 2.4)

@item

MyStruct(4, 6)

@tab

RawValue(MyStruct, 4, 6)

@tab

@item

(c_short * 7)()

@tab

RawArray(c_short, 7)

@tab

RawArray('h', 7)

@item

(c_int * 3)(9, 2, 8)

@tab

RawArray(c_int, (9, 2, 8))

@tab

RawArray('i', (9, 2, 8))

@end multitable


以下に子プロセスが多くの ctypes オブジェクトを変更する例を紹介します:

@example
from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
from ctypes import Structure, c_double

class Point(Structure):
    _fields_ = [('x', c_double), ('y', c_double)]

def modify(n, x, s, A):
    n.value **= 2
    x.value **= 2
    s.value = s.value.upper()
    for a in A:
        a.x **= 2
        a.y **= 2

if __name__ == '__main__':
    lock = Lock()

    n = Value('i', 7)
    x = Value(c_double, 1.0/3.0, lock=False)
    s = Array('c', b'hello world', lock=lock)
    A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

    p = Process(target=modify, args=(n, x, s, A))
    p.start()
    p.join()

    print(n.value)
    print(x.value)
    print(s.value)
    print([(a.x, a.y) for a in A])
@end example

結果は以下のように表示されます

@example
49
0.1111111111111111
HELLO WORLD
[(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
@end example

@node マネージャー,Proxy オブジェクト,共有 ctypes オブジェクト,リファレンス<3>
@anchor{library/multiprocessing managers}@anchor{3696}@anchor{library/multiprocessing multiprocessing-managers}@anchor{366b}
@subsubsection マネージャー


マネージャーは異なるプロセス間で共有されるデータの作成方法を提供します。これには別のマシン上で走るプロセス間のネットワーク越しの共有も含まれます。マネージャーオブジェクトは `共有オブジェクト' を管理するサーバープロセスを制御します。他のプロセスはプロキシ経由で共有オブジェクトへアクセスすることができます。

@geindex built-in function; multiprocessing.Manager()
@anchor{library/multiprocessing multiprocessing Manager}@anchor{250}
@deffn {の関数} multiprocessing.Manager ()

プロセス間でオブジェクトを共有するために使用される @ref{1894,,SyncManager} オブジェクトを返します。返されたマネージャーオブジェクトは生成される子プロセスに対応付けられ、共有オブジェクトを作成するメソッドや、共有オブジェクトに対応するプロキシを返すメソッドを持ちます。
@end deffn

@geindex module; multiprocessing.managers
@anchor{library/multiprocessing module-multiprocessing managers}@anchor{9b}
マネージャープロセスは親プロセスが終了するか、ガベージコレクトされると停止します。マネージャークラスは @ref{9b,,multiprocessing.managers} モジュールで定義されています:

@geindex BaseManager (multiprocessing.managers のクラス)
@anchor{library/multiprocessing multiprocessing managers BaseManager}@anchor{3697}
@deffn {クラス} multiprocessing.managers.BaseManager (address=None, authkey=None, serializer='pickle', ctx=None, *, shutdown_timeout=1.0)

BaseManager オブジェクトを作成します。

作成後、@ref{3698,,start()} または @code{get_server().serve_forever()} を呼び出して、マネージャーオブジェクトが、開始されたマネージャープロセスを確実に参照するようにしてください。

`address' はマネージャープロセスが新たなコネクションを待ち受けるアドレスです。`address' が @code{None} の場合、任意のアドレスが設定されます。

`authkey' はサーバープロセスへ接続しようとするコネクションの正当性を検証するために 使用される認証キーです。`authkey' が @code{None} の場合 @code{current_process().authkey} が使用されます。`authkey' を使用する場合はバイト文字列でなければなりません。

`serializer' must be @code{'pickle'} (use @ref{ab,,pickle} serialization) or
@code{'xmlrpclib'} (use @ref{134,,xmlrpc.client} serialization).

`ctx' is a context object, or @code{None} (use the current context). If @code{None},
calling this may set the global start method. See
@ref{3658,,Global start method} for more details.

`shutdown_timeout' is a timeout in seconds used to wait until the process
used by the manager completes in the @ref{3699,,shutdown()} method. If the
shutdown times out, the process is terminated. If terminating the process
also times out, the process is killed.


バージョン 3.11 で変更: `shutdown_timeout' パラメータを追加しました。


@geindex start() (multiprocessing.managers.BaseManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseManager start}@anchor{3698}
@deffn {メソッド} start ([initializer[, initargs]])

マネージャーを開始するためにサブプロセスを開始します。`initializer' が @code{None} でなければ、サブプロセスは開始時に @code{initializer(*initargs)} を呼び出します。
@end deffn

@geindex get_server() (multiprocessing.managers.BaseManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseManager get_server}@anchor{369a}
@deffn {メソッド} get_server ()

マネージャーの制御下にある実際のサーバーを表す @code{Server} オブジェクトを返します。 @code{Server} オブジェクトは @code{serve_forever()} メソッドをサポートします:

@example
>>> from multiprocessing.managers import BaseManager
>>> manager = BaseManager(address=('@w{'}, 50000), authkey=b'abc')
>>> server = manager.get_server()
>>> server.serve_forever()
@end example

@code{Server} はさらに @ref{369b,,address} 属性も持っています。
@end deffn

@geindex connect() (multiprocessing.managers.BaseManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseManager connect}@anchor{369c}
@deffn {メソッド} connect ()

ローカルからリモートのマネージャーオブジェクトへ接続します:

@example
>>> from multiprocessing.managers import BaseManager
>>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
>>> m.connect()
@end example
@end deffn

@geindex shutdown() (multiprocessing.managers.BaseManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseManager shutdown}@anchor{3699}
@deffn {メソッド} shutdown ()

マネージャーが使用するプロセスを停止します。これはサーバープロセスを開始するために @ref{3698,,start()} が使用された場合のみ有効です。

これは複数回呼び出すことができます。
@end deffn

@geindex register() (multiprocessing.managers.BaseManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseManager register}@anchor{369d}
@deffn {メソッド} register (typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])

マネージャークラスで呼び出し可能オブジェクト(callable)や型を登録するために使用されるクラスメソッドです。

`typeid' は特に共有オブジェクトの型を識別するために使用される "型識別子" です。これは文字列でなければなりません。

`callable' はこの型識別子のオブジェクトを作成するために使用される呼び出し可能オブジェクトです。マネージャーインスタンスが @ref{369c,,connect()} メソッドを使ってサーバーに接続されているか、 `create_method' 引数が @code{False} の場合は、 @code{None} でも構いません。

`proxytype' はこの `typeid' で共有オブジェクトのプロキシを作成するために使用される @ref{369e,,BaseProxy} のサブクラスです。 @code{None} の場合、プロキシクラスは自動的に作成されます。

`exposed' は @ref{369f,,BaseProxy._callmethod()} を使用したアクセスが許されるべき typeid をプロキシするメソッド名のシーケンスを指定するために使用されます (`exposed' が @code{None} の場合 @code{proxytype._exposed_} が存在すればそれが代わりに使用されます)。`exposed' リストが指定されない場合、共有オブジェクトのすべての "パブリックメソッド" がアクセス可能になります。 (ここでいう "パブリックメソッド" とは @ref{77a,,__call__()} メソッドを持つものと名前が @code{'_'} で始まらないあらゆる属性を意味します。)

`method_to_typeid' はプロキシが返す exposed メソッドの返り値の型を指定するために使用されるマッピングで、メソッド名を typeid 文字列にマップします。 (`method_to_typeid' が @code{None} の場合 @code{proxytype._method_to_typeid_} が存在すれば、それが代わりに使用されます。) メソッド名がこのマッピングのキーではないか、マッピングが @code{None} の場合、そのメソッドによって返されるオブジェクトが値として (by value) コピーされます。

`create_method' は、共有オブジェクトを作成し、それに対するプロキシを返すようサーバープロセスに伝える、名前 `typeid' のメソッドを作成するかを決定します。デフォルトでは @code{True} です。
@end deffn

@ref{3697,,BaseManager} インスタンスも読み出し専用属性を1つ持っています:

@geindex address (multiprocessing.managers.BaseManager の属性)
@anchor{library/multiprocessing multiprocessing managers BaseManager address}@anchor{369b}
@deffn {の属性} address

マネージャーが使用するアドレスです。
@end deffn


バージョン 3.3 で変更: マネージャーオブジェクトはコンテキストマネージメント・プロトコルをサポートします -- @ref{240d,,コンテキストマネージャ型} を参照してください。 @ref{26a8,,__enter__()} は (まだ開始していない場合) サーバープロセスを開始してから、マネージャーオブジェクトを返します。 @ref{26a9,,__exit__()} は @ref{3699,,shutdown()} を呼び出します。

旧バージョンでは、 @ref{26a8,,__enter__()} はマネージャーのサーバープロセスがまだ開始していなかった場合でもプロセスを開始しませんでした。

@end deffn

@geindex SyncManager (multiprocessing.managers のクラス)
@anchor{library/multiprocessing multiprocessing managers SyncManager}@anchor{1894}
@deffn {クラス} multiprocessing.managers.SyncManager

プロセス間の同期のために使用される @ref{3697,,BaseManager} のサブクラスです。 @ref{250,,multiprocessing.Manager()} はこの型のオブジェクトを返します。

Its methods create and return @ref{24c,,Proxy オブジェクト} for a
number of commonly used data types to be synchronized across processes.
This notably includes shared lists and dictionaries.

@geindex Barrier() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Barrier}@anchor{36a0}
@deffn {メソッド} Barrier (parties[, action[, timeout]])

共有 @ref{13fc,,threading.Barrier} オブジェクトを作成して、そのプロキシを返します。


Added in version 3.3.

@end deffn

@geindex BoundedSemaphore() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager BoundedSemaphore}@anchor{36a1}
@deffn {メソッド} BoundedSemaphore ([value])

共有 @ref{136f,,threading.BoundedSemaphore} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex Condition() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Condition}@anchor{36a2}
@deffn {メソッド} Condition ([lock])

共有 @ref{136d,,threading.Condition} オブジェクトを作成して、そのプロキシを返します。

`lock' が提供される場合 @ref{19f4,,threading.Lock} か @ref{32e,,threading.RLock} オブジェクトのためのプロキシになります。


バージョン 3.3 で変更: @ref{362d,,wait_for()} メソッドが追加されました。

@end deffn

@geindex Event() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Event}@anchor{36a3}
@deffn {メソッド} Event ()

共有 @ref{1370,,threading.Event} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex Lock() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Lock}@anchor{15af}
@deffn {メソッド} Lock ()

共有 @ref{19f4,,threading.Lock} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex Namespace() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Namespace}@anchor{36a4}
@deffn {メソッド} Namespace ()

共有 @ref{3651,,Namespace} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex Queue() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Queue}@anchor{31c4}
@deffn {メソッド} Queue ([maxsize])

共有 @ref{15ac,,queue.Queue} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex RLock() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager RLock}@anchor{15b0}
@deffn {メソッド} RLock ()

共有 @ref{32e,,threading.RLock} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex Semaphore() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Semaphore}@anchor{15b1}
@deffn {メソッド} Semaphore ([value])

共有 @ref{136e,,threading.Semaphore} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex Array() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Array}@anchor{36a5}
@deffn {メソッド} Array (typecode, sequence)

配列を作成して、そのプロキシを返します。
@end deffn

@geindex Value() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager Value}@anchor{36a6}
@deffn {メソッド} Value (typecode, value)

書き込み可能な @code{value} 属性を作成して、そのプロキシを返します。
@end deffn

@geindex dict() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager dict}@anchor{36a7}
@deffn {メソッド} dict ()

@deffnx {メソッド} dict (mapping)

@deffnx {メソッド} dict (sequence)

共有 @ref{183,,dict} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex list() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager list}@anchor{36a8}
@deffn {メソッド} list ()

@deffnx {メソッド} list (sequence)

共有 @ref{24d,,list} オブジェクトを作成して、そのプロキシを返します。
@end deffn

@geindex set() (multiprocessing.managers.SyncManager のメソッド)
@anchor{library/multiprocessing multiprocessing managers SyncManager set}@anchor{24f}
@deffn {メソッド} set ()

@deffnx {メソッド} set (sequence)

@deffnx {メソッド} set (mapping)

Create a shared @ref{184,,set} object and return a proxy for it.


Added in version 3.14: @ref{184,,set} support was added.

@end deffn


バージョン 3.6 で変更: 共有オブジェクトは入れ子もできます。
例えば、共有リストのような共有コンテナオブジェクトは、 @ref{1894,,SyncManager} がまとめて管理し同期を取っている他の共有オブジェクトを保持できます。

@end deffn

@geindex Namespace (multiprocessing.managers のクラス)
@anchor{library/multiprocessing multiprocessing managers Namespace}@anchor{3651}
@deffn {クラス} multiprocessing.managers.Namespace

@ref{1894,,SyncManager} に登録することのできる型です。

Namespace オブジェクトにはパブリックなメソッドはありませんが、書き込み可能な属性を持ちます。そのオブジェクト表現はその属性の値を表示します。

しかし、Namespace オブジェクトのためにプロキシを使用するとき @code{'_'} が先頭に付く属性はプロキシの属性になり、参照対象の属性にはなりません:

@example
>>> mp_context = multiprocessing.get_context('spawn')
>>> manager = mp_context.Manager()
>>> Global = manager.Namespace()
>>> Global.x = 10
>>> Global.y = 'hello'
>>> Global._z = 12.3    # this is an attribute of the proxy
>>> print(Global)
Namespace(x=10, y='hello')
@end example
@end deffn

@menu
* カスタマイズされたマネージャー:: 
* リモートマネージャーを使用する:: 

@end menu

@node カスタマイズされたマネージャー,リモートマネージャーを使用する,,マネージャー
@anchor{library/multiprocessing customized-managers}@anchor{36a9}
@subsubsection カスタマイズされたマネージャー


独自のマネージャーを作成するには、@ref{3697,,BaseManager} のサブクラスを作成して、 マネージャークラスで呼び出し可能なオブジェクトか新たな型を登録するために @ref{369d,,register()} クラスメソッドを使用します。例えば:

@example
from multiprocessing.managers import BaseManager

class MathsClass:
    def add(self, x, y):
        return x + y
    def mul(self, x, y):
        return x * y

class MyManager(BaseManager):
    pass

MyManager.register('Maths', MathsClass)

if __name__ == '__main__':
    with MyManager() as manager:
        maths = manager.Maths()
        print(maths.add(4, 3))         # prints 7
        print(maths.mul(7, 8))         # prints 56
@end example

@node リモートマネージャーを使用する,,カスタマイズされたマネージャー,マネージャー
@anchor{library/multiprocessing using-a-remote-manager}@anchor{36aa}
@subsubsection リモートマネージャーを使用する


あるマシン上でマネージャーサーバーを実行して、他のマシンからそのサーバーを使用するクライアントを持つことができます(ファイアウォールを通過できることが前提)。

次のコマンドを実行することでリモートクライアントからアクセスを受け付ける1つの共有キューのためにサーバーを作成します:

@example
>>> from multiprocessing.managers import BaseManager
>>> from queue import Queue
>>> queue = Queue()
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue', callable=lambda:queue)
>>> m = QueueManager(address=('@w{'}, 50000), authkey=b'abracadabra')
>>> s = m.get_server()
>>> s.serve_forever()
@end example

あるクライアントからサーバーへのアクセスは次のようになります:

@example
>>> from multiprocessing.managers import BaseManager
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue')
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
>>> m.connect()
>>> queue = m.get_queue()
>>> queue.put('hello')
@end example

別のクライアントもそれを使用することができます:

@example
>>> from multiprocessing.managers import BaseManager
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue')
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
>>> m.connect()
>>> queue = m.get_queue()
>>> queue.get()
'hello'
@end example

ローカルプロセスもそのキューへアクセスすることができます。クライアント上で上述のコードを使用してアクセスします:

@example
>>> from multiprocessing import Process, Queue
>>> from multiprocessing.managers import BaseManager
>>> class Worker(Process):
...     def __init__(self, q):
...         self.q = q
...         super().__init__()
...     def run(self):
...         self.q.put('local hello')
...
>>> queue = Queue()
>>> w = Worker(queue)
>>> w.start()
>>> class QueueManager(BaseManager): pass
...
>>> QueueManager.register('get_queue', callable=lambda: queue)
>>> m = QueueManager(address=('@w{'}, 50000), authkey=b'abracadabra')
>>> s = m.get_server()
>>> s.serve_forever()
@end example

@node Proxy オブジェクト,プロセスプール,マネージャー,リファレンス<3>
@anchor{library/multiprocessing multiprocessing-proxy-objects}@anchor{24c}@anchor{library/multiprocessing proxy-objects}@anchor{36ab}
@subsubsection Proxy オブジェクト


プロキシは別のプロセスで(おそらく)有効な共有オブジェクトを `参照する' オブジェクトです。共有オブジェクトはプロキシの `参照対象' になるということができます。複数のプロキシオブジェクトが同じ参照対象を持つ可能性もあります。

プロキシオブジェクトはその参照対象の対応するメソッドを呼び出すメソッドを持ちます (そうは言っても、参照対象のすべてのメソッドが必ずしもプロキシ経由で利用可能なわけではありません)。
この方法で、プロキシオブジェクトはまるでその参照先と同じように使えます:

@example
>>> mp_context = multiprocessing.get_context('spawn')
>>> manager = mp_context.Manager()
>>> l = manager.list([i*i for i in range(10)])
>>> print(l)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> print(repr(l))
<ListProxy object, typeid 'list' at 0x...>
>>> l[4]
16
>>> l[2:5]
[4, 9, 16]
@end example

プロキシに @ref{169,,str()} を適用すると参照対象のオブジェクト表現を返すのに対して、 @ref{1c1,,repr()} を適用するとプロキシのオブジェクト表現を返すことに注意してください。

プロキシオブジェクトの重要な機能は pickle 化ができることで、これによりプロセス間での受け渡しができます。
そのため、参照対象が @ref{24c,,Proxy オブジェクト} を持てます。
これによって管理されたリスト、辞書、その他 @ref{24c,,Proxy オブジェクト} をネストできます:

@example
>>> a = manager.list()
>>> b = manager.list()
>>> a.append(b)         # referent of a now contains referent of b
>>> print(a, b)
[<ListProxy object, typeid 'list' at ...>] []
>>> b.append('hello')
>>> print(a[0], b)
['hello'] ['hello']
@end example

同様に、辞書とリストのプロキシも他のプロキシの内部に入れてネストできます:

@example
>>> l_outer = manager.list([ manager.dict() for i in range(2) ])
>>> d_first_inner = l_outer[0]
>>> d_first_inner['a'] = 1
>>> d_first_inner['b'] = 2
>>> l_outer[1]['c'] = 3
>>> l_outer[1]['z'] = 26
>>> print(l_outer[0])
@{'a': 1, 'b': 2@}
>>> print(l_outer[1])
@{'c': 3, 'z': 26@}
@end example

(プロキシでない) 標準の @ref{24d,,list} オブジェクトや @ref{183,,dict} オブジェクトが参照対象に含まれていた場合、それらの可変な値の変更はマネージャーからは伝搬されません。
というのも、プロキシには参照対象の中に含まれる値がいつ変更されたかを知る術が無いのです。
しかし、コンテナプロキシに値を保存する (これはプロキシオブジェクトの @code{__setitem__} を起動します) 場合はマネージャーを通して変更が伝搬され、その要素を実際に変更するために、コンテナプロキシに変更後の値が再代入されます:

@example
# create a list proxy and append a mutable object (a dictionary)
lproxy = manager.list()
lproxy.append(@{@})
# now mutate the dictionary
d = lproxy[0]
d['a'] = 1
d['b'] = 2
# at this point, the changes to d are not yet synced, but by
# updating the dictionary, the proxy is notified of the change
lproxy[0] = d
@end example

This approach is perhaps less convenient than employing nested
@ref{24c,,Proxy オブジェクト} for most use cases but also
demonstrates a level of control over the synchronization.

@cartouche
@quotation 注釈 
The proxy types in @code{multiprocessing} do nothing to support comparisons
by value.  So, for instance, we have:

@example
>>> manager.list([1,2,3]) == [1,2,3]
False
@end example

比較を行いたいときは参照対象のコピーを使用してください。
@end quotation
@end cartouche

@geindex BaseProxy (multiprocessing.managers のクラス)
@anchor{library/multiprocessing multiprocessing managers BaseProxy}@anchor{369e}
@deffn {クラス} multiprocessing.managers.BaseProxy

プロキシオブジェクトは @ref{369e,,BaseProxy} のサブクラスのインスタンスです。

@geindex _callmethod() (multiprocessing.managers.BaseProxy のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseProxy _callmethod}@anchor{369f}
@deffn {メソッド} _callmethod (methodname[, args[, kwds]])

プロキシの参照対象のメソッドの実行結果を返します。

@code{proxy} がプロキシで、プロキシ内の参照対象が @code{obj} ならこの式

@example
proxy._callmethod(methodname, args, kwds)
@end example

はこの式を評価します

@example
getattr(obj, methodname)(*args, **kwds)
@end example

(マネージャープロセス内の)。

返される値はその呼び出し結果のコピーか、新たな共有オブジェクトに対するプロキシになります。詳細は @ref{369d,,BaseManager.register()} の `method_to_typeid' 引数のドキュメントを参照してください。

その呼び出しによって例外が発生した場合、@ref{369f,,_callmethod()} によってその例外は再送出されます。他の例外がマネージャープロセスで発生したなら、@code{RemoteError} 例外に変換されたものが @ref{369f,,_callmethod()} によって送出されます。

特に `methodname' が `公開' されていない場合は例外が発生することに注意してください。

@ref{369f,,_callmethod()} の使用例になります:

@example
>>> l = manager.list(range(10))
>>> l._callmethod('__len__')
10
>>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7]
[2, 3, 4, 5, 6]
>>> l._callmethod('__getitem__', (20,))          # equivalent to l[20]
Traceback (most recent call last):
...
IndexError: list index out of range
@end example
@end deffn

@geindex _getvalue() (multiprocessing.managers.BaseProxy のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseProxy _getvalue}@anchor{36ac}
@deffn {メソッド} _getvalue ()

参照対象のコピーを返します。

参照対象が unpickle 化できるなら例外を発生します。
@end deffn

@geindex __repr__() (multiprocessing.managers.BaseProxy のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseProxy __repr__}@anchor{36ad}
@deffn {メソッド} __repr__ ()

プロキシオブジェクトのオブジェクト表現を返します。
@end deffn

@geindex __str__() (multiprocessing.managers.BaseProxy のメソッド)
@anchor{library/multiprocessing multiprocessing managers BaseProxy __str__}@anchor{36ae}
@deffn {メソッド} __str__ ()

参照対象のオブジェクト表現を返します。
@end deffn
@end deffn

@menu
* クリーンアップ: クリーンアップ<2>. 

@end menu

@node クリーンアップ<2>,,,Proxy オブジェクト
@anchor{library/multiprocessing cleanup}@anchor{36af}
@subsubsection クリーンアップ


プロキシオブジェクトは弱参照(weakref)コールバックを使用します。プロキシオブジェクトがガベージコレクトされるときにその参照対象が所有するマネージャーからその登録を取り消せるようにするためです。

共有オブジェクトはプロキシが参照しなくなったときにマネージャープロセスから削除されます。

@node プロセスプール,リスナーとクライアント,Proxy オブジェクト,リファレンス<3>
@anchor{library/multiprocessing module-multiprocessing pool}@anchor{9c}@anchor{library/multiprocessing process-pools}@anchor{36b0}
@subsubsection プロセスプール


@geindex module; multiprocessing.pool

@ref{116d,,Pool} クラスでタスクを実行するプロセスのプールを作成することができます。

@geindex Pool (multiprocessing.pool のクラス)
@anchor{library/multiprocessing multiprocessing pool Pool}@anchor{116d}
@deffn {クラス} multiprocessing.pool.Pool ([processes[, initializer[, initargs[, maxtasksperchild[, context]]]]])

プロセスプールオブジェクトは、ジョブを送り込めるワーカープロセスのプールを制御します。タイムアウトやコールバックのある非同期の実行をサポートし、並列 map 実装を持ちます。

`processes' is the number of worker processes to use.  If `processes' is
@code{None} then the number returned by @ref{4da,,os.process_cpu_count()} is used.

`initializer' が @code{None} ではない場合、各ワーカープロセスは開始時に @code{initializer(*initargs)} を呼び出します。

`maxtasksperchild' は、ワーカープロセスが exit して新たなワーカープロセスと置き替えられるまでの間に、ワーカープロセスが完了することのできるタスクの数です。この設定により未利用のリソースが解放されるようなります。デフォルトの `maxtasksperchild' は @code{None} で、これはワーカープロセスがプールと同じ期間だけ生き続けるということを意味します。

`context' can be used to specify the context used for starting
the worker processes.  Usually a pool is created using the
function @code{multiprocessing.Pool()} or the @ref{116d,,Pool()} method
of a context object.  In both cases `context' is set
appropriately. If @code{None}, calling this function will have the side effect
of setting the current global start method if it has not been set already.
See the @code{get_context()} function.

プールオブジェクトのメソッドは、そのプールを作成したプロセスのみが呼び出すべきです。

@cartouche
@quotation 警告 
@ref{9c,,multiprocessing.pool} objects have internal resources that need to be
properly managed (like any other resource) by using the pool as a context manager
or by calling @ref{36b1,,close()} and @ref{36b2,,terminate()} manually. Failure to do this
can lead to the process hanging on finalization.

Note that it is `not correct' to rely on the garbage collector to destroy the pool
as CPython does not assure that the finalizer of the pool will be called
(see @ref{11ff,,object.__del__()} for more information).
@end quotation
@end cartouche


バージョン 3.2 で変更: Added the `maxtasksperchild' parameter.



バージョン 3.4 で変更: `context' パラメータを追加しました。



バージョン 3.13 で変更: `processes' uses @ref{4da,,os.process_cpu_count()} by default, instead of
@ref{4db,,os.cpu_count()}.


@cartouche
@quotation 注釈 
Worker processes within a @ref{116d,,Pool} typically live for the complete
duration of the Pool's work queue. A frequent pattern found in other
systems (such as Apache, mod_wsgi, etc) to free resources held by
workers is to allow a worker within a pool to complete only a set
amount of work before exiting, being cleaned up and a new
process spawned to replace the old one. The `maxtasksperchild'
argument to the @ref{116d,,Pool} exposes this ability to the end user.
@end quotation
@end cartouche

@geindex apply() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool apply}@anchor{15ad}
@deffn {メソッド} apply (func[, args[, kwds]])

引数 `args' とキーワード引数 `kwds' を伴って `func' を呼びます。結果が準備できるまでブロックします。このブロックがあるため、 @ref{15ae,,apply_async()} の方が並行作業により適しています。加えて、 `func' は、プール内の1つのワーカーだけで実行されます。
@end deffn

@geindex apply_async() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool apply_async}@anchor{15ae}
@deffn {メソッド} apply_async (func[, args[, kwds[, callback[, error_callback]]]])

@ref{15ad,,apply()} メソッドの派生版で @ref{36b3,,AsyncResult} オブジェクトを返します。

`callback' が指定された場合、それは単一の引数を受け取る呼び出し可能オブジェクトでなければなりません。結果を返せるようになったときに `callback' が結果オブジェクトに対して適用されます。ただし呼び出しが失敗した場合は、代わりに `error_callback' が適用されます。

`error_callback' が指定された場合、それは単一の引数を受け取る呼び出し可能オブジェクトでなければなりません。対象の関数が失敗した場合、例外インスタンスを伴って `error_callback' が呼ばれます。

コールバックは直ちに完了すべきです。なぜなら、そうしなければ、結果を扱うスレッドがブロックするからです。
@end deffn

@geindex map() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool map}@anchor{12fb}
@deffn {メソッド} map (func, iterable[, chunksize])

@ref{19f,,map()} 組み込み関数の並列版です (`iterable' な引数を1つだけサポートするという違いはあります。もしも複数のイテラブルを使いたいのならば @ref{12fd,,starmap()} を参照)。結果が出るまでブロックします。

このメソッドはイテラブルをいくつものチャンクに分割し、プロセスプールにそれぞれ独立したタスクとして送ります。(概算の) チャンクサイズは `chunksize' を正の整数に設定することで指定できます。

Note that it may cause high memory usage for very long iterables. Consider
using @ref{36b4,,imap()} or @ref{36b5,,imap_unordered()} with explicit `chunksize'
option for better efficiency.
@end deffn

@geindex map_async() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool map_async}@anchor{12fc}
@deffn {メソッド} map_async (func, iterable[, chunksize[, callback[, error_callback]]])

@ref{12fb,,map()} メソッドの派生版で @ref{36b3,,AsyncResult} オブジェクトを返します。

`callback' が指定された場合、それは単一の引数を受け取る呼び出し可能オブジェクトでなければなりません。結果を返せるようになったときに `callback' が結果オブジェクトに対して適用されます。ただし呼び出しが失敗した場合は、代わりに `error_callback' が適用されます。

`error_callback' が指定された場合、それは単一の引数を受け取る呼び出し可能オブジェクトでなければなりません。対象の関数が失敗した場合、例外インスタンスを伴って `error_callback' が呼ばれます。

コールバックは直ちに完了すべきです。なぜなら、そうしなければ、結果を扱うスレッドがブロックするからです。
@end deffn

@geindex imap() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool imap}@anchor{36b4}
@deffn {メソッド} imap (func, iterable[, chunksize])

@ref{12fb,,map()} の遅延評価版です。

`chunksize' 引数は @ref{12fb,,map()} メソッドで使用されるものと同じです。 引数 iterable がとても長いなら `chunksize' に大きな値を指定して使用する方がデフォルト値の @code{1} を使用するよりもジョブの完了が `かなり' 速くなります。

また `chunksize' が @code{1} の場合 @ref{36b4,,imap()} メソッドが返すイテレーターの @code{next()} メソッドはオプションで `timeout' パラメーターを持ちます。 @code{next(timeout)} は、その結果が `timeout' 秒以内に返されないときに @ref{3665,,multiprocessing.TimeoutError} を発生させます。
@end deffn

@geindex imap_unordered() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool imap_unordered}@anchor{36b5}
@deffn {メソッド} imap_unordered (func, iterable[, chunksize])

イテレーターが返す結果の順番が任意の順番で良いと見なされることを除けば @ref{36b4,,imap()} と同じです。 (ワーカープロセスが1つしかない場合のみ "正しい" 順番になることが保証されます。)
@end deffn

@geindex starmap() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool starmap}@anchor{12fd}
@deffn {メソッド} starmap (func, iterable[, chunksize])

`iterable' の要素が、引数として unpack されるイテレート可能オブジェクトであると期待される以外は、 @ref{12fb,,map()} と似ています。

そのため、`iterable' が @code{[(1,2), (3, 4)]} なら、結果は @code{[func(1,2), func(3,4)]} になります。


Added in version 3.3.

@end deffn

@geindex starmap_async() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool starmap_async}@anchor{12fe}
@deffn {メソッド} starmap_async (func, iterable[, chunksize[, callback[, error_callback]]])

@ref{12fd,,starmap()} と @ref{12fc,,map_async()} の組み合わせです。 イテレート可能オブジェクトの `iterable' をイテレートして、 unpack したイテレート可能オブジェクトを伴って `func' を呼び出します。結果オブジェクトを返します。


Added in version 3.3.

@end deffn

@geindex close() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool close}@anchor{36b1}
@deffn {メソッド} close ()

これ以上プールでタスクが実行されないようにします。すべてのタスクが完了した後でワーカープロセスが終了します。
@end deffn

@geindex terminate() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool terminate}@anchor{36b2}
@deffn {メソッド} terminate ()

実行中の処理を完了させずにワーカープロセスをすぐに停止します。プールオブジェクトがガベージコレクトされるときに @ref{36b2,,terminate()} が呼び出されます。
@end deffn

@geindex join() (multiprocessing.pool.Pool のメソッド)
@anchor{library/multiprocessing multiprocessing pool Pool join}@anchor{36b6}
@deffn {メソッド} join ()

ワーカープロセスが終了するのを待ちます。 @ref{36b6,,join()} を使用する前に @ref{36b1,,close()} か @ref{36b2,,terminate()} を呼び出さなければなりません。
@end deffn


バージョン 3.3 で変更: Pool オブジェクトがコンテキストマネージメント・プロトコルをサポートするようになりました。 -- @ref{240d,,コンテキストマネージャ型} を参照してください。 @ref{26a8,,__enter__()} は Pool オブジェクトを返します。また @ref{26a9,,__exit__()} は @ref{36b2,,terminate()} を呼び出します。

@end deffn

@geindex AsyncResult (multiprocessing.pool のクラス)
@anchor{library/multiprocessing multiprocessing pool AsyncResult}@anchor{36b3}
@deffn {クラス} multiprocessing.pool.AsyncResult

@ref{15ae,,Pool.apply_async()} や @ref{12fc,,Pool.map_async()} で返される結果のクラスです。

@geindex get() (multiprocessing.pool.AsyncResult のメソッド)
@anchor{library/multiprocessing multiprocessing pool AsyncResult get}@anchor{36b7}
@deffn {メソッド} get ([timeout])

結果を受け取ったときに返します。 `timeout' が @code{None} ではなくて、その結果が `timeout' 秒以内に受け取れない場合 @ref{3665,,multiprocessing.TimeoutError} が発生します。リモートの呼び出しが例外を発生させる場合、その例外は @ref{36b7,,get()} が再発生させます。
@end deffn

@geindex wait() (multiprocessing.pool.AsyncResult のメソッド)
@anchor{library/multiprocessing multiprocessing pool AsyncResult wait}@anchor{36b8}
@deffn {メソッド} wait ([timeout])

その結果が有効になるか `timeout' 秒経つまで待ちます。
@end deffn

@geindex ready() (multiprocessing.pool.AsyncResult のメソッド)
@anchor{library/multiprocessing multiprocessing pool AsyncResult ready}@anchor{36b9}
@deffn {メソッド} ready ()

その呼び出しが完了しているかどうかを返します。
@end deffn

@geindex successful() (multiprocessing.pool.AsyncResult のメソッド)
@anchor{library/multiprocessing multiprocessing pool AsyncResult successful}@anchor{36ba}
@deffn {メソッド} successful ()

その呼び出しが例外を発生させることなく完了したかどうかを返します。その結果が返せる状態でない場合 @ref{2ec,,ValueError} が発生します。


バージョン 3.7 で変更: If the result is not ready, @ref{2ec,,ValueError} is raised instead of
@ref{8b8,,AssertionError}.

@end deffn
@end deffn

次の例はプールの使用例を紹介します:

@example
from multiprocessing import Pool
import time

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(processes=4) as pool:         # start 4 worker processes
        result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
        print(result.get(timeout=1))        # prints "100" unless your computer is *very* slow

        print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"

        it = pool.imap(f, range(10))
        print(next(it))                     # prints "0"
        print(next(it))                     # prints "1"
        print(it.next(timeout=1))           # prints "4" unless your computer is *very* slow

        result = pool.apply_async(time.sleep, (10,))
        print(result.get(timeout=1))        # raises multiprocessing.TimeoutError
@end example

@node リスナーとクライアント,認証キー,プロセスプール,リファレンス<3>
@anchor{library/multiprocessing listeners-and-clients}@anchor{36bb}@anchor{library/multiprocessing module-multiprocessing connection}@anchor{99}@anchor{library/multiprocessing multiprocessing-listeners-clients}@anchor{367d}
@subsubsection リスナーとクライアント


@geindex module; multiprocessing.connection

通常、プロセス間でメッセージを渡すにはキューを使用するか @ref{364c,,Pipe()} が返す @ref{12f8,,Connection} オブジェクトを使用します。

However, the @code{multiprocessing.connection} module allows some extra
flexibility.  It basically gives a high level message oriented API for dealing
with sockets or Windows named pipes.  It also has support for `digest
authentication' using the @ref{6e,,hmac} module, and for polling
multiple connections at the same time.

@geindex deliver_challenge() (multiprocessing.connection モジュール)
@anchor{library/multiprocessing multiprocessing connection deliver_challenge}@anchor{36bc}
@deffn {の関数} multiprocessing.connection.deliver_challenge (connection, authkey)

ランダム生成したメッセージをコネクションの相手側へ送信して応答を待ちます。

その応答がキーとして `authkey' を使用するメッセージのダイジェストと一致する場合、 コネクションの相手側へ歓迎メッセージを送信します。 そうでなければ @ref{3664,,AuthenticationError} を発生させます。
@end deffn

@geindex answer_challenge() (multiprocessing.connection モジュール)
@anchor{library/multiprocessing multiprocessing connection answer_challenge}@anchor{36bd}
@deffn {の関数} multiprocessing.connection.answer_challenge (connection, authkey)

メッセージを受信して、そのキーとして `authkey' を使用するメッセージのダイジェストを計算し、ダイジェストを送り返します。

歓迎メッセージを受け取れない場合 @ref{3664,,AuthenticationError} が発生します。
@end deffn

@geindex Client() (multiprocessing.connection モジュール)
@anchor{library/multiprocessing multiprocessing connection Client}@anchor{36be}
@deffn {の関数} multiprocessing.connection.Client (address[, family[, authkey]])

`address' で渡したアドレスを使用するリスナーに対してコネクションを確立しようとして @ref{12f8,,Connection} を返します。

コネクション種別は `family' 引数で決定しますが、一般的には `address' のフォーマットから推測できるので、これは指定されません。 (@ref{36bf,,アドレスフォーマット} を参照してください)

If `authkey' is given and not @code{None}, it should be a byte string and will be
used as the secret key for an HMAC-based authentication challenge. No
authentication is done if `authkey' is @code{None}.
@ref{3664,,AuthenticationError} is raised if authentication fails.
See @ref{3661,,認証キー}.
@end deffn

@geindex Listener (multiprocessing.connection のクラス)
@anchor{library/multiprocessing multiprocessing connection Listener}@anchor{1a23}
@deffn {クラス} multiprocessing.connection.Listener ([address[, family[, backlog[, authkey]]]])

コネクションを '待ち受ける' 束縛されたソケットか Windows の名前付きパイプのラッパーです。

`address' はリスナーオブジェクトの束縛されたソケットか名前付きパイプが使用するアドレスです。

@cartouche
@quotation 注釈 
'0.0.0.0' のアドレスを使用する場合、Windows 上の終点へ接続することができません。終点へ接続したい場合は '127.0.0.1' を使用すべきです。
@end quotation
@end cartouche

`family' は使用するソケット(名前付きパイプ)の種別です。これは @code{'AF_INET'} (TCP ソケット), @code{'AF_UNIX'} (Unix ドメインソケット) または @code{'AF_PIPE'} (Windows 名前付きパイプ) という文字列のどれか1つになります。これらのうち @code{'AF_INET'} のみが利用可能であることが保証されています。 `family' が @code{None} の場合 `address' のフォーマットから推測されたものが使用されます。 `address' も @code{None} の場合はデフォルトが選択されます。詳細は @ref{36bf,,アドレスフォーマット} を参照してください。 `family' が @code{'AF_UNIX'} で `address' が @code{None} の場合 @ref{2cca,,tempfile.mkstemp()} を使用して作成されたプライベートな一時ディレクトリにソケットが作成されます。

リスナーオブジェクトがソケットを使用する場合、ソケットに束縛されるときに `backlog' (デフォルトでは1つ) がソケットの @ref{105e,,listen()} メソッドに対して渡されます。

If `authkey' is given and not @code{None}, it should be a byte string and will be
used as the secret key for an HMAC-based authentication challenge. No
authentication is done if `authkey' is @code{None}.
@ref{3664,,AuthenticationError} is raised if authentication fails.
See @ref{3661,,認証キー}.

@geindex accept() (multiprocessing.connection.Listener のメソッド)
@anchor{library/multiprocessing multiprocessing connection Listener accept}@anchor{19df}
@deffn {メソッド} accept ()

リスナーオブジェクトの名前付きパイプか束縛されたソケット上でコネクションを 受け付けて @ref{12f8,,Connection} オブジェクトを返します。 認証が失敗した場合 @ref{3664,,AuthenticationError} が発生します。
@end deffn

@geindex close() (multiprocessing.connection.Listener のメソッド)
@anchor{library/multiprocessing multiprocessing connection Listener close}@anchor{36c0}
@deffn {メソッド} close ()

リスナーオブジェクトの名前付きパイプか束縛されたソケットをクローズします。これはリスナーがガベージコレクトされるときに自動的に呼ばれます。そうは言っても、明示的に close() を呼び出す方が望ましいです。
@end deffn

リスナーオブジェクトは次の読み出し専用属性を持っています:

@geindex address (multiprocessing.connection.Listener の属性)
@anchor{library/multiprocessing multiprocessing connection Listener address}@anchor{36c1}
@deffn {の属性} address

リスナーオブジェクトが使用中のアドレスです。
@end deffn

@geindex last_accepted (multiprocessing.connection.Listener の属性)
@anchor{library/multiprocessing multiprocessing connection Listener last_accepted}@anchor{36c2}
@deffn {の属性} last_accepted

最後にコネクションを受け付けたアドレスです。有効なアドレスがない場合は @code{None} になります。
@end deffn


バージョン 3.3 で変更: Listener オブジェクトがコンテキストマネージメント・プロトコルをサポートするようになりました。 -- @ref{240d,,コンテキストマネージャ型} を参照してください。 @ref{26a8,,__enter__()} はリスナーオブジェクトを返します。また @ref{26a9,,__exit__()} は @ref{36c0,,close()} を呼び出します。

@end deffn

@geindex wait() (multiprocessing.connection モジュール)
@anchor{library/multiprocessing multiprocessing connection wait}@anchor{12f7}
@deffn {の関数} multiprocessing.connection.wait (object_list, timeout=None)

`object_list' 中のオブジェクトが準備ができるまで待機します。準備ができた `object_list' 中のオブジェクトのリストを返します。`timeout' が浮動小数点なら、最大でその秒数だけ呼び出しがブロックします。`timeout' が @code{None} の場合、無制限の期間ブロックします。負のタイムアウトは0と等価です。

For both POSIX and Windows, an object can appear in `object_list' if
it is


@itemize *

@item 
読み取り可能な @ref{12f8,,Connection} オブジェクト;

@item 
接続された読み取り可能な @ref{fa1,,socket.socket} オブジェクト; または

@item 
@ref{252,,Process} オブジェクトの @ref{12f9,,sentinel} 属性。
@end itemize

読み取ることのできるデータがある場合、あるいは相手側の端が閉じられている場合、コネクションまたはソケットオブジェクトは準備ができています。

`POSIX': @code{wait(object_list, timeout)} almost equivalent
@code{select.select(object_list, [], [], timeout)}.  The difference is
that, if @ref{fa0,,select.select()} is interrupted by a signal, it can
raise @ref{2c0,,OSError} with an error number of @code{EINTR}, whereas
@ref{12f7,,wait()} will not.

`Windows': An item in `object_list' must either be an integer
handle which is waitable (according to the definition used by the
documentation of the Win32 function @code{WaitForMultipleObjects()})
or it can be an object with a @ref{17ad,,fileno()} method which returns a
socket handle or pipe handle.  (Note that pipe handles and socket
handles are `not' waitable handles.)


Added in version 3.3.

@end deffn

`例'

次のサーバーコードは認証キーとして @code{'secret password'} を使用するリスナーを作成します。このサーバーはコネクションを待ってクライアントへデータを送信します:

@example
from multiprocessing.connection import Listener
from array import array

address = ('localhost', 6000)     # family is deduced to be 'AF_INET'

with Listener(address, authkey=b'secret password') as listener:
    with listener.accept() as conn:
        print('connection accepted from', listener.last_accepted)

        conn.send([2.25, None, 'junk', float])

        conn.send_bytes(b'hello')

        conn.send_bytes(array('i', [42, 1729]))
@end example

次のコードはサーバーへ接続して、サーバーからデータを受信します:

@example
from multiprocessing.connection import Client
from array import array

address = ('localhost', 6000)

with Client(address, authkey=b'secret password') as conn:
    print(conn.recv())                  # => [2.25, None, 'junk', float]

    print(conn.recv_bytes())            # => 'hello'

    arr = array('i', [0, 0, 0, 0, 0])
    print(conn.recv_bytes_into(arr))    # => 8
    print(arr)                          # => array('i', [42, 1729, 0, 0, 0])
@end example

次のコードは @ref{12f7,,wait()} を使って複数のプロセスからのメッセージを同時に待ちます:

@example
from multiprocessing import Process, Pipe, current_process
from multiprocessing.connection import wait

def foo(w):
    for i in range(10):
        w.send((i, current_process().name))
    w.close()

if __name__ == '__main__':
    readers = []

    for i in range(4):
        r, w = Pipe(duplex=False)
        readers.append(r)
        p = Process(target=foo, args=(w,))
        p.start()
        # We close the writable end of the pipe now to be sure that
        # p is the only process which owns a handle for it.  This
        # ensures that when p closes its handle for the writable end,
        # wait() will promptly report the readable end as being ready.
        w.close()

    while readers:
        for r in wait(readers):
            try:
                msg = r.recv()
            except EOFError:
                readers.remove(r)
            else:
                print(msg)
@end example

@menu
* アドレスフォーマット:: 

@end menu

@node アドレスフォーマット,,,リスナーとクライアント
@anchor{library/multiprocessing address-formats}@anchor{36c3}@anchor{library/multiprocessing multiprocessing-address-formats}@anchor{36bf}
@subsubsection アドレスフォーマット



@itemize *

@item 
@code{'AF_INET'} アドレスは @code{(hostname, port)} のタプルになります。 `hostname' は文字列で `port' は整数です。

@item 
@code{'AF_UNIX'} アドレスはファイルシステム上のファイル名の文字列です。

@item 
@code{'AF_PIPE'} アドレスは @code{r'\\.\pipe\@var{PipeName}'} という形式の文字列です。 `ServerName' という名前のリモートコンピューター上の名前付きパイプに接続するために @ref{36be,,Client()} を使用するには、代わりに @code{r'\\@var{ServerName}\pipe\@var{PipeName}'} 形式のアドレスを使用する必要があります。
@end itemize

デフォルトでは、2つのバックスラッシュで始まる文字列は @code{'AF_UNIX'} よりも @code{'AF_PIPE'} として推測されることに注意してください。

@node 認証キー,ログ記録<2>,リスナーとクライアント,リファレンス<3>
@anchor{library/multiprocessing authentication-keys}@anchor{36c4}@anchor{library/multiprocessing multiprocessing-auth-keys}@anchor{3661}
@subsubsection 認証キー


@code{Connection.recv} を使用するとき、データは自動的に unpickle されて受信します。 信頼できない接続元からのデータを unpickle することはセキュリティリスクがあります。 そのため @ref{1a23,,Listener} や @ref{36be,,Client()} はダイジェスト認証を提供するために @ref{6e,,hmac} モジュールを使用します。

認証キーはパスワードとして見なされるバイト文字列です。コネクションが確立すると、双方の終点で正しい接続先であることを証明するために 知っているお互いの認証キーを要求します。(双方の終点が同じキーを使用して通信しようとしても、コネクション上でそのキーを送信することは `できません'。)

認証が要求されているにもかかわらず認証キーが指定されていない場合 @code{current_process().authkey} の返す値が使用されます。 (詳細は @ref{252,,Process} を参照してください。) この値はカレントプロセスを作成する @ref{252,,Process} オブジェクトによって自動的に継承されます。 これは(デフォルトでは)複数プロセスのプログラムの全プロセスが相互にコネクションを 確立するときに使用される1つの認証キーを共有することを意味します。

適当な認証キーを @ref{746,,os.urandom()} を使用して生成することもできます。

@node ログ記録<2>,The multiprocessing dummy module,認証キー,リファレンス<3>
@anchor{library/multiprocessing logging}@anchor{36c5}
@subsubsection ログ記録


ロギングのためにいくつかの機能が利用可能です。しかし @ref{8b,,logging} パッケージは、 (ハンドラー種別に依存して)違うプロセスからのメッセージがごちゃ混ぜになるので、プロセスの共有ロックを使用しないことに注意してください。

@geindex get_logger() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing get_logger}@anchor{321f}
@deffn {の関数} multiprocessing.get_logger ()

Returns the logger used by @code{multiprocessing}.  If necessary, a new one
will be created.

When first created the logger has level @ref{315a,,logging.NOTSET} and no
default handler. Messages sent to this logger will not by default propagate
to the root logger.

Windows 上では子プロセスが親プロセスのロガーレベルを継承しないことに注意してください。さらにその他のロガーのカスタマイズ内容もすべて継承されません。
@end deffn

@geindex log_to_stderr() (multiprocessing モジュール)
@anchor{library/multiprocessing multiprocessing log_to_stderr}@anchor{36c6}
@deffn {の関数} multiprocessing.log_to_stderr (level=None)

この関数は @ref{321f,,get_logger()} に対する呼び出しを実行しますが、 get_logger によって作成されるロガーを返すことに加えて、 @code{'[%(levelname)s/%(processName)s] %(message)s'} のフォーマットを使用して @ref{b33,,sys.stderr} へ出力を送るハンドラーを追加します。@code{level} 引数を渡すことによってロガーの @code{levelname} を変更できます。
@end deffn

以下にロギングを有効にした例を紹介します:

@example
>>> import multiprocessing, logging
>>> logger = multiprocessing.log_to_stderr()
>>> logger.setLevel(logging.INFO)
>>> logger.warning('doomed')
[WARNING/MainProcess] doomed
>>> m = multiprocessing.Manager()
[INFO/SyncManager-...] child process calling self.run()
[INFO/SyncManager-...] created temp directory /.../pymp-...
[INFO/SyncManager-...] manager serving at '/.../listener-...'
>>> del m
[INFO/MainProcess] sending shutdown message to manager
[INFO/SyncManager-...] manager exiting with exitcode 0
@end example

完全なロギングレベルの表については @ref{8b,,logging} モジュールを参照してください。

@node The multiprocessing dummy module,,ログ記録<2>,リファレンス<3>
@anchor{library/multiprocessing module-multiprocessing dummy}@anchor{9a}@anchor{library/multiprocessing the-multiprocessing-dummy-module}@anchor{36c7}
@subsubsection The @code{multiprocessing.dummy} module


@geindex module; multiprocessing.dummy

@code{multiprocessing.dummy} replicates the API of @code{multiprocessing} but is
no more than a wrapper around the @ref{f3,,threading} module.

In particular, the @code{Pool} function provided by @code{multiprocessing.dummy}
returns an instance of @ref{1cd4,,ThreadPool}, which is a subclass of
@ref{116d,,Pool} that supports all the same method calls but uses a pool of
worker threads rather than worker processes.

@geindex ThreadPool (multiprocessing.pool のクラス)
@anchor{library/multiprocessing multiprocessing pool ThreadPool}@anchor{1cd4}
@deffn {クラス} multiprocessing.pool.ThreadPool ([processes[, initializer[, initargs]]])

A thread pool object which controls a pool of worker threads to which jobs
can be submitted.  @ref{1cd4,,ThreadPool} instances are fully interface
compatible with @ref{116d,,Pool} instances, and their resources must also be
properly managed, either by using the pool as a context manager or by
calling @ref{36b1,,close()} and
@ref{36b2,,terminate()} manually.

`processes' is the number of worker threads to use.  If `processes' is
@code{None} then the number returned by @ref{4da,,os.process_cpu_count()} is used.

`initializer' が @code{None} ではない場合、各ワーカープロセスは開始時に @code{initializer(*initargs)} を呼び出します。

Unlike @ref{116d,,Pool}, `maxtasksperchild' and `context' cannot be provided.

@cartouche
@quotation 注釈 
A @ref{1cd4,,ThreadPool} shares the same interface as @ref{116d,,Pool}, which
is designed around a pool of processes and predates the introduction of
the @ref{24,,concurrent.futures} module.  As such, it inherits some
operations that don't make sense for a pool backed by threads, and it
has its own type for representing the status of asynchronous jobs,
@ref{36b3,,AsyncResult}, that is not understood by any other libraries.

Users should generally prefer to use
@ref{949,,concurrent.futures.ThreadPoolExecutor}, which has a simpler
interface that was designed around threads from the start, and which
returns @ref{13ca,,concurrent.futures.Future} instances that are
compatible with many other libraries, including @ref{b,,asyncio}.
@end quotation
@end cartouche
@end deffn

@node プログラミングガイドライン,使用例<21>,リファレンス<3>,multiprocessing --- プロセスベースの並列処理
@anchor{library/multiprocessing multiprocessing-programming}@anchor{3648}@anchor{library/multiprocessing programming-guidelines}@anchor{36c8}
@subsubsection プログラミングガイドライン


There are certain guidelines and idioms which should be adhered to when using
@code{multiprocessing}.

@menu
* すべての開始方式について:: 
* 開始方式が spawn および forkserver の場合:: 

@end menu

@node すべての開始方式について,開始方式が spawn および forkserver の場合,,プログラミングガイドライン
@anchor{library/multiprocessing all-start-methods}@anchor{36c9}
@subsubsection すべての開始方式について


以下はすべての開始方式に当てはまります。

共有状態を避ける

@quotation

できるだけプロセス間で巨大なデータを移動することは避けるようにすべきです。

プロセス間の通信には、@ref{f3,,threading} モジュールの低レベルな同期プリミティブを使うのではなく、キューやパイプを使うのが良いでしょう。
@end quotation

pickle 化の可能性

@quotation

プロキシのメソッドへの引数は、 pickle 化できるものにしてください。
@end quotation

プロキシのスレッドセーフ性

@quotation

1 つのプロキシオブジェクトは、ロックで保護しないかぎり、2 つ以上のスレッドから使用してはいけません。

(異なるプロセスで `同じ' プロキシを使用することは問題ではありません。)
@end quotation

ゾンビプロセスを join する

@quotation

On POSIX when a process finishes but has not been joined it becomes a zombie.
There should never be very many because each time a new process starts (or
@ref{3679,,active_children()} is called) all completed processes
which have not yet been joined will be joined.  Also calling a finished
process's @ref{15aa,,Process.is_alive} will
join the process.  Even so it is probably good
practice to explicitly join all the processes that you start.
@end quotation

pickle/unpickle より継承する方が良い

@quotation

When using the `spawn' or `forkserver' start methods many types
from @code{multiprocessing} need to be picklable so that child
processes can use them.  However, one should generally avoid
sending shared objects to other processes using pipes or queues.
Instead you should arrange the program so that a process which
needs access to a shared resource created elsewhere can inherit it
from an ancestor process.
@end quotation

プロセスの強制終了を避ける

@quotation

あるプロセスを停止するために @ref{1857,,Process.terminate} メソッドを使用すると、そのプロセスが現在使用されている (ロック、セマフォ、パイプやキューのような) 共有リソースを破壊したり他のプロセスから利用できない状態を引き起こし易いです。

そのため、共有リソースを使用しないプロセスでのみ @ref{1857,,Process.terminate} を使用することを考慮することがおそらく最善の方法です。
@end quotation

キューを使用するプロセスを join する

@quotation

キューに要素を追加するプロセスは、すべてのバッファーされた要素が "feeder" スレッドによって下位層のパイプに対してフィードされるまで終了を待つということを覚えておいてください。 (子プロセスはこの動作を避けるためにキューの @ref{366f,,Queue.cancel_join_thread} メソッドを呼ぶことができます。)

これはキューを使用するときに、キューに追加されたすべての要素が最終的にそのプロセスが join される前に削除されていることを確認する必要があることを意味します。そうしないと、そのキューに要素が追加したプロセスの終了を保証できません。デーモンではないプロセスは自動的に join されることも覚えておいてください。

次の例はデッドロックを引き起こします:

@example
from multiprocessing import Process, Queue

def f(q):
    q.put('X' * 1000000)

if __name__ == '__main__':
    queue = Queue()
    p = Process(target=f, args=(queue,))
    p.start()
    p.join()                    # this deadlocks
    obj = queue.get()
@end example

修正するには最後の2行を入れ替えます(または単純に @code{p.join()} の行を削除します)。
@end quotation

明示的に子プロセスへリソースを渡す

@quotation

On POSIX using the `fork' start method, a child process can make
use of a shared resource created in a parent process using a
global resource.  However, it is better to pass the object as an
argument to the constructor for the child process.

Windows や他の開始方式と (将来的にでも) 互換性のあるコードを書く場合は別として、これは子プロセスが実行中である限りは親プロセス内でオブジェクトがガベージコレクトされないことも保証します。これは親プロセス内でオブジェクトがガベージコレクトされたときに一部のリソースが開放されてしまう場合に重要かもしれません。

そのため、例えば

@example
from multiprocessing import Process, Lock

def f():
    ... do something using "lock" ...

if __name__ == '__main__':
    lock = Lock()
    for i in range(10):
        Process(target=f).start()
@end example

は、次のように書き直すべきです

@example
from multiprocessing import Process, Lock

def f(l):
    ... do something using "l" ...

if __name__ == '__main__':
    lock = Lock()
    for i in range(10):
        Process(target=f, args=(lock,)).start()
@end example
@end quotation

@ref{75f,,sys.stdin} を file-like オブジェクトに置き換えることに注意する

@quotation

@code{multiprocessing} originally unconditionally called:

@example
os.close(sys.stdin.fileno())
@end example

を @code{multiprocessing.Process._bootstrap()} メソッドの中で呼び出していました --- これはプロセス内プロセス (processes-in-processes) で問題が起こしてしまいます。そこで、これは以下のように変更されました:

@example
sys.stdin.close()
sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)
@end example

Which solves the fundamental issue of processes colliding with each other
resulting in a bad file descriptor error, but introduces a potential danger
to applications which replace @ref{75f,,sys.stdin()} with a "file-like object"
with output buffering.  This danger is that if multiple processes call
@ref{506,,close()} on this file-like object, it could result in the same
data being flushed to the object multiple times, resulting in corruption.

もし file-like オブジェクトを書いて独自のキャッシュを実装するなら、キャッシュするときに常に pid を記録しておき、pid が変わったらキュッシュを捨てることで、フォークセーフにできます。例:

@example
@@property
def cache(self):
    pid = os.getpid()
    if pid != self._pid:
        self._pid = pid
        self._cache = []
    return self._cache
@end example

より詳しい情報は bpo-5155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5155} 、 bpo-5313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5313} 、 bpo-5331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5331} を見てください
@end quotation
@anchor{library/multiprocessing multiprocessing-programming-spawn}@anchor{365d}
@node 開始方式が spawn および forkserver の場合,,すべての開始方式について,プログラミングガイドライン
@anchor{library/multiprocessing multiprocessing-programming-forkserver}@anchor{1d9}@anchor{library/multiprocessing the-spawn-and-forkserver-start-methods}@anchor{36ca}
@subsubsection 開始方式が `spawn' および `forkserver' の場合


There are a few extra restrictions which don't apply to the `fork'
start method.

さらなる pickle 化の可能性

@quotation

Ensure that all arguments to @ref{252,,Process} are
picklable.  Also, if you subclass @code{Process.__init__}, you must make sure
that instances will be picklable when the
@ref{15a9,,Process.start} method is called.
@end quotation

グローバル変数

@quotation

子プロセスで実行されるコードがグローバル変数にアクセスしようとする場合、子プロセスが見るその値は @ref{15a9,,Process.start} が呼ばれたときの親プロセスの値と同じではない可能性があります。

しかし、単にモジュールレベルの定数であるグローバル変数なら問題にはなりません。
@end quotation
@anchor{library/multiprocessing multiprocessing-safe-main-import}@anchor{36cb}
メインモジュールの安全なインポート

@quotation

Make sure that the main module can be safely imported by a new Python
interpreter without causing unintended side effects (such as starting a new
process).

例えば、開始方式に `spawn' あるいは `forkserver' を使用した場合に以下のモジュールを実行すると @ref{244,,RuntimeError} で失敗します:

@example
from multiprocessing import Process

def foo():
    print('hello')

p = Process(target=foo)
p.start()
@end example

代わりに、次のように @code{if __name__ == '__main__':} を使用してプログラムの "エントリポイント" を保護すべきです:

@example
from multiprocessing import Process, freeze_support, set_start_method

def foo():
    print('hello')

if __name__ == '__main__':
    freeze_support()
    set_start_method('spawn')
    p = Process(target=foo)
    p.start()
@end example

(プログラムをフリーズせずに通常通り実行するなら @code{freeze_support()} 行は取り除けます。)

これは新たに生成された Python インタープリターがそのモジュールを安全にインポートして、モジュールの @code{foo()} 関数を実行します。

プールまたはマネージャーがメインモジュールで作成される場合に似たような制限が適用されます。
@end quotation

@node 使用例<21>,,プログラミングガイドライン,multiprocessing --- プロセスベースの並列処理
@anchor{library/multiprocessing examples}@anchor{36cc}@anchor{library/multiprocessing multiprocessing-examples}@anchor{3670}
@subsubsection 使用例


カスタマイズされたマネージャーやプロキシの作成方法と使用方法を紹介します:

@example
from multiprocessing import freeze_support
from multiprocessing.managers import BaseManager, BaseProxy
import operator

##

class Foo:
    def f(self):
        print('you called Foo.f()')
    def g(self):
        print('you called Foo.g()')
    def _h(self):
        print('you called Foo._h()')

# A simple generator function
def baz():
    for i in range(10):
        yield i*i

# Proxy type for generator objects
class GeneratorProxy(BaseProxy):
    _exposed_ = ['__next__']
    def __iter__(self):
        return self
    def __next__(self):
        return self._callmethod('__next__')

# Function to return the operator module
def get_operator_module():
    return operator

##

class MyManager(BaseManager):
    pass

# register the Foo class; make `f()` and `g()` accessible via proxy
MyManager.register('Foo1', Foo)

# register the Foo class; make `g()` and `_h()` accessible via proxy
MyManager.register('Foo2', Foo, exposed=('g', '_h'))

# register the generator function baz; use `GeneratorProxy` to make proxies
MyManager.register('baz', baz, proxytype=GeneratorProxy)

# register get_operator_module(); make public functions accessible via proxy
MyManager.register('operator', get_operator_module)

##

def test():
    manager = MyManager()
    manager.start()

    print('-' * 20)

    f1 = manager.Foo1()
    f1.f()
    f1.g()
    assert not hasattr(f1, '_h')
    assert sorted(f1._exposed_) == sorted(['f', 'g'])

    print('-' * 20)

    f2 = manager.Foo2()
    f2.g()
    f2._h()
    assert not hasattr(f2, 'f')
    assert sorted(f2._exposed_) == sorted(['g', '_h'])

    print('-' * 20)

    it = manager.baz()
    for i in it:
        print('<%d>' % i, end=' ')
    print()

    print('-' * 20)

    op = manager.operator()
    print('op.add(23, 45) =', op.add(23, 45))
    print('op.pow(2, 94) =', op.pow(2, 94))
    print('op._exposed_ =', op._exposed_)

##

if __name__ == '__main__':
    freeze_support()
    test()
@end example

@ref{116d,,Pool} を使用する例です:

@example
import multiprocessing
import time
import random
import sys

#
# Functions used by test code
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % (
        multiprocessing.current_process().name,
        func.__name__, args, result
        )

def calculatestar(args):
    return calculate(*args)

def mul(a, b):
    time.sleep(0.5 * random.random())
    return a * b

def plus(a, b):
    time.sleep(0.5 * random.random())
    return a + b

def f(x):
    return 1.0 / (x - 5.0)

def pow3(x):
    return x ** 3

def noop(x):
    pass

#
# Test code
#

def test():
    PROCESSES = 4
    print('Creating pool with %d processes\n' % PROCESSES)

    with multiprocessing.Pool(PROCESSES) as pool:
        #
        # Tests
        #

        TASKS = [(mul, (i, 7)) for i in range(10)] + \
                [(plus, (i, 8)) for i in range(10)]

        results = [pool.apply_async(calculate, t) for t in TASKS]
        imap_it = pool.imap(calculatestar, TASKS)
        imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)

        print('Ordered results using pool.apply_async():')
        for r in results:
            print('\t', r.get())
        print()

        print('Ordered results using pool.imap():')
        for x in imap_it:
            print('\t', x)
        print()

        print('Unordered results using pool.imap_unordered():')
        for x in imap_unordered_it:
            print('\t', x)
        print()

        print('Ordered results using pool.map() --- will block till complete:')
        for x in pool.map(calculatestar, TASKS):
            print('\t', x)
        print()

        #
        # Test error handling
        #

        print('Testing error handling:')

        try:
            print(pool.apply(f, (5,)))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from pool.apply()')
        else:
            raise AssertionError('expected ZeroDivisionError')

        try:
            print(pool.map(f, list(range(10))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from pool.map()')
        else:
            raise AssertionError('expected ZeroDivisionError')

        try:
            print(list(pool.imap(f, list(range(10)))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from list(pool.imap())')
        else:
            raise AssertionError('expected ZeroDivisionError')

        it = pool.imap(f, list(range(10)))
        for i in range(10):
            try:
                x = next(it)
            except ZeroDivisionError:
                if i == 5:
                    pass
            except StopIteration:
                break
            else:
                if i == 5:
                    raise AssertionError('expected ZeroDivisionError')

        assert i == 9
        print('\tGot ZeroDivisionError as expected from IMapIterator.next()')
        print()

        #
        # Testing timeouts
        #

        print('Testing ApplyResult.get() with timeout:', end=' ')
        res = pool.apply_async(calculate, TASKS[0])
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % res.get(0.02))
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()

        print('Testing IMapIterator.next() with timeout:', end=' ')
        it = pool.imap(calculatestar, TASKS)
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % it.next(0.02))
            except StopIteration:
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()


if __name__ == '__main__':
    multiprocessing.freeze_support()
    test()
@end example

ワーカープロセスのコレクションに対してタスクをフィードしてその結果をまとめるキューの使い方の例を紹介します:

@example
import time
import random

from multiprocessing import Process, Queue, current_process, freeze_support

#
# Function run by worker processes
#

def worker(input, output):
    for func, args in iter(input.get, 'STOP'):
        result = calculate(func, args)
        output.put(result)

#
# Function used to calculate result
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % \
        (current_process().name, func.__name__, args, result)

#
# Functions referenced by tasks
#

def mul(a, b):
    time.sleep(0.5*random.random())
    return a * b

def plus(a, b):
    time.sleep(0.5*random.random())
    return a + b

#
#
#

def test():
    NUMBER_OF_PROCESSES = 4
    TASKS1 = [(mul, (i, 7)) for i in range(20)]
    TASKS2 = [(plus, (i, 8)) for i in range(10)]

    # Create queues
    task_queue = Queue()
    done_queue = Queue()

    # Submit tasks
    for task in TASKS1:
        task_queue.put(task)

    # Start worker processes
    for i in range(NUMBER_OF_PROCESSES):
        Process(target=worker, args=(task_queue, done_queue)).start()

    # Get and print results
    print('Unordered results:')
    for i in range(len(TASKS1)):
        print('\t', done_queue.get())

    # Add more tasks using `put()`
    for task in TASKS2:
        task_queue.put(task)

    # Get and print some more results
    for i in range(len(TASKS2)):
        print('\t', done_queue.get())

    # Tell child processes to stop
    for i in range(NUMBER_OF_PROCESSES):
        task_queue.put('STOP')


if __name__ == '__main__':
    freeze_support()
    test()
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node multiprocessing shared_memory --- プロセス間で直接アクセス可能な共有メモリ,concurrent パッケージ,multiprocessing --- プロセスベースの並列処理,並行実行
@anchor{library/multiprocessing shared_memory doc}@anchor{36cd}@anchor{library/multiprocessing shared_memory module-multiprocessing shared_memory}@anchor{9d}@anchor{library/multiprocessing shared_memory multiprocessing-shared-memory-shared-memory-for-direct-access-across-processes}@anchor{36ce}@anchor{library/multiprocessing shared_memory translation-repo}@anchor{36cf}
@subsection @code{multiprocessing.shared_memory} --- プロセス間で直接アクセス可能な共有メモリ


@geindex module; multiprocessing.shared_memory

`ソースコード' Lib/multiprocessing/shared_memory.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/multiprocessing/shared_memory.py}


Added in version 3.8.


@geindex Shared Memory
@geindex POSIX Shared Memory
@geindex Named Shared Memory


__________________________________________________________________


このモジュールは、マルチコアもしくは対称型マルチプロセッサ(SMP) を持つマシン上で実行される、ひとつ以上のプロセスから参照される共有メモリの確保、管理を行うための @ref{19d8,,SharedMemory} クラスを提供します。共有メモリのライフサイクル管理、とりわけ複数のプロセスにわたる場合のために、 @ref{9b,,multiprocessing.managers} モジュールでは @ref{3697,,BaseManager} のサブクラス @ref{36d0,,SharedMemoryManager} も提供されます。

In this module, shared memory refers to "POSIX style" shared memory blocks
(though is not necessarily implemented explicitly as such) and does not refer
to "distributed shared memory".  This style of shared memory permits distinct
processes to potentially read and write to a common (or shared) region of
volatile memory.  Processes are conventionally limited to only have access to
their own process memory space but shared memory permits the sharing
of data between processes, avoiding the need to instead send messages between
processes containing that data.  Sharing data directly via memory can provide
significant performance benefits compared to sharing data via disk or socket
or other communications requiring the serialization/deserialization and
copying of data.

@geindex SharedMemory (multiprocessing.shared_memory のクラス)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory}@anchor{19d8}
@deffn {クラス} multiprocessing.shared_memory.SharedMemory (name=None, create=False, size=0, *, track=True)

Create an instance of the @code{SharedMemory} class for either
creating a new shared memory block or attaching to an existing shared
memory block.  Each shared memory block is assigned a unique name.
In this way, one process can create a shared memory block with a
particular name and a different process can attach to that same shared
memory block using that same name.

As a resource for sharing data across processes, shared memory blocks
may outlive the original process that created them.  When one process
no longer needs access to a shared memory block that might still be
needed by other processes, the @ref{36d1,,close()} method should be called.
When a shared memory block is no longer needed by any process, the
@ref{36d2,,unlink()} method should be called to ensure proper cleanup.

@*パラメータ: 

@itemize *

@item 
@code{name} (@ref{169,,str}@code{ | }@code{None}) -- The unique name for the requested shared memory, specified as a string.
When creating a new shared memory block, if @code{None} (the default)
is supplied for the name, a novel name will be generated.

@item 
@code{create} (@ref{3c3,,bool}) -- Control whether a new shared memory block is created (@code{True})
or an existing shared memory block is attached (@code{False}).

@item 
@code{size} (@ref{19b,,int}) -- The requested number of bytes when creating a new shared memory block.
Because some platforms choose to allocate chunks of memory
based upon that platform's memory page size, the exact size of the shared
memory block may be larger or equal to the size requested.
When attaching to an existing shared memory block,
the `size' parameter is ignored.

@item 
@code{track} (@ref{3c3,,bool}) -- When @code{True}, register the shared memory block with a resource
tracker process on platforms where the OS does not do this automatically.
The resource tracker ensures proper cleanup of the shared memory even
if all other processes with access to the memory exit without doing so.
Python processes created from a common ancestor using @ref{98,,multiprocessing}
facilities share a single resource tracker process, and the lifetime of
shared memory segments is handled automatically among these processes.
Python processes created in any other way will receive their own
resource tracker when accessing shared memory with `track' enabled.
This will cause the shared memory to be deleted by the resource tracker
of the first process that terminates.
To avoid this issue, users of @ref{dc,,subprocess} or standalone Python
processes should set `track' to @code{False} when there is already another
process in place that does the bookkeeping.
`track' is ignored on Windows, which has its own tracking and
automatically deletes shared memory when all handles to it have been closed.
@end itemize



バージョン 3.13 で変更: Added the `track' parameter.


@geindex close() (multiprocessing.shared_memory.SharedMemory のメソッド)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory close}@anchor{36d1}
@deffn {メソッド} close ()

Close the file descriptor/handle to the shared memory from this
instance.  @ref{36d1,,close()} should be called once access to the shared
memory block from this instance is no longer needed.  Depending
on operating system, the underlying memory may or may not be freed
even if all handles to it have been closed.  To ensure proper cleanup,
use the @ref{36d2,,unlink()} method.
@end deffn

@geindex unlink() (multiprocessing.shared_memory.SharedMemory のメソッド)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory unlink}@anchor{36d2}
@deffn {メソッド} unlink ()

Delete the underlying shared memory block.  This should be called only
once per shared memory block regardless of the number of handles to it,
even in other processes.
@ref{36d2,,unlink()} and @ref{36d1,,close()} can be called in any order, but
trying to access data inside a shared memory block after @ref{36d2,,unlink()}
may result in memory access errors, depending on platform.

This method has no effect on Windows, where the only way to delete a
shared memory block is to close all handles.
@end deffn

@geindex buf (multiprocessing.shared_memory.SharedMemory の属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory buf}@anchor{36d3}
@deffn {の属性} buf

A memoryview of contents of the shared memory block.
@end deffn

@geindex name (multiprocessing.shared_memory.SharedMemory の属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory name}@anchor{36d4}
@deffn {の属性} name

Read-only access to the unique name of the shared memory block.
@end deffn

@geindex size (multiprocessing.shared_memory.SharedMemory の属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory size}@anchor{36d5}
@deffn {の属性} size

Read-only access to size in bytes of the shared memory block.
@end deffn
@end deffn

The following example demonstrates low-level use of @ref{19d8,,SharedMemory}
instances:

@example
>>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
>>> buffer[4] = 100                           # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5])      # Access via shm_a
b'howdy'
>>> shm_b.close()   # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink()  # Call unlink only once to release the shared memory
@end example

The following example demonstrates a practical use of the @ref{19d8,,SharedMemory}
class with NumPy arrays@footnote{https://numpy.org/}, accessing the
same @code{numpy.ndarray} from two distinct Python shells:

@example
>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:]  # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name  # We did not specify a name so one was chosen for us
'psm_21467_46075'

>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([  1,   1,   2,   3,   5, 888])

>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([  1,   1,   2,   3,   5, 888])

>>> # Clean up from within the second Python shell
>>> del c  # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()

>>> # Clean up from within the first Python shell
>>> del b  # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink()  # Free and release the shared memory block at the very end
@end example

@geindex SharedMemoryManager (multiprocessing.managers のクラス)
@anchor{library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager}@anchor{36d0}
@deffn {クラス} multiprocessing.managers.SharedMemoryManager ([address[, authkey]])

A subclass of @ref{3697,,multiprocessing.managers.BaseManager} which can be
used for the management of shared memory blocks across processes.

A call to @ref{3698,,start()} on a
@code{SharedMemoryManager} instance causes a new process to be started.
This new process's sole purpose is to manage the life cycle
of all shared memory blocks created through it.  To trigger the release
of all shared memory blocks managed by that process, call
@ref{3699,,shutdown()} on the instance.
This triggers a @ref{36d2,,unlink()} call
on all of the @ref{36d6,,SharedMemory} objects managed by that process and then
stops the process itself.  By creating @code{SharedMemory} instances
through a @code{SharedMemoryManager}, we avoid the need to manually track
and trigger the freeing of shared memory resources.

This class provides methods for creating and returning @ref{36d6,,SharedMemory}
instances and for creating a list-like object (@ref{36d7,,ShareableList})
backed by shared memory.

Refer to @ref{3697,,BaseManager} for a description
of the inherited `address' and `authkey' optional input arguments and how
they may be used to connect to an existing @code{SharedMemoryManager} service
from other processes.

@geindex SharedMemory() (multiprocessing.managers.SharedMemoryManager のメソッド)
@anchor{library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager SharedMemory}@anchor{36d6}
@deffn {メソッド} SharedMemory (size)

Create and return a new @ref{36d6,,SharedMemory} object with the
specified `size' in bytes.
@end deffn

@geindex ShareableList() (multiprocessing.managers.SharedMemoryManager のメソッド)
@anchor{library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager ShareableList}@anchor{36d7}
@deffn {メソッド} ShareableList (sequence)

Create and return a new @ref{36d7,,ShareableList} object, initialized
by the values from the input `sequence'.
@end deffn
@end deffn

The following example demonstrates the basic mechanisms of a
@ref{36d0,,SharedMemoryManager}:

@example
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
@end example

The following example depicts a potentially more convenient pattern for using
@ref{36d0,,SharedMemoryManager} objects via the
@ref{186,,with} statement to ensure that all shared memory blocks are released
after they are no longer needed:

@example
>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
@end example

When using a @ref{36d0,,SharedMemoryManager}
in a @ref{186,,with} statement, the shared memory blocks created using that
manager are all released when the @code{with} statement's code block
finishes execution.

@geindex ShareableList (multiprocessing.shared_memory のクラス)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList}@anchor{1d58}
@deffn {クラス} multiprocessing.shared_memory.ShareableList (sequence=None, *, name=None)

Provide a mutable list-like object where all values stored within are
stored in a shared memory block.
This constrains storable values to the following built-in data types:


@itemize *

@item 
@ref{19b,,int} (signed 64-bit)

@item 
@ref{196,,float}

@item 
@ref{3c3,,bool}

@item 
@ref{169,,str} (less than 10M bytes each when encoded as UTF-8)

@item 
@ref{192,,bytes} (less than 10M bytes each)

@item 
@code{None}
@end itemize

It also notably differs from the built-in @ref{24d,,list} type
in that these lists can not change their overall length
(i.e. no @code{append()}, @code{insert()}, etc.) and do not
support the dynamic creation of new @code{ShareableList} instances
via slicing.

`sequence' is used in populating a new @code{ShareableList} full of values.
Set to @code{None} to instead attach to an already existing
@code{ShareableList} by its unique shared memory name.

`name' is the unique name for the requested shared memory, as described
in the definition for @ref{19d8,,SharedMemory}.  When attaching to an
existing @code{ShareableList}, specify its shared memory block's unique
name while leaving `sequence' set to @code{None}.

@cartouche
@quotation 注釈 
A known issue exists for @ref{192,,bytes} and @ref{169,,str} values.
If they end with @code{\x00} nul bytes or characters, those may be
`silently stripped' when fetching them by index from the
@code{ShareableList}. This @code{.rstrip(b'\x00')} behavior is
considered a bug and may go away in the future. See gh-106939@footnote{https://github.com/python/cpython/issues/106939}.
@end quotation
@end cartouche

For applications where rstripping of trailing nulls is a problem,
work around it by always unconditionally appending an extra non-0
byte to the end of such values when storing and unconditionally
removing it when fetching:

@example
>>> from multiprocessing import shared_memory
>>> nul_bug_demo = shared_memory.ShareableList(['?\x00', b'\x03\x02\x01\x00\x00\x00'])
>>> nul_bug_demo[0]
'?'
>>> nul_bug_demo[1]
b'\x03\x02\x01'
>>> nul_bug_demo.shm.unlink()
>>> padded = shared_memory.ShareableList(['?\x00\x07', b'\x03\x02\x01\x00\x00\x00\x07'])
>>> padded[0][:-1]
'?\x00'
>>> padded[1][:-1]
b'\x03\x02\x01\x00\x00\x00'
>>> padded.shm.unlink()
@end example

@geindex count() (multiprocessing.shared_memory.ShareableList のメソッド)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList count}@anchor{36d8}
@deffn {メソッド} count (value)

Return the number of occurrences of `value'.
@end deffn

@geindex index() (multiprocessing.shared_memory.ShareableList のメソッド)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList index}@anchor{36d9}
@deffn {メソッド} index (value)

Return first index position of `value'.
Raise @ref{2ec,,ValueError} if `value' is not present.
@end deffn

@geindex format (multiprocessing.shared_memory.ShareableList の属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList format}@anchor{36da}
@deffn {の属性} format

Read-only attribute containing the @ref{db,,struct} packing format used by
all currently stored values.
@end deffn

@geindex shm (multiprocessing.shared_memory.ShareableList の属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList shm}@anchor{36db}
@deffn {の属性} shm

The @ref{19d8,,SharedMemory} instance where the values are stored.
@end deffn
@end deffn

以下に @ref{1d58,,ShareableList} インスタンスの利用例を示します。

@example
>>> from multiprocessing import shared_memory
>>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
>>> [ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
>>> a[2]
-273.154
>>> a[2] = -78.5
>>> a[2]
-78.5
>>> a[2] = 'dry ice'  # Changing data types is supported as well
>>> a[2]
'dry ice'
>>> a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
  ...
ValueError: exceeds available storage for existing str
>>> a[2]
'dry ice'
>>> len(a)
7
>>> a.index(42)
6
>>> a.count(b'howdy')
0
>>> a.count(b'HoWdY')
1
>>> a.shm.close()
>>> a.shm.unlink()
>>> del a  # Use of a ShareableList after call to unlink() is unsupported
@end example

The following example depicts how one, two, or many processes may access the
same @ref{1d58,,ShareableList} by supplying the name of the shared memory block
behind it:

@example
>>> b = shared_memory.ShareableList(range(5))         # In a first process
>>> c = shared_memory.ShareableList(name=b.shm.name)  # In a second process
>>> c
ShareableList([0, 1, 2, 3, 4], name='...')
>>> c[-1] = -999
>>> b[-1]
-999
>>> b.shm.close()
>>> c.shm.close()
>>> c.shm.unlink()
@end example

The following examples demonstrates that @ref{1d58,,ShareableList}
(and underlying @ref{19d8,,SharedMemory}) objects
can be pickled and unpickled if needed.
Note, that it will still be the same shared object.
This happens, because the deserialized object has
the same unique name and is just attached to an existing
object with the same name (if the object is still alive):

@example
>>> import pickle
>>> from multiprocessing import shared_memory
>>> sl = shared_memory.ShareableList(range(10))
>>> list(sl)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@end example

@example
>>> deserialized_sl = pickle.loads(pickle.dumps(sl))
>>> list(deserialized_sl)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@end example

@example
>>> sl[0] = -1
>>> deserialized_sl[1] = -2
>>> list(sl)
[-1, -2, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(deserialized_sl)
[-1, -2, 2, 3, 4, 5, 6, 7, 8, 9]
@end example

@example
>>> sl.shm.close()
>>> sl.shm.unlink()
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node concurrent パッケージ,concurrent futures --- 並列タスク実行,multiprocessing shared_memory --- プロセス間で直接アクセス可能な共有メモリ,並行実行
@anchor{library/concurrent doc}@anchor{36dc}@anchor{library/concurrent the-concurrent-package}@anchor{36dd}@anchor{library/concurrent translation-repo}@anchor{36de}
@subsection @code{concurrent} パッケージ


This package contains the following modules:


@itemize *

@item 
@ref{24,,concurrent.futures} -- 並列タスク実行

@item 
@ref{25,,concurrent.interpreters} -- Multiple interpreters in the same process
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node concurrent futures --- 並列タスク実行,concurrent interpreters --- Multiple interpreters in the same process,concurrent パッケージ,並行実行
@anchor{library/concurrent futures doc}@anchor{36df}@anchor{library/concurrent futures concurrent-futures-launching-parallel-tasks}@anchor{36e0}@anchor{library/concurrent futures module-concurrent futures}@anchor{24}@anchor{library/concurrent futures translation-repo}@anchor{36e1}
@subsection @code{concurrent.futures} --- 並列タスク実行


@geindex module; concurrent.futures


Added in version 3.2.


`ソースコード:' Lib/concurrent/futures/thread.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/concurrent/futures/thread.py}、Lib/concurrent/futures/process.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/concurrent/futures/process.py} および Lib/concurrent/futures/interpreter.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/concurrent/futures/interpreter.py}


__________________________________________________________________


The @code{concurrent.futures} module provides a high-level interface for
asynchronously executing callables.

The asynchronous execution can be performed with threads, using
@ref{949,,ThreadPoolExecutor} or @ref{1d2,,InterpreterPoolExecutor},
or separate processes, using @ref{1d6,,ProcessPoolExecutor}.
Each implements the same interface, which is defined
by the abstract @ref{36e2,,Executor} class.

@ref{13ca,,concurrent.futures.Future} must not be confused with
@ref{dc6,,asyncio.Future}, which is designed for use with @ref{b,,asyncio}
tasks and coroutines. See the @ref{36e3,,asyncio's Future}
documentation for a detailed comparison of the two.

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@menu
* Executor オブジェクト:: 
* ThreadPoolExecutor:: 
* InterpreterPoolExecutor:: 
* ProcessPoolExecutor:: 
* Future オブジェクト:: 
* モジュール関数: モジュール関数<2>. 
* 例外クラス:: 

@end menu

@node Executor オブジェクト,ThreadPoolExecutor,,concurrent futures --- 並列タスク実行
@anchor{library/concurrent futures executor-objects}@anchor{36e4}
@subsubsection Executor オブジェクト


@geindex Executor (concurrent.futures のクラス)
@anchor{library/concurrent futures concurrent futures Executor}@anchor{36e2}
@deffn {クラス} concurrent.futures.Executor

非同期呼び出しを実行するためのメソッドを提供する抽象クラスです。このクラスを直接使ってはならず、具象サブクラスを介して使います。

@geindex submit() (concurrent.futures.Executor のメソッド)
@anchor{library/concurrent futures concurrent futures Executor submit}@anchor{c75}
@deffn {メソッド} submit (fn, /, *args, **kwargs)

呼び出し可能オブジェクト `fn' を、 @code{fn(*args, **kwargs)} として実行するようにスケジュールし、呼び出し可能オブジェクトの実行を表現する @ref{13ca,,Future} オブジェクトを返します。

@example
with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())
@end example
@end deffn

@geindex map() (concurrent.futures.Executor のメソッド)
@anchor{library/concurrent futures concurrent futures Executor map}@anchor{1dc}
@deffn {メソッド} map (fn, *iterables, timeout=None, chunksize=1, buffersize=None)

Similar to @ref{19f,,map(fn@comma{} *iterables)} except:


@itemize *

@item 
The `iterables' are collected immediately rather than lazily, unless a
`buffersize' is specified to limit the number of submitted tasks whose
results have not yet been yielded. If the buffer is full, iteration over
the `iterables' pauses until a result is yielded from the buffer.

@item 
`fn' is executed asynchronously and several calls to
`fn' may be made concurrently.
@end itemize

もし @ref{14e5,,__next__()} が呼ばれその結果が元々の @ref{1dc,,Executor.map()} の呼び出しから `timeout' 秒経った後も利用できない場合、返されるイテレータは @ref{a36,,TimeoutError} を送出します。`timeout' は整数または浮動小数点数です。もし `timeout' が指定されないか の場合、待ち時間に制限はありません。

もし `fn' の呼び出しが例外を送出した場合、その例外はイテレータから値を受け取る時に送出されます。

When using @ref{1d6,,ProcessPoolExecutor}, this method chops `iterables'
into a number of chunks which it submits to the pool as separate
tasks.  The (approximate) size of these chunks can be specified by
setting `chunksize' to a positive integer.  For very long iterables,
using a large value for `chunksize' can significantly improve
performance compared to the default size of 1.  With
@ref{949,,ThreadPoolExecutor} and @ref{1d2,,InterpreterPoolExecutor},
`chunksize' has no effect.


バージョン 3.5 で変更: `chunksize' 引数が追加されました。



バージョン 3.14 で変更: `buffersize' 引数が追加されました。

@end deffn

@geindex shutdown() (concurrent.futures.Executor のメソッド)
@anchor{library/concurrent futures concurrent futures Executor shutdown}@anchor{aea}
@deffn {メソッド} shutdown (wait=True, *, cancel_futures=False)

executor に対して、現在保留中のフューチャーが実行された後で、使用中のすべての資源を解放するように伝えます。シャットダウンにより後に @ref{c75,,Executor.submit()} と @ref{1dc,,Executor.map()} を呼び出すと @ref{244,,RuntimeError} が送出されます。

`wait' が @code{True} の場合、すべての未完了のフューチャの実行が完了して Executor に関連付けられたリソースが解放されるまで、このメソッドは返りません。 `wait' が @code{False} の場合、このメソッドはすぐに返り、すべての未完了のフューチャの実行が完了したときに、 Executor に関連付けられたリソースが解放されます。 `wait' の値に関係なく、すべての未完了のフューチャの実行が完了するまで Python プログラム全体は終了しません。

If `cancel_futures' is @code{True}, this method will cancel all pending
futures that the executor has not started running. Any futures that
are completed or running won't be cancelled, regardless of the value
of `cancel_futures'.

If both `cancel_futures' and `wait' are @code{True}, all futures that the
executor has started running will be completed prior to this method
returning. The remaining futures are cancelled.

You can avoid having to call this method explicitly if you use the executor
as a @ref{1e1,,context manager} via the  @ref{186,,with} statement, which
will shutdown the @ref{36e2,,Executor} (waiting as if @ref{aea,,Executor.shutdown()}
were called with `wait' set to @code{True}):

@example
import shutil
with ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src4.txt', 'dest4.txt')
@end example


バージョン 3.9 で変更: `cancel_futures' が追加されました。

@end deffn
@end deffn

@node ThreadPoolExecutor,InterpreterPoolExecutor,Executor オブジェクト,concurrent futures --- 並列タスク実行
@anchor{library/concurrent futures threadpoolexecutor}@anchor{36e5}
@subsubsection ThreadPoolExecutor


@ref{949,,ThreadPoolExecutor} はスレッドのプールを使用して非同期に呼び出しを行う、 @ref{36e2,,Executor} のサブクラスです。

@ref{13ca,,Future} に関連づけられた呼び出し可能オブジェクトが、別の @ref{13ca,,Future} の結果を待つ時にデッドロックすることがあります。例:

@example
import time
def wait_on_b():
    time.sleep(5)
    print(b.result())  # b will never complete because it is waiting on a.
    return 5

def wait_on_a():
    time.sleep(5)
    print(a.result())  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)
@end example

以下でも同様です:

@example
def wait_on_future():
    f = executor.submit(pow, 5, 2)
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print(f.result())

executor = ThreadPoolExecutor(max_workers=1)
executor.submit(wait_on_future)
@end example

@geindex ThreadPoolExecutor (concurrent.futures のクラス)
@anchor{library/concurrent futures concurrent futures ThreadPoolExecutor}@anchor{949}
@deffn {クラス} concurrent.futures.ThreadPoolExecutor (max_workers=None, thread_name_prefix='@w{'}, initializer=None, initargs=())

最大で `max_workers' 個のスレッドを非同期実行に使う @ref{36e2,,Executor} のサブクラスです。

All threads enqueued to @code{ThreadPoolExecutor} will be joined before the
interpreter can exit. Note that the exit handler which does this is
executed `before' any exit handlers added using @code{atexit}. This means
exceptions in the main thread must be caught and handled in order to
signal threads to exit gracefully. For this reason, it is recommended
that @code{ThreadPoolExecutor} not be used for long-running tasks.

`initializer' is an optional callable that is called at the start of
each worker thread; `initargs' is a tuple of arguments passed to the
initializer.  Should `initializer' raise an exception, all currently
pending jobs will raise a @ref{36e6,,BrokenThreadPool},
as well as any attempt to submit more jobs to the pool.


バージョン 3.5 で変更: `max_workers' が @code{None} か指定されない場合のデフォルト値はマシンのプロセッサの数に 5 を掛けたものになります。これは、 @ref{949,,ThreadPoolExecutor} は CPU の処理ではなく I/O をオーバーラップするのによく使用されるため、 @ref{1d6,,ProcessPoolExecutor} のワーカーの数よりもこのワーカーの数を増やすべきであるという想定に基づいています。



バージョン 3.6 で変更: `thread_name_prefix' 引数が追加され、デバッグしやすくなるようにプールから作られたワーカスレッド @ref{176,,threading.Thread} の名前を管理できるようになりました。



バージョン 3.7 で変更: `initializer' と `initargs' 引数が追加されました。



バージョン 3.8 で変更: Default value of `max_workers' is changed to @code{min(32, os.cpu_count() + 4)}.
This default value preserves at least 5 workers for I/O bound tasks.
It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL.
And it avoids using very large resources implicitly on many-core machines.

ThreadPoolExecutor now reuses idle worker threads before starting
`max_workers' worker threads too.



バージョン 3.13 で変更: Default value of `max_workers' is changed to
@code{min(32, (os.process_cpu_count() or 1) + 4)}.

@end deffn

@menu
* ThreadPoolExecutor の例:: 

@end menu

@node ThreadPoolExecutor の例,,,ThreadPoolExecutor
@anchor{library/concurrent futures id1}@anchor{36e7}@anchor{library/concurrent futures threadpoolexecutor-example}@anchor{13cb}
@subsubsection ThreadPoolExecutor の例


@example
import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://nonexistent-subdomain.python.org/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = @{executor.submit(load_url, url, 60): url for url in URLS@}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))
@end example

@node InterpreterPoolExecutor,ProcessPoolExecutor,ThreadPoolExecutor,concurrent futures --- 並列タスク実行
@anchor{library/concurrent futures interpreterpoolexecutor}@anchor{36e8}
@subsubsection InterpreterPoolExecutor



Added in version 3.14.


The @ref{1d2,,InterpreterPoolExecutor} class uses a pool of interpreters
to execute calls asynchronously.  It is a @ref{949,,ThreadPoolExecutor}
subclass, which means each worker is running in its own thread.
The difference here is that each worker has its own interpreter,
and runs each task using that interpreter.

The biggest benefit to using interpreters instead of only threads
is true multi-core parallelism.  Each interpreter has its own
@ref{474,,Global Interpreter Lock}, so code
running in one interpreter can run on one CPU core, while code in
another interpreter runs unblocked on a different core.

The tradeoff is that writing concurrent code for use with multiple
interpreters can take extra effort.  However, this is because it
forces you to be deliberate about how and when interpreters interact,
and to be explicit about what data is shared between interpreters.
This results in several benefits that help balance the extra effort,
including true multi-core parallelism,  For example, code written
this way can make it easier to reason about concurrency.  Another
major benefit is that you don't have to deal with several of the
big pain points of using threads, like race conditions.

Each worker's interpreter is isolated from all the other interpreters.
"Isolated" means each interpreter has its own runtime state and
operates completely independently.  For example, if you redirect
@ref{ccd,,sys.stdout} in one interpreter, it will not be automatically
redirected to any other interpreter.  If you import a module in one
interpreter, it is not automatically imported in any other.  You
would need to import the module separately in interpreter where
you need it.  In fact, each module imported in an interpreter is
a completely separate object from the same module in a different
interpreter, including @ref{df,,sys}, @ref{13,,builtins},
and even @code{__main__}.

Isolation means a mutable object, or other data, cannot be used
by more than one interpreter at the same time.  That effectively means
interpreters cannot actually share such objects or data.  Instead,
each interpreter must have its own copy, and you will have to
synchronize any changes between the copies manually.  Immutable
objects and data, like the builtin singletons, strings, and tuples
of immutable objects, don't have these limitations.

Communicating and synchronizing between interpreters is most effectively
done using dedicated tools, like those proposed in 
@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}.  One less
efficient alternative is to serialize with @ref{ab,,pickle} and then send
the bytes over a shared @ref{d1,,socket} or
@ref{1b64,,pipe}.

@geindex InterpreterPoolExecutor (concurrent.futures のクラス)
@anchor{library/concurrent futures concurrent futures InterpreterPoolExecutor}@anchor{1d2}
@deffn {クラス} concurrent.futures.InterpreterPoolExecutor (max_workers=None, thread_name_prefix='@w{'}, initializer=None, initargs=())

A @ref{949,,ThreadPoolExecutor} subclass that executes calls asynchronously
using a pool of at most `max_workers' threads.  Each thread runs
tasks in its own interpreter.  The worker interpreters are isolated
from each other, which means each has its own runtime state and that
they can't share any mutable objects or other data.  Each interpreter
has its own @ref{474,,Global Interpreter Lock},
which means code run with this executor has true multi-core parallelism.

The optional `initializer' and `initargs' arguments have the same
meaning as for @code{ThreadPoolExecutor}: the initializer is run
when each worker is created, though in this case it is run in
the worker's interpreter.  The executor serializes the `initializer'
and `initargs' using @ref{ab,,pickle} when sending them to the worker's
interpreter.

@cartouche
@quotation 注釈 
The executor may replace uncaught exceptions from `initializer'
with @ref{36e9,,ExecutionFailed}.
@end quotation
@end cartouche

Other caveats from parent @ref{949,,ThreadPoolExecutor} apply here.
@end deffn

@ref{c75,,submit()} and @ref{1dc,,map()} work like normal,
except the worker serializes the callable and arguments using
@ref{ab,,pickle} when sending them to its interpreter.  The worker
likewise serializes the return value when sending it back.

When a worker's current task raises an uncaught exception, the worker
always tries to preserve the exception as-is.  If that is successful
then it also sets the @code{__cause__} to a corresponding
@ref{36e9,,ExecutionFailed}
instance, which contains a summary of the original exception.
In the uncommon case that the worker is not able to preserve the
original as-is then it directly preserves the corresponding
@ref{36e9,,ExecutionFailed}
instance instead.

@node ProcessPoolExecutor,Future オブジェクト,InterpreterPoolExecutor,concurrent futures --- 並列タスク実行
@anchor{library/concurrent futures processpoolexecutor}@anchor{36ea}
@subsubsection ProcessPoolExecutor


@ref{1d6,,ProcessPoolExecutor}  はプロセスプールを使って非同期呼び出しを実施する @ref{36e2,,Executor} のサブクラスです。@ref{1d6,,ProcessPoolExecutor} は @ref{98,,multiprocessing} モジュールを利用します。このため @ref{474,,Global Interpreter Lock} を回避することができますが、pickle 化できるオブジェクトしか実行したり返したりすることができません。

@code{__main__} モジュールはワーカサブプロセスでインポート可能でなければなりません。
すなわち、 @ref{1d6,,ProcessPoolExecutor} は対話的インタープリタでは動きません。

@ref{1d6,,ProcessPoolExecutor} に渡された呼び出し可能オブジェクトから @ref{36e2,,Executor} や @ref{13ca,,Future} メソッドを呼ぶとデッドロックに陥ります。

Note that the restrictions on functions and arguments needing to picklable as
per @ref{252,,multiprocessing.Process} apply when using @ref{c75,,submit()}
and @ref{1dc,,map()} on a @ref{1d6,,ProcessPoolExecutor}. A function defined
in a REPL or a lambda should not be expected to work.

@geindex ProcessPoolExecutor (concurrent.futures のクラス)
@anchor{library/concurrent futures concurrent futures ProcessPoolExecutor}@anchor{1d6}
@deffn {クラス} concurrent.futures.ProcessPoolExecutor (max_workers=None, mp_context=None, initializer=None, initargs=(), max_tasks_per_child=None)

An @ref{36e2,,Executor} subclass that executes calls asynchronously using a pool
of at most `max_workers' processes.  If `max_workers' is @code{None} or not
given, it will default to @ref{4da,,os.process_cpu_count()}.
If `max_workers' is less than or equal to @code{0}, then a @ref{2ec,,ValueError}
will be raised.
On Windows, `max_workers' must be less than or equal to @code{61}. If it is not
then @ref{2ec,,ValueError} will be raised. If `max_workers' is @code{None}, then
the default chosen will be at most @code{61}, even if more processors are
available.
`mp_context' can be a @ref{98,,multiprocessing} context or @code{None}. It will be
used to launch the workers. If `mp_context' is @code{None} or not given, the
default @ref{98,,multiprocessing} context is used.
See @ref{1d5,,コンテキストと開始方式}.

`initializer' is an optional callable that is called at the start of
each worker process; `initargs' is a tuple of arguments passed to the
initializer.  Should `initializer' raise an exception, all currently
pending jobs will raise a @ref{36eb,,BrokenProcessPool},
as well as any attempt to submit more jobs to the pool.

`max_tasks_per_child' is an optional argument that specifies the maximum
number of tasks a single process can execute before it will exit and be
replaced with a fresh worker process. By default `max_tasks_per_child' is
@code{None} which means worker processes will live as long as the pool. When
a max is specified, the "spawn" multiprocessing start method will be used by
default in absence of a `mp_context' parameter. This feature is incompatible
with the "fork" start method.

@cartouche
@quotation 注釈 
Bugs have been reported when using the `max_tasks_per_child' feature that
can result in the @ref{1d6,,ProcessPoolExecutor} hanging in some
circumstances. Follow its eventual resolution in gh-115634@footnote{https://github.com/python/cpython/issues/115634}.
@end quotation
@end cartouche


バージョン 3.3 で変更: ワーカプロセスの1つが突然終了した場合、@ref{36eb,,BrokenProcessPool} エラーが送出されるようになりました。
以前は挙動は未定義でしたが、 executor や  futures がフリーズしたりデッドロックを起こすことがしばしばでした。



バージョン 3.7 で変更: The `mp_context' argument was added to allow users to control the
start_method for worker processes created by the pool.

`initializer' と `initargs' 引数が追加されました。



バージョン 3.11 で変更: The `max_tasks_per_child' argument was added to allow users to
control the lifetime of workers in the pool.



バージョン 3.12 で変更: On POSIX systems, if your application has multiple threads and the
@ref{98,,multiprocessing} context uses the @code{"fork"} start method:
The @ref{4b5,,os.fork()} function called internally to spawn workers may raise a
@ref{1a3,,DeprecationWarning}. Pass a `mp_context' configured to use a
different start method. See the @ref{4b5,,os.fork()} documentation for
further explanation.



バージョン 3.13 で変更: `max_workers' uses @ref{4da,,os.process_cpu_count()} by default, instead of
@ref{4db,,os.cpu_count()}.



バージョン 3.14 で変更: The default process start method (see
@ref{1d5,,コンテキストと開始方式}) changed away from `fork'. If you
require the `fork' start method for @ref{1d6,,ProcessPoolExecutor} you must
explicitly pass @code{mp_context=multiprocessing.get_context("fork")}.


@geindex terminate_workers() (concurrent.futures.ProcessPoolExecutor のメソッド)
@anchor{library/concurrent futures concurrent futures ProcessPoolExecutor terminate_workers}@anchor{1da}
@deffn {メソッド} terminate_workers ()

Attempt to terminate all living worker processes immediately by calling
@ref{1857,,Process.terminate} on each of them.
Internally, it will also call @ref{aea,,Executor.shutdown()} to ensure that all
other resources associated with the executor are freed.

After calling this method the caller should no longer submit tasks to the
executor.


Added in version 3.14.

@end deffn

@geindex kill_workers() (concurrent.futures.ProcessPoolExecutor のメソッド)
@anchor{library/concurrent futures concurrent futures ProcessPoolExecutor kill_workers}@anchor{1db}
@deffn {メソッド} kill_workers ()

Attempt to kill all living worker processes immediately by calling
@ref{d4f,,Process.kill} on each of them.
Internally, it will also call @ref{aea,,Executor.shutdown()} to ensure that all
other resources associated with the executor are freed.

After calling this method the caller should no longer submit tasks to the
executor.


Added in version 3.14.

@end deffn
@end deffn

@menu
* ProcessPoolExecutor の例:: 

@end menu

@node ProcessPoolExecutor の例,,,ProcessPoolExecutor
@anchor{library/concurrent futures id2}@anchor{36ec}@anchor{library/concurrent futures processpoolexecutor-example}@anchor{13cc}
@subsubsection ProcessPoolExecutor の例


@example
import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()
@end example

@node Future オブジェクト,モジュール関数<2>,ProcessPoolExecutor,concurrent futures --- 並列タスク実行
@anchor{library/concurrent futures future-objects}@anchor{36ed}
@subsubsection Future オブジェクト


@ref{13ca,,Future} クラスは呼び出し可能オブジェクトの非同期実行をカプセル化します。 @ref{13ca,,Future} のインスタンスは @ref{c75,,Executor.submit()} によって生成されます。

@geindex Future (concurrent.futures のクラス)
@anchor{library/concurrent futures concurrent futures Future}@anchor{13ca}
@deffn {クラス} concurrent.futures.Future

呼び出し可能オブジェクトの非同期実行をカプセル化します。 @ref{13ca,,Future} インスタンスは @ref{c75,,Executor.submit()} で生成され、テストを除いて直接生成すべきではありません。

@geindex cancel() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future cancel}@anchor{36ee}
@deffn {メソッド} cancel ()

Attempt to cancel the call.  If the call is currently being executed or
finished running and cannot be cancelled then the method will return
@code{False}, otherwise the call will be cancelled and the method will
return @code{True}.
@end deffn

@geindex cancelled() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future cancelled}@anchor{36ef}
@deffn {メソッド} cancelled ()

呼び出しが正常にキャンセルされた場合 @code{True} を返します。
@end deffn

@geindex running() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future running}@anchor{36f0}
@deffn {メソッド} running ()

現在呼び出しが実行中でキャンセルできない場合 @code{True} を返します。
@end deffn

@geindex done() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future done}@anchor{36f1}
@deffn {メソッド} done ()

呼び出しが正常にキャンセルされたか終了した場合 @code{True} を返します。
@end deffn

@geindex result() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future result}@anchor{36f2}
@deffn {メソッド} result (timeout=None)

呼び出しによって返された値を返します。もし呼び出しがまだ完了していなければ、このメソッドは `timeout' 秒の間、待機します。もし呼び出しが `timeout' 秒間の間に完了しなければ、 @ref{a36,,TimeoutError} が送出されます。 `timeout' はintかfloatを指定できます。もし `timeout' が指定されていないか、 @code{None} であれば、待機時間に制限はありません。

future が完了する前にキャンセルされた場合 @ref{bce,,CancelledError} が送出されます。

If the call raised an exception, this method will raise the same exception.
@end deffn

@geindex exception() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future exception}@anchor{36f3}
@deffn {メソッド} exception (timeout=None)

呼び出しによって送出された例外を返します。もし呼び出しがまだ完了されていなければ、このメソッドは `timeout' 秒だけ待機します。もし呼び出しが `timeout' 秒の間に完了しなければ、 @ref{a36,,TimeoutError} が送出されます。 `timeout' にはintかfloatを指定できます。 `timeout' が指定されていないか、 @code{None} であれば、待機時間に制限はありません。

future が完了する前にキャンセルされた場合 @ref{bce,,CancelledError} が送出されます。

呼び出しが例外を送出することなく完了した場合、@code{None} を返します。
@end deffn

@geindex add_done_callback() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future add_done_callback}@anchor{36f4}
@deffn {メソッド} add_done_callback (fn)

呼び出し可能な `fn' オブジェクトを future にアタッチします。futureがキャンセルされたか、実行を終了した際に、future をそのただ一つの引数として `fn' が呼び出されます。

追加された呼び出し可能オブジェクトは、追加された順番で呼びだされ、追加を行ったプロセスに属するスレッド中で呼び出されます。もし呼び出し可能オブジェクトが @ref{bcd,,Exception} のサブクラスを送出した場合、それはログに記録され無視されます。呼び出し可能オブジェクトが @ref{7d6,,BaseException} のサブクラスを送出した場合の動作は未定義です。

もしfutureがすでに完了しているか、キャンセル済みであれば、`fn' は即座に実行されます。
@end deffn

以下の @ref{13ca,,Future} メソッドは、ユニットテストでの使用と @ref{36e2,,Executor} を実装することを意図しています。

@geindex set_running_or_notify_cancel() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future set_running_or_notify_cancel}@anchor{36f5}
@deffn {メソッド} set_running_or_notify_cancel ()

このメソッドは、@ref{13ca,,Future} に関連付けられたワークやユニットテストによるワークの実行前に、 @ref{36e2,,Executor} の実装によってのみ呼び出してください。

このメソッドが @code{False} を返す場合、 @ref{13ca,,Future} はキャンセルされています。つまり、 @ref{36ee,,Future.cancel()} が呼び出されて @code{True} が返っています。@ref{13ca,,Future} の完了を  (@ref{19c7,,as_completed()} または @ref{1c05,,wait()} により)  待機するすべてのスレッドが起動します。

このメソッドが @code{True} を返す場合、 @ref{13ca,,Future} はキャンセルされて、実行状態に移行されています。つまり、 @ref{36f0,,Future.running()} を呼び出すと @code{True} が返ります。

このメソッドは、一度だけ呼び出すことができ、@ref{36f6,,Future.set_result()} または @ref{36f7,,Future.set_exception()} がキャンセルされた後には呼び出すことができません。
@end deffn

@geindex set_result() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future set_result}@anchor{36f6}
@deffn {メソッド} set_result (result)

@ref{13ca,,Future} に関連付けられたワークの結果を `result' に設定します。

このメソッドは、 @ref{36e2,,Executor} の実装またはユニットテストによってのみ使用してください。


バージョン 3.8 で変更: This method raises
@ref{1951,,concurrent.futures.InvalidStateError} if the @ref{13ca,,Future} is
already done.

@end deffn

@geindex set_exception() (concurrent.futures.Future のメソッド)
@anchor{library/concurrent futures concurrent futures Future set_exception}@anchor{36f7}
@deffn {メソッド} set_exception (exception)

@ref{13ca,,Future} に関連付けられたワークの結果を @ref{bcd,,Exception} `exception' に設定します。

このメソッドは、 @ref{36e2,,Executor} の実装またはユニットテストによってのみ使用してください。


バージョン 3.8 で変更: This method raises
@ref{1951,,concurrent.futures.InvalidStateError} if the @ref{13ca,,Future} is
already done.

@end deffn
@end deffn

@node モジュール関数<2>,例外クラス,Future オブジェクト,concurrent futures --- 並列タスク実行
@anchor{library/concurrent futures module-functions}@anchor{36f8}
@subsubsection モジュール関数


@geindex wait() (concurrent.futures モジュール)
@anchor{library/concurrent futures concurrent futures wait}@anchor{1c05}
@deffn {の関数} concurrent.futures.wait (fs, timeout=None, return_when=ALL_COMPLETED)

Wait for the @ref{13ca,,Future} instances (possibly created by different
@ref{36e2,,Executor} 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 @code{done}, contains the futures that
completed (finished or cancelled futures) before the wait completed.  The
second set, named @code{not_done}, contains the futures that did not complete
(pending or running futures).

`timeout' で結果を返すまで待機する最大秒数を指定できます。`timeout' は整数か浮動小数点数をとります。`timeout' が指定されないか @code{None} の場合、無期限に待機します。

`return_when' でこの関数がいつ結果を返すか指定します。指定できる値は以下の 定数のどれか一つです:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

説明

@item

@geindex FIRST_COMPLETED (concurrent.futures モジュール)
@anchor{library/concurrent futures concurrent futures FIRST_COMPLETED}@anchor{36f9}
@deffn {データ} concurrent.futures.FIRST_COMPLETED
@end deffn

@tab

いずれかのフューチャが終了したかキャンセルされたときに返します。

@item

@geindex FIRST_EXCEPTION (concurrent.futures モジュール)
@anchor{library/concurrent futures concurrent futures FIRST_EXCEPTION}@anchor{36fa}
@deffn {データ} concurrent.futures.FIRST_EXCEPTION
@end deffn

@tab

The function will return when any future finishes by raising an
exception. If no future raises an exception
then it is equivalent to @ref{36fb,,ALL_COMPLETED}.

@item

@geindex ALL_COMPLETED (concurrent.futures モジュール)
@anchor{library/concurrent futures concurrent futures ALL_COMPLETED}@anchor{36fb}
@deffn {データ} concurrent.futures.ALL_COMPLETED
@end deffn

@tab

すべてのフューチャが終了したかキャンセルされたときに返します。

@end multitable

@end deffn

@geindex as_completed() (concurrent.futures モジュール)
@anchor{library/concurrent futures concurrent futures as_completed}@anchor{19c7}
@deffn {の関数} concurrent.futures.as_completed (fs, timeout=None)

Returns an iterator over the @ref{13ca,,Future} instances (possibly created by
different @ref{36e2,,Executor} instances) given by `fs' that yields futures as
they complete (finished or cancelled futures). Any futures given by `fs' that
are duplicated will be returned once. Any futures that completed before
@ref{19c7,,as_completed()} is called will be yielded first.  The returned iterator
raises a @ref{a36,,TimeoutError} if @ref{14e5,,__next__()}
is called and the result isn't available after `timeout' seconds from the
original call to @ref{19c7,,as_completed()}.  `timeout' can be an int or float. If
`timeout' is not specified or @code{None}, there is no limit to the wait time.
@end deffn


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 3148

@item PEP 3148@footnote{https://peps.python.org/pep-3148/} -- futures - execute computations asynchronously

この機能を Python 標準ライブラリに含めることを述べた提案です。
@end table


@node 例外クラス,,モジュール関数<2>,concurrent futures --- 並列タスク実行
@anchor{library/concurrent futures exception-classes}@anchor{36fc}
@subsubsection 例外クラス


@geindex CancelledError
@anchor{library/concurrent futures concurrent futures CancelledError}@anchor{bce}
@deffn {例外} concurrent.futures.CancelledError

future がキャンセルされたときに送出されます。
@end deffn

@geindex TimeoutError
@anchor{library/concurrent futures concurrent futures TimeoutError}@anchor{36fd}
@deffn {例外} concurrent.futures.TimeoutError

A deprecated alias of @ref{a36,,TimeoutError},
raised when a future operation exceeds the given timeout.


バージョン 3.11 で変更: このクラスは @ref{a36,,TimeoutError} のエイリアスになりました。

@end deffn

@geindex BrokenExecutor
@anchor{library/concurrent futures concurrent futures BrokenExecutor}@anchor{36fe}
@deffn {例外} concurrent.futures.BrokenExecutor

Derived from @ref{244,,RuntimeError}, this exception class is raised
when an executor is broken for some reason, and cannot be used
to submit or execute new tasks.


Added in version 3.7.

@end deffn

@geindex InvalidStateError
@anchor{library/concurrent futures concurrent futures InvalidStateError}@anchor{1951}
@deffn {例外} concurrent.futures.InvalidStateError

Raised when an operation is performed on a future that is not allowed
in the current state.


Added in version 3.8.

@end deffn

@geindex BrokenThreadPool
@anchor{library/concurrent futures concurrent futures thread BrokenThreadPool}@anchor{36e6}
@deffn {例外} concurrent.futures.thread.BrokenThreadPool

Derived from @ref{36fe,,BrokenExecutor}, this exception
class is raised when one of the workers
of a @ref{949,,ThreadPoolExecutor}
has failed initializing.


Added in version 3.7.

@end deffn

@geindex BrokenInterpreterPool
@anchor{library/concurrent futures concurrent futures interpreter BrokenInterpreterPool}@anchor{36ff}
@deffn {例外} concurrent.futures.interpreter.BrokenInterpreterPool

Derived from @ref{36e6,,BrokenThreadPool},
this exception class is raised when one of the workers
of a @ref{1d2,,InterpreterPoolExecutor}
has failed initializing.


Added in version 3.14.

@end deffn

@geindex BrokenProcessPool
@anchor{library/concurrent futures concurrent futures process BrokenProcessPool}@anchor{36eb}
@deffn {例外} concurrent.futures.process.BrokenProcessPool

Derived from @ref{36fe,,BrokenExecutor} (formerly
@ref{244,,RuntimeError}), this exception class is raised when one of the
workers of a @ref{1d6,,ProcessPoolExecutor}
has terminated in a non-clean
fashion (for example, if it was killed from the outside).


Added in version 3.3.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node concurrent interpreters --- Multiple interpreters in the same process,subprocess --- サブプロセス管理,concurrent futures --- 並列タスク実行,並行実行
@anchor{library/concurrent interpreters doc}@anchor{3700}@anchor{library/concurrent interpreters concurrent-interpreters-multiple-interpreters-in-the-same-process}@anchor{3701}@anchor{library/concurrent interpreters module-concurrent interpreters}@anchor{25}@anchor{library/concurrent interpreters translation-repo}@anchor{3702}
@subsection @code{concurrent.interpreters} --- Multiple interpreters in the same process


@geindex module; concurrent.interpreters


Added in version 3.14.


`Source code:' Lib/concurrent/interpreters@footnote{https://github.com/python/cpython/tree/3.14/Lib/concurrent/interpreters}


__________________________________________________________________


The @code{concurrent.interpreters} module constructs higher-level
interfaces on top of the lower level @code{_interpreters} module.

The module is primarily meant to provide a basic API for managing
interpreters (AKA "subinterpreters") and running things in them.
Running mostly involves switching to an interpreter (in the current
thread) and calling a function in that execution context.

For concurrency, interpreters themselves (and this module) don't
provide much more than isolation, which on its own isn't useful.
Actual concurrency is available separately through
@ref{f3,,threads}  See @ref{3703,,below}@anchor{library/concurrent interpreters interp-concurrency}@anchor{3703}


@subsubheading 参考



@table @asis

@item @ref{1d2,,InterpreterPoolExecutor}

Combines threads with interpreters in a familiar interface.
@end table

@c XXX Add references to the upcoming HOWTO docs in the seealso block.


@table @asis

@item @ref{166,,拡張モジュールを分離する}

How to update an extension module to support multiple interpreters.
@end table

@geindex Python Enhancement Proposals; PEP 554
PEP 554@footnote{https://peps.python.org/pep-0554/}

@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}

@geindex Python Enhancement Proposals; PEP 684
PEP 684@footnote{https://peps.python.org/pep-0684/}


@c XXX Why do we disallow multiple interpreters on WASM?

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@menu
* Key details:: 
* はじめに: はじめに<10>. 
* リファレンス: リファレンス<4>. 
* 基本的な使い方: 基本的な使い方<3>. 

@end menu

@node Key details,はじめに<10>,,concurrent interpreters --- Multiple interpreters in the same process
@anchor{library/concurrent interpreters key-details}@anchor{3704}
@subsubsection Key details


Before we dive in further, there are a small number of details
to keep in mind about using multiple interpreters:


@itemize *

@item 
@ref{3705,,isolated}@anchor{library/concurrent interpreters interp-isolation}@anchor{3705}, by default

@item 
no implicit threads

@item 
not all PyPI packages support use in multiple interpreters yet
@end itemize

@c XXX Are there other relevant details to list?

@node はじめに<10>,リファレンス<4>,Key details,concurrent interpreters --- Multiple interpreters in the same process
@anchor{library/concurrent interpreters interpreters-intro}@anchor{3706}@anchor{library/concurrent interpreters introduction}@anchor{3707}
@subsubsection はじめに


An "interpreter" is effectively the execution context of the Python
runtime.  It contains all of the state the runtime needs to execute
a program.  This includes things like the import state and builtins.
(Each thread, even if there's only the main thread, has some extra
runtime state, in addition to the current interpreter, related to
the current exception and the bytecode eval loop.)

The concept and functionality of the interpreter have been a part of
Python since version 2.2, but the feature was only available through
the C-API and not well known, and the @ref{3705,,isolation}
was relatively incomplete until version 3.12.

@menu
* Multiple Interpreters and Isolation:: 
* Running in an Interpreter:: 
* Concurrency and Parallelism:: 
* Communication Between Interpreters:: 
* "Sharing" Objects:: 

@end menu

@node Multiple Interpreters and Isolation,Running in an Interpreter,,はじめに<10>
@anchor{library/concurrent interpreters multiple-interpreters-and-isolation}@anchor{3708}
@subsubsection Multiple Interpreters and Isolation


A Python implementation may support using multiple interpreters in the
same process.  CPython has this support.  Each interpreter is
effectively isolated from the others (with a limited number of
carefully managed process-global exceptions to the rule).

That isolation is primarily useful as a strong separation between
distinct logical components of a program, where you want to have
careful control of how those components interact.

@cartouche
@quotation 注釈 
Interpreters in the same process can technically never be strictly
isolated from one another since there are few restrictions on memory
access within the same process.  The Python runtime makes a best
effort at isolation but extension modules may easily violate that.
Therefore, do not use multiple interpreters in security-sensitive
situations, where they shouldn't have access to each other's data.
@end quotation
@end cartouche

@node Running in an Interpreter,Concurrency and Parallelism,Multiple Interpreters and Isolation,はじめに<10>
@anchor{library/concurrent interpreters running-in-an-interpreter}@anchor{3709}
@subsubsection Running in an Interpreter


Running in a different interpreter involves switching to it in the
current thread and then calling some function.  The runtime will
execute the function using the current interpreter's state.  The
@code{concurrent.interpreters} module provides a basic API for
creating and managing interpreters, as well as the switch-and-call
operation.

No other threads are automatically started for the operation.
There is @ref{370a,,a helper}@anchor{library/concurrent interpreters interp-call-in-thread}@anchor{370a} for that though.
There is another dedicated helper for calling the builtin
@ref{4a2,,exec()} in an interpreter.

When @ref{4a2,,exec()} (or @ref{4a3,,eval()}) are called in an interpreter,
they run using the interpreter's @code{__main__} module as the
"globals" namespace.  The same is true for functions that aren't
associated with any module.  This is the same as how scripts invoked
from the command-line run in the @code{__main__} module.

@node Concurrency and Parallelism,Communication Between Interpreters,Running in an Interpreter,はじめに<10>
@anchor{library/concurrent interpreters concurrency-and-parallelism}@anchor{370b}
@subsubsection Concurrency and Parallelism


As noted earlier, interpreters do not provide any concurrency
on their own.  They strictly represent the isolated execution
context the runtime will use `in the current thread'.  That isolation
makes them similar to processes, but they still enjoy in-process
efficiency, like threads.

All that said, interpreters do naturally support certain flavors of
concurrency.
There's a powerful side effect of that isolation.  It enables a
different approach to concurrency than you can take with async or
threads.  It's a similar concurrency model to CSP or the actor model,
a model which is relatively easy to reason about.

You can take advantage of that concurrency model in a single thread,
switching back and forth between interpreters, Stackless-style.
However, this model is more useful when you combine interpreters
with multiple threads.  This mostly involves starting a new thread,
where you switch to another interpreter and run what you want there.

Each actual thread in Python, even if you're only running in the main
thread, has its own `current' execution context.  Multiple threads can
use the same interpreter or different ones.

At a high level, you can think of the combination of threads and
interpreters as threads with opt-in sharing.

As a significant bonus, interpreters are sufficiently isolated that
they do not share the @ref{164,,GIL}, which means combining threads with
multiple interpreters enables full multi-core parallelism.
(This has been the case since Python 3.12.)

@node Communication Between Interpreters,"Sharing" Objects,Concurrency and Parallelism,はじめに<10>
@anchor{library/concurrent interpreters communication-between-interpreters}@anchor{370c}
@subsubsection Communication Between Interpreters


In practice, multiple interpreters are useful only if we have a way
to communicate between them.  This usually involves some form of
message passing, but can even mean sharing data in some carefully
managed way.

With this in mind, the @code{concurrent.interpreters} module provides
a @ref{15ac,,queue.Queue} implementation, available through
@ref{370d,,create_queue()}.

@node "Sharing" Objects,,Communication Between Interpreters,はじめに<10>
@anchor{library/concurrent interpreters interp-object-sharing}@anchor{370e}@anchor{library/concurrent interpreters sharing-objects}@anchor{370f}
@subsubsection "Sharing" Objects


Any data actually shared between interpreters loses the thread-safety
provided by the @ref{164,,GIL}.  There are various options for dealing with
this in extension modules.  However, from Python code the lack of
thread-safety means objects can't actually be shared, with a few
exceptions.  Instead, a copy must be created, which means mutable
objects won't stay in sync.

By default, most objects are copied with @ref{ab,,pickle} when they are
passed to another interpreter.  Nearly all of the immutable builtin
objects are either directly shared or copied efficiently.  For example:


@itemize *

@item 
@ref{885,,None}

@item 
@ref{3c3,,bool} (@ref{e07,,True} and @ref{d2b,,False})

@item 
@ref{192,,bytes}

@item 
@ref{169,,str}

@item 
@ref{19b,,int}

@item 
@ref{196,,float}

@item 
@ref{614,,tuple} (of similarly supported objects)
@end itemize

There is a small number of Python types that actually share mutable
data between interpreters:


@itemize *

@item 
@ref{165,,memoryview}

@item 
@ref{3710,,Queue}
@end itemize

@node リファレンス<4>,基本的な使い方<3>,はじめに<10>,concurrent interpreters --- Multiple interpreters in the same process
@anchor{library/concurrent interpreters reference}@anchor{3711}
@subsubsection リファレンス


このモジュールは以下の関数を定義しています:

@geindex list_all() (concurrent.interpreters モジュール)
@anchor{library/concurrent interpreters concurrent interpreters list_all}@anchor{3712}
@deffn {の関数} concurrent.interpreters.list_all ()

Return a @ref{24d,,list} of @ref{3713,,Interpreter} objects,
one for each existing interpreter.
@end deffn

@geindex get_current() (concurrent.interpreters モジュール)
@anchor{library/concurrent interpreters concurrent interpreters get_current}@anchor{3714}
@deffn {の関数} concurrent.interpreters.get_current ()

Return an @ref{3713,,Interpreter} object for the currently running
interpreter.
@end deffn

@geindex get_main() (concurrent.interpreters モジュール)
@anchor{library/concurrent interpreters concurrent interpreters get_main}@anchor{3715}
@deffn {の関数} concurrent.interpreters.get_main ()

Return an @ref{3713,,Interpreter} object for the main interpreter.
This is the interpreter the runtime created to run the @ref{491,,REPL}
or the script given at the command-line.  It is usually the only one.
@end deffn

@geindex create() (concurrent.interpreters モジュール)
@anchor{library/concurrent interpreters concurrent interpreters create}@anchor{17bc}
@deffn {の関数} concurrent.interpreters.create ()

Initialize a new (idle) Python interpreter
and return a @ref{3713,,Interpreter} object for it.
@end deffn

@geindex create_queue() (concurrent.interpreters モジュール)
@anchor{library/concurrent interpreters concurrent interpreters create_queue}@anchor{370d}
@deffn {の関数} concurrent.interpreters.create_queue ()

Initialize a new cross-interpreter queue and return a @ref{3710,,Queue}
object for it.
@end deffn

@menu
* Interpreter objects:: 
* 例外: 例外<13>. 
* Communicating Between Interpreters:: 

@end menu

@node Interpreter objects,例外<13>,,リファレンス<4>
@anchor{library/concurrent interpreters interpreter-objects}@anchor{3716}
@subsubsection Interpreter objects


@geindex Interpreter (concurrent.interpreters のクラス)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter}@anchor{3713}
@deffn {クラス} concurrent.interpreters.Interpreter (id)

A single interpreter in the current process.

Generally, @ref{3713,,Interpreter} shouldn't be called directly.
Instead, use @ref{17bc,,create()} or one of the other module functions.

@geindex id (concurrent.interpreters.Interpreter の属性)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter id}@anchor{3717}
@deffn {の属性} id

(read-only)

The underlying interpreter's ID.
@end deffn

@geindex whence (concurrent.interpreters.Interpreter の属性)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter whence}@anchor{3718}
@deffn {の属性} whence

(read-only)

A string describing where the interpreter came from.
@end deffn

@geindex is_running() (concurrent.interpreters.Interpreter のメソッド)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter is_running}@anchor{3719}
@deffn {メソッド} is_running ()

Return @code{True} if the interpreter is currently executing code
in its @code{__main__} module and @code{False} otherwise.
@end deffn

@geindex close() (concurrent.interpreters.Interpreter のメソッド)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter close}@anchor{17d1}
@deffn {メソッド} close ()

Finalize and destroy the interpreter.
@end deffn

@geindex prepare_main() (concurrent.interpreters.Interpreter のメソッド)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter prepare_main}@anchor{371a}
@deffn {メソッド} prepare_main (ns=None, **kwargs)

Bind objects in the interpreter's @code{__main__} module.

Some objects are actually shared and some are copied efficiently,
but most are copied via @ref{ab,,pickle}.  See @ref{370e,,"Sharing" Objects}.
@end deffn

@geindex exec() (concurrent.interpreters.Interpreter のメソッド)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter exec}@anchor{371b}
@deffn {メソッド} exec (code, /, dedent=True)

Run the given source code in the interpreter (in the current thread).
@end deffn

@geindex call() (concurrent.interpreters.Interpreter のメソッド)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter call}@anchor{371c}
@deffn {メソッド} call (callable, /, *args, **kwargs)

Return the result of calling running the given function in the
interpreter (in the current thread).
@end deffn

@geindex call_in_thread() (concurrent.interpreters.Interpreter のメソッド)
@anchor{library/concurrent interpreters concurrent interpreters Interpreter call_in_thread}@anchor{371d}
@deffn {メソッド} call_in_thread (callable, /, *args, **kwargs)

Run the given function in the interpreter (in a new thread).
@end deffn
@end deffn

@node 例外<13>,Communicating Between Interpreters,Interpreter objects,リファレンス<4>
@anchor{library/concurrent interpreters exceptions}@anchor{371e}
@subsubsection 例外


@geindex InterpreterError
@anchor{library/concurrent interpreters concurrent interpreters InterpreterError}@anchor{371f}
@deffn {例外} concurrent.interpreters.InterpreterError

This exception, a subclass of @ref{bcd,,Exception}, is raised when
an interpreter-related error happens.
@end deffn

@geindex InterpreterNotFoundError
@anchor{library/concurrent interpreters concurrent interpreters InterpreterNotFoundError}@anchor{3720}
@deffn {例外} concurrent.interpreters.InterpreterNotFoundError

This exception, a subclass of @ref{371f,,InterpreterError}, is raised when
the targeted interpreter no longer exists.
@end deffn

@geindex ExecutionFailed
@anchor{library/concurrent interpreters concurrent interpreters ExecutionFailed}@anchor{36e9}
@deffn {例外} concurrent.interpreters.ExecutionFailed

This exception, a subclass of @ref{371f,,InterpreterError}, is raised when
the running code raised an uncaught exception.

@geindex excinfo (concurrent.interpreters.ExecutionFailed の属性)
@anchor{library/concurrent interpreters concurrent interpreters ExecutionFailed excinfo}@anchor{3721}
@deffn {の属性} excinfo

A basic snapshot of the exception raised in the other interpreter.
@end deffn
@end deffn

@c XXX Document the excinfoattrs?

@geindex NotShareableError
@anchor{library/concurrent interpreters concurrent interpreters NotShareableError}@anchor{3722}
@deffn {例外} concurrent.interpreters.NotShareableError

This exception, a subclass of @ref{198,,TypeError}, is raised when
an object cannot be sent to another interpreter.
@end deffn

@node Communicating Between Interpreters,,例外<13>,リファレンス<4>
@anchor{library/concurrent interpreters communicating-between-interpreters}@anchor{3723}
@subsubsection Communicating Between Interpreters


@geindex Queue (concurrent.interpreters のクラス)
@anchor{library/concurrent interpreters concurrent interpreters Queue}@anchor{3710}
@deffn {クラス} concurrent.interpreters.Queue (id)

A wrapper around a low-level, cross-interpreter queue, which
implements the @ref{15ac,,queue.Queue} interface.  The underlying queue
can only be created through @ref{370d,,create_queue()}.

Some objects are actually shared and some are copied efficiently,
but most are copied via @ref{ab,,pickle}.  See @ref{370e,,"Sharing" Objects}.

@geindex id (concurrent.interpreters.Queue の属性)
@anchor{library/concurrent interpreters concurrent interpreters Queue id}@anchor{3724}
@deffn {の属性} id

(read-only)

The queue's ID.
@end deffn
@end deffn

@geindex QueueEmptyError
@anchor{library/concurrent interpreters concurrent interpreters QueueEmptyError}@anchor{3725}
@deffn {例外} concurrent.interpreters.QueueEmptyError

This exception, a subclass of @ref{366c,,queue.Empty}, is raised from
@code{Queue.get()} and @code{Queue.get_nowait()} when the queue
is empty.
@end deffn

@geindex QueueFullError
@anchor{library/concurrent interpreters concurrent interpreters QueueFullError}@anchor{3726}
@deffn {例外} concurrent.interpreters.QueueFullError

This exception, a subclass of @ref{366d,,queue.Full}, is raised from
@code{Queue.put()} and @code{Queue.put_nowait()} when the queue
is full.
@end deffn

@node 基本的な使い方<3>,,リファレンス<4>,concurrent interpreters --- Multiple interpreters in the same process
@anchor{library/concurrent interpreters basic-usage}@anchor{3727}
@subsubsection 基本的な使い方


Creating an interpreter and running code in it:

@example
from concurrent import interpreters

interp = interpreters.create()

# Run in the current OS thread.

interp.exec('print("spam!")')

interp.exec("""if True:
    print('spam!')
    """)

from textwrap import dedent
interp.exec(dedent("""
    print('spam!')
    """))

def run(arg):
    return arg

res = interp.call(run, 'spam!')
print(res)

def run():
    print('spam!')

interp.call(run)

# Run in new OS thread.

t = interp.call_in_thread(run)
t.join()
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node subprocess --- サブプロセス管理,sched --- イベントスケジューラー,concurrent interpreters --- Multiple interpreters in the same process,並行実行
@anchor{library/subprocess doc}@anchor{3728}@anchor{library/subprocess module-subprocess}@anchor{dc}@anchor{library/subprocess subprocess-subprocess-management}@anchor{3729}@anchor{library/subprocess translation-repo}@anchor{372a}
@subsection @code{subprocess} --- サブプロセス管理


@geindex module; subprocess

`ソースコード:' Lib/subprocess.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/subprocess.py}


__________________________________________________________________


The @code{subprocess} module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes.  This module intends to
replace several older modules and functions:

@example
os.system
os.spawn*
@end example

Information about how the @code{subprocess} module can be used to replace these
modules and functions can be found in the following sections.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 324
PEP 324@footnote{https://peps.python.org/pep-0324/} -- subprocess モジュールを提案している PEP


@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

@menu
* Using the subprocess Module:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<2>. 
* Popen オブジェクト:: 
* Windows Popen ヘルパー:: 
* 古い高水準 API:: 
* Replacing Older Functions with the subprocess Module:: 
* レガシーなシェル呼び出し関数:: 
* 注釈: 注釈<2>. 

@end menu

@node Using the subprocess Module,セキュリティで考慮すべき点<2>,,subprocess --- サブプロセス管理
@anchor{library/subprocess using-the-subprocess-module}@anchor{372b}
@subsubsection Using the @code{subprocess} Module


サブプロセスを起動するために推奨される方法は、すべての用法を扱える @ref{d7f,,run()} 関数を使用することです。より高度な用法では下層の @ref{4b7,,Popen} インターフェースを直接使用することもできます。

@geindex run() (subprocess モジュール)
@anchor{library/subprocess subprocess run}@anchor{d7f}
@deffn {の関数} subprocess.run (args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

`args' で指定されたコマンドを実行します。コマンドの完了を待って、@ref{1073,,CompletedProcess} インスタンスを返します。

上記の引数は、もっともよく使われるものだけ示しており、後述の @ref{372c,,よく使われる引数} で説明されています (そのためここではキーワード専用引数の表記に省略されています)。関数の完全な使用法を説明しても大部分が @ref{4b7,,Popen} コンストラクターの内容と同じになります - この関数のほとんどの引数は @ref{4b7,,Popen} インターフェイスに渡されます。(`timeout'、`input' および `check' は除く。)

If `capture_output' is true, stdout and stderr will be captured.
When used, the internal @ref{4b7,,Popen} object is automatically created with
`stdout' and `stderr' both set to @ref{d80,,PIPE}.
The `stdout' and `stderr' arguments may not be supplied at the same time as `capture_output'.
If you wish to capture and combine both streams into one,
set `stdout' to @ref{d80,,PIPE}
and `stderr' to @ref{372d,,STDOUT},
instead of using `capture_output'.

A `timeout' may be specified in seconds, it is internally passed on to
@ref{17aa,,Popen.communicate()}. If the timeout expires, the child process will be
killed and waited for. The @ref{17ab,,TimeoutExpired} exception will be
re-raised after the child process has terminated. The initial process
creation itself cannot be interrupted on many platform APIs so you are not
guaranteed to see a timeout exception until at least after however long
process creation takes.

The `input' argument is passed to @ref{17aa,,Popen.communicate()} and thus to the
subprocess's stdin.  If used it must be a byte sequence, or a string if
`encoding' or `errors' is specified or `text' is true.  When
used, the internal @ref{4b7,,Popen} object is automatically created with
`stdin' set to @ref{d80,,PIPE},
and the `stdin' argument may not be used as well.

`check' に真を指定した場合、プロセスが非ゼロの終了コードで終了すると @ref{153c,,CalledProcessError} 例外が送出されます。
この例外の属性には、引数、終了コード、標準出力および標準エラー出力が捕捉できた場合に格納されます。

`encoding' または `errors' 引数が指定されるか、`text' 引数が true である場合、stdin, stdout および stderr のためのファイルオブジェクトはテキストモードでオープンされます。 その際には指定された `encoding' および `errors' が使われるか、デフォルトの @ref{9be,,io.TextIOWrapper} になります。`universal_newlines' 引数は `text' 引数と等価であり、後方互換性のために提供されています。そうでない場合、デフォルトでこれらのファイルオブジェクトはバイナリモードでオープンされます。

`env' が @code{None} 以外の場合、これは新しいプロセスでの環境変数を定義します。デフォルトでは、子プロセスは現在のプロセスの環境変数を引き継ぎます。 @ref{4b7,,Popen} に直接渡されます。あらゆるプラットフォームで @ref{259,,os.environ} のように文字列から文字列へ、またPOSIX プラットフォームにおいては @ref{25a,,os.environb} のようにバイトからバイトへも、定義すること出来ます。

例:

@example
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'@w{'})
@end example


Added in version 3.5.



バージョン 3.6 で変更: `encoding' と `error' が引数に追加されました。



バージョン 3.7 で変更: `universal_newlines' 引数のよりわかりやすい名前として、`text' 引数が追加されました。`capture_output' 引数が追加されました。



バージョン 3.12 で変更: @code{shell=True} のときのWindowsシェル検索順序を変更しました。カレントディレクトリと @code{%PATH%} は、 @code{%COMSPEC%} と @code{%SystemRoot%\System32\cmd.exe} に置き換えられました。これにより、 @code{cmd.exe} という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

@end deffn

@geindex CompletedProcess (subprocess のクラス)
@anchor{library/subprocess subprocess CompletedProcess}@anchor{1073}
@deffn {クラス} subprocess.CompletedProcess

@ref{d7f,,run()} の戻り値。プロセスが終了したことを表します。

@geindex args (subprocess.CompletedProcess の属性)
@anchor{library/subprocess subprocess CompletedProcess args}@anchor{372e}
@deffn {の属性} args

プロセスを起動するときに使用された引数。1 個のリストか 1 個の文字列になります。
@end deffn

@geindex returncode (subprocess.CompletedProcess の属性)
@anchor{library/subprocess subprocess CompletedProcess returncode}@anchor{372f}
@deffn {の属性} returncode

子プロセスの終了コード。一般に、終了ステータス 0 はプロセスが正常に終了したことを示します。

負の値 @code{-N} は子プロセスがシグナル @code{N} により中止させられたことを示します (POSIX のみ)。
@end deffn

@geindex stdout (subprocess.CompletedProcess の属性)
@anchor{library/subprocess subprocess CompletedProcess stdout}@anchor{3730}
@deffn {の属性} stdout

子プロセスから補足された標準出力です。バイト列、もしくは @ref{d7f,,run()} でエンコーディングが指定された場合、エラーの場合、text=True が指定された場合は文字列です。標準出力が補足できなかったら @code{None} になります。

プロセスが @code{stderr=subprocess.STDOUT} で実行された場合、標準出力と標準エラー出力が混合されたものがこの属性に格納され、@ref{3731,,stderr} は @code{None} になります。
@end deffn

@geindex stderr (subprocess.CompletedProcess の属性)
@anchor{library/subprocess subprocess CompletedProcess stderr}@anchor{3731}
@deffn {の属性} stderr

子プロセスから補足された標準エラー出力です。バイト列、もしくは @ref{d7f,,run()} でエンコーディングが指定された場合、エラーの場合、text=True が指定された場合は文字列です。標準エラー出力が補足できなかったら @code{None} になります。
@end deffn

@geindex check_returncode() (subprocess.CompletedProcess のメソッド)
@anchor{library/subprocess subprocess CompletedProcess check_returncode}@anchor{3732}
@deffn {メソッド} check_returncode ()

@ref{372f,,returncode} が非ゼロの場合、@ref{153c,,CalledProcessError} が送出されます。
@end deffn


Added in version 3.5.

@end deffn

@geindex DEVNULL (subprocess モジュール)
@anchor{library/subprocess subprocess DEVNULL}@anchor{1366}
@deffn {データ} subprocess.DEVNULL

@ref{4b7,,Popen} の `stdin', `stdout', `stderr' 引数に渡して、標準入出力を @ref{1e14,,os.devnull} から入出力するように指定するための特殊値です。


Added in version 3.3.

@end deffn

@geindex PIPE (subprocess モジュール)
@anchor{library/subprocess subprocess PIPE}@anchor{d80}
@deffn {データ} subprocess.PIPE

@ref{4b7,,Popen} の `stdin', `stdout', `stderr' 引数に渡して、標準ストリームに対するパイプを開くことを指定するための特殊値です。@ref{17aa,,Popen.communicate()} に非常に有用です。
@end deffn

@geindex STDOUT (subprocess モジュール)
@anchor{library/subprocess subprocess STDOUT}@anchor{372d}
@deffn {データ} subprocess.STDOUT

@ref{4b7,,Popen} の `stderr' 引数に渡して、標準エラー出力が標準出力と同じハンドルに出力されるように指定するための特殊値です。
@end deffn

@geindex SubprocessError
@anchor{library/subprocess subprocess SubprocessError}@anchor{3733}
@deffn {例外} subprocess.SubprocessError

このモジュールの他のすべての例外のための基底クラスです。


Added in version 3.3.

@end deffn

@geindex TimeoutExpired
@anchor{library/subprocess subprocess TimeoutExpired}@anchor{17ab}
@deffn {例外} subprocess.TimeoutExpired

@ref{3733,,SubprocessError} のサブクラスです。子プロセスの終了を待機している間にタイムアウトが発生した場合に送出されます。

@geindex cmd (subprocess.TimeoutExpired の属性)
@anchor{library/subprocess subprocess TimeoutExpired cmd}@anchor{3734}
@deffn {の属性} cmd

子プロセスの生成に使用されるコマンド本文。
@end deffn

@geindex timeout (subprocess.TimeoutExpired の属性)
@anchor{library/subprocess subprocess TimeoutExpired timeout}@anchor{3735}
@deffn {の属性} timeout

タイムアウト秒数。
@end deffn

@geindex output (subprocess.TimeoutExpired の属性)
@anchor{library/subprocess subprocess TimeoutExpired output}@anchor{3736}
@deffn {の属性} output

@ref{d7f,,run()} にまたは @ref{11c4,,check_output()} によって捕捉された場合は、子プロセスの出力となり、それ以外の場合は @code{None} となります。@code{text=True} の設定に関係なく、出力が捕捉された場合は常に @ref{192,,bytes} となります。出力がない場合は @code{b'@w{'}} の代わりに`@w{`}None`@w{`} のままになることがあります。
@end deffn

@geindex stdout (subprocess.TimeoutExpired の属性)
@anchor{library/subprocess subprocess TimeoutExpired stdout}@anchor{3737}
@deffn {の属性} stdout

output の別名。@ref{3738,,stderr} と対になります。
@end deffn

@geindex stderr (subprocess.TimeoutExpired の属性)
@anchor{library/subprocess subprocess TimeoutExpired stderr}@anchor{3738}
@deffn {の属性} stderr

@ref{d7f,,run()} によって捕捉された場合、子プロセスの標準エラー出力が表示され、それ以外の場合は @code{None} となります。@code{text=True} の設定に関係なく、標準エラー出力を捕捉した場合は常に @ref{192,,bytes} となります。標準エラー出力がない場合は、@code{b'@w{'}} の代わりに @code{None} のままになることがあります。
@end deffn


Added in version 3.3.



バージョン 3.5 で変更: 属性 `stdout' および `stderr' が追加されました。

@end deffn

@geindex CalledProcessError
@anchor{library/subprocess subprocess CalledProcessError}@anchor{153c}
@deffn {例外} subprocess.CalledProcessError

@ref{3733,,SubprocessError} のサブクラスです。@ref{3739,,check_call()} または @ref{11c4,,check_output()} 、 @code{check=True} であるときの @ref{d7f,,run()} 、によって実行されたプロセスが非ゼロの終了ステータスを返した場合に送出されます。

@geindex returncode (subprocess.CalledProcessError の属性)
@anchor{library/subprocess subprocess CalledProcessError returncode}@anchor{373a}
@deffn {の属性} returncode

子プロセスの終了ステータスです。もしプロセスがシグナルによって終了したなら、これは負のシグナル番号になります。
@end deffn

@geindex cmd (subprocess.CalledProcessError の属性)
@anchor{library/subprocess subprocess CalledProcessError cmd}@anchor{373b}
@deffn {の属性} cmd

子プロセスの生成に使用されるコマンド本文。
@end deffn

@geindex output (subprocess.CalledProcessError の属性)
@anchor{library/subprocess subprocess CalledProcessError output}@anchor{373c}
@deffn {の属性} output

@ref{d7f,,run()} または @ref{11c4,,check_output()} によって捕捉された子プロセスの出力。捕捉されなかったら @code{None} になります。
@end deffn

@geindex stdout (subprocess.CalledProcessError の属性)
@anchor{library/subprocess subprocess CalledProcessError stdout}@anchor{373d}
@deffn {の属性} stdout

output の別名。@ref{373e,,stderr} と対になります。
@end deffn

@geindex stderr (subprocess.CalledProcessError の属性)
@anchor{library/subprocess subprocess CalledProcessError stderr}@anchor{373e}
@deffn {の属性} stderr

@ref{d7f,,run()} によって捕捉された子プロセスの標準エラー出力。捕捉されなかったら @code{None} になります。
@end deffn


バージョン 3.5 で変更: 属性 `stdout' および `stderr' が追加されました。

@end deffn

@menu
* よく使われる引数:: 
* Popen コンストラクター:: 
* 例外: 例外<14>. 

@end menu

@node よく使われる引数,Popen コンストラクター,,Using the subprocess Module
@anchor{library/subprocess frequently-used-arguments}@anchor{372c}@anchor{library/subprocess id1}@anchor{373f}
@subsubsection よく使われる引数


幅広い使用例をサポートするために、@ref{4b7,,Popen} コンストラクター (とその他の簡易関数) は、多くのオプション引数を受け付けます。一般的な用法については、これらの引数の多くはデフォルト値のままで問題ありません。通常必要とされる引数は以下の通りです:

@quotation

`args' はすべての呼び出しに必要で、文字列あるいはプログラム引数のシーケンスでなければなりません。一般に、引数のシーケンスを渡す方が望ましいです。なぜなら、モジュールが必要な引数のエスケープやクオート (例えばファイル名中のスペースを許すこと) の面倒を見ることができるためです。単一の文字列を渡す場合、`shell' は @ref{e07,,True} でなければなりません (以下を参照)。もしくは、その文字列は引数を指定せずに実行される単なるプログラムの名前でなければなりません。

`stdin', `stdout' and `stderr' specify the executed program's standard input,
standard output and standard error file handles, respectively.  Valid values
are @code{None}, @ref{d80,,PIPE}, @ref{1366,,DEVNULL}, an existing file descriptor (a
positive integer), and an existing @ref{13db,,file object} with a valid file
descriptor.  With the default settings of @code{None}, no redirection will
occur.  @ref{d80,,PIPE} indicates that a new pipe to the child should be
created.  @ref{1366,,DEVNULL} indicates that the special file @ref{1e14,,os.devnull}
will be used.  Additionally, `stderr' can be @ref{372d,,STDOUT}, which indicates
that the stderr data from the child process should be captured into the same
file handle as for `stdout'.

@geindex universal newlines;subprocess モジュール

If `encoding' or `errors' are specified, or `text' (also known as
`universal_newlines') is true,
the file objects `stdin', `stdout' and `stderr' will be opened in text
mode using the `encoding' and `errors' specified in the call or the
defaults for @ref{9be,,io.TextIOWrapper}.

`stdin' については、入力での行末文字 @code{'\n'} はデフォルトの行セパレーター @ref{25dc,,os.linesep} に変換されます。`stdout' と `stderr' については、出力での行末はすべて @code{'\n'} に変換されます。詳細は @ref{9be,,io.TextIOWrapper} クラスのドキュメントでコンストラクターの引数 `newline' が @code{None} である場合を参照してください。

If text mode is not used, `stdin', `stdout' and `stderr' will be opened as
binary streams. No encoding or line ending conversion is performed.


バージョン 3.6 で変更: `encoding' と `errors' が引数に追加されました。



バージョン 3.7 で変更: `universal_newlines' の別名として、`text' 引数が追加されました。


@cartouche
@quotation 注釈 
ファイルオブジェクト @ref{3740,,Popen.stdin}、@ref{3741,,Popen.stdout} ならびに @ref{3742,,Popen.stderr} の改行属性は @ref{17aa,,Popen.communicate()} メソッドで更新されません。
@end quotation
@end cartouche

`shell' が @code{True} なら、指定されたコマンドはシェルによって実行されます。あなたが Python を主として (ほとんどのシステムシェル以上の) 強化された制御フローのために使用していて、さらにシェルパイプ、ファイル名ワイルドカード、環境変数展開、@code{~} のユーザーホームディレクトリへの展開のような他のシェル機能への簡単なアクセスを望むなら、これは有用かもしれません。しかしながら、Python 自身が多くのシェル的な機能の実装を提供していることに注意してください (特に @ref{68,,glob}, @ref{60,,fnmatch}, @ref{6d0,,os.walk()}, @ref{15f2,,os.path.expandvars()}, @ref{c09,,os.path.expanduser()}, @ref{ca,,shutil})。


バージョン 3.3 で変更: `universal_newlines' が @code{True} の場合、クラスはエンコーディング @code{locale.getpreferredencoding()} の代わりに @ref{75c,,locale.getpreferredencoding(False)} を使用します。この変更についての詳細は、 @ref{9be,,io.TextIOWrapper} クラスを参照してください。


@cartouche
@quotation 注釈 
@code{shell=True} を使う前に @ref{3743,,セキュリティで考慮すべき点} を読んでください。
@end quotation
@end cartouche
@end quotation

これらのオプションは、他のすべてのオプションとともに @ref{4b7,,Popen} コンストラクターのドキュメントの中でより詳細に説明されています。

@node Popen コンストラクター,例外<14>,よく使われる引数,Using the subprocess Module
@anchor{library/subprocess popen-constructor}@anchor{3744}
@subsubsection Popen コンストラクター


このモジュールの中で、根底のプロセス生成と管理は @ref{4b7,,Popen} クラスによって扱われます。簡易関数によってカバーされないあまり一般的でないケースを開発者が扱えるように、@ref{4b7,,Popen} クラスは多くの柔軟性を提供しています。

@geindex Popen (subprocess のクラス)
@anchor{library/subprocess subprocess Popen}@anchor{4b7}
@deffn {クラス} subprocess.Popen (args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None, pipesize=-1, process_group=None)

新しいプロセスで子のプログラムを実行します。POSIX においては、子のプログラムを実行するために、このクラスは @ref{30ba,,os.execvpe()} のような挙動を使用します。Windows においては、このクラスは Windows の @code{CreateProcess()} 関数を使用します。@ref{4b7,,Popen} への引数は以下の通りです。

`args' はプログラム引数のシーケンスか、単一の文字列または @ref{5a1,,path-like object} でなければなりません。デフォルトでは、`args' がシーケンスの場合に実行されるプログラムは `args' の最初の要素です。`args' が文字列の場合、解釈はプラットフォーム依存であり、下記に説明されます。デフォルトの挙動からの追加の違いについては `shell' および `executable' 引数を参照してください。特に明記されない限り、`args' をシーケンスとして渡すことが推奨されます。

@cartouche
@quotation 警告 
For maximum reliability, use a fully qualified path for the executable.
To search for an unqualified name on 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}, use
@ref{6db,,shutil.which()}. On all platforms, passing @ref{3ed,,sys.executable}
is the recommended way to launch the current Python interpreter again,
and use the @code{-m} command-line format to launch an installed module.

Resolving the path of `executable' (or the first item of `args') is
platform dependent. For POSIX, see @ref{30ba,,os.execvpe()}, and note that
when resolving or searching for the executable path, `cwd' overrides the
current working directory and `env' can override the @code{PATH}
environment variable. For Windows, see the documentation of the
@code{lpApplicationName} and @code{lpCommandLine} parameters of WinAPI
@code{CreateProcess}, and note that when resolving or searching for the
executable path with @code{shell=False}, `cwd' does not override the
current working directory and `env' cannot override the @code{PATH}
environment variable. Using a full path avoids all of these variations.
@end quotation
@end cartouche

An example of passing some arguments to an external program
as a sequence is:

@example
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
@end example

POSIX 上では、`args' が文字列の場合、その文字列は実行すべきプログラムの名前またはパスとして解釈されます。しかし、これはプログラムに引数を渡さない場合にのみ可能です。

@cartouche
@quotation 注釈 
It may not be obvious how to break a shell command into a sequence of arguments,
especially in complex cases. @ref{75e,,shlex.split()} can illustrate how to
determine the correct tokenization for `args':

@example
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
@end example

特に注意すべき点は、シェル内でスペースで区切られたオプション (`-input' など) と引数 (`eggs.txt' など) はリストの別々の要素になるのに対し、シェル内で (上記のスペースを含むファイル名や `echo' コマンドのように) クォーティングやバックスラッシュエスケープが必要なものは単一のリスト要素であることです。
@end quotation
@end cartouche

Windows 上では、`args' がシーケンスなら @ref{3745,,Windows における引数シーケンスから文字列への変換} に記述された方法で文字列に変換されます。これは根底の @code{CreateProcess()} が文字列上で動作するからです。


バージョン 3.6 で変更: `args' parameter accepts a @ref{5a1,,path-like object} if `shell' is
@code{False} and a sequence containing path-like objects on POSIX.



バージョン 3.8 で変更: `args' parameter accepts a @ref{5a1,,path-like object} if `shell' is
@code{False} and a sequence containing bytes and path-like objects
on Windows.


`shell' 引数 (デフォルトでは @code{False}) は、実行するプログラムとしてシェルを使用するかどうかを指定します。 `shell' が @code{True} の場合、 `args' をシーケンスとしてではなく文字列として渡すことが推奨されます。

POSIX で @code{shell=True} の場合、シェルのデフォルトは @code{/bin/sh} になります。`args' が文字列の場合、この文字列はシェルを介して実行されるコマンドを指定します。したがって、文字列は厳密にシェルプロンプトで打つ形式と一致しなければなりません。例えば、文字列の中にスペースを含むファイル名がある場合は、クォーティングやバックスラッシュエスケープが必要です。`args' がシーケンスの場合には、最初の要素はコマンド名を表わす文字列として、残りの要素は追加の引数としてシェルに渡されます。つまり、以下の @ref{4b7,,Popen} と等価ということです:

@example
Popen(['/bin/sh', '-c', args[0], args[1], ...])
@end example

Windows で @code{shell=True} とすると、
@geindex COMSPEC
@geindex 環境変数; COMSPEC
@code{COMSPEC} 環境変数がデフォルトシェルを指定します。Windows で @code{shell=True} を指定する必要があるのは、実行したいコマンドがシェルに組み込みの場合だけです (例えば @code{dir} や @code{copy})。バッチファイルやコンソールベースの実行ファイルを実行するために @code{shell=True} は必要ありません。

@cartouche
@quotation 注釈 
@code{shell=True} を使う前に @ref{3743,,セキュリティで考慮すべき点} を読んでください。
@end quotation
@end cartouche

`bufsize' は標準入力/標準出力/標準エラー出力パイプファイルオブジェクトを生成するときに @ref{316,,open()} 関数の対応する引数に渡されます:


@itemize -

@item 
@code{0} means unbuffered (read and write are one
system call and can return short)

@item 
@code{1} means line buffered
(only usable if @code{text=True} or @code{universal_newlines=True})

@item 
それ以外の正の整数はバッファーのおよそのサイズになることを意味します。

@item 
負のサイズ (デフォルト) は io.DEFAULT_BUFFER_SIZE のシステムデフォルトが使用されることを意味します。
@end itemize


バージョン 3.3.1 で変更: `bufsize' now defaults to -1 to enable buffering by default to match the
behavior that most code expects.  In versions prior to Python 3.2.4 and
3.3.1 it incorrectly defaulted to @code{0} which was unbuffered
and allowed short reads.  This was unintentional and did not match the
behavior of Python 2 as most code expected.


`executable' 引数は、実行する置換プログラムを指定します。これが必要になるのは極めて稀です。@code{shell=False} のときは、`executable' は `args' で指定されている実行プログラムを置換します。しかし、オリジナルの `args' は依然としてプログラムに渡されます。ほとんどのプログラムは、`args' で指定されたプログラムをコマンド名として扱います。そして、それは実際に実行されたプログラムとは異なる可能性があります。POSIX において、@code{ps} のようなユーティリティの中では、`args' 名が実行ファイルの表示名になります。@code{shell=True} の場合、POSIX において `executable' 引数はデフォルトの @code{/bin/sh} に対する置換シェルを指定します。


バージョン 3.6 で変更: `executable' 引数が POSIX で @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.8 で変更: `executable' 引数が Windows で @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.12 で変更: @code{shell=True} のときのWindowsシェル検索順序を変更しました。カレントディレクトリと @code{%PATH%} は、 @code{%COMSPEC%} と @code{%SystemRoot%\System32\cmd.exe} に置き換えられました。これにより、 @code{cmd.exe} という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。


`stdin', `stdout' and `stderr' specify the executed program's standard input,
standard output and standard error file handles, respectively.  Valid values
are @code{None}, @ref{d80,,PIPE}, @ref{1366,,DEVNULL}, an existing file descriptor (a
positive integer), and an existing @ref{13db,,file object} with a valid file
descriptor.  With the default settings of @code{None}, no redirection will
occur.  @ref{d80,,PIPE} indicates that a new pipe to the child should be
created.  @ref{1366,,DEVNULL} indicates that the special file @ref{1e14,,os.devnull}
will be used.  Additionally, `stderr' can be @ref{372d,,STDOUT}, which indicates
that the stderr data from the applications should be captured into the same
file handle as for `stdout'.

`preexec_fn' に呼び出し可能オブジェクトが指定されている場合、このオブジェクトは子プロセスが実行される直前 (fork されたあと、exec される直前) に子プロセス内で呼ばれます。(POSIXのみ)

@cartouche
@quotation 警告 
アプリケーション中に複数のスレッドが存在する状態で `preexec_fn' 引数を使用するのは**安全ではありません**。exec が呼ばれる前に子プロセスがデッドロックを起こすことがあります。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
If you need to modify the environment for the child use the `env'
parameter rather than doing it in a `preexec_fn'.
The `start_new_session' and `process_group' parameters should take the place of
code using `preexec_fn' to call @ref{1dba,,os.setsid()} or @ref{301f,,os.setpgid()} in the child.
@end quotation
@end cartouche


バージョン 3.8 で変更: The `preexec_fn' parameter is no longer supported in subinterpreters.
The use of the parameter in a subinterpreter raises
@ref{244,,RuntimeError}. The new restriction may affect applications that
are deployed in mod_wsgi, uWSGI, and other embedded environments.


If `close_fds' is true, all file descriptors except @code{0}, @code{1} and
@code{2} will be closed before the child process is executed.  Otherwise
when `close_fds' is false, file descriptors obey their inheritable flag
as described in @ref{10fc,,ファイル記述子の継承}.

On Windows, if `close_fds' is true then no handles will be inherited by the
child process unless explicitly passed in the @code{handle_list} element of
@ref{e08,,STARTUPINFO.lpAttributeList}, or by standard handle redirection.


バージョン 3.2 で変更: `close_fds' のデフォルトは、@ref{d2b,,False} から上記のものに変更されました。



バージョン 3.7 で変更: On Windows the default for `close_fds' was changed from @ref{d2b,,False} to
@ref{e07,,True} when redirecting the standard handles. It's now possible to
set `close_fds' to @ref{e07,,True} when redirecting the standard handles.


`pass_fds' はオプションで、親と子の間で開いたままにしておくファイル記述子のシーケンスを指定します。何らかの `pass_fds' を渡した場合、`close_fds' は強制的に @ref{e07,,True} になります。(POSIXのみ)


バージョン 3.2 で変更: `pass_fds' 引数が追加されました。


If `cwd' is not @code{None}, the function changes the working directory to
`cwd' before executing the child.  `cwd' can be a string, bytes or
@ref{5a1,,path-like} object.  On POSIX, the function
looks for `executable' (or for the first item in `args') relative to `cwd'
if the executable path is a relative path.


バージョン 3.6 で変更: `cwd' 引数が POSIX で @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.7 で変更: `cwd' 引数が Windows で @ref{5a1,,path-like object} を受け付けるようになりました。



バージョン 3.8 で変更: `cwd' 引数が Windows で bytes オブジェクトを受け付けるようになりました。


`restore_signals' が真の場合 (デフォルト)、Python が SIG_IGN に設定したすべてのシグナルは子プロセスが exec される前に子プロセスの SIG_DFL に格納されます。現在これには SIGPIPE, SIGXFZ および SIGXFSZ シグナルが含まれています。(POSIX のみ)


バージョン 3.2 で変更: `restore_signals' が追加されました。


If `start_new_session' is true the @code{setsid()} system call will be made in the
child process prior to the execution of the subprocess.

@ref{213f,,Availability}: POSIX


バージョン 3.2 で変更: `start_new_session' が追加されました。


If `process_group' is a non-negative integer, the @code{setpgid(0, value)} system call will
be made in the child process prior to the execution of the subprocess.

@ref{213f,,Availability}: POSIX


バージョン 3.11 で変更: `process_group' was added.


If `group' is not @code{None}, the setregid() system call will be made in the
child process prior to the execution of the subprocess. If the provided
value is a string, it will be looked up via @ref{3746,,grp.getgrnam()} and
the value in @code{gr_gid} will be used. If the value is an integer, it
will be passed verbatim. (POSIX only)

@ref{213f,,Availability}: POSIX


Added in version 3.9.


If `extra_groups' is not @code{None}, the setgroups() system call will be
made in the child process prior to the execution of the subprocess.
Strings provided in `extra_groups' will be looked up via
@ref{3746,,grp.getgrnam()} and the values in @code{gr_gid} will be used.
Integer values will be passed verbatim. (POSIX only)

@ref{213f,,Availability}: POSIX


Added in version 3.9.


If `user' is not @code{None}, the setreuid() system call will be made in the
child process prior to the execution of the subprocess. If the provided
value is a string, it will be looked up via @ref{3747,,pwd.getpwnam()} and
the value in @code{pw_uid} will be used. If the value is an integer, it will
be passed verbatim. (POSIX only)

@ref{213f,,Availability}: POSIX


Added in version 3.9.


If `umask' is not negative, the umask() system call will be made in the
child process prior to the execution of the subprocess.

@ref{213f,,Availability}: POSIX


Added in version 3.9.


`env' が @code{None} 以外の場合、これは新しいプロセスでの環境変数を定義します。デフォルトでは、子プロセスは現在のプロセスの環境変数を引き継ぎます。あらゆるプラットフォームで @ref{259,,os.environ} のように文字列から文字列へ、またPOSIX プラットフォームにおいては @ref{25a,,os.environb} のようにバイトからバイトへも、定義すること出来ます。

@cartouche
@quotation 注釈 
If specified, `env' must provide any variables required for the program to
execute.  On Windows, in order to run a side-by-side assembly@footnote{https://en.wikipedia.org/wiki/Side-by-Side_Assembly} the
specified `env' `must' include a valid @code{%SystemRoot%}.
@end quotation
@end cartouche

If `encoding' or `errors' are specified, or `text' is true, the file objects
`stdin', `stdout' and `stderr' are opened in text mode with the specified
`encoding' and `errors', as described above in @ref{372c,,よく使われる引数}.
The `universal_newlines' argument is equivalent  to `text' and is provided
for backwards compatibility. By default, file objects are opened in binary mode.


Added in version 3.6: `encoding' と `errors' が追加されました。



Added in version 3.7: `text' が、`universal_newlines' のより読みやすい別名として追加されました。


If given, `startupinfo' will be a @ref{3748,,STARTUPINFO} object, which is
passed to the underlying @code{CreateProcess} function.

If given, `creationflags', can be one or more of the following flags:


@itemize *

@item 
@ref{3749,,CREATE_NEW_CONSOLE}

@item 
@ref{374a,,CREATE_NEW_PROCESS_GROUP}

@item 
@ref{374b,,ABOVE_NORMAL_PRIORITY_CLASS}

@item 
@ref{374c,,BELOW_NORMAL_PRIORITY_CLASS}

@item 
@ref{374d,,HIGH_PRIORITY_CLASS}

@item 
@ref{374e,,IDLE_PRIORITY_CLASS}

@item 
@ref{374f,,NORMAL_PRIORITY_CLASS}

@item 
@ref{3750,,REALTIME_PRIORITY_CLASS}

@item 
@ref{3751,,CREATE_NO_WINDOW}

@item 
@ref{3752,,DETACHED_PROCESS}

@item 
@ref{3753,,CREATE_DEFAULT_ERROR_MODE}

@item 
@ref{3754,,CREATE_BREAKAWAY_FROM_JOB}
@end itemize

`pipesize' can be used to change the size of the pipe when
@ref{d80,,PIPE} is used for `stdin', `stdout' or `stderr'. The size of the pipe
is only changed on platforms that support this (only Linux at this time of
writing). Other platforms will ignore this parameter.


バージョン 3.10 で変更: Added the `pipesize' parameter.


Popen オブジェクトは @ref{186,,with} 文によってコンテキストマネージャーとしてサポートされます: 終了時には標準ファイル記述子が閉じられ、プロセスを待機します:

@example
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
@end example


Popen and the other functions in this module that use it raise an
@ref{1c6e,,auditing event} @code{subprocess.Popen} with arguments
@code{executable}, @code{args}, @code{cwd}, and @code{env}. The value for @code{args}
may be a single string or a list of strings, depending on platform.



バージョン 3.2 で変更: コンテキストマネージャーサポートが追加されました。



バージョン 3.6 で変更: Popen destructor now emits a @ref{54c,,ResourceWarning} warning if the child
process is still running.



バージョン 3.8 で変更: Popen can use @ref{52e,,os.posix_spawn()} in some cases for better
performance. On Windows Subsystem for Linux and QEMU User Emulation,
Popen constructor using @ref{52e,,os.posix_spawn()} no longer raise an
exception on errors like missing program, but the child process fails
with a non-zero @ref{c83,,returncode}.

@end deffn

@node 例外<14>,,Popen コンストラクター,Using the subprocess Module
@anchor{library/subprocess exceptions}@anchor{3755}
@subsubsection 例外


Exceptions raised in the child process, before the new program has started to
execute, will be re-raised in the parent.

The most common exception raised is @ref{2c0,,OSError}.  This occurs, for example,
when trying to execute a non-existent file.  Applications should prepare for
@ref{2c0,,OSError} exceptions. Note that, when @code{shell=True}, @ref{2c0,,OSError}
will be raised by the child only if the selected shell itself was not found.
To determine if the shell failed to find the requested application, it is
necessary to check the return code or output from the subprocess.

不正な引数で @ref{4b7,,Popen} が呼ばれた場合は @ref{2ec,,ValueError} が発生します。

呼び出されたプロセスが非ゼロのリターンコードを返した場合 @ref{3739,,check_call()} や @ref{11c4,,check_output()} は @ref{153c,,CalledProcessError} を送出します。

All of the functions and methods that accept a `timeout' parameter, such as
@ref{d7f,,run()} and @ref{17aa,,Popen.communicate()} will raise @ref{17ab,,TimeoutExpired} if
the timeout expires before the process exits.

このモジュールで定義されたすべての例外は @ref{3733,,SubprocessError} を継承しています。


Added in version 3.3: @ref{3733,,SubprocessError} 基底クラスが追加されました。


@node セキュリティで考慮すべき点<2>,Popen オブジェクト,Using the subprocess Module,subprocess --- サブプロセス管理
@anchor{library/subprocess security-considerations}@anchor{3743}@anchor{library/subprocess subprocess-security}@anchor{3756}
@subsubsection セキュリティで考慮すべき点


Unlike some other popen functions, this library will not
implicitly choose to call a system shell.  This means that all characters,
including shell metacharacters, can safely be passed to child processes.
If the shell is invoked explicitly, via @code{shell=True}, it is the application's
responsibility to ensure that all whitespace and metacharacters are
quoted appropriately to avoid
shell injection@footnote{https://en.wikipedia.org/wiki/Shell_injection#Shell_injection}
vulnerabilities. On @ref{3757,,some platforms}, it is possible
to use @ref{582,,shlex.quote()} for this escaping.

On Windows, batch files (@code{*.bat} or @code{*.cmd}) may be launched by the
operating system in a system shell regardless of the arguments passed to this
library. This could result in arguments being parsed according to shell rules,
but without any escaping added by Python. If you are intentionally launching a
batch file with arguments from untrusted sources, consider passing
@code{shell=True} to allow Python to escape special characters. See gh-114539@footnote{https://github.com/python/cpython/issues/114539}
for additional discussion.

@node Popen オブジェクト,Windows Popen ヘルパー,セキュリティで考慮すべき点<2>,subprocess --- サブプロセス管理
@anchor{library/subprocess popen-objects}@anchor{3758}
@subsubsection Popen オブジェクト


@ref{4b7,,Popen} クラスのインスタンスには、以下のようなメソッドがあります:

@geindex poll() (subprocess.Popen のメソッド)
@anchor{library/subprocess subprocess Popen poll}@anchor{3759}
@deffn {メソッド} Popen.poll ()

子プロセスが終了しているかどうかを調べます。 @ref{c83,,returncode} 属性を設定して返します。そうでなければ @code{None} を返します。
@end deffn

@geindex wait() (subprocess.Popen のメソッド)
@anchor{library/subprocess subprocess Popen wait}@anchor{ee0}
@deffn {メソッド} Popen.wait (timeout=None)

子プロセスが終了するまで待ちます。@ref{c83,,returncode} 属性を設定して返します。

プロセスが `timeout' 秒後に終了してない場合、@ref{17ab,,TimeoutExpired} 例外を送出します。この例外を捕捉して wait を再試行するのは安全です。

@cartouche
@quotation 注釈 
@code{stdout=PIPE} や @code{stderr=PIPE} を使っていて、より多くのデータを受け入れるために OS のパイプバッファーをブロックしているパイプに子プロセスが十分な出力を生成した場合、デッドロックが発生します。これを避けるには @ref{17aa,,Popen.communicate()} を使用してください。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
When the @code{timeout} parameter is not @code{None}, then (on POSIX) the
function is implemented using a busy loop (non-blocking call and short
sleeps). Use the @ref{b,,asyncio} module for an asynchronous wait: see
@ref{c6b,,asyncio.create_subprocess_exec}.
@end quotation
@end cartouche


バージョン 3.3 で変更: `timeout' が追加されました

@end deffn

@geindex communicate() (subprocess.Popen のメソッド)
@anchor{library/subprocess subprocess Popen communicate}@anchor{17aa}
@deffn {メソッド} Popen.communicate (input=None, timeout=None)

Interact with process: Send data to stdin.  Read data from stdout and stderr,
until end-of-file is reached.  Wait for process to terminate and set the
@ref{c83,,returncode} attribute.  The optional `input' argument should be
data to be sent to the child process, or @code{None}, if no data should be sent
to the child.  If streams were opened in text mode, `input' must be a string.
Otherwise, it must be bytes.

@ref{17aa,,communicate()} returns a tuple @code{(stdout_data, stderr_data)}.
The data will be strings if streams were opened in text mode; otherwise,
bytes.

子プロセスの標準入力にデータを送りたい場合は、 Popen オブジェクトを @code{stdin=PIPE} と指定して作成しなければなりません。同じく、戻り値のタプルから @code{None} ではない値を取得するためには、 @code{stdout=PIPE} かつ/または @code{stderr=PIPE} を指定しなければなりません。

If the process does not terminate after `timeout' seconds, a
@ref{17ab,,TimeoutExpired} exception will be raised.  Catching this exception and
retrying communication will not lose any output.  Supplying `input' to a
subsequent post-timeout @ref{17aa,,communicate()} call is in undefined behavior
and may become an error in the future.

タイムアウトが発生した場合子プロセスは kill されません。したがって、適切にクリーンアップを行うために、正常に動作するアプリケーションは子プロセスを kill して通信を終了すべきです:

@example
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
@end example

After a call to @ref{17aa,,communicate()} raises @ref{17ab,,TimeoutExpired}, do
not call @ref{ee0,,wait()}. Use an additional @ref{17aa,,communicate()}
call to finish handling pipes and populate the @ref{c83,,returncode}
attribute.

@cartouche
@quotation 注釈 
受信したデータはメモリにバッファーされます。そのため、返されるデータが大きいかあるいは制限がないような場合はこのメソッドを使うべきではありません。
@end quotation
@end cartouche


バージョン 3.3 で変更: `timeout' が追加されました

@end deffn

@geindex send_signal() (subprocess.Popen のメソッド)
@anchor{library/subprocess subprocess Popen send_signal}@anchor{15f7}
@deffn {メソッド} Popen.send_signal (signal)

`signal' シグナルを子プロセスに送ります。

Do nothing if the process completed.

@cartouche
@quotation 注釈 
Windows では、SIGTERM は @ref{15f5,,terminate()} の別名です。CTRL_C_EVENT と CTRL_BREAK_EVENT を、@code{CREATE_NEW_PROCESS_GROUP} を含む `creationflags' で始まった、プロセスに送れます。
@end quotation
@end cartouche
@end deffn

@geindex terminate() (subprocess.Popen のメソッド)
@anchor{library/subprocess subprocess Popen terminate}@anchor{15f5}
@deffn {メソッド} Popen.terminate ()

Stop the child. On POSIX OSs the method sends @ref{15f8,,SIGTERM} to the
child. On Windows the Win32 API function @code{TerminateProcess()} is called
to stop the child.
@end deffn

@geindex kill() (subprocess.Popen のメソッド)
@anchor{library/subprocess subprocess Popen kill}@anchor{15f6}
@deffn {メソッド} Popen.kill ()

子プロセスを kill します。POSIX OS では SIGKILL シグナルを子プロセスに送ります。Windows では、@ref{15f6,,kill()} は @ref{15f5,,terminate()} の別名です。
@end deffn

The following attributes are also set by the class for you to access.
Reassigning them to new values is unsupported:

@geindex args (subprocess.Popen の属性)
@anchor{library/subprocess subprocess Popen args}@anchor{375a}
@deffn {の属性} Popen.args

@ref{4b7,,Popen} に渡された引数 `args' です -- プログラム引数のシーケンスまたは 1 個の文字列になります。


Added in version 3.3.

@end deffn

@geindex stdin (subprocess.Popen の属性)
@anchor{library/subprocess subprocess Popen stdin}@anchor{3740}
@deffn {の属性} Popen.stdin

If the `stdin' argument was @ref{d80,,PIPE}, this attribute is a writeable
stream object as returned by @ref{316,,open()}. If the `encoding' or `errors'
arguments were specified or the `text' or `universal_newlines' argument
was @code{True}, the stream is a text stream, otherwise it is a byte stream.
If the `stdin' argument was not @ref{d80,,PIPE}, this attribute is @code{None}.
@end deffn

@geindex stdout (subprocess.Popen の属性)
@anchor{library/subprocess subprocess Popen stdout}@anchor{3741}
@deffn {の属性} Popen.stdout

If the `stdout' argument was @ref{d80,,PIPE}, this attribute is a readable
stream object as returned by @ref{316,,open()}. Reading from the stream provides
output from the child process. If the `encoding' or `errors' arguments were
specified or the `text' or `universal_newlines' argument was @code{True}, the
stream is a text stream, otherwise it is a byte stream. If the `stdout'
argument was not @ref{d80,,PIPE}, this attribute is @code{None}.
@end deffn

@geindex stderr (subprocess.Popen の属性)
@anchor{library/subprocess subprocess Popen stderr}@anchor{3742}
@deffn {の属性} Popen.stderr

If the `stderr' argument was @ref{d80,,PIPE}, this attribute is a readable
stream object as returned by @ref{316,,open()}. Reading from the stream provides
error output from the child process. If the `encoding' or `errors' arguments
were specified or the `text' or `universal_newlines' argument was @code{True}, the
stream is a text stream, otherwise it is a byte stream. If the `stderr' argument
was not @ref{d80,,PIPE}, this attribute is @code{None}.
@end deffn

@cartouche
@quotation 警告 
@ref{3740,,.stdin.write}, @ref{3741,,.stdout.read}, @ref{3742,,.stderr.read} を利用すると、別のパイプの OS パイプバッファーがいっぱいになってデッドロックが発生する恐れがあります。これを避けるためには @ref{17aa,,communicate()} を利用してください。
@end quotation
@end cartouche

@geindex pid (subprocess.Popen の属性)
@anchor{library/subprocess subprocess Popen pid}@anchor{375b}
@deffn {の属性} Popen.pid

子プロセスのプロセス ID が入ります。

`shell' 引数を @code{True} に設定した場合は、生成されたシェルのプロセス ID になります。
@end deffn

@geindex returncode (subprocess.Popen の属性)
@anchor{library/subprocess subprocess Popen returncode}@anchor{c83}
@deffn {の属性} Popen.returncode

The child return code. Initially @code{None}, @ref{c83,,returncode} is set by
a call to the @ref{3759,,poll()}, @ref{ee0,,wait()}, or @ref{17aa,,communicate()} methods
if they detect that the process has terminated.

A @code{None} value indicates that the process hadn't yet terminated at the
time of the last method call.

負の値 @code{-N} は子プロセスがシグナル @code{N} により中止させられたことを示します (POSIX のみ)。
@end deffn

@node Windows Popen ヘルパー,古い高水準 API,Popen オブジェクト,subprocess --- サブプロセス管理
@anchor{library/subprocess windows-popen-helpers}@anchor{375c}
@subsubsection Windows Popen ヘルパー


@ref{3748,,STARTUPINFO} クラスと以下の定数は、Windows のみで利用できます。

@geindex STARTUPINFO (subprocess のクラス)
@anchor{library/subprocess subprocess STARTUPINFO}@anchor{3748}
@deffn {クラス} subprocess.STARTUPINFO (*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)

Partial support of the Windows
STARTUPINFO@footnote{https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx}
structure is used for @ref{4b7,,Popen} creation.  The following attributes can
be set by passing them as keyword-only arguments.


バージョン 3.7 で変更: キーワード専用引数のサポートが追加されました。


@geindex dwFlags (subprocess.STARTUPINFO の属性)
@anchor{library/subprocess subprocess STARTUPINFO dwFlags}@anchor{375d}
@deffn {の属性} dwFlags

特定の @ref{3748,,STARTUPINFO} の属性が、プロセスがウィンドウを生成するときに使われるかを決定するビットフィールドです:

@example
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
@end example
@end deffn

@geindex hStdInput (subprocess.STARTUPINFO の属性)
@anchor{library/subprocess subprocess STARTUPINFO hStdInput}@anchor{375e}
@deffn {の属性} hStdInput

@ref{375d,,dwFlags} が @ref{375f,,STARTF_USESTDHANDLES} を指定すれば、この属性がプロセスの標準入力処理です。@ref{375f,,STARTF_USESTDHANDLES} が指定されなければ、標準入力のデフォルトはキーボードバッファーです。
@end deffn

@geindex hStdOutput (subprocess.STARTUPINFO の属性)
@anchor{library/subprocess subprocess STARTUPINFO hStdOutput}@anchor{3760}
@deffn {の属性} hStdOutput

@ref{375d,,dwFlags} が @ref{375f,,STARTF_USESTDHANDLES} を指定すれば、この属性がプロセスの標準出力処理です。そうでなければ、この属性は無視され、標準出力のデフォルトはコンソールウィンドウのバッファーです。
@end deffn

@geindex hStdError (subprocess.STARTUPINFO の属性)
@anchor{library/subprocess subprocess STARTUPINFO hStdError}@anchor{3761}
@deffn {の属性} hStdError

@ref{375d,,dwFlags} が @ref{375f,,STARTF_USESTDHANDLES} を指定すれば、この属性がプロセスの標準エラー処理です。そうでなければ、この属性は無視され、標準エラー出力のデフォルトはコンソールウィンドウのバッファーです。
@end deffn

@geindex wShowWindow (subprocess.STARTUPINFO の属性)
@anchor{library/subprocess subprocess STARTUPINFO wShowWindow}@anchor{3762}
@deffn {の属性} wShowWindow

@ref{375d,,dwFlags} が @ref{3763,,STARTF_USESHOWWINDOW} を指定すれば、この属性は ShowWindow@footnote{https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx} 関数の @code{nCmdShow} 引数で指定された値なら、 @code{SW_SHOWDEFAULT} 以外の任意のものにできます。しかし、この属性は無視されます。

この属性には @ref{3764,,SW_HIDE} が提供されています。これは、@ref{4b7,,Popen} が @code{shell=True} として呼び出されたときに使われます。
@end deffn

@geindex lpAttributeList (subprocess.STARTUPINFO の属性)
@anchor{library/subprocess subprocess STARTUPINFO lpAttributeList}@anchor{e08}
@deffn {の属性} lpAttributeList

A dictionary of additional attributes for process creation as given in
@code{STARTUPINFOEX}, see
UpdateProcThreadAttribute@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx}.

Supported attributes:


@table @asis

@item `handle_list'

Sequence of handles that will be inherited. `close_fds' must be true if
non-empty.

The handles must be temporarily made inheritable by
@ref{1100,,os.set_handle_inheritable()} when passed to the @ref{4b7,,Popen}
constructor, else @ref{2c0,,OSError} will be raised with Windows error
@code{ERROR_INVALID_PARAMETER} (87).

@cartouche
@quotation 警告 
In a multithreaded process, use caution to avoid leaking handles
that are marked inheritable when combining this feature with
concurrent calls to other process creation functions that inherit
all handles such as @ref{1676,,os.system()}.  This also applies to
standard handle redirection, which temporarily creates inheritable
handles.
@end quotation
@end cartouche
@end table


Added in version 3.7.

@end deffn
@end deffn

@menu
* Windows Constants:: 

@end menu

@node Windows Constants,,,Windows Popen ヘルパー
@anchor{library/subprocess windows-constants}@anchor{3765}
@subsubsection Windows Constants


The @code{subprocess} module exposes the following constants.

@geindex STD_INPUT_HANDLE (subprocess モジュール)
@anchor{library/subprocess subprocess STD_INPUT_HANDLE}@anchor{3766}
@deffn {データ} subprocess.STD_INPUT_HANDLE

標準入力デバイスです。この初期値は、コンソール入力バッファ、 @code{CONIN$} です。
@end deffn

@geindex STD_OUTPUT_HANDLE (subprocess モジュール)
@anchor{library/subprocess subprocess STD_OUTPUT_HANDLE}@anchor{3767}
@deffn {データ} subprocess.STD_OUTPUT_HANDLE

標準出力デバイスです。この初期値は、アクティブコンソールスクリーン、 @code{CONOUT$} です。
@end deffn

@geindex STD_ERROR_HANDLE (subprocess モジュール)
@anchor{library/subprocess subprocess STD_ERROR_HANDLE}@anchor{3768}
@deffn {データ} subprocess.STD_ERROR_HANDLE

標準エラーデバイスです。この初期値は、アクティブコンソールスクリーン、 @code{CONOUT$} です。
@end deffn

@geindex SW_HIDE (subprocess モジュール)
@anchor{library/subprocess subprocess SW_HIDE}@anchor{3764}
@deffn {データ} subprocess.SW_HIDE

ウィンドウを隠します。別のウィンドウがアクティブになります。
@end deffn

@geindex STARTF_USESTDHANDLES (subprocess モジュール)
@anchor{library/subprocess subprocess STARTF_USESTDHANDLES}@anchor{375f}
@deffn {データ} subprocess.STARTF_USESTDHANDLES

追加情報を保持する、@ref{375e,,STARTUPINFO.hStdInput}, @ref{3760,,STARTUPINFO.hStdOutput}, および @ref{3761,,STARTUPINFO.hStdError} 属性を指定します。
@end deffn

@geindex STARTF_USESHOWWINDOW (subprocess モジュール)
@anchor{library/subprocess subprocess STARTF_USESHOWWINDOW}@anchor{3763}
@deffn {データ} subprocess.STARTF_USESHOWWINDOW

追加情報を保持する、 @ref{3762,,STARTUPINFO.wShowWindow} 属性を指定します。
@end deffn

@geindex STARTF_FORCEONFEEDBACK (subprocess モジュール)
@anchor{library/subprocess subprocess STARTF_FORCEONFEEDBACK}@anchor{3769}
@deffn {データ} subprocess.STARTF_FORCEONFEEDBACK

A @ref{375d,,STARTUPINFO.dwFlags} parameter to specify that the
`Working in Background' mouse cursor will be displayed while a
process is launching. This is the default behavior for GUI
processes.


Added in version 3.13.

@end deffn

@geindex STARTF_FORCEOFFFEEDBACK (subprocess モジュール)
@anchor{library/subprocess subprocess STARTF_FORCEOFFFEEDBACK}@anchor{376a}
@deffn {データ} subprocess.STARTF_FORCEOFFFEEDBACK

A @ref{375d,,STARTUPINFO.dwFlags} parameter to specify that the mouse
cursor will not be changed when launching a process.


Added in version 3.13.

@end deffn

@geindex CREATE_NEW_CONSOLE (subprocess モジュール)
@anchor{library/subprocess subprocess CREATE_NEW_CONSOLE}@anchor{3749}
@deffn {データ} subprocess.CREATE_NEW_CONSOLE

新しいプロセスが、親プロセスのコンソールを継承する (デフォルト) のではなく、新しいコンソールを持ちます。
@end deffn

@geindex CREATE_NEW_PROCESS_GROUP (subprocess モジュール)
@anchor{library/subprocess subprocess CREATE_NEW_PROCESS_GROUP}@anchor{374a}
@deffn {データ} subprocess.CREATE_NEW_PROCESS_GROUP

新しいプロセスグループが生成されることを指定する @ref{4b7,,Popen} @code{creationflags} パラメーターです。このフラグは、サブプロセスで @ref{157f,,os.kill()} を使うのに必要です。

@ref{3749,,CREATE_NEW_CONSOLE} が指定されていたら、このフラグは無視されます。
@end deffn

@geindex ABOVE_NORMAL_PRIORITY_CLASS (subprocess モジュール)
@anchor{library/subprocess subprocess ABOVE_NORMAL_PRIORITY_CLASS}@anchor{374b}
@deffn {データ} subprocess.ABOVE_NORMAL_PRIORITY_CLASS

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will have an above average priority.


Added in version 3.7.

@end deffn

@geindex BELOW_NORMAL_PRIORITY_CLASS (subprocess モジュール)
@anchor{library/subprocess subprocess BELOW_NORMAL_PRIORITY_CLASS}@anchor{374c}
@deffn {データ} subprocess.BELOW_NORMAL_PRIORITY_CLASS

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will have a below average priority.


Added in version 3.7.

@end deffn

@geindex HIGH_PRIORITY_CLASS (subprocess モジュール)
@anchor{library/subprocess subprocess HIGH_PRIORITY_CLASS}@anchor{374d}
@deffn {データ} subprocess.HIGH_PRIORITY_CLASS

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will have a high priority.


Added in version 3.7.

@end deffn

@geindex IDLE_PRIORITY_CLASS (subprocess モジュール)
@anchor{library/subprocess subprocess IDLE_PRIORITY_CLASS}@anchor{374e}
@deffn {データ} subprocess.IDLE_PRIORITY_CLASS

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will have an idle (lowest) priority.


Added in version 3.7.

@end deffn

@geindex NORMAL_PRIORITY_CLASS (subprocess モジュール)
@anchor{library/subprocess subprocess NORMAL_PRIORITY_CLASS}@anchor{374f}
@deffn {データ} subprocess.NORMAL_PRIORITY_CLASS

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will have a normal priority. (default)


Added in version 3.7.

@end deffn

@geindex REALTIME_PRIORITY_CLASS (subprocess モジュール)
@anchor{library/subprocess subprocess REALTIME_PRIORITY_CLASS}@anchor{3750}
@deffn {データ} subprocess.REALTIME_PRIORITY_CLASS

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will have realtime priority.
You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts
system threads that manage mouse input, keyboard input, and background disk
flushing. This class can be appropriate for applications that "talk" directly
to hardware or that perform brief tasks that should have limited interruptions.


Added in version 3.7.

@end deffn

@geindex CREATE_NO_WINDOW (subprocess モジュール)
@anchor{library/subprocess subprocess CREATE_NO_WINDOW}@anchor{3751}
@deffn {データ} subprocess.CREATE_NO_WINDOW

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will not create a window.


Added in version 3.7.

@end deffn

@geindex DETACHED_PROCESS (subprocess モジュール)
@anchor{library/subprocess subprocess DETACHED_PROCESS}@anchor{3752}
@deffn {データ} subprocess.DETACHED_PROCESS

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
will not inherit its parent's console.
This value cannot be used with CREATE_NEW_CONSOLE.


Added in version 3.7.

@end deffn

@geindex CREATE_DEFAULT_ERROR_MODE (subprocess モジュール)
@anchor{library/subprocess subprocess CREATE_DEFAULT_ERROR_MODE}@anchor{3753}
@deffn {データ} subprocess.CREATE_DEFAULT_ERROR_MODE

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
does not inherit the error mode of the calling process. Instead, the new
process gets the default error mode.
This feature is particularly useful for multithreaded shell applications
that run with hard errors disabled.


Added in version 3.7.

@end deffn

@geindex CREATE_BREAKAWAY_FROM_JOB (subprocess モジュール)
@anchor{library/subprocess subprocess CREATE_BREAKAWAY_FROM_JOB}@anchor{3754}
@deffn {データ} subprocess.CREATE_BREAKAWAY_FROM_JOB

A @ref{4b7,,Popen} @code{creationflags} parameter to specify that a new process
is not associated with the job.


Added in version 3.7.

@end deffn

@node 古い高水準 API,Replacing Older Functions with the subprocess Module,Windows Popen ヘルパー,subprocess --- サブプロセス管理
@anchor{library/subprocess call-function-trio}@anchor{376b}@anchor{library/subprocess older-high-level-api}@anchor{376c}
@subsubsection 古い高水準 API


Python 3.5 より前のバージョンでは、サブプロセスに対して以下の 3 つの関数からなる高水準 API が用意されていました。現在多くの場合 @ref{d7f,,run()} の使用で済みますが、既存の多くのコードではこれらの関数が使用されています。

@geindex call() (subprocess モジュール)
@anchor{library/subprocess subprocess call}@anchor{d81}
@deffn {の関数} subprocess.call (args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

`args' で指定されたコマンドを実行します。コマンドの終了を待ち、@ref{c83,,returncode} 属性を返します。

Code needing to capture stdout or stderr should use @ref{d7f,,run()} instead:

@example
run(...).returncode
@end example

To suppress stdout or stderr, supply a value of @ref{1366,,DEVNULL}.

上記の引数は、よく使われるものだけ示しています。関数の全使用法は @ref{4b7,,Popen} コンストラクターの内容と同じになります -  この関数は、このインターフェースに直接指定される `timeout' 以外は与えられた全引数を渡します。

@cartouche
@quotation 注釈 
この関数を使用する際は @code{stdout=PIPE} および @code{stderr=PIPE} を使用しないでください。子プロセスが OS のパイプバッファーを埋めてしまうほどの出力データを生成した場合、パイプからは読み込まれないので、子プロセスがブロックされることがあります。
@end quotation
@end cartouche


バージョン 3.3 で変更: `timeout' が追加されました



バージョン 3.12 で変更: @code{shell=True} のときのWindowsシェル検索順序を変更しました。カレントディレクトリと @code{%PATH%} は、 @code{%COMSPEC%} と @code{%SystemRoot%\System32\cmd.exe} に置き換えられました。これにより、 @code{cmd.exe} という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

@end deffn

@geindex check_call() (subprocess モジュール)
@anchor{library/subprocess subprocess check_call}@anchor{3739}
@deffn {の関数} 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 @ref{153c,,CalledProcessError}. The
@ref{153c,,CalledProcessError} object will have the return code in the
@ref{373a,,returncode} attribute.
If @ref{3739,,check_call()} was unable to start the process it will propagate the exception
that was raised.

Code needing to capture stdout or stderr should use @ref{d7f,,run()} instead:

@example
run(..., check=True)
@end example

To suppress stdout or stderr, supply a value of @ref{1366,,DEVNULL}.

上記の引数は、よく使われるものだけ示しています。関数の全使用法は @ref{4b7,,Popen} コンストラクターの内容と同じになります -  この関数は、このインターフェースに直接指定される `timeout' 以外は与えられた全引数を渡します。

@cartouche
@quotation 注釈 
この関数を使用する際は @code{stdout=PIPE} および @code{stderr=PIPE} を使用しないでください。子プロセスが OS のパイプバッファーを埋めてしまうほどの出力データを生成した場合、パイプからは読み込まれないので、子プロセスがブロックされることがあります。
@end quotation
@end cartouche


バージョン 3.3 で変更: `timeout' が追加されました



バージョン 3.12 で変更: @code{shell=True} のときのWindowsシェル検索順序を変更しました。カレントディレクトリと @code{%PATH%} は、 @code{%COMSPEC%} と @code{%SystemRoot%\System32\cmd.exe} に置き換えられました。これにより、 @code{cmd.exe} という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

@end deffn

@geindex check_output() (subprocess モジュール)
@anchor{library/subprocess subprocess check_output}@anchor{11c4}
@deffn {の関数} subprocess.check_output (args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

引数でコマンドを実行し、その出力を返します。

コマンドのリターンコードが非ゼロならば @ref{153c,,CalledProcessError} 例外が送出されます。@ref{153c,,CalledProcessError} オブジェクトには、リターンコードが @ref{373a,,returncode} 属性に、コマンドからの出力が @ref{373c,,output} 属性に、それぞれ格納されています。

これは次と等価です:

@example
run(..., check=True, stdout=PIPE).stdout
@end example

The arguments shown above are merely some common ones.
The full function signature is largely the same as that of @ref{d7f,,run()} -
most arguments are passed directly through to that interface.
One API deviation from @ref{d7f,,run()} behavior exists: passing @code{input=None}
will behave the same as @code{input=b'@w{'}} (or @code{input='@w{'}}, depending on other
arguments) rather than using the parent's standard input file handle.

デフォルトで、この関数はデータをエンコードされたバイトとして返します。出力されたデータの実際のエンコードは起動されているコマンドに依存するため、テキストへのデコードは通常アプリケーションレベルで扱う必要があります。

This behaviour may be overridden by setting `text', `encoding', `errors',
or `universal_newlines' to @code{True} as described in
@ref{372c,,よく使われる引数} and @ref{d7f,,run()}.

標準エラー出力も結果に含めるには、@code{stderr=subprocess.STDOUT} を使います:

@example
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
@end example


Added in version 3.1.



バージョン 3.3 で変更: `timeout' が追加されました



バージョン 3.4 で変更: キーワード引数 `input' が追加されました。



バージョン 3.6 で変更: `encoding' and `errors' were added.  See @ref{d7f,,run()} for details.



Added in version 3.7: `text' が、`universal_newlines' のより読みやすい別名として追加されました。



バージョン 3.12 で変更: @code{shell=True} のときのWindowsシェル検索順序を変更しました。カレントディレクトリと @code{%PATH%} は、 @code{%COMSPEC%} と @code{%SystemRoot%\System32\cmd.exe} に置き換えられました。これにより、 @code{cmd.exe} という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

@end deffn

@node Replacing Older Functions with the subprocess Module,レガシーなシェル呼び出し関数,古い高水準 API,subprocess --- サブプロセス管理
@anchor{library/subprocess replacing-older-functions-with-the-subprocess-module}@anchor{376d}@anchor{library/subprocess subprocess-replacements}@anchor{13a0}
@subsubsection Replacing Older Functions with the @code{subprocess} Module


この節では、 "a becomes b" と書かれているものは a の代替として b が使えるということを表します。

@cartouche
@quotation 注釈 
この節で紹介されている "a" 関数は全て、実行するプログラムが見つからないときは (おおむね) 静かに終了します。それに対して "b" 代替手段は @ref{2c0,,OSError} 例外を送出します。

また、要求された操作が非ゼロの終了コードを返した場合、@ref{11c4,,check_output()} を使用した置き換えは @ref{153c,,CalledProcessError} で失敗します。その出力は、送出された例外の @ref{373c,,output} 属性として利用可能です。
@end quotation
@end cartouche

In the following examples, we assume that the relevant functions have already
been imported from the @code{subprocess} module.

@menu
* Replacing /bin/sh shell command substitution:: 
* シェルのパイプラインを置き換える:: 
* os.system() を置き換える: os system を置き換える. 
* os.spawn 関数群を置き換える: os spawn 関数群を置き換える. 
* Replacing os.popen(): Replacing os popen. 

@end menu

@node Replacing /bin/sh shell command substitution,シェルのパイプラインを置き換える,,Replacing Older Functions with the subprocess Module
@anchor{library/subprocess replacing-bin-sh-shell-command-substitution}@anchor{376e}
@subsubsection Replacing @code{/bin/sh} shell command substitution


@example
output=$(mycmd myarg)
@end example

これは以下のようになります:

@example
output = check_output(["mycmd", "myarg"])
@end example

@node シェルのパイプラインを置き換える,os system を置き換える,Replacing /bin/sh shell command substitution,Replacing Older Functions with the subprocess Module
@anchor{library/subprocess replacing-shell-pipeline}@anchor{376f}
@subsubsection シェルのパイプラインを置き換える


@example
output=$(dmesg | grep hda)
@end example

これは以下のようになります:

@example
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
@end example

p2 を開始した後の @code{p1.stdout.close()} の呼び出しは、p1 が p2 の前に存在した場合に、p1 が SIGPIPE を受け取るために重要です。

あるいは、信頼された入力に対しては、シェル自身のパイプラインサポートを直接使用することもできます:

@example
output=$(dmesg | grep hda)
@end example

これは以下のようになります:

@example
output = check_output("dmesg | grep hda", shell=True)
@end example

@node os system を置き換える,os spawn 関数群を置き換える,シェルのパイプラインを置き換える,Replacing Older Functions with the subprocess Module
@anchor{library/subprocess replacing-os-system}@anchor{3770}
@subsubsection @code{os.system()} を置き換える


@example
sts = os.system("mycmd" + " myarg")
# becomes
retcode = call("mycmd" + " myarg", shell=True)
@end example

注釈:


@itemize *

@item 
このプログラムは普通シェル経由で呼び出す必要はありません。

@item 
The @ref{d81,,call()} return value is encoded differently to that of
@ref{1676,,os.system()}.

@item 
The @ref{1676,,os.system()} function ignores SIGINT and SIGQUIT signals while
the command is running, but the caller must do this separately when
using the @code{subprocess} module.
@end itemize

より現実的な例ではこうなるでしょう:

@example
try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode, file=sys.stderr)
    else:
        print("Child returned", retcode, file=sys.stderr)
except OSError as e:
    print("Execution failed:", e, file=sys.stderr)
@end example

@node os spawn 関数群を置き換える,Replacing os popen,os system を置き換える,Replacing Older Functions with the subprocess Module
@anchor{library/subprocess replacing-the-os-spawn-family}@anchor{3771}
@subsubsection @code{os.spawn} 関数群を置き換える


P_NOWAIT の例:

@example
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
@end example

P_WAIT の例:

@example
retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])
@end example

シーケンスを使った例:

@example
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])
@end example

環境変数を使った例:

@example
os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env=@{"PATH": "/usr/bin"@})
@end example

@node Replacing os popen,,os spawn 関数群を置き換える,Replacing Older Functions with the subprocess Module
@anchor{library/subprocess replacing-os-popen}@anchor{3772}
@subsubsection Replacing @code{os.popen()}


終了コードハンドリングは以下のように解釈します:

@example
pipe = os.popen(cmd, 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
    print("There were some errors")
==>
process = Popen(cmd, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
    print("There were some errors")
@end example

@node レガシーなシェル呼び出し関数,注釈<2>,Replacing Older Functions with the subprocess Module,subprocess --- サブプロセス管理
@anchor{library/subprocess legacy-shell-invocation-functions}@anchor{3773}
@subsubsection レガシーなシェル呼び出し関数


このモジュールでは、以下のような 2.x @code{commands} モジュールからのレガシー関数も提供しています。これらの操作は、暗黙的にシステムシェルを起動します。また、セキュリティに関して上述した保証や例外処理一貫性は、これらの関数では有効ではありません。

@geindex getstatusoutput() (subprocess モジュール)
@anchor{library/subprocess subprocess getstatusoutput}@anchor{11c6}
@deffn {の関数} subprocess.getstatusoutput (cmd, *, encoding=None, errors=None)

シェル中の `cmd' を実行して @code{(exitcode, output)} を返します。

Execute the string `cmd' in a shell with @ref{11c4,,check_output()} and
return a 2-tuple @code{(exitcode, output)}.
`encoding' and `errors' are used to decode output;
see the notes on @ref{372c,,よく使われる引数} for more details.

A trailing newline is stripped from the output.
The exit code for the command can be interpreted as the return code
of subprocess.  Example:

@example
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> subprocess.getstatusoutput('cat /bin/junk')
(1, 'cat: /bin/junk: No such file or directory')
>>> subprocess.getstatusoutput('/bin/junk')
(127, 'sh: /bin/junk: not found')
>>> subprocess.getstatusoutput('/bin/kill $$')
(-15, '@w{'})
@end example

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.3.4 で変更: Windows のサポートが追加されました。

The function now returns (exitcode, output) instead of (status, output)
as it did in Python 3.3.3 and earlier.  exitcode has the same value as
@ref{c83,,returncode}.



バージョン 3.11 で変更: `encoding' と `errors' が引数に追加されました。

@end deffn

@geindex getoutput() (subprocess モジュール)
@anchor{library/subprocess subprocess getoutput}@anchor{11c5}
@deffn {の関数} subprocess.getoutput (cmd, *, encoding=None, errors=None)

シェル中の `cmd' を実行して出力 (stdout と stderr) を返します。

@ref{11c6,,getstatusoutput()} に似ていますが、終了コードは無視され、コマンドの出力のみを返します。例えば:

@example
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'
@end example

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.3.4 で変更: Windowsで利用可能になりました



バージョン 3.11 で変更: `encoding' と `errors' が引数に追加されました。

@end deffn

@node 注釈<2>,,レガシーなシェル呼び出し関数,subprocess --- サブプロセス管理
@anchor{library/subprocess notes}@anchor{3774}
@subsubsection 注釈


@menu
* Timeout Behavior:: 
* Windows における引数シーケンスから文字列への変換:: 
* Disable use of posix_spawn(): Disable use of posix_spawn. 

@end menu

@node Timeout Behavior,Windows における引数シーケンスから文字列への変換,,注釈<2>
@anchor{library/subprocess subprocess-timeout-behavior}@anchor{3775}@anchor{library/subprocess timeout-behavior}@anchor{3776}
@subsubsection Timeout Behavior


When using the @code{timeout} parameter in functions like @ref{d7f,,run()},
@ref{ee0,,Popen.wait()}, or @ref{17aa,,Popen.communicate()},
users should be aware of the following behaviors:


@enumerate 

@item 
`Process Creation Delay': The initial process creation itself cannot be interrupted
on many platform APIs. This means that even when specifying a timeout, you are not
guaranteed to see a timeout exception until at least after however long process
creation takes.

@item 
`Extremely Small Timeout Values': Setting very small timeout values (such as a few
milliseconds) may result in almost immediate @ref{17ab,,TimeoutExpired} exceptions because
process creation and system scheduling inherently require time.
@end enumerate

@node Windows における引数シーケンスから文字列への変換,Disable use of posix_spawn,Timeout Behavior,注釈<2>
@anchor{library/subprocess converting-an-argument-sequence-to-a-string-on-windows}@anchor{3777}@anchor{library/subprocess converting-argument-sequence}@anchor{3745}
@subsubsection Windows における引数シーケンスから文字列への変換


Windows では、 `args' シーケンスは以下の (MS C ランタイムで使われる規則に対応する) 規則を使って解析できる文字列に変換されます:


@enumerate 

@item 
引数は、スペースかタブのどちらかの空白で分けられます。

@item 
ダブルクオーテーションマークで囲まれた文字列は、空白が含まれていたとしても 1 つの引数として解釈されます。クオートされた文字列は引数に埋め込めます。

@item 
バックスラッシュに続くダブルクオーテーションマークは、リテラルのダブルクオーテーションマークと解釈されます。

@item 
バックスラッシュは、ダブルクオーテーションが続かない限り、リテラルとして解釈されます。

@item 
複数のバックスラッシュにダブルクオーテーションマークが続くなら、バックスラッシュ 2 つで 1 つのバックスラッシュ文字と解釈されます。バックスラッシュの数が奇数なら、最後のバックスラッシュは規則 3 に従って続くダブルクオーテーションマークをエスケープします。
@end enumerate


@subsubheading 参考



@table @asis

@item @ref{c9,,shlex}

コマンドラインを解析したりエスケープしたりする関数を提供するモジュール。
@end table


@node Disable use of posix_spawn,,Windows における引数シーケンスから文字列への変換,注釈<2>
@anchor{library/subprocess disable-posix-spawn}@anchor{3778}@anchor{library/subprocess disable-use-of-posix-spawn}@anchor{3779}
@subsubsection Disable use of @code{posix_spawn()}


On Linux, @code{subprocess} defaults to using the @code{vfork()} system call
internally when it is safe to do so rather than @code{fork()}. This greatly
improves performance.

@example
subprocess._USE_POSIX_SPAWN = False  # See CPython issue gh-NNNNNN.
@end example

It is safe to set this to false on any Python version. It will have no
effect on older or newer versions where unsupported. Do not assume the attribute
is available to read. Despite the name, a true value does not indicate the
corresponding function will be used, only that it may be.

Please file issues any time you have to use these private knobs with a way to
reproduce the issue you were seeing. Link to that issue from a comment in your
code.


Added in version 3.8: @code{_USE_POSIX_SPAWN}


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node sched --- イベントスケジューラー,queue --- 同期キュークラス,subprocess --- サブプロセス管理,並行実行
@anchor{library/sched doc}@anchor{377a}@anchor{library/sched module-sched}@anchor{c4}@anchor{library/sched sched-event-scheduler}@anchor{377b}@anchor{library/sched translation-repo}@anchor{377c}
@subsection @code{sched} --- イベントスケジューラー


@geindex module; sched

`ソースコード:' Lib/sched.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/sched.py}

@geindex イベントスケジューリング


__________________________________________________________________


The @code{sched} module defines a class which implements a general purpose event
scheduler:

@geindex scheduler (sched のクラス)
@anchor{library/sched sched scheduler}@anchor{133f}
@deffn {クラス} sched.scheduler (timefunc=time.monotonic, delayfunc=time.sleep)

@ref{133f,,scheduler} クラスはイベントをスケジュールするための一般的なインターフェースを定義します。それは "外の世界" を実際に扱うための2つの関数を必要とします --- `timefunc' は引数なしで呼ばれて 1 つの数値を返す callable オブジェクトでなければなりません (戻り値は任意の単位で「時間」を表します)。 `delayfunc' は 1 つの引数を持つ callable オブジェクトでなければならず、その時間だけ遅延する必要があります (引数は `timefunc' の出力と互換)。 `delayfunc' は、各々のイベントが実行された後に引数 @code{0} で呼ばれることがあります。これは、マルチスレッドアプリケーションの中で他のスレッドが実行する機会を与えるためです。


バージョン 3.3 で変更: `timefunc' と `delayfunc' がオプション引数になりました。



バージョン 3.3 で変更: @ref{133f,,scheduler} クラスをマルチスレッド環境で安全に使用出来るようになりました。

@end deffn

以下はプログラム例です:

@example
>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(a='default'):
...     print("From print_time", time.time(), a)
...
>>> def print_some_times():
...     print(time.time())
...     s.enter(10, 1, print_time)
...     s.enter(5, 2, print_time, argument=('positional',))
...     # despite having higher priority, 'keyword' runs after 'positional' as enter() is relative
...     s.enter(5, 1, print_time, kwargs=@{'a': 'keyword'@})
...     s.enterabs(1_650_000_000, 10, print_time, argument=("first enterabs",))
...     s.enterabs(1_650_000_000, 5, print_time, argument=("second enterabs",))
...     s.run()
...     print(time.time())
...
>>> print_some_times()
1652342830.3640375
From print_time 1652342830.3642538 second enterabs
From print_time 1652342830.3643398 first enterabs
From print_time 1652342835.3694863 positional
From print_time 1652342835.3696074 keyword
From print_time 1652342840.369612 default
1652342840.3697174
@end example

@menu
* スケジューラオブジェクト:: 

@end menu

@node スケジューラオブジェクト,,,sched --- イベントスケジューラー
@anchor{library/sched id1}@anchor{377d}@anchor{library/sched scheduler-objects}@anchor{377e}
@subsubsection スケジューラオブジェクト


@ref{133f,,scheduler} インスタンスは以下のメソッドと属性を持っています:

@geindex enterabs() (sched.scheduler のメソッド)
@anchor{library/sched sched scheduler enterabs}@anchor{1341}
@deffn {メソッド} scheduler.enterabs (time, priority, action, argument=(), kwargs=@{@})

新しいイベントをスケジュールします。
引数 `time' は、コンストラクタへ渡された `timefunc' の戻り値と互換な数値型でなければいけません。
同じ `time' によってスケジュールされたイベントは、それらの `priority' によって実行されます。
数値の小さい方が高い優先度となります。

イベントを実行することは、 @code{action(*argument, **kwargs)} を実行することを意味します。 `argument' は `action' のための位置引数を保持するシーケンスでなければいけません。 `kwargs' は `action' のためのキーワード引数を保持する辞書でなければいけません。

戻り値は、後にイベントをキャンセルする時に使われる可能性のあるイベントです (@ref{1cfb,,cancel()} を参照)。


バージョン 3.3 で変更: `argument' 引数が任意になりました。



バージョン 3.3 で変更: `kwargs' 引数が追加されました。

@end deffn

@geindex enter() (sched.scheduler のメソッド)
@anchor{library/sched sched scheduler enter}@anchor{1340}
@deffn {メソッド} scheduler.enter (delay, priority, action, argument=(), kwargs=@{@})

時間単位以上の `delay' でイベントをスケジュールします。相対的時間以外の、引数、効果、戻り値は、 @ref{1341,,enterabs()} に対するものと同じです。


バージョン 3.3 で変更: `argument' 引数が任意になりました。



バージョン 3.3 で変更: `kwargs' 引数が追加されました。

@end deffn

@geindex cancel() (sched.scheduler のメソッド)
@anchor{library/sched sched scheduler cancel}@anchor{1cfb}
@deffn {メソッド} scheduler.cancel (event)

キューからイベントを消去します。もし `event' がキューにある現在のイベントでないならば、このメソッドは @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex empty() (sched.scheduler のメソッド)
@anchor{library/sched sched scheduler empty}@anchor{377f}
@deffn {メソッド} scheduler.empty ()

もしイベントキューが空ならば、 @code{True} を返します。
@end deffn

@geindex run() (sched.scheduler のメソッド)
@anchor{library/sched sched scheduler run}@anchor{133e}
@deffn {メソッド} scheduler.run (blocking=True)

すべてのスケジュールされたイベントを実行します。このメソッドは次のイベントを待ち、それを実行し、スケジュールされたイベントがなくなるまで同じことを繰り返します。(イベントの待機は、 コンストラクタへ渡された関数 `delayfunc' を使うことで行います。)

`blocking' が False の場合、最も早く期限が来るスケジュールされたイベントを (存在する場合) 実行し、スケジューラ内で次にスケジュールされた呼び出しの期限を (存在する場合) 返します。

`action' あるいは `delayfunc' は例外を投げることができます。いずれの場合も、スケジューラは一貫した状態を維持し、例外を伝播するでしょう。例外が `action' によって投げられる場合、イベントは @ref{133e,,run()} への呼出しを未来に行なわないでしょう。

イベントのシーケンスが、次イベントの前に、利用可能時間より実行時間が長いと、スケジューラは単に遅れることになるでしょう。イベントが落ちることはありません; 呼出しコードはもはや適切でないキャンセルイベントに対して責任があります。


バージョン 3.3 で変更: `blocking' 引数が追加されました。

@end deffn

@geindex queue (sched.scheduler の属性)
@anchor{library/sched sched scheduler queue}@anchor{3780}
@deffn {の属性} scheduler.queue

読み出し専用の属性で、これから起こるイベントが実行される順序で格納されたリストを返します。各イベントは、次の属性 time, priority, action, argument, kwargs を持った @ref{85e,,named tuple} の形式になります。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node queue --- 同期キュークラス,contextvars --- コンテキスト変数,sched --- イベントスケジューラー,並行実行
@anchor{library/queue doc}@anchor{3781}@anchor{library/queue module-queue}@anchor{bb}@anchor{library/queue queue-a-synchronized-queue-class}@anchor{3782}@anchor{library/queue translation-repo}@anchor{3783}
@subsection @code{queue} --- 同期キュークラス


@geindex module; queue

`ソースコード:' Lib/queue.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/queue.py}


__________________________________________________________________


The @code{queue} module implements multi-producer, multi-consumer queues.
It is especially useful in threaded programming when information must be
exchanged safely between multiple threads.  The @ref{15ac,,Queue} class in this
module implements all the required locking semantics.

このモジュールでは3種類のキューが実装されています。それらはキューから取り出されるエントリの順番だけが違います。 @abbr{FIFO} キューでは、最初に追加されたエントリが最初に取り出されます。  @abbr{LIFO} キューでは、最後に追加されたエントリが最初に取り出されます(スタックのように振る舞います)。 優先順位付きキュー(priority queue)では、エントリは(@ref{6d,,heapq} モジュールを利用して)ソートされ、 最も低い値のエントリが最初に取り出されます。

内部的には、これらの3種類のキューは競争スレッドを一時的にブロックするためにロックを使っています; しかし、スレッド内での再入を扱うようには設計されていません。

In addition, the module implements a "simple"
@abbr{FIFO} queue type, @ref{d61,,SimpleQueue}, whose
specific implementation provides additional guarantees
in exchange for the smaller functionality.

The @code{queue} module defines the following classes and exceptions:

@geindex Queue (queue のクラス)
@anchor{library/queue queue Queue}@anchor{15ac}
@deffn {クラス} queue.Queue (maxsize=0)

@abbr{FIFO} キューのコンストラクタです。
`maxsize' はキューに入れられる要素数の上限を設定する整数です。
いったんこの大きさに達したら、挿入処理はキューの要素が消費されるまでブロックされます。
`maxsize' が0以下の場合は、キューの大きさは無限です。
@end deffn

@geindex LifoQueue (queue のクラス)
@anchor{library/queue queue LifoQueue}@anchor{26b6}
@deffn {クラス} queue.LifoQueue (maxsize=0)

@abbr{LIFO} キューのコンストラクタです。
`maxsize' はキューに入れられる要素数の上限を設定する整数です。
いったんこの大きさに達したら、挿入処理はキューの要素が消費されるまでブロックされます。
`maxsize' が0以下の場合は、キューの大きさは無限です。
@end deffn

@geindex PriorityQueue (queue のクラス)
@anchor{library/queue queue PriorityQueue}@anchor{26b7}
@deffn {クラス} queue.PriorityQueue (maxsize=0)

優先順位付きキューのコンストラクタです。`maxsize' はキューに置くことのできる要素数の上限を設定する整数です。いったんこの大きさに達したら、挿入はキューの要素が消費されるまでブロックされます。もし `maxsize' が0以下であるならば、キューの大きさは無限です。

最小の値を持つ要素が最初に検索されます (最小の値を持つ値は、@code{min(entries)} によって返されるものです)。典型的な要素のパターンは、@code{(priority_number, data)} 形式のタプルです。

If the `data' elements are not comparable, the data can be wrapped in a class
that ignores the data item and only compares the priority number:

@example
from dataclasses import dataclass, field
from typing import Any

@@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)
@end example
@end deffn

@geindex SimpleQueue (queue のクラス)
@anchor{library/queue queue SimpleQueue}@anchor{d61}
@deffn {クラス} queue.SimpleQueue

Constructor for an unbounded @abbr{FIFO} queue.
Simple queues lack advanced functionality such as task tracking.


Added in version 3.7.

@end deffn

@geindex Empty
@anchor{library/queue queue Empty}@anchor{366c}
@deffn {例外} queue.Empty

空の @ref{15ac,,Queue} オブジェクトで、非ブロックメソッド @ref{31c3,,get()} (または @ref{3784,,get_nowait()}) が呼ばれたとき、送出される例外です。
@end deffn

@geindex Full
@anchor{library/queue queue Full}@anchor{366d}
@deffn {例外} queue.Full

満杯の @ref{15ac,,Queue} オブジェクトで、非ブロックメソッド @ref{3785,,put()} (または @ref{31c2,,put_nowait()}) が呼ばれたとき、送出される例外です。
@end deffn

@geindex ShutDown
@anchor{library/queue queue ShutDown}@anchor{543}
@deffn {例外} queue.ShutDown

Exception raised when @ref{3785,,put()} or @ref{31c3,,get()} is called on
a @ref{15ac,,Queue} object which has been shut down.


Added in version 3.13.

@end deffn

@menu
* キューオブジェクト:: 
* SimpleQueue オブジェクト:: 

@end menu

@node キューオブジェクト,SimpleQueue オブジェクト,,queue --- 同期キュークラス
@anchor{library/queue queue-objects}@anchor{3786}@anchor{library/queue queueobjects}@anchor{3787}
@subsubsection キューオブジェクト


キューオブジェクト(@ref{15ac,,Queue}, @ref{26b6,,LifoQueue}, @ref{26b7,,PriorityQueue})は、以下のpublicメソッドを提供しています。

@geindex qsize() (queue.Queue のメソッド)
@anchor{library/queue queue Queue qsize}@anchor{3788}
@deffn {メソッド} Queue.qsize ()

キューの近似サイズを返します。ここで、qsize() > 0 は後続の get() がブロックしないことを保証しないこと、また qsize() < maxsize が put() がブロックしないことを保証しないことに注意してください。
@end deffn

@geindex empty() (queue.Queue のメソッド)
@anchor{library/queue queue Queue empty}@anchor{3789}
@deffn {メソッド} Queue.empty ()

キューが空の場合は @code{True} を返し、そうでなければ @code{False} を返します。empty() が @code{True} を返しても、後続の put() の呼び出しがブロックしないことは保証されません。同様に、empty() が @code{False} を返しても、後続の get() の呼び出しがブロックしないことは保証されません。
@end deffn

@geindex full() (queue.Queue のメソッド)
@anchor{library/queue queue Queue full}@anchor{378a}
@deffn {メソッド} Queue.full ()

キューが一杯の場合は @code{True} を返し、そうでなければ @code{False} を返します。full() が @code{True} を返しても、後続の get() の呼び出しがブロックしないことは保証されません。同様に、full() が @code{False} を返しても、後続の put() の呼び出しがブロックしないことは保証されません。
@end deffn

@geindex put() (queue.Queue のメソッド)
@anchor{library/queue queue Queue put}@anchor{3785}
@deffn {メソッド} Queue.put (item, block=True, timeout=None)

`item' をキューに入れます。
もしオプション引数 `block' が真で `timeout' が @code{None} (デフォルト) の場合は、必要であればフリースロットが利用可能になるまでブロックします。
`timeout' が正の数の場合は、最大で `timeout' 秒間ブロックし、その時間内に空きスロットが利用可能にならなければ、例外 @ref{366d,,Full} を送出します。
そうでない場合 (`block' が偽) は、空きスロットが直ちに利用できるならば、キューにアイテムを置きます。
できないならば、例外 @ref{366d,,Full} を送出します (この場合 `timeout' は無視されます)。

Raises @ref{543,,ShutDown} if the queue has been shut down.
@end deffn

@geindex put_nowait() (queue.Queue のメソッド)
@anchor{library/queue queue Queue put_nowait}@anchor{31c2}
@deffn {メソッド} Queue.put_nowait (item)

@code{put(item, block=False)} と等価です。
@end deffn

@geindex get() (queue.Queue のメソッド)
@anchor{library/queue queue Queue get}@anchor{31c3}
@deffn {メソッド} Queue.get (block=True, timeout=None)

キューからアイテムを取り除き、それを返します。
オプション引数 `block' が真で `timeout' が @code{None} (デフォルト) の場合は、必要であればアイテムが取り出せるようになるまでブロックします。
もし `timeout' が正の数の場合は、最大で `timeout' 秒間ブロックし、その時間内でアイテムが取り出せるようにならなければ、例外 @ref{366c,,Empty} を送出します。
そうでない場合 (`block' が偽) は、直ちにアイテムが取り出せるならば、それを返します。
できないならば、例外 @ref{366c,,Empty} を送出します (この場合 `timeout' は無視されます)。

Prior to 3.0 on POSIX systems, and for all versions on Windows, if
`block' is true and `timeout' is @code{None}, this operation goes into
an uninterruptible wait on an underlying lock.  This means that no exceptions
can occur, and in particular a SIGINT will not trigger a @ref{bc5,,KeyboardInterrupt}.

Raises @ref{543,,ShutDown} if the queue has been shut down and is empty, or if
the queue has been shut down immediately.
@end deffn

@geindex get_nowait() (queue.Queue のメソッド)
@anchor{library/queue queue Queue get_nowait}@anchor{3784}
@deffn {メソッド} Queue.get_nowait ()

@code{get(False)} と等価です。
@end deffn

キューに入れられたタスクが全てコンシューマスレッドに処理されたかどうかを追跡するために 2つのメソッドが提供されます。

@geindex task_done() (queue.Queue のメソッド)
@anchor{library/queue queue Queue task_done}@anchor{3668}
@deffn {メソッド} Queue.task_done ()

過去にキューに入れられたタスクが完了した事を示します。キューのコンシューマスレッドに利用されます。タスクの取り出しに使われた各 @ref{31c3,,get()} の後に @ref{3668,,task_done()} を呼び出すと、取り出したタスクに対する処理が完了した事をキューに教えます。

@ref{3669,,join()} がブロックされていた場合、全itemが処理された (キューに @ref{3785,,put()} された全てのitemに対して @ref{3668,,task_done()} が呼び出されたことを意味します) 時に復帰します。

キューにある要素より多く呼び出された場合 @ref{2ec,,ValueError} が発生します。
@end deffn

@geindex join() (queue.Queue のメソッド)
@anchor{library/queue queue Queue join}@anchor{3669}
@deffn {メソッド} Queue.join ()

キューにあるすべてのアイテムが取り出されて処理されるまでブロックします。

未完了のタスクのカウント値はキューにアイテムが追加されるときは常に加算され、コンシューマースレッドが @ref{3668,,task_done()} を呼び出してアイテムの回収とその全処理の完了が示されるときは常に減算されます。未完了のタスクのカウント値がゼロになった場合、@ref{3669,,join()} のブロックが解除されます。
@end deffn

@menu
* Waiting for task completion:: 
* Terminating queues:: 

@end menu

@node Waiting for task completion,Terminating queues,,キューオブジェクト
@anchor{library/queue waiting-for-task-completion}@anchor{378b}
@subsubsection Waiting for task completion


キューに入れたタスクが完了するのを待つ例:

@example
import threading
import 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)

# Block until all tasks are done.
q.join()
print('All work completed')
@end example

@node Terminating queues,,Waiting for task completion,キューオブジェクト
@anchor{library/queue terminating-queues}@anchor{378c}
@subsubsection Terminating queues


When no longer needed, @ref{15ac,,Queue} objects can be wound down
until empty or terminated immediately with a hard shutdown.

@geindex shutdown() (queue.Queue のメソッド)
@anchor{library/queue queue Queue shutdown}@anchor{542}
@deffn {メソッド} Queue.shutdown (immediate=False)

Put a @ref{15ac,,Queue} instance into a shutdown mode.

The queue can no longer grow.
Future calls to @ref{3785,,put()} raise @ref{543,,ShutDown}.
Currently blocked callers of @ref{3785,,put()} will be unblocked
and will raise @ref{543,,ShutDown} in the formerly blocked thread.

If `immediate' is false (the default), the queue can be wound
down normally with @ref{31c3,,get()} calls to extract tasks
that have already been loaded.

And if @ref{3668,,task_done()} is called for each remaining task, a
pending @ref{3669,,join()} will be unblocked normally.

Once the queue is empty, future calls to @ref{31c3,,get()} will
raise @ref{543,,ShutDown}.

If `immediate' is true, the queue is terminated immediately.
The queue is drained to be completely empty and the count
of unfinished tasks is reduced by the number of tasks drained.
If unfinished tasks is zero, callers of @ref{3669,,join()}
are unblocked.  Also, blocked callers of @ref{31c3,,get()}
are unblocked and will raise @ref{543,,ShutDown} because the
queue is empty.

Use caution when using @ref{3669,,join()} with `immediate' set
to true. This unblocks the join even when no work has been done
on the tasks, violating the usual invariant for joining a queue.


Added in version 3.13.

@end deffn

@node SimpleQueue オブジェクト,,キューオブジェクト,queue --- 同期キュークラス
@anchor{library/queue simplequeue-objects}@anchor{378d}
@subsubsection SimpleQueue オブジェクト


@ref{d61,,SimpleQueue} オブジェクトは以下のpublicメソッドを提供しています。

@geindex qsize() (queue.SimpleQueue のメソッド)
@anchor{library/queue queue SimpleQueue qsize}@anchor{378e}
@deffn {メソッド} SimpleQueue.qsize ()

キューの近似サイズを返します。ここで、qsize() > 0 であるからといって、後続の get() の呼び出しがブロックしないことが保証されないことに注意してください。
@end deffn

@geindex empty() (queue.SimpleQueue のメソッド)
@anchor{library/queue queue SimpleQueue empty}@anchor{378f}
@deffn {メソッド} SimpleQueue.empty ()

キューが空の場合は @code{True} を返し、そうでなければ @code{False} を返します。 empty() が @code{False} を返しても、後続の get() の呼び出しがブロックしないことは保証されません。
@end deffn

@geindex put() (queue.SimpleQueue のメソッド)
@anchor{library/queue queue SimpleQueue put}@anchor{3790}
@deffn {メソッド} SimpleQueue.put (item, block=True, timeout=None)

Put `item' into the queue.  The method never blocks and always succeeds
(except for potential low-level errors such as failure to allocate memory).
The optional args `block' and `timeout' are ignored and only provided
for compatibility with @ref{3785,,Queue.put()}.

`CPython 実装の詳細:' This method has a C implementation which is reentrant.  That is, a
@code{put()} or @code{get()} call can be interrupted by another @code{put()}
call in the same thread without deadlocking or corrupting internal
state inside the queue.  This makes it appropriate for use in
destructors such as @code{__del__} methods or @ref{11a,,weakref} callbacks.
@end deffn

@geindex put_nowait() (queue.SimpleQueue のメソッド)
@anchor{library/queue queue SimpleQueue put_nowait}@anchor{3791}
@deffn {メソッド} SimpleQueue.put_nowait (item)

@code{put(item, block=False)} と等価です。@ref{31c2,,Queue.put_nowait()} との互換性のためのメソッドです。
@end deffn

@geindex get() (queue.SimpleQueue のメソッド)
@anchor{library/queue queue SimpleQueue get}@anchor{3792}
@deffn {メソッド} SimpleQueue.get (block=True, timeout=None)

キューからアイテムを取り除き、それを返します。
オプション引数 `block' が真で `timeout' が @code{None} (デフォルト) の場合は、必要であればアイテムが取り出せるようになるまでブロックします。
もし `timeout' が正の数の場合は、最大で `timeout' 秒間ブロックし、その時間内でアイテムが取り出せるようにならなければ、例外 @ref{366c,,Empty} を送出します。
そうでない場合 (`block' が偽) は、直ちにアイテムが取り出せるならば、それを返します。
できないならば、例外 @ref{366c,,Empty} を送出します (この場合 `timeout' は無視されます)。
@end deffn

@geindex get_nowait() (queue.SimpleQueue のメソッド)
@anchor{library/queue queue SimpleQueue get_nowait}@anchor{3793}
@deffn {メソッド} SimpleQueue.get_nowait ()

@code{get(False)} と等価です。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{1b89,,multiprocessing.Queue} クラス

(マルチスレッドではなく) マルチプロセスの文脈で使用されるキュークラス。
@end table

@ref{7f4,,collections.deque} is an alternative implementation of unbounded
queues with fast atomic @ref{297c,,append()} and
@ref{2982,,popleft()} operations that do not require locking
and also support indexing.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node contextvars --- コンテキスト変数,_thread --- 低水準なスレッド API,queue --- 同期キュークラス,並行実行
@anchor{library/contextvars doc}@anchor{3794}@anchor{library/contextvars contextvars-context-variables}@anchor{3795}@anchor{library/contextvars module-contextvars}@anchor{28}@anchor{library/contextvars translation-repo}@anchor{3796}
@subsection @code{contextvars} --- コンテキスト変数


@geindex module; contextvars


__________________________________________________________________


このモジュールは、コンテキストローカルな状態を管理し、保持し、アクセスするための API を提供します。
@ref{1875,,ContextVar} クラスは `コンテキスト変数' を宣言し、取り扱うために使われます。
非同期フレームワークで現時点のコンテキストを管理するのには、 @ref{361f,,copy_context()} 関数と @ref{177,,Context} クラスを使うべきです。

Context managers that have state should use Context Variables
instead of @ref{185f,,threading.local()} to prevent their state from
bleeding to other code unexpectedly, when used in concurrent code.

より詳しくは 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} を参照をしてください。


Added in version 3.7.


@menu
* コンテキスト変数:: 
* マニュアルでのコンテキスト管理:: 
* asyncio サポート:: 

@end menu

@node コンテキスト変数,マニュアルでのコンテキスト管理,,contextvars --- コンテキスト変数
@anchor{library/contextvars context-variables}@anchor{3797}
@subsubsection コンテキスト変数


@geindex ContextVar (contextvars のクラス)
@anchor{library/contextvars contextvars ContextVar}@anchor{1875}
@deffn {クラス} contextvars.ContextVar (name[, *, default])

このクラスは新しいコンテキスト変数を宣言するのに使われます。例えば、次の通りです:

@example
var: ContextVar[int] = ContextVar('var', default=42)
@end example

必須のパラメータの `name' は内観やデバッグの目的で使われます。

オプションのキーワード専用引数 `default' は、現在のコンテキストにその変数の値が見付からなかったときに @ref{3798,,ContextVar.get()} から返されます。

`重要:' コンテキスト変数は、モジュールのトップレベルで生成する必要があり、クロージャの中で作成すべきではありません。@ref{177,,Context} オブジェクトはコンテキスト変数への強参照を持っており、コンテキスト変数がガーベジコレクトされるのを防ぎます。

@geindex name (contextvars.ContextVar の属性)
@anchor{library/contextvars contextvars ContextVar name}@anchor{3799}
@deffn {の属性} name

変数の名前。読み出し専用のプロパティです。


Added in version 3.7.1.

@end deffn

@geindex get() (contextvars.ContextVar のメソッド)
@anchor{library/contextvars contextvars ContextVar get}@anchor{3798}
@deffn {メソッド} get ([default])

現在のコンテキストのコンテキスト変数の値を返します。

現在のコンテキストのコンテキスト変数に値がなければ、メソッドは:


@itemize *

@item 
メソッドの `default' 引数に値が指定されていればその値を返します。さもなければ

@item 
コンテキスト変数が生成された時にデフォルト値が渡されていれば、その値を返します。さもなければ

@item 
@ref{23e5,,LookupError} を送出します。
@end itemize
@end deffn

@geindex set() (contextvars.ContextVar のメソッド)
@anchor{library/contextvars contextvars ContextVar set}@anchor{1792}
@deffn {メソッド} set (value)

現在のコンテキストのコンテキスト変数に新しい値を設定する際に呼び出します。

`value' は必須の引数で、コンテキスト変数の新しい値を指定します。

@ref{1e2,,Token} オブジェクトを返します。このオブジェクトを @ref{379a,,ContextVar.reset()} メソッドに渡すことで、以前の値に戻すことができます。

For convenience, the token object can be used as a context manager
to avoid calling @ref{379a,,ContextVar.reset()} manually:

@example
var = ContextVar('var', default='default value')

with var.set('new value'):
    assert var.get() == 'new value'

assert var.get() == 'default value'
@end example

It is a shorthand for:

@example
var = ContextVar('var', default='default value')

token = var.set('new value')
try:
    assert var.get() == 'new value'
finally:
    var.reset(token)

assert var.get() == 'default value'
@end example


Added in version 3.14: Added support for using tokens as context managers.

@end deffn

@geindex reset() (contextvars.ContextVar のメソッド)
@anchor{library/contextvars contextvars ContextVar reset}@anchor{379a}
@deffn {メソッド} reset (token)

コンテキスト変数の値を、 `token' を生成した @ref{1792,,ContextVar.set()} が呼び出される前の値にリセットします。

例えば:

@example
var = ContextVar('var')

token = var.set('new value')
# code that uses 'var'; var.get() returns 'new value'.
var.reset(token)

# After the reset call the var has no value again, so
# var.get() would raise a LookupError.
@end example

The same `token' cannot be used twice.
@end deffn
@end deffn

@geindex Token (contextvars のクラス)
@anchor{library/contextvars contextvars Token}@anchor{1e2}
@deffn {クラス} contextvars.Token

`Token' objects are returned by the @ref{1792,,ContextVar.set()} method.
They can be passed to the @ref{379a,,ContextVar.reset()} method to revert
the value of the variable to what it was before the corresponding
`set'. A single token cannot reset a context variable more than once.

Tokens support the @ref{240b,,context manager protocol}
to automatically reset context variables. See @ref{1792,,ContextVar.set()}.


Added in version 3.14: Added support for usage as a context manager.


@geindex var (contextvars.Token の属性)
@anchor{library/contextvars contextvars Token var}@anchor{379b}
@deffn {の属性} var

読み出し専用のプロパティです。トークンを生成した @ref{1875,,ContextVar} オブジェクトを指します。
@end deffn

@geindex old_value (contextvars.Token の属性)
@anchor{library/contextvars contextvars Token old_value}@anchor{379c}
@deffn {の属性} old_value

読み出し専用のプロパティです。このトークンを作成した @ref{1792,,ContextVar.set()} メソッドの呼び出しの前に持っていた値に設定されています。もし呼び出しの前に値が設定されていなければ @ref{17f9,,Token.MISSING} を指します。
@end deffn

@geindex MISSING (contextvars.Token の属性)
@anchor{library/contextvars contextvars Token MISSING}@anchor{17f9}
@deffn {の属性} MISSING

@ref{379c,,Token.old_value} で利用されるマーカーオブジェクトです。
@end deffn
@end deffn

@node マニュアルでのコンテキスト管理,asyncio サポート,コンテキスト変数,contextvars --- コンテキスト変数
@anchor{library/contextvars manual-context-management}@anchor{379d}
@subsubsection マニュアルでのコンテキスト管理


@geindex copy_context() (contextvars モジュール)
@anchor{library/contextvars contextvars copy_context}@anchor{361f}
@deffn {の関数} contextvars.copy_context ()

現在の @ref{177,,Context} オブジェクトのコピーを返します。

次のスニペットは、現在のコンテキストのコピーを取得し、コンテキストに設定されているすべての変数とその値を表示します:

@example
ctx: Context = copy_context()
print(list(ctx.items()))
@end example

この関数の複雑性は `O'(1) です。つまり、少数のコンテキスト変数を持つコンテキストと多くの変数を持つコンテキストで同程度の速度で動作します。
@end deffn

@geindex Context (contextvars のクラス)
@anchor{library/contextvars contextvars Context}@anchor{177}
@deffn {クラス} contextvars.Context

@code{ContextVars} とその値の対応付け。

@code{Context()} は、値を持たない空のコンテキストを生成します。現在のコンテキストのコピーを得るには、@ref{361f,,copy_context()} 関数を利用します。

Each thread has its own effective stack of @code{Context} objects.  The
@ref{1964,,current context} is the @code{Context} object at the top of the
current thread's stack.  All @code{Context} objects in the stacks are
considered to be `entered'.

`Entering' a context, which can be done by calling its @ref{194b,,run()}
method, makes the context the current context by pushing it onto the top of
the current thread's context stack.

`Exiting' from the current context, which can be done by returning from the
callback passed to the @ref{194b,,run()} method, restores the current
context to what it was before the context was entered by popping the context
off the top of the context stack.

Since each thread has its own context stack, @ref{1875,,ContextVar} objects
behave in a similar fashion to @ref{185f,,threading.local()} when values are
assigned in different threads.

Attempting to enter an already entered context, including contexts entered in
other threads, raises a @ref{244,,RuntimeError}.

After exiting a context, it can later be re-entered (from any thread).

Any changes to @ref{1875,,ContextVar} values via the @ref{1792,,ContextVar.set()}
method are recorded in the current context.  The @ref{3798,,ContextVar.get()}
method returns the value associated with the current context.  Exiting a
context effectively reverts any changes made to context variables while the
context was entered (if needed, the values can be restored by re-entering the
context).

Context は、 @ref{ac7,,collections.abc.Mapping} インターフェースを実装します。

@geindex run() (contextvars.Context のメソッド)
@anchor{library/contextvars contextvars Context run}@anchor{194b}
@deffn {メソッド} run (callable, *args, **kwargs)

Enters the Context, executes @code{callable(*args, **kwargs)}, then exits the
Context.  Returns `callable''s return value, or propagates an exception if
one occurred.

例:

@example
import contextvars

var = contextvars.ContextVar('var')
var.set('spam')
print(var.get())  # 'spam'

ctx = contextvars.copy_context()

def main():
    # 'var' was set to 'spam' before
    # calling 'copy_context()' and 'ctx.run(main)', so:
    print(var.get())  # 'spam'
    print(ctx[var])  # 'spam'

    var.set('ham')

    # Now, after setting 'var' to 'ham':
    print(var.get())  # 'ham'
    print(ctx[var])  # 'ham'

# 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:
print(ctx[var])  # 'ham'

# However, outside of 'ctx', 'var' is still set to 'spam':
print(var.get())  # 'spam'
@end example

@c spam
@c spam
@c spam
@c ham
@c ham
@c ham
@c spam
@end deffn

@geindex copy() (contextvars.Context のメソッド)
@anchor{library/contextvars contextvars Context copy}@anchor{379e}
@deffn {メソッド} copy ()

コンテキストオブジェクトの浅いコピーを返します。
@end deffn


@deffn {Describe} var in context

`context' に `var' の値が設定されていた場合 @code{True} を返します; そうでない場合は @code{False} を返します。
@end deffn


@deffn {Describe} context[var]

@ref{1875,,ContextVar} `var' の値を返します。コンテキストオブジェクト内で変数が設定されていない場合は、@ref{5e7,,KeyError} を送出します。
@end deffn

@geindex get() (contextvars.Context のメソッド)
@anchor{library/contextvars contextvars Context get}@anchor{379f}
@deffn {メソッド} get (var[, default])

`var' がコンテキストオブジェクトの中に値を持てば、その値を返します。さもなければ、`default' を返します。`default' を指定していなければ、@code{None} を返します。
@end deffn


@deffn {Describe} iter(context)

コンテキストオブジェクトに格納されている変数群のイテレータを返します。
@end deffn


@deffn {Describe} len(proxy)

コンテキストオブジェクトに格納されている変数の数を返します。
@end deffn

@geindex keys() (contextvars.Context のメソッド)
@anchor{library/contextvars contextvars Context keys}@anchor{37a0}
@deffn {メソッド} keys ()

コンテキストオブジェクト中のすべての変数のリストを返します。
@end deffn

@geindex values() (contextvars.Context のメソッド)
@anchor{library/contextvars contextvars Context values}@anchor{37a1}
@deffn {メソッド} values ()

コンテキストオブジェクト中のすべての変数の値のリストを返します。
@end deffn

@geindex items() (contextvars.Context のメソッド)
@anchor{library/contextvars contextvars Context items}@anchor{37a2}
@deffn {メソッド} items ()

コンテキストオブジェクト中のすべての変数について、変数とその値からなる2要素のタプルのリストを返します。
@end deffn
@end deffn

@node asyncio サポート,,マニュアルでのコンテキスト管理,contextvars --- コンテキスト変数
@anchor{library/contextvars asyncio-support}@anchor{37a3}
@subsubsection asyncio サポート


コンテキスト変数は、追加の設定なしに @ref{b,,asyncio} をサポートします。例えば、次の単純なechoサーバーは、クライアントを扱う Task の中でリモートクライアントのアドレスが利用できるように、コンテキスト変数を利用します:

@example
import asyncio
import contextvars

client_addr_var = contextvars.ContextVar('client_addr')

def render_goodbye():
    # The address of the currently handled client can be accessed
    # without passing it explicitly to this function.

    client_addr = client_addr_var.get()
    return f'Good bye, client @@ @{client_addr@}\r\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(b'HTTP/1.1 200 OK\r\n')  # status line
    writer.write(b'\r\n')  # headers
    writer.write(render_goodbye())  # body
    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 or curl:
#     telnet 127.0.0.1 8081
#     curl 127.0.0.1:8081
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

以下のモジュールは上記のサービスの一部で使われるサポートモジュールです:

@node _thread --- 低水準なスレッド API,,contextvars --- コンテキスト変数,並行実行
@anchor{library/_thread doc}@anchor{37a4}@anchor{library/_thread module-_thread}@anchor{2}@anchor{library/_thread thread-low-level-threading-api}@anchor{37a5}@anchor{library/_thread translation-repo}@anchor{37a6}
@subsection @code{_thread} --- 低水準なスレッド API


@geindex module; _thread

@geindex light-weight processes
@geindex processes@comma{} light-weight
@geindex binary semaphores
@geindex semaphores@comma{} binary


__________________________________________________________________


このモジュールはマルチスレッド (別名 `軽量プロセス' (`light-weight processes')または `タスク' (`tasks')) に用いられる低水準プリミティブを提供します --- グローバルデータ空間を共有するマルチスレッドを制御します。同期のための単純なロック (別名 `mutexes' またはバイナリセマフォ (`binary semaphores'))が提供されています。 @ref{f3,,threading} モジュールは、このモジュール上で、より使い易く高級なスレッディングの API を提供します。

@geindex pthreads
@geindex threads;POSIX


バージョン 3.7 で変更: このモジュールは以前はオプションでしたが、常に利用可能なモジュールとなりました。


このモジュールでは以下の定数および関数を定義しています:

@geindex error
@anchor{library/_thread thread error}@anchor{37a7}
@deffn {例外} _thread.error

スレッド固有の例外です。


バージョン 3.3 で変更: 現在は組み込みの @ref{244,,RuntimeError} の別名です。

@end deffn

@geindex LockType (_thread モジュール)
@anchor{library/_thread thread LockType}@anchor{37a8}
@deffn {データ} _thread.LockType

これはロックオブジェクトのタイプです。
@end deffn

@geindex start_new_thread() (_thread モジュール)
@anchor{library/_thread thread start_new_thread}@anchor{4b4}
@deffn {の関数} _thread.start_new_thread (function, args[, kwargs])

新しいスレッドを開始して、そのIDを返します。スレッドは引数リスト `args' (タプルでなければなりません)の関数 `function' を実行します。オプション引数 `kwargs' はキーワード引数の辞書を指定します。

関数が戻るとき、スレッドは静かに終了します。

When the function terminates with an unhandled exception,
@ref{507,,sys.unraisablehook()} is called to handle the exception. The `object'
attribute of the hook argument is `function'. By default, a stack trace is
printed and then the thread exits (but other threads continue to run).

When the function raises a @ref{f3c,,SystemExit} exception, it is silently
ignored.

Raises an @ref{1c6e,,auditing event} @code{_thread.start_new_thread} with arguments @code{function}, @code{args}, @code{kwargs}.


バージョン 3.8 で変更: @ref{507,,sys.unraisablehook()} is now used to handle unhandled exceptions.

@end deffn

@geindex interrupt_main() (_thread モジュール)
@anchor{library/_thread thread interrupt_main}@anchor{a44}
@deffn {の関数} _thread.interrupt_main (signum=signal.SIGINT, /)

Simulate the effect of a signal arriving in the main thread.
A thread can use this function to interrupt the main thread, though
there is no guarantee that the interruption will happen immediately.

If given, `signum' is the number of the signal to simulate.
If `signum' is not given, @ref{253,,signal.SIGINT} is simulated.

If the given signal isn't handled by Python (it was set to
@ref{1bb2,,signal.SIG_DFL} or @ref{1bb1,,signal.SIG_IGN}), this function does
nothing.


バージョン 3.10 で変更: The `signum' argument is added to customize the signal number.


@cartouche
@quotation 注釈 
This does not emit the corresponding signal but schedules a call to
the associated handler (if it exists).
If you want to truly emit the signal, use @ref{1b8f,,signal.raise_signal()}.
@end quotation
@end cartouche
@end deffn

@geindex exit() (_thread モジュール)
@anchor{library/_thread thread exit}@anchor{37a9}
@deffn {の関数} _thread.exit ()

@ref{f3c,,SystemExit} を送出します。それが捕えられないときは、静かにスレッドを終了させます。
@end deffn

@c function:: exit_prog(status)
@c 
@c    Exit all threads and report the value of the integer argument
@c    *status* as the exit status of the entire program.
@c    **Caveat:** code in pending :keyword:`finally` clauses, in this thread
@c    or in other threads, is not executed.

@geindex allocate_lock() (_thread モジュール)
@anchor{library/_thread thread allocate_lock}@anchor{37aa}
@deffn {の関数} _thread.allocate_lock ()

新しいロックオブジェクトを返します。ロックのメソッドはこの後に記述されます。ロックは初期状態としてアンロック状態です。
@end deffn

@geindex get_ident() (_thread モジュール)
@anchor{library/_thread thread get_ident}@anchor{37ab}
@deffn {の関数} _thread.get_ident ()

現在のスレッドの 'スレッドID' を返します。非ゼロの整数です。この値は直接の意味を持っていません; 例えばスレッド特有のデータの辞書に索引をつけるためのような、マジッククッキーとして意図されています。スレッドが終了し、他のスレッドが作られたとき、スレッド ID は再利用されるかもしれません。
@end deffn

@geindex get_native_id() (_thread モジュール)
@anchor{library/_thread thread get_native_id}@anchor{37ac}
@deffn {の関数} _thread.get_native_id ()

Return the native integral Thread ID of the current thread assigned by the kernel.
This is a non-negative integer.
Its value may be used to uniquely identify this particular thread system-wide
(until the thread terminates, after which the value may be recycled by the OS).

@ref{213f,,Availability}: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD.


Added in version 3.8.



バージョン 3.13 で変更: Added support for GNU/kFreeBSD.

@end deffn

@geindex stack_size() (_thread モジュール)
@anchor{library/_thread thread stack_size}@anchor{1779}
@deffn {の関数} _thread.stack_size ([size])

新しいスレッドを作るときのスレッドスタックサイズを返します。オプションの `size' 引数にはこれ以降に作成するスレッドのスタックサイズを指定し、0 (プラットフォームのデフォルト値または設定されたデフォルト値) か、 32,768 (32 KiB) 以上の正の整数でなければなりません。`size' が指定されない場合 0 が使われます。スレッドのスタックサイズの変更がサポートされていない場合、 @ref{244,,RuntimeError} を送出します。不正なスタックサイズが指定された場合、 @ref{2ec,,ValueError} を送出して、スタックサイズは変更されません。32 KiB は現在のインタープリタ自身のために十分であると保証された最小のスタックサイズです。いくつかのプラットフォームではスタックサイズに対して制限があることに注意してください。例えば最小のスタックサイズが 32 KiB より大きかったり、システムのメモリページサイズ の整数倍の必要があるなどです。この制限についてはプラットフォームのドキュメントを参照してください (一般的なページサイズは 4 KiB なので、プラットフォームに関する情報がない場合は 4096 の整数倍のスタックサイズを選ぶといいかもしれません)。

@ref{213f,,Availability}: Windows, pthreads.

Unix platforms with POSIX threads support.
@end deffn

@geindex TIMEOUT_MAX (_thread モジュール)
@anchor{library/_thread thread TIMEOUT_MAX}@anchor{37ad}
@deffn {データ} _thread.TIMEOUT_MAX

The maximum value allowed for the `timeout' parameter of
@ref{8a7,,Lock.acquire}. Specifying a timeout greater
than this value will raise an @ref{a81,,OverflowError}.


Added in version 3.2.

@end deffn

ロックオブジェクトは次のようなメソッドを持っています:

@geindex acquire() (_thread.lock のメソッド)
@anchor{library/_thread thread lock acquire}@anchor{37ae}
@deffn {メソッド} lock.acquire (blocking=True, timeout=-1)

オプションの引数なしで使用すると、このメソッドは他のスレッドがロックしているかどうかにかかわらずロックを獲得します。ただし、他のスレッドがすでにロックしている場合には解除されるまで待ってからロックを獲得します (同時にロックを獲得できるスレッドはひとつだけであり、これこそがロックの存在理由です)。

If the `blocking' argument is present, the action depends on its
value: if it is false, the lock is only acquired if it can be acquired
immediately without waiting, while if it is true, the lock is acquired
unconditionally as above.

If the floating-point `timeout' argument is present and positive, it
specifies the maximum wait time in seconds before returning.  A negative
`timeout' argument specifies an unbounded wait.  You cannot specify
a `timeout' if `blocking' is false.

なお、ロックを獲得できた場合は @code{True}、できなかった場合は @code{False} を返します。


バージョン 3.2 で変更: 新しい `timeout' 引数。



バージョン 3.2 で変更: POSIX ではロックの取得がシグナルに割り込まれるようになりました。



バージョン 3.14 で変更: Lock acquires can now be interrupted by signals on Windows.

@end deffn

@geindex release() (_thread.lock のメソッド)
@anchor{library/_thread thread lock release}@anchor{37af}
@deffn {メソッド} lock.release ()

ロックを解放します。そのロックは既に獲得されたものでなければなりませんが、しかし同じスレッドによって獲得されたものである必要はありません。
@end deffn

@geindex locked() (_thread.lock のメソッド)
@anchor{library/_thread thread lock locked}@anchor{37b0}
@deffn {メソッド} lock.locked ()

ロックの状態を返します: 同じスレッドによって獲得されたものなら @code{True} 、違うのなら @code{False} を返します。
@end deffn

これらのメソッドに加えて、ロックオブジェクトは @ref{186,,with} 文を通じて以下の例のように使うこともできます。

@example
import _thread

a_lock = _thread.allocate_lock()

with a_lock:
    print("a_lock is locked while this executes")
@end example

`警告:'

@geindex module;signal


@itemize *

@item 
Interrupts always go to the main thread (the @ref{bc5,,KeyboardInterrupt}
exception will be received by that thread.)

@item 
@ref{277,,sys.exit()} を呼び出す、あるいは @ref{f3c,,SystemExit} 例外を送出することは、 @ref{37a9,,_thread.exit()} を呼び出すことと同じです。

@item 
メインスレッドが終了したとき、他のスレッドが生き残るかどうかは、システムに依存します。多くのシステムでは、 @ref{8f8,,try} ... @ref{1b0,,finally} 節や、オブジェクトデストラクタを実行せずに終了されます。
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ネットワーク通信とプロセス間通信,インターネット上のデータの操作,並行実行,Python 標準ライブラリ
@anchor{library/ipc doc}@anchor{37b1}@anchor{library/ipc ipc}@anchor{37b2}@anchor{library/ipc networking-and-interprocess-communication}@anchor{37b3}@anchor{library/ipc translation-repo}@anchor{37b4}
@section ネットワーク通信とプロセス間通信


この章で解説しているモジュールはネットワーク通信とプロセス間通信の仕組みを提供しています。

例えば @ref{cb,,signal} や @ref{94,,mmap} のように、同じマシン上の 2 つのプロセスでしか使えないモジュールがあります。その他のモジュールは 2 つ以上のプロセスを使ってマシン間で通信できるネットワークプロトコルをサポートします。

この章で解説されるモジュールのリスト:

@menu
* asyncio: asyncio --- 非同期 I/O. 非同期 I/O
* socket: socket --- 低水準ネットワークインターフェース. 低水準ネットワークインターフェース
* ssl: ssl --- ソケットオブジェクト用の TLS/SSL ラッパー. ソケットオブジェクト用の TLS/SSL ラッパー
* select: select --- I/O 完了の待機. I/O 完了の待機
* selectors: selectors --- 高水準の I/O 多重化. 高水準の I/O 多重化
* signal: signal --- 非同期イベントにハンドラーを設定する. 非同期イベントにハンドラーを設定する
* mmap: mmap --- メモリマップファイルのサポート. メモリマップファイルのサポート

@end menu

@node asyncio --- 非同期 I/O,socket --- 低水準ネットワークインターフェース,,ネットワーク通信とプロセス間通信
@anchor{library/asyncio doc}@anchor{37b5}@anchor{library/asyncio asyncio-asynchronous-i-o}@anchor{37b6}@anchor{library/asyncio module-asyncio}@anchor{b}
@subsection @code{asyncio} --- 非同期 I/O


@geindex module; asyncio


__________________________________________________________________


@subsubheading Hello World!



@example
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

asyncio.run(main())
@end example

asyncio は `async/await' 構文を使い `並行処理の' コードを書くためのライブラリです。

asyncio は、高性能なネットワークとウェブサーバ、データベース接続ライブラリ、分散タスクキューなどの複数の非同期 Python フレームワークの基盤として使われています。

asyncio は多くの場合、 IOバウンドだったり高レベルの `構造化された' ネットワークコードに完璧に適しています。


@subsubheading 参考



@table @asis

@item @ref{37b7,,A Conceptual Overview of asyncio}

asyncio の基本が解説されています。
@end table


asyncio は次の目的で `高レベル' API を提供しています:


@itemize *

@item 
並行に @ref{37b8,,Python コルーチンを起動} し、実行全体を管理する

@item 
@ref{37b9,,ネットワーク IO と IPC} を執り行う

@item 
@ref{37ba,,subprocesses} を管理する

@item 
@ref{37bb,,キュー} を使ってタスクを分散する

@item 
並列処理のコードを @ref{37bc,,同期} させる
@end itemize

これに加えて、 `ライブラリやフレームワークの開発者' が次のことをするための `低レベル' API があります:


@itemize *

@item 
@ref{37bd,,ネットワーク通信} 、 @ref{37be,,サブプロセス} の実行、 @ref{37bf,,OS シグナル} の取り扱いなどのための非同期 API を提供する @ref{f76,,イベントループ} の作成と管理を行う

@item 
@ref{37c0,,Transport} を使った効率的な protocol を実装します

@item 
コールバックを用いたライブラリと async/await 構文を使ったコードの @ref{37c1,,橋渡し}
@end itemize

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。
@anchor{library/asyncio asyncio-cli}@anchor{37c2}
@subsubheading asyncio REPL


@ref{491,,REPL} で、@code{asyncio} 並行コンテキストを試すことができます:

@example
$ python -m asyncio
asyncio REPL ...
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> await asyncio.sleep(10, result='hello')
'hello'
@end example

This REPL provides limited compatibility with 
@geindex PYTHON_BASIC_REPL
@geindex 環境変数; PYTHON_BASIC_REPL
@ref{1b6,,PYTHON_BASIC_REPL}.
It is recommended that the default REPL is used
for full functionality and the latest features.

引数無しで @ref{1c6e,,監査イベント} @code{cpython.run_stdin} を送出します。


バージョン 3.12.5 で変更: (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20)
Emits audit events.



バージョン 3.13 で変更: Uses PyREPL if possible, in which case 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} is
also executed. Emits audit events.


@c We use the "rubric" directive here to avoid creating
@c the "Reference" subsection in the TOC.

@subsubheading リファレンス


@menu
* Runners:: 
* コルーチンと Task:: 
* ストリーム:: 
* 同期プリミティブ: 同期プリミティブ<2>. 
* サブプロセス:: 
* キュー:: 
* 例外: 例外<16>. 
* Call Graph Introspection:: 
* イベントループ:: 
* Future:: 
* トランスポートとプロトコル:: 
* ポリシー:: 
* プラットフォームでのサポート:: 
* Extending:: 
* 高水準の API インデックス:: 
* 低水準の API インデックス:: 
* asyncio での開発:: 

@end menu

@node Runners,コルーチンと Task,,asyncio --- 非同期 I/O
@anchor{library/asyncio-runner doc}@anchor{37c3}@anchor{library/asyncio-runner runners}@anchor{37c4}
@subsubsection Runners


`ソースコード:' Lib/asyncio/runners.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/runners.py}

この節では、asyncio のコードを実行するための高レベルの asyncio のプリミティブの概略を解説します。

これらは @ref{f76,,イベントループ} の上に構築されており、一般的な広く普及しているシナリオでの非同期コードの使用を簡素化することを目的としています。

@menu
* 非同期プログラムの実行:: 
* Runner context manager:: 
* Handling Keyboard Interruption:: 

@end menu

@node 非同期プログラムの実行,Runner context manager,,Runners
@anchor{library/asyncio-runner running-an-asyncio-program}@anchor{37c5}
@subsubsection 非同期プログラムの実行


@geindex run() (asyncio モジュール)
@anchor{library/asyncio-runner asyncio run}@anchor{2f3}
@deffn {の関数} asyncio.run (coro, *, debug=None, loop_factory=None)

Execute `coro' in an asyncio event loop and return the result.

The argument can be any awaitable object.

This function runs the awaitable, taking care of managing the
asyncio event loop, `finalizing asynchronous generators', and
closing the executor.

この関数は、同じスレッドで他の非同期イベントループが実行中のときは呼び出せません。

`debug' が @code{True} の場合、イベントループはデバッグモードで実行されます。@code{False} は明示的にデバッグモードを無効化します。 グローバルな @ref{213a,,デバッグモード} 設定を尊重するために @code{None} が使用されます。

If `loop_factory' is not @code{None}, it is used to create a new event loop;
otherwise @ref{37c6,,asyncio.new_event_loop()} is used. The loop is closed at the end.
This function should be used as a main entry point for asyncio programs,
and should ideally only be called once. It is recommended to use
`loop_factory' to configure the event loop instead of policies.
Passing @ref{1a67,,asyncio.EventLoop} allows running asyncio without the
policy system.

The executor is given a timeout duration of 5 minutes to shutdown.
If the executor hasn't finished within that duration, a warning is
emitted and the executor is closed.

以下はプログラム例です:

@example
async def main():
    await asyncio.sleep(1)
    print('hello')

asyncio.run(main())
@end example


Added in version 3.7.



バージョン 3.9 で変更: @ref{ae4,,loop.shutdown_default_executor()} メソッドを使うように更新されました。



バージョン 3.10 で変更: `debug' はグローバルなデバッグモード設定を尊重するためにデフォルトで @code{None} です。



バージョン 3.12 で変更: `loop_factory' 引数が追加されました。



バージョン 3.14 で変更: `coro' can be any awaitable object.


@cartouche
@quotation 注釈 
The @code{asyncio} policy system is deprecated and will be removed
in Python 3.16; from there on, an explicit `loop_factory' is needed
to configure the event loop.
@end quotation
@end cartouche
@end deffn

@node Runner context manager,Handling Keyboard Interruption,非同期プログラムの実行,Runners
@anchor{library/asyncio-runner runner-context-manager}@anchor{37c7}
@subsubsection Runner context manager


@geindex Runner (asyncio のクラス)
@anchor{library/asyncio-runner asyncio Runner}@anchor{2f5}
@deffn {クラス} asyncio.Runner (*, debug=None, loop_factory=None)

同じコンテキスト上での `複数' の非同期関数呼び出しをシンプルにするコンテキストマネージャ。

Sometimes several top-level async functions should be called in the same @ref{f76,,event loop} and @ref{177,,contextvars.Context}.

`debug' が @code{True} の場合、イベントループはデバッグモードで実行されます。@code{False} は明示的にデバッグモードを無効化します。 グローバルな @ref{213a,,デバッグモード} 設定を尊重するために @code{None} が使用されます。

`loop_factory' could be used for overriding the loop creation.
It is the responsibility of the `loop_factory' to set the created loop as the
current one. By default @ref{37c6,,asyncio.new_event_loop()} is used and set as
current event loop with @ref{1b55,,asyncio.set_event_loop()} if `loop_factory' is @code{None}.

Basically, @ref{2f3,,asyncio.run()} example can be rewritten with the runner usage:

@example
async def main():
    await asyncio.sleep(1)
    print('hello')

with asyncio.Runner() as runner:
    runner.run(main())
@end example


Added in version 3.11.


@geindex run() (asyncio.Runner のメソッド)
@anchor{library/asyncio-runner asyncio Runner run}@anchor{194d}
@deffn {メソッド} run (coro, *, context=None)

Execute `coro' in the embedded event loop.

The argument can be any awaitable object.

If the argument is a coroutine, it is wrapped in a Task.

An optional keyword-only `context' argument allows specifying a
custom @ref{177,,contextvars.Context} for the code to run in.
The runner's default context is used if context is @code{None}.

Returns the awaitable's result or raises an exception.

この関数は、同じスレッドで他の非同期イベントループが実行中のときは呼び出せません。


バージョン 3.14 で変更: `coro' can be any awaitable object.

@end deffn

@geindex close() (asyncio.Runner のメソッド)
@anchor{library/asyncio-runner asyncio Runner close}@anchor{37c8}
@deffn {メソッド} close ()

Close the runner.

Finalize asynchronous generators, shutdown default executor, close the event loop
and release embedded @ref{177,,contextvars.Context}.
@end deffn

@geindex get_loop() (asyncio.Runner のメソッド)
@anchor{library/asyncio-runner asyncio Runner get_loop}@anchor{37c9}
@deffn {メソッド} get_loop ()

Return the event loop associated with the runner instance.
@end deffn

@cartouche
@quotation 注釈 
@ref{2f5,,Runner} uses the lazy initialization strategy, its constructor doesn't
initialize underlying low-level structures.

Embedded `loop' and `context' are created at the @ref{186,,with} body entering
or the first call of @ref{2f3,,run()} or @ref{37c9,,get_loop()}.
@end quotation
@end cartouche
@end deffn

@node Handling Keyboard Interruption,,Runner context manager,Runners
@anchor{library/asyncio-runner handling-keyboard-interruption}@anchor{37ca}
@subsubsection Handling Keyboard Interruption



Added in version 3.11.


When @ref{253,,signal.SIGINT} is raised by @code{Ctrl}-@code{C}, @ref{bc5,,KeyboardInterrupt}
exception is raised in the main thread by default. However this doesn't work with
@ref{b,,asyncio} because it can interrupt asyncio internals and can hang the program from
exiting.

To mitigate this issue, @ref{b,,asyncio} handles @ref{253,,signal.SIGINT} as follows:


@enumerate 

@item 
@ref{194d,,asyncio.Runner.run()} installs a custom @ref{253,,signal.SIGINT} handler before
any user code is executed and removes it when exiting from the function.

@item 
The @ref{2f5,,Runner} creates the main task for the passed coroutine for its
execution.

@item 
When @ref{253,,signal.SIGINT} is raised by @code{Ctrl}-@code{C}, the custom signal handler
cancels the main task by calling @ref{4d3,,asyncio.Task.cancel()} which raises
@ref{4d4,,asyncio.CancelledError} inside the main task.  This causes the Python stack
to unwind, @code{try/except} and @code{try/finally} blocks can be used for resource
cleanup.  After the main task is cancelled, @ref{194d,,asyncio.Runner.run()} raises
@ref{bc5,,KeyboardInterrupt}.

@item 
A user could write a tight loop which cannot be interrupted by
@ref{4d3,,asyncio.Task.cancel()}, in which case the second following @code{Ctrl}-@code{C}
immediately raises the @ref{bc5,,KeyboardInterrupt} without cancelling the main task.
@end enumerate

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node コルーチンと Task,ストリーム,Runners,asyncio --- 非同期 I/O
@anchor{library/asyncio-task doc}@anchor{37cb}@anchor{library/asyncio-task coroutines-and-tasks}@anchor{37cc}@anchor{library/asyncio-task translation-repo}@anchor{37cd}
@subsubsection コルーチンと Task


この節では、コルーチンと Task を利用する高レベルの asyncio の API の概略を解説します。

@menu
* コルーチン: コルーチン<3>. 
* Awaitable:: 
* Task の作成:: 
* タスクのキャンセル:: 
* Task Groups:: 
* スリープ:: 
* 並行な Task 実行:: 
* Eager Task Factory:: 
* キャンセルからの保護:: 
* タイムアウト:: 
* 要素の終了待機:: 
* スレッド内での実行:: 
* 外部スレッドからのスケジュール:: 
* イントロスペクション:: 
* Task オブジェクト:: 

@end menu

@node コルーチン<3>,Awaitable,,コルーチンと Task
@anchor{library/asyncio-task coroutine}@anchor{37b8}@anchor{library/asyncio-task coroutines}@anchor{37ce}
@subsubsection コルーチン


`Source code:' Lib/asyncio/coroutines.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/coroutines.py}


__________________________________________________________________


async/await 構文で宣言された @ref{6b9,,コルーチン} は、 asyncio を使ったアプリケーションを書くのに推奨される方法です。例えば、次のコードスニペットは "hello" を出力し、そこから 1 秒待って "world" を出力します:

@example
>>> import asyncio

>>> async def main():
...     print('hello')
...     await asyncio.sleep(1)
...     print('world')

>>> asyncio.run(main())
hello
world
@end example

単にコルーチンを呼び出しただけでは、コルーチンの実行スケジュールは予約されていないことに注意してください:

@example
>>> main()
<coroutine object main at 0x1053bb7c8>
@end example

実際にコルーチンを実行するために、asyncio は以下のメカニズムを提供しています:


@itemize *

@item 
最上位のエントリーポイントである "main()" 関数を実行する @ref{2f3,,asyncio.run()} 関数 (上の例を参照してください。)

@item 
コルーチンを await すること。次のコード片は 1 秒間待機した後に "hello" と出力し、 `更に' 2 秒間待機してから "world" と出力します:

@example
import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at @{time.strftime('%X')@}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at @{time.strftime('%X')@}")

asyncio.run(main())
@end example

予想される出力:

@example
started at 17:13:52
hello
world
finished at 17:13:55
@end example

@item 
asyncio の @ref{1c7,,Tasks} としてコルーチンを並行して走らせる @ref{1c9,,asyncio.create_task()} 関数。

上のコード例を編集して、ふたつの @code{say_after} コルーチンを `並行して' 走らせてみましょう:

@example
async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at @{time.strftime('%X')@}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at @{time.strftime('%X')@}")
@end example

予想される出力が、スニペットの実行が前回よりも 1 秒早いことを示していることに注意してください:

@example
started at 17:14:32
hello
world
finished at 17:14:34
@end example

@item 
The @ref{4d1,,asyncio.TaskGroup} class provides a more modern
alternative to @ref{1c9,,create_task()}.
Using this API, the last example becomes:

@example
async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(
            say_after(1, 'hello'))

        task2 = tg.create_task(
            say_after(2, 'world'))

        print(f"started at @{time.strftime('%X')@}")

    # The await is implicit when the context manager exits.

    print(f"finished at @{time.strftime('%X')@}")
@end example

The timing and output should be the same as for the previous version.


Added in version 3.11: @ref{4d1,,asyncio.TaskGroup}.

@end itemize

@node Awaitable,Task の作成,コルーチン<3>,コルーチンと Task
@anchor{library/asyncio-task asyncio-awaitables}@anchor{37cf}@anchor{library/asyncio-task awaitables}@anchor{37d0}
@subsubsection Awaitable


あるオブジェクトを @ref{18d,,await} 式の中で使うことができる場合、そのオブジェクトを `awaitable' オブジェクトと言います。多くの asyncio API は awaitable を受け取るように設計されています。

`awaitable' オブジェクトには主に3つの種類があります: `コルーチン', `Task', そして `Future' です

@subsubheading コルーチン


Python のコルーチンは `awaitable' であり、他のコルーチンから待機されることができます:

@example
import asyncio

async def nested():
    return 42

async def main():
    # Nothing happens if we just call "nested()".
    # A coroutine object is created but not awaited,
    # so it *won't run at all*.
    nested()  # will raise a "RuntimeWarning".

    # Let's do it differently now and await it:
    print(await nested())  # will print "42".

asyncio.run(main())
@end example

@cartouche
@quotation 重要 
このドキュメントにおいて「コルーチン」という用語は以下2つの密接に関連した概念に対して使用できます:


@itemize *

@item 
`コルーチン関数': @ref{7ed,,async def} 関数;

@item 
`コルーチンオブジェクト': `コルーチン関数' を呼び出すと返ってくるオブジェクト.
@end itemize
@end quotation
@end cartouche

@subsubheading Task


`Task' は、コルーチンを `並行に' スケジュールするのに使います。

@ref{1c9,,asyncio.create_task()} のような関数で、コルーチンが `Task' にラップされているとき、自動的にコルーチンは即時実行されるようにスケジュールされます:

@example
import asyncio

async def nested():
    return 42

async def main():
    # Schedule nested() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(nested())

    # "task" can now be used to cancel "nested()", or
    # can simply be awaited to wait until it is complete:
    await task

asyncio.run(main())
@end example

@subsubheading Future


@ref{dc6,,Future} は、非同期処理の `最終結果' を表現する特別な `低レベルの' awaitable オブジェクトです。

Future オブジェクトが `待機 (await) されている' とは、Future がどこか他の場所で解決されるまでコルーチンが待機するということです。

asyncioのFutureオブジェクトを使うと、async/awaitとコールバック形式のコードを併用できます。

通常、アプリケーション水準のコードで Future オブジェクトを作る `必要はありません' 。

Future オブジェクトはライブラリや asyncio のAPIで外部に提供されることもあり、await （待機）されることができます:

@example
async def main():
    await function_that_returns_a_future_object()

    # this is also valid:
    await asyncio.gather(
        function_that_returns_a_future_object(),
        some_python_coroutine()
    )
@end example

Future オブジェクトを返す低レベル関数の良い例は @ref{ae6,,loop.run_in_executor()} です。

@node Task の作成,タスクのキャンセル,Awaitable,コルーチンと Task
@anchor{library/asyncio-task creating-tasks}@anchor{37d1}
@subsubsection Task の作成


`ソースコード:' Lib/asyncio/tasks.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/tasks.py}


__________________________________________________________________


@geindex create_task() (asyncio モジュール)
@anchor{library/asyncio-task asyncio create_task}@anchor{1c9}
@deffn {の関数} asyncio.create_task (coro, *, name=None, context=None, eager_start=None, **kwargs)

`coro' @ref{37b8,,coroutine} を @ref{1c7,,Task} でラップし、その実行をスケジュールします。
Task オブジェクトを返します。

The full function signature is largely the same as that of the
@ref{1c7,,Task} constructor (or factory) - all of the keyword arguments to
this function are passed through to that interface.

省略可能なキーワード引数 `context' によって、`coro' を実行するためのカスタムの @ref{177,,contextvars.Context} を指定できます。`context' が省略された場合、現在のコンテキストのコピーが作成されます。

An optional keyword-only `eager_start' argument allows specifying
if the task should execute eagerly during the call to create_task,
or be scheduled later. If `eager_start' is not passed the mode set
by @ref{1c8,,loop.set_task_factory()} will be used.

その Task オブジェクトは @ref{d01,,get_running_loop()} から返されたループの中で実行されます。現在のスレッドに実行中のループが無い場合は、 @ref{244,,RuntimeError} が送出されます。

@cartouche
@quotation 注釈 
@ref{1cb,,asyncio.TaskGroup.create_task()} is a new alternative
leveraging structural concurrency; it allows for waiting
for a group of related tasks with strong safety guarantees.
@end quotation
@end cartouche

@cartouche
@quotation 重要 
タスクが実行中に消えないように、この関数の結果の参照を保存してください。イベントループは弱い参照のみを保持します。ほかに参照元のないタスクは、完了していなくてもガーベジコレクションされる可能性があります。信頼性のある "fire-and-forget" バックグラウンドタスクが必要な場合、コレクションを使ってください。

@example
background_tasks = set()

for i in range(10):
    task = asyncio.create_task(some_coro(param=i))

    # Add task to the set. This creates a strong reference.
    background_tasks.add(task)

    # To prevent keeping references to finished tasks forever,
    # make each task remove its own reference from the set after
    # completion:
    task.add_done_callback(background_tasks.discard)
@end example
@end quotation
@end cartouche


Added in version 3.7.



バージョン 3.8 で変更: `name' パラメータを追加しました。



バージョン 3.11 で変更: `context' パラメータを追加しました。



バージョン 3.14 で変更: Added the `eager_start' parameter by passing on all `kwargs'.

@end deffn

@node タスクのキャンセル,Task Groups,Task の作成,コルーチンと Task
@anchor{library/asyncio-task task-cancellation}@anchor{37d2}
@subsubsection タスクのキャンセル


タスクは簡単に、そして安全にキャンセルできます。タスクがキャンセルされた場合、@ref{4d4,,asyncio.CancelledError} が次の機会に送出されます。

It is recommended that coroutines use @code{try/finally} blocks to robustly
perform clean-up logic. In case @ref{4d4,,asyncio.CancelledError}
is explicitly caught, it should generally be propagated when
clean-up is complete. @ref{4d4,,asyncio.CancelledError} directly subclasses
@ref{7d6,,BaseException} so most code will not need to be aware of it.

The asyncio components that enable structured concurrency, like
@ref{4d1,,asyncio.TaskGroup} and @ref{814,,asyncio.timeout()},
are implemented using cancellation internally and might misbehave if
a coroutine swallows @ref{4d4,,asyncio.CancelledError}. Similarly, user code
should not generally call @ref{4d6,,uncancel}.
However, in cases when suppressing @ref{4d4,,asyncio.CancelledError} is
truly desired, it is necessary to also call @code{uncancel()} to completely
remove the cancellation state.

@node Task Groups,スリープ,タスクのキャンセル,コルーチンと Task
@anchor{library/asyncio-task task-groups}@anchor{37d3}@anchor{library/asyncio-task taskgroups}@anchor{37d4}
@subsubsection Task Groups


Task groups combine a task creation API with a convenient
and reliable way to wait for all tasks in the group to finish.

@geindex TaskGroup (asyncio のクラス)
@anchor{library/asyncio-task asyncio TaskGroup}@anchor{4d1}
@deffn {クラス} asyncio.TaskGroup

An @ref{812,,asynchronous context manager}
holding a group of tasks.
Tasks can be added to the group using @ref{1c9,,create_task()}.
All tasks are awaited when the context manager exits.


Added in version 3.11.


@geindex create_task() (asyncio.TaskGroup のメソッド)
@anchor{library/asyncio-task asyncio TaskGroup create_task}@anchor{1cb}
@deffn {メソッド} create_task (coro, *, name=None, context=None, eager_start=None, **kwargs)

Create a task in this task group.
The signature matches that of @ref{1c9,,asyncio.create_task()}.
If the task group is inactive (e.g. not yet entered,
already finished, or in the process of shutting down),
we will close the given @code{coro}.


バージョン 3.13 で変更: Close the given coroutine if the task group is not active.



バージョン 3.14 で変更: Passes on all `kwargs' to @ref{1ca,,loop.create_task()}

@end deffn
@end deffn

以下はプログラム例です:

@example
async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(some_coro(...))
        task2 = tg.create_task(another_coro(...))
    print(f"Both tasks have completed now: @{task1.result()@}, @{task2.result()@}")
@end example

The @code{async with} statement will wait for all tasks in the group to finish.
While waiting, new tasks may still be added to the group
(for example, by passing @code{tg} into one of the coroutines
and calling @code{tg.create_task()} in that coroutine).
Once the last task has finished and the @code{async with} block is exited,
no new tasks may be added to the group.

The first time any of the tasks belonging to the group fails
with an exception other than @ref{4d4,,asyncio.CancelledError},
the remaining tasks in the group are cancelled.
No further tasks can then be added to the group.
At this point, if the body of the @code{async with} statement is still active
(i.e., @ref{19a1,,__aexit__()} hasn't been called yet),
the task directly containing the @code{async with} statement is also cancelled.
The resulting @ref{4d4,,asyncio.CancelledError} will interrupt an @code{await},
but it will not bubble out of the containing @code{async with} statement.

Once all tasks have finished, if any tasks have failed
with an exception other than @ref{4d4,,asyncio.CancelledError},
those exceptions are combined in an
@ref{4d2,,ExceptionGroup} or @ref{566,,BaseExceptionGroup}
(as appropriate; see their documentation)
which is then raised.

Two base exceptions are treated specially:
If any task fails with @ref{bc5,,KeyboardInterrupt} or @ref{f3c,,SystemExit},
the task group still cancels the remaining tasks and waits for them,
but then the initial @ref{bc5,,KeyboardInterrupt} or @ref{f3c,,SystemExit}
is re-raised instead of @ref{4d2,,ExceptionGroup} or @ref{566,,BaseExceptionGroup}.

If the body of the @code{async with} statement exits with an exception
(so @ref{19a1,,__aexit__()} is called with an exception set),
this is treated the same as if one of the tasks failed:
the remaining tasks are cancelled and then waited for,
and non-cancellation exceptions are grouped into an
exception group and raised.
The exception passed into @ref{19a1,,__aexit__()},
unless it is @ref{4d4,,asyncio.CancelledError},
is also included in the exception group.
The same special case is made for
@ref{bc5,,KeyboardInterrupt} and @ref{f3c,,SystemExit} as in the previous paragraph.

Task groups are careful not to mix up the internal cancellation used to
"wake up" their @ref{19a1,,__aexit__()} with cancellation requests
for the task in which they are running made by other parties.
In particular, when one task group is syntactically nested in another,
and both experience an exception in one of their child tasks simultaneously,
the inner task group will process its exceptions, and then the outer task group
will receive another cancellation and process its own exceptions.

In the case where a task group is cancelled externally and also must
raise an @ref{4d2,,ExceptionGroup}, it will call the parent task's
@ref{4d3,,cancel()} method. This ensures that a
@ref{4d4,,asyncio.CancelledError} will be raised at the next
@ref{18d,,await}, so the cancellation is not lost.

Task groups preserve the cancellation count
reported by @ref{4d5,,asyncio.Task.cancelling()}.


バージョン 3.13 で変更: Improved handling of simultaneous internal and external cancellations
and correct preservation of cancellation counts.


@menu
* Terminating a Task Group:: 

@end menu

@node Terminating a Task Group,,,Task Groups
@anchor{library/asyncio-task terminating-a-task-group}@anchor{37d5}
@subsubsection Terminating a Task Group


While terminating a task group is not natively supported by the standard
library, termination can be achieved by adding an exception-raising task
to the task group and ignoring the raised exception:

@example
import asyncio
from asyncio import TaskGroup

class TerminateTaskGroup(Exception):
    """Exception raised to terminate a task group."""

async def force_terminate_task_group():
    """Used to force termination of a task group."""
    raise TerminateTaskGroup()

async def job(task_id, sleep_time):
    print(f'Task @{task_id@}: start')
    await asyncio.sleep(sleep_time)
    print(f'Task @{task_id@}: done')

async def main():
    try:
        async with TaskGroup() as group:
            # spawn some tasks
            group.create_task(job(1, 0.5))
            group.create_task(job(2, 1.5))
            # sleep for 1 second
            await asyncio.sleep(1)
            # add an exception-raising task to force the group to terminate
            group.create_task(force_terminate_task_group())
    except* TerminateTaskGroup:
        pass

asyncio.run(main())
@end example

予想される出力:

@example
Task 1: start
Task 2: start
Task 1: done
@end example

@node スリープ,並行な Task 実行,Task Groups,コルーチンと Task
@anchor{library/asyncio-task sleeping}@anchor{37d6}
@subsubsection スリープ


@geindex sleep() (asyncio モジュール)
@anchor{library/asyncio-task asyncio sleep}@anchor{c64}
@deffn {の関数} async asyncio.sleep (delay, result=None)

`delay' 秒だけ停止します。

`result' が提供されている場合は、コルーチン完了時にそれが呼び出し元に返されます。

@code{sleep()} は常に現在の Task を一時中断し、他の Task が実行されるのを許可します。

delay を 0 に設定することで、他のタスクを実行可能にする最適な方針を提供します。この方法は、実行時間の長い関数が、その実行時間全体にわたってイベントループをブロックしないようにするために利用できます。
@anchor{library/asyncio-task asyncio-example-sleep}@anchor{37d7}
現在の時刻を5秒間、毎秒表示するコルーチンの例:

@example
import asyncio
import datetime

async def display_date():
    loop = asyncio.get_running_loop()
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

asyncio.run(display_date())
@end example


バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.13 で変更: Raises @ref{2ec,,ValueError} if `delay' is @ref{873,,nan}.

@end deffn

@node 並行な Task 実行,Eager Task Factory,スリープ,コルーチンと Task
@anchor{library/asyncio-task running-tasks-concurrently}@anchor{37d8}
@subsubsection 並行な Task 実行


@geindex gather() (asyncio モジュール)
@anchor{library/asyncio-task asyncio gather}@anchor{813}
@deffn {の関数} awaitable asyncio.gather (*aws, return_exceptions=False)

`aws' シーケンスにある @ref{37cf,,awaitable オブジェクト} を `並行' 実行します。

`aws' にある awaitable がコルーチンである場合、自動的に Task としてスケジュールされます。

全ての awaitable が正常終了した場合、その結果は返り値を集めたリストになります。
返り値の順序は、 `aws' での awaitable の順序に相当します。

`return_exceptions' が @code{False} である場合(デフォルト)、@code{gather()} で await しているタスクに対して、最初の例外が直接伝えられます。`aws' に並んでいる他の awaitable は、`キャンセルされずに' 引き続いて実行されます。

`return_exceptions' が @code{True} だった場合、例外は成功した結果と同じように取り扱われ、結果リストに集められます。

@code{gather()} が `キャンセル' された場合、起動された全ての (未完了の) awaitable も `キャンセル' されます。

`aws' シーケンスにある Task あるいは Future が `キャンセル' された場合、 @ref{4d4,,CancelledError} を送出したかのうように扱われます。つまり、この場合 @code{gather()} 呼び出しはキャンセル `されません'。
これは、起動された 1 つの Task あるいは Future のキャンセルが、他の Task あるいは Future のキャンセルを引き起こすのを避けるためです。

@cartouche
@quotation 注釈 
A new alternative to create and run tasks concurrently and
wait for their completion is @ref{4d1,,asyncio.TaskGroup}. `TaskGroup'
provides stronger safety guarantees than `gather' for scheduling a nesting of subtasks:
if a task (or a subtask, a task scheduled by a task)
raises an exception, `TaskGroup' will, while `gather' will not,
cancel the remaining scheduled tasks).
@end quotation
@end cartouche
@anchor{library/asyncio-task asyncio-example-gather}@anchor{37d9}
以下はプログラム例です:

@example
import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task @{name@}: Compute factorial(@{number@}), currently i=@{i@}...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task @{name@}: factorial(@{number@}) = @{f@}")
    return f

async def main():
    # Schedule three calls *concurrently*:
    L = await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )
    print(L)

asyncio.run(main())

# Expected output:
#
#     Task A: Compute factorial(2), currently i=2...
#     Task B: Compute factorial(3), currently i=2...
#     Task C: Compute factorial(4), currently i=2...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3), currently i=3...
#     Task C: Compute factorial(4), currently i=3...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4), currently i=4...
#     Task C: factorial(4) = 24
#     [2, 6, 24]
@end example

@cartouche
@quotation 注釈 
If `return_exceptions' is false, cancelling gather() after it
has been marked done won't cancel any submitted awaitables.
For instance, gather can be marked done after propagating an
exception to the caller, therefore, calling @code{gather.cancel()}
after catching an exception (raised by one of the awaitables) from
gather won't cancel any other awaitables.
@end quotation
@end cartouche


バージョン 3.7 で変更: `gather' 自身がキャンセルされた場合は、 `return_exceptions' の値に関わらずキャンセルが伝搬されます。



バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.10 で非推奨: Deprecation warning is emitted if no positional arguments are provided
or not all positional arguments are Future-like objects
and there is no running event loop.

@end deffn

@node Eager Task Factory,キャンセルからの保護,並行な Task 実行,コルーチンと Task
@anchor{library/asyncio-task eager-task-factory}@anchor{37da}@anchor{library/asyncio-task id2}@anchor{37db}
@subsubsection Eager Task Factory


@geindex eager_task_factory() (asyncio モジュール)
@anchor{library/asyncio-task asyncio eager_task_factory}@anchor{6a2}
@deffn {の関数} asyncio.eager_task_factory (loop, coro, *, name=None, context=None)

A task factory for eager task execution.

When using this factory (via @ref{1c8,,loop.set_task_factory(asyncio.eager_task_factory)}),
coroutines begin execution synchronously during @ref{1c7,,Task} construction.
Tasks are only scheduled on the event loop if they block.
This can be a performance improvement as the overhead of loop scheduling
is avoided for coroutines that complete synchronously.

A common example where this is beneficial is coroutines which employ
caching or memoization to avoid actual I/O when possible.

@cartouche
@quotation 注釈 
Immediate execution of the coroutine is a semantic change.
If the coroutine returns or raises, the task is never scheduled
to the event loop. If the coroutine execution blocks, the task is
scheduled to the event loop. This change may introduce behavior
changes to existing applications. For example,
the application's task execution order is likely to change.
@end quotation
@end cartouche


Added in version 3.12.

@end deffn

@geindex create_eager_task_factory() (asyncio モジュール)
@anchor{library/asyncio-task asyncio create_eager_task_factory}@anchor{6a3}
@deffn {の関数} asyncio.create_eager_task_factory (custom_task_constructor)

Create an eager task factory, similar to @ref{6a2,,eager_task_factory()},
using the provided `custom_task_constructor' when creating a new task instead
of the default @ref{1c7,,Task}.

`custom_task_constructor' must be a `callable' with the signature matching
the signature of @ref{1c7,,Task.__init__}.
The callable must return a @ref{1c7,,asyncio.Task}-compatible object.

This function returns a `callable' intended to be used as a task factory of an
event loop via @ref{1c8,,loop.set_task_factory(factory)}).


Added in version 3.12.

@end deffn

@node キャンセルからの保護,タイムアウト,Eager Task Factory,コルーチンと Task
@anchor{library/asyncio-task shielding-from-cancellation}@anchor{37dc}
@subsubsection キャンセルからの保護


@geindex shield() (asyncio モジュール)
@anchor{library/asyncio-task asyncio shield}@anchor{c65}
@deffn {の関数} awaitable asyncio.shield (aw)

@ref{4d3,,キャンセル} から @ref{37cf,,awaitable オブジェクト} を保護します。

`aw' がコルーチンだった場合、自動的に Task としてスケジュールされます。

文:

@example
task = asyncio.create_task(something())
res = await shield(task)
@end example

は、以下と同じです

@example
res = await something()
@end example

それを含むコルーチンがキャンセルされた場合を `除き'、@code{something()} 内で動作している Task はキャンセルされません。
@code{something()} 側から見るとキャンセルは発生しません。
呼び出し元がキャンセルされた場合でも、 "await" 式は @ref{4d4,,CancelledError} を送出します。

注意: @code{something()} が他の理由 (例えば、原因が自分自身) でキャンセルされた場合は @code{shield()} でも保護できません。

完全にキャンセルを無視したい場合 (推奨はしません) は、 @code{shield()} 関数は次のように try/except 節と組み合わせることになるでしょう:

@example
task = asyncio.create_task(something())
try:
    res = await shield(task)
except CancelledError:
    res = None
@end example

@cartouche
@quotation 重要 
Save a reference to tasks passed to this function, to avoid
a task disappearing mid-execution. The event loop only keeps
weak references to tasks. A task that isn't referenced elsewhere
may get garbage collected at any time, even before it's done.
@end quotation
@end cartouche


バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.10 で非推奨: Deprecation warning is emitted if `aw' is not Future-like object
and there is no running event loop.

@end deffn

@node タイムアウト,要素の終了待機,キャンセルからの保護,コルーチンと Task
@anchor{library/asyncio-task timeouts}@anchor{37dd}
@subsubsection タイムアウト


@geindex timeout() (asyncio モジュール)
@anchor{library/asyncio-task asyncio timeout}@anchor{814}
@deffn {の関数} asyncio.timeout (delay)

Return an @ref{812,,asynchronous context manager}
that can be used to limit the amount of time spent waiting on
something.

`delay' can either be @code{None}, or a float/int number of
seconds to wait. If `delay' is @code{None}, no time limit will
be applied; this can be useful if the delay is unknown when
the context manager is created.

In either case, the context manager can be rescheduled after
creation using @ref{37de,,Timeout.reschedule()}.

以下はプログラム例です:

@example
async def main():
    async with asyncio.timeout(10):
        await long_running_task()
@end example

If @code{long_running_task} takes more than 10 seconds to complete,
the context manager will cancel the current task and handle
the resulting @ref{4d4,,asyncio.CancelledError} internally, transforming it
into a @ref{a36,,TimeoutError} which can be caught and handled.

@cartouche
@quotation 注釈 
The @ref{814,,asyncio.timeout()} context manager is what transforms
the @ref{4d4,,asyncio.CancelledError} into a @ref{a36,,TimeoutError},
which means the @ref{a36,,TimeoutError} can only be caught
`outside' of the context manager.
@end quotation
@end cartouche

Example of catching @ref{a36,,TimeoutError}:

@example
async def main():
    try:
        async with asyncio.timeout(10):
            await long_running_task()
    except TimeoutError:
        print("The long operation timed out, but we've handled it.")

    print("This statement will run regardless.")
@end example

The context manager produced by @ref{814,,asyncio.timeout()} can be
rescheduled to a different deadline and inspected.

@geindex Timeout (asyncio のクラス)
@anchor{library/asyncio-task asyncio Timeout}@anchor{1a40}
@deffn {クラス} asyncio.Timeout (when)

An @ref{812,,asynchronous context manager}
for cancelling overdue coroutines.

Prefer using @ref{814,,asyncio.timeout()} or @ref{1bb3,,asyncio.timeout_at()}
rather than instantiating @code{Timeout} directly.

@code{when} should be an absolute time at which the context should time out,
as measured by the event loop's clock:


@itemize -

@item 
If @code{when} is @code{None}, the timeout will never trigger.

@item 
If @code{when < loop.time()}, the timeout will trigger on the next
iteration of the event loop.
@end itemize

@quotation

@geindex when() (asyncio.Timeout のメソッド)
@anchor{library/asyncio-task asyncio Timeout when}@anchor{37df}
@deffn {メソッド} when () -> float | None

Return the current deadline, or @code{None} if the current
deadline is not set.
@end deffn

@geindex reschedule() (asyncio.Timeout のメソッド)
@anchor{library/asyncio-task asyncio Timeout reschedule}@anchor{37de}
@deffn {メソッド} reschedule (when: float | None)

Reschedule the timeout.
@end deffn

@geindex expired() (asyncio.Timeout のメソッド)
@anchor{library/asyncio-task asyncio Timeout expired}@anchor{37e0}
@deffn {メソッド} expired () -> bool

Return whether the context manager has exceeded its deadline
(expired).
@end deffn
@end quotation
@end deffn

以下はプログラム例です:

@example
async def main():
    try:
        # We do not know the timeout when starting, so we pass `@w{`}None`@w{`}.
        async with asyncio.timeout(None) as cm:
            # We know the timeout now, so we reschedule it.
            new_deadline = get_running_loop().time() + 10
            cm.reschedule(new_deadline)

            await long_running_task()
    except TimeoutError:
        pass

    if cm.expired():
        print("Looks like we haven't finished on time.")
@end example

Timeout context managers can be safely nested.


Added in version 3.11.

@end deffn

@geindex timeout_at() (asyncio モジュール)
@anchor{library/asyncio-task asyncio timeout_at}@anchor{1bb3}
@deffn {の関数} asyncio.timeout_at (when)

Similar to @ref{814,,asyncio.timeout()}, except `when' is the absolute time
to stop waiting, or @code{None}.

以下はプログラム例です:

@example
async def main():
    loop = get_running_loop()
    deadline = loop.time() + 20
    try:
        async with asyncio.timeout_at(deadline):
            await long_running_task()
    except TimeoutError:
        print("The long operation timed out, but we've handled it.")

    print("This statement will run regardless.")
@end example


Added in version 3.11.

@end deffn

@geindex wait_for() (asyncio モジュール)
@anchor{library/asyncio-task asyncio wait_for}@anchor{815}
@deffn {の関数} async asyncio.wait_for (aw, timeout)

`aw' @ref{37cf,,awaitable} が、完了するかタイムアウトになるのを待ちます。

`aw' がコルーチンだった場合、自動的に Task としてスケジュールされます。

`timeout' には @code{None} もしくは待つ秒数の浮動小数点数か整数を指定できます。
`timeout' が @code{None} の場合、 Future が完了するまで待ちます。

If a timeout occurs, it cancels the task and raises
@ref{a36,,TimeoutError}.

Task の @ref{4d3,,キャンセル} を避けるためには、 @ref{c65,,shield()} の中にラップしてください。

この関数は future が実際にキャンセルされるまで待つため、待ち時間の合計は `timeout'  を超えることがあります。キャンセル中に例外が発生した場合は、その例外は伝達されます。

待機が中止された場合 `aw' も中止されます。
@anchor{library/asyncio-task asyncio-example-waitfor}@anchor{37e1}
以下はプログラム例です:

@example
async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except TimeoutError:
        print('timeout!')

asyncio.run(main())

# Expected output:
#
#     timeout!
@end example


バージョン 3.7 で変更: When `aw' is cancelled due to a timeout, @code{wait_for} waits
for `aw' to be cancelled.  Previously, it raised
@ref{a36,,TimeoutError} immediately.



バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.11 で変更: Raises @ref{a36,,TimeoutError} instead of @ref{1ab5,,asyncio.TimeoutError}.

@end deffn

@node 要素の終了待機,スレッド内での実行,タイムアウト,コルーチンと Task
@anchor{library/asyncio-task waiting-primitives}@anchor{37e2}
@subsubsection 要素の終了待機


@geindex wait() (asyncio モジュール)
@anchor{library/asyncio-task asyncio wait}@anchor{6a7}
@deffn {の関数} async asyncio.wait (aws, *, timeout=None, return_when=ALL_COMPLETED)

Run @ref{dc6,,Future} and @ref{1c7,,Task} instances in the `aws'
iterable concurrently and block until the condition specified
by `return_when'.

イテラブル `aws' は空であってはなりません。

Task/Future からなる 2 つの集合 @code{(done, pending)} を返します。

使い方:

@example
done, pending = await asyncio.wait(aws)
@end example

`timeout' (浮動小数点数または整数) が指定されていたら、処理を返すのを待つ最大秒数を制御するのに使われます。

Note that this function does not raise @ref{a36,,TimeoutError}.
Futures or Tasks that aren't done when the timeout occurs are simply
returned in the second set.

`return_when' でこの関数がいつ結果を返すか指定します。指定できる値は以下の 定数のどれか一つです:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

説明

@item

@geindex FIRST_COMPLETED (asyncio モジュール)
@anchor{library/asyncio-task asyncio FIRST_COMPLETED}@anchor{37e3}
@deffn {データ} asyncio.FIRST_COMPLETED
@end deffn

@tab

いずれかのフューチャが終了したかキャンセルされたときに返します。

@item

@geindex FIRST_EXCEPTION (asyncio モジュール)
@anchor{library/asyncio-task asyncio FIRST_EXCEPTION}@anchor{37e4}
@deffn {データ} asyncio.FIRST_EXCEPTION
@end deffn

@tab

The function will return when any future finishes by raising an
exception. If no future raises an exception
then it is equivalent to @ref{37e5,,ALL_COMPLETED}.

@item

@geindex ALL_COMPLETED (asyncio モジュール)
@anchor{library/asyncio-task asyncio ALL_COMPLETED}@anchor{37e5}
@deffn {データ} asyncio.ALL_COMPLETED
@end deffn

@tab

すべてのフューチャが終了したかキャンセルされたときに返します。

@end multitable


@ref{815,,wait_for()} と異なり、  @code{wait()} はタイムアウトが起きたときに Future をキャンセルしません。


バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.11 で変更: Passing coroutine objects to @code{wait()} directly is forbidden.



バージョン 3.12 で変更: Added support for generators yielding tasks.

@end deffn

@geindex as_completed() (asyncio モジュール)
@anchor{library/asyncio-task asyncio as_completed}@anchor{4c6}
@deffn {の関数} asyncio.as_completed (aws, *, timeout=None)

Run @ref{37cf,,awaitable objects} in the `aws' iterable
concurrently. The returned object can be iterated to obtain the results
of the awaitables as they finish.

The object returned by @code{as_completed()} can be iterated as an
@ref{4c7,,asynchronous iterator} or a plain @ref{4c8,,iterator}. When asynchronous
iteration is used, the originally-supplied awaitables are yielded if they
are tasks or futures. This makes it easy to correlate previously-scheduled
tasks with their results. Example:

@example
ipv4_connect = create_task(open_connection("127.0.0.1", 80))
ipv6_connect = create_task(open_connection("::1", 80))
tasks = [ipv4_connect, ipv6_connect]

async for earliest_connect in as_completed(tasks):
    # earliest_connect is done. The result can be obtained by
    # awaiting it or calling earliest_connect.result()
    reader, writer = await earliest_connect

    if earliest_connect is ipv6_connect:
        print("IPv6 connection established.")
    else:
        print("IPv4 connection established.")
@end example

During asynchronous iteration, implicitly-created tasks will be yielded for
supplied awaitables that aren't tasks or futures.

When used as a plain iterator, each iteration yields a new coroutine that
returns the result or raises the exception of the next completed awaitable.
This pattern is compatible with Python versions older than 3.13:

@example
ipv4_connect = create_task(open_connection("127.0.0.1", 80))
ipv6_connect = create_task(open_connection("::1", 80))
tasks = [ipv4_connect, ipv6_connect]

for next_connect in as_completed(tasks):
    # next_connect is not one of the original task objects. It must be
    # awaited to obtain the result value or raise the exception of the
    # awaitable that finishes next.
    reader, writer = await next_connect
@end example

A @ref{a36,,TimeoutError} is raised if the timeout occurs before all awaitables
are done. This is raised by the @code{async for} loop during asynchronous
iteration or by the coroutines yielded during plain iteration.


バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.10 で非推奨: Deprecation warning is emitted if not all awaitable objects in the `aws'
iterable are Future-like objects and there is no running event loop.



バージョン 3.12 で変更: Added support for generators yielding tasks.



バージョン 3.13 で変更: The result can now be used as either an @ref{4c7,,asynchronous iterator}
or as a plain @ref{4c8,,iterator} (previously it was only a plain iterator).

@end deffn

@node スレッド内での実行,外部スレッドからのスケジュール,要素の終了待機,コルーチンと Task
@anchor{library/asyncio-task running-in-threads}@anchor{37e6}
@subsubsection スレッド内での実行


@geindex to_thread() (asyncio モジュール)
@anchor{library/asyncio-task asyncio to_thread}@anchor{ae5}
@deffn {の関数} async asyncio.to_thread (func, /, *args, **kwargs)

別のスレッドで非同期的に関数 `func' を実行します。

この関数に渡された *args と **kwargs は関数 `func' に直接渡されます。また、イベントループスレッドのコンテキスト変数に関数を実行するスレッドからアクセスできるように、現在の @ref{177,,contextvars.Context} も伝播されます。

関数 `func' の最終結果を待ち受けできるコルーチンを返します。

This coroutine function is primarily intended to be used for executing
IO-bound functions/methods that would otherwise block the event loop if
they were run in the main thread. For example:

@example
def blocking_io():
    print(f"start blocking_io at @{time.strftime('%X')@}")
    # Note that time.sleep() can be replaced with any blocking
    # IO-bound operation, such as file operations.
    time.sleep(1)
    print(f"blocking_io complete at @{time.strftime('%X')@}")

async def main():
    print(f"started main at @{time.strftime('%X')@}")

    await asyncio.gather(
        asyncio.to_thread(blocking_io),
        asyncio.sleep(1))

    print(f"finished main at @{time.strftime('%X')@}")


asyncio.run(main())

# Expected output:
#
# started main at 19:50:53
# start blocking_io at 19:50:53
# blocking_io complete at 19:50:54
# finished main at 19:50:54
@end example

Directly calling @code{blocking_io()} in any coroutine would block the event loop
for its duration, resulting in an additional 1 second of run time. Instead,
by using @code{asyncio.to_thread()}, we can run it in a separate thread without
blocking the event loop.

@cartouche
@quotation 注釈 
Due to the @ref{164,,GIL}, @code{asyncio.to_thread()} can typically only be used
to make IO-bound functions non-blocking. However, for extension modules
that release the GIL or alternative Python implementations that don't
have one, @code{asyncio.to_thread()} can also be used for CPU-bound functions.
@end quotation
@end cartouche


Added in version 3.9.

@end deffn

@node 外部スレッドからのスケジュール,イントロスペクション,スレッド内での実行,コルーチンと Task
@anchor{library/asyncio-task scheduling-from-other-threads}@anchor{37e7}
@subsubsection 外部スレッドからのスケジュール


@geindex run_coroutine_threadsafe() (asyncio モジュール)
@anchor{library/asyncio-task asyncio run_coroutine_threadsafe}@anchor{a82}
@deffn {の関数} asyncio.run_coroutine_threadsafe (coro, loop)

与えられたイベントループにコルーチンを送ります。
この処理は、スレッドセーフです。

他の OS スレッドから結果を待つための @ref{13ca,,concurrent.futures.Future} を返します。

この関数は、イベントループが動作しているスレッドとは異なる OS スレッドから呼び出すためのものです。
例えば次のように使います:

@example
def in_thread(loop: asyncio.AbstractEventLoop) -> None:
    # Run some blocking IO
    pathlib.Path("example.txt").write_text("hello world", encoding="utf8")

    # 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=2) == 3

async def amain() -> None:
    # Get the running loop
    loop = asyncio.get_running_loop()

    # Run something in a thread
    await asyncio.to_thread(in_thread, loop)
@end example

It's also possible to run the other way around.  Example:

@example
@@contextlib.contextmanager
def loop_in_thread() -> Generator[asyncio.AbstractEventLoop]:
    loop_fut = concurrent.futures.Future[asyncio.AbstractEventLoop]()
    stop_event = asyncio.Event()

    async def main() -> None:
        loop_fut.set_result(asyncio.get_running_loop())
        await stop_event.wait()

    with concurrent.futures.ThreadPoolExecutor(1) as tpe:
        complete_fut = tpe.submit(asyncio.run, main())
        for fut in concurrent.futures.as_completed((loop_fut, complete_fut)):
            if fut is loop_fut:
                loop = loop_fut.result()
                try:
                    yield loop
                finally:
                    loop.call_soon_threadsafe(stop_event.set)
            else:
                fut.result()

# Create a loop in another thread
with loop_in_thread() as loop:
    # 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=2) == 3
@end example

コルーチンから例外が送出された場合、返された Future に通知されます。
これはイベントループの Task をキャンセルするのにも使えます:

@example
try:
    result = future.result(timeout)
except TimeoutError:
    print('The coroutine took too long, cancelling the task...')
    future.cancel()
except Exception as exc:
    print(f'The coroutine raised an exception: @{exc!r@}')
else:
    print(f'The coroutine returned: @{result!r@}')
@end example

このドキュメントの @ref{37e8,,並行処理とマルチスレッド処理} 節を参照してください。

他の asyncio 関数とは異なり、この関数は明示的に渡される `loop' 引数を必要とします。


Added in version 3.5.1.

@end deffn

@node イントロスペクション,Task オブジェクト,外部スレッドからのスケジュール,コルーチンと Task
@anchor{library/asyncio-task introspection}@anchor{37e9}
@subsubsection イントロスペクション


@geindex current_task() (asyncio モジュール)
@anchor{library/asyncio-task asyncio current_task}@anchor{6a5}
@deffn {の関数} asyncio.current_task (loop=None)

現在実行中の @ref{1c7,,Task} インスタンスを返します。実行中の Task が無い場合は @code{None} を返します。

`loop' が @code{None} の場合、 @ref{d01,,get_running_loop()} が現在のループを取得するのに使われます。


Added in version 3.7.

@end deffn

@geindex all_tasks() (asyncio モジュール)
@anchor{library/asyncio-task asyncio all_tasks}@anchor{b4f}
@deffn {の関数} asyncio.all_tasks (loop=None)

ループで実行された @ref{1c7,,Task} オブジェクトでまだ完了していないものの集合を返します。

`loop' が @code{None} の場合、 @ref{d01,,get_running_loop()} は現在のループを取得するのに使われます。


Added in version 3.7.

@end deffn

@geindex iscoroutine() (asyncio モジュール)
@anchor{library/asyncio-task asyncio iscoroutine}@anchor{6a6}
@deffn {の関数} asyncio.iscoroutine (obj)

Return @code{True} if `obj' is a coroutine object.


Added in version 3.4.

@end deffn

@node Task オブジェクト,,イントロスペクション,コルーチンと Task
@anchor{library/asyncio-task asyncio-task-obj}@anchor{37ea}@anchor{library/asyncio-task task-object}@anchor{37eb}
@subsubsection Task オブジェクト


@geindex Task (asyncio のクラス)
@anchor{library/asyncio-task asyncio Task}@anchor{1c7}
@deffn {クラス} asyncio.Task (coro, *, loop=None, name=None, context=None, eager_start=False)

Python @ref{37b8,,コルーチン} を実行する @ref{dc6,,Future 類} オブジェクトです。
スレッドセーフではありません。

Task はイベントループのコルーチンを実行するのに使われます。
Future でコルーチンが待機している場合、 Task は自身のコルーチンの実行を一時停止させ、 Future の完了を待ちます。
Future が `完了' したら、 Task が内包しているコルーチンの実行を再開します。

イベントループは協調スケジューリングを使用します。つまり、イベントループは同時に 1 つの Task のみ実行します。
Task が Future の完了を待っているときは、イベントループは他の Task やコールバックを動作させるか、 IO 処理を実行します。

Task を作成するには高レベルの @ref{1c9,,asyncio.create_task()} 関数、あるいは低レベルの @ref{1ca,,loop.create_task()} 関数や @ref{e71,,ensure_future()} 関数を使用してください。
手作業での Task の実装は推奨されません。

実行中のタスクをキャンセルするためには、@ref{4d3,,cancel()} メソッドを使用します。このメソッドを呼ぶと、タスクはそれを内包するコルーチンに対して @ref{4d4,,CancelledError} 例外を送出します。キャンセルの際にコルーチンが Future オブジェクトを待っていた場合、その Future オブジェクトはキャンセルされます。

@ref{37ec,,cancelled()} は、タスクがキャンセルされたかを調べるのに使用できます。タスクを内包するコルーチンで @ref{4d4,,CancelledError} 例外が抑制されておらず、かつタスクが実際にキャンセルされている場合に、このメソッドは @code{True} を変えます。

@ref{1c7,,asyncio.Task} は、@ref{37ed,,Future.set_result()} と @ref{e78,,Future.set_exception()} を除いて、@ref{dc6,,Future} の API をすべて継承しています。

An optional keyword-only `context' argument allows specifying a
custom @ref{177,,contextvars.Context} for the `coro' to run in.
If no `context' is provided, the Task copies the current context
and later runs its coroutine in the copied context.

An optional keyword-only `eager_start' argument allows eagerly starting
the execution of the @ref{1c7,,asyncio.Task} at task creation time.
If set to @code{True} and the event loop is running, the task will start
executing the coroutine immediately, until the first time the coroutine
blocks. If the coroutine returns or raises without blocking, the task
will be finished eagerly and will skip scheduling to the event loop.


バージョン 3.7 で変更: @ref{28,,contextvars} モジュールのサポートを追加。



バージョン 3.8 で変更: `name' パラメータを追加しました。



バージョン 3.10 で非推奨: Deprecation warning is emitted if `loop' is not specified
and there is no running event loop.



バージョン 3.11 で変更: `context' パラメータを追加しました。



バージョン 3.12 で変更: Added the `eager_start' parameter.


@geindex done() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task done}@anchor{37ee}
@deffn {メソッド} done ()

Task が `完了' しているなら @code{True} を返します。

Task がラップしているコルーチンが値を返すか、例外を送出するか、または Task がキャンセルされたとき、 Task は `完了' します。
@end deffn

@geindex result() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task result}@anchor{37ef}
@deffn {メソッド} result ()

Task の結果を返します。

Task が `完了' している場合、ラップしているコルーチンの結果が返されます (コルーチンが例外を送出された場合、その例外が例外が再送出されます)

Task が `キャンセル' されている場合、このメソッドは @ref{4d4,,CancelledError} 例外を送出します。

If the Task's result isn't yet available, this method raises
an @ref{37f0,,InvalidStateError} exception.
@end deffn

@geindex exception() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task exception}@anchor{37f1}
@deffn {メソッド} exception ()

Task の例外を返します。

ラップされたコルーチンが例外を送出した場合、その例外が返されます。ラップされたコルーチンが正常終了した場合、このメソッドは @code{None} を返します。

Task が `キャンセル' されている場合、このメソッドは @ref{4d4,,CancelledError} 例外を送出します。

Task がまだ `完了' していない場合、このメソッドは @ref{37f0,,InvalidStateError} 例外を送出します。
@end deffn

@geindex add_done_callback() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task add_done_callback}@anchor{37f2}
@deffn {メソッド} add_done_callback (callback, *, context=None)

Task が `完了' したときに実行されるコールバックを追加します。

このメソッドは低水準のコールバックベースのコードでのみ使うべきです。

詳細については @ref{cfe,,Future.add_done_callback()} のドキュメントを参照してください。
@end deffn

@geindex remove_done_callback() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task remove_done_callback}@anchor{37f3}
@deffn {メソッド} remove_done_callback (callback)

コールバックリストから `callback' を削除します。

このメソッドは低水準のコールバックベースのコードでのみ使うべきです。

詳細については @ref{1911,,Future.remove_done_callback()} のドキュメントを参照してください。
@end deffn

@geindex get_stack() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task get_stack}@anchor{37f4}
@deffn {メソッド} get_stack (*, limit=None)

このタスクのスタックフレームのリストを返します。

コルーチンが完了していない場合、これはサスペンドされた時点でのスタックを返します。コルーチンが正常に処理を完了したか、キャンセルされていた場合は空のリストを返します。コルーチンが例外で終了した場合はトレースバックフレームのリストを返します。

フレームは常に古いものから新しい物へ並んでいます。

サスペンドされているコルーチンの場合スタックフレームが 1 個だけ返されます。

オプション引数 `limit' は返すフレームの最大数を指定します; デフォルトでは取得可能な全てのフレームを返します。返されるリストの順番は、スタックが返されるか、トレースバックが返されるかによって変わります: スタックでは新しい順に並んだリストが返されますが、トレースバックでは古い順に並んだリストが返されます（これは traceback モジュールの振る舞いと一致します）。
@end deffn

@geindex print_stack() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task print_stack}@anchor{1ad0}
@deffn {メソッド} print_stack (*, limit=None, file=None)

このタスクのスタックまたはトレースバックを出力します。

このメソッドは @ref{37f4,,get_stack()} によって取得されるフレームに対し、 traceback モジュールと同じような出力を生成します。

引数 `limit' は @ref{37f4,,get_stack()} にそのまま渡されます。

The `file' argument is an I/O stream to which the output
is written; by default output is written to @ref{ccd,,sys.stdout}.
@end deffn

@geindex get_coro() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task get_coro}@anchor{bcf}
@deffn {メソッド} get_coro ()

@ref{1c7,,Task} がラップしているコルーチンオブジェクトを返します。

@cartouche
@quotation 注釈 
This will return @code{None} for Tasks which have already
completed eagerly. See the @ref{37da,,Eager Task Factory}.
@end quotation
@end cartouche


Added in version 3.8.



バージョン 3.12 で変更: Newly added eager task execution means result may be @code{None}.

@end deffn

@geindex get_context() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task get_context}@anchor{37f5}
@deffn {メソッド} get_context ()

Return the @ref{177,,contextvars.Context} object
associated with the task.


Added in version 3.12.

@end deffn

@geindex get_name() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task get_name}@anchor{bd1}
@deffn {メソッド} get_name ()

Task の名前を返します。

Task に対して明示的に名前が設定されていない場合, デフォルトの asyncio Task 実装はタスクをインスタンス化する際にデフォルトの名前を生成します。


Added in version 3.8.

@end deffn

@geindex set_name() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task set_name}@anchor{bd0}
@deffn {メソッド} set_name (value)

Task に名前を設定します。

引数 `value' は文字列に変換可能なオブジェクトであれば何でもかまいません。

Task のデフォルト実装では、名前はオブジェクトの @ref{1c1,,repr()} メソッドの出力で確認できます。


Added in version 3.8.

@end deffn

@geindex cancel() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task cancel}@anchor{4d3}
@deffn {メソッド} cancel (msg=None)

このタスクに、自身のキャンセルを要求します。

If the Task is already `done' or `cancelled', return @code{False},
otherwise, return @code{True}.

The method arranges for a @ref{4d4,,CancelledError} exception to be thrown
into the wrapped coroutine on the next cycle of the event loop.

The coroutine then has a chance to clean up or even deny the
request by suppressing the exception with a @ref{8f8,,try} ...
... @code{except CancelledError} ... @ref{1b0,,finally} block.
Therefore, unlike @ref{1ba9,,Future.cancel()}, @ref{4d3,,Task.cancel()} does
not guarantee that the Task will be cancelled, although
suppressing cancellation completely is not common and is actively
discouraged.  Should the coroutine nevertheless decide to suppress
the cancellation, it needs to call @ref{4d6,,Task.uncancel()} in addition
to catching the exception.


バージョン 3.9 で変更: Added the `msg' parameter.



バージョン 3.11 で変更: The @code{msg} parameter is propagated from cancelled task to its awaiter.

@anchor{library/asyncio-task asyncio-example-task-cancel}@anchor{37f6}
以下の例は、コルーチンがどのようにしてキャンセルのリクエストを阻止するかを示しています:

@example
async def cancel_me():
    print('cancel_me(): before sleep')

    try:
        # Wait for 1 hour
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print('cancel_me(): cancel sleep')
        raise
    finally:
        print('cancel_me(): after sleep')

async def main():
    # Create a "cancel_me" Task
    task = asyncio.create_task(cancel_me())

    # Wait for 1 second
    await asyncio.sleep(1)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main(): cancel_me is cancelled now")

asyncio.run(main())

# Expected output:
#
#     cancel_me(): before sleep
#     cancel_me(): cancel sleep
#     cancel_me(): after sleep
#     main(): cancel_me is cancelled now
@end example
@end deffn

@geindex cancelled() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task cancelled}@anchor{37ec}
@deffn {メソッド} cancelled ()

Task が `キャンセルされた' 場合に @code{True} を返します。

@ref{4d3,,cancel()} メソッドによりキャンセルがリクエストされ、かつ Task がラップしているコルーチンが内部で送出された @ref{4d4,,CancelledError} 例外を伝達したとき、 Task は実際に `キャンセル' されます。
@end deffn

@geindex uncancel() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task uncancel}@anchor{4d6}
@deffn {メソッド} uncancel ()

Decrement the count of cancellation requests to this Task.

Returns the remaining number of cancellation requests.

Note that once execution of a cancelled task completed, further
calls to @ref{4d6,,uncancel()} are ineffective.


Added in version 3.11.


This method is used by asyncio's internals and isn't expected to be
used by end-user code.  In particular, if a Task gets successfully
uncancelled, this allows for elements of structured concurrency like
@ref{37d4,,Task Groups} and @ref{814,,asyncio.timeout()} to continue running,
isolating cancellation to the respective structured block.
For example:

@example
async def make_request_with_timeout():
    try:
        async with asyncio.timeout(1):
            # Structured block affected by the timeout:
            await make_request()
            await make_another_request()
    except TimeoutError:
        log("There was a timeout")
    # Outer code not affected by the timeout:
    await unrelated_code()
@end example

While the block with @code{make_request()} and @code{make_another_request()}
might get cancelled due to the timeout, @code{unrelated_code()} should
continue running even in case of the timeout.  This is implemented
with @ref{4d6,,uncancel()}.  @ref{4d1,,TaskGroup} context managers use
@ref{4d6,,uncancel()} in a similar fashion.

If end-user code is, for some reason, suppressing cancellation by
catching @ref{4d4,,CancelledError}, it needs to call this method to remove
the cancellation state.

When this method decrements the cancellation count to zero,
the method checks if a previous @ref{4d3,,cancel()} call had arranged
for @ref{4d4,,CancelledError} to be thrown into the task.
If it hasn't been thrown yet, that arrangement will be
rescinded (by resetting the internal @code{_must_cancel} flag).
@end deffn


バージョン 3.13 で変更: Changed to rescind pending cancellation requests upon reaching zero.


@geindex cancelling() (asyncio.Task のメソッド)
@anchor{library/asyncio-task asyncio Task cancelling}@anchor{4d5}
@deffn {メソッド} cancelling ()

Return the number of pending cancellation requests to this Task, i.e.,
the number of calls to @ref{4d3,,cancel()} less the number of
@ref{4d6,,uncancel()} calls.

Note that if this number is greater than zero but the Task is
still executing, @ref{37ec,,cancelled()} will still return @code{False}.
This is because this number can be lowered by calling @ref{4d6,,uncancel()},
which can lead to the task not being cancelled after all if the
cancellation requests go down to zero.

This method is used by asyncio's internals and isn't expected to be
used by end-user code.  See @ref{4d6,,uncancel()} for more details.


Added in version 3.11.

@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ストリーム,同期プリミティブ<2>,コルーチンと Task,asyncio --- 非同期 I/O
@anchor{library/asyncio-stream doc}@anchor{37f7}@anchor{library/asyncio-stream asyncio-streams}@anchor{37b9}@anchor{library/asyncio-stream streams}@anchor{37f8}@anchor{library/asyncio-stream translation-repo}@anchor{37f9}
@subsubsection ストリーム


`ソースコード:' Lib/asyncio/streams.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/streams.py}


__________________________________________________________________


ストリームはネットワークコネクションと合わせて動作する高水準の async/await 可能な基本要素です。ストリームはコールバックや低水準のプロトコルやトランスポートを使うことなくデータを送受信することを可能にします。
@anchor{library/asyncio-stream asyncio-example-stream}@anchor{37fa}
以下は asyncio ストリームを使って書いた TCP エコークライアントの例です:

@example
import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    print(f'Send: @{message!r@}')
    writer.write(message.encode())
    await writer.drain()

    data = await reader.read(100)
    print(f'Received: @{data.decode()!r@}')

    print('Close the connection')
    writer.close()
    await writer.wait_closed()

asyncio.run(tcp_echo_client('Hello World!'))
@end example

下記の @ref{37fb,,使用例} 節も参照してください。

@subsubheading ストリーム関数


以下の asyncio のトップレベル関数はストリームの作成や操作を行うことができます:

@geindex open_connection() (asyncio モジュール)
@anchor{library/asyncio-stream asyncio open_connection}@anchor{d0e}
@deffn {の関数} async asyncio.open_connection (host=None, port=None, *, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, happy_eyeballs_delay=None, interleave=None)

ネットワークコネクションを確立し、 @code{(reader, writer)} のオブジェクトのペアを返します。

戻り値の `reader' と `writer' はそれぞれ @ref{1c7d,,StreamReader} と @ref{1a70,,StreamWriter} クラスのインスタンスです。

`limit' は戻り値の @ref{1c7d,,StreamReader} インスタンスが利用するバッファのサイズの上限値を設定します。デフォルトでは `limit' は 64 KiB に設定されます。

残りの引数は直接 @ref{818,,loop.create_connection()} に渡されます。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
@ref{1a70,,StreamWriter} created. To close the socket, call its
@ref{37fc,,close()} method.
@end quotation
@end cartouche


バージョン 3.7 で変更: `ssl_handshake_timeout' 引数が追加されました。



バージョン 3.8 で変更: `happy_eyeballs_delay' と `interleave' が追加されました。



バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。

@end deffn

@geindex start_server() (asyncio モジュール)
@anchor{library/asyncio-stream asyncio start_server}@anchor{d0f}
@deffn {の関数} async asyncio.start_server (client_connected_cb, host=None, port=None, *, limit=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, keep_alive=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)

ソケットサーバーを起動します。

`client_connected_cb' コールバックは新しいクライアントコネクションが確立されるたびに呼び出されます。このコールバックは @ref{1c7d,,StreamReader} と @ref{1a70,,StreamWriter} クラスのインスタンスのペア @code{(reader, writer)} を2つの引数として受け取ります。

`client_connected_cb' には単純な呼び出し可能オブジェクトか、または @ref{37b8,,コルーチン関数} を指定します; コルーチン関数が指定された場合、コールバックの呼び出しは自動的に @ref{1c7,,Task} としてスケジュールされます。

`limit' は戻り値の @ref{1c7d,,StreamReader} インスタンスが利用するバッファのサイズの上限値を設定します。デフォルトでは `limit' は 64 KiB に設定されます。

残りの引数は直接 @ref{d09,,loop.create_server()} に渡されます。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
server created. To close the socket, call the server's
@ref{37fd,,close()} method.
@end quotation
@end cartouche


バージョン 3.7 で変更: `ssl_handshake_timeout' と `start_serving' パラメータが追加されました。



バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。



バージョン 3.13 で変更: Added the `keep_alive' parameter.

@end deffn

@subsubheading Unix ソケット


@geindex open_unix_connection() (asyncio モジュール)
@anchor{library/asyncio-stream asyncio open_unix_connection}@anchor{37fe}
@deffn {の関数} async asyncio.open_unix_connection (path=None, *, limit=None, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

Unix ソケットコネクションを確立し、 @code{(reader, writer)} のオブジェクトのペアを返します。

この関数は @ref{d0e,,open_connection()} と似ていますが Unix ソケットに対して動作します。

@ref{37ff,,loop.create_unix_connection()} のドキュメントも参照してください。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
@ref{1a70,,StreamWriter} created. To close the socket, call its
@ref{37fc,,close()} method.
@end quotation
@end cartouche

@ref{213f,,Availability}: Unix.


バージョン 3.7 で変更: Added the `ssl_handshake_timeout' parameter.
The `path' parameter can now be a @ref{5a1,,path-like object}



バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。

@end deffn

@geindex start_unix_server() (asyncio モジュール)
@anchor{library/asyncio-stream asyncio start_unix_server}@anchor{3800}
@deffn {の関数} async asyncio.start_unix_server (client_connected_cb, path=None, *, limit=None, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True, cleanup_socket=True)

Unix のソケットサーバーを起動します。

@ref{d0f,,start_server()} と似ていますが Unix ソケットに対して動作します。

If `cleanup_socket' is true then the Unix socket will automatically
be removed from the filesystem when the server is closed, unless the
socket has been replaced after the server has been created.

@ref{4ca,,loop.create_unix_server()} のドキュメントも参照してください。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
server created. To close the socket, call the server's
@ref{37fd,,close()} method.
@end quotation
@end cartouche

@ref{213f,,Availability}: Unix.


バージョン 3.7 で変更: Added the `ssl_handshake_timeout' and `start_serving' parameters.
The `path' parameter can now be a @ref{5a1,,path-like object}.



バージョン 3.10 で変更: `loop' パラメータが削除されました。



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。



バージョン 3.13 で変更: Added the `cleanup_socket' parameter.

@end deffn

@menu
* StreamReader:: 
* StreamWriter:: 
* 使用例: 使用例<22>. 

@end menu

@node StreamReader,StreamWriter,,ストリーム
@anchor{library/asyncio-stream streamreader}@anchor{3801}
@subsubsection StreamReader


@geindex StreamReader (asyncio のクラス)
@anchor{library/asyncio-stream asyncio StreamReader}@anchor{1c7d}
@deffn {クラス} asyncio.StreamReader

Represents a reader object that provides APIs to read data
from the IO stream. As an @ref{f74,,asynchronous iterable}, the
object supports the @ref{ca1,,async for} statement.

`StreamReader' オブジェクトを直接インスタンス化することは推奨されません; 代わりに @ref{d0e,,open_connection()} や @ref{d0f,,start_server()} を使ってください。

@geindex feed_eof() (asyncio.StreamReader のメソッド)
@anchor{library/asyncio-stream asyncio StreamReader feed_eof}@anchor{3802}
@deffn {メソッド} feed_eof ()

EOF の肯定応答を行います。
@end deffn

@geindex read() (asyncio.StreamReader のメソッド)
@anchor{library/asyncio-stream asyncio StreamReader read}@anchor{3803}
@deffn {メソッド} async read (n=-1)

ストリームから最大 `n' バイト読み込みます。

`n' が指定されないか @code{-1} が指定されていた場合 EOF になるまで読み込み、読み込まれた全ての @ref{192,,bytes} を返します。EOF を受信し、かつ内部バッファーが空の場合、空の @code{bytes} オブジェクトを返します。

`n' が @code{0} なら、ただちに空の @code{bytes} オブジェクトを返します。

`n' が正なら、内部バッファで最低でも 1 バイトが利用可能になり次第、利用可能な最大 `n' @code{bytes} を返します。1 バイトも読み込まないうちに EOF を受信したなら、空の @code{bytes} オブジェクトを返します。
@end deffn

@geindex readline() (asyncio.StreamReader のメソッド)
@anchor{library/asyncio-stream asyncio StreamReader readline}@anchor{3804}
@deffn {メソッド} async readline ()

1 行読み込みます。 "行" とは、@code{\n} で終了するバイト列のシーケンスです。

EOF を受信し、かつ @code{\n} が見つからない場合、このメソッドは部分的に読み込んだデータを返します。

EOF を受信し、かつ内部バッファーが空の場合、空の @code{bytes} オブジェクトを返します。
@end deffn

@geindex readexactly() (asyncio.StreamReader のメソッド)
@anchor{library/asyncio-stream asyncio StreamReader readexactly}@anchor{e76}
@deffn {メソッド} async readexactly (n)

厳密に `n' バイトのデータを読み出します。

`n' バイトを読み出す前に EOF に達した場合 @ref{1ce8,,IncompleteReadError} を送出します。部分的に読み出したデータを取得するには @ref{3805,,IncompleteReadError.partial} 属性を使ってください。
@end deffn

@geindex readuntil() (asyncio.StreamReader のメソッド)
@anchor{library/asyncio-stream asyncio StreamReader readuntil}@anchor{4d0}
@deffn {メソッド} async readuntil (separator=b'\n')

`separator' が見つかるまでストリームからデータを読み出します。

成功時には、データと区切り文字は内部バッファから削除されます (消費されます)。返されるデータの最後には区切り文字が含まれます。

読み出したデータの量が設定したストリームの上限を超えると @ref{3806,,LimitOverrunError} 例外が送出されます。このときデータは内部バッファーに残され、再度読み出すことができます。

完全な区切り文字が見つかる前に EOF に達すると @ref{1ce8,,IncompleteReadError}  例外が送出され、内部バッファーがリセットされます。このとき @ref{3805,,IncompleteReadError.partial} 属性は区切り文字の一部を含むかもしれません。

The `separator' may also be a tuple of separators. In this
case the return value will be the shortest possible that has any
separator as the suffix. For the purposes of @ref{3806,,LimitOverrunError},
the shortest possible separator is considered to be the one that
matched.


Added in version 3.5.2.



バージョン 3.13 で変更: The `separator' parameter may now be a @ref{614,,tuple} of
separators.

@end deffn

@geindex at_eof() (asyncio.StreamReader のメソッド)
@anchor{library/asyncio-stream asyncio StreamReader at_eof}@anchor{3807}
@deffn {メソッド} at_eof ()

バッファーが空で @ref{3802,,feed_eof()} が呼ばれていた場合 @code{True} を返します。
@end deffn
@end deffn

@node StreamWriter,使用例<22>,StreamReader,ストリーム
@anchor{library/asyncio-stream streamwriter}@anchor{3808}
@subsubsection StreamWriter


@geindex StreamWriter (asyncio のクラス)
@anchor{library/asyncio-stream asyncio StreamWriter}@anchor{1a70}
@deffn {クラス} asyncio.StreamWriter

IO ストリームにデータを書き込むための API を提供するライターオブジェクトを表します。

`StreamWriter' オブジェクトを直接インスタンス化することは推奨されません; 代わりに @ref{d0e,,open_connection()} や @ref{d0f,,start_server()} を使ってください。

@geindex write() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter write}@anchor{3809}
@deffn {メソッド} write (data)

このメソッドは、背後にあるソケットにデータ `data' を即座に書き込みます。書き込みに失敗した場合、データは送信可能になるまで内部の書き込みバッファーに格納されて待機します。

The `data' buffer should be a bytes, bytearray, or C-contiguous one-dimensional
memoryview object.

このメソッドは @code{drain()} メソッドと組み合わせて使うべきです:

@example
stream.write(data)
await stream.drain()
@end example
@end deffn

@geindex writelines() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter writelines}@anchor{380a}
@deffn {メソッド} writelines (data)

このメソッドは、背後にあるソケットにバイトデータのリスト (またはイテラブル) を即座に書き込みます。書き込みに失敗した場合、データは送信可能になるまで内部の書き込みバッファーに格納されて待機します。

このメソッドは @code{drain()} メソッドと組み合わせて使うべきです:

@example
stream.writelines(lines)
await stream.drain()
@end example
@end deffn

@geindex close() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter close}@anchor{37fc}
@deffn {メソッド} close ()

このメソッドはストリームと背後にあるソケットをクローズします。

The method should be used, though not mandatory,
along with the @code{wait_closed()} method:

@example
stream.close()
await stream.wait_closed()
@end example
@end deffn

@geindex can_write_eof() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter can_write_eof}@anchor{380b}
@deffn {メソッド} can_write_eof ()

背後にあるトランスポートが @ref{380c,,write_eof()} メソッドをサポートしている場合 @code{True} を返し、そうでない場合は @code{False} を返します。
@end deffn

@geindex write_eof() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter write_eof}@anchor{380c}
@deffn {メソッド} write_eof ()

バッファーされた書き込みデータを全て書き込んでから、ストリームの書き込み側終端をクローズします。
@end deffn

@geindex transport (asyncio.StreamWriter の属性)
@anchor{library/asyncio-stream asyncio StreamWriter transport}@anchor{380d}
@deffn {の属性} transport

背後にある asyncio トランスポートを返します。
@end deffn

@geindex get_extra_info() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter get_extra_info}@anchor{380e}
@deffn {メソッド} get_extra_info (name, default=None)

オプションのトランスポート情報にアクセスします。詳細は @ref{c93,,BaseTransport.get_extra_info()} を参照してください。
@end deffn

@geindex drain() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter drain}@anchor{1b29}
@deffn {メソッド} async drain ()

ストリームへの書き込み再開に適切な状態になるまで待ちます。使用例:

@example
writer.write(data)
await writer.drain()
@end example

このメソッドは背後にある IO 書き込みバッファーとやりとりを行うフロー制御メソッドです。バッファーのサイズが最高水位点に達した場合、`drain()' はバッファのサイズが最低水位点を下回るまで減量され、書き込み再開可能になるまで書き込みをブロックします。待ち受けの必要がない場合、 @ref{1b29,,drain()} は即座にリターンします。
@end deffn

@geindex start_tls() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter start_tls}@anchor{819}
@deffn {メソッド} async start_tls (sslcontext, *, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

Upgrade an existing stream-based connection to TLS.

引数:


@itemize *

@item 
`sslcontext': 構成済みの @ref{357,,SSLContext} インスタンスです。

@item 
`server_hostname': 対象のサーバーの証明書との照合に使われるホスト名を設定または上書きします。

@item 
`ssl_handshake_timeout' is the time in seconds to wait for the TLS
handshake to complete before aborting the connection.  @code{60.0} seconds
if @code{None} (default).

@item 
`ssl_shutdown_timeout' is the time in seconds to wait for the SSL shutdown
to complete before aborting the connection. @code{30.0} seconds if @code{None}
(default).
@end itemize


Added in version 3.11.



バージョン 3.12 で変更: `ssl_shutdown_timeout' パラメータが追加されました。

@end deffn

@geindex is_closing() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter is_closing}@anchor{d03}
@deffn {メソッド} is_closing ()

ストリームがクローズされたか、またはクローズ処理中の場合に @code{True} を返します。


Added in version 3.7.

@end deffn

@geindex wait_closed() (asyncio.StreamWriter のメソッド)
@anchor{library/asyncio-stream asyncio StreamWriter wait_closed}@anchor{d02}
@deffn {メソッド} async wait_closed ()

ストリームがクローズされるまで待機します。

Should be called after @ref{37fc,,close()} to wait until the underlying
connection is closed, ensuring that all data has been flushed
before e.g. exiting the program.


Added in version 3.7.

@end deffn
@end deffn

@node 使用例<22>,,StreamWriter,ストリーム
@anchor{library/asyncio-stream examples}@anchor{37fb}
@subsubsection 使用例


@menu
* ストリームを使った TCP Echo クライアント:: 
* ストリームを使った TCP Echo サーバー:: 
* HTTP ヘッダーの取得:: 
* ストリームを使ってデータを待つオープンソケットの登録:: 

@end menu

@node ストリームを使った TCP Echo クライアント,ストリームを使った TCP Echo サーバー,,使用例<22>
@anchor{library/asyncio-stream asyncio-tcp-echo-client-streams}@anchor{380f}@anchor{library/asyncio-stream tcp-echo-client-using-streams}@anchor{3810}
@subsubsection ストリームを使った TCP Echo クライアント


@ref{d0e,,asyncio.open_connection()} 関数を使った TCP Echo クライアントです:

@example
import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    print(f'Send: @{message!r@}')
    writer.write(message.encode())
    await writer.drain()

    data = await reader.read(100)
    print(f'Received: @{data.decode()!r@}')

    print('Close the connection')
    writer.close()
    await writer.wait_closed()

asyncio.run(tcp_echo_client('Hello World!'))
@end example


@subsubheading 参考


@ref{3811,,TCP エコークライアントプロトコル} の例は低水準の @ref{818,,loop.create_connection()} メソッドを使っています。


@node ストリームを使った TCP Echo サーバー,HTTP ヘッダーの取得,ストリームを使った TCP Echo クライアント,使用例<22>
@anchor{library/asyncio-stream asyncio-tcp-echo-server-streams}@anchor{3812}@anchor{library/asyncio-stream tcp-echo-server-using-streams}@anchor{3813}
@subsubsection ストリームを使った TCP Echo サーバー


@ref{d0f,,asyncio.start_server()} 関数を使った TCP Echo サーバーです:

@example
import asyncio

async def handle_echo(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')

    print(f"Received @{message!r@} from @{addr!r@}")

    print(f"Send: @{message!r@}")
    writer.write(data)
    await writer.drain()

    print("Close the connection")
    writer.close()
    await writer.wait_closed()

async def main():
    server = await asyncio.start_server(
        handle_echo, '127.0.0.1', 8888)

    addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
    print(f'Serving on @{addrs@}')

    async with server:
        await server.serve_forever()

asyncio.run(main())
@end example


@subsubheading 参考


@ref{3814,,TCP エコーサーバープロトコル} の例は @ref{d09,,loop.create_server()} メソッドを使っています。


@node HTTP ヘッダーの取得,ストリームを使ってデータを待つオープンソケットの登録,ストリームを使った TCP Echo サーバー,使用例<22>
@anchor{library/asyncio-stream get-http-headers}@anchor{3815}
@subsubsection HTTP ヘッダーの取得


コマンドラインから渡された URL の HTTP ヘッダーを問い合わせる簡単な例です:

@example
import asyncio
import urllib.parse
import sys

async def print_http_headers(url):
    url = urllib.parse.urlsplit(url)
    if url.scheme == 'https':
        reader, writer = await asyncio.open_connection(
            url.hostname, 443, ssl=True)
    else:
        reader, writer = await asyncio.open_connection(
            url.hostname, 80)

    query = (
        f"HEAD @{url.path or '/'@} HTTP/1.0\r\n"
        f"Host: @{url.hostname@}\r\n"
        f"\r\n"
    )

    writer.write(query.encode('latin-1'))
    while True:
        line = await reader.readline()
        if not line:
            break

        line = line.decode('latin1').rstrip()
        if line:
            print(f'HTTP header> @{line@}')

    # Ignore the body, close the socket
    writer.close()
    await writer.wait_closed()

url = sys.argv[1]
asyncio.run(print_http_headers(url))
@end example

使い方:

@example
python example.py http://example.com/path/page.html
@end example

または HTTPS を使用:

@example
python example.py https://example.com/path/page.html
@end example

@node ストリームを使ってデータを待つオープンソケットの登録,,HTTP ヘッダーの取得,使用例<22>
@anchor{library/asyncio-stream asyncio-example-create-connection-streams}@anchor{3816}@anchor{library/asyncio-stream register-an-open-socket-to-wait-for-data-using-streams}@anchor{3817}
@subsubsection ストリームを使ってデータを待つオープンソケットの登録


@ref{d0e,,open_connection()} 関数を使ってソケットがデータを受信するまで待つコルーチンです:

@example
import asyncio
import socket

async def wait_for_data():
    # Get a reference to the current event loop because
    # we want to access low-level APIs.
    loop = asyncio.get_running_loop()

    # Create a pair of connected sockets.
    rsock, wsock = socket.socketpair()

    # Register the open socket to wait for data.
    reader, writer = await asyncio.open_connection(sock=rsock)

    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())

    # Wait for data
    data = await reader.read(100)

    # Got data, we are done: close the socket
    print("Received:", data.decode())
    writer.close()
    await writer.wait_closed()

    # Close the second socket
    wsock.close()

asyncio.run(wait_for_data())
@end example


@subsubheading 参考


@ref{3818,,プロトコルを使ってオープンしたソケットをデータ待ち受けのために登録する} 例では、低水準のプロトコルと @ref{818,,loop.create_connection()} メソッドを使っています。

@ref{3819,,ファイル記述子の読み出しイベントを監視する} 例では、低水準の @ref{381a,,loop.add_reader()} メソッドを使ってファイル記述子を監視しています。


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 同期プリミティブ<2>,サブプロセス,ストリーム,asyncio --- 非同期 I/O
@anchor{library/asyncio-sync doc}@anchor{381b}@anchor{library/asyncio-sync asyncio-sync}@anchor{37bc}@anchor{library/asyncio-sync synchronization-primitives}@anchor{381c}@anchor{library/asyncio-sync translation-repo}@anchor{381d}
@subsubsection 同期プリミティブ


`ソースコード:' Lib/asyncio/locks.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/locks.py}


__________________________________________________________________


asyncio の同期プリミティブは @ref{f3,,threading} モジュールのそれと類似するようにデザインされていますが、2つの重要な注意事項があります:


@itemize *

@item 
asyncio の同期プリミティブはスレッドセーフではありません。従って OS スレッドの同期に使うべきではありません (代わりに @ref{f3,,threading} を使ってください);

@item 
同期プリミティブのメソッドは `timeout' 引数を受け付けません; タイムアウトを伴う操作を実行するには @ref{815,,asyncio.wait_for()} 関数を使ってください。
@end itemize

asyncio モジュールは以下の基本的な同期プリミティブを持っています:


@itemize *

@item 
@ref{c66,,Lock}

@item 
@ref{2f4,,Event}

@item 
@ref{c67,,Condition}

@item 
@ref{c68,,Semaphore}

@item 
@ref{c69,,BoundedSemaphore}

@item 
@ref{816,,Barrier}
@end itemize


__________________________________________________________________


@menu
* Lock:: 
* Event:: 
* Condition:: 
* Semaphore:: 
* BoundedSemaphore:: 
* Barrier:: 

@end menu

@node Lock,Event,,同期プリミティブ<2>
@anchor{library/asyncio-sync lock}@anchor{381e}
@subsubsection Lock


@geindex Lock (asyncio のクラス)
@anchor{library/asyncio-sync asyncio Lock}@anchor{c66}
@deffn {クラス} asyncio.Lock

asyncio タスクのためのミューテックスロックを実装しています。スレッドセーフではありません。

asyncio ロックは、共有リソースに対する排他的なアクセスを保証するために使うことができます。

Lock の望ましい使用方法は、 @ref{185,,async with} 文と組み合わせて使うことです:

@example
lock = asyncio.Lock()

# ... later
async with lock:
    # access shared state
@end example

これは以下のコードと等価です:

@example
lock = asyncio.Lock()

# ... later
await lock.acquire()
try:
    # access shared state
finally:
    lock.release()
@end example


バージョン 3.10 で変更: `loop' パラメータが削除されました。


@geindex acquire() (asyncio.Lock のメソッド)
@anchor{library/asyncio-sync asyncio Lock acquire}@anchor{381f}
@deffn {メソッド} async acquire ()

ロックを獲得します。

このメソッドはロックが `解除される' まで待機し、ロックを `ロック状態' に変更して @code{True} を返します。

複数のコルーチンが @ref{381f,,acquire()} メソッドによりロックの解除を待ち受けている場合、最終的にただひとつのコルーチンが実行されます。

ロックの獲得は `公平' です: すなわちロックを獲得して実行されるコルーチンは、最初にロックの待ち受けを開始したコルーチンです。
@end deffn

@geindex release() (asyncio.Lock のメソッド)
@anchor{library/asyncio-sync asyncio Lock release}@anchor{3820}
@deffn {メソッド} release ()

ロックを解放します。

ロックが `ロック状態' の場合、 ロックを `解除状態' にしてリターンします。

ロックが `解除状態' の場合、 @ref{244,,RuntimeError} 例外が送出されます。
@end deffn

@geindex locked() (asyncio.Lock のメソッド)
@anchor{library/asyncio-sync asyncio Lock locked}@anchor{3821}
@deffn {メソッド} locked ()

`ロック状態' の場合に @code{True} を返します。
@end deffn
@end deffn

@node Event,Condition,Lock,同期プリミティブ<2>
@anchor{library/asyncio-sync event}@anchor{3822}
@subsubsection Event


@geindex Event (asyncio のクラス)
@anchor{library/asyncio-sync asyncio Event}@anchor{2f4}
@deffn {クラス} asyncio.Event

イベントオブジェクトです。スレッドセーフではありません。

asyncio イベントは、複数の asyncio タスクに対して何らかのイベントが発生したことを通知するために使うことができます。

Event オブジェクトは内部フラグを管理します。フラグの値は @ref{3823,,set()} メソッドにより `true' に、また @ref{3824,,clear()} メソッドにより `false' に設定することができます。 @ref{3825,,wait()} メソッドはフラグが `true' になるまで処理をブロックします。フラグの初期値は `false' です。


バージョン 3.10 で変更: `loop' パラメータが削除されました。

@anchor{library/asyncio-sync asyncio-example-sync-event}@anchor{3826}
以下はプログラム例です:

@example
async def waiter(event):
    print('waiting for it ...')
    await event.wait()
    print('... got it!')

async def main():
    # Create an Event object.
    event = asyncio.Event()

    # Spawn a Task to wait until 'event' is set.
    waiter_task = asyncio.create_task(waiter(event))

    # Sleep for 1 second and set the event.
    await asyncio.sleep(1)
    event.set()

    # Wait until the waiter task is finished.
    await waiter_task

asyncio.run(main())
@end example

@geindex wait() (asyncio.Event のメソッド)
@anchor{library/asyncio-sync asyncio Event wait}@anchor{3825}
@deffn {メソッド} async wait ()

イベントがセットされるまで待機します。

イベントがセットされると、即座に @code{True} を返します。 そうでなければ、他のタスクが @ref{3823,,set()} メソッドを呼び出すまで処理をブロックします。
@end deffn

@geindex set() (asyncio.Event のメソッド)
@anchor{library/asyncio-sync asyncio Event set}@anchor{3823}
@deffn {メソッド} set ()

イベントをセットします。

イベントがセットされるまで待機している全てのタスクは、即座に通知を受けて実行を再開します。
@end deffn

@geindex clear() (asyncio.Event のメソッド)
@anchor{library/asyncio-sync asyncio Event clear}@anchor{3824}
@deffn {メソッド} clear ()

イベントをクリア (アンセット) します

Subsequent tasks awaiting on @ref{3825,,wait()} will now block until the
@ref{3823,,set()} method is called again.
@end deffn

@geindex is_set() (asyncio.Event のメソッド)
@anchor{library/asyncio-sync asyncio Event is_set}@anchor{3827}
@deffn {メソッド} is_set ()

イベントがセットされている場合 @code{True} を返します。
@end deffn
@end deffn

@node Condition,Semaphore,Event,同期プリミティブ<2>
@anchor{library/asyncio-sync condition}@anchor{3828}
@subsubsection Condition


@geindex Condition (asyncio のクラス)
@anchor{library/asyncio-sync asyncio Condition}@anchor{c67}
@deffn {クラス} asyncio.Condition (lock=None)

条件変数オブジェクトです。スレッドセーフではありません。

asyncio 条件プリミティブは何らかのイベントが発生するのを待ち受け、そのイベントを契機として共有リソースへの排他的なアクセスを得るために利用することができます。

本質的に、 Condition オブジェクトは @ref{2f4,,Event} と a @ref{c66,,Lock} の2つのクラスの機能を組み合わせたものです。複数の Condition オブジェクトが単一の Lock を共有することでができます。これにより、共有リソースのそれぞれの状態に関連する異なるタスクの間で、そのリソースへの排他的アクセスを調整することが可能になります。

オプション引数 `lock' は @ref{c66,,Lock} または @code{None} でなければなりません。後者の場合自動的に新しい Lock オブジェクトが生成されます。


バージョン 3.10 で変更: `loop' パラメータが削除されました。


Condition の望ましい使用方法は @ref{185,,async with} 文と組み合わせて使うことです:

@example
cond = asyncio.Condition()

# ... later
async with cond:
    await cond.wait()
@end example

これは以下のコードと等価です:

@example
cond = asyncio.Condition()

# ... later
await cond.acquire()
try:
    await cond.wait()
finally:
    cond.release()
@end example

@geindex acquire() (asyncio.Condition のメソッド)
@anchor{library/asyncio-sync asyncio Condition acquire}@anchor{3829}
@deffn {メソッド} async acquire ()

下層でのロックを獲得します。

このメソッドは下層のロックが  `解除される' まで待機し、ロックを `ロック状態' に変更して @code{True} を返します。
@end deffn

@geindex notify() (asyncio.Condition のメソッド)
@anchor{library/asyncio-sync asyncio Condition notify}@anchor{19f7}
@deffn {メソッド} notify (n=1)

Wake up `n' tasks (1 by default) waiting on this
condition.  If fewer than `n' tasks are waiting they are all awakened.

このメソッドが呼び出される前にロックを獲得しておかなければなりません。また、メソッド呼び出し後速やかにロックを解除しなければなりません。 `解除された' ロックとと共に呼び出された場合、 @ref{244,,RuntimeError} 例外が送出されます。
@end deffn

@geindex locked() (asyncio.Condition のメソッド)
@anchor{library/asyncio-sync asyncio Condition locked}@anchor{382a}
@deffn {メソッド} locked ()

下層のロックを獲得していれば @code{True} を返します。
@end deffn

@geindex notify_all() (asyncio.Condition のメソッド)
@anchor{library/asyncio-sync asyncio Condition notify_all}@anchor{382b}
@deffn {メソッド} notify_all ()

この条件を待ち受けている全てのタスクを起動します。

このメソッドは @ref{19f7,,notify()} と同じように振る舞いますが、待ち受けている全てのタスクを起動します。

このメソッドが呼び出される前にロックを獲得しておかなければなりません。また、メソッド呼び出し後速やかにロックを解除しなければなりません。 `解除された' ロックとと共に呼び出された場合、 @ref{244,,RuntimeError} 例外が送出されます。
@end deffn

@geindex release() (asyncio.Condition のメソッド)
@anchor{library/asyncio-sync asyncio Condition release}@anchor{382c}
@deffn {メソッド} release ()

下層のロックを解除します。

アンロック状態のロックに対して呼び出された場合、@ref{244,,RuntimeError} が送出されます。
@end deffn

@geindex wait() (asyncio.Condition のメソッド)
@anchor{library/asyncio-sync asyncio Condition wait}@anchor{1a20}
@deffn {メソッド} async wait ()

通知を受けるまで待機します。

このメソッドが呼び出された時点で呼び出し元のタスクがロックを獲得していない場合、 @ref{244,,RuntimeError} 例外が送出されます。

このメソッドは下層のロックを解除し、その後 @ref{19f7,,notify()} または @ref{382b,,notify_all()} の呼び出しによって起動されるまで処理をブロックします。いったん起動されると、  Condition は再びロックを獲得し、メソッドは @code{True} を返します。

Note that a task `may' return from this call spuriously,
which is why the caller should always re-check the state
and be prepared to @ref{1a20,,wait()} again. For this reason, you may
prefer to use @ref{382d,,wait_for()} instead.
@end deffn

@geindex wait_for() (asyncio.Condition のメソッド)
@anchor{library/asyncio-sync asyncio Condition wait_for}@anchor{382d}
@deffn {メソッド} async wait_for (predicate)

引数 predicate の条件が `真' になるまで待機します。

The predicate must be a callable which result will be
interpreted as a boolean value.  The method will repeatedly
@ref{1a20,,wait()} until the predicate evaluates to `true'. The final value is the
return value.
@end deffn
@end deffn

@node Semaphore,BoundedSemaphore,Condition,同期プリミティブ<2>
@anchor{library/asyncio-sync semaphore}@anchor{382e}
@subsubsection Semaphore


@geindex Semaphore (asyncio のクラス)
@anchor{library/asyncio-sync asyncio Semaphore}@anchor{c68}
@deffn {クラス} asyncio.Semaphore (value=1)

セマフォオブジェクトです。スレッドセーフではありません。

セマフォは内部のカウンターを管理しています。カウンターは @ref{1a21,,acquire()} メソッドの呼び出しによって減算され、 @ref{382f,,release()} メソッドの呼び出しによって加算されます。カウンターがゼロを下回ることはありません。 @ref{1a21,,acquire()} メソッドが呼び出された時にカウンターがゼロになっていると、セマフォは処理をブロックし、他のタスクが @ref{382f,,release()} メソッドを呼び出すまで待機します。

オプション引数 `value' は内部カウンターの初期値を与えます (デフォルトは @code{1} です)。 指定された値が @code{0} より小さい場合、 @ref{2ec,,ValueError} 例外が送出されます。


バージョン 3.10 で変更: `loop' パラメータが削除されました。


セマフォの望ましい使用方法は、 @ref{185,,async with} 文と組み合わせて使うことです:

@example
sem = asyncio.Semaphore(10)

# ... later
async with sem:
    # work with shared resource
@end example

これは以下のコードと等価です:

@example
sem = asyncio.Semaphore(10)

# ... later
await sem.acquire()
try:
    # work with shared resource
finally:
    sem.release()
@end example

@geindex acquire() (asyncio.Semaphore のメソッド)
@anchor{library/asyncio-sync asyncio Semaphore acquire}@anchor{1a21}
@deffn {メソッド} async acquire ()

セマフォを獲得します。

内部カウンターがゼロより大きい場合、カウンターを1つ減算して即座に @code{True} を返します。内部カウンターがゼロの場合、 @ref{382f,,release()} が呼び出されるまで待機してから @code{True} を返します。
@end deffn

@geindex locked() (asyncio.Semaphore のメソッド)
@anchor{library/asyncio-sync asyncio Semaphore locked}@anchor{3830}
@deffn {メソッド} locked ()

セマフォを直ちに獲得できない場合 @code{True} を返します。
@end deffn

@geindex release() (asyncio.Semaphore のメソッド)
@anchor{library/asyncio-sync asyncio Semaphore release}@anchor{382f}
@deffn {メソッド} release ()

セマフォを解放し、内部カウンターを1つ加算します。セマフォ待ちをしているタスクを起動する可能性があります。

@ref{c69,,BoundedSemaphore} と異なり、 @ref{c68,,Semaphore} は @code{release()} を @code{acquire()} よりも多く呼び出すことを許容します。
@end deffn
@end deffn

@node BoundedSemaphore,Barrier,Semaphore,同期プリミティブ<2>
@anchor{library/asyncio-sync boundedsemaphore}@anchor{3831}
@subsubsection BoundedSemaphore


@geindex BoundedSemaphore (asyncio のクラス)
@anchor{library/asyncio-sync asyncio BoundedSemaphore}@anchor{c69}
@deffn {クラス} asyncio.BoundedSemaphore (value=1)

有限セマフォオブジェクトです。スレッドセーフではありません。

有限セマフォは @ref{c68,,Semaphore} の一種で、 @ref{382f,,release()} メソッドの呼び出しにより内部カウンターが `初期値' よりも増加してしまう場合は @ref{2ec,,ValueError} 例外を送出します。


バージョン 3.10 で変更: `loop' パラメータが削除されました。

@end deffn

@node Barrier,,BoundedSemaphore,同期プリミティブ<2>
@anchor{library/asyncio-sync barrier}@anchor{3832}
@subsubsection Barrier


@geindex Barrier (asyncio のクラス)
@anchor{library/asyncio-sync asyncio Barrier}@anchor{816}
@deffn {クラス} asyncio.Barrier (parties)

A barrier object.  Not thread-safe.

A barrier is a simple synchronization primitive that allows to block until
`parties' number of tasks are waiting on it.
Tasks can wait on the @ref{3833,,wait()} method and would be blocked until
the specified number of tasks end up waiting on @ref{3833,,wait()}.
At that point all of the waiting tasks would unblock simultaneously.

@ref{185,,async with} can be used as an alternative to awaiting on
@ref{3833,,wait()}.

The barrier can be reused any number of times.
@anchor{library/asyncio-sync asyncio-example-barrier}@anchor{3834}
以下はプログラム例です:

@example
async def example_barrier():
   # barrier with 3 parties
   b = asyncio.Barrier(3)

   # create 2 new waiting tasks
   asyncio.create_task(b.wait())
   asyncio.create_task(b.wait())

   await asyncio.sleep(0)
   print(b)

   # The third .wait() call passes the barrier
   await b.wait()
   print(b)
   print("barrier passed")

   await asyncio.sleep(0)
   print(b)

asyncio.run(example_barrier())
@end example

Result of this example is:

@example
<asyncio.locks.Barrier object at 0x... [filling, waiters:2/3]>
<asyncio.locks.Barrier object at 0x... [draining, waiters:0/3]>
barrier passed
<asyncio.locks.Barrier object at 0x... [filling, waiters:0/3]>
@end example


Added in version 3.11.


@geindex wait() (asyncio.Barrier のメソッド)
@anchor{library/asyncio-sync asyncio Barrier wait}@anchor{3833}
@deffn {メソッド} async wait ()

Pass the barrier. When all the tasks party to the barrier have called
this function, they are all unblocked simultaneously.

When a waiting or blocked task in the barrier is cancelled,
this task exits the barrier which stays in the same state.
If the state of the barrier is "filling", the number of waiting task
decreases by 1.

The return value is an integer in the range of 0 to @code{parties-1}, different
for each task. This can be used to select a task to do some special
housekeeping, e.g.:

@example
...
async with barrier as position:
   if position == 0:
      # Only one task prints this
      print('End of *draining phase*')
@end example

This method may raise a @ref{817,,BrokenBarrierError} exception if the
barrier is broken or reset while a task is waiting.
It could raise a @ref{4d4,,CancelledError} if a task is cancelled.
@end deffn

@geindex reset() (asyncio.Barrier のメソッド)
@anchor{library/asyncio-sync asyncio Barrier reset}@anchor{3835}
@deffn {メソッド} async reset ()

Return the barrier to the default, empty state.  Any tasks waiting on it
will receive the @ref{817,,BrokenBarrierError} exception.

If a barrier is broken it may be better to just leave it and create a new one.
@end deffn

@geindex abort() (asyncio.Barrier のメソッド)
@anchor{library/asyncio-sync asyncio Barrier abort}@anchor{3836}
@deffn {メソッド} async abort ()

Put the barrier into a broken state.  This causes any active or future
calls to @ref{3833,,wait()} to fail with the @ref{817,,BrokenBarrierError}.
Use this for example if one of the tasks needs to abort, to avoid infinite
waiting tasks.
@end deffn

@geindex parties (asyncio.Barrier の属性)
@anchor{library/asyncio-sync asyncio Barrier parties}@anchor{3837}
@deffn {の属性} parties

The number of tasks required to pass the barrier.
@end deffn

@geindex n_waiting (asyncio.Barrier の属性)
@anchor{library/asyncio-sync asyncio Barrier n_waiting}@anchor{3838}
@deffn {の属性} n_waiting

The number of tasks currently waiting in the barrier while filling.
@end deffn

@geindex broken (asyncio.Barrier の属性)
@anchor{library/asyncio-sync asyncio Barrier broken}@anchor{3839}
@deffn {の属性} broken

バリアが broken な状態である場合に @code{True} となるブール値。
@end deffn
@end deffn

@geindex BrokenBarrierError
@anchor{library/asyncio-sync asyncio BrokenBarrierError}@anchor{817}
@deffn {例外} asyncio.BrokenBarrierError

@ref{816,,Barrier} オブジェクトがリセットされるか broken な場合に、この例外 (@ref{244,,RuntimeError} のサブクラス) が送出されます。
@end deffn


__________________________________________________________________



バージョン 3.9 で変更: @code{await lock} や @code{yield from lock} およびそれらと @ref{186,,with} 文との組み合わせ (すなわち @code{with await lock} や @code{with (yield from lock)}) によるロックの獲得は削除されました。代わりに @code{async with lock} を使ってください。


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node サブプロセス,キュー,同期プリミティブ<2>,asyncio --- 非同期 I/O
@anchor{library/asyncio-subprocess doc}@anchor{383a}@anchor{library/asyncio-subprocess asyncio-subprocess}@anchor{37ba}@anchor{library/asyncio-subprocess subprocesses}@anchor{383b}@anchor{library/asyncio-subprocess translation-repo}@anchor{383c}
@subsubsection サブプロセス


`ソースコード:' Lib/asyncio/subprocess.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/subprocess.py}, Lib/asyncio/base_subprocess.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/base_subprocess.py}


__________________________________________________________________


このセクションはサブプロセスの生成と管理を行う高水準の async/await asyncio API について説明します。
@anchor{library/asyncio-subprocess asyncio-example-subprocess-shell}@anchor{383d}
以下は、 asyncio モジュールがどのようにシェルコマンドを実行し、結果を取得できるかを示す例です:

@example
import asyncio

async def run(cmd):
    proc = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)

    stdout, stderr = await proc.communicate()

    print(f'[@{cmd!r@} exited with @{proc.returncode@}]')
    if stdout:
        print(f'[stdout]\n@{stdout.decode()@}')
    if stderr:
        print(f'[stderr]\n@{stderr.decode()@}')

asyncio.run(run('ls /zzz'))
@end example

このサンプルコードは以下を出力します:

@example
['ls /zzz' exited with 1]
[stderr]
ls: /zzz: No such file or directory
@end example

全ての asyncio のサブプロセス関数は非同期ですが、 asyncio モジュールはこれらの非同期関数と協調するための多くのツールを提供しているので、複数のサブプロセスを並列に実行して監視することは簡単です。実際、上記のサンプルコードを複数のコマンドを同時に実行するように修正するのはきわめて単純です:

@example
async def main():
    await asyncio.gather(
        run('ls /zzz'),
        run('sleep 1; echo "hello"'))

asyncio.run(main())
@end example

@ref{383e,,使用例} 節も参照してください。

@menu
* サブプロセスの生成:: 
* 定数: 定数<7>. 
* サブプロセスとやりとりする:: 

@end menu

@node サブプロセスの生成,定数<7>,,サブプロセス
@anchor{library/asyncio-subprocess creating-subprocesses}@anchor{383f}
@subsubsection サブプロセスの生成


@geindex create_subprocess_exec() (asyncio モジュール)
@anchor{library/asyncio-subprocess asyncio create_subprocess_exec}@anchor{c6b}
@deffn {の関数} async asyncio.create_subprocess_exec (program, *args, stdin=None, stdout=None, stderr=None, limit=None, **kwds)

サブプロセスを作成します。

The `limit' argument sets the buffer limit for @ref{1c7d,,StreamReader}
wrappers for @ref{3840,,stdout} and @ref{3841,,stderr}
(if @ref{d80,,subprocess.PIPE} is passed to `stdout' and `stderr' arguments).

@ref{3842,,Process} のインスタンスを返します。

他のパラメータについては @ref{3843,,loop.subprocess_exec()} を参照してください。

If the process object is garbage collected while the process is still
running, the child process will be killed.


バージョン 3.10 で変更: `loop' パラメータが削除されました。

@end deffn

@geindex create_subprocess_shell() (asyncio モジュール)
@anchor{library/asyncio-subprocess asyncio create_subprocess_shell}@anchor{c6c}
@deffn {の関数} async asyncio.create_subprocess_shell (cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)

シェルコマンド `cmd' を実行します。

The `limit' argument sets the buffer limit for @ref{1c7d,,StreamReader}
wrappers for @ref{3840,,stdout} and @ref{3841,,stderr}
(if @ref{d80,,subprocess.PIPE} is passed to `stdout' and `stderr' arguments).

@ref{3842,,Process} のインスタンスを返します。

他のパラメータについては @ref{3844,,loop.subprocess_shell()} のドキュメントを参照してください。

If the process object is garbage collected while the process is still
running, the child process will be killed.

@cartouche
@quotation 重要 
シェルインジェクション@footnote{https://en.wikipedia.org/wiki/Shell_injection#Shell_injection} の脆弱性を回避するために全ての空白文字および特殊文字を適切にクオートすることは、アプリケーション側の責任で確実に行ってください。シェルコマンドを構成する文字列内の空白文字と特殊文字のエスケープは、 @ref{582,,shlex.quote()} 関数を使うと適切に行うことができます。
@end quotation
@end cartouche


バージョン 3.10 で変更: `loop' パラメータが削除されました。

@end deffn

@cartouche
@quotation 注釈 
サブプロセスは、 @ref{81d,,ProactorEventLoop} を使えば Windows でも利用可能です。詳しくは @ref{3845,,Windows におけるサブプロセスのサポート} を参照してください。
@end quotation
@end cartouche


@subsubheading 参考


asyncio は以下に挙げるサブプロセスと協調するための `低水準の' API も持っています: @ref{3843,,loop.subprocess_exec()}, @ref{3844,,loop.subprocess_shell()}, @ref{3846,,loop.connect_read_pipe()}, @ref{3847,,loop.connect_write_pipe()} および @ref{3848,,Subprocess Transports} と @ref{3849,,Subprocess Protocols}。


@node 定数<7>,サブプロセスとやりとりする,サブプロセスの生成,サブプロセス
@anchor{library/asyncio-subprocess constants}@anchor{384a}
@subsubsection 定数


@geindex asyncio.subprocess.PIPE (組み込み変数)
@anchor{library/asyncio-subprocess asyncio subprocess PIPE}@anchor{384b}
@deffn {データ} asyncio.subprocess.PIPE

`stdin', `stdout' または `stderr' に渡すことができます。

If `PIPE' is passed to `stdin' argument, the
@ref{384c,,Process.stdin} attribute
will point to a @ref{1a70,,StreamWriter} instance.

If `PIPE' is passed to `stdout' or `stderr' arguments, the
@ref{3840,,Process.stdout} and
@ref{3841,,Process.stderr}
attributes will point to @ref{1c7d,,StreamReader} instances.
@end deffn

@geindex asyncio.subprocess.STDOUT (組み込み変数)
@anchor{library/asyncio-subprocess asyncio subprocess STDOUT}@anchor{384d}
@deffn {データ} asyncio.subprocess.STDOUT

`stderr' 引数に対して利用できる特殊な値で、標準エラー出力が標準出力にリダイレクトされることを意味します。
@end deffn

@geindex asyncio.subprocess.DEVNULL (組み込み変数)
@anchor{library/asyncio-subprocess asyncio subprocess DEVNULL}@anchor{384e}
@deffn {データ} asyncio.subprocess.DEVNULL

プロセスを生成する関数の `stdin', `stdout' または `stderr' 引数に利用できる特殊な値です。対応するサブプロセスのストリームに特殊なファイル @ref{1e14,,os.devnull} が使われることを意味します。
@end deffn

@node サブプロセスとやりとりする,,定数<7>,サブプロセス
@anchor{library/asyncio-subprocess interacting-with-subprocesses}@anchor{384f}
@subsubsection サブプロセスとやりとりする


@ref{c6b,,create_subprocess_exec()} と @ref{c6c,,create_subprocess_shell()} の2つの関数はどちらも `Process' クラスのインスタンスを返します。 `Process' クラスはサブプロセスと通信したり、サブプロセスの完了を監視したりするための高水準のラッパーです。

@geindex asyncio.subprocess.Process (組み込みクラス)
@anchor{library/asyncio-subprocess asyncio subprocess Process}@anchor{3842}
@deffn {クラス} asyncio.subprocess.Process

An object that wraps OS processes created by the
@ref{c6b,,create_subprocess_exec()} and @ref{c6c,,create_subprocess_shell()}
functions.

このクラスは @ref{4b7,,subprocess.Popen} クラスと同様の API を持つように設計されていますが、いくつかの注意すべき違いがあります:


@itemize *

@item 
Popen と異なり、 Process インスタンスは @ref{3759,,poll()} メソッドに相当するメソッドを持っていません;

@item 
the @ref{1a9f,,communicate()} and
@ref{3850,,wait()} methods don't have a
`timeout' parameter: use the @ref{815,,wait_for()} function;

@item 
@ref{ee0,,subprocess.Popen.wait()} メソッドが同期処理のビジーループとして実装されているのに対して、 @ref{3850,,Process.wait()} メソッドは非同期処理です;

@item 
`universal_newlines' パラメータはサポートされていません。
@end itemize

このクラスは @ref{37e8,,スレッド安全ではありません}。

@ref{3851,,サブプロセスとスレッド} 節も参照してください。

@geindex wait() (asyncio.subprocess.Process のメソッド)
@anchor{library/asyncio-subprocess asyncio subprocess Process wait}@anchor{3850}
@deffn {メソッド} async wait ()

子プロセスが終了するのを待ち受けます。

@ref{3852,,returncode} 属性を設定し、その値を返します。

@cartouche
@quotation 注釈 
@code{stdout=PIPE} または @code{stderr=PIPE} を使っており、OS パイプバッファがさらなるデータを受け付けるようになるまで子プロセスをブロックするほど大量の出力を生成場合、このメソッドはデッドロックする可能性があります。この条件を避けるため、パイプを使用する場合は @ref{1a9f,,communicate()} メソッドを使ってください。
@end quotation
@end cartouche
@end deffn

@geindex communicate() (asyncio.subprocess.Process のメソッド)
@anchor{library/asyncio-subprocess asyncio subprocess Process communicate}@anchor{1a9f}
@deffn {メソッド} async communicate (input=None)

プロセスとのやりとりを行います:


@enumerate 

@item 
`stdin' にデータを送信します (`input' が @code{None} でない場合);

@item 
`stdin' を閉じます;

@item 
EOF に達するまで `stdout' および `stderr' からデータを読み出します;

@item 
プロセスが終了するまで待ち受けます。
@end enumerate

`input' オプション引数は子プロセスに送信されるデータ (@ref{192,,bytes} オブジェクト) です。

@code{(stdout_data, stderr_data)} のタプルを返します。

`input' を標準入力 `stdin' nに書き込んでいる時に @ref{1267,,BrokenPipeError} または @ref{126a,,ConnectionResetError} 例外が送出された場合、例外は無視されます。このような条件は、全てのデータが `stdin' に書き込まれる前にプロセスが終了した場合に起こります。

子プロセスの標準入力 `stdin' にデータを送りたい場合、プロセスは @code{stdin=PIPE} を設定して生成する必要があります。同様に、 @code{None} 以外の何らかのデータを戻り値のタプルで受け取りたい場合、プロセスは @code{stdout=PIPE} と @code{stderr=PIPE} のいずれかまたは両方を指定して生成しなければなりません。

プロセスから受信したデータはメモリ上にバッファーされることに注意してください。そのため、返されるデータのサイズが大きいかまたは無制限の場合はこのメソッドを使わないようにしてください。


バージョン 3.12 で変更: `stdin' gets closed when @code{input=None} too.

@end deffn

@geindex send_signal() (asyncio.subprocess.Process のメソッド)
@anchor{library/asyncio-subprocess asyncio subprocess Process send_signal}@anchor{194a}
@deffn {メソッド} send_signal (signal)

子プロセスにシグナル `signal' を送信します。

@cartouche
@quotation 注釈 
On Windows, @ref{15f8,,SIGTERM} is an alias for @ref{3853,,terminate()}.
@code{CTRL_C_EVENT} and @code{CTRL_BREAK_EVENT} can be sent to processes
started with a `creationflags' parameter which includes
@code{CREATE_NEW_PROCESS_GROUP}.
@end quotation
@end cartouche
@end deffn

@geindex terminate() (asyncio.subprocess.Process のメソッド)
@anchor{library/asyncio-subprocess asyncio subprocess Process terminate}@anchor{3853}
@deffn {メソッド} terminate ()

子プロセスを停止します。

On POSIX systems this method sends @ref{15f8,,SIGTERM} to the
child process.

On Windows the Win32 API function @code{TerminateProcess()} is
called to stop the child process.
@end deffn

@geindex kill() (asyncio.subprocess.Process のメソッド)
@anchor{library/asyncio-subprocess asyncio subprocess Process kill}@anchor{3854}
@deffn {メソッド} kill ()

子プロセスを強制終了 (kill) します。

On POSIX systems this method sends @ref{d50,,SIGKILL} to the child
process.

Windows では、このメソッドは @ref{3853,,terminate()} のエイリアスです。
@end deffn

@geindex stdin (asyncio.subprocess.Process の属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process stdin}@anchor{384c}
@deffn {の属性} stdin

Standard input stream (@ref{1a70,,StreamWriter}) or @code{None}
if the process was created with @code{stdin=None}.
@end deffn

@geindex stdout (asyncio.subprocess.Process の属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process stdout}@anchor{3840}
@deffn {の属性} stdout

Standard output stream (@ref{1c7d,,StreamReader}) or @code{None}
if the process was created with @code{stdout=None}.
@end deffn

@geindex stderr (asyncio.subprocess.Process の属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process stderr}@anchor{3841}
@deffn {の属性} stderr

Standard error stream (@ref{1c7d,,StreamReader}) or @code{None}
if the process was created with @code{stderr=None}.
@end deffn

@cartouche
@quotation 警告 
Use the @ref{1a9f,,communicate()} method rather than
@ref{384c,,process.stdin.write()},
@ref{3840,,await process.stdout.read()} or
@ref{3841,,await process.stderr.read()}.
This avoids deadlocks due to streams pausing reading or writing
and blocking the child process.
@end quotation
@end cartouche

@geindex pid (asyncio.subprocess.Process の属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process pid}@anchor{3855}
@deffn {の属性} pid

子プロセスのプロセス番号 (PID) です。

Note that for processes created by the @ref{c6c,,create_subprocess_shell()}
function, this attribute is the PID of the spawned shell.
@end deffn

@geindex returncode (asyncio.subprocess.Process の属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process returncode}@anchor{3852}
@deffn {の属性} returncode

プロセスが終了した時の終了ステータスを返します。

この属性が @code{None} であることは、プロセスがまだ終了していないことを示しています。

負の値 @code{-N} は子プロセスがシグナル @code{N} により中止させられたことを示します (POSIX のみ)。
@end deffn
@end deffn

@menu
* サブプロセスとスレッド:: 
* 使用例: 使用例<23>. 

@end menu

@node サブプロセスとスレッド,使用例<23>,,サブプロセスとやりとりする
@anchor{library/asyncio-subprocess asyncio-subprocess-threads}@anchor{3851}@anchor{library/asyncio-subprocess subprocess-and-threads}@anchor{3856}
@subsubsection サブプロセスとスレッド


標準的な asyncio のイベントループは、異なるスレッドからサブプロセスを実行するのをデフォルトでサポートしています。

Windows のサブプロセスは @ref{81d,,ProactorEventLoop}  (デフォルト) のみ提供され、 @ref{314,,SelectorEventLoop} はサブプロセスをサポートしていません。

標準で提供されない別のイベントループ実装の場合、固有の制限がある可能性があります; それぞれの実装のドキュメントを参照してください。


@subsubheading 参考


@ref{37e8,,並行処理とマルチスレッド処理}


@node 使用例<23>,,サブプロセスとスレッド,サブプロセスとやりとりする
@anchor{library/asyncio-subprocess examples}@anchor{383e}
@subsubsection 使用例


サブプロセスの制御のために @ref{3842,,Process} クラスを使い、サブプロセスの標準出力を読み出すために @ref{1c7d,,StreamReader} を使う例です。
@anchor{library/asyncio-subprocess asyncio-example-create-subprocess-exec}@anchor{3857}
サブプロセスは @ref{c6b,,create_subprocess_exec()} 関数により生成されます:

@example
import asyncio
import sys

async def get_date():
    code = 'import datetime; print(datetime.datetime.now())'

    # Create the subprocess; redirect the standard output
    # into a pipe.
    proc = await asyncio.create_subprocess_exec(
        sys.executable, '-c', code,
        stdout=asyncio.subprocess.PIPE)

    # Read one line of output.
    data = await proc.stdout.readline()
    line = data.decode('ascii').rstrip()

    # Wait for the subprocess exit.
    await proc.wait()
    return line

date = asyncio.run(get_date())
print(f"Current date: @{date@}")
@end example

低水準の API を使って書かれた @ref{3858,,同様の例} も参照してください。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node キュー,例外<16>,サブプロセス,asyncio --- 非同期 I/O
@anchor{library/asyncio-queue doc}@anchor{3859}@anchor{library/asyncio-queue asyncio-queues}@anchor{37bb}@anchor{library/asyncio-queue queues}@anchor{385a}@anchor{library/asyncio-queue translation-repo}@anchor{385b}
@subsubsection キュー


`ソースコード:' Lib/asyncio/queues.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/queues.py}


__________________________________________________________________


asyncio キューは @ref{bb,,queue} モジュールのクラス群と同じ形になるように設計されています。 asyncio キューはスレッドセーフではありませんが、それらは async/await コードから使われるために特別に設計されています。

asyncio キューのメソッドは `timeout' パラメータを持たないことに注意してください; タイムアウトを伴うキューを使った処理を行うには @ref{815,,asyncio.wait_for()} 関数を使ってください。

下記の @ref{385c,,使用例} 節も参照してください。

@menu
* Queue:: 
* 優先度付きのキュー:: 
* LIFO キュー:: 
* 例外: 例外<15>. 
* 使用例: 使用例<24>. 

@end menu

@node Queue,優先度付きのキュー,,キュー
@anchor{library/asyncio-queue queue}@anchor{385d}
@subsubsection Queue


@geindex Queue (asyncio のクラス)
@anchor{library/asyncio-queue asyncio Queue}@anchor{c6a}
@deffn {クラス} asyncio.Queue (maxsize=0)

先入れ先出し (FIFO) キューです。

`maxsize' がゼロ以下の場合、キューは無限長になります。 @code{0} より大きい整数の場合、キューが `maxsize' に達すると @code{await put()} は @ref{385e,,get()} によってキューの要素が除去されるまでブロックします。

標準ライブラリにおけるスレッドベースの @ref{bb,,queue} モジュールと異なり、キューのサイズは常に既知であり、 @ref{385f,,qsize()} メソッドを呼び出すことによって取得することができます。


バージョン 3.10 で変更: `loop' パラメータが削除されました。


このクラスは @ref{37e8,,スレッド安全ではありません}。

@geindex maxsize (asyncio.Queue の属性)
@anchor{library/asyncio-queue asyncio Queue maxsize}@anchor{3860}
@deffn {の属性} maxsize

キューに追加できるアイテム数です。
@end deffn

@geindex empty() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue empty}@anchor{3861}
@deffn {メソッド} empty ()

キューが空ならば @code{True} を、そうでなければ @code{False} を返します。
@end deffn

@geindex full() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue full}@anchor{3862}
@deffn {メソッド} full ()

キューに要素が @ref{3860,,maxsize} 個あれば @code{True} を返します。

If the queue was initialized with @code{maxsize=0} (the default),
then @ref{3862,,full()} never returns @code{True}.
@end deffn

@geindex get() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue get}@anchor{385e}
@deffn {メソッド} async get ()

キューから要素を削除して返します。キューが空の場合項目が利用可能になるまで待機します。

Raises @ref{4cd,,QueueShutDown} if the queue has been shut down and
is empty, or if the queue has been shut down immediately.
@end deffn

@geindex get_nowait() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue get_nowait}@anchor{3863}
@deffn {メソッド} get_nowait ()

直ちに利用できるアイテムがあるときはそれを、そうでなければ @ref{3864,,QueueEmpty} を返します。
@end deffn

@geindex join() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue join}@anchor{fc6}
@deffn {メソッド} async join ()

キューにある全ての要素が取得され、処理されるまでブロックします。

未完了のタスクのカウント値は、キューにアイテムが追加されるときは常に加算され、キューの要素を消費するコルーチンが要素を取り出し、処理を完了したことを通知するために @ref{fc7,,task_done()} を呼び出すと減算されます。未完了のタスクのカウント値がゼロになると、 @ref{fc6,,join()} のブロックは解除されます。
@end deffn

@geindex put() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue put}@anchor{3865}
@deffn {メソッド} async put (item)

要素をキューに入力します。キューが満杯の場合、要素を追加する前に空きスロットが利用できるようになるまで待機します。

Raises @ref{4cd,,QueueShutDown} if the queue has been shut down.
@end deffn

@geindex put_nowait() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue put_nowait}@anchor{3866}
@deffn {メソッド} put_nowait (item)

ブロックせずにアイテムをキューに追加します。

直ちに利用できるスロットがない場合、@ref{3867,,QueueFull} を送出します。
@end deffn

@geindex qsize() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue qsize}@anchor{385f}
@deffn {メソッド} qsize ()

キュー内の要素数を返します。
@end deffn

@geindex shutdown() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue shutdown}@anchor{4cc}
@deffn {メソッド} shutdown (immediate=False)

Put a @ref{c6a,,Queue} instance into a shutdown mode.

The queue can no longer grow.
Future calls to @ref{3865,,put()} raise @ref{4cd,,QueueShutDown}.
Currently blocked callers of @ref{3865,,put()} will be unblocked
and will raise @ref{4cd,,QueueShutDown} in the formerly awaiting task.

If `immediate' is false (the default), the queue can be wound
down normally with @ref{385e,,get()} calls to extract tasks
that have already been loaded.

And if @ref{fc7,,task_done()} is called for each remaining task, a
pending @ref{fc6,,join()} will be unblocked normally.

Once the queue is empty, future calls to @ref{385e,,get()} will
raise @ref{4cd,,QueueShutDown}.

If `immediate' is true, the queue is terminated immediately.
The queue is drained to be completely empty and the count
of unfinished tasks is reduced by the number of tasks drained.
If unfinished tasks is zero, callers of @ref{fc6,,join()}
are unblocked.  Also, blocked callers of @ref{385e,,get()}
are unblocked and will raise @ref{4cd,,QueueShutDown} because the
queue is empty.

Use caution when using @ref{fc6,,join()} with `immediate' set
to true. This unblocks the join even when no work has been done
on the tasks, violating the usual invariant for joining a queue.


Added in version 3.13.

@end deffn

@geindex task_done() (asyncio.Queue のメソッド)
@anchor{library/asyncio-queue asyncio Queue task_done}@anchor{fc7}
@deffn {メソッド} task_done ()

Indicate that a formerly enqueued work item is complete.

Used by queue consumers. For each @ref{385e,,get()} used to
fetch a work item, a subsequent call to @ref{fc7,,task_done()} tells the
queue that the processing on the work item is complete.

@ref{fc6,,join()} が現在ブロック中だった場合、全アイテムが処理されたとき (@ref{3865,,put()} でキューに追加された全アイテムの @ref{fc7,,task_done()} の呼び出しを受信したとき) に再開します。

キューに追加されているアイテム数以上の呼び出しが行われたときに @ref{2ec,,ValueError} を送出します。
@end deffn
@end deffn

@node 優先度付きのキュー,LIFO キュー,Queue,キュー
@anchor{library/asyncio-queue priority-queue}@anchor{3868}
@subsubsection 優先度付きのキュー


@geindex PriorityQueue (asyncio のクラス)
@anchor{library/asyncio-queue asyncio PriorityQueue}@anchor{3869}
@deffn {クラス} asyncio.PriorityQueue

@ref{c6a,,Queue} の変種です; 優先順位にしたがって要素を取り出します (最低順位が最初に取り出されます)。

項目は典型的には @code{(priority_number, data)} 形式のタプルです。
@end deffn

@node LIFO キュー,例外<15>,優先度付きのキュー,キュー
@anchor{library/asyncio-queue lifo-queue}@anchor{386a}
@subsubsection LIFO キュー


@geindex LifoQueue (asyncio のクラス)
@anchor{library/asyncio-queue asyncio LifoQueue}@anchor{386b}
@deffn {クラス} asyncio.LifoQueue

@ref{c6a,,Queue} の変種で、最後に追加された項目を最初に取り出します (後入れ先出し、またはスタック)。
@end deffn

@node 例外<15>,使用例<24>,LIFO キュー,キュー
@anchor{library/asyncio-queue exceptions}@anchor{386c}
@subsubsection 例外


@geindex QueueEmpty
@anchor{library/asyncio-queue asyncio QueueEmpty}@anchor{3864}
@deffn {例外} asyncio.QueueEmpty

この例外は @ref{3863,,get_nowait()} メソッドが空のキューに対して呼ばれたときに送出されます。
@end deffn

@geindex QueueFull
@anchor{library/asyncio-queue asyncio QueueFull}@anchor{3867}
@deffn {例外} asyncio.QueueFull

サイズが `maxsize' に達したキューに対して @ref{3866,,put_nowait()} メソッドが 呼ばれたときに送出される例外です。
@end deffn

@geindex QueueShutDown
@anchor{library/asyncio-queue asyncio QueueShutDown}@anchor{4cd}
@deffn {例外} asyncio.QueueShutDown

Exception raised when @ref{3865,,put()} or @ref{385e,,get()} is
called on a queue which has been shut down.


Added in version 3.13.

@end deffn

@node 使用例<24>,,例外<15>,キュー
@anchor{library/asyncio-queue examples}@anchor{385c}
@subsubsection 使用例

@anchor{library/asyncio-queue asyncio-example-queue-dist}@anchor{386d}
キューを使って、並行処理を行う複数のタスクにワークロードを分散させることができます:

@example
import asyncio
import random
import time


async def worker(name, queue):
    while True:
        # Get a "work item" out of the queue.
        sleep_for = await queue.get()

        # Sleep for the "sleep_for" seconds.
        await asyncio.sleep(sleep_for)

        # Notify the queue that the "work item" has been processed.
        queue.task_done()

        print(f'@{name@} has slept for @{sleep_for:.2f@} seconds')


async def main():
    # Create a queue that we will use to store our "workload".
    queue = asyncio.Queue()

    # Generate random timings and put them into the queue.
    total_sleep_time = 0
    for _ in range(20):
        sleep_for = random.uniform(0.05, 1.0)
        total_sleep_time += sleep_for
        queue.put_nowait(sleep_for)

    # Create three worker tasks to process the queue concurrently.
    tasks = []
    for i in range(3):
        task = asyncio.create_task(worker(f'worker-@{i@}', queue))
        tasks.append(task)

    # Wait until the queue is fully processed.
    started_at = time.monotonic()
    await queue.join()
    total_slept_for = time.monotonic() - started_at

    # Cancel our worker tasks.
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)

    print('====')
    print(f'3 workers slept in parallel for @{total_slept_for:.2f@} seconds')
    print(f'total expected sleep time: @{total_sleep_time:.2f@} seconds')


asyncio.run(main())
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 例外<16>,Call Graph Introspection,キュー,asyncio --- 非同期 I/O
@anchor{library/asyncio-exceptions doc}@anchor{386e}@anchor{library/asyncio-exceptions asyncio-exceptions}@anchor{386f}@anchor{library/asyncio-exceptions exceptions}@anchor{3870}@anchor{library/asyncio-exceptions translation-repo}@anchor{3871}
@subsubsection 例外


`ソースコード:' Lib/asyncio/exceptions.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/exceptions.py}


__________________________________________________________________


@geindex TimeoutError
@anchor{library/asyncio-exceptions asyncio TimeoutError}@anchor{1ab5}
@deffn {例外} asyncio.TimeoutError

操作が指定された期限を超えたときに送出される、非推奨な @ref{a36,,TimeoutError} のエイリアス。


バージョン 3.11 で変更: このクラスは @ref{a36,,TimeoutError} のエイリアスになりました。

@end deffn

@geindex CancelledError
@anchor{library/asyncio-exceptions asyncio CancelledError}@anchor{4d4}
@deffn {例外} asyncio.CancelledError

処理がキャンセルされました。

asyncio タスクがキャンセルされた場合の処理をカスタマイズするために、この例外を一旦キャッチすることができます。 ほとんどの場合、キャッチした例外は再度送出しなければなりません。


バージョン 3.8 で変更: @ref{4d4,,CancelledError} は @ref{bcd,,Exception} ではなく @ref{7d6,,BaseException} のサブクラスになりました。

@end deffn

@geindex InvalidStateError
@anchor{library/asyncio-exceptions asyncio InvalidStateError}@anchor{37f0}
@deffn {例外} asyncio.InvalidStateError

@ref{1c7,,Task} または @ref{dc6,,Future} の内部状態が不正になりました。

すでに結果の値が設定されている `Future' オブジェクトに対してさらに結果の値を再び設定しようとする場合などに送出されることがあります。
@end deffn

@geindex SendfileNotAvailableError
@anchor{library/asyncio-exceptions asyncio SendfileNotAvailableError}@anchor{3872}
@deffn {例外} asyncio.SendfileNotAvailableError

与えられたソケットまたはファイルタイプに対して "sendfile" システムコールが利用可能ではありません。

@ref{244,,RuntimeError} の派生クラスです。
@end deffn

@geindex IncompleteReadError
@anchor{library/asyncio-exceptions asyncio IncompleteReadError}@anchor{1ce8}
@deffn {例外} asyncio.IncompleteReadError

要求された読み込み処理が完了できませんでした。

@ref{37b9,,asyncio ストリーム API} から送出されます。

この例外は @ref{14f1,,EOFError} の派生クラスです。

@geindex expected (asyncio.IncompleteReadError の属性)
@anchor{library/asyncio-exceptions asyncio IncompleteReadError expected}@anchor{3873}
@deffn {の属性} expected

期待される総バイト数 (@ref{19b,,int}) です。
@end deffn

@geindex partial (asyncio.IncompleteReadError の属性)
@anchor{library/asyncio-exceptions asyncio IncompleteReadError partial}@anchor{3805}
@deffn {の属性} partial

ストリームの終端に達するまでに読み込んだ @ref{192,,bytes} 文字列です。
@end deffn
@end deffn

@geindex LimitOverrunError
@anchor{library/asyncio-exceptions asyncio LimitOverrunError}@anchor{3806}
@deffn {例外} asyncio.LimitOverrunError

区切り文字を探している間にバッファサイズの上限に到達しました。

@ref{37b9,,asyncio ストリーム API} から送出されます。

@geindex consumed (asyncio.LimitOverrunError の属性)
@anchor{library/asyncio-exceptions asyncio LimitOverrunError consumed}@anchor{3874}
@deffn {の属性} consumed

未消費のバイトの合計数です。
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Call Graph Introspection,イベントループ,例外<16>,asyncio --- 非同期 I/O
@anchor{library/asyncio-graph doc}@anchor{3875}@anchor{library/asyncio-graph asyncio-graph}@anchor{3876}@anchor{library/asyncio-graph call-graph-introspection}@anchor{3877}@anchor{library/asyncio-graph translation-repo}@anchor{3878}
@subsubsection Call Graph Introspection


`Source code:' Lib/asyncio/graph.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/graph.py}


__________________________________________________________________


asyncio has powerful runtime call graph introspection utilities
to trace the entire call graph of a running `coroutine' or `task', or
a suspended `future'.  These utilities and the underlying machinery
can be used from within a Python program or by external profilers
and debuggers.


Added in version 3.14.


@geindex print_call_graph() (asyncio モジュール)
@anchor{library/asyncio-graph asyncio print_call_graph}@anchor{1cd}
@deffn {の関数} asyncio.print_call_graph (future=None, /, *, file=None, depth=1, limit=None)

Print the async call graph for the current task or the provided
@ref{1c7,,Task} or @ref{dc6,,Future}.

This function prints entries starting from the top frame and going
down towards the invocation point.

The function receives an optional `future' argument.
If not passed, the current running task will be used.

If the function is called on `the current task', the optional
keyword-only `depth' argument can be used to skip the specified
number of frames from top of the stack.

If the optional keyword-only `limit' argument is provided, each call stack
in the resulting graph is truncated to include at most @code{abs(limit)}
entries. If `limit' is positive, the entries left are the closest to
the invocation point. If `limit' is negative, the topmost entries are
left. If `limit' is omitted or @code{None}, all entries are present.
If `limit' is @code{0}, the call stack is not printed at all, only
"awaited by" information is printed.

If `file' is omitted or @code{None}, the function will print
to @ref{ccd,,sys.stdout}.

`Example:'

The following Python code:

@example
import asyncio

async def test():
    asyncio.print_call_graph()

async def main():
    async with asyncio.TaskGroup() as g:
        g.create_task(test(), name='test')

asyncio.run(main())
@end example

このサンプルコードは以下を出力します:

@example
* Task(name='test', id=0x1039f0fe0)
+ Call stack:
|   File 't2.py', line 4, in async test()
+ Awaited by:
   * Task(name='Task-1', id=0x103a5e060)
      + Call stack:
      |   File 'taskgroups.py', line 107, in async TaskGroup.__aexit__()
      |   File 't2.py', line 7, in async main()
@end example
@end deffn

@geindex format_call_graph() (asyncio モジュール)
@anchor{library/asyncio-graph asyncio format_call_graph}@anchor{3879}
@deffn {の関数} asyncio.format_call_graph (future=None, /, *, depth=1, limit=None)

Like @ref{1cd,,print_call_graph()}, but returns a string.
If `future' is @code{None} and there's no current task,
the function returns an empty string.
@end deffn

@geindex capture_call_graph() (asyncio モジュール)
@anchor{library/asyncio-graph asyncio capture_call_graph}@anchor{1cc}
@deffn {の関数} asyncio.capture_call_graph (future=None, /, *, depth=1, limit=None)

Capture the async call graph for the current task or the provided
@ref{1c7,,Task} or @ref{dc6,,Future}.

The function receives an optional `future' argument.
If not passed, the current running task will be used. If there's no
current task, the function returns @code{None}.

If the function is called on `the current task', the optional
keyword-only `depth' argument can be used to skip the specified
number of frames from top of the stack.

Returns a @code{FutureCallGraph} data class object:


@itemize *

@item 
@code{FutureCallGraph(future, call_stack, awaited_by)}

@quotation

Where `future' is a reference to a @ref{dc6,,Future} or
a @ref{1c7,,Task} (or their subclasses.)

@code{call_stack} is a tuple of @code{FrameCallGraphEntry} objects.

@code{awaited_by} is a tuple of @code{FutureCallGraph} objects.
@end quotation

@item 
@code{FrameCallGraphEntry(frame)}

@quotation

Where `frame' is a frame object of a regular Python function
in the call stack.
@end quotation
@end itemize
@end deffn

@menu
* Low level utility functions:: 

@end menu

@node Low level utility functions,,,Call Graph Introspection
@anchor{library/asyncio-graph low-level-utility-functions}@anchor{387a}
@subsubsection Low level utility functions


To introspect an async call graph asyncio requires cooperation from
control flow structures, such as @ref{c65,,shield()} or @ref{4d1,,TaskGroup}.
Any time an intermediate @ref{dc6,,Future} object with low-level APIs like
@ref{cfe,,Future.add_done_callback()} is
involved, the following two functions should be used to inform asyncio
about how exactly such intermediate future objects are connected with
the tasks they wrap or control.

@geindex future_add_to_awaited_by() (asyncio モジュール)
@anchor{library/asyncio-graph asyncio future_add_to_awaited_by}@anchor{387b}
@deffn {の関数} asyncio.future_add_to_awaited_by (future, waiter, /)

Record that `future' is awaited on by `waiter'.

Both `future' and `waiter' must be instances of
@ref{dc6,,Future} or @ref{1c7,,Task} or their subclasses,
otherwise the call would have no effect.

A call to @code{future_add_to_awaited_by()} must be followed by an
eventual call to the @ref{387c,,future_discard_from_awaited_by()} function
with the same arguments.
@end deffn

@geindex future_discard_from_awaited_by() (asyncio モジュール)
@anchor{library/asyncio-graph asyncio future_discard_from_awaited_by}@anchor{387c}
@deffn {の関数} asyncio.future_discard_from_awaited_by (future, waiter, /)

Record that `future' is no longer awaited on by `waiter'.

Both `future' and `waiter' must be instances of
@ref{dc6,,Future} or @ref{1c7,,Task} or their subclasses, otherwise
the call would have no effect.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node イベントループ,Future,Call Graph Introspection,asyncio --- 非同期 I/O
@anchor{library/asyncio-eventloop doc}@anchor{387d}@anchor{library/asyncio-eventloop asyncio-event-loop}@anchor{f76}@anchor{library/asyncio-eventloop event-loop}@anchor{387e}@anchor{library/asyncio-eventloop translation-repo}@anchor{387f}
@subsubsection イベントループ


`ソースコード:' Lib/asyncio/profile.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/profile.py} と Lib/asyncio/pstats.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/pstats.py}


__________________________________________________________________


@subsubheading まえがき


イベントループは全ての asyncio アプリケーションの中核をなす存在です。イベントループは非同期タスクやコールバックを実行し、ネットワーク I/O を処理し、サブプロセスを実行します。

アプリケーション開発者は通常 @ref{2f3,,asyncio.run()} のような高水準の ayncio 関数だけを利用し、ループオブジェクトを参照したり、ループオブジェクトのメソッドを呼び出したりすることはほとんどありません。この節は、イベントループの振る舞いに対して細かい調整が必要な、低水準のコード、ライブラリ、フレームワークの開発者向けです。

@subsubheading イベントループの取得


以下の低水準関数はイベントループの取得、設定、生成するために使います:

@geindex get_running_loop() (asyncio モジュール)
@anchor{library/asyncio-eventloop asyncio get_running_loop}@anchor{d01}
@deffn {の関数} asyncio.get_running_loop ()

現在の OS スレッドで実行中のイベントループを取得します。

Raise a @ref{244,,RuntimeError} if there is no running event loop.

This function can only be called from a coroutine or a callback.


Added in version 3.7.

@end deffn

@geindex get_event_loop() (asyncio モジュール)
@anchor{library/asyncio-eventloop asyncio get_event_loop}@anchor{2f2}
@deffn {の関数} asyncio.get_event_loop ()

現在のイベントループを取得します。

When called from a coroutine or a callback (e.g. scheduled with
call_soon or similar API), this function will always return the
running event loop.

If there is no running event loop set, the function will return
the result of the @code{get_event_loop_policy().get_event_loop()} call.

この関数の振る舞いは (特にイベントループポリシーをカスタマイズした場合) 複雑なため、コルーチンやコールバックでは @ref{2f2,,get_event_loop()}  よりも @ref{d01,,get_running_loop()} を使うほうが好ましいと考えられます。

As noted above, consider using the higher-level @ref{2f3,,asyncio.run()} function,
instead of using these lower level functions to manually create and close an
event loop.


バージョン 3.14 で変更: Raises a @ref{244,,RuntimeError} if there is no current event loop.


@cartouche
@quotation 注釈 
The @code{asyncio} policy system is deprecated and will be removed
in Python 3.16; from there on, this function will return the current
running event loop if present else it will return the
loop set by @ref{1b55,,set_event_loop()}.
@end quotation
@end cartouche
@end deffn

@geindex set_event_loop() (asyncio モジュール)
@anchor{library/asyncio-eventloop asyncio set_event_loop}@anchor{1b55}
@deffn {の関数} asyncio.set_event_loop (loop)

`loop' を OS スレッドの現在のイベントループに設定します。
@end deffn

@geindex new_event_loop() (asyncio モジュール)
@anchor{library/asyncio-eventloop asyncio new_event_loop}@anchor{37c6}
@deffn {の関数} asyncio.new_event_loop ()

新しいイベントループオブジェクトを生成して返します。
@end deffn

@ref{2f2,,get_event_loop()}, @ref{1b55,,set_event_loop()}, および @ref{37c6,,new_event_loop()} 関数の振る舞いは、 @ref{3880,,カスタムイベントループポリシーを設定する} ことにより変更することができます。

@subsubheading 内容


このページは以下の節から構成されます:


@itemize *

@item 
@ref{3881,,イベントループのメソッド} 節は、イベントループ API のリファレンスです。

@item 
@ref{3882,,コールバックハンドル} 節は @ref{cfa,,loop.call_soon()} や @ref{cfc,,loop.call_later()} などのスケジューリングメソッドが返す @ref{1e84,,Handle} や @ref{1add,,TimerHandle} インスタンスについて解説しています。

@item 
@ref{3883,,サーバーオブジェクト} 節は @ref{d09,,loop.create_server()} のようなメソッドが返す型について解説しています。

@item 
@ref{3884,,イベントループの実装} 節は @ref{314,,SelectorEventLoop} と @ref{81d,,ProactorEventLoop} の2つのクラスについて解説しています。

@item 
@ref{3885,,使用例} 節ではイベントループ API の具体的な使い方を紹介しています。
@end itemize

@menu
* イベントループのメソッド:: 
* コールバックのハンドル:: 
* Serverオブジェクト:: 
* イベントループの実装:: 
* 使用例: 使用例<25>. 

@end menu

@node イベントループのメソッド,コールバックのハンドル,,イベントループ
@anchor{library/asyncio-eventloop asyncio-event-loop-methods}@anchor{3886}@anchor{library/asyncio-eventloop event-loop-methods}@anchor{3881}
@subsubsection イベントループのメソッド


イベントループは以下の `低水準な' API を持っています:

@menu
* ループの開始と停止:: 
* コールバックのスケジューリング:: 
* 遅延コールバックのスケジューリング:: 
* フューチャーとタスクの生成:: 
* ネットワーク接続の確立:: 
* ネットワークサーバの生成:: 
* ファイルの転送:: 
* TLS へのアップグレード:: 
* ファイル記述子の監視:: 
* ソケットオブジェクトと直接やりとりする:: 
* DNS:: 
* パイプとやりとりする:: 
* Unix シグナル:: 
* スレッドまたはプロセスプールでコードを実行する:: 
* エラーハンドリング API:: 
* デバッグモードの有効化:: 
* サブプロセスの実行:: 

@end menu

@node ループの開始と停止,コールバックのスケジューリング,,イベントループのメソッド
@anchor{library/asyncio-eventloop running-and-stopping-the-loop}@anchor{3887}
@subsubsection ループの開始と停止


@geindex run_until_complete() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop run_until_complete}@anchor{e72}
@deffn {メソッド} loop.run_until_complete (future)

`フューチャー' (@ref{dc6,,Future} インスタンス) が完了するまで実行します。

引数が @ref{37b8,,コルーチンオブジェクト} の場合、暗黙のうちに @ref{1c7,,asyncio.Task} として実行されるようにスケジュールされます。

Future の結果を返すか、例外を送出します。
@end deffn

@geindex run_forever() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop run_forever}@anchor{3888}
@deffn {メソッド} loop.run_forever ()

@ref{e77,,stop()} が呼び出されるまでイベントループを実行します。

@ref{3888,,run_forever()} メソッドが呼ばれるより前に @ref{e77,,stop()} メソッドが呼ばれた場合、イベントループはタイムアウトをゼロにして一度だけ I/O セレクタの問い合わせ処理を行い、 I/O イベントに対してスケジュールされた全てのコールバック (および既にスケジュール済みのコールバック) を実行したのち、終了します。

@ref{3888,,run_forever()} メソッドを実行中に @ref{e77,,stop()} メソッドが呼び出された場合、イベントループは現在処理されているすべてのコールバックを実行してから終了します。 この場合、コールバックにより新たにスケジュールされるコールバックは実行されないことに注意してください; これら新たにスケジュールされたコールバックは、次に @ref{3888,,run_forever()} または @ref{e72,,run_until_complete()} が呼び出されたときに実行されます。
@end deffn

@geindex stop() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop stop}@anchor{e77}
@deffn {メソッド} loop.stop ()

イベントループを停止します。
@end deffn

@geindex is_running() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop is_running}@anchor{3889}
@deffn {メソッド} loop.is_running ()

イベントループが現在実行中の場合 @code{True} を返します。
@end deffn

@geindex is_closed() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop is_closed}@anchor{fc3}
@deffn {メソッド} loop.is_closed ()

イベントループが閉じられていた場合 @code{True} を返します。
@end deffn

@geindex close() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop close}@anchor{388a}
@deffn {メソッド} loop.close ()

イベントループをクローズします。

この関数が呼び出される時点で、イベントループが実行中であってはいけません。保留中のコールバックはすべて破棄されます。

このメソッドは全てのキューをクリアし、エグゼキューターが実行完了するのを待たずにシャットダウンします。

このメソッドはべき等 (何回実行しても結果は同じ) であり取り消せません。イベントループがクローズされた後、他のいかなるメソッドも呼び出すべきではありません。
@end deffn

@geindex shutdown_asyncgens() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop shutdown_asyncgens}@anchor{e79}
@deffn {メソッド} async loop.shutdown_asyncgens ()

現在オープンになっているすべての @ref{249b,,asynchronous generator} (非同期ジェネレータ) オブジェクトをスケジュールし、 @ref{ad5,,aclose()} メソッドを呼び出すことでそれらをクローズします。 このメソッドの呼び出し後に新しい非同期ジェネレータがイテレートされると、イベントループは警告を発します。このメソッドはスケジュールされたすべての非同期ジェネレータの終了処理を確実に行うために使用すべきです。

@ref{2f3,,asyncio.run()} を使った場合はこの関数を呼び出す必要はありません。

以下はプログラム例です:

@example
try:
    loop.run_forever()
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
@end example


Added in version 3.6.

@end deffn

@geindex shutdown_default_executor() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop shutdown_default_executor}@anchor{ae4}
@deffn {メソッド} async loop.shutdown_default_executor (timeout=None)

Schedule the closure of the default executor and wait for it to join all of
the threads in the @ref{949,,ThreadPoolExecutor}.
Once this method has been called,
using the default executor with @ref{ae6,,loop.run_in_executor()}
will raise a @ref{244,,RuntimeError}.

The `timeout' parameter specifies the amount of time
(in @ref{196,,float} seconds) the executor will be given to finish joining.
With the default, @code{None},
the executor is allowed an unlimited amount of time.

If the `timeout' is reached, a @ref{4d7,,RuntimeWarning} is emitted
and the default executor is terminated
without waiting for its threads to finish joining.

@cartouche
@quotation 注釈 
Do not call this method when using @ref{2f3,,asyncio.run()},
as the latter handles default executor shutdown automatically.
@end quotation
@end cartouche


Added in version 3.9.



バージョン 3.12 で変更: `timeout' 引数が追加されました。

@end deffn

@node コールバックのスケジューリング,遅延コールバックのスケジューリング,ループの開始と停止,イベントループのメソッド
@anchor{library/asyncio-eventloop scheduling-callbacks}@anchor{388b}
@subsubsection コールバックのスケジューリング


@geindex call_soon() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop call_soon}@anchor{cfa}
@deffn {メソッド} loop.call_soon (callback, *args, context=None)

イベントループの次のイテレーションで `callback' に指定したコールバック (@ref{2d9c,,callback}) を `args' 引数で呼び出すようにスケジュールします。

@ref{1e84,,asyncio.Handle} のインスタンスを返します。このインスタンスを使ってスケジュールしたコールバックをキャンセルすることができます。

コールバックは登録された順に呼び出されます。各コールバックは厳密に1回だけ呼び出されます。

The optional keyword-only `context' argument specifies a
custom @ref{177,,contextvars.Context} for the `callback' to run in.
Callbacks use the current context when no `context' is provided.

Unlike @ref{cfb,,call_soon_threadsafe()}, this method is not thread-safe.
@end deffn

@geindex call_soon_threadsafe() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop call_soon_threadsafe}@anchor{cfb}
@deffn {メソッド} loop.call_soon_threadsafe (callback, *args, context=None)

A thread-safe variant of @ref{cfa,,call_soon()}. When scheduling callbacks from
another thread, this function `must' be used, since @ref{cfa,,call_soon()} is not
thread-safe.

This function is safe to be called from a reentrant context or signal handler,
however, it is not safe or fruitful to use the returned handle in such contexts.

すでにクローズされたイベントループに対してこのメソッドが呼び出された場合 @ref{244,,RuntimeError} 例外を送出します。これはメインアプリケーションが終了しているにもかかわらずセカンダリスレッドでメソッドが呼び出されるといった場合に起こりえます。

このドキュメントの @ref{37e8,,並行処理とマルチスレッド処理} 節を参照してください。


バージョン 3.7 で変更: キーワード引数 `context' が追加されました。詳細は 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} を参照してください。

@end deffn
@anchor{library/asyncio-eventloop asyncio-pass-keywords}@anchor{388c}
@cartouche
@quotation 注釈 
ほとんどの @ref{b,,asyncio} モジュールのスケジューリング関数は、キーワード引数をコールバックに渡すことを許していません。キーワード引数を渡すためには @ref{217,,functools.partial()} を使ってください:

@example
# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
@end example

asyncio は partial オブジェクトのデバッグメッセージやエラーメッセージをよりよく可視化することができるため、通常はラムダ式よりも partial オブジェクトを使う方が便利です。
@end quotation
@end cartouche

@node 遅延コールバックのスケジューリング,フューチャーとタスクの生成,コールバックのスケジューリング,イベントループのメソッド
@anchor{library/asyncio-eventloop asyncio-delayed-calls}@anchor{388d}@anchor{library/asyncio-eventloop scheduling-delayed-callbacks}@anchor{388e}
@subsubsection 遅延コールバックのスケジューリング


イベントループは、コールバック関数を未来のある時点で呼び出されるようにスケジュールする仕組みを提供します。イベントループは時刻が戻らない単調な時計 (monotonic clock) を使って時刻を追跡します。

@geindex call_later() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop call_later}@anchor{cfc}
@deffn {メソッド} loop.call_later (delay, callback, *args, context=None)

`delay' 秒経過後にコールバック関数 `callback' を呼び出すようにスケジュールします。 `delay' には整数または浮動小数点数を指定します。

@ref{1add,,asyncio.TimerHandle} のインスタンスを返します。このインスタンスを使ってスケジュールしたコールバックをキャンセルすることができます。

`callback' は厳密に一度だけ呼び出されます。2つのコールバックが完全に同じ時間にスケジュールされた場合、呼び出しの順序は未定義です。

The optional positional `args' will be passed to the callback when
it is called. Use @ref{217,,functools.partial()}
@ref{388c,,to pass keyword arguments} to
`callback'.

オプションのキーワード引数 `context' を使って、コールバック*callback* を実行する際のコンテキスト @ref{177,,contextvars.Context} を設定することができます。コンテキスト `context' が指定されない場合は現在のコンテキストが使われます。

@cartouche
@quotation 注釈 
For performance, callbacks scheduled with @ref{cfc,,loop.call_later()}
may run up to one clock-resolution early (see
@code{time.get_clock_info('monotonic').resolution}).
@end quotation
@end cartouche


バージョン 3.7 で変更: キーワード引数 `context' が追加されました。詳細は 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} を参照してください。



バージョン 3.8 で変更: Python 3.7 またはそれ以前のバージョンでは、デフォルトイベントループの実装を利用した場合に遅延時間 `delay' が1日を超えることができませんでした。この問題は Python 3.8 で修正されました。

@end deffn

@geindex call_at() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop call_at}@anchor{cfd}
@deffn {メソッド} loop.call_at (when, callback, *args, context=None)

絶対値の時刻 `when' (整数または浮動小数点数) にコールバックを呼び出すようにスケジュールします。 @ref{388f,,loop.time()} と同じ参照時刻を使用します。

このメソッドの振る舞いは @ref{cfc,,call_later()} と同じです。

@ref{1add,,asyncio.TimerHandle} のインスタンスを返します。このインスタンスを使ってスケジュールしたコールバックをキャンセルすることができます。

@cartouche
@quotation 注釈 
For performance, callbacks scheduled with @ref{cfd,,loop.call_at()}
may run up to one clock-resolution early (see
@code{time.get_clock_info('monotonic').resolution}).
@end quotation
@end cartouche


バージョン 3.7 で変更: キーワード引数 `context' が追加されました。詳細は 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} を参照してください。



バージョン 3.8 で変更: Python 3.7 またはそれ以前のバージョンでは、デフォルトイベントループの実装を利用した場合に現在の時刻と `when' との差が1日を超えることができませんでした。この問題は Python 3.8 で修正されました。

@end deffn

@geindex time() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop time}@anchor{388f}
@deffn {メソッド} loop.time ()

現在の時刻を @ref{196,,float} 値で返します。時刻はイベントループが内部で参照している時刻が戻らない単調な時計 (monotonic clock) に従います。
@end deffn

@cartouche
@quotation 注釈 

バージョン 3.8 で変更: Python 3.7 またはそれ以前のバージョンでは、タイムアウト (相対値 `delay' もしくは絶対値 `when') は1日を超えることができませんでした。この問題は Python 3.8 で修正されました。

@end quotation
@end cartouche


@subsubheading 参考


関数 @ref{c64,,asyncio.sleep()}。


@node フューチャーとタスクの生成,ネットワーク接続の確立,遅延コールバックのスケジューリング,イベントループのメソッド
@anchor{library/asyncio-eventloop creating-futures-and-tasks}@anchor{3890}
@subsubsection フューチャーとタスクの生成


@geindex create_future() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop create_future}@anchor{e74}
@deffn {メソッド} loop.create_future ()

イベントループに接続した @ref{dc6,,asyncio.Future} オブジェクトを生成します。

asyncio でフューチャーオブジェクトを作成するために推奨される方法です。このメソッドにより、サードパーティ製のイベントループがFutures クラスの(パフォーマンスや計測方法が優れた) 代替実装を提供することを可能にします。


Added in version 3.5.2.

@end deffn

@geindex create_task() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop create_task}@anchor{1ca}
@deffn {メソッド} loop.create_task (coro, *, name=None, context=None, eager_start=None, **kwargs)

@ref{37b8,,コルーチン}  `coro' の実行をスケジュールします。 @ref{1c7,,Task} オブジェクトを返します。

サードパーティのイベントループは相互運用のための自身の @ref{1c7,,Task} のサブクラスを使用できます。この場合、結果は @ref{1c7,,Task} のサブクラスになります。

The full function signature is largely the same as that of the
@ref{1c7,,Task} constructor (or factory) - all of the keyword arguments to
this function are passed through to that interface.

`name' 引数が指定され、値が @code{None} でない場合、 @ref{bd0,,Task.set_name()} メソッドにより `name' がタスクの名前として設定されます。

省略可能なキーワード引数 `context' によって、`coro' を実行するためのカスタムの @ref{177,,contextvars.Context} を指定できます。`context' が省略された場合、現在のコンテキストのコピーが作成されます。

An optional keyword-only `eager_start' argument allows specifying
if the task should execute eagerly during the call to create_task,
or be scheduled later. If `eager_start' is not passed the mode set
by @ref{1c8,,loop.set_task_factory()} will be used.


バージョン 3.8 で変更: `name' パラメータを追加しました。



バージョン 3.11 で変更: `context' パラメータを追加しました。



バージョン 3.13.3 で変更: Added @code{kwargs} which passes on arbitrary extra parameters, including  @code{name} and @code{context}.



バージョン 3.13.4 で変更: Rolled back the change that passes on `name' and `context' (if it is None),
while still passing on other arbitrary keyword arguments (to avoid breaking backwards compatibility with 3.13.3).



バージョン 3.14 で変更: All `kwargs' are now passed on. The `eager_start' parameter works with eager task factories.

@end deffn

@geindex set_task_factory() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop set_task_factory}@anchor{1c8}
@deffn {メソッド} loop.set_task_factory (factory)

@ref{1ca,,loop.create_task()} が使用するタスクファクトリーを設定します。

If `factory' is @code{None} the default task factory will be set.
Otherwise, `factory' must be a `callable' with the signature matching
@code{(loop, coro, **kwargs)}, where `loop' is a reference to the active
event loop, and `coro' is a coroutine object.  The callable
must pass on all `kwargs', and return a @ref{1c7,,asyncio.Task}-compatible object.


バージョン 3.13.3 で変更: Required that all `kwargs' are passed on to @ref{1c7,,asyncio.Task}.



バージョン 3.13.4 で変更: `name' is no longer passed to task factories. `context' is no longer passed
to task factories if it is @code{None}.


バージョン 3.14 で変更: `name' and `context' are now unconditionally passed on to task factories again.


@end deffn

@geindex get_task_factory() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop get_task_factory}@anchor{fc5}
@deffn {メソッド} loop.get_task_factory ()

タスクファクトリを返します。デフォルトのタスクファクトリを使用中の場合は @code{None} を返します。
@end deffn

@node ネットワーク接続の確立,ネットワークサーバの生成,フューチャーとタスクの生成,イベントループのメソッド
@anchor{library/asyncio-eventloop opening-network-connections}@anchor{3891}
@subsubsection ネットワーク接続の確立


@geindex create_connection() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop create_connection}@anchor{818}
@deffn {メソッド} async 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, ssl_shutdown_timeout=None, happy_eyeballs_delay=None, interleave=None, all_errors=False)

`host' と `port' で指定されたアドレスとのストリーミングトランスポート接続をオープンします。

ソケットファミリーは `host' (または `family' 引数が与えられた場合は `family') に依存し、 @ref{1bad,,AF_INET} か @ref{1bae,,AF_INET6} のいずれかを指定します。

ソケットタイプは @ref{150b,,SOCK_STREAM} になります。

`protocol_factory' は @ref{3892,,asyncio プロトコル} の実装を返す呼び出し可能オブジェクトでなければなりません。

このメソッドはバックグラウンドで接続の確立を試みます。成功した場合、メソッドは @code{(transport, protocol)} のペアを返します。

時系列での下層処理の概要は以下のとおりです:


@enumerate 

@item 
接続を確立し、その接続に対する @ref{3893,,トランスポート} が生成されます。

@item 
`protocol_factory' が引数なしで呼び出され、ファクトリが @ref{3892,,プロトコル} インスタンスを返すよう要求します。

@item 
プロトコルインスタンスが @ref{3894,,connection_made()} メソッドを呼び出すことにより、トランスポートと紐付けられます。

@item 
成功すると @code{(transport, protocol)} タプルが返されます。
@end enumerate

作成されたトランスポートは実装依存の双方向ストリームです。

その他の引数:


@itemize *

@item 
`ssl': 偽値以外が与えられた場合、SSL/TLS トランスポートが作成されます (デフォルトでは暗号化なしの TCP トランスポートが作成されます)。 `ssl' が @ref{357,,ssl.SSLContext} オブジェクトの場合、このコンテキストがトランスポートを作成するために使用されます; `ssl' が @ref{e07,,True} の場合、 @ref{480,,ssl.create_default_context()} が返すデフォルトのコンテキストが使われます。


@subsubheading 参考


@ref{3895,,SSL/TLS セキュリティについての考察}


@item 
`server_hostname' は対象サーバーの証明書との一致を確認するためのホスト名を設定または上書きします。この引数は `ssl' が @code{None} でない場合のみ設定すべきです。デフォルトでは `host' に指定したサーバー名が使用されます。 `host' が空の文字列の場合のデフォルト値は設定されていません。その場合、 `server_hostname' を必ず指定してください。 `server_hostname' も空の文字列の場合は、ホスト名の一致確認は行われません (これは深刻なセキュリティリスクであり、中間者攻撃を受ける可能性があります)。

@item 
`family', `proto', `flags' は任意のアドレスファミリであり、`host' 解決のための getaddrinfo() 経由で渡されるプロトコルおよびフラグになります。このオプションが与えられた場合、これらはすべて @ref{d1,,socket} モジュール定数に従った整数でなければなりません。

@item 
`happy_eyeballs_delay' が設定されると、この接続に対して Happy Eyeballs が有効化されます。設定する値は浮動小数点数であり、次の接続試行を開始する前に、現在の接続試行が完了するのを待つ時間を秒単位で表現します。この値は 
@geindex RFC; RFC 8305
RFC 8305@footnote{https://datatracker.ietf.org/doc/html/rfc8305.html} で定義されている "接続試行遅延" に相当します。RFC で推奨されている実用的なデフォルト値は @code{0.25} (250 ミリ秒) です。

@item 
`interleave' はホスト名が複数の IP アドレスに名前解決される場合のアドレスの並べ替えを制御します。 @code{0} または未指定の場合並べ替えは行われず、 @ref{e0e,,getaddrinfo()} が返す順番にしたがってアドレスへの接続を試行します。正の整数が指定されると、アドレスはアドレスファミリに応じてインターリーブされます。このとき、与えられた整数は 
@geindex RFC; RFC 8305
RFC 8305@footnote{https://datatracker.ietf.org/doc/html/rfc8305.html} で定義される "最初のアドレスファミリカウント (First Address Family Count)" として解釈されます。デフォルト値は、 `happy_eyeballs_delay' が指定されない場合は @code{0} であり、指定された場合は @code{1} です。

@item 
`sock' を与える場合、トランスポートに使用される、既存の、かつ接続済の @ref{fa1,,socket.socket} オブジェクトを指定します。`sock' を指定する場合、`host'、 `port'、 `family'、 `proto'、 `flags'、 `happy_eyeballs_delay'、 `interleave' および `local_addr' のいずれも指定してはいけません。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
transport created. To close the socket, call the transport's
@ref{3896,,close()} method.
@end quotation
@end cartouche

@item 
`local_addr' を与える場合、ソケットをローカルにバインドするために使用する @code{(local_host, local_port)} タプルを指定します。 `local_host' と `local_port' は、 `host' および `port' と同じく @code{getaddrinfo()} を使ってルックアップされます。

@item 
`ssl_handshake_timeout' は TLS ハンドシェイクが完了するまでの (TLS 接続のための) 待ち時間を秒単位で指定します。指定した待ち時間を超えると接続は中断します。 @code{None} が与えられた場合はデフォルト値 @code{60.0} が使われます。

@item 
`ssl_shutdown_timeout' is the time in seconds to wait for the SSL shutdown
to complete before aborting the connection. @code{30.0} seconds if @code{None}
(default).

@item 
`all_errors' determines what exceptions are raised when a connection cannot
be created. By default, only a single @code{Exception} is raised: the first
exception if there is only one or all errors have same message, or a single
@code{OSError} with the error messages combined. When @code{all_errors} is @code{True},
an @code{ExceptionGroup} will be raised containing all exceptions (even if there
is only one).
@end itemize


バージョン 3.5 で変更: @ref{81d,,ProactorEventLoop} において SSL/TLS のサポートが追加されました。



バージョン 3.6 で変更: 全ての TCP 接続に対してデフォルトでソケットオプション @ref{d6c,,socket.TCP_NODELAY}  が設定されるようになりました。



バージョン 3.7 で変更: `ssl_handshake_timeout' 引数が追加されました。



バージョン 3.8 で変更: `happy_eyeballs_delay' と `interleave' が追加されました。

Happy Eyeballs Algorithm: Success with Dual-Stack Hosts.
When a server's IPv4 path and protocol are working, but the server's
IPv6 path and protocol are not working, a dual-stack client
application experiences significant connection delay compared to an
IPv4-only client.  This is undesirable because it causes the
dual-stack client to have a worse user experience.  This document
specifies requirements for algorithms that reduce this user-visible
delay and provides an algorithm.

詳しくは右記を参照してください: @indicateurl{https://datatracker.ietf.org/doc/html/rfc6555}



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。



バージョン 3.12 で変更: `all_errors' が追加されました



@subsubheading 参考


@ref{d0e,,open_connection()} 関数は高水準の代替 API です。この関数は(@ref{1c7d,,StreamReader}, @ref{1a70,,StreamWriter}) のペアを返し、 async/await コードから直接使うことができます。

@end deffn

@geindex create_datagram_endpoint() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop create_datagram_endpoint}@anchor{93c}
@deffn {メソッド} async loop.create_datagram_endpoint (protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_port=None, allow_broadcast=None, sock=None)

データグラム接続 (UDP) を生成します。

ソケットファミリーは `host' (または `family' 引数が与えられた場合は `family') に依存し、 @ref{1bad,,AF_INET}、 @ref{1bae,,AF_INET6}、@ref{1bb0,,AF_UNIX} のいずれかを指定します。

ソケットタイプは @ref{150a,,SOCK_DGRAM} になります。

`protocol_factory' は @ref{3892,,asyncio プロトコル} の実装を返す呼び出し可能オブジェクトでなければなりません。

成功すると @code{(transport, protocol)} タプルが返されます。

その他の引数:


@itemize *

@item 
`local_addr' が指定される場合、ソケットをローカルにバインドするための @code{(local_host, local_port)} のタプルを指定します。 `local_host' と `local_port' は @ref{e0e,,getaddrinfo()} メソッドを使用して検索されます。

@cartouche
@quotation 注釈 
On Windows, when using the proactor event loop with @code{local_addr=None},
an @ref{2c0,,OSError} with @code{errno.WSAEINVAL} will be raised
when running it.
@end quotation
@end cartouche

@item 
`remote_addr' が指定される場合、@code{(remote_host, remote_por)} のタプルで、ソケットをリモートアドレスに束縛するために使用されます。`remote_host' と `remote_port' は @ref{e0e,,getaddrinfo()} を使用して検索されます。

@item 
`family', `proto', `flags' は任意のアドレスファミリです。これらのファミリ、プロトコル、フラグは、`host' 解決のため @ref{e0e,,getaddrinfo()} 経由でオプションで渡されます。これらのオプションを指定する場合、すべて @ref{d1,,socket} モジュール定数に従った整数でなければなりません。

@item 
`reuse_port' は、同じポートにバインドされた既存の端点すべてがこのフラグを設定して生成されている場合に限り、この端点を既存の端点と同じポートにバインドすることを許可するよう、カーネルに指示します（訳註: ソケットのオプション SO_REUSEPORT を使用します）。このオプションは、Windows やいくつかの UNIX システムではサポートされていません。@ref{d6c,,socket.SO_REUSEPORT}  定数が定義されていなければ、この機能はサポートされません。

@item 
`allow_broadcast' は、カーネルに、このエンドポイントがブロードキャストアドレスにメッセージを送信することを許可するように指示します。

@item 
オプションの `sock' を指定することで、既存の、すでに接続されている @ref{fa1,,socket.socket} をトランスポートで使用することができます。このオプションを使用する場合、`local_addr' と `remote_addr' は省略してください (@ref{885,,None} でなければなりません)。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
transport created. To close the socket, call the transport's
@ref{3896,,close()} method.
@end quotation
@end cartouche
@end itemize

@ref{3897,,UDP echo クライアントプロトコル} および @ref{3898,,UDP echo サーバープロトコル} の例を参照してください。


バージョン 3.4.4 で変更: `family', `proto', `flags', `reuse_address', `reuse_port', `allow_broadcast', `sock' パラメータが追加されました。



バージョン 3.8 で変更: Windows サポートが追加されました。



バージョン 3.8.1 で変更: @ref{d6c,,socket.SO_REUSEADDR} の利用が UDP に対して重大なセキュリティ上の懸念をもたらすため、 `reuse_address' パラメータはサポートされなくなりました。明示的に @code{reuse_address=True} を設定すると例外を送出します。

@code{SO_REUSEADDR} を使って、同一の UDP ソケットアドレスに対して複数のプロセスが異なる UID でソケットを割り当てている場合、受信パケットは複数のソケット間にランダムに分散する可能性があります。

サポートされているプラットフォームでは、 `reuse_port' が同様の機能に対する代用品として利用できます。 `reuse_port' は代替機能として @ref{d6c,,socket.SO_REUSEPORT} を使っており、複数のプロセスが異なる UID で同一のソケットに対して割り当てられるのを明確に禁止します。



バージョン 3.11 で変更: The `reuse_address' parameter, disabled since Python 3.8.1,
3.7.6 and 3.6.10, has been entirely removed.

@end deffn

@geindex create_unix_connection() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop create_unix_connection}@anchor{37ff}
@deffn {メソッド} async loop.create_unix_connection (protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

Unix 接続を生成します。

ソケットファミリーは @ref{1bb0,,AF_UNIX} になります; また、ソケットタイプは @ref{150b,,SOCK_STREAM} になります。

成功すると @code{(transport, protocol)} タプルが返されます。

`path' は Unix ドメインソケット名で、 `sock' パラメータが指定されない場合は必須です。 抽象 Unix ソケット、 @ref{169,,str}、 @ref{192,,bytes}、 and @ref{266,,Path} 形式でのパスがサポートされています。

このメソッドの引数についての詳細は @ref{818,,loop.create_connection()} メソッドのドキュメントを参照してください。

@ref{213f,,Availability}: Unix.


バージョン 3.7 で変更: Added the `ssl_handshake_timeout' parameter.
The `path' parameter can now be a @ref{5a1,,path-like object}.



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。

@end deffn

@node ネットワークサーバの生成,ファイルの転送,ネットワーク接続の確立,イベントループのメソッド
@anchor{library/asyncio-eventloop creating-network-servers}@anchor{3899}
@subsubsection ネットワークサーバの生成


@geindex create_server() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop loop-create-server}@anchor{37bd}@anchor{library/asyncio-eventloop asyncio loop create_server}@anchor{d09}
@deffn {メソッド} async 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, keep_alive=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)

Create a TCP server (socket type @ref{150b,,SOCK_STREAM}) listening
on `port' of the `host' address.

@ref{d08,,Server} オブジェクトを返します。

引数:


@itemize *

@item 
`protocol_factory' は @ref{3892,,asyncio プロトコル} の実装を返す呼び出し可能オブジェクトでなければなりません。

@item 
`host' パラメータはいくつかの方法で指定することができ、その値によってサーバーがどこをリッスンするかが決まります。


@itemize -

@item 
`host' が文字列の場合、 TCP サーバーは `host' で指定した単一のネットワークインターフェースに束縛されます。

@item 
`host' が文字列のシーケンスである場合、 TCP サーバーはそのシーケンスで指定された全てのネットワークインターフェースに束縛されます。

@item 
`host' が空の文字列か @code{None} の場合、すべてのインターフェースが想定され、複合的なソケットのリスト (通常は一つが IPv4、もう一つが IPv6) が返されます。
@end itemize

@item 
The `port' parameter can be set to specify which port the server should
listen on. If @code{0} or @code{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).

@item 
`family' can be set to either @ref{1bad,,socket.AF_INET} or
@ref{1bae,,AF_INET6} to force the socket to use IPv4 or IPv6.
If not set, the `family' will be determined from host name
(defaults to @ref{389a,,AF_UNSPEC}).

@item 
`flags' は @ref{e0e,,getaddrinfo()} のためのビットマスクになります。

@item 
サーバーで既存のソケットオブジェクトを使用するために、オプションの引数 `sock' にソケットオブジェクトを設定することができます。指定した場合、 `host' と `port' を指定してはいけません。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
server created. To close the socket, call the server's
@ref{37fd,,close()} method.
@end quotation
@end cartouche

@item 
`backlog' は @ref{105e,,listen()} に渡される、キューに入るコネクションの最大数になります (デフォルトは 100)。

@item 
確立した接続の上で TLS を有効化するために、 `ssl' に @ref{357,,SSLContext} のインスタンスを指定することができます。

@item 
`reuse_address' は、@code{TIME_WAIT} 状態にあるローカルソケットを、その状態が自然にタイムアウトするのを待つことなく再利用するようカーネルに指示します（訳註: ソケットのオプション SO_REUSEADDR を使用します）。指定しない場合、UNIX では自動的に @code{True} が設定されます。

@item 
`reuse_port' は、同じポートにバインドされた既存の端点すべてがこのフラグを設定して生成されている場合に限り、この端点を既存の端点と同じポートにバインドすることを許可するよう、カーネルに指示します（訳註: ソケットのオプション SO_REUSEPORT を使用します）。このオプションは、Windows ではサポートされていません。

@item 
`keep_alive' set to @code{True} keeps connections active by enabling the
periodic transmission of messages.
@end itemize


バージョン 3.13 で変更: Added the `keep_alive' parameter.



@itemize *

@item 
`ssl_handshake_timeout' は TLS ハンドシェイクが完了するまでの (TLS サーバーのための) 待ち時間を秒単位で指定します。指定した待ち時間を超えると接続は中断します。 @code{None} が与えられた場合はデフォルト値 @code{60.0} が使われます。

@item 
`ssl_shutdown_timeout' is the time in seconds to wait for the SSL shutdown
to complete before aborting the connection. @code{30.0} seconds if @code{None}
(default).

@item 
`start_serving' が @code{True} に設定された場合 (これがデフォルトです)、 生成されたサーバーは即座に接続の受け付けを開始します。 @code{False} が指定された場合、ユーザーは接続の受け付けを開始するために @ref{d0a,,Server.start_serving()} または @ref{d0b,,Server.serve_forever()} を待ち受け (await) る必要があります。
@end itemize


バージョン 3.5 で変更: @ref{81d,,ProactorEventLoop} において SSL/TLS のサポートが追加されました。



バージョン 3.5.1 で変更: `host' パラメータに文字列のシーケンスを指定できるようになりました。



バージョン 3.6 で変更: Added `ssl_handshake_timeout' and `start_serving' parameters.
The socket option @ref{d6c,,socket.TCP_NODELAY} is set by default
for all TCP connections.



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。



@subsubheading 参考


@ref{d0f,,start_server()} 関数は高水準の代替 API です。この関数は @ref{1c7d,,StreamReader} と @ref{1a70,,StreamWriter} のペアを返し、async/await コードから使うことができます。

@end deffn

@geindex create_unix_server() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop create_unix_server}@anchor{4ca}
@deffn {メソッド} async loop.create_unix_server (protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True, cleanup_socket=True)

Similar to @ref{d09,,loop.create_server()} but works with the
@ref{1bb0,,AF_UNIX} socket family.

`path' は Unix ドメインソケット名で、 `sock' パラメータが指定されない場合は必須です。 抽象 Unix ソケット、 @ref{169,,str}、 @ref{192,,bytes}、 and @ref{266,,Path} 形式でのパスがサポートされています。

If `cleanup_socket' is true then the Unix socket will automatically
be removed from the filesystem when the server is closed, unless the
socket has been replaced after the server has been created.

このメソッドの引数についての詳細は @ref{d09,,loop.create_server()} メソッドのドキュメントを参照してください。

@ref{213f,,Availability}: Unix.


バージョン 3.7 で変更: Added the `ssl_handshake_timeout' and `start_serving' parameters.
The `path' parameter can now be a @ref{266,,Path} object.



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。



バージョン 3.13 で変更: Added the `cleanup_socket' parameter.

@end deffn

@geindex connect_accepted_socket() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop connect_accepted_socket}@anchor{9de}
@deffn {メソッド} async loop.connect_accepted_socket (protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

すでに確立した接続を transport と protocol のペアでラップします。

このメソッドは asyncio の範囲外で確立された接続を使うサーバーに対しても使えますが、その場合でも接続は asyncio を使って処理されます。

引数:


@itemize *

@item 
`protocol_factory' は @ref{3892,,asyncio プロトコル} の実装を返す呼び出し可能オブジェクトでなければなりません。

@item 
`sock' は @ref{fa2,,socket.accept} メソッドが返す既存のソケットオブジェクトです。

@cartouche
@quotation 注釈 
The `sock' argument transfers ownership of the socket to the
transport created. To close the socket, call the transport's
@ref{3896,,close()} method.
@end quotation
@end cartouche

@item 
`ssl' には @ref{357,,SSLContext} を指定できます。指定すると、受け付けたコネクション上での SSL を有効にします。

@item 
`ssl_handshake_timeout' は SSL ハンドシェイクが完了するまでの (SSL 接続のための) 待ち時間を秒単位で指定します。 @code{None} が与えられた場合はデフォルト値 @code{60.0} が使われます。

@item 
`ssl_shutdown_timeout' is the time in seconds to wait for the SSL shutdown
to complete before aborting the connection. @code{30.0} seconds if @code{None}
(default).
@end itemize

@code{(transport, protocol)} のペアを返します。


Added in version 3.5.3.



バージョン 3.7 で変更: `ssl_handshake_timeout' 引数が追加されました。



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。

@end deffn

@node ファイルの転送,TLS へのアップグレード,ネットワークサーバの生成,イベントループのメソッド
@anchor{library/asyncio-eventloop transferring-files}@anchor{389b}
@subsubsection ファイルの転送


@geindex sendfile() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sendfile}@anchor{389c}
@deffn {メソッド} async loop.sendfile (transport, file, offset=0, count=None, *, fallback=True)

`transport' を通じて `file' を送信します。送信したデータの総バイト数を返します。

このメソッドは、もし利用可能であれば高性能な @ref{d05,,os.sendfile()} を利用します。

`file' はバイナリモードでオープンされた通常のファイルオブジェクトでなければなりません。

`offset' はファイルの読み込み開始位置を指定します。 `count' が指定された場合、ファイルの EOF までファイルを送信する代わりに、 `count' で指定された総バイト数の分だけ送信します。ファイルオブジェクトが指し示す位置は、メソッドがエラーを送出した場合でも更新されます。この場合実際に送信されたバイト数は @ref{15c6,,file.tell()} メソッドで取得することができます。

`fallback' を @code{True} に指定することで、 asyncio がプラットフォームが sendfile システムコールをサポートしていない場合 (たとえば Windows や Unix の SSL ソケットなど) に別の方法でファイルの読み込みと送信を行うようにすることができます。

システムが `sendfile' システムコールをサポートしておらず、かつ `fallback' が @code{False} の場合、 @ref{3872,,SendfileNotAvailableError} 例外を送出します。


Added in version 3.7.

@end deffn

@node TLS へのアップグレード,ファイル記述子の監視,ファイルの転送,イベントループのメソッド
@anchor{library/asyncio-eventloop tls-upgrade}@anchor{389d}
@subsubsection TLS へのアップグレード


@geindex start_tls() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop start_tls}@anchor{cff}
@deffn {メソッド} async loop.start_tls (transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

既存のトランスポートベースの接続を TLS にアップグレードします。

Create a TLS coder/decoder instance and insert it between the `transport'
and the `protocol'. The coder/decoder implements both `transport'-facing
protocol and `protocol'-facing transport.

Return the created two-interface instance. After `await', the `protocol'
must stop using the original `transport' and communicate with the returned
object only because the coder caches `protocol'-side data and sporadically
exchanges extra TLS session packets with `transport'.

In some situations (e.g. when the passed transport is already closing) this
may return @code{None}.

引数:


@itemize *

@item 
`transport' と `protocol' には、 @ref{d09,,create_server()} や @ref{818,,create_connection()} が返すものと同等のインスタンスを指定します。

@item 
`sslcontext': 構成済みの @ref{357,,SSLContext} インスタンスです。

@item 
(@ref{d09,,create_server()} で生成されたような) サーバーサイドの接続をアップグレードする場合は `server_side' に @code{True} を渡します。

@item 
`server_hostname': 対象のサーバーの証明書との照合に使われるホスト名を設定または上書きします。

@item 
`ssl_handshake_timeout' は TLS ハンドシェイクが完了するまでの (TLS 接続のための) 待ち時間を秒単位で指定します。指定した待ち時間を超えると接続は中断します。 @code{None} が与えられた場合はデフォルト値 @code{60.0} が使われます。

@item 
`ssl_shutdown_timeout' is the time in seconds to wait for the SSL shutdown
to complete before aborting the connection. @code{30.0} seconds if @code{None}
(default).
@end itemize


Added in version 3.7.



バージョン 3.11 で変更: `ssl_shutdown_timeout' パラメータが追加されました。

@end deffn

@node ファイル記述子の監視,ソケットオブジェクトと直接やりとりする,TLS へのアップグレード,イベントループのメソッド
@anchor{library/asyncio-eventloop watching-file-descriptors}@anchor{389e}
@subsubsection ファイル記述子の監視


@geindex add_reader() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop add_reader}@anchor{381a}
@deffn {メソッド} loop.add_reader (fd, callback, *args)

ファイル記述子 `fd' に対する読み込みが可能かどうかの監視を開始し、 `fd' が読み込み可能になると、指定した引数でコールバック `callback' を呼び出します。

Any preexisting callback registered for `fd' is cancelled and replaced by
`callback'.
@end deffn

@geindex remove_reader() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop remove_reader}@anchor{389f}
@deffn {メソッド} loop.remove_reader (fd)

Stop monitoring the `fd' file descriptor for read availability. Returns
@code{True} if `fd' was previously being monitored for reads.
@end deffn

@geindex add_writer() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop add_writer}@anchor{38a0}
@deffn {メソッド} loop.add_writer (fd, callback, *args)

Start monitoring the `fd' file descriptor for write availability and
invoke `callback' with the specified arguments `args' once `fd' is
available for writing.

Any preexisting callback registered for `fd' is cancelled and replaced by
`callback'.

コールバック `callback' に @ref{388c,,キーワード引数を渡す} 場合は @ref{217,,functools.partial()} を使ってください。
@end deffn

@geindex remove_writer() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop remove_writer}@anchor{38a1}
@deffn {メソッド} loop.remove_writer (fd)

Stop monitoring the `fd' file descriptor for write availability. Returns
@code{True} if `fd' was previously being monitored for writes.
@end deffn

これらのメソッドに対する制限事項については @ref{38a2,,プラットフォームのサポート状況} 節も参照してください。

@node ソケットオブジェクトと直接やりとりする,DNS,ファイル記述子の監視,イベントループのメソッド
@anchor{library/asyncio-eventloop working-with-socket-objects-directly}@anchor{38a3}
@subsubsection ソケットオブジェクトと直接やりとりする


一般に、 @ref{818,,loop.create_connection()} や @ref{d09,,loop.create_server()} のようなトランスポートベースの API を使ったプロトコルの実装はソケットと直接やり取りする実装に比べて高速です。しかしながら、パフォーマンスが重要でなく、直接 @ref{fa1,,socket} オブジェクトとやりとりした方が便利なユースケースがいくつかあります。

@geindex sock_recv() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_recv}@anchor{e0b}
@deffn {メソッド} async loop.sock_recv (sock, nbytes)

`nbytes' で指定したバイト数までのデータをソケット `sock' から受信します。 このメソッドは @ref{fa4,,socket.recv()} の非同期版です。

受信したデータをバイトオブジェクトとして返します。

`sock' はノンブロッキングソケットでなければなりません。


バージョン 3.7 で変更: このメソッドは常にコルーチンメソッドとしてドキュメントに記載されてきましたが、 Python 3.7 以前のリリースでは @ref{dc6,,Future} オブジェクトを返していました。 Python 3.7 からは @code{async def} メソッドになりました。

@end deffn

@geindex sock_recv_into() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_recv_into}@anchor{d00}
@deffn {メソッド} async loop.sock_recv_into (sock, buf)

ソケット `sock' からデータを受信してバッファ `buf' に格納します。ブロッキングコードの @ref{1535,,socket.recv_into()} メソッドをモデルとしています。

バッファに書き込んだデータのバイト数を返します。

`sock' はノンブロッキングソケットでなければなりません。


Added in version 3.7.

@end deffn

@geindex sock_recvfrom() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_recvfrom}@anchor{81b}
@deffn {メソッド} async loop.sock_recvfrom (sock, bufsize)

Receive a datagram of up to `bufsize' from `sock'.  Asynchronous version of
@ref{fa5,,socket.recvfrom()}.

Return a tuple of (received data, remote address).

`sock' はノンブロッキングソケットでなければなりません。


Added in version 3.11.

@end deffn

@geindex sock_recvfrom_into() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_recvfrom_into}@anchor{81c}
@deffn {メソッド} async loop.sock_recvfrom_into (sock, buf, nbytes=0)

Receive a datagram of up to `nbytes' from `sock' into `buf'.
Asynchronous version of
@ref{1536,,socket.recvfrom_into()}.

Return a tuple of (number of bytes received, remote address).

`sock' はノンブロッキングソケットでなければなりません。


Added in version 3.11.

@end deffn

@geindex sock_sendall() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_sendall}@anchor{e0c}
@deffn {メソッド} async loop.sock_sendall (sock, data)

データ `data' をソケット `sock' に送信します。 @ref{fa8,,socket.sendall()} メソッドの非同期版です。

このメソッドは `data' をすべて送信し終えるか、またはエラーが起きるまでデータをソケットに送信し続けます。送信に成功した場合 @code{None} を返します。エラーの場合は例外が送出されます。エラーとなった場合、接続の受信側で正しく処理されたデータの総量を特定する方法はありません。

`sock' はノンブロッキングソケットでなければなりません。


バージョン 3.7 で変更: このメソッドは常にコルーチンメソッドとしてドキュメントに記載されてきましたが、 Python 3.7 以前のリリースでは @ref{dc6,,Future} オブジェクトを返していました。 Python 3.7 からは @code{async def} メソッドになりました。

@end deffn

@geindex sock_sendto() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_sendto}@anchor{81a}
@deffn {メソッド} async loop.sock_sendto (sock, data, address)

Send a datagram from `sock' to `address'.
Asynchronous version of
@ref{fa9,,socket.sendto()}.

Return the number of bytes sent.

`sock' はノンブロッキングソケットでなければなりません。


Added in version 3.11.

@end deffn

@geindex sock_connect() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_connect}@anchor{fc8}
@deffn {メソッド} async loop.sock_connect (sock, address)

ソケット `sock' をアドレス `address' のリモートソケットに接続します。

@ref{fa3,,socket.connect()} の非同期版です。

`sock' はノンブロッキングソケットでなければなりません。


バージョン 3.5.2 で変更: @code{address} を名前解決する必要はなくなりました。 @code{sock_connect} は @ref{b5b,,socket.inet_pton()} を呼び出して `address' が解決済みかどうかを確認します。未解決の場合、 `address' の名前解決には @ref{e0e,,loop.getaddrinfo()} メソッドが使われます。



@subsubheading 参考


@ref{818,,loop.create_connection()} および  @ref{d0e,,asyncio.open_connection()}。

@end deffn

@geindex sock_accept() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_accept}@anchor{e0d}
@deffn {メソッド} async loop.sock_accept (sock)

接続を受け付けます。ブロッキングコールの @ref{fa2,,socket.accept()} メソッドをモデルとしています。

ソケットはアドレスに束縛済みで、接続を listen 中である必要があります。戻り値は @code{(conn, address)} のペアで、`conn' は接続を通じてデータの送受信を行うための `新しい' ソケットオブジェクト、`address' は接続先の端点でソケットに束縛されているアドレスを示します。

`sock' はノンブロッキングソケットでなければなりません。


バージョン 3.7 で変更: このメソッドは常にコルーチンメソッドとしてドキュメントに記載されてきましたが、 Python 3.7 以前のリリースでは @ref{dc6,,Future} オブジェクトを返していました。 Python 3.7 からは @code{async def} メソッドになりました。



@subsubheading 参考


@ref{d09,,loop.create_server()} および @ref{d0f,,start_server()}。

@end deffn

@geindex sock_sendfile() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop sock_sendfile}@anchor{d04}
@deffn {メソッド} async loop.sock_sendfile (sock, file, offset=0, count=None, *, fallback=True)

ファイルを送信します。利用可能なら高性能な @ref{d05,,os.sendfile} を使います。送信したデータの総バイト数を返します。

@ref{105d,,socket.sendfile()} メソッドの非同期版です。

`sock' は @ref{150b,,socket.SOCK_STREAM} タイプのノンブロッキングな @ref{fa1,,socket} でなければなりません。

`file' はバイナリモードでオープンされた通常のファイルオブジェクトでなければなりません。

`offset' はファイルの読み込み開始位置を指定します。 `count' が指定された場合、ファイルの EOF までファイルを送信する代わりに、 `count' で指定された総バイト数の分だけ送信します。ファイルオブジェクトが指し示す位置は、メソッドがエラーを送出した場合でも更新されます。この場合実際に送信されたバイト数は @ref{15c6,,file.tell()} メソッドで取得することができます。

`fallback' が @code{True} に設定された場合、 プラットフォームが sendfile システムコールをサポートしていない場合 (たとえば Windows や Unix の SSL ソケットなど) に asyncio が別の方法でファイルの読み込みと送信を行うようにすることができます。

システムが `sendfile' システムコールをサポートしておらず、かつ `fallback' が @code{False} の場合、 @ref{3872,,SendfileNotAvailableError} 例外を送出します。

`sock' はノンブロッキングソケットでなければなりません。


Added in version 3.7.

@end deffn

@node DNS,パイプとやりとりする,ソケットオブジェクトと直接やりとりする,イベントループのメソッド
@anchor{library/asyncio-eventloop dns}@anchor{38a4}
@subsubsection DNS


@geindex getaddrinfo() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop getaddrinfo}@anchor{e0e}
@deffn {メソッド} async loop.getaddrinfo (host, port, *, family=0, type=0, proto=0, flags=0)

@ref{1ac3,,socket.getaddrinfo()} の非同期版です。
@end deffn

@geindex getnameinfo() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop getnameinfo}@anchor{e0f}
@deffn {メソッド} async loop.getnameinfo (sockaddr, flags=0)

@ref{1a3a,,socket.getnameinfo()} の非同期版です。
@end deffn

@cartouche
@quotation 注釈 
Both `getaddrinfo' and `getnameinfo' internally utilize their synchronous
versions through the loop's default thread pool executor.
When this executor is saturated, these methods may experience delays,
which higher-level networking libraries may report as increased timeouts.
To mitigate this, consider using a custom executor for other user tasks,
or setting a default executor with a larger number of workers.
@end quotation
@end cartouche


バージョン 3.7 で変更: `getaddrinfo' と `getnameinfo' の2つのメソッドは、いずれも常にコルーチンメソッドとしてドキュメントに記載されてきましたが、 Python 3.7 以前のリリースでは、実際には @ref{dc6,,asyncio.Future} オブジェクトを返していました。 Python 3.7 からはどちらのメソッドもコルーチンになりました。


@node パイプとやりとりする,Unix シグナル,DNS,イベントループのメソッド
@anchor{library/asyncio-eventloop working-with-pipes}@anchor{38a5}
@subsubsection パイプとやりとりする


@geindex connect_read_pipe() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop connect_read_pipe}@anchor{3846}
@deffn {メソッド} async loop.connect_read_pipe (protocol_factory, pipe)

イベントループの読み込み側終端に `pipe' を登録します。

`protocol_factory' は @ref{3892,,asyncio プロトコル} の実装を返す呼び出し可能オブジェクトでなければなりません。

`pipe' には @ref{13db,,file-like オブジェクト} を指定します。

@code{(transport, protocol)} のペアを返します。ここで `transport' は @ref{38a6,,ReadTransport} のインターフェースをサポートし、 `protocol' は `protocol_factory' ファクトリでインスタンス化されたオブジェクトです。

@ref{314,,SelectorEventLoop} イベントループの場合、`pipe' は非ブロックモードに設定されていなければなりません。
@end deffn

@geindex connect_write_pipe() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop connect_write_pipe}@anchor{3847}
@deffn {メソッド} async loop.connect_write_pipe (protocol_factory, pipe)

`pipe' の書き込み側終端をイベントループに登録します。

`protocol_factory' は @ref{3892,,asyncio プロトコル} の実装を返す呼び出し可能オブジェクトでなければなりません。

`pipe' は @ref{13db,,file-like オブジェクト} です。

@code{(transport, protocol)} のペアを返します。ここで `transport' は @ref{38a7,,WriteTransport} のインスタンスであり、 `protocol' は `protocol_factory' ファクトリでインスタンス化されたオブジェクトです。

@ref{314,,SelectorEventLoop} イベントループの場合、`pipe' は非ブロックモードに設定されていなければなりません。
@end deffn

@cartouche
@quotation 注釈 
@ref{314,,SelectorEventLoop} は Windows 上で上記のメソッドをサポートしていません。 Windowsでは代わりに @ref{81d,,ProactorEventLoop} を使ってください。
@end quotation
@end cartouche


@subsubheading 参考


@ref{3843,,loop.subprocess_exec()} および @ref{3844,,loop.subprocess_shell()} メソッド。


@node Unix シグナル,スレッドまたはプロセスプールでコードを実行する,パイプとやりとりする,イベントループのメソッド
@anchor{library/asyncio-eventloop unix-signals}@anchor{38a8}
@subsubsection Unix シグナル


@geindex add_signal_handler() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop loop-add-signal-handler}@anchor{37bf}@anchor{library/asyncio-eventloop asyncio loop add_signal_handler}@anchor{38a9}
@deffn {メソッド} loop.add_signal_handler (signum, callback, *args)

Set `callback' as the handler for the `signum' signal,
passing `args' as positional arguments.

コールバックは `loop'、登録された他のコールバック、およびイベントループの実行可能なコルーチンから呼び出されます。 @ref{134c,,signal.signal()} を使って登録されたシグナルハンドラと異なり、この関数で登録されたコールバックはイベントループと相互作用することが可能です。

シグナルナンバーが誤っているか捕捉不可能な場合 @ref{2ec,,ValueError} が送出されます。ハンドラーの設定に問題があった場合 @ref{244,,RuntimeError} が送出されます。

コールバック `callback' に @ref{388c,,キーワード引数を渡す} 場合は @ref{217,,functools.partial()} を使ってください。

@ref{134c,,signal.signal()} と同じく、この関数はメインスレッドから呼び出されなければなりません。
@end deffn

@geindex remove_signal_handler() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop remove_signal_handler}@anchor{38aa}
@deffn {メソッド} loop.remove_signal_handler (sig)

シグナル `sig' に対するハンドラを削除します。

シグナルハンドラが削除された場合 @code{True} を返します。シグナルに対してハンドラが設定されていない場合には @code{False} を返します。

@ref{213f,,Availability}: Unix.
@end deffn


@subsubheading 参考


@ref{cb,,signal} モジュール。


@node スレッドまたはプロセスプールでコードを実行する,エラーハンドリング API,Unix シグナル,イベントループのメソッド
@anchor{library/asyncio-eventloop executing-code-in-thread-or-process-pools}@anchor{38ab}
@subsubsection スレッドまたはプロセスプールでコードを実行する


@geindex run_in_executor() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop run_in_executor}@anchor{ae6}
@deffn {メソッド} awaitable loop.run_in_executor (executor, func, *args)

Arrange for `func' to be called in the specified executor
passing `args' as positional arguments.

The `executor' argument should be an @ref{36e2,,concurrent.futures.Executor}
instance. The default executor is used if `executor' is @code{None}.
The default executor can be set by @ref{94a,,loop.set_default_executor()},
otherwise, a @ref{949,,concurrent.futures.ThreadPoolExecutor} will be
lazy-initialized and used by @ref{ae6,,run_in_executor()} if needed.

以下はプログラム例です:

@example
import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

    # 4. Run in a custom interpreter pool:
    with concurrent.futures.InterpreterPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom interpreter pool', result)

if __name__ == '__main__':
    asyncio.run(main())
@end example

Note that the entry point guard (@code{if __name__ == '__main__'})
is required for option 3 due to the peculiarities of @ref{98,,multiprocessing},
which is used by @ref{1d6,,ProcessPoolExecutor}.
See @ref{36cb,,Safe importing of main module}.

このメソッドは @ref{dc6,,asyncio.Future} オブジェクトを返します。

関数 `func' に @ref{388c,,キーワード引数を渡す} 場合は @ref{217,,functools.partial()} を使ってください。


バージョン 3.5.3 で変更: @ref{ae6,,loop.run_in_executor()} は内部で生成するスレッドプールエグゼキュータの @code{max_workers} を設定せず、代わりにスレッドプールエグゼキュータ (@ref{949,,ThreadPoolExecutor}) にデフォルト値を設定させるようになりました。

@end deffn

@geindex set_default_executor() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop set_default_executor}@anchor{94a}
@deffn {メソッド} loop.set_default_executor (executor)

Set `executor' as the default executor used by @ref{ae6,,run_in_executor()}.
`executor' must be an instance of
@ref{949,,ThreadPoolExecutor}, which includes
@ref{1d2,,InterpreterPoolExecutor}.


バージョン 3.11 で変更: `executor' must be an instance of
@ref{949,,ThreadPoolExecutor}.

@end deffn

@node エラーハンドリング API,デバッグモードの有効化,スレッドまたはプロセスプールでコードを実行する,イベントループのメソッド
@anchor{library/asyncio-eventloop error-handling-api}@anchor{38ac}
@subsubsection エラーハンドリング API


イベントループ内での例外の扱い方をカスタマイズできます。

@geindex set_exception_handler() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop set_exception_handler}@anchor{38ad}
@deffn {メソッド} loop.set_exception_handler (handler)

`handler' を新しいイベントループ例外ハンドラーとして設定します。

`handler' が @code{None} の場合、デフォルトの例外ハンドラが設定されます。そうでなければ、 `handler' は @code{(loop, context)} に一致する関数シグネチャを持った呼び出し可能オブジェクトでなければなりません。ここで @code{loop} はアクティブなイベントループへの参照であり、 @code{context} は例外の詳細な記述からなる @code{dict} オブジェクトです (`context' についての詳細は @ref{38ae,,call_exception_handler()} メソッドのドキュメントを参照してください)。

If the handler is called on behalf of a @ref{1c7,,Task} or
@ref{1e84,,Handle}, it is run in the
@ref{177,,contextvars.Context} of that task or callback handle.


バージョン 3.12 で変更: The handler may be called in the @ref{177,,Context}
of the task or handle where the exception originated.

@end deffn

@geindex get_exception_handler() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop get_exception_handler}@anchor{e75}
@deffn {メソッド} loop.get_exception_handler ()

現在の例外ハンドラを返します。カスタム例外ハンドラが設定されていない場合は @code{None} を返します。


Added in version 3.5.2.

@end deffn

@geindex default_exception_handler() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop default_exception_handler}@anchor{38af}
@deffn {メソッド} loop.default_exception_handler (context)

デフォルトの例外ハンドラーです。

デフォルト例外ハンドラは、例外ハンドラが未設定の場合、例外が発生した時に呼び出されます。デフォルト例外ハンドラの挙動を受け入れるために、カスタム例外ハンドラから呼び出すことも可能です。

引数 `context' の意味は @ref{38ae,,call_exception_handler()} と同じです。
@end deffn

@geindex call_exception_handler() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop call_exception_handler}@anchor{38ae}
@deffn {メソッド} loop.call_exception_handler (context)

現在のイベントループ例外ハンドラーを呼び出します。

`context' は以下のキーを含む @code{dict} オブジェクトです (将来の Python バージョンで新しいキーが追加される可能性があります):


@itemize *

@item 
'message': エラーメッセージ;

@item 
'exception' (任意): 例外オブジェクト;

@item 
'future' (任意): @ref{dc6,,asyncio.Future} インスタンス;

@item 
'task' (optional): @ref{1c7,,asyncio.Task} instance;

@item 
'handle' (任意): @ref{1e84,,asyncio.Handle} インスタンス;

@item 
'protocol' (任意): @ref{3892,,プロトコル} インスタンス;

@item 
'transport' (任意): @ref{3893,,トランスポート} インスタンス;

@item 
'socket' (optional): @ref{fa1,,socket.socket} instance;

@item 
'source_traceback' (optional): Traceback of the source;

@item 
'handle_traceback' (optional): Traceback of the handle;

@item 

@table @asis

@item 'asyncgen' (optional): Asynchronous generator that caused

the exception.
@end table
@end itemize

@cartouche
@quotation 注釈 
This method should not be overloaded in subclassed
event loops.  For custom exception handling, use
the @ref{38ad,,set_exception_handler()} method.
@end quotation
@end cartouche
@end deffn

@node デバッグモードの有効化,サブプロセスの実行,エラーハンドリング API,イベントループのメソッド
@anchor{library/asyncio-eventloop enabling-debug-mode}@anchor{38b0}
@subsubsection デバッグモードの有効化


@geindex get_debug() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop get_debug}@anchor{fc2}
@deffn {メソッド} loop.get_debug ()

イベントループのデバッグモード (@ref{3c3,,bool}) を取得します。

環境変数 
@geindex PYTHONASYNCIODEBUG
@geindex 環境変数; PYTHONASYNCIODEBUG
@ref{2139,,PYTHONASYNCIODEBUG} に空でない文字列が設定されている場合のデフォルト値は @code{True}、そうでない場合は @code{False} になります。
@end deffn

@geindex set_debug() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop set_debug}@anchor{fc1}
@deffn {メソッド} loop.set_debug (enabled: bool)

イベントループのデバッグモードを設定します。


バージョン 3.7 で変更: 新しい @ref{508,,Python 開発モード} を使ってデバッグモードを有効化することができるようになりました。

@end deffn

@geindex slow_callback_duration (asyncio.loop の属性)
@anchor{library/asyncio-eventloop asyncio loop slow_callback_duration}@anchor{38b1}
@deffn {の属性} loop.slow_callback_duration

This attribute can be used to set the
minimum execution duration in seconds that is considered "slow".
When debug mode is enabled, "slow" callbacks are logged.

Default value is 100 milliseconds.
@end deffn


@subsubheading 参考


@ref{213a,,asyncio のデバッグモード}。


@node サブプロセスの実行,,デバッグモードの有効化,イベントループのメソッド
@anchor{library/asyncio-eventloop running-subprocesses}@anchor{38b2}
@subsubsection サブプロセスの実行


この節で解説しているのは低水準のメソッドです。通常の async/await コードでは、高水準の関数である @ref{c6c,,asyncio.create_subprocess_shell()} や @ref{c6b,,asyncio.create_subprocess_exec()} を代わりに使うことを検討してください。

@cartouche
@quotation 注釈 
On Windows, the default event loop @ref{81d,,ProactorEventLoop} supports
subprocesses, whereas @ref{314,,SelectorEventLoop} does not. See
@ref{3845,,Subprocess Support on Windows} for
details.
@end quotation
@end cartouche

@geindex subprocess_exec() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop loop-subprocess-exec}@anchor{37be}@anchor{library/asyncio-eventloop asyncio loop subprocess_exec}@anchor{3843}
@deffn {メソッド} async loop.subprocess_exec (protocol_factory, *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)

`args' で指定されたひとつの、または複数の文字列引数からサブプロセスを生成します。

`args' は下記のいずれかに当てはまる文字列のリストでなければなりません:


@itemize *

@item 
@ref{169,,str};

@item 
または @ref{2c35,,ファイルシステムのエンコーディング} にエンコードされた @ref{192,,bytes}
@end itemize

引数の最初の文字列はプログラムの実行ファイルを指定します。それに続く残りの文字列は引数を指定し、そのプログラムに対する @code{argv} を構成します。

このメソッドは標準ライブラリの @ref{4b7,,subprocess.Popen} クラスを、 @code{shell=False} かつ最初の引数に文字列のリストを渡して呼び出した場合に似ています。しかし、 @ref{4b7,,Popen} クラスは文字列のリストを引数としてひとつだけ取るのに対して、 `subprocess_exec' は複数の文字列引数をとることができます。

`protocol_factory' は @ref{38b3,,asyncio.SubprocessProtocol} クラスの派生クラスを返す呼び出し可能オブジェクトでなければなりません。

その他の引数:


@itemize *

@item 
`stdin' は下記のいずれかをとることができます:


@itemize *

@item 
a file-like object

@item 
an existing file descriptor (a positive integer), for example those created with @ref{1b64,,os.pipe()}

@item 
デフォルト値は @ref{d80,,subprocess.PIPE} 定数で、この場合新規にパイプを生成して接続します。

@item 
@code{None} が設定された場合、サブプロセスは元のプロセスのファイルデスクリプタを引き継ぎます。

@item 
@ref{1366,,subprocess.DEVNULL} 定数を設定すると、特別なファイル @ref{1e14,,os.devnull} を使います。
@end itemize

@item 
`stdout' は下記のいずれかをとることができます:


@itemize *

@item 
a file-like object

@item 
デフォルト値は @ref{d80,,subprocess.PIPE} 定数で、この場合新規にパイプを生成して接続します。

@item 
@code{None} が設定された場合、サブプロセスは元のプロセスのファイルデスクリプタを引き継ぎます。

@item 
@ref{1366,,subprocess.DEVNULL} 定数を設定すると、特別なファイル @ref{1e14,,os.devnull} を使います。
@end itemize

@item 
`stderr' は下記のいずれかをとることができます:


@itemize *

@item 
a file-like object

@item 
デフォルト値は @ref{d80,,subprocess.PIPE} 定数で、この場合新規にパイプを生成して接続します。

@item 
@code{None} が設定された場合、サブプロセスは元のプロセスのファイルデスクリプタを引き継ぎます。

@item 
@ref{1366,,subprocess.DEVNULL} 定数を設定すると、特別なファイル @ref{1e14,,os.devnull} を使います。

@item 
@ref{372d,,subprocess.STDOUT} 定数を設定すると、標準エラー出力ストリームをプロセスの標準出力ストリームに接続します。
@end itemize

@item 
その他のすべてのキーワード引数は解釈されずにそのまま @ref{4b7,,subprocess.Popen} に渡されます。ただし、 `bufsize'、 `universal_newlines'、 `shell'、 `text'、 `encoding' および `errors' は指定してはいけません。

@code{asyncio} のサブプロセス API はストリームからテキストへのデコードをサポートしていません。ストリームからテキストに変換するには @ref{ad3,,bytes.decode()} 関数を使ってください。
@end itemize

If a file-like object passed as `stdin', `stdout' or `stderr' represents a
pipe, then the other side of this pipe should be registered with
@ref{3847,,connect_write_pipe()} or @ref{3846,,connect_read_pipe()} for use
with the event loop.

他の引数についての詳細は @ref{4b7,,subprocess.Popen} クラスのコンストラクタを参照してください。

@code{(transport, protocol)} のペアを返します。ここで `transport' は @ref{38b4,,asyncio.SubprocessTransport} 基底クラスに適合するオブジェクトで、 `protocol' は `protocol_factory' によりインスタンス化されたオブジェクトです。

If the transport is closed or is garbage collected, the child process
is killed if it is still running.
@end deffn

@geindex subprocess_shell() (asyncio.loop のメソッド)
@anchor{library/asyncio-eventloop asyncio loop subprocess_shell}@anchor{3844}
@deffn {メソッド} async loop.subprocess_shell (protocol_factory, cmd, *, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)

コマンド `cmd' からプラットフォームの "シェル" シンタックスを使ってサブプロセスを生成します。 `cmd' は @ref{169,,str} 文字列もしくは @ref{2c35,,ファイルシステムのエンコーディング} でエンコードされた @ref{192,,bytes} 文字列です。

これは標準ライブラリの @ref{4b7,,subprocess.Popen} クラスを @code{shell=True} で呼び出した場合と似ています。

`protocol_factory' は @ref{38b3,,SubprocessProtocol} の派生クラスを返す呼び出し可能オブジェクトでなければなりません。

その他の引数についての詳細は @ref{3843,,subprocess_exec()} メソッドを参照してください。

@code{(transport, protocol)} のペアを返します。ここで `transport' は @ref{38b4,,SubprocessTransport} 基底クラスに適合するオブジェクトで、 `protocol' は `protocol_factory' によりインスタンス化されたオブジェクトです。

If the transport is closed or is garbage collected, the child process
is killed if it is still running.
@end deffn

@cartouche
@quotation 注釈 
シェルインジェクション@footnote{https://en.wikipedia.org/wiki/Shell_injection#Shell_injection} の脆弱性を回避するために全ての空白文字および特殊文字を適切にクオートすることは、アプリケーション側の責任で確実に行ってください。シェルコマンドを構成する文字列内の空白文字と特殊文字のエスケープは、 @ref{582,,shlex.quote()} 関数を使うと適切に行うことができます。
@end quotation
@end cartouche

@node コールバックのハンドル,Serverオブジェクト,イベントループのメソッド,イベントループ
@anchor{library/asyncio-eventloop callback-handles}@anchor{3882}
@subsubsection コールバックのハンドル


@geindex Handle (asyncio のクラス)
@anchor{library/asyncio-eventloop asyncio Handle}@anchor{1e84}
@deffn {クラス} asyncio.Handle

@ref{cfa,,loop.call_soon()} や @ref{cfb,,loop.call_soon_threadsafe()} が返すコールバックのラッパーです。

@geindex get_context() (asyncio.Handle のメソッド)
@anchor{library/asyncio-eventloop asyncio Handle get_context}@anchor{38b5}
@deffn {メソッド} get_context ()

Return the @ref{177,,contextvars.Context} object
associated with the handle.


Added in version 3.12.

@end deffn

@geindex cancel() (asyncio.Handle のメソッド)
@anchor{library/asyncio-eventloop asyncio Handle cancel}@anchor{38b6}
@deffn {メソッド} cancel ()

コールバックをキャンセルします。コールバックがキャンセル済みまたは実行済みの場合、このメソッドは何の影響もありません。
@end deffn

@geindex cancelled() (asyncio.Handle のメソッド)
@anchor{library/asyncio-eventloop asyncio Handle cancelled}@anchor{d10}
@deffn {メソッド} cancelled ()

コールバックがキャンセルされた場合 @code{True} を返します。


Added in version 3.7.

@end deffn
@end deffn

@geindex TimerHandle (asyncio のクラス)
@anchor{library/asyncio-eventloop asyncio TimerHandle}@anchor{1add}
@deffn {クラス} asyncio.TimerHandle

A callback wrapper object returned by @ref{cfc,,loop.call_later()},
and @ref{cfd,,loop.call_at()}.

このクラスは @ref{1e84,,Handle} の派生クラスです。

@geindex when() (asyncio.TimerHandle のメソッド)
@anchor{library/asyncio-eventloop asyncio TimerHandle when}@anchor{d0d}
@deffn {メソッド} when ()

コールバックのスケジュール時刻を秒単位の @ref{196,,float} で返します。

戻り値の時刻は絶対値で、 @ref{388f,,loop.time()} と同じ参照時刻を使って定義されています。


Added in version 3.7.

@end deffn
@end deffn

@node Serverオブジェクト,イベントループの実装,コールバックのハンドル,イベントループ
@anchor{library/asyncio-eventloop server-objects}@anchor{3883}
@subsubsection Serverオブジェクト


Server オブジェクトは @ref{d09,,loop.create_server()}、 @ref{4ca,,loop.create_unix_server()}、 @ref{d0f,,start_server()} および @ref{3800,,start_unix_server()} 関数により生成されます。

Do not instantiate the @ref{d08,,Server} class directly.

@geindex Server (asyncio のクラス)
@anchor{library/asyncio-eventloop asyncio Server}@anchor{d08}
@deffn {クラス} asyncio.Server

`Server' オブジェクトは非同期のコンテキストマネージャです。 @code{async with} 文の中で使われた場合、 @code{async with} 文が完了した時に Server オブジェクトがクローズされること、およびそれ以降に接続を受け付けないことが保証されます。

@example
srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
@end example


バージョン 3.7 で変更: Python 3.7 から、 Server オブジェクトは非同期のコンテキストマネージャになりました。



バージョン 3.11 で変更: This class was exposed publicly as @code{asyncio.Server} in Python 3.9.11, 3.10.3 and 3.11.


@geindex close() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server close}@anchor{37fd}
@deffn {メソッド} close ()

サーバーを停止します: 待機しているソケットをクローズし @ref{e10,,sockets} 属性に @code{None} を設定します。

既存の受信中のクライアントとの接続を表すソケットはオープンのままです。

The server is closed asynchronously; use the @ref{1a3f,,wait_closed()}
coroutine to wait until the server is closed (and no more
connections are active).
@end deffn

@geindex close_clients() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server close_clients}@anchor{4ce}
@deffn {メソッド} close_clients ()

Close all existing incoming client connections.

Calls @ref{3896,,close()} on all associated
transports.

@ref{37fd,,close()} should be called before @ref{4ce,,close_clients()} when
closing the server to avoid races with new clients connecting.


Added in version 3.13.

@end deffn

@geindex abort_clients() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server abort_clients}@anchor{4cf}
@deffn {メソッド} abort_clients ()

Close all existing incoming client connections immediately,
without waiting for pending operations to complete.

Calls @ref{38b7,,abort()} on all associated
transports.

@ref{37fd,,close()} should be called before @ref{4cf,,abort_clients()} when
closing the server to avoid races with new clients connecting.


Added in version 3.13.

@end deffn

@geindex get_loop() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server get_loop}@anchor{d07}
@deffn {メソッド} get_loop ()

サーバオブジェクトに付随するイベントループを返します。


Added in version 3.7.

@end deffn

@geindex start_serving() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server start_serving}@anchor{d0a}
@deffn {メソッド} async start_serving ()

接続の受け付けを開始します。

This method is idempotent, so it can be called when
the server is already serving.

キーワード専用のパラメータ `start_serving' を @ref{d09,,loop.create_server()} や @ref{d0f,,asyncio.start_server()} メソッドに対して使用することにより、初期に接続を受け付けない Server オブジェクトを生成することができます。この場合 @code{Server.start_serving()} または @ref{d0b,,Server.serve_forever()} メソッドを使ってオブジェクトが接続の受け付けを開始するようにすることができます。


Added in version 3.7.

@end deffn

@geindex serve_forever() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server serve_forever}@anchor{d0b}
@deffn {メソッド} async serve_forever ()

接続の受け入れを開始し、コルーチンがキャンセルされるまで継続します。 @code{serve_forever} タスクのキャンセルによりサーバーもクローズされます。

このメソッドはサーバーがすでに接続の受け入れを開始していても呼び出し可能です。ひとつの `Server' オブジェクトにつき @code{serve_forever} タスクはひとつだけ存在できます。

以下はプログラム例です:

@example
async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))
@end example


Added in version 3.7.

@end deffn

@geindex is_serving() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server is_serving}@anchor{d0c}
@deffn {メソッド} is_serving ()

サーバーが新規に接続の受け入れを開始した場合 @code{True} を返します。


Added in version 3.7.

@end deffn

@geindex wait_closed() (asyncio.Server のメソッド)
@anchor{library/asyncio-eventloop asyncio Server wait_closed}@anchor{1a3f}
@deffn {メソッド} async wait_closed ()

Wait until the @ref{37fd,,close()} method completes and all active
connections have finished.
@end deffn

@geindex sockets (asyncio.Server の属性)
@anchor{library/asyncio-eventloop asyncio Server sockets}@anchor{e10}
@deffn {の属性} sockets

List of socket-like objects, @code{asyncio.trsock.TransportSocket}, which
the server is listening on.


バージョン 3.7 で変更: Python 3.7 より前のバージョンでは、 @code{Server.sockets} は内部に持っているサーバーソケットのリストを直接返していました。 Python 3.7 ではリストのコピーが返されるようになりました。

@end deffn
@end deffn
@anchor{library/asyncio-eventloop asyncio-event-loops}@anchor{38b8}
@node イベントループの実装,使用例<25>,Serverオブジェクト,イベントループ
@anchor{library/asyncio-eventloop asyncio-event-loop-implementations}@anchor{38b9}@anchor{library/asyncio-eventloop event-loop-implementations}@anchor{3884}
@subsubsection イベントループの実装


asyncio は2つの異なるイベントループの実装、 @ref{314,,SelectorEventLoop} と @ref{81d,,ProactorEventLoop}、 を提供します:

By default asyncio is configured to use @ref{1a67,,EventLoop}.

@geindex SelectorEventLoop (asyncio のクラス)
@anchor{library/asyncio-eventloop asyncio SelectorEventLoop}@anchor{314}
@deffn {クラス} asyncio.SelectorEventLoop

A subclass of @ref{b58,,AbstractEventLoop} based on the
@ref{c7,,selectors} module.

プラットフォーム上で利用可能な最も効率の良い `selector' を使います。特定のセレクタ実装を使うように手動で構成することも可能です:

@example
import asyncio
import selectors

async def main():
   ...

loop_factory = lambda: asyncio.SelectorEventLoop(selectors.SelectSelector())
asyncio.run(main(), loop_factory=loop_factory)
@end example

@ref{213f,,Availability}: Unix, Windows.
@end deffn

@geindex ProactorEventLoop (asyncio のクラス)
@anchor{library/asyncio-eventloop asyncio ProactorEventLoop}@anchor{81d}
@deffn {クラス} asyncio.ProactorEventLoop

A subclass of @ref{b58,,AbstractEventLoop} for Windows that uses "I/O Completion Ports" (IOCP).

@ref{213f,,Availability}: Windows.


@subsubheading 参考


MSDN documentation on I/O Completion Ports@footnote{https://learn.microsoft.com/windows/win32/fileio/i-o-completion-ports}.

@end deffn

@geindex EventLoop (asyncio のクラス)
@anchor{library/asyncio-eventloop asyncio EventLoop}@anchor{1a67}
@deffn {クラス} asyncio.EventLoop

@quotation

An alias to the most efficient available subclass of @ref{b58,,AbstractEventLoop} for the given
platform.

It is an alias to @ref{314,,SelectorEventLoop} on Unix and @ref{81d,,ProactorEventLoop} on Windows.
@end quotation


Added in version 3.13.

@end deffn

@geindex AbstractEventLoop (asyncio のクラス)
@anchor{library/asyncio-eventloop asyncio AbstractEventLoop}@anchor{b58}
@deffn {クラス} asyncio.AbstractEventLoop

asyncio に適合するイベントループの抽象基底クラスです。

The @ref{3886,,イベントループのメソッド} section lists all
methods that an alternative implementation of @code{AbstractEventLoop}
should have defined.
@end deffn

@node 使用例<25>,,イベントループの実装,イベントループ
@anchor{library/asyncio-eventloop examples}@anchor{3885}
@subsubsection 使用例


この節の全ての使用例は `意図的に'  @ref{3888,,loop.run_forever()} や @ref{cfa,,loop.call_soon()} のような 低水準のイベントループ API の使用法を示しています。一方で現代的な asyncio アプリケーションはここに示すような方法をほとんど必要としません。 @ref{2f3,,asyncio.run()} のような高水準の関数の使用を検討してください。

@menu
* call_soon() を使った Hello World: call_soon を使った Hello World. 
* call_later() で現在の日時を表示する: call_later で現在の日時を表示する. 
* 読み込みイベント用ファイル記述子の監視:: 
* SIGINT および SIGTERM 用のシグナルハンドラーの設定:: 

@end menu

@node call_soon を使った Hello World,call_later で現在の日時を表示する,,使用例<25>
@anchor{library/asyncio-eventloop asyncio-example-lowlevel-helloworld}@anchor{38ba}@anchor{library/asyncio-eventloop hello-world-with-call-soon}@anchor{38bb}
@subsubsection call_soon() を使った Hello World


@ref{cfa,,loop.call_soon()} メソッドを使ってコールバックをスケジュールする例です。コールバックは @code{"Hello World"} を出力しイベントループを停止します:

@example
import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
@end example


@subsubheading 参考


コルーチンと @ref{2f3,,run()} 関数を使用した同じような @ref{37b8,,Hello World} の例。


@node call_later で現在の日時を表示する,読み込みイベント用ファイル記述子の監視,call_soon を使った Hello World,使用例<25>
@anchor{library/asyncio-eventloop asyncio-example-call-later}@anchor{38bc}@anchor{library/asyncio-eventloop display-the-current-date-with-call-later}@anchor{38bd}
@subsubsection call_later() で現在の日時を表示する


毎秒現在時刻を表示するコールバックの例です。コールバックは @ref{cfc,,loop.call_later()} メソッドを使って自身を5秒後に実行するよう再スケジュールし、イベントループを停止します:

@example
import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
@end example


@subsubheading 参考


コルーチンと @ref{2f3,,run()} 関数を使用した同じような @ref{37d7,,現在時刻出力} の例。


@node 読み込みイベント用ファイル記述子の監視,SIGINT および SIGTERM 用のシグナルハンドラーの設定,call_later で現在の日時を表示する,使用例<25>
@anchor{library/asyncio-eventloop asyncio-example-watch-fd}@anchor{3819}@anchor{library/asyncio-eventloop watch-a-file-descriptor-for-read-events}@anchor{38be}
@subsubsection 読み込みイベント用ファイル記述子の監視


ファイル記述子が @ref{381a,,loop.add_reader()} メソッドを使って何らかのデータを受信するまで待機し、その後イベントループをクローズします:

@example
import asyncio
from socket import socketpair

# Create a pair of connected file descriptors
rsock, wsock = socketpair()

loop = asyncio.new_event_loop()

def reader():
    data = rsock.recv(100)
    print("Received:", data.decode())

    # We are done: unregister the file descriptor
    loop.remove_reader(rsock)

    # Stop the event loop
    loop.stop()

# Register the file descriptor for read event
loop.add_reader(rsock, reader)

# Simulate the reception of data from the network
loop.call_soon(wsock.send, 'abc'.encode())

try:
    # Run the event loop
    loop.run_forever()
finally:
    # We are done. Close sockets and the event loop.
    rsock.close()
    wsock.close()
    loop.close()
@end example


@subsubheading 参考



@itemize *

@item 
トランスポート、プロトコル、および @ref{818,,loop.create_connection()} メソッドを使用した同じような @ref{3818,,例}。

@item 
高水準の @ref{d0e,,asyncio.open_connection()} 関数とストリームを使用したもうひとつの @ref{3816,,実装例}。
@end itemize


@node SIGINT および SIGTERM 用のシグナルハンドラーの設定,,読み込みイベント用ファイル記述子の監視,使用例<25>
@anchor{library/asyncio-eventloop asyncio-example-unix-signals}@anchor{38bf}@anchor{library/asyncio-eventloop set-signal-handlers-for-sigint-and-sigterm}@anchor{38c0}
@subsubsection SIGINT および SIGTERM 用のシグナルハンドラーの設定


(ここに挙げる @code{signals} の例は Unix でのみ動きます。)

Register handlers for signals @ref{253,,SIGINT} and @ref{15f8,,SIGTERM}
using the @ref{38a9,,loop.add_signal_handler()} method:

@example
import asyncio
import functools
import os
import signal

def ask_exit(signame, loop):
    print("got signal %s: exit" % signame)
    loop.stop()

async def main():
    loop = asyncio.get_running_loop()

    for signame in @{'SIGINT', 'SIGTERM'@}:
        loop.add_signal_handler(
            getattr(signal, signame),
            functools.partial(ask_exit, signame, loop))

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
print(f"pid @{os.getpid()@}: send SIGINT or SIGTERM to exit.")

asyncio.run(main())
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Future,トランスポートとプロトコル,イベントループ,asyncio --- 非同期 I/O
@anchor{library/asyncio-future doc}@anchor{36e3}@anchor{library/asyncio-future asyncio-futures}@anchor{37c1}@anchor{library/asyncio-future futures}@anchor{38c1}@anchor{library/asyncio-future translation-repo}@anchor{38c2}
@subsubsection Future


`ソースコード:' Lib/asyncio/futures.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/futures.py}, Lib/asyncio/base_futures.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/base_futures.py}


__________________________________________________________________


`Future' オブジェクトは `低水準のコールバックベースのコード' と高水準の async/await コードとの間を橋渡しします。

@menu
* Future の関数:: 
* Future オブジェクト: Future オブジェクト<2>. 

@end menu

@node Future の関数,Future オブジェクト<2>,,Future
@anchor{library/asyncio-future future-functions}@anchor{38c3}
@subsubsection Future の関数


@geindex isfuture() (asyncio モジュール)
@anchor{library/asyncio-future asyncio isfuture}@anchor{38c4}
@deffn {の関数} asyncio.isfuture (obj)

オブジェクト `obj' が下記のいずれかであれば @code{True} を返します:


@itemize *

@item 
@ref{dc6,,asyncio.Future} クラスのインスタンス

@item 
@ref{1c7,,asyncio.Task} クラスのインスタンス

@item 
@code{_asyncio_future_blocking} 属性を持った Future 的なオブジェクト
@end itemize


Added in version 3.5.

@end deffn

@geindex ensure_future() (asyncio モジュール)
@anchor{library/asyncio-future asyncio ensure_future}@anchor{e71}
@deffn {の関数} asyncio.ensure_future (obj, *, loop=None)

下記のいずれかを返します:


@itemize *

@item 
`obj' が @ref{dc6,,Future} オブジェクト、 @ref{1c7,,Task} オブジェクト、または Future 的なオブジェクト (@ref{38c4,,isfuture()} 関数を使って検査します) である場合には `obj' そのもの

@item 
引数 `obj' がコルーチンである (@ref{6a6,,iscoroutine()} 関数を使って検査します) 場合には `obj' をラップした @ref{1c7,,Task} オブジェクト; この場合コルーチンは @code{ensure_future()} によりスケジュールされます。

@item 
引数 `obj' が awaitable である (@ref{1018,,inspect.isawaitable()} 関数を使って検査します) 場合には `obj' を await する @ref{1c7,,Task} オブジェクト
@end itemize

引数 `obj' が上記のいずれにもあてはまらない場合は @ref{198,,TypeError} 例外を送出します。

@cartouche
@quotation 重要 
Save a reference to the result of this function, to avoid
a task disappearing mid-execution.

See also the @ref{1c9,,create_task()} function which is the
preferred way for creating new tasks or use @ref{4d1,,asyncio.TaskGroup}
which keeps reference to the task internally.
@end quotation
@end cartouche


バージョン 3.5.1 で変更: この関数はどんな @ref{4c9,,awaitable} なオブジェクトでも受け入れるようになりました。



バージョン 3.10 で非推奨: Deprecation warning is emitted if `obj' is not a Future-like object
and `loop' is not specified and there is no running event loop.

@end deffn

@geindex wrap_future() (asyncio モジュール)
@anchor{library/asyncio-future asyncio wrap_future}@anchor{1c7c}
@deffn {の関数} asyncio.wrap_future (future, *, loop=None)

@ref{13ca,,concurrent.futures.Future} オブジェクトを @ref{dc6,,asyncio.Future} オブジェクトでラップします。


バージョン 3.10 で非推奨: Deprecation warning is emitted if `future' is not a Future-like object
and `loop' is not specified and there is no running event loop.

@end deffn

@node Future オブジェクト<2>,,Future の関数,Future
@anchor{library/asyncio-future asyncio-future-obj}@anchor{38c5}@anchor{library/asyncio-future future-object}@anchor{38c6}
@subsubsection Future オブジェクト


@geindex Future (asyncio のクラス)
@anchor{library/asyncio-future asyncio Future}@anchor{dc6}
@deffn {クラス} asyncio.Future (*, loop=None)

Future は非同期処理の最終結果を表すクラスです。スレッドセーフではありません。

Future is an @ref{4c9,,awaitable} object.  Coroutines can await on
Future objects until they either have a result or an exception
set, or until they are cancelled. A Future can be awaited multiple
times and the result is same.

典型的には、 Future は低水準のコールバックベースのコード (たとえば asyncio の @ref{37c0,,transports} を使って実装されたプロトコル) が高水準の async/await と相互運用することを可能にするために利用されます。

経験則は Future オブジェクトをユーザー向けの API であらわに利用しないことです。推奨される Future オブジェクトの生成方法は @ref{e74,,loop.create_future()} を呼び出すことです。これによりイベントループの代替実装は、自身に最適化された Future オブジェクトの実装を合わせて提供することができます。


バージョン 3.7 で変更: @ref{28,,contextvars} モジュールのサポートを追加。



バージョン 3.10 で非推奨: Deprecation warning is emitted if `loop' is not specified
and there is no running event loop.


@geindex result() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future result}@anchor{38c7}
@deffn {メソッド} result ()

Future の結果を返します。

Future が `完了' していて、 @ref{37ed,,set_result()} メソッドにより設定された結果を持っている場合は結果の値を返します。

Future が `完了' していて、 @ref{e78,,set_exception()} メソッドにより設定された例外を持っている場合はその例外を送出します。

Future が `キャンセルされた' 場合、このメソッドは @ref{4d4,,CancelledError} 例外を送出します。

If the Future's result isn't yet available, this method raises
an @ref{37f0,,InvalidStateError} exception.
@end deffn

@geindex set_result() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future set_result}@anchor{37ed}
@deffn {メソッド} set_result (result)

Future を `完了' とマークし、結果を設定します。

Raises an @ref{37f0,,InvalidStateError} error if the Future is
already `done'.
@end deffn

@geindex set_exception() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future set_exception}@anchor{e78}
@deffn {メソッド} set_exception (exception)

Future を `完了' とマークし、例外を設定します。

Raises an @ref{37f0,,InvalidStateError} error if the Future is
already `done'.
@end deffn

@geindex done() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future done}@anchor{38c8}
@deffn {メソッド} done ()

Future が `完了' しているなら @code{True} を返します。

Future は `キャンセルされた' か、または @ref{37ed,,set_result()} メソッドや @ref{e78,,set_exception()} メソッドの呼び出しにより結果や例外が設定された場合に `完了' とみなされます。
@end deffn

@geindex cancelled() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future cancelled}@anchor{38c9}
@deffn {メソッド} cancelled ()

Future が `キャンセルされた' 場合に @code{True} を返します。

通常の場合、このメソッドは Future に処理結果や例外を設定する前に Future が `キャンセルされていない' ことを確認するために使用されます:

@example
if not fut.cancelled():
    fut.set_result(42)
@end example
@end deffn

@geindex add_done_callback() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future add_done_callback}@anchor{cfe}
@deffn {メソッド} add_done_callback (callback, *, context=None)

Future が `完了' したときに実行されるコールバックを追加します。

`callback' は Future オブジェクトだけを引数にとって呼び出されます。

このメソッドが呼び出される時点ですでに Future が `完了' している場合、コールバックは @ref{cfa,,loop.call_soon()} メソッドによりスケジュールされます。

オプションのキーワード引数 `context' を使って、コールバック*callback* を実行する際のコンテキスト @ref{177,,contextvars.Context} を設定することができます。コンテキスト `context' が指定されない場合は現在のコンテキストが使われます。

コールバックにパラメータを渡すには、次の例のように @ref{217,,functools.partial()} を使うことができます:

@example
# Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
    functools.partial(print, "Future:"))
@end example


バージョン 3.7 で変更: キーワード引数 `context' が追加されました。詳細は 
@geindex Python Enhancement Proposals; PEP 567
PEP 567@footnote{https://peps.python.org/pep-0567/} を参照してください。

@end deffn

@geindex remove_done_callback() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future remove_done_callback}@anchor{1911}
@deffn {メソッド} remove_done_callback (callback)

コールバックリストから `callback' を削除します。

削除されたコールバックの数を返します。コールバックが複数回追加されていない限り、通常は1が返ります。
@end deffn

@geindex cancel() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future cancel}@anchor{1ba9}
@deffn {メソッド} cancel (msg=None)

Future をキャンセルし、コールバックをスケジュールします。

Future がすでに `完了' または `キャンセル' された場合、 @code{False} を返します。そうでない場合 Future の状態を `キャンセル' に変更した上でコールバックをスケジュールし、 @code{True} を返します。


バージョン 3.9 で変更: Added the `msg' parameter.

@end deffn

@geindex exception() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future exception}@anchor{38ca}
@deffn {メソッド} exception ()

この Future オブジェクトに設定された例外を返します。

例外 (または例外が設定されていないときは @code{None}) は Future が `完了' している場合のみ返されます。

Future が `キャンセルされた' 場合、このメソッドは @ref{4d4,,CancelledError} 例外を送出します。

Future が `未完了' の場合、このメソッドは @ref{37f0,,InvalidStateError} 例外を送出します。
@end deffn

@geindex get_loop() (asyncio.Future のメソッド)
@anchor{library/asyncio-future asyncio Future get_loop}@anchor{d06}
@deffn {メソッド} get_loop ()

Future オブジェクトが束縛されているイベントループを返します。


Added in version 3.7.

@end deffn
@end deffn
@anchor{library/asyncio-future asyncio-example-future}@anchor{38cb}
この例は Future オブジェクトを生成し、Future に結果を設定するための非同期タスクを生成してスケジュールし、そして Future に結果が設定されるまで待機します:

@example
async def set_after(fut, delay, value):
    # Sleep for *delay* seconds.
    await asyncio.sleep(delay)

    # Set *value* as a result of *fut* Future.
    fut.set_result(value)

async def main():
    # Get the current event loop.
    loop = asyncio.get_running_loop()

    # Create a new Future object.
    fut = loop.create_future()

    # Run "set_after()" coroutine in a parallel Task.
    # We are using the low-level "loop.create_task()" API here because
    # we already have a reference to the event loop at hand.
    # Otherwise we could have just used "asyncio.create_task()".
    loop.create_task(
        set_after(fut, 1, '... world'))

    print('hello ...')

    # Wait until *fut* has a result (1 second) and print it.
    print(await fut)

asyncio.run(main())
@end example

@cartouche
@quotation 重要 
Future オブジェクトは @ref{13ca,,concurrent.futures.Future} を模倣してデザインされました。両者の重要な違いは以下の通りです:


@itemize -

@item 
asyncio の Futures と異なり、 @ref{13ca,,concurrent.futures.Future} インスタンスは待ち受けできません。

@item 
@ref{38c7,,asyncio.Future.result()} と @ref{38ca,,asyncio.Future.exception()}  は `timeout' 引数を取りません。

@item 
@ref{38c7,,asyncio.Future.result()} と @ref{38ca,,asyncio.Future.exception()} は Future が `未完了' の場合に @ref{37f0,,InvalidStateError} 例外を送出します。

@item 
@ref{cfe,,asyncio.Future.add_done_callback()} メソッドによって登録されたコールバックは、即座に呼び出されません。代わりにコールバックは @ref{cfa,,loop.call_soon()} によりスケジュールされます。

@item 
asyncio の Future は @ref{1c05,,concurrent.futures.wait()} および @ref{19c7,,concurrent.futures.as_completed()} との互換性がありません。

@item 
@ref{1ba9,,asyncio.Future.cancel()} accepts an optional @code{msg} argument,
but @ref{36ee,,concurrent.futures.Future.cancel()} does not.
@end itemize
@end quotation
@end cartouche

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node トランスポートとプロトコル,ポリシー,Future,asyncio --- 非同期 I/O
@anchor{library/asyncio-protocol doc}@anchor{38cc}@anchor{library/asyncio-protocol asyncio-transports-protocols}@anchor{37c0}@anchor{library/asyncio-protocol translation-repo}@anchor{38cd}@anchor{library/asyncio-protocol transports-and-protocols}@anchor{38ce}
@subsubsection トランスポートとプロトコル


@subsubheading まえがき


トランスポートとプロトコルは @ref{818,,loop.create_connection()} のような `低水準の' イベントループ API から使われます。これらはコールバックに基づくプログラミングスタイルを使うことでネットワークや IPC プロトコル (HTTP など) の高性能な実装を可能にします。

基本的にトランスポートとプロトコルはライブラリやフレームワークからのみ使われるべきであり、高水準の asyncio アプリケーションから使われるものではありません。

このドキュメントは @ref{38cf,,Transports} と @ref{38d0,,Protocols} を扱います。

@subsubheading はじめに


最上位の観点からは、トランスポートは `どのように' バイトデータを送信するかに影響を与え、いっぽうプロトコルは `どの' バイトデータを送信するかを決定します (また、ある程度は `いつ' も決定します) 。

同じことを違う言い方で表現します: トランスポートはソケット (または同様の I/O 端点) の抽象化であり、プロトコルはトランスポートから見たときのアプリケーションの抽象化です。

さらにもう一つの見方として、トランスポートとプロトコルの2つのインターフェースは、協調してネットワーク I/O やプロセス間 I/O の抽象インターフェースを定義しています。

トランスポートオブジェクトとプロトコルオブジェクトの間には常に1対1の関係があります: プロトコルはデータを送信するためにトランスポートのメソッドを呼び出し、トランスポートは受信したデータを渡すためにプロトコルのメソッドを呼び出します。

ほとんどの接続に基づくイベントループメソッド (@ref{818,,loop.create_connection()} など) は通常 `protocol_factory' 引数を受け取り、 `Transport' オブジェクトで表現される確立した接続に対する `Protocol' オブジェクトを生成するために使います。そのようなメソッドは通常 @code{(transport, protocol)} タプルを返します。

@subsubheading 内容


このページは以下の節から構成されます:


@itemize *

@item 
@ref{38cf,,Transports} 節は asyncio の @ref{38d1,,BaseTransport}, @ref{38a6,,ReadTransport}, @ref{38a7,,WriteTransport}, @ref{38d2,,Transport}, @ref{1b27,,DatagramTransport}, および @ref{38b4,,SubprocessTransport} クラスについて記述しています。

@item 
@ref{38d0,,Protocols} 節は asyncio の @ref{38d3,,BaseProtocol}, @ref{38d4,,Protocol}, @ref{c94,,BufferedProtocol}, @ref{8de,,DatagramProtocol}, および @ref{38b3,,SubprocessProtocol} クラスについて記述しています。

@item 
@ref{38d5,,Examples} 節はトランスポート、プロトコル、および低水準のイベントループ API の利用方法を紹介しています。
@end itemize

@menu
* トランスポート:: 
* プロトコル: プロトコル<2>. 
* 使用例: 使用例<26>. 

@end menu

@node トランスポート,プロトコル<2>,,トランスポートとプロトコル
@anchor{library/asyncio-protocol asyncio-transport}@anchor{3893}@anchor{library/asyncio-protocol transports}@anchor{38cf}
@subsubsection トランスポート


`ソースコード:' Lib/asyncio/transports.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/transports.py}


__________________________________________________________________


トランスポートはさまざまな通信方法を抽象化するために @ref{b,,asyncio} が提供するクラス群です。

トランスポートオブジェクトは常に @ref{f76,,asyncio イベントループ} によってインスタンス化されます。

asyncio は TCP, UDP, SSL, およびサブプロセスパイプのトランスポートを実装しています。利用可能なトランスポートのメソッドはトランスポートの種類に依存します。

トランスポートクラスは @ref{37e8,,スレッド安全ではありません}。

@menu
* トランスポートのクラス階層構造:: 
* 基底トランスポート:: 
* 読み出し専用のトランスポート:: 
* 書き込み専用のトランスポート:: 
* データグラムトランスポート:: 
* サブプロセス化されたトランスポート:: 

@end menu

@node トランスポートのクラス階層構造,基底トランスポート,,トランスポート
@anchor{library/asyncio-protocol transports-hierarchy}@anchor{38d6}
@subsubsection トランスポートのクラス階層構造


@geindex BaseTransport (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio BaseTransport}@anchor{38d1}
@deffn {クラス} asyncio.BaseTransport

全てのトランスポートの基底クラスです。すべての asyncio トランスポートが共有するメソッドを含んでいます。
@end deffn

@geindex WriteTransport (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio WriteTransport}@anchor{38a7}
@deffn {クラス} asyncio.WriteTransport (BaseTransport)

書き込み専用の接続に対する基底トランスポートクラスです。

`WriteTransport' クラスのインスタンスは @ref{3847,,loop.connect_write_pipe()} イベントループメソッドから返され、 @ref{3843,,loop.subprocess_exec()} のようなサブプロセスに関連するメソッドから利用されます。
@end deffn

@geindex ReadTransport (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio ReadTransport}@anchor{38a6}
@deffn {クラス} asyncio.ReadTransport (BaseTransport)

読み込み専用の接続に対する基底トランスポートクラスです。

Instances of the `ReadTransport' class are returned from
the @ref{3846,,loop.connect_read_pipe()} event loop method and
are also used by subprocess-related methods like
@ref{3843,,loop.subprocess_exec()}.
@end deffn

@geindex Transport (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio Transport}@anchor{38d2}
@deffn {クラス} asyncio.Transport (WriteTransport, ReadTransport)

TCP 接続のような、読み出しと書き込みの双方向のトランスポートを表現するインターフェースです。

ユーザーはトランスポートを直接インスタンス化することはありません; ユーザーは、ユーティリティ関数にプロトコルファクトリとその他トランスポートとプロトコルを作成するために必要な情報を渡して呼び出します。

`Transport' クラスのインスタンスは、@ref{818,,loop.create_connection()}, @ref{37ff,,loop.create_unix_connection()}, @ref{d09,,loop.create_server()}, @ref{389c,,loop.sendfile()} などのイベントループメソッドから返されたり、これらのメソッドから利用されたりします。
@end deffn

@geindex DatagramTransport (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio DatagramTransport}@anchor{1b27}
@deffn {クラス} asyncio.DatagramTransport (BaseTransport)

データグラム (UDP) 接続のためのトランスポートです。

`DatagramTransport' クラスのインスタンスは @ref{93c,,loop.create_datagram_endpoint()} イベントループメソッドから返されます。
@end deffn

@geindex SubprocessTransport (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio SubprocessTransport}@anchor{38b4}
@deffn {クラス} asyncio.SubprocessTransport (BaseTransport)

親プロセスとその子プロセスの間の接続を表現する抽象クラスです。

`SubprocessTransport' クラスのインスタンスは @ref{3844,,loop.subprocess_shell()} と @ref{3843,,loop.subprocess_exec()} の2つのイベントループメソッドから返されます。
@end deffn

@node 基底トランスポート,読み出し専用のトランスポート,トランスポートのクラス階層構造,トランスポート
@anchor{library/asyncio-protocol base-transport}@anchor{38d7}
@subsubsection 基底トランスポート


@geindex close() (asyncio.BaseTransport のメソッド)
@anchor{library/asyncio-protocol asyncio BaseTransport close}@anchor{3896}
@deffn {メソッド} BaseTransport.close ()

トランスポートをクローズします。

トランスポートが発信データのバッファーを持っていた場合、バッファーされたデータは非同期にフラッシュされます。それ以降データは受信されません。バッファーされていたデータがすべてフラッシュされた後、そのプロトコルの @ref{38d8,,protocol.connection_lost()} メソッドが引数 @ref{885,,None} で呼び出されます。一度閉じたトランスポートは、使用されるべきではありません。
@end deffn

@geindex is_closing() (asyncio.BaseTransport のメソッド)
@anchor{library/asyncio-protocol asyncio BaseTransport is_closing}@anchor{e73}
@deffn {メソッド} BaseTransport.is_closing ()

トランスポートを閉じている最中か閉じていた場合 @code{True} を返します。
@end deffn

@geindex get_extra_info() (asyncio.BaseTransport のメソッド)
@anchor{library/asyncio-protocol asyncio BaseTransport get_extra_info}@anchor{c93}
@deffn {メソッド} BaseTransport.get_extra_info (name, default=None)

トランスポートまたはそれが背後で利用しているリソースの情報を返します。

`name' は取得するトランスポート特有の情報を表す文字列です。

`default' は、取得したい情報が取得可能でなかったり、サードパーティのイベントループ実装や現在のプラットフォームがその情報の問い合わせをサポートしていない場合に返される値です。

例えば、以下のコードはトランスポート内のソケットオブジェクトを取得しようとします:

@example
sock = transport.get_extra_info('socket')
if sock is not None:
    print(sock.getsockopt(...))
@end example

いくつかのトランスポートで問い合わせ可能な情報のカテゴリを示します:


@itemize *

@item 
ソケット:


@itemize -

@item 
@code{'peername'}: ソケットが接続されているリモートアドレスで、@ref{38d9,,socket.socket.getpeername()} の結果になります (エラーのときは @code{None})

@item 
@code{'socket'}: @ref{fa1,,socket.socket} のインスタンスになります

@item 
@code{'sockname'}: ソケット自身のアドレスで、@ref{284,,socket.socket.getsockname()} の結果になります
@end itemize

@item 
SSL ソケット:


@itemize -

@item 
@code{'compression'}: 圧縮アルゴリズムで、@ref{135d,,ssl.SSLSocket.compression()} の結果になります。圧縮されていないときは @code{None} になります

@item 
@code{'cipher'}: 3 個の値 (使用されている暗号アルゴリズムの名称、使用が定義されている SSL プロトコルのバージョン、および使用されている秘密鍵のビット数) からなるタプルで、@ref{38da,,ssl.SSLSocket.cipher()} の結果になります

@item 
@code{'peercert'}: ピアの証明書で、@ref{11ba,,ssl.SSLSocket.getpeercert()} の結果になります

@item 
@code{'sslcontext'}: @ref{357,,ssl.SSLContext} のインスタンスになります

@item 
@code{'ssl_object'}: @ref{d7a,,ssl.SSLObject} または @ref{ae7,,ssl.SSLSocket} インスタンス
@end itemize

@item 
パイプ:


@itemize -

@item 
@code{'pipe'}: パイプオブジェクトです
@end itemize

@item 
サブプロセス:


@itemize -

@item 
@code{'subprocess'}: @ref{4b7,,subprocess.Popen} のインスタンスになります
@end itemize
@end itemize
@end deffn

@geindex set_protocol() (asyncio.BaseTransport のメソッド)
@anchor{library/asyncio-protocol asyncio BaseTransport set_protocol}@anchor{38db}
@deffn {メソッド} BaseTransport.set_protocol (protocol)

トランスポートに新しいプロトコルを設定します。

プロトコルの切り替えは、両方のプロトコルのドキュメントで切り替えがサポートされている場合にのみ行うべきです。
@end deffn

@geindex get_protocol() (asyncio.BaseTransport のメソッド)
@anchor{library/asyncio-protocol asyncio BaseTransport get_protocol}@anchor{38dc}
@deffn {メソッド} BaseTransport.get_protocol ()

現在のプロトコルを返します。
@end deffn

@node 読み出し専用のトランスポート,書き込み専用のトランスポート,基底トランスポート,トランスポート
@anchor{library/asyncio-protocol read-only-transports}@anchor{38dd}
@subsubsection 読み出し専用のトランスポート


@geindex is_reading() (asyncio.ReadTransport のメソッド)
@anchor{library/asyncio-protocol asyncio ReadTransport is_reading}@anchor{d11}
@deffn {メソッド} ReadTransport.is_reading ()

トランスポートが新しいデータを受信中の場合 @code{True} を返します。


Added in version 3.7.

@end deffn

@geindex pause_reading() (asyncio.ReadTransport のメソッド)
@anchor{library/asyncio-protocol asyncio ReadTransport pause_reading}@anchor{d13}
@deffn {メソッド} ReadTransport.pause_reading ()

トランスポートの受信側を一時停止します。 @ref{d12,,resume_reading()} メソッドが呼び出されるまでプロトコルの @ref{1b02,,protocol.data_received()} メソッドにデータは渡されません。


バージョン 3.7 で変更: このメソッドはべき等です。すなわちトランスポートがすでに停止していたりクローズしていても呼び出すことができます。

@end deffn

@geindex resume_reading() (asyncio.ReadTransport のメソッド)
@anchor{library/asyncio-protocol asyncio ReadTransport resume_reading}@anchor{d12}
@deffn {メソッド} ReadTransport.resume_reading ()

受信を再開します。データが読み込み可能になるとプロトコルの @ref{1b02,,protocol.data_received()} メソッドが再び呼び出されるようになります。


バージョン 3.7 で変更: このメソッドはべき等です。すなわちトランスポートがすでにデータを読み込み中であっても呼び出すことができます。

@end deffn

@node 書き込み専用のトランスポート,データグラムトランスポート,読み出し専用のトランスポート,トランスポート
@anchor{library/asyncio-protocol write-only-transports}@anchor{38de}
@subsubsection 書き込み専用のトランスポート


@geindex abort() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport abort}@anchor{38b7}
@deffn {メソッド} WriteTransport.abort ()

未完了の処理が完了するのを待たず、即座にトランスポートをクローズします。バッファーされているデータは失われます。このメソッドの呼び出し以降データは受信されません。最終的にプロトコルの @ref{38d8,,protocol.connection_lost()} メソッドが引数 @ref{885,,None} で呼び出されます。
@end deffn

@geindex can_write_eof() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport can_write_eof}@anchor{38df}
@deffn {メソッド} WriteTransport.can_write_eof ()

トランスポートが @ref{38e0,,write_eof()} メソッドをサポートしている場合 @ref{e07,,True} を返し、そうでない場合は @ref{d2b,,False} を返します。
@end deffn

@geindex get_write_buffer_size() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport get_write_buffer_size}@anchor{38e1}
@deffn {メソッド} WriteTransport.get_write_buffer_size ()

トランスポートで使用されている出力バッファーの現在のサイズを返します。
@end deffn

@geindex get_write_buffer_limits() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport get_write_buffer_limits}@anchor{fc4}
@deffn {メソッド} WriteTransport.get_write_buffer_limits ()

書き込みフロー制御の `最高' および `最低' 水位点を取得します。 @code{(low, high)} タプルを返します。ここで `low' と `high' はバイト数をあらわす正の整数です。

水位点の設定は @ref{38e2,,set_write_buffer_limits()} で行います。


Added in version 3.4.2.

@end deffn

@geindex set_write_buffer_limits() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport set_write_buffer_limits}@anchor{38e2}
@deffn {メソッド} WriteTransport.set_write_buffer_limits (high=None, low=None)

書き込みフロー制御の `最高' および `最低' 水位点を設定します。

(バイト数をあらわす) これら2つの値はプロトコルの @ref{38e3,,protocol.pause_writing()} と @ref{38e4,,protocol.resume_writing()} の2つのメソッドがいつ呼ばれるかを制御します。指定する場合、 `low' は `high' と等しいかまたは `high' より小さくなければなりません。また、 `high' も `low' も負の値を指定することはできません。

@ref{38e3,,pause_writing()} はバッファーサイズが `high' の値以上になった場合に呼び出されます。書き込みが一時停止している場合、バッファーサイズが `low' の値以下になると @ref{38e4,,resume_writing()} メソッドが呼び出されます。

デフォルト値は実装固有になります。 `high' のみ与えられた場合、 `low' は `high' 以下の実装固有のデフォルト値になります。 `high' をゼロに設定すると `low' も強制的にゼロになり、バッファーが空でなくなるとすぐに @ref{38e3,,pause_writing()} メソッドが呼び出されるようになります。 `low' をゼロに設定すると、バッファーが空にな @ref{38e4,,resume_writing()} が呼び出されるようになります。どちらかにゼロを設定することは I/O と計算を並行に実行する機会を減少させるため、一般に最適ではありません。

上限値と下限値を取得するには @ref{fc4,,get_write_buffer_limits()} メソッドを使ってください。
@end deffn

@geindex write() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport write}@anchor{17ca}
@deffn {メソッド} WriteTransport.write (data)

トランスポートにバイト列 `data' を書き込みます。

このメソッドはブロックしません; データをバッファーし、非同期に送信する準備を行います。
@end deffn

@geindex writelines() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport writelines}@anchor{17c9}
@deffn {メソッド} WriteTransport.writelines (list_of_data)

バイト列のデータのリスト (またはイテラブル) をトランスポートに書き込みます。この振る舞いはイテラブルを yield して各要素で @ref{17ca,,write()} を呼び出すことと等価ですが、より効率的な実装となる場合があります。
@end deffn

@geindex write_eof() (asyncio.WriteTransport のメソッド)
@anchor{library/asyncio-protocol asyncio WriteTransport write_eof}@anchor{38e0}
@deffn {メソッド} WriteTransport.write_eof ()

バッファーされた全てのデータをフラッシュした後トランスポートの送信側をクローズします。送信側をクローズした後もデータを受信することは可能です。

このメソッドはトランスポート (例えば SSL) がハーフクローズドな接続をサポートしていない場合 @ref{36b,,NotImplementedError} を送出します。
@end deffn

@node データグラムトランスポート,サブプロセス化されたトランスポート,書き込み専用のトランスポート,トランスポート
@anchor{library/asyncio-protocol datagram-transports}@anchor{38e5}
@subsubsection データグラムトランスポート


@geindex sendto() (asyncio.DatagramTransport のメソッド)
@anchor{library/asyncio-protocol asyncio DatagramTransport sendto}@anchor{4cb}
@deffn {メソッド} DatagramTransport.sendto (data, addr=None)

リモートピア `addr' (トランスポート依存の対象アドレス) にバイト列 `data' を送信します。`addr' が @ref{885,,None} の場合、データはトランスポートの作成時に指定された送信先に送られます。

このメソッドはブロックしません; データをバッファーし、非同期に送信する準備を行います。


バージョン 3.13 で変更: このメソッドは、長さがゼロのデータグラムを送信するために、空のバイトオブジェクトで呼び出すこともできます。フロー制御に使用されるバッファサイズ計算も、データグラムヘッダーを考慮するように更新されました。

@end deffn

@geindex abort() (asyncio.DatagramTransport のメソッド)
@anchor{library/asyncio-protocol asyncio DatagramTransport abort}@anchor{38e6}
@deffn {メソッド} DatagramTransport.abort ()

未完了の処理が完了するのを待たず、即座にトランスポートをクローズします。バッファーされているデータは失われます。このメソッドの呼び出し以降データは受信されません。最終的にプロトコルの @ref{38d8,,protocol.connection_lost()} メソッドが引数 @ref{885,,None} で呼び出されます。
@end deffn

@node サブプロセス化されたトランスポート,,データグラムトランスポート,トランスポート
@anchor{library/asyncio-protocol asyncio-subprocess-transports}@anchor{3848}@anchor{library/asyncio-protocol subprocess-transports}@anchor{38e7}
@subsubsection サブプロセス化されたトランスポート


@geindex get_pid() (asyncio.SubprocessTransport のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessTransport get_pid}@anchor{38e8}
@deffn {メソッド} SubprocessTransport.get_pid ()

サブプロセスのプロセス ID (整数) を返します。
@end deffn

@geindex get_pipe_transport() (asyncio.SubprocessTransport のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessTransport get_pipe_transport}@anchor{38e9}
@deffn {メソッド} SubprocessTransport.get_pipe_transport (fd)

整数のファイル記述子 `fd' に該当する通信パイプのトランスポートを返します:


@itemize *

@item 
@code{0}: writable streaming transport of the standard input (`stdin'),
or @ref{885,,None} if the subprocess was not created with @code{stdin=PIPE}

@item 
@code{1}: readable streaming transport of the standard output (`stdout'),
or @ref{885,,None} if the subprocess was not created with @code{stdout=PIPE}

@item 
@code{2}: readable streaming transport of the standard error (`stderr'),
or @ref{885,,None} if the subprocess was not created with @code{stderr=PIPE}

@item 
その他の `fd': @ref{885,,None}
@end itemize
@end deffn

@geindex get_returncode() (asyncio.SubprocessTransport のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessTransport get_returncode}@anchor{38ea}
@deffn {メソッド} SubprocessTransport.get_returncode ()

サブプロセスのリターンコードを整数で返します。サブプロセスがリターンしなかった場合は @ref{885,,None} を返します。 @ref{c83,,subprocess.Popen.returncode} 属性と同じです。
@end deffn

@geindex kill() (asyncio.SubprocessTransport のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessTransport kill}@anchor{38eb}
@deffn {メソッド} SubprocessTransport.kill ()

サブプロセスを強制終了 (kill) します。

POSIX システムでは、この関数はサブプロセスに SIGKILL を送信します。Windows では、このメソッドは @ref{38ec,,terminate()} の別名です。

@ref{15f6,,subprocess.Popen.kill()} も参照してください。
@end deffn

@geindex send_signal() (asyncio.SubprocessTransport のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessTransport send_signal}@anchor{38ed}
@deffn {メソッド} SubprocessTransport.send_signal (signal)

サブプロセスにシグナル `signal' を送信します。@ref{15f7,,subprocess.Popen.send_signal()} と同じです。
@end deffn

@geindex terminate() (asyncio.SubprocessTransport のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessTransport terminate}@anchor{38ec}
@deffn {メソッド} SubprocessTransport.terminate ()

サブプロセスを停止します。

POSIX システムでは、このメソッドはサブプロセスに @ref{15f8,,SIGTERM} を送信します。Windows では、Windows API 関数 @code{TerminateProcess()} がサブプロセスを停止するために呼び出されます。

@ref{15f5,,subprocess.Popen.terminate()} も参照してください。
@end deffn

@geindex close() (asyncio.SubprocessTransport のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessTransport close}@anchor{38ee}
@deffn {メソッド} SubprocessTransport.close ()

@ref{38eb,,kill()} メソッドを呼び出すことでサブプロセスを強制終了します。

サブプロセスがまだリターンしていない場合、 `stdin', `stdout', および `stderr' の各パイプのトランスポートをクローズします。
@end deffn

@node プロトコル<2>,使用例<26>,トランスポート,トランスポートとプロトコル
@anchor{library/asyncio-protocol asyncio-protocol}@anchor{3892}@anchor{library/asyncio-protocol protocols}@anchor{38d0}
@subsubsection プロトコル


`ソースコード:' Lib/asyncio/protocols.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/protocols.py}


__________________________________________________________________


asyncio はネットワークプロトコルを実装するために使う抽象基底クラス群を提供します。これらのクラスは @ref{3893,,トランスポート} と組み合わせて使うことが想定されています。

抽象基底プロトコルクラスの派生クラスはメソッドの一部または全てを実装することができます。これらのメソッドは全てコールバックです: それらは、データを受信した、などの決まったイベントに対してトランスポートから呼び出されます。基底プロトコルメソッドは対応するトランスポートから呼び出されるべきです。

@menu
* 基底プロトコル:: 
* 基底プロトコル: 基底プロトコル<2>. 
* ストリーミングプロトコル:: 
* バッファリングされたストリーミングプロトコル:: 
* データグラムプロトコル:: 
* サブプロセスプロトコル:: 

@end menu

@node 基底プロトコル,基底プロトコル<2>,,プロトコル<2>
@anchor{library/asyncio-protocol base-protocols}@anchor{38ef}
@subsubsection 基底プロトコル


@geindex BaseProtocol (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio BaseProtocol}@anchor{38d3}
@deffn {クラス} asyncio.BaseProtocol

全てのプロトコルクラスが共有する全てのメソッドを持った基底プロトコルクラスです。
@end deffn

@geindex Protocol (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio Protocol}@anchor{38d4}
@deffn {クラス} asyncio.Protocol (BaseProtocol)

ストリーミングプロトコル (TCP, Unix ソケットなど) を実装するための基底クラスです。
@end deffn

@geindex BufferedProtocol (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio BufferedProtocol}@anchor{c94}
@deffn {クラス} asyncio.BufferedProtocol (BaseProtocol)

受信バッファーを手動で制御するストリーミングプロトコルを実装するための基底クラスです。
@end deffn

@geindex DatagramProtocol (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio DatagramProtocol}@anchor{8de}
@deffn {クラス} asyncio.DatagramProtocol (BaseProtocol)

データグラム (UDP) プロトコルを実装するための基底クラスです。
@end deffn

@geindex SubprocessProtocol (asyncio のクラス)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol}@anchor{38b3}
@deffn {クラス} asyncio.SubprocessProtocol (BaseProtocol)

子プロセスと (一方向パイプを通じて) 通信するプロトコルを実装するための基底クラスです。
@end deffn

@node 基底プロトコル<2>,ストリーミングプロトコル,基底プロトコル,プロトコル<2>
@anchor{library/asyncio-protocol base-protocol}@anchor{38f0}
@subsubsection 基底プロトコル


全ての asyncio プロトコルは基底プロトコルのコールバックを実装することができます。

@subsubheading 通信のコールバック


コネクションコールバックは全てのプロトコルから、成功したコネクションそれぞれにつきただ一度だけ呼び出されます。その他の全てのプロトコルコールバックはこれら2つのメソッドの間に呼び出すことができます。

@geindex connection_made() (asyncio.BaseProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio BaseProtocol connection_made}@anchor{3894}
@deffn {メソッド} BaseProtocol.connection_made (transport)

コネクションが作成されたときに呼び出されます。

引数 `transport' はコネクションをあらわすトランスポートです。プロトコルはトランスポートへの参照を保存する責任を負います。
@end deffn

@geindex connection_lost() (asyncio.BaseProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio BaseProtocol connection_lost}@anchor{38d8}
@deffn {メソッド} BaseProtocol.connection_lost (exc)

コネクションが失われた、あるいはクローズされたときに呼び出されます。

引数は例外オブジェクトまたは @ref{885,,None} になります。@ref{885,,None} のとき、通常の EOF が受信されたか、あるいはコネクションがこちら側から中止またはクローズされたことを意味します。
@end deffn

@subsubheading フロー制御コールバック


フロー制御コールバックは、プロトコルによって実行される書き込み処理を停止または再開するためにトランスポートから呼び出されます。

詳しくは @ref{38e2,,set_write_buffer_limits()} メソッドのドキュメントを参照してください。

@geindex pause_writing() (asyncio.BaseProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio BaseProtocol pause_writing}@anchor{38e3}
@deffn {メソッド} BaseProtocol.pause_writing ()

トランスポートのバッファーサイズが最高水位点 (high watermark) を超えたときに呼び出されます。
@end deffn

@geindex resume_writing() (asyncio.BaseProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio BaseProtocol resume_writing}@anchor{38e4}
@deffn {メソッド} BaseProtocol.resume_writing ()

トランスポートのバッファーサイズが最低水位点 (low watermark) に達したきに呼び出されます。
@end deffn

バッファーサイズが最高水位点と等しい場合、 @ref{38e3,,pause_writing()} は呼び出されません: バッファーサイズは必ず制限値を超えなければなりません。

それに対して、 @ref{38e4,,resume_writing()} はバッファーサイズが最低水位点と等しいかそれよりも小さい場合に呼び出されます。これらの境界条件は、どちらの基準値もゼロである場合の処理が期待通りとなることを保証するために重要です。

@node ストリーミングプロトコル,バッファリングされたストリーミングプロトコル,基底プロトコル<2>,プロトコル<2>
@anchor{library/asyncio-protocol streaming-protocols}@anchor{38f1}
@subsubsection ストリーミングプロトコル


@ref{d09,,loop.create_server()}, @ref{4ca,,loop.create_unix_server()}, @ref{818,,loop.create_connection()}, @ref{37ff,,loop.create_unix_connection()}, @ref{9de,,loop.connect_accepted_socket()}, @ref{3846,,loop.connect_read_pipe()}, そして @ref{3847,,loop.connect_write_pipe()} などのイベントメソッドはストリーミングプロトコルを返すファクトリを受け付けます。

@geindex data_received() (asyncio.Protocol のメソッド)
@anchor{library/asyncio-protocol asyncio Protocol data_received}@anchor{1b02}
@deffn {メソッド} Protocol.data_received (data)

データを受信したときに呼び出されます。`data' は受信したデータを含む空ではないバイト列オブジェクトになります。

データがバッファーされるか、チャンキングされるか、または再構築されるかはトランスポートに依存します。一般には、特定のセマンティクスを信頼するべきではなく、代わりにデータのパースを全般的かつ柔軟に行うべきです。ただし、データは常に正しい順序で受信されます。

このメソッドは、コネクションがオープンである間は何度でも呼び出すことができます。

いっぽうで、 @ref{38f2,,protocol.eof_received()} メソッドは最大でも一度だけ呼び出されます。いったん @code{eof_received()} が呼び出されると、それ以降 @code{data_received()} は呼び出されません。
@end deffn

@geindex eof_received() (asyncio.Protocol のメソッド)
@anchor{library/asyncio-protocol asyncio Protocol eof_received}@anchor{38f2}
@deffn {メソッド} Protocol.eof_received ()

コネクションの相手方がこれ以上データを送信しないことを伝えてきたとき (例えば相手方が asyncio を使用しており、 @ref{38e0,,transport.write_eof()} を呼び出した場合) に呼び出されます。

このメソッドは (@code{None} を含む) 偽値 を返すことがあり、その場合トランスポートは自身をクローズします。一方メソッドが真値を返す場合は、利用しているプロトコルがトランスポートをクローズするかどうかを決めます。デフォルトの実装は @code{None} を返すため、コネクションは暗黙のうちにクローズされます。

SSL を含む一部のトランスポートはハーフクローズ接続をサポートしません。そのような場合このメソッドが真値を返すとコネクションはクローズされます。
@end deffn

ステートマシン:

@example
start -> connection_made
    [-> data_received]*
    [-> eof_received]?
-> connection_lost -> end
@end example

@node バッファリングされたストリーミングプロトコル,データグラムプロトコル,ストリーミングプロトコル,プロトコル<2>
@anchor{library/asyncio-protocol buffered-streaming-protocols}@anchor{38f3}
@subsubsection バッファリングされたストリーミングプロトコル



Added in version 3.7.


バッファー付きプロトコルは  @ref{38f1,,ストリーミングプロトコル} をサポートするイベントループメソッドで利用することができます。

@code{BufferedProtocol} 実装は受信バッファーの手動での明示的な割り当てや制御を可能にします。イベントループはプロトコルにより提供されるバッファを利用することにより不要なデータのコピーを避けることができます。これにより大量のデータを受信するプロトコルにおいて顕著なパフォーマンスの向上をもたらします。精巧なプロトコル実装によりバッファー割り当ての数を劇的に減少させることができます。

以下に示すコールバックは @ref{c94,,BufferedProtocol} インスタンスに対して呼び出されます:

@geindex get_buffer() (asyncio.BufferedProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio BufferedProtocol get_buffer}@anchor{38f4}
@deffn {メソッド} BufferedProtocol.get_buffer (sizehint)

新しい受信バッファを割り当てるために呼び出します。

`sizehint' は返されるバッファーの推奨される最小サイズです。 `sizehint' によって推奨された値より小さい、または大きいサイズのバッファーを返すことは容認されています。 -1 がセットされた場合、バッファーサイズは任意となります。サイズがゼロのバッファーを返すとエラーになります。

@code{get_buffer()} は @ref{260,,バッファープロトコル} を実装したオブジェクトを返さなければなりません。
@end deffn

@geindex buffer_updated() (asyncio.BufferedProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio BufferedProtocol buffer_updated}@anchor{38f5}
@deffn {メソッド} BufferedProtocol.buffer_updated (nbytes)

受信データによりバッファが更新された場合に呼び出されます。

`nbytes' はバッファに書き込まれた総バイト数です。
@end deffn

@geindex eof_received() (asyncio.BufferedProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio BufferedProtocol eof_received}@anchor{38f6}
@deffn {メソッド} BufferedProtocol.eof_received ()

@ref{38f2,,protocol.eof_received()} メソッドのドキュメントを参照してください。
@end deffn

コネクションの間、 @ref{38f4,,get_buffer()} は何度でも呼び出すことができます。しかし @ref{38f2,,protocol.eof_received()} が呼び出されるのは最大でも1回で、もし呼び出されると、それ以降 @ref{38f4,,get_buffer()} と @ref{38f5,,buffer_updated()} が呼び出されることはありません。

ステートマシン:

@example
start -> connection_made
    [-> get_buffer
        [-> buffer_updated]?
    ]*
    [-> eof_received]?
-> connection_lost -> end
@end example

@node データグラムプロトコル,サブプロセスプロトコル,バッファリングされたストリーミングプロトコル,プロトコル<2>
@anchor{library/asyncio-protocol datagram-protocols}@anchor{38f7}
@subsubsection データグラムプロトコル


データグラムプロトコルのインスタンスは @ref{93c,,loop.create_datagram_endpoint()} メソッドに渡されたプロトコルファクトリによって生成されるべきです。

@geindex datagram_received() (asyncio.DatagramProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio DatagramProtocol datagram_received}@anchor{38f8}
@deffn {メソッド} DatagramProtocol.datagram_received (data, addr)

データグラムを受信したときに呼び出されます。`data' は受信データを含むバイトオブジェクトです。`addr' はデータを送信するピアのアドレスです; 正確な形式はトランスポートに依存します。
@end deffn

@geindex error_received() (asyncio.DatagramProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio DatagramProtocol error_received}@anchor{38f9}
@deffn {メソッド} DatagramProtocol.error_received (exc)

直前の送信あるいは受信が @ref{2c0,,OSError} を送出したときに呼び出されます。`exc' は @ref{2c0,,OSError} のインスタンスになります。

このメソッドが呼ばれるのは、トランスポート (UDP など) がデータグラムを受信側に配信できなかったことが検出されたなどの、まれな場合においてのみです。ほとんどの場合、データグラムが配信できなければそのまま通知されることなく破棄されます。
@end deffn

@cartouche
@quotation 注釈 
BSD システム (macOS, FreeBSD など) ではフロー制御はサポートされていません。これは非常に多くのパケットを書き込もうとしたことによる送信の失敗を検出する信頼できる方法が存在しないためです。

ソケットは常に '準備ができた状態' のように振る舞いますが、超過したパケットは破棄されます。この場合 @code{errno} を @ref{1b71,,errno.ENOBUFS} に設定した @ref{2c0,,OSError} 例外が送出されることがあります。もし例外が送出された場合は @ref{38f9,,DatagramProtocol.error_received()} に通知されますが、送出されない場合は単に無視されます。
@end quotation
@end cartouche

@node サブプロセスプロトコル,,データグラムプロトコル,プロトコル<2>
@anchor{library/asyncio-protocol asyncio-subprocess-protocols}@anchor{3849}@anchor{library/asyncio-protocol subprocess-protocols}@anchor{38fa}
@subsubsection サブプロセスプロトコル


サブプロセスプロトコルのインスタンスは  @ref{3843,,loop.subprocess_exec()} と @ref{3844,,loop.subprocess_shell()} メソッドに渡されたプロトコルファクトリにより生成されるべきです。

@geindex pipe_data_received() (asyncio.SubprocessProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol pipe_data_received}@anchor{1b50}
@deffn {メソッド} SubprocessProtocol.pipe_data_received (fd, data)

子プロセスが標準出力または標準エラー出力のパイプにデータを書き込んだ時に呼び出されます。

`fd' はパイプのファイル記述子を表す整数です。

`data' は受信データを含む空でないバイトオブジェクトです。
@end deffn

@geindex pipe_connection_lost() (asyncio.SubprocessProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol pipe_connection_lost}@anchor{38fb}
@deffn {メソッド} SubprocessProtocol.pipe_connection_lost (fd, exc)

子プロセスと通信するパイプのいずれかがクローズされたときに呼び出されます。

`fd' はクローズされたファイル記述子を表す整数です。
@end deffn

@geindex process_exited() (asyncio.SubprocessProtocol のメソッド)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol process_exited}@anchor{1b4f}
@deffn {メソッド} SubprocessProtocol.process_exited ()

子プロセスが終了したときに呼び出されます。

これは、 @ref{1b50,,pipe_data_received()} と @ref{38fb,,pipe_connection_lost()} メソッドの前に呼び出すことができます。
@end deffn

@node 使用例<26>,,プロトコル<2>,トランスポートとプロトコル
@anchor{library/asyncio-protocol examples}@anchor{38d5}
@subsubsection 使用例


@menu
* TCP エコーサーバー:: 
* TCP エコークライアント:: 
* UDP エコーサーバー:: 
* UDP エコークライアント:: 
* 既存のソケットへの接続:: 
* loop.subprocess_exec() と SubprocessProtocol: loop subprocess_exec と SubprocessProtocol. 

@end menu

@node TCP エコーサーバー,TCP エコークライアント,,使用例<26>
@anchor{library/asyncio-protocol asyncio-example-tcp-echo-server-protocol}@anchor{3814}@anchor{library/asyncio-protocol tcp-echo-server}@anchor{38fc}
@subsubsection TCP エコーサーバー


@ref{d09,,loop.create_server()} メソッドを使って TCP エコーサーバーを生成し、受信したデータをそのまま送り返して、最後にコネクションをクローズします:

@example
import asyncio


class EchoServerProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        peername = transport.get_extra_info('peername')
        print('Connection from @{@}'.format(peername))
        self.transport = transport

    def data_received(self, data):
        message = data.decode()
        print('Data received: @{!r@}'.format(message))

        print('Send: @{!r@}'.format(message))
        self.transport.write(data)

        print('Close the client socket')
        self.transport.close()


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    server = await loop.create_server(
        EchoServerProtocol,
        '127.0.0.1', 8888)

    async with server:
        await server.serve_forever()


asyncio.run(main())
@end example


@subsubheading 参考


@ref{3812,,ストリームを使った TCP エコーサーバー} の例では高水準の @ref{d0f,,asyncio.start_server()} 関数を使っています。


@node TCP エコークライアント,UDP エコーサーバー,TCP エコーサーバー,使用例<26>
@anchor{library/asyncio-protocol asyncio-example-tcp-echo-client-protocol}@anchor{3811}@anchor{library/asyncio-protocol tcp-echo-client}@anchor{38fd}
@subsubsection TCP エコークライアント


@ref{818,,loop.create_connection()} メソッドを使った TCP エコークライアントは、データを送信したあとコネクションがクローズされるまで待機します:

@example
import asyncio


class EchoClientProtocol(asyncio.Protocol):
    def __init__(self, message, on_con_lost):
        self.message = message
        self.on_con_lost = on_con_lost

    def connection_made(self, transport):
        transport.write(self.message.encode())
        print('Data sent: @{!r@}'.format(self.message))

    def data_received(self, data):
        print('Data received: @{!r@}'.format(data.decode()))

    def connection_lost(self, exc):
        print('The server closed the connection')
        self.on_con_lost.set_result(True)


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    on_con_lost = loop.create_future()
    message = 'Hello World!'

    transport, protocol = await loop.create_connection(
        lambda: EchoClientProtocol(message, on_con_lost),
        '127.0.0.1', 8888)

    # Wait until the protocol signals that the connection
    # is lost and close the transport.
    try:
        await on_con_lost
    finally:
        transport.close()


asyncio.run(main())
@end example


@subsubheading 参考


@ref{380f,,ストリームを使った TCP エコークライアント} の例では高水準の @ref{d0e,,asyncio.open_connection()} 関数を使っています。


@node UDP エコーサーバー,UDP エコークライアント,TCP エコークライアント,使用例<26>
@anchor{library/asyncio-protocol asyncio-udp-echo-server-protocol}@anchor{3898}@anchor{library/asyncio-protocol udp-echo-server}@anchor{38fe}
@subsubsection UDP エコーサーバー


@ref{93c,,loop.create_datagram_endpoint()} メソッドを使った UDP エコーサーバーは受信したデータをそのまま送り返します:

@example
import asyncio


class EchoServerProtocol:
    def connection_made(self, transport):
        self.transport = transport

    def datagram_received(self, data, addr):
        message = data.decode()
        print('Received %r from %s' % (message, addr))
        print('Send %r to %s' % (message, addr))
        self.transport.sendto(data, addr)


async def main():
    print("Starting UDP server")

    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    # One protocol instance will be created to serve all
    # client requests.
    transport, protocol = await loop.create_datagram_endpoint(
        EchoServerProtocol,
        local_addr=('127.0.0.1', 9999))

    try:
        await asyncio.sleep(3600)  # Serve for 1 hour.
    finally:
        transport.close()


asyncio.run(main())
@end example

@node UDP エコークライアント,既存のソケットへの接続,UDP エコーサーバー,使用例<26>
@anchor{library/asyncio-protocol asyncio-udp-echo-client-protocol}@anchor{3897}@anchor{library/asyncio-protocol udp-echo-client}@anchor{38ff}
@subsubsection UDP エコークライアント


@ref{93c,,loop.create_datagram_endpoint()} メソッドを使った UDP エコークライアントはデータを送信し、応答を受信するとトランスポートをクローズします:

@example
import asyncio


class EchoClientProtocol:
    def __init__(self, message, on_con_lost):
        self.message = message
        self.on_con_lost = on_con_lost
        self.transport = None

    def connection_made(self, transport):
        self.transport = transport
        print('Send:', self.message)
        self.transport.sendto(self.message.encode())

    def datagram_received(self, data, addr):
        print("Received:", data.decode())

        print("Close the socket")
        self.transport.close()

    def error_received(self, exc):
        print('Error received:', exc)

    def connection_lost(self, exc):
        print("Connection closed")
        self.on_con_lost.set_result(True)


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    on_con_lost = loop.create_future()
    message = "Hello World!"

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: EchoClientProtocol(message, on_con_lost),
        remote_addr=('127.0.0.1', 9999))

    try:
        await on_con_lost
    finally:
        transport.close()


asyncio.run(main())
@end example

@node 既存のソケットへの接続,loop subprocess_exec と SubprocessProtocol,UDP エコークライアント,使用例<26>
@anchor{library/asyncio-protocol asyncio-example-create-connection}@anchor{3818}@anchor{library/asyncio-protocol connecting-existing-sockets}@anchor{3900}
@subsubsection 既存のソケットへの接続


プロトコルを設定した @ref{818,,loop.create_connection()} メソッドを使ってソケットがデータを受信するまで待機します:

@example
import asyncio
import socket


class MyProtocol(asyncio.Protocol):

    def __init__(self, on_con_lost):
        self.transport = None
        self.on_con_lost = on_con_lost

    def connection_made(self, transport):
        self.transport = transport

    def data_received(self, data):
        print("Received:", data.decode())

        # We are done: close the transport;
        # connection_lost() will be called automatically.
        self.transport.close()

    def connection_lost(self, exc):
        # The socket has been closed
        self.on_con_lost.set_result(True)


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()
    on_con_lost = loop.create_future()

    # Create a pair of connected sockets
    rsock, wsock = socket.socketpair()

    # Register the socket to wait for data.
    transport, protocol = await loop.create_connection(
        lambda: MyProtocol(on_con_lost), sock=rsock)

    # Simulate the reception of data from the network.
    loop.call_soon(wsock.send, 'abc'.encode())

    try:
        await protocol.on_con_lost
    finally:
        transport.close()
        wsock.close()

asyncio.run(main())
@end example


@subsubheading 参考


@ref{3819,,ファイル記述子の読み込みイベントを監視する} 例では低レベルの @ref{381a,,loop.add_reader()} メソッドを使ってファイル記述子 (FD) を登録しています。

@ref{3816,,ストリームを使ってデータを待ち受けるオープンなソケットを登録する} 例ではコルーチン内で @ref{d0e,,open_connection()} 関数によって生成されたストリームを使っています。


@node loop subprocess_exec と SubprocessProtocol,,既存のソケットへの接続,使用例<26>
@anchor{library/asyncio-protocol asyncio-example-subprocess-proto}@anchor{3858}@anchor{library/asyncio-protocol loop-subprocess-exec-and-subprocessprotocol}@anchor{3901}
@subsubsection loop.subprocess_exec() と SubprocessProtocol


サブプロセスからの出力を受け取り、サブプロセスが終了するまで待機するために使われるサブプロセスプロトコルの例です。

サブプロセスは @ref{3843,,loop.subprocess_exec()} メソッドにより生成されます:

@example
import asyncio
import sys

class DateProtocol(asyncio.SubprocessProtocol):
    def __init__(self, exit_future):
        self.exit_future = exit_future
        self.output = bytearray()
        self.pipe_closed = False
        self.exited = False

    def pipe_connection_lost(self, fd, exc):
        self.pipe_closed = True
        self.check_for_exit()

    def pipe_data_received(self, fd, data):
        self.output.extend(data)

    def process_exited(self):
        self.exited = True
        # process_exited() method can be called before
        # pipe_connection_lost() method: wait until both methods are
        # called.
        self.check_for_exit()

    def check_for_exit(self):
        if self.pipe_closed and self.exited:
            self.exit_future.set_result(True)

async def get_date():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    code = 'import datetime; print(datetime.datetime.now())'
    exit_future = asyncio.Future(loop=loop)

    # Create the subprocess controlled by DateProtocol;
    # redirect the standard output into a pipe.
    transport, protocol = await loop.subprocess_exec(
        lambda: DateProtocol(exit_future),
        sys.executable, '-c', code,
        stdin=None, stderr=None)

    # Wait for the subprocess exit using the process_exited()
    # method of the protocol.
    await exit_future

    # Close the stdout pipe.
    transport.close()

    # Read the output which was collected by the
    # pipe_data_received() method of the protocol.
    data = bytes(protocol.output)
    return data.decode('ascii').rstrip()

date = asyncio.run(get_date())
print(f"Current date: @{date@}")
@end example

高水準の API を使って書かれた @ref{3857,,同様の例} も参照してください。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ポリシー,プラットフォームでのサポート,トランスポートとプロトコル,asyncio --- 非同期 I/O
@anchor{library/asyncio-policy doc}@anchor{3902}@anchor{library/asyncio-policy asyncio-policies}@anchor{3880}@anchor{library/asyncio-policy policies}@anchor{3903}@anchor{library/asyncio-policy translation-repo}@anchor{3904}
@subsubsection ポリシー


@cartouche
@quotation 警告 
Policies are deprecated and will be removed in Python 3.16.
Users are encouraged to use the @ref{2f3,,asyncio.run()} function
or the @ref{2f5,,asyncio.Runner} with `loop_factory' to use
the desired loop implementation.
@end quotation
@end cartouche

An event loop policy is a global object
used to get and set the current @ref{f76,,event loop},
as well as create new event loops.
The default policy can be @ref{3905,,replaced} with
@ref{3906,,built-in alternatives}
to use different event loop implementations,
or substituted by a @ref{3907,,custom policy}
that can override these behaviors.

The @ref{3908,,policy object}
gets and sets a separate event loop per `context'.
This is per-thread by default,
though custom policies could define `context' differently.

Custom event loop policies can control the behavior of
@ref{2f2,,get_event_loop()}, @ref{1b55,,set_event_loop()}, and @ref{37c6,,new_event_loop()}.

ポリシーオブジェクトは @ref{30e,,AbstractEventLoopPolicy} 抽象基底クラスで定義された API を実装しなければなりません。

@menu
* ポリシーの取得と設定:: 
* ポリシーオブジェクト:: 
* ポリシーのカスタマイズ:: 

@end menu

@node ポリシーの取得と設定,ポリシーオブジェクト,,ポリシー
@anchor{library/asyncio-policy asyncio-policy-get-set}@anchor{3905}@anchor{library/asyncio-policy getting-and-setting-the-policy}@anchor{3909}
@subsubsection ポリシーの取得と設定


以下の関数は現在のプロセスに対するポリシーの取得や設定をするために使われます:

@geindex get_event_loop_policy() (asyncio モジュール)
@anchor{library/asyncio-policy asyncio get_event_loop_policy}@anchor{312}
@deffn {の関数} asyncio.get_event_loop_policy ()

プロセス全体にわたる現在のポリシーを返します。


バージョン 3.14 で非推奨: The @ref{312,,get_event_loop_policy()} function is deprecated and
will be removed in Python 3.16.

@end deffn

@geindex set_event_loop_policy() (asyncio モジュール)
@anchor{library/asyncio-policy asyncio set_event_loop_policy}@anchor{313}
@deffn {の関数} asyncio.set_event_loop_policy (policy)

プロセス全体にわたる現在のポリシーを `policy' に設定します。

`policy' が @code{None} の場合、デフォルトポリシーが現在のポリシーに戻されます。


バージョン 3.14 で非推奨: The @ref{313,,set_event_loop_policy()} function is deprecated and
will be removed in Python 3.16.

@end deffn

@node ポリシーオブジェクト,ポリシーのカスタマイズ,ポリシーの取得と設定,ポリシー
@anchor{library/asyncio-policy asyncio-policy-objects}@anchor{3908}@anchor{library/asyncio-policy policy-objects}@anchor{390a}
@subsubsection ポリシーオブジェクト


イベントループポリシーの抽象基底クラスは以下のように定義されています:

@geindex AbstractEventLoopPolicy (asyncio のクラス)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy}@anchor{30e}
@deffn {クラス} asyncio.AbstractEventLoopPolicy

asyncio ポリシーの抽象基底クラスです。

@geindex get_event_loop() (asyncio.AbstractEventLoopPolicy のメソッド)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy get_event_loop}@anchor{390b}
@deffn {メソッド} get_event_loop ()

現在のコンテキストのイベントループを取得します。

@ref{b58,,AbstractEventLoop} のインターフェースを実装したイベントループオブジェクトを返します。

このメソッドは @code{None} を返してはいけません。


バージョン 3.6 で変更.

@end deffn

@geindex set_event_loop() (asyncio.AbstractEventLoopPolicy のメソッド)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy set_event_loop}@anchor{390c}
@deffn {メソッド} set_event_loop (loop)

現在のコンテキストにイベントループ `loop' を設定します。
@end deffn

@geindex new_event_loop() (asyncio.AbstractEventLoopPolicy のメソッド)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy new_event_loop}@anchor{390d}
@deffn {メソッド} new_event_loop ()

新しいイベントループオブジェクトを生成して返します。

このメソッドは @code{None} を返してはいけません。
@end deffn


バージョン 3.14 で非推奨: The @ref{30e,,AbstractEventLoopPolicy} class is deprecated and
will be removed in Python 3.16.

@end deffn
@anchor{library/asyncio-policy asyncio-policy-builtin}@anchor{3906}
asyncio は以下の組み込みポリシーを提供します:

@geindex DefaultEventLoopPolicy (asyncio のクラス)
@anchor{library/asyncio-policy asyncio DefaultEventLoopPolicy}@anchor{30f}
@deffn {クラス} asyncio.DefaultEventLoopPolicy

デフォルトの asyncio ポリシーです。Unix では @ref{314,,SelectorEventLoop} 、Windows では @ref{81d,,ProactorEventLoop} を使います。

デフォルトのポリシーを手動でインストールする必要はありません。 asyncio はデフォルトポリシーを使うように自動的に構成されます。


バージョン 3.8 で変更: Windows では @ref{81d,,ProactorEventLoop} がデフォルトで使われるようになりました。



バージョン 3.14 で変更: The @ref{2f2,,get_event_loop()} method of the default asyncio policy now
raises a @ref{244,,RuntimeError} if there is no set event loop.



バージョン 3.14 で非推奨: The @ref{30f,,DefaultEventLoopPolicy} class is deprecated and
will be removed in Python 3.16.

@end deffn

@geindex WindowsSelectorEventLoopPolicy (asyncio のクラス)
@anchor{library/asyncio-policy asyncio WindowsSelectorEventLoopPolicy}@anchor{310}
@deffn {クラス} asyncio.WindowsSelectorEventLoopPolicy

@ref{314,,SelectorEventLoop} イベントループ実装を使った別のイベントループポリシーです。

@ref{213f,,Availability}: Windows.


バージョン 3.14 で非推奨: The @ref{310,,WindowsSelectorEventLoopPolicy} class is deprecated and
will be removed in Python 3.16.

@end deffn

@geindex WindowsProactorEventLoopPolicy (asyncio のクラス)
@anchor{library/asyncio-policy asyncio WindowsProactorEventLoopPolicy}@anchor{311}
@deffn {クラス} asyncio.WindowsProactorEventLoopPolicy

@ref{81d,,ProactorEventLoop} イベントループ実装を使った別のイベントループポリシーです。

@ref{213f,,Availability}: Windows.


バージョン 3.14 で非推奨: The @ref{311,,WindowsProactorEventLoopPolicy} class is deprecated and
will be removed in Python 3.16.

@end deffn

@node ポリシーのカスタマイズ,,ポリシーオブジェクト,ポリシー
@anchor{library/asyncio-policy asyncio-custom-policies}@anchor{3907}@anchor{library/asyncio-policy custom-policies}@anchor{390e}
@subsubsection ポリシーのカスタマイズ


新しいイベントループのポリシーを実装するためには、以下に示すように @ref{30f,,DefaultEventLoopPolicy} を継承して振る舞いを変更したいメソッドをオーバーライドすることが推奨されます。:

@example
class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):

    def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        loop = super().get_event_loop()
        # Do something with loop ...
        return loop

asyncio.set_event_loop_policy(MyEventLoopPolicy())
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node プラットフォームでのサポート,Extending,ポリシー,asyncio --- 非同期 I/O
@anchor{library/asyncio-platforms doc}@anchor{390f}@anchor{library/asyncio-platforms asyncio-platform-support}@anchor{38a2}@anchor{library/asyncio-platforms platform-support}@anchor{3910}@anchor{library/asyncio-platforms translation-repo}@anchor{3911}
@subsubsection プラットフォームでのサポート


@ref{b,,asyncio} モジュールは可搬的であるようにデザインされていますが、いくつかのプラットフォームでは、その根底にあるアーキテクチャや性能による微妙な動作の違いや制限があります。

@menu
* 全てのプラットホーム:: 
* Windows: Windows<84>. 
* macOS: macOS<52>. 

@end menu

@node 全てのプラットホーム,Windows<84>,,プラットフォームでのサポート
@anchor{library/asyncio-platforms all-platforms}@anchor{3912}
@subsubsection 全てのプラットホーム



@itemize *

@item 
@ref{381a,,loop.add_reader()} と @ref{38a0,,loop.add_writer()} をファイル I/O を監視するためには使えません。
@end itemize

@node Windows<84>,macOS<52>,全てのプラットホーム,プラットフォームでのサポート
@anchor{library/asyncio-platforms windows}@anchor{3913}
@subsubsection Windows


`ソースコード:' Lib/asyncio/proactor_events.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/proactor_events.py}, Lib/asyncio/windows_events.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/windows_events.py}, Lib/asyncio/windows_utils.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/windows_utils.py}


__________________________________________________________________



バージョン 3.8 で変更: Windows では @ref{81d,,ProactorEventLoop} がデフォルトのイベントループになりました。


全ての Windows 上のイベントループは以下のメソッドをサポートしません:


@itemize *

@item 
@ref{37ff,,loop.create_unix_connection()} と @ref{4ca,,loop.create_unix_server()} はサポートされません。 @ref{1bb0,,socket.AF_UNIX} ソケットファミリーは Unix 固有です。

@item 
@ref{38a9,,loop.add_signal_handler()} と @ref{38aa,,loop.remove_signal_handler()} はサポートされていません。
@end itemize

@ref{314,,SelectorEventLoop} は以下の制限があります:


@itemize *

@item 
@ref{3914,,SelectSelector} はソケットイベントの待ち受けに使われます: このクラスはソケットをサポートしますが 512 ソケットまでに制限されています。

@item 
@ref{381a,,loop.add_reader()} と @ref{38a0,,loop.add_writer()} はソケットハンドルのみを受け付けます (たとえばパイプファイル記述子はサポートされていません)。

@item 
パイプはサポートされていません。従って @ref{3846,,loop.connect_read_pipe()} と @ref{3847,,loop.connect_write_pipe()} の2つのメソッドは未実装です。

@item 
@ref{37ba,,Subprocesses} はサポートされていません。すなわち @ref{3843,,loop.subprocess_exec()} と @ref{3844,,loop.subprocess_shell()} の2つのメソッドは未実装です。
@end itemize

@ref{81d,,ProactorEventLoop} は以下の制限があります:


@itemize *

@item 
@ref{381a,,loop.add_reader()} と @ref{38a0,,loop.add_writer()} はサポートされていません。
@end itemize

Windows のモノトニッククロックの時間分解能は、通常約15.6ミリ秒です。最高分解能は0.5ミリ秒です。分解能はハードウエア (HPET@footnote{https://en.wikipedia.org/wiki/High_Precision_Event_Timer} が利用可能かどうか) および WIndows の設定に依存します。

@menu
* Windows におけるサブプロセスのサポート:: 

@end menu

@node Windows におけるサブプロセスのサポート,,,Windows<84>
@anchor{library/asyncio-platforms asyncio-windows-subprocess}@anchor{3845}@anchor{library/asyncio-platforms subprocess-support-on-windows}@anchor{3915}
@subsubsection Windows におけるサブプロセスのサポート


Windows において、デフォルトのイベントループ @ref{81d,,ProactorEventLoop} はサブプロセスをサポートしますが、 @ref{314,,SelectorEventLoop} はサポートしません。

@node macOS<52>,,Windows<84>,プラットフォームでのサポート
@anchor{library/asyncio-platforms macos}@anchor{3916}
@subsubsection macOS


最近の macOS バージョンは完全にサポートされています。

@subsubheading 10.8 以前の macOS


macOS 10.6, 10.7 および 10.8 では、デフォルトイベントループは @ref{3917,,selectors.KqueueSelector} をしていますが、このクラスはこれらの macOS バージョンのキャラクターデバイスをサポートしていません。これらの macOS バージョンでキャラクターデバイスをサポートするためには @ref{314,,SelectorEventLoop} で @ref{3914,,SelectSelector} または @ref{dd1,,PollSelector} を使うように手動で設定します。以下はその例です:

@example
import asyncio
import selectors

selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Extending,高水準の API インデックス,プラットフォームでのサポート,asyncio --- 非同期 I/O
@anchor{library/asyncio-extending doc}@anchor{3918}@anchor{library/asyncio-extending extending}@anchor{3919}@anchor{library/asyncio-extending translation-repo}@anchor{391a}
@subsubsection Extending


The main direction for @ref{b,,asyncio} extending is writing custom `event loop'
classes. Asyncio has helpers that could be used to simplify this task.

@cartouche
@quotation 注釈 
Third-parties should reuse existing asyncio code with caution,
a new Python version is free to break backward compatibility
in `internal' part of API.
@end quotation
@end cartouche

@menu
* Writing a Custom Event Loop:: 
* Future and Task private constructors:: 
* Task lifetime support:: 

@end menu

@node Writing a Custom Event Loop,Future and Task private constructors,,Extending
@anchor{library/asyncio-extending writing-a-custom-event-loop}@anchor{391b}
@subsubsection Writing a Custom Event Loop


@ref{b58,,asyncio.AbstractEventLoop} declares very many methods.  Implementing all them
from scratch is a tedious job.

A loop can get many common methods implementation for free by inheriting from
@code{asyncio.BaseEventLoop}.

In turn, the successor should implement a bunch of `private' methods declared but not
implemented in @code{asyncio.BaseEventLoop}.

For example, @code{loop.create_connection()} checks arguments, resolves DNS addresses, and
calls @code{loop._make_socket_transport()} that should be implemented by inherited class.
The @code{_make_socket_transport()} method is not documented and is considered as an
`internal' API.

@node Future and Task private constructors,Task lifetime support,Writing a Custom Event Loop,Extending
@anchor{library/asyncio-extending future-and-task-private-constructors}@anchor{391c}
@subsubsection Future and Task private constructors


@ref{dc6,,asyncio.Future} and @ref{1c7,,asyncio.Task} should be never created directly,
please use corresponding @ref{e74,,loop.create_future()} and @ref{1ca,,loop.create_task()},
or @ref{1c9,,asyncio.create_task()} factories instead.

However, third-party `event loops' may `reuse' built-in future and task implementations
for the sake of getting a complex and highly optimized code for free.

For this purpose the following, `private' constructors are listed:

@geindex __init__() (asyncio.Future のメソッド)
@anchor{library/asyncio-extending asyncio Future __init__}@anchor{391d}
@deffn {メソッド} Future.__init__ (*, loop=None)

Create a built-in future instance.

`loop' is an optional event loop instance.
@end deffn

@geindex __init__() (asyncio.Task のメソッド)
@anchor{library/asyncio-extending asyncio Task __init__}@anchor{391e}
@deffn {メソッド} Task.__init__ (coro, *, loop=None, name=None, context=None)

Create a built-in task instance.

`loop' is an optional event loop instance. The rest of arguments are described in
@ref{1ca,,loop.create_task()} description.


バージョン 3.11 で変更: `context' argument is added.

@end deffn

@node Task lifetime support,,Future and Task private constructors,Extending
@anchor{library/asyncio-extending task-lifetime-support}@anchor{391f}
@subsubsection Task lifetime support


A third party task implementation should call the following functions to keep a task
visible by @ref{b4f,,asyncio.all_tasks()} and @ref{6a5,,asyncio.current_task()}:

@geindex _register_task() (asyncio モジュール)
@anchor{library/asyncio-extending asyncio _register_task}@anchor{3920}
@deffn {の関数} asyncio._register_task (task)

Register a new `task' as managed by `asyncio'.

Call the function from a task constructor.
@end deffn

@geindex _unregister_task() (asyncio モジュール)
@anchor{library/asyncio-extending asyncio _unregister_task}@anchor{3921}
@deffn {の関数} asyncio._unregister_task (task)

Unregister a `task' from `asyncio' internal structures.

The function should be called when a task is about to finish.
@end deffn

@geindex _enter_task() (asyncio モジュール)
@anchor{library/asyncio-extending asyncio _enter_task}@anchor{3922}
@deffn {の関数} asyncio._enter_task (loop, task)

Switch the current task to the `task' argument.

Call the function just before executing a portion of embedded `coroutine'
(@ref{2419,,coroutine.send()} or @ref{71b,,coroutine.throw()}).
@end deffn

@geindex _leave_task() (asyncio モジュール)
@anchor{library/asyncio-extending asyncio _leave_task}@anchor{3923}
@deffn {の関数} asyncio._leave_task (loop, task)

Switch the current task back from `task' to @code{None}.

Call the function just after @ref{2419,,coroutine.send()} or @ref{71b,,coroutine.throw()}
execution.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 高水準の API インデックス,低水準の API インデックス,Extending,asyncio --- 非同期 I/O
@anchor{library/asyncio-api-index doc}@anchor{a79}@anchor{library/asyncio-api-index high-level-api-index}@anchor{3924}@anchor{library/asyncio-api-index translation-repo}@anchor{3925}
@subsubsection 高水準の API インデックス


このページには、すべての高水準の 非同期/待機 可能な asyncio API が一覧になっています。

@menu
* Task:: 
* キュー: キュー<2>. 
* サブプロセス: サブプロセス<2>. 
* ストリーム: ストリーム<2>. 
* 同期:: 
* 例外: 例外<17>. 

@end menu

@node Task,キュー<2>,,高水準の API インデックス
@anchor{library/asyncio-api-index tasks}@anchor{3926}
@subsubsection Task


ユーティリティは asyncio プログラムを実行し、タスクを作成し、タイムアウトのある複数の機能を待っています。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2f3,,run()}

@tab

イベントループを作成し、コルーチンを実行し、ループを閉じます。

@item

@ref{2f5,,Runner}

@tab

複数の非同期関数呼び出しをシンプルにするコンテキストマネージャ。

@item

@ref{1c7,,Task}

@tab

Task オブジェクト

@item

@ref{4d1,,TaskGroup}

@tab

タスクのグループを保持するコンテキストマネージャ。グループに属するすべてのタスクが完了するのを待つのに便利で信頼性のある方法を提供します。

@item

@ref{1c9,,create_task()}

@tab

asyncio タスクを開始し、それを返します。

@item

@ref{6a5,,current_task()}

@tab

現在のタスクを返します。

@item

@ref{b4f,,all_tasks()}

@tab

イベントループのまだ終了していないすべてのタスクを返します。

@item

@code{await} @ref{c64,,sleep()}

@tab

数秒間スリープします。

@item

@code{await} @ref{813,,gather()}

@tab

並行してスケジュールして、待ちます。

@item

@code{await} @ref{815,,wait_for()}

@tab

タイムアウトで実行します。

@item

@code{await} @ref{c65,,shield()}

@tab

取り消しから保護します。

@item

@code{await} @ref{6a7,,wait()}

@tab

完了かどうかを監視します。

@item

@ref{814,,timeout()}

@tab

タイムアウト付きで実行します。 @code{wait_for} が適していない場合に有用です。

@item

@ref{ae5,,to_thread()}

@tab

別の OS スレッドで非同期的に関数を実行します。

@item

@ref{a82,,run_coroutine_threadsafe()}

@tab

別の OS スレッドからコルーチンの実行をスケジュールします。

@item

@code{for in} @ref{4c6,,as_completed()}

@tab

@code{for} ループ向けにコルーチンの完了を監視します。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{37d9,,asyncio.gather() を使って複数の処理を並列に実行する} 。

@item 
@ref{37e1,,asyncio.wait_for() を使って強制的にタイムアウトする} 。

@item 
@ref{37f6,,非同期処理をキャンセルする} 。

@item 
@ref{37d7,,asyncio.sleep() を使う} 。

@item 
@ref{37b8,,Tasks のドキュメント} も参照してください。
@end itemize

@node キュー<2>,サブプロセス<2>,Task,高水準の API インデックス
@anchor{library/asyncio-api-index queues}@anchor{3927}
@subsubsection キュー


キューは複数の非同期タスクの分散処理、コネクションプールやpub/subパターンの実装に適しています。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{c6a,,Queue}

@tab

FIFO キューです。

@item

@ref{3869,,PriorityQueue}

@tab

優先度付きのキューです。

@item

@ref{386b,,LifoQueue}

@tab

LIFO キュー (スタック) です。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{386d,,asyncio.Queue を使って複数のタスクを分散処理する}.

@item 
@ref{37bb,,Queue のドキュメント} も参照してください。
@end itemize

@node サブプロセス<2>,ストリーム<2>,キュー<2>,高水準の API インデックス
@anchor{library/asyncio-api-index subprocesses}@anchor{3928}
@subsubsection サブプロセス


サブプロセスを生成したり、シェルコマンドを実行するためのユーティリティです。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{c6b,,create_subprocess_exec()}

@tab

サブプロセスを作成します。

@item

@code{await} @ref{c6c,,create_subprocess_shell()}

@tab

シェルコマンドを実行します。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{383d,,シェルコマンドを実行する}。

@item 
@ref{37ba,,サブプロセス API}  のドキュメントも参照してください。
@end itemize

@node ストリーム<2>,同期,サブプロセス<2>,高水準の API インデックス
@anchor{library/asyncio-api-index streams}@anchor{3929}
@subsubsection ストリーム


ネットワーク IO を利用するための高水準の APIs です。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{d0e,,open_connection()}

@tab

TCP コネクションを確立します。

@item

@code{await} @ref{37fe,,open_unix_connection()}

@tab

Unix のソケット接続を確立します。

@item

@code{await} @ref{d0f,,start_server()}

@tab

TCP サーバーを起動します。

@item

@code{await} @ref{3800,,start_unix_server()}

@tab

Unix のソケットサーバーを起動します。

@item

@ref{1c7d,,StreamReader}

@tab

ネットワークからデータを受信するための高水準の async/await オブジェクトです。

@item

@ref{1a70,,StreamWriter}

@tab

ネットワークにデータを送信するための高水準の async/await オブジェクトです。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{37fa,,TCPクライアントの例}.

@item 
@ref{37b9,,ストリーム API} のドキュメントも参照してください。
@end itemize

@node 同期,例外<17>,ストリーム<2>,高水準の API インデックス
@anchor{library/asyncio-api-index synchronization}@anchor{392a}
@subsubsection 同期


タスク内で利用できるスレッド並列処理に似た同期プリミティブです。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{c66,,Lock}

@tab

ミューテックスロックです。

@item

@ref{2f4,,Event}

@tab

イベントオブジェクトです。

@item

@ref{c67,,Condition}

@tab

条件変数オブジェクトです。

@item

@ref{c68,,Semaphore}

@tab

セマフォ (semaphore) です。

@item

@ref{c69,,BoundedSemaphore}

@tab

有限セマフォ (bounded semaphore) です。

@item

@ref{816,,Barrier}

@tab

バリアーオブジェクト。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{3826,,asyncio.Event の使用例} 。

@item 
@ref{3834,,asyncio.Barrier を使う}。

@item 
asyncio の @ref{37bc,,同期プリミティブ} についてのドキュメントも参照してください。
@end itemize

@node 例外<17>,,同期,高水準の API インデックス
@anchor{library/asyncio-api-index exceptions}@anchor{392b}
@subsubsection 例外



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{4d4,,asyncio.CancelledError}

@tab

タスクがキャンセルされた場合に送出されます。 @ref{4d3,,Task.cancel()} も参照してください。

@item

@ref{817,,asyncio.BrokenBarrierError}

@tab

バリアーが破壊された場合に送出されます。 @ref{3833,,Barrier.wait()} も参照してください。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{37f6,,CancelledError を処理してキャンセル要求に対応するコードを実行する}.

@item 
@ref{386f,,asyncio に特有な例外の完全なリスト} も参照してください。
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 低水準の API インデックス,asyncio での開発,高水準の API インデックス,asyncio --- 非同期 I/O
@anchor{library/asyncio-llapi-index doc}@anchor{392c}@anchor{library/asyncio-llapi-index low-level-api-index}@anchor{392d}@anchor{library/asyncio-llapi-index translation-repo}@anchor{392e}
@subsubsection 低水準の API インデックス


このページでは低水準の asyncio API を全てリストしています。

@menu
* イベントループの取得:: 
* イベントループのメソッド: イベントループのメソッド<2>. 
* トランスポート: トランスポート<2>. 
* プロトコル: プロトコル<3>. 
* イベントループのポリシー:: 

@end menu

@node イベントループの取得,イベントループのメソッド<2>,,低水準の API インデックス
@anchor{library/asyncio-llapi-index obtaining-the-event-loop}@anchor{392f}
@subsubsection イベントループの取得



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{d01,,asyncio.get_running_loop()}

@tab

実行中のイベントループを取得するために `利用が推奨される' 関数です。

@item

@ref{2f2,,asyncio.get_event_loop()}

@tab

Get an event loop instance (running or current via the current policy).

@item

@ref{1b55,,asyncio.set_event_loop()}

@tab

ポリシーに基づいて引数のイベントループを "カレント" (current event loop) に設定します。

@item

@ref{37c6,,asyncio.new_event_loop()}

@tab

新しいイベントループのインスタンスを生成します。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{38cb,,asyncio.get_running_loop() を使う}。
@end itemize

@node イベントループのメソッド<2>,トランスポート<2>,イベントループの取得,低水準の API インデックス
@anchor{library/asyncio-llapi-index event-loop-methods}@anchor{3930}
@subsubsection イベントループのメソッド


See also the main documentation section about the
@ref{3886,,イベントループのメソッド}.

@subsubheading ライフサイクル



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{e72,,loop.run_until_complete()}

@tab

Future/Task/awaitable が完了するまで実行します。

@item

@ref{3888,,loop.run_forever()}

@tab

イベントループを永久に実行します。

@item

@ref{e77,,loop.stop()}

@tab

イベントループを停止します。

@item

@ref{388a,,loop.close()}

@tab

イベントループをクローズします。

@item

@ref{3889,,loop.is_running()}

@tab

イベントループが実行中の場合 @code{True} を返します。

@item

@ref{fc3,,loop.is_closed()}

@tab

イベントループがクローズされている場合 @code{True} を返します。

@item

@code{await} @ref{e79,,loop.shutdown_asyncgens()}

@tab

非同期ジェネレータをクローズします。

@end multitable


@subsubheading デバッグ



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{fc1,,loop.set_debug()}

@tab

デバッグモードを有効化または無効化します。

@item

@ref{fc2,,loop.get_debug()}

@tab

現在のデバッグモードを取得します。

@end multitable


@subsubheading コールバックのスケジューリング



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{cfa,,loop.call_soon()}

@tab

コールバックを即座に実行します。

@item

@ref{cfb,,loop.call_soon_threadsafe()}

@tab

@ref{cfa,,loop.call_soon()} のスレッドセーフ版です。

@item

@ref{cfc,,loop.call_later()}

@tab

与えられた遅延時間の `経過後' にコールバックを実行します。

@item

@ref{cfd,,loop.call_at()}

@tab

`与えられた時刻に' コールバックを実行します。

@end multitable


@subsubheading Thread/Interpreter/Process Pool



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{ae6,,loop.run_in_executor()}

@tab

CPUバウンドなブロッキング関数、またはその他のブロッキング関数を @ref{24,,concurrent.futures} 実行オブジェクト (executor) 上で実行します。

@item

@ref{94a,,loop.set_default_executor()}

@tab

@ref{ae6,,loop.run_in_executor()} のデフォルト実行オブジェクト (executor) を設定します。

@end multitable


@subsubheading タスクとフューチャー



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{e74,,loop.create_future()}

@tab

@ref{dc6,,Future} オブジェクトを生成します。

@item

@ref{1ca,,loop.create_task()}

@tab

コルーチンを @ref{1c7,,Task} としてスケジュールします。

@item

@ref{1c8,,loop.set_task_factory()}

@tab

@ref{1ca,,loop.create_task()} が @ref{1c7,,Tasks} を生成する際に使われるファクトリを設定します。

@item

@ref{fc5,,loop.get_task_factory()}

@tab

@ref{1ca,,loop.create_task()} が @ref{1c7,,Tasks} を生成するファクトリを取得します。

@end multitable


@subsubheading DNS



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{e0e,,loop.getaddrinfo()}

@tab

@ref{1ac3,,socket.getaddrinfo()} の非同期版です。

@item

@code{await} @ref{e0f,,loop.getnameinfo()}

@tab

@ref{1a3a,,socket.getnameinfo()} の非同期版です。

@end multitable


@subsubheading ネットワークとプロセス間通信 (IPC)



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{818,,loop.create_connection()}

@tab

TCP接続を確立します。

@item

@code{await} @ref{d09,,loop.create_server()}

@tab

TCPサーバーを起動します。

@item

@code{await} @ref{37ff,,loop.create_unix_connection()}

@tab

Unix のソケット接続を確立します。

@item

@code{await} @ref{4ca,,loop.create_unix_server()}

@tab

Create a Unix socket server.

@item

@code{await} @ref{9de,,loop.connect_accepted_socket()}

@tab

@ref{fa1,,socket} を @code{(transport, protocol)} のペアでラップします。

@item

@code{await} @ref{93c,,loop.create_datagram_endpoint()}

@tab

データグラム (UDP) 接続を確立します。

@item

@code{await} @ref{389c,,loop.sendfile()}

@tab

確立した接続 (transport) を通じてファイルを送信します。

@item

@code{await} @ref{cff,,loop.start_tls()}

@tab

既存の接続を TLS にアップグレードします。

@item

@code{await} @ref{3846,,loop.connect_read_pipe()}

@tab

パイプの読み出し側を @code{(transport, protocol)} のペアでラップします。

@item

@code{await} @ref{3847,,loop.connect_write_pipe()}

@tab

パイプの書き込み側を @code{(transport, protocol)} のペアでラップします。

@end multitable


@subsubheading ソケット



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{e0b,,loop.sock_recv()}

@tab

@ref{fa1,,socket} からデータを受信します。

@item

@code{await} @ref{d00,,loop.sock_recv_into()}

@tab

@ref{fa1,,socket} からデータを受信し、バッファに送信します。

@item

@code{await} @ref{81b,,loop.sock_recvfrom()}

@tab

Receive a datagram from the @ref{fa1,,socket}.

@item

@code{await} @ref{81c,,loop.sock_recvfrom_into()}

@tab

Receive a datagram from the @ref{fa1,,socket} into a buffer.

@item

@code{await} @ref{e0c,,loop.sock_sendall()}

@tab

@ref{fa1,,socket} にデータを送信します。

@item

@code{await} @ref{81a,,loop.sock_sendto()}

@tab

Send a datagram via the @ref{fa1,,socket} to the given address.

@item

@code{await} @ref{fc8,,loop.sock_connect()}

@tab

@ref{fa1,,socket} を接続します。

@item

@code{await} @ref{e0d,,loop.sock_accept()}

@tab

@ref{fa1,,socket} の接続を受け入れます。

@item

@code{await} @ref{d04,,loop.sock_sendfile()}

@tab

Send a file over the @ref{fa1,,socket}.

@item

@ref{381a,,loop.add_reader()}

@tab

ファイル記述子が読み込み可能かどうかの監視を開始します。

@item

@ref{389f,,loop.remove_reader()}

@tab

ファイル記述子が読み込み可能かどうかの監視を停止します。

@item

@ref{38a0,,loop.add_writer()}

@tab

ファイル記述子が書き込み可能かどうかの監視を開始します。

@item

@ref{38a1,,loop.remove_writer()}

@tab

ファイル記述子が書き込み可能かどうかの監視を停止します。

@end multitable


@subsubheading Unix シグナル



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{38a9,,loop.add_signal_handler()}

@tab

@ref{cb,,signal} 用のハンドラーを追加します。

@item

@ref{38aa,,loop.remove_signal_handler()}

@tab

@ref{cb,,signal} 用のハンドラーを削除します。

@end multitable


@subsubheading サブプロセス



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{3843,,loop.subprocess_exec()}

@tab

サブプロセスを生成します。

@item

@ref{3844,,loop.subprocess_shell()}

@tab

シェルコマンドからサブプロセスを生成します。

@end multitable


@subsubheading エラー処理



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{38ae,,loop.call_exception_handler()}

@tab

例外ハンドラを呼び出します。

@item

@ref{38ad,,loop.set_exception_handler()}

@tab

新しい例外ハンドラーを設定します。

@item

@ref{e75,,loop.get_exception_handler()}

@tab

現在の例外ハンドラーを取得します。

@item

@ref{38af,,loop.default_exception_handler()}

@tab

デフォルトの例外ハンドラー実装です。

@end multitable


@subsubheading 使用例



@itemize *

@item 
@ref{38ba,,Using asyncio.new_event_loop() and loop.run_forever()}.

@item 
@ref{38bc,,loop.call_later() を使う}。

@item 
@code{loop.create_connection()} を使って @ref{3811,,an echo-client} を実装する。

@item 
@code{loop.create_connection()} を使って @ref{3818,,ソケットに接続する}。

@item 
@ref{3819,,add_reader() を使ってファイルデスクリプタの読み込みイベントを監視する}。

@item 
@ref{38bf,,loop.add_signal_handler() を使う}。

@item 
@ref{3858,,loop.subprocess_exec() を使う}。
@end itemize

@node トランスポート<2>,プロトコル<3>,イベントループのメソッド<2>,低水準の API インデックス
@anchor{library/asyncio-llapi-index transports}@anchor{3931}
@subsubsection トランスポート


全てのトランスポートは以下のメソッドを実装します:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{3896,,transport.close()}

@tab

トランスポートをクローズします。

@item

@ref{e73,,transport.is_closing()}

@tab

トランスポートを閉じている最中か閉じていた場合 @code{True} を返します。

@item

@ref{c93,,transport.get_extra_info()}

@tab

トランスポートについての情報をリクエストします。

@item

@ref{38db,,transport.set_protocol()}

@tab

トランスポートに新しいプロトコルを設定します。

@item

@ref{38dc,,transport.get_protocol()}

@tab

現在のプロトコルを返します。

@end multitable


データを受信できるトランスポート (TCP 接続、 Unix 接続、パイプなど) のメソッドです。該当するトランスポートは @ref{818,,loop.create_connection()}, @ref{37ff,,loop.create_unix_connection()}, @ref{3846,,loop.connect_read_pipe()} などの戻り値です:

@subsubheading 読み込みトランスポート



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{d11,,transport.is_reading()}

@tab

トランスポートがデータを受信中の場合 @code{True} を返します。

@item

@ref{d13,,transport.pause_reading()}

@tab

データの受信を停止します。

@item

@ref{d12,,transport.resume_reading()}

@tab

データの受信を再開します。

@end multitable


データを送信できるトランスポート (TCP 接続、 Unix 接続、パイプなど) のメソッドです。該当するトランスポートは @ref{818,,loop.create_connection()}, @ref{37ff,,loop.create_unix_connection()}, @ref{3847,,loop.connect_write_pipe()} などの戻り値です:

@subsubheading トランスポートにデータを書き込みます。



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{17ca,,transport.write()}

@tab

トランスポートにデータを書き込みます。

@item

@ref{17c9,,transport.writelines()}

@tab

トランスポートにバッファの内容を書き込みます。

@item

@ref{38df,,transport.can_write_eof()}

@tab

トランスポートが 終端 (EOF) の送信をサポートしている場合 @ref{e07,,True} を返します。

@item

@ref{38e0,,transport.write_eof()}

@tab

バッファに残っているデータをフラッシュしてから終端 (EOF) を送信して、トランスポートをクローズします。

@item

@ref{38b7,,transport.abort()}

@tab

トランスポートを即座にクローズします。

@item

@ref{38e1,,transport.get_write_buffer_size()}

@tab

Return the current size of the output buffer.

@item

@ref{fc4,,transport.get_write_buffer_limits()}

@tab

書き込みフロー制御の高水位点と低水位点を取得します。

@item

@ref{38e2,,transport.set_write_buffer_limits()}

@tab

書き込みフロー制御の高水位点と低水位点を設定します。

@end multitable


@ref{93c,,loop.create_datagram_endpoint()} が返すトランスポート:

@subsubheading データグラムトランスポート



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{4cb,,transport.sendto()}

@tab

リモートピアにデータを送信します。

@item

@ref{38e6,,transport.abort()}

@tab

トランスポートを即座にクローズします。

@end multitable


サブプロセスに対するトランスポートの低レベルな抽象化です。 @ref{3843,,loop.subprocess_exec()} や @ref{3844,,loop.subprocess_shell()} の戻り値です:

@subsubheading サブプロセス化されたトランスポート



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{38e8,,transport.get_pid()}

@tab

サブプロセスのプロセス ID を返します。

@item

@ref{38e9,,transport.get_pipe_transport()}

@tab

リクエストされた通信パイプ (標準入力 `stdin', 標準出力 `stdout', または標準エラー出力 `stderr') のためのトランスポートを返します。

@item

@ref{38ea,,transport.get_returncode()}

@tab

サブプロセスの終了ステータスを返します。

@item

@ref{38eb,,transport.kill()}

@tab

サブプロセスを強制終了 (kill) します。

@item

@ref{38ed,,transport.send_signal()}

@tab

サブプロセスにシグナルを送信します。

@item

@ref{38ec,,transport.terminate()}

@tab

サブプロセスを停止します。

@item

@ref{38ee,,transport.close()}

@tab

サブプロセスを強制終了 (kill) し、全てのパイプをクローズします。

@end multitable


@node プロトコル<3>,イベントループのポリシー,トランスポート<2>,低水準の API インデックス
@anchor{library/asyncio-llapi-index protocols}@anchor{3932}
@subsubsection プロトコル


プロトコルクラスは以下の `コールバックメソッド' を実装することができます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{3894,,connection_made()}

@tab

コネクションが作成されたときに呼び出されます。

@item

@code{callback} @ref{38d8,,connection_lost()}

@tab

コネクションが失われた、あるいはクローズされたときに呼び出されます。

@item

@code{callback} @ref{38e3,,pause_writing()}

@tab

トランスポートのバッファーサイズが最高水位点 (High-Water Mark) を超えたときに呼び出されます。

@item

@code{callback} @ref{38e4,,resume_writing()}

@tab

トランスポートのバッファーサイズが最低水位点 (Low-Water Mark) に達したきに呼び出されます。

@end multitable


@subsubheading ストリーミングプロトコル (TCP, Unix ソケット, パイプ)



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{1b02,,data_received()}

@tab

データを受信したときに呼び出されます。

@item

@code{callback} @ref{38f2,,eof_received()}

@tab

終端 (EOF) を受信したときに呼び出されます。

@end multitable


@subsubheading バッファリングされたストリーミングプロトコル



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{38f4,,get_buffer()}

@tab

新しい受信バッファを割り当てるために呼び出します。

@item

@code{callback} @ref{38f5,,buffer_updated()}

@tab

受信データによりバッファが更新された場合に呼び出されます。

@item

@code{callback} @ref{38f6,,eof_received()}

@tab

終端 (EOF) を受信したときに呼び出されます。

@end multitable


@subsubheading データグラムプロトコル



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{38f8,,datagram_received()}

@tab

データグラムを受信したときに呼び出されます。

@item

@code{callback} @ref{38f9,,error_received()}

@tab

直前の送信あるいは受信が @ref{2c0,,OSError} を送出したときに呼び出されます。

@end multitable


@subsubheading サブプロセスプロトコル



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{1b50,,pipe_data_received()}

@tab

子プロセスが標準出力 (`stdout') または標準エラー出力 (`stderr') のパイプにデータを書き込んだときに呼び出されます。

@item

@code{callback} @ref{38fb,,pipe_connection_lost()}

@tab

子プロセスと通信するパイプのいずれかがクローズされたときに呼び出されます。

@item

@code{callback} @ref{1b4f,,process_exited()}

@tab

Called when the child process has exited. It can be called before
@ref{1b50,,pipe_data_received()} and
@ref{38fb,,pipe_connection_lost()} methods.

@end multitable


@node イベントループのポリシー,,プロトコル<3>,低水準の API インデックス
@anchor{library/asyncio-llapi-index event-loop-policies}@anchor{3933}
@subsubsection イベントループのポリシー


ポリシーは @ref{2f2,,asyncio.get_event_loop()} などの関数の振る舞いを変更する低レベルなメカニズムです。詳細は @ref{3880,,ポリシーについてのセクション} を参照してください。

@subsubheading ポリシーへのアクセス



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{312,,asyncio.get_event_loop_policy()}

@tab

プロセス全体にわたる現在のポリシーを返します。

@item

@ref{313,,asyncio.set_event_loop_policy()}

@tab

新たなプロセス全体にわたるポリシーを設定します。

@item

@ref{30e,,AbstractEventLoopPolicy}

@tab

ポリシーオブジェクトの基底クラスです。

@end multitable


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node asyncio での開発,,低水準の API インデックス,asyncio --- 非同期 I/O
@anchor{library/asyncio-dev doc}@anchor{3934}@anchor{library/asyncio-dev asyncio-dev}@anchor{3935}@anchor{library/asyncio-dev developing-with-asyncio}@anchor{3936}@anchor{library/asyncio-dev translation-repo}@anchor{3937}
@subsubsection asyncio での開発


非同期プログラミングは伝統的な "同期的" プログラミングとは異なります。

このページはよくある間違いや落とし穴を列挙し、それらを回避する方法を説明します。

@menu
* デバッグモード:: 
* 並行処理とマルチスレッド処理:: 
* ブロッキングコードの実行:: 
* ログ記録: ログ記録<3>. 
* 待ち受け処理を伴わないコルーチンの検出:: 
* 回収されない例外の検出:: 

@end menu

@node デバッグモード,並行処理とマルチスレッド処理,,asyncio での開発
@anchor{library/asyncio-dev asyncio-debug-mode}@anchor{213a}@anchor{library/asyncio-dev debug-mode}@anchor{3938}
@subsubsection デバッグモード


asyncio はデフォルトで本運用モードで実行されます。いっぽう、開発を容易にするために asyncio は "デバッグモード" を持っています。

asyncio のデバッグモードを有効化する方法はいくつかあります:


@itemize *

@item 
@geindex PYTHONASYNCIODEBUG
@geindex 環境変数; PYTHONASYNCIODEBUG
@ref{2139,,PYTHONASYNCIODEBUG} 環境変数の値を @code{1} に設定する。

@item 
@ref{508,,Python 開発モード} を使う。

@item 
@ref{2f3,,asyncio.run()} 実行時に @code{debug=True} を設定する。

@item 
@ref{fc1,,loop.set_debug()} を呼び出す。
@end itemize

デバッグモードを有効化することに加え、以下も検討してください:


@itemize *

@item 
@ref{3939,,asyncio ロガー} のログレベルを @ref{20de,,logging.DEBUG} に設定します。例えばアプリケーションの起動時に以下を実行します:

@example
logging.basicConfig(level=logging.DEBUG)
@end example

@item 
@ref{118,,warnings} モジュールが @ref{54c,,ResourceWarning} 警告を表示するように設定します。やり方のひとつは @ref{ac6,,-W} @code{default} コマンドラインオプションを使うことです。
@end itemize

デバッグモードが有効化されたときの動作:


@itemize *

@item 
スレッドセーフでない asyncio APIs の多く (@ref{cfa,,loop.call_soon()} や @ref{cfd,,loop.call_at()} など) は、誤ったスレッドから呼び出されたときに例外を送出します。

@item 
I/O セレクタが I/O 処理を実行する時間が長すぎる場合、その実行時間が記録されます。

@item 
実行時間が100ミリ秒を超えるコールバックは記録されます。 "遅い" の判断基準となる実行時間の最小値は @ref{38b1,,loop.slow_callback_duration} 属性で設定できます。
@end itemize

@node 並行処理とマルチスレッド処理,ブロッキングコードの実行,デバッグモード,asyncio での開発
@anchor{library/asyncio-dev asyncio-multithreading}@anchor{37e8}@anchor{library/asyncio-dev concurrency-and-multithreading}@anchor{393a}
@subsubsection 並行処理とマルチスレッド処理


イベントループはスレッド（典型的にはメインスレッド）内で動作し、すべてのコールバックとタスクをそのスレッド内で実行します。ひとつのタスクがイベントループ内で実行される間、他のタスクを同じスレッド内で実行することはできません。タスクが @code{await} 式を実行すると、実行中のタスクはサスペンドされ、イベントループは次のタスクを実行します。

別の OS スレッドからのコールバック (@ref{2d9c,,callback}) をスケジュールする場合、  @ref{cfb,,loop.call_soon_threadsafe()} メソッドを使ってください。例:

@example
loop.call_soon_threadsafe(callback, *args)
@end example

ほぼ全ての非同期オブジェクトはスレッドセーフではありませんが、タスクやコールバックの外側で非同期オブジェクトを使うコードが存在しない限り、それが問題にはなることはほとんどありません。もしそのような目的で低レベルの asyncio API を呼び出すようなコードを書く必要がある場合、 @ref{cfb,,loop.call_soon_threadsafe()} メソッドを使ってください。例:

@example
loop.call_soon_threadsafe(fut.cancel)
@end example

別の OS スレッドからコルーチンオブジェクトをスケジュールする場合は、 @ref{a82,,run_coroutine_threadsafe()} メソッドを使ってください。 @ref{a82,,run_coroutine_threadsafe()} は結果にアクセスするための @ref{13ca,,concurrent.futures.Future}  オブジェクトを返します:

@example
async def coro_func():
     return await asyncio.sleep(1, 42)

# Later in another OS thread:

future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
# Wait for the result:
result = future.result()
@end example

シグナルの処理を行うには、イベントループはメインスレッド内で実行しなければなりません。

The @ref{ae6,,loop.run_in_executor()} method can be used with a
@ref{949,,concurrent.futures.ThreadPoolExecutor} or
@ref{1d2,,InterpreterPoolExecutor} to execute
blocking code in a different OS thread without blocking the OS thread
that the event loop runs in.

現在のところ、 (たとえば @ref{98,,multiprocessing} で開始したような) 別のプロセスからコルーチンやコールバックを直接スケジュールすることはできません。 @ref{3886,,イベントループのメソッド} 節では、イベントループをブロックすることなくパイプからの読み込みやファイルデスクリプタの監視ができる API のリストを掲載しています。さらに、 asyncio の @ref{37ba,,サブプロセス} API はイベントループからプロセスを開始したりプロセスと通信したりする方法を提供します。 最後に、前述の @ref{ae6,,loop.run_in_executor()} メソッドは @ref{1d6,,concurrent.futures.ProcessPoolExecutor} とともに使用することで、別のプロセス内でコードを実行することもできます。

@node ブロッキングコードの実行,ログ記録<3>,並行処理とマルチスレッド処理,asyncio での開発
@anchor{library/asyncio-dev asyncio-handle-blocking}@anchor{393b}@anchor{library/asyncio-dev running-blocking-code}@anchor{393c}
@subsubsection ブロッキングコードの実行


ブロッキングコード (CPU バウンドなコード) を直接呼び出すべきではありません。たとえば、 CPU 負荷の高い関数を1秒実行したとすると、並行に処理されている全ての非同期タスクと I/O 処理は1秒遅れる可能性があります。

An executor can be used to run a task in a different thread,
including in a different interpreter, or even in
a different process to avoid blocking the OS thread with the
event loop.  See the @ref{ae6,,loop.run_in_executor()} method for more
details.

@node ログ記録<3>,待ち受け処理を伴わないコルーチンの検出,ブロッキングコードの実行,asyncio での開発
@anchor{library/asyncio-dev asyncio-logger}@anchor{3939}@anchor{library/asyncio-dev logging}@anchor{393d}
@subsubsection ログ記録


asyncio は @ref{8b,,logging} モジュールを利用し、 全てのログ記録は @code{"asyncio"} ロガーを通じて行われます。

デフォルトのログレベルは @ref{20df,,logging.INFO} ですが、これは簡単に調節できます:

@example
logging.getLogger("asyncio").setLevel(logging.WARNING)
@end example

ネットワークログ記録は、イベントループをブロックし得ます。ログ処理のスレッドを分離するか、ノンブロッキング IO を使用することを推奨します。例えば、 @ref{393e,,ブロックする handler を扱う} を見てください。

@node 待ち受け処理を伴わないコルーチンの検出,回収されない例外の検出,ログ記録<3>,asyncio での開発
@anchor{library/asyncio-dev asyncio-coroutine-not-scheduled}@anchor{393f}@anchor{library/asyncio-dev detect-never-awaited-coroutines}@anchor{3940}
@subsubsection 待ち受け処理を伴わないコルーチンの検出


コルーチンが呼び出されただけで、待ち受け処理がない場合 (たとえば @code{await coro()} のかわりに @code{coro()} と書いてしまった場合) 、またはコルーチンが @ref{1c9,,asyncio.create_task()} を使わずにスケジュールされた場合、 asyncio は @ref{4d7,,RuntimeWarning} 警告を送出します:

@example
import asyncio

async def test():
    print("never scheduled")

async def main():
    test()

asyncio.run(main())
@end example

出力:

@example
test.py:7: RuntimeWarning: coroutine 'test' was never awaited
  test()
@end example

デバッグモードの出力:

@example
test.py:7: RuntimeWarning: coroutine 'test' was never awaited
Coroutine created at (most recent call last)
  File "../t.py", line 9, in <module>
    asyncio.run(main(), debug=True)

  < .. >

  File "../t.py", line 7, in main
    test()
  test()
@end example

通常の修正方法はコルーチンを待ち受ける (await) か、 @ref{1c9,,asyncio.create_task()} 関数を呼び出すことです:

@example
async def main():
    await test()
@end example

@node 回収されない例外の検出,,待ち受け処理を伴わないコルーチンの検出,asyncio での開発
@anchor{library/asyncio-dev detect-never-retrieved-exceptions}@anchor{3941}
@subsubsection 回収されない例外の検出


もし @ref{e78,,Future.set_exception()} メソッドが呼び出されても、その Future オブジェクトを待ち受けていなければ、例外は決してユーザーコードまで伝播しません。この場合 asyncio は、 Future オブジェクトがガベージコレクションの対象となったときにログメッセージを送出することがあります。

処理されない例外の例:

@example
import asyncio

async def bug():
    raise Exception("not consumed")

async def main():
    asyncio.create_task(bug())

asyncio.run(main())
@end example

出力:

@example
Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
  exception=Exception('not consumed')>

Traceback (most recent call last):
  File "test.py", line 4, in bug
    raise Exception("not consumed")
Exception: not consumed
@end example

タスクが生成された箇所を特定するには、 @ref{213a,,デバッグモードを有効化して} トレースバックを取得してください:

@example
asyncio.run(main(), debug=True)
@end example

デバッグモードの出力:

@example
Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
    exception=Exception('not consumed') created at asyncio/tasks.py:321>

source_traceback: Object created at (most recent call last):
  File "../t.py", line 9, in <module>
    asyncio.run(main(), debug=True)

< .. >

Traceback (most recent call last):
  File "../t.py", line 4, in bug
    raise Exception("not consumed")
Exception: not consumed
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@cartouche
@quotation 注釈 
asyncio のソースコードは Lib/asyncio/@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/} にあります。
@end quotation
@end cartouche

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node socket --- 低水準ネットワークインターフェース,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー,asyncio --- 非同期 I/O,ネットワーク通信とプロセス間通信
@anchor{library/socket doc}@anchor{3942}@anchor{library/socket module-socket}@anchor{d1}@anchor{library/socket socket-low-level-networking-interface}@anchor{3943}@anchor{library/socket translation-repo}@anchor{3944}
@subsection @code{socket} --- 低水準ネットワークインターフェース


@geindex module; socket

`ソースコード:' Lib/socket.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/socket.py}


__________________________________________________________________


このモジュールはBSDの `ソケット(socket)' インターフェイスへのアクセスを提供します。これは、近代的なUnixシステム、Windows、MacOS、その他多くのプラットフォームで動作します。

@cartouche
@quotation 注釈 
いくつかの挙動はプラットフォームに依存します。オペレーティングシステムのソケットAPIを呼び出しているためです。
@end quotation
@end cartouche

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@geindex object;socket

Pythonインターフェースは、Unixのソケット用システムコールとライブラリインターフェースを、そのままPythonのオブジェクト指向スタイルに変換したものです。各種ソケット関連のシステムコールは、 @ref{fa1,,socket()} 関数で生成される `socket オブジェクト' のメソッドとして実装されています。 メソッドの引数は C のインターフェイスよりも多少高水準で、例えばファイルに対する @code{read()} や @code{write()} メソッドと同様に、 受信時のバッファ確保は自動的に処理され、送信時のバッファ長は暗黙的に決まります。


@subsubheading 参考



@table @asis

@item Module @ref{d2,,socketserver}

ネットワークサーバの開発を省力化するためのクラス群。

@item Module @ref{d5,,ssl}

ソケットオブジェクトに対する TLS/SSL ラッパー.
@end table


@menu
* ソケットファミリー:: 
* モジュールの内容:: 
* socket オブジェクト:: 
* ソケットタイムアウトの注意事項:: 
* 使用例: 使用例<27>. 

@end menu

@node ソケットファミリー,モジュールの内容,,socket --- 低水準ネットワークインターフェース
@anchor{library/socket socket-families}@anchor{3945}
@subsubsection ソケットファミリー


どのシステムで実行するかとビルドオプションに依存しますが、このモジュールによって多様なソケットファミリーをサポートします。

特定のソケットオブジェクトによって必要とされるアドレスフォーマットは、ソケットオブジェクトが生成されたときに指定されたアドレスファミリーを元に自動的に選択されます。ソケットアドレスは次の通りです。


@itemize -

@item 
ファイルシステム上のノードに束縛された @ref{1bb0,,AF_UNIX} ソケットのアドレスは、ファイルシステムエンコーディングと @code{'surrogateescape'} エラーハンドラ (
@geindex Python Enhancement Proposals; PEP 383
PEP 383@footnote{https://peps.python.org/pep-0383/} を参照) を使って文字列として表現されます。 Linux の抽象名前空間のアドレスは、先頭が null バイトとなる @ref{193,,bytes-like object} として返されます。この名前空間のソケットは通常のファイルシステム上のソケットと通信できるので、 Linux 上で動作することを意図したプログラムは両方のアドレスを扱う必要がある可能性があります。文字列と bytes-like オブジェクトはどちらのタイプのアドレスにも引数として渡すことができます。


バージョン 3.3 で変更: これまでは @ref{1bb0,,AF_UNIX} ソケットパスは UTF-8 エンコーディングを使用するものとされていました。



バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。

@end itemize
@anchor{library/socket host-port}@anchor{3946}

@itemize -

@item 
@ref{1bad,,AF_INET} アドレスファミリーには、 @code{(host, port)} ペアがアドレスとして利用されます。 `host' はホスト名か @code{'daring.cwi.nl'} のようなインターネットドメインか、 @code{'100.50.200.5'} のような IPv4 アドレスで、 `port' は整数です。


@itemize -

@item 
IPv4ではホストアドレスのほかに2つの特別な形式が使用できます。@code{'@w{'}} はすべてのインターフェイスにバインドされるために使われる @code{INADDR_ANY} を表し、@code{'<broadcast>'} は @code{INADDR_BROADCAST} を表します。これらの動作はIPv6と互換性がありません。そのためもしもあなたがPythonプログラムでIPv6をサポートする予定があるのならばこれらを避けたほうが良いでしょう。
@end itemize

@item 
For @ref{1bae,,AF_INET6} address family, a four-tuple @code{(host, port, flowinfo,
scope_id)} is used, where `flowinfo' and `scope_id' represent the @code{sin6_flowinfo}
and @code{sin6_scope_id} members in @code{struct sockaddr_in6} in C.  For
@code{socket} module methods, `flowinfo' and `scope_id' can be omitted just for
backward compatibility.  Note, however, omission of `scope_id' can cause problems
in manipulating scoped IPv6 addresses.


バージョン 3.7 で変更: For multicast addresses (with `scope_id' meaningful) `address' may not contain
@code{%scope_id} (or @code{zone id}) part. This information is superfluous and may
be safely omitted (recommended).


@item 
@code{AF_NETLINK} ソケットのアドレスは @code{(pid, groups)} のペアで表されます。

@item 
Linux 限定で、 @code{AF_TIPC} アドレスファミリーを用いて TIPC がサポートされます。 TIPC は、クラスタコンピューティング環境のために設計された、IP ベースではないオープンなネットワークプロトコルです。アドレスはタプルで表現され、フィールドはアドレスタイプに依存します。一般的なタプルの形式は @code{(addr_type, v1, v2, v3 [, scope])} で、それぞれは次の通りです:


@itemize -

@item 
`addr_type' は @code{TIPC_ADDR_NAMESEQ}, @code{TIPC_ADDR_NAME}, @code{TIPC_ADDR_ID} の1つ。

@item 
`scope' は @code{TIPC_ZONE_SCOPE}, @code{TIPC_CLUSTER_SCOPE}, @code{TIPC_NODE_SCOPE} の1つ。

@item 
`addr_type' が @code{TIPC_ADDR_NAME} の場合、 `v1' はサーバータイプ、 `v2' はポートID (the port identifier)、そして `v3' は 0 であるべきです。

`addr_type' が @code{TIPC_ADDR_NAMESEQ} の場合、 `v1' はサーバータイプ、 `v2' はポート番号下位(lower port number)、 `v3' はポート番号上位(upper port number) です。

`addr_type' が @code{TIPC_ADDR_ID} の場合、 `v1' はノード、 `v2' は参照、 `v3' は0であるべきです。
@end itemize

@item 
@ref{3947,,AF_CAN} アドレスファミリーには @code{(interface, )} というタプルを利用します。 `interface' は @code{'can0'} のようなネットワークインターフェース名を表す文字列です。このファミリーの全てのネットワークインターフェースからパケットを受信するために、ネットワークインターフェース名 @code{'@w{'}} を利用できます。


@itemize -

@item 
@ref{3948,,CAN_ISOTP} protocol requires a tuple @code{(interface, rx_addr, tx_addr)}
where both additional parameters are unsigned long integer that represent a
CAN identifier (standard or extended).

@item 
@ref{b2c,,CAN_J1939} protocol requires a tuple @code{(interface, name, pgn, addr)}
where additional parameters are 64-bit unsigned integer representing the
ECU name, a 32-bit unsigned integer representing the Parameter Group Number
(PGN), and an 8-bit integer representing the address.
@end itemize

@item 
文字列またはタプル @code{(id, unit)} は @code{PF_SYSTEM} ファミリーの @code{SYSPROTO_CONTROL} プロトコルのために使用されます。この文字列は、動的に割り当てられたIDによるカーネルコントロールの名前です。このタプルは、カーネルコントロールのIDとユニット番号が既知の場合、または登録済みIDが使用中の場合に使用することができます。


Added in version 3.3.


@item 
@ref{1baf,,AF_BLUETOOTH} は以下のプロトコルとアドレスフォーマットをサポートしています。


@itemize -

@item 
@ref{283,,BTPROTO_L2CAP} accepts a tuple
@code{(bdaddr, psm[, cid[, bdaddr_type]])} where:


@itemize -

@item 
@code{bdaddr} is a string specifying the Bluetooth address.

@item 
@code{psm} is an integer specifying the Protocol/Service Multiplexer.

@item 
@code{cid} is an optional integer specifying the Channel Identifier.
If not given, defaults to zero.

@item 
@code{bdaddr_type} is an optional integer specifying the address type;
one of @ref{3949,,BDADDR_BREDR} (default), @ref{394a,,BDADDR_LE_PUBLIC},
@ref{394b,,BDADDR_LE_RANDOM}.
@end itemize


バージョン 3.14 で変更: Added @code{cid} and @code{bdaddr_type} fields.


@item 
@ref{394c,,BTPROTO_RFCOMM} は @code{(bdaddr, channel)} を受け取ります。
@code{bdaddr} は Bluetooth アドレスを表す文字列で、 @code{channel} は整数です。

@item 
@ref{281,,BTPROTO_HCI} accepts a format that depends on your OS.


@itemize -

@item 
On Linux it accepts an integer @code{device_id} or a tuple
@code{(device_id, [channel])} where @code{device_id}
specifies the number of the Bluetooth device,
and @code{channel} is an optional integer specifying the HCI channel
(@ref{394d,,HCI_CHANNEL_RAW} by default).

@item 
On FreeBSD, NetBSD and DragonFly BSD it accepts @code{bdaddr}
where @code{bdaddr} is the Bluetooth address as a string.
@end itemize


バージョン 3.2 で変更: NetBSD と DragonFlyBSD のサポートが追加されました。



バージョン 3.13.3 で変更: FreeBSD support added.



バージョン 3.14 で変更: Added @code{channel} field.
@code{device_id} not packed in a tuple is now accepted.


@item 
@ref{282,,BTPROTO_SCO} accepts @code{bdaddr} where @code{bdaddr} is
the Bluetooth address as a string or a @ref{192,,bytes} object.
(ex. @code{'12:23:34:45:56:67'} or @code{b'12:23:34:45:56:67'})


バージョン 3.14 で変更: FreeBSD support added.

@end itemize

@item 
@ref{ed2,,AF_ALG} はカーネル暗号へのソケットベースのインターフェイスで、Linux でのみ使用できます。アルゴリズムソケットは、2 つから 4 つの要素を持つタプル @code{(type, name [, feat [, mask]])} で構成されます。各要素の意味は、以下の通りです。


@itemize -

@item 
`type' はアルゴリズムタイプを示す文字列です。例: @code{aead}, @code{hash}, @code{skcipher} または @code{rng}。

@item 
`name' はアルゴリズム名及び操作モードを示す文字列です。例: @code{sha256}, @code{hmac(sha256)}, @code{cbc(aes)} または @code{drbg_nopr_ctr_aes256}。

@item 
`feat' と `mask' は、符号を持たない 32 ビットの整数です。
@end itemize

@ref{213f,,Availability}: Linux >= 2.6.38.

一部のアルゴリズムタイプでは、さらに新しいカーネルが必要です。


Added in version 3.6.


@item 
@ref{d6d,,AF_VSOCK} allows communication between virtual machines and
their hosts. The sockets are represented as a @code{(CID, port)} tuple
where the context ID or CID and port are integers.

@ref{213f,,Availability}: Linux >= 3.9

See @code{vsock(7)@footnote{https://manpages.debian.org/vsock(7)}}


Added in version 3.7.


@item 
@ref{394e,,AF_PACKET} is a low-level interface directly to network devices.
The addresses are represented by the tuple
@code{(ifname, proto[, pkttype[, hatype[, addr]]])} where:


@itemize -

@item 
`ifname' - デバイス名を指定する文字列。

@item 
`proto' - The Ethernet protocol number.
May be @ref{1b23,,ETH_P_ALL} to capture all protocols,
one of the @ref{1b24,,ETHERTYPE_* constants}
or any other Ethernet protocol number.

@item 
`pkttype' - パケットタイプを指定するオプションの整数:


@itemize -

@item 
@code{PACKET_HOST} (the default) - Packet addressed to the local host.

@item 
@code{PACKET_BROADCAST} - Physical-layer broadcast packet.

@item 
@code{PACKET_MULTICAST} - Packet sent to a physical-layer multicast address.

@item 
@code{PACKET_OTHERHOST} - Packet to some other host that has been caught by
a device driver in promiscuous mode.

@item 
@code{PACKET_OUTGOING} - Packet originating from the local host that is
looped back to a packet socket.
@end itemize

@item 
`hatype' - Optional integer specifying the ARP hardware address type.

@item 
`addr' - Optional bytes-like object specifying the hardware physical
address, whose interpretation depends on the device.
@end itemize

@ref{213f,,Availability}: Linux >= 2.2.

@item 
@ref{394f,,AF_QIPCRTR} is a Linux-only socket based interface for communicating
with services running on co-processors in Qualcomm platforms. The address
family is represented as a @code{(node, port)} tuple where the `node' and `port'
are non-negative integers.

@ref{213f,,Availability}: Linux >= 4.7.


Added in version 3.8.


@item 
@code{IPPROTO_UDPLITE} is a variant of UDP which allows you to specify
what portion of a packet is covered with the checksum. It adds two socket
options that you can change.
@code{self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length)} will
change what portion of outgoing packets are covered by the checksum and
@code{self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length)} will
filter out packets which cover too little of their data. In both cases
@code{length} should be in @code{range(8, 2**16, 8)}.

Such a socket should be constructed with
@code{socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE)} for IPv4 or
@code{socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE)} for IPv6.

@ref{213f,,Availability}: Linux >= 2.6.20, FreeBSD >= 10.1


Added in version 3.9.


@item 
@ref{3950,,AF_HYPERV} is a Windows-only socket based interface for communicating
with Hyper-V hosts and guests. The address family is represented as a
@code{(vm_id, service_id)} tuple where the @code{vm_id} and @code{service_id} are
UUID strings.

The @code{vm_id} is the virtual machine identifier or a set of known VMID values
if the target is not a specific virtual machine. Known VMID constants
defined on @code{socket} are:


@itemize -

@item 
@code{HV_GUID_ZERO}

@item 
@code{HV_GUID_BROADCAST}

@item 
@code{HV_GUID_WILDCARD} - Used to bind on itself and accept connections from
all partitions.

@item 
@code{HV_GUID_CHILDREN} - Used to bind on itself and accept connection from
child partitions.

@item 
@code{HV_GUID_LOOPBACK} - Used as a target to itself.

@item 
@code{HV_GUID_PARENT} - When used as a bind accepts connection from the parent
partition. When used as an address target it will connect to the parent partition.
@end itemize

The @code{service_id} is the service identifier of the registered service.


Added in version 3.12.

@end itemize

IPv4/v6ソケットの `host' 部にホスト名を指定すると、処理結果が一定ではない場合があります。これはPythonはDNSから取得したアドレスのうち最初のアドレスを使用するので、 DNSの処理やホストの設定によって異なるIPv4/6アドレスを取得する場合があるためです。常に同じ結果が必要であれば、 `host' に数値のアドレスを指定してください。

エラー時には例外が発生します。引数型のエラーやメモリ不足の場合には通常の例外が発生し、ソケットやアドレス関連のエラーの場合は @ref{2c0,,OSError} またはそのサブクラスが発生します。

@ref{303c,,setblocking()} メソッドで、非ブロッキングモードを使用することができます。また、より汎用的に @ref{3951,,settimeout()} メソッドでタイムアウトを指定する事ができます。

@node モジュールの内容,socket オブジェクト,ソケットファミリー,socket --- 低水準ネットワークインターフェース
@anchor{library/socket module-contents}@anchor{3952}
@subsubsection モジュールの内容


The module @code{socket} exports the following elements.

@menu
* 例外: 例外<18>. 
* 定数: 定数<8>. 
* 関数: 関数<8>. 

@end menu

@node 例外<18>,定数<8>,,モジュールの内容
@anchor{library/socket exceptions}@anchor{3953}
@subsubsection 例外


@geindex error
@anchor{library/socket socket error}@anchor{1261}
@deffn {例外} socket.error

@ref{2c0,,OSError} の非推奨のエイリアスです。


バージョン 3.3 で変更: 
@geindex Python Enhancement Proposals; PEP 3151
PEP 3151@footnote{https://peps.python.org/pep-3151/} に基づき、このクラスは @ref{2c0,,OSError} のエイリアスになりました。

@end deffn

@geindex herror
@anchor{library/socket socket herror}@anchor{3954}
@deffn {例外} socket.herror

@ref{2c0,,OSError} のサブクラス。この例外はアドレス関連のエラー、つまり @ref{1c85,,gethostbyname_ex()} と @ref{1c84,,gethostbyaddr()} などの、 POSIX C API の `h_errno' を利用する関数のために利用されます。例外に付随する @code{(h_errno, string)} ペアはライブラリの呼び出しによって返されたエラーを表します。 `h_errno' は数値で、 `string' は、 @code{hstrerror()} C関数によって返される `h_errno' を説明する文字列です。


バージョン 3.3 で変更: このクラスは @ref{2c0,,OSError} のサブクラスになりました。

@end deffn

@geindex gaierror
@anchor{library/socket socket gaierror}@anchor{1ac4}
@deffn {例外} socket.gaierror

A subclass of @ref{2c0,,OSError}, this exception is raised for
address-related errors by @ref{1ac3,,getaddrinfo()} and @ref{1a3a,,getnameinfo()}.
The accompanying value is a pair @code{(error, string)} representing an error
returned by a library call.  `string' represents the description of
`error', as returned by the @code{gai_strerror()} C function.  The
numeric `error' value will match one of the @code{EAI_*} constants
defined in this module.


バージョン 3.3 で変更: このクラスは @ref{2c0,,OSError} のサブクラスになりました。

@end deffn

@geindex timeout
@anchor{library/socket socket timeout}@anchor{a35}
@deffn {例外} socket.timeout

@ref{a36,,TimeoutError} の非推奨のエイリアスです。

@ref{2c0,,OSError} のサブクラスです。この例外は、あらかじめ @ref{3951,,settimeout()} を呼び出して (あるいは @ref{3955,,setdefaulttimeout()} を利用して暗黙に) タイムアウトを有効にしてあるソケットでタイムアウトが生じた際に送出されます。 例外に付属する値は文字列で、その内容は現状では常に "timed out" となります。


バージョン 3.3 で変更: このクラスは @ref{2c0,,OSError} のサブクラスになりました。



バージョン 3.10 で変更: このクラスは @ref{a36,,TimeoutError} のエイリアスになりました。

@end deffn

@node 定数<8>,関数<8>,例外<18>,モジュールの内容
@anchor{library/socket constants}@anchor{3956}
@subsubsection 定数


AF_* 定数と SOCK_* 定数は、 @code{AddressFamily} と @code{SocketKind} @ref{edb,,IntEnum} collection になりました。


Added in version 3.4.


@geindex AF_UNIX (socket モジュール)
@geindex AF_INET (socket モジュール)
@geindex AF_INET6 (socket モジュール)
@anchor{library/socket socket AF_UNIX}@anchor{1bb0}
@deffn {データ} socket.AF_UNIX
@anchor{library/socket socket AF_INET}@anchor{1bad}
@deffnx {データ} socket.AF_INET
@anchor{library/socket socket AF_INET6}@anchor{1bae}
@deffnx {データ} socket.AF_INET6

These constants represent the address (and protocol) families, used for the
first argument to @ref{fa1,,socket()}.  If the @ref{1bb0,,AF_UNIX} constant is not
defined then this protocol is unsupported.  More constants may be available
depending on the system.
@end deffn

@geindex AF_UNSPEC (socket モジュール)
@anchor{library/socket socket AF_UNSPEC}@anchor{389a}
@deffn {データ} socket.AF_UNSPEC

@ref{389a,,AF_UNSPEC} means that
@ref{1ac3,,getaddrinfo()} should return socket addresses for any
address family (either IPv4, IPv6, or any other) that can be used.
@end deffn

@geindex SOCK_STREAM (socket モジュール)
@geindex SOCK_DGRAM (socket モジュール)
@geindex SOCK_RAW (socket モジュール)
@geindex SOCK_RDM (socket モジュール)
@geindex SOCK_SEQPACKET (socket モジュール)
@anchor{library/socket socket SOCK_STREAM}@anchor{150b}
@deffn {データ} socket.SOCK_STREAM
@anchor{library/socket socket SOCK_DGRAM}@anchor{150a}
@deffnx {データ} socket.SOCK_DGRAM
@anchor{library/socket socket SOCK_RAW}@anchor{3957}
@deffnx {データ} socket.SOCK_RAW
@anchor{library/socket socket SOCK_RDM}@anchor{3958}
@deffnx {データ} socket.SOCK_RDM
@anchor{library/socket socket SOCK_SEQPACKET}@anchor{3959}
@deffnx {データ} socket.SOCK_SEQPACKET

These constants represent the socket types, used for the second argument to
@ref{fa1,,socket()}.  More constants may be available depending on the system.
(Only @ref{150b,,SOCK_STREAM} and @ref{150a,,SOCK_DGRAM} appear to be generally
useful.)
@end deffn

@geindex SOCK_CLOEXEC (socket モジュール)
@geindex SOCK_NONBLOCK (socket モジュール)
@anchor{library/socket socket SOCK_CLOEXEC}@anchor{e05}
@deffn {データ} socket.SOCK_CLOEXEC
@anchor{library/socket socket SOCK_NONBLOCK}@anchor{e04}
@deffnx {データ} socket.SOCK_NONBLOCK

この2つの定数が定義されていた場合、ソケットタイプと組み合わせていくつかの flags をアトミックに設定することができます (別の呼び出しを不要にして競合状態を避ける事ができます)。


@subsubheading 参考


より完全な説明は Secure File Descriptor Handling@footnote{https://udrepper.livejournal.com/20407.html} を参照してください。


@ref{213f,,Availability}: Linux >= 2.6.27.


Added in version 3.2.

@end deffn

@geindex SOMAXCONN (socket モジュール)
@anchor{library/socket socket-unix-constants}@anchor{d6c}
@deffn {データ} SO_*
@anchor{library/socket socket SOMAXCONN}@anchor{105f}
@deffnx {データ} socket.SOMAXCONN

@deffnx {データ} MSG_*

@deffnx {データ} SOL_*

@deffnx {データ} SCM_*

@deffnx {データ} IPPROTO_*

@deffnx {データ} IPPORT_*

@deffnx {データ} INADDR_*

@deffnx {データ} IP_*

@deffnx {データ} IPV6_*

@deffnx {データ} EAI_*

@deffnx {データ} AI_*

@deffnx {データ} NI_*

@deffnx {データ} TCP_*

Many constants of these forms, documented in the Unix documentation on sockets
and/or the IP protocol, are also defined in the socket module. They are
generally used in arguments to the @ref{ed1,,setsockopt()} and @ref{ed0,,getsockopt()}
methods of socket objects.  In most cases, only those symbols that are defined
in the Unix header files are defined; for a few symbols, default values are
provided.


バージョン 3.6 で変更: @code{SO_DOMAIN}, @code{SO_PROTOCOL}, @code{SO_PEERSEC}, @code{SO_PASSSEC}, @code{TCP_USER_TIMEOUT}, @code{TCP_CONGESTION} が追加されました。



バージョン 3.6.5 で変更: Added support for @code{TCP_FASTOPEN}, @code{TCP_KEEPCNT} on Windows platforms
when available.



バージョン 3.7 で変更: @code{TCP_NOTSENT_LOWAT} が追加されました。

Added support for @code{TCP_KEEPIDLE}, @code{TCP_KEEPINTVL} on Windows platforms
when available.



バージョン 3.10 で変更: @code{IP_RECVTOS} was added.
 Added @code{TCP_KEEPALIVE}. On MacOS this constant can be used in the same
 way that @code{TCP_KEEPIDLE} is used on Linux.



バージョン 3.11 で変更: Added @code{TCP_CONNECTION_INFO}. On MacOS this constant can be used in the
same way that @code{TCP_INFO} is used on Linux and BSD.



バージョン 3.12 で変更: Added @code{SO_RTABLE} and @code{SO_USER_COOKIE}. On OpenBSD
and FreeBSD respectively those constants can be used in the same way that
@code{SO_MARK} is used on Linux. Also added missing TCP socket options from
Linux: @code{TCP_MD5SIG}, @code{TCP_THIN_LINEAR_TIMEOUTS}, @code{TCP_THIN_DUPACK},
@code{TCP_REPAIR}, @code{TCP_REPAIR_QUEUE}, @code{TCP_QUEUE_SEQ},
@code{TCP_REPAIR_OPTIONS}, @code{TCP_TIMESTAMP}, @code{TCP_CC_INFO},
@code{TCP_SAVE_SYN}, @code{TCP_SAVED_SYN}, @code{TCP_REPAIR_WINDOW},
@code{TCP_FASTOPEN_CONNECT}, @code{TCP_ULP}, @code{TCP_MD5SIG_EXT},
@code{TCP_FASTOPEN_KEY}, @code{TCP_FASTOPEN_NO_COOKIE},
@code{TCP_ZEROCOPY_RECEIVE}, @code{TCP_INQ}, @code{TCP_TX_DELAY}.
Added @code{IP_PKTINFO}, @code{IP_UNBLOCK_SOURCE}, @code{IP_BLOCK_SOURCE},
@code{IP_ADD_SOURCE_MEMBERSHIP}, @code{IP_DROP_SOURCE_MEMBERSHIP}.



バージョン 3.13 で変更: Added @code{SO_BINDTOIFINDEX}. On Linux this constant can be used in the
same way that @code{SO_BINDTODEVICE} is used, but with the index of a
network interface instead of its name.



バージョン 3.14 で変更: Added missing @code{IP_FREEBIND}, @code{IP_RECVERR}, @code{IPV6_RECVERR},
@code{IP_RECVTTL}, and @code{IP_RECVORIGDSTADDR} on Linux.



バージョン 3.14 で変更: Added support for @code{TCP_QUICKACK} on Windows platforms when available.

@end deffn

@geindex AF_CAN (socket モジュール)
@geindex PF_CAN (socket モジュール)
@anchor{library/socket socket AF_CAN}@anchor{3947}
@deffn {データ} socket.AF_CAN
@anchor{library/socket socket PF_CAN}@anchor{395a}
@deffnx {データ} socket.PF_CAN

@deffnx {データ} SOL_CAN_*

@deffnx {データ} CAN_*

Linux ドキュメントにあるこの形式の定数は socket モジュールでも定義されています。

@ref{213f,,Availability}: Linux >= 2.6.25, NetBSD >= 8.


Added in version 3.3.



バージョン 3.11 で変更: NetBSD サポートが追加されました。



バージョン 3.14 で変更: Restored missing @code{CAN_RAW_ERR_FILTER} on Linux.

@end deffn

@geindex CAN_BCM (socket モジュール)
@anchor{library/socket socket CAN_BCM}@anchor{11a5}
@deffn {データ} socket.CAN_BCM

@deffnx {データ} CAN_BCM_*

CANプロトコルファミリーのCAN_BCMは、ブロードキャストマネージャー(BCM)プロトコルです。Linuxドキュメントにあるこの形式の定数は、socketモジュールでも定義されています。

@ref{213f,,Availability}: Linux >= 2.6.25.

@cartouche
@quotation 注釈 
The @code{CAN_BCM_CAN_FD_FRAME} flag is only available on Linux >= 4.8.
@end quotation
@end cartouche


Added in version 3.4.

@end deffn

@geindex CAN_RAW_FD_FRAMES (socket モジュール)
@anchor{library/socket socket CAN_RAW_FD_FRAMES}@anchor{10ca}
@deffn {データ} socket.CAN_RAW_FD_FRAMES

CAN_RAW ソケットで CAN FD をサポートします。これはデフォルトで無効になっています。これにより、アプリケーションが CAN フレームと CAN FD フレームを送信できるようになります。ただし、ソケットからの読み出し時に、CAN と CAN FD の両方のフレームを受け入れなければなりません。

この定数は、 Linux のドキュメンテーションで説明されています。

@ref{213f,,Availability}: Linux >= 3.6.


Added in version 3.5.

@end deffn

@geindex CAN_RAW_JOIN_FILTERS (socket モジュール)
@anchor{library/socket socket CAN_RAW_JOIN_FILTERS}@anchor{b2b}
@deffn {データ} socket.CAN_RAW_JOIN_FILTERS

Joins the applied CAN filters such that only CAN frames that match all
given CAN filters are passed to user space.

この定数は、 Linux のドキュメンテーションで説明されています。

@ref{213f,,Availability}: Linux >= 4.1.


Added in version 3.9.

@end deffn

@geindex CAN_ISOTP (socket モジュール)
@anchor{library/socket socket CAN_ISOTP}@anchor{3948}
@deffn {データ} socket.CAN_ISOTP

CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol.
ISO-TP constants, documented in the Linux documentation.

@ref{213f,,Availability}: Linux >= 2.6.25.


Added in version 3.7.

@end deffn

@geindex CAN_J1939 (socket モジュール)
@anchor{library/socket socket CAN_J1939}@anchor{b2c}
@deffn {データ} socket.CAN_J1939

CAN_J1939, in the CAN protocol family, is the SAE J1939 protocol.
J1939 constants, documented in the Linux documentation.

@ref{213f,,Availability}: Linux >= 5.4.


Added in version 3.9.

@end deffn

@geindex AF_DIVERT (socket モジュール)
@geindex PF_DIVERT (socket モジュール)
@anchor{library/socket socket AF_DIVERT}@anchor{395b}
@deffn {データ} socket.AF_DIVERT
@anchor{library/socket socket PF_DIVERT}@anchor{395c}
@deffnx {データ} socket.PF_DIVERT

These two constants, documented in the FreeBSD divert(4) manual page, are
also defined in the socket module.

@ref{213f,,Availability}: FreeBSD >= 14.0.


Added in version 3.12.

@end deffn

@geindex AF_PACKET (socket モジュール)
@geindex PF_PACKET (socket モジュール)
@anchor{library/socket socket AF_PACKET}@anchor{394e}
@deffn {データ} socket.AF_PACKET
@anchor{library/socket socket PF_PACKET}@anchor{395d}
@deffnx {データ} socket.PF_PACKET

@deffnx {データ} PACKET_*

Linux ドキュメントにあるこの形式の定数は socket モジュールでも定義されています。

@ref{213f,,Availability}: Linux >= 2.2.
@end deffn

@geindex ETH_P_ALL (socket モジュール)
@anchor{library/socket socket ETH_P_ALL}@anchor{1b23}
@deffn {データ} socket.ETH_P_ALL

@code{ETH_P_ALL} can be used in the @ref{fa1,,socket}
constructor as `proto' for the @ref{394e,,AF_PACKET} family in order to
capture every packet, regardless of protocol.

For more information, see the @code{packet(7)@footnote{https://manpages.debian.org/packet(7)}} manpage.

@ref{213f,,Availability}: Linux.


Added in version 3.12.

@end deffn

@geindex AF_RDS (socket モジュール)
@geindex PF_RDS (socket モジュール)
@geindex SOL_RDS (socket モジュール)
@anchor{library/socket socket AF_RDS}@anchor{395e}
@deffn {データ} socket.AF_RDS
@anchor{library/socket socket PF_RDS}@anchor{395f}
@deffnx {データ} socket.PF_RDS
@anchor{library/socket socket SOL_RDS}@anchor{3960}
@deffnx {データ} socket.SOL_RDS

@deffnx {データ} RDS_*

Linux ドキュメントにあるこの形式の定数は socket モジュールでも定義されています。

@ref{213f,,Availability}: Linux >= 2.6.30.


Added in version 3.3.

@end deffn

@geindex SIO_RCVALL (socket モジュール)
@geindex SIO_KEEPALIVE_VALS (socket モジュール)
@geindex SIO_LOOPBACK_FAST_PATH (socket モジュール)
@anchor{library/socket socket SIO_RCVALL}@anchor{3961}
@deffn {データ} socket.SIO_RCVALL
@anchor{library/socket socket SIO_KEEPALIVE_VALS}@anchor{3962}
@deffnx {データ} socket.SIO_KEEPALIVE_VALS
@anchor{library/socket socket SIO_LOOPBACK_FAST_PATH}@anchor{ecf}
@deffnx {データ} socket.SIO_LOOPBACK_FAST_PATH

@deffnx {データ} RCVALL_*

Windows の WSAIoctl() のための定数です。この定数はソケットオブジェクトの @ref{ece,,ioctl()} メソッドに引数として渡されます。


バージョン 3.6 で変更: @code{SIO_LOOPBACK_FAST_PATH} が追加されました。

@end deffn


@deffn {データ} TIPC_*

TIPC 関連の定数で、C のソケットAPIが公開しているものにマッチします。詳しい情報は TIPC のドキュメントを参照してください。
@end deffn

@geindex AF_ALG (socket モジュール)
@geindex SOL_ALG (socket モジュール)
@anchor{library/socket socket AF_ALG}@anchor{ed2}
@deffn {データ} socket.AF_ALG
@anchor{library/socket socket SOL_ALG}@anchor{3963}
@deffnx {データ} socket.SOL_ALG

@deffnx {データ} ALG_*

Linux カーネル暗号用の定数です。

@ref{213f,,Availability}: Linux >= 2.6.38.


Added in version 3.6.

@end deffn

@geindex AF_VSOCK (socket モジュール)
@geindex IOCTL_VM_SOCKETS_GET_LOCAL_CID (socket モジュール)
@anchor{library/socket socket AF_VSOCK}@anchor{d6d}
@deffn {データ} socket.AF_VSOCK
@anchor{library/socket socket IOCTL_VM_SOCKETS_GET_LOCAL_CID}@anchor{3964}
@deffnx {データ} socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID

@deffnx {データ} VMADDR*

@deffnx {データ} SO_VM*

Constants for Linux host/guest communication.

@ref{213f,,Availability}: Linux >= 4.8.


Added in version 3.7.

@end deffn

@geindex AF_LINK (socket モジュール)
@anchor{library/socket socket AF_LINK}@anchor{11a6}
@deffn {データ} socket.AF_LINK

@ref{213f,,Availability}: BSD, macOS.


Added in version 3.4.

@end deffn

@geindex has_ipv6 (socket モジュール)
@anchor{library/socket socket has_ipv6}@anchor{3965}
@deffn {データ} socket.has_ipv6

現在のプラットフォームでIPv6がサポートされているか否かを示す真偽値。
@end deffn

@geindex AF_BLUETOOTH (socket モジュール)
@geindex BTPROTO_L2CAP (socket モジュール)
@geindex BTPROTO_RFCOMM (socket モジュール)
@geindex BTPROTO_HCI (socket モジュール)
@geindex BTPROTO_SCO (socket モジュール)
@anchor{library/socket socket AF_BLUETOOTH}@anchor{1baf}
@deffn {データ} socket.AF_BLUETOOTH
@anchor{library/socket socket BTPROTO_L2CAP}@anchor{283}
@deffnx {データ} socket.BTPROTO_L2CAP
@anchor{library/socket socket BTPROTO_RFCOMM}@anchor{394c}
@deffnx {データ} socket.BTPROTO_RFCOMM
@anchor{library/socket socket BTPROTO_HCI}@anchor{281}
@deffnx {データ} socket.BTPROTO_HCI
@anchor{library/socket socket BTPROTO_SCO}@anchor{282}
@deffnx {データ} socket.BTPROTO_SCO

Integer constants for use with Bluetooth addresses.
@end deffn

@geindex BDADDR_ANY (socket モジュール)
@geindex BDADDR_LOCAL (socket モジュール)
@anchor{library/socket socket BDADDR_ANY}@anchor{3966}
@deffn {データ} socket.BDADDR_ANY
@anchor{library/socket socket BDADDR_LOCAL}@anchor{3967}
@deffnx {データ} socket.BDADDR_LOCAL

これらは、特別な意味を持つ Bluetooth アドレスを含む文字列定数です。例えば、@ref{3966,,BDADDR_ANY} を使用すると、 @ref{394c,,BTPROTO_RFCOMM} で束縛ソケットを指定する際に、任意のアドレスを指し示すことができます。
@end deffn

@geindex BDADDR_BREDR (socket モジュール)
@geindex BDADDR_LE_PUBLIC (socket モジュール)
@geindex BDADDR_LE_RANDOM (socket モジュール)
@anchor{library/socket socket BDADDR_BREDR}@anchor{3949}
@deffn {データ} socket.BDADDR_BREDR
@anchor{library/socket socket BDADDR_LE_PUBLIC}@anchor{394a}
@deffnx {データ} socket.BDADDR_LE_PUBLIC
@anchor{library/socket socket BDADDR_LE_RANDOM}@anchor{394b}
@deffnx {データ} socket.BDADDR_LE_RANDOM

These constants describe the Bluetooth address type when binding or
connecting a @ref{283,,BTPROTO_L2CAP} socket.

@ref{213f,,Availability}: Linux, FreeBSD


Added in version 3.14.

@end deffn

@geindex SOL_RFCOMM (socket モジュール)
@geindex SOL_L2CAP (socket モジュール)
@geindex SOL_HCI (socket モジュール)
@geindex SOL_SCO (socket モジュール)
@geindex SOL_BLUETOOTH (socket モジュール)
@anchor{library/socket socket SOL_RFCOMM}@anchor{3968}
@deffn {データ} socket.SOL_RFCOMM
@anchor{library/socket socket SOL_L2CAP}@anchor{3969}
@deffnx {データ} socket.SOL_L2CAP
@anchor{library/socket socket SOL_HCI}@anchor{396a}
@deffnx {データ} socket.SOL_HCI
@anchor{library/socket socket SOL_SCO}@anchor{396b}
@deffnx {データ} socket.SOL_SCO
@anchor{library/socket socket SOL_BLUETOOTH}@anchor{396c}
@deffnx {データ} socket.SOL_BLUETOOTH

Used in the level argument to the @ref{ed1,,setsockopt()} and
@ref{ed0,,getsockopt()} methods of Bluetooth socket objects.

@ref{396c,,SOL_BLUETOOTH} is only available on Linux. Other constants
are available if the corresponding protocol is supported.
@end deffn

@geindex L2CAP_LM (socket モジュール)

@deffn {データ} SO_L2CAP_*
@anchor{library/socket socket L2CAP_LM}@anchor{396d}
@deffnx {データ} socket.L2CAP_LM

@deffnx {データ} L2CAP_LM_*

@deffnx {データ} SO_RFCOMM_*

@deffnx {データ} RFCOMM_LM_*

@deffnx {データ} SO_SCO_*

@deffnx {データ} SO_BTH_*

@deffnx {データ} BT_*

Used in the option name and value argument to the @ref{ed1,,setsockopt()}
and @ref{ed0,,getsockopt()} methods of Bluetooth socket objects.

@code{BT_*} and @ref{396d,,L2CAP_LM} are only available on Linux.
@code{SO_BTH_*} are only available on Windows.
Other constants may be available on Linux and various BSD platforms.


Added in version 3.14.

@end deffn

@geindex HCI_FILTER (socket モジュール)
@geindex HCI_TIME_STAMP (socket モジュール)
@geindex HCI_DATA_DIR (socket モジュール)
@geindex SO_HCI_EVT_FILTER (socket モジュール)
@geindex SO_HCI_PKT_FILTER (socket モジュール)
@anchor{library/socket socket HCI_FILTER}@anchor{396e}
@deffn {データ} socket.HCI_FILTER
@anchor{library/socket socket HCI_TIME_STAMP}@anchor{396f}
@deffnx {データ} socket.HCI_TIME_STAMP
@anchor{library/socket socket HCI_DATA_DIR}@anchor{3970}
@deffnx {データ} socket.HCI_DATA_DIR
@anchor{library/socket socket SO_HCI_EVT_FILTER}@anchor{3971}
@deffnx {データ} socket.SO_HCI_EVT_FILTER
@anchor{library/socket socket SO_HCI_PKT_FILTER}@anchor{3972}
@deffnx {データ} socket.SO_HCI_PKT_FILTER

Option names for use with @ref{281,,BTPROTO_HCI}.
Availability and format of the option values depend on platform.


バージョン 3.14 で変更: Added @code{SO_HCI_EVT_FILTER} and @code{SO_HCI_PKT_FILTER}
on NetBSD and DragonFly BSD.
Added @code{HCI_DATA_DIR} on FreeBSD, NetBSD and DragonFly BSD.

@end deffn

@geindex HCI_DEV_NONE (socket モジュール)
@anchor{library/socket socket HCI_DEV_NONE}@anchor{3973}
@deffn {データ} socket.HCI_DEV_NONE

The @code{device_id} value used to create an HCI socket that isn't specific
to a single Bluetooth adapter.

@ref{213f,,Availability}: Linux


Added in version 3.14.

@end deffn

@geindex HCI_CHANNEL_RAW (socket モジュール)
@geindex HCI_CHANNEL_USER (socket モジュール)
@geindex HCI_CHANNEL_MONITOR (socket モジュール)
@geindex HCI_CHANNEL_CONTROL (socket モジュール)
@geindex HCI_CHANNEL_LOGGING (socket モジュール)
@anchor{library/socket socket HCI_CHANNEL_RAW}@anchor{394d}
@deffn {データ} socket.HCI_CHANNEL_RAW
@anchor{library/socket socket HCI_CHANNEL_USER}@anchor{3974}
@deffnx {データ} socket.HCI_CHANNEL_USER
@anchor{library/socket socket HCI_CHANNEL_MONITOR}@anchor{3975}
@deffnx {データ} socket.HCI_CHANNEL_MONITOR
@anchor{library/socket socket HCI_CHANNEL_CONTROL}@anchor{3976}
@deffnx {データ} socket.HCI_CHANNEL_CONTROL
@anchor{library/socket socket HCI_CHANNEL_LOGGING}@anchor{3977}
@deffnx {データ} socket.HCI_CHANNEL_LOGGING

Possible values for @code{channel} field in the @ref{281,,BTPROTO_HCI} address.

@ref{213f,,Availability}: Linux


Added in version 3.14.

@end deffn

@geindex AF_QIPCRTR (socket モジュール)
@anchor{library/socket socket AF_QIPCRTR}@anchor{394f}
@deffn {データ} socket.AF_QIPCRTR

Constant for Qualcomm's IPC router protocol, used to communicate with
service providing remote processors.

@ref{213f,,Availability}: Linux >= 4.7.
@end deffn

@geindex SCM_CREDS2 (socket モジュール)
@geindex LOCAL_CREDS (socket モジュール)
@geindex LOCAL_CREDS_PERSISTENT (socket モジュール)
@anchor{library/socket socket SCM_CREDS2}@anchor{3978}
@deffn {データ} socket.SCM_CREDS2
@anchor{library/socket socket LOCAL_CREDS}@anchor{3979}
@deffnx {データ} socket.LOCAL_CREDS
@anchor{library/socket socket LOCAL_CREDS_PERSISTENT}@anchor{397a}
@deffnx {データ} socket.LOCAL_CREDS_PERSISTENT

LOCAL_CREDS and LOCAL_CREDS_PERSISTENT can be used
with SOCK_DGRAM, SOCK_STREAM sockets, equivalent to
Linux/DragonFlyBSD SO_PASSCRED, while LOCAL_CREDS
sends the credentials at first read, LOCAL_CREDS_PERSISTENT
sends for each read, SCM_CREDS2 must be then used for
the latter for the message type.


Added in version 3.11.


@ref{213f,,Availability}: FreeBSD.
@end deffn

@geindex SO_INCOMING_CPU (socket モジュール)
@anchor{library/socket socket SO_INCOMING_CPU}@anchor{397b}
@deffn {データ} socket.SO_INCOMING_CPU

Constant to optimize CPU locality, to be used in conjunction with
@code{SO_REUSEPORT}.


Added in version 3.11.


@ref{213f,,Availability}: Linux >= 3.9
@end deffn

@geindex SO_REUSEPORT_LB (socket モジュール)
@anchor{library/socket socket SO_REUSEPORT_LB}@anchor{18d4}
@deffn {データ} socket.SO_REUSEPORT_LB

@quotation

Constant to enable duplicate address and port bindings with load balancing.
@end quotation


Added in version 3.14.


@ref{213f,,Availability}: FreeBSD >= 12.0
@end deffn

@geindex AF_HYPERV (socket モジュール)
@geindex HV_PROTOCOL_RAW (socket モジュール)
@geindex HVSOCKET_CONNECT_TIMEOUT (socket モジュール)
@geindex HVSOCKET_CONNECT_TIMEOUT_MAX (socket モジュール)
@geindex HVSOCKET_CONNECTED_SUSPEND (socket モジュール)
@geindex HVSOCKET_ADDRESS_FLAG_PASSTHRU (socket モジュール)
@geindex HV_GUID_ZERO (socket モジュール)
@geindex HV_GUID_WILDCARD (socket モジュール)
@geindex HV_GUID_BROADCAST (socket モジュール)
@geindex HV_GUID_CHILDREN (socket モジュール)
@geindex HV_GUID_LOOPBACK (socket モジュール)
@geindex HV_GUID_PARENT (socket モジュール)
@anchor{library/socket socket AF_HYPERV}@anchor{3950}
@deffn {データ} socket.AF_HYPERV
@anchor{library/socket socket HV_PROTOCOL_RAW}@anchor{397c}
@deffnx {データ} socket.HV_PROTOCOL_RAW
@anchor{library/socket socket HVSOCKET_CONNECT_TIMEOUT}@anchor{397d}
@deffnx {データ} socket.HVSOCKET_CONNECT_TIMEOUT
@anchor{library/socket socket HVSOCKET_CONNECT_TIMEOUT_MAX}@anchor{397e}
@deffnx {データ} socket.HVSOCKET_CONNECT_TIMEOUT_MAX
@anchor{library/socket socket HVSOCKET_CONNECTED_SUSPEND}@anchor{397f}
@deffnx {データ} socket.HVSOCKET_CONNECTED_SUSPEND
@anchor{library/socket socket HVSOCKET_ADDRESS_FLAG_PASSTHRU}@anchor{3980}
@deffnx {データ} socket.HVSOCKET_ADDRESS_FLAG_PASSTHRU
@anchor{library/socket socket HV_GUID_ZERO}@anchor{3981}
@deffnx {データ} socket.HV_GUID_ZERO
@anchor{library/socket socket HV_GUID_WILDCARD}@anchor{3982}
@deffnx {データ} socket.HV_GUID_WILDCARD
@anchor{library/socket socket HV_GUID_BROADCAST}@anchor{3983}
@deffnx {データ} socket.HV_GUID_BROADCAST
@anchor{library/socket socket HV_GUID_CHILDREN}@anchor{3984}
@deffnx {データ} socket.HV_GUID_CHILDREN
@anchor{library/socket socket HV_GUID_LOOPBACK}@anchor{3985}
@deffnx {データ} socket.HV_GUID_LOOPBACK
@anchor{library/socket socket HV_GUID_PARENT}@anchor{3986}
@deffnx {データ} socket.HV_GUID_PARENT

Constants for Windows Hyper-V sockets for host/guest communications.

@ref{213f,,Availability}: Windows.


Added in version 3.12.

@end deffn

@geindex ETHERTYPE_ARP (socket モジュール)
@geindex ETHERTYPE_IP (socket モジュール)
@geindex ETHERTYPE_IPV6 (socket モジュール)
@geindex ETHERTYPE_VLAN (socket モジュール)
@anchor{library/socket socket-ethernet-types}@anchor{1b24}@anchor{library/socket socket ETHERTYPE_ARP}@anchor{3987}
@deffn {データ} socket.ETHERTYPE_ARP
@anchor{library/socket socket ETHERTYPE_IP}@anchor{3988}
@deffnx {データ} socket.ETHERTYPE_IP
@anchor{library/socket socket ETHERTYPE_IPV6}@anchor{3989}
@deffnx {データ} socket.ETHERTYPE_IPV6
@anchor{library/socket socket ETHERTYPE_VLAN}@anchor{398a}
@deffnx {データ} socket.ETHERTYPE_VLAN

IEEE 802.3 protocol number@footnote{https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.txt}.
constants.

@ref{213f,,Availability}: Linux, FreeBSD, macOS.


Added in version 3.12.

@end deffn

@geindex SHUT_RD (socket モジュール)
@geindex SHUT_WR (socket モジュール)
@geindex SHUT_RDWR (socket モジュール)
@anchor{library/socket socket SHUT_RD}@anchor{398b}
@deffn {データ} socket.SHUT_RD
@anchor{library/socket socket SHUT_WR}@anchor{398c}
@deffnx {データ} socket.SHUT_WR
@anchor{library/socket socket SHUT_RDWR}@anchor{398d}
@deffnx {データ} socket.SHUT_RDWR

These constants are used by the @ref{398e,,shutdown()} method of socket objects.

@ref{213f,,Availability}: not WASI.
@end deffn

@node 関数<8>,,定数<8>,モジュールの内容
@anchor{library/socket functions}@anchor{398f}
@subsubsection 関数


@menu
* ソケットの作成:: 
* その他の関数: その他の関数<2>. 

@end menu

@node ソケットの作成,その他の関数<2>,,関数<8>
@anchor{library/socket creating-sockets}@anchor{3990}
@subsubsection ソケットの作成


以下の関数は全て @ref{3991,,socket object} を生成します。

@geindex socket (socket のクラス)
@anchor{library/socket socket socket}@anchor{fa1}
@deffn {クラス} socket.socket (family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

アドレスファミリー、ソケットタイプ、プロトコル番号を指定してソケットを作成します。アドレスファミリーには @ref{1bad,,AF_INET} (デフォルト値), @ref{1bae,,AF_INET6}, @ref{1bb0,,AF_UNIX}, @ref{3947,,AF_CAN}, @ref{394e,,AF_PACKET}, @ref{395e,,AF_RDS} を指定することができます。ソケットタイプには @ref{150b,,SOCK_STREAM} (デフォルト値), @ref{150a,,SOCK_DGRAM}, @ref{3957,,SOCK_RAW} または他の @code{SOCK_} 定数の何れかを指定します。プロトコル番号は通常省略するか、または0を指定しますが、アドレスファミリーに @ref{3947,,AF_CAN} を指定した場合は、プロトコル番号には const:@cite{CAN_RAW}, @ref{11a5,,CAN_BCM}, @ref{3948,,CAN_ISOTP}, @ref{b2c,,CAN_J1939} のいずれかを指定すべきです。

If `fileno' is specified, the values for `family', `type', and `proto' are
auto-detected from the specified file descriptor.  Auto-detection can be
overruled by calling the function with explicit `family', `type', or `proto'
arguments.  This only affects how Python represents e.g. the return value
of @ref{38d9,,socket.getpeername()} but not the actual OS resource.  Unlike
@ref{3992,,socket.fromfd()}, `fileno' will return the same socket and not a
duplicate. This may help close a detached socket using
@ref{d6a,,socket.close()}.

新たに作成されたソケットは @ref{10fc,,継承不可}  です。

引数 @code{self}, @code{family}, @code{type}, @code{protocol} 付きで @ref{1c6e,,監査イベント} @code{socket.__new__} を送出します。


バージョン 3.3 で変更: AF_CAN, AF_RDS ファミリーが追加されました。



バージョン 3.4 で変更: CAN_BCMプロトコルが追加されました。



バージョン 3.4 で変更: 返されるソケットは継承不可になりました。



バージョン 3.7 で変更: CAN_ISOTP プロトコルが追加されました。



バージョン 3.7 で変更: When @ref{e04,,SOCK_NONBLOCK} or @ref{e05,,SOCK_CLOEXEC}
bit flags are applied to `type' they are cleared, and
@ref{e06,,socket.type} will not reflect them.  They are still passed
to the underlying system @code{socket()} call.  Therefore,

@example
sock = socket.socket(
    socket.AF_INET,
    socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
@end example

will still create a non-blocking socket on OSes that support
@code{SOCK_NONBLOCK}, but @code{sock.type} will be set to
@code{socket.SOCK_STREAM}.



バージョン 3.9 で変更: CAN_J1939 プロトコルが追加されました。



バージョン 3.10 で変更: IPPROTO_MPTCP プロトコルが追加されました。

@end deffn

@geindex socketpair() (socket モジュール)
@anchor{library/socket socket socketpair}@anchor{df0}
@deffn {の関数} socket.socketpair ([family[, type[, proto]]])

Build a pair of connected socket objects using the given address family, socket
type, and protocol number.  Address family, socket type, and protocol number are
as for the @ref{fa1,,socket()} function above. The default family is @ref{1bb0,,AF_UNIX}
if defined on the platform; otherwise, the default is @ref{1bad,,AF_INET}.

新たに作成されたソケットは @ref{10fc,,継承不可} です。


バージョン 3.2 で変更: 返されるソケットオブジェクトが、サブセットではなく完全なソケットAPIを提供するようになりました。



バージョン 3.4 で変更: 返されるソケットの組は、どちらも継承不可になりました。



バージョン 3.5 で変更: Windows のサポートが追加されました。

@end deffn

@geindex create_connection() (socket モジュール)
@anchor{library/socket socket create_connection}@anchor{882}
@deffn {の関数} socket.create_connection (address, timeout=GLOBAL_DEFAULT, source_address=None, *, all_errors=False)

インターネット `address' (@code{(host, port)} ペア) で listen しているTCPサービスに接続し、ソケットオブジェクトを返します。これは @ref{fa3,,socket.connect()} を高級にした関数です。 `host' が数値でないホスト名の場合、 @ref{1bad,,AF_INET} と @ref{1bae,,AF_INET6} の両方で名前解決を試み、得られた全てのアドレスに対して成功するまで接続を試みます。この関数を使って IPv4 と IPv6 に両対応したクライアントを簡単に書くことができます。

オプションの `timeout' 引数を指定すると、接続を試みる前にソケットオブジェクトのタイムアウトを設定します。 `timeout' が指定されない場合、 @ref{3993,,getdefaulttimeout()} が返すデフォルトのタイムアウト設定値を利用します。

`source_address' は接続する前にバインドするソースアドレスを指定するオプション引数で、指定する場合は @code{(host, port)} の2要素タプルでなければなりません。 host や port が '@w{'} か 0 だった場合は、OSのデフォルトの動作になります。

When a connection cannot be created, an exception is raised. By default,
it is the exception from the last address in the list. If `all_errors'
is @code{True}, it is an @ref{4d2,,ExceptionGroup} containing the errors of all
attempts.


バージョン 3.2 で変更: `source_address' が追加されました。



バージョン 3.11 で変更: `all_errors' が追加されました

@end deffn

@geindex create_server() (socket モジュール)
@anchor{library/socket socket create_server}@anchor{c20}
@deffn {の関数} socket.create_server (address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)

Convenience function which creates a TCP socket bound to `address' (a 2-tuple
@code{(host, port)}) and returns the socket object.

`family' should be either @ref{1bad,,AF_INET} or @ref{1bae,,AF_INET6}.
`backlog' is the queue size passed to @ref{105e,,socket.listen()}; if not specified
, a default reasonable value is chosen.
`reuse_port' dictates whether to set the @code{SO_REUSEPORT} socket option.

If `dualstack_ipv6' is true, `family' is @ref{1bae,,AF_INET6} and the platform
supports it the socket will be able to accept both IPv4 and IPv6 connections,
else it will raise @ref{2ec,,ValueError}. Most POSIX platforms and Windows are
supposed to support this functionality.
When this functionality is enabled the address returned by
@ref{38d9,,socket.getpeername()} when an IPv4 connection occurs will be an IPv6
address represented as an IPv4-mapped IPv6 address.
If `dualstack_ipv6' is false it will explicitly disable this functionality
on platforms that enable it by default (e.g. Linux).
This parameter can be used in conjunction with @ref{c21,,has_dualstack_ipv6()}:

@example
import socket

addr = ("", 8080)  # all interfaces, port 8080
if socket.has_dualstack_ipv6():
    s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True)
else:
    s = socket.create_server(addr)
@end example

@cartouche
@quotation 注釈 
On POSIX platforms the @code{SO_REUSEADDR} socket option is set in order to
immediately reuse previous sockets which were bound on the same `address'
and remained in TIME_WAIT state.
@end quotation
@end cartouche


Added in version 3.8.

@end deffn

@geindex has_dualstack_ipv6() (socket モジュール)
@anchor{library/socket socket has_dualstack_ipv6}@anchor{c21}
@deffn {の関数} socket.has_dualstack_ipv6 ()

Return @code{True} if the platform supports creating a TCP socket which can
handle both IPv4 and IPv6 connections.


Added in version 3.8.

@end deffn

@geindex fromfd() (socket モジュール)
@anchor{library/socket socket fromfd}@anchor{3992}
@deffn {の関数} socket.fromfd (fd, family, type, proto=0)

Duplicate the file descriptor `fd' (an integer as returned by a file object's
@ref{17ad,,fileno()} method) and build a socket object from the result.  Address
family, socket type and protocol number are as for the @ref{fa1,,socket()} function
above. The file descriptor should refer to a socket, but this is not checked ---
subsequent operations on the object may fail if the file descriptor is invalid.
This function is rarely needed, but can be used to get or set socket options on
a socket passed to a program as standard input or output (such as a server
started by the Unix inet daemon).  The socket is assumed to be in blocking mode.

新たに作成されたソケットは @ref{10fc,,継承不可}  です。


バージョン 3.4 で変更: 返されるソケットは継承不可になりました。

@end deffn

@geindex fromshare() (socket モジュール)
@anchor{library/socket socket fromshare}@anchor{e01}
@deffn {の関数} socket.fromshare (data)

@ref{e02,,socket.share()} メソッドから取得した data からソケットオブジェクトを生成します。ソケットはブロッキングモードだと仮定されます。

@ref{213f,,Availability}: Windows.


Added in version 3.3.

@end deffn

@geindex SocketType (socket モジュール)
@anchor{library/socket socket SocketType}@anchor{3994}
@deffn {データ} socket.SocketType

ソケットオブジェクトの型を示す型オブジェクト。 @code{type(socket(...))} と同じです。
@end deffn

@node その他の関数<2>,,ソケットの作成,関数<8>
@anchor{library/socket other-functions}@anchor{3995}
@subsubsection その他の関数


The @code{socket} module also offers various network-related services:

@geindex close() (socket モジュール)
@anchor{library/socket socket close}@anchor{d6a}
@deffn {の関数} socket.close (fd)

Close a socket file descriptor. This is like @ref{d6b,,os.close()}, but for
sockets. On some platforms (most notably Windows) @ref{d6b,,os.close()}
does not work for socket file descriptors.


Added in version 3.7.

@end deffn

@geindex getaddrinfo() (socket モジュール)
@anchor{library/socket socket getaddrinfo}@anchor{1ac3}
@deffn {の関数} socket.getaddrinfo (host, port, family=AF_UNSPEC, type=0, proto=0, flags=0)

This function wraps the C function @code{getaddrinfo} of the underlying system.

`host' / `port' 引数の指すアドレス情報を、そのサービスに接続されたソケットを作成するために必要な全ての引数が入った 5 要素のタプルに変換します。 `host' はドメイン名、IPv4/v6アドレスの文字列、または @code{None} です。 `port' は @code{'http'} のようなサービス名文字列、ポート番号を表す数値、または @code{None} です。 `host' と `port' に @code{None} を指定すると C APIに @code{NULL} を渡せます。

The `family', `type' and `proto' arguments can be optionally specified
in order to provide options and limit the list of addresses returned.
Pass their default values (@ref{389a,,AF_UNSPEC}, 0, and 0, respectively)
to not limit the results. See the note below for details.

The `flags' argument can be one or several of the @code{AI_*} constants,
and will influence how results are computed and returned.
For example, @code{AI_NUMERICHOST} will disable domain name resolution
and will raise an error if `host' is a domain name.

この関数は以下の構造をとる 5 要素のタプルのリストを返します:

@code{(family, type, proto, canonname, sockaddr)}

In these tuples, `family', `type', `proto' are all integers and are
meant to be passed to the @ref{fa1,,socket()} function.  `canonname' will be
a string representing the canonical name of the `host' if
@code{AI_CANONNAME} is part of the `flags' argument; else `canonname'
will be empty.  `sockaddr' is a tuple describing a socket address, whose
format depends on the returned `family' (a @code{(address, port)} 2-tuple for
@ref{1bad,,AF_INET}, a @code{(address, port, flowinfo, scope_id)} 4-tuple for
@ref{1bae,,AF_INET6}), and is meant to be passed to the @ref{fa3,,socket.connect()}
method.

@cartouche
@quotation 注釈 
If you intend to use results from @code{getaddrinfo()} to create a socket
(rather than, for example, retrieve `canonname'),
consider limiting the results by `type' (e.g. @ref{150b,,SOCK_STREAM} or
@ref{150a,,SOCK_DGRAM}) and/or `proto' (e.g. @code{IPPROTO_TCP} or
@code{IPPROTO_UDP}) that your application can handle.

The behavior with default values of `family', `type', `proto'
and `flags' is system-specific.

Many systems (for example, most Linux configurations) will return a sorted
list of all matching addresses.
These addresses should generally be tried in order until a connection succeeds
(possibly tried in parallel, for example, using a Happy Eyeballs@footnote{https://en.wikipedia.org/wiki/Happy_Eyeballs} algorithm).
In these cases, limiting the `type' and/or `proto' can help eliminate
unsuccessful or unusable connection attempts.

Some systems will, however, only return a single address.
(For example, this was reported on Solaris and AIX configurations.)
On these systems, limiting the `type' and/or `proto' helps ensure that
this address is usable.
@end quotation
@end cartouche

引数 @code{host}, @code{port}, @code{family}, @code{type}, @code{protocol} 付きで @ref{1c6e,,監査イベント} @code{socket.getaddrinfo} を送出します。

次の例では @code{example.org} の 80 番ポートポートへの TCP 接続を得るためのアドレス情報を取得しようとしています。 (結果は IPv6 をサポートしているかどうかで変わります):

@example
>>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
[(socket.AF_INET6, socket.SOCK_STREAM,
 6, '@w{'}, ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
 (socket.AF_INET, socket.SOCK_STREAM,
 6, '@w{'}, ('93.184.216.34', 80))]
@end example


バージョン 3.2 で変更: パラメータをキーワード引数で渡すことができるようになりました。



バージョン 3.7 で変更: for IPv6 multicast addresses, string representing an address will not
contain @code{%scope_id} part.

@end deffn

@geindex getfqdn() (socket モジュール)
@anchor{library/socket socket getfqdn}@anchor{1aed}
@deffn {の関数} 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 @ref{1c84,,gethostbyaddr()} 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 @code{'0.0.0.0'},
the hostname from @ref{3026,,gethostname()} is returned.
@end deffn

@geindex gethostbyname() (socket モジュール)
@anchor{library/socket socket gethostbyname}@anchor{3996}
@deffn {の関数} socket.gethostbyname (hostname)

ホスト名を @code{'100.50.200.5'} のようなIPv4形式のアドレスに変換します。ホスト名としてIPv4アドレスを指定した場合、その値は変換せずにそのまま返ります。 @ref{3996,,gethostbyname()} APIへのより完全なインターフェイスが必要であれば、 @ref{1c85,,gethostbyname_ex()} を参照してください。 @ref{3996,,gethostbyname()} は、IPv6名前解決をサポートしていません。IPv4/ v6のデュアルスタックをサポートする場合は @ref{1ac3,,getaddrinfo()} を使用します。

引数 @code{hostname} を指定して @ref{1c6e,,監査イベント} @code{socket.gethostbyname} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex gethostbyname_ex() (socket モジュール)
@anchor{library/socket socket gethostbyname_ex}@anchor{1c85}
@deffn {の関数} socket.gethostbyname_ex (hostname)

Translate a host name to IPv4 address format, extended interface. Return a
3-tuple @code{(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). @ref{1c85,,gethostbyname_ex()} does not support IPv6 name
resolution, and @ref{1ac3,,getaddrinfo()} should be used instead for IPv4/v6 dual
stack support.

引数 @code{hostname} を指定して @ref{1c6e,,監査イベント} @code{socket.gethostbyname} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex gethostname() (socket モジュール)
@anchor{library/socket socket gethostname}@anchor{3026}
@deffn {の関数} socket.gethostname ()

Pythonインタープリタを現在実行しているマシンのホスト名を含む文字列を返します。

引数無しで @ref{1c6e,,監査イベント} @code{socket.gethostname} を送出します。

注意: @ref{3026,,gethostname()} は完全修飾ドメイン名を返すとは限りません。完全修飾ドメイン名が必要であれば、@ref{1aed,,getfqdn()} を使用してください。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex gethostbyaddr() (socket モジュール)
@anchor{library/socket socket gethostbyaddr}@anchor{1c84}
@deffn {の関数} socket.gethostbyaddr (ip_address)

Return a 3-tuple @code{(hostname, aliaslist, ipaddrlist)} where `hostname' is the
primary host name responding to the given `ip_address', `aliaslist' is a
(possibly empty) list of alternative host names for the same address, and
`ipaddrlist' is a list of IPv4/v6 addresses for the same interface on the same
host (most likely containing only a single address). To find the fully qualified
domain name, use the function @ref{1aed,,getfqdn()}. @ref{1c84,,gethostbyaddr()} supports
both IPv4 and IPv6.

引数 @code{ip_address} を指定して @ref{1c6e,,監査イベント} @code{socket.gethostbyaddr} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex getnameinfo() (socket モジュール)
@anchor{library/socket socket getnameinfo}@anchor{1a3a}
@deffn {の関数} socket.getnameinfo (sockaddr, flags)

Translate a socket address `sockaddr' into a 2-tuple @code{(host, port)}. Depending
on the settings of `flags', the result can contain a fully qualified domain name
or numeric address representation in `host'.  Similarly, `port' can contain a
string port name or a numeric port number.

For IPv6 addresses, @code{%scope_id} is appended to the host part if `sockaddr'
contains meaningful `scope_id'. Usually this happens for multicast addresses.

For more information about `flags' you can consult @code{getnameinfo(3)@footnote{https://manpages.debian.org/getnameinfo(3)}}.

引数 @code{sockaddr} を指定して @ref{1c6e,,監査イベント} @code{socket.getnameinfo} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex getprotobyname() (socket モジュール)
@anchor{library/socket socket getprotobyname}@anchor{3997}
@deffn {の関数} socket.getprotobyname (protocolname)

Translate an internet protocol name (for example, @code{'icmp'}) to a constant
suitable for passing as the (optional) third argument to the @ref{fa1,,socket()}
function.  This is usually only needed for sockets opened in "raw" mode
(@ref{3957,,SOCK_RAW}); for the normal socket modes, the correct protocol is chosen
automatically if the protocol is omitted or zero.

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex getservbyname() (socket モジュール)
@anchor{library/socket socket getservbyname}@anchor{3998}
@deffn {の関数} socket.getservbyname (servicename[, protocolname])

インターネットサービス名とプロトコルから、そのサービスのポート番号を取得します。省略可能なプロトコル名として、 @code{'tcp'} か @code{'udp'} のどちらかを指定することができます。指定がなければどちらのプロトコルにもマッチします。

引数 @code{servicename}, @code{protocolname} を指定して @ref{1c6e,,監査イベント} @code{socket.getservbyname} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex getservbyport() (socket モジュール)
@anchor{library/socket socket getservbyport}@anchor{3999}
@deffn {の関数} socket.getservbyport (port[, protocolname])

インターネットポート番号とプロトコル名から、サービス名を取得します。省略可能なプロトコル名として、 @code{'tcp'} か @code{'udp'} のどちらかを指定することができます。指定がなければどちらのプロトコルにもマッチします。

引数 @code{port}, @code{protocolname} を指定して @ref{1c6e,,監査イベント} @code{socket.getservbyport} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex ntohl() (socket モジュール)
@anchor{library/socket socket ntohl}@anchor{399a}
@deffn {の関数} socket.ntohl (x)

32ビットの正の整数のバイトオーダを、ネットワークバイトオーダからホストバイトオーダに変換します。ホストバイトオーダとネットワークバイトオーダが一致するマシンでは、この関数は何もしません。それ以外の場合は4バイトのスワップを行います。
@end deffn

@geindex ntohs() (socket モジュール)
@anchor{library/socket socket ntohs}@anchor{a80}
@deffn {の関数} socket.ntohs (x)

16ビットの正の整数のバイトオーダを、ネットワークバイトオーダからホストバイトオーダに変換します。ホストバイトオーダとネットワークバイトオーダが一致するマシンでは、この関数は何もしません。それ以外の場合は2バイトのスワップを行います。


バージョン 3.10 で変更: Raises @ref{a81,,OverflowError} if `x' does not fit in a 16-bit unsigned
integer.

@end deffn

@geindex htonl() (socket モジュール)
@anchor{library/socket socket htonl}@anchor{399b}
@deffn {の関数} socket.htonl (x)

32ビットの正の整数のバイトオーダを、ホストバイトオーダからネットワークバイトオーダに変換します。ホストバイトオーダとネットワークバイトオーダが一致するマシンでは、この関数は何もしません。それ以外の場合は4バイトのスワップを行います。
@end deffn

@geindex htons() (socket モジュール)
@anchor{library/socket socket htons}@anchor{a7f}
@deffn {の関数} socket.htons (x)

16ビットの正の整数のバイトオーダを、ホストバイトオーダからネットワークバイトオーダに変換します。ホストバイトオーダとネットワークバイトオーダが一致するマシンでは、この関数は何もしません。それ以外の場合は2バイトのスワップを行います。


バージョン 3.10 で変更: Raises @ref{a81,,OverflowError} if `x' does not fit in a 16-bit unsigned
integer.

@end deffn

@geindex inet_aton() (socket モジュール)
@anchor{library/socket socket inet_aton}@anchor{b5a}
@deffn {の関数} socket.inet_aton (ip_string)

ドット記法によるIPv4アドレス(@code{'123.45.67.89'} など)を32ビットにパックしたバイナリ形式に変換し、長さ4のバイト列オブジェクトとして返します。この関数が返す値は、標準Cライブラリの @code{in_addr} 型を使用する関数に渡す事ができます。

@ref{b5a,,inet_aton()} はドットが 3 個以下の文字列も受け取ります; 詳細については Unix のマニュアル @code{inet(3)@footnote{https://manpages.debian.org/inet(3)}} を参照してください。

IPv4アドレス文字列が不正であれば、 @ref{2c0,,OSError} が発生します。このチェックは、この関数で使用しているCの実装 @code{inet_aton()} で行われます。

@ref{b5a,,inet_aton()} は、IPv6をサポートしません。IPv4/v6のデュアルスタックをサポートする場合は @ref{b5b,,inet_pton()} を使用します。
@end deffn

@geindex inet_ntoa() (socket モジュール)
@anchor{library/socket socket inet_ntoa}@anchor{399c}
@deffn {の関数} socket.inet_ntoa (packed_ip)

32 ビットにパックされた IPv4 アドレス (長さ 4 バイトの @ref{193,,bytes-like object}) を、標準的なドット記法による 4 桁の文字列 ('123.45.67.89' など) に変換します。この関数は、@code{in_addr} 型、つまりこの関数が引数として受け取る 32 ビットにパックされたバイナリデータに対する C の型、を使用する標準 C ライブラリのプログラムとやりとりする場合に便利です。

この関数に渡すバイトシーケンスの長さが4バイト以外であれば、 @ref{2c0,,OSError} が発生します。 @ref{399c,,inet_ntoa()} は、IPv6をサポートしません。IPv4/v6のデュアルスタックをサポートする場合は @ref{11a7,,inet_ntop()} を使用します。


バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。

@end deffn

@geindex inet_pton() (socket モジュール)
@anchor{library/socket socket inet_pton}@anchor{b5b}
@deffn {の関数} socket.inet_pton (address_family, ip_string)

IPアドレスを、アドレスファミリ固有の文字列からパックしたバイナリ形式に変換します。 @ref{b5b,,inet_pton()} は、 @code{in_addr} 型 (@ref{b5a,,inet_aton()} と同様)や @code{in6_addr} を使用するライブラリやネットワークプロトコルを呼び出す際に使用することができます。

現在サポートされている `address_family' は、 @ref{1bad,,AF_INET} と @ref{1bae,,AF_INET6} です。 `ip_string' に不正なIPアドレス文字列を指定すると、 @ref{2c0,,OSError} が発生します。有効な `ip_string' は、 `address_family' と @code{inet_pton()} の実装によって異なります。

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.4 で変更: Windowsで利用可能になりました

@end deffn

@geindex inet_ntop() (socket モジュール)
@anchor{library/socket socket inet_ntop}@anchor{11a7}
@deffn {の関数} socket.inet_ntop (address_family, packed_ip)

パックしたIPアドレス (数バイトからなる @ref{193,,bytes-like オブジェクト} ) を、 @code{'7.10.0.5'} や @code{'5aef:2b::8'} などの標準的な、アドレスファミリ固有の文字列形式に変換します。 @ref{11a7,,inet_ntop()} は (@ref{399c,,inet_ntoa()} と同様に)、 @code{in_addr} 型や @code{in6_addr} 型のオブジェクトを返すライブラリやネットワークプロトコル等で使用することができます。

現在サポートされている `address_family' の値は、 @ref{1bad,,AF_INET} と @ref{1bae,,AF_INET6} です。バイトオブジェクトの `packed_ip' の長さが、指定したアドレスファミリで適切な長さでない場合、 @ref{2ec,,ValueError} が発生します。 @ref{11a7,,inet_ntop()} の呼び出しでエラーが起こると、 @ref{2c0,,OSError} が発生します。

@ref{213f,,Availability}: Unix, Windows.


バージョン 3.4 で変更: Windowsで利用可能になりました



バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。

@end deffn

@c XXX: Are sendmsg(), recvmsg() and CMSG_*() available on any
@c non-Unix platforms?  The old (obsolete?) 4.2BSD form of the
@c interface, in which struct msghdr has no msg_control or
@c msg_controllen members, is not currently supported.

@geindex CMSG_LEN() (socket モジュール)
@anchor{library/socket socket CMSG_LEN}@anchor{1e18}
@deffn {の関数} socket.CMSG_LEN (length)

指定された `length' にある制御メッセージ（CMSG）から、末尾のパディングを除いた全体の長さを返します。この値は多くの場合、 @ref{fa6,,recvmsg()} が制御メッセージの一連の要素を受信するためのバッファサイズとして使用できますが、バッファの末尾が要素である場合であってもパディングは含まれるので、バッファサイズを取得するには 
@geindex RFC; RFC 3542
RFC 3542@footnote{https://datatracker.ietf.org/doc/html/rfc3542.html} で求められているように、 @ref{1e17,,CMSG_SPACE()} を使用した移植可能なアプリケーションが必要です。通常 `length' は定数であり、許容範囲外の値が指定された場合は @ref{a81,,OverflowError} 例外が送出されます。

@ref{213f,,Availability}: Unix, not WASI.

Unix プラットフォーム。


Added in version 3.3.

@end deffn

@geindex CMSG_SPACE() (socket モジュール)
@anchor{library/socket socket CMSG_SPACE}@anchor{1e17}
@deffn {の関数} socket.CMSG_SPACE (length)

指定された `length' の制御メッセージ（CMSG）の要素を @ref{fa6,,recvmsg()} が受信するために必要な、パディングを含めたバッファサイズを返します。複数の項目を受信するために必要なバッファスペースは、 @ref{1e17,,CMSG_SPACE()} が返すそれぞれの要素の長さの合計です。通常 `length' は定数であり、許容範囲外の値が指定された場合は @ref{a81,,OverflowError} 例外が送出されます。

一部のシステムではこの関数を提供せずに制御メッセージをサポートする可能性があることに注意してください。また、この関数の返り値を使用して設定するバッファサイズは、受信する制御メッセージの量を正確に規定しないことがあり、その後に受信するデータがパディング領域に合う場合があることに注意してください。

@ref{213f,,Availability}: Unix, not WASI.

most Unix platforms.


Added in version 3.3.

@end deffn

@geindex getdefaulttimeout() (socket モジュール)
@anchor{library/socket socket getdefaulttimeout}@anchor{3993}
@deffn {の関数} socket.getdefaulttimeout ()

新規に生成されたソケットオブジェクトの、デフォルトのタイムアウト値を浮動小数点形式の秒数で返します。タイムアウトを使用しない場合には @code{None} を返します。最初に socket モジュールがインポートされた時の初期値は @code{None} です。
@end deffn

@geindex setdefaulttimeout() (socket モジュール)
@anchor{library/socket socket setdefaulttimeout}@anchor{3955}
@deffn {の関数} socket.setdefaulttimeout (timeout)

新規に生成されるソケットオブジェクトの、デフォルトのタイムアウト値を秒数 (float 型) で設定します。最初に socket モジュールがインポートされた時の初期値は @code{None} です。指定可能な値とその意味については @ref{3951,,settimeout()} メソッドを参照してください。
@end deffn

@geindex sethostname() (socket モジュール)
@anchor{library/socket socket sethostname}@anchor{1353}
@deffn {の関数} socket.sethostname (name)

マシンのホスト名を `name' に設定します。必要な権限がない場合は @ref{2c0,,OSError} を送出します。

引数 @code{name} を指定して @ref{1c6e,,監査イベント} @code{socket.sethostname} を送出します。

@ref{213f,,Availability}: Unix, not Android.


Added in version 3.3.

@end deffn

@geindex if_nameindex() (socket モジュール)
@anchor{library/socket socket if_nameindex}@anchor{c22}
@deffn {の関数} socket.if_nameindex ()

ネットワークインターフェース情報 (index int, name string)のタプルを返します。システムコールが失敗した場合、 @ref{2c0,,OSError} 例外を送出します。

@ref{213f,,Availability}: Unix, Windows, not WASI.


Added in version 3.3.



バージョン 3.8 で変更: Windows のサポートが追加されました。


@cartouche
@quotation 注釈 
On Windows network interfaces have different names in different contexts
(all names are examples):


@itemize *

@item 
UUID: @code{@{FB605B73-AAC2-49A6-9A2F-25416AEA0573@}}

@item 
name: @code{ethernet_32770}

@item 
friendly name: @code{vEthernet (nat)}

@item 
description: @code{Hyper-V Virtual Ethernet Adapter}
@end itemize

This function returns names of the second form from the list, @code{ethernet_32770}
in this example case.
@end quotation
@end cartouche
@end deffn

@geindex if_nametoindex() (socket モジュール)
@anchor{library/socket socket if_nametoindex}@anchor{c23}
@deffn {の関数} socket.if_nametoindex (if_name)

インターフェース名 `if_name' に対応するネットワークインターフェースのインデックス番号を返します。対応するインターフェースが存在しない場合は @ref{2c0,,OSError} 例外を送出します。

@ref{213f,,Availability}: Unix, Windows, not WASI.


Added in version 3.3.



バージョン 3.8 で変更: Windows のサポートが追加されました。



@subsubheading 参考


"Interface name" is a name as documented in @ref{c22,,if_nameindex()}.

@end deffn

@geindex if_indextoname() (socket モジュール)
@anchor{library/socket socket if_indextoname}@anchor{c24}
@deffn {の関数} socket.if_indextoname (if_index)

インターフェースインデックス番号 `if_index' に対応するネットワークインターフェース名を返します。対応するインターフェースが存在しない場合は @ref{2c0,,OSError} 例外を送出します。

@ref{213f,,Availability}: Unix, Windows, not WASI.


Added in version 3.3.



バージョン 3.8 で変更: Windows のサポートが追加されました。



@subsubheading 参考


"Interface name" is a name as documented in @ref{c22,,if_nameindex()}.

@end deffn

@geindex send_fds() (socket モジュール)
@anchor{library/socket socket send_fds}@anchor{b2d}
@deffn {の関数} socket.send_fds (sock, buffers, fds[, flags[, address]])

Send the list of file descriptors `fds' over an @ref{1bb0,,AF_UNIX} socket `sock'.
The `fds' parameter is a sequence of file descriptors.
Consult @ref{6a1,,sendmsg()} for the documentation of these parameters.

@ref{213f,,Availability}: Unix, not WASI.

Unix platforms supporting @ref{6a1,,sendmsg()}
and @code{SCM_RIGHTS} mechanism.


Added in version 3.9.

@end deffn

@geindex recv_fds() (socket モジュール)
@anchor{library/socket socket recv_fds}@anchor{b2e}
@deffn {の関数} socket.recv_fds (sock, bufsize, maxfds[, flags])

Receive up to `maxfds' file descriptors from an @ref{1bb0,,AF_UNIX} socket `sock'.
Return @code{(msg, list(fds), flags, addr)}.
Consult @ref{fa6,,recvmsg()} for the documentation of these parameters.

@ref{213f,,Availability}: Unix, not WASI.

Unix platforms supporting @ref{fa6,,recvmsg()}
and @code{SCM_RIGHTS} mechanism.


Added in version 3.9.


@cartouche
@quotation 注釈 
Any truncated integers at the end of the list of file descriptors.
@end quotation
@end cartouche
@end deffn

@node socket オブジェクト,ソケットタイムアウトの注意事項,モジュールの内容,socket --- 低水準ネットワークインターフェース
@anchor{library/socket id1}@anchor{399d}@anchor{library/socket socket-objects}@anchor{3991}
@subsubsection socket オブジェクト


ソケットオブジェクトは以下のメソッドを持ちます。 @ref{13b7,,makefile()} 以外のメソッドは、Unixのソケット用システムコールに対応しています。


バージョン 3.2 で変更: @ref{1e1,,context manager} プロトコルのサポートが追加されました。コンテキストマネージャを終了することは、 @ref{d6a,,close()} を呼ぶことと同一です。


@geindex accept() (socket.socket のメソッド)
@anchor{library/socket socket socket accept}@anchor{fa2}
@deffn {メソッド} socket.accept ()

接続を受け付けます。ソケットはアドレスにbind済みで、listen中である必要があります。戻り値は @code{(conn, address)} のペアで、 `conn' は接続を通じてデータの送受信を行うための `新しい' ソケットオブジェクト、 `address' は接続先でソケットにbindしているアドレスを示します。

新たに作成されたソケットは @ref{10fc,,継承不可}  です。


バージョン 3.4 で変更: ソケットが @ref{10fc,,継承不可} になりました。



バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex bind() (socket.socket のメソッド)
@anchor{library/socket socket socket bind}@anchor{12d7}
@deffn {メソッド} socket.bind (address)

ソケットを `address' にbindします。bind済みのソケットを再バインドする事はできません。(`address' のフォーマットはアドレスファミリによって異なります -- 前述。)

引数 @code{self}, @code{address} を指定して @ref{1c6e,,監査イベント} @code{socket.bind} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex close() (socket.socket のメソッド)
@anchor{library/socket socket socket close}@anchor{f3f}
@deffn {メソッド} socket.close ()

Mark the socket closed.  The underlying system resource (e.g. a file
descriptor) is also closed when all file objects from @ref{13b7,,makefile()}
are closed.  Once that happens, all future operations on the socket
object will fail. The remote end will receive no more data (after
queued data is flushed).

ソケットはガベージコレクション時に自動的にクローズされます。しかし、明示的に @ref{d6a,,close()} するか、 @ref{186,,with} 文の中でソケットを使うことを推奨します。


バージョン 3.6 で変更: 下層の @code{close()} が呼び出される時、@ref{2c0,,OSError} が送出されるようになりました。


@cartouche
@quotation 注釈 
@ref{d6a,,close()} releases the resource associated with a connection but
does not necessarily close the connection immediately.  If you want
to close the connection in a timely fashion, call @ref{398e,,shutdown()}
before @ref{d6a,,close()}.
@end quotation
@end cartouche
@end deffn

@geindex connect() (socket.socket のメソッド)
@anchor{library/socket socket socket connect}@anchor{fa3}
@deffn {メソッド} socket.connect (address)

`address' で示されるリモートソケットに接続します。(`address' のフォーマットはアドレスファミリによって異なります --- 前述。)

If the connection is interrupted by a signal, the method waits until the
connection completes, or raises a @ref{a36,,TimeoutError} on timeout, if the
signal handler doesn't raise an exception and the socket is blocking or has
a timeout. For non-blocking sockets, the method raises an
@ref{f88,,InterruptedError} exception if the connection is interrupted by a
signal (or the exception raised by the signal handler).

引数 @code{self}, @code{address} を指定して @ref{1c6e,,監査イベント} @code{socket.connect} を送出します。


バージョン 3.5 で変更: このメソッドは、接続が信号によって中断され、信号ハンドラが例外を送出せず、ソケットがブロックであるかタイムアウトが設定されている場合、@ref{f88,,InterruptedError} 例外を送出する代わりに、接続を完了するまで待機するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/}  を参照してください)。


@ref{213f,,Availability}: not WASI.
@end deffn

@geindex connect_ex() (socket.socket のメソッド)
@anchor{library/socket socket socket connect_ex}@anchor{1753}
@deffn {メソッド} socket.connect_ex (address)

@code{connect(address)} と同様ですが、C言語の @code{connect()} 関数の呼び出しでエラーが発生した場合には例外を送出せずにエラーを戻り値として返します。(これ以外の、"host not found,"等のエラーの場合には例外が発生します。)処理が正常に終了した場合には @code{0} を返し、エラー時には @code{errno} の値を返します。この関数は、非同期接続をサポートする場合などに使用することができます。

引数 @code{self}, @code{address} を指定して @ref{1c6e,,監査イベント} @code{socket.connect} を送出します。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex detach() (socket.socket のメソッド)
@anchor{library/socket socket socket detach}@anchor{1435}
@deffn {メソッド} socket.detach ()

実際にファイル記述子を閉じることなく、ソケットオブジェクトを閉じた状態にします。ファイル記述子は返却され、他の目的に再利用することができます。


Added in version 3.2.

@end deffn

@geindex dup() (socket.socket のメソッド)
@anchor{library/socket socket socket dup}@anchor{399e}
@deffn {メソッド} socket.dup ()

ソケットを複製します。

新たに作成されたソケットは @ref{10fc,,継承不可}  です。


バージョン 3.4 で変更: ソケットが @ref{10fc,,継承不可} になりました。


@ref{213f,,Availability}: not WASI.
@end deffn

@geindex fileno() (socket.socket のメソッド)
@anchor{library/socket socket socket fileno}@anchor{399f}
@deffn {メソッド} socket.fileno ()

ソケットのファイル記述子を短い整数型で返します。失敗時には、-1 を返します。ファイル記述子は、 @ref{fa0,,select.select()} などで使用します。

Windowsではこのメソッドで返された小整数をファイル記述子を扱う箇所 (@ref{2381,,os.fdopen()} など) で利用できません。 Unix にはこの制限はありません。
@end deffn

@geindex get_inheritable() (socket.socket のメソッド)
@anchor{library/socket socket socket get_inheritable}@anchor{1101}
@deffn {メソッド} socket.get_inheritable ()

ソケットのファイル記述子またはソケットのハンドルの @ref{10fc,,継承可能フラグ} を取得します。ソケットが子プロセスへ継承可能なら @code{True} 、継承不可なら @code{False} を返します。


Added in version 3.4.

@end deffn

@geindex getpeername() (socket.socket のメソッド)
@anchor{library/socket socket socket getpeername}@anchor{38d9}
@deffn {メソッド} socket.getpeername ()

ソケットが接続しているリモートアドレスを返します。この関数は、リモート IPv4/v6ソケットのポート番号を調べる場合などに使用します。 `address' のフォーマットはアドレスファミリによって異なります(前述)。この関数をサポートしていないシステムも存在します。
@end deffn

@geindex getsockname() (socket.socket のメソッド)
@anchor{library/socket socket socket getsockname}@anchor{284}
@deffn {メソッド} socket.getsockname ()

ソケット自身のアドレスを返します。この関数は、IPv4/v6ソケットのポート番号を調べる場合などに使用します。(`address' のフォーマットはアドレスファミリによって異なります --- 前述。)
@end deffn

@geindex getsockopt() (socket.socket のメソッド)
@anchor{library/socket socket socket getsockopt}@anchor{ed0}
@deffn {メソッド} socket.getsockopt (level, optname[, buflen])

Return the value of the given socket option (see the Unix man page
@code{getsockopt(2)@footnote{https://manpages.debian.org/getsockopt(2)}}).  The needed symbolic constants (@ref{d6c,,SO_* etc.})
are defined in this module.  If `buflen' is absent, an integer option is assumed
and its integer value is returned by the function.  If `buflen' is present, it
specifies the maximum length of the buffer used to receive the option in, and
this buffer is returned as a bytes object.  It is up to the caller to decode the
contents of the buffer (see the optional built-in module @ref{db,,struct} for a way
to decode C structures encoded as byte strings).

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex getblocking() (socket.socket のメソッド)
@anchor{library/socket socket socket getblocking}@anchor{d69}
@deffn {メソッド} socket.getblocking ()

Return @code{True} if socket is in blocking mode, @code{False} if in
non-blocking.

This is equivalent to checking @code{socket.gettimeout() != 0}.


Added in version 3.7.

@end deffn

@geindex gettimeout() (socket.socket のメソッド)
@anchor{library/socket socket socket gettimeout}@anchor{39a0}
@deffn {メソッド} socket.gettimeout ()

ソケットに指定されたタイムアウト値を取得します。タイムアウト値が設定されている場合には浮動小数点型で秒数が、設定されていなければ @code{None} が返ります。この値は、最後に呼び出された @ref{303c,,setblocking()} または @ref{3951,,settimeout()} によって設定されます。
@end deffn

@geindex ioctl() (socket.socket のメソッド)
@anchor{library/socket socket socket ioctl}@anchor{ece}
@deffn {メソッド} socket.ioctl (control, option)

@ref{ece,,ioctl()} メソッドは WSAIoctl システムインターフェースへの制限されたインターフェースです。詳しい情報については、 Win32 documentation@footnote{https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx} を参照してください。

他のプラットフォームでは一般的な @ref{1851,,fcntl.fcntl()} と @ref{1694,,fcntl.ioctl()} が使われるでしょう; これらの関数は第 1 引数としてソケットオブジェクトを取ります。

現在、以下のコントロールコードのみがサポートされています。 @code{SIO_RCVALL}, @code{SIO_KEEPALIVE_VALS}, @code{SIO_LOOPBACK_FAST_PATH}。

@ref{213f,,Availability}: Windows


バージョン 3.6 で変更: @code{SIO_LOOPBACK_FAST_PATH} が追加されました。

@end deffn

@geindex listen() (socket.socket のメソッド)
@anchor{library/socket socket socket listen}@anchor{105e}
@deffn {メソッド} socket.listen ([backlog])

サーバーを有効にして、接続を受け付けるようにします。`backlog' が指定されている場合、少なくとも 0 以上でなければなりません (それより低い場合、0 に設定されます)。システムが新しい接続を拒否するまでに許可する未受付の接続の数を指定します。指定しない場合、デフォルトの妥当な値が選択されます。

@ref{213f,,Availability}: not WASI.


バージョン 3.5 で変更: `backlog' 引数が任意になりました。

@end deffn

@geindex makefile() (socket.socket のメソッド)
@anchor{library/socket socket socket makefile}@anchor{13b7}
@deffn {メソッド} socket.makefile (mode='r', buffering=None, *, encoding=None, errors=None, newline=None)

@geindex I/O control;buffering

Return a @ref{13db,,file object} associated with the socket.  The exact returned
type depends on the arguments given to @ref{13b7,,makefile()}.  These arguments are
interpreted the same way as by the built-in @ref{316,,open()} function, except
the only supported `mode' values are @code{'r'} (default), @code{'w'}, @code{'b'}, or
a combination of those.

ソケットはブロッキングモードでなければなりません。タイムアウトを設定することはできますが、タイムアウトが発生すると、ファイルオブジェクトの内部バッファが矛盾した状態になることがあります。

@ref{13b7,,makefile()} でファイルオブジェクトにソケットを関連づけた場合、ソケットを閉じるには、関連づけられたすべてのファイルオブジェクトを閉じたあとで、元のソケットの @ref{d6a,,socket.close()} を呼び出さなければなりません。

@cartouche
@quotation 注釈 
Windows では @ref{4b7,,subprocess.Popen()} の stream 引数などファイルディスクリプタつき file オブジェクトが期待されている場所では、 @ref{13b7,,makefile()} によって作成される file-like オブジェクトは使用できません。
@end quotation
@end cartouche
@end deffn

@geindex recv() (socket.socket のメソッド)
@anchor{library/socket socket socket recv}@anchor{fa4}
@deffn {メソッド} socket.recv (bufsize[, flags])

Receive data from the socket.  The return value is a bytes object representing the
data received.  The maximum amount of data to be received at once is specified
by `bufsize'. A returned empty bytes object indicates that the client has disconnected.
See the Unix manual page @code{recv(2)@footnote{https://manpages.debian.org/recv(2)}} for the meaning of the optional argument
`flags'; it defaults to zero.


バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex recvfrom() (socket.socket のメソッド)
@anchor{library/socket socket socket recvfrom}@anchor{fa5}
@deffn {メソッド} socket.recvfrom (bufsize[, flags])

ソケットからデータを受信し、結果をタプル @code{(bytes, address)} として返します。 `bytes' は受信データの bytes オブジェクトで、 `address' は送信元のアドレスを示します。オプション引数 `flags' については、 Unix のマニュアルページ @code{recv(2)@footnote{https://manpages.debian.org/recv(2)}} を参照してください。デフォルトは0です。 (`address' のフォーマットはアドレスファミリによって異なります(前述))


バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。



バージョン 3.7 で変更: For multicast IPv6 address, first item of `address' does not contain
@code{%scope_id} part anymore. In order to get full IPv6 address use
@ref{1a3a,,getnameinfo()}.

@end deffn

@geindex recvmsg() (socket.socket のメソッド)
@anchor{library/socket socket socket recvmsg}@anchor{fa6}
@deffn {メソッド} socket.recvmsg (bufsize[, ancbufsize[, flags]])

ソケットから通常のデータ (最大 `bufsize' バイト) と補助的なデータを受信します。`ancbufsize' 引数により、補助的なデータの受信に使用される内部バッファのバイト数として、サイズが設定されます。このデフォルトは 0 で、補助的なデータを受信しないことを意味します。@ref{1e17,,CMSG_SPACE()} または @ref{1e18,,CMSG_LEN()} を使用して、補助的なデータの適切なサイズを計算することができ、バッファ内に収まらないアイテムは、短縮されるか破棄されます。`flags' 引数はデフォルトでは 0 で、@ref{fa4,,recv()} での意味と同じ意味を持ちます。

戻り値は 4 要素のタプル @code{(data, ancdata, msg_flags, address)} です。`data' アイテムは、受信した非付属的データを保持する @ref{192,,bytes} オブジェクトです。`ancdata' アイテムは、ゼロ以上のタプル @code{(cmsg_level, cmsg_type, cmsg_data)} からなるリストで、受信する付属的なデータ (制御メッセージ) を表します。`cmsg_level' と `cmsg_type' はそれぞれ、プロトコルレベルとプロトコル固有のタイプを指定する整数で、`cmsg_data' は関連するデータを保持する @ref{192,,bytes} オブジェクトです。`msg_flags' アイテムは、受信したメッセージの条件を示す様々なフラグのビット OR です。詳細は、システムのドキュメントを参照してください。受信ソケットが接続されていない場合、`address' は、送信ソケットが利用できる場合にはそのアドレスで、利用できない場合、その値は未指定になります。

一部のシステムでは、@ref{6a1,,sendmsg()} と @ref{fa6,,recvmsg()} を使用して、プロセス間で @ref{1bb0,,AF_UNIX} ソケットを経由してファイル記述子を渡すことができます。この機能を使用する場合 (しばしば @ref{150b,,SOCK_STREAM} ソケットに限定されます)、@ref{fa6,,recvmsg()} は、付属的なデータ中に、@code{(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)} という形式のアイテムを返します。ここで、`fds' は、新しいファイル記述子をネイティブ C の int 型のバイナリ配列として表す @ref{192,,bytes} オブジェクトです。システムコールが返った後 @ref{fa6,,recvmsg()} が例外を送出する場合、まずこのメカニズムを経由して受信したファイル記述子を全て閉じようと試みます。

一部のシステムでは、部分的に受信した付属的なデータアイテムの短縮された長さが示されません。アイテムがバッファの末尾を超えているようである場合、@ref{fa6,,recvmsg()} は @ref{4d7,,RuntimeWarning} を送出し、関連するデータの開始位置より前で途切れていない場合、バッファ内の付属的なデータの一部を返します。

@code{SCM_RIGHTS} メカニズムをサポートするシステム上では、次の関数が最大 `maxfds' のファイル記述子を受信し、メッセージデータと記述子を含むリストを返しま(無関係な制御メッセージを受信した場合など、予期しない条件は無視します)。 @ref{6a1,,sendmsg()} も参照してください。

@example
import socket, array

def recv_fds(sock, msglen, maxfds):
    fds = array.array("i")   # Array of ints
    msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
    for cmsg_level, cmsg_type, cmsg_data in ancdata:
        if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
            # Append data, ignoring any truncated integers at the end.
            fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
    return msg, list(fds)
@end example

@ref{213f,,Availability}: Unix.

Unix プラットフォーム。


Added in version 3.3.



バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex recvmsg_into() (socket.socket のメソッド)
@anchor{library/socket socket socket recvmsg_into}@anchor{1352}
@deffn {メソッド} socket.recvmsg_into (buffers[, ancbufsize[, flags]])

@ref{fa6,,recvmsg()} と同様に動作してソケットから通常のデータと付属的なデータを受信しますが、非付属的データは新しいバイトオブジェクトとして返すのではなく、一連のバッファとして返します。`buffers' 引数は書き込み可能なバッファをエクスポートするオブジェクトのイテラブルでなければなりません (例: @ref{344,,bytearray} オブジェクト)。これらは、全てに書き込まれるか、残りバッファがなくなるまで、非付属的データの連続チャンクで埋められます。オペレーティングシステムによって、使用できるバッファの数が制限 (@ref{18ed,,sysconf()} 値 @code{SC_IOV_MAX}) されている場合があります。`ancbufsize' 引数と `flags' 引数は、@ref{fa6,,recvmsg()} での意味と同じ意味を持ちます。

戻り値は 4 要素のタプル @code{(nbytes, ancdata, msg_flags, address)} です。ここで、`nbytes' はバッファに書き込まれた非付属的データの総数で、`ancdata'、`msg_flags'、`address' は @ref{fa6,,recvmsg()} と同様です。

以下はプログラム例です:

@example
>>> import socket
>>> s1, s2 = socket.socketpair()
>>> b1 = bytearray(b'----')
>>> b2 = bytearray(b'0123456789')
>>> b3 = bytearray(b'--------------')
>>> s1.send(b'Mary had a little lamb')
22
>>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
(22, [], 0, None)
>>> [b1, b2, b3]
[bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]
@end example

@ref{213f,,Availability}: Unix.

Unix プラットフォーム。


Added in version 3.3.

@end deffn

@geindex recvfrom_into() (socket.socket のメソッド)
@anchor{library/socket socket socket recvfrom_into}@anchor{1536}
@deffn {メソッド} socket.recvfrom_into (buffer[, nbytes[, flags]])

ソケットからデータを受信し、そのデータを新しいバイト文字列として返す代わりに `buffer' に書きます。戻り値は @code{(nbytes, address)} のペアで、 `nbytes' は受信したデータのバイト数を、 `address' はデータを送信したソケットのアドレスです。オプション引数 `flags' (デフォルト:0) の意味については、 Unix マニュアルページ @code{recv(2)@footnote{https://manpages.debian.org/recv(2)}} を参照してください。(`address' のフォーマットは前述のとおりアドレスファミリーに依存します。)
@end deffn

@geindex recv_into() (socket.socket のメソッド)
@anchor{library/socket socket socket recv_into}@anchor{1535}
@deffn {メソッド} socket.recv_into (buffer[, nbytes[, flags]])

`nbytes' バイトまでのデータをソケットから受信して、そのデータを新しいバイト文字列にするのではなく `buffer' に保存します。 `nbytes' が指定されない(あるいは0が指定された)場合、 `buffer' の利用可能なサイズまで受信します。受信したバイト数を返り値として返します。オプション引数 `flags' (デフォルト:0) の意味については、 Unix マニュアルページ @code{recv(2)@footnote{https://manpages.debian.org/recv(2)}} を参照してください。
@end deffn

@geindex send() (socket.socket のメソッド)
@anchor{library/socket socket socket send}@anchor{fa7}
@deffn {メソッド} socket.send (bytes[, flags])

ソケットにデータを送信します。ソケットはリモートソケットに接続済みでなければなりません。オプション引数 `flags' の意味は、上記 @ref{fa4,,recv()} と同じです。戻り値として、送信したバイト数を返します。アプリケーションでは、必ず戻り値をチェックし、全てのデータが送られた事を確認する必要があります。データの一部だけが送信された場合、アプリケーションで残りのデータを再送信してください。 @ref{39a1,,ソケットプログラミングHOWTO} に、さらに詳しい情報があります。


バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex sendall() (socket.socket のメソッド)
@anchor{library/socket socket socket sendall}@anchor{fa8}
@deffn {メソッド} socket.sendall (bytes[, flags])

ソケットにデータを送信します。ソケットはリモートソケットに接続済みでなければなりません。オプション引数 `flags' の意味は、上記 @ref{fa4,,recv()} と同じです。 @ref{fa7,,send()} と異なり、このメソッドは `bytes' の全データを送信するか、エラーが発生するまで処理を継続します。正常終了の場合は @code{None} を返し、エラー発生時には例外が発生します。エラー発生時、送信されたバイト数を調べる事はできません。


バージョン 3.5 で変更: ソケットのタイムアウトは、データが正常に送信される度にリセットされなくなりました。ソケットのタイムアウトは、すべてのデータを送る最大の合計時間となります。



バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex sendto() (socket.socket のメソッド)
@anchor{library/socket socket socket sendto}@anchor{fa9}
@deffn {メソッド} socket.sendto (bytes, address)

@deffnx {メソッド} socket.sendto (bytes, flags, address)

ソケットにデータを送信します。このメソッドでは接続先を `address' で指定するので、接続済みではいけません。オプション引数 `flags' の意味は、上記 @ref{fa4,,recv()} と同じです。戻り値として、送信したバイト数を返します。(`address' のフォーマットはアドレスファミリによって異なります --- 前述。)

引数 @code{self}, @code{address} を指定して @ref{1c6e,,監査イベント} @code{socket.sendto} を送出します。


バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex sendmsg() (socket.socket のメソッド)
@anchor{library/socket socket socket sendmsg}@anchor{6a1}
@deffn {メソッド} socket.sendmsg (buffers[, ancdata[, flags[, address]]])

非付属的なデータを一連のバッファから集め、単一のメッセージにまとめることで、通常のデータと付属的なデータをソケットに送信します。`buffers' 引数は、非付属的なデータを @ref{193,,bytes-like objects} (例: @ref{192,,bytes} オブジェクト) のイテラブルとして指定します。オペレーティングシステムによって、使用できるバッファの数が制限 (@ref{18ed,,sysconf()} 値 @code{SC_IOV_MAX}) されている場合があります。`ancdata' 引数は付属的なデータ (制御メッセージ) をゼロ以上のタプル @code{(cmsg_level, cmsg_type, cmsg_data)} のイテラブルとして指定します。ここで、`cmsg_level' と `cmsg_type' はそれぞれプロトコルレベルとプロトコル固有のタイプを指定する整数で、`cmsg_data' は関連データを保持するバイトライクオブジェクトです。一部のシステム (特に @ref{1e17,,CMSG_SPACE()} を持たないシステム) では、一度の呼び出しで一つの制御メッセージの送信しかサポートされていない場合があります。`flags' 引数のデフォルトは 0 であり、@ref{fa7,,send()} での意味と同じ意味を持ちます。@code{None} 以外の `address' が渡された場合、メッセージの目的地のアドレスを設定します。戻り値は、送信された非付属的データのバイト数です。

以下の関数は、@code{SCM_RIGHTS} メカニズムをサポートするシステムで、ファイル記述子 `fds' を @ref{1bb0,,AF_UNIX} ソケット経由で送信します。@ref{fa6,,recvmsg()} も参照してください。

@example
import socket, array

def send_fds(sock, msg, fds):
    return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
@end example

@ref{213f,,Availability}: Unix, not WASI.

Unix プラットフォーム。

引数 @code{self}, @code{address} を指定して @ref{1c6e,,監査イベント} @code{socket.sendmsg} を送出します。


Added in version 3.3.



バージョン 3.5 で変更: システムコールが中断されシグナルハンドラが例外を送出しなかった場合、このメソッドは @ref{f88,,InterruptedError} 例外を送出する代わりにシステムコールを再試行するようになりました (論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex sendmsg_afalg() (socket.socket のメソッド)
@anchor{library/socket socket socket sendmsg_afalg}@anchor{ed3}
@deffn {メソッド} socket.sendmsg_afalg ([msg], *, op[, iv[, assoclen[, flags]]])

@ref{6a1,,sendmsg()} の @ref{ed2,,AF_ALG} ソケット用に特化したバージョンです。@ref{ed2,,AF_ALG} ソケットの、モード、IV、AEAD に関連づけられたデータ長、フラグを設定します。

@ref{213f,,Availability}: Linux >= 2.6.38.


Added in version 3.6.

@end deffn

@geindex sendfile() (socket.socket のメソッド)
@anchor{library/socket socket socket sendfile}@anchor{105d}
@deffn {メソッド} socket.sendfile (file, offset=0, count=None)

高性能の @ref{d05,,os.sendfile} を使用して、ファイルを EOF まで送信し、送信されたバイトの総数を返します。`file' は、バイナリモードで開かれた標準的なファイルオブジェクトです。@ref{d05,,os.sendfile} が使用できない場合 (例: Windows)、または `file' が標準的なファイルでない場合、代わりに @ref{fa7,,send()} が使用されます。`offset' は、ファイルの読み出し開始位置を指定します。`count' が指定されている場合、ファイルを EOF まで送信するのではなく、転送するバイトの総数を指定します。ファイルの位置は、返る時に更新されます。あるいは、エラー時には @ref{15c6,,file.tell()}  を使用して送信されたバイトの数を確認することができます。ソケットは @ref{150b,,SOCK_STREAM} タイプでなければなりません。非ブロックソケットはサポートされていません。


Added in version 3.5.

@end deffn

@geindex set_inheritable() (socket.socket のメソッド)
@anchor{library/socket socket socket set_inheritable}@anchor{1102}
@deffn {メソッド} socket.set_inheritable (inheritable)

ソケットのファイル記述子、またはソケットのハンドルの、 @ref{10fc,,継承可能フラグ} を立てます。


Added in version 3.4.

@end deffn

@geindex setblocking() (socket.socket のメソッド)
@anchor{library/socket socket socket setblocking}@anchor{303c}
@deffn {メソッド} socket.setblocking (flag)

ソケットをブロッキングモード、または非ブロッキングモードに設定します。`flag' が False の場合にはソケットは非ブロッキングモードになり、True の場合にはブロッキングモードになります。

このメソッドは、次の @ref{3951,,settimeout()} 呼び出しの省略表記です:


@itemize *

@item 
@code{sock.setblocking(True)} は @code{sock.settimeout(None)} と等価です

@item 
@code{sock.setblocking(False)} は @code{sock.settimeout(0.0)} と等価です
@end itemize


バージョン 3.7 で変更: The method no longer applies @ref{e04,,SOCK_NONBLOCK} flag on
@ref{e06,,socket.type}.

@end deffn

@geindex settimeout() (socket.socket のメソッド)
@anchor{library/socket socket socket settimeout}@anchor{3951}
@deffn {メソッド} socket.settimeout (value)

Set a timeout on blocking socket operations.  The `value' argument can be a
nonnegative floating-point number expressing seconds, or @code{None}.
If a non-zero value is given, subsequent socket operations will raise a
@ref{a35,,timeout} exception if the timeout period `value' has elapsed before
the operation has completed.  If zero is given, the socket is put in
non-blocking mode. If @code{None} is given, the socket is put in blocking mode.

詳しくは @ref{39a2,,ソケットタイムアウトの注意事項} を参照してください。


バージョン 3.7 で変更: The method no longer toggles @ref{e04,,SOCK_NONBLOCK} flag on
@ref{e06,,socket.type}.

@end deffn

@geindex setsockopt() (socket.socket のメソッド)
@anchor{library/socket socket socket setsockopt}@anchor{ed1}
@deffn {メソッド} socket.setsockopt (level, optname, value: int | Buffer)

@deffnx {メソッド} socket.setsockopt (level, optname, None, optlen: int)

@geindex module;struct

Set the value of the given socket option (see the Unix manual page
@code{setsockopt(2)@footnote{https://manpages.debian.org/setsockopt(2)}}).  The needed symbolic constants are defined in this
module (SO_* etc. <socket-unix-constants>).  The value can be an integer,
@code{None} or a @ref{193,,bytes-like object} representing a buffer. In the latter
case it is up to the caller to ensure that the bytestring contains the
proper bits (see the optional built-in module @ref{db,,struct} for a way to
encode C structures as bytestrings). When `value' is set to @code{None},
`optlen' argument is required. It's equivalent to calling @code{setsockopt()} C
function with @code{optval=NULL} and @code{optlen=optlen}.


バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。



バージョン 3.6 で変更: setsockopt(level, optname, None, optlen: int) の形式が追加されました。


@ref{213f,,Availability}: not WASI.
@end deffn

@geindex shutdown() (socket.socket のメソッド)
@anchor{library/socket socket socket shutdown}@anchor{398e}
@deffn {メソッド} socket.shutdown (how)

接続の片方向、または両方向を切断します。 `how' が @ref{398b,,SHUT_RD} の場合、以降は受信を行えません。 `how' が @ref{398c,,SHUT_WR} の場合、以降は送信を行えません。 `how' が @ref{398d,,SHUT_RDWR} の場合、以降は送受信を行えません。

@ref{213f,,Availability}: not WASI.
@end deffn

@geindex share() (socket.socket のメソッド)
@anchor{library/socket socket socket share}@anchor{e02}
@deffn {メソッド} socket.share (process_id)

ソケットを複製し、対象のプロセスと共有するための bytes オブジェクトを返します。対象のプロセスを `process_id' で指定しなければなりません。戻り値の bytes オブジェクトは、何らかのプロセス間通信を使って対象のプロセスに伝えます。対象のプロセス側では、 @ref{e01,,fromshare()} を使って複製されたソケットをとらえます。オペレーティング・システムは対象のプロセスに対してソケットを複製するため、このメソッドを呼び出した後であれば、元のソケットをクローズしても、対象のプロセスに渡ったソケットには影響がありません。

@ref{213f,,Availability}: Windows.


Added in version 3.3.

@end deffn

@code{read()} メソッドと @code{write()} メソッドは存在しませんので注意してください。代わりに `flags' を省略した @ref{fa4,,recv()} と @ref{fa7,,send()} を使うことができます。

ソケットオブジェクトには以下の @ref{fa1,,socket} コンストラクタに渡された値に対応した (読み出し専用) 属性があります。

@geindex family (socket.socket の属性)
@anchor{library/socket socket socket family}@anchor{39a3}
@deffn {の属性} socket.family

ソケットファミリー。
@end deffn

@geindex type (socket.socket の属性)
@anchor{library/socket socket socket type}@anchor{e06}
@deffn {の属性} socket.type

ソケットタイプ。
@end deffn

@geindex proto (socket.socket の属性)
@anchor{library/socket socket socket proto}@anchor{39a4}
@deffn {の属性} socket.proto

ソケットプロトコル。
@end deffn

@node ソケットタイムアウトの注意事項,使用例<27>,socket オブジェクト,socket --- 低水準ネットワークインターフェース
@anchor{library/socket notes-on-socket-timeouts}@anchor{39a5}@anchor{library/socket socket-timeouts}@anchor{39a2}
@subsubsection ソケットタイムアウトの注意事項


ソケットオブジェクトは、ブロッキングモード、非ブロッキングモード、タイムアウトモードのうち、いずれか1つのモードをとります。デフォルトでは、ソケットは常にブロッキングモードで作成されますが、 @ref{3955,,setdefaulttimeout()} で標準のモードを変更することができます。


@itemize *

@item 
`ブロッキングモード' での操作は、完了するか、または（接続がタイムアウトするなどして）システムがエラーを返すまで、ブロックされます。

@item 
`非ブロッキングモード' での操作は、ただちに完了できない場合、例外を送出して失敗します。この場合の例外の種類は、システムに依存するため、ここに記すことができません。 @ref{c6,,select} モジュールの関数を使って、ソケットの読み書きが利用可能かどうか、可能な場合はいつ利用できるかを調べることができます。

@item 
`タイムアウトモード' での操作は、指定されたタイムアウトの時間内に完了しなければ、 @ref{a35,,timeout} 例外を送出します。タイムアウトの時間内にシステムがエラーを返した場合は、そのエラーを返します。
@end itemize

@cartouche
@quotation 注釈 
At the operating system level, sockets in `timeout mode' are internally set
in non-blocking mode.  Also, the blocking and timeout modes are shared between
file descriptors and socket objects that refer to the same network endpoint.
This implementation detail can have visible consequences if e.g. you decide
to use the @ref{399f,,fileno()} of a socket.
@end quotation
@end cartouche

@menu
* タイムアウトと connect メソッド:: 
* タイムアウトと accept メソッド:: 

@end menu

@node タイムアウトと connect メソッド,タイムアウトと accept メソッド,,ソケットタイムアウトの注意事項
@anchor{library/socket timeouts-and-the-connect-method}@anchor{39a6}
@subsubsection タイムアウトと @code{connect} メソッド


@ref{fa3,,connect()} もタイムアウト設定に従います。一般的に、 @ref{3951,,settimeout()} を @ref{fa3,,connect()} の前に呼ぶか、 @ref{882,,create_connection()} にタイムアウト引数を渡すことが推奨されます。ただし、システムのネットワークスタックが Python のソケットタイムアウトの設定を無視して、自身の接続タイムアウトエラーを返すこともあります。

@node タイムアウトと accept メソッド,,タイムアウトと connect メソッド,ソケットタイムアウトの注意事項
@anchor{library/socket timeouts-and-the-accept-method}@anchor{39a7}
@subsubsection タイムアウトと @code{accept} メソッド


@ref{3993,,getdefaulttimeout()} が @ref{885,,None} でない場合、 @ref{fa2,,accept()} メソッドが返すソケットでは、そのタイムアウトが継承されます。 @ref{885,,None} である場合、待機中のソケットの設定によって動作は異なります。


@itemize *

@item 
待機中のソケットが `ブロッキングモード' または `タイムアウトモード' である場合、@ref{fa2,,accept()} が返すソケットは、`ブロッキングモード' になります。

@item 
待機中のソケットが `非ブロッキングモード' である場合、@ref{fa2,,accept()} が返すソケットは、オペレーティングシステムによってブロッキングモードまたは非ブロッキングモードになります。クロスプラットフォームの動作を確保したい場合、この設定を手動でオーバーライドすることをお勧めします。
@end itemize

@node 使用例<27>,,ソケットタイムアウトの注意事項,socket --- 低水準ネットワークインターフェース
@anchor{library/socket example}@anchor{39a8}@anchor{library/socket socket-example}@anchor{39a9}
@subsubsection 使用例


Here are four minimal example programs using the TCP/IP protocol: a server that
echoes all data that it receives back (servicing only one client), and a client
using it.  Note that a server must perform the sequence @ref{fa1,,socket()},
@ref{12d7,,bind()}, @ref{105e,,listen()}, @ref{fa2,,accept()} (possibly
repeating the @ref{fa2,,accept()} to service more than one client), while a
client only needs the sequence @ref{fa1,,socket()}, @ref{fa3,,connect()}.  Also
note that the server does not @ref{fa8,,sendall()}/@ref{fa4,,recv()} on
the socket it is listening on but on the new socket returned by
@ref{fa2,,accept()}.

次のクライアントとサーバは、IPv4 のみをサポートしています。

@example
# Echo server program
import socket

HOST = '@w{'}                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data: break
            conn.sendall(data)
@end example

@example
# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))
@end example

The next two examples are identical to the above two, but support both IPv4 and
IPv6. The server side will listen to the first address family available (it
should listen to both instead). On most of IPv6-ready systems, IPv6 will take
precedence and the server may not accept IPv4 traffic. The client side will try
to connect to all the addresses returned as a result of the name resolution, and
sends traffic to the first one connected successfully.

@example
# Echo server program
import socket
import sys

HOST = None               # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                              socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.bind(sa)
        s.listen(1)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
conn, addr = s.accept()
with conn:
    print('Connected by', addr)
    while True:
        data = conn.recv(1024)
        if not data: break
        conn.send(data)
@end example

@example
# Echo client program
import socket
import sys

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.connect(sa)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
with s:
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))
@end example

次の例は、Windowsで raw socket を利用して非常にシンプルなネットワークスニファーを書きます。このサンプルを実行するには、インターフェースを操作するための管理者権限が必要です:

@example
import socket

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())

# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))

# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# receive all packets
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

# receive a packet
print(s.recvfrom(65565))

# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
@end example

次の例では、ソケットインターフェースを使用してローソケットプロトコルを使用する CAN ネットワークと通信する方法を説明します。ブロードキャストマネージャプロトコロルで CAN を使用するには、以下でソケットを開きます。

@example
socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
@end example

ソケットの束縛 (@code{CAN_RAW}) または (@ref{11a5,,CAN_BCM}) 接続を行ったあと、ソケットオブジェクトで @ref{fa7,,socket.send()} と @ref{fa4,,socket.recv()} 操作 (とそのカウンターパート) を通常通りに使用することができます。

最後の例では、特権が必要になるかもしれません:

@example
import socket
import struct


# CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)

can_frame_fmt = "=IB3x8s"
can_frame_size = struct.calcsize(can_frame_fmt)

def build_can_frame(can_id, data):
    can_dlc = len(data)
    data = data.ljust(8, b'\x00')
    return struct.pack(can_frame_fmt, can_id, can_dlc, data)

def dissect_can_frame(frame):
    can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
    return (can_id, can_dlc, data[:can_dlc])


# create a raw socket and bind it to the 'vcan0' interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind(('vcan0',))

while True:
    cf, addr = s.recvfrom(can_frame_size)

    print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))

    try:
        s.send(cf)
    except OSError:
        print('Error sending CAN frame')

    try:
        s.send(build_can_frame(0x01, b'\x01\x02\x03'))
    except OSError:
        print('Error sending CAN frame')
@end example

この例を、ほとんど間を空けずに複数回実行すると、以下のエラーが発生する場合があります:

@example
OSError: [Errno 98] Address already in use
@end example

これは以前の実行がソケットを @code{TIME_WAIT} 状態のままにし、すぐには再利用できないことで起こります。

There is a @code{socket} flag to set, in order to prevent this,
@code{socket.SO_REUSEADDR}:

@example
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
@end example

@code{SO_REUSEADDR} フラグは、 @code{TIME_WAIT} 状態にあるローカルソケットをそのタイムアウト期限が自然に切れるのを待つことなく再利用することをカーネルに伝えます。


@subsubheading 参考


C 言語によるソケットプログラミングの基礎については、以下の資料を参照してください。


@itemize -

@item 
`An Introductory 4.3BSD Interprocess Communication Tutorial', by Stuart Sechrest

@item 
`An Advanced 4.3BSD Interprocess Communication Tutorial', by Samuel J.  Leffler et
al,
@end itemize

両書とも UNIX Programmer's Manual, Supplementary Documents 1 (PS1:7章 PS1:8章)。ソケットの詳細については、各プラットフォームのソケット関連システムコールに関するドキュメントも参照してください。Unix ではマニュアルページ、WindowsではWinSock (または WinSock2) 仕様書をご覧ください。IPv6 対応の API については、 
@geindex RFC; RFC 3493
RFC 3493@footnote{https://datatracker.ietf.org/doc/html/rfc3493.html} "Basic Socket Interface Extensions for IPv6" を参照してください。


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ssl --- ソケットオブジェクト用の TLS/SSL ラッパー,select --- I/O 完了の待機,socket --- 低水準ネットワークインターフェース,ネットワーク通信とプロセス間通信
@anchor{library/ssl doc}@anchor{39aa}@anchor{library/ssl module-ssl}@anchor{d5}@anchor{library/ssl ssl-tls-ssl-wrapper-for-socket-objects}@anchor{39ab}@anchor{library/ssl translation-repo}@anchor{39ac}
@subsection @code{ssl} --- ソケットオブジェクト用の TLS/SSL ラッパー


@geindex module; ssl

`Source code:' Lib/ssl.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/ssl.py}

@geindex OpenSSL;(use in module ssl)

@geindex TLS
@geindex SSL
@geindex Transport Layer Security
@geindex Secure Sockets Layer


__________________________________________________________________


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.

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@cartouche
@quotation 注釈 
Some behavior may be platform dependent, since calls are made to the
operating system socket APIs.  The installed version of OpenSSL may also
cause variations in behavior. For example, TLSv1.3 comes with OpenSSL version
1.1.1.
@end quotation
@end cartouche

@cartouche
@quotation 警告 
@ref{3895,,セキュリティで考慮すべき点} を読まずにこのモジュールを使用しないでください。SSL のデフォルト設定はアプリケーションに十分ではないので、読まない場合はセキュリティに誤った意識を持ってしまうかもしれません。
@end quotation
@end cartouche

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

このセクションでは、 @code{ssl} モジュールのオブジェクトと関数を解説します。 TLS, SSL, 証明書に関するより一般的な情報は、末尾にある "See Also" のセクションを参照してください。

This module provides a class, @ref{ae7,,ssl.SSLSocket}, which is derived from the
@ref{fa1,,socket.socket} type, and provides a socket-like wrapper that also
encrypts and decrypts the data going over the socket with SSL.  It supports
additional methods such as @code{getpeercert()}, which retrieves the
certificate of the other side of the connection, @code{cipher()}, which
retrieves the cipher being used for the secure connection or
@code{get_verified_chain()}, @code{get_unverified_chain()} which retrieves
certificate chain.

より洗練されたアプリケーションのために、 @ref{357,,ssl.SSLContext} クラスが設定と証明書の管理の助けとなるでしょう。それは @ref{748,,SSLContext.wrap_socket()} メソッドを通して SSL ソケットを作成することで引き継がれます。


バージョン 3.5.3 で変更: Updated to support linking with OpenSSL 1.1.0



バージョン 3.6 で変更: OpenSSL 0.9.8, 1.0.0, 1.0.1 は廃止されており、もはやサポートされていません。ssl モジュールは、将来的に OpenSSL 1.0.2 または 1.1.0 を必要とするようになります。



バージョン 3.10 で変更: 
@geindex Python Enhancement Proposals; PEP 644
PEP 644@footnote{https://peps.python.org/pep-0644/} has been implemented. The ssl module requires OpenSSL 1.1.1
or newer.

Use of deprecated constants and functions result in deprecation warnings.


@menu
* 関数、定数、例外:: 
* SSL ソケット:: 
* SSL コンテキスト:: 
* 証明書:: 
* 使用例: 使用例<28>. 
* ノンブロッキングソケットについての注意事項:: 
* メモリ BIO サポート: メモリ BIO サポート<2>. 
* SSL セッション:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<3>. 
* TLS 1.3: TLS 1 3. 

@end menu

@node 関数、定数、例外,SSL ソケット,,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl functions-constants-and-exceptions}@anchor{39ad}
@subsubsection 関数、定数、例外


@menu
* ソケットの作成: ソケットの作成<2>. 
* コンテキストの作成:: 
* 例外: 例外<19>. 
* 乱数生成:: 
* 証明書の取り扱い:: 
* 定数: 定数<9>. 

@end menu

@node ソケットの作成<2>,コンテキストの作成,,関数、定数、例外
@anchor{library/ssl socket-creation}@anchor{39ae}
@subsubsection ソケットの作成


Instances of @ref{ae7,,SSLSocket} must be created using the
@ref{748,,SSLContext.wrap_socket()} method. The helper function
@ref{480,,create_default_context()} returns a new context with secure default
settings.

Client socket example with default context and IPv4/IPv6 dual stack:

@example
import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
@end example

Client socket example with custom context and IPv4:

@example
hostname = 'www.python.org'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('path/to/cabundle.pem')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
@end example

Server socket example listening on localhost IPv4:

@example
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    sock.bind(('127.0.0.1', 8443))
    sock.listen(5)
    with context.wrap_socket(sock, server_side=True) as ssock:
        conn, addr = ssock.accept()
        ...
@end example

@node コンテキストの作成,例外<19>,ソケットの作成<2>,関数、定数、例外
@anchor{library/ssl context-creation}@anchor{39af}
@subsubsection コンテキストの作成


コンビニエンス関数が、共通の目的で使用される @ref{357,,SSLContext} オブジェクトを作成するのに役立ちます。

@geindex create_default_context() (ssl モジュール)
@anchor{library/ssl ssl create_default_context}@anchor{480}
@deffn {の関数} ssl.create_default_context (purpose=Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None)

Return a new @ref{357,,SSLContext} object with default settings for
the given `purpose'.  The settings are chosen by the @code{ssl} module,
and usually represent a higher security level than when calling the
@ref{357,,SSLContext} constructor directly.

`cafile', `capath', `cadata' は証明書の検証で信用するオプションの CA 証明書で、 @ref{10ee,,SSLContext.load_verify_locations()} のものと同じです。これら 3 つすべてが @ref{885,,None} であれば、この関数は代わりにシステムのデフォルトの CA 証明書を信用して選択することができます。

The settings are: @ref{a72,,PROTOCOL_TLS_CLIENT} or
@ref{a73,,PROTOCOL_TLS_SERVER}, @ref{a3a,,OP_NO_SSLv2}, and @ref{a3b,,OP_NO_SSLv3}
with high encryption cipher suites without RC4 and
without unauthenticated cipher suites. Passing @ref{11b5,,SERVER_AUTH}
as `purpose' sets @ref{39b0,,verify_mode} to @ref{39b1,,CERT_REQUIRED}
and either loads CA certificates (when at least one of `cafile', `capath' or
`cadata' is given) or uses @ref{11b4,,SSLContext.load_default_certs()} to load
default CA certificates.

When @ref{39b2,,keylog_filename} is supported and the environment
variable 
@geindex SSLKEYLOGFILE
@geindex 環境変数; SSLKEYLOGFILE
@code{SSLKEYLOGFILE} is set, @ref{480,,create_default_context()}
enables key logging.

The default settings for this context include
@ref{481,,VERIFY_X509_PARTIAL_CHAIN} and @ref{551,,VERIFY_X509_STRICT}.
These make the underlying OpenSSL implementation behave more like
a conforming implementation of 
@geindex RFC; RFC 5280
RFC 5280@footnote{https://datatracker.ietf.org/doc/html/rfc5280.html}, in exchange for a small
amount of incompatibility with older X.509 certificates.

@cartouche
@quotation 注釈 
プロトコル、オプション、暗号方式その他の設定は、事前に非推奨の状態にすることなく、もっと制限の強い値に変更される場合があります。これらの値は、互換性と安全性との妥当なバランスをとって決められます。

もしもあなたのアプリケーションが特定の設定を必要とする場合、 @ref{357,,SSLContext} を作って自分自身で設定を適用すべきです。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
ある種の古いクライアントやサーバが接続しようと試みてきた場合に、この関数で作られた @ref{357,,SSLContext} が "Protocol or cipher suite mismatch" で始まるエラーを起こすのを目撃したらそれは、この関数が @ref{a3b,,OP_NO_SSLv3} を使って除外している SSL 3.0 しかサポートしていないのでしょう。SSL 3.0 は 完璧にぶっ壊れている@footnote{https://en.wikipedia.org/wiki/POODLE} ことが広く知られています。それでもまだこの関数を使って、ただし SSL 3.0 接続を許可したいと望むならば、これをこのように再有効化できます:

@example
ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
ctx.options &= ~ssl.OP_NO_SSLv3
@end example
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
This context enables @ref{551,,VERIFY_X509_STRICT} by default, which
may reject pre-
@geindex RFC; RFC 5280
RFC 5280@footnote{https://datatracker.ietf.org/doc/html/rfc5280.html} or malformed certificates that the
underlying OpenSSL implementation otherwise would accept. While disabling
this is not recommended, you can do so using:

@example
ctx = ssl.create_default_context()
ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT
@end example
@end quotation
@end cartouche


Added in version 3.4.



バージョン 3.4.4 で変更: デフォルトの暗号設定から RC4 が除かれました。



バージョン 3.6 で変更: デフォルトの暗号化文字列に ChaCha20/Poly1305 が追加されました。

デフォルトの暗号化文字列から 3DES が除かれました。



バージョン 3.8 で変更: Support for key logging to 
@geindex SSLKEYLOGFILE
@geindex 環境変数; SSLKEYLOGFILE
@code{SSLKEYLOGFILE} was added.



バージョン 3.10 で変更: The context now uses @ref{a72,,PROTOCOL_TLS_CLIENT} or
@ref{a73,,PROTOCOL_TLS_SERVER} protocol instead of generic
@ref{39b3,,PROTOCOL_TLS}.



バージョン 3.13 で変更: The context now uses @ref{481,,VERIFY_X509_PARTIAL_CHAIN} and
@ref{551,,VERIFY_X509_STRICT} in its default verify flags.

@end deffn

@node 例外<19>,乱数生成,コンテキストの作成,関数、定数、例外
@anchor{library/ssl exceptions}@anchor{39b4}
@subsubsection 例外


@geindex SSLError
@anchor{library/ssl ssl SSLError}@anchor{1491}
@deffn {例外} ssl.SSLError

(現在のところ OpenSSL ライブラリによって提供されている)下層の SSL 実装からのエラーを伝えるための例外です。このエラーは、低レベルなネットワークの上に載っている、高レベルな暗号化と認証レイヤーでの問題を通知します。このエラーは @ref{2c0,,OSError} のサブタイプです。 @ref{1491,,SSLError} インスタンスのエラーコードとメッセージは OpenSSL ライブラリによるものです。


バージョン 3.3 で変更: @ref{1491,,SSLError} は以前は @ref{1261,,socket.error} のサブタイプでした。


@geindex library (ssl.SSLError の属性)
@anchor{library/ssl ssl SSLError library}@anchor{135f}
@deffn {の属性} library

エラーが起こった OpenSSL サブモジュールを示すニーモニック文字列で、 @code{SSL}, @code{PEM}, @code{X509} などです。取り得る値は OpenSSL のバージョンに依存します。


Added in version 3.3.

@end deffn

@geindex reason (ssl.SSLError の属性)
@anchor{library/ssl ssl SSLError reason}@anchor{1360}
@deffn {の属性} reason

エラーが起こった原因を示すニーモニック文字列で、 @code{CERTIFICATE_VERIFY_FAILED} などです。取り得る値は OpenSSL のバージョンに依存します。


Added in version 3.3.

@end deffn
@end deffn

@geindex SSLZeroReturnError
@anchor{library/ssl ssl SSLZeroReturnError}@anchor{39b5}
@deffn {例外} ssl.SSLZeroReturnError

読み出しあるいは書き込みを試みようとした際に SSL コネクションが行儀よく閉じられてしまった場合に送出される @ref{1491,,SSLError} サブクラス例外です。これは下層の転送(read TCP)が閉じたことは意味しないことに注意してください。


Added in version 3.3.

@end deffn

@geindex SSLWantReadError
@anchor{library/ssl ssl SSLWantReadError}@anchor{1069}
@deffn {例外} ssl.SSLWantReadError

読み出しあるいは書き込みを試みようとした際に、リクエストが遂行される前に下層の TCP 転送で受け取る必要があるデータが不足した場合に @ref{39b6,,non-blocking SSL socket} によって送出される @ref{1491,,SSLError} サブクラス例外です。


Added in version 3.3.

@end deffn

@geindex SSLWantWriteError
@anchor{library/ssl ssl SSLWantWriteError}@anchor{106a}
@deffn {例外} ssl.SSLWantWriteError

読み出しあるいは書き込みを試みようとした際に、リクエストが遂行される前に下層の TCP 転送が送信する必要があるデータが不足した場合に @ref{39b6,,non-blocking SSL socket} によって送出される @ref{1491,,SSLError} サブクラス例外です。


Added in version 3.3.

@end deffn

@geindex SSLSyscallError
@anchor{library/ssl ssl SSLSyscallError}@anchor{39b7}
@deffn {例外} ssl.SSLSyscallError

SSL ソケット上で操作を遂行しようとしていてシステムエラーが起こった場合に送出される @ref{1491,,SSLError} サブクラス例外です。残念ながら元となった errno 番号を調べる簡単な方法はありません。


Added in version 3.3.

@end deffn

@geindex SSLEOFError
@anchor{library/ssl ssl SSLEOFError}@anchor{1ab8}
@deffn {例外} ssl.SSLEOFError

SSL コネクションが唐突に打ち切られた際に送出される @ref{1491,,SSLError} サブクラス例外です。一般的に、このエラーが起こったら下層の転送を再利用しようと試みるべきではありません。


Added in version 3.3.

@end deffn

@geindex SSLCertVerificationError
@anchor{library/ssl ssl SSLCertVerificationError}@anchor{d75}
@deffn {例外} ssl.SSLCertVerificationError

A subclass of @ref{1491,,SSLError} raised when certificate validation has
failed.


Added in version 3.7.


@geindex verify_code (ssl.SSLCertVerificationError の属性)
@anchor{library/ssl ssl SSLCertVerificationError verify_code}@anchor{39b8}
@deffn {の属性} verify_code

A numeric error number that denotes the verification error.
@end deffn

@geindex verify_message (ssl.SSLCertVerificationError の属性)
@anchor{library/ssl ssl SSLCertVerificationError verify_message}@anchor{39b9}
@deffn {の属性} verify_message

A human readable string of the verification error.
@end deffn
@end deffn

@geindex CertificateError
@anchor{library/ssl ssl CertificateError}@anchor{39ba}
@deffn {例外} ssl.CertificateError

@ref{d75,,SSLCertVerificationError} の別名です。


バージョン 3.7 で変更: 例外は @ref{d75,,SSLCertVerificationError} の別名になりました。

@end deffn

@node 乱数生成,証明書の取り扱い,例外<19>,関数、定数、例外
@anchor{library/ssl random-generation}@anchor{39bb}
@subsubsection 乱数生成


@geindex RAND_bytes() (ssl モジュール)
@anchor{library/ssl ssl RAND_bytes}@anchor{747}
@deffn {の関数} ssl.RAND_bytes (num, /)

暗号学的に強固な擬似乱数の `num' バイトを返します。擬似乱数生成器に十分なデータでシードが与えられていない場合や、現在の RANDOM メソッドに操作がサポートされていない場合は @ref{1491,,SSLError} を送出します。 @ref{1c7e,,RAND_status()} を使って擬似乱数生成器の状態をチェックできます。
@ref{39bc,,RAND_add()} を使って擬似乱数生成器にシードを与えることができます。

ほとんどすべてのアプリケーションでは @ref{746,,os.urandom()} が望ましいです。

暗号論的に強い擬似乱数生成器に要求されることについては Wikipedia の記事 Cryptographically secure pseudorandom number generator (CSPRNG)@footnote{https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator} (日本語版: 暗号論的擬似乱数生成器@footnote{http://ja.wikipedia.org/wiki/%E6%9A%97%E5%8F%B7%E8%AB%96%E7%9A%84%E6%93%AC%E4%BC%BC%E4%B9%B1%E6%95%B0%E7%94%9F%E6%88%90%E5%99%A8}) を参照してください。


Added in version 3.3.

@end deffn

@geindex RAND_status() (ssl モジュール)
@anchor{library/ssl ssl RAND_status}@anchor{1c7e}
@deffn {の関数} ssl.RAND_status ()

SSL 擬似乱数生成器が十分なランダム性(randomness)を受け取っている時に @code{True} を、それ以外の場合は @cite{False} を返します。 @code{ssl.RAND_egd()} と @ref{39bc,,ssl.RAND_add()} を使って擬似乱数生成機にランダム性を加えることができます。
@end deffn

@geindex RAND_add() (ssl モジュール)
@anchor{library/ssl ssl RAND_add}@anchor{39bc}
@deffn {の関数} ssl.RAND_add (bytes, entropy, /)

Mix the given `bytes' into the SSL pseudo-random number generator.  The
parameter `entropy' (a float) is a lower bound on the entropy contained in
string (so you can always use @code{0.0}).  See 
@geindex RFC; RFC 1750
RFC 1750@footnote{https://datatracker.ietf.org/doc/html/rfc1750.html} for more
information on sources of entropy.


バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。

@end deffn

@node 証明書の取り扱い,定数<9>,乱数生成,関数、定数、例外
@anchor{library/ssl certificate-handling}@anchor{39bd}
@subsubsection 証明書の取り扱い


@c import ssl

@geindex cert_time_to_seconds() (ssl モジュール)
@anchor{library/ssl ssl cert_time_to_seconds}@anchor{106b}
@deffn {の関数} ssl.cert_time_to_seconds (cert_time)

@code{cert_time} として証明書内の "notBefore" や "notAfter" の @code{"%b %d %H:%M:%S %Y %Z"} strptime フォーマット (C locale) 日付を渡すと、エポックからの積算秒を返します。

例です。 :

@example
>>> import ssl
>>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
>>> timestamp
1515144883
>>> from datetime import datetime
>>> print(datetime.utcfromtimestamp(timestamp))
2018-01-05 09:34:43
@end example

"notBefore" や "notAfter" の日付には GMT を使わなければなりません(
@geindex RFC; RFC 5280
RFC 5280@footnote{https://datatracker.ietf.org/doc/html/rfc5280.html})。


バージョン 3.5 で変更: 入力文字列に指定された 'GMT' タイムゾーンを UTC として解釈するようになりました。以前はローカルタイムで解釈していました。また、整数を返すようになりました(入力に含まれる秒の端数を含まない)。

@end deffn

@geindex get_server_certificate() (ssl モジュール)
@anchor{library/ssl ssl get_server_certificate}@anchor{a3d}
@deffn {の関数} ssl.get_server_certificate (addr, ssl_version=PROTOCOL_TLS_CLIENT, ca_certs=None[, timeout])

Given the address @code{addr} of an SSL-protected server, as a (`hostname',
`port-number') pair, fetches the server's certificate, and returns it as a
PEM-encoded string.  If @code{ssl_version} is specified, uses that version of
the SSL protocol to attempt to connect to the server.  If `ca_certs' is
specified, it should be a file containing a list of root certificates, the
same format as used for the `cafile' parameter in
@ref{10ee,,SSLContext.load_verify_locations()}.  The call will attempt to validate the
server certificate against that set of root certificates, and will fail
if the validation attempt fails.  A timeout can be specified with the
@code{timeout} parameter.


バージョン 3.3 で変更: この関数はIPv6互換になりました。



バージョン 3.5 で変更: `ssl_version' のデフォルトが、最近のサーバへの最大限の互換性のために @ref{39be,,PROTOCOL_SSLv3} から @ref{39b3,,PROTOCOL_TLS} に変更されました。



バージョン 3.10 で変更: `timeout' 引数が追加されました。

@end deffn

@geindex DER_cert_to_PEM_cert() (ssl モジュール)
@anchor{library/ssl ssl DER_cert_to_PEM_cert}@anchor{39bf}
@deffn {の関数} ssl.DER_cert_to_PEM_cert (der_cert_bytes)

DERエンコードされたバイト列として与えられた証明書から、 PEMエンコードされたバージョンの同じ証明書を返します。
@end deffn

@geindex PEM_cert_to_DER_cert() (ssl モジュール)
@anchor{library/ssl ssl PEM_cert_to_DER_cert}@anchor{39c0}
@deffn {の関数} ssl.PEM_cert_to_DER_cert (pem_cert_string)

PEM 形式のASCII文字列として与えられた証明書から、同じ証明書をDERエンコードしたバイト列を返します。
@end deffn

@geindex get_default_verify_paths() (ssl モジュール)
@anchor{library/ssl ssl get_default_verify_paths}@anchor{11ac}
@deffn {の関数} ssl.get_default_verify_paths ()

OpenSSL デフォルトの cafile, capath を指すパスを名前付きタプルで返します。パスは @ref{11ad,,SSLContext.set_default_verify_paths()} で使われるものと同じです。戻り値は @ref{85e,,named tuple} @code{DefaultVerifyPaths} です:


@itemize *

@item 
@code{cafile} - cafile の解決済みパス、またはファイルが存在しない場合は @code{None}

@item 
@code{capath} - capath の解決済みパス、またはディレクトリが存在しない場合は @code{None}

@item 
@code{openssl_cafile_env} - cafile を指す OpenSSL の環境変数

@item 
@code{openssl_cafile} - OpenSSL にハードコードされた cafile のパス

@item 
@code{openssl_capath_env} - capath を指す OpenSSL の環境変数

@item 
@code{openssl_capath} - OpenSSL にハードコードされた capath のパス
@end itemize


Added in version 3.4.

@end deffn

@geindex enum_certificates() (ssl モジュール)
@anchor{library/ssl ssl enum_certificates}@anchor{11b7}
@deffn {の関数} ssl.enum_certificates (store_name)

Windows のシステム証明書ストアより証明書を抽出します。 `store_name' は @code{CA}, @code{ROOT}, @code{MY} のうちどれか一つでしょう。Windows は追加の証明書ストアを提供しているかもしれません。

この関数はタプル (cert_bytes, encoding_type, trust) のリストで返します。encoding_type は cert_bytes のエンコーディングを表します。X.509 ASN.1 に対する @code{x509_asn} か PKCS#7 ASN.1 データに対する @code{pkcs_7_asn} のいずれかです。trust は、証明書の目的を、OIDS を内容に持つ set として表すか、または証明書がすべての目的で信頼できるならば @code{True} です。

以下はプログラム例です:

@example
>>> ssl.enum_certificates("CA")
[(b'data...', 'x509_asn', @{'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'@}),
 (b'data...', 'x509_asn', True)]
@end example

@ref{213f,,Availability}: Windows.


Added in version 3.4.

@end deffn

@geindex enum_crls() (ssl モジュール)
@anchor{library/ssl ssl enum_crls}@anchor{11b8}
@deffn {の関数} ssl.enum_crls (store_name)

Windows のシステム証明書ストアより CRLs を抽出します。 `store_name' は @code{CA}, @code{ROOT}, @code{MY} のうちどれか一つでしょう。Windows は追加の証明書ストアを提供しているかもしれません。

この関数はタプル (cert_bytes, encoding_type, trust) のリストで返します。encoding_type は cert_bytes のエンコーディングを表します。X.509 ASN.1 に対する @code{x509_asn} か PKCS#7 ASN.1 データに対する @code{pkcs_7_asn} のいずれかです。

@ref{213f,,Availability}: Windows.


Added in version 3.4.

@end deffn

@node 定数<9>,,証明書の取り扱い,関数、定数、例外
@anchor{library/ssl constants}@anchor{39c1}
@subsubsection 定数


@quotation

すべての定数が @ref{edb,,enum.IntEnum} コレクションまたは @ref{e9a,,enum.IntFlag} コレクションになりました。


Added in version 3.6.

@end quotation

@geindex CERT_NONE (ssl モジュール)
@anchor{library/ssl ssl CERT_NONE}@anchor{39c2}
@deffn {データ} ssl.CERT_NONE

Possible value for @ref{39b0,,SSLContext.verify_mode}.
Except for @ref{a72,,PROTOCOL_TLS_CLIENT},
it is the default mode.  With client-side sockets, just about any
cert is accepted.  Validation errors, such as untrusted or expired cert,
are ignored and do not abort the TLS/SSL handshake.

In server mode, no certificate is requested from the client, so the client
does not send any for client cert authentication.

このドキュメントの下の方の、 @ref{3895,,セキュリティで考慮すべき点} に関する議論を参照してください。
@end deffn

@geindex CERT_OPTIONAL (ssl モジュール)
@anchor{library/ssl ssl CERT_OPTIONAL}@anchor{39c3}
@deffn {データ} ssl.CERT_OPTIONAL

Possible value for @ref{39b0,,SSLContext.verify_mode}.
In client mode, @ref{39c3,,CERT_OPTIONAL}
has the same meaning as @ref{39b1,,CERT_REQUIRED}. It is recommended to
use @ref{39b1,,CERT_REQUIRED} for client-side sockets instead.

In server mode, a client certificate request is sent to the client.  The
client may either ignore the request or send a certificate in order
perform TLS client cert authentication.  If the client chooses to send
a certificate, it is verified.  Any verification error immediately aborts
the TLS handshake.

Use of this setting requires a valid set of CA certificates to
be passed to @ref{10ee,,SSLContext.load_verify_locations()}.
@end deffn

@geindex CERT_REQUIRED (ssl モジュール)
@anchor{library/ssl ssl CERT_REQUIRED}@anchor{39b1}
@deffn {データ} ssl.CERT_REQUIRED

Possible value for @ref{39b0,,SSLContext.verify_mode}.
In this mode, certificates are
required from the other side of the socket connection; an @ref{1491,,SSLError}
will be raised if no certificate is provided, or if its validation fails.
This mode is `not' sufficient to verify a certificate in client mode as
it does not match hostnames.  @ref{39c4,,check_hostname} must be
enabled as well to verify the authenticity of a cert.
@ref{a72,,PROTOCOL_TLS_CLIENT} uses @ref{39b1,,CERT_REQUIRED} and
enables @ref{39c4,,check_hostname} by default.

With server socket, this mode provides mandatory TLS client cert
authentication.  A client certificate request is sent to the client and
the client must provide a valid and trusted certificate.

Use of this setting requires a valid set of CA certificates to
be passed to @ref{10ee,,SSLContext.load_verify_locations()}.
@end deffn

@geindex VerifyMode (ssl のクラス)
@anchor{library/ssl ssl VerifyMode}@anchor{39c5}
@deffn {クラス} ssl.VerifyMode

CERT_* 定数の @ref{edb,,enum.IntEnum} コレクションです。


Added in version 3.6.

@end deffn

@geindex VERIFY_DEFAULT (ssl モジュール)
@anchor{library/ssl ssl VERIFY_DEFAULT}@anchor{11b1}
@deffn {データ} ssl.VERIFY_DEFAULT

@ref{11b0,,SSLContext.verify_flags} に渡せる値です。このモードでは、証明書失効リスト(CRLs)はチェックされません。デフォルトでは OpenSSL は CRLs を必要ともしませんし検証にも使いません。


Added in version 3.4.

@end deffn

@geindex VERIFY_CRL_CHECK_LEAF (ssl モジュール)
@anchor{library/ssl ssl VERIFY_CRL_CHECK_LEAF}@anchor{11b2}
@deffn {データ} ssl.VERIFY_CRL_CHECK_LEAF

@ref{11b0,,SSLContext.verify_flags} に渡せる値です。このモードでは、接続先の証明書のみがチェックされ、仲介の CA 証明書はチェックされません。接続先証明書の発行者(その CA の直接の祖先)によって署名された妥当な CRL が必要です。 @ref{10ee,,SSLContext.load_verify_locations} で相応しい CRL をロードしていなければ、検証は失敗します。


Added in version 3.4.

@end deffn

@geindex VERIFY_CRL_CHECK_CHAIN (ssl モジュール)
@anchor{library/ssl ssl VERIFY_CRL_CHECK_CHAIN}@anchor{11b3}
@deffn {データ} ssl.VERIFY_CRL_CHECK_CHAIN

@ref{11b0,,SSLContext.verify_flags} に渡せる値です。このモードでは、接続先の証明書チェイン内のすべての証明書についての CRLs がチェックされます。


Added in version 3.4.

@end deffn

@geindex VERIFY_X509_STRICT (ssl モジュール)
@anchor{library/ssl ssl VERIFY_X509_STRICT}@anchor{551}
@deffn {データ} ssl.VERIFY_X509_STRICT

@ref{11b0,,SSLContext.verify_flags} に渡せる値で、壊れた X.509 証明書に対するワークアラウンドを無効にします。


Added in version 3.4.

@end deffn

@geindex VERIFY_ALLOW_PROXY_CERTS (ssl モジュール)
@anchor{library/ssl ssl VERIFY_ALLOW_PROXY_CERTS}@anchor{1c95}
@deffn {データ} ssl.VERIFY_ALLOW_PROXY_CERTS

Possible value for @ref{11b0,,SSLContext.verify_flags} to enables proxy
certificate verification.


Added in version 3.10.

@end deffn

@geindex VERIFY_X509_TRUSTED_FIRST (ssl モジュール)
@anchor{library/ssl ssl VERIFY_X509_TRUSTED_FIRST}@anchor{39c6}
@deffn {データ} ssl.VERIFY_X509_TRUSTED_FIRST

@ref{11b0,,SSLContext.verify_flags} に渡せる値です。OpenSSL に対し、証明書検証のために信頼チェインを構築する際、信頼できる証明書を選ぶように指示します。これはデフォルトで有効にされています。


Added in version 3.4.4.

@end deffn

@geindex VERIFY_X509_PARTIAL_CHAIN (ssl モジュール)
@anchor{library/ssl ssl VERIFY_X509_PARTIAL_CHAIN}@anchor{481}
@deffn {データ} ssl.VERIFY_X509_PARTIAL_CHAIN

Possible value for @ref{11b0,,SSLContext.verify_flags}. It instructs OpenSSL to
accept intermediate CAs in the trust store to be treated as trust-anchors,
in the same way as the self-signed root CA certificates. This makes it
possible to trust certificates issued by an intermediate CA without having
to trust its ancestor root CA.


Added in version 3.10.

@end deffn

@geindex VerifyFlags (ssl のクラス)
@anchor{library/ssl ssl VerifyFlags}@anchor{39c7}
@deffn {クラス} ssl.VerifyFlags

VERIFY_* 定数の @ref{e9a,,enum.IntFlag} コレクションです。


Added in version 3.6.

@end deffn

@geindex PROTOCOL_TLS (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_TLS}@anchor{39b3}
@deffn {データ} ssl.PROTOCOL_TLS

クライアントとサーバの両方がサポートするプロトコルバージョンのうち、最も大きなものを選択します。名前に反して、このオプションは "SSL" と "TLS" プロトコルのいずれも選択できます。


Added in version 3.6.



バージョン 3.10 で非推奨: TLS clients and servers require different default settings for secure
communication. The generic TLS protocol constant is deprecated in
favor of @ref{a72,,PROTOCOL_TLS_CLIENT} and @ref{a73,,PROTOCOL_TLS_SERVER}.

@end deffn

@geindex PROTOCOL_TLS_CLIENT (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_TLS_CLIENT}@anchor{a72}
@deffn {データ} ssl.PROTOCOL_TLS_CLIENT

Auto-negotiate the highest protocol version that both the client and
server support, and configure the context client-side connections. The
protocol enables @ref{39b1,,CERT_REQUIRED} and
@ref{39c4,,check_hostname} by default.


Added in version 3.6.

@end deffn

@geindex PROTOCOL_TLS_SERVER (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_TLS_SERVER}@anchor{a73}
@deffn {データ} ssl.PROTOCOL_TLS_SERVER

Auto-negotiate the highest protocol version that both the client and
server support, and configure the context server-side connections.


Added in version 3.6.

@end deffn

@geindex PROTOCOL_SSLv23 (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_SSLv23}@anchor{39c8}
@deffn {データ} ssl.PROTOCOL_SSLv23

@ref{39b3,,PROTOCOL_TLS} のエイリアスです。


バージョン 3.6 で非推奨: 代わりに @ref{39b3,,PROTOCOL_TLS} を使用してください。

@end deffn

@geindex PROTOCOL_SSLv3 (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_SSLv3}@anchor{39be}
@deffn {データ} ssl.PROTOCOL_SSLv3

チャンネル暗号化プロトコルとしてSSLバージョン3を選択します。

このプロトコルは、 OpenSSL が @code{no-ssl3} オプションをつけてコンパイルされている場合には利用できません。

@cartouche
@quotation 警告 
SSL version 3 は非セキュアです。このプロトコルは強く非推奨です。
@end quotation
@end cartouche


バージョン 3.6 で非推奨: OpenSSL has deprecated all version specific protocols. Use the default
protocol @ref{a73,,PROTOCOL_TLS_SERVER} or @ref{a72,,PROTOCOL_TLS_CLIENT}
with @ref{a70,,SSLContext.minimum_version} and
@ref{a71,,SSLContext.maximum_version} instead.

@end deffn

@geindex PROTOCOL_TLSv1 (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_TLSv1}@anchor{39c9}
@deffn {データ} ssl.PROTOCOL_TLSv1

チャンネル暗号化プロトコルとしてTLSバージョン1.0を選択します。


バージョン 3.6 で非推奨: OpenSSL has deprecated all version specific protocols.

@end deffn

@geindex PROTOCOL_TLSv1_1 (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_TLSv1_1}@anchor{11aa}
@deffn {データ} ssl.PROTOCOL_TLSv1_1

チャンネル暗号化プロトコルとしてTLSバージョン1.1を選択します。 openssl version 1.0.1+ のみで利用可能です。


Added in version 3.4.



バージョン 3.6 で非推奨: OpenSSL has deprecated all version specific protocols.

@end deffn

@geindex PROTOCOL_TLSv1_2 (ssl モジュール)
@anchor{library/ssl ssl PROTOCOL_TLSv1_2}@anchor{11ab}
@deffn {データ} ssl.PROTOCOL_TLSv1_2

チャンネル暗号化プロトコルとしてTLSバージョン 1.2 を選択します。 openssl version 1.0.1+ のみで利用可能です。


Added in version 3.4.



バージョン 3.6 で非推奨: OpenSSL has deprecated all version specific protocols.

@end deffn

@geindex OP_ALL (ssl モジュール)
@anchor{library/ssl ssl OP_ALL}@anchor{39ca}
@deffn {データ} ssl.OP_ALL

相手にする SSL 実装のさまざまなバグを回避するためのワークアラウンドを有効にします。このオプションはデフォルトで有効です。これを有効にする場合 OpenSSL 用の同じ意味のフラグ @code{SSL_OP_ALL} をセットする必要はありません。


Added in version 3.2.

@end deffn

@geindex OP_NO_SSLv2 (ssl モジュール)
@anchor{library/ssl ssl OP_NO_SSLv2}@anchor{a3a}
@deffn {データ} ssl.OP_NO_SSLv2

SSLv2 接続が行われないようにします。このオプションは @ref{39b3,,PROTOCOL_TLS} と組み合わされている場合にのみ適用されます。ピアがプロトコルバージョンとして SSLv2 を選択しないようにします。


Added in version 3.2.



バージョン 3.6 で非推奨: SSLv2 は非推奨です

@end deffn

@geindex OP_NO_SSLv3 (ssl モジュール)
@anchor{library/ssl ssl OP_NO_SSLv3}@anchor{a3b}
@deffn {データ} ssl.OP_NO_SSLv3

SSLv3 接続が行われないようにします。このオプションは @ref{39b3,,PROTOCOL_TLS} と組み合わされている場合にのみ適用されます。ピアがプロトコルバージョンとして SSLv3 を選択しないようにします。


Added in version 3.2.



バージョン 3.6 で非推奨: SSLv3 は非推奨です

@end deffn

@geindex OP_NO_TLSv1 (ssl モジュール)
@anchor{library/ssl ssl OP_NO_TLSv1}@anchor{39cb}
@deffn {データ} ssl.OP_NO_TLSv1

TLSv1 接続が行われないようにします。このオプションは @ref{39b3,,PROTOCOL_TLS} と組み合わされている場合にのみ適用されます。ピアがプロトコルバージョンとして TLSv1 を選択しないようにします。


Added in version 3.2.



バージョン 3.7 で非推奨: The option is deprecated since OpenSSL 1.1.0, use the new
@ref{a70,,SSLContext.minimum_version} and
@ref{a71,,SSLContext.maximum_version} instead.

@end deffn

@geindex OP_NO_TLSv1_1 (ssl モジュール)
@anchor{library/ssl ssl OP_NO_TLSv1_1}@anchor{39cc}
@deffn {データ} ssl.OP_NO_TLSv1_1

TLSv1.1 接続が行われないようにします。このオプションは @ref{39b3,,PROTOCOL_TLS} と組み合わされている場合にのみ適用されます。ピアがプロトコルバージョンとして TLSv1.1 を選択しないようにします。openssl バージョン 1.0.1 以降でのみ利用できます。


Added in version 3.4.



バージョン 3.7 で非推奨: The option is deprecated since OpenSSL 1.1.0.

@end deffn

@geindex OP_NO_TLSv1_2 (ssl モジュール)
@anchor{library/ssl ssl OP_NO_TLSv1_2}@anchor{39cd}
@deffn {データ} ssl.OP_NO_TLSv1_2

TLSv1.2 接続が行われないようにします。このオプションは @ref{39b3,,PROTOCOL_TLS} と組み合わされている場合にのみ適用されます。ピアがプロトコルバージョンとして TLSv1.2 を選択しないようにします。openssl バージョン 1.0.1 以降でのみ利用できます。


Added in version 3.4.



バージョン 3.7 で非推奨: The option is deprecated since OpenSSL 1.1.0.

@end deffn

@geindex OP_NO_TLSv1_3 (ssl モジュール)
@anchor{library/ssl ssl OP_NO_TLSv1_3}@anchor{1c5b}
@deffn {データ} ssl.OP_NO_TLSv1_3

Prevents a TLSv1.3 connection. This option is only applicable in conjunction
with @ref{39b3,,PROTOCOL_TLS}. It prevents the peers from choosing TLSv1.3 as
the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later.
When Python has been compiled against an older version of OpenSSL, the
flag defaults to `0'.


Added in version 3.6.3.



バージョン 3.7 で非推奨: The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15 and
3.6.3 for backwards compatibility with OpenSSL 1.0.2.

@end deffn

@geindex OP_NO_RENEGOTIATION (ssl モジュール)
@anchor{library/ssl ssl OP_NO_RENEGOTIATION}@anchor{39ce}
@deffn {データ} ssl.OP_NO_RENEGOTIATION

Disable all renegotiation in TLSv1.2 and earlier. Do not send
HelloRequest messages, and ignore renegotiation requests via ClientHello.

このオプションは OpenSSL 1.1.0h 以降のみで使用できます。


Added in version 3.7.

@end deffn

@geindex OP_CIPHER_SERVER_PREFERENCE (ssl モジュール)
@anchor{library/ssl ssl OP_CIPHER_SERVER_PREFERENCE}@anchor{1361}
@deffn {データ} ssl.OP_CIPHER_SERVER_PREFERENCE

暗号の優先順位として、クライアントのものではなくサーバのものを使います。このオプションはクライアントソケットと SSLv2 のサーバソケットでは効果はありません。


Added in version 3.3.

@end deffn

@geindex OP_SINGLE_DH_USE (ssl モジュール)
@anchor{library/ssl ssl OP_SINGLE_DH_USE}@anchor{39cf}
@deffn {データ} ssl.OP_SINGLE_DH_USE

Prevents reuse of the same DH key for distinct SSL sessions.  This
improves forward secrecy but requires more computational resources.
This option only applies to server sockets.


Added in version 3.3.

@end deffn

@geindex OP_SINGLE_ECDH_USE (ssl モジュール)
@anchor{library/ssl ssl OP_SINGLE_ECDH_USE}@anchor{39d0}
@deffn {データ} ssl.OP_SINGLE_ECDH_USE

Prevents reuse of the same ECDH key for distinct SSL sessions.  This
improves forward secrecy but requires more computational resources.
This option only applies to server sockets.


Added in version 3.3.

@end deffn

@geindex OP_ENABLE_MIDDLEBOX_COMPAT (ssl モジュール)
@anchor{library/ssl ssl OP_ENABLE_MIDDLEBOX_COMPAT}@anchor{39d1}
@deffn {データ} ssl.OP_ENABLE_MIDDLEBOX_COMPAT

Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make
a TLS 1.3 connection look more like a TLS 1.2 connection.

このオプションは OpenSSL 1.1.1 以降のみで使用できます。


Added in version 3.8.

@end deffn

@geindex OP_NO_COMPRESSION (ssl モジュール)
@anchor{library/ssl ssl OP_NO_COMPRESSION}@anchor{135e}
@deffn {データ} ssl.OP_NO_COMPRESSION

SSL チャネルでの圧縮を無効にします。これはアプリケーションのプロトコルが自身の圧縮方法をサポートする場合に有用です。


Added in version 3.3.

@end deffn

@geindex Options (ssl のクラス)
@anchor{library/ssl ssl Options}@anchor{39d2}
@deffn {クラス} ssl.Options

OP_* 定数の @ref{e9a,,enum.IntFlag} コレクションです。
@end deffn

@geindex OP_NO_TICKET (ssl モジュール)
@anchor{library/ssl ssl OP_NO_TICKET}@anchor{39d3}
@deffn {データ} ssl.OP_NO_TICKET

クライアントサイドがセッションチケットをリクエストしないようにします。


Added in version 3.6.

@end deffn

@geindex OP_IGNORE_UNEXPECTED_EOF (ssl モジュール)
@anchor{library/ssl ssl OP_IGNORE_UNEXPECTED_EOF}@anchor{a38}
@deffn {データ} ssl.OP_IGNORE_UNEXPECTED_EOF

Ignore unexpected shutdown of TLS connections.

このオプションは OpenSSL 3.0.0以降のみで使用できます。


Added in version 3.10.

@end deffn

@geindex OP_ENABLE_KTLS (ssl モジュール)
@anchor{library/ssl ssl OP_ENABLE_KTLS}@anchor{1b0f}
@deffn {データ} ssl.OP_ENABLE_KTLS

Enable the use of the kernel TLS. To benefit from the feature, OpenSSL must
have been compiled with support for it, and the negotiated cipher suites and
extensions must be supported by it (a list of supported ones may vary by
platform and kernel version).

Note that with enabled kernel TLS some cryptographic operations are
performed by the kernel directly and not via any available OpenSSL
Providers. This might be undesirable if, for example, the application
requires all cryptographic operations to be performed by the FIPS provider.

このオプションは OpenSSL 3.0.0以降のみで使用できます。


Added in version 3.12.

@end deffn

@geindex OP_LEGACY_SERVER_CONNECT (ssl モジュール)
@anchor{library/ssl ssl OP_LEGACY_SERVER_CONNECT}@anchor{1af1}
@deffn {データ} ssl.OP_LEGACY_SERVER_CONNECT

Allow legacy insecure renegotiation between OpenSSL and unpatched servers
only.


Added in version 3.12.

@end deffn

@geindex HAS_ALPN (ssl モジュール)
@anchor{library/ssl ssl HAS_ALPN}@anchor{1066}
@deffn {データ} ssl.HAS_ALPN

OpenSSL ライブラリが、組み込みで 
@geindex RFC; RFC 7301
RFC 7301@footnote{https://datatracker.ietf.org/doc/html/rfc7301.html} で記述されている `Application-Layer Protocol Negotiation' TLS 拡張をサポートしているかどうか。


Added in version 3.5.

@end deffn

@geindex HAS_NEVER_CHECK_COMMON_NAME (ssl モジュール)
@anchor{library/ssl ssl HAS_NEVER_CHECK_COMMON_NAME}@anchor{39d4}
@deffn {データ} ssl.HAS_NEVER_CHECK_COMMON_NAME

Whether the OpenSSL library has built-in support not checking subject
common name and @ref{d76,,SSLContext.hostname_checks_common_name} is
writeable.


Added in version 3.7.

@end deffn

@geindex HAS_ECDH (ssl モジュール)
@anchor{library/ssl ssl HAS_ECDH}@anchor{39d5}
@deffn {データ} ssl.HAS_ECDH

OpenSSL ライブラリが、組み込みの楕円曲線ディフィー・ヘルマン鍵共有をサポートしているかどうか。これは、ディストリビュータが明示的に無効にしていない限りは、真であるはずです。


Added in version 3.3.

@end deffn

@geindex HAS_SNI (ssl モジュール)
@anchor{library/ssl ssl HAS_SNI}@anchor{39d6}
@deffn {データ} ssl.HAS_SNI

OpenSSL ライブラリが、組み込みで (
@geindex RFC; RFC 6066
RFC 6066@footnote{https://datatracker.ietf.org/doc/html/rfc6066.html} で記述されている) `Server Name Indication' 拡張をサポートしているかどうか。


Added in version 3.2.

@end deffn

@geindex HAS_NPN (ssl モジュール)
@anchor{library/ssl ssl HAS_NPN}@anchor{39d7}
@deffn {データ} ssl.HAS_NPN

OpenSSL ライブラリが、組み込みで、Application Layer Protocol Negotiation@footnote{https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation} で記述されている `Next Protocol Negotiation' をサポートしているかどうか。 true であれば、サポートしたいプロトコルを @ref{358,,SSLContext.set_npn_protocols()} メソッドで提示することができます。


Added in version 3.3.

@end deffn

@geindex HAS_SSLv2 (ssl モジュール)
@anchor{library/ssl ssl HAS_SSLv2}@anchor{39d8}
@deffn {データ} ssl.HAS_SSLv2

OpenSSL ライブラリが、組み込みで SSL 2.0 プロトコルをサポートしているかどうか。


Added in version 3.7.

@end deffn

@geindex HAS_SSLv3 (ssl モジュール)
@anchor{library/ssl ssl HAS_SSLv3}@anchor{39d9}
@deffn {データ} ssl.HAS_SSLv3

OpenSSL ライブラリが、組み込みで SSL 3.0 プロトコルをサポートしているかどうか。


Added in version 3.7.

@end deffn

@geindex HAS_TLSv1 (ssl モジュール)
@anchor{library/ssl ssl HAS_TLSv1}@anchor{39da}
@deffn {データ} ssl.HAS_TLSv1

OpenSSL ライブラリが、組み込みで TLS 1.0 プロトコルをサポートしているかどうか。


Added in version 3.7.

@end deffn

@geindex HAS_TLSv1_1 (ssl モジュール)
@anchor{library/ssl ssl HAS_TLSv1_1}@anchor{d7c}
@deffn {データ} ssl.HAS_TLSv1_1

OpenSSL ライブラリが、組み込みで TLS 1.1 プロトコルをサポートしているかどうか。


Added in version 3.7.

@end deffn

@geindex HAS_TLSv1_2 (ssl モジュール)
@anchor{library/ssl ssl HAS_TLSv1_2}@anchor{39db}
@deffn {データ} ssl.HAS_TLSv1_2

OpenSSL ライブラリが、組み込みで TLS 1.2 プロトコルをサポートしているかどうか。


Added in version 3.7.

@end deffn

@geindex HAS_TLSv1_3 (ssl モジュール)
@anchor{library/ssl ssl HAS_TLSv1_3}@anchor{39dc}
@deffn {データ} ssl.HAS_TLSv1_3

OpenSSL ライブラリが、組み込みで TLS 1.3 プロトコルをサポートしているかどうか。


Added in version 3.7.

@end deffn

@geindex HAS_PSK (ssl モジュール)
@anchor{library/ssl ssl HAS_PSK}@anchor{39dd}
@deffn {データ} ssl.HAS_PSK

Whether the OpenSSL library has built-in support for TLS-PSK.


Added in version 3.13.

@end deffn

@geindex HAS_PHA (ssl モジュール)
@anchor{library/ssl ssl HAS_PHA}@anchor{286}
@deffn {データ} ssl.HAS_PHA

Whether the OpenSSL library has built-in support for TLS-PHA.


Added in version 3.14.

@end deffn

@geindex CHANNEL_BINDING_TYPES (ssl モジュール)
@anchor{library/ssl ssl CHANNEL_BINDING_TYPES}@anchor{39de}
@deffn {データ} ssl.CHANNEL_BINDING_TYPES

サポートされている TLS のチャネルバインディングのタイプのリスト。リスト内の文字列は @ref{135c,,SSLSocket.get_channel_binding()} の引数に渡せます。


Added in version 3.3.

@end deffn

@geindex OPENSSL_VERSION (ssl モジュール)
@anchor{library/ssl ssl OPENSSL_VERSION}@anchor{1437}
@deffn {データ} ssl.OPENSSL_VERSION

インタプリタによってロードされた OpenSSL ライブラリのバージョン文字列:

@example
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2k  26 Jan 2017'
@end example


Added in version 3.2.

@end deffn

@geindex OPENSSL_VERSION_INFO (ssl モジュール)
@anchor{library/ssl ssl OPENSSL_VERSION_INFO}@anchor{1438}
@deffn {データ} ssl.OPENSSL_VERSION_INFO

OpenSSL ライブラリのバージョン情報を表す5つの整数のタプル:

@example
>>> ssl.OPENSSL_VERSION_INFO
(1, 0, 2, 11, 15)
@end example


Added in version 3.2.

@end deffn

@geindex OPENSSL_VERSION_NUMBER (ssl モジュール)
@anchor{library/ssl ssl OPENSSL_VERSION_NUMBER}@anchor{1439}
@deffn {データ} ssl.OPENSSL_VERSION_NUMBER

1つの整数の形式の、 OpenSSL ライブラリの生のバージョン番号:

@example
>>> ssl.OPENSSL_VERSION_NUMBER
268443839
>>> hex(ssl.OPENSSL_VERSION_NUMBER)
'0x100020bf'
@end example


Added in version 3.2.

@end deffn

@geindex ALERT_DESCRIPTION_HANDSHAKE_FAILURE (ssl モジュール)
@geindex ALERT_DESCRIPTION_INTERNAL_ERROR (ssl モジュール)
@anchor{library/ssl ssl ALERT_DESCRIPTION_HANDSHAKE_FAILURE}@anchor{39df}
@deffn {データ} ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE
@anchor{library/ssl ssl ALERT_DESCRIPTION_INTERNAL_ERROR}@anchor{39e0}
@deffnx {データ} ssl.ALERT_DESCRIPTION_INTERNAL_ERROR

@deffnx {データ} ALERT_DESCRIPTION_*

@geindex RFC; RFC 5246
RFC 5246@footnote{https://datatracker.ietf.org/doc/html/rfc5246.html} その他からのアラートの種類です。 IANA TLS Alert Registry@footnote{https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6} にはこのリストとその意味が定義された RFC へのリファレンスが含まれています。

@ref{11b9,,SSLContext.set_servername_callback()} でのコールバック関数の戻り値として使われます。


Added in version 3.4.

@end deffn

@geindex AlertDescription (ssl のクラス)
@anchor{library/ssl ssl AlertDescription}@anchor{39e1}
@deffn {クラス} ssl.AlertDescription

ALERT_DESCRIPTION_* 定数の @ref{edb,,enum.IntEnum} コレクションです。


Added in version 3.6.

@end deffn

@geindex Purpose.SERVER_AUTH (ssl モジュール)
@anchor{library/ssl ssl Purpose SERVER_AUTH}@anchor{11b5}
@deffn {データ} Purpose.SERVER_AUTH

@ref{480,,create_default_context()} と @ref{11b4,,SSLContext.load_default_certs()} に渡すオプションです。この値はコンテキストが web サーバの認証に使われることを示します (ですので、クライアントサイドのソケットを作るのに使うことになるでしょう)。


Added in version 3.4.

@end deffn

@geindex Purpose.CLIENT_AUTH (ssl モジュール)
@anchor{library/ssl ssl Purpose CLIENT_AUTH}@anchor{11b6}
@deffn {データ} Purpose.CLIENT_AUTH

@ref{480,,create_default_context()} と @ref{11b4,,SSLContext.load_default_certs()} に渡すオプションです。この値はコンテキストが web クライアントの認証に使われることを示します (ですので、サーバサイドのソケットを作るのに使うことになるでしょう)。


Added in version 3.4.

@end deffn

@geindex SSLErrorNumber (ssl のクラス)
@anchor{library/ssl ssl SSLErrorNumber}@anchor{39e2}
@deffn {クラス} ssl.SSLErrorNumber

SSL_ERROR_* 定数の @ref{edb,,enum.IntEnum} コレクションです。


Added in version 3.6.

@end deffn

@geindex TLSVersion (ssl のクラス)
@anchor{library/ssl ssl TLSVersion}@anchor{39e3}
@deffn {クラス} ssl.TLSVersion

@ref{edb,,enum.IntEnum} collection of SSL and TLS versions for
@ref{a71,,SSLContext.maximum_version} and @ref{a70,,SSLContext.minimum_version}.


Added in version 3.7.

@end deffn

@geindex MINIMUM_SUPPORTED (ssl.TLSVersion の属性)
@anchor{library/ssl ssl TLSVersion MINIMUM_SUPPORTED}@anchor{39e4}
@deffn {の属性} TLSVersion.MINIMUM_SUPPORTED
@end deffn

@geindex MAXIMUM_SUPPORTED (ssl.TLSVersion の属性)
@anchor{library/ssl ssl TLSVersion MAXIMUM_SUPPORTED}@anchor{39e5}
@deffn {の属性} TLSVersion.MAXIMUM_SUPPORTED

The minimum or maximum supported SSL or TLS version. These are magic
constants. Their values don't reflect the lowest and highest available
TLS/SSL versions.
@end deffn

@geindex SSLv3 (ssl.TLSVersion の属性)
@anchor{library/ssl ssl TLSVersion SSLv3}@anchor{39e6}
@deffn {の属性} TLSVersion.SSLv3
@end deffn

@geindex TLSv1 (ssl.TLSVersion の属性)
@anchor{library/ssl ssl TLSVersion TLSv1}@anchor{39e7}
@deffn {の属性} TLSVersion.TLSv1
@end deffn

@geindex TLSv1_1 (ssl.TLSVersion の属性)
@anchor{library/ssl ssl TLSVersion TLSv1_1}@anchor{39e8}
@deffn {の属性} TLSVersion.TLSv1_1
@end deffn

@geindex TLSv1_2 (ssl.TLSVersion の属性)
@anchor{library/ssl ssl TLSVersion TLSv1_2}@anchor{39e9}
@deffn {の属性} TLSVersion.TLSv1_2
@end deffn

@geindex TLSv1_3 (ssl.TLSVersion の属性)
@anchor{library/ssl ssl TLSVersion TLSv1_3}@anchor{39ea}
@deffn {の属性} TLSVersion.TLSv1_3

SSL 3.0 to TLS 1.3.


バージョン 3.10 で非推奨: All @ref{39e3,,TLSVersion} members except @ref{39e9,,TLSVersion.TLSv1_2} and
@ref{39ea,,TLSVersion.TLSv1_3} are deprecated.

@end deffn

@node SSL ソケット,SSL コンテキスト,関数、定数、例外,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl ssl-sockets}@anchor{39eb}
@subsubsection SSL ソケット


@geindex SSLSocket (ssl のクラス)
@anchor{library/ssl ssl SSLSocket}@anchor{ae7}
@deffn {クラス} ssl.SSLSocket (socket.socket)

SSL ソケットは @ref{3991,,socket オブジェクト} の以下のメソッドを提供します:


@itemize -

@item 
@ref{fa2,,accept()}

@item 
@ref{12d7,,bind()}

@item 
@ref{f3f,,close()}

@item 
@ref{fa3,,connect()}

@item 
@ref{1435,,detach()}

@item 
@ref{399f,,fileno()}

@item 
@ref{38d9,,getpeername()}, @ref{284,,getsockname()}

@item 
@ref{ed0,,getsockopt()}, @ref{ed1,,setsockopt()}

@item 
@ref{39a0,,gettimeout()}, @ref{3951,,settimeout()},
@ref{303c,,setblocking()}

@item 
@ref{105e,,listen()}

@item 
@ref{13b7,,makefile()}

@item 
@ref{fa4,,recv()}, @ref{1535,,recv_into()}
(but passing a non-zero @code{flags} argument is not allowed)

@item 
@ref{fa7,,send()}, @ref{fa8,,sendall()} (with
the same limitation)

@item 
@ref{105d,,sendfile()} (but @ref{d05,,os.sendfile} will be used
for plain-text sockets only, else @ref{fa7,,send()} will be used)

@item 
@ref{398e,,shutdown()}
@end itemize

SSL(およびTLS)プロトコルは TCP の上に独自の枠組みを持っているので、SSLソケットの抽象化は、いくつかの点で通常の OSレベルのソケットの仕様から逸脱することがあります。特に @ref{39b6,,ノンブロッキングソケットについての注釈} を参照してください。

@ref{ae7,,SSLSocket} のインスタンスは @ref{748,,SSLContext.wrap_socket()} メソッドを使用して作成されなければなりません。


バージョン 3.5 で変更: @code{sendfile()} メソッドが追加されました。



バージョン 3.5 で変更: @code{shutdown()} は、バイトが送受信されるたびにソケットのタイムアウトをリセットしません。ソケットのタイムアウトは、シャットダウンの最大合計時間になりました。



バージョン 3.6 で非推奨: @ref{ae7,,SSLSocket} インスタンスを直接作成することは非推奨です。ソケットをラップするために @ref{748,,SSLContext.wrap_socket()} を使用してください。



バージョン 3.7 で変更: @ref{ae7,,SSLSocket} instances must to created with
@ref{748,,wrap_socket()}. In earlier versions, it was possible
to create instances directly. This was never documented or officially
supported.



バージョン 3.10 で変更: Python now uses @code{SSL_read_ex} and @code{SSL_write_ex} internally. The
functions support reading and writing of data larger than 2 GB. Writing
zero-length data no longer fails with a protocol violation error.

@end deffn

SSL ソケットには、以下に示す追加のメソッドと属性もあります:

@geindex read() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket read}@anchor{106e}
@deffn {メソッド} SSLSocket.read (len=1024, buffer=None)

SSL ソケットからデータの `len' バイトまでを読み出し、読み出した結果を @code{bytes} インスタンスで返します。 `buffer' を指定すると、結果は代わりに buffer に読み込まれ、読み込んだバイト数を返します。

ソケットが @ref{39b6,,non-blocking} で読み出しがブロックすると、 @ref{1069,,SSLWantReadError} もしくは @ref{106a,,SSLWantWriteError} が送出されます。

再ネゴシエーションがいつでも可能なので、 @ref{106e,,read()}  の呼び出しは書き込み操作も引き起こしえます。


バージョン 3.5 で変更: ソケットのタイムアウトは、バイトが送受信されるたびにリセットされなくなりました。ソケットのタイムアウトは、最大 `len' バイトを読むのにかかる最大合計時間になりました。



バージョン 3.6 で非推奨: @ref{106e,,read()} の代わりに @code{recv()} を使用してください。

@end deffn

@geindex write() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket write}@anchor{106f}
@deffn {メソッド} SSLSocket.write (data)

Write `data' to the SSL socket and return the number of bytes written. The
`data' argument must be an object supporting the buffer interface.

ソケットが @ref{39b6,,non-blocking} で書き込みがブロックすると、 @ref{1069,,SSLWantReadError} もしくは @ref{106a,,SSLWantWriteError} が送出されます。

再ネゴシエーションがいつでも可能なので、 @ref{106f,,write()}  の呼び出しは読み出し操作も引き起こしえます。


バージョン 3.5 で変更: The socket timeout is no longer reset each time bytes are received or sent.
The socket timeout is now the maximum total duration to write `data'.



バージョン 3.6 で非推奨: @ref{106f,,write()} の代わりに @code{send()} を使用してください。

@end deffn

@cartouche
@quotation 注釈 
@ref{106e,,read()}, @ref{106f,,write()} メソッドは下位レベルのメソッドであり、暗号化されていないアプリケーションレベルのデータを読み書きし、それを復号/暗号化して暗号化された書き込みレベルのデータにします。これらのメソッドはアクティブな SSL 接続つまり、ハンドシェイクが完了していて、 @ref{39ec,,SSLSocket.unwrap()} が呼ばれていないことを必要とします。

通常はこれらのメソッドの代わりに @ref{fa4,,recv()} や @ref{fa7,,send()} のようなソケット API メソッドを使うべきです。
@end quotation
@end cartouche

@geindex do_handshake() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket do_handshake}@anchor{106d}
@deffn {メソッド} SSLSocket.do_handshake (block=False)

SSL セットアップのハンドシェイクを実行します。

If `block' is true and the timeout obtained by @ref{39a0,,gettimeout()}
is zero, the socket is set in blocking mode until the handshake is performed.


バージョン 3.4 で変更: The handshake method also performs @code{match_hostname()} when the
@ref{39c4,,check_hostname} attribute of the socket's
@ref{39ed,,context} is true.



バージョン 3.5 で変更: ソケットのタイムアウトは、バイトが送受信されるたびにリセットされなくなりました。ソケットのタイムアウトは、ハンドシェイクにかかる最大合計時間になりました。



バージョン 3.7 で変更: Hostname or IP address is matched by OpenSSL during handshake. The
function @code{match_hostname()} is no longer used. In case OpenSSL
refuses a hostname or IP address, the handshake is aborted early and
a TLS alert message is sent to the peer.

@end deffn

@geindex getpeercert() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket getpeercert}@anchor{11ba}
@deffn {メソッド} SSLSocket.getpeercert (binary_form=False)

接続先に証明書が無い場合、 @code{None} を返します。SSL ハンドシェイクがまだ行われていない場合は、 @ref{2ec,,ValueError} が送出されます。

@code{binary_form} が @ref{d2b,,False} で接続先から証明書を取得した場合、このメソッドは @ref{183,,dict} のインスタンスを返します。証明書が認証されていない場合、辞書は空です。証明書が認証されていた場合いくつかのキーを持った辞書を返し、 @code{subject} (証明書が発行された principal), @code{issuer} (証明書を発行した principal) を含みます。証明書が `Subject Alternative Name' 拡張(
@geindex RFC; RFC 3280
RFC 3280@footnote{https://datatracker.ietf.org/doc/html/rfc3280.html} を参照)のインスタンスを格納していた場合、 @code{subjectAltName} キーも辞書に含まれます。

@code{subject}, @code{issuer} フィールドは、証明書のそれぞれのフィールドについてのデータ構造で与えられる RDN (relative distinguishued name) のシーケンスを格納したタプルで、各 RDN は name-value ペアのシーケンスです。現実世界での例をお見せします:

@example
@{'issuer': ((('countryName', 'IL'),),
            (('organizationName', 'StartCom Ltd.'),),
            (('organizationalUnitName',
              'Secure Digital Certificate Signing'),),
            (('commonName',
              'StartCom Class 2 Primary Intermediate Server CA'),)),
 'notAfter': 'Nov 22 08:15:19 2013 GMT',
 'notBefore': 'Nov 21 03:09:52 2011 GMT',
 'serialNumber': '95F0',
 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'California'),),
             (('localityName', 'San Francisco'),),
             (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
             (('commonName', '*.eff.org'),),
             (('emailAddress', 'hostmaster@@eff.org'),)),
 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
 'version': 3@}
@end example

@code{binary_form} 引数が @ref{e07,,True} だった場合、証明書が渡されていればこのメソッドはDERエンコードされた証明書全体をバイト列として返し、接続先が証明書を提示しなかった場合は @ref{885,,None} を返します。接続先が証明書を提供するかどうかは SSL ソケットの役割に依存します:


@itemize *

@item 
クライアント SSL ソケットでは、認証が要求されているかどうかに関わらず、サーバは常に証明書を提供します。

@item 
サーバ SSL ソケットでは、クライアントはサーバによって認証が要求されている場合にのみ証明書を提供します。したがって、 (@ref{39c3,,CERT_OPTIONAL} や @ref{39b1,,CERT_REQUIRED} ではなく) @ref{39c2,,CERT_NONE} を使用した場合 @ref{11ba,,getpeercert()} は @ref{885,,None} を返します。
@end itemize

See also @ref{39c4,,SSLContext.check_hostname}.


バージョン 3.2 で変更: 返される辞書に @code{issuer}, @code{notBefore} のような追加アイテムを含むようになりました。



バージョン 3.4 で変更: ハンドシェイクが済んでいなければ @ref{2ec,,ValueError} を投げるようになりました。返される辞書に @code{crlDistributionPoints}, @code{caIssuers}, @code{OCSP} URI のような X509v3 拡張アイテムを含むようになりました。



バージョン 3.9 で変更: IPv6 address strings no longer have a trailing new line.

@end deffn

@geindex get_verified_chain() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket get_verified_chain}@anchor{195c}
@deffn {メソッド} SSLSocket.get_verified_chain ()

Returns verified certificate chain provided by the other
end of the SSL channel as a list of DER-encoded bytes.
If certificate verification was disabled method acts the same as
@ref{195d,,get_unverified_chain()}.


Added in version 3.13.

@end deffn

@geindex get_unverified_chain() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket get_unverified_chain}@anchor{195d}
@deffn {メソッド} SSLSocket.get_unverified_chain ()

Returns raw certificate chain provided by the other
end of the SSL channel as a list of DER-encoded bytes.


Added in version 3.13.

@end deffn

@geindex cipher() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket cipher}@anchor{38da}
@deffn {メソッド} SSLSocket.cipher ()

利用されている暗号の名前、その暗号の利用を定義しているSSLプロトコルのバージョン、利用されている鍵のbit長の3つの値を含むタプルを返します。もし接続が確立されていない場合、 @code{None} を返します。
@end deffn

@geindex shared_ciphers() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket shared_ciphers}@anchor{106c}
@deffn {メソッド} SSLSocket.shared_ciphers ()

クライアントとサーバーの両方で利用できる暗号方式のリストを返します。返されるリストの各要素は 3つの値を含むタプルで、その値はそれぞれ、暗号方式の名前、その暗号の利用を定義している SSL プロトコルのバージョン、暗号で使用される秘密鍵のビット長です。接続が確立されていないか、ソケットがクライアントソケットである場合、@ref{106c,,shared_ciphers()} は @code{None} を返します。


Added in version 3.5.

@end deffn

@geindex compression() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket compression}@anchor{135d}
@deffn {メソッド} SSLSocket.compression ()

使われている圧縮アルゴリズムを文字列で返します。接続が圧縮されていなければ @code{None} を返します。

上位レベルのプロトコルが自身で圧縮メカニズムをサポートする場合、SSL レベルでの圧縮を @ref{135e,,OP_NO_COMPRESSION} を使って無効にできます。


Added in version 3.3.

@end deffn

@geindex get_channel_binding() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket get_channel_binding}@anchor{135c}
@deffn {メソッド} SSLSocket.get_channel_binding (cb_type='tls-unique')

現在の接続におけるチャネルバインディングのデータを取得します。未接続あるいはハンドシェイクが完了していなければ @code{None} を返します。

`cb_type' パラメータにより、望みのチャネルバインディングのタイプを選択できます。チャネルバインディングのタイプの妥当なものは @ref{39de,,CHANNEL_BINDING_TYPES} でリストされています。現在のところは 
@geindex RFC; RFC 5929
RFC 5929@footnote{https://datatracker.ietf.org/doc/html/rfc5929.html} で定義されている 'tls-unique' のみがサポートされています。未サポートのチャネルバインディングのタイプが要求された場合、 @ref{2ec,,ValueError} を送出します。


Added in version 3.3.

@end deffn

@geindex selected_alpn_protocol() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket selected_alpn_protocol}@anchor{1065}
@deffn {メソッド} SSLSocket.selected_alpn_protocol ()

TLS ハンドシェイクで選択されたプロトコルを返します。 @ref{1064,,SSLContext.set_alpn_protocols()} が呼ばれていない場合、相手側が ALPN をサポートしていない場合、クライアントが提案したプロトコルのどれもソケットがサポートしない場合、あるいはハンドシェイクがまだ行われていない場合には、 @code{None} が返されます。


Added in version 3.5.

@end deffn

@geindex selected_npn_protocol() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket selected_npn_protocol}@anchor{a74}
@deffn {メソッド} SSLSocket.selected_npn_protocol ()

TLS/SSL ハンドシェイクで選択された上位レベルのプロトコルを返します。 @ref{358,,SSLContext.set_npn_protocols()} が呼ばれていない場合、相手側が NPN をサポートしていない場合、あるいはハンドシェイクがまだ行われていない場合には、 @code{None} が返されます。


Added in version 3.3.



バージョン 3.10 で非推奨: NPN has been superseded by ALPN

@end deffn

@geindex unwrap() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket unwrap}@anchor{39ec}
@deffn {メソッド} SSLSocket.unwrap ()

SSLシャットダウンハンドシェイクを実行します。これは下位レイヤーのソケットからTLSレイヤーを取り除き、下位レイヤーのソケットオブジェクトを返します。これは暗号化されたオペレーションから暗号化されていない接続に移行するときに利用されます。以降の通信には、オリジナルのソケットではなくこのメソッドが返したソケットのみを利用するべきです。
@end deffn

@geindex verify_client_post_handshake() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket verify_client_post_handshake}@anchor{c27}
@deffn {メソッド} SSLSocket.verify_client_post_handshake ()

Requests post-handshake authentication (PHA) from a TLS 1.3 client. PHA
can only be initiated for a TLS 1.3 connection from a server-side socket,
after the initial TLS handshake and with PHA enabled on both sides, see
@ref{c26,,SSLContext.post_handshake_auth}.

The method does not perform a cert exchange immediately. The server-side
sends a CertificateRequest during the next write event and expects the
client to respond with a certificate on the next read event.

If any precondition isn't met (e.g. not TLS 1.3, PHA not enabled), an
@ref{1491,,SSLError} is raised.

@cartouche
@quotation 注釈 
Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3
support, the method raises @ref{36b,,NotImplementedError}.
@end quotation
@end cartouche


Added in version 3.8.

@end deffn

@geindex version() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket version}@anchor{1068}
@deffn {メソッド} SSLSocket.version ()

コネクションによって実際にネゴシエイトされた SSL プロトコルバージョンを文字列で、または、セキュアなコネクションが確立していなければ @code{None} を返します。これを書いている時点では、 @code{"SSLv2"}, @code{"SSLv3"}, @code{"TLSv1"}, @code{"TLSv1.1"}, @code{"TLSv1.2"} などが返ります。最新の OpenSSL はもっと色々な値を定義しているかもしれません。


Added in version 3.5.

@end deffn

@geindex pending() (ssl.SSLSocket のメソッド)
@anchor{library/ssl ssl SSLSocket pending}@anchor{39ee}
@deffn {メソッド} SSLSocket.pending ()

接続において既に復号済みで読み出し可能で保留になっているバイト列の数を返します。
@end deffn

@geindex context (ssl.SSLSocket の属性)
@anchor{library/ssl ssl SSLSocket context}@anchor{39ed}
@deffn {の属性} SSLSocket.context

The @ref{357,,SSLContext} object this SSL socket is tied to.


Added in version 3.2.

@end deffn

@geindex server_side (ssl.SSLSocket の属性)
@anchor{library/ssl ssl SSLSocket server_side}@anchor{39ef}
@deffn {の属性} SSLSocket.server_side

サーバサイドのソケットに対して @code{True} 、クライアントサイドのソケットに対して @code{False} となる真偽値です。


Added in version 3.2.

@end deffn

@geindex server_hostname (ssl.SSLSocket の属性)
@anchor{library/ssl ssl SSLSocket server_hostname}@anchor{d78}
@deffn {の属性} SSLSocket.server_hostname

サーバのホスト名: @ref{169,,str} 型、またはサーバサイドのソケットの場合とコンストラクタで hostname が指定されなかった場合は @code{None}


Added in version 3.2.



バージョン 3.7 で変更: The attribute is now always ASCII text. When @code{server_hostname} is
an internationalized domain name (IDN), this attribute now stores the
A-label form (@code{"xn--pythn-mua.org"}), rather than the U-label form
(@code{"pythön.org"}).

@end deffn

@geindex session (ssl.SSLSocket の属性)
@anchor{library/ssl ssl SSLSocket session}@anchor{193d}
@deffn {の属性} SSLSocket.session

この SSL 接続に対する @ref{ed9,,SSLSession} です。このセッションは、TLS ハンドシェイクの実行後、クライアントサイドとサーバサイドのソケットで使用できます。クライアントソケットでは、このセッションを @ref{106d,,do_handshake()} が呼ばれる前に設定して、セッションを再利用できます。


Added in version 3.6.

@end deffn

@geindex session_reused (ssl.SSLSocket の属性)
@anchor{library/ssl ssl SSLSocket session_reused}@anchor{39f0}
@deffn {の属性} SSLSocket.session_reused


Added in version 3.6.

@end deffn

@node SSL コンテキスト,証明書,SSL ソケット,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl ssl-contexts}@anchor{39f1}
@subsubsection SSL コンテキスト



Added in version 3.2.


SSL コンテキストは、SSL 構成オプション、証明書(群)や秘密鍵(群)などのような、一回の SSL 接続よりも長生きするさまざまなデータを保持します。これはサーバサイドソケットの SSL セッションのキャッシュも管理し、同じクライアントからの繰り返しの接続時の速度向上に一役買います。

@geindex SSLContext (ssl のクラス)
@anchor{library/ssl ssl SSLContext}@anchor{357}
@deffn {クラス} ssl.SSLContext (protocol=None)

Create a new SSL context.  You may pass `protocol' which must be one
of the @code{PROTOCOL_*} constants defined in this module.  The parameter
specifies which version of the SSL protocol to use.  Typically, the
server chooses a particular protocol version, and the client must adapt
to the server's choice.  Most of the versions are not interoperable
with the other versions.  If not specified, the default is
@ref{39b3,,PROTOCOL_TLS}; it provides the most compatibility with other
versions.

次のテーブルは、どのクライアントのバージョンがどのサーバのバージョンに接続できるかを示しています:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
@item

`client' / `server'

@tab

`SSLv2'

@tab

`SSLv3'

@tab

`TLS' @footnote{
TLS 1.3 protocol will be available with @ref{39b3,,PROTOCOL_TLS} in
OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just
TLS 1.3.
}

@tab

`TLSv1'

@tab

`TLSv1.1'

@tab

`TLSv1.2'

@item

`SSLv2'

@tab

yes

@tab

no

@tab

no @footnote{
@ref{357,,SSLContext} では、デフォルトで @ref{a3a,,OP_NO_SSLv2} によりSSLv2 が無効になっています。
}

@tab

no

@tab

no

@tab

no

@item

`SSLv3'

@tab

no

@tab

yes

@tab

no @footnote{
@ref{357,,SSLContext} では、デフォルトで @ref{a3b,,OP_NO_SSLv3} により SSLv3 が無効になっています。
}

@tab

no

@tab

no

@tab

no

@item

`TLS' (`SSLv23') @footnote{
TLS 1.3 protocol will be available with @ref{39b3,,PROTOCOL_TLS} in
OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just
TLS 1.3.
}

@tab

no @footnote{
@ref{357,,SSLContext} では、デフォルトで @ref{a3a,,OP_NO_SSLv2} によりSSLv2 が無効になっています。
}

@tab

no @footnote{
@ref{357,,SSLContext} では、デフォルトで @ref{a3b,,OP_NO_SSLv3} により SSLv3 が無効になっています。
}

@tab

yes

@tab

yes

@tab

yes

@tab

yes

@item

`TLSv1'

@tab

no

@tab

no

@tab

yes

@tab

yes

@tab

no

@tab

no

@item

`TLSv1.1'

@tab

no

@tab

no

@tab

yes

@tab

no

@tab

yes

@tab

no

@item

`TLSv1.2'

@tab

no

@tab

no

@tab

yes

@tab

no

@tab

no

@tab

yes

@end multitable


@subsubheading 脚注



@subsubheading 参考


@ref{480,,create_default_context()} lets the @code{ssl} module choose
security settings for a given purpose.



バージョン 3.6 で変更: The context is created with secure default values. The options
@ref{135e,,OP_NO_COMPRESSION}, @ref{1361,,OP_CIPHER_SERVER_PREFERENCE},
@ref{39cf,,OP_SINGLE_DH_USE}, @ref{39d0,,OP_SINGLE_ECDH_USE},
@ref{a3a,,OP_NO_SSLv2},
and @ref{a3b,,OP_NO_SSLv3} (except for @ref{39be,,PROTOCOL_SSLv3}) are
set by default. The initial cipher suite list contains only @code{HIGH}
ciphers, no @code{NULL} ciphers and no @code{MD5} ciphers.



バージョン 3.10 で非推奨: @ref{357,,SSLContext} without protocol argument is deprecated. The
context class will either require @ref{a72,,PROTOCOL_TLS_CLIENT} or
@ref{a73,,PROTOCOL_TLS_SERVER} protocol in the future.



バージョン 3.10 で変更: The default cipher suites now include only secure AES and ChaCha20
ciphers with forward secrecy and security level 2. RSA and DH keys with
less than 2048 bits and ECC keys with less than 224 bits are prohibited.
@ref{39b3,,PROTOCOL_TLS}, @ref{a72,,PROTOCOL_TLS_CLIENT}, and
@ref{a73,,PROTOCOL_TLS_SERVER} use TLS 1.2 as minimum TLS version.


@cartouche
@quotation 注釈 
@ref{357,,SSLContext} only supports limited mutation once it has been used
by a connection. Adding new certificates to the internal trust store is
allowed, but changing ciphers, verification settings, or mTLS
certificates may result in surprising behavior.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
@ref{357,,SSLContext} is designed to be shared and used by multiple
connections.
Thus, it is thread-safe as long as it is not reconfigured after being
used by a connection.
@end quotation
@end cartouche
@end deffn

@ref{357,,SSLContext} オブジェクトは以下のメソッドと属性を持っています:

@geindex cert_store_stats() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext cert_store_stats}@anchor{11ae}
@deffn {メソッド} SSLContext.cert_store_stats ()

ロードされた X.509 証明書の数、CA 証明書で活性の X.509 証明書の数、証明書失効リストの数、についての統計情報を辞書として取得します。

一つの CA と他の一つの証明書を持ったコンテキストでの例です:

@example
>>> context.cert_store_stats()
@{'crl': 0, 'x509_ca': 1, 'x509': 2@}
@end example


Added in version 3.4.

@end deffn

@geindex load_cert_chain() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext load_cert_chain}@anchor{598}
@deffn {メソッド} SSLContext.load_cert_chain (certfile, keyfile=None, password=None)

秘密鍵と対応する証明書をロードします。 `certfile' は、証明書と、証明書認証で必要とされる任意の数の CA 証明書を含む、PEM フォーマットの単一ファイルへのパスでなければなりません。 `keyfile' 文字列を指定する場合、秘密鍵が含まれるファイルを指すものでなければなりません。指定しない場合、秘密鍵も `certfile' から取得されます。 `certfile' への証明書の格納についての詳細は、 @ref{39f2,,証明書} の議論を参照してください。

`password' 引数に、秘密鍵を復号するためのパスワードを返す関数を与えることができます。その関数は秘密鍵が暗号化されていて、なおかつパスワードが必要な場合にのみ呼び出されます。その関数は引数なしで呼び出され、string, bytes, または bytearray を返さなければなりません。戻り値が string の場合は鍵を復号化するのに使う前に UTF-8 でエンコードされます。string の代わりに bytes や bytearray を返した場合は `password' 引数に直接供給されます。秘密鍵が暗号化されていなかったりパスワードを必要としない場合は、指定は無視されます。

`password' が与えられず、そしてパスワードが必要な場合には、OpenSSL 組み込みのパスワード問い合わせメカニズムが、ユーザに対話的にパスワードを問い合わせます。

秘密鍵が証明書に合致しなければ、 @ref{1491,,SSLError} が送出されます。


バージョン 3.3 で変更: 新しいオプション引数 `password'。

@end deffn

@geindex load_default_certs() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext load_default_certs}@anchor{11b4}
@deffn {メソッド} SSLContext.load_default_certs (purpose=Purpose.SERVER_AUTH)

デフォルトの場所から "認証局" (CA=certification authority) 証明書ファイル一式をロードします。Windows では、CA 証明書はシステム記憶域の @code{CA} と @code{ROOT} からロードします。全てのシステムでは、この関数は @ref{11ad,,SSLContext.set_default_verify_paths()} を呼び出します。将来的にはこのメソッドは、他の場所からも CA 証明書をロードするかもしれません。

The `purpose' flag specifies what kind of CA certificates are loaded. The
default settings @ref{11b5,,Purpose.SERVER_AUTH} loads certificates, that are
flagged and trusted for TLS web server authentication (client side
sockets). @ref{11b6,,Purpose.CLIENT_AUTH} loads CA certificates for client
certificate verification on the server side.


Added in version 3.4.

@end deffn

@geindex load_verify_locations() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext load_verify_locations}@anchor{10ee}
@deffn {メソッド} SSLContext.load_verify_locations (cafile=None, capath=None, cadata=None)

@ref{39b0,,verify_mode} が @ref{39c2,,CERT_NONE} でない場合に接続先の証明書ファイルの正当性検証に使われる "認証局" (CA=certification authority) 証明書ファイル一式をロードします。少なくとも `cafile' か `capath' のどちらかは指定しなければなりません。

このメソッドは PEM または DER フォーマットの証明書失効リスト (CRLs=certification revocation lists)もロードできます。CRLs のために使うには、 @ref{11b0,,SSLContext.verify_flags} を適切に設定しなければなりません。

`cafile' を指定する場合は、PEM フォーマットで CA 証明書が結合されたファイルへのパスを指定してください。このファイル内で証明書をどのように編成すれば良いのかについての詳しい情報については、 @ref{39f2,,証明書} の議論を参照してください。

The `capath' string, if present, is
the path to a directory containing several CA certificates in PEM format,
following an OpenSSL specific layout@footnote{https://docs.openssl.org/master/man3/SSL_CTX_load_verify_locations/}.

`cadata' オブジェクトを指定する場合は、PEM エンコードの証明書一つ以上の ASCII 文字列か、DER エンコードの証明書の @ref{193,,bytes-like object} オブジェクトのどちらかを指定してください。PEM エンコードの証明書の周囲の余分な行は無視されますが、少なくとも一つの証明書が含まれている必要があります。


バージョン 3.4 で変更: 新しいオプション引数 `cadata' 。

@end deffn

@geindex get_ca_certs() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext get_ca_certs}@anchor{11af}
@deffn {メソッド} SSLContext.get_ca_certs (binary_form=False)

ロードされた "認証局" (CA=certification authority) 証明書のリストを取得します。 @code{binary_form} 引数が @ref{d2b,,False} である場合、リストのそれぞれのエントリは @ref{11ba,,SSLSocket.getpeercert()} が出力するような辞書になります。True である場合、このメソッドは、DER エンコード形式の証明書のリストを返します。返却されるリストには、 SSL 接続によって証明書がリクエストおよびロードされない限り、 `capath' からの証明書は含まれません。

@cartouche
@quotation 注釈 
capath ディレクトリ内の証明書は一度でも使われない限りはロードされません。
@end quotation
@end cartouche


Added in version 3.4.

@end deffn

@geindex get_ciphers() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext get_ciphers}@anchor{eda}
@deffn {メソッド} SSLContext.get_ciphers ()

有効な暗号化のリストを取得します。リストは暗号化優先度順に並びます。@ref{39f3,,SSLContext.set_ciphers()} を参照してください。

以下はプログラム例です:

@example
>>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
>>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
>>> ctx.get_ciphers()
[@{'aead': True,
  'alg_bits': 256,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(256) Mac=AEAD',
  'digest': None,
  'id': 50380848,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES256-GCM-SHA384',
  'protocol': 'TLSv1.2',
  'strength_bits': 256,
  'symmetric': 'aes-256-gcm'@},
 @{'aead': True,
  'alg_bits': 128,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(128) Mac=AEAD',
  'digest': None,
  'id': 50380847,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES128-GCM-SHA256',
  'protocol': 'TLSv1.2',
  'strength_bits': 128,
  'symmetric': 'aes-128-gcm'@}]
@end example


Added in version 3.6.

@end deffn

@geindex set_default_verify_paths() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_default_verify_paths}@anchor{11ad}
@deffn {メソッド} SSLContext.set_default_verify_paths ()

デフォルトの "認証局" (CA=certification authority) 証明書を、OpenSSL ライブラリがビルドされた際に定義されたファイルシステム上のパスからロードします。残念ながらこのメソッドが成功したかどうかを知るための簡単な方法はありません: 証明書が見つからなくてもエラーは返りません。OpenSSL ライブラリがオペレーティングシステムの一部として提供されている際にはどうやら適切に構成できるようですが。
@end deffn

@geindex set_ciphers() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_ciphers}@anchor{39f3}
@deffn {メソッド} SSLContext.set_ciphers (ciphers, /)

Set the available ciphers for sockets created with this context.
It should be a string in the OpenSSL cipher list format@footnote{https://docs.openssl.org/master/man1/ciphers/}.
If no cipher can be selected (because compile-time options or other
configuration forbids use of all the specified ciphers), an
@ref{1491,,SSLError} will be raised.

@cartouche
@quotation 注釈 
接続時に SSL ソケットの @ref{38da,,SSLSocket.cipher()} メソッドが、現在選択されているその暗号を使います。

TLS 1.3 cipher suites cannot be disabled with
@ref{39f3,,set_ciphers()}.
@end quotation
@end cartouche
@end deffn

@geindex set_alpn_protocols() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_alpn_protocols}@anchor{1064}
@deffn {メソッド} SSLContext.set_alpn_protocols (alpn_protocols)

SSL/TLS ハンドシェイク時にソケットが提示すべきプロトコルを指定します。 @code{['http/1.1', 'spdy/2']} のような推奨順に並べた ASCII 文字列のリストでなければなりません。プロトコルの選択は 
@geindex RFC; RFC 7301
RFC 7301@footnote{https://datatracker.ietf.org/doc/html/rfc7301.html} に従いハンドシェイク中に行われます。ハンドシェイクが正常に終了した後、 @ref{1065,,SSLSocket.selected_alpn_protocol()} メソッドは合意されたプロトコルを返します。

このメソッドは @ref{1066,,HAS_ALPN} が @code{False} の場合 @ref{36b,,NotImplementedError} を送出します。


Added in version 3.5.

@end deffn

@geindex set_npn_protocols() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_npn_protocols}@anchor{358}
@deffn {メソッド} SSLContext.set_npn_protocols (npn_protocols)

SSL/TLS ハンドシェイク時にソケットが提示すべきプロトコルを指定します。 @code{['http/1.1', 'spdy/2']} のような推奨順に並べた文字列のリストでなければなりません。プロトコルの選択は Application Layer Protocol Negotiation@footnote{https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation} に従いハンドシェイク中に行われます。ハンドシェイクが正常に終了した後、 @ref{1065,,SSLSocket.selected_alpn_protocol()} メソッドは合意されたプロトコルを返します。

このメソッドは @ref{39d7,,HAS_NPN} が @code{False} の場合 @ref{36b,,NotImplementedError} を送出します。


Added in version 3.3.



バージョン 3.10 で非推奨: NPN has been superseded by ALPN

@end deffn

@geindex sni_callback (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext sni_callback}@anchor{1c8f}
@deffn {の属性} SSLContext.sni_callback

TLS クライアントがサーバ名表示を指定した際の、SSL/TLS サーバによって TLS Client Hello ハンドシェイクメッセージが受け取られたあとで呼び出されるコールバック関数を登録します。サーバ名表示メカニズムは 
@geindex RFC; RFC 6066
RFC 6066@footnote{https://datatracker.ietf.org/doc/html/rfc6066.html} セクション 3 - Server Name Indication で述べられています。

@code{SSLContext} ごとに一つだけコールバックをセットできます。 `sni_callback' を @code{None} にすればコールバックは無効になります。この関数を続けて呼ぶと、以前に登録されたコールバックを上書きします。

The callback function will be called with three
arguments; the first being the @ref{ae7,,ssl.SSLSocket}, the second is a string
that represents the server name that the client is intending to communicate
(or @ref{885,,None} if the TLS Client Hello does not contain a server name)
and the third argument is the original @ref{357,,SSLContext}. The server name
argument is text. For internationalized domain name, the server
name is an IDN A-label (@code{"xn--pythn-mua.org"}).

このコールバックの典型的な利用方法は、 @ref{ae7,,ssl.SSLSocket} の @ref{39ed,,SSLSocket.context} 属性を、サーバ名に合致する証明書チェインを持つ新しい @ref{357,,SSLContext} オブジェクトに変更することです。

Due to the early negotiation phase of the TLS connection, only limited
methods and attributes are usable like
@ref{1065,,SSLSocket.selected_alpn_protocol()} and @ref{39ed,,SSLSocket.context}.
The @ref{11ba,,SSLSocket.getpeercert()}, @ref{195c,,SSLSocket.get_verified_chain()},
@ref{195d,,SSLSocket.get_unverified_chain()} @ref{38da,,SSLSocket.cipher()}
and @ref{135d,,SSLSocket.compression()} methods require that
the TLS connection has progressed beyond the TLS Client Hello and therefore
will not return meaningful values nor can they be called safely.

TLS ネゴシエーションを継続させるならば、 `sni_callback' 関数は @code{None} を返さなければなりません。TLS が失敗することを必要とするなら、 constant @ref{39e0,,ALERT_DESCRIPTION_*} を返してください。ここにない値を返すと、致命エラー @ref{39e0,,ALERT_DESCRIPTION_INTERNAL_ERROR} を引き起こします。

`sni_callback' 関数が例外を送出した場合、TLS 接続は TLS の致命的アラートメッセージ @ref{39df,,ALERT_DESCRIPTION_HANDSHAKE_FAILURE} とともに終了します。

このメソッドは OpenSSL ライブラリが OPENSSL_NO_TLSEXT を定義してビルドされている場合、 @ref{36b,,NotImplementedError} を送出します。


Added in version 3.7.

@end deffn

@geindex set_servername_callback() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_servername_callback}@anchor{11b9}
@deffn {メソッド} SSLContext.set_servername_callback (server_name_callback)

This is a legacy API retained for backwards compatibility. When possible,
you should use @ref{1c8f,,sni_callback} instead. The given `server_name_callback'
is similar to `sni_callback', except that when the server hostname is an
IDN-encoded internationalized domain name, the `server_name_callback'
receives a decoded U-label (@code{"pythön.org"}).

If there is a decoding error on the server name, the TLS connection will
terminate with an @ref{39e0,,ALERT_DESCRIPTION_INTERNAL_ERROR} fatal TLS
alert message to the client.


Added in version 3.4.

@end deffn

@geindex load_dh_params() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext load_dh_params}@anchor{135a}
@deffn {メソッド} SSLContext.load_dh_params (dhfile, /)

ディフィー・ヘルマン(DH)鍵交換のための鍵生成パラメータをロードします。DH 鍵交換を用いることは、(サーバ、クライアントともに)計算機リソースに高い処理負荷をかけますがセキュリティを向上させます。 `dhfile' パラメータは PEM フォーマットの DH パラメータを含んだファイルへのパスでなければなりません。

この設定はクライアントソケットには適用されません。さらにセキュリティを改善するのに @ref{39cf,,OP_SINGLE_DH_USE} オプションも利用できます。


Added in version 3.3.

@end deffn

@geindex set_ecdh_curve() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_ecdh_curve}@anchor{135b}
@deffn {メソッド} SSLContext.set_ecdh_curve (curve_name, /)

楕円曲線ディフィー・ヘルマン(ECDH)鍵交換の曲線名を指定します。ECDH はもとの DH に較べて、ほぼ間違いなく同程度に安全である一方で、顕著に高速です。 `curve_name' パラメータは既知の楕円曲線を表す文字列でなければなりません。例えば @code{prime256v1} が広くサポートされている曲線です。

この設定はクライアントソケットには適用されません。さらにセキュリティを改善するのに @ref{39d0,,OP_SINGLE_ECDH_USE} オプションも利用できます。

このメソッドは @ref{39d5,,HAS_ECDH} が @code{False} の場合は利用できません。


Added in version 3.3.



@subsubheading 参考



@table @asis

@item SSL/TLS & Perfect Forward Secrecy@footnote{https://vincent.bernat.ch/en/blog/2011-ssl-perfect-forward-secrecy}

Vincent Bernat.
@end table

@end deffn

@geindex wrap_socket() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext wrap_socket}@anchor{748}
@deffn {メソッド} SSLContext.wrap_socket (sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None)

Wrap an existing Python socket `sock' and return an instance of
@ref{39f4,,SSLContext.sslsocket_class} (default @ref{ae7,,SSLSocket}). The
returned SSL socket is tied to the context, its settings and certificates.
`sock' must be a @ref{150b,,SOCK_STREAM} socket; other
socket types are unsupported.

@code{server_side} 引数は真偽値で、このソケットがサーバサイドとクライアントサイドのどちらの動作をするのかを指定します。

クライアントサイドソケットにおいて、コンテキストの生成は遅延されます。つまり、低レイヤのソケットがまだ接続されていない場合、コンテキストの生成はそのソケットの @code{connect()} メソッドが呼ばれた後に行われます。サーバサイドソケットの場合、そのソケットに接続先が居なければそれは listen 用ソケットだと判断されます。 @code{accept()} メソッドで生成されるクライアント接続に対してのサーバサイド SSLラップは自動的に行われます。メソッドは @ref{1491,,SSLError} を送出することがあります。

クライアントからの接続では、 `server_hostname' で接続先サービスのホスト名を指定できます。これは HTTP バーチャルホストにかなり似て、シングルサーバで複数の SSL ベースのサービスを別々の証明書でホストしているようなサーバに対して使えます。 `server_side' が True の場合に `server_hostname' を指定すると @ref{2ec,,ValueError} を送出します。

@code{do_handshake_on_connect} 引数は、 @code{socket.connect()} の後に自動的に SSLハンドシェイクを行うか、それともアプリケーションが明示的に @ref{106d,,SSLSocket.do_handshake()} メソッドを実行するかを指定します。 @ref{106d,,SSLSocket.do_handshake()} を明示的に呼びだすことで、ハンドシェイクによるソケットI/Oのブロッキング動作を制御できます。

@code{suppress_ragged_eofs} 引数は、 @code{SSLSocket.recv()} メソッドが、接続先から予期しないEOF を受け取った時に通知する方法を指定します。 @ref{e07,,True} (デフォルト) の場合、下位のソケットレイヤーから予期せぬEOFエラーが来た場合、通常のEOF (空のバイト列オブジェクト)を返します。 @ref{d2b,,False} の場合、呼び出し元に例外を投げて通知します。

`session', @ref{193d,,session} を参照してください。

To wrap an @ref{ae7,,SSLSocket} in another @ref{ae7,,SSLSocket}, use
@ref{d7b,,SSLContext.wrap_bio()}.


バージョン 3.5 で変更: OpenSSL が SNI をサポートしなくても server_hostname を許容するようになりました。



バージョン 3.6 で変更: `session' 引数が追加されました。



バージョン 3.7 で変更: The method returns an instance of @ref{39f4,,SSLContext.sslsocket_class}
instead of hard-coded @ref{ae7,,SSLSocket}.

@end deffn

@geindex sslsocket_class (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext sslsocket_class}@anchor{39f4}
@deffn {の属性} SSLContext.sslsocket_class

The return type of @ref{748,,SSLContext.wrap_socket()}, defaults to
@ref{ae7,,SSLSocket}. The attribute can be assigned to on instances of
@ref{357,,SSLContext} in order to return a custom subclass of
@ref{ae7,,SSLSocket}.


Added in version 3.7.

@end deffn

@geindex wrap_bio() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext wrap_bio}@anchor{d7b}
@deffn {メソッド} SSLContext.wrap_bio (incoming, outgoing, server_side=False, server_hostname=None, session=None)

Wrap the BIO objects `incoming' and `outgoing' and return an instance of
@ref{39f5,,SSLContext.sslobject_class} (default @ref{d7a,,SSLObject}). The SSL
routines will read input data from the incoming BIO and write data to the
outgoing BIO.

`server_side'、 `server_hostname' 、 `session' 引数は、 @ref{748,,SSLContext.wrap_socket()} での意味と同じ意味を持ちます。


バージョン 3.6 で変更: `session' 引数が追加されました。



バージョン 3.7 で変更: The method returns an instance of @ref{39f5,,SSLContext.sslobject_class}
instead of hard-coded @ref{d7a,,SSLObject}.

@end deffn

@geindex sslobject_class (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext sslobject_class}@anchor{39f5}
@deffn {の属性} SSLContext.sslobject_class

The return type of @ref{d7b,,SSLContext.wrap_bio()}, defaults to
@ref{d7a,,SSLObject}. The attribute can be overridden on instance of class
in order to return a custom subclass of @ref{d7a,,SSLObject}.


Added in version 3.7.

@end deffn

@geindex session_stats() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext session_stats}@anchor{39f6}
@deffn {メソッド} SSLContext.session_stats ()

Get statistics about the SSL sessions created or managed by this context.
A dictionary is returned which maps the names of each piece of information@footnote{https://docs.openssl.org/1.1.1/man3/SSL_CTX_sess_number/} to their
numeric values.  For example, here is the total number of hits and misses
in the session cache since the context was created:

@example
>>> stats = context.session_stats()
>>> stats['hits'], stats['misses']
(0, 0)
@end example
@end deffn

@geindex check_hostname (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext check_hostname}@anchor{39c4}
@deffn {の属性} SSLContext.check_hostname

Whether to match the peer cert's hostname in
@ref{106d,,SSLSocket.do_handshake()}. The context's
@ref{39b0,,verify_mode} must be set to @ref{39c3,,CERT_OPTIONAL} or
@ref{39b1,,CERT_REQUIRED}, and you must pass `server_hostname' to
@ref{748,,wrap_socket()} in order to match the hostname.  Enabling
hostname checking automatically sets @ref{39b0,,verify_mode} from
@ref{39c2,,CERT_NONE} to @ref{39b1,,CERT_REQUIRED}.  It cannot be set back to
@ref{39c2,,CERT_NONE} as long as hostname checking is enabled. The
@ref{a72,,PROTOCOL_TLS_CLIENT} protocol enables hostname checking by default.
With other protocols, hostname checking must be enabled explicitly.

以下はプログラム例です:

@example
import socket, ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
ssl_sock.connect(('www.verisign.com', 443))
@end example


Added in version 3.4.



バージョン 3.7 で変更: @ref{39b0,,verify_mode} is now automatically changed
to @ref{39b1,,CERT_REQUIRED}  when hostname checking is enabled and
@ref{39b0,,verify_mode} is @ref{39c2,,CERT_NONE}. Previously
the same operation would have failed with a @ref{2ec,,ValueError}.

@end deffn

@geindex keylog_filename (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext keylog_filename}@anchor{39b2}
@deffn {の属性} SSLContext.keylog_filename

Write TLS keys to a keylog file, whenever key material is generated or
received. The keylog file is designed for debugging purposes only. The
file format is specified by NSS and used by many traffic analyzers such
as Wireshark. The log file is opened in append-only mode. Writes are
synchronized between threads, but not between processes.


Added in version 3.8.

@end deffn

@geindex maximum_version (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext maximum_version}@anchor{a71}
@deffn {の属性} SSLContext.maximum_version

A @ref{39e3,,TLSVersion} enum member representing the highest supported
TLS version. The value defaults to @ref{39e5,,TLSVersion.MAXIMUM_SUPPORTED}.
The attribute is read-only for protocols other than @ref{39b3,,PROTOCOL_TLS},
@ref{a72,,PROTOCOL_TLS_CLIENT}, and @ref{a73,,PROTOCOL_TLS_SERVER}.

The attributes @ref{a71,,maximum_version},
@ref{a70,,minimum_version} and
@ref{a39,,SSLContext.options} all affect the supported SSL
and TLS versions of the context. The implementation does not prevent
invalid combination. For example a context with
@ref{39cd,,OP_NO_TLSv1_2} in @ref{a39,,options} and
@ref{a71,,maximum_version} set to @ref{39e9,,TLSVersion.TLSv1_2}
will not be able to establish a TLS 1.2 connection.


Added in version 3.7.

@end deffn

@geindex minimum_version (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext minimum_version}@anchor{a70}
@deffn {の属性} SSLContext.minimum_version

Like @ref{a71,,SSLContext.maximum_version} except it is the lowest
supported version or @ref{39e4,,TLSVersion.MINIMUM_SUPPORTED}.


Added in version 3.7.

@end deffn

@geindex num_tickets (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext num_tickets}@anchor{39f7}
@deffn {の属性} SSLContext.num_tickets

Control the number of TLS 1.3 session tickets of a
@ref{a73,,PROTOCOL_TLS_SERVER} context. The setting has no impact on TLS
1.0 to 1.2 connections.


Added in version 3.8.

@end deffn

@geindex options (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext options}@anchor{a39}
@deffn {の属性} SSLContext.options

このコンテキストで有効になっている SSL オプションを表す整数。デフォルトの値は @ref{39ca,,OP_ALL} ですが、 @ref{a3a,,OP_NO_SSLv2} のような他の値をビット OR 演算で指定できます。


バージョン 3.6 で変更: @ref{a39,,SSLContext.options} は次のように @ref{39d2,,Options} のフラグを返します。

@example
>>> ssl.create_default_context().options
<Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>
@end example



バージョン 3.7 で非推奨: All @code{OP_NO_SSL*} and @code{OP_NO_TLS*} options have been deprecated since
Python 3.7. Use @ref{a70,,SSLContext.minimum_version} and
@ref{a71,,SSLContext.maximum_version} instead.

@end deffn

@geindex post_handshake_auth (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext post_handshake_auth}@anchor{c26}
@deffn {の属性} SSLContext.post_handshake_auth

Enable TLS 1.3 post-handshake client authentication. Post-handshake auth
is disabled by default and a server can only request a TLS client
certificate during the initial handshake. When enabled, a server may
request a TLS client certificate at any time after the handshake.

When enabled on client-side sockets, the client signals the server that
it supports post-handshake authentication.

When enabled on server-side sockets, @ref{39b0,,SSLContext.verify_mode} must
be set to @ref{39c3,,CERT_OPTIONAL} or @ref{39b1,,CERT_REQUIRED}, too. The
actual client cert exchange is delayed until
@ref{c27,,SSLSocket.verify_client_post_handshake()} is called and some I/O is
performed.


Added in version 3.8.

@end deffn

@geindex protocol (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext protocol}@anchor{39f8}
@deffn {の属性} SSLContext.protocol

コンテキストの構築時に選択されたプロトコルバージョン。この属性は読み出し専用です。
@end deffn

@geindex hostname_checks_common_name (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext hostname_checks_common_name}@anchor{d76}
@deffn {の属性} SSLContext.hostname_checks_common_name

Whether @ref{39c4,,check_hostname} falls back to verify the cert's
subject common name in the absence of a subject alternative name
extension (default: true).


Added in version 3.7.



バージョン 3.10 で変更: The flag had no effect with OpenSSL before version 1.1.1l. Python 3.8.9,
3.9.3, and 3.10 include workarounds for previous versions.

@end deffn

@geindex security_level (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext security_level}@anchor{39f9}
@deffn {の属性} SSLContext.security_level

An integer representing the security level@footnote{https://docs.openssl.org/master/man3/SSL_CTX_get_security_level/}
for the context. This attribute is read-only.


Added in version 3.10.

@end deffn

@geindex verify_flags (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext verify_flags}@anchor{11b0}
@deffn {の属性} SSLContext.verify_flags

証明書の検証操作のためのフラグです。 @ref{11b2,,VERIFY_CRL_CHECK_LEAF} などのフラグをビット OR 演算でセットできます。デフォルトでは OpenSSL は証明書失効リスト (CRLs) を必要としませんし検証にも使いません。


Added in version 3.4.



バージョン 3.6 で変更: @ref{11b0,,SSLContext.verify_flags} は次のように @ref{39c7,,VerifyFlags} のフラグを返します。

@example
>>> ssl.create_default_context().verify_flags
<VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>
@end example

@end deffn

@geindex verify_mode (ssl.SSLContext の属性)
@anchor{library/ssl ssl SSLContext verify_mode}@anchor{39b0}
@deffn {の属性} SSLContext.verify_mode

接続先の証明書の検証を試みるかどうか、また、検証が失敗した場合にどのように振舞うべきかを制御します。この属性は @ref{39c2,,CERT_NONE}, @ref{39c3,,CERT_OPTIONAL}, @ref{39b1,,CERT_REQUIRED} のうちどれか一つでなければなりません。


バージョン 3.6 で変更: @ref{39b0,,SSLContext.verify_mode} は次のように @ref{39c5,,VerifyMode} enum (列挙) を返します。

@example
>>> ssl.create_default_context().verify_mode
<VerifyMode.CERT_REQUIRED: 2>
@end example

@end deffn

@geindex set_psk_client_callback() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_psk_client_callback}@anchor{39fa}
@deffn {メソッド} SSLContext.set_psk_client_callback (callback)

Enables TLS-PSK (pre-shared key) authentication on a client-side connection.

In general, certificate based authentication should be preferred over this method.

The parameter @code{callback} is a callable object with the signature:
@code{def callback(hint: str | None) -> tuple[str | None, bytes]}.
The @code{hint} parameter is an optional identity hint sent by the server.
The return value is a tuple in the form (client-identity, psk).
Client-identity is an optional string which may be used by the server to
select a corresponding PSK for the client. The string must be less than or
equal to @code{256} octets when UTF-8 encoded. PSK is a
@ref{193,,bytes-like object} representing the pre-shared key. Return a zero
length PSK to reject the connection.

Setting @code{callback} to @ref{885,,None} removes any existing callback.

@cartouche
@quotation 注釈 
When using TLS 1.3:


@itemize -

@item 
the @code{hint} parameter is always @ref{885,,None}.

@item 
client-identity must be a non-empty string.
@end itemize
@end quotation
@end cartouche

使用例:

@example
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.maximum_version = ssl.TLSVersion.TLSv1_2
context.set_ciphers('PSK')

# A simple lambda:
psk = bytes.fromhex('c0ffee')
context.set_psk_client_callback(lambda hint: (None, psk))

# A table using the hint from the server:
psk_table = @{ 'ServerId_1': bytes.fromhex('c0ffee'),
              'ServerId_2': bytes.fromhex('facade')
@}
def callback(hint):
    return 'ClientId_1', psk_table.get(hint, b'@w{'})
context.set_psk_client_callback(callback)
@end example

This method will raise @ref{36b,,NotImplementedError} if @ref{39dd,,HAS_PSK} is
@code{False}.


Added in version 3.13.

@end deffn

@geindex set_psk_server_callback() (ssl.SSLContext のメソッド)
@anchor{library/ssl ssl SSLContext set_psk_server_callback}@anchor{39fb}
@deffn {メソッド} SSLContext.set_psk_server_callback (callback, identity_hint=None)

Enables TLS-PSK (pre-shared key) authentication on a server-side connection.

In general, certificate based authentication should be preferred over this method.

The parameter @code{callback} is a callable object with the signature:
@code{def callback(identity: str | None) -> bytes}.
The @code{identity} parameter is an optional identity sent by the client which can
be used to select a corresponding PSK.
The return value is a @ref{193,,bytes-like object} representing the pre-shared key.
Return a zero length PSK to reject the connection.

Setting @code{callback} to @ref{885,,None} removes any existing callback.

The parameter @code{identity_hint} is an optional identity hint string sent to
the client. The string must be less than or equal to @code{256} octets when
UTF-8 encoded.

@cartouche
@quotation 注釈 
When using TLS 1.3 the @code{identity_hint} parameter is not sent to the client.
@end quotation
@end cartouche

使用例:

@example
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.maximum_version = ssl.TLSVersion.TLSv1_2
context.set_ciphers('PSK')

# A simple lambda:
psk = bytes.fromhex('c0ffee')
context.set_psk_server_callback(lambda identity: psk)

# A table using the identity of the client:
psk_table = @{ 'ClientId_1': bytes.fromhex('c0ffee'),
              'ClientId_2': bytes.fromhex('facade')
@}
def callback(identity):
    return psk_table.get(identity, b'@w{'})
context.set_psk_server_callback(callback, 'ServerId_1')
@end example

This method will raise @ref{36b,,NotImplementedError} if @ref{39dd,,HAS_PSK} is
@code{False}.


Added in version 3.13.

@end deffn

@geindex certificates

@geindex X509 certificate

@node 証明書,使用例<28>,SSL コンテキスト,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl certificates}@anchor{39fc}@anchor{library/ssl ssl-certificates}@anchor{39f2}
@subsubsection 証明書


証明書を大まかに説明すると、公開鍵/秘密鍵システムの一種です。このシステムでは、各 `principal' (これはマシン、人、組織などです) は、ユニークな2つの暗号鍵を割り当てられます。1つは公開され、 `公開鍵(public key)' と呼ばれます。もう一方は秘密にされ、 `秘密鍵(private key)' と呼ばれます。 2つの鍵は関連しており、片方の鍵で暗号化したメッセージは、もう片方の鍵 `のみ' で復号できます。

証明書は2つの principal の情報を含んでいます。証明書は `subject' 名とその公開鍵を含んでいます。また、もう一つの principal である `発行者(issuer)' からの、 subject が本人であることと、その公開鍵が正しいことの宣言(statement)を含んでいます。発行者からの宣言は、その発行者の秘密鍵で署名されています。発行者の秘密鍵は発行者しか知りませんが、誰もがその発行者の公開鍵を利用して宣言を復号し、証明書内の別の情報と比較することで認証することができます。証明書はまた、その証明書が有効である期限に関する情報も含んでいます。この期限は "notBefore" と "notAfter" と呼ばれる2つのフィールドで表現されています。

Python において証明書を利用する場合、クライアントもサーバーも自分を証明するために証明書を利用することができます。ネットワーク接続の相手側に証明書の提示を要求する事ができ、そのクライアントやサーバーが認証を必要とするならその証明書を認証することができます。認証が失敗した場合、接続は例外を発生させます。認証は下位層のOpenSSLフレームワークが自動的に行います。アプリケーションは認証機構について意識する必要はありません。しかし、アプリケーションは認証プロセスのために幾つかの証明書を提供する必要があるかもしれません。

Python は証明書を格納したファイルを利用します。そのファイルは "PEM" (
@geindex RFC; RFC 1422
RFC 1422@footnote{https://datatracker.ietf.org/doc/html/rfc1422.html} 参照) フォーマットという、ヘッダー行とフッター行の間にbase-64エンコードされた形をとっている必要があります。

@example
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
@end example

@menu
* 証明書チェイン:: 
* CA 証明書:: 
* 秘密鍵と証明書の組み合わせ:: 
* 自己署名証明書:: 

@end menu

@node 証明書チェイン,CA 証明書,,証明書
@anchor{library/ssl certificate-chains}@anchor{39fd}
@subsubsection 証明書チェイン


Pythonが利用する証明書を格納したファイルは、ときには `証明書チェイン(certificate chain)' と呼ばれる証明書のシーケンスを格納します。このチェインの先頭には、まずクライアントやサーバーである principal の証明書を置き、それ以降には、その証明書の発行者(issuer)の証明書などを続け、最後に証明対象(subject)と発行者が同じ `自己署名(self-signed)' 証明書で終わります。この最後の証明書は `ルート証明書(root certificate' と呼ばれます。これらの証明書チェインは単純に1つの証明書ファイルに結合してください。例えば、3つの証明書からなる証明書チェインがある場合、私たちのサーバーの証明書から、私たちのサーバーに署名した認証局の証明書、そして認証局の証明書を発行した機関のルート証明書と続きます:

@example
-----BEGIN CERTIFICATE-----
... (certificate for your server)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the certificate for the CA)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the root certificate for the CA's issuer)...
-----END CERTIFICATE-----
@end example

@node CA 証明書,秘密鍵と証明書の組み合わせ,証明書チェイン,証明書
@anchor{library/ssl ca-certificates}@anchor{39fe}
@subsubsection CA 証明書


もし相手から送られてきた証明書の認証をしたい場合、信頼している各発行者の証明書チェインが入った "CA certs" ファイルを提供する必要があります。繰り返しますが、このファイルは単純に、各チェインを結合しただけのものです。認証のために、Pythonはそのファイルの中の最初にマッチしたチェインを利用します。@ref{11b4,,SSLContext.load_default_certs()} を呼び出すことでプラットフォームの証明書ファイルも使われますが、これは @ref{480,,create_default_context()} によって自動的に行われます。

@node 秘密鍵と証明書の組み合わせ,自己署名証明書,CA 証明書,証明書
@anchor{library/ssl combined-key-and-certificate}@anchor{39ff}
@subsubsection 秘密鍵と証明書の組み合わせ


Often the private key is stored in the same file as the certificate; in this
case, only the @code{certfile} parameter to @ref{598,,SSLContext.load_cert_chain()}
needs to be passed.  If the private key is stored
with the certificate, it should come before the first certificate in
the certificate chain:

@example
-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
@end example

@node 自己署名証明書,,秘密鍵と証明書の組み合わせ,証明書
@anchor{library/ssl self-signed-certificates}@anchor{3a00}
@subsubsection 自己署名証明書


SSL暗号化接続サービスを提供するサーバーを建てる場合、適切な証明書を取得するには、認証局から買うなどの幾つかの方法があります。また、自己署名証明書を作るケースもあります。 OpenSSLを使って自己署名証明書を作るには、次のようにします。

@example
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key
.......++++++
.............................++++++
writing new private key to 'cert.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:MyState
Locality Name (eg, city) []:Some City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
Organizational Unit Name (eg, section) []:My Group
Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
Email Address []:ops@@myserver.mygroup.myorganization.com
%
@end example

自己署名証明書の欠点は、それ自身がルート証明書であり、他の人はその証明書を持っていない (そして信頼しない)ことです。

@node 使用例<28>,ノンブロッキングソケットについての注意事項,証明書,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl examples}@anchor{3a01}
@subsubsection 使用例


@menu
* SSLサポートをテストする:: 
* クライアントサイドの処理:: 
* サーバサイドの処理:: 

@end menu

@node SSLサポートをテストする,クライアントサイドの処理,,使用例<28>
@anchor{library/ssl testing-for-ssl-support}@anchor{3a02}
@subsubsection SSLサポートをテストする


インストールされているPythonがSSLをサポートしているかどうかをテストするために、ユーザーコードは次のイディオムを利用することができます。

@example
try:
    import ssl
except ImportError:
    pass
else:
    ...  # do something that requires SSL support
@end example

@node クライアントサイドの処理,サーバサイドの処理,SSLサポートをテストする,使用例<28>
@anchor{library/ssl client-side-operation}@anchor{3a03}
@subsubsection クライアントサイドの処理


この例では、自動的に証明書の検証を行うことを含む望ましいセキュリティ設定でクライアントソケットの SSL コンテキストを作ります:

@example
>>> context = ssl.create_default_context()
@end example

自分自身でセキュリティ設定を調整したい場合、コンテキストを一から作ることはできます (ただし、正しくない設定をしてしまいがちなことに注意してください):

@example
>>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
@end example

(このスニペットはすべての CA 証明書が @code{/etc/ssl/certs/ca-bundle.crt} にバンドルされていることを仮定しています; もし違っていればエラーになりますので、適宜修正してください)

The @ref{a72,,PROTOCOL_TLS_CLIENT} protocol configures the context for cert
validation and hostname verification. @ref{39b0,,verify_mode} is
set to @ref{39b1,,CERT_REQUIRED} and @ref{39c4,,check_hostname} is set
to @code{True}. All other protocols create SSL contexts with insecure defaults.

When you use the context to connect to a server, @ref{39b1,,CERT_REQUIRED}
and @ref{39c4,,check_hostname} validate the server certificate: it
ensures that the server certificate was signed with one of the CA
certificates, checks the signature for correctness, and verifies other
properties like validity and identity of the hostname:

@example
>>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
...                            server_hostname="www.python.org")
>>> conn.connect(("www.python.org", 443))
@end example

そして証明書を持ってくることができます:

@example
>>> cert = conn.getpeercert()
@end example

証明書が、期待しているサービス (つまり、 HTTPS ホスト @code{www.python.org}) の身元を特定していることを視覚的に点検してみましょう:

@example
>>> pprint.pprint(cert)
@{'OCSP': ('http://ocsp.digicert.com',),
 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
                           'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
 'issuer': ((('countryName', 'US'),),
            (('organizationName', 'DigiCert Inc'),),
            (('organizationalUnitName', 'www.digicert.com'),),
            (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
 'notAfter': 'Sep  9 12:00:00 2016 GMT',
 'notBefore': 'Sep  5 00:00:00 2014 GMT',
 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
 'subject': ((('businessCategory', 'Private Organization'),),
             (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
             (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
             (('serialNumber', '3359300'),),
             (('streetAddress', '16 Allen Rd'),),
             (('postalCode', '03894-4801'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'NH'),),
             (('localityName', 'Wolfeboro'),),
             (('organizationName', 'Python Software Foundation'),),
             (('commonName', 'www.python.org'),)),
 'subjectAltName': (('DNS', 'www.python.org'),
                    ('DNS', 'python.org'),
                    ('DNS', 'pypi.org'),
                    ('DNS', 'docs.python.org'),
                    ('DNS', 'testpypi.org'),
                    ('DNS', 'bugs.python.org'),
                    ('DNS', 'wiki.python.org'),
                    ('DNS', 'hg.python.org'),
                    ('DNS', 'mail.python.org'),
                    ('DNS', 'packaging.python.org'),
                    ('DNS', 'pythonhosted.org'),
                    ('DNS', 'www.pythonhosted.org'),
                    ('DNS', 'test.pythonhosted.org'),
                    ('DNS', 'us.pycon.org'),
                    ('DNS', 'id.python.org')),
 'version': 3@}
@end example

SSL チャネルは今や確立されて証明書が検証されているので、サーバとのお喋りを続けることができます:

@example
>>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
>>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
[b'HTTP/1.1 200 OK',
 b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
 b'Server: nginx',
 b'Content-Type: text/html; charset=utf-8',
 b'X-Frame-Options: SAMEORIGIN',
 b'Content-Length: 45679',
 b'Accept-Ranges: bytes',
 b'Via: 1.1 varnish',
 b'Age: 2188',
 b'X-Served-By: cache-lcy1134-LCY',
 b'X-Cache: HIT',
 b'X-Cache-Hits: 11',
 b'Vary: Cookie',
 b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
 b'Connection: close',
 b'@w{'},
 b'@w{'}]
@end example

このドキュメントの下の方の、 @ref{3895,,セキュリティで考慮すべき点} に関する議論を参照してください。

@node サーバサイドの処理,,クライアントサイドの処理,使用例<28>
@anchor{library/ssl server-side-operation}@anchor{3a04}
@subsubsection サーバサイドの処理


サーバサイドの処理では、通常、サーバー証明書と秘密鍵がそれぞれファイルに格納された形で必要です。最初に秘密鍵と証明書が保持されたコンテキストを作成し、クライアントがあなたの信憑性をチェックできるようにします。そののちにソケットを開き、ポートにバインドし、そのソケットの @code{listen()} を呼び、クライアントからの接続を待ちます。

@example
import socket, ssl

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")

bindsocket = socket.socket()
bindsocket.bind(('myaddr.example.com', 10023))
bindsocket.listen(5)
@end example

クライアントが接続してきた場合、 @code{accept()} を呼んで新しいソケットを作成し、接続のためにサーバサイドの SSL ソケットを、コンテキストの @ref{748,,SSLContext.wrap_socket()} メソッドで作ります:

@example
while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = context.wrap_socket(newsocket, server_side=True)
    try:
        deal_with_client(connstream)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()
@end example

そして、 @code{connstream} からデータを読み、クライアントと切断する(あるいはクライアントが切断してくる)まで何か処理をします。

@example
def deal_with_client(connstream):
    data = connstream.recv(1024)
    # empty data means the client is finished with us
    while data:
        if not do_something(connstream, data):
            # we'll assume do_something returns False
            # when we're finished with client
            break
        data = connstream.recv(1024)
    # finished with client
@end example

そして新しいクライアント接続のために listen に戻ります。 (もちろん現実のサーバは、おそらく個々のクライアント接続ごとに別のスレッドで処理するか、ソケットを @ref{39b6,,ノンブロッキングモード} にし、イベントループを使うでしょう。)

@node ノンブロッキングソケットについての注意事項,メモリ BIO サポート<2>,使用例<28>,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl notes-on-non-blocking-sockets}@anchor{3a05}@anchor{library/ssl ssl-nonblocking}@anchor{39b6}
@subsubsection ノンブロッキングソケットについての注意事項


SSL ソケットはノンブロッキングモードにおいては、普通のソケットとは少し違った振る舞いをします。ですのでノンブロッキングソケットとともに使う場合、いくつか気をつけなければならない事項があります:


@itemize -

@item 
ほとんどの @ref{ae7,,SSLSocket} のメソッドは I/O 操作がブロックすると @ref{235,,BlockingIOError} ではなく @ref{106a,,SSLWantWriteError} か @ref{1069,,SSLWantReadError} のどちらかを送出します。 @ref{1069,,SSLWantReadError} は下層のソケットで読み出しが必要な場合に送出され、 @ref{106a,,SSLWantWriteError} は下層のソケットで書き込みが必要な場合に送出されます。SSL ソケットに対して `書き込み' を試みると下層のソケットから最初に `読み出す' 必要があるかもしれず、SSL ソケットに対して `読み出し' を試みると下層のソケットに先に `書き込む' 必要があるかもしれないことに注意してください。


バージョン 3.5 で変更: 以前の Python バージョンでは、 @code{SSLSocket.send()} メソッドは @ref{106a,,SSLWantWriteError} または @ref{1069,,SSLWantReadError} を送出するのではなく、ゼロを返していました。


@item 
@ref{fa0,,select()} 呼び出しは OS レベルでのソケットが読み出し可能(または書き込み可能)になったことを教えてくれますが、上位の SSL レイヤーでの十分なデータがあることを意味するわけではありません。例えば、SSL フレームの一部が届いただけかもしれません。ですから、 @code{SSLSocket.recv()} と @code{SSLSocket.send()} の失敗を処理することに備え、ほかの @ref{fa0,,select()} 呼び出し後にリトライしなければなりません。

@item 
反対に、SSL レイヤーは独自の枠組みを持っているため、@ref{fa0,,select()} が気付かない読み出し可能なデータを SSL ソケットが持っている場合があります。したがって、入手可能な可能性のあるデータをすべて引き出すために最初に @code{SSLSocket.recv()} を呼び出し、次にそれでもまだ必要な場合にだけ @ref{fa0,,select()} 呼び出しでブロックすべきです。

(当然のことながら、ほかのプリミティブ、例えば @ref{30a9,,poll()} や @ref{c7,,selectors} モジュール内のものを使う際にも似た但し書きが付きます)

@item 
SSL ハンドシェイクそのものがノンブロッキングになります: @ref{106d,,SSLSocket.do_handshake()} メソッドは成功するまでリトライしなければなりません。 @ref{fa0,,select()} を用いてソケットの準備が整うのを待つためには、およそ以下のようにします:

@example
while True:
    try:
        sock.do_handshake()
        break
    except ssl.SSLWantReadError:
        select.select([sock], [], [])
    except ssl.SSLWantWriteError:
        select.select([], [sock], [])
@end example
@end itemize


@subsubheading 参考


The @ref{b,,asyncio} module supports @ref{39b6,,non-blocking SSL sockets} and provides a higher level @ref{37b9,,Streams API}.
It polls for events using the @ref{c7,,selectors} module and
handles @ref{106a,,SSLWantWriteError}, @ref{1069,,SSLWantReadError} and
@ref{235,,BlockingIOError} exceptions. It runs the SSL handshake asynchronously
as well.


@node メモリ BIO サポート<2>,SSL セッション,ノンブロッキングソケットについての注意事項,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl memory-bio-support}@anchor{3a06}
@subsubsection メモリ BIO サポート



Added in version 3.5.


Python 2.6 で SSL モジュールが導入されて以降、@ref{ae7,,SSLSocket} クラスは、以下の互いに関連するが別々の機能を提供してきました。


@itemize -

@item 
SSL プロトコル処理

@item 
ネットワーク IO
@end itemize

ネットワーク IO API は、@ref{fa1,,socket.socket} が提供するものと同じです。@ref{ae7,,SSLSocket} も、そのクラスから継承しています。これにより、SSL ソケットは標準のソケットをそっくりそのまま置き換えるものとして使用できるため、既存のアプリケーションを SSL に対応させるのが非常に簡単になります。

SSL プロトコルの処理とネットワーク IO を組み合わせた場合、通常は問題なく動作しますが、問題が発生する場合があります。一例を挙げると、非同期 IO フレームワークが別の多重化モデルを使用する場合、これは @ref{fa1,,socket.socket} と内部 OpenSSL ソケット IO ルーティンが想定する「ファイル記述子上の select/poll」モデル（準備状態ベース）とは異なります。これは、このモデルが非効率的になる Windows などのプラットフォームに主に該当します。そのため、スコープを限定した @ref{ae7,,SSLSocket} の変種、 @ref{d7a,,SSLObject} が提供されています。

@geindex SSLObject (ssl のクラス)
@anchor{library/ssl ssl SSLObject}@anchor{d7a}
@deffn {クラス} ssl.SSLObject

ネットワーク IO メソッドを含まない SSL プロトコルインスタンスを表す、スコープを限定した @ref{ae7,,SSLSocket} の変種です。一般的にこ、のクラスを使用するのは、メモリバッファを通じて SSL のための非同期 IO を実装するフレームワーク作成者です。

このクラスは、OpenSSL が実装する低水準 SSL オブジェクトの上にインターフェースを実装します。このオブジェクトは SSL 接続の状態をキャプチャしますが、ネットワーク IO 自体は提供しません。IO は、OpenSSL の IO 抽象レイヤである別の「BIO」オブジェクトを通じて実行する必要があります。

このクラスには公開されたコンストラクタがありません。@ref{d7a,,SSLObject} インスタンスは、 @ref{d7b,,wrap_bio()} メソッドを使用して作成しなければなりません。このメソッドは、@ref{d7a,,SSLObject} インスタンスを作成し、2 つの BIO に束縛します。`incoming' BIO は、Python から SSL プロトコルインスタンスにデータを渡すために使用され、`outgoing' BIO は、データを反対向きに渡すために使用されます。

次のメソッドがサポートされています:


@itemize -

@item 
@ref{39ed,,context}

@item 
@ref{39ef,,server_side}

@item 
@ref{d78,,server_hostname}

@item 
@ref{193d,,session}

@item 
@ref{39f0,,session_reused}

@item 
@ref{106e,,read()}

@item 
@ref{106f,,write()}

@item 
@ref{11ba,,getpeercert()}

@item 
@ref{195c,,get_verified_chain()}

@item 
@ref{195d,,get_unverified_chain()}

@item 
@ref{1065,,selected_alpn_protocol()}

@item 
@ref{a74,,selected_npn_protocol()}

@item 
@ref{38da,,cipher()}

@item 
@ref{106c,,shared_ciphers()}

@item 
@ref{135d,,compression()}

@item 
@ref{39ee,,pending()}

@item 
@ref{106d,,do_handshake()}

@item 
@ref{c27,,verify_client_post_handshake()}

@item 
@ref{39ec,,unwrap()}

@item 
@ref{135c,,get_channel_binding()}

@item 
@ref{1068,,version()}
@end itemize

@ref{ae7,,SSLSocket} と比較すると、このオブジェクトでは以下の機能が不足しています。


@itemize -

@item 
Any form of network IO; @code{recv()} and @code{send()} read and write only to
the underlying @ref{1062,,MemoryBIO} buffers.

@item 
`do_handshake_on_connect' 機構はありません。必ず手動で @ref{106d,,do_handshake()} を呼んで、ハンドシェイクを開始する必要があります。

@item 
`suppress_ragged_eofs' は処理されません。プロトコルに違反するファイル末尾状態は、 @ref{1ab8,,SSLEOFError} 例外を通じて報告されます。

@item 
@ref{39ec,,unwrap()} メソッドの呼び出しは、下層のソケットを返す SSL ソケットとは異なり、何も返しません。

@item 
@ref{11b9,,SSLContext.set_servername_callback()} に渡される `server_name_callback' コールバックは、1 つ目の引数として @ref{ae7,,SSLSocket} インスタンスではなく @ref{d7a,,SSLObject} インスタンスを受け取ります。
@end itemize

@ref{d7a,,SSLObject} の使用に関する注意:


@itemize -

@item 
@ref{d7a,,SSLObject} 上のすべての IO は @ref{39b6,,non-blocking} です。例えば、@ref{106e,,read()} は入力 BIO が持つデータよりも多くのデータを必要とする場合、@ref{1069,,SSLWantReadError} を送出します。
@end itemize


バージョン 3.7 で変更: @ref{d7a,,SSLObject} instances must be created with
@ref{d7b,,wrap_bio()}. In earlier versions, it was possible to
create instances directly. This was never documented or officially
supported.

@end deffn

SSLObject は、メモリバッファを使用して外界と通信します。@ref{1062,,MemoryBIO} クラスは、以下のように OpenSSL メモリ BIO (Basic IO) オブジェクトをラップし、この目的に使用できるメモリバッファを提供します。

@geindex MemoryBIO (ssl のクラス)
@anchor{library/ssl ssl MemoryBIO}@anchor{1062}
@deffn {クラス} ssl.MemoryBIO

Python と SSL プロトコルインスタンス間でデータをやり取りするために使用できるメモリバッファ。

@geindex pending (ssl.MemoryBIO の属性)
@anchor{library/ssl ssl MemoryBIO pending}@anchor{3a07}
@deffn {の属性} pending

現在メモリバッファ中にあるバイト数を返します。
@end deffn

@geindex eof (ssl.MemoryBIO の属性)
@anchor{library/ssl ssl MemoryBIO eof}@anchor{3a08}
@deffn {の属性} eof

メモリ BIOが現在ファイルの末尾にあるかを表す真偽値です。
@end deffn

@geindex read() (ssl.MemoryBIO のメソッド)
@anchor{library/ssl ssl MemoryBIO read}@anchor{3a09}
@deffn {メソッド} read (n=-1, /)

メモリバッファから最大 `n' 読み取ります。`n' が指定されていないか、負値の場合、すべてのバイトが返されます。
@end deffn

@geindex write() (ssl.MemoryBIO のメソッド)
@anchor{library/ssl ssl MemoryBIO write}@anchor{3a0a}
@deffn {メソッド} write (buf, /)

`buf' からメモリ BIO にバイトを書き込みます。`buf' 引数は、バッファプロトコルをサポートするオブジェクトでなければなりません。

戻り値は、書き込まれるバイト数であり、常に `buf' の長さと等しくなります。
@end deffn

@geindex write_eof() (ssl.MemoryBIO のメソッド)
@anchor{library/ssl ssl MemoryBIO write_eof}@anchor{3a0b}
@deffn {メソッド} write_eof ()

EOF マーカーをメモリ BIO に書き込みます。このメソッドが呼び出された後に @ref{3a0a,,write()} を呼ぶことはできません。@ref{3a08,,eof} 属性は、バッファ内のすべてのデータが読み出された後に True になります。
@end deffn
@end deffn

@node SSL セッション,セキュリティで考慮すべき点<3>,メモリ BIO サポート<2>,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl ssl-session}@anchor{3a0c}
@subsubsection SSL セッション



Added in version 3.6.


@geindex SSLSession (ssl のクラス)
@anchor{library/ssl ssl SSLSession}@anchor{ed9}
@deffn {クラス} ssl.SSLSession

@ref{193d,,session} が使用するセッションオブジェクトです。

@geindex id (ssl.SSLSession の属性)
@anchor{library/ssl ssl SSLSession id}@anchor{3a0d}
@deffn {の属性} id
@end deffn

@geindex time (ssl.SSLSession の属性)
@anchor{library/ssl ssl SSLSession time}@anchor{3a0e}
@deffn {の属性} time
@end deffn

@geindex timeout (ssl.SSLSession の属性)
@anchor{library/ssl ssl SSLSession timeout}@anchor{3a0f}
@deffn {の属性} timeout
@end deffn

@geindex ticket_lifetime_hint (ssl.SSLSession の属性)
@anchor{library/ssl ssl SSLSession ticket_lifetime_hint}@anchor{3a10}
@deffn {の属性} ticket_lifetime_hint
@end deffn

@geindex has_ticket (ssl.SSLSession の属性)
@anchor{library/ssl ssl SSLSession has_ticket}@anchor{3a11}
@deffn {の属性} has_ticket
@end deffn
@end deffn

@node セキュリティで考慮すべき点<3>,TLS 1 3,SSL セッション,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl security-considerations}@anchor{3a12}@anchor{library/ssl ssl-security}@anchor{3895}
@subsubsection セキュリティで考慮すべき点


@menu
* 最善のデフォルト値:: 
* 手動での設定:: 
* マルチプロセス化:: 

@end menu

@node 最善のデフォルト値,手動での設定,,セキュリティで考慮すべき点<3>
@anchor{library/ssl best-defaults}@anchor{3a13}
@subsubsection 最善のデフォルト値


`クライアントでの使用' では、セキュリティポリシーによる特殊な要件がない限りは、 @ref{480,,create_default_context()} 関数を使用して SSL コンテキストを作成することを強くお勧めします。この関数は、システムの信頼済み CA 証明書をロードし、証明書の検証とホスト名のチェックを有効化し、十分にセキュアなプロトコルと暗号を選択しようとします。

例として、 @ref{b27,,smtplib.SMTP} クラスを使用して SMTP サーバーに対して信頼できるセキュアな接続を行う方法を以下に示します:

@example
>>> import ssl, smtplib
>>> smtp = smtplib.SMTP("mail.python.org", port=587)
>>> context = ssl.create_default_context()
>>> smtp.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')
@end example

接続にクライアントの証明書が必要な場合、 @ref{598,,SSLContext.load_cert_chain()} によって追加できます。

対照的に、自分自身で @ref{357,,SSLContext} クラスのコンストラクタを呼び出すことによって SSL コンテキストを作ると、デフォルトでは証明書検証もホスト名チェックも有効になりません。自分で設定を行う場合は、十分なセキュリティレベルを達成するために、以下のパラグラフをお読みください。

@node 手動での設定,マルチプロセス化,最善のデフォルト値,セキュリティで考慮すべき点<3>
@anchor{library/ssl manual-settings}@anchor{3a14}
@subsubsection 手動での設定


@menu
* 証明書の検証:: 
* プロトコルのバージョン:: 
* 暗号の選択:: 

@end menu

@node 証明書の検証,プロトコルのバージョン,,手動での設定
@anchor{library/ssl verifying-certificates}@anchor{3a15}
@subsubsection 証明書の検証


When calling the @ref{357,,SSLContext} constructor directly,
@ref{39c2,,CERT_NONE} is the default.  Since it does not authenticate the other
peer, it can be insecure, especially in client mode where most of the time you
would like to ensure the authenticity of the server you're talking to.
Therefore, when in client mode, it is highly recommended to use
@ref{39b1,,CERT_REQUIRED}.  However, it is in itself not sufficient; you also
have to check that the server certificate, which can be obtained by calling
@ref{11ba,,SSLSocket.getpeercert()}, matches the desired service.  For many
protocols and applications, the service can be identified by the hostname.
This common check is automatically performed when
@ref{39c4,,SSLContext.check_hostname} is enabled.


バージョン 3.7 で変更: Hostname matchings is now performed by OpenSSL. Python no longer uses
@code{match_hostname()}.


サーバモードにおいて、(より上位のレベルでの認証メカニズムではなく) SSL レイヤーを使ってあなたのクライアントを認証したいならば、 @ref{39b1,,CERT_REQUIRED} を指定して同じようにクライアントの証明書を検証すべきでしょう。

@node プロトコルのバージョン,暗号の選択,証明書の検証,手動での設定
@anchor{library/ssl protocol-versions}@anchor{3a16}
@subsubsection プロトコルのバージョン


SSL バージョン 2 と 3 は安全性に欠けると考えられており、使用するのは危険です。クライアントとサーバ間の互換性を最大限に確保したい場合、プロトコルバージョンとして @ref{a72,,PROTOCOL_TLS_CLIENT} または @ref{a73,,PROTOCOL_TLS_SERVER} を使用してください。 SSLv2 と SSLv3 はデフォルトで無効になっています。

@example
>>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> client_context.minimum_version = ssl.TLSVersion.TLSv1_3
>>> client_context.maximum_version = ssl.TLSVersion.TLSv1_3
@end example

The SSL context created above will only allow TLSv1.3 and later (if
supported by your system) connections to a server. @ref{a72,,PROTOCOL_TLS_CLIENT}
implies certificate validation and hostname checks by default. You have to
load certificates into the context.

@node 暗号の選択,,プロトコルのバージョン,手動での設定
@anchor{library/ssl cipher-selection}@anchor{3a17}
@subsubsection 暗号の選択


If you have advanced security requirements, fine-tuning of the ciphers
enabled when negotiating a SSL session is possible through the
@ref{39f3,,SSLContext.set_ciphers()} method.  Starting from Python 3.2.3, the
ssl module disables certain weak ciphers by default, but you may want
to further restrict the cipher choice. Be sure to read OpenSSL's documentation
about the cipher list format@footnote{https://docs.openssl.org/1.1.1/man1/ciphers/#cipher-list-format}.
If you want to check which ciphers are enabled by a given cipher list, use
@ref{eda,,SSLContext.get_ciphers()} or the @code{openssl ciphers} command on your
system.

@node マルチプロセス化,,手動での設定,セキュリティで考慮すべき点<3>
@anchor{library/ssl multi-processing}@anchor{3a18}
@subsubsection マルチプロセス化


If using this module as part of a multi-processed application (using,
for example the @ref{98,,multiprocessing} or @ref{24,,concurrent.futures} modules),
be aware that OpenSSL's internal random number generator does not properly
handle forked processes.  Applications must change the PRNG state of the
parent process if they use any SSL feature with @ref{4b5,,os.fork()}.  Any
successful call of @ref{39bc,,RAND_add()} or @ref{747,,RAND_bytes()} is
sufficient.

@node TLS 1 3,,セキュリティで考慮すべき点<3>,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー
@anchor{library/ssl ssl-tlsv1-3}@anchor{d79}@anchor{library/ssl tls-1-3}@anchor{3a19}
@subsubsection TLS 1.3



Added in version 3.7.


The TLS 1.3 protocol behaves slightly differently than previous version
of TLS/SSL. Some new TLS 1.3 features are not yet available.


@itemize -

@item 
TLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and
ChaCha20 cipher suites are enabled by default.  The method
@ref{39f3,,SSLContext.set_ciphers()} cannot enable or disable any TLS 1.3
ciphers yet, but @ref{eda,,SSLContext.get_ciphers()} returns them.

@item 
Session tickets are no longer sent as part of the initial handshake and
are handled differently.  @ref{193d,,SSLSocket.session} and @ref{ed9,,SSLSession}
are not compatible with TLS 1.3.

@item 
Client-side certificates are also no longer verified during the initial
handshake.  A server can request a certificate at any time.  Clients
process certificate requests while they send or receive application data
from the server.

@item 
TLS 1.3 features like early data, deferred TLS client cert request,
signature algorithm configuration, and rekeying are not supported yet.
@end itemize


@subsubheading 参考



@table @asis

@item @ref{fa1,,socket.socket} クラス

下位レイヤーの @ref{d1,,socket} クラスのドキュメント

@item SSL/TLS Strong Encryption: An Introduction@footnote{https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html}

Apache HTTPサーバのドキュメンテーションのイントロ

@geindex RFC; RFC 1422

@item RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management@footnote{https://datatracker.ietf.org/doc/html/rfc1422.html}

Steve Kent

@geindex RFC; RFC 4086

@item RFC 4086: Randomness Requirements for Security@footnote{https://datatracker.ietf.org/doc/html/rfc4086.html}

Donald E. Eastlake, Jeffrey I. Schiller, Steve Crocker

@geindex RFC; RFC 5280

@item RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile@footnote{https://datatracker.ietf.org/doc/html/rfc5280.html}

David Cooper et al.

@geindex RFC; RFC 5246

@item RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2@footnote{https://datatracker.ietf.org/doc/html/rfc5246.html}

Tim Dierks and Eric Rescorla.

@geindex RFC; RFC 6066

@item RFC 6066: Transport Layer Security (TLS) Extensions@footnote{https://datatracker.ietf.org/doc/html/rfc6066.html}

Donald E. Eastlake

@item IANA TLS: Transport Layer Security (TLS) Parameters@footnote{https://www.iana.org/assignments/tls-parameters/tls-parameters.xml}

IANA

@geindex RFC; RFC 7525

@item RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)@footnote{https://datatracker.ietf.org/doc/html/rfc7525.html}

IETF

@item Mozilla's Server Side TLS recommendations@footnote{https://wiki.mozilla.org/Security/Server_Side_TLS}

Mozilla
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node select --- I/O 完了の待機,selectors --- 高水準の I/O 多重化,ssl --- ソケットオブジェクト用の TLS/SSL ラッパー,ネットワーク通信とプロセス間通信
@anchor{library/select doc}@anchor{3a1a}@anchor{library/select module-select}@anchor{c6}@anchor{library/select select-waiting-for-i-o-completion}@anchor{3a1b}@anchor{library/select translation-repo}@anchor{3a1c}
@subsection @code{select} --- I/O 完了の待機


@geindex module; select


__________________________________________________________________


このモジュールでは、ほとんどのオペレーティングシステムで利用可能な @code{select()} および @code{poll()} 関数、Solaris やその派生で利用可能な @code{devpoll()} 、Linux 2.5+ で利用可能な @code{epoll()} 、多くのBSDで利用可能な @code{kqueue()} 関数に対するアクセスを提供しています。 Windows 上ではソケットに対してしか動作しないので注意してください; その他のオペレーティングシステムでは、他のファイル形式でも (特に Unixではパイプにも) 動作します。通常のファイルに対して適用し、最後にファイルを読み出した時から内容が増えているかを決定するために使うことはできません。

@cartouche
@quotation 注釈 
The @ref{c7,,selectors} module allows high-level and efficient I/O
multiplexing, built upon the @code{select} module primitives. Users are
encouraged to use the @ref{c7,,selectors} module instead, unless they want
precise control over the OS-level primitives used.
@end quotation
@end cartouche

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

このモジュールは以下を定義します:

@geindex error
@anchor{library/select select error}@anchor{1262}
@deffn {例外} select.error

@ref{2c0,,OSError} の非推奨のエイリアスです。


バージョン 3.3 で変更: 
@geindex Python Enhancement Proposals; PEP 3151
PEP 3151@footnote{https://peps.python.org/pep-3151/} に基づき、このクラスは @ref{2c0,,OSError} のエイリアスになりました。

@end deffn

@geindex devpoll() (select モジュール)
@anchor{library/select select devpoll}@anchor{1198}
@deffn {の関数} select.devpoll ()

(Solaris およびその派生でのみサポートされています)
@code{/dev/poll} ポーリングオブジェクトを返します。
ポーリングオブジェクトが提供しているメソッドについては @ref{3a1d,,ポーリングオブジェクト} 節を参照してください。

@code{devpoll()} オブジェクトはインスタンス化時に許されるファイル記述子の数にリンクされます。プログラムがこの値を減らす場合 @code{devpoll()} は失敗します。プログラムがこの値を増やす場合 @code{devpoll()} は有効なファイル記述子の不完全なリストを返すことがあります。

新しいファイル記述子は @ref{10fc,,継承不可} です。


Added in version 3.3.



バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。

@end deffn

@geindex epoll() (select モジュール)
@anchor{library/select select epoll}@anchor{1196}
@deffn {の関数} select.epoll (sizehint=-1, flags=0)

(Linux 2.5.44 以降でのみサポート) エッジポーリング (edge polling) オブジェクトを返します。
このオブジェクトは、 I/O イベントのエッジトリガもしくはレベルトリガインターフェースとして使えます。

`sizehint' informs epoll about the expected number of events to be
registered.  It must be positive, or @code{-1} to use the default. It is only
used on older systems where @code{epoll_create1()} is not available;
otherwise it has no effect (though its value is still checked).

`flags' is deprecated and completely ignored.  However, when supplied, its
value must be @code{0} or @code{select.EPOLL_CLOEXEC}, otherwise @code{OSError} is
raised.

エッジポーリングオブジェクトが提供しているメソッドについては @ref{3a1e,,エッジおよびレベルトリガポーリング (epoll) オブジェクト} 節を参照してください。

@code{epoll} オブジェクトはコンテキストマネジメントプロトコルをサポートしています。
@ref{186,,with} 文内で使用された場合、新たなファイル記述子はブロックの最後で自動的に閉じられます。

新しいファイル記述子は @ref{10fc,,継承不可} です。


バージョン 3.3 で変更: `flags' 引数が追加されました。



バージョン 3.4 で変更: @ref{186,,with} 文のサポートが追加されました。新しいファイル記述子が継承不可になりました。



バージョン 3.4 で非推奨: `flags' パラメータ。
現在ではデフォルトで @code{select.EPOLL_CLOEXEC} が使われます。
ファイルディスクリプタを継承可能にするには @ref{10fe,,os.set_inheritable()} を使ってください。

@end deffn

@geindex poll() (select モジュール)
@anchor{library/select select poll}@anchor{30a9}
@deffn {の関数} select.poll ()

(全てのオペレーティングシステムでサポートされているわけではありません) ポーリングオブジェクトを返します。このオブジェクトはファイル記述子を登録したり登録解除したりすることができ、ファイル記述子に対する I/O イベント発生をポーリングすることができます; ポーリングオブジェクトが提供しているメソッドについては @ref{3a1d,,ポーリングオブジェクト} 節を参照してください。
@end deffn

@geindex kqueue() (select モジュール)
@anchor{library/select select kqueue}@anchor{1a43}
@deffn {の関数} select.kqueue ()

(BSD でのみサポート) カーネルキュー(kernel queue)オブジェクトを返します。カーネルキューオブジェクトが提供しているメソッドについては、 @ref{3a1f,,kqueue オブジェクト} 節を参照してください。

新しいファイル記述子は @ref{10fc,,継承不可} です。


バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。

@end deffn

@geindex kevent() (select モジュール)
@anchor{library/select select kevent}@anchor{3a20}
@deffn {の関数} select.kevent (ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)

(BSD でのみサポート) カーネルイベント(kernel event)オブジェクトを返します。カーネルイベントオブジェクトが提供しているメソッドについては、 @ref{3a21,,kevent オブジェクト} 節を参照してください。
@end deffn

@geindex select() (select モジュール)
@anchor{library/select select select}@anchor{fa0}
@deffn {の関数} select.select (rlist, wlist, xlist, timeout=None)

This is a straightforward interface to the Unix @code{select()} system call.
The first three arguments are iterables of 'waitable objects': either
integers representing file descriptors or objects with a parameterless method
named @ref{17ad,,fileno()} returning such an integer:


@itemize *

@item 
`rlist': 読み込み可能になるまで待機

@item 
`wlist': 書き込み可能になるまで待機

@item 
`xlist': "例外状態 (exceptional condition)" になるまで待機 ("例外状態" については、システムのマニュアルページを参照してください)
@end itemize

Empty iterables are allowed, but acceptance of three empty iterables is
platform-dependent. (It is known to work on Unix but not on Windows.)  The
optional `timeout' argument specifies a time-out as a floating-point number
in seconds.
When the `timeout' argument is omitted or @code{None}, the function blocks until
at least one file descriptor is ready.  A time-out value of zero specifies a
poll and never blocks.

戻り値は準備完了状態のオブジェクトからなる 3 つのリストです: したがってこのリストはそれぞれ関数の最初の 3 つの引数のサブセットになります。ファイル記述子のいずれも準備完了にならないままタイムアウトした場合、3 つの空のリストが返されます。

@geindex socket() (in module socket)
@geindex popen() (os モジュール)

イテラブルの中に含めることのできるオブジェクトは Python @ref{13db,,ファイルオブジェクト} (例えば @code{sys.stdin} や、 @ref{316,,open()} または @ref{31a,,os.popen()} が返すオブジェクト)、 @ref{fa1,,socket.socket()} が返すソケットオブジェクトです。 `ラッパー <wrapper>' クラスを自分で定義することもできます。この場合、適切な (まったくデタラメな数ではなく本物のファイル記述子を返す) @ref{17ad,,fileno()} メソッドを持つ必要があります。

@cartouche
@quotation 注釈 
@geindex WinSock

File objects on Windows are not acceptable, but sockets are.  On Windows,
the underlying @code{select()} function is provided by the WinSock
library, and does not handle file descriptors that don't originate from
WinSock.
@end quotation
@end cartouche


バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 @ref{f88,,InterruptedError} を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を見てください)。

@end deffn

@geindex PIPE_BUF (select モジュール)
@anchor{library/select select PIPE_BUF}@anchor{1423}
@deffn {データ} select.PIPE_BUF

The minimum number of bytes which can be written without blocking to a pipe
when the pipe has been reported as ready for writing by @ref{fa0,,select()},
@code{poll()} or another interface in this module.  This doesn't apply
to other kinds of file-like objects such as sockets.

この値は POSIX により少なくとも512であることが保証されています。

@ref{213f,,Availability}: Unix


Added in version 3.2.

@end deffn

@menu
* /dev/poll ポーリングオブジェクト:: 
* エッジおよびレベルトリガポーリング (epoll) オブジェクト: エッジおよびレベルトリガポーリング epoll オブジェクト. 
* ポーリングオブジェクト:: 
* kqueue オブジェクト:: 
* kevent オブジェクト:: 

@end menu

@node /dev/poll ポーリングオブジェクト,エッジおよびレベルトリガポーリング epoll オブジェクト,,select --- I/O 完了の待機
@anchor{library/select dev-poll-polling-objects}@anchor{3a22}@anchor{library/select devpoll-objects}@anchor{3a23}
@subsubsection @code{/dev/poll} ポーリングオブジェクト


Solaris and derivatives have @code{/dev/poll}. While @code{select()} is
`O'(`highest file descriptor') and @code{poll()} is `O'(`number of file
descriptors'), @code{/dev/poll} is `O'(`active file descriptors').

@code{/dev/poll} behaviour is very close to the standard @code{poll()}
object.

@geindex close() (select.devpoll のメソッド)
@anchor{library/select select devpoll close}@anchor{119a}
@deffn {メソッド} devpoll.close ()

ポーリングオブジェクトのファイル記述子を閉じます。


Added in version 3.4.

@end deffn

@geindex closed (select.devpoll の属性)
@anchor{library/select select devpoll closed}@anchor{119b}
@deffn {の属性} devpoll.closed

ポーリングオブジェクトが閉じている場合 @code{True} です。


Added in version 3.4.

@end deffn

@geindex fileno() (select.devpoll のメソッド)
@anchor{library/select select devpoll fileno}@anchor{1199}
@deffn {メソッド} devpoll.fileno ()

ポーリングオブジェクトのファイル記述子番号を返します。


Added in version 3.4.

@end deffn

@geindex register() (select.devpoll のメソッド)
@anchor{library/select select devpoll register}@anchor{3a24}
@deffn {メソッド} devpoll.register (fd[, eventmask])

ファイル記述子をポーリングオブジェクトに登録します。これ以降の @ref{30a9,,poll()} メソッド呼び出しでは、そのファイル記述子に処理待ち中の I/O イベントがあるかどうかを監視します。 `fd' は整数か、整数値を返す @ref{17ad,,fileno()} メソッドを持つオブジェクトを取ります。ファイルオブジェクトも @code{fileno()} を実装しているので、引数として使うことができます。

`eventmask' is an optional bitmask describing the type of events you want to
check for. The constants are the same as with @code{poll()}
object. The default value is a combination of the constants @code{POLLIN},
@code{POLLPRI}, and @code{POLLOUT}.

@cartouche
@quotation 警告 
Registering a file descriptor that's already registered is not an
error, but the result is undefined. The appropriate action is to
unregister or modify it first. This is an important difference
compared with @code{poll()}.
@end quotation
@end cartouche
@end deffn

@geindex modify() (select.devpoll のメソッド)
@anchor{library/select select devpoll modify}@anchor{3a25}
@deffn {メソッド} devpoll.modify (fd[, eventmask])

This method does an @ref{3a26,,unregister()} followed by a
@ref{3a24,,register()}. It is (a bit) more efficient than doing the same
explicitly.
@end deffn

@geindex unregister() (select.devpoll のメソッド)
@anchor{library/select select devpoll unregister}@anchor{3a26}
@deffn {メソッド} devpoll.unregister (fd)

ポーリングオブジェクトによって追跡中のファイル記述子を登録解除します。 @ref{3a24,,register()} メソッドと同様に、 `fd' は整数か、整数値を返す @ref{17ad,,fileno()} メソッドを持つオブジェクトを取ります。

登録されていないファイル記述子の削除を試みるのは安全に無視されます。
@end deffn

@geindex poll() (select.devpoll のメソッド)
@anchor{library/select select devpoll poll}@anchor{f9c}
@deffn {メソッド} devpoll.poll ([timeout])

登録されたファイル記述子に対してポーリングを行い、報告すべき I/O イベントまたはエラーの発生したファイル記述子毎に 2 要素のタプル @code{(fd, event)} からなるリストを返します。リストは空になることもあります。 `fd' はファイル記述子で、 `event' は該当するファイル記述子について報告されたイベントを表すビットマスクです --- 例えば @code{POLLIN} は入力待ちを示し、 @code{POLLOUT} はファイル記述子に対する書き込みが可能を示す、などです。空のリストは呼び出しがタイムアウトしたか、報告すべきイベントがどのファイル記述子でも発生しなかったことを示します。 `timeout' が与えられた場合、処理を戻すまで待機する時間の長さをミリ秒単位で指定します。 `timeout' が省略されたり、 -1 であったり、あるいは @ref{885,,None} の場合、そのポーリングオブジェクトが監視している何らかのイベントが発生するまでブロックします。


バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 @ref{f88,,InterruptedError} を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を見てください)。

@end deffn

@node エッジおよびレベルトリガポーリング epoll オブジェクト,ポーリングオブジェクト,/dev/poll ポーリングオブジェクト,select --- I/O 完了の待機
@anchor{library/select edge-and-level-trigger-polling-epoll-objects}@anchor{3a27}@anchor{library/select epoll-objects}@anchor{3a1e}
@subsubsection エッジおよびレベルトリガポーリング (epoll) オブジェクト


@quotation

@indicateurl{https://linux.die.net/man/4/epoll}

`eventmask'


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{EPOLLIN}

@tab

読み込み可能

@item

@code{EPOLLOUT}

@tab

書き込み可能

@item

@code{EPOLLPRI}

@tab

緊急の読み出しデータ

@item

@code{EPOLLERR}

@tab

設定された fd にエラー状態が発生した

@item

@code{EPOLLHUP}

@tab

設定された fd がハングアップした

@item

@code{EPOLLET}

@tab

エッジトリガ動作に設定する。デフォルトではレベルトリガ動作

@item

@code{EPOLLONESHOT}

@tab

1ショット動作に設定する。1回イベントが取り出されたら、その fd が内部で無効になる

@item

@code{EPOLLEXCLUSIVE}

@tab

関連づけられた fd にイベントがある場合、1 つの epoll オブジェクトのみを起こします。デフォルトでは (このフラグが設定されていない場合には)、fd に対してポーリングするすべての epoll オブジェクトを起こします。

@item

@code{EPOLLRDHUP}

@tab

ストリームソケットの他端が接続を切断したか、接続の書き込み側のシャットダウンを行った。

@item

@code{EPOLLRDNORM}

@tab

@code{EPOLLIN} と同じ

@item

@code{EPOLLRDBAND}

@tab

優先データバンドを読み込める。

@item

@code{EPOLLWRNORM}

@tab

@code{EPOLLOUT} と同じ

@item

@code{EPOLLWRBAND}

@tab

優先データに書き込みできる。

@item

@code{EPOLLMSG}

@tab

無視される。

@item

@code{EPOLLWAKEUP}

@tab

Prevents sleep during event waiting.

@end multitable



Added in version 3.6: @code{EPOLLEXCLUSIVE} was added.  It's only supported by Linux Kernel 4.5
or later.



Added in version 3.14: @code{EPOLLWAKEUP} was added. It's only supported by Linux Kernel 3.5
or later.

@end quotation

@geindex close() (select.epoll のメソッド)
@anchor{library/select select epoll close}@anchor{1197}
@deffn {メソッド} epoll.close ()

epoll オブジェクトの制御用ファイル記述子を閉じます。
@end deffn

@geindex closed (select.epoll の属性)
@anchor{library/select select epoll closed}@anchor{3a28}
@deffn {の属性} epoll.closed

epoll オブジェクトが閉じている場合 True です。
@end deffn

@geindex fileno() (select.epoll のメソッド)
@anchor{library/select select epoll fileno}@anchor{3a29}
@deffn {メソッド} epoll.fileno ()

制御用ファイル記述子の番号を返します。
@end deffn

@geindex fromfd() (select.epoll のメソッド)
@anchor{library/select select epoll fromfd}@anchor{3a2a}
@deffn {メソッド} epoll.fromfd (fd)

`fd' から epoll オブジェクトを作成します。
@end deffn

@geindex register() (select.epoll のメソッド)
@anchor{library/select select epoll register}@anchor{3a2b}
@deffn {メソッド} epoll.register (fd[, eventmask])

epoll オブジェクトにファイル記述子 `fd' を登録します。
@end deffn

@geindex modify() (select.epoll のメソッド)
@anchor{library/select select epoll modify}@anchor{3a2c}
@deffn {メソッド} epoll.modify (fd, eventmask)

登録されたファイル記述子変更します。
@end deffn

@geindex unregister() (select.epoll のメソッド)
@anchor{library/select select epoll unregister}@anchor{b53}
@deffn {メソッド} epoll.unregister (fd)

epoll オブジェクトから登録されたファイル記述子 `fd' を削除します。


バージョン 3.9 で変更: The method no longer ignores the @ref{b54,,EBADF} error.

@end deffn

@geindex poll() (select.epoll のメソッド)
@anchor{library/select select epoll poll}@anchor{f9d}
@deffn {メソッド} epoll.poll (timeout=None, maxevents=-1)

イベントを待機します。`timeout' はタイムアウト時間で、単位は秒 (float型) です。


バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 @ref{f88,,InterruptedError} を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を見てください)。

@end deffn

@node ポーリングオブジェクト,kqueue オブジェクト,エッジおよびレベルトリガポーリング epoll オブジェクト,select --- I/O 完了の待機
@anchor{library/select poll-objects}@anchor{3a1d}@anchor{library/select polling-objects}@anchor{3a2d}
@subsubsection ポーリングオブジェクト


The @code{poll()} system call, supported on most Unix systems, provides better
scalability for network servers that service many, many clients at the same
time. @code{poll()} scales better because the system call only requires listing
the file descriptors of interest, while @code{select()} builds a bitmap, turns
on bits for the fds of interest, and then afterward the whole bitmap has to be
linearly scanned again. @code{select()} is `O'(`highest file descriptor'), while
@code{poll()} is `O'(`number of file descriptors').

@geindex register() (select.poll のメソッド)
@anchor{library/select select poll register}@anchor{3a2e}
@deffn {メソッド} poll.register (fd[, eventmask])

ファイル記述子をポーリングオブジェクトに登録します。これ以降の @ref{30a9,,poll()} メソッド呼び出しでは、そのファイル記述子に処理待ち中の I/O イベントがあるかどうかを監視します。 `fd' は整数か、整数値を返す @ref{17ad,,fileno()} メソッドを持つオブジェクトを取ります。ファイルオブジェクトも @code{fileno()} を実装しているので、引数として使うことができます。

`eventmask' はオプションのビットマスクで、どの種類の I/O イベントを監視したいかを記述します。この値は以下の表で述べる定数 @code{POLLIN} 、 @code{POLLPRI} 、および @code{POLLOUT} の組み合わせにすることができます。ビットマスクを指定しない場合、標準の値が使われ、 3 種類のイベント全てに対して監視が行われます。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{POLLIN}

@tab

読み出し可能なデータが存在する

@item

@code{POLLPRI}

@tab

緊急の読み出し可能なデータが存在する

@item

@code{POLLOUT}

@tab

書き出しの準備ができている: 書き出し処理がブロックしない

@item

@code{POLLERR}

@tab

何らかのエラー状態

@item

@code{POLLHUP}

@tab

ハングアップ

@item

@code{POLLRDHUP}

@tab

ストリームソケットの他端が接続を切断したか、接続の書き込み側のシャットダウンを行った。

@item

@code{POLLNVAL}

@tab

無効な要求: 記述子が開かれていない

@end multitable


登録済みのファイル記述子を登録してもエラーにはならず、一度だけ登録した場合と同じ効果になります。
@end deffn

@geindex modify() (select.poll のメソッド)
@anchor{library/select select poll modify}@anchor{3a2f}
@deffn {メソッド} poll.modify (fd, eventmask)

登録されているファイル記述子 `fd' を変更する。これは、 @code{register(fd, eventmask)} と同じ効果を持ちます。登録されていないファイル記述子に対してこのメソッドを呼び出すと、 errno @code{ENOENT} で @ref{2c0,,OSError} 例外が発生します。
@end deffn

@geindex unregister() (select.poll のメソッド)
@anchor{library/select select poll unregister}@anchor{3a30}
@deffn {メソッド} poll.unregister (fd)

ポーリングオブジェクトによって追跡中のファイル記述子を登録解除します。 @ref{3a2e,,register()} メソッドと同様に、 `fd' は整数か、整数値を返す @ref{17ad,,fileno()} メソッドを持つオブジェクトを取ります。

登録されていないファイル記述子を登録解除しようとすると @ref{5e7,,KeyError} 例外が送出されます。
@end deffn

@geindex poll() (select.poll のメソッド)
@anchor{library/select select poll poll}@anchor{f9f}
@deffn {メソッド} poll.poll ([timeout])

登録されたファイル記述子に対してポーリングを行い、報告すべき I/O イベントまたはエラーの発生したファイル記述子毎に 2 要素のタプル @code{(fd, event)} からなるリストを返します。リストは空になることもあります。 `fd' はファイル記述子で、 `event' は該当するファイル記述子について報告されたイベントを表すビットマスクです --- 例えば @code{POLLIN} は入力待ちを示し、 @code{POLLOUT} はファイル記述子に対する書き込みが可能を示す、などです。空のリストは呼び出しがタイムアウトしたか、報告すべきイベントがどのファイル記述子でも発生しなかったことを示します。 `timeout' が与えられた場合、処理を戻すまで待機する時間の長さをミリ秒単位で指定します。 `timeout' が省略されたり、負の値であったり、あるいは @ref{885,,None} の場合、そのポーリングオブジェクトが監視している何らかのイベントが発生するまでブロックします。


バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 @ref{f88,,InterruptedError} を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を見てください)。

@end deffn

@node kqueue オブジェクト,kevent オブジェクト,ポーリングオブジェクト,select --- I/O 完了の待機
@anchor{library/select id1}@anchor{3a31}@anchor{library/select kqueue-objects}@anchor{3a1f}
@subsubsection kqueue オブジェクト


@geindex close() (select.kqueue のメソッド)
@anchor{library/select select kqueue close}@anchor{3a32}
@deffn {メソッド} kqueue.close ()

kqueue オブジェクトの制御用ファイル記述子を閉じる。
@end deffn

@geindex closed (select.kqueue の属性)
@anchor{library/select select kqueue closed}@anchor{3a33}
@deffn {の属性} kqueue.closed

kqueue オブジェクトが閉じている場合 @code{True} です。
@end deffn

@geindex fileno() (select.kqueue のメソッド)
@anchor{library/select select kqueue fileno}@anchor{3a34}
@deffn {メソッド} kqueue.fileno ()

制御用ファイル記述子の番号を返します。
@end deffn

@geindex fromfd() (select.kqueue のメソッド)
@anchor{library/select select kqueue fromfd}@anchor{3a35}
@deffn {メソッド} kqueue.fromfd (fd)

与えられたファイル記述子から、kqueue オブジェクトを作成する。
@end deffn

@geindex control() (select.kqueue のメソッド)
@anchor{library/select select kqueue control}@anchor{f9e}
@deffn {メソッド} kqueue.control (changelist, max_events[, timeout]) -> eventlist

kevent に対する低水準のインターフェース


@itemize -

@item 
`changelist' は kevent オブジェクトのイテラブルまたは @code{None}

@item 
`max_events' は 0 または正の整数

@item 
timeout in seconds (floats possible); the default is @code{None},
to wait forever
@end itemize


バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 @ref{f88,,InterruptedError} を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を見てください)。

@end deffn

@node kevent オブジェクト,,kqueue オブジェクト,select --- I/O 完了の待機
@anchor{library/select id2}@anchor{3a36}@anchor{library/select kevent-objects}@anchor{3a21}
@subsubsection kevent オブジェクト


@indicateurl{https://man.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2}

@geindex ident (select.kevent の属性)
@anchor{library/select select kevent ident}@anchor{3a37}
@deffn {の属性} kevent.ident

イベントを特定するための値。この値は、フィルタにもよりますが、大抵の場合はファイル記述子です。コンストラクタでは、 ident として、整数値か @ref{17ad,,fileno()} メソッドを持ったオブジェクトを渡せます。 kevent は内部で整数値を保存します。
@end deffn

@geindex filter (select.kevent の属性)
@anchor{library/select select kevent filter}@anchor{3a38}
@deffn {の属性} kevent.filter

カーネルフィルタの名前。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{KQ_FILTER_READ}

@tab

記述子を受け取り、読み込めるデータが存在する時に戻る

@item

@code{KQ_FILTER_WRITE}

@tab

記述子を受け取り、書き込み可能な時に戻る

@item

@code{KQ_FILTER_AIO}

@tab

AIO リクエスト

@item

@code{KQ_FILTER_VNODE}

@tab

`fflag' で監視されたイベントが1つ以上発生したときに戻る

@item

@code{KQ_FILTER_PROC}

@tab

プロセスID上のイベントを監視する

@item

@code{KQ_FILTER_NETDEV}

@tab

ネットワークデバイス上のイベントを監視する (macOS では利用不可)

@item

@code{KQ_FILTER_SIGNAL}

@tab

監視しているシグナルがプロセスに届いたときに戻る

@item

@code{KQ_FILTER_TIMER}

@tab

任意のタイマを設定する

@end multitable

@end deffn

@geindex flags (select.kevent の属性)
@anchor{library/select select kevent flags}@anchor{3a39}
@deffn {の属性} kevent.flags

フィルタアクション。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{KQ_EV_ADD}

@tab

イベントを追加または修正する

@item

@code{KQ_EV_DELETE}

@tab

キューからイベントを取り除く

@item

@code{KQ_EV_ENABLE}

@tab

Permits control() to return the event

@item

@code{KQ_EV_DISABLE}

@tab

Disables event

@item

@code{KQ_EV_ONESHOT}

@tab

イベントを最初の発生後無効にする

@item

@code{KQ_EV_CLEAR}

@tab

イベントを受け取った後で状態をリセットする

@item

@code{KQ_EV_SYSFLAGS}

@tab

内部イベント

@item

@code{KQ_EV_FLAG1}

@tab

内部イベント

@item

@code{KQ_EV_EOF}

@tab

フィルタ依存のEOF状態

@item

@code{KQ_EV_ERROR}

@tab

戻り値を参照

@end multitable

@end deffn

@geindex fflags (select.kevent の属性)
@anchor{library/select select kevent fflags}@anchor{3a3a}
@deffn {の属性} kevent.fflags

フィルタ依存のフラグ。

@code{KQ_FILTER_READ} と @code{KQ_FILTER_WRITE} フィルタのフラグ:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{KQ_NOTE_LOWAT}

@tab

ソケットバッファの最低基準値

@end multitable


@code{KQ_FILTER_VNODE} フィルタのフラグ:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{KQ_NOTE_DELETE}

@tab

`unlink()' が呼ばれた

@item

@code{KQ_NOTE_WRITE}

@tab

書き込みが発生した

@item

@code{KQ_NOTE_EXTEND}

@tab

ファイルのサイズが拡張された

@item

@code{KQ_NOTE_ATTRIB}

@tab

属性が変更された

@item

@code{KQ_NOTE_LINK}

@tab

リンクカウントが変更された

@item

@code{KQ_NOTE_RENAME}

@tab

ファイル名が変更された

@item

@code{KQ_NOTE_REVOKE}

@tab

ファイルアクセスが破棄された

@end multitable


@code{KQ_FILTER_PROC} フィルタフラグ:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{KQ_NOTE_EXIT}

@tab

プロセスが終了した

@item

@code{KQ_NOTE_FORK}

@tab

プロセスが `fork()' を呼び出した

@item

@code{KQ_NOTE_EXEC}

@tab

プロセスが新しいプロセスを実行した

@item

@code{KQ_NOTE_PCTRLMASK}

@tab

内部フィルタフラグ

@item

@code{KQ_NOTE_PDATAMASK}

@tab

内部フィルタフラグ

@item

@code{KQ_NOTE_TRACK}

@tab

`fork()' の呼び出しを超えてプロセスを監視する

@item

@code{KQ_NOTE_CHILD}

@tab

`NOTE_TRACK' に対して子プロセスに渡される

@item

@code{KQ_NOTE_TRACKERR}

@tab

子プロセスにアタッチできなかった

@end multitable


@code{KQ_FILTER_NETDEV} フィルタフラグ (macOS では利用不可):


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{KQ_NOTE_LINKUP}

@tab

リンクアップしている

@item

@code{KQ_NOTE_LINKDOWN}

@tab

リンクダウンしている

@item

@code{KQ_NOTE_LINKINV}

@tab

リンク状態が不正

@end multitable

@end deffn

@geindex data (select.kevent の属性)
@anchor{library/select select kevent data}@anchor{3a3b}
@deffn {の属性} kevent.data

フィルタ固有のデータ。
@end deffn

@geindex udata (select.kevent の属性)
@anchor{library/select select kevent udata}@anchor{3a3c}
@deffn {の属性} kevent.udata

ユーザー定義値。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node selectors --- 高水準の I/O 多重化,signal --- 非同期イベントにハンドラーを設定する,select --- I/O 完了の待機,ネットワーク通信とプロセス間通信
@anchor{library/selectors doc}@anchor{3a3d}@anchor{library/selectors module-selectors}@anchor{c7}@anchor{library/selectors selectors-high-level-i-o-multiplexing}@anchor{3a3e}@anchor{library/selectors translation-repo}@anchor{3a3f}
@subsection @code{selectors} --- 高水準の I/O 多重化


@geindex module; selectors


Added in version 3.4.


`ソースコード:' Lib/selectors.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/selectors.py}


__________________________________________________________________


@menu
* はじめに: はじめに<11>. 
* クラス: クラス<4>. 
* 使用例: 使用例<29>. 

@end menu

@node はじめに<11>,クラス<4>,,selectors --- 高水準の I/O 多重化
@anchor{library/selectors introduction}@anchor{3a40}
@subsubsection はじめに


このモジュールにより、@ref{c6,,select} モジュールプリミティブに基づく高水準かつ効率的な I/O の多重化が行えます。OS 水準のプリミティブを使用した正確な制御を求めない限り、このモジュールの使用が推奨されます。

このモジュールは @ref{3a41,,BaseSelector} 抽象基底クラスと、いくつかの具象実装 (@ref{3917,,KqueueSelector}, @ref{dd0,,EpollSelector}...) を定義しており、これらは複数のファイルオブジェクトの I/O の準備状況の通知の待機に使用できます。以下では、 "ファイルオブジェクト" は、@ref{17ad,,fileno()} メソッドを持つあらゆるオブジェクトか、あるいは Raw ファイル記述子を意味します。@ref{13db,,ファイルオブジェクト} を参照してください。

@ref{3a42,,DefaultSelector} は、現在のプラットフォームで利用できる、もっとも効率的な実装の別名になります: これはほとんどのユーザーにとってのデフォルトの選択になるはずです。

@cartouche
@quotation 注釈 
プラットフォームごとにサポートされているファイルオブジェクトのタイプは異なります: Windows ではソケットはサポートされますが、パイプはされません。Unix では両方がサポートされます (その他の fifo やスペシャルファイルデバイスなどのタイプもサポートされます)。
@end quotation
@end cartouche


@subsubheading 参考



@table @asis

@item @ref{c6,,select}

低水準の I/O 多重化モジュールです。
@end table


@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@node クラス<4>,使用例<29>,はじめに<11>,selectors --- 高水準の I/O 多重化
@anchor{library/selectors classes}@anchor{3a43}
@subsubsection クラス


クラス階層:

@example
BaseSelector
+-- SelectSelector
+-- PollSelector
+-- EpollSelector
+-- DevpollSelector
+-- KqueueSelector
@end example

In the following, `events' is a bitwise mask indicating which I/O events should
be waited for on a given file object. It can be a combination of the module's
constants below:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@geindex EVENT_READ (selectors モジュール)
@anchor{library/selectors selectors EVENT_READ}@anchor{3a44}
@deffn {データ} selectors.EVENT_READ
@end deffn

@tab

読み込み可能

@item

@geindex EVENT_WRITE (selectors モジュール)
@anchor{library/selectors selectors EVENT_WRITE}@anchor{3a45}
@deffn {データ} selectors.EVENT_WRITE
@end deffn

@tab

書き込み可能

@end multitable

@end quotation

@geindex SelectorKey (selectors のクラス)
@anchor{library/selectors selectors SelectorKey}@anchor{3a46}
@deffn {クラス} selectors.SelectorKey

@ref{3a46,,SelectorKey} はそれの下層のファイルディスクリプタ、選択したイベントマスク、および付属データへのファイルオブジェクトの関連付けに使用される @ref{4e0,,namedtuple} です。いくつかの @ref{3a41,,BaseSelector} メソッドを返します。

@geindex fileobj (selectors.SelectorKey の属性)
@anchor{library/selectors selectors SelectorKey fileobj}@anchor{3a47}
@deffn {の属性} fileobj

登録されたファイルオブジェクトです。
@end deffn

@geindex fd (selectors.SelectorKey の属性)
@anchor{library/selectors selectors SelectorKey fd}@anchor{3a48}
@deffn {の属性} fd

下層のファイル記述子です。
@end deffn

@geindex events (selectors.SelectorKey の属性)
@anchor{library/selectors selectors SelectorKey events}@anchor{3a49}
@deffn {の属性} events

このファイルオブジェクトで待機しなければならないイベントです。
@end deffn

@geindex data (selectors.SelectorKey の属性)
@anchor{library/selectors selectors SelectorKey data}@anchor{3a4a}
@deffn {の属性} data

このファイルオブジェクトに関連付けられたオプションの不透明型 (Opaque) データです。例えば、これはクライアントごとのセッション ID を格納するために使用できます。
@end deffn
@end deffn

@geindex BaseSelector (selectors のクラス)
@anchor{library/selectors selectors BaseSelector}@anchor{3a41}
@deffn {クラス} selectors.BaseSelector

@ref{3a41,,BaseSelector} は複数のファイルオブジェクトの I/O イベントの準備状況の待機に使用されます。これはファイルストリームを登録、登録解除、およびこれらのストリームでの I/O イベントを待機 (オプションでタイムアウト) するメソッドをサポートします。これは抽象基底クラスであるため、インスタンスを作成できません。使用する実装を明示的に指定したい、そしてプラットフォームがそれをサポートしている場合は、代わりに @ref{3a42,,DefaultSelector} を使用するか、@ref{3914,,SelectSelector} や  @ref{3917,,KqueueSelector} などの一つを使用します。@ref{3a41,,BaseSelector} とその具象実装は @ref{1e1,,コンテキストマネージャー} プロトコルをサポートしています。

@geindex register() (selectors.BaseSelector のメソッド)
@anchor{library/selectors selectors BaseSelector register}@anchor{3a4b}
@deffn {メソッド} abstractmethod register (fileobj, events, data=None)

I/O イベントを監視するファイルオブジェクトをセレクションに登録します。

`fileobj' は監視するファイルオブジェクトです。これは整数のファイル記述子か、@code{fileno()} メソッドを持つオブジェクトのどちらかになります。`events' は監視するイベントのビット幅マスクになります。`data' は不透明型 (Opaque) オブジェクトです。

これは新しい @ref{3a46,,SelectorKey} インスタンスを返します。不正なイベントマスク化ファイル記述子のときは @ref{2ec,,ValueError} が、ファイルオブジェクトがすでに登録済みのときは @ref{5e7,,KeyError} が送出されます。
@end deffn

@geindex unregister() (selectors.BaseSelector のメソッド)
@anchor{library/selectors selectors BaseSelector unregister}@anchor{3a4c}
@deffn {メソッド} abstractmethod unregister (fileobj)

ファイルオブジェクトのセレクション登録を解除し、監視対象から外します。ファイルオブジェクトの登録解除はそのクローズより前に行われます。

`fileobj' は登録済みのファイルオブジェクトでなければなりません。

関連付けられた @ref{3a46,,SelectorKey} インスタンスを返します。`fileobj' が登録されていない場合 @ref{5e7,,KeyError} を送出します。`fileobj' が不正な場合 (例えば `fileobj' に @code{fileno()} メソッドが無い場合や @code{fileno()} メソッドの戻り値が不正な場合) @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex modify() (selectors.BaseSelector のメソッド)
@anchor{library/selectors selectors BaseSelector modify}@anchor{dcf}
@deffn {メソッド} modify (fileobj, events, data=None)

登録されたファイルオブジェクトの監視されたイベントや付属データを変更します。

より効率的に実装できる点を除けば、 @code{BaseSelector.unregister(fileobj)} に続けて @code{BaseSelector.register(fileobj, events, data)} を行うのと等価です。

新たな @ref{3a46,,SelectorKey} インスタンスを返します。
イベントマスクやファイル記述子が不正な場合は @ref{2ec,,ValueError} を、ファイルオブジェクトが登録されていない場合は @ref{5e7,,KeyError} を送出します。
@end deffn

@geindex select() (selectors.BaseSelector のメソッド)
@anchor{library/selectors selectors BaseSelector select}@anchor{3a4d}
@deffn {メソッド} abstractmethod select (timeout=None)

登録されたいくつかのファイルオブジェクトが準備できたか、タイムアウトするまで待機します。

@code{timeout > 0} の場合、最大待機時間を秒で指定します。 @code{timeout <= 0} の場合、この関数の呼び出しはブロックせず、 現在準備できているファイルオブジェクトを報告します。 `timeout' が @code{None} の場合、監視しているファイルオブジェクトの一つが準備できるまでブロックします。

この関数は @code{(key, events)} タプルのリストを返します。準備できたファイルオブジェクトにつき1タプルです。

`key' は準備状態のファイルオブジェクトに対応する @ref{3a46,,SelectorKey} インスタンスです。 `events' はそのファイルオブジェクトで準備が完了したイベントのビットマスクです。

@cartouche
@quotation 注釈 
このメソッドは、現在のプロセスで信号を受信した場合、どのファイルオブジェクトも準備完了にならないうちに、またはタイムアウトが経過する前に返ることがあります。その場合、空のリストが返されます。
@end quotation
@end cartouche


バージョン 3.5 で変更: このセレクタは、シグナルによって中断された時に、シグナルハンドラが例外を起こさなかった場合、空のイベントリストを返すのではなく、再計算されたタイムアウトによってリトライするようになりました (この論拠については 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} を参照してください)。

@end deffn

@geindex close() (selectors.BaseSelector のメソッド)
@anchor{library/selectors selectors BaseSelector close}@anchor{3a4e}
@deffn {メソッド} close ()

セレクタを閉じます。

下層のリソースがすべて解放されたことを確かめるために呼ばれなければなりません。一旦閉じられたセレクタは使ってはいけません。
@end deffn

@geindex get_key() (selectors.BaseSelector のメソッド)
@anchor{library/selectors selectors BaseSelector get_key}@anchor{3a4f}
@deffn {メソッド} get_key (fileobj)

登録されたファイルオブジェクトに関連付けられたキーを返します。

そのファイルオブジェクトに関連付けられた @ref{3a46,,SelectorKey} インスタンスを返します。そのファイルオブジェクトが登録されていない場合 @ref{5e7,,KeyError} を送出します。
@end deffn

@geindex get_map() (selectors.BaseSelector のメソッド)
@anchor{library/selectors selectors BaseSelector get_map}@anchor{3a50}
@deffn {メソッド} abstractmethod get_map ()

ファイルオブジェクトからセレクタキーへのマッピングを返します。

これは、登録済みのファイルオブジェクトを、それらに関連づけられた @ref{3a46,,SelectorKey} インスタンスにマッピングする @ref{ac7,,Mapping} のインスタンスを返します。
@end deffn
@end deffn

@geindex DefaultSelector (selectors のクラス)
@anchor{library/selectors selectors DefaultSelector}@anchor{3a42}
@deffn {クラス} selectors.DefaultSelector

デフォルトの selector クラスで、現在のプラットフォームで利用できる最も効率的な実装を使用しています。大半のユーザはこれをデフォルトにすべきです。
@end deffn

@geindex SelectSelector (selectors のクラス)
@anchor{library/selectors selectors SelectSelector}@anchor{3914}
@deffn {クラス} selectors.SelectSelector

@ref{fa0,,select.select()} を基底とするセレクタです。
@end deffn

@geindex PollSelector (selectors のクラス)
@anchor{library/selectors selectors PollSelector}@anchor{dd1}
@deffn {クラス} selectors.PollSelector

@ref{30a9,,select.poll()} を基底とするセレクタです。
@end deffn

@geindex EpollSelector (selectors のクラス)
@anchor{library/selectors selectors EpollSelector}@anchor{dd0}
@deffn {クラス} selectors.EpollSelector

@ref{1196,,select.epoll()} を基底とするセレクタです。

@geindex fileno() (selectors.EpollSelector のメソッド)
@anchor{library/selectors selectors EpollSelector fileno}@anchor{3a51}
@deffn {メソッド} fileno ()

下層の @ref{1196,,select.epoll()} オブジェクトが使用しているファイル記述子を返します。
@end deffn
@end deffn

@geindex DevpollSelector (selectors のクラス)
@anchor{library/selectors selectors DevpollSelector}@anchor{dd2}
@deffn {クラス} selectors.DevpollSelector

@ref{1198,,select.devpoll()} を基底とするセレクタです。

@geindex fileno() (selectors.DevpollSelector のメソッド)
@anchor{library/selectors selectors DevpollSelector fileno}@anchor{3a52}
@deffn {メソッド} fileno ()

下層の @ref{1198,,select.devpoll()} オブジェクトが使用しているファイル記述子を返します。
@end deffn


Added in version 3.5.

@end deffn

@geindex KqueueSelector (selectors のクラス)
@anchor{library/selectors selectors KqueueSelector}@anchor{3917}
@deffn {クラス} selectors.KqueueSelector

@ref{1a43,,select.kqueue()} を基底とするセレクタです。

@geindex fileno() (selectors.KqueueSelector のメソッド)
@anchor{library/selectors selectors KqueueSelector fileno}@anchor{3a53}
@deffn {メソッド} fileno ()

下層の @ref{1a43,,select.kqueue()} オブジェクトが使用しているファイル記述子を返します。
@end deffn
@end deffn

@node 使用例<29>,,クラス<4>,selectors --- 高水準の I/O 多重化
@anchor{library/selectors examples}@anchor{3a54}
@subsubsection 使用例


簡単なエコーサーバの実装です:

@example
import selectors
import socket

sel = selectors.DefaultSelector()

def accept(sock, mask):
    conn, addr = sock.accept()  # Should be ready
    print('accepted', conn, 'from', addr)
    conn.setblocking(False)
    sel.register(conn, selectors.EVENT_READ, read)

def read(conn, mask):
    data = conn.recv(1000)  # Should be ready
    if data:
        print('echoing', repr(data), 'to', conn)
        conn.send(data)  # Hope it won't block
    else:
        print('closing', conn)
        sel.unregister(conn)
        conn.close()

sock = socket.socket()
sock.bind(('localhost', 1234))
sock.listen(100)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)

while True:
    events = sel.select()
    for key, mask in events:
        callback = key.data
        callback(key.fileobj, mask)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node signal --- 非同期イベントにハンドラーを設定する,mmap --- メモリマップファイルのサポート,selectors --- 高水準の I/O 多重化,ネットワーク通信とプロセス間通信
@anchor{library/signal doc}@anchor{3a55}@anchor{library/signal module-signal}@anchor{cb}@anchor{library/signal signal-set-handlers-for-asynchronous-events}@anchor{3a56}@anchor{library/signal translation-repo}@anchor{3a57}
@subsection @code{signal} --- 非同期イベントにハンドラーを設定する


@geindex module; signal

`ソースコード:' Lib/signal.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/signal.py}


__________________________________________________________________


このモジュールでは Python でシグナルハンドラを使うための機構を提供します。

@menu
* 一般的なルール:: 
* モジュールの内容: モジュールの内容<2>. 
* 使用例: 使用例<30>. 
* Note on SIGPIPE:: 
* Note on Signal Handlers and Exceptions:: 

@end menu

@node 一般的なルール,モジュールの内容<2>,,signal --- 非同期イベントにハンドラーを設定する
@anchor{library/signal general-rules}@anchor{3a58}
@subsubsection 一般的なルール


@ref{134c,,signal.signal()} 関数を使って、シグナルを受信した時に実行されるハンドラを定義することができます。 Python は標準でごく少数のシグナルハンドラをインストールしています: @ref{3a59,,SIGPIPE} は無視され (したがって、 pipe や socket に対する書き込みで生じたエラーは通常の Python 例外として報告されます)、 @ref{253,,SIGINT} は @ref{bc5,,KeyboardInterrupt} 例外に変換されます。親プロセスが変更していない場合は、これらはどれも上書きすることができます。

特定のシグナルに対するハンドラが一度設定されると、明示的にリセットしないかぎり設定されたままになります (Python は背後の実装系に関係なく BSD 形式のインターフェースをエミュレートします)。例外は @ref{30e4,,SIGCHLD} のハンドラで、この場合は背後の実装系の仕様に従います。

On WebAssembly platforms, signals are emulated and therefore behave
differently. Several functions and signals are not available on these
platforms.

@menu
* Python のシグナルハンドラの実行:: 
* シグナルとスレッド:: 

@end menu

@node Python のシグナルハンドラの実行,シグナルとスレッド,,一般的なルール
@anchor{library/signal execution-of-python-signal-handlers}@anchor{3a5a}
@subsubsection Python のシグナルハンドラの実行


A Python signal handler does not get executed inside the low-level (C) signal
handler.  Instead, the low-level signal handler sets a flag which tells the
@ref{3a5b,,virtual machine} to execute the corresponding Python signal handler
at a later point (for example, at the next @ref{4aa,,bytecode} instruction).
This has consequences:


@itemize *

@item 
It makes little sense to catch synchronous errors like @ref{128d,,SIGFPE} or
@ref{128c,,SIGSEGV} that are caused by an invalid operation in C code.  Python
will return from the signal handler to the C code, which is likely to raise
the same signal again, causing Python to apparently hang.  From Python 3.3
onwards, you can use the @ref{5c,,faulthandler} module to report on synchronous
errors.

@item 
完全にCで実装された長時間かかる計算 (大きいテキストに対する正規表現のマッチなど) は、どのシグナルを受信しても中断されないまま長時間実行され続ける可能性があります。Python のシグナルハンドラはその計算が終了してから呼び出されます。

@item 
If the handler raises an exception, it will be raised "out of thin air" in
the main thread. See the @ref{26ec,,note below} for a
discussion.
@end itemize

@node シグナルとスレッド,,Python のシグナルハンドラの実行,一般的なルール
@anchor{library/signal id1}@anchor{3a5c}@anchor{library/signal signals-and-threads}@anchor{3a5d}
@subsubsection シグナルとスレッド


Python のシグナルハンドラは、もしシグナルを受け取ったのが別のスレッドだったとしても、常にメインインタープリターの Python のメインスレッドで実行されます。このためシグナルをスレッド間通信に使うことはできません。代わりに @ref{f3,,threading} モジュールが提供している同期プリミティブを利用できます。

また、メインインタープリターのメインスレッドだけが新しいシグナルハンドラを登録できます。

@cartouche
@quotation 警告 
Synchronization primitives such as @ref{19f4,,threading.Lock} should not be used
within signal handlers.  Doing so can lead to unexpected deadlocks.
@end quotation
@end cartouche

@node モジュールの内容<2>,使用例<30>,一般的なルール,signal --- 非同期イベントにハンドラーを設定する
@anchor{library/signal module-contents}@anchor{3a5e}
@subsubsection モジュールの内容



バージョン 3.5 で変更: signal (SIG*), handler (@ref{1bb2,,SIG_DFL}, @ref{1bb1,,SIG_IGN}) and sigmask
(@ref{3a5f,,SIG_BLOCK}, @ref{3a60,,SIG_UNBLOCK}, @ref{3a61,,SIG_SETMASK})
related constants listed below were turned into
@ref{edb,,enums} (@ref{3a62,,Signals}, @ref{3a63,,Handlers} and @ref{3a64,,Sigmasks} respectively).
@ref{1a25,,getsignal()}, @ref{1348,,pthread_sigmask()}, @ref{134a,,sigpending()} and
@ref{134b,,sigwait()} functions return human-readable
@ref{edb,,enums} as @ref{3a62,,Signals} objects.


The signal module defines three enums:

@geindex Signals (signal のクラス)
@anchor{library/signal signal Signals}@anchor{3a62}
@deffn {クラス} signal.Signals

@ref{edb,,enum.IntEnum} collection of SIG* constants and the CTRL_* constants.


Added in version 3.5.

@end deffn

@geindex Handlers (signal のクラス)
@anchor{library/signal signal Handlers}@anchor{3a63}
@deffn {クラス} signal.Handlers

@ref{edb,,enum.IntEnum} collection of the constants @ref{1bb2,,SIG_DFL} and @ref{1bb1,,SIG_IGN}.


Added in version 3.5.

@end deffn

@geindex Sigmasks (signal のクラス)
@anchor{library/signal signal Sigmasks}@anchor{3a64}
@deffn {クラス} signal.Sigmasks

@ref{edb,,enum.IntEnum} collection of the constants @ref{3a5f,,SIG_BLOCK}, @ref{3a60,,SIG_UNBLOCK} and @ref{3a61,,SIG_SETMASK}.

@ref{213f,,Availability}: Unix.

See the man page @code{sigprocmask(2)@footnote{https://manpages.debian.org/sigprocmask(2)}} and
@code{pthread_sigmask(3)@footnote{https://manpages.debian.org/pthread_sigmask(3)}} for further information.


Added in version 3.5.

@end deffn

The variables defined in the @code{signal} module are:

@geindex SIG_DFL (signal モジュール)
@anchor{library/signal signal SIG_DFL}@anchor{1bb2}
@deffn {データ} signal.SIG_DFL

二つある標準シグナル処理オプションのうちの一つです; 単純にシグナルに対する標準の関数を実行します。例えば、ほとんどのシステムでは、 @ref{3a65,,SIGQUIT} に対する標準の動作はコアダンプと終了で、 @ref{30e4,,SIGCHLD} に対する標準の動作は単にシグナルの無視です。
@end deffn

@geindex SIG_IGN (signal モジュール)
@anchor{library/signal signal SIG_IGN}@anchor{1bb1}
@deffn {データ} signal.SIG_IGN

もう一つの標準シグナル処理オプションで、受け取ったシグナルを単に無視します。
@end deffn

@geindex SIGABRT (signal モジュール)
@anchor{library/signal signal SIGABRT}@anchor{128e}
@deffn {データ} signal.SIGABRT

Abort signal from @code{abort(3)@footnote{https://manpages.debian.org/abort(3)}}.
@end deffn

@geindex SIGALRM (signal モジュール)
@anchor{library/signal signal SIGALRM}@anchor{3a66}
@deffn {データ} signal.SIGALRM

Timer signal from @code{alarm(2)@footnote{https://manpages.debian.org/alarm(2)}}.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGBREAK (signal モジュール)
@anchor{library/signal signal SIGBREAK}@anchor{3a67}
@deffn {データ} signal.SIGBREAK

Interrupt from keyboard (CTRL + BREAK).

@ref{213f,,Availability}: Windows.
@end deffn

@geindex SIGBUS (signal モジュール)
@anchor{library/signal signal SIGBUS}@anchor{128f}
@deffn {データ} signal.SIGBUS

Bus error (bad memory access).

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGCHLD (signal モジュール)
@anchor{library/signal signal SIGCHLD}@anchor{30e4}
@deffn {データ} signal.SIGCHLD

Child process stopped or terminated.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGCLD (signal モジュール)
@anchor{library/signal signal SIGCLD}@anchor{3a68}
@deffn {データ} signal.SIGCLD

@ref{30e4,,SIGCHLD} のエイリアスです。

@ref{213f,,Availability}: not macOS.
@end deffn

@geindex SIGCONT (signal モジュール)
@anchor{library/signal signal SIGCONT}@anchor{30f2}
@deffn {データ} signal.SIGCONT

Continue the process if it is currently stopped

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGFPE (signal モジュール)
@anchor{library/signal signal SIGFPE}@anchor{128d}
@deffn {データ} signal.SIGFPE

Floating-point exception. For example, division by zero.


@subsubheading 参考


@ref{b3f,,ZeroDivisionError} is raised when the second argument of a division
or modulo operation is zero.

@end deffn

@geindex SIGHUP (signal モジュール)
@anchor{library/signal signal SIGHUP}@anchor{3a69}
@deffn {データ} signal.SIGHUP

Hangup detected on controlling terminal or death of controlling process.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGILL (signal モジュール)
@anchor{library/signal signal SIGILL}@anchor{1290}
@deffn {データ} signal.SIGILL

Illegal instruction.
@end deffn

@geindex SIGINT (signal モジュール)
@anchor{library/signal signal SIGINT}@anchor{253}
@deffn {データ} signal.SIGINT

Interrupt from keyboard (CTRL + C).

Default action is to raise @ref{bc5,,KeyboardInterrupt}.
@end deffn

@geindex SIGKILL (signal モジュール)
@anchor{library/signal signal SIGKILL}@anchor{d50}
@deffn {データ} signal.SIGKILL

Kill signal.

It cannot be caught, blocked, or ignored.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGPIPE (signal モジュール)
@anchor{library/signal signal SIGPIPE}@anchor{3a59}
@deffn {データ} signal.SIGPIPE

Broken pipe: write to pipe with no readers.

Default action is to ignore the signal.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGPROF (signal モジュール)
@anchor{library/signal signal SIGPROF}@anchor{3a6a}
@deffn {データ} signal.SIGPROF

Profiling timer expired.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGQUIT (signal モジュール)
@anchor{library/signal signal SIGQUIT}@anchor{3a65}
@deffn {データ} signal.SIGQUIT

Terminal quit signal.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGSEGV (signal モジュール)
@anchor{library/signal signal SIGSEGV}@anchor{128c}
@deffn {データ} signal.SIGSEGV

Segmentation fault: invalid memory reference.
@end deffn

@geindex SIGSTOP (signal モジュール)
@anchor{library/signal signal SIGSTOP}@anchor{3a6b}
@deffn {データ} signal.SIGSTOP

Stop executing (cannot be caught or ignored).
@end deffn

@geindex SIGSTKFLT (signal モジュール)
@anchor{library/signal signal SIGSTKFLT}@anchor{1c07}
@deffn {データ} signal.SIGSTKFLT

Stack fault on coprocessor. The Linux kernel does not raise this signal: it
can only be raised in user space.

@ref{213f,,Availability}: Linux.

On architectures where the signal is available. See
the man page @code{signal(7)@footnote{https://manpages.debian.org/signal(7)}} for further information.


Added in version 3.11.

@end deffn

@geindex SIGTERM (signal モジュール)
@anchor{library/signal signal SIGTERM}@anchor{15f8}
@deffn {データ} signal.SIGTERM

Termination signal.
@end deffn

@geindex SIGUSR1 (signal モジュール)
@anchor{library/signal signal SIGUSR1}@anchor{3a6c}
@deffn {データ} signal.SIGUSR1

User-defined signal 1.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGUSR2 (signal モジュール)
@anchor{library/signal signal SIGUSR2}@anchor{3a6d}
@deffn {データ} signal.SIGUSR2

User-defined signal 2.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGVTALRM (signal モジュール)
@anchor{library/signal signal SIGVTALRM}@anchor{3a6e}
@deffn {データ} signal.SIGVTALRM

Virtual timer expired.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGWINCH (signal モジュール)
@anchor{library/signal signal SIGWINCH}@anchor{3a6f}
@deffn {データ} signal.SIGWINCH

Window resize signal.

@ref{213f,,Availability}: Unix.
@end deffn

@geindex SIGXCPU (signal モジュール)
@anchor{library/signal signal SIGXCPU}@anchor{3a70}
@deffn {データ} signal.SIGXCPU

CPU time limit exceeded.

@ref{213f,,Availability}: Unix.
@end deffn


@deffn {データ} SIG*

All the signal numbers are defined symbolically.  For example, the hangup signal
is defined as @ref{3a69,,signal.SIGHUP}; the variable names are identical to the
names used in C programs, as found in @code{<signal.h>}.  The Unix man page for
'@code{signal}' lists the existing signals (on some systems this is
@code{signal(2)@footnote{https://manpages.debian.org/signal(2)}}, on others the list is in @code{signal(7)@footnote{https://manpages.debian.org/signal(7)}}). Note that
not all systems define the same set of signal names; only those names defined by
the system are defined by this module.
@end deffn

@geindex CTRL_C_EVENT (signal モジュール)
@anchor{library/signal signal CTRL_C_EVENT}@anchor{1580}
@deffn {データ} signal.CTRL_C_EVENT

@code{CTRL}+@code{C} キーストロークに該当するシグナル。このシグナルは @ref{157f,,os.kill()} でだけ利用できます。

@ref{213f,,Availability}: Windows.


Added in version 3.2.

@end deffn

@geindex CTRL_BREAK_EVENT (signal モジュール)
@anchor{library/signal signal CTRL_BREAK_EVENT}@anchor{1581}
@deffn {データ} signal.CTRL_BREAK_EVENT

@code{CTRL}+@code{BREAK} キーストロークに該当するシグナル。このシグナルは @ref{157f,,os.kill()} でだけ利用できます。

@ref{213f,,Availability}: Windows.


Added in version 3.2.

@end deffn

@geindex NSIG (signal モジュール)
@anchor{library/signal signal NSIG}@anchor{1b8b}
@deffn {データ} signal.NSIG

One more than the number of the highest signal number.
Use @ref{3a71,,valid_signals()} to get valid signal numbers.
@end deffn

@geindex ITIMER_REAL (signal モジュール)
@anchor{library/signal signal ITIMER_REAL}@anchor{3a72}
@deffn {データ} signal.ITIMER_REAL

実時間でデクリメントするインターバルタイマーです。タイマーが発火したときに @ref{3a66,,SIGALRM} を送ります。
@end deffn

@geindex ITIMER_VIRTUAL (signal モジュール)
@anchor{library/signal signal ITIMER_VIRTUAL}@anchor{3a73}
@deffn {データ} signal.ITIMER_VIRTUAL

プロセスの実行時間だけデクリメントするインターバルタイマーです。タイマーが発火したときに @ref{3a6e,,SIGVTALRM} を送ります。
@end deffn

@geindex ITIMER_PROF (signal モジュール)
@anchor{library/signal signal ITIMER_PROF}@anchor{3a74}
@deffn {データ} signal.ITIMER_PROF

プロセスの実行中と、システムがそのプロセスのために実行している時間だけデクリメントするインターバルタイマーです。ITIMER_VIRTUAL と組み合わせて、このタイマーはよくアプリケーションがユーザー空間とカーネル空間で消費した時間のプロファイリングに利用されます。タイマーが発火したときに @ref{3a6a,,SIGPROF} を送ります。
@end deffn

@geindex SIG_BLOCK (signal モジュール)
@anchor{library/signal signal SIG_BLOCK}@anchor{3a5f}
@deffn {データ} signal.SIG_BLOCK

@ref{1348,,pthread_sigmask()} の `how' 引数に渡せる値で、シグナルがブロックされることを意味します。


Added in version 3.3.

@end deffn

@geindex SIG_UNBLOCK (signal モジュール)
@anchor{library/signal signal SIG_UNBLOCK}@anchor{3a60}
@deffn {データ} signal.SIG_UNBLOCK

@ref{1348,,pthread_sigmask()} の `how' 引数に渡せる値で、シグナルがブロック解除されることを意味します。


Added in version 3.3.

@end deffn

@geindex SIG_SETMASK (signal モジュール)
@anchor{library/signal signal SIG_SETMASK}@anchor{3a61}
@deffn {データ} signal.SIG_SETMASK

@ref{1348,,pthread_sigmask()} の `how' 引数に渡せる値で、シグナルが置換されることを意味します。


Added in version 3.3.

@end deffn

The @code{signal} module defines one exception:

@geindex ItimerError
@anchor{library/signal signal ItimerError}@anchor{3a75}
@deffn {例外} signal.ItimerError

背後の @ref{3a76,,setitimer()} または @ref{3a77,,getitimer()} 実装からエラーを通知するために送出されます。無効なインタバルタイマーや負の時間が @ref{3a76,,setitimer()} に渡された場合、このエラーを予期してください。このエラーは @ref{2c0,,OSError} を継承しています。


Added in version 3.3: このエラーは以前は @ref{125e,,IOError} のサブタイプでしたが、 @ref{2c0,,OSError} のエイリアスになりました。

@end deffn

The @code{signal} module defines the following functions:

@geindex alarm() (signal モジュール)
@anchor{library/signal signal alarm}@anchor{3a78}
@deffn {の関数} signal.alarm (time)

`time' がゼロでない値の場合、この関数は `time' 秒後頃に @ref{3a66,,SIGALRM} をプロセスに送るように要求します。それ以前にスケジュールしたアラームはキャンセルされます (常に一つのアラームしかスケジュールできません)。この場合、戻り値は以前に設定されたアラームシグナルが通知されるまであと何秒だったかを示す値です。 `time' がゼロの場合、アラームは一切スケジュールされず、現在スケジュールされているアラームがキャンセルされます。戻り値がゼロの場合、現在アラームがスケジュールされていないことを示します。

@ref{213f,,Availability}: Unix.

See the man page @code{alarm(2)@footnote{https://manpages.debian.org/alarm(2)}} for further information.
@end deffn

@geindex getsignal() (signal モジュール)
@anchor{library/signal signal getsignal}@anchor{1a25}
@deffn {の関数} signal.getsignal (signalnum)

シグナル `signalnum' に対する現在のシグナルハンドラを返します。戻り値は呼び出し可能な Python オブジェクトか、 @ref{1bb1,,signal.SIG_IGN}、 @ref{1bb2,,signal.SIG_DFL}、および @ref{885,,None} といった特殊な値のいずれかです。ここで @ref{1bb1,,signal.SIG_IGN} は以前そのシグナルが無視されていたことを示し、 @ref{1bb2,,signal.SIG_DFL} は以前そのシグナルの標準の処理方法が使われていたことを示し、 @code{None} はシグナルハンドラがまだ Python によってインストールされていないことを示します。
@end deffn

@geindex strsignal() (signal モジュール)
@anchor{library/signal signal strsignal}@anchor{1e1f}
@deffn {の関数} signal.strsignal (signalnum)

Returns the description of signal `signalnum', such as "Interrupt"
for @ref{253,,SIGINT}. Returns @ref{885,,None} if `signalnum' has no
description. Raises @ref{2ec,,ValueError} if `signalnum' is invalid.


Added in version 3.8.

@end deffn

@geindex valid_signals() (signal モジュール)
@anchor{library/signal signal valid_signals}@anchor{3a71}
@deffn {の関数} signal.valid_signals ()

Return the set of valid signal numbers on this platform.  This can be
less than @code{range(1, NSIG)} if some signals are reserved by the system
for internal use.


Added in version 3.8.

@end deffn

@geindex pause() (signal モジュール)
@anchor{library/signal signal pause}@anchor{3a79}
@deffn {の関数} signal.pause ()

シグナルを受け取るまでプロセスを一時停止します; その後、適切なハンドラが呼び出されます。戻り値はありません。

@ref{213f,,Availability}: Unix.

See the man page @code{signal(2)@footnote{https://manpages.debian.org/signal(2)}} for further information.

@ref{134b,,sigwait()}, @ref{fab,,sigwaitinfo()}, @ref{faa,,sigtimedwait()} @ref{134a,,sigpending()} も参照してください。
@end deffn

@geindex raise_signal() (signal モジュール)
@anchor{library/signal signal raise_signal}@anchor{1b8f}
@deffn {の関数} signal.raise_signal (signum)

Sends a signal to the calling process. Returns nothing.


Added in version 3.8.

@end deffn

@geindex pidfd_send_signal() (signal モジュール)
@anchor{library/signal signal pidfd_send_signal}@anchor{b25}
@deffn {の関数} signal.pidfd_send_signal (pidfd, sig, siginfo=None, flags=0)

Send signal `sig' to the process referred to by file descriptor `pidfd'.
Python does not currently support the `siginfo' parameter; it must be
@code{None}.  The `flags' argument is provided for future extensions; no flag
values are currently defined.

さらに詳しい情報についてはオンラインマニュアルページ @code{pidfd_send_signal(2)@footnote{https://manpages.debian.org/pidfd_send_signal(2)}} を参照してください。

@ref{213f,,Availability}: Linux >= 5.1, Android >= @ref{d83,,build-time} API level 31


Added in version 3.9.

@end deffn

@geindex pthread_kill() (signal モジュール)
@anchor{library/signal signal pthread_kill}@anchor{1349}
@deffn {の関数} signal.pthread_kill (thread_id, signalnum)

Send the signal `signalnum' to the thread `thread_id', another thread in the
same process as the caller.  The target thread can be executing any code
(Python or not).  However, if the target thread is executing the Python
interpreter, the Python signal handlers will be @ref{3a5d,,executed by the main thread of the main interpreter}.  Therefore, the only point of sending a
signal to a particular Python thread would be to force a running system call
to fail with @ref{f88,,InterruptedError}.

Use @ref{1372,,threading.get_ident()} or the @ref{3137,,ident}
attribute of @ref{176,,threading.Thread} objects to get a suitable value
for `thread_id'.

If `signalnum' is 0, then no signal is sent, but error checking is still
performed; this can be used to check if the target thread is still running.

引数 @code{thread_id}, @code{signalnum} を指定して @ref{1c6e,,監査イベント} @code{signal.pthread_kill} を送出します。

@ref{213f,,Availability}: Unix.

See the man page @code{pthread_kill(3)@footnote{https://manpages.debian.org/pthread_kill(3)}} for further  information.

@ref{157f,,os.kill()} を参照してください。


Added in version 3.3.

@end deffn

@geindex pthread_sigmask() (signal モジュール)
@anchor{library/signal signal pthread_sigmask}@anchor{1348}
@deffn {の関数} signal.pthread_sigmask (how, mask)

これを呼び出すスレッドにセットされているシグナルマスクを取り出したり変更したりします。シグナルマスクは、呼び出し側のために現在どのシグナルの配送がブロックされているかを示す集合 (set) です。呼び出し前のもとのシグナルマスクを集合として返却します。

この関数の振る舞いは `how' に依存して以下のようになります。


@itemize *

@item 
@ref{3a5f,,SIG_BLOCK}: `mask' で指定されるシグナルが現時点のシグナルマスクに追加されます。

@item 
@ref{3a60,,SIG_UNBLOCK}: `mask' で指定されるシグナルが現時点のシグナルマスクから取り除かれます。もともとブロックされていないシグナルをブロック解除しようとしても問題ありません。

@item 
@ref{3a61,,SIG_SETMASK}: シグナルマスク全体を `mask' としてセットします。
@end itemize

`mask' はシグナル番号の集合です (例えば @{@ref{253,,signal.SIGINT}, @ref{15f8,,signal.SIGTERM}@})。全てのシグナルを含む全集合として @ref{3a71,,valid_signals()} を使うことが出来ます。

呼び出しスレッドにセットされたシグナルマスクを問い合わせるには例えば @code{signal.pthread_sigmask(signal.SIG_BLOCK, [])} とします。

@ref{d50,,SIGKILL} and @ref{3a6b,,SIGSTOP} cannot be blocked.

@ref{213f,,Availability}: Unix.

See the man page @code{sigprocmask(2)@footnote{https://manpages.debian.org/sigprocmask(2)}} and
@code{pthread_sigmask(3)@footnote{https://manpages.debian.org/pthread_sigmask(3)}} for further information.

@ref{3a79,,pause()}, @ref{134a,,sigpending()}, @ref{134b,,sigwait()} も参照して下さい。


Added in version 3.3.

@end deffn

@geindex setitimer() (signal モジュール)
@anchor{library/signal signal setitimer}@anchor{3a76}
@deffn {の関数} signal.setitimer (which, seconds, interval=0.0)

`which' で指定されたタイマー (@ref{3a72,,signal.ITIMER_REAL}, @ref{3a73,,signal.ITIMER_VIRTUAL}, @ref{3a74,,signal.ITIMER_PROF} のどれか) を、 `seconds' 秒後と (@ref{3a78,,alarm()} と異なり、floatを指定できます)、それから (`interval' が0でなければ) `interval' 秒間隔で起動するように設定します。 `seconds' に0を指定すると、`which' で指定されたタイマーをクリアすることができます。

インターバルタイマーが起動したとき、シグナルがプロセスに送られます。送られるシグナルは利用されたタイマーの種類に依存します。 @ref{3a72,,signal.ITIMER_REAL} の場合は @ref{3a66,,SIGALRM} が、 @ref{3a73,,signal.ITIMER_VIRTUAL} の場合は @ref{3a6e,,SIGVTALRM} が、 @ref{3a74,,signal.ITIMER_PROF} の場合は @ref{3a6a,,SIGPROF} が送られます。

以前の値が (delay, interval) のタプルとして返されます。

無効なインターバルタイマーを渡すと @ref{3a75,,ItimerError} 例外が発生します。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex getitimer() (signal モジュール)
@anchor{library/signal signal getitimer}@anchor{3a77}
@deffn {の関数} signal.getitimer (which)

`which' で指定されたインターバルタイマーの現在の値を返します。

@ref{213f,,Availability}: Unix.
@end deffn

@geindex set_wakeup_fd() (signal モジュール)
@anchor{library/signal signal set_wakeup_fd}@anchor{d67}
@deffn {の関数} signal.set_wakeup_fd (fd, *, warn_on_full_buffer=True)

Set the wakeup file descriptor to `fd'.  When a signal your program has
registered a signal handler for is received, the signal number is written as
a single byte into the fd.  If you haven't registered a signal handler for
the signals you care about, then nothing will be written to the wakeup fd.
This can be used by a library to wakeup a poll or select call, allowing the
signal to be fully processed.

The old wakeup fd is returned (or -1 if file descriptor wakeup was not
enabled).  If `fd' is -1, file descriptor wakeup is disabled.
If not -1, `fd' must be non-blocking.  It is up to the library to remove
any bytes from `fd' before calling poll or select again.

スレッドが有効な場合、この関数は @ref{3a5d,,メインインタープリターのメインスレッド} からしか実行できません。それ以外のスレッドからこの関数を実行しようとすると @ref{2ec,,ValueError} 例外が発生します。

There are two common ways to use this function. In both approaches,
you use the fd to wake up when a signal arrives, but then they
differ in how they determine `which' signal or signals have
arrived.

In the first approach, we read the data out of the fd's buffer, and
the byte values give you the signal numbers. This is simple, but in
rare cases it can run into a problem: generally the fd will have a
limited amount of buffer space, and if too many signals arrive too
quickly, then the buffer may become full, and some signals may be
lost. If you use this approach, then you should set
@code{warn_on_full_buffer=True}, which will at least cause a warning
to be printed to stderr when signals are lost.

In the second approach, we use the wakeup fd `only' for wakeups,
and ignore the actual byte values. In this case, all we care about
is whether the fd's buffer is empty or non-empty; a full buffer
doesn't indicate a problem at all. If you use this approach, then
you should set @code{warn_on_full_buffer=False}, so that your users
are not confused by spurious warning messages.


バージョン 3.5 で変更: Windowsで、この関数はソケットハンドルをサポートするようになりました。



バージョン 3.7 で変更: @code{warn_on_full_buffer} 引数が追加されました。

@end deffn

@geindex siginterrupt() (signal モジュール)
@anchor{library/signal signal siginterrupt}@anchor{134d}
@deffn {の関数} signal.siginterrupt (signalnum, flag)

システムコールのリスタートの動作を変更します。 `flag' が @ref{d2b,,False} の場合、 `signalnum' シグナルに中断されたシステムコールは再実行されます。それ以外の場合、システムコールは中断されます。戻り値はありません。

@ref{213f,,Availability}: Unix.

See the man page @code{siginterrupt(3)@footnote{https://manpages.debian.org/siginterrupt(3)}} for further information.

Note that installing a signal handler with @ref{cb,,signal()} will reset the
restart behaviour to interruptible by implicitly calling
@code{siginterrupt()} with a true `flag' value for the given signal.
@end deffn

@geindex signal() (signal モジュール)
@anchor{library/signal signal signal}@anchor{134c}
@deffn {の関数} signal.signal (signalnum, handler)

シグナル `signalnum' に対するハンドラを関数 `handler' にします。 `handler' は二つの引数 (下記参照) を取る呼び出し可能な Python オブジェクトか、 @ref{1bb1,,signal.SIG_IGN} あるいは @ref{1bb2,,signal.SIG_DFL} といった特殊な値にすることができます。以前に使われていたシグナルハンドラが返されます (上記の @ref{1a25,,getsignal()} の記述を参照してください)。 (さらに詳しい情報については Unix マニュアルページ @code{signal(2)@footnote{https://manpages.debian.org/signal(2)}} を参照してください。)

スレッドが有効な場合、この関数は @ref{3a5d,,メインインタープリターのメインスレッド} からしか実行できません。それ以外のスレッドからこの関数を実行しようとすると @ref{2ec,,ValueError} 例外が発生します。

`handler' は二つの引数とともに呼び出されます: シグナル番号、および現在のスタックフレーム (@code{None} またはフレームオブジェクト; フレームオブジェクトについての記述は @ref{8ef,,標準型の階層における説明} か、 @ref{82,,inspect} モジュールの属性の説明を参照してください)。

On Windows, @ref{cb,,signal()} can only be called with @ref{128e,,SIGABRT},
@ref{128d,,SIGFPE}, @ref{1290,,SIGILL}, @ref{253,,SIGINT}, @ref{128c,,SIGSEGV},
@ref{15f8,,SIGTERM}, or @ref{3a67,,SIGBREAK}.
A @ref{2ec,,ValueError} will be raised in any other case.
Note that not all systems define the same set of signal names; an
@ref{5f0,,AttributeError} will be raised if a signal name is not defined as
@code{SIG*} module level constant.
@end deffn

@geindex sigpending() (signal モジュール)
@anchor{library/signal signal sigpending}@anchor{134a}
@deffn {の関数} signal.sigpending ()

呼び出しスレッドで配送が保留されているシグナル (つまり配送がブロックされている間に発生したシグナル) の集合を調べます。保留中のシグナルの集合を返します。

@ref{213f,,Availability}: Unix.

See the man page @code{sigpending(2)@footnote{https://manpages.debian.org/sigpending(2)}} for further information.

@ref{3a79,,pause()}, @ref{1348,,pthread_sigmask()}, @ref{134b,,sigwait()} も参照して下さい。


Added in version 3.3.

@end deffn

@geindex sigwait() (signal モジュール)
@anchor{library/signal signal sigwait}@anchor{134b}
@deffn {の関数} signal.sigwait (sigset)

`sigset' 集合で指定されたシグナルのうちどれか一つが届くまで呼び出しスレッドを一時停止します。この関数はそのシグナルを受け取ると (それを保留シグナルリストから取り除いて) そのシグナル番号を返します。

@ref{213f,,Availability}: Unix.

See the man page @code{sigwait(3)@footnote{https://manpages.debian.org/sigwait(3)}} for further information.

@ref{3a79,,pause()}, @ref{1348,,pthread_sigmask()}, @ref{134a,,sigpending()}, @ref{fab,,sigwaitinfo()}, @ref{faa,,sigtimedwait()} も参照して下さい。


Added in version 3.3.

@end deffn

@geindex sigwaitinfo() (signal モジュール)
@anchor{library/signal signal sigwaitinfo}@anchor{fab}
@deffn {の関数} signal.sigwaitinfo (sigset)

Suspend execution of the calling thread until the delivery of one of the
signals specified in the signal set `sigset'.  The function accepts the
signal and removes it from the pending list of signals. If one of the
signals in `sigset' is already pending for the calling thread, the function
will return immediately with information about that signal. The signal
handler is not called for the delivered signal. The function raises an
@ref{f88,,InterruptedError} if it is interrupted by a signal that is not in
`sigset'.

The return value is an object representing the data contained in the
@code{siginfo_t} structure, namely: @code{si_signo}, @code{si_code},
@code{si_errno}, @code{si_pid}, @code{si_uid}, @code{si_status}, @code{si_band}.

@ref{213f,,Availability}: Unix.

See the man page @code{sigwaitinfo(2)@footnote{https://manpages.debian.org/sigwaitinfo(2)}} for further information.

@ref{3a79,,pause()}, @ref{134b,,sigwait()}, @ref{faa,,sigtimedwait()} も参照して下さい。


Added in version 3.3.



バージョン 3.5 で変更: The function is now retried if interrupted by a signal not in `sigset'
and the signal handler does not raise an exception (see 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} for
the rationale).

@end deffn

@geindex sigtimedwait() (signal モジュール)
@anchor{library/signal signal sigtimedwait}@anchor{faa}
@deffn {の関数} signal.sigtimedwait (sigset, timeout)

Like @ref{fab,,sigwaitinfo()}, but takes an additional `timeout' argument
specifying a timeout. If `timeout' is specified as @code{0}, a poll is
performed. Returns @ref{885,,None} if a timeout occurs.

@ref{213f,,Availability}: Unix.

See the man page @code{sigtimedwait(2)@footnote{https://manpages.debian.org/sigtimedwait(2)}} for further information.

@ref{3a79,,pause()}, @ref{134b,,sigwait()}, @ref{fab,,sigwaitinfo()} も参照して下さい。


Added in version 3.3.



バージョン 3.5 で変更: The function is now retried with the recomputed `timeout' if interrupted
by a signal not in `sigset' and the signal handler does not raise an
exception (see 
@geindex Python Enhancement Proposals; PEP 475
PEP 475@footnote{https://peps.python.org/pep-0475/} for the rationale).

@end deffn

@node 使用例<30>,Note on SIGPIPE,モジュールの内容<2>,signal --- 非同期イベントにハンドラーを設定する
@anchor{library/signal examples}@anchor{3a7a}@anchor{library/signal signal-example}@anchor{3a7b}
@subsubsection 使用例


以下は最小限のプログラム例です。この例では @ref{3a78,,alarm()} を使ってファイルを開く処理を待つのに費やす時間を制限します; 例えば、電源の入っていないシリアルデバイスを開こうとすると、通常 @ref{f92,,os.open()} は未定義の期間ハングアップしてしまいますが、この方法はそうした場合に便利です。ここではファイルを開くまで 5 秒間のアラームを設定することで解決しています; ファイルを開く処理が長くかかりすぎると、アラームシグナルが送信され、ハンドラが例外を送出するようになっています。

@example
import signal, os

def handler(signum, frame):
    signame = signal.Signals(signum).name
    print(f'Signal handler called with signal @{signame@} (@{signum@})')
    raise OSError("Couldn't open device!")

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)

# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)

signal.alarm(0)          # Disable the alarm
@end example

@node Note on SIGPIPE,Note on Signal Handlers and Exceptions,使用例<30>,signal --- 非同期イベントにハンドラーを設定する
@anchor{library/signal note-on-sigpipe}@anchor{3a7c}
@subsubsection Note on SIGPIPE


Piping output of your program to tools like @code{head(1)@footnote{https://manpages.debian.org/head(1)}} will
cause a @ref{3a59,,SIGPIPE} signal to be sent to your process when the receiver
of its standard output closes early.  This results in an exception
like @code{BrokenPipeError: [Errno 32] Broken pipe}.  To handle this
case, wrap your entry point to catch this exception as follows:

@example
import os
import sys

def main():
    try:
        # simulate large output (your code replaces this loop)
        for x in range(10000):
            print("y")
        # flush output here to force SIGPIPE to be triggered
        # while inside this try block.
        sys.stdout.flush()
    except BrokenPipeError:
        # Python flushes standard streams on exit; redirect remaining output
        # to devnull to avoid another BrokenPipeError at shutdown
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(1)  # Python exits with error code 1 on EPIPE

if __name__ == '__main__':
    main()
@end example

Do not set @ref{3a59,,SIGPIPE}'s disposition to @ref{1bb2,,SIG_DFL} in
order to avoid @ref{1267,,BrokenPipeError}.  Doing that would cause
your program to exit unexpectedly whenever any socket
connection is interrupted while your program is still writing to
it.

@node Note on Signal Handlers and Exceptions,,Note on SIGPIPE,signal --- 非同期イベントにハンドラーを設定する
@anchor{library/signal handlers-and-exceptions}@anchor{26ec}@anchor{library/signal note-on-signal-handlers-and-exceptions}@anchor{3a7d}
@subsubsection Note on Signal Handlers and Exceptions


If a signal handler raises an exception, the exception will be propagated to
the main thread and may be raised after any @ref{4aa,,bytecode} instruction. Most
notably, a @ref{bc5,,KeyboardInterrupt} may appear at any point during execution.
Most Python code, including the standard library, cannot be made robust against
this, and so a @ref{bc5,,KeyboardInterrupt} (or any other exception resulting from
a signal handler) may on rare occasions put the program in an unexpected state.

To illustrate this issue, consider the following code:

@example
class SpamContext:
    def __init__(self):
        self.lock = threading.Lock()

    def __enter__(self):
        # If KeyboardInterrupt occurs here, everything is fine
        self.lock.acquire()
        # If KeyboardInterrupt occurs here, __exit__ will not be called
        ...
        # KeyboardInterrupt could occur just before the function returns

    def __exit__(self, exc_type, exc_val, exc_tb):
        ...
        self.lock.release()
@end example

For many programs, especially those that merely want to exit on
@ref{bc5,,KeyboardInterrupt}, this is not a problem, but applications that are
complex or require high reliability should avoid raising exceptions from signal
handlers. They should also avoid catching @ref{bc5,,KeyboardInterrupt} as a means
of gracefully shutting down.  Instead, they should install their own
@ref{253,,SIGINT} handler. Below is an example of an HTTP server that avoids
@ref{bc5,,KeyboardInterrupt}:

@example
import signal
import socket
from selectors import DefaultSelector, EVENT_READ
from http.server import HTTPServer, SimpleHTTPRequestHandler

interrupt_read, interrupt_write = socket.socketpair()

def handler(signum, frame):
    print('Signal handler called with signal', signum)
    interrupt_write.send(b'\0')
signal.signal(signal.SIGINT, handler)

def serve_forever(httpd):
    sel = DefaultSelector()
    sel.register(interrupt_read, EVENT_READ)
    sel.register(httpd, EVENT_READ)

    while True:
        for key, _ in sel.select():
            if key.fileobj == interrupt_read:
                interrupt_read.recv(1)
                return
            if key.fileobj == httpd:
                httpd.handle_request()

print("Serving on port 8000")
httpd = HTTPServer(('@w{'}, 8000), SimpleHTTPRequestHandler)
serve_forever(httpd)
print("Shutdown...")
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node mmap --- メモリマップファイルのサポート,,signal --- 非同期イベントにハンドラーを設定する,ネットワーク通信とプロセス間通信
@anchor{library/mmap doc}@anchor{3a7e}@anchor{library/mmap mmap-memory-mapped-file-support}@anchor{3a7f}@anchor{library/mmap module-mmap}@anchor{94}@anchor{library/mmap translation-repo}@anchor{3a80}
@subsection @code{mmap} --- メモリマップファイルのサポート


@geindex module; mmap


__________________________________________________________________


@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

メモリにマップされたファイルオブジェクトは、 @ref{344,,bytearray} と @ref{13db,,ファイルオブジェクト} の両方のように振舞います。しかし通常の文字列オブジェクトとは異なり、これらは可変です。 @ref{344,,bytearray} が期待されるほとんどの場所で mmap オブジェクトを利用できます。例えば、メモリマップファイルを探索するために @ref{be,,re} モジュールを使うことができます。それらは可変なので、 @code{obj[index] = 97} のように文字を変換できますし、スライスを使うことで  @code{obj[i1:i2] = b'...'} のように部分文字列を変換することができます。現在のファイル位置をデータの始めとする読込みや書込み、ファイルの異なる位置へ @code{seek()} することもできます。

メモリマップドファイルは Unix と Windows で異なる @ref{519,,mmap} コンストラクタで生成されます。どちらの場合も、更新用に開かれたファイル記述子を渡さなければなりません。既存の Python ファイルオブジェクトをマップしたければ、 @ref{17ad,,fileno()} メソッドを使って `fileno' パラメータの正しい値を取得してください。そうでなければ、 @ref{f92,,os.open()} 関数を使ってファイルを開けます。この関数はファイルディスクリプタを直接返します(処理が終わったら、やはりファイルを閉じる必要があります)。

@cartouche
@quotation 注釈 
書き込み可能でバッファされたファイルへのメモリマップファイルを作りたいのであれば、まず最初にファイルの @ref{2ce6,,flush()} を呼び出すべきです。これはバッファへのローカルな修正がマッピングで実際に利用可能になることを保障するために必要です。
@end quotation
@end cartouche

Unix バージョンと Windows バージョンのどちらのコンストラクタについても、オプションのキーワード・パラメータとして `access' を指定できます。 `access' は4つの値の内の1つを受け入れます。 @code{ACCESS_READ} は読み出し専用、 @code{ACCESS_WRITE} は書き込み可能、 @code{ACCESS_COPY} はコピーした上での書き込み、@code{ACCESS_DEFAULT} は `prot' に従います。 `access' は Unix と Windows の両方で使用することができます。 `access' が指定されない場合、 Windows の mmap は書き込み可能マップを返します。 3つのアクセス型すべてに対する初期メモリ値は、指定されたファイルから得られます。 @code{ACCESS_READ} 型のメモリマップに対して書き込むと @ref{198,,TypeError} 例外を送出します。 @code{ACCESS_WRITE} 型のメモリマップへの書き込みはメモリと元のファイルの両方に影響を与えます。 @code{ACCESS_COPY} 型のメモリマップへの書き込みはメモリに影響を与えますが、元のファイルを更新することはありません。


バージョン 3.7 で変更: 定数 @code{ACCESS_DEFAULT} が追加されました。


無名メモリ(anonymous memory)にマップするためには fileno として -1 を渡し、length を与えてください。

@geindex mmap (mmap のクラス)
@anchor{library/mmap mmap mmap}@anchor{519}
@deffn {クラス} mmap.mmap (fileno, length, tagname=None, access=ACCESS_DEFAULT, offset=0)

`(Windows バージョン)' ファイルハンドル `fileno' によって指定されたファイルから `length' バイトをマップして、 mmap オブジェクトを生成します。 `length' が現在のファイルサイズより大きな場合、ファイルサイズは `length' を含む大きさにまで拡張されます。 `length' が @code{0} の場合、マップの最大の長さは現在のファイルサイズになります。ただし、ファイル自体が空のときは Windows が例外を送出します (Windows では空のマップを作成することができません)。

`tagname' は、 @code{None} 以外で指定された場合、マップのタグ名を与える文字列となります。 Windows は同じファイルに対する様々なマップを持つことを可能にします。既存のタグの名前を指定すればそのタグがオープンされ、そうでなければこの名前の新しいタグが作成されます。もしこのパラメータを省略したり @code{None} を与えたりしたならば、マップは名前なしで作成されます。 "tagname" パラメータの使用の回避は、あなたのコードを Unix と Windows の間で移植可能にしておくのを助けてくれるでしょう。

`offset' は非負整数のオフセットとして指定できます。mmap の参照はファイルの先頭からのオフセットに相対的になります。`offset' のデフォルトは 0 です。`offset' は  @code{ALLOCATIONGRANULARITY} の倍数でなければなりません。

引数 @code{fileno}, @code{length}, @code{access}, @code{offset} 付きで @ref{1c6e,,監査イベント} @code{mmap.__new__} を送出します。
@end deffn


@deffn {クラス} mmap.mmap (fileno, length, flags=MAP_SHARED, prot=PROT_WRITE | PROT_READ, access=ACCESS_DEFAULT, offset=0, *, trackfd=True)

`(Unix バージョン)' ファイルディスクリプタ `fileno' で指定されたファイルから `length' バイトをマップし、mmap オブジェクトを返します。`length' が @code{0} の場合、マップの最大の長さは @ref{519,,mmap} が呼ばれた時点でのファイルサイズになります。

`flags' specifies the nature of the mapping. @ref{3a81,,MAP_PRIVATE} creates a
private copy-on-write mapping, so changes to the contents of the mmap
object will be private to this process, and @ref{3a82,,MAP_SHARED} creates a
mapping that's shared with all other processes mapping the same areas of
the file.  The default value is @ref{3a82,,MAP_SHARED}. Some systems have
additional possible flags with the full list specified in
@ref{3a83,,MAP_* constants}.

`prot' が指定された場合、希望のメモリ保護を与えます。 2つの最も有用な値は、 @code{PROT_READ} と @code{PROT_WRITE} です。これは、読込み可能または書込み可能を指定するものです。 `prot' のデフォルトは @code{PROT_READ | PROT_WRITE} です。

`access' はオプションのキーワード・パラメータとして、 `flags' と `prot' の代わりに指定してもかまいません。 `flags', `prot' と `access' の両方を指定することは間違っています。このパラメータの使用法についての情報は、先に述べた `access' の記述を参照してください。

`offset' may be specified as a non-negative integer offset. mmap references
will be relative to the offset from the beginning of the file. `offset'
defaults to 0. `offset' must be a multiple of @code{ALLOCATIONGRANULARITY}
which is equal to @code{PAGESIZE} on Unix systems.

If `trackfd' is @code{False}, the file descriptor specified by `fileno' will
not be duplicated, and the resulting @code{mmap} object will not
be associated with the map's underlying file.
This means that the @ref{3a84,,size()} and @ref{3a85,,resize()}
methods will fail.
This mode is useful to limit the number of open file descriptors.

macOS において、作成された memory mapping の正当性を確実にするために `fileno' で指定されたファイルディスクリプタは内部で自動的に物理的なストレージ (physical backing store) と同期されます。


バージョン 3.13 で変更: `trackfd' パラメータが追加されました。


この例は @ref{519,,mmap} の簡潔な使い方を示すものです:

@example
import mmap

# write a simple example file
with open("hello.txt", "wb") as f:
    f.write(b"Hello Python!\n")

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print(mm.readline())  # prints b"Hello Python!\n"
    # read content via slice notation
    print(mm[:5])  # prints b"Hello"
    # update content using slice notation;
    # note that new content must have same size
    mm[6:] = b" world!\n"
    # ... and read again using standard file methods
    mm.seek(0)
    print(mm.readline())  # prints b"Hello  world!\n"
    # close the map
    mm.close()
@end example

@ref{519,,mmap} は @ref{186,,with} 文の中でコンテキストマネージャとしても使えます:

@example
import mmap

with mmap.mmap(-1, 13) as mm:
    mm.write(b"Hello world!")
@end example


Added in version 3.2: コンテキストマネージャのサポート。


次の例では無名マップを作り親プロセスと子プロセスの間でデータのやりとりをしてみせます:

@example
import mmap
import os

mm = mmap.mmap(-1, 13)
mm.write(b"Hello world!")

pid = os.fork()

if pid == 0:  # In a child process
    mm.seek(0)
    print(mm.readline())

    mm.close()
@end example

引数 @code{fileno}, @code{length}, @code{access}, @code{offset} 付きで @ref{1c6e,,監査イベント} @code{mmap.__new__} を送出します。

メモリマップファイルオブジェクトは以下のメソッドをサポートしています:

@geindex close() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap close}@anchor{3a86}
@deffn {メソッド} close ()

メモリマップファイルを閉じます。この呼出しの後にオブジェクトの他のメソッドの呼出すことは、 @ref{2ec,,ValueError} 例外の送出を引き起こします。このメソッドは開いたファイルのクローズはしません。
@end deffn

@geindex closed (mmap.mmap の属性)
@anchor{library/mmap mmap mmap closed}@anchor{3a87}
@deffn {の属性} closed

ファイルが閉じている場合 @code{True} となります。


Added in version 3.2.

@end deffn

@geindex find() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap find}@anchor{3a88}
@deffn {メソッド} find (sub[, start[, end]])

オブジェクト内の [`start', `end'] の範囲に含まれている部分シーケンス `sub' が見つかった場所の最も小さいインデックスを返します。オプションの引数 `start' と `end' はスライスに使われるときのように解釈されます。失敗したときには @code{-1} を返します。


バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。

@end deffn

@geindex flush() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap flush}@anchor{c8f}
@deffn {メソッド} flush ()

@deffnx {メソッド} flush (offset, size, /)

Flushes changes made to the in-memory copy of a file back to disk. Without
use of this call there is no guarantee that changes are written back before
the object is destroyed.  If `offset' and `size' are specified, only
changes to the given range of bytes will be flushed to disk; otherwise, the
whole extent of the mapping is flushed.  `offset' must be a multiple of the
@code{PAGESIZE} or @code{ALLOCATIONGRANULARITY}.

@code{None} が返されたら成功を意味します。呼び出しが失敗すると例外が送出されます。


バージョン 3.8 で変更: Previously, a nonzero value was returned on success; zero was returned
on error under Windows.  A zero value was returned on success; an
exception was raised on error under Unix.

@end deffn

@geindex madvise() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap madvise}@anchor{bfb}
@deffn {メソッド} madvise (option[, start[, length]])

Send advice `option' to the kernel about the memory region beginning at
`start' and extending `length' bytes.  `option' must be one of the
@ref{3a89,,MADV_* constants} available on the system.  If
`start' and `length' are omitted, the entire mapping is spanned.  On
some systems (including Linux), `start' must be a multiple of the
@code{PAGESIZE}.

Availability: Systems with the @code{madvise()} system call.


Added in version 3.8.

@end deffn

@geindex move() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap move}@anchor{3a8a}
@deffn {メソッド} move (dest, src, count)

オフセット `src' から始まる `count' バイトをインデックス `dest' の位置へコピーします。もし mmap が @code{ACCESS_READ} で作成されていた場合、 @ref{198,,TypeError} 例外を発生させます。
@end deffn

@geindex read() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap read}@anchor{12f5}
@deffn {メソッド} read ([n])

現在のファイル位置からの最大 `n' バイトを含む @ref{192,,bytes} を返します。引数が省略されるか、 @code{None} もしくは負の値が指定された場合、現在のファイル位置からマップ終端までの全てのバイト列を返します。ファイル位置は返されたバイト列の直後を指すように更新されます。


バージョン 3.3 で変更: 引数が省略可能になり、 @code{None} も受け付けるようになりました。

@end deffn

@geindex read_byte() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap read_byte}@anchor{3a8b}
@deffn {メソッド} read_byte ()

現在のファイル位置のバイトを整数値として返し、ファイル位置を 1 進めます。
@end deffn

@geindex readline() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap readline}@anchor{3a8c}
@deffn {メソッド} readline ()

Returns a single line, starting at the current file position and up to the
next newline. The file position is updated to point after the bytes that were
returned.
@end deffn

@geindex resize() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap resize}@anchor{3a85}
@deffn {メソッド} resize (newsize)

Resizes the map and the underlying file, if any.

Resizing a map created with `access' of @code{ACCESS_READ} or
@code{ACCESS_COPY}, will raise a @ref{198,,TypeError} exception.
Resizing a map created with `trackfd' set to @code{False},
will raise a @ref{2ec,,ValueError} exception.

`On Windows': Resizing the map will raise an @ref{2c0,,OSError} if there are other
maps against the same named file. Resizing an anonymous map (ie against the
pagefile) will silently create a new map with the original data copied over
up to the length of the new size.


バージョン 3.11 で変更: Correctly fails if attempting to resize when another map is held
Allows resize against an anonymous map on Windows

@end deffn

@geindex rfind() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap rfind}@anchor{3a8d}
@deffn {メソッド} rfind (sub[, start[, end]])

オブジェクト内の [`start', `end'] の範囲に含まれている部分シーケンス `sub' が見つかった場所の最も大きいインデックスを返します。オプションの引数 `start' と `end' はスライスに使われるときのように解釈されます。失敗したときには @code{-1} を返します。


バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。

@end deffn

@geindex seek() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap seek}@anchor{51b}
@deffn {メソッド} seek (pos[, whence])

ファイルの現在位置をセットします。 `whence' 引数はオプションであり、デフォルトは @code{os.SEEK_SET} つまり @code{0} (絶対位置)です。その他の値として、 @code{os.SEEK_CUR} つまり @code{1} (現在位置からの相対位置)と @code{os.SEEK_END} つまり @code{2} (ファイルの終わりからの相対位置)があります。


バージョン 3.13 で変更: @code{None} ではなく新しい絶対位置を返します。

@end deffn

@geindex seekable() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap seekable}@anchor{51a}
@deffn {メソッド} seekable ()

Return whether the file supports seeking, and the return value is always @code{True}.


Added in version 3.13.

@end deffn

@geindex size() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap size}@anchor{3a84}
@deffn {メソッド} size ()

ファイルの長さを返します。メモリマップ領域のサイズより大きいかもしれません。
@end deffn

@geindex tell() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap tell}@anchor{3a8e}
@deffn {メソッド} tell ()

ファイルポインタの現在位置を返します。
@end deffn

@geindex write() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap write}@anchor{f46}
@deffn {メソッド} write (bytes)

メモリ内のファイルポイントの現在位置に `bytes' のバイト列を書き込み、書き込まれたバイト数を返します(もし書き込みが失敗したら @ref{2ec,,ValueError} が送出されるため、@code{len(bytes)} より少なくなりません)。ファイル位置はバイト列が書き込まれた位置に更新されます。もしmmapが @code{ACCESS_READ} とともに作成されていた場合は、書き込みは @ref{198,,TypeError} 例外を送出するでしょう。


バージョン 3.5 で変更: 書き込み可能な @ref{193,,bytes-like object} を使用できるようになりました。



バージョン 3.6 で変更: 書きこまれたバイト数を返すようになりました。

@end deffn

@geindex write_byte() (mmap.mmap のメソッド)
@anchor{library/mmap mmap mmap write_byte}@anchor{3a8f}
@deffn {メソッド} write_byte (byte)

メモリ内のファイル・ポインタの現在位置に整数 `byte' を書き込みます。ファイル位置は @code{1} だけ進みます。もし mmap が @code{ACCESS_READ} で作成されていた場合、書き込み時に @ref{198,,TypeError} 例外を発生させるでしょう。
@end deffn
@end deffn

@menu
* MADV_* 定数:: 
* MAP_* 定数:: 

@end menu

@node MADV_* 定数,MAP_* 定数,,mmap --- メモリマップファイルのサポート
@anchor{library/mmap madv-constants}@anchor{3a90}@anchor{library/mmap madvise-constants}@anchor{3a89}
@subsubsection MADV_* 定数


@geindex MADV_NORMAL (mmap モジュール)
@geindex MADV_RANDOM (mmap モジュール)
@geindex MADV_SEQUENTIAL (mmap モジュール)
@geindex MADV_WILLNEED (mmap モジュール)
@geindex MADV_DONTNEED (mmap モジュール)
@geindex MADV_REMOVE (mmap モジュール)
@geindex MADV_DONTFORK (mmap モジュール)
@geindex MADV_DOFORK (mmap モジュール)
@geindex MADV_HWPOISON (mmap モジュール)
@geindex MADV_MERGEABLE (mmap モジュール)
@geindex MADV_UNMERGEABLE (mmap モジュール)
@geindex MADV_SOFT_OFFLINE (mmap モジュール)
@geindex MADV_HUGEPAGE (mmap モジュール)
@geindex MADV_NOHUGEPAGE (mmap モジュール)
@geindex MADV_DONTDUMP (mmap モジュール)
@geindex MADV_DODUMP (mmap モジュール)
@geindex MADV_FREE (mmap モジュール)
@geindex MADV_NOSYNC (mmap モジュール)
@geindex MADV_AUTOSYNC (mmap モジュール)
@geindex MADV_NOCORE (mmap モジュール)
@geindex MADV_CORE (mmap モジュール)
@geindex MADV_PROTECT (mmap モジュール)
@geindex MADV_FREE_REUSABLE (mmap モジュール)
@geindex MADV_FREE_REUSE (mmap モジュール)
@anchor{library/mmap mmap MADV_NORMAL}@anchor{3a91}
@deffn {データ} mmap.MADV_NORMAL
@anchor{library/mmap mmap MADV_RANDOM}@anchor{3a92}
@deffnx {データ} mmap.MADV_RANDOM
@anchor{library/mmap mmap MADV_SEQUENTIAL}@anchor{3a93}
@deffnx {データ} mmap.MADV_SEQUENTIAL
@anchor{library/mmap mmap MADV_WILLNEED}@anchor{3a94}
@deffnx {データ} mmap.MADV_WILLNEED
@anchor{library/mmap mmap MADV_DONTNEED}@anchor{3a95}
@deffnx {データ} mmap.MADV_DONTNEED
@anchor{library/mmap mmap MADV_REMOVE}@anchor{3a96}
@deffnx {データ} mmap.MADV_REMOVE
@anchor{library/mmap mmap MADV_DONTFORK}@anchor{3a97}
@deffnx {データ} mmap.MADV_DONTFORK
@anchor{library/mmap mmap MADV_DOFORK}@anchor{3a98}
@deffnx {データ} mmap.MADV_DOFORK
@anchor{library/mmap mmap MADV_HWPOISON}@anchor{3a99}
@deffnx {データ} mmap.MADV_HWPOISON
@anchor{library/mmap mmap MADV_MERGEABLE}@anchor{3a9a}
@deffnx {データ} mmap.MADV_MERGEABLE
@anchor{library/mmap mmap MADV_UNMERGEABLE}@anchor{3a9b}
@deffnx {データ} mmap.MADV_UNMERGEABLE
@anchor{library/mmap mmap MADV_SOFT_OFFLINE}@anchor{3a9c}
@deffnx {データ} mmap.MADV_SOFT_OFFLINE
@anchor{library/mmap mmap MADV_HUGEPAGE}@anchor{3a9d}
@deffnx {データ} mmap.MADV_HUGEPAGE
@anchor{library/mmap mmap MADV_NOHUGEPAGE}@anchor{3a9e}
@deffnx {データ} mmap.MADV_NOHUGEPAGE
@anchor{library/mmap mmap MADV_DONTDUMP}@anchor{3a9f}
@deffnx {データ} mmap.MADV_DONTDUMP
@anchor{library/mmap mmap MADV_DODUMP}@anchor{3aa0}
@deffnx {データ} mmap.MADV_DODUMP
@anchor{library/mmap mmap MADV_FREE}@anchor{3aa1}
@deffnx {データ} mmap.MADV_FREE
@anchor{library/mmap mmap MADV_NOSYNC}@anchor{3aa2}
@deffnx {データ} mmap.MADV_NOSYNC
@anchor{library/mmap mmap MADV_AUTOSYNC}@anchor{3aa3}
@deffnx {データ} mmap.MADV_AUTOSYNC
@anchor{library/mmap mmap MADV_NOCORE}@anchor{3aa4}
@deffnx {データ} mmap.MADV_NOCORE
@anchor{library/mmap mmap MADV_CORE}@anchor{3aa5}
@deffnx {データ} mmap.MADV_CORE
@anchor{library/mmap mmap MADV_PROTECT}@anchor{3aa6}
@deffnx {データ} mmap.MADV_PROTECT
@anchor{library/mmap mmap MADV_FREE_REUSABLE}@anchor{3aa7}
@deffnx {データ} mmap.MADV_FREE_REUSABLE
@anchor{library/mmap mmap MADV_FREE_REUSE}@anchor{3aa8}
@deffnx {データ} mmap.MADV_FREE_REUSE

These options can be passed to @ref{bfb,,mmap.madvise()}.  Not every option will
be present on every system.

Availability: Systems with the madvise() system call.


Added in version 3.8.

@end deffn

@node MAP_* 定数,,MADV_* 定数,mmap --- メモリマップファイルのサポート
@anchor{library/mmap id1}@anchor{3aa9}@anchor{library/mmap map-constants}@anchor{3a83}
@subsubsection MAP_* 定数


@geindex MAP_SHARED (mmap モジュール)
@geindex MAP_PRIVATE (mmap モジュール)
@geindex MAP_32BIT (mmap モジュール)
@geindex MAP_ALIGNED_SUPER (mmap モジュール)
@geindex MAP_ANON (mmap モジュール)
@geindex MAP_ANONYMOUS (mmap モジュール)
@geindex MAP_CONCEAL (mmap モジュール)
@geindex MAP_DENYWRITE (mmap モジュール)
@geindex MAP_EXECUTABLE (mmap モジュール)
@geindex MAP_HASSEMAPHORE (mmap モジュール)
@geindex MAP_JIT (mmap モジュール)
@geindex MAP_NOCACHE (mmap モジュール)
@geindex MAP_NOEXTEND (mmap モジュール)
@geindex MAP_NORESERVE (mmap モジュール)
@geindex MAP_POPULATE (mmap モジュール)
@geindex MAP_RESILIENT_CODESIGN (mmap モジュール)
@geindex MAP_RESILIENT_MEDIA (mmap モジュール)
@geindex MAP_STACK (mmap モジュール)
@geindex MAP_TPRO (mmap モジュール)
@geindex MAP_TRANSLATED_ALLOW_EXECUTE (mmap モジュール)
@geindex MAP_UNIX03 (mmap モジュール)
@anchor{library/mmap mmap MAP_SHARED}@anchor{3a82}
@deffn {データ} mmap.MAP_SHARED
@anchor{library/mmap mmap MAP_PRIVATE}@anchor{3a81}
@deffnx {データ} mmap.MAP_PRIVATE
@anchor{library/mmap mmap MAP_32BIT}@anchor{1a1c}
@deffnx {データ} mmap.MAP_32BIT
@anchor{library/mmap mmap MAP_ALIGNED_SUPER}@anchor{1ac7}
@deffnx {データ} mmap.MAP_ALIGNED_SUPER
@anchor{library/mmap mmap MAP_ANON}@anchor{3aaa}
@deffnx {データ} mmap.MAP_ANON
@anchor{library/mmap mmap MAP_ANONYMOUS}@anchor{3aab}
@deffnx {データ} mmap.MAP_ANONYMOUS
@anchor{library/mmap mmap MAP_CONCEAL}@anchor{1ac8}
@deffnx {データ} mmap.MAP_CONCEAL
@anchor{library/mmap mmap MAP_DENYWRITE}@anchor{3aac}
@deffnx {データ} mmap.MAP_DENYWRITE
@anchor{library/mmap mmap MAP_EXECUTABLE}@anchor{3aad}
@deffnx {データ} mmap.MAP_EXECUTABLE
@anchor{library/mmap mmap MAP_HASSEMAPHORE}@anchor{1a17}
@deffnx {データ} mmap.MAP_HASSEMAPHORE
@anchor{library/mmap mmap MAP_JIT}@anchor{1a19}
@deffnx {データ} mmap.MAP_JIT
@anchor{library/mmap mmap MAP_NOCACHE}@anchor{1a18}
@deffnx {データ} mmap.MAP_NOCACHE
@anchor{library/mmap mmap MAP_NOEXTEND}@anchor{1a16}
@deffnx {データ} mmap.MAP_NOEXTEND
@anchor{library/mmap mmap MAP_NORESERVE}@anchor{1a15}
@deffnx {データ} mmap.MAP_NORESERVE
@anchor{library/mmap mmap MAP_POPULATE}@anchor{1d2f}
@deffnx {データ} mmap.MAP_POPULATE
@anchor{library/mmap mmap MAP_RESILIENT_CODESIGN}@anchor{1a1a}
@deffnx {データ} mmap.MAP_RESILIENT_CODESIGN
@anchor{library/mmap mmap MAP_RESILIENT_MEDIA}@anchor{1a1b}
@deffnx {データ} mmap.MAP_RESILIENT_MEDIA
@anchor{library/mmap mmap MAP_STACK}@anchor{3aae}
@deffnx {データ} mmap.MAP_STACK
@anchor{library/mmap mmap MAP_TPRO}@anchor{1a1f}
@deffnx {データ} mmap.MAP_TPRO
@anchor{library/mmap mmap MAP_TRANSLATED_ALLOW_EXECUTE}@anchor{1a1d}
@deffnx {データ} mmap.MAP_TRANSLATED_ALLOW_EXECUTE
@anchor{library/mmap mmap MAP_UNIX03}@anchor{1a1e}
@deffnx {データ} mmap.MAP_UNIX03

These are the various flags that can be passed to @ref{519,,mmap.mmap()}.  @ref{1ac7,,MAP_ALIGNED_SUPER}
is only available at FreeBSD and @ref{1ac8,,MAP_CONCEAL} is only available at OpenBSD.  Note
that some options might not be present on some systems.


バージョン 3.10 で変更: Added @ref{1d2f,,MAP_POPULATE} constant.



Added in version 3.11: Added @ref{3aae,,MAP_STACK} constant.



Added in version 3.12: Added @ref{1ac7,,MAP_ALIGNED_SUPER} and @ref{1ac8,,MAP_CONCEAL} constants.



Added in version 3.13: Added @ref{1a1c,,MAP_32BIT}, @ref{1a17,,MAP_HASSEMAPHORE}, @ref{1a19,,MAP_JIT},
@ref{1a18,,MAP_NOCACHE}, @ref{1a16,,MAP_NOEXTEND}, @ref{1a15,,MAP_NORESERVE},
@ref{1a1a,,MAP_RESILIENT_CODESIGN}, @ref{1a1b,,MAP_RESILIENT_MEDIA},
@ref{1a1f,,MAP_TPRO}, @ref{1a1d,,MAP_TRANSLATED_ALLOW_EXECUTE}, and
@ref{1a1e,,MAP_UNIX03} constants.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node インターネット上のデータの操作,構造化マークアップツール,ネットワーク通信とプロセス間通信,Python 標準ライブラリ
@anchor{library/netdata doc}@anchor{3aaf}@anchor{library/netdata internet-data-handling}@anchor{3ab0}@anchor{library/netdata netdata}@anchor{3ab1}@anchor{library/netdata translation-repo}@anchor{3ab2}
@section インターネット上のデータの操作


この章ではインターネット上で一般的に利用されているデータ形式の操作をサポートするモジュール群について記述します。

@menu
* email: email --- 電子メールと MIME 処理のためのパッケージ. 電子メールと MIME 処理のためのパッケージ
* json: json --- JSON エンコーダーとデコーダー. JSON エンコーダーとデコーダー
* mailbox: mailbox --- 様々な形式のメールボックスを操作する. 様々な形式のメールボックスを操作する
* mimetypes: mimetypes --- ファイル名を MIME タイプへマップする. ファイル名を MIME タイプへマップする
* base64: base64 --- Base16 Base32 Base64 Base85 データのエンコード. Base16, Base32, Base64, Base85 データのエンコード
* binascii: binascii --- バイナリ と ASCII 間の変換. バイナリ と ASCII 間の変換
* quopri: quopri --- MIME quoted-printable データのエンコードとデコード. MIME quoted-printable データのエンコードとデコード

@end menu

@node email --- 電子メールと MIME 処理のためのパッケージ,json --- JSON エンコーダーとデコーダー,,インターネット上のデータの操作
@anchor{library/email doc}@anchor{3ab3}@anchor{library/email email-an-email-and-mime-handling-package}@anchor{3ab4}@anchor{library/email module-email}@anchor{3f}
@subsection @code{email} --- 電子メールと MIME 処理のためのパッケージ


@geindex module; email

`ソースコード:' Lib/email/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/__init__.py}


__________________________________________________________________


The @code{email} package is a library for managing email messages.  It is
specifically `not' designed to do any sending of email messages to SMTP
(
@geindex RFC; RFC 2821
RFC 2821@footnote{https://datatracker.ietf.org/doc/html/rfc2821.html}), NNTP, or other servers; those are functions of modules such as
@ref{cf,,smtplib}.  The @code{email} package attempts to be as
RFC-compliant as possible, supporting 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} and 
@geindex RFC; RFC 6532
RFC 6532@footnote{https://datatracker.ietf.org/doc/html/rfc6532.html}, as well as
such MIME-related RFCs as 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html}, 
@geindex RFC; RFC 2046
RFC 2046@footnote{https://datatracker.ietf.org/doc/html/rfc2046.html}, 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html}, 
@geindex RFC; RFC 2183
RFC 2183@footnote{https://datatracker.ietf.org/doc/html/rfc2183.html},
and 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html}.

The overall structure of the email package can be divided into three major
components, plus a fourth component that controls the behavior of the other
components.

The central component of the package is an "object model" that represents email
messages.  An application interacts with the package primarily through the
object model interface defined in the @ref{48,,message} sub-module.  The
application can use this API to ask questions about an existing email, to
construct a new email, or to add or remove email subcomponents that themselves
use the same object model interface.  That is, following the nature of email
messages and their MIME subcomponents, the email object model is a tree
structure of objects that all provide the @ref{580,,EmailMessage}
API.

The other two major components of the package are the @ref{52,,parser} and
the @ref{44,,generator}.  The parser takes the serialized version of an
email message (a stream of bytes) and converts it into a tree of
@ref{580,,EmailMessage} objects.  The generator takes an
@ref{580,,EmailMessage} and turns it back into a serialized byte
stream.  (The parser and generator also handle streams of text characters, but
this usage is discouraged as it is too easy to end up with messages that are
not valid in one way or another.)

The control component is the @ref{53,,policy} module.  Every
@ref{580,,EmailMessage}, every @ref{44,,generator}, and every
@ref{52,,parser} has an associated @ref{53,,policy} object that
controls its behavior.  Usually an application only needs to specify the policy
when an @ref{580,,EmailMessage} is created, either by directly
instantiating an @ref{580,,EmailMessage}  to create a new email,
or by parsing an input stream using a @ref{52,,parser}.  But the policy can
be changed when the message is serialized using a @ref{44,,generator}.
This allows, for example, a generic email message to be parsed from disk, but
to serialize it using standard SMTP settings when sending it to an email
server.

The email package does its best to hide the details of the various governing
RFCs from the application.  Conceptually the application should be able to
treat the email message as a structured tree of unicode text and binary
attachments, without having to worry about how these are represented when
serialized.  In practice, however, it is often necessary to be aware of at
least some of the rules governing MIME messages and their structure,
specifically the names and nature of the MIME "content types" and how they
identify multipart documents.  For the most part this knowledge should only be
required for more complex applications, and even then it should only be the
high level structure in question, and not the details of how those structures
are represented.  Since MIME content types are used widely in modern internet
software (not just email), this will be a familiar concept to many programmers.

The following sections describe the functionality of the @code{email} package.
We start with the @ref{48,,message} object model, which is the primary
interface an application will use, and follow that with the
@ref{52,,parser} and @ref{44,,generator} components.  Then we cover the
@ref{53,,policy} controls, which completes the treatment of the main
components of the library.

The next three sections cover the exceptions the package may raise and the
defects (non-compliance with the RFCs) that the @ref{52,,parser} may
detect.  Then we cover the @ref{46,,headerregistry} and the
@ref{41,,contentmanager} sub-components, which provide tools for doing more
detailed manipulation of headers and payloads, respectively.  Both of these
components contain features relevant to consuming and producing non-trivial
messages, but also document their extensibility APIs, which will be of interest
to advanced applications.

Following those is a set of examples of using the fundamental parts of the APIs
covered in the preceding sections.

The foregoing represent the modern (unicode friendly) API of the email package.
The remaining sections, starting with the @ref{581,,Message}
class, cover the legacy @ref{e97,,compat32} API that deals much more
directly with the details of how email messages are represented.  The
@ref{e97,,compat32} API does `not' hide the details of the RFCs from
the application, but for applications that need to operate at that level, they
can be useful tools.  This documentation is also relevant for applications that
are still using the @ref{e97,,compat32} API for backward
compatibility reasons.


バージョン 3.6 で変更: Docs reorganized and rewritten to promote the new
@ref{580,,EmailMessage}/@ref{12cb,,EmailPolicy}
API.


Contents of the @code{email} package documentation:

@menu
* email.message; Representing an email message: email message Representing an email message. 
* email.parser; Parsing email messages: email parser Parsing email messages. 
* email.generator; Generating MIME documents: email generator Generating MIME documents. 
* email.policy; Policy Objects: email policy Policy Objects. 
* email.errors; Exception and Defect classes: email errors Exception and Defect classes. 
* email.headerregistry; Custom Header Objects: email headerregistry Custom Header Objects. 
* email.contentmanager; Managing MIME Content: email contentmanager Managing MIME Content. 
* email; 使用例: email 使用例. 
* email.message.Message; compat32 API を使用した電子メールメッセージの表現: email message Message compat32 API を使用した電子メールメッセージの表現. 
* email.mime; Creating email and MIME objects from scratch: email mime Creating email and MIME objects from scratch. 
* email.header; 国際化されたヘッダー: email header 国際化されたヘッダー. 
* email.charset; 文字集合の表現: email charset 文字集合の表現. 
* email.encoders; エンコーダー: email encoders エンコーダー. 
* email.utils; Miscellaneous utilities: email utils Miscellaneous utilities. 
* email.iterators; イテレータ: email iterators イテレータ. 

@end menu

@node email message Representing an email message,email parser Parsing email messages,,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email message doc}@anchor{3ab5}@anchor{library/email message email-message-representing-an-email-message}@anchor{3ab6}@anchor{library/email message module-email message}@anchor{48}
@subsubsection @code{email.message}: Representing an email message


@geindex module; email.message

`ソースコード:' Lib/email/message.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/message.py}


__________________________________________________________________



Added in version 3.6: @footnote{
Originally added in 3.4 as a @ref{1243,,provisional module}.  Docs for legacy message class moved to
@ref{3ab7,,email.message.Message; compat32 API を使用した電子メールメッセージの表現}.
}


The central class in the @ref{3f,,email} package is the @ref{580,,EmailMessage}
class, imported from the @code{email.message} module.  It is the base class for
the @ref{3f,,email} object model.  @ref{580,,EmailMessage} provides the core
functionality for setting and querying header fields, for accessing message
bodies, and for creating or modifying structured messages.

An email message consists of `headers' and a `payload' (which is also referred
to as the `content').  Headers are 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} or 
@geindex RFC; RFC 6532
RFC 6532@footnote{https://datatracker.ietf.org/doc/html/rfc6532.html} style field names
and values, where the field name and value are separated by a colon.  The colon
is not part of either the field name or the field value.  The payload may be a
simple text message, or a binary object, or a structured sequence of
sub-messages each with their own set of headers and their own payload.  The
latter type of payload is indicated by the message having a MIME type such as
@code{multipart/*} or @code{message/rfc822}.

The conceptual model provided by an @ref{580,,EmailMessage} object is that of an
ordered dictionary of headers coupled with a `payload' that represents the
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} body of the message, which might be a list of sub-@code{EmailMessage}
objects.  In addition to the normal dictionary methods for accessing the header
names and values, there are methods for accessing specialized information from
the headers (for example the MIME content type), for operating on the payload,
for generating a serialized version of the message, and for recursively walking
over the object tree.

The @ref{580,,EmailMessage} dictionary-like interface is indexed by the header
names, which must be ASCII values.  The values of the dictionary are strings
with some extra methods.  Headers are stored and returned in case-preserving
form, but field names are matched case-insensitively.  The keys are ordered,
but unlike a real dict, there can be duplicates.  Additional methods are
provided for working with headers that have duplicate keys.

The `payload' is either a string or bytes object, in the case of simple message
objects, or a list of @ref{580,,EmailMessage} objects, for MIME container
documents such as @code{multipart/*} and @code{message/rfc822}
message objects.

@geindex EmailMessage (email.message のクラス)
@anchor{library/email message email message EmailMessage}@anchor{580}
@deffn {クラス} email.message.EmailMessage (policy=default)

If `policy' is specified use the rules it specifies to update and serialize
the representation of the message.  If `policy' is not set, use the
@ref{12cc,,default} policy, which follows the rules of the email
RFCs except for line endings (instead of the RFC mandated @code{\r\n}, it uses
the Python standard @code{\n} line endings).  For more information see the
@ref{53,,policy} documentation. @footnote{
The @ref{580,,EmailMessage} class requires a policy that provides a
@code{content_manager} attribute for content management methods like
@code{set_content()} and @code{get_content()} to work. The legacy
@ref{e97,,compat32} policy does not support these methods
and should not be used with @ref{580,,EmailMessage}.
}

@geindex as_string() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage as_string}@anchor{3ab8}
@deffn {メソッド} as_string (unixfrom=False, maxheaderlen=None, policy=None)

Return the entire message flattened as a string.  When optional
`unixfrom' is true, the envelope header is included in the returned
string.  `unixfrom' defaults to @code{False}.  For backward compatibility
with the base @ref{581,,Message} class `maxheaderlen' is
accepted, but defaults to @code{None}, which means that by default the line
length is controlled by the
@ref{3ab9,,max_line_length} of the policy.  The
`policy' argument may be used to override the default policy obtained
from the message instance.  This can be used to control some of the
formatting produced by the method, since the specified `policy' will be
passed to the @ref{13e6,,Generator}.

もし、文字列への変換を完全に行うためにデフォルト値を埋める必要がある場合、メッセージのフラット化は @ref{580,,EmailMessage} の変更を引き起こす可能性があります (例えば、MIME の境界が生成される、変更される等)。

Note that this method is provided as a convenience and may not be the
most useful way to serialize messages in your application, especially if
you are dealing with multiple messages.  See
@ref{13e6,,email.generator.Generator} for a more flexible API for
serializing messages.  Note also that this method is restricted to
producing messages serialized as "7 bit clean" when
@ref{ff9,,utf8} is @code{False}, which is the default.


バージョン 3.6 で変更: the default behavior when `maxheaderlen'
is not specified was changed from defaulting to 0 to defaulting
to the value of `max_line_length' from the policy.

@end deffn

@geindex __str__() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage __str__}@anchor{3aba}
@deffn {メソッド} __str__ ()

Equivalent to @code{as_string(policy=self.policy.clone(utf8=True))}.  Allows
@code{str(msg)} to produce a string containing the serialized message in a
readable format.


バージョン 3.4 で変更: the method was changed to use @code{utf8=True},
thus producing an 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://datatracker.ietf.org/doc/html/rfc6531.html}-like message representation, instead of
being a direct alias for @ref{3ab8,,as_string()}.

@end deffn

@geindex as_bytes() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage as_bytes}@anchor{3abb}
@deffn {メソッド} as_bytes (unixfrom=False, policy=None)

Return the entire message flattened as a bytes object.  When optional
`unixfrom' is true, the envelope header is included in the returned
string.  `unixfrom' defaults to @code{False}.  The `policy' argument may be
used to override the default policy obtained from the message instance.
This can be used to control some of the formatting produced by the
method, since the specified `policy' will be passed to the
@ref{13e7,,BytesGenerator}.

もし、文字列への変換を完全に行うためにデフォルト値を埋める必要がある場合、メッセージのフラット化は @ref{580,,EmailMessage} の変更を引き起こす可能性があります (例えば、MIME の境界が生成される、変更される等)。

Note that this method is provided as a convenience and may not be the
most useful way to serialize messages in your application, especially if
you are dealing with multiple messages.  See
@ref{13e7,,email.generator.BytesGenerator} for a more flexible API for
serializing messages.
@end deffn

@geindex __bytes__() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage __bytes__}@anchor{3abc}
@deffn {メソッド} __bytes__ ()

Equivalent to @ref{3abb,,as_bytes()}.  Allows @code{bytes(msg)} to produce a
bytes object containing the serialized message.
@end deffn

@geindex is_multipart() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage is_multipart}@anchor{3abd}
@deffn {メソッド} is_multipart ()

Return @code{True} if the message's payload is a list of
sub-@ref{580,,EmailMessage} objects, otherwise return @code{False}.  When
@ref{3abd,,is_multipart()} returns @code{False}, the payload should be a string
object (which might be a CTE encoded binary payload).  Note that
@ref{3abd,,is_multipart()} returning @code{True} does not necessarily mean that
"msg.get_content_maintype() == 'multipart'" will return the @code{True}.
For example, @code{is_multipart} will return @code{True} when the
@ref{580,,EmailMessage} is of type @code{message/rfc822}.
@end deffn

@geindex set_unixfrom() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage set_unixfrom}@anchor{3abe}
@deffn {メソッド} set_unixfrom (unixfrom)

Set the message's envelope header to `unixfrom', which should be a
string.  (See @ref{3abf,,mboxMessage} for a brief description of
this header.)
@end deffn

@geindex get_unixfrom() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_unixfrom}@anchor{3ac0}
@deffn {メソッド} get_unixfrom ()

メッセージのエンベロープヘッダを返します。エンベロープヘッダが設定されていない場合は @code{None} が返されます。
@end deffn

The following methods implement the mapping-like interface for accessing the
message's headers.  Note that there are some semantic differences
between these methods and a normal mapping (i.e. dictionary) interface.  For
example, in a dictionary there are no duplicate keys, but here there may be
duplicate message headers.  Also, in dictionaries there is no guaranteed
order to the keys returned by @ref{3ac1,,keys()}, but in an @ref{580,,EmailMessage}
object, headers are always returned in the order they appeared in the
original message, or in which they were added to the message later.  Any
header deleted and then re-added is always appended to the end of the
header list.

These semantic differences are intentional and are biased toward
convenience in the most common use cases.

注意: どんな場合も、メッセージ中のエンベロープヘッダはこのマップ形式のインタフェイスには含まれません。

@geindex __len__() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage __len__}@anchor{3ac2}
@deffn {メソッド} __len__ ()

複製されたものもふくめてヘッダ数の合計を返します。
@end deffn

@geindex __contains__() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage __contains__}@anchor{3ac3}
@deffn {メソッド} __contains__ (name)

Return @code{True} if the message object has a field named `name'. Matching is
done without regard to case and `name' does not include the trailing
colon.  Used for the @code{in} operator.  For example:

@example
if 'message-id' in myMessage:
   print('Message-ID:', myMessage['message-id'])
@end example
@end deffn

@geindex __getitem__() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage __getitem__}@anchor{3ac4}
@deffn {メソッド} __getitem__ (name)

Return the value of the named header field.  `name' does not include the
colon field separator.  If the header is missing, @code{None} is returned; a
@ref{5e7,,KeyError} is never raised.

Note that if the named field appears more than once in the message's
headers, exactly which of those field values will be returned is
undefined.  Use the @ref{3ac5,,get_all()} method to get the values of all the
extant headers named `name'.

Using the standard (non-@code{compat32}) policies, the returned value is an
instance of a subclass of @ref{3ac6,,email.headerregistry.BaseHeader}.
@end deffn

@geindex __setitem__() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage __setitem__}@anchor{3ac7}
@deffn {メソッド} __setitem__ (name, val)

メッセージヘッダに `name' という名前の `val' という値をもつフィールドをあらたに追加します。このフィールドは現在メッセージに存在するヘッダーのいちばん後に追加されます。

注意: このメソッドでは、すでに同一の名前で存在するフィールドは上書き `されません'。もしメッセージが名前 `name' をもつフィールドをひとつしか持たないようにしたければ、最初にそれを除去してください。たとえば:

@example
del msg['subject']
msg['subject'] = 'Python roolz!'
@end example

If the @ref{53,,policy} defines certain headers to be unique (as the standard
policies do), this method may raise a @ref{2ec,,ValueError} when an attempt
is made to assign a value to such a header when one already exists.  This
behavior is intentional for consistency's sake, but do not depend on it
as we may choose to make such assignments do an automatic deletion of the
existing header in the future.
@end deffn

@geindex __delitem__() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage __delitem__}@anchor{3ac8}
@deffn {メソッド} __delitem__ (name)

メッセージのヘッダから、`name' という名前をもつフィールドをすべて除去します。たとえこの名前をもつヘッダが存在していなくても例外は発生しません。
@end deffn

@geindex keys() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage keys}@anchor{3ac1}
@deffn {メソッド} keys ()

メッセージ中にあるすべてのヘッダのフィールド名のリストを返します。
@end deffn

@geindex values() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage values}@anchor{3ac9}
@deffn {メソッド} values ()

メッセージ中にあるすべてのフィールドの値のリストを返します。
@end deffn

@geindex items() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage items}@anchor{3aca}
@deffn {メソッド} items ()

メッセージ中にあるすべてのヘッダのフィールド名とその値を 2-タプルのリストとして返します。
@end deffn

@geindex get() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get}@anchor{3acb}
@deffn {メソッド} get (name, failobj=None)

Return the value of the named header field.  This is identical to
@ref{588,,__getitem__()} except that optional `failobj' is returned if the
named header is missing (`failobj' defaults to @code{None}).
@end deffn

Here are some additional useful header related methods:

@geindex get_all() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_all}@anchor{3ac5}
@deffn {メソッド} get_all (name, failobj=None)

`name' の名前をもつフィールドのすべての値からなるリストを返します。該当する名前のヘッダがメッセージ中に含まれていない場合は `failobj' (デフォルトでは @code{None}) が返されます。
@end deffn

@geindex add_header() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage add_header}@anchor{3acc}
@deffn {メソッド} add_header (_name, _value, **_params)

拡張ヘッダ設定。このメソッドは @ref{3ac7,,__setitem__()} と似ていますが、追加のヘッダ・パラメータをキーワード引数で指定できるところが違っています。 `_name' に追加するヘッダフィールドを、 `_value' にそのヘッダの `最初の' 値を渡します。

For each item in the keyword argument dictionary `_params', the key is
taken as the parameter name, with underscores converted to dashes (since
dashes are illegal in Python identifiers).  Normally, the parameter will
be added as @code{key="value"} unless the value is @code{None}, in which case
only the key will be added.

If the value contains non-ASCII characters, the charset and language may
be explicitly controlled by specifying the value as a three tuple in the
format @code{(CHARSET, LANGUAGE, VALUE)}, where @code{CHARSET} is a string
naming the charset to be used to encode the value, @code{LANGUAGE} can
usually be set to @code{None} or the empty string (see 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} for other
possibilities), and @code{VALUE} is the string value containing non-ASCII
code points.  If a three tuple is not passed and the value contains
non-ASCII characters, it is automatically encoded in 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} format
using a @code{CHARSET} of @code{utf-8} and a @code{LANGUAGE} of @code{None}.

以下に例を示します。:

@example
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
@end example

こうするとヘッダには以下のように追加されます

@example
Content-Disposition: attachment; filename="bud.gif"
@end example

An example of the extended interface with non-ASCII characters:

@example
msg.add_header('Content-Disposition', 'attachment',
               filename=('iso-8859-1', '@w{'}, 'Fußballer.ppt'))
@end example
@end deffn

@geindex replace_header() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage replace_header}@anchor{3acd}
@deffn {メソッド} replace_header (_name, _value)

Replace a header.  Replace the first header found in the message that
matches `_name', retaining header order and field name case of the
original header.  If no matching header is found, raise a
@ref{5e7,,KeyError}.
@end deffn

@geindex get_content_type() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_content_type}@anchor{3ace}
@deffn {メソッド} get_content_type ()

Return the message's content type, coerced to lower case of the form
@code{maintype/subtype}.  If there is no @code{Content-Type}
header in the message return the value returned by
@ref{3acf,,get_default_type()}.  If the @code{Content-Type} header is
invalid, return @code{text/plain}.

(According to 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html}, messages always have a default type,
@ref{3ace,,get_content_type()} will always return a value.  
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} defines
a message's default type to be @code{text/plain} unless it appears
inside a @code{multipart/digest} container, in which case it would
be @code{message/rfc822}.  If the @code{Content-Type} header
has an invalid type specification, 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} mandates that the default
type be @code{text/plain}.)
@end deffn

@geindex get_content_maintype() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_content_maintype}@anchor{3ad0}
@deffn {メソッド} get_content_maintype ()

そのメッセージの主 content-type を返します。これは @ref{3ace,,get_content_type()} によって返される文字列の @code{maintype} 部分です。
@end deffn

@geindex get_content_subtype() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_content_subtype}@anchor{3ad1}
@deffn {メソッド} get_content_subtype ()

そのメッセージの副 content-type (sub content-type、subtype) を返します。これは @ref{3ace,,get_content_type()} によって返される文字列の @code{subtype} 部分です。
@end deffn

@geindex get_default_type() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_default_type}@anchor{3acf}
@deffn {メソッド} get_default_type ()

デフォルトの content-type を返します。ほどんどのメッセージではデフォルトの content-type は @code{text/plain} ですが、メッセージが @code{multipart/digest} コンテナに含まれているときだけ例外的に @code{message/rfc822} になります。
@end deffn

@geindex set_default_type() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage set_default_type}@anchor{3ad2}
@deffn {メソッド} set_default_type (ctype)

Set the default content type.  `ctype' should either be
@code{text/plain} or @code{message/rfc822}, although this is
not enforced.  The default content type is not stored in the
@code{Content-Type} header, so it only affects the return value of
the @code{get_content_type} methods when no @code{Content-Type}
header is present in the message.
@end deffn

@geindex set_param() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage set_param}@anchor{3ad3}
@deffn {メソッド} set_param (param, value, header='Content-Type', requote=True, charset=None, language='@w{'}, replace=False)

Set a parameter in the @code{Content-Type} header.  If the
parameter already exists in the header, replace its value with `value'.
When `header' is @code{Content-Type} (the default) and the header does not
yet exist in the message, add it, set its value to
@code{text/plain}, and append the new parameter value.  Optional
`header' specifies an alternative header to @code{Content-Type}.

If the value contains non-ASCII characters, the charset and language may
be explicitly specified using the optional `charset' and `language'
parameters.  Optional `language' specifies the 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} language,
defaulting to the empty string.  Both `charset' and `language' should be
strings.  The default is to use the @code{utf8} `charset' and @code{None} for
the `language'.

If `replace' is @code{False} (the default) the header is moved to the
end of the list of headers.  If `replace' is @code{True}, the header
will be updated in place.

Use of the `requote' parameter with @ref{580,,EmailMessage} objects is
deprecated.

Note that existing parameter values of headers may be accessed through
the @ref{3ad4,,params} attribute of the
header value (for example, @code{msg['Content-Type'].params['charset']}).


バージョン 3.4 で変更: @code{replace} キーワードが追加されました。

@end deffn

@geindex del_param() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage del_param}@anchor{3ad5}
@deffn {メソッド} del_param (param, header='content-type', requote=True)

指定されたパラメータを @code{Content-Type} ヘッダ中から完全にとりのぞきます。ヘッダはそのパラメータと値がない状態に書き換えられます。オプション変数 `header' が与えられた場合、 @code{Content-Type} のかわりにそのヘッダが使用されます。

Use of the `requote' parameter with @ref{580,,EmailMessage} objects is
deprecated.
@end deffn

@geindex get_filename() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_filename}@anchor{3ad6}
@deffn {メソッド} get_filename (failobj=None)

そのメッセージ中の @code{Content-Disposition} ヘッダにある、 @code{filename} パラメータの値を返します。目的のヘッダに @code{filename} パラメータがない場合には @code{Content-Type} ヘッダにある @code{name} パラメータを探します。それも無い場合またはヘッダが無い場合には `failobj' が返されます。返される文字列はつねに @ref{3ad7,,email.utils.unquote()} によって unquote されます。
@end deffn

@geindex get_boundary() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_boundary}@anchor{3ad8}
@deffn {メソッド} get_boundary (failobj=None)

そのメッセージ中の @code{Content-Type} ヘッダにある、 @code{boundary} パラメータの値を返します。目的のヘッダが欠けていたり、 @code{boundary} パラメータがない場合には `failobj' が返されます。返される文字列はつねに @ref{3ad7,,email.utils.unquote()} によって unquote されます。
@end deffn

@geindex set_boundary() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage set_boundary}@anchor{3ad9}
@deffn {メソッド} set_boundary (boundary)

メッセージ中の @code{Content-Type} ヘッダにある、 @code{boundary} パラメータに値を設定します。 @ref{3ad9,,set_boundary()} は必要に応じて `boundary' を quote します。そのメッセージが @code{Content-Type} ヘッダを含んでいない場合、 @ref{3ada,,HeaderParseError} が発生します。

Note that using this method is subtly different from deleting the old
@code{Content-Type} header and adding a new one with the new
boundary via @ref{3acc,,add_header()}, because @ref{3ad9,,set_boundary()} preserves
the order of the @code{Content-Type} header in the list of
headers.
@end deffn

@geindex get_content_charset() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_content_charset}@anchor{3adb}
@deffn {メソッド} get_content_charset (failobj=None)

そのメッセージ中の @code{Content-Type} ヘッダにある、 @code{charset} パラメータの値を返します。値はすべて小文字に変換されます。メッセージ中に @code{Content-Type} がなかったり、このヘッダ中に @code{charaset} パラメータがない場合には `failobj' が返されます。
@end deffn

@geindex get_charsets() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_charsets}@anchor{3adc}
@deffn {メソッド} get_charsets (failobj=None)

メッセージ中に含まれる文字セットの名前をすべてリストにして返します。そのメッセージが @code{multipart} である場合、返されるリストの各要素がそれぞれの subpart のペイロードに対応します。それ以外の場合、これは長さ 1 のリストを返します。

リスト中の各要素は文字列であり、これは対応する subpart 中のそれぞれの @code{Content-Type} ヘッダにある @code{charset} の値です。その subpart が @code{Content-Type} をもってないか、 @code{charset} がないか、あるいは MIME maintype が @code{text} でないいずれかの場合には、リストの要素として `failobj' が返されます。
@end deffn

@geindex is_attachment() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage is_attachment}@anchor{3add}
@deffn {メソッド} is_attachment ()

@code{Content-Disposition} ヘッダが存在し、その (大文字小文字を区別しない) 値が @code{attachment} の場合、 @code{True} を返します。 それ以外の場合は @code{False} を返します。


バージョン 3.4.2 で変更: @ref{3ade,,is_multipart()} との一貫性のために、is_attachment が属性からメソッドになりました。

@end deffn

@geindex get_content_disposition() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_content_disposition}@anchor{3adf}
@deffn {メソッド} get_content_disposition ()

Return the lowercased value (without parameters) of the message's
@code{Content-Disposition} header if it has one, or @code{None}.  The
possible values for this method are `inline', `attachment' or @code{None}
if the message follows 
@geindex RFC; RFC 2183
RFC 2183@footnote{https://datatracker.ietf.org/doc/html/rfc2183.html}.


Added in version 3.5.

@end deffn

The following methods relate to interrogating and manipulating the content
(payload) of the message.

@geindex walk() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage walk}@anchor{3ae0}
@deffn {メソッド} walk ()

@ref{3ae0,,walk()} メソッドは多目的のジェネレータで、これはあるメッセージオブジェクトツリー中のすべての part および subpart をわたり歩くのに使えます。順序は深さ優先です。おそらく典型的な用法は、 @ref{3ae0,,walk()} を @code{for} ループ中でのイテレータとして使うことでしょう。ループを一回まわるごとに、次の subpart が返されるのです。

以下の例は、 multipart メッセージのすべての part において、その MIME タイプを表示していくものです。 :

@c from email import message_from_binary_file
@c with open('../Lib/test/test_email/data/msg_16.txt', 'rb') as f:
@c     msg = message_from_binary_file(f)

@example
>>> for part in msg.walk():
...     print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain
@end example

@code{walk} iterates over the subparts of any part where
@ref{3abd,,is_multipart()} returns @code{True}, even though
@code{msg.get_content_maintype() == 'multipart'} may return @code{False}.  We
can see this in our example by making use of the @code{_structure} debug
helper function:

@example
>>> from email.iterators import _structure
>>> for part in msg.walk():
...     print(part.get_content_maintype() == 'multipart',
...           part.is_multipart())
True True
False False
False True
False False
False False
False True
False False
>>> _structure(msg)
multipart/report
    text/plain
    message/delivery-status
        text/plain
        text/plain
    message/rfc822
        text/plain
@end example

Here the @code{message} parts are not @code{multiparts}, but they do contain
subparts. @code{is_multipart()} returns @code{True} and @code{walk} descends
into the subparts.
@end deffn

@geindex get_body() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_body}@anchor{3ae1}
@deffn {メソッド} get_body (preferencelist=('related', 'html', 'plain'))

メッセージの "本体" の最有力候補となる MIME 部を返します。

`preferencelist' must be a sequence of strings from the set @code{related},
@code{html}, and @code{plain}, and indicates the order of preference for the
content type of the part returned.

Start looking for candidate matches with the object on which the
@code{get_body} method is called.

If @code{related} is not included in `preferencelist', consider the root
part (or subpart of the root part) of any related encountered as a
candidate if the (sub-)part matches a preference.

When encountering a @code{multipart/related}, check the @code{start} parameter
and if a part with a matching @code{Content-ID} is found, consider
only it when looking for candidate matches.  Otherwise consider only the
first (default root) part of the @code{multipart/related}.

If a part has a @code{Content-Disposition} header, only consider
the part a candidate match if the value of the header is @code{inline}.

If none of the candidates matches any of the preferences in
`preferencelist', return @code{None}.

Notes: (1) For most applications the only `preferencelist' combinations
that really make sense are @code{('plain',)}, @code{('html', 'plain')}, and the
default @code{('related', 'html', 'plain')}.  (2) Because matching starts
with the object on which @code{get_body} is called, calling @code{get_body} on
a @code{multipart/related} will return the object itself unless
`preferencelist' has a non-default value. (3) Messages (or message parts)
that do not specify a @code{Content-Type} or whose
@code{Content-Type} header is invalid will be treated as if they
are of type @code{text/plain}, which may occasionally cause @code{get_body} to
return unexpected results.
@end deffn

@geindex iter_attachments() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage iter_attachments}@anchor{3ae2}
@deffn {メソッド} iter_attachments ()

Return an iterator over all of the immediate sub-parts of the message
that are not candidate "body" parts.  That is, skip the first occurrence
of each of @code{text/plain}, @code{text/html}, @code{multipart/related}, or
@code{multipart/alternative} (unless they are explicitly marked as
attachments via @code{Content-Disposition: attachment}), and
return all remaining parts.  When applied directly to a
@code{multipart/related}, return an iterator over the all the related parts
except the root part (ie: the part pointed to by the @code{start} parameter,
or the first part if there is no @code{start} parameter or the @code{start}
parameter doesn't match the @code{Content-ID} of any of the
parts).  When applied directly to a @code{multipart/alternative} or a
non-@code{multipart}, return an empty iterator.
@end deffn

@geindex iter_parts() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage iter_parts}@anchor{3ae3}
@deffn {メソッド} iter_parts ()

Return an iterator over all of the immediate sub-parts of the message,
which will be empty for a non-@code{multipart}.  (See also
@ref{3ae0,,walk()}.)
@end deffn

@geindex get_content() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage get_content}@anchor{3ae4}
@deffn {メソッド} get_content (*args, content_manager=None, **kw)

Call the @ref{3ae5,,get_content()} method
of the `content_manager', passing self as the message object, and passing
along any other arguments or keywords as additional arguments.  If
`content_manager' is not specified, use the @code{content_manager} specified
by the current @ref{53,,policy}.
@end deffn

@geindex set_content() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage set_content}@anchor{1c5d}
@deffn {メソッド} set_content (*args, content_manager=None, **kw)

Call the @ref{3ae6,,set_content()} method
of the `content_manager', passing self as the message object, and passing
along any other arguments or keywords as additional arguments.  If
`content_manager' is not specified, use the @code{content_manager} specified
by the current @ref{53,,policy}.
@end deffn

@geindex make_related() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage make_related}@anchor{3ae7}
@deffn {メソッド} make_related (boundary=None)

Convert a non-@code{multipart} message into a @code{multipart/related} message,
moving any existing @code{Content-} headers and payload into a
(new) first part of the @code{multipart}.  If `boundary' is specified, use
it as the boundary string in the multipart, otherwise leave the boundary
to be automatically created when it is needed (for example, when the
message is serialized).
@end deffn

@geindex make_alternative() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage make_alternative}@anchor{3ae8}
@deffn {メソッド} make_alternative (boundary=None)

Convert a non-@code{multipart} or a @code{multipart/related} into a
@code{multipart/alternative}, moving any existing @code{Content-}
headers and payload into a (new) first part of the @code{multipart}.  If
`boundary' is specified, use it as the boundary string in the multipart,
otherwise leave the boundary to be automatically created when it is
needed (for example, when the message is serialized).
@end deffn

@geindex make_mixed() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage make_mixed}@anchor{3ae9}
@deffn {メソッド} make_mixed (boundary=None)

Convert a non-@code{multipart}, a @code{multipart/related}, or a
@code{multipart-alternative} into a @code{multipart/mixed}, moving any existing
@code{Content-} headers and payload into a (new) first part of the
@code{multipart}.  If `boundary' is specified, use it as the boundary string
in the multipart, otherwise leave the boundary to be automatically
created when it is needed (for example, when the message is serialized).
@end deffn

@geindex add_related() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage add_related}@anchor{3aea}
@deffn {メソッド} add_related (*args, content_manager=None, **kw)

If the message is a @code{multipart/related}, create a new message
object, pass all of the arguments to its @ref{1c5d,,set_content()} method,
and @ref{3aeb,,attach()} it to the @code{multipart}.  If
the message is a non-@code{multipart}, call @ref{3ae7,,make_related()} and then
proceed as above.  If the message is any other type of @code{multipart},
raise a @ref{198,,TypeError}. If `content_manager' is not specified, use
the @code{content_manager} specified by the current @ref{53,,policy}.
If the added part has no @code{Content-Disposition} header,
add one with the value @code{inline}.
@end deffn

@geindex add_alternative() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage add_alternative}@anchor{3aec}
@deffn {メソッド} add_alternative (*args, content_manager=None, **kw)

If the message is a @code{multipart/alternative}, create a new message
object, pass all of the arguments to its @ref{1c5d,,set_content()} method, and
@ref{3aeb,,attach()} it to the @code{multipart}.  If the
message is a non-@code{multipart} or @code{multipart/related}, call
@ref{3ae8,,make_alternative()} and then proceed as above.  If the message is
any other type of @code{multipart}, raise a @ref{198,,TypeError}. If
`content_manager' is not specified, use the @code{content_manager} specified
by the current @ref{53,,policy}.
@end deffn

@geindex add_attachment() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage add_attachment}@anchor{3aed}
@deffn {メソッド} add_attachment (*args, content_manager=None, **kw)

If the message is a @code{multipart/mixed}, create a new message object,
pass all of the arguments to its @ref{1c5d,,set_content()} method, and
@ref{3aeb,,attach()} it to the @code{multipart}.  If the
message is a non-@code{multipart}, @code{multipart/related}, or
@code{multipart/alternative}, call @ref{3ae9,,make_mixed()} and then proceed as
above. If `content_manager' is not specified, use the @code{content_manager}
specified by the current @ref{53,,policy}.  If the added part
has no @code{Content-Disposition} header, add one with the value
@code{attachment}.  This method can be used both for explicit attachments
(@code{Content-Disposition: attachment}) and @code{inline} attachments
(@code{Content-Disposition: inline}), by passing appropriate
options to the @code{content_manager}.
@end deffn

@geindex clear() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage clear}@anchor{3aee}
@deffn {メソッド} clear ()

ペイロードとヘッダの全てを削除します。
@end deffn

@geindex clear_content() (email.message.EmailMessage のメソッド)
@anchor{library/email message email message EmailMessage clear_content}@anchor{3aef}
@deffn {メソッド} clear_content ()

Remove the payload and all of the @code{!Content-} headers, leaving
all other headers intact and in their original order.
@end deffn

@ref{580,,EmailMessage} オブジェクトは次のようなインスタンス属性を持ちます:

@geindex preamble (email.message.EmailMessage の属性)
@anchor{library/email message email message EmailMessage preamble}@anchor{3af0}
@deffn {の属性} preamble

MIME ドキュメントの形式では、ヘッダ直後にくる空行と最初の multipart 境界をあらわす文字列のあいだにいくらかのテキスト (訳注: preamble, 序文) を埋めこむことを許しています。このテキストは標準的な MIME の範疇からはみ出しているので、MIME 形式を認識するメールソフトからこれらは通常まったく見えません。しかしメッセージのテキストを生で見る場合、あるいはメッセージを MIME 対応していないメールソフトで見る場合、このテキストは目に見えることになります。

`preamble' 属性は MIME ドキュメントに加えるこの最初の MIME 範囲外テキストを含んでいます。 @ref{13b5,,Parser} があるテキストをヘッダ以降に発見したが、それはまだ最初の MIME 境界文字列が現れる前だった場合、パーザはそのテキストをメッセージの `preamble' 属性に格納します。 @ref{13e6,,Generator} がある MIME メッセージからプレーンテキスト形式を生成するときメッセージが `preamble' 属性を持つことが発見されれば、これはそのテキストをヘッダと最初の MIME 境界の間に挿入します。詳細は @ref{52,,email.parser} および @ref{44,,email.generator} を参照してください。

注意: そのメッセージに preamble がない場合、`preamble' 属性には @code{None} が格納されます。
@end deffn

@geindex epilogue (email.message.EmailMessage の属性)
@anchor{library/email message email message EmailMessage epilogue}@anchor{3af1}
@deffn {の属性} epilogue

The `epilogue' attribute acts the same way as the `preamble' attribute,
except that it contains text that appears between the last boundary and
the end of the message.  As with the @ref{3af0,,preamble},
if there is no epilog text this attribute will be @code{None}.
@end deffn

@geindex defects (email.message.EmailMessage の属性)
@anchor{library/email message email message EmailMessage defects}@anchor{3af2}
@deffn {の属性} defects

`defects' 属性はメッセージを解析する途中で検出されたすべての問題点 (defect、障害) のリストを保持しています。解析中に発見されうる障害についてのより詳細な説明は @ref{43,,email.errors} を参照してください。
@end deffn
@end deffn

@geindex MIMEPart (email.message のクラス)
@anchor{library/email message email message MIMEPart}@anchor{113d}
@deffn {クラス} email.message.MIMEPart (policy=default)

This class represents a subpart of a MIME message.  It is identical to
@ref{580,,EmailMessage}, except that no @code{MIME-Version} headers are
added when @ref{1c5d,,set_content()} is called, since sub-parts do
not need their own @code{MIME-Version} headers.
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email parser Parsing email messages,email generator Generating MIME documents,email message Representing an email message,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email parser doc}@anchor{3af3}@anchor{library/email parser email-parser-parsing-email-messages}@anchor{3af4}@anchor{library/email parser module-email parser}@anchor{52}@anchor{library/email parser translation-repo}@anchor{3af5}
@subsubsection @code{email.parser}: Parsing email messages


@geindex module; email.parser

`ソースコード:' Lib/email/parser.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/parser.py}


__________________________________________________________________


Message object structures can be created in one of two ways: they can be
created from whole cloth by creating an @ref{580,,EmailMessage}
object, adding headers using the dictionary interface, and adding payload(s)
using @ref{1c5d,,set_content()} and related methods, or
they can be created by parsing a serialized representation of the email
message.

The @ref{3f,,email} package provides a standard parser that understands most email
document structures, including MIME documents.  You can pass the parser a
bytes, string or file object, and the parser will return to you the root
@ref{580,,EmailMessage} instance of the object structure.  For
simple, non-MIME messages the payload of this root object will likely be a
string containing the text of the message.  For MIME messages, the root object
will return @code{True} from its @ref{3abd,,is_multipart()}
method, and the subparts can be accessed via the payload manipulation methods,
such as @ref{3ae1,,get_body()},
@ref{3ae3,,iter_parts()}, and
@ref{3ae0,,walk()}.

There are actually two parser interfaces available for use, the @ref{13b5,,Parser}
API and the incremental @ref{1785,,FeedParser} API.  The @ref{13b5,,Parser} API is
most useful if you have the entire text of the message in memory, or if the
entire message lives in a file on the file system.  @ref{1785,,FeedParser} is more
appropriate when you are reading the message from a stream which might block
waiting for more input (such as reading an email message from a socket).  The
@ref{1785,,FeedParser} can consume and parse the message incrementally, and only
returns the root object when you close the parser.

Note that the parser can be extended in limited ways, and of course you can
implement your own parser completely from scratch.  All of the logic that
connects the @ref{3f,,email} package's bundled parser and the
@ref{580,,EmailMessage} class is embodied in the @ref{12c7,,Policy}
class, so a custom parser can create message object trees any way it finds
necessary by implementing custom versions of the appropriate @code{Policy}
methods.

@menu
* FeedParser API:: 
* Parser API:: 
* 追記事項:: 

@end menu

@node FeedParser API,Parser API,,email parser Parsing email messages
@anchor{library/email parser feedparser-api}@anchor{3af6}
@subsubsection FeedParser API


The @ref{13e3,,BytesFeedParser}, imported from the @code{email.feedparser} module,
provides an API that is conducive to incremental parsing of email messages,
such as would be necessary when reading the text of an email message from a
source that can block (such as a socket).  The @ref{13e3,,BytesFeedParser} can of
course be used to parse an email message fully contained in a @ref{193,,bytes-like object}, string, or file, but the @ref{13e4,,BytesParser} API may be more
convenient for such use cases.  The semantics and results of the two parser
APIs are identical.

@ref{13e3,,BytesFeedParser} API は簡単です。まずインスタンスをつくり、それに bytes を (それ以上 bytes が必要なくなるまで) 流しこみます。その後パーザを close すると根っこ (root) のメッセージオブジェクトが返されます。標準に従ったメッセージを解析する場合、 @ref{13e3,,BytesFeedParser} は非常に正確であり、標準に従っていないメッセージでもちゃんと動きます。そのさい、これはメッセージがどのように壊れていると認識されたかについての情報を残します。これはメッセージオブジェクトの @ref{3af2,,defects} 属性にリストとして現れ、メッセージ中に発見された問題が記録されます。パーザが検出できる障害 (defect) については @ref{43,,email.errors} モジュールを参照してください。

以下は @ref{13e3,,BytesFeedParser} の API です:

@geindex BytesFeedParser (email.parser のクラス)
@anchor{library/email parser email parser BytesFeedParser}@anchor{13e3}
@deffn {クラス} email.parser.BytesFeedParser (_factory=None, *, policy=policy.compat32)

Create a @ref{13e3,,BytesFeedParser} instance.  Optional `_factory' is a
no-argument callable; if not specified use the
@ref{e96,,message_factory} from the `policy'.  Call
`_factory' whenever a new message object is needed.

If `policy' is specified use the rules it specifies to update the
representation of the message.  If `policy' is not set, use the
@ref{12c8,,compat32} policy, which maintains backward
compatibility with the Python 3.2 version of the email package and provides
@ref{581,,Message} as the default factory.  All other policies
provide @ref{580,,EmailMessage} as the default `_factory'. For
more information on what else `policy' controls, see the
@ref{53,,policy} documentation.

Note: `The policy keyword should always be specified'; The default will
change to @ref{12cc,,email.policy.default} in a future version of Python.


Added in version 3.2.



バージョン 3.3 で変更: キーワード引数 `policy' が追加されました。



バージョン 3.6 で変更: `_factory' defaults to the policy @code{message_factory}.


@geindex feed() (email.parser.BytesFeedParser のメソッド)
@anchor{library/email parser email parser BytesFeedParser feed}@anchor{3af7}
@deffn {メソッド} feed (data)

パーサーにデータを供給します。 `data' は 1行または複数行からなる @ref{193,,bytes-like object} を渡します。渡される行は完結していなくてもよく、その場合パーサーは部分的な行を適切につなぎ合わせます。各行は3種類の標準的な行末文字 (復帰 CR、改行 LF、または CR+LF) どれかの組み合わせでよく、これらが混在してもかまいません。
@end deffn

@geindex close() (email.parser.BytesFeedParser のメソッド)
@anchor{library/email parser email parser BytesFeedParser close}@anchor{3af8}
@deffn {メソッド} close ()

Complete the parsing of all previously fed data and return the root
message object.  It is undefined what happens if @ref{3af7,,feed()} is called
after this method has been called.
@end deffn
@end deffn

@geindex FeedParser (email.parser のクラス)
@anchor{library/email parser email parser FeedParser}@anchor{1785}
@deffn {クラス} email.parser.FeedParser (_factory=None, *, policy=policy.compat32)

Works like @ref{13e3,,BytesFeedParser} except that the input to the
@ref{3af7,,feed()} method must be a string.  This is of limited
utility, since the only way for such a message to be valid is for it to
contain only ASCII text or, if @ref{ff9,,utf8} is
@code{True}, no binary attachments.


バージョン 3.3 で変更: キーワード引数 `policy' が追加されました。

@end deffn

@node Parser API,追記事項,FeedParser API,email parser Parsing email messages
@anchor{library/email parser parser-api}@anchor{3af9}
@subsubsection Parser API


The @ref{13e4,,BytesParser} class, imported from the @code{email.parser} module,
provides an API that can be used to parse a message when the complete contents
of the message are available in a @ref{193,,bytes-like object} or file.  The
@code{email.parser} module also provides @ref{13b5,,Parser} for parsing strings,
and header-only parsers, @ref{12d1,,BytesHeaderParser} and
@ref{12d2,,HeaderParser}, which can be used if you're only interested in the
headers of the message.  @ref{12d1,,BytesHeaderParser} and @ref{12d2,,HeaderParser}
can be much faster in these situations, since they do not attempt to parse the
message body, instead setting the payload to the raw body.

@geindex BytesParser (email.parser のクラス)
@anchor{library/email parser email parser BytesParser}@anchor{13e4}
@deffn {クラス} email.parser.BytesParser (_class=None, *, policy=policy.compat32)

Create a @ref{13e4,,BytesParser} instance.  The `_class' and `policy'
arguments have the same meaning and semantics as the `_factory'
and `policy' arguments of @ref{13e3,,BytesFeedParser}.

Note: `The policy keyword should always be specified'; The default will
change to @ref{12cc,,email.policy.default} in a future version of Python.


バージョン 3.3 で変更: 2.4 で非推奨になった `strict' 引数の削除。キーワード引数 `policy' の追加。



バージョン 3.6 で変更: `_class' defaults to the policy @code{message_factory}.


@geindex parse() (email.parser.BytesParser のメソッド)
@anchor{library/email parser email parser BytesParser parse}@anchor{3afa}
@deffn {メソッド} parse (fp, headersonly=False)

Read all the data from the binary file-like object `fp', parse the
resulting bytes, and return the message object.  `fp' must support
both the @ref{1541,,readline()} and the @code{read()}
methods.

The bytes contained in `fp' must be formatted as a block of 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}
(or, if @ref{ff9,,utf8} is @code{True}, 
@geindex RFC; RFC 6532
RFC 6532@footnote{https://datatracker.ietf.org/doc/html/rfc6532.html})
style headers and header continuation lines, optionally preceded by an
envelope header.  The header block is terminated either by the end of the
data or by a blank line.  Following the header block is the body of the
message (which may contain MIME-encoded subparts, including subparts
with a @code{Content-Transfer-Encoding} of @code{8bit}).

オプション引数 `headersonly' はヘッダを読み終えた後にパースを止めるかを指定するフラグです。デフォルトは @code{False} で、ファイルの内容全体をパースします。
@end deffn

@geindex parsebytes() (email.parser.BytesParser のメソッド)
@anchor{library/email parser email parser BytesParser parsebytes}@anchor{3afb}
@deffn {メソッド} parsebytes (bytes, headersonly=False)

Similar to the @ref{3afa,,parse()} method, except it takes a @ref{193,,bytes-like object} instead of a file-like object.  Calling this method on a
@ref{193,,bytes-like object} is equivalent to wrapping `bytes' in a
@ref{10a4,,BytesIO} instance first and calling @ref{3afa,,parse()}.

オプション引数 `headersonly' は @ref{3afa,,parse()} メソッドと同じです。
@end deffn


Added in version 3.2.

@end deffn

@geindex BytesHeaderParser (email.parser のクラス)
@anchor{library/email parser email parser BytesHeaderParser}@anchor{12d1}
@deffn {クラス} email.parser.BytesHeaderParser (_class=None, *, policy=policy.compat32)

Exactly like @ref{13e4,,BytesParser}, except that `headersonly'
defaults to @code{True}.


Added in version 3.3.

@end deffn

@geindex Parser (email.parser のクラス)
@anchor{library/email parser email parser Parser}@anchor{13b5}
@deffn {クラス} email.parser.Parser (_class=None, *, policy=policy.compat32)

This class is parallel to @ref{13e4,,BytesParser}, but handles string input.


バージョン 3.3 で変更: `strict' 引数の削除。キーワード引数 `policy' の追加。



バージョン 3.6 で変更: `_class' defaults to the policy @code{message_factory}.


@geindex parse() (email.parser.Parser のメソッド)
@anchor{library/email parser email parser Parser parse}@anchor{3afc}
@deffn {メソッド} parse (fp, headersonly=False)

ファイルなどテキストモードのストリーム形式 (file-like) のオブジェクト `fp' からすべてのデータを読み込み、得られたテキストを解析して基底 (root) メッセージオブジェクト構造を返します。 `fp' はストリーム形式のオブジェクトで @ref{20a6,,readline()} および @ref{206c,,read()} 両方のメソッドをサポートしている必要があります。

Other than the text mode requirement, this method operates like
@ref{3afa,,BytesParser.parse()}.
@end deffn

@geindex parsestr() (email.parser.Parser のメソッド)
@anchor{library/email parser email parser Parser parsestr}@anchor{3afd}
@deffn {メソッド} parsestr (text, headersonly=False)

@ref{3afc,,parse()} メソッドに似ていますが、ファイルなどのストリーム形式のかわりに文字列を引数としてとるところが違います。文字列に対してこのメソッドを呼ぶことは、 `text' を @ref{112a,,StringIO} インスタンスとして作成して @ref{3afc,,parse()} を適用するのと同じです。

オプション引数 `headersonly' は @ref{3afc,,parse()} メソッドと同じです。
@end deffn
@end deffn

@geindex HeaderParser (email.parser のクラス)
@anchor{library/email parser email parser HeaderParser}@anchor{12d2}
@deffn {クラス} email.parser.HeaderParser (_class=None, *, policy=policy.compat32)

Exactly like @ref{13b5,,Parser}, except that `headersonly'
defaults to @code{True}.
@end deffn

ファイルや文字列からメッセージオブジェクト構造を作成するのはかなりよくおこなわれる作業なので、便宜上次のような 4つの関数が提供されています。これらは @ref{3f,,email} パッケージのトップレベルの名前空間で使用できます。

@geindex message_from_bytes() (email モジュール)
@anchor{library/email parser email message_from_bytes}@anchor{13e1}
@deffn {の関数} email.message_from_bytes (s, _class=None, *, policy=policy.compat32)

@ref{193,,bytes-like オブジェクト} からメッセージオブジェクト構造を作成して返します。これは @code{BytesParser().parsebytes(s)} と同じです。オプション引数 `_class' および `policy' は @ref{13e4,,BytesParser} クラスのコンストラクタと同様に解釈されます。


Added in version 3.2.



バージョン 3.3 で変更: `strict' 引数の削除。キーワード引数 `policy' の追加。

@end deffn

@geindex message_from_binary_file() (email モジュール)
@anchor{library/email parser email message_from_binary_file}@anchor{13e2}
@deffn {の関数} email.message_from_binary_file (fp, _class=None, *, policy=policy.compat32)

オープンされたバイナリ @ref{13db,,file object} からメッセージオブジェクト構造を作成して返します。これは @code{BytesParser().parse(fp)} と同じです。 `_class' および `policy' は @ref{13e4,,BytesParser} クラスのコンストラクタと同様に解釈されます。


Added in version 3.2.



バージョン 3.3 で変更: `strict' 引数の削除。キーワード引数 `policy' の追加。

@end deffn

@geindex message_from_string() (email モジュール)
@anchor{library/email parser email message_from_string}@anchor{3afe}
@deffn {の関数} email.message_from_string (s, _class=None, *, policy=policy.compat32)

文字列からメッセージオブジェクト構造を作成して返します。これは @code{Parser().parsestr(s)} と同じです。 `_class' および `policy' は @ref{13b5,,Parser} クラスのコンストラクタと同様に解釈されます。


バージョン 3.3 で変更: `strict' 引数の削除。キーワード引数 `policy' の追加。

@end deffn

@geindex message_from_file() (email モジュール)
@anchor{library/email parser email message_from_file}@anchor{3aff}
@deffn {の関数} email.message_from_file (fp, _class=None, *, policy=policy.compat32)

オープンされた @ref{13db,,file object} からメッセージオブジェクト構造を作成して返します。これは @code{Parser().parse(fp)} と同じです。 `_class' および `policy' は @ref{13b5,,Parser} クラスのコンストラクタと同様に解釈されます。


バージョン 3.3 で変更: `strict' 引数の削除。キーワード引数 `policy' の追加。



バージョン 3.6 で変更: `_class' defaults to the policy @code{message_factory}.

@end deffn

対話的な Python プロンプトで @ref{13e1,,message_from_bytes()} を使用するとすれば、このようになります:

@example
>>> import email
>>> msg = email.message_from_bytes(myBytes)
@end example

@node 追記事項,,Parser API,email parser Parsing email messages
@anchor{library/email parser additional-notes}@anchor{3b00}
@subsubsection 追記事項


以下はテキスト解析の際に適用されるいくつかの規約です:


@itemize *

@item 
Most non-@code{multipart} type messages are parsed as a single message
object with a string payload.  These objects will return @code{False} for
@ref{3abd,,is_multipart()}, and
@ref{3ae3,,iter_parts()} will yield an empty list.

@item 
All @code{multipart} type messages will be parsed as a container message
object with a list of sub-message objects for their payload.  The outer
container message will return @code{True} for
@ref{3abd,,is_multipart()}, and
@ref{3ae3,,iter_parts()} will yield a list of subparts.

@item 
Most messages with a content type of @code{message/*} (such as
@code{message/delivery-status} and @code{message/rfc822}) will also
be parsed as container object containing a list payload of length 1.  Their
@ref{3abd,,is_multipart()} method will return @code{True}.
The single element yielded by @ref{3ae3,,iter_parts()}
will be a sub-message object.

@item 
いくつかの標準的でないメッセージは、 @code{multipart} の使い方に統一がとれていない場合があります。このようなメッセージは @code{Content-Type} ヘッダに @code{multipart} を指定しているものの、その @ref{3abd,,is_multipart()} メソッドは @code{False} を返すことがあります。もしこのようなメッセージが @ref{1785,,FeedParser} によって解析されると、その `defects' 属性のリスト中には @ref{3b01,,MultipartInvariantViolationDefect} クラスのインスタンスが現れます。詳しい情報については @ref{43,,email.errors} を参照してください。
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email generator Generating MIME documents,email policy Policy Objects,email parser Parsing email messages,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email generator doc}@anchor{3b02}@anchor{library/email generator email-generator-generating-mime-documents}@anchor{3b03}@anchor{library/email generator module-email generator}@anchor{44}@anchor{library/email generator translation-repo}@anchor{3b04}
@subsubsection @code{email.generator}: Generating MIME documents


@geindex module; email.generator

`ソースコード:' Lib/email/generator.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/generator.py}


__________________________________________________________________


One of the most common tasks is to generate the flat (serialized) version of
the email message represented by a message object structure.  You will need to
do this if you want to send your message via @ref{1059,,smtplib.SMTP.sendmail()},
or print the message on the console.  Taking a
message object structure and producing a serialized representation is the job
of the generator classes.

As with the @ref{52,,email.parser} module, you aren't limited to the functionality
of the bundled generator; you could write one from scratch yourself.  However
the bundled generator knows how to generate most email in a standards-compliant
way, should handle MIME and non-MIME email messages just fine, and is designed
so that the bytes-oriented parsing and generation operations are inverses,
assuming the same non-transforming @ref{53,,policy} is used for both.  That
is, parsing the serialized byte stream via the
@ref{13e4,,BytesParser} class and then regenerating the serialized
byte stream using @ref{13e7,,BytesGenerator} should produce output identical to
the input @footnote{
This statement assumes that you use the appropriate setting for
@code{unixfrom}, and that there are no @ref{53,,email.policy} settings calling for
automatic adjustments (for example,
@ref{3b05,,refold_source} must be @code{none}, which is
`not' the default).  It is also not 100% true, since if the message
does not conform to the RFC standards occasionally information about the
exact original text is lost during parsing error recovery.  It is a goal
to fix these latter edge cases when possible.
}.  (On the other hand, using the generator on an
@ref{580,,EmailMessage} constructed by program may result in
changes to the @ref{580,,EmailMessage} object as defaults are
filled in.)

The @ref{13e6,,Generator} class can be used to flatten a message into a text (as
opposed to binary) serialized representation, but since Unicode cannot
represent binary data directly, the message is of necessity transformed into
something that contains only ASCII characters, using the standard email RFC
Content Transfer Encoding techniques for encoding email messages for transport
over channels that are not "8 bit clean".

To accommodate reproducible processing of SMIME-signed messages
@ref{13e6,,Generator} disables header folding for message parts of type
@code{multipart/signed} and all subparts.

@geindex BytesGenerator (email.generator のクラス)
@anchor{library/email generator email generator BytesGenerator}@anchor{13e7}
@deffn {クラス} email.generator.BytesGenerator (outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)

Return a @ref{13e7,,BytesGenerator} object that will write any message provided
to the @ref{3b06,,flatten()} method, or any surrogateescape encoded text provided
to the @ref{3b07,,write()} method, to the @ref{17ac,,file-like object} `outfp'.
`outfp' must support a @code{write} method that accepts binary data.

If optional `mangle_from_' is @code{True}, put a @code{>} character in front of
any line in the body that starts with the exact string @code{"From "}, that is
@code{From} followed by a space at the beginning of a line.  `mangle_from_'
defaults to the value of the @ref{ff7,,mangle_from_}
setting of the `policy' (which is @code{True} for the
@ref{e97,,compat32} policy and @code{False} for all others).
`mangle_from_' is intended for use when messages are stored in Unix mbox
format (see @ref{8f,,mailbox} and WHY THE CONTENT-LENGTH FORMAT IS BAD@footnote{https://www.jwz.org/doc/content-length.html}).

If `maxheaderlen' is not @code{None}, refold any header lines that are longer
than `maxheaderlen', or if @code{0}, do not rewrap any headers.  If
`manheaderlen' is @code{None} (the default), wrap headers and other message
lines according to the `policy' settings.

If `policy' is specified, use that policy to control message generation.  If
`policy' is @code{None} (the default), use the policy associated with the
@ref{581,,Message} or @ref{580,,EmailMessage}
object passed to @code{flatten} to control the message generation.  See
@ref{53,,email.policy} for details on what `policy' controls.


Added in version 3.2.



バージョン 3.3 で変更: キーワード引数 `policy' が追加されました。



バージョン 3.6 で変更: The default behavior of the `mangle_from_'
and `maxheaderlen' parameters is to follow the policy.


@geindex flatten() (email.generator.BytesGenerator のメソッド)
@anchor{library/email generator email generator BytesGenerator flatten}@anchor{3b06}
@deffn {メソッド} flatten (msg, unixfrom=False, linesep=None)

`msg' を基点とするメッセージオブジェクト構造体の文字表現を出力します。出力先のファイルにはこの @ref{13e7,,BytesGenerator} インスタンスが作成されたときに指定されたものが使われます。

If the @ref{53,,policy} option @ref{3b08,,cte_type}
is @code{8bit} (the default), copy any headers in the original parsed
message that have not been modified to the output with any bytes with the
high bit set reproduced as in the original, and preserve the non-ASCII
@code{Content-Transfer-Encoding} of any body parts that have them.
If @code{cte_type} is @code{7bit}, convert the bytes with the high bit set as
needed using an ASCII-compatible @code{Content-Transfer-Encoding}.
That is, transform parts with non-ASCII
@code{Content-Transfer-Encoding}
(@code{Content-Transfer-Encoding: 8bit}) to an ASCII compatible
@code{Content-Transfer-Encoding}, and encode RFC-invalid non-ASCII
bytes in headers using the MIME @code{unknown-8bit} character set, thus
rendering them RFC-compliant.

@c XXX: There should be an option that just does the RFC
@c compliance transformation on headers but leaves CTE 8bit parts alone.

If `unixfrom' is @code{True}, print the envelope header delimiter used by
the Unix mailbox format (see @ref{8f,,mailbox}) before the first of the
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} headers of the root message object.  If the root object has
no envelope header, craft a standard one.  The default is @code{False}.
Note that for subparts, no envelope header is ever printed.

If `linesep' is not @code{None}, use it as the separator character between
all the lines of the flattened message.  If `linesep' is @code{None} (the
default), use the value specified in the `policy'.

@c XXX: flatten should take a *policy* keyword.
@end deffn

@geindex clone() (email.generator.BytesGenerator のメソッド)
@anchor{library/email generator email generator BytesGenerator clone}@anchor{3b09}
@deffn {メソッド} clone (fp)

Return an independent clone of this @ref{13e7,,BytesGenerator} instance with
the exact same option settings, and `fp' as the new `outfp'.
@end deffn

@geindex write() (email.generator.BytesGenerator のメソッド)
@anchor{library/email generator email generator BytesGenerator write}@anchor{3b07}
@deffn {メソッド} write (s)

Encode `s' using the @code{ASCII} codec and the @code{surrogateescape} error
handler, and pass it to the `write' method of the `outfp' passed to the
@ref{13e7,,BytesGenerator}'s constructor.
@end deffn
@end deffn

As a convenience, @ref{580,,EmailMessage} provides the methods
@ref{3abb,,as_bytes()} and @code{bytes(aMessage)} (a.k.a.
@ref{3abc,,__bytes__()}), which simplify the generation of
a serialized binary representation of a message object.  For more detail, see
@ref{48,,email.message}.

Because strings cannot represent binary data, the @ref{13e6,,Generator} class must
convert any binary data in any message it flattens to an ASCII compatible
format, by converting them to an ASCII compatible
@code{Content-Transfer_Encoding}.  Using the terminology of the email
RFCs, you can think of this as @ref{13e6,,Generator} serializing to an I/O stream
that is not "8 bit clean".  In other words, most applications will want
to be using @ref{13e7,,BytesGenerator}, and not @ref{13e6,,Generator}.

@geindex Generator (email.generator のクラス)
@anchor{library/email generator email generator Generator}@anchor{13e6}
@deffn {クラス} email.generator.Generator (outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)

Return a @ref{13e6,,Generator} object that will write any message provided
to the @ref{3b0a,,flatten()} method, or any text provided to the @ref{3b0b,,write()}
method, to the @ref{17ac,,file-like object} `outfp'.  `outfp' must support a
@code{write} method that accepts string data.

If optional `mangle_from_' is @code{True}, put a @code{>} character in front of
any line in the body that starts with the exact string @code{"From "}, that is
@code{From} followed by a space at the beginning of a line.  `mangle_from_'
defaults to the value of the @ref{ff7,,mangle_from_}
setting of the `policy' (which is @code{True} for the
@ref{e97,,compat32} policy and @code{False} for all others).
`mangle_from_' is intended for use when messages are stored in Unix mbox
format (see @ref{8f,,mailbox} and WHY THE CONTENT-LENGTH FORMAT IS BAD@footnote{https://www.jwz.org/doc/content-length.html}).

If `maxheaderlen' is not @code{None}, refold any header lines that are longer
than `maxheaderlen', or if @code{0}, do not rewrap any headers.  If
`manheaderlen' is @code{None} (the default), wrap headers and other message
lines according to the `policy' settings.

If `policy' is specified, use that policy to control message generation.  If
`policy' is @code{None} (the default), use the policy associated with the
@ref{581,,Message} or @ref{580,,EmailMessage}
object passed to @code{flatten} to control the message generation.  See
@ref{53,,email.policy} for details on what `policy' controls.


バージョン 3.3 で変更: キーワード引数 `policy' が追加されました。



バージョン 3.6 で変更: The default behavior of the `mangle_from_'
and `maxheaderlen' parameters is to follow the policy.


@geindex flatten() (email.generator.Generator のメソッド)
@anchor{library/email generator email generator Generator flatten}@anchor{3b0a}
@deffn {メソッド} flatten (msg, unixfrom=False, linesep=None)

`msg' を基点とするメッセージオブジェクト構造体の文字表現を出力します。出力先のファイルにはこの @ref{13e6,,Generator} インスタンスが作成されたときに指定されたものが使われます。

If the @ref{53,,policy} option @ref{3b08,,cte_type}
is @code{8bit}, generate the message as if the option were set to @code{7bit}.
(This is required because strings cannot represent non-ASCII bytes.)
Convert any bytes with the high bit set as needed using an
ASCII-compatible @code{Content-Transfer-Encoding}.  That is,
transform parts with non-ASCII @code{Content-Transfer-Encoding}
(@code{Content-Transfer-Encoding: 8bit}) to an ASCII compatible
@code{Content-Transfer-Encoding}, and encode RFC-invalid non-ASCII
bytes in headers using the MIME @code{unknown-8bit} character set, thus
rendering them RFC-compliant.

If `unixfrom' is @code{True}, print the envelope header delimiter used by
the Unix mailbox format (see @ref{8f,,mailbox}) before the first of the
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} headers of the root message object.  If the root object has
no envelope header, craft a standard one.  The default is @code{False}.
Note that for subparts, no envelope header is ever printed.

If `linesep' is not @code{None}, use it as the separator character between
all the lines of the flattened message.  If `linesep' is @code{None} (the
default), use the value specified in the `policy'.

@c XXX: flatten should take a *policy* keyword.


バージョン 3.2 で変更: @code{8bit} メッセージ本体の再エンコードがサポートされました。`linesep' 引数が追加されました。

@end deffn

@geindex clone() (email.generator.Generator のメソッド)
@anchor{library/email generator email generator Generator clone}@anchor{3b0c}
@deffn {メソッド} clone (fp)

Return an independent clone of this @ref{13e6,,Generator} instance with the
exact same options, and `fp' as the new `outfp'.
@end deffn

@geindex write() (email.generator.Generator のメソッド)
@anchor{library/email generator email generator Generator write}@anchor{3b0b}
@deffn {メソッド} write (s)

Write `s' to the `write' method of the `outfp' passed to the
@ref{13e6,,Generator}'s constructor.  This provides just enough file-like
API for @ref{13e6,,Generator} instances to be used in the @ref{1177,,print()}
function.
@end deffn
@end deffn

As a convenience, @ref{580,,EmailMessage} provides the methods
@ref{3ab8,,as_string()} and @code{str(aMessage)} (a.k.a.
@ref{3aba,,__str__()}), which simplify the generation of
a formatted string representation of a message object.  For more detail, see
@ref{48,,email.message}.

The @code{email.generator} module also provides a derived class,
@ref{e95,,DecodedGenerator}, which is like the @ref{13e6,,Generator} base class,
except that non-@code{text} parts are not serialized, but are instead
represented in the output stream by a string derived from a template filled
in with information about the part.

@geindex DecodedGenerator (email.generator のクラス)
@anchor{library/email generator email generator DecodedGenerator}@anchor{e95}
@deffn {クラス} email.generator.DecodedGenerator (outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *, policy=None)

Act like @ref{13e6,,Generator}, except that for any subpart of the message
passed to @ref{3b0a,,Generator.flatten()}, if the subpart is of main type
@code{text}, print the decoded payload of the subpart, and if the main
type is not @code{text}, instead of printing it fill in the string
`fmt' using information from the part and print the resulting
filled-in string.

To fill in `fmt', execute @code{fmt % part_info}, where @code{part_info}
is a dictionary composed of the following keys and values:


@itemize *

@item 
@code{type} -- 非 @code{text} 型 subpart の MIME 形式

@item 
@code{maintype} -- 非 @code{text} 型 subpart の MIME 主形式 (maintype)

@item 
@code{subtype} -- 非 @code{text} 型 subpart の MIME 副形式 (subtype)

@item 
@code{filename} -- 非 @code{text} 型 subpart のファイル名

@item 
@code{description} -- 非 @code{text} 型 subpart につけられた説明文字列

@item 
@code{encoding} -- 非 @code{text} 型 subpart の Content-transfer-encoding
@end itemize

If `fmt' is @code{None}, use the following default `fmt':

@quotation

"[Non-text (%(type)s) part of message omitted, filename %(filename)s]"
@end quotation

Optional `_mangle_from_' and `maxheaderlen' are as with the
@ref{13e6,,Generator} base class.
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email policy Policy Objects,email errors Exception and Defect classes,email generator Generating MIME documents,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email policy doc}@anchor{3b0d}@anchor{library/email policy email-policy-policy-objects}@anchor{3b0e}@anchor{library/email policy module-email policy}@anchor{53}@anchor{library/email policy translation-repo}@anchor{3b0f}
@subsubsection @code{email.policy}: Policy Objects


@geindex module; email.policy


Added in version 3.3.


`ソースコード:' Lib/email/policy.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/policy.py}


__________________________________________________________________


@ref{3f,,email} パッケージの主要な目的は様々なEメールやMIMEのRFCで記述されたEメールメッセージを取り扱うことにあります。しかし、Eメールメッセージの一般的なフォーマット(名前の後にコロンが続き、コロンの後に値が続くという構成の複数のヘッダーフィールドのブロック、空白行、任意の 'body')はEメールの分野外での用途が見いだされたフォーマットです。これらの用途には主となるEメールのRFCに厳密に従っているものもあれば、そうでないものもあります。Eメールを使ったworkingのときでさえも、厳密なRFC準拠にしないのが望ましいことがあります。たとえば、基準に従わないEメールサーバーと相互運用するEメールを作成するときや、基準に違反する方法で使用したい拡張機能を実装するEメールを作成するときです。

これらのばらばらな用途に対応するためPolicyオブジェクトはEメールパッケージに対して柔軟性を提供します。

A @ref{12c7,,Policy} object encapsulates a set of attributes and methods that
control the behavior of various components of the email package during use.
@ref{12c7,,Policy} instances can be passed to various classes and methods in the
email package to alter the default behavior.  The settable values and their
defaults are described below.

There is a default policy used by all classes in the email package.  For all of
the @ref{52,,parser} classes and the related convenience functions, and for
the @ref{581,,Message} class, this is the @ref{12c8,,Compat32}
policy, via its corresponding pre-defined instance @ref{e97,,compat32}.  This
policy provides for complete backward compatibility (in some cases, including
bug compatibility) with the pre-Python3.3 version of the email package.

This default value for the `policy' keyword to
@ref{580,,EmailMessage} is the @ref{12cb,,EmailPolicy} policy, via
its pre-defined instance @ref{12cc,,default}.

When a @ref{581,,Message} or @ref{580,,EmailMessage}
object is created, it acquires a policy.  If the message is created by a
@ref{52,,parser}, a policy passed to the parser will be the policy used by
the message it creates.  If the message is created by the program, then the
policy can be specified when it is created.  When a message is passed to a
@ref{44,,generator}, the generator uses the policy from the message by
default, but you can also pass a specific policy to the generator that will
override the one stored on the message object.

The default value for the `policy' keyword for the @ref{52,,email.parser} classes
and the parser convenience functions `will be changing' in a future version of
Python.  Therefore you should `always specify explicitly which policy you want
to use' when calling any of the classes and functions described in the
@ref{52,,parser} module.

The first part of this documentation covers the features of @ref{12c7,,Policy}, an
@ref{13ce,,abstract base class} that defines the features that are common to all
policy objects, including @ref{e97,,compat32}.  This includes certain hook
methods that are called internally by the email package, which a custom policy
could override to obtain different behavior.  The second part describes the
concrete classes @ref{12cb,,EmailPolicy} and @ref{12c8,,Compat32}, which implement
the hooks that provide the standard behavior and the backward compatible
behavior and features, respectively.

@ref{12c7,,Policy} instances are immutable, but they can be cloned, accepting the
same keyword arguments as the class constructor and returning a new
@ref{12c7,,Policy} instance that is a copy of the original but with the specified
attributes values changed.

As an example, the following code could be used to read an email message from a
file on disk and pass it to the system @code{sendmail} program on a Unix system:

@c from unittest import mock
@c mocker = mock.patch('subprocess.Popen')
@c m = mocker.start()
@c proc = mock.MagicMock()
@c m.return_value = proc
@c proc.stdin.close.return_value = None
@c mymsg = open('mymsg.txt', 'w')
@c mymsg.write('To: abc@xyz.com\n\n')
@c mymsg.flush()

@example
>>> from email import message_from_binary_file
>>> from email.generator import BytesGenerator
>>> from email import policy
>>> from subprocess import Popen, PIPE
>>> with open('mymsg.txt', 'rb') as f:
...     msg = message_from_binary_file(f, policy=policy.default)
...
>>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
>>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
>>> g.flatten(msg)
>>> p.stdin.close()
>>> rc = p.wait()
@end example

@c mymsg.close()
@c mocker.stop()
@c import os
@c os.remove('mymsg.txt')

Here we are telling @ref{13e7,,BytesGenerator} to use the RFC
correct line separator characters when creating the binary string to feed into
@code{sendmail's} @code{stdin}, where the default policy would use @code{\n} line
separators.

Some email package methods accept a `policy' keyword argument, allowing the
policy to be overridden for that method.  For example, the following code uses
the @ref{1139,,as_bytes()} method of the `msg' object from
the previous example and writes the message to a file using the native line
separators for the platform on which it is running:

@example
>>> import os
>>> with open('converted.txt', 'wb') as f:
...     f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))
17
@end example

Policyオブジェクトは加算オペレータを使用して組み合わせることも可能で、それらのオブジェクトの非デフォルト値を組み合わせた設定を持つPolicyオブジェクトを生成します:

@example
>>> compat_SMTP = policy.compat32.clone(linesep='\r\n')
>>> compat_strict = policy.compat32.clone(raise_on_defect=True)
>>> compat_strict_SMTP = compat_SMTP + compat_strict
@end example

この操作には交換法則が成り立ちません。つまり、オブジェクトを加える順番に結果が依存します。次のように説明できます:

@example
>>> policy100 = policy.compat32.clone(max_line_length=100)
>>> policy80 = policy.compat32.clone(max_line_length=80)
>>> apolicy = policy100 + policy80
>>> apolicy.max_line_length
80
>>> apolicy = policy80 + policy100
>>> apolicy.max_line_length
100
@end example

@geindex Policy (email.policy のクラス)
@anchor{library/email policy email policy Policy}@anchor{12c7}
@deffn {クラス} email.policy.Policy (**kw)

This is the @ref{13ce,,abstract base class} for all policy classes.  It provides
default implementations for a couple of trivial methods, as well as the
implementation of the immutability property, the @ref{12c9,,clone()} method, and
the constructor semantics.

The constructor of a policy class can be passed various keyword arguments.
The arguments that may be specified are any non-method properties on this
class, plus any additional non-method properties on the concrete class.  A
value specified in the constructor will override the default value for the
corresponding attribute.

This class defines the following properties, and thus values for the
following may be passed in the constructor of any policy class:

@geindex max_line_length (email.policy.Policy の属性)
@anchor{library/email policy email policy Policy max_line_length}@anchor{3ab9}
@deffn {の属性} max_line_length

行の終端文字を数に含まない、シリアライズした出力の任意の行の最大長。デフォルトは 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} に従い78となっています。値が @code{0} または @ref{885,,None} の場合は行の折り返しを全くしないべきであるということを示します。
@end deffn

@geindex linesep (email.policy.Policy の属性)
@anchor{library/email policy email policy Policy linesep}@anchor{3b10}
@deffn {の属性} linesep

The string to be used to terminate lines in serialized output.  The
default is @code{\n} because that's the internal end-of-line discipline used
by Python, though @code{\r\n} is required by the RFCs.
@end deffn

@geindex cte_type (email.policy.Policy の属性)
@anchor{library/email policy email policy Policy cte_type}@anchor{3b08}
@deffn {の属性} cte_type

Controls the type of Content Transfer Encodings that may be or are
required to be used.  The possible values are:


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{7bit}

@tab

all data must be "7 bit clean" (ASCII-only).  This means that
where necessary data will be encoded using either
quoted-printable or base64 encoding.

@item

@code{8bit}

@tab

data is not constrained to be 7 bit clean.  Data in headers is
still required to be ASCII-only and so will be encoded (see
@ref{3b11,,fold_binary()} and @ref{ff9,,utf8} below for
exceptions), but body parts may use the @code{8bit} CTE.

@end multitable


A @code{cte_type} value of @code{8bit} only works with @code{BytesGenerator}, not
@code{Generator}, because strings cannot contain binary data.  If a
@code{Generator} is operating under a policy that specifies
@code{cte_type=8bit}, it will act as if @code{cte_type} is @code{7bit}.
@end deffn

@geindex raise_on_defect (email.policy.Policy の属性)
@anchor{library/email policy email policy Policy raise_on_defect}@anchor{3b12}
@deffn {の属性} raise_on_defect

If @ref{e07,,True}, any defects encountered will be raised as errors.  If
@ref{d2b,,False} (the default), defects will be passed to the
@ref{3b13,,register_defect()} method.
@end deffn

@geindex mangle_from_ (email.policy.Policy の属性)
@anchor{library/email policy email policy Policy mangle_from_}@anchor{ff7}
@deffn {の属性} mangle_from_

If @ref{e07,,True}, lines starting with `"From "' in the body are
escaped by putting a @code{>} in front of them. This parameter is used when
the message is being serialized by a generator.
Default: @ref{d2b,,False}.


Added in version 3.5.

@end deffn

@geindex message_factory (email.policy.Policy の属性)
@anchor{library/email policy email policy Policy message_factory}@anchor{e96}
@deffn {の属性} message_factory

A factory function for constructing a new empty message object.  Used
by the parser when building messages.  Defaults to @code{None}, in
which case @ref{581,,Message} is used.


Added in version 3.6.

@end deffn

@geindex verify_generated_headers (email.policy.Policy の属性)
@anchor{library/email policy email policy Policy verify_generated_headers}@anchor{4f2}
@deffn {の属性} verify_generated_headers

If @code{True} (the default), the generator will raise
@ref{3b14,,HeaderWriteError} instead of writing a header
that is improperly folded or delimited, such that it would
be parsed as multiple headers or joined with adjacent data.
Such headers can be generated by custom header classes or bugs
in the @code{email} module.

As it's a security feature, this defaults to @code{True} even in the
@ref{12c8,,Compat32} policy.
For backwards compatible, but unsafe, behavior, it must be set to
@code{False} explicitly.


Added in version 3.13.

@end deffn

The following @ref{12c7,,Policy} method is intended to be called by code using
the email library to create policy instances with custom settings:

@geindex clone() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy clone}@anchor{12c9}
@deffn {メソッド} clone (**kw)

Return a new @ref{12c7,,Policy} instance whose attributes have the same
values as the current instance, except where those attributes are
given new values by the keyword arguments.
@end deffn

The remaining @ref{12c7,,Policy} methods are called by the email package code,
and are not intended to be called by an application using the email package.
A custom policy must implement all of these methods.

@geindex handle_defect() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy handle_defect}@anchor{3b15}
@deffn {メソッド} handle_defect (obj, defect)

Handle a `defect' found on `obj'.  When the email package calls this
method, `defect' will always be a subclass of
@ref{3b16,,MessageDefect}.

The default implementation checks the @ref{3b12,,raise_on_defect} flag.  If
it is @code{True}, `defect' is raised as an exception.  If it is @code{False}
(the default), `obj' and `defect' are passed to @ref{3b13,,register_defect()}.
@end deffn

@geindex register_defect() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy register_defect}@anchor{3b13}
@deffn {メソッド} register_defect (obj, defect)

Register a `defect' on `obj'.  In the email package, `defect' will always
be a subclass of @ref{3b16,,MessageDefect}.

The default implementation calls the @code{append} method of the @code{defects}
attribute of `obj'.  When the email package calls @ref{3b15,,handle_defect},
`obj' will normally have a @code{defects} attribute that has an @code{append}
method.  Custom object types used with the email package (for example,
custom @code{Message} objects) should also provide such an attribute,
otherwise defects in parsed messages will raise unexpected errors.
@end deffn

@geindex header_max_count() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy header_max_count}@anchor{3b17}
@deffn {メソッド} header_max_count (name)

`name' というヘッダに許される最大の数を返します。

Called when a header is added to an @ref{580,,EmailMessage}
or @ref{581,,Message} object.  If the returned value is not
@code{0} or @code{None}, and there are already a number of headers with the
name `name' greater than or equal to the value returned, a
@ref{2ec,,ValueError} is raised.

Because the default behavior of @code{Message.__setitem__} is to append the
value to the list of headers, it is easy to create duplicate headers
without realizing it.  This method allows certain headers to be limited
in the number of instances of that header that may be added to a
@code{Message} programmatically.  (The limit is not observed by the parser,
which will faithfully produce as many headers as exist in the message
being parsed.)

デフォルトの実装は全てのヘッダ名に @code{None} を返します。
@end deffn

@geindex header_source_parse() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy header_source_parse}@anchor{3b18}
@deffn {メソッド} header_source_parse (sourcelines)

The email package calls this method with a list of strings, each string
ending with the line separation characters found in the source being
parsed.  The first line includes the field header name and separator.
All whitespace in the source is preserved.  The method should return the
@code{(name, value)} tuple that is to be stored in the @code{Message} to
represent the parsed header.

If an implementation wishes to retain compatibility with the existing
email package policies, `name' should be the case preserved name (all
characters up to the '@code{:}' separator), while `value' should be the
unfolded value (all line separator characters removed, but whitespace
kept intact), stripped of leading whitespace.

`sourcelines' はサロゲートエスケープされたバイナリーデータを持つことがあります。

デフォルトの実装はありません。
@end deffn

@geindex header_store_parse() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy header_store_parse}@anchor{3b19}
@deffn {メソッド} header_store_parse (name, value)

The email package calls this method with the name and value provided by
the application program when the application program is modifying a
@code{Message} programmatically (as opposed to a @code{Message} created by a
parser).  The method should return the @code{(name, value)} tuple that is to
be stored in the @code{Message} to represent the header.

If an implementation wishes to retain compatibility with the existing
email package policies, the `name' and `value' should be strings or
string subclasses that do not change the content of the passed in
arguments.

デフォルトの実装はありません。
@end deffn

@geindex header_fetch_parse() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy header_fetch_parse}@anchor{3b1a}
@deffn {メソッド} header_fetch_parse (name, value)

The email package calls this method with the `name' and `value' currently
stored in the @code{Message} when that header is requested by the
application program, and whatever the method returns is what is passed
back to the application as the value of the header being retrieved.
Note that there may be more than one header with the same name stored in
the @code{Message}; the method is passed the specific name and value of the
header destined to be returned to the application.

`value' はサロゲートエスケープされたバイナリーデータを持つことがあります。このメソッドの返り値にはサロゲートエスケープされたバイナリーデータはありません。

デフォルトの実装はありません。
@end deffn

@geindex fold() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy fold}@anchor{3b1b}
@deffn {メソッド} fold (name, value)

The email package calls this method with the `name' and `value' currently
stored in the @code{Message} for a given header.  The method should return a
string that represents that header "folded" correctly (according to the
policy settings) by composing the `name' with the `value' and inserting
@ref{3b10,,linesep} characters at the appropriate places.  See 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}
for a discussion of the rules for folding email headers.

`value' はサロゲートエスケープされたバイナリーデータを持つことがあります。このメソッドが返す文字列にはサロゲートエスケープされたバイナリーデータはありません。
@end deffn

@geindex fold_binary() (email.policy.Policy のメソッド)
@anchor{library/email policy email policy Policy fold_binary}@anchor{3b11}
@deffn {メソッド} fold_binary (name, value)

返り値が文字列でなく bytes オブジェクトである点を除けば、@ref{3b1b,,fold()} と同じです。

`value' はサロゲートエスケープされたバイナリデータを持つことがあります。これらは返されたbytesオブジェクト内でバイナリデータに変換されることがあります。
@end deffn
@end deffn

@geindex EmailPolicy (email.policy のクラス)
@anchor{library/email policy email policy EmailPolicy}@anchor{12cb}
@deffn {クラス} email.policy.EmailPolicy (**kw)

This concrete @ref{12c7,,Policy} provides behavior that is intended to be fully
compliant with the current email RFCs.  These include (but are not limited
to) 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}, 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html}, and the current MIME RFCs.

This policy adds new header parsing and folding algorithms.  Instead of
simple strings, headers are @code{str} subclasses with attributes that depend
on the type of the field.  The parsing and folding algorithm fully implement
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} and 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}.

The default value for the @ref{e96,,message_factory}
attribute is @ref{580,,EmailMessage}.

In addition to the settable attributes listed above that apply to all
policies, this policy adds the following additional attributes:


Added in version 3.6: @footnote{
Originally added in 3.3 as a @ref{1243,,provisional feature}.
}


@geindex utf8 (email.policy.EmailPolicy の属性)
@anchor{library/email policy email policy EmailPolicy utf8}@anchor{ff9}
@deffn {の属性} utf8

If @code{False}, follow 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}, supporting non-ASCII characters in
headers by encoding them as "encoded words".  If @code{True}, follow
@geindex RFC; RFC 6532
RFC 6532@footnote{https://datatracker.ietf.org/doc/html/rfc6532.html} and use @code{utf-8} encoding for headers.  Messages
formatted in this way may be passed to SMTP servers that support
the @code{SMTPUTF8} extension (
@geindex RFC; RFC 6531
RFC 6531@footnote{https://datatracker.ietf.org/doc/html/rfc6531.html}).
@end deffn

@geindex refold_source (email.policy.EmailPolicy の属性)
@anchor{library/email policy email policy EmailPolicy refold_source}@anchor{3b05}
@deffn {の属性} refold_source

If the value for a header in the @code{Message} object originated from a
@ref{52,,parser} (as opposed to being set by a program), this
attribute indicates whether or not a generator should refold that value
when transforming the message back into serialized form.  The possible
values are:


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{none}

@tab

all source values use original folding

@item

@code{long}

@tab

source values that have any line that is longer than
@code{max_line_length} will be refolded

@item

@code{all}

@tab

all values are refolded.

@end multitable


デフォルトは @code{long} です。
@end deffn

@geindex header_factory (email.policy.EmailPolicy の属性)
@anchor{library/email policy email policy EmailPolicy header_factory}@anchor{3b1c}
@deffn {の属性} header_factory

A callable that takes two arguments, @code{name} and @code{value}, where
@code{name} is a header field name and @code{value} is an unfolded header field
value, and returns a string subclass that represents that header.  A
default @code{header_factory} (see @ref{46,,headerregistry}) is provided
that supports custom parsing for the various address and date 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}
header field types, and the major MIME header field stypes.  Support for
additional custom parsing will be added in the future.
@end deffn

@geindex content_manager (email.policy.EmailPolicy の属性)
@anchor{library/email policy email policy EmailPolicy content_manager}@anchor{113c}
@deffn {の属性} content_manager

An object with at least two methods: get_content and set_content.  When
the @ref{3ae4,,get_content()} or
@ref{1c5d,,set_content()} method of an
@ref{580,,EmailMessage} object is called, it calls the
corresponding method of this object, passing it the message object as its
first argument, and any arguments or keywords that were passed to it as
additional arguments.  By default @code{content_manager} is set to
@ref{3b1d,,raw_data_manager}.


Added in version 3.4.

@end deffn

このクラスは @ref{12c7,,Policy} の抽象メソッドの具象実装を提供します:

@geindex header_max_count() (email.policy.EmailPolicy のメソッド)
@anchor{library/email policy email policy EmailPolicy header_max_count}@anchor{3b1e}
@deffn {メソッド} header_max_count (name)

Returns the value of the
@ref{3b1f,,max_count} attribute of the
specialized class used to represent the header with the given name.
@end deffn

@geindex header_source_parse() (email.policy.EmailPolicy のメソッド)
@anchor{library/email policy email policy EmailPolicy header_source_parse}@anchor{1912}
@deffn {メソッド} header_source_parse (sourcelines)

The name is parsed as everything up to the '@code{:}' and returned
unmodified.  The value is determined by stripping leading whitespace off
the remainder of the first line, joining all subsequent lines together,
and stripping any trailing carriage return or linefeed characters.
@end deffn

@geindex header_store_parse() (email.policy.EmailPolicy のメソッド)
@anchor{library/email policy email policy EmailPolicy header_store_parse}@anchor{3b20}
@deffn {メソッド} header_store_parse (name, value)

The name is returned unchanged.  If the input value has a @code{name}
attribute and it matches `name' ignoring case, the value is returned
unchanged.  Otherwise the `name' and `value' are passed to
@code{header_factory}, and the resulting header object is returned as
the value.  In this case a @code{ValueError} is raised if the input value
contains CR or LF characters.
@end deffn

@geindex header_fetch_parse() (email.policy.EmailPolicy のメソッド)
@anchor{library/email policy email policy EmailPolicy header_fetch_parse}@anchor{3b21}
@deffn {メソッド} header_fetch_parse (name, value)

If the value has a @code{name} attribute, it is returned to unmodified.
Otherwise the `name', and the `value' with any CR or LF characters
removed, are passed to the @code{header_factory}, and the resulting
header object is returned.  Any surrogateescaped bytes get turned into
the unicode unknown-character glyph.
@end deffn

@geindex fold() (email.policy.EmailPolicy のメソッド)
@anchor{library/email policy email policy EmailPolicy fold}@anchor{19f2}
@deffn {メソッド} fold (name, value)

Header folding is controlled by the @ref{3b05,,refold_source} policy setting.
A value is considered to be a 'source value' if and only if it does not
have a @code{name} attribute (having a @code{name} attribute means it is a
header object of some sort).  If a source value needs to be refolded
according to the policy, it is converted into a header object by
passing the `name' and the `value' with any CR and LF characters removed
to the @code{header_factory}.  Folding of a header object is done by
calling its @code{fold} method with the current policy.

Source values are split into lines using @ref{146e,,splitlines()}.  If
the value is not to be refolded, the lines are rejoined using the
@code{linesep} from the policy and returned.  The exception is lines
containing non-ascii binary data.  In that case the value is refolded
regardless of the @code{refold_source} setting, which causes the binary data
to be CTE encoded using the @code{unknown-8bit} charset.
@end deffn

@geindex fold_binary() (email.policy.EmailPolicy のメソッド)
@anchor{library/email policy email policy EmailPolicy fold_binary}@anchor{3b22}
@deffn {メソッド} fold_binary (name, value)

返り値が bytes である点を除いて、@ref{3b08,,cte_type} が @code{7bit} の場合は @ref{19f2,,fold()} と同じです。

If @ref{3b08,,cte_type} is @code{8bit}, non-ASCII binary data is
converted back
into bytes.  Headers with binary data are not refolded, regardless of the
@code{refold_header} setting, since there is no way to know whether the
binary data consists of single byte characters or multibyte characters.
@end deffn
@end deffn

The following instances of @ref{12cb,,EmailPolicy} provide defaults suitable for
specific application domains.  Note that in the future the behavior of these
instances (in particular the @code{HTTP} instance) may be adjusted to conform even
more closely to the RFCs relevant to their domains.

@geindex default (email.policy モジュール)
@anchor{library/email policy email policy default}@anchor{12cc}
@deffn {データ} email.policy.default

デフォルト値を変更していない @code{EmailPolicy} のインスタンスです。このポリシーの行末は、 RFC で正しい @code{\r\n} ではなく Python の標準の @code{\n} です。
@end deffn

@geindex SMTP (email.policy モジュール)
@anchor{library/email policy email policy SMTP}@anchor{12cd}
@deffn {データ} email.policy.SMTP

Suitable for serializing messages in conformance with the email RFCs.
Like @code{default}, but with @code{linesep} set to @code{\r\n}, which is RFC
compliant.
@end deffn

@geindex SMTPUTF8 (email.policy モジュール)
@anchor{library/email policy email policy SMTPUTF8}@anchor{3b23}
@deffn {データ} email.policy.SMTPUTF8

The same as @code{SMTP} except that @ref{ff9,,utf8} is @code{True}.
Useful for serializing messages to a message store without using encoded
words in the headers.  Should only be used for SMTP transmission if the
sender or recipient addresses have non-ASCII characters (the
@ref{105a,,smtplib.SMTP.send_message()} method handles this automatically).
@end deffn

@geindex HTTP (email.policy モジュール)
@anchor{library/email policy email policy HTTP}@anchor{3b24}
@deffn {データ} email.policy.HTTP

Suitable for serializing headers with for use in HTTP traffic.  Like
@code{SMTP} except that @code{max_line_length} is set to @code{None} (unlimited).
@end deffn

@geindex strict (email.policy モジュール)
@anchor{library/email policy email policy strict}@anchor{3b25}
@deffn {データ} email.policy.strict

Convenience instance.  The same as @code{default} except that
@code{raise_on_defect} is set to @code{True}.  This allows any policy to be made
strict by writing:

@example
somepolicy + policy.strict
@end example
@end deffn

With all of these @ref{12cb,,EmailPolicies}, the effective API of
the email package is changed from the Python 3.2 API in the following ways:


@itemize *

@item 
Setting a header on a @ref{581,,Message} results in that
header being parsed and a header object created.

@item 
Fetching a header value from a @ref{581,,Message} results
in that header being parsed and a header object created and
returned.

@item 
Any header object, or any header that is refolded due to the
policy settings, is folded using an algorithm that fully implements the
RFC folding algorithms, including knowing where encoded words are required
and allowed.
@end itemize

From the application view, this means that any header obtained through the
@ref{580,,EmailMessage} is a header object with extra
attributes, whose string value is the fully decoded unicode value of the
header.  Likewise, a header may be assigned a new value, or a new header
created, using a unicode string, and the policy will take care of converting
the unicode string into the correct RFC encoded form.

ヘッダオブジェクトとその属性は @ref{46,,headerregistry} で述べられています。

@geindex Compat32 (email.policy のクラス)
@anchor{library/email policy email policy Compat32}@anchor{12c8}
@deffn {クラス} email.policy.Compat32 (**kw)

This concrete @ref{12c7,,Policy} is the backward compatibility policy.  It
replicates the behavior of the email package in Python 3.2.  The
@code{policy} module also defines an instance of this class,
@ref{e97,,compat32}, that is used as the default policy.  Thus the default
behavior of the email package is to maintain compatibility with Python 3.2.

以下の属性は @ref{12c7,,Policy} デフォルトとは異なる値を持ちます:

@geindex mangle_from_ (email.policy.Compat32 の属性)
@anchor{library/email policy email policy Compat32 mangle_from_}@anchor{3b26}
@deffn {の属性} mangle_from_

デフォルトは @code{True} です。
@end deffn

このクラスは @ref{12c7,,Policy} の抽象メソッドの具象実装を提供します:

@geindex header_source_parse() (email.policy.Compat32 のメソッド)
@anchor{library/email policy email policy Compat32 header_source_parse}@anchor{1913}
@deffn {メソッド} header_source_parse (sourcelines)

The name is parsed as everything up to the '@code{:}' and returned
unmodified.  The value is determined by stripping leading whitespace off
the remainder of the first line, joining all subsequent lines together,
and stripping any trailing carriage return or linefeed characters.
@end deffn

@geindex header_store_parse() (email.policy.Compat32 のメソッド)
@anchor{library/email policy email policy Compat32 header_store_parse}@anchor{3b27}
@deffn {メソッド} header_store_parse (name, value)

名前と値は変更されずに返されます。
@end deffn

@geindex header_fetch_parse() (email.policy.Compat32 のメソッド)
@anchor{library/email policy email policy Compat32 header_fetch_parse}@anchor{3b28}
@deffn {メソッド} header_fetch_parse (name, value)

If the value contains binary data, it is converted into a
@ref{1c5e,,Header} object using the @code{unknown-8bit} charset.
Otherwise it is returned unmodified.
@end deffn

@geindex fold() (email.policy.Compat32 のメソッド)
@anchor{library/email policy email policy Compat32 fold}@anchor{3b29}
@deffn {メソッド} fold (name, value)

Headers are folded using the @ref{1c5e,,Header} folding
algorithm, which preserves existing line breaks in the value, and wraps
each resulting line to the @code{max_line_length}.  Non-ASCII binary data are
CTE encoded using the @code{unknown-8bit} charset.
@end deffn

@geindex fold_binary() (email.policy.Compat32 のメソッド)
@anchor{library/email policy email policy Compat32 fold_binary}@anchor{3b2a}
@deffn {メソッド} fold_binary (name, value)

Headers are folded using the @ref{1c5e,,Header} folding
algorithm, which preserves existing line breaks in the value, and wraps
each resulting line to the @code{max_line_length}.  If @code{cte_type} is
@code{7bit}, non-ascii binary data is CTE encoded using the @code{unknown-8bit}
charset.  Otherwise the original source header is used, with its existing
line breaks and any (RFC invalid) binary data it may contain.
@end deffn
@end deffn

@geindex compat32 (email.policy モジュール)
@anchor{library/email policy email policy compat32}@anchor{e97}
@deffn {データ} email.policy.compat32

@ref{12c8,,Compat32} のインスタンスで、Python 3.2 の email パッケージの挙動との後方互換性を提供します。

@cartouche
@quotation 注釈 
The @ref{e97,,compat32} policy should not be used as a policy for
@ref{580,,EmailMessage} objects, and should only be used
to serialize messages that were created using the @ref{e97,,compat32}
policy.
@end quotation
@end cartouche
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email errors Exception and Defect classes,email headerregistry Custom Header Objects,email policy Policy Objects,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email errors doc}@anchor{3b2b}@anchor{library/email errors email-errors-exception-and-defect-classes}@anchor{3b2c}@anchor{library/email errors module-email errors}@anchor{43}@anchor{library/email errors translation-repo}@anchor{3b2d}
@subsubsection @code{email.errors}: Exception and Defect classes


@geindex module; email.errors

`ソースコード:' Lib/email/errors.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/errors.py}


__________________________________________________________________


The following exception classes are defined in the @code{email.errors} module:

@geindex MessageError
@anchor{library/email errors email errors MessageError}@anchor{3b2e}
@deffn {例外} email.errors.MessageError

これは @ref{3f,,email} パッケージが送出しうるすべての例外の基底クラスです。これは標準の @ref{bcd,,Exception} クラスから派生しており、追加のメソッドは定義されていません。
@end deffn

@geindex MessageParseError
@anchor{library/email errors email errors MessageParseError}@anchor{3b2f}
@deffn {例外} email.errors.MessageParseError

This is the base class for exceptions raised by the
@ref{13b5,,Parser} class.  It is derived from
@ref{3b2e,,MessageError}.  This class is also used internally by the parser used
by @ref{46,,headerregistry}.
@end deffn

@geindex HeaderParseError
@anchor{library/email errors email errors HeaderParseError}@anchor{3ada}
@deffn {例外} email.errors.HeaderParseError

Raised under some error conditions when parsing the 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} headers of a
message, this class is derived from @ref{3b2f,,MessageParseError}.  The
@ref{3ad9,,set_boundary()} method will raise this
error if the content type is unknown when the method is called.
@ref{1c5e,,Header} may raise this error for certain base64
decoding errors, and when an attempt is made to create a header that appears
to contain an embedded header (that is, there is what is supposed to be a
continuation line that has no leading whitespace and looks like a header).
@end deffn

@geindex BoundaryError
@anchor{library/email errors email errors BoundaryError}@anchor{3b30}
@deffn {例外} email.errors.BoundaryError

Deprecated and no longer used.
@end deffn

@geindex MultipartConversionError
@anchor{library/email errors email errors MultipartConversionError}@anchor{3b31}
@deffn {例外} email.errors.MultipartConversionError

Raised if the @ref{3aeb,,attach()} method is called
on an instance of a class derived from
@ref{3b32,,MIMENonMultipart} (e.g.
@ref{3b33,,MIMEImage}).
@ref{3b31,,MultipartConversionError} multiply
inherits from @ref{3b2e,,MessageError} and the built-in @ref{198,,TypeError}.
@end deffn

@geindex HeaderWriteError
@anchor{library/email errors email errors HeaderWriteError}@anchor{3b14}
@deffn {例外} email.errors.HeaderWriteError

Raised when an error occurs when the @ref{44,,generator} outputs
headers.
@end deffn

@geindex MessageDefect
@anchor{library/email errors email errors MessageDefect}@anchor{3b16}
@deffn {例外} email.errors.MessageDefect

This is the base class for all defects found when parsing email messages.
It is derived from @ref{2ec,,ValueError}.
@end deffn

@geindex HeaderDefect
@anchor{library/email errors email errors HeaderDefect}@anchor{3b34}
@deffn {例外} email.errors.HeaderDefect

This is the base class for all defects found when parsing email headers.
It is derived from @ref{3b16,,MessageDefect}.
@end deffn

以下は @ref{1785,,FeedParser} がメッセージの解析中に検出する障害 (defect) の一覧です。これらの障害は、問題が見つかったメッセージに追加されるため、たとえば @code{multipart/alternative} 内にあるネストしたメッセージが異常なヘッダをもっていた場合には、そのネストしたメッセージが障害を持っているが、その親メッセージには障害はないとみなされることに注意してください。

すべての障害クラスは @ref{3b16,,email.errors.MessageDefect} のサブクラスです。

@geindex NoBoundaryInMultipartDefect
@anchor{library/email errors email errors NoBoundaryInMultipartDefect}@anchor{3b35}
@deffn {例外} email.errors.NoBoundaryInMultipartDefect

A message claimed to be a multipart, but had no @code{boundary}
parameter.
@end deffn

@geindex StartBoundaryNotFoundDefect
@anchor{library/email errors email errors StartBoundaryNotFoundDefect}@anchor{3b36}
@deffn {例外} email.errors.StartBoundaryNotFoundDefect

The start boundary claimed in the @code{Content-Type} header was
never found.
@end deffn

@geindex CloseBoundaryNotFoundDefect
@anchor{library/email errors email errors CloseBoundaryNotFoundDefect}@anchor{3b37}
@deffn {例外} email.errors.CloseBoundaryNotFoundDefect

A start boundary was found, but no corresponding close boundary was ever
found.


Added in version 3.3.

@end deffn

@geindex FirstHeaderLineIsContinuationDefect
@anchor{library/email errors email errors FirstHeaderLineIsContinuationDefect}@anchor{3b38}
@deffn {例外} email.errors.FirstHeaderLineIsContinuationDefect

The message had a continuation line as its first header line.
@end deffn

@geindex MisplacedEnvelopeHeaderDefect
@anchor{library/email errors email errors MisplacedEnvelopeHeaderDefect}@anchor{3b39}
@deffn {例外} email.errors.MisplacedEnvelopeHeaderDefect

A "Unix From" header was found in the middle of a header block.
@end deffn

@geindex MissingHeaderBodySeparatorDefect
@anchor{library/email errors email errors MissingHeaderBodySeparatorDefect}@anchor{3b3a}
@deffn {例外} email.errors.MissingHeaderBodySeparatorDefect

A line was found while parsing headers that had no leading white space but
contained no ':'.  Parsing continues assuming that the line represents the
first line of the body.


Added in version 3.3.

@end deffn

@geindex MalformedHeaderDefect
@anchor{library/email errors email errors MalformedHeaderDefect}@anchor{3b3b}
@deffn {例外} email.errors.MalformedHeaderDefect

A header was found that was missing a colon, or was otherwise malformed.


バージョン 3.3 で非推奨: この欠陥が使われていないPythonバージョンがいくつかあります。

@end deffn

@geindex MultipartInvariantViolationDefect
@anchor{library/email errors email errors MultipartInvariantViolationDefect}@anchor{3b01}
@deffn {例外} email.errors.MultipartInvariantViolationDefect

A message claimed to be a @code{multipart}, but no subparts were found.
Note that when a message has this defect, its
@ref{3ade,,is_multipart()} method may return @code{False}
even though its content type claims to be @code{multipart}.
@end deffn

@geindex InvalidBase64PaddingDefect
@anchor{library/email errors email errors InvalidBase64PaddingDefect}@anchor{3b3c}
@deffn {例外} email.errors.InvalidBase64PaddingDefect

When decoding a block of base64 encoded bytes, the padding was not correct.
Enough padding is added to perform the decode, but the resulting decoded
bytes may be invalid.
@end deffn

@geindex InvalidBase64CharactersDefect
@anchor{library/email errors email errors InvalidBase64CharactersDefect}@anchor{3b3d}
@deffn {例外} email.errors.InvalidBase64CharactersDefect

When decoding a block of base64 encoded bytes, characters outside the base64
alphabet were encountered.  The characters are ignored, but the resulting
decoded bytes may be invalid.
@end deffn

@geindex InvalidBase64LengthDefect
@anchor{library/email errors email errors InvalidBase64LengthDefect}@anchor{3b3e}
@deffn {例外} email.errors.InvalidBase64LengthDefect

When decoding a block of base64 encoded bytes, the number of non-padding
base64 characters was invalid (1 more than a multiple of 4).  The encoded
block was kept as-is.
@end deffn

@geindex InvalidDateDefect
@anchor{library/email errors email errors InvalidDateDefect}@anchor{3b3f}
@deffn {例外} email.errors.InvalidDateDefect

When decoding an invalid or unparsable date field.  The original value is
kept as-is.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email headerregistry Custom Header Objects,email contentmanager Managing MIME Content,email errors Exception and Defect classes,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email headerregistry doc}@anchor{3b40}@anchor{library/email headerregistry email-headerregistry-custom-header-objects}@anchor{3b41}@anchor{library/email headerregistry module-email headerregistry}@anchor{46}@anchor{library/email headerregistry translation-repo}@anchor{3b42}
@subsubsection @code{email.headerregistry}: Custom Header Objects


@geindex module; email.headerregistry

`ソースコード:' Lib/email/headerregistry.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/headerregistry.py}


__________________________________________________________________



Added in version 3.6: @footnote{
Originally added in 3.3 as a @ref{1243,,provisional module}
}


ヘッダーは @ref{169,,str} のカスタマイズされたサブクラスで表現されます。 与えられたヘッダーを表現するために使用される特定のクラスは、ヘッダーが作成されるときに有効な @ref{53,,policy} の @ref{3b1c,,header_factory} で決定されます。 このセクションでは、email ライブラリが 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} に準拠したメールメッセージを扱うために実装している、特定の @code{header_factory} について説明します。このヘッダーは、様々なヘッダータイプに対してカスタマイズされたヘッダーオブジェクトを提供するだけでなく、アプリケーションが独自のカスタムヘッダータイプを追加できるような拡張メカニズムも備えています。

@ref{12cb,,EmailPolicy} から派生したポリシーオブジェクトのいずれかを使用する場合、すべてのヘッダーは @ref{3b43,,HeaderRegistry} によって生成され、最終的な基底クラスとして @ref{3ac6,,BaseHeader} を有します。 各ヘッダクラスには、ヘッダの種類によって決まる追加のベースクラスがあります。 例えば、多くのヘッダーは @ref{3b44,,UnstructuredHeader} というクラスをもうひとつの基底クラスとして持っています。 ヘッダーに特化した第二のクラスは、ヘッダーの名前によって決定され、 @ref{3b43,,HeaderRegistry} に格納されたルックアップテーブルを使用します。 これらすべては、典型的なアプリケーションプログラムに対しては透過的に管理されますが、より複雑なアプリケーションで使用するためにデフォルトの動作を変更するためのインタフェースが提供されています。

以下のセクションでは、まずヘッダーの基本クラスとその属性を説明し、次に @ref{3b43,,HeaderRegistry} の動作を変更するための API、そして最後に構造化ヘッダーからパースされたデータを表現するためのサポートクラスについて説明します。

@geindex BaseHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry BaseHeader}@anchor{3ac6}
@deffn {クラス} email.headerregistry.BaseHeader (name, value)

`name' と `value' は @ref{3b1c,,header_factory} 呼び出しから @code{BaseHeader} に渡されます。 どのヘッダーオブジェクトの文字列値も、完全にユニコードにデコードされた `value' です。

基底クラスは以下の読み出し専用属性を定義しています:

@geindex name (email.headerregistry.BaseHeader の属性)
@anchor{library/email headerregistry email headerregistry BaseHeader name}@anchor{3b45}
@deffn {の属性} name

ヘッダーの名前(フィールドの':'の前の部分)。これは @ref{3b1c,,header_factory} の `name' の呼び出しで渡された値と全く同じです; つまり、大文字・小文字が保持されます。
@end deffn

@geindex defects (email.headerregistry.BaseHeader の属性)
@anchor{library/email headerregistry email headerregistry BaseHeader defects}@anchor{3b46}
@deffn {の属性} defects

パース中に見つかったRFCのコンプライアンス問題を報告する @ref{3b34,,HeaderDefect} インスタンスのタプルです。 email パッケージはコンプライアンスに関する問題を完全に検出するように努めています。 報告されるかもしれない欠陥の種類の議論については、 @ref{43,,errors} モジュールを参照してください。
@end deffn

@geindex max_count (email.headerregistry.BaseHeader の属性)
@anchor{library/email headerregistry email headerregistry BaseHeader max_count}@anchor{3b1f}
@deffn {の属性} max_count

このタイプのヘッダーで、同じ @code{name} を持つことができる最大数。 値として @code{None} を指定すると、無制限になります。 この属性の @code{BaseHeader} の値は @code{None} です; 特殊な header クラスでは、必要に応じてこの値をオーバーライドすることが期待されます。
@end deffn

@code{BaseHeader} は以下のメソッドも提供します。このメソッドはemail ライブラリのコードから呼び出され、一般にアプリケーションプログラムからは呼び出されません：

@geindex fold() (email.headerregistry.BaseHeader のメソッド)
@anchor{library/email headerregistry email headerregistry BaseHeader fold}@anchor{3b47}
@deffn {メソッド} fold (*, policy)

ヘッダを `policy' に従って正しく折りたたむために必要な @ref{3b10,,linesep} 文字を含む文字列を返します。 ヘッダには任意のバイナリデータを含めることができないため、 @ref{3b08,,cte_type} が @code{8bit} の場合は @code{7bit} と同じように扱われます。 もし @ref{ff9,,utf8} が @code{False} であれば、非ASCIIデータは 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} でエンコードされます。
@end deffn

@code{BaseHeader} 自身はヘッダーオブジェクトを生成するために使用することはできません。このクラスは、それぞれの特殊化ヘッダーがヘッダーオブジェクトを生成するために協力するプロトコルを定義しています。 具体的には、 @code{BaseHeader} は @code{parse} という名前の @ref{48e,,classmethod()} を特殊化されたクラスが提供することを要求しています。このメソッドは以下のように呼び出されます:

@example
parse(string, kwds)
@end example

@code{kwds} は、初期化されたキー @code{defects} を含む辞書です。@code{defects} は空のリストです。 解析メソッドは、検出された不具合をこのリストに追加するべきです。 returnの際には、 @code{kwds} 辞書に少なくとも @code{decoded} と`@w{`}defects`@w{`} のキーを含む必要があります。 @code{decoded} はヘッダの文字列値 (つまり、ヘッダを Unicode に完全にデコードした値) でなければなりません。 parseメソッドは、 `string' がcontent-transfer-encodedな部分を含む可能性があると仮定すべきですが、エンコードされていないヘッダ値をパースできるように、すべての有効なUnicode文字も正しく処理する必要があります。

その後、 @code{BaseHeader} の @code{__new__} がヘッダのインスタンスを生成し、 @code{init} メソッドを呼び出します。 特殊クラスは、 @code{BaseHeader} が提供しない属性を設定したい場合にのみ @code{init} メソッドを提供する必要があります。 このような`@w{`}init`@w{`} メソッドは以下のようなものです：

@example
def init(self, /, *args, **kw):
    self._myattr = kw.pop('myattr')
    super().init(*args, **kw)
@end example

つまり、特殊クラスが @code{kwds} の辞書に追加したものはすべて削除して処理し、 @code{kw`@w{`}の残りの内容 (と `@w{`}args}) は`@w{`}BaseHeader`@w{`} の`@w{`}init`@w{`} メソッドに渡す必要があるのです。
@end deffn

@geindex UnstructuredHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry UnstructuredHeader}@anchor{3b44}
@deffn {クラス} email.headerregistry.UnstructuredHeader

"unstructured" ヘッダは 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} におけるデフォルトのヘッダのタイプです。指定された構文を持たないすべてのヘッダは、unstructuredとして扱われます。 構造化されていないヘッダの典型的な例は @code{Subject} ヘッダです。

@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} では、非構造化ヘッダは ASCII 文字セットの任意のテキストの集まりです。しかし、 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} にはヘッダ値の中で非 ASCII テキストを ASCII 文字としてエンコードするための 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} と互換性のあるメカニズムが備わっています。 エンコードされた単語を含む `value' がコンストラクタに渡されると、 @code{UnstructuredHeader} パーサは非構造化テキストに対する 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} 規則に従って、エンコードされた単語を unicode に変換します。 パーサは特定の非適合なエンコードされた単語のデコードを試みるためにヒューリスティックを使用します。 このような場合、欠陥が登録されます。また、エンコードされた単語やエンコードされていないテキスト内の無効な文字などの問題に対しても欠陥が登録されます。

このヘッダ型には追加の属性はありません。
@end deffn

@geindex DateHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry DateHeader}@anchor{3b48}
@deffn {クラス} email.headerregistry.DateHeader

@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} specifies a very specific format for dates within email headers.
The @code{DateHeader} parser recognizes that date format, as well as
recognizing a number of variant forms that are sometimes found "in the
wild".

このヘッダ型は以下の属性も提供しています:

@geindex datetime (email.headerregistry.DateHeader の属性)
@anchor{library/email headerregistry email headerregistry DateHeader datetime}@anchor{3b49}
@deffn {の属性} datetime

If the header value can be recognized as a valid date of one form or
another, this attribute will contain a @ref{4e2,,datetime}
instance representing that date.  If the timezone of the input date is
specified as @code{-0000} (indicating it is in UTC but contains no
information about the source timezone), then @ref{3b49,,datetime} will be a
naive @ref{4e2,,datetime}.  If a specific timezone offset is
found (including @code{+0000}), then @ref{3b49,,datetime} will contain an aware
@code{datetime} that uses @ref{12d5,,datetime.timezone} to record the timezone
offset.
@end deffn

ヘッダーの @code{decoded} 値は、 @code{datetime} を 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} のルールに従ってフォーマットすることで決定されます。

@example
email.utils.format_datetime(self.datetime)
@end example

@code{DateHeader} を作成する際に、 `value' は @ref{4e2,,datetime} インスタンスである可能性があります。 これは、例えば、次のようなコードは有効であり、期待通りの動作をすることを意味します:

@example
msg['Date'] = datetime(2011, 7, 15, 21)
@end example

これは単純な @code{datetime} であるため、UTC タイムスタンプとして解釈され、結果として @code{-0000} というタイムゾーンを持つ値になります。 もっと便利なのは @ref{54,,utils} モジュールの @ref{2f7,,localtime()} 関数を使用することです:

@example
msg['Date'] = utils.localtime()
@end example

この例では、現在のタイムゾーンオフセットを使用して、日付ヘッダーを現在の時刻と日付に設定します。
@end deffn

@geindex AddressHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry AddressHeader}@anchor{3b4a}
@deffn {クラス} email.headerregistry.AddressHeader

アドレスヘッダは最も複雑な構造のヘッダタイプの1つです。 @code{AddressHeader} クラスは、あらゆるアドレスヘッダに対する汎用的なインターフェースを提供します。

このヘッダ型は以下の属性も提供しています:

@geindex groups (email.headerregistry.AddressHeader の属性)
@anchor{library/email headerregistry email headerregistry AddressHeader groups}@anchor{3b4b}
@deffn {の属性} groups

ヘッダー値に含まれるアドレスとグループをエンコードした @ref{3b4c,,Group} オブジェクトのタプルです。 グループに属さないアドレスは、このリストでは @ref{3b4d,,display_name} が @code{None} であるシングルアドレスの @code{Groups} として表現されます。
@end deffn

@geindex addresses (email.headerregistry.AddressHeader の属性)
@anchor{library/email headerregistry email headerregistry AddressHeader addresses}@anchor{3b4e}
@deffn {の属性} addresses

ヘッダー値に含まれる全ての個別アドレスをエンコードした @ref{3b4f,,Address} オブジェクトのタプルです。 ヘッダ値にグループが含まれている場合、そのグループに含まれる個々のアドレスは、ヘッダ値でグループが出現した時点でリストに含まれます (つまり、アドレスのリストは一次元のリストに「フラット化」されます)。
@end deffn

The @code{decoded} value of the header will have all encoded words decoded to
unicode.  @ref{56,,idna} encoded domain names are also decoded to
unicode.  The @code{decoded} value is set by @ref{2655,,joining} the
@ref{169,,str} value of the elements of the @code{groups} attribute with @code{',
'}.

A list of @ref{3b4f,,Address} and @ref{3b4c,,Group} objects in any combination
may be used to set the value of an address header.  @code{Group} objects whose
@code{display_name} is @code{None} will be interpreted as single addresses, which
allows an address list to be copied with groups intact by using the list
obtained from the @code{groups} attribute of the source header.
@end deffn

@geindex SingleAddressHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry SingleAddressHeader}@anchor{3b50}
@deffn {クラス} email.headerregistry.SingleAddressHeader

追加の属性を 1 つ持つ、@ref{3b4a,,AddressHeader} の派生クラスです:

@geindex address (email.headerregistry.SingleAddressHeader の属性)
@anchor{library/email headerregistry email headerregistry SingleAddressHeader address}@anchor{3b51}
@deffn {の属性} address

The single address encoded by the header value.  If the header value
actually contains more than one address (which would be a violation of
the RFC under the default @ref{53,,policy}), accessing this attribute
will result in a @ref{2ec,,ValueError}.
@end deffn
@end deffn

Many of the above classes also have a @code{Unique} variant (for example,
@code{UniqueUnstructuredHeader}).  The only difference is that in the @code{Unique}
variant, @ref{3b1f,,max_count} is set to 1.

@geindex MIMEVersionHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader}@anchor{3b52}
@deffn {クラス} email.headerregistry.MIMEVersionHeader

There is really only one valid value for the @code{MIME-Version}
header, and that is @code{1.0}.  For future proofing, this header class
supports other valid version numbers.  If a version number has a valid value
per 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html}, then the header object will have non-@code{None} values for
the following attributes:

@geindex version (email.headerregistry.MIMEVersionHeader の属性)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader version}@anchor{3b53}
@deffn {の属性} version

バージョン番号 (文字列)、空白やコメントは除かれます。
@end deffn

@geindex major (email.headerregistry.MIMEVersionHeader の属性)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader major}@anchor{3b54}
@deffn {の属性} major

メジャーバージョン番号 (整数)
@end deffn

@geindex minor (email.headerregistry.MIMEVersionHeader の属性)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader minor}@anchor{3b55}
@deffn {の属性} minor

マイナーバージョン番号 (整数)
@end deffn
@end deffn

@geindex ParameterizedMIMEHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry ParameterizedMIMEHeader}@anchor{3b56}
@deffn {クラス} email.headerregistry.ParameterizedMIMEHeader

MIME headers all start with the prefix 'Content-'.  Each specific header has
a certain value, described under the class for that header.  Some can
also take a list of supplemental parameters, which have a common format.
This class serves as a base for all the MIME headers that take parameters.

@geindex params (email.headerregistry.ParameterizedMIMEHeader の属性)
@anchor{library/email headerregistry email headerregistry ParameterizedMIMEHeader params}@anchor{3ad4}
@deffn {の属性} params

A dictionary mapping parameter names to parameter values.
@end deffn
@end deffn

@geindex ContentTypeHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader}@anchor{3b57}
@deffn {クラス} email.headerregistry.ContentTypeHeader

@code{Content-Type} ヘッダを扱う @ref{3b56,,ParameterizedMIMEHeader} クラスです。

@geindex content_type (email.headerregistry.ContentTypeHeader の属性)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader content_type}@anchor{3b58}
@deffn {の属性} content_type

The content type string, in the form @code{maintype/subtype}.
@end deffn

@geindex maintype (email.headerregistry.ContentTypeHeader の属性)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader maintype}@anchor{3b59}
@deffn {の属性} maintype
@end deffn

@geindex subtype (email.headerregistry.ContentTypeHeader の属性)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader subtype}@anchor{3b5a}
@deffn {の属性} subtype
@end deffn
@end deffn

@geindex ContentDispositionHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry ContentDispositionHeader}@anchor{3b5b}
@deffn {クラス} email.headerregistry.ContentDispositionHeader

@code{Content-Disposition} ヘッダを扱う @ref{3b56,,ParameterizedMIMEHeader} クラスです。

@geindex content_disposition (email.headerregistry.ContentDispositionHeader の属性)
@anchor{library/email headerregistry email headerregistry ContentDispositionHeader content_disposition}@anchor{3b5c}
@deffn {の属性} content_disposition

@code{inline} and @code{attachment} are the only valid values in common use.
@end deffn
@end deffn

@geindex ContentTransferEncodingHeader (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry ContentTransferEncodingHeader}@anchor{3b5d}
@deffn {クラス} email.headerregistry.ContentTransferEncodingHeader

@code{Content-Transfer-Encoding} ヘッダを扱います。

@geindex cte (email.headerregistry.ContentTransferEncodingHeader の属性)
@anchor{library/email headerregistry email headerregistry ContentTransferEncodingHeader cte}@anchor{3b5e}
@deffn {の属性} cte

有効な値は @code{7bit}、@code{8bit}、@code{base64}、@code{quoted-printable} です。詳細については 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} を参照してください。
@end deffn
@end deffn

@geindex HeaderRegistry (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry HeaderRegistry}@anchor{3b43}
@deffn {クラス} email.headerregistry.HeaderRegistry (base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True)

This is the factory used by @ref{12cb,,EmailPolicy} by default.
@code{HeaderRegistry} builds the class used to create a header instance
dynamically, using `base_class' and a specialized class retrieved from a
registry that it holds.  When a given header name does not appear in the
registry, the class specified by `default_class' is used as the specialized
class.  When `use_default_map' is @code{True} (the default), the standard
mapping of header names to classes is copied in to the registry during
initialization.  `base_class' is always the last class in the generated
class's @ref{16c5,,__bases__} list.

デフォルトのマッピング:

@quotation

@*subject: 
UniqueUnstructuredHeader


@*date: 
UniqueDateHeader


@*resent-date: 
DateHeader


@*orig-date: 
UniqueDateHeader


@*sender: 
UniqueSingleAddressHeader


@*resent-sender: 
SingleAddressHeader


@*to: 
UniqueAddressHeader


@*resent-to: 
AddressHeader


@*cc: 
UniqueAddressHeader


@*resent-cc: 
AddressHeader


@*bcc: 
UniqueAddressHeader


@*resent-bcc: 
AddressHeader


@*from: 
UniqueAddressHeader


@*resent-from: 
AddressHeader


@*reply-to: 
UniqueAddressHeader


@*mime-version: 
MIMEVersionHeader


@*content-type: 
ContentTypeHeader


@*content-disposition: 
ContentDispositionHeader


@*content-transfer-encoding: 
ContentTransferEncodingHeader


@*message-id: 
MessageIDHeader

@end quotation

@code{HeaderRegistry} には以下のメソッドがあります:

@geindex map_to_type() (email.headerregistry.HeaderRegistry のメソッド)
@anchor{library/email headerregistry email headerregistry HeaderRegistry map_to_type}@anchor{3b5f}
@deffn {メソッド} map_to_type (self, name, cls)

`name' is the name of the header to be mapped.  It will be converted to
lower case in the registry.  `cls' is the specialized class to be used,
along with `base_class', to create the class used to instantiate headers
that match `name'.
@end deffn

@geindex __getitem__() (email.headerregistry.HeaderRegistry のメソッド)
@anchor{library/email headerregistry email headerregistry HeaderRegistry __getitem__}@anchor{3b60}
@deffn {メソッド} __getitem__ (name)

Construct and return a class to handle creating a `name' header.
@end deffn

@geindex __call__() (email.headerregistry.HeaderRegistry のメソッド)
@anchor{library/email headerregistry email headerregistry HeaderRegistry __call__}@anchor{3b61}
@deffn {メソッド} __call__ (name, value)

Retrieves the specialized header associated with `name' from the
registry (using `default_class' if `name' does not appear in the
registry) and composes it with `base_class' to produce a class,
calls the constructed class's constructor, passing it the same
argument list, and finally returns the class instance created thereby.
@end deffn
@end deffn

The following classes are the classes used to represent data parsed from
structured headers and can, in general, be used by an application program to
construct structured values to assign to specific headers.

@geindex Address (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry Address}@anchor{3b4f}
@deffn {クラス} email.headerregistry.Address (display_name='@w{'}, username='@w{'}, domain='@w{'}, addr_spec=None)

このクラスは電子メールのアドレスを表すのに使われます。アドレスの一般的な形式は:

@example
[display_name] <username@@domain>
@end example

もしくは:

@example
username@@domain
@end example

where each part must conform to specific syntax rules spelled out in
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}.

As a convenience `addr_spec' can be specified instead of `username' and
`domain', in which case `username' and `domain' will be parsed from the
`addr_spec'.  An `addr_spec' must be a properly RFC quoted string; if it is
not @code{Address} will raise an error.  Unicode characters are allowed and
will be property encoded when serialized.  However, per the RFCs, unicode is
`not' allowed in the username portion of the address.

@geindex display_name (email.headerregistry.Address の属性)
@anchor{library/email headerregistry email headerregistry Address display_name}@anchor{3b62}
@deffn {の属性} display_name

The display name portion of the address, if any, with all quoting
removed.  If the address does not have a display name, this attribute
will be an empty string.
@end deffn

@geindex username (email.headerregistry.Address の属性)
@anchor{library/email headerregistry email headerregistry Address username}@anchor{3b63}
@deffn {の属性} username

アドレスの @code{username} 部分、クォートは取り除かれます。
@end deffn

@geindex domain (email.headerregistry.Address の属性)
@anchor{library/email headerregistry email headerregistry Address domain}@anchor{3b64}
@deffn {の属性} domain

アドレスの @code{domain} 部分。
@end deffn

@geindex addr_spec (email.headerregistry.Address の属性)
@anchor{library/email headerregistry email headerregistry Address addr_spec}@anchor{3b65}
@deffn {の属性} addr_spec

The @code{username@@domain} portion of the address, correctly quoted
for use as a bare address (the second form shown above).  This
attribute is not mutable.
@end deffn

@geindex __str__() (email.headerregistry.Address のメソッド)
@anchor{library/email headerregistry email headerregistry Address __str__}@anchor{3b66}
@deffn {メソッド} __str__ ()

The @code{str} value of the object is the address quoted according to
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} rules, but with no Content Transfer Encoding of any non-ASCII
characters.
@end deffn

To support SMTP (
@geindex RFC; RFC 5321
RFC 5321@footnote{https://datatracker.ietf.org/doc/html/rfc5321.html}), @code{Address} handles one special case: if
@code{username} and @code{domain} are both the empty string (or @code{None}), then
the string value of the @code{Address} is @code{<>}.
@end deffn

@geindex Group (email.headerregistry のクラス)
@anchor{library/email headerregistry email headerregistry Group}@anchor{3b4c}
@deffn {クラス} email.headerregistry.Group (display_name=None, addresses=None)

このクラスはアドレスグループを表すのに使われます。アドレスグループの一般的な形式は:

@example
display_name: [address-list];
@end example

As a convenience for processing lists of addresses that consist of a mixture
of groups and single addresses, a @code{Group} may also be used to represent
single addresses that are not part of a group by setting `display_name' to
@code{None} and providing a list of the single address as `addresses'.

@geindex display_name (email.headerregistry.Group の属性)
@anchor{library/email headerregistry email headerregistry Group display_name}@anchor{3b4d}
@deffn {の属性} display_name

The @code{display_name} of the group.  If it is @code{None} and there is
exactly one @code{Address} in @code{addresses}, then the @code{Group} represents a
single address that is not in a group.
@end deffn

@geindex addresses (email.headerregistry.Group の属性)
@anchor{library/email headerregistry email headerregistry Group addresses}@anchor{3b67}
@deffn {の属性} addresses

A possibly empty tuple of @ref{3b4f,,Address} objects representing the
addresses in the group.
@end deffn

@geindex __str__() (email.headerregistry.Group のメソッド)
@anchor{library/email headerregistry email headerregistry Group __str__}@anchor{3b68}
@deffn {メソッド} __str__ ()

The @code{str} value of a @code{Group} is formatted according to 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html},
but with no Content Transfer Encoding of any non-ASCII characters.  If
@code{display_name} is none and there is a single @code{Address} in the
@code{addresses} list, the @code{str} value will be the same as the @code{str} of
that single @code{Address}.
@end deffn
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email contentmanager Managing MIME Content,email 使用例,email headerregistry Custom Header Objects,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email contentmanager doc}@anchor{3b69}@anchor{library/email contentmanager email-contentmanager-managing-mime-content}@anchor{3b6a}@anchor{library/email contentmanager module-email contentmanager}@anchor{41}@anchor{library/email contentmanager translation-repo}@anchor{3b6b}
@subsubsection @code{email.contentmanager}: Managing MIME Content


@geindex module; email.contentmanager

`ソースコード:' Lib/email/contentmanager.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/contentmanager.py}


__________________________________________________________________



Added in version 3.6: @footnote{
Originally added in 3.4 as a @ref{1243,,provisional module}
}


@geindex ContentManager (email.contentmanager のクラス)
@anchor{library/email contentmanager email contentmanager ContentManager}@anchor{3b6c}
@deffn {クラス} email.contentmanager.ContentManager

Base class for content managers.  Provides the standard registry mechanisms
to register converters between MIME content and other representations, as
well as the @code{get_content} and @code{set_content} dispatch methods.

@geindex get_content() (email.contentmanager.ContentManager のメソッド)
@anchor{library/email contentmanager email contentmanager ContentManager get_content}@anchor{3ae5}
@deffn {メソッド} get_content (msg, *args, **kw)

Look up a handler function based on the @code{mimetype} of `msg' (see next
paragraph), call it, passing through all arguments, and return the result
of the call.  The expectation is that the handler will extract the
payload from `msg' and return an object that encodes information about
the extracted data.

To find the handler, look for the following keys in the registry,
stopping with the first one found:


@itemize *

@item 
完全な MIME 型を表す文字列 (@code{maintype/subtype})

@item 
@code{maintype} を表す文字列

@item 
空の文字列
@end itemize

If none of these keys produce a handler, raise a @ref{5e7,,KeyError} for the
full MIME type.
@end deffn

@geindex set_content() (email.contentmanager.ContentManager のメソッド)
@anchor{library/email contentmanager email contentmanager ContentManager set_content}@anchor{3ae6}
@deffn {メソッド} set_content (msg, obj, *args, **kw)

If the @code{maintype} is @code{multipart}, raise a @ref{198,,TypeError}; otherwise
look up a handler function based on the type of `obj' (see next
paragraph), call @ref{3aef,,clear_content()} on the
`msg', and call the handler function, passing through all arguments.  The
expectation is that the handler will transform and store `obj' into
`msg', possibly making other changes to `msg' as well, such as adding
various MIME headers to encode information needed to interpret the stored
data.

To find the handler, obtain the type of `obj' (@code{typ = type(obj)}), and
look for the following keys in the registry, stopping with the first one
found:


@itemize *

@item 
型自身 (@code{typ})

@item 
型の完全修飾名 (@code{typ.__module__ + '.' + typ.__qualname__}).

@item 
the type's @ref{2373,,qualname} (@code{typ.__qualname__})

@item 
the type's @ref{16c4,,name} (@code{typ.__name__}).
@end itemize

If none of the above match, repeat all of the checks above for each of
the types in the @ref{18dd,,MRO} (@ref{2378,,typ.__mro__}).
Finally, if no other key
yields a handler, check for a handler for the key @code{None}.  If there is
no handler for @code{None}, raise a @ref{5e7,,KeyError} for the fully
qualified name of the type.

Also add a @code{MIME-Version} header if one is not present (see
also @ref{113d,,MIMEPart}).
@end deffn

@geindex add_get_handler() (email.contentmanager.ContentManager のメソッド)
@anchor{library/email contentmanager email contentmanager ContentManager add_get_handler}@anchor{3b6d}
@deffn {メソッド} add_get_handler (key, handler)

Record the function `handler' as the handler for `key'.  For the possible
values of `key', see @ref{3b6e,,get_content()}.
@end deffn

@geindex add_set_handler() (email.contentmanager.ContentManager のメソッド)
@anchor{library/email contentmanager email contentmanager ContentManager add_set_handler}@anchor{3b6f}
@deffn {メソッド} add_set_handler (typekey, handler)

Record `handler' as the function to call when an object of a type
matching `typekey' is passed to @ref{3b70,,set_content()}.  For the possible
values of `typekey', see @ref{3b70,,set_content()}.
@end deffn
@end deffn

@menu
* Content Manager Instances:: 

@end menu

@node Content Manager Instances,,,email contentmanager Managing MIME Content
@anchor{library/email contentmanager content-manager-instances}@anchor{3b71}
@subsubsection Content Manager Instances


Currently the email package provides only one concrete content manager,
@ref{3b1d,,raw_data_manager}, although more may be added in the future.
@ref{3b1d,,raw_data_manager} is the
@ref{113c,,content_manager} provided by
@ref{12cb,,EmailPolicy} and its derivatives.

@geindex raw_data_manager (email.contentmanager モジュール)
@anchor{library/email contentmanager email contentmanager raw_data_manager}@anchor{3b1d}
@deffn {データ} email.contentmanager.raw_data_manager

This content manager provides only a minimum interface beyond that provided
by @ref{581,,Message} itself:  it deals only with text, raw
byte strings, and @ref{581,,Message} objects.  Nevertheless, it
provides significant advantages compared to the base API: @code{get_content} on
a text part will return a unicode string without the application needing to
manually decode it, @code{set_content} provides a rich set of options for
controlling the headers added to a part and controlling the content transfer
encoding, and it enables the use of the various @code{add_} methods, thereby
simplifying the creation of multipart messages.

@geindex get_content() (email.contentmanager モジュール)
@anchor{library/email contentmanager email contentmanager get_content}@anchor{3b6e}
@deffn {メソッド} email.contentmanager.get_content (msg, errors='replace')

Return the payload of the part as either a string (for @code{text} parts), an
@ref{580,,EmailMessage} object (for @code{message/rfc822}
parts), or a @code{bytes} object (for all other non-multipart types).  Raise
a @ref{5e7,,KeyError} if called on a @code{multipart}.  If the part is a
@code{text} part and `errors' is specified, use it as the error handler when
decoding the payload to unicode.  The default error handler is
@code{replace}.
@end deffn

@geindex set_content() (email.contentmanager モジュール)
@anchor{library/email contentmanager email contentmanager set_content}@anchor{3b70}
@deffn {メソッド} email.contentmanager.set_content (msg, <'str'>, subtype="plain", charset='utf-8', cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)

@deffnx {メソッド} email.contentmanager.set_content (msg, <'bytes'>, maintype, subtype, cte="base64", disposition=None, filename=None, cid=None, params=None, headers=None)

@deffnx {メソッド} email.contentmanager.set_content (msg, <'EmailMessage'>, cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)

Add headers and payload to `msg':

Add a @code{Content-Type} header with a @code{maintype/subtype}
value.


@itemize *

@item 
For @code{str}, set the MIME @code{maintype} to @code{text}, and set the
subtype to `subtype' if it is specified, or @code{plain} if it is not.

@item 
For @code{bytes}, use the specified `maintype' and `subtype', or
raise a @ref{198,,TypeError} if they are not specified.

@item 
For @ref{580,,EmailMessage} objects, set the maintype
to @code{message}, and set the subtype to `subtype' if it is
specified or @code{rfc822} if it is not.  If `subtype' is
@code{partial}, raise an error (@code{bytes} objects must be used to
construct @code{message/partial} parts).
@end itemize

If `charset' is provided (which is valid only for @code{str}), encode the
string to bytes using the specified character set.  The default is
@code{utf-8}.  If the specified `charset' is a known alias for a standard
MIME charset name, use the standard charset instead.

If `cte' is set, encode the payload using the specified content transfer
encoding, and set the @code{Content-Transfer-Encoding} header to
that value.  Possible values for `cte' are @code{quoted-printable},
@code{base64}, @code{7bit}, @code{8bit}, and @code{binary}.  If the input cannot be
encoded in the specified encoding (for example, specifying a `cte' of
@code{7bit} for an input that contains non-ASCII values), raise a
@ref{2ec,,ValueError}.


@itemize *

@item 
For @code{str} objects, if `cte' is not set use heuristics to
determine the most compact encoding.  Prior to encoding,
@ref{146e,,str.splitlines()} is used to normalize all line boundaries,
ensuring that each line of the payload is terminated by the
current policy's @ref{3b10,,linesep} property
(even if the original string did not end with one).

@item 
For @code{bytes} objects, `cte' is taken to be base64 if not set,
and the aforementioned newline translation is not performed.

@item 
For @ref{580,,EmailMessage}, per 
@geindex RFC; RFC 2046
RFC 2046@footnote{https://datatracker.ietf.org/doc/html/rfc2046.html}, raise
an error if a `cte' of @code{quoted-printable} or @code{base64} is
requested for `subtype' @code{rfc822}, and for any `cte' other than
@code{7bit} for `subtype' @code{external-body}.  For
@code{message/rfc822}, use @code{8bit} if `cte' is not specified.  For
all other values of `subtype', use @code{7bit}.
@end itemize

@cartouche
@quotation 注釈 
A `cte' of @code{binary} does not actually work correctly yet.
The @code{EmailMessage} object as modified by @code{set_content} is
correct, but @ref{13e7,,BytesGenerator} does not
serialize it correctly.
@end quotation
@end cartouche

If `disposition' is set, use it as the value of the
@code{Content-Disposition} header.  If not specified, and
`filename' is specified, add the header with the value @code{attachment}.
If `disposition' is not specified and `filename' is also not specified,
do not add the header.  The only valid values for `disposition' are
@code{attachment} and @code{inline}.

If `filename' is specified, use it as the value of the @code{filename}
parameter of the @code{Content-Disposition} header.

If `cid' is specified, add a @code{Content-ID} header with
`cid' as its value.

If `params' is specified, iterate its @code{items} method and use the
resulting @code{(key, value)} pairs to set additional parameters on the
@code{Content-Type} header.

If `headers' is specified and is a list of strings of the form
@code{headername: headervalue} or a list of @code{header} objects
(distinguished from strings by having a @code{name} attribute), add the
headers to `msg'.
@end deffn
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email 使用例,email message Message compat32 API を使用した電子メールメッセージの表現,email contentmanager Managing MIME Content,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email examples doc}@anchor{3b72}@anchor{library/email examples email-examples}@anchor{113e}@anchor{library/email examples id1}@anchor{3b73}@anchor{library/email examples translation-repo}@anchor{3b74}
@subsubsection @code{email}: 使用例


ここでは @ref{3f,,email} パッケージを使って電子メールメッセージを読む・書く・送信するいくつかの例を紹介します。より複雑な MIME メッセージについても扱います。

最初に、シンプルなテキストメッセージ (テキストコンテンツとアドレスの両方がユニコード文字を含み得る) を作成・送信する方法を見てみましょう:

@example
# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = f'The contents of @{textfile@}'
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
@end example

@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html} ヘッダーの解析は、 @ref{52,,parser} モジュールにあるクラスを使用することにより、簡単に実現できます:

@example
# Import the email modules we'll need
#from email.parser import BytesParser
from email.parser import Parser
from email.policy import default

# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
#     headers = BytesParser(policy=default).parse(fp)

#  Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
        'From: Foo Bar <user@@example.com>\n'
        'To: <someone_else@@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Now the header items can be accessed as a dictionary:
print('To: @{@}'.format(headers['to']))
print('From: @{@}'.format(headers['from']))
print('Subject: @{@}'.format(headers['subject']))

# You can also access the parts of the addresses:
print('Recipient username: @{@}'.format(headers['to'].addresses[0].username))
print('Sender name: @{@}'.format(headers['from'].addresses[0].display_name))
@end example

つぎに、あるディレクトリ内にある何枚かの家族写真をひとつの MIME メッセージに収めて送信する例です:

@example
# Import smtplib for the actual sending function.
import smtplib

# 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.  You can also omit the subtype
# if you want MIMEImage to guess it.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype='png')

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
@end example

つぎはあるディレクトリに含まれている内容全体をひとつの電子メールメッセージとして送信するやり方です: @footnote{
最初の思いつきと用例は Matthew Dixon Cowles のおかげです。
}

@example
#!/usr/bin/env python3

"""Send the contents of a directory as a MIME message."""

import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP


def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = f'Contents of directory @{os.path.abspath(directory)@}'
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_file_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)


if __name__ == '__main__':
    main()
@end example

つぎに、上のような MIME メッセージをどうやって展開してひとつのディレクトリ上の複数ファイルにするかを示します:

@example
#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import email
import mimetypes

from email.policy import default

from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile, 'rb') as fp:
        msg = email.message_from_binary_file(fp, policy=default)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = f'part-@{counter:03d@}@{ext@}'
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))


if __name__ == '__main__':
    main()
@end example

代替のプレーンテキストバージョン付きの HTML メッセージを作成する方法の例です。もう少し面白くするために、 HTML 部分に関連する画像を追加し、さらに送信だけでなく、送信しようとしているもののコピーをディスクにも保存してみます。

@example
#!/usr/bin/env python3

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Pourquoi pas des asperges pour ce midi ?"
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!

Cette recette [1] sera sûrement un très bon repas.

[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>Cette
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
            recette
        </a> sera sûrement un très bon repas.
    </p>
    <img src="cid:@{asparagus_cid@}">
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
@end example

前の例のメッセージが送信されてきたら、これを処理する方法の一つは次のようなものです:

@example
import os
import sys
import tempfile
import mimetypes
import webbrowser

# Import the email modules we'll need
from email import policy
from email.parser import BytesParser


def magic_html_parser(html_text, partfiles):
    """Return safety-sanitized html linked to partfiles.

    Rewrite the href="cid:...." attributes to point to the filenames in partfiles.
    Though not trivial, this should be possible using html.parser.
    """
    raise NotImplementedError("Add the magic needed")


# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
    msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])

# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines.  Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print('@w{'}.join(simplest.get_content().splitlines(keepends=True)[:3]))

ans = input("View full message?")
if ans.lower()[0] == 'n':
    sys.exit()

# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = @{@}
if richest['content-type'].maintype == 'text':
    if richest['content-type'].subtype == 'plain':
        for line in richest.get_content().splitlines():
            print(line)
        sys.exit()
    elif richest['content-type'].subtype == 'html':
        body = richest
    else:
        print("Don't know how to display @{@}".format(richest.get_content_type()))
        sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
    body = richest.get_body(preferencelist=('html'))
    for part in richest.iter_attachments():
        fn = part.get_filename()
        if fn:
            extension = os.path.splitext(part.get_filename())[1]
        else:
            extension = mimetypes.guess_extension(part.get_content_type())
        with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
            f.write(part.get_content())
            # again strip the <> to go from email form of cid to html form.
            partfiles[part['content-id'][1:-1]] = f.name
else:
    print("Don't know how to display @{@}".format(richest.get_content_type()))
    sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
    os.remove(fn)

# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.
@end example

プロンプトまでの、上記のプログラムの出力はこうなります:

@example
To: Penelope Pussycat <penelope@@example.com>, Fabrette Pussycat <fabrette@@example.com>
From: Pepé Le Pew <pepe@@example.com>
Subject: Pourquoi pas des asperges pour ce midi ?

Salut!

Cette recette [1] sera sûrement un très bon repas.
@end example

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

レガシーAPI:

@node email message Message compat32 API を使用した電子メールメッセージの表現,email mime Creating email and MIME objects from scratch,email 使用例,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email compat32-message doc}@anchor{3b75}@anchor{library/email compat32-message compat32-message}@anchor{3ab7}@anchor{library/email compat32-message email-message-message-representing-an-email-message-using-the-compat32-api}@anchor{3b76}@anchor{library/email compat32-message translation-repo}@anchor{3b77}
@subsubsection @code{email.message.Message}: @code{compat32} API を使用した電子メールメッセージの表現


The @ref{581,,Message} class is very similar to the
@ref{580,,EmailMessage} class, without the methods added by that
class, and with the default behavior of certain other methods being slightly
different.  We also document here some methods that, while supported by the
@ref{580,,EmailMessage} class, are not recommended unless you are
dealing with legacy code.

The philosophy and structure of the two classes is otherwise the same.

This document describes the behavior under the default (for @ref{581,,Message})
policy @ref{12c8,,Compat32}.  If you are going to use another policy,
you should be using the @ref{580,,EmailMessage} class instead.

An email message consists of `headers' and a `payload'.  Headers must be
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} style names and values, where the field name and value are
separated by a colon.  The colon is not part of either the field name or the
field value.  The payload may be a simple text message, or a binary object, or
a structured sequence of sub-messages each with their own set of headers and
their own payload.  The latter type of payload is indicated by the message
having a MIME type such as @code{multipart/*} or
@code{message/rfc822}.

The conceptual model provided by a @ref{581,,Message} object is that of an
ordered dictionary of headers with additional methods for accessing both
specialized information from the headers, for accessing the payload, for
generating a serialized version of the message, and for recursively walking
over the object tree.  Note that duplicate headers are supported but special
methods must be used to access them.

The @ref{581,,Message} pseudo-dictionary is indexed by the header names, which
must be ASCII values.  The values of the dictionary are strings that are
supposed to contain only ASCII characters; there is some special handling for
non-ASCII input, but it doesn't always produce the correct results.  Headers
are stored and returned in case-preserving form, but field names are matched
case-insensitively.  There may also be a single envelope header, also known as
the `Unix-From' header or the @code{From_} header.  The `payload' is either a
string or bytes, in the case of simple message objects, or a list of
@ref{581,,Message} objects, for MIME container documents (e.g.
@code{multipart/*} and @code{message/rfc822}).

@ref{581,,Message} クラスのメソッドは以下のとおりです:

@geindex Message (email.message のクラス)
@anchor{library/email compat32-message email message Message}@anchor{581}
@deffn {クラス} email.message.Message (policy=compat32)

If `policy' is specified (it must be an instance of a @ref{53,,policy}
class) use the rules it specifies to update and serialize the representation
of the message.  If `policy' is not set, use the @ref{12c8,,compat32} policy, which maintains backward compatibility with
the Python 3.2 version of the email package.  For more information see the
@ref{53,,policy} documentation.


バージョン 3.3 で変更: キーワード引数 `policy' が追加されました。


@geindex as_string() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message as_string}@anchor{1138}
@deffn {メソッド} as_string (unixfrom=False, maxheaderlen=0, policy=None)

Return the entire message flattened as a string.  When optional `unixfrom'
is true, the envelope header is included in the returned string.
`unixfrom' defaults to @code{False}.  For backward compatibility reasons,
`maxheaderlen' defaults to @code{0}, so if you want a different value you
must override it explicitly (the value specified for `max_line_length' in
the policy will be ignored by this method).  The `policy' argument may be
used to override the default policy obtained from the message instance.
This can be used to control some of the formatting produced by the
method, since the specified `policy' will be passed to the @code{Generator}.

もし、文字列への変換を完全に行うためにデフォルト値を埋める必要がある場合、メッセージのフラット化は @ref{581,,Message} の変更を引き起こす可能性があります (例えば、MIME の境界が生成される、変更される等)。

Note that this method is provided as a convenience and may not always
format the message the way you want.  For example, by default it does
not do the mangling of lines that begin with @code{From} that is
required by the Unix mbox format.  For more flexibility, instantiate a
@ref{13e6,,Generator} instance and use its
@ref{3b0a,,flatten()} method directly.  For example:

@example
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
@end example

If the message object contains binary data that is not encoded according
to RFC standards, the non-compliant data will be replaced by unicode
"unknown character" code points.  (See also @ref{1139,,as_bytes()} and
@ref{13e7,,BytesGenerator}.)


バージョン 3.4 で変更: `policy' キーワード引数が追加されました。

@end deffn

@geindex __str__() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message __str__}@anchor{3b78}
@deffn {メソッド} __str__ ()

Equivalent to @ref{1138,,as_string()}.  Allows @code{str(msg)} to produce a
string containing the formatted message.
@end deffn

@geindex as_bytes() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message as_bytes}@anchor{1139}
@deffn {メソッド} as_bytes (unixfrom=False, policy=None)

Return the entire message flattened as a bytes object.  When optional
`unixfrom' is true, the envelope header is included in the returned
string.  `unixfrom' defaults to @code{False}.  The `policy' argument may be
used to override the default policy obtained from the message instance.
This can be used to control some of the formatting produced by the
method, since the specified `policy' will be passed to the
@code{BytesGenerator}.

もし、文字列への変換を完全に行うためにデフォルト値を埋める必要がある場合、メッセージのフラット化は @ref{581,,Message} の変更を引き起こす可能性があります (例えば、MIME の境界が生成される、変更される等)。

Note that this method is provided as a convenience and may not always
format the message the way you want.  For example, by default it does
not do the mangling of lines that begin with @code{From} that is
required by the Unix mbox format.  For more flexibility, instantiate a
@ref{13e7,,BytesGenerator} instance and use its
@ref{3b06,,flatten()} method directly.
For example:

@example
from io import BytesIO
from email.generator import BytesGenerator
fp = BytesIO()
g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
@end example


Added in version 3.4.

@end deffn

@geindex __bytes__() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message __bytes__}@anchor{113a}
@deffn {メソッド} __bytes__ ()

Equivalent to @ref{1139,,as_bytes()}.  Allows @code{bytes(msg)} to produce a
bytes object containing the formatted message.


Added in version 3.4.

@end deffn

@geindex is_multipart() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message is_multipart}@anchor{3ade}
@deffn {メソッド} is_multipart ()

Return @code{True} if the message's payload is a list of
sub-@ref{581,,Message} objects, otherwise return @code{False}.  When
@ref{3ade,,is_multipart()} returns @code{False}, the payload should be a string
object (which might be a CTE encoded binary payload).  (Note that
@ref{3ade,,is_multipart()} returning @code{True} does not necessarily mean that
"msg.get_content_maintype() == 'multipart'" will return the @code{True}.
For example, @code{is_multipart} will return @code{True} when the
@ref{581,,Message} is of type @code{message/rfc822}.)
@end deffn

@geindex set_unixfrom() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message set_unixfrom}@anchor{3b79}
@deffn {メソッド} set_unixfrom (unixfrom)

メッセージのエンベロープヘッダを `unixfrom' に設定します。これは文字列でなければなりません。
@end deffn

@geindex get_unixfrom() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_unixfrom}@anchor{3b7a}
@deffn {メソッド} get_unixfrom ()

メッセージのエンベロープヘッダを返します。エンベロープヘッダが設定されていない場合は @code{None} が返されます。
@end deffn

@geindex attach() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message attach}@anchor{3aeb}
@deffn {メソッド} attach (payload)

与えられた `payload' を現在のペイロードに追加します。この時点でのペイロードは @code{None} か、あるいは @ref{581,,Message} オブジェクトのリストである必要があります。このメソッドの実行後、ペイロードは必ず @ref{581,,Message} オブジェクトのリストになります。ペイロードにスカラーオブジェクト (文字列など) を格納したい場合は、かわりに @ref{3b7b,,set_payload()} を使ってください。

This is a legacy method.  On the
@ref{580,,EmailMessage} class its functionality is
replaced by @ref{1c5d,,set_content()} and the
related @code{make} and @code{add} methods.
@end deffn

@geindex get_payload() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_payload}@anchor{13e5}
@deffn {メソッド} get_payload (i=None, decode=False)

現在のペイロードへの参照を返します。これは @ref{3ade,,is_multipart()} が @code{True} の場合 @ref{581,,Message} オブジェクトのリストになり、 @ref{3ade,,is_multipart()} が @code{False} の場合は文字列になります。ペイロードがリストの場合、リストを変更することはそのメッセージのペイロードを変更することになります。

オプション引数の `i' がある場合、 @ref{3ade,,is_multipart()} が @code{True} ならば @ref{13e5,,get_payload()} はペイロード中で 0 から数えて `i' 番目の要素を返します。 `i' が 0 より小さい場合、あるいはペイロードの個数以上の場合は @ref{174e,,IndexError} が発生します。ペイロードが文字列 (つまり @ref{3ade,,is_multipart()} が @code{False}) にもかかわらず `i' が与えられたときは @ref{198,,TypeError} が発生します。

Optional `decode' is a flag indicating whether the payload should be
decoded or not, according to the @code{Content-Transfer-Encoding}
header. When @code{True} and the message is not a multipart, the payload will
be decoded if this header's value is @code{quoted-printable} or @code{base64}.
If some other encoding is used, or @code{Content-Transfer-Encoding}
header is missing, the payload is
returned as-is (undecoded).  In all cases the returned value is binary
data.  If the message is a multipart and the `decode' flag is @code{True},
then @code{None} is returned.  If the payload is base64 and it was not
perfectly formed (missing padding, characters outside the base64
alphabet), then an appropriate defect will be added to the message's
defect property (@ref{3b3c,,InvalidBase64PaddingDefect} or
@ref{3b3d,,InvalidBase64CharactersDefect}, respectively).

When `decode' is @code{False} (the default) the body is returned as a string
without decoding the @code{Content-Transfer-Encoding}.  However,
for a @code{Content-Transfer-Encoding} of 8bit, an attempt is made
to decode the original bytes using the @code{charset} specified by the
@code{Content-Type} header, using the @code{replace} error handler.
If no @code{charset} is specified, or if the @code{charset} given is not
recognized by the email package, the body is decoded using the default
ASCII charset.

This is a legacy method.  On the
@ref{580,,EmailMessage} class its functionality is
replaced by @ref{3ae4,,get_content()} and
@ref{3ae3,,iter_parts()}.
@end deffn

@geindex set_payload() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message set_payload}@anchor{3b7b}
@deffn {メソッド} set_payload (payload, charset=None)

メッセージオブジェクト全体のペイロードを `payload' に設定します。クライアントはペイロードを変更してはいけません。オプションの `charset' はメッセージのデフォルト文字セットを設定します。詳しくは @ref{3b7c,,set_charset()} を参照してください。

This is a legacy method.  On the
@ref{580,,EmailMessage} class its functionality is
replaced by @ref{1c5d,,set_content()}.
@end deffn

@geindex set_charset() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message set_charset}@anchor{3b7c}
@deffn {メソッド} set_charset (charset)

ペイロードの文字セットを `charset' に変更します。これは @ref{ffb,,Charset} インスタンス (@ref{40,,email.charset} 参照)、文字セット名を表す文字列、あるいは @code{None} のいずれかです。文字列を指定した場合は @ref{ffb,,Charset} インスタンスに変換されます。 `charset' が @code{None} の場合、 @code{charset} 引数は @code{Content-Type} ヘッダから除去されます (それ以外にメッセージは変更されません)。これら以外のものを文字セットとして指定した場合、 @ref{198,,TypeError} を送出します。

@code{MIME-Version} ヘッダが存在しなければ、追加されます。 @code{Content-Type} ヘッダが存在しなければ、 @code{text/plain} を値として追加されます。 @code{Content-Type} が存在していてもいなくても、 @code{charset} パラメタは `charset.output_charset' に設定されます。 `charset.input_charset' と `charset.output_charset' が異なるなら、ペイロードは `output_charset' に再エンコードされます。 @code{Content-Transfer-Encoding} ヘッダが存在しなければ、ペイロードは、必要なら指定された @ref{ffb,,Charset} を使って transfer エンコードされ、適切な値のヘッダが追加されます。 @code{Content-Transfer-Encoding} ヘッダがすでに存在すれば、ペイロードはすでにその @code{Content-Transfer-Encoding} によって正しくエンコードされたものと見なされ、変形されません。

This is a legacy method.  On the
@ref{580,,EmailMessage} class its functionality is
replaced by the `charset' parameter of the
@ref{1c5d,,email.message.EmailMessage.set_content()} method.
@end deffn

@geindex get_charset() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_charset}@anchor{3b7d}
@deffn {メソッド} get_charset ()

そのメッセージ中のペイロードの @ref{ffb,,Charset} インスタンスを返します。

This is a legacy method.  On the
@ref{580,,EmailMessage} class it always returns
@code{None}.
@end deffn

以下のメソッドは、メッセージの 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} ヘッダにアクセスするためのマップ (辞書) 形式のインタフェイスを実装したものです。これらのメソッドと、通常のマップ (辞書) 型はまったく同じ意味をもつわけではないことに注意してください。たとえば辞書型では、同じキーが複数あることは許されていませんが、ここでは同じメッセージヘッダが複数ある場合があります。また、辞書型では @ref{3b7e,,keys()} で返されるキーの順序は保証されていませんが、 @ref{581,,Message} オブジェクト内のヘッダはつねに元のメッセージ中に現れた順序、あるいはそのあとに追加された順序で返されます。削除され、その後ふたたび追加されたヘッダはリストの一番最後に現れます。

こういった意味のちがいは意図的なもので、最大の利便性をもつようにつくられています。

注意: どんな場合も、メッセージ中のエンベロープヘッダはこのマップ形式のインタフェイスには含まれません。

In a model generated from bytes, any header values that (in contravention of
the RFCs) contain non-ASCII bytes will, when retrieved through this
interface, be represented as @ref{1c5e,,Header} objects with
a charset of @code{unknown-8bit}.

@geindex __len__() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message __len__}@anchor{3b7f}
@deffn {メソッド} __len__ ()

複製されたものもふくめてヘッダ数の合計を返します。
@end deffn

@geindex __contains__() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message __contains__}@anchor{1af4}
@deffn {メソッド} __contains__ (name)

メッセージオブジェクトが `name' という名前のフィールドを持っていれば @code{True} を返します。この検査では名前の大文字小文字は区別されません。`name' は最後にコロンをふくんでいてはいけません。このメソッドは以下のように @code{in} 演算子で使われます:

@example
if 'message-id' in myMessage:
   print('Message-ID:', myMessage['message-id'])
@end example
@end deffn

@geindex __getitem__() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message __getitem__}@anchor{3b80}
@deffn {メソッド} __getitem__ (name)

指定された名前のヘッダフィールドの値を返します。 `name' は最後にコロンをふくんでいてはいけません。そのヘッダがない場合は @code{None} が返され、 @ref{5e7,,KeyError} 例外は発生しません。

注意: 指定された名前のフィールドがメッセージのヘッダに2回以上現れている場合、どちらの値が返されるかは未定義です。ヘッダに存在するフィールドの値をすべて取り出したい場合は @ref{3b81,,get_all()} メソッドを使ってください。
@end deffn

@geindex __setitem__() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message __setitem__}@anchor{187d}
@deffn {メソッド} __setitem__ (name, val)

メッセージヘッダに `name' という名前の `val' という値をもつフィールドをあらたに追加します。このフィールドは現在メッセージに存在するフィールドのいちばん後に追加されます。

注意: このメソッドでは、すでに同一の名前で存在するフィールドは上書き `されません'。もしメッセージが名前 `name' をもつフィールドをひとつしか持たないようにしたければ、最初にそれを除去してください。たとえば:

@example
del msg['subject']
msg['subject'] = 'Python roolz!'
@end example
@end deffn

@geindex __delitem__() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message __delitem__}@anchor{3b82}
@deffn {メソッド} __delitem__ (name)

メッセージのヘッダから、`name' という名前をもつフィールドをすべて除去します。たとえこの名前をもつヘッダが存在していなくても例外は発生しません。
@end deffn

@geindex keys() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message keys}@anchor{3b7e}
@deffn {メソッド} keys ()

メッセージ中にあるすべてのヘッダのフィールド名のリストを返します。
@end deffn

@geindex values() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message values}@anchor{3b83}
@deffn {メソッド} values ()

メッセージ中にあるすべてのフィールドの値のリストを返します。
@end deffn

@geindex items() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message items}@anchor{3b84}
@deffn {メソッド} items ()

メッセージ中にあるすべてのヘッダのフィールド名とその値を 2-タプルのリストとして返します。
@end deffn

@geindex get() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get}@anchor{3b85}
@deffn {メソッド} get (name, failobj=None)

Return the value of the named header field.  This is identical to
@ref{588,,__getitem__()} except that optional `failobj' is returned if the
named header is missing (defaults to @code{None}).
@end deffn

さらに、役に立つメソッドをいくつか紹介します:

@geindex get_all() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_all}@anchor{3b81}
@deffn {メソッド} get_all (name, failobj=None)

`name' の名前をもつフィールドのすべての値からなるリストを返します。該当する名前のヘッダがメッセージ中に含まれていない場合は `failobj' (デフォルトでは @code{None}) が返されます。
@end deffn

@geindex add_header() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message add_header}@anchor{187e}
@deffn {メソッド} add_header (_name, _value, **_params)

拡張ヘッダ設定。このメソッドは @ref{187d,,__setitem__()} と似ていますが、追加のヘッダ・パラメータをキーワード引数で指定できるところが違っています。 `_name' に追加するヘッダフィールドを、 `_value' にそのヘッダの `最初の' 値を渡します。

キーワード引数辞書 `_params' の各項目ごとに、そのキーがパラメータ名として扱われ、キー名にふくまれるアンダースコアはハイフンに置換されます (アンダースコアは、Python 識別子としてハイフンを使えないための代替です)。ふつう、パラメータの値が @code{None} 以外のときは、 @code{key="value"} の形で追加されます。パラメータの値が @code{None} のときはキーのみが追加されます。値が非 ASCII 文字を含むなら、それは @code{(CHARSET, LANGUAGE, VALUE)} の形式の 3 タプルにすることが出来ます。ここで @code{CHARSET} はその値をエンコードするのに使われる文字セットを指示する文字列で、 @code{LANGUAGE} は通常 @code{None} か空文字列にでき (これら以外で指定出来るものについては 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} を参照してください)、 @code{VALUE} は非 ASCII コードポイントを含む文字列値です。この 3 タプルではなく非 ASCII 文字を含む値が渡された場合は、 @code{CHARSET} に @code{utf-8} 、 @code{LANGUAGE} に @code{None} を使って 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} 形式に自動的にエンコードされます。

以下はこの使用例です:

@example
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
@end example

こうするとヘッダには以下のように追加されます

@example
Content-Disposition: attachment; filename="bud.gif"
@end example

非 ASCII 文字を使った例:

@example
msg.add_header('Content-Disposition', 'attachment',
               filename=('iso-8859-1', '@w{'}, 'Fußballer.ppt'))
@end example

は、以下のようになります

@example
Content-Disposition: attachment; filename*="iso-8859-1'@w{'}Fu%DFballer.ppt"
@end example
@end deffn

@geindex replace_header() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message replace_header}@anchor{3b86}
@deffn {メソッド} replace_header (_name, _value)

ヘッダの置換。 `_name' と一致するヘッダで最初に見つかったものを置き換えます。このときヘッダの順序とフィールド名の大文字小文字は保存されます。一致するヘッダがない場合、 @ref{5e7,,KeyError} が発生します。
@end deffn

@geindex get_content_type() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_content_type}@anchor{3b87}
@deffn {メソッド} get_content_type ()

そのメッセージの content-type を返します。返された文字列は強制的に小文字で @code{maintype/subtype} の形式に変換されます。メッセージ中に @code{Content-Type} ヘッダがない場合、デフォルトの content-type は @ref{3b88,,get_default_type()} が返す値によって与えられます。 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} によればメッセージはつねにデフォルトの content-type をもっているので、 @ref{3b87,,get_content_type()} はつねになんらかの値を返すはずです。

@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} はメッセージのデフォルト content-type を、それが @code{multipart/digest} コンテナに現れているとき以外は @code{text/plain} に規定しています。あるメッセージが @code{multipart/digest} コンテナ中にある場合、その content-type は @code{message/rfc822} になります。もし @code{Content-Type} ヘッダが適切でない content-type 書式だった場合、 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} はそれのデフォルトを @code{text/plain} として扱うよう定めています。
@end deffn

@geindex get_content_maintype() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_content_maintype}@anchor{3b89}
@deffn {メソッド} get_content_maintype ()

そのメッセージの主 content-type を返します。これは @ref{3b87,,get_content_type()} によって返される文字列の @code{maintype} 部分です。
@end deffn

@geindex get_content_subtype() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_content_subtype}@anchor{3b8a}
@deffn {メソッド} get_content_subtype ()

そのメッセージの副 content-type (sub content-type、subtype) を返します。これは @ref{3b87,,get_content_type()} によって返される文字列の @code{subtype} 部分です。
@end deffn

@geindex get_default_type() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_default_type}@anchor{3b88}
@deffn {メソッド} get_default_type ()

デフォルトの content-type を返します。ほどんどのメッセージではデフォルトの content-type は @code{text/plain} ですが、メッセージが @code{multipart/digest} コンテナに含まれているときだけ例外的に @code{message/rfc822} になります。
@end deffn

@geindex set_default_type() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message set_default_type}@anchor{3b8b}
@deffn {メソッド} set_default_type (ctype)

デフォルトの content-type を設定します。 `ctype' は @code{text/plain} あるいは @code{message/rfc822} である必要がありますが、強制ではありません。デフォルトの content-type はヘッダの @code{Content-Type} には格納されません。
@end deffn

@geindex get_params() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_params}@anchor{3b8c}
@deffn {メソッド} get_params (failobj=None, header='content-type', unquote=True)

メッセージの @code{Content-Type} パラメータをリストとして返します。返されるリストはキー/値の組からなる2要素タプルが連なったものであり、これらは @code{'='} 記号で分離されています。 @code{'='} の左側はキーになり、右側は値になります。パラメータ中に @code{'='} がなかった場合、値の部分は空文字列になり、そうでなければその値は @ref{3b8d,,get_param()} で説明されている形式になります。また、オプション引数 `unquote' が @code{True} (デフォルト) である場合、この値は unquote されます。

オプション引数 `failobj' は、 @code{Content-Type} ヘッダが存在しなかった場合に返すオブジェクトです。オプション引数 `header' には @code{Content-Type} のかわりに検索すべきヘッダを指定します。

This is a legacy method.  On the
@ref{580,,EmailMessage} class its functionality is
replaced by the `params' property of the individual header objects
returned by the header access methods.
@end deffn

@geindex get_param() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_param}@anchor{3b8d}
@deffn {メソッド} get_param (param, failobj=None, header='content-type', unquote=True)

メッセージの @code{Content-Type} ヘッダ中のパラメータ `param' を文字列として返します。そのメッセージ中に @code{Content-Type} ヘッダが存在しなかった場合、 `failobj'  (デフォルトは @code{None}) が返されます。

オプション引数 `header' が与えられた場合、 @code{Content-Type} のかわりにそのヘッダが使用されます。

パラメータのキー比較は常に大文字小文字を区別しません。返り値は文字列か 3 要素のタプルで、タプルになるのはパラメータが 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} エンコードされている場合です。3 要素タプルの場合、各要素の値は @code{(CHARSET, LANGUAGE, VALUE)} の形式になっています。 @code{CHARSET} と @code{LAGUAGE} は @code{None} になることがあり、その場合 @code{VALUE} は @code{us-ascii} 文字セットでエンコードされているとみなさなければならないので注意してください。普段は @code{LANGUAGE} を無視できます。

この関数を使うアプリケーションが、パラメータが 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} 形式でエンコードされているかどうかを気にしないのであれば、 @ref{3b8e,,email.utils.collapse_rfc2231_value()} に @ref{3b8d,,get_param()} の返り値を渡して呼び出すことで、このパラメータをひとつにまとめることができます。この値がタプルならばこの関数は適切にデコードされた Unicode 文字列を返し、そうでない場合は unquote された元の文字列を返します。たとえば:

@example
rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam)
@end example

いずれの場合もパラメータの値は (文字列であれ3要素タプルの @code{VALUE} 項目であれ) つねに unquote されます。ただし、`unquote' が @code{False} に指定されている場合は unquote されません。

This is a legacy method.  On the
@ref{580,,EmailMessage} class its functionality is
replaced by the `params' property of the individual header objects
returned by the header access methods.
@end deffn

@geindex set_param() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message set_param}@anchor{113b}
@deffn {メソッド} set_param (param, value, header='Content-Type', requote=True, charset=None, language='@w{'}, replace=False)

@code{Content-Type} ヘッダ中のパラメータを設定します。指定されたパラメータがヘッダ中にすでに存在する場合、その値は `value' に置き換えられます。 @code{Content-Type} ヘッダがまだこのメッセージ中に存在していない場合、 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} にしたがいこの値には @code{text/plain} が設定され、新しいパラメータ値が末尾に追加されます。

オプション引数 `header' が与えられた場合、 @code{Content-Type} のかわりにそのヘッダが使用されます。オプション引数 `requote' が @code{False} でない限り、この値は quote されます (デフォルトは @code{True})。

オプション引数 `charset' が与えられると、そのパラメータは 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} に従ってエンコードされます。オプション引数 `language' は RFC 2231 の言語を指定しますが、デフォルトではこれは空文字列となります。 `charset' と `language' はどちらも文字列である必要があります。

If `replace' is @code{False} (the default) the header is moved to the
end of the list of headers.  If `replace' is @code{True}, the header
will be updated in place.


バージョン 3.4 で変更: @code{replace} キーワードが追加されました。

@end deffn

@geindex del_param() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message del_param}@anchor{3b8f}
@deffn {メソッド} del_param (param, header='content-type', requote=True)

指定されたパラメータを @code{Content-Type} ヘッダ中から完全にとりのぞきます。ヘッダはそのパラメータと値がない状態に書き換えられます。 `requote' が @code{False} でない限り (デフォルトでは @code{True} です)、すべての値は必要に応じて quote されます。オプション変数 `header' が与えられた場合、 @code{Content-Type} のかわりにそのヘッダが使用されます。
@end deffn

@geindex set_type() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message set_type}@anchor{3b90}
@deffn {メソッド} set_type (type, header='Content-Type', requote=True)

@code{Content-Type} ヘッダの maintype と subtype を設定します。 `type' は @code{maintype/subtype} という形の文字列でなければなりません。それ以外の場合は @ref{2ec,,ValueError} が発生します。

このメソッドは @code{Content-Type} ヘッダを置き換えますが、すべてのパラメータはそのままにします。 `requote' が @code{False} の場合、これはすでに存在するヘッダを quote せず放置しますが、そうでない場合は自動的に quote します (デフォルト動作)。

オプション変数 `header' が与えられた場合、 @code{Content-Type} のかわりにそのヘッダが使用されます。 @code{Content-Type} ヘッダが設定される場合には、 @code{MIME-Version} ヘッダも同時に付加されます。

This is a legacy method.  On the
@ref{580,,EmailMessage} class its functionality is
replaced by the @code{make_} and @code{add_} methods.
@end deffn

@geindex get_filename() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_filename}@anchor{3b91}
@deffn {メソッド} get_filename (failobj=None)

そのメッセージ中の @code{Content-Disposition} ヘッダにある、 @code{filename} パラメータの値を返します。目的のヘッダに @code{filename} パラメータがない場合には @code{Content-Type} ヘッダにある @code{name} パラメータを探します。それも無い場合またはヘッダが無い場合には `failobj' が返されます。返される文字列はつねに @ref{3ad7,,email.utils.unquote()} によって unquote されます。
@end deffn

@geindex get_boundary() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_boundary}@anchor{3b92}
@deffn {メソッド} get_boundary (failobj=None)

そのメッセージ中の @code{Content-Type} ヘッダにある、 @code{boundary} パラメータの値を返します。目的のヘッダが欠けていたり、 @code{boundary} パラメータがない場合には `failobj' が返されます。返される文字列はつねに @ref{3ad7,,email.utils.unquote()} によって unquote されます。
@end deffn

@geindex set_boundary() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message set_boundary}@anchor{3b93}
@deffn {メソッド} set_boundary (boundary)

メッセージ中の @code{Content-Type} ヘッダにある、 @code{boundary} パラメータに値を設定します。 @ref{3b93,,set_boundary()} は必要に応じて `boundary' を quote します。そのメッセージが @code{Content-Type} ヘッダを含んでいない場合、 @ref{3ada,,HeaderParseError} が発生します。

注意: このメソッドを使うのは、古い @code{Content-Type} ヘッダを削除して新しい boundary をもったヘッダを @ref{187e,,add_header()} で足すのとは少し違います。 @ref{3b93,,set_boundary()} は一連のヘッダ中での @code{Content-Type} ヘッダの位置を保つからです。しかし、これは元の @code{Content-Type} ヘッダ中に存在していた連続する行の順番までは `保ちません' 。
@end deffn

@geindex get_content_charset() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_content_charset}@anchor{3b94}
@deffn {メソッド} get_content_charset (failobj=None)

そのメッセージ中の @code{Content-Type} ヘッダにある、 @code{charset} パラメータの値を返します。値はすべて小文字に変換されます。メッセージ中に @code{Content-Type} がなかったり、このヘッダ中に @code{charaset} パラメータがない場合には `failobj' が返されます。

注意: これは @ref{3b7d,,get_charset()} メソッドとは異なります。こちらのほうは文字列のかわりに、そのメッセージボディのデフォルトエンコーディングの @ref{ffb,,Charset} インスタンスを返します。
@end deffn

@geindex get_charsets() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_charsets}@anchor{3b95}
@deffn {メソッド} get_charsets (failobj=None)

メッセージ中に含まれる文字セットの名前をすべてリストにして返します。そのメッセージが @code{multipart} である場合、返されるリストの各要素がそれぞれの subpart のペイロードに対応します。それ以外の場合、これは長さ 1 のリストを返します。

リスト中の各要素は文字列であり、これは対応する subpart 中のそれぞれの @code{Content-Type} ヘッダにある @code{charset} の値です。しかし、その subpart が @code{Content-Type} をもってないか、 @code{charset} がないか、あるいは MIME maintype が @code{text} でないいずれかの場合には、リストの要素として `failobj' が返されます。
@end deffn

@geindex get_content_disposition() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message get_content_disposition}@anchor{ff8}
@deffn {メソッド} get_content_disposition ()

Return the lowercased value (without parameters) of the message's
@code{Content-Disposition} header if it has one, or @code{None}.  The
possible values for this method are `inline', `attachment' or @code{None}
if the message follows 
@geindex RFC; RFC 2183
RFC 2183@footnote{https://datatracker.ietf.org/doc/html/rfc2183.html}.


Added in version 3.5.

@end deffn

@geindex walk() (email.message.Message のメソッド)
@anchor{library/email compat32-message email message Message walk}@anchor{3b96}
@deffn {メソッド} walk ()

@ref{3b96,,walk()} メソッドは多目的のジェネレータで、これはあるメッセージオブジェクトツリー中のすべての part および subpart をわたり歩くのに使えます。順序は深さ優先です。おそらく典型的な用法は、 @ref{3b96,,walk()} を @code{for} ループ中でのイテレータとして使うことでしょう。ループを一回まわるごとに、次の subpart が返されるのです。

以下の例は、 multipart メッセージのすべての part において、その MIME タイプを表示していくものです。 :

@c import email
@c from email import message_from_binary_file
@c from os.path import join, dirname
@c lib_dir = dirname(dirname(email.__file__))
@c file_path = join(lib_dir, 'test/test_email/data/msg_16.txt')
@c with open(file_path, 'rb') as f:
@c     msg = message_from_binary_file(f)
@c from email.iterators import _structure

@example
>>> for part in msg.walk():
...     print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain
@end example

@code{walk} iterates over the subparts of any part where
@ref{3ade,,is_multipart()} returns @code{True}, even though
@code{msg.get_content_maintype() == 'multipart'} may return @code{False}.  We
can see this in our example by making use of the @code{_structure} debug
helper function:

@example
>>> for part in msg.walk():
...     print(part.get_content_maintype() == 'multipart',
...           part.is_multipart())
True True
False False
False True
False False
False False
False True
False False
>>> _structure(msg)
multipart/report
    text/plain
    message/delivery-status
        text/plain
        text/plain
    message/rfc822
        text/plain
@end example

Here the @code{message} parts are not @code{multiparts}, but they do contain
subparts. @code{is_multipart()} returns @code{True} and @code{walk} descends
into the subparts.
@end deffn

@ref{581,,Message} オブジェクトはオプションとして 2つのインスタンス属性をとることができます。これはある MIME メッセージからプレーンテキストを生成するのに使うことができます。

@geindex preamble (email.message.Message の属性)
@anchor{library/email compat32-message email message Message preamble}@anchor{3b97}
@deffn {の属性} preamble

MIME ドキュメントの形式では、ヘッダ直後にくる空行と最初の multipart 境界をあらわす文字列のあいだにいくらかのテキスト (訳注: preamble, 序文) を埋めこむことを許しています。このテキストは標準的な MIME の範疇からはみ出しているので、MIME 形式を認識するメールソフトからこれらは通常まったく見えません。しかしメッセージのテキストを生で見る場合、あるいはメッセージを MIME 対応していないメールソフトで見る場合、このテキストは目に見えることになります。

`preamble' 属性は MIME ドキュメントに加えるこの最初の MIME 範囲外テキストを含んでいます。 @ref{13b5,,Parser} があるテキストをヘッダ以降に発見したが、それはまだ最初の MIME 境界文字列が現れる前だった場合、パーザはそのテキストをメッセージの `preamble' 属性に格納します。 @ref{13e6,,Generator} がある MIME メッセージからプレーンテキスト形式を生成するときメッセージが `preamble' 属性を持つことが発見されれば、これはそのテキストをヘッダと最初の MIME 境界の間に挿入します。詳細は @ref{52,,email.parser} および @ref{44,,email.generator} を参照してください。

注意: そのメッセージに preamble がない場合、`preamble' 属性には @code{None} が格納されます。
@end deffn

@geindex epilogue (email.message.Message の属性)
@anchor{library/email compat32-message email message Message epilogue}@anchor{3b98}
@deffn {の属性} epilogue

`epilogue' 属性はメッセージの最後の MIME 境界文字列からメッセージ末尾までのテキストを含むもので、それ以外は `preamble' 属性と同じです。

@ref{13e6,,Generator} でファイル終端に改行を出力するため、 epilogue に空文字列を設定する必要はなくなりました。
@end deffn

@geindex defects (email.message.Message の属性)
@anchor{library/email compat32-message email message Message defects}@anchor{3b99}
@deffn {の属性} defects

`defects' 属性はメッセージを解析する途中で検出されたすべての問題点 (defect、障害) のリストを保持しています。解析中に発見されうる障害についてのより詳細な説明は @ref{43,,email.errors} を参照してください。
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email mime Creating email and MIME objects from scratch,email header 国際化されたヘッダー,email message Message compat32 API を使用した電子メールメッセージの表現,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email mime doc}@anchor{3b9a}@anchor{library/email mime email-mime-creating-email-and-mime-objects-from-scratch}@anchor{3b9b}@anchor{library/email mime module-email mime}@anchor{49}@anchor{library/email mime translation-repo}@anchor{3b9c}
@subsubsection @code{email.mime}: Creating email and MIME objects from scratch


@geindex module; email.mime

`ソースコード:' Lib/email/mime/@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/mime/}


__________________________________________________________________


This module is part of the legacy (@code{Compat32}) email API.  Its functionality
is partially replaced by the @ref{41,,contentmanager} in the new API, but
in certain applications these classes may still be useful, even in non-legacy
code.

ふつう、メッセージオブジェクト構造はファイルまたは何がしかのテキストをパーザに通すことで得られます。パーザは与えられたテキストを解析し、基底となる root のメッセージオブジェクトを返します。しかし、完全なメッセージオブジェクト構造を何もないところから作成することもまた可能です。個別の @ref{581,,Message} を手で作成することさえできます。実際には、すでに存在するメッセージオブジェクト構造をとってきて、そこに新たな @ref{581,,Message} オブジェクトを追加したり、あるものを別のところへ移動させたりできます。これは MIME メッセージを切ったりおろしたりするために非常に便利なインターフェイスを提供します。

新しいメッセージオブジェクト構造は @ref{581,,Message} インスタンスを作成することにより作れます。ここに添付ファイルやその他適切なものをすべて手で加えてやればよいのです。MIME メッセージの場合、 @ref{3f,,email} パッケージはこれらを簡単におこなえるようにするためにいくつかの便利なサブクラスを提供しています。

以下がそのサブクラスです:

@geindex module; email.mime.base

@geindex MIMEBase (email.mime.base のクラス)
@anchor{library/email mime module-email mime base}@anchor{4c}@anchor{library/email mime email mime base MIMEBase}@anchor{3b9d}
@deffn {クラス} email.mime.base.MIMEBase (_maintype, _subtype, *, policy=compat32, **_params)

モジュール: @ref{4c,,email.mime.base}

これはすべての @ref{581,,Message} の MIME 用サブクラスの基底となるクラスです。とくに @ref{3b9d,,MIMEBase} のインスタンスを直接作成することは (可能ではありますが) ふつうはしないでしょう。 @ref{3b9d,,MIMEBase} は単により特化された MIME 用サブクラスのための便宜的な基底クラスとして提供されています。

`_maintype' は @code{Content-Type} の主形式 (maintype) であり (@code{text} や @code{image} など)、 `_subtype' は @code{Content-Type} の副形式 (subtype) です (@code{plain} や @code{gif} など)。 `_params' は各パラメータのキーと値を格納した辞書であり、これは直接 @ref{187e,,Message.add_header} に渡されます。

If `policy' is specified, (defaults to the
@ref{12c8,,compat32} policy) it will be passed to
@ref{581,,Message}.

@ref{3b9d,,MIMEBase} クラスはつねに (`_maintype' 、 `_subtype' 、および `_params' にもとづいた) @code{Content-Type} ヘッダと、 @code{MIME-Version} ヘッダ (必ず @code{1.0} に設定される) を追加します。


バージョン 3.6 で変更: キーワード専用引数 `policy' が追加されました。

@end deffn

@geindex module; email.mime.nonmultipart

@geindex MIMENonMultipart (email.mime.nonmultipart のクラス)
@anchor{library/email mime module-email mime nonmultipart}@anchor{50}@anchor{library/email mime email mime nonmultipart MIMENonMultipart}@anchor{3b32}
@deffn {クラス} email.mime.nonmultipart.MIMENonMultipart

モジュール: @ref{50,,email.mime.nonmultipart}

@ref{3b9d,,MIMEBase} のサブクラスで、これは @code{multipart} 形式でない MIME メッセージのための中間的な基底クラスです。このクラスのおもな目的は、通常 @code{multipart} 形式のメッセージに対してのみ意味をなす @ref{3aeb,,attach()} メソッドの使用をふせぐことです。もし @ref{3aeb,,attach()} メソッドが呼ばれた場合、これは @ref{3b31,,MultipartConversionError} 例外を発生します。
@end deffn

@geindex module; email.mime.multipart

@geindex MIMEMultipart (email.mime.multipart のクラス)
@anchor{library/email mime module-email mime multipart}@anchor{4f}@anchor{library/email mime email mime multipart MIMEMultipart}@anchor{3b9e}
@deffn {クラス} email.mime.multipart.MIMEMultipart (_subtype='mixed', boundary=None, _subparts=None, *, policy=compat32, **_params)

モジュール: @ref{4f,,email.mime.multipart}

@ref{3b9d,,MIMEBase} のサブクラスで、これは @code{multipart} 形式の MIME メッセージのための中間的な基底クラスです。オプション引数 `_subtype' はデフォルトでは @code{mixed} になっていますが、そのメッセージの副形式 (subtype) を指定するのに使うことができます。メッセージオブジェクトには @code{multipart/_subtype} という値をもつ @code{Content-Type} ヘッダとともに、 @code{MIME-Version} ヘッダが追加されるでしょう。

オプション引数 `boundary' は multipart の境界文字列です。これが @code{None} の場合 (デフォルト)、境界は必要に応じて計算されます（例えばメッセージがシリアライズされるときなど）。

`_subparts' はそのペイロードの subpart の初期値からなるシーケンスです。このシーケンスはリストに変換できるようになっている必要があります。新しい subpart はつねに @ref{3aeb,,Message.attach} メソッドを使ってそのメッセージに追加できるようになっています。

Optional `policy' argument defaults to @ref{12c8,,compat32}.

@code{Content-Type} ヘッダに対する追加のパラメータはキーワード引数 `_params' を介して取得あるいは設定されます。これはキーワード辞書になっています。


バージョン 3.6 で変更: キーワード専用引数 `policy' が追加されました。

@end deffn

@geindex module; email.mime.application

@geindex MIMEApplication (email.mime.application のクラス)
@anchor{library/email mime module-email mime application}@anchor{4a}@anchor{library/email mime email mime application MIMEApplication}@anchor{3b9f}
@deffn {クラス} email.mime.application.MIMEApplication (_data, _subtype='octet-stream', _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

モジュール: @ref{4a,,email.mime.application}

A subclass of @ref{3b32,,MIMENonMultipart}, the
@ref{3b9f,,MIMEApplication} class is used to represent MIME message objects of
major type @code{application}.  `_data' contains the bytes for the raw
application data.  Optional `_subtype' specifies the MIME subtype and defaults
to @code{octet-stream}.

オプション引数の `_encoder' は呼び出し可能なオブジェクト (関数など) で、データの転送に使う実際のエンコード処理を行います。この呼び出し可能なオブジェクトは引数を 1 つ取り、それは @ref{3b9f,,MIMEApplication} のインスタンスです。ペイロードをエンコードされた形式に変更するために @ref{13e5,,get_payload()} と @ref{3b7b,,set_payload()} を使い、必要に応じて @code{Content-Transfer-Encoding} やその他のヘッダをメッセージオブジェクトに追加するべきです。デフォルトのエンコードは base64 です。組み込みのエンコーダの一覧は @ref{42,,email.encoders} モジュールを見てください。

Optional `policy' argument defaults to @ref{12c8,,compat32}.

`_params' は基底クラスのコンストラクタにそのまま渡されます。


バージョン 3.6 で変更: キーワード専用引数 `policy' が追加されました。

@end deffn

@geindex module; email.mime.audio

@geindex MIMEAudio (email.mime.audio のクラス)
@anchor{library/email mime module-email mime audio}@anchor{4b}@anchor{library/email mime email mime audio MIMEAudio}@anchor{3ba0}
@deffn {クラス} email.mime.audio.MIMEAudio (_audiodata, _subtype=None, _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

モジュール: @ref{4b,,email.mime.audio}

A subclass of @ref{3b32,,MIMENonMultipart}, the
@ref{3ba0,,MIMEAudio} class is used to create MIME message objects of major type
@code{audio}. `_audiodata' contains the bytes for the raw audio data.  If
this data can be decoded as au, wav, aiff, or aifc, then the
subtype will be automatically included in the @code{Content-Type} header.
Otherwise you can explicitly specify the audio subtype via the `_subtype'
argument.  If the minor type could not be guessed and `_subtype' was not given,
then @ref{198,,TypeError} is raised.

オプション引数の `_encoder' は呼び出し可能なオブジェクト (関数など) で、オーディオデータの転送に使う実際のエンコード処理を行います。この呼び出し可能なオブジェクトは引数を 1 つ取り、それは @ref{3ba0,,MIMEAudio} のインスタンスです。ペイロードをエンコードされた形式に変更するために @ref{13e5,,get_payload()} と @ref{3b7b,,set_payload()} を使い、必要に応じて @code{Content-Transfer-Encoding} やその他のヘッダをメッセージオブジェクトに追加するべきです。デフォルトのエンコードは base64 です。組み込みのエンコーダの一覧は @ref{42,,email.encoders} モジュールを見てください。

Optional `policy' argument defaults to @ref{12c8,,compat32}.

`_params' は基底クラスのコンストラクタにそのまま渡されます。


バージョン 3.6 で変更: キーワード専用引数 `policy' が追加されました。

@end deffn

@geindex module; email.mime.image

@geindex MIMEImage (email.mime.image のクラス)
@anchor{library/email mime module-email mime image}@anchor{4d}@anchor{library/email mime email mime image MIMEImage}@anchor{3b33}
@deffn {クラス} email.mime.image.MIMEImage (_imagedata, _subtype=None, _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

モジュール: @ref{4d,,email.mime.image}

A subclass of @ref{3b32,,MIMENonMultipart}, the
@ref{3b33,,MIMEImage} class is used to create MIME message objects of major type
@code{image}. `_imagedata' contains the bytes for the raw image data.  If
this data type can be detected (jpeg, png, gif, tiff, rgb, pbm, pgm, ppm,
rast, xbm, bmp, webp, and exr attempted), then the subtype will be
automatically included in the @code{Content-Type} header. Otherwise
you can explicitly specify the image subtype via the `_subtype' argument.
If the minor type could not be guessed and `_subtype' was not given, then
@ref{198,,TypeError} is raised.

オプション引数の `_encoder' は呼び出し可能なオブジェクト (関数など) で、画像データの転送に使う実際のエンコード処理を行います。この呼び出し可能なオブジェクトは引数を 1 つ取り、それは @ref{3b33,,MIMEImage} のインスタンスです。ペイロードをエンコードされた形式に変更するために @ref{13e5,,get_payload()} と @ref{3b7b,,set_payload()} を使い、必要に応じて @code{Content-Transfer-Encoding} やその他のヘッダをメッセージオブジェクトに追加するべきです。デフォルトのエンコードは base64 です。組み込みのエンコーダの一覧は @ref{42,,email.encoders} モジュールを見てください。

Optional `policy' argument defaults to @ref{12c8,,compat32}.

`_params' は @ref{3b9d,,MIMEBase} コンストラクタに直接渡されます。


バージョン 3.6 で変更: キーワード専用引数 `policy' が追加されました。

@end deffn

@geindex module; email.mime.message

@geindex MIMEMessage (email.mime.message のクラス)
@anchor{library/email mime module-email mime message}@anchor{4e}@anchor{library/email mime email mime message MIMEMessage}@anchor{3ba1}
@deffn {クラス} email.mime.message.MIMEMessage (_msg, _subtype='rfc822', *, policy=compat32)

モジュール: @ref{4e,,email.mime.message}

@ref{3ba1,,MIMEMessage} クラスは @ref{3b32,,MIMENonMultipart} のサブクラスで、主形式 (maintype) が @code{message} の MIME オブジェクトを作成するのに使われます。ペイロードとして使われるメッセージは `_msg' になります。これは @ref{581,,Message} クラス (あるいはそのサブクラス) のインスタンスでなければいけません。そうでない場合、この関数は @ref{198,,TypeError} を発生します。

オプション引数 `_subtype' はそのメッセージの副形式 (subtype) を設定します。デフォルトではこれは @code{rfc822} になっています。

Optional `policy' argument defaults to @ref{12c8,,compat32}.


バージョン 3.6 で変更: キーワード専用引数 `policy' が追加されました。

@end deffn

@geindex module; email.mime.text

@geindex MIMEText (email.mime.text のクラス)
@anchor{library/email mime module-email mime text}@anchor{51}@anchor{library/email mime email mime text MIMEText}@anchor{ffa}
@deffn {クラス} email.mime.text.MIMEText (_text, _subtype='plain', _charset=None, *, policy=compat32)

モジュール: @ref{51,,email.mime.text}

@ref{ffa,,MIMEText} クラスは @ref{3b32,,MIMENonMultipart} のサブクラスで、主形式 (maintype) が @code{text} の MIME オブジェクトを作成するのに使われます。ペイロードの文字列は `_text' になります。 `_subtype' には副形式 (subtype) を指定し、デフォルトは @code{plain} です。 `_charset' はテキストの文字セットで、 @ref{3b32,,MIMENonMultipart} コンストラクタに引数として渡されます。この値は、文字列が @code{ascii} コードポイントのみを含む場合 @code{us-ascii} 、それ以外は @code{utf-8} がデフォルトになっています。 `_charset' パラメータは、文字列と @ref{ffb,,Charset} インスタンスの両方を受け付けます。

@code{_charset} 引数に明示的に @code{None} をセットしない限りは、作成される MIMEText オブジェクトは @code{charset} の付いた @code{Content-Type} ヘッダと @code{Content-Transfer-Endcoding} ヘッダの両方を持ちます。これは後続の @code{set_payload} 呼び出しが、 @code{set_payload} コマンドに charset が渡したとしてもエンコードされたペイロードにはならないことを意味します。 @code{Content-Transfer-Encoding} ヘッダを削除することでこの振る舞いを「リセット」出来ます。これにより @code{set_payload} 呼び出しが新たなペイロードを自動的にエンコード (そして新たな @code{Content-Transfer-Encoding} ヘッダを追加) します。

Optional `policy' argument defaults to @ref{12c8,,compat32}.


バージョン 3.5 で変更: `_charset' は @ref{ffb,,Charset} インスタンスも受け取ります。



バージョン 3.6 で変更: キーワード専用引数 `policy' が追加されました。

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email header 国際化されたヘッダー,email charset 文字集合の表現,email mime Creating email and MIME objects from scratch,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email header doc}@anchor{3ba2}@anchor{library/email header email-header-internationalized-headers}@anchor{3ba3}@anchor{library/email header module-email header}@anchor{45}@anchor{library/email header translation-repo}@anchor{3ba4}
@subsubsection @code{email.header}: 国際化されたヘッダー


@geindex module; email.header

`ソースコード:' Lib/email/header.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/header.py}


__________________________________________________________________


このモジュールはレガシー(@code{Compat32})な電子メールAPIの一部です。現在のAPIではヘッダのエンコードとデコードは @ref{580,,EmailMessage} クラスの辞書的なAPIによって透過的に処理されます。レガシーコードでの使用に加えて、このモジュールは、ヘッダーをエンコードする際に使用される文字セットを完全に制御する必要があるアプリケーションで役立ちます

この節の以降のテキストはモジュールの元々のドキュメントです。

@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} は電子メールメッセージの形式を規定する基本規格です。これはほとんどの電子メールが ASCII 文字のみで構成されていたころ普及した 
@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html} 標準から発展したものです。 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} は電子メールがすべて 7-bit ASCII 文字のみから構成されていると仮定して作られた仕様です。

Of course, as email has been deployed worldwide, it has become
internationalized, such that language specific character sets can now be used in
email messages.  The base standard still requires email messages to be
transferred using only 7-bit ASCII characters, so a slew of RFCs have been
written describing how to encode email containing non-ASCII characters into
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html}-compliant format. These RFCs include 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html}, 
@geindex RFC; RFC 2046
RFC 2046@footnote{https://datatracker.ietf.org/doc/html/rfc2046.html},
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html}, and 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html}. The @ref{3f,,email} package supports these standards
in its @code{email.header} and @ref{40,,email.charset} modules.

If you want to include non-ASCII characters in your email headers, say in the
@code{Subject} or @code{To} fields, you should use the
@ref{1c5e,,Header} class and assign the field in the @ref{581,,Message}
object to an instance of @ref{1c5e,,Header} instead of using a string for the header
value.  Import the @ref{1c5e,,Header} class from the @code{email.header} module.
For example:

@example
>>> from email.message import Message
>>> from email.header import Header
>>> msg = Message()
>>> h = Header('p\xf6stal', 'iso-8859-1')
>>> msg['Subject'] = h
>>> msg.as_string()
'Subject: =?iso-8859-1?q?p=F6stal?=\n\n'
@end example

@code{Subject} フィールドに非ASCII文字を含めていることに注目してください。ここでは、含めたいバイト列がエンコードされている文字集合を指定して @ref{1c5e,,Header} インスタンスを作成することによって実現しています。のちにこの @ref{581,,Message} インスタンスからフラットなテキストを生成する際に、この @code{Subject} フィールドは 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} 準拠の適切な形式にエンコードされます。MIME 機能のあるメーラなら、このヘッダに埋めこまれた ISO-8859-1 文字を正しく表示するでしょう。

以下は @ref{1c5e,,Header} クラスの説明です:

@geindex Header (email.header のクラス)
@anchor{library/email header email header Header}@anchor{1c5e}
@deffn {クラス} email.header.Header (s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict')

別の文字集合の文字列を含む MIME 準拠なヘッダを作成します。

オプション引数 `s' はヘッダの値の初期値です。これが @code{None} の場合 (デフォルト)、ヘッダの初期値は設定されません。この値はあとから @ref{3ba5,,append()} メソッドを呼びだすことによって追加することができます。 `s' は @ref{192,,bytes} または @ref{169,,str} のインスタンスにできます。このセマンティクスについては @ref{3ba5,,append()} の項を参照してください。

オプション引数 `charset' には 2 つの目的があります。ひとつは @ref{3ba5,,append()} メソッドにおける `charset' 引数と同じものです。もうひとつは、これ以降 `charset' 引数を省略した @ref{3ba5,,append()} メソッド呼び出しすべてにおける、デフォルト文字集合を決定するものです。コンストラクタに `charset' が与えられない場合 (デフォルト)、初期値の `s' および以後の @ref{3ba5,,append()} 呼び出しにおける文字集合として @code{us-ascii} が使われます。

行の最大長は `maxlinelen' によって明示的に指定できます。最初の行を (@code{Subject} などの `s' に含まれないフィールドヘッダの責任をとるため) 短く切りとる場合、 `header_name' にそのフィールド名を指定してください。 `maxlinelen' のデフォルト値は 78 であり、 `header_name' のデフォルト値は @code{None} です。これはその最初の行を長い、切りとられたヘッダとして扱わないことを意味します。

オプション引数 `continuation_ws' は 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} 準拠の折り返し用余白文字で、ふつうこれは空白か、ハードタブ文字 (hard tab) である必要があります。ここで指定された文字は複数にわたる行の行頭に挿入されます。 `continuation_ws' のデフォルト値は 1 つのスペース文字です。

オプション引数 `errors' は、 @ref{3ba5,,append()} メソッドにそのまま渡されます。

@geindex append() (email.header.Header のメソッド)
@anchor{library/email header email header Header append}@anchor{3ba5}
@deffn {メソッド} append (s, charset=None, errors='strict')

この MIME ヘッダに文字列 `s' を追加します。

オプション引数 `charset' がもし与えられた場合、これは @ref{ffb,,Charset} インスタンス (@ref{40,,email.charset} を参照) か、あるいは文字集合の名前でなければなりません。この場合は @ref{ffb,,Charset} インスタンスに変換されます。この値が @code{None} の場合 (デフォルト)、コンストラクタで与えられた `charset' が使われます。

`s' は @ref{192,,bytes} または @ref{169,,str} のインスタンスです。 @ref{192,,bytes} のインスタンスの場合、 `charset' はその文字列のエンコーディングであり、この文字セットでデコードできないときは @ref{462,,UnicodeError} が発生します。

`s' が @ref{169,,str} のインスタンスの場合、 `charset' はその文字列の文字セットを決定するためのヒントとして使われます。

いずれの場合でも、 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} 準拠のヘッダを 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} の規則を用いて生成する際、文字列は指定された文字セットの出力コーデックを用いてエンコードされます。出力コーデックを用いて文字列がエンコードできないときは @ref{462,,UnicodeError} が発生します。

オプションの `errors' は、 `s' がバイト文字列だった場合のデコード呼び出しに errors 引数として渡されます。
@end deffn

@geindex encode() (email.header.Header のメソッド)
@anchor{library/email header email header Header encode}@anchor{3ba6}
@deffn {メソッド} encode (splitchars=';, \t', maxlinelen=None, linesep='\n')

メッセージヘッダを RFC に沿ったやり方でエンコードします。おそらく長い行は折り返され、非 ASCII 部分は base64 または quoted-printable エンコーディングで包含されるでしょう。

オプション引数 `splitchars' は、通常のヘッダーの折り返し処理の間に分割アルゴリズムによって特別な重みが与えられるべき文字を含む文字列です。これは、 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} の 'higher level syntactic breaks' の非常に荒いサポートです: splitchar の後の分割点は、行分割において優先されます。 分割文字は文字列中での出現順に優先されます。スペースとタブは、分割しようとする行に他の分割文字が出現しない時に、分割点として他の文字と比べてどのような優先順位が与えられるべきかを示すために、文字列に含めることができます。 Splitchars は 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} エンコードされた行には影響しません。

与えられた場合、`maxlinelen' はインスタンスの最大行長の値を上書きします。

`linesep' は、折り返しヘッダの行を区切る文字を指定します。デフォルトではPythonアプリケーションコードに最も有用な値(@code{\n})になりますが、RFC準拠の行区切り文字でヘッダを生成するために`@w{`}rn`@w{`}を指定することができます。


バージョン 3.2 で変更: `linesep' 引数が追加されました。

@end deffn

@ref{1c5e,,Header} クラスは、標準の演算子や組み込み関数をサポートするためのメソッドもいくつか提供しています。

@geindex __str__() (email.header.Header のメソッド)
@anchor{library/email header email header Header __str__}@anchor{3ba7}
@deffn {メソッド} __str__ ()

@ref{1c5e,,Header} の概要を文字列として返します。無制限の行長を使用します。すべての箇所は、指定されたエンコーディングを使用してUnicodeに変換され、適切に結合されます。文字セット @code{'unknown-8bit'} を持つ箇所は、 @code{'replace'} エラーハンドラを使ってASCIIとしてデコードされます。


バージョン 3.2 で変更: @code{'unknown-8bit'} 文字集合の処理が追加されました。

@end deffn

@geindex __eq__() (email.header.Header のメソッド)
@anchor{library/email header email header Header __eq__}@anchor{3ba8}
@deffn {メソッド} __eq__ (other)

このメソッドは、ふたつの @ref{1c5e,,Header} インスタンスどうしが等しいかどうか判定するのに使えます。
@end deffn

@geindex __ne__() (email.header.Header のメソッド)
@anchor{library/email header email header Header __ne__}@anchor{3ba9}
@deffn {メソッド} __ne__ (other)

このメソッドは、ふたつの @ref{1c5e,,Header} インスタンスどうしが異なっているかどうかを判定するのに使えます。
@end deffn
@end deffn

The @code{email.header} module also provides the following convenient functions.

@geindex decode_header() (email.header モジュール)
@anchor{library/email header email header decode_header}@anchor{12ce}
@deffn {の関数} email.header.decode_header (header)

文字集合を変換せずにメッセージのヘッダをデコードします。ヘッダの値は `header' にあります。

For historical reasons, this function may return either:


@enumerate 

@item 
A list of pairs containing each of the decoded parts of the header,
@code{(decoded_bytes, charset)}, where `decoded_bytes' is always an instance of
@ref{192,,bytes}, and `charset' is either:

@quotation


@itemize -

@item 
A lower case string containing the name of the character set specified.

@item 
@code{None} for non-encoded parts of the header.
@end itemize
@end quotation

@item 
A list of length 1 containing a pair @code{(string, None)}, where
`string' is always an instance of @ref{169,,str}.
@end enumerate

An @ref{3ada,,email.errors.HeaderParseError} may be raised when certain decoding
errors occur (e.g. a base64 decoding exception).

Here are examples:

@example
>>> from email.header import decode_header
>>> decode_header('=?iso-8859-1?q?p=F6stal?=')
[(b'p\xf6stal', 'iso-8859-1')]
>>> decode_header('unencoded_string')
[('unencoded_string', None)]
>>> decode_header('bar =?utf-8?B?ZsOzbw==?=')
[(b'bar ', None), (b'f\xc3\xb3o', 'utf-8')]
@end example

@cartouche
@quotation 注釈 
This function exists for backwards compatibility only. For
new code, we recommend using @ref{3b43,,email.headerregistry.HeaderRegistry}.
@end quotation
@end cartouche
@end deffn

@geindex make_header() (email.header モジュール)
@anchor{library/email header email header make_header}@anchor{12cf}
@deffn {の関数} email.header.make_header (decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' ')

@ref{12ce,,decode_header()} によって返される 2要素タプルのリストから @ref{1c5e,,Header} インスタンスを作成します。

@ref{12ce,,decode_header()} はヘッダの値をとってきて、 @code{(decoded_string, charset)} という形式の 2要素タプルからなるリストを返します。ここで `decoded_string' はデコードされた文字列、 `charset' はその文字集合です。

この関数はこれらのリストの項目から、 @ref{1c5e,,Header} インスタンスを返します。オプション引数 `maxlinelen' 、 `header_name' および `continuation_ws' は @ref{1c5e,,Header} コンストラクタに与えるものと同じです。

@cartouche
@quotation 注釈 
This function exists for backwards compatibility only, and is
not recommended for use in new code.
@end quotation
@end cartouche
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email charset 文字集合の表現,email encoders エンコーダー,email header 国際化されたヘッダー,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email charset doc}@anchor{3baa}@anchor{library/email charset email-charset-representing-character-sets}@anchor{3bab}@anchor{library/email charset module-email charset}@anchor{40}@anchor{library/email charset translation-repo}@anchor{3bac}
@subsubsection @code{email.charset}: 文字集合の表現


@geindex module; email.charset

`ソースコード:' Lib/email/charset.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/charset.py}


__________________________________________________________________


このモジュールは、レガシーな (@code{Compat32}) email API の一部分です。
新しい API では別名の表のみ使われています。

この節の以降のテキストはモジュールの元々のドキュメントです。

このモジュールは文字集合の表現および電子メールメッセージの文字集合の変換を行う @ref{ffb,,Charset} クラスに加え、文字集合のレジストリとそれを操作する簡易メソッドを提供しています。
@ref{ffb,,Charset} インスタンスは @ref{3f,,email} パッケージ中にある他のいくつかのモジュールで使用されます。

Import this class from the @code{email.charset} module.

@geindex Charset (email.charset のクラス)
@anchor{library/email charset email charset Charset}@anchor{ffb}
@deffn {クラス} email.charset.Charset (input_charset=DEFAULT_CHARSET)

文字集合を電子メールのプロパティに写像します。

このクラスは、ある特定の文字集合に対し電子メールに課される条件についての情報を提供します。
また、適用可能なコーデックスが利用出来れば、文字集合間の変換を行う簡易ルーチンを提供します。
文字集合について、この関数は電子メールメッセージ内での RFC に準拠した文字集合の使い方に関する情報を提供するのに最善を尽くします。

文字集合によっては、電子メールのヘッダや本体で使う場合に quoted-printable や base64 形式でエンコードされなければなりません。
また、文字集合によっては完全に変換する必要があり、電子メールの中では使用できません。

以下ではオプション引数 `input_charset' について説明します。この値は常に小文字に強制的に変換されます。そして文字集合の別名が正規化されたあと、この値は文字集合のレジストリ内を検索し、ヘッダのエンコーディングとメッセージ本体のエンコーディング、および出力時の変換に使われるコーデックを見付けるのに使われます。たとえば `input_charset' が @code{iso-8859-1} の場合、ヘッダおよびメッセージ本体は quoted-printable でエンコードされ、出力時の変換用コーデックは必要ありません。もし `input_charset' が @code{euc-jp} ならば、ヘッダは base64 でエンコードされ、メッセージ本体はエンコードされませんが、出力されるテキストは @code{euc-jp} 文字集合から @code{iso-2022-jp} 文字集合に変換されます。

@ref{ffb,,Charset} インスタンスは以下のようなデータ属性をもっています:

@geindex input_charset (email.charset.Charset の属性)
@anchor{library/email charset email charset Charset input_charset}@anchor{3bad}
@deffn {の属性} input_charset

最初に指定される文字集合です。一般的な別名は、`正式な' 電子メール用の名前に変換されます (たとえば、@code{latin_1} は @code{iso-8859-1} に変換されます)。デフォルトは 7-bit の @code{us-ascii} です。
@end deffn

@geindex header_encoding (email.charset.Charset の属性)
@anchor{library/email charset email charset Charset header_encoding}@anchor{3bae}
@deffn {の属性} header_encoding

この文字集合が電子メールヘッダに使われる前にエンコードされなければならない場合、この属性は @code{charset.QP} (quoted-printable エンコーディング)、@code{charset.BASE64} (base64 エンコーディング)、あるいは最短の QP または BASE64 エンコーディングである @code{charset.SHORTEST} に設定されます。そうでない場合、この値は @code{None} になります。
@end deffn

@geindex body_encoding (email.charset.Charset の属性)
@anchor{library/email charset email charset Charset body_encoding}@anchor{3baf}
@deffn {の属性} body_encoding

`header_encoding' と同じですが、この値はメッセージ本体のためのエンコーディングを記述します。これはヘッダ用のエンコーディングとは違うかもしれません。`body_encoding' では、@code{charset.SHORTEST} を使うことはできません。
@end deffn

@geindex output_charset (email.charset.Charset の属性)
@anchor{library/email charset email charset Charset output_charset}@anchor{3bb0}
@deffn {の属性} output_charset

文字集合によっては、電子メールのヘッダあるいはメッセージ本体に使う前に変換しなければなりません。もし `input_charset' がそれらの文字集合のどれかをさしていたら、この `output_charset' 属性はそれが出力時に変換される文字集合の名前を表しています。それ以外の場合、この値は @code{None} になります。
@end deffn

@geindex input_codec (email.charset.Charset の属性)
@anchor{library/email charset email charset Charset input_codec}@anchor{3bb1}
@deffn {の属性} input_codec

`input_charset' を Unicode に変換するための Python 用コーデック名です。変換用のコーデックが必要ないときは、この値は @code{None} になります。
@end deffn

@geindex output_codec (email.charset.Charset の属性)
@anchor{library/email charset email charset Charset output_codec}@anchor{3bb2}
@deffn {の属性} output_codec

Unicode を `output_charset' に変換するための Python 用コーデック名です。変換用のコーデックが必要ないときは、この値は @code{None} になります。この属性は `input_codec' と同じ値を持つことになるでしょう。
@end deffn

@ref{ffb,,Charset} インスタンスは、以下のメソッドも持っています:

@geindex get_body_encoding() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset get_body_encoding}@anchor{3bb3}
@deffn {メソッド} get_body_encoding ()

メッセージ本体のエンコードに使われる content-transfer-encoding の値を返します。

この値は使用しているエンコーディングの文字列 @code{quoted-printable} または @code{base64} か、あるいは関数のいずれかです。後者の場合、これはエンコードされる Message オブジェクトを単一の引数として取るような関数である必要があります。この関数は変換後 @code{Content-Transfer-Encoding} ヘッダ自体を、なんであれ適切な値に設定する必要があります。

このメソッドは `body_encoding' が @code{QP} の場合 @code{quoted-printable} を返し、`body_encoding' が @code{BASE64} の場合 @code{base64} を返します。それ以外の場合は文字列 @code{7bit} を返します。
@end deffn

@geindex get_output_charset() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset get_output_charset}@anchor{3bb4}
@deffn {メソッド} get_output_charset ()

出力用の文字集合を返します。

これは `output_charset' 属性が @code{None} でなければその値になります。それ以外の場合、この値は `input_charset' と同じです。
@end deffn

@geindex header_encode() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset header_encode}@anchor{3bb5}
@deffn {メソッド} header_encode (string)

文字列 `string' をヘッダ用にエンコードします。

エンコーディングの形式 (base64 または quoted-printable) は、`header_encoding' 属性に基づきます。
@end deffn

@geindex header_encode_lines() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset header_encode_lines}@anchor{3bb6}
@deffn {メソッド} header_encode_lines (string, maxlengths)

`string' を最初にバイト列に変換し、ヘッダ用にエンコードします。

これは @ref{3bb5,,header_encode()} と似ていますが、与えられた引数 `maxlengths' に従って、行の最大長に合うように文字列が調整されるところが異なります。 `maxlengths' はイテレータでなければなりません: このイテレータが返す要素は次の行の最大長を表します。
@end deffn

@geindex body_encode() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset body_encode}@anchor{3bb7}
@deffn {メソッド} body_encode (string)

文字列 `string' をメッセージ本体用にエンコードします。

エンコーディングの形式 (base64 または quoted-printable) は、`body_encoding' 属性に基づきます。
@end deffn

@ref{ffb,,Charset} クラスには、標準的な演算と組み込み関数をサポートするいくつかのメソッドがあります。

@geindex __str__() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset __str__}@anchor{3bb8}
@deffn {メソッド} __str__ ()

`input_charset' を小文字に変換された文字列型として返します。 @code{__repr__()} は、 @code{__str__()} の別名となっています。
@end deffn

@geindex __eq__() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset __eq__}@anchor{3bb9}
@deffn {メソッド} __eq__ (other)

このメソッドは、2つの @ref{ffb,,Charset} インスタンスが同じかどうかをチェックするのに使います。
@end deffn

@geindex __ne__() (email.charset.Charset のメソッド)
@anchor{library/email charset email charset Charset __ne__}@anchor{3bba}
@deffn {メソッド} __ne__ (other)

このメソッドは、2つの @ref{ffb,,Charset} インスタンスが異なるかどうかをチェックするのに使います。
@end deffn
@end deffn

The @code{email.charset} module also provides the following functions for adding
new entries to the global character set, alias, and codec registries:

@geindex add_charset() (email.charset モジュール)
@anchor{library/email charset email charset add_charset}@anchor{3bbb}
@deffn {の関数} email.charset.add_charset (charset, header_enc=None, body_enc=None, output_charset=None)

文字の属性をグローバルなレジストリに追加します。

`charset' は入力用の文字集合で、その文字集合の正式名称を指定する必要があります。

オプション引数 `header_enc' および `body_enc' は quoted-printable エンコーディングを表す @code{charset.QP} か、base64 エンコーディングを表す @code{charset.BASE64}、最短の quoted-printable または base64 エンコーディングを表す @code{charset.SHORTEST}、あるいはエンコーディングなしの @code{None} のいずれかになります。@code{SHORTEST} が使えるのは `header_enc' だけです。デフォルトの値はエンコーディングなしの @code{None} になっています。

オプション引数 `output_charset' には出力用の文字集合が入ります。 @code{Charset.convert()} が呼ばれたときの変換はまず入力用の文字集合を Unicode に変換し、それから出力用の文字集合に変換されます。デフォルトでは、出力は入力と同じ文字集合になっています。

`input_charset' および `output_charset' はこのモジュール中の文字集合-コーデック対応表にある Unicode コーデックエントリである必要があります。モジュールがまだ対応していないコーデックを追加するには、 @ref{3bbc,,add_codec()} を使ってください。より詳しい情報については @ref{1c,,codecs} モジュールの文書を参照してください。

グローバルな文字集合用のレジストリは、モジュールのグローバル辞書 @code{CHARSETS} 内に保持されています。
@end deffn

@geindex add_alias() (email.charset モジュール)
@anchor{library/email charset email charset add_alias}@anchor{3bbd}
@deffn {の関数} email.charset.add_alias (alias, canonical)

文字集合の別名を追加します。`alias' はその別名で、たとえば @code{latin-1} のように指定します。`canonical' はその文字集合の正式名称で、たとえば @code{iso-8859-1} のように指定します。

文字集合のグローバルな別名用レジストリは、モジュールのグローバル辞書 @code{ALIASES} 内に保持されています。
@end deffn

@geindex add_codec() (email.charset モジュール)
@anchor{library/email charset email charset add_codec}@anchor{3bbc}
@deffn {の関数} email.charset.add_codec (charset, codecname)

与えられた文字集合の文字と Unicode との変換を行うコーデックを追加します。

`charset' は文字集合の正式な名前です。 `codecname' は、 @ref{169,,str} の @ref{ad2,,encode()} メソッドの第 2 引数で使える Python コーデックの名前です。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email encoders エンコーダー,email utils Miscellaneous utilities,email charset 文字集合の表現,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email encoders doc}@anchor{3bbe}@anchor{library/email encoders email-encoders-encoders}@anchor{3bbf}@anchor{library/email encoders module-email encoders}@anchor{42}@anchor{library/email encoders translation-repo}@anchor{3bc0}
@subsubsection @code{email.encoders}: エンコーダー


@geindex module; email.encoders

`ソースコード:' Lib/email/encoders.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/encoders.py}


__________________________________________________________________


このモジュールは、レガシーな (@code{Compat32}) email APIの一部です。新しいAPIでは、この機能は @ref{1c5d,,set_content()} メソッドの*cte*パラメータによって提供されます。

このモジュールはPython3で非推奨になりました。 @ref{ffa,,MIMEText} クラスはクラスのインスタンス化中に渡された `_subtype' と `_charset' の値を使ってcontent typeとCTEヘッダを設定するので、ここで提供されている関数は明示的に呼び出すべきではありません。

この節の以降のテキストはモジュールの元々のドキュメントです。

何もないところから @ref{581,,Message} を作成するときしばしば必要になるのが、ペイロードをメールサーバに通すためにエンコードすることです。これはとくにバイナリデータを含んだ @code{image/*} や @code{text/*} タイプのメッセージで必要です。

The @ref{3f,,email} package provides some convenient encoders in its
@code{encoders} module.  These encoders are actually used by the
@ref{3ba0,,MIMEAudio} and @ref{3b33,,MIMEImage}
class constructors to provide default encodings.  All encoder functions take
exactly one argument, the message object to encode.  They usually extract the
payload, encode it, and reset the payload to this newly encoded value.  They
should also set the @code{Content-Transfer-Encoding} header as appropriate.

マルチパートメッセージにこれら関数を使うことは全く無意味です。それらは各々のサブパートごとに適用されるべきものです。メッセージがマルチパートのものを渡すと @ref{198,,TypeError} が発生します。

提供されているエンコーディング関数は以下のとおりです:

@geindex encode_quopri() (email.encoders モジュール)
@anchor{library/email encoders email encoders encode_quopri}@anchor{3bc1}
@deffn {の関数} email.encoders.encode_quopri (msg)

ペイロードを quoted-printable 形式にエンコードし、 @code{Content-Transfer-Encoding} ヘッダを @code{quoted-printable} @footnote{
注意: @ref{3bc1,,encode_quopri()} を使ってエンコードすると、データ中のタブ文字や空白文字もエンコードされます。
} に設定します。これはそのペイロードのほとんどが通常の印刷可能な文字からなっているが、印刷不可能な文字がすこしだけあるときのエンコード方法として適しています。
@end deffn

@geindex encode_base64() (email.encoders モジュール)
@anchor{library/email encoders email encoders encode_base64}@anchor{3bc2}
@deffn {の関数} email.encoders.encode_base64 (msg)

ペイロードを base64 形式でエンコードし、 @code{Content-Transfer-Encoding} ヘッダを @code{base64} に変更します。これはペイロード中のデータのほとんどが印刷不可能な文字である場合に適しています。 quoted-printable 形式よりも結果としてはコンパクトなサイズになるからです。 base64 形式の欠点は、これが人間にはまったく読めないテキストになってしまうことです。
@end deffn

@geindex encode_7or8bit() (email.encoders モジュール)
@anchor{library/email encoders email encoders encode_7or8bit}@anchor{3bc3}
@deffn {の関数} email.encoders.encode_7or8bit (msg)

これは実際にはペイロードを変更はしませんが、ペイロードの形式に応じて @code{Content-Transfer-Encoding} ヘッダを @code{7bit} あるいは @code{8bit} に適した形に設定します。
@end deffn

@geindex encode_noop() (email.encoders モジュール)
@anchor{library/email encoders email encoders encode_noop}@anchor{3bc4}
@deffn {の関数} email.encoders.encode_noop (msg)

これは何もしないエンコーダです。 @code{Content-Transfer-Encoding} ヘッダを設定さえしません。
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email utils Miscellaneous utilities,email iterators イテレータ,email encoders エンコーダー,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email utils doc}@anchor{3bc5}@anchor{library/email utils email-utils-miscellaneous-utilities}@anchor{3bc6}@anchor{library/email utils module-email utils}@anchor{54}@anchor{library/email utils translation-repo}@anchor{3bc7}
@subsubsection @code{email.utils}: Miscellaneous utilities


@geindex module; email.utils

`ソースコード:' Lib/email/utils.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/utils.py}


__________________________________________________________________


There are a couple of useful utilities provided in the @code{email.utils}
module:

@geindex localtime() (email.utils モジュール)
@anchor{library/email utils email utils localtime}@anchor{2f7}
@deffn {の関数} email.utils.localtime (dt=None)

Return local time as an aware datetime object.  If called without
arguments, return current time.  Otherwise `dt' argument should be a
@ref{4e2,,datetime} instance, and it is converted to the local time
zone according to the system time zone database.  If `dt' is naive (that
is, @code{dt.tzinfo} is @code{None}), it is assumed to be in local time.


Added in version 3.3.



Deprecated since version 3.12, removed in version 3.14: The `isdst' parameter.

@end deffn

@geindex make_msgid() (email.utils モジュール)
@anchor{library/email utils email utils make_msgid}@anchor{3bc8}
@deffn {の関数} email.utils.make_msgid (idstring=None, domain=None)

Returns a string suitable for an 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html}-compliant
@code{Message-ID} header.  Optional `idstring' if given, is a string
used to strengthen the uniqueness of the message id.  Optional `domain' if
given provides the portion of the msgid after the '@@'.  The default is the
local hostname.  It is not normally necessary to override this default, but
may be useful certain cases, such as a constructing distributed system that
uses a consistent domain name across multiple hosts.


バージョン 3.2 で変更: `domain' キーワードが追加されました。

@end deffn

The remaining functions are part of the legacy (@code{Compat32}) email API.  There
is no need to directly use these with the new API, since the parsing and
formatting they provide is done automatically by the header parsing machinery
of the new API.

@geindex quote() (email.utils モジュール)
@anchor{library/email utils email utils quote}@anchor{3bc9}
@deffn {の関数} email.utils.quote (str)

文字列 `str' 内のバックスラッシュをバックスラッシュ2つに置換した新しい文字列を返します。また、ダブルクォートはバックスラッシュ + ダブルクォートに置換されます。
@end deffn

@geindex unquote() (email.utils モジュール)
@anchor{library/email utils email utils unquote}@anchor{3ad7}
@deffn {の関数} email.utils.unquote (str)

文字列 `str' の `クォートを外した' 新しい文字列を返します。`str' の先頭と末尾がダブルクォートだった場合、それらは取り除かれます。同様に `str' の先頭と末尾が角ブラケット (<、>) だった場合もそれらは取り除かれます。
@end deffn

@geindex parseaddr() (email.utils モジュール)
@anchor{library/email utils email utils parseaddr}@anchor{4f4}
@deffn {の関数} email.utils.parseaddr (address, *, strict=True)

@code{To} や @code{Cc} のようなフィールドを持つアドレスをパースして、構成要素の `実名' と `電子メールアドレス' を取り出します。 パースに成功した場合、これらの情報持つタプルを返します。失敗した場合は 2 要素のタプル @code{('@w{'}, '@w{'})} を返します。

If `strict' is true, use a strict parser which rejects malformed inputs.


バージョン 3.13 で変更: Add `strict' optional parameter and reject malformed inputs by default.

@end deffn

@geindex formataddr() (email.utils モジュール)
@anchor{library/email utils email utils formataddr}@anchor{13b2}
@deffn {の関数} email.utils.formataddr (pair, charset='utf-8')

@ref{4f4,,parseaddr()} の逆で、2 要素のタプル @code{(realname, email_address)} を取って @code{To} や @code{Cc} ヘッダに適した文字列を返します。タプル `pair' の第1要素が偽である場合、第2要素の値をそのまま返します。

任意の `charset' は、 @code{realname} が非 ASCII 文字を含んでいる場合にその 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://datatracker.ietf.org/doc/html/rfc2047.html} エンコーディングに使われる文字集合です。@ref{169,,str} か @ref{ffb,,Charset} のインスタンスで、デフォルトは @code{utf-8} です。


バージョン 3.3 で変更: `charset' オプションが追加されました。

@end deffn

@geindex getaddresses() (email.utils モジュール)
@anchor{library/email utils email utils getaddresses}@anchor{4f3}
@deffn {の関数} email.utils.getaddresses (fieldvalues, *, strict=True)

This method returns a list of 2-tuples of the form returned by @code{parseaddr()}.
`fieldvalues' is a sequence of header field values as might be returned by
@ref{3b81,,Message.get_all}.

If `strict' is true, use a strict parser which rejects malformed inputs.

Here's a simple example that gets all the recipients of a message:

@example
from email.utils import getaddresses

tos = msg.get_all('to', [])
ccs = msg.get_all('cc', [])
resent_tos = msg.get_all('resent-to', [])
resent_ccs = msg.get_all('resent-cc', [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
@end example


バージョン 3.13 で変更: Add `strict' optional parameter and reject malformed inputs by default.

@end deffn

@geindex parsedate() (email.utils モジュール)
@anchor{library/email utils email utils parsedate}@anchor{3bca}
@deffn {の関数} email.utils.parsedate (date)

@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} の規則に基づいて日付の解析を試みます。
しかしながらメイラーによっては指定された形式に従っていないものがあるので、その場合 @ref{3bca,,parsedate()} は正しく推測しようとします。
`date' は @code{"Mon, 20 Nov 1995 19:12:08 -0500"} のような 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} 形式の日付を含む文字列です。
日付の解析に成功した場合、 @ref{3bca,,parsedate()} は関数 @ref{1401,,time.mktime()} に直接渡せる形式の 9 要素からなるタプルを返します。
失敗した場合は @code{None} を返します。
返されるタプルの 6、7、8番目の添字は使用不可なので注意してください。
@end deffn

@geindex parsedate_tz() (email.utils モジュール)
@anchor{library/email utils email utils parsedate_tz}@anchor{1c23}
@deffn {の関数} email.utils.parsedate_tz (date)

Performs the same function as @ref{3bca,,parsedate()}, but returns either @code{None} or
a 10-tuple; the first 9 elements make up a tuple that can be passed directly to
@ref{1401,,time.mktime()}, and the tenth is the offset of the date's timezone from UTC
(which is the official term for Greenwich Mean Time) @footnote{
注意: この時間帯のオフセット値は @code{time.timezone} の値と符号が逆です。これは @code{time.timezone} が POSIX 標準に準拠しているのに対して、こちらは 
@geindex RFC; RFC 2822
@uref{https://datatracker.ietf.org/doc/html/rfc2822.html,RFC 2822} に準拠しているからです。
}.  If the input string
has no timezone, the last element of the tuple returned is @code{0}, which represents
UTC. Note that indexes 6, 7, and 8 of the result tuple are not usable.
@end deffn

@geindex parsedate_to_datetime() (email.utils モジュール)
@anchor{library/email utils email utils parsedate_to_datetime}@anchor{12d4}
@deffn {の関数} email.utils.parsedate_to_datetime (date)

The inverse of @ref{12d3,,format_datetime()}.  Performs the same function as
@ref{3bca,,parsedate()}, but on success returns a @ref{4e2,,datetime};
otherwise @code{ValueError} is raised if `date' contains an invalid value such
as an hour greater than 23 or a timezone offset not between -24 and 24 hours.
If the input date has a timezone of @code{-0000}, the @code{datetime} will be a naive
@code{datetime}, and if the date is conforming to the RFCs it will represent a
time in UTC but with no indication of the actual source timezone of the
message the date comes from.  If the input date has any other valid timezone
offset, the @code{datetime} will be an aware @code{datetime} with the
corresponding a @ref{12d5,,timezone} @ref{7f6,,tzinfo}.


Added in version 3.3.

@end deffn

@geindex mktime_tz() (email.utils モジュール)
@anchor{library/email utils email utils mktime_tz}@anchor{3bcb}
@deffn {の関数} email.utils.mktime_tz (tuple)

@ref{1c23,,parsedate_tz()} が返す 10 要素のタプルを UTC のタイムスタンプ (エポックからの秒数) に変換します。与えられた時間帯が @code{None} である場合、時間帯として現地時間 (localtime) が仮定されます。
@end deffn

@geindex formatdate() (email.utils モジュール)
@anchor{library/email utils email utils formatdate}@anchor{1683}
@deffn {の関数} email.utils.formatdate (timeval=None, localtime=False, usegmt=False)

日付を 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://datatracker.ietf.org/doc/html/rfc2822.html} 形式の文字列で返します。例:

@example
Fri, 09 Nov 2001 01:08:47 -0000
@end example

Optional `timeval' if given is a floating-point time value as accepted by
@ref{13d8,,time.gmtime()} and @ref{1712,,time.localtime()}, otherwise the current time is
used.

オプション引数 `localtime' はフラグです。@code{True} の場合、この関数は `timeval' を解析して UTC の代わりに現地のタイムゾーンに対する日付を返します。おそらく夏時間も考慮するでしょう。デフォルトは @code{False} で、UTC が使われます。

オプション引数 `usegmt' はフラグです。@code{True} の場合、この関数はタイムゾーンを数値の @code{-0000} ではなく ascii 文字列 @code{GMT} として日付を出力します。これはプロトコルによっては (例えば HTTP) 必要です。これは `localtime' が @code{False} のときのみ適用されます。デフォルトは @code{False} です。
@end deffn

@geindex format_datetime() (email.utils モジュール)
@anchor{library/email utils email utils format_datetime}@anchor{12d3}
@deffn {の関数} email.utils.format_datetime (dt, usegmt=False)

Like @code{formatdate}, but the input is a @ref{34,,datetime} instance.  If it is
a naive datetime, it is assumed to be "UTC with no information about the
source timezone", and the conventional @code{-0000} is used for the timezone.
If it is an aware @code{datetime}, then the numeric timezone offset is used.
If it is an aware timezone with offset zero, then `usegmt' may be set to
@code{True}, in which case the string @code{GMT} is used instead of the numeric
timezone offset.  This provides a way to generate standards conformant HTTP
date headers.


Added in version 3.3.

@end deffn

@geindex decode_rfc2231() (email.utils モジュール)
@anchor{library/email utils email utils decode_rfc2231}@anchor{3bcc}
@deffn {の関数} email.utils.decode_rfc2231 (s)

@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} に従って文字列 `s' をデコードします。
@end deffn

@geindex encode_rfc2231() (email.utils モジュール)
@anchor{library/email utils email utils encode_rfc2231}@anchor{3bcd}
@deffn {の関数} email.utils.encode_rfc2231 (s, charset=None, language=None)

@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} に従って `s' をエンコードします。オプション引数 `charset' および `language' が与えられた場合、これらは文字セット名と言語名として使われます。もしこれらのどちらも与えられていない場合、 `s' はそのまま返されます。 `charset' は与えられているが `language' が与えられていない場合、文字列 `s' は `language' の空文字列を使ってエンコードされます。
@end deffn

@geindex collapse_rfc2231_value() (email.utils モジュール)
@anchor{library/email utils email utils collapse_rfc2231_value}@anchor{3b8e}
@deffn {の関数} email.utils.collapse_rfc2231_value (value, errors='replace', fallback_charset='us-ascii')

ヘッダのパラメータが 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} 形式でエンコードされている場合、 @ref{3b8d,,Message.get_param} は 3 要素からなるタプルを返すことがあります。ここには、そのパラメータの文字セット、言語、および値の順に格納されています。 @ref{3b8e,,collapse_rfc2231_value()} はこのパラメータをひとつの Unicode 文字列にまとめます。オプション引数 `errors' は @ref{169,,str} の @ref{ad2,,encode()} メソッドの引数 `errors' に渡されます。このデフォルト値は @code{'replace'} となっています。オプション引数 `fallback_charset' は、もし 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} ヘッダの使用している文字セットが Python の知っているものではなかった場合の非常用文字セットとして使われます。デフォルトでは、この値は @code{'us-ascii'} です。

便宜上、 @ref{3b8e,,collapse_rfc2231_value()} に渡された引数 `value' がタプルでない場合には、これは文字列でなければなりません。その場合にはクォートを除いた文字列を返します。
@end deffn

@geindex decode_params() (email.utils モジュール)
@anchor{library/email utils email utils decode_params}@anchor{1824}
@deffn {の関数} email.utils.decode_params (params)

@geindex RFC; RFC 2231
RFC 2231@footnote{https://datatracker.ietf.org/doc/html/rfc2231.html} に従って引数のリストをデコードします。 `params' は @code{(content-type, string-value)} のような形式の 2 要素タプルです。
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node email iterators イテレータ,,email utils Miscellaneous utilities,email --- 電子メールと MIME 処理のためのパッケージ
@anchor{library/email iterators doc}@anchor{3bce}@anchor{library/email iterators email-iterators-iterators}@anchor{3bcf}@anchor{library/email iterators module-email iterators}@anchor{47}@anchor{library/email iterators translation-repo}@anchor{3bd0}
@subsubsection @code{email.iterators}: イテレータ


@geindex module; email.iterators

`ソースコード:' Lib/email/iterators.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/email/iterators.py}


__________________________________________________________________


Iterating over a message object tree is fairly easy with the
@ref{3b96,,Message.walk} method.  The
@code{email.iterators} module provides some useful higher level iterations over
message object trees.

@geindex body_line_iterator() (email.iterators モジュール)
@anchor{library/email iterators email iterators body_line_iterator}@anchor{3bd1}
@deffn {の関数} email.iterators.body_line_iterator (msg, decode=False)

このイテレータは `msg' 中のすべてのサブパートに含まれるペイロードをすべて順にたどっていき、ペイロード内の文字列を 1 行ずつ返します。サブパートのヘッダはすべて無視され、Python 文字列でないペイロードからなるサブパートも無視されます。これは @ref{20a6,,readline()} を使って、ファイルからメッセージを (ヘッダだけとばして) フラットなテキストとして読むのにいくぶん似ているかもしれません。

オプション引数 `decode' は、 @ref{13e5,,Message.get_payload} にそのまま渡されます。
@end deffn

@geindex typed_subpart_iterator() (email.iterators モジュール)
@anchor{library/email iterators email iterators typed_subpart_iterator}@anchor{3bd2}
@deffn {の関数} email.iterators.typed_subpart_iterator (msg, maintype='text', subtype=None)

このイテレータは `msg' 中のすべてのサブパートをたどり、それらの中で指定されたMIME 形式 `maintype' と `subtype' をもつようなパートのみを返します。

`subtype' は省略可能であることに注意してください。これが省略された場合、サブパートの MIME 形式は maintype のみがチェックされます。じつは `maintype' も省略可能で、その場合にはデフォルトは @code{text} です。

つまり、デフォルトでは @ref{3bd2,,typed_subpart_iterator()} は MIME 形式 @code{text/*} をもつサブパートを順に返していくというわけです。
@end deffn

以下の関数は役に立つデバッグ用ツールとして追加されたもので、パッケージとして公式なサポートのあるインターフェイスでは `ありません'。

@geindex _structure() (email.iterators モジュール)
@anchor{library/email iterators email iterators _structure}@anchor{3bd3}
@deffn {の関数} email.iterators._structure (msg, fp=None, level=0, include_default=False)

そのメッセージオブジェクト構造の content-type をインデントつきで表示します。例えば:

@c import email
@c from email.iterators import _structure
@c somefile = open('../Lib/test/test_email/data/msg_02.txt')

@example
>>> msg = email.message_from_file(somefile)
>>> _structure(msg)
multipart/mixed
    text/plain
    text/plain
    multipart/digest
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
    text/plain
@end example

@c somefile.close()

オプション引数 `fp' は出力を渡すための file-like オブジェクトです。
これは Python の @ref{1177,,print()} 関数が対応できるようになっている必要があります。
`level' は内部的に使用されます。
`include_default' が真の場合、デフォルトの型も出力します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)


@subsubheading 参考



@table @asis

@item @ref{cf,,smtplib} モジュール

SMTP（簡易メール転送プロトコル）クライアント

@item @ref{b1,,poplib} モジュール

POP (Post Office Protocol) クライアント

@item モジュール @ref{78,,imaplib}

IMAP (Internet Message Access Protocol) クライアント

@item @ref{8f,,mailbox} モジュール

Tools for creating, reading, and managing collections of messages on disk
using a variety standard formats.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node json --- JSON エンコーダーとデコーダー,mailbox --- 様々な形式のメールボックスを操作する,email --- 電子メールと MIME 処理のためのパッケージ,インターネット上のデータの操作
@anchor{library/json doc}@anchor{3bd4}@anchor{library/json json-json-encoder-and-decoder}@anchor{3bd5}@anchor{library/json module-json}@anchor{86}@anchor{library/json translation-repo}@anchor{3bd6}
@subsection @code{json} --- JSON エンコーダーとデコーダー


@geindex module; json

`ソースコード:' Lib/json/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/json/__init__.py}


__________________________________________________________________


JSON (JavaScript Object Notation)@footnote{https://json.org} は、 
@geindex RFC; RFC 7159
RFC 7159@footnote{https://datatracker.ietf.org/doc/html/rfc7159.html} (
@geindex RFC; RFC 4627
RFC 4627@footnote{https://datatracker.ietf.org/doc/html/rfc4627.html} を obsolete) と ECMA-404@footnote{https://ecma-international.org/publications-and-standards/standards/ecma-404/} によって定義された軽量のデータ交換用のフォーマットです。 JavaScript のオブジェクトリテラル記法に由来しています (JavaScript@footnote{https://en.wikipedia.org/wiki/JavaScript} の厳密なサブセットではありませんが @footnote{
@uref{https://www.rfc-editor.org/errata_search.php?rfc=7159,RFC 7159 正誤表} で述べられている通り、JSON は (ECMAScript Edition 5.1 の) JavaScript とは逆に、 U+2028 (LINE SEPARATOR) と U+2029 (PARAGRAPH SEPARATOR) が文字列内に含まれることを許容しています。
})。

@cartouche
@quotation 注釈 
The term "object" in the context of JSON processing in Python can be
ambiguous. All values in Python are objects. In JSON, an object refers to
any data wrapped in curly braces, similar to a Python dictionary.
@end quotation
@end cartouche

@cartouche
@quotation 警告 
信頼されていないソースからの JSON データをパースするときは十分注意してください。悪意を持った JSON 文字列はデコーダに著しい量の CPU とメモリリソースを消費させる可能性があります。パースするデータ量を制限することを推奨します。
@end quotation
@end cartouche

このモジュールの API は標準ライブラリの @ref{91,,marshal} や @ref{ab,,pickle} のユーザに馴染み深いものです。

基本的な Python オブジェクト階層のエンコーディング:

@example
>>> import json
>>> json.dumps(['foo', @{'bar': ('baz', None, 1.0, 2)@}])
'["foo", @{"bar": ["baz", null, 1.0, 2]@}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps(@{"c": 0, "b": 0, "a": 0@}, sort_keys=True))
@{"a": 0, "b": 0, "c": 0@}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
@end example

コンパクトなエンコーディング:

@example
>>> import json
>>> json.dumps([1, 2, 3, @{'4': 5, '6': 7@}], separators=(',', ':'))
'[1,2,3,@{"4":5,"6":7@}]'
@end example

見やすい表示:

@example
>>> import json
>>> print(json.dumps(@{'6': 7, '4': 5@}, sort_keys=True, indent=4))
@{
    "4": 5,
    "6": 7
@}
@end example

JSON オブジェクトのエンコーディング方法をカスタマイズする:

@example
>>> import json
>>> def custom_json(obj):
...     if isinstance(obj, complex):
...         return @{'__complex__': True, 'real': obj.real, 'imag': obj.imag@}
...     raise TypeError(f'Cannot serialize object of @{type(obj)@}')
...
>>> json.dumps(1 + 2j, default=custom_json)
'@{"__complex__": true, "real": 1.0, "imag": 2.0@}'
@end example

JSON のデコーディング:

@example
>>> import json
>>> json.loads('["foo", @{"bar":["baz", null, 1.0, 2]@}]')
['foo', @{'bar': ['baz', None, 1.0, 2]@}]
>>> json.loads('"\\"foo\\bar"')
'"foo\x08ar'
>>> from io import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
['streaming API']
@end example

JSON オブジェクトのデコーディング方法をカスタマイズする:

@example
>>> import json
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
>>> json.loads('@{"__complex__": true, "real": 1, "imag": 2@}',
...     object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')
@end example

@ref{f42,,JSONEncoder} の拡張:

@example
>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return super().default(obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']
@end example

Using @code{json} from the shell to validate and pretty-print:

@example
$ echo '@{"json":"obj"@}' | python -m json
@{
    "json": "obj"
@}
$ echo '@{1.2:3.4@}' | python -m json
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
@end example

詳細については @ref{23e,,コマンドライン・インターフェース} を参照してください。

@cartouche
@quotation 注釈 
JSON は YAML@footnote{https://yaml.org/} 1.2 のサブセットです。このモジュールのデフォルト設定 (特に、デフォルトの `セパレータ' 値) で生成される JSON は YAML 1.0 および 1.1 のサブセットでもあります。このモジュールは YAML シリアライザとしても使えます。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
このモジュールのエンコーダとデコーダは、デフォルトで入力順と出力順を保つようになっています。根底のコンテナに順序がない場合のみ、順序が失われます。
@end quotation
@end cartouche

@menu
* 基本的な使い方: 基本的な使い方<4>. 
* エンコーダとデコーダ:: 
* 例外: 例外<20>. 
* 標準への準拠と互換性:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<5>. 

@end menu

@node 基本的な使い方<4>,エンコーダとデコーダ,,json --- JSON エンコーダーとデコーダー
@anchor{library/json basic-usage}@anchor{3bd7}
@subsubsection 基本的な使い方


@geindex dump() (json モジュール)
@anchor{library/json json dump}@anchor{f40}
@deffn {の関数} json.dump (obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

この @ref{3bd8,,PythonからJSONへの変換表} を使って、 `obj' を JSON 形式の `fp' (@code{.write()} がサポートされている @ref{17ac,,file-like object}) へのストリームとして直列化します。

@cartouche
@quotation 注釈 
@ref{ab,,pickle} や @ref{91,,marshal} とは異なり JSON はフレーム付きのプロトコルではないので、同じ `fp' に対し繰り返し @ref{f40,,dump()} を呼び、複数のオブジェクトを直列化しようとすると、不正な JSON ファイルが作られてしまいます。
@end quotation
@end cartouche

@*パラメータ: 

@itemize *

@item 
@code{obj} (@ref{c7e,,object}) -- The Python object to be serialized.

@item 
@code{fp} (@ref{17ac,,file-like object}) -- The file-like object `obj' will be serialized to.
The @code{json} module always produces @ref{169,,str} objects,
not @ref{192,,bytes} objects,
therefore @code{fp.write()} must support @ref{169,,str} input.

@item 
@code{skipkeys} (@ref{3c3,,bool}) -- If @code{True}, keys that are not of a basic type
(@ref{169,,str}, @ref{19b,,int}, @ref{196,,float}, @ref{3c3,,bool}, @code{None})
will be skipped instead of raising a @ref{198,,TypeError}.
Default @code{False}.

@item 
@code{ensure_ascii} (@ref{3c3,,bool}) -- If @code{True} (the default), the output is guaranteed to
have all incoming non-ASCII and non-printable characters escaped.
If @code{False}, all characters will be outputted as-is, except for
the characters that must be escaped: quotation mark, reverse solidus,
and the control characters U+0000 through U+001F.

@item 
@code{check_circular} (@ref{3c3,,bool}) -- If @code{False}, the circular reference check for container types is skipped
and a circular reference will result in a @ref{f68,,RecursionError} (or worse).
Default @code{True}.

@item 
@code{allow_nan} (@ref{3c3,,bool}) -- If @code{False}, serialization of out-of-range @ref{196,,float} values
(@code{nan}, @code{inf}, @code{-inf}) will result in a @ref{2ec,,ValueError},
in strict compliance with the JSON specification.
If @code{True} (the default), their JavaScript equivalents
(@code{NaN}, @code{Infinity}, @code{-Infinity}) are used.

@item 
@code{cls} (a @ref{f42,,JSONEncoder} subclass) -- If set, a custom JSON encoder with the
@ref{3bd9,,default()} method overridden,
for serializing into custom datatypes.
If @code{None} (the default), @code{JSONEncoder} is used.

@item 
@code{indent} (@ref{19b,,int}@code{ | }@ref{169,,str}@code{ | }@code{None}) -- If a positive integer or string, JSON array elements and
object members will be pretty-printed with that indent level.
A positive integer indents that many spaces per level;
a string (such as @code{"\t"}) is used to indent each level.
If zero, negative, or @code{""} (the empty string),
only newlines are inserted.
If @code{None} (the default), the most compact representation is used.

@item 
@code{separators} (@ref{614,,tuple}@code{ | }@code{None}) -- A two-tuple: @code{(item_separator, key_separator)}.
If @code{None} (the default), `separators' defaults to
@code{(', ', ': ')} if `indent' is @code{None},
and @code{(',', ': ')} otherwise.
For the most compact JSON,
specify @code{(',', ':')} to eliminate whitespace.

@item 
@code{default} (@ref{2d7b,,callable} | None) -- A function that is called for objects that can't otherwise be serialized.
It should return a JSON encodable version of the object
or raise a @ref{198,,TypeError}.
If @code{None} (the default), @code{TypeError} is raised.

@item 
@code{sort_keys} (@ref{3c3,,bool}) -- If @code{True}, dictionaries will be outputted sorted by key.
Default @code{False}.
@end itemize



バージョン 3.2 で変更: 整数に加えて、文字列が `indent' に使用できるようになりました。



バージョン 3.4 で変更: `indent' が @code{None} でなければ @code{(',', ': ')} がデフォルトで使われます。



バージョン 3.6 で変更: すべてのオプション引数は、 @ref{5a5,,キーワード専用} になりました。

@end deffn

@geindex dumps() (json モジュール)
@anchor{library/json json dumps}@anchor{f41}
@deffn {の関数} json.dumps (obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

この @ref{3bd8,,変換表} を使って、`obj' を JSON 形式の @ref{169,,str} オブジェクトに直列化します。引数は @ref{f40,,dump()} と同じ意味です。

@cartouche
@quotation 注釈 
JSON のキー値ペアのキーは、常に @ref{169,,str} 型です。辞書が JSON に変換されるとき、辞書の全てのキーは文字列へ強制的に変換が行われます。この結果として、辞書が JSON に変換され、それから辞書に戻された場合、辞書は元のものと同じではありません。つまり文字列ではないキーを持っている場合、 @code{loads(dumps(x)) != x} となるということです。
@end quotation
@end cartouche
@end deffn

@geindex load() (json モジュール)
@anchor{library/json json load}@anchor{eb2}
@deffn {の関数} json.load (fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize `fp' to a Python object
using the @ref{3bda,,JSON-to-Python conversion table}.

@*パラメータ: 

@itemize *

@item 
@code{fp} (@ref{17ac,,file-like object}) -- A @code{.read()}-supporting @ref{206d,,text file} or @ref{206e,,binary file}
containing the JSON document to be deserialized.

@item 
@code{cls} (a @ref{f43,,JSONDecoder} subclass) -- If set, a custom JSON decoder.
Additional keyword arguments to @code{load()}
will be passed to the constructor of `cls'.
If @code{None} (the default), @code{JSONDecoder} is used.

@item 
@code{object_hook} (@ref{2d7b,,callable} | None) -- If set, a function that is called with the result of
any JSON object literal decoded (a @ref{183,,dict}).
The return value of this function will be used
instead of the @ref{183,,dict}.
This feature can be used to implement custom decoders,
for example JSON-RPC@footnote{https://www.jsonrpc.org} class hinting.
Default @code{None}.

@item 
@code{object_pairs_hook} (@ref{2d7b,,callable} | None) -- If set, a function that is called with the result of
any JSON object literal decoded with an ordered list of pairs.
The return value of this function will be used
instead of the @ref{183,,dict}.
This feature can be used to implement custom decoders.
If `object_hook' is also set, `object_pairs_hook' takes priority.
Default @code{None}.

@item 
@code{parse_float} (@ref{2d7b,,callable} | None) -- If set, a function that is called with
the string of every JSON float to be decoded.
If @code{None} (the default), it is equivalent to @code{float(num_str)}.
This can be used to parse JSON floats into custom datatypes,
for example @ref{1fe,,decimal.Decimal}.

@item 
@code{parse_int} (@ref{2d7b,,callable} | None) -- If set, a function that is called with
the string of every JSON int to be decoded.
If @code{None} (the default), it is equivalent to @code{int(num_str)}.
This can be used to parse JSON integers into custom datatypes,
for example @ref{196,,float}.

@item 
@code{parse_constant} (@ref{2d7b,,callable} | None) -- If set, a function that is called with one of the following strings:
@code{'-Infinity'}, @code{'Infinity'}, or @code{'NaN'}.
This can be used to raise an exception
if invalid JSON numbers are encountered.
Default @code{None}.
@end itemize


@*例外: 

@itemize *

@item 
@ref{1022,,JSONDecodeError} -- When the data being deserialized is not a valid JSON document.

@item 
@ref{c08,,UnicodeDecodeError} -- When the data being deserialized does not contain
UTF-8, UTF-16 or UTF-32 encoded data.
@end itemize



バージョン 3.1 で変更: 


@itemize *

@item 
Added the optional `object_pairs_hook' parameter.

@item 
'null', 'true', 'false' に対して `parse_constant' は呼びされません。
@end itemize



バージョン 3.6 で変更: 


@itemize *

@item 
すべてのオプション引数は、 @ref{5a5,,キーワード専用} になりました。

@item 
`fp' には @ref{206e,,binary file} 型も使えるようになりました。入力のエンコーディングは UTF-8, UTF-16, UTF-32 のいずれかでなければなりません。
@end itemize



バージョン 3.11 で変更: デフォルトの `parse_int' である @ref{19b,,int()} は、インタープリタの @ref{80b,,integer string conversion length limitation} により整数文字列の最大長を制限するようになり、サービスを妨害する攻撃を拒否します。

@end deffn

@geindex loads() (json モジュール)
@anchor{library/json json loads}@anchor{b4e}
@deffn {の関数} json.loads (s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Identical to @ref{eb2,,load()}, but instead of a file-like object,
deserialize `s' (a @ref{169,,str}, @ref{192,,bytes} or @ref{344,,bytearray}
instance containing a JSON document) to a Python object using this
@ref{3bda,,conversion table}.


バージョン 3.6 で変更: `s' には @ref{192,,bytes}  型と @ref{344,,bytearray} 型も使えるようになりました。
入力エンコーディングは UTF-8, UTF-16, UTF-32 のいずれかでなければなりません。



バージョン 3.9 で変更: キーワード引数 `encoding' が削除されました。

@end deffn

@node エンコーダとデコーダ,例外<20>,基本的な使い方<4>,json --- JSON エンコーダーとデコーダー
@anchor{library/json encoders-and-decoders}@anchor{3bdb}
@subsubsection エンコーダとデコーダ


@geindex JSONDecoder (json のクラス)
@anchor{library/json json JSONDecoder}@anchor{f43}
@deffn {クラス} json.JSONDecoder (*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)

単純な JSON デコーダ。

デフォルトではデコーディングの際、以下の変換を行います:
@anchor{library/json json-to-py-table}@anchor{3bda}

@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} 
@headitem

JSON

@tab

Python

@item

object

@tab

dict

@item

array

@tab

list

@item

string

@tab

str

@item

number (int)

@tab

int

@item

number (real)

@tab

浮動小数点数

@item

true

@tab

True

@item

false

@tab

False

@item

null

@tab

None

@end multitable


また、このデコーダは @code{NaN}, @code{Infinity}, @code{-Infinity} を対応する @code{float} の値として、JSON の仕様からは外れますが、理解します。

`object_hook' is an optional function that will be called with the result of
every JSON object decoded and its return value will be used in place of the
given @ref{183,,dict}.  This can be used to provide custom deserializations
(e.g. to support JSON-RPC@footnote{https://www.jsonrpc.org} class hinting).

`object_pairs_hook' is an optional function that will be called with the
result of every JSON object decoded with an ordered list of pairs.  The
return value of `object_pairs_hook' will be used instead of the
@ref{183,,dict}.  This feature can be used to implement custom decoders.  If
`object_hook' is also defined, the `object_pairs_hook' takes priority.


バージョン 3.1 で変更: `object_pairs_hook' のサポートが追加されました。


`parse_float' is an optional function that will be called with the string of
every JSON float to be decoded.  By default, this is equivalent to
@code{float(num_str)}.  This can be used to use another datatype or parser for
JSON floats (e.g. @ref{1fe,,decimal.Decimal}).

`parse_int' is an optional function that will be called with the string of
every JSON int to be decoded.  By default, this is equivalent to
@code{int(num_str)}.  This can be used to use another datatype or parser for
JSON integers (e.g. @ref{196,,float}).

`parse_constant' is an optional function that will be called with one of the
following strings: @code{'-Infinity'}, @code{'Infinity'}, @code{'NaN'}.  This can be
used to raise an exception if invalid JSON numbers are encountered.

`strict' が false (デフォルトは @code{True}) の場合、制御文字を文字列に含めることができます。ここで言う制御文字とは、@code{'\t'} (タブ)、@code{'\n'}、@code{'\r'}、@code{'\0'} を含む 0-31 の範囲のコードを持つ文字のことです。

脱直列化しようとしているデータが不正な JSON ドキュメントだった場合、 @ref{1022,,JSONDecodeError} が送出されます。


バージョン 3.6 で変更: すべての引数は、 @ref{5a5,,キーワード専用} になりました。


@geindex decode() (json.JSONDecoder のメソッド)
@anchor{library/json json JSONDecoder decode}@anchor{3bdc}
@deffn {メソッド} decode (s)

`s' (@ref{169,,str} インスタンスで JSON 文書を含むもの) の Python 表現を返します。

不正な JSON ドキュメントが与えられた場合、 @ref{1022,,JSONDecodeError} が送出されます。
@end deffn

@geindex raw_decode() (json.JSONDecoder のメソッド)
@anchor{library/json json JSONDecoder raw_decode}@anchor{3bdd}
@deffn {メソッド} raw_decode (s)

`s' (@ref{169,,str} インスタンスで JSON 文書で始まるもの) から JSON 文書をデコードし、Python 表現と `s' の文書の終わるところのインデックスからなる 2 要素のタプルを返します。

このメソッドは後ろに余分なデータを従えた文字列から JSON 文書をデコードするのに使えます。
@end deffn
@end deffn

@geindex JSONEncoder (json のクラス)
@anchor{library/json json JSONEncoder}@anchor{f42}
@deffn {クラス} json.JSONEncoder (*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Python データ構造に対する拡張可能な JSON エンコーダ。

デフォルトでは以下のオブジェクトと型をサポートします:
@anchor{library/json py-to-json-table}@anchor{3bd8}

@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

Python

@tab

JSON

@item

dict

@tab

object

@item

list, tuple

@tab

array

@item

str

@tab

string

@item

int、float と int や float の派生列挙型

@tab

number

@item

True

@tab

true

@item

False

@tab

false

@item

None

@tab

null

@end multitable



バージョン 3.4 で変更: int と float の派生列挙型クラスの対応が追加されました。


このクラスを拡張して他のオブジェクトも認識するようにするには、サブクラスを作って @ref{3bd9,,default()} メソッドを次のように実装します。もう一つ別のメソッドでオブジェクト @code{o} に対する直列化可能なオブジェクトを返すものを呼び出すようにします。変換できない時はスーパークラスの実装を (@ref{198,,TypeError} を送出させるために) 呼ばなければなりません。

If `skipkeys' is false (the default), a @ref{198,,TypeError} will be raised when
trying to encode keys that are not @ref{169,,str}, @ref{19b,,int}, @ref{196,,float},
@ref{3c3,,bool} or @code{None}.  If `skipkeys' is true, such items are simply skipped.

If `ensure_ascii' is true (the default), the output is guaranteed to
have all incoming non-ASCII and non-printable characters escaped.
If `ensure_ascii' is false, all characters will be output as-is, except for
the characters that must be escaped: quotation mark, reverse solidus,
and the control characters U+0000 through U+001F.

`check_circular' が true (デフォルト) ならば、リスト、辞書および自作でエンコードしたオブジェクトは循環参照がないかエンコード中にチェックされ、無限再帰 (これは @ref{f68,,RecursionError} を引き起こします) を防止します。 @code{True} でない場合は、そういったチェックは施されません。

`allow_nan' が true (デフォルト) ならば、 @code{NaN}, @code{Infinity}, @code{-Infinity} はそのままエンコードされます。この振る舞いは JSON 仕様に従っていませんが、大半の JavaScript ベースのエンコーダ、デコーダと矛盾しません。 @code{True} でない場合は、そのような浮動小数点数をエンコードすると @ref{2ec,,ValueError} が送出されます。

`sort_keys' が true (デフォルトは @code{False}) ならば、辞書の出力がキーでソートされます。これは JSON の直列化がいつでも比較できるようになるので回帰試験の際に便利です。

`indent' が非負の整数または文字列であれば、JSON の配列要素とオブジェクトメンバはそのインデントレベルで見やすく表示されます。インデントレベルが 0 か負数または @code{""} であれば 改行だけが挿入されます。@code{None} (デフォルト) では最もコンパクトな表現が選択されます。正の数のindentはレベル毎に、指定した数のスペースでインデントします。もし `indent' が文字列 (@code{"\t"} のような) であれば、その文字列が個々のレベルのインデントに使用されます。


バージョン 3.2 で変更: 整数に加えて、文字列が `indent' に使用できるようになりました。


`separators' はもし指定するなら @code{(item_separator, key_separator)} というタプルでなければなりません。デフォルトは `indent' が @code{None} のとき @code{(', ', ': ')} で、そうでなければ @code{(',', ': ')} です。最もコンパクトな JSON の表現を得たければ空白を削った @code{(',', ':')} を指定すればいいでしょう。


バージョン 3.4 で変更: `indent' が @code{None} でなければ @code{(',', ': ')} がデフォルトで使われます。


`default' を指定する場合は関数を指定して、この関数はそれ以外では直列化できないオブジェクトに対して呼び出されます。
その関数は、オブジェクトを JSON でエンコードできるバージョンにして返すか、さもなければ @ref{198,,TypeError} を送出しなければなりません。
指定しない場合は、 @ref{198,,TypeError} が送出されます。


バージョン 3.6 で変更: すべての引数は、 @ref{5a5,,キーワード専用} になりました。


@geindex default() (json.JSONEncoder のメソッド)
@anchor{library/json json JSONEncoder default}@anchor{3bd9}
@deffn {メソッド} default (o)

このメソッドをサブクラスで実装する際には `o' に対して直列化可能なオブジェクトを返すか、基底クラスの実装を (@ref{198,,TypeError} を送出するために) 呼び出すかします。

例えば、任意のイテレータをサポートする場合、 @ref{3bd9,,default()} をこのように実装できます

@example
def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return super().default(o)
@end example
@end deffn

@geindex encode() (json.JSONEncoder のメソッド)
@anchor{library/json json JSONEncoder encode}@anchor{3bde}
@deffn {メソッド} encode (o)

Python データ構造 `o' の JSON 文字列表現を返します。たとえば:

@example
>>> json.JSONEncoder().encode(@{"foo": ["bar", "baz"]@})
'@{"foo": ["bar", "baz"]@}'
@end example
@end deffn

@geindex iterencode() (json.JSONEncoder のメソッド)
@anchor{library/json json JSONEncoder iterencode}@anchor{3bdf}
@deffn {メソッド} iterencode (o)

与えられたオブジェクト `o' をエンコードし、得られた文字列表現ごとに yield します。たとえば:

@example
for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
@end example
@end deffn
@end deffn

@node 例外<20>,標準への準拠と互換性,エンコーダとデコーダ,json --- JSON エンコーダーとデコーダー
@anchor{library/json exceptions}@anchor{3be0}
@subsubsection 例外


@geindex JSONDecodeError
@anchor{library/json json JSONDecodeError}@anchor{1022}
@deffn {例外} json.JSONDecodeError (msg, doc, pos)

@ref{2ec,,ValueError} のサブクラスで、以下の追加の属性を持ちます:

@geindex msg (json.JSONDecodeError の属性)
@anchor{library/json json JSONDecodeError msg}@anchor{3be1}
@deffn {の属性} msg

フォーマットされていないエラーメッセージです。
@end deffn

@geindex doc (json.JSONDecodeError の属性)
@anchor{library/json json JSONDecodeError doc}@anchor{3be2}
@deffn {の属性} doc

パース対象 JSON ドキュメントです。
@end deffn

@geindex pos (json.JSONDecodeError の属性)
@anchor{library/json json JSONDecodeError pos}@anchor{3be3}
@deffn {の属性} pos

`doc' の、解析に失敗した開始インデクスです。
@end deffn

@geindex lineno (json.JSONDecodeError の属性)
@anchor{library/json json JSONDecodeError lineno}@anchor{3be4}
@deffn {の属性} lineno

`pos' に対応する行です。
@end deffn

@geindex colno (json.JSONDecodeError の属性)
@anchor{library/json json JSONDecodeError colno}@anchor{3be5}
@deffn {の属性} colno

`pos' に対応する列です。
@end deffn


Added in version 3.5.

@end deffn

@node 標準への準拠と互換性,コマンドライン・インターフェース<5>,例外<20>,json --- JSON エンコーダーとデコーダー
@anchor{library/json standard-compliance-and-interoperability}@anchor{3be6}
@subsubsection 標準への準拠と互換性


The JSON format is specified by 
@geindex RFC; RFC 7159
RFC 7159@footnote{https://datatracker.ietf.org/doc/html/rfc7159.html} and by
ECMA-404@footnote{https://ecma-international.org/publications-and-standards/standards/ecma-404/}.
This section details this module's level of compliance with the RFC.
For simplicity, @ref{f42,,JSONEncoder} and @ref{f43,,JSONDecoder} subclasses, and
parameters other than those explicitly mentioned, are not considered.

このモジュールは、JavaScript では正しいが JSON では不正ないくつかの拡張が実装されているため、厳密な意味では RFC に準拠していません。特に:


@itemize -

@item 
無限および NaN の数値を受け付け、また出力します;

@item 
あるオブジェクト内での同じ名前の繰り返しを受け付け、最後の名前と値のペアの値のみを使用します。
@end itemize

この RFC は、RFC 準拠のパーサが RFC 準拠でない入力テキストを受け付けることを許容しているので、このモジュールの脱直列化は技術的に言えば、デフォルトの設定では RFC に準拠しています。

@menu
* 文字エンコーディング:: 
* 無限および NaN の数値:: 
* オブジェクト中に重複した名前の扱い:: 
* トップレベルの非オブジェクト、非配列の値の扱い:: 
* 実装の制限:: 

@end menu

@node 文字エンコーディング,無限および NaN の数値,,標準への準拠と互換性
@anchor{library/json character-encodings}@anchor{3be7}
@subsubsection 文字エンコーディング


RFC は、UTF-8、UTF-16、UTF-32のいずれかでJSONを表現するように要求しており、UTF-8 が最大の互換性を確保するために推奨されるデフォルトです。

As permitted, though not required, by the RFC, this module's serializer sets
`ensure_ascii=True' by default, thus escaping the output so that the resulting
strings only contain printable ASCII characters.

`ensure_ascii' パラメータ以外は、このモジュールは Python オブジェクトと @ref{169,,Unicode 文字列} の間の変換において厳密に定義されていて、それ以外のパラメータで文字エンコーディングに直接的に関わるものはありません。

RFC は JSON テキストの最初にバイトオーダマーク(BOM)を追加することを禁止していますので、このモジュールはその出力に BOM を追加しません。RFC は JSON デシリアライザが入力の一番最初の BOM を無視することを、許容はしますが求めてはいません。このモジュールのデシリアライザは一番最初の BOM を見つけると @ref{2ec,,ValueError} を送出します。

RFC は JSON 文字列に正当な Unicode 文字に対応付かないバイト列(例えばペアにならない UTF-16 サロゲートのかたわれ)が含まれることを明示的に禁止してはおらず、もちろんこれは相互運用性の問題を引き起こします。デフォルトでは、このモジュールは(オリジナルの @ref{169,,str} にある場合)そのようなシーケンスのコードポイントを受け取り、出力します。

@node 無限および NaN の数値,オブジェクト中に重複した名前の扱い,文字エンコーディング,標準への準拠と互換性
@anchor{library/json infinite-and-nan-number-values}@anchor{3be8}
@subsubsection 無限および NaN の数値


RFC は、無限もしくは NaN の数値の表現は許可していません。それにも関わらずデフォルトでは、このモジュールは @code{Infinity}、@code{-Infinity}、@code{NaN} を正しい JSON の数値リテラルの値であるかのように受け付け、出力します:

@example
>>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan
@end example

シリアライザでは、この振る舞いを変更するのに `allow_nan' パラメータが使えます。デシリアライザでは、この振る舞いを変更するのに `parse_constant' パラメータが使えます。

@node オブジェクト中に重複した名前の扱い,トップレベルの非オブジェクト、非配列の値の扱い,無限および NaN の数値,標準への準拠と互換性
@anchor{library/json repeated-names-within-an-object}@anchor{3be9}
@subsubsection オブジェクト中に重複した名前の扱い


RFC は JSON オブジェクト中の名前はユニークでなければならないと規定していますが、JSONオブジェクトで名前が繰り返された場合の扱いについて指定していません。デフォルトでは、このモジュールは例外を送出せず、かわりに重複した名前のうち、最後に出現した名前と値のペア以外を無視します。

@example
>>> weird_json = '@{"x": 1, "x": 2, "x": 3@}'
>>> json.loads(weird_json)
@{'x': 3@}
@end example

`object_pairs_hook' パラメータでこの動作を変更できます。

@node トップレベルの非オブジェクト、非配列の値の扱い,実装の制限,オブジェクト中に重複した名前の扱い,標準への準拠と互換性
@anchor{library/json top-level-non-object-non-array-values}@anchor{3bea}
@subsubsection トップレベルの非オブジェクト、非配列の値の扱い


廃止された 
@geindex RFC; RFC 4627
RFC 4627@footnote{https://datatracker.ietf.org/doc/html/rfc4627.html} によって規定された古いバージョンの JSON では、JSON テキストのトップレベルの値は JSON オブジェクトか配列(Python での @ref{183,,dict} か @ref{24d,,list})であることを要求していて、JSON の null, boolean, number, string であることは許されていませんでしたが、この制限は 
@geindex RFC; RFC 7159
RFC 7159@footnote{https://datatracker.ietf.org/doc/html/rfc7159.html} により取り払われました。このモジュールはこの制限を持っていませんし、シリアライザでもデシリアライズでも、一度としてこの制限で実装されたことはありません。

それにも関わらず、相互運用可能性を最大化したいならば、あなた自身の手で自発的にその制約に忠実に従いたいと思うでしょう。

@node 実装の制限,,トップレベルの非オブジェクト、非配列の値の扱い,標準への準拠と互換性
@anchor{library/json implementation-limitations}@anchor{3beb}
@subsubsection 実装の制限


いくつかの JSON デシリアライザの実装は、以下の制限を設定することがあります。


@itemize *

@item 
受け入れられる JSON テキストのサイズ

@item 
JSON オブジェクトと配列のネストの最大の深さ

@item 
JSON 数値の範囲と精度

@item 
JSON 文字列の内容と最大の長さ
@end itemize

このモジュールは関連する Python データ型や Python インタプリタ自身の制約の世界を超えたそのような制約を強要はしません。

JSON にシリアライズする際には、あなたの JSON を消費する側のアプリケーションが持つ当該制約に思いを馳せてください。とりわけJSON 数値を IEEE 754 倍精度浮動小数にデシリアライズする際の問題はありがちで、すなわちその有効桁数と精度の制限の影響を受けます。これは、極端に大きな値を持った Python @ref{19b,,int} をシリアライズするとき、あるいは @ref{1fe,,decimal.Decimal} のような "風変わりな" 数値型をシリアライズするとき、に特に関係があります。

@node コマンドライン・インターフェース<5>,,標準への準拠と互換性,json --- JSON エンコーダーとデコーダー
@anchor{library/json command-line-interface}@anchor{3bec}@anchor{library/json json-commandline}@anchor{23e}@anchor{library/json module-json tool}@anchor{87}
@subsubsection コマンドライン・インターフェース


@geindex module; json.tool

`ソースコード:' Lib/json/tool.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/json/tool.py}


__________________________________________________________________


The @code{json} module can be invoked as a script via @code{python -m json}
to validate and pretty-print JSON objects. The @code{json.tool} submodule
implements this interface.

オプション引数の @code{infile} と @code{outfile} が指定されない場合、それぞれ @ref{75f,,sys.stdin} と @ref{ccd,,sys.stdout} が使用されます。

@example
$ echo '@{"json": "obj"@}' | python -m json
@{
    "json": "obj"
@}
$ echo '@{1.2:3.4@}' | python -m json
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
@end example


バージョン 3.5 で変更: 出力が、入力と同じ順序になりました。辞書をキーでアルファベット順に並べ替えた出力が欲しければ、 @ref{3bed,,--sort-keys} オプションを使ってください。



バージョン 3.14 で変更: The @code{json} module may now be directly executed as
@code{python -m json}. For backwards compatibility, invoking
the CLI as @code{python -m json.tool} remains supported.


@menu
* コマンドラインオプション: コマンドラインオプション<4>. 

@end menu

@node コマンドラインオプション<4>,,,コマンドライン・インターフェース<5>
@anchor{library/json command-line-options}@anchor{3bee}
@subsubsection コマンドラインオプション


@geindex json コマンドラインオプション; infile
@anchor{library/json cmdoption-json-arg-infile}@anchor{3bef}
@deffn {Option} infile

検証を行う、あるいは整形出力を行う JSON ファイルを指定します:

@example
$ python -m json mp_films.json
[
    @{
        "title": "And Now for Something Completely Different",
        "year": 1971
    @},
    @{
        "title": "Monty Python and the Holy Grail",
        "year": 1975
    @}
]
@end example

`infile' が指定されない場合、 @ref{75f,,sys.stdin} から読み込みます。
@end deffn

@geindex json コマンドラインオプション; outfile
@anchor{library/json cmdoption-json-arg-outfile}@anchor{3bf0}
@deffn {Option} outfile

`infile' の出力を `outfile' に書き込みます。そうでない場合、 @ref{ccd,,sys.stdout} に書き込みます。
@end deffn

@geindex json コマンドラインオプション; --sort-keys
@anchor{library/json cmdoption-json-sort-keys}@anchor{3bed}
@deffn {Option} @w{-}@w{-}sort@w{-}keys

辞書の出力を、キーのアルファベット順にソートします。


Added in version 3.5.

@end deffn

@geindex json コマンドラインオプション; --no-ensure-ascii
@anchor{library/json cmdoption-json-no-ensure-ascii}@anchor{3bf1}
@deffn {Option} @w{-}@w{-}no@w{-}ensure@w{-}ascii

非 ASCII 文字のエスケープを無効化します。より詳しくは @ref{f41,,json.dumps()} を参照してください。


Added in version 3.9.

@end deffn

@geindex json コマンドラインオプション; --json-lines
@anchor{library/json cmdoption-json-json-lines}@anchor{3bf2}
@deffn {Option} @w{-}@w{-}json@w{-}lines

すべての入力行を個別のJSON オブジェクトとしてパースします。


Added in version 3.8.

@end deffn

@geindex json コマンドラインオプション; --indent
@geindex json コマンドラインオプション; --tab
@geindex json コマンドラインオプション; --no-indent
@geindex json コマンドラインオプション; --compact
@anchor{library/json cmdoption-json-indent}@anchor{3bf3}@anchor{library/json cmdoption-json-tab}@anchor{3bf4}@anchor{library/json cmdoption-json-no-indent}@anchor{3bf5}@anchor{library/json cmdoption-json-compact}@anchor{3bf6}
@deffn {Option} @w{-}@w{-}indent, @w{-}@w{-}tab, @w{-}@w{-}no@w{-}indent, @w{-}@w{-}compact

空白文字の制御のための排他的なオプション。


Added in version 3.9.

@end deffn

@geindex json コマンドラインオプション; -h
@geindex json コマンドラインオプション; --help
@anchor{library/json cmdoption-json-h}@anchor{3bf7}@anchor{library/json cmdoption-json-help}@anchor{3bf8}
@deffn {Option} @w{-}h, @w{-}@w{-}help

ヘルプメッセージを出力します
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node mailbox --- 様々な形式のメールボックスを操作する,mimetypes --- ファイル名を MIME タイプへマップする,json --- JSON エンコーダーとデコーダー,インターネット上のデータの操作
@anchor{library/mailbox doc}@anchor{3bf9}@anchor{library/mailbox mailbox-manipulate-mailboxes-in-various-formats}@anchor{3bfa}@anchor{library/mailbox module-mailbox}@anchor{8f}@anchor{library/mailbox translation-repo}@anchor{3bfb}
@subsection @code{mailbox} --- 様々な形式のメールボックスを操作する


@geindex module; mailbox

`ソースコード:' Lib/mailbox.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/mailbox.py}


__________________________________________________________________


このモジュールでは二つのクラス @ref{1463,,Mailbox} および @ref{1468,,Message} をディスク上のメールボックスとそこに収められたメッセージへのアクセスと操作のために定義しています。 @code{Mailbox} は辞書のようなキーからメッセージへの対応付けを提供しています。 @code{Message} は @ref{48,,email.message} モジュールの @ref{581,,Message} を拡張して形式ごとの状態と振る舞いを追加しています。サポートされるメールボックスの形式は Maildir, mbox, MH, Babyl, MMDF です。


@subsubheading 参考



@table @asis

@item @ref{3f,,email} モジュール

メッセージの表現と操作。
@end table


@menu
* Mailbox オブジェクト:: 
* Message オブジェクト:: 
* 例外: 例外<21>. 
* 使用例: 使用例<31>. 

@end menu

@node Mailbox オブジェクト,Message オブジェクト,,mailbox --- 様々な形式のメールボックスを操作する
@anchor{library/mailbox id1}@anchor{3bfc}@anchor{library/mailbox mailbox-objects}@anchor{3bfd}
@subsubsection @code{Mailbox} オブジェクト


@geindex Mailbox (mailbox のクラス)
@anchor{library/mailbox mailbox Mailbox}@anchor{1463}
@deffn {クラス} mailbox.Mailbox

メールボックス。内容を確認したり変更したりできます。

@code{Mailbox} クラスはインターフェースを定義するもので、インスタンス化されることは想定していません。代わりに、@code{Mailbox} から継承した形式ごとのサブクラスを作り、コードでは特定のサブクラスをインスタンス化するべきです。

@code{Mailbox} のインターフェースは辞書風で、小さなキーがメッセージに対応します。キーは対象となる @code{Mailbox} インスタンスが発行するもので、その @code{Mailbox} インスタンスに対してのみ意味を持ちます。一つのキーは一つのメッセージにひも付けられ、その対応はメッセージが他のメッセージで置き換えられるような更新をされたあとも続きます。

メッセージを @code{Mailbox} インスタンスに追加するには集合風のメソッド @ref{1464,,add()} を使います。また削除は @code{del} 文または集合風の @ref{3bfe,,remove()} や @ref{3bff,,discard()} を使って行ないます。

@code{Mailbox} インターフェースのセマンティクスと辞書のそれとは注意すべき違いがあります。メッセージは、要求されるたびに新しい表現(典型的には @ref{1468,,Message} インスタンス)が現在のメールボックスの状態に基づいて生成されます。同様に、メッセージが @code{Mailbox} インスタンスに追加される時も、渡されたメッセージ表現の内容がコピーされます。どちらの場合も @code{Mailbox} インスタンスにメッセージ表現への参照は保たれません。

デフォルトの @code{Mailbox} @ref{4c8,,イテレータ} はメッセージ表現ごとに繰り返すもので、@ref{183,,辞書} のイテレータのようにキーごとの繰り返しではありません。さらに、繰り返し中のメールボックスを変更することは安全であり整合的に定義されています。イテレータが作られた後にメールボックスに追加されたメッセージはそのイテレータからは見えません。そのイテレータが yield するまえにメールボックスから削除されたメッセージは黙ってスキップされますが、イテレータからのキーを使ったときにはそのキーに対応するメッセージが削除されているならば @ref{5e7,,KeyError} を受け取ることになります。

@cartouche
@quotation 警告 
十分な注意を、何か他のプロセスによっても同時に変更される可能性のあるメールボックスを更新する時は、払わなければなりません。そのようなタスクをこなすのに最も安全なメールボックス形式は @ref{65e,,Maildir} で、 @ref{19fb,,mbox} のような単一ファイルの形式を並行した書き込みに利用するのは避けるように努力しましょう。メールボックスを更新する場面では、 `必ず' @ref{3c00,,lock()} と @ref{3c01,,unlock()} メソッドを、ファイル内のメッセージを読んだり書き込んだり削除したりといった操作をする `前' に、呼び出してロックします。メールボックスをロックし損なうと、メッセージを失ったりメールボックス全体をぐちゃぐちゃにしたりする羽目に陥ります。
@end quotation
@end cartouche

@code{Mailbox} インスタンスには次のメソッドがあります:

@geindex add() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox add}@anchor{1464}
@deffn {メソッド} add (message)

メールボックスに `message' を追加し、それに割り当てられたキーを返します。

引数 `message' は @ref{1468,,Message} インスタンス、 @ref{581,,email.message.Message} インスタンス、文字列、バイト文字列、ファイル風オブジェクト (バイナリモードで開かれていなければなりません) を使えます。 `message' が適切な形式に特化した @ref{1468,,Message} サブクラスのインスタンス (例えばメールボックスが @ref{19fb,,mbox} インスタンスのときの @ref{3abf,,mboxMessage} インスタンス) であれば、形式ごとの情報が利用されます。そうでなければ、形式ごとに必要な情報は適当なデフォルトが使われます。


バージョン 3.2 で変更: バイナリ入力のサポートが追加されました。

@end deffn

@geindex remove() (mailbox.Mailbox のメソッド)
@geindex __delitem__() (mailbox.Mailbox のメソッド)
@geindex discard() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox remove}@anchor{3bfe}
@deffn {メソッド} remove (key)
@anchor{library/mailbox mailbox Mailbox __delitem__}@anchor{3c02}
@deffnx {メソッド} __delitem__ (key)
@anchor{library/mailbox mailbox Mailbox discard}@anchor{3bff}
@deffnx {メソッド} discard (key)

メールボックスから `key' に対応するメッセージを削除します。

対応するメッセージが無い場合、メソッドが @ref{3bfe,,remove()} または @ref{3c02,,__delitem__()} として呼び出されている時は @ref{5e7,,KeyError} 例外が送出されます。しかし、 @ref{3bff,,discard()} として呼び出されている場合は例外は発生しません。基づいているメールボックス形式が別のプロセスからの平行した変更をサポートしているならば、この @ref{3bff,,discard()} の振る舞いの方が好まれるかもしれません。
@end deffn

@geindex __setitem__() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox __setitem__}@anchor{3c03}
@deffn {メソッド} __setitem__ (key, message)

`key' に対応するメッセージを `message' で置き換えます。 `key' に対応しているメッセージが既に無くなっている場合 @ref{5e7,,KeyError} 例外が送出されます。

@ref{1464,,add()} と同様に、引数の `message' には @ref{1468,,Message} インスタンス、 @ref{581,,email.message.Message} インスタンス、文字列、バイト文字列、ファイル風オブジェクト (バイナリモードで開かれていなければなりません) を使えます。 `message' が適切な形式に特化した @ref{1468,,Message} サブクラスのインスタンス (例えばメールボックスが @ref{19fb,,mbox} インスタンスのときの @ref{3abf,,mboxMessage} インスタンス) であれば、形式ごとの情報が利用されます。そうでなければ、現在 `key' に対応するメッセージの形式ごとの情報が変更されずに残ります。
@end deffn

@geindex iterkeys() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox iterkeys}@anchor{3c04}
@deffn {メソッド} iterkeys ()

Return an @ref{4c8,,iterator} over all keys
@end deffn

@geindex keys() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox keys}@anchor{3c05}
@deffn {メソッド} keys ()

The same as @ref{3c04,,iterkeys()}, except that a @ref{24d,,list} is returned
rather than an @ref{4c8,,iterator}
@end deffn

@geindex itervalues() (mailbox.Mailbox のメソッド)
@geindex __iter__() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox itervalues}@anchor{3c06}
@deffn {メソッド} itervalues ()
@anchor{library/mailbox mailbox Mailbox __iter__}@anchor{3c07}
@deffnx {メソッド} __iter__ ()

全てのメッセージの表現についての @ref{4c8,,イテレータ} を返します。メッセージは適切な形式ごとの @ref{1468,,Message} サブクラスのインスタンスとして表現されるのが普通ですが、 @code{Mailbox} インスタンスが初期化されるときに指定すればお好みのメッセージファクトリを使うこともできます。

@cartouche
@quotation 注釈 
@ref{3c07,,__iter__()} は辞書のそれのようにキーについてのイテレータではありません。
@end quotation
@end cartouche
@end deffn

@geindex values() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox values}@anchor{3c08}
@deffn {メソッド} values ()

The same as @ref{3c06,,itervalues()}, except that a @ref{24d,,list} is returned
rather than an @ref{4c8,,iterator}
@end deffn

@geindex iteritems() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox iteritems}@anchor{3c09}
@deffn {メソッド} iteritems ()

(`key', `message') ペア、ただし `key' はキーで `message' はメッセージ表現、のイテレータを返します。メッセージは適切な形式ごとの @ref{1468,,Message} サブクラスのインスタンスとして表現されるのが普通ですが、 @code{Mailbox} インスタンスが初期化されるときに指定すればお好みのメッセージファクトリを使うこともできます。
@end deffn

@geindex items() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox items}@anchor{3c0a}
@deffn {メソッド} items ()

The same as @ref{3c09,,iteritems()}, except that a @ref{24d,,list} of pairs is
returned rather than an @ref{4c8,,iterator} of pairs.
@end deffn

@geindex get() (mailbox.Mailbox のメソッド)
@geindex __getitem__() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox get}@anchor{3c0b}
@deffn {メソッド} get (key, default=None)
@anchor{library/mailbox mailbox Mailbox __getitem__}@anchor{3c0c}
@deffnx {メソッド} __getitem__ (key)

`key' に対応するメッセージの表現を返します。対応するメッセージが存在しない場合、 @ref{3c0b,,get()} として呼び出されたなら `default' を返しますが、 @code{__getitem__()} として呼び出されたなら @ref{5e7,,KeyError} 例外が送出されます。メッセージは適切な形式ごとの @ref{1468,,Message} サブクラスのインスタンスとして表現されるのが普通ですが、 @code{Mailbox} スタンスが初期化されるときに指定すればお好みのメッセージファクトリを使うこともできます。
@end deffn

@geindex get_message() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox get_message}@anchor{3c0d}
@deffn {メソッド} get_message (key)

`key' に対応するメッセージの表現を形式ごとの @ref{1468,,Message} サブクラスのインスタンスとして返します。もし対応するメッセージが存在しなければ @ref{5e7,,KeyError} 例外が送出されます。
@end deffn

@geindex get_bytes() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox get_bytes}@anchor{1466}
@deffn {メソッド} get_bytes (key)

`key' に対応するメッセージのバイト列を返すか、そのようなメッセージが存在しない場合は @ref{5e7,,KeyError} 例外を送出します。


Added in version 3.2.

@end deffn

@geindex get_string() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox get_string}@anchor{1467}
@deffn {メソッド} get_string (key)

`key' に対応するメッセージの文字列表現を返すか、そのようなメッセージが存在しない場合は @ref{5e7,,KeyError} 例外を送出します。このメッセージは @ref{581,,email.message.Message} を通して処理されて7ビットクリーンな表現へ変換されます。
@end deffn

@geindex get_file() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox get_file}@anchor{1465}
@deffn {メソッド} get_file (key)

`key' に対応するメッセージの表現を @ref{17ac,,ファイル風} 表現として返します。もし対応するメッセージが存在しなければ @ref{5e7,,KeyError} 例外が送出されます。ファイル風オブジェクトはバイナリモードで開かれているように振る舞います。このファイルは必要がなくなったら閉じなければなりません。


バージョン 3.2 で変更: ファイルオブジェクトは実際は @ref{206e,,バイナリファイル} です; 以前は誤ってテキストモードで返されていました。 また、現在 @ref{17ac,,ファイル風オブジェクト} は @ref{1e1,,コンテキストマネージャ} プロトコルをサポートしています: @ref{186,,with} 文を用いることで自動的にファイルを閉じることができます。


@cartouche
@quotation 注釈 
他の表現方法とは違い、@ref{17ac,,ファイル風} 表現はそれを作り出した @code{Mailbox} インスタンスやそれが基づいているメールボックスと独立である必要がありません。より詳細な説明は各サブクラスごとにあります。
@end quotation
@end cartouche
@end deffn

@geindex __contains__() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox __contains__}@anchor{3c0e}
@deffn {メソッド} __contains__ (key)

`key' がメッセージに対応していれば @code{True} を、そうでなければ @code{False} を返します。
@end deffn

@geindex __len__() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox __len__}@anchor{3c0f}
@deffn {メソッド} __len__ ()

メールボックス中のメッセージ数を返します。
@end deffn

@geindex clear() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox clear}@anchor{3c10}
@deffn {メソッド} clear ()

メールボックスから全てのメッセージを削除します。
@end deffn

@geindex pop() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox pop}@anchor{3c11}
@deffn {メソッド} pop (key, default=None)

`key' に対応するメッセージの表現を返します。メッセージは適切な形式ごとの @ref{1468,,Message} サブクラスのインスタンスとして表現されるのが普通ですが、 @code{Mailbox} インスタンスが初期化されるときに指定すればお好みのメッセージファクトリを使うこともできます。
@end deffn

@geindex popitem() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox popitem}@anchor{3c12}
@deffn {メソッド} popitem ()

任意に選んだ (`key', `message') ペアを返します。ただしここで `key' はキーで `message' はメッセージ表現です。もしメールボックスが空ならば、 @ref{5e7,,KeyError} 例外を送出します。メッセージは適切な形式ごとの @ref{1468,,Message} サブクラスのインスタンスとして表現されるのが普通ですが、 @code{Mailbox} インスタンスが初期化されるときに指定すればお好みのメッセージファクトリを使うこともできます。
@end deffn

@geindex update() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox update}@anchor{3c13}
@deffn {メソッド} update (arg)

引数 `arg' は `key' から `message' へのマッピングまたは (`key', `message') ペアのイテレート可能オブジェクトでなければなりません。メールボックスは、各 `key' と `message' のペアについて @ref{3c03,,__setitem__()} を使ったかのように `key' に対応するメッセージが `message' になるように更新されます。 @ref{3c03,,__setitem__()} と同様に、 `key' は既存のメールボックス中のメッセージに対応しているものでなければならず、そうでなければ @ref{5e7,,KeyError} が送出されます。ですから、一般的には `arg' に @code{Mailbox} インスタンスを渡すのは間違いです。

@cartouche
@quotation 注釈 
辞書と違い、キーワード引数はサポートされていません。
@end quotation
@end cartouche
@end deffn

@geindex flush() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox flush}@anchor{19c1}
@deffn {メソッド} flush ()

保留されている変更をファイルシステムに書き込みます。 @ref{1463,,Mailbox} のサブクラスによっては変更はいつも直ちにファイルに書き込まれ @code{flush()} は何もしないということもありますが、それでもこのメソッドを呼ぶように習慣付けておきましょう。
@end deffn

@geindex lock() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox lock}@anchor{3c00}
@deffn {メソッド} lock ()

メールボックスの排他的アドバイザリロックを取得し、他のプロセスが変更しないようにします。ロックが取得できない場合 @ref{3c14,,ExternalClashError} が送出されます。ロック機構はメールボックス形式によって変わります。メールボックスの内容に変更を加えるときは `いつも' ロックを掛けるべきです。
@end deffn

@geindex unlock() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox unlock}@anchor{3c01}
@deffn {メソッド} unlock ()

メールボックスのロックが存在する場合は解放します。
@end deffn

@geindex close() (mailbox.Mailbox のメソッド)
@anchor{library/mailbox mailbox Mailbox close}@anchor{3c15}
@deffn {メソッド} close ()

メールボックスをフラッシュし、必要ならばアンロックし、開いているファイルを閉じます。 @code{Mailbox} サブクラスによっては何もしないこともあります。
@end deffn
@end deffn

@menu
* Maildir オブジェクト:: 
* mbox オブジェクト:: 
* MH オブジェクト:: 
* Babyl オブジェクト:: 
* MMDF オブジェクト:: 

@end menu

@node Maildir オブジェクト,mbox オブジェクト,,Mailbox オブジェクト
@anchor{library/mailbox mailbox-maildir}@anchor{3c16}@anchor{library/mailbox maildir-objects}@anchor{3c17}
@subsubsection @code{Maildir} オブジェクト


@geindex Maildir (mailbox のクラス)
@anchor{library/mailbox mailbox Maildir}@anchor{65e}
@deffn {クラス} mailbox.Maildir (dirname, factory=None, create=True)

Maildir 形式のメールボックスのための @ref{1463,,Mailbox} のサブクラス。パラメータ `factory' は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 `factory' が @code{None} ならば、 @ref{3c18,,MaildirMessage} がデフォルトのメッセージ表現として使われます。 `create' が @code{True} ならばメールボックスが存在しないときには作成します。

`create' が @code{True} で、パス `dirname' が存在する場合、ディレクトリレイアウトを検証せずに既存の maildir として扱います。

`path' ではなく `dirname' と命名される歴史的な理由のためです。

Maildir はディレクトリ型のメールボックス形式でメール転送エージェント qmail 用に発明され、現在では多くの他のプログラムでもサポートされているものです。Maildir メールボックス中のメッセージは共通のディレクトリ構造の下で個別のファイルに保存されます。このデザインにより、Maildir メールボックスは複数の無関係のプログラムからデータを失うことなくアクセスしたり変更したりできます。そのためロックは不要です。

Maildir メールボックスには三つのサブディレクトリ @code{tmp}, @code{new}, @code{cur} があります。メッセージはまず @code{tmp} サブディレクトリに瞬間的に作られた後、 @code{new} サブディレクトリに移動されて配送を完了します。メールユーザエージェントが引き続いて @code{cur} サブディレクトリにメッセージを移動しメッセージの状態についての情報をファイル名に追加される特別な "info" セクションに保存することができます。

Courier メール転送エージェントによって導入されたスタイルのフォルダもサポートされます。主たるメールボックスのサブディレクトリは @code{'.'} がファイル名の先頭であればフォルダと見なされます。フォルダ名は @code{Maildir} によって先頭の @code{'.'} を除いて表現されます。各フォルダはまた Maildir メールボックスですがさらにフォルダを含むことはできません。その代わり、論理的包含関係は例えば "Archived.2005.07" のような @code{'.'} を使ったレベル分けで表わされます。

@geindex colon (mailbox.Maildir の属性)
@anchor{library/mailbox mailbox Maildir colon}@anchor{3c19}
@deffn {の属性} colon

本来の Maildir 仕様ではある種のメッセージのファイル名にコロン (@code{':'}) を使う必要があります。しかしながら、オペレーティングシステムによってはこの文字をファイル名に含めることができないことがあります。そういった環境で Maildir のような形式を使いたい場合、代わりに使われる文字を指定する必要があります。感嘆符 (@code{'!'}) を使うのが一般的な選択です。以下の例を見てください:

@example
import mailbox
mailbox.Maildir.colon = '!'
@end example

@code{colon} 属性はインスタンスごとにセットしても構いません。
@end deffn


バージョン 3.13 で変更: @ref{65e,,Maildir} now ignores files with a leading dot.


@code{Maildir} インスタンスには @ref{1463,,Mailbox} の全てのメソッドに加え以下のメソッドもあります:

@geindex list_folders() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir list_folders}@anchor{3c1a}
@deffn {メソッド} list_folders ()

全てのフォルダ名のリストを返します。
@end deffn

@geindex get_folder() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir get_folder}@anchor{3c1b}
@deffn {メソッド} get_folder (folder)

名前が `folder' であるフォルダを表わす @code{Maildir} インスタンスを返します。そのようなフォルダが存在しなければ @ref{3c1c,,NoSuchMailboxError} 例外が送出されます。
@end deffn

@geindex add_folder() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir add_folder}@anchor{3c1d}
@deffn {メソッド} add_folder (folder)

名前が `folder' であるフォルダを作り、それを表わす @code{Maildir} インスタンスを返します。
@end deffn

@geindex remove_folder() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir remove_folder}@anchor{3c1e}
@deffn {メソッド} remove_folder (folder)

名前が `folder' であるフォルダを削除します。もしフォルダに一つでもメッセージが含まれていれば @ref{3c1f,,NotEmptyError} 例外が送出されフォルダは削除されません。
@end deffn

@geindex clean() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir clean}@anchor{3c20}
@deffn {メソッド} clean ()

過去36時間以内にアクセスされなかったメールボックス内の一時ファイルを削除します。Maildir 仕様はメールを読むプログラムはときどきこの作業をすべきだとしています。
@end deffn

@geindex get_flags() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir get_flags}@anchor{1a46}
@deffn {メソッド} get_flags (key)

Return as a string the flags that are set on the message
corresponding to `key'.
This is the same as @code{get_message(key).get_flags()} but much
faster, because it does not open the message file.
Use this method when iterating over the keys to determine which
messages are interesting to get.

If you do have a @ref{3c18,,MaildirMessage} object, use
its @ref{3c21,,get_flags()} method instead, because
changes made by the message's @ref{3c22,,set_flags()},
@ref{3c23,,add_flag()} and @ref{3c24,,remove_flag()}
methods are not reflected here until the mailbox's
@ref{3c25,,__setitem__()} method is called.


Added in version 3.13.

@end deffn

@geindex set_flags() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir set_flags}@anchor{1a47}
@deffn {メソッド} set_flags (key, flags)

On the message corresponding to `key', set the flags specified
by `flags' and unset all others.
Calling @code{some_mailbox.set_flags(key, flags)} is similar to

@example
one_message = some_mailbox.get_message(key)
one_message.set_flags(flags)
some_mailbox[key] = one_message
@end example

but faster, because it does not open the message file.

If you do have a @ref{3c18,,MaildirMessage} object, use
its @ref{3c22,,set_flags()} method instead, because
changes made with this mailbox method will not be visible to the
message object's method, @ref{3c21,,get_flags()}.


Added in version 3.13.

@end deffn

@geindex add_flag() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir add_flag}@anchor{1a48}
@deffn {メソッド} add_flag (key, flag)

On the message corresponding to `key', set the flags specified
by `flag' without changing other flags. To add more than one
flag at a time, `flag' may be a string of more than one character.

Considerations for using this method versus the message object's
@ref{3c23,,add_flag()} method are similar to
those for @ref{1a47,,set_flags()}; see the discussion there.


Added in version 3.13.

@end deffn

@geindex remove_flag() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir remove_flag}@anchor{1a49}
@deffn {メソッド} remove_flag (key, flag)

On the message corresponding to `key', unset the flags specified
by `flag' without changing other flags. To remove more than one
flag at a time, `flag' may be a string of more than one character.

Considerations for using this method versus the message object's
@ref{3c24,,remove_flag()} method are similar to
those for @ref{1a47,,set_flags()}; see the discussion there.


Added in version 3.13.

@end deffn

@geindex get_info() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir get_info}@anchor{1a44}
@deffn {メソッド} get_info (key)

Return a string containing the info for the message
corresponding to `key'.
This is the same as @code{get_message(key).get_info()} but much
faster, because it does not open the message file.
Use this method when iterating over the keys to determine which
messages are interesting to get.

If you do have a @ref{3c18,,MaildirMessage} object, use
its @ref{3c26,,get_info()} method instead, because
changes made by the message's @ref{3c27,,set_info()} method
are not reflected here until the mailbox's @ref{3c25,,__setitem__()} method
is called.


Added in version 3.13.

@end deffn

@geindex set_info() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir set_info}@anchor{1a45}
@deffn {メソッド} set_info (key, info)

Set the info of the message corresponding to `key' to `info'.
Calling @code{some_mailbox.set_info(key, flags)} is similar to

@example
one_message = some_mailbox.get_message(key)
one_message.set_info(info)
some_mailbox[key] = one_message
@end example

but faster, because it does not open the message file.

If you do have a @ref{3c18,,MaildirMessage} object, use
its @ref{3c27,,set_info()} method instead, because
changes made with this mailbox method will not be visible to the
message object's method, @ref{3c26,,get_info()}.


Added in version 3.13.

@end deffn

@code{Maildir} で実装された @ref{1463,,Mailbox} のいくつかのメソッドには特別な注意が必要です:

@geindex add() (mailbox.Maildir のメソッド)
@geindex __setitem__() (mailbox.Maildir のメソッド)
@geindex update() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir add}@anchor{3c28}
@deffn {メソッド} add (message)
@anchor{library/mailbox mailbox Maildir __setitem__}@anchor{3c25}
@deffnx {メソッド} __setitem__ (key, message)
@anchor{library/mailbox mailbox Maildir update}@anchor{3c29}
@deffnx {メソッド} update (arg)

@cartouche
@quotation 警告 
これらのメソッドは一意的なファイル名をプロセスIDに基づいて生成します。複数のスレッドを使う場合は、同じメールボックスを同時に操作しないようにスレッド間で調整しておかないと検知されない名前の衝突が起こりメールボックスを壊すかもしれません。
@end quotation
@end cartouche
@end deffn

@geindex flush() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir flush}@anchor{3c2a}
@deffn {メソッド} flush ()

Maildir メールボックスへの変更は即時に適用されるので、このメソッドは何もしません。
@end deffn

@geindex lock() (mailbox.Maildir のメソッド)
@geindex unlock() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir lock}@anchor{3c2b}
@deffn {メソッド} lock ()
@anchor{library/mailbox mailbox Maildir unlock}@anchor{3c2c}
@deffnx {メソッド} unlock ()

Maildir メールボックスはロックをサポート(または要求)しないので、このメソッドは何もしません。
@end deffn

@geindex close() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir close}@anchor{3c2d}
@deffn {メソッド} close ()

@code{Maildir} インスタンスは開いたファイルを保持しませんしメールボックスはロックをサポートしませんので、このメソッドは何もしません。
@end deffn

@geindex get_file() (mailbox.Maildir のメソッド)
@anchor{library/mailbox mailbox Maildir get_file}@anchor{3c2e}
@deffn {メソッド} get_file (key)

ホストのプラットフォームによっては、返されたファイルが開いている間、元になったメッセージを変更したり削除したりできない場合があります。
@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item Courier の maildir マニュアルページ@footnote{https://www.courier-mta.org/maildir.html}

Maildir 形式の仕様。フォルダをサポートする一般的な拡張について記述されています。

@item Using maildir format@footnote{https://cr.yp.to/proto/maildir.html}

Maildir 形式の発明者による注意書き。更新された名前生成規則と "info" の解釈についても含まれます。
@end table


@node mbox オブジェクト,MH オブジェクト,Maildir オブジェクト,Mailbox オブジェクト
@anchor{library/mailbox mailbox-mbox}@anchor{3c2f}@anchor{library/mailbox mbox-objects}@anchor{3c30}
@subsubsection @code{mbox} オブジェクト


@geindex mbox (mailbox のクラス)
@anchor{library/mailbox mailbox mbox}@anchor{19fb}
@deffn {クラス} mailbox.mbox (path, factory=None, create=True)

mbox 形式のメールボックスのための @ref{1463,,Mailbox} のサブクラス。パラメータ `factory' は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 `factory' が @code{None} ならば、 @ref{3abf,,mboxMessage} がデフォルトのメッセージ表現として使われます。 `create' が @code{True} ならばメールボックスが存在しないときには作成します。

mbox 形式は Unixシステム上でメールを保存する古くからある形式です。mbox メールボックスでは全てのメッセージが一つのファイルに保存されておりそれぞれのメッセージは "From " という5文字で始まる行を先頭に付けられています。

mbox 形式には幾つかのバリエーションがあり、それぞれオリジナルの形式にあった欠点を克服すると主張しています。互換性のために、 @code{mbox} はオリジナルの(時に `mboxo' と呼ばれる) 形式を実装しています。すなわち、 @code{Content-Length} ヘッダはもしあっても無視され、メッセージのボディにある行頭の "From " はメッセージを保存する際に ">From " に変換されますが、この ">From " は読み出し時にも "From " に変換されません。

@code{mbox} で実装された @ref{1463,,Mailbox} のいくつかのメソッドには特別な注意が必要です:

@geindex get_bytes() (mailbox.mbox のメソッド)
@anchor{library/mailbox mailbox mbox get_bytes}@anchor{3c31}
@deffn {メソッド} get_bytes (key, from_=False)

Note: This method has an extra parameter (`from_') compared with other classes.
The first line of an mbox file entry is the Unix "From " line.
If `from_' is False, the first line of the file is dropped.
@end deffn

@geindex get_file() (mailbox.mbox のメソッド)
@anchor{library/mailbox mailbox mbox get_file}@anchor{3c32}
@deffn {メソッド} get_file (key, from_=False)

@code{mbox} インスタンスに対し @ref{19c1,,flush()} や meth:@cite{~Mailbox.close} を呼び出した後でファイルを使用すると予期しない結果を引き起こしたり例外が送出されたりすることがあります。

Note: This method has an extra parameter (`from_') compared with other classes.
The first line of an mbox file entry is the Unix "From " line.
If `from_' is False, the first line of the file is dropped.
@end deffn

@geindex get_string() (mailbox.mbox のメソッド)
@anchor{library/mailbox mailbox mbox get_string}@anchor{3c33}
@deffn {メソッド} get_string (key, from_=False)

Note: This method has an extra parameter (`from_') compared with other classes.
The first line of an mbox file entry is the Unix "From " line.
If `from_' is False, the first line of the file is dropped.
@end deffn

@geindex lock() (mailbox.mbox のメソッド)
@geindex unlock() (mailbox.mbox のメソッド)
@anchor{library/mailbox mailbox mbox lock}@anchor{3c34}
@deffn {メソッド} lock ()
@anchor{library/mailbox mailbox mbox unlock}@anchor{3c35}
@deffnx {メソッド} unlock ()

3種類のロック機構が使われます --- ドットロッキングと、もし使用可能ならば @code{flock()} と @code{lockf()} システムコールです。
@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item tin の mbox マニュアルページ@footnote{http://www.tin.org/bin/man.cgi?section=5&topic=mbox}

mbox 形式の仕様でロックについての詳細を含む。

@item Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad@footnote{https://www.jwz.org/doc/content-length.html}

バリエーションの一つではなくオリジナルの mbox を使う理由。

@item "mbox" は相互に互換性を持たないいくつかのメールボックスフォーマットの集まりです@footnote{https://www.loc.gov/preservation/digital/formats/fdd/fdd000383.shtml}

mbox バリエーションの歴史。
@end table


@node MH オブジェクト,Babyl オブジェクト,mbox オブジェクト,Mailbox オブジェクト
@anchor{library/mailbox mailbox-mh}@anchor{3c36}@anchor{library/mailbox mh-objects}@anchor{3c37}
@subsubsection @code{MH} オブジェクト


@geindex MH (mailbox のクラス)
@anchor{library/mailbox mailbox MH}@anchor{1a2d}
@deffn {クラス} mailbox.MH (path, factory=None, create=True)

MH 形式のメールボックスのための @ref{1463,,Mailbox} のサブクラス。パラメータ `factory' は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 `factory' が @code{None} ならば、 @ref{3c38,,MHMessage} がデフォルトのメッセージ表現として使われます。 `create' が @code{True} ならばメールボックスが存在しないときには作成します。

MH はディレクトリに基づいたメールボックス形式で MH Message Handling System というメールユーザエージェントのために発明されました。 MH メールボックス中のそれぞれのメッセージは一つのファイルとして収められています。 MH メールボックスにはメッセージの他に別の MH メールボックス (`フォルダ' と呼ばれます)を含んでもかまいません。フォルダは無限にネストできます。 MH メールボックスにはもう一つ `シーケンス' という名前付きのリストでメッセージをサブフォルダに移動することなく論理的に分類するものがサポートされています。シーケンスは各フォルダの @code{.mh_sequences} というファイルで定義されます。

@code{MH} クラスは MH メールボックスを操作しますが、 @code{mh} の動作の全てを模倣しようとはしていません。特に、 @code{mh} が状態と設定を保存する @code{context} や @code{.mh_profile} といったファイルは書き換えませんし影響も受けません。

@code{MH} インスタンスには @ref{1463,,Mailbox} の全てのメソッドの他に次のメソッドがあります:


バージョン 3.13 で変更: Supported folders that don't contain a @code{.mh_sequences} file.


@geindex list_folders() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH list_folders}@anchor{3c39}
@deffn {メソッド} list_folders ()

全てのフォルダ名のリストを返します。
@end deffn

@geindex get_folder() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH get_folder}@anchor{3c3a}
@deffn {メソッド} get_folder (folder)

`folder' という名前のフォルダを表わす @code{MH} インスタンスを返します。もしフォルダが存在しなければ @ref{3c1c,,NoSuchMailboxError} 例外が送出されます。
@end deffn

@geindex add_folder() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH add_folder}@anchor{3c3b}
@deffn {メソッド} add_folder (folder)

`folder' という名前のフォルダを作成し、それを表わす @code{MH} インスタンスを返します。
@end deffn

@geindex remove_folder() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH remove_folder}@anchor{3c3c}
@deffn {メソッド} remove_folder (folder)

名前が `folder' であるフォルダを削除します。もしフォルダに一つでもメッセージが含まれていれば @ref{3c1f,,NotEmptyError} 例外が送出されフォルダは削除されません。
@end deffn

@geindex get_sequences() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH get_sequences}@anchor{3c3d}
@deffn {メソッド} get_sequences ()

シーケンス名をキーのリストに対応付ける辞書を返します。シーケンスが一つもなければ空の辞書を返します。
@end deffn

@geindex set_sequences() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH set_sequences}@anchor{3c3e}
@deffn {メソッド} set_sequences (sequences)

メールボックス中のシーケンスを @ref{3c3d,,get_sequences()} で返されるような名前とキーのリストを対応付ける辞書 `sequences' に基づいて再定義します。
@end deffn

@geindex pack() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH pack}@anchor{3c3f}
@deffn {メソッド} pack ()

番号付けの間隔を詰める必要に応じてメールボックス中のメッセージの名前を付け替えます。シーケンスのリストのエントリもそれに応じて更新されます。

@cartouche
@quotation 注釈 
既に発行されたキーはこの操作によって無効になるのでそれ以降使ってはなりません。
@end quotation
@end cartouche
@end deffn

@code{MH} で実装された @ref{1463,,Mailbox} のいくつかのメソッドには特別な注意が必要です:

@geindex remove() (mailbox.MH のメソッド)
@geindex __delitem__() (mailbox.MH のメソッド)
@geindex discard() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH remove}@anchor{3c40}
@deffn {メソッド} remove (key)
@anchor{library/mailbox mailbox MH __delitem__}@anchor{3c41}
@deffnx {メソッド} __delitem__ (key)
@anchor{library/mailbox mailbox MH discard}@anchor{3c42}
@deffnx {メソッド} discard (key)

これらのメソッドはメッセージを直ちに削除します。名前の前にコンマを付加してメッセージに削除の印を付けるという MH の規約は使いません。
@end deffn

@geindex lock() (mailbox.MH のメソッド)
@geindex unlock() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH lock}@anchor{3c43}
@deffn {メソッド} lock ()
@anchor{library/mailbox mailbox MH unlock}@anchor{3c44}
@deffnx {メソッド} unlock ()

3種類のロック機構が使われます --- ドットロッキングと、もし使用可能ならば @code{flock()} と @code{lockf()} システムコールです。 MH メールボックスに対するロックとは @code{.mh_sequences} のロックと、それが影響を与える操作中だけの個々のメッセージファイルに対するロックを意味します。
@end deffn

@geindex get_file() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH get_file}@anchor{3c45}
@deffn {メソッド} get_file (key)

ホストプラットフォームにより、ファイルが開かれたままの場合はメッセージを削除することができない場合があります。
@end deffn

@geindex flush() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH flush}@anchor{3c46}
@deffn {メソッド} flush ()

MH メールボックスへの変更は即時に適用されますのでこのメソッドは何もしません。
@end deffn

@geindex close() (mailbox.MH のメソッド)
@anchor{library/mailbox mailbox MH close}@anchor{3c47}
@deffn {メソッド} close ()

@code{MH} インスタンスは開いたファイルを保持しませんのでこのメソッドは @ref{3c44,,unlock()} と同じです。
@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item nmh - Message Handling System@footnote{https://www.nongnu.org/nmh/}

@code{mh} の改良版である @code{nmh} のホームページ。

@item MH & nmh: Email for Users & Programmers@footnote{https://rand-mh.sourceforge.io/book/}

GPLライセンスの @code{mh} および @code{nmh} の本で、このメールボックス形式についての情報があります。
@end table


@node Babyl オブジェクト,MMDF オブジェクト,MH オブジェクト,Mailbox オブジェクト
@anchor{library/mailbox babyl-objects}@anchor{3c48}@anchor{library/mailbox mailbox-babyl}@anchor{3c49}
@subsubsection @code{Babyl} オブジェクト


@geindex Babyl (mailbox のクラス)
@anchor{library/mailbox mailbox Babyl}@anchor{3c4a}
@deffn {クラス} mailbox.Babyl (path, factory=None, create=True)

Babyl 形式のメールボックスのための @ref{1463,,Mailbox} のサブクラス。パラメータ `factory' は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 `factory' が @code{None} ならば、 @ref{3c4b,,BabylMessage} がデフォルトのメッセージ表現として使われます。 `create' が @code{True} ならばメールボックスが存在しないときには作成します。

Babyl は単一ファイルのメールボックス形式で Emacs に付属している Rmail メールユーザエージェントで使われているものです。メッセージの開始は Control-Underscore (@code{'\037'}) および Control-L (@code{'\014'}) の二文字を含む行で示されます。メッセージの終了は次のメッセージの開始または最後のメッセージの場合には Control-Underscore を含む行で示されます。

Babyl メールボックス中のメッセージには二つのヘッダのセット、オリジナルヘッダといわゆる可視ヘッダ、があります。可視ヘッダは典型的にはオリジナルヘッダの一部を分り易いように再整形したり短くしたりしたものです。 Babyl メールボックス中のそれぞれのメッセージには `ラベル' というそのメッセージについての追加情報を記録する短い文字列のリストを伴い、メールボックス中に見出されるユーザが定義した全てのラベルのリストは Babyl オプションセクションに保持されます。

@code{Babyl} インスタンスには @ref{1463,,Mailbox} の全てのメソッドの他に次のメソッドがあります:

@geindex get_labels() (mailbox.Babyl のメソッド)
@anchor{library/mailbox mailbox Babyl get_labels}@anchor{3c4c}
@deffn {メソッド} get_labels ()

メールボックスで使われているユーザが定義した全てのラベルのリストを返します。

@cartouche
@quotation 注釈 
メールボックスにどのようなラベルが存在するかを決めるのに、Babyl オプションセクションのリストを参考にせず、実際のメッセージを捜索しますが、Babyl セクションもメールボックスが変更されたときにはいつでも更新されます。
@end quotation
@end cartouche
@end deffn

@code{Babyl} で実装された @ref{1463,,Mailbox} のいくつかのメソッドには特別な注意が必要です:

@geindex get_file() (mailbox.Babyl のメソッド)
@anchor{library/mailbox mailbox Babyl get_file}@anchor{3c4d}
@deffn {メソッド} get_file (key)

Babyl メールボックスにおいて、メッセージのヘッダはボディと繋がって格納されていません。ファイル風の表現を生成するために、ヘッダとボディがファイルと同じ API を持つ @ref{10a4,,io.BytesIO} インスタンスに一緒にコピーされます。その結果、ファイル風オブジェクトは元にしているメールボックスとは真に独立していますが、文字列表現と比べてメモリーを節約することにはなりません。
@end deffn

@geindex lock() (mailbox.Babyl のメソッド)
@geindex unlock() (mailbox.Babyl のメソッド)
@anchor{library/mailbox mailbox Babyl lock}@anchor{3c4e}
@deffn {メソッド} lock ()
@anchor{library/mailbox mailbox Babyl unlock}@anchor{3c4f}
@deffnx {メソッド} unlock ()

3種類のロック機構が使われます --- ドットロッキングと、もし使用可能ならば @code{flock()} と @code{lockf()} システムコールです。
@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item Format of Version 5 Babyl Files@footnote{https://quimby.gnus.org/notes/BABYL}

Babyl 形式の仕様。

@item Reading Mail with Rmail@footnote{https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html}

Rmail のマニュアルで Babyl のセマンティクスについての情報も少しある。
@end table


@node MMDF オブジェクト,,Babyl オブジェクト,Mailbox オブジェクト
@anchor{library/mailbox mailbox-mmdf}@anchor{3c50}@anchor{library/mailbox mmdf-objects}@anchor{3c51}
@subsubsection @code{MMDF} オブジェクト


@geindex MMDF (mailbox のクラス)
@anchor{library/mailbox mailbox MMDF}@anchor{19fc}
@deffn {クラス} mailbox.MMDF (path, factory=None, create=True)

MMDF 形式のメールボックスのための @ref{1463,,Mailbox} のサブクラス。パラメータ `factory' は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 `factory' が @code{None} ならば、 @ref{3c52,,MMDFMessage} がデフォルトのメッセージ表現として使われます。 `create' が @code{True} ならばメールボックスが存在しないときには作成します。

MMDF は単一ファイルのメールボックス形式で Multichannel Memorandum Distribution Facility というメール転送エージェント用に発明されたものです。各メッセージは mbox と同様の形式で収められますが、前後を4つの Control-A (@code{'\001'}) を含む行で挟んであります。mbox 形式と同じようにそれぞれのメッセージの開始は "From " の5文字を含む行で示されますが、それ以外の場所での "From " は格納の際 ">From " には変えられません。それは追加されたメッセージ区切りによって新たなメッセージの開始と見間違うことが避けられるからです。

@code{MMDF} で実装された @ref{1463,,Mailbox} のいくつかのメソッドには特別な注意が必要です:

@geindex get_bytes() (mailbox.MMDF のメソッド)
@anchor{library/mailbox mailbox MMDF get_bytes}@anchor{3c53}
@deffn {メソッド} get_bytes (key, from_=False)

Note: This method has an extra parameter (`from_') compared with other classes.
The first line of an mbox file entry is the Unix "From " line.
If `from_' is False, the first line of the file is dropped.
@end deffn

@geindex get_file() (mailbox.MMDF のメソッド)
@anchor{library/mailbox mailbox MMDF get_file}@anchor{3c54}
@deffn {メソッド} get_file (key, from_=False)

@code{MMDF} インスタンスに対し @ref{19c1,,flush()} や meth:@cite{~Mailbox.close} を呼び出した後でファイルを使用すると予期しない結果を引き起こしたり例外が送出されたりすることがあります。

Note: This method has an extra parameter (`from_') compared with other classes.
The first line of an mbox file entry is the Unix "From " line.
If `from_' is False, the first line of the file is dropped.
@end deffn

@geindex lock() (mailbox.MMDF のメソッド)
@geindex unlock() (mailbox.MMDF のメソッド)
@anchor{library/mailbox mailbox MMDF lock}@anchor{3c55}
@deffn {メソッド} lock ()
@anchor{library/mailbox mailbox MMDF unlock}@anchor{3c56}
@deffnx {メソッド} unlock ()

3種類のロック機構が使われます --- ドットロッキングと、もし使用可能ならば @code{flock()} と @code{lockf()} システムコールです。
@end deffn
@end deffn


@subsubheading 参考



@table @asis

@item mmdf man page from tin@footnote{http://www.tin.org/bin/man.cgi?section=5&topic=mmdf}

ニュースリーダ tin のドキュメント中の MMDF 形式仕様。

@item MMDF@footnote{https://en.wikipedia.org/wiki/MMDF}

Multichannel Memorandum Distribution Facility についてのウィキペディアの記事。
@end table


@node Message オブジェクト,例外<21>,Mailbox オブジェクト,mailbox --- 様々な形式のメールボックスを操作する
@anchor{library/mailbox mailbox-message-objects}@anchor{3c57}@anchor{library/mailbox message-objects}@anchor{3c58}
@subsubsection @code{Message} オブジェクト


@geindex Message (mailbox のクラス)
@anchor{library/mailbox mailbox Message}@anchor{1468}
@deffn {クラス} mailbox.Message (message=None)

@ref{48,,email.message} モジュールの @ref{581,,Message} のサブクラス。 @code{mailbox.Message} のサブクラスはメールボックス形式ごとの状態と動作を追加します。

If `message' is omitted, the new instance is created in a default, empty state.
If `message' is an @ref{581,,email.message.Message} instance, its contents are
copied; furthermore, any format-specific information is converted insofar as
possible if `message' is a @code{Message} instance. If `message' is a string,
a byte string,
or a file, it should contain an 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}-compliant message, which is read
and parsed.  Files should be open in binary mode, but text mode files
are accepted for backward compatibility.

サブクラスにより提供される形式ごとの状態と動作は様々ですが、一般に或るメールボックスに固有のものでないプロパティだけがサポートされます(おそらくプロパティのセットはメールボックス形式ごとに固有でしょうが)。例えば、単一ファイルメールボックス形式におけるファイルオフセットやディレクトリ式メールボックス形式におけるファイル名は保持されません、というのもそれらは元々のメールボックスにしか適用できないからです。しかし、メッセージがユーザに読まれたかどうかあるいは重要だとマークされたかどうかという状態は保持されます、というのはそれらはメッセージ自体に適用されるからです。

@ref{1463,,Mailbox} インスタンスを使って取得したメッセージを表現するのに @code{Message} インスタンスが使われなければいけないとは要求していません。ある種の状況では @code{Message} による表現を生成するのに必要な時間やメモリーが受け入れられないこともあります。そういった状況では @code{Mailbox} インスタンスは文字列やファイル風オブジェクトの表現も提供できますし、 @code{Mailbox} インスタンスを初期化する際にメッセージファクトリーを指定することもできます。
@end deffn

@menu
* MaildirMessage オブジェクト:: 
* mboxMessage オブジェクト:: 
* MHMessage オブジェクト:: 
* BabylMessage オブジェクト:: 
* MMDFMessage オブジェクト:: 

@end menu

@node MaildirMessage オブジェクト,mboxMessage オブジェクト,,Message オブジェクト
@anchor{library/mailbox mailbox-maildirmessage}@anchor{3c59}@anchor{library/mailbox maildirmessage-objects}@anchor{3c5a}
@subsubsection @code{MaildirMessage} オブジェクト


@geindex MaildirMessage (mailbox のクラス)
@anchor{library/mailbox mailbox MaildirMessage}@anchor{3c18}
@deffn {クラス} mailbox.MaildirMessage (message=None)

Maildir 固有の動作をするメッセージ。引数 `message' は @ref{1468,,Message} のコンストラクタと同じ意味を持ちます。

通常、メールユーザエージェントは @code{new} サブディレクトリにある全てのメッセージをユーザが最初にメールボックスを開くか閉じるかした後で @code{cur} サブディレクトリに移動し、メッセージが実際に読まれたかどうかを記録します。 @code{cur} にある各メッセージには状態情報を保存するファイル名に付け加えられた "info" セクションがあります。(メールリーダの中には "info" セクションを @code{new} にあるメッセージに付けることもあります。) "info" セクションには二つの形式があります。一つは "2," の後に標準化されたフラグのリストを付けたもの (たとえば "2,FR")、もう一つは "1," の後にいわゆる実験的情報を付け加えるものです。 Maildir の標準的なフラグは以下の通りです:


@multitable {xxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@tab

説明

@item

D

@tab

ドラフト(Draft)

@tab

作成中

@item

F

@tab

フラグ付き(Flagged)

@tab

重要とされたもの

@item

P

@tab

通過(Passed)

@tab

転送、再送またはバウンス

@item

R

@tab

返答済み(Replied)

@tab

返答されたもの

@item

S

@tab

既読(Seen)

@tab

読んだもの

@item

T

@tab

ごみ(Trashed)

@tab

削除予定とされたもの

@end multitable


@code{MaildirMessage} インスタンスは以下のメソッドを提供します:

@geindex get_subdir() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage get_subdir}@anchor{3c5b}
@deffn {メソッド} get_subdir ()

"new" (メッセージが @code{new} サブディレクトリに保存されるべき場合) または "cur" (メッセージが @code{cur} サブディレクトリに保存されるべき場合)のどちらかを返します。

@cartouche
@quotation 注釈 
メッセージは通常メールボックスがアクセスされた後、メッセージが読まれたかどうかに関わらず @code{new} から @code{cur} に移動されます。メッセージ @code{msg} は @code{"S" in msg.get_flags()} が @code{True} ならば読まれています。
@end quotation
@end cartouche
@end deffn

@geindex set_subdir() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage set_subdir}@anchor{3c5c}
@deffn {メソッド} set_subdir (subdir)

メッセージが保存されるべきサブディレクトリをセットします。パラメータ `subdir' は "new" または "cur" のいずれかでなければなりません。
@end deffn

@geindex get_flags() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage get_flags}@anchor{3c21}
@deffn {メソッド} get_flags ()

現在セットされているフラグを特定する文字列を返します。メッセージが標準 Maildir 形式に準拠しているならば、結果はアルファベット順に並べられたゼロまたは1回の @code{'D'}、@code{'F'}、@code{'P'}、@code{'R'}、@code{'S'}、@code{'T'} をつなげたものです。空文字列が返されるのはフラグが一つもない場合、または "info" が実験的セマンティクスを使っている場合です。
@end deffn

@geindex set_flags() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage set_flags}@anchor{3c22}
@deffn {メソッド} set_flags (flags)

`flags' で指定されたフラグをセットし、他のフラグは下ろします。
@end deffn

@geindex add_flag() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage add_flag}@anchor{3c23}
@deffn {メソッド} add_flag (flag)

`flag' で指定されたフラグをセットしますが他のフラグは変えません。一度に二つ以上のフラグをセットすることは、`flag' に2文字以上の文字列を指定すればできます。現在の "info" はフラグの代わりに実験的情報を使っていても上書きされます。
@end deffn

@geindex remove_flag() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage remove_flag}@anchor{3c24}
@deffn {メソッド} remove_flag (flag)

Unset the flag(s) specified by `flag' without changing other flags. To
remove more than one flag at a time, `flag' may be a string of more than
one character.  If "info" contains experimental information rather than
flags, the current "info" is not modified.
@end deffn

@geindex get_date() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage get_date}@anchor{3c5d}
@deffn {メソッド} get_date ()

メッセージの配送日時をエポックからの秒数を表わす浮動小数点数で返します。
@end deffn

@geindex set_date() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage set_date}@anchor{3c5e}
@deffn {メソッド} set_date (date)

メッセージの配送日時を `date' にセットします。`date' はエポックからの秒数を表わす浮動小数点数です。
@end deffn

@geindex get_info() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage get_info}@anchor{3c26}
@deffn {メソッド} get_info ()

メッセージの "info" を含む文字列を返します。このメソッドは実験的 (即ちフラグのリストでない) "info" にアクセスし、また変更するのに役立ちます。
@end deffn

@geindex set_info() (mailbox.MaildirMessage のメソッド)
@anchor{library/mailbox mailbox MaildirMessage set_info}@anchor{3c27}
@deffn {メソッド} set_info (info)

"info" に文字列 `info' をセットします。
@end deffn
@end deffn

@code{MaildirMessage} インスタンスが @ref{3abf,,mboxMessage} や @ref{3c52,,MMDFMessage} のインスタンスに基づいて生成されるとき、 @code{Status} および @code{X-Status} ヘッダは省かれ以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3abf,,mboxMessage} または @ref{3c52,,MMDFMessage} の状態

@item

"cur" サブディレクトリ

@tab

O フラグ

@item

F フラグ

@tab

F フラグ

@item

R フラグ

@tab

A フラグ

@item

S フラグ

@tab

R フラグ

@item

T フラグ

@tab

D フラグ

@end multitable


@code{MaildirMessage} インスタンスが @ref{3c38,,MHMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c38,,MHMessage} の状態

@item

"cur" サブディレクトリ

@tab

"unseen" シーケンス

@item

"cur" サブディレクトリおよび S フラグ

@tab

"unseen" シーケンス無し

@item

F フラグ

@tab

"flagged" シーケンス

@item

R フラグ

@tab

"replied" シーケンス

@end multitable


@code{MaildirMessage} インスタンスが @ref{3c4b,,BabylMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c4b,,BabylMessage} の状態

@item

"cur" サブディレクトリ

@tab

"unseen" ラベル

@item

"cur" サブディレクトリおよび S フラグ

@tab

"unseen" ラベル無し

@item

P フラグ

@tab

"forwarded" または "resent" ラベル

@item

R フラグ

@tab

"answered" ラベル

@item

T フラグ

@tab

"deleted" ラベル

@end multitable


@node mboxMessage オブジェクト,MHMessage オブジェクト,MaildirMessage オブジェクト,Message オブジェクト
@anchor{library/mailbox mailbox-mboxmessage}@anchor{3c5f}@anchor{library/mailbox mboxmessage-objects}@anchor{3c60}
@subsubsection @code{mboxMessage} オブジェクト


@geindex mboxMessage (mailbox のクラス)
@anchor{library/mailbox mailbox mboxMessage}@anchor{3abf}
@deffn {クラス} mailbox.mboxMessage (message=None)

mbox 固有の動作をするメッセージ。引数 `message' は @ref{1468,,Message} のコンストラクタと同じ意味を持ちます。

mbox メールボックス中のメッセージは単一ファイルにまとめて格納されています。送り主のエンベロープアドレスおよび配送日時は通常メッセージの開始を示す "From " から始まる行に記録されますが、正確なフォーマットに関しては mbox の実装ごとに大きな違いがあります。メッセージの状態を示すフラグ、たとえば読んだかどうかあるいは重要だとマークを付けられているかどうかといったようなもの、は典型的には @code{Status} および @code{X-Status} に収められます。

規定されている mbox メッセージのフラグは以下の通りです:


@multitable {xxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@tab

説明

@item

R

@tab

読んだもの

@tab

読んだもの

@item

O

@tab

古い(Old)

@tab

以前に MUA に発見された

@item

D

@tab

削除(Deleted)

@tab

削除予定とされたもの

@item

F

@tab

フラグ付き(Flagged)

@tab

重要とされたもの

@item

A

@tab

返答済み(Answered)

@tab

返答されたもの

@end multitable


"R" および "O" フラグは @code{Status} ヘッダに記録され、 "D"、"F"、"A" フラグは @code{X-Status} ヘッダに記録されます。フラグとヘッダは通常記述された順番に出現します。

@code{mboxMessage} インスタンスは以下のメソッドを提供します:

@geindex get_from() (mailbox.mboxMessage のメソッド)
@anchor{library/mailbox mailbox mboxMessage get_from}@anchor{3c61}
@deffn {メソッド} get_from ()

mbox メールボックスのメッセージの開始を示す "From " 行を表わす文字列を返します。先頭の "From " および末尾の改行は含まれません。
@end deffn

@geindex set_from() (mailbox.mboxMessage のメソッド)
@anchor{library/mailbox mailbox mboxMessage set_from}@anchor{3c62}
@deffn {メソッド} set_from (from_, time_=None)

"From " 行を `from_' にセットします。 `from_' は先頭の "From " や末尾の改行を含まない形で指定しなければなりません。利便性のために、 `time_' を指定して適切に整形して `from_' に追加させることができます。 `time_' を指定する場合、それは @ref{ee6,,time.struct_time} インスタンス、 @ref{1402,,time.strftime()} に渡すのに適したタプル、または @code{True} (この場合 @ref{13d8,,time.gmtime()} を使います) のいずれかでなければなりません。
@end deffn

@geindex get_flags() (mailbox.mboxMessage のメソッド)
@anchor{library/mailbox mailbox mboxMessage get_flags}@anchor{3c63}
@deffn {メソッド} get_flags ()

現在セットされているフラグを特定する文字列を返します。メッセージが規定された形式に準拠しているならば、結果は次の順に並べられた 0回か1回の @code{'R'}、@code{'O'}、@code{'D'}、@code{'F'}、@code{'A'} です。
@end deffn

@geindex set_flags() (mailbox.mboxMessage のメソッド)
@anchor{library/mailbox mailbox mboxMessage set_flags}@anchor{3c64}
@deffn {メソッド} set_flags (flags)

`flags' で指定されたフラグをセットして、他のフラグは下ろします。`flags' は並べられたゼロまたは1回の @code{'R'}、@code{'O'}、@code{'D'}、@code{'F'}、@code{'A'} です。
@end deffn

@geindex add_flag() (mailbox.mboxMessage のメソッド)
@anchor{library/mailbox mailbox mboxMessage add_flag}@anchor{3c65}
@deffn {メソッド} add_flag (flag)

`flag' で指定されたフラグをセットしますが他のフラグは変えません。一度に二つ以上のフラグをセットすることは、`flag' に2文字以上の文字列を指定すればできます。
@end deffn

@geindex remove_flag() (mailbox.mboxMessage のメソッド)
@anchor{library/mailbox mailbox mboxMessage remove_flag}@anchor{3c66}
@deffn {メソッド} remove_flag (flag)

Unset the flag(s) specified by `flag' without changing other flags. To
remove more than one flag at a time, `flag' may be a string of more than
one character.
@end deffn
@end deffn

@code{mboxMessage} インスタンスが @ref{3c18,,MaildirMessage} インスタンスに基づいて生成されるとき、 @ref{3c18,,MaildirMessage} インスタンスの配送日時に基づいて "From " 行が作り出され、次の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c18,,MaildirMessage} の状態

@item

R フラグ

@tab

S フラグ

@item

O フラグ

@tab

"cur" サブディレクトリ

@item

D フラグ

@tab

T フラグ

@item

F フラグ

@tab

F フラグ

@item

A フラグ

@tab

R フラグ

@end multitable


@code{mboxMessage} インスタンスが @ref{3c38,,MHMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c38,,MHMessage} の状態

@item

R フラグおよび O フラグ

@tab

"unseen" シーケンス無し

@item

O フラグ

@tab

"unseen" シーケンス

@item

F フラグ

@tab

"flagged" シーケンス

@item

A フラグ

@tab

"replied" シーケンス

@end multitable


@code{mboxMessage} インスタンスが @ref{3c4b,,BabylMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c4b,,BabylMessage} の状態

@item

R フラグおよび O フラグ

@tab

"unseen" ラベル無し

@item

O フラグ

@tab

"unseen" ラベル

@item

D フラグ

@tab

"deleted" ラベル

@item

A フラグ

@tab

"answered" ラベル

@end multitable


@code{mboxMessage} インスタンスが @ref{3c52,,MMDFMessage} インスタンスに基づいて生成されるとき、"From " 行はコピーされ全てのフラグは直接対応します:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c52,,MMDFMessage} の状態

@item

R フラグ

@tab

R フラグ

@item

O フラグ

@tab

O フラグ

@item

D フラグ

@tab

D フラグ

@item

F フラグ

@tab

F フラグ

@item

A フラグ

@tab

A フラグ

@end multitable


@node MHMessage オブジェクト,BabylMessage オブジェクト,mboxMessage オブジェクト,Message オブジェクト
@anchor{library/mailbox mailbox-mhmessage}@anchor{3c67}@anchor{library/mailbox mhmessage-objects}@anchor{3c68}
@subsubsection @code{MHMessage} オブジェクト


@geindex MHMessage (mailbox のクラス)
@anchor{library/mailbox mailbox MHMessage}@anchor{3c38}
@deffn {クラス} mailbox.MHMessage (message=None)

MH 固有の動作をするメッセージ。引数 `message' は @ref{1468,,Message} のコンストラクタと同じ意味を持ちます。

MH メッセージは伝統的な意味あいにおいてマークやフラグをサポートしません。しかし、MH メッセージにはシーケンスがあり任意のメッセージを論理的にグループ分けできます。いくつかのメールソフト(標準の @code{mh} や @code{nmh} はそうではありませんが) は他の形式におけるフラグとほぼ同じようにシーケンスを使います:


@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

シーケンス

@tab

説明

@item

unseen

@tab

読んではいないが既にMUAに見つけられている

@item

replied

@tab

返答されたもの

@item

flagged

@tab

重要とされたもの

@end multitable


@code{MHMessage} インスタンスは以下のメソッドを提供します:

@geindex get_sequences() (mailbox.MHMessage のメソッド)
@anchor{library/mailbox mailbox MHMessage get_sequences}@anchor{3c69}
@deffn {メソッド} get_sequences ()

このメッセージを含むシーケンスの名前のリストを返す。
@end deffn

@geindex set_sequences() (mailbox.MHMessage のメソッド)
@anchor{library/mailbox mailbox MHMessage set_sequences}@anchor{3c6a}
@deffn {メソッド} set_sequences (sequences)

このメッセージを含むシーケンスのリストをセットする。
@end deffn

@geindex add_sequence() (mailbox.MHMessage のメソッド)
@anchor{library/mailbox mailbox MHMessage add_sequence}@anchor{3c6b}
@deffn {メソッド} add_sequence (sequence)

`sequence' をこのメッセージを含むシーケンスのリストに追加する。
@end deffn

@geindex remove_sequence() (mailbox.MHMessage のメソッド)
@anchor{library/mailbox mailbox MHMessage remove_sequence}@anchor{3c6c}
@deffn {メソッド} remove_sequence (sequence)

`sequence' をこのメッセージを含むシーケンスのリストから除く。
@end deffn
@end deffn

@code{MHMessage} インスタンスが @ref{3c18,,MaildirMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c18,,MaildirMessage} の状態

@item

"unseen" シーケンス

@tab

S フラグ無し

@item

"replied" シーケンス

@tab

R フラグ

@item

"flagged" シーケンス

@tab

F フラグ

@end multitable


@code{MHMessage} インスタンスが @ref{3abf,,mboxMessage} や @ref{3c52,,MMDFMessage} のインスタンスに基づいて生成されるとき、 @code{Status} および @code{X-Status} ヘッダは省かれ以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3abf,,mboxMessage} または @ref{3c52,,MMDFMessage} の状態

@item

"unseen" シーケンス

@tab

R フラグ無し

@item

"replied" シーケンス

@tab

A フラグ

@item

"flagged" シーケンス

@tab

F フラグ

@end multitable


@code{MHMessage} インスタンスが @ref{3c4b,,BabylMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c4b,,BabylMessage} の状態

@item

"unseen" シーケンス

@tab

"unseen" ラベル

@item

"replied" シーケンス

@tab

"answered" ラベル

@end multitable


@node BabylMessage オブジェクト,MMDFMessage オブジェクト,MHMessage オブジェクト,Message オブジェクト
@anchor{library/mailbox babylmessage-objects}@anchor{3c6d}@anchor{library/mailbox mailbox-babylmessage}@anchor{3c6e}
@subsubsection @code{BabylMessage} オブジェクト


@geindex BabylMessage (mailbox のクラス)
@anchor{library/mailbox mailbox BabylMessage}@anchor{3c4b}
@deffn {クラス} mailbox.BabylMessage (message=None)

Babyl 固有の動作をするメッセージ。引数 `message' は @ref{1468,,Message} のコンストラクタと同じ意味を持ちます。

ある種のメッセージラベルは `アトリビュート' と呼ばれ、規約により特別な意味が与えられています。アトリビュートは以下の通りです:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ラベル

@tab

説明

@item

unseen

@tab

読んではいないが既にMUAに見つけられている

@item

deleted

@tab

削除予定とされたもの

@item

filed

@tab

他のファイルまたはメールボックスにコピーされた

@item

answered

@tab

返答されたもの

@item

forwarded

@tab

転送された

@item

edited

@tab

ユーザによって変更された

@item

resent

@tab

再送された

@end multitable


デフォルトでは Rmail は可視ヘッダのみ表示します。 @code{BabylMessage} クラスはしかし、オリジナルヘッダをより完全だという理由で使います。可視ヘッダは望むならそのように指示してアクセスすることができます。

@code{BabylMessage} インスタンスは以下のメソッドを提供します:

@geindex get_labels() (mailbox.BabylMessage のメソッド)
@anchor{library/mailbox mailbox BabylMessage get_labels}@anchor{3c6f}
@deffn {メソッド} get_labels ()

メッセージに付いているラベルのリストを返します。
@end deffn

@geindex set_labels() (mailbox.BabylMessage のメソッド)
@anchor{library/mailbox mailbox BabylMessage set_labels}@anchor{3c70}
@deffn {メソッド} set_labels (labels)

メッセージに付いているラベルのリストを `labels' にセットします。
@end deffn

@geindex add_label() (mailbox.BabylMessage のメソッド)
@anchor{library/mailbox mailbox BabylMessage add_label}@anchor{3c71}
@deffn {メソッド} add_label (label)

メッセージに付いているラベルのリストに `label' を追加します。
@end deffn

@geindex remove_label() (mailbox.BabylMessage のメソッド)
@anchor{library/mailbox mailbox BabylMessage remove_label}@anchor{3c72}
@deffn {メソッド} remove_label (label)

メッセージに付いているラベルのリストから `label' を削除します。
@end deffn

@geindex get_visible() (mailbox.BabylMessage のメソッド)
@anchor{library/mailbox mailbox BabylMessage get_visible}@anchor{3c73}
@deffn {メソッド} get_visible ()

ヘッダがメッセージの可視ヘッダでありボディが空であるような @ref{1468,,Message} インスタンスを返します。
@end deffn

@geindex set_visible() (mailbox.BabylMessage のメソッド)
@anchor{library/mailbox mailbox BabylMessage set_visible}@anchor{3c74}
@deffn {メソッド} set_visible (visible)

メッセージの可視ヘッダを `visible' のヘッダと同じにセットします。引数 `visible' は @ref{1468,,Message} インスタンスまたは @ref{581,,email.message.Message} インスタンス、文字列、ファイル風オブジェクト(テキストモードで開かれてなければなりません)のいずれかです。
@end deffn

@geindex update_visible() (mailbox.BabylMessage のメソッド)
@anchor{library/mailbox mailbox BabylMessage update_visible}@anchor{3c75}
@deffn {メソッド} update_visible ()

@code{BabylMessage} インスタンスのオリジナルヘッダが変更されたとき、可視ヘッダは自動的に対応して変更されるわけではありません。このメソッドは可視ヘッダを以下のように更新します。対応するオリジナルヘッダのある可視ヘッダはオリジナルヘッダの値がセットされます。対応するオリジナルヘッダの無い可視ヘッダは除去されます。そして、オリジナルヘッダにあって可視ヘッダに無い @code{Date} 、 @code{From} 、 @code{Reply-To} 、 @code{To} 、 @code{CC} 、 @code{Subject} は可視ヘッダに追加されます。
@end deffn
@end deffn

@code{BabylMessage} インスタンスが @ref{3c18,,MaildirMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c18,,MaildirMessage} の状態

@item

"unseen" ラベル

@tab

S フラグ無し

@item

"deleted" ラベル

@tab

T フラグ

@item

"answered" ラベル

@tab

R フラグ

@item

"forwarded" ラベル

@tab

P フラグ

@end multitable


@code{BabylMessage} インスタンスが @ref{3abf,,mboxMessage} や @ref{3c52,,MMDFMessage} のインスタンスに基づいて生成されるとき、 @code{Status} および @code{X-Status} ヘッダは省かれ以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3abf,,mboxMessage} または @ref{3c52,,MMDFMessage} の状態

@item

"unseen" ラベル

@tab

R フラグ無し

@item

"deleted" ラベル

@tab

D フラグ

@item

"answered" ラベル

@tab

A フラグ

@end multitable


@code{BabylMessage} インスタンスが @ref{3c38,,MHMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c38,,MHMessage} の状態

@item

"unseen" ラベル

@tab

"unseen" シーケンス

@item

"answered" ラベル

@tab

"replied" シーケンス

@end multitable


@node MMDFMessage オブジェクト,,BabylMessage オブジェクト,Message オブジェクト
@anchor{library/mailbox mailbox-mmdfmessage}@anchor{3c76}@anchor{library/mailbox mmdfmessage-objects}@anchor{3c77}
@subsubsection @code{MMDFMessage} オブジェクト


@geindex MMDFMessage (mailbox のクラス)
@anchor{library/mailbox mailbox MMDFMessage}@anchor{3c52}
@deffn {クラス} mailbox.MMDFMessage (message=None)

MMDF 固有の動作をするメッセージ。引数 `message' は @ref{1468,,Message} のコンストラクタと同じ意味を持ちます。

mbox メールボックスのメッセージと同様に、MMDF メッセージは送り主のアドレスと配送日時が最初の "From " で始まる行に記録されています。同様に、メッセージの状態を示すフラグは通常 @code{Status} および @code{X-Status} ヘッダに収められています。

よく使われる MMDF メッセージのフラグは mbox メッセージのものと同一で以下の通りです:


@multitable {xxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@tab

説明

@item

R

@tab

読んだもの

@tab

読んだもの

@item

O

@tab

古い(Old)

@tab

以前に MUA に発見された

@item

D

@tab

削除(Deleted)

@tab

削除予定とされたもの

@item

F

@tab

フラグ付き(Flagged)

@tab

重要とされたもの

@item

A

@tab

返答済み(Answered)

@tab

返答されたもの

@end multitable


"R" および "O" フラグは @code{Status} ヘッダに記録され、 "D"、"F"、"A" フラグは @code{X-Status} ヘッダに記録されます。フラグとヘッダは通常記述された順番に出現します。

@code{MMDFMessage} インスタンスは @ref{3abf,,mboxMessage} インスタンスと同一の以下のメソッドを提供します:

@geindex get_from() (mailbox.MMDFMessage のメソッド)
@anchor{library/mailbox mailbox MMDFMessage get_from}@anchor{3c78}
@deffn {メソッド} get_from ()

mbox メールボックスのメッセージの開始を示す "From " 行を表わす文字列を返します。先頭の "From " および末尾の改行は含まれません。
@end deffn

@geindex set_from() (mailbox.MMDFMessage のメソッド)
@anchor{library/mailbox mailbox MMDFMessage set_from}@anchor{3c79}
@deffn {メソッド} set_from (from_, time_=None)

"From " 行を `from_' にセットします。 `from_' は先頭の "From " や末尾の改行を含まない形で指定しなければなりません。利便性のために、 `time_' を指定して適切に整形して `from_' に追加させることができます。 `time_' を指定する場合、それは @ref{ee6,,time.struct_time} インスタンス、 @ref{1402,,time.strftime()} に渡すのに適したタプル、または @code{True} (この場合 @ref{13d8,,time.gmtime()} を使います) のいずれかでなければなりません。
@end deffn

@geindex get_flags() (mailbox.MMDFMessage のメソッド)
@anchor{library/mailbox mailbox MMDFMessage get_flags}@anchor{3c7a}
@deffn {メソッド} get_flags ()

現在セットされているフラグを特定する文字列を返します。メッセージが規定された形式に準拠しているならば、結果は次の順に並べられた 0回か1回の @code{'R'}、@code{'O'}、@code{'D'}、@code{'F'}、@code{'A'} です。
@end deffn

@geindex set_flags() (mailbox.MMDFMessage のメソッド)
@anchor{library/mailbox mailbox MMDFMessage set_flags}@anchor{3c7b}
@deffn {メソッド} set_flags (flags)

`flags' で指定されたフラグをセットして、他のフラグは下ろします。`flags' は並べられたゼロまたは1回の @code{'R'}、@code{'O'}、@code{'D'}、@code{'F'}、@code{'A'} です。
@end deffn

@geindex add_flag() (mailbox.MMDFMessage のメソッド)
@anchor{library/mailbox mailbox MMDFMessage add_flag}@anchor{3c7c}
@deffn {メソッド} add_flag (flag)

`flag' で指定されたフラグをセットしますが他のフラグは変えません。一度に二つ以上のフラグをセットすることは、`flag' に2文字以上の文字列を指定すればできます。
@end deffn

@geindex remove_flag() (mailbox.MMDFMessage のメソッド)
@anchor{library/mailbox mailbox MMDFMessage remove_flag}@anchor{3c7d}
@deffn {メソッド} remove_flag (flag)

Unset the flag(s) specified by `flag' without changing other flags. To
remove more than one flag at a time, `flag' may be a string of more than
one character.
@end deffn
@end deffn

@code{MMDFMessage} インスタンスが @ref{3c18,,MaildirMessage} インスタンスに基づいて生成されるとき、"From"行が @ref{3c18,,MaildirMessage} インスタンスの配信日をもとに生成され、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c18,,MaildirMessage} の状態

@item

R フラグ

@tab

S フラグ

@item

O フラグ

@tab

"cur" サブディレクトリ

@item

D フラグ

@tab

T フラグ

@item

F フラグ

@tab

F フラグ

@item

A フラグ

@tab

R フラグ

@end multitable


 @code{MMDFMessage} インスタンスが @ref{3c38,,MHMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c38,,MHMessage} の状態

@item

R フラグおよび O フラグ

@tab

"unseen" シーケンス無し

@item

O フラグ

@tab

"unseen" シーケンス

@item

F フラグ

@tab

"flagged" シーケンス

@item

A フラグ

@tab

"replied" シーケンス

@end multitable


@code{MMDFMessage} インスタンスが @ref{3c4b,,BabylMessage} インスタンスに基づいて生成されるとき、以下の変換が行われます:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3c4b,,BabylMessage} の状態

@item

R フラグおよび O フラグ

@tab

"unseen" ラベル無し

@item

O フラグ

@tab

"unseen" ラベル

@item

D フラグ

@tab

"deleted" ラベル

@item

A フラグ

@tab

"answered" ラベル

@end multitable


@code{MMDFMessage} インスタンスが @ref{3abf,,mboxMessage} インスタンスに基づいて生成されるとき、"From"行がコピーされ、全てのフラグが直接対応します:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

結果の状態

@tab

@ref{3abf,,mboxMessage} の状態

@item

R フラグ

@tab

R フラグ

@item

O フラグ

@tab

O フラグ

@item

D フラグ

@tab

D フラグ

@item

F フラグ

@tab

F フラグ

@item

A フラグ

@tab

A フラグ

@end multitable


@node 例外<21>,使用例<31>,Message オブジェクト,mailbox --- 様々な形式のメールボックスを操作する
@anchor{library/mailbox exceptions}@anchor{3c7e}
@subsubsection 例外


@code{mailbox} モジュールでは以下の例外クラスが定義されています:

@geindex Error
@anchor{library/mailbox mailbox Error}@anchor{3c7f}
@deffn {例外} mailbox.Error

The base class for all other module-specific exceptions.
@end deffn

@geindex NoSuchMailboxError
@anchor{library/mailbox mailbox NoSuchMailboxError}@anchor{3c1c}
@deffn {例外} mailbox.NoSuchMailboxError

メールボックスがあると思っていたが見つからなかった場合に送出されます。これはたとえば @ref{1463,,Mailbox} のサブクラスを存在しないパスでインスタンス化しようとしたとき(かつ `create' パラメータは @code{False} であった場合)、あるいは存在しないフォルダを開こうとした時などに発生します。
@end deffn

@geindex NotEmptyError
@anchor{library/mailbox mailbox NotEmptyError}@anchor{3c1f}
@deffn {例外} mailbox.NotEmptyError

メールボックスが空であることを期待されているときに空でない場合、たとえばメッセージの残っているフォルダを削除しようとした時などに送出されます。
@end deffn

@geindex ExternalClashError
@anchor{library/mailbox mailbox ExternalClashError}@anchor{3c14}
@deffn {例外} mailbox.ExternalClashError

Raised when some mailbox-related condition beyond the control of the program
causes it to be unable to proceed, such as when failing to acquire a lock that
another program already holds, or when a uniquely generated file name
already exists.
@end deffn

@geindex FormatError
@anchor{library/mailbox mailbox FormatError}@anchor{3c80}
@deffn {例外} mailbox.FormatError

ファイル中のデータが解析できない場合、たとえば @ref{1a2d,,MH} インスタンスが壊れた @code{.mh_sequences} ファイルを読もうと試みた場合などに送出されます。
@end deffn

@node 使用例<31>,,例外<21>,mailbox --- 様々な形式のメールボックスを操作する
@anchor{library/mailbox examples}@anchor{3c81}@anchor{library/mailbox mailbox-examples}@anchor{3c82}
@subsubsection 使用例


メールボックス中の面白そうなメッセージのサブジェクトを全て印字する簡単な例:

@example
import mailbox
for message in mailbox.mbox('~/mbox'):
    subject = message['subject']       # Could possibly be None.
    if subject and 'python' in subject.lower():
        print(subject)
@end example

Babyl メールボックスから MH メールボックスへ全てのメールをコピーし、変換可能な全ての形式固有の情報を変換する:

@example
import mailbox
destination = mailbox.MH('~/Mail')
destination.lock()
for message in mailbox.Babyl('~/RMAIL'):
    destination.add(mailbox.MHMessage(message))
destination.flush()
destination.unlock()
@end example

この例は幾つかのメーリングリストのメールをソートするものです。他のプログラムと平行して変更を加えることでメールが破損したり、プログラムを中断することでメールを失ったり、はたまた半端なメッセージがメールボックス中にあることで途中で終了してしまう、といったことを避けるように注意深く扱っています:

@example
import mailbox
import email.errors

list_names = ('python-list', 'python-dev', 'python-bugs')

boxes = @{name: mailbox.mbox('~/email/%s' % name) for name in list_names@}
inbox = mailbox.Maildir('~/Maildir', factory=None)

for key in inbox.iterkeys():
    try:
        message = inbox[key]
    except email.errors.MessageParseError:
        continue                # The message is malformed. Just leave it.

    for name in list_names:
        list_id = message['list-id']
        if list_id and name in list_id:
            # Get mailbox to use
            box = boxes[name]

            # Write copy to disk before removing original.
            # If there's a crash, you might duplicate a message, but
            # that's better than losing a message completely.
            box.lock()
            box.add(message)
            box.flush()
            box.unlock()

            # Remove original message
            inbox.lock()
            inbox.discard(key)
            inbox.flush()
            inbox.unlock()
            break               # Found destination, so stop looking.

for box in boxes.itervalues():
    box.close()
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node mimetypes --- ファイル名を MIME タイプへマップする,base64 --- Base16 Base32 Base64 Base85 データのエンコード,mailbox --- 様々な形式のメールボックスを操作する,インターネット上のデータの操作
@anchor{library/mimetypes doc}@anchor{3c83}@anchor{library/mimetypes mimetypes-map-filenames-to-mime-types}@anchor{3c84}@anchor{library/mimetypes module-mimetypes}@anchor{93}@anchor{library/mimetypes translation-repo}@anchor{3c85}
@subsection @code{mimetypes} --- ファイル名を MIME タイプへマップする


@geindex module; mimetypes

`ソースコード:' Lib/mimetypes.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/mimetypes.py}

@geindex MIME;content type


__________________________________________________________________


The @code{mimetypes} module converts between a filename or URL and the MIME type
associated with the filename extension.  Conversions are provided from filename
to MIME type and from MIME type to filename extension; encodings are not
supported for the latter conversion.

このモジュールは、一つのクラスと多くの便利な関数を提供します。これらの関数がこのモジュールへの標準のインターフェースですが、アプリケーションによっては、そのクラスにも関係するかもしれません。

以下で説明されている関数は、このモジュールへの主要なインターフェースを提供します。たとえモジュールが初期化されていなくても、もしこれらの関数が、 @ref{3c86,,init()} がセットアップする情報に依存していれば、これらの関数は、 @ref{3c86,,init()} を呼びます。

@geindex guess_type() (mimetypes モジュール)
@anchor{library/mimetypes mimetypes guess_type}@anchor{517}
@deffn {の関数} mimetypes.guess_type (url, strict=True)

@geindex MIME;ヘッダー

`url' で与えられるファイル名あるいは URL に基づいて、ファイルの型を推定します。URL は文字列または @ref{5a1,,path-like object} です。

戻り値は、タプル @code{(type, encoding)} です、ここで  `type' は、もし型が(拡張子がないあるいは未定義のため)推定できない場合は、 @code{None} を、あるいは、 MIME @code{content-type} ヘッダ  に利用できる、 @code{'type/subtype'} の形の文字列です。

`encoding' は、符合化方式がない場合は @code{None} を、あるいは、符号化に使われるプログラムの名前 (たとえば、 @code{compress} あるいは @code{gzip})です。符号化方式は @code{Content-Encoding} ヘッダとして使うのに適しており、 @code{Content-Transfer-Encoding} ヘッダには適して `いません' 。マッピングはテーブル駆動です。符号化方式のサフィックスは大/小文字を区別します; データ型サフィックスは、最初大/小文字を区別して試し、それから大/小文字を区別せずに試します。

The optional `strict' argument is a flag specifying whether the list of known MIME types
is limited to only the official types registered with IANA@footnote{https://www.iana.org/assignments/media-types/media-types.xhtml}.
However, the behavior of this module also depends on the underlying operating
system. Only file types recognized by the OS or explicitly registered with
Python's internal database can be identified. When `strict' is @code{True} (the
default), only the IANA types are supported; when `strict' is @code{False}, some
additional non-standard but commonly used MIME types are also recognized.


バージョン 3.8 で変更: Added support for `url' being a @ref{5a1,,path-like object}.



バージョン 3.13 で非推奨: Passing a file path instead of URL is @ref{23d,,soft deprecated}.
Use @ref{516,,guess_file_type()} for this.

@end deffn

@geindex guess_file_type() (mimetypes モジュール)
@anchor{library/mimetypes mimetypes guess_file_type}@anchor{516}
@deffn {の関数} mimetypes.guess_file_type (path, *, strict=True)

@geindex MIME;ヘッダー

Guess the type of a file based on its path, given by `path'.
Similar to the @ref{517,,guess_type()} function, but accepts a path instead of URL.
Path can be a string, a bytes object or a @ref{5a1,,path-like object}.


Added in version 3.13.

@end deffn

@geindex guess_all_extensions() (mimetypes モジュール)
@anchor{library/mimetypes mimetypes guess_all_extensions}@anchor{1c4a}
@deffn {の関数} mimetypes.guess_all_extensions (type, strict=True)

Guess the extensions for a file based on its MIME type, given by `type'. The
return value is a list of strings giving all possible filename extensions,
including the leading dot (@code{'.'}).  The extensions are not guaranteed to have
been associated with any particular data stream, but would be mapped to the MIME
type `type' by @ref{517,,guess_type()} and @ref{516,,guess_file_type()}.

省略可能な `strict' 引数は @ref{517,,guess_type()} 関数のものと同じ意味を持ちます。
@end deffn

@geindex guess_extension() (mimetypes モジュール)
@anchor{library/mimetypes mimetypes guess_extension}@anchor{3c87}
@deffn {の関数} mimetypes.guess_extension (type, strict=True)

Guess the extension for a file based on its MIME type, given by `type'. The
return value is a string giving a filename extension, including the leading dot
(@code{'.'}).  The extension is not guaranteed to have been associated with any
particular data stream, but would be mapped to the MIME type `type' by
@ref{517,,guess_type()} and @ref{516,,guess_file_type()}.
If no extension can be guessed for `type', @code{None} is returned.

省略可能な `strict' 引数は @ref{517,,guess_type()} 関数のものと同じ意味を持ちます。
@end deffn

モジュールの動作を制御するために、いくつかの追加の関数とデータ項目が利用できます。

@geindex init() (mimetypes モジュール)
@anchor{library/mimetypes mimetypes init}@anchor{3c86}
@deffn {の関数} mimetypes.init (files=None)

内部のデータ構造を初期化します。もし  `files' が与えられていれば、これはデフォルトの type map を増やすために使われる、一連のファイル名でなければなりません。もし省略されていれば、使われるファイル名は @ref{3c88,,knownfiles} から取られます。 Windows であれば、現在のレジストリの設定が読み込まれます。 `files' あるいは @ref{3c88,,knownfiles} 内の各ファイル名は、それ以前に現れる名前より優先されます。繰り返し @ref{3c86,,init()} を呼び出すことは許されています。

`files' に空リストを与えることで、システムのデフォルトが適用されるのを避けることが出来ます; 組み込みのリストから well-known な値だけが取り込まれます。

`files' が @code{None} の場合、内部のデータ構造は初期のデフォルト値に完全に再構築されます。
これは安定な操作であり、複数回呼び出されたときは同じ結果になります。


バージョン 3.2 で変更: 前のバージョンでは、 Windows のレジストリの設定は無視されていました。

@end deffn

@geindex read_mime_types() (mimetypes モジュール)
@anchor{library/mimetypes mimetypes read_mime_types}@anchor{1d2a}
@deffn {の関数} mimetypes.read_mime_types (filename)

ファイル `filename' で与えられた型のマップが、もしあればロードします。型のマップは、先頭の dot (@code{'.'}) を含むファイル名拡張子を、@code{'type/subtype'} の形の文字列にマッピングする辞書として返されます。もしファイル `filename' が存在しないか、読み込めなければ、@code{None} が返されます。
@end deffn

@geindex add_type() (mimetypes モジュール)
@anchor{library/mimetypes mimetypes add_type}@anchor{3c89}
@deffn {の関数} mimetypes.add_type (type, ext, strict=True)

MIME 型 `type' からのマッピングを拡張子 `ext' に追加します。拡張子がすでに既知であれば、新しい型が古いものに置き替わります。その型がすでに既知であれば、その拡張子が、既知の拡張子のリストに追加されます。

`strict' が @code{True} の時(デフォルト)は、そのマッピングは正式な MIME 型に、そうでなければ、非標準の MIME 型に追加されます。
@end deffn

@geindex inited (mimetypes モジュール)
@anchor{library/mimetypes mimetypes inited}@anchor{3c8a}
@deffn {データ} mimetypes.inited

グローバルなデータ構造が初期化されているかどうかを示すフラグ。これは @ref{3c86,,init()} により @code{True} に設定されます。
@end deffn

@geindex knownfiles (mimetypes モジュール)
@anchor{library/mimetypes mimetypes knownfiles}@anchor{3c88}
@deffn {データ} mimetypes.knownfiles

@geindex ファイル;mime.types

共通にインストールされた型マップファイル名のリスト。これらのファイルは、普通 @code{mime.types} という名前であり、パッケージごとに異なる場所にインストールされます。
@end deffn

@geindex suffix_map (mimetypes モジュール)
@anchor{library/mimetypes mimetypes suffix_map}@anchor{3c8b}
@deffn {データ} mimetypes.suffix_map

サフィックスをサフィックスにマップする辞書。これは、符号化方式と型が同一拡張子で示される符号化ファイルが認識できるように使用されます。例えば、 @code{.tgz} 拡張子は、符号化と型が別個に認識できるように @code{.tar.gz} にマップされます。
@end deffn

@geindex encodings_map (mimetypes モジュール)
@anchor{library/mimetypes mimetypes encodings_map}@anchor{3c8c}
@deffn {データ} mimetypes.encodings_map

ファイル名拡張子を符号化方式型にマッピングする辞書。
@end deffn

@geindex types_map (mimetypes モジュール)
@anchor{library/mimetypes mimetypes types_map}@anchor{3c8d}
@deffn {データ} mimetypes.types_map

ファイル名拡張子を MIME 型にマップする辞書。
@end deffn

@geindex common_types (mimetypes モジュール)
@anchor{library/mimetypes mimetypes common_types}@anchor{3c8e}
@deffn {データ} mimetypes.common_types

ファイル名拡張子を非標準ではあるが、一般に使われている MIME 型にマップする辞書。
@end deffn

モジュールの使用例:

@example
>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'
@end example

@menu
* MimeTypes objects:: 
* コマンドラインでの使用: コマンドラインでの使用<4>. 
* コマンドラインの例: コマンドラインの例<2>. 

@end menu

@node MimeTypes objects,コマンドラインでの使用<4>,,mimetypes --- ファイル名を MIME タイプへマップする
@anchor{library/mimetypes id1}@anchor{3c8f}@anchor{library/mimetypes mimetypes-objects}@anchor{3c90}
@subsubsection MimeTypes objects


The @ref{1714,,MimeTypes} class may be useful for applications which may want more
than one MIME-type database; it provides an interface similar to the one of the
@code{mimetypes} module.

@geindex MimeTypes (mimetypes のクラス)
@anchor{library/mimetypes mimetypes MimeTypes}@anchor{1714}
@deffn {クラス} mimetypes.MimeTypes (filenames=(), strict=True)

このクラスは、MIME 型データベースを表現します。デフォルトでは、このモジュールの他のものと同じデータベースへのアクセスを提供します。初期データベースは、このモジュールによって提供されるもののコピーで、追加の @code{mime.types} 形式のファイルを、 @ref{3c91,,read()} あるいは @ref{3c92,,readfp()} メソッドを使って、データベースにロードすることで拡張されます。マッピング辞書も、もしデフォルトのデータが望むものでなければ、追加のデータをロードする前にクリアされます。

省略可能な `filenames' パラメータは、追加のファイルを、デフォルトデータベースの"トップに"ロードさせるのに使うことができます。

@geindex suffix_map (mimetypes.MimeTypes の属性)
@anchor{library/mimetypes mimetypes MimeTypes suffix_map}@anchor{3c93}
@deffn {の属性} suffix_map

サフィックスをサフィックスにマップする辞書。これは、符号化方式と型が同一拡張子で示されるような符号化ファイルが認識できるように使用されます。例えば、 @code{.tgz} 拡張子は、符号化方式と型が別個に認識できるように @code{.tar.gz} に対応づけられます。これは、最初はモジュールで定義されたグローバルな @ref{3c8b,,suffix_map} のコピーです。
@end deffn

@geindex encodings_map (mimetypes.MimeTypes の属性)
@anchor{library/mimetypes mimetypes MimeTypes encodings_map}@anchor{3c94}
@deffn {の属性} encodings_map

ファイル名拡張子を符号化型にマッピングする辞書。これは、最初はモジュールで定義されたグローバルな @ref{3c8c,,encodings_map} のコピーです。
@end deffn

@geindex types_map (mimetypes.MimeTypes の属性)
@anchor{library/mimetypes mimetypes MimeTypes types_map}@anchor{3c95}
@deffn {の属性} types_map

ファイル名拡張子を MIME 型にマッピングする 2 種類の辞書のタプル; 最初の辞書は非標準型、二つ目は標準型の辞書です。初期状態ではそれぞれ @ref{3c8e,,common_types} と @ref{3c8d,,types_map} です。
@end deffn

@geindex types_map_inv (mimetypes.MimeTypes の属性)
@anchor{library/mimetypes mimetypes MimeTypes types_map_inv}@anchor{3c96}
@deffn {の属性} types_map_inv

MIME 型をファイル名拡張子のリストにマッピングする 2 種類の辞書のタプル; 最初の辞書は非標準型、二つ目は標準型の辞書です。初期状態ではそれぞれ @ref{3c8e,,common_types} と @ref{3c8d,,types_map} です。
@end deffn

@geindex guess_extension() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes guess_extension}@anchor{3c97}
@deffn {メソッド} guess_extension (type, strict=True)

@ref{3c87,,guess_extension()} 関数と同様ですが、オブジェクトに保存されたテーブルを使用します。
@end deffn

@geindex guess_type() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes guess_type}@anchor{1e19}
@deffn {メソッド} guess_type (url, strict=True)

@ref{517,,guess_type()} 関数と同様ですが、オブジェクトに保存されたテーブルを使用します。
@end deffn

@geindex guess_file_type() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes guess_file_type}@anchor{3c98}
@deffn {メソッド} guess_file_type (path, *, strict=True)

Similar to the @ref{516,,guess_file_type()} function, using the tables stored
as part of the object.


Added in version 3.13.

@end deffn

@geindex guess_all_extensions() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes guess_all_extensions}@anchor{3c99}
@deffn {メソッド} guess_all_extensions (type, strict=True)

@ref{1c4a,,guess_all_extensions()} と同様ですが、オブジェクトに保存されたテーブルを参照します。
@end deffn

@geindex read() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes read}@anchor{3c91}
@deffn {メソッド} read (filename, strict=True)

MIME 情報を、 `filename' という名のファイルからロードします。これはファイルを解析するのに @ref{3c92,,readfp()} を使用します。

`strict' が @code{True} の時 (デフォルト) は、そのマッピングは標準 MIME 型のリストに、そうでなければ、非標準 MIME 型のリストに追加されます。
@end deffn

@geindex readfp() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes readfp}@anchor{3c92}
@deffn {メソッド} readfp (fp, strict=True)

MIME 型情報を、オープンしたファイル `fp' からロードします。ファイルは、標準の @code{mime.types} ファイルの形式でなければなりません。

`strict' が @code{True} の時 (デフォルト) は、そのマッピングは標準 MIME 型のリストに、そうでなければ、非標準 MIME 型のリストに追加されます。
@end deffn

@geindex read_windows_registry() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes read_windows_registry}@anchor{3c9a}
@deffn {メソッド} read_windows_registry (strict=True)

MIME type 情報を Windows のレジストリから読み込みます。

@ref{213f,,Availability}: Windows.

`strict' が @code{True} の時 (デフォルト) は、そのマッピングは標準 MIME 型のリストに、そうでなければ、非標準 MIME 型のリストに追加されます。


Added in version 3.2.

@end deffn

@geindex add_type() (mimetypes.MimeTypes のメソッド)
@anchor{library/mimetypes mimetypes MimeTypes add_type}@anchor{319}
@deffn {メソッド} add_type (type, ext, strict=True)

Add a mapping from the MIME type `type' to the extension `ext'.
Valid extensions start with a '.' or are empty. When the
extension is already known, the new type will replace the old one. When the type
is already known the extension will be added to the list of known extensions.

`strict' が @code{True} の時(デフォルト)は、そのマッピングは正式な MIME 型に、そうでなければ、非標準の MIME 型に追加されます。


Deprecated since version 3.14, will be removed in version 3.16: Invalid, undotted extensions will raise a
@ref{2ec,,ValueError} in Python 3.16.

@end deffn
@end deffn

@node コマンドラインでの使用<4>,コマンドラインの例<2>,MimeTypes objects,mimetypes --- ファイル名を MIME タイプへマップする
@anchor{library/mimetypes command-line-usage}@anchor{3c9b}@anchor{library/mimetypes mimetypes-cli}@anchor{247}
@subsubsection コマンドラインでの使用


The @code{mimetypes} module can be executed as a script from the command line.

@example
python -m mimetypes [-h] [-e] [-l] type [type ...]
@end example

以下のオプションが使用できます:

@geindex mimetypes コマンドラインオプション; -h
@geindex mimetypes コマンドラインオプション; --help
@anchor{library/mimetypes cmdoption-mimetypes-h}@anchor{3c9c}
@deffn {プログラムオプション} @w{-}h
@anchor{library/mimetypes cmdoption-mimetypes-help}@anchor{3c9d}
@deffnx {プログラムオプション} @w{-}@w{-}help

ヘルプメッセージを表示して終了します。
@end deffn

@geindex mimetypes コマンドラインオプション; -e
@geindex mimetypes コマンドラインオプション; --extension
@anchor{library/mimetypes cmdoption-mimetypes-e}@anchor{3c9e}
@deffn {プログラムオプション} @w{-}e
@anchor{library/mimetypes cmdoption-mimetypes-extension}@anchor{3c9f}
@deffnx {プログラムオプション} @w{-}@w{-}extension

Guess extension instead of type.
@end deffn

@geindex mimetypes コマンドラインオプション; -l
@geindex mimetypes コマンドラインオプション; --lenient
@anchor{library/mimetypes cmdoption-mimetypes-l}@anchor{3ca0}
@deffn {プログラムオプション} @w{-}l
@anchor{library/mimetypes cmdoption-mimetypes-lenient}@anchor{3ca1}
@deffnx {プログラムオプション} @w{-}@w{-}lenient

Additionally search for some common, but non-standard types.
@end deffn

By default the script converts MIME types to file extensions.
However, if @code{--extension} is specified,
it converts file extensions to MIME types.

For each @code{type} entry, the script writes a line into the standard output
stream. If an unknown type occurs, it writes an error message into the
standard error stream and exits with the return code @code{1}.

@c mimetypes-cli-example:

@node コマンドラインの例<2>,,コマンドラインでの使用<4>,mimetypes --- ファイル名を MIME タイプへマップする
@anchor{library/mimetypes command-line-example}@anchor{3ca2}
@subsubsection コマンドラインの例


Here are some examples of typical usage of the @code{mimetypes} command-line
interface:

@example
$ # get a MIME type by a file name
$ python -m mimetypes filename.png
type: image/png encoding: None

$ # get a MIME type by a URL
$ python -m mimetypes https://example.com/filename.txt
type: text/plain encoding: None

$ # get a complex MIME type
$ python -m mimetypes filename.tar.gz
type: application/x-tar encoding: gzip

$ # get a MIME type for a rare file extension
$ python -m mimetypes filename.pict
error: unknown extension of filename.pict

$ # now look in the extended database built into Python
$ python -m mimetypes --lenient filename.pict
type: image/pict encoding: None

$ # get a file extension by a MIME type
$ python -m mimetypes --extension text/javascript
.js

$ # get a file extension by a rare MIME type
$ python -m mimetypes --extension text/xul
error: unknown type text/xul

$ # now look in the extended database again
$ python -m mimetypes --extension --lenient text/xul
.xul

$ # try to feed an unknown file extension
$ python -m mimetypes filename.sh filename.nc filename.xxx filename.txt
type: application/x-sh encoding: None
type: application/x-netcdf encoding: None
error: unknown extension of filename.xxx

$ # try to feed an unknown MIME type
$ python -m mimetypes --extension audio/aac audio/opus audio/future audio/x-wav
.aac
.opus
error: unknown type audio/future
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node base64 --- Base16 Base32 Base64 Base85 データのエンコード,binascii --- バイナリ と ASCII 間の変換,mimetypes --- ファイル名を MIME タイプへマップする,インターネット上のデータの操作
@anchor{library/base64 doc}@anchor{3ca3}@anchor{library/base64 base64-base16-base32-base64-base85-data-encodings}@anchor{3ca4}@anchor{library/base64 module-base64}@anchor{f}@anchor{library/base64 translation-repo}@anchor{3ca5}
@subsection @code{base64} --- Base16, Base32, Base64, Base85 データのエンコード


@geindex module; base64

`ソースコード:' Lib/base64.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/base64.py}

@geindex base64;encoding
@geindex MIME;base64 encoding


__________________________________________________________________


このモジュールは、バイナリデータを印刷可能なASCII文字列にエンコード、及びデコードするための関数を提供しています。
@geindex RFC; RFC 4648
RFC 4648@footnote{https://datatracker.ietf.org/doc/html/rfc4648.html} に @ref{3ca6,,定義されているエンコーディング} (Base64、Base32、Base16)に加えて標準ではない @ref{3ca7,,Base 85} をサポートしています。

このモジュールは、2つのインターフェースを提供します。このモダンなインターフェースは、@ref{193,,bytes-like object} を ASCII @ref{192,,bytes} にエンコードし、@ref{193,,bytes-like object} か ASCII 文字列を、@ref{192,,bytes} にデコードすることができます。
@geindex RFC; RFC 4648
RFC 4648@footnote{https://datatracker.ietf.org/doc/html/rfc4648.html} に定義されている base-64 アルファベット (一般の、URL あるいはファイルシステムセーフなもの) の両方が使用できます。

@ref{3ca8,,従来のインターフェース} は文字列からのデコードができませんが、@ref{13db,,file object} との間のエンコードとデコードが可能な関数を提供します。これは標準の base64 アルファベットのみをサポートし、
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} の規定にあるように、76文字ごとに改行されます。
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} のサポートのためには、代わりに @ref{3f,,email} パッケージを参照する必要があるかもしれません。


バージョン 3.3 で変更: モダンなインターフェイスのデコード関数が ASCII のみの Unicode 文字列を受け付けるようになりました。



バージョン 3.4 で変更: このモジュールのすべてのエンコード・デコード関数が任意の @ref{193,,bytes-like オブジェクト} を受け取るようになりました。Ascii85/Base85 のサポートが追加されました。


@menu
* RFC 4648 エンコーディング:: 
* Base85 エンコーディング:: 
* レガシーインターフェース:: 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<4>. 

@end menu

@node RFC 4648 エンコーディング,Base85 エンコーディング,,base64 --- Base16 Base32 Base64 Base85 データのエンコード
@anchor{library/base64 base64-rfc-4648}@anchor{3ca6}@anchor{library/base64 rfc-4648-encodings}@anchor{3ca9}
@subsubsection RFC 4648 エンコーディング


@geindex RFC; RFC 4648
RFC 4648@footnote{https://datatracker.ietf.org/doc/html/rfc4648.html} エンコーディングは、email で安全に送信したり、 URL の一部として使ったり、あるいは HTTP POST リクエストの一部に含めるために用いるのに適しています。

@geindex b64encode() (base64 モジュール)
@anchor{library/base64 base64 b64encode}@anchor{3caa}
@deffn {の関数} base64.b64encode (s, altchars=None)

Base64 を使って @ref{193,,bytes-like object} の `s' をエンコードし、エンコードされた @ref{192,,bytes} を返します。

オプション引数 `altchars' は長さ 2 の @ref{193,,bytes-like object} で 、@code{+} と @code{/} の代わりに使われる代替アルファベットを指定します。これにより、アプリケーションはたとえば URL やファイルシステムの影響を受けない Base64 文字列を生成できます。デフォルトは @code{None} で、標準の Base64 アルファベットが使われます。

`altchars' の長さが2でない場合は、 assert または @ref{2ec,,ValueError} が発生します。 `altchars' が @ref{193,,bytes-like object} でない場合は、 @ref{198,,TypeError} が発生します。
@end deffn

@geindex b64decode() (base64 モジュール)
@anchor{library/base64 base64 b64decode}@anchor{1d90}
@deffn {の関数} base64.b64decode (s, altchars=None, validate=False)

Base64 エンコードされた  @ref{193,,bytes-like object} または ASCII 文字列 `s' をデコードし、デコードされた @ref{192,,bytes} を返します。

オプション引数の `altchars' は長さ 2 の @ref{193,,bytes-like object}  または ASCII 文字列で、@code{+} と @code{/} の代わりに使われる代替アルファベットを指定します。

`s' が正しくパディングされていない場合は @ref{1227,,binascii.Error} 例外を発生させます。

`validate' が @code{False} (デフォルト) の場合、標準の base64 アルファベットでも代替文字でもない文字はパディングチェックの前に無視されます。 `validate' が @code{True} の場合、入力に base64 アルファベット以外の文字があると @ref{1227,,binascii.Error} を発生させます。

厳密な base64 チェックのについての詳細は @ref{19a4,,binascii.a2b_base64()} を参照してください

`altchars' の長さが2でない場合は、 assert または:exc:>>`<<ValueError`が発生します。
@end deffn

@geindex standard_b64encode() (base64 モジュール)
@anchor{library/base64 base64 standard_b64encode}@anchor{3cab}
@deffn {の関数} base64.standard_b64encode (s)

標準の base64 アルファベットを使用して  @ref{193,,bytes-like object} の `s' をエンコードし、エンコードされた @ref{192,,bytes} を返します。
@end deffn

@geindex standard_b64decode() (base64 モジュール)
@anchor{library/base64 base64 standard_b64decode}@anchor{3cac}
@deffn {の関数} base64.standard_b64decode (s)

標準の base64 アルファベットを使用した @ref{193,,bytes-like object} または ASCII 文字列 `s' をデコードし、デコードされた @ref{192,,bytes} を返します。
@end deffn

@geindex urlsafe_b64encode() (base64 モジュール)
@anchor{library/base64 base64 urlsafe_b64encode}@anchor{3cad}
@deffn {の関数} base64.urlsafe_b64encode (s)

@ref{193,,bytes-like object} `s' を URLとファイルシステムセーフなアルファベットを利用してエンコードし、エンコードされた @ref{192,,bytes} を返します。標準 base64 アルファベットに比べて、@code{+} の替わりに @code{-} を、@code{/} の替わりに @code{_} を利用します。結果は @code{=} を含みます。
@end deffn

@geindex urlsafe_b64decode() (base64 モジュール)
@anchor{library/base64 base64 urlsafe_b64decode}@anchor{3cae}
@deffn {の関数} base64.urlsafe_b64decode (s)

@ref{193,,bytes-like object} または ASCII 文字列 `s' を URLとファイルシステムセーフなアルファベットを利用してデコードし、デコードされた @ref{192,,bytes} を返します。標準 base64 アルファベットに比べて、@code{+} の替わりに @code{-} を、@code{/} の替わりに @code{_} を置換します。
@end deffn

@geindex b32encode() (base64 モジュール)
@anchor{library/base64 base64 b32encode}@anchor{3caf}
@deffn {の関数} base64.b32encode (s)

Base32 を使って @ref{193,,bytes-like object} の `s' をエンコードし、エンコードされた @ref{192,,bytes} を返します。
@end deffn

@geindex b32decode() (base64 モジュール)
@anchor{library/base64 base64 b32decode}@anchor{1226}
@deffn {の関数} base64.b32decode (s, casefold=False, map01=None)

Base32 エンコードされた  @ref{193,,bytes-like object} または ASCII 文字列 `s' をデコードし、デコードされた @ref{192,,bytes} を返します。

オプション引数 `casefold' は小文字のアルファベットを受けつけるかどうかを指定します。セキュリティ上の理由により、デフォルトではこれは @code{False} になっています。

@geindex RFC; RFC 4648
RFC 4648@footnote{https://datatracker.ietf.org/doc/html/rfc4648.html} は付加的なマッピングとして、数字の 0 (零) をアルファベットの O (オー) に、数字の 1 (壱) をアルファベットの I (アイ) または L (エル) に対応させることを許しています。オプション引数は `map01' は、 @code{None} でないときは、数字の 1 をどの文字に対応づけるかを指定します (`map01' が @code{None} でないとき、数字の 0 はつねにアルファベットの O (オー) に対応づけられます)。セキュリティ上の理由により、これはデフォルトでは @code{None} になっているため、 0 および 1 は入力として許可されていません。

`s' が正しくパディングされていない場合や、入力にアルファベットでない文字が含まれていた場合に、 @ref{1227,,binascii.Error} 例外を発生させます。
@end deffn

@geindex b32hexencode() (base64 モジュール)
@anchor{library/base64 base64 b32hexencode}@anchor{9e4}
@deffn {の関数} base64.b32hexencode (s)

:func:>>`<<b32encode`に似ていますが、:rfc:>>`<<4648`で定義されているようにExtended Hex Alphabetを使用します。


Added in version 3.10.

@end deffn

@geindex b32hexdecode() (base64 モジュール)
@anchor{library/base64 base64 b32hexdecode}@anchor{9e5}
@deffn {の関数} base64.b32hexdecode (s, casefold=False)

:func:>>`<<b32decode`に似ていますが、:rfc:>>`<<4648`で定義されているようにExtended Hex Alphabetを使用します。

This version does not allow the digit 0 (zero) to the letter O (oh) and digit
1 (one) to either the letter I (eye) or letter L (el) mappings, all these
characters are included in the Extended Hex Alphabet and are not
interchangeable.


Added in version 3.10.

@end deffn

@geindex b16encode() (base64 モジュール)
@anchor{library/base64 base64 b16encode}@anchor{3cb0}
@deffn {の関数} base64.b16encode (s)

Base16 を使って @ref{193,,bytes-like object} の `s' をエンコードし、エンコードされた @ref{192,,bytes} を返します。
@end deffn

@geindex b16decode() (base64 モジュール)
@anchor{library/base64 base64 b16decode}@anchor{2d3}
@deffn {の関数} base64.b16decode (s, casefold=False)

Base16 エンコードされた  @ref{193,,bytes-like object} または ASCII 文字列 `s' をデコードし、デコードされた @ref{192,,bytes} を返します。

オプション引数 `casefold' は小文字のアルファベットを受けつけるかどうかを指定します。セキュリティ上の理由により、デフォルトではこれは @code{False} になっています。

`s' が正しくパディングされていない場合や、入力にアルファベットでない文字が含まれていた場合に、 @ref{1227,,binascii.Error} 例外を発生させます。
@end deffn

@node Base85 エンコーディング,レガシーインターフェース,RFC 4648 エンコーディング,base64 --- Base16 Base32 Base64 Base85 データのエンコード
@anchor{library/base64 base64-base-85}@anchor{3ca7}@anchor{library/base64 base85-encodings}@anchor{3cb1}
@subsubsection Base85 エンコーディング


Base85 encoding is not formally specified but rather a de facto standard,
thus different systems perform the encoding differently.

The @ref{1121,,a85encode()} and @ref{1123,,b85encode()} functions in this module are two implementations of
the de facto standard. You should call the function with the Base85
implementation used by the software you intend to work with.

The two functions present in this module differ in how they handle the following:


@itemize *

@item 
Whether to include enclosing @code{<~} and @code{~>} markers

@item 
Whether to include newline characters

@item 
The set of ASCII characters used for encoding

@item 
Handling of null bytes
@end itemize

Refer to the documentation of the individual functions for more information.

@geindex a85encode() (base64 モジュール)
@anchor{library/base64 base64 a85encode}@anchor{1121}
@deffn {の関数} base64.a85encode (b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)

Ascii85 を使って @ref{193,,bytes-like object} の `b' をエンコードし、エンコードされた @ref{192,,bytes} を返します。

`foldspaces' を使うと、4 つの連続した空白文字(ASCII 0x20)を 'btoa' によってサポートされている短い特殊文字 'y' に置き換えます。この機能は "標準" Ascii85 ではサポートされていません。

`wrapcol' controls whether the output should have newline (@code{b'\n'})
characters added to it. If this is non-zero, each output line will be
at most this many characters long, excluding the trailing newline.

`pad' を指定すると、エンコード前に入力が 4 の倍数になるようにパディングされます。なお、 @code{btoa} の実装は常にパディングします。

`adobe' を指定すると、エンコードしたバイトシーケンスを @code{<~} と @code{~>} で囲みます。これは Adobe の実装で使われています。


Added in version 3.4.

@end deffn

@geindex a85decode() (base64 モジュール)
@anchor{library/base64 base64 a85decode}@anchor{1122}
@deffn {の関数} base64.a85decode (b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\x0b')

Ascii85 エンコードされた @ref{193,,bytes-like object} または ASCII 文字列 `b' をデコードし、デコードされた @ref{192,,bytes} を返します。

`foldspaces' は、短い特殊文字 'y' を受け取って 4 つの連続した空白文字(ASCII 0x20)と解釈するかどうかを制御します。この機能は "標準" Ascii85 ではサポートされていません。

`adobe' で、入力シーケンスが Adobe Ascii85 (つまり @code{<~} と @code{~>} で囲まれている)かどうかを伝えます。

`ignorechars' should be a byte string containing characters to ignore
from the input. This should only contain whitespace characters, and by
default contains all whitespace characters in ASCII.


Added in version 3.4.

@end deffn

@geindex b85encode() (base64 モジュール)
@anchor{library/base64 base64 b85encode}@anchor{1123}
@deffn {の関数} base64.b85encode (b, pad=False)

base85 (これは例えば git スタイルのバイナリ diff で用いられています) を使って @ref{193,,bytes-like object} の `b' をエンコードし、エンコードされた @ref{192,,bytes} を返します。

`pad' が真ならば、エンコードに先立って、バイト数が 4 の倍数となるように入力が @code{b'\0'} でパディングされます。


Added in version 3.4.

@end deffn

@geindex b85decode() (base64 モジュール)
@anchor{library/base64 base64 b85decode}@anchor{1124}
@deffn {の関数} base64.b85decode (b)

base85でエンコードされた @ref{193,,bytes-like object}  または ASCII 文字列の `b' をデコードし、デコードされた @ref{192,,bytes} を返します。パディングは、もしあれば、暗黙に削除されます。


Added in version 3.4.

@end deffn

@geindex z85encode() (base64 モジュール)
@anchor{library/base64 base64 z85encode}@anchor{47b}
@deffn {の関数} base64.z85encode (s)

Encode the @ref{193,,bytes-like object} `s' using Z85 (as used in ZeroMQ)
and return the encoded @ref{192,,bytes}.  See Z85 specification@footnote{https://rfc.zeromq.org/spec/32/} for more information.


Added in version 3.13.

@end deffn

@geindex z85decode() (base64 モジュール)
@anchor{library/base64 base64 z85decode}@anchor{47c}
@deffn {の関数} base64.z85decode (s)

Decode the Z85-encoded @ref{193,,bytes-like object} or ASCII string `s' and
return the decoded @ref{192,,bytes}.  See Z85 specification@footnote{https://rfc.zeromq.org/spec/32/} for more information.


Added in version 3.13.

@end deffn

@node レガシーインターフェース,セキュリティで考慮すべき点<4>,Base85 エンコーディング,base64 --- Base16 Base32 Base64 Base85 データのエンコード
@anchor{library/base64 base64-legacy}@anchor{3ca8}@anchor{library/base64 legacy-interface}@anchor{3cb2}
@subsubsection レガシーインターフェース


@geindex decode() (base64 モジュール)
@anchor{library/base64 base64 decode}@anchor{3cb3}
@deffn {の関数} base64.decode (input, output)

`input' ファイルの中身をデコードし、結果のバイナリデータを `output' ファイルに出力します。  `input' 、 `output' ともに @ref{13db,,file objects} でなければなりません。 `input' は @code{input.readline()} が空バイト列を返すまで読まれます。
@end deffn

@geindex decodebytes() (base64 モジュール)
@anchor{library/base64 base64 decodebytes}@anchor{b4d}
@deffn {の関数} base64.decodebytes (s)

@ref{193,,bytes-like object} `s' をデコードし、デコードされた @ref{192,,bytes} を返します。 `s' には一行以上の base64 形式でエンコードされたデータが含まれている必要があります。


Added in version 3.1.

@end deffn

@geindex encode() (base64 モジュール)
@anchor{library/base64 base64 encode}@anchor{3cb4}
@deffn {の関数} base64.encode (input, output)

バイナリの `input' ファイルの中身を base64 形式でエンコードした結果を `output' ファイルに出力します。 `input' 、 `output' ともに @ref{13db,,file objects} でなければなりません。 `input' は @code{input.read()} が空バイト列を返すまで読まれます。 @ref{3cb4,,encode()} は76バイトの出力ごとに改行文字(@code{b'\n'})を挿入し、
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} (MIME) の規定にあるように常に出力が新しい行で終わることを保証します。
@end deffn

@geindex encodebytes() (base64 モジュール)
@anchor{library/base64 base64 encodebytes}@anchor{b4c}
@deffn {の関数} base64.encodebytes (s)

@ref{193,,bytes-like object} `s' (任意のバイナリデータを含むことができます) を、
@geindex RFC; RFC 2045
RFC 2045@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html} (MIME) に規定されるように末尾に新しい行のある、76バイトの出力ごとに新しい行 (@code{b'\n'}) が挿入された、base64 形式でエンコードしたデータを含む @ref{192,,bytes} を返します。


Added in version 3.1.

@end deffn

モジュールの使用例:

@example
>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'
@end example

@node セキュリティで考慮すべき点<4>,,レガシーインターフェース,base64 --- Base16 Base32 Base64 Base85 データのエンコード
@anchor{library/base64 base64-security}@anchor{3cb5}@anchor{library/base64 security-considerations}@anchor{3cb6}
@subsubsection セキュリティで考慮すべき点


A new security considerations section was added to 
@geindex RFC; RFC 4648
RFC 4648@footnote{https://datatracker.ietf.org/doc/html/rfc4648.html} (section 12); it's
recommended to review the security section for any code deployed to production.


@subsubheading 参考



@table @asis

@item モジュール @ref{11,,binascii}

ASCII からバイナリへ、バイナリから ASCII への変換をサポートするモジュール。

@geindex RFC; RFC 1521

@item RFC 1521@footnote{https://datatracker.ietf.org/doc/html/rfc1521.html} - MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies

Section 5.2, "Base64 Content-Transfer-Encoding," provides the definition of the
base64 encoding.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node binascii --- バイナリ と ASCII 間の変換,quopri --- MIME quoted-printable データのエンコードとデコード,base64 --- Base16 Base32 Base64 Base85 データのエンコード,インターネット上のデータの操作
@anchor{library/binascii doc}@anchor{3cb7}@anchor{library/binascii binascii-convert-between-binary-and-ascii}@anchor{3cb8}@anchor{library/binascii module-binascii}@anchor{11}@anchor{library/binascii translation-repo}@anchor{3cb9}
@subsection @code{binascii} --- バイナリ と ASCII 間の変換


@geindex module; binascii

@geindex module;base64


__________________________________________________________________


The @code{binascii} module contains a number of methods to convert between
binary and various ASCII-encoded binary representations. Normally, you will not
use these functions directly but use wrapper modules like
@ref{f,,base64} instead. The @code{binascii} module contains
low-level functions written in C for greater speed that are used by the
higher-level modules.

@cartouche
@quotation 注釈 
@code{a2b_*} 関数は ASCII 文字だけを含むユニコード文字列を受け取ります。他の関数は (@ref{192,,bytes} や @ref{344,,bytearray} またはバッファープロトコルをサポートするその他のオブジェクトのような) @ref{193,,bytes-like オブジェクト} だけを受け取ります。


バージョン 3.3 で変更: @code{a2b_*} 関数は ASCII のみのユニコード文字列を受け取るようになりました。

@end quotation
@end cartouche

The @code{binascii} module defines the following functions:

@geindex a2b_uu() (binascii モジュール)
@anchor{library/binascii binascii a2b_uu}@anchor{3cba}
@deffn {の関数} binascii.a2b_uu (string)

uuencode された 1 行のデータをバイナリに変換し、変換後のバイナリデータを返します。最後の行を除いて、通常 1 行には (バイナリデータで) 45 バイトが含まれます。入力データの先頭には空白文字が連続していてもかまいません。
@end deffn

@geindex b2a_uu() (binascii モジュール)
@anchor{library/binascii binascii b2a_uu}@anchor{d16}
@deffn {の関数} binascii.b2a_uu (data, *, backtick=False)

Convert binary data to a line of ASCII characters, the return value is the
converted line, including a newline char. The length of `data' should be at most
45. If `backtick' is true, zeros are represented by @code{'`'} instead of spaces.


バージョン 3.7 で変更: `backtick' パラメータを追加しました.

@end deffn

@geindex a2b_base64() (binascii モジュール)
@anchor{library/binascii binascii a2b_base64}@anchor{19a4}
@deffn {の関数} binascii.a2b_base64 (string, /, *, strict_mode=False)

base64 でエンコードされたデータのブロックをバイナリに変換し、変換後のバイナリデータを返します。一度に 1 行以上のデータを与えてもかまいません。

If `strict_mode' is true, only valid base64 data will be converted. Invalid base64
data will raise @ref{1227,,binascii.Error}.

Valid base64:


@itemize *

@item 
Conforms to 
@geindex RFC; RFC 3548
RFC 3548@footnote{https://datatracker.ietf.org/doc/html/rfc3548.html}.

@item 
Contains only characters from the base64 alphabet.

@item 
Contains no excess data after padding (including excess padding, newlines, etc.).

@item 
Does not start with a padding.
@end itemize


バージョン 3.11 で変更: Added the `strict_mode' parameter.

@end deffn

@geindex b2a_base64() (binascii モジュール)
@anchor{library/binascii binascii b2a_base64}@anchor{e7b}
@deffn {の関数} binascii.b2a_base64 (data, *, newline=True)

バイナリデータを base64 でエンコードされた 1 行の ASCII 文字列に変換します。戻り値は変換後の 1 行の文字列で、`newline' が真の場合改行文字を含みます。この関数の出力は 
@geindex RFC; RFC 3548
RFC 3548@footnote{https://datatracker.ietf.org/doc/html/rfc3548.html} を遵守します。


バージョン 3.6 で変更: パラメータに `newline' を追加しました。

@end deffn

@geindex a2b_qp() (binascii モジュール)
@anchor{library/binascii binascii a2b_qp}@anchor{3cbb}
@deffn {の関数} binascii.a2b_qp (data, header=False)

quoted-printable 形式のデータをバイナリに変換し、バイナリデータを返します。一度に 1 行以上のデータを渡すことができます。オプション引数 `header' が与えられており、かつその値が真であれば、アンダースコアは空白文字にデコードされます。
@end deffn

@geindex b2a_qp() (binascii モジュール)
@anchor{library/binascii binascii b2a_qp}@anchor{3cbc}
@deffn {の関数} binascii.b2a_qp (data, quotetabs=False, istext=True, header=False)

バイナリデータを quoted-printable 形式でエンコードして 1 行から複数行の ASCII 文字列に変換します。変換後の文字列を返します。オプション引数 `quptetabs' が存在し、かつその値が真であれば、全てのタブおよび空白文字もエンコードされます。オプション引数 `istext' が存在し、かつその値が真であれば、改行はエンコードされませんが、行末の空白文字はエンコードされます。オプション引数 `header' が存在し、かつその値が真である場合、空白文字は 
@geindex RFC; RFC 1522
RFC 1522@footnote{https://datatracker.ietf.org/doc/html/rfc1522.html} にしたがってアンダースコアにエンコードされます。オプション引数 `header' が存在し、かつその値が偽である場合、改行文字も同様にエンコードされます。そうでない場合、復帰 (linefeed) 文字の変換によってバイナリデータストリームが破損してしまうかもしれません。
@end deffn

@geindex crc_hqx() (binascii モジュール)
@anchor{library/binascii binascii crc_hqx}@anchor{93d}
@deffn {の関数} binascii.crc_hqx (data, value)

`value' を CRC の初期値として `data' の 16 ビット CRC 値を計算し、その結果を返します。
この関数は、よく 0x1021 と表現される CRC-CCITT 多項式 `x'@w{^16} + `x'@w{^12} + `x'@w{^5} + 1 を使います。
この CRC は binhex4 形式で使われています。
@end deffn

@geindex crc32() (binascii モジュール)
@anchor{library/binascii binascii crc32}@anchor{1a11}
@deffn {の関数} binascii.crc32 (data[, value])

符号無し 32 ビットチェックサムである CRC-32 を `data' に対して計算します。 crc の初期値は `value' です。デフォルトの CRC の初期値はゼロです。このアルゴリズムは ZIP ファイルのチェックサムと同じです。このアルゴリズムはチェックサムアルゴリズムとして設計されたもので、一般的なハッシュアルゴリズムには向きません。以下のようにして使います:

@example
print(binascii.crc32(b"hello world"))
# Or, in two pieces:
crc = binascii.crc32(b"hello")
crc = binascii.crc32(b" world", crc)
print('crc32 = @{:#010x@}'.format(crc))
@end example


バージョン 3.0 で変更: The result is always unsigned.

@end deffn

@geindex b2a_hex() (binascii モジュール)
@geindex hexlify() (binascii モジュール)
@anchor{library/binascii binascii b2a_hex}@anchor{287e}
@deffn {の関数} binascii.b2a_hex (data[, sep[, bytes_per_sep=1]])
@anchor{library/binascii binascii hexlify}@anchor{3cbd}
@deffnx {の関数} binascii.hexlify (data[, sep[, bytes_per_sep=1]])

バイナリ `data' の16進表現を返します。`data' の各バイトは、対応する2桁の16進表現に変換されます。したがって、返されるバイトオブジェクトは `data' の2倍の長さになります。

Similar functionality (but returning a text string) is also conveniently
accessible using the @ref{f65,,bytes.hex()} method.

If `sep' is specified, it must be a single character str or bytes object.
It will be inserted in the output after every `bytes_per_sep' input bytes.
Separator placement is counted from the right end of the output by default,
if you wish to count from the left, supply a negative `bytes_per_sep' value.

@example
>>> import binascii
>>> binascii.b2a_hex(b'\xb9\x01\xef')
b'b901ef'
>>> binascii.hexlify(b'\xb9\x01\xef', '-')
b'b9-01-ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2)
b'b9_01ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2)
b'b901 ef'
@end example


バージョン 3.8 で変更: 引数 `sep' と `bytes_per_sep' が追加されました.

@end deffn

@geindex a2b_hex() (binascii モジュール)
@geindex unhexlify() (binascii モジュール)
@anchor{library/binascii binascii a2b_hex}@anchor{287f}
@deffn {の関数} binascii.a2b_hex (hexstr)
@anchor{library/binascii binascii unhexlify}@anchor{1e26}
@deffnx {の関数} binascii.unhexlify (hexstr)

16進数表記の文字列 `hexstr' の表すバイナリデータを返します。この関数は @ref{287e,,b2a_hex()} の逆です。 `hexstr' は 16進数字 (大文字でも小文字でも構いません) を偶数個含んでいなければなりません。そうでない場合、例外 @ref{1227,,Error} が送出されます。

Similar functionality (accepting only text string arguments, but more
liberal towards whitespace) is also accessible using the
@ref{190,,bytes.fromhex()} class method.
@end deffn

@geindex Error
@anchor{library/binascii binascii Error}@anchor{1227}
@deffn {例外} binascii.Error

エラーが発生した際に送出される例外です。通常はプログラムのエラーです。
@end deffn

@geindex Incomplete
@anchor{library/binascii binascii Incomplete}@anchor{3cbe}
@deffn {例外} binascii.Incomplete

変換するデータが不完全な場合に送出される例外です。通常はプログラムのエラーではなく、多少追加読み込みを行って再度変換を試みることで対処できます。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{f,,base64} モジュール

RFC 準拠の base64 形式の、底が 16、32、64、85 のエンコーディング。

@item @ref{bc,,quopri} モジュール

MIME 電子メールメッセージで使われる quoted-printable エンコードのサポート。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node quopri --- MIME quoted-printable データのエンコードとデコード,,binascii --- バイナリ と ASCII 間の変換,インターネット上のデータの操作
@anchor{library/quopri doc}@anchor{3cbf}@anchor{library/quopri module-quopri}@anchor{bc}@anchor{library/quopri quopri-encode-and-decode-mime-quoted-printable-data}@anchor{3cc0}@anchor{library/quopri translation-repo}@anchor{3cc1}
@subsection @code{quopri} --- MIME quoted-printable データのエンコードとデコード


@geindex module; quopri

`ソースコード:' Lib/quopri.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/quopri.py}

@geindex quoted-printable;encoding
@geindex MIME;quoted-printable encoding


__________________________________________________________________


このモジュールは 
@geindex RFC; RFC 1521
RFC 1521@footnote{https://datatracker.ietf.org/doc/html/rfc1521.html}: "MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies" で定義されている quoted-printable による伝送のエンコードおよびデコードを行います。 quoted-printable エンコーディングは比較的印字不可能な文字の少ないデータのために設計されています; 画像ファイルを送るときのように印字不可能な文字がたくさんある場合には、 @ref{f,,base64} モジュールで利用できる base64 エンコーディングのほうがよりコンパクトになります。

@geindex decode() (quopri モジュール)
@anchor{library/quopri quopri decode}@anchor{2881}
@deffn {の関数} quopri.decode (input, output, header=False)

ファイル `input' の内容をデコードして、デコードされたバイナリデータをファイル `output' に書き出します。 `input' および `output' は @ref{13db,,バイナリファイルオブジェクト} でなければなりません。オプション引数 `header' が存在し、かつその値が真である場合、アンダースコアは空白文字にデコードされます。これは 
@geindex RFC; RFC 1522
RFC 1522@footnote{https://datatracker.ietf.org/doc/html/rfc1522.html}: "MIME (Multipurpose Internet Mail Extensions) Part Two: Message Header Extensions for Non-ASCII Text" で記述されているところの "Q"-エンコードされたヘッダをデコードするのに使われます。
@end deffn

@geindex encode() (quopri モジュール)
@anchor{library/quopri quopri encode}@anchor{2880}
@deffn {の関数} quopri.encode (input, output, quotetabs, header=False)

ファイル `input' の内容をエンコードして、その結果の quoted-printable データをファイル `output' に書き出します。
`input' および `output' は @ref{13db,,バイナリファイルオブジェクト} でなければなりません。
`quotetabs' は、内容に含まれている空白とタブ文字をエンコードするかどうかを制御する必須のフラグで、真のときは空白文字をエンコードし、偽のときはエンコードしないままにしておきます。
@geindex RFC; RFC 1521
RFC 1521@footnote{https://datatracker.ietf.org/doc/html/rfc1521.html} に従って、行末にある空白とタブ文字は常にエンコードされることに注意してください。
`header' は、空白を 
@geindex RFC; RFC 1522
RFC 1522@footnote{https://datatracker.ietf.org/doc/html/rfc1522.html} に従ってアンダースコアにエンコードするかどうかを制御するフラグです。
@end deffn

@geindex decodestring() (quopri モジュール)
@anchor{library/quopri quopri decodestring}@anchor{3cc2}
@deffn {の関数} quopri.decodestring (s, header=False)

@ref{2881,,decode()} に似ていますが、ソース @ref{192,,bytes} を受け取り、対応するデコードされた @ref{192,,bytes} を返します。
@end deffn

@geindex encodestring() (quopri モジュール)
@anchor{library/quopri quopri encodestring}@anchor{3cc3}
@deffn {の関数} quopri.encodestring (s, quotetabs=False, header=False)

@ref{2880,,encode()} に似ていますが、ソース @ref{192,,bytes} を受け取り、対応するエンコードされた @ref{192,,bytes} を返します。
デフォルトでは、 @ref{2880,,encode()} 関数の `quotetabs' パラメータに @code{False} を渡します。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{f,,base64} モジュール

MIME base64 形式データのエンコードおよびデコード
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 構造化マークアップツール,インターネットプロトコルとサポート,インターネット上のデータの操作,Python 標準ライブラリ
@anchor{library/markup doc}@anchor{3cc4}@anchor{library/markup markup}@anchor{3cc5}@anchor{library/markup structured-markup-processing-tools}@anchor{3cc6}@anchor{library/markup translation-repo}@anchor{3cc7}
@section 構造化マークアップツール


Python は様々な構造化データマークアップ形式を扱うための、様々なモジュールをサポートしています。これらは標準化一般マークアップ言語 (SGML) およびハイパーテキストマークアップ言語 (HTML)、そして可拡張性マークアップ言語 (XML) を扱うためのいくつかのインターフェースからなります。

@menu
* html: html --- HyperText Markup Language のサポート. HyperText Markup Language のサポート
* html.parser: html parser --- HTML と XHTML のシンプルなパーサー. HTML と XHTML のシンプルなパーサー
* html.entities: html entities --- HTML 一般実体の定義. HTML 一般実体の定義
* XMLを扱うモジュール群:: 
* xml.etree.ElementTree: xml etree ElementTree --- ElementTree XML API. ElementTree XML API
* xml.dom: xml dom --- ドキュメントオブジェクトモデル API. ドキュメントオブジェクトモデル API
* xml.dom.minidom: xml dom minidom --- 最小限の DOM の実装. 最小限の DOM の実装
* xml.dom.pulldom: xml dom pulldom --- 部分的な DOM ツリー構築のサポート. 部分的な DOM ツリー構築のサポート
* xml.sax: xml sax --- SAX2 バーサーのサポート. SAX2 バーサーのサポート
* xml.sax.handler: xml sax handler --- SAX ハンドラーの基底クラス. SAX ハンドラーの基底クラス
* xml.sax.saxutils: xml sax saxutils --- SAX ユーティリティー. SAX ユーティリティー
* xml.sax.xmlreader: xml sax xmlreader --- XML パーサーのインターフェース. XML パーサーのインターフェース
* xml.parsers.expat: xml parsers expat --- Expat を使用した高速な XML 解析. Expat を使用した高速な XML 解析

@end menu

@node html --- HyperText Markup Language のサポート,html parser --- HTML と XHTML のシンプルなパーサー,,構造化マークアップツール
@anchor{library/html doc}@anchor{3cc8}@anchor{library/html html-hypertext-markup-language-support}@anchor{3cc9}@anchor{library/html module-html}@anchor{6f}
@subsection @code{html} --- HyperText Markup Language のサポート


@geindex module; html

`ソースコード:' Lib/html/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/html/__init__.py}


__________________________________________________________________


このモジュールは HTML を操作するユーティリティを定義しています。

@geindex escape() (html モジュール)
@anchor{library/html html escape}@anchor{1210}
@deffn {の関数} html.escape (s, quote=True)

Convert the characters @code{&}, @code{<} and @code{>} in string `s' to HTML-safe
sequences.  Use this if you need to display text that might contain such
characters in HTML.  If the optional flag `quote' is true (the default), the
characters (@code{"}) and (@code{'}) are also translated; this helps for inclusion
in an HTML attribute value delimited by quotes, as in @code{<a href="...">}.
If `quote' is set to false, the characters (@code{"}) and (@code{'}) are not
translated.


Added in version 3.2.

@end deffn

@geindex unescape() (html モジュール)
@anchor{library/html html unescape}@anchor{b50}
@deffn {の関数} html.unescape (s)

文字列 `s' 中の名前や数字による参照 (例えば @code{&gt;}, @code{&#62;}, @code{&#x3e;}) を全て対応するユニコード文字に変換します。
この関数は、 HTML 5 標準規格で定められた有効な文字参照および無効な文字参照、 @ref{12e9,,list of HTML 5 named character references} を対象とします。


Added in version 3.4.

@end deffn


__________________________________________________________________


@code{html} パッケージのサブモジュールは以下のとおりです:


@itemize *

@item 
@ref{71,,html.parser} -- 許容性のあるモードを持つ HTML/XHTML パーサー

@item 
@ref{70,,html.entities} -- HTML 実体の定義
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node html parser --- HTML と XHTML のシンプルなパーサー,html entities --- HTML 一般実体の定義,html --- HyperText Markup Language のサポート,構造化マークアップツール
@anchor{library/html parser doc}@anchor{3cca}@anchor{library/html parser html-parser-simple-html-and-xhtml-parser}@anchor{3ccb}@anchor{library/html parser module-html parser}@anchor{71}@anchor{library/html parser translation-repo}@anchor{3ccc}
@subsection @code{html.parser} --- HTML と XHTML のシンプルなパーサー


@geindex module; html.parser

`ソースコード:' Lib/html/parser.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/html/parser.py}

@geindex HTML
@geindex XHTML


__________________________________________________________________


このモジュールでは @ref{a77,,HTMLParser} クラスを定義します。このクラスは HTML (ハイパーテキスト記述言語、HyperText Mark-up Language) および XHTML で書式化されているテキストファイルを解釈するための基礎となります。

@geindex HTMLParser (html.parser のクラス)
@anchor{library/html parser html parser HTMLParser}@anchor{a77}
@deffn {クラス} html.parser.HTMLParser (*, convert_charrefs=True, scripting=False)

不正なマークアップをパースできるパーサーインスタンスを作成します。

If `convert_charrefs' is true (the default), all character
references (except the ones in elements like @code{script} and @code{style}) are
automatically converted to the corresponding Unicode characters.

If `scripting' is false (the default), the content of the @code{noscript}
element is parsed normally; if it's true, it's returned as is without
being parsed.

@ref{a77,,HTMLParser} インスタンスは、HTML データが入力されると、開始タグ、終了タグ、およびその他の要素が見つかる度にハンドラーメソッドを呼び出します。各メソッドの挙動を実装するには @ref{a77,,HTMLParser} サブクラスを使ってそれぞれを上書きして行います。

このパーサーは終了タグが開始タグと一致しているか調べたり、外側のタグ要素が閉じるときに内側で明示的に閉じられていないタグ要素のタグ終了ハンドラーを呼び出したりはしません。


バージョン 3.4 で変更: キーワード引数 `convert_charrefs' を追加。



バージョン 3.5 で変更: `convert_charrefs' のデフォルト値は @code{True} になりました。



バージョン 3.14.1 で変更: Added the `scripting' parameter.

@end deffn

@menu
* HTML パーサーアプリケーションの例:: 
* HTMLParser メソッド:: 
* 使用例: 使用例<32>. 

@end menu

@node HTML パーサーアプリケーションの例,HTMLParser メソッド,,html parser --- HTML と XHTML のシンプルなパーサー
@anchor{library/html parser example-html-parser-application}@anchor{3ccd}
@subsubsection HTML パーサーアプリケーションの例


As a basic example, below is a simple HTML parser that uses the
@ref{a77,,HTMLParser} class to print out start tags, end tags, and data
as they are encountered:

@example
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)

    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')
@end example

出力は以下のようになります:

@example
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data  : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
@end example

@node HTMLParser メソッド,使用例<32>,HTML パーサーアプリケーションの例,html parser --- HTML と XHTML のシンプルなパーサー
@anchor{library/html parser htmlparser-methods}@anchor{3cce}
@subsubsection @code{HTMLParser} メソッド


@ref{a77,,HTMLParser} インスタンスは以下のメソッドを提供します:

@geindex feed() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser feed}@anchor{3ccf}
@deffn {メソッド} HTMLParser.feed (data)

パーサーにテキストを入力します。入力が完全なタグ要素で構成されている場合に限り処理が行われます; 不完全なデータであった場合、新たにデータが入力されるか、@ref{1841,,close()} が呼び出されるまでバッファーされます。 `data' は @ref{169,,str} でなければなりません。
@end deffn

@geindex close() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser close}@anchor{1841}
@deffn {メソッド} HTMLParser.close ()

全てのバッファーされているデータについて、その後にファイル終端マークが続いているとみなして強制的に処理を行います。このメソッドは入力データの終端で行う追加処理を定義するために、派生クラスで再定義することができます。しかし、再定義されたバージョンでは、常に @ref{a77,,HTMLParser} 基底クラスのメソッド @ref{1841,,close()} を呼び出さなくてはなりません。
@end deffn

@geindex reset() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser reset}@anchor{3cd0}
@deffn {メソッド} HTMLParser.reset ()

インスタンスをリセットします。未処理のデータはすべて失われます。インスタンス化の際に暗黙的に呼び出されます。
@end deffn

@geindex getpos() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser getpos}@anchor{3cd1}
@deffn {メソッド} HTMLParser.getpos ()

現在の行番号およびオフセット値を返します。
@end deffn

@geindex get_starttag_text() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser get_starttag_text}@anchor{3cd2}
@deffn {メソッド} HTMLParser.get_starttag_text ()

最も最近開かれた開始タグのテキスト部分を返します。このテキストは必ずしも元データを構造化する上で必須ではありませんが、 "広く知られている (as deployed)" HTML を扱ったり、入力を最小限の変更で再生成 (属性間の空白をそのままにする、など) したりする場合に便利なことがあります。
@end deffn

以下のメソッドはデータまたはマークアップ要素が見つかる度に呼び出されます。これらはサブクラスで上書きされることを想定されています。基底クラスの実装は (@ref{3cd3,,handle_startendtag()} を除き) 何もしません:

@geindex handle_starttag() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_starttag}@anchor{3cd4}
@deffn {メソッド} HTMLParser.handle_starttag (tag, attrs)

このメソッドは要素の開始タグを扱うために呼び出されます (例: @code{<div id="main">})。

引数 `tag' はタグの名前で、小文字に変換されます。引数 `attrs' は @code{(name, value)} のペアからなるリストで、タグの @code{<>} 括弧内にある属性が収められています。`name' は小文字に変換され、`value' 内の引用符は取り除かれ、文字参照と実態参照は置き換えられます。

例えば、タグ @code{<A HREF="https://www.cwi.nl/">} を処理する場合、このメソッドは @code{handle_starttag('a', [('href', 'https://www.cwi.nl/')])} として呼び出されます。

@ref{70,,html.entities} からのすべての実態参照は、属性値に置き換えられます。
@end deffn

@geindex handle_endtag() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_endtag}@anchor{3cd5}
@deffn {メソッド} HTMLParser.handle_endtag (tag)

このメソッドは要素の終了タグを扱うために呼び出されます (例: @code{</div>})。

引数 `tag' はタグの名前で、小文字に変換されます。
@end deffn

@geindex handle_startendtag() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_startendtag}@anchor{3cd3}
@deffn {メソッド} HTMLParser.handle_startendtag (tag, attrs)

@ref{3cd4,,handle_starttag()} と似ていますが、パーサーが XHTML 形式の空タグ (@code{<img ... />}) を見つける度に呼び出されます。この特定の字句情報が必要な場合にこのメソッドをサブクラスで上書きすることができます; 既定の実装では、単に @ref{3cd4,,handle_starttag()} および @ref{3cd5,,handle_endtag()} を呼び出します。
@end deffn

@geindex handle_data() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_data}@anchor{3cd6}
@deffn {メソッド} HTMLParser.handle_data (data)

This method is called to process arbitrary data (e.g. text nodes and the
content of elements like @code{script} and @code{style}).
@end deffn

@geindex handle_entityref() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_entityref}@anchor{3cd7}
@deffn {メソッド} HTMLParser.handle_entityref (name)

This method is called to process a named character reference of the form
@code{&name;} (e.g. @code{&gt;}), where `name' is a general entity reference
(e.g. @code{'gt'}).
This method is only called if `convert_charrefs' is false.
@end deffn

@geindex handle_charref() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_charref}@anchor{3cd8}
@deffn {メソッド} HTMLParser.handle_charref (name)

This method is called to process decimal and hexadecimal numeric character
references of the form @code{&#@var{NNN};} and @code{&#x@var{NNN};}.  For example, the decimal
equivalent for @code{&gt;} is @code{&#62;}, whereas the hexadecimal is @code{&#x3E;};
in this case the method will receive @code{'62'} or @code{'x3E'}.
This method is only called if `convert_charrefs' is false.
@end deffn

@geindex handle_comment() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_comment}@anchor{3cd9}
@deffn {メソッド} HTMLParser.handle_comment (data)

このメソッドはコメントが見つかった場合に呼び出されます (例: @code{<!--comment-->})。

例えば、コメント @code{<!-- comment -->} があると。このメソッドを引数 @code{' comment '} で呼び出されます。

Internet Explorer 独自拡張の条件付きコメント (condcoms) はこのメソッドに送ることができます。@code{<!--[if IE 9]>IE9-specific content<![endif]-->} の場合、このメソッドは @code{'[if IE 9]>IE9-specific content<![endif]'} を受け取ります。
@end deffn

@geindex handle_decl() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_decl}@anchor{3cda}
@deffn {メソッド} HTMLParser.handle_decl (decl)

このメソッドは HTML doctype 宣言を扱うために呼び出されます (例: @code{<!DOCTYPE html>})。

引数 `decl' は @code{<!...>} マークアップ内の宣言の内容全体になります (例: @code{'DOCTYPE html'})。
@end deffn

@geindex handle_pi() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser handle_pi}@anchor{3cdb}
@deffn {メソッド} HTMLParser.handle_pi (data)

処理指令が見つかった場合に呼び出されます。`data' には、処理指令全体が含まれ、例えば @code{<?proc color='red'>} という処理指令の場合、@code{handle_pi("proc color='red'")} のように呼び出されます。このメソッドは派生クラスで上書きするためのメソッドです; 基底クラスの実装では何も行いません。

@cartouche
@quotation 注釈 
@ref{a77,,HTMLParser} クラスでは、処理指令に SGML の構文を使用します。末尾に @code{'?'} がある XHTML の処理指令では、 @code{'?'} が `data' に含まれることになります。
@end quotation
@end cartouche
@end deffn

@geindex unknown_decl() (html.parser.HTMLParser のメソッド)
@anchor{library/html parser html parser HTMLParser unknown_decl}@anchor{3cdc}
@deffn {メソッド} HTMLParser.unknown_decl (data)

このメソッドはパーサーが未知の宣言を読み込んだ時に呼び出されます。

パラメータ `data' は @code{<![...]>} マークアップ内の宣言の内容全体になります。
これは派生クラスで上書きする時に役立つことがあります。
基底クラスの実装では何もしません。
@end deffn

@node 使用例<32>,,HTMLParser メソッド,html parser --- HTML と XHTML のシンプルなパーサー
@anchor{library/html parser examples}@anchor{3cdd}@anchor{library/html parser htmlparser-examples}@anchor{3cde}
@subsubsection 使用例


The following class implements a parser that will be used to illustrate more
examples:

@example
from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
@end example

Parsing a doctype:

@example
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
@end example

Parsing an element with a few attributes and a title:

@example
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h1>Python</h1>')
Start tag: h1
Data     : Python
End tag  : h1
@end example

The content of elements like @code{script} and @code{style} is returned as is,
without further parsing:

@example
>>> parser.feed('<style type="text/css">#python @{ color: green @}</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python @{ color: green @}
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello! &#9786;</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello! &#9786;</strong>");
End tag  : script
@end example

Parsing comments:

@example
>>> parser.feed('<!--a comment-->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  : a comment
Comment  : [if IE 9]>IE-specific content<![endif]
@end example

Parsing named and numeric character references and converting them to the
correct char (note: these 3 references are all equivalent to @code{'>'}):

@example
>>> parser = MyHTMLParser()
>>> parser.feed('&gt;&#62;&#x3E;')
Data     : >>>

>>> parser = MyHTMLParser(convert_charrefs=False)
>>> parser.feed('&gt;&#62;&#x3E;')
Named ent: >
Num ent  : >
Num ent  : >
@end example

Feeding incomplete chunks to @ref{3ccf,,feed()} works, but
@ref{3cd6,,handle_data()} might be called more than once
if `convert_charrefs' is false:

@example
>>> for chunk in ['<sp', 'an>buff', 'ered', ' text</s', 'pan>']:
...     parser.feed(chunk)
...
Start tag: span
Data     : buff
Data     : ered
Data     :  text
End tag  : span
@end example

Parsing invalid HTML (e.g. unquoted attributes) also works:

@example
>>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
Start tag: p
Start tag: a
     attr: ('class', 'link')
     attr: ('href', '#main')
Data     : tag soup
End tag  : p
End tag  : a
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node html entities --- HTML 一般実体の定義,XMLを扱うモジュール群,html parser --- HTML と XHTML のシンプルなパーサー,構造化マークアップツール
@anchor{library/html entities doc}@anchor{3cdf}@anchor{library/html entities html-entities-definitions-of-html-general-entities}@anchor{3ce0}@anchor{library/html entities module-html entities}@anchor{70}@anchor{library/html entities translation-repo}@anchor{3ce1}
@subsection @code{html.entities} --- HTML 一般実体の定義


@geindex module; html.entities

`ソースコード:' Lib/html/entities.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/html/entities.py}


__________________________________________________________________


このモジュールは 4 つの辞書、@ref{12e9,,html5}、@ref{3ce2,,name2codepoint}、@ref{3ce3,,codepoint2name}、および @ref{3ce4,,entitydefs} を定義しています。

@geindex html5 (html.entities モジュール)
@anchor{library/html entities html entities html5}@anchor{12e9}
@deffn {データ} html.entities.html5

HTML5 名前付き文字参照 @footnote{
@indicateurl{https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references} を参照
} と Unicode 文字とを対応付ける辞書です (例: @code{html5['gt;'] == '>'})。末尾のセミコロンは名前に含まれますが (例: @code{'gt;'})、一部の名前はセミコロンなしでも標準で受け付けます。この場合、@code{';'} ありの名前と @code{';'} なしの名前が両方存在します。 @ref{b50,,html.unescape()} も参照してください。


Added in version 3.3.

@end deffn

@geindex entitydefs (html.entities モジュール)
@anchor{library/html entities html entities entitydefs}@anchor{3ce4}
@deffn {データ} html.entities.entitydefs

各 XHTML 1.0 実体定義と ISO Latin-1 における置換テキストとを対応付ける辞書です。
@end deffn

@geindex name2codepoint (html.entities モジュール)
@anchor{library/html entities html entities name2codepoint}@anchor{3ce2}
@deffn {データ} html.entities.name2codepoint

HTML4 実体名と Unicode コードポイントとを対応付ける辞書です。
@end deffn

@geindex codepoint2name (html.entities モジュール)
@anchor{library/html entities html entities codepoint2name}@anchor{3ce3}
@deffn {データ} html.entities.codepoint2name

Unicode コードポイントと HTML4 実体名とを対応付ける辞書です。
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node XMLを扱うモジュール群,xml etree ElementTree --- ElementTree XML API,html entities --- HTML 一般実体の定義,構造化マークアップツール
@anchor{library/xml doc}@anchor{3ce5}@anchor{library/xml module-xml}@anchor{126}@anchor{library/xml translation-repo}@anchor{3ce6}@anchor{library/xml xml}@anchor{3ce7}@anchor{library/xml xml-processing-modules}@anchor{3ce8}
@subsection XMLを扱うモジュール群


@geindex module; xml

`ソースコード:' Lib/xml/@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/}


__________________________________________________________________


PythonのXMLを扱うインターフェースは @code{xml} パッケージにまとめられています。

@cartouche
@quotation 注釈 
If you need to parse untrusted or unauthenticated data, see
@ref{3ce9,,XML security}.
@end quotation
@end cartouche

It is important to note that modules in the @code{xml} package require that
there be at least one SAX-compliant XML parser available. The Expat parser is
included with Python, so the @ref{12c,,xml.parsers.expat} module will always be
available.

@ref{127,,xml.dom} および @ref{12f,,xml.sax} パッケージのドキュメントは Python による DOM および SAX インターフェースへのバインディングに関する定義です。

XML に関連するサブモジュール:


@itemize *

@item 
@ref{12b,,xml.etree.ElementTree}: ElementTree API、シンプルで軽量な XML プロセッサ
@end itemize



@itemize *

@item 
@ref{127,,xml.dom}: DOM API の定義

@item 
@ref{128,,xml.dom.minidom}: 最小限の DOM の実装

@item 
@ref{129,,xml.dom.pulldom}: 部分的な DOM ツリー構築のサポート
@end itemize



@itemize *

@item 
@ref{12f,,xml.sax}: SAX2 基底クラスと便利関数群

@item 
@ref{12c,,xml.parsers.expat}: Expat parser バインディング
@end itemize
@anchor{library/xml xml-security}@anchor{3ce9}
@menu
* XML security:: 

@end menu

@node XML security,,,XMLを扱うモジュール群
@anchor{library/xml id1}@anchor{3cea}@anchor{library/xml xml-vulnerabilities}@anchor{3ceb}
@subsubsection XML security


An attacker can abuse XML features to carry out denial of service attacks,
access local files, generate network connections to other machines, or
circumvent firewalls when attacker-controlled XML is being parsed,
in Python or elsewhere.

The built-in XML parsers of Python rely on the library libexpat@footnote{https://github.com/libexpat/libexpat}, commonly
called Expat, for parsing XML.

By default, Expat itself does not access local files or create network
connections.

Expat versions lower than 2.7.2 may be vulnerable to the "billion laughs",
"quadratic blowup" and "large tokens" vulnerabilities, or to disproportional
use of dynamic memory.
Python bundles a copy of Expat, and whether Python uses the bundled or a
system-wide Expat, depends on how the Python interpreter
@ref{1b2d,,has been configured} in your environment.
Python may be vulnerable if it uses such older versions of Expat.
Check @code{pyexpat.EXPAT_VERSION}.

@ref{133,,xmlrpc} is `vulnerable' to the "decompression bomb" attack.


@table @asis

@item billion laughs / exponential entity expansion

Billion Laughs@footnote{https://en.wikipedia.org/wiki/Billion_laughs} 攻撃 -- または指数関数的エンティティ展開 (exponential entity expansion) -- は複数階層の入れ子になったエンティティを使用します。
各エンティティは別のエンティティを複数回参照し、最終的なエンティティの定義は短い文字列です。
指数関数的に展開されることで数 GB のテキストができ、多くのメモリと CPU 時間を消費します。

@item quadratic blowup entity expansion

二次爆発攻撃 (quadratic blowup attack) はエンティティ展開を悪用する点で Billion Laughs@footnote{https://en.wikipedia.org/wiki/Billion_laughs} 攻撃に似ています。
入れ子になったエンティティの代わりに、この攻撃は数千字の大きなエンティティを何度も繰り返します。
この攻撃は指数関数的なものほど効率的ではありませんが、パーザの深い入れ子になったエンティティを禁止する対抗手段をすり抜けます。

@item decompression bomb

解凍爆弾 (あるいは ZIP 爆弾@footnote{https://ja.wikipedia.org/wiki/%E9%AB%98%E5%9C%A7%E7%B8%AE%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E7%88%86%E5%BC%BE}) は、gzip 圧縮 HTTP ストリームや LZMA 圧縮ファイルなどの圧縮された XML ストリームをパースできる全ての XML ライブラリに対し行われます。
攻撃者は送信データ量を1/3以下に減らすことができます。

@item large tokens

Expat needs to re-parse unfinished tokens; without the protection
introduced in Expat 2.6.0, this can lead to quadratic runtime that can
be used to cause denial of service in the application parsing XML.
The issue is known as 
@geindex Common Vulnerabilities and Exposures; CVE 2023-52425
CVE 2023-52425@footnote{https://www.cve.org/CVERecord?id=CVE-2023-52425}.
@end table

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml etree ElementTree --- ElementTree XML API,xml dom --- ドキュメントオブジェクトモデル API,XMLを扱うモジュール群,構造化マークアップツール
@anchor{library/xml etree elementtree doc}@anchor{3cec}@anchor{library/xml etree elementtree module-xml etree ElementTree}@anchor{12b}@anchor{library/xml etree elementtree translation-repo}@anchor{3ced}@anchor{library/xml etree elementtree xml-etree-elementtree-the-elementtree-xml-api}@anchor{3cee}
@subsection @code{xml.etree.ElementTree} --- ElementTree XML API


@geindex module; xml.etree.ElementTree

`Source code:' Lib/xml/etree/ElementTree.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/etree/ElementTree.py}


__________________________________________________________________


The @code{xml.etree.ElementTree} module implements a simple and efficient API
for parsing and creating XML data.


バージョン 3.3 で変更: このモジュールは利用出来る場合は常に高速な実装を使用します。



バージョン 3.3 で非推奨: The @code{xml.etree.cElementTree} モジュールは非推奨です。


@cartouche
@quotation 注釈 
If you need to parse untrusted or unauthenticated data, see
@ref{3ce9,,XML security}.
@end quotation
@end cartouche

@menu
* チュートリアル: チュートリアル<3>. 
* XPath サポート:: 
* リファレンス: リファレンス<5>. 
* XInclude サポート:: 
* リファレンス: リファレンス<6>. 

@end menu

@node チュートリアル<3>,XPath サポート,,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree tutorial}@anchor{3cef}
@subsubsection チュートリアル


This is a short tutorial for using @code{xml.etree.ElementTree} (@code{ET} in
short).  The goal is to demonstrate some of the building blocks and basic
concepts of the module.

@menu
* XML 木構造と要素:: 
* XML の解析:: 
* 非ブロックパースのためのプル API:: 
* 関心ある要素の検索:: 
* XML ファイルの編集:: 
* XML 文書の構築:: 
* 名前空間のある XML の解析:: 

@end menu

@node XML 木構造と要素,XML の解析,,チュートリアル<3>
@anchor{library/xml etree elementtree xml-tree-and-elements}@anchor{3cf0}
@subsubsection XML 木構造と要素


XML は本質的に階層データ形式で、木構造で表すのが最も自然な方法です。@code{ET} はこの目的のために 2 つのクラス - XML 文書全体を木で表す @ref{b47,,ElementTree} および木構造内の単一ノードを表す @ref{363,,Element} - を持っています。文書全体とのやりとり (ファイルの読み書き) は通常 @ref{b47,,ElementTree} レベルで行います。単一 XML 要素およびその子要素とのやりとりは @ref{363,,Element} レベルで行います。

@node XML の解析,非ブロックパースのためのプル API,XML 木構造と要素,チュートリアル<3>
@anchor{library/xml etree elementtree elementtree-parsing-xml}@anchor{3cf1}@anchor{library/xml etree elementtree parsing-xml}@anchor{3cf2}
@subsubsection XML の解析


We'll be using the fictive @code{country_data.xml} XML document as the sample data for this section:

@example
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
@end example

ファイルを読み込むことでこのデータをインポートすることが出来ます:

@example
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
@end example

文字列から直接インポートすることも出来ます:

@example
root = ET.fromstring(country_data_as_string)
@end example

@ref{3cf3,,fromstring()} は XML を文字列から @ref{363,,Element} に直接パースします。@ref{363,,Element} はパースされた木のルート要素です。他のパース関数は @ref{b47,,ElementTree} を作成するかもしれません。ドキュメントをきちんと確認してください。

@ref{363,,Element} として、@code{root} はタグと属性の辞書を持ちます:

@example
>>> root.tag
'data'
>>> root.attrib
@{@}
@end example

さらにイテレート可能な子ノードも持ちます:

@example
>>> for child in root:
...     print(child.tag, child.attrib)
...
country @{'name': 'Liechtenstein'@}
country @{'name': 'Singapore'@}
country @{'name': 'Panama'@}
@end example

子ノードは入れ子になっており、インデックスで子ノードを指定してアクセスできます:

@example
>>> root[0][1].text
'2008'
@end example

@cartouche
@quotation 注釈 
XML 入力の全ての要素が、パース後の木に要素として含まれる訳ではありません。現在、このモジュールは入力中のいかなる XML コメント、処理命令、ドキュメントタイプ宣言も読み飛ばします。しかし、XML テキストからのパースではなく、このモジュールの API を使用して構築された木には、コメントや処理命令を含むことができ、それらは XML 出力の生成時に含まれます。ドキュメントタイプ宣言は、 @ref{c49,,XMLParser} コンストラクタにカスタムの @ref{c4a,,TreeBuilder} インスタンスを渡すことで、アクセスすることができます。
@end quotation
@end cartouche

@node 非ブロックパースのためのプル API,関心ある要素の検索,XML の解析,チュートリアル<3>
@anchor{library/xml etree elementtree elementtree-pull-parsing}@anchor{11f6}@anchor{library/xml etree elementtree pull-api-for-non-blocking-parsing}@anchor{3cf4}
@subsubsection 非ブロックパースのためのプル API


このモジュールが提供するパース関数のほとんどは、結果を返す前に、ドキュメント全体を読む必要があります。 @ref{c49,,XMLParser} を使用して、インクリメンタルにデータを渡すことは可能ではありますが、それはコールバック対象のメソッドを呼ぶプッシュ API であり、多くの場合、低水準すぎて不便です。ユーザーが望むのは、完全に出来上がった @ref{363,,Element} オブジェクトを便利に使いながら、操作をブロックすることなく XML のパースをインクリメンタルに行えることです。

これを行うための最も強力なツールは、 @ref{11f5,,XMLPullParser} です。XML データを取得するためにブロックするような読み込みは必要なく、 @ref{3cf5,,XMLPullParser.feed()} を呼び出して、インクリメンタルにデータを読みます。パースされた XML 要素を取得するには、@ref{3cf6,,XMLPullParser.read_events()} を呼び出します。以下に、例を示します。

@example
>>> parser = ET.XMLPullParser(['start', 'end'])
>>> parser.feed('<mytag>sometext')
>>> list(parser.read_events())
[('start', <Element 'mytag' at 0x7fa66db2be58>)]
>>> parser.feed(' more text</mytag>')
>>> for event, elem in parser.read_events():
...     print(event)
...     print(elem.tag, 'text=', elem.text)
...
end
mytag text= sometext more text
@end example

これの分かりやすい用途は、XML データをソケットから受信したり、ストレージデバイスからインクリメンタルに読み出したりするような、非ブロック式に動作するアプリケーションです。このような場合、ブロッキング読み出しは使用できません。

@ref{11f5,,XMLPullParser} は柔軟性が非常に高いため、単純に使用したいユーザーにとっては不便かもしれません。アプリケーションにおいて、XML データの読み取り時にブロックすることに支障がないが、インクリメンタルにパースする能力が欲しい場合、@ref{57a,,iterparse()} を参照してください。大きな XML ドキュメントを読んでいて、全てメモリ上にあるという状態にしたくない場合に有用です。

Where `immediate' feedback through events is wanted, calling method
@ref{577,,XMLPullParser.flush()} can help reduce delay;
please make sure to study the related security notes.

@node 関心ある要素の検索,XML ファイルの編集,非ブロックパースのためのプル API,チュートリアル<3>
@anchor{library/xml etree elementtree finding-interesting-elements}@anchor{3cf7}
@subsubsection 関心ある要素の検索


@ref{363,,Element} は、例えば、@ref{1566,,Element.iter()} などの、配下 (その子ノードや孫ノードなど) の部分木全体を再帰的にイテレートするいくつかの役立つメソッドを持っています:

@example
>>> for neighbor in root.iter('neighbor'):
...     print(neighbor.attrib)
...
@{'name': 'Austria', 'direction': 'E'@}
@{'name': 'Switzerland', 'direction': 'W'@}
@{'name': 'Malaysia', 'direction': 'N'@}
@{'name': 'Costa Rica', 'direction': 'W'@}
@{'name': 'Colombia', 'direction': 'E'@}
@end example

@ref{187c,,Element.findall()} はタグで現在の要素の直接の子要素のみ検索します。 @ref{187a,,Element.find()} は特定のタグで `最初の' 子要素を検索し、 @ref{3cf8,,Element.text} は要素のテキストコンテンツにアクセスします。 @ref{3cf9,,Element.get()} は要素の属性にアクセスします:

@example
>>> for country in root.findall('country'):
...     rank = country.find('rank').text
...     name = country.get('name')
...     print(name, rank)
...
Liechtenstein 1
Singapore 4
Panama 68
@end example

@ref{da6,,XPath} を使用すると、より洗練された方法で、検索したい要素を指定することができます。

@node XML ファイルの編集,XML 文書の構築,関心ある要素の検索,チュートリアル<3>
@anchor{library/xml etree elementtree modifying-an-xml-file}@anchor{3cfa}
@subsubsection XML ファイルの編集


@ref{b47,,ElementTree} は XML 文書を構築してファイルに出力する簡単な方法を提供しています。@ref{c8c,,ElementTree.write()} メソッドはこの目的に適います。

@ref{363,,Element} オブジェクトを作成すると、そのフィールドの直接変更 (@ref{3cf8,,Element.text} など) や、属性の追加および変更 (@ref{3cfb,,Element.set()} メソッド)、あるいは新しい子ノードの追加 (例えば @ref{3cfc,,Element.append()} など) によってそれを操作できます。

例えば各 country の rank に 1 を足して、rank 要素に @code{updated} 属性を追加したい場合:

@example
>>> for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')
...
>>> tree.write('output.xml')
@end example

XML はこのようになります:

@example
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
@end example

@ref{1876,,Element.remove()} を使って要素を削除することが出来ます。例えば rank が 50 より大きい全ての country を削除したい場合:

@example
>>> for country in root.findall('country'):
...     # using root.findall() to avoid removal during traversal
...     rank = int(country.find('rank').text)
...     if rank > 50:
...         root.remove(country)
...
>>> tree.write('output.xml')
@end example

Note that concurrent modification while iterating can lead to problems,
just like when iterating and modifying Python lists or dicts.
Therefore, the example first collects all matching elements with
@code{root.findall()}, and only then iterates over the list of matches.

XML はこのようになります:

@example
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>
@end example

@node XML 文書の構築,名前空間のある XML の解析,XML ファイルの編集,チュートリアル<3>
@anchor{library/xml etree elementtree building-xml-documents}@anchor{3cfd}
@subsubsection XML 文書の構築


@ref{3cfe,,SubElement()} 関数は、与えられた要素に新しい子要素を作成する便利な手段も提供しています:

@example
>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>
@end example

@node 名前空間のある XML の解析,,XML 文書の構築,チュートリアル<3>
@anchor{library/xml etree elementtree parsing-xml-with-namespaces}@anchor{3cff}
@subsubsection 名前空間のある XML の解析


XML 入力が 名前空間@footnote{https://en.wikipedia.org/wiki/XML_namespace} を持っている場合、 @code{prefix:sometag} の形式で修飾されたタグと属性が、その `prefix' が完全な `URI' で置換された @code{@{uri@}sometag} の形に展開されます。さらに、 デフォルトの XML 名前空間@footnote{https://www.w3.org/TR/xml-names/#defaulting} があると、修飾されていない全てのタグにその完全 URI が前置されます。

ひとつは接頭辞 "fictional" でもうひとつがデフォルト名前空間で提供された、 2 つの名前空間を組み込んだ XML の例をここにお見せします:

@example
<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>
@end example

この XML の例を、検索し、渡り歩くためのひとつの方法としては、 @ref{187a,,find()} や @ref{187c,,findall()} に渡す xpath で全てのタグや属性に手作業で URI を付けてまわる手があります:

@example
root = fromstring(xml_text)
for actor in root.findall('@{http://people.example.com@}actor'):
    name = actor.find('@{http://people.example.com@}name')
    print(name.text)
    for char in actor.findall('@{http://characters.example.com@}character'):
        print(' |-->', char.text)
@end example

もっと良い方法があります。接頭辞の辞書を作り、これを検索関数で使うことです:

@example
ns = @{'real_person': 'http://people.example.com',
      'role': 'http://characters.example.com'@}

for actor in root.findall('real_person:actor', ns):
    name = actor.find('real_person:name', ns)
    print(name.text)
    for char in actor.findall('role:character', ns):
        print(' |-->', char.text)
@end example

どちらのアプローチでも同じ結果です:

@example
John Cleese
 |--> Lancelot
 |--> Archie Leach
Eric Idle
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement
@end example

@node XPath サポート,リファレンス<5>,チュートリアル<3>,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree elementtree-xpath}@anchor{da6}@anchor{library/xml etree elementtree xpath-support}@anchor{3d00}
@subsubsection XPath サポート


このモジュールは木構造内の要素の位置決めのための XPath 式@footnote{https://www.w3.org/TR/xpath} を限定的にサポートしています。その目指すところは短縮構文のほんの一部だけのサポートであり、XPath エンジンのフルセットは想定していません。

@menu
* 使用例: 使用例<33>. 
* サポートされている XPath 構文:: 

@end menu

@node 使用例<33>,サポートされている XPath 構文,,XPath サポート
@anchor{library/xml etree elementtree example}@anchor{3d01}
@subsubsection 使用例


以下はこのモジュールの XPath 機能の一部を紹介する例です。@ref{3cf1,,XML の解析} 節から XML 文書 @code{countrydata} を使用します:

@example
import xml.etree.ElementTree as ET

root = ET.fromstring(countrydata)

# Top-level elements
root.findall(".")

# All 'neighbor' grand-children of 'country' children of the top-level
# elements
root.findall("./country/neighbor")

# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@@name='Singapore']")

# 'year' nodes that are children of nodes with name='Singapore'
root.findall(".//*[@@name='Singapore']/year")

# All 'neighbor' nodes that are the second child of their parent
root.findall(".//neighbor[2]")
@end example

For XML with namespaces, use the usual qualified @code{@{namespace@}tag} notation:

@example
# All dublin-core "title" tags in the document
root.findall(".//@{http://purl.org/dc/elements/1.1/@}title")
@end example

@node サポートされている XPath 構文,,使用例<33>,XPath サポート
@anchor{library/xml etree elementtree supported-xpath-syntax}@anchor{3d02}
@subsubsection サポートされている XPath 構文



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

操作

@tab

意味

@item

@code{tag}

@tab

Selects all child elements with the given tag.
For example, @code{spam} selects all child elements
named @code{spam}, and @code{spam/egg} selects all
grandchildren named @code{egg} in all children named
@code{spam}.  @code{@{namespace@}*} selects all tags in the
given namespace, @code{@{*@}spam} selects tags named
@code{spam} in any (or no) namespace, and @code{@{@}*}
only selects tags that are not in a namespace.


バージョン 3.8 で変更: Support for star-wildcards was added.


@item

@code{*}

@tab

Selects all child elements, including comments and
processing instructions.  For example, @code{*/egg}
selects all grandchildren named @code{egg}.

@item

@code{.}

@tab

現在のノードを選択します。これはパスの先頭に置くことで相対パスであることを示すのに役立ちます。

@item

@code{//}

@tab

現在の要素の下にある全てのレベルの全ての子要素を選択します。例えば、@code{.//egg} は木全体から @code{egg} 要素を選択します。

@item

@code{..}

@tab

親ノードを選択します。パスが開始要素 (@code{find} が呼ばれた要素) の上の要素に進もうとした場合 @code{None} を返します。

@item

@code{[@@attrib]}

@tab

与えられた属性を持つ全ての要素を選択します。

@item

@code{[@@attrib='value']}

@tab

与えられた属性が与えられた値を持つ全ての要素を選択します。
値に引用符は含められません。

@item

@code{[@@attrib!='value']}

@tab

与えられた属性が与えられた値を持たない全ての要素を選択します。
値に引用符は含められません。


Added in version 3.10.


@item

@code{[tag]}

@tab

@code{tag} という名前の子要素を持つ全ての要素を選択します。
直下の子要素のみサポートしています。

@item

@code{[.='text']}

@tab

子孫のうち、与えられた @code{text} とテキスト全体が等しい全ての要素を選択します。


Added in version 3.7.


@item

@code{[.!='text']}

@tab

子孫のうち、与えられた @code{text} とテキスト全体が等しくない全ての要素を選択します。


Added in version 3.10.


@item

@code{[tag='text']}

@tab

子孫を含む完全なテキストコンテンツと与えられた @code{text} が一致する、 @code{tag} と名付けられた子要素を持つすべての要素を選択します。

@item

@code{[tag!='text']}

@tab

子孫を含む完全なテキストコンテンツと与えられた @code{text} が一致しない、 @code{tag} と名付けられた子要素を持つすべての要素を選択します。


Added in version 3.10.


@item

@code{[position]}

@tab

与えられた位置にあるすべての要素を選択します。位置は整数 (先頭は 1)、式 @code{last()} (末尾)、あるいは末尾からの相対位置 (例えば @code{last()-1}) のいずれかで指定できます。

@end multitable


述語 (角括弧内の式) の前にはタグ名、アスタリスク、あるいはその他の述語がなければなりません。
@code{position} 述語の前にはタグ名がなければなりません。

@node リファレンス<5>,XInclude サポート,XPath サポート,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree reference}@anchor{3d03}
@subsubsection リファレンス


@menu
* 関数: 関数<9>. 

@end menu

@node 関数<9>,,,リファレンス<5>
@anchor{library/xml etree elementtree elementtree-functions}@anchor{3d04}@anchor{library/xml etree elementtree functions}@anchor{3d05}
@subsubsection 関数


@geindex canonicalize() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree canonicalize}@anchor{c48}
@deffn {の関数} xml.etree.ElementTree.canonicalize (xml_data=None, *, out=None, from_file=None, **options)

C14N 2.0@footnote{https://www.w3.org/TR/xml-c14n2/} transformation function.

Canonicalization is a way to normalise XML output in a way that allows
byte-by-byte comparisons and digital signatures.  It reduces the freedom
that XML serializers have and instead generates a more constrained XML
representation.  The main restrictions regard the placement of namespace
declarations, the ordering of attributes, and ignorable whitespace.

This function takes an XML data string (`xml_data') or a file path or
file-like object (`from_file') as input, converts it to the canonical
form, and writes it out using the `out' file(-like) object, if provided,
or returns it as a text string if not.  The output file receives text,
not bytes.  It should therefore be opened in text mode with @code{utf-8}
encoding.

利用例:

@example
xml_data = "<root>...</root>"
print(canonicalize(xml_data))

with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
    canonicalize(xml_data, out=out_file)

with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
    canonicalize(from_file="inputfile.xml", out=out_file)
@end example

The configuration `options' are as follows:


@itemize -

@item 
`with_comments': set to true to include comments (default: false)

@item 

@table @asis

@item `strip_text': set to true to strip whitespace before and after text content

(デフォルト: false)
@end table

@item 

@table @asis

@item `rewrite_prefixes': set to true to replace namespace prefixes by "n@{number@}"

(デフォルト: false)
@end table

@item 

@table @asis

@item `qname_aware_tags': a set of qname aware tag names in which prefixes

should be replaced in text content (default: empty)
@end table

@item 

@table @asis

@item `qname_aware_attrs': a set of qname aware attribute names in which prefixes

should be replaced in text content (default: empty)
@end table

@item 
`exclude_attrs': a set of attribute names that should not be serialised

@item 
`exclude_tags': a set of tag names that should not be serialised
@end itemize

In the option list above, "a set" refers to any collection or iterable of
strings, no ordering is expected.


Added in version 3.8.

@end deffn

@geindex Comment() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree Comment}@anchor{3d06}
@deffn {の関数} xml.etree.ElementTree.Comment (text=None)

コメント要素のファクトリです。このファクトリ関数は、標準のシリアライザでは XML コメントにシリアライズされる特別な要素を作ります。コメント文字列はバイト文字列でも Unicode 文字列でも構いません。`text' はそのコメント文字列を含んだ文字列です。コメントを表わす要素のインスタンスを返します。

@ref{c49,,XMLParser} は、入力に含まれるコメントを読み飛ばし、コメントオブジェクトは作成しません。@ref{b47,,ElementTree} は、@ref{363,,Element} メソッドの 1 つを使用して木内に挿入されたコメントノードのみを含みます。
@end deffn

@geindex dump() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree dump}@anchor{3d07}
@deffn {の関数} xml.etree.ElementTree.dump (elem)

要素の木もしくは要素の構造を sys.stdout に出力します。この関数はデバッグ目的のみに使用してください。

出力される形式の正確なところは実装依存です。このバージョンでは、通常の XML ファイルとして出力されます。

`elem' は要素の木もしくは個別の要素です。


バージョン 3.8 で変更: @ref{3d07,,dump()} 関数はユーザーが指定した属性の順序を保持するようになりました。

@end deffn

@geindex fromstring() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree fromstring}@anchor{3cf3}
@deffn {の関数} xml.etree.ElementTree.fromstring (text, parser=None)

文字列定数で与えられた XML 断片を解析します。 @ref{3d08,,XML()} と同じです。 `text' には XML データを含む文字列を指定します。 `parser' はオプションで、パーザのインスタンスを指定します。指定されなかった場合、標準の @ref{c49,,XMLParser} パーザを使用します。 @ref{363,,Element} インスタンスを返します。
@end deffn

@geindex fromstringlist() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree fromstringlist}@anchor{13e9}
@deffn {の関数} xml.etree.ElementTree.fromstringlist (sequence, parser=None)

文字列フラグメントのシーケンスから XML ドキュメントを解析します。 `sequence' は XML データのフラグメントを格納した、リストかその他のシーケンスです。 `parser' はオプションのパーザインスタンスです。パーザが指定されない場合、標準の @ref{c49,,XMLParser} パーザが使用されます。 @ref{363,,Element} インスタンスを返します。


Added in version 3.2.

@end deffn

@geindex indent() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree indent}@anchor{3d09}
@deffn {の関数} xml.etree.ElementTree.indent (tree, space='  ', level=0)

Appends whitespace to the subtree to indent the tree visually.
This can be used to generate pretty-printed XML output.
`tree' can be an Element or ElementTree.  `space' is the whitespace
string that will be inserted for each indentation level, two space
characters by default.  For indenting partial subtrees inside of an
already indented tree, pass the initial indentation level as `level'.


Added in version 3.9.

@end deffn

@geindex iselement() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree iselement}@anchor{3d0a}
@deffn {の関数} xml.etree.ElementTree.iselement (element)

オブジェクトが正当な要素オブジェクトであるかをチェックします。 `element' は要素インスタンスです。引数が要素オブジェクトの場合 @code{True} を返します。
@end deffn

@geindex iterparse() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree iterparse}@anchor{57a}
@deffn {の関数} xml.etree.ElementTree.iterparse (source, events=None, parser=None)

Parses an XML section into an element tree incrementally, and reports what's
going on to the user.  `source' is a filename or @ref{13db,,file object}
containing XML data.  `events' is a sequence of events to report back.  The
supported events are the strings @code{"start"}, @code{"end"}, @code{"comment"},
@code{"pi"}, @code{"start-ns"} and @code{"end-ns"}
(the "ns" events are used to get detailed namespace
information).  If `events' is omitted, only @code{"end"} events are reported.
`parser' is an optional parser instance.  If not given, the standard
@ref{c49,,XMLParser} parser is used.  `parser' must be a subclass of
@ref{c49,,XMLParser} and can only use the default @ref{c4a,,TreeBuilder} as a
target. Returns an @ref{4c8,,iterator} providing @code{(event, elem)} pairs;
it has a @code{root} attribute that references the root element of the
resulting XML tree once `source' is fully read.
The iterator has the @code{close()} method that closes the internal
file object if `source' is a filename.

@ref{57a,,iterparse()} は木をインクリメンタルに構築しますが、`source' (または指定のファイル) でのブロッキング読みを起こします。したがって、ブロッキング読みが許可されないアプリケーションには適しません。完全に非ブロックのパースのためには、@ref{11f5,,XMLPullParser} を参照してください。

@cartouche
@quotation 注釈 
@ref{57a,,iterparse()} は "start" イベントを発行した時に開始タグの文字 ">" が現れたことだけを保証します。そのため、属性は定義されますが、その時点ではテキストの内容も tail 属性も定義されていません。同じことは子要素にも言えて、その時点ではあるともないとも言えません。

全部揃った要素が必要ならば、"end" イベントを探してください。
@end quotation
@end cartouche


バージョン 3.4 で非推奨: `parser' 引数。



バージョン 3.8 で変更: イベント @code{comment}, @code{pi} が追加されました。



バージョン 3.13 で変更: Added the @code{close()} method.

@end deffn

@geindex parse() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree parse}@anchor{3d0b}
@deffn {の関数} xml.etree.ElementTree.parse (source, parser=None)

XML 断片を解析して要素の木にします。 `source' には XML データを含むファイル名またはファイルオブジェクトを指定します。 `parser' はオプションでパーザインスタンスを指定します。パーザが指定されない場合、標準の @ref{c49,,XMLParser} パーザが使用されます。 @ref{b47,,ElementTree} インスタンスを返します。
@end deffn

@geindex ProcessingInstruction() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree ProcessingInstruction}@anchor{3d0c}
@deffn {の関数} xml.etree.ElementTree.ProcessingInstruction (target, text=None)

PI 要素のファクトリです。このファクトリ関数は XML の処理命令としてシリアライズされた特別な要素を作成します。`target' は PI ターゲットを含んだ文字列です。`text' を指定する場合は PI コンテンツを含む文字列にします。PI を表わす要素インスタンスを返します。

Note that @ref{c49,,XMLParser} skips over processing instructions
in the input instead of creating PI objects for them. An
@ref{b47,,ElementTree} will only contain processing instruction nodes if
they have been inserted into to the tree using one of the
@ref{363,,Element} methods.
@end deffn

@geindex register_namespace() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree register_namespace}@anchor{13ea}
@deffn {の関数} xml.etree.ElementTree.register_namespace (prefix, uri)

名前空間の接頭辞を登録します。レジストリはグローバルで、与えられた接頭辞か名前空間 URI のどちらかの既存のマッピングはすべて削除されます。`prefix' には名前空間の接頭辞を指定します。`uri' には名前空間の URI を指定します。この名前空間のタグや属性は、可能な限り与えられた接頭辞をつけてシリアライズされます。


Added in version 3.2.

@end deffn

@geindex SubElement() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree SubElement}@anchor{3cfe}
@deffn {の関数} xml.etree.ElementTree.SubElement (parent, tag, attrib=@{@}, **extra)

子要素のファクトリです。この関数は要素インスタンスを作成し、それを既存の要素に追加します。

要素名、属性名、および属性値はバイト文字列でも Unicode 文字列でも構いません。 `parent' には親要素を指定します。 `tag' には要素名を指定します。`attrib' はオプションで要素の属性を含む辞書を指定します。 `extra' は追加の属性で、キーワード引数として与えます。要素インスタンスを返します。
@end deffn

@geindex tostring() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree tostring}@anchor{11f7}
@deffn {の関数} xml.etree.ElementTree.tostring (element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)

XML 要素を全ての子要素を含めて表現する文字列を生成します。 `element' は @ref{363,,Element} のインスタンスです。 `encoding' @footnote{
XML 出力に含まれるエンコーディング文字列は適切な規格に従っていなければなりません。例えば、"UTF-8" は有効ですが、"UTF8" はそうではありません。@indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} と @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml} を参照してください。
} は出力エンコーディング(デフォルトは US-ASCII)です。Unicode 文字列を生成するには、@code{encoding="unicode"} を使用してください。 `method' は @code{"xml"}, @code{"html"}, @code{"text"} のいずれか(デフォルトは @code{"xml"}) です。 `xml_declaration', `default_namespace', `short_empty_elements' は、 @ref{c8c,,ElementTree.write()} での意味と同じ意味を持ちます。 XML データを含んだ (オプションで) エンコードされた文字列を返します。


バージョン 3.4 で変更: `short_empty_elements' 引数を追加しました。



バージョン 3.8 で変更: Added the `xml_declaration' and `default_namespace' parameters.



バージョン 3.8 で変更: The @ref{11f7,,tostring()} function now preserves the attribute order
specified by the user.

@end deffn

@geindex tostringlist() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree tostringlist}@anchor{11f8}
@deffn {の関数} xml.etree.ElementTree.tostringlist (element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)

XML 要素を全ての子要素を含めて表現する文字列を生成します。 `element' は @ref{363,,Element} のインスタンスです。 `encoding' @footnote{
XML 出力に含まれるエンコーディング文字列は適切な規格に従っていなければなりません。例えば、"UTF-8" は有効ですが、"UTF8" はそうではありません。@indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} と @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml} を参照してください。
} は出力エンコーディング(デフォルトは US-ASCII)です。Unicode 文字列を生成するには、@code{encoding="unicode"} を使用してください。 `method' は @code{"xml"}, @code{"html"}, @code{"text"} のいずれか(デフォルトは @code{"xml"}) です。 xml_declaration*, `default_namespace', `short_empty_elements' は、 @ref{c8c,,ElementTree.write()} での意味と同じ意味を持ちます。 XML データを含んだ (オプションで) エンコードされた文字列のリストを返します。@code{b"".join(tostringlist(element)) == tostring(element)} となること以外、特定の順序になる保証はありません。


Added in version 3.2.



バージョン 3.4 で変更: `short_empty_elements' 引数を追加しました。



バージョン 3.8 で変更: Added the `xml_declaration' and `default_namespace' parameters.



バージョン 3.8 で変更: @ref{11f8,,tostringlist()} 関数はユーザーが指定した属性の順序を保持するようになりました。

@end deffn

@geindex XML() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree XML}@anchor{3d08}
@deffn {の関数} xml.etree.ElementTree.XML (text, parser=None)

文字列定数で与えられた XML 断片を解析します。この関数は Python コードに "XML リテラル" を埋め込むのに使えます。 `text' には XML データを含む文字列を指定します。 `parser' はオプションで、パーザのインスタンスを指定します。指定されなかった場合、標準の @ref{c49,,XMLParser} パーザを使用します。 @ref{363,,Element} インスタンスを返します。
@end deffn

@geindex XMLID() (xml.etree.ElementTree モジュール)
@anchor{library/xml etree elementtree xml etree ElementTree XMLID}@anchor{3d0d}
@deffn {の関数} xml.etree.ElementTree.XMLID (text, parser=None)

文字列定数で与えられた XML 断片を解析し、要素 ID と要素を対応付ける辞書を返します。 `text' には XMLデータを含んだ文字列を指定します。 `parser' はオプションで、パーザのインスタンスを指定します。指定されなかった場合、標準の @ref{c49,,XMLParser} パーザを使用します。 @ref{363,,Element} のインスタンスと辞書のタプルを返します。
@end deffn

@node XInclude サポート,リファレンス<6>,リファレンス<5>,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree elementtree-xinclude}@anchor{3d0e}@anchor{library/xml etree elementtree xinclude-support}@anchor{3d0f}
@subsubsection XInclude サポート


This module provides limited support for
XInclude directives@footnote{https://www.w3.org/TR/xinclude/}, via the @ref{12a,,xml.etree.ElementInclude} helper module.  This module can be used to insert subtrees and text strings into element trees, based on information in the tree.

@menu
* 使用例: 使用例<34>. 

@end menu

@node 使用例<34>,,,XInclude サポート
@anchor{library/xml etree elementtree id3}@anchor{3d10}
@subsubsection 使用例


Here's an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the @code{@{http://www.w3.org/2001/XInclude@}include} element and set the `parse' attribute to @code{"xml"}, and use the `href' attribute to specify the document to include.

@example
<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="source.xml" parse="xml" />
</document>
@end example

By default, the `href' attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax.

To process this file, load it as usual, and pass the root element to the @code{xml.etree.ElementTree} module:

@example
from xml.etree import ElementTree, ElementInclude

tree = ElementTree.parse("document.xml")
root = tree.getroot()

ElementInclude.include(root)
@end example

The ElementInclude module replaces the @code{@{http://www.w3.org/2001/XInclude@}include} element with the root element from the `source.xml' document. The result might look something like this:

@example
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <para>This is a paragraph.</para>
</document>
@end example

If the `parse' attribute is omitted, it defaults to "xml". The href attribute is required.

To include a text document, use the @code{@{http://www.w3.org/2001/XInclude@}include} element, and set the `parse' attribute to "text":

@example
<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) <xi:include href="year.txt" parse="text" />.
</document>
@end example

The result might look something like:

@example
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) 2003.
</document>
@end example

@node リファレンス<6>,,XInclude サポート,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree id4}@anchor{3d11}
@subsubsection リファレンス


@menu
* 関数: 関数<10>. 
* Element オブジェクト:: 
* ElementTree オブジェクト:: 
* QName オブジェクト:: 
* TreeBuilder オブジェクト:: 
* XMLParser オブジェクト:: 
* XMLPullParser オブジェクト:: 
* 例外: 例外<22>. 

@end menu

@node 関数<10>,Element オブジェクト,,リファレンス<6>
@anchor{library/xml etree elementtree elementinclude-functions}@anchor{3d12}@anchor{library/xml etree elementtree id5}@anchor{3d13}
@subsubsection 関数


@geindex module; xml.etree.ElementInclude

@geindex default_loader() (xml.etree.ElementInclude モジュール)
@anchor{library/xml etree elementtree module-xml etree ElementInclude}@anchor{12a}@anchor{library/xml etree elementtree xml etree ElementInclude default_loader}@anchor{3d14}
@deffn {の関数} xml.etree.ElementInclude.default_loader (href, parse, encoding=None)

Default loader. This default loader reads an included resource from disk.
`href' is a URL.  `parse' is for parse mode either "xml" or "text".
`encoding' is an optional text encoding.  If not given, encoding is @code{utf-8}.
Returns the expanded resource.
If the parse mode is @code{"xml"}, this is an @ref{363,,Element} instance.
If the parse mode is @code{"text"}, this is a string.
If the loader fails, it can return @code{None} or raise an exception.
@end deffn

@geindex include() (xml.etree.ElementInclude モジュール)
@anchor{library/xml etree elementtree xml etree ElementInclude include}@anchor{3d15}
@deffn {の関数} xml.etree.ElementInclude.include (elem, loader=None, base_url=None, max_depth=6)

This function expands XInclude directives in-place in tree pointed by `elem'.
`elem' is either the root @ref{363,,Element} or an
@ref{b47,,ElementTree} instance to find such element.
`loader' is an optional resource loader.  If omitted, it defaults to @ref{3d14,,default_loader()}.
If given, it should be a callable that implements the same interface as
@ref{3d14,,default_loader()}.  `base_url' is base URL of the original file, to resolve
relative include file references.  `max_depth' is the maximum number of recursive
inclusions.  Limited to reduce the risk of malicious content explosion.
Pass @code{None} to disable the limitation.


バージョン 3.9 で変更: Added the `base_url' and `max_depth' parameters.

@end deffn

@node Element オブジェクト,ElementTree オブジェクト,関数<10>,リファレンス<6>
@anchor{library/xml etree elementtree element-objects}@anchor{3d16}@anchor{library/xml etree elementtree elementtree-element-objects}@anchor{3d17}
@subsubsection Element オブジェクト


@geindex Element (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree Element}@anchor{363}
@deffn {クラス} xml.etree.ElementTree.Element (tag, attrib=@{@}, **extra)

要素クラスです。この関数は Element インターフェースを定義すると同時に、そのリファレンス実装を提供します。

要素名、属性名、および属性値はバイト文字列でも Unicode 文字列でも構いません。 `tag' には要素名を指定します。`attrib' はオプションで、要素と属性を含む辞書を指定します。`extra' は追加の属性で、キーワード引数として与えます。要素インスタンスを返します。

@geindex tag (xml.etree.ElementTree.Element の属性)
@anchor{library/xml etree elementtree xml etree ElementTree Element tag}@anchor{1565}
@deffn {の属性} tag

この要素が表すデータの種類を示す文字列です (言い替えると、要素の型です)。
@end deffn

@geindex text (xml.etree.ElementTree.Element の属性)
@geindex tail (xml.etree.ElementTree.Element の属性)
@anchor{library/xml etree elementtree xml etree ElementTree Element text}@anchor{3cf8}
@deffn {の属性} text
@anchor{library/xml etree elementtree xml etree ElementTree Element tail}@anchor{3d18}
@deffnx {の属性} tail

これらの属性は要素に結びつけられた付加的なデータを保持するのに使われます。これらの属性値はたいてい文字列ですが、アプリケーション固有のオブジェクトであって構いません。要素が XML ファイルから作られる場合、 `text' 属性は要素の開始タグとその最初の子要素または終了タグまでのテキストか、あるいは @code{None} を保持し、 `tail' 属性は要素の終了タグと次のタグまでのテキストか、あるいは @code{None}  を保持します。このような XML データ

@example
<a><b>1<c>2<d/>3</c></b>4</a>
@end example

の場合、 `a' 要素は `text', `tail' 属性ともに @code{None}, `b' 要素は `text' に @code{"1"} で `tail' に @code{"4"}, `c' 要素は `text' に @code{"2"} で `tail' は @code{None}, `d' 要素 は `text' が @code{None} で `tail' に @code{"3"} をそれぞれ保持します。

要素の内側のテキストを収集するためには、@ref{13ed,,itertext()} を参照してください。例えば @code{"".join(element.itertext())} のようにします。

アプリケーションはこれらの属性に任意のオブジェクトを格納できます。
@end deffn

@geindex attrib (xml.etree.ElementTree.Element の属性)
@anchor{library/xml etree elementtree xml etree ElementTree Element attrib}@anchor{3d19}
@deffn {の属性} attrib

要素の属性を保持する辞書です。 `attrib' の値は常に書き換え可能な Python 辞書ですが、ElementTree の実装によっては別の内部表現を使用し、要求されたときにだけ辞書を作るようにしているかもしれません。そうした実装の利益を享受するために、可能な限り下記の辞書メソッドを通じて使用してください。
@end deffn

以下の辞書風メソッドが要素の属性に対して動作します。

@geindex clear() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element clear}@anchor{3d1a}
@deffn {メソッド} clear ()

要素をリセットします。この関数は全ての子要素を削除し、全属性を消去し、テキストとテール属性を @code{None} に設定します。
@end deffn

@geindex get() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element get}@anchor{3cf9}
@deffn {メソッド} get (key, default=None)

要素の `key' という名前の属性を取得します。

属性の値、または属性がない場合は `default' を返します。
@end deffn

@geindex items() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element items}@anchor{3d1b}
@deffn {メソッド} items ()

要素の属性を (名前, 値) ペアのシーケンスとして返します。返される属性の順番は決まっていません。
@end deffn

@geindex keys() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element keys}@anchor{3d1c}
@deffn {メソッド} keys ()

要素の属性名をリストとして返します。返される名前の順番は決まっていません。
@end deffn

@geindex set() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element set}@anchor{3cfb}
@deffn {メソッド} set (key, value)

要素の属性 `key' に `value' をセットします。
@end deffn

以下のメソッドは要素の子要素 (副要素) に対して動作します。

@geindex append() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element append}@anchor{3cfc}
@deffn {メソッド} append (subelement)

要素 `subelement' を、要素の子要素の内部リストの末尾に追加します。`subelement' @ref{363,,Element} でない場合、@ref{198,,TypeError} を送出します。
@end deffn

@geindex extend() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element extend}@anchor{13eb}
@deffn {メソッド} extend (subelements)

Appends `subelements' from an iterable of elements.
Raises @ref{198,,TypeError} if a subelement is not an @ref{363,,Element}.


Added in version 3.2.

@end deffn

@geindex find() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element find}@anchor{187a}
@deffn {メソッド} find (match, namespaces=None)

Finds the first subelement matching `match'.  `match' may be a tag name
or a @ref{da6,,path}.  Returns an element instance
or @code{None}.  `namespaces' is an optional mapping from namespace prefix
to full name.  Pass @code{'@w{'}} as prefix to move all unprefixed tag names
in the expression into the given namespace.
@end deffn

@geindex findall() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element findall}@anchor{187c}
@deffn {メソッド} findall (match, namespaces=None)

Finds all matching subelements, by tag name or
@ref{da6,,path}.  Returns a list containing all matching
elements in document order.  `namespaces' is an optional mapping from
namespace prefix to full name.  Pass @code{'@w{'}} as prefix to move all
unprefixed tag names in the expression into the given namespace.
@end deffn

@geindex findtext() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element findtext}@anchor{187b}
@deffn {メソッド} findtext (match, default=None, namespaces=None)

Finds text for the first subelement matching `match'.  `match' may be
a tag name or a @ref{da6,,path}.  Returns the text content
of the first matching element, or `default' if no element was found.
Note that if the matching element has no text content an empty string
is returned. `namespaces' is an optional mapping from namespace prefix
to full name.  Pass @code{'@w{'}} as prefix to move all unprefixed tag names
in the expression into the given namespace.
@end deffn

@geindex insert() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element insert}@anchor{3d1d}
@deffn {メソッド} insert (index, subelement)

要素内の指定された位置に `subelement' を挿入します。`subelement' が @ref{363,,Element} でない場合、@ref{198,,TypeError} を送出します。
@end deffn

@geindex iter() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element iter}@anchor{1566}
@deffn {メソッド} iter (tag=None)

現在の要素を根とする木の @ref{4c8,,イテレータ} を作成します。イテレータは現在の要素とそれ以下のすべての要素を、文書内での出現順 (深さ優先順) でイテレートします。 `tag' が @code{None} または @code{'*'} でない場合、与えられたタグに等しいものについてのみイテレータから返されます。イテレート中に木構造が変更された場合の結果は未定義です。


Added in version 3.2.

@end deffn

@geindex iterfind() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element iterfind}@anchor{13ec}
@deffn {メソッド} iterfind (match, namespaces=None)

タグ名または @ref{da6,,パス} にマッチするすべての子要素を検索します。マッチしたすべての要素を文書内での出現順で yield するイテレータを返します。`namespaces' はオプションで、名前空間接頭辞と完全名を対応付けるマップオブジェクトを指定します。


Added in version 3.2.

@end deffn

@geindex itertext() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element itertext}@anchor{13ed}
@deffn {メソッド} itertext ()

テキストのイテレータを作成します。イテレータは、この要素とすべての子要素を文書上の順序で巡回し、すべての内部のテキストを返します。


Added in version 3.2.

@end deffn

@geindex makeelement() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element makeelement}@anchor{3d1e}
@deffn {メソッド} makeelement (tag, attrib)

現在の要素と同じ型の新しい要素オブジェクトを作成します。このメソッドは呼び出さずに、 @ref{3cfe,,SubElement()} ファクトリ関数を使って下さい。
@end deffn

@geindex remove() (xml.etree.ElementTree.Element のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree Element remove}@anchor{1876}
@deffn {メソッド} remove (subelement)

要素から `subelement' を削除します。find* メソッド群と異なり、このメソッドは要素をインスタンスの同一性で比較します。タグや内容では比較しません。
@end deffn

@ref{363,,Element} オブジェクトは以下のシーケンス型のメソッドを、サブ要素を操作するためにサポートします:  @ref{14e4,,__delitem__()}, @ref{588,,__getitem__()}, @ref{14e3,,__setitem__()}, @ref{178f,,__len__()}.

Caution: Elements with no subelements will test as @code{False}.  In a future
release of Python, all elements will test as @code{True} regardless of whether
subelements exist.  Instead, prefer explicit @code{len(elem)} or
@code{elem is not None} tests.:

@example
element = root.find('foo')

if not element:  # careful!
    print("element not found, or element has no subelements")

if element is None:
    print("element not found")
@end example


バージョン 3.12 で変更: Testing the truth value of an Element emits @ref{1a3,,DeprecationWarning}.


Prior to Python 3.8, the serialisation order of the XML attributes of
elements was artificially made predictable by sorting the attributes by
their name. Based on the now guaranteed ordering of dicts, this arbitrary
reordering was removed in Python 3.8 to preserve the order in which
attributes were originally parsed or created by user code.

In general, user code should try not to depend on a specific ordering of
attributes, given that the XML Information Set@footnote{https://www.w3.org/TR/xml-infoset/} explicitly excludes the attribute
order from conveying information. Code should be prepared to deal with
any ordering on input. In cases where deterministic XML output is required,
e.g. for cryptographic signing or test data sets, canonical serialisation
is available with the @ref{c48,,canonicalize()} function.

In cases where canonical output is not applicable but a specific attribute
order is still desirable on output, code should aim for creating the
attributes directly in the desired order, to avoid perceptual mismatches
for readers of the code. In cases where this is difficult to achieve, a
recipe like the following can be applied prior to serialisation to enforce
an order independently from the Element creation:

@example
def reorder_attributes(root):
    for el in root.iter():
        attrib = el.attrib
        if len(attrib) > 1:
            # adjust attribute order, e.g. by sorting
            attribs = sorted(attrib.items())
            attrib.clear()
            attrib.update(attribs)
@end example
@end deffn

@node ElementTree オブジェクト,QName オブジェクト,Element オブジェクト,リファレンス<6>
@anchor{library/xml etree elementtree elementtree-elementtree-objects}@anchor{3d1f}@anchor{library/xml etree elementtree elementtree-objects}@anchor{3d20}
@subsubsection ElementTree オブジェクト


@geindex ElementTree (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree}@anchor{b47}
@deffn {クラス} xml.etree.ElementTree.ElementTree (element=None, file=None)

ElementTree ラッパークラスです。このクラスは要素の全階層を表現し、さらに標準 XML との相互変換を追加しています。

`element' は根要素です。`file' が指定されている場合、その XML ファイルの内容により木は初期化されます。

@geindex _setroot() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree _setroot}@anchor{3d21}
@deffn {メソッド} _setroot (element)

この木の根要素を置き換えます。従って現在の木の内容は破棄され、与えられた要素が代わりに使われます。注意して使ってください。 `element' は要素インスタンスです。
@end deffn

@geindex find() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree find}@anchor{3d22}
@deffn {メソッド} find (match, namespaces=None)

@ref{187a,,Element.find()} と同じで、木の根要素を起点とします。
@end deffn

@geindex findall() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree findall}@anchor{3d23}
@deffn {メソッド} findall (match, namespaces=None)

@ref{187c,,Element.findall()} と同じで、木の根要素を起点とします。
@end deffn

@geindex findtext() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree findtext}@anchor{3d24}
@deffn {メソッド} findtext (match, default=None, namespaces=None)

@ref{187b,,Element.findtext()} と同じで、木の根要素を起点とします。
@end deffn

@geindex getroot() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree getroot}@anchor{3d25}
@deffn {メソッド} getroot ()

この木のルート要素を返します。
@end deffn

@geindex iter() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree iter}@anchor{3d26}
@deffn {メソッド} iter (tag=None)

根要素に対する、木を巡回するイテレータを返します。イテレータは木のすべての要素に渡ってセクション順にループします。`tag' は探したいタグです (デフォルトではすべての要素を返します)。
@end deffn

@geindex iterfind() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree iterfind}@anchor{3d27}
@deffn {メソッド} iterfind (match, namespaces=None)

@ref{13ec,,Element.iterfind()} と同じで、木の根要素を起点とします。


Added in version 3.2.

@end deffn

@geindex parse() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree parse}@anchor{3d28}
@deffn {メソッド} parse (source, parser=None)

外部の XML 断片をこの要素木に入れます。`source' にはファイル名か @ref{13db,,ファイルオブジェクト} を指定します。`parser' はオプションで、パーザインスタンスを指定します。パーザが指定されない場合、標準の @ref{c49,,XMLParser} パーザが使用されます。断片の根要素を返します。
@end deffn

@geindex write() (xml.etree.ElementTree.ElementTree のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree write}@anchor{c8c}
@deffn {メソッド} write (file, encoding='us-ascii', xml_declaration=None, default_namespace=None, method='xml', *, short_empty_elements=True)

要素の木をファイルに XML として書き込みます。
`file' は、書き込み用に開かれたファイル名または @ref{13db,,ファイルオブジェクト} です。
`encoding' @footnote{
XML 出力に含まれるエンコーディング文字列は適切な規格に従っていなければなりません。例えば、"UTF-8" は有効ですが、"UTF8" はそうではありません。@indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} と @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml} を参照してください。
} は出力エンコーディング(デフォルトは US-ASCII)です。
`xml_declaration' は、 XML 宣言がファイルに書かれるかどうかを制御します。
@code{False} の場合は常に書かれず、 @code{True} の場合は常に書かれ、 @code{None} の場合は US-ASCII 、 UTF-8 、 Unicode 以外の場合に書かれます (デフォルトは @code{None} です)。
`default_namespace' でデフォルトの XML 名前空間 ("xmlns" 用) を指定します。
`method' は @code{"xml"}, @code{"html"}, @code{"text"} のいずれかです (デフォルトは @code{"xml"} です)。
キーワード専用の `short_empty_elements' 引数は、内容がない属性のフォーマットを制御します。
@code{True} (既定) の場合、単一の空要素タグとして書かれ、@code{False} の場合、開始タグと終了タグのペアとしてかかれます。

出力は引数 `encoding' によって、文字列 (@ref{169,,str}) かバイト列 (@ref{192,,bytes}) になります。`encoding' が @code{"unicode"} の場合、出力は文字列になり、それ以外ではバイト列になります。`file' が @ref{13db,,ファイルオブジェクト} の場合、型が衝突する場合があります。文字列をバイト列ファイルへ書き込んだり、その逆を行わないよう注意してください。


バージョン 3.4 で変更: `short_empty_elements' 引数を追加しました。



バージョン 3.8 で変更: @ref{c8c,,write()} メソッドはユーザーが指定した属性の順序を保持するようになりました。

@end deffn
@end deffn

以下はこれから操作する XML ファイルです:

@example
<html>
    <head>
        <title>Example page</title>
    </head>
    <body>
        <p>Moved to <a href="http://example.org/">example.org</a>
        or <a href="http://example.com/">example.com</a>.</p>
    </body>
</html>
@end example

第 1 段落のすべてのリンクの "target" 属性を変更する例:

@example
>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
<Element 'html' at 0xb77e6fac>
>>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
>>> p
<Element 'p' at 0xb77ec26c>
>>> links = list(p.iter("a"))   # Returns list of all links
>>> links
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links:             # Iterates through all found links
...     i.attrib["target"] = "blank"
...
>>> tree.write("output.xhtml")
@end example

@node QName オブジェクト,TreeBuilder オブジェクト,ElementTree オブジェクト,リファレンス<6>
@anchor{library/xml etree elementtree elementtree-qname-objects}@anchor{3d29}@anchor{library/xml etree elementtree qname-objects}@anchor{3d2a}
@subsubsection QName オブジェクト


@geindex QName (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree QName}@anchor{3d2b}
@deffn {クラス} xml.etree.ElementTree.QName (text_or_uri, tag=None)

QName ラッパーです。
このクラスは QName 属性値をラップし、出力時に適切な名前空間の扱いを得るために使われます。
`text_or_uri' は @{uri@}local という形式の QName 値を含む文字列、または tag 引数が与えられた場合には QName の URI 部分の文字列です。
`tag' が与えられた場合、一つめの引数は URI と解釈され、この引数はローカル名と解釈されます。
@ref{3d2b,,QName} インスタンスは不透明です。
@end deffn

@node TreeBuilder オブジェクト,XMLParser オブジェクト,QName オブジェクト,リファレンス<6>
@anchor{library/xml etree elementtree elementtree-treebuilder-objects}@anchor{3d2c}@anchor{library/xml etree elementtree treebuilder-objects}@anchor{3d2d}
@subsubsection TreeBuilder オブジェクト


@geindex TreeBuilder (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder}@anchor{c4a}
@deffn {クラス} xml.etree.ElementTree.TreeBuilder (element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, insert_pis=False)

汎用の要素構造ビルダー。これは start, data, end, comment, pi のメソッド呼び出しの列を整形式の要素構造に変換します。このクラスを使うと、好みの XML 構文解析器、または他の XML に似た形式の構文解析器を使って、要素構造を作り出すことができます。

`element_factory', when given, must be a callable accepting two positional
arguments: a tag and a dict of attributes.  It is expected to return a new
element instance.

The `comment_factory' and `pi_factory' functions, when given, should behave
like the @ref{3d06,,Comment()} and @ref{3d0c,,ProcessingInstruction()} functions to
create comments and processing instructions.  When not given, the default
factories will be used.  When `insert_comments' and/or `insert_pis' is true,
comments/pis will be inserted into the tree if they appear within the root
element (but not outside of it).

@geindex close() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder close}@anchor{3d2e}
@deffn {メソッド} close ()

ビルダのバッファをフラッシュし、最上位の文書要素を返します。戻り値は  @ref{363,,Element} インスタンスになります。
@end deffn

@geindex data() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder data}@anchor{3d2f}
@deffn {メソッド} data (data)

現在の要素にテキストを追加します。 `data' は文字列です。バイト文字列もしくは Unicode 文字列でなければなりません。
@end deffn

@geindex end() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder end}@anchor{13ee}
@deffn {メソッド} end (tag)

現在の要素を閉じます。 `tag' は要素の名前です。閉じられた要素を返します。
@end deffn

@geindex start() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder start}@anchor{1d6c}
@deffn {メソッド} start (tag, attrs)

新しい要素を開きます。 `tag' は要素の名前です。 `attrs' は要素の属性を保持した辞書です。開かれた要素を返します。
@end deffn

@geindex comment() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder comment}@anchor{3d30}
@deffn {メソッド} comment (text)

Creates a comment with the given `text'.  If @code{insert_comments} is true,
this will also add it to the tree.


Added in version 3.8.

@end deffn

@geindex pi() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder pi}@anchor{3d31}
@deffn {メソッド} pi (target, text)

Creates a process instruction with the given `target' name and `text'.
If @code{insert_pis} is true, this will also add it to the tree.


Added in version 3.8.

@end deffn

加えて、カスタムの @ref{c4a,,TreeBuilder} オブジェクトは以下のメソッドを提供できます:

@geindex doctype() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder doctype}@anchor{c8e}
@deffn {メソッド} doctype (name, pubid, system)

doctype 宣言を処理します。 `name' は doctype 名です。 `pubid' は公式の識別子です。 `system' はシステム識別子です。このメソッドはデフォルトの @ref{c4a,,TreeBuilder} クラスには存在しません。


Added in version 3.2.

@end deffn

@geindex start_ns() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder start_ns}@anchor{3d32}
@deffn {メソッド} start_ns (prefix, uri)

Is called whenever the parser encounters a new namespace declaration,
before the @code{start()} callback for the opening element that defines it.
`prefix' is @code{'@w{'}} for the default namespace and the declared
namespace prefix name otherwise.  `uri' is the namespace URI.


Added in version 3.8.

@end deffn

@geindex end_ns() (xml.etree.ElementTree.TreeBuilder のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder end_ns}@anchor{3d33}
@deffn {メソッド} end_ns (prefix)

Is called after the @code{end()} callback of an element that declared
a namespace prefix mapping, with the name of the `prefix' that went
out of scope.


Added in version 3.8.

@end deffn
@end deffn

@geindex C14NWriterTarget (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree C14NWriterTarget}@anchor{3d34}
@deffn {クラス} xml.etree.ElementTree.C14NWriterTarget (write, *, with_comments=False, strip_text=False, rewrite_prefixes=False, qname_aware_tags=None, qname_aware_attrs=None, exclude_attrs=None, exclude_tags=None)

A C14N 2.0@footnote{https://www.w3.org/TR/xml-c14n2/} writer.  Arguments are the
same as for the @ref{c48,,canonicalize()} function.  This class does not build a
tree but translates the callback events directly into a serialised form
using the `write' function.


Added in version 3.8.

@end deffn

@node XMLParser オブジェクト,XMLPullParser オブジェクト,TreeBuilder オブジェクト,リファレンス<6>
@anchor{library/xml etree elementtree elementtree-xmlparser-objects}@anchor{3d35}@anchor{library/xml etree elementtree xmlparser-objects}@anchor{3d36}
@subsubsection XMLParser オブジェクト


@geindex XMLParser (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree XMLParser}@anchor{c49}
@deffn {クラス} xml.etree.ElementTree.XMLParser (*, target=None, encoding=None)

このクラスは、このモジュールの構成要素のうち、低水準のものです。効率的でイベントベースのXMLパースのため、@ref{12c,,xml.parsers.expat} を使用します。@ref{3d37,,feed()} メソッドで XML データをインクリメンタルに受け取り、`target' オブジェクトのコールバックを呼び出すことで、パースイベントをプッシュ API に変換します。`target' が省略された場合、標準の @ref{c4a,,TreeBuilder} が使用されます。 `encoding' @footnote{
XML 出力に含まれるエンコーディング文字列は適切な規格に従っていなければなりません。例えば、"UTF-8" は有効ですが、"UTF8" はそうではありません。@indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} と @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml} を参照してください。
} が指定された場合、このあたいは XML ファイル内で指定されたエンコーディングを上書きします。


バージョン 3.8 で変更: Parameters are now @ref{5a5,,keyword-only}.
The `html' argument is no longer supported.


@geindex close() (xml.etree.ElementTree.XMLParser のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree XMLParser close}@anchor{3d38}
@deffn {メソッド} close ()

パーザへのデータの提供を完了します。構築中に渡される `target' の @code{close()} メソッドを呼び出す結果を返します。既定では、これがトップレベルのドキュメント要素になります。
@end deffn

@geindex feed() (xml.etree.ElementTree.XMLParser のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree XMLParser feed}@anchor{3d37}
@deffn {メソッド} feed (data)

パーザへデータを入力します。 `data' はエンコードされたデータです。
@end deffn

@geindex flush() (xml.etree.ElementTree.XMLParser のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree XMLParser flush}@anchor{576}
@deffn {メソッド} flush ()

Triggers parsing of any previously fed unparsed data, which can be
used to ensure more immediate feedback, in particular with Expat >=2.6.0.
The implementation of @ref{576,,flush()} temporarily disables reparse deferral
with Expat (if currently enabled) and triggers a reparse.
Disabling reparse deferral has security consequences; please see
@ref{579,,xml.parsers.expat.xmlparser.SetReparseDeferralEnabled()} for details.

Note that @ref{576,,flush()} has been backported to some prior releases of
CPython as a security fix.  Check for availability of @ref{576,,flush()}
using @ref{6f9,,hasattr()} if used in code running across a variety of Python
versions.


Added in version 3.13.

@end deffn

@ref{3d37,,XMLParser.feed()} は `target' の @code{start(tag, attrs_dict)} メソッドをそれぞれの開始タグに対して呼び、また @code{end(tag)} メソッドを終了タグに対して呼び、そしてデータを @code{data(data)} メソッドで処理します。サポートされているその他のコールバックメソッドについては、 @ref{c4a,,TreeBuilder} クラスを参照してください。@ref{3d38,,XMLParser.close()} は `target' の @code{close()} メソッドを呼びます。 @ref{c49,,XMLParser} は木構造を構築する以外にも使えます。以下の例では、XML ファイルの最高の深さを数えます。

@example
>>> from xml.etree.ElementTree import XMLParser
>>> class MaxDepth:                     # The target object of the parser
...     maxDepth = 0
...     depth = 0
...     def start(self, tag, attrib):   # Called for each opening tag.
...         self.depth += 1
...         if self.depth > self.maxDepth:
...             self.maxDepth = self.depth
...     def end(self, tag):             # Called for each closing tag.
...         self.depth -= 1
...     def data(self, data):
...         pass            # We do not need to do anything with data.
...     def close(self):    # Called when all data has been parsed.
...         return self.maxDepth
...
>>> target = MaxDepth()
>>> parser = XMLParser(target=target)
>>> exampleXml = """
... <a>
...   <b>
...   </b>
...   <b>
...     <c>
...       <d>
...       </d>
...     </c>
...   </b>
... </a>"""
>>> parser.feed(exampleXml)
>>> parser.close()
4
@end example
@end deffn

@node XMLPullParser オブジェクト,例外<22>,XMLParser オブジェクト,リファレンス<6>
@anchor{library/xml etree elementtree elementtree-xmlpullparser-objects}@anchor{3d39}@anchor{library/xml etree elementtree xmlpullparser-objects}@anchor{3d3a}
@subsubsection XMLPullParser オブジェクト


@geindex XMLPullParser (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser}@anchor{11f5}
@deffn {クラス} xml.etree.ElementTree.XMLPullParser (events=None)

非ブロックアプリケーションに適したプルパーザです。入力側の API は @ref{c49,,XMLParser} のものと似ていますが、コールバックターゲットに呼び出しをプッシュするのではなく、 @ref{11f5,,XMLPullParser} はパースイベントの内部リストを収集し、ユーザーがそこから読み出すことができます。`events' は、呼び出し元に報告するイベントのシーケンスです。サポートされているイベントは、文字列の @code{"start"}, @code{"end"}, @code{"comment"}, @code{"pi"}, @code{"start-ns"}, @code{"end-ns"} ("ns" イベントは、名前空間の詳細情報の取得に使用) です。`events' が省略された場合、 @code{"end"} イベントのみが報告されます。

@geindex feed() (xml.etree.ElementTree.XMLPullParser のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser feed}@anchor{3cf5}
@deffn {メソッド} feed (data)

指定したバイトデータをパーザに与えます。
@end deffn

@geindex flush() (xml.etree.ElementTree.XMLPullParser のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser flush}@anchor{577}
@deffn {メソッド} flush ()

Triggers parsing of any previously fed unparsed data, which can be
used to ensure more immediate feedback, in particular with Expat >=2.6.0.
The implementation of @ref{577,,flush()} temporarily disables reparse deferral
with Expat (if currently enabled) and triggers a reparse.
Disabling reparse deferral has security consequences; please see
@ref{579,,xml.parsers.expat.xmlparser.SetReparseDeferralEnabled()} for details.

Note that @ref{577,,flush()} has been backported to some prior releases of
CPython as a security fix.  Check for availability of @ref{577,,flush()}
using @ref{6f9,,hasattr()} if used in code running across a variety of Python
versions.


Added in version 3.13.

@end deffn

@geindex close() (xml.etree.ElementTree.XMLPullParser のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser close}@anchor{3d3b}
@deffn {メソッド} close ()

パーザに、データストリームが終了したことを伝えます。@ref{3d38,,XMLParser.close()} とは異なり、このメソッドは常に @ref{885,,None} を返します。パーザがクローズした時にまだ帰って来ていないイベントは、まだ @ref{3cf6,,read_events()} で読むことができます。
@end deffn

@geindex read_events() (xml.etree.ElementTree.XMLPullParser のメソッド)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser read_events}@anchor{3cf6}
@deffn {メソッド} read_events ()

Return an iterator over the events which have been encountered in the
data fed to the
parser.  The iterator yields @code{(event, elem)} pairs, where `event' is a
string representing the type of event (e.g. @code{"end"}) and `elem' is the
encountered @ref{363,,Element} object, or other context value as follows.


@itemize *

@item 
@code{start}, @code{end}: the current Element.

@item 
@code{comment}, @code{pi}: the current comment / processing instruction

@item 
@code{start-ns}: a tuple @code{(prefix, uri)} naming the declared namespace
mapping.

@item 
@code{end-ns}: @ref{885,,None} (this may change in a future version)
@end itemize

@ref{3cf6,,read_events()} の前の呼び出しで提供されたイベントは、再度 yield されることはありません。イベントは、イテレータから取得された場合にのみ内部キューから消費されるため、@ref{3cf6,,read_events()} から取得されたイテレータに対して複数の読み出しを並行して反復的に行うと、予期せぬ結果が引き起こされます。
@end deffn

@cartouche
@quotation 注釈 
@ref{11f5,,XMLPullParser}  は "start" イベントを発行した時に開始タグの文字 ">" が現れたことだけを保証します。そのため、属性は定義されますが、その時点ではテキストの内容も tail 属性も定義されていません。子要素にもそれが存在する、しないにかかわらず同じ物が適用されます。

全部揃った要素が必要ならば、"end" イベントを探してください。
@end quotation
@end cartouche


Added in version 3.4.



バージョン 3.8 で変更: イベント @code{comment}, @code{pi} が追加されました。

@end deffn

@node 例外<22>,,XMLPullParser オブジェクト,リファレンス<6>
@anchor{library/xml etree elementtree exceptions}@anchor{3d3c}
@subsubsection 例外


@geindex ParseError (xml.etree.ElementTree のクラス)
@anchor{library/xml etree elementtree xml etree ElementTree ParseError}@anchor{148f}
@deffn {クラス} xml.etree.ElementTree.ParseError

解析に失敗した時、このモジュールの様々なメソッドから送出される XML 解析エラーです。この例外のインスタンスが表す文字列は、ユーザフレンドリなメッセージを含んでいます。その他に、以下の属性も利用できます:

@geindex code (xml.etree.ElementTree.ParseError の属性)
@anchor{library/xml etree elementtree xml etree ElementTree ParseError code}@anchor{3d3d}
@deffn {の属性} code

expat パーザからの数値エラーコードです。エラーコードの一覧とそれらの意味については、@ref{12c,,xml.parsers.expat} のドキュメントを参照してください。
@end deffn

@geindex position (xml.etree.ElementTree.ParseError の属性)
@anchor{library/xml etree elementtree xml etree ElementTree ParseError position}@anchor{3d3e}
@deffn {の属性} position

エラーが発生した場所を示す `line' と `column' 番号のタプルです。
@end deffn
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml dom --- ドキュメントオブジェクトモデル API,xml dom minidom --- 最小限の DOM の実装,xml etree ElementTree --- ElementTree XML API,構造化マークアップツール
@anchor{library/xml dom doc}@anchor{3d3f}@anchor{library/xml dom module-xml dom}@anchor{127}@anchor{library/xml dom translation-repo}@anchor{3d40}@anchor{library/xml dom xml-dom-the-document-object-model-api}@anchor{3d41}
@subsection @code{xml.dom} --- ドキュメントオブジェクトモデル API


@geindex module; xml.dom

`ソースコード:' Lib/xml/dom/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/dom/__init__.py}


__________________________________________________________________


文書オブジェクトモデル (Document Object Model)、すなわち "DOM" は、ワールドワイドウェブコンソーシアム (World Wide Web Consortium, W3C) による、XML ドキュメントにアクセスしたり変更を加えたりするための、プログラミング言語間共通の API です。DOM 実装によって、XML ドキュメントはツリー構造として表現されます。また、クライアントコード側でツリー構造をゼロから構築できるようになります。さらに、前述の構造に対して、よく知られたインターフェースをもつ一連のオブジェクトを通したアクセス手段も提供します。

DOM はランダムアクセスを行うアプリケーションで非常に有用です。SAX では、一度に閲覧することができるのはドキュメントのほんの一部分です。ある SAX 要素に注目している際には、別の要素をアクセスすることはできません。またテキストノードに注目しているときには、その中に入っている要素をアクセスすることができません。SAX によるアプリケーションを書くときには、プログラムがドキュメント内のどこを処理しているのかを追跡するよう、コードのどこかに記述する必要があります。SAX 自体がその作業を行ってくれることはありません。さらに、XML ドキュメントに対する先読み (look ahead) が必要だとすると不運なことになります。

アプリケーションによっては、ツリーにアクセスできなければイベント駆動モデルを実現できません。もちろん、何らかのツリーを SAX イベントに応じて自分で構築することもできるでしょうが、DOM ではそのようなコードを書かなくてもよくなります。DOM は XML データに対する標準的なツリー表現なのです。

文書オブジェクトモデルは、W3C によっていくつかの段階、W3C の用語で言えば "レベル (level)" で定義されています。Python においては、DOM API への対応付けは実質的には DOM レベル 2 勧告に基づいています。

@c What if your needs are somewhere between SAX and the DOM?  Perhaps
@c you cannot afford to load the entire tree in memory but you find the
@c SAX model somewhat cumbersome and low-level.  There is also a module
@c called xml.dom.pulldom that allows you to build trees of only the
@c parts of a document that you need structured access to.  It also has
@c features that allow you to find your way around the DOM.
@c See http://www.prescod.net/python/pulldom

DOM アプリケーションは、普通は XML を DOM に解析するところから始まります。どのようにして解析を行うかについては DOM レベル 1 では全くカバーしておらず、レベル 2 では限定的な改良だけが行われました: レベル 2 では @code{Document} を生成するメソッドを提供する @code{DOMImplementation} オブジェクトクラスがありますが、実装に依存しない方法で XML リーダ(reader)/パーザ(parser)/文書ビルダ (Document builder) にアクセスする方法はありません。また、既存の @code{Document} オブジェクトなしにこれらのメソッドにアクセスするような、よく定義された方法もありません。 Python では、各々の DOM 実装で @ref{3d42,,getDOMImplementation()} が定義されているはずです。 DOM レベル 3 ではロード(Load)/ストア(Store) 仕様が追加され、リーダのインターフェースにを定義していますが、Python 標準ライブラリではまだ利用することができません。

DOM 文書オブジェクトを生成したら、そのプロパティとメソッドを使って XML 文書の一部にアクセスできます。これらのプロパティは DOM 仕様で定義されています; 本リファレンスマニュアルでは、Python において DOM 仕様がどのように解釈されているかを記述しています。

W3C から提供されている仕様は、 DOM API を Java、ECMAScript、および OMG IDL で定義しています。ここで定義されている Python での対応づけは、大部分がこの仕様の IDL 版に基づいていますが、厳密な準拠は必要とされていません (実装で IDL の厳密な対応付けをサポートするのは自由ですが)。API への対応付けに関する詳細な議論は @ref{3d43,,適合性} を参照してください。


@subsubheading 参考



@table @asis

@item Document Object Model (DOM) Level 2 Specification@footnote{https://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/}

Python DOM API が準拠している W3C 勧告。

@item Document Object Model (DOM) Level 1 Specification@footnote{https://www.w3.org/TR/REC-DOM-Level-1/}

@ref{128,,xml.dom.minidom} でサポートされている W3C の DOM に関する勧告。

@item Python Language Mapping Specification@footnote{https://www.omg.org/spec/PYTH/1.2/PDF}

このドキュメントでは OMG IDL から Python への対応付けを記述しています。
@end table


@menu
* モジュールコンテンツ: モジュールコンテンツ<4>. 
* DOM 内のオブジェクト:: 
* 適合性:: 

@end menu

@node モジュールコンテンツ<4>,DOM 内のオブジェクト,,xml dom --- ドキュメントオブジェクトモデル API
@anchor{library/xml dom module-contents}@anchor{3d44}
@subsubsection モジュールコンテンツ


The @code{xml.dom} contains the following functions:

@geindex registerDOMImplementation() (xml.dom モジュール)
@anchor{library/xml dom xml dom registerDOMImplementation}@anchor{3d45}
@deffn {の関数} xml.dom.registerDOMImplementation (name, factory)

ファクトリ関数 (factory function) `factory' を名前 `name' で登録します。ファクトリ関数は @code{DOMImplementation} インターフェースを実装するオブジェクトを返さなければなりません。特定の実装 (例えば実装が何らかのカスタマイズをサポートしている場合) に適切となるように、ファクトリ関数は毎回同じオブジェクトを返したり、呼び出しごとに新しいオブジェクトを返したりすることが出来ます。
@end deffn

@geindex getDOMImplementation() (xml.dom モジュール)
@anchor{library/xml dom xml dom getDOMImplementation}@anchor{3d42}
@deffn {の関数} xml.dom.getDOMImplementation (name=None, features=())

適切な DOM 実装を返します。`name' は、よく知られた DOM 実装のモジュール名か、 @code{None} になります。 @code{None} でない場合、対応するモジュールを import して、import が成功した場合 @code{DOMImplementation} オブジェクトを返します。 `name' が与えられておらず、環境変数 
@geindex PYTHON_DOM
@geindex 環境変数; PYTHON_DOM
@code{PYTHON_DOM} が設定されていた場合、 DOM 実装を見つけるのに環境変数が使われます。

`name' が与えられない場合、利用可能な実装を調べて、指定された機能 (feature) セットを持つものを探します。実装が見つからなければ @ref{65b,,ImportError} を送出します。 `features' のリストは @code{(feature, version)} のペアからなるシーケンスで、利用可能な @code{DOMImplementation} オブジェクトの @code{hasFeature()} メソッドに渡されます。
@end deffn

いくつかの便利な定数も提供されています:

@geindex EMPTY_NAMESPACE (xml.dom モジュール)
@anchor{library/xml dom xml dom EMPTY_NAMESPACE}@anchor{3d46}
@deffn {データ} xml.dom.EMPTY_NAMESPACE

DOM 内のノードに名前空間が何も関連づけられていないことを示すために使われる値です。この値は通常、ノードの @code{namespaceURI} の値として見つかったり、名前空間特有のメソッドに対する `namespaceURI' パラメタとして使われます。
@end deffn

@geindex XML_NAMESPACE (xml.dom モジュール)
@anchor{library/xml dom xml dom XML_NAMESPACE}@anchor{3d47}
@deffn {データ} xml.dom.XML_NAMESPACE

Namespaces in XML@footnote{https://www.w3.org/TR/REC-xml-names/} (4 節) で定義されている、予約済みプレフィクス (reserved prefix) @code{xml} に関連付けられた名前空間 URI です。
@end deffn

@geindex XMLNS_NAMESPACE (xml.dom モジュール)
@anchor{library/xml dom xml dom XMLNS_NAMESPACE}@anchor{3d48}
@deffn {データ} xml.dom.XMLNS_NAMESPACE

Document Object Model (DOM) Level 2 Core Specification@footnote{https://www.w3.org/TR/DOM-Level-2-Core/core.html} (1.1.8 節) で定義されている、名前空間宣言への名前空間 URI です。
@end deffn

@geindex XHTML_NAMESPACE (xml.dom モジュール)
@anchor{library/xml dom xml dom XHTML_NAMESPACE}@anchor{3d49}
@deffn {データ} xml.dom.XHTML_NAMESPACE

XHTML 1.0: The Extensible HyperText Markup Language@footnote{https://www.w3.org/TR/xhtml1/} (3.1.1 節) で定義されている、XHTML 名前空間 URI です。
@end deffn

In addition, @code{xml.dom} contains a base @code{Node} class and the DOM
exception classes.  The @code{Node} class provided by this module does not
implement any of the methods or attributes defined by the DOM specification;
concrete DOM implementations must provide those.  The @code{Node} class
provided as part of this module does provide the constants used for the
@code{nodeType} attribute on concrete @code{Node} objects; they are located
within the class rather than at the module level to conform with the DOM
specifications.

@c Should the Node documentation go here?

@node DOM 内のオブジェクト,適合性,モジュールコンテンツ<4>,xml dom --- ドキュメントオブジェクトモデル API
@anchor{library/xml dom dom-objects}@anchor{3d4a}@anchor{library/xml dom objects-in-the-dom}@anchor{3d4b}
@subsubsection DOM 内のオブジェクト


DOM について最も明確に限定しているドキュメントは W3C による DOM 仕様です。

DOM 属性は単純な文字列としてだけではなく、ノードとして操作されるかもしれないので注意してください。とはいえ、そうしなければならない場合はかなり稀なので、今のところ記述されていません。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インターフェース

@tab

節

@tab

目的

@item

@code{DOMImplementation}

@tab

@ref{3d4c,,DOMImplementation オブジェクト}

@tab

根底にある実装へのインターフェース。

@item

@code{Node}

@tab

@ref{3d4d,,Node オブジェクト}

@tab

ドキュメント内の大部分のオブジェクトに対する基底インターフェース。

@item

@code{NodeList}

@tab

@ref{23ab,,NodeList オブジェクト}

@tab

ノード列に対するインターフェース。

@item

@code{DocumentType}

@tab

@ref{3d4e,,DocumentType オブジェクト}

@tab

ドキュメントの処理に必要な宣言についての情報。

@item

@code{Document}

@tab

@ref{3d4f,,Document オブジェクト}

@tab

ドキュメント全体を表現するオブジェクト。

@item

@code{Element}

@tab

@ref{3d50,,Element オブジェクト}

@tab

ドキュメント階層内の要素ノード。

@item

@code{Attr}

@tab

@ref{3d51,,Attr オブジェクト}

@tab

要素ノード上の属性値ノード。

@item

@code{Comment}

@tab

@ref{3d52,,Comment オブジェクト}

@tab

ソースドキュメント内のコメント表現。

@item

@code{Text}

@tab

@ref{3d53,,Text オブジェクトおよび CDATASection オブジェクト}

@tab

ドキュメント内のテキスト記述を含むノード。

@item

@code{ProcessingInstruction}

@tab

@ref{3d54,,ProcessingInstruction オブジェクト}

@tab

処理命令 (processing instruction) 表現。

@end multitable


さらに追加の節として、Python で DOM を利用するために定義されている例外について記述しています。

@menu
* DOMImplementation オブジェクト:: 
* Node オブジェクト:: 
* NodeList オブジェクト:: 
* DocumentType オブジェクト:: 
* Document オブジェクト:: 
* Element オブジェクト: Element オブジェクト<2>. 
* Attr オブジェクト:: 
* NamedNodeMap Objects:: 
* Comment オブジェクト:: 
* Text オブジェクトおよび CDATASection オブジェクト:: 
* ProcessingInstruction オブジェクト:: 
* 例外: 例外<23>. 

@end menu

@node DOMImplementation オブジェクト,Node オブジェクト,,DOM 内のオブジェクト
@anchor{library/xml dom dom-implementation-objects}@anchor{3d4c}@anchor{library/xml dom domimplementation-objects}@anchor{3d55}
@subsubsection DOMImplementation オブジェクト


@code{DOMImplementation} インターフェースは、利用している DOM 実装において特定の機能が利用可能かどうかを決定するための方法をアプリケーションに提供します。DOM レベル 2 では、 @code{DOMImplementation} を使って新たな @code{Document} オブジェクトや @code{DocumentType} オブジェクトを生成する機能も追加しています。

@geindex hasFeature() (xml.dom.DOMImplementation のメソッド)
@anchor{library/xml dom xml dom DOMImplementation hasFeature}@anchor{3d56}
@deffn {メソッド} DOMImplementation.hasFeature (feature, version)

機能名 `feature' とバージョン番号 `version' で識別される機能（feature）が実装されていれば @code{True} を返します。
@end deffn

@geindex createDocument() (xml.dom.DOMImplementation のメソッド)
@anchor{library/xml dom xml dom DOMImplementation createDocument}@anchor{3d57}
@deffn {メソッド} DOMImplementation.createDocument (namespaceUri, qualifiedName, doctype)

新たな(DOMのスーパークラスである) @code{Document} クラスのオブジェクトを返します。このクラスは `namespaceUri' と `qualifiedName' が設定された子クラス @code{Element} のオブジェクトを所有しています。 `doctype' は @ref{3d58,,createDocumentType()} によって生成された @code{DocumentType} クラスのオブジェクト、または @code{None} である必要があります。 Python DOM APIでは、子クラスである @code{Element} を作成しないことを示すために、はじめの２つの引数を @code{None} に設定することができます。
@end deffn

@geindex createDocumentType() (xml.dom.DOMImplementation のメソッド)
@anchor{library/xml dom xml dom DOMImplementation createDocumentType}@anchor{3d58}
@deffn {メソッド} DOMImplementation.createDocumentType (qualifiedName, publicId, systemId)

新たな @code{DocumentType} クラスのオブジェクトを返します。このオブジェクトは `qualifiedName' 、 `publicId' 、そして `systemId' 文字列をふくんでおり、XML文書の形式情報を表現しています。
@end deffn

@node Node オブジェクト,NodeList オブジェクト,DOMImplementation オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom dom-node-objects}@anchor{3d4d}@anchor{library/xml dom node-objects}@anchor{3d59}
@subsubsection Node オブジェクト


XML 文書の全ての構成要素は @code{Node} のサブクラスです。

@geindex nodeType (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node nodeType}@anchor{3d5a}
@deffn {の属性} Node.nodeType

ノード (node) の型を表現する整数値です。型に対応する以下のシンボル定数: @code{ELEMENT_NODE} 、 @code{ATTRIBUTE_NODE} 、 @code{TEXT_NODE} 、 @code{CDATA_SECTION_NODE} 、 @code{ENTITY_NODE} 、 @code{PROCESSING_INSTRUCTION_NODE} 、 @code{COMMENT_NODE} 、 @code{DOCUMENT_NODE} 、 @code{DOCUMENT_TYPE_NODE} 、 @code{NOTATION_NODE} 、が @code{Node} オブジェクトで定義されています。読み出し専用の属性です。
@end deffn

@geindex parentNode (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node parentNode}@anchor{3d5b}
@deffn {の属性} Node.parentNode

現在のノードの親ノードか、文書ノードの場合には @code{None} になります。この値は常に @code{Node} オブジェクトか @code{None} になります。 @code{Element} ノードの場合、この値はルート要素 (root element) の場合を除き親要素 (parent element) となり、ルート要素の場合には @code{Document} オブジェクトとなります。 @code{Attr} ノードの場合、この値は常に @code{None} となります。読み出し専用の属性です。
@end deffn

@geindex attributes (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node attributes}@anchor{3d5c}
@deffn {の属性} Node.attributes

属性オブジェクトの @code{NamedNodeMap} です。要素だけがこの属性に実際の値を持ちます; その他のオブジェクトでは、この属性を @code{None} にします。読み出し専用の属性です。
@end deffn

@geindex previousSibling (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node previousSibling}@anchor{3d5d}
@deffn {の属性} Node.previousSibling

このノードと同じ親ノードを持ち、直前にくるノードです。例えば、`self' 要素の開始タグの直前にくる終了タグを持つ要素です。もちろん、XML 文書は要素だけで構成されているだけではないので、直前にくる兄弟関係にある要素 (sibling) はテキストやコメント、その他になる可能性があります。このノードが親ノードにおける先頭の子ノードである場合、属性値は @code{None} になります。読み出し専用の属性です。
@end deffn

@geindex nextSibling (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node nextSibling}@anchor{3d5e}
@deffn {の属性} Node.nextSibling

このノードと同じ親ノードを持ち、直後にくるノードです。例えば、 @ref{3d5d,,previousSibling} も参照してください。このノードが親ノードにおける末尾の子ノードである場合、属性値は @code{None} になります。読み出し専用の属性です。
@end deffn

@geindex childNodes (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node childNodes}@anchor{3d5f}
@deffn {の属性} Node.childNodes

このノード内に収められているノードからなるリストです。読み出し専用の属性です。
@end deffn

@geindex firstChild (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node firstChild}@anchor{3d60}
@deffn {の属性} Node.firstChild

このノードに子ノードがある場合、その先頭のノードです。そうでない場合 @code{None} になります。読み出し専用の属性です。
@end deffn

@geindex lastChild (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node lastChild}@anchor{3d61}
@deffn {の属性} Node.lastChild

このノードに子ノードがある場合、その末尾のノードです。そうでない場合 @code{None} になります。読み出し専用の属性です。
@end deffn

@geindex localName (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node localName}@anchor{3d62}
@deffn {の属性} Node.localName

@code{tagName} にコロンがあれば、コロン以降の部分に、なければ @code{tagName} 全体になります。値は文字列です。
@end deffn

@geindex prefix (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node prefix}@anchor{3d63}
@deffn {の属性} Node.prefix

@code{tagName} のコロンがあれば、コロン以前の部分に、なければ空文字列になります。値は文字列か、 @code{None} になります。
@end deffn

@geindex namespaceURI (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node namespaceURI}@anchor{3d64}
@deffn {の属性} Node.namespaceURI

要素名に関連付けられた名前空間です。文字列か @code{None} になります。読み出し専用の属性です。
@end deffn

@geindex nodeName (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node nodeName}@anchor{3d65}
@deffn {の属性} Node.nodeName

この属性はノード型ごとに異なる意味を持ちます。その詳細は DOM 仕様を参照してください。この属性で得られることになる情報は、全てのノード型では @code{tagName} 、属性では @code{name} プロパティといったように、常に他のプロパティで得ることができます。全てのノード型で、この属性の値は文字列か @code{None} になります。読み出し専用の属性です。
@end deffn

@geindex nodeValue (xml.dom.Node の属性)
@anchor{library/xml dom xml dom Node nodeValue}@anchor{3d66}
@deffn {の属性} Node.nodeValue

この属性はノード型ごとに異なる意味を持ちます。その詳細は DOM 仕様を参照してください。その状況は @ref{3d65,,nodeName} と似ています。この属性の値は文字列または @code{None} になります。
@end deffn

@geindex hasAttributes() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node hasAttributes}@anchor{3d67}
@deffn {メソッド} Node.hasAttributes ()

ノードが何らかの属性を持っている場合に @code{True} を返します。
@end deffn

@geindex hasChildNodes() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node hasChildNodes}@anchor{3d68}
@deffn {メソッド} Node.hasChildNodes ()

ノードが何らかの子ノードを持っている場合に @code{True} を返します。
@end deffn

@geindex isSameNode() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node isSameNode}@anchor{3d69}
@deffn {メソッド} Node.isSameNode (other)

`other' がこのノードと同じノードを参照している場合に @code{True} を返します。このメソッドは、何らかのプロキシ (proxy) 機構を利用するような DOM 実装で特に便利です (一つ以上のオブジェクトが同じノードを参照するかもしれないからです)。

@cartouche
@quotation 注釈 
このメソッドは DOM レベル 3 API の提案に基づいたもので、まだ "ワーキングドラフト(working draft)" の段階です。しかし、このインターフェースには異論は出ないと考えられます。W3C による変更があっても、必ずしも Python DOM インターフェースにおけるこのメソッドに影響するとは限りません (ただしこのメソッドに対する何らかの新しい W3C API もサポートされるかもしれません)。
@end quotation
@end cartouche
@end deffn

@geindex appendChild() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node appendChild}@anchor{3d6a}
@deffn {メソッド} Node.appendChild (newChild)

現在のノードの子ノードリストの末尾に新たな子ノードを追加し、`newChild' を返します。もしノードが既にツリーにあれば、最初に削除されます。
@end deffn

@geindex insertBefore() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node insertBefore}@anchor{3d6b}
@deffn {メソッド} Node.insertBefore (newChild, refChild)

新たな子ノードを既存の子ノードの前に挿入します。 `refChild' は現在のノードの子ノードである場合に限られます; そうでない場合、 @ref{2ec,,ValueError} が送出されます。 `newChild' が返されます。もし `refChild' が @code{None} なら、 `newChild' を子ノードリストの最後に挿入します。
@end deffn

@geindex removeChild() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node removeChild}@anchor{3d6c}
@deffn {メソッド} Node.removeChild (oldChild)

子ノードを削除します。 `oldChild' はこのノードの子ノードでなければなりません。そうでない場合、 @ref{2ec,,ValueError} が送出されます。成功した場合 `oldChild' が返されます。 `oldChild' をそれ以降使わない場合、 @code{unlink()} メソッドを呼び出さなければなりません。
@end deffn

@geindex replaceChild() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node replaceChild}@anchor{3d6d}
@deffn {メソッド} Node.replaceChild (newChild, oldChild)

既存のノードと新たなノードを置き換えます。この操作は `oldChild' が現在のノードの子ノードである場合に限られます; そうでない場合、 @ref{2ec,,ValueError} が送出されます。
@end deffn

@geindex normalize() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node normalize}@anchor{3d6e}
@deffn {メソッド} Node.normalize ()

一続きのテキスト全体を一個の @code{Text} インスタンスとして保存するために隣接するテキストノードを結合します。これにより、多くのアプリケーションで DOM ツリーからのテキスト処理が簡単になります。
@end deffn

@geindex cloneNode() (xml.dom.Node のメソッド)
@anchor{library/xml dom xml dom Node cloneNode}@anchor{3d6f}
@deffn {メソッド} Node.cloneNode (deep)

このノードを複製 (clone) します。`deep' を設定すると、子ノードも同様に複製することを意味します。複製されたノードを返します。
@end deffn

@node NodeList オブジェクト,DocumentType オブジェクト,Node オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom dom-nodelist-objects}@anchor{23ab}@anchor{library/xml dom nodelist-objects}@anchor{3d70}
@subsubsection NodeList オブジェクト


@code{NodeList} はノードのシーケンスを表現します。
これらのオブジェクトは DOM コア勧告 (DOM Core recommendation) において、二通りに使われています: @code{Element} オブジェクトでは、子ノードのリストを提供するのに @code{NodeList} を利用します。
また、このインターフェースにおける @code{Node} の @code{getElementsByTagName()} および @code{getElementsByTagNameNS()} メソッドは、クエリに対する結果を表現するのに @code{NodeList} を利用します。

DOM レベル 2 勧告では、これらのオブジェクトに対し、以下のようにメソッドを一つ、属性を一つ定義しています。

@geindex item() (xml.dom.NodeList のメソッド)
@anchor{library/xml dom xml dom NodeList item}@anchor{3d71}
@deffn {メソッド} NodeList.item (i)

存在する場合シークエンスの `i' 番目の要素を、そうでない場合 @code{None} を返します。`i' は 0 未満やシークエンスの長さ以上であってはなりません。
@end deffn

@geindex length (xml.dom.NodeList の属性)
@anchor{library/xml dom xml dom NodeList length}@anchor{3d72}
@deffn {の属性} NodeList.length

シーケンス中のノードの数です。
@end deffn

この他に、Python の DOM インターフェースでは、 @code{NodeList} オブジェクトを Python のシーケンスとして使えるようにするサポートが追加されていることが必要です。 @code{NodeList}  の実装では、全て @ref{178f,,__len__()} と @ref{588,,__getitem__()} をサポートしなければなりません; このサポートにより、 @ref{34a,,for}  文内で @code{NodeList} にわたる繰り返しと、組み込み関数 @ref{840,,len()} の適切なサポートができるようになります。

DOM 実装が文書の変更をサポートしている場合、 @code{NodeList}  の実装でも @ref{14e3,,__setitem__()} および @ref{14e4,,__delitem__()} メソッドをサポートしなければなりません。

@node DocumentType オブジェクト,Document オブジェクト,NodeList オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom documenttype-objects}@anchor{3d73}@anchor{library/xml dom dom-documenttype-objects}@anchor{3d4e}
@subsubsection DocumentType オブジェクト


文書で宣言されている記法 (notation) やエンティティ (entity) に関する (外部サブセット(external subset) がパーザから利用でき、情報を提供できる場合にはそれも含めた) 情報は、 @code{DocumentType} オブジェクトから手に入れることができます。文書の @code{DocumentType} は、 @code{Document} オブジェクトの @code{doctype} 属性で入手することができます; 文書の @code{DOCTYPE} 宣言がない場合、文書の @code{doctype} 属性は、このインターフェースを持つインスタンスの代わりに @code{None} に設定されます。

@code{DocumentType} は @code{Node} を特殊化したもので、以下の属性を加えています:

@geindex publicId (xml.dom.DocumentType の属性)
@anchor{library/xml dom xml dom DocumentType publicId}@anchor{3d74}
@deffn {の属性} DocumentType.publicId

文書型定義 (document type definition) の外部サブセットに対する公開識別子 (public identifier) です。文字列または @code{None} になります。
@end deffn

@geindex systemId (xml.dom.DocumentType の属性)
@anchor{library/xml dom xml dom DocumentType systemId}@anchor{3d75}
@deffn {の属性} DocumentType.systemId

文書型定義 (document type definition) の外部サブセットに対するシステム識別子 (system identifier) です。文字列の URI または @code{None} になります。
@end deffn

@geindex internalSubset (xml.dom.DocumentType の属性)
@anchor{library/xml dom xml dom DocumentType internalSubset}@anchor{3d76}
@deffn {の属性} DocumentType.internalSubset

ドキュメントの完全な内部サブセットを与える文字列です。サブセットを囲むブラケットは含みません。ドキュメントが内部サブセットを持たない場合、この値は @code{None} です。
@end deffn

@geindex name (xml.dom.DocumentType の属性)
@anchor{library/xml dom xml dom DocumentType name}@anchor{3d77}
@deffn {の属性} DocumentType.name

@code{DOCTYPE} 宣言でルート要素の名前が与えられている場合、その値になります。
@end deffn

@geindex entities (xml.dom.DocumentType の属性)
@anchor{library/xml dom xml dom DocumentType entities}@anchor{3d78}
@deffn {の属性} DocumentType.entities

外部エンティティの定義を与える @code{NamedNodeMap} です。複数回定義されているエンティティに対しては、最初の定義だけが提供されます (その他は XML 勧告での要求仕様によって無視されます)。パーザによって情報が提供されないか、エンティティが定義されていない場合には、この値は @code{None} になることがあります。
@end deffn

@geindex notations (xml.dom.DocumentType の属性)
@anchor{library/xml dom xml dom DocumentType notations}@anchor{3d79}
@deffn {の属性} DocumentType.notations

記法の定義を与える @code{NamedNodeMap} です。複数回定義されている記法名に対しては、最初の定義だけが提供されます (その他は XML 勧告での要求仕様によって無視されます)。パーザによって情報が提供されないか、エンティティが定義されていない場合には、この値は @code{None} になることがあります。
@end deffn

@node Document オブジェクト,Element オブジェクト<2>,DocumentType オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom document-objects}@anchor{3d7a}@anchor{library/xml dom dom-document-objects}@anchor{3d4f}
@subsubsection Document オブジェクト


@code{Document} は XML ドキュメント全体を表現し、その構成要素である要素、属性、処理命令、コメント等を持ちます。 @code{Document} は @code{Node} からプロパティを継承していることを思い出してください。

@geindex documentElement (xml.dom.Document の属性)
@anchor{library/xml dom xml dom Document documentElement}@anchor{1780}
@deffn {の属性} Document.documentElement

ドキュメントの唯一無二のルート要素です。
@end deffn

@geindex createElement() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document createElement}@anchor{3d7b}
@deffn {メソッド} Document.createElement (tagName)

新たな要素ノードを生成して返します。要素は、生成された時点ではドキュメント内に挿入されません。 @code{insertBefore()} や @code{appendChild()} のような他のメソッドの一つを使って明示的に挿入を行う必要があります。
@end deffn

@geindex createElementNS() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document createElementNS}@anchor{3d7c}
@deffn {メソッド} Document.createElementNS (namespaceURI, tagName)

名前空間を伴う新たな要素ノードを生成して返します。 `tagName' には接頭辞 (prefix) があってもかまいません。要素は、生成された時点では文書内に挿入されません。 @code{insertBefore()} や @code{appendChild()} のような他のメソッドの一つを使って明示的に挿入を行う必要があります。
@end deffn

@geindex createTextNode() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document createTextNode}@anchor{3d7d}
@deffn {メソッド} Document.createTextNode (data)

引数として渡されたデータの入ったテキストノードを生成して返します。他の生成 (create) メソッドと同じく、このメソッドは生成されたノードをツリーに挿入しません。
@end deffn

@geindex createComment() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document createComment}@anchor{3d7e}
@deffn {メソッド} Document.createComment (data)

引数として渡されたデータの入ったコメントノードを生成して返します。他の生成 (create) メソッドと同じく、このメソッドは生成されたノードをツリーに挿入しません。
@end deffn

@geindex createProcessingInstruction() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document createProcessingInstruction}@anchor{3d7f}
@deffn {メソッド} Document.createProcessingInstruction (target, data)

引数として渡された `target' および `data' の入った処理命令ノードを生成して返します。他の生成 (create) メソッドと同じく、このメソッドは生成されたノードをツリーに挿入しません。
@end deffn

@geindex createAttribute() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document createAttribute}@anchor{3d80}
@deffn {メソッド} Document.createAttribute (name)

属性ノードを生成して返します。このメソッドは属性ノードを特定の要素に関連づけることはしません。新たに生成された属性インスタンスを使うには、適切な @code{Element} オブジェクトの @code{setAttributeNode()} を使わなければなりません。
@end deffn

@geindex createAttributeNS() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document createAttributeNS}@anchor{3d81}
@deffn {メソッド} Document.createAttributeNS (namespaceURI, qualifiedName)

名前空間を伴う新たな属性ノードを生成して返します。 `tagName' には接頭辞 (prefix) があってもかまいません。このメソッドは属性ノードを特定の要素に関連づけることはしません。新たに生成された属性インスタンスを使うには、適切な @code{Element} オブジェクトの @code{setAttributeNode()} を使わなければなりません。
@end deffn

@geindex getElementsByTagName() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document getElementsByTagName}@anchor{3d82}
@deffn {メソッド} Document.getElementsByTagName (tagName)

全ての下位要素 (直接の子要素、子要素の子要素等) から特定の要素型名を持つものを検索します。
@end deffn

@geindex getElementsByTagNameNS() (xml.dom.Document のメソッド)
@anchor{library/xml dom xml dom Document getElementsByTagNameNS}@anchor{3d83}
@deffn {メソッド} Document.getElementsByTagNameNS (namespaceURI, localName)

全ての下位要素 (直接の子要素、子要素の子要素等) から特定の名前空間 URI とローカル名 (local name) を持つものを検索します。ローカル名は名前空間における接頭辞以降の部分です。
@end deffn

@node Element オブジェクト<2>,Attr オブジェクト,Document オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom dom-element-objects}@anchor{3d50}@anchor{library/xml dom element-objects}@anchor{3d84}
@subsubsection Element オブジェクト


@code{Element} は @code{Node} のサブクラスです。このため @code{Node} クラスの全ての属性を継承します。

@geindex tagName (xml.dom.Element の属性)
@anchor{library/xml dom xml dom Element tagName}@anchor{3d85}
@deffn {の属性} Element.tagName

要素型名です。名前空間使用の文書では、要素型名中にコロンがあるかもしれません。値は文字列です。
@end deffn

@geindex getElementsByTagName() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element getElementsByTagName}@anchor{3d86}
@deffn {メソッド} Element.getElementsByTagName (tagName)

@code{Document} クラス内における同名のメソッドと同じです。
@end deffn

@geindex getElementsByTagNameNS() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element getElementsByTagNameNS}@anchor{3d87}
@deffn {メソッド} Element.getElementsByTagNameNS (namespaceURI, localName)

@code{Document} クラス内における同名のメソッドと同じです。
@end deffn

@geindex hasAttribute() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element hasAttribute}@anchor{3d88}
@deffn {メソッド} Element.hasAttribute (name)

指定要素に `name' で渡した名前の属性が存在していれば @code{True} を返します。
@end deffn

@geindex hasAttributeNS() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element hasAttributeNS}@anchor{3d89}
@deffn {メソッド} Element.hasAttributeNS (namespaceURI, localName)

指定要素に `namespaceURI' と `localName' で指定した名前の属性が存在していれば @code{True} を返します。
@end deffn

@geindex getAttribute() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element getAttribute}@anchor{3d8a}
@deffn {メソッド} Element.getAttribute (name)

`name' で指定した属性の値を文字列として返します。もし、属性が存在しない、もしくは属性に値が設定されていない場合、空の文字列が返されます。
@end deffn

@geindex getAttributeNode() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element getAttributeNode}@anchor{3d8b}
@deffn {メソッド} Element.getAttributeNode (attrname)

`attrname' で指定された属性の @code{Attr} ノードを返します。
@end deffn

@geindex getAttributeNS() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element getAttributeNS}@anchor{3d8c}
@deffn {メソッド} Element.getAttributeNS (namespaceURI, localName)

`namespaceURI' と `localName' によって指定した属性の値を文字列として返します。もし、属性が存在しない、もしくは属性に値が設定されていない場合、空の文字列が返されます。
@end deffn

@geindex getAttributeNodeNS() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element getAttributeNodeNS}@anchor{3d8d}
@deffn {メソッド} Element.getAttributeNodeNS (namespaceURI, localName)

指定した `namespaceURI' および `localName' を持つ属性値をノードとして返します。
@end deffn

@geindex removeAttribute() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element removeAttribute}@anchor{3d8e}
@deffn {メソッド} Element.removeAttribute (name)

名前で指定された属性を削除します。該当する属性がない場合、@ref{3d8f,,NotFoundErr} が送出されます。
@end deffn

@geindex removeAttributeNode() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element removeAttributeNode}@anchor{3d90}
@deffn {メソッド} Element.removeAttributeNode (oldAttr)

`oldAttr' が属性リストにある場合、削除して返します。 `oldAttr' が存在しない場合、 @ref{3d8f,,NotFoundErr} が送出されます。
@end deffn

@geindex removeAttributeNS() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element removeAttributeNS}@anchor{3d91}
@deffn {メソッド} Element.removeAttributeNS (namespaceURI, localName)

名前で指定された属性を削除します。このメソッドは `qname' ではなく `localName' を使うので注意してください。該当する属性がなくても例外は送出されません。
@end deffn

@geindex setAttribute() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element setAttribute}@anchor{3d92}
@deffn {メソッド} Element.setAttribute (name, value)

文字列を使って属性値を設定します。
@end deffn

@geindex setAttributeNode() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element setAttributeNode}@anchor{3d93}
@deffn {メソッド} Element.setAttributeNode (newAttr)

新たな属性ノードを要素に追加します。 @code{name} 属性が既存の属性に一致した場合、必要に応じて属性を置換します。置換が行われると古い属性ノードが返されます。 `newAttr' がすでに使われていれば、 @ref{3d94,,InuseAttributeErr} が送出されます。
@end deffn

@geindex setAttributeNodeNS() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element setAttributeNodeNS}@anchor{3d95}
@deffn {メソッド} Element.setAttributeNodeNS (newAttr)

新たな属性ノードを要素に追加します。 @code{namespaceURI} および @code{localName} 属性が既存の属性に一致した場合、必要に応じて属性を置き換えます。置換が生じると、古い属性ノードが返されます。 `newAttr' がすでに使われていれば、 @ref{3d94,,InuseAttributeErr} が送出されます。
@end deffn

@geindex setAttributeNS() (xml.dom.Element のメソッド)
@anchor{library/xml dom xml dom Element setAttributeNS}@anchor{3d96}
@deffn {メソッド} Element.setAttributeNS (namespaceURI, qname, value)

指定された `namespaceURI' および `qname' で与えられた属性の値を文字列で設定します。qname は属性の完全な名前であり、この点が上記のメソッドと違うので注意してください。
@end deffn

@node Attr オブジェクト,NamedNodeMap Objects,Element オブジェクト<2>,DOM 内のオブジェクト
@anchor{library/xml dom attr-objects}@anchor{3d97}@anchor{library/xml dom dom-attr-objects}@anchor{3d51}
@subsubsection Attr オブジェクト


@code{Attr} は @code{Node} を継承しており、全ての属性を継承しています。

@geindex name (xml.dom.Attr の属性)
@anchor{library/xml dom xml dom Attr name}@anchor{3d98}
@deffn {の属性} Attr.name

要素型名です。名前空間使用の文書では、要素型名中にコロンが含まれるかもしれません。
@end deffn

@geindex localName (xml.dom.Attr の属性)
@anchor{library/xml dom xml dom Attr localName}@anchor{3d99}
@deffn {の属性} Attr.localName

名前にコロンがあればコロン以降の部分に、なければ名前全体になります。
@end deffn

@geindex prefix (xml.dom.Attr の属性)
@anchor{library/xml dom xml dom Attr prefix}@anchor{3d9a}
@deffn {の属性} Attr.prefix

名前にコロンがあればコロン以前の部分に、なければ空文字列になります。
@end deffn

@geindex value (xml.dom.Attr の属性)
@anchor{library/xml dom xml dom Attr value}@anchor{3d9b}
@deffn {の属性} Attr.value

その要素の text value. これは @code{nodeValue} 属性の別名です。
@end deffn

@node NamedNodeMap Objects,Comment オブジェクト,Attr オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom dom-attributelist-objects}@anchor{3d9c}@anchor{library/xml dom namednodemap-objects}@anchor{3d9d}
@subsubsection NamedNodeMap Objects


@code{NamedNodeMap} は @code{Node} を継承して `いません' 。

@geindex length (xml.dom.NamedNodeMap の属性)
@anchor{library/xml dom xml dom NamedNodeMap length}@anchor{3d9e}
@deffn {の属性} NamedNodeMap.length

属性リストの長さです。
@end deffn

@geindex item() (xml.dom.NamedNodeMap のメソッド)
@anchor{library/xml dom xml dom NamedNodeMap item}@anchor{3d9f}
@deffn {メソッド} NamedNodeMap.item (index)

特定のインデクスを持つ属性を返します。属性の並び方は任意ですが、 DOM 文書が生成されている間は一定になります。各要素は属性ノードです。属性値はノードの @code{value} 属性で取得してください。
@end deffn

このクラスをよりマップ型的な動作ができるようにする実験的なメソッドもあります。そうしたメソッドを使うこともできますし、 @code{Element} オブジェクトに対して、標準化された @code{getAttribute*()} ファミリのメソッドを使うこともできます。

@node Comment オブジェクト,Text オブジェクトおよび CDATASection オブジェクト,NamedNodeMap Objects,DOM 内のオブジェクト
@anchor{library/xml dom comment-objects}@anchor{3da0}@anchor{library/xml dom dom-comment-objects}@anchor{3d52}
@subsubsection Comment オブジェクト


@code{Comment} は XML 文書中のコメントを表現します。 @code{Comment} は @code{Node} のサブクラスですが、子ノードを持つことはありません。

@geindex data (xml.dom.Comment の属性)
@anchor{library/xml dom xml dom Comment data}@anchor{3da1}
@deffn {の属性} Comment.data

文字列によるコメントの内容です。この属性には、コメントの先頭にある @code{<!-} @code{-} と末尾にある @code{-} @code{->} 間の全ての文字が入っていますが、@code{<!-} @code{-} と @code{-} @code{->} 自体は含みません。
@end deffn

@node Text オブジェクトおよび CDATASection オブジェクト,ProcessingInstruction オブジェクト,Comment オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom dom-text-objects}@anchor{3d53}@anchor{library/xml dom text-and-cdatasection-objects}@anchor{3da2}
@subsubsection Text オブジェクトおよび CDATASection オブジェクト


@code{Text} インターフェースは XML 文書内のテキストを表現します。パーザおよび DOM 実装が DOM の XML 拡張をサポートしている場合、 CDATA でマークされた区域 (section) に入れられている部分テキストは @code{CDATASection} オブジェクトに記憶されます。これら二つのインターフェースは同一のものですが、 @code{nodeType} 属性が異なります。

これらのインターフェースは @code{Node} インターフェースを拡張したものです。しかし子ノードを持つことはできません。

@geindex data (xml.dom.Text の属性)
@anchor{library/xml dom xml dom Text data}@anchor{3da3}
@deffn {の属性} Text.data

文字列によるテキストノードの内容です。
@end deffn

@cartouche
@quotation 注釈 
@code{CDATASection} ノードの利用は、ノードが完全な CDATA マーク区域を表現するという意味ではなく、ノードの内容が CDATA 区域の一部であるということを意味するだけです。単一の CDATA セクションは文書ツリー内で複数のノードとして表現されることがあります。二つの隣接する @code{CDATASection} ノードが、異なる CDATA マーク区域かどうかを決定する方法はありません。
@end quotation
@end cartouche

@node ProcessingInstruction オブジェクト,例外<23>,Text オブジェクトおよび CDATASection オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom dom-pi-objects}@anchor{3d54}@anchor{library/xml dom processinginstruction-objects}@anchor{3da4}
@subsubsection ProcessingInstruction オブジェクト


XML 文書内の処理命令を表現します; @code{Node} インターフェースを継承していますが、子ノードを持つことはできません。

@geindex target (xml.dom.ProcessingInstruction の属性)
@anchor{library/xml dom xml dom ProcessingInstruction target}@anchor{3da5}
@deffn {の属性} ProcessingInstruction.target

最初の空白文字までの処理命令の内容です。読み出し専用の属性です。
@end deffn

@geindex data (xml.dom.ProcessingInstruction の属性)
@anchor{library/xml dom xml dom ProcessingInstruction data}@anchor{3da6}
@deffn {の属性} ProcessingInstruction.data

最初の空白文字以降の処理命令の内容です。
@end deffn

@node 例外<23>,,ProcessingInstruction オブジェクト,DOM 内のオブジェクト
@anchor{library/xml dom dom-exceptions}@anchor{3da7}@anchor{library/xml dom exceptions}@anchor{3da8}
@subsubsection 例外


DOM レベル 2 勧告では、単一の例外 @ref{3da9,,DOMException} と、どの種のエラーが発生したかをアプリケーションが決定できるようにする多くの定数を定義しています。 @ref{3da9,,DOMException} インスタンスは、特定の例外に関する適切な値を提供する @ref{1b,,code} 属性を伴っています。

Python DOM インターフェースでは、上記の定数を提供していますが、同時に一連の例外を拡張して、DOM で定義されている各例外コードに対して特定の例外が存在するようにしています。 DOM の実装では、適切な特定の例外を送出しなければならず、各例外は @ref{1b,,code} 属性に対応する適切な値を伴わなければなりません。

@geindex DOMException
@anchor{library/xml dom xml dom DOMException}@anchor{3da9}
@deffn {例外} xml.dom.DOMException

全ての特定の DOM 例外で使われている基底例外クラスです。この例外クラスを直接インスタンス化することはできません。
@end deffn

@geindex DomstringSizeErr
@anchor{library/xml dom xml dom DomstringSizeErr}@anchor{3daa}
@deffn {例外} xml.dom.DomstringSizeErr

指定された範囲のテキストが文字列に収まらない場合に送出されます。この例外は Python の DOM 実装で使われるかどうかは判っていませんが、Python で書かれていない DOM 実装から送出される場合があります。
@end deffn

@geindex HierarchyRequestErr
@anchor{library/xml dom xml dom HierarchyRequestErr}@anchor{3dab}
@deffn {例外} xml.dom.HierarchyRequestErr

挿入できない型のノードを挿入しようと試みたときに送出されます。
@end deffn

@geindex IndexSizeErr
@anchor{library/xml dom xml dom IndexSizeErr}@anchor{3dac}
@deffn {例外} xml.dom.IndexSizeErr

メソッドに与えたインデクスやサイズパラメタが負の値や許容範囲の値を超えた際に送出されます。
@end deffn

@geindex InuseAttributeErr
@anchor{library/xml dom xml dom InuseAttributeErr}@anchor{3d94}
@deffn {例外} xml.dom.InuseAttributeErr

文書中にすでに存在する @code{Attr} ノードを挿入しようと試みた際に送出されます。
@end deffn

@geindex InvalidAccessErr
@anchor{library/xml dom xml dom InvalidAccessErr}@anchor{3dad}
@deffn {例外} xml.dom.InvalidAccessErr

パラメタまたは操作が根底にあるオブジェクトでサポートされていない場合に送出されます。
@end deffn

@geindex InvalidCharacterErr
@anchor{library/xml dom xml dom InvalidCharacterErr}@anchor{3dae}
@deffn {例外} xml.dom.InvalidCharacterErr

この例外は、文字列パラメタが、現在使われているコンテキストで XML 1.0 勧告によって許可されていない場合に送出されます。例えば、要素型に空白の入った @code{Element} ノードを生成しようとすると、このエラーが送出されます。
@end deffn

@geindex InvalidModificationErr
@anchor{library/xml dom xml dom InvalidModificationErr}@anchor{3daf}
@deffn {例外} xml.dom.InvalidModificationErr

ノードの型を変更しようと試みた際に送出されます。
@end deffn

@geindex InvalidStateErr
@anchor{library/xml dom xml dom InvalidStateErr}@anchor{3db0}
@deffn {例外} xml.dom.InvalidStateErr

定義されていないオブジェクトや、もはや利用できなくなったオブジェクトを使おうと試みた際に送出されます。
@end deffn

@geindex NamespaceErr
@anchor{library/xml dom xml dom NamespaceErr}@anchor{3db1}
@deffn {例外} xml.dom.NamespaceErr

Namespaces in XML@footnote{https://www.w3.org/TR/REC-xml-names/} に照らして許可されていない方法でオブジェクトを変更しようと試みた場合、この例外が送出されます。
@end deffn

@geindex NotFoundErr
@anchor{library/xml dom xml dom NotFoundErr}@anchor{3d8f}
@deffn {例外} xml.dom.NotFoundErr

参照しているコンテキスト中に目的のノードが存在しない場合に送出される例外です。例えば、 @code{NamedNodeMap.removeNamedItem()} は渡されたノードがノードマップ中に存在しない場合にこの例外を送出します。
@end deffn

@geindex NotSupportedErr
@anchor{library/xml dom xml dom NotSupportedErr}@anchor{3db2}
@deffn {例外} xml.dom.NotSupportedErr

要求された方のオブジェクトや操作が実装でサポートされていない場合に送出されます。
@end deffn

@geindex NoDataAllowedErr
@anchor{library/xml dom xml dom NoDataAllowedErr}@anchor{3db3}
@deffn {例外} xml.dom.NoDataAllowedErr

データ属性をサポートしないノードにデータを指定した際に送出されます。

@c XXX  a better explanation is needed!
@end deffn

@geindex NoModificationAllowedErr
@anchor{library/xml dom xml dom NoModificationAllowedErr}@anchor{3db4}
@deffn {例外} xml.dom.NoModificationAllowedErr

オブジェクトに対して (読み出し専用ノードに対する修正のように) 許可されていない修正を行おうと試みた際に送出されます。
@end deffn

@geindex SyntaxErr
@anchor{library/xml dom xml dom SyntaxErr}@anchor{3db5}
@deffn {例外} xml.dom.SyntaxErr

無効または不正な文字列が指定された際に送出されます。

@c XXX  how is this different from InvalidCharacterErr?
@end deffn

@geindex WrongDocumentErr
@anchor{library/xml dom xml dom WrongDocumentErr}@anchor{3db6}
@deffn {例外} xml.dom.WrongDocumentErr

ノードが現在属している文書と異なる文書に挿入され、かつある文書から別の文書へのノードの移行が実装でサポートされていない場合に送出されます。
@end deffn

DOM 勧告で定義されている例外コードは、以下のテーブルに従って上記の例外と対応付けられます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

例外

@item

@code{DOMSTRING_SIZE_ERR}

@tab

@ref{3daa,,DomstringSizeErr}

@item

@code{HIERARCHY_REQUEST_ERR}

@tab

@ref{3dab,,HierarchyRequestErr}

@item

@code{INDEX_SIZE_ERR}

@tab

@ref{3dac,,IndexSizeErr}

@item

@code{INUSE_ATTRIBUTE_ERR}

@tab

@ref{3d94,,InuseAttributeErr}

@item

@code{INVALID_ACCESS_ERR}

@tab

@ref{3dad,,InvalidAccessErr}

@item

@code{INVALID_CHARACTER_ERR}

@tab

@ref{3dae,,InvalidCharacterErr}

@item

@code{INVALID_MODIFICATION_ERR}

@tab

@ref{3daf,,InvalidModificationErr}

@item

@code{INVALID_STATE_ERR}

@tab

@ref{3db0,,InvalidStateErr}

@item

@code{NAMESPACE_ERR}

@tab

@ref{3db1,,NamespaceErr}

@item

@code{NOT_FOUND_ERR}

@tab

@ref{3d8f,,NotFoundErr}

@item

@code{NOT_SUPPORTED_ERR}

@tab

@ref{3db2,,NotSupportedErr}

@item

@code{NO_DATA_ALLOWED_ERR}

@tab

@ref{3db3,,NoDataAllowedErr}

@item

@code{NO_MODIFICATION_ALLOWED_ERR}

@tab

@ref{3db4,,NoModificationAllowedErr}

@item

@code{SYNTAX_ERR}

@tab

@ref{3db5,,SyntaxErr}

@item

@code{WRONG_DOCUMENT_ERR}

@tab

@ref{3db6,,WrongDocumentErr}

@end multitable


@node 適合性,,DOM 内のオブジェクト,xml dom --- ドキュメントオブジェクトモデル API
@anchor{library/xml dom conformance}@anchor{3db7}@anchor{library/xml dom dom-conformance}@anchor{3d43}
@subsubsection 適合性


この節では適合性に関する要求と、Python DOM API、W3C DOM 勧告、および OMG IDL の Python API への対応付けとの間の関係について述べます。

@menu
* 型の対応付け:: 
* アクセサメソッド:: 

@end menu

@node 型の対応付け,アクセサメソッド,,適合性
@anchor{library/xml dom dom-type-mapping}@anchor{3db8}@anchor{library/xml dom type-mapping}@anchor{3db9}
@subsubsection 型の対応付け


DOM 仕様で使われている IDL 型は、以下のテーブルに従って Python の型に対応付けられています。


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

IDL 型

@tab

Python の型

@item

@code{boolean}

@tab

@code{bool} または @code{int}

@item

@code{int}

@tab

@code{int}

@item

@code{long int}

@tab

@code{int}

@item

@code{unsigned int}

@tab

@code{int}

@item

@code{DOMString}

@tab

@code{str} または @code{bytes}

@item

@code{null}

@tab

@code{None}

@end multitable


@node アクセサメソッド,,型の対応付け,適合性
@anchor{library/xml dom accessor-methods}@anchor{3dba}@anchor{library/xml dom dom-accessor-methods}@anchor{3dbb}
@subsubsection アクセサメソッド


OMG IDL から Python への対応付けは、IDL @code{attribute} 宣言へのアクセサ関数の定義を、Java による対応付けが行うのとほとんど同じように行います。IDL 宣言の対応付け

@example
readonly attribute string someValue;
         attribute string anotherValue;
@end example

は、三つのアクセサ関数: @code{someValue} に対する "get" メソッド (@code{_get_someValue()})、そして @code{anotherValue} に対する "get" および "set" メソッド (@code{_get_anotherValue()} および @code{_set_anotherValue()}) を生成します。とりわけ、対応付けでは、IDL 属性が通常の Python 属性としてアクセス可能であることは必須ではありません: @code{object.someValue} が動作することは必須 `ではなく' 、 @ref{5f0,,AttributeError} を送出してもかまいません。

しかしながら、Python DOM API では、通常の属性アクセスが動作することが必須です。これは、Python IDL コンパイラによって生成された典型的な代用物はまず動作することはなく、DOM オブジェクトが CORBA を介してアクセスされる場合には、クライアント上でラッパーオブジェクトが必要であることを意味します。CORBA DOM クライアントでは他にもいくつか考慮すべきことがある一方で、Python から CORBA を介して DOM を使った経験を持つ実装者はこのことを問題視していません。@code{readonly} であると宣言された属性は、全ての DOM 実装で書き込みアクセスを制限しているとは限りません。

Python DOM API では、アクセサ関数は必須ではありません。アクセサ関数が提供された場合、Python IDL 対応付けによって定義された形式をとらなければなりませんが、属性は Python から直接アクセスすることができるので、それらのメソッドは必須ではないと考えられます。@code{readonly} であると宣言された属性に対しては、 "set" アクセサを提供してはなりません。

このIDLでの定義はW3C DOM APIの全ての要件を実装しているわけではありません。例えば、一部のオブジェクトの概念や @code{getElementsByTagName()} が "live" であることなどです。 Python DOM API はこれらの要件を実装することを強制しません。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml dom minidom --- 最小限の DOM の実装,xml dom pulldom --- 部分的な DOM ツリー構築のサポート,xml dom --- ドキュメントオブジェクトモデル API,構造化マークアップツール
@anchor{library/xml dom minidom doc}@anchor{3dbc}@anchor{library/xml dom minidom module-xml dom minidom}@anchor{128}@anchor{library/xml dom minidom translation-repo}@anchor{3dbd}@anchor{library/xml dom minidom xml-dom-minidom-minimal-dom-implementation}@anchor{3dbe}
@subsection @code{xml.dom.minidom} --- 最小限の DOM の実装


@geindex module; xml.dom.minidom

`ソースコード:' Lib/xml/dom/minidom.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/dom/minidom.py}


__________________________________________________________________


@code{xml.dom.minidom} is a minimal implementation of the Document Object
Model interface, with an API similar to that in other languages.  It is intended
to be simpler than the full DOM and also significantly smaller.  Users who are
not already proficient with the DOM should consider using the
@ref{12b,,xml.etree.ElementTree} module for their XML processing instead.

@cartouche
@quotation 注釈 
If you need to parse untrusted or unauthenticated data, see
@ref{3ce9,,XML security}.
@end quotation
@end cartouche

DOM applications typically start by parsing some XML into a DOM.  With
@code{xml.dom.minidom}, this is done through the parse functions:

@example
from xml.dom.minidom import parse, parseString

dom1 = parse('c:\\temp\\mydata.xml')  # parse an XML file by name

datasource = open('c:\\temp\\mydata.xml')
dom2 = parse(datasource)  # parse an open file

dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')
@end example

@ref{3dbf,,parse()} 関数はファイル名か、開かれたファイルオブジェクトを引数にとることができます。

@geindex parse() (xml.dom.minidom モジュール)
@anchor{library/xml dom minidom xml dom minidom parse}@anchor{3dbf}
@deffn {の関数} xml.dom.minidom.parse (filename_or_file, parser=None, bufsize=None)

与えられた入力から @code{Document} を返します。 `filename_or_file' はファイル名でもファイルオブジェクトでもかまいません。 `parser' を指定する場合、SAX2 パーザオブジェクトでなければなりません。この関数はパーザの文書ハンドラを変更し、名前空間サポートを有効にします; (エンティティリゾルバ (entity resolver) のような) 他のパーザ設定は前もっておこなわなければなりません。
@end deffn

XML データを文字列で持っている場合、 @ref{3dc0,,parseString()} を代わりに使うことができます:

@geindex parseString() (xml.dom.minidom モジュール)
@anchor{library/xml dom minidom xml dom minidom parseString}@anchor{3dc0}
@deffn {の関数} xml.dom.minidom.parseString (string, parser=None)

`string' を表わす @code{Document} を返します。このメソッドは、文字列に対する @ref{112a,,io.StringIO} オブジェクトを作成し、それを @ref{3dbf,,parse()} に渡します。
@end deffn

これらの関数は両方とも、文書の内容を表現する @code{Document} オブジェクトを返します。

What the @ref{3dbf,,parse()} and @ref{3dc0,,parseString()} functions do is connect an XML
parser with a "DOM builder" that can accept parse events from any SAX parser and
convert them into a DOM tree.  The names of the functions are perhaps misleading,
but are easy to grasp when learning the interfaces.  The parsing of the document
will be completed before these functions return; it's simply that these
functions do not provide a parser implementation themselves.

You can also create a @code{Document} by calling a method on a "DOM
Implementation" object.  You can get this object either by calling the
@code{getDOMImplementation()} function in the @ref{127,,xml.dom} package or the
@code{xml.dom.minidom} module.  Once you have a @code{Document}, you
can add child nodes to it to populate the DOM:

@example
from xml.dom.minidom import getDOMImplementation

impl = getDOMImplementation()

newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')
top_element.appendChild(text)
@end example

DOM 文書オブジェクトを手にしたら、XML 文書のプロパティやメソッドを使って、文書の一部にアクセスすることができます。これらのプロパティは DOM 仕様で定義されています。文書オブジェクトの主要なプロパティは @code{documentElement} プロパティです。このプロパティは XML 文書の主要な要素、つまり他の全ての要素を保持する要素を与えます。以下にプログラム例を示します。

@example
dom3 = parseString("<myxml>Some data</myxml>")
assert dom3.documentElement.tagName == "myxml"
@end example

When you are finished with a DOM tree, you may optionally call the
@code{unlink()} method to encourage early cleanup of the now-unneeded
objects.  @code{unlink()} is an @code{xml.dom.minidom}-specific
extension to the DOM API that renders the node and its descendants
essentially useless.  Otherwise, Python's garbage collector will
eventually take care of the objects in the tree.


@subsubheading 参考



@table @asis

@item Document Object Model (DOM) Level 1 Specification@footnote{https://www.w3.org/TR/REC-DOM-Level-1/}

The W3C recommendation for the DOM supported by @code{xml.dom.minidom}.
@end table


@menu
* DOM オブジェクト:: 
* DOM の例:: 
* minidom と DOM 標準:: 

@end menu

@node DOM オブジェクト,DOM の例,,xml dom minidom --- 最小限の DOM の実装
@anchor{library/xml dom minidom dom-objects}@anchor{3dc1}@anchor{library/xml dom minidom minidom-objects}@anchor{3dc2}
@subsubsection DOM オブジェクト


The definition of the DOM API for Python is given as part of the @ref{127,,xml.dom}
module documentation.  This section lists the differences between the API and
@code{xml.dom.minidom}.

@geindex unlink() (xml.dom.minidom.Node のメソッド)
@anchor{library/xml dom minidom xml dom minidom Node unlink}@anchor{3dc3}
@deffn {メソッド} Node.unlink ()

DOM との内部的な参照を破壊して、循環参照ガベージコレクションを持たないバージョンの Python でもガベージコレクションされるようにします。循環参照ガベージコレクションが利用できる場合でも、このメソッドを使えば大量のメモリをすぐに使えるようにできるため、不要になったらすぐに DOM オブジェクトに対してこのメソッドを呼ぶのが良い習慣です。このメソッドは @code{Document} オブジェクトに対して呼び出すだけでよいのですが、あるノードの子ノードを破棄するために子ノードに対して呼び出してもかまいません。

@ref{186,,with} ステートメントを使用することで、このメソッドを明示的に呼ばないようにできます。 @code{with} ブロックから出る時に自動的に次のコードが `dom' を unlink します:

@example
with xml.dom.minidom.parse(datasource) as dom:
    ... # Work with dom.
@end example
@end deffn

@geindex writexml() (xml.dom.minidom.Node のメソッド)
@anchor{library/xml dom minidom xml dom minidom Node writexml}@anchor{c89}
@deffn {メソッド} Node.writexml (writer, indent='@w{'}, addindent='@w{'}, newl='@w{'}, encoding=None, standalone=None)

XML を `writer' オブジェクトに書き込みます。
`writer' は入力としてテキストは受け付けますが、バイト列は受け付けません。 `writer' はファイルオブジェクトインターフェースの @code{write()} に該当するメソッドを持たなければなりません。
`indent' 引数には現在のノードのインデントを指定します。
`addindent' 引数には現在のノードの下にサブノードを追加する際のインデント増分を指定します。
`newl' には、改行時に行末を終端する文字列を指定します。

@code{Document} ノードでは、追加のキーワード引数 `encoding' を使って XML ヘッダの encoding フィールドを指定することができます。

同様に、`standalone' 引数を明示的に指定すると、スタンドアロン文書宣言がXMLのプロローグに追加されます。値が @code{True} の場合、@code{standalone="yes"} が追加され、それ以外の場合 @code{"no"} が設定されます。引数を指定しない場合は文書から宣言が省略されます。


バージョン 3.8 で変更: @ref{c89,,writexml()} メソッドはユーザーが指定した属性の順序を保持するようになりました。



バージョン 3.9 で変更: `standalone' パラメータが追加されました。

@end deffn

@geindex toxml() (xml.dom.minidom.Node のメソッド)
@anchor{library/xml dom minidom xml dom minidom Node toxml}@anchor{c8a}
@deffn {メソッド} Node.toxml (encoding=None, standalone=None)

DOM ノードによって表わされる XML を含んだ文字列またはバイト文字列を返します。

明示的に `encoding' @footnote{
XML 出力に含まれるエンコード名は適切な規格に従っていなければなりません。例えば "UTF-8" は有効ですが、 "UTF8" は XML 文書の宣言では有効ではありません。後者はエンコード名として Python に認められるとしてもです。@indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} と @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml} を参照してください。
} 引数を渡すと、結果は指定されたエンコードのバイト文字列になります。`encoding' 引数なしだと、結果は unicode 文字列です。また、結果として生じる文字列の中の XML 宣言はエンコーディングを指定しません。XML のデフォルトエンコーディングは UTF-8 なので、この文字列を UTF-8 以外でエンコードすることはおそらく正しくありません。

`standalone' 引数は @ref{c89,,writexml()} と全く同じ動作をします。


バージョン 3.8 で変更: @ref{c8a,,toxml()} メソッドはユーザーが指定した属性の順序を保持するようになりました。



バージョン 3.9 で変更: `standalone' パラメータが追加されました。

@end deffn

@geindex toprettyxml() (xml.dom.minidom.Node のメソッド)
@anchor{library/xml dom minidom xml dom minidom Node toprettyxml}@anchor{c8b}
@deffn {メソッド} Node.toprettyxml (indent='\t', newl='\n', encoding=None, standalone=None)

文書の整形されたバージョンを返します。 `indent' はインデントを行うための文字で、デフォルトはタブです; `newl' には行末で出力される文字列を指定し、デフォルトは @code{\n} です。

`encoding' 引数は @ref{c8a,,toxml()} の対応する引数と同様に振る舞います。

`standalone' 引数は @ref{c89,,writexml()} と全く同じ動作をします。


バージョン 3.8 で変更: @ref{c8b,,toprettyxml()}  メソッドはユーザーが指定した属性の順序を保持するようになりました。



バージョン 3.9 で変更: `standalone' パラメータが追加されました。

@end deffn

@node DOM の例,minidom と DOM 標準,DOM オブジェクト,xml dom minidom --- 最小限の DOM の実装
@anchor{library/xml dom minidom dom-example}@anchor{3dc4}@anchor{library/xml dom minidom id2}@anchor{3dc5}
@subsubsection DOM の例


以下のプログラム例は、単純なプログラムのかなり現実的な例です。特にこの例に関しては、DOM の柔軟性をあまり活用してはいません。

@example
import xml.dom.minidom

document = """\
<slideshow>
<title>Demo slideshow</title>
<slide><title>Slide title</title>
<point>This is a demo</point>
<point>Of a program for processing slides</point>
</slide>

<slide><title>Another demo slide</title>
<point>It is important</point>
<point>To have more than</point>
<point>one slide</point>
</slide>
</slideshow>
"""

dom = xml.dom.minidom.parseString(document)

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return '@w{'}.join(rc)

def handleSlideshow(slideshow):
    print("<html>")
    handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
    slides = slideshow.getElementsByTagName("slide")
    handleToc(slides)
    handleSlides(slides)
    print("</html>")

def handleSlides(slides):
    for slide in slides:
        handleSlide(slide)

def handleSlide(slide):
    handleSlideTitle(slide.getElementsByTagName("title")[0])
    handlePoints(slide.getElementsByTagName("point"))

def handleSlideshowTitle(title):
    print(f"<title>@{getText(title.childNodes)@}</title>")

def handleSlideTitle(title):
    print(f"<h2>@{getText(title.childNodes)@}</h2>")

def handlePoints(points):
    print("<ul>")
    for point in points:
        handlePoint(point)
    print("</ul>")

def handlePoint(point):
    print(f"<li>@{getText(point.childNodes)@}</li>")

def handleToc(slides):
    for slide in slides:
        title = slide.getElementsByTagName("title")[0]
        print(f"<p>@{getText(title.childNodes)@}</p>")

handleSlideshow(dom)
@end example

@node minidom と DOM 標準,,DOM の例,xml dom minidom --- 最小限の DOM の実装
@anchor{library/xml dom minidom minidom-and-dom}@anchor{3dc6}@anchor{library/xml dom minidom minidom-and-the-dom-standard}@anchor{3dc7}
@subsubsection minidom と DOM 標準


The @code{xml.dom.minidom} module is essentially a DOM 1.0-compatible DOM with
some DOM 2 features (primarily namespace features).

Python における DOM インターフェースは率直なものです。以下の対応付け規則が適用されます:


@itemize *

@item 
インターフェースはインスタンスオブジェクトを介してアクセスされます。アプリケーション自身から、クラスをインスタンス化してはなりません; @code{Document} オブジェクト上で利用可能な生成関数 (creator function) を使わなければなりません。派生インターフェースでは基底インターフェースの全ての演算 (および属性) に加え、新たな演算をサポートします。

@item 
演算はメソッドとして使われます。DOM では @ref{34b,,in} パラメタのみを使うので、引数は通常の順番 (左から右へ) で渡されます。オプション引数はありません。  @code{void} 演算は @code{None} を返します。

@item 
IDL 属性はインスタンス属性に対応付けられます。OMG IDL 言語における Python への対応付けとの互換性のために、属性 @code{foo} はアクセサメソッド @code{_get_foo()} および @code{_set_foo()} でもアクセスできます。 @code{readonly} 属性は変更してはなりません; とはいえ、これは実行時には強制されません。

@item 
@code{short int} 、 @code{unsigned int} 、 @code{unsigned long long} 、および @code{boolean} 型は、全て Python 整数オブジェクトに対応付けられます。

@item 
The type @code{DOMString} maps to Python strings. @code{xml.dom.minidom} supports
either bytes or strings, but will normally produce strings.
Values of type @code{DOMString} may also be @code{None} where allowed to have the IDL
@code{null} value by the DOM specification from the W3C.

@item 
@code{const} 宣言を行うと、 (@code{xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE} のように) 対応するスコープ内の変数に対応付けを行います; これらは変更してはなりません。

@item 
@code{DOMException} is currently not supported in @code{xml.dom.minidom}.
Instead, @code{xml.dom.minidom} uses standard Python exceptions such as
@ref{198,,TypeError} and @ref{5f0,,AttributeError}.

@item 
@code{NodeList} オブジェクトは Python の組み込みのリスト型を使って実装されています。これらのオブジェクトは DOM 仕様で定義されたインターフェースを提供していますが、以前のバージョンの Python では、公式の API をサポートしていません。しかしながら、これらの API は W3C 勧告で定義されたインターフェースよりも "Python 的な" ものになっています。
@end itemize

The following interfaces have no implementation in @code{xml.dom.minidom}:


@itemize *

@item 
@code{DOMTimeStamp}

@item 
@code{EntityReference}
@end itemize

これらの大部分は、ほとんどの DOM のユーザにとって一般的な用途として有用とはならないような XML 文書内の情報を反映しています。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml dom pulldom --- 部分的な DOM ツリー構築のサポート,xml sax --- SAX2 バーサーのサポート,xml dom minidom --- 最小限の DOM の実装,構造化マークアップツール
@anchor{library/xml dom pulldom doc}@anchor{3dc8}@anchor{library/xml dom pulldom module-xml dom pulldom}@anchor{129}@anchor{library/xml dom pulldom translation-repo}@anchor{3dc9}@anchor{library/xml dom pulldom xml-dom-pulldom-support-for-building-partial-dom-trees}@anchor{3dca}
@subsection @code{xml.dom.pulldom} --- 部分的な DOM ツリー構築のサポート


@geindex module; xml.dom.pulldom

`Source code:' Lib/xml/dom/pulldom.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/dom/pulldom.py}


__________________________________________________________________


The @code{xml.dom.pulldom} module provides a "pull parser" which can also be
asked to produce DOM-accessible fragments of the document where necessary. The
basic concept involves pulling "events" from a stream of incoming XML and
processing them. In contrast to SAX which also employs an event-driven
processing model together with callbacks, the user of a pull parser is
responsible for explicitly pulling events from the stream, looping over those
events until either processing is finished or an error condition occurs.

@cartouche
@quotation 注釈 
If you need to parse untrusted or unauthenticated data, see
@ref{3ce9,,XML security}.
@end quotation
@end cartouche


バージョン 3.7.1 で変更: SAXパーサーは、デフォルトでセキュリティーを向上させるために、一般的な外部エンティティーをデフォルトでは処理しなくなりました。外部エンティティの処理を有効にするには、次の場所にカスタムパーサーインスタンスを渡します:

@example
from xml.dom.pulldom import parse
from xml.sax import make_parser
from xml.sax.handler import feature_external_ges

parser = make_parser()
parser.setFeature(feature_external_ges, True)
parse(filename, parser=parser)
@end example


以下はプログラム例です:

@example
from xml.dom import pulldom

doc = pulldom.parse('sales_items.xml')
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'item':
        if int(node.getAttribute('price')) > 50:
            doc.expandNode(node)
            print(node.toxml())
@end example

@code{event} は定数で以下の内の一つです:


@itemize *

@item 
@code{START_ELEMENT}

@item 
@code{END_ELEMENT}

@item 
@code{COMMENT}

@item 
@code{START_DOCUMENT}

@item 
@code{END_DOCUMENT}

@item 
@code{CHARACTERS}

@item 
@code{PROCESSING_INSTRUCTION}

@item 
@code{IGNORABLE_WHITESPACE}
@end itemize

@code{node} は型 @code{xml.dom.minidom.Document}、 @code{xml.dom.minidom.Element} または @code{xml.dom.minidom.Text} のオブジェクトです。

文書はイベントの `フラットな' 流れとして扱われるため、文書の "木" は暗黙のうちに全て読み込まれ、目的の要素は木の中の深さに依らずに見つけられます。つまり、文書ノードの再帰的な検索のような階層的な問題を考える必要はありません。しかしながら要素の前後関係が重要な場合は、前後関係の状態を維持する (すなわち文章中の任意の点の場所を記憶する) か、 @ref{3dcb,,DOMEventStream.expandNode()} メソッドを使用して DOM 関連の処理に切り替える必要があります。

@geindex PullDOM (xml.dom.pulldom のクラス)
@anchor{library/xml dom pulldom xml dom pulldom PullDOM}@anchor{3dcc}
@deffn {クラス} xml.dom.pulldom.PullDOM (documentFactory=None)

@ref{3dcd,,xml.sax.handler.ContentHandler} のサブクラスです。
@end deffn

@geindex SAX2DOM (xml.dom.pulldom のクラス)
@anchor{library/xml dom pulldom xml dom pulldom SAX2DOM}@anchor{3dce}
@deffn {クラス} xml.dom.pulldom.SAX2DOM (documentFactory=None)

@ref{3dcd,,xml.sax.handler.ContentHandler} のサブクラスです。
@end deffn

@geindex parse() (xml.dom.pulldom モジュール)
@anchor{library/xml dom pulldom xml dom pulldom parse}@anchor{3dcf}
@deffn {の関数} xml.dom.pulldom.parse (stream_or_string, parser=None, bufsize=None)

与えられた入力から @ref{93e,,DOMEventStream} を返します。`stream_or_string' はファイル名かファイル様オブジェクトのいずれかです。`parser' は、与えれた場合、 @ref{3dd0,,XMLReader} オブジェクトでなければなりません。この関数はパーザの文書ハンドラを変えて名前空間のサポートを有効にします。パーザの他の設定 (例えばエンティティリゾルバ) は前もってしておかなければなりません。
@end deffn

XML データを文字列で持っている場合、 @ref{3dd1,,parseString()} を代わりに使うことができます:

@geindex parseString() (xml.dom.pulldom モジュール)
@anchor{library/xml dom pulldom xml dom pulldom parseString}@anchor{3dd1}
@deffn {の関数} xml.dom.pulldom.parseString (string, parser=None)

(ユニコード) `string' を表す @ref{93e,,DOMEventStream} を返します。
@end deffn

@geindex default_bufsize (xml.dom.pulldom モジュール)
@anchor{library/xml dom pulldom xml dom pulldom default_bufsize}@anchor{3dd2}
@deffn {データ} xml.dom.pulldom.default_bufsize

@ref{3dcf,,parse()} の `bufsize' パラメタのデフォルト値です。

この変数の値は @ref{3dcf,,parse()} を呼び出す前に変更することができます。その場合、その新しい値が有効になります。
@end deffn

@menu
* DOMEventStream オブジェクト:: 

@end menu

@node DOMEventStream オブジェクト,,,xml dom pulldom --- 部分的な DOM ツリー構築のサポート
@anchor{library/xml dom pulldom domeventstream-objects}@anchor{3dd3}@anchor{library/xml dom pulldom id1}@anchor{3dd4}
@subsubsection DOMEventStream オブジェクト


@geindex DOMEventStream (xml.dom.pulldom のクラス)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream}@anchor{93e}
@deffn {クラス} xml.dom.pulldom.DOMEventStream (stream, parser, bufsize)


バージョン 3.11 で変更: @ref{588,,__getitem__()} メソッドのサポートは削除されました。


@geindex getEvent() (xml.dom.pulldom.DOMEventStream のメソッド)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream getEvent}@anchor{3dd5}
@deffn {メソッド} getEvent ()

event が @code{START_DOCUMENT} の場合は `event' と @code{xml.dom.minidom.Document} としての現在の `node' からなるタプルを、
@code{START_ELEMENT} か @code{END_ELEMENT} の場合は @code{xml.dom.minidom.Element} を、
@code{CHARACTERS} の場合は @code{xml.dom.minidom.Text} を返します。
@ref{3dcb,,expandNode()} が呼ばれない限り、現在のノードは子ノードの情報を持ちません。
@end deffn

@geindex expandNode() (xml.dom.pulldom.DOMEventStream のメソッド)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream expandNode}@anchor{3dcb}
@deffn {メソッド} expandNode (node)

`node' の全子ノードを `node' に展開します。例:

@example
from xml.dom import pulldom

xml = '<html><title>Foo</title> <p>Some text <div>and more</div></p> </html>'
doc = pulldom.parseString(xml)
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'p':
        # Following statement only prints '<p/>'
        print(node.toxml())
        doc.expandNode(node)
        # Following statement prints node with all its children '<p>Some text <div>and more</div></p>'
        print(node.toxml())
@end example
@end deffn

@geindex reset() (xml.dom.pulldom.DOMEventStream のメソッド)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream reset}@anchor{3dd6}
@deffn {メソッド} reset ()
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml sax --- SAX2 バーサーのサポート,xml sax handler --- SAX ハンドラーの基底クラス,xml dom pulldom --- 部分的な DOM ツリー構築のサポート,構造化マークアップツール
@anchor{library/xml sax doc}@anchor{3dd7}@anchor{library/xml sax module-xml sax}@anchor{12f}@anchor{library/xml sax translation-repo}@anchor{3dd8}@anchor{library/xml sax xml-sax-support-for-sax2-parsers}@anchor{3dd9}
@subsection @code{xml.sax} --- SAX2 バーサーのサポート


@geindex module; xml.sax

`ソースコード:' Lib/xml/sax/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/sax/__init__.py}


__________________________________________________________________


The @code{xml.sax} package provides a number of modules which implement the
Simple API for XML (SAX) interface for Python.  The package itself provides the
SAX exceptions and the convenience functions which will be most used by users of
the SAX API.

@cartouche
@quotation 注釈 
If you need to parse untrusted or unauthenticated data, see
@ref{3ce9,,XML security}.
@end quotation
@end cartouche


バージョン 3.7.1 で変更: SAXパーサーは、セキュリティーを向上させるために、デフォルトで一般的な外部エンティティーを処理しなくなりました。以前は、パーサーは、DTDおよびエンティティ用にファイルシステムからリモートファイルまたはロードされたローカルファイルをフェッチするためのネットワーク接続を作成していました。この機能は parser オブジェクトと(実) 引数 @ref{17cd,,feature_external_ges} の @ref{3dda,,setFeature()} メソッドで再度有効にすることができます。


その関数群は以下の通りです:

@geindex make_parser() (xml.sax モジュール)
@anchor{library/xml sax xml sax make_parser}@anchor{1e1c}
@deffn {の関数} xml.sax.make_parser (parser_list=[])

SAX @ref{3dd0,,XMLReader} オブジェクトを生成し、返します。最初に見つかったパーサーが使用されます。`parser_list' を与える場合、それは @code{create_parser()} という名前の関数をもつモジュール名のイテラブルでなければなりません。
`parser_list' に列挙されているモジュールは、パーサーのデフォルトリストにあるモジュールよりも先に使われます。


バージョン 3.8 で変更: `parser_list' 引数はリストだけでなく、イテラブルでもよくなりました。

@end deffn

@geindex parse() (xml.sax モジュール)
@anchor{library/xml sax xml sax parse}@anchor{1de6}
@deffn {の関数} xml.sax.parse (filename_or_stream, handler, error_handler=handler.ErrorHandler())

SAX パーサを生成し、そのパーサをドキュメントの解析に使用します。`filename_or_stream' として与えられるドキュメントは、ファイル名でもファイルオブジェクトでもかまいません。 `handler' 引数は SAX @ref{3dcd,,ContentHandler} のインスタントである必要があります。`error_handler' が与えられる場合は、 SAX @ref{3ddb,,ErrorHandler}  のインスタンスである必要があります。この引数を省略した場合、全ての例外に対して @ref{3ddc,,SAXParseException} が発生します。 戻り値はありません。すべての操作は渡される `handler' によって行われなければなりません。
@end deffn

@geindex parseString() (xml.sax モジュール)
@anchor{library/xml sax xml sax parseString}@anchor{109c}
@deffn {の関数} xml.sax.parseString (string, handler, error_handler=handler.ErrorHandler())

@ref{1de6,,parse()} と同様ですが、こちらは引数で受け取ったバッファ `string' をパースします。
`string' は @ref{169,,str} インスタンスか @ref{193,,bytes-like object} でなければなりません。


バージョン 3.5 で変更: @ref{169,,str} インスタンスがサポートされました。

@end deffn

典型的な SAX アプリケーションでは3種類のオブジェクト(リーダ、ハンドラ、入力元)が用いられます。ここで言うリーダとはパーサを指しています。つまり、入力元からバイト列または文字列を読み込み、一連のイベントを発生させるコード片のことです。発生したイベントはハンドラ・オブジェクトに割り振られます。言い換えると、リーダがハンドラのメソッドを呼び出すわけです。つまり、 SAX アプリケーションは、リーダ・オブジェクトを作成し、入力元のオブジェクトを作成するか開き、ハンドラ・オブジェクトを作成し、これら3つのオブジェクトを連携させる必要があります。準備の最終段階では、リーダが呼び出され、入力をパースします。パース中には、入力データからの構造イベントや構文イベントに基づいて、ハンドラ・オブジェクトのメソッドが呼び出されます。

For these objects, only the interfaces are relevant; they are normally not
instantiated by the application itself.  Since Python does not have an explicit
notion of interface, they are formally introduced as classes, but applications
may use implementations which do not inherit from the provided classes.  The
@ref{109b,,InputSource}, @ref{3ddd,,Locator},
@code{Attributes}, @code{AttributesNS},
and @ref{3dd0,,XMLReader} interfaces are defined in the
module @ref{132,,xml.sax.xmlreader}.  The handler interfaces are defined in
@ref{130,,xml.sax.handler}.  For convenience,
@ref{109b,,InputSource} (which is often
instantiated directly) and the handler classes are also available from
@code{xml.sax}.  These interfaces are described below.

In addition to these classes, @code{xml.sax} provides the following exception
classes.

@geindex SAXException
@anchor{library/xml sax xml sax SAXException}@anchor{3dde}
@deffn {例外} xml.sax.SAXException (msg, exception=None)

XML エラーと警告をカプセル化します。このクラスには XML パーサとアプリケーションで発生するエラーおよび警告の基本的な情報を持たせることができます。また機能追加や地域化のためにサブクラス化することも可能です。なお @ref{3ddb,,ErrorHandler} で定義されているハンドラがこの例外のインスタンスを受け取ることに注意してください。実際に例外を発生させることは必須でなく、情報のコンテナとして利用されることもあるからです。

インスタンスを作成する際 `msg' はエラー内容を示す可読データにしてください。オプションの `exception' 引数は @code{None} にするか、パース用コードで捕捉されて情報として渡される例外にしてください。

このクラスはSAX 例外の基底クラスになります。
@end deffn

@geindex SAXParseException
@anchor{library/xml sax xml sax SAXParseException}@anchor{3ddc}
@deffn {例外} xml.sax.SAXParseException (msg, exception, locator)

パースエラー時に発生する @ref{3dde,,SAXException} のサブクラスです。パースエラーに関する情報として、このクラスのインスタンスが SAX @ref{3ddb,,ErrorHandler} インターフェースのメソッドに渡されます。このクラスは @ref{3dde,,SAXException} 同様 SAX @ref{3ddd,,Locator} インターフェースもサポートしています。
@end deffn

@geindex SAXNotRecognizedException
@anchor{library/xml sax xml sax SAXNotRecognizedException}@anchor{3ddf}
@deffn {例外} xml.sax.SAXNotRecognizedException (msg, exception=None)

SAX @ref{3dd0,,XMLReader} が認識できない機能やプロパティに遭遇したとき発生させる @ref{3dde,,SAXException} のサブクラスです。 SAX アプリケーションや拡張モジュールにおいて同様の目的にこのクラスを利用することもできます。
@end deffn

@geindex SAXNotSupportedException
@anchor{library/xml sax xml sax SAXNotSupportedException}@anchor{3de0}
@deffn {例外} xml.sax.SAXNotSupportedException (msg, exception=None)

SAX @ref{3dd0,,XMLReader} が要求された機能をサポートしていないとき発生させる @ref{3dde,,SAXException} のサブクラスです。 SAX アプリケーションや拡張モジュールにおいて同様の目的にこのクラスを利用することもできます。
@end deffn


@subsubheading 参考



@table @asis

@item SAX: The Simple API for XML@footnote{http://www.saxproject.org/}

SAX API 定義に関し中心となっているサイトです。Java による実装とオンライン・ドキュメントが提供されています。実装と SAX API の歴史に関する情報のリンクも掲載されています。

@item @ref{130,,xml.sax.handler} モジュール

アプリケーションが提供するオブジェクトのインターフェース定義。

@item @ref{131,,xml.sax.saxutils} モジュール

SAX アプリケーション向けの有用な関数群。

@item @ref{132,,xml.sax.xmlreader} モジュール

パーサが提供するオブジェクトのインターフェース定義。
@end table


@menu
* SAXException オブジェクト:: 

@end menu

@node SAXException オブジェクト,,,xml sax --- SAX2 バーサーのサポート
@anchor{library/xml sax sax-exception-objects}@anchor{3de1}@anchor{library/xml sax saxexception-objects}@anchor{3de2}
@subsubsection SAXException オブジェクト


@ref{3dde,,SAXException} 例外クラスは以下のメソッドをサポートしています:

@geindex getMessage() (xml.sax.SAXException のメソッド)
@anchor{library/xml sax xml sax SAXException getMessage}@anchor{3de3}
@deffn {メソッド} SAXException.getMessage ()

エラー状態を示す可読メッセージを返します。
@end deffn

@geindex getException() (xml.sax.SAXException のメソッド)
@anchor{library/xml sax xml sax SAXException getException}@anchor{3de4}
@deffn {メソッド} SAXException.getException ()

カプセル化した例外オブジェクトまたは @code{None} を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml sax handler --- SAX ハンドラーの基底クラス,xml sax saxutils --- SAX ユーティリティー,xml sax --- SAX2 バーサーのサポート,構造化マークアップツール
@anchor{library/xml sax handler doc}@anchor{3de5}@anchor{library/xml sax handler module-xml sax handler}@anchor{130}@anchor{library/xml sax handler translation-repo}@anchor{3de6}@anchor{library/xml sax handler xml-sax-handler-base-classes-for-sax-handlers}@anchor{3de7}
@subsection @code{xml.sax.handler} --- SAX ハンドラーの基底クラス


@geindex module; xml.sax.handler

`ソースコード:' Lib/xml/sax/handler.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/sax/handler.py}


__________________________________________________________________


The SAX API defines five kinds of handlers: content handlers, DTD handlers,
error handlers, entity resolvers and lexical handlers. Applications normally
only need to implement those interfaces whose events they are interested in;
they can implement the interfaces in a single object or in multiple objects.
Handler implementations should inherit from the base classes provided in the
module @code{xml.sax.handler}, so that all methods get default implementations.

@geindex ContentHandler (xml.sax.handler のクラス)
@anchor{library/xml sax handler xml sax handler ContentHandler}@anchor{3dcd}
@deffn {クラス} xml.sax.handler.ContentHandler

アプリケーションにとって最も重要なメインの SAX コールバック・インターフェースです。このインターフェースで発生するイベントの順序はドキュメント内の情報の順序を反映しています。
@end deffn

@geindex DTDHandler (xml.sax.handler のクラス)
@anchor{library/xml sax handler xml sax handler DTDHandler}@anchor{3de8}
@deffn {クラス} xml.sax.handler.DTDHandler

DTD イベントのハンドラです。

パースされていないエンティティや属性など、基本的なパースに必要な DTD イベントの指定だけを行うインターフェースです。
@end deffn

@geindex EntityResolver (xml.sax.handler のクラス)
@anchor{library/xml sax handler xml sax handler EntityResolver}@anchor{3de9}
@deffn {クラス} xml.sax.handler.EntityResolver

エンティティ解決用の基本インターフェースです。このインターフェースを実装したオブジェクトを作成しパーサに登録することで、パーサはすべての外部エンティティを解決するメソッドを呼び出すようになります。
@end deffn

@geindex ErrorHandler (xml.sax.handler のクラス)
@anchor{library/xml sax handler xml sax handler ErrorHandler}@anchor{3ddb}
@deffn {クラス} xml.sax.handler.ErrorHandler

エラーや警告メッセージをアプリケーションに通知するためにパーサが使用するインターフェースです。このオブジェクトのメソッドが、エラーをただちに例外に変換するか、あるいは別の方法で処理するかの制御をしています。
@end deffn

@geindex LexicalHandler (xml.sax.handler のクラス)
@anchor{library/xml sax handler xml sax handler LexicalHandler}@anchor{a5c}
@deffn {クラス} xml.sax.handler.LexicalHandler

Interface used by the parser to represent low frequency events which may not
be of interest to many applications.
@end deffn

In addition to these classes, @code{xml.sax.handler} provides symbolic constants
for the feature and property names.

@geindex feature_namespaces (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler feature_namespaces}@anchor{3dea}
@deffn {データ} xml.sax.handler.feature_namespaces


@display
値: @code{"http://xml.org/sax/features/namespaces"}@w{ }
真: 名前空間を処理します。@w{ }
偽: オプションで名前空間を処理しません (暗黙に名前空間接頭辞も無効にします; デフォルト)。@w{ }
アクセス: (パース時) 読み込み専用; (パース時以外) 読み書き可@w{ }
@end display


@end deffn

@geindex feature_namespace_prefixes (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler feature_namespace_prefixes}@anchor{3deb}
@deffn {データ} xml.sax.handler.feature_namespace_prefixes


@display
値: @code{"http://xml.org/sax/features/namespace-prefixes"}@w{ }
真: 名前空間宣言で用いられている元々の接頭辞付きの名前と属性を報告します。@w{ }
偽: 名前空間宣言で用いられている属性を報告しません。オプションで元々の接頭辞付きの名前も報告しません (デフォルト)。@w{ }
アクセス: (パース時) 読み込み専用; (パース時以外) 読み書き可@w{ }
@end display


@end deffn

@geindex feature_string_interning (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler feature_string_interning}@anchor{3dec}
@deffn {データ} xml.sax.handler.feature_string_interning


@display
値: @code{"http://xml.org/sax/features/string-interning"}@w{ }
真: 全ての要素名、接頭辞、属性名、名前空間 URI、ローカル名を組込みの intern 関数を使ってシンボルに登録します。@w{ }
偽: 名前を必ずしもシンボルに登録しませんが、されるかもしれません (デフォルト)。@w{ }
アクセス: (パース時) 読み込み専用; (パース時以外) 読み書き可@w{ }
@end display


@end deffn

@geindex feature_validation (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler feature_validation}@anchor{3ded}
@deffn {データ} xml.sax.handler.feature_validation


@display
値: @code{"http://xml.org/sax/features/validation"}@w{ }
真: 全ての妥当性検査エラーを報告します (外部一般エンティティと外部変数エンティティが暗示されます)。@w{ }
偽: 妥当性検査エラーを報告しません。@w{ }
アクセス: (パース時) 読み込み専用; (パース時以外) 読み書き可@w{ }
@end display


@end deffn

@geindex feature_external_ges (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler feature_external_ges}@anchor{17cd}
@deffn {データ} xml.sax.handler.feature_external_ges

@cartouche
@quotation 警告 
Enabling opens a vulnerability to
external entity attacks@footnote{https://en.wikipedia.org/wiki/XML_external_entity_attack}
if the parser is used with user-provided XML content.
Please reflect on your threat model@footnote{https://en.wikipedia.org/wiki/Threat_model}
before enabling this feature.
@end quotation
@end cartouche


@display
値: @code{"http://xml.org/sax/features/external-general-entities"}@w{ }
真: 全ての外部一般 (テキスト) エンティティを取り込みます。@w{ }
偽: 外部一般エンティティを取り込みません。@w{ }
アクセス: (パース時) 読み込み専用; (パース時以外) 読み書き可@w{ }
@end display


@end deffn

@geindex feature_external_pes (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler feature_external_pes}@anchor{3dee}
@deffn {データ} xml.sax.handler.feature_external_pes


@display
値: @code{"http://xml.org/sax/features/external-parameter-entities"}@w{ }
真: 外部 DTD サブセットを含む全ての外部変数エンティティを取り込みます。@w{ }
偽: 外部 DTD サブセットであっても外部変数エンティティを取り込みません。@w{ }
アクセス: (パース時) 読み込み専用; (パース時以外) 読み書き可@w{ }
@end display


@end deffn

@geindex all_features (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler all_features}@anchor{3def}
@deffn {データ} xml.sax.handler.all_features

全機能のリスト。
@end deffn

@geindex property_lexical_handler (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler property_lexical_handler}@anchor{3df0}
@deffn {データ} xml.sax.handler.property_lexical_handler


@display
値: @code{"http://xml.org/sax/properties/lexical-handler"}@w{ }
data type: xml.sax.handler.LexicalHandler (not supported in Python 2)@w{ }
説明: コメントなど字句解析イベント用のオプション拡張ハンドラ。@w{ }
アクセス: 読み書き可@w{ }
@end display


@end deffn

@geindex property_declaration_handler (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler property_declaration_handler}@anchor{3df1}
@deffn {データ} xml.sax.handler.property_declaration_handler


@display
値: @code{"http://xml.org/sax/properties/declaration-handler"}@w{ }
データ型: xml.sax.sax2lib.DeclHandler (Python 2 では未サポート)@w{ }
説明: 表記や未解析エンティティをのぞく DTD 関連イベント用のオプション拡張ハンドラ。@w{ }
アクセス: 読み書き可@w{ }
@end display


@end deffn

@geindex property_dom_node (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler property_dom_node}@anchor{3df2}
@deffn {データ} xml.sax.handler.property_dom_node


@display
値: @code{"http://xml.org/sax/properties/dom-node"}@w{ }
データ型: org.w3c.dom.Node (Python 2 では未サポート)@w{ }
説明: パース時は DOM イテレータならば現在の DOM ノードです。非パース時はイテレートのルート DOM ノードです。@w{ }
アクセス: (パース時) 読み込み専用; (パース時以外) 読み書き可@w{ }
@end display


@end deffn

@geindex property_xml_string (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler property_xml_string}@anchor{3df3}
@deffn {データ} xml.sax.handler.property_xml_string


@display
値: @code{"http://xml.org/sax/properties/xml-string"}@w{ }
data type: Bytes@w{ }
説明: 現在のイベントの元になったリテラル文字列。@w{ }
アクセス: 読み出し専用@w{ }
@end display


@end deffn

@geindex all_properties (xml.sax.handler モジュール)
@anchor{library/xml sax handler xml sax handler all_properties}@anchor{3df4}
@deffn {データ} xml.sax.handler.all_properties

既知の全プロパティ名のリスト。
@end deffn

@menu
* ContentHandler オブジェクト:: 
* DTDHandler オブジェクト:: 
* EntityResolver オブジェクト:: 
* ErrorHandler オブジェクト:: 
* LexicalHandler Objects:: 

@end menu

@node ContentHandler オブジェクト,DTDHandler オブジェクト,,xml sax handler --- SAX ハンドラーの基底クラス
@anchor{library/xml sax handler content-handler-objects}@anchor{3df5}@anchor{library/xml sax handler contenthandler-objects}@anchor{3df6}
@subsubsection ContentHandler オブジェクト


@ref{3dcd,,ContentHandler} はアプリケーション側でサブクラス化して利用することが前提になっています。パーサは入力ドキュメントのイベントにより、それぞれに対応する以下のメソッドを呼び出します:

@geindex setDocumentLocator() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler setDocumentLocator}@anchor{3df7}
@deffn {メソッド} ContentHandler.setDocumentLocator (locator)

アプリケーションにドキュメントイベントの発生位置を指すロケータを与えるためにパーサから呼び出されます。

SAX パーサによるロケータの提供は強く推奨されています(必須ではありません)。もし提供する場合は、DocumentHandler インターフェースのどのメソッドよりも先にこのメソッドが呼び出されるようにしなければなりません。

パーサがエラーを報告しない場合でも、ロケータによってアプリケーションは全てのドキュメント関連イベントの終了位置を知ることが出来ます。
通常、アプリケーションは自身のエラー (例えば文字コンテンツがアプリケーションの規則に適合しない場合) を報告するためにこれを使用します。
ロケータが返す情報は検索エンジンでの利用にはおそらく不充分です。

ロケータが正しい情報を返すのは、このインターフェースからイベントの呼出しが実行されている間だけです。それ以外のときは使用すべきでありません。
@end deffn

@geindex startDocument() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler startDocument}@anchor{3df8}
@deffn {メソッド} ContentHandler.startDocument ()

ドキュメントの開始通知を受け取ります。

SAX パーサはこのインターフェースやDTDHandler のどのメソッド (@ref{3df7,,setDocumentLocator()} を除く) よりも先にこのメソッドを一度だけ呼び出します。
@end deffn

@geindex endDocument() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler endDocument}@anchor{3df9}
@deffn {メソッド} ContentHandler.endDocument ()

ドキュメントの終了通知を受け取ります。

SAX パーサはこのメソッドを一度だけ呼び出します。パース中に呼び出す最後のメソッドです。パーサは (回復不能なエラーで) パース処理を中断するか、あるいは入力の最後に到達するまでこのメソッドを呼び出しません。
@end deffn

@geindex startPrefixMapping() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler startPrefixMapping}@anchor{3dfa}
@deffn {メソッド} ContentHandler.startPrefixMapping (prefix, uri)

接頭辞と URI 名前空間の関連付けのスコープを開始します。

このイベントからの情報は名前空間処理に必須ではありません。SAX XML リーダは @code{feature_namespaces} 機能が有効な場合 (デフォルト)、要素と属性名の接頭辞を自動的に置換します。

しかしながら、接頭辞の自動展開を安全に行えないために、アプリケーションが文字データや属性値の中で接頭辞を使わなければならない場合があります。
必要ならば @ref{3dfa,,startPrefixMapping()} や @ref{3dfb,,endPrefixMapping()} イベントはアプリケーションにコンテキスト自身の中で接頭辞を展開するための情報を提供します。

@c XXX This is not really the default, is it? MvL

@ref{3dfa,,startPrefixMapping()} と @ref{3dfb,,endPrefixMapping()} イベントは相互に正しい入れ子関係になることが保証されていないので注意が必要です。すべての @ref{3dfa,,startPrefixMapping()} は対応する @ref{175c,,startElement()} の前に発生し、 @ref{3dfb,,endPrefixMapping()} イベントは対応する @ref{175d,,endElement()} の後で発生しますが、その順序は保証されていません。
@end deffn

@geindex endPrefixMapping() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler endPrefixMapping}@anchor{3dfb}
@deffn {メソッド} ContentHandler.endPrefixMapping (prefix)

接頭辞と URI の関連付けのスコープを終了します。

詳しくは @ref{3dfa,,startPrefixMapping()} を参照してください。このイベントは常に対応する @ref{175d,,endElement()} の後で発生しますが、複数の @ref{3dfb,,endPrefixMapping()} イベントの順序は特に保証されません。
@end deffn

@geindex startElement() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler startElement}@anchor{175c}
@deffn {メソッド} ContentHandler.startElement (name, attrs)

非名前空間モードでの要素の開始を通知します。

The `name' parameter contains the raw XML 1.0 name of the element type as a
string and the `attrs' parameter holds an object of the
@ref{3dfc,,Attributes} interface containing the attributes of
the element.  The object passed as `attrs' may be re-used by the parser; holding
on to a reference to it is not a reliable way to keep a copy of the attributes.
To keep a copy of the attributes, use the @ref{29,,copy()} method of the `attrs'
object.
@end deffn

@geindex endElement() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler endElement}@anchor{175d}
@deffn {メソッド} ContentHandler.endElement (name)

非名前空間モードでの要素の終了を通知します。

`name' 引数は @ref{175c,,startElement()} イベントとまったく同じ要素型名を持ちます。
@end deffn

@geindex startElementNS() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler startElementNS}@anchor{3dfd}
@deffn {メソッド} ContentHandler.startElementNS (name, qname, attrs)

名前空間モードでの要素の開始を通知します。

The `name' parameter contains the name of the element type as a @code{(uri,
localname)} tuple, the `qname' parameter contains the raw XML 1.0 name used in
the source document, and the `attrs' parameter holds an instance of the
@ref{3dfe,,AttributesNS} interface
containing the attributes of the element.  If no namespace is associated with
the element, the `uri' component of `name' will be @code{None}.  The object passed
as `attrs' may be re-used by the parser; holding on to a reference to it is not
a reliable way to keep a copy of the attributes.  To keep a copy of the
attributes, use the @ref{29,,copy()} method of the `attrs' object.

@code{feature_namespace_prefixes} 機能が有効でなければ、パーサで `qname' を @code{None} に設定することも可能です。
@end deffn

@geindex endElementNS() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler endElementNS}@anchor{3dff}
@deffn {メソッド} ContentHandler.endElementNS (name, qname)

名前空間モードでの要素の終了を通知します。

`name' 引数は @ref{3dfd,,startElementNS()} イベントとまったく同じ要素型を持ちます。 `qname' 引数も同様です。
@end deffn

@geindex characters() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler characters}@anchor{175e}
@deffn {メソッド} ContentHandler.characters (content)

文字データの通知を受け取ります。

パーサはこのメソッドを呼び出して文字データの各チャンクを報告します。SAX パーサは一連の文字データを単一のチャンクとして返す場合と複数のチャンクに分けて返す場合がありますが、ロケータの情報が正しく保たれるように、一つのイベントの文字データは常に同じ外部エンティティのものでなければなりません。

`content' は文字列、バイト列のどちらでもかまいませんが、@code{expat} リーダ・モジュールは常に文字列を生成するようになっています。

@cartouche
@quotation 注釈 
Python XML SIG が提供していた初期 SAX 1 では、このメソッドにもっと JAVA 風のインターフェースが用いられています。しかし Python で採用されている大半のパーサでは古いインターフェースを有効に使うことができないため、よりシンプルなものに変更されました。古いコードを新しいインターフェースに変更するには、古い `offset' と `length' パラメータでスライスせずに、`content' を指定するようにしてください。
@end quotation
@end cartouche
@end deffn

@geindex ignorableWhitespace() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler ignorableWhitespace}@anchor{3e00}
@deffn {メソッド} ContentHandler.ignorableWhitespace (whitespace)

要素内容中の無視できる空白文字の通知を受け取ります。

妥当性検査を行うパーサはこのメソッドを使って、無視できる空白文字 (W3C XML 1.0 勧告の 2.10 節参照) の各チャンクを報告しなければなりません。妥当性検査をしないパーサもコンテンツモデルの利用とパースが可能な場合、このメソッドを利用することが可能です。

SAX パーサは連続する複数の空白文字を単一のチャンクとして返す場合と複数のチャンクに分けて返す場合があります。しかし、ロケータが有用な情報を提供できるように、単一のイベント中のすべての文字は同じ外部エンティティからのものでなければなりません。
@end deffn

@geindex processingInstruction() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler processingInstruction}@anchor{3e01}
@deffn {メソッド} ContentHandler.processingInstruction (target, data)

処理命令の通知を受け取ります。

パーサは処理命令が見つかるたびにこのメソッドを呼び出します。処理命令はメインのドキュメント要素の前や後にも発生することがあるので注意してください。

SAX パーサがこのメソッドを使って XML 宣言 (XML 1.0 のセクション 2.8) やテキスト宣言 (XML 1.0 のセクション 4.3.1) の通知をすることはありません。
@end deffn

@geindex skippedEntity() (xml.sax.handler.ContentHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ContentHandler skippedEntity}@anchor{3e02}
@deffn {メソッド} ContentHandler.skippedEntity (name)

スキップしたエンティティの通知を受け取ります。

パーサはエンティティをスキップするたびにこのメソッドを呼び出します。妥当性検査をしないプロセッサは (外部 DTD サブセットで宣言されているなどの理由で) 宣言が見当たらないエンティティをスキップします。すべてのプロセッサは @code{feature_external_ges} および @code{feature_external_pes} 属性の値によっては外部エンティティをスキップすることがあります。
@end deffn

@node DTDHandler オブジェクト,EntityResolver オブジェクト,ContentHandler オブジェクト,xml sax handler --- SAX ハンドラーの基底クラス
@anchor{library/xml sax handler dtd-handler-objects}@anchor{3e03}@anchor{library/xml sax handler dtdhandler-objects}@anchor{3e04}
@subsubsection DTDHandler オブジェクト


@ref{3de8,,DTDHandler} インスタンスは以下のメソッドを提供します:

@geindex notationDecl() (xml.sax.handler.DTDHandler のメソッド)
@anchor{library/xml sax handler xml sax handler DTDHandler notationDecl}@anchor{3e05}
@deffn {メソッド} DTDHandler.notationDecl (name, publicId, systemId)

表記宣言イベントの通知を扱います。
@end deffn

@geindex unparsedEntityDecl() (xml.sax.handler.DTDHandler のメソッド)
@anchor{library/xml sax handler xml sax handler DTDHandler unparsedEntityDecl}@anchor{3e06}
@deffn {メソッド} DTDHandler.unparsedEntityDecl (name, publicId, systemId, ndata)

未パースのエンティティ宣言イベントの通知を扱います。
@end deffn

@node EntityResolver オブジェクト,ErrorHandler オブジェクト,DTDHandler オブジェクト,xml sax handler --- SAX ハンドラーの基底クラス
@anchor{library/xml sax handler entity-resolver-objects}@anchor{3e07}@anchor{library/xml sax handler entityresolver-objects}@anchor{3e08}
@subsubsection EntityResolver オブジェクト


@geindex resolveEntity() (xml.sax.handler.EntityResolver のメソッド)
@anchor{library/xml sax handler xml sax handler EntityResolver resolveEntity}@anchor{3e09}
@deffn {メソッド} EntityResolver.resolveEntity (publicId, systemId)

エンティティのシステム識別子を解決し、文字列として読み込んだシステム識別子あるいは InputSource オブジェクトのいずれかを返します。デフォルトの実装では `systemId' を返します。
@end deffn

@node ErrorHandler オブジェクト,LexicalHandler Objects,EntityResolver オブジェクト,xml sax handler --- SAX ハンドラーの基底クラス
@anchor{library/xml sax handler errorhandler-objects}@anchor{3e0a}@anchor{library/xml sax handler sax-error-handler}@anchor{3e0b}
@subsubsection ErrorHandler オブジェクト


Objects with this interface are used to receive error and warning information
from the @ref{3dd0,,XMLReader}.  If you create an object that
implements this interface, then register the object with your
@ref{3dd0,,XMLReader}, the parser
will call the methods in your object to report all warnings and errors. There
are three levels of errors available: warnings, (possibly) recoverable errors,
and unrecoverable errors.  All methods take a @ref{3ddc,,SAXParseException} as the
only parameter.  Errors and warnings may be converted to an exception by raising
the passed-in exception object.

@geindex error() (xml.sax.handler.ErrorHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ErrorHandler error}@anchor{3e0c}
@deffn {メソッド} ErrorHandler.error (exception)

パーサが回復可能なエラーに遭遇すると呼び出されます。このメソッドが例外を送出しない場合パースは継続されますが、アプリケーションは更なるドキュメント情報を期待すべきではありません。パーサの処理を継続を認めることで入力ドキュメント内の他のエラーを見つけることができます。
@end deffn

@geindex fatalError() (xml.sax.handler.ErrorHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ErrorHandler fatalError}@anchor{3e0d}
@deffn {メソッド} ErrorHandler.fatalError (exception)

パーサが回復不能なエラーに遭遇すると呼び出されます。このメソッドが return したとき、パースの停止が求められています。
@end deffn

@geindex warning() (xml.sax.handler.ErrorHandler のメソッド)
@anchor{library/xml sax handler xml sax handler ErrorHandler warning}@anchor{3e0e}
@deffn {メソッド} ErrorHandler.warning (exception)

パーサが軽微な警告情報をアプリケーションに通知するときに呼び出されます。このメソッドが return したときはパースの継続が求められ、ドキュメント情報はアプリケーションに送り続けられます。このメソッドでの例外の送出はパースを終了します。
@end deffn

@node LexicalHandler Objects,,ErrorHandler オブジェクト,xml sax handler --- SAX ハンドラーの基底クラス
@anchor{library/xml sax handler lexical-handler-objects}@anchor{3e0f}@anchor{library/xml sax handler lexicalhandler-objects}@anchor{3e10}
@subsubsection LexicalHandler Objects


Optional SAX2 handler for lexical events.

This handler is used to obtain lexical information about an XML
document. Lexical information includes information describing the
document encoding used and XML comments embedded in the document, as
well as section boundaries for the DTD and for any CDATA sections.
The lexical handlers are used in the same manner as content handlers.

Set the LexicalHandler of an XMLReader by using the setProperty method
with the property identifier
@code{'http://xml.org/sax/properties/lexical-handler'}.

@geindex comment() (xml.sax.handler.LexicalHandler のメソッド)
@anchor{library/xml sax handler xml sax handler LexicalHandler comment}@anchor{3e11}
@deffn {メソッド} LexicalHandler.comment (content)

Reports a comment anywhere in the document (including the DTD and
outside the document element).
@end deffn

@geindex startDTD() (xml.sax.handler.LexicalHandler のメソッド)
@anchor{library/xml sax handler xml sax handler LexicalHandler startDTD}@anchor{3e12}
@deffn {メソッド} LexicalHandler.startDTD (name, public_id, system_id)

Reports the start of the DTD declarations if the document has an
associated DTD.
@end deffn

@geindex endDTD() (xml.sax.handler.LexicalHandler のメソッド)
@anchor{library/xml sax handler xml sax handler LexicalHandler endDTD}@anchor{3e13}
@deffn {メソッド} LexicalHandler.endDTD ()

Reports the end of DTD declaration.
@end deffn

@geindex startCDATA() (xml.sax.handler.LexicalHandler のメソッド)
@anchor{library/xml sax handler xml sax handler LexicalHandler startCDATA}@anchor{3e14}
@deffn {メソッド} LexicalHandler.startCDATA ()

Reports the start of a CDATA marked section.

The contents of the CDATA marked section will be reported through
the characters handler.
@end deffn

@geindex endCDATA() (xml.sax.handler.LexicalHandler のメソッド)
@anchor{library/xml sax handler xml sax handler LexicalHandler endCDATA}@anchor{3e15}
@deffn {メソッド} LexicalHandler.endCDATA ()

Reports the end of a CDATA marked section.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml sax saxutils --- SAX ユーティリティー,xml sax xmlreader --- XML パーサーのインターフェース,xml sax handler --- SAX ハンドラーの基底クラス,構造化マークアップツール
@anchor{library/xml sax utils doc}@anchor{3e16}@anchor{library/xml sax utils module-xml sax saxutils}@anchor{131}@anchor{library/xml sax utils translation-repo}@anchor{3e17}@anchor{library/xml sax utils xml-sax-saxutils-sax-utilities}@anchor{3e18}
@subsection @code{xml.sax.saxutils} --- SAX ユーティリティー


@geindex module; xml.sax.saxutils

`ソースコード:' Lib/xml/sax/saxutils.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/sax/saxutils.py}


__________________________________________________________________


The module @code{xml.sax.saxutils} contains a number of classes and functions
that are commonly useful when creating SAX applications, either in direct use,
or as base classes.

@geindex escape() (xml.sax.saxutils モジュール)
@anchor{library/xml sax utils xml sax saxutils escape}@anchor{3e19}
@deffn {の関数} xml.sax.saxutils.escape (data, entities=@{@})

文字列データ内の @code{'&'}, @code{'<'}, @code{'>'} をエスケープします。

オプションの `entities' 引数に辞書を渡すことで、そのほかの文字列データをエスケープすることも可能です。辞書のキーと値はすべて文字列で、キーは対応する値に置換されます。`entities' が与えられている場合でも、 @code{'&'}, @code{'<'}, @code{'>'} は常にエスケープされます。

@cartouche
@quotation 注釈 
この関数は、 XML 内で直接使用できない文字のエスケープにのみ使用するべきです。この関数を一般的な文字列変換関数のように使用してはなりません。
@end quotation
@end cartouche
@end deffn

@geindex unescape() (xml.sax.saxutils モジュール)
@anchor{library/xml sax utils xml sax saxutils unescape}@anchor{3e1a}
@deffn {の関数} xml.sax.saxutils.unescape (data, entities=@{@})

エスケープされた文字列 @code{'&amp;'}, @code{'&lt;'}, @code{'&gt;'} を元の文字に戻します。

You can unescape other strings of data by passing a dictionary as the optional
`entities' parameter.  The keys and values must all be strings; each key will be
replaced with its corresponding value.  @code{'&amp;'}, @code{'&lt;'}, and @code{'&gt;'}
are always unescaped, even if `entities' is provided.
@end deffn

@geindex quoteattr() (xml.sax.saxutils モジュール)
@anchor{library/xml sax utils xml sax saxutils quoteattr}@anchor{3e1b}
@deffn {の関数} xml.sax.saxutils.quoteattr (data, entities=@{@})

@ref{3e19,,escape()} に似ていますが、 `data' は属性値の作成に使われます。戻り値はクォート済みの `data' で、置換する文字の追加も可能です。 @ref{3e1b,,quoteattr()} はクォートすべき文字を `data' の文脈から判断し、クォートすべき文字を残さないように文字列をエンコードします。 `data' の中にシングル・クォート、ダブル・クォートがあれば、両方ともエンコードし、全体をダブルクォートで囲みます。戻り値の文字列はそのままで属性値として利用できます:

@example
>>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
<element attr="ab ' cd &quot; ef">
@end example

この関数は参照具象構文を使って、 HTML や SGML の属性値を生成するのに便利です。
@end deffn

@geindex XMLGenerator (xml.sax.saxutils のクラス)
@anchor{library/xml sax utils xml sax saxutils XMLGenerator}@anchor{3e1c}
@deffn {クラス} xml.sax.saxutils.XMLGenerator (out=None, encoding='iso-8859-1', short_empty_elements=False)

このクラスは SAX イベントを XML 文書に書き戻すことで @ref{3dcd,,ContentHandler} インターフェースを実装しています。
つまり、 @ref{3e1c,,XMLGenerator} をコンテントハンドラとして用いることで、パースしている元々の文書を複製することが出来ます。
`out' にはファイル様オブジェクトでなければなりません。
デフォルトは `sys.stdout' です。
`encoding' は出力ストリームのエンコーディングで、デフォルトは @code{'iso-8859-1'} です。
`short_empty_elements' は
内容を持たない要素のフォーマットを制御します。
@code{False} (デフォルト) の場合、開始/終了タグのペアとなり、 @code{True} の場合、1つの空タグになります。


バージョン 3.2 で変更: `short_empty_elements' 引数を追加しました。

@end deffn

@geindex XMLFilterBase (xml.sax.saxutils のクラス)
@anchor{library/xml sax utils xml sax saxutils XMLFilterBase}@anchor{3e1d}
@deffn {クラス} xml.sax.saxutils.XMLFilterBase (base)

このクラスは @ref{3dd0,,XMLReader} とクライアント・アプリケーションのイベント・ハンドラとの間に位置するものとして設計されています。デフォルトでは何もせず、ただリクエストをリーダに、イベントをハンドラに、それぞれ加工せず渡すだけです。しかし、サブクラスでメソッドをオーバーライドすると、イベント・ストリームやリクエストを加工してから渡すように変更可能です。
@end deffn

@geindex prepare_input_source() (xml.sax.saxutils モジュール)
@anchor{library/xml sax utils xml sax saxutils prepare_input_source}@anchor{3e1e}
@deffn {の関数} xml.sax.saxutils.prepare_input_source (source, base='@w{'})

この関数は引数に入力ソース、オプションとして URL を取り、読み取り可能な解決済み @ref{109b,,InputSource} オブジェクトを返します。入力ソースは文字列、ファイル風オブジェクト、 @ref{109b,,InputSource} のいずれでも良く、この関数を使うことで、パーサは様々な `source' 引数を @ref{3e1f,,parse()} メソッドに実装することが可能になります。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml sax xmlreader --- XML パーサーのインターフェース,xml parsers expat --- Expat を使用した高速な XML 解析,xml sax saxutils --- SAX ユーティリティー,構造化マークアップツール
@anchor{library/xml sax reader doc}@anchor{3e20}@anchor{library/xml sax reader module-xml sax xmlreader}@anchor{132}@anchor{library/xml sax reader translation-repo}@anchor{3e21}@anchor{library/xml sax reader xml-sax-xmlreader-interface-for-xml-parsers}@anchor{3e22}
@subsection @code{xml.sax.xmlreader} --- XML パーサーのインターフェース


@geindex module; xml.sax.xmlreader

`ソースコード:' Lib/xml/sax/xmlreader.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xml/sax/xmlreader.py}


__________________________________________________________________


各 SAX パーサは Python モジュールとして @ref{3dd0,,XMLReader} インターフェースを実装しており、関数 @code{create_parser()} を提供しています。この関数は新たなパーサ・オブジェクトを生成する際、 @ref{1e1c,,xml.sax.make_parser()} から引数なしで呼び出されます。

@geindex XMLReader (xml.sax.xmlreader のクラス)
@anchor{library/xml sax reader xml sax xmlreader XMLReader}@anchor{3dd0}
@deffn {クラス} xml.sax.xmlreader.XMLReader

SAX パーサが継承可能な基底クラスです。
@end deffn

@geindex IncrementalParser (xml.sax.xmlreader のクラス)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser}@anchor{3e23}
@deffn {クラス} xml.sax.xmlreader.IncrementalParser

入力ソースを一度にパースするのではなく、ドキュメントのチャンクが利用可能になるごとに取得したいことがあります。SAX リーダは通常、ファイル全体を一気に読み込まず、チャンク単位で処理するのですが、全体の処理が終わるまで @code{parse()} は返りません。そのため、 @code{parse()} の排他的挙動を望まないときにこれらのインターフェースを使用してください。

パーサのインスタンスが作成されるとすぐに、feed メソッドを通じてデータを受け入れられるようになります。パースが完了して閉じるための呼び出しが行われた後、パーサがフィードからまたはパースメソッドを使用して新しいデータを受け入れられるように、reset メソッドが呼び出される必要があります。

これらのメソッドをパース処理の途中で呼び出すことはできません。つまり、パースが実行された後で、パーサから return する前に呼び出す必要があるのです。

デフォルトでは、SAX 2.0 ドライバを書く人のために、このクラスは IncrementalParser の feed、close、reset メソッドを使って XMLReader インターフェースの parse メソッドを実装しています。
@end deffn

@geindex Locator (xml.sax.xmlreader のクラス)
@anchor{library/xml sax reader xml sax xmlreader Locator}@anchor{3ddd}
@deffn {クラス} xml.sax.xmlreader.Locator

SAX イベントと文書の位置を関連付けるインターフェースです。locator オブジェクトは DocumentHandler メソッドを呼び出している間だけ正しい結果を返し、それ以外とのときは、予測できない結果を返します。情報を利用できない場合、メソッドは @code{None} を返すこともあります。
@end deffn

@geindex InputSource (xml.sax.xmlreader のクラス)
@anchor{library/xml sax reader xml sax xmlreader InputSource}@anchor{109b}
@deffn {クラス} xml.sax.xmlreader.InputSource (system_id=None)

@ref{3dd0,,XMLReader} がエンティティを読み込むために必要な情報をカプセル化します。

このクラスには公開識別子、システム識別子、(場合によっては文字エンコーディング情報を含む) バイト・ストリーム、そしてエンティティの文字ストリームなどの情報が含まれます。

アプリケーションは @ref{3e1f,,XMLReader.parse()} メソッドでの使用や EntityResolver.resolveEntity の戻り値としてこのオブジェトを作成します。

@ref{109b,,InputSource} はアプリケーションに属します。 @ref{3dd0,,XMLReader} はアプリケーションから渡された @ref{109b,,InputSource} オブジェクトの変更を許可されていませんが、コピーを作ってそれを変更することは可能です。
@end deffn

@geindex AttributesImpl (xml.sax.xmlreader のクラス)
@anchor{library/xml sax reader xml sax xmlreader AttributesImpl}@anchor{3e24}
@deffn {クラス} xml.sax.xmlreader.AttributesImpl (attrs)

@code{Attributes} インターフェース (@ref{3dfc,,Attributes インターフェース} 参照) の実装です。これは辞書風のオブジェクトで、 @code{startElement()} 内で要素の属性を表示します。最も有用な辞書操作に加え、インターフェースに記述されているメソッドを多数サポートしています。このクラスのオブジェクトはリーダによってインスタンス化されなければなりません。`attrs' は属性名と属性値の対応付けを含む辞書風オブジェクトでなければなりません。
@end deffn

@geindex AttributesNSImpl (xml.sax.xmlreader のクラス)
@anchor{library/xml sax reader xml sax xmlreader AttributesNSImpl}@anchor{3e25}
@deffn {クラス} xml.sax.xmlreader.AttributesNSImpl (attrs, qnames)

@ref{3e24,,AttributesImpl} を名前空間認識型に改良したクラスで、 @code{startElementNS()} に渡されます。 @ref{3e24,,AttributesImpl} の派生クラスですが、 `namespaceURI' と `localname' の2要素のタプルを解釈します。さらに、元の文書に出てくる修飾名を返す多くのメソッドを提供します。このクラスは @code{AttributesNS} インターフェース (@ref{3dfe,,AttributesNS インターフェース} 参照) の実装です。
@end deffn

@menu
* XMLReader オブジェクト:: 
* IncrementalParser オブジェクト:: 
* Locator オブジェクト:: 
* InputSource オブジェクト:: 
* Attributes インターフェース:: 
* AttributesNS インターフェース:: 

@end menu

@node XMLReader オブジェクト,IncrementalParser オブジェクト,,xml sax xmlreader --- XML パーサーのインターフェース
@anchor{library/xml sax reader id1}@anchor{3e26}@anchor{library/xml sax reader xmlreader-objects}@anchor{3e27}
@subsubsection XMLReader オブジェクト


@ref{3dd0,,XMLReader} は次のメソッドをサポートします:

@geindex parse() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader parse}@anchor{3e1f}
@deffn {メソッド} XMLReader.parse (source)

入力ソースを処理し、SAX イベントを作成します。 `source' オブジェクトはシステム識別子 (入力ソースを特定する文字列 -- 一般にファイル名や URL)、 @ref{266,,pathlib.Path} オブジェクトか @ref{5a1,,path-like} オブジェクトまたは @ref{109b,,InputSource} オブジェクトです。 @ref{3e1f,,parse()} が return したとき、入力データの処理は完了し、パーサ・オブジェクトは破棄ないしリセットされます。


バージョン 3.5 で変更: 文字ストリームがサポートされました。



バージョン 3.8 で変更: path-like オブジェクトのサポートが追加されました。

@end deffn

@geindex getContentHandler() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getContentHandler}@anchor{3e28}
@deffn {メソッド} XMLReader.getContentHandler ()

現在の @ref{3dcd,,ContentHandler} を返します。
@end deffn

@geindex setContentHandler() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setContentHandler}@anchor{3e29}
@deffn {メソッド} XMLReader.setContentHandler (handler)

現在の @ref{3dcd,,ContentHandler} を設定します。 @ref{3dcd,,ContentHandler} が設定されていない場合、内容イベントは破棄されます。
@end deffn

@geindex getDTDHandler() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getDTDHandler}@anchor{3e2a}
@deffn {メソッド} XMLReader.getDTDHandler ()

現在の @ref{3de8,,DTDHandler} を返します。
@end deffn

@geindex setDTDHandler() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setDTDHandler}@anchor{3e2b}
@deffn {メソッド} XMLReader.setDTDHandler (handler)

現在の @ref{3de8,,DTDHandler} を返します。 @ref{3de8,,DTDHandler} が設定されていな場合、DTD イベントは破棄されます。
@end deffn

@geindex getEntityResolver() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getEntityResolver}@anchor{3e2c}
@deffn {メソッド} XMLReader.getEntityResolver ()

現在の @ref{3de9,,EntityResolver} を返します。
@end deffn

@geindex setEntityResolver() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setEntityResolver}@anchor{3e2d}
@deffn {メソッド} XMLReader.setEntityResolver (handler)

現在の @ref{3de9,,EntityResolver} を返します。 @ref{3de9,,EntityResolver} が設定されていない場合、外部エンティティの解決を試行することでエンティティのシステム識別子が開かれます。利用できない場合は失敗します。
@end deffn

@geindex getErrorHandler() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getErrorHandler}@anchor{3e2e}
@deffn {メソッド} XMLReader.getErrorHandler ()

現在の @ref{3ddb,,ErrorHandler} を返します。
@end deffn

@geindex setErrorHandler() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setErrorHandler}@anchor{3e2f}
@deffn {メソッド} XMLReader.setErrorHandler (handler)

現在のエラーハンドラを設定します。@ref{3ddb,,ErrorHandler} が設定されていない場合、エラーが例外として送出され、警告が表示されます。
@end deffn

@geindex setLocale() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setLocale}@anchor{3e30}
@deffn {メソッド} XMLReader.setLocale (locale)

アプリケーションにエラーや警告のロケール設定を許可します。

SAX パーサにとって、エラーや警告の地域化は必須ではありません。しかし、パーサが要求されたロケールをサポートしていない場合、SAX 例外を送出しなければなりません。アプリケーションはパースの途中でロケールの変更を要求することができます。
@end deffn

@geindex getFeature() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getFeature}@anchor{3e31}
@deffn {メソッド} XMLReader.getFeature (featurename)

機能 `featurename' の現在の設定を返します。その機能が認識できないときは、 @code{SAXNotRecognizedException} を送出します。有名な機能名はモジュール @ref{130,,xml.sax.handler} に列挙されています。
@end deffn

@geindex setFeature() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setFeature}@anchor{3dda}
@deffn {メソッド} XMLReader.setFeature (featurename, value)

機能名 `featurename' に値 `value' を設定します。その機能が認識できないときは、 @code{SAXNotRecognizedException} を送出します。また、パーサが指定された機能や設定をサポートしていないときは、 @code{SAXNotSupportedException} を送出します。
@end deffn

@geindex getProperty() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getProperty}@anchor{3e32}
@deffn {メソッド} XMLReader.getProperty (propertyname)

属性名 `propertyname' の現在の値を返します。その属性が認識できないときは、 @code{SAXNotRecognizedException} を送出します。有名な属性名はモジュール @ref{130,,xml.sax.handler} に列挙されています。
@end deffn

@geindex setProperty() (xml.sax.xmlreader.XMLReader のメソッド)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setProperty}@anchor{3e33}
@deffn {メソッド} XMLReader.setProperty (propertyname, value)

属性名 `propertyname' に値 `value' を設定します。その機能が認識できないときは、 @code{SAXNotRecognizedException} を送出します。また、パーサが指定された機能や設定をサポートしていないときは、 @code{SAXNotSupportedException} を送出します。
@end deffn

@node IncrementalParser オブジェクト,Locator オブジェクト,XMLReader オブジェクト,xml sax xmlreader --- XML パーサーのインターフェース
@anchor{library/xml sax reader incremental-parser-objects}@anchor{3e34}@anchor{library/xml sax reader incrementalparser-objects}@anchor{3e35}
@subsubsection IncrementalParser オブジェクト


@ref{3e23,,IncrementalParser} のインスタンスは次の追加メソッドを提供します:

@geindex feed() (xml.sax.xmlreader.IncrementalParser のメソッド)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser feed}@anchor{3e36}
@deffn {メソッド} IncrementalParser.feed (data)

`data' のチャンクを処理します。
@end deffn

@geindex close() (xml.sax.xmlreader.IncrementalParser のメソッド)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser close}@anchor{3e37}
@deffn {メソッド} IncrementalParser.close ()

文書の終端を決定します。文書の適格性を調べ (終端でのみ可能)、ハンドラを起動し、パース時に割り当てた資源を解放します。
@end deffn

@geindex reset() (xml.sax.xmlreader.IncrementalParser のメソッド)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser reset}@anchor{3e38}
@deffn {メソッド} IncrementalParser.reset ()

このメソッドは close が呼び出された後、新しい文書をパースできるように、パーサをリセットするのに呼び出されます。close 後 reset を呼び出さずに parse や feed を呼び出した場合の戻り値は未定義です。
@end deffn

@node Locator オブジェクト,InputSource オブジェクト,IncrementalParser オブジェクト,xml sax xmlreader --- XML パーサーのインターフェース
@anchor{library/xml sax reader id2}@anchor{3e39}@anchor{library/xml sax reader locator-objects}@anchor{3e3a}
@subsubsection Locator オブジェクト


@ref{3ddd,,Locator} のインスタンスは次のメソッドを提供します:

@geindex getColumnNumber() (xml.sax.xmlreader.Locator のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Locator getColumnNumber}@anchor{3e3b}
@deffn {メソッド} Locator.getColumnNumber ()

現在のイベントが開始する列番号を返します。
@end deffn

@geindex getLineNumber() (xml.sax.xmlreader.Locator のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Locator getLineNumber}@anchor{3e3c}
@deffn {メソッド} Locator.getLineNumber ()

現在のイベントが開始する行番号を返します。
@end deffn

@geindex getPublicId() (xml.sax.xmlreader.Locator のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Locator getPublicId}@anchor{3e3d}
@deffn {メソッド} Locator.getPublicId ()

現在の文書イベントの公開識別子を返します。
@end deffn

@geindex getSystemId() (xml.sax.xmlreader.Locator のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Locator getSystemId}@anchor{3e3e}
@deffn {メソッド} Locator.getSystemId ()

現在のイベントのシステム識別子を返します。
@end deffn

@node InputSource オブジェクト,Attributes インターフェース,Locator オブジェクト,xml sax xmlreader --- XML パーサーのインターフェース
@anchor{library/xml sax reader input-source-objects}@anchor{3e3f}@anchor{library/xml sax reader inputsource-objects}@anchor{3e40}
@subsubsection InputSource オブジェクト


@geindex setPublicId() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource setPublicId}@anchor{3e41}
@deffn {メソッド} InputSource.setPublicId (id)

この @ref{109b,,InputSource} の公開識別子を設定します。
@end deffn

@geindex getPublicId() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource getPublicId}@anchor{3e42}
@deffn {メソッド} InputSource.getPublicId ()

この @ref{109b,,InputSource} の公開識別子を返します。
@end deffn

@geindex setSystemId() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource setSystemId}@anchor{3e43}
@deffn {メソッド} InputSource.setSystemId (id)

この @ref{109b,,InputSource} のシステム識別子を設定します。
@end deffn

@geindex getSystemId() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource getSystemId}@anchor{3e44}
@deffn {メソッド} InputSource.getSystemId ()

この @ref{109b,,InputSource} のシステム識別子を返します。
@end deffn

@geindex setEncoding() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource setEncoding}@anchor{3e45}
@deffn {メソッド} InputSource.setEncoding (encoding)

この @ref{109b,,InputSource} の文字エンコーディングを設定します。

エンコーディングは XML エンコーディング宣言として受け入れられる文字列でなければなりません (XML 勧告の 4.3.3 節を参照)。

@ref{109b,,InputSource} も文字ストリームを含んでいた場合、@ref{109b,,InputSource} のエンコーディング属性は無視されます。
@end deffn

@geindex getEncoding() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource getEncoding}@anchor{3e46}
@deffn {メソッド} InputSource.getEncoding ()

この InputSource の文字エンコーディングを取得します。
@end deffn

@geindex setByteStream() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource setByteStream}@anchor{3e47}
@deffn {メソッド} InputSource.setByteStream (bytefile)

この入力ソースのバイトストリーム (@ref{206e,,binary file}) を設定します。

文字ストリームも指定されている場合、SAX パーサはこのバイトストリームを無視しますが、URI 接続自体を開くときには優先してバイトストリームを使います。

アプリケーションがバイトストリームの文字エンコーディングを知っている場合は、setEncoding メソッドで設定する必要があります。
@end deffn

@geindex getByteStream() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource getByteStream}@anchor{3e48}
@deffn {メソッド} InputSource.getByteStream ()

この入力ソースのバイトストリームを取得します。

getEncoding メソッドは、このバイトストリームの文字エンコーディングを返します。不明なときは @code{None} を返します。
@end deffn

@geindex setCharacterStream() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource setCharacterStream}@anchor{3e49}
@deffn {メソッド} InputSource.setCharacterStream (charfile)

この入力ソースの文字ストリーム (@ref{206d,,text file}) を設定します。

文字ストリームが指定された場合、SAX パーサは全バイトストリームを無視し、システム識別子への URI 接続の開始を試みません。
@end deffn

@geindex getCharacterStream() (xml.sax.xmlreader.InputSource のメソッド)
@anchor{library/xml sax reader xml sax xmlreader InputSource getCharacterStream}@anchor{3e4a}
@deffn {メソッド} InputSource.getCharacterStream ()

この入力ソースの文字ストリームを取得します。
@end deffn

@node Attributes インターフェース,AttributesNS インターフェース,InputSource オブジェクト,xml sax xmlreader --- XML パーサーのインターフェース
@anchor{library/xml sax reader attributes-objects}@anchor{3dfc}@anchor{library/xml sax reader the-attributes-interface}@anchor{3e4b}
@subsubsection @code{Attributes} インターフェース


@code{Attributes} オブジェクトは @code{copy()}、@code{get()}、@ref{15d3,,__contains__()}、@code{items()}、@code{keys()}、@code{values()} を含む @ref{13d3,,マッピングプロトコル} の一部を実装しています。以下のメソッドも提供されています:

@geindex getLength() (xml.sax.xmlreader.Attributes のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Attributes getLength}@anchor{3e4c}
@deffn {メソッド} Attributes.getLength ()

属性の数を返します。
@end deffn

@geindex getNames() (xml.sax.xmlreader.Attributes のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Attributes getNames}@anchor{3e4d}
@deffn {メソッド} Attributes.getNames ()

属性の名前を返します。
@end deffn

@geindex getType() (xml.sax.xmlreader.Attributes のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Attributes getType}@anchor{3e4e}
@deffn {メソッド} Attributes.getType (name)

属性名 `name' のタイプを返します。通常は @code{'CDATA'} です。
@end deffn

@geindex getValue() (xml.sax.xmlreader.Attributes のメソッド)
@anchor{library/xml sax reader xml sax xmlreader Attributes getValue}@anchor{3e4f}
@deffn {メソッド} Attributes.getValue (name)

属性 `name' の値を返します。
@end deffn

@c getValueByQName, getNameByQName, getQNameByName, getQNames available

@c here already, but documented only for derived class.

@node AttributesNS インターフェース,,Attributes インターフェース,xml sax xmlreader --- XML パーサーのインターフェース
@anchor{library/xml sax reader attributes-ns-objects}@anchor{3dfe}@anchor{library/xml sax reader the-attributesns-interface}@anchor{3e50}
@subsubsection @code{AttributesNS} インターフェース


このインターフェースは @code{Attributes} インターフェース (@ref{3dfc,,Attributes インターフェース} 参照) のサブタイプです。 Attributes インターフェースがサポートしているすべてのメソッドは @code{AttributesNS} オブジェクトでも利用可能です。

次のメソッドもサポートされています:

@geindex getValueByQName() (xml.sax.xmlreader.AttributesNS のメソッド)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getValueByQName}@anchor{3e51}
@deffn {メソッド} AttributesNS.getValueByQName (name)

修飾名の値を返します。
@end deffn

@geindex getNameByQName() (xml.sax.xmlreader.AttributesNS のメソッド)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getNameByQName}@anchor{3e52}
@deffn {メソッド} AttributesNS.getNameByQName (name)

修飾名 `name' に対応する @code{(namespace, localname)} のペアを返します。
@end deffn

@geindex getQNameByName() (xml.sax.xmlreader.AttributesNS のメソッド)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getQNameByName}@anchor{3e53}
@deffn {メソッド} AttributesNS.getQNameByName (name)

@code{(namespace, localname)} のペアに対応する修飾名を返します。
@end deffn

@geindex getQNames() (xml.sax.xmlreader.AttributesNS のメソッド)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getQNames}@anchor{3e54}
@deffn {メソッド} AttributesNS.getQNames ()

すべての属性の修飾名を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xml parsers expat --- Expat を使用した高速な XML 解析,,xml sax xmlreader --- XML パーサーのインターフェース,構造化マークアップツール
@anchor{library/pyexpat doc}@anchor{3e55}@anchor{library/pyexpat module-xml parsers expat}@anchor{12c}@anchor{library/pyexpat translation-repo}@anchor{3e56}@anchor{library/pyexpat xml-parsers-expat-fast-xml-parsing-using-expat}@anchor{3e57}
@subsection @code{xml.parsers.expat} --- Expat を使用した高速な XML 解析


@geindex module; xml.parsers.expat


__________________________________________________________________


@c Markup notes:
@c 
@c Many of the attributes of the XMLParser objects are callbacks.  Since
@c signature information must be presented, these are described using the method
@c directive.  Since they are attributes which are set by client code, in-text
@c references to these attributes should be marked using the :member: role.

@cartouche
@quotation 注釈 
If you need to parse untrusted or unauthenticated data, see
@ref{3ce9,,XML security}.
@end quotation
@end cartouche

@geindex Expat

The @code{xml.parsers.expat} module is a Python interface to the Expat
non-validating XML parser. The module provides a single extension type,
@code{xmlparser}, that represents the current state of an XML parser.  After
an @code{xmlparser} object has been created, various attributes of the object
can be set to handler functions.  When an XML document is then fed to the
parser, the handler functions are called for the character data and markup in
the XML document.

@geindex module;pyexpat

このモジュールでは、Expatパーザへのアクセスを提供するために @code{pyexpat} モジュールを使用します。 @code{pyexpat} モジュールの直接使用は撤廃されています。

このモジュールは、例外を一つと型オブジェクトを一つ提供しています:

@geindex ExpatError
@anchor{library/pyexpat xml parsers expat ExpatError}@anchor{1490}
@deffn {例外} xml.parsers.expat.ExpatError

Expat がエラーを報告したときに例外を送出します。 Expatのエラーを解釈する上での詳細な情報は、 @ref{3e58,,ExpatError 例外} を参照してください。
@end deffn

@geindex error
@anchor{library/pyexpat xml parsers expat error}@anchor{3e59}
@deffn {例外} xml.parsers.expat.error

@ref{1490,,ExpatError} の別名です。
@end deffn

@geindex XMLParserType (xml.parsers.expat モジュール)
@anchor{library/pyexpat xml parsers expat XMLParserType}@anchor{3e5a}
@deffn {データ} xml.parsers.expat.XMLParserType

@ref{3e5b,,ParserCreate()} 関数から返された戻り値の型を示します。
@end deffn

The @code{xml.parsers.expat} module contains two functions:

@geindex ErrorString() (xml.parsers.expat モジュール)
@anchor{library/pyexpat xml parsers expat ErrorString}@anchor{3e5c}
@deffn {の関数} xml.parsers.expat.ErrorString (errno)

与えられたエラー番号 `errno' を解説する文字列を返します。
@end deffn

@geindex ParserCreate() (xml.parsers.expat モジュール)
@anchor{library/pyexpat xml parsers expat ParserCreate}@anchor{3e5b}
@deffn {の関数} xml.parsers.expat.ParserCreate (encoding=None, namespace_separator=None)

新しい @code{xmlparser} オブジェクトを作成し、返します。 `encoding' が指定されていた場合、XMLデータで使われている文字列のエンコード名でなければなりません。 Expatは、Pythonのように多くのエンコードをサポートしておらず、またエンコーディングのレパートリを拡張することはできません; サポートするエンコードは、UTF-8, UTF-16, ISO-8859-1 (Latin1), ASCII です。 `encoding' @footnote{
XML 出力に含まれるエンコーディング文字列は適切な規格に従っていなければなりません。例えば、 "UTF-8" は有効ですが、 "UTF8" はそうではありません。@indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} と @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml} を参照してください。
} が指定されると、文書に対する明示的、非明示的なエンコード指定を上書き (override) します。
@anchor{library/pyexpat xmlparser-non-root}@anchor{3e5d}
Parsers created through @code{ParserCreate()} are called "root" parsers,
in the sense that they do not have any parent parser attached. Non-root
parsers are created by @ref{17ee,,parser.ExternalEntityParserCreate}.

Expat はオプションで XML 名前空間の処理を行うことができます。これは引数 `namespace_separator' に値を指定することで有効になります。この値は、1文字の文字列でなければなりません; 文字列が誤った長さを持つ場合には @ref{2ec,,ValueError} が送出されます (@code{None} は値の省略と見なされます)。名前空間の処理が可能なとき、名前空間に属する要素と属性が展開されます。要素のハンドラである @code{StartElementHandler} と @code{EndElementHandler} に渡された要素名は、名前空間の URI、名前空間の区切り文字、要素名のローカル部を連結したものになります。名前空間の区切り文字が 0 バイト (@code{chr(0)}) の場合、名前空間の URI とローカル部は区切り文字なしで連結されます。

たとえば、`namespace_separator' に空白文字(@code{' '})がセットされ、次のような文書が解析されるとします:

@example
<?xml version="1.0"?>
<root xmlns    = "http://default-namespace.org/"
      xmlns:py = "http://www.python.org/ns/">
  <py:elem1 />
  <elem2 xmlns="" />
</root>
@end example

@code{StartElementHandler} は各要素ごとに次のような文字列を受け取ります:

@example
http://default-namespace.org/ root
http://www.python.org/ns/ elem1
elem2
@end example

@code{pyexpat} が使っている @code{Expat} ライブラリの制限により、返される @code{xmlparser} インスタンスは単独の XML ドキュメントの解析にしか使えません。それぞれのドキュメントごとに別々のパーサのインスタンスを作るために @code{ParserCreate} を呼び出してください。
@end deffn


@subsubheading 参考



@table @asis

@item The Expat XML Parser@footnote{http://www.libexpat.org/}

Expatプロジェクトのホームページ。
@end table


@menu
* XMLParser オブジェクト: XMLParser オブジェクト<2>. 
* ExpatError 例外:: 
* 使用例: 使用例<35>. 
* 内容モデルの記述:: 
* Expat エラー定数:: 

@end menu

@node XMLParser オブジェクト<2>,ExpatError 例外,,xml parsers expat --- Expat を使用した高速な XML 解析
@anchor{library/pyexpat id2}@anchor{3e5e}@anchor{library/pyexpat xmlparser-objects}@anchor{17bb}
@subsubsection XMLParser オブジェクト


@code{xmlparser} オブジェクトは以下のようなメソッドを持ちます:

@geindex Parse() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser Parse}@anchor{3e5f}
@deffn {メソッド} xmlparser.Parse (data[, isfinal])

文字列 `data' の内容を解析し、解析されたデータを処理するための適切な関数を呼び出します。このメソッドを最後に呼び出す時は `isfinal' を真にしなければなりません; 単体ファイルを細切れに渡して解析出来ることを意味しますが、複数ファイルは扱えません。 `data' にはいつでも空の文字列を渡せます。
@end deffn

@geindex ParseFile() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser ParseFile}@anchor{3e60}
@deffn {メソッド} xmlparser.ParseFile (file)

`file' オブジェクトから読み込んだXMLデータを解析します。 `file' には @cite{read(nbytes)} メソッドのみが必要です。このメソッドはデータがなくなった場合に空文字列を返さねばなりません。。
@end deffn

@geindex SetBase() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser SetBase}@anchor{3e61}
@deffn {メソッド} xmlparser.SetBase (base)

(XML) 宣言中のシステム識別子中の相対 URI を解決するための、基底 URI を設定します。相対識別子の解決はアプリケーションに任されます: この値は関数 @ref{3e62,,ExternalEntityRefHandler()} や @ref{3e63,,NotationDeclHandler()}, @ref{3e64,,UnparsedEntityDeclHandler()} に引数 `base' としてそのまま渡されます。
@end deffn

@geindex GetBase() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser GetBase}@anchor{3e65}
@deffn {メソッド} xmlparser.GetBase ()

以前の @ref{3e61,,SetBase()} によって設定された基底 URI を文字列の形で返します。 @ref{3e61,,SetBase()} が呼ばれていないときには @code{None} を返します。
@end deffn

@geindex GetInputContext() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser GetInputContext}@anchor{3e66}
@deffn {メソッド} xmlparser.GetInputContext ()

現在のイベントを発生させた入力データを文字列として返します。データはテキストの入っているエンティティが持っているエンコードになります。イベントハンドラがアクティブでないときに呼ばれると、戻り値は @code{None} となります。
@end deffn

@geindex ExternalEntityParserCreate() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser ExternalEntityParserCreate}@anchor{17ee}
@deffn {メソッド} xmlparser.ExternalEntityParserCreate (context[, encoding])

親となるパーザで解析された内容が参照している、外部で解析されるエンティティを解析するために使える "子の" パーザを作成します。 `context' パラメータは、以下に記すように @ref{3e62,,ExternalEntityRefHandler()} ハンドラ関数に渡される文字列でなければなりません。子のパーザは @ref{3e67,,ordered_attributes}, @ref{3e68,,specified_attributes} が現在のパーザの値に設定されて生成されます。
@end deffn

@geindex SetParamEntityParsing() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser SetParamEntityParsing}@anchor{3e69}
@deffn {メソッド} xmlparser.SetParamEntityParsing (flag)

パラメータエンティティ (外部DTDサブセットを含む) の解析を制御します。 `flag' の有効な値は、 @code{XML_PARAM_ENTITY_PARSING_NEVER}, @code{XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE}, @code{XML_PARAM_ENTITY_PARSING_ALWAYS} です。 flag の設定をしたら true を返します。
@end deffn

@geindex UseForeignDTD() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser UseForeignDTD}@anchor{3e6a}
@deffn {メソッド} xmlparser.UseForeignDTD ([flag])

`flag' の値をデフォルトのtrueにすると、Expatは代わりのDTDをロードするため、すべての引数に @ref{885,,None} を設定して @ref{3e62,,ExternalEntityRefHandler} を呼び出します。XML文書が文書型定義を持っていなければ、 @ref{3e62,,ExternalEntityRefHandler} が呼び出しますが、 @ref{3e6b,,StartDoctypeDeclHandler} と @ref{3e6c,,EndDoctypeDeclHandler} は呼び出されません。

`flag' にfalseを与えると、メソッドが前回呼ばれた時のtrueの設定が解除されますが、他には何も起こりません。

このメソッドは @ref{3e5f,,Parse()} または @ref{3e60,,ParseFile()} メソッドが呼び出される前にだけ呼び出されます;これら2つのメソッドのどちらかが呼び出されたあとにメソッドが呼ばれると、 @ref{1b,,code} に定数 @code{errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]} が設定されて例外 @ref{1490,,ExpatError} が送出されます。
@end deffn

@geindex SetReparseDeferralEnabled() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser SetReparseDeferralEnabled}@anchor{579}
@deffn {メソッド} xmlparser.SetReparseDeferralEnabled (enabled)

@cartouche
@quotation 警告 
Calling @code{SetReparseDeferralEnabled(False)} has security implications,
as detailed below; please make sure to understand these consequences
prior to using the @code{SetReparseDeferralEnabled} method.
@end quotation
@end cartouche

Expat 2.6.0 introduced a security mechanism called "reparse deferral"
where instead of causing denial of service through quadratic runtime
from reparsing large tokens, reparsing of unfinished tokens is now delayed
by default until a sufficient amount of input is reached.
Due to this delay, registered handlers may — depending of the sizing of
input chunks pushed to Expat — no longer be called right after pushing new
input to the parser.  Where immediate feedback and taking over responsibility
of protecting against denial of service from large tokens are both wanted,
calling @code{SetReparseDeferralEnabled(False)} disables reparse deferral
for the current Expat parser instance, temporarily or altogether.
Calling @code{SetReparseDeferralEnabled(True)} allows re-enabling reparse
deferral.

Note that @ref{579,,SetReparseDeferralEnabled()} has been backported to some
prior releases of CPython as a security fix.  Check for availability of
@ref{579,,SetReparseDeferralEnabled()} using @ref{6f9,,hasattr()} if used in code
running across a variety of Python versions.


Added in version 3.13.

@end deffn

@geindex GetReparseDeferralEnabled() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser GetReparseDeferralEnabled}@anchor{578}
@deffn {メソッド} xmlparser.GetReparseDeferralEnabled ()

Returns whether reparse deferral is currently enabled for the given
Expat parser instance.


Added in version 3.13.

@end deffn

@code{xmlparser} objects have the following methods to mitigate some
common XML vulnerabilities.

@geindex SetAllocTrackerActivationThreshold() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser SetAllocTrackerActivationThreshold}@anchor{17b9}
@deffn {メソッド} xmlparser.SetAllocTrackerActivationThreshold (threshold, /)

Sets the number of allocated bytes of dynamic memory needed to activate
protection against disproportionate use of RAM.

By default, parser objects have an allocation activation threshold of 64 MiB,
or equivalently 67,108,864 bytes.

An @ref{1490,,ExpatError} is raised if this method is called on a
@ref{3e5d,,non-root} parser.
The corresponding @ref{3e6d,,lineno} and @ref{3e6e,,offset}
should not be used as they may have no special meaning.


Added in version 3.14.1.

@end deffn

@geindex SetAllocTrackerMaximumAmplification() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser SetAllocTrackerMaximumAmplification}@anchor{17ba}
@deffn {メソッド} xmlparser.SetAllocTrackerMaximumAmplification (max_factor, /)

Sets the maximum amplification factor between direct input and bytes
of dynamic memory allocated.

The amplification factor is calculated as @code{allocated / direct}
while parsing, where @code{direct} is the number of bytes read from
the primary document in parsing and @code{allocated} is the number
of bytes of dynamic memory allocated in the parser hierarchy.

The `max_factor' value must be a non-NaN @ref{196,,float} value greater than
or equal to 1.0. Amplification factors greater than 100.0 can be observed
near the start of parsing even with benign files in practice. In particular,
the activation threshold should be carefully chosen to avoid false positives.

By default, parser objects have a maximum amplification factor of 100.0.

An @ref{1490,,ExpatError} is raised if this method is called on a
@ref{3e5d,,non-root} parser or if `max_factor' is outside the valid range.
The corresponding @ref{3e6d,,lineno} and @ref{3e6e,,offset}
should not be used as they may have no special meaning.

@cartouche
@quotation 注釈 
The maximum amplification factor is only considered if the threshold
that can be adjusted by @ref{17b9,,SetAllocTrackerActivationThreshold()}
is exceeded.
@end quotation
@end cartouche


Added in version 3.14.1.

@end deffn

@code{xmlparser} オブジェクトは次のような属性を持ちます:

@geindex buffer_size (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser buffer_size}@anchor{3e6f}
@deffn {の属性} xmlparser.buffer_size

@ref{16db,,buffer_text} が真の時に使われるバッファのサイズです。この属性に新しい整数値を代入することで違うバッファサイズにできます。サイズが変えられるときにバッファはフラッシュされます。
@end deffn

@geindex buffer_text (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser buffer_text}@anchor{16db}
@deffn {の属性} xmlparser.buffer_text

Setting this to true causes the @code{xmlparser} object to buffer textual
content returned by Expat to avoid multiple calls to the
@ref{3e70,,CharacterDataHandler()} callback whenever possible.  This can improve
performance substantially since Expat normally breaks character data into chunks
at every line ending.  This attribute is false by default, and may be changed at
any time. Note that when it is false, data that does not contain newlines
may be chunked too.
@end deffn

@geindex buffer_used (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser buffer_used}@anchor{3e71}
@deffn {の属性} xmlparser.buffer_used

@ref{16db,,buffer_text} が利用可能なとき、バッファに保持されたバイト数です。これらのバイトはUTF-8でエンコードされたテキストを表します。この属性は @ref{16db,,buffer_text} が偽の時には意味がありません。
@end deffn

@geindex ordered_attributes (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser ordered_attributes}@anchor{3e67}
@deffn {の属性} xmlparser.ordered_attributes

この属性をゼロ以外の整数にすると、報告される(XMLノードの) 属性を辞書型ではなくリスト型にします。属性は文書のテキスト中の出現順で示されます。それぞれの属性は、2つのリストのエントリ: 属性名とその値、が与えられます。 (このモジュールの古いバージョンでも、同じフォーマットが使われています。) デフォルトでは、この属性はデフォルトでは偽となりますが、いつでも変更可能です。
@end deffn

@geindex specified_attributes (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser specified_attributes}@anchor{3e68}
@deffn {の属性} xmlparser.specified_attributes

ゼロ以外の整数にすると、パーザは文書のインスタンスで特定される属性だけを報告し、属性宣言から導出された属性は報告しないようになります。この属性が指定されたアプリケーションでは、XMLプロセッサの振る舞いに関する標準に従うために必要とされる (文書型) 宣言によって、どのような付加情報が利用できるのかということについて特に注意を払わなければなりません。デフォルトで、この属性は偽となりますが、いつでも変更可能です。
@end deffn

以下の属性には、 @code{xmlparser} オブジェクトで最も最近に起きたエラーに関する値が入っており、また @code{Parse()} または @code{ParseFile()} メソッドが @ref{1490,,xml.parsers.expat.ExpatError} 例外を送出した際にのみ正しい値となります。

@geindex ErrorByteIndex (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorByteIndex}@anchor{3e72}
@deffn {の属性} xmlparser.ErrorByteIndex

エラーが発生したバイトのインデクスです。
@end deffn

@geindex ErrorCode (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorCode}@anchor{3e73}
@deffn {の属性} xmlparser.ErrorCode

エラーを特定する数値によるコードです。この値は @ref{3e5c,,ErrorString()} に渡したり、 @code{errors} オブジェクトで定義された内容と比較できます。
@end deffn

@geindex ErrorColumnNumber (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorColumnNumber}@anchor{3e74}
@deffn {の属性} xmlparser.ErrorColumnNumber

エラーの発生したカラム番号です。
@end deffn

@geindex ErrorLineNumber (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorLineNumber}@anchor{3e75}
@deffn {の属性} xmlparser.ErrorLineNumber

エラーの発生した行番号です。
@end deffn

以下の属性は @code{xmlparser} オブジェクトがその時パースしている位置に関する値を保持しています。コールバックがパースイベントを報告している間、これらの値はイベントの生成した文字列の先頭の位置を指し示します。コールバックの外から参照された時には、（対応するコールバックであるかにかかわらず）直前のパースイベントの位置を示します。

@geindex CurrentByteIndex (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser CurrentByteIndex}@anchor{3e76}
@deffn {の属性} xmlparser.CurrentByteIndex

パーサへの入力の、現在のバイトインデックス。
@end deffn

@geindex CurrentColumnNumber (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser CurrentColumnNumber}@anchor{3e77}
@deffn {の属性} xmlparser.CurrentColumnNumber

パーサへの入力の、現在のカラム番号。
@end deffn

@geindex CurrentLineNumber (xml.parsers.expat.xmlparser の属性)
@anchor{library/pyexpat xml parsers expat xmlparser CurrentLineNumber}@anchor{3e78}
@deffn {の属性} xmlparser.CurrentLineNumber

パーサへの入力の、現在の行番号。
@end deffn

以下に指定可能なハンドラのリストを示します。 @code{xmlparser} オブジェクト `o' にハンドラを指定するには、 @code{o.handlername = func} を使用します。 `handlername' は、以下のリストに挙げた値をとらなければならず、また `func' は正しい数の引数を受理する呼び出し可能なオブジェクトでなければなりません。引数は特に明記しない限り、すべて文字列となります。

@geindex XmlDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser XmlDeclHandler}@anchor{3e79}
@deffn {メソッド} xmlparser.XmlDeclHandler (version, encoding, standalone)

XML 宣言が解析された時に呼ばれます。
XML宣言は XML 勧告の適用バージョン、文書テクストのエンコード、ならびに任意の "standalone" 宣言の (任意の) 宣言です。
`version' と `encoding' は文字列で、`standalone' は文書がスタンドアローンと宣言された場合は @code{1}、スタンドアローンでないと宣言された場合は @code{0}、スタンドアローン節がない場合は @code{-1} です。
Expat のバージョン 1.95.0 以降でのみ使用できます。
@end deffn

@geindex StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser StartDoctypeDeclHandler}@anchor{3e6b}
@deffn {メソッド} xmlparser.StartDoctypeDeclHandler (doctypeName, systemId, publicId, has_internal_subset)

Called when Expat begins parsing the document type declaration (@code{<!DOCTYPE
...}).  The `doctypeName' is provided exactly as presented.  The `systemId' and
`publicId' parameters give the system and public identifiers if specified, or
@code{None} if omitted.  `has_internal_subset' will be true if the document
contains an internal document declaration subset. This requires Expat version
1.2 or newer.
@end deffn

@geindex EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser EndDoctypeDeclHandler}@anchor{3e6c}
@deffn {メソッド} xmlparser.EndDoctypeDeclHandler ()

Expatが文書型宣言の解析を終えたときに呼び出されます。このハンドラには、Expat version 1.2以上が必要です。
@end deffn

@geindex ElementDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser ElementDeclHandler}@anchor{17b4}
@deffn {メソッド} xmlparser.ElementDeclHandler (name, model)

それぞれの要素型宣言ごとに呼び出されます。 `name' は要素型の名前であり、 `model' は内容モデル (content model) の表現です。
@end deffn

@geindex AttlistDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser AttlistDeclHandler}@anchor{3e7a}
@deffn {メソッド} xmlparser.AttlistDeclHandler (elname, attname, type, default, required)

ひとつの要素型で宣言される属性ごとに呼び出されます。属性リストの宣言が 3つの属性を宣言したとすると、このハンドラは各属性に1度ずつ、 3度呼び出されます。 `elname' は要素名であり、これに対して宣言が適用され、 `attname' が宣言された属性名となります。属性型は文字列で、 `type' として渡されます。取り得る値は、 @code{'CDATA'}, @code{'ID'}, @code{'IDREF'}, ... です。 `default' は、文書のインスタンスによって属性が指定されていないときに使用されるデフォルト値です。デフォルト値(@code{#IMPLIED} values)が存在しないときには @code{None} を与えます。文書のインスタンス中に属性値を与える必要のあるときには `required' が true になります。これにはExpat version 1.95.0 以上が必要です。
@end deffn

@geindex StartElementHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser StartElementHandler}@anchor{3e7b}
@deffn {メソッド} xmlparser.StartElementHandler (name, attributes)

要素の開始ごとに呼び出されます。
`name' は要素名を持つ文字列で、 `attributes' は要素の属性です。
@ref{3e67,,ordered_attributes} が真の場合これはリストです (詳細は @ref{3e67,,ordered_attributes} を参照してください)。
そうでなければ名前を値に対応させる辞書です。
@end deffn

@geindex EndElementHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser EndElementHandler}@anchor{3e7c}
@deffn {メソッド} xmlparser.EndElementHandler (name)

要素の終端を処理するごとに呼び出されます。
@end deffn

@geindex ProcessingInstructionHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser ProcessingInstructionHandler}@anchor{3e7d}
@deffn {メソッド} xmlparser.ProcessingInstructionHandler (target, data)

処理命令を処理するごとに呼び出されます。
@end deffn

@geindex CharacterDataHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser CharacterDataHandler}@anchor{3e70}
@deffn {メソッド} xmlparser.CharacterDataHandler (data)

Called for character data.  This will be called for normal character data, CDATA
marked content, and ignorable whitespace.  Applications which must distinguish
these cases can use the @ref{3e7e,,StartCdataSectionHandler},
@ref{3e7f,,EndCdataSectionHandler}, and @ref{17b4,,ElementDeclHandler} callbacks to
collect the required information. Note that the character data may be
chunked even if it is short and so you may receive more than one call to
@ref{3e70,,CharacterDataHandler()}. Set the @ref{16db,,buffer_text} instance attribute
to @code{True} to avoid that.
@end deffn

@geindex UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser UnparsedEntityDeclHandler}@anchor{3e64}
@deffn {メソッド} xmlparser.UnparsedEntityDeclHandler (entityName, base, systemId, publicId, notationName)

解析されていない (NDATA) エンティティ宣言を処理するために呼び出されます。このハンドラは Expat ライブラリのバージョン1.2のためだけに存在します; より最近のバージョンでは、代わりに @ref{3e80,,EntityDeclHandler} を使用してください (根底にある Expat ライブラリ内の関数は、撤廃されたものであると宣言されています)。
@end deffn

@geindex EntityDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser EntityDeclHandler}@anchor{3e80}
@deffn {メソッド} xmlparser.EntityDeclHandler (entityName, is_parameter_entity, value, base, systemId, publicId, notationName)

エンティティ宣言ごとに呼び出されます。パラメタと内部エンティティについて、 `value' はエンティティ宣言の宣言済みの内容を与える文字列となります; 外部エンティティの時には @code{None} となります。解析済みエンティティの場合、 `notationName' パラメタは @code{None} となり、解析されていないエンティティの時には記法 (notation) 名となります。 `is_parameter_entity' は、エンティティがパラメタエンティティの場合真に、一般エンティティ (general entitiy) の場合には偽になります (ほとんどのアプリケーションでは、一般エンティティのことしか気にする必要がありません)。このハンドラは Expat ライブラリのバージョン1.95.0 以降でのみ使用できます。
@end deffn

@geindex NotationDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser NotationDeclHandler}@anchor{3e63}
@deffn {メソッド} xmlparser.NotationDeclHandler (notationName, base, systemId, publicId)

記法の宣言 (notation declaration) で呼び出されます。 `notationName', `base', `systemId', および `publicId' を与える場合、文字列にします。public な識別子が省略された場合、 `publicId' は @code{None} になります。
@end deffn

@geindex StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser StartNamespaceDeclHandler}@anchor{3e81}
@deffn {メソッド} xmlparser.StartNamespaceDeclHandler (prefix, uri)

要素が名前空間宣言を含んでいる場合に呼び出されます。名前空間宣言は、宣言が配置されている要素に対して @ref{3e7b,,StartElementHandler} が呼び出される前に処理されます。
@end deffn

@geindex EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser EndNamespaceDeclHandler}@anchor{3e82}
@deffn {メソッド} xmlparser.EndNamespaceDeclHandler (prefix)

名前空間宣言を含んでいたエレメントの終了タグに到達したときに呼び出されます。このハンドラは、要素に関する名前空間宣言ごとに、 @ref{3e81,,StartNamespaceDeclHandler} とは逆の順番で一度だけ呼び出され、各名前空間宣言のスコープが開始されたことを示します。このハンドラは、要素が終了する際、対応する @ref{3e7c,,EndElementHandler} が呼ばれた後に呼び出されます。
@end deffn

@geindex CommentHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser CommentHandler}@anchor{3e83}
@deffn {メソッド} xmlparser.CommentHandler (data)

コメントで呼び出されます。 `data' はコメントのテキストで、先頭の '@code{<!-} @code{-}' と末尾の '@code{-} @code{->}' を除きます。
@end deffn

@geindex StartCdataSectionHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser StartCdataSectionHandler}@anchor{3e7e}
@deffn {メソッド} xmlparser.StartCdataSectionHandler ()

CDATA セクションの開始時に呼び出されます。CDATA セクションの構文的な開始と終了位置を識別できるようにするには、このハンドラと @ref{3e7f,,EndCdataSectionHandler} が必要です。
@end deffn

@geindex EndCdataSectionHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser EndCdataSectionHandler}@anchor{3e7f}
@deffn {メソッド} xmlparser.EndCdataSectionHandler ()

CDATA セクションの終了時に呼び出されます。
@end deffn

@geindex DefaultHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser DefaultHandler}@anchor{3e84}
@deffn {メソッド} xmlparser.DefaultHandler (data)

XML 文書中で、適用可能なハンドラが指定されていない文字すべてに対して呼び出されます。この文字とは、検出されたことが報告されるが、ハンドラは指定されていないようなコンストラクト (construct) の一部である文字を意味します。
@end deffn

@geindex DefaultHandlerExpand() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser DefaultHandlerExpand}@anchor{3e85}
@deffn {メソッド} xmlparser.DefaultHandlerExpand (data)

@ref{3e84,,DefaultHandler()} と同じですが、内部エンティティの展開を禁止しません。エンティティ参照はデフォルトハンドラに渡されません。
@end deffn

@geindex NotStandaloneHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser NotStandaloneHandler}@anchor{3e86}
@deffn {メソッド} xmlparser.NotStandaloneHandler ()

XML 文書がスタンドアロンの文書として宣言されていない場合に呼び出されます。外部サブセットやパラメタエンティティへの参照が存在するが、XML 宣言が XML 宣言中で standalone 変数を @code{yes} に設定していない場合に起きます。このハンドラが @code{0} を返すと、パーザは @code{XML_ERROR_NOT_STANDALONE} を発生させます。このハンドラが設定されていなければ、パーザは前述の事態で例外を送出しません。
@end deffn

@geindex ExternalEntityRefHandler() (xml.parsers.expat.xmlparser のメソッド)
@anchor{library/pyexpat xml parsers expat xmlparser ExternalEntityRefHandler}@anchor{3e62}
@deffn {メソッド} xmlparser.ExternalEntityRefHandler (context, base, systemId, publicId)

@cartouche
@quotation 警告 
Implementing a handler that accesses local files and/or the network
may create a vulnerability to
external entity attacks@footnote{https://en.wikipedia.org/wiki/XML_external_entity_attack}
if @code{xmlparser} is used with user-provided XML content.
Please reflect on your threat model@footnote{https://en.wikipedia.org/wiki/Threat_model}
before implementing this handler.
@end quotation
@end cartouche

外部エンティティの参照時に呼び出されます。 `base' は現在の基底 (base) で、以前の @ref{3e61,,SetBase()} で設定された値になっています。 public、および system の識別子である、 `systemId' と `publicId' が指定されている場合、値は文字列です; public 識別子が指定されていない場合、 `publicId' は @code{None} になります。 `context' の値は不明瞭なものであり、以下に記述するようにしか使ってはなりません。

外部エンティティが解析されるようにするには、このハンドラを実装しなければなりません。このハンドラは、 @code{ExternalEntityParserCreate(context)} を使って適切なコールバックを指定し、子パーザを生成して、エンティティを解析する役割を担います。このハンドラは整数を返さなければなりません; @code{0} を返した場合、パーザは @code{XML_ERROR_EXTERNAL_ENTITY_HANDLING} エラーを送出します。そうでない場合、解析を継続します。

このハンドラが与えられておらず、 @ref{3e84,,DefaultHandler} コールバックが指定されていれば、外部エンティティは @ref{3e84,,DefaultHandler} で報告されます。
@end deffn

@node ExpatError 例外,使用例<35>,XMLParser オブジェクト<2>,xml parsers expat --- Expat を使用した高速な XML 解析
@anchor{library/pyexpat expaterror-exceptions}@anchor{3e87}@anchor{library/pyexpat expaterror-objects}@anchor{3e58}
@subsubsection ExpatError 例外


@ref{1490,,ExpatError} 例外はいくつかの興味深い属性を備えています:

@geindex code (xml.parsers.expat.ExpatError の属性)
@anchor{library/pyexpat xml parsers expat ExpatError code}@anchor{3e88}
@deffn {の属性} ExpatError.code

特定のエラーに対する Expat の内部エラー番号です。
@ref{3e89,,errors.messages} 辞書はこれらのエラー番号を Expat のエラーメッセージに対応させます。
例えば:

@example
from xml.parsers.expat import ParserCreate, ExpatError, errors

p = ParserCreate()
try:
    p.Parse(some_xml_document)
except ExpatError as err:
    print("Error:", errors.messages[err.code])
@end example

@ref{12d,,errors} モジュールはエラーメッセージ定数と、それらのメッセージをエラーコードに対応させる辞書 @ref{3e8a,,codes} も提供しています。以下を参照してください。
@end deffn

@geindex lineno (xml.parsers.expat.ExpatError の属性)
@anchor{library/pyexpat xml parsers expat ExpatError lineno}@anchor{3e6d}
@deffn {の属性} ExpatError.lineno

エラーが検出された場所の行番号です。最初の行の番号は @code{1} です。
@end deffn

@geindex offset (xml.parsers.expat.ExpatError の属性)
@anchor{library/pyexpat xml parsers expat ExpatError offset}@anchor{3e6e}
@deffn {の属性} ExpatError.offset

エラーが発生した場所の行内でのオフセットです。最初のカラムの番号は @code{0} です。
@end deffn

@node 使用例<35>,内容モデルの記述,ExpatError 例外,xml parsers expat --- Expat を使用した高速な XML 解析
@anchor{library/pyexpat example}@anchor{3e8b}@anchor{library/pyexpat expat-example}@anchor{3e8c}
@subsubsection 使用例


以下のプログラムでは、与えられた引数を出力するだけの三つのハンドラを定義しています。

@example
import xml.parsers.expat

# 3 handler functions
def start_element(name, attrs):
    print('Start element:', name, attrs)
def end_element(name):
    print('End element:', name)
def char_data(data):
    print('Character data:', repr(data))

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

p.Parse("""<?xml version="1.0"?>
<parent id="top"><child1 name="paul">Text goes here</child1>
<child2 name="fred">More text</child2>
</parent>""", 1)
@end example

このプログラムの出力は以下のようになります:

@example
Start element: parent @{'id': 'top'@}
Start element: child1 @{'name': 'paul'@}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 @{'name': 'fred'@}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent
@end example

@node 内容モデルの記述,Expat エラー定数,使用例<35>,xml parsers expat --- Expat を使用した高速な XML 解析
@anchor{library/pyexpat content-model-descriptions}@anchor{3e8d}@anchor{library/pyexpat expat-content-models}@anchor{3e8e}@anchor{library/pyexpat module-xml parsers expat model}@anchor{12e}
@subsubsection 内容モデルの記述


@geindex module; xml.parsers.expat.model

内容モデルは入れ子になったタプルを使って記述されています。各タプルには以下の 4 つの値が収められています: 型、限定詞 (quantifier)、名前、そして子のタプル。子のタプルは単に内容モデルを記述したものです。

The values of the first two fields are constants defined in the
@code{xml.parsers.expat.model} module.  These constants can be collected in two
groups: the model type group and the quantifier group.

以下にモデル型グループにおける定数を示します:


@deffn {データ} xml.parsers.expat.model.XML_CTYPE_ANY

モデル名で指定された要素は @code{ANY} の内容モデルを持つと宣言されます。
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CTYPE_CHOICE

指定されたエレメントはいくつかのオプションから選択できるようになっています; @code{(A | B | C)} のような内容モデルで用いられます。
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CTYPE_EMPTY

@code{EMPTY} であると宣言されている要素はこのモデル型を持ちます。
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CTYPE_MIXED
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CTYPE_NAME
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CTYPE_SEQ

順々に続くようなモデルの系列を表すモデルがこのモデル型で表されます。 @code{(A, B, C)} のようなモデルで用いられます。
@end deffn

限定子グループにおける定数を以下に示します:


@deffn {データ} xml.parsers.expat.model.XML_CQUANT_NONE

修飾子 (modifier) が指定されていません。従って @code{A} のように、厳密に一つだけです。
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CQUANT_OPT

このモデルはオプションです: @code{A?} のように、一つか全くないかです。
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CQUANT_PLUS

このモデルは (@code{A+} のように) 一つかそれ以上あります。
@end deffn


@deffn {データ} xml.parsers.expat.model.XML_CQUANT_REP

このモデルは @code{A*} のようにゼロ回以上あります。
@end deffn

@node Expat エラー定数,,内容モデルの記述,xml parsers expat --- Expat を使用した高速な XML 解析
@anchor{library/pyexpat expat-error-constants}@anchor{3e8f}@anchor{library/pyexpat expat-errors}@anchor{3e90}@anchor{library/pyexpat module-xml parsers expat errors}@anchor{12d}
@subsubsection Expat エラー定数


@geindex module; xml.parsers.expat.errors

The following constants are provided in the @code{xml.parsers.expat.errors}
module.  These constants are useful in interpreting some of the attributes of
the @code{ExpatError} exception objects raised when an error has occurred.
Since for backwards compatibility reasons, the constants' value is the error
`message' and not the numeric error `code', you do this by comparing its
@ref{1b,,code} attribute with
@code{errors.codes[errors.XML_ERROR_@var{CONSTANT_NAME}]}.

@code{errors} モジュールには以下の属性があります:

@geindex codes (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors codes}@anchor{3e8a}
@deffn {データ} xml.parsers.expat.errors.codes

文字列の記述をエラーコードに対応させる辞書です。


Added in version 3.2.

@end deffn

@geindex messages (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors messages}@anchor{3e89}
@deffn {データ} xml.parsers.expat.errors.messages

数値的なエラーコードを文字列の記述に対応させる辞書です。


Added in version 3.2.

@end deffn

@geindex XML_ERROR_ASYNC_ENTITY (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ASYNC_ENTITY}@anchor{3e91}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY
@end deffn

@geindex XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF}@anchor{3e92}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF

属性値中のエンティティ参照が、内部エンティティではなく外部エンティティを参照しました。
@end deffn

@geindex XML_ERROR_BAD_CHAR_REF (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_BAD_CHAR_REF}@anchor{3e93}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF

文字参照が、XML では正しくない (illegal) 文字を参照しました (例えば @code{0} や '@code{&#0;}')。
@end deffn

@geindex XML_ERROR_BINARY_ENTITY_REF (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_BINARY_ENTITY_REF}@anchor{3e94}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF

エンティティ参照が、記法 (notation) つきで宣言されているエンティティを参照したため、解析できません。
@end deffn

@geindex XML_ERROR_DUPLICATE_ATTRIBUTE (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_DUPLICATE_ATTRIBUTE}@anchor{3e95}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE

一つの属性が一つの開始タグ内に一度より多く使われています。
@end deffn

@geindex XML_ERROR_INCORRECT_ENCODING (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_INCORRECT_ENCODING}@anchor{3e96}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING
@end deffn

@geindex XML_ERROR_INVALID_TOKEN (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_INVALID_TOKEN}@anchor{3e97}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN

入力されたバイトが文字に適切に関連付けできない際に送出されます; 例えば、UTF-8 入力ストリームにおける NUL バイト (値 @code{0}) などです。
@end deffn

@geindex XML_ERROR_JUNK_AFTER_DOC_ELEMENT (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_JUNK_AFTER_DOC_ELEMENT}@anchor{3e98}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT

空白以外の何かがドキュメント要素の後にあります。
@end deffn

@geindex XML_ERROR_MISPLACED_XML_PI (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_MISPLACED_XML_PI}@anchor{3e99}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI

入力データの先頭以外の場所に XML 定義が見つかりました。
@end deffn

@geindex XML_ERROR_NO_ELEMENTS (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NO_ELEMENTS}@anchor{3e9a}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS

この文書には要素がありません (XML では全ての文書は確実に最上位の要素を正確に一つ持たなければなりません)。
@end deffn

@geindex XML_ERROR_NO_MEMORY (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NO_MEMORY}@anchor{3e9b}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_NO_MEMORY

Expat が内部メモリを確保できませんでした。
@end deffn

@geindex XML_ERROR_PARAM_ENTITY_REF (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_PARAM_ENTITY_REF}@anchor{3e9c}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF

パラメータエンティティが許可されていない場所で見つかりました。
@end deffn

@geindex XML_ERROR_PARTIAL_CHAR (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_PARTIAL_CHAR}@anchor{3e9d}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR

入力に不完全な文字が見つかりました。
@end deffn

@geindex XML_ERROR_RECURSIVE_ENTITY_REF (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_RECURSIVE_ENTITY_REF}@anchor{3e9e}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF

エンティティ参照中に、同じエンティティへの別の参照が入っていました; おそらく違う名前で参照しているか、間接的に参照しています。
@end deffn

@geindex XML_ERROR_SYNTAX (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_SYNTAX}@anchor{3e9f}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_SYNTAX

何らかの仕様化されていない構文エラーに遭遇しました。
@end deffn

@geindex XML_ERROR_TAG_MISMATCH (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_TAG_MISMATCH}@anchor{3ea0}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH

終了タグが最も内側で開かれている開始タグに一致しません。
@end deffn

@geindex XML_ERROR_UNCLOSED_TOKEN (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_TOKEN}@anchor{3ea1}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN

何らかの (開始タグのような) トークンが閉じられないまま、ストリームの終端や次のトークンに遭遇しました。
@end deffn

@geindex XML_ERROR_UNDEFINED_ENTITY (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNDEFINED_ENTITY}@anchor{3ea2}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY

定義されていないエンティティへの参照が行われました。
@end deffn

@geindex XML_ERROR_UNKNOWN_ENCODING (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNKNOWN_ENCODING}@anchor{3ea3}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING

ドキュメントのエンコードが Expat でサポートされていません。
@end deffn

@geindex XML_ERROR_UNCLOSED_CDATA_SECTION (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_CDATA_SECTION}@anchor{3ea4}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION

CDATAセクションが閉じられていません。
@end deffn

@geindex XML_ERROR_EXTERNAL_ENTITY_HANDLING (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_EXTERNAL_ENTITY_HANDLING}@anchor{3ea5}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING
@end deffn

@geindex XML_ERROR_NOT_STANDALONE (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NOT_STANDALONE}@anchor{3ea6}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE

XML文書が "standalone" だと宣言されており @code{NotStandaloneHandler} が設定され @code{0} が返されているにもかかわらず、パーサは "standalone" ではないと判別しました。
@end deffn

@geindex XML_ERROR_UNEXPECTED_STATE (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNEXPECTED_STATE}@anchor{3ea7}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE
@end deffn

@geindex XML_ERROR_ENTITY_DECLARED_IN_PE (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ENTITY_DECLARED_IN_PE}@anchor{3ea8}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE
@end deffn

@geindex XML_ERROR_FEATURE_REQUIRES_XML_DTD (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_FEATURE_REQUIRES_XML_DTD}@anchor{3ea9}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD

An operation was requested that requires DTD support to be compiled in, but
Expat was configured without DTD support.  This should never be reported by a
standard build of the @code{xml.parsers.expat} module.
@end deffn

@geindex XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING}@anchor{3eaa}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING

パースが始まったあとで動作の変更が要求されました。これはパースが開始される前にのみ変更可能です。（現在のところ） @code{UseForeignDTD()} によってのみ送出されます。
@end deffn

@geindex XML_ERROR_UNBOUND_PREFIX (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNBOUND_PREFIX}@anchor{3eab}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX

名前空間の処理を有効すると宣言されていないプレフィックスが見つかります。
@end deffn

@geindex XML_ERROR_UNDECLARING_PREFIX (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNDECLARING_PREFIX}@anchor{3eac}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX

XML文書はプレフィックスに対応した名前空間宣言を削除しようとしました。
@end deffn

@geindex XML_ERROR_INCOMPLETE_PE (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_INCOMPLETE_PE}@anchor{3ead}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE

パラメータエンティティは不完全なマークアップを含んでいます。
@end deffn

@geindex XML_ERROR_XML_DECL (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_XML_DECL}@anchor{3eae}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_XML_DECL

XML文書中に要素がありません。
@end deffn

@geindex XML_ERROR_TEXT_DECL (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_TEXT_DECL}@anchor{3eaf}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_TEXT_DECL

外部エンティティ中のテキスト宣言にエラーがあります。
@end deffn

@geindex XML_ERROR_PUBLICID (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_PUBLICID}@anchor{3eb0}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_PUBLICID

パブリックID中に許可されていない文字があります。
@end deffn

@geindex XML_ERROR_SUSPENDED (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_SUSPENDED}@anchor{3eb1}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_SUSPENDED

要求された操作は一時停止されたパーサで行われていますが、許可されていない操作です。このエラーは追加の入力を行なおうとしている場合、もしくはパーサが停止しようとしている場合にも送出されます。
@end deffn

@geindex XML_ERROR_NOT_SUSPENDED (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NOT_SUSPENDED}@anchor{3eb2}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED

パーサを一時停止しようとしましたが、停止されませんでした。
@end deffn

@geindex XML_ERROR_ABORTED (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ABORTED}@anchor{3eb3}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_ABORTED

Pythonアプリケーションには通知されません。
@end deffn

@geindex XML_ERROR_FINISHED (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_FINISHED}@anchor{3eb4}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_FINISHED

要求された操作で、パース対象となる入力が完了したと判断しましたが、入力は受理されませんでした。このエラーは追加の入力を行なおうとしている場合、もしくはパーサが停止しようとしている場合に送出されます。
@end deffn

@geindex XML_ERROR_SUSPEND_PE (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_SUSPEND_PE}@anchor{3eb5}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE
@end deffn

@geindex XML_ERROR_RESERVED_PREFIX_XML (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_RESERVED_PREFIX_XML}@anchor{3eb6}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_RESERVED_PREFIX_XML

An attempt was made to
undeclare reserved namespace prefix @code{xml}
or to bind it to another namespace URI.
@end deffn

@geindex XML_ERROR_RESERVED_PREFIX_XMLNS (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_RESERVED_PREFIX_XMLNS}@anchor{3eb7}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_RESERVED_PREFIX_XMLNS

An attempt was made to declare or undeclare reserved namespace prefix @code{xmlns}.
@end deffn

@geindex XML_ERROR_RESERVED_NAMESPACE_URI (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_RESERVED_NAMESPACE_URI}@anchor{3eb8}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_RESERVED_NAMESPACE_URI

An attempt was made to bind the URI of one the reserved namespace
prefixes @code{xml} and @code{xmlns} to another namespace prefix.
@end deffn

@geindex XML_ERROR_INVALID_ARGUMENT (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_INVALID_ARGUMENT}@anchor{3eb9}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_INVALID_ARGUMENT

Pythonアプリケーションには通知されません。
@end deffn

@geindex XML_ERROR_NO_BUFFER (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NO_BUFFER}@anchor{3eba}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_NO_BUFFER

Pythonアプリケーションには通知されません。
@end deffn

@geindex XML_ERROR_AMPLIFICATION_LIMIT_BREACH (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_AMPLIFICATION_LIMIT_BREACH}@anchor{3ebb}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_AMPLIFICATION_LIMIT_BREACH

The limit on input amplification factor (from DTD and entities)
has been breached.
@end deffn

@geindex XML_ERROR_NOT_STARTED (xml.parsers.expat.errors モジュール)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NOT_STARTED}@anchor{18d3}
@deffn {データ} xml.parsers.expat.errors.XML_ERROR_NOT_STARTED

The parser was tried to be stopped or suspended before it started.


Added in version 3.14.

@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node インターネットプロトコルとサポート,マルチメディアサービス,構造化マークアップツール,Python 標準ライブラリ
@anchor{library/internet doc}@anchor{3ebc}@anchor{library/internet internet}@anchor{3ebd}@anchor{library/internet internet-protocols-and-support}@anchor{3ebe}@anchor{library/internet translation-repo}@anchor{3ebf}
@section インターネットプロトコルとサポート


@geindex WWW
@geindex Internet
@geindex World Wide Web

@geindex module;socket

この章で記述されるモジュールは、インターネットプロトコルを実装し、関連技術をサポートします。それらは全てPythonで実装されています。これらのモジュールの大部分は、システム依存のモジュール @ref{d1,,socket} が存在することが必要ですが、これは現在ではほとんどの一般的なプラットフォーム上でサポートされています。ここに概観を示します:

@menu
* webbrowser: webbrowser --- 便利なウェブブラウザコントローラー. 便利なウェブブラウザコントローラー
* wsgiref: wsgiref --- WSGI ユーティリティとリファレンス実装. WSGI ユーティリティとリファレンス実装
* urllib: urllib --- URL を扱うモジュール群. URL を扱うモジュール群
* urllib.request: urllib request --- URL を開くための大規模なライブラリ. URL を開くための大規模なライブラリ
* urllib.response: urllib response --- Response classes used by urllib. Response classes used by urllib
* urllib.parse: urllib parse --- URL を構成要素に解析する. URL を構成要素に解析する
* urllib.error: urllib error --- urllib request によって送出される例外クラス. urllib.request によって送出される例外クラス
* urllib.robotparser: urllib robotparser --- robots txt 用のパーサー. robots.txt 用のパーサー
* http: http --- HTTP モジュール群. HTTP モジュール群
* http.client: http client --- HTTP プロトコルクライアント. HTTP プロトコルクライアント
* ftplib: ftplib --- FTP プロトコルクライアント. FTP プロトコルクライアント
* poplib: poplib --- POP3 プロトコルクライアント. POP3 プロトコルクライアント
* imaplib: imaplib --- IMAP4 プロトコルクライアント. IMAP4 プロトコルクライアント
* smtplib: smtplib --- SMTP プロトコルクライアント. SMTP プロトコルクライアント
* uuid: uuid --- RFC 9562 に基づく UUID オブジェクト. RFC 9562 に基づく UUID オブジェクト
* socketserver: socketserver --- ネットワークサーバーのフレームワーク. ネットワークサーバーのフレームワーク
* http.server: http server --- HTTP サーバー. HTTP サーバー
* http.cookies: http cookies --- HTTP の状態管理. HTTP の状態管理
* http.cookiejar: http cookiejar --- HTTP クライアント用の Cookie 処理. HTTP クライアント用の Cookie 処理
* xmlrpc: xmlrpc --- XMLRPC サーバーとクライアントモジュール群. XMLRPC サーバーとクライアントモジュール群
* xmlrpc.client: xmlrpc client --- XML-RPC クライアントアクセス. XML-RPC クライアントアクセス
* xmlrpc.server: xmlrpc server --- 基本的な XML-RPC サーバー. 基本的な XML-RPC サーバー
* ipaddress: ipaddress --- IPv4/IPv6 操作ライブラリ. IPv4/IPv6 操作ライブラリ

@end menu

@node webbrowser --- 便利なウェブブラウザコントローラー,wsgiref --- WSGI ユーティリティとリファレンス実装,,インターネットプロトコルとサポート
@anchor{library/webbrowser doc}@anchor{3ec0}@anchor{library/webbrowser module-webbrowser}@anchor{11b}@anchor{library/webbrowser webbrowser-convenient-web-browser-controller}@anchor{3ec1}
@subsection @code{webbrowser} --- 便利なウェブブラウザコントローラー


@geindex module; webbrowser

`ソースコード:' Lib/webbrowser.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/webbrowser.py}


__________________________________________________________________


The @code{webbrowser} module provides a high-level interface to allow displaying
web-based documents to users. Under most circumstances, simply calling the
@ref{1889,,open()} function from this module will do the right thing.

Unixでは、X11上でグラフィカルなブラウザが選択されますが、グラフィカルなブラウザが利用できなかったり、X11が利用できない場合はテキストモードのブラウザが使われます。もしテキストモードのブラウザが使われたら、ユーザがブラウザから抜け出すまでプロセスの呼び出しはブロックされます。

If the environment variable 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} exists, it is interpreted as the
@ref{2134,,os.pathsep}-separated list of browsers to try ahead of the platform
defaults.  When the value of a list part contains the string @code{%s}, then it is
interpreted as a literal browser command line to be used with the argument URL
substituted for @code{%s}; if the value is a single word that refers to one of the
already registered browsers this browser is added to the front of the search list;
if the part does not contain @code{%s}, it is simply interpreted as the name of the
browser to launch. @footnote{
ここでブラウザの名前が絶対パスで書かれていない場合は 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} 環境変数で与えられたディレクトリから探し出されます。
}


バージョン 3.14 で変更: The 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} variable can now also be used to reorder the list of
platform defaults. This is particularly useful on macOS where the platform
defaults do not refer to command-line tools on 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}.


非UnixプラットフォームあるいはUnix上でリモートブラウザが利用可能な場合、制御プロセスはユーザがブラウザを終了するのを待ちませんが、ディスプレイにブラウザのウィンドウを表示させたままにします。Unix上でリモートブラウザが利用可能でない場合、制御プロセスは新しいブラウザを立ち上げ、待ちます。

On iOS, the 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} environment variable, as well as any arguments
controlling autoraise, browser preference, and new tab/window creation will be
ignored. Web pages will `always' be opened in the user's preferred browser, in
a new tab, with the browser being brought to the foreground. The use of the
@code{webbrowser} module on iOS requires the @ref{2e,,ctypes} module. If
@ref{2e,,ctypes} isn't available, calls to @ref{1889,,open()} will fail.

@menu
* コマンドライン・インターフェース: コマンドライン・インターフェース<6>. 
* Browser controller objects:: 

@end menu

@node コマンドライン・インターフェース<6>,Browser controller objects,,webbrowser --- 便利なウェブブラウザコントローラー
@anchor{library/webbrowser command-line-interface}@anchor{3ec2}@anchor{library/webbrowser webbrowser-cli}@anchor{3ec3}
@subsubsection コマンドライン・インターフェース


@code{webbrowser} のスクリプトは、モジュールのコマンドラインインターフェースとして利用可能です。これは引数として URL を受け入れます。また、次のオプションのパラメーターを受け入れます。

@geindex webbrowser コマンドラインオプション; -n
@geindex webbrowser コマンドラインオプション; --new-window
@anchor{library/webbrowser cmdoption-webbrowser-n}@anchor{3ec4}@anchor{library/webbrowser cmdoption-webbrowser-new-window}@anchor{3ec5}
@deffn {Option} @w{-}n, @w{-}@w{-}new@w{-}window

Opens the URL in a new browser window, if possible.
@end deffn

@geindex webbrowser コマンドラインオプション; -t
@geindex webbrowser コマンドラインオプション; --new-tab
@anchor{library/webbrowser cmdoption-webbrowser-t}@anchor{3ec6}@anchor{library/webbrowser cmdoption-webbrowser-new-tab}@anchor{3ec7}
@deffn {Option} @w{-}t, @w{-}@w{-}new@w{-}tab

Opens the URL in a new browser tab.
@end deffn

The options are, naturally, mutually exclusive.  Usage example:

@example
python -m webbrowser -t "https://www.python.org"
@end example

@ref{213f,,Availability}: not WASI, not Android.

以下の例外が定義されています:

@geindex Error
@anchor{library/webbrowser webbrowser Error}@anchor{3ec8}
@deffn {例外} webbrowser.Error

ブラウザのコントロールエラーが起こると発生する例外。
@end deffn

以下の関数が定義されています:

@geindex open() (webbrowser モジュール)
@anchor{library/webbrowser webbrowser open}@anchor{1889}
@deffn {の関数} webbrowser.open (url, new=0, autoraise=True)

デフォルトのブラウザで `url' を表示します。`new' が 0 なら、`url' はブラウザの今までと同じウィンドウで開きます。`new' が 1 なら、可能であればブラウザの新しいウィンドウが開きます。`new' が 2 なら、可能であればブラウザの新しいタブが開きます。`autoraise' が @code{True} なら、可能であればウィンドウが前面に表示されます（多くのウィンドウマネージャではこの変数の設定に関わらず、前面に表示されます）。

Returns @code{True} if a browser was successfully launched, @code{False} otherwise.

幾つかのプラットフォームにおいて、ファイル名をこの関数で開こうとすると、OSによって関連付けられたプログラムが起動されます。しかし、この動作はポータブルではありませんし、サポートされていません。

引数 @code{url} を指定して @ref{1c6e,,監査イベント} @code{webbrowser.open} を送出します。
@end deffn

@geindex open_new() (webbrowser モジュール)
@anchor{library/webbrowser webbrowser open_new}@anchor{3ec9}
@deffn {の関数} webbrowser.open_new (url)

可能であれば、デフォルトブラウザの新しいウィンドウで `url' を開きますが、そうでない場合はブラウザのただ１つのウィンドウで `url' を開きます。

Returns @code{True} if a browser was successfully launched, @code{False} otherwise.
@end deffn

@geindex open_new_tab() (webbrowser モジュール)
@anchor{library/webbrowser webbrowser open_new_tab}@anchor{3eca}
@deffn {の関数} webbrowser.open_new_tab (url)

可能であれば、デフォルトブラウザの新しいページ(「タブ」)で `url' を開きますが、そうでない場合は @ref{3ec9,,open_new()} と同様に振る舞います。

Returns @code{True} if a browser was successfully launched, @code{False} otherwise.
@end deffn

@geindex get() (webbrowser モジュール)
@anchor{library/webbrowser webbrowser get}@anchor{3ecb}
@deffn {の関数} webbrowser.get (using=None)

ブラウザの種類 `using' のコントローラーオブジェクトを返します。もし `using' が @code{None} なら、呼び出した環境に適したデフォルトブラウザのコントローラーを返します。
@end deffn

@geindex register() (webbrowser モジュール)
@anchor{library/webbrowser webbrowser register}@anchor{3ecc}
@deffn {の関数} webbrowser.register (name, constructor, instance=None, *, preferred=False)

ブラウザの種類 `name' を登録します。ブラウザの種類が登録されたら、 @ref{3ecb,,get()} でそのブラウザのコントローラーを呼び出すことができます。 `instance' が指定されなかったり、 @code{None} なら、インスタンスが必要な時には `constructor' がパラメータなしに呼び出されて作られます。 `instance' が指定されたら、 `constructor' は呼び出されないので、 @code{None} でかまいません。

`preferred' を @code{True} に設定すると、 @ref{3ecb,,get()} の引数無しの呼び出しの結果が優先的にこのブラウザになります。
そうでない場合は、この関数は、変数 
@geindex BROWSER
@geindex 環境変数; BROWSER
@code{BROWSER} を設定するか、 @ref{3ecb,,get()} を空文字列ではない、宣言したハンドラの名前と一致する引数とともに呼び出すときにだけ、役に立ちます。


バージョン 3.7 で変更: `preferred' キーワード専用引数が追加されました。

@end deffn

いくつかの種類のブラウザがあらかじめ定義されています。このモジュールで定義されている、関数 @ref{3ecb,,get()} に与えるブラウザの名前と、それぞれのコントローラークラスのインスタンスを以下の表に示します。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

Type Name

@tab

Class Name

@tab

注釈

@item

@code{'mozilla'}

@tab

@code{Mozilla('mozilla')}

@tab

@item

@code{'firefox'}

@tab

@code{Mozilla('mozilla')}

@tab

@item

@code{'epiphany'}

@tab

@code{Epiphany('epiphany')}

@tab

@item

@code{'kfmclient'}

@tab

@code{Konqueror()}

@tab

(1)

@item

@code{'konqueror'}

@tab

@code{Konqueror()}

@tab

(1)

@item

@code{'kfm'}

@tab

@code{Konqueror()}

@tab

(1)

@item

@code{'opera'}

@tab

@code{Opera()}

@tab

@item

@code{'links'}

@tab

@code{GenericBrowser('links')}

@tab

@item

@code{'elinks'}

@tab

@code{Elinks('elinks')}

@tab

@item

@code{'lynx'}

@tab

@code{GenericBrowser('lynx')}

@tab

@item

@code{'w3m'}

@tab

@code{GenericBrowser('w3m')}

@tab

@item

@code{'windows-default'}

@tab

@code{WindowsDefault}

@tab

(2)

@item

@code{'macosx'}

@tab

@code{MacOSXOSAScript('default')}

@tab

(3)

@item

@code{'safari'}

@tab

@code{MacOSXOSAScript('safari')}

@tab

(3)

@item

@code{'google-chrome'}

@tab

@code{Chrome('google-chrome')}

@tab

@item

@code{'chrome'}

@tab

@code{Chrome('chrome')}

@tab

@item

@code{'chromium'}

@tab

@code{Chromium('chromium')}

@tab

@item

@code{'chromium-browser'}

@tab

@code{Chromium('chromium-browser')}

@tab

@item

@code{'iosbrowser'}

@tab

@code{IOSBrowser}

@tab

(4)

@end multitable


注釈:


@enumerate 

@item 
"Konqueror" は Unix の KDE デスクトップ環境のファイルマネージャで、 KDE が動作している時にだけ意味を持ちます。何か信頼できる方法で KDE を検出するのがいいでしょう; 変数 @code{KDEDIR} では十分ではありません。また、 KDE 2 で @code{konqueror} コマンドを使うときにも、 "kfm" が使われます  --- Konqueror を動作させるのに最も良い方法が実装によって選択されます。

@item 
Windows プラットフォームのみ。

@item 
macOS のみ。

@item 
iOS のみ。
@end enumerate


Added in version 3.2: 新しい @code{MacOSXOSAScript} クラスが追加され、以前の @code{MacOSX} に替わって Mac で使用されます。これにより、現在 OS のデフォルトとして設定されていないブラウザを開くサポートが追加されました。



Added in version 3.3: Chrome/Chromium のサポートが追加されました。



バージョン 3.12 で変更: いくつかの古いブラウザのサポートが削除されました。削除されたブラウザには、 Grail 、 Mosaic 、 Netscape 、 Galeon 、 Skipstone 、 Iceape 、そして Firefox のバージョン 35 以前が含まれます。



バージョン 3.13 で変更: iOS のサポートが追加されました。


簡単な例を示します:

@example
url = 'https://docs.python.org/'

# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)

# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)
@end example

@node Browser controller objects,,コマンドライン・インターフェース<6>,webbrowser --- 便利なウェブブラウザコントローラー
@anchor{library/webbrowser browser-controller-objects}@anchor{3ecd}@anchor{library/webbrowser browser-controllers}@anchor{3ece}
@subsubsection Browser controller objects


Browser controllers provide the @ref{59a,,name} attribute,
and the following three methods which parallel module-level convenience functions:

@geindex name (webbrowser.controller の属性)
@anchor{library/webbrowser webbrowser controller name}@anchor{59a}
@deffn {の属性} controller.name

ブラウザのシステム依存名。
@end deffn

@geindex open() (webbrowser.controller のメソッド)
@anchor{library/webbrowser webbrowser controller open}@anchor{3ecf}
@deffn {メソッド} controller.open (url, new=0, autoraise=True)

このコントローラーでハンドルされたブラウザで `url' を表示します。`new' が 1 なら、可能であればブラウザの新しいウィンドウが開きます。`new' が 2 なら、可能であればブラウザの新しいページ(「タブ」)が開きます。
@end deffn

@geindex open_new() (webbrowser.controller のメソッド)
@anchor{library/webbrowser webbrowser controller open_new}@anchor{3ed0}
@deffn {メソッド} controller.open_new (url)

可能であれば、このコントローラーでハンドルされたブラウザの新しいウィンドウで `url' を開きますが、そうでない場合はブラウザのただ１つのウィンドウで `url' を開きます。 @ref{3ec9,,open_new()} の別名。
@end deffn

@geindex open_new_tab() (webbrowser.controller のメソッド)
@anchor{library/webbrowser webbrowser controller open_new_tab}@anchor{3ed1}
@deffn {メソッド} controller.open_new_tab (url)

可能であれば、このコントローラーでハンドルされたブラウザの新しいページ(「タブ」)で `url' を開きますが、そうでない場合は @ref{3ec9,,open_new()} と同じです。
@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node wsgiref --- WSGI ユーティリティとリファレンス実装,urllib --- URL を扱うモジュール群,webbrowser --- 便利なウェブブラウザコントローラー,インターネットプロトコルとサポート
@anchor{library/wsgiref doc}@anchor{3ed2}@anchor{library/wsgiref module-wsgiref}@anchor{11e}@anchor{library/wsgiref translation-repo}@anchor{3ed3}@anchor{library/wsgiref wsgiref-wsgi-utilities-and-reference-implementation}@anchor{3ed4}
@subsection @code{wsgiref} --- WSGI ユーティリティとリファレンス実装


@geindex module; wsgiref

`ソースコード:' Lib/wsgiref@footnote{https://github.com/python/cpython/tree/3.14/Lib/wsgiref}


__________________________________________________________________


@cartouche
@quotation 警告 
@code{wsgiref} is a reference implementation and is not recommended for
production. The module only implements basic security checks.
@end quotation
@end cartouche

Web Server Gateway Interface (WSGI) は、Web サーバソフトウェアと Python で記述された Web アプリケーションとの標準インターフェースです。標準インターフェースを持つことで、WSGI をサポートするアプリケーションを幾つもの異なる Web サーバで使うことが容易になります。

Web サーバとプログラミングフレームワークの作者だけが、WSGI デザインのあらゆる細部や特例などを知る必要があります。WSGI アプリケーションをインストールしたり、既存のフレームワークを使ったアプリケーションを記述するだけの皆さんは、すべてについて理解する必要はありません。

@code{wsgiref} is a reference implementation of the WSGI specification that can
be used to add WSGI support to a web server or framework.  It provides utilities
for manipulating WSGI environment variables and response headers, base classes
for implementing WSGI servers, a demo HTTP server that serves WSGI applications,
types for static type checking,
and a validation tool that checks WSGI servers and applications for conformance
to the WSGI specification (
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/}).

wsgi.readthedocs.io@footnote{https://wsgi.readthedocs.io/} に、WSGIに関するさらなる情報と、チュートリアルやその他のリソースへのリンクがあります。

@c XXX If you're just trying to write a web application...

@menu
* wsgiref.util: wsgiref util -- WSGI environment utilities. WSGI environment utilities
* wsgiref.headers: wsgiref headers -- WSGI response header tools. WSGI response header tools
* wsgiref.simple_server: wsgiref simple_server -- a simple WSGI HTTP server. a simple WSGI HTTP server
* wsgiref.validate: wsgiref validate --- WSGI conformance checker. WSGI conformance checker
* wsgiref.handlers: wsgiref handlers -- server/gateway base classes. server/gateway base classes
* wsgiref.types: wsgiref types -- WSGI types for static type checking. WSGI types for static type checking
* 使用例: 使用例<36>. 

@end menu

@node wsgiref util -- WSGI environment utilities,wsgiref headers -- WSGI response header tools,,wsgiref --- WSGI ユーティリティとリファレンス実装
@anchor{library/wsgiref module-wsgiref util}@anchor{123}@anchor{library/wsgiref wsgiref-util-wsgi-environment-utilities}@anchor{3ed5}
@subsubsection @code{wsgiref.util} -- WSGI environment utilities


@geindex module; wsgiref.util

このモジュールは WSGI 環境で使う様々なユーティリティ関数を提供します。 WSGI 環境は 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} で記述されているような HTTP リクエスト変数を含む辞書です。`environ' パラメータを取るすべての関数は WSGI 準拠の辞書を与えられることを期待しています; 細かい仕様については 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} を、型アノテーションに使える型エイリアスについては @ref{3ed6,,WSGIEnvironment} を参照してください。

@geindex guess_scheme() (wsgiref.util モジュール)
@anchor{library/wsgiref wsgiref util guess_scheme}@anchor{3ed7}
@deffn {の関数} wsgiref.util.guess_scheme (environ)

`environ' 辞書の @code{HTTPS} 環境変数を調べることで @code{wsgi.url_scheme} が "http" か "https" のどちらであるべきか推測し、その結果を返します。戻り値は文字列です。

この関数は、CGI や FastCGI のような CGI に似たプロトコルをラップするゲートウェイを作成する場合に便利です。典型的には、それらのプロトコルを提供するサーバが SSL 経由でリクエストを受け取った場合には @code{HTTPS} 変数に値 "1", "yes" または "on" を持つでしょう。そのため、この関数はそのような値が見つかった場合には "https" を返し、そうでなければ "http" を返します。
@end deffn

@geindex request_uri() (wsgiref.util モジュール)
@anchor{library/wsgiref wsgiref util request_uri}@anchor{3ed8}
@deffn {の関数} wsgiref.util.request_uri (environ, include_query=True)

リクエスト URI 全体 (オプションでクエリ文字列を含む) を、 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} の "URL 再構築(URL Reconstruction)" にあるアルゴリズムを使って返します。 `include_query' が false の場合、クエリ文字列は結果となる文字列には含まれません。
@end deffn

@geindex application_uri() (wsgiref.util モジュール)
@anchor{library/wsgiref wsgiref util application_uri}@anchor{3ed9}
@deffn {の関数} wsgiref.util.application_uri (environ)

@code{PATH_INFO} と @code{QUERY_STRING} 変数が無視されることを除けば @ref{3ed8,,request_uri()} に似ています。結果はリクエストによって指定されたアプリケーションオブジェクトのベース URI です。
@end deffn

@geindex shift_path_info() (wsgiref.util モジュール)
@anchor{library/wsgiref wsgiref util shift_path_info}@anchor{3eda}
@deffn {の関数} wsgiref.util.shift_path_info (environ)

@code{PATH_INFO} から @code{SCRIPT_NAME} に一つの名前をシフトしてその名前を返します。`environ' 辞書は `変更されます' 。@code{PATH_INFO} や @code{SCRIPT_NAME} のオリジナルをそのまま残したい場合にはコピーを使ってください。

@code{PATH_INFO} にパスセグメントが何も残っていなければ、@code{None} が返されます。

典型的なこのルーチンの使い方はリクエスト URI のそれぞれの要素の処理で、例えばパスを一連の辞書のキーとして取り扱う場合です。このルーチンは、渡された環境を、ターゲット URL で示される別の WSGI アプリケーションの呼び出しに合うように調整します。例えば、 @code{/foo} に WSGI アプリケーションがあったとして、そしてリクエスト URL パスが @code{/foo/bar/baz} で、 @code{/foo} の WSGI アプリケーションが @ref{3eda,,shift_path_info()} を呼んだ場合、これは "bar" 文字列を受け取り、 environ は @code{/foo/bar} の WSGI アプリケーションへの受け渡しに適するように更新されます。つまり、 @code{SCRIPT_NAME} は @code{/foo} から @code{/foo/bar} に変わって、 @code{PATH_INFO} は @code{/bar/baz} から @code{/baz} に変化するのです。

@code{PATH_INFO} が単に "/" の場合、このルーチンは空の文字列を返し、@code{SCRIPT_NAME} の末尾にスラッシュを加えます、これはたとえ空のパスセグメントが通常は無視され、そして @code{SCRIPT_NAME} は通常スラッシュで終わる事が無かったとしてもです。これは意図的な振る舞いで、このルーチンでオブジェクト巡回(object traversal) をした場合に @code{/x} で終わる URI と @code{/x/} で終わるものをアプリケーションが識別できることを保証するためのものです。
@end deffn

@geindex setup_testing_defaults() (wsgiref.util モジュール)
@anchor{library/wsgiref wsgiref util setup_testing_defaults}@anchor{3edb}
@deffn {の関数} wsgiref.util.setup_testing_defaults (environ)

`environ' をテスト用に自明なデフォルト値で更新します。

このルーチンは WSGI に必要な様々なパラメータを追加します。そのようなパラメータとして @code{HTTP_HOST} 、 @code{SERVER_NAME} 、 @code{SERVER_PORT} 、 @code{REQUEST_METHOD} 、 @code{SCRIPT_NAME} 、 @code{PATH_INFO} 、そして 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} で定義されている @code{wsgi.*} 変数群が含まれます。このルーチンはデフォルト値を提供するだけで、これらの変数の既存設定は一切置きかえません。

このルーチンは、ダミー環境をセットアップすることによって WSGI サーバとアプリケーションのユニットテストを容易にすることを意図しています。これは実際の WSGI サーバやアプリケーションで使うべきではありません。なぜならこのデータは偽物なのです！

Example usage (see also @ref{3edc,,demo_app()}
for another example):

@example
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]

    start_response(status, headers)

    ret = [("%s: %s\n" % (key, value)).encode("utf-8")
           for key, value in environ.items()]
    return ret

with make_server('@w{'}, 8000, simple_app) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()
@end example
@end deffn

In addition to the environment functions above, the @code{wsgiref.util} module
also provides these miscellaneous utilities:

@geindex is_hop_by_hop() (wsgiref.util モジュール)
@anchor{library/wsgiref wsgiref util is_hop_by_hop}@anchor{1a3b}
@deffn {の関数} wsgiref.util.is_hop_by_hop (header_name)

'header_name' が 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} で定義されている HTTP/1.1 の "Hop-by-Hop" ヘッダの場合に @code{True} を返します。
@end deffn

@geindex FileWrapper (wsgiref.util のクラス)
@anchor{library/wsgiref wsgiref util FileWrapper}@anchor{93f}
@deffn {クラス} wsgiref.util.FileWrapper (filelike, blksize=8192)

A concrete implementation of the @ref{3edd,,wsgiref.types.FileWrapper}
protocol used to convert a file-like object to an @ref{4c8,,iterator}.
The resulting objects
are @ref{12f1,,iterable}s. As the object is iterated over, the
optional `blksize' parameter will be repeatedly passed to the `filelike'
object's @code{read()} method to obtain bytestrings to yield.  When @code{read()}
returns an empty bytestring, iteration is ended and is not resumable.

`filelike' に @code{close()} メソッドがある場合、返されたオブジェクトも @code{close()} メソッドを持ち、これが呼ばれた場合には `filelike' オブジェクトの @code{close()} メソッドを呼び出します。

使用例:

@example
from io import StringIO
from wsgiref.util import FileWrapper

# We're using a StringIO-buffer for as the file-like object
filelike = StringIO("This is an example file-like object"*10)
wrapper = FileWrapper(filelike, blksize=5)

for chunk in wrapper:
    print(chunk)
@end example


バージョン 3.11 で変更: @ref{588,,__getitem__()} メソッドのサポートは削除されました。

@end deffn

@node wsgiref headers -- WSGI response header tools,wsgiref simple_server -- a simple WSGI HTTP server,wsgiref util -- WSGI environment utilities,wsgiref --- WSGI ユーティリティとリファレンス実装
@anchor{library/wsgiref module-wsgiref headers}@anchor{120}@anchor{library/wsgiref wsgiref-headers-wsgi-response-header-tools}@anchor{3ede}
@subsubsection @code{wsgiref.headers} -- WSGI response header tools


@geindex module; wsgiref.headers

このモジュールは単一のクラス、 @ref{1098,,Headers} を提供し、WSGI レスポンスヘッダの操作をマップに似たインターフェースで便利にします。

@geindex Headers (wsgiref.headers のクラス)
@anchor{library/wsgiref wsgiref headers Headers}@anchor{1098}
@deffn {クラス} wsgiref.headers.Headers ([headers])

`headers' をラップするマップ風オブジェクトを生成します。これは 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} に定義されるようなヘッダの名前／値のタプルのリストです。 `headers' のデフォルト値は空のリストです。

@ref{1098,,Headers} objects support typical mapping operations including
@ref{588,,__getitem__()}, @ref{2034,,get()}, @ref{14e3,,__setitem__()},
@ref{1285,,setdefault()},
@ref{14e4,,__delitem__()} and @ref{15d3,,__contains__()}.  For each of
these methods, the key is the header name (treated case-insensitively), and the
value is the first value associated with that header name.  Setting a header
deletes any existing values for that header, then adds a new value at the end of
the wrapped header list.  Headers' existing order is generally maintained, with
new headers added to the end of the wrapped list.

辞書とは違って、 @ref{1098,,Headers} オブジェクトはラップされたヘッダリストに存在しないキーを取得または削除しようとした場合にもエラーを発生しません。単に、存在しないヘッダの取得は @code{None} を返し、存在しないヘッダの削除は何もしません。

@ref{1098,,Headers} オブジェクトは @code{keys()} 、 @code{values()} 、 @code{items()} メソッドもサポートします。複数の値を持つヘッダがある場合には、 @code{keys()} と @code{items()} で返されるリストは同じキーを一つ以上含むことがあります。 @ref{1098,,Headers} オブジェクトの @code{len()} は、その @code{items()} の長さと同じであり、ラップされたヘッダリストの長さと同じです。実際、 @code{items()} メソッドは単にラップされたヘッダリストのコピーを返しているだけです。

@ref{1098,,Headers} オブジェクトに対して @code{bytes()} を呼ぶと、HTTP レスポンスヘッダとして送信するのに適した形に整形されたバイト文字列を返します。それぞれのヘッダはコロンとスペースで区切られた値と共に一列に並んでいます。それぞれの行はキャリッジリターンとラインフィードで終了し、バイト文字列は空行で終了しています。

これらのマッピングインターフェースと整形機能に加えて、 @ref{1098,,Headers} オブジェクトは複数の値を持つヘッダの取得と追加、MIME パラメータでヘッダを追加するための以下のようなメソッド群も持っています:

@geindex get_all() (wsgiref.headers.Headers のメソッド)
@anchor{library/wsgiref wsgiref headers Headers get_all}@anchor{3edf}
@deffn {メソッド} get_all (name)

指定されたヘッダのすべての値のリストを返します。

返されるリストは、元々のヘッダリストに現れる順、またはこのインスタンスに追加された順に並んでいて、重複を含む場合があります。削除されて加えられたフィールドはすべてヘッダリストの末尾に付きます。与えられた name に対するフィールドが何もなければ、空のリストが返ります。
@end deffn

@geindex add_header() (wsgiref.headers.Headers のメソッド)
@anchor{library/wsgiref wsgiref headers Headers add_header}@anchor{3ee0}
@deffn {メソッド} add_header (name, value, **_params)

(複数の値を持つ可能性のある) ヘッダを、キーワード引数を通じて指定するオプションの MIME パラメータと共に追加します。

`name' は追加するヘッダフィールドです。このヘッダフィールドに MIME パラメータを設定するためにキーワード引数を使うことができます。それぞれのパラメータは文字列か @code{None} でなければいけません。パラメータ中のアンダースコアはダッシュ (-) に変換されます。これは、ダッシュが Python の識別子としては不正なのですが、多くの MIME パラメータはダッシュを含むためです。パラメータ値が文字列の場合、これはヘッダ値のパラメータに @code{name="value"} の形で追加されます。この値がもし @code{None} の場合、パラメータ名だけが追加されます。（これは値なしの MIME パラメータの場合に使われます。）使い方の例は:

@example
h.add_header('content-disposition', 'attachment', filename='bud.gif')
@end example

上記はこのようなヘッダを追加します:

@example
Content-Disposition: attachment; filename="bud.gif"
@end example
@end deffn


バージョン 3.5 で変更: `headers' 引数が任意になりました。

@end deffn

@node wsgiref simple_server -- a simple WSGI HTTP server,wsgiref validate --- WSGI conformance checker,wsgiref headers -- WSGI response header tools,wsgiref --- WSGI ユーティリティとリファレンス実装
@anchor{library/wsgiref module-wsgiref simple_server}@anchor{121}@anchor{library/wsgiref wsgiref-simple-server-a-simple-wsgi-http-server}@anchor{3ee1}
@subsubsection @code{wsgiref.simple_server} -- a simple WSGI HTTP server


@geindex module; wsgiref.simple_server

このモジュールは WSGI アプリケーションを提供するシンプルな HTTP サーバです (@ref{76,,http.server} がベースです)。個々のサーバインスタンスは単一の WSGI アプリケーションを、特定のホストとポート上で提供します。もし一つのホストとポート上で複数のアプリケーションを提供したいならば、 @code{PATH_INFO} をパースして個々のリクエストでどのアプリケーションを呼び出すか選択するような WSGI アプリケーションを作る必要があります。（例えば、 @ref{123,,wsgiref.util} から @code{shift_path_info()} を利用します。）

@geindex make_server() (wsgiref.simple_server モジュール)
@anchor{library/wsgiref wsgiref simple_server make_server}@anchor{3ee2}
@deffn {の関数} wsgiref.simple_server.make_server (host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)

`host' と `port' 上で待機し、 `app' へのコネクションを受け付ける  WSGI サーバを作成します。戻り値は与えられた `server_class' のインスタンスで、指定された `handler_class' を使ってリクエストを処理します。 `app' は 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} で定義されるところの WSGI アプリケーションでなければいけません。

使用例:

@example
from wsgiref.simple_server import make_server, demo_app

with make_server('@w{'}, 8000, demo_app) as httpd:
    print("Serving HTTP on port 8000...")

    # Respond to requests until process is killed
    httpd.serve_forever()

    # Alternative: serve one request, then exit
    httpd.handle_request()
@end example
@end deffn

@geindex demo_app() (wsgiref.simple_server モジュール)
@anchor{library/wsgiref wsgiref simple_server demo_app}@anchor{3edc}
@deffn {の関数} wsgiref.simple_server.demo_app (environ, start_response)

This function is a small but complete WSGI application that returns a text page
containing the message "Hello world!" and a list of the key/value pairs provided
in the `environ' parameter.  It's useful for verifying that a WSGI server (such
as @code{wsgiref.simple_server}) is able to run a simple WSGI application
correctly.

The `start_response' callable should follow the @ref{3ee3,,StartResponse} protocol.
@end deffn

@geindex WSGIServer (wsgiref.simple_server のクラス)
@anchor{library/wsgiref wsgiref simple_server WSGIServer}@anchor{3ee4}
@deffn {クラス} wsgiref.simple_server.WSGIServer (server_address, RequestHandlerClass)

@ref{3ee4,,WSGIServer} インスタンスを作成します。 `server_address' は @code{(host,port)} のタプル、そして `RequestHandlerClass' はリクエストの処理に使われる @ref{12e2,,http.server.BaseHTTPRequestHandler} のサブクラスでなければいけません。

@ref{3ee2,,make_server()} が細かい調整をやってくれるので、通常はこのコンストラクタを呼ぶ必要はありません。

@ref{3ee4,,WSGIServer} は @ref{3ee5,,http.server.HTTPServer} のサブクラスなので、そのすべてのメソッド (@code{serve_forever()} や @code{handle_request()} のような) が利用できます。 @ref{3ee4,,WSGIServer} も以下のような WSGI 固有メソッドを提供します:

@geindex set_app() (wsgiref.simple_server.WSGIServer のメソッド)
@anchor{library/wsgiref wsgiref simple_server WSGIServer set_app}@anchor{3ee6}
@deffn {メソッド} set_app (application)

呼び出し可能 (callable) な `application' をリクエストを受け取る WSGI アプリケーションとして設定します。
@end deffn

@geindex get_app() (wsgiref.simple_server.WSGIServer のメソッド)
@anchor{library/wsgiref wsgiref simple_server WSGIServer get_app}@anchor{3ee7}
@deffn {メソッド} get_app ()

Returns the currently set application callable.
@end deffn

しかしながら、通常はこれらの追加されたメソッドを使う必要はありません。 @ref{3ee6,,set_app()} は普通は @ref{3ee2,,make_server()} によって呼ばれ、 @ref{3ee7,,get_app()} は主にリクエストハンドラインスタンスの便宜上存在するからです。
@end deffn

@geindex WSGIRequestHandler (wsgiref.simple_server のクラス)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler}@anchor{3ee8}
@deffn {クラス} wsgiref.simple_server.WSGIRequestHandler (request, client_address, server)

与えられた `request' （すなわちソケット）の HTTP ハンドラ、 `client_address' (@code{(host,port)} のタプル)、 `server' (@ref{3ee4,,WSGIServer} インスタンス) の HTTP ハンドラを作成します。

このクラスのインスタンスを直接生成する必要はありません; これらは必要に応じて @ref{3ee4,,WSGIServer} オブジェクトによって自動的に生成されます。しかしながら、このクラスをサブクラス化し、 @ref{3ee2,,make_server()} 関数に `handler_class' として与えることは可能でしょう。サブクラスにおいてオーバーライドする意味のありそうなものは:

@geindex get_environ() (wsgiref.simple_server.WSGIRequestHandler のメソッド)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler get_environ}@anchor{3ee9}
@deffn {メソッド} get_environ ()

リクエストに対する @ref{3ed6,,WSGIEnvironment} 辞書を返します。デフォルト実装では @ref{3ee4,,WSGIServer} オブジェクトの @code{base_environ} 辞書属性のコンテンツをコピーし、それから HTTP リクエスト由来の様々なヘッダを追加しています。このメソッド呼び出し毎に、 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} に指定されている関連する CGI 環境変数をすべて含む新規の辞書を返さなければいけません。
@end deffn

@geindex get_stderr() (wsgiref.simple_server.WSGIRequestHandler のメソッド)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler get_stderr}@anchor{3eea}
@deffn {メソッド} get_stderr ()

@code{wsgi.errors} ストリームとして使われるオブジェクトを返します。デフォルト実装では単に @code{sys.stderr} を返します。
@end deffn

@geindex handle() (wsgiref.simple_server.WSGIRequestHandler のメソッド)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler handle}@anchor{3eeb}
@deffn {メソッド} handle ()

HTTP リクエストを処理します。デフォルト実装では実際の WGI アプリケーションインターフェースを実装するのに @ref{11f,,wsgiref.handlers} クラスを使ってハンドラインスタンスを作成します。
@end deffn
@end deffn

@node wsgiref validate --- WSGI conformance checker,wsgiref handlers -- server/gateway base classes,wsgiref simple_server -- a simple WSGI HTTP server,wsgiref --- WSGI ユーティリティとリファレンス実装
@anchor{library/wsgiref module-wsgiref validate}@anchor{124}@anchor{library/wsgiref wsgiref-validate-wsgi-conformance-checker}@anchor{3eec}
@subsubsection @code{wsgiref.validate} --- WSGI conformance checker


@geindex module; wsgiref.validate

When creating new WSGI application objects, frameworks, servers, or middleware,
it can be useful to validate the new code's conformance using
@code{wsgiref.validate}.  This module provides a function that creates WSGI
application objects that validate communications between a WSGI server or
gateway and a WSGI application object, to check both sides for protocol
conformance.

このユーティリティは完全な 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} 準拠を保証するものでないことは注意してください; このモジュールでエラーが出ないことは必ずしもエラーが存在しないことを意味しません。しかしこのモジュールがエラーを出したならば、ほぼ確実にサーバかアプリケーションのどちらかが 100% 準拠ではありません。

このモジュールは lan Bicking の "Python Paste" ライブラリの @code{paste.lint} モジュールをベースにしています。

@geindex validator() (wsgiref.validate モジュール)
@anchor{library/wsgiref wsgiref validate validator}@anchor{3eed}
@deffn {の関数} wsgiref.validate.validator (application)

`application' をラップし、新しい WSGI アプリケーションオブジェクトを返します。返されたアプリケーションは全てのリクエストを元々の `application' に転送し、`application' とそれを呼び出すサーバの両方が WSGI 仕様と 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} の両方に準拠しているかをチェックします。

何らかの非準拠が検出されると、 @ref{8b8,,AssertionError} 例外が送出されます; しかし、このエラーがどう扱われるかはサーバ依存であることに注意してください。例えば、 @ref{121,,wsgiref.simple_server} とその他 @ref{11f,,wsgiref.handlers} ベースのサーバ（エラー処理メソッドが他のことをするようにオーバライドしていないもの）は単純にエラーが発生したというメッセージとトレースバックのダンプを @code{sys.stderr} やその他のエラーストリームに出力します。

このラッパーは、疑わしいものの実際には 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} で禁止されていないかもしれない挙動を指摘するために @ref{118,,warnings} モジュールを使って出力を生成します。これらは Python のコマンドラインオプションや @ref{118,,warnings} API で抑制されなければ、 @code{sys.stderr} (@code{wsgi.errors} では `ありません' 。ただし、たまたま同一のオブジェクトだった場合を除く)に書き出されます。

使用例:

@example
from wsgiref.validate import validator
from wsgiref.simple_server import make_server

# Our callable object which is intentionally not compliant to the
# standard, so the validator is going to break
def simple_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain')]  # HTTP Headers
    start_response(status, headers)

    # This is going to break because we need to return a list, and
    # the validator is going to inform us
    return b"Hello World"

# This is the application wrapped in a validator
validator_app = validator(simple_app)

with make_server('@w{'}, 8000, validator_app) as httpd:
    print("Listening on port 8000....")
    httpd.serve_forever()
@end example
@end deffn

@node wsgiref handlers -- server/gateway base classes,wsgiref types -- WSGI types for static type checking,wsgiref validate --- WSGI conformance checker,wsgiref --- WSGI ユーティリティとリファレンス実装
@anchor{library/wsgiref module-wsgiref handlers}@anchor{11f}@anchor{library/wsgiref wsgiref-handlers-server-gateway-base-classes}@anchor{3eee}
@subsubsection @code{wsgiref.handlers} -- server/gateway base classes


@geindex module; wsgiref.handlers

このモジュールは WSGI サーバとゲートウェイ実装のベースハンドラクラスを提供します。これらのベースクラスは、CGI 風の環境と、それに加えて入力、出力そしてエラーストリームが与えられることで、WSGI アプリケーションとの通信の大部分を処理します。

@geindex CGIHandler (wsgiref.handlers のクラス)
@anchor{library/wsgiref wsgiref handlers CGIHandler}@anchor{3eef}
@deffn {クラス} wsgiref.handlers.CGIHandler

@code{sys.stdin}、@code{sys.stdout}、@code{sys.stderr} そして @code{os.environ} 経由での CGI ベースの呼び出しです。これは、もしあなたが WSGI アプリケーションを持っていて、これを CGI スクリプトとして実行したい場合に有用です。単に @code{CGIHandler().run(app)} を起動してください。@code{app} はあなたが起動したい WSGI アプリケーションオブジェクトです。

このクラスは @ref{3ef0,,BaseCGIHandler} のサブクラスで、これは @code{wsgi.run_once} を true、 @code{wsgi.multithread} を false、そして @code{wsgi.multiprocess} を true にセットし、常に @ref{df,,sys} と @ref{a5,,os} を、必要な CGI ストリームと環境を取得するために使用します。
@end deffn

@geindex IISCGIHandler (wsgiref.handlers のクラス)
@anchor{library/wsgiref wsgiref handlers IISCGIHandler}@anchor{3ef1}
@deffn {クラス} wsgiref.handlers.IISCGIHandler

(IIS 7 以降の) 設定オプションの allowPathInfo や (IIS 7 より前の) メタベースの allowPathInfoForScriptMappings を設定せずに Microsoft の IIS Web サーバにデプロイするときに使う、 @ref{3eef,,CGIHandler} クラス以外の専用の選択肢です。

By default, IIS gives a @code{PATH_INFO} that duplicates the @code{SCRIPT_NAME} at
the front, causing problems for WSGI applications that wish to implement
routing. This handler strips any such duplicated path.

IIS can be configured to pass the correct @code{PATH_INFO}, but this causes
another bug where @code{PATH_TRANSLATED} is wrong. Luckily this variable is
rarely used and is not guaranteed by WSGI. On IIS<7, though, the
setting can only be made on a vhost level, affecting all other script
mappings, many of which break when exposed to the @code{PATH_TRANSLATED} bug.
For this reason IIS<7 is almost never deployed with the fix (Even IIS7
rarely uses it because there is still no UI for it.).

There is no way for CGI code to tell whether the option was set, so a
separate handler class is provided.  It is used in the same way as
@ref{3eef,,CGIHandler}, i.e., by calling @code{IISCGIHandler().run(app)}, where
@code{app} is the WSGI application object you wish to invoke.


Added in version 3.2.

@end deffn

@geindex BaseCGIHandler (wsgiref.handlers のクラス)
@anchor{library/wsgiref wsgiref handlers BaseCGIHandler}@anchor{3ef0}
@deffn {クラス} wsgiref.handlers.BaseCGIHandler (stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

@ref{3eef,,CGIHandler} に似ていますが、 @ref{df,,sys} と @ref{a5,,os} モジュールを使う代わりに CGI 環境と I/O ストリームを明示的に指定します。 `multithread' と `multiprocess' の値は、ハンドラインスタンスにより実行されるアプリケーションの @code{wsgi.multithread} と @code{wsgi.multiprocess} フラグの設定に使われます。

このクラスは @ref{3ef2,,SimpleHandler} のサブクラスで、HTTP の "本サーバ" でないソフトウェアと使うことを意図しています。もしあなたが @code{Status:} ヘッダを HTTP ステータスを送信するのに使うようなゲートウェイプロトコルの実装（CGI、FastCGI、SCGIなど）を書いている場合、おそらく @ref{3ef2,,SimpleHandler} ではなくこのクラスをサブクラス化するとよいでしょう。
@end deffn

@geindex SimpleHandler (wsgiref.handlers のクラス)
@anchor{library/wsgiref wsgiref handlers SimpleHandler}@anchor{3ef2}
@deffn {クラス} wsgiref.handlers.SimpleHandler (stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

@ref{3ef0,,BaseCGIHandler} と似ていますが、HTTP の本サーバと使うためにデザインされています。もしあなたが HTTP サーバ実装を書いている場合、おそらく @ref{3ef0,,BaseCGIHandler} ではなくこのクラスをサブクラス化するとよいでしょう。

This class is a subclass of @ref{1dd3,,BaseHandler}.  It overrides the
@code{__init__()}, @ref{3ef3,,get_stdin()},
@ref{3ef4,,get_stderr()}, @ref{3ef5,,add_cgi_vars()},
@ref{3ef6,,_write()}, and @ref{3ef7,,_flush()} methods to
support explicitly setting the
environment and streams via the constructor.  The supplied environment and
streams are stored in the @code{stdin}, @code{stdout}, @code{stderr}, and
@code{environ} attributes.

The @ref{ed7,,write()} method of `stdout' should write
each chunk in full, like @ref{8a3,,io.BufferedIOBase}.
@end deffn

@geindex BaseHandler (wsgiref.handlers のクラス)
@anchor{library/wsgiref wsgiref handlers BaseHandler}@anchor{1dd3}
@deffn {クラス} wsgiref.handlers.BaseHandler

これは WSGI アプリケーションを実行するための抽象ベースクラスです。それぞれのインスタンスは一つの HTTP リクエストを処理します。しかし原理上は複数のリクエスト用に再利用可能なサブクラスを作成することができます。

@ref{1dd3,,BaseHandler} インスタンスは外部から利用されるたった一つのメソッドを持ちます:

@geindex run() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler run}@anchor{3ef8}
@deffn {メソッド} run (app)

指定された WSGI アプリケーション、`app' を実行します。
@end deffn

その他のすべての @ref{1dd3,,BaseHandler} のメソッドはアプリケーション実行プロセスでこのメソッドから呼ばれます。したがって、それらは主にそのプロセスのカスタマイズのために存在しています。

以下のメソッドはサブクラスでオーバーライドされなければいけません:

@geindex _write() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler _write}@anchor{3ef6}
@deffn {メソッド} _write (data)

バイト列の `data' をクライアントへの転送用にバッファします。このメソッドが実際にデータを転送しても OK です: 下部システムが実際にそのような区別をしている場合に効率をより良くするために、 @ref{1dd3,,BaseHandler} は書き出しとフラッシュ操作を分けているからです。
@end deffn

@geindex _flush() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler _flush}@anchor{3ef7}
@deffn {メソッド} _flush ()

バッファされたデータをクライアントに強制的に転送します。このメソッドは何もしなくても OK です（すなわち、 @ref{3ef6,,_write()} が実際にデータを送る場合）。
@end deffn

@geindex get_stdin() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler get_stdin}@anchor{3ef3}
@deffn {メソッド} get_stdin ()

Return an object compatible with @ref{3ef9,,InputStream}
suitable for use as the @code{wsgi.input} of the
request currently being processed.
@end deffn

@geindex get_stderr() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler get_stderr}@anchor{3ef4}
@deffn {メソッド} get_stderr ()

Return an object compatible with @ref{3efa,,ErrorStream}
suitable for use as the @code{wsgi.errors} of the
request currently being processed.
@end deffn

@geindex add_cgi_vars() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler add_cgi_vars}@anchor{3ef5}
@deffn {メソッド} add_cgi_vars ()

現在のリクエストの CGI 変数を @code{environ} 属性に追加します。
@end deffn

オーバーライドされることの多いメソッド及び属性を以下に挙げます。しかし、このリストは単にサマリであり、オーバーライド可能なすべてのメソッドは含んでいません。カスタマイズした @ref{1dd3,,BaseHandler} サブクラスを作成しようとする前に docstring やソースコードでさらなる情報を調べてください。

WSGI 環境のカスタマイズのための属性とメソッド:

@geindex wsgi_multithread (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_multithread}@anchor{3efb}
@deffn {の属性} wsgi_multithread

@code{wsgi.multithread} 環境変数で使われる値。 @ref{1dd3,,BaseHandler} ではデフォルトが true ですが、別のサブクラスではデフォルトで（またはコンストラクタによって設定されて）異なる値を持つことがあります。
@end deffn

@geindex wsgi_multiprocess (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_multiprocess}@anchor{3efc}
@deffn {の属性} wsgi_multiprocess

@code{wsgi.multiprocess} 環境変数で使われる値。 @ref{1dd3,,BaseHandler} ではデフォルトが true ですが、別のサブクラスではデフォルトで（またはコンストラクタによって設定されて）異なる値を持つことがあります。
@end deffn

@geindex wsgi_run_once (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_run_once}@anchor{3efd}
@deffn {の属性} wsgi_run_once

@code{wsgi.run_once} 環境変数で使われる値。 @ref{1dd3,,BaseHandler} ではデフォルトが false ですが、 @ref{3eef,,CGIHandler} はデフォルトでこれを true に設定します。
@end deffn

@geindex os_environ (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler os_environ}@anchor{3efe}
@deffn {の属性} os_environ

The default environment variables to be included in every request's WSGI
environment.  By default, this is a copy of @code{os.environ} at the time that
@code{wsgiref.handlers} was imported, but subclasses can either create their own
at the class or instance level.  Note that the dictionary should be considered
read-only, since the default value is shared between multiple classes and
instances.
@end deffn

@geindex server_software (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler server_software}@anchor{3eff}
@deffn {の属性} server_software

@ref{3f00,,origin_server} 属性が設定されている場合、この属性の値がデフォルトの @code{SERVER_SOFTWARE} WSGI 環境変数の設定や HTTP レスポンス中のデフォルトの @code{Server:} ヘッダの設定に使われます。これは (@ref{3ef0,,BaseCGIHandler} や @ref{3eef,,CGIHandler} のような) HTTP オリジンサーバでないハンドラでは無視されます。


バージョン 3.3 で変更: "Python" という語は "CPython" や "Jython" などのような個別実装の語に置き換えられました。

@end deffn

@geindex get_scheme() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler get_scheme}@anchor{3f01}
@deffn {メソッド} get_scheme ()

現在のリクエストで使われている URL スキームを返します。デフォルト実装は @ref{123,,wsgiref.util} の @code{guess_scheme()} を使い、現在のリクエストの @code{environ} 変数に基づいてスキームが"http" か "https" かを推測します。
@end deffn

@geindex setup_environ() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler setup_environ}@anchor{3f02}
@deffn {メソッド} setup_environ ()

@code{environ} 属性を、フル実装 (fully populated) の WSGI 環境に設定します。デフォルトの実装は、上記すべてのメソッドと属性、加えて @ref{3ef3,,get_stdin()} 、 @ref{3ef4,,get_stderr()} 、 @ref{3ef5,,add_cgi_vars()} メソッドと @ref{3f03,,wsgi_file_wrapper} 属性を利用します。これは、キーが存在せず、 @ref{3f00,,origin_server} 属性が true 値で @ref{3eff,,server_software} 属性も設定されている場合に @code{SERVER_SOFTWARE} を挿入します。
@end deffn

例外処理のカスタマイズのためのメソッドと属性:

@geindex log_exception() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler log_exception}@anchor{3f04}
@deffn {メソッド} log_exception (exc_info)

`exc_info' タプルをサーバログに記録します。`exc_info' は @code{(type, value, traceback)} のタプルです。デフォルトの実装は単純にトレースバックをリクエストの @code{wsgi.errors} ストリームに書き出してフラッシュします。サブクラスはこのメソッドをオーバーライドしてフォーマットを変更したり出力先の変更、トレースバックを管理者にメールしたりその他適切と思われるいかなるアクションも取ることができます。
@end deffn

@geindex traceback_limit (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler traceback_limit}@anchor{3f05}
@deffn {の属性} traceback_limit

デフォルトの @ref{3f04,,log_exception()} メソッドで出力されるトレースバック出力に含まれる最大のフレーム数です。 @code{None} ならば、すべてのフレームが含まれます。
@end deffn

@geindex error_output() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_output}@anchor{3f06}
@deffn {メソッド} error_output (environ, start_response)

このメソッドは、ユーザに対してエラーページを出力する WSGI アプリケーションです。これはクライアントにヘッダが送出される前にエラーが発生した場合にのみ呼び出されます。

This method can access the current error using @code{sys.exception()},
and should pass that information to `start_response' when calling it (as
described in the "Error Handling" section of 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/}). In particular,
the `start_response' callable should follow the @ref{3ee3,,StartResponse}
protocol.

デフォルト実装は単に @ref{3f07,,error_status} 、 @ref{3f08,,error_headers} 、 @ref{3f09,,error_body} 属性を出力ページの生成に使います。サブクラスではこれをオーバーライドしてもっと動的なエラー出力をすることができます。

しかし、セキュリティの観点からは診断をあらゆるユーザに吐き出すことは推奨されないことに気をつけてください; 理想的には、診断的な出力を有効にするには何らかの特別なことをする必要があるようにすべきで、これがデフォルト実装では何も含まれていない理由です。
@end deffn

@geindex error_status (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_status}@anchor{3f07}
@deffn {の属性} error_status

エラーレスポンスで使われる HTTP ステータスです。これは 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} で定義されているステータス文字列です; デフォルトは 500 コードとメッセージです。
@end deffn

@geindex error_headers (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_headers}@anchor{3f08}
@deffn {の属性} error_headers

エラーレスポンスで使われる HTTP ヘッダです。これは 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} で述べられているような、 WSGI レスポンスヘッダ (@code{(name, value)} タプル) のリストであるべきです。デフォルトのリストはコンテントタイプを @code{text/plain} にセットしているだけです。
@end deffn

@geindex error_body (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_body}@anchor{3f09}
@deffn {の属性} error_body

エラーレスポンスボディ。これは HTTP レスポンスのボディバイト文字列であるべきです。これはデフォルトではプレーンテキストで "A server error occurred.  Please contact the administrator." です。
@end deffn

@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} の "オプションのプラットフォーム固有のファイルハンドリング" 機能のためのメソッドと属性:

@geindex wsgi_file_wrapper (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_file_wrapper}@anchor{3f03}
@deffn {の属性} wsgi_file_wrapper

A @code{wsgi.file_wrapper} factory, compatible with
@ref{3edd,,wsgiref.types.FileWrapper}, or @code{None}.  The default value
of this attribute is the @ref{93f,,wsgiref.util.FileWrapper} class.
@end deffn

@geindex sendfile() (wsgiref.handlers.BaseHandler のメソッド)
@anchor{library/wsgiref wsgiref handlers BaseHandler sendfile}@anchor{3f0a}
@deffn {メソッド} sendfile ()

オーバーライドしてプラットフォーム固有のファイル転送を実装します。このメソッドはアプリケーションの戻り値が @ref{3f03,,wsgi_file_wrapper} 属性で指定されたクラスのインスタンスの場合にのみ呼ばれます。これはファイルの転送が成功できた場合には true を返して、デフォルトの転送コードが実行されないようにするべきです。このデフォルトの実装は単に false 値を返します。
@end deffn

その他のメソッドと属性:

@geindex origin_server (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler origin_server}@anchor{3f00}
@deffn {の属性} origin_server

この属性はハンドラの @ref{3ef6,,_write()} と @ref{3ef7,,_flush()} が、特別に @code{Status:} ヘッダに HTTP ステータスを求めるような CGI 風のゲートウェイプロトコル経由でなく、クライアントと直接通信をするような場合には true 値に設定されているべきです。

この属性のデフォルト値は @ref{1dd3,,BaseHandler} では true ですが、 @ref{3ef0,,BaseCGIHandler} と @ref{3eef,,CGIHandler} では false です。
@end deffn

@geindex http_version (wsgiref.handlers.BaseHandler の属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler http_version}@anchor{3f0b}
@deffn {の属性} http_version

@ref{3f00,,origin_server} が true の場合、この文字列属性はクライアントへのレスポンスセットの HTTP バージョンの設定に使われます。デフォルトは @code{"1.0"} です。
@end deffn
@end deffn

@geindex read_environ() (wsgiref.handlers モジュール)
@anchor{library/wsgiref wsgiref handlers read_environ}@anchor{13d1}
@deffn {の関数} wsgiref.handlers.read_environ ()

Transcode CGI variables from @code{os.environ} to 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/} "bytes in unicode"
strings, returning a new dictionary.  This function is used by
@ref{3eef,,CGIHandler} and @ref{3ef1,,IISCGIHandler} in place of directly using
@code{os.environ}, which is not necessarily WSGI-compliant on all platforms
and web servers using Python 3 -- specifically, ones where the OS's
actual environment is Unicode (i.e. Windows), or ones where the environment
is bytes, but the system encoding used by Python to decode it is anything
other than ISO-8859-1 (e.g. Unix systems using UTF-8).

If you are implementing a CGI-based handler of your own, you probably want
to use this routine instead of just copying values out of @code{os.environ}
directly.


Added in version 3.2.

@end deffn

@node wsgiref types -- WSGI types for static type checking,使用例<36>,wsgiref handlers -- server/gateway base classes,wsgiref --- WSGI ユーティリティとリファレンス実装
@anchor{library/wsgiref module-wsgiref types}@anchor{122}@anchor{library/wsgiref wsgiref-types-wsgi-types-for-static-type-checking}@anchor{3f0c}
@subsubsection @code{wsgiref.types} -- WSGI types for static type checking


@geindex module; wsgiref.types

This module provides various types for static type checking as described
in 
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/}.


Added in version 3.11.


@geindex StartResponse (wsgiref.types のクラス)
@anchor{library/wsgiref wsgiref types StartResponse}@anchor{3ee3}
@deffn {クラス} wsgiref.types.StartResponse

A @ref{56b,,typing.Protocol} describing 
@geindex Python Enhancement Proposals; PEP 3333#the-start-response-callable
start_response()@footnote{https://peps.python.org/pep-3333/#the-start-response-callable}
callables (
@geindex Python Enhancement Proposals; PEP 3333
PEP 3333@footnote{https://peps.python.org/pep-3333/}).
@end deffn

@geindex WSGIEnvironment (wsgiref.types モジュール)
@anchor{library/wsgiref wsgiref types WSGIEnvironment}@anchor{3ed6}
@deffn {データ} wsgiref.types.WSGIEnvironment

A type alias describing a WSGI environment dictionary.
@end deffn

@geindex WSGIApplication (wsgiref.types モジュール)
@anchor{library/wsgiref wsgiref types WSGIApplication}@anchor{3f0d}
@deffn {データ} wsgiref.types.WSGIApplication

A type alias describing a WSGI application callable.
@end deffn

@geindex InputStream (wsgiref.types のクラス)
@anchor{library/wsgiref wsgiref types InputStream}@anchor{3ef9}
@deffn {クラス} wsgiref.types.InputStream

A @ref{56b,,typing.Protocol} describing a 
@geindex Python Enhancement Proposals; PEP 3333#input-and-error-streams
WSGI Input Stream@footnote{https://peps.python.org/pep-3333/#input-and-error-streams}.
@end deffn

@geindex ErrorStream (wsgiref.types のクラス)
@anchor{library/wsgiref wsgiref types ErrorStream}@anchor{3efa}
@deffn {クラス} wsgiref.types.ErrorStream

A @ref{56b,,typing.Protocol} describing a 
@geindex Python Enhancement Proposals; PEP 3333#input-and-error-streams
WSGI Error Stream@footnote{https://peps.python.org/pep-3333/#input-and-error-streams}.
@end deffn

@geindex FileWrapper (wsgiref.types のクラス)
@anchor{library/wsgiref wsgiref types FileWrapper}@anchor{3edd}
@deffn {クラス} wsgiref.types.FileWrapper

A @ref{56b,,typing.Protocol} describing a 
@geindex Python Enhancement Proposals; PEP 3333#optional-platform-specific-file-handling
file wrapper@footnote{https://peps.python.org/pep-3333/#optional-platform-specific-file-handling}.
See @ref{93f,,wsgiref.util.FileWrapper} for a concrete implementation of this
protocol.
@end deffn

@node 使用例<36>,,wsgiref types -- WSGI types for static type checking,wsgiref --- WSGI ユーティリティとリファレンス実装
@anchor{library/wsgiref examples}@anchor{3f0e}
@subsubsection 使用例


This is a working "Hello World" WSGI application, where the `start_response'
callable should follow the @ref{3ee3,,StartResponse} protocol:

@example
"""
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.
"""
from wsgiref.simple_server import make_server


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()
@end example

Example of a WSGI application serving the current directory, accept optional
directory and port number (default: 8000) on the command line:

@example
"""
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.
"""
import mimetypes
import os
import sys
from wsgiref import simple_server, util


def app(environ, respond):
    # Get the file name and MIME type
    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")
    mime_type = mimetypes.guess_file_type(fn)[0]

    # Return 200 OK if file exists, otherwise 404 Not Found
    if os.path.exists(fn):
        respond("200 OK", [("Content-Type", mime_type)])
        return util.FileWrapper(open(fn, "rb"))
    else:
        respond("404 Not Found", [("Content-Type", "text/plain")])
        return [b"not found"]


if __name__ == "__main__":
    # Get the path and port from command-line arguments
    path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000

    # Make and start the server until control-c
    httpd = simple_server.make_server("", port, app)
    print(f"Serving @{path@} on port @{port@}, control-C to stop")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("Shutting down.")
        httpd.server_close()
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node urllib --- URL を扱うモジュール群,urllib request --- URL を開くための大規模なライブラリ,wsgiref --- WSGI ユーティリティとリファレンス実装,インターネットプロトコルとサポート
@anchor{library/urllib doc}@anchor{3f0f}@anchor{library/urllib module-urllib}@anchor{10e}@anchor{library/urllib translation-repo}@anchor{3f10}@anchor{library/urllib urllib-url-handling-modules}@anchor{3f11}
@subsection @code{urllib} --- URL を扱うモジュール群


@geindex module; urllib

`ソースコード:' Lib/urllib/@footnote{https://github.com/python/cpython/tree/3.14/Lib/urllib/}


__________________________________________________________________


@code{urllib} は URL を扱う幾つかのモジュールを集めたパッケージです:


@itemize *

@item 
@ref{111,,urllib.request} は URL を開いて読むためのモジュールです

@item 
@ref{10f,,urllib.error} は @ref{111,,urllib.request} が発生させる例外を持っています

@item 
@ref{110,,urllib.parse} は URL をパースするためのモジュールです

@item 
@ref{113,,urllib.robotparser} は @code{robots.txt} ファイルをパースするためのモジュールです
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node urllib request --- URL を開くための大規模なライブラリ,urllib response --- Response classes used by urllib,urllib --- URL を扱うモジュール群,インターネットプロトコルとサポート
@anchor{library/urllib request doc}@anchor{3f12}@anchor{library/urllib request module-urllib request}@anchor{111}@anchor{library/urllib request translation-repo}@anchor{3f13}@anchor{library/urllib request urllib-request-extensible-library-for-opening-urls}@anchor{3f14}
@subsection @code{urllib.request} --- URL を開くための大規模なライブラリ


@geindex module; urllib.request

`ソースコード:' Lib/urllib/request.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/urllib/request.py}


__________________________________________________________________


The @code{urllib.request} module defines functions and classes which help in
opening URLs (mostly HTTP) in a complex world --- basic and digest
authentication, redirections, cookies and more.


@subsubheading 参考


より高水準のHTTPクライアントインターフェースとして Requestsパッケージ@footnote{https://requests.readthedocs.io/en/master/} がお奨めです。


@cartouche
@quotation 警告 
On macOS it is unsafe to use this module in programs using
@ref{4b5,,os.fork()} because the @ref{3f15,,getproxies()} implementation for
macOS uses a higher-level system API. Set the environment variable
@code{no_proxy} to @code{*} to avoid this problem
(e.g. @code{os.environ["no_proxy"] = "*"}).
@end quotation
@end cartouche

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

The @code{urllib.request} module defines the following functions:

@geindex urlopen() (urllib.request モジュール)
@anchor{library/urllib request urllib request urlopen}@anchor{307}
@deffn {の関数} urllib.request.urlopen (url, data=None[, timeout], *, context=None)

Open `url', which can be either a string containing a valid, properly
encoded URL, or a @ref{11da,,Request} object.

`data' はサーバーに送信する追加データを指定するオブジェクトであるか @code{None} である必要があります。詳細は @ref{11da,,Request} を確認してください。

urllib.request モジュールは HTTP/1.1 を使用し、その HTTP リクエストに @code{Connection:close} ヘッダーを含みます。

任意引数 `timeout' には接続開始などのブロックする操作におけるタイムアウト時間を秒数で指定します (指定されなかった場合、グローバルのデフォルトタイムアウト時間が利用されます)。この引数は、 HTTP, HTTPS, FTP 接続でのみ有効です。

`context' を指定する場合は、様々な SSL オプションを記述する @ref{357,,ssl.SSLContext} インスタンスでなければなりません。
詳細は @ref{d36,,HTTPSConnection} を参照してください。

この関数は常にプロパティ `url'、 `headers'、および `status' を持ち、 @ref{1e1,,コンテキストマネージャ} として動作するオブジェクトを返します。これらのプロパティに関する詳細は @ref{3f16,,urllib.response.addinfourl} を確認してください。

HTTP および HTTPS URL の場合、この関数は、わずかに修正された @ref{12e5,,http.client.HTTPResponse} オブジェクトを返します。上記の3つの新しいメソッドに加えて、 msg 属性が @ref{12e5,,HTTPResponse} のドキュメンテーションで指定されているレスポンスヘッダーの代わりに @ref{3f17,,reason} 属性 --- サーバーから返された reason フレーズ --- と同じ情報を含んでいます。

FTP 、ファイルおよびデータURLの場合、この関数は @ref{3f16,,urllib.response.addinfourl} オブジェクトを返します。

プロトコルエラー発生時は @ref{2be,,URLError} を送出します。

どのハンドラもリクエストを処理しなかった場合には @code{None} を返すことがあるので注意してください (デフォルトでインストールされる グローバルハンドラの @ref{3f18,,OpenerDirector} は、 @ref{3f19,,UnknownHandler} を使って上記の問題が起きないようにしています)。

さらに、プロキシ設定が検出された場合(例えば @code{http_proxy} のような @code{*_proxy} 環境変数がセットされているなど)には @ref{1db5,,ProxyHandler} がデフォルトでインストールされ、これがプロキシを通してリクエストを処理するようにしています。

Python 2.6 以前のレガシーな @code{urllib.urlopen} 関数は廃止されました。@ref{307,,urllib.request.urlopen()} が過去の @code{urllib2.urlopen} に相当します。@code{urllib.urlopen} において辞書型オブジェクトで渡していたプロキシの扱いは、@ref{1db5,,ProxyHandler} オブジェクトを使用して取得できます。


The default opener raises an @ref{1c6e,,auditing event}
@code{urllib.Request} with arguments @code{fullurl}, @code{data}, @code{headers},
@code{method} taken from the request object.



バージョン 3.2 で変更: `cafile' および `capath' が追加されました。

HTTPS バーチャルホストがサポートされました (@ref{39d6,,ssl.HAS_SNI} が真の場合のみ)。

`data' にイテラブルなオブジェクトを指定できるようになりました。



バージョン 3.3 で変更: `cadefault' が追加されました。



バージョン 3.4.3 で変更: `context' が追加されました。



バージョン 3.10 で変更: HTTPS connection now send an ALPN extension with protocol indicator
@code{http/1.1} when no `context' is given. Custom `context' should set
ALPN protocols with @ref{1064,,set_alpn_protocols()}.



バージョン 3.13 で変更: Remove `cafile', `capath' and `cadefault' parameters: use the `context'
parameter instead.

@end deffn

@geindex install_opener() (urllib.request モジュール)
@anchor{library/urllib request urllib request install_opener}@anchor{3f1a}
@deffn {の関数} urllib.request.install_opener (opener)

指定された @ref{3f18,,OpenerDirector} のインスタンスを、デフォルトで利用されるグローバルの opener としてインストールします。 opener のインストールは、 urlopen にその opener を使って欲しいとき以外必要ありません。普段は単に @ref{307,,urlopen()} の代わりに @ref{11de,,OpenerDirector.open()} を利用してください。この関数は引数が本当に @ref{3f18,,OpenerDirector} のインスタンスであるかどうかはチェックしません。適切なインターフェースを持った任意のクラスを利用することができます。
@end deffn

@geindex build_opener() (urllib.request モジュール)
@anchor{library/urllib request urllib request build_opener}@anchor{309}
@deffn {の関数} urllib.request.build_opener ([handler, ...])

与えられた順番に URL ハンドラを連鎖させる @ref{3f18,,OpenerDirector}  のインスタンスを返します。 `handler' は @ref{3f1b,,BaseHandler} または @ref{3f1b,,BaseHandler} のサブクラスのインスタンスのどちらかです (どちらの場合も、コンストラクトは引数無しで呼び出せるようになっていなければなりません) 。クラス  @ref{1db5,,ProxyHandler} (proxy 設定が検出された場合), @ref{3f19,,UnknownHandler}, @ref{ef8,,HTTPHandler}, @ref{3f1c,,HTTPDefaultErrorHandler}, @ref{3f1d,,HTTPRedirectHandler}, @ref{3f1e,,FTPHandler}, @ref{3f1f,,FileHandler}, @ref{3f20,,HTTPErrorProcessor} については、そのクラスのインスタンスか、そのサブクラスのインスタンスが `handler'  に含まれていない限り、 `handler' よりも先に連鎖します。

Python が SSL をサポートするように設定してインストールされている場合 (すなわち、 @ref{d5,,ssl} モジュールを import できる場合) @ref{143c,,HTTPSHandler} も追加されます。

@ref{3f1b,,BaseHandler} サブクラスでも @code{handler_order} メンバー変数を変更して、ハンドラーリスト内での場所を変更できます。
@end deffn

@geindex pathname2url() (urllib.request モジュール)
@anchor{library/urllib request urllib request pathname2url}@anchor{2bf}
@deffn {の関数} urllib.request.pathname2url (path, *, add_scheme=False)

Convert the given local path to a @code{file:} URL. This function uses
@ref{d9c,,quote()} function to encode the path.

If `add_scheme' is false (the default), the return value omits the
@code{file:} scheme prefix. Set `add_scheme' to true to return a complete URL.

This example shows the function being used on Windows:

@example
>>> from urllib.request import pathname2url
>>> path = 'C:\\Program Files'
>>> pathname2url(path, add_scheme=True)
'file:///C:/Program%20Files'
@end example


バージョン 3.14 で変更: Windows drive letters are no longer converted to uppercase, and @code{:}
characters not following a drive letter no longer cause an
@ref{2c0,,OSError} exception to be raised on Windows.



バージョン 3.14 で変更: Paths beginning with a slash are converted to URLs with authority
sections. For example, the path @code{/etc/hosts} is converted to
the URL @code{///etc/hosts}.



バージョン 3.14 で変更: `add_scheme' パラメータが追加されました。

@end deffn

@geindex url2pathname() (urllib.request モジュール)
@anchor{library/urllib request urllib request url2pathname}@anchor{2bd}
@deffn {の関数} urllib.request.url2pathname (url, *, require_scheme=False, resolve_host=False)

Convert the given @code{file:} URL to a local path. This function uses
@ref{1afb,,unquote()} to decode the URL.

If `require_scheme' is false (the default), the given value should omit a
@code{file:} scheme prefix. If `require_scheme' is set to true, the given
value should include the prefix; a @ref{2be,,URLError} is raised
if it doesn't.

The URL authority is discarded if it is empty, @code{localhost}, or the local
hostname. Otherwise, if `resolve_host' is set to true, the authority is
resolved using @ref{3996,,socket.gethostbyname()} and discarded if it matches a
local IP address (as per 
@geindex RFC; RFC 8089 Section 3
RFC 8089 §3@footnote{https://datatracker.ietf.org/doc/html/rfc8089.html#section-3}). If the
authority is still unhandled, then on Windows a UNC path is returned, and
on other platforms a @ref{2be,,URLError} is raised.

This example shows the function being used on Windows:

@example
>>> from urllib.request import url2pathname
>>> url = 'file:///C:/Program%20Files'
>>> url2pathname(url, require_scheme=True)
'C:\\Program Files'
@end example


バージョン 3.14 で変更: Windows drive letters are no longer converted to uppercase, and @code{:}
characters not following a drive letter no longer cause an
@ref{2c0,,OSError} exception to be raised on Windows.



バージョン 3.14 で変更: The URL authority is discarded if it matches the local hostname.
Otherwise, if the authority isn't empty or @code{localhost}, then on
Windows a UNC path is returned (as before), and on other platforms a
@ref{2be,,URLError} is raised.



バージョン 3.14 で変更: The URL query and fragment components are discarded if present.



バージョン 3.14 で変更: `require_scheme' および `resolve_host' パラメータが追加されました。

@end deffn

@geindex getproxies() (urllib.request モジュール)
@anchor{library/urllib request urllib request getproxies}@anchor{3f15}
@deffn {の関数} urllib.request.getproxies ()

このヘルパー関数はスキーマからプロキシサーバーのURLへのマッピングを行う辞書を返します。この関数はまず、どのOSでも最初に @code{<scheme>_proxy} という名前の環境変数を大文字小文字を区別せずにスキャンします。そこで見つからなかった場合、 macOS の場合は macOS システム環境設定を、 Windows の場合はシステムレジストリを参照します。もし小文字と大文字の環境変数が両方存在する (そして値が一致しない) なら、小文字の環境変数が優先されます。

@cartouche
@quotation 注釈 
もし環境変数 @code{REQUEST_METHOD} が設定されていたら (これは通常スクリプトが CGI 環境で動いていることを示しています)、環境変数 @code{HTTP_PROXY} (大文字の @code{_PROXY}) は無視されます。その理由は、クライアントが "Proxy:" HTTP ヘッダーを使ってこの環境変数を注入できるからです。もし CGI 環境で HTTP プロキシを使う必要があれば、 @code{ProxyHandler} を明示的に使用するか、環境変数名を小文字にしてください (あるいは、少なくともサフィックスを @code{_proxy} にしてください) 。
@end quotation
@end cartouche
@end deffn

以下のクラスが提供されています:

@geindex Request (urllib.request のクラス)
@anchor{library/urllib request urllib request Request}@anchor{11da}
@deffn {クラス} urllib.request.Request (url, data=None, headers=@{@}, origin_req_host=None, unverifiable=False, method=None)

このクラスは URL リクエストを抽象化したものです。

`url' should be a string containing a valid, properly encoded URL.

`data' must be an object specifying additional data to send to the
server, or @code{None} if no such data is needed.  Currently HTTP
requests are the only ones that use `data'.  The supported object
types include bytes, file-like objects, and iterables of bytes-like objects.
If no @code{Content-Length} nor @code{Transfer-Encoding} header field
has been provided, @ref{ef8,,HTTPHandler} will set these headers according
to the type of `data'.  @code{Content-Length} will be used to send
bytes objects, while @code{Transfer-Encoding: chunked} as specified in
@geindex RFC; RFC 7230
RFC 7230@footnote{https://datatracker.ietf.org/doc/html/rfc7230.html}, Section 3.3.1 will be used to send files and other iterables.

HTTP POST リクエストメソッドでは `data' は標準の @code{application/x-www-form-urlencoded} 形式のバッファーでなければなりません。 @ref{1095,,urllib.parse.urlencode()} 関数は、マップ型あるいは 2 タプルのシーケンスを取り、この形式の ASCII 文字列を返します。これは `data' パラメーターとして使用される前に bytes 型にエンコードされなければなりません。

`headers' は辞書でなければなりません。この辞書は @ref{3f21,,add_header()} を辞書のキーおよび値を引数として呼び出した時と同じように扱われます。この引数は、多くの場合ブラウザーが何であるかを特定する @code{User-Agent} ヘッダーの値を "偽装" するために用いられます。これは一部の HTTP サーバーが、スクリプトからのアクセスを禁止するために一般的なブラウザーの @code{User-Agent} ヘッダーしか許可しないためです。例えば、 Mozilla Firefox は @code{User-Agent} に @code{"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"} のように設定し、 @ref{10e,,urllib} はデフォルトで @code{"Python-urllib/2.6"} (Python 2.6の場合) と設定します。headersのすべてのキーはキャメルケースで送信されます。

An appropriate @code{Content-Type} header should be included if the `data'
argument is present.  If this header has not been provided and `data'
is not @code{None}, @code{Content-Type: application/x-www-form-urlencoded} will
be added as a default.

次の2つの引数は、サードパーティの HTTP クッキーを正しく扱いたい場合にのみ関係してきます:

`origin_req_host' は、 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} で定義されている元のトランザクションにおけるリクエストホスト (request-host of the origin transaction) です。デフォルトの値は @code{http.cookiejar.request_host(self)} です。この値は、ユーザーによって開始された元々のリクエストにおけるホスト名や IP アドレスです。例えば、もしリクエストがある HTML ドキュメント内の画像を指していれば、この値は画像を含んでいるページへのリクエストにおけるリクエストホストになるはずです。

`unverifiable' は、 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} の定義において、該当するリクエストが証明不能 (unverifiable) であるかどうかを示します。デフォルトの値は @code{False} です。証明不能なリクエストとは、ユーザが受け入れの可否を選択できないような URL を持つリクエストのことです。例えば、リクエストが HTML ドキュメント中の画像であり、ユーザがこの画像を自動的に取得するか どうかを選択できない場合には、証明不能フラグは True になります。

`method' は使用される HTTP リクエストメソッド (例: @code{'HEAD'}) を示す文字列でなければなりません。もし与えられた場合、この値は属性 @ref{11db,,method} に格納され、 @ref{1381,,get_method()} で使用されます。デフォルトは `data' が @code{None} であれば @code{'GET'} で、そうでなければ @code{'POST'} です。サブクラスは @ref{11db,,method} 属性をクラス自身に設定して、異なるデフォルトメソッドを示すことができます。

@cartouche
@quotation 注釈 
The request will not work as expected if the data object is unable
to deliver its content more than once (e.g. a file or an iterable
that can produce the content only once) and the request is retried
for HTTP redirects or authentication.  The `data' is sent to the
HTTP server right away after the headers.  There is no support for
a 100-continue expectation in the library.
@end quotation
@end cartouche


バージョン 3.3 で変更: 引数 @ref{11db,,Request.method} が Request クラスに追加されました。



バージョン 3.4 で変更: @ref{11db,,Request.method} のデフォルト値はクラスレベルで指定されることがあります。



バージョン 3.6 で変更: Do not raise an error if the @code{Content-Length} has not been
provided and `data' is neither @code{None} nor a bytes object.
Fall back to use chunked transfer encoding instead.

@end deffn

@geindex OpenerDirector (urllib.request のクラス)
@anchor{library/urllib request urllib request OpenerDirector}@anchor{3f18}
@deffn {クラス} urllib.request.OpenerDirector

@ref{3f18,,OpenerDirector} クラスは、 @ref{3f1b,,BaseHandler} の連鎖的に呼び出して URL を開きます。このクラスはハンドラをどのように連鎖させるか、またどのようにエラーをリカバリするかを管理します。
@end deffn

@geindex BaseHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request BaseHandler}@anchor{3f1b}
@deffn {クラス} urllib.request.BaseHandler

このクラスはハンドラ連鎖に登録される全てのハンドラがベースとしているクラスです -- このクラスでは登録のための単純なメカニズムだけを扱います。
@end deffn

@geindex HTTPDefaultErrorHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPDefaultErrorHandler}@anchor{3f1c}
@deffn {クラス} urllib.request.HTTPDefaultErrorHandler

HTTP エラーレスポンスのデフォルトハンドラーを定義するクラスです; すべてのレスポンスは @ref{11e0,,HTTPError} 例外に変換されます。
@end deffn

@geindex HTTPRedirectHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPRedirectHandler}@anchor{3f1d}
@deffn {クラス} urllib.request.HTTPRedirectHandler

リダイレクションを扱うクラスです。
@end deffn

@geindex HTTPCookieProcessor (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPCookieProcessor}@anchor{3f22}
@deffn {クラス} urllib.request.HTTPCookieProcessor (cookiejar=None)

HTTP Cookie を扱うためのクラスです。
@end deffn

@geindex ProxyHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request ProxyHandler}@anchor{1db5}
@deffn {クラス} urllib.request.ProxyHandler (proxies=None)

このクラスはプロキシを通過してリクエストを送らせます。引数 `proxies' を与える場合、プロトコル名からプロキシの URL へ対応付ける辞書でなくてはなりません。標準では、プロキシのリストを環境変数 @code{<protocol>_proxy} から読み出します。プロキシ環境変数が設定されていない場合は、 Windows 環境では、 レジストリのインターネット設定セクションからプロキシ設定を手に入れ、 macOS 環境では、 macOS システム設定フレームワーク (System Configuration Framework) からプロキシ情報を取得します。

自動検出されたproxyを無効にするには、空の辞書を渡してください。

@geindex no_proxy
@geindex 環境変数; no_proxy
@code{no_proxy} 環境変数は、proxyを利用せずにアクセスするべきホストを指定するために利用されます。設定する場合は、カンマ区切りの、ホストネーム suffix のリストで、オプションとして @code{:port} を付けることができます。例えば、 @code{cern.ch,ncsa.uiuc.edu,some.host:8080}.

@cartouche
@quotation 注釈 
変数 @code{REQUEST_METHOD} が設定されている場合、 @code{HTTP_PROXY} は無視されます; @ref{3f15,,getproxies()} のドキュメンテーションを参照してください。
@end quotation
@end cartouche
@end deffn

@geindex HTTPPasswordMgr (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPPasswordMgr}@anchor{3f23}
@deffn {クラス} urllib.request.HTTPPasswordMgr

@code{(realm, uri) -> (user, password)} の対応付けデータベースを保持します。
@end deffn

@geindex HTTPPasswordMgrWithDefaultRealm (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithDefaultRealm}@anchor{3f24}
@deffn {クラス} urllib.request.HTTPPasswordMgrWithDefaultRealm

@code{(realm, uri) -> (user, password)}  の対応付けデータベースを保持します。レルム @code{None} はその他諸々のレルムを表し、他のレルムが該当しない場合に検索されます。
@end deffn

@geindex HTTPPasswordMgrWithPriorAuth (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth}@anchor{1094}
@deffn {クラス} urllib.request.HTTPPasswordMgrWithPriorAuth

@code{uri -> is_authenticated} マッピングのデータベースも持つ @ref{3f24,,HTTPPasswordMgrWithDefaultRealm} のバリエーションです。最初に @code{401} レスポンスを待つのではなく直ちに認証情報を送るときの条件を判断するために、 BasicAuth ハンドラによって使われます。


Added in version 3.5.

@end deffn

@geindex AbstractBasicAuthHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request AbstractBasicAuthHandler}@anchor{1c6f}
@deffn {クラス} urllib.request.AbstractBasicAuthHandler (password_mgr=None)

これは、リモートホストとプロキシの両方に対して HTTP 認証を行うことを助ける mixin クラスです。 `password_mgr' は、もし与えられたら @ref{3f23,,HTTPPasswordMgr} と互換性のあるオブジェクトでなければなりません; サポートすべきインターフェースに関する情報は @ref{3f25,,HTTPPasswordMgr オブジェクト} 節を参照してください。もし `passwd_mgr' が @code{is_authenticated} と @code{update_authenticated} メソッドも提供するなら (@ref{3f26,,HTTPPasswordMgrWithPriorAuth オブジェクト} を参照)、ハンドラは与えられた URI に対する @code{is_authenticated} の結果を用いてリクエストにおいて認証情報を送るかどうかを決定します。もし @code{is_authenticated} がその URI に対して @code{True} を返すなら、認証情報が送られます。 @code{is_authenticated} が @code{False} なら認証情報は送られません。そして、もし @code{401} レスポンスを受け取ったら、認証情報を付けて改めてリクエストが送信されます。もし認証が成功したら、それ以降その URI またはその親 URI に対して行われるリクエストが認証情報を自動的に含むように、 URI に対して @code{is_authenticated} を @code{True} に設定するために @code{update_authenticated} が呼ばれます。


Added in version 3.5: @code{is_authenticated} サポートが追加されました。

@end deffn

@geindex HTTPBasicAuthHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPBasicAuthHandler}@anchor{3f27}
@deffn {クラス} urllib.request.HTTPBasicAuthHandler (password_mgr=None)

遠隔ホストとの間での認証を扱います。 `password_mgr' を与える場合、 @ref{3f23,,HTTPPasswordMgr} と互換性がなければなりません; 互換性のためにサポートしなければならないインターフェースについての情報はセクション @ref{3f25,,HTTPPasswordMgr オブジェクト} を参照してください。HTTPBasicAuthHandler は、間違った認証スキーマが与えられると @ref{2ec,,ValueError} を送出します。
@end deffn

@geindex ProxyBasicAuthHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request ProxyBasicAuthHandler}@anchor{3f28}
@deffn {クラス} urllib.request.ProxyBasicAuthHandler (password_mgr=None)

プロキシとの間での認証を扱います。 `password_mgr' を与える場合、 @ref{3f23,,HTTPPasswordMgr} と互換性が なければなりません;  互換性のためにサポートしなければならないインターフェースについての情報はセクション @ref{3f25,,HTTPPasswordMgr オブジェクト} を参照してください。
@end deffn

@geindex AbstractDigestAuthHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request AbstractDigestAuthHandler}@anchor{1d6b}
@deffn {クラス} urllib.request.AbstractDigestAuthHandler (password_mgr=None)

このクラスはHTTP 認証を補助するための混ぜ込みクラス (mixin class) です。遠隔ホストとプロキシの両方に対応しています。 `password_mgr' を与える場合、 @ref{3f23,,HTTPPasswordMgr} と互換性がなければなりません; 互換性のためにサポートしなければならないインターフェースについての情報はセクション @ref{3f25,,HTTPPasswordMgr オブジェクト} を参照してください。


バージョン 3.14 で変更: Added support for HTTP digest authentication algorithm @code{SHA-256}.

@end deffn

@geindex HTTPDigestAuthHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPDigestAuthHandler}@anchor{3f29}
@deffn {クラス} urllib.request.HTTPDigestAuthHandler (password_mgr=None)

リモートホストとの認証を扱います。`password_mgr' を与える場合、@ref{3f23,,HTTPPasswordMgr} と互換性のあるものでなければなりません。サポートしなければならないインターフェースについての情報は @ref{3f25,,HTTPPasswordMgr オブジェクト} 節を参照してください。Digest 認証ハンドラーと Basic 認証ハンドラーの両方が追加された場合、常に Digest 認証を先に試みます。Digest 認証が 40x のレスポンスを再び返すと、Basic 認証ハンドラーに送信されます。このハンドラーメソッドは、Digest および Basic 以外の認証スキームが存在する場合は @ref{2ec,,ValueError} を送出します。


バージョン 3.3 で変更: 未サポートの認証スキームでは @ref{2ec,,ValueError} を送出するようになりました。

@end deffn

@geindex ProxyDigestAuthHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request ProxyDigestAuthHandler}@anchor{3f2a}
@deffn {クラス} urllib.request.ProxyDigestAuthHandler (password_mgr=None)

プロキシとの間での認証を扱います。 `password_mgr' を与える場合、 @ref{3f23,,HTTPPasswordMgr} と互換性が なければなりません;  互換性のためにサポートしなければならないインターフェースについての情報はセクション @ref{3f25,,HTTPPasswordMgr オブジェクト} を参照してください。
@end deffn

@geindex HTTPHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPHandler}@anchor{ef8}
@deffn {クラス} urllib.request.HTTPHandler

HTTP の URL を開きます。
@end deffn

@geindex HTTPSHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPSHandler}@anchor{143c}
@deffn {クラス} urllib.request.HTTPSHandler (debuglevel=0, context=None, check_hostname=None)

HTTPS で URL を開きます。`context' および `check_hostname' は @ref{d36,,http.client.HTTPSConnection} のものと同じ意味です。


バージョン 3.2 で変更: `context' および `check_hostname' が追加されました。

@end deffn

@geindex FileHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request FileHandler}@anchor{3f1f}
@deffn {クラス} urllib.request.FileHandler

ローカルファイルを開きます。
@end deffn

@geindex DataHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request DataHandler}@anchor{11d9}
@deffn {クラス} urllib.request.DataHandler

data URL を開きます。


Added in version 3.4.

@end deffn

@geindex FTPHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request FTPHandler}@anchor{3f1e}
@deffn {クラス} urllib.request.FTPHandler

FTP の URL を開きます。
@end deffn

@geindex CacheFTPHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request CacheFTPHandler}@anchor{1a99}
@deffn {クラス} urllib.request.CacheFTPHandler

FTP の URL を開きます。遅延を最小限にするために、開かれている FTP  接続に対するキャッシュを保持します。
@end deffn

@geindex UnknownHandler (urllib.request のクラス)
@anchor{library/urllib request urllib request UnknownHandler}@anchor{3f19}
@deffn {クラス} urllib.request.UnknownHandler

その他諸々のためのクラスで、未知のプロトコルの URL を開きます。
@end deffn

@geindex HTTPErrorProcessor (urllib.request のクラス)
@anchor{library/urllib request urllib request HTTPErrorProcessor}@anchor{3f20}
@deffn {クラス} urllib.request.HTTPErrorProcessor

HTTP エラー応答の処理をします。
@end deffn

@menu
* Request オブジェクト:: 
* OpenerDirector オブジェクト:: 
* BaseHandler オブジェクト:: 
* HTTPRedirectHandler オブジェクト:: 
* HTTPCookieProcessor オブジェクト:: 
* ProxyHandler オブジェクト:: 
* HTTPPasswordMgr オブジェクト:: 
* HTTPPasswordMgrWithPriorAuth オブジェクト:: 
* AbstractBasicAuthHandler オブジェクト:: 
* HTTPBasicAuthHandler オブジェクト:: 
* ProxyBasicAuthHandler オブジェクト:: 
* AbstractDigestAuthHandler オブジェクト:: 
* HTTPDigestAuthHandler オブジェクト:: 
* ProxyDigestAuthHandler オブジェクト:: 
* HTTPHandler オブジェクト:: 
* HTTPSHandler オブジェクト:: 
* FileHandler オブジェクト:: 
* DataHandler オブジェクト:: 
* FTPHandler オブジェクト:: 
* CacheFTPHandler オブジェクト:: 
* UnknownHandler オブジェクト:: 
* HTTPErrorProcessor オブジェクト:: 
* 使用例: 使用例<37>. 
* レガシーインターフェース: レガシーインターフェース<2>. 
* urllib.request Restrictions: urllib request Restrictions. 

@end menu

@node Request オブジェクト,OpenerDirector オブジェクト,,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request id1}@anchor{3f2b}@anchor{library/urllib request request-objects}@anchor{3f2c}
@subsubsection Request オブジェクト


以下のメソッドは @ref{11da,,Request} の公開インターフェースについて説明しています。これらはすべてサブクラスでオーバーライドできます。また、解析したリクエストを調査するためにクライアントで使用するいくつかの属性も定義します。

@geindex full_url (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request full_url}@anchor{11dc}
@deffn {の属性} Request.full_url

コンストラクターに渡されたオリジナルの URL です。


バージョン 3.4 で変更.


Request.full_url は、 setter, getter, deleter を持つプロパティです。もし存在すれば、 @ref{11dc,,full_url} はオリジナルのリクエスト URL フラグメント付きで返します。
@end deffn

@geindex type (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request type}@anchor{3f2d}
@deffn {の属性} Request.type

URI スキームです。
@end deffn

@geindex host (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request host}@anchor{3f2e}
@deffn {の属性} Request.host

URI オーソリティです。通常はホスト名ですが、コロンで区切られたポート番号が付随することもあります。
@end deffn

@geindex origin_req_host (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request origin_req_host}@anchor{3f2f}
@deffn {の属性} Request.origin_req_host

リクエストしたオリジナルのホスト名です。ポート番号はつきません。
@end deffn

@geindex selector (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request selector}@anchor{3f30}
@deffn {の属性} Request.selector

URI パスです。@ref{11da,,Request} がプロキシを使用する場合、セレクターはプロキシに渡される完全な URL になります。
@end deffn

@geindex data (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request data}@anchor{11dd}
@deffn {の属性} Request.data

リクエストのエンティティボディか、指定されない場合は @code{None} になります。


バージョン 3.4 で変更: @ref{11dd,,Request.data} の値が変更されると、もしそれ以前に "Content-Length" ヘッダーの値が設定または計算されていたらヘッダーが削除されるようになりました。

@end deffn

@geindex unverifiable (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request unverifiable}@anchor{3f31}
@deffn {の属性} Request.unverifiable

リクエストが 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} で定義された証明不能 (unverifiable) であるかどうかを示す論理値です。
@end deffn

@geindex method (urllib.request.Request の属性)
@anchor{library/urllib request urllib request Request method}@anchor{11db}
@deffn {の属性} Request.method

HTTP リクエストで使うメソッドです。
デフォルト値は @ref{885,,None} で、このときは使うメソッドを @ref{1381,,get_method()} が通常の方法で決定するということになります。
この値を設定する (従って @ref{1381,,get_method()} のデフォルトの決定を上書きする) 方法は、 @ref{11da,,Request} サブクラスでのクラスレベルの設定処理でデフォルト値を提供するか、 @ref{11da,,Request} のコンストラクタの `method' 引数へ値を渡すかです。


Added in version 3.3.



バージョン 3.4 で変更: サブクラスでデフォルト値が設定できるようになりました; 以前はコンストラクタ引数からしか設定できませんでした。

@end deffn

@geindex get_method() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request get_method}@anchor{1381}
@deffn {メソッド} Request.get_method ()

HTTP リクエストメソッドを示す文字列を返します。@ref{11db,,Request.method} が @code{None} でなければその値を返します。そうでない場合、@ref{11dd,,Request.data} が @code{None} なら @code{'GET'} を、そうでなければ @code{'POST'} を返します。これは HTTP リクエストに対してのみ意味を持ちます。


バージョン 3.3 で変更: get_method は @ref{11db,,Request.method} の値を参照するようになりました。

@end deffn

@geindex add_header() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request add_header}@anchor{3f21}
@deffn {メソッド} Request.add_header (key, val)

リクエストに新たなヘッダーを追加します。ヘッダーは HTTP ハンドラ以外のハンドラでは無視されます。HTTP ハンドラでは、引数はサーバに送信される ヘッダーのリストに追加されます。同じ名前を持つヘッダを 2 つ以上持つことはできず、 `key' の衝突が生じた場合、後で追加したヘッダーが前に 追加したヘッダーを上書きします。現時点では、この機能は HTTP の機能を損ねることはありません。というのは、複数回呼び出したときに意味を 持つようなヘッダーには、どれもただ一つのヘッダーを使って同じ機能を果たすための (ヘッダー特有の) 方法があるからです。このメソッドを使って追加されたヘッダーはリダイレクトされたリクエストにも追加されることに注意してください。
@end deffn

@geindex add_unredirected_header() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request add_unredirected_header}@anchor{3f32}
@deffn {メソッド} Request.add_unredirected_header (key, header)

リダイレクトされたリクエストには追加されないヘッダーを追加します。
@end deffn

@geindex has_header() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request has_header}@anchor{3f33}
@deffn {メソッド} Request.has_header (header)

インスタンスが名前つきヘッダーであるかどうかを (通常のヘッダーと非リダイレクトヘッダの両方を調べて) 返します。
@end deffn

@geindex remove_header() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request remove_header}@anchor{11df}
@deffn {メソッド} Request.remove_header (header)

リクエストインスタンス (の通常のヘッダーと非リダイレクトヘッダーの両方) から名前つきヘッダーを削除します。


Added in version 3.4.

@end deffn

@geindex get_full_url() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request get_full_url}@anchor{3f34}
@deffn {メソッド} Request.get_full_url ()

コンストラクタで与えられた URL を返します。


バージョン 3.4 で変更.


@ref{11dc,,Request.full_url} を返します。
@end deffn

@geindex set_proxy() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request set_proxy}@anchor{3f35}
@deffn {メソッド} Request.set_proxy (host, type)

リクエストがプロキシサーバを経由するように準備します。 `host' および `type' はインスタンスのもとの設定と置き換えられ ます。インスタンスのセレクタはコンストラクタに与えたもともとの URL になります。
@end deffn

@geindex get_header() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request get_header}@anchor{3f36}
@deffn {メソッド} Request.get_header (header_name, default=None)

指定されたヘッダーの値を返します。ヘッダーがない場合は、 `default' の値を返します。
@end deffn

@geindex header_items() (urllib.request.Request のメソッド)
@anchor{library/urllib request urllib request Request header_items}@anchor{3f37}
@deffn {メソッド} Request.header_items ()

リクエストヘッダーの値を、タプル (header_name, header_value) のリストで返します。
@end deffn


バージョン 3.4 で変更: 3.3 から非推奨だった Request オブジェクトのメソッド add_data, has_data, get_data, get_type, get_host, get_selector, get_origin_req_host, is_unverifiable が削除されました。


@node OpenerDirector オブジェクト,BaseHandler オブジェクト,Request オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request opener-director-objects}@anchor{3f38}@anchor{library/urllib request openerdirector-objects}@anchor{3f39}
@subsubsection OpenerDirector オブジェクト


@ref{3f18,,OpenerDirector} インスタンスは以下のメソッドを持っています:

@geindex add_handler() (urllib.request.OpenerDirector のメソッド)
@anchor{library/urllib request urllib request OpenerDirector add_handler}@anchor{3f3a}
@deffn {メソッド} OpenerDirector.add_handler (handler)

`handler' should be an instance of @ref{3f1b,,BaseHandler}.  The following methods
are searched, and added to the possible chains (note that HTTP errors are a
special case).  Note that, in the following, `protocol' should be replaced
with the actual protocol to handle, for example @code{http_response()} would
be the HTTP protocol response handler.  Also `type' should be replaced with
the actual HTTP code, for example @code{http_error_404()} would handle HTTP
404 errors.


@itemize *

@item 
@code{<protocol>_open()} --- ハンドラーが `protocol' の URL を開く方法を知っているかどうかを調べます。

詳細は、 @ref{3f3b,,BaseHandler.<protocol>_open()} を参照してください。

@item 
@code{http_error_<type>()} --- ハンドラーが HTTP エラーコード `type' の処理方法を知っていることを示すシグナルです。

詳細は、 @ref{3f3c,,BaseHandler.http_error_<nnn>()} を参照してください。

@item 
@code{<protocol>_error()} --- ハンドラーが (@code{http} でない) `protocol' のエラーを処理する方法を知っていることを示すシグナルです。

@item 
@code{<protocol>_request()} --- ハンドラーが `protocol' リクエストのプリプロセス方法を知っていることを示すシグナルです。

詳細は、 @ref{3f3d,,BaseHandler.<protocol>_request()} を参照してください。

@item 
@code{<protocol>_response()} --- ハンドラーが `protocol' リクエストのポストプロセス方法を知っていることを示すシグナルです。

詳細は、 @ref{3f3e,,BaseHandler.<protocol>_response()} を参照してください。
@end itemize
@end deffn

@geindex open() (urllib.request.OpenerDirector のメソッド)
@anchor{library/urllib request urllib request OpenerDirector open}@anchor{11de}
@deffn {メソッド} OpenerDirector.open (url, data=None[, timeout])

与えられた `url' (リクエストオブジェクトでも文字列でもかまいません) を開きます。オプションとして `data' を与えることができます。 引数、戻り値、および送出される例外は @ref{307,,urlopen()} と同じです (@ref{307,,urlopen()} の場合、標準でインストールされている グローバルな @ref{3f18,,OpenerDirector} の @ref{316,,open()} メソッドを呼び出します) 。 オプションの `timeout' 引数は、接続開始のようなブロックする処理におけるタイムアウト時間を 秒数で指定します。(指定しなかった場合は、グローバルのデフォルト設定が利用されます) タイムアウト機能は、 HTTP, HTTPS, FTP 接続でのみ有効です。
@end deffn

@geindex error() (urllib.request.OpenerDirector のメソッド)
@anchor{library/urllib request urllib request OpenerDirector error}@anchor{3f3f}
@deffn {メソッド} OpenerDirector.error (proto, *args)

与えられたプロトコルにおけるエラーを処理します。このメソッドは与えられたプロトコルにおける登録済みのエラーハンドラを (プロトコル固有の) 引数で呼び出します。 HTTP プロトコルは特殊なケースで、特定のエラーハンドラを選び出すのに HTTP レスポンスコードを使います; ハンドラクラスの @code{http_error_<type>()} メソッドを参照してください。

戻り値および送出される例外は @ref{307,,urlopen()} と同じものです。
@end deffn

OpenerDirector オブジェクトは、以下の 3 つのステージに分けて URL を開きます:

各ステージで OpenerDirector オブジェクトのメソッドがどのような順で呼び出されるかは、ハンドラインスタンスの並び方で決まります。


@enumerate 

@item 
@code{<protocol>_request()} 形式のメソッドを持つすべてのハンドラーに対してそのメソッドを呼び出し、リクエストのプリプロセスを行います。

@item 
@code{<protocol>_open()} のようなメソッドでハンドラーが呼び出され、リクエストを処理します。このステージではハンドラーが非-@ref{885,,None} 値 (例: レスポンス) か例外 (通常は @ref{2be,,URLError}) を返した時点で終了します。例外は伝搬できます。

実際には、上のアルゴリズムではまず @ref{3f40,,default_open()} という名前のメソッドを呼び出します。このメソッドがすべて @ref{885,,None} を返す場合、同じアルゴリズムを繰り返して、今度は @code{<protocol>_open()} 形式のメソッドを試します。メソッドがすべて @ref{885,,None} を返すと、さらに同じアルゴリズムを繰り返して @ref{3f41,,unknown_open()} を呼び出します。

これらのメソッドの実装には、親となる @ref{3f18,,OpenerDirector} インスタンスの @code{open()} や @code{error()} といったメソッド呼び出しが入る場合があるので注意してください。

@item 
@code{<protocol>_response()} 形式のメソッドを持つすべてのハンドラーに対してそのメソッドを呼び出し、リクエストのポストプロセスを行います。
@end enumerate

@node BaseHandler オブジェクト,HTTPRedirectHandler オブジェクト,OpenerDirector オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request base-handler-objects}@anchor{3f42}@anchor{library/urllib request basehandler-objects}@anchor{3f43}
@subsubsection BaseHandler オブジェクト


@ref{3f1b,,BaseHandler} オブジェクトは直接的に役に立つ 2 つのメソッドと、その他として派生クラスで使われることを想定したメソッドを 提供します。以下は直接的に使うためのメソッドです:

@geindex add_parent() (urllib.request.BaseHandler のメソッド)
@anchor{library/urllib request urllib request BaseHandler add_parent}@anchor{3f44}
@deffn {メソッド} BaseHandler.add_parent (director)

親オブジェクトとして、 @code{director} を追加します。
@end deffn

@geindex close() (urllib.request.BaseHandler のメソッド)
@anchor{library/urllib request urllib request BaseHandler close}@anchor{3f45}
@deffn {メソッド} BaseHandler.close ()

全ての親オブジェクトを削除します。
@end deffn

以下の属性およびメソッドは @ref{3f1b,,BaseHandler} から派生したクラスでのみ使われます。

@cartouche
@quotation 注釈 
慣習的に、 @code{<protocol>_request()} や @code{<protocol>_response()} といったメソッドを定義している サブクラスは @code{*Processor`と名づけ、その他は :class:}!*Handler` と名づけることになっています
@end quotation
@end cartouche

@geindex parent (urllib.request.BaseHandler の属性)
@anchor{library/urllib request urllib request BaseHandler parent}@anchor{3f46}
@deffn {の属性} BaseHandler.parent

有効な @ref{3f18,,OpenerDirector} です。この値は違うプロトコルを使って URL を開く場合やエラーを処理する際に使われます。
@end deffn

@geindex default_open() (urllib.request.BaseHandler のメソッド)
@anchor{library/urllib request urllib request BaseHandler default_open}@anchor{3f40}
@deffn {メソッド} BaseHandler.default_open (req)

このメソッドは @ref{3f1b,,BaseHandler} では定義されて `いません' 。しかし、全ての URL をキャッチさせたいなら、サブクラスで定義する 必要があります。

このメソッドが実装されていれば、@ref{3f18,,OpenerDirector} の親クラスによって呼び出されます。これは @ref{3f18,,OpenerDirector} の @ref{11de,,open()} の戻り値で表されるファイルライクオブジェクトか、または @code{None} を返さなければならず、真に想定外の事態が発生した場合を除き、@ref{2be,,URLError} を送出しなければなりません (例えば、@ref{179e,,MemoryError} は @ref{2be,,URLError} にマップしてはなりません)。

このメソッドはプロトコル固有のオープンメソッドが呼び出される前に呼び出されます。
@end deffn

@anchor{library/urllib request protocol-open}@anchor{3f3b}
@deffn {メソッド} BaseHandler.<protocol>_open(req)

このメソッドは @ref{3f1b,,BaseHandler} では定義されて `いません' 。しかしプロトコルの URL をキャッチしたいなら、サブクラスで定義する必要があります。

このメソッドが定義されていた場合、 @ref{3f18,,OpenerDirector} から呼び出されます。戻り値は @ref{3f40,,default_open()} と同じでなければなりません。
@end deffn

@geindex unknown_open() (urllib.request.BaseHandler のメソッド)
@anchor{library/urllib request urllib request BaseHandler unknown_open}@anchor{3f41}
@deffn {メソッド} BaseHandler.unknown_open (req)

このメソッドは @ref{3f1b,,BaseHandler} では定義されて `いません' 。しかし URL を開くための特定のハンドラが登録されていないような URL をキャッチしたいなら、サブクラスで定義する必要があります。

このメソッドが定義されていた場合、 @ref{3f46,,parent} @ref{3f18,,OpenerDirector} から呼び出されます。戻り値は @ref{3f40,,default_open()} と同じでなければなりません。
@end deffn

@geindex http_error_default() (urllib.request.BaseHandler のメソッド)
@anchor{library/urllib request urllib request BaseHandler http_error_default}@anchor{3f47}
@deffn {メソッド} BaseHandler.http_error_default (req, fp, code, msg, hdrs)

このメソッドは @ref{3f1b,,BaseHandler} では定義されて `いません' 。しかしその他の処理されなかった HTTP エラーを処理する機能をもたせたいなら、サブクラスで定義する必要があります。このメソッドはエラーに遭遇した @ref{3f18,,OpenerDirector} から自動的に呼び出されます。その他の状況では普通呼び出すべきではありません。

@ref{3f18,,OpenerDirector} will call this method with five positional arguments:


@enumerate 

@item 
@ref{11da,,Request} オブジェクト

@item 
a file-like object with the HTTP error body,

@item 
the three-digit code of the error, as a string,

@item 
the user-visible explanation of the code, as a string, and

@item 
the headers of the error, as a mapping object.
@end enumerate

返される値および送出される例外は @ref{307,,urlopen()} と同じものでなければなりません。
@end deffn

@anchor{library/urllib request http-error-nnn}@anchor{3f3c}
@deffn {メソッド} BaseHandler.http_error_<nnn>(req, fp, code, msg, hdrs)

`nnn' は 3 桁の 10 進数からなる HTTP エラーコードでなくてはなりません。このメソッドも @ref{3f1b,,BaseHandler} では定義されていませんが、サブクラスのインスタンスで定義されていた場合、エラーコード `nnn' の HTTP エラーが発生した際に呼び出されます。

特定の HTTP エラーに対する処理を行うためには、このメソッドをサブクラスでオーバライドする必要があります。

引数、返される値、および送出される例外は @ref{3f47,,http_error_default()} と同じものでなければなりません。
@end deffn

@anchor{library/urllib request protocol-request}@anchor{3f3d}
@deffn {メソッド} BaseHandler.<protocol>_request(req)

このメソッドは @ref{3f1b,,BaseHandler} では `定義されていません' が、サブクラスで特定のプロトコルのリクエストのプリプロセスを行いたい場合には定義する必要があります。

このメソッドが定義されていると、親となる @ref{3f18,,OpenerDirector} から呼び出されます。その際、 `req' は @ref{11da,,Request} オブジェクトになります。戻り値は @ref{11da,,Request} オブジェクトでなければなりません。
@end deffn

@anchor{library/urllib request protocol-response}@anchor{3f3e}
@deffn {メソッド} BaseHandler.<protocol>_response(req, response)

このメソッドは @ref{3f1b,,BaseHandler} では `定義されていません' が、サブクラスで特定のプロトコルのリクエストのポストプロセスを行いたい場合には定義する必要があります。

このメソッドが定義されていると、親となる @ref{3f18,,OpenerDirector} から呼び出されます。その際、 `req' は @ref{11da,,Request} オブジェクトになります。 `response' は @ref{307,,urlopen()} の戻り値と同じインターフェースを 実装したオブジェクトになります。戻り値もまた、 @ref{307,,urlopen()} の戻り値と同じインターフェースを実装したオブジェクトでなければなりません。
@end deffn

@node HTTPRedirectHandler オブジェクト,HTTPCookieProcessor オブジェクト,BaseHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-redirect-handler}@anchor{3f48}@anchor{library/urllib request httpredirecthandler-objects}@anchor{3f49}
@subsubsection HTTPRedirectHandler オブジェクト


@cartouche
@quotation 注釈 
一部の HTTP リクエストはこのモジュールのクライアントモードからの操作を要求します。その場合、@ref{11e0,,HTTPError} が送出されます。さまざまなリダイレクションコードの正確な意味についての詳細は 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} を参照してください。

セキュリティ上の配慮として、HTTPRedirectHandler に HTTP、HTTPS、あるいは FTP の URL ではないリダイレクトされた URL が存在した場合、@ref{11e0,,HTTPError} 例外が送出されます。
@end quotation
@end cartouche

@geindex redirect_request() (urllib.request.HTTPRedirectHandler のメソッド)
@anchor{library/urllib request urllib request HTTPRedirectHandler redirect_request}@anchor{3f4a}
@deffn {メソッド} HTTPRedirectHandler.redirect_request (req, fp, code, msg, hdrs, newurl)

リダイレクトへのレスポンスの @ref{11da,,Request} または @code{None} を返します。これはサーバーからリダイレクションを受信した時に @code{http_error_30*()} メソッドのデフォルトの実装によって呼び出されます。リダイレクションを行わなければならない場合、`newurl' へのリダイレクトを実行するための @code{http_error_30*()} を許可する新しい @ref{11da,,Request} を返します。その他の場合、この URL を扱うその他のハンドラーがない場合は @ref{11e0,,HTTPError} を、他のハンドラーでできそうな場合は @code{None} を返します。

@cartouche
@quotation 注釈 
このメソッドのデフォルトの実装は、 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} に厳密に従ったものではありません。 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} では、 @code{POST} リクエストに対する 301 および 302 応答が、ユーザの承認なく自動的にリダイレクトされてはならないと述べています。現実には、ブラウザは POST を @code{GET} に変更することで、これらの応答に対して自動的にリダイレクトを行えるようにしています。デフォルトの実装でも、この挙動を再現しています。
@end quotation
@end cartouche
@end deffn

@geindex http_error_301() (urllib.request.HTTPRedirectHandler のメソッド)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_301}@anchor{3f4b}
@deffn {メソッド} HTTPRedirectHandler.http_error_301 (req, fp, code, msg, hdrs)

@code{Location:} か @code{URI:} のURL にリダイレクトします。このメソッドは HTTP  における 'moved permanently' レスポンスを取得した際に 親オブジェクトとなる @ref{3f18,,OpenerDirector} によって呼び出されます。
@end deffn

@geindex http_error_302() (urllib.request.HTTPRedirectHandler のメソッド)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_302}@anchor{3f4c}
@deffn {メソッド} HTTPRedirectHandler.http_error_302 (req, fp, code, msg, hdrs)

@ref{3f4b,,http_error_301()} と同じですが、'found' レスポンスに対して呼び出されます。
@end deffn

@geindex http_error_303() (urllib.request.HTTPRedirectHandler のメソッド)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_303}@anchor{3f4d}
@deffn {メソッド} HTTPRedirectHandler.http_error_303 (req, fp, code, msg, hdrs)

@ref{3f4b,,http_error_301()} と同じですが、'see other' レスポンスに対して呼び出されます。
@end deffn

@geindex http_error_307() (urllib.request.HTTPRedirectHandler のメソッド)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_307}@anchor{3f4e}
@deffn {メソッド} HTTPRedirectHandler.http_error_307 (req, fp, code, msg, hdrs)

The same as @ref{3f4b,,http_error_301()}, but called for the 'temporary redirect'
response. It does not allow changing the request method from @code{POST}
to @code{GET}.
@end deffn

@geindex http_error_308() (urllib.request.HTTPRedirectHandler のメソッド)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_308}@anchor{3f4f}
@deffn {メソッド} HTTPRedirectHandler.http_error_308 (req, fp, code, msg, hdrs)

The same as @ref{3f4b,,http_error_301()}, but called for the 'permanent redirect'
response. It does not allow changing the request method from @code{POST}
to @code{GET}.


Added in version 3.11.

@end deffn

@node HTTPCookieProcessor オブジェクト,ProxyHandler オブジェクト,HTTPRedirectHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-cookie-processor}@anchor{3f50}@anchor{library/urllib request httpcookieprocessor-objects}@anchor{3f51}
@subsubsection HTTPCookieProcessor オブジェクト


@ref{3f22,,HTTPCookieProcessor} インスタンスは属性をひとつだけ持ちます:

@geindex cookiejar (urllib.request.HTTPCookieProcessor の属性)
@anchor{library/urllib request urllib request HTTPCookieProcessor cookiejar}@anchor{3f52}
@deffn {の属性} HTTPCookieProcessor.cookiejar

Cookie の入っている @ref{3f53,,http.cookiejar.CookieJar} オブジェクトです。
@end deffn

@node ProxyHandler オブジェクト,HTTPPasswordMgr オブジェクト,HTTPCookieProcessor オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request proxy-handler}@anchor{3f54}@anchor{library/urllib request proxyhandler-objects}@anchor{3f55}
@subsubsection ProxyHandler オブジェクト



@deffn {メソッド} ProxyHandler.<protocol>_open(request)

@ref{1db5,,ProxyHandler} は、コンストラクターで与えた辞書 `proxies' にプロキシが設定されているような `protocol' すべてについて、メソッド  @code{<protocol>_open()} を持つことになります。このメソッドは @code{request.set_proxy()} を呼び出して、リクエストがプロキシを通過できるように修正します。その後連鎖するハンドラーの中から次のハンドラーを呼び出して実際にプロトコルを実行します。
@end deffn

@node HTTPPasswordMgr オブジェクト,HTTPPasswordMgrWithPriorAuth オブジェクト,ProxyHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-password-mgr}@anchor{3f25}@anchor{library/urllib request httppasswordmgr-objects}@anchor{3f56}
@subsubsection HTTPPasswordMgr オブジェクト


以下のメソッドは @ref{3f23,,HTTPPasswordMgr} および @ref{3f24,,HTTPPasswordMgrWithDefaultRealm} オブジェクトで利用できます。

@geindex add_password() (urllib.request.HTTPPasswordMgr のメソッド)
@anchor{library/urllib request urllib request HTTPPasswordMgr add_password}@anchor{3f57}
@deffn {メソッド} HTTPPasswordMgr.add_password (realm, uri, user, passwd)

`uri' は単一の URI でも複数の URI からなるシーケンスでもかまいません。 `realm' 、 `user' および `passwd' は文字列でなくてはなりません。このメソッドによって、 `realm' と与えられた URI の上位 URI に対して @code{(user, passwd)} が認証トークンとして使われるようになります。
@end deffn

@geindex find_user_password() (urllib.request.HTTPPasswordMgr のメソッド)
@anchor{library/urllib request urllib request HTTPPasswordMgr find_user_password}@anchor{1bd6}
@deffn {メソッド} HTTPPasswordMgr.find_user_password (realm, authuri)

与えられたレルムおよび URI に対するユーザ名またはパスワードがあればそれを取得します。該当するユーザ名／パスワードが存在しない場合、このメソッドは @code{(None, None)} を返します。

@ref{3f24,,HTTPPasswordMgrWithDefaultRealm} オブジェクトでは、与えられた `realm' に対して該当するユーザ名/パスワードが存在しない場合、レルム @code{None} が検索されます。
@end deffn

@node HTTPPasswordMgrWithPriorAuth オブジェクト,AbstractBasicAuthHandler オブジェクト,HTTPPasswordMgr オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-password-mgr-with-prior-auth}@anchor{3f26}@anchor{library/urllib request httppasswordmgrwithpriorauth-objects}@anchor{3f58}
@subsubsection HTTPPasswordMgrWithPriorAuth オブジェクト


このパスワードマネージャは @ref{3f24,,HTTPPasswordMgrWithDefaultRealm} を継承して、認証の証明書を常に送らないといけない URI を追跡する機能をサポートしています。

@geindex add_password() (urllib.request.HTTPPasswordMgrWithPriorAuth のメソッド)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth add_password}@anchor{3f59}
@deffn {メソッド} HTTPPasswordMgrWithPriorAuth.add_password (realm, uri, user, passwd, is_authenticated=False)

`realm', `uri', `user', `passwd' は @ref{3f57,,HTTPPasswordMgr.add_password()} のものと同じです。
`is_authenticated' は、与えられた URI や URI のリストの @code{is_authenticated} フラグの初期値に設定されます。
`is_authenticated' に @code{True} を指定した場合は、 `realm' は無視されます。
@end deffn

@geindex find_user_password() (urllib.request.HTTPPasswordMgrWithPriorAuth のメソッド)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth find_user_password}@anchor{3f5a}
@deffn {メソッド} HTTPPasswordMgrWithPriorAuth.find_user_password (realm, authuri)

@ref{3f24,,HTTPPasswordMgrWithDefaultRealm} オブジェクトに対する同名のメソッドと同じです。
@end deffn

@geindex update_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth のメソッド)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth update_authenticated}@anchor{3f5b}
@deffn {メソッド} HTTPPasswordMgrWithPriorAuth.update_authenticated (self, uri, is_authenticated=False)

与えられた `url' や URI のリストの @code{is_authenticated} フラグを更新します。
@end deffn

@geindex is_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth のメソッド)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth is_authenticated}@anchor{1bd7}
@deffn {メソッド} HTTPPasswordMgrWithPriorAuth.is_authenticated (self, authuri)

与えられた URI の @code{is_authenticated} フラグの現在の状態を返します。
@end deffn

@node AbstractBasicAuthHandler オブジェクト,HTTPBasicAuthHandler オブジェクト,HTTPPasswordMgrWithPriorAuth オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request abstract-basic-auth-handler}@anchor{3f5c}@anchor{library/urllib request abstractbasicauthhandler-objects}@anchor{3f5d}
@subsubsection AbstractBasicAuthHandler オブジェクト


@geindex http_error_auth_reqed() (urllib.request.AbstractBasicAuthHandler のメソッド)
@anchor{library/urllib request urllib request AbstractBasicAuthHandler http_error_auth_reqed}@anchor{3f5e}
@deffn {メソッド} AbstractBasicAuthHandler.http_error_auth_reqed (authreq, host, req, headers)

ユーザ名／パスワードを取得し、再度サーバへのリクエストを試みることで、サーバからの認証リクエストを処理します。 `authreq' はリクエストにおいて レルムに関する情報が含まれているヘッダーの名前、 `host' は認証を行う対象の URL とパスを指定します、 `req' は (失敗した) @ref{11da,,Request} オブジェクト、そして `headers' はエラーヘッダーでなくてはなりません。

`host' は、オーソリティ (例 @code{"python.org"}) か、オーソリティコンポーネントを含む URL (例 @code{"http://python.org"}) です。どちらの場合も、オーソリティはユーザ情報コンポーネントを含んではいけません (なので、 @code{"python.org"} や @code{"python.org:80"} は正しく、 @code{"joe:password@@python.org"} は不正です) 。
@end deffn

@node HTTPBasicAuthHandler オブジェクト,ProxyBasicAuthHandler オブジェクト,AbstractBasicAuthHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-basic-auth-handler}@anchor{3f5f}@anchor{library/urllib request httpbasicauthhandler-objects}@anchor{3f60}
@subsubsection HTTPBasicAuthHandler オブジェクト


@geindex http_error_401() (urllib.request.HTTPBasicAuthHandler のメソッド)
@anchor{library/urllib request urllib request HTTPBasicAuthHandler http_error_401}@anchor{3f61}
@deffn {メソッド} HTTPBasicAuthHandler.http_error_401 (req, fp, code, msg, hdrs)

認証情報がある場合、認証情報付きで再度リクエストを試みます。
@end deffn

@node ProxyBasicAuthHandler オブジェクト,AbstractDigestAuthHandler オブジェクト,HTTPBasicAuthHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request proxy-basic-auth-handler}@anchor{3f62}@anchor{library/urllib request proxybasicauthhandler-objects}@anchor{3f63}
@subsubsection ProxyBasicAuthHandler オブジェクト


@geindex http_error_407() (urllib.request.ProxyBasicAuthHandler のメソッド)
@anchor{library/urllib request urllib request ProxyBasicAuthHandler http_error_407}@anchor{3f64}
@deffn {メソッド} ProxyBasicAuthHandler.http_error_407 (req, fp, code, msg, hdrs)

認証情報がある場合、認証情報付きで再度リクエストを試みます。
@end deffn

@node AbstractDigestAuthHandler オブジェクト,HTTPDigestAuthHandler オブジェクト,ProxyBasicAuthHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request abstract-digest-auth-handler}@anchor{3f65}@anchor{library/urllib request abstractdigestauthhandler-objects}@anchor{3f66}
@subsubsection AbstractDigestAuthHandler オブジェクト


@geindex http_error_auth_reqed() (urllib.request.AbstractDigestAuthHandler のメソッド)
@anchor{library/urllib request urllib request AbstractDigestAuthHandler http_error_auth_reqed}@anchor{3f67}
@deffn {メソッド} AbstractDigestAuthHandler.http_error_auth_reqed (authreq, host, req, headers)

`authreq' はリクエストにおいてレルムに関する情報が含まれているヘッダーの名前、 `host' は認証を行う対象のホスト名、 `req' は  (失敗した) @ref{11da,,Request} オブジェクト、そして `headers' はエラーヘッダーでなくてはなりません。
@end deffn

@node HTTPDigestAuthHandler オブジェクト,ProxyDigestAuthHandler オブジェクト,AbstractDigestAuthHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-digest-auth-handler}@anchor{3f68}@anchor{library/urllib request httpdigestauthhandler-objects}@anchor{3f69}
@subsubsection HTTPDigestAuthHandler オブジェクト


@geindex http_error_401() (urllib.request.HTTPDigestAuthHandler のメソッド)
@anchor{library/urllib request urllib request HTTPDigestAuthHandler http_error_401}@anchor{3f6a}
@deffn {メソッド} HTTPDigestAuthHandler.http_error_401 (req, fp, code, msg, hdrs)

認証情報がある場合、認証情報付きで再度リクエストを試みます。
@end deffn

@node ProxyDigestAuthHandler オブジェクト,HTTPHandler オブジェクト,HTTPDigestAuthHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request proxy-digest-auth-handler}@anchor{3f6b}@anchor{library/urllib request proxydigestauthhandler-objects}@anchor{3f6c}
@subsubsection ProxyDigestAuthHandler オブジェクト


@geindex http_error_407() (urllib.request.ProxyDigestAuthHandler のメソッド)
@anchor{library/urllib request urllib request ProxyDigestAuthHandler http_error_407}@anchor{3f6d}
@deffn {メソッド} ProxyDigestAuthHandler.http_error_407 (req, fp, code, msg, hdrs)

認証情報がある場合、認証情報付きで再度リクエストを試みます。
@end deffn

@node HTTPHandler オブジェクト,HTTPSHandler オブジェクト,ProxyDigestAuthHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-handler-objects}@anchor{3f6e}@anchor{library/urllib request httphandler-objects}@anchor{3f6f}
@subsubsection HTTPHandler オブジェクト


@geindex http_open() (urllib.request.HTTPHandler のメソッド)
@anchor{library/urllib request urllib request HTTPHandler http_open}@anchor{3f70}
@deffn {メソッド} HTTPHandler.http_open (req)

HTTP リクエストを送ります。 @code{req.data} に応じて、 GET または POST のどちらでも送ることができます。
@end deffn

@node HTTPSHandler オブジェクト,FileHandler オブジェクト,HTTPHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request https-handler-objects}@anchor{3f71}@anchor{library/urllib request httpshandler-objects}@anchor{3f72}
@subsubsection HTTPSHandler オブジェクト


@geindex https_open() (urllib.request.HTTPSHandler のメソッド)
@anchor{library/urllib request urllib request HTTPSHandler https_open}@anchor{3f73}
@deffn {メソッド} HTTPSHandler.https_open (req)

HTTPS リクエストを送ります。 @code{req.data} に応じて、 GET または POST のどちらでも送ることができます。
@end deffn

@node FileHandler オブジェクト,DataHandler オブジェクト,HTTPSHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request file-handler-objects}@anchor{3f74}@anchor{library/urllib request filehandler-objects}@anchor{3f75}
@subsubsection FileHandler オブジェクト


@geindex file_open() (urllib.request.FileHandler のメソッド)
@anchor{library/urllib request urllib request FileHandler file_open}@anchor{3f76}
@deffn {メソッド} FileHandler.file_open (req)

ホスト名がない場合、またはホスト名が @code{'localhost'} の場合にファイルをローカルでオープンします。


バージョン 3.2 で変更: このメソッドはローカルのホスト名に対してのみ適用可能です。リモートホスト名が与えられた場合、@ref{2be,,URLError} が送出されます。

@end deffn

@node DataHandler オブジェクト,FTPHandler オブジェクト,FileHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request data-handler-objects}@anchor{3f77}@anchor{library/urllib request datahandler-objects}@anchor{3f78}
@subsubsection DataHandler オブジェクト


@geindex data_open() (urllib.request.DataHandler のメソッド)
@anchor{library/urllib request urllib request DataHandler data_open}@anchor{3f79}
@deffn {メソッド} DataHandler.data_open (req)

Read a data URL. This kind of URL contains the content encoded in the URL
itself. The data URL syntax is specified in 
@geindex RFC; RFC 2397
RFC 2397@footnote{https://datatracker.ietf.org/doc/html/rfc2397.html}. This implementation
ignores white spaces in base64 encoded data URLs so the URL may be wrapped
in whatever source file it comes from. But even though some browsers don't
mind about a missing padding at the end of a base64 encoded data URL, this
implementation will raise a @ref{2ec,,ValueError} in that case.
@end deffn

@node FTPHandler オブジェクト,CacheFTPHandler オブジェクト,DataHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request ftp-handler-objects}@anchor{3f7a}@anchor{library/urllib request ftphandler-objects}@anchor{3f7b}
@subsubsection FTPHandler オブジェクト


@geindex ftp_open() (urllib.request.FTPHandler のメソッド)
@anchor{library/urllib request urllib request FTPHandler ftp_open}@anchor{3f7c}
@deffn {メソッド} FTPHandler.ftp_open (req)

`req' で表されるファイルを FTP 越しにオープンします。ログインは常に空のユーザネームおよびパスワードで行われます。
@end deffn

@node CacheFTPHandler オブジェクト,UnknownHandler オブジェクト,FTPHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request cacheftp-handler-objects}@anchor{3f7d}@anchor{library/urllib request cacheftphandler-objects}@anchor{3f7e}
@subsubsection CacheFTPHandler オブジェクト


@ref{1a99,,CacheFTPHandler} オブジェクトは @ref{3f1e,,FTPHandler} オブジェクトに以下のメソッドを追加したものです:

@geindex setTimeout() (urllib.request.CacheFTPHandler のメソッド)
@anchor{library/urllib request urllib request CacheFTPHandler setTimeout}@anchor{3f7f}
@deffn {メソッド} CacheFTPHandler.setTimeout (t)

接続のタイムアウトを `t' 秒に設定します。
@end deffn

@geindex setMaxConns() (urllib.request.CacheFTPHandler のメソッド)
@anchor{library/urllib request urllib request CacheFTPHandler setMaxConns}@anchor{3f80}
@deffn {メソッド} CacheFTPHandler.setMaxConns (m)

キャッシュ付き接続の最大接続数を `m' に設定します。
@end deffn

@node UnknownHandler オブジェクト,HTTPErrorProcessor オブジェクト,CacheFTPHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request unknown-handler-objects}@anchor{3f81}@anchor{library/urllib request unknownhandler-objects}@anchor{3f82}
@subsubsection UnknownHandler オブジェクト


@geindex unknown_open() (urllib.request.UnknownHandler のメソッド)
@anchor{library/urllib request urllib request UnknownHandler unknown_open}@anchor{3f83}
@deffn {メソッド} UnknownHandler.unknown_open ()

@ref{2be,,URLError} 例外を送出します。
@end deffn

@node HTTPErrorProcessor オブジェクト,使用例<37>,UnknownHandler オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request http-error-processor-objects}@anchor{3f84}@anchor{library/urllib request httperrorprocessor-objects}@anchor{3f85}
@subsubsection HTTPErrorProcessor オブジェクト


@geindex http_response() (urllib.request.HTTPErrorProcessor のメソッド)
@anchor{library/urllib request urllib request HTTPErrorProcessor http_response}@anchor{3f86}
@deffn {メソッド} HTTPErrorProcessor.http_response (request, response)

HTTP エラー応答の処理をします。

エラーコード 200 の場合、レスポンスオブジェクトを即座に返します。

200 以外のエラーコードの場合、これは単に @code{http_error_<type>()} ハンドラーメソッドに @ref{3f3f,,OpenerDirector.error()} 経由で処理を渡します。他にそのエラーを処理するハンドラーがない場合、@ref{3f1c,,HTTPDefaultErrorHandler} は最後に @ref{11e0,,HTTPError} を送出します。
@end deffn

@geindex https_response() (urllib.request.HTTPErrorProcessor のメソッド)
@anchor{library/urllib request urllib request HTTPErrorProcessor https_response}@anchor{3f87}
@deffn {メソッド} HTTPErrorProcessor.https_response (request, response)

HTTPS エラー応答の処理をします。

振る舞いは @ref{3f86,,http_response()} と同じです。
@end deffn

@node 使用例<37>,レガシーインターフェース<2>,HTTPErrorProcessor オブジェクト,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request examples}@anchor{3f88}@anchor{library/urllib request urllib-request-examples}@anchor{3f89}
@subsubsection 使用例


以下の例の他に @ref{3f8a,,urllib パッケージを使ってインターネット上のリソースを取得するには} に多くの例があります。

以下の例では、python.org のメインページを取得して、その最初の 300 バイト分を表示します。

@example
>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(300))
...
b'<!doctype html>\n<!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]-->\n<!--[if IE 7]>      <html class="no-js ie7 lt-ie8 lt-ie9">          <![endif]-->\n<!--[if IE 8]>      <html class="no-js ie8 lt-ie9">
@end example

urlopen は bytes オブジェクトを返すことに注意してください。これは urlopen が、HTTP サーバーから受信したバイトストリームのエンコーディングを自動的に決定できないためです。一般に、返された bytes オブジェクトを文字列にデコードするためのエンコーディングの決定あるいは推測はプログラム側が行います。

以下の HTML の仕様ドキュメント ttps://html.spec.whatwg.org/#charset には HTML や XML ドキュメントでそのエンコーディング情報を指定するさまざまな方法の一覧があります。

For additional information, see the W3C document: @indicateurl{https://www.w3.org/International/questions/qa-html-encoding-declarations}.

python.org ウェブサイトでは `utf-8' エンコーディングを使用しており、それをその meta タグで指定していますので、bytes オブジェクトのデコードも同様に行います。

@example
>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(100).decode('utf-8'))
...
<!doctype html>
<!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]-->
<!-
@end example

@ref{1e1,,コンテキストマネージャー} を使用しないアプローチでも同様の結果を得ることができます。

@example
>>> import urllib.request
>>> f = urllib.request.urlopen('http://www.python.org/')
>>> try:
...     print(f.read(100).decode('utf-8'))
... finally:
...     f.close()
...
<!doctype html>
<!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]-->
<!--
@end example

以下の例では、データストリームを CGI の標準入力へ送信し、返されたデータを読み込みます。この例は Python が SSL をサポートするように設定してインストールされている場合のみ動作します。

@example
>>> import urllib.request
>>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
...                       data=b'This data is passed to stdin of the CGI')
>>> with urllib.request.urlopen(req) as f:
...     print(f.read().decode('utf-8'))
...
Got Data: "This data is passed to stdin of the CGI"
@end example

上の例で使われているサンプルの CGI は以下のようになっています:

@example
#!/usr/bin/env python
import sys
data = sys.stdin.read()
print('Content-type: text/plain\n\nGot Data: "%s"' % data)
@end example

これは @ref{11da,,Request} を使った @code{PUT} リクエストの例です:

@example
import urllib.request
DATA = b'some data'
req = urllib.request.Request(url='http://localhost:8080', data=DATA, method='PUT')
with urllib.request.urlopen(req) as f:
    pass
print(f.status)
print(f.reason)
@end example

以下はベーシック HTTP 認証の例です:

@example
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
with urllib.request.urlopen('http://www.example.com/login.html') as f:
    print(f.read().decode('utf-8'))
@end example

@ref{309,,build_opener()} はデフォルトで沢山のハンドラを提供しており、その中に @ref{1db5,,ProxyHandler} があります。デフォルトでは、 @ref{1db5,,ProxyHandler} は @code{<scheme>_proxy} という環境変数を使います。 ここで @code{<scheme>} は URL スキームです。例えば、 HTTP プロキシの URL を得るには、環境変数 @code{http_proxy} を読み出します。

この例では、デフォルトの @ref{1db5,,ProxyHandler} を置き換えてプログラム的に作成したプロキシ URL を使うようにし、 @ref{3f28,,ProxyBasicAuthHandler} でプロキシ認証サポートを追加します。

@example
proxy_handler = urllib.request.ProxyHandler(@{'http': 'http://www.example.com:3128/'@})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
with opener.open('http://www.example.com/login.html') as f:
   print(f.read().decode('utf-8'))
@end example

以下は HTTP ヘッダーを追加する例です:

`headers' 引数を使って @ref{11da,,Request} コンストラクタを呼び出す方法の他に、以下のようにできます:

@example
import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
# Customize the default User-Agent header value:
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
with urllib.request.urlopen(req) as f:
    print(f.read().decode('utf-8'))
@end example

@ref{3f18,,OpenerDirector} は全ての @ref{11da,,Request} に @code{User-Agent} ヘッダーを自動的に追加します。これを変更するには以下のようにします:

@example
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
with opener.open('http://www.example.com/') as f:
   print(f.read().decode('utf-8'))
@end example

また、 @ref{11da,,Request} が @ref{307,,urlopen()} (や @ref{11de,,OpenerDirector.open()})に渡される際には、いくつかの標準ヘッダー (@code{Content-Length}, @code{Content-Type} および @code{Host}) も追加されることを忘れないでください。
@anchor{library/urllib request urllib-examples}@anchor{3f8b}
以下は @code{GET} メソッドを使ってパラメータを含む URL を取得するセッションの例です:

@example
>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode(@{'spam': 1, 'eggs': 2, 'bacon': 0@})
>>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
>>> with urllib.request.urlopen(url) as f:
...     print(f.read().decode('utf-8'))
...
@end example

以下の例では、@code{POST} メソッドを使用しています。urlencode から出力されたパラメーターは urlopen にデータとして渡される前に bytes にエンコードされていることに注意してください:

@example
>>> import urllib.request
>>> import urllib.parse
>>> data = urllib.parse.urlencode(@{'spam': 1, 'eggs': 2, 'bacon': 0@})
>>> data = data.encode('ascii')
>>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
...     print(f.read().decode('utf-8'))
...
@end example

以下の例では、環境変数による設定内容に対して上書きする形で HTTP プロキシを明示的に設定しています:

@example
>>> import urllib.request
>>> proxies = @{'http': 'http://proxy.example.com:8080/'@}
>>> opener = urllib.request.build_opener(urllib.request.ProxyHandler(proxies))
>>> with opener.open("http://www.python.org") as f:
...     f.read().decode('utf-8')
...
@end example

以下の例では、環境変数による設定内容に対して上書きする形で、まったくプロキシを使わないよう設定しています:

@example
>>> import urllib.request
>>> opener = urllib.request.build_opener(urllib.request.ProxyHandler(@{@}@}))
>>> with opener.open("http://www.python.org/") as f:
...     f.read().decode('utf-8')
...
@end example

@node レガシーインターフェース<2>,urllib request Restrictions,使用例<37>,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request legacy-interface}@anchor{3f8c}
@subsubsection レガシーインターフェース


以下の関数およびクラスは、Python 2 のモジュール @code{urllib} (@code{urllib2} ではありません) から移植されたものです。これらは将来的に廃止されるかもしれません。

@geindex urlretrieve() (urllib.request モジュール)
@anchor{library/urllib request urllib request urlretrieve}@anchor{308}
@deffn {の関数} urllib.request.urlretrieve (url, filename=None, reporthook=None, data=None)

URL で表されるネットワークオブジェクトをローカルファイルにコピーします。 URL がローカルファイルを示している場合は、ファイル名が与えられない限りオブジェクトはコピーされません。戻り値はタプル @code{(filename, headers)} になり、 `filename' はオブジェクトが保存されたローカルファイル名、 `headers' は (リモートオブジェクトに対しては) @ref{307,,urlopen()} が返したオブジェクトの @code{info()} メソッドが返すものすべてになります。例外は @ref{307,,urlopen()} のものと同じになります。

The second argument, if present, specifies the file location to copy to (if
absent, the location will be a tempfile with a generated name). The third
argument, if present, is a callable that will be called once on
establishment of the network connection and once after each block read
thereafter.  The callable will be passed three arguments; a count of blocks
transferred so far, a block size in bytes, and the total size of the file.  The
third argument may be @code{-1} on older FTP servers which do not return a file
size in response to a retrieval request.

以下は最も一般的な使用例です:

@example
>>> import urllib.request
>>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
>>> html.close()
@end example

`url' が @code{http:} スキーム識別子を使用していた場合、任意の引数 `data' は @code{POST} リクエストの指定に使用される場合があります (通常のリクエストタイプは @code{GET} です)。引数 `data' は標準 @code{application/x-www-form-urlencoded} 形式のバイトオブジェクトでなければなりません。 @ref{1095,,urllib.parse.urlencode()} 関数を参照してください。

@ref{308,,urlretrieve()} は、予想 (これは `Content-Length' ヘッダーにより通知されるサイズです) よりも取得できるデータ量が少ないことを検知した場合、 @ref{3f8d,,ContentTooShortError} を発生します。これは、例えば、ダウンロードが中断された場合などに発生します。

`Content-Length' はデータ量の下限です: 読み込むデータ量がこれを超えている場合 urlretrieve はそれらも読み込みますが、利用できるデータがこれを下回った場合、例外が送出されます。

このような場合にもダウンロードされたデータを取得することは可能で、これは exception インスタンスの @code{content} 属性に保存されています。

`Content-Length' ヘッダーが与えられなれけば urlretrieve はダウンロードしたデータのサイズをチェックできません。この場合ダウンロードは正常に完了したとみなすしかありません。
@end deffn

@geindex urlcleanup() (urllib.request モジュール)
@anchor{library/urllib request urllib request urlcleanup}@anchor{1dbc}
@deffn {の関数} urllib.request.urlcleanup ()

以前の @ref{308,,urlretrieve()} 呼び出し後に残っているかもしれない一時ファイルをクリーンアップします。
@end deffn

@node urllib request Restrictions,,レガシーインターフェース<2>,urllib request --- URL を開くための大規模なライブラリ
@anchor{library/urllib request urllib-request-restrictions}@anchor{3f8e}
@subsubsection @code{urllib.request} Restrictions


@geindex HTTP;プロトコル
@geindex FTP;プロトコル


@itemize *

@item 
現在、次のプロトコルのみサポートされています: HTTP (バージョン 0.9 および 1.0)、FTP、ローカルファイル、およびデータ URL


バージョン 3.4 で変更: データ URL サポートが追加されました。


@item 
@ref{308,,urlretrieve()} のキャッシュ機能は、誰かが Expiration time ヘッダーの正しい処理をハックする時間を見つけるまで無効にされています。

@item 
ある URL がキャッシュにあるかどうか調べるような関数があればと思っています。

@item 
後方互換性のため、 URL がローカルシステム上のファイルを指しているように見えるにも関わらずファイルを開くことができなければ、 URL は FTP プロトコルを使って再解釈されます。この機能は時として混乱を招くエラーメッセージを引き起こします。

@item 
関数 @ref{307,,urlopen()} および @ref{308,,urlretrieve()} は、ネットワーク接続が確立されるまでの間、一定でない長さの遅延を引き起こすことがあります。このことは、これらの関数を使ってインタラクティブな Web クライアントを構築するのはスレッドなしには難しいことを意味します。

@geindex HTML
@geindex HTTP;プロトコル

@item 
@ref{307,,urlopen()} あるいは @ref{308,,urlretrieve()} が返すデータはサーバーから返された生データです。これは (画像のような) バイナリ、プレーンテキスト、あるいは (例えば) HTML などになります。HTTP プロトコルはレスポンスヘッダー内でタイプ情報を提供しており、@code{Content-Type} ヘッダーを見ることで調査できます。返されたデータが HTML の場合、モジュール @ref{71,,html.parser} を使用してこれを解析できます。

@geindex FTP

@item 
FTP プロトコルを扱うコードでは、ファイルとディレクトリを区別できません。このことから、アクセスできないファイルを指している URL からデータを読み出そうとすると、予期しない動作を引き起こす場合があります。 URL が @code{/} で終わっていれば、ディレクトリを指しているものとみなして、それに適した処理を行います。しかし、ファイルの読み出し操作が 550 エラー (URL が存在しないか、主にパーミッションの理由でアクセスできない) になった場合、 URL がディレクトリを指していて、末尾の @code{/} を忘れたケースを処理するため、パスをディレクトリとして扱います。このために、パーミッションのためにアクセスできないファイルを fetch しようとすると、FTP コードはそのファイルを開こうとして 550 エラーに陥り、次にディレクトリ一覧を表示しようとするため、誤解を生むような結果を引き起こす可能性があるのです。よく調整された制御が必要なら、 @ref{62,,ftplib} モジュールを使用します。
@end itemize

@node urllib response --- Response classes used by urllib,urllib parse --- URL を構成要素に解析する,urllib request --- URL を開くための大規模なライブラリ,インターネットプロトコルとサポート
@anchor{library/urllib request module-urllib response}@anchor{112}@anchor{library/urllib request urllib-response-response-classes-used-by-urllib}@anchor{3f8f}
@subsection @code{urllib.response} --- Response classes used by urllib


@geindex module; urllib.response

The @code{urllib.response} module defines functions and classes which define a
minimal file-like interface, including @code{read()} and @code{readline()}.
Functions defined by this module are used internally by the @code{urllib.request} module.
The typical response object is a @ref{3f16,,urllib.response.addinfourl} instance:

@geindex addinfourl (urllib.response のクラス)
@anchor{library/urllib request urllib response addinfourl}@anchor{3f16}
@deffn {クラス} urllib.response.addinfourl

@geindex url (urllib.response.addinfourl の属性)
@anchor{library/urllib request urllib response addinfourl url}@anchor{18e8}
@deffn {の属性} url

取得されたリソースの URL、主にリダイレクトが発生したかどうかを確認するために利用します。
@end deffn

@geindex headers (urllib.response.addinfourl の属性)
@anchor{library/urllib request urllib response addinfourl headers}@anchor{3f90}
@deffn {の属性} headers

Returns the headers of the response in the form of an @ref{580,,EmailMessage} instance.
@end deffn

@geindex status (urllib.response.addinfourl の属性)
@anchor{library/urllib request urllib response addinfourl status}@anchor{3f91}
@deffn {の属性} status


Added in version 3.9.


サーバから返される状態コードです。
@end deffn

@geindex geturl() (urllib.response.addinfourl のメソッド)
@anchor{library/urllib request urllib response addinfourl geturl}@anchor{3f92}
@deffn {メソッド} geturl ()


バージョン 3.9 で非推奨: 非推奨となったので @ref{18e8,,url} を使用してください。

@end deffn

@geindex info() (urllib.response.addinfourl のメソッド)
@anchor{library/urllib request urllib response addinfourl info}@anchor{3f93}
@deffn {メソッド} info ()


バージョン 3.9 で非推奨: 非推奨となったので @ref{3f90,,headers} を使用してください。

@end deffn

@geindex code (urllib.response.addinfourl の属性)
@anchor{library/urllib request urllib response addinfourl code}@anchor{3f94}
@deffn {の属性} code


バージョン 3.9 で非推奨: 非推奨となったので @ref{3f91,,status} を使用してください。

@end deffn

@geindex getcode() (urllib.response.addinfourl のメソッド)
@anchor{library/urllib request urllib response addinfourl getcode}@anchor{3f95}
@deffn {メソッド} getcode ()


バージョン 3.9 で非推奨: 非推奨となったので @ref{3f91,,status} を使用してください。

@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node urllib parse --- URL を構成要素に解析する,urllib error --- urllib request によって送出される例外クラス,urllib response --- Response classes used by urllib,インターネットプロトコルとサポート
@anchor{library/urllib parse doc}@anchor{3f96}@anchor{library/urllib parse module-urllib parse}@anchor{110}@anchor{library/urllib parse translation-repo}@anchor{3f97}@anchor{library/urllib parse urllib-parse-parse-urls-into-components}@anchor{3f98}
@subsection @code{urllib.parse} --- URL を構成要素に解析する


@geindex module; urllib.parse

`ソースコード:' Lib/urllib/parse.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/urllib/parse.py}

@geindex WWW
@geindex World Wide Web
@geindex URL
@geindex URL;parsing
@geindex relative;URL


__________________________________________________________________


このモジュールでは URL (Uniform Resource Locator) 文字列をその構成要素 (アドレススキーム、ネットワーク上の位置、パスその他) に分解したり、構成要素を URL に組みなおしたり、 "相対 URL (relative URL)" を指定した "基底 URL (base URL)" に基づいて絶対 URL に変換するための標準的なインターフェースを定義しています。

このモジュールは Relative Uniform Resource Locators (相対 URL) に関するインターネット RFC に適合するよう設計されており、次の URL スキームをサポートしています: @code{file}, @code{ftp}, @code{gopher}, @code{hdl}, @code{http}, @code{https}, @code{imap}, @code{itms-services}, @code{mailto}, @code{mms}, @code{news}, @code{nntp}, @code{prospero}, @code{rsync}, @code{rtsp}, @code{rtsps}, @code{rtspu}, @code{sftp}, @code{shttp}, @code{sip}, @code{sips}, @code{snews}, @code{svn}, @code{svn+ssh}, @code{telnet}, @code{wais}, @code{ws}, @code{wss}

`CPython 実装の詳細:' The inclusion of the @code{itms-services} URL scheme can prevent an app from
passing Apple's App Store review process for the macOS and iOS App Stores.
Handling for the @code{itms-services} scheme is always removed on iOS; on
macOS, it `may' be removed if CPython has been built with the
@ref{1997,,--with-app-store-compliance} option.

The @code{urllib.parse} module defines functions that fall into two broad
categories: URL parsing and URL quoting. These are covered in detail in
the following sections.

This module's functions use the deprecated term @code{netloc} (or @code{net_loc}),
which was introduced in 
@geindex RFC; RFC 1808
RFC 1808@footnote{https://datatracker.ietf.org/doc/html/rfc1808.html}. However, this term has been obsoleted by
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html}, which introduced the term @code{authority} as its replacement.
The use of @code{netloc} is continued for backward compatibility.

@menu
* URL の解析:: 
* URL parsing security:: 
* ASCII エンコードバイト列の解析:: 
* 構造化された解析結果:: 
* URL のクオート:: 

@end menu

@node URL の解析,URL parsing security,,urllib parse --- URL を構成要素に解析する
@anchor{library/urllib parse url-parsing}@anchor{3f99}
@subsubsection URL の解析


URL 解析関数は、URL 文字列を各構成要素に分割するか、あるいは URL の構成要素を組み合わせて URL 文字列を生成します。

@geindex urlsplit() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse urlsplit}@anchor{f3a}
@deffn {の関数} urllib.parse.urlsplit (urlstring, scheme=None, allow_fragments=True)

Parse a URL into five components, returning a 5-item @ref{85e,,named tuple}
@ref{3f9a,,SplitResult} or @ref{3f9b,,SplitResultBytes}.
This corresponds to the general structure of a URL:
@code{scheme://netloc/path?query#fragment}.
Each tuple item is a string, possibly empty. The components are not broken up
into smaller parts (for example, the network location is a single string), and %
escapes are not expanded. The delimiters as shown above are not part of the
result, except for a leading slash in the `path' component, which is retained if
present.  For example:

@example
>>> from urllib.parse import urlsplit
>>> urlsplit("scheme://netloc/path?query#fragment")
SplitResult(scheme='scheme', netloc='netloc', path='/path',
            query='query', fragment='fragment')
>>> o = urlsplit("http://docs.python.org:80/3/library/urllib.parse.html?"
...              "highlight=params#url-parsing")
>>> o
SplitResult(scheme='http', netloc='docs.python.org:80',
            path='/3/library/urllib.parse.html',
            query='highlight=params', fragment='url-parsing')
>>> o.scheme
'http'
>>> o.netloc
'docs.python.org:80'
>>> o.hostname
'docs.python.org'
>>> o.port
80
>>> o._replace(fragment="").geturl()
'http://docs.python.org:80/3/library/urllib.parse.html?highlight=params'
@end example

Following the syntax specifications in 
@geindex RFC; RFC 1808
RFC 1808@footnote{https://datatracker.ietf.org/doc/html/rfc1808.html}, @code{urlsplit()} recognizes
a netloc only if it is properly introduced by '//'.  Otherwise the
input is presumed to be a relative URL and thus to start with
a path component.

@example
>>> from urllib.parse import urlsplit
>>> urlsplit('//www.cwi.nl:80/%7Eguido/Python.html')
SplitResult(scheme='@w{'}, netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            query='@w{'}, fragment='@w{'})
>>> urlsplit('www.cwi.nl/%7Eguido/Python.html')
SplitResult(scheme='@w{'}, netloc='@w{'}, path='www.cwi.nl/%7Eguido/Python.html',
            query='@w{'}, fragment='@w{'})
>>> urlsplit('help/Python.html')
SplitResult(scheme='@w{'}, netloc='@w{'}, path='help/Python.html',
            query='@w{'}, fragment='@w{'})
@end example

`scheme' 引数によってデフォルトのアドレススキームを与えると、アドレススキームを指定していない URL のみに使用されます。常に許されるデフォルトの @code{'@w{'}} (@code{b'@w{'}} に自動変換出来る)を除き、 `urlstring' と同じ型(テキストもしくはバイト列)であるべきです。

引数 `allow_fragments' が false の場合、フラグメント識別子は認識されません。その代わり、それはパス、パラメータ、またはクエリ要素の一部として解析され、戻り値の @code{fragment} は空文字に設定されます。

戻り値は @ref{85e,,名前付きタプル} です。これは、インデックス指定もしくは以下のような名前属性で要素にアクセスできることを意味します:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

インデックス

@tab

値

@tab

指定されなかった場合の値

@item

@code{scheme}

@tab

0

@tab

URL スキーム

@tab

`scheme' パラメータ

@item

@code{netloc}

@tab

1

@tab

ネットワーク上の位置

@tab

空文字列

@item

@code{path}

@tab

2

@tab

階層的パス

@tab

空文字列

@item

@code{query}

@tab

3

@tab

クエリ要素

@tab

空文字列

@item

@code{fragment}

@tab

4

@tab

フラグメント識別子

@tab

空文字列

@item

@code{username}

@tab

@tab

ユーザ名

@tab

@ref{885,,None}

@item

@code{password}

@tab

@tab

パスワード

@tab

@ref{885,,None}

@item

@code{hostname}

@tab

@tab

ホスト名 (小文字)

@tab

@ref{885,,None}

@item

@code{port}

@tab

@tab

ポート番号を表わす整数 (もしあれば)

@tab

@ref{885,,None}

@end multitable


URL中で不正なポートが指定されている場合、 @code{port} 属性を読みだすと、@ref{2ec,,ValueError} を送出します。結果オブジェクトのより詳しい情報は @ref{3f9c,,構造化された解析結果} 節を参照してください。

@code{netloc} 属性にマッチしなかった角括弧があると @ref{2ec,,ValueError} を送出します。

Characters in the @code{netloc} attribute that decompose under NFKC
normalization (as used by the IDNA encoding) into any of @code{/}, @code{?},
@code{#}, @code{@@}, or @code{:} will raise a @ref{2ec,,ValueError}. If the URL is
decomposed before parsing, no error will be raised.

Following some of the WHATWG spec@footnote{https://url.spec.whatwg.org/#concept-basic-url-parser} that updates 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html}, leading C0
control and space characters are stripped from the URL. @code{\n},
@code{\r} and tab @code{\t} characters are removed from the URL at any position.

As is the case with all named tuples, the subclass has a few additional methods
and attributes that are particularly useful. One such method is @code{_replace()}.
The @code{_replace()} method will return a new @ref{3f9a,,SplitResult} object
replacing specified fields with new values.

@example
>>> from urllib.parse import urlsplit
>>> u = urlsplit('//www.cwi.nl:80/%7Eguido/Python.html')
>>> u
SplitResult(scheme='@w{'}, netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            query='@w{'}, fragment='@w{'})
>>> u._replace(scheme='http')
SplitResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            query='@w{'}, fragment='@w{'})
@end example

@cartouche
@quotation 警告 
@ref{f3a,,urlsplit()} does not perform validation.  See @ref{3f9d,,URL parsing security} for details.
@end quotation
@end cartouche


バージョン 3.2 で変更: IPv6 URL の解析も行えるようになりました。



バージョン 3.3 で変更: The fragment is now parsed for all URL schemes (unless `allow_fragments' is
false), in accordance with 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html}.  Previously, an allowlist of
schemes that support fragments existed.



バージョン 3.6 で変更: 範囲外のポート番号を指定すると、 @ref{885,,None} を返す代わりに、@ref{2ec,,ValueError} を送出するようになりました。



バージョン 3.8 で変更: Characters that affect netloc parsing under NFKC normalization will
now raise @ref{2ec,,ValueError}.



バージョン 3.10 で変更: ASCII newline and tab characters are stripped from the URL.



バージョン 3.12 で変更: Leading WHATWG C0 control and space characters are stripped from the URL.

@end deffn

@geindex parse_qs() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse parse_qs}@anchor{31f}
@deffn {の関数} urllib.parse.parse_qs (qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')

文字列引数として渡されたクエリ文字列  (@code{application/x-www-form-urlencoded} 型のデータ) を解析します。解析されたデータを辞書として返します。辞書のキーは一意なクエリ変数名で、値は各変数名に対する値からなるリストです。

任意の引数 `keep_blank_values' は、パーセントエンコードされたクエリの中の値が入っていないクエリの値を空白文字列と見なすかどうかを示すフラグです。値が真であれば、値の入っていないフィールドは空文字列のままになります。標準では偽で、値の入っていないフィールドを無視し、そのフィールドはクエリに含まれていないものとして扱います。

任意の引数 `strict_parsing' はパース時のエラーをどう扱うかを決めるフラグです。値が偽なら (デフォルトの設定です)、エラーは暗黙のうちに無視します。値が真なら @ref{2ec,,ValueError} 例外を送出します。

任意のパラメータ `encoding' および `errors' はパーセントエンコードされたシーケンスを Unicode 文字にデコードする方法を指定します。これは @ref{ad3,,bytes.decode()} メソッドに渡されます。

The optional argument `max_num_fields' is the maximum number of fields to
read. If set, then throws a @ref{2ec,,ValueError} if there are more than
`max_num_fields' fields read.

The optional argument `separator' is the symbol to use for separating the
query arguments. It defaults to @code{&}.

このような辞書をクエリ文字列に変換するには @ref{1095,,urllib.parse.urlencode()} 関数を (@code{doseq} パラメータに @code{True} を指定して) 使用します。


バージョン 3.2 で変更: `encoding' および `errors' パラメータが追加されました。



バージョン 3.8 で変更: `max_num_fields' パラメータが追加されました。



バージョン 3.10 で変更: Added `separator' parameter with the default value of @code{&}. Python
versions earlier than Python 3.10 allowed using both @code{;} and @code{&} as
query parameter separator. This has been changed to allow only a single
separator key, with @code{&} as the default separator.



バージョン 3.14 で非推奨: Accepting objects with false values (like @code{0} and @code{[]}) except empty
strings and byte-like objects and @code{None} is now deprecated.

@end deffn

@geindex parse_qsl() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse parse_qsl}@anchor{31e}
@deffn {の関数} urllib.parse.parse_qsl (qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')

文字列引数として渡されたクエリ文字列 (@code{application/x-www-form-urlencoded} 型のデータ) を解析します。解析されたデータは名前と値のペアからなるリストです。

任意の引数 `keep_blank_values' は、パーセントエンコードされたクエリの中の値が入っていないクエリの値を空白文字列と見なすかどうかを示すフラグです。値が真であれば、値の入っていないフィールドは空文字列のままになります。標準では偽で、値の入っていないフィールドを無視し、そのフィールドはクエリに含まれていないものとして扱います。

任意の引数 `strict_parsing' はパース時のエラーをどう扱うかを決めるフラグです。値が偽なら (デフォルトの設定です)、エラーは暗黙のうちに無視します。値が真なら @ref{2ec,,ValueError} 例外を送出します。

任意のパラメータ `encoding' および `errors' はパーセントエンコードされたシーケンスを Unicode 文字にデコードする方法を指定します。これは @ref{ad3,,bytes.decode()} メソッドに渡されます。

The optional argument `max_num_fields' is the maximum number of fields to
read. If set, then throws a @ref{2ec,,ValueError} if there are more than
`max_num_fields' fields read.

The optional argument `separator' is the symbol to use for separating the
query arguments. It defaults to @code{&}.

ペアのリストからクエリ文字列を生成する場合には @ref{1095,,urllib.parse.urlencode()} 関数を使用します。


バージョン 3.2 で変更: `encoding' および `errors' パラメータが追加されました。



バージョン 3.8 で変更: `max_num_fields' パラメータが追加されました。



バージョン 3.10 で変更: Added `separator' parameter with the default value of @code{&}. Python
versions earlier than Python 3.10 allowed using both @code{;} and @code{&} as
query parameter separator. This has been changed to allow only a single
separator key, with @code{&} as the default separator.

@end deffn

@geindex urlunsplit() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse urlunsplit}@anchor{193e}
@deffn {の関数} urllib.parse.urlunsplit (parts)

Construct a URL from a tuple as returned by @code{urlsplit()}. The `parts'
argument can be any five-item iterable. This may result in a slightly
different, but equivalent URL, if the URL that was parsed originally had
unnecessary delimiters (for example, a @code{?} with an empty query; the RFC
states that these are equivalent).
@end deffn

@geindex urlparse() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse urlparse}@anchor{362}
@deffn {の関数} urllib.parse.urlparse (urlstring, scheme=None, allow_fragments=True)

This is similar to @ref{f3a,,urlsplit()}, but additionally splits the `path'
component on `path' and `params'.
This function returns a 6-item @ref{85e,,named tuple} @ref{3f9e,,ParseResult}
or @ref{3f9f,,ParseResultBytes}.
Its items are the same as for the @code{urlsplit()} result, except that
`params' is inserted at index 3, between `path' and `query'.

This function is based on obsoleted 
@geindex RFC; RFC 1738
RFC 1738@footnote{https://datatracker.ietf.org/doc/html/rfc1738.html} and 
@geindex RFC; RFC 1808
RFC 1808@footnote{https://datatracker.ietf.org/doc/html/rfc1808.html}, which
listed `params' as the main URL component.
The more recent URL syntax allows parameters to be applied to each segment
of the `path' portion of the URL (see 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html}).
@ref{f3a,,urlsplit()} should generally be used instead of @ref{362,,urlparse()}.
A separate function is needed to separate the path segments and parameters.
@end deffn

@geindex urlunparse() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse urlunparse}@anchor{193f}
@deffn {の関数} urllib.parse.urlunparse (parts)

Combine the elements of a tuple as returned by @ref{362,,urlparse()} into a
complete URL as a string. The `parts' argument can be any six-item
iterable. This may result in a slightly different, but equivalent URL, if the
URL that was parsed originally had unnecessary delimiters (for example, a ?
with an empty query; the RFC states that these are equivalent).
@end deffn

@geindex urljoin() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse urljoin}@anchor{1096}
@deffn {の関数} urllib.parse.urljoin (base, url, allow_fragments=True)

"基底 URL"(`base')と別のURL(`url')を組み合わせて、完全な URL ("絶対 URL") を構成します。くだけて言えば、この関数は相対 URL にない要素を提供するために基底 URL の要素、特にアドレススキーム、ネットワーク上の位置、およびパス (の一部) を使います。例えば:

@example
>>> from urllib.parse import urljoin
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
'http://www.cwi.nl/%7Eguido/FAQ.html'
@end example

The `allow_fragments' argument has the same meaning and default as for
@ref{f3a,,urlsplit()}.

@cartouche
@quotation 注釈 
`url' が (@code{//} か @code{scheme://} で始まる) 絶対URLであれば、その `url' のホスト名と / もしくは scheme は結果に反映されます。例えば:

@example
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
...         '//www.python.org/%7Eguido')
'http://www.python.org/%7Eguido'
@end example

もしこの動作が望みのものでない場合は、 `url' を @ref{f3a,,urlsplit()} と @ref{193e,,urlunsplit()} で先に処理して、 `scheme' と `netloc' を削除してください。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
Because an absolute URL may be passed as the @code{url} parameter, it is
generally `not secure' to use @code{urljoin} with an attacker-controlled
@code{url}. For example in,
@code{urljoin("https://website.com/users/", username)}, if @code{username} can
contain an absolute URL, the result of @code{urljoin} will be the absolute
URL.
@end quotation
@end cartouche


バージョン 3.5 で変更: 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html} で定義された意味論とマッチするように挙動がアップデートされました。

@end deffn

@geindex urldefrag() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse urldefrag}@anchor{145f}
@deffn {の関数} urllib.parse.urldefrag (url)

`url' がフラグメント識別子を含む場合、フラグメント識別子を持たないバージョンに修正された `url' と、別の文字列に分割されたフラグメント識別子を返します。`url' 中にフラグメント識別子がない場合、そのままの `url' と空文字列を返します。

戻り値は @ref{85e,,名前付きタプル} で、インデックスによってもしくは名前属性として要素にアクセスできます:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

インデックス

@tab

値

@tab

指定されなかった場合の値

@item

@code{url}

@tab

0

@tab

フラグメントのない URL

@tab

空文字列

@item

@code{fragment}

@tab

1

@tab

フラグメント識別子

@tab

空文字列

@end multitable


結果オブジェクトのより詳しい情報は @ref{3f9c,,構造化された解析結果} 節を参照してください。


バージョン 3.2 で変更: 結果はシンプルな 2 要素のタプルから構造化オブジェクトに変更されました。

@end deffn

@geindex unwrap() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse unwrap}@anchor{3fa0}
@deffn {の関数} urllib.parse.unwrap (url)

Extract the url from a wrapped URL (that is, a string formatted as
@code{<URL:scheme://host/path>}, @code{<scheme://host/path>}, @code{URL:scheme://host/path}
or @code{scheme://host/path}). If `url' is not a wrapped URL, it is returned
without changes.
@end deffn

@node URL parsing security,ASCII エンコードバイト列の解析,URL の解析,urllib parse --- URL を構成要素に解析する
@anchor{library/urllib parse id1}@anchor{3fa1}@anchor{library/urllib parse url-parsing-security}@anchor{3f9d}
@subsubsection URL parsing security


The @ref{f3a,,urlsplit()} and @ref{362,,urlparse()} APIs do not perform `validation' of
inputs.  They may not raise errors on inputs that other applications consider
invalid.  They may also succeed on some inputs that might not be considered
URLs elsewhere.  Their purpose is for practical functionality rather than
purity.

Instead of raising an exception on unusual input, they may instead return some
component parts as empty strings. Or components may contain more than perhaps
they should.

We recommend that users of these APIs where the values may be used anywhere
with security implications code defensively. Do some verification within your
code before trusting a returned component part.  Does that @code{scheme} make
sense?  Is that a sensible @code{path}?  Is there anything strange about that
@code{hostname}?  etc.

What constitutes a URL is not universally well defined.  Different applications
have different needs and desired constraints.  For instance the living WHATWG spec@footnote{https://url.spec.whatwg.org/#concept-basic-url-parser} describes what user facing web clients such as a web browser require.
While 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html} is more general.  These functions incorporate some aspects of
both, but cannot be claimed compliant with either.  The APIs and existing user
code with expectations on specific behaviors predate both standards leading us
to be very cautious about making API behavior changes.

@node ASCII エンコードバイト列の解析,構造化された解析結果,URL parsing security,urllib parse --- URL を構成要素に解析する
@anchor{library/urllib parse id2}@anchor{3fa2}@anchor{library/urllib parse parsing-ascii-encoded-bytes}@anchor{1461}
@subsubsection ASCII エンコードバイト列の解析


URL を解析する関数は元々文字列のみ操作するよう設計されていました。実際のところ、それは URL が正しくクオートされエンコードされた ASCII バイト列を操作できた方が有用でした。結果的にこのモジュールの URL 解析関数はすべて @ref{192,,bytes} および @ref{344,,bytearray} オブジェクトに加えて @ref{169,,str} オブジェクトでも処理するようになりました。

@ref{169,,str} データが渡された場合、戻り値は @ref{169,,str} データのみを含んだものになります。@ref{192,,bytes} あるいは @ref{344,,bytearray} が渡された場合、戻り値は @ref{192,,bytes} データのみを含んだものになります。

単一の関数を呼び出す時に @ref{192,,bytes} または @ref{344,,bytearray} が混在した @ref{169,,str} を渡した場合、@ref{198,,TypeError} が、非 ASCII バイト値が渡された場合 @ref{c08,,UnicodeDecodeError} が送出されます。

@ref{169,,str} と @ref{192,,bytes} 間で容易に変換を行えるよう、すべての URL 解析関数は @code{encode()} メソッド (結果に @ref{169,,str} データが含まれる時用) か @code{decode()} メソッド (結果に @ref{192,,bytes} データが含まれる時用) のどちらかを提供しています。これらメソッドの動作は対応する @ref{169,,str} と @ref{192,,bytes} メソッドが持つものと同じです (ただしデフォルトのエンコーディングは @code{'utf-8'} ではなく @code{'ascii'} になります)。それぞれは @code{encode()} メソッドを持つ @ref{192,,bytes} データか @code{decode()} メソッドを持つ @ref{169,,str} データのどちらかに対応した型を生成します。

非 ASCII データを含むなど、不適切にクオートされた URL を操作する可能性のあるアプリケーションでは、URL 解析メソッドを呼び出す前に独自にバイト列から文字列にデコードする必要があります。

この項で説明された挙動は URL 解析関数にのみ該当します。URL クオート関数でバイトシーケンスを生成もしくは消化する際には、別にURL クオート関数の項で詳説されている通りのルールに従います。


バージョン 3.2 で変更: URL 解析関数は ASCII エンコードバイトシーケンスも受け付けるようになりました


@node 構造化された解析結果,URL のクオート,ASCII エンコードバイト列の解析,urllib parse --- URL を構成要素に解析する
@anchor{library/urllib parse structured-parse-results}@anchor{3fa3}@anchor{library/urllib parse urlparse-result-object}@anchor{3f9c}
@subsubsection 構造化された解析結果


The result objects from the @ref{f3a,,urlsplit()}, @ref{362,,urlparse()}  and
@ref{145f,,urldefrag()} functions are subclasses of the @ref{614,,tuple} type.
These subclasses add the attributes listed in the documentation for
those functions, the encoding and decoding support described in the
previous section, as well as an additional method:

@geindex geturl() (urllib.parse.urllib.parse.SplitResult のメソッド)
@anchor{library/urllib parse urllib parse urllib parse SplitResult geturl}@anchor{3fa4}
@deffn {メソッド} urllib.parse.SplitResult.geturl ()

オリジナルの URL を再結合した場合は文字列で返されます。これはスキームが小文字に正規化されていたり、空の構成要素が除去されるなど、オリジナルの URL とは異なる場合があります。特に、空のパラメータ、クエリ、およびフラグメント識別子は削除されます。

@ref{145f,,urldefrag()} の戻り値では、空のフラグメント識別子のみ削除されます。@ref{f3a,,urlsplit()} および @ref{362,,urlparse()} の戻り値では、このメソッドが返す URL には説明されているすべての変更が加えられます。

加えた解析関数を逆に行えばこのメソッドの戻り値は元の URL になります:

@example
>>> from urllib.parse import urlsplit
>>> url = 'HTTP://www.Python.org/doc/#'
>>> r1 = urlsplit(url)
>>> r1.geturl()
'http://www.Python.org/doc/'
>>> r2 = urlsplit(r1.geturl())
>>> r2.geturl()
'http://www.Python.org/doc/'
@end example
@end deffn

以下のクラスは @ref{169,,str} オブジェクトを操作した場合、構造化された解析結果の実装を提供します:

@geindex DefragResult (urllib.parse のクラス)
@anchor{library/urllib parse urllib parse DefragResult}@anchor{3fa5}
@deffn {クラス} urllib.parse.DefragResult (url, fragment)

@ref{145f,,urldefrag()} の具象クラスの結果には @ref{169,,str} データが含まれます。@code{encode()} メソッドは @ref{3fa6,,DefragResultBytes} インスタンスを返します。


Added in version 3.2.

@end deffn

@geindex ParseResult (urllib.parse のクラス)
@anchor{library/urllib parse urllib parse ParseResult}@anchor{3f9e}
@deffn {クラス} urllib.parse.ParseResult (scheme, netloc, path, params, query, fragment)

@ref{362,,urlparse()} の具象クラスの結果には @ref{169,,str} データが含まれます。@code{encode()} メソッドは @ref{3f9f,,ParseResultBytes} インスタンスを返します。
@end deffn

@geindex SplitResult (urllib.parse のクラス)
@anchor{library/urllib parse urllib parse SplitResult}@anchor{3f9a}
@deffn {クラス} urllib.parse.SplitResult (scheme, netloc, path, query, fragment)

@ref{f3a,,urlsplit()} の具象クラスの結果には @ref{169,,str} データが含まれます。@code{encode()} メソッドは @ref{3f9b,,SplitResultBytes} インスタンスを返します。
@end deffn

以下のクラスは @ref{192,,bytes} または @ref{344,,bytearray} オブジェクトを操作した時に解析結果の実装を提供します:

@geindex DefragResultBytes (urllib.parse のクラス)
@anchor{library/urllib parse urllib parse DefragResultBytes}@anchor{3fa6}
@deffn {クラス} urllib.parse.DefragResultBytes (url, fragment)

@ref{145f,,urldefrag()} の具象クラスの結果には @ref{192,,bytes} データが含まれます。@code{decode()} メソッドは @ref{3fa5,,DefragResult} インスタンスを返します。


Added in version 3.2.

@end deffn

@geindex ParseResultBytes (urllib.parse のクラス)
@anchor{library/urllib parse urllib parse ParseResultBytes}@anchor{3f9f}
@deffn {クラス} urllib.parse.ParseResultBytes (scheme, netloc, path, params, query, fragment)

@ref{362,,urlparse()} の具象クラスの結果には @ref{192,,bytes} が含まれます。@code{decode()} メソッドは @ref{3f9e,,ParseResult} インスタンスを返します。


Added in version 3.2.

@end deffn

@geindex SplitResultBytes (urllib.parse のクラス)
@anchor{library/urllib parse urllib parse SplitResultBytes}@anchor{3f9b}
@deffn {クラス} urllib.parse.SplitResultBytes (scheme, netloc, path, query, fragment)

@ref{f3a,,urlsplit()} の具象クラスの結果には @ref{192,,bytes} データが含まれます。@code{decode()} メソッドは @ref{3f9a,,SplitResult} インスタンスを返します。


Added in version 3.2.

@end deffn

@node URL のクオート,,構造化された解析結果,urllib parse --- URL を構成要素に解析する
@anchor{library/urllib parse url-quoting}@anchor{3fa7}
@subsubsection URL のクオート


URL クオート関数は、プログラムデータを取り URL 構成要素として使用できるよう特殊文字をクオートしたり非 ASCII 文字を適切にエンコードすることに焦点を当てています。これらは上述の URL 解析関数でカバーされていない URL 構成要素からオリジナルデータの再作成もサポートしています。

@geindex quote() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse quote}@anchor{d9c}
@deffn {の関数} urllib.parse.quote (string, safe='/', encoding=None, errors=None)

`string' 内の特殊文字を @code{%@var{xx}} を使用してエスケープします。文字、数字、および @code{'_.-~'} はクオートされません。デフォルトでは、この関数は URL のパス部分のクオートのために用意されています。任意のパラメータ `safe' を指定すると、指定した ASCII 文字もクオートされません。デフォルトは @code{'/'} です。

`string' に使用できるのは @ref{169,,str} か @ref{192,,bytes} オブジェクトです。


バージョン 3.7 で変更: Moved from 
@geindex RFC; RFC 2396
RFC 2396@footnote{https://datatracker.ietf.org/doc/html/rfc2396.html} to 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html} for quoting URL strings. "~" is now
included in the set of unreserved characters.


任意のパラメータ `encoding' と `errors' は @ref{ad2,,str.encode()} で受け付けられる非 ASCII 文字への対処法を指定します。`encoding' のデフォルトは @code{'utf-8'}、`errors' のデフォルトは @code{'strict'} で、非サポート文字があると @ref{887,,UnicodeEncodeError} を送出します。`string' が @ref{192,,bytes} の場合 `encoding' と `errors' を指定してはいけません。指定すると @ref{198,,TypeError} が送出されます。

@code{quote(string, safe, encoding, errors)} は @code{quote_from_bytes(string.encode(encoding, errors), safe)} と等価であることに留意してください。

例: @code{quote('/El Niño/')} は @code{'/El%20Ni%C3%B1o/'} を返します。
@end deffn

@geindex quote_plus() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse quote_plus}@anchor{1460}
@deffn {の関数} urllib.parse.quote_plus (string, safe='@w{'}, encoding=None, errors=None)

Like @ref{d9c,,quote()}, but also replace spaces with plus signs, as required for
quoting HTML form values when building up a query string to go into a URL.
Plus signs in the original string are escaped unless they are included in
`safe'.  It also does not have `safe' default to @code{'/'}.

例: @code{quote_plus('/El Niño/')} は @code{'%2FEl+Ni%C3%B1o%2F'} を返します。
@end deffn

@geindex quote_from_bytes() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse quote_from_bytes}@anchor{1b51}
@deffn {の関数} urllib.parse.quote_from_bytes (bytes, safe='/')

@ref{d9c,,quote()} と似ていますが、@ref{169,,str} ではなく @ref{192,,bytes} オブジェクトを取り、文字列からバイト列へのエンコードを行いません。

例: @code{quote_from_bytes(b'a&\xef')} は @code{'a%26%EF'} を返します。
@end deffn

@geindex unquote() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse unquote}@anchor{1afb}
@deffn {の関数} urllib.parse.unquote (string, encoding='utf-8', errors='replace')

エスケープされた @code{%@var{xx}} をそれに対応した単一文字に置き換えます。オプション引数の `encoding' と `errors' は @ref{ad3,,bytes.decode()} メソッドで受け付けられるパーセントエンコードされたシーケンスから Unicode 文字へのデコード法を指定します。

`string' に使用できるのは @ref{169,,str} か @ref{192,,bytes} オブジェクトです。

`encoding' のデフォルトは @code{'utf-8'}、`errors' のデフォルトは @code{'replace'} で、不正なシーケンスはプレースホルダー文字に置き換えられます。

例: @code{unquote('/El%20Ni%C3%B1o/')} は @code{'/El Niño/'} を返します。


バージョン 3.9 で変更: `string' parameter supports bytes and str objects (previously only str).

@end deffn

@geindex unquote_plus() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse unquote_plus}@anchor{3fa8}
@deffn {の関数} urllib.parse.unquote_plus (string, encoding='utf-8', errors='replace')

@ref{1afb,,unquote()} と似ていますが、HTML フォームの値のアンクオートのために「+」を空白に置き換えます。

`string' は @ref{169,,str} でなければなりません。

例: @code{unquote_plus('/El+Ni%C3%B1o/')} は @code{'/El Niño/'} を返します。
@end deffn

@geindex unquote_to_bytes() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse unquote_to_bytes}@anchor{1afc}
@deffn {の関数} urllib.parse.unquote_to_bytes (string)

スケープされた @code{%@var{xx}} をそれに対応した 1 オクテットに置き換え、@ref{192,,bytes} オブジェクトを返します。

`string' に使用できるのは @ref{169,,str} か @ref{192,,bytes} オブジェクトです。

@ref{169,,str} だった場合、`string' 内のエスケープされていない非 ASCII 文字は UTF-8 バイト列にエンコードされます。

例: @code{unquote_to_bytes('a%26%EF')} は @code{b'a&\xef'} を返します。
@end deffn

@geindex urlencode() (urllib.parse モジュール)
@anchor{library/urllib parse urllib parse urlencode}@anchor{1095}
@deffn {の関数} urllib.parse.urlencode (query, doseq=False, safe='@w{'}, encoding=None, errors=None, quote_via=quote_plus)

マッピング型オブジェクトまたは 2 個の要素からなるタプルのシーケンス (@ref{169,,str} か @ref{192,,bytes} オブジェクトが含まれているかもしれません) を、パーセントエンコードされた ASCII 文字列に変換します。戻り値の文字列が @ref{307,,urlopen()} 関数での POST 操作の `data' で使用される場合はバイト列にエンコードしなければなりません。そうでない場合は @ref{198,,TypeError} が送出されます。

戻り値は @code{'&'} 文字で区切られた @code{key=value} のペアからなる一組の文字列になります。 `key' と `value' は `quote_via' を使用してクオートされます。デフォルトで、値をクォートするために @ref{1460,,quote_plus()} が使用されます。つまり、スペースは @code{'+'} 文字に、 '/' 文字は @code{%2F} にクォートされます。これは GET リクエストの標準に準拠します (@code{application/x-www-form-urlencoded})。 `quote_via' として渡すことができる別の関数は @ref{d9c,,quote()} です。それはスペースを @code{%20} にエンコードし、 '/' をエンコードしません。何がクォートされるかを最大限コントロールしたければ、 @code{quote} を使って `safe' に値を指定してください。

引数 `query' が 2 要素のタプルのシーケンスの場合、各タプルの第一要素はキーに、第二要素は値になります。
値となる要素はシーケンスを取ることもでき、この場合、オプションのパラメーター `doseq' が @code{True} と評価されるのであれば、キーに対し値シーケンスの各要素を個別に結び付けた @code{key=value} のペアを、 @code{'&'} 文字でつないだものを生成します。
エンコードされた文字列内のパラメーターの順序はシーケンス内のパラメータータプルの順序と一致します。

`safe', `encoding', および `errors' パラメータは `quote_via' にそのまま渡されます (クエリ要素が @ref{169,,str} の場合は、 `encoding' と `errors' パラメータだけが渡されます)。

このエンコード処理の逆を行うには、このモジュールで提供されている @ref{31f,,parse_qs()} と @ref{31e,,parse_qsl()} を使用して、クエリ文字列を Python データ構造に変換できます。

POST リクエストのデータ、あるいは URL クエリ文字列を生成するために、 @ref{1095,,urllib.parse.urlencode()} メソッドをどのように使えばよいかを見るには、@ref{3f8b,,urllib の使用例} を参照してください。


バージョン 3.2 で変更: `query' はバイト列と文字列オブジェクトをサポートします。



バージョン 3.5 で変更: `quote_via' パラメータが追加されました。



バージョン 3.14 で非推奨: Accepting objects with false values (like @code{0} and @code{[]}) except empty
strings and byte-like objects and @code{None} is now deprecated.

@end deffn


@subsubheading 参考



@table @asis

@item WHATWG@footnote{https://url.spec.whatwg.org/} -  URL Living standard

Working Group for the URL Standard that defines URLs, domains, IP addresses, the
application/x-www-form-urlencoded format, and their API.

@geindex RFC; RFC 3986

@item RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html} - Uniform Resource Identifiers

これが現在の標準規格 (STD66) です。urllib.parse モジュールに対するすべての変更はこの規格に準拠していなければなりませんが、若干の逸脱はありえます。これは主には後方互換性のため、また主要なブラウザで一般的に見られる、URL を解析する上でのいくつかの事実上の要件を満たすためです。

@geindex RFC; RFC 2732

@item RFC 2732@footnote{https://datatracker.ietf.org/doc/html/rfc2732.html} - Format for Literal IPv6 Addresses in URL's.

この規格は IPv6 の URL を解析するときの要求事項を記述しています。

@geindex RFC; RFC 2396

@item RFC 2396@footnote{https://datatracker.ietf.org/doc/html/rfc2396.html} - Uniform Resource Identifiers (URI): Generic Syntax

この RFC では Uniform Resource Name (URN) と Uniform Resource Locator (URL) の両方に対する一般的な文法的要求事項を記述しています。

@geindex RFC; RFC 2368

@item RFC 2368@footnote{https://datatracker.ietf.org/doc/html/rfc2368.html} - The mailto URL scheme.

mailto URL スキームに対する文法的要求事項です。

@geindex RFC; RFC 1808

@item RFC 1808@footnote{https://datatracker.ietf.org/doc/html/rfc1808.html} - Relative Uniform Resource Locators

この RFC には絶対 URL と相対 URL を結合するための規則がボーダケースの取扱い方を決定する "異常な例" つきで収められています。

@geindex RFC; RFC 1738

@item RFC 1738@footnote{https://datatracker.ietf.org/doc/html/rfc1738.html} - Uniform Resource Locators (URL)

この RFC では絶対 URL の形式的な文法と意味付けを仕様化しています。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node urllib error --- urllib request によって送出される例外クラス,urllib robotparser --- robots txt 用のパーサー,urllib parse --- URL を構成要素に解析する,インターネットプロトコルとサポート
@anchor{library/urllib error doc}@anchor{3fa9}@anchor{library/urllib error module-urllib error}@anchor{10f}@anchor{library/urllib error translation-repo}@anchor{3faa}@anchor{library/urllib error urllib-error-exception-classes-raised-by-urllib-request}@anchor{3fab}
@subsection @code{urllib.error} --- urllib.request によって送出される例外クラス


@geindex module; urllib.error

`ソースコード:' Lib/urllib/error.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/urllib/error.py}


__________________________________________________________________


The @code{urllib.error} module defines the exception classes for exceptions
raised by @ref{111,,urllib.request}.  The base exception class is @ref{2be,,URLError}.

The following exceptions are raised by @code{urllib.error} as appropriate:

@geindex URLError
@anchor{library/urllib error urllib error URLError}@anchor{2be}
@deffn {例外} urllib.error.URLError

ハンドラが何らかの問題に遭遇した場合、この例外 (またはこの例外から派生した例外)を送出します。この例外は @ref{2c0,,OSError} のサブクラスです。

@geindex reason (urllib.error.URLError の属性)
@anchor{library/urllib error urllib error URLError reason}@anchor{3fac}
@deffn {の属性} reason

このエラーの理由。メッセージ文字列あるいは他の例外インスタンスです。
@end deffn


バージョン 3.3 で変更: @ref{2be,,URLError} は以前は @ref{125e,,IOError} のサブタイプでしたが、 @ref{2c0,,OSError} のエイリアスになりました。

@end deffn

@geindex HTTPError
@anchor{library/urllib error urllib error HTTPError}@anchor{11e0}
@deffn {例外} urllib.error.HTTPError (url, code, msg, hdrs, fp)

@ref{11e0,,HTTPError} は例外 (@ref{2be,,URLError} のサブクラス) ですが、同時に例外ではない file-like な戻り値を返す関数でもあります (@ref{307,,urlopen()} の戻り値と同じです)。これは、例えばサーバからの認証リクエストのように、変わった HTTP エラーを処理するのに役立ちます。

@geindex url (urllib.error.HTTPError の属性)
@anchor{library/urllib error urllib error HTTPError url}@anchor{3fad}
@deffn {の属性} url

リクエスト URL を含みます。 `filename' 属性のエイリアスです。
@end deffn

@geindex code (urllib.error.HTTPError の属性)
@anchor{library/urllib error urllib error HTTPError code}@anchor{3fae}
@deffn {の属性} code

@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} に定義されているHTTPステータスコード。
この数値型の値は、 @ref{3faf,,http.server.BaseHTTPRequestHandler.responses} の辞書に登録されているコードに対応します。
@end deffn

@geindex reason (urllib.error.HTTPError の属性)
@anchor{library/urllib error urllib error HTTPError reason}@anchor{3fb0}
@deffn {の属性} reason

これは通常、このエラーの原因を説明する文字列です。 `msg' 属性のエイリアスです。
@end deffn

@geindex headers (urllib.error.HTTPError の属性)
@anchor{library/urllib error urllib error HTTPError headers}@anchor{11e1}
@deffn {の属性} headers

@ref{11e0,,HTTPError} の原因となった HTTP リクエストの HTTP レスポンスヘッダ。 `hdrs' 属性のエイリアスです。


Added in version 3.4.

@end deffn

@geindex fp (urllib.error.HTTPError の属性)
@anchor{library/urllib error urllib error HTTPError fp}@anchor{3fb1}
@deffn {の属性} fp

HTTP エラーの body を読み出し可能なファイルライクオブジェクト。
@end deffn
@end deffn

@geindex ContentTooShortError
@anchor{library/urllib error urllib error ContentTooShortError}@anchor{3f8d}
@deffn {例外} urllib.error.ContentTooShortError (msg, content)

この例外は @ref{308,,urlretrieve()} 関数が、ダウンロードされたデータの量が予期した量 (`Content-Length' ヘッダで与えられる) よりも少ないことを検知した際に発生します。

@geindex content (urllib.error.ContentTooShortError の属性)
@anchor{library/urllib error urllib error ContentTooShortError content}@anchor{3fb2}
@deffn {の属性} content

ダウンロードされた、 (おそらく切り捨てられた) データ。
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node urllib robotparser --- robots txt 用のパーサー,http --- HTTP モジュール群,urllib error --- urllib request によって送出される例外クラス,インターネットプロトコルとサポート
@anchor{library/urllib robotparser doc}@anchor{3fb3}@anchor{library/urllib robotparser module-urllib robotparser}@anchor{113}@anchor{library/urllib robotparser translation-repo}@anchor{3fb4}@anchor{library/urllib robotparser urllib-robotparser-parser-for-robots-txt}@anchor{3fb5}
@subsection @code{urllib.robotparser} ---  robots.txt 用のパーサー


@geindex module; urllib.robotparser

`ソースコード:' Lib/urllib/robotparser.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/urllib/robotparser.py}

@geindex WWW
@geindex World Wide Web
@geindex URL
@geindex robots.txt


__________________________________________________________________


This module provides a single class, @ref{efa,,RobotFileParser}, which answers
questions about whether or not a particular user agent can fetch a URL on the
website that published the @code{robots.txt} file.  For more details on the
structure of @code{robots.txt} files, see @indicateurl{http://www.robotstxt.org/orig.html}.

@geindex RobotFileParser (urllib.robotparser のクラス)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser}@anchor{efa}
@deffn {クラス} urllib.robotparser.RobotFileParser (url='@w{'})

`url' の @code{robots.txt} に対し読み込み、パーズ、応答するメソッドを提供します。

@geindex set_url() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser set_url}@anchor{3fb6}
@deffn {メソッド} set_url (url)

@code{robots.txt} ファイルを参照するための URL を設定します。
@end deffn

@geindex read() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser read}@anchor{18d1}
@deffn {メソッド} read ()

@code{robots.txt} URL を読み出し、パーザに入力します。
@end deffn

@geindex parse() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser parse}@anchor{1e83}
@deffn {メソッド} parse (lines)

引数 `lines' の内容を解釈します。
@end deffn

@geindex can_fetch() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser can_fetch}@anchor{3fb7}
@deffn {メソッド} can_fetch (useragent, url)

解釈された @code{robots.txt} ファイル中に記載された規則に従ったとき、 `useragent' が `url' を取得してもよい場合には @code{True} を返します。
@end deffn

@geindex mtime() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser mtime}@anchor{3fb8}
@deffn {メソッド} mtime ()

@code{robots.txt} ファイルを最後に取得した時刻を返します。この値は、定期的に新たな @code{robots.txt} をチェックする必要がある、長時間動作する Web スパイダープログラムを実装する際に便利です。
@end deffn

@geindex modified() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser modified}@anchor{3fb9}
@deffn {メソッド} modified ()

@code{robots.txt} ファイルを最後に取得した時刻を現在の時刻に設定します。
@end deffn

@geindex crawl_delay() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser crawl_delay}@anchor{3fba}
@deffn {メソッド} crawl_delay (useragent)

当該の `ユーザーエージェント' 用の @code{robots.txt} の @code{Crawl-delay} パラメーターの値を返します。そのようなパラメーターが存在しないか、指定された `ユーザーエージェント' にあてはまらない、もしくは @code{robots.txt} のこのパラメーターのエントリの構文が無効な場合は、 @code{None} を返します。


Added in version 3.6.

@end deffn

@geindex request_rate() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser request_rate}@anchor{3fbb}
@deffn {メソッド} request_rate (useragent)

@code{robots.txt} の @code{Request-rate} パラメーターの内容を @ref{85e,,named tuple} @code{RequestRate(requests, seconds)} として返します。そのようなパラメーターが存在しないか、指定された `ユーザーエージェント' にあてはまらない、もしくは @code{robots.txt} のこのパラメーターのエントリの構文が無効な場合は、 @code{None} を返します。


Added in version 3.6.

@end deffn

@geindex site_maps() (urllib.robotparser.RobotFileParser のメソッド)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser site_maps}@anchor{1e22}
@deffn {メソッド} site_maps ()

@code{robots.txt} の @code{Sitemap} パラメーターの内容を @ref{24d,,list()} の形式で返します。そのようなパラメーターが存在しないか、 @code{robots.txt} のこのパラメーターのエントリの構文が無効な場合は、 @code{None} を返します。


Added in version 3.8.

@end deffn
@end deffn

以下に @ref{efa,,RobotFileParser} クラスの利用例を示します。

@example
>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.pythontest.net/robots.txt")
>>> rp.read()
>>> rrate = rp.request_rate("*")
>>> rrate.requests
1
>>> rrate.seconds
1
>>> rp.crawl_delay("*")
6
>>> rp.can_fetch("*", "http://www.pythontest.net/")
True
>>> rp.can_fetch("*", "http://www.pythontest.net/no-robots-here/")
False
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node http --- HTTP モジュール群,http client --- HTTP プロトコルクライアント,urllib robotparser --- robots txt 用のパーサー,インターネットプロトコルとサポート
@anchor{library/http doc}@anchor{3fbc}@anchor{library/http http-http-modules}@anchor{3fbd}@anchor{library/http module-http}@anchor{72}@anchor{library/http translation-repo}@anchor{3fbe}
@subsection @code{http} --- HTTP モジュール群


@geindex module; http

`ソースコード:' Lib/http/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/http/__init__.py}

@geindex HTTP;プロトコル
@geindex HTTP;http (標準モジュール)


__________________________________________________________________


@code{http} is a package that collects several modules for working with the
HyperText Transfer Protocol:


@itemize *

@item 
@ref{73,,http.client} は低水準のHTTPプロトコルのクライアントです。高水準の URL を開く操作には @ref{111,,urllib.request} を使ってください

@item 
@ref{76,,http.server} は @ref{d2,,socketserver} をベースにした基礎的な HTTP サーバーを実装しています

@item 
@ref{75,,http.cookies} は cookie の状態管理を実装するためのユーティリティーを提供しています

@item 
@ref{74,,http.cookiejar} は cookie の永続化機能を提供しています
@end itemize

The @code{http} module also defines the following enums that help you work with http related code:

@geindex HTTPStatus (http のクラス)
@anchor{library/http http HTTPStatus}@anchor{afc}
@deffn {クラス} http.HTTPStatus


Added in version 3.5.


一連の HTTP ステータスコード、理由の表現、英語で書かれた長い記述を定義した @ref{edb,,enum.IntEnum} のサブクラスです。

使い方:

@example
>>> from http import HTTPStatus
>>> HTTPStatus.OK
HTTPStatus.OK
>>> HTTPStatus.OK == 200
True
>>> HTTPStatus.OK.value
200
>>> HTTPStatus.OK.phrase
'OK'
>>> HTTPStatus.OK.description
'Request fulfilled, document follows'
>>> list(HTTPStatus)
[HTTPStatus.CONTINUE, HTTPStatus.SWITCHING_PROTOCOLS, ...]
@end example
@end deffn

@menu
* HTTP ステータスコード:: 
* HTTP ステータスコードカテゴリ:: 
* HTTP メソッド:: 

@end menu

@node HTTP ステータスコード,HTTP ステータスコードカテゴリ,,http --- HTTP モジュール群
@anchor{library/http http-status-codes}@anchor{3fbf}@anchor{library/http id1}@anchor{3fc0}
@subsubsection HTTP ステータスコード


@ref{afc,,http.HTTPStatus} で利用可能な、サポートされている、IANA に登録されたステータスコード@footnote{https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml} は:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

コード

@tab

列挙名

@tab

詳細

@item

@code{100}

@tab

@code{CONTINUE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.2.1

@item

@code{101}

@tab

@code{SWITCHING_PROTOCOLS}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.2.2

@item

@code{102}

@tab

@code{PROCESSING}

@tab

WebDAV 
@geindex RFC; RFC 2518
RFC 2518@footnote{https://datatracker.ietf.org/doc/html/rfc2518.html}, Section 10.1

@item

@code{103}

@tab

@code{EARLY_HINTS}

@tab

An HTTP Status Code for Indicating Hints 
@geindex RFC; RFC 8297
RFC 8297@footnote{https://datatracker.ietf.org/doc/html/rfc8297.html}

@item

@code{200}

@tab

@code{OK}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.3.1

@item

@code{201}

@tab

@code{CREATED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.3.2

@item

@code{202}

@tab

@code{ACCEPTED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.3.3

@item

@code{203}

@tab

@code{NON_AUTHORITATIVE_INFORMATION}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.3.4

@item

@code{204}

@tab

@code{NO_CONTENT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.3.5

@item

@code{205}

@tab

@code{RESET_CONTENT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.3.6

@item

@code{206}

@tab

@code{PARTIAL_CONTENT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.3.7

@item

@code{207}

@tab

@code{MULTI_STATUS}

@tab

WebDAV 
@geindex RFC; RFC 4918
RFC 4918@footnote{https://datatracker.ietf.org/doc/html/rfc4918.html}, Section 11.1

@item

@code{208}

@tab

@code{ALREADY_REPORTED}

@tab

WebDAV Binding Extensions 
@geindex RFC; RFC 5842
RFC 5842@footnote{https://datatracker.ietf.org/doc/html/rfc5842.html}, Section 7.1 (Experimental)

@item

@code{226}

@tab

@code{IM_USED}

@tab

Delta Encoding in HTTP 
@geindex RFC; RFC 3229
RFC 3229@footnote{https://datatracker.ietf.org/doc/html/rfc3229.html}, Section 10.4.1

@item

@code{300}

@tab

@code{MULTIPLE_CHOICES}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.1

@item

@code{301}

@tab

@code{MOVED_PERMANENTLY}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.2

@item

@code{302}

@tab

@code{FOUND}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.3

@item

@code{303}

@tab

@code{SEE_OTHER}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.4

@item

@code{304}

@tab

@code{NOT_MODIFIED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.5

@item

@code{305}

@tab

@code{USE_PROXY}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.6

@item

@code{307}

@tab

@code{TEMPORARY_REDIRECT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.8

@item

@code{308}

@tab

@code{PERMANENT_REDIRECT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.4.9

@item

@code{400}

@tab

@code{BAD_REQUEST}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.1

@item

@code{401}

@tab

@code{UNAUTHORIZED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.2

@item

@code{402}

@tab

@code{PAYMENT_REQUIRED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.3

@item

@code{403}

@tab

@code{FORBIDDEN}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.4

@item

@code{404}

@tab

@code{NOT_FOUND}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.5

@item

@code{405}

@tab

@code{METHOD_NOT_ALLOWED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.6

@item

@code{406}

@tab

@code{NOT_ACCEPTABLE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.7

@item

@code{407}

@tab

@code{PROXY_AUTHENTICATION_REQUIRED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.8

@item

@code{408}

@tab

@code{REQUEST_TIMEOUT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.9

@item

@code{409}

@tab

@code{CONFLICT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.10

@item

@code{410}

@tab

@code{GONE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.11

@item

@code{411}

@tab

@code{LENGTH_REQUIRED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.12

@item

@code{412}

@tab

@code{PRECONDITION_FAILED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.13

@item

@code{413}

@tab

@code{CONTENT_TOO_LARGE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.14

@item

@code{414}

@tab

@code{URI_TOO_LONG}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.15

@item

@code{415}

@tab

@code{UNSUPPORTED_MEDIA_TYPE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.16

@item

@code{416}

@tab

@code{RANGE_NOT_SATISFIABLE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.17

@item

@code{417}

@tab

@code{EXPECTATION_FAILED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.18

@item

@code{418}

@tab

@code{IM_A_TEAPOT}

@tab

HTCPCP/1.0 
@geindex RFC; RFC 2324
RFC 2324@footnote{https://datatracker.ietf.org/doc/html/rfc2324.html}, Section 2.3.2

@item

@code{421}

@tab

@code{MISDIRECTED_REQUEST}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.20

@item

@code{422}

@tab

@code{UNPROCESSABLE_CONTENT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.21

@item

@code{423}

@tab

@code{LOCKED}

@tab

WebDAV 
@geindex RFC; RFC 4918
RFC 4918@footnote{https://datatracker.ietf.org/doc/html/rfc4918.html}, Section 11.3

@item

@code{424}

@tab

@code{FAILED_DEPENDENCY}

@tab

WebDAV 
@geindex RFC; RFC 4918
RFC 4918@footnote{https://datatracker.ietf.org/doc/html/rfc4918.html}, Section 11.4

@item

@code{425}

@tab

@code{TOO_EARLY}

@tab

Using Early Data in HTTP 
@geindex RFC; RFC 8470
RFC 8470@footnote{https://datatracker.ietf.org/doc/html/rfc8470.html}

@item

@code{426}

@tab

@code{UPGRADE_REQUIRED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.5.22

@item

@code{428}

@tab

@code{PRECONDITION_REQUIRED}

@tab

Additional HTTP Status Codes 
@geindex RFC; RFC 6585
RFC 6585@footnote{https://datatracker.ietf.org/doc/html/rfc6585.html}

@item

@code{429}

@tab

@code{TOO_MANY_REQUESTS}

@tab

Additional HTTP Status Codes 
@geindex RFC; RFC 6585
RFC 6585@footnote{https://datatracker.ietf.org/doc/html/rfc6585.html}

@item

@code{431}

@tab

@code{REQUEST_HEADER_FIELDS_TOO_LARGE}

@tab

Additional HTTP Status Codes 
@geindex RFC; RFC 6585
RFC 6585@footnote{https://datatracker.ietf.org/doc/html/rfc6585.html}

@item

@code{451}

@tab

@code{UNAVAILABLE_FOR_LEGAL_REASONS}

@tab

An HTTP Status Code to Report Legal Obstacles 
@geindex RFC; RFC 7725
RFC 7725@footnote{https://datatracker.ietf.org/doc/html/rfc7725.html}

@item

@code{500}

@tab

@code{INTERNAL_SERVER_ERROR}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.6.1

@item

@code{501}

@tab

@code{NOT_IMPLEMENTED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.6.2

@item

@code{502}

@tab

@code{BAD_GATEWAY}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.6.3

@item

@code{503}

@tab

@code{SERVICE_UNAVAILABLE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.6.4

@item

@code{504}

@tab

@code{GATEWAY_TIMEOUT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.6.5

@item

@code{505}

@tab

@code{HTTP_VERSION_NOT_SUPPORTED}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15.6.6

@item

@code{506}

@tab

@code{VARIANT_ALSO_NEGOTIATES}

@tab

Transparent Content Negotiation in HTTP 
@geindex RFC; RFC 2295
RFC 2295@footnote{https://datatracker.ietf.org/doc/html/rfc2295.html}, Section 8.1 (Experimental)

@item

@code{507}

@tab

@code{INSUFFICIENT_STORAGE}

@tab

WebDAV 
@geindex RFC; RFC 4918
RFC 4918@footnote{https://datatracker.ietf.org/doc/html/rfc4918.html}, Section 11.5

@item

@code{508}

@tab

@code{LOOP_DETECTED}

@tab

WebDAV Binding Extensions 
@geindex RFC; RFC 5842
RFC 5842@footnote{https://datatracker.ietf.org/doc/html/rfc5842.html}, Section 7.2 (Experimental)

@item

@code{510}

@tab

@code{NOT_EXTENDED}

@tab

An HTTP Extension Framework 
@geindex RFC; RFC 2774
RFC 2774@footnote{https://datatracker.ietf.org/doc/html/rfc2774.html}, Section 7 (Experimental)

@item

@code{511}

@tab

@code{NETWORK_AUTHENTICATION_REQUIRED}

@tab

Additional HTTP Status Codes 
@geindex RFC; RFC 6585
RFC 6585@footnote{https://datatracker.ietf.org/doc/html/rfc6585.html}, Section 6

@end multitable


後方互換性を保つために列挙値は @ref{73,,http.client} にも定数という形で存在します。
列挙名は定数名と同じです (すなわち @code{http.HTTPStatus.OK} は @code{http.client.OK} としても利用可能です)。


バージョン 3.7 で変更: ステータスコード @code{421 MISDIRECTED_REQUEST} が追加されました。



Added in version 3.8: ステータスコード @code{451 UNAVAILABLE_FOR_LEGAL_REASONS} が追加されました。



Added in version 3.9: ステータスコード @code{103 EARLY_HINTS}, @code{418 IM_A_TEAPOT}, @code{425 TOO_EARLY} が追加されました。



バージョン 3.13 で変更: Implemented RFC9110 naming for status constants. Old constant names are preserved for
backwards compatibility: @code{413 REQUEST_ENTITY_TOO_LARGE}, @code{414 REQUEST_URI_TOO_LONG},
@code{416 REQUESTED_RANGE_NOT_SATISFIABLE} and @code{422 UNPROCESSABLE_ENTITY}.


@node HTTP ステータスコードカテゴリ,HTTP メソッド,HTTP ステータスコード,http --- HTTP モジュール群
@anchor{library/http http-status-category}@anchor{3fc1}
@subsubsection HTTP ステータスコードカテゴリ



Added in version 3.12.


列挙型の値は HTTP ステータスカテゴリを示すいくつかのプロパティを持ちます。


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

プロパティ

@tab

示していること

@tab

詳細

@item

@code{is_informational}

@tab

@code{100 <= status <= 199}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15

@item

@code{is_success}

@tab

@code{200 <= status <= 299}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15

@item

@code{is_redirection}

@tab

@code{300 <= status <= 399}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15

@item

@code{is_client_error}

@tab

@code{400 <= status <= 499}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15

@item

@code{is_server_error}

@tab

@code{500 <= status <= 599}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 15

@end multitable


@quotation

使い方:

@example
>>> from http import HTTPStatus
>>> HTTPStatus.OK.is_success
True
>>> HTTPStatus.OK.is_client_error
False
@end example
@end quotation

@geindex HTTPMethod (http のクラス)
@anchor{library/http http HTTPMethod}@anchor{3fc2}
@deffn {クラス} http.HTTPMethod


Added in version 3.11.


一連の HTTP メソッド、英語で書かれた記述を定義した @ref{82d,,enum.StrEnum} のサブクラスです。

使い方:

@example
>>> from http import HTTPMethod
>>>
>>> HTTPMethod.GET
<HTTPMethod.GET>
>>> HTTPMethod.GET == 'GET'
True
>>> HTTPMethod.GET.value
'GET'
>>> HTTPMethod.GET.description
'Retrieve the target.'
>>> list(HTTPMethod)
[<HTTPMethod.CONNECT>,
 <HTTPMethod.DELETE>,
 <HTTPMethod.GET>,
 <HTTPMethod.HEAD>,
 <HTTPMethod.OPTIONS>,
 <HTTPMethod.PATCH>,
 <HTTPMethod.POST>,
 <HTTPMethod.PUT>,
 <HTTPMethod.TRACE>]
@end example
@end deffn

@node HTTP メソッド,,HTTP ステータスコードカテゴリ,http --- HTTP モジュール群
@anchor{library/http http-methods}@anchor{3fc3}@anchor{library/http id2}@anchor{3fc4}
@subsubsection HTTP メソッド


@ref{3fc2,,http.HTTPMethod} で利用可能な、サポートされている、IANA に登録されたメソッド@footnote{https://www.iana.org/assignments/http-methods/http-methods.xhtml} は:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

メソッド

@tab

列挙名

@tab

詳細

@item

@code{GET}

@tab

@code{GET}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.1

@item

@code{HEAD}

@tab

@code{HEAD}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.2

@item

@code{POST}

@tab

@code{POST}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.3

@item

@code{PUT}

@tab

@code{PUT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.4

@item

@code{DELETE}

@tab

@code{DELETE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.5

@item

@code{CONNECT}

@tab

@code{CONNECT}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.6

@item

@code{OPTIONS}

@tab

@code{OPTIONS}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.7

@item

@code{TRACE}

@tab

@code{TRACE}

@tab

HTTP Semantics 
@geindex RFC; RFC 9110
RFC 9110@footnote{https://datatracker.ietf.org/doc/html/rfc9110.html}, Section 9.3.8

@item

@code{PATCH}

@tab

@code{PATCH}

@tab

HTTP/1.1 
@geindex RFC; RFC 5789
RFC 5789@footnote{https://datatracker.ietf.org/doc/html/rfc5789.html}

@end multitable


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node http client --- HTTP プロトコルクライアント,ftplib --- FTP プロトコルクライアント,http --- HTTP モジュール群,インターネットプロトコルとサポート
@anchor{library/http client doc}@anchor{3fc5}@anchor{library/http client http-client-http-protocol-client}@anchor{3fc6}@anchor{library/http client module-http client}@anchor{73}@anchor{library/http client translation-repo}@anchor{3fc7}
@subsection @code{http.client} --- HTTP プロトコルクライアント


@geindex module; http.client

`ソースコード:' Lib/http/client.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/http/client.py}

@geindex HTTP;プロトコル
@geindex HTTP;http.client (標準モジュール)

@geindex module;urllib.request


__________________________________________________________________


このモジュールでは HTTP および HTTPS プロトコルのクライアントサイドを実装しているクラスを定義しています。通常、このモジュールは直接使いません --- @ref{111,,urllib.request} モジュールが HTTP や HTTPS を使った URL を扱う上でこのモジュールを使います。


@subsubheading 参考


より高水準の HTTP クライアントインターフェースとして Requests パッケージ@footnote{https://requests.readthedocs.io/en/latest/} が推奨されています。


@cartouche
@quotation 注釈 
HTTPS のサポートは、Python が SSL サポート付きでコンパイルされている場合にのみ利用できます (@ref{d5,,ssl} モジュールによって)。
@end quotation
@end cartouche

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

このモジュールでは以下のクラスを提供しています:

@geindex HTTPConnection (http.client のクラス)
@anchor{library/http client http client HTTPConnection}@anchor{d35}
@deffn {クラス} http.client.HTTPConnection (host, port=None[, timeout], source_address=None, blocksize=8192)

@ref{d35,,HTTPConnection} インスタンスは、HTTP サーバとの一回のトランザクションを表現します。
インスタンスの生成はホスト名とオプションのポート番号を与えることで行います。
ポート番号を指定しなかった場合、ホスト名文字列が @code{host:port} の形式であれば、ホスト名からポート番号を抽出し、そうでない場合には標準の HTTP ポート番号 (80) を使います。
オプションの引数 `timeout' が渡された場合、ブロックする処理 (コネクション接続など) のタイムアウト時間(秒数)として利用されます (渡されなかった場合は、グローバルのデフォルトタイムアウト設定が利用されます)。
オプションの引数 `source_address' を (host, port) という形式のタプルにすると HTTP 接続の接続元アドレスとして使用します。
オプションの `blocksize' 引数は、送信するファイル類メッセージボディのバッファサイズをバイト単位で設定します。

例えば、以下の呼び出しは全て同じサーバの同じポートに接続するインスタンスを生成します:

@example
>>> h1 = http.client.HTTPConnection('www.python.org')
>>> h2 = http.client.HTTPConnection('www.python.org:80')
>>> h3 = http.client.HTTPConnection('www.python.org', 80)
>>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)
@end example


バージョン 3.2 で変更: `source_address' が追加されました。



バージョン 3.4 で変更: `strict' パラメータは廃止されました。HTTP 0.9 の "シンプルなレスポンス" のような形式はもはやサポートされません。



バージョン 3.7 で変更: `blocksize' 引数が追加されました。

@end deffn

@geindex HTTPSConnection (http.client のクラス)
@anchor{library/http client http client HTTPSConnection}@anchor{d36}
@deffn {クラス} http.client.HTTPSConnection (host, port=None, *[, timeout], source_address=None, context=None, blocksize=8192)

@ref{d35,,HTTPConnection} のサブクラスはセキュア・サーバとやりとりする為の SSL を使う場合に用います。デフォルトのポート番号は @code{443} です。`context' が指定されれば、それは様々な SSL オプションを記述する @ref{357,,ssl.SSLContext} インスタンスでなければなりません。

ベストプラクティスに関するより良い情報が @ref{3895,,セキュリティで考慮すべき点} にありますのでお読みください。


バージョン 3.2 で変更: `source_address'、`context' そして `check_hostname' が追加されました。



バージョン 3.2 で変更: このクラスは現在、可能であれば (つまり @ref{39d6,,ssl.HAS_SNI} が真の場合) HTTPS のバーチャルホストをサポートしています。



バージョン 3.4 で変更: `strict' パラメータは廃止されました。HTTP 0.9 の "シンプルなレスポンス" のような形式はもはやサポートされません。



バージョン 3.4.3 で変更: このクラスは今や全ての必要な証明書とホスト名の検証をデフォルトで行うようになりました。 `context' パラメーターに @code{ssl._create_unverified_context()} を渡すことで、昔の、検証を行わない振る舞いに戻すことができます。



バージョン 3.8 で変更: This class now enables TLS 1.3
@ref{c26,,ssl.SSLContext.post_handshake_auth} for the default `context' or
when `cert_file' is passed with a custom `context'.



バージョン 3.10 で変更: This class now sends an ALPN extension with protocol indicator
@code{http/1.1} when no `context' is given. Custom `context' should set
ALPN protocols with @ref{1064,,set_alpn_protocols()}.



バージョン 3.12 で変更: The deprecated `key_file', `cert_file' and `check_hostname' parameters
have been removed.

@end deffn

@geindex HTTPResponse (http.client のクラス)
@anchor{library/http client http client HTTPResponse}@anchor{12e5}
@deffn {クラス} http.client.HTTPResponse (sock, debuglevel=0, method=None, url=None)

コネクションに成功したときに、このクラスのインスタンスが返されます。ユーザーから直接利用されることはありません。


バージョン 3.4 で変更: `strict' パラメータは廃止されました。HTTP 0.9 の "シンプルなレスポンス" のような形式はもはやサポートされません。

@end deffn

このモジュールは以下の関数を提供します:

@geindex parse_headers() (http.client モジュール)
@anchor{library/http client http client parse_headers}@anchor{1e28}
@deffn {の関数} http.client.parse_headers (fp)

Parse the headers from a file pointer `fp' representing a HTTP
request/response. The file has to be a @ref{8a3,,BufferedIOBase} reader
(i.e. not text) and must provide a valid 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} style header.

This function returns an instance of @ref{3fc8,,http.client.HTTPMessage}
that holds the header fields, but no payload
(the same as @ref{3fc9,,HTTPResponse.msg}
and @ref{3fca,,http.server.BaseHTTPRequestHandler.headers}).
After returning, the file pointer `fp' is ready to read the HTTP body.

@cartouche
@quotation 注釈 
@ref{1e28,,parse_headers()} does not parse the start-line of a HTTP message;
it only parses the @code{Name: value} lines. The file has to be ready to
read these field lines, so the first line should already be consumed
before calling the function.
@end quotation
@end cartouche
@end deffn

状況に応じて、以下の例外が送出されます:

@geindex HTTPException
@anchor{library/http client http client HTTPException}@anchor{3fcb}
@deffn {例外} http.client.HTTPException

このモジュールにおける他の例外クラスの基底クラスです。 @ref{bcd,,Exception} のサブクラスです。
@end deffn

@geindex NotConnected
@anchor{library/http client http client NotConnected}@anchor{3fcc}
@deffn {例外} http.client.NotConnected

@ref{3fcb,,HTTPException} サブクラスです。
@end deffn

@geindex InvalidURL
@anchor{library/http client http client InvalidURL}@anchor{3fcd}
@deffn {例外} http.client.InvalidURL

@ref{3fcb,,HTTPException} のサブクラスです。ポート番号を指定したものの、その値が数字でなかったり空のオブジェクトであった場合に送出されます。
@end deffn

@geindex UnknownProtocol
@anchor{library/http client http client UnknownProtocol}@anchor{3fce}
@deffn {例外} http.client.UnknownProtocol

@ref{3fcb,,HTTPException} サブクラスです。
@end deffn

@geindex UnknownTransferEncoding
@anchor{library/http client http client UnknownTransferEncoding}@anchor{3fcf}
@deffn {例外} http.client.UnknownTransferEncoding

@ref{3fcb,,HTTPException} サブクラスです。
@end deffn

@geindex UnimplementedFileMode
@anchor{library/http client http client UnimplementedFileMode}@anchor{3fd0}
@deffn {例外} http.client.UnimplementedFileMode

@ref{3fcb,,HTTPException} サブクラスです。
@end deffn

@geindex IncompleteRead
@anchor{library/http client http client IncompleteRead}@anchor{3fd1}
@deffn {例外} http.client.IncompleteRead

@ref{3fcb,,HTTPException} サブクラスです。
@end deffn

@geindex ImproperConnectionState
@anchor{library/http client http client ImproperConnectionState}@anchor{3fd2}
@deffn {例外} http.client.ImproperConnectionState

@ref{3fcb,,HTTPException} サブクラスです。
@end deffn

@geindex CannotSendRequest
@anchor{library/http client http client CannotSendRequest}@anchor{3fd3}
@deffn {例外} http.client.CannotSendRequest

@ref{3fd2,,ImproperConnectionState} のサブクラスです。
@end deffn

@geindex CannotSendHeader
@anchor{library/http client http client CannotSendHeader}@anchor{3fd4}
@deffn {例外} http.client.CannotSendHeader

@ref{3fd2,,ImproperConnectionState} のサブクラスです。
@end deffn

@geindex ResponseNotReady
@anchor{library/http client http client ResponseNotReady}@anchor{3fd5}
@deffn {例外} http.client.ResponseNotReady

@ref{3fd2,,ImproperConnectionState} のサブクラスです。
@end deffn

@geindex BadStatusLine
@anchor{library/http client http client BadStatusLine}@anchor{3fd6}
@deffn {例外} http.client.BadStatusLine

@ref{3fcb,,HTTPException} のサブクラスです。サーバが理解できない HTTP 状態コードで応答した場合に送出されます。
@end deffn

@geindex LineTooLong
@anchor{library/http client http client LineTooLong}@anchor{3fd7}
@deffn {例外} http.client.LineTooLong

A subclass of @ref{3fcb,,HTTPException}.  Raised if an excessively long line
is received in the HTTP protocol from the server.
@end deffn

@geindex RemoteDisconnected
@anchor{library/http client http client RemoteDisconnected}@anchor{100a}
@deffn {例外} http.client.RemoteDisconnected

A subclass of @ref{126a,,ConnectionResetError} and @ref{3fd6,,BadStatusLine}.  Raised
by @ref{1009,,HTTPConnection.getresponse()} when the attempt to read the response
results in no data read from the connection, indicating that the remote end
has closed the connection.


Added in version 3.5: Previously, @ref{3fd6,,BadStatusLine}@code{('@w{'})} was raised.

@end deffn

このモジュールで定義されている定数は以下の通りです:

@geindex HTTP_PORT (http.client モジュール)
@anchor{library/http client http client HTTP_PORT}@anchor{3fd8}
@deffn {データ} http.client.HTTP_PORT

HTTP プロトコルの標準のポート (通常は @code{80}) です。
@end deffn

@geindex HTTPS_PORT (http.client モジュール)
@anchor{library/http client http client HTTPS_PORT}@anchor{3fd9}
@deffn {データ} http.client.HTTPS_PORT

HTTPS プロトコルの標準のポート (通常は @code{443}) です。
@end deffn

@geindex responses (http.client モジュール)
@anchor{library/http client http client responses}@anchor{3fda}
@deffn {データ} http.client.responses

このディクショナリは、HTTP 1.1ステータスコードをW3Cの名前にマップしたものです。

例: @code{http.client.responses[http.client.NOT_FOUND]} は @code{'Not Found'} を示します。
@end deffn

See @ref{3fbf,,HTTP ステータスコード} for a list of HTTP status codes that are
available in this module as constants.

@menu
* HTTPConnection オブジェクト:: 
* HTTPResponse オブジェクト:: 
* 使用例: 使用例<38>. 
* HTTPMessage オブジェクト:: 

@end menu

@node HTTPConnection オブジェクト,HTTPResponse オブジェクト,,http client --- HTTP プロトコルクライアント
@anchor{library/http client httpconnection-objects}@anchor{3fdb}@anchor{library/http client id1}@anchor{3fdc}
@subsubsection HTTPConnection オブジェクト


@ref{d35,,HTTPConnection} インスタンスには以下のメソッドがあります:

@geindex request() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection request}@anchor{ea7}
@deffn {メソッド} HTTPConnection.request (method, url, body=None, headers=@{@}, *, encode_chunked=False)

This will send a request to the server using the HTTP request
method `method' and the request URI `url'. The provided `url' must be
an absolute path to conform with 
@geindex RFC; RFC 2616 Section 5.1.2
RFC 2616 §5.1.2@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html#section-5.1.2}
(unless connecting to an HTTP proxy server or using the @code{OPTIONS} or
@code{CONNECT} methods).

If `body' is specified, the specified data is sent after the headers are
finished.  It may be a @ref{169,,str}, a @ref{193,,bytes-like object}, an
open @ref{13db,,file object}, or an iterable of @ref{192,,bytes}.  If `body'
is a string, it is encoded as ISO-8859-1, the default for HTTP.  If it
is a bytes-like object, the bytes are sent as is.  If it is a @ref{13db,,file object}, the contents of the file is sent; this file object should
support at least the @code{read()} method.  If the file object is an
instance of @ref{8a4,,io.TextIOBase}, the data returned by the @code{read()}
method will be encoded as ISO-8859-1, otherwise the data returned by
@code{read()} is sent as is.  If `body' is an iterable, the elements of the
iterable are sent as is until the iterable is exhausted.

The `headers' argument should be a mapping of extra HTTP headers to send
with the request. A 
@geindex RFC; RFC 2616 Section 14.23
Host header@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html#section-14.23}
must be provided to conform with 
@geindex RFC; RFC 2616 Section 5.1.2
RFC 2616 §5.1.2@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html#section-5.1.2}
(unless connecting to an HTTP proxy server or using the @code{OPTIONS} or
@code{CONNECT} methods).

If `headers' contains neither Content-Length nor Transfer-Encoding,
but there is a request body, one of those
header fields will be added automatically.  If
`body' is @code{None}, the Content-Length header is set to @code{0} for
methods that expect a body (@code{PUT}, @code{POST}, and @code{PATCH}).  If
`body' is a string or a bytes-like object that is not also a
@ref{13db,,file}, the Content-Length header is
set to its length.  Any other type of `body' (files
and iterables in general) will be chunk-encoded, and the
Transfer-Encoding header will automatically be set instead of
Content-Length.

The `encode_chunked' argument is only relevant if Transfer-Encoding is
specified in `headers'.  If `encode_chunked' is @code{False}, the
HTTPConnection object assumes that all encoding is handled by the
calling code.  If it is @code{True}, the body will be chunk-encoded.

For example, to perform a @code{GET} request to @code{https://docs.python.org/3/}:

@example
>>> import http.client
>>> host = "docs.python.org"
>>> conn = http.client.HTTPSConnection(host)
>>> conn.request("GET", "/3/", headers=@{"Host": host@})
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200 OK
@end example

@cartouche
@quotation 注釈 
Chunked transfer encoding has been added to the HTTP protocol
version 1.1.  Unless the HTTP server is known to handle HTTP 1.1,
the caller must either specify the Content-Length, or must pass a
@ref{169,,str} or bytes-like object that is not also a file as the
body representation.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
Note that you must have read the whole response or call @ref{3fdd,,close()}
if @ref{1009,,getresponse()} raised an non-@ref{100b,,ConnectionError} exception
before you can send a new request to the server.
@end quotation
@end cartouche


バージョン 3.2 で変更: `body' は iterable オブジェクトとして使用できます。



バージョン 3.6 で変更: If neither Content-Length nor Transfer-Encoding are set in
`headers', file and iterable `body' objects are now chunk-encoded.
The `encode_chunked' argument was added.
No attempt is made to determine the Content-Length for file
objects.

@end deffn

@geindex getresponse() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection getresponse}@anchor{1009}
@deffn {メソッド} HTTPConnection.getresponse ()

サーバに対して HTTP 要求を送り出した後に呼び出されなければりません。要求に対する応答を取得します。 @ref{12e5,,HTTPResponse} インスタンスを返します。


バージョン 3.5 で変更: If a @ref{100b,,ConnectionError} or subclass is raised, the
@ref{d35,,HTTPConnection} object will be ready to reconnect when
a new request is sent.

Note that this does not apply to @ref{2c0,,OSError}s raised by the underlying
socket. Instead the caller is responsible to call @ref{3fdd,,close()} on the
existing connection.

@end deffn

@geindex set_debuglevel() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection set_debuglevel}@anchor{3fde}
@deffn {メソッド} HTTPConnection.set_debuglevel (level)

Set the debugging level.  The default debug level is @code{0}, meaning no
debugging output is printed.  Any value greater than @code{0} will cause all
currently defined debug output to be printed to stdout.  The @code{debuglevel}
is passed to any new @ref{12e5,,HTTPResponse} objects that are created.


Added in version 3.1.

@end deffn

@geindex set_tunnel() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection set_tunnel}@anchor{1440}
@deffn {メソッド} HTTPConnection.set_tunnel (host, port=None, headers=None)

HTTP トンネリング接続のホスト名とポート番号を設定します。これによりプロキシサーバを通しての接続を実行できます。

The `host' and `port' arguments specify the endpoint of the tunneled connection
(i.e. the address included in the CONNECT request, `not' the address of the
proxy server).

The `headers' argument should be a mapping of extra HTTP headers to send with
the CONNECT request.

As HTTP/1.1 is used for HTTP CONNECT tunnelling request, as per the RFC@footnote{https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.6}, a HTTP @code{Host:}
header must be provided, matching the authority-form of the request target
provided as the destination for the CONNECT request. If a HTTP @code{Host:}
header is not provided via the headers argument, one is generated and
transmitted automatically.

For example, to tunnel through a HTTPS proxy server running locally on port
8080, we would pass the address of the proxy to the @ref{d36,,HTTPSConnection}
constructor, and the address of the host that we eventually want to reach to
the @ref{1440,,set_tunnel()} method:

@example
>>> import http.client
>>> conn = http.client.HTTPSConnection("localhost", 8080)
>>> conn.set_tunnel("www.python.org")
>>> conn.request("HEAD","/index.html")
@end example


Added in version 3.2.



バージョン 3.12 で変更: HTTP CONNECT tunnelling requests use protocol HTTP/1.1, upgraded from
protocol HTTP/1.0. @code{Host:} HTTP headers are mandatory for HTTP/1.1, so
one will be automatically generated and transmitted if not provided in
the headers argument.

@end deffn

@geindex get_proxy_response_headers() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection get_proxy_response_headers}@anchor{1a73}
@deffn {メソッド} HTTPConnection.get_proxy_response_headers ()

Returns a dictionary with the headers of the response received from
the proxy server to the CONNECT request.

If the CONNECT request was not sent, the method returns @code{None}.


Added in version 3.12.

@end deffn

@geindex connect() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection connect}@anchor{3fdf}
@deffn {メソッド} HTTPConnection.connect ()

Connect to the server specified when the object was created.  By default,
this is called automatically when making a request if the client does not
already have a connection.

Raises an @ref{1c6e,,auditing event} @code{http.client.connect} with arguments @code{self}, @code{host}, @code{port}.
@end deffn

@geindex close() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection close}@anchor{3fdd}
@deffn {メソッド} HTTPConnection.close ()

サーバへの接続を閉じます。
@end deffn

@geindex blocksize (http.client.HTTPConnection の属性)
@anchor{library/http client http client HTTPConnection blocksize}@anchor{3fe0}
@deffn {の属性} HTTPConnection.blocksize

Buffer size in bytes for sending a file-like message body.


Added in version 3.7.

@end deffn

As an alternative to using the @ref{ea7,,request()} method described above, you can
also send your request step by step, by using the four functions below.

@geindex putrequest() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection putrequest}@anchor{3fe1}
@deffn {メソッド} HTTPConnection.putrequest (method, url, skip_host=False, skip_accept_encoding=False)

サーバへの接続が確立したら、最初にこのメソッドを呼び出さなくてはなりません。このメソッドは `method' 文字列、`url' 文字列、そして HTTP バージョン (@code{HTTP/1.1}) からなる一行を送信します。@code{Host:} や @code{Accept-Encoding:} ヘッダの自動送信を無効にしたい場合 (例えば別のコンテンツエンコーディングを受け入れたい場合) には、`skip_host' や `skip_accept_encoding' を偽でない値に設定してください。
@end deffn

@geindex putheader() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection putheader}@anchor{3fe2}
@deffn {メソッド} HTTPConnection.putheader (header, argument[, ...])

@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html} 形式のヘッダをサーバに送ります。この処理では、 `header' 、コロンとスペース、そして最初の引数からなる 1 行をサーバに送ります。追加の引数を指定した場合、継続して各行にタブ一つと引数の入った引数行が送信されます。
@end deffn

@geindex endheaders() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection endheaders}@anchor{ea8}
@deffn {メソッド} HTTPConnection.endheaders (message_body=None, *, encode_chunked=False)

サーバに空行を送り、ヘッダ部が終了したことを通知します。オプションの `message_body' 引数を、リクエストに関連したメッセージボディを渡すのに使うことが出来ます。

If `encode_chunked' is @code{True}, the result of each iteration of
`message_body' will be chunk-encoded as specified in 
@geindex RFC; RFC 7230
RFC 7230@footnote{https://datatracker.ietf.org/doc/html/rfc7230.html},
Section 3.3.1.  How the data is encoded is dependent on the type of
`message_body'.  If `message_body' implements the @ref{260,,buffer interface} the encoding will result in a single chunk.
If `message_body' is a @ref{26ae,,collections.abc.Iterable}, each iteration
of `message_body' will result in a chunk.  If `message_body' is a
@ref{13db,,file object}, each call to @code{.read()} will result in a chunk.
The method automatically signals the end of the chunk-encoded data
immediately after `message_body'.

@cartouche
@quotation 注釈 
Due to the chunked encoding specification, empty chunks
yielded by an iterator body will be ignored by the chunk-encoder.
This is to avoid premature termination of the read of the request by
the target server due to malformed encoding.
@end quotation
@end cartouche


バージョン 3.6 で変更: Added chunked encoding support and the `encode_chunked' parameter.

@end deffn

@geindex send() (http.client.HTTPConnection のメソッド)
@anchor{library/http client http client HTTPConnection send}@anchor{3fe3}
@deffn {メソッド} HTTPConnection.send (data)

サーバにデータを送ります。このメソッドは @ref{ea8,,endheaders()}  が呼び出された直後で、かつ @ref{1009,,getresponse()} が呼び出される前に使わなければなりません。

Raises an @ref{1c6e,,auditing event} @code{http.client.send} with arguments @code{self}, @code{data}.
@end deffn

@node HTTPResponse オブジェクト,使用例<38>,HTTPConnection オブジェクト,http client --- HTTP プロトコルクライアント
@anchor{library/http client httpresponse-objects}@anchor{3fe4}@anchor{library/http client id2}@anchor{3fe5}
@subsubsection HTTPResponse オブジェクト


@ref{12e5,,HTTPResponse} インスタンスはサーバからのHTTPレスポンスをラップします。これを使用してリクエストヘッダとエンティティボディへアクセスすることができます。レスポンスはイテレート可能なオブジェクトであり、また with文と使うことも可能です。


バージョン 3.5 で変更: The @ref{8a3,,io.BufferedIOBase} interface is now implemented and
all of its reader operations are supported.


@geindex read() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse read}@anchor{18af}
@deffn {メソッド} HTTPResponse.read ([amt])

応答の本体全体か、`amt' バイトまで読み出して返します。
@end deffn

@geindex readinto() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse readinto}@anchor{12e6}
@deffn {メソッド} HTTPResponse.readinto (b)

バッファ `b' にレスポンスボディの次のデータを最大 len(b) バイト読み込みます。何バイト読んだかを返します。


Added in version 3.3.

@end deffn

@geindex getheader() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse getheader}@anchor{3fe6}
@deffn {メソッド} HTTPResponse.getheader (name, default=None)

Return the value of the header `name', or `default' if there is no header
matching `name'.  If there is more than one  header with the name `name',
return all of the values joined by ', '.  If `default' is any iterable other
than a single string, its elements are similarly returned joined by commas.
@end deffn

@geindex getheaders() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse getheaders}@anchor{3fe7}
@deffn {メソッド} HTTPResponse.getheaders ()

(header, value) のタプルからなるリストを返します。
@end deffn

@geindex fileno() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse fileno}@anchor{3fe8}
@deffn {メソッド} HTTPResponse.fileno ()

ソケットの @code{fileno} を返します。
@end deffn

@geindex msg (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse msg}@anchor{3fc9}
@deffn {の属性} HTTPResponse.msg

A @ref{3fc8,,http.client.HTTPMessage} instance containing the response
headers.  @ref{3fc8,,http.client.HTTPMessage} is a subclass of
@ref{581,,email.message.Message}.
@end deffn

@geindex version (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse version}@anchor{3fe9}
@deffn {の属性} HTTPResponse.version

サーバが使用した HTTP プロトコルバージョンです。10 は HTTP/1.0 を、11 は HTTP/1.1 を表します。
@end deffn

@geindex url (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse url}@anchor{3fea}
@deffn {の属性} HTTPResponse.url

取得されたリソースの URL、主にリダイレクトが発生したかどうかを確認するために利用します。
@end deffn

@geindex headers (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse headers}@anchor{3feb}
@deffn {の属性} HTTPResponse.headers

Headers of the response in the form of an @ref{580,,email.message.EmailMessage} instance.
@end deffn

@geindex status (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse status}@anchor{3fec}
@deffn {の属性} HTTPResponse.status

サーバから返される状態コードです。
@end deffn

@geindex reason (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse reason}@anchor{3f17}
@deffn {の属性} HTTPResponse.reason

サーバから返される応答の理由文です。
@end deffn

@geindex debuglevel (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse debuglevel}@anchor{3fed}
@deffn {の属性} HTTPResponse.debuglevel

A debugging hook.  If @ref{3fed,,debuglevel} is greater than zero, messages
will be printed to stdout as the response is read and parsed.
@end deffn

@geindex closed (http.client.HTTPResponse の属性)
@anchor{library/http client http client HTTPResponse closed}@anchor{3fee}
@deffn {の属性} HTTPResponse.closed

ストリームが閉じている場合 @code{True} となります。
@end deffn

@geindex geturl() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse geturl}@anchor{3fef}
@deffn {メソッド} HTTPResponse.geturl ()


バージョン 3.9 で非推奨: 非推奨となったので @ref{3fea,,url} を使用してください。

@end deffn

@geindex info() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse info}@anchor{3ff0}
@deffn {メソッド} HTTPResponse.info ()


バージョン 3.9 で非推奨: 非推奨となったので @ref{3feb,,headers} を使用してください。

@end deffn

@geindex getcode() (http.client.HTTPResponse のメソッド)
@anchor{library/http client http client HTTPResponse getcode}@anchor{3ff1}
@deffn {メソッド} HTTPResponse.getcode ()


バージョン 3.9 で非推奨: 非推奨となったので @ref{3fec,,status} を使用してください。

@end deffn

@node 使用例<38>,HTTPMessage オブジェクト,HTTPResponse オブジェクト,http client --- HTTP プロトコルクライアント
@anchor{library/http client examples}@anchor{3ff2}
@subsubsection 使用例


以下は @code{GET} リクエストの送信方法を示した例です:

@example
>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
200 OK
>>> data1 = r1.read()  # This will return entire content.
>>> # The following example demonstrates reading data in chunks.
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> while chunk := r1.read(200):
...     print(repr(chunk))
b'<!doctype html>\n<!--[if"...
...
>>> # Example of an invalid request
>>> conn = http.client.HTTPSConnection("docs.python.org")
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
@end example

次の例のセッションでは、@code{HEAD} メソッドを利用しています。@code{HEAD} メソッドは全くデータを返さないことに注目してください。

@example
>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("HEAD", "/")
>>> res = conn.getresponse()
>>> print(res.status, res.reason)
200 OK
>>> data = res.read()
>>> print(len(data))
0
>>> data == b'@w{'}
True
@end example

Here is an example session that uses the @code{POST} method:

@example
>>> import http.client, urllib.parse
>>> params = urllib.parse.urlencode(@{'@@number': 12524, '@@type': 'issue', '@@action': 'show'@})
>>> headers = @{"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"@}
>>> conn = http.client.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
302 Found
>>> data = response.read()
>>> data
b'Redirecting to <a href="https://bugs.python.org/issue12524">https://bugs.python.org/issue12524</a>'
>>> conn.close()
@end example

Client side HTTP @code{PUT} requests are very similar to @code{POST} requests. The
difference lies only on the server side where HTTP servers will allow resources to
be created via @code{PUT} requests. It should be noted that custom HTTP methods
are also handled in @ref{11da,,urllib.request.Request} by setting the appropriate
method attribute. Here is an example session that uses the @code{PUT} method:

@example
>>> # This creates an HTTP request
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/file
...
>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200, OK
@end example

@node HTTPMessage オブジェクト,,使用例<38>,http client --- HTTP プロトコルクライアント
@anchor{library/http client httpmessage-objects}@anchor{3ff3}@anchor{library/http client id3}@anchor{3ff4}
@subsubsection HTTPMessage オブジェクト


@geindex HTTPMessage (http.client のクラス)
@anchor{library/http client http client HTTPMessage}@anchor{3fc8}
@deffn {クラス} http.client.HTTPMessage (email.message.Message)
@end deffn

@ref{3fc8,,http.client.HTTPMessage} のインスタンスは HTTP レスポンスヘッダを格納します。 @ref{581,,email.message.Message} クラスを利用して実装されています。

@c XXX Define the methods that clients can depend upon between versions.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ftplib --- FTP プロトコルクライアント,poplib --- POP3 プロトコルクライアント,http client --- HTTP プロトコルクライアント,インターネットプロトコルとサポート
@anchor{library/ftplib doc}@anchor{3ff5}@anchor{library/ftplib ftplib-ftp-protocol-client}@anchor{3ff6}@anchor{library/ftplib module-ftplib}@anchor{62}@anchor{library/ftplib translation-repo}@anchor{3ff7}
@subsection @code{ftplib} --- FTP プロトコルクライアント


@geindex module; ftplib

`ソースコード:' Lib/ftplib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/ftplib.py}

@geindex FTP;プロトコル
@geindex FTP;ftplib (standard module)


__________________________________________________________________


このモジュールでは @ref{af6,,FTP} クラスと、それに関連するいくつかの項目を定義しています。 @ref{af6,,FTP} クラスは、FTPプロトコルのクライアント側の機能を備えています。このクラスを使うとFTPのいろいろな機能の自動化、例えば他のFTPサーバのミラーリングといったことを実行するPythonプログラムを書くことができます。また、 @ref{111,,urllib.request} モジュールもFTPを使うURLを操作するのにこのクラスを使っています。 FTP (File Transfer Protocol)についての詳しい情報はinternet 
@geindex RFC; RFC 959
RFC 959@footnote{https://datatracker.ietf.org/doc/html/rfc959.html} を参照して下さい。

The default encoding is UTF-8, following 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://datatracker.ietf.org/doc/html/rfc2640.html}.

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

Here's a sample session using the @code{ftplib} module:

@example
>>> from ftplib import FTP
>>> ftp = FTP('ftp.us.debian.org')  # connect to host, default port
>>> ftp.login()                     # user anonymous, passwd anonymous@@
'230 Login successful.'
>>> ftp.cwd('debian')               # change into "debian" directory
'250 Directory successfully changed.'
>>> ftp.retrlines('LIST')           # list directory contents
-rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
...
drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
'226 Directory send OK.'
>>> with open('README', 'wb') as fp:
>>>     ftp.retrbinary('RETR README', fp.write)
'226 Transfer complete.'
>>> ftp.quit()
'221 Goodbye.'
@end example

@menu
* リファレンス: リファレンス<7>. 

@end menu

@node リファレンス<7>,,,ftplib --- FTP プロトコルクライアント
@anchor{library/ftplib ftplib-reference}@anchor{3ff8}@anchor{library/ftplib reference}@anchor{3ff9}
@subsubsection リファレンス


@menu
* FTP オブジェクト:: 
* FTP_TLS オブジェクト:: 
* モジュール変数:: 

@end menu

@node FTP オブジェクト,FTP_TLS オブジェクト,,リファレンス<7>
@anchor{library/ftplib ftp-objects}@anchor{3ffa}@anchor{library/ftplib id1}@anchor{3ffb}
@subsubsection FTP オブジェクト


@c Use substitutions for some param docs so we don't need to repeat them
@c in multiple places.

@c Ideally, we'd like to use the :rfc: directive, but Sphinx will not allow it.

@geindex FTP (ftplib のクラス)
@anchor{library/ftplib ftplib FTP}@anchor{af6}
@deffn {クラス} ftplib.FTP (host='@w{'}, user='@w{'}, passwd='@w{'}, acct='@w{'}, timeout=None, source_address=None, *, encoding='utf-8')

Return a new instance of the @ref{af6,,FTP} class.

@*パラメータ: 

@itemize *

@item 
@code{host} (@ref{169,,str}) -- The hostname to connect to.
If given, @code{connect(host)} is implicitly called by the constructor.

@item 
@code{user} (@ref{169,,str}) -- The username to log in with (default: @code{'anonymous'}).
If given, @code{login(host, passwd, acct)} is implicitly called
by the constructor.

@item 
@code{passwd} (@ref{169,,str}) -- The password to use when logging in.
If not given, and if `passwd' is the empty string or @code{"-"},
a password will be automatically generated.

@item 
@code{acct} (@ref{169,,str}) -- Account information to be used for the @code{ACCT} FTP command.
Few systems implement this.
See RFC-959@footnote{https://datatracker.ietf.org/doc/html/rfc959.html}
for more details.

@item 
@code{timeout} (@ref{196,,float}@code{ | }@code{None}) -- A timeout in seconds for blocking operations like @ref{3ffc,,connect()}
(default: the global default timeout setting).

@item 
@code{source_address} (@ref{614,,tuple}@code{ | }@code{None}) -- A 2-tuple @code{(host, port)} for the socket to bind to as its
source address before connecting.

@item 
@code{encoding} (@ref{169,,str}) -- The encoding for directories and filenames (default: @code{'utf-8'}).
@end itemize


@ref{af6,,FTP} クラスは @ref{186,,with} 文をサポートしています。例えば:

@example
>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
...     ftp.login()
...     ftp.dir()
...
'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
>>>
@end example


バージョン 3.2 で変更: @ref{186,,with} 構文のサポートが追加されました。



バージョン 3.3 で変更: `source_address' 引数が追加されました。



バージョン 3.9 で変更: If the `timeout' parameter is set to be zero, it will raise a
@ref{2ec,,ValueError} to prevent the creation of a non-blocking socket.
The `encoding' parameter was added, and the default was changed from
Latin-1 to UTF-8 to follow 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://datatracker.ietf.org/doc/html/rfc2640.html}.


Several @code{FTP} methods are available in two flavors:
one for handling text files and another for binary files.
The methods are named for the command which is used followed by
@code{lines} for the text version or @code{binary} for the binary version.

@ref{af6,,FTP} インスタンスには以下のメソッドがあります:

@geindex set_debuglevel() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP set_debuglevel}@anchor{3ffd}
@deffn {メソッド} set_debuglevel (level)

Set the instance's debugging level as an @ref{19b,,int}.
This controls the amount of debugging output printed.
The debug levels are:


@itemize *

@item 
@code{0} (default): No debug output.

@item 
@code{1}: Produce a moderate amount of debug output,
generally a single line per request.

@item 
@code{2} or higher: Produce the maximum amount of debugging output,
logging each line sent and received on the control connection.
@end itemize
@end deffn

@geindex connect() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP connect}@anchor{3ffc}
@deffn {メソッド} connect (host='@w{'}, port=0, timeout=None, source_address=None)

Connect to the given host and port.
This function should be called only once for each instance;
it should not be called if a `host' argument was given
when the @ref{af6,,FTP} instance was created.
All other @code{FTP} methods can only be called
after a connection has successfully been made.

@*パラメータ: 

@itemize *

@item 
@code{host} (@ref{169,,str}) -- The host to connect to.

@item 
@code{port} (@ref{19b,,int}) -- The TCP port to connect to (default: @code{21},
as specified by the FTP protocol specification).
It is rarely needed to specify a different port number.

@item 
@code{timeout} (@ref{196,,float}@code{ | }@code{None}) -- A timeout in seconds for the connection attempt
(default: the global default timeout setting).

@item 
@code{source_address} (@ref{614,,tuple}@code{ | }@code{None}) -- A 2-tuple @code{(host, port)} for the socket to bind to as its
source address before connecting.
@end itemize


引数 @code{self}, @code{host}, @code{port} を指定して @ref{1c6e,,監査イベント} @code{ftplib.connect} を送出します。


バージョン 3.3 で変更: `source_address' 引数が追加されました。

@end deffn

@geindex getwelcome() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP getwelcome}@anchor{3ffe}
@deffn {メソッド} getwelcome ()

サーバに最初に接続した際に送信される応答中のウェルカムメッセージを返します。(このメッセージには時に、ユーザにとって重要な免責事項や ヘルプ情報が入っています。)
@end deffn

@geindex login() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP login}@anchor{3fff}
@deffn {メソッド} login (user='anonymous', passwd='@w{'}, acct='@w{'})

Log on to the connected FTP server.
This function should be called only once for each instance,
after a connection has been established;
it should not be called if the `host' and `user' arguments were given
when the @ref{af6,,FTP} instance was created.
Most FTP commands are only allowed after the client has logged in.

@*パラメータ: 

@itemize *

@item 
@code{user} (@ref{169,,str}) -- The username to log in with (default: @code{'anonymous'}).

@item 
@code{passwd} (@ref{169,,str}) -- The password to use when logging in.
If not given, and if `passwd' is the empty string or @code{"-"},
a password will be automatically generated.

@item 
@code{acct} (@ref{169,,str}) -- Account information to be used for the @code{ACCT} FTP command.
Few systems implement this.
See RFC-959@footnote{https://datatracker.ietf.org/doc/html/rfc959.html}
for more details.
@end itemize

@end deffn

@geindex abort() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP abort}@anchor{4000}
@deffn {メソッド} abort ()

実行中のファイル転送を中止します。これはいつも機能するわけではありませんが、やってみる価値はあります。
@end deffn

@geindex sendcmd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP sendcmd}@anchor{4001}
@deffn {メソッド} sendcmd (cmd)

シンプルなコマンド文字列をサーバに送信して、受信した文字列を返します。

引数 @code{self}, @code{cmd} を指定して @ref{1c6e,,監査イベント} @code{ftplib.sendcmd} を送出します。
@end deffn

@geindex voidcmd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP voidcmd}@anchor{4002}
@deffn {メソッド} voidcmd (cmd)

Send a simple command string to the server and handle the response.  Return
the response string if the response code corresponds to success (codes in
the range 200--299).  Raise @ref{4003,,error_reply} otherwise.

引数 @code{self}, @code{cmd} を指定して @ref{1c6e,,監査イベント} @code{ftplib.sendcmd} を送出します。
@end deffn

@geindex retrbinary() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP retrbinary}@anchor{4004}
@deffn {メソッド} retrbinary (cmd, callback, blocksize=8192, rest=None)

Retrieve a file in binary transfer mode.

@*パラメータ: 

@itemize *

@item 
@code{cmd} (@ref{169,,str}) -- An appropriate @code{RETR} command: @code{"RETR @var{filename}"}.

@item 
@code{callback} (@ref{2d7b,,callable}) -- A single parameter callable that is called
for each block of data received,
with its single argument being the data as @ref{192,,bytes}.

@item 
@code{blocksize} (@ref{19b,,int}) -- The maximum chunk size to read on the low-level
@ref{fa1,,socket} object created to do the actual transfer.
This also corresponds to the largest size of data
that will be passed to `callback'.
Defaults to @code{8192}.

@item 
@code{rest} (@ref{19b,,int}) -- A @code{REST} command to be sent to the server.
See the documentation for the `rest' parameter of the @ref{4005,,transfercmd()} method.
@end itemize

@end deffn

@geindex retrlines() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP retrlines}@anchor{4006}
@deffn {メソッド} retrlines (cmd, callback=None)

Retrieve a file or directory listing in the encoding specified by the
`encoding' parameter at initialization.
`cmd' should be an appropriate @code{RETR} command (see @ref{4004,,retrbinary()}) or
a command such as @code{LIST} or @code{NLST} (usually just the string @code{'LIST'}).
@code{LIST} retrieves a list of files and information about those files.
@code{NLST} retrieves a list of file names.
The `callback' function is called for each line with a string argument
containing the line with the trailing CRLF stripped.  The default `callback'
prints the line to @ref{ccd,,sys.stdout}.
@end deffn

@geindex set_pasv() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP set_pasv}@anchor{4007}
@deffn {メソッド} set_pasv (val)

`val' が真の場合 "パッシブ" モードを有効化し、偽の場合は無効化します。 デフォルトではパッシブモードです。
@end deffn

@geindex storbinary() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP storbinary}@anchor{1521}
@deffn {メソッド} storbinary (cmd, fp, blocksize=8192, callback=None, rest=None)

Store a file in binary transfer mode.

@*パラメータ: 

@itemize *

@item 
@code{cmd} (@ref{169,,str}) -- An appropriate @code{STOR} command: @code{"STOR @var{filename}"}.

@item 
@code{fp} (@ref{13db,,file object}) -- A file object (opened in binary mode) which is read until EOF,
using its @ref{101d,,read()} method in blocks of size `blocksize'
to provide the data to be stored.

@item 
@code{blocksize} (@ref{19b,,int}) -- The read block size.
Defaults to @code{8192}.

@item 
@code{callback} (@ref{2d7b,,callable}) -- A single parameter callable that is called
for each block of data sent,
with its single argument being the data as @ref{192,,bytes}.

@item 
@code{rest} (@ref{19b,,int}) -- A @code{REST} command to be sent to the server.
See the documentation for the `rest' parameter of the @ref{4005,,transfercmd()} method.
@end itemize



バージョン 3.2 で変更: The `rest' parameter was added.

@end deffn

@geindex storlines() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP storlines}@anchor{4008}
@deffn {メソッド} storlines (cmd, fp, callback=None)

Store a file in line mode.  `cmd' should be an appropriate
@code{STOR} command (see @ref{1521,,storbinary()}).  Lines are read until EOF from the
@ref{13db,,file object} `fp' (opened in binary mode) using its @ref{1541,,readline()}
method to provide the data to be stored.  `callback' is an optional single
parameter callable that is called on each line after it is sent.
@end deffn

@geindex transfercmd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP transfercmd}@anchor{4005}
@deffn {メソッド} transfercmd (cmd, rest=None)

データ接続中に転送を初期化します。もし転送中なら、@code{EPRT} あるいは @code{PORT} コマンドと、`cmd' で指定したコマンドを送信し、接続を続けます。サーバがパッシブなら、@code{EPSV} あるいは @code{PASV} コマンドを送信して接続し、転送コマンドを開始します。どちらの場合も、接続のためのソケットを返します。

If optional `rest' is given, a @code{REST} command is sent to the server, passing
`rest' as an argument.  `rest' is usually a byte offset into the requested file,
telling the server to restart sending the file's bytes at the requested offset,
skipping over the initial bytes.  Note however that the @ref{4005,,transfercmd()}
method converts `rest' to a string with the `encoding' parameter specified
at initialization, but no check is performed on the string's contents.  If the
server does not recognize the @code{REST} command, an @ref{4003,,error_reply} exception
will be raised.  If this happens, simply call @ref{4005,,transfercmd()} without a
`rest' argument.
@end deffn

@geindex ntransfercmd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP ntransfercmd}@anchor{4009}
@deffn {メソッド} ntransfercmd (cmd, rest=None)

@ref{4005,,transfercmd()} と同様ですが、データと予想されるサイズとのタプルを返します。もしサイズが計算できないなら、サイズの代わりに @code{None} が返されます。 `cmd' と `rest' は @ref{4005,,transfercmd()} のものと同じです。
@end deffn

@geindex mlsd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP mlsd}@anchor{12d9}
@deffn {メソッド} mlsd (path='@w{'}, facts=[])

List a directory in a standardized format by using @code{MLSD} command
(
@geindex RFC; RFC 3659
RFC 3659@footnote{https://datatracker.ietf.org/doc/html/rfc3659.html}).  If `path' is omitted the current directory is assumed.
`facts' is a list of strings representing the type of information desired
(e.g. @code{["type", "size", "perm"]}).  Return a generator object yielding a
tuple of two elements for every file found in path.  First element is the
file name, the second one is a dictionary containing facts about the file
name.  Content of this dictionary might be limited by the `facts' argument
but server is not guaranteed to return all requested facts.


Added in version 3.3.

@end deffn

@geindex nlst() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP nlst}@anchor{12da}
@deffn {メソッド} nlst (argument[, ...])

@code{NLST} コマンドで返されるファイル名のリストを返します。省略可能な `argument' は、リストアップするディレクトリです（デフォルトではサーバのカレントディレクトリです）。 @code{NLST} コマンドに非標準である複数の引数を渡すことができます。

@cartouche
@quotation 注釈 
If your server supports the command, @ref{12d9,,mlsd()} offers a better API.
@end quotation
@end cartouche
@end deffn

@geindex dir() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP dir}@anchor{12db}
@deffn {メソッド} dir (argument[, ...])

Produce a directory listing as returned by the @code{LIST} command, printing it to
standard output.  The optional `argument' is a directory to list (default is the
current server directory).  Multiple arguments can be used to pass non-standard
options to the @code{LIST} command.  If the last argument is a function, it is used
as a `callback' function as for @ref{4006,,retrlines()}; the default prints to
@ref{ccd,,sys.stdout}.  This method returns @code{None}.

@cartouche
@quotation 注釈 
If your server supports the command, @ref{12d9,,mlsd()} offers a better API.
@end quotation
@end cartouche
@end deffn

@geindex rename() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP rename}@anchor{400a}
@deffn {メソッド} rename (fromname, toname)

サーバ上のファイルのファイル名 `fromname' を `toname' へ変更します。
@end deffn

@geindex delete() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP delete}@anchor{400b}
@deffn {メソッド} delete (filename)

サーバからファイル `filename' を削除します。成功したら応答のテキストを返し、そうでないならパーミッションエラーでは @ref{400c,,error_perm} を、他のエラーでは @ref{4003,,error_reply} を返します。
@end deffn

@geindex cwd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP cwd}@anchor{400d}
@deffn {メソッド} cwd (pathname)

サーバのカレントディレクトリを設定します。
@end deffn

@geindex mkd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP mkd}@anchor{400e}
@deffn {メソッド} mkd (pathname)

サーバ上に新たにディレクトリを作ります。
@end deffn

@geindex pwd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP pwd}@anchor{400f}
@deffn {メソッド} pwd ()

サーバ上のカレントディレクトリのパスを返します。
@end deffn

@geindex rmd() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP rmd}@anchor{4010}
@deffn {メソッド} rmd (dirname)

サーバ上のディレクトリ `dirname' を削除します。
@end deffn

@geindex size() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP size}@anchor{4011}
@deffn {メソッド} size (filename)

サーバ上のファイル `filename' のサイズを尋ねます。成功したらファイルサイズが整数で返され、そうでないなら @code{None} が返されます。 @code{SIZE} コマンドは標準化されていませんが、多くの普通のサーバで実装されていることに注意して下さい。
@end deffn

@geindex quit() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP quit}@anchor{4012}
@deffn {メソッド} quit ()

サーバに @code{QUIT} コマンドを送信し、接続を閉じます。これは接続を閉じるのに"礼儀正しい"方法ですが、 @code{QUIT} コマンドに反応してサーバの例外が発生するかもしれません。この例外は、 @ref{4013,,close()} メソッドによって @ref{af6,,FTP} インスタンスに対するその後のコマンド使用が不可になっていることを示しています（下記参照）。
@end deffn

@geindex close() (ftplib.FTP のメソッド)
@anchor{library/ftplib ftplib FTP close}@anchor{4013}
@deffn {メソッド} close ()

接続を一方的に閉じます。既に閉じた接続に対して実行すべきではありません（例えば @ref{4012,,quit()} を呼び出して成功した後など）。この実行の後、 @ref{af6,,FTP} インスタンスはもう使用すべきではありません（ @ref{4013,,close()} あるいは @ref{4012,,quit()} を呼び出した後で、 @ref{3fff,,login()} メソッドをもう一度実行して再び接続を開くことはできません）。
@end deffn
@end deffn

@node FTP_TLS オブジェクト,モジュール変数,FTP オブジェクト,リファレンス<7>
@anchor{library/ftplib ftp-tls-objects}@anchor{4014}
@subsubsection FTP_TLS オブジェクト


@geindex FTP_TLS (ftplib のクラス)
@anchor{library/ftplib ftplib FTP_TLS}@anchor{af7}
@deffn {クラス} ftplib.FTP_TLS (host='@w{'}, user='@w{'}, passwd='@w{'}, acct='@w{'}, *, context=None, timeout=None, source_address=None, encoding='utf-8')

An @ref{af6,,FTP} subclass which adds TLS support to FTP as described in
@geindex RFC; RFC 4217
RFC 4217@footnote{https://datatracker.ietf.org/doc/html/rfc4217.html}.
Connect to port 21 implicitly securing the FTP control connection
before authenticating.

@cartouche
@quotation 注釈 
The user must explicitly secure the data connection
by calling the @ref{4015,,prot_p()} method.
@end quotation
@end cartouche

@*パラメータ: 

@itemize *

@item 
@code{host} (@ref{169,,str}) -- The hostname to connect to.
If given, @code{connect(host)} is implicitly called by the constructor.

@item 
@code{user} (@ref{169,,str}) -- The username to log in with (default: @code{'anonymous'}).
If given, @code{login(host, passwd, acct)} is implicitly called
by the constructor.

@item 
@code{passwd} (@ref{169,,str}) -- The password to use when logging in.
If not given, and if `passwd' is the empty string or @code{"-"},
a password will be automatically generated.

@item 
@code{acct} (@ref{169,,str}) -- Account information to be used for the @code{ACCT} FTP command.
Few systems implement this.
See RFC-959@footnote{https://datatracker.ietf.org/doc/html/rfc959.html}
for more details.

@item 
@code{context} (@ref{357,,ssl.SSLContext}) -- An SSL context object which allows bundling SSL configuration options,
certificates and private keys into a single, potentially long-lived,
structure.
Please read @ref{3895,,セキュリティで考慮すべき点} for best practices.

@item 
@code{timeout} (@ref{196,,float}@code{ | }@code{None}) -- A timeout in seconds for blocking operations like @ref{3ffc,,connect()}
(default: the global default timeout setting).

@item 
@code{source_address} (@ref{614,,tuple}@code{ | }@code{None}) -- A 2-tuple @code{(host, port)} for the socket to bind to as its
source address before connecting.

@item 
@code{encoding} (@ref{169,,str}) -- The encoding for directories and filenames (default: @code{'utf-8'}).
@end itemize



Added in version 3.2.



バージョン 3.3 で変更: Added the `source_address' parameter.



バージョン 3.4 で変更: このクラスは @ref{39c4,,ssl.SSLContext.check_hostname} と `Server Name Indication' でホスト名のチェックをサポートしました。(@ref{39d6,,ssl.HAS_SNI} を参照してください)。



バージョン 3.9 で変更: If the `timeout' parameter is set to be zero, it will raise a
@ref{2ec,,ValueError} to prevent the creation of a non-blocking socket.
The `encoding' parameter was added, and the default was changed from
Latin-1 to UTF-8 to follow 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://datatracker.ietf.org/doc/html/rfc2640.html}.



バージョン 3.12 で変更: 非推奨の `keyfile' と `certfile' 引数を削除しました。


@ref{af7,,FTP_TLS} クラスを使ったサンプルセッションはこちらです:

@example
>>> ftps = FTP_TLS('ftp.pureftpd.org')
>>> ftps.login()
'230 Anonymous user logged in'
>>> ftps.prot_p()
'200 Data protection level set to "private"'
>>> ftps.nlst()
['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp']
@end example

@code{FTP_TLS} class inherits from @ref{af6,,FTP},
defining these additional methods and attributes:

@geindex ssl_version (ftplib.FTP_TLS の属性)
@anchor{library/ftplib ftplib FTP_TLS ssl_version}@anchor{4016}
@deffn {の属性} ssl_version

The SSL version to use (defaults to @ref{39c8,,ssl.PROTOCOL_SSLv23}).
@end deffn

@geindex auth() (ftplib.FTP_TLS のメソッド)
@anchor{library/ftplib ftplib FTP_TLS auth}@anchor{4017}
@deffn {メソッド} auth ()

@ref{4016,,ssl_version} 属性で指定されたものに従って、 TLS または SSL を使い、セキュアコントロール接続をセットアップします。


バージョン 3.4 で変更: The method now supports hostname check with
@ref{39c4,,ssl.SSLContext.check_hostname} and `Server Name Indication' (see
@ref{39d6,,ssl.HAS_SNI}).

@end deffn

@geindex ccc() (ftplib.FTP_TLS のメソッド)
@anchor{library/ftplib ftplib FTP_TLS ccc}@anchor{12d8}
@deffn {メソッド} ccc ()

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.


Added in version 3.3.

@end deffn

@geindex prot_p() (ftplib.FTP_TLS のメソッド)
@anchor{library/ftplib ftplib FTP_TLS prot_p}@anchor{4015}
@deffn {メソッド} prot_p ()

セキュアデータ接続をセットアップします。
@end deffn

@geindex prot_c() (ftplib.FTP_TLS のメソッド)
@anchor{library/ftplib ftplib FTP_TLS prot_c}@anchor{4018}
@deffn {メソッド} prot_c ()

平文データ接続をセットアップします。
@end deffn
@end deffn

@node モジュール変数,,FTP_TLS オブジェクト,リファレンス<7>
@anchor{library/ftplib module-variables}@anchor{4019}
@subsubsection モジュール変数


@geindex error_reply
@anchor{library/ftplib ftplib error_reply}@anchor{4003}
@deffn {例外} ftplib.error_reply

サーバから想定外の応答があったときに送出される例外。
@end deffn

@geindex error_temp
@anchor{library/ftplib ftplib error_temp}@anchor{401a}
@deffn {例外} ftplib.error_temp

一時的エラーを表すエラーコード(400--499の範囲の応答コード)を受け取った時に発生する例外。
@end deffn

@geindex error_perm
@anchor{library/ftplib ftplib error_perm}@anchor{400c}
@deffn {例外} ftplib.error_perm

永久エラーを表すエラーコード(500--599の範囲の応答コード)を受け取った時に発生する例外。
@end deffn

@geindex error_proto
@anchor{library/ftplib ftplib error_proto}@anchor{401b}
@deffn {例外} ftplib.error_proto

File Transfer Protocol の応答仕様に適合しない、すなわち1--5の数字で始まらない応答コードをサーバから受け取った時に発生する例外。
@end deffn

@geindex all_errors (ftplib モジュール)
@anchor{library/ftplib ftplib all_errors}@anchor{401c}
@deffn {データ} ftplib.all_errors

@ref{af6,,FTP} インスタンスのメソッド実行時、FTP接続で (プログラミングのエラーと考えられるメソッドの実行によって) 発生する全ての例外 (タプル形式)。この例外には以上の４つのエラーはもちろん、 @ref{2c0,,OSError} と @ref{14f1,,EOFError} も含まれます。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{9f,,netrc} モジュール

@code{.netrc} ファイルフォーマットのパーザ。 @code{.netrc} ファイルは、 FTPクライアントがユーザにプロンプトを出す前に、ユーザ認証情報をロードするのによく使われます。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node poplib --- POP3 プロトコルクライアント,imaplib --- IMAP4 プロトコルクライアント,ftplib --- FTP プロトコルクライアント,インターネットプロトコルとサポート
@anchor{library/poplib doc}@anchor{401d}@anchor{library/poplib module-poplib}@anchor{b1}@anchor{library/poplib poplib-pop3-protocol-client}@anchor{401e}@anchor{library/poplib translation-repo}@anchor{401f}
@subsection @code{poplib} --- POP3 プロトコルクライアント


@geindex module; poplib

@c revised by ESR, January 2000

`ソースコード:' Lib/poplib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/poplib.py}

@geindex POP3;プロトコル


__________________________________________________________________


このモジュールはクラス @ref{b1d,,POP3} を定義しています。
@ref{b1d,,POP3} はPOP3 サーバへの接続をカプセル化し、
@geindex RFC; RFC 1939
RFC 1939@footnote{https://datatracker.ietf.org/doc/html/rfc1939.html} で定義されているプロトコルを実装しています。
@ref{b1d,,POP3} クラスは 
@geindex RFC; RFC 1939
RFC 1939@footnote{https://datatracker.ietf.org/doc/html/rfc1939.html} の最小限のコマンドセットとオプションのコマンドセットをサポートしています。
既に確立されている接続で暗号化された通信を行うために、
@geindex RFC; RFC 2595
RFC 2595@footnote{https://datatracker.ietf.org/doc/html/rfc2595.html} で導入された @code{STLS} コマンドもサポートされています。

加えて、このモジュールはクラス @ref{b1e,,POP3_SSL} を提供しています。
@ref{b1e,,POP3_SSL}  は SSL を下層のプロトコルレイヤーとして使う POP3 サーバへの接続をサポートしています。

POP3についての注意事項は、それが広くサポートされているにもかかわらず、既に時代遅れだということです。幾つも実装されているPOP3サーバーの品質は、貧弱なものが多数を占めています。もし、お使いのメールサーバーがIMAPをサポートしているなら、 @ref{aff,,imaplib.IMAP4} クラスが使えます。 IMAPサーバーは、より良く実装されている傾向があります。

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

The @code{poplib} module provides two classes:

@geindex POP3 (poplib のクラス)
@anchor{library/poplib poplib POP3}@anchor{b1d}
@deffn {クラス} poplib.POP3 (host, port=POP3_PORT[, timeout])

このクラスが、実際にPOP3プロトコルを実装します。インスタンスが初期化されるときに、コネクションが作成されます。 `port' が省略されると、POP3標準のポート(110)が使われます。オプションの `timeout' 引数は、接続時のタイムアウト時間を秒数で指定します (指定されなかった場合は、グローバルのデフォルトタイムアウト設定が利用されます)。

引数 @code{self}, @code{host}, @code{port} 付きで @ref{1c6e,,監査イベント} @code{poplib.connect} を送出します。

全てのコマンドは引数 @code{self} と @code{line} を指定して @ref{1c6e,,auditing event} @code{poplib.putline} を送出します。ここで @code{line} はリモートホストに送信されるバイト数です。


バージョン 3.9 で変更: `timeout' パラメータが0に設定されている場合、非ブロッキングソケットの作成を防ぐために @ref{2ec,,ValueError} を送出します。

@end deffn

@geindex POP3_SSL (poplib のクラス)
@anchor{library/poplib poplib POP3_SSL}@anchor{b1e}
@deffn {クラス} poplib.POP3_SSL (host, port=POP3_SSL_PORT, *, timeout=None, context=None)

@ref{b1d,,POP3} クラスのサブクラスで、SSL でカプセル化されたソケットによる POP サーバへの接続を提供します。 `port' が指定されていない場合、 POP3-over-SSL 標準の 995 番ポートが使われます。`timeout' については @ref{b1d,,POP3} クラスのコンストラクタの引数と同じです。 `context' は SSL の設定、証明書、秘密鍵を一つの (POP3_SSL オブジェクトよりも長く存在し続けうる) 構造にまとめた @ref{357,,ssl.SSLContext} オブジェクトで、省略可能です。ベストプラクティスについては @ref{3895,,セキュリティで考慮すべき点} を参照してください。

引数 @code{self}, @code{host}, @code{port} 付きで @ref{1c6e,,監査イベント} @code{poplib.connect} を送出します。

全てのコマンドは引数 @code{self} と @code{line} を指定して @ref{1c6e,,auditing event} @code{poplib.putline} を送出します。ここで @code{line} はリモートホストに送信されるバイト数です。


バージョン 3.2 で変更: `context' 引数が追加されました。



バージョン 3.4 で変更: このクラスは @ref{39c4,,ssl.SSLContext.check_hostname} と `Server Name Indication' でホスト名のチェックをサポートしました。(@ref{39d6,,ssl.HAS_SNI} を参照してください)。



バージョン 3.9 で変更: `timeout' パラメータが0に設定されている場合、非ブロッキングソケットの作成を防ぐために @ref{2ec,,ValueError} を送出します。



バージョン 3.12 で変更: 非推奨の `keyfile' と `certfile' 引数を削除しました。

@end deffn

One exception is defined as an attribute of the @code{poplib} module:

@geindex error_proto
@anchor{library/poplib poplib error_proto}@anchor{13b4}
@deffn {例外} poplib.error_proto

このモジュール内で起こったあらゆるエラーで送出される例外です (@ref{d1,,socket} モジュールからのエラーは捕捉されません)。例外の理由は文字列としてコンストラクタに渡されます。
@end deffn


@subsubheading 参考



@table @asis

@item モジュール @ref{78,,imaplib}

標準 Python IMAP モジュールです。

@item Frequently Asked Questions About Fetchmail@footnote{http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html}

POP/IMAPクライアント @code{fetchmail} のFAQ。POPプロトコルをベースにしたアプリケーションを書くときに有用な、POP3サーバの種類や RFCへの適合度といった情報を収集しています。
@end table


@menu
* POP3 オブジェクト:: 
* POP3 の例:: 

@end menu

@node POP3 オブジェクト,POP3 の例,,poplib --- POP3 プロトコルクライアント
@anchor{library/poplib id1}@anchor{4020}@anchor{library/poplib pop3-objects}@anchor{4021}
@subsubsection POP3 オブジェクト


POP3コマンドはすべて、それと同じ名前のメソッドとして小文字で表現されます。そしてそのほとんどは、サーバからのレスポンスとなるテキストを返します。

@ref{b1d,,POP3} クラスのインスタンスは以下のメソッドを持ちます:

@geindex set_debuglevel() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 set_debuglevel}@anchor{4022}
@deffn {メソッド} POP3.set_debuglevel (level)

インスタンスのデバッグレベルを設定します。この設定によってデバッグ時に出力される量を調節します。デフォルトは @code{0} で、何も出力されません。 @code{1} なら、一般的に１つのコマンドあたり１行の適当な量のデバッグ出力を行います。 @code{2} 以上なら、コントロール接続で受信した各行を出力して、最大のデバッグ出力をします。
@end deffn

@geindex getwelcome() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 getwelcome}@anchor{4023}
@deffn {メソッド} POP3.getwelcome ()

POP3サーバーから送られるグリーティングメッセージを返します。
@end deffn

@geindex capa() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 capa}@anchor{117e}
@deffn {メソッド} POP3.capa ()

@geindex RFC; RFC 2449
RFC 2449@footnote{https://datatracker.ietf.org/doc/html/rfc2449.html} で規定されている機能についてサーバに問い合わせます。@code{@{'name': ['param'...]@}} という形の辞書を返します。


Added in version 3.4.

@end deffn

@geindex user() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 user}@anchor{4024}
@deffn {メソッド} POP3.user (username)

userコマンドを送出します。応答はパスワード要求を表示します。
@end deffn

@geindex pass_() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 pass_}@anchor{4025}
@deffn {メソッド} POP3.pass_ (password)

パスワードを送出します。応答は、メッセージ数とメールボックスのサイズを含みます。注意：サーバー上のメールボックスは @ref{13b3,,quit()} が呼ばれるまでロックされます。
@end deffn

@geindex apop() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 apop}@anchor{4026}
@deffn {メソッド} POP3.apop (user, secret)

POP3サーバーにログオンするのに、よりセキュアなAPOP認証を使用します。
@end deffn

@geindex rpop() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 rpop}@anchor{4027}
@deffn {メソッド} POP3.rpop (user)

POP3サーバーにログオンするのに、（UNIXのr-コマンドと同様の）RPOP認証を使用します。
@end deffn

@geindex stat() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 stat}@anchor{4028}
@deffn {メソッド} POP3.stat ()

メールボックスの状態を得ます。結果は2つのintegerからなるタプルとなります。 @code{(message count, mailbox size)}.
@end deffn

@geindex list() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 list}@anchor{4029}
@deffn {メソッド} POP3.list ([which])

メッセージのリストを要求します。結果は @code{(response, ['mesg_num octets', ...], octets)} という形式で表されます。 `which' が与えられると、それによりメッセージを指定します。
@end deffn

@geindex retr() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 retr}@anchor{402a}
@deffn {メソッド} POP3.retr (which)

`which' 番のメッセージ全体を取り出し、そのメッセージに既読フラグを立てます。結果は @code{(response, ['line', ...], octets)} という形式で表されます。
@end deffn

@geindex dele() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 dele}@anchor{402b}
@deffn {メソッド} POP3.dele (which)

`which' 番のメッセージに削除のためのフラグを立てます。ほとんどのサーバで、QUITコマンドが実行されるまでは実際の削除は行われません（もっとも良く知られた例外は Eudora QPOPで、その配送メカニズムはRFCに違反しており、どんな切断状況でも削除操作を未解決にしています）。
@end deffn

@geindex rset() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 rset}@anchor{402c}
@deffn {メソッド} POP3.rset ()

メールボックスの削除マークすべてを取り消します。
@end deffn

@geindex noop() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 noop}@anchor{402d}
@deffn {メソッド} POP3.noop ()

何もしません。接続保持のために使われます。
@end deffn

@geindex quit() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 quit}@anchor{13b3}
@deffn {メソッド} POP3.quit ()

サインオフ: 変更をコミットし、メールボックスをアンロックして、接続を破棄します。
@end deffn

@geindex top() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 top}@anchor{402e}
@deffn {メソッド} POP3.top (which, howmuch)

メッセージヘッダと `howmuch' で指定した行数のメッセージを、 `which' で指定したメッセージ分取り出します。結果は以下のような形式となります。 @code{(response, ['line', ...], octets)}.

このメソッドはPOP3のTOPコマンドを利用し、RETRコマンドのように、メッセージに既読フラグをセットしません。残念ながら、TOPコマンドはRFCでは貧弱な仕様しか定義されておらず、しばしばノーブランドのサーバーでは（その仕様が）守られていません。このメソッドを信用してしまう前に、実際に使用するPOPサーバーでテストをしてください。
@end deffn

@geindex uidl() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 uidl}@anchor{402f}
@deffn {メソッド} POP3.uidl (which=None)

（ユニークIDによる）メッセージダイジェストのリストを返します。 `which' が設定されている場合、結果はユニークIDを含みます。それは @code{'response mesgnum uid} という形式のメッセージ、または @code{(response, ['mesgnum uid', ...], octets)} という形式のリストとなります。
@end deffn

@geindex utf8() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 utf8}@anchor{1049}
@deffn {メソッド} POP3.utf8 ()

UTF-8 モードへの切り替えを試行します。成功した場合はサーバの応答を返し、失敗した場合は @ref{13b4,,error_proto} を送出します。
@geindex RFC; RFC 6856
RFC 6856@footnote{https://datatracker.ietf.org/doc/html/rfc6856.html} で規定されています。


Added in version 3.5.

@end deffn

@geindex stls() (poplib.POP3 のメソッド)
@anchor{library/poplib poplib POP3 stls}@anchor{117f}
@deffn {メソッド} POP3.stls (context=None)

アクティブな接続にて 
@geindex RFC; RFC 2595
RFC 2595@footnote{https://datatracker.ietf.org/doc/html/rfc2595.html} で定められた方法で TLS セッションを開始します。TLS セッションはユーザ認証を行う前に開始する必要があります。

`context' は SSL の設定、証明書、秘密鍵を一つの (POP3 オブジェクトよりも長く存在し続けうる) 構造にまとめた @ref{357,,ssl.SSLContext} オブジェクトです。ベストプラクティスについては @ref{3895,,セキュリティで考慮すべき点} を参照してください。

このメソッドは @ref{39c4,,ssl.SSLContext.check_hostname} と `Server Name Indication' でホスト名のチェックをサポートしました。(@ref{39d6,,ssl.HAS_SNI} を参照してください)。


Added in version 3.4.

@end deffn

@ref{b1e,,POP3_SSL} クラスのインスタンスは追加のメソッドを持ちません。このサブクラスのインターフェイスは親クラスと同じです。

@node POP3 の例,,POP3 オブジェクト,poplib --- POP3 プロトコルクライアント
@anchor{library/poplib id2}@anchor{4030}@anchor{library/poplib pop3-example}@anchor{4031}
@subsubsection POP3 の例


以下にメールボックスを開き、全てのメッセージを取得して印刷する最小の (エラーチェックをしない) 使用例を示します:

@example
import getpass, poplib

M = poplib.POP3('localhost')
M.user(getpass.getuser())
M.pass_(getpass.getpass())
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print(j)
@end example

モジュールの末尾に、より拡張的な使用例が収められたテストセクションがあります。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node imaplib --- IMAP4 プロトコルクライアント,smtplib --- SMTP プロトコルクライアント,poplib --- POP3 プロトコルクライアント,インターネットプロトコルとサポート
@anchor{library/imaplib doc}@anchor{4032}@anchor{library/imaplib imaplib-imap4-protocol-client}@anchor{4033}@anchor{library/imaplib module-imaplib}@anchor{78}@anchor{library/imaplib translation-repo}@anchor{4034}
@subsection @code{imaplib} --- IMAP4 プロトコルクライアント


@geindex module; imaplib

@c revised by ESR, January 2000

@c changes for IMAP4_SSL by Tino Lange <Tino.Lange@isg.de>, March 2002

@c changes for IMAP4_stream by Piers Lauder <piers@communitysolutions.com.au>,
@c November 2002

@c changes for IMAP4 IDLE by Forest <forestix@nom.one>, August 2024

`ソースコード:' Lib/imaplib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/imaplib.py}

@geindex IMAP4;プロトコル
@geindex IMAP4_SSL;プロトコル
@geindex IMAP4_stream;プロトコル


__________________________________________________________________


このモジュールでは三つのクラス、 @ref{aff,,IMAP4}, @ref{b00,,IMAP4_SSL} と @ref{b02,,IMAP4_stream} を定義します。これらのクラスは IMAP4 サーバへの接続をカプセル化し、 
@geindex RFC; RFC 2060
RFC 2060@footnote{https://datatracker.ietf.org/doc/html/rfc2060.html} に定義されている IMAP4rev1 クライアントプロトコルの大規模なサブセットを実装しています。このクラスは IMAP4 (
@geindex RFC; RFC 1730
RFC 1730@footnote{https://datatracker.ietf.org/doc/html/rfc1730.html}) 準拠のサーバと後方互換性がありますが、 @code{STATUS} コマンドは IMAP4 ではサポートされていないので注意してください。

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

Three classes are provided by the @code{imaplib} module, @ref{aff,,IMAP4} is the
base class:

@geindex IMAP4 (imaplib のクラス)
@anchor{library/imaplib imaplib IMAP4}@anchor{aff}
@deffn {クラス} imaplib.IMAP4 (host='@w{'}, port=IMAP4_PORT, timeout=None)

This class implements the actual IMAP4 protocol.  The connection is created and
protocol version (IMAP4 or IMAP4rev1) is determined when the instance is
initialized. If `host' is not specified, @code{'@w{'}} (the local host) is used. If
`port' is omitted, the standard IMAP4 port (143) is used. The optional `timeout'
parameter specifies a timeout in seconds for the connection attempt.
If timeout is not given or is @code{None}, the global default socket timeout is used.

The @ref{aff,,IMAP4} class supports the @ref{186,,with} statement.  When used
like this, the IMAP4 @code{LOGOUT} command is issued automatically when the
@code{with} statement exits.  E.g.:

@example
>>> from imaplib import IMAP4
>>> with IMAP4("domain.org") as M:
...     M.noop()
...
('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])
@end example


バージョン 3.5 で変更: @ref{186,,with} 構文のサポートが追加されました。



バージョン 3.9 で変更: オプションの `timeout' 引数が追加されました。

@end deffn

例外は @ref{aff,,IMAP4} クラスの属性として定義されています:

@geindex IMAP4.error
@anchor{library/imaplib imaplib IMAP4 error}@anchor{17f7}
@deffn {例外} IMAP4.error

何らかのエラー発生の際に送出される例外です。例外の理由は文字列としてコンストラクタに渡されます。
@end deffn

@geindex IMAP4.abort
@anchor{library/imaplib imaplib IMAP4 abort}@anchor{4035}
@deffn {例外} IMAP4.abort

IMAP4 サーバのエラーが生じると、この例外が送出されます。この例外は @ref{17f7,,IMAP4.error} のサブクラスです。通常、インスタンスを閉じ、新たなインスタンスを再び生成することで、この例外から復旧できます。
@end deffn

@geindex IMAP4.readonly
@anchor{library/imaplib imaplib IMAP4 readonly}@anchor{4036}
@deffn {例外} IMAP4.readonly

この例外は書き込み可能なメールボックスの状態がサーバによって変更された際に送出されます。この例外は @ref{17f7,,IMAP4.error} のサブクラスです。他の何らかのクライアントが現在書き込み権限を獲得しており、メールボックスを開きなおして書き込み権限を再獲得する必要があります。
@end deffn

このモジュールではもう一つ、安全 (secure) な接続を使ったサブクラスがあります:

@geindex IMAP4_SSL (imaplib のクラス)
@anchor{library/imaplib imaplib IMAP4_SSL}@anchor{b00}
@deffn {クラス} imaplib.IMAP4_SSL (host='@w{'}, port=IMAP4_SSL_PORT, *, ssl_context=None, timeout=None)

This is a subclass derived from @ref{aff,,IMAP4} that connects over an SSL
encrypted socket (to use this class you need a socket module that was compiled
with SSL support).  If `host' is not specified, @code{'@w{'}} (the local host) is used.
If `port' is omitted, the standard IMAP4-over-SSL port (993) is used.
`ssl_context' is a @ref{357,,ssl.SSLContext} object which allows bundling
SSL configuration options, certificates and private keys into a single
(potentially long-lived) structure.  Please read @ref{3895,,セキュリティで考慮すべき点} for
best practices.

The optional `timeout' parameter specifies a timeout in seconds for the
connection attempt. If timeout is not given or is @code{None}, the global default
socket timeout is used.


バージョン 3.3 で変更: `ssl_context' 引数が追加されました。



バージョン 3.4 で変更: このクラスは @ref{39c4,,ssl.SSLContext.check_hostname} と `Server Name Indication' でホスト名のチェックをサポートしました。(@ref{39d6,,ssl.HAS_SNI} を参照してください)。



バージョン 3.9 で変更: オプションの `timeout' 引数が追加されました。



バージョン 3.12 で変更: 非推奨の `keyfile' と `certfile' 引数を削除しました。

@end deffn

さらにもう一つのサブクラスは、子プロセスで確立した接続を使用する場合に使用します:

@geindex IMAP4_stream (imaplib のクラス)
@anchor{library/imaplib imaplib IMAP4_stream}@anchor{b02}
@deffn {クラス} imaplib.IMAP4_stream (command)

@ref{aff,,IMAP4} から派生したサブクラスで、 `command' を @code{subprocess.Popen()} に渡して作成される @code{stdin/stdout} ディスクリプタと接続します。
@end deffn

以下のユーティリティ関数が定義されています:

@geindex Internaldate2tuple() (imaplib モジュール)
@anchor{library/imaplib imaplib Internaldate2tuple}@anchor{4037}
@deffn {の関数} imaplib.Internaldate2tuple (datestr)

IMAP4 の @code{INTERNALDATE} 文字列を解析してそれに相当するローカルタイムを返します。戻り値は @ref{ee6,,time.struct_time} のタプルか、文字列のフォーマットが不正な場合は @code{None} です。
@end deffn

@geindex Int2AP() (imaplib モジュール)
@anchor{library/imaplib imaplib Int2AP}@anchor{4038}
@deffn {の関数} imaplib.Int2AP (num)

整数を [@code{A} .. @code{P}] からなる文字集合を用いて表現した bytes に変換します。
@end deffn

@geindex ParseFlags() (imaplib モジュール)
@anchor{library/imaplib imaplib ParseFlags}@anchor{4039}
@deffn {の関数} imaplib.ParseFlags (flagstr)

IMAP4 @code{FLAGS} 応答を個々のフラグからなるタプルに変換します。
@end deffn

@geindex Time2Internaldate() (imaplib モジュール)
@anchor{library/imaplib imaplib Time2Internaldate}@anchor{403a}
@deffn {の関数} imaplib.Time2Internaldate (date_time)

Convert `date_time' to an IMAP4 @code{INTERNALDATE} representation.
The return value is a string in the form: @code{"DD-Mmm-YYYY HH:MM:SS
+HHMM"} (including double-quotes).  The `date_time' argument can
be a number (int or float) representing seconds since epoch (as
returned by @ref{55d,,time.time()}), a 9-tuple representing local time
an instance of @ref{ee6,,time.struct_time} (as returned by
@ref{1712,,time.localtime()}), an aware instance of
@ref{4e2,,datetime.datetime}, or a double-quoted string.  In the last
case, it is assumed to already be in the correct format.
@end deffn

IMAP4 メッセージ番号は、メールボックスに対する変更が行われた後には変化します; 特に、@code{EXPUNGE} 命令はメッセージの削除を行いますが、残ったメッセージには再度番号を振りなおします。従って、メッセージ番号ではなく、UID 命令を使い、その UID を利用するよう強く勧めます。

モジュールの末尾に、より拡張的な使用例が収められたテストセクションがあります。


@subsubheading 参考


Documents describing the protocol, sources for servers
implementing it, by the University of Washington's IMAP Information Center
can all be found at (`Source Code') @indicateurl{https://github.com/uw-imap/imap} (`Not Maintained').


@menu
* IMAP4 オブジェクト:: 
* IMAP4 の使用例:: 

@end menu

@node IMAP4 オブジェクト,IMAP4 の使用例,,imaplib --- IMAP4 プロトコルクライアント
@anchor{library/imaplib id1}@anchor{403b}@anchor{library/imaplib imap4-objects}@anchor{403c}
@subsubsection IMAP4 オブジェクト


All IMAP4rev1 commands are represented by methods of the same name, either
uppercase or lowercase.

命令に対する引数は全て文字列に変換されます。例外は @code{AUTHENTICATE} の引数と @code{APPEND} の最後の引数で、これは IMAP4 リテラルとして渡されます。必要に応じて (IMAP4 プロトコルが感知対象としている文字が文字列に入っており、かつ丸括弧か二重引用符で囲われていなかった場合) 文字列はクオートされます。しかし、@code{LOGIN} 命令の  `password' 引数は常にクオートされます。文字列がクオートされないようにしたい (例えば @code{STORE} 命令の `flags' 引数) 場合、文字列を丸括弧で囲んでください (例: @code{r'(\Deleted)'})。

Most commands return a tuple: @code{(type, [data, ...])} where `type' is usually
@code{'OK'} or @code{'NO'}, and `data' is either the text from the command response,
or mandated results from the command. Each `data' is either a @code{bytes}, or a
tuple. If a tuple, then the first part is the header of the response, and the
second part contains the data (ie: 'literal' value).

以下のコマンドにおける `message_set' オプションは、操作の対象となるひとつあるいは複数のメッセージを指す文字列です。単一のメッセージ番号 (@code{'1'}) かメッセージ番号の範囲 (@code{'2:4'})、あるいは連続していないメッセージをカンマでつなげたもの (@code{'1:3,6:9'}) となります。範囲指定でアスタリスクを使用すると、上限を無限とすることができます (@code{'3:*'})。

@ref{aff,,IMAP4} のインスタンスは以下のメソッドを持っています:

@geindex append() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 append}@anchor{403d}
@deffn {メソッド} IMAP4.append (mailbox, flags, date_time, message)

指定された名前のメールボックスに `message' を追加します。
@end deffn

@geindex authenticate() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 authenticate}@anchor{403e}
@deffn {メソッド} IMAP4.authenticate (mechanism, authobject)

認証命令です --- 応答の処理が必要です。

`mechanism' は利用する認証メカニズムを与えます。認証メカニズムはインスタンス変数 @code{capabilities} の中に @code{AUTH=mechanism} という形式で現れる必要があります。

`authobject' は呼び出し可能なオブジェクトである必要があります:

@example
data = authobject(response)
@end example

It will be called to process server continuation responses; the `response'
argument it is passed will be @code{bytes}.  It should return @code{bytes} `data'
that will be base64 encoded and sent to the server.  It should return
@code{None} if the client abort response @code{*} should be sent instead.


バージョン 3.5 で変更: string usernames and passwords are now encoded to @code{utf-8} instead of
being limited to ASCII.

@end deffn

@geindex check() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 check}@anchor{403f}
@deffn {メソッド} IMAP4.check ()

サーバ上のメールボックスにチェックポイントを設定します。
@end deffn

@geindex close() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 close}@anchor{b04}
@deffn {メソッド} IMAP4.close ()

現在選択されているメールボックスを閉じます。削除されたメッセージは書き込み可能メールボックスから除去されます。@code{LOGOUT} 前に実行することを勧めます。
@end deffn

@geindex copy() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 copy}@anchor{4040}
@deffn {メソッド} IMAP4.copy (message_set, new_mailbox)

`message_set' で指定したメッセージ群を `new_mailbox' の末尾にコピーします。
@end deffn

@geindex create() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 create}@anchor{4041}
@deffn {メソッド} IMAP4.create (mailbox)

`mailbox' と名づけられた新たなメールボックスを生成します。
@end deffn

@geindex delete() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 delete}@anchor{4042}
@deffn {メソッド} IMAP4.delete (mailbox)

`mailbox' と名づけられた古いメールボックスを削除します。
@end deffn

@geindex deleteacl() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 deleteacl}@anchor{4043}
@deffn {メソッド} IMAP4.deleteacl (mailbox, who)

mailbox における who についてのACLを削除(権限を削除)します。
@end deffn

@geindex enable() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 enable}@anchor{100e}
@deffn {メソッド} IMAP4.enable (capability)

Enable `capability' (see 
@geindex RFC; RFC 5161
RFC 5161@footnote{https://datatracker.ietf.org/doc/html/rfc5161.html}).  Most capabilities do not need to be
enabled.  Currently only the @code{UTF8=ACCEPT} capability is supported
(see 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://datatracker.ietf.org/doc/html/rfc6855.html}).


Added in version 3.5: The @ref{100e,,enable()} method itself, and 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://datatracker.ietf.org/doc/html/rfc6855.html} support.

@end deffn

@geindex expunge() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 expunge}@anchor{4044}
@deffn {メソッド} IMAP4.expunge ()

選択されたメールボックスから削除された要素を永久に除去します。各々の削除されたメッセージに対して、@code{EXPUNGE} 応答を生成します。返されるデータには @code{EXPUNGE} メッセージ番号を受信した順番に並べたリストが入っています。
@end deffn

@geindex fetch() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 fetch}@anchor{4045}
@deffn {メソッド} IMAP4.fetch (message_set, message_parts)

メッセージ (の一部) を取りよせます。`message_parts' はメッセージパートの名前を表す文字列を丸括弧で囲ったもので、例えば: @code{"(UID BODY[TEXT])"} のようになります。返されるデータはメッセージパートのエンベロープ情報とデータからなるタプルです。
@end deffn

@geindex getacl() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 getacl}@anchor{4046}
@deffn {メソッド} IMAP4.getacl (mailbox)

`mailbox' に対する @code{ACL} を取得します。このメソッドは非標準ですが、@code{Cyrus} サーバでサポートされています。
@end deffn

@geindex getannotation() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 getannotation}@anchor{4047}
@deffn {メソッド} IMAP4.getannotation (mailbox, entry, attribute)

`mailbox' に対する @code{ANNOTATION} を取得します。このメソッドは非標準ですが、@code{Cyrus} サーバでサポートされています。
@end deffn

@geindex getquota() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 getquota}@anchor{4048}
@deffn {メソッド} IMAP4.getquota (root)

@code{quota} `root' により、リソース使用状況と制限値を取得します。このメソッドは 
@geindex RFC; RFC 2087
RFC 2087@footnote{https://datatracker.ietf.org/doc/html/rfc2087.html} で定義されている IMAP4 QUOTA 拡張の一部です。
@end deffn

@geindex getquotaroot() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 getquotaroot}@anchor{4049}
@deffn {メソッド} IMAP4.getquotaroot (mailbox)

`mailbox' に対して @code{quota} `root' を実行した結果のリストを取得します。このメソッドは 
@geindex RFC; RFC 2087
RFC 2087@footnote{https://datatracker.ietf.org/doc/html/rfc2087.html} で定義されている IMAP4 QUOTA 拡張の一部です。
@end deffn

@geindex idle() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 idle}@anchor{22d}
@deffn {メソッド} IMAP4.idle (duration=None)

Return an @code{Idler}: an iterable context manager implementing the
IMAP4 @code{IDLE} command as defined in 
@geindex RFC; RFC 2177
RFC 2177@footnote{https://datatracker.ietf.org/doc/html/rfc2177.html}.

The returned object sends the @code{IDLE} command when activated by the
@ref{186,,with} statement, produces IMAP untagged responses via the
@ref{4c8,,iterator} protocol, and sends @code{DONE} upon context exit.

All untagged responses that arrive after sending the @code{IDLE} command
(including any that arrive before the server acknowledges the command) will
be available via iteration. Any leftover responses (those not iterated in
the @ref{186,,with} context) can be retrieved in the usual way after
@code{IDLE} ends, using @ref{404a,,IMAP4.response()}.

Responses are represented as @code{(type, [data, ...])} tuples, as described
in @ref{403c,,IMAP4 Objects}.

The `duration' argument sets a maximum duration (in seconds) to keep idling,
after which any ongoing iteration will stop. It can be an @ref{19b,,int} or
@ref{196,,float}, or @code{None} for no time limit.
Callers wishing to avoid inactivity timeouts on servers that impose them
should keep this at most 29 minutes (1740 seconds).
Requires a socket connection; `duration' must be @code{None} on
@ref{b02,,IMAP4_stream} connections.

@example
>>> with M.idle(duration=29 * 60) as idler:
...     for typ, data in idler:
...         print(typ, data)
...
EXISTS [b'1']
RECENT [b'1']
@end example

@geindex burst() (imaplib.IMAP4.Idler のメソッド)
@anchor{library/imaplib imaplib IMAP4 Idler burst}@anchor{404b}
@deffn {メソッド} Idler.burst (interval=0.1)

Yield a burst of responses no more than `interval' seconds apart
(expressed as an @ref{19b,,int} or @ref{196,,float}).

This @ref{126c,,generator} is an alternative to iterating one response at a
time, intended to aid in efficient batch processing. It retrieves the
next response along with any immediately available subsequent responses.
(For example, a rapid series of @code{EXPUNGE} responses after a bulk
delete.)

Requires a socket connection; does not work on @ref{b02,,IMAP4_stream}
connections.

@example
>>> with M.idle() as idler:
...     # get a response and any others following by < 0.1 seconds
...     batch = list(idler.burst())
...     print(f'processing @{len(batch)@} responses...')
...     print(batch)
...
processing 3 responses...
[('EXPUNGE', [b'2']), ('EXPUNGE', [b'1']), ('RECENT', [b'0'])]
@end example

@cartouche
@quotation Tip 
The @code{IDLE} context's maximum duration, as passed to
@ref{22d,,IMAP4.idle()}, is respected when waiting for the first response
in a burst. Therefore, an expired @code{Idler} will cause this
generator to return immediately without producing anything. Callers
should consider this if using it in a loop.
@end quotation
@end cartouche
@end deffn

@cartouche
@quotation 注釈 
The iterator returned by @ref{22d,,IMAP4.idle()} is usable only within a
@ref{186,,with} statement. Before or after that context, unsolicited
responses are collected internally whenever a command finishes, and can
be retrieved with @ref{404a,,IMAP4.response()}.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
The @code{Idler} class name and structure are internal interfaces,
subject to change. Calling code can rely on its context management,
iteration, and public method to remain stable, but should not subclass,
instantiate, compare, or otherwise directly reference the class.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@geindex list() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 list}@anchor{404c}
@deffn {メソッド} IMAP4.list ([directory[, pattern]])

`pattern' にマッチする `directory' メールボックス名を列挙します。`directory' の標準の設定値は最上レベルのメールフォルダで、`pattern' は標準の設定では全てにマッチします。返されるデータには @code{LIST} 応答のリストが入っています。
@end deffn

@geindex login() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 login}@anchor{404d}
@deffn {メソッド} IMAP4.login (user, password)

平文パスワードを使ってクライアントを照合します。`password' はクオートされます。
@end deffn

@geindex login_cram_md5() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 login_cram_md5}@anchor{17f6}
@deffn {メソッド} IMAP4.login_cram_md5 (user, password)

パスワードの保護のため、クライアント認証時に @code{CRAM-MD5} だけを使用します。これは、@code{CAPABILITY} レスポンスに @code{AUTH=CRAM-MD5} が含まれる場合のみ有効です。


バージョン 3.14 で変更: An @ref{17f7,,IMAP4.error} is raised if MD5 support is not available.

@end deffn

@geindex logout() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 logout}@anchor{c84}
@deffn {メソッド} IMAP4.logout ()

サーバへの接続を遮断します。サーバからの @code{BYE} 応答を返します。


バージョン 3.8 で変更: The method no longer ignores silently arbitrary exceptions.

@end deffn

@geindex lsub() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 lsub}@anchor{404e}
@deffn {メソッド} IMAP4.lsub (directory='""', pattern='*')

購読しているメールボックス名のうち、ディレクトリ内でパターンにマッチするものを列挙します。`directory' の標準の設定値は最上レベルのメールフォルダで、`pattern' は標準の設定では全てにマッチします。返されるデータには返されるデータはメッセージパートエンベロープ情報とデータからなるタプルです。
@end deffn

@geindex myrights() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 myrights}@anchor{404f}
@deffn {メソッド} IMAP4.myrights (mailbox)

mailboxにおける自分のACLを返します (すなわち自分がmailboxで持っている権限を返します)。
@end deffn

@geindex namespace() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 namespace}@anchor{4050}
@deffn {メソッド} IMAP4.namespace ()

@geindex RFC; RFC 2342
RFC 2342@footnote{https://datatracker.ietf.org/doc/html/rfc2342.html} で定義されるIMAP名前空間を返します。
@end deffn

@geindex noop() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 noop}@anchor{4051}
@deffn {メソッド} IMAP4.noop ()

サーバに @code{NOOP} を送信します。
@end deffn

@geindex open() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 open}@anchor{b01}
@deffn {メソッド} IMAP4.open (host, port, timeout=None)

Opens socket to `port' at `host'. The optional `timeout' parameter
specifies a timeout in seconds for the connection attempt.
If timeout is not given or is @code{None}, the global default socket timeout
is used. Also note that if the `timeout' parameter is set to be zero,
it will raise a @ref{2ec,,ValueError} to reject creating a non-blocking socket.
This method is implicitly called by the @ref{aff,,IMAP4} constructor.
The connection objects established by this method will be used in
the @ref{4052,,IMAP4.read()}, @ref{4053,,IMAP4.readline()}, @ref{4054,,IMAP4.send()},
and @ref{4055,,IMAP4.shutdown()} methods. You may override this method.

引数 @code{self}, @code{host}, @code{port} を指定して @ref{1c6e,,監査イベント} @code{imaplib.open} を送出します。


バージョン 3.9 で変更: `timeout' 引数が追加されました。

@end deffn

@geindex partial() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 partial}@anchor{4056}
@deffn {メソッド} IMAP4.partial (message_num, message_part, start, length)

メッセージの後略された部分を取り寄せます。返されるデータはメッセージパートエンベロープ情報とデータからなるタプルです。
@end deffn

@geindex proxyauth() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 proxyauth}@anchor{4057}
@deffn {メソッド} IMAP4.proxyauth (user)

`user' として認証されたものとします。認証された管理者がユーザの代理としてメールボックスにアクセスする際に使用します。
@end deffn

@geindex read() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 read}@anchor{4052}
@deffn {メソッド} IMAP4.read (size)

遠隔のサーバから `size' バイト読み出します。このメソッドはオーバライドすることができます。
@end deffn

@geindex readline() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 readline}@anchor{4053}
@deffn {メソッド} IMAP4.readline ()

遠隔のサーバから一行読み出します。このメソッドはオーバライドすることができます。
@end deffn

@geindex recent() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 recent}@anchor{4058}
@deffn {メソッド} IMAP4.recent ()

サーバに更新を促します。新たなメッセージがない場合応答は @code{None} になり、そうでない場合 @code{RECENT} 応答の値になります。
@end deffn

@geindex rename() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 rename}@anchor{4059}
@deffn {メソッド} IMAP4.rename (oldmailbox, newmailbox)

`oldmailbox' という名前のメールボックスを `newmailbox' に名称変更します。
@end deffn

@geindex response() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 response}@anchor{404a}
@deffn {メソッド} IMAP4.response (code)

応答 `code' を受信していれば、そのデータを返し、そうでなければ @code{None} を返します。通常の形式 (usual type) ではなく指定したコードを返します。
@end deffn

@geindex search() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 search}@anchor{405a}
@deffn {メソッド} IMAP4.search (charset, criterion[, ...])

Search mailbox for matching messages.  `charset' may be @code{None}, in which case
no @code{CHARSET} will be specified in the request to the server.  The IMAP
protocol requires that at least one criterion be specified; an exception will be
raised when the server returns an error.  `charset' must be @code{None} if
the @code{UTF8=ACCEPT} capability was enabled using the @ref{100e,,enable()}
command.

以下はプログラム例です:

@example
# M is a connected IMAP4 instance...
typ, msgnums = M.search(None, 'FROM', '"LDJ"')

# or:
typ, msgnums = M.search(None, '(FROM "LDJ")')
@end example
@end deffn

@geindex select() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 select}@anchor{405b}
@deffn {メソッド} IMAP4.select (mailbox='INBOX', readonly=False)

メールボックスを選択します。返されるデータは `mailbox' 内のメッセージ数 (@code{EXISTS} 応答) です。標準の設定では `mailbox' は @code{'INBOX'} です。`readonly' が設定された場合、メールボックスに対する変更はできません。
@end deffn

@geindex send() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 send}@anchor{4054}
@deffn {メソッド} IMAP4.send (data)

遠隔のサーバに @code{data} を送信します。このメソッドはオーバライドすることができます。

引数 @code{self}, @code{data} を指定して @ref{1c6e,,監査イベント} @code{imaplib.send} を送出します。
@end deffn

@geindex setacl() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 setacl}@anchor{405c}
@deffn {メソッド} IMAP4.setacl (mailbox, who, what)

@code{ACL} を `mailbox' に設定します。このメソッドは非標準ですが、@code{Cyrus} サーバでサポートされています。
@end deffn

@geindex setannotation() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 setannotation}@anchor{405d}
@deffn {メソッド} IMAP4.setannotation (mailbox, entry, attribute[, ...])

@code{ANNOTATION} を `mailbox' に設定します。このメソッドは非標準ですが、@code{Cyrus} サーバでサポートされています。
@end deffn

@geindex setquota() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 setquota}@anchor{405e}
@deffn {メソッド} IMAP4.setquota (root, limits)

@code{quota} `root' のリソースを `limits' に設定します。このメソッドは 
@geindex RFC; RFC 2087
RFC 2087@footnote{https://datatracker.ietf.org/doc/html/rfc2087.html} で定義されている IMAP4 QUOTA 拡張の一部です。
@end deffn

@geindex shutdown() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 shutdown}@anchor{4055}
@deffn {メソッド} IMAP4.shutdown ()

@code{open} で確立された接続を閉じます。 @ref{c84,,IMAP4.logout()} は暗黙的にこのメソッドを呼び出します。このメソッドはオーバライドすることができます。
@end deffn

@geindex socket() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 socket}@anchor{405f}
@deffn {メソッド} IMAP4.socket ()

サーバへの接続に使われているソケットインスタンスを返します。
@end deffn

@geindex sort() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 sort}@anchor{4060}
@deffn {メソッド} IMAP4.sort (sort_criteria, charset, search_criterion[, ...])

@code{sort} 命令は @code{search} に結果の並べ替え (sort) 機能をつけた変種です。返されるデータには、条件に合致するメッセージ番号をスペースで分割したリストが入っています。

sort 命令は `search_criterion' の前に二つの引数を持ちます;  `sort_criteria' のリストを丸括弧で囲ったものと、検索時の `charset' です。@code{search} と違って、検索時の `charset' は必須です。@code{uid sort} 命令もあり、@code{search} に対する @code{uid search} と同じように @code{sort} 命令に対応します。@code{sort} 命令はまず、charset 引数の指定に従って searching criteria の文字列を解釈し、メールボックスから与えられた検索条件に合致するメッセージを探します。次に、合致したメッセージの数を返します。

@code{IMAP4rev1} 拡張命令です。
@end deffn

@geindex starttls() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 starttls}@anchor{143e}
@deffn {メソッド} IMAP4.starttls (ssl_context=None)

Send a @code{STARTTLS} command.  The `ssl_context' argument is optional
and should be a @ref{357,,ssl.SSLContext} object.  This will enable
encryption on the IMAP connection.  Please read @ref{3895,,セキュリティで考慮すべき点} for
best practices.


Added in version 3.2.



バージョン 3.4 で変更: The method now supports hostname check with
@ref{39c4,,ssl.SSLContext.check_hostname} and `Server Name Indication' (see
@ref{39d6,,ssl.HAS_SNI}).

@end deffn

@geindex status() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 status}@anchor{4061}
@deffn {メソッド} IMAP4.status (mailbox, names)

`mailbox' の指定ステータス名の状態情報を要求します。
@end deffn

@geindex store() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 store}@anchor{4062}
@deffn {メソッド} IMAP4.store (message_set, command, flag_list)

メールボックス内のメッセージ群のフラグ設定を変更します。 `command' は 
@geindex RFC; RFC 2060
RFC 2060@footnote{https://datatracker.ietf.org/doc/html/rfc2060.html} のセクション 6.4.6 で指定されているもので、 "FLAGS", "+FLAGS", あるいは "-FLAGS" のいずれかとなります。オプションで末尾に ".SILENT" がつくこともあります。

たとえば、すべてのメッセージに削除フラグを設定するには次のようにします:

@example
typ, data = M.search(None, 'ALL')
for num in data[0].split():
   M.store(num, '+FLAGS', '\\Deleted')
M.expunge()
@end example

@cartouche
@quotation 注釈 
Creating flags containing ']' (for example: "[test]") violates
@geindex RFC; RFC 3501
RFC 3501@footnote{https://datatracker.ietf.org/doc/html/rfc3501.html} (the IMAP protocol).  However, imaplib has historically
allowed creation of such tags, and popular IMAP servers, such as Gmail,
accept and produce such flags.  There are non-Python programs which also
create such tags.  Although it is an RFC violation and IMAP clients and
servers are supposed to be strict, imaplib still continues to allow
such tags to be created for backward compatibility reasons, and as of
Python 3.6, handles them if they are sent from the server, since this
improves real-world compatibility.
@end quotation
@end cartouche
@end deffn

@geindex subscribe() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 subscribe}@anchor{4063}
@deffn {メソッド} IMAP4.subscribe (mailbox)

新たなメールボックスを購読 (subscribe) します。
@end deffn

@geindex thread() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 thread}@anchor{4064}
@deffn {メソッド} IMAP4.thread (threading_algorithm, charset, search_criterion[, ...])

@code{thread} コマンドは @code{search} にスレッドの概念を加えた変形版です。返されるデータは空白で区切られたスレッドメンバのリストを含んでいます。

各スレッドメンバは0以上のメッセージ番号からなり、空白で区切られており、親子関係を示しています。

Thread has two arguments before the `search_criterion' argument(s); a
`threading_algorithm', and the searching `charset'.  Note that unlike
@code{search}, the searching `charset' argument is mandatory.  There is also a
@code{uid thread} command which corresponds to @code{thread} the way that @code{uid
search} corresponds to @code{search}.  The @code{thread} command first searches the
mailbox for messages that match the given searching criteria using the `charset'
argument for the interpretation of strings in the searching criteria. It then
returns the matching messages threaded according to the specified threading
algorithm.

@code{IMAP4rev1} 拡張命令です。
@end deffn

@geindex uid() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 uid}@anchor{4065}
@deffn {メソッド} IMAP4.uid (command, arg[, ...])

command args を、メッセージ番号ではなく UID で指定されたメッセージ群に対して実行します。命令内容に応じた応答を返します。少なくとも一つの引数を与えなくてはなりません; 何も与えない場合、サーバはエラーを返し、例外が送出されます。
@end deffn

@geindex unsubscribe() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 unsubscribe}@anchor{4066}
@deffn {メソッド} IMAP4.unsubscribe (mailbox)

古いメールボックスの購読を解除 (unsubscribe) します。
@end deffn

@geindex unselect() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 unselect}@anchor{b03}
@deffn {メソッド} IMAP4.unselect ()

@ref{b03,,imaplib.IMAP4.unselect()} frees server's resources associated with the
selected mailbox and returns the server to the authenticated
state. This command performs the same actions as @ref{b04,,imaplib.IMAP4.close()}, except
that no messages are permanently removed from the currently
selected mailbox.


Added in version 3.9.

@end deffn

@geindex xatom() (imaplib.IMAP4 のメソッド)
@anchor{library/imaplib imaplib IMAP4 xatom}@anchor{4067}
@deffn {メソッド} IMAP4.xatom (name[, ...])

サーバから @code{CAPABILITY} 応答で通知された単純な拡張命令を許容 (allow) します。
@end deffn

以下の属性が @ref{aff,,IMAP4} のインスタンス上で定義されています:

@geindex PROTOCOL_VERSION (imaplib.IMAP4 の属性)
@anchor{library/imaplib imaplib IMAP4 PROTOCOL_VERSION}@anchor{4068}
@deffn {の属性} IMAP4.PROTOCOL_VERSION

サーバから返された @code{CAPABILITY} 応答にある、サポートされている最新のプロトコルです。
@end deffn

@geindex debug (imaplib.IMAP4 の属性)
@anchor{library/imaplib imaplib IMAP4 debug}@anchor{4069}
@deffn {の属性} IMAP4.debug

デバッグ出力を制御するための整数値です。初期値はモジュール変数 @code{Debug} から取られます。3 以上の値にすると各命令をトレースします。
@end deffn

@geindex utf8_enabled (imaplib.IMAP4 の属性)
@anchor{library/imaplib imaplib IMAP4 utf8_enabled}@anchor{100f}
@deffn {の属性} IMAP4.utf8_enabled

Boolean value that is normally @code{False}, but is set to @code{True} if an
@ref{100e,,enable()} command is successfully issued for the @code{UTF8=ACCEPT}
capability.


Added in version 3.5.

@end deffn

@node IMAP4 の使用例,,IMAP4 オブジェクト,imaplib --- IMAP4 プロトコルクライアント
@anchor{library/imaplib id2}@anchor{406a}@anchor{library/imaplib imap4-example}@anchor{406b}
@subsubsection IMAP4 の使用例


以下にメールボックスを開き、全てのメッセージを取得して印刷する最小の (エラーチェックをしない) 使用例を示します:

@example
import getpass, imaplib

M = imaplib.IMAP4(host='example.org')
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node smtplib --- SMTP プロトコルクライアント,uuid --- RFC 9562 に基づく UUID オブジェクト,imaplib --- IMAP4 プロトコルクライアント,インターネットプロトコルとサポート
@anchor{library/smtplib doc}@anchor{406c}@anchor{library/smtplib module-smtplib}@anchor{cf}@anchor{library/smtplib smtplib-smtp-protocol-client}@anchor{406d}@anchor{library/smtplib translation-repo}@anchor{406e}
@subsection @code{smtplib} --- SMTP プロトコルクライアント


@geindex module; smtplib

`ソースコード:' Lib/smtplib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/smtplib.py}

@geindex SMTP;プロトコル
@geindex Simple Mail Transfer Protocol


__________________________________________________________________


The @code{smtplib} module defines an SMTP client session object that can be used
to send mail to any internet machine with an SMTP or ESMTP listener daemon.  For
details of SMTP and ESMTP operation, consult 
@geindex RFC; RFC 821
RFC 821@footnote{https://datatracker.ietf.org/doc/html/rfc821.html} (Simple Mail Transfer
Protocol) and 
@geindex RFC; RFC 1869
RFC 1869@footnote{https://datatracker.ietf.org/doc/html/rfc1869.html} (SMTP Service Extensions).

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@geindex SMTP (smtplib のクラス)
@anchor{library/smtplib smtplib SMTP}@anchor{b27}
@deffn {クラス} smtplib.SMTP (host='@w{'}, port=0, local_hostname=None[, timeout], source_address=None)

@ref{b27,,SMTP} インスタンスはSMTP接続をカプセル化します。SMTPとESMTP操作の完全なレパートリーをサポートするメソッドがあります。オプションパラメータの `host' および `port' が指定されている場合、SMTPの @ref{1daf,,connect()} メソッドは初期化中にこれらのパラメータを使って呼び出されます。 `local_hostname' を指定した場合、それはHELO/EHLOコマンドのローカルホストのFQDNとして使用されます。指定しない場合、ローカルホスト名は @ref{1aed,,socket.getfqdn()} を使用して検索されます。 @ref{1daf,,connect()} 呼び出しが成功コード以外を返すと、 @ref{406f,,SMTPConnectError} が送出されます。オプションの `timeout' パラメータは、接続試行のようなブロッキング操作のタイムアウトを秒単位で指定します（指定されていない場合、グローバルなデフォルトのタイムアウト設定が使用されます）。タイムアウトが切れると、 @ref{a36,,TimeoutError} が送出されます。オプションの `source_address' パラメータを使用すると、複数のネットワークインターフェースを持つマシンの特定の送信元アドレス、かつ（または）特定の送信元TCPポートにバインドできます。接続する前にソケットを送信元アドレスとしてバインドするためにタプル @code{(host, port)} が必要です。省略された場合（あるいは、`host' または `port' がそれぞれ @code{'@w{'}} かつ/または @code{0} の場合）、OSのデフォルト動作が使用されます。

普通に使う場合は、初期化と接続を行ってから、 @ref{1059,,sendmail()} と @ref{4070,,SMTP.quit()} メソッドを呼びます。使用例は先の方で記載しています。

The @ref{b27,,SMTP} class supports the @ref{186,,with} statement.  When used
like this, the SMTP @code{QUIT} command is issued automatically when the
@code{with} statement exits.  E.g.:

@example
>>> from smtplib import SMTP
>>> with SMTP("domain.org") as smtp:
...     smtp.noop()
...
(250, b'Ok')
>>>
@end example

全てのコマンドは引数 @code{self} と @code{data} を指定して @ref{1c6e,,auditing event} @code{smtplib.SMTP.send} を送出します。ここで @code{data} はリモートホストに送信されるバイト数です。


バージョン 3.3 で変更: @ref{186,,with} 構文のサポートが追加されました。



バージョン 3.3 で変更: `source_address' argument was added.



Added in version 3.5: SMTPUTF8 拡張 (
@geindex RFC; RFC 6531
RFC 6531@footnote{https://datatracker.ietf.org/doc/html/rfc6531.html}) がサポートされました。



バージョン 3.9 で変更: `timeout' パラメータが0に設定されている場合、非ブロッキングソケットの作成を防ぐために @ref{2ec,,ValueError} を送出します。

@end deffn

@geindex SMTP_SSL (smtplib のクラス)
@anchor{library/smtplib smtplib SMTP_SSL}@anchor{b28}
@deffn {クラス} smtplib.SMTP_SSL (host='@w{'}, port=0, local_hostname=None, *[, timeout], context=None, source_address=None)

An @ref{b28,,SMTP_SSL} instance behaves exactly the same as instances of
@ref{b27,,SMTP}. @ref{b28,,SMTP_SSL} should be used for situations where SSL is
required from the beginning of the connection and using @ref{1350,,starttls()}
is not appropriate. If `host' is not specified, the local host is used. If
`port' is zero, the standard SMTP-over-SSL port (465) is used.  The optional
arguments `local_hostname', `timeout' and `source_address' have the same
meaning as they do in the @ref{b27,,SMTP} class.  `context', also optional,
can contain a @ref{357,,SSLContext} and allows configuring various
aspects of the secure connection.  Please read @ref{3895,,セキュリティで考慮すべき点} for
best practices.


バージョン 3.3 で変更: `context' が追加されました。



バージョン 3.3 で変更: The `source_address' argument was added.



バージョン 3.4 で変更: このクラスは @ref{39c4,,ssl.SSLContext.check_hostname} と `Server Name Indication' でホスト名のチェックをサポートしました。(@ref{39d6,,ssl.HAS_SNI} を参照してください)。



バージョン 3.9 で変更: `timeout' パラメータが0に設定されている場合、非ブロッキングソケットの作成を防ぐために @ref{2ec,,ValueError} を送出します。



バージョン 3.12 で変更: 非推奨の `keyfile' と `certfile' 引数を削除しました。

@end deffn

@geindex LMTP (smtplib のクラス)
@anchor{library/smtplib smtplib LMTP}@anchor{b29}
@deffn {クラス} smtplib.LMTP (host='@w{'}, port=LMTP_PORT, local_hostname=None, source_address=None[, timeout])

The LMTP protocol, which is very similar to ESMTP, is heavily based on the
standard SMTP client. It's common to use Unix sockets for LMTP, so our
@ref{1daf,,connect()} method must support that as well as a regular host:port
server. The optional arguments `local_hostname' and `source_address' have the
same meaning as they do in the @ref{b27,,SMTP} class. To specify a Unix
socket, you must use an absolute path for `host', starting with a '/'.

認証は、通常のSMTP機構を利用してサポートされています。 Unixソケットを利用する場合、LMTPは通常認証をサポートしたり要求したりはしません。しかし、あなたが必要であれば、利用することができます。


バージョン 3.9 で変更: オプションの `timeout' 引数が追加されました。

@end deffn

このモジュールの例外には次のものがあります:

@geindex SMTPException
@anchor{library/smtplib smtplib SMTPException}@anchor{11a3}
@deffn {例外} smtplib.SMTPException

@ref{2c0,,OSError} の派生クラスで、このモジュールが提供する他の全ての例外の基底クラスです。


バージョン 3.4 で変更: SMTPException が @ref{2c0,,OSError} の派生クラスになりました。

@end deffn

@geindex SMTPServerDisconnected
@anchor{library/smtplib smtplib SMTPServerDisconnected}@anchor{4071}
@deffn {例外} smtplib.SMTPServerDisconnected

この例外はサーバが突然接続が切断されるか、@ref{b27,,SMTP} インスタンスを生成する前に接続しようとした場合に送出されます。
@end deffn

@geindex SMTPResponseException
@anchor{library/smtplib smtplib SMTPResponseException}@anchor{4072}
@deffn {例外} smtplib.SMTPResponseException

Base class for all exceptions that include an SMTP error code. These exceptions
are generated in some instances when the SMTP server returns an error code.

@geindex smtp_code (smtplib.SMTPResponseException の属性)
@anchor{library/smtplib smtplib SMTPResponseException smtp_code}@anchor{4073}
@deffn {の属性} smtp_code

エラーコード。
@end deffn

@geindex smtp_error (smtplib.SMTPResponseException の属性)
@anchor{library/smtplib smtplib SMTPResponseException smtp_error}@anchor{4074}
@deffn {の属性} smtp_error

The error message.
@end deffn
@end deffn

@geindex SMTPSenderRefused
@anchor{library/smtplib smtplib SMTPSenderRefused}@anchor{4075}
@deffn {例外} smtplib.SMTPSenderRefused

送信者のアドレスが弾かれたときに送出される例外です。全ての @ref{4072,,SMTPResponseException} 例外に、 SMTPサーバが弾いた 'sender' アドレスの文字列がセットされます。
@end deffn

@geindex SMTPRecipientsRefused
@anchor{library/smtplib smtplib SMTPRecipientsRefused}@anchor{4076}
@deffn {例外} smtplib.SMTPRecipientsRefused

All recipient addresses refused.

@geindex recipients (smtplib.SMTPRecipientsRefused の属性)
@anchor{library/smtplib smtplib SMTPRecipientsRefused recipients}@anchor{4077}
@deffn {の属性} recipients

A dictionary of exactly the same sort as returned
by @ref{1059,,SMTP.sendmail()} containing the errors for
each recipient.
@end deffn
@end deffn

@geindex SMTPDataError
@anchor{library/smtplib smtplib SMTPDataError}@anchor{4078}
@deffn {例外} smtplib.SMTPDataError

SMTPサーバが、メッセージのデータを受け入れることを拒絶したときに送出される例外です。
@end deffn

@geindex SMTPConnectError
@anchor{library/smtplib smtplib SMTPConnectError}@anchor{406f}
@deffn {例外} smtplib.SMTPConnectError

サーバへの接続時にエラーが発生したときに送出される例外です。
@end deffn

@geindex SMTPHeloError
@anchor{library/smtplib smtplib SMTPHeloError}@anchor{4079}
@deffn {例外} smtplib.SMTPHeloError

サーバーが @code{HELO} メッセージを弾いたときに送出される例外です。
@end deffn

@geindex SMTPNotSupportedError
@anchor{library/smtplib smtplib SMTPNotSupportedError}@anchor{1dae}
@deffn {例外} smtplib.SMTPNotSupportedError

試行したコマンドやオプションはサーバにサポートされていません。


Added in version 3.5.

@end deffn

@geindex SMTPAuthenticationError
@anchor{library/smtplib smtplib SMTPAuthenticationError}@anchor{407a}
@deffn {例外} smtplib.SMTPAuthenticationError

SMTP 認証が失敗しました。最もあり得るのは、サーバーがユーザ名/パスワードのペアを受け付なかった事です。
@end deffn


@subsubheading 参考



@table @asis

@geindex RFC; RFC 821

@item RFC 821@footnote{https://datatracker.ietf.org/doc/html/rfc821.html} - Simple Mail Transfer Protocol

SMTP のプロトコル定義です。このドキュメントでは SMTP のモデル、操作手順、プロトコルの詳細についてカバーしています。

@geindex RFC; RFC 1869

@item RFC 1869@footnote{https://datatracker.ietf.org/doc/html/rfc1869.html} - SMTP Service Extensions

SMTP に対する ESMTP 拡張の定義です。このドキュメントでは、新たな命令による SMTP の拡張、サーバによって提供される命令を動的に発見する機能のサポート、およびいくつかの追加命令定義について記述しています。
@end table


@menu
* SMTP オブジェクト:: 
* SMTP 使用例:: 

@end menu

@node SMTP オブジェクト,SMTP 使用例,,smtplib --- SMTP プロトコルクライアント
@anchor{library/smtplib id1}@anchor{407b}@anchor{library/smtplib smtp-objects}@anchor{407c}
@subsubsection SMTP オブジェクト


@ref{b27,,SMTP} クラスインスタンスは次のメソッドを提供します:

@geindex set_debuglevel() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP set_debuglevel}@anchor{1058}
@deffn {メソッド} SMTP.set_debuglevel (level)

デバッグ出力レベルを設定します。`level' が 1 や @code{True} の場合、接続ならびにサーバとの送受信のメッセージがデバッグメッセージとなります。`level' が 2 の場合、それらのメッセージにタイムスタンプが付きます。


バージョン 3.5 で変更: デバッグレベル2が追加されました。

@end deffn

@geindex docmd() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP docmd}@anchor{407d}
@deffn {メソッド} SMTP.docmd (cmd, args='@w{'})

サーバへコマンド `cmd' を送信します。オプション引数 `args' はスペース文字でコマンドに連結します。戻り値は、整数値のレスポンスコードと、サーバからの応答の値をタプルで返します (サーバからの応答が数行に渡る場合でも一つの大きな文字列で返します)。

数値応答コードと実際の応答行 (複数の応答は 1 つの長い行に結合されます) からなる 2 値タプルを返します。

通常、このメソッドを明示的に使う必要はありません。他のメソッドを実装するのに使い、自分で拡張したものをテストするのに役立つかもしれません。

応答待ちのときにサーバへの接続が切れると @ref{4071,,SMTPServerDisconnected} が送出されます。
@end deffn

@geindex connect() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP connect}@anchor{1daf}
@deffn {メソッド} SMTP.connect (host='localhost', port=0)

ホスト名とポート番号をもとに接続します。デフォルトはlocalhostの標準的なSMTPポート(25番)に接続します。もしホスト名の末尾がコロン(@code{':'})で、後に番号がついている場合は、「ホスト名:ポート番号」として扱われます。このメソッドはコンストラクタにホスト名及びポート番号が指定されている場合、自動的に呼び出されます。戻り値は、この接続の応答内でサーバによって送信された応答コードとメッセージの2要素タプルです。

引数 @code{self}, @code{host}, @code{port} を指定して @ref{1c6e,,監査イベント} @code{smtplib.connect} を送出します。
@end deffn

@geindex helo() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP helo}@anchor{407e}
@deffn {メソッド} SMTP.helo (name='@w{'})

SMTPサーバに @code{HELO} コマンドで身元を示します。デフォルトではhostname引数はローカルホストを指します。サーバーが返したメッセージは、オブジェクトの @ref{407f,,helo_resp} 属性に格納されます。

通常は @ref{1059,,sendmail()} が呼びだすため、これを明示的に呼び出す必要はありません。
@end deffn

@geindex ehlo() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP ehlo}@anchor{4080}
@deffn {メソッド} SMTP.ehlo (name='@w{'})

@code{EHLO} を利用し、ESMTPサーバに身元を明かします。デフォルトではhostname引数はローカルホストのFQDNです。また、ESMTPオプションのために応答を調べたものは、 @ref{4081,,has_extn()} に備えて保存されます。また、幾つかの情報を属性に保存します: サーバーが返したメッセージは @ref{4082,,ehlo_resp} 属性に、 @ref{4083,,does_esmtp} 属性はサーバーがESMTPをサポートしているかどうかによって @code{True} か @code{False} に、 @ref{4084,,esmtp_features} 属性は辞書で、サーバーが対応しているSMTP サービス拡張の名前と、もしあればそのパラメータを格納します。

メールを送信する前に @ref{4081,,has_extn()} を使おうとしない限り、このメソッドを明示的に呼ぶ必要はないはずです。必要な場合は @ref{1059,,sendmail()} に暗黙的に呼ばれます。
@end deffn

@geindex ehlo_or_helo_if_needed() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP ehlo_or_helo_if_needed}@anchor{4085}
@deffn {メソッド} SMTP.ehlo_or_helo_if_needed ()

このメソッドは、現在のセッションでまだ @code{EHLO} か @code{HELO} コマンドが実行されていない場合、 @ref{4080,,ehlo()} and/or @ref{407e,,helo()} メソッドを呼び出します。このメソッドは先に ESMTP @code{EHLO} を試します。


@table @asis

@item @ref{4079,,SMTPHeloError}

サーバーが @code{HELO} に正しく返答しませんでした。
@end table
@end deffn

@geindex has_extn() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP has_extn}@anchor{4081}
@deffn {メソッド} SMTP.has_extn (name)

`name' が拡張SMTPサービスセットに含まれている場合には @ref{e07,,True} を返し、そうでなければ @ref{d2b,,False} を返します。大小文字は区別されません。
@end deffn

@geindex verify() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP verify}@anchor{4086}
@deffn {メソッド} SMTP.verify (address)

@code{VRFY} を利用してSMTPサーバにアドレスの妥当性をチェックします。妥当である場合はコード250と完全な 
@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html} アドレス (人名を含む) のタプルを返します。それ以外の場合は、400以上のエラーコードとエラー文字列を返します。

@cartouche
@quotation 注釈 
ほとんどのサイトはスパマーの裏をかくためにSMTPの @code{VRFY} は使用不可になっています。
@end quotation
@end cartouche
@end deffn

@geindex login() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP login}@anchor{4087}
@deffn {メソッド} SMTP.login (user, password, *, initial_response_ok=True)

認証が必要なSMTPサーバにログインします。認証に使用する引数はユーザ名とパスワードです。まだセッションが無い場合は、 @code{EHLO} または @code{HELO} コマンドでセッションを作ります。ESMTPの場合は @code{EHLO} が先に試されます。認証が成功した場合は通常このメソッドは戻りますが、例外が起こった場合は以下の例外が上がります:


@table @asis

@item @ref{4079,,SMTPHeloError}

サーバーが @code{HELO} に正しく返答しませんでした。

@item @ref{407a,,SMTPAuthenticationError}

サーバがユーザ名/パスワードでの認証に失敗しました。

@item @ref{1dae,,SMTPNotSupportedError}

@code{AUTH} コマンドはサーバにサポートされていません。

@item @ref{11a3,,SMTPException}

適当な認証方法が見付かりませんでした。
@end table

Each of the authentication methods supported by @code{smtplib} are tried in
turn if they are advertised as supported by the server.  See @ref{1057,,auth()}
for a list of supported authentication methods.  `initial_response_ok' is
passed through to @ref{1057,,auth()}.

オプションのキーワード引数 `initial_response_ok' は、それをサポートする認証方法に対して、チャレンジ/レスポンスを要求するのではなく、 "AUTH"コマンドとともに 
@geindex RFC; RFC 4954
RFC 4954@footnote{https://datatracker.ietf.org/doc/html/rfc4954.html} で指定された"初期応答"を送信できるかどうかを指定します。


バージョン 3.5 で変更: @ref{1dae,,SMTPNotSupportedError} が送出される場合があります。`initial_response_ok' 引数が追加されました。

@end deffn

@geindex auth() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP auth}@anchor{1057}
@deffn {メソッド} SMTP.auth (mechanism, authobject, *, initial_response_ok=True)

Issue an @code{SMTP} @code{AUTH} command for the specified authentication
`mechanism', and handle the challenge response via `authobject'.

`mechanism' specifies which authentication mechanism is to
be used as argument to the @code{AUTH} command; the valid values are
those listed in the @code{auth} element of @ref{4084,,esmtp_features}.

`authobject' must be a callable object taking an optional single argument:

@example
data = authobject(challenge=None)
@end example

If optional keyword argument `initial_response_ok' is true,
@code{authobject()} will be called first with no argument.  It can return the
@geindex RFC; RFC 4954
RFC 4954@footnote{https://datatracker.ietf.org/doc/html/rfc4954.html} "initial response" ASCII @code{str} which will be encoded and sent with
the @code{AUTH} command as below.  If the @code{authobject()} does not support an
initial response (e.g. because it requires a challenge), it should return
@code{None} when called with @code{challenge=None}.  If `initial_response_ok' is
false, then @code{authobject()} will not be called first with @code{None}.

If the initial response check returns @code{None}, or if `initial_response_ok' is
false, @code{authobject()} will be called to process the server's challenge
response; the `challenge' argument it is passed will be a @code{bytes}.  It
should return ASCII @code{str} `data' that will be base64 encoded and sent to the
server.

The @code{SMTP} class provides @code{authobjects} for the @code{CRAM-MD5}, @code{PLAIN},
and @code{LOGIN} mechanisms; they are named @code{SMTP.auth_cram_md5},
@code{SMTP.auth_plain}, and @code{SMTP.auth_login} respectively.  They all require
that the @code{user} and @code{password} properties of the @code{SMTP} instance are
set to appropriate values.

User code does not normally need to call @code{auth} directly, but can instead
call the @ref{4087,,login()} method, which will try each of the above mechanisms
in turn, in the order listed.  @code{auth} is exposed to facilitate the
implementation of authentication methods not (or not yet) supported
directly by @code{smtplib}.


Added in version 3.5.

@end deffn

@geindex starttls() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP starttls}@anchor{1350}
@deffn {メソッド} SMTP.starttls (*, context=None)

TLS (Transport Layer Security) モードで SMTP 接続します。続く全てのSMTP コマンドは暗号化されます。その後、もう一度 @ref{4080,,ehlo()} を呼んでください。

If `keyfile' and `certfile' are provided, they are used to create an
@ref{357,,ssl.SSLContext}.

Optional `context' parameter is an @ref{357,,ssl.SSLContext} object; This is
an alternative to using a keyfile and a certfile and if specified both
`keyfile' and `certfile' should be @code{None}.

もしまだ @code{EHLO} か @code{HELO} コマンドが実行されていない場合、このメソッドは ESMTP @code{EHLO} を先に試します。


バージョン 3.12 で変更: 非推奨の `keyfile' と `certfile' 引数を削除しました。



@table @asis

@item @ref{4079,,SMTPHeloError}

サーバーが @code{HELO} に正しく返答しませんでした。

@item @ref{1dae,,SMTPNotSupportedError}

サーバーが STARTTLS 拡張に対応していません。

@item @ref{244,,RuntimeError}

実行中の Python インタプリタで、SSL/TLS サポートが利用できません。
@end table


バージョン 3.3 で変更: `context' が追加されました。



バージョン 3.4 で変更: The method now supports hostname check with
@ref{39c4,,ssl.SSLContext.check_hostname} and `Server Name Indicator' (see
@ref{39d6,,HAS_SNI}).



バージョン 3.5 で変更: The error raised for lack of STARTTLS support is now the
@ref{1dae,,SMTPNotSupportedError} subclass instead of the base
@ref{11a3,,SMTPException}.

@end deffn

@geindex sendmail() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP sendmail}@anchor{1059}
@deffn {メソッド} SMTP.sendmail (from_addr, to_addrs, msg, mail_options=(), rcpt_options=())

Send mail.  The required arguments are an 
@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html} from-address string, a list
of 
@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html} to-address strings (a bare string will be treated as a list with 1
address), and a message string.  The caller may pass a list of ESMTP options
(such as @code{"8bitmime"}) to be used in @code{MAIL FROM} commands as `mail_options'.
ESMTP options (such as @code{DSN} commands) that should be used with all @code{RCPT}
commands can be passed as `rcpt_options'. Each option should be passed as a string
containing the full text of the option, including any potential key
(for instance, @code{"NOTIFY=SUCCESS,FAILURE"}). (If you need to use different ESMTP
options to different recipients you have to use the low-level methods such as
@code{mail()}, @code{rcpt()} and @code{data()} to send the message.)

@cartouche
@quotation 注釈 
配送エージェントは `from_addr'、`to_addrs' 引数を使い、メッセージのエンベロープを構成します。@code{sendmail} はメッセージヘッダを修正しません。
@end quotation
@end cartouche

`msg' may be a string containing characters in the ASCII range, or a byte
string.  A string is encoded to bytes using the ascii codec, and lone @code{\r}
and @code{\n} characters are converted to @code{\r\n} characters.  A byte string is
not modified.

まだセッションが無い場合は、 @code{EHLO} または @code{HELO} コマンドでセッションを作ります。ESMTPの場合は @code{EHLO} が先に試されます。また、サーバがESMTP対応ならば、メッセージサイズとそれぞれ指定されたオプションも渡します。(featureオプションがあればサーバの広告をセットします) @code{EHLO} が失敗した場合は、ESMTPオプションの無い @code{HELO} が試されます。

このメソッドは最低でも1人の受信者にメールが受け取られたときは正常に戻ります。そうでない場合は例外を投げます。つまり、このメソッドが例外を送出しないときは誰かが送信したメールを受け取ったはずです。また、例外を送出しない場合は拒絶された受信者ごとに項目のある辞書を返します。各項目はサーバーが送ったSMTPエラーコードと付随するエラーメッセージのタプルを持ちます。

`mail_options' に @code{SMTPUTF8} があり、サーバがサポートしている場合は、`from_addr' と `to_addrs' に非 ASCII 文字を含めることが出来ます。

このメソッドは次の例外を送出することがあります:


@table @asis

@item @ref{4076,,SMTPRecipientsRefused}

All recipients were refused.  Nobody got the mail.

@item @ref{4079,,SMTPHeloError}

サーバーが @code{HELO} に正しく返答しませんでした。

@item @ref{4075,,SMTPSenderRefused}

サーバが `from_addr' を受理しませんでした。

@item @ref{4078,,SMTPDataError}

サーバが予期しないエラーコードを返しました (受信拒否以外)。

@item @ref{1dae,,SMTPNotSupportedError}

`mail_options' に @code{SMTPUTF8} が与えられましたが、サーバがサポートしていません。
@end table

また、この他の注意として、例外が上がった後もコネクションは開いたままになっています。


バージョン 3.2 で変更: `msg' はバイト文字列でも構いません。



バージョン 3.5 で変更: @code{SMTPUTF8} のサポートが追加されました。@code{SMTPUTF8} が与えられたが、サーバがサポートしていない場合は @ref{1dae,,SMTPNotSupportedError} が送出されます。

@end deffn

@geindex send_message() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP send_message}@anchor{105a}
@deffn {メソッド} SMTP.send_message (msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=())

This is a convenience method for calling @ref{1059,,sendmail()} with the message
represented by an @ref{581,,email.message.Message} object.  The arguments have
the same meaning as for @ref{1059,,sendmail()}, except that `msg' is a @code{Message}
object.

If `from_addr' is @code{None} or `to_addrs' is @code{None}, @code{send_message} fills
those arguments with addresses extracted from the headers of `msg' as
specified in 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html}: `from_addr' is set to the @code{Sender}
field if it is present, and otherwise to the @code{From} field.
`to_addrs' combines the values (if any) of the @code{To},
@code{Cc}, and @code{Bcc} fields from `msg'.  If exactly one
set of @code{Resent-*} headers appear in the message, the regular
headers are ignored and the @code{Resent-*} headers are used instead.
If the message contains more than one set of @code{Resent-*} headers,
a @ref{2ec,,ValueError} is raised, since there is no way to unambiguously detect
the most recent set of @code{Resent-} headers.

@code{send_message} serializes `msg' using
@ref{13e7,,BytesGenerator} with @code{\r\n} as the `linesep', and
calls @ref{1059,,sendmail()} to transmit the resulting message.  Regardless of the
values of `from_addr' and `to_addrs', @code{send_message} does not transmit any
@code{Bcc} or @code{Resent-Bcc} headers that may appear
in `msg'.  If any of the addresses in `from_addr' and `to_addrs' contain
non-ASCII characters and the server does not advertise @code{SMTPUTF8} support,
an @ref{1dae,,SMTPNotSupportedError} is raised.  Otherwise the @code{Message} is
serialized with a clone of its @ref{53,,policy} with the
@ref{ff9,,utf8} attribute set to @code{True}, and
@code{SMTPUTF8} and @code{BODY=8BITMIME} are added to `mail_options'.


Added in version 3.2.



Added in version 3.5: 国際化アドレスのサポート (@code{SMTPUTF8})。

@end deffn

@geindex quit() (smtplib.SMTP のメソッド)
@anchor{library/smtplib smtplib SMTP quit}@anchor{4070}
@deffn {メソッド} SMTP.quit ()

SMTPセッションを終了し、接続を閉じます。SMTP @code{QUIT} コマンドの結果を返します。
@end deffn

下位レベルのメソッドは標準SMTP/ESMTPコマンド @code{HELP} 、 @code{RSET} 、 @code{NOOP} 、 @code{MAIL} 、 @code{RCPT} 、 @code{DATA} に対応しています。通常これらは直接呼ぶ必要はなく、また、ドキュメントもありません。詳細はモジュールのコードを調べてください。

Additionally, an SMTP instance has the following attributes:

@geindex helo_resp (smtplib.SMTP の属性)
@anchor{library/smtplib smtplib SMTP helo_resp}@anchor{407f}
@deffn {の属性} SMTP.helo_resp

The response to the @code{HELO} command, see @ref{407e,,helo()}.
@end deffn

@geindex ehlo_resp (smtplib.SMTP の属性)
@anchor{library/smtplib smtplib SMTP ehlo_resp}@anchor{4082}
@deffn {の属性} SMTP.ehlo_resp

The response to the @code{EHLO} command, see @ref{4080,,ehlo()}.
@end deffn

@geindex does_esmtp (smtplib.SMTP の属性)
@anchor{library/smtplib smtplib SMTP does_esmtp}@anchor{4083}
@deffn {の属性} SMTP.does_esmtp

A boolean value indicating whether the server supports ESMTP, see
@ref{4080,,ehlo()}.
@end deffn

@geindex esmtp_features (smtplib.SMTP の属性)
@anchor{library/smtplib smtplib SMTP esmtp_features}@anchor{4084}
@deffn {の属性} SMTP.esmtp_features

A dictionary of the names of SMTP service extensions supported by the server,
see @ref{4080,,ehlo()}.
@end deffn

@node SMTP 使用例,,SMTP オブジェクト,smtplib --- SMTP プロトコルクライアント
@anchor{library/smtplib id2}@anchor{4088}@anchor{library/smtplib smtp-example}@anchor{4089}
@subsubsection SMTP 使用例


This example prompts the user for addresses needed in the message envelope ('To'
and 'From' addresses), and the message to be delivered.  Note that the headers
to be included with the message must be included in the message as entered; this
example doesn't do any processing of the 
@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html} headers.  In particular, the
'To' and 'From' addresses must be included in the message headers explicitly:

@example
import smtplib

def prompt(title):
    return input(title).strip()

from_addr = prompt("From: ")
to_addrs  = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")

# Add the From: and To: headers at the start!
lines = [f"From: @{from_addr@}", f"To: @{', '.join(to_addrs)@}", ""]
while True:
    try:
        line = input()
    except EOFError:
        break
    else:
        lines.append(line)

msg = "\r\n".join(lines)
print("Message length is", len(msg))

server = smtplib.SMTP("localhost")
server.set_debuglevel(1)
server.sendmail(from_addr, to_addrs, msg)
server.quit()
@end example

@cartouche
@quotation 注釈 
多くの場合、 @ref{3f,,email} パッケージの機能を使って email メッセージを構築し、それを、 @ref{105a,,send_message()} で送信する、という手順を用います。 @ref{113e,,email; 使用例} を参照してください。
@end quotation
@end cartouche

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node uuid --- RFC 9562 に基づく UUID オブジェクト,socketserver --- ネットワークサーバーのフレームワーク,smtplib --- SMTP プロトコルクライアント,インターネットプロトコルとサポート
@anchor{library/uuid doc}@anchor{408a}@anchor{library/uuid module-uuid}@anchor{116}@anchor{library/uuid translation-repo}@anchor{408b}@anchor{library/uuid uuid-uuid-objects-according-to-rfc-9562}@anchor{408c}
@subsection @code{uuid} --- 
@geindex RFC; RFC 9562
`RFC 9562' に基づく UUID オブジェクト


@geindex module; uuid

`ソースコード:' Lib/uuid.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/uuid.py}


__________________________________________________________________


This module provides immutable @ref{c56,,UUID} objects (the @ref{c56,,UUID} class)
and @ref{408d,,functions} for generating UUIDs corresponding
to a specific UUID version as specified in 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html} (which supersedes 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://datatracker.ietf.org/doc/html/rfc4122.html}),
for example, @ref{da1,,uuid1()} for UUID version 1, @ref{2e5,,uuid3()} for UUID version 3, and so on.
Note that UUID version 2 is deliberately omitted as it is outside the scope of the RFC.

もしユニークな ID が必要なだけであれば、おそらく @ref{da1,,uuid1()} か @ref{2e7,,uuid4()} を呼び出せば良いでしょう。 @ref{da1,,uuid1()} はコンピュータのネットワークアドレスを含む UUID を生成するためにプライバシーを侵害するかもしれない点に注意してください。 @ref{2e7,,uuid4()} はランダムな UUID を生成します。

Depending on support from the underlying platform, @ref{da1,,uuid1()} may or may
not return a "safe" UUID.  A safe UUID is one which is generated using
synchronization methods that ensure no two processes can obtain the same
UUID.  All instances of @ref{c56,,UUID} have an @ref{d9f,,is_safe} attribute
which relays any information about the UUID's safety, using this enumeration:

@geindex SafeUUID (uuid のクラス)
@anchor{library/uuid uuid SafeUUID}@anchor{408e}
@deffn {クラス} uuid.SafeUUID


Added in version 3.7.


@geindex safe (uuid.SafeUUID の属性)
@anchor{library/uuid uuid SafeUUID safe}@anchor{408f}
@deffn {の属性} safe

UUID は並列処理に対して安全なプラットフォームで生成された
@end deffn

@geindex unsafe (uuid.SafeUUID の属性)
@anchor{library/uuid uuid SafeUUID unsafe}@anchor{4090}
@deffn {の属性} unsafe

UUID は並列処理に対して安全なプラットフォームで生成されなかった
@end deffn

@geindex unknown (uuid.SafeUUID の属性)
@anchor{library/uuid uuid SafeUUID unknown}@anchor{4091}
@deffn {の属性} unknown

プラットフォームは、UUID が安全に生成されたかどうかの情報を提供しなかった
@end deffn
@end deffn

@geindex UUID (uuid のクラス)
@anchor{library/uuid uuid UUID}@anchor{c56}
@deffn {クラス} uuid.UUID (hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown)

32 桁の 16 進数文字列、`bytes' に 16 バイトのビッグエンディアンの文字列、`bytes_le' 引数に 16 バイトのリトルエンディアンの文字列、`fields' 引数に 6 つの整数のタプル（32ビット `time_low', 16 ビット `time_mid', 16ビット `time_hi_version', 8ビット `clock_seq_hi_variant', 8ビット `clock_seq_low', 48ビット `node' ）、または `int' に一つの 128 ビット整数のいずれかから UUID を生成します。16 進数が与えられた時、波括弧、ハイフン、それと URN 接頭辞は無視されます。例えば、これらの表現は全て同じ UUID を払い出します:

@example
UUID('@{12345678-1234-5678-1234-567812345678@}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes=b'\x12\x34\x56\x78'*4)
UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
              b'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
@end example

Exactly one of `hex', `bytes', `bytes_le', `fields', or `int' must be given.
The `version' argument is optional; if given, the resulting UUID will have its
variant and version number set according to 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}, overriding bits in the
given `hex', `bytes', `bytes_le', `fields', or `int'.

2つのUUIDオブジェクトの比較は、@ref{4092,,UUID.int} 属性の比較によって行われます。UUIDではないオブジェクトとの比較は、 @ref{198,,TypeError} を送出します。

@code{str(uuid)} は 32桁の16進でUUIDを表す`@w{`}12345678-1234-5678-1234-567812345678`@w{`} 形式の文字列を返します。
@end deffn

@ref{c56,,UUID} インスタンスは以下の読み出し専用属性を持ちます:

@geindex bytes (uuid.UUID の属性)
@anchor{library/uuid uuid UUID bytes}@anchor{4093}
@deffn {の属性} UUID.bytes

16 バイト文字列（バイトオーダーがビッグエンディアンの 6 つの整数フィールドを持つ）のUUID。
@end deffn

@geindex bytes_le (uuid.UUID の属性)
@anchor{library/uuid uuid UUID bytes_le}@anchor{4094}
@deffn {の属性} UUID.bytes_le

16 バイト文字列（ `time_low', `time_mid', `time_hi_version' をリトルエンディアンで持つ）の UUID。
@end deffn

@geindex fields (uuid.UUID の属性)
@anchor{library/uuid uuid UUID fields}@anchor{4095}
@deffn {の属性} UUID.fields

UUID の 6 つの整数フィールドを持つタプルで、これは 6 つの個別の属性と 2 つの派生した属性としても取得可能です:
@end deffn


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

フィールド

@tab

意味

@item

@geindex time_low (uuid.UUID の属性)
@anchor{library/uuid uuid UUID time_low}@anchor{4096}
@deffn {の属性} UUID.time_low
@end deffn

@tab

The first 32 bits of the UUID. Only relevant to version 1.

@item

@geindex time_mid (uuid.UUID の属性)
@anchor{library/uuid uuid UUID time_mid}@anchor{4097}
@deffn {の属性} UUID.time_mid
@end deffn

@tab

The next 16 bits of the UUID. Only relevant to version 1.

@item

@geindex time_hi_version (uuid.UUID の属性)
@anchor{library/uuid uuid UUID time_hi_version}@anchor{4098}
@deffn {の属性} UUID.time_hi_version
@end deffn

@tab

The next 16 bits of the UUID. Only relevant to version 1.

@item

@geindex clock_seq_hi_variant (uuid.UUID の属性)
@anchor{library/uuid uuid UUID clock_seq_hi_variant}@anchor{4099}
@deffn {の属性} UUID.clock_seq_hi_variant
@end deffn

@tab

The next 8 bits of the UUID. Only relevant to versions 1 and 6.

@item

@geindex clock_seq_low (uuid.UUID の属性)
@anchor{library/uuid uuid UUID clock_seq_low}@anchor{409a}
@deffn {の属性} UUID.clock_seq_low
@end deffn

@tab

The next 8 bits of the UUID. Only relevant to versions 1 and 6.

@item

@geindex node (uuid.UUID の属性)
@anchor{library/uuid uuid UUID node}@anchor{409b}
@deffn {の属性} UUID.node
@end deffn

@tab

The last 48 bits of the UUID. Only relevant to version 1.

@item

@geindex time (uuid.UUID の属性)
@anchor{library/uuid uuid UUID time}@anchor{409c}
@deffn {の属性} UUID.time
@end deffn

@tab

The 60-bit timestamp as a count of 100-nanosecond intervals since
Gregorian epoch (1582-10-15 00:00:00) for versions 1 and 6, or the
48-bit timestamp in milliseconds since Unix epoch (1970-01-01 00:00:00)
for version 7.

@item

@geindex clock_seq (uuid.UUID の属性)
@anchor{library/uuid uuid UUID clock_seq}@anchor{409d}
@deffn {の属性} UUID.clock_seq
@end deffn

@tab

The 14-bit sequence number. Only relevant to versions 1 and 6.

@end multitable


@geindex hex (uuid.UUID の属性)
@anchor{library/uuid uuid UUID hex}@anchor{188f}
@deffn {の属性} UUID.hex

32 文字の小文字 16 進数文字列での UUID。
@end deffn

@geindex int (uuid.UUID の属性)
@anchor{library/uuid uuid UUID int}@anchor{4092}
@deffn {の属性} UUID.int

128 ビット整数での UUID。
@end deffn

@geindex urn (uuid.UUID の属性)
@anchor{library/uuid uuid UUID urn}@anchor{409e}
@deffn {の属性} UUID.urn

The UUID as a URN as specified in 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}.
@end deffn

@geindex variant (uuid.UUID の属性)
@anchor{library/uuid uuid UUID variant}@anchor{409f}
@deffn {の属性} UUID.variant

UUID の内部レイアウトを決定する UUID の variant。これは定数 @ref{40a0,,RESERVED_NCS}, @ref{40a1,,RFC_4122}, @ref{40a2,,RESERVED_MICROSOFT}, @ref{40a3,,RESERVED_FUTURE} のいずれかです。
@end deffn

@geindex version (uuid.UUID の属性)
@anchor{library/uuid uuid UUID version}@anchor{40a4}
@deffn {の属性} UUID.version

The UUID version number (1 through 8, meaningful only when the variant is
@ref{40a1,,RFC_4122}).


バージョン 3.14 で変更: Added UUID versions 6, 7 and 8.

@end deffn

@geindex is_safe (uuid.UUID の属性)
@anchor{library/uuid uuid UUID is_safe}@anchor{d9f}
@deffn {の属性} UUID.is_safe

@ref{408e,,SafeUUID} の列挙で、UUID は並列処理に対して安全なプラットフォームで生成されたかを示す。


Added in version 3.7.

@end deffn

The @code{uuid} module defines the following functions:

@geindex getnode() (uuid モジュール)
@anchor{library/uuid uuid getnode}@anchor{da0}
@deffn {の関数} uuid.getnode ()

48 ビットの正の整数としてハードウェアアドレスを取得します。最初にこれを起動すると、別個のプログラムが立ち上がって非常に遅くなることがあります。もしハードウェアを取得する試みが全て失敗すると、ランダムな 48 ビットを、
@geindex RFC; RFC 4122
RFC 4122@footnote{https://datatracker.ietf.org/doc/html/rfc4122.html} で推奨されているように、マルチキャストビット (最初のオクテットの最下位ビット) を 1 に設定して使います。"ハードウェアアドレス" とはネットワークインターフェースの MAC アドレスを指します。複数のネットワークインターフェースを持つマシンの場合、全域管理されたMACアドレス (最初のオクテットの下位より2番目のビットが `設定されていない' MACアドレス) が、他の個別管理アドレスよりも優先的に使用されます。この優先順序は保証されません。


バージョン 3.7 で変更: 全域管理されたMACアドレスは、グローバルに固有であると保証されるため、固有である保証のない個別管理アドレスよりも好ましいです。

@end deffn

@geindex uuid1() (uuid モジュール)
@anchor{library/uuid uuid-factory-functions}@anchor{408d}@anchor{library/uuid uuid uuid1}@anchor{da1}
@deffn {の関数} uuid.uuid1 (node=None, clock_seq=None)

Generate a UUID from a host ID, sequence number, and the current time
according to 
@geindex RFC; RFC 9562 Section 5.1
RFC 9562@comma{} §5.1@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.1}.

When `node' is not specified, @ref{da0,,getnode()} is used to obtain the hardware
address as a 48-bit positive integer. When a sequence number `clock_seq' is
not specified, a pseudo-random 14-bit positive integer is generated.

If `node' or `clock_seq' exceed their expected bit count,
only their least significant bits are kept.
@end deffn

@geindex uuid3() (uuid モジュール)
@anchor{library/uuid uuid uuid3}@anchor{2e5}
@deffn {の関数} uuid.uuid3 (namespace, name)

Generate a UUID based on the MD5 hash of a namespace identifier (which is a
UUID) and a name (which is a @ref{192,,bytes} object or a string
that will be encoded using UTF-8)
according to 
@geindex RFC; RFC 9562 Section 5.3
RFC 9562@comma{} §5.3@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.3}.
@end deffn

@geindex uuid4() (uuid モジュール)
@anchor{library/uuid uuid uuid4}@anchor{2e7}
@deffn {の関数} uuid.uuid4 ()

Generate a random UUID in a cryptographically-secure method
according to 
@geindex RFC; RFC 9562 Section 5.4
RFC 9562@comma{} §5.4@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.4}.
@end deffn

@geindex uuid5() (uuid モジュール)
@anchor{library/uuid uuid uuid5}@anchor{2e6}
@deffn {の関数} uuid.uuid5 (namespace, name)

Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a
UUID) and a name (which is a @ref{192,,bytes} object or a string
that will be encoded using UTF-8)
according to 
@geindex RFC; RFC 9562 Section 5.5
RFC 9562@comma{} §5.5@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.5}.
@end deffn

@geindex uuid6() (uuid モジュール)
@anchor{library/uuid uuid uuid6}@anchor{2c2}
@deffn {の関数} uuid.uuid6 (node=None, clock_seq=None)

Generate a UUID from a sequence number and the current time according to
@geindex RFC; RFC 9562 Section 5.6
RFC 9562@comma{} §5.6@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.6}.

This is an alternative to @ref{da1,,uuid1()} to improve database locality.

When `node' is not specified, @ref{da0,,getnode()} is used to obtain the hardware
address as a 48-bit positive integer. When a sequence number `clock_seq' is
not specified, a pseudo-random 14-bit positive integer is generated.

If `node' or `clock_seq' exceed their expected bit count,
only their least significant bits are kept.


Added in version 3.14.

@end deffn

@geindex uuid7() (uuid モジュール)
@anchor{library/uuid uuid uuid7}@anchor{2c3}
@deffn {の関数} uuid.uuid7 ()

Generate a time-based UUID according to
@geindex RFC; RFC 9562 Section 5.7
RFC 9562@comma{} §5.7@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.7}.

For portability across platforms lacking sub-millisecond precision, UUIDs
produced by this function embed a 48-bit timestamp and use a 42-bit counter
to guarantee monotonicity within a millisecond.


Added in version 3.14.

@end deffn

@geindex uuid8() (uuid モジュール)
@anchor{library/uuid uuid uuid8}@anchor{2c4}
@deffn {の関数} uuid.uuid8 (a=None, b=None, c=None)

Generate a pseudo-random UUID according to
@geindex RFC; RFC 9562 Section 5.8
RFC 9562@comma{} §5.8@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.8}.

When specified, the parameters `a', `b' and `c' are expected to be
positive integers of 48, 12 and 62 bits respectively. If they exceed
their expected bit count, only their least significant bits are kept;
non-specified arguments are substituted for a pseudo-random integer of
appropriate size.

By default, `a', `b' and `c' are not generated by a cryptographically
secure pseudo-random number generator (CSPRNG). Use @ref{2e7,,uuid4()} when
a UUID needs to be used in a security-sensitive context.


Added in version 3.14.

@end deffn

The @code{uuid} module defines the following namespace identifiers for use with
@ref{2e5,,uuid3()} or @ref{2e6,,uuid5()}.

@geindex NAMESPACE_DNS (uuid モジュール)
@anchor{library/uuid uuid NAMESPACE_DNS}@anchor{40a5}
@deffn {データ} uuid.NAMESPACE_DNS

この名前空間が指定された場合、`name' 文字列は完全修飾ドメイン名です。
@end deffn

@geindex NAMESPACE_URL (uuid モジュール)
@anchor{library/uuid uuid NAMESPACE_URL}@anchor{40a6}
@deffn {データ} uuid.NAMESPACE_URL

この名前空間が指定された場合、`name' 文字列は URL です。
@end deffn

@geindex NAMESPACE_OID (uuid モジュール)
@anchor{library/uuid uuid NAMESPACE_OID}@anchor{40a7}
@deffn {データ} uuid.NAMESPACE_OID

この名前空間が指定された場合、`name' 文字列は ISO OID です。
@end deffn

@geindex NAMESPACE_X500 (uuid モジュール)
@anchor{library/uuid uuid NAMESPACE_X500}@anchor{40a8}
@deffn {データ} uuid.NAMESPACE_X500

この名前空間が指定された場合、`name' 文字列は X.500 DN の DER またはテキスト出力形式です。
@end deffn

The @code{uuid} module defines the following constants for the possible values
of the @ref{409f,,variant} attribute:

@geindex RESERVED_NCS (uuid モジュール)
@anchor{library/uuid uuid RESERVED_NCS}@anchor{40a0}
@deffn {データ} uuid.RESERVED_NCS

NCS 互換性のために予約されています。
@end deffn

@geindex RFC_4122 (uuid モジュール)
@anchor{library/uuid uuid RFC_4122}@anchor{40a1}
@deffn {データ} uuid.RFC_4122

Specifies the UUID layout given in 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://datatracker.ietf.org/doc/html/rfc4122.html}. This constant is kept
for backward compatibility even though 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://datatracker.ietf.org/doc/html/rfc4122.html} has been superseded
by 
@geindex RFC; RFC 9562
RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html}.
@end deffn

@geindex RESERVED_MICROSOFT (uuid モジュール)
@anchor{library/uuid uuid RESERVED_MICROSOFT}@anchor{40a2}
@deffn {データ} uuid.RESERVED_MICROSOFT

Microsoft の互換性のために予約されています。
@end deffn

@geindex RESERVED_FUTURE (uuid モジュール)
@anchor{library/uuid uuid RESERVED_FUTURE}@anchor{40a3}
@deffn {データ} uuid.RESERVED_FUTURE

将来のために予約されています。
@end deffn

The @code{uuid} module defines the special Nil and Max UUID values:

@geindex NIL (uuid モジュール)
@anchor{library/uuid uuid NIL}@anchor{2c5}
@deffn {データ} uuid.NIL

A special form of UUID that is specified to have all 128 bits set to zero
according to 
@geindex RFC; RFC 9562 Section 5.9
RFC 9562@comma{} §5.9@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.9}.


Added in version 3.14.

@end deffn

@geindex MAX (uuid モジュール)
@anchor{library/uuid uuid MAX}@anchor{2c6}
@deffn {データ} uuid.MAX

A special form of UUID that is specified to have all 128 bits set to one
according to 
@geindex RFC; RFC 9562 Section 5.10
RFC 9562@comma{} §5.10@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html#section-5.10}.


Added in version 3.14.

@end deffn


@subsubheading 参考



@table @asis

@geindex RFC; RFC 9562

@item RFC 9562@footnote{https://datatracker.ietf.org/doc/html/rfc9562.html} - A Universally Unique IDentifier (UUID) URN Namespace

この仕様は UUID のための Uniform Resource Name 名前空間、UUID の内部フォーマットと UUID の生成方法を定義しています。
@end table


@menu
* コマンドラインからの使用:: 
* 使用例: 使用例<39>. 
* Command-Line Example:: 

@end menu

@node コマンドラインからの使用,使用例<39>,,uuid --- RFC 9562 に基づく UUID オブジェクト
@anchor{library/uuid command-line-usage}@anchor{40a9}@anchor{library/uuid uuid-cli}@anchor{676}
@subsubsection コマンドラインからの使用



Added in version 3.12.


The @code{uuid} module can be executed as a script from the command line.

@example
python -m uuid [-h] [-u @{uuid1,uuid3,uuid4,uuid5,uuid6,uuid7,uuid8@}] [-n NAMESPACE] [-N NAME]
@end example

以下のオプションが使用できます:

@geindex uuid コマンドラインオプション; -h
@geindex uuid コマンドラインオプション; --help
@anchor{library/uuid cmdoption-uuid-h}@anchor{40aa}@anchor{library/uuid cmdoption-uuid-help}@anchor{40ab}
@deffn {Option} @w{-}h, @w{-}@w{-}help

ヘルプメッセージを表示して終了します。
@end deffn

@geindex uuid コマンドラインオプション; -u
@geindex uuid コマンドラインオプション; --uuid
@anchor{library/uuid cmdoption-uuid-u}@anchor{40ac}
@deffn {Option} @w{-}u <uuid>
@anchor{library/uuid cmdoption-uuid-uuid}@anchor{40ad}
@deffnx {Option} @w{-}@w{-}uuid <uuid>

Specify the function name to use to generate the uuid. By default @ref{2e7,,uuid4()}
is used.


バージョン 3.14 で変更: Allow generating UUID versions 6, 7 and 8.

@end deffn

@geindex uuid コマンドラインオプション; -n
@geindex uuid コマンドラインオプション; --namespace
@anchor{library/uuid cmdoption-uuid-n}@anchor{40ae}
@deffn {Option} @w{-}n <namespace>
@anchor{library/uuid cmdoption-uuid-namespace}@anchor{40af}
@deffnx {Option} @w{-}@w{-}namespace <namespace>

The namespace is a @code{UUID}, or @code{@@ns} where @code{ns} is a well-known predefined UUID
addressed by namespace name. Such as @code{@@dns}, @code{@@url}, @code{@@oid}, and @code{@@x500}.
Only required for @ref{2e5,,uuid3()} / @ref{2e6,,uuid5()} functions.
@end deffn

@geindex uuid コマンドラインオプション; -N
@geindex uuid コマンドラインオプション; --name
@anchor{library/uuid cmdoption-uuid-N}@anchor{40b0}
@deffn {Option} @w{-}N <name>
@anchor{library/uuid cmdoption-uuid-name}@anchor{40b1}
@deffnx {Option} @w{-}@w{-}name <name>

The name used as part of generating the uuid. Only required for
@ref{2e5,,uuid3()} / @ref{2e6,,uuid5()} functions.
@end deffn

@geindex uuid コマンドラインオプション; -C
@geindex uuid コマンドラインオプション; --count
@anchor{library/uuid cmdoption-uuid-C}@anchor{40b2}
@deffn {Option} @w{-}C <num>
@anchor{library/uuid cmdoption-uuid-count}@anchor{2c7}
@deffnx {Option} @w{-}@w{-}count <num>

Generate `num' fresh UUIDs.


Added in version 3.14.

@end deffn

@node 使用例<39>,Command-Line Example,コマンドラインからの使用,uuid --- RFC 9562 に基づく UUID オブジェクト
@anchor{library/uuid example}@anchor{40b3}@anchor{library/uuid uuid-example}@anchor{40b4}
@subsubsection 使用例


Here are some examples of typical usage of the @code{uuid} module:

@example
>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # 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')

>>> # get the Nil UUID
>>> uuid.NIL
UUID('00000000-0000-0000-0000-000000000000')

>>> # get the Max UUID
>>> uuid.MAX
UUID('ffffffff-ffff-ffff-ffff-ffffffffffff')

>>> # same as UUIDv1 but with fields reordered to improve DB locality
>>> uuid.uuid6()
UUID('1f0799c0-98b9-62db-92c6-a0d365b91053')

>>> # get UUIDv7 creation (local) time as a timestamp in milliseconds
>>> u = uuid.uuid7()
>>> u.time
1743936859822

>>> # get UUIDv7 creation (local) time as a datetime object
>>> import datetime as dt
>>> dt.datetime.fromtimestamp(u.time / 1000)
datetime.datetime(...)

>>> # make a UUID with custom blocks
>>> uuid.uuid8(0x12345678, 0x9abcdef0, 0x11223344)
UUID('00001234-5678-8ef0-8000-000011223344')
@end example

@node Command-Line Example,,使用例<39>,uuid --- RFC 9562 に基づく UUID オブジェクト
@anchor{library/uuid command-line-example}@anchor{40b5}@anchor{library/uuid uuid-cli-example}@anchor{40b6}
@subsubsection Command-Line Example


Here are some examples of typical usage of the @code{uuid} command-line interface:

@example
# generate a random UUID - by default uuid4() is used
$ python -m uuid

# generate a UUID using uuid1()
$ python -m uuid -u uuid1

# generate a UUID using uuid5
$ python -m uuid -u uuid5 -n @@url -N example.com

# generate 42 random UUIDs
$ python -m uuid -C 42
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node socketserver --- ネットワークサーバーのフレームワーク,http server --- HTTP サーバー,uuid --- RFC 9562 に基づく UUID オブジェクト,インターネットプロトコルとサポート
@anchor{library/socketserver doc}@anchor{40b7}@anchor{library/socketserver module-socketserver}@anchor{d2}@anchor{library/socketserver socketserver-a-framework-for-network-servers}@anchor{40b8}@anchor{library/socketserver translation-repo}@anchor{40b9}
@subsection @code{socketserver} --- ネットワークサーバーのフレームワーク


@geindex module; socketserver

`ソースコード:' Lib/socketserver.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/socketserver.py}


__________________________________________________________________


The @code{socketserver} module simplifies the task of writing network servers.

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

基本的な具象サーバクラスが4つあります:

@geindex TCPServer (socketserver のクラス)
@anchor{library/socketserver socketserver TCPServer}@anchor{1537}
@deffn {クラス} socketserver.TCPServer (server_address, RequestHandlerClass, bind_and_activate=True)

This uses the internet TCP protocol, which provides for
continuous streams of data between the client and server.
If `bind_and_activate' is true, the constructor automatically attempts to
invoke @ref{40ba,,server_bind()} and
@ref{40bb,,server_activate()}.  The other parameters are passed to
the @ref{1355,,BaseServer} base class.
@end deffn

@geindex UDPServer (socketserver のクラス)
@anchor{library/socketserver socketserver UDPServer}@anchor{40bc}
@deffn {クラス} socketserver.UDPServer (server_address, RequestHandlerClass, bind_and_activate=True)

This uses datagrams, which are discrete packets of information that may
arrive out of order or be lost while in transit.  The parameters are
the same as for @ref{1537,,TCPServer}.
@end deffn

@geindex UnixStreamServer (socketserver のクラス)
@geindex UnixDatagramServer (socketserver のクラス)
@anchor{library/socketserver socketserver UnixStreamServer}@anchor{40bd}
@deffn {クラス} socketserver.UnixStreamServer (server_address, RequestHandlerClass, bind_and_activate=True)
@anchor{library/socketserver socketserver UnixDatagramServer}@anchor{40be}
@deffnx {クラス} socketserver.UnixDatagramServer (server_address, RequestHandlerClass, bind_and_activate=True)

These more infrequently used classes are similar to the TCP and
UDP classes, but use Unix domain sockets; they're not available on
non-Unix platforms.  The parameters are the same as for
@ref{1537,,TCPServer}.
@end deffn

これらの 4 つのクラスは要求を `同期的に (synchronously)' 処理します; 各要求は次の要求を開始する前に完結していなければなりません。同期的な処理は、サーバで大量の計算を必要とする、あるいはクライアントが処理するには時間がかかりすぎるような大量のデータを返す、といった理由によってリクエストに長い時間がかかる状況には向いていません。こうした状況の解決方法は別のプロセスを生成するか、個々の要求を扱うスレッドを生成することです;  @ref{d71,,ForkingMixIn} および @ref{d3a,,ThreadingMixIn} 配合クラス (mix-in classes) を使えば、非同期的な動作をサポートできます。

サーバの作成にはいくつかのステップが必要です。最初に、 @ref{40bf,,BaseRequestHandler} クラスをサブクラス化して要求処理クラス (request hander class) を生成し、その @ref{40c0,,handle()} メソッドをオーバーライドしなければなりません; このメソッドは入力される要求を処理します。次に、サーバクラスのうち一つを、サーバのアドレスと要求処理クラスを渡してインスタンス化しなければなりません。サーバを @ref{186,,with} 文中で使うことが推奨されます。そして、@ref{153a,,handle_request()} または @ref{1357,,serve_forever()} メソッドを呼び出して、一つのまたは多数の要求を処理します。最後に、(@code{with} 文を使っていなかったなら) @ref{d6f,,server_close()} を呼び出してソケットを閉じます。

@ref{d3a,,ThreadingMixIn} から継承してスレッドを利用した接続を行う場合、突発的な通信切断時の処理を明示的に指定する必要があります。 @ref{d3a,,ThreadingMixIn} クラスには `daemon_threads' 属性があり、サーバがスレッドの終了を待ち合わせるかどうかを指定する事ができます。スレッドが独自の処理を行う場合は、このフラグを明示的に指定します。デフォルトは @ref{d2b,,False} で、Pythonは @ref{d3a,,ThreadingMixIn} クラスが起動した全てのスレッドが終了するまで実行し続けます。

サーバクラス群は使用するネットワークプロトコルに関わらず、同じ外部メソッドおよび属性を持ちます。

@menu
* サーバ生成に関するノート:: 
* Serverオブジェクト: Serverオブジェクト<2>. 
* Request Handler Objects:: 
* 使用例: 使用例<40>. 

@end menu

@node サーバ生成に関するノート,Serverオブジェクト<2>,,socketserver --- ネットワークサーバーのフレームワーク
@anchor{library/socketserver server-creation-notes}@anchor{40c1}
@subsubsection サーバ生成に関するノート


継承図にある五つのクラスのうち四つは四種類の同期サーバを表わしています:

@example
+------------+
| BaseServer |
+------------+
      |
      v
+-----------+        +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+        +------------------+
      |
      v
+-----------+        +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+        +--------------------+
@end example

@ref{40be,,UnixDatagramServer} は @ref{40bc,,UDPServer} から派生していて、 @ref{40bd,,UnixStreamServer} からではないことに注意してください --- IP と Unix サーバの唯一の違いはアドレスファミリーです。

@geindex ForkingMixIn (socketserver のクラス)
@geindex ThreadingMixIn (socketserver のクラス)
@anchor{library/socketserver socketserver ForkingMixIn}@anchor{d71}
@deffn {クラス} socketserver.ForkingMixIn
@anchor{library/socketserver socketserver ThreadingMixIn}@anchor{d3a}
@deffnx {クラス} socketserver.ThreadingMixIn

それぞれのタイプのサーバのフォークしたりスレッド実行したりするバージョンはそれらのミクシン(mix-in)クラスを使って作ることができます。たとえば、@ref{40c2,,ThreadingUDPServer} は以下のようにして作られます:

@example
class ThreadingUDPServer(ThreadingMixIn, UDPServer):
    pass
@end example

ミクシンクラスは @ref{40bc,,UDPServer} で定義されるメソッドをオーバライドするために、最初に来ます。様々な属性を設定することで元になるサーバ機構の振る舞いを変えられます。

@ref{d71,,ForkingMixIn} and the Forking classes mentioned below are
only available on POSIX platforms that support @ref{4b5,,fork()}.

@geindex block_on_close (socketserver.ThreadingMixIn の属性)
@anchor{library/socketserver socketserver ThreadingMixIn block_on_close}@anchor{d70}
@deffn {の属性} block_on_close

@ref{d6f,,ForkingMixIn.server_close}
waits until all child processes complete, except if
@ref{d70,,block_on_close} attribute is @code{False}.

@ref{d6f,,ThreadingMixIn.server_close}
waits until all non-daemon threads complete, except if
@ref{d70,,block_on_close} attribute is @code{False}.
@end deffn

@geindex max_children (socketserver.ThreadingMixIn の属性)
@anchor{library/socketserver socketserver ThreadingMixIn max_children}@anchor{40c3}
@deffn {の属性} max_children

Specify how many child processes will exist to handle requests at a time
for @ref{d71,,ForkingMixIn}.  If the limit is reached,
new requests will wait until one child process has finished.
@end deffn

@geindex daemon_threads (socketserver.ThreadingMixIn の属性)
@anchor{library/socketserver socketserver ThreadingMixIn daemon_threads}@anchor{40c4}
@deffn {の属性} daemon_threads

For @ref{d3a,,ThreadingMixIn} use daemonic threads by setting
@ref{40c4,,ThreadingMixIn.daemon_threads}
to @code{True} to not wait until threads complete.
@end deffn


バージョン 3.7 で変更: @ref{d6f,,ForkingMixIn.server_close} and
@ref{d6f,,ThreadingMixIn.server_close} now waits until all
child processes and non-daemonic threads complete.
Add a new @ref{d70,,ForkingMixIn.block_on_close} class
attribute to opt-in for the pre-3.7 behaviour.

@end deffn

@geindex ForkingTCPServer (socketserver のクラス)
@geindex ForkingUDPServer (socketserver のクラス)
@geindex ThreadingTCPServer (socketserver のクラス)
@geindex ThreadingUDPServer (socketserver のクラス)
@geindex ForkingUnixStreamServer (socketserver のクラス)
@geindex ForkingUnixDatagramServer (socketserver のクラス)
@geindex ThreadingUnixStreamServer (socketserver のクラス)
@geindex ThreadingUnixDatagramServer (socketserver のクラス)
@anchor{library/socketserver socketserver ForkingTCPServer}@anchor{40c5}
@deffn {クラス} socketserver.ForkingTCPServer
@anchor{library/socketserver socketserver ForkingUDPServer}@anchor{40c6}
@deffnx {クラス} socketserver.ForkingUDPServer
@anchor{library/socketserver socketserver ThreadingTCPServer}@anchor{40c7}
@deffnx {クラス} socketserver.ThreadingTCPServer
@anchor{library/socketserver socketserver ThreadingUDPServer}@anchor{40c2}
@deffnx {クラス} socketserver.ThreadingUDPServer
@anchor{library/socketserver socketserver ForkingUnixStreamServer}@anchor{40c8}
@deffnx {クラス} socketserver.ForkingUnixStreamServer
@anchor{library/socketserver socketserver ForkingUnixDatagramServer}@anchor{40c9}
@deffnx {クラス} socketserver.ForkingUnixDatagramServer
@anchor{library/socketserver socketserver ThreadingUnixStreamServer}@anchor{40ca}
@deffnx {クラス} socketserver.ThreadingUnixStreamServer
@anchor{library/socketserver socketserver ThreadingUnixDatagramServer}@anchor{40cb}
@deffnx {クラス} socketserver.ThreadingUnixDatagramServer

These classes are pre-defined using the mix-in classes.
@end deffn


Added in version 3.12: The @code{ForkingUnixStreamServer} and @code{ForkingUnixDatagramServer} classes
were added.


サービスの実装には、 @ref{40bf,,BaseRequestHandler} からクラスを派生させてその @ref{40c0,,handle()} メソッドを再定義しなければなりません。このようにすれば、サーバクラスと要求処理クラスを結合して様々なバージョンのサービスを実行することができます。要求処理クラスはデータグラムサービスかストリームサービスかで異なることでしょう。この違いは処理サブクラス @ref{ed6,,StreamRequestHandler} または @ref{40cc,,DatagramRequestHandler} を使うという形で隠蔽できます。

もちろん、まだ頭を使わなければなりません! たとえば、サービスがリクエストによっては書き換えられるようなメモリ上の状態を使うならば、フォークするサーバを使うのは馬鹿げています。というのも子プロセスでの書き換えは親プロセスで保存されている初期状態にも親プロセスから分配される各子プロセスの状態にも届かないからです。この場合、スレッド実行するサーバを使うことはできますが、共有データの一貫性を保つためにロックを使わなければならなくなるでしょう。

一方、全てのデータが外部に(たとえばファイルシステムに)保存される HTTP サーバを作っているのだとすると、同期クラスではどうしても一つの要求が処理されている間サービスが「耳の聞こえない」状態を呈することになります --- この状態はもしクライアントが要求した全てのデータをゆっくり受け取るととても長い時間続きかねません。こういう場合にはサーバをスレッド実行したりフォークすることが適切です。

ある場合には、要求の一部を同期的に処理する一方で、要求データに依って子プロセスをフォークして処理を終了させる、といった方法も適当かもしれません。こうした処理方法は同期サーバを使って要求処理クラスの @ref{40c0,,handle()} メソッドの中で自分でフォークするようにして実装することができます。

Another approach to handling multiple simultaneous requests in an environment
that supports neither threads nor @ref{4b5,,fork()} (or where these are too
expensive or inappropriate for the service) is to maintain an explicit table of
partially finished requests and to use @ref{c7,,selectors} to decide which
request to work on next (or whether to handle a new incoming request).  This is
particularly important for stream services where each client can potentially be
connected for a long time (if threads or subprocesses cannot be used).

@c XXX should data and methods be intermingled, or separate?
@c how should the distinction between class and instance variables be drawn?

@node Serverオブジェクト<2>,Request Handler Objects,サーバ生成に関するノート,socketserver --- ネットワークサーバーのフレームワーク
@anchor{library/socketserver server-objects}@anchor{40cd}
@subsubsection Serverオブジェクト


@geindex BaseServer (socketserver のクラス)
@anchor{library/socketserver socketserver BaseServer}@anchor{1355}
@deffn {クラス} socketserver.BaseServer (server_address, RequestHandlerClass)

This is the superclass of all Server objects in the module.  It defines the
interface, given below, but does not implement most of the methods, which is
done in subclasses.  The two parameters are stored in the respective
@ref{40ce,,server_address} and @ref{40cf,,RequestHandlerClass} attributes.

@geindex fileno() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer fileno}@anchor{40d0}
@deffn {メソッド} fileno ()

サーバが要求待ちを行っているソケットのファイル記述子を整数で返します。この関数は一般的に、同じプロセス中の複数のサーバを監視できるようにするために、 @ref{c7,,selectors} に渡されます。
@end deffn

@geindex handle_request() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer handle_request}@anchor{153a}
@deffn {メソッド} handle_request ()

単一の要求を処理します。この関数は以下のメソッド: @ref{40d1,,get_request()} 、 @ref{40d2,,verify_request()} 、および @ref{40d3,,process_request()} を順番に呼び出します。ハンドラ中でユーザによって提供された @ref{40c0,,handle()} が例外を送出した場合、サーバの @ref{f3d,,handle_error()} メソッドが呼び出されます。 @ref{1538,,timeout} 秒以内にリクエストが来なかった場合、 @ref{1539,,handle_timeout()} が呼ばれて、 @ref{153a,,handle_request()} が終了します。
@end deffn

@geindex serve_forever() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer serve_forever}@anchor{1357}
@deffn {メソッド} serve_forever (poll_interval=0.5)

Handle requests until an explicit @ref{1e16,,shutdown()} request.  Poll for
shutdown every `poll_interval' seconds.
Ignores the @ref{1538,,timeout} attribute.  It
also calls @ref{1356,,service_actions()}, which may be used by a subclass or mixin
to provide actions specific to a given service.  For example, the
@ref{d71,,ForkingMixIn} class uses @ref{1356,,service_actions()} to clean up zombie
child processes.


バージョン 3.3 で変更: Added @code{service_actions} call to the @code{serve_forever} method.

@end deffn

@geindex service_actions() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer service_actions}@anchor{1356}
@deffn {メソッド} service_actions ()

This is called in the @ref{1357,,serve_forever()} loop. This method can be
overridden by subclasses or mixin classes to perform actions specific to
a given service, such as cleanup actions.


Added in version 3.3.

@end deffn

@geindex shutdown() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer shutdown}@anchor{1e16}
@deffn {メソッド} shutdown ()

Tell the @ref{1357,,serve_forever()} loop to stop and wait until it does.
@ref{1e16,,shutdown()} must be called while @ref{1357,,serve_forever()} is running in a
different thread otherwise it will deadlock.
@end deffn

@geindex server_close() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer server_close}@anchor{d6f}
@deffn {メソッド} server_close ()

サーバをクリーンアップします。上書き出来ます。
@end deffn

@geindex address_family (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer address_family}@anchor{40d4}
@deffn {の属性} address_family

The family of protocols to which the server's socket belongs.  Common
examples are @ref{1bad,,socket.AF_INET}, @ref{1bae,,socket.AF_INET6}, and
@ref{1bb0,,socket.AF_UNIX}.  Subclass the TCP or UDP server classes in this
module with class attribute @code{address_family = AF_INET6} set if you
want IPv6 server classes.
@end deffn

@geindex RequestHandlerClass (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer RequestHandlerClass}@anchor{40cf}
@deffn {の属性} RequestHandlerClass

ユーザが提供する要求処理クラスです; 要求ごとにこのクラスのインスタンスが生成されます。
@end deffn

@geindex server_address (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer server_address}@anchor{40ce}
@deffn {の属性} server_address

サーバが要求待ちを行うアドレスです。アドレスの形式はプロトコルファミリによって異なります。詳細は @ref{d1,,socket} モジュールを参照してください。インターネットプロトコルでは、この値は例えば @code{('127.0.0.1', 80)} のようにアドレスを与える文字列と整数のポート番号を含むタプルです。
@end deffn

@geindex socket (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer socket}@anchor{40d5}
@deffn {の属性} socket

サーバが入力の要求待ちを行うためのソケットオブジェクトです。
@end deffn

サーバクラスは以下のクラス変数をサポートします:

@c XXX should class variables be covered before instance variables, or vice versa?

@geindex allow_reuse_address (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer allow_reuse_address}@anchor{40d6}
@deffn {の属性} allow_reuse_address

サーバがアドレスの再使用を許すかどうかを示す値です。この値は標準で @ref{d2b,,False} で、サブクラスで再使用ポリシを変更するために設定することができます。
@end deffn

@geindex request_queue_size (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer request_queue_size}@anchor{40d7}
@deffn {の属性} request_queue_size

要求待ち行列 (queue) のサイズです。単一の要求を処理するのに長時間かかる場合には、サーバが処理中に届いた要求は最大 @ref{40d7,,request_queue_size} 個まで待ち行列に置かれます。待ち行列が一杯になると、それ以降のクライアントからの要求は "接続拒否 (Connection denied)" エラーになります。標準の値は通常 5 ですが、この値はサブクラスで上書きすることができます。
@end deffn

@geindex socket_type (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer socket_type}@anchor{40d8}
@deffn {の属性} socket_type

サーバが使うソケットの型です; 一般的な2つの値は、 @ref{150b,,socket.SOCK_STREAM} と @ref{150a,,socket.SOCK_DGRAM} です。
@end deffn

@geindex timeout (socketserver.BaseServer の属性)
@anchor{library/socketserver socketserver BaseServer timeout}@anchor{1538}
@deffn {の属性} timeout

タイムアウト時間(秒)、もしくは、タイムアウトを望まない場合に @ref{885,,None} 。 @ref{153a,,handle_request()} がこの時間内にリクエストを受信しない場合、 @ref{1539,,handle_timeout()} メソッドが呼ばれます。
@end deffn

@ref{1537,,TCPServer} のような基底クラスのサブクラスで上書きできるサーバメソッドは多数あります; これらのメソッドはサーバオブジェクトの外部のユーザにとっては役にたたないものです。

@c XXX should the default implementations of these be documented, or should
@c it be assumed that the user will look at socketserver.py?

@geindex finish_request() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer finish_request}@anchor{40d9}
@deffn {メソッド} finish_request (request, client_address)

@ref{40cf,,RequestHandlerClass} をインスタンス化し、 @ref{40c0,,handle()} メソッドを呼び出して、実際に要求を処理します。
@end deffn

@geindex get_request() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer get_request}@anchor{40d1}
@deffn {メソッド} get_request ()

ソケットから要求を受理して、クライアントとの通信に使われる `新しい' ソケットオブジェクト、およびクライアントのアドレスからなる、2 要素のタプルを返します。
@end deffn

@geindex handle_error() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer handle_error}@anchor{f3d}
@deffn {メソッド} handle_error (request, client_address)

この関数は @ref{40cf,,RequestHandlerClass} インスタンスの @ref{40c0,,handle()} メソッドが例外を送出した際に呼び出されます。標準の動作では標準エラー出力へトレースバックを出力し、後続する要求を継続して処理します。


バージョン 3.6 で変更: Now only called for exceptions derived from the @ref{bcd,,Exception}
class.

@end deffn

@geindex handle_timeout() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer handle_timeout}@anchor{1539}
@deffn {メソッド} handle_timeout ()

この関数は @ref{1538,,timeout} 属性が @ref{885,,None} 以外に設定されて、リクエストがないままタイムアウト秒数が過ぎたときに呼ばれます。 fork型サーバーでのデフォルトの動作は、終了した子プロセスの情報を集めるようになっています。スレッド型サーバーではこのメソッドは何もしません。
@end deffn

@geindex process_request() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer process_request}@anchor{40d3}
@deffn {メソッド} process_request (request, client_address)

@ref{40d9,,finish_request()} を呼び出して、 @ref{40cf,,RequestHandlerClass} のインスタンスを生成します。必要なら、この関数から新たなプロセスかスレッドを生成して要求を処理することができます; その処理は @ref{d71,,ForkingMixIn} または @ref{d3a,,ThreadingMixIn}  クラスが行います。
@end deffn

@c Is there any point in documenting the following two functions?
@c What would the purpose of overriding them be: initializing server
@c instance variables, adding new network families?

@geindex server_activate() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer server_activate}@anchor{40bb}
@deffn {メソッド} server_activate ()

Called by the server's constructor to activate the server.  The default behavior
for a TCP server just invokes @ref{105e,,listen()}
on the server's socket.  May be overridden.
@end deffn

@geindex server_bind() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer server_bind}@anchor{40ba}
@deffn {メソッド} server_bind ()

サーバのコンストラクタによって呼び出され、適切なアドレスにソケットをバインドします。このメソッドは上書きできます。
@end deffn

@geindex verify_request() (socketserver.BaseServer のメソッド)
@anchor{library/socketserver socketserver BaseServer verify_request}@anchor{40d2}
@deffn {メソッド} verify_request (request, client_address)

ブール値を返さなければなりません; 値が @ref{e07,,True} の場合には要求が処理され、 @ref{d2b,,False} の場合には要求は拒否されます。サーバへのアクセス制御を実装するためにこの関数を上書きすることができます。標準の実装では常に @ref{e07,,True} を返します。
@end deffn


バージョン 3.6 で変更: @ref{1e1,,context manager} プロトコルのサポートが追加されました。コンテキストマネージャを終了することは、 @ref{d6f,,server_close()} を呼ぶことと同一です。

@end deffn

@node Request Handler Objects,使用例<40>,Serverオブジェクト<2>,socketserver --- ネットワークサーバーのフレームワーク
@anchor{library/socketserver request-handler-objects}@anchor{40da}
@subsubsection Request Handler Objects


@geindex BaseRequestHandler (socketserver のクラス)
@anchor{library/socketserver socketserver BaseRequestHandler}@anchor{40bf}
@deffn {クラス} socketserver.BaseRequestHandler

This is the superclass of all request handler objects.  It defines
the interface, given below.  A concrete request handler subclass must
define a new @ref{40c0,,handle()} method, and can override any of
the other methods.  A new instance of the subclass is created for each
request.

@geindex setup() (socketserver.BaseRequestHandler のメソッド)
@anchor{library/socketserver socketserver BaseRequestHandler setup}@anchor{40db}
@deffn {メソッド} setup ()

@ref{40c0,,handle()}   メソッドより前に呼び出され、何らかの必要な初期化処理を行います。標準の実装では何も行いません。
@end deffn

@geindex handle() (socketserver.BaseRequestHandler のメソッド)
@anchor{library/socketserver socketserver BaseRequestHandler handle}@anchor{40c0}
@deffn {メソッド} handle ()

This function must do all the work required to service a request.  The
default implementation does nothing.  Several instance attributes are
available to it; the request is available as @ref{40dc,,request}; the client
address as @ref{40dd,,client_address}; and the server instance as
@ref{40de,,server}, in case it needs access to per-server information.

The type of @ref{40dc,,request} is different for datagram or stream
services.  For stream services, @ref{40dc,,request} is a socket object; for
datagram services, @ref{40dc,,request} is a pair of string and socket.
@end deffn

@geindex finish() (socketserver.BaseRequestHandler のメソッド)
@anchor{library/socketserver socketserver BaseRequestHandler finish}@anchor{40df}
@deffn {メソッド} finish ()

@ref{40c0,,handle()}   メソッドより後に呼び出され、何らかの必要なクリーンアップ処理を行います。標準の実装では何も行いません。 @ref{40db,,setup()} メソッドが例外を送出した場合、このメソッドは呼び出されません。
@end deffn

@geindex request (socketserver.BaseRequestHandler の属性)
@anchor{library/socketserver socketserver BaseRequestHandler request}@anchor{40dc}
@deffn {の属性} request

The `new' @ref{fa1,,socket.socket} object
to be used to communicate with the client.
@end deffn

@geindex client_address (socketserver.BaseRequestHandler の属性)
@anchor{library/socketserver socketserver BaseRequestHandler client_address}@anchor{40dd}
@deffn {の属性} client_address

Client address returned by @ref{40d1,,BaseServer.get_request()}.
@end deffn

@geindex server (socketserver.BaseRequestHandler の属性)
@anchor{library/socketserver socketserver BaseRequestHandler server}@anchor{40de}
@deffn {の属性} server

@ref{1355,,BaseServer} object used for handling the request.
@end deffn
@end deffn

@geindex StreamRequestHandler (socketserver のクラス)
@geindex DatagramRequestHandler (socketserver のクラス)
@anchor{library/socketserver socketserver StreamRequestHandler}@anchor{ed6}
@deffn {クラス} socketserver.StreamRequestHandler
@anchor{library/socketserver socketserver DatagramRequestHandler}@anchor{40cc}
@deffnx {クラス} socketserver.DatagramRequestHandler

These @ref{40bf,,BaseRequestHandler} subclasses override the
@ref{40db,,setup()} and @ref{40df,,finish()}
methods, and provide @ref{40e0,,rfile} and @ref{ed5,,wfile} attributes.

@geindex rfile (socketserver.DatagramRequestHandler の属性)
@anchor{library/socketserver socketserver DatagramRequestHandler rfile}@anchor{40e0}
@deffn {の属性} rfile

A file object from which receives the request is read.
Support the @ref{8a3,,io.BufferedIOBase} readable interface.
@end deffn

@geindex wfile (socketserver.DatagramRequestHandler の属性)
@anchor{library/socketserver socketserver DatagramRequestHandler wfile}@anchor{ed5}
@deffn {の属性} wfile

A file object to which the reply is written.
Support the @ref{8a3,,io.BufferedIOBase} writable interface
@end deffn


バージョン 3.6 で変更: @ref{ed5,,wfile} also supports the
@ref{8a3,,io.BufferedIOBase} writable interface.

@end deffn

@node 使用例<40>,,Request Handler Objects,socketserver --- ネットワークサーバーのフレームワーク
@anchor{library/socketserver examples}@anchor{40e1}
@subsubsection 使用例


@menu
* socketserver.TCPServer の例: socketserver TCPServer の例. 
* socketserver.UDPServer の例: socketserver UDPServer の例. 
* 非同期処理の Mix-in:: 

@end menu

@node socketserver TCPServer の例,socketserver UDPServer の例,,使用例<40>
@anchor{library/socketserver socketserver-tcpserver-example}@anchor{40e2}
@subsubsection @code{socketserver.TCPServer} の例


サーバサイドの例です:

@example
import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        pieces = [b'@w{'}]
        total = 0
        while b'\n' not in pieces[-1] and total < 10_000:
            pieces.append(self.request.recv(2000))
            total += len(pieces[-1])
        self.data = b'@w{'}.join(pieces)
        print(f"Received from @{self.client_address[0]@}:")
        print(self.data.decode("utf-8"))
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())
        # after we return, the socket will be closed.

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()
@end example

別の、ストリーム(標準のファイル型のインターフェースを利用して通信をシンプルにしたファイルライクオブジェクト)を使うリクエストハンドラクラスの例です:

@example
class MyTCPHandler(socketserver.StreamRequestHandler):

    def handle(self):
        # self.rfile is a file-like object created by the handler.
        # We can now use e.g. readline() instead of raw recv() calls.
        # We limit ourselves to 10000 bytes to avoid abuse by the sender.
        self.data = self.rfile.readline(10000).rstrip()
        print(f"@{self.client_address[0]@} wrote:")
        print(self.data.decode("utf-8"))
        # Likewise, self.wfile is a file-like object used to write back
        # to the client
        self.wfile.write(self.data.upper())
@end example

The difference is that the @code{readline()} call in the second handler will call
@code{recv()} multiple times until it encounters a newline character, while the
first handler had to use a @code{recv()} loop to accumulate data until a
newline itself.  If it had just used a single @code{recv()} without the loop it
would just have returned what has been received so far from the client.
TCP is stream based: data arrives in the order it was sent, but there is no
correlation between client @code{send()} or @code{sendall()} calls and the number
of @code{recv()} calls on the server required to receive it.

クライアントサイドの例:

@example
import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data, "utf-8"))
    sock.sendall(b"\n")

    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")

print("Sent:    ", data)
print("Received:", received)
@end example

この例の出力は次のようになります:

サーバー:

@example
$ python TCPServer.py
127.0.0.1 wrote:
b'hello world with TCP'
127.0.0.1 wrote:
b'python is nice'
@end example

クライアント:

@example
$ python TCPClient.py hello world with TCP
Sent:     hello world with TCP
Received: HELLO WORLD WITH TCP
$ python TCPClient.py python is nice
Sent:     python is nice
Received: PYTHON IS NICE
@end example

@node socketserver UDPServer の例,非同期処理の Mix-in,socketserver TCPServer の例,使用例<40>
@anchor{library/socketserver socketserver-udpserver-example}@anchor{40e3}
@subsubsection @code{socketserver.UDPServer} の例


サーバサイドの例です:

@example
import socketserver

class MyUDPHandler(socketserver.BaseRequestHandler):
    """
    This class works similar to the TCP handler class, except that
    self.request consists of a pair of data and client socket, and since
    there is no connection the client address must be given explicitly
    when sending data back via sendto().
    """

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        print(f"@{self.client_address[0]@} wrote:")
        print(data)
        socket.sendto(data.upper(), self.client_address)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
        server.serve_forever()
@end example

クライアントサイドの例:

@example
import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT))
received = str(sock.recv(1024), "utf-8")

print("Sent:    ", data)
print("Received:", received)
@end example

この例の出力は、TCPサーバーの例と全く同じようになります。

@node 非同期処理の Mix-in,,socketserver UDPServer の例,使用例<40>
@anchor{library/socketserver asynchronous-mixins}@anchor{40e4}
@subsubsection 非同期処理の Mix-in


複数の接続を非同期に処理するハンドラを作るには、 @ref{d3a,,ThreadingMixIn} か @ref{d71,,ForkingMixIn} クラスを利用します。

@ref{d3a,,ThreadingMixIn} クラスの利用例:

@example
import socket
import threading
import socketserver

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = str(self.request.recv(1024), 'ascii')
        cur_thread = threading.current_thread()
        response = bytes("@{@}: @{@}".format(cur_thread.name, data), 'ascii')
        self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

def client(ip, port, message):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((ip, port))
        sock.sendall(bytes(message, 'ascii'))
        response = str(sock.recv(1024), 'ascii')
        print("Received: @{@}".format(response))

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "localhost", 0

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    with server:
        ip, port = server.server_address

        # Start a thread with the server -- that thread will then start one
        # more thread for each request
        server_thread = threading.Thread(target=server.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.daemon = True
        server_thread.start()
        print("Server loop running in thread:", server_thread.name)

        client(ip, port, "Hello World 1")
        client(ip, port, "Hello World 2")
        client(ip, port, "Hello World 3")

        server.shutdown()
@end example

この例の出力は次のようになります:

@example
$ python ThreadedTCPServer.py
Server loop running in thread: Thread-1
Received: Thread-2: Hello World 1
Received: Thread-3: Hello World 2
Received: Thread-4: Hello World 3
@end example

@ref{d71,,ForkingMixIn} クラスは同じように利用することができます。この場合、サーバーはリクエスト毎に新しいプロセスを作成します。@ref{4b5,,fork()} をサポートする POSIX プラットフォームでのみ利用可能です。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node http server --- HTTP サーバー,http cookies --- HTTP の状態管理,socketserver --- ネットワークサーバーのフレームワーク,インターネットプロトコルとサポート
@anchor{library/http server doc}@anchor{40e5}@anchor{library/http server http-server-http-servers}@anchor{40e6}@anchor{library/http server module-http server}@anchor{76}@anchor{library/http server translation-repo}@anchor{40e7}
@subsection @code{http.server} --- HTTP サーバー


@geindex module; http.server

`ソースコード:' Lib/http/server.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/http/server.py}

@geindex WWW;サーバ
@geindex HTTP;プロトコル
@geindex URL
@geindex httpd


__________________________________________________________________


このモジュールは HTTP サーバを実装するためのクラスを提供しています。

@cartouche
@quotation 警告 
@code{http.server} is not recommended for production. It only implements
@ref{40e8,,basic security checks}.
@end quotation
@end cartouche

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

クラス @ref{3ee5,,HTTPServer} は @ref{1537,,socketserver.TCPServer} のサブクラスです。
@ref{3ee5,,HTTPServer} は HTTP ソケットを生成してリクエスト待ち (listen) を行い、リクエストをハンドラに渡します。
サーバを作成して動作させるためのコードは以下のようになります:

@example
def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('@w{'}, 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()
@end example

@geindex HTTPServer (http.server のクラス)
@anchor{library/http server http server HTTPServer}@anchor{3ee5}
@deffn {クラス} http.server.HTTPServer (server_address, RequestHandlerClass)

このクラスは @ref{1537,,TCPServer} クラスの上に構築されており、サーバのアドレスをインスタンス変数 @code{server_name} および @code{server_port} に記憶します。
サーバはハンドラからアクセス可能で、通常ハンドラの @code{server} インスタンス変数からアクセスします。
@end deffn

@geindex ThreadingHTTPServer (http.server のクラス)
@anchor{library/http server http server ThreadingHTTPServer}@anchor{d39}
@deffn {クラス} http.server.ThreadingHTTPServer (server_address, RequestHandlerClass)

This class is identical to HTTPServer but uses threads to handle
requests by using the @ref{d3a,,ThreadingMixIn}. This
is useful to handle web browsers pre-opening sockets, on which
@ref{3ee5,,HTTPServer} would wait indefinitely.


Added in version 3.7.

@end deffn

@geindex HTTPSServer (http.server のクラス)
@anchor{library/http server http server HTTPSServer}@anchor{228}
@deffn {クラス} http.server.HTTPSServer (server_address, RequestHandlerClass, bind_and_activate=True, *, certfile, keyfile=None, password=None, alpn_protocols=None)

Subclass of @ref{3ee5,,HTTPServer} with a wrapped socket using the @ref{d5,,ssl} module.
If the @ref{d5,,ssl} module is not available, instantiating a @code{HTTPSServer}
object fails with a @ref{244,,RuntimeError}.

The `certfile' argument is the path to the SSL certificate chain file,
and the `keyfile' is the path to file containing the private key.

A `password' can be specified for files protected and wrapped with PKCS#8,
but beware that this could possibly expose hardcoded passwords in clear.


@subsubheading 参考


See @ref{598,,ssl.SSLContext.load_cert_chain()} for additional
information on the accepted values for `certfile', `keyfile'
and `password'.


When specified, the `alpn_protocols' argument must be a sequence of strings
specifying the "Application-Layer Protocol Negotiation" (ALPN) protocols
supported by the server. ALPN allows the server and the client to negotiate
the application protocol during the TLS handshake.

By default, it is set to @code{["http/1.1"]}, meaning the server supports HTTP/1.1.


Added in version 3.14.

@end deffn

@geindex ThreadingHTTPSServer (http.server のクラス)
@anchor{library/http server http server ThreadingHTTPSServer}@anchor{40e9}
@deffn {クラス} http.server.ThreadingHTTPSServer (server_address, RequestHandlerClass, bind_and_activate=True, *, certfile, keyfile=None, password=None, alpn_protocols=None)

This class is identical to @ref{228,,HTTPSServer} but uses threads to handle
requests by inheriting from @ref{d3a,,ThreadingMixIn}. This is
analogous to @ref{d39,,ThreadingHTTPServer} only using @ref{228,,HTTPSServer}.


Added in version 3.14.

@end deffn

The @ref{3ee5,,HTTPServer}, @ref{d39,,ThreadingHTTPServer}, @ref{228,,HTTPSServer} and
@ref{40e9,,ThreadingHTTPSServer} must be given a `RequestHandlerClass' on
instantiation, of which this module provides three different variants:

@geindex BaseHTTPRequestHandler (http.server のクラス)
@anchor{library/http server http server BaseHTTPRequestHandler}@anchor{12e2}
@deffn {クラス} http.server.BaseHTTPRequestHandler (request, client_address, server)

このクラスはサーバに到着したリクエストを処理します。
このメソッド自体では、実際のリクエストに応答することはできません; (GET や POST のような) 各リクエストメソッドを処理するためにはサブクラス化しなければなりません。
@ref{12e2,,BaseHTTPRequestHandler} では、サブクラスで使うためのクラスやインスタンス変数、メソッド群を数多く提供しています。

The handler will parse the request and the headers, then call a method
specific to the request type. The method name is constructed from the
request. For example, for the request method @code{SPAM}, the @code{do_SPAM()}
method will be called with no arguments. All of the relevant information is
stored in instance variables of the handler.  Subclasses should not need to
override or extend the @code{__init__()} method.

@ref{12e2,,BaseHTTPRequestHandler} は以下のインスタンス変数を持っています:

@geindex client_address (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler client_address}@anchor{40ea}
@deffn {の属性} client_address

HTTP クライアントのアドレスを参照している、@code{(host, port)} の形式をとるタプルが入っています。
@end deffn

@geindex server (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler server}@anchor{40eb}
@deffn {の属性} server

server インスタンスが入っています。
@end deffn

@geindex close_connection (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler close_connection}@anchor{40ec}
@deffn {の属性} close_connection

@ref{40ed,,handle_one_request()} が返る前に設定すべき真偽値で、別のリクエストが期待されているかどうか、もしくはコネクションを切断すべきかどうかを指し示しています。
@end deffn

@geindex requestline (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler requestline}@anchor{40ee}
@deffn {の属性} requestline

HTTP リクエスト行の文字列表現を保持しています。
末尾の CRLF は除去されています。
この属性は @ref{40ed,,handle_one_request()} によって設定されるべきです。
妥当なリクエスト行が1行も処理されなかった場合は、空文字列に設定されるべきです。
@end deffn

@geindex command (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler command}@anchor{40ef}
@deffn {の属性} command

HTTP 命令 (リクエスト形式) が入っています。例えば @code{'GET'} です。
@end deffn

@geindex path (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler path}@anchor{40f0}
@deffn {の属性} path

Contains the request path. If query component of the URL is present,
then @code{path} includes the query. Using the terminology of 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://datatracker.ietf.org/doc/html/rfc3986.html},
@code{path} here includes @code{hier-part} and the @code{query}.
@end deffn

@geindex request_version (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler request_version}@anchor{40f1}
@deffn {の属性} request_version

リクエストのバージョン文字列が入っています。例えば @code{'HTTP/1.0'} です。
@end deffn

@geindex headers (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler headers}@anchor{3fca}
@deffn {の属性} headers

Holds an instance of the class specified by the @ref{40f2,,MessageClass} class
variable. This instance parses and manages the headers in the HTTP
request. The @ref{1e28,,parse_headers()} function from
@ref{73,,http.client} is used to parse the headers and it requires that the
HTTP request provide a valid 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://datatracker.ietf.org/doc/html/rfc5322.html} style header.
@end deffn

@geindex rfile (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler rfile}@anchor{40f3}
@deffn {の属性} rfile

An @ref{8a3,,io.BufferedIOBase} input stream, ready to read from
the start of the optional input data.
@end deffn

@geindex wfile (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler wfile}@anchor{40f4}
@deffn {の属性} wfile

Contains the output stream for writing a response back to the
client. Proper adherence to the HTTP protocol must be used when writing to
this stream in order to achieve successful interoperation with HTTP
clients.


バージョン 3.6 で変更: This is an @ref{8a3,,io.BufferedIOBase} stream.

@end deffn

@ref{12e2,,BaseHTTPRequestHandler} は以下の属性を持っています:

@geindex server_version (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler server_version}@anchor{40f5}
@deffn {の属性} server_version

サーバのソフトウェアバージョンを指定します。この値は上書きする必要が生じるかもしれません。書式は複数の文字列を空白で分割したもので、各文字列はソフトウェア名[/バージョン] の形式をとります。例えば、@code{'BaseHTTP/0.2'} です。
@end deffn

@geindex sys_version (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler sys_version}@anchor{40f6}
@deffn {の属性} sys_version

Python 処理系のバージョンが, @ref{40f7,,version_string} メソッドや @ref{40f5,,server_version} クラス変数で利用可能な形式で入っています。例えば @code{'Python/1.4'} です。
@end deffn

@geindex error_message_format (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler error_message_format}@anchor{1152}
@deffn {の属性} error_message_format

Specifies a format string that should be used by @ref{1151,,send_error()} method
for building an error response to the client. The string is filled by
default with variables from @ref{3faf,,responses} based on the status code
that passed to @ref{1151,,send_error()}.
@end deffn

@geindex error_content_type (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler error_content_type}@anchor{40f8}
@deffn {の属性} error_content_type

エラーレスポンスをクライアントに送信する時に使う Content-Type HTTP ヘッダを指定します。デフォルトでは @code{'text/html'} です。
@end deffn

@geindex protocol_version (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler protocol_version}@anchor{40f9}
@deffn {の属性} protocol_version

Specifies the HTTP version to which the server is conformant. It is sent
in responses to let the client know the server's communication
capabilities for future requests. If set to
@code{'HTTP/1.1'}, the server will permit HTTP persistent connections;
however, your server `must' then include an accurate @code{Content-Length}
header (using @ref{40fa,,send_header()}) in all of its responses to clients.
For backwards compatibility, the setting defaults to @code{'HTTP/1.0'}.
@end deffn

@geindex MessageClass (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler MessageClass}@anchor{40f2}
@deffn {の属性} MessageClass

HTTP ヘッダを解釈するための @ref{581,,email.message.Message} 類似のクラスを指定します。
通常この値が上書きされることはなく、デフォルトの @ref{3fc8,,http.client.HTTPMessage} になっています。
@end deffn

@geindex responses (http.server.BaseHTTPRequestHandler の属性)
@anchor{library/http server http server BaseHTTPRequestHandler responses}@anchor{3faf}
@deffn {の属性} responses

This attribute contains a mapping of error code integers to two-element tuples
containing a short and long message. For example, @code{@{code: (shortmessage,
longmessage)@}}. The `shortmessage' is usually used as the `message' key in an
error response, and `longmessage' as the `explain' key.  It is used by
@ref{40fb,,send_response_only()} and @ref{1151,,send_error()} methods.
@end deffn

@ref{12e2,,BaseHTTPRequestHandler} インスタンスは以下のメソッドを持っています:

@geindex handle() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler handle}@anchor{40fc}
@deffn {メソッド} handle ()

Calls @ref{40ed,,handle_one_request()} once (or, if persistent connections are
enabled, multiple times) to handle incoming HTTP requests. You should
never need to override it; instead, implement appropriate @code{do_*()}
methods.
@end deffn

@geindex handle_one_request() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler handle_one_request}@anchor{40ed}
@deffn {メソッド} handle_one_request ()

This method will parse and dispatch the request to the appropriate
@code{do_*()} method.  You should never need to override it.
@end deffn

@geindex handle_expect_100() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler handle_expect_100}@anchor{40fd}
@deffn {メソッド} handle_expect_100 ()

HTTP/1.1 準拠のサーバが @code{Expect: 100-continue} リクエストヘッダを受け取ったとき、 @code{100 Continue} を返し、その後に @code{200 OK} がきます。
このメソッドは、サーバがクライアントに継続を要求しない場合、エラーを送出するようにオーバーライドできます。
例えば、サーバはレスポンスヘッダとして @code{417 Expectation Failed} を送る選択をし、 @code{return False} とできます。


Added in version 3.2.

@end deffn

@geindex send_error() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler send_error}@anchor{1151}
@deffn {メソッド} send_error (code, message=None, explain=None)

Sends and logs a complete error reply to the client. The numeric `code'
specifies the HTTP error code, with `message' as an optional, short, human
readable description of the error.  The `explain' argument can be used to
provide more detailed information about the error; it will be formatted
using the @ref{1152,,error_message_format} attribute and emitted, after
a complete set of headers, as the response body.  The @ref{3faf,,responses}
attribute holds the default values for `message' and `explain' that
will be used if no value is provided; for unknown codes the default value
for both is the string @code{???}. The body will be empty if the method is
HEAD or the response code is one of the following: @code{1@var{xx}},
@code{204 No Content}, @code{205 Reset Content}, @code{304 Not Modified}.


バージョン 3.4 で変更: The error response includes a Content-Length header.
Added the `explain' argument.

@end deffn

@geindex send_response() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler send_response}@anchor{40fe}
@deffn {メソッド} send_response (code, message=None)

Adds a response header to the headers buffer and logs the accepted
request. The HTTP response line is written to the internal buffer,
followed by `Server' and `Date' headers. The values for these two headers
are picked up from the @ref{40f7,,version_string()} and
@ref{40ff,,date_time_string()} methods, respectively. If the server does not
intend to send any other headers using the @ref{40fa,,send_header()} method,
then @ref{40fe,,send_response()} should be followed by an @ref{12e3,,end_headers()}
call.


バージョン 3.3 で変更: Headers are stored to an internal buffer and @ref{12e3,,end_headers()}
needs to be called explicitly.

@end deffn

@geindex send_header() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler send_header}@anchor{40fa}
@deffn {メソッド} send_header (keyword, value)

Adds the HTTP header to an internal buffer which will be written to the
output stream when either @ref{12e3,,end_headers()} or @ref{12e4,,flush_headers()} is
invoked. `keyword' should specify the header keyword, with `value'
specifying its value. Note that, after the send_header calls are done,
@ref{12e3,,end_headers()} MUST BE called in order to complete the operation.


バージョン 3.2 で変更: ヘッダは内部バッファに保存されます。

@end deffn

@geindex send_response_only() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler send_response_only}@anchor{40fb}
@deffn {メソッド} send_response_only (code, message=None)

Sends the response header only, used for the purposes when @code{100
Continue} response is sent by the server to the client. The headers not
buffered and sent directly the output stream.If the `message' is not
specified, the HTTP message corresponding the response `code'  is sent.


Added in version 3.2.

@end deffn

@geindex end_headers() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler end_headers}@anchor{12e3}
@deffn {メソッド} end_headers ()

Adds a blank line
(indicating the end of the HTTP headers in the response)
to the headers buffer and calls @ref{12e4,,flush_headers()}.


バージョン 3.2 で変更: バッファされたヘッダは出力ストリームに書き出されます。

@end deffn

@geindex flush_headers() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler flush_headers}@anchor{12e4}
@deffn {メソッド} flush_headers ()

最終的にヘッダを出力ストリームに送り、内部ヘッダバッファをフラッシュします。


Added in version 3.3.

@end deffn

@geindex log_request() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler log_request}@anchor{4100}
@deffn {メソッド} log_request (code='-', size='-')

受理された (成功した) リクエストをログに記録します。`code' にはこの応答に関連付けられた HTTP コード番号を指定します。応答メッセージの大きさを知ることができる場合、`size' パラメタに渡すとよいでしょう。
@end deffn

@geindex log_error() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler log_error}@anchor{4101}
@deffn {メソッド} log_error (...)

リクエストを遂行できなかった際に、エラーをログに記録します。標準では、メッセージを @ref{4102,,log_message()} に渡します。従って同じ引数 (`format' と追加の値) を取ります。
@end deffn

@geindex log_message() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler log_message}@anchor{4102}
@deffn {メソッド} log_message (format, ...)

任意のメッセージを @code{sys.stderr} にログ記録します。このメソッドは通常、カスタムのエラーログ記録機構を作成するために上書きされます。 `format' 引数は標準の printf 形式の書式文字列で、 @ref{4102,,log_message()} に渡された追加の引数は書式化の入力として適用されます。ログ記録される全てのメッセージには、クライアントの IP アドレスおよび現在の日付、時刻が先頭に付けられます。
@end deffn

@geindex version_string() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler version_string}@anchor{40f7}
@deffn {メソッド} version_string ()

サーバーのソフトウェアのバージョンを示す文字列を返します。
その文字列は、@ref{40f5,,server_version} と @ref{40f6,,sys_version} の属性が含まれます。
@end deffn

@geindex date_time_string() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler date_time_string}@anchor{40ff}
@deffn {メソッド} date_time_string (timestamp=None)

メッセージヘッダ向けに書式化された、 `timestamp' (@code{None} または @ref{55d,,time.time()} のフォーマットである必要があります)で与えられた日時を返します。もし `timestamp' が省略された場合には、現在の日時が使われます。

出力は @code{'Sun, 06 Nov 1994 08:49:37 GMT'} のようになります。
@end deffn

@geindex log_date_time_string() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler log_date_time_string}@anchor{4103}
@deffn {メソッド} log_date_time_string ()

ログ記録向けに書式化された、現在の日付および時刻を返します。
@end deffn

@geindex address_string() (http.server.BaseHTTPRequestHandler のメソッド)
@anchor{library/http server http server BaseHTTPRequestHandler address_string}@anchor{4104}
@deffn {メソッド} address_string ()

クライアントのアドレスを返します。


バージョン 3.3 で変更: Previously, a name lookup was performed. To avoid name resolution
delays, it now always returns the IP address.

@end deffn
@end deffn

@geindex SimpleHTTPRequestHandler (http.server のクラス)
@anchor{library/http server http server SimpleHTTPRequestHandler}@anchor{d38}
@deffn {クラス} http.server.SimpleHTTPRequestHandler (request, client_address, server, directory=None)

This class serves files from the directory `directory' and below,
or the current directory if `directory' is not provided, directly
mapping the directory structure to HTTP requests.


バージョン 3.7 で変更: Added the `directory' parameter.



バージョン 3.9 で変更: The `directory' parameter accepts a @ref{5a1,,path-like object}.


リクエストの解釈のような、多くの作業は基底クラス @ref{12e2,,BaseHTTPRequestHandler} で行われます。このクラスは関数 @ref{4105,,do_GET()} および @ref{4106,,do_HEAD()} を実装しています。

@ref{d38,,SimpleHTTPRequestHandler} では以下のメンバ変数を定義しています:

@geindex server_version (http.server.SimpleHTTPRequestHandler の属性)
@anchor{library/http server http server SimpleHTTPRequestHandler server_version}@anchor{4107}
@deffn {の属性} server_version

この値は @code{"SimpleHTTP/" + __version__} になります。@code{__version__} はこのモジュールで定義されている値です。
@end deffn

@geindex extensions_map (http.server.SimpleHTTPRequestHandler の属性)
@anchor{library/http server http server SimpleHTTPRequestHandler extensions_map}@anchor{4108}
@deffn {の属性} extensions_map

A dictionary mapping suffixes into MIME types, contains custom overrides
for the default system mappings. The mapping is used case-insensitively,
and so should contain only lower-cased keys.


バージョン 3.9 で変更: This dictionary is no longer filled with the default system mappings,
but only contains overrides.

@end deffn

@ref{d38,,SimpleHTTPRequestHandler} では以下のメソッドを定義しています:

@geindex do_HEAD() (http.server.SimpleHTTPRequestHandler のメソッド)
@anchor{library/http server http server SimpleHTTPRequestHandler do_HEAD}@anchor{4106}
@deffn {メソッド} do_HEAD ()

このメソッドは @code{'HEAD'} 型のリクエスト処理を実行します: すなわち、 @code{GET} リクエストの時に送信されるものと同じヘッダを送信します。送信される可能性のあるヘッダについての完全な説明は @ref{4105,,do_GET()} メソッドを参照してください。
@end deffn

@geindex do_GET() (http.server.SimpleHTTPRequestHandler のメソッド)
@anchor{library/http server http server SimpleHTTPRequestHandler do_GET}@anchor{4105}
@deffn {メソッド} do_GET ()

リクエストを現在の作業ディレクトリからの相対的なパスとして解釈することで、リクエストをローカルシステム上のファイルと対応付けます。

リクエストがディレクトリに対応付けられた場合、 @code{index.html} または @code{index.htm} を (この順序で) チェックします。もしファイルを発見できればその内容を、そうでなければディレクトリ一覧を @code{list_directory()} メソッドで生成して、返します。このメソッドは @ref{1312,,os.listdir()} をディレクトリのスキャンに用いており、 @ref{1312,,listdir()} が失敗した場合には @code{404} 応答が返されます。

If the request was mapped to a file, it is opened. Any @ref{2c0,,OSError}
exception in opening the requested file is mapped to a @code{404},
@code{'File not found'} error. If there was an @code{'If-Modified-Since'}
header in the request, and the file was not modified after this time,
a @code{304}, @code{'Not Modified'} response is sent. Otherwise, the content
type is guessed by calling the @code{guess_type()} method, which in turn
uses the `extensions_map' variable, and the file contents are returned.

出力は @code{'Content-type:'} と推測されたコンテントタイプで、その後にファイルサイズを示す @code{'Content-Length;'} ヘッダと、ファイルの更新日時を示す @code{'Last-Modified:'} ヘッダが続きます。

Then follows a blank line signifying the end of the headers, and then the
contents of the file are output.

For example usage, see the implementation of the @code{test} function
in Lib/http/server.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/http/server.py}.


バージョン 3.7 で変更: Support of the @code{'If-Modified-Since'} header.

@end deffn
@end deffn

The @ref{d38,,SimpleHTTPRequestHandler} class can be used in the following
manner in order to create a very basic webserver serving files relative to
the current directory:

@example
import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
@end example

@ref{d38,,SimpleHTTPRequestHandler} can also be subclassed to enhance behavior,
such as using different index file names by overriding the class attribute
@code{index_pages}.

@geindex CGIHTTPRequestHandler (http.server のクラス)
@anchor{library/http server http server CGIHTTPRequestHandler}@anchor{325}
@deffn {クラス} http.server.CGIHTTPRequestHandler (request, client_address, server)

このクラスは、現在のディレクトリかその下のディレクトリにおいて、ファイルか CGI スクリプト出力を提供するために使われます。 HTTP 階層構造からローカルなディレクトリ構造への対応付けは @ref{d38,,SimpleHTTPRequestHandler} と全く同じなので注意してください。

@cartouche
@quotation 注釈 
@ref{325,,CGIHTTPRequestHandler} クラスで実行される CGI スクリプトは HTTP コード 200 (スクリプトの出力が後に続く) を実行に先立って出力される (これがステータスコードになります) ため、リダイレクト(コード302) を行なうことができません。
@end quotation
@end cartouche

このクラスでは、ファイルが CGI スクリプトであると推測された場合、これをファイルとして提供する代わりにスクリプトを実行します。 --- 他の一般的なサーバ設定は特殊な拡張子を使って CGI スクリプトであることを示すのに対し、ディレクトリベースの CGI だけが使われます。

@code{do_GET()} および @code{do_HEAD()} 関数は、HTTP 要求が @code{cgi_directories} パス以下のどこかを指している場合、ファイルを提供するのではなく、CGI スクリプトを実行してその出力を提供するように変更されています。

@ref{325,,CGIHTTPRequestHandler} では以下のデータメンバを定義しています:

@geindex cgi_directories (http.server.CGIHTTPRequestHandler の属性)
@anchor{library/http server http server CGIHTTPRequestHandler cgi_directories}@anchor{4109}
@deffn {の属性} cgi_directories

この値は標準で @code{['/cgi-bin', '/htbin']} であり、CGI スクリプトを含んでいることを示すディレクトリを記述します。
@end deffn

@ref{325,,CGIHTTPRequestHandler} は以下のメソッドを定義しています:

@geindex do_POST() (http.server.CGIHTTPRequestHandler のメソッド)
@anchor{library/http server http server CGIHTTPRequestHandler do_POST}@anchor{410a}
@deffn {メソッド} do_POST ()

このメソッドは、CGI スクリプトでのみ許されている @code{'POST'} 型の HTTP 要求に対するサービスを行います。CGI でない url に対して POST を試みた場合、出力は Error 501, "Can only POST to CGI scripts" になります。
@end deffn

セキュリティ上の理由から、CGI スクリプトはユーザ nobody の UID で動作するので注意してください。 CGI スクリプトが原因で発生した問題は、Error 403 に変換されます。


Deprecated since version 3.13, will be removed in version 3.15: @ref{325,,CGIHTTPRequestHandler} is being removed in 3.15.  CGI has not
been considered a good way to do things for well over a decade. This code
has been unmaintained for a while now and sees very little practical use.
Retaining it could lead to further @ref{40e8,,security considerations}.

@end deffn

@menu
* コマンドライン・インターフェース: コマンドライン・インターフェース<7>. 
* セキュリティで考慮すべき点: セキュリティで考慮すべき点<5>. 

@end menu

@node コマンドライン・インターフェース<7>,セキュリティで考慮すべき点<5>,,http server --- HTTP サーバー
@anchor{library/http server command-line-interface}@anchor{410b}@anchor{library/http server http-server-cli}@anchor{1153}
@subsubsection コマンドライン・インターフェース


@code{http.server} can also be invoked directly using the @ref{23c,,-m}
switch of the interpreter.  The following example illustrates how to serve
files relative to the current directory:

@example
python -m http.server [OPTIONS] [port]
@end example

以下のオプションが使用できます:

@geindex http.server コマンドラインオプション; port
@anchor{library/http server cmdoption-http server-arg-port}@anchor{410c}
@deffn {Option} port

The server listens to port 8000 by default. The default can be overridden
by passing the desired port number as an argument:

@example
python -m http.server 9000
@end example
@end deffn

@geindex http.server コマンドラインオプション; -b
@geindex http.server コマンドラインオプション; --bind
@anchor{library/http server cmdoption-http server-b}@anchor{410d}@anchor{library/http server cmdoption-http server-bind}@anchor{410e}
@deffn {Option} @w{-}b, @w{-}@w{-}bind <address>

Specifies a specific address to which it should bind. Both IPv4 and IPv6
addresses are supported. By default, the server binds itself to all
interfaces. For example, the following command causes the server to bind
to localhost only:

@example
python -m http.server --bind 127.0.0.1
@end example


Added in version 3.4.



バージョン 3.8 で変更: Support IPv6 in the @code{--bind} option.

@end deffn

@geindex http.server コマンドラインオプション; -d
@geindex http.server コマンドラインオプション; --directory
@anchor{library/http server cmdoption-http server-d}@anchor{183f}@anchor{library/http server cmdoption-http server-directory}@anchor{410f}
@deffn {Option} @w{-}d, @w{-}@w{-}directory <dir>

Specifies a directory to which it should serve the files. By default,
the server uses the current directory. For example, the following command
uses a specific directory:

@example
python -m http.server --directory /tmp/
@end example


Added in version 3.7.

@end deffn

@geindex http.server コマンドラインオプション; -p
@geindex http.server コマンドラインオプション; --protocol
@anchor{library/http server cmdoption-http server-p}@anchor{4110}@anchor{library/http server cmdoption-http server-protocol}@anchor{4111}
@deffn {Option} @w{-}p, @w{-}@w{-}protocol <version>

Specifies the HTTP version to which the server is conformant. By default,
the server is conformant to HTTP/1.0. For example, the following command
runs an HTTP/1.1 conformant server:

@example
python -m http.server --protocol HTTP/1.1
@end example


Added in version 3.11.

@end deffn

@geindex http.server コマンドラインオプション; --cgi
@anchor{library/http server cmdoption-http server-cgi}@anchor{4112}
@deffn {Option} @w{-}@w{-}cgi

@ref{325,,CGIHTTPRequestHandler} can be enabled in the command line by passing
the @code{--cgi} option:

@example
python -m http.server --cgi
@end example


Deprecated since version 3.13, will be removed in version 3.15: @code{http.server} command line @code{--cgi} support is being removed
because @ref{325,,CGIHTTPRequestHandler} is being removed.

@end deffn

@cartouche
@quotation 警告 
@ref{325,,CGIHTTPRequestHandler} and the @code{--cgi} command-line option
are not intended for use by untrusted clients and may be vulnerable
to exploitation. Always use within a secure environment.
@end quotation
@end cartouche

@geindex http.server コマンドラインオプション; --tls-cert
@anchor{library/http server cmdoption-http server-tls-cert}@anchor{229}
@deffn {Option} @w{-}@w{-}tls@w{-}cert

Specifies a TLS certificate chain for HTTPS connections:

@example
python -m http.server --tls-cert fullchain.pem
@end example


Added in version 3.14.

@end deffn

@geindex http.server コマンドラインオプション; --tls-key
@anchor{library/http server cmdoption-http server-tls-key}@anchor{22a}
@deffn {Option} @w{-}@w{-}tls@w{-}key

Specifies a private key file for HTTPS connections.

This option requires @code{--tls-cert} to be specified.


Added in version 3.14.

@end deffn

@geindex http.server コマンドラインオプション; --tls-password-file
@anchor{library/http server cmdoption-http server-tls-password-file}@anchor{22b}
@deffn {Option} @w{-}@w{-}tls@w{-}password@w{-}file

Specifies the password file for password-protected private keys:

@example
python -m http.server \
       --tls-cert cert.pem \
       --tls-key key.pem \
       --tls-password-file password.txt
@end example

This option requires @cite{--tls-cert`} to be specified.


Added in version 3.14.

@end deffn

@node セキュリティで考慮すべき点<5>,,コマンドライン・インターフェース<7>,http server --- HTTP サーバー
@anchor{library/http server http-server-security}@anchor{40e8}@anchor{library/http server security-considerations}@anchor{4113}
@subsubsection セキュリティで考慮すべき点


@geindex http.server;セキュリティ

@ref{d38,,SimpleHTTPRequestHandler} will follow symbolic links when handling
requests, this makes it possible for files outside of the specified directory
to be served.

Earlier versions of Python did not scrub control characters from the
log messages emitted to stderr from @code{python -m http.server} or the
default @ref{12e2,,BaseHTTPRequestHandler} @code{.log_message}
implementation. This could allow remote clients connecting to your
server to send nefarious control codes to your terminal.


バージョン 3.12 で変更: Control characters are scrubbed in stderr logs.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node http cookies --- HTTP の状態管理,http cookiejar --- HTTP クライアント用の Cookie 処理,http server --- HTTP サーバー,インターネットプロトコルとサポート
@anchor{library/http cookies doc}@anchor{4114}@anchor{library/http cookies http-cookies-http-state-management}@anchor{4115}@anchor{library/http cookies module-http cookies}@anchor{75}@anchor{library/http cookies translation-repo}@anchor{4116}
@subsection @code{http.cookies} --- HTTP の状態管理


@geindex module; http.cookies

`ソースコード:' Lib/http/cookies.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/http/cookies.py}


__________________________________________________________________


The @code{http.cookies} module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple string-only
cookies, and provides an abstraction for having any serializable data-type as
cookie value.

このモジュールは元々 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} と 
@geindex RFC; RFC 2068
RFC 2068@footnote{https://datatracker.ietf.org/doc/html/rfc2068.html} に定義されている構文解析の規則を厳密に守っていました。しかし、MSIE 3.0x がこれらの RFC で定義された文字の規則に従っていなかったことが判明し、現在の多くのブラウザーとサーバーも Cookie の処理に関しては緩い解析を行っています。結局、このモジュールは昔よりもやや厳密さを欠く構文解析規則になっています。

文字集合 @ref{14db,,string.ascii_letters} 、 @ref{2722,,string.digits} 、 @code{!#$%&'*+-.^_`|~:} を、このモジュールは cookie 名 (@ref{dfb,,key}) として有効と認めています。


バージョン 3.3 で変更: ':' が有効な cookie 名の文字として認められました。


@cartouche
@quotation 注釈 
不正な cookie に遭遇した場合、 @ref{4117,,CookieError} 例外を送出します。そのため、ブラウザから持ってきた cookie データをパースするときには常に不正なデータに備え @ref{4117,,CookieError} 例外を捕捉してください。
@end quotation
@end cartouche

@geindex CookieError
@anchor{library/http cookies http cookies CookieError}@anchor{4117}
@deffn {例外} http.cookies.CookieError

属性や @code{Set-Cookie} ヘッダが正しくないなど、 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} に合致していないときに発生する例外です。
@end deffn

@geindex BaseCookie (http.cookies のクラス)
@anchor{library/http cookies http cookies BaseCookie}@anchor{4118}
@deffn {クラス} http.cookies.BaseCookie ([input])

このクラスはキーが文字列、値が @ref{dfe,,Morsel} インスタンスで構成される辞書風オブジェクトです。値に対するキーを設定するときは、値がキーと値を含む @ref{dfe,,Morsel} に変換されることに注意してください。

`input' が与えられたときは、そのまま @ref{4119,,load()} メソッドへ渡されます。
@end deffn

@geindex SimpleCookie (http.cookies のクラス)
@anchor{library/http cookies http cookies SimpleCookie}@anchor{1e24}
@deffn {クラス} http.cookies.SimpleCookie ([input])

このクラスは @ref{4118,,BaseCookie} を継承し、 @ref{411a,,value_decode()} と @ref{411b,,value_encode()} をオーバーライドします。 @code{SimpleCookie} は文字列と cookie 値をサポートします。値を設定するとき、 @code{SimpleCookie} は組み込みの @ref{169,,str()} を呼び出して値を文字列に変換します。HTTP から受け取った値は文字列として保持されます。
@end deffn


@subsubheading 参考



@table @asis

@item モジュール @ref{74,,http.cookiejar}

HTTP cookie handling for web `clients'.  The @ref{74,,http.cookiejar} and
@code{http.cookies} modules do not depend on each other.

@geindex RFC; RFC 2109

@item RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} - HTTP State Management Mechanism

このモジュールが実装しているHTTPの状態管理に関する規格です。
@end table


@menu
* Cookieオブジェクト:: 
* Morselオブジェクト:: 
* 使用例: 使用例<41>. 

@end menu

@node Cookieオブジェクト,Morselオブジェクト,,http cookies --- HTTP の状態管理
@anchor{library/http cookies cookie-objects}@anchor{411c}@anchor{library/http cookies id1}@anchor{411d}
@subsubsection Cookieオブジェクト


@geindex value_decode() (http.cookies.BaseCookie のメソッド)
@anchor{library/http cookies http cookies BaseCookie value_decode}@anchor{411a}
@deffn {メソッド} BaseCookie.value_decode (val)

文字列表現のタプル @code{(real_value, coded_value)} を返します。 @code{real_value} の型はどのようなものでも許容されます。このメソッドは @ref{4118,,BaseCookie} においてデコードを行わず、オーバーライドされるためにだけ存在します。
@end deffn

@geindex value_encode() (http.cookies.BaseCookie のメソッド)
@anchor{library/http cookies http cookies BaseCookie value_encode}@anchor{411b}
@deffn {メソッド} BaseCookie.value_encode (val)

タプル @code{(real_value, coded_value)} を返します。 `val' の型はどのようなものでも許容されますが、 @code{coded_value} は常に文字列に変換されます。このメソッドは @ref{4118,,BaseCookie} においてエンコードを行わず、オーバーライドされるためにだけ存在します。

通常 @ref{411b,,value_encode()} と @ref{411a,,value_decode()} はともに `value_decode' の処理内容から逆算した範囲に収まっていなければなりません。
@end deffn

@geindex output() (http.cookies.BaseCookie のメソッド)
@anchor{library/http cookies http cookies BaseCookie output}@anchor{411e}
@deffn {メソッド} BaseCookie.output (attrs=None, header='Set-Cookie:', sep='\r\n')

Return a string representation suitable to be sent as HTTP headers. `attrs' and
`header' are sent to each @ref{dfe,,Morsel}'s @ref{411f,,output()} method. `sep' is used
to join the headers together, and is by default the combination @code{'\r\n'}
(CRLF).
@end deffn

@geindex js_output() (http.cookies.BaseCookie のメソッド)
@anchor{library/http cookies http cookies BaseCookie js_output}@anchor{4120}
@deffn {メソッド} BaseCookie.js_output (attrs=None)

ブラウザがJavaScriptをサポートしている場合、HTTPヘッダを送信した場合と同様に動作する埋め込み可能なJavaScript snippetを返します。

`attrs' の意味は @ref{411e,,output()} と同じです。
@end deffn

@geindex load() (http.cookies.BaseCookie のメソッド)
@anchor{library/http cookies http cookies BaseCookie load}@anchor{4119}
@deffn {メソッド} BaseCookie.load (rawdata)

`rawdata' が文字列であれば、 @code{HTTP_COOKIE} として処理し、その値を @ref{dfe,,Morsel} として追加します。辞書の場合は次と同様の処理をおこないます。

@example
for k, v in rawdata.items():
    cookie[k] = v
@end example
@end deffn

@node Morselオブジェクト,使用例<41>,Cookieオブジェクト,http cookies --- HTTP の状態管理
@anchor{library/http cookies id2}@anchor{4121}@anchor{library/http cookies morsel-objects}@anchor{4122}
@subsubsection Morselオブジェクト


@geindex Morsel (http.cookies のクラス)
@anchor{library/http cookies http cookies Morsel}@anchor{dfe}
@deffn {クラス} http.cookies.Morsel

@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} の属性をキーと値で保持するabstractクラスです。

Morselは辞書風のオブジェクトで、キーは次のような 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} 準拠の定数となっています:

@quotation

@geindex expires (http.cookies.Morsel の属性)
@geindex path (http.cookies.Morsel の属性)
@geindex comment (http.cookies.Morsel の属性)
@geindex domain (http.cookies.Morsel の属性)
@geindex secure (http.cookies.Morsel の属性)
@geindex version (http.cookies.Morsel の属性)
@geindex httponly (http.cookies.Morsel の属性)
@geindex samesite (http.cookies.Morsel の属性)
@geindex partitioned (http.cookies.Morsel の属性)
@anchor{library/http cookies http cookies Morsel expires}@anchor{4123}
@deffn {の属性} expires
@anchor{library/http cookies http cookies Morsel path}@anchor{4124}
@deffnx {の属性} path
@anchor{library/http cookies http cookies Morsel comment}@anchor{4125}
@deffnx {の属性} comment
@anchor{library/http cookies http cookies Morsel domain}@anchor{4126}
@deffnx {の属性} domain

@deffnx {の属性} max@w{-}age
@anchor{library/http cookies http cookies Morsel secure}@anchor{4127}
@deffnx {の属性} secure
@anchor{library/http cookies http cookies Morsel version}@anchor{4128}
@deffnx {の属性} version
@anchor{library/http cookies http cookies Morsel httponly}@anchor{15e9}
@deffnx {の属性} httponly
@anchor{library/http cookies http cookies Morsel samesite}@anchor{4129}
@deffnx {の属性} samesite
@anchor{library/http cookies http cookies Morsel partitioned}@anchor{412a}
@deffnx {の属性} partitioned
@end deffn
@end quotation

@ref{15e9,,httponly} 属性は、 cookie が HTTP リクエストでのみ送信されて、 JavaScript からのはアクセスできない事を示します。これはいくつかのクロスサイトスクリプティングの脅威を和らげることを意図しています。

The attribute @ref{4129,,samesite} controls when the browser sends the cookie with
cross-site requests. This helps to mitigate CSRF attacks. Valid values are
"Strict" (only sent with same-site requests), "Lax" (sent with same-site
requests and top-level navigations), and "None" (sent with same-site and
cross-site requests). When using "None", the "secure" attribute must also
be set, as required by modern browsers.

The attribute @ref{412a,,partitioned} indicates to user agents that these
cross-site cookies `should' only be available in the same top-level context
that the cookie was first set in. For this to be accepted by the user agent,
you `must' also set @code{Secure}.

In addition, it is recommended to use the @code{__Host} prefix when setting
partitioned cookies to make them bound to the hostname and not the
registrable domain. Read
CHIPS (Cookies Having Independent Partitioned State)@footnote{https://github.com/privacycg/CHIPS/blob/main/README.md}
for full details and examples.

キーの大小文字は区別されません。そのデフォルト値は @code{'@w{'}} です。


バージョン 3.5 で変更: @code{__eq__()} は @ref{dfb,,key} 及び @ref{dfc,,value} を考慮するようになりました。



バージョン 3.7 で変更: @ref{dfb,,key} と @ref{dfc,,value} 、 @ref{dfd,,coded_value} 属性は読み出し専用です。設定には、 @ref{dff,,set()} を使用してください。



バージョン 3.8 で変更: @ref{4129,,samesite} 属性がサポートされました。



バージョン 3.14 で変更: Added support for the @ref{412a,,partitioned} attribute.

@end deffn

@geindex value (http.cookies.Morsel の属性)
@anchor{library/http cookies http cookies Morsel value}@anchor{dfc}
@deffn {の属性} Morsel.value

クッキーの値。
@end deffn

@geindex coded_value (http.cookies.Morsel の属性)
@anchor{library/http cookies http cookies Morsel coded_value}@anchor{dfd}
@deffn {の属性} Morsel.coded_value

実際に送信する形式にエンコードされたcookieの値。
@end deffn

@geindex key (http.cookies.Morsel の属性)
@anchor{library/http cookies http cookies Morsel key}@anchor{dfb}
@deffn {の属性} Morsel.key

cookieの名前。
@end deffn

@geindex set() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel set}@anchor{dff}
@deffn {メソッド} Morsel.set (key, value, coded_value)

属性 `key' 、 `value' 、 `coded_value' に値をセットします。
@end deffn

@geindex isReservedKey() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel isReservedKey}@anchor{412b}
@deffn {メソッド} Morsel.isReservedKey (K)

`K' が @ref{dfe,,Morsel} のキーであるかどうかを判定します。
@end deffn

@geindex output() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel output}@anchor{411f}
@deffn {メソッド} Morsel.output (attrs=None, header='Set-Cookie:')

MoselをHTTPヘッダ形式の文字列表現にして返します。 `attrs' を指定しない場合、デフォルトですべての属性を含めます。 `attrs' を指定する場合、属性をリストで渡さなければなりません。 `header' のデフォルトは @code{"Set-Cookie:"} です。
@end deffn

@geindex js_output() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel js_output}@anchor{412c}
@deffn {メソッド} Morsel.js_output (attrs=None)

ブラウザがJavaScriptをサポートしている場合、HTTPヘッダを送信した場合と同様に動作する埋め込み可能なJavaScript snippetを返します。

`attrs' の意味は @ref{411f,,output()} と同じです。
@end deffn

@geindex OutputString() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel OutputString}@anchor{412d}
@deffn {メソッド} Morsel.OutputString (attrs=None)

Moselの文字列表現をHTTPやJavaScriptで囲まずに出力します。

`attrs' の意味は @ref{411f,,output()} と同じです。
@end deffn

@geindex update() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel update}@anchor{10c9}
@deffn {メソッド} Morsel.update (values)

Morsel 辞書の値を辞書 `values' の値で更新します。`values' 辞書のキーのいずれかが有効な 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} 属性でない場合エラーを送出します。


バージョン 3.5 で変更: 不正なキーではエラーが送出されます。

@end deffn

@geindex copy() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel copy}@anchor{10c8}
@deffn {メソッド} Morsel.copy (value)

Morsel オブジェクトの浅いコピーを返します。


バージョン 3.5 で変更: 辞書ではなく Morsel オブジェクトを返します。

@end deffn

@geindex setdefault() (http.cookies.Morsel のメソッド)
@anchor{library/http cookies http cookies Morsel setdefault}@anchor{412e}
@deffn {メソッド} Morsel.setdefault (key, value=None)

キーが有効な 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} 属性でない場合エラーを送出します。そうでない場合は @ref{1285,,dict.setdefault()} と同じように振る舞います。
@end deffn

@node 使用例<41>,,Morselオブジェクト,http cookies --- HTTP の状態管理
@anchor{library/http cookies cookie-example}@anchor{412f}@anchor{library/http cookies example}@anchor{4130}
@subsubsection 使用例


The following example demonstrates how to use the @code{http.cookies} module.

@example
>>> from http import cookies
>>> C = cookies.SimpleCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafer"
>>> print(C) # generate HTTP headers
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> print(C.output()) # same thing
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> C = cookies.SimpleCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie
>>> print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road
>>> C = cookies.SimpleCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print(C)
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = cookies.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";')
>>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;"
>>> C = cookies.SimpleCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
>>> print(C)
Set-Cookie: oreo=doublestuff; Path=/
>>> C = cookies.SimpleCookie()
>>> C["twix"] = "none for you"
>>> C["twix"].value
'none for you'
>>> C = cookies.SimpleCookie()
>>> C["number"] = 7 # equivalent to C["number"] = str(7)
>>> C["string"] = "seven"
>>> C["number"].value
'7'
>>> C["string"].value
'seven'
>>> print(C)
Set-Cookie: number=7
Set-Cookie: string=seven
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node http cookiejar --- HTTP クライアント用の Cookie 処理,xmlrpc --- XMLRPC サーバーとクライアントモジュール群,http cookies --- HTTP の状態管理,インターネットプロトコルとサポート
@anchor{library/http cookiejar doc}@anchor{4131}@anchor{library/http cookiejar http-cookiejar-cookie-handling-for-http-clients}@anchor{4132}@anchor{library/http cookiejar module-http cookiejar}@anchor{74}@anchor{library/http cookiejar translation-repo}@anchor{4133}
@subsection @code{http.cookiejar} --- HTTP クライアント用の Cookie 処理


@geindex module; http.cookiejar

`ソースコード:' Lib/http/cookiejar.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/http/cookiejar.py}


__________________________________________________________________


The @code{http.cookiejar} module defines classes for automatic handling of HTTP
cookies.  It is useful for accessing websites that require small pieces of data
-- `cookies' -- to be set on the client machine by an HTTP response from a
web server, and then returned to the server in later HTTP requests.

Both the regular Netscape cookie protocol and the protocol defined by
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} are handled.  RFC 2965 handling is switched off by default.
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} cookies are parsed as Netscape cookies and subsequently treated
either as Netscape or RFC 2965 cookies according to the 'policy' in effect.
Note that the great majority of cookies on the internet are Netscape cookies.
@code{http.cookiejar} attempts to follow the de-facto Netscape cookie protocol (which
differs substantially from that set out in the original Netscape specification),
including taking note of the @code{max-age} and @code{port} cookie-attributes
introduced with RFC 2965.

@cartouche
@quotation 注釈 
@code{Set-Cookie} や @code{Set-Cookie2} ヘッダに現れる多種多様なパラメータの名前 (@code{domain} や @code{expires} など) は便宜上 `属性' と呼ばれますが、ここでは Python の属性と区別するため、かわりに `クッキー属性' と呼ぶことにします。
@end quotation
@end cartouche

このモジュールは以下の例外を定義しています:

@geindex LoadError
@anchor{library/http cookiejar http cookiejar LoadError}@anchor{4134}
@deffn {例外} http.cookiejar.LoadError

この例外は @ref{4135,,FileCookieJar} インスタンスがファイルからクッキーを読み込むのに失敗した場合に発生します。 @ref{4134,,LoadError} は @ref{2c0,,OSError} のサブクラスです。


バージョン 3.3 で変更: @ref{4134,,LoadError} は以前は @ref{125e,,IOError} のサブタイプでしたが、 @ref{2c0,,OSError} のエイリアスになりました。

@end deffn

以下のクラスが提供されています:

@geindex CookieJar (http.cookiejar のクラス)
@anchor{library/http cookiejar http cookiejar CookieJar}@anchor{3f53}
@deffn {クラス} http.cookiejar.CookieJar (policy=None)

`policy' は @ref{4136,,CookiePolicy} インターフェイスを実装するオブジェクトです。

@ref{3f53,,CookieJar} クラスには HTTP クッキーを保管します。これは HTTP リクエストに応じてクッキーを取り出し、それを HTTP レスポンスの中で返します。必要に応じて、 @ref{3f53,,CookieJar} インスタンスは保管されているクッキーを自動的に破棄します。このサブクラスは、クッキーをファイルやデータベースに格納したり取り出したりする操作をおこなう役割を負っています。
@end deffn

@geindex FileCookieJar (http.cookiejar のクラス)
@anchor{library/http cookiejar http cookiejar FileCookieJar}@anchor{4135}
@deffn {クラス} http.cookiejar.FileCookieJar (filename=None, delayload=None, policy=None)

`policy' は @ref{4136,,CookiePolicy} インターフェイスを実装するオブジェクトです。これ以外の引数については、該当する属性の説明を参照してください。

@ref{4135,,FileCookieJar} はディスク上のファイルからのクッキーの読み込み、もしくは書き込みをサポートします。実際には、 @ref{4137,,load()} または  @ref{4138,,revert()} のどちらかのメソッドが呼ばれるまでクッキーは指定されたファイルからはロード `されません' 。このクラスのサブクラスは @ref{4139,,FileCookieJar のサブクラスと web ブラウザとの連携} 節で説明します。

これは直接初期化されるべきではありません。以下のサブクラスを代わりに使用してください。


バージョン 3.8 で変更: `filename' 引数が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@geindex CookiePolicy (http.cookiejar のクラス)
@anchor{library/http cookiejar http cookiejar CookiePolicy}@anchor{4136}
@deffn {クラス} http.cookiejar.CookiePolicy

このクラスは、あるクッキーをサーバから受け入れるべきか、そしてサーバに返すべきかを決定する役割を負っています。
@end deffn

@geindex DefaultCookiePolicy (http.cookiejar のクラス)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy}@anchor{1df4}
@deffn {クラス} http.cookiejar.DefaultCookiePolicy (blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False, secure_protocols=('https', 'wss'))

コンストラクタはキーワード引数しか取りません。 `blocked_domains' はドメイン名からなるシーケンスで、ここからは決してクッキーを受けとらないし、このドメインにクッキーを返すこともありません。 `allowed_domains' が @ref{885,,None} でない場合、クッキーを受けとり、返すのはこのシーケンスのドメインに限定されます。 `secure_protocols' は、安全なクッキーを追加できるプロトコルのシーケンスです。デフォルトでは、 `https' と `wss' (secure websocket) が安全なプロトコルとみなされます。これ以外の引数については @ref{4136,,CookiePolicy} および @ref{1df4,,DefaultCookiePolicy} オブジェクトの説明をごらんください。

@ref{1df4,,DefaultCookiePolicy} は Netscape および 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} クッキーの標準的な許可 / 拒絶のルールを実装しています。デフォルトでは、 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} のクッキー (@code{Set-Cookie} の version クッキー属性が 1 で受けとられるもの) は RFC 2965 のルールで扱われます。しかし、RFC 2965 処理が無効に設定されているか @ref{413a,,rfc2109_as_netscape} が @code{True} の場合、RFC 2109 クッキーは @ref{3f53,,CookieJar} インスタンスによって @ref{413b,,Cookie} のインスタンスの @code{version} 属性を 0 に設定する事で Netscapeクッキーに「ダウングレード」されます。また @ref{1df4,,DefaultCookiePolicy} にはいくつかの細かいポリシー設定をおこなうパラメータが用意されています。
@end deffn

@geindex Cookie (http.cookiejar のクラス)
@anchor{library/http cookiejar http cookiejar Cookie}@anchor{413b}
@deffn {クラス} http.cookiejar.Cookie

This class represents Netscape, 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} and 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} cookies.  It is not
expected that users of @code{http.cookiejar} construct their own @ref{413b,,Cookie}
instances.  Instead, if necessary, call @code{make_cookies()} on a
@ref{3f53,,CookieJar} instance.
@end deffn


@subsubheading 参考



@table @asis

@item @ref{111,,urllib.request} モジュール

クッキーの自動処理をおこない URL を開くモジュールです。

@item @ref{75,,http.cookies} モジュール

HTTP cookie classes, principally useful for server-side code.  The
@code{http.cookiejar} and @ref{75,,http.cookies} modules do not depend on each
other.

@item @indicateurl{https://curl.se/rfc/cookie_spec.html}

The specification of the original Netscape cookie protocol.  Though this is
still the dominant protocol, the 'Netscape cookie protocol' implemented by all
the major browsers (and @code{http.cookiejar}) only bears a passing resemblance to
the one sketched out in @code{cookie_spec.html}.

@geindex RFC; RFC 2109

@item RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} - HTTP State Management Mechanism

@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} によって過去の遺物になりました。 @code{Set-Cookie} の version=1 で使います。

@geindex RFC; RFC 2965

@item RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} - HTTP State Management Mechanism

Netscape プロトコルのバグを修正したものです。 @code{Set-Cookie} のかわりに @code{Set-Cookie2} を使いますが、普及してはいません。

@item @indicateurl{https://kristol.org/cookie/errata.html}

@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} に対する未完の正誤表です。
@end table

@geindex RFC; RFC 2964
RFC 2964@footnote{https://datatracker.ietf.org/doc/html/rfc2964.html} - Use of HTTP State Management


@menu
* CookieJar および FileCookieJar オブジェクト:: 
* FileCookieJar のサブクラスと web ブラウザとの連携:: 
* CookiePolicy オブジェクト:: 
* DefaultCookiePolicy オブジェクト:: 
* Cookieオブジェクト: Cookieオブジェクト<2>. 
* 使用例: 使用例<42>. 

@end menu

@node CookieJar および FileCookieJar オブジェクト,FileCookieJar のサブクラスと web ブラウザとの連携,,http cookiejar --- HTTP クライアント用の Cookie 処理
@anchor{library/http cookiejar cookie-jar-objects}@anchor{413c}@anchor{library/http cookiejar cookiejar-and-filecookiejar-objects}@anchor{413d}
@subsubsection CookieJar および FileCookieJar オブジェクト


@ref{3f53,,CookieJar} オブジェクトは保管されている @ref{413b,,Cookie} オブジェクトをひとつずつ取り出すための、 @ref{4c8,,イテレータ} プロトコルをサポートしています。

@ref{3f53,,CookieJar} は以下のようなメソッドを持っています:

@geindex add_cookie_header() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar add_cookie_header}@anchor{413e}
@deffn {メソッド} CookieJar.add_cookie_header (request)

`request' に正しい @code{Cookie} ヘッダを追加します。

ポリシーが許すようであれば (@ref{3f53,,CookieJar} の @ref{4136,,CookiePolicy} インスタンスにある属性のうち、 @code{rfc2965} および @code{hide_cookie2} がそれぞれ真と偽であるような場合)、必要に応じて @code{Cookie2} ヘッダも追加されます。

`request' オブジェクト (通常は @ref{11da,,urllib.request.Request} インスタンス) は、 @ref{111,,urllib.request} のドキュメントに記されているように、メソッド @code{get_full_url()}, @code{has_header()}, @code{get_header()}, @code{header_items()}, @code{add_unredirected_header()} および属性 @code{host}, @code{type}, @code{unverifiable}, @code{origin_req_host} をサポートしている必要があります。


バージョン 3.3 で変更: `request' オブジェクトには @code{origin_req_host} 属性が必要です。非推奨のメソッド @code{get_origin_req_host()} への依存は解消されました。

@end deffn

@geindex extract_cookies() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar extract_cookies}@anchor{413f}
@deffn {メソッド} CookieJar.extract_cookies (response, request)

HTTP `response' からクッキーを取り出し、ポリシーによって許可されていればこれを @ref{3f53,,CookieJar} 内に保管します。

@ref{3f53,,CookieJar} は `response' 引数の中から許可されている @code{Set-Cookie} および @code{Set-Cookie2} ヘッダを探しだし、適切に (@ref{4140,,CookiePolicy.set_ok()} メソッドの承認におうじて) クッキーを保管します。

`response' オブジェクト (通常は @ref{307,,urllib.request.urlopen()} あるいはそれに類似する呼び出しによって得られます) は @code{info()} メソッドをサポートしている必要があります。これは @ref{581,,email.message.Message} メソッドのあるオブジェクトを返すものです。

`request' オブジェクト (通常は @ref{11da,,urllib.request.Request} インスタンス) は @ref{111,,urllib.request} のドキュメントに記されているように、メソッド @code{get_full_url()}, および属性 @code{host}, @code{unverifiable}, @code{origin_req_host} をサポートしている必要があります。この request はそのクッキーの保存が許可されているかを検査するとともに、クッキー属性のデフォルト値を設定するのに使われます。


バージョン 3.3 で変更: `request' オブジェクトには @code{origin_req_host} 属性が必要です。非推奨のメソッド @code{get_origin_req_host()} への依存は解消されました。

@end deffn

@geindex set_policy() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar set_policy}@anchor{4141}
@deffn {メソッド} CookieJar.set_policy (policy)

使用する @ref{4136,,CookiePolicy} インスタンスを指定します。
@end deffn

@geindex make_cookies() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar make_cookies}@anchor{4142}
@deffn {メソッド} CookieJar.make_cookies (response, request)

`response' オブジェクトから得られた @ref{413b,,Cookie} オブジェクトからなるシーケンスを返します。

`response' および `request' 引数で要求されるインスタンスについては、 @ref{413f,,extract_cookies()} の説明を参照してください。
@end deffn

@geindex set_cookie_if_ok() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar set_cookie_if_ok}@anchor{4143}
@deffn {メソッド} CookieJar.set_cookie_if_ok (cookie, request)

ポリシーが許すのであれば、与えられた @ref{413b,,Cookie} を設定します。
@end deffn

@geindex set_cookie() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar set_cookie}@anchor{4144}
@deffn {メソッド} CookieJar.set_cookie (cookie)

与えられた @ref{413b,,Cookie} を、それが設定されるべきかどうかのポリシーのチェックを行わずに設定します。
@end deffn

@geindex clear() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar clear}@anchor{4145}
@deffn {メソッド} CookieJar.clear ([domain[, path[, name]]])

いくつかのクッキーを消去します。

引数なしで呼ばれた場合は、すべてのクッキーを消去します。引数がひとつ与えられた場合、その `domain' に属するクッキーのみを消去します。ふたつの引数が与えられた場合、指定された `domain' と URL `path' に属するクッキーのみを消去します。引数が 3つ与えられた場合、`domain', `path' および `name' で指定されるクッキーが消去されます。

与えられた条件に一致するクッキーがない場合は @ref{5e7,,KeyError} を発生させます。
@end deffn

@geindex clear_session_cookies() (http.cookiejar.CookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar CookieJar clear_session_cookies}@anchor{4146}
@deffn {メソッド} CookieJar.clear_session_cookies ()

すべてのセッションクッキーを消去します。

保存されているクッキーのうち、 @code{discard} 属性が真になっているものすべてを消去します (通常これは @code{max-age} または @code{expires} のどちらのクッキー属性もないか、あるいは明示的に @code{discard} クッキー属性が指定されているものです)。対話的なブラウザの場合、セッションの終了はふつうブラウザのウィンドウを閉じることに相当します。

注意: `ignore_discard' 引数に真を指定しないかぎり、 @code{save()} メソッドはセッションクッキーは保存しません。
@end deffn

さらに @ref{4135,,FileCookieJar} は以下のようなメソッドを実装しています:

@geindex save() (http.cookiejar.FileCookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar FileCookieJar save}@anchor{4147}
@deffn {メソッド} FileCookieJar.save (filename=None, ignore_discard=False, ignore_expires=False)

クッキーをファイルに保存します。

この基底クラスは  @ref{36b,,NotImplementedError} を発生させます。サブクラスはこのメソッドを実装しないままにしておいてもかまいません。

`filename' はクッキーを保存するファイルの名前です。 `filename' が指定されない場合、 @code{self.filename} が使用されます (このデフォルト値は、それが存在する場合は、コンストラクタに渡されています)。 @code{self.filename} も @ref{885,,None} の場合は @ref{2ec,,ValueError} が発生します。

`ignore_discard' : 破棄されるよう指示されていたクッキーでも保存します。`ignore_expires' : 期限の切れたクッキーでも保存します。

ここで指定されたファイルがもしすでに存在する場合は上書きされるため、以前にあったクッキーはすべて消去されます。保存したクッキーはあとで @ref{4137,,load()} または @ref{4138,,revert()} メソッドを使って復元することができます。
@end deffn

@geindex load() (http.cookiejar.FileCookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar FileCookieJar load}@anchor{4137}
@deffn {メソッド} FileCookieJar.load (filename=None, ignore_discard=False, ignore_expires=False)

ファイルからクッキーを読み込みます。

それまでのクッキーは新しいものに上書きされない限り残ります。

ここでの引数の値は @ref{4147,,save()} と同じです。

名前のついたファイルはこのクラスがわかるやり方で指定する必要があります。さもないと @ref{4134,,LoadError} が発生します。さらに、例えばファイルが存在しないような時に @ref{2c0,,OSError} が発生する場合があります。


バージョン 3.3 で変更: 以前は @ref{125e,,IOError} が送出されました; それは現在 @ref{2c0,,OSError} のエイリアスです。

@end deffn

@geindex revert() (http.cookiejar.FileCookieJar のメソッド)
@anchor{library/http cookiejar http cookiejar FileCookieJar revert}@anchor{4138}
@deffn {メソッド} FileCookieJar.revert (filename=None, ignore_discard=False, ignore_expires=False)

すべてのクッキーを破棄し、保存されているファイルから読み込み直します。

@ref{4138,,revert()} は @ref{4137,,load()} と同じ例外を発生させる事ができます。失敗した場合、オブジェクトの状態は変更されません。
@end deffn

@ref{4135,,FileCookieJar} インスタンスは以下のような公開の属性をもっています:

@geindex filename (http.cookiejar.FileCookieJar の属性)
@anchor{library/http cookiejar http cookiejar FileCookieJar filename}@anchor{4148}
@deffn {の属性} FileCookieJar.filename

クッキーを保存するデフォルトのファイル名を指定します。この属性には代入することができます。
@end deffn

@geindex delayload (http.cookiejar.FileCookieJar の属性)
@anchor{library/http cookiejar http cookiejar FileCookieJar delayload}@anchor{4149}
@deffn {の属性} FileCookieJar.delayload

真であれば、クッキーを読み込むさいにディスクから遅延読み込みします。この属性には代入することができません。この情報は単なるヒントであり、 (ディスク上のクッキーが変わらない限りは) インスタンスのふるまいには影響を与えず、パフォーマンスのみに影響します。 @ref{3f53,,CookieJar} オブジェクトはこの値を無視することもあります。標準ライブラリに含まれている @ref{4135,,FileCookieJar} クラスで遅延読み込みをおこなうものはありません。
@end deffn

@node FileCookieJar のサブクラスと web ブラウザとの連携,CookiePolicy オブジェクト,CookieJar および FileCookieJar オブジェクト,http cookiejar --- HTTP クライアント用の Cookie 処理
@anchor{library/http cookiejar file-cookie-jar-classes}@anchor{4139}@anchor{library/http cookiejar filecookiejar-subclasses-and-co-operation-with-web-browsers}@anchor{414a}
@subsubsection FileCookieJar のサブクラスと web ブラウザとの連携


クッキーの読み書きのために、以下の @ref{3f53,,CookieJar} サブクラスが提供されています。

@geindex MozillaCookieJar (http.cookiejar のクラス)
@anchor{library/http cookiejar http cookiejar MozillaCookieJar}@anchor{414b}
@deffn {クラス} http.cookiejar.MozillaCookieJar (filename=None, delayload=None, policy=None)

Mozilla の @code{cookies.txt} ファイル形式 (この形式はまた curl や Lynx と Netscape ブラウザによっても使われています) でディスクにクッキーを読み書きするための @ref{4135,,FileCookieJar} です。

@cartouche
@quotation 注釈 
このクラスは 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} クッキーに関する情報を失います。また、より新しいか、標準でない @code{port} などのクッキー属性についての情報も失います。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
もしクッキーの損失や欠損が望ましくない場合は、クッキーを保存する前にバックアップを取っておくようにしてください (ファイルへの読み込み / 保存をくり返すと微妙な変化が生じる場合があります)。
@end quotation
@end cartouche

また、Mozilla の起動中にクッキーを保存すると、Mozilla によって内容が破壊されてしまうことにも注意してください。
@end deffn

@geindex LWPCookieJar (http.cookiejar のクラス)
@anchor{library/http cookiejar http cookiejar LWPCookieJar}@anchor{414c}
@deffn {クラス} http.cookiejar.LWPCookieJar (filename=None, delayload=None, policy=None)

libwww-perl のライブラリである @code{Set-Cookie3} ファイル形式でディスクにクッキーを読み書きするための @ref{4135,,FileCookieJar} です。これはクッキーを人間に可読な形式で保存するのに向いています。


バージョン 3.8 で変更: `filename' 引数が @ref{5a1,,path-like object} を受け付けるようになりました。

@end deffn

@node CookiePolicy オブジェクト,DefaultCookiePolicy オブジェクト,FileCookieJar のサブクラスと web ブラウザとの連携,http cookiejar --- HTTP クライアント用の Cookie 処理
@anchor{library/http cookiejar cookie-policy-objects}@anchor{414d}@anchor{library/http cookiejar cookiepolicy-objects}@anchor{414e}
@subsubsection CookiePolicy オブジェクト


@ref{4136,,CookiePolicy} インターフェイスを実装するオブジェクトは以下のようなメソッドを持っています:

@geindex set_ok() (http.cookiejar.CookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar CookiePolicy set_ok}@anchor{4140}
@deffn {メソッド} CookiePolicy.set_ok (cookie, request)

クッキーがサーバから受け入れられるべきかどうかを表わす boolean 値を返します。

`cookie' は @ref{413b,,Cookie} インスタンスです。 `request' は @ref{413f,,CookieJar.extract_cookies()} の説明で定義されているインターフェイスを実装するオブジェクトです。
@end deffn

@geindex return_ok() (http.cookiejar.CookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar CookiePolicy return_ok}@anchor{414f}
@deffn {メソッド} CookiePolicy.return_ok (cookie, request)

クッキーがサーバに返されるべきかどうかを表わす boolean 値を返します。

`cookie' は @ref{413b,,Cookie} インスタンスです。 `request' は @ref{413e,,CookieJar.add_cookie_header()} の説明で定義されているインターフェイスを実装するオブジェクトです。
@end deffn

@geindex domain_return_ok() (http.cookiejar.CookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar CookiePolicy domain_return_ok}@anchor{4150}
@deffn {メソッド} CookiePolicy.domain_return_ok (domain, request)

与えられたクッキーのドメインに対して、そこにクッキーを返すべきでない場合には @code{False} を返します。

このメソッドは高速化のためのものです。これにより、すべてのクッキーをある特定のドメインに対してチェックする (これには多数のファイル読みこみを伴なう場合があります) 必要がなくなります。 @ref{4150,,domain_return_ok()} および @ref{4151,,path_return_ok()} の両方から true が返された場合、すべての決定は @ref{414f,,return_ok()} に委ねられます。

もし、このクッキードメインに対して @ref{4150,,domain_return_ok()} が true を返すと、つぎにそのクッキーのパス名に対して @ref{4151,,path_return_ok()} が呼ばれます。そうでない場合、そのクッキードメインに対する @ref{4151,,path_return_ok()} および @ref{414f,,return_ok()} は決して呼ばれることはありません。 @ref{4151,,path_return_ok()} が true を返すと、 @ref{414f,,return_ok()} がその @ref{413b,,Cookie} オブジェクト自身の全チェックのために呼ばれます。そうでない場合、そのクッキーパス名に対する @ref{414f,,return_ok()} は決して呼ばれることはありません。

注意: @ref{4150,,domain_return_ok()} は `request' ドメインだけではなく、すべての `cookie' ドメインに対して呼ばれます。たとえば request ドメインが @code{"www.example.com"} だった場合、この関数は @code{".example.com"} および @code{"www.example.com"} の両方に対して呼ばれることがあります。同じことは @ref{4151,,path_return_ok()} にもいえます。

`request' 引数は @ref{414f,,return_ok()} で説明されているとおりです。
@end deffn

@geindex path_return_ok() (http.cookiejar.CookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar CookiePolicy path_return_ok}@anchor{4151}
@deffn {メソッド} CookiePolicy.path_return_ok (path, request)

与えられたクッキーのパス名に対して、そこにクッキーを返すべきでない場合には @code{False} を返します。

@ref{4150,,domain_return_ok()} の説明を参照してください。
@end deffn

上のメソッドの実装にくわえて、 @ref{4136,,CookiePolicy} インターフェイスの実装では以下の属性を設定する必要があります。これはどのプロトコルがどのように使われるべきかを示すもので、これらの属性にはすべて代入することが許されています。

@geindex netscape (http.cookiejar.CookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar CookiePolicy netscape}@anchor{4152}
@deffn {の属性} CookiePolicy.netscape

Netscape プロトコルを実装していることを示します。
@end deffn

@geindex rfc2965 (http.cookiejar.CookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar CookiePolicy rfc2965}@anchor{4153}
@deffn {の属性} CookiePolicy.rfc2965

@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} プロトコルを実装していることを示します。
@end deffn

@geindex hide_cookie2 (http.cookiejar.CookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar CookiePolicy hide_cookie2}@anchor{4154}
@deffn {の属性} CookiePolicy.hide_cookie2

@code{Cookie2} ヘッダをリクエストに含めないようにします (このヘッダが存在する場合、私たちは 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} クッキーを理解するということをサーバに示すことになります)。
@end deffn

もっとも有用な方法は、 @ref{1df4,,DefaultCookiePolicy} をサブクラス化した @ref{4136,,CookiePolicy} クラスを定義して、いくつか (あるいはすべて) のメソッドをオーバーライドすることでしょう。 @ref{4136,,CookiePolicy} 自体はどのようなクッキーも受け入れて設定を許可する「ポリシー無し」ポリシーとして使うこともできます (これが役に立つことはあまりありませんが)。

@node DefaultCookiePolicy オブジェクト,Cookieオブジェクト<2>,CookiePolicy オブジェクト,http cookiejar --- HTTP クライアント用の Cookie 処理
@anchor{library/http cookiejar default-cookie-policy-objects}@anchor{4155}@anchor{library/http cookiejar defaultcookiepolicy-objects}@anchor{4156}
@subsubsection DefaultCookiePolicy オブジェクト


クッキーを受けつけ、またそれを返す際の標準的なルールを実装します。

@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} クッキーと Netscape クッキーの両方に対応しています。デフォルトでは、RFC 2965 の処理はオフになっています。

自分のポリシーを提供するいちばん簡単な方法は、このクラスを継承して、自分用の追加チェックの前にオーバーライドした元のメソッドを呼び出すことです:

@example
import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
    def set_ok(self, cookie, request):
        if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
            return False
        if i_dont_want_to_store_this_cookie(cookie):
            return False
        return True
@end example

@ref{4136,,CookiePolicy} インターフェイスを実装するのに必要な機能に加えて、このクラスではクッキーを受けとったり設定したりするドメインを許可したり拒絶したりできるようになっています。ほかにも、 Netscape プロトコルのかなり緩い規則をややきつくするために、いくつかの厳密性のスイッチがついています (いくつかの良性クッキーをブロックする危険性もありますが)。

ドメインの拒否リストや許可リストも提供されています (デフォルトではどちらもオフです)。拒否リストになく、(許可リストがアクティブなら) 許可リストにあるドメインのみがクッキーを設定したり返したりできます。コンストラクタの引数 `blocked_domains' 、および @code{blocked_domains()} と @code{set_blocked_domains()} メソッド ( そして `allowed_domains' に対応する引数とメソッド) を使ってください。許可リストを設定した場合は、それを @ref{885,,None} にすることでオフに戻せます。

拒否あるいは許可リスト中にあるドメインのうち、ドット (.) で始まっていないものは、正確にそれと一致するドメインのクッキーにしか適用されません。たとえば拒否リスト中のエントリ @code{"example.com"} は、@code{"example.com"} にはマッチしますが、@code{"www.example.com"} にはマッチしません。一方ドット (.) で始まっているドメインは、より特化されたドメインともマッチします。たとえば、@code{".example.com"} は、@code{"www.example.com"} と @code{"www.coyote.example.com"} の両方にマッチします (が、@code{"example.com"} 自身にはマッチしません)。IP アドレスは例外で、つねに正確に一致する必要があります。たとえば、`blocked_domains' が @code{"192.168.1.2"} と @code{".168.1.2"} を含んでいるとすると、192.168.1.2 はブロックされますが、193.168.1.2 はブロックされません。

@ref{1df4,,DefaultCookiePolicy} は以下のような追加メソッドを実装しています:

@geindex blocked_domains() (http.cookiejar.DefaultCookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy blocked_domains}@anchor{4157}
@deffn {メソッド} DefaultCookiePolicy.blocked_domains ()

ブロックしているドメインのシーケンスを (タプルとして) 返します。
@end deffn

@geindex set_blocked_domains() (http.cookiejar.DefaultCookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy set_blocked_domains}@anchor{4158}
@deffn {メソッド} DefaultCookiePolicy.set_blocked_domains (blocked_domains)

ブロックするドメインを設定します。
@end deffn

@geindex is_blocked() (http.cookiejar.DefaultCookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy is_blocked}@anchor{4159}
@deffn {メソッド} DefaultCookiePolicy.is_blocked (domain)

`domain' がクッキーを授受しない拒否リストに載っていれば @code{True} を返します。
@end deffn

@geindex allowed_domains() (http.cookiejar.DefaultCookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy allowed_domains}@anchor{415a}
@deffn {メソッド} DefaultCookiePolicy.allowed_domains ()

@ref{885,,None} あるいは明示的に許可されているドメインを (タプルとして) 返します。
@end deffn

@geindex set_allowed_domains() (http.cookiejar.DefaultCookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy set_allowed_domains}@anchor{415b}
@deffn {メソッド} DefaultCookiePolicy.set_allowed_domains (allowed_domains)

許可するドメイン、あるいは @ref{885,,None} を設定します。
@end deffn

@geindex is_not_allowed() (http.cookiejar.DefaultCookiePolicy のメソッド)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy is_not_allowed}@anchor{415c}
@deffn {メソッド} DefaultCookiePolicy.is_not_allowed (domain)

`domain' がクッキーを授受する許可リストに載っていれば @code{True} を返します。
@end deffn

@ref{1df4,,DefaultCookiePolicy} インスタンスは以下の属性をもっています。これらはすべてコンストラクタから同じ名前の引数をつかって初期化することができ、代入してもかまいません。

@geindex rfc2109_as_netscape (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy rfc2109_as_netscape}@anchor{413a}
@deffn {の属性} DefaultCookiePolicy.rfc2109_as_netscape

真の場合、 @ref{3f53,,CookieJar} のインスタンスに 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} クッキー (即ち @code{Set-Cookie} ヘッダのクッキー属性 Version の値が 1 のクッキー) を Netscapeクッキーへ、 @ref{413b,,Cookie} インスタンスの version 属性を 0 に設定する事でダウングレードするように要求します。デフォルトの値は @ref{885,,None} であり、この場合 RFC 2109 クッキーは 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} 処理が無効に設定されている場合に限りダウングレードされます。それ故に RFC 2109 クッキーはデフォルトではダウングレードされます。
@end deffn

一般的な厳密性のスイッチ:

@geindex strict_domain (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_domain}@anchor{415d}
@deffn {の属性} DefaultCookiePolicy.strict_domain

サイトに、国別コードとトップレベルドメインだけからなるドメイン名 (@code{.co.uk}, @code{.gov.uk}, @code{.co.nz} など) を設定させないようにします。これは完璧からはほど遠い実装であり、いつもうまくいくとは限りません!
@end deffn

@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} プロトコルの厳密性に関するスイッチ:

@geindex strict_rfc2965_unverifiable (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_rfc2965_unverifiable}@anchor{415e}
@deffn {の属性} DefaultCookiePolicy.strict_rfc2965_unverifiable

検証不可能なトランザクション (通常これはリダイレクトか、別のサイトがホスティングしているイメージの読み込み要求です) に関する 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} の規則に従います。この値が偽の場合、検証可能性を基準にしてクッキーがブロックされることは `決して' ありません
@end deffn

Netscape プロトコルの厳密性に関するスイッチ:

@geindex strict_ns_unverifiable (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_unverifiable}@anchor{415f}
@deffn {の属性} DefaultCookiePolicy.strict_ns_unverifiable

検証不可能なトランザクションに関する 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} の規則を Netscape クッキーに対しても適用します。
@end deffn

@geindex strict_ns_domain (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_domain}@anchor{4160}
@deffn {の属性} DefaultCookiePolicy.strict_ns_domain

Netscape クッキーに対するドメインマッチングの規則をどの程度厳しくするかを指示するフラグです。とりうる値については下の説明を見てください。
@end deffn

@geindex strict_ns_set_initial_dollar (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_initial_dollar}@anchor{4161}
@deffn {の属性} DefaultCookiePolicy.strict_ns_set_initial_dollar

Set-Cookie: ヘッダで、@code{'$'} で始まる名前のクッキーを無視します。
@end deffn

@geindex strict_ns_set_path (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_path}@anchor{4162}
@deffn {の属性} DefaultCookiePolicy.strict_ns_set_path

要求した URI にパスがマッチしないクッキーの設定を禁止します。
@end deffn

@ref{4160,,strict_ns_domain} is a collection of flags.  Its value is constructed by
or-ing together (for example, @code{DomainStrictNoDots|DomainStrictNonDomain} means
both flags are set).

@geindex DomainStrictNoDots (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNoDots}@anchor{4163}
@deffn {の属性} DefaultCookiePolicy.DomainStrictNoDots

クッキーを設定するさい、ホスト名のプレフィクスにドットが含まれるのを禁止します (例: @code{www.foo.bar.com} は @code{.bar.com} のクッキーを設定することはできません、なぜなら @code{www.foo} はドットを含んでいるからです)。
@end deffn

@geindex DomainStrictNonDomain (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNonDomain}@anchor{4164}
@deffn {の属性} DefaultCookiePolicy.DomainStrictNonDomain

@code{domain} クッキー属性を明示的に指定していないクッキーは、そのクッキーを設定したドメインと同一のドメインだけに返されます (例: @code{example.com} からのクッキーに @code{domain} クッキー属性がない場合、そのクッキーが @code{spam.example.com} に返されることはありません)。
@end deffn

@geindex DomainRFC2965Match (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainRFC2965Match}@anchor{4165}
@deffn {の属性} DefaultCookiePolicy.DomainRFC2965Match

クッキーを設定するさい、 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} の完全ドメインマッチングを要求します。
@end deffn

以下の属性は上記のフラグのうちもっともよく使われる組み合わせで、便宜をはかるために提供されています:

@geindex DomainLiberal (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainLiberal}@anchor{4166}
@deffn {の属性} DefaultCookiePolicy.DomainLiberal

0 と同じです (つまり、上述の Netscape のドメイン厳密性フラグがすべてオフにされます)。
@end deffn

@geindex DomainStrict (http.cookiejar.DefaultCookiePolicy の属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrict}@anchor{4167}
@deffn {の属性} DefaultCookiePolicy.DomainStrict

@code{DomainStrictNoDots|DomainStrictNonDomain} と同じです。
@end deffn

@node Cookieオブジェクト<2>,使用例<42>,DefaultCookiePolicy オブジェクト,http cookiejar --- HTTP クライアント用の Cookie 処理
@anchor{library/http cookiejar cookie-objects}@anchor{4168}
@subsubsection Cookieオブジェクト


@ref{413b,,Cookie} instances have Python attributes roughly corresponding to the
standard cookie-attributes specified in the various cookie standards.  The
correspondence is not one-to-one, because there are complicated rules for
assigning default values, because the @code{max-age} and @code{expires}
cookie-attributes contain equivalent information, and because 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} cookies
may be 'downgraded' by @code{http.cookiejar} from version 1 to version 0 (Netscape)
cookies.

@ref{4136,,CookiePolicy} メソッド内でのごくわずかな例外を除けば、これらの属性に代入する必要はないはずです。このクラスは内部の一貫性を保つようにはしていないため、代入するのは自分のやっていることを理解している場合のみにしてください。

@geindex version (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie version}@anchor{4169}
@deffn {の属性} Cookie.version

Integer or @ref{885,,None}.  Netscape cookies have @ref{4169,,version} 0. 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} and
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} cookies have a @code{version} cookie-attribute of 1.  However, note that
@code{http.cookiejar} may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
case @ref{4169,,version} is 0.
@end deffn

@geindex name (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie name}@anchor{416a}
@deffn {の属性} Cookie.name

クッキーの名前 (文字列)。
@end deffn

@geindex value (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie value}@anchor{416b}
@deffn {の属性} Cookie.value

クッキーの値 (文字列)、あるいは @ref{885,,None} 。
@end deffn

@geindex port (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie port}@anchor{416c}
@deffn {の属性} Cookie.port

ポートあるいはポートの集合をあらわす文字列 (例: '80' または '80,8080')、あるいは @ref{885,,None} 。
@end deffn

@geindex domain (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie domain}@anchor{416d}
@deffn {の属性} Cookie.domain

クッキーのドメイン (文字列) 。
@end deffn

@geindex path (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie path}@anchor{416e}
@deffn {の属性} Cookie.path

クッキーのパス名 (文字列、例: @code{'/acme/rocket_launchers'})。
@end deffn

@geindex secure (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie secure}@anchor{416f}
@deffn {の属性} Cookie.secure

そのクッキーを返せるのがセキュアな接続のみならば @code{True} を返します。
@end deffn

@geindex expires (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie expires}@anchor{4170}
@deffn {の属性} Cookie.expires

クッキーの期限が切れる日時をあわらす整数 (エポックから経過した秒数)、あるいは @ref{885,,None} 。 @ref{4171,,is_expired()} も参照してください。
@end deffn

@geindex discard (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie discard}@anchor{4172}
@deffn {の属性} Cookie.discard

これがセッションクッキーであれば @code{True} を返します。
@end deffn

@geindex comment (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie comment}@anchor{4173}
@deffn {の属性} Cookie.comment

このクッキーの働きを説明する、サーバからのコメント文字列、あるいは @ref{885,,None} 。
@end deffn

@geindex comment_url (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie comment_url}@anchor{4174}
@deffn {の属性} Cookie.comment_url

このクッキーの働きを説明する、サーバからのコメントのリンク URL、あるいは @ref{885,,None} 。
@end deffn

@geindex rfc2109 (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie rfc2109}@anchor{4175}
@deffn {の属性} Cookie.rfc2109

@code{True} if this cookie was received as an 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://datatracker.ietf.org/doc/html/rfc2109.html} cookie (ie. the cookie
arrived in a @code{Set-Cookie} header, and the value of the Version
cookie-attribute in that header was 1).  This attribute is provided because
@code{http.cookiejar} may 'downgrade' RFC 2109 cookies to Netscape cookies, in
which case @ref{4169,,version} is 0.
@end deffn

@geindex port_specified (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie port_specified}@anchor{4176}
@deffn {の属性} Cookie.port_specified

サーバがポート、あるいはポートの集合を (@code{Set-Cookie} / @code{Set-Cookie2} ヘッダ内で) 明示的に指定していれば @code{True} を返します。
@end deffn

@geindex domain_specified (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie domain_specified}@anchor{4177}
@deffn {の属性} Cookie.domain_specified

サーバにより明示的にドメインが指定されていれば @code{True} を返します。
@end deffn

@geindex domain_initial_dot (http.cookiejar.Cookie の属性)
@anchor{library/http cookiejar http cookiejar Cookie domain_initial_dot}@anchor{4178}
@deffn {の属性} Cookie.domain_initial_dot

サーバが明示的に指定したドメインがドット (@code{'.'}) で始まっていれば @code{True} を返します。
@end deffn

クッキーは、オプションとして標準的でないクッキー属性を持つこともできます。これらは以下のメソッドでアクセスできます:

@geindex has_nonstandard_attr() (http.cookiejar.Cookie のメソッド)
@anchor{library/http cookiejar http cookiejar Cookie has_nonstandard_attr}@anchor{4179}
@deffn {メソッド} Cookie.has_nonstandard_attr (name)

そのクッキーが指定された名前のクッキー属性をもっている場合には @code{True} を返します。
@end deffn

@geindex get_nonstandard_attr() (http.cookiejar.Cookie のメソッド)
@anchor{library/http cookiejar http cookiejar Cookie get_nonstandard_attr}@anchor{417a}
@deffn {メソッド} Cookie.get_nonstandard_attr (name, default=None)

クッキーが指定された名前のクッキー属性をもっていれば、その値を返します。そうでない場合は `default' を返します。
@end deffn

@geindex set_nonstandard_attr() (http.cookiejar.Cookie のメソッド)
@anchor{library/http cookiejar http cookiejar Cookie set_nonstandard_attr}@anchor{417b}
@deffn {メソッド} Cookie.set_nonstandard_attr (name, value)

指定された名前のクッキー属性を設定します。
@end deffn

@ref{413b,,Cookie} クラスは以下のメソッドも定義しています:

@geindex is_expired() (http.cookiejar.Cookie のメソッド)
@anchor{library/http cookiejar http cookiejar Cookie is_expired}@anchor{4171}
@deffn {メソッド} Cookie.is_expired (now=None)

サーバが要求するクッキーの有効期限を過ぎていれば @code{True} を返します。 `now' が (エポックからの経過秒で) 指定されているときは、特定の時刻で期限切れかどうかを判定します。
@end deffn

@node 使用例<42>,,Cookieオブジェクト<2>,http cookiejar --- HTTP クライアント用の Cookie 処理
@anchor{library/http cookiejar examples}@anchor{417c}
@subsubsection 使用例


The first example shows the most common usage of @code{http.cookiejar}:

@example
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
@end example

以下の例では、URL を開く際に Netscape や Mozilla または Lynx のクッキーを使う方法を示しています (クッキーファイルの位置は Unix/Netscape の慣例にしたがうものと仮定しています):

@example
import os, http.cookiejar, urllib.request
cj = http.cookiejar.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
@end example

つぎの例は @ref{1df4,,DefaultCookiePolicy} の使用例です。 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://datatracker.ietf.org/doc/html/rfc2965.html} クッキーをオンにし、Netscape クッキーを設定したり返したりするドメインに対してより厳密な規則を適用します。そしていくつかのドメインからクッキーを設定あるいは返還するのをブロックしています:

@example
import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
    rfc2965=True, strict_ns_domain=Policy.DomainStrict,
    blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xmlrpc --- XMLRPC サーバーとクライアントモジュール群,xmlrpc client --- XML-RPC クライアントアクセス,http cookiejar --- HTTP クライアント用の Cookie 処理,インターネットプロトコルとサポート
@anchor{library/xmlrpc doc}@anchor{417d}@anchor{library/xmlrpc module-xmlrpc}@anchor{133}@anchor{library/xmlrpc translation-repo}@anchor{417e}@anchor{library/xmlrpc xmlrpc-xmlrpc-server-and-client-modules}@anchor{417f}
@subsection @code{xmlrpc} --- XMLRPC サーバーとクライアントモジュール群


@geindex module; xmlrpc

XML-RPC は HTTP 経由の XML を使って遠隔手続き呼び出し (Remote Procedure Call) を実現する方法です。XML-RPC を使うと、クライアントはリモートサーバー (サーバーは URI で名前付けられます) 上のメソッドを引数付きで呼び出して、構造化されたデータを受け取る事ができます。

@code{xmlrpc} パッケージは XML-RPC のサーバーとクライアントを実装したモジュールを持っています。モジュール一覧:


@itemize *

@item 
@ref{134,,xmlrpc.client}

@item 
@ref{135,,xmlrpc.server}
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xmlrpc client --- XML-RPC クライアントアクセス,xmlrpc server --- 基本的な XML-RPC サーバー,xmlrpc --- XMLRPC サーバーとクライアントモジュール群,インターネットプロトコルとサポート
@anchor{library/xmlrpc client doc}@anchor{4180}@anchor{library/xmlrpc client module-xmlrpc client}@anchor{134}@anchor{library/xmlrpc client translation-repo}@anchor{4181}@anchor{library/xmlrpc client xmlrpc-client-xml-rpc-client-access}@anchor{4182}
@subsection @code{xmlrpc.client} --- XML-RPC クライアントアクセス


@geindex module; xmlrpc.client

`ソースコード:' Lib/xmlrpc/client.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xmlrpc/client.py}

@c XXX Not everything is documented yet.  It might be good to describe
@c Marshaller, Unmarshaller, getparser and Transport.


__________________________________________________________________


XML-RPCはXMLを利用した遠隔手続き呼び出し(Remote Procedure Call)の一種で、HTTP(S)をトランスポートとして使用します。XML- RPCでは、クライアントはリモートサーバ(URIで指定されたサーバ)上のメソッドをパラメータを指定して呼び出し、構造化されたデータを取得します。このモジュールは、XML-RPCクライアントの開発をサポートしており、Pythonオブジェクトに適合する転送用XMLの変換の全てを行います。

@cartouche
@quotation 警告 
The @code{xmlrpc.client} module is not secure against maliciously
constructed data.  If you need to parse untrusted or unauthenticated data,
see @ref{3ce9,,XML security}.
@end quotation
@end cartouche


バージョン 3.5 で変更: For HTTPS URIs, @code{xmlrpc.client} now performs all the necessary
certificate and hostname checks by default.


@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@geindex ServerProxy (xmlrpc.client のクラス)
@anchor{library/xmlrpc client xmlrpc client ServerProxy}@anchor{c4c}
@deffn {クラス} xmlrpc.client.ServerProxy (uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, headers=(), context=None)

@ref{c4c,,ServerProxy} は、リモートのXML-RPCサーバとの通信を管理するオブジェクトです。最初のパラメータはURI(Uniform Resource Indicator)で、通常はサーバのURLを指定します。2番目のパラメータにはトランスポート・ファクトリを指定する事ができます。トランスポート・ファクトリを省略した場合、URLが https: ならモジュール内部の @code{SafeTransport} インスタンスを使用し、それ以外の場合にはモジュール内部の @code{Transport} インスタンスを使用します。オプションの 3 番目の引数はエンコード方法で、デフォルトでは UTF-8 です。オプションの 4 番目の引数はデバッグフラグです。

The following parameters govern the use of the returned proxy instance.
If `allow_none' is true,  the Python constant @code{None} will be translated into
XML; the default behaviour is for @code{None} to raise a @ref{198,,TypeError}. This is
a commonly used extension to the XML-RPC specification, but isn't supported by
all clients and servers; see http://ontosys.com/xml-rpc/extensions.php@footnote{https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php}
for a description.
The `use_builtin_types' flag can be used to cause date/time values
to be presented as @ref{4e2,,datetime.datetime} objects and binary data to be
presented as @ref{192,,bytes} objects; this flag is false by default.
@ref{4e2,,datetime.datetime}, @ref{192,,bytes} and @ref{344,,bytearray} objects
may be passed to calls.
The `headers' parameter is an optional sequence of HTTP headers to send with
each request, expressed as a sequence of 2-tuples representing the header
name and value. (e.g. @code{[('Header-Name', 'value')]}).
If an HTTPS URL is provided, `context' may be @ref{357,,ssl.SSLContext}
and configures the SSL settings of the underlying HTTPS connection.
The obsolete `use_datetime' flag is similar to `use_builtin_types' but it
applies only to date/time values.


バージョン 3.3 で変更: `use_builtin_types' フラグが追加されました。



バージョン 3.8 で変更: `headers' 引数が追加されました。


HTTP及びHTTPS通信の両方で、 @code{http://user:pass@@host:port/path} のようなHTTP基本認証のための拡張URL構文をサポートしています。 @code{user:pass} はbase64でエンコードしてHTTPの'Authorization 'ヘッダとなり、XML-RPCメソッド呼び出し時に接続処理の一部としてリモートサーバに送信されます。リモートサーバが基本認証を要求する場合のみ、この機能を利用する必要があります。

生成されるインスタンスはリモートサーバへのプロクシオブジェクトで、RPC呼び出しを行う為のメソッドを持ちます。リモートサーバがイントロスペクション APIをサポートしている場合は、リモートサーバのサポートするメソッドを検索 (サービス検索)やサーバのメタデータの取得なども行えます。

以下の型をXMLに変換(XMLを通じてマーシャルする)する事ができます (特別な指定がない限り、逆変換でも同じ型として変換されます):


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

XML-RPC の型

@tab

Python の型

@item

@code{boolean}

@tab

@ref{3c3,,bool}

@item

@code{int}, @code{i1}, @code{i2},  @code{i4}, @code{i8} または @code{biginteger}

@tab

@ref{19b,,int} in range from -2147483648 to 2147483647.
Values get the @code{<int>} tag.

@item

@code{double} または @code{float}

@tab

@ref{196,,float}.  Values get the @code{<double>} tag.

@item

@code{string}

@tab

@ref{169,,str}

@item

@code{array}

@tab

適合する要素を持つ @ref{24d,,list} または @ref{614,,tuple}。array は @ref{24d,,list} として返します。

@item

@code{struct}

@tab

@ref{183,,dict} 。キーは文字列のみ。全ての値は変換可能でなくてはならない。ユーザー定義型を渡すこともできます。 @ref{77d,,__dict__} の属性のみ転送されます。

@item

@code{dateTime.iso8601}

@tab

@ref{15fc,,DateTime} または @ref{4e2,,datetime.datetime}。返される型は `use_builtin_types' および `use_datetime' の値に依ります。

@item

@code{base64}

@tab

@ref{4183,,Binary}、 @ref{192,,bytes} または @ref{344,,bytearray}。返される型は `use_builtin_types' フラグの値に依ります。

@item

@code{nil}

@tab

@code{None} 定数。 `allow_none' が真の場合にのみ渡すことが出来ます。

@item

@code{bigdecimal}

@tab

@ref{1fe,,decimal.Decimal}.  Returned type only.

@end multitable


上記のXML-RPCでサポートする全データ型を使用することができます。メソッド呼び出し時、XML- RPCサーバエラーが発生すると @ref{4184,,Fault} インスタンスを送出し、HTTP/HTTPSトランスポート層でエラーが発生した場合には @ref{4185,,ProtocolError} を送出します。 @code{Error} をベースとする @ref{4184,,Fault} と @ref{4185,,ProtocolError} の両方が発生します。現在のところxmlrpclibでは組み込み型のサブクラスのインスタンスをマーシャルすることはできません。

文字列を渡す場合、 @code{<}, @code{>}, @code{&} などのXMLで特殊な意味を持つ文字は自動的にエスケープされます。しかし、ASCII値0〜31の制御文字(もちろん、タブ'TAB',改行'LF',リターン'CR'は除く)などのXMLで使用することのできない文字を使用することはできず、使用するとそのXML-RPCリクエストはwell-formedなXMLとはなりません。そのようなバイト列を渡す必要がある場合は、 @ref{192,,bytes}, @ref{344,,bytearray} クラスまたは後述の @ref{4183,,Binary} ラッパークラスを使用してください。

@code{Server} は、後方互換性の為に @ref{c4c,,ServerProxy} の別名として残されています。新しいコードでは @ref{c4c,,ServerProxy} を使用してください。


バージョン 3.5 で変更: `context' 引数が追加されました。



バージョン 3.6 で変更: Added support of type tags with prefixes (e.g. @code{ex:nil}).
Added support of unmarshalling additional types used by Apache XML-RPC
implementation for numerics: @code{i1}, @code{i2}, @code{i8}, @code{biginteger},
@code{float} and @code{bigdecimal}.
See @indicateurl{https://ws.apache.org/xmlrpc/types.html} for a description.

@end deffn


@subsubheading 参考



@table @asis

@item XML-RPC HOWTO@footnote{https://tldp.org/HOWTO/XML-RPC-HOWTO/index.html}

数種類のプログラミング言語で記述された XML-RPCの操作とクライアントソフトウェアの素晴らしい説明が掲載されています。 XML- RPCクライアントの開発者が知っておくべきことがほとんど全て記載されています。

@item XML-RPC Introspection@footnote{https://xmlrpc-c.sourceforge.io/introspection.html}

インストロペクションをサポートする、 XML-RPC プロトコルの拡張を解説しています。

@item XML-RPC Specification@footnote{http://xmlrpc.scripting.com/spec.html}

公式の仕様
@end table


@menu
* ServerProxy オブジェクト:: 
* DateTime オブジェクト:: 
* Binary オブジェクト:: 
* Fault オブジェクト:: 
* ProtocolError オブジェクト:: 
* MultiCall オブジェクト:: 
* 補助関数:: 
* クライアントのサンプル:: 
* クライアントとサーバーの利用例:: 

@end menu

@node ServerProxy オブジェクト,DateTime オブジェクト,,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client id1}@anchor{4186}@anchor{library/xmlrpc client serverproxy-objects}@anchor{4187}
@subsubsection ServerProxy オブジェクト


@ref{c4c,,ServerProxy} インスタンスの各メソッドはそれぞれXML-RPCサーバの遠隔手続き呼び出しに対応しており、メソッドが呼び出されると名前と引数をシグネチャとしてRPCを実行します(同じ名前のメソッドでも、異なる引数シグネチャによってオーバロードされます)。RPC実行後、変換された値を返すか、または @ref{4184,,Fault} オブジェクトもしくは @ref{4185,,ProtocolError} オブジェクトでエラーを通知します。

予約属性 @code{system} から、XMLイントロスペクションAPIの一般的なメソッドを利用する事ができます:

@geindex listMethods() (xmlrpc.client.ServerProxy.system のメソッド)
@anchor{library/xmlrpc client xmlrpc client ServerProxy system listMethods}@anchor{4188}
@deffn {メソッド} ServerProxy.system.listMethods ()

XML-RPCサーバがサポートするメソッド名(system以外)を格納する文字列のリストを返します。
@end deffn

@geindex methodSignature() (xmlrpc.client.ServerProxy.system のメソッド)
@anchor{library/xmlrpc client xmlrpc client ServerProxy system methodSignature}@anchor{4189}
@deffn {メソッド} ServerProxy.system.methodSignature (name)

XML-RPCサーバで実装されているメソッドの名前を指定し、利用可能なシグネチャの配列を取得します。シグネチャは型のリストで、先頭の型は戻り値の型を示し、以降はパラメータの型を示します。

XML-RPCでは複数のシグネチャ(オーバロード)を使用することができるので、単独のシグネチャではなく、シグネチャのリストを返します。

シグネチャは、メソッドが使用する最上位のパラメータにのみ適用されます。例えばあるメソッドのパラメータが構造体の配列で戻り値が文字列の場合、シグネチャは単に"string, array" となります。パラメータが三つの整数で戻り値が文字列の場合は"string, int, int, int"となります。

メソッドにシグネチャが定義されていない場合、配列以外の値が返ります。 Pythonでは、この値はlist以外の値となります。
@end deffn

@geindex methodHelp() (xmlrpc.client.ServerProxy.system のメソッド)
@anchor{library/xmlrpc client xmlrpc client ServerProxy system methodHelp}@anchor{418a}
@deffn {メソッド} ServerProxy.system.methodHelp (name)

XML-RPCサーバで実装されているメソッドの名前を指定し、そのメソッドを解説する文書文字列を取得します。文書文字列を取得できない場合は空文字列を返します。文書文字列にはHTMLマークアップが含まれます。
@end deffn


バージョン 3.5 で変更: Instances of @ref{c4c,,ServerProxy} support the @ref{1e1,,context manager} protocol
for closing the underlying transport.


以下は、動作する例です。サーバ側のコード:

@example
from xmlrpc.server import SimpleXMLRPCServer

def is_even(n):
    return n % 2 == 0

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever()
@end example

上記のサーバーに対するクライアントコード:

@example
import xmlrpc.client

with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
    print("3 is even: %s" % str(proxy.is_even(3)))
    print("100 is even: %s" % str(proxy.is_even(100)))
@end example

@node DateTime オブジェクト,Binary オブジェクト,ServerProxy オブジェクト,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client datetime-objects}@anchor{418b}@anchor{library/xmlrpc client id2}@anchor{418c}
@subsubsection DateTime オブジェクト


@geindex DateTime (xmlrpc.client のクラス)
@anchor{library/xmlrpc client xmlrpc client DateTime}@anchor{15fc}
@deffn {クラス} xmlrpc.client.DateTime

このクラスは、エポックからの秒数、タプルで表現された時刻、ISO 8601形式の時間/日付文字列、 @ref{4e2,,datetime.datetime}, のインスタンスのいずれかで初期化することができます。このクラスには以下のメソッドがあり、主にコードをマーシャル/アンマーシャルするための内部処理を行います:

@geindex decode() (xmlrpc.client.DateTime のメソッド)
@anchor{library/xmlrpc client xmlrpc client DateTime decode}@anchor{418d}
@deffn {メソッド} decode (string)

文字列をインスタンスの新しい時間を示す値として指定します。
@end deffn

@geindex encode() (xmlrpc.client.DateTime のメソッド)
@anchor{library/xmlrpc client xmlrpc client DateTime encode}@anchor{418e}
@deffn {メソッド} encode (out)

出力ストリームオブジェクト `out' に、XML-RPCエンコーディングの @ref{15fc,,DateTime} 値を出力します。
@end deffn

It also supports certain of Python's built-in operators through
@ref{14b8,,rich comparison} and @ref{82f,,__repr__()}
methods.
@end deffn

以下は、動作する例です。サーバ側のコード:

@example
import datetime
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

def today():
    today = datetime.datetime.today()
    return xmlrpc.client.DateTime(today)

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(today, "today")
server.serve_forever()
@end example

上記のサーバーに対するクライアントコード:

@example
import xmlrpc.client
import datetime

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")

today = proxy.today()
# convert the ISO8601 string to a datetime object
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
@end example

@node Binary オブジェクト,Fault オブジェクト,DateTime オブジェクト,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client binary-objects}@anchor{418f}@anchor{library/xmlrpc client id3}@anchor{4190}
@subsubsection Binary オブジェクト


@geindex Binary (xmlrpc.client のクラス)
@anchor{library/xmlrpc client xmlrpc client Binary}@anchor{4183}
@deffn {クラス} xmlrpc.client.Binary

このクラスは、バイト列データ(NULを含む)で初期化することができます。 @ref{4183,,Binary} の内容は、属性で参照します:

@geindex data (xmlrpc.client.Binary の属性)
@anchor{library/xmlrpc client xmlrpc client Binary data}@anchor{4191}
@deffn {の属性} data

@ref{4183,,Binary} インスタンスがカプセル化しているバイナリデータ。このデータは @ref{192,,bytes} オブジェクトです。
@end deffn

@ref{4183,,Binary} オブジェクトは以下のメソッドを持ち、主に内部的にマーシャル/アンマーシャル時に使用されます:

@geindex decode() (xmlrpc.client.Binary のメソッド)
@anchor{library/xmlrpc client xmlrpc client Binary decode}@anchor{4192}
@deffn {メソッド} decode (bytes)

指定されたbase64 @ref{192,,bytes} オブジェクトをデコードし、インスタンスのデータとします。
@end deffn

@geindex encode() (xmlrpc.client.Binary のメソッド)
@anchor{library/xmlrpc client xmlrpc client Binary encode}@anchor{4193}
@deffn {メソッド} encode (out)

バイナリ値をbase64でエンコードし、出力ストリームオブジェクト `out' に出力します。

エンコードされたデータは、 
@geindex RFC; RFC 2045 Section 6.8
RFC 2045 section 6.8@footnote{https://datatracker.ietf.org/doc/html/rfc2045.html#section-6.8} にある通り、76文字ごとに改行されます。これは、XMC-RPC仕様が作成された時のデ・ファクト・スタンダードのbase64です。
@end deffn

It also supports certain of Python's built-in operators through
@ref{cf2,,__eq__()} and @ref{1730,,__ne__()} methods.
@end deffn

バイナリオブジェクトの使用例です。 XML-RPCごしに画像を転送します。

@example
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

def python_logo():
    with open("python_logo.jpg", "rb") as handle:
        return xmlrpc.client.Binary(handle.read())

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(python_logo, 'python_logo')

server.serve_forever()
@end example

クライアントは画像を取得して、ファイルに保存します。

@example
import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
with open("fetched_python_logo.jpg", "wb") as handle:
    handle.write(proxy.python_logo().data)
@end example

@node Fault オブジェクト,ProtocolError オブジェクト,Binary オブジェクト,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client fault-objects}@anchor{4194}@anchor{library/xmlrpc client id4}@anchor{4195}
@subsubsection Fault オブジェクト


@geindex Fault (xmlrpc.client のクラス)
@anchor{library/xmlrpc client xmlrpc client Fault}@anchor{4184}
@deffn {クラス} xmlrpc.client.Fault

@ref{4184,,Fault} オブジェクトは、XML-RPCのfaultタグの内容をカプセル化しており、以下の属性を持ちます:

@geindex faultCode (xmlrpc.client.Fault の属性)
@anchor{library/xmlrpc client xmlrpc client Fault faultCode}@anchor{4196}
@deffn {の属性} faultCode

失敗のタイプを示す整数。
@end deffn

@geindex faultString (xmlrpc.client.Fault の属性)
@anchor{library/xmlrpc client xmlrpc client Fault faultString}@anchor{4197}
@deffn {の属性} faultString

失敗の診断メッセージを含む文字列。
@end deffn
@end deffn

以下のサンプルでは、複素数型のオブジェクトを返そうとして、故意に @ref{4184,,Fault} を起こしています。

@example
from xmlrpc.server import SimpleXMLRPCServer

# A marshalling error is going to occur because we're returning a
# complex number
def add(x, y):
    return x+y+0j

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(add, 'add')

server.serve_forever()
@end example

上記のサーバーに対するクライアントコード:

@example
import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
try:
    proxy.add(2, 5)
except xmlrpc.client.Fault as err:
    print("A fault occurred")
    print("Fault code: %d" % err.faultCode)
    print("Fault string: %s" % err.faultString)
@end example

@node ProtocolError オブジェクト,MultiCall オブジェクト,Fault オブジェクト,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client protocol-error-objects}@anchor{4198}@anchor{library/xmlrpc client protocolerror-objects}@anchor{4199}
@subsubsection ProtocolError オブジェクト


@geindex ProtocolError (xmlrpc.client のクラス)
@anchor{library/xmlrpc client xmlrpc client ProtocolError}@anchor{4185}
@deffn {クラス} xmlrpc.client.ProtocolError

@ref{4185,,ProtocolError} オブジェクトはトランスポート層で発生したエラー(URI で指定したサーバが見つからなかった場合に発生する404 'not found'など)の内容を示し、以下の属性を持ちます:

@geindex url (xmlrpc.client.ProtocolError の属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError url}@anchor{419a}
@deffn {の属性} url

エラーの原因となったURIまたはURL。
@end deffn

@geindex errcode (xmlrpc.client.ProtocolError の属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError errcode}@anchor{419b}
@deffn {の属性} errcode

エラーコード。
@end deffn

@geindex errmsg (xmlrpc.client.ProtocolError の属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError errmsg}@anchor{419c}
@deffn {の属性} errmsg

エラーメッセージまたは診断文字列。
@end deffn

@geindex headers (xmlrpc.client.ProtocolError の属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError headers}@anchor{419d}
@deffn {の属性} headers

エラーの原因となったHTTP/HTTPSリクエストを含む辞書。
@end deffn
@end deffn

次の例では、不適切な URI を利用して、故意に @ref{4185,,ProtocolError} を発生させています:

@example
import xmlrpc.client

# create a ServerProxy with a URI that doesn't respond to XMLRPC requests
proxy = xmlrpc.client.ServerProxy("http://google.com/")

try:
    proxy.some_method()
except xmlrpc.client.ProtocolError as err:
    print("A protocol error occurred")
    print("URL: %s" % err.url)
    print("HTTP/HTTPS headers: %s" % err.headers)
    print("Error code: %d" % err.errcode)
    print("Error message: %s" % err.errmsg)
@end example

@node MultiCall オブジェクト,補助関数,ProtocolError オブジェクト,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client multicall-objects}@anchor{419e}
@subsubsection MultiCall オブジェクト


@ref{419f,,MultiCall} オブジェクトは遠隔のサーバに対する複数の呼び出しをひとつのリクエストにカプセル化する方法を提供します @footnote{
このアプローチは @uref{https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic,a discussion on xmlrpc.com} にて最初に著されました。
}。

@geindex MultiCall (xmlrpc.client のクラス)
@anchor{library/xmlrpc client xmlrpc client MultiCall}@anchor{419f}
@deffn {クラス} xmlrpc.client.MultiCall (server)

巨大な (boxcar) メソッド呼び出しに使えるオブジェクトを作成します。 `server' には最終的に呼び出しを行う対象を指定します。作成した MultiCall オブジェクトを使って呼び出しを行うと、即座に @code{None} を返し、呼び出したい手続き名とパラメタを @ref{419f,,MultiCall} オブジェクトに保存するだけに留まります。オブジェクト自体を呼び出すと、それまでに保存しておいたすべての呼び出しを単一の @code{system.multicall} リクエストの形で伝送します。呼び出し結果は @ref{126c,,ジェネレータ} になります。このジェネレータにわたってイテレーションを行うと、個々の呼び出し結果を返します。
@end deffn

以下は、このクラスの使用例です。サーバ側のコード:

@example
from xmlrpc.server import SimpleXMLRPCServer

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x // y

# A simple server with simple arithmetic functions
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_multicall_functions()
server.register_function(add, 'add')
server.register_function(subtract, 'subtract')
server.register_function(multiply, 'multiply')
server.register_function(divide, 'divide')
server.serve_forever()
@end example

上記のサーバーに対するクライアントコード:

@example
import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
multicall = xmlrpc.client.MultiCall(proxy)
multicall.add(7, 3)
multicall.subtract(7, 3)
multicall.multiply(7, 3)
multicall.divide(7, 3)
result = multicall()

print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
@end example

@node 補助関数,クライアントのサンプル,MultiCall オブジェクト,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client convenience-functions}@anchor{41a0}
@subsubsection 補助関数


@geindex dumps() (xmlrpc.client モジュール)
@anchor{library/xmlrpc client xmlrpc client dumps}@anchor{41a1}
@deffn {の関数} xmlrpc.client.dumps (params, methodname=None, methodresponse=None, encoding=None, allow_none=False)

Convert `params' into an XML-RPC request, or into a response if `methodresponse'
is true. `params' can be either a tuple of arguments or an instance of the
@ref{4184,,Fault} exception class.  If `methodresponse' is true, only a single value
can be returned, meaning that `params' must be of length 1. `encoding', if
supplied, is the encoding to use in the generated XML; the default is UTF-8.
Python's @ref{885,,None} value cannot be used in standard XML-RPC; to allow using
it via an extension,  provide a true value for `allow_none'.
@end deffn

@geindex loads() (xmlrpc.client モジュール)
@anchor{library/xmlrpc client xmlrpc client loads}@anchor{164e}
@deffn {の関数} xmlrpc.client.loads (data, use_datetime=False, use_builtin_types=False)

XML-RPC リクエストまたはレスポンスを @code{(params, methodname)} の形式をとる Python オブジェクトにします。 `params' は引数のタプルです。 `methodname' は文字列で、パケット中にメソッド名がない場合には @code{None} になります。例外条件を示す XML-RPC パケットの場合には、 @ref{4184,,Fault} 例外を送出します。 `use_builtin_types' フラグは @ref{4e2,,datetime.datetime} のオブジェクトとして日付/時刻を、 @ref{192,,bytes} のオブジェクトとしてバイナリデータを表現する時に使用し、デフォルトでは false に設定されています。

非推奨となった `use_datetime' フラグは `use_builtin_types' に似ていますが date/time 値にのみ適用されます。


バージョン 3.3 で変更: `use_builtin_types' フラグが追加されました。

@end deffn

@node クライアントのサンプル,クライアントとサーバーの利用例,補助関数,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client example-of-client-usage}@anchor{41a2}@anchor{library/xmlrpc client xmlrpc-client-example}@anchor{41a3}
@subsubsection クライアントのサンプル


@example
# simple test program (from the XML-RPC specification)
from xmlrpc.client import ServerProxy, Error

# server = ServerProxy("http://localhost:8000") # local server
with ServerProxy("http://betty.userland.com") as proxy:

    print(proxy)

    try:
        print(proxy.examples.getStateName(41))
    except Error as v:
        print("ERROR", v)
@end example

XML-RPC サーバに HTTP プロキシを経由して接続する場合、カスタムトランスポートを定義する必要があります。以下に例を示します:

@example
import http.client
import xmlrpc.client

class ProxiedTransport(xmlrpc.client.Transport):

    def set_proxy(self, host, port=None, headers=None):
        self.proxy = host, port
        self.proxy_headers = headers

    def make_connection(self, host):
        connection = http.client.HTTPConnection(*self.proxy)
        connection.set_tunnel(host, headers=self.proxy_headers)
        self._connection = host, connection
        return connection

transport = ProxiedTransport()
transport.set_proxy('proxy-server', 8080)
server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
print(server.examples.getStateName(41))
@end example

@node クライアントとサーバーの利用例,,クライアントのサンプル,xmlrpc client --- XML-RPC クライアントアクセス
@anchor{library/xmlrpc client example-of-client-and-server-usage}@anchor{41a4}
@subsubsection クライアントとサーバーの利用例


@ref{41a5,,SimpleXMLRPCServer の例} を参照してください。

@subsubheading 脚注


@c the link now points to webarchive since the one at

@c http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin

@c doesn't reply)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xmlrpc server --- 基本的な XML-RPC サーバー,ipaddress --- IPv4/IPv6 操作ライブラリ,xmlrpc client --- XML-RPC クライアントアクセス,インターネットプロトコルとサポート
@anchor{library/xmlrpc server doc}@anchor{41a6}@anchor{library/xmlrpc server module-xmlrpc server}@anchor{135}@anchor{library/xmlrpc server translation-repo}@anchor{41a7}@anchor{library/xmlrpc server xmlrpc-server-basic-xml-rpc-servers}@anchor{41a8}
@subsection @code{xmlrpc.server} --- 基本的な XML-RPC サーバー


@geindex module; xmlrpc.server

`ソースコード:' Lib/xmlrpc/server.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/xmlrpc/server.py}


__________________________________________________________________


The @code{xmlrpc.server} module provides a basic server framework for XML-RPC
servers written in Python.  Servers can either be free standing, using
@ref{41a9,,SimpleXMLRPCServer}, or embedded in a CGI environment, using
@ref{41aa,,CGIXMLRPCRequestHandler}.

@cartouche
@quotation 警告 
The @code{xmlrpc.server} module is not secure against maliciously
constructed data.  If you need to parse untrusted or unauthenticated data,
see @ref{3ce9,,XML security}.
@end quotation
@end cartouche

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@geindex SimpleXMLRPCServer (xmlrpc.server のクラス)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer}@anchor{41a9}
@deffn {クラス} xmlrpc.server.SimpleXMLRPCServer (addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False)

サーバーインスタンスを新たに作成します。
このクラスは XML-RPC プロトコルで呼ばれる関数の登録のためのメソッドを提供します。
引数 `requestHandler' にはリクエストハンドラーインスタンスのファクトリーを設定します。
デフォルトは @ref{153f,,SimpleXMLRPCRequestHandler} です。
引数 `addr' と `requestHandler' は @ref{1537,,socketserver.TCPServer} のコンストラクターに渡されます。
`logRequests' が真の場合 (デフォルト)、 リクエストはログに記録されます。
この引数を偽にするとはログは記録されません。
引数 `allow_none' と `encoding' は @ref{134,,xmlrpc.client} に渡され、サーバーが返す XML-RPC 応答を制御します。
`bind_and_activate' 引数はコンストラクタが直ちに @code{server_bind()} と @code{server_activate()} を呼ぶかどうかを制御します。デフォルトでは真です。
この引数に @code{False} を設定することで、アドレスを束縛する前に `allow_reuse_address' クラス変数を操作することが出来ます。
`use_builtin_types' 引数は @ref{164e,,loads()} 関数に渡されます。
この引数は日付/時刻の値やバイナリデータを受け取ったときにどの型が処理されるかを制御します。デフォルトでは偽です。


バージョン 3.3 で変更: `use_builtin_types' フラグが追加されました。

@end deffn

@geindex CGIXMLRPCRequestHandler (xmlrpc.server のクラス)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler}@anchor{41aa}
@deffn {クラス} xmlrpc.server.CGIXMLRPCRequestHandler (allow_none=False, encoding=None, use_builtin_types=False)

CGI 環境における XML-RPC リクエストハンドラーを新たに作成します。
引数 `allow_none' と `encoding' は @ref{134,,xmlrpc.client} に渡され、サーバーが返す XML-RPC 応答を制御します。
`use_builtin_types' 引数は @ref{164e,,loads()} 関数に渡されます。
この引数は日付/時刻の値やバイナリデータを受け取ったときにどの型が処理されるかを制御します。デフォルトは偽です。


バージョン 3.3 で変更: `use_builtin_types' フラグが追加されました。

@end deffn

@geindex SimpleXMLRPCRequestHandler (xmlrpc.server のクラス)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler}@anchor{153f}
@deffn {クラス} xmlrpc.server.SimpleXMLRPCRequestHandler

リクエストハンドラーインスタンスを新たに作成します。このリクエストハンドラーは @code{POST} リクエストをサポートし、 @ref{41a9,,SimpleXMLRPCServer} コンストラクターの引数 `logRequests' に従ってログ出力を行います。
@end deffn

@menu
* SimpleXMLRPCServer オブジェクト:: 
* CGIXMLRPCRequestHandler:: 
* XMLRPC サーバの文書化:: 
* DocXMLRPCServer オブジェクト:: 
* DocCGIXMLRPCRequestHandler:: 

@end menu

@node SimpleXMLRPCServer オブジェクト,CGIXMLRPCRequestHandler,,xmlrpc server --- 基本的な XML-RPC サーバー
@anchor{library/xmlrpc server simple-xmlrpc-servers}@anchor{41ab}@anchor{library/xmlrpc server simplexmlrpcserver-objects}@anchor{41ac}
@subsubsection SimpleXMLRPCServer オブジェクト


@ref{41a9,,SimpleXMLRPCServer} クラスは @ref{1537,,socketserver.TCPServer} のサブクラスで、基本的なスタンドアロンの XML-RPC サーバーを作成する手段を提供します。

@geindex register_function() (xmlrpc.server.SimpleXMLRPCServer のメソッド)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_function}@anchor{41ad}
@deffn {メソッド} SimpleXMLRPCServer.register_function (function=None, name=None)

XML-RPC リクエストに応答可能な関数を登録します。引数 `name' が与えられた場合は、それが関数 `function' に関連付けられたメソッド名となります。そうでない場合は、 @ref{14ec,,function.__name__} の値が用いられます。引数 `name' は文字列で、例えばピリオド "." のようなPythonで識別子として正しくない文字を含んでいても構いません。

このメソッドはデコレーターとしても使用することができます。デコレーターとして使用するときは、 `name' は関数を `name' で登録するキーワード引数としてのみ渡すことができます。 `name' が与えられていないときは、 @ref{14ec,,function.__name__} が使用されます。


バージョン 3.7 で変更: @ref{41ad,,register_function()} はデコレーターとして使用できます。

@end deffn

@geindex register_instance() (xmlrpc.server.SimpleXMLRPCServer のメソッド)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_instance}@anchor{41ae}
@deffn {メソッド} SimpleXMLRPCServer.register_instance (instance, allow_dotted_names=False)

オブジェクトを登録します。
オブジェクトは @ref{41ad,,register_function()} を使用して登録されていないメソッド名を公開するのに使われます。
`instance' に @code{_dispatch()}  メソッドがあった場合、リクエストされたメソッド名と引数で @code{_dispatch()}  を呼び出します。
API は @code{def _dispatch(self, method, params)} (`params' 可変引数リストではないことに注意) です。
タスクを実行するのに下層の関数を呼び出す場合、その関数は @code{func(*params)} のように引数リストを展開して呼び出されます。
@code{_dispatch()} の返り値は結果としてクライアントに返されます。
`instance' に @code{_dispatch()} メソッドがない場合、リクエストされたメソッド名にマッチする属性を検索します。

オプション引数 `allow_dotted_names' が真でインスタンスに @code{_dispatch()} メソッドがない場合、リクエストされたメソッド名がピリオドを含むなら、メソッド名の各要素が個々に検索され、簡単な階層的検索が行われます。
その検索で発見された値をリクエストの引数で呼び出し、クライアントに返り値を返します。

@cartouche
@quotation 警告 
`allow_dotted_names' オプションを有効にすると、侵入者はあなたのモジュールのグローバル変数にアクセスすることができ、あなたのマシンで任意のコードを実行できる可能性があります。このオプションは閉じた安全なネットワークでのみお使い下さい。
@end quotation
@end cartouche
@end deffn

@geindex register_introspection_functions() (xmlrpc.server.SimpleXMLRPCServer のメソッド)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_introspection_functions}@anchor{41af}
@deffn {メソッド} SimpleXMLRPCServer.register_introspection_functions ()

XML-RPC のイントロスペクション関数、 @code{system.listMethods} 、 @code{system.methodHelp} 、 @code{system.methodSignature} を登録します。
@end deffn

@geindex register_multicall_functions() (xmlrpc.server.SimpleXMLRPCServer のメソッド)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_multicall_functions}@anchor{41b0}
@deffn {メソッド} SimpleXMLRPCServer.register_multicall_functions ()

XML-RPC における複数の要求を処理する関数 system.multicall を登録します。
@end deffn

@geindex rpc_paths (xmlrpc.server.SimpleXMLRPCRequestHandler の属性)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler rpc_paths}@anchor{41b1}
@deffn {の属性} SimpleXMLRPCRequestHandler.rpc_paths

この属性値はXML-RPCリクエストを受け付けるURLの有効なパス部分をリストするタプルでなければなりません。これ以外のパスへのリクエストは404「そのようなページはありません」 HTTPエラーになります。このタプルが空の場合は全てのパスが有効であると見なされます。デフォルト値は @code{('/', '/RPC2')} です。
@end deffn

@menu
* SimpleXMLRPCServer の例:: 

@end menu

@node SimpleXMLRPCServer の例,,,SimpleXMLRPCServer オブジェクト
@anchor{library/xmlrpc server id1}@anchor{41b2}@anchor{library/xmlrpc server simplexmlrpcserver-example}@anchor{41a5}
@subsubsection SimpleXMLRPCServer の例


サーバーのコード:

@example
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)

    # Register a function under a different name
    def adder_function(x, y):
        return x + y
    server.register_function(adder_function, 'add')

    # Register an instance; all the methods of the instance are
    # published as XML-RPC methods (in this case, just 'mul').
    class MyFuncs:
        def mul(self, x, y):
            return x * y

    server.register_instance(MyFuncs())

    # Run the server's main loop
    server.serve_forever()
@end example

以下のクライアントコードは上のサーバーで使えるようになったメソッドを呼び出します:

@example
import xmlrpc.client

s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3))  # Returns 2**3 = 8
print(s.add(2,3))  # Returns 5
print(s.mul(5,2))  # Returns 5*2 = 10

# Print list of available methods
print(s.system.listMethods())
@end example

@code{register_function()} はデコレーターとしても使用できます。前のサーバーの例は、デコレーターの方法で関数を登録することもできます。

@example
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)

    # Register a function under a different name, using
    # register_function as a decorator. *name* can only be given
    # as a keyword argument.
    @@server.register_function(name='add')
    def adder_function(x, y):
        return x + y

    # Register a function under function.__name__.
    @@server.register_function
    def mul(x, y):
        return x * y

    server.serve_forever()
@end example

@code{Lib/xmlrpc/server.py} モジュール内にある以下の例はドット付名前を許容し複数呼び出し関数を登録するサーバです。

@cartouche
@quotation 警告 
Enabling the `allow_dotted_names' option allows intruders to access your
module's global variables and may allow intruders to execute arbitrary code on
your machine.  Only use this example within a secure, closed network.
@end quotation
@end cartouche

@example
import datetime

class ExampleService:
    def getData(self):
        return '42'

    class currentTime:
        @@staticmethod
        def getCurrentTime():
            return datetime.datetime.now()

with SimpleXMLRPCServer(("localhost", 8000)) as server:
    server.register_function(pow)
    server.register_function(lambda x,y: x+y, 'add')
    server.register_instance(ExampleService(), allow_dotted_names=True)
    server.register_multicall_functions()
    print('Serving XML-RPC on localhost port 8000')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nKeyboard interrupt received, exiting.")
        sys.exit(0)
@end example

この ExampleService デモはコマンドラインから起動することができます。

@example
python -m xmlrpc.server
@end example

上記のサーバとやりとりするクライアントは @code{Lib/xmlrpc/client.py} にあります:

@example
server = ServerProxy("http://localhost:8000")

try:
    print(server.currentTime.getCurrentTime())
except Error as v:
    print("ERROR", v)

multi = MultiCall(server)
multi.getData()
multi.pow(2,9)
multi.add(1,2)
try:
    for response in multi():
        print(response)
except Error as v:
    print("ERROR", v)
@end example

デモ XMLRPC サーバとやりとりするクライアントは以下のように呼び出します:

@example
python -m xmlrpc.client
@end example

@node CGIXMLRPCRequestHandler,XMLRPC サーバの文書化,SimpleXMLRPCServer オブジェクト,xmlrpc server --- 基本的な XML-RPC サーバー
@anchor{library/xmlrpc server cgixmlrpcrequesthandler}@anchor{41b3}
@subsubsection CGIXMLRPCRequestHandler


@ref{41aa,,CGIXMLRPCRequestHandler} クラスは、Python の CGI スクリプトに送られた XML-RPC リクエストを処理するときに使用できます。

@geindex register_function() (xmlrpc.server.CGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_function}@anchor{41b4}
@deffn {メソッド} CGIXMLRPCRequestHandler.register_function (function=None, name=None)

XML-RPC リクエストに応答可能な関数を登録します。引数 `name' が与えられた場合は、それが関数 `function' に関連付けられたメソッド名となります。そうでない場合は、 @ref{14ec,,function.__name__} の値が用いられます。引数 `name' は文字列で、例えばピリオド "." のようなPythonで識別子として正しくない文字を含んでいても構いません。

このメソッドはデコレーターとしても使用することができます。デコレーターとして使用するときは、 `name' は関数を `name' で登録するキーワード引数としてのみ渡すことができます。 `name' が与えられていないときは、 @ref{14ec,,function.__name__} が使用されます。


バージョン 3.7 で変更: @ref{41b4,,register_function()} はデコレーターとして使用できます。

@end deffn

@geindex register_instance() (xmlrpc.server.CGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_instance}@anchor{41b5}
@deffn {メソッド} CGIXMLRPCRequestHandler.register_instance (instance)

オブジェクトを登録します。
オブジェクトは @ref{41b4,,register_function()} を使用して登録されていないメソッド名を公開するのに使われます。
`instance' に @code{_dispatch()} メソッドがあった場合、リクエストされたメソッド名と引数で @code{_dispatch()} を呼び出します。
返り値は結果としてクライアントに返されます。
`instance' に @code{_dispatch()} メソッドがなかった場合、リクエストされたメソッド名にマッチする属性を検索します。
リクエストされたメソッド名がピリオドを含む場合、モジュール名の各要素が個々に検索され、簡単な階層的検索が実行されます。
その検索で発見された値をリクエストの引数で呼び出し、クライアントに返り値を返します。
@end deffn

@geindex register_introspection_functions() (xmlrpc.server.CGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_introspection_functions}@anchor{41b6}
@deffn {メソッド} CGIXMLRPCRequestHandler.register_introspection_functions ()

XML-RPC のイントロスペクション関数、 @code{system.listMethods} 、 @code{system.methodHelp} 、 @code{system.methodSignature} を登録します。
@end deffn

@geindex register_multicall_functions() (xmlrpc.server.CGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_multicall_functions}@anchor{41b7}
@deffn {メソッド} CGIXMLRPCRequestHandler.register_multicall_functions ()

XML-RPC マルチコール関数 @code{system.multicall} を登録します。
@end deffn

@geindex handle_request() (xmlrpc.server.CGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler handle_request}@anchor{41b8}
@deffn {メソッド} CGIXMLRPCRequestHandler.handle_request (request_text=None)

XML-RPC リクエストを処理します。 与えられた場合、 `request_text' はHTTP サーバが提供する POST データでなければなりません。
そうでない場合、標準入力の内容が使われます。
@end deffn

以下はプログラム例です:

@example
class MyFuncs:
    def mul(self, x, y):
        return x * y


handler = CGIXMLRPCRequestHandler()
handler.register_function(pow)
handler.register_function(lambda x,y: x+y, 'add')
handler.register_introspection_functions()
handler.register_instance(MyFuncs())
handler.handle_request()
@end example

@node XMLRPC サーバの文書化,DocXMLRPCServer オブジェクト,CGIXMLRPCRequestHandler,xmlrpc server --- 基本的な XML-RPC サーバー
@anchor{library/xmlrpc server documenting-xmlrpc-server}@anchor{41b9}
@subsubsection XMLRPC サーバの文書化


これらのクラスは HTTP GET 要求への応答内で HTML 文書となるよう上記クラスを拡張します。
サーバは独立していても CGI 環境に埋め込まれていてもかまいません。
前者では @ref{1da6,,DocXMLRPCServer} を、後者では @ref{41ba,,DocCGIXMLRPCRequestHandler} を使用します。

@geindex DocXMLRPCServer (xmlrpc.server のクラス)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer}@anchor{1da6}
@deffn {クラス} xmlrpc.server.DocXMLRPCServer (addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=True)

サーバ・インスタンスを新たに生成します。全ての引数の意味は @ref{41a9,,SimpleXMLRPCServer} のものと同じですが、 `requestHandler' のデフォルトは @ref{41bb,,DocXMLRPCRequestHandler} になっています。


バージョン 3.3 で変更: `use_builtin_types' フラグが追加されました。

@end deffn

@geindex DocCGIXMLRPCRequestHandler (xmlrpc.server のクラス)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler}@anchor{41ba}
@deffn {クラス} xmlrpc.server.DocCGIXMLRPCRequestHandler

CGI環境で XMR-RPC リクエストを処理するインスタンスを新たに生成します。
@end deffn

@geindex DocXMLRPCRequestHandler (xmlrpc.server のクラス)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCRequestHandler}@anchor{41bb}
@deffn {クラス} xmlrpc.server.DocXMLRPCRequestHandler

リクエスト・ハンドラのインスタンスを新たに生成します。このリクエスト・ハンドラは XML-RPC POST 要求とドキュメントの GET 要求をサポートし、 @ref{1da6,,DocXMLRPCServer} コンストラクタに与えられた引数 `logRequests' を優先するためにロギングを変更します。
@end deffn

@node DocXMLRPCServer オブジェクト,DocCGIXMLRPCRequestHandler,XMLRPC サーバの文書化,xmlrpc server --- 基本的な XML-RPC サーバー
@anchor{library/xmlrpc server doc-xmlrpc-servers}@anchor{41bc}@anchor{library/xmlrpc server docxmlrpcserver-objects}@anchor{41bd}
@subsubsection DocXMLRPCServer オブジェクト


@ref{1da6,,DocXMLRPCServer} は @ref{41a9,,SimpleXMLRPCServer} の派生クラスで、自己文書化するスタンドアローン XML-RPC サーバの作成手段を提供します。
HTTP POST リクエストは XML-RPC メソッドの呼び出しとして処理されます。
HTTP GET リクエストは pydoc スタイルの HTML 文書の生成に処理されます。
これによりサーバは自身の web ベースの文書を提供できます。

@geindex set_server_title() (xmlrpc.server.DocXMLRPCServer のメソッド)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_title}@anchor{41be}
@deffn {メソッド} DocXMLRPCServer.set_server_title (server_title)

生成する HTML 文書で使用されるタイトルを設定します。このタイトルは HTML の title 要素内で使われます。
@end deffn

@geindex set_server_name() (xmlrpc.server.DocXMLRPCServer のメソッド)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_name}@anchor{41bf}
@deffn {メソッド} DocXMLRPCServer.set_server_name (server_name)

生成する HTML 文書内で使用される名前を設定します。この名前は生成した文書冒頭の h1 要素内で使われます。
@end deffn

@geindex set_server_documentation() (xmlrpc.server.DocXMLRPCServer のメソッド)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_documentation}@anchor{41c0}
@deffn {メソッド} DocXMLRPCServer.set_server_documentation (server_documentation)

生成する HTML 文書内で使用される説明を設定します。この説明は文書中のサーバ名の下にパラグラフとして出力されます。
@end deffn

@node DocCGIXMLRPCRequestHandler,,DocXMLRPCServer オブジェクト,xmlrpc server --- 基本的な XML-RPC サーバー
@anchor{library/xmlrpc server doccgixmlrpcrequesthandler}@anchor{41c1}
@subsubsection DocCGIXMLRPCRequestHandler


@ref{41ba,,DocCGIXMLRPCRequestHandler} は @ref{41aa,,CGIXMLRPCRequestHandler} の派生クラスで、自己文書化する XML-RPC CGI スクリプトの作成手段を提供します。
HTTP POST リクエストは XML-RCP メソッドの呼び出しとして処理されます。
HTTP GET リクエストは pydoc スタイルの HTML 文書の生成に処理されます。
これによりサーバは自身の web ベースの文書を提供できます。

@geindex set_server_title() (xmlrpc.server.DocCGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_title}@anchor{41c2}
@deffn {メソッド} DocCGIXMLRPCRequestHandler.set_server_title (server_title)

生成する HTML 文書で使用されるタイトルを設定します。このタイトルは HTML の title 要素内で使われます。
@end deffn

@geindex set_server_name() (xmlrpc.server.DocCGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_name}@anchor{41c3}
@deffn {メソッド} DocCGIXMLRPCRequestHandler.set_server_name (server_name)

生成する HTML 文書内で使用される名前を設定します。この名前は生成した文書冒頭の h1 要素内で使われます。
@end deffn

@geindex set_server_documentation() (xmlrpc.server.DocCGIXMLRPCRequestHandler のメソッド)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_documentation}@anchor{41c4}
@deffn {メソッド} DocCGIXMLRPCRequestHandler.set_server_documentation (server_documentation)

生成する HTML 文書内で使用される説明を設定します。この説明は文書中のサーバ名の下にパラグラフとして出力されます。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ipaddress --- IPv4/IPv6 操作ライブラリ,,xmlrpc server --- 基本的な XML-RPC サーバー,インターネットプロトコルとサポート
@anchor{library/ipaddress doc}@anchor{41c5}@anchor{library/ipaddress ipaddress-ipv4-ipv6-manipulation-library}@anchor{41c6}@anchor{library/ipaddress module-ipaddress}@anchor{84}@anchor{library/ipaddress translation-repo}@anchor{41c7}
@subsection @code{ipaddress} --- IPv4/IPv6 操作ライブラリ


@geindex module; ipaddress

`ソースコード:' Lib/ipaddress.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/ipaddress.py}


__________________________________________________________________


@code{ipaddress} provides the capabilities to create, manipulate and
operate on IPv4 and IPv6 addresses and networks.

このモジュールの関数やクラスを使うと、IPアドレスに関する様々なタスク、例えば2つのホストが同じサブネットに属しているかどうかをチェックしたり、特定のサブネット内の全てのホストをイテレートしたり、文字列が正しい IP アドレスかネットワークを定義しているかどうかをチェックするなどを簡単に実現することができます。

これはモジュールの完全な API リファレンスです。概要や紹介は @ref{41c8,,ipaddressモジュールの紹介} を参照してください。


Added in version 3.3.


@c import ipaddress
@c from ipaddress import (
@c     ip_network, IPv4Address, IPv4Interface, IPv4Network,
@c )

@menu
* 便利なファクトリ関数:: 
* IP アドレス:: 
* IP ネットワーク定義:: 
* インターフェイスオブジェクト:: 
* その他のモジュールレベル関数:: 
* Custom Exceptions:: 

@end menu

@node 便利なファクトリ関数,IP アドレス,,ipaddress --- IPv4/IPv6 操作ライブラリ
@anchor{library/ipaddress convenience-factory-functions}@anchor{41c9}
@subsubsection 便利なファクトリ関数


The @code{ipaddress} module provides factory functions to conveniently create
IP addresses, networks and interfaces:

@geindex ip_address() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress ip_address}@anchor{41ca}
@deffn {の関数} ipaddress.ip_address (address)

引数に渡された IP address に応じて、 @ref{50c,,IPv4Address} か @ref{50d,,IPv6Address} のオブジェクトを返します。 IPv4 か IPv6 のアドレスを受け取ります; @code{2**32} より小さい整数はデフォルトでは IPv4 アドレスだと判断されます。 `address' が正しい IPv4, IPv6 アドレスを表現していない場合は @ref{2ec,,ValueError} を発生させます。

@example
>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')
@end example
@end deffn

@geindex ip_network() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress ip_network}@anchor{41cb}
@deffn {の関数} ipaddress.ip_network (address, strict=True)

引数に渡された IP address に応じて、 @ref{50e,,IPv4Network} か @ref{50f,,IPv6Network} のオブジェクトを返します。 `address' は IP ネットワークを示す文字列あるいは整数です。 IPv4 か IPv6 のネットワークを受け取ります; @code{2**32} より小さい整数はデフォルトでは IPv4 アドレスだと判断されます。 `strict' は @ref{50e,,IPv4Network} か @ref{50f,,IPv6Network} のコンストラクタに渡されます。 `address' が正しい IPv4, IPv6 アドレスを表現していない場合や、ネットワークの host bit がセットされていた場合は @ref{2ec,,ValueError} を発生させます。

@example
>>> ipaddress.ip_network('192.168.0.0/28')
IPv4Network('192.168.0.0/28')
@end example
@end deffn

@geindex ip_interface() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress ip_interface}@anchor{41cc}
@deffn {の関数} ipaddress.ip_interface (address)

引数に渡された IP address に応じて、 @ref{1b99,,IPv4Interface} か @ref{1b9a,,IPv6Interface} のオブジェクトを返します。 `address' は IP ネットワークを示す文字列あるいは整数です。 IPv4 か IPv6 のネットワークを受け取ります; @code{2**32} より小さい整数はデフォルトでは IPv4 アドレスだと判断されます。 `address' が正しい IPv4, IPv6 アドレスを表現していない場合は @ref{2ec,,ValueError} を発生させます。
@end deffn

これらの便利関数を利用するデメリットとして、IPv4 と IPv6 両方のフォーマットを扱う必要性があるために、どちらを期待されていたのかを知ることができず、エラーメッセージが最小限の情報しか提供できないことです。利用したいバージョンの特定のコンストラクタを直接呼ぶことで、より詳細なエラーレポートを得ることができます。

@node IP アドレス,IP ネットワーク定義,便利なファクトリ関数,ipaddress --- IPv4/IPv6 操作ライブラリ
@anchor{library/ipaddress ip-addresses}@anchor{41cd}
@subsubsection IP アドレス


@menu
* Address オブジェクト:: 
* 文字列と整数への変換:: 
* 演算子: 演算子<2>. 

@end menu

@node Address オブジェクト,文字列と整数への変換,,IP アドレス
@anchor{library/ipaddress address-objects}@anchor{41ce}
@subsubsection Address オブジェクト


@ref{50c,,IPv4Address} と @ref{50d,,IPv6Address} オブジェクトは多くの共通した属性を持っています。両方の IP バージョンを扱うコードを書きやすくするために、IPv6 アドレスでしか意味が無いいくつかの属性も @ref{50c,,IPv4Address} オブジェクトに実装されています。アドレスオブジェクトは @ref{824,,hashable} なので、辞書のキーとして利用できます。

@geindex IPv4Address (ipaddress のクラス)
@anchor{library/ipaddress ipaddress IPv4Address}@anchor{50c}
@deffn {クラス} ipaddress.IPv4Address (address)

IPv4 アドレスを構築する。 `address' が正しい IPv4 アドレスでない場合、 @ref{41cf,,AddressValueError} を発生させます。

以下のものが正しい IPv4 アドレスを構築します:


@enumerate 

@item 
A string in decimal-dot notation, consisting of four decimal integers in
the inclusive range 0--255, separated by dots (e.g. @code{192.168.0.1}). Each
integer represents an octet (byte) in the address. Leading zeroes are
not tolerated to prevent confusion with octal notation.

@item 
32bit に収まる整数。

@item 
大きさ4の @ref{192,,bytes} オブジェクトに (最上位オクテットが最初になるように) パックされた整数。
@end enumerate

@example
>>> ipaddress.IPv4Address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(3232235521)
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(b'\xC0\xA8\x00\x01')
IPv4Address('192.168.0.1')
@end example


バージョン 3.8 で変更: Leading zeros are tolerated, even in ambiguous cases that look like
octal notation.



バージョン 3.9.5 で変更: Leading zeros are no longer tolerated and are treated as an error.
IPv4 address strings are now parsed as strict as glibc
@ref{b5b,,inet_pton()}.


@geindex version (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address version}@anchor{41d0}
@deffn {の属性} version

適切なバージョン番号: IPv4 なら @code{4}, IPv6 なら @code{6}.


バージョン 3.14 で変更: Made available on the class.

@end deffn

@geindex max_prefixlen (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address max_prefixlen}@anchor{41d1}
@deffn {の属性} max_prefixlen

このバージョンのアドレスを表現するのに必要なビット数: IPv4 なら @code{32}, IPv6 なら @code{128}.

prefix は、アドレスがネットワークに含まれるかどうかを決定するために比較する、アドレスの先頭ビット数を定義します。


バージョン 3.14 で変更: Made available on the class.

@end deffn

@geindex compressed (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address compressed}@anchor{41d2}
@deffn {の属性} compressed
@end deffn

@geindex exploded (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address exploded}@anchor{41d3}
@deffn {の属性} exploded

ドットと10進数を使った表現の文字列。この表現には先頭の 0 は含まれません。

IPv4 はアドレスの 0 オクテットを省略する記法を定義していないので、IPv4 アドレスにおいてこれらの2つの属性は常に @code{str(addr)} と等しくなります。これらの属性を用意することで、IPv4 と IPv6 アドレス両方を扱う、表示用コードが書きやすくなります。
@end deffn

@geindex packed (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address packed}@anchor{41d4}
@deffn {の属性} packed

このアドレスのバイナリ表現 - 適切な長さをもった @ref{192,,bytes} オブジェクト(最上位オクテットが先頭)。 IPv4 では 4 byte で、 IPv6 では 16 byte。
@end deffn

@geindex reverse_pointer (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address reverse_pointer}@anchor{1020}
@deffn {の属性} reverse_pointer

The name of the reverse DNS PTR record for the IP address, e.g.:

@example
>>> ipaddress.ip_address("127.0.0.1").reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> ipaddress.ip_address("2001:db8::1").reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
@end example

This is the name that could be used for performing a PTR lookup, not the
resolved hostname itself.


Added in version 3.5.

@end deffn

@geindex is_multicast (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address is_multicast}@anchor{41d5}
@deffn {の属性} is_multicast

アドレスがマルチキャスト用に予約されている場合は @code{True} 。 
@geindex RFC; RFC 3171
RFC 3171@footnote{https://datatracker.ietf.org/doc/html/rfc3171.html} (IPv4) か 
@geindex RFC; RFC 2373
RFC 2373@footnote{https://datatracker.ietf.org/doc/html/rfc2373.html} (IPv6) を参照。
@end deffn

@geindex is_private (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address is_private}@anchor{19c3}
@deffn {の属性} is_private

@code{True} if the address is defined as not globally reachable by
iana-ipv4-special-registry@footnote{https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml} (for IPv4) or iana-ipv6-special-registry@footnote{https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml}
(for IPv6) with the following exceptions:


@itemize *

@item 
@code{is_private} is @code{False} for the shared address space (@code{100.64.0.0/10})

@item 
For IPv4-mapped IPv6-addresses the @code{is_private} value is determined by the
semantics of the underlying IPv4 addresses and the following condition holds
(see @ref{41d6,,IPv6Address.ipv4_mapped}):

@example
address.is_private == address.ipv4_mapped.is_private
@end example
@end itemize

@code{is_private} has value opposite to @ref{1161,,is_global}, except for the shared address space
(@code{100.64.0.0/10} range) where they are both @code{False}.


バージョン 3.13 で変更: Fixed some false positives and false negatives.


@itemize *

@item 
@code{192.0.0.0/24} is considered private with the exception of @code{192.0.0.9/32} and
@code{192.0.0.10/32} (previously: only the @code{192.0.0.0/29} sub-range was considered private).

@item 
@code{64:ff9b:1::/48} is considered private.

@item 
@code{2002::/16} is considered private.

@item 
There are exceptions within @code{2001::/23} (otherwise considered private): @code{2001:1::1/128},
@code{2001:1::2/128}, @code{2001:3::/32}, @code{2001:4:112::/48}, @code{2001:20::/28}, @code{2001:30::/28}.
The exceptions are not considered private.
@end itemize

@end deffn

@geindex is_global (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address is_global}@anchor{1161}
@deffn {の属性} is_global

@code{True} if the address is defined as globally reachable by
iana-ipv4-special-registry@footnote{https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml} (for IPv4) or iana-ipv6-special-registry@footnote{https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml}
(for IPv6) with the following exception:

For IPv4-mapped IPv6-addresses the @code{is_private} value is determined by the
semantics of the underlying IPv4 addresses and the following condition holds
(see @ref{41d6,,IPv6Address.ipv4_mapped}):

@example
address.is_global == address.ipv4_mapped.is_global
@end example

@code{is_global} has value opposite to @ref{19c3,,is_private}, except for the shared address space
(@code{100.64.0.0/10} range) where they are both @code{False}.


Added in version 3.4.



バージョン 3.13 で変更: Fixed some false positives and false negatives, see @ref{19c3,,is_private} for details.

@end deffn

@geindex is_unspecified (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address is_unspecified}@anchor{41d7}
@deffn {の属性} is_unspecified

アドレスが未定義の時に @code{True}. 
@geindex RFC; RFC 5735
RFC 5735@footnote{https://datatracker.ietf.org/doc/html/rfc5735.html} (IPv4) か 
@geindex RFC; RFC 2373
RFC 2373@footnote{https://datatracker.ietf.org/doc/html/rfc2373.html} (IPv6) を参照。
@end deffn

@geindex is_reserved (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address is_reserved}@anchor{41d8}
@deffn {の属性} is_reserved

@code{True} if the address is noted as reserved by the IETF.
For IPv4, this is only @code{240.0.0.0/4}, the @code{Reserved} address block.
For IPv6, this is all addresses allocated@footnote{https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml} as
@code{Reserved by IETF} for future use.

@cartouche
@quotation 注釈 
For IPv4, @code{is_reserved} is not related to the address block value of the
@code{Reserved-by-Protocol} column in iana-ipv4-special-registry@footnote{https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml}.
@end quotation
@end cartouche

@cartouche
@quotation 注意 
For IPv6, @code{fec0::/10} a former Site-Local scoped address prefix is
currently excluded from that list (see @ref{41d9,,is_site_local} & 
@geindex RFC; RFC 3879
RFC 3879@footnote{https://datatracker.ietf.org/doc/html/rfc3879.html}).
@end quotation
@end cartouche
@end deffn

@geindex is_loopback (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address is_loopback}@anchor{41da}
@deffn {の属性} is_loopback

ループバックアドレスである場合に @code{True}. 
@geindex RFC; RFC 3330
RFC 3330@footnote{https://datatracker.ietf.org/doc/html/rfc3330.html} (IPv4) か 
@geindex RFC; RFC 2373
RFC 2373@footnote{https://datatracker.ietf.org/doc/html/rfc2373.html} (IPv6) を参照。
@end deffn

@geindex is_link_local (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address is_link_local}@anchor{41db}
@deffn {の属性} is_link_local

アドレスがリンクローカル用に予約されいている場合に @code{True}. 
@geindex RFC; RFC 3927
RFC 3927@footnote{https://datatracker.ietf.org/doc/html/rfc3927.html} を参照。
@end deffn

@geindex ipv6_mapped (ipaddress.IPv4Address の属性)
@anchor{library/ipaddress ipaddress IPv4Address ipv6_mapped}@anchor{50b}
@deffn {の属性} ipv6_mapped

@ref{50c,,IPv4Address} object representing the IPv4-mapped IPv6 address. See 
@geindex RFC; RFC 4291
RFC 4291@footnote{https://datatracker.ietf.org/doc/html/rfc4291.html}.


Added in version 3.13.

@end deffn
@end deffn

@geindex __format__() (ipaddress.IPv4Address のメソッド)
@anchor{library/ipaddress ipaddress IPv4Address __format__}@anchor{41dc}
@deffn {メソッド} IPv4Address.__format__ (fmt)

Returns a string representation of the IP address, controlled by
an explicit format string.
`fmt' can be one of the following: @code{'s'}, the default option,
equivalent to @ref{169,,str()}, @code{'b'} for a zero-padded binary string,
@code{'X'} or @code{'x'} for an uppercase or lowercase hexadecimal
representation, or @code{'n'}, which is equivalent to @code{'b'} for IPv4
addresses and @code{'x'} for IPv6. For binary and hexadecimal
representations, the form specifier @code{'#'} and the grouping option
@code{'_'} are available. @code{__format__} is used by @code{format}, @code{str.format}
and f-strings.

@example
>>> format(ipaddress.IPv4Address('192.168.0.1'))
'192.168.0.1'
>>> '@{:#b@}'.format(ipaddress.IPv4Address('192.168.0.1'))
'0b11000000101010000000000000000001'
>>> f'@{ipaddress.IPv6Address("2001:db8::1000"):s@}'
'2001:db8::1000'
>>> format(ipaddress.IPv6Address('2001:db8::1000'), '_X')
'2001_0DB8_0000_0000_0000_0000_0000_1000'
>>> '@{:#_n@}'.format(ipaddress.IPv6Address('2001:db8::1000'))
'0x2001_0db8_0000_0000_0000_0000_0000_1000'
@end example


Added in version 3.9.

@end deffn

@geindex IPv6Address (ipaddress のクラス)
@anchor{library/ipaddress ipaddress IPv6Address}@anchor{50d}
@deffn {クラス} ipaddress.IPv6Address (address)

IPv6 アドレスを構築する。 `address' が正しい IPv6 アドレスでない場合、 @ref{41cf,,AddressValueError} を発生させます。

以下のものが正しい IPv6 アドレスを構築します:


@enumerate 

@item 
4桁の16進数からなるグループ8個で構成された文字列。各グループは16bitを表現している。グループはコロンで区切られる。これは `exploded' (長い) 記法を表す。文字列は `compressed' (省略) 記法でも良い。詳細は 
@geindex RFC; RFC 4291
RFC 4291@footnote{https://datatracker.ietf.org/doc/html/rfc4291.html} を参照。例えば、 @code{"0000:0000:0000:0000:0000:0abc:0007:0def"} は @code{"::abc:7:def"} と省略できる。

Optionally, the string may also have a scope zone ID, expressed
with a suffix @code{%scope_id}. If present, the scope ID must be non-empty,
and may not contain @code{%}.
See 
@geindex RFC; RFC 4007
RFC 4007@footnote{https://datatracker.ietf.org/doc/html/rfc4007.html} for details.
For example, @code{fe80::1234%1} might identify address @code{fe80::1234} on the first link of the node.

@item 
128bit に収まる整数。

@item 
ビッグエンディアンで 16 バイトの長さの @ref{192,,bytes} オブジェクトにパックされた整数。
@end enumerate

@example
>>> ipaddress.IPv6Address('2001:db8::1000')
IPv6Address('2001:db8::1000')
>>> ipaddress.IPv6Address('ff02::5678%1')
IPv6Address('ff02::5678%1')
@end example

@geindex compressed (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address compressed}@anchor{41dd}
@deffn {の属性} compressed
@end deffn

アドレス表現の短い形式で、グループ内の先頭の 0 を省略し、連続する完全に0のグループの一番長いシーケンスを1つの空グループに折りたたんだもの。

これは IPv6 アドレスに対して @code{str(addr)} が返す値と同じです。

@geindex exploded (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address exploded}@anchor{41de}
@deffn {の属性} exploded
@end deffn

アドレス表現の長い形式。全てのグループの先頭の0は省略されず、完全に0のグループも省略されない。

以降の属性とメソッドについては、@ref{50c,,IPv4Address} クラスの対応するドキュメントを参照してください:

@geindex packed (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address packed}@anchor{41df}
@deffn {の属性} packed
@end deffn

@geindex reverse_pointer (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address reverse_pointer}@anchor{193a}
@deffn {の属性} reverse_pointer
@end deffn

@geindex version (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address version}@anchor{41e0}
@deffn {の属性} version
@end deffn

@geindex max_prefixlen (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address max_prefixlen}@anchor{41e1}
@deffn {の属性} max_prefixlen
@end deffn

@geindex is_multicast (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_multicast}@anchor{41e2}
@deffn {の属性} is_multicast
@end deffn

@geindex is_private (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_private}@anchor{19c4}
@deffn {の属性} is_private
@end deffn

@geindex is_global (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_global}@anchor{19c5}
@deffn {の属性} is_global


Added in version 3.4.

@end deffn

@geindex is_unspecified (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_unspecified}@anchor{41e3}
@deffn {の属性} is_unspecified
@end deffn

@geindex is_reserved (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_reserved}@anchor{41e4}
@deffn {の属性} is_reserved
@end deffn

@geindex is_loopback (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_loopback}@anchor{19aa}
@deffn {の属性} is_loopback
@end deffn

@geindex is_link_local (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_link_local}@anchor{41e5}
@deffn {の属性} is_link_local
@end deffn

@geindex is_site_local (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address is_site_local}@anchor{41d9}
@deffn {の属性} is_site_local

アドレスがサイトローカルな目的のために予約されいている場合に @code{True}. サイトローカルアドレスは 
@geindex RFC; RFC 3879
RFC 3879@footnote{https://datatracker.ietf.org/doc/html/rfc3879.html} によって廃止されている事に注意してください。アドレスが 
@geindex RFC; RFC 4193
RFC 4193@footnote{https://datatracker.ietf.org/doc/html/rfc4193.html} で定義されているユニークローカルアドレスの範囲に含まれているかどうかをテストするには、 @ref{19c3,,is_private} を利用してください。
@end deffn

@geindex ipv4_mapped (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address ipv4_mapped}@anchor{41d6}
@deffn {の属性} ipv4_mapped

IPv4 にマップされた(@code{::FFFF/96} で始まる)アドレスの場合、このプロパティは埋め込まれた IPv4 Address を返します。それ以外のアドレスに対しては、このプロパティは @code{None} になります。
@end deffn

@geindex scope_id (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address scope_id}@anchor{b0a}
@deffn {の属性} scope_id

For scoped addresses as defined by 
@geindex RFC; RFC 4007
RFC 4007@footnote{https://datatracker.ietf.org/doc/html/rfc4007.html}, this property identifies
the particular zone of the address's scope that the address belongs to,
as a string. When no scope zone is specified, this property will be @code{None}.
@end deffn

@geindex sixtofour (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address sixtofour}@anchor{41e6}
@deffn {の属性} sixtofour

@geindex RFC; RFC 3056
RFC 3056@footnote{https://datatracker.ietf.org/doc/html/rfc3056.html} で定義された 6to4 (@code{2002::/16} で始まる)アドレスの場合、このプロパティは埋め込まれた IPv4 Address を返します。それ以外のアドレスに対しては、このプロパティは @code{None} になります。
@end deffn

@geindex teredo (ipaddress.IPv6Address の属性)
@anchor{library/ipaddress ipaddress IPv6Address teredo}@anchor{41e7}
@deffn {の属性} teredo

@geindex RFC; RFC 4380
RFC 4380@footnote{https://datatracker.ietf.org/doc/html/rfc4380.html} で定義された Teredo (@code{2001::/32} で始まる)アドレスの場合、このプロパティは埋め込まれた @code{(server, client)} IP アドレスペアを返します。それ以外のアドレスに対しては、このプロパティは @code{None} になります。
@end deffn
@end deffn

@geindex __format__() (ipaddress.IPv6Address のメソッド)
@anchor{library/ipaddress ipaddress IPv6Address __format__}@anchor{41e8}
@deffn {メソッド} IPv6Address.__format__ (fmt)

@ref{50c,,IPv4Address} の対応するメソッドのドキュメントを参照してください。


Added in version 3.9.

@end deffn

@node 文字列と整数への変換,演算子<2>,Address オブジェクト,IP アドレス
@anchor{library/ipaddress conversion-to-strings-and-integers}@anchor{41e9}
@subsubsection 文字列と整数への変換


socket モジュールなどのネットワークインターフェースを利用するには、アドレスを文字列や整数に変換しなければなりません。これには組み込みの @ref{169,,str()} と @ref{19b,,int()} 関数を利用します:

@example
>>> str(ipaddress.IPv4Address('192.168.0.1'))
'192.168.0.1'
>>> int(ipaddress.IPv4Address('192.168.0.1'))
3232235521
>>> str(ipaddress.IPv6Address('::1'))
'::1'
>>> int(ipaddress.IPv6Address('::1'))
1
@end example

Note that IPv6 scoped addresses are converted to integers without scope zone ID.

@node 演算子<2>,,文字列と整数への変換,IP アドレス
@anchor{library/ipaddress operators}@anchor{41ea}
@subsubsection 演算子


Address オブジェクトはいくつかの演算子をサポートします。明記されない限り、演算子は互換性のあるオブジェクト間 (つまり IPv4 同士や IPv6 同士) でのみ利用できます。

@menu
* 比較演算子:: 
* 算術演算:: 

@end menu

@node 比較演算子,算術演算,,演算子<2>
@anchor{library/ipaddress comparison-operators}@anchor{41eb}
@subsubsection 比較演算子


Address objects can be compared with the usual set of comparison operators.
Same IPv6 addresses with different scope zone IDs are not equal.
Some examples:

@example
>>> IPv4Address('127.0.0.2') > IPv4Address('127.0.0.1')
True
>>> IPv4Address('127.0.0.2') == IPv4Address('127.0.0.1')
False
>>> IPv4Address('127.0.0.2') != IPv4Address('127.0.0.1')
True
>>> IPv6Address('fe80::1234') == IPv6Address('fe80::1234%1')
False
>>> IPv6Address('fe80::1234%1') != IPv6Address('fe80::1234%2')
True
@end example

@node 算術演算,,比較演算子,演算子<2>
@anchor{library/ipaddress arithmetic-operators}@anchor{41ec}
@subsubsection 算術演算


アドレスオブジェクトから整数を加減算できます。いくつかの例:

@example
>>> IPv4Address('127.0.0.2') + 3
IPv4Address('127.0.0.5')
>>> IPv4Address('127.0.0.2') - 3
IPv4Address('126.255.255.255')
>>> IPv4Address('255.255.255.255') + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ipaddress.AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
@end example

@node IP ネットワーク定義,インターフェイスオブジェクト,IP アドレス,ipaddress --- IPv4/IPv6 操作ライブラリ
@anchor{library/ipaddress ip-network-definitions}@anchor{41ed}
@subsubsection IP ネットワーク定義


@ref{50e,,IPv4Network} と @ref{50f,,IPv6Network} オブジェクトは IP ネットワークの定義とインスペクトのための機構を提供します。ネットワーク定義は `mask' と `ネットワークアドレス' からなり、 `mask' でマスク(bitごとの AND) するとネットワークアドレスと同じになる IP アドレスの範囲を定義します。例えば、 @code{255.255.255.0} という `mask' と @code{192.168.1.0} というネットワークアドレスからなるネットワーク定義は、 @code{192.168.1.0} から @code{192.168.1.255} を含む範囲を表します。

@menu
* プリフィックス@comma{} ネットマスク、ホストマスク: プリフィックス ネットマスク、ホストマスク. 
* Network オブジェクト:: 
* 演算子: 演算子<3>. 

@end menu

@node プリフィックス ネットマスク、ホストマスク,Network オブジェクト,,IP ネットワーク定義
@anchor{library/ipaddress prefix-net-mask-and-host-mask}@anchor{41ee}
@subsubsection プリフィックス, ネットマスク、ホストマスク


IP ネットワークマスクを定義する幾つかの等価な方法があります。`プリフィックス' @code{/<nbits>} は先頭の何bitがネットワークマスクで立っているかを示します。`ネットマスク' は先頭の幾つかのbitが立っている IP アドレスです。プリフィックス @code{/24} はIPv4 ではネットマスク @code{255.255.255.0} と、IPv6 では @code{ffff:ff00::} と同じになります。加えて、`ネットマスク' と論理が逆の `ホストマスク' があり、ときどき (例えば Cisco のアクセスコントロールリスト) ネットワークマスクを表すために利用されます。@code{/24} と等しい IPv4 のホストマスクは @code{0.0.0.255} になります。

@node Network オブジェクト,演算子<3>,プリフィックス ネットマスク、ホストマスク,IP ネットワーク定義
@anchor{library/ipaddress network-objects}@anchor{41ef}
@subsubsection Network オブジェクト


address オブジェクトで実装されていた属性は全て network オブジェクトにも実装されています。 network はそれに追加で幾つかの属性を実装しています。
全ての追加属性は @ref{50e,,IPv4Network} と @ref{50f,,IPv6Network} で共通なので、重複を避けるために @ref{50e,,IPv4Network} にだけドキュメントされています。ネットワークオブジェクトは @ref{824,,hashable} なので、辞書のキーとして使用できます。

@geindex IPv4Network (ipaddress のクラス)
@anchor{library/ipaddress ipaddress IPv4Network}@anchor{50e}
@deffn {クラス} ipaddress.IPv4Network (address, strict=True)

IPv4 ネットワーク定義を構築します。`address' は以下の1つです:


@enumerate 

@item 
IPアドレスと、オプションでスラッシュ (@code{/}) で区切られたマスクを持つ文字列。IPアドレスはネットワークアドレスで、マスクは `プリフィックス' を意味する1つの数値か、 IPv4 アドレスの文字列表現です。マスクがIPv4アドレスのとき、非ゼロのフィールドで始まるときは `ネットマスク' として、ゼロのフィールドで始まるときは `ホストマスク' として解釈されます。ただし、すべてのフィールドが0の場合は、`ネットマスク' として扱われます。マスクが省略された場合、 @code{/32} が指定されたものとします。

例えば、次の `address' 指定は全て等しくなります: @code{192.168.1.0/24}, @code{192.168.1.0/255.255.255.0} @code{192.168.1.0/0.0.0.255}.

@item 
32bit に収まる整数。これは1つのアドレスのネットワークと等しく、ネットワークアドレスが `address' に、マスクが @code{/32} になります。

@item 
4byte の @ref{192,,bytes} オブジェクトにビッグエンディアンでパックされた整数。これは整数の `address' と同じように解釈されます。

@item 
A two-tuple of an address description and a netmask, where the address
description is either a string, a 32-bits integer, a 4-bytes packed
integer, or an existing @ref{50c,,IPv4Address} object; and the netmask is either
an integer representing the prefix length (e.g. @code{24}) or a string
representing the prefix mask (e.g. @code{255.255.255.0}).
@end enumerate

`address' が有効な IPv4 アドレスでない場合に @ref{41cf,,AddressValueError} 例外を発生させます。マスクが IPv4 アドレスに対して有効でない場合に @ref{41f0,,NetmaskValueError} 例外を発生させます。

`strict' が @code{True} の場合、与えられたアドレスのホストビットが立っていたら @ref{2ec,,ValueError} を発生させます。そうでない場合、ホストビットをマスクして正しいネットワークアドレスを計算します。

特に明記されない場合、他の network や address を受け取る network のメソッドは、引数の IP バージョンが @code{self} と異なる場合に @ref{198,,TypeError} を発生させます。


バージョン 3.5 で変更: `address' コンストラクタ引数に2要素のタプル形式を追加しました


@geindex version (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network version}@anchor{41f1}
@deffn {の属性} version
@end deffn

@geindex max_prefixlen (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network max_prefixlen}@anchor{41f2}
@deffn {の属性} max_prefixlen

@ref{50c,,IPv4Address} の対応する属性のドキュメントを参照してください。
@end deffn

@geindex is_multicast (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network is_multicast}@anchor{41f3}
@deffn {の属性} is_multicast
@end deffn

@geindex is_private (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network is_private}@anchor{41f4}
@deffn {の属性} is_private
@end deffn

@geindex is_unspecified (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network is_unspecified}@anchor{41f5}
@deffn {の属性} is_unspecified
@end deffn

@geindex is_reserved (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network is_reserved}@anchor{41f6}
@deffn {の属性} is_reserved
@end deffn

@geindex is_loopback (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network is_loopback}@anchor{41f7}
@deffn {の属性} is_loopback
@end deffn

@geindex is_link_local (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network is_link_local}@anchor{41f8}
@deffn {の属性} is_link_local

These attributes are true for the network as a whole if they are true
for both the network address and the broadcast address.
@end deffn

@geindex network_address (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network network_address}@anchor{41f9}
@deffn {の属性} network_address

この network のネットワークアドレス。ネットワークアドレスとプリフィックス長によってユニークにネットワークが定義されます。
@end deffn

@geindex broadcast_address (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network broadcast_address}@anchor{41fa}
@deffn {の属性} broadcast_address

このネットワークのブロードキャストアドレス。ブロードキャストアドレスに投げられたパケットはそのネットワーク内の全てのホストに受信されます。
@end deffn

@geindex hostmask (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network hostmask}@anchor{41fb}
@deffn {の属性} hostmask

@ref{50c,,IPv4Address} オブジェクトとして表現された ホストマスク。
@end deffn

@geindex netmask (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network netmask}@anchor{41fc}
@deffn {の属性} netmask

@ref{50c,,IPv4Address} オブジェクトとして表現された ネットマスク。
@end deffn

@geindex with_prefixlen (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network with_prefixlen}@anchor{41fd}
@deffn {の属性} with_prefixlen
@end deffn

@geindex compressed (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network compressed}@anchor{41fe}
@deffn {の属性} compressed
@end deffn

@geindex exploded (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network exploded}@anchor{41ff}
@deffn {の属性} exploded

A string representation of the network, with the mask in prefix
notation.

@code{with_prefixlen} and @code{compressed} are always the same as
@code{str(network)}.
@code{exploded} uses the exploded form the network address.
@end deffn

@geindex with_netmask (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network with_netmask}@anchor{4200}
@deffn {の属性} with_netmask

A string representation of the network, with the mask in net mask
notation.
@end deffn

@geindex with_hostmask (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network with_hostmask}@anchor{4201}
@deffn {の属性} with_hostmask

A string representation of the network, with the mask in host mask
notation.
@end deffn

@geindex num_addresses (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network num_addresses}@anchor{4202}
@deffn {の属性} num_addresses

ネットワーク内のアドレスの総数
@end deffn

@geindex prefixlen (ipaddress.IPv4Network の属性)
@anchor{library/ipaddress ipaddress IPv4Network prefixlen}@anchor{4203}
@deffn {の属性} prefixlen

ネットワークプレフィックスのビット長。
@end deffn

@geindex hosts() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network hosts}@anchor{17ae}
@deffn {メソッド} hosts ()

Returns an iterator over the usable hosts in the network.  The usable
hosts are all the IP addresses that belong to the network, except the
network address itself and the network broadcast address.  For networks
with a mask length of 31, the network address and network broadcast
address are also included in the result. Networks with a mask of 32
will return a list containing the single host address.

@example
>>> list(ip_network('192.0.2.0/29').hosts())
[IPv4Address('192.0.2.1'), IPv4Address('192.0.2.2'),
 IPv4Address('192.0.2.3'), IPv4Address('192.0.2.4'),
 IPv4Address('192.0.2.5'), IPv4Address('192.0.2.6')]
>>> list(ip_network('192.0.2.0/31').hosts())
[IPv4Address('192.0.2.0'), IPv4Address('192.0.2.1')]
>>> list(ip_network('192.0.2.1/32').hosts())
[IPv4Address('192.0.2.1')]
@end example
@end deffn

@geindex overlaps() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network overlaps}@anchor{4204}
@deffn {メソッド} overlaps (other)

@code{True} if this network is partly or wholly contained in `other' or
`other' is wholly contained in this network.
@end deffn

@geindex address_exclude() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network address_exclude}@anchor{4205}
@deffn {メソッド} address_exclude (network)

Computes the network definitions resulting from removing the given
`network' from this one.  Returns an iterator of network objects.
Raises @ref{2ec,,ValueError} if `network' is not completely contained in
this network.

@example
>>> n1 = ip_network('192.0.2.0/28')
>>> n2 = ip_network('192.0.2.1/32')
>>> list(n1.address_exclude(n2))
[IPv4Network('192.0.2.8/29'), IPv4Network('192.0.2.4/30'),
 IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.0/32')]
@end example
@end deffn

@geindex subnets() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network subnets}@anchor{10a0}
@deffn {メソッド} subnets (prefixlen_diff=1, new_prefix=None)

The subnets that join to make the current network definition, depending
on the argument values.  `prefixlen_diff' is the amount our prefix
length should be increased by.  `new_prefix' is the desired new
prefix of the subnets; it must be larger than our prefix.  One and
only one of `prefixlen_diff' and `new_prefix' must be set.  Returns an
iterator of network objects.

@example
>>> list(ip_network('192.0.2.0/24').subnets())
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
>>> list(ip_network('192.0.2.0/24').subnets(prefixlen_diff=2))
[IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
 IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=26))
[IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
 IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=23))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise ValueError('new prefix must be longer')
ValueError: new prefix must be longer
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=25))
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
@end example
@end deffn

@geindex supernet() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network supernet}@anchor{10a1}
@deffn {メソッド} supernet (prefixlen_diff=1, new_prefix=None)

The supernet containing this network definition, depending on the
argument values.  `prefixlen_diff' is the amount our prefix length
should be decreased by.  `new_prefix' is the desired new prefix of
the supernet; it must be smaller than our prefix.  One and only one
of `prefixlen_diff' and `new_prefix' must be set.  Returns a single
network object.

@example
>>> ip_network('192.0.2.0/24').supernet()
IPv4Network('192.0.2.0/23')
>>> ip_network('192.0.2.0/24').supernet(prefixlen_diff=2)
IPv4Network('192.0.0.0/22')
>>> ip_network('192.0.2.0/24').supernet(new_prefix=20)
IPv4Network('192.0.0.0/20')
@end example
@end deffn

@geindex subnet_of() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network subnet_of}@anchor{4206}
@deffn {メソッド} subnet_of (other)

このネットワークが `other' のサブネットの場合に @code{True} を返します。

@example
>>> a = ip_network('192.168.1.0/24')
>>> b = ip_network('192.168.1.128/30')
>>> b.subnet_of(a)
True
@end example


Added in version 3.7.

@end deffn

@geindex supernet_of() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network supernet_of}@anchor{4207}
@deffn {メソッド} supernet_of (other)

このネットワークが `other' のスーパーネットの場合に @code{True} を返します。

@example
>>> a = ip_network('192.168.1.0/24')
>>> b = ip_network('192.168.1.128/30')
>>> a.supernet_of(b)
True
@end example


Added in version 3.7.

@end deffn

@geindex compare_networks() (ipaddress.IPv4Network のメソッド)
@anchor{library/ipaddress ipaddress IPv4Network compare_networks}@anchor{4208}
@deffn {メソッド} compare_networks (other)

このネットワークを `other' と比較します。比較ではネットワークアドレスのみが考慮され、ホストアドレスは考慮されません。@code{-1}、@code{0}、@code{1} のいずれかを返します。

@example
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.2/32'))
-1
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.0/32'))
1
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.1/32'))
0
@end example


バージョン 3.7 で非推奨: It uses the same ordering and comparison algorithm as "<", "==", and ">"

@end deffn
@end deffn

@geindex IPv6Network (ipaddress のクラス)
@anchor{library/ipaddress ipaddress IPv6Network}@anchor{50f}
@deffn {クラス} ipaddress.IPv6Network (address, strict=True)

IPv6 ネットワーク定義を構築します。`address' は以下の1つです:


@enumerate 

@item 
A string consisting of an IP address and an optional prefix length,
separated by a slash (@code{/}).  The IP address is the network address,
and the prefix length must be a single number, the `prefix'.  If no
prefix length is provided, it's considered to be @code{/128}.

Note that currently expanded netmasks are not supported.  That means
@code{2001:db00::0/24} is a valid argument while @code{2001:db00::0/ffff:ff00::}
is not.

@item 
128bit に収まる整数。これは1つのアドレスのネットワークと等しく、ネットワークアドレスが `address' に、マスクが @code{/128} になります。

@item 
16byte の @ref{192,,bytes} オブジェクトにビッグエンディアンでパックされた整数。これは整数の `address' と同じように解釈されます。

@item 
A two-tuple of an address description and a netmask, where the address
description is either a string, a 128-bits integer, a 16-bytes packed
integer, or an existing @ref{50d,,IPv6Address} object; and the netmask is an
integer representing the prefix length.
@end enumerate

`address' が有効な IPv6 アドレスでない場合に @ref{41cf,,AddressValueError} 例外を発生させます。マスクが IPv6 アドレスに対して有効でない場合に @ref{41f0,,NetmaskValueError} 例外を発生させます。

`strict' が @code{True} の場合、与えられたアドレスのホストビットが立っていたら @ref{2ec,,ValueError} を発生させます。そうでない場合、ホストビットをマスクして正しいネットワークアドレスを計算します。


バージョン 3.5 で変更: `address' コンストラクタ引数に2要素のタプル形式を追加しました


@geindex version (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network version}@anchor{4209}
@deffn {の属性} version
@end deffn

@geindex max_prefixlen (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network max_prefixlen}@anchor{420a}
@deffn {の属性} max_prefixlen
@end deffn

@geindex is_multicast (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network is_multicast}@anchor{420b}
@deffn {の属性} is_multicast
@end deffn

@geindex is_private (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network is_private}@anchor{420c}
@deffn {の属性} is_private
@end deffn

@geindex is_unspecified (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network is_unspecified}@anchor{420d}
@deffn {の属性} is_unspecified
@end deffn

@geindex is_reserved (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network is_reserved}@anchor{420e}
@deffn {の属性} is_reserved
@end deffn

@geindex is_loopback (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network is_loopback}@anchor{420f}
@deffn {の属性} is_loopback
@end deffn

@geindex is_link_local (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network is_link_local}@anchor{4210}
@deffn {の属性} is_link_local
@end deffn

@geindex network_address (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network network_address}@anchor{4211}
@deffn {の属性} network_address
@end deffn

@geindex broadcast_address (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network broadcast_address}@anchor{4212}
@deffn {の属性} broadcast_address
@end deffn

@geindex hostmask (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network hostmask}@anchor{4213}
@deffn {の属性} hostmask
@end deffn

@geindex netmask (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network netmask}@anchor{4214}
@deffn {の属性} netmask
@end deffn

@geindex with_prefixlen (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network with_prefixlen}@anchor{4215}
@deffn {の属性} with_prefixlen
@end deffn

@geindex compressed (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network compressed}@anchor{4216}
@deffn {の属性} compressed
@end deffn

@geindex exploded (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network exploded}@anchor{4217}
@deffn {の属性} exploded
@end deffn

@geindex with_netmask (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network with_netmask}@anchor{4218}
@deffn {の属性} with_netmask
@end deffn

@geindex with_hostmask (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network with_hostmask}@anchor{4219}
@deffn {の属性} with_hostmask
@end deffn

@geindex num_addresses (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network num_addresses}@anchor{421a}
@deffn {の属性} num_addresses
@end deffn

@geindex prefixlen (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network prefixlen}@anchor{421b}
@deffn {の属性} prefixlen
@end deffn

@geindex hosts() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network hosts}@anchor{17af}
@deffn {メソッド} hosts ()

Returns an iterator over the usable hosts in the network.  The usable
hosts are all the IP addresses that belong to the network, except the
Subnet-Router anycast address.  For networks with a mask length of 127,
the Subnet-Router anycast address is also included in the result.
Networks with a mask of 128 will return a list containing the
single host address.
@end deffn

@geindex overlaps() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network overlaps}@anchor{421c}
@deffn {メソッド} overlaps (other)
@end deffn

@geindex address_exclude() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network address_exclude}@anchor{421d}
@deffn {メソッド} address_exclude (network)
@end deffn

@geindex subnets() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network subnets}@anchor{421e}
@deffn {メソッド} subnets (prefixlen_diff=1, new_prefix=None)
@end deffn

@geindex supernet() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network supernet}@anchor{421f}
@deffn {メソッド} supernet (prefixlen_diff=1, new_prefix=None)
@end deffn

@geindex subnet_of() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network subnet_of}@anchor{4220}
@deffn {メソッド} subnet_of (other)
@end deffn

@geindex supernet_of() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network supernet_of}@anchor{4221}
@deffn {メソッド} supernet_of (other)
@end deffn

@geindex compare_networks() (ipaddress.IPv6Network のメソッド)
@anchor{library/ipaddress ipaddress IPv6Network compare_networks}@anchor{4222}
@deffn {メソッド} compare_networks (other)

@ref{50e,,IPv4Network} の対応する属性のドキュメントを参照してください。
@end deffn

@geindex is_site_local (ipaddress.IPv6Network の属性)
@anchor{library/ipaddress ipaddress IPv6Network is_site_local}@anchor{4223}
@deffn {の属性} is_site_local

This attribute is true for the network as a whole if it is true
for both the network address and the broadcast address.
@end deffn
@end deffn

@node 演算子<3>,,Network オブジェクト,IP ネットワーク定義
@anchor{library/ipaddress id1}@anchor{4224}
@subsubsection 演算子


Network オブジェクトはいくつかの演算子をサポートします。明記されない限り、演算子は互換性のあるオブジェクト間 (つまり IPv4 同士や IPv6 同士) でのみ利用できます。

@menu
* 論理演算子:: 
* イテレーション:: 
* アドレスのコンテナとしてのネットワーク:: 

@end menu

@node 論理演算子,イテレーション,,演算子<3>
@anchor{library/ipaddress logical-operators}@anchor{4225}
@subsubsection 論理演算子


Network objects can be compared with the usual set of logical operators.
Network objects are ordered first by network address, then by net mask.

@node イテレーション,アドレスのコンテナとしてのネットワーク,論理演算子,演算子<3>
@anchor{library/ipaddress iteration}@anchor{4226}
@subsubsection イテレーション


Network objects can be iterated to list all the addresses belonging to the
network.  For iteration, `all' hosts are returned, including unusable hosts
(for usable hosts, use the @ref{17ae,,hosts()} method).  An
example:

@example
>>> for addr in IPv4Network('192.0.2.0/28'):
...     addr
...
IPv4Address('192.0.2.0')
IPv4Address('192.0.2.1')
IPv4Address('192.0.2.2')
IPv4Address('192.0.2.3')
IPv4Address('192.0.2.4')
IPv4Address('192.0.2.5')
IPv4Address('192.0.2.6')
IPv4Address('192.0.2.7')
IPv4Address('192.0.2.8')
IPv4Address('192.0.2.9')
IPv4Address('192.0.2.10')
IPv4Address('192.0.2.11')
IPv4Address('192.0.2.12')
IPv4Address('192.0.2.13')
IPv4Address('192.0.2.14')
IPv4Address('192.0.2.15')
@end example

@node アドレスのコンテナとしてのネットワーク,,イテレーション,演算子<3>
@anchor{library/ipaddress networks-as-containers-of-addresses}@anchor{4227}
@subsubsection アドレスのコンテナとしてのネットワーク


ネットワークオブジェクトは、アドレスのコンテナとして振舞えます。いくつか例をあげます:

@example
>>> IPv4Network('192.0.2.0/28')[0]
IPv4Address('192.0.2.0')
>>> IPv4Network('192.0.2.0/28')[15]
IPv4Address('192.0.2.15')
>>> IPv4Address('192.0.2.6') in IPv4Network('192.0.2.0/28')
True
>>> IPv4Address('192.0.3.6') in IPv4Network('192.0.2.0/28')
False
@end example

@node インターフェイスオブジェクト,その他のモジュールレベル関数,IP ネットワーク定義,ipaddress --- IPv4/IPv6 操作ライブラリ
@anchor{library/ipaddress interface-objects}@anchor{4228}
@subsubsection インターフェイスオブジェクト


インターフェースオブジェクトは @ref{824,,hashable} なので、辞書のキーとして使用できます。

@geindex IPv4Interface (ipaddress のクラス)
@anchor{library/ipaddress ipaddress IPv4Interface}@anchor{1b99}
@deffn {クラス} ipaddress.IPv4Interface (address)

Construct an IPv4 interface.  The meaning of `address' is as in the
constructor of @ref{50e,,IPv4Network}, except that arbitrary host addresses
are always accepted.

@ref{1b99,,IPv4Interface} is a subclass of @ref{50c,,IPv4Address}, so it inherits
all the attributes from that class.  In addition, the following attributes
are available:

@geindex ip (ipaddress.IPv4Interface の属性)
@anchor{library/ipaddress ipaddress IPv4Interface ip}@anchor{4229}
@deffn {の属性} ip

The address (@ref{50c,,IPv4Address}) without network information.

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.ip
IPv4Address('192.0.2.5')
@end example
@end deffn

@geindex network (ipaddress.IPv4Interface の属性)
@anchor{library/ipaddress ipaddress IPv4Interface network}@anchor{422a}
@deffn {の属性} network

The network (@ref{50e,,IPv4Network}) this interface belongs to.

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.network
IPv4Network('192.0.2.0/24')
@end example
@end deffn

@geindex with_prefixlen (ipaddress.IPv4Interface の属性)
@anchor{library/ipaddress ipaddress IPv4Interface with_prefixlen}@anchor{422b}
@deffn {の属性} with_prefixlen

A string representation of the interface with the mask in prefix notation.

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_prefixlen
'192.0.2.5/24'
@end example
@end deffn

@geindex with_netmask (ipaddress.IPv4Interface の属性)
@anchor{library/ipaddress ipaddress IPv4Interface with_netmask}@anchor{422c}
@deffn {の属性} with_netmask

A string representation of the interface with the network as a net mask.

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_netmask
'192.0.2.5/255.255.255.0'
@end example
@end deffn

@geindex with_hostmask (ipaddress.IPv4Interface の属性)
@anchor{library/ipaddress ipaddress IPv4Interface with_hostmask}@anchor{422d}
@deffn {の属性} with_hostmask

A string representation of the interface with the network as a host mask.

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_hostmask
'192.0.2.5/0.0.0.255'
@end example
@end deffn
@end deffn

@geindex IPv6Interface (ipaddress のクラス)
@anchor{library/ipaddress ipaddress IPv6Interface}@anchor{1b9a}
@deffn {クラス} ipaddress.IPv6Interface (address)

Construct an IPv6 interface.  The meaning of `address' is as in the
constructor of @ref{50f,,IPv6Network}, except that arbitrary host addresses
are always accepted.

@ref{1b9a,,IPv6Interface} is a subclass of @ref{50d,,IPv6Address}, so it inherits
all the attributes from that class.  In addition, the following attributes
are available:

@geindex ip (ipaddress.IPv6Interface の属性)
@anchor{library/ipaddress ipaddress IPv6Interface ip}@anchor{422e}
@deffn {の属性} ip
@end deffn

@geindex network (ipaddress.IPv6Interface の属性)
@anchor{library/ipaddress ipaddress IPv6Interface network}@anchor{422f}
@deffn {の属性} network
@end deffn

@geindex with_prefixlen (ipaddress.IPv6Interface の属性)
@anchor{library/ipaddress ipaddress IPv6Interface with_prefixlen}@anchor{4230}
@deffn {の属性} with_prefixlen
@end deffn

@geindex with_netmask (ipaddress.IPv6Interface の属性)
@anchor{library/ipaddress ipaddress IPv6Interface with_netmask}@anchor{4231}
@deffn {の属性} with_netmask
@end deffn

@geindex with_hostmask (ipaddress.IPv6Interface の属性)
@anchor{library/ipaddress ipaddress IPv6Interface with_hostmask}@anchor{4232}
@deffn {の属性} with_hostmask

@ref{1b99,,IPv4Interface} の対応する属性のドキュメントを参照してください。
@end deffn
@end deffn

@menu
* 演算子: 演算子<4>. 

@end menu

@node 演算子<4>,,,インターフェイスオブジェクト
@anchor{library/ipaddress id2}@anchor{4233}
@subsubsection 演算子


Interface オブジェクトはいくつかの演算子をサポートします。明記されない限り、演算子は互換性のあるオブジェクト間 (つまり IPv4 同士や IPv6 同士) でのみ利用できます。

@menu
* 論理演算子: 論理演算子<2>. 

@end menu

@node 論理演算子<2>,,,演算子<4>
@anchor{library/ipaddress id3}@anchor{4234}
@subsubsection 論理演算子


Interface objects can be compared with the usual set of logical operators.

For equality comparison (@code{==} and @code{!=}), both the IP address and network
must be the same for the objects to be equal.  An interface will not compare
equal to any address or network object.

For ordering (@code{<}, @code{>}, etc) the rules are different.  Interface and
address objects with the same IP version can be compared, and the address
objects will always sort before the interface objects.  Two interface objects
are first compared by their networks and, if those are the same, then by their
IP addresses.

@node その他のモジュールレベル関数,Custom Exceptions,インターフェイスオブジェクト,ipaddress --- IPv4/IPv6 操作ライブラリ
@anchor{library/ipaddress other-module-level-functions}@anchor{4235}
@subsubsection その他のモジュールレベル関数


このモジュールは以下のモジュールレベル関数も提供しています:

@geindex v4_int_to_packed() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress v4_int_to_packed}@anchor{4236}
@deffn {の関数} ipaddress.v4_int_to_packed (address)

アドレスをネットワークバイトオーダー(ビッグエンディアン)でパックされた4バイトで表現します。 `address' は IPv4 IPアドレスを整数で表したものです。整数が負だったり IPv4 IPアドレスとして大きすぎる場合は @ref{2ec,,ValueError} 例外を発生させます。

@example
>>> ipaddress.ip_address(3221225985)
IPv4Address('192.0.2.1')
>>> ipaddress.v4_int_to_packed(3221225985)
b'\xc0\x00\x02\x01'
@end example
@end deffn

@geindex v6_int_to_packed() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress v6_int_to_packed}@anchor{4237}
@deffn {の関数} ipaddress.v6_int_to_packed (address)

アドレスをネットワークバイトオーダー(ビッグエンディアン)でパックされた16バイトで表現します。 `address' は IPv6 IPアドレスを整数で表したものです。整数が負だったり IPv6 IPアドレスとして大きすぎる場合は @ref{2ec,,ValueError} 例外を発生させます。
@end deffn

@geindex summarize_address_range() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress summarize_address_range}@anchor{10a2}
@deffn {の関数} ipaddress.summarize_address_range (first, last)

first と last で指定された IPアドレス帯に対するイテレーターを返します。 `first' はアドレス帯の中の最初の @ref{50c,,IPv4Address} か @ref{50d,,IPv6Address} で、 `last' はアドレス帯の中の最後の  @ref{50c,,IPv4Address} か @ref{50d,,IPv6Address} です。 `first' か `last' がIPアドレスでない場合や、2つの型が揃っていない場合に、 @ref{198,,TypeError} を発生させます。 `last' が `first' より大きくない場合や、 `first' アドレスのバージョンが 4 でも 6 でもない場合は @ref{2ec,,ValueError} を発生させます。

@example
>>> [ipaddr for ipaddr in ipaddress.summarize_address_range(
...    ipaddress.IPv4Address('192.0.2.0'),
...    ipaddress.IPv4Address('192.0.2.130'))]
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')]
@end example
@end deffn

@geindex collapse_addresses() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress collapse_addresses}@anchor{10a3}
@deffn {の関数} ipaddress.collapse_addresses (addresses)

Return an iterator of the collapsed @ref{50e,,IPv4Network} or
@ref{50f,,IPv6Network} objects.  `addresses' is an @ref{12f1,,iterable} of
@ref{50e,,IPv4Network} or @ref{50f,,IPv6Network} objects.  A @ref{198,,TypeError} is
raised if `addresses' contains mixed version objects.

@example
>>> [ipaddr for ipaddr in
... ipaddress.collapse_addresses([ipaddress.IPv4Network('192.0.2.0/25'),
... ipaddress.IPv4Network('192.0.2.128/25')])]
[IPv4Network('192.0.2.0/24')]
@end example
@end deffn

@geindex get_mixed_type_key() (ipaddress モジュール)
@anchor{library/ipaddress ipaddress get_mixed_type_key}@anchor{4238}
@deffn {の関数} ipaddress.get_mixed_type_key (obj)

ネットワークとアドレスをソートするための key 関数を返します。アドレスとネットワークは本質的に違うものなので、デフォルトでは比較できません。そのため、次の式は:

@example
IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
@end example

doesn't make sense.  There are some times however, where you may wish to
have @code{ipaddress} sort these anyway.  If you need to do this, you can use
this function as the `key' argument to @ref{dc7,,sorted()}.

`obj' はネットワークオブジェクトかアドレスオブジェクトのどちらかです。
@end deffn

@node Custom Exceptions,,その他のモジュールレベル関数,ipaddress --- IPv4/IPv6 操作ライブラリ
@anchor{library/ipaddress custom-exceptions}@anchor{4239}
@subsubsection Custom Exceptions


クラスのコンストラクタがより具体的なエラー報告をするために、このモジュールでは以下の例外を定義します:

@geindex AddressValueError
@anchor{library/ipaddress ipaddress AddressValueError}@anchor{41cf}
@deffn {例外} ipaddress.AddressValueError (ValueError)

Any value error related to the address.
@end deffn

@geindex NetmaskValueError
@anchor{library/ipaddress ipaddress NetmaskValueError}@anchor{41f0}
@deffn {例外} ipaddress.NetmaskValueError (ValueError)

Any value error related to the net mask.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node マルチメディアサービス,国際化,インターネットプロトコルとサポート,Python 標準ライブラリ
@anchor{library/mm doc}@anchor{423a}@anchor{library/mm mmedia}@anchor{423b}@anchor{library/mm multimedia-services}@anchor{423c}@anchor{library/mm translation-repo}@anchor{423d}
@section マルチメディアサービス


この章で記述されているモジュールは、主にマルチメディアアプリケーションに役立つさまざまなアルゴリズムまたはインターフェイスを実装しています。これらのモジュールはインストール時の自由裁量に応じて利用できます:

@menu
* wave: wave --- WAV ファイルの読み書き. WAV ファイルの読み書き
* colorsys: colorsys --- 色体系間の変換. 色体系間の変換

@end menu

@node wave --- WAV ファイルの読み書き,colorsys --- 色体系間の変換,,マルチメディアサービス
@anchor{library/wave doc}@anchor{423e}@anchor{library/wave module-wave}@anchor{119}@anchor{library/wave wave-read-and-write-wav-files}@anchor{423f}
@subsection @code{wave} --- WAV ファイルの読み書き


@geindex module; wave

@c Documentations stolen from comments in file.

`ソースコード:' Lib/wave.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/wave.py}


__________________________________________________________________


The @code{wave} module provides a convenient interface to the Waveform Audio
"WAVE" (or "WAV") file format. Only uncompressed PCM encoded wave files are
supported.


バージョン 3.12 で変更: Support for @code{WAVE_FORMAT_EXTENSIBLE} headers was added, provided that the
extended format is @code{KSDATAFORMAT_SUBTYPE_PCM}.


The @code{wave} module defines the following function and exception:

@geindex open() (wave モジュール)
@anchor{library/wave wave open}@anchor{b45}
@deffn {の関数} wave.open (file, mode=None)

`file' が文字列ならその名前のファイルを開き、そうでないなら file like オブジェクトとして扱います。 `mode' は以下のうちのいずれかです:


@table @asis

@item @code{'rb'}

読み出しのみのモード。

@item @code{'wb'}

書き込みのみのモード。
@end table

WAVファイルに対して読み込み／書き込み両方のモードで開くことはできないことに注意して下さい。

`mode' が @code{'rb'} の場合 @ref{336,,Wave_read} オブジェクトを返し、 @code{'wb'} の場合 @ref{337,,Wave_write} オブジェクトを返します。 `mode' が省略されていて、 file-like オブジェクトが `file' として渡されると、 @code{file.mode} が `mode' のデフォルト値として使われます。

If you pass in a file-like object, the wave object will not close it when its
@code{close()} method is called; it is the caller's responsibility to close
the file object.

The @ref{b45,,open()} function may be used in a @ref{186,,with} statement.  When
the @code{with} block completes, the @ref{4240,,Wave_read.close()} or
@ref{4241,,Wave_write.close()} method is called.


バージョン 3.4 で変更: シーク不能なファイルのサポートが追加されました。

@end deffn

@geindex Error
@anchor{library/wave wave Error}@anchor{4242}
@deffn {例外} wave.Error

WAVの仕様を犯したり、実装の欠陥に遭遇して何か実行不可能となった時に発生するエラー。
@end deffn

@menu
* Wave_read オブジェクト:: 
* Wave_write オブジェクト:: 

@end menu

@node Wave_read オブジェクト,Wave_write オブジェクト,,wave --- WAV ファイルの読み書き
@anchor{library/wave id1}@anchor{4243}@anchor{library/wave wave-read-objects}@anchor{4244}
@subsubsection Wave_read オブジェクト


@geindex Wave_read (wave のクラス)
@anchor{library/wave wave Wave_read}@anchor{336}
@deffn {クラス} wave.Wave_read

Read a WAV file.

@ref{b45,,open()} によって返される Wave_read オブジェクトには、以下のメソッドがあります:

@geindex close() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read close}@anchor{4240}
@deffn {メソッド} close ()

Close the stream if it was opened by @code{wave}, and make the instance
unusable.  This is called automatically on object collection.
@end deffn

@geindex getnchannels() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getnchannels}@anchor{4245}
@deffn {メソッド} getnchannels ()

オーディオチャンネル数（モノラルなら @code{1} 、ステレオなら @code{2} ）を返します。
@end deffn

@geindex getsampwidth() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getsampwidth}@anchor{4246}
@deffn {メソッド} getsampwidth ()

サンプルサイズをバイト数で返します。
@end deffn

@geindex getframerate() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getframerate}@anchor{4247}
@deffn {メソッド} getframerate ()

サンプリングレートを返します。
@end deffn

@geindex getnframes() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getnframes}@anchor{4248}
@deffn {メソッド} getnframes ()

オーディオフレーム数を返します。
@end deffn

@geindex getcomptype() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getcomptype}@anchor{4249}
@deffn {メソッド} getcomptype ()

圧縮形式を返します（ @code{'NONE'} だけがサポートされている形式です）。
@end deffn

@geindex getcompname() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getcompname}@anchor{424a}
@deffn {メソッド} getcompname ()

@ref{4249,,getcomptype()} を人に判読可能な形にしたものです。通常、 @code{'NONE'} に対して @code{'not compressed'} が返されます。
@end deffn

@geindex getparams() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getparams}@anchor{11ec}
@deffn {メソッド} getparams ()

Returns a @ref{4e0,,namedtuple()} @code{(nchannels, sampwidth,
framerate, nframes, comptype, compname)}, equivalent to output of the
@code{get*()} methods.
@end deffn

@geindex readframes() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read readframes}@anchor{424b}
@deffn {メソッド} readframes (n)

最大 `n' 個のオーディオフレームを読み込んで、 @ref{192,,bytes} オブジェクトとして返します。
@end deffn

@geindex rewind() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read rewind}@anchor{424c}
@deffn {メソッド} rewind ()

ファイルのポインタをオーディオストリームの先頭に戻します。
@end deffn

The following two methods are defined for compatibility with the old @code{aifc}
module, and don't do anything interesting.

@geindex getmarkers() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getmarkers}@anchor{335}
@deffn {メソッド} getmarkers ()

@code{None} を返します。


Deprecated since version 3.13, will be removed in version 3.15: The method only existed for compatibility with the @code{aifc} module
which has been removed in Python 3.13.

@end deffn

@geindex getmark() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read getmark}@anchor{334}
@deffn {メソッド} getmark (id)

エラーを発生します。


Deprecated since version 3.13, will be removed in version 3.15: The method only existed for compatibility with the @code{aifc} module
which has been removed in Python 3.13.

@end deffn

以下の2つのメソッドは共通の"位置"を定義しています。"位置"は他の関数とは独立して実装されています。

@geindex setpos() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read setpos}@anchor{424d}
@deffn {メソッド} setpos (pos)

ファイルのポインタを指定した位置に設定します。
@end deffn

@geindex tell() (wave.Wave_read のメソッド)
@anchor{library/wave wave Wave_read tell}@anchor{424e}
@deffn {メソッド} tell ()

ファイルの現在のポインタ位置を返します。
@end deffn
@end deffn

@node Wave_write オブジェクト,,Wave_read オブジェクト,wave --- WAV ファイルの読み書き
@anchor{library/wave id2}@anchor{424f}@anchor{library/wave wave-write-objects}@anchor{11ed}
@subsubsection Wave_write オブジェクト


@geindex Wave_write (wave のクラス)
@anchor{library/wave wave Wave_write}@anchor{337}
@deffn {クラス} wave.Wave_write

Write a WAV file.

Wave_write objects, as returned by @ref{b45,,open()}.

For seekable output streams, the @code{wave} header will automatically be updated
to reflect the number of frames actually written.  For unseekable streams, the
`nframes' value must be accurate when the first frame data is written.  An
accurate `nframes' value can be achieved either by calling
@ref{4250,,setnframes()} or @ref{4251,,setparams()} with the number
of frames that will be written before @ref{4241,,close()} is called and
then using @ref{11ee,,writeframesraw()} to write the frame data, or by
calling @ref{11ef,,writeframes()} with all of the frame data to be
written.  In the latter case @ref{11ef,,writeframes()} will calculate
the number of frames in the data and set `nframes' accordingly before writing
the frame data.


バージョン 3.4 で変更: シーク不能なファイルのサポートが追加されました。


Wave_write objects have the following methods:

@geindex close() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write close}@anchor{4241}
@deffn {メソッド} close ()

Make sure `nframes' is correct, and close the file if it was opened by
@code{wave}.  This method is called upon object collection.  It will raise
an exception if the output stream is not seekable and `nframes' does not
match the number of frames actually written.
@end deffn

@geindex setnchannels() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write setnchannels}@anchor{4252}
@deffn {メソッド} setnchannels (n)

チャンネル数を設定します。
@end deffn

@geindex setsampwidth() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write setsampwidth}@anchor{4253}
@deffn {メソッド} setsampwidth (n)

サンプルサイズを `n' バイトに設定します。
@end deffn

@geindex setframerate() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write setframerate}@anchor{4254}
@deffn {メソッド} setframerate (n)

サンプリングレートを `n' に設定します。


バージョン 3.2 で変更: 整数ではない値がこのメソッドに入力された場合は、直近の整数に丸められます。

@end deffn

@geindex setnframes() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write setnframes}@anchor{4250}
@deffn {メソッド} setnframes (n)

フレーム数を `n' に設定します。もし実際に書き込まれたフレームの数と異なるなら、これは後で変更されます (出力ストリームがシーク不能なら、更新しようとした時にエラーが起きます)。
@end deffn

@geindex setcomptype() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write setcomptype}@anchor{4255}
@deffn {メソッド} setcomptype (type, name)

圧縮形式とその記述を設定します。現在のところ、非圧縮を示す圧縮形式 @code{NONE} だけがサポートされています。
@end deffn

@geindex setparams() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write setparams}@anchor{4251}
@deffn {メソッド} setparams (tuple)

The `tuple' should be @code{(nchannels, sampwidth, framerate, nframes, comptype,
compname)}, with values valid for the @code{set*()} methods.  Sets all
parameters.
@end deffn

@geindex tell() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write tell}@anchor{4256}
@deffn {メソッド} tell ()

ファイルの中の現在位置を返します。 @ref{424e,,Wave_read.tell()} と @ref{424d,,Wave_read.setpos()} メソッドでお断りしたことがこのメソッドにも当てはまります。
@end deffn

@geindex writeframesraw() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write writeframesraw}@anchor{11ee}
@deffn {メソッド} writeframesraw (data)

`nframes' の修正なしにオーディオフレームを書き込みます。


バージョン 3.4 で変更: どのような @ref{193,,bytes-like object} も使用できるようになりました。

@end deffn

@geindex writeframes() (wave.Wave_write のメソッド)
@anchor{library/wave wave Wave_write writeframes}@anchor{11ef}
@deffn {メソッド} writeframes (data)

出力ストリームが seek 不可能で、 `data' が書き込まれた後でそれ以前に `nframes' に設定された値と書き込まれた全フレーム数が一致しなければ、エラーを送出します。


バージョン 3.4 で変更: どのような @ref{193,,bytes-like object} も使用できるようになりました。


@ref{11ef,,writeframes()} や @ref{11ee,,writeframesraw()} メソッドを呼び出したあとで、どんなパラメータを設定しようとしても不正となることに注意して下さい。そうすると @ref{4242,,wave.Error} を発生します。
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node colorsys --- 色体系間の変換,,wave --- WAV ファイルの読み書き,マルチメディアサービス
@anchor{library/colorsys doc}@anchor{4257}@anchor{library/colorsys colorsys-conversions-between-color-systems}@anchor{4258}@anchor{library/colorsys module-colorsys}@anchor{20}@anchor{library/colorsys translation-repo}@anchor{4259}
@subsection @code{colorsys} --- 色体系間の変換


@geindex module; colorsys

`ソースコード:' Lib/colorsys.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/colorsys.py}


__________________________________________________________________


The @code{colorsys} module defines bidirectional conversions of color values
between colors expressed in the RGB (Red Green Blue) color space used in
computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness
Saturation) and HSV (Hue Saturation Value).  Coordinates in all of these color
spaces are floating-point values.  In the YIQ space, the Y coordinate is between
0 and 1, but the I and Q coordinates can be positive or negative.  In all other
spaces, the coordinates are all between 0 and 1.


@subsubheading 参考


色空間に関するより詳細な情報は @indicateurl{https://poynton.ca/ColorFAQ.html} と @indicateurl{https://www.cambridgeincolour.com/tutorials/color-spaces.htm} にあります。


The @code{colorsys} module defines the following functions:

@geindex rgb_to_yiq() (colorsys モジュール)
@anchor{library/colorsys colorsys rgb_to_yiq}@anchor{425a}
@deffn {の関数} colorsys.rgb_to_yiq (r, g, b)

RGB から YIQ に変換します。
@end deffn

@geindex yiq_to_rgb() (colorsys モジュール)
@anchor{library/colorsys colorsys yiq_to_rgb}@anchor{425b}
@deffn {の関数} colorsys.yiq_to_rgb (y, i, q)

YIQ から RGB に変換します。
@end deffn

@geindex rgb_to_hls() (colorsys モジュール)
@anchor{library/colorsys colorsys rgb_to_hls}@anchor{1a72}
@deffn {の関数} colorsys.rgb_to_hls (r, g, b)

RGB から HLS に変換します。
@end deffn

@geindex hls_to_rgb() (colorsys モジュール)
@anchor{library/colorsys colorsys hls_to_rgb}@anchor{425c}
@deffn {の関数} colorsys.hls_to_rgb (h, l, s)

HLS から RGB に変換します。
@end deffn

@geindex rgb_to_hsv() (colorsys モジュール)
@anchor{library/colorsys colorsys rgb_to_hsv}@anchor{425d}
@deffn {の関数} colorsys.rgb_to_hsv (r, g, b)

RGB から HSV に変換します。
@end deffn

@geindex hsv_to_rgb() (colorsys モジュール)
@anchor{library/colorsys colorsys hsv_to_rgb}@anchor{425e}
@deffn {の関数} colorsys.hsv_to_rgb (h, s, v)

HSV から RGB に変換します。
@end deffn

以下はプログラム例です:

@example
>>> import colorsys
>>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)
(0.5, 0.5, 0.4)
>>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)
(0.2, 0.4, 0.4)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 国際化,Graphical user interfaces with Tk,マルチメディアサービス,Python 標準ライブラリ
@anchor{library/i18n doc}@anchor{425f}@anchor{library/i18n i18n}@anchor{4260}@anchor{library/i18n internationalization}@anchor{4261}@anchor{library/i18n translation-repo}@anchor{4262}
@section 国際化


この章で解説されるモジュールは、プログラムのメッセージで使用される言語を選択したり、または出力を地域の習慣に従って変更するメカニズムを提供して、言語やロケールに依存しないソフトの開発を手助けします。

この章で解説されるモジュールのリスト:

@menu
* gettext: gettext --- 多言語国際化サービス. 多言語国際化サービス
* locale: locale --- 国際化サービス. 国際化サービス

@end menu

@node gettext --- 多言語国際化サービス,locale --- 国際化サービス,,国際化
@anchor{library/gettext doc}@anchor{4263}@anchor{library/gettext gettext-multilingual-internationalization-services}@anchor{4264}@anchor{library/gettext module-gettext}@anchor{67}
@subsection @code{gettext} --- 多言語国際化サービス


@geindex module; gettext

`ソースコード:' Lib/gettext.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/gettext.py}


__________________________________________________________________


The @code{gettext} module provides internationalization (I18N) and localization
(L10N) services for your Python modules and applications. It supports both the
GNU @code{gettext} message catalog API and a higher level, class-based API that may
be more appropriate for Python files.  The interface described below allows you
to write your module and application messages in one natural language, and
provide a catalog of translated messages for running under different natural
languages.

ここでは Python のモジュールやアプリケーションを地域化するためのいくつかのヒントも提供しています。

@menu
* GNU gettext API:: 
* クラス形式の API:: 
* プログラムやモジュールを国際化する:: 
* 謝辞: 謝辞<9>. 

@end menu

@node GNU gettext API,クラス形式の API,,gettext --- 多言語国際化サービス
@anchor{library/gettext gnu-gettext-api}@anchor{4265}
@subsubsection GNU @code{gettext} API


The @code{gettext} module defines the following API, which is very similar to
the GNU @code{gettext} API.  If you use this API you will affect the
translation of your entire application globally.  Often this is what you want if
your application is monolingual, with the choice of language dependent on the
locale of your user.  If you are localizing a Python module, or if your
application needs to switch languages on the fly, you probably want to use the
class-based API instead.

@geindex bindtextdomain() (gettext モジュール)
@anchor{library/gettext gettext bindtextdomain}@anchor{4266}
@deffn {の関数} gettext.bindtextdomain (domain, localedir=None)

Bind the `domain' to the locale directory `localedir'.  More concretely,
@code{gettext} will look for binary @code{.mo} files for the given domain using
the path (on Unix): @code{`localedir'/`language'/LC_MESSAGES/`domain'.mo}, where
`language' is searched for in the environment variables 
@geindex LANGUAGE
@geindex 環境変数; LANGUAGE
@code{LANGUAGE},
@geindex LC_ALL
@geindex 環境変数; LC_ALL
@code{LC_ALL}, 
@geindex LC_MESSAGES
@geindex 環境変数; LC_MESSAGES
@code{LC_MESSAGES}, and 
@geindex LANG
@geindex 環境変数; LANG
@code{LANG} respectively.

`localedir' が省略されるか @code{None} の場合、現在 `domain' に対応付けられているロケールディレクトリが返されます。 @footnote{
The default locale directory is system dependent; for example, on Red Hat Linux
it is @code{/usr/share/locale}, but on Solaris it is @code{/usr/lib/locale}.
The @code{gettext} module does not try to support these system dependent
defaults; instead its default is @code{`sys.base_prefix'/share/locale} (see
@ref{3e6,,sys.base_prefix}). For this reason, it is always best to call
@ref{4266,,bindtextdomain()} with an explicit absolute path at the start of your
application.
}
@end deffn

@geindex textdomain() (gettext モジュール)
@anchor{library/gettext gettext textdomain}@anchor{4267}
@deffn {の関数} gettext.textdomain (domain=None)

現在のグローバルドメインを変更したり調べたりします。
`domain' が @code{None} の場合、現在のグローバルドメインが返されます。それ以外の場合には、グローバルドメインに `domain' を設定し、その設定されたグローバルドメインを返します。
@end deffn

@geindex _ (下線);gettext

@geindex gettext() (gettext モジュール)
@anchor{library/gettext gettext gettext}@anchor{1682}
@deffn {の関数} gettext.gettext (message)

Return the localized translation of `message', based on the current global
domain, language, and locale directory.  This function is usually aliased as
@code{_()} in the local namespace (see examples below).
@end deffn

@geindex dgettext() (gettext モジュール)
@anchor{library/gettext gettext dgettext}@anchor{4268}
@deffn {の関数} gettext.dgettext (domain, message)

@ref{1682,,gettext()} と同様ですが、指定された `domain' からメッセージを探します。
@end deffn

@geindex ngettext() (gettext モジュール)
@anchor{library/gettext gettext ngettext}@anchor{4269}
@deffn {の関数} gettext.ngettext (singular, plural, n)

@ref{1682,,gettext()} と同様ですが、複数形を考慮しています。
翻訳が見つかった場合、複数形の選択公式を `n' に適用し、その結果得られたメッセージを返します (言語によっては二つ以上の複数形があります)。
翻訳が見つからなかった場合、 `n' が 1 なら `singular' を返します; そうでない場合 `plural' を返します。

複数形の選択公式はカタログのヘッダから取得されます。
選択公式は自由変数 `n' を持つ C または Python の式です;
その式の評価結果はカタログにある複数形のインデックスになります。
@code{.po} ファイルで用いられる詳細な文法と、様々な言語における選択公式については GNU gettext ドキュメント@footnote{https://www.gnu.org/software/gettext/manual/gettext.html} を参照してください。
@end deffn

@geindex dngettext() (gettext モジュール)
@anchor{library/gettext gettext dngettext}@anchor{426a}
@deffn {の関数} gettext.dngettext (domain, singular, plural, n)

@ref{4269,,ngettext()} と同様ですが、指定された `domain' からメッセージを探します。
@end deffn

@geindex pgettext() (gettext モジュール)
@anchor{library/gettext gettext pgettext}@anchor{be8}
@deffn {の関数} gettext.pgettext (context, message)
@end deffn

@geindex dpgettext() (gettext モジュール)
@anchor{library/gettext gettext dpgettext}@anchor{426b}
@deffn {の関数} gettext.dpgettext (domain, context, message)
@end deffn

@geindex npgettext() (gettext モジュール)
@anchor{library/gettext gettext npgettext}@anchor{426c}
@deffn {の関数} gettext.npgettext (context, singular, plural, n)
@end deffn

@geindex dnpgettext() (gettext モジュール)
@anchor{library/gettext gettext dnpgettext}@anchor{426d}
@deffn {の関数} gettext.dnpgettext (domain, context, singular, plural, n)

Similar to the corresponding functions without the @code{p} in the prefix (that
is, @ref{67,,gettext()}, @ref{4268,,dgettext()}, @ref{4269,,ngettext()}, @ref{426a,,dngettext()}),
but the translation is restricted to the given message `context'.


Added in version 3.8.

@end deffn

Note that GNU @code{gettext} also defines a @code{dcgettext()} method, but
this was deemed not useful and so it is currently unimplemented.

以下にこの API の典型的な使用法を示します:

@example
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print(_('This is a translatable string.'))
@end example

@node クラス形式の API,プログラムやモジュールを国際化する,GNU gettext API,gettext --- 多言語国際化サービス
@anchor{library/gettext class-based-api}@anchor{426e}
@subsubsection クラス形式の API


The class-based API of the @code{gettext} module gives you more flexibility and
greater convenience than the GNU @code{gettext} API.  It is the recommended
way of localizing your Python applications and modules.  @code{gettext} defines
a @ref{426f,,GNUTranslations} class which implements the parsing of GNU @code{.mo} format
files, and has methods for returning strings. Instances of this class can also
install themselves in the built-in namespace as the function @code{_()}.

@geindex find() (gettext モジュール)
@anchor{library/gettext gettext find}@anchor{4270}
@deffn {の関数} gettext.find (domain, localedir=None, languages=None, all=False)

この関数は標準的な @code{.mo} ファイル検索アルゴリズムを実装しています。 @ref{4267,,textdomain()} と同じく、 `domain' を引数にとります。オプションの `localedir' は @ref{4266,,bindtextdomain()} と同じです。またオプションの `languages' は文字列を列挙したリストで、各文字列は言語コードを表します。

`localedir' が与えられていない場合、標準のシステムロケールディレクトリが使われます。 @footnote{
上の @ref{4266,,bindtextdomain()} に関する脚注を参照してください。
} `languages' が与えられなかった場合、以下の環境変数: 
@geindex LANGUAGE
@geindex 環境変数; LANGUAGE
@code{LANGUAGE} 、 
@geindex LC_ALL
@geindex 環境変数; LC_ALL
@code{LC_ALL} 、 
@geindex LC_MESSAGES
@geindex 環境変数; LC_MESSAGES
@code{LC_MESSAGES} 、および 
@geindex LANG
@geindex 環境変数; LANG
@code{LANG} が検索されます。空でない値を返した最初の候補が `languages' 変数として使われます。この環境変数は言語名をコロンで分かち書きしたリストを含んでいなければなりません。 @ref{4270,,find()} はこの文字列をコロンで分割し、言語コードの候補リストを生成します。

@ref{4270,,find()} は次に言語コードを展開および正規化し、リストの各要素について、以下のパス構成:

@code{`localedir'/`language'/LC_MESSAGES/`domain'.mo}

からなる実在するファイルの探索を反復的に行います。 @ref{4270,,find()} は上記のような実在するファイルで最初に見つかったものを返します。該当するファイルが見つからなかった場合、 @code{None} が返されます。 `all' が与えられていれば、全ファイル名のリストが言語リストまたは環境変数で指定されている順番に並べられたものを返します。
@end deffn

@geindex translation() (gettext モジュール)
@anchor{library/gettext gettext translation}@anchor{c6d}
@deffn {の関数} gettext.translation (domain, localedir=None, languages=None, class_=None, fallback=False)

Return a @code{*Translations} instance based on the `domain', `localedir',
and `languages', which are first passed to @ref{4270,,find()} to get a list of the
associated @code{.mo} file paths.  Instances with identical @code{.mo} file
names are cached.  The actual class instantiated is `class_' if
provided, otherwise @ref{426f,,GNUTranslations}.  The class's constructor must
take a single @ref{13db,,file object} argument.

複数の @code{.mo} ファイルがあった場合、後ろのファイルは前のファイルのフォールバックとして利用されます。
フォールバックの設定のために、 @ref{757,,copy.copy()} を使いキャッシュから翻訳オブジェクトを複製します; こうすることで、実際のインスタンスデータはキャッシュのものと共有されたままになります。

@code{.mo} ファイルが見つからなかった場合、 `fallback' が偽 (デフォルト値) ならこの関数は @ref{2c0,,OSError} を送出し、 `fallback' が真なら @ref{4271,,NullTranslations} インスタンスが返されます。


バージョン 3.3 で変更: 以前は @ref{125e,,IOError} が送出されました; それは現在 @ref{2c0,,OSError} のエイリアスです。



バージョン 3.11 で変更: `codeset' parameter is removed.

@end deffn

@geindex install() (gettext モジュール)
@anchor{library/gettext gettext install}@anchor{c6e}
@deffn {の関数} gettext.install (domain, localedir=None, *, names=None)

This installs the function @code{_()} in Python's builtins namespace, based on
`domain' and `localedir' which are passed to the function @ref{c6d,,translation()}.

`names' パラメータについては、翻訳オブジェクトの @ref{4272,,install()} メソッドの説明を参照ください。

As seen below, you usually mark the strings in your application that are
candidates for translation, by wrapping them in a call to the @code{_()}
function, like this:

@example
print(_('This string will be translated.'))
@end example

For convenience, you want the @code{_()} function to be installed in Python's
builtins namespace, so it is easily accessible in all modules of your
application.


バージョン 3.11 で変更: `names' is now a keyword-only parameter.

@end deffn

@menu
* NullTranslations クラス:: 
* GNUTranslations クラス:: 
* Solaris メッセージカタログ機構のサポート:: 
* Catalog コンストラクタ:: 

@end menu

@node NullTranslations クラス,GNUTranslations クラス,,クラス形式の API
@anchor{library/gettext the-nulltranslations-class}@anchor{4273}
@subsubsection @code{NullTranslations} クラス


翻訳クラスは、元のソースファイル中のメッセージ文字列から翻訳されたメッセージ文字列への変換処理が実際に実装されているクラスです。
全ての翻訳クラスで基底クラスとして使われているクラスが @ref{4271,,NullTranslations} です; このクラスは、独自の翻訳クラスを実装するのに使える基本的なインターフェースを提供しています。
以下に @code{NullTranslations} のメソッドを示します:

@geindex NullTranslations (gettext のクラス)
@anchor{library/gettext gettext NullTranslations}@anchor{4271}
@deffn {クラス} gettext.NullTranslations (fp=None)

オプションの @ref{13db,,ファイルオブジェクト} `fp' を取ります。この引数は基底クラスでは無視されます。このメソッドは  "保護された (protected)" インスタンス変数 `_info' および  `_charset' を初期化します。これらの変数の値は派生クラスで設定することができます。同様に `_fallback' も初期化しますが、この値は @ref{4274,,add_fallback()} で設定されます。その後、 `fp' が @code{None} でない場合 @code{self._parse(fp)} を呼び出します。

@geindex _parse() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations _parse}@anchor{4275}
@deffn {メソッド} _parse (fp)

基底クラスでは何もしない (no-op) ようになっています。このメソッドの役割はファイルオブジェクト `fp' を引数に取り、ファイルからデータを読み出し、メッセージカタログを初期化することです。サポートされていないメッセージカタログ形式を使っている場合、その形式を解釈するためにはこのメソッドを上書きしなくてはなりません。
@end deffn

@geindex add_fallback() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations add_fallback}@anchor{4274}
@deffn {メソッド} add_fallback (fallback)

`fallback' を現在の翻訳オブジェクトの代替オブジェクトとして追加します。翻訳オブジェクトが与えられたメッセージに対して翻訳メッセージを提供できない場合、この代替オブジェクトに問い合わせることになります。
@end deffn

@geindex gettext() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations gettext}@anchor{4276}
@deffn {メソッド} gettext (message)

フォールバックが設定されている場合、フォールバックの @code{gettext()} に処理を移譲します。
そうでない場合、引数として受け取った `message' を返します。
派生クラスで上書きするメソッドです。
@end deffn

@geindex ngettext() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations ngettext}@anchor{4277}
@deffn {メソッド} ngettext (singular, plural, n)

フォールバックが設定されている場合、フォールバックの @code{ngettext()} に処理を移譲します。
そうでない場合、 `n' が 1 なら `singular' を返します; それ以外なら `plural' を返します。
派生クラスで上書きするメソッドです。
@end deffn

@geindex pgettext() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations pgettext}@anchor{4278}
@deffn {メソッド} pgettext (context, message)

代替オブジェクトが設定されている場合、 @ref{be8,,pgettext()} を代替オブジェクトに転送します。そうでない場合、翻訳されたメッセージを返します。派生クラスで上書きするメソッドです。


Added in version 3.8.

@end deffn

@geindex npgettext() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations npgettext}@anchor{4279}
@deffn {メソッド} npgettext (context, singular, plural, n)

代替オブジェクトが設定されている場合、 @ref{426c,,npgettext()} を代替オブジェクトに転送します。そうでない場合、翻訳されたメッセージを返します。派生クラスで上書きするメソッドです。


Added in version 3.8.

@end deffn

@geindex info() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations info}@anchor{427a}
@deffn {メソッド} info ()

Return a dictionary containing
the metadata found in the message catalog file.
@end deffn

@geindex charset() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations charset}@anchor{427b}
@deffn {メソッド} charset ()

メッセージカタログファイルのエンコーディングを返します。
@end deffn

@geindex install() (gettext.NullTranslations のメソッド)
@anchor{library/gettext gettext NullTranslations install}@anchor{4272}
@deffn {メソッド} install (names=None)

このメソッドは @ref{4276,,gettext()} を組み込み名前空間にインストールし、変数 @code{_} に束縛します。

If the `names' parameter is given, it must be a sequence containing the
names of functions you want to install in the builtins namespace in
addition to @code{_()}.  Supported names are @code{'gettext'}, @code{'ngettext'},
@code{'pgettext'}, and @code{'npgettext'}.

Note that this is only one way, albeit the most convenient way, to make
the @code{_()} function available to your application.  Because it affects
the entire application globally, and specifically the built-in namespace,
localized modules should never install @code{_()}. Instead, they should use
this code to make @code{_()} available to their module:

@example
import gettext
t = gettext.translation('mymodule', ...)
_ = t.gettext
@end example

This puts @code{_()} only in the module's global namespace and so only
affects calls within this module.


バージョン 3.8 で変更: @code{'pgettext'} と @code{'npgettext'} が追加されました。

@end deffn
@end deffn

@node GNUTranslations クラス,Solaris メッセージカタログ機構のサポート,NullTranslations クラス,クラス形式の API
@anchor{library/gettext the-gnutranslations-class}@anchor{427c}
@subsubsection @code{GNUTranslations} クラス


The @code{gettext} module provides one additional class derived from
@ref{4271,,NullTranslations}: @ref{426f,,GNUTranslations}.  This class overrides
@code{_parse()} to enable reading GNU @code{gettext} format @code{.mo} files
in both big-endian and little-endian format.

@ref{426f,,GNUTranslations} parses optional metadata out of the translation
catalog. It is convention with GNU @code{gettext} to include metadata as
the translation for the empty string. This metadata is in 
@geindex RFC; RFC 822
RFC 822@footnote{https://datatracker.ietf.org/doc/html/rfc822.html}-style
@code{key: value} pairs, and should contain the @code{Project-Id-Version} key.  If the
key @code{Content-Type} is found, then the @code{charset} property is used to
initialize the "protected" @code{_charset} instance variable, defaulting to
@code{None} if not found.  If the charset encoding is specified, then all message
ids and message strings read from the catalog are converted to Unicode using
this encoding, else ASCII is assumed.

Since message ids are read as Unicode strings too, all @code{*gettext()} methods
will assume message ids as Unicode strings, not byte strings.

The entire set of key/value pairs are placed into a dictionary and set as the
"protected" @code{_info} instance variable.

@code{.mo} ファイルのマジックナンバーが不正な場合や、メジャーバージョン番号が予期されないものの場合、あるいはその他の問題がファイルの読み出し中に発生した場合、 @ref{426f,,GNUTranslations} クラスのインスタンス化で @ref{2c0,,OSError} が送出されることがあります。

@geindex GNUTranslations (gettext のクラス)
@anchor{library/gettext gettext GNUTranslations}@anchor{426f}
@deffn {クラス} gettext.GNUTranslations

以下のメソッドは基底クラスの実装からオーバライドされています:

@geindex gettext() (gettext.GNUTranslations のメソッド)
@anchor{library/gettext gettext GNUTranslations gettext}@anchor{427d}
@deffn {メソッド} gettext (message)

カタログから `message' id を検索して、対応するメッセージ文字列を Unicode でエンコードして返します。
`message' id に対応するエントリがカタログに存在せず、フォールバックが設定されている場合、検索処理をフォールバックの @ref{4276,,gettext()} メソッドに移譲します。
それ以外の場合は、 `message' id 自体が返されます。
@end deffn

@geindex ngettext() (gettext.GNUTranslations のメソッド)
@anchor{library/gettext gettext GNUTranslations ngettext}@anchor{427e}
@deffn {メソッド} ngettext (singular, plural, n)

メッセージ id に対する複数形を検索します。カタログに対する検索では `singular' がメッセージ id として用いられ、 `n' にはどの複数形を用いるかを指定します。返されるメッセージ文字列は Unicode 文字列です。

メッセージ id がカタログ中に見つからず、フォールバックが指定されている場合は、メッセージ検索要求はフォールバックの @ref{4277,,ngettext()} メソッドに移譲されます。
それ以外の場合、 `n' が 1 ならば `singular' が返され、それ以外なら `plural' が返されます。

以下に例を示します。:

@example
n = len(os.listdir('.'))
cat = GNUTranslations(somefile)
message = cat.ngettext(
    'There is %(num)d file in this directory',
    'There are %(num)d files in this directory',
    n) % @{'num': n@}
@end example
@end deffn

@geindex pgettext() (gettext.GNUTranslations のメソッド)
@anchor{library/gettext gettext GNUTranslations pgettext}@anchor{427f}
@deffn {メソッド} pgettext (context, message)

カタログから `context' と `message' id を検索して、対応するメッセージ文字列を、 Unicode でエンコードして返します。 `message' id と `context' に対するエントリがカタログに存在せず、フォールバックが設定されている場合、フォールバック検索はオブジェクトの @ref{be8,,pgettext()} メソッドに転送されます。そうでない場合、 `message' id 自体が返されます。


Added in version 3.8.

@end deffn

@geindex npgettext() (gettext.GNUTranslations のメソッド)
@anchor{library/gettext gettext GNUTranslations npgettext}@anchor{4280}
@deffn {メソッド} npgettext (context, singular, plural, n)

メッセージ id に対する複数形を検索します。カタログに対する検索では `singular' がメッセージ id として用いられ、 `n' にはどの複数形を用いるかを指定します。

`context' に対するメッセージ id がカタログ中に見つからず、フォールバックオブジェクトが指定されている場合、メッセージ検索要求はフォールバックオブジェクトの @ref{426c,,npgettext()} メソッドに転送されます。そうでない場合、 `n' が 1 ならば `singular' が返され、それ以外に対しては `plural' が返されます。


Added in version 3.8.

@end deffn
@end deffn

@node Solaris メッセージカタログ機構のサポート,Catalog コンストラクタ,GNUTranslations クラス,クラス形式の API
@anchor{library/gettext solaris-message-catalog-support}@anchor{4281}
@subsubsection Solaris メッセージカタログ機構のサポート


Solaris オペレーティングシステムでは、独自の @code{.mo} バイナリファイル形式を定義していますが、この形式に関するドキュメントが手に入らないため、現時点ではサポートされていません。

@node Catalog コンストラクタ,,Solaris メッセージカタログ機構のサポート,クラス形式の API
@anchor{library/gettext the-catalog-constructor}@anchor{4282}
@subsubsection Catalog コンストラクタ


@geindex GNOME

GNOME uses a version of the @code{gettext} module by James Henstridge, but this
version has a slightly different API.  Its documented usage was:

@example
import gettext
cat = gettext.Catalog(domain, localedir)
_ = cat.gettext
print(_('hello world'))
@end example

For compatibility with this older module, the function @code{Catalog()} is an
alias for the @ref{c6d,,translation()} function described above.

このモジュールと Henstridge のバージョンとの間には一つ相違点があります: 彼のカタログオブジェクトはマップ型の API を介したアクセスがサポートされていましたが、この API は使われていないらしく、現在はサポートされていません。

@node プログラムやモジュールを国際化する,謝辞<9>,クラス形式の API,gettext --- 多言語国際化サービス
@anchor{library/gettext i18n-howto}@anchor{33cb}@anchor{library/gettext internationalizing-your-programs-and-modules}@anchor{4283}
@subsubsection プログラムやモジュールを国際化する


国際化 (I18N, I-nternationalizatio-N) とは、プログラムを複数の言語に対応させる操作を指します。地域化 (L10N, L-ocalizatio-N) とは、すでに国際化されているプログラムを特定地域の言語や文化的な事情に対応させることを指します。Python プログラムに多言語メッセージ機能を追加するには、以下の手順を踏む必要があります:


@enumerate 

@item 
プログラムやモジュールで翻訳対象とする文字列に特殊なマークをつけて準備します

@item 
マークづけをしたファイルに一連のツールを走らせ、生のメッセージカタログを生成します

@item 
特定の言語へのメッセージカタログの翻訳を作成します

@item 
use the @code{gettext} module so that message strings are properly translated
@end enumerate

In order to prepare your code for I18N, you need to look at all the strings in
your files.  Any string that needs to be translated should be marked by wrapping
it in @code{_('...')} --- that is, a call to the function @ref{67,,_}.  For example:

@example
filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
    fp.write(message)
@end example

この例では、文字列 @code{'writing a log message'} が翻訳対象候補としてマーク付けされており、文字列 @code{'mylog.txt'} および @code{'w'} はされていません。

翻訳対象の文字列を抽出するツールもあります。
オリジナルの GNU @code{gettext} は C と C++ のソースコードしかサポートしませんが、拡張版の @code{xgettext} は Python を含めた多くの言語で書かれたコードを読み取り、翻訳できる文字列を発見します。
Babel@footnote{https://babel.pocoo.org/} は Python の国際化ライブラリで、翻訳文字列の抽出とメッセージカタログのコンパイルを行う @code{pybabel} スクリプトがあります。
François Pinard が開発した @code{xpot} と呼ばれるプログラムは同じような処理を行え、彼の po-utils package@footnote{https://github.com/pinard/po-utils} の一部として利用可能です。

(Python には @code{pygettext.py} および @code{msgfmt.py} という名前の pure-Python 版プログラムもあります;
これをインストールしてくれる Python ディストリビューションもあります。
@code{pygettext.py} は @code{xgettext} に似たプログラムですが Python のソースコードしか理解できず、 C や C++ のような他のプログラミング言語を扱えません。
@code{pygettext.py} は @code{xgettext} と同様のコマンドラインインターフェースをサポートしています;
詳しい使い方については @code{pygettext.py --help} と実行してください。
@code{msgfmt.py} は GNU @code{msgfmt} とバイナリ互換性があります。
この2つのプログラムがあれば、 GNU @code{gettext} パッケージを使わずに Python アプリケーションを国際化できるでしょう。)

@code{xgettext} や @code{pygettext} のようなツールは、メッセージカタログである @code{.po} ファイルを生成します。
このファイルは人間が判読可能な構造をしていて、ソースコード中のマークが着けられた文字列と、その文字列の仮置きの訳文が一緒に書き込まれています。

Copies of these @code{.po} files are then handed over to the
individual human translators who write translations for every
supported natural language.  They send back the completed
language-specific versions as a @code{<language-name>.po} file that's
compiled into a machine-readable @code{.mo} binary catalog file using
the @code{msgfmt} program.  The @code{.mo} files are used by the
@code{gettext} module for the actual translation processing at
run-time.

How you use the @code{gettext} module in your code depends on whether you are
internationalizing a single module or your entire application. The next two
sections will discuss each case.

@menu
* モジュールを地域化する:: 
* アプリケーションを地域化する:: 
* 動作中 (on the fly) に言語を切り替える: 動作中 on the fly に言語を切り替える. 
* 翻訳処理の遅延解決:: 

@end menu

@node モジュールを地域化する,アプリケーションを地域化する,,プログラムやモジュールを国際化する
@anchor{library/gettext localizing-your-module}@anchor{4284}
@subsubsection モジュールを地域化する


モジュールを地域化する場合、グローバルな変更、例えば組み込み名前空間への変更を行わないように注意しなければなりません。GNU @code{gettext} API ではなく、クラス形式の API を使うべきです。

仮に対象のモジュール名を "spam" とし、モジュールの各言語における翻訳が収められた @code{.mo} ファイルが @code{/usr/share/locale} に GNU @code{gettext} 形式で置かれているとします。この場合、モジュールの最初で以下のようにします:

@example
import gettext
t = gettext.translation('spam', '/usr/share/locale')
_ = t.gettext
@end example

@node アプリケーションを地域化する,動作中 on the fly に言語を切り替える,モジュールを地域化する,プログラムやモジュールを国際化する
@anchor{library/gettext localizing-your-application}@anchor{4285}
@subsubsection アプリケーションを地域化する


If you are localizing your application, you can install the @code{_()} function
globally into the built-in namespace, usually in the main driver file of your
application.  This will let all your application-specific files just use
@code{_('...')} without having to explicitly install it in each file.

単純な場合では、単に以下の短いコードをアプリケーションの主ドライバファイルに追加するだけです:

@example
import gettext
gettext.install('myapplication')
@end example

ロケールの辞書を設定する必要がある場合、@ref{c6e,,install()} 関数に渡すことが出来ます:

@example
import gettext
gettext.install('myapplication', '/usr/share/locale')
@end example

@node 動作中 on the fly に言語を切り替える,翻訳処理の遅延解決,アプリケーションを地域化する,プログラムやモジュールを国際化する
@anchor{library/gettext changing-languages-on-the-fly}@anchor{4286}
@subsubsection 動作中 (on the fly) に言語を切り替える


多くの言語を同時にサポートする必要がある場合、複数の翻訳インスタンスを生成して、例えば以下のコードのように、インスタンスを明示的に切り替えてもかまいません。:

@example
import gettext

lang1 = gettext.translation('myapplication', languages=['en'])
lang2 = gettext.translation('myapplication', languages=['fr'])
lang3 = gettext.translation('myapplication', languages=['de'])

# start by using language1
lang1.install()

# ... time goes by, user selects language 2
lang2.install()

# ... more time goes by, user selects language 3
lang3.install()
@end example

@node 翻訳処理の遅延解決,,動作中 on the fly に言語を切り替える,プログラムやモジュールを国際化する
@anchor{library/gettext deferred-translations}@anchor{4287}
@subsubsection 翻訳処理の遅延解決


コードを書く上では、ほとんどの状況で文字列はコードされた場所で翻訳されます。しかし場合によっては、翻訳対象として文字列をマークはするが、その後実際に翻訳が行われるように遅延させる必要が生じます。古典的な例は以下のようなコートです:

@example
animals = ['mollusk',
           'albatross',
           'rat',
           'penguin',
           'python', ]
# ...
for a in animals:
    print(a)
@end example

ここで、リスト @code{animals} 内の文字列は翻訳対象としてマークはしたいが、文字列が出力されるまで実際に翻訳を行うのは避けたいとします。

こうした状況を処理する一つの方法を以下に示します:

@example
def _(message): return message

animals = [_('mollusk'),
           _('albatross'),
           _('rat'),
           _('penguin'),
           _('python'), ]

del _

# ...
for a in animals:
    print(_(a))
@end example

This works because the dummy definition of @code{_()} simply returns the string
unchanged.  And this dummy definition will temporarily override any definition
of @code{_()} in the built-in namespace (until the @ref{1b1f,,del} command). Take
care, though if you have a previous definition of @code{_()} in the local
namespace.

Note that the second use of @code{_()} will not identify "a" as being
translatable to the @code{gettext} program, because the parameter
is not a string literal.

もう一つの処理法は、以下の例のようなやり方です:

@example
def N_(message): return message

animals = [N_('mollusk'),
           N_('albatross'),
           N_('rat'),
           N_('penguin'),
           N_('python'), ]

# ...
for a in animals:
    print(_(a))
@end example

In this case, you are marking translatable strings with the function
@code{N_()}, which won't conflict with any definition of @code{_()}.
However, you will need to teach your message extraction program to
look for translatable strings marked with @code{N_()}. @code{xgettext},
@code{pygettext}, @code{pybabel extract}, and @code{xpot} all
support this through the use of the @code{-k} command-line switch.
The choice of @code{N_()} here is totally arbitrary; it could have just
as easily been @code{MarkThisStringForTranslation()}.

@node 謝辞<9>,,プログラムやモジュールを国際化する,gettext --- 多言語国際化サービス
@anchor{library/gettext acknowledgements}@anchor{4288}
@subsubsection 謝辞


以下の人々が、このモジュールのコード、フィードバック、設計に関する助言、過去の実装、そして有益な経験談による貢献をしてくれました:


@itemize *

@item 
Peter Funk

@item 
James Henstridge

@item 
Juan David Ibáñez Palomar

@item 
Marc-André Lemburg

@item 
Martin von Löwis

@item 
François Pinard

@item 
Barry Warsaw

@item 
Gustavo Niemeyer
@end itemize

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node locale --- 国際化サービス,,gettext --- 多言語国際化サービス,国際化
@anchor{library/locale doc}@anchor{4289}@anchor{library/locale locale-internationalization-services}@anchor{428a}@anchor{library/locale module-locale}@anchor{8a}@anchor{library/locale translation-repo}@anchor{428b}
@subsection @code{locale} --- 国際化サービス


@geindex module; locale

`ソースコード:' Lib/locale.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/locale.py}


__________________________________________________________________


The @code{locale} module opens access to the POSIX locale database and
functionality. The POSIX locale mechanism allows programmers to deal with
certain cultural issues in an application, without requiring the programmer to
know all the specifics of each country where the software is executed.

@geindex module;_locale

The @code{locale} module is implemented on top of the @code{_locale} module,
which in turn uses an ANSI C locale implementation if available.

The @code{locale} module defines the following exception and functions:

@geindex Error
@anchor{library/locale locale Error}@anchor{428c}
@deffn {例外} locale.Error

@ref{328,,setlocale()} に渡されたロケールが認識されない場合例外が送出されます。
@end deffn

@geindex setlocale() (locale モジュール)
@anchor{library/locale locale setlocale}@anchor{328}
@deffn {の関数} locale.setlocale (category, locale=None)

If `locale' is given and not @code{None}, @ref{328,,setlocale()} modifies the locale
setting for the `category'. The available categories are listed in the data
description below. `locale' may be a @ref{428d,,string}, or a pair,
language code and encoding. An empty string specifies the user's
default settings. If the modification of the locale fails, the exception
@ref{428c,,Error} is raised. If successful, the new locale setting is returned.

If `locale' is a pair, it is converted to a locale name using
the locale aliasing engine.
The language code has the same format as a @ref{428d,,locale name},
but without encoding and @code{@@}-modifier.
The language code and encoding can be @code{None}.

`locale' が省略されたり @code{None} の場合、`category' の現在の設定が返されます。

以下はプログラム例です:

@example
>>> import locale
>>> loc = locale.setlocale(locale.LC_ALL)  # get current locale
# use German locale; name and availability varies with platform
>>> locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
>>> locale.strcoll('f\xe4n', 'foo')  # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '@w{'})   # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale
@end example

@ref{328,,setlocale()} is not thread-safe on most systems. Applications typically
start with a call of:

@example
import locale
locale.setlocale(locale.LC_ALL, '@w{'})
@end example

から書き始めます。これは全てのカテゴリをユーザの環境における標準設定 (大抵は環境変数 
@geindex LANG
@geindex 環境変数; LANG
@code{LANG} で指定されています) に設定します。その後複数スレッドを使ってロケールを変更したりしない限り、問題は起こらないはずです。
@end deffn

@geindex localeconv() (locale モジュール)
@anchor{library/locale locale localeconv}@anchor{df8}
@deffn {の関数} locale.localeconv ()

地域的な慣行のデータベースを辞書として返します。辞書は以下の文字列をキーとして持っています:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

カテゴリ

@tab

キー

@tab

意味

@item

@ref{428e,,LC_NUMERIC}

@tab

@code{'decimal_point'}

@tab

小数点を表す文字です。

@item

@tab

@code{'grouping'}

@tab

@code{'thousands_sep'} が来るかもしれない場所を相対的に表した数からなる配列です。配列が @ref{428f,,CHAR_MAX} で終端されている場合、それ以上の桁では桁数字のグループ化を行いません。配列が @code{0} で終端されている場合、最後に指定したグループが反復的に使われます。

@item

@tab

@code{'thousands_sep'}

@tab

桁グループ間を区切るために使われる文字です。

@item

@ref{4290,,LC_MONETARY}

@tab

@code{'int_curr_symbol'}

@tab

国際通貨を表現する記号です。

@item

@tab

@code{'currency_symbol'}

@tab

地域的な通貨を表現する記号です。

@item

@tab

@code{'p_cs_precedes/n_cs_precedes'}

@tab

通貨記号が値の前につくかどうかです (それぞれ正の値、負の値を表します)。

@item

@tab

@code{'p_sep_by_space/n_sep_by_space'}

@tab

通貨記号と値との間にスペースを入れるかどうかです (それぞれ正の値、負の値を表します)。

@item

@tab

@code{'mon_decimal_point'}

@tab

金額表示の際に使われる小数点です。

@item

@tab

@code{'frac_digits'}

@tab

金額を地域的な方法で表現する際の小数点以下の桁数です。

@item

@tab

@code{'int_frac_digits'}

@tab

金額を国際的な方法で表現する際の小数点以下の桁数です。

@item

@tab

@code{'mon_thousands_sep'}

@tab

金額表示の際に桁区切り記号です。

@item

@tab

@code{'mon_grouping'}

@tab

@code{'grouping'} と同じで、金額表示の際に使われます。

@item

@tab

@code{'positive_sign'}

@tab

正の値の金額表示に使われる記号です。

@item

@tab

@code{'negative_sign'}

@tab

負の値の金額表示に使われる記号です。

@item

@tab

@code{'p_sign_posn/n_sign_posn'}

@tab

符号の位置です (それぞれ正の値と負の値を表します)。以下を参照してください。

@end multitable


数値形式の値に @ref{428f,,CHAR_MAX} を設定すると、そのロケールでは値が指定されていないことを表します。

@code{'p_sign_posn'} および @code{'n_sign_posn'} の取り得る値は以下の通りです。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

値

@tab

説明

@item

@code{0}

@tab

通貨記号および値は丸括弧で囲われます。

@item

@code{1}

@tab

符号は値と通貨記号より前に来ます。

@item

@code{2}

@tab

符号は値と通貨記号の後に続きます。

@item

@code{3}

@tab

符号は値の直前に来ます。

@item

@code{4}

@tab

符号は値の直後に来ます。

@item

@code{CHAR_MAX}

@tab

このロケールでは特に指定しません。

@end multitable


@code{LC_NUMERIC} ロケールや @code{LC_MONETARY} ロケールが @code{LC_CTYPE} ロケールと異なっていて、数値文字列や通貨文字列が非 ASCII 文字列の場合、この関数は一時的に @code{LC_NUMERIC} ロケールや @code{LC_MONETARY} ロケールに @code{LC_CTYPE} ロケールを設定します。
この一時的な変更は他のスレッドに影響を及ぼします。


バージョン 3.7 で変更: この関数は、一時的に @code{LC_NUMERIC} ロケールに @code{LC_CTYPE} ロケールを設定する場合があります。

@end deffn

@geindex nl_langinfo() (locale モジュール)
@anchor{library/locale locale nl_langinfo}@anchor{454}
@deffn {の関数} locale.nl_langinfo (option)

ロケール特有の情報を文字列として返します。この関数は全てのシステムで利用可能なわけではなく、指定できる `option' もプラットフォーム間で大きく異なります。引数として使えるのは、locale モジュールで利用可能なシンボル定数を表す数字です。

関数 @ref{454,,nl_langinfo()} は以下のキーのうち一つを受理します。ほとんどの記述は GNU C ライブラリ中の対応する説明から引用されています。

@geindex CODESET (locale モジュール)
@anchor{library/locale locale CODESET}@anchor{4291}
@deffn {データ} locale.CODESET

選択されたロケールで用いられている文字エンコーディングの名前を文字列で取得します。
@end deffn

@geindex D_T_FMT (locale モジュール)
@anchor{library/locale locale D_T_FMT}@anchor{4292}
@deffn {データ} locale.D_T_FMT

日付と時刻をロケール特有の方法で表現するために、 @ref{1402,,time.strftime()} の書式文字列として用いることのできる文字列を取得します。
@end deffn

@geindex D_FMT (locale モジュール)
@anchor{library/locale locale D_FMT}@anchor{4293}
@deffn {データ} locale.D_FMT

日付をロケール特有の方法で表現するために、 @ref{1402,,time.strftime()} の書式文字列として用いることのできる文字列を取得します。
@end deffn

@geindex T_FMT (locale モジュール)
@anchor{library/locale locale T_FMT}@anchor{4294}
@deffn {データ} locale.T_FMT

時刻をロケール特有の方法で表現するために、 @ref{1402,,time.strftime()} の書式文字列として用いることのできる文字列を取得します。
@end deffn

@geindex T_FMT_AMPM (locale モジュール)
@anchor{library/locale locale T_FMT_AMPM}@anchor{4295}
@deffn {データ} locale.T_FMT_AMPM

時刻を午前／午後の書式で表現するために、 @ref{1402,,time.strftime()} の書式文字列として用いることのできる文字列を取得します。
@end deffn

@geindex DAY_1 (locale モジュール)
@geindex DAY_2 (locale モジュール)
@geindex DAY_3 (locale モジュール)
@geindex DAY_4 (locale モジュール)
@geindex DAY_5 (locale モジュール)
@geindex DAY_6 (locale モジュール)
@geindex DAY_7 (locale モジュール)
@anchor{library/locale locale DAY_1}@anchor{4296}
@deffn {データ} locale.DAY_1
@anchor{library/locale locale DAY_2}@anchor{4297}
@deffnx {データ} locale.DAY_2
@anchor{library/locale locale DAY_3}@anchor{4298}
@deffnx {データ} locale.DAY_3
@anchor{library/locale locale DAY_4}@anchor{4299}
@deffnx {データ} locale.DAY_4
@anchor{library/locale locale DAY_5}@anchor{429a}
@deffnx {データ} locale.DAY_5
@anchor{library/locale locale DAY_6}@anchor{429b}
@deffnx {データ} locale.DAY_6
@anchor{library/locale locale DAY_7}@anchor{429c}
@deffnx {データ} locale.DAY_7

1 週間中の n 番目の曜日名を取得します。

@cartouche
@quotation 注釈 
ロケール US における、 @ref{4296,,DAY_1} を日曜日とする慣行に従っています。国際的な (ISO 8601) 月曜日を週の初めとする慣行ではありません。
@end quotation
@end cartouche
@end deffn

@geindex ABDAY_1 (locale モジュール)
@geindex ABDAY_2 (locale モジュール)
@geindex ABDAY_3 (locale モジュール)
@geindex ABDAY_4 (locale モジュール)
@geindex ABDAY_5 (locale モジュール)
@geindex ABDAY_6 (locale モジュール)
@geindex ABDAY_7 (locale モジュール)
@anchor{library/locale locale ABDAY_1}@anchor{429d}
@deffn {データ} locale.ABDAY_1
@anchor{library/locale locale ABDAY_2}@anchor{429e}
@deffnx {データ} locale.ABDAY_2
@anchor{library/locale locale ABDAY_3}@anchor{429f}
@deffnx {データ} locale.ABDAY_3
@anchor{library/locale locale ABDAY_4}@anchor{42a0}
@deffnx {データ} locale.ABDAY_4
@anchor{library/locale locale ABDAY_5}@anchor{42a1}
@deffnx {データ} locale.ABDAY_5
@anchor{library/locale locale ABDAY_6}@anchor{42a2}
@deffnx {データ} locale.ABDAY_6
@anchor{library/locale locale ABDAY_7}@anchor{42a3}
@deffnx {データ} locale.ABDAY_7

1 週間中の n 番目の曜日名を略式表記で取得します。
@end deffn

@geindex MON_1 (locale モジュール)
@geindex MON_2 (locale モジュール)
@geindex MON_3 (locale モジュール)
@geindex MON_4 (locale モジュール)
@geindex MON_5 (locale モジュール)
@geindex MON_6 (locale モジュール)
@geindex MON_7 (locale モジュール)
@geindex MON_8 (locale モジュール)
@geindex MON_9 (locale モジュール)
@geindex MON_10 (locale モジュール)
@geindex MON_11 (locale モジュール)
@geindex MON_12 (locale モジュール)
@anchor{library/locale locale MON_1}@anchor{42a4}
@deffn {データ} locale.MON_1
@anchor{library/locale locale MON_2}@anchor{42a5}
@deffnx {データ} locale.MON_2
@anchor{library/locale locale MON_3}@anchor{42a6}
@deffnx {データ} locale.MON_3
@anchor{library/locale locale MON_4}@anchor{42a7}
@deffnx {データ} locale.MON_4
@anchor{library/locale locale MON_5}@anchor{42a8}
@deffnx {データ} locale.MON_5
@anchor{library/locale locale MON_6}@anchor{42a9}
@deffnx {データ} locale.MON_6
@anchor{library/locale locale MON_7}@anchor{42aa}
@deffnx {データ} locale.MON_7
@anchor{library/locale locale MON_8}@anchor{42ab}
@deffnx {データ} locale.MON_8
@anchor{library/locale locale MON_9}@anchor{42ac}
@deffnx {データ} locale.MON_9
@anchor{library/locale locale MON_10}@anchor{42ad}
@deffnx {データ} locale.MON_10
@anchor{library/locale locale MON_11}@anchor{42ae}
@deffnx {データ} locale.MON_11
@anchor{library/locale locale MON_12}@anchor{42af}
@deffnx {データ} locale.MON_12

n 番目の月の名前を取得します。
@end deffn

@geindex ABMON_1 (locale モジュール)
@geindex ABMON_2 (locale モジュール)
@geindex ABMON_3 (locale モジュール)
@geindex ABMON_4 (locale モジュール)
@geindex ABMON_5 (locale モジュール)
@geindex ABMON_6 (locale モジュール)
@geindex ABMON_7 (locale モジュール)
@geindex ABMON_8 (locale モジュール)
@geindex ABMON_9 (locale モジュール)
@geindex ABMON_10 (locale モジュール)
@geindex ABMON_11 (locale モジュール)
@geindex ABMON_12 (locale モジュール)
@anchor{library/locale locale ABMON_1}@anchor{42b0}
@deffn {データ} locale.ABMON_1
@anchor{library/locale locale ABMON_2}@anchor{42b1}
@deffnx {データ} locale.ABMON_2
@anchor{library/locale locale ABMON_3}@anchor{42b2}
@deffnx {データ} locale.ABMON_3
@anchor{library/locale locale ABMON_4}@anchor{42b3}
@deffnx {データ} locale.ABMON_4
@anchor{library/locale locale ABMON_5}@anchor{42b4}
@deffnx {データ} locale.ABMON_5
@anchor{library/locale locale ABMON_6}@anchor{42b5}
@deffnx {データ} locale.ABMON_6
@anchor{library/locale locale ABMON_7}@anchor{42b6}
@deffnx {データ} locale.ABMON_7
@anchor{library/locale locale ABMON_8}@anchor{42b7}
@deffnx {データ} locale.ABMON_8
@anchor{library/locale locale ABMON_9}@anchor{42b8}
@deffnx {データ} locale.ABMON_9
@anchor{library/locale locale ABMON_10}@anchor{42b9}
@deffnx {データ} locale.ABMON_10
@anchor{library/locale locale ABMON_11}@anchor{42ba}
@deffnx {データ} locale.ABMON_11
@anchor{library/locale locale ABMON_12}@anchor{42bb}
@deffnx {データ} locale.ABMON_12

n 番目の月の名前を略式表記で取得します。
@end deffn

@geindex RADIXCHAR (locale モジュール)
@anchor{library/locale locale RADIXCHAR}@anchor{42bc}
@deffn {データ} locale.RADIXCHAR

基数点 (小数点ドット、あるいは小数点コンマ、等) を取得します。
@end deffn

@geindex THOUSEP (locale モジュール)
@anchor{library/locale locale THOUSEP}@anchor{42bd}
@deffn {データ} locale.THOUSEP

1000 単位桁区切り (3 桁ごとのグループ化) の区切り文字を取得します。
@end deffn

@geindex YESEXPR (locale モジュール)
@anchor{library/locale locale YESEXPR}@anchor{42be}
@deffn {データ} locale.YESEXPR

肯定／否定で答える質問に対する肯定回答を正規表現関数で認識するために利用できる正規表現を取得します。
@end deffn

@geindex NOEXPR (locale モジュール)
@anchor{library/locale locale NOEXPR}@anchor{42bf}
@deffn {データ} locale.NOEXPR

Get a regular expression that can be used with the @code{regex(3)} function to
recognize a negative response to a yes/no question.

@cartouche
@quotation 注釈 
The regular expressions for @ref{42be,,YESEXPR} and
@ref{42bf,,NOEXPR} use syntax suitable for the
@code{regex} function from the C library, which might
differ from the syntax used in @ref{be,,re}.
@end quotation
@end cartouche
@end deffn

@geindex CRNCYSTR (locale モジュール)
@anchor{library/locale locale CRNCYSTR}@anchor{42c0}
@deffn {データ} locale.CRNCYSTR

通貨シンボルを取得します。シンボルを値の前に表示させる場合には "-"、値の後ろに表示させる場合には "+"、シンボルを基数点と置き換える場合には "." を前につけます。
@end deffn

@geindex ERA (locale モジュール)
@anchor{library/locale locale ERA}@anchor{42c1}
@deffn {データ} locale.ERA

Get a string which describes how years are counted and displayed for
each era in a locale.

ほとんどのロケールではこの値を定義していません。この値を設定しているロケールの例は Japanese です。日本には日付の伝統的な表示法として、時の天皇に対応する元号名があります。

Normally it should not be necessary to use this value directly. Specifying
the @code{E} modifier in their format strings causes the @ref{1402,,time.strftime()}
function to use this information.
The format of the returned string is specified in `The Open Group Base
Specifications Issue 8', paragraph 7.3.5.2 LC_TIME C-Language Access@footnote{https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html#tag_07_03_05_02}.
@end deffn

@geindex ERA_D_T_FMT (locale モジュール)
@anchor{library/locale locale ERA_D_T_FMT}@anchor{42c2}
@deffn {データ} locale.ERA_D_T_FMT

日付および時間をロケール固有の年代に基づいた方法で表現するために、 @ref{1402,,time.strftime()} の書式文字列として用いることのできる文字列を取得します。
@end deffn

@geindex ERA_D_FMT (locale モジュール)
@anchor{library/locale locale ERA_D_FMT}@anchor{42c3}
@deffn {データ} locale.ERA_D_FMT

日付をロケール固有の年代に基づいた方法で表現するために、 @ref{1402,,time.strftime()} の書式文字列として用いることのできる文字列を取得します。
@end deffn

@geindex ERA_T_FMT (locale モジュール)
@anchor{library/locale locale ERA_T_FMT}@anchor{42c4}
@deffn {データ} locale.ERA_T_FMT

時刻をロケール固有の年代に基づいた方法で表現するために、 @ref{1402,,time.strftime()} の書式文字列として用いることのできる文字列を取得します。
@end deffn

@geindex ALT_DIGITS (locale モジュール)
@anchor{library/locale locale ALT_DIGITS}@anchor{42c5}
@deffn {データ} locale.ALT_DIGITS

Get a string consisting of up to 100 semicolon-separated symbols used
to represent the values 0 to 99 in a locale-specific way.
In most locales this is an empty string.
@end deffn

The function temporarily sets the @code{LC_CTYPE} locale to the locale
of the category that determines the requested value (@code{LC_TIME},
@code{LC_NUMERIC}, @code{LC_MONETARY} or @code{LC_MESSAGES}) if locales are
different and the resulting string is non-ASCII.
This temporary change affects other threads.


バージョン 3.14 で変更: The function now temporarily sets the @code{LC_CTYPE} locale in some cases.

@end deffn

@geindex getdefaultlocale() (locale モジュール)
@anchor{library/locale locale getdefaultlocale}@anchor{326}
@deffn {の関数} locale.getdefaultlocale ([envvars])

標準のロケール設定を取得しようと試み、結果をタプル @code{(language code, encoding)} の形式で返します。

POSIXによると、 @code{setlocale(LC_ALL, '@w{'})} を呼ばなかったプログラムは、移植可能な @code{'C'} ロケール設定を使います。 @code{setlocale(LC_ALL, '@w{'})} を呼ぶことで、 
@geindex LANG
@geindex 環境変数; LANG
@code{LANG} 変数で定義された標準のロケール設定を使うようになります。 Python では現在のロケール設定に干渉したくないので、上で述べたような方法でその挙動をエミュレーションしています。

他のプラットフォームとの互換性を維持するために、環境変数 
@geindex LANG
@geindex 環境変数; LANG
@code{LANG} だけでなく、引数 `envvars' で指定された環境変数のリストも調べられます。最初に見つかった定義が使われます。 `envvars' は標準では GNU gettext で使われている検索順になります; これは常に変数名 @code{LANG} を探します。GNU gettext では @code{'LC_ALL'} 、 @code{'LC_CTYPE'} 、 @code{'LANG'} 、および @code{'LANGUAGE'} の順に調べられます。

The language code has the same format as a @ref{428d,,locale name},
but without encoding and @code{@@}-modifier.
The language code and encoding may be @code{None} if their values cannot be
determined.
The "C" locale is represented as @code{(None, None)}.


Deprecated since version 3.11, will be removed in version 3.15.

@end deffn

@geindex getlocale() (locale モジュール)
@anchor{library/locale locale getlocale}@anchor{327}
@deffn {の関数} locale.getlocale (category=LC_CTYPE)

Returns the current setting for the given locale category as a tuple containing
the language code and encoding. `category' may be one of the @code{LC_*}
values except @ref{42c6,,LC_ALL}.  It defaults to @ref{42c7,,LC_CTYPE}.

The language code has the same format as a @ref{428d,,locale name},
but without encoding and @code{@@}-modifier.
The language code and encoding may be @code{None} if their values cannot be
determined.
The "C" locale is represented as @code{(None, None)}.
@end deffn

@geindex getpreferredencoding() (locale モジュール)
@anchor{library/locale locale getpreferredencoding}@anchor{75c}
@deffn {の関数} locale.getpreferredencoding (do_setlocale=True)

テキストデータに使われる @ref{54a,,ロケールエンコーディング} を、ユーザの設定に基づいて返します。ユーザの設定は異なるシステム間では異なった方法で表現され、システムによってはプログラミング的に得ることができないこともあるので、この関数が返すのはただの推測です。

システムによっては、ユーザの設定を取得するために @ref{328,,setlocale()} を呼び出す必要があるため、この関数はスレッド安全ではありません。 @ref{328,,setlocale()} を呼び出す必要がない、または呼び出したくない場合、 `do_setlocale' を @code{False} に設定する必要があります。

On Android or if the @ref{866,,Python UTF-8 Mode} is enabled, always
return @code{'utf-8'}, the @ref{54a,,locale encoding} and the `do_setlocale'
argument are ignored.

The @ref{42c8,,Python preinitialization} configures the LC_CTYPE
locale. See also the @ref{75d,,filesystem encoding and error handler}.


バージョン 3.7 で変更: この関数は、 Android 上あるいは @ref{866,,Python UTF-8 モード} が有効になっている場合、常に @code{"utf-8"} を返すようになりました。

@end deffn

@geindex getencoding() (locale モジュール)
@anchor{library/locale locale getencoding}@anchor{329}
@deffn {の関数} locale.getencoding ()

Get the current @ref{54a,,locale encoding}:


@itemize *

@item 
On Android and VxWorks, return @code{"utf-8"}.

@item 
On Unix, return the encoding of the current @ref{42c7,,LC_CTYPE} locale.
Return @code{"utf-8"} if @code{nl_langinfo(CODESET)} returns an empty string:
for example, if the current LC_CTYPE locale is not supported.

@item 
On Windows, return the ANSI code page.
@end itemize

The @ref{42c8,,Python preinitialization} configures the LC_CTYPE
locale. See also the @ref{75d,,filesystem encoding and error handler}.

This function is similar to
@ref{75c,,getpreferredencoding(False)} except this
function ignores the @ref{866,,Python UTF-8 Mode}.


Added in version 3.11.

@end deffn

@geindex normalize() (locale モジュール)
@anchor{library/locale locale normalize}@anchor{42c9}
@deffn {の関数} locale.normalize (localename)

与えたロケール名を規格化したロケールコードを返します。返されるロケールコードは @ref{328,,setlocale()} で使うために書式化されています。規格化が失敗した場合、もとの名前がそのまま返されます。

与えたエンコードがシステムにとって未知の場合、標準の設定では、この関数は @ref{328,,setlocale()} と同様に、エンコーディングをロケールコードにおける標準のエンコーディングに設定します。
@end deffn

@geindex strcoll() (locale モジュール)
@anchor{library/locale locale strcoll}@anchor{42ca}
@deffn {の関数} locale.strcoll (string1, string2)

現在の @ref{42cb,,LC_COLLATE} 設定に従って二つの文字列を比較します。他の比較を行う関数と同じように、 `string1' が `string2' に対して前に来るか、後に来るか、あるいは二つが等しいかによって、それぞれ負の値、正の値、あるいは @code{0} を返します。
@end deffn

@geindex strxfrm() (locale モジュール)
@anchor{library/locale locale strxfrm}@anchor{17bd}
@deffn {の関数} locale.strxfrm (string)

文字列を、ロケールを考慮した比較に使える形式に変換します。例えば、 @code{strxfrm(s1) < strxfrm(s2)} は @code{strcoll(s1, s2) < 0} と等価です。この関数は同じ文字列が何度も比較される場合、例えば文字列からなるシーケンスを順序付けて並べる際に使うことができます。
@end deffn

@geindex format_string() (locale モジュール)
@anchor{library/locale locale format_string}@anchor{742}
@deffn {の関数} locale.format_string (format, val, grouping=False, monetary=False)

Formats a number `val' according to the current @ref{428e,,LC_NUMERIC} setting.
The format follows the conventions of the @code{%} operator.  For floating-point
values, the decimal point is modified if appropriate.  If `grouping' is @code{True},
also takes the grouping into account.

`monetary' が真なら、桁区切り記号やグループ化文字列を用いて変換を行います。

@code{format % val} 形式のフォーマット指定子を、現在のロケール設定を考慮したうえで処理します。


バージョン 3.7 で変更: `monetary' キーワード引数が追加されました。

@end deffn

@geindex currency() (locale モジュール)
@anchor{library/locale locale currency}@anchor{42cc}
@deffn {の関数} locale.currency (val, symbol=True, grouping=False, international=False)

数値 `val' を、現在の @ref{4290,,LC_MONETARY} の設定にあわせてフォーマットします。

`symbol' が真の場合は、返される文字列に通貨記号が含まれるようになります。これはデフォルトの設定です。`grouping' が @code{True} の場合(これはデフォルトではありません)は、値をグループ化します。`international' が @code{True} の場合(これはデフォルトではありません)は、国際的な通貨記号を使用します。

@cartouche
@quotation 注釈 
この関数は 'C' ロケールでは動作しないので、まず @ref{328,,setlocale()} でロケールを設定する必要があります。
@end quotation
@end cartouche
@end deffn

@geindex str() (locale モジュール)
@anchor{library/locale locale str}@anchor{42cd}
@deffn {の関数} locale.str (float)

Formats a floating-point number using the same format as the built-in function
@code{str(float)}, but takes the decimal point into account.
@end deffn

@geindex delocalize() (locale モジュール)
@anchor{library/locale locale delocalize}@anchor{1026}
@deffn {の関数} locale.delocalize (string)

文字列を @ref{428e,,LC_NUMERIC} で設定された慣行に従って正規化された数値文字列に変換します。


Added in version 3.5.

@end deffn

@geindex localize() (locale モジュール)
@anchor{library/locale locale localize}@anchor{42ce}
@deffn {の関数} locale.localize (string, grouping=False, monetary=False)

Converts a normalized number string into a formatted string following the
@ref{428e,,LC_NUMERIC} settings.


Added in version 3.10.

@end deffn

@geindex atof() (locale モジュール)
@anchor{library/locale locale atof}@anchor{42cf}
@deffn {の関数} locale.atof (string, func=float)

Converts a string to a number, following the @ref{428e,,LC_NUMERIC} settings,
by calling `func' on the result of calling @ref{1026,,delocalize()} on `string'.
@end deffn

@geindex atoi() (locale モジュール)
@anchor{library/locale locale atoi}@anchor{42d0}
@deffn {の関数} locale.atoi (string)

文字列を @ref{428e,,LC_NUMERIC} で設定された慣行に従って整数に変換します。
@end deffn

@geindex LC_CTYPE (locale モジュール)
@anchor{library/locale locale LC_CTYPE}@anchor{42c7}
@deffn {データ} locale.LC_CTYPE

Locale category for the character type functions.  Most importantly, this
category defines the text encoding, i.e. how bytes are interpreted as
Unicode codepoints.  See 
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/} and 
@geindex Python Enhancement Proposals; PEP 540
PEP 540@footnote{https://peps.python.org/pep-0540/} for how this variable
might be automatically coerced to @code{C.UTF-8} to avoid issues created by
invalid settings in containers or incompatible settings passed over remote
SSH connections.

Python doesn't internally use locale-dependent character transformation functions
from @code{ctype.h}. Instead, @code{pyctype.h} provides locale-independent
equivalents like @ref{1570,,Py_TOLOWER}.
@end deffn

@geindex LC_COLLATE (locale モジュール)
@anchor{library/locale locale LC_COLLATE}@anchor{42cb}
@deffn {データ} locale.LC_COLLATE

Locale category for sorting strings.  The functions @ref{42ca,,strcoll()} and
@ref{17bd,,strxfrm()} of the @code{locale} module are affected.
@end deffn

@geindex LC_TIME (locale モジュール)
@anchor{library/locale locale LC_TIME}@anchor{42d1}
@deffn {データ} locale.LC_TIME

時刻を書式化するためのロケールカテゴリです。 @ref{1402,,time.strftime()}  はこのカテゴリに設定されている慣行に従います。
@end deffn

@geindex LC_MONETARY (locale モジュール)
@anchor{library/locale locale LC_MONETARY}@anchor{4290}
@deffn {データ} locale.LC_MONETARY

金額に関係する値を書式化するためのロケールカテゴリです。設定可能なオプションは関数 @ref{df8,,localeconv()} で得ることができます。
@end deffn

@geindex LC_MESSAGES (locale モジュール)
@anchor{library/locale locale LC_MESSAGES}@anchor{42d2}
@deffn {データ} locale.LC_MESSAGES

メッセージ表示のためのロケールカテゴリです。現在 Python はアプリケーション毎にロケールに対応したメッセージを出力する機能はサポートしていません。 @ref{3024,,os.strerror()} が返すような、オペレーティングシステムによって表示されるメッセージはこのカテゴリによって影響を受けます。

This value may not be available on operating systems not conforming to the
POSIX standard, most notably Windows.
@end deffn

@geindex LC_NUMERIC (locale モジュール)
@anchor{library/locale locale LC_NUMERIC}@anchor{428e}
@deffn {データ} locale.LC_NUMERIC

Locale category for formatting numbers.  The functions @ref{742,,format_string()},
@ref{42d0,,atoi()}, @ref{42cf,,atof()} and @ref{42cd,,str()} of the @code{locale} module are
affected by that category.  All other numeric formatting operations are not
affected.
@end deffn

@geindex LC_ALL (locale モジュール)
@anchor{library/locale locale LC_ALL}@anchor{42c6}
@deffn {データ} locale.LC_ALL

全てのロケール設定を総合したものです。ロケールを変更する際にこのフラグが使われた場合、そのロケールにおける全てのカテゴリを設定しようと試みます。一つでも失敗したカテゴリがあった場合、全てのカテゴリにおいて設定変更を行いません。このフラグを使ってロケールを取得した場合、全てのカテゴリにおける設定を示す文字列が返されます。この文字列は、後に設定を元に戻すために使うことができます。
@end deffn

@geindex CHAR_MAX (locale モジュール)
@anchor{library/locale locale CHAR_MAX}@anchor{428f}
@deffn {データ} locale.CHAR_MAX

@ref{df8,,localeconv()} の返す特別な値のためのシンボル定数です。
@end deffn

@menu
* ロケールの背景、詳細、ヒント、助言および補足説明:: 
* Locale names:: 
* Python 拡張の作者と、Python を埋め込むようなプログラムに関して:: 
* メッセージカタログへのアクセス:: 

@end menu

@node ロケールの背景、詳細、ヒント、助言および補足説明,Locale names,,locale --- 国際化サービス
@anchor{library/locale background-details-hints-tips-and-caveats}@anchor{42d3}
@subsubsection ロケールの背景、詳細、ヒント、助言および補足説明


C 標準では、ロケールはプログラム全体にわたる特性であり、その変更は高価な処理であるとしています。加えて、頻繁にロケールを変更するようなひどい実装はコアダンプを引き起こすこともあります。このことがロケールを正しく利用する上で苦痛となっています。

最初、プログラムが起動したときには、ユーザの希望するロケールにかかわらずロケールは @code{C} です。例外が1つあります: @ref{42c7,,LC_CTYPE} カテゴリは、現在のロケールエンコーディングをユーザーの希望するロケールエンコーディングに設定するために、スタートアップで変更されます。他のカテゴリについては、プログラムは @code{setlocale(LC_ALL, '@w{'})} を呼び出して、明示的にユーザの希望するロケール設定を行わなければなりません。

@ref{328,,setlocale()} をライブラリルーチン内で呼ぶことは、それがプログラム全体に及ぼす副作用の面から、一般的によくない考えです。ロケールを保存したり復帰したりするのもよくありません: 高価な処理であり、ロケールの設定が復帰する以前に起動してしまった他のスレッドに悪影響を及ぼすからです。

もし、汎用を目的としたモジュールを作っていて、ロケールによって影響をうけるような操作 (例えば @ref{1402,,time.strftime()} の書式の一部) のロケール独立のバージョンが必要ということになれば、標準ライブラリルーチンを使わずに何とかしなければなりません。よりましな方法は、ロケール設定が正しく利用できているか確かめることです。最後の手段は、あなたのモジュールが @code{C} ロケール以外の設定には互換性がないとドキュメントに書くことです。

The only way to perform numeric operations according to the locale is to use the
special functions defined by this module: @ref{42cf,,atof()}, @ref{42d0,,atoi()},
@ref{742,,format_string()}, @ref{42cd,,str()}.

ロケールに従ってケース変換や文字分類を行う方法はありません。 (ユニコード) テキスト文字列については、これらは文字の値のみによって行われます。その一方、バイト文字列はバイトの ASCII 値に従って変換と分類が行われます。そして、上位ビットが立っているバイト (すなわち、non-ASCII バイト) は、決して変換されず、英字や空白などの文字クラスの一部とみなされることもありません。

@node Locale names,Python 拡張の作者と、Python を埋め込むようなプログラムに関して,ロケールの背景、詳細、ヒント、助言および補足説明,locale --- 国際化サービス
@anchor{library/locale locale-name}@anchor{428d}@anchor{library/locale locale-names}@anchor{42d4}
@subsubsection Locale names


The format of the locale name is platform dependent, and the set of supported
locales can depend on the system configuration.

On Posix platforms, it usually has the format @footnote{
@uref{https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap08.html#tag_08_02,IEEE Std 1003.1-2024; 8.2 Internationalization Variables}
}:

@example
  language ["_" territory] ["." charset] ["@@" modifier]
@end example

where `language' is a two- or three-letter language code from ISO 639@footnote{https://www.iso.org/iso-639-language-code},
`territory' is a two-letter country or region code from ISO 3166@footnote{https://www.iso.org/iso-3166-country-codes.html},
`charset' is a locale encoding, and `modifier' is a script name,
a language subtag, a sort order identifier, or other locale modifier
(for example, "latin", "valencia", "stroke" and "euro").

On Windows, several formats are supported. @footnote{
@uref{https://learn.microsoft.com/en-us/cpp/c-runtime-library/locale-names-languages-and-country-region-strings,UCRT Locale names@comma{} Languages@comma{} and Country/Region strings}
} @footnote{
@uref{https://learn.microsoft.com/en-us/windows/win32/intl/locale-names,Locale Names}
}
A subset of IETF BCP 47@footnote{https://www.rfc-editor.org/info/bcp47} tags:

@example
  language ["-" script] ["-" territory] ["." charset]
  language ["-" script] "-" territory "-" modifier
@end example

where `language' and `territory' have the same meaning as in Posix,
`script' is a four-letter script code from ISO 15924@footnote{https://www.unicode.org/iso15924/},
and `modifier' is a language subtag, a sort order identifier
or custom modifier (for example, "valencia", "stroke" or "x-python").
Both hyphen (@code{'-'}) and underscore (@code{'_'}) separators are supported.
Only UTF-8 encoding is allowed for BCP 47 tags.

Windows also supports locale names in the format:

@example
  language ["_" territory] ["." charset]
@end example

where `language' and `territory' are full names, such as "English" and
"United States", and `charset' is either a code page number (for example, "1252")
or UTF-8.
Only the underscore separator is supported in this format.

The "C" locale is supported on all platforms.

@node Python 拡張の作者と、Python を埋め込むようなプログラムに関して,メッセージカタログへのアクセス,Locale names,locale --- 国際化サービス
@anchor{library/locale embedding-locale}@anchor{42d5}@anchor{library/locale for-extension-writers-and-programs-that-embed-python}@anchor{42d6}
@subsubsection Python 拡張の作者と、Python を埋め込むようなプログラムに関して


拡張モジュールは、現在のロケールを調べる以外は、決して @ref{328,,setlocale()} を呼び出してはなりません。しかし、返される値もロケールの復帰のために使えるだけなので、さほど便利とはいえません (例外はおそらくロケールが @code{C} かどうか調べることでしょう)。

When Python code uses the @code{locale} module to change the locale, this also
affects the embedding application.  If the embedding application doesn't want
this to happen, it should remove the @code{_locale} extension module (which does
all the work) from the table of built-in modules in the @code{config.c} file,
and make sure that the @code{_locale} module is not accessible as a shared
library.

@node メッセージカタログへのアクセス,,Python 拡張の作者と、Python を埋め込むようなプログラムに関して,locale --- 国際化サービス
@anchor{library/locale access-to-message-catalogs}@anchor{42d7}@anchor{library/locale locale-gettext}@anchor{42d8}
@subsubsection メッセージカタログへのアクセス


@geindex gettext() (locale モジュール)
@anchor{library/locale locale gettext}@anchor{42d9}
@deffn {の関数} locale.gettext (msg)
@end deffn

@geindex dgettext() (locale モジュール)
@anchor{library/locale locale dgettext}@anchor{42da}
@deffn {の関数} locale.dgettext (domain, msg)
@end deffn

@geindex dcgettext() (locale モジュール)
@anchor{library/locale locale dcgettext}@anchor{42db}
@deffn {の関数} locale.dcgettext (domain, msg, category)
@end deffn

@geindex textdomain() (locale モジュール)
@anchor{library/locale locale textdomain}@anchor{42dc}
@deffn {の関数} locale.textdomain (domain)
@end deffn

@geindex bindtextdomain() (locale モジュール)
@anchor{library/locale locale bindtextdomain}@anchor{42dd}
@deffn {の関数} locale.bindtextdomain (domain, dir)
@end deffn

@geindex bind_textdomain_codeset() (locale モジュール)
@anchor{library/locale locale bind_textdomain_codeset}@anchor{42de}
@deffn {の関数} locale.bind_textdomain_codeset (domain, codeset)
@end deffn

C ライブラリの gettext インタフェースが提供されているシステムでは、 locake モジュールでそのインタフェースを公開しています。このインタフェースは関数 @ref{67,,gettext()} 、 @ref{42da,,dgettext()} 、 @ref{42db,,dcgettext()} 、 @ref{42dc,,textdomain()} 、 @ref{42dd,,bindtextdomain()} 、および @ref{42de,,bind_textdomain_codeset()} からなります。これらは @ref{67,,gettext} モジュールの同名の関数に似ていますが、メッセージカタログとして C ライブラリのバイナリフォーマットを使い、メッセージカタログを探すために C ライブラリのサーチアルゴリズムを使います。

Python applications should normally find no need to invoke these functions, and
should use @ref{67,,gettext} instead.  A known exception to this rule are
applications that link with additional C libraries which internally invoke
C functions @code{gettext} or @code{dcgettext}.  For these applications, it may be
necessary to bind the text domain, so that the libraries can properly locate
their message catalogs.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Graphical user interfaces with Tk,開発ツール,国際化,Python 標準ライブラリ
@anchor{library/tk doc}@anchor{42df}@anchor{library/tk graphical-user-interfaces-with-tk}@anchor{42e0}@anchor{library/tk tkinter}@anchor{42e1}@anchor{library/tk translation-repo}@anchor{42e2}
@section Graphical user interfaces with Tk


@geindex GUI
@geindex グラフィカルユーザインターフェース
@geindex Tkinter
@geindex Tk

Tk/Tcl は長きにわたり Python の不可欠な一部でありつづけています。 Tk/Tcl は頑健でプラットホームに依存しないウィンドウ構築ツールキットであり、 Python プログラマは @ref{f6,,tkinter} パッケージやその拡張の @ref{ff,,tkinter.ttk} モジュールを使って利用できます。

@ref{f6,,tkinter} パッケージはオブジェクトの薄い層で作ったTcl/Tkの最上層です。@ref{f6,,tkinter} を使うには、Tcl のコードを書く必要はありませんが、Tk のドキュメント、またはときどき、Tcl のドキュメントを調べる
必要が出て来ます。@ref{f6,,tkinter} は Python クラスとして実装した Tk ウィジェットのラッパーの集合です。

@ref{f6,,tkinter} の一番素晴らしい点は、速く、そしてほとんどの Python に付属していることです。標準ドキュメントが頼りないものだとしても、代わりとなる、リファレンス、チュートリアル、書籍その他が入手可能です。@ref{f6,,tkinter} は古臭いルックアンドフィールでも有名ですが、その点は Tk 8.5 で大きく改善されました。とはいえ、他にも興味を引きそうな GUI ライブラリは多数あります。 Python wiki には、いくつかの代替の GUI フレームワークとツール@footnote{https://wiki.python.org/moin/GuiProgramming} の一覧があります。

@menu
* tkinter: tkinter --- Tcl/Tk の Python インターフェース. Tcl/Tk の Python インターフェース
* tkinter.colorchooser: tkinter colorchooser --- カラー選択ダイアログ. カラー選択ダイアログ
* tkinter.font: tkinter font --- Tkinter フォントラッパー. Tkinter フォントラッパー
* Tkinter ダイアログ:: 
* tkinter.messagebox: tkinter messagebox --- Tkinter メッセージプロンプト. Tkinter メッセージプロンプト
* tkinter.scrolledtext: tkinter scrolledtext --- スクロール可能なテキストウィジェット. スクロール可能なテキストウィジェット
* tkinter.dnd: tkinter dnd --- ドラッグアンドドロップのサポート. ドラッグアンドドロップのサポート
* tkinter.ttk: tkinter ttk --- Tk のテーマ付きウィジェット. Tk のテーマ付きウィジェット
* IDLE: IDLE --- Python のエディタとシェル<2>. Python のエディタとシェル
* turtle: turtle --- Turtle graphics. Turtle graphics

@end menu

@node tkinter --- Tcl/Tk の Python インターフェース,tkinter colorchooser --- カラー選択ダイアログ,,Graphical user interfaces with Tk
@anchor{library/tkinter doc}@anchor{42e3}@anchor{library/tkinter module-tkinter}@anchor{f6}@anchor{library/tkinter tkinter-python-interface-to-tcl-tk}@anchor{42e4}
@subsection @code{tkinter} --- Tcl/Tk の Python インターフェース


@geindex module; tkinter

`ソースコード:' Lib/tkinter/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/__init__.py}


__________________________________________________________________


The @code{tkinter} package ("Tk interface") is the standard Python interface to
the Tcl/Tk GUI toolkit.  Both Tk and @code{tkinter} are available on most Unix
platforms, including macOS, as well as on Windows systems.

Running @code{python -m tkinter} from the command line should open a window
demonstrating a simple Tk interface, letting you know that @code{tkinter} is
properly installed on your system, and also showing what version of Tcl/Tk is
installed, so you can read the Tcl/Tk documentation specific to that version.

Tkinter supports a range of Tcl/Tk versions, built either with or
without thread support. The official Python binary release bundles Tcl/Tk 8.6
threaded. See the source code for the @ref{3,,_tkinter} module
for more information about supported versions.

Tkinter is not a thin wrapper, but adds a fair amount of its own logic to
make the experience more pythonic. This documentation will concentrate on these
additions and changes, and refer to the official Tcl/Tk documentation for
details that are unchanged.

@cartouche
@quotation 注釈 
Tcl/Tk 8.5 (2007) introduced a modern set of themed user interface components
along with a new API to use them. Both old and new APIs are still available.
Most documentation you will find online still uses the old API and
can be woefully outdated.
@end quotation
@end cartouche

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile


@subsubheading 参考



@itemize *

@item 

@table @asis

@item TkDocs@footnote{https://tkdocs.com/}

Tkinterを使ったユーザインタフェースの作成に関する広範なチュートリアルです。主要な概念を説明し、最新のAPI を使用した推奨されるアプローチを説明します。
@end table

@item 

@table @asis

@item Tkinter 8.5 reference: a GUI for Python@footnote{https://www.tkdocs.com/shipman/}

参照: 利用可能なクラス、メソッド、オプションの詳細については、Tkinter 8.5のドキュメントを参照してください。
@end table
@end itemize

Tcl/Tk リソース:


@itemize *

@item 

@table @asis

@item Tk commands@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm}

Comprehensive reference to each of the underlying Tcl/Tk commands used by Tkinter.
@end table

@item 

@table @asis

@item Tcl/Tk ホームページ@footnote{https://www.tcl.tk}

Additional documentation, and links to Tcl/Tk core development.
@end table
@end itemize

Books:


@itemize *

@item 

@table @asis

@item Modern Tkinter for Busy Python Developers@footnote{https://tkdocs.com/book.html}

By Mark Roseman. (ISBN 978-1999149567)
@end table

@item 

@table @asis

@item Python GUI programming with Tkinter@footnote{https://www.packtpub.com/en-us/product/python-gui-programming-with-tkinter-9781788835886}

By Alan D. Moore. (ISBN 978-1788835886)
@end table

@item 

@table @asis

@item Programming Python@footnote{https://learning-python.com/about-pp4e.html}

By Mark Lutz; has excellent coverage of Tkinter. (ISBN 978-0596158101)
@end table

@item 

@table @asis

@item Tcl and the Tk Toolkit (2nd edition)@footnote{https://www.amazon.com/exec/obidos/ASIN/032133633X}

By John Ousterhout, inventor of Tcl/Tk, and Ken Jones; does not cover Tkinter. (ISBN 978-0321336330)
@end table
@end itemize


@menu
* Architecture:: 
* Tkinter モジュール:: 
* Tkinter お助け手帳:: 
* Threading model:: 
* 簡単なリファレンス:: 
* ファイルハンドラ:: 

@end menu

@node Architecture,Tkinter モジュール,,tkinter --- Tcl/Tk の Python インターフェース
@anchor{library/tkinter architecture}@anchor{42e5}
@subsubsection Architecture


Tcl/Tk is not a single library but rather consists of a few distinct
modules, each with separate functionality and its own official
documentation. Python's binary releases also ship an add-on module
together with it.


@table @asis

@item Tcl

Tcl is a dynamic interpreted programming language, just like Python. Though
it can be used on its own as a general-purpose programming language, it is
most commonly embedded into C applications as a scripting engine or an
interface to the Tk toolkit. The Tcl library has a C interface to
create and manage one or more instances of a Tcl interpreter, run Tcl
commands and scripts in those instances, and add custom commands
implemented in either Tcl or C. Each interpreter has an event queue,
and there are facilities to send events to it and process them.
Unlike Python, Tcl's execution model is designed around cooperative
multitasking, and Tkinter bridges this difference
(see @ref{42e6,,Threading model} for details).

@item Tk

Tk is a Tcl package@footnote{https://wiki.tcl-lang.org/37432} implemented in C
that adds custom commands to create and manipulate GUI widgets. Each
@ref{19ac,,Tk} object embeds its own Tcl interpreter instance with Tk loaded into
it. Tk's widgets are very customizable, though at the cost of a dated appearance.
Tk uses Tcl's event queue to generate and process GUI events.

@item Ttk

Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better
appearance on different platforms than many of the classic Tk widgets.
Ttk is distributed as part of Tk, starting with Tk version 8.5. Python
bindings are provided in a separate module, @ref{ff,,tkinter.ttk}.
@end table

Internally, Tk and Ttk use facilities of the underlying operating system,
i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.

When your Python application uses a class in Tkinter, e.g., to create a widget,
the @code{tkinter} module first assembles a Tcl/Tk command string. It passes that
Tcl command string to an internal @ref{3,,_tkinter} binary module, which then
calls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the
Tk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI.

@node Tkinter モジュール,Tkinter お助け手帳,Architecture,tkinter --- Tcl/Tk の Python インターフェース
@anchor{library/tkinter tkinter-modules}@anchor{42e7}
@subsubsection Tkinter モジュール


Support for Tkinter is spread across several modules. Most applications will need the
main @code{tkinter} module, as well as the @ref{ff,,tkinter.ttk} module, which provides
the modern themed widget set and API:

@example
from tkinter import *
from tkinter import ttk
@end example

@geindex Tk (tkinter のクラス)
@anchor{library/tkinter tkinter Tk}@anchor{19ac}
@deffn {クラス} tkinter.Tk (screenName=None, baseName=None, className='Tk', useTk=True, sync=False, use=None)

Construct a toplevel Tk widget, which is usually the main window of an
application, and initialize a Tcl interpreter for this widget.  Each
instance has its own associated Tcl interpreter.

The @ref{19ac,,Tk} class is typically instantiated using all default values.
However, the following keyword arguments are currently recognized:


@table @asis

@item `screenName'

When given (as a string), sets the 
@geindex DISPLAY
@geindex 環境変数; DISPLAY
@code{DISPLAY} environment
variable. (X11 only)

@item `baseName'

Name of the profile file.  By default, `baseName' is derived from the
program name (@code{sys.argv[0]}).

@item `className'

Name of the widget class.  Used as a profile file and also as the name
with which Tcl is invoked (`argv0' in `interp').

@item `useTk'

If @code{True}, initialize the Tk subsystem.  The @ref{42e8,,tkinter.Tcl()}
function sets this to @code{False}.

@item `sync'

If @code{True}, execute all X server commands synchronously, so that errors
are reported immediately.  Can be used for debugging. (X11 only)

@item `use'

Specifies the `id' of the window in which to embed the application,
instead of it being created as an independent toplevel window. `id' must
be specified in the same way as the value for the -use option for
toplevel widgets (that is, it has a form like that returned by
@code{winfo_id()}).

Note that on some platforms this will only work correctly if `id' refers
to a Tk frame or toplevel that has its -container option enabled.
@end table

@ref{19ac,,Tk} reads and interprets profile files, named
@code{.`className'.tcl} and @code{.`baseName'.tcl}, into the Tcl
interpreter and calls @ref{4a2,,exec()} on the contents of
@code{.`className'.py} and @code{.`baseName'.py}.  The path for the
profile files is the 
@geindex HOME
@geindex 環境変数; HOME
@code{HOME} environment variable or, if that
isn't defined, then @ref{2c57,,os.curdir}.

@geindex tk (tkinter.Tk の属性)
@anchor{library/tkinter tkinter Tk tk}@anchor{42e9}
@deffn {の属性} tk

The Tk application object created by instantiating @ref{19ac,,Tk}.  This
provides access to the Tcl interpreter.  Each widget that is attached
the same instance of @ref{19ac,,Tk} has the same value for its @ref{42e9,,tk}
attribute.
@end deffn

@geindex master (tkinter.Tk の属性)
@anchor{library/tkinter tkinter Tk master}@anchor{42ea}
@deffn {の属性} master

The widget object that contains this widget.  For @ref{19ac,,Tk}, the
@code{master} is @ref{885,,None} because it is the main window.  The terms
`master' and `parent' are similar and sometimes used interchangeably
as argument names; however, calling @code{winfo_parent()} returns a
string of the widget name whereas @code{master} returns the object.
`parent'/`child' reflects the tree-like relationship while
`master' (or `container')/`content' reflects the container structure.
@end deffn

@geindex children (tkinter.Tk の属性)
@anchor{library/tkinter tkinter Tk children}@anchor{42eb}
@deffn {の属性} children

The immediate descendants of this widget as a @ref{183,,dict} with the
child widget names as the keys and the child instance objects as the
values.
@end deffn
@end deffn

@geindex Tcl() (tkinter モジュール)
@anchor{library/tkinter tkinter Tcl}@anchor{42e8}
@deffn {の関数} tkinter.Tcl (screenName=None, baseName=None, className='Tk', useTk=False)

@ref{42e8,,Tcl()} はファクトリ関数で、 @ref{19ac,,Tk} クラスで生成するオブジェクトとよく似たオブジェクトを生成します。ただし Tk サブシステムを初期化しません。この関数は、余分なトップレベルウィンドウを作る必要がなかったり、 (X サーバを持たない Unix/Linux システムなどのように) 作成できない環境において Tcl インタプリタを駆動したい場合に便利です。 @ref{42e8,,Tcl()} で生成したオブジェクトに対して @code{loadtk()} メソッドを呼び出せば、トップレベルウィンドウを作成 (して、Tk サブシステムを初期化) します。
@end deffn

The modules that provide Tk support include:


@table @asis

@item @code{tkinter}

Main Tkinter module.

@item @ref{f7,,tkinter.colorchooser}

ユーザに色を選択させるためのダイアログです。

@item @ref{f8,,tkinter.commondialog}

このリストの他のモジュールが定義しているダイアログの基底クラスです。

@item @ref{fa,,tkinter.filedialog}

ユーザが開きたいファイルや保存したいファイルを指定できるようにする共通のダイアログです。

@item @ref{fb,,tkinter.font}

フォントの扱いを補助するためのユーティリティです。

@item @ref{fc,,tkinter.messagebox}

標準的な Tk のダイアログボックスにアクセスします。

@item @ref{fd,,tkinter.scrolledtext}

垂直スクロールバー付きのテキストウィジェットです。

@item @ref{fe,,tkinter.simpledialog}

基本的なダイアログと便宜関数 (convenience function) です。

@item @ref{ff,,tkinter.ttk}

Themed widget set introduced in Tk 8.5, providing modern alternatives
for many of the classic widgets in the main @code{tkinter} module.
@end table

Additional modules:

@geindex module; _tkinter
@anchor{library/tkinter module-_tkinter}@anchor{3}

@table @asis

@item @ref{3,,_tkinter}

A binary module that contains the low-level interface to Tcl/Tk.
It is automatically imported by the main @code{tkinter} 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.

@item @ref{77,,idlelib}

Python's Integrated Development and Learning Environment (IDLE). Based
on @code{tkinter}.

@item @code{tkinter.constants}

Symbolic constants that can be used in place of strings when passing
various parameters to Tkinter calls. Automatically imported by the
main @code{tkinter} module.

@item @ref{f9,,tkinter.dnd}

(experimental) Drag-and-drop support for @code{tkinter}. This will
become deprecated when it is replaced with the Tk DND.

@item @ref{107,,turtle}

Tk ウィンドウ上でタートルグラフィックスを実現します。
@end table

@node Tkinter お助け手帳,Threading model,Tkinter モジュール,tkinter --- Tcl/Tk の Python インターフェース
@anchor{library/tkinter tkinter-life-preserver}@anchor{42ec}
@subsubsection Tkinter お助け手帳


This section is not designed to be an exhaustive tutorial on either Tk or
Tkinter.  For that, refer to one of the external resources noted earlier.
Instead, this section provides a very quick orientation to what a Tkinter
application looks like, identifies foundational Tk concepts, and
explains how the Tkinter wrapper is structured.

The remainder of this section will help you to identify the classes,
methods, and options you'll need in your Tkinter application, and where to
find more detailed documentation on them, including in the official Tcl/Tk
reference manual.

@menu
* A Hello World Program:: 
* Important Tk Concepts:: 
* Understanding How Tkinter Wraps Tcl/Tk:: 
* How do I...? What option does...?: How do I ? What option does ?. 
* Navigating the Tcl/Tk Reference Manual:: 

@end menu

@node A Hello World Program,Important Tk Concepts,,Tkinter お助け手帳
@anchor{library/tkinter a-hello-world-program}@anchor{42ed}
@subsubsection A Hello World Program


We'll start by walking through a "Hello World" application in Tkinter. This
isn't the smallest one we could write, but has enough to illustrate some
key concepts you'll need to know.

@example
from tkinter import *
from tkinter import ttk
root = Tk()
frm = ttk.Frame(root, padding=10)
frm.grid()
ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
root.mainloop()
@end example

After the imports, the next line creates an instance of the @code{Tk} class,
which initializes Tk and creates its associated Tcl interpreter. It also
creates a toplevel window, known as the root window, which serves as the main
window of the application.

The following line creates a frame widget, which in this case will contain
a label and a button we'll create next. The frame is fit inside the root
window.

The next line creates a label widget holding a static text string. The
@code{grid()} method is used to specify the relative layout (position) of the
label within its containing frame widget, similar to how tables in HTML work.

A button widget is then created, and placed to the right of the label. When
pressed, it will call the @code{destroy()} method of the root window.

Finally, the @code{mainloop()} method puts everything on the display, and
responds to user input until the program terminates.

@node Important Tk Concepts,Understanding How Tkinter Wraps Tcl/Tk,A Hello World Program,Tkinter お助け手帳
@anchor{library/tkinter important-tk-concepts}@anchor{42ee}
@subsubsection Important Tk Concepts


Even this simple program illustrates the following key Tk concepts:


@table @asis

@item widgets

A Tkinter user interface is made up of individual `widgets'. Each widget is
represented as a Python object, instantiated from classes like
@code{ttk.Frame}, @code{ttk.Label}, and @code{ttk.Button}.

@item widget hierarchy

Widgets are arranged in a `hierarchy'. The label and button were contained
within a frame, which in turn was contained within the root window. When
creating each `child' widget, its `parent' widget is passed as the first
argument to the widget constructor.

@item configuration options

Widgets have `configuration options', which modify their appearance and
behavior, such as the text to display in a label or button. Different
classes of widgets will have different sets of options.

@item geometry management

Widgets aren't automatically added to the user interface when they are
created. A `geometry manager' like @code{grid} controls where in the
user interface they are placed.

@item event loop

Tkinter reacts to user input, changes from your program, and even refreshes
the display only when actively running an `event loop'. If your program
isn't running the event loop, your user interface won't update.
@end table

@node Understanding How Tkinter Wraps Tcl/Tk,How do I ? What option does ?,Important Tk Concepts,Tkinter お助け手帳
@anchor{library/tkinter understanding-how-tkinter-wraps-tcl-tk}@anchor{42ef}
@subsubsection Understanding How Tkinter Wraps Tcl/Tk


When your application uses Tkinter's classes and methods, internally Tkinter
is assembling strings representing Tcl/Tk commands, and executing those
commands in the Tcl interpreter attached to your application's @code{Tk}
instance.

Whether it's trying to navigate reference documentation, trying to find
the right method or option, adapting some existing code, or debugging your
Tkinter application, there are times that it will be useful to understand
what those underlying Tcl/Tk commands look like.

To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter
script above.

@example
ttk::frame .frm -padding 10
grid .frm
grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0
grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0
@end example

Tcl's syntax is similar to many shell languages, where the first word is the
command to be executed, with arguments to that command following it, separated
by spaces. Without getting into too many details, notice the following:


@itemize *

@item 
The commands used to create widgets (like @code{ttk::frame}) correspond to
widget classes in Tkinter.

@item 
Tcl widget options (like @code{-text}) correspond to keyword arguments in
Tkinter.

@item 
Widgets are referred to by a `pathname' in Tcl (like @code{.frm.btn}),
whereas Tkinter doesn't use names but object references.

@item 
A widget's place in the widget hierarchy is encoded in its (hierarchical)
pathname, which uses a @code{.} (dot) as a path separator. The pathname for
the root window is just @code{.} (dot). In Tkinter, the hierarchy is defined
not by pathname but by specifying the parent widget when creating each
child widget.

@item 
Operations which are implemented as separate `commands' in Tcl (like
@code{grid} or @code{destroy}) are represented as `methods' on Tkinter widget
objects. As you'll see shortly, at other times Tcl uses what appear to be
method calls on widget objects, which more closely mirror what is
used in Tkinter.
@end itemize

@node How do I ? What option does ?,Navigating the Tcl/Tk Reference Manual,Understanding How Tkinter Wraps Tcl/Tk,Tkinter お助け手帳
@anchor{library/tkinter how-do-i-what-option-does}@anchor{42f0}
@subsubsection How do I...? What option does...?


If you're not sure how to do something in Tkinter, and you can't immediately
find it in the tutorial or reference documentation you're using, there are a
few strategies that can be helpful.

First, remember that the details of how individual widgets work may vary
across different versions of both Tkinter and Tcl/Tk. If you're searching
documentation, make sure it corresponds to the Python and Tcl/Tk versions
installed on your system.

When searching for how to use an API, it helps to know the exact name of the
class, option, or method that you're using. Introspection, either in an
interactive Python shell or with @ref{1177,,print()}, can help you identify what
you need.

To find out what configuration options are available on any widget, call its
@code{configure()} method, which returns a dictionary containing a variety of
information about each object, including its default and current values. Use
@code{keys()} to get just the names of each option.

@example
btn = ttk.Button(frm, ...)
print(btn.configure().keys())
@end example

As most widgets have many configuration options in common, it can be useful
to find out which are specific to a particular widget class. Comparing the
list of options to that of a simpler widget, like a frame, is one way to
do that.

@example
print(set(btn.configure().keys()) - set(frm.configure().keys()))
@end example

Similarly, you can find the available methods for a widget object using the
standard @ref{844,,dir()} function. If you try it, you'll see there are over 200
common widget methods, so again identifying those specific to a widget class
is helpful.

@example
print(dir(btn))
print(set(dir(btn)) - set(dir(frm)))
@end example

@node Navigating the Tcl/Tk Reference Manual,,How do I ? What option does ?,Tkinter お助け手帳
@anchor{library/tkinter navigating-the-tcl-tk-reference-manual}@anchor{42f1}
@subsubsection Navigating the Tcl/Tk Reference Manual


As noted, the official Tk commands@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm}
reference manual (man pages) is often the most accurate description of what
specific operations on widgets do. Even when you know the name of the option
or method that you need, you may still have a few places to look.

While all operations in Tkinter are implemented as method calls on widget
objects, you've seen that many Tcl/Tk operations appear as commands that
take a widget pathname as its first parameter, followed by optional
parameters, e.g.

@example
destroy .
grid .frm.btn -column 0 -row 0
@end example

Others, however, look more like methods called on a widget object (in fact,
when you create a widget in Tcl/Tk, it creates a Tcl command with the name
of the widget pathname, with the first parameter to that command being the
name of a method to call).

@example
.frm.btn invoke
.frm.lbl configure -text "Goodbye"
@end example

In the official Tcl/Tk reference documentation, you'll find most operations
that look like method calls on the man page for a specific widget (e.g.,
you'll find the @code{invoke()} method on the
ttk::button@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_button.htm}
man page), while functions that take a widget as a parameter often have
their own man page (e.g.,
grid@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/grid.htm}).

You'll find many common options and methods in the
options@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/options.htm} or
ttk::widget@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_widget.htm} man
pages, while others are found in the man page for a specific widget class.

You'll also find that many Tkinter methods have compound names, e.g.,
@code{winfo_x()}, @code{winfo_height()}, @code{winfo_viewable()}. You'd find
documentation for all of these in the
winfo@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/winfo.htm} man page.

@cartouche
@quotation 注釈 
Somewhat confusingly, there are also methods on all Tkinter widgets
that don't actually operate on the widget, but operate at a global
scope, independent of any widget. Examples are methods for accessing
the clipboard or the system bell. (They happen to be implemented as
methods in the base @code{Widget} class that all Tkinter widgets
inherit from).
@end quotation
@end cartouche

@node Threading model,簡単なリファレンス,Tkinter お助け手帳,tkinter --- Tcl/Tk の Python インターフェース
@anchor{library/tkinter threading-model}@anchor{42e6}
@subsubsection Threading model


Python and Tcl/Tk have very different threading models, which @code{tkinter}
tries to bridge. If you use threads, you may need to be aware of this.

A Python interpreter may have many threads associated with it. In Tcl, multiple
threads can be created, but each thread has a separate Tcl interpreter instance
associated with it. Threads can also create more than one interpreter instance,
though each interpreter instance can be used only by the one thread that created it.

Each @code{Tk} object created by @code{tkinter} contains a Tcl interpreter.
It also keeps track of which thread created that interpreter. Calls to
@code{tkinter} can be made from any Python thread. Internally, if a call comes
from a thread other than the one that created the @code{Tk} object, an event
is posted to the interpreter's event queue, and when executed, the result is
returned to the calling Python thread.

Tcl/Tk applications are normally event-driven, meaning that after initialization,
the interpreter runs an event loop (i.e. @code{Tk.mainloop()}) and responds to events.
Because it is single-threaded, event handlers must respond quickly, otherwise they
will block other events from being processed. To avoid this, any long-running
computations should not run in an event handler, but are either broken into smaller
pieces using timers, or run in another thread. This is different from many GUI
toolkits where the GUI runs in a completely separate thread from all application
code including event handlers.

If the Tcl interpreter is not running the event loop and processing events, any
@code{tkinter} calls made from threads other than the one running the Tcl
interpreter will fail.

A number of special cases exist:


@itemize *

@item 
Tcl/Tk libraries can be built so they are not thread-aware. In this case,
@code{tkinter} calls the library from the originating Python thread, even
if this is different than the thread that created the Tcl interpreter. A global
lock ensures only one call occurs at a time.

@item 
While @code{tkinter} allows you to create more than one instance of a @code{Tk}
object (with its own interpreter), all interpreters that are part of the same
thread share a common event queue, which gets ugly fast. In practice, don't create
more than one instance of @code{Tk} at a time. Otherwise, it's best to create
them in separate threads and ensure you're running a thread-aware Tcl/Tk build.

@item 
Blocking event handlers are not the only way to prevent the Tcl interpreter from
reentering the event loop. It is even possible to run multiple nested event loops
or abandon the event loop entirely. If you're doing anything tricky when it comes
to events or threads, be aware of these possibilities.

@item 
There are a few select @code{tkinter} functions that presently work only when
called from the thread that created the Tcl interpreter.
@end itemize

@node 簡単なリファレンス,ファイルハンドラ,Threading model,tkinter --- Tcl/Tk の Python インターフェース
@anchor{library/tkinter handy-reference}@anchor{42f2}
@subsubsection 簡単なリファレンス


@menu
* オプションの設定:: 
* Packer:: 
* Packer のオプション:: 
* ウィジェット変数を関連付ける:: 
* ウィンドウマネージャ:: 
* Tk オプションデータ型:: 
* バインドとイベント:: 
* index パラメータ:: 
* 画像:: 

@end menu

@node オプションの設定,Packer,,簡単なリファレンス
@anchor{library/tkinter setting-options}@anchor{42f3}@anchor{library/tkinter tkinter-setting-options}@anchor{42f4}
@subsubsection オプションの設定


オプションは、色やウィジェットの境界線幅などを制御します。オプションの設定には三通りの方法があります:


@table @asis

@item オブジェクト生成時、キーワード引数を使用する

@example
fred = Button(self, fg="red", bg="blue")
@end example

@item オブジェクト生成後、オプション名を辞書インデックスのように扱う

@example
fred["fg"] = "red"
fred["bg"] = "blue"
@end example

@item オブジェクト生成後に、config()メソッドを使って複数の属性を更新する

@example
fred.config(fg="red", bg="blue")
@end example
@end table

オプションとその振る舞いに関する詳細な説明は、該当するウィジェットの Tk の man ページを参照してください。

man ページには、各ウィジェットの "STANDARD OPTIONS (標準オプション)" と "WIDGET SPECIFIC OPTIONS (ウィジェット固有のオプション)" がリストされていることに注意してください。前者は多くのウィジェットに共通のオプションのリストで、後者は特定のウィジェットに特有のオプションです。標準オプションの説明は man ページの @code{options(3)@footnote{https://manpages.debian.org/options(3)}} にあります。

このドキュメントでは、標準オプションとウィジェット固有のオプションを区別していません。オプションによっては、ある種のウィジェットに適用できません。あるウィジェットがあるオプションに対応しているかどうかは、ウィジェットのクラスによります。例えばボタンには @code{command} オプションがありますが、ラベルにはありません。

あるウィジェットがどんなオプションをサポートしているかは、ウィジェットの man ページにリストされています。また、実行時にウィジェットの @code{config()} メソッドを引数なしで呼び出したり、 @code{keys()} メソッドを呼び出したりして問い合わせることもできます。メソッド呼び出しを行うと辞書型の値を返します。この辞書は、オプションの名前がキー (例えば @code{'relief'}) になっていて、値が 5 要素のタプルになっています。

@code{bg} のように、いくつかのオプションはより長い名前を持つ共通のオプションに対する同義語になっています (@code{bg} は "background" を短縮したものです)。短縮形のオプション名を @code{config()} に渡すと、 5 要素ではなく 2 要素のタプルを返します。このタプルには、同義語の名前と「本当の」オプション名が入っています (例えば @code{('bg', 'background')})。


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

意味

@tab

使用例

@item

0

@tab

オプション名

@tab

@code{'relief'}

@item

1

@tab

データベース検索用のオプション名

@tab

@code{'relief'}

@item

2

@tab

データベース検索用のオプションクラス

@tab

@code{'Relief'}

@item

3

@tab

デフォルト値

@tab

@code{'raised'}

@item

4

@tab

現在の値

@tab

@code{'groove'}

@end multitable


以下はプログラム例です:

@example
>>> print(fred.config())
@{'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')@}
@end example

もちろん、実際に出力される辞書には利用可能なオプションが全て表示されます。上の表示例は単なる例にすぎません。

@node Packer,Packer のオプション,オプションの設定,簡単なリファレンス
@anchor{library/tkinter the-packer}@anchor{42f5}
@subsubsection Packer


@geindex packing (widgets)

The packer is one of Tk's geometry-management mechanisms.    Geometry managers
are used to specify the relative positioning of widgets within their container.
In contrast to the more cumbersome `placer' (which is
used less commonly, and we do not cover here), the packer takes qualitative
relationship specification - `above', `to the left of', `filling', etc - and
works everything out to determine the exact placement coordinates for you.

The size of any container widget is determined by the size of the "content widgets"
inside.  The packer is used to control where content widgets appear inside the
container into which they are packed.  You can pack widgets into frames, and frames
into other frames, in order to achieve the kind of layout you desire.
Additionally, the arrangement is dynamically adjusted to accommodate incremental
changes to the configuration, once it is packed.

ジオメトリマネージャがウィジェットのジオメトリを確定するまで、ウィジェットは表示されないので注意してください。初心者のころにはよくジオメトリの確定を忘れてしまい、ウィジェットを生成したのに何も表示されず驚くことになります。ウィジェットは、(例えば packer の @code{pack()} メソッドを適用して) ジオメトリを確定した後で初めて表示されます。

pack() メソッドは、キーワード引数つきで呼び出せます。キーワード引数は、ウィジェットをコンテナ内のどこに表示するか、メインのアプリケーションウィンドウをリサイズしたときにウィジェットがどう振舞うかを制御します。以下に例を示します:

@example
fred.pack()                     # defaults to side = "top"
fred.pack(side="left")
fred.pack(expand=1)
@end example

@node Packer のオプション,ウィジェット変数を関連付ける,Packer,簡単なリファレンス
@anchor{library/tkinter packer-options}@anchor{42f6}
@subsubsection Packer のオプション


packer と packer の取りえるオプションについての詳細は、man ページや John Ousterhout の本の183ページを参照してください。


@table @asis

@item anchor

Anchor type.  Denotes where the packer is to place each content in its parcel.

@item expand

ブール値で、 @code{0} または @code{1} になります。

@item fill

指定できる値は @code{'x'} 、 @code{'y'} 、 @code{'both'} 、 @code{'none'} です。

@item ipadx および ipady

A distance - designating internal padding on each side of the content.

@item padx および pady

A distance - designating external padding on each side of the content.

@item side

指定できる値は @code{'left'}, @code{'right'}, @code{'top'}, @code{'bottom'} です。
@end table

@node ウィジェット変数を関連付ける,ウィンドウマネージャ,Packer のオプション,簡単なリファレンス
@anchor{library/tkinter coupling-widget-variables}@anchor{42f7}
@subsubsection ウィジェット変数を関連付ける


ウィジェットによっては、(テキスト入力ウィジェットのように) 特殊なオプションを使って、現在設定されている値をアプリケーション内の変数に直接関連付けできます。このようなオプションには @code{variable}, @code{textvariable}, @code{onvalue}, @code{offvalue} および @code{value} があります。この関連付けは双方向に働きます: 変数の値が何らかの理由で変更されると、関連付けされているウィジェットも更新され、新しい値を反映します。

Unfortunately, in the current implementation of @code{tkinter} it is not
possible to hand over an arbitrary Python variable to a widget through a
@code{variable} or @code{textvariable} option.  The only kinds of variables for which
this works are variables that are subclassed from a class called Variable,
defined in @code{tkinter}.

Variable には、 @code{StringVar}, @code{IntVar}, @code{DoubleVar}, @code{BooleanVar} といった便利なサブクラスがすでにすでに数多く定義されています。こうした変数の現在の値を読み出したければ、 @code{get()} メソッドを呼び出します。また、値を変更したければ @code{set()} メソッドを呼び出します。このプロトコルに従っている限り、それ以上なにも手を加えなくてもウィジェットは常に現在値に追従します。

例えば:

@example
import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.pack()

        self.entrythingy = tk.Entry()
        self.entrythingy.pack()

        # Create the application variable.
        self.contents = tk.StringVar()
        # Set it to some value.
        self.contents.set("this is a variable")
        # Tell the entry widget to watch this variable.
        self.entrythingy["textvariable"] = self.contents

        # Define a callback for when the user hits return.
        # It prints the current value of the variable.
        self.entrythingy.bind('<Key-Return>',
                             self.print_contents)

    def print_contents(self, event):
        print("Hi. The current entry content is:",
              self.contents.get())

root = tk.Tk()
myapp = App(root)
myapp.mainloop()
@end example

@node ウィンドウマネージャ,Tk オプションデータ型,ウィジェット変数を関連付ける,簡単なリファレンス
@anchor{library/tkinter the-window-manager}@anchor{42f8}
@subsubsection ウィンドウマネージャ


@geindex window manager (widgets)

In Tk, there is a utility command, @code{wm}, for interacting with the window
manager.  Options to the @code{wm} command allow you to control things like titles,
placement, icon bitmaps, and the like.  In @code{tkinter}, these commands have
been implemented as methods on the @code{Wm} class.  Toplevel widgets are
subclassed from the @code{Wm} class, and so can call the @code{Wm} methods
directly.

To get at the toplevel window that contains a given widget, you can often just
refer to the widget's @code{master}.  Of course if the widget has been packed inside of
a frame, the @code{master} won't represent a toplevel window.  To get at the toplevel
window that contains an arbitrary widget, you can call the @code{_root()} method.
This method begins with an underscore to denote the fact that this function is
part of the implementation, and not an interface to Tk functionality.

以下に典型的な使い方の例をいくつか挙げます:

@example
import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

# create the application
myapp = App()

#
# here are method calls to the window manager class
#
myapp.master.title("My Do-Nothing Application")
myapp.master.maxsize(1000, 400)

# start the program
myapp.mainloop()
@end example

@node Tk オプションデータ型,バインドとイベント,ウィンドウマネージャ,簡単なリファレンス
@anchor{library/tkinter tk-option-data-types}@anchor{42f9}
@subsubsection Tk オプションデータ型


@geindex Tk オプションデータ型


@table @asis

@item anchor

指定できる値はコンパスの方位です: @code{"n"} 、 @code{"ne"} 、 @code{"e"} 、 @code{"se"} 、 @code{"s"} 、 @code{"sw"} 、 @code{"w"} 、 @code{"nw"} 、および @code{"center"} 。

@item bitmap

八つの組み込み、名前付きビットマップ: @code{'error'} 、 @code{'gray25'} 、 @code{'gray50'} 、 @code{'hourglass'} 、 @code{'info'} 、 @code{'questhead'} 、 @code{'question'} 、 @code{'warning'} 。 X ビットマップファイル名を指定するために、 @code{"@@/usr/contrib/bitmap/gumby.bit"} のような @code{@@} を先頭に付けたファイルへの完全なパスを与えてください。

@item boolean

整数 0 または 1 、あるいは、文字列 @code{"yes"} または @code{"no"} を渡すことができます。

@item callback

これは引数を取らない Python 関数ならどれでも構いません。例えば:

@example
def print_it():
    print("hi there")
fred["command"] = print_it
@end example

@item color

Colors can be given as the names of X colors in the rgb.txt file, or as strings
representing RGB values in 4 bit: @code{"#RGB"}, 8 bit: @code{"#RRGGBB"}, 12 bit:
@code{"#RRRGGGBBB"}, or 16 bit: @code{"#RRRRGGGGBBBB"} ranges, where R,G,B here
represent any legal hex digit.  See page 160 of Ousterhout's book for details.

@item cursor

@code{cursorfont.h} の標準Xカーソル名を、接頭語 @code{XC_} 無しで使うことができます。例えば、handカーソル(@code{XC_hand2})を得るには、文字列 @code{"hand2"} を使ってください。あなた自身のビットマップとマスクファイルを指定することもできます。 Ousterhout の本の179ページを参照してください。

@item distance

スクリーン上の距離をピクセルか絶対距離のどちらかで指定できます。ピクセルは数値として与えられ、絶対距離は文字列として与えられます。絶対距離を表す文字列は、単位を表す終了文字 (センチメートルには @code{c} 、インチには @code{i} 、ミリメートルには @code{m} 、プリンタのポイントには @code{p})を伴います。例えば、3.5インチは @code{"3.5i"} と表現します。

@item font

Tkはフォント名の形式に @code{@{courier 10 bold@}} のようなリストを使います。正の数のフォントサイズはポイント単位で使用され、負の数のサイズはピクセル単位と見なされます。

@item geometry

これは @code{widthxheight} 形式の文字列です。ここでは、ほとんどのウィジェットに対して幅と高さピクセル単位で (テキストを表示するウィジェットに対しては文字単位で)表されます。例えば: @code{fred["geometry"] = "200x100"} 。

@item justify

Legal values are the strings: @code{"left"}, @code{"center"}, and @code{"right"}.

@item region

これは空白で区切られた四つの要素をもつ文字列です。各要素は指定可能な距離です(以下を参照)。例えば: @code{"2 3 4 5"} と @code{"3i 2i 4.5i 2i"} と @code{"3c 2c 4c 10.43c"} は、すべて指定可能な範囲です。

@item relief

ウィジェットのボーダのスタイルが何かを決めます。指定できる値は: @code{"raised"} 、 @code{"sunken"} 、 @code{"flat"} 、 @code{"groove"} 、と @code{"ridge"} 。

@item scrollcommand

これはほとんどの場合スクロールバーウィジェットの @code{set()} メソッドですが、1 個の引数を取るあらゆるウィジェットにもなりえます。

@item wrap

次の中の一つでなければなりません: @code{"none"} 、 @code{"char"} 、あるいは @code{"word"} 。
@end table

@node バインドとイベント,index パラメータ,Tk オプションデータ型,簡単なリファレンス
@anchor{library/tkinter bindings-and-events}@anchor{42fa}@anchor{library/tkinter id2}@anchor{42fb}
@subsubsection バインドとイベント


@geindex bind (widgets)
@geindex events (widgets)

ウィジェットコマンドからの bind メソッドによって、あるイベントを待つことと、そのイベント型が起きたときにコールバック関数を呼び出すことができるようになります。 bind メソッドの形式は:

@example
def bind(self, sequence, func, add='@w{'}):
@end example

ここでは:


@table @asis

@item sequence

is a string that denotes the target kind of event.  (See the
@code{bind(3tk)@footnote{https://manpages.debian.org/bind(3tk)}} man page, and page 201 of John Ousterhout's book,
@cite{Tcl and the Tk Toolkit (2nd edition)}, for details).

@item func

は一引数を取り、イベントが起きるときに呼び出される Python 関数です。イベント・インスタンスが引数として渡されます。 (このように実施される関数は、一般に `callbacks' として知られています。)

@item add

はオプションで、 @code{'@w{'}} か @code{'+'} のどちらかです。空文字列を渡すことは、このイベントが関係する他のどんなバインドをもこのバインドが置き換えることを意味します。 @code{'+'} を使う仕方は、この関数がこのイベント型にバインドされる関数のリストに追加されることを意味しています。
@end table

例えば:

@example
def turn_red(self, event):
    event.widget["activeforeground"] = "red"

self.button.bind("<Enter>", self.turn_red)
@end example

イベントのウィジェットフィールドが @code{turn_red()} コールバック内でどのようにアクセスされているかに注目してください。このフィールドは X イベントを捕らえたウィジェットを含んでいます。以下の表はアクセスできる他のイベントフィールドとそれらの Tk での表現方法の一覧です。Tk man ページを参照するときに役に立つでしょう。


@multitable {xxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Tk

@tab

Tkinter イベントフィールド

@tab

Tk

@tab

Tkinter イベントフィールド

@item

%f

@tab

focus

@tab

%A

@tab

char

@item

%h

@tab

高さ

@tab

%E

@tab

send_event

@item

%k

@tab

keycode

@tab

%K

@tab

keysym

@item

%s

@tab

state

@tab

%N

@tab

keysym_num

@item

%t

@tab

time

@tab

%T

@tab

type

@item

%w

@tab

幅

@tab

%W

@tab

widget

@item

%x

@tab

x

@tab

%X

@tab

x_root

@item

%y

@tab

y

@tab

%Y

@tab

y_root

@end multitable


@node index パラメータ,画像,バインドとイベント,簡単なリファレンス
@anchor{library/tkinter the-index-parameter}@anchor{42fc}
@subsubsection index パラメータ


多くのウィジェットにはパラメータ "index" を渡す必要があります。これらはテキストウィジェット内の特定の位置や、エントリウィジェット内の特定の文字、あるいはメニューウィジェット内の特定のメニューアイテムを指定するために使用されます。


@table @asis

@item エントリウィジェットのインデックス(インデックス、ビューインデックスなど)

Entry widgets have options that refer to character positions in the text being
displayed.  You can use these @code{tkinter} functions to access these special
points in text widgets:

@item テキストウィジェットのインデックス

テキストウィジェットに対するインデックス記法はとても機能が豊富で、 Tk manページでよく説明されています。

@item メニューのインデックス(menu.invoke()、menu.entryconfig()など)

メニューに対するいくつかのオプションとメソッドは特定のメニュー項目を操作します。メニューインデックスはオプションまたはパラメータのために必要とされるときはいつでも、以下のものを渡すことができます:


@itemize *

@item 
ウィジェット内の数字の先頭からの位置を指す整数。先頭は 0。

@item 
文字列 @code{"active"}。現在カーソルがあるメニューの位置を指します。

@item 
文字列 @code{"last"} 。最後のメニューを指します。

@item 
@code{@@6} のような @code{@@} が前に来る整数。ここでは、整数がメニューの座標系における y ピクセル座標として解釈されます。

@item 
文字列 @code{"none"}。どんなメニューエントリもまったく指しておらず、ほとんどの場合、すべてのエントリの動作を停止させるために menu.activate() と一緒に使われます。そして、最後に、

@item 
メニューの先頭から一番下までスキャンしたときに、メニューエントリのラベルに一致したパターンであるテキスト文字列。このインデックス型は他すべての後に考慮されることに注意してください。その代わりに、それは @code{last} 、 @code{active} または @code{none} とラベル付けされたメニュー項目への一致は上のリテラルとして解釈されることを意味します。
@end itemize
@end table

@node 画像,,index パラメータ,簡単なリファレンス
@anchor{library/tkinter images}@anchor{42fd}
@subsubsection 画像


様々な形式の画像を、それに対応する @code{tkinter.Image} のサブクラスを使って作成できます:


@itemize *

@item 
XBM 形式の画像のための @code{BitmapImage} 。

@item 
PGM, PPM, GIF, PNG 形式の画像のための @code{PhotoImage} 。
最後のは Tk 8.6 からサポートされるようになりました。
@end itemize

画像のどちらの型でも @code{file} または @code{data} オプションを使って作られます (その上、他のオプションも利用できます)。


バージョン 3.13 で変更: Added the @code{PhotoImage} method @code{copy_replace()} to copy a region
from one image to other image, possibly with pixel zooming and/or
subsampling.
Add `from_coords' parameter to @code{PhotoImage} methods @code{copy()},
@code{zoom()} and @code{subsample()}.
Add `zoom' and `subsample' parameters to @code{PhotoImage} method
@code{copy()}.


@code{image} オプションがウィジェットにサポートされるところならどこでも、画像オブジェクトを使うことができます (例えば、ラベル、ボタン、メニュー)。これらの場合では、Tk は画像への参照を保持しないでしょう。画像オブジェクトへの最後の Python の参照が削除されたときに、画像データも削除されます。そして、どこで画像が使われていようとも、Tk は空の箱を表示します。


@subsubheading 参考


The Pillow@footnote{https://python-pillow.org/} package adds support for
formats such as BMP, JPEG, TIFF, and WebP, among others.


@node ファイルハンドラ,,簡単なリファレンス,tkinter --- Tcl/Tk の Python インターフェース
@anchor{library/tkinter file-handlers}@anchor{42fe}@anchor{library/tkinter tkinter-file-handlers}@anchor{42ff}
@subsubsection ファイルハンドラ


Tk を使うとコールバック関数の登録や解除ができ、ファイルディスクリプタに対する入出力が可能なときに、Tk のメインループからその関数が呼ばれます。
ファイルディスクリプタ1つにつき、1つだけハンドラは登録されます。コード例です:

@example
import tkinter
widget = tkinter.Tk()
mask = tkinter.READABLE | tkinter.WRITABLE
widget.tk.createfilehandler(file, mask, callback)
...
widget.tk.deletefilehandler(file)
@end example

これらの機能は Windows では利用できません。

読み込みに使えるバイト数は分からないので、 @ref{8a3,,BufferedIOBase} クラスや @ref{8a4,,TextIOBase} クラスの @ref{1540,,read()} メソッドおよび @ref{1541,,readline()} メソッドを使おうとしないでください。これらは読み込みの際に、あらかじめ決められたバイト数を要求するのです。ソケットには、 @ref{fa4,,recv()} や @ref{fa5,,recvfrom()} メソッドを使うといいです。その他のファイルには、 raw 読み込みか @code{os.read(file.fileno(), maxbytecount)} を使ってください。

@geindex createfilehandler() (_tkinter.Widget.tk のメソッド)
@anchor{library/tkinter tkinter Widget tk createfilehandler}@anchor{4300}
@deffn {メソッド} Widget.tk.createfilehandler (file, mask, func)

ファイルハンドラであるコールバック関数 `func' を登録します。 `file' 引数は、 (ファイルやソケットオブジェクトのような) @ref{17ad,,fileno()} メソッドを持つオブジェクトか、整数のファイルディスクリプタとなります。 `mask' 引数は、以下にある3つの定数の組み合わせの OR を取ったものです。コールバックは次のように呼ばれます:

@example
callback(file, mask)
@end example
@end deffn

@geindex deletefilehandler() (_tkinter.Widget.tk のメソッド)
@anchor{library/tkinter tkinter Widget tk deletefilehandler}@anchor{4301}
@deffn {メソッド} Widget.tk.deletefilehandler (file)

ファイルハンドラの登録を解除します。
@end deffn

@geindex READABLE (_tkinter モジュール)
@geindex WRITABLE (_tkinter モジュール)
@geindex EXCEPTION (_tkinter モジュール)
@anchor{library/tkinter tkinter READABLE}@anchor{4302}
@deffn {データ} _tkinter.READABLE
@anchor{library/tkinter tkinter WRITABLE}@anchor{4303}
@deffnx {データ} _tkinter.WRITABLE
@anchor{library/tkinter tkinter EXCEPTION}@anchor{4304}
@deffnx {データ} _tkinter.EXCEPTION

`mask' 引数で使う定数です。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tkinter colorchooser --- カラー選択ダイアログ,tkinter font --- Tkinter フォントラッパー,tkinter --- Tcl/Tk の Python インターフェース,Graphical user interfaces with Tk
@anchor{library/tkinter colorchooser doc}@anchor{4305}@anchor{library/tkinter colorchooser module-tkinter colorchooser}@anchor{f7}@anchor{library/tkinter colorchooser tkinter-colorchooser-color-choosing-dialog}@anchor{4306}@anchor{library/tkinter colorchooser translation-repo}@anchor{4307}
@subsection @code{tkinter.colorchooser} --- カラー選択ダイアログ


@geindex module; tkinter.colorchooser

`ソースコード:' Lib/tkinter/colorchooser.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/colorchooser.py}


__________________________________________________________________


The @code{tkinter.colorchooser} module provides the @ref{4308,,Chooser} class
as an interface to the native color picker dialog. @code{Chooser} implements
a modal color choosing dialog window. The @code{Chooser} class inherits from
the @ref{4309,,Dialog} class.

@geindex Chooser (tkinter.colorchooser のクラス)
@anchor{library/tkinter colorchooser tkinter colorchooser Chooser}@anchor{4308}
@deffn {クラス} tkinter.colorchooser.Chooser (master=None, **options)
@end deffn

@geindex askcolor() (tkinter.colorchooser モジュール)
@anchor{library/tkinter colorchooser tkinter colorchooser askcolor}@anchor{430a}
@deffn {の関数} tkinter.colorchooser.askcolor (color=None, **options)

カラー選択ダイアログを作成します。このメソッドを呼び出すと、ウィンドウが表示されユーザーが選択するのを待ち、選択された色（もしくは @code{None} ）を呼び出し元に返します。
@end deffn


@subsubheading 参考



@table @asis

@item モジュール @ref{f8,,tkinter.commondialog}

Tkinter標準ダイアログモジュール
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tkinter font --- Tkinter フォントラッパー,Tkinter ダイアログ,tkinter colorchooser --- カラー選択ダイアログ,Graphical user interfaces with Tk
@anchor{library/tkinter font doc}@anchor{430b}@anchor{library/tkinter font module-tkinter font}@anchor{fb}@anchor{library/tkinter font tkinter-font-tkinter-font-wrapper}@anchor{430c}@anchor{library/tkinter font translation-repo}@anchor{430d}
@subsection @code{tkinter.font} --- Tkinter フォントラッパー


@geindex module; tkinter.font

`ソースコード:' Lib/tkinter/font.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/font.py}


__________________________________________________________________


The @code{tkinter.font} module provides the @ref{1cce,,Font} class for creating
and using named fonts.

The different font weights and slants are:

@geindex NORMAL (tkinter.font モジュール)
@geindex BOLD (tkinter.font モジュール)
@geindex ITALIC (tkinter.font モジュール)
@geindex ROMAN (tkinter.font モジュール)
@anchor{library/tkinter font tkinter font NORMAL}@anchor{430e}
@deffn {データ} tkinter.font.NORMAL
@anchor{library/tkinter font tkinter font BOLD}@anchor{430f}
@deffnx {データ} tkinter.font.BOLD
@anchor{library/tkinter font tkinter font ITALIC}@anchor{4310}
@deffnx {データ} tkinter.font.ITALIC
@anchor{library/tkinter font tkinter font ROMAN}@anchor{4311}
@deffnx {データ} tkinter.font.ROMAN
@end deffn

@geindex Font (tkinter.font のクラス)
@anchor{library/tkinter font tkinter font Font}@anchor{1cce}
@deffn {クラス} tkinter.font.Font (root=None, font=None, name=None, exists=False, **options)

The @ref{1cce,,Font} class represents a named font. `Font' instances are given
unique names and can be specified by their family, size, and style
configuration. Named fonts are Tk's method of creating and identifying
fonts as a single object, rather than specifying a font by its attributes
with each occurrence.

@quotation

arguments:

@quotation


@display
`font' - font specifier tuple (family, size, options)@w{ }
`name' - unique font name@w{ }
`exists' - self points to existing named font if true@w{ }
@end display


@end quotation

additional keyword options (ignored if `font' is specified):

@quotation


@display
`family' - font family i.e. Courier, Times@w{ }
`size' - font size@w{ }
@display
If `size' is positive it is interpreted as size in points.@w{ }
If `size' is a negative number its absolute value is treated@w{ }
as size in pixels.@w{ }
@end display
`weight' - font emphasis (NORMAL, BOLD)@w{ }
`slant' - ROMAN, ITALIC@w{ }
`underline' - font underlining (0 - none, 1 - underline)@w{ }
`overstrike' - font strikeout (0 - none, 1 - strikeout)@w{ }
@end display


@end quotation
@end quotation

@geindex actual() (tkinter.font.Font のメソッド)
@anchor{library/tkinter font tkinter font Font actual}@anchor{4312}
@deffn {メソッド} actual (option=None, displayof=None)

Return the attributes of the font.
@end deffn

@geindex cget() (tkinter.font.Font のメソッド)
@anchor{library/tkinter font tkinter font Font cget}@anchor{4313}
@deffn {メソッド} cget (option)

Retrieve an attribute of the font.
@end deffn

@geindex config() (tkinter.font.Font のメソッド)
@anchor{library/tkinter font tkinter font Font config}@anchor{4314}
@deffn {メソッド} config (**options)

Modify attributes of the font.
@end deffn

@geindex copy() (tkinter.font.Font のメソッド)
@anchor{library/tkinter font tkinter font Font copy}@anchor{4315}
@deffn {メソッド} copy ()

Return new instance of the current font.
@end deffn

@geindex measure() (tkinter.font.Font のメソッド)
@anchor{library/tkinter font tkinter font Font measure}@anchor{4316}
@deffn {メソッド} measure (text, displayof=None)

Return amount of space the text would occupy on the specified display
when formatted in the current font. If no display is specified then the
main application window is assumed.
@end deffn

@geindex metrics() (tkinter.font.Font のメソッド)
@anchor{library/tkinter font tkinter font Font metrics}@anchor{4317}
@deffn {メソッド} metrics (*options, **kw)

Return font-specific data.
Options include:


@table @asis

@item `ascent' - distance between baseline and highest point that a

character of the font can occupy

@item `descent' - distance between baseline and lowest point that a

character of the font can occupy

@item `linespace' - minimum vertical separation necessary between any two

characters of the font that ensures no vertical overlap between lines.
@end table

`fixed' - 1 if font is fixed-width else 0
@end deffn
@end deffn

@geindex families() (tkinter.font モジュール)
@anchor{library/tkinter font tkinter font families}@anchor{4318}
@deffn {の関数} tkinter.font.families (root=None, displayof=None)

Return the different font families.
@end deffn

@geindex names() (tkinter.font モジュール)
@anchor{library/tkinter font tkinter font names}@anchor{4319}
@deffn {の関数} tkinter.font.names (root=None)

Return the names of defined fonts.
@end deffn

@geindex nametofont() (tkinter.font モジュール)
@anchor{library/tkinter font tkinter font nametofont}@anchor{1cd0}
@deffn {の関数} tkinter.font.nametofont (name, root=None)

Return a @ref{1cce,,Font} representation of a tk named font.


バージョン 3.10 で変更: The `root' parameter was added.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Tkinter ダイアログ,tkinter messagebox --- Tkinter メッセージプロンプト,tkinter font --- Tkinter フォントラッパー,Graphical user interfaces with Tk
@anchor{library/dialog doc}@anchor{431a}@anchor{library/dialog tkinter-dialogs}@anchor{431b}@anchor{library/dialog translation-repo}@anchor{431c}
@subsection Tkinter ダイアログ


@menu
* tkinter.simpledialog: tkinter simpledialog --- Standard Tkinter input dialogs. Standard Tkinter input dialogs
* tkinter.filedialog: tkinter filedialog --- File selection dialogs. File selection dialogs
* tkinter.commondialog: tkinter commondialog --- Dialog window templates. Dialog window templates

@end menu

@node tkinter simpledialog --- Standard Tkinter input dialogs,tkinter filedialog --- File selection dialogs,,Tkinter ダイアログ
@anchor{library/dialog module-tkinter simpledialog}@anchor{fe}@anchor{library/dialog tkinter-simpledialog-standard-tkinter-input-dialogs}@anchor{431d}
@subsubsection @code{tkinter.simpledialog} --- Standard Tkinter input dialogs


@geindex module; tkinter.simpledialog

`ソースコード:' Lib/tkinter/simpledialog.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/simpledialog.py}


__________________________________________________________________


The @code{tkinter.simpledialog} module contains convenience classes and
functions for creating simple modal dialogs to get a value from the user.

@geindex askfloat() (tkinter.simpledialog モジュール)
@geindex askinteger() (tkinter.simpledialog モジュール)
@geindex askstring() (tkinter.simpledialog モジュール)
@anchor{library/dialog tkinter simpledialog askfloat}@anchor{431e}
@deffn {の関数} tkinter.simpledialog.askfloat (title, prompt, **kw)
@anchor{library/dialog tkinter simpledialog askinteger}@anchor{1cd1}
@deffnx {の関数} tkinter.simpledialog.askinteger (title, prompt, **kw)
@anchor{library/dialog tkinter simpledialog askstring}@anchor{431f}
@deffnx {の関数} tkinter.simpledialog.askstring (title, prompt, **kw)

上の３つの関数は、ユーザーに期待する型の値を入力を促すダイアログを提供します。
@end deffn

@geindex Dialog (tkinter.simpledialog のクラス)
@anchor{library/dialog tkinter simpledialog Dialog}@anchor{4320}
@deffn {クラス} tkinter.simpledialog.Dialog (parent, title=None)

カスタムダイアログ用の基底クラスです。

@geindex body() (tkinter.simpledialog.Dialog のメソッド)
@anchor{library/dialog tkinter simpledialog Dialog body}@anchor{4321}
@deffn {メソッド} body (master)

ダイアログインターフェースの構築をオーバーライドし、初期フォーカスを持つべきウィジットを返します。
@end deffn

@geindex buttonbox() (tkinter.simpledialog.Dialog のメソッド)
@anchor{library/dialog tkinter simpledialog Dialog buttonbox}@anchor{4322}
@deffn {メソッド} buttonbox ()

デフォルト動作はOKとCancelボタンを追加します。カスタムのボタンレイアウトが必要であればオーバーライドします。
@end deffn
@end deffn

@node tkinter filedialog --- File selection dialogs,tkinter commondialog --- Dialog window templates,tkinter simpledialog --- Standard Tkinter input dialogs,Tkinter ダイアログ
@anchor{library/dialog module-tkinter filedialog}@anchor{fa}@anchor{library/dialog tkinter-filedialog-file-selection-dialogs}@anchor{4323}
@subsubsection @code{tkinter.filedialog} --- File selection dialogs


@geindex module; tkinter.filedialog

`ソースコード:' Lib/tkinter/filedialog.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/filedialog.py}


__________________________________________________________________


The @code{tkinter.filedialog} module provides classes and factory functions for
creating file/directory selection windows.

@menu
* ネイティブの読み込み/保存ダイアログ:: 

@end menu

@node ネイティブの読み込み/保存ダイアログ,,,tkinter filedialog --- File selection dialogs
@anchor{library/dialog native-load-save-dialogs}@anchor{4324}
@subsubsection ネイティブの読み込み/保存ダイアログ


下記のクラスは、振る舞いをカスタマイズできる設定オプション付きの、ネイティブルック＆フィールと統合したファイルダイアログを提供します。以下のキーワード引数は、下記で列挙するクラスや関数に適用できます。

@quotation


@display
`parent' - ダイアログをその上に表示するウィンドウ@w{ }
@end display




@display
`title' - ウィンドウのタイトル@w{ }
@end display




@display
`initialdir' - 最初に表示するディレクトリ@w{ }
@end display




@display
`initialfile' - ダイアログを表示した際に選択するファイル@w{ }
@end display




@display
`filetypes' - (ラベル, パターン) のタプルからなるシーケンスで、'*' ワイルドカードが利用できます@w{ }
@end display




@display
`defaultextension' - ファイルに追加するデフォルトの拡張子 (保存ダイアログ向け)@w{ }
@end display




@display
`multiple' - 真の場合、複数要素の選択を許可します@w{ }
@end display


@end quotation

`静的なファクトリ関数'

The below functions when called create a modal, native look-and-feel dialog,
wait for the user's selection, then return the selected value(s) or @code{None} to the
caller.

@geindex askopenfile() (tkinter.filedialog モジュール)
@geindex askopenfiles() (tkinter.filedialog モジュール)
@anchor{library/dialog tkinter filedialog askopenfile}@anchor{4325}
@deffn {の関数} tkinter.filedialog.askopenfile (mode='r', **options)
@anchor{library/dialog tkinter filedialog askopenfiles}@anchor{4326}
@deffnx {の関数} tkinter.filedialog.askopenfiles (mode='r', **options)

The above two functions create an @ref{4327,,Open} dialog and return the opened
file object(s) in read-only mode.
@end deffn

@geindex asksaveasfile() (tkinter.filedialog モジュール)
@anchor{library/dialog tkinter filedialog asksaveasfile}@anchor{4328}
@deffn {の関数} tkinter.filedialog.asksaveasfile (mode='w', **options)

Create a @ref{4329,,SaveAs} dialog and return a file object opened in write-only mode.
@end deffn

@geindex askopenfilename() (tkinter.filedialog モジュール)
@geindex askopenfilenames() (tkinter.filedialog モジュール)
@anchor{library/dialog tkinter filedialog askopenfilename}@anchor{432a}
@deffn {の関数} tkinter.filedialog.askopenfilename (**options)
@anchor{library/dialog tkinter filedialog askopenfilenames}@anchor{432b}
@deffnx {の関数} tkinter.filedialog.askopenfilenames (**options)

The above two functions create an @ref{4327,,Open} dialog and return the
selected filename(s) that correspond to existing file(s).
@end deffn

@geindex asksaveasfilename() (tkinter.filedialog モジュール)
@anchor{library/dialog tkinter filedialog asksaveasfilename}@anchor{432c}
@deffn {の関数} tkinter.filedialog.asksaveasfilename (**options)

Create a @ref{4329,,SaveAs} dialog and return the selected filename.
@end deffn

@geindex askdirectory() (tkinter.filedialog モジュール)
@anchor{library/dialog tkinter filedialog askdirectory}@anchor{432d}
@deffn {の関数} tkinter.filedialog.askdirectory (**options)


@display
Prompt user to select a directory.@w{ }
Additional keyword option:@w{ }
@display
`mustexist' - determines if selection must be an existing directory.@w{ }
@end display
@end display


@end deffn

@geindex Open (tkinter.filedialog のクラス)
@geindex SaveAs (tkinter.filedialog のクラス)
@anchor{library/dialog tkinter filedialog Open}@anchor{4327}
@deffn {クラス} tkinter.filedialog.Open (master=None, **options)
@anchor{library/dialog tkinter filedialog SaveAs}@anchor{4329}
@deffnx {クラス} tkinter.filedialog.SaveAs (master=None, **options)

The above two classes provide native dialog windows for saving and loading
files.
@end deffn

`便利なクラス'

The below classes are used for creating file/directory windows from scratch.
These do not emulate the native look-and-feel of the platform.

@geindex Directory (tkinter.filedialog のクラス)
@anchor{library/dialog tkinter filedialog Directory}@anchor{432e}
@deffn {クラス} tkinter.filedialog.Directory (master=None, **options)

Create a dialog prompting the user to select a directory.
@end deffn

@cartouche
@quotation 注釈 
The `FileDialog' class should be subclassed for custom event
handling and behaviour.
@end quotation
@end cartouche

@geindex FileDialog (tkinter.filedialog のクラス)
@anchor{library/dialog tkinter filedialog FileDialog}@anchor{432f}
@deffn {クラス} tkinter.filedialog.FileDialog (master, title=None)

Create a basic file selection dialog.

@geindex cancel_command() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog cancel_command}@anchor{4330}
@deffn {メソッド} cancel_command (event=None)

Trigger the termination of the dialog window.
@end deffn

@geindex dirs_double_event() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog dirs_double_event}@anchor{4331}
@deffn {メソッド} dirs_double_event (event)

Event handler for double-click event on directory.
@end deffn

@geindex dirs_select_event() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog dirs_select_event}@anchor{4332}
@deffn {メソッド} dirs_select_event (event)

Event handler for click event on directory.
@end deffn

@geindex files_double_event() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog files_double_event}@anchor{4333}
@deffn {メソッド} files_double_event (event)

Event handler for double-click event on file.
@end deffn

@geindex files_select_event() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog files_select_event}@anchor{4334}
@deffn {メソッド} files_select_event (event)

Event handler for single-click event on file.
@end deffn

@geindex filter_command() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog filter_command}@anchor{4335}
@deffn {メソッド} filter_command (event=None)

Filter the files by directory.
@end deffn

@geindex get_filter() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog get_filter}@anchor{4336}
@deffn {メソッド} get_filter ()

Retrieve the file filter currently in use.
@end deffn

@geindex get_selection() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog get_selection}@anchor{4337}
@deffn {メソッド} get_selection ()

Retrieve the currently selected item.
@end deffn

@geindex go() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog go}@anchor{4338}
@deffn {メソッド} go (dir_or_file=os.curdir, pattern='*', default='@w{'}, key=None)

Render dialog and start event loop.
@end deffn

@geindex ok_event() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog ok_event}@anchor{4339}
@deffn {メソッド} ok_event (event)

Exit dialog returning current selection.
@end deffn

@geindex quit() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog quit}@anchor{433a}
@deffn {メソッド} quit (how=None)

Exit dialog returning filename, if any.
@end deffn

@geindex set_filter() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog set_filter}@anchor{433b}
@deffn {メソッド} set_filter (dir, pat)

Set the file filter.
@end deffn

@geindex set_selection() (tkinter.filedialog.FileDialog のメソッド)
@anchor{library/dialog tkinter filedialog FileDialog set_selection}@anchor{433c}
@deffn {メソッド} set_selection (file)

Update the current file selection to `file'.
@end deffn
@end deffn

@geindex LoadFileDialog (tkinter.filedialog のクラス)
@anchor{library/dialog tkinter filedialog LoadFileDialog}@anchor{433d}
@deffn {クラス} tkinter.filedialog.LoadFileDialog (master, title=None)

A subclass of FileDialog that creates a dialog window for selecting an
existing file.

@geindex ok_command() (tkinter.filedialog.LoadFileDialog のメソッド)
@anchor{library/dialog tkinter filedialog LoadFileDialog ok_command}@anchor{433e}
@deffn {メソッド} ok_command ()

Test that a file is provided and that the selection indicates an
already existing file.
@end deffn
@end deffn

@geindex SaveFileDialog (tkinter.filedialog のクラス)
@anchor{library/dialog tkinter filedialog SaveFileDialog}@anchor{433f}
@deffn {クラス} tkinter.filedialog.SaveFileDialog (master, title=None)

A subclass of FileDialog that creates a dialog window for selecting a
destination file.

@geindex ok_command() (tkinter.filedialog.SaveFileDialog のメソッド)
@anchor{library/dialog tkinter filedialog SaveFileDialog ok_command}@anchor{4340}
@deffn {メソッド} ok_command ()

Test whether or not the selection points to a valid file that is not a
directory. Confirmation is required if an already existing file is
selected.
@end deffn
@end deffn

@node tkinter commondialog --- Dialog window templates,,tkinter filedialog --- File selection dialogs,Tkinter ダイアログ
@anchor{library/dialog module-tkinter commondialog}@anchor{f8}@anchor{library/dialog tkinter-commondialog-dialog-window-templates}@anchor{4341}
@subsubsection @code{tkinter.commondialog} --- Dialog window templates


@geindex module; tkinter.commondialog

`Source code:' Lib/tkinter/commondialog.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/commondialog.py}


__________________________________________________________________


The @code{tkinter.commondialog} module provides the @ref{4309,,Dialog} class that
is the base class for dialogs defined in other supporting modules.

@geindex Dialog (tkinter.commondialog のクラス)
@anchor{library/dialog tkinter commondialog Dialog}@anchor{4309}
@deffn {クラス} tkinter.commondialog.Dialog (master=None, **options)

@geindex show() (tkinter.commondialog.Dialog のメソッド)
@anchor{library/dialog tkinter commondialog Dialog show}@anchor{4342}
@deffn {メソッド} show (**options)

Render the Dialog window.
@end deffn
@end deffn


@subsubheading 参考


Modules @ref{fc,,tkinter.messagebox}, @ref{2066,,ファイルを読み書きする}


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tkinter messagebox --- Tkinter メッセージプロンプト,tkinter scrolledtext --- スクロール可能なテキストウィジェット,Tkinter ダイアログ,Graphical user interfaces with Tk
@anchor{library/tkinter messagebox doc}@anchor{4343}@anchor{library/tkinter messagebox module-tkinter messagebox}@anchor{fc}@anchor{library/tkinter messagebox tkinter-messagebox-tkinter-message-prompts}@anchor{4344}@anchor{library/tkinter messagebox translation-repo}@anchor{4345}
@subsection @code{tkinter.messagebox} --- Tkinter メッセージプロンプト


@geindex module; tkinter.messagebox

`ソースコード:' Lib/tkinter/messagebox.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/messagebox.py}


__________________________________________________________________


The @code{tkinter.messagebox} module provides a template base class as well as
a variety of convenience methods for commonly used configurations. The message
boxes are modal and will return a subset of (@code{True}, @code{False}, @code{None},
@ref{4346,,OK}, @ref{4347,,CANCEL}, @ref{4348,,YES}, @ref{4349,,NO}) based on
the user's selection. Common message box styles and layouts include but are not
limited to:


@float Figure

@image{python-figures/tk_msg,,,,png}

@end float


@geindex Message (tkinter.messagebox のクラス)
@anchor{library/tkinter messagebox tkinter messagebox Message}@anchor{434a}
@deffn {クラス} tkinter.messagebox.Message (master=None, **options)

Create a message window with an application-specified message, an icon
and a set of buttons.
Each of the buttons in the message window is identified by a unique symbolic name (see the `type' options).

The following options are supported:

@quotation


@table @asis

@item `command'

Specifies the function to invoke when the user closes the dialog.
The name of the button clicked by the user to close the dialog is
passed as argument.
This is only available on macOS.

@item `default'

Gives the @ref{434b,,symbolic name} of the default button
for this message window (@ref{4346,,OK}, @ref{4347,,CANCEL}, and so on).
If this option is not specified, the first button in the dialog will
be made the default.

@item `detail'

Specifies an auxiliary message to the main message given by the
`message' option.
The message detail will be presented beneath the main message and,
where supported by the OS, in a less emphasized font than the main
message.

@item `icon'

Specifies an @ref{434c,,icon} to display.
If this option is not specified, then the @ref{434d,,INFO} icon will be
displayed.

@item `message'

Specifies the message to display in this message box.
The default value is an empty string.

@item `parent'

Makes the specified window the logical parent of the message box.
The message box is displayed on top of its parent window.

@item `title'

Specifies a string to display as the title of the message box.
This option is ignored on macOS, where platform guidelines forbid
the use of a title on this kind of dialog.

@item `type'

Arranges for a @ref{434e,,predefined set of buttons}
to be displayed.
@end table
@end quotation

@geindex show() (tkinter.messagebox.Message のメソッド)
@anchor{library/tkinter messagebox tkinter messagebox Message show}@anchor{434f}
@deffn {メソッド} show (**options)

Display a message window and wait for the user to select one of the buttons. Then return the symbolic name of the selected button.
Keyword arguments can override options specified in the constructor.
@end deffn
@end deffn

`情報メッセージボックス'

@geindex showinfo() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox showinfo}@anchor{4350}
@deffn {の関数} tkinter.messagebox.showinfo (title=None, message=None, **options)

Creates and displays an information message box with the specified title
and message.
@end deffn

`警告メッセージボックス'

@geindex showwarning() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox showwarning}@anchor{4351}
@deffn {の関数} tkinter.messagebox.showwarning (title=None, message=None, **options)

Creates and displays a warning message box with the specified title
and message.
@end deffn

@geindex showerror() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox showerror}@anchor{4352}
@deffn {の関数} tkinter.messagebox.showerror (title=None, message=None, **options)

Creates and displays an error message box with the specified title
and message.
@end deffn

`質問メッセージボックス'

@geindex askquestion() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox askquestion}@anchor{4353}
@deffn {の関数} tkinter.messagebox.askquestion (title=None, message=None, *, type=YESNO, **options)

Ask a question. By default shows buttons @ref{4348,,YES} and @ref{4349,,NO}.
Returns the symbolic name of the selected button.
@end deffn

@geindex askokcancel() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox askokcancel}@anchor{4354}
@deffn {の関数} tkinter.messagebox.askokcancel (title=None, message=None, **options)

Ask if operation should proceed. Shows buttons @ref{4346,,OK} and @ref{4347,,CANCEL}.
Returns @code{True} if the answer is ok and @code{False} otherwise.
@end deffn

@geindex askretrycancel() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox askretrycancel}@anchor{4355}
@deffn {の関数} tkinter.messagebox.askretrycancel (title=None, message=None, **options)

Ask if operation should be retried. Shows buttons @ref{4356,,RETRY} and @ref{4347,,CANCEL}.
Return @code{True} if the answer is yes and @code{False} otherwise.
@end deffn

@geindex askyesno() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox askyesno}@anchor{4357}
@deffn {の関数} tkinter.messagebox.askyesno (title=None, message=None, **options)

Ask a question. Shows buttons @ref{4348,,YES} and @ref{4349,,NO}.
Returns @code{True} if the answer is yes and @code{False} otherwise.
@end deffn

@geindex askyesnocancel() (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox askyesnocancel}@anchor{4358}
@deffn {の関数} tkinter.messagebox.askyesnocancel (title=None, message=None, **options)

Ask a question. Shows buttons @ref{4348,,YES}, @ref{4349,,NO} and @ref{4347,,CANCEL}.
Return @code{True} if the answer is yes, @code{None} if cancelled, and @code{False}
otherwise.
@end deffn
@anchor{library/tkinter messagebox messagebox-buttons}@anchor{434b}
Symbolic names of buttons:

@geindex ABORT (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox ABORT}@anchor{4359}
@deffn {データ} tkinter.messagebox.ABORT = 'abort'
@end deffn

@geindex RETRY (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox RETRY}@anchor{4356}
@deffn {データ} tkinter.messagebox.RETRY = 'retry'
@end deffn

@geindex IGNORE (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox IGNORE}@anchor{435a}
@deffn {データ} tkinter.messagebox.IGNORE = 'ignore'
@end deffn

@geindex OK (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox OK}@anchor{4346}
@deffn {データ} tkinter.messagebox.OK = 'ok'
@end deffn

@geindex CANCEL (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox CANCEL}@anchor{4347}
@deffn {データ} tkinter.messagebox.CANCEL = 'cancel'
@end deffn

@geindex YES (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox YES}@anchor{4348}
@deffn {データ} tkinter.messagebox.YES = 'yes'
@end deffn

@geindex NO (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox NO}@anchor{4349}
@deffn {データ} tkinter.messagebox.NO = 'no'
@end deffn
@anchor{library/tkinter messagebox messagebox-types}@anchor{434e}
Predefined sets of buttons:

@geindex ABORTRETRYIGNORE (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox ABORTRETRYIGNORE}@anchor{435b}
@deffn {データ} tkinter.messagebox.ABORTRETRYIGNORE = 'abortretryignore'

Displays three buttons whose symbolic names are @ref{4359,,ABORT},
@ref{4356,,RETRY} and @ref{435a,,IGNORE}.
@end deffn


@deffn {データ} tkinter.messagebox.OK = 'ok'

Displays one button whose symbolic name is @ref{4346,,OK}.
@end deffn

@geindex OKCANCEL (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox OKCANCEL}@anchor{435c}
@deffn {データ} tkinter.messagebox.OKCANCEL = 'okcancel'

Displays two buttons whose symbolic names are @ref{4346,,OK} and
@ref{4347,,CANCEL}.
@end deffn

@geindex RETRYCANCEL (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox RETRYCANCEL}@anchor{435d}
@deffn {データ} tkinter.messagebox.RETRYCANCEL = 'retrycancel'

Displays two buttons whose symbolic names are @ref{4356,,RETRY} and
@ref{4347,,CANCEL}.
@end deffn

@geindex YESNO (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox YESNO}@anchor{435e}
@deffn {データ} tkinter.messagebox.YESNO = 'yesno'

Displays two buttons whose symbolic names are @ref{4348,,YES} and
@ref{4349,,NO}.
@end deffn

@geindex YESNOCANCEL (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox YESNOCANCEL}@anchor{435f}
@deffn {データ} tkinter.messagebox.YESNOCANCEL = 'yesnocancel'

Displays three buttons whose symbolic names are @ref{4348,,YES},
@ref{4349,,NO} and @ref{4347,,CANCEL}.
@end deffn
@anchor{library/tkinter messagebox messagebox-icons}@anchor{434c}
Icon images:

@geindex ERROR (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox ERROR}@anchor{4360}
@deffn {データ} tkinter.messagebox.ERROR = 'error'
@end deffn

@geindex INFO (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox INFO}@anchor{434d}
@deffn {データ} tkinter.messagebox.INFO = 'info'
@end deffn

@geindex QUESTION (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox QUESTION}@anchor{4361}
@deffn {データ} tkinter.messagebox.QUESTION = 'question'
@end deffn

@geindex WARNING (tkinter.messagebox モジュール)
@anchor{library/tkinter messagebox tkinter messagebox WARNING}@anchor{4362}
@deffn {データ} tkinter.messagebox.WARNING = 'warning'
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tkinter scrolledtext --- スクロール可能なテキストウィジェット,tkinter dnd --- ドラッグアンドドロップのサポート,tkinter messagebox --- Tkinter メッセージプロンプト,Graphical user interfaces with Tk
@anchor{library/tkinter scrolledtext doc}@anchor{4363}@anchor{library/tkinter scrolledtext module-tkinter scrolledtext}@anchor{fd}@anchor{library/tkinter scrolledtext tkinter-scrolledtext-scrolled-text-widget}@anchor{4364}@anchor{library/tkinter scrolledtext translation-repo}@anchor{4365}
@subsection @code{tkinter.scrolledtext} --- スクロール可能なテキストウィジェット


@geindex module; tkinter.scrolledtext

`ソースコード:' Lib/tkinter/scrolledtext.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/scrolledtext.py}


__________________________________________________________________


The @code{tkinter.scrolledtext} module provides a class of the same name which
implements a basic text widget which has a vertical scroll bar configured to do
the "right thing."  Using the @ref{4366,,ScrolledText} class is a lot easier than
setting up a text widget and scroll bar directly.

テキストウィジェットとスクロールバーは @code{Frame} の中に一緒にpackされ、 @code{Grid} と @code{Pack} ジオメトリマネジャのメソッドは@code{Frame} オブジェクトから得られます。これによって、もっとも標準的なジオメトリマネジャの振る舞いにするために、直接 @ref{4366,,ScrolledText} ウィジェットを使えるようになります。

特定の制御が必要ならば、以下の属性が利用できます:

@geindex ScrolledText (tkinter.scrolledtext のクラス)
@anchor{library/tkinter scrolledtext tkinter scrolledtext ScrolledText}@anchor{4366}
@deffn {クラス} tkinter.scrolledtext.ScrolledText (master=None, **kw)

@geindex frame (tkinter.scrolledtext.ScrolledText の属性)
@anchor{library/tkinter scrolledtext tkinter scrolledtext ScrolledText frame}@anchor{4367}
@deffn {の属性} frame

テキストとスクロールバーウィジェットを取り囲むフレーム。
@end deffn

@geindex vbar (tkinter.scrolledtext.ScrolledText の属性)
@anchor{library/tkinter scrolledtext tkinter scrolledtext ScrolledText vbar}@anchor{4368}
@deffn {の属性} vbar

スクロールバーウィジェット。
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tkinter dnd --- ドラッグアンドドロップのサポート,tkinter ttk --- Tk のテーマ付きウィジェット,tkinter scrolledtext --- スクロール可能なテキストウィジェット,Graphical user interfaces with Tk
@anchor{library/tkinter dnd doc}@anchor{4369}@anchor{library/tkinter dnd module-tkinter dnd}@anchor{f9}@anchor{library/tkinter dnd tkinter-dnd-drag-and-drop-support}@anchor{436a}@anchor{library/tkinter dnd translation-repo}@anchor{436b}
@subsection @code{tkinter.dnd} --- ドラッグアンドドロップのサポート


@geindex module; tkinter.dnd

`ソースコード:' Lib/tkinter/dnd.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/dnd.py}


__________________________________________________________________


@cartouche
@quotation 注釈 
This is experimental and due to be deprecated when it is replaced
with the Tk DND.
@end quotation
@end cartouche

The @code{tkinter.dnd} module provides drag-and-drop support for objects within
a single application, within the same window or between windows. To enable an
object to be dragged, you must create an event binding for it that starts the
drag-and-drop process. Typically, you bind a ButtonPress event to a callback
function that you write (see @ref{42fa,,バインドとイベント}). The function should
call @ref{436c,,dnd_start()}, where 'source' is the object to be dragged, and 'event'
is the event that invoked the call (the argument to your callback function).

Selection of a target object occurs as follows:


@enumerate 

@item 
Top-down search of area under mouse for target widget
@end enumerate

@quotation


@itemize *

@item 
Target widget should have a callable `dnd_accept' attribute

@item 
If `dnd_accept' is not present or returns @code{None}, search moves to parent widget

@item 
If no target widget is found, then the target object is @code{None}
@end itemize
@end quotation


@enumerate 2

@item 
Call to `<old_target>.dnd_leave(source, event)'

@item 
Call to `<new_target>.dnd_enter(source, event)'

@item 
Call to `<target>.dnd_commit(source, event)' to notify of drop

@item 
Call to `<source>.dnd_end(target, event)' to signal end of drag-and-drop
@end enumerate

@geindex DndHandler (tkinter.dnd のクラス)
@anchor{library/tkinter dnd tkinter dnd DndHandler}@anchor{436d}
@deffn {クラス} tkinter.dnd.DndHandler (source, event)

The `DndHandler' class handles drag-and-drop events tracking Motion and
ButtonRelease events on the root of the event widget.

@geindex cancel() (tkinter.dnd.DndHandler のメソッド)
@anchor{library/tkinter dnd tkinter dnd DndHandler cancel}@anchor{436e}
@deffn {メソッド} cancel (event=None)

Cancel the drag-and-drop process.
@end deffn

@geindex finish() (tkinter.dnd.DndHandler のメソッド)
@anchor{library/tkinter dnd tkinter dnd DndHandler finish}@anchor{436f}
@deffn {メソッド} finish (event, commit=0)

Execute end of drag-and-drop functions.
@end deffn

@geindex on_motion() (tkinter.dnd.DndHandler のメソッド)
@anchor{library/tkinter dnd tkinter dnd DndHandler on_motion}@anchor{4370}
@deffn {メソッド} on_motion (event)

Inspect area below mouse for target objects while drag is performed.
@end deffn

@geindex on_release() (tkinter.dnd.DndHandler のメソッド)
@anchor{library/tkinter dnd tkinter dnd DndHandler on_release}@anchor{4371}
@deffn {メソッド} on_release (event)

Signal end of drag when the release pattern is triggered.
@end deffn
@end deffn

@geindex dnd_start() (tkinter.dnd モジュール)
@anchor{library/tkinter dnd tkinter dnd dnd_start}@anchor{436c}
@deffn {の関数} tkinter.dnd.dnd_start (source, event)

Factory function for drag-and-drop process.
@end deffn


@subsubheading 参考


@ref{42fa,,バインドとイベント}


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tkinter ttk --- Tk のテーマ付きウィジェット,IDLE --- Python のエディタとシェル<2>,tkinter dnd --- ドラッグアンドドロップのサポート,Graphical user interfaces with Tk
@anchor{library/tkinter ttk doc}@anchor{4372}@anchor{library/tkinter ttk module-tkinter ttk}@anchor{ff}@anchor{library/tkinter ttk tkinter-ttk-tk-themed-widgets}@anchor{4373}@anchor{library/tkinter ttk translation-repo}@anchor{4374}
@subsection @code{tkinter.ttk} --- Tk のテーマ付きウィジェット


@geindex module; tkinter.ttk

`ソースコード:' Lib/tkinter/ttk.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tkinter/ttk.py}

@geindex ttk


__________________________________________________________________


The @code{tkinter.ttk} module provides access to the Tk themed widget set,
introduced in Tk 8.5. It provides additional benefits including anti-aliased font
rendering under X11 and window transparency (requiring a composition
window manager on X11).

The basic idea for @code{tkinter.ttk} is to separate, to the extent possible,
the code implementing a widget's behavior from the code implementing its
appearance.


@subsubheading 参考



@table @asis

@item Tk Widget Styling Support@footnote{https://core.tcl.tk/tips/doc/trunk/tip/48.md}

Tk のテーマサポートを紹介するドキュメント
@end table


@menu
* Ttk を使う:: 
* Ttk ウィジェット:: 
* ウィジェット:: 
* コンボボックス:: 
* Spinbox:: 
* ノートブック:: 
* プログレスバー:: 
* セパレータ:: 
* サイズグリップ:: 
* ツリービュー:: 
* Ttk スタイル:: 

@end menu

@node Ttk を使う,Ttk ウィジェット,,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk using-ttk}@anchor{4375}
@subsubsection Ttk を使う


Ttk を使い始めるために、モジュールをインポートします:

@example
from tkinter import ttk
@end example

基本的な Tk ウィジェットを上書きするため、次のように Tk のインポートに続けてインポートを行います:

@example
from tkinter import *
from tkinter.ttk import *
@end example

That code causes several @code{tkinter.ttk} widgets (@code{Button},
@code{Checkbutton}, @code{Entry}, @code{Frame}, @code{Label},
@code{LabelFrame}, @code{Menubutton}, @code{PanedWindow},
@code{Radiobutton}, @code{Scale} and @code{Scrollbar}) to
automatically replace the Tk widgets.

これにはプラットフォームをまたいでより良い見た目を得られるという、直接的な利益がありますが、ウィジェットは完全な互換性を持っているわけではありません。一番の違いは "fg" や "bg" やその他のスタイルに関係するウィジェットのオプションが Ttk ウィジェットから無くなっていることです。同じ (もしくはより良い) 見た目にするためには @code{ttk.Style} を使ってください。


@subsubheading 参考



@table @asis

@item Converting existing applications to use Tile widgets@footnote{https://tktable.sourceforge.net/tile/doc/converting.txt}

アプリケーションを移行して新しいウィジェットを使用する際に出くわす典型的な差異について (Tcl の用語を使って) 書かれている研究論文
@end table


@node Ttk ウィジェット,ウィジェット,Ttk を使う,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk ttk-widgets}@anchor{4376}
@subsubsection Ttk ウィジェット


Ttk には 18 のウィジェットがあり、そのうち 12 は Tkinter に既にあるものです: @code{Button}, @code{Checkbutton}, @code{Entry}, @code{Frame}, @code{Label}, @code{LabelFrame}, @code{Menubutton}, @code{PanedWindow}, @code{Radiobutton}, @code{Scale}, @code{Scrollbar}, @ref{d8d,,Spinbox} 。新しい 6 つは次のものです: @ref{4377,,Combobox}, @ref{4378,,Notebook}, @ref{4379,,Progressbar}, @code{Separator}, @code{Sizegrip}, @ref{c87,,Treeview} 。そして、これらは全て @ref{437a,,Widget} の子クラスです。

Ttk ウィジェットを使用すると、アプリケーションの見た目と使いやすさが向上します。上述の通り、書式をコーディングする方法は異なります。

Tk のコード

@example
l1 = tkinter.Label(text="Test", fg="black", bg="white")
l2 = tkinter.Label(text="Test", fg="black", bg="white")
@end example

Ttk のコード:

@example
style = ttk.Style()
style.configure("BW.TLabel", foreground="black", background="white")

l1 = ttk.Label(text="Test", style="BW.TLabel")
l2 = ttk.Label(text="Test", style="BW.TLabel")
@end example

@ref{437b,,TtkStyling} についての詳細は @ref{560,,Style} クラスの文書を読んでください。

@node ウィジェット,コンボボックス,Ttk ウィジェット,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk widget}@anchor{437c}
@subsubsection ウィジェット


@code{ttk.Widget} はTk のテーマ付きウィジェットがサポートしている標準のオプションやメソッドを定義するもので、これを直接インスタンス化するものではありません。

@menu
* 標準オプション:: 
* スクロール可能ウィジェットのオプション:: 
* ラベルオプション:: 
* 互換性オプション:: 
* ウィジェットの状態:: 
* ttk.Widget: ttk Widget. 

@end menu

@node 標準オプション,スクロール可能ウィジェットのオプション,,ウィジェット
@anchor{library/tkinter ttk standard-options}@anchor{437d}
@subsubsection 標準オプション


All the @code{ttk} Widgets accept the following options:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

クラス

@tab

ウィンドウクラスを指定します。このクラスはオプションデータベースにウィンドウの他のオプションについて問い合わせを行うときに使われ、これによりウィンドウのデフォルトのバインドタグを決定したり、ウィジェットのデフォルトのレイアウトやスタイルを選択します。このオプションは読み出し専用で、ウィンドウが作成されるときにのみ指定できます。

@item

cursor

@tab

このウィジェットで使うマウスカーソルを指定します。空文字列 (デフォルト) が設定されている場合は、カーソルは親ウィジェットのものを引き継ぎます。

@item

takefocus

@tab

キーボードによる移動のときにウィンドウがフォーカスを受け入れるかを決定します。0、1、空文字列のいずれかを返します。0 が返されると、キーボードによる移動でそのウィンドウは常にスキップされます。1 なら、そのウィンドウが表示されているときに限り入力フォーカスを受け入れます。そして空文字列は、移動スクリプトによってウィンドウにフォーカスを当てるかどうかが決まることを意味します。

@item

style

@tab

独自のウィジェットスタイルを指定するのに使われます。

@end multitable


@node スクロール可能ウィジェットのオプション,ラベルオプション,標準オプション,ウィジェット
@anchor{library/tkinter ttk scrollable-widget-options}@anchor{437e}
@subsubsection スクロール可能ウィジェットのオプション


以下のオプションはスクロールバーで操作されるウィジェットが持っているオプションです。


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

xscrollcommand

@tab

水平方向のスクロールバーとのやり取りに使われます。

ウィジェットのウィンドウが再描画されたとき, ウィジェットは scrollcommand に基いて Tcl コマンドを生成します。

通常このオプションにはあるスクロールバーのメソッド @code{Scrollbar.set()} が設定されます。こうすると、ウィンドウの見た目が変わったときにスクロールバーの状態も更新されます。

@item

yscrollcommand

@tab

垂直方向のスクロールバーとのやり取りに使われます。詳しくは、上記を参照してください。

@end multitable


@node ラベルオプション,互換性オプション,スクロール可能ウィジェットのオプション,ウィジェット
@anchor{library/tkinter ttk label-options}@anchor{437f}
@subsubsection ラベルオプション


以下のオプションはラベルやボタンやボタンに類似したウィジェットが持っているオプションです。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

text

@tab

ウィジェットに表示される文字列を指定します。

@item

textvariable

@tab

text オプションの代わりに使う値の変数名を指定します。

@item

underline

@tab

このオプションを設定すると、文字列の中で下線を引く文字のインデックス (0 基点) を指定します。下線が引かれた文字はショートカットとして使われます。

@item

image

@tab

表示する画像を指定します。これは 1 つ以上の要素を持つリストです。先頭の要素はデフォルトの画像名です。残りの要素は @ref{1ce6,,Style.map()} で定義されているような状態名と値のペアの並びで、ウィジェットがある状態、もしくはある状態の組み合わせにいるときに使用する別の画像を指定します。このリストにある全ての画像は同じサイズでなればなりません。

@item

compound

@tab

text オプションと image オプションが両方とも指定されていた場合に、テキストに対して画像をどう配置するかを指定します。適当な値は:


@itemize *

@item 
text: テキストのみ表示する

@item 
image: 画像のみ表示する

@item 
top, bottom, left, right: それぞれ画像をテキストの上、下、左、右に配置する。

@item 
none: デフォルト。もしあれば画像を表示し、そうでなければテキストを表示する。
@end itemize

@item

幅

@tab

0 より大きい場合、テキストラベルを作成するのにどれくらいのスペースを使うかを文字の幅で指定します。0 より小さい場合、最小の幅が指定されます。0 もしくは無指定の場合、テキストラベルに対して自然な幅が使われます。

@end multitable


@node 互換性オプション,ウィジェットの状態,ラベルオプション,ウィジェット
@anchor{library/tkinter ttk compatibility-options}@anchor{4380}
@subsubsection 互換性オプション



@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

state

@tab

"normal" か "disabled" に設定され、 "disabled" 状態のビットをコントロールします。これは書き込み専用のオプションです: これを設定するとウィジェットの状態を変更できますが、 @ref{4381,,Widget.state()} メソッドはこのオプションに影響を及ぼしません。

@end multitable


@node ウィジェットの状態,ttk Widget,互換性オプション,ウィジェット
@anchor{library/tkinter ttk widget-states}@anchor{4382}
@subsubsection ウィジェットの状態


ウィジェットの状態は独立した状態フラグのビットマップです。


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

説明

@item

active

@tab

マウスカーソルがウィジェットの上にあり、マウスのボタンをクリックすることで何らかの動作をさせられます

@item

disabled

@tab

プログラムによってウィジェットは無効化されています

@item

focus

@tab

ウィジェットにキーボードフォーカスがあります

@item

pressed

@tab

ウィジェットは押されています

@item

selected

@tab

チェックボタンやラジオボタンのようなウィジェットでの "オン" や "チェック有" や "選択中" に当たります

@item

background

@tab

Windows と Mac には "アクティブな" もしくは最前面のウィンドウという概念があります。背面のウィンドウにあるウィジェットには `background' 状態が設定され、最前面のウィンドウにあるウィジェットでは解除されます

@item

readonly

@tab

ウィジェットはユーザからの変更を受け付けません

@item

alternate

@tab

ウィジェット特有の切り替え表示になっています

@item

invalid

@tab

ウィジェットの値が不正です

@end multitable


状態仕様は状態名の並びになっていて、状態名の先頭にはビットがオフになっていることを示す感嘆符が付くことがあります。

@node ttk Widget,,ウィジェットの状態,ウィジェット
@anchor{library/tkinter ttk ttk-widget}@anchor{4383}
@subsubsection ttk.Widget


以下に書かれているメソッドに加えて、 @code{ttk.Widget} は @code{tkinter.Widget.cget()} メソッドと @code{tkinter.Widget.configure()} メソッドをサポートしています。

@geindex Widget (tkinter.ttk のクラス)
@anchor{library/tkinter ttk tkinter ttk Widget}@anchor{437a}
@deffn {クラス} tkinter.ttk.Widget

@geindex identify() (tkinter.ttk.Widget のメソッド)
@anchor{library/tkinter ttk tkinter ttk Widget identify}@anchor{4384}
@deffn {メソッド} identify (x, y)

`x' `y' の位置にある要素の名前、もしくはその位置に要素が無ければ空文字列を返します。

`x' と `y' はウィジェットに対するピクセル単位の座標です。
@end deffn

@geindex instate() (tkinter.ttk.Widget のメソッド)
@anchor{library/tkinter ttk tkinter ttk Widget instate}@anchor{4385}
@deffn {メソッド} instate (statespec, callback=None, *args, **kw)

ウィジェットの状態をチェックします。コールバックが指定されていない場合、ウィジェットの状態が `statespec' に一致していれば @code{True} 、そうでなければ @code{False} を返します。コールバックが指定されていて、ウィジェットの状態が `statespec' に一致している場合、引数に args を指定してそのコールバックを呼び出します。
@end deffn

@geindex state() (tkinter.ttk.Widget のメソッド)
@anchor{library/tkinter ttk tkinter ttk Widget state}@anchor{4381}
@deffn {メソッド} state (statespec=None)

ウィジェットの状態を変更したり、取得したりします。`statespec' が指定されている場合、それに応じてウィジェットの状態を設定し、どのフラグが変更されたかを示す新しい `statespec' を返します。`statespec' が指定されていない場合、現在の状態フラグを返します。
@end deffn

通常 `statespec' はリストもしくはタプルです。
@end deffn

@node コンボボックス,Spinbox,ウィジェット,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk combobox}@anchor{4386}
@subsubsection コンボボックス


@code{ttk.Combobox} ウィジェットはテキストフィールドと値のポップダウンリストを結び付けます。このウィジェットは @code{Entry} の子クラスです。

@ref{437a,,Widget} から継承したメソッド (@code{Widget.cget()}, @code{Widget.configure()}, @ref{4384,,Widget.identify()}, @ref{4385,,Widget.instate()}, @ref{4381,,Widget.state()}) と以下の @code{Entry} から継承したメソッド (@code{Entry.bbox()}, @code{Entry.delete()}, @code{Entry.icursor()}, @code{Entry.index()}, @code{Entry.insert()}, @code{Entry.selection()}, @code{Entry.xview()}) に加え、このクラスには @code{ttk.Combobox} で説明するメソッドがあります。

@menu
* オプション:: 
* 仮想イベント:: 
* ttk.Combobox: ttk Combobox. 

@end menu

@node オプション,仮想イベント,,コンボボックス
@anchor{library/tkinter ttk options}@anchor{4387}
@subsubsection オプション


このウィジェットは以下の固有のオプションを受け付けます:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

exportselection

@tab

真偽値を取る。設定されている場合、ウィジェットの選択はウィンドウマネージャの選択とリンクしています (例えば、Misc.selection_get を実行することで得られます)。

@item

justify

@tab

ウィジェットの中でテキストをどう配置するかを指定します。 "left", "center", "right" のうちのどれか 1 つです。

@item

高さ

@tab

ポップダウンリストの高さを行数で指定します。

@item

postcommand

@tab

コンボボックスの値を表示する直前に呼び出される、(Misc.register などで登録した) スクリプトです。どの値を表示するかについても指定できます。

@item

state

@tab

"normal", "readonly", "disabled" のどれか 1 つです。"readonly" 状態では、直接入力値を編集することはできず、ユーザはドロップダウンリストから値を 1 つ選ぶことしかできません。"normal" 状態では、テキストフィールドは直接編集できます。"disabled" 状態では、コンボボックスは一切反応しません。

@item

textvariable

@tab

コンボボックスの値とリンクさせる変数名を指定します。その変数の値が変更されたとき、ウィジェットの値は更新されます。ウィジェットの値が更新されたときも同様です。 @code{tkinter.StringVar} を参照してください。

@item

@code{values}

@tab

ドロップダウンリストに表示する値のリストを指定します。

@item

幅

@tab

入力ウィンドウに必要な幅をウィジェットのフォントの平均的なサイズの文字で測った、文字数を指定します。

@end multitable


@node 仮想イベント,ttk Combobox,オプション,コンボボックス
@anchor{library/tkinter ttk virtual-events}@anchor{4388}
@subsubsection 仮想イベント


コンボボックスウィジェットは、ユーザが値のリストから1つ選んだときに仮想イベント `<<ComboboxSelected>>' を生成します。

@node ttk Combobox,,仮想イベント,コンボボックス
@anchor{library/tkinter ttk ttk-combobox}@anchor{4389}
@subsubsection ttk.Combobox


@geindex Combobox (tkinter.ttk のクラス)
@anchor{library/tkinter ttk tkinter ttk Combobox}@anchor{4377}
@deffn {クラス} tkinter.ttk.Combobox

@geindex current() (tkinter.ttk.Combobox のメソッド)
@anchor{library/tkinter ttk tkinter ttk Combobox current}@anchor{438a}
@deffn {メソッド} current (newindex=None)

`newindex' が指定されている場合、コンボボックスの値がドロップダウンリストの `newindex' の位置にある値に設定されます。そうでない場合、現在の値のインデックスを、もしくは現在の値がリストに含まれていないなら -1 を返します。
@end deffn

@geindex get() (tkinter.ttk.Combobox のメソッド)
@anchor{library/tkinter ttk tkinter ttk Combobox get}@anchor{438b}
@deffn {メソッド} get ()

コンボボックスの現在の値を返します。
@end deffn

@geindex set() (tkinter.ttk.Combobox のメソッド)
@anchor{library/tkinter ttk tkinter ttk Combobox set}@anchor{438c}
@deffn {メソッド} set (value)

コンボボックスの値を `value' に設定します。
@end deffn
@end deffn

@node Spinbox,ノートブック,コンボボックス,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk spinbox}@anchor{438d}
@subsubsection Spinbox


The @code{ttk.Spinbox} widget is a @code{ttk.Entry} enhanced with increment
and decrement arrows.  It can be used for numbers or lists of string values.
This widget is a subclass of @code{Entry}.

@ref{437a,,Widget} から継承したメソッド: @code{Widget.cget()}, @code{Widget.configure()}, @ref{4384,,Widget.identify()}, @ref{4385,,Widget.instate()}, @ref{4381,,Widget.state()} と、以下の @code{Entry} から継承したメソッド: @code{Entry.bbox()}, @code{Entry.delete()}, @code{Entry.icursor()}, @code{Entry.index()}, @code{Entry.insert()}, @code{Entry.xview()} に加え、このクラスには @code{ttk.Spinbox} で説明するいくつかのメソッドがあります。

@menu
* オプション: オプション<2>. 
* 仮想イベント: 仮想イベント<2>. 
* ttk.Spinbox: ttk Spinbox. 

@end menu

@node オプション<2>,仮想イベント<2>,,Spinbox
@anchor{library/tkinter ttk id1}@anchor{438e}
@subsubsection オプション


このウィジェットは以下の固有のオプションを受け付けます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

from

@tab

Float value.  If set, this is the minimum value to
which the decrement button will decrement.  Must be
spelled as @code{from_} when used as an argument, since
@code{from} is a Python keyword.

@item

to

@tab

Float value.  If set, this is the maximum value to
which the increment button will increment.

@item

increment

@tab

Float value.  Specifies the amount which the
increment/decrement buttons change the
value. Defaults to 1.0.

@item

@code{values}

@tab

Sequence of string or float values.  If specified,
the increment/decrement buttons will cycle through
the items in this sequence rather than incrementing
or decrementing numbers.

@item

wrap

@tab

Boolean value.  If @code{True}, increment and decrement
buttons will cycle from the @code{to} value to the
@code{from} value or the @code{from} value to the @code{to}
value, respectively.

@item

format

@tab

String value.  This specifies the format of numbers
set by the increment/decrement buttons.  It must be
in the form "%W.Pf", where W is the padded width of
the value, P is the precision, and '%' and 'f' are
literal.

@item

command

@tab

Python callable.  Will be called with no arguments
whenever either of the increment or decrement buttons
are pressed.

@end multitable


@node 仮想イベント<2>,ttk Spinbox,オプション<2>,Spinbox
@anchor{library/tkinter ttk id2}@anchor{438f}
@subsubsection 仮想イベント


The spinbox widget generates an `<<Increment>>' virtual event when the
user presses <Up>, and a `<<Decrement>>' virtual event when the user
presses <Down>.

@node ttk Spinbox,,仮想イベント<2>,Spinbox
@anchor{library/tkinter ttk ttk-spinbox}@anchor{4390}
@subsubsection ttk.Spinbox


@geindex Spinbox (tkinter.ttk のクラス)
@anchor{library/tkinter ttk tkinter ttk Spinbox}@anchor{d8d}
@deffn {クラス} tkinter.ttk.Spinbox

@geindex get() (tkinter.ttk.Spinbox のメソッド)
@anchor{library/tkinter ttk tkinter ttk Spinbox get}@anchor{4391}
@deffn {メソッド} get ()

Returns the current value of the spinbox.
@end deffn

@geindex set() (tkinter.ttk.Spinbox のメソッド)
@anchor{library/tkinter ttk tkinter ttk Spinbox set}@anchor{4392}
@deffn {メソッド} set (value)

Sets the value of the spinbox to `value'.
@end deffn
@end deffn

@node ノートブック,プログレスバー,Spinbox,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk notebook}@anchor{4393}
@subsubsection ノートブック


ノートブックウィジェットは複数のウィンドウを管理し、同時に 1 つのウィンドウを表示します。それぞれの子ウィンドウはタブの関連付けられていて、ユーザはそれを選択して表示されているウィンドウを切り替えます。

@menu
* オプション: オプション<3>. 
* タブオプション:: 
* タブ識別子:: 
* 仮想イベント: 仮想イベント<3>. 
* ttk.Notebook: ttk Notebook. 

@end menu

@node オプション<3>,タブオプション,,ノートブック
@anchor{library/tkinter ttk id3}@anchor{4394}
@subsubsection オプション


このウィジェットは以下の固有のオプションを受け付けます:


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

高さ

@tab

0 より大きな値が設定されている場合、 (内部のパディングやタブを含まない) ペイン領域に必要な高さを指定します。設定されていない場合、全てのペインの高さの最大値が使われます。

@item

padding

@tab

ノートブックの外周に付け足す追加の領域の量を指定します。パディングは最大 4 個の長さ指定のリストです: 左、上、右、下の順で指定します。4 個より少ない場合、デフォルトで下は上と、右は左と、上は左と同じ値が、それぞれ使われます。

@item

幅

@tab

0 より大きな値が指定されている場合、(内部のパディングを含まない) ペイン領域に必要な幅を指定します。設定されていない場合、全てのペインの幅の最大値が使われます。

@end multitable


@node タブオプション,タブ識別子,オプション<3>,ノートブック
@anchor{library/tkinter ttk tab-options}@anchor{4395}
@subsubsection タブオプション


タブ用のオプションもあります:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

state

@tab

"normal", "disabled", "hidden" のうちどれか 1 つです。 "disabled" の場合、タブは選択することができません。 "hidden" の場合、タブは表示されません。

@item

sticky

@tab

ペイン領域の中に子ウィンドウがどう置かれるかを指定します。指定する値は "n", "s", "e", "w" からなる 0 文字以上の文字列です。配置マネージャの @code{grid()} と同様に、それぞれの文字は子ウィンドウが (北、南、東、西の) どの辺に対して追随するかに対応しています。

@item

padding

@tab

ノートブックとこのペインの間に付け足す追加の領域の量を指定します。文法はこのウィジェットの padding オプションと同じです。

@item

text

@tab

タブに表示するテキストを指定します。

@item

image

@tab

タブに表示する画像を指定します。 @ref{437a,,Widget} のオプション image の説明を参照してください。

@item

compound

@tab

text オプションと image オプションが両方指定されているときにテキストに対して画像をどう表示するかを指定します。指定する値については @ref{437f,,Label Options} を参照してください。

@item

underline

@tab

テキスト中の下線を引く文字のインデックス (0 基点) を指定します。 @ref{4396,,Notebook.enable_traversal()} が呼ばれていた場合、下線が引かれた文字はショートカットとして使われます。

@end multitable


@node タブ識別子,仮想イベント<3>,タブオプション,ノートブック
@anchor{library/tkinter ttk tab-identifiers}@anchor{4397}
@subsubsection タブ識別子


@code{ttk.Notebook} のいくつかのメソッドにある `tab_id' は以下の形式を取ります:


@itemize *

@item 
0 からタブの数の間の整数

@item 
子ウィンドウの名前

@item 
タブを指し示す "@@x,y" という形式の位置指定

@item 
現在選択されているタブを指し示すリテラル文字列 "current"

@item 
タブ数を返すリテラル文字列 "end" (@ref{4398,,Notebook.index()} でのみ有効)
@end itemize

@node 仮想イベント<3>,ttk Notebook,タブ識別子,ノートブック
@anchor{library/tkinter ttk id4}@anchor{4399}
@subsubsection 仮想イベント


このウィジェットは新しいタブが選択された後に仮想イベント `<<NotebookTabChanged>>' を生成します。

@node ttk Notebook,,仮想イベント<3>,ノートブック
@anchor{library/tkinter ttk ttk-notebook}@anchor{439a}
@subsubsection ttk.Notebook


@geindex Notebook (tkinter.ttk のクラス)
@anchor{library/tkinter ttk tkinter ttk Notebook}@anchor{4378}
@deffn {クラス} tkinter.ttk.Notebook

@geindex add() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook add}@anchor{439b}
@deffn {メソッド} add (child, **kw)

ノートブックに新しいタブを追加します。

ウィンドウが現在ノートブックによって管理されているが隠れている場合、以前の位置に復元します。

利用可能なオプションのリストについては @ref{4395,,Tab Options} を参照してください。
@end deffn

@geindex forget() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook forget}@anchor{439c}
@deffn {メソッド} forget (tab_id)

`tab_id' で指定されたタブを削除します。関連付けられていたウィンドウは切り離され、管理対象でなくなります。
@end deffn

@geindex hide() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook hide}@anchor{439d}
@deffn {メソッド} hide (tab_id)

`tab_id' で指定されたタブを隠します。

タブは表示されませんが、関連付いているウィンドウはノートブックによって保持されていて、その設定も記憶されています。隠れたタブは @ref{439b,,add()} コマンドで復元できます。
@end deffn

@geindex identify() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook identify}@anchor{439e}
@deffn {メソッド} identify (x, y)

`x' `y' の位置にあるタブの名前を、そこにタブが無ければ空文字列を返します。
@end deffn

@geindex index() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook index}@anchor{4398}
@deffn {メソッド} index (tab_id)

`tab_id' で指定されたタブのインデックスを、 `tab_id' が文字列の "end" だった場合はタブの総数を返します。
@end deffn

@geindex insert() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook insert}@anchor{439f}
@deffn {メソッド} insert (pos, child, **kw)

指定された位置にペインを挿入します。

`pos' は文字列の "end" か整数のインデックスか管理されている子ウィンドウの名前です。 `child' が既にノートブックの管理対象だった場合、指定された場所に移動させます。

利用可能なオプションのリストについては @ref{4395,,Tab Options} を参照してください。
@end deffn

@geindex select() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook select}@anchor{43a0}
@deffn {メソッド} select (tab_id=None)

指定された `tab_id' を選択します。

関連付いている子ウィンドウは表示され、直前に選択されていたウィンドウは (もし異なれば) 表示されなくなります。 `tab_id' が指定されていない場合は、現在選択されているペインのウィジェット名を返します。
@end deffn

@geindex tab() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook tab}@anchor{43a1}
@deffn {メソッド} tab (tab_id, option=None, **kw)

指定された `tab_id' のオプションを問い合わせたり、変更したりします。

`kw' が与えられなかった場合、タブのオプション値の辞書を返します。 `option' が指定されていた場合、その `option' の値を返します。それ以外の場合は、オプションに対応する値が設定されます。
@end deffn

@geindex tabs() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook tabs}@anchor{43a2}
@deffn {メソッド} tabs ()

ノートブックに管理されているウィンドウのリストを返します。
@end deffn

@geindex enable_traversal() (tkinter.ttk.Notebook のメソッド)
@anchor{library/tkinter ttk tkinter ttk Notebook enable_traversal}@anchor{4396}
@deffn {メソッド} enable_traversal ()

このノートブックを含む最上位にあるウィンドウでのキーボード移動を可能にします。

これによりノートブックを含んだ最上位にあるウィンドウに対し、以下のキーバインディングが追加されます:


@itemize *

@item 
@code{Control}-@code{Tab}: 現在選択されているタブの 1 つ次のタブを選択します。

@item 
@code{Shift}-@code{Control}-@code{Tab}: 現在選択されているタブの 1 つ前のタブを選択します。

@item 
@code{Alt}-@code{K}: `K' があるタブの (下線が引かれた) ショートカットキーだとして、そのタブを選択します。
@end itemize

ネストしたノートブックも含め、1 つのウィンドウの最上位にある複数のノートブックのキーボード移動が可能になることもあります。しかしノートブック上の移動は、全てのペインが同じノートブックを親としているときのみ正しく動作します。
@end deffn
@end deffn

@node プログレスバー,セパレータ,ノートブック,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk progressbar}@anchor{43a3}
@subsubsection プログレスバー


@code{ttk.Progressbar} ウィジェットは長く走る処理の状態を表示します。このウィジェットは 2 つのモードで動作します: 1) 決定的モードでは、全ての処理の総量のうち完了した量を表示します。 2) 非決定的モードでは、今作業が進んでいることをユーザに示します。

@menu
* オプション: オプション<4>. 
* ttk.Progressbar: ttk Progressbar. 

@end menu

@node オプション<4>,ttk Progressbar,,プログレスバー
@anchor{library/tkinter ttk id5}@anchor{43a4}
@subsubsection オプション


このウィジェットは以下の固有のオプションを受け付けます:


@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

orient

@tab

"horizontal" もしくは "vertical" のいずれかです。プログレスバーの方向を指定します。

@item

length

@tab

プログレスバーの長さを指定します。 (水平方向の場合は幅、垂直方向の場合は高さです)

@item

mode

@tab

"determinate" か "indeterminate" のいずれかです。

@item

maximum

@tab

最大値を数値で指定します。デフォルトは 100 です。

@item

value

@tab

プログレスバーの現在値です。決定的 ("determinate") モードでは、完了した処理の量を表します。非決定的 ("indeterminate") モードでは、 `maximum' を法として解釈され、値が `maximum' に達したときにプログレスバーは 1 "サイクル" を完了したことになります。

@item

variable

@tab

value オプションとリンクさせる変数名です。指定されている場合、変数の値が変更されるとプログレスバーの値は自動的にその値に設定されます。

@item

phase

@tab

読み出し専用のオプションです。このウィジェットの値が 0 より大きく、かつ決定的モードでは最大値より小さいときに、ウィジェットが定期的にこのオプションの値を増加させます。このオプションは現在の画面テーマが追加のアニメーション効果を出すのに使います。

@end multitable


@node ttk Progressbar,,オプション<4>,プログレスバー
@anchor{library/tkinter ttk ttk-progressbar}@anchor{43a5}
@subsubsection ttk.Progressbar


@geindex Progressbar (tkinter.ttk のクラス)
@anchor{library/tkinter ttk tkinter ttk Progressbar}@anchor{4379}
@deffn {クラス} tkinter.ttk.Progressbar

@geindex start() (tkinter.ttk.Progressbar のメソッド)
@anchor{library/tkinter ttk tkinter ttk Progressbar start}@anchor{43a6}
@deffn {メソッド} start (interval=None)

自動増加モードを開始します: `interval' ミリ秒ごとに @ref{43a7,,Progressbar.step()} を繰り返し呼び出すタイマーイベントを設定します。引数で指定しない場合は、 `interval' はデフォルトで 50 ミリ秒になります。
@end deffn

@geindex step() (tkinter.ttk.Progressbar のメソッド)
@anchor{library/tkinter ttk tkinter ttk Progressbar step}@anchor{43a7}
@deffn {メソッド} step (amount=None)

プログレスバーの値を `amount' だけ増加させます。

引数で指定しない場合は、 `amount' はデフォルトで 1.0 になります。
@end deffn

@geindex stop() (tkinter.ttk.Progressbar のメソッド)
@anchor{library/tkinter ttk tkinter ttk Progressbar stop}@anchor{43a8}
@deffn {メソッド} stop ()

自動増加モードを停止します: このプログレスバーの @ref{43a6,,Progressbar.start()} で開始された繰り返しのタイマーイベントを全てキャンセルします。
@end deffn
@end deffn

@node セパレータ,サイズグリップ,プログレスバー,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk separator}@anchor{43a9}
@subsubsection セパレータ


@code{ttk.Separator} ウィジェットは水平もしくは垂直のセパレータを表示します。

@code{ttk.Widget} から継承したメソッド以外にメソッドを持ちません。

@menu
* オプション: オプション<5>. 

@end menu

@node オプション<5>,,,セパレータ
@anchor{library/tkinter ttk id6}@anchor{43aa}
@subsubsection オプション


このウィジェットは次の特定のオプションを受け付けます。


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

orient

@tab

"horizontal" か "vertical" のいずれかです。セパレータの方向を指定します。

@end multitable


@node サイズグリップ,ツリービュー,セパレータ,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk sizegrip}@anchor{43ab}
@subsubsection サイズグリップ


(グローボックスとしても知られる) @code{ttk.Sizegrip} ウィジェットを使用すると、つまみ部分を押してドラッグすることで、このウィジェットを含む最上位のウィンドウのサイズを変更できます。

このウィジェットは @code{ttk.Widget} から継承したもの以外のオプションとメソッドを持ちません。

@menu
* プラットフォーム固有のメモ:: 
* バグ:: 

@end menu

@node プラットフォーム固有のメモ,バグ,,サイズグリップ
@anchor{library/tkinter ttk platform-specific-notes}@anchor{43ac}
@subsubsection プラットフォーム固有のメモ



@itemize *

@item 
macOS では、最上位のウィンドウにはデフォルトで組み込みのサイズグリップが含まれています。組み込みのグリップが @code{Sizegrip} を隠してしまうので、 @code{Sizegrip} を追加しても問題ありません。
@end itemize

@node バグ,,プラットフォーム固有のメモ,サイズグリップ
@anchor{library/tkinter ttk bugs}@anchor{43ad}
@subsubsection バグ



@itemize *

@item 
このウィジェットを含む最上位のウィンドウの位置がスクリーンの右端や下端に対して相対的に指定されている場合 (例: ....) 、 @code{Sizegrip} ウィジェットはウィンドウのサイズ変更をしません。

@item 
このウィジェットは "南東" 方向のサイズ変更しかサポートしていません。
@end itemize

@node ツリービュー,Ttk スタイル,サイズグリップ,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk treeview}@anchor{43ae}
@subsubsection ツリービュー


@code{ttk.Treeview} ウィジェットは階層のある要素 (アイテム) の集まりを表示します。それぞれの要素はテキストラベル、オプションの画像、オプションのデータのリストを持っています。データはラベルの後に続くカラムに表示されます。

データが表示される順序はウィジェットの @code{displaycolumns} オプションで制御されます。ツリーウィジェットはカラムヘッダを表示することもできます。カラムには数字もしくはウィジェットの columns オプションにある名前でアクセスできます。 @ref{43af,,Column Identifiers} を参照してください。

それぞれの要素は一意な名前で識別されます。要素の作成時に識別子が与えられなかった場合、ウィジェットが要素の識別子を生成します。このウィジェットには @code{@{@}} という名前の特別なルート要素があります。ルート要素自身は表示されません; その子要素たちが階層の最上位に現れます。

それぞれの要素はタグのリストも持っていて、イベントバインディングと個別の要素を関連付け、要素の見た目を管理するのに使えます。

ツリービューウィジェットは水平方向と垂直方向のスクロールをサポートしていて、 @ref{437e,,Scrollable Widget Options} に記述してあるオプションと @ref{43b0,,Treeview.xview()} メソッドおよび @ref{43b1,,Treeview.yview()} メソッドが使えます。

@menu
* オプション: オプション<6>. 
* 要素オプション:: 
* タグオプション:: 
* カラム識別子:: 
* 仮想イベント: 仮想イベント<4>. 
* ttk.Treeview: ttk Treeview. 

@end menu

@node オプション<6>,要素オプション,,ツリービュー
@anchor{library/tkinter ttk id7}@anchor{43b2}
@subsubsection オプション


このウィジェットは以下の固有のオプションを受け付けます:


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

columns

@tab

カラム数とその名前を指定するカラム識別子のリストです。

@item

displaycolumns

@tab

どのデータカラムをどの順序で表示するかを指定する、 (名前もしくは整数のインデックスの) カラム識別子のリストか、文字列 "#all" です。

@item

高さ

@tab

表示する行数を指定します。メモ: 表示に必要な幅はカラム幅の合計から決定されます。

@item

padding

@tab

ウィジェットの内部のパディングのサイズを指定します。パディングは最大 4 個の長さ指定のリストです。

@item

selectmode

@tab

組み込みのクラスバインディングが選択状態をどう管理するかを指定します。設定する値は "extended", "browse", "none" のどれか 1 つです。 "extended" に設定した場合 (デフォルト)、複数の要素が選択できます。 "browse" に設定した場合、同時に 1 つの要素しか選択できません。 "none" に設定した場合、選択を変更することはできません。

このオプションの値によらず、アプリケーションのコードと関連付けられているタグからは好きなように選択状態を設定できます。

@item

show

@tab

ツリーのどの要素を表示するかを指定する、以下にある値を 0 個以上含むリストです。


@itemize *

@item 
tree: カラム #0 にツリーのラベルを表示します。

@item 
headings: ヘッダ行を表示します。
@end itemize

デフォルトは "tree headings" 、つまり全ての要素を表示します。

`メモ': show="tree" が指定されていない場合でも、カラム #0 は常にツリーカラムを参照します。

@end multitable


@node 要素オプション,タグオプション,オプション<6>,ツリービュー
@anchor{library/tkinter ttk item-options}@anchor{43b3}
@subsubsection 要素オプション


以下の要素オプションは、ウィジェットの insert コマンドと item コマンドで要素に対して指定できます。


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

text

@tab

アイテムに表示するテキストラベルです。

@item

image

@tab

ラベルの左に表示される Tk 画像です。

@item

@code{values}

@tab

要素に関連付けられている値のリストです。

それぞれの要素はウィジェットの columns オプションと同じ数の値を持たなければいけません。 columns オプションより少ない場合、残りの値は空として扱われます。 columns オプションより多い場合、余計な値は無視されます。

@item

open

@tab

要素の子供を表示するか隠すかを指示する @code{True}/@code{False} 値です。

@item

tags

@tab

この要素に関連付いているタグのリストです。

@end multitable


@node タグオプション,カラム識別子,要素オプション,ツリービュー
@anchor{library/tkinter ttk tag-options}@anchor{43b4}
@subsubsection タグオプション


以下のオプションはタグに対して設定できます:


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

説明

@item

foreground

@tab

テキストの色を指定します。

@item

background

@tab

セルや要素の背景色を指定します。

@item

font

@tab

テキストを描画するときに使うフォントを指定します。

@item

image

@tab

要素の image オプションが空だった場合に使用する画像を指定します。

@end multitable


@node カラム識別子,仮想イベント<4>,タグオプション,ツリービュー
@anchor{library/tkinter ttk column-identifiers}@anchor{43af}
@subsubsection カラム識別子


カラム識別子は以下のいずれかの形式を取ります:


@itemize *

@item 
columns オプションのリストにある名前。

@item 
n 番目のデータカラムを指し示す整数 n 。

@item 
n を整数として n 番目の表示されているカラムを指し示す #n という形式の文字列。
@end itemize

注釈:


@itemize *

@item 
要素のオプション値は実際に格納されている順序とは違った順序で表示されることがあります。

@item 
show="tree" が指定されていない場合でも、カラム #0 は常にツリーカラムを指しています。
@end itemize

データカラムを指す数字は、要素の values オプションのリストのインデックスです; 表示カラムを指す数字は、値が表示されているツリーのカラム番号です。ツリーラベルはカラム #0 に表示されます。 displaycolumns オプションが設定されていない場合は、 n 番目のデータカラムはカラム #n+1 に表示されます。再度言っておくと、 `カラム #0 は常にツリーカラムを指します' 。

@node 仮想イベント<4>,ttk Treeview,カラム識別子,ツリービュー
@anchor{library/tkinter ttk id8}@anchor{43b5}
@subsubsection 仮想イベント


ツリービューは以下の仮想イベントを生成します。


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Event

@tab

説明

@item

<<TreeviewSelect>>

@tab

選択状態が変更されたときに生成されます。

@item

<<TreeviewOpen>>

@tab

フォーカスが当たっている要素に open=True が設定される直前に生成されます。

@item

<<TreeviewClose>>

@tab

フォーカスが当たっている要素に open=False が設定された直後に生成されます。

@end multitable


@ref{43b6,,Treeview.focus()} メソッドと @ref{c86,,Treeview.selection()} メソッドは変更を受けた要素を判別するのに使えます。

@node ttk Treeview,,仮想イベント<4>,ツリービュー
@anchor{library/tkinter ttk ttk-treeview}@anchor{43b7}
@subsubsection ttk.Treeview


@geindex Treeview (tkinter.ttk のクラス)
@anchor{library/tkinter ttk tkinter ttk Treeview}@anchor{c87}
@deffn {クラス} tkinter.ttk.Treeview

@geindex bbox() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview bbox}@anchor{43b8}
@deffn {メソッド} bbox (item, column=None)

(ツリービューウィジェットのウィンドウを基準として) 指定された `item' のバウンディングボックス情報を (x 座標, y 座標, 幅, 高さ) の形式で返します。

`column' が指定されている場合は、セルのバウンディングボックスを返します。 (例えば、閉じた状態の要素の子供であったり、枠外にスクロールされていて) `item' が見えなくなっている場合は、空文字列が返されます。
@end deffn

@geindex get_children() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview get_children}@anchor{43b9}
@deffn {メソッド} get_children (item=None)

`item' の子要素のリストを返します。

`item' が指定されていなかった場合は、ルート要素の子供が返されます。
@end deffn

@geindex set_children() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview set_children}@anchor{43ba}
@deffn {メソッド} set_children (item, *newchildren)

`item' の子要素を `newchildren' で置き換えます。

`item' にいる子供のうち `newchildren' にないものはツリーから切り離されます。 `newchildren' にあるどの要素も `item' の祖先であってはいけません。 `newchildren' を指定しなかった場合は、 `item' の子要素が全て切り離されることに注意してください。
@end deffn

@geindex column() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview column}@anchor{43bb}
@deffn {メソッド} column (column, option=None, **kw)

指定した `column' のオプションを問い合わせたり、変更したりします。

`kw' が与えられなかった場合は、カラムのオプション値の辞書が返されます。 `option' が指定されていた場合は、その `option' の値が返されます。それ以外の場合は、オプションに値を設定します。

設定できるオプションとその値は次の通りです:


@table @asis

@item `id'

カラム名を返します。これは読み出し専用のオプションです。

@item `anchor': One of the standard Tk anchor values.

このカラムでセルに対してテキストをどう配置するかを指定します。

@item `minwidth': width

カラムの最小幅をピクセル単位で表したものです。ツリービューウィジェットは、ウィジェットのサイズが変更されたりカラムをユーザがドラッグして移動させたりしたときに、このオプションで指定した幅より狭くすることはありません。

@item `stretch': @code{True}/@code{False}

ウィジェットがサイズ変更されたとき、カラムの幅をそれに合わせるかどうかを指定します。

@item `width': width

カラムの幅をピクセル単位で表したものです。
@end table

ツリーカラムの設定を行うには、 column = "#0" を付けてこのメソッドを呼び出してください。
@end deffn

@geindex delete() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview delete}@anchor{43bc}
@deffn {メソッド} delete (*items)

指定された `items' とその子孫たち全てを削除します。

ルート要素は削除されません。
@end deffn

@geindex detach() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview detach}@anchor{43bd}
@deffn {メソッド} detach (*items)

指定された `items' を全てツリーから切り離します。

その要素と子孫たちは依然として存在していて、ツリーの別の場所に再度挿入することができますが、隠された状態になり表示はされません。

ルート要素は切り離されません。
@end deffn

@geindex exists() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview exists}@anchor{43be}
@deffn {メソッド} exists (item)

指定された `item' がツリーの中にあれば @code{True} を返します。
@end deffn

@geindex focus() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview focus}@anchor{43b6}
@deffn {メソッド} focus (item=None)

`item' が指定されていた場合は、 `item' にフォーカスを当てます。そうでない場合は、現在フォーカスが当たっている要素が、どの要素にもフォーカスが当たっていない場合は '@w{'} が返されます。
@end deffn

@geindex heading() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview heading}@anchor{43bf}
@deffn {メソッド} heading (column, option=None, **kw)

指定された `column' の heading のオプションを問い合わせたり、変更したりします。

`kw' が与えられなかった場合は、見出しのオプション値の辞書が返されます。 `option' が指定されている場合は、 `option' の値が返されます。それ以外の場合は、オプションに値を設定します。

設定できるオプションとその値は次の通りです:


@table @asis

@item `text': text

カラムの見出しに表示するテキスト。

@item `image': imageName

カラムの見出しの右に表示する画像を指定します。

@item `anchor': anchor

見出しのテキストをどう配置するかを指定します。標準の Tk anchor の値です。

@item `command': callback

見出しラベルがクリックされたときに実行されるコールバックです。
@end table

ツリーカラムの見出しの設定を行うには、 column = "#0" を付けてこのメソッドを呼び出してください。
@end deffn

@geindex identify() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview identify}@anchor{43c0}
@deffn {メソッド} identify (component, x, y)

`x' `y' で与えられた場所にある指定された `component' の説明を返します。その場所に指定された `component' が無い場合は空文字列を返します。 (訳注: component には "region", "item", "column", "row", "element" が指定でき、それぞれ "cell", "heading" などの場所の名前、要素の識別子、 #n という形式のカラム名、その行にある要素の識別子、 "text", "padding" などの画面構成要素の名前を返します。)
@end deffn

@geindex identify_row() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_row}@anchor{43c1}
@deffn {メソッド} identify_row (y)

y 座標が `y' の位置にある要素の識別子を返します。
@end deffn

@geindex identify_column() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_column}@anchor{43c2}
@deffn {メソッド} identify_column (x)

x 座標が `x' の位置にあるセルのデータカラムの識別子を返します。

ツリーカラムは #0 という識別子を持ちます。
@end deffn

@geindex identify_region() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_region}@anchor{43c3}
@deffn {メソッド} identify_region (x, y)

以下のうち 1 つを返します:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

region

@tab

意味

@item

heading

@tab

ツリーの見出し領域

@item

separator

@tab

2 つのカラム見出しの間のスペース

@item

tree

@tab

ツリーの領域

@item

cell

@tab

データセル

@end multitable


使用可能バージョン: Tk 8.6
@end deffn

@geindex identify_element() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_element}@anchor{43c4}
@deffn {メソッド} identify_element (x, y)

`x' `y' の位置にある画面構成要素の名前を返します。

使用可能バージョン: Tk 8.6
@end deffn

@geindex index() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview index}@anchor{43c5}
@deffn {メソッド} index (item)

親要素の子要素リストの中での `item' のインデックスを返します。
@end deffn

@geindex insert() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview insert}@anchor{43c6}
@deffn {メソッド} insert (parent, index, iid=None, **kw)

新しい要素を作り、その要素の識別子を返します。

`parent' は親となる要素の識別子で、空文字列にすると新しい要素を最上位に作成します。 `index' は整数もしくは "end" という値で、それによって親要素の子要素リストのどこに新しい要素を挿入するかを指定します。 `index' が 0 以下だった場合は、新しい要素は先頭に挿入されます; `index' が現在の子要素の数以上だった場合は末尾に挿入されます。 `iid' が指定された場合は、要素の識別子として使われます; `iid' はまだツリーに存在していないものに限ります。それ以外の場合は、一意な識別子が生成されます。

See @ref{43b3,,Item Options} for the list of available options.
@end deffn

@geindex item() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview item}@anchor{43c7}
@deffn {メソッド} item (item, option=None, **kw)

指定された `item' のオプションを問い合わせたり、変更したりします。

オプションが与えられなかった場合は、要素のオプションと値が辞書の形で返されます。 `option' が指定された場合は、そのオプションの値が返されます。それ以外の場合は、 `kw' で与えられたようにオプションに値が設定されます。
@end deffn

@geindex move() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview move}@anchor{43c8}
@deffn {メソッド} move (item, parent, index)

`item' を `parent' の子要素リストの `index' の位置に移動します。

要素を自身の子孫の下に移動させるのは許されていません。 `index' が 0 以下の場合、 `item' は先頭に移動されます; 子要素の数以上だった場合、末尾に移動されます。 `item' が切り離された状態の場合は、再度取り付けられます。
@end deffn

@geindex next() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview next}@anchor{43c9}
@deffn {メソッド} next (item)

`item' の 1 つ下の兄弟の識別子を、 `item' が親にとって一番下の子供だった場合 '@w{'} を返します。
@end deffn

@geindex parent() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview parent}@anchor{43ca}
@deffn {メソッド} parent (item)

`item' の親の識別子を、 `item' が階層の最上位にいた場合 '@w{'} を返します。
@end deffn

@geindex prev() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview prev}@anchor{43cb}
@deffn {メソッド} prev (item)

`item' の 1 つ上の兄弟の識別子を、 `item' が親にとって一番上の子供だった場合 '@w{'} を返します。
@end deffn

@geindex reattach() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview reattach}@anchor{43cc}
@deffn {メソッド} reattach (item, parent, index)

@ref{43c8,,Treeview.move()} のエイリアスです。
@end deffn

@geindex see() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview see}@anchor{43cd}
@deffn {メソッド} see (item)

`item' を見える状態にします。

`item' の全ての子孫の open オプションを @code{True} にし、必要であれば `item' がツリーの見える範囲に来るようにウィジェットをスクロールさせます。
@end deffn

@geindex selection() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview selection}@anchor{c86}
@deffn {メソッド} selection ()

Returns a tuple of selected items.


バージョン 3.8 で変更: @code{selection()} no longer takes arguments.  For changing the selection
state use the following selection methods.

@end deffn

@geindex selection_set() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_set}@anchor{c88}
@deffn {メソッド} selection_set (*items)

新しく選択状態の要素が `items' になります。


バージョン 3.6 で変更: `items' は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

@end deffn

@geindex selection_add() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_add}@anchor{43ce}
@deffn {メソッド} selection_add (*items)

選択状態の要素として `items' を追加します。


バージョン 3.6 で変更: `items' は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

@end deffn

@geindex selection_remove() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_remove}@anchor{43cf}
@deffn {メソッド} selection_remove (*items)

選択状態の要素から `items' を取り除きます。


バージョン 3.6 で変更: `items' は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

@end deffn

@geindex selection_toggle() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_toggle}@anchor{43d0}
@deffn {メソッド} selection_toggle (*items)

`items' のそれぞれの要素の選択状態を入れ替えます。


バージョン 3.6 で変更: `items' は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

@end deffn

@geindex set() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview set}@anchor{43d1}
@deffn {メソッド} set (item, column=None, value=None)

1 引数で呼び出された場合、指定された `item' のカラムと値のペアからなる辞書を返します。 2 引数で呼び出された場合、指定された `column' の現在の値を返します。 3 引数で呼び出された場合、与えられた `item' の `column' を指定された値 `value' に設定します。
@end deffn

@geindex tag_bind() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview tag_bind}@anchor{43d2}
@deffn {メソッド} tag_bind (tagname, sequence=None, callback=None)

与えられたイベント `sequence' 用のコールバックをタグ `tagname' にバインドします。イベントが要素に渡ってきたときに、要素の tags オプションのそれぞれのコールバックが呼び出されます。
@end deffn

@geindex tag_configure() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview tag_configure}@anchor{43d3}
@deffn {メソッド} tag_configure (tagname, option=None, **kw)

指定された `tagname' のオプションを問い合わせたり、変更したりします。

`kw' が与えられなかった場合、 `tagname' のオプション設定を辞書の形で返します。 `option' が指定された場合、指定された `tagname' の `option' の値を返します。それ以外の場合、与えられた `tagname' のオプションに値を設定します。
@end deffn

@geindex tag_has() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview tag_has}@anchor{43d4}
@deffn {メソッド} tag_has (tagname, item=None)

`item' が指定されていた場合、指定された `item' が与えられた `tagname' を持っているかどうかに従って 1 または 0 が返されます。そうでない場合、指定されたタグを持つ全ての要素のリストを返します。

使用可能バージョン: Tk 8.6
@end deffn

@geindex xview() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview xview}@anchor{43b0}
@deffn {メソッド} xview (*args)

ツリービューの水平方向の位置を問い合わせたり、変更したりします。
@end deffn

@geindex yview() (tkinter.ttk.Treeview のメソッド)
@anchor{library/tkinter ttk tkinter ttk Treeview yview}@anchor{43b1}
@deffn {メソッド} yview (*args)

ツリービューの垂直方向の位置を問い合わせたり、変更したりします。
@end deffn
@end deffn

@node Ttk スタイル,,ツリービュー,tkinter ttk --- Tk のテーマ付きウィジェット
@anchor{library/tkinter ttk ttk-styling}@anchor{43d5}@anchor{library/tkinter ttk ttkstyling}@anchor{437b}
@subsubsection Ttk スタイル


@code{ttk} のそれぞれのウィジェットにはスタイルが関連付けられていて、それと動的もしくはデフォルトで設定される要素のオプションによってウィジェットを構成する要素とその配置を指定します。デフォルトではスタイル名はウィジェットのクラス名と同じですが、ウィジェットの style オプションで上書きすることができます。ウィジェットのクラス名が分からない場合は、 @code{Misc.winfo_class()} (somewidget.winfo_class()) メソッドを使ってください。


@subsubheading 参考



@table @asis

@item Tcl'2004 conference のプレゼンテーション@footnote{https://tktable.sourceforge.net/tile/tile-tcl2004.pdf}

この文書ではテーマエンジンがどう動くかを説明しています
@end table


@geindex Style (tkinter.ttk のクラス)
@anchor{library/tkinter ttk tkinter ttk Style}@anchor{560}
@deffn {クラス} tkinter.ttk.Style

このクラスはスタイルデータベースを操作するために使われます。

@geindex configure() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style configure}@anchor{43d6}
@deffn {メソッド} configure (style, query_opt=None, **kw)

`style' の指定されたオプションのデフォルト値を問い合わせたり、設定したりします。

`kw' のそれぞれのキーはオプション名で値はそのオプションの値の文字列です。

例えば、全てのデフォルトのボタンをパディングのある平らな見た目にし、背景の色を変更するには以下のようにします:

@example
from tkinter import ttk
import tkinter

root = tkinter.Tk()

ttk.Style().configure("TButton", padding=6, relief="flat",
   background="#ccc")

btn = ttk.Button(text="Sample")
btn.pack()

root.mainloop()
@end example
@end deffn

@geindex map() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style map}@anchor{1ce6}
@deffn {メソッド} map (style, query_opt=None, **kw)

`style' の指定されたオプションの動的な値を問い合わせたり、設定したりします。

`kw' のそれぞれのキーはオプション名で、値はタプルやリストや何か他のお好みのものでグループ化された状態仕様 (statespec) を要素とするリストやタプルです。状態仕様は 1 つもしくは複数の状態と値の組み合わせです。

以下のように、例を示す方がわかりやすいでしょう:

@example
import tkinter
from tkinter import ttk

root = tkinter.Tk()

style = ttk.Style()
style.map("C.TButton",
    foreground=[('pressed', 'red'), ('active', 'blue')],
    background=[('pressed', '!disabled', 'black'), ('active', 'white')]
    )

colored_btn = ttk.Button(text="Test", style="C.TButton").pack()

root.mainloop()
@end example

あるオプションに対する状態と値の組 (states, value) の並び順はスタイルに影響を与えることに注意してください。例えば、foreground オプションの順序を @code{[('active', 'blue'), ('pressed', 'red')]} に変更した場合、ウィジェットがアクティブもしくは押された状態のとき前面が青くなります。
@end deffn

@geindex lookup() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style lookup}@anchor{43d7}
@deffn {メソッド} lookup (style, option, state=None, default=None)

`style' の指定された `option' の値を返します。

`state' を指定する場合は、1 つ以上の状態名の並びである必要があります。 `default' 引数が指定されていた場合は、オプション指定が見付からなかったときに代わりに返される値として使われます。

デフォルトでボタンがどのフォントを使うかを調べるには、以下のように実行します:

@example
from tkinter import ttk

print(ttk.Style().lookup("TButton", "font"))
@end example
@end deffn

@geindex layout() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style layout}@anchor{43d8}
@deffn {メソッド} layout (style, layoutspec=None)

与えられた `style' でのウィジェットのレイアウトを定義します。 `layoutspec' が省略されていた場合は、与えられたスタイルのレイアウト仕様を返します。

`layoutspec' を指定する場合は、リストもしくは (文字列を除いた) 何か他のシーケンス型である必要があります。それぞれの要素はタプルで、レイアウト名を 1 番目の要素とし、2 番目の要素は @ref{43d9,,Layouts} で説明されているフォーマットである必要があります。

フォーマットを理解するために以下の例を見てください (何かを使い易くするための例ではありません):

@example
from tkinter import ttk
import tkinter

root = tkinter.Tk()

style = ttk.Style()
style.layout("TMenubutton", [
   ("Menubutton.background", None),
   ("Menubutton.button", @{"children":
       [("Menubutton.focus", @{"children":
           [("Menubutton.padding", @{"children":
               [("Menubutton.label", @{"side": "left", "expand": 1@})]
           @})]
       @})]
   @}),
])

mbtn = ttk.Menubutton(text='Text')
mbtn.pack()
root.mainloop()
@end example
@end deffn

@geindex element_create() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style element_create}@anchor{55f}
@deffn {メソッド} 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.6 on Windows.

"image" が使われた場合、 `args' はデフォルトの画像名の後ろに状態仕様と値のペア (これが画像仕様です) を並べたものである必要があります。 `kw' には以下のオプションが指定できます:


@table @asis

@item border=padding

padding は 4 個以下の整数のリストで、それぞれ左、上、右、下の縁の幅を指定します。

@item height=height

要素の最小の高さを指定します。0 より小さい場合は、画像の高さをデフォルトとして使用します。

@item padding=padding

要素の内部のパディングを指定します。指定されない場合は、 border の値がデフォルトとして使われます。

@item sticky=spec

1 つ外側の枠に対し画像をどう配置するかを指定します。 spec は "n", "s", "w", "e" の文字を 0 個以上含みます。

@item width=width

要素の最小の幅を指定します。0 より小さい場合は、画像の幅をデフォルトとして使用します。
@end table

以下はプログラム例です:

@example
img1 = tkinter.PhotoImage(master=root, file='button.png')
img1 = tkinter.PhotoImage(master=root, file='button-pressed.png')
img1 = tkinter.PhotoImage(master=root, file='button-active.png')
style = ttk.Style(root)
style.element_create('Button.button', 'image',
                     img1, ('pressed', img2), ('active', img3),
                     border=(2, 4), sticky='we')
@end example

`etype' の値として "from" が使われた場合は、 @ref{55f,,element_create()} が現在の要素を複製します。 `args' は要素の複製元のテーマの名前と、オプションで複製する要素を含んでいる必要があります。複製元の要素が指定されていなかった場合、空要素が使用され、 `kw' は破棄されます。

以下はプログラム例です:

@example
style = ttk.Style(root)
style.element_create('plain.background', 'from', 'default')
@end example

If "vsapi" is used as the value of `etype', @ref{55f,,element_create()}
will create a new element in the current theme whose visual appearance
is drawn using the Microsoft Visual Styles API which is responsible
for the themed styles on Windows XP and Vista.
`args' is expected to contain the Visual Styles class and part as
given in the Microsoft documentation followed by an optional sequence
of tuples of ttk states and the corresponding Visual Styles API state
value.
`kw' may have the following options:


@table @asis

@item padding=padding

Specify the element's interior padding.
`padding' is a list of up to four integers specifying the left,
top, right and bottom padding quantities respectively.
If fewer than four elements are specified, bottom defaults to top,
right defaults to left, and top defaults to left.
In other words, a list of three numbers specify the left, vertical,
and right padding; a list of two numbers specify the horizontal
and the vertical padding; a single number specifies the same
padding all the way around the widget.
This option may not be mixed with any other options.

@item margins=padding

Specifies the elements exterior padding.
`padding' is a list of up to four integers specifying the left, top,
right and bottom padding quantities respectively.
This option may not be mixed with any other options.

@item width=width

Specifies the width for the element.
If this option is set then the Visual Styles API will not be queried
for the recommended size or the part.
If this option is set then `height' should also be set.
The `width' and `height' options cannot be mixed with the `padding'
or `margins' options.

@item height=height

Specifies the height of the element.
See the comments for `width'.
@end table

以下はプログラム例です:

@example
style = ttk.Style(root)
style.element_create('pin', 'vsapi', 'EXPLORERBAR', 3, [
                     ('pressed', '!selected', 3),
                     ('active', '!selected', 2),
                     ('pressed', 'selected', 6),
                     ('active', 'selected', 5),
                     ('selected', 4),
                     ('@w{'}, 1)])
style.layout('Explorer.Pin',
             [('Explorer.Pin.pin', @{'sticky': 'news'@})])
pin = ttk.Checkbutton(style='Explorer.Pin')
pin.pack(expand=True, fill='both')
@end example


バージョン 3.13 で変更: Added support of the "vsapi" element factory.

@end deffn

@geindex element_names() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style element_names}@anchor{43da}
@deffn {メソッド} element_names ()

現在のテーマに定義されている要素のリストを返します。
@end deffn

@geindex element_options() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style element_options}@anchor{43db}
@deffn {メソッド} element_options (elementname)

`elementname' のオプションのリストを返します。
@end deffn

@geindex theme_create() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style theme_create}@anchor{43dc}
@deffn {メソッド} theme_create (themename, parent=None, settings=None)

新しいテーマを作成します。

`themename' が既に存在していた場合はエラーになります。 `parent' が指定されていた場合は、新しいテーマは親テーマからスタイルや要素やレイアウトを継承します。 `settings' が指定された場合は、 @ref{43dd,,theme_settings()} で使われるのと同じ形式である必要があります。
@end deffn

@geindex theme_settings() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style theme_settings}@anchor{43dd}
@deffn {メソッド} theme_settings (themename, settings)

一時的に現在のテーマを `themename' に設定し、指定された `settings' を適用した後、元のテーマを復元します。

`settings' のそれぞれのキーはスタイル名で値はさらに 'configure', 'map', 'layout', 'element create' をキーとして持ち、その値はそれぞれ @ref{43d6,,Style.configure()}, @ref{1ce6,,Style.map()}, @ref{43d8,,Style.layout()}, @ref{55f,,Style.element_create()} メソッドで指定するのと同じ形式である必要があります。

例として、コンボボックスの default テーマを少し変更してみましょう

@example
from tkinter import ttk
import tkinter

root = tkinter.Tk()

style = ttk.Style()
style.theme_settings("default", @{
   "TCombobox": @{
       "configure": @{"padding": 5@},
       "map": @{
           "background": [("active", "green2"),
                          ("!disabled", "green4")],
           "fieldbackground": [("!disabled", "green3")],
           "foreground": [("focus", "OliveDrab1"),
                          ("!disabled", "OliveDrab2")]
       @}
   @}
@})

combo = ttk.Combobox().pack()

root.mainloop()
@end example
@end deffn

@geindex theme_names() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style theme_names}@anchor{43de}
@deffn {メソッド} theme_names ()

全ての既存のテーマのリストを返します。
@end deffn

@geindex theme_use() (tkinter.ttk.Style のメソッド)
@anchor{library/tkinter ttk tkinter ttk Style theme_use}@anchor{43df}
@deffn {メソッド} theme_use (themename=None)

`themename' が与えられなかった場合は、現在使用中のテーマ名を返します。そうでない場合は、現在のテーマを `themename' に設定し、全てのウィジェットを再描画し、 <<ThemeChanged>> イベントを発生させます。
@end deffn
@end deffn

@menu
* レイアウト:: 

@end menu

@node レイアウト,,,Ttk スタイル
@anchor{library/tkinter ttk layouts}@anchor{43d9}
@subsubsection レイアウト


A layout can be just @code{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.

設定できるオプションとその値は次の通りです:


@table @asis

@item `side': whichside

要素を空間のどちら側に配置するかを指定します; top, right, bottom, left のどれか 1 つです。省略された場合は、要素は空間全体を占めます。

@item `sticky': nswe

配分された空間の内部に要素をどう配置するかを指定します。

@item `unit': 0 or 1

1 に設定されると、 @ref{4384,,Widget.identify()} などには要素とその子で単一の要素として扱われます。これは、グリップのついたスクロールバーサムのようなものに使われます。

@item `children': [sublayout... ]

要素の内部に配置する要素のリストを指定します。リストのそれぞれの要素はタプル (もしくは他のシーケンス型) で、それの 1 番目の要素はレイアウト名でそれ以降は @ref{43d9,,Layout} です。
@end table
@anchor{library/tkinter ttk layout}@anchor{43e0}
@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node IDLE --- Python のエディタとシェル<2>,turtle --- Turtle graphics,tkinter ttk --- Tk のテーマ付きウィジェット,Graphical user interfaces with Tk
@anchor{library/idle doc}@anchor{43e1}@anchor{library/idle idle}@anchor{1217}@anchor{library/idle idle-python-editor-and-shell}@anchor{43e2}@anchor{library/idle translation-repo}@anchor{43e3}
@subsection IDLE --- Python のエディタとシェル


`ソースコード:' Lib/idlelib/@footnote{https://github.com/python/cpython/tree/3.14/Lib/idlelib/}

@geindex IDLE
@geindex Python Editor
@geindex Integrated Development Environment

@c Remember to update Lib/idlelib/help.html with idlelib.help.copy_strip() when modifying this file.


__________________________________________________________________


IDLE は Python の統合開発環境で、学習用環境です。

IDLE は次のような特徴があります:


@itemize *

@item 
クロスプラットホーム: Windows, Unix, macOS で動作します

@item 
コード入力、出力、エラーメッセージの色付け機能を持った Python shell (対話的インタプリタ) ウィンドウ

@item 
多段 Undo、 Python 対応の色づけ、自動的な字下げ、呼び出し情報の表示、自動補完、他たくさんの機能をもつマルチウィンドウ・テキストエディタ

@item 
任意のウィンドウ内での検索、エディタウィンドウ内での置換、複数ファイルを跨いだ検索 (grep)

@item 
永続的なブレイクポイント、ステップ実行、グローバルとローカル名前空間の視覚化機能を持ったデバッガ

@item 
設定、ブラウザ群、ほかダイアログ群
@end itemize

The IDLE application is implemented in the @ref{77,,idlelib} package.

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@menu
* メニュー:: 
* Editing and Navigation:: 
* Startup and Code Execution:: 
* Help and Preferences:: 
* idlelib: idlelib --- implementation of IDLE application. implementation of IDLE application

@end menu

@node メニュー,Editing and Navigation,,IDLE --- Python のエディタとシェル<2>
@anchor{library/idle menus}@anchor{43e4}
@subsubsection メニュー


IDLE には2種類のメインウィンドウ、Shell ウィンドウと Editor ウィンドウがあります。
Editor ウィンドウは同時に複数開けます。
Windows と Linux では、それぞれ個別のトップメニューがあります。
後で解説するそれぞれのメニューは、ウィンドウがどちらのウィンドウタイプなのかを示しています。

ファイル内の編集 (Edit) => 検索 (Find) で使われるような出力ウィンドウ (Output ウィンドウ) は editor ウィンドウのサブタイプで、 Editor ウィンドウと同じトップメニューを持ちますが、デフォルトタイトルとコンテキストメニューが違います。

On macOS, there is one application menu.  It dynamically changes according
to the window currently selected.  It has an IDLE menu, and some entries
described below are moved around to conform to Apple guidelines.

@menu
* File メニュー (Shell ウィンドウ、Editor ウィンドウ): File メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Edit メニュー (Shell ウィンドウ、Editor ウィンドウ): Edit メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Format メニュー (Shell ウィンドウ、Editor ウィンドウ): Format メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Run メニュー (Editor ウィンドウのみ): Run メニュー Editor ウィンドウのみ. 
* Shell メニュー (Shell ウィンドウのみ): Shell メニュー Shell ウィンドウのみ. 
* Debug メニュー (Shell ウィンドウのみ): Debug メニュー Shell ウィンドウのみ. 
* Options メニュー (Shell ウィンドウ、Editor ウィンドウ): Options メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Window メニュー (Shell ウィンドウ、Editor ウィンドウ): Window メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Help メニュー (Shell ウィンドウ、Editor ウィンドウ): Help メニュー Shell ウィンドウ、Editor ウィンドウ. 
* Context menus:: 

@end menu

@node File メニュー Shell ウィンドウ、Editor ウィンドウ,Edit メニュー Shell ウィンドウ、Editor ウィンドウ,,メニュー
@anchor{library/idle file-menu-shell-and-editor}@anchor{43e5}
@subsubsection File メニュー (Shell ウィンドウ、Editor ウィンドウ)



@table @asis

@item New File [新規ファイル]

新しいファイル編集ウィンドウを作成します。

@item Open... [開く...]

Open ダイアログを使って既存のファイルをオープンします。

@item Open Module... [モジュールを開く...]

既存のモジュールをオープンします (sys.path を検索します)。

@item Recent Files [最近使ったファイル]

最近使ったファイルのリストを開きます。ファイルを一つクリックするとそれを開きます。
@end table

@geindex Module browser
@geindex Path browser


@table @asis

@item Module Browser

現在 Editor が開いているファイル内にあるクラス、関数、メソッドを木構造で可視化します。 Shell からの場合は、先にモジュール選択のダイアログが開きます。

@item Path Browser [パスブラウザ]

sys.path ディレクトリ、モジュール、クラスおよびメソッドを木構造で可視化します。

@item Save [保存]

現在のウィンドウを対応するファイルがあればそこに保存します。開いてから、または最後に保存したのちに編集があった場合のウィンドウには、ウィンドウタイトルの前後に * が付けられます。対応するファイルがなければ代わりに Save As が実行されます。

@item Save As... [名前を付けて保存...]

Save the current window with a Save As dialog.  The file saved becomes the
new associated file for the window. (If your file manager is set to hide
extensions, the current extension will be omitted in the file name box.
If the new filename has no '.', '.py' and '.txt' will be added for Python
and text files, except that on macOS Aqua,'.py' is added for all files.)

@item Save Copy As... [コピーとして保存...]

Save the current window to different file without changing the associated
file.  (See Save As note above about filename extensions.)

@item Print Window [ウィンドウを印刷]

現在のウィンドウをデフォルトプリンタで印刷します。

@item Close Window

Close the current window (if an unsaved editor, ask to save; if an unsaved
Shell, ask to quit execution).  Calling @code{exit()} or @code{close()} in the Shell
window also closes Shell.  If this is the only window, also exit IDLE.

@item Exit IDLE

Close all windows and quit IDLE (ask to save unsaved edit windows).
@end table

@node Edit メニュー Shell ウィンドウ、Editor ウィンドウ,Format メニュー Shell ウィンドウ、Editor ウィンドウ,File メニュー Shell ウィンドウ、Editor ウィンドウ,メニュー
@anchor{library/idle edit-menu-shell-and-editor}@anchor{43e6}
@subsubsection Edit メニュー (Shell ウィンドウ、Editor ウィンドウ)



@table @asis

@item Undo [元に戻す]

現在のウィンドウに対する最後の変更を Undo (取り消し) します。最大で 1000 個の変更が Undo できます。

@item Redo [やり直し]

現在のウィンドウに対する最後にundoされた変更をRedo(再スタート)します。

@item Select All [全て選択]

カレントウィンドウの内容全体を選択します。

@item Cut [切り取り]

システムのクリップボードへ選択された部分をコピーします。それから選択された部分を削除します。

@item Copy [コピー]

選択された部分をシステムのクリップボードへコピーします。

@item Paste [貼り付け]

システムのクリップボードの内容をカレントウィンドウへ挿入します。
@end table

クリップボードの機能はコンテキストメニューからも使えます。


@table @asis

@item Find... [検索...]

たくさんのオプションをもつ検索ダイアログボックスを開きます。

@item Find Again [再検索]

直前の検索があれば、それを繰り返します。

@item Find Selection [現在の選択を検索]

現在選択された文字列があれば、それを検索します。

@item Find in Files... [ファイルから検索...]

ファイル検索ダイアログを開きます。結果を新しい出力ウィンドウに出力します。

@item Replace... [置換...]

検索と置換ダイアログを開きます。

@item Go to Line [指定行へジャンプ]

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.

@item Show Completions [補完候補の一覧]

Open a scrollable list allowing selection of existing names. See
@ref{43e7,,Completions} in the Editing and Navigation section below.

@item Expand Word [語の展開]

先頭だけタイプしたものを、同一ウィンドウ内の完全な語と合致するものに展開します。異なる展開を得るためには繰り返します。

@item Show Call Tip

After an unclosed parenthesis for a function, open a small window with
function parameter hints.  See @ref{43e8,,Calltips} in the
Editing and Navigation section below.

@item Show Surrounding Parens

囲んでいる括弧をハイライトします。
@end table

@node Format メニュー Shell ウィンドウ、Editor ウィンドウ,Run メニュー Editor ウィンドウのみ,Edit メニュー Shell ウィンドウ、Editor ウィンドウ,メニュー
@anchor{library/idle format-menu}@anchor{43e9}@anchor{library/idle format-menu-editor-window-only}@anchor{43ea}
@subsubsection Format メニュー (Shell ウィンドウ、Editor ウィンドウ)



@table @asis

@item Format Paragraph [パラグラフのフォーマット]

Rewrap the text block containing the text insert cursor.
Avoid code lines.  See @ref{43eb,,Format block} in the
Editing and Navigation section below.

@item Indent Region [領域をインデント]

選択された行を右へインデント幅分シフトします (デフォルトは空白 4 個)。

@item Dedent Region [領域をインデント解除]

選択された行を左へインデント幅分シフトします (デフォルトは空白 4 個)。

@item Comment Out Region [領域をコメントアウト]

選択された行の先頭に ## を挿入します。

@item Uncomment Region [領域のコメントを解除]

選択された行から先頭の # あるいは ## を取り除きます。

@item Tabify Region [領域のタブ化]

`先頭' の一続きの空白をタブに置き換えます (注意: Python コードのインデントには 4 つの空白を使うことをお勧めします)。

@item Untabify Region [領域の非タブ化]

`すべての' タブを適切な数の空白に置き換えます。

@item Toggle Tabs [タブの切り替え]

字下げのために空白を使うかタブを使うかを切り替えるダイアログを開きます。

@item New Indent Width [新しいインデント幅]

インデント幅を変更するダイアログを開きます。Python コミュニティによって受け容れられているデフォルトは空白 4 個です。

@item Strip Trailing Whitespace

Remove trailing space and other whitespace characters after the last
non-whitespace character of a line by applying @ref{16ca,,str.rstrip()} to each line,
including lines within multiline strings.  Except for Shell windows,
remove extra newlines at the end of the file.
@end table

@geindex Run script

@node Run メニュー Editor ウィンドウのみ,Shell メニュー Shell ウィンドウのみ,Format メニュー Shell ウィンドウ、Editor ウィンドウ,メニュー
@anchor{library/idle run-menu-editor-window-only}@anchor{43ec}
@subsubsection Run メニュー (Editor ウィンドウのみ)

@anchor{library/idle run-module}@anchor{43ed}

@table @asis

@item Run Module [モジュールの実行]

@ref{43ee,,Check Module} を実行します。エラーがなければ Shell の環境をクリーンにして再スタートした上で、モジュールを実行します。出力は Shell ウィンドウに表示されます。@code{print} や @code{write} しない限り、この出力はされません。モジュール実行が完了すると Shell はフォーカスされた状態のままで、プロンプトを表示します。これにより対話的に実行結果を調べることができます。この機能は、コマンドラインからファイルを @code{python -i file} で実行することに相当します。
@end table
@anchor{library/idle run-custom}@anchor{43ef}

@table @asis

@item Run... Customized

Same as @ref{43ed,,Run Module}, but run the module with customized
settings.  `Command Line Arguments' extend @ref{147c,,sys.argv} as if passed
on a command line. The module can be run in the Shell without restarting.
@end table
@anchor{library/idle check-module}@anchor{43ee}

@table @asis

@item Check Module [モジュールのチェック]

Editor ウィンドウでいま開いているモジュールを構文チェックします。モジュールが未保存の場合、 Options -> Configure IDLE -> General の "Autosave Preferences" の設定にもとづき、確認を求められるか自動的に保存します。構文エラーが見つかると Editor ウィンドウでそのおよその位置に移動します。
@end table
@anchor{library/idle python-shell}@anchor{43f0}

@table @asis

@item Python Shell [Python シェル]

Python Shell ウィンドウを開くか、起こします。
@end table

@node Shell メニュー Shell ウィンドウのみ,Debug メニュー Shell ウィンドウのみ,Run メニュー Editor ウィンドウのみ,メニュー
@anchor{library/idle shell-menu-shell-window-only}@anchor{43f1}
@subsubsection Shell メニュー (Shell ウィンドウのみ)



@table @asis

@item View Last Restart [最後のリスタートを表示する]

最後に Shell のリスタートを行った場所まで Shell ウインドウをスクロールします。

@item Restart Shell [Shell のリスタート]

Restart the shell to clean the environment and reset display and exception handling.

@item Previous History

Cycle through earlier commands in history which match the current entry.

@item Next History

Cycle through later commands in history which match the current entry.

@item Interrupt Execution [実行の中断]

プログラムの実行を停止します。
@end table

@node Debug メニュー Shell ウィンドウのみ,Options メニュー Shell ウィンドウ、Editor ウィンドウ,Shell メニュー Shell ウィンドウのみ,メニュー
@anchor{library/idle debug-menu-shell-window-only}@anchor{43f2}
@subsubsection Debug メニュー (Shell ウィンドウのみ)



@table @asis

@item Go to File/Line [ファイル/行へ移動]

カーソルのある現在行の上にファイル名と行番号が見つかれば、(開かれていなければ) そのファイルを開いてその行に飛びます。例外のトレースバックが参照しているソース行を見るのにこれを使いましょう。そのようなファイル名・行番号表示をしている行を見つけるのには Find を使えます。この機能は Shell ウィンドウと Output ウィンドウのコンテキストメニューからも使えます。
@end table

@geindex debugger
@geindex stack viewer


@table @asis

@item Debugger [デバッガ] (トグル切り替え)

アクティブにすると、Shell または Editor に入力したコードをデバッガのもとで実行します。Editor ではコンテキストメニューからブレイクポイントをセット出来ます。この機能はまだ不完全で、少々実験的です。

@item Stack Viewer [スタックビューア]

最後の例外のスタックトレースと locals 辞書、 globals 辞書をツリーウィジットで表示します。

@item Auto-open Stack Viewer [スタックビューアの自動オープン]

未捕捉の例外時にスタックビューアを自動的に開くかどうかを切り替えます。
@end table

@node Options メニュー Shell ウィンドウ、Editor ウィンドウ,Window メニュー Shell ウィンドウ、Editor ウィンドウ,Debug メニュー Shell ウィンドウのみ,メニュー
@anchor{library/idle options-menu-shell-and-editor}@anchor{43f3}
@subsubsection Options メニュー (Shell ウィンドウ、Editor ウィンドウ)



@table @asis

@item Configure IDLE [IDLE の設定]

Open a configuration dialog and change preferences for the following:
fonts, indentation, keybindings, text color themes, startup windows and
size, additional help sources, and extensions.  On macOS, open the
configuration dialog by selecting Preferences in the application
menu. For more details, see
@ref{43f4,,Setting preferences} under Help and preferences.
@end table

Most configuration options apply to all windows or all future windows.
The option items below only apply to the active window.


@table @asis

@item Show/Hide Code Context (Editor Window only)

Editor ウィンドウの上部にペインが開き、そこにウィンドウの一番上のコードのブロックコンテキスト (訳注: コードが含まれているブロックのインデント構造) が表示されます。
下の編集とナビゲーションの節にある @ref{43f5,,コードコンテキスト} の項を参照してください。

@item Show/Hide Line Numbers (Editor Window only)

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 @ref{43f4,,Setting preferences}).

@item Zoom/Restore Height

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.
@end table

@node Window メニュー Shell ウィンドウ、Editor ウィンドウ,Help メニュー Shell ウィンドウ、Editor ウィンドウ,Options メニュー Shell ウィンドウ、Editor ウィンドウ,メニュー
@anchor{library/idle window-menu-shell-and-editor}@anchor{43f6}
@subsubsection Window メニュー (Shell ウィンドウ、Editor ウィンドウ)


Lists the names of all open windows; select one to bring it to the foreground
(deiconifying it if necessary).

@node Help メニュー Shell ウィンドウ、Editor ウィンドウ,Context menus,Window メニュー Shell ウィンドウ、Editor ウィンドウ,メニュー
@anchor{library/idle help-menu-shell-and-editor}@anchor{43f7}
@subsubsection Help メニュー (Shell ウィンドウ、Editor ウィンドウ)



@table @asis

@item About IDLE [IDLE について]

バージョン、コピーライト、ライセンス、クレジット、その他を表示します。

@item IDLE Help [IDLE ヘルプ]

メニューオプション、基本的な編集やナビゲーションその他チップスを詳しく書いた IDLE のドキュメントを表示します。

@item Python Docs [Python ドキュメント]

Python ドキュメントがローカルにインストールされていればそれを開きます。もしくはウェブブラウザで最新の Python ドキュメント (@indicateurl{https://docs.python.org}) を開きます。(訳注: いずれも何もしていなければ英語。下記参照。)

@item Turtle Demo [Turtle デモ]

Python コード例とタートルによる描画を使って turtledemo モジュールを実行します。
@end table

General タブの下の方にある Configure IDLE ダイアログで、追加のヘルプソースを Help メニューに加えられます。
下の編集とナビゲーションの節にある @ref{43f8,,ヘルプソース} の項を参照してください。

@geindex Cut [切り取り]
@geindex Copy [コピー]
@geindex Paste [貼り付け]
@geindex Set Breakpoint [ブレークポイントのセット]
@geindex Clear Breakpoint [ブレークポイントのクリア]
@geindex breakpoints

@node Context menus,,Help メニュー Shell ウィンドウ、Editor ウィンドウ,メニュー
@anchor{library/idle context-menus}@anchor{43f9}
@subsubsection Context menus


ウィンドウ内で右クリック (macOS では Control-クリック) でコンテキストメニューが開きます。コンテキストメニューには Edit メニューにもある標準的なクリップボード機能が含まれています。


@table @asis

@item Cut [切り取り]

システムのクリップボードへ選択された部分をコピーします。それから選択された部分を削除します。

@item Copy [コピー]

選択された部分をシステムのクリップボードへコピーします。

@item Paste [貼り付け]

システムのクリップボードの内容をカレントウィンドウへ挿入します。
@end table

Editor ウィンドウではさらにブレイクポイント機能が使えます。ブレイクポイントがセットされた行には、特別に印がつきます。ブレイクポイントはデバッガのもとでの実行にだけ影響します。ファイルに付けたブレイクポイントはユーザの @code{.idlerc} ディレクトリに保存されます。


@table @asis

@item Set Breakpoint [ブレークポイントのセット]

現在行にブレークポイントをセットします。

@item Clear Breakpoint [ブレークポイントのクリア]

その行のブレークポイントをクリアします。
@end table

Shell ウィンドウや Output ウィンドウには次のメニューもあります。


@table @asis

@item Go to file/line [ファイル/行へ移動]

Debug メニューと同じものです。
@end table

The Shell window also has an output squeezing facility explained in the `Python
Shell window' subsection below.


@table @asis

@item Squeeze

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.
@end table

@node Editing and Navigation,Startup and Code Execution,メニュー,IDLE --- Python のエディタとシェル<2>
@anchor{library/idle editing-and-navigation}@anchor{43fa}@anchor{library/idle id1}@anchor{43fb}
@subsubsection Editing and Navigation


@menu
* Editor windows:: 
* Key bindings:: 
* 自動的な字下げ:: 
* 検索と置換:: 
* 補完 (Completions): 補完 Completions. 
* 呼び出しヒント (Calltips): 呼び出しヒント Calltips. 
* Format block:: 
* Code Context:: 
* Shell window:: 
* テキストの色:: 

@end menu

@node Editor windows,Key bindings,,Editing and Navigation
@anchor{library/idle editor-windows}@anchor{43fc}
@subsubsection Editor windows


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.

@node Key bindings,自動的な字下げ,Editor windows,Editing and Navigation
@anchor{library/idle key-bindings}@anchor{43fd}
@subsubsection Key bindings


The IDLE insertion cursor is a thin vertical bar between character
positions.  When characters are entered, the insertion cursor and
everything to its right moves right one character and
the new character is entered in the new space.

Several non-character keys move the cursor and possibly
delete characters.  Deletion does not puts text on the clipboard,
but IDLE has an undo list.  Wherever this doc discusses keys,
'C' refers to the @code{Control} key on Windows and
Unix and the @code{Command} key on macOS.  (And all such discussions
assume that the keys have not been re-bound to something else.)


@itemize *

@item 
Arrow keys move the cursor one character or line.

@item 
@code{C}-@code{LeftArrow} and @code{C}-@code{RightArrow} moves left or right one word.

@item 
@code{Home} and @code{End} go to the beginning or end of the line.

@item 
@code{Page Up} and @code{Page Down} go up or down one screen.

@item 
@code{C}-@code{Home} and @code{C}-@code{End} go to beginning or end of the file.

@item 
@code{Backspace} and @code{Del} (or @code{C}-@code{d}) delete the previous
or next character.

@item 
@code{C}-@code{Backspace} and @code{C}-@code{Del} delete one word left or right.

@item 
@code{C}-@code{k} deletes ('kills') everything to the right.
@end itemize

標準的なキーバインディング (@code{C}-@code{c} がコピーで @code{C}-@code{v} がペースト、など) は機能するかもしれません。キーバインディングは Configure IDLE ダイアログで選択します。

@node 自動的な字下げ,検索と置換,Key bindings,Editing and Navigation
@anchor{library/idle automatic-indentation}@anchor{43fe}
@subsubsection 自動的な字下げ


ブロックの始まりの文の後、次の行は 4 つの空白 (Python Shell ウィンドウでは、一つのタブ) で字下げされます。あるキーワード (break、return など) の後では、次の行は字下げが解除 (dedent) されます。先頭の字下げでは、 @code{Backspace} は 4 つの空白があれば削除します。 @code{Tab} はインデント幅に対応する数の空白 (Python Shell ウィンドウでは一つのタブ) を挿入します。現在、タブは Tcl/Tk の制約のため 4 つの空白に固定されています。

@ref{43e9,,Format メニュー} の indent/dedent region コマンドも参照してください。

@node 検索と置換,補完 Completions,自動的な字下げ,Editing and Navigation
@anchor{library/idle search-and-replace}@anchor{43ff}
@subsubsection 検索と置換


Any selection becomes a search target.  However, only selections within
a line work because searches are only performed within lines with the
terminal newline removed.  If @code{[x] Regular expression} is checked, the
target is interpreted according to the Python re module.

@node 補完 Completions,呼び出しヒント Calltips,検索と置換,Editing and Navigation
@anchor{library/idle completions}@anchor{43e7}@anchor{library/idle id2}@anchor{4400}
@subsubsection 補完 (Completions)


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 @code{Up}, @code{Down},
@code{PageUp}, @code{PageDown}, @code{Home}, and @code{End} keys;
and by a single click within the box.  Close the box with @code{Escape},
@code{Enter}, and double @code{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 @ref{87a,,os.sep} or
@ref{87b,,os.altsep} 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 @code{C}-@code{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 @code{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 @code{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.

@node 呼び出しヒント Calltips,Format block,補完 Completions,Editing and Navigation
@anchor{library/idle calltips}@anchor{43e8}@anchor{library/idle id3}@anchor{4401}
@subsubsection 呼び出しヒント (Calltips)


A calltip is shown automatically when one types @code{(} 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 @code{)} 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 @code{itertools.count(}.  A calltip
appears because Idle imports itertools into the user process for its own
use.  (This could change.)  Enter @code{turtle.write(} and nothing appears.
Idle does not itself import turtle.  The menu entry and shortcut also do
nothing.  Enter @code{import turtle}.  Thereafter, @code{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.

@node Format block,Code Context,呼び出しヒント Calltips,Editing and Navigation
@anchor{library/idle format-block}@anchor{43eb}@anchor{library/idle id4}@anchor{4402}
@subsubsection Format block


Reformat Paragraph rewraps a block ('paragraph') of contiguous equally
indented non-blank comments, a similar block of text within a multiline
string, or a selected subset of either.
If needed, add a blank line to separate string from code.
Partial lines in a selection expand to complete lines.
The resulting lines have the same indent as before
but have maximum total length of N columns (characters).
Change the default N of 72 on the Window tab of IDLE Settings.

@node Code Context,Shell window,Format block,Editing and Navigation
@anchor{library/idle code-context}@anchor{43f5}@anchor{library/idle id5}@anchor{4403}
@subsubsection Code Context


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
@code{class}, @code{def}, or @code{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.

@node Shell window,テキストの色,Code Context,Editing and Navigation
@anchor{library/idle shell-window}@anchor{4404}
@subsubsection Shell window


In IDLE's Shell, enter, edit, and recall complete statements. (Most
consoles and terminals only work with a single physical line at a time).

Submit a single-line statement for execution by hitting @code{Return}
with the cursor anywhere on the line.  If a line is extended with
Backslash (@code{\}), the cursor must be on the last physical line.
Submit a multi-line compound statement by entering a blank line after
the statement.

When one pastes code into Shell, it is not compiled and possibly executed
until one hits @code{Return}, as specified above.
One may edit pasted code first.
If one pastes more than one statement into Shell, the result will be a
@ref{18e,,SyntaxError} when multiple statements are compiled as if they were one.

Lines containing @code{RESTART} mean that the user execution process has been
re-started.  This occurs when the user execution process has crashed,
when one requests a restart on the Shell menu, or when one runs code
in an editor window.

The editing features described in previous subsections work when entering
code interactively.  IDLE's Shell window also responds to the following:


@itemize *

@item 
@code{C}-@code{c} attempts to interrupt statement execution (but may fail).

@item 
@code{C}-@code{d} closes Shell if typed at a @code{>>>} prompt.

@item 
@code{Alt}-@code{p} and @code{Alt}-@code{n} (@code{C}-@code{p} and @code{C}-@code{n} on macOS)
retrieve to the current prompt the previous or next previously
entered statement that matches anything already typed.

@item 
@code{Return} while the cursor is on any previous statement
appends the latter to anything already typed at the prompt.
@end itemize

@node テキストの色,,Shell window,Editing and Navigation
@anchor{library/idle text-colors}@anchor{4405}
@subsubsection テキストの色


IDLE の表示はデフォルトで白背景に黒字ですが、以下のような特別な意味を持ったテキストには色が付きす。Shell では shell 出力、 shell エラー、ユーザエラー。Python コードでは Shell プロンプト内や Editor でのキーワード、組み込みクラスや組み込み関数の名前、 @code{class} や @code{def} に続く名前、文字列、そしてコメント。どんなテキストウィンドウでも、カーソル (あれば)、検索で合致したテキスト (あれば)、そして選択されているテキストには色が付きます。

IDLE also highlights the @ref{a0d,,soft keywords} @ref{a0e,,match},
@ref{a0e,,case}, and @ref{a0f,,_} in
pattern-matching statements. However, this highlighting is not perfect and
will be incorrect in some rare cases, including some @code{_}-s in @code{case}
patterns.

このテキストの色付けはバックグラウンドで行われるため、たまに色が付いてない状態が見えてしまいます。カラースキームは、 Configure IDLE [IDLE の設定] ダイアログの Highlighting タブで変更できます。ただし、エディタ内のデバッガブレークポイント行のマーキングと、ポップアップとダイアログないのテキストの色は、ユーザーにより変更することはできません。

@node Startup and Code Execution,Help and Preferences,Editing and Navigation,IDLE --- Python のエディタとシェル<2>
@anchor{library/idle startup-and-code-execution}@anchor{4406}
@subsubsection Startup and Code Execution


@code{-s} オプションとともに起動すると、IDLE は環境変数 
@geindex IDLESTARTUP
@geindex 環境変数; IDLESTARTUP
@code{IDLESTARTUP} か 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} で参照されているファイルを実行します。 IDLE はまず @code{IDLESTARTUP} をチェックし、あれば参照しているファイルを実行します。 @code{IDLESTARTUP} が無ければ、IDLE は @code{PYTHONSTARTUP} をチェックします。これらの環境変数で参照されているファイルは、IDLE シェルでよく使う関数を置いたり、一般的なモジュールの import 文を実行するのに便利です。

加えて、@code{Tk} もスタートアップファイルがあればそれをロードします。その Tk のファイルは無条件にロードされることに注意してください。このファイルは @code{.Idle.py} で、ユーザーのホームディレクトリから探されます。このファイルの中の文は Tk の名前空間で実行されるので、IDLE の Python シェルで使う関数を import するのには便利ではありません。

@menu
* コマンドラインでの使用: コマンドラインでの使用<5>. 
* Startup failure:: 
* Running user code:: 
* User output in Shell:: 
* Developing tkinter applications:: 
* サブプロセスを起こさずに起動する:: 

@end menu

@node コマンドラインでの使用<5>,Startup failure,,Startup and Code Execution
@anchor{library/idle command-line-usage}@anchor{4407}@anchor{library/idle idlelib-cli}@anchor{4408}
@subsubsection コマンドラインでの使用


IDLE can be invoked from the command line with various options. The general syntax is:

@example
python -m idlelib [options] [file ...]
@end example

The following options are available:

@geindex idle コマンドラインオプション; -c
@anchor{library/idle cmdoption-idle-c}@anchor{4409}
@deffn {Option} @w{-}c <command>

Run the specified Python command in the shell window.
For example, pass @code{-c "print('Hello, World!')"}.
On Windows, the outer quotes must be double quotes as shown.
@end deffn

@geindex idle コマンドラインオプション; -d
@anchor{library/idle cmdoption-idle-d}@anchor{440a}
@deffn {Option} @w{-}d

Enable the debugger and open the shell window.
@end deffn

@geindex idle コマンドラインオプション; -e
@anchor{library/idle cmdoption-idle-e}@anchor{440b}
@deffn {Option} @w{-}e

Open an editor window.
@end deffn

@geindex idle コマンドラインオプション; -h
@anchor{library/idle cmdoption-idle-h}@anchor{440c}
@deffn {Option} @w{-}h

Print a help message with legal combinations of options and exit.
@end deffn

@geindex idle コマンドラインオプション; -i
@anchor{library/idle cmdoption-idle-i}@anchor{440d}
@deffn {Option} @w{-}i

Open a shell window.
@end deffn

@geindex idle コマンドラインオプション; -r
@anchor{library/idle cmdoption-idle-r}@anchor{440e}
@deffn {Option} @w{-}r <file>

Run the specified file in the shell window.
@end deffn

@geindex idle コマンドラインオプション; -s
@anchor{library/idle cmdoption-idle-s}@anchor{440f}
@deffn {Option} @w{-}s

Run the startup file (as defined by the environment variables 
@geindex IDLESTARTUP
@geindex 環境変数; IDLESTARTUP
@code{IDLESTARTUP} or 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP}) before opening the shell window.
@end deffn

@geindex idle コマンドラインオプション; -t
@anchor{library/idle cmdoption-idle-t}@anchor{4410}
@deffn {Option} @w{-}t <title>

Set the title of the shell window.
@end deffn

@geindex idle コマンドラインオプション; -
@anchor{library/idle cmdoption-idle-0}@anchor{4411}
@deffn {Option} @w{-}

Read and execute standard input in the shell window. This option must be the last one before any arguments.
@end deffn

If arguments are provided:


@itemize -

@item 
If @code{-}, @code{-c}, or @code{-r} is used, all arguments are placed in @code{sys.argv[1:]},
and @code{sys.argv[0]} is set to @code{'@w{'}}, @code{'-c'}, or @code{'-r'} respectively.
No editor window is opened, even if that is the default set in the `Options' dialog.

@item 
Otherwise, arguments are treated as files to be opened for editing, and @code{sys.argv} reflects the arguments passed to IDLE itself.
@end itemize

@node Startup failure,Running user code,コマンドラインでの使用<5>,Startup and Code Execution
@anchor{library/idle startup-failure}@anchor{4412}
@subsubsection Startup failure


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 @code{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 @code{** Invalid host:}.
The valid value is @code{127.0.0.1 (idlelib.rpc.LOCALHOST)}.
One can diagnose with @code{tcpconnect -irv 127.0.0.1 6543} in one
terminal window and @code{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
@code{~/.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 (@code{python -m idlelib}) and see if
this results in an error message.

On Unix-based systems with tcl/tk older than @code{8.6.11} (see
@code{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.

@node Running user code,User output in Shell,Startup failure,Startup and Code Execution
@anchor{library/idle running-user-code}@anchor{4413}
@subsubsection Running user code


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, @code{sys.modules} starts with more entries,
and @code{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 @code{sys.stdin}, @code{sys.stdout}, and @code{sys.stderr}
with objects that get input from and send output to the Shell window.
The original values stored in @code{sys.__stdin__}, @code{sys.__stdout__}, and
@code{sys.__stderr__} are not touched, but may be @code{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 @ref{2609,,str.join()} 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 @code{input} from
sys.stdin or @code{print} or @code{write} to sys.stdout or sys.stderr,
IDLE should be started in a command line window.  (On Windows,
use @code{python} or @code{py} rather than @code{pythonw} or @code{pyw}.)
The secondary subprocess
will then be attached to that window for input and output.

If @code{sys} is reset by user code, such as with @code{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 @code{sys.getrecursionlimit} and
@code{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.

@node User output in Shell,Developing tkinter applications,Running user code,Startup and Code Execution
@anchor{library/idle user-output-in-shell}@anchor{4414}
@subsubsection User output in Shell


When a program outputs text, the result is determined by the
corresponding output device.  When IDLE executes user code, @code{sys.stdout}
and @code{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.)

@example
>>> s = 'a\tb\a<\x02><\r>\bc\nd'  # Enter 22 chars.
>>> len(s)
14
>>> s  # Display repr(s)
'a\tb\x07<\x02><\r>\x08c\nd'
>>> print(s, end='@w{'})  # Display s as is.
# Result varies by OS and font.  Try it.
@end example

The @code{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.

@node Developing tkinter applications,サブプロセスを起こさずに起動する,User output in Shell,Startup and Code Execution
@anchor{library/idle developing-tkinter-applications}@anchor{4415}
@subsubsection Developing tkinter applications


IDLE is intentionally different from standard Python in order to
facilitate development of tkinter programs.  Enter @code{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
@code{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 @code{b = tk.Button(root, text='button'); b.pack()}.  Again,
nothing visibly changes in standard Python until one enters @code{root.update()}.

Most tkinter programs run @code{root.mainloop()}, which usually does not
return until the tk app is destroyed.  If the program is run with
@code{python -i} or from an IDLE editor, a @code{>>>} shell prompt does not
appear until @code{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.

@node サブプロセスを起こさずに起動する,,Developing tkinter applications,Startup and Code Execution
@anchor{library/idle running-without-a-subprocess}@anchor{4416}
@subsubsection サブプロセスを起こさずに起動する


デフォルトでは、IDLE でのユーザコードの実行は、内部的なループバックインターフェイスを使用する、ソケット経由の分離されたサブプロセスで行われます。この接続は外部からは見えませんし、インターネットとのデータの送受信は行われません。ファイアウォールソフトウェアの警告が発生しても、無視して構いません。

ソケット接続の確立を試みて失敗した場合、IDLE によって通知されます。このような失敗は一過性の場合もありますが、永続的に失敗する場合は、ファイアウォールが接続をブロックしているか、特定のシステムの設定が誤っていることが原因かもしれません。問題が解決するまでは、 IDLE をコマンドラインオプション @code{-n} で起動することもできます。

IDLE を @code{-n} コマンドラインスイッチを使って開始した場合、IDLE は単一のプロセス内で動作し、RPC Python 実行サーバを走らせるサブプロセスを作りません。これは、プラットフォーム上で Python がサブプロセスや RPC ソケットインターフェイスを作れない場合に有用かもしれません。ただし、このモードではユーザコードが IDLE 自身から隔離されませんし、Run/Run Module (F5) 選択時に環境が再起動されてまっさらな状態になることもありません。コードを変更した場合、影響するモジュールを reload() しないといけませんし、変更を反映するには、すべての特定の項目 (@code{from foo import baz} など) を再インポートしないといけません。これらの理由から、可能なら常にデフォルトのサブプロセスを起こすモードで IDLE を起動するのが吉です。


バージョン 3.4 で非推奨.


@node Help and Preferences,idlelib --- implementation of IDLE application,Startup and Code Execution,IDLE --- Python のエディタとシェル<2>
@anchor{library/idle help-and-preferences}@anchor{4417}
@subsubsection Help and Preferences


@menu
* Help sources:: 
* Setting preferences [お好み設定]:: 
* IDLE on macOS:: 
* Extensions [拡張]:: 

@end menu

@node Help sources,Setting preferences [お好み設定],,Help and Preferences
@anchor{library/idle help-sources}@anchor{43f8}@anchor{library/idle id6}@anchor{4418}
@subsubsection Help sources


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 @code{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.

@node Setting preferences [お好み設定],IDLE on macOS,Help sources,Help and Preferences
@anchor{library/idle preferences}@anchor{43f4}@anchor{library/idle setting-preferences}@anchor{4419}
@subsubsection Setting preferences [お好み設定]


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 @code{.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 @code{.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.

@node IDLE on macOS,Extensions [拡張],Setting preferences [お好み設定],Help and Preferences
@anchor{library/idle idle-on-macos}@anchor{441a}
@subsubsection IDLE on macOS


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.

@node Extensions [拡張],,IDLE on macOS,Help and Preferences
@anchor{library/idle extensions}@anchor{441b}
@subsubsection Extensions [拡張]


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.

@node idlelib --- implementation of IDLE application,,Help and Preferences,IDLE --- Python のエディタとシェル<2>
@anchor{library/idle idlelib-implementation-of-idle-application}@anchor{441c}@anchor{library/idle module-idlelib}@anchor{77}
@subsubsection idlelib --- implementation of IDLE application


@geindex module; idlelib

`Source code:' Lib/idlelib@footnote{https://github.com/python/cpython/tree/3.14/Lib/idlelib}


__________________________________________________________________


The Lib/idlelib package implements the IDLE application.  See the rest
of this page for how to use IDLE.

The files in idlelib are described in idlelib/README.txt.  Access it
either in idlelib or click Help => About IDLE on the IDLE menu.  This
file also maps IDLE menu items to the code that implements the item.
Except for files listed under 'Startup', the idlelib code is 'private' in
sense that feature changes can be backported (see 
@geindex Python Enhancement Proposals; PEP 434
PEP 434@footnote{https://peps.python.org/pep-0434/}).

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node turtle --- Turtle graphics,,IDLE --- Python のエディタとシェル<2>,Graphical user interfaces with Tk
@anchor{library/turtle doc}@anchor{441d}@anchor{library/turtle module-turtle}@anchor{107}@anchor{library/turtle translation-repo}@anchor{441e}@anchor{library/turtle turtle-turtle-graphics}@anchor{441f}
@subsection @code{turtle} --- Turtle graphics


@geindex module; turtle

`ソースコード:' Lib/turtle.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/turtle.py}

@c from turtle import *
@c turtle = Turtle()

@c import os
@c os.remove("my_drawing.ps")


__________________________________________________________________


@menu
* はじめに: はじめに<12>. 
* Get started:: 
* チュートリアル: チュートリアル<4>. 
* How to...: How to. 
* Turtle graphics reference:: 
* RawTurtle/Turtle のメソッドと対応する関数:: 
* TurtleScreen/Screen のメソッドと対応する関数:: 
* Public classes:: 
* 説明: 説明<2>. 
* ヘルプと設定:: 
* turtledemo: turtledemo --- Demo scripts. Demo scripts
* python 2.6からの変更点: python 2 6からの変更点. 
* python 3.0からの変更点: python 3 0からの変更点. 

@end menu

@node はじめに<12>,Get started,,turtle --- Turtle graphics
@anchor{library/turtle introduction}@anchor{4420}
@subsubsection はじめに


Turtle graphics is an implementation of the popular geometric drawing tools introduced in Logo@footnote{https://en.wikipedia.org/wiki/Turtle_(robot)}, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon
in 1967.

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile

@node Get started,チュートリアル<4>,はじめに<12>,turtle --- Turtle graphics
@anchor{library/turtle get-started}@anchor{4421}
@subsubsection Get started


x-y 平面の (0, 0) から動き出すロボット亀を想像してみて下さい。 @code{turtle.forward(15)} という命令を出すと、その亀が (スクリーン上で!) 15 ピクセル分顔を向けている方向に動き、動きに沿って線を引きます。 @code{turtle.left(25)} という命令を出すと、今度はその場で25度反時計回りに回ります。

@subsubheading Turtle star



Turtle can draw intricate shapes using programs that repeat simple
moves.

@image{python-figures/turtle-star,,,,png}

In Python, turtle graphics provides a representation of a physical "turtle"
(a little robot with a pen) that draws on a sheet of paper on the floor.

It's an effective and well-proven way for learners to encounter
programming concepts and interaction with software, as it provides instant,
visible feedback. It also provides convenient access to graphical output
in general.

Turtle drawing was originally created as an educational tool, to be used by
teachers in the classroom. For the programmer who needs to produce some
graphical output it can be a way to do that without the overhead of
introducing more complex or external libraries into their work.

@node チュートリアル<4>,How to,Get started,turtle --- Turtle graphics
@anchor{library/turtle turtle-tutorial}@anchor{4422}@anchor{library/turtle tutorial}@anchor{4423}
@subsubsection チュートリアル


New users should start here. In this tutorial we'll explore some of the
basics of turtle drawing.

@menu
* Starting a turtle environment:: 
* Basic drawing:: 
* Making algorithmic patterns:: 

@end menu

@node Starting a turtle environment,Basic drawing,,チュートリアル<4>
@anchor{library/turtle starting-a-turtle-environment}@anchor{4424}
@subsubsection Starting a turtle environment


In a Python shell, import all the objects of the @code{turtle} module:

@example
from turtle import *
@end example

If you run into a @code{No module named '_tkinter'} error, you'll have to
install the @ref{f6,,Tk interface package} on your system.

@node Basic drawing,Making algorithmic patterns,Starting a turtle environment,チュートリアル<4>
@anchor{library/turtle basic-drawing}@anchor{4425}
@subsubsection Basic drawing


Send the turtle forward 100 steps:

@example
forward(100)
@end example

You should see (most likely, in a new window on your display) a line
drawn by the turtle, heading East. Change the direction of the turtle,
so that it turns 120 degrees left (anti-clockwise):

@example
left(120)
@end example

Let's continue by drawing a triangle:

@example
forward(100)
left(120)
forward(100)
@end example

Notice how the turtle, represented by an arrow, points in different
directions as you steer it.

Experiment with those commands, and also with @code{backward()} and
@code{right()}.

@menu
* Pen の制御:: 
* The turtle's position:: 

@end menu

@node Pen の制御,The turtle's position,,Basic drawing
@anchor{library/turtle pen-control}@anchor{4426}
@subsubsection Pen の制御


Try changing the color - for example, @code{color('blue')} - and
width of the line - for example, @code{width(3)} - and then drawing again.

You can also move the turtle around without drawing, by lifting up the pen:
@code{up()} before moving. To start drawing again, use @code{down()}.

@node The turtle's position,,Pen の制御,Basic drawing
@anchor{library/turtle the-turtle-s-position}@anchor{4427}
@subsubsection The turtle's position


Send your turtle back to its starting-point (useful if it has disappeared
off-screen):

@example
home()
@end example

The home position is at the center of the turtle's screen. If you ever need to
know them, get the turtle's x-y coordinates with:

@example
pos()
@end example

Home is at @code{(0, 0)}.

And after a while, it will probably help to clear the window so we can start
anew:

@example
clearscreen()
@end example

@node Making algorithmic patterns,,Basic drawing,チュートリアル<4>
@anchor{library/turtle making-algorithmic-patterns}@anchor{4428}
@subsubsection Making algorithmic patterns


Using loops, it's possible to build up geometric patterns:

@example
for steps in range(100):
    for c in ('blue', 'red', 'green'):
        color(c)
        forward(steps)
        right(30)
@end example

- which of course, are limited only by the imagination!

Let's draw the star shape at the top of this page. We want red lines,
filled in with yellow:

@example
color('red')
fillcolor('yellow')
@end example

Just as @code{up()} and @code{down()} determine whether lines will be drawn,
filling can be turned on and off:

@example
begin_fill()
@end example

Next we'll create a loop:

@example
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
@end example

@code{abs(pos()) < 1} is a good way to know when the turtle is back at its
home position.

Finally, complete the filling:

@example
end_fill()
@end example

(Note that filling only actually takes place when you give the
@code{end_fill()} command.)

@node How to,Turtle graphics reference,チュートリアル<4>,turtle --- Turtle graphics
@anchor{library/turtle how-to}@anchor{4429}@anchor{library/turtle turtle-how-to}@anchor{442a}
@subsubsection How to...


This section covers some typical turtle use-cases and approaches.

@menu
* Get started as quickly as possible:: 
* Automatically begin and end filling:: 
* Use the turtle module namespace:: 
* Use turtle graphics in a script:: 
* Use object-oriented turtle graphics:: 

@end menu

@node Get started as quickly as possible,Automatically begin and end filling,,How to
@anchor{library/turtle get-started-as-quickly-as-possible}@anchor{442b}
@subsubsection Get started as quickly as possible


One of the joys of turtle graphics is the immediate, visual feedback that's
available from simple commands - it's an excellent way to introduce children
to programming ideas, with a minimum of overhead (not just children, of
course).

The turtle module makes this possible by exposing all its basic functionality
as functions, available with @code{from turtle import *}. The @ref{4422,,turtle graphics tutorial} covers this approach.

It's worth noting that many of the turtle commands also have even more terse
equivalents, such as @code{fd()} for @ref{360f,,forward()}. These are especially
useful when working with learners for whom typing is not a skill.
@anchor{library/turtle note}@anchor{442c}
@quotation

You'll need to have the @ref{f6,,Tk interface package} installed on
your system for turtle graphics to work. Be warned that this is not
always straightforward, so check this in advance if you're planning to
use turtle graphics with a learner.
@end quotation

@node Automatically begin and end filling,Use the turtle module namespace,Get started as quickly as possible,How to
@anchor{library/turtle automatically-begin-and-end-filling}@anchor{442d}
@subsubsection Automatically begin and end filling


Starting with Python 3.14, you can use the @ref{2a3,,fill()} @ref{1e1,,context manager}
instead of @ref{442e,,begin_fill()} and @ref{442f,,end_fill()} to automatically begin and
end fill. Here is an example:

@example
with fill():
    for i in range(4):
        forward(100)
        right(90)

forward(200)
@end example

The code above is equivalent to:

@example
begin_fill()
for i in range(4):
    forward(100)
    right(90)
end_fill()

forward(200)
@end example

@node Use the turtle module namespace,Use turtle graphics in a script,Automatically begin and end filling,How to
@anchor{library/turtle use-the-turtle-module-namespace}@anchor{4430}
@subsubsection Use the @code{turtle} module namespace


Using @code{from turtle import *} is convenient - but be warned that it imports a
rather large collection of objects, and if you're doing anything but turtle
graphics you run the risk of a name conflict (this becomes even more an issue
if you're using turtle graphics in a script where other modules might be
imported).

The solution is to use @code{import turtle} - @code{fd()} becomes
@code{turtle.fd()}, @code{width()} becomes @code{turtle.width()} and so on. (If typing
"turtle" over and over again becomes tedious, use for example @code{import turtle
as t} instead.)

@node Use turtle graphics in a script,Use object-oriented turtle graphics,Use the turtle module namespace,How to
@anchor{library/turtle use-turtle-graphics-in-a-script}@anchor{4431}
@subsubsection Use turtle graphics in a script


It's recommended to use the @code{turtle} module namespace as described
immediately above, for example:

@example
import turtle as t
from random import random

for i in range(100):
    steps = int(random() * 100)
    angle = int(random() * 360)
    t.right(angle)
    t.fd(steps)
@end example

Another step is also required though - as soon as the script ends, Python
will also close the turtle's window. Add:

@example
t.mainloop()
@end example

to the end of the script. The script will now wait to be dismissed and
will not exit until it is terminated, for example by closing the turtle
graphics window.

@node Use object-oriented turtle graphics,,Use turtle graphics in a script,How to
@anchor{library/turtle use-object-oriented-turtle-graphics}@anchor{4432}
@subsubsection Use object-oriented turtle graphics



@subsubheading 参考


@ref{4433,,Explanation of the object-oriented interface}


Other than for very basic introductory purposes, or for trying things out
as quickly as possible, it's more usual and much more powerful to use the
object-oriented approach to turtle graphics. For example, this allows
multiple turtles on screen at once.

In this approach, the various turtle commands are methods of objects (mostly of
@code{Turtle} objects). You `can' use the object-oriented approach in the shell,
but it would be more typical in a Python script.

The example above then becomes:

@example
from turtle import Turtle
from random import random

t = Turtle()
for i in range(100):
    steps = int(random() * 100)
    angle = int(random() * 360)
    t.right(angle)
    t.fd(steps)

t.screen.mainloop()
@end example

Note the last line. @code{t.screen} is an instance of the @ref{4434,,Screen}
that a Turtle instance exists on; it's created automatically along with
the turtle.

The turtle's screen can be customised, for example:

@example
t.screen.title('Object-oriented turtle demo')
t.screen.bgcolor("orange")
@end example

@node Turtle graphics reference,RawTurtle/Turtle のメソッドと対応する関数,How to,turtle --- Turtle graphics
@anchor{library/turtle turtle-graphics-reference}@anchor{4435}
@subsubsection Turtle graphics reference


@cartouche
@quotation 注釈 
以下の文書では関数に対する引数リストが与えられています。メソッドでは、勿論、ここでは省略されている `self' が第一引数になります。
@end quotation
@end cartouche

@menu
* Turtle のメソッド:: 
* TurtleScreen/Screen のメソッド:: 

@end menu

@node Turtle のメソッド,TurtleScreen/Screen のメソッド,,Turtle graphics reference
@anchor{library/turtle turtle-methods}@anchor{4436}
@subsubsection Turtle のメソッド



@table @asis

@item Turtle の動き


@table @asis

@item 移動および描画


@display
@ref{360f,,forward()} | @ref{4437,,fd()}@w{ }
@ref{4438,,backward()} | @ref{4439,,bk()} | @ref{443a,,back()}@w{ }
@ref{443b,,right()} | @ref{443c,,rt()}@w{ }
@ref{443d,,left()} | @ref{443e,,lt()}@w{ }
@ref{443f,,goto()} | @ref{4440,,setpos()} | @ref{4441,,setposition()}@w{ }
@ref{1a97,,teleport()}@w{ }
@ref{4442,,setx()}@w{ }
@ref{4443,,sety()}@w{ }
@ref{4444,,setheading()} | @ref{4445,,seth()}@w{ }
@ref{4446,,home()}@w{ }
@ref{4447,,circle()}@w{ }
@ref{4448,,dot()}@w{ }
@ref{4449,,stamp()}@w{ }
@ref{444a,,clearstamp()}@w{ }
@ref{444b,,clearstamps()}@w{ }
@ref{444c,,undo()}@w{ }
@ref{444d,,speed()}@w{ }
@end display



@item Turtle の状態を知る


@display
@ref{444e,,position()} | @ref{444f,,pos()}@w{ }
@ref{4450,,towards()}@w{ }
@ref{4451,,xcor()}@w{ }
@ref{4452,,ycor()}@w{ }
@ref{4453,,heading()}@w{ }
@ref{4454,,distance()}@w{ }
@end display



@item 設定と計測


@display
@ref{4455,,degrees()}@w{ }
@ref{4456,,radians()}@w{ }
@end display


@end table

@item Pen の制御


@table @asis

@item 描画状態


@display
@ref{4457,,pendown()} | @ref{4458,,pd()} | @ref{4459,,down()}@w{ }
@ref{445a,,penup()} | @ref{445b,,pu()} | @ref{445c,,up()}@w{ }
@ref{445d,,pensize()} | @ref{445e,,width()}@w{ }
@ref{445f,,pen()}@w{ }
@ref{4460,,isdown()}@w{ }
@end display



@item 色の制御


@display
@ref{4461,,color()}@w{ }
@ref{4462,,pencolor()}@w{ }
@ref{4463,,fillcolor()}@w{ }
@end display



@item 塗りつぶし


@display
@ref{4464,,filling()}@w{ }
@ref{2a3,,fill()}@w{ }
@ref{442e,,begin_fill()}@w{ }
@ref{442f,,end_fill()}@w{ }
@end display



@item さらなる描画の制御


@display
@ref{4465,,reset()}@w{ }
@ref{4466,,clear()}@w{ }
@ref{4467,,write()}@w{ }
@end display


@end table

@item タートルの状態


@table @asis

@item 可視性


@display
@ref{4468,,showturtle()} | @ref{4469,,st()}@w{ }
@ref{446a,,hideturtle()} | @ref{446b,,ht()}@w{ }
@ref{446c,,isvisible()}@w{ }
@end display



@item 見た目


@display
@ref{446d,,shape()}@w{ }
@ref{446e,,resizemode()}@w{ }
@ref{446f,,shapesize()} | @ref{4470,,turtlesize()}@w{ }
@ref{4471,,shearfactor()}@w{ }
@ref{92f,,tiltangle()}@w{ }
@ref{4472,,tilt()}@w{ }
@ref{4473,,shapetransform()}@w{ }
@ref{4474,,get_shapepoly()}@w{ }
@end display


@end table

@item イベントを利用する


@display
@ref{4475,,onclick()}@w{ }
@ref{4476,,onrelease()}@w{ }
@ref{4477,,ondrag()}@w{ }
@end display



@item 特別な Turtle のメソッド


@display
@ref{2a4,,poly()}@w{ }
@ref{4478,,begin_poly()}@w{ }
@ref{4479,,end_poly()}@w{ }
@ref{447a,,get_poly()}@w{ }
@ref{447b,,clone()}@w{ }
@ref{447c,,getturtle()} | @ref{447d,,getpen()}@w{ }
@ref{447e,,getscreen()}@w{ }
@ref{447f,,setundobuffer()}@w{ }
@ref{4480,,undobufferentries()}@w{ }
@end display


@end table

@node TurtleScreen/Screen のメソッド,,Turtle のメソッド,Turtle graphics reference
@anchor{library/turtle methods-of-turtlescreen-screen}@anchor{4481}
@subsubsection TurtleScreen/Screen のメソッド



@table @asis

@item ウィンドウの制御


@display
@ref{4482,,bgcolor()}@w{ }
@ref{4483,,bgpic()}@w{ }
@ref{4484,,clearscreen()}@w{ }
@ref{4485,,resetscreen()}@w{ }
@ref{4486,,screensize()}@w{ }
@ref{4487,,setworldcoordinates()}@w{ }
@end display



@item アニメーションの制御


@display
@ref{2a5,,no_animation()}@w{ }
@ref{4488,,delay()}@w{ }
@ref{4489,,tracer()}@w{ }
@ref{448a,,update()}@w{ }
@end display



@item スクリーンイベントを利用する


@display
@ref{448b,,listen()}@w{ }
@ref{448c,,onkey()} | @ref{448d,,onkeyrelease()}@w{ }
@ref{448e,,onkeypress()}@w{ }
@ref{4475,,onclick()} | @ref{448f,,onscreenclick()}@w{ }
@ref{4490,,ontimer()}@w{ }
@ref{4491,,mainloop()} | @ref{4492,,done()}@w{ }
@end display



@item 設定と特殊なメソッド


@display
@ref{4493,,mode()}@w{ }
@ref{4494,,colormode()}@w{ }
@ref{4495,,getcanvas()}@w{ }
@ref{4496,,getshapes()}@w{ }
@ref{4497,,register_shape()} | @ref{4498,,addshape()}@w{ }
@ref{4499,,turtles()}@w{ }
@ref{449a,,window_height()}@w{ }
@ref{449b,,window_width()}@w{ }
@end display



@item 入力メソッド


@display
@ref{1c7a,,textinput()}@w{ }
@ref{1c7b,,numinput()}@w{ }
@end display



@item Screen 独自のメソッド


@display
@ref{449c,,bye()}@w{ }
@ref{449d,,exitonclick()}@w{ }
@ref{1970,,save()}@w{ }
@ref{449e,,setup()}@w{ }
@ref{449f,,title()}@w{ }
@end display


@end table

@node RawTurtle/Turtle のメソッドと対応する関数,TurtleScreen/Screen のメソッドと対応する関数,Turtle graphics reference,turtle --- Turtle graphics
@anchor{library/turtle methods-of-rawturtle-turtle-and-corresponding-functions}@anchor{44a0}
@subsubsection RawTurtle/Turtle のメソッドと対応する関数


この節のほとんどの例では @code{turtle} という名前の Turtle インスタンスを使います。

@menu
* Turtle の動き:: 
* Turtle の状態を知る:: 
* 設定と計測:: 
* Pen の制御: Pen の制御<2>. 
* タートルの状態:: 
* イベントを利用する:: 
* 特別な Turtle のメソッド:: 
* Compound shapes:: 

@end menu

@node Turtle の動き,Turtle の状態を知る,,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle turtle-motion}@anchor{44a1}
@subsubsection Turtle の動き


@geindex forward() (turtle モジュール)
@geindex fd() (turtle モジュール)
@anchor{library/turtle turtle forward}@anchor{360f}
@deffn {の関数} turtle.forward (distance)
@anchor{library/turtle turtle fd}@anchor{4437}
@deffnx {の関数} turtle.fd (distance)

@*パラメータ: 
@code{distance} -- 数 (整数または浮動小数点数)


タートルが頭を向けている方へ、タートルを距離 `distance' だけ前進させます。

@example
>>> turtle.position()
(0.00,0.00)
>>> turtle.forward(25)
>>> turtle.position()
(25.00,0.00)
>>> turtle.forward(-75)
>>> turtle.position()
(-50.00,0.00)
@end example
@end deffn

@geindex back() (turtle モジュール)
@geindex bk() (turtle モジュール)
@geindex backward() (turtle モジュール)
@anchor{library/turtle turtle back}@anchor{443a}
@deffn {の関数} turtle.back (distance)
@anchor{library/turtle turtle bk}@anchor{4439}
@deffnx {の関数} turtle.bk (distance)
@anchor{library/turtle turtle backward}@anchor{4438}
@deffnx {の関数} turtle.backward (distance)

@*パラメータ: 
@code{distance} -- 数


タートルが頭を向けている方と反対方向へ、タートルを距離 `distance' だけ後退させます。 タートルの向きは変えません。

@c >>> turtle.goto(0, 0)

@example
>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
@end example
@end deffn

@geindex right() (turtle モジュール)
@geindex rt() (turtle モジュール)
@anchor{library/turtle turtle right}@anchor{443b}
@deffn {の関数} turtle.right (angle)
@anchor{library/turtle turtle rt}@anchor{443c}
@deffnx {の関数} turtle.rt (angle)

@*パラメータ: 
@code{angle} -- 数 (整数または浮動小数点数)


タートルを `angle' 単位だけ右に回します。 (単位のデフォルトは度ですが、 @ref{4455,,degrees()} と @ref{4456,,radians()} 関数を使って設定できます。) 角度の向きはタートルのモードによって意味が変わります。 @ref{4493,,mode()} を参照してください。

@c >>> turtle.setheading(22)

@example
>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
@end example
@end deffn

@geindex left() (turtle モジュール)
@geindex lt() (turtle モジュール)
@anchor{library/turtle turtle left}@anchor{443d}
@deffn {の関数} turtle.left (angle)
@anchor{library/turtle turtle lt}@anchor{443e}
@deffnx {の関数} turtle.lt (angle)

@*パラメータ: 
@code{angle} -- 数 (整数または浮動小数点数)


タートルを `angle' 単位だけ左に回します。 (単位のデフォルトは度ですが、 @ref{4455,,degrees()} と @ref{4456,,radians()} 関数を使って設定できます。) 角度の向きはタートルのモードによって意味が変わります。 @ref{4493,,mode()} を参照してください。

@c >>> turtle.setheading(22)

@example
>>> turtle.heading()
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0
@end example
@end deffn

@geindex goto() (turtle モジュール)
@geindex setpos() (turtle モジュール)
@geindex setposition() (turtle モジュール)
@anchor{library/turtle turtle goto}@anchor{443f}
@deffn {の関数} turtle.goto (x, y=None)
@anchor{library/turtle turtle setpos}@anchor{4440}
@deffnx {の関数} turtle.setpos (x, y=None)
@anchor{library/turtle turtle setposition}@anchor{4441}
@deffnx {の関数} turtle.setposition (x, y=None)

@*パラメータ: 

@itemize *

@item 
@code{x} -- 数または数のペア/ベクトル

@item 
@code{y} -- 数または @code{None}
@end itemize


`y' が @code{None} の場合、 `x' は座標のペアかまたは @ref{44a2,,Vec2D} (たとえば @ref{444f,,pos()} で返されます) でなければなりません。

タートルを指定された絶対位置に移動します。ペンが下りていれば線を引きます。タートルの向きは変わりません。

@c >>> turtle.goto(0, 0)

@example
>>> tp = turtle.pos()
>>> tp
(0.00,0.00)
>>> turtle.setpos(60,30)
>>> turtle.pos()
(60.00,30.00)
>>> turtle.setpos((20,80))
>>> turtle.pos()
(20.00,80.00)
>>> turtle.setpos(tp)
>>> turtle.pos()
(0.00,0.00)
@end example
@end deffn

@geindex teleport() (turtle モジュール)
@anchor{library/turtle turtle teleport}@anchor{1a97}
@deffn {の関数} turtle.teleport (x, y=None, *, fill_gap=False)

@*パラメータ: 

@itemize *

@item 
@code{x} -- 数または @code{None}

@item 
@code{y} -- 数または @code{None}

@item 
@code{fill_gap} -- ブール値
@end itemize


Move turtle to an absolute position. Unlike goto(x, y), a line will not
be drawn. The turtle's orientation does not change. If currently
filling, the polygon(s) teleported from will be filled after leaving,
and filling will begin again after teleporting. This can be disabled
with fill_gap=True, which makes the imaginary line traveled during
teleporting act as a fill barrier like in goto(x, y).

@c >>> turtle.goto(0, 0)

@example
>>> tp = turtle.pos()
>>> tp
(0.00,0.00)
>>> turtle.teleport(60)
>>> turtle.pos()
(60.00,0.00)
>>> turtle.teleport(y=10)
>>> turtle.pos()
(60.00,10.00)
>>> turtle.teleport(20, 30)
>>> turtle.pos()
(20.00,30.00)
@end example


Added in version 3.12.

@end deffn

@geindex setx() (turtle モジュール)
@anchor{library/turtle turtle setx}@anchor{4442}
@deffn {の関数} turtle.setx (x)

@*パラメータ: 
@code{x} -- 数 (整数または浮動小数点数)


タートルの第一座標を `x' にします。第二座標は変わりません。

@c >>> turtle.goto(0, 240)

@example
>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
@end example
@end deffn

@geindex sety() (turtle モジュール)
@anchor{library/turtle turtle sety}@anchor{4443}
@deffn {の関数} turtle.sety (y)

@*パラメータ: 
@code{y} -- 数 (整数または浮動小数点数)


タートルの第二座標を `y' にします。第一座標は変わりません。

@c >>> turtle.goto(0, 40)

@example
>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)
@end example
@end deffn

@geindex setheading() (turtle モジュール)
@geindex seth() (turtle モジュール)
@anchor{library/turtle turtle setheading}@anchor{4444}
@deffn {の関数} turtle.setheading (to_angle)
@anchor{library/turtle turtle seth}@anchor{4445}
@deffnx {の関数} turtle.seth (to_angle)

@*パラメータ: 
@code{to_angle} -- 数 (整数または浮動小数点数)


タートルの向きを `to_angle' に設定します。以下はよく使われる方向を度で表わしたものです:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} 
@headitem

標準モード

@tab

logo モード

@item

0 - 東

@tab

0 - 北

@item

90 - 北

@tab

90 - 東

@item

180 - 西

@tab

180 - 南

@item

270 - 南

@tab

270 - 西

@end multitable


@example
>>> turtle.setheading(90)
>>> turtle.heading()
90.0
@end example
@end deffn

@geindex home() (turtle モジュール)
@anchor{library/turtle turtle home}@anchor{4446}
@deffn {の関数} turtle.home ()

タートルを原点 -- 座標 (0, 0) -- に移動し、向きを開始方向に設定します (開始方向はモードに依って違います。 @ref{4493,,mode()} を参照してください)。

@c >>> turtle.setheading(90)
@c >>> turtle.goto(0, -10)

@example
>>> turtle.heading()
90.0
>>> turtle.position()
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
@end example
@end deffn

@geindex circle() (turtle モジュール)
@anchor{library/turtle turtle circle}@anchor{4447}
@deffn {の関数} turtle.circle (radius, extent=None, steps=None)

@*パラメータ: 

@itemize *

@item 
@code{radius} -- 数

@item 
@code{extent} -- 数 (または @code{None})

@item 
@code{steps} -- 整数 (または @code{None})
@end itemize


半径 `radius' の円を描きます。中心はタートルの左 `radius' ユニットの点です。 `extent' -- 角度です -- は円のどの部分を描くかを決定します。 `extent' が与えられなければ、デフォルトで完全な円になります。 `extent' が完全な円でない場合は、弧の一つの端点は、現在のペンの位置です。 `radius' が正の場合、弧は反時計回りに描かれます。そうでなければ、時計回りです。最後にタートルの向きが `extent' 分だけ変わります。

円は内接する正多角形で近似されます。 `steps' でそのために使うステップ数を決定します。この値は与えられなければ自動的に計算されます。また、これを正多角形の描画に利用することもできます。

@example
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(50)
>>> turtle.position()
(-0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(120, 180)  # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0
@end example
@end deffn

@geindex dot() (turtle モジュール)
@anchor{library/turtle turtle dot}@anchor{4448}
@deffn {の関数} turtle.dot ()

@deffnx {の関数} turtle.dot (size)

@deffnx {の関数} turtle.dot (color, /)

@deffnx {の関数} turtle.dot (size, color, /)

@deffnx {の関数} turtle.dot (size, r, g, b, /)

@*パラメータ: 

@itemize *

@item 
@code{size} -- 1 以上の整数 (与えられる場合には)

@item 
@code{color} -- 色を表わす文字列またはタプル
@end itemize


Draw a circular dot with diameter `size', using `color'.  If `size' is
not given, the maximum of @code{pensize+4} and @code{2*pensize} is used.

@example
>>> turtle.home()
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
>>> turtle.position()
(100.00,-0.00)
>>> turtle.heading()
0.0
@end example
@end deffn

@geindex stamp() (turtle モジュール)
@anchor{library/turtle turtle stamp}@anchor{4449}
@deffn {の関数} turtle.stamp ()

キャンバス上の現在タートルがいる位置にタートルの姿のハンコを押します。そのハンコに対して stamp_id が返されますが、これを使うと後で @code{clearstamp(stamp_id)} のように呼び出して消すことができます。

@example
>>> turtle.color("blue")
>>> stamp_id = turtle.stamp()
>>> turtle.fd(50)
@end example
@end deffn

@geindex clearstamp() (turtle モジュール)
@anchor{library/turtle turtle clearstamp}@anchor{444a}
@deffn {の関数} turtle.clearstamp (stampid)

@*パラメータ: 
@code{stampid} -- 整数で、先立つ @ref{4449,,stamp()} 呼出しで返された値でなければなりません


`stampid' に対応するハンコを消します。

@example
>>> turtle.position()
(150.00,-0.00)
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.position()
(200.00,-0.00)
>>> turtle.clearstamp(astamp)
>>> turtle.position()
(200.00,-0.00)
@end example
@end deffn

@geindex clearstamps() (turtle モジュール)
@anchor{library/turtle turtle clearstamps}@anchor{444b}
@deffn {の関数} turtle.clearstamps (n=None)

@*パラメータ: 
@code{n} -- 整数 (または @code{None})


全ての、または最初の/最後の `n' 個のハンコを消します。 `n' が @code{None} の場合、全てのハンコを消します。 `n' が正の場合には最初の `n' 個、 `n' が負の場合には最後の `n' 個を消します。

@example
>>> for i in range(8):
...     unused_stamp_id = turtle.stamp()
...     turtle.fd(30)
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
@end example
@end deffn

@geindex undo() (turtle モジュール)
@anchor{library/turtle turtle undo}@anchor{444c}
@deffn {の関数} turtle.undo ()

最後の(繰り返すことにより複数の)タートルの動きを取り消します。取り消しできる動きの最大数は undobuffer のサイズによって決まります。

@example
>>> for i in range(4):
...     turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
...     turtle.undo()
@end example
@end deffn

@geindex speed() (turtle モジュール)
@anchor{library/turtle turtle speed}@anchor{444d}
@deffn {の関数} turtle.speed (speed=None)

@*パラメータ: 
@code{speed} -- 0 から 10 までの整数またはスピードを表わす文字列(以下の説明を参照)


タートルのスピードを 0 から 10 までの範囲の整数に設定します。引数が与えられない場合は現在のスピードを返します。

与えられた数字が 10 より大きかったり 0.5 より小さかったりした場合は、スピードは 0 になります。スピードを表わす文字列は次のように数字に変換されます:


@itemize *

@item 
"fastest":  0

@item 
"fast":  10

@item 
"normal":  6

@item 
"slow":  3

@item 
"slowest":  1
@end itemize

1 から 10 までのスピードを上げていくにつれて線を描いたりタートルが回ったりするアニメーションがだんだん速くなります。

注意: `speed' = 0 はアニメーションを無くします。forward/backward ではタートルがジャンプし、left/right では瞬時に方向を変えます。

@example
>>> turtle.speed()
3
>>> turtle.speed('normal')
>>> turtle.speed()
6
>>> turtle.speed(9)
>>> turtle.speed()
9
@end example
@end deffn

@node Turtle の状態を知る,設定と計測,Turtle の動き,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle tell-turtle-s-state}@anchor{44a3}
@subsubsection Turtle の状態を知る


@geindex position() (turtle モジュール)
@geindex pos() (turtle モジュール)
@anchor{library/turtle turtle position}@anchor{444e}
@deffn {の関数} turtle.position ()
@anchor{library/turtle turtle pos}@anchor{444f}
@deffnx {の関数} turtle.pos ()

タートルの現在位置を (@ref{44a2,,Vec2D} のベクトルとして) 返します。

@example
>>> turtle.pos()
(440.00,-0.00)
@end example
@end deffn

@geindex towards() (turtle モジュール)
@anchor{library/turtle turtle towards}@anchor{4450}
@deffn {の関数} turtle.towards (x, y=None)

@*パラメータ: 

@itemize *

@item 
@code{x} -- 数または数のペア/ベクトルまたはタートルのインスタンス

@item 
@code{y} -- `x' が数ならば数、そうでなければ @code{None}
@end itemize


タートルの位置から指定された (x,y) への直線の角度を返します。この値はタートルの開始方向にそして開始方向はモード ("standard"/"world" または "logo") に依存します。

@example
>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0
@end example
@end deffn

@geindex xcor() (turtle モジュール)
@anchor{library/turtle turtle xcor}@anchor{4451}
@deffn {の関数} turtle.xcor ()

タートルの x 座標を返します。

@example
>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print(round(turtle.xcor(), 5))
64.27876
@end example
@end deffn

@geindex ycor() (turtle モジュール)
@anchor{library/turtle turtle ycor}@anchor{4452}
@deffn {の関数} turtle.ycor ()

タートルの y 座標を返します。

@example
>>> turtle.home()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print(turtle.pos())
(50.00,86.60)
>>> print(round(turtle.ycor(), 5))
86.60254
@end example
@end deffn

@geindex heading() (turtle モジュール)
@anchor{library/turtle turtle heading}@anchor{4453}
@deffn {の関数} turtle.heading ()

タートルの現在の向きを返します (返される値はタートルのモードに依存します。 @ref{4493,,mode()} を参照してください)。

@example
>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0
@end example
@end deffn

@geindex distance() (turtle モジュール)
@anchor{library/turtle turtle distance}@anchor{4454}
@deffn {の関数} turtle.distance (x, y=None)

@*パラメータ: 

@itemize *

@item 
@code{x} -- 数または数のペア/ベクトルまたはタートルのインスタンス

@item 
@code{y} -- `x' が数ならば数、そうでなければ @code{None}
@end itemize


タートルから与えられた (x,y) あるいはベクトルあるいは渡されたタートルへの距離を、タートルのステップを単位として測った値を返します。

@example
>>> turtle.home()
>>> turtle.distance(30,40)
50.0
>>> turtle.distance((30,40))
50.0
>>> joe = Turtle()
>>> joe.forward(77)
>>> turtle.distance(joe)
77.0
@end example
@end deffn

@node 設定と計測,Pen の制御<2>,Turtle の状態を知る,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle settings-for-measurement}@anchor{44a4}
@subsubsection 設定と計測


@geindex degrees() (turtle モジュール)
@anchor{library/turtle turtle degrees}@anchor{4455}
@deffn {の関数} turtle.degrees (fullcircle=360.0)

@*パラメータ: 
@code{fullcircle} -- 数


角度を計る単位「度」を、円周を何等分するかという値に指定します。デフォルトは360等分で通常の意味での度です。

@example
>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0

>>> # Change angle measurement unit to grad (also known as gon,
>>> # grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0)
>>> turtle.heading()
100.0
>>> turtle.degrees(360)
>>> turtle.heading()
90.0
@end example
@end deffn

@geindex radians() (turtle モジュール)
@anchor{library/turtle turtle radians}@anchor{4456}
@deffn {の関数} turtle.radians ()

角度を計る単位をラジアンにします。 @code{degrees(2*math.pi)} と同じ意味です。

@example
>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966
@end example

@c >>> turtle.degrees(360)
@end deffn

@node Pen の制御<2>,タートルの状態,設定と計測,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle id1}@anchor{44a5}
@subsubsection Pen の制御


@menu
* 描画状態:: 
* 色の制御: 色の制御<2>. 
* 塗りつぶし:: 
* さらなる描画の制御:: 

@end menu

@node 描画状態,色の制御<2>,,Pen の制御<2>
@anchor{library/turtle drawing-state}@anchor{44a6}
@subsubsection 描画状態


@geindex pendown() (turtle モジュール)
@geindex pd() (turtle モジュール)
@geindex down() (turtle モジュール)
@anchor{library/turtle turtle pendown}@anchor{4457}
@deffn {の関数} turtle.pendown ()
@anchor{library/turtle turtle pd}@anchor{4458}
@deffnx {の関数} turtle.pd ()
@anchor{library/turtle turtle down}@anchor{4459}
@deffnx {の関数} turtle.down ()

ペンを下ろします -- 動くと線が引かれます。
@end deffn

@geindex penup() (turtle モジュール)
@geindex pu() (turtle モジュール)
@geindex up() (turtle モジュール)
@anchor{library/turtle turtle penup}@anchor{445a}
@deffn {の関数} turtle.penup ()
@anchor{library/turtle turtle pu}@anchor{445b}
@deffnx {の関数} turtle.pu ()
@anchor{library/turtle turtle up}@anchor{445c}
@deffnx {の関数} turtle.up ()

ペンを上げます -- 動いても線は引かれません。
@end deffn

@geindex pensize() (turtle モジュール)
@geindex width() (turtle モジュール)
@anchor{library/turtle turtle pensize}@anchor{445d}
@deffn {の関数} turtle.pensize (width=None)
@anchor{library/turtle turtle width}@anchor{445e}
@deffnx {の関数} turtle.width (width=None)

@*パラメータ: 
@code{width} -- 正の数


線の太さを `width' にするか、または現在の太さを返します。resizemode が "auto" でタートルの形が多角形の場合、その多角形も同じ太さで描画されます。引数が渡されなければ、現在の pensize が返されます。

@example
>>> turtle.pensize()
1
>>> turtle.pensize(10)   # from here on lines of width 10 are drawn
@end example
@end deffn

@geindex pen() (turtle モジュール)
@anchor{library/turtle turtle pen}@anchor{445f}
@deffn {の関数} turtle.pen (pen=None, **pendict)

@*パラメータ: 

@itemize *

@item 
@code{pen} -- 以下にリストされたキーをもった辞書

@item 
@code{pendict} -- 以下にリストされたキーをキーワードとするキーワード引数
@end itemize


ペンの属性を "pen-dictionary" に以下のキー/値ペアで設定するかまたは返します:


@itemize *

@item 
"shown": True/False

@item 
"pendown": True/False

@item 
"pencolor": 色文字列または色タプル

@item 
"fillcolor": 色文字列または色タプル

@item 
"pensize": 正の数

@item 
"speed": 0 から 10 までの整数

@item 
"resizemode": "auto" または "user" または "noresize"

@item 
"stretchfactor": (正の数, 正の数)

@item 
"outline": 正の数

@item 
"tilt": 数
@end itemize

この辞書を以降の @ref{445f,,pen()} 呼出しに渡して以前のペンの状態に復旧することができます。さらに一つ以上の属性をキーワード引数として渡すこともできます。一つの文で幾つものペンの属性を設定するのに使えます。

@example
>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> sorted(turtle.pen().items())
[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
 ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
 ('shearfactor', 0.0), ('shown', True), ('speed', 9),
 ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
>>> penstate=turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', '@w{'}), ('outline', 1), ('pencolor', 'yellow')]
>>> turtle.pen(penstate, fillcolor="green")
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]
@end example
@end deffn

@geindex isdown() (turtle モジュール)
@anchor{library/turtle turtle isdown}@anchor{4460}
@deffn {の関数} turtle.isdown ()

もしペンが下りていれば @code{True} を、上がっていれば @code{False} を返します。

@example
>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True
@end example
@end deffn

@node 色の制御<2>,塗りつぶし,描画状態,Pen の制御<2>
@anchor{library/turtle color-control}@anchor{44a7}
@subsubsection 色の制御


@geindex pencolor() (turtle モジュール)
@anchor{library/turtle turtle pencolor}@anchor{4462}
@deffn {の関数} turtle.pencolor ()

@deffnx {の関数} turtle.pencolor (color, /)

@deffnx {の関数} turtle.pencolor (r, g, b, /)

ペンの色(pencolor)を設定するかまたは返します。

4種類の入力形式が受け入れ可能です:


@table @asis

@item @code{pencolor()}

Return the current pencolor as color specification string or
as a tuple (see example).  May be used as input to another
color/pencolor/fillcolor/bgcolor call.

@item @code{pencolor(colorstring)}

ペンの色を `colorstring' に設定します。その値は Tk の色指定文字列で、 @code{"red"}, @code{"yellow"}, @code{"#33cc8c"} のような文字列です。

@item @code{pencolor((r, g, b))}

ペンの色を `r', `g', `b' のタプルで表された RGB の色に設定します。各 `r', `g', `b' は 0 から colormode の間の値でなければなりません。ここで colormode は 1.0 か 255 のどちらかです (@ref{4494,,colormode()} を参照)。

@item @code{pencolor(r, g, b)}

ペンの色を `r', `g', `b' で表された RGB の色に設定します。各 `r', `g', `b' は 0 から colormode の間の値でなければなりません。
@end table

タートルの形(turtleshape)が多角形の場合、多角形の外側が新しく設定された色で描かれます。

@example
>>> colormode()
1.0
>>> turtle.pencolor()
'red'
>>> turtle.pencolor("brown")
>>> turtle.pencolor()
'brown'
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
(0.2, 0.8, 0.5490196078431373)
>>> colormode(255)
>>> turtle.pencolor()
(51.0, 204.0, 140.0)
>>> turtle.pencolor('#32c18f')
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
@end example
@end deffn

@geindex fillcolor() (turtle モジュール)
@anchor{library/turtle turtle fillcolor}@anchor{4463}
@deffn {の関数} turtle.fillcolor ()

@deffnx {の関数} turtle.fillcolor (color, /)

@deffnx {の関数} turtle.fillcolor (r, g, b, /)

塗りつぶしの色(fillcolor)を設定するかまたは返します。

4種類の入力形式が受け入れ可能です:


@table @asis

@item @code{fillcolor()}

Return the current fillcolor as color specification string, possibly
in tuple format (see example).  May be used as input to another
color/pencolor/fillcolor/bgcolor call.

@item @code{fillcolor(colorstring)}

塗りつぶしの色を `colorstring' に設定します。その値は Tk の色指定文字列で、 @code{"red"}, @code{"yellow"}, @code{"#33cc8c"} のような文字列です。

@item @code{fillcolor((r, g, b))}

塗りつぶしの色を `r', `g', `b' のタプルで表された RGB の色に設定します。各 `r', `g', `b' は 0 から colormode の間の値でなければなりません。ここで colormode は 1.0 か 255 のどちらかです (@ref{4494,,colormode()} を参照)。

@item @code{fillcolor(r, g, b)}

塗りつぶしの色を `r', `g', `b' で表された RGB の色に設定します。各 `r', `g', `b' は 0 から colormode の間の値でなければなりません。
@end table

タートルの形(turtleshape)が多角形の場合、多角形の内側が新しく設定された色で描かれます。

@example
>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
'violet'
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
>>> turtle.fillcolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor('#ffffff')
>>> turtle.fillcolor()
(255.0, 255.0, 255.0)
@end example
@end deffn

@geindex color() (turtle モジュール)
@anchor{library/turtle turtle color}@anchor{4461}
@deffn {の関数} turtle.color ()

@deffnx {の関数} turtle.color (color, /)

@deffnx {の関数} turtle.color (r, g, b, /)

@deffnx {の関数} turtle.color (pencolor, fillcolor, /)

ペンの色(pencolor)と塗りつぶしの色(fillcolor)を設定するかまたは返します。

いくつかの入力形式が受け入れ可能です。形式ごとに 0 から 3 個の引数を以下のように使います:


@table @asis

@item @code{color()}

現在のペンの色と塗りつぶしの色を @ref{4462,,pencolor()} および @ref{4463,,fillcolor()} で返される色指定文字列またはタプルのペアで返します。

@item @code{color(colorstring)}, @code{color((r,g,b))}, @code{color(r,g,b)}

@ref{4462,,pencolor()} の入力と同じですが、塗りつぶしの色とペンの色、両方を与えられた値に設定します。

@item @code{color(colorstring1, colorstring2)}, @code{color((r1,g1,b1), (r2,g2,b2))}

@code{pencolor(colorstring1)} および @code{fillcolor(colorstring2)} を呼び出すのと等価です。もう一つの入力形式についても同様です。
@end table

タートルの形(turtleshape)が多角形の場合、多角形の内側も外側も新しく設定された色で描かれます。

@example
>>> turtle.color("red", "green")
>>> turtle.color()
('red', 'green')
>>> color("#285078", "#a0c8f0")
>>> color()
((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
@end example
@end deffn

こちらも参照: スクリーンのメソッド @ref{4494,,colormode()} 。

@node 塗りつぶし,さらなる描画の制御,色の制御<2>,Pen の制御<2>
@anchor{library/turtle filling}@anchor{44a8}
@subsubsection 塗りつぶし


@c >>> turtle.home()

@geindex filling() (turtle モジュール)
@anchor{library/turtle turtle filling}@anchor{4464}
@deffn {の関数} turtle.filling ()

Return fillstate (@code{True} if filling, @code{False} else).

@example
>>> turtle.begin_fill()
>>> if turtle.filling():
...    turtle.pensize(5)
... else:
...    turtle.pensize(3)
@end example
@end deffn

@geindex fill() (turtle モジュール)
@anchor{library/turtle turtle fill}@anchor{2a3}
@deffn {の関数} turtle.fill ()

Fill the shape drawn in the @code{with turtle.fill():} block.

@example
>>> turtle.color("black", "red")
>>> with turtle.fill():
...     turtle.circle(80)
@end example

Using @code{fill()} is equivalent to adding the @ref{442e,,begin_fill()} before the
fill-block and @ref{442f,,end_fill()} after the fill-block:

@example
>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()
@end example


Added in version 3.14.

@end deffn

@geindex begin_fill() (turtle モジュール)
@anchor{library/turtle turtle begin_fill}@anchor{442e}
@deffn {の関数} turtle.begin_fill ()

To be called just before drawing a shape to be filled.
@end deffn

@geindex end_fill() (turtle モジュール)
@anchor{library/turtle turtle end_fill}@anchor{442f}
@deffn {の関数} turtle.end_fill ()

最後に呼び出された @ref{442e,,begin_fill()} の後に描かれた図形を塗りつぶします。

Whether or not overlap regions for self-intersecting polygons
or multiple shapes are filled depends on the operating system graphics,
type of overlap, and number of overlaps.  For example, the Turtle star
above may be either all yellow or have some white regions.

@example
>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()
@end example
@end deffn

@node さらなる描画の制御,,塗りつぶし,Pen の制御<2>
@anchor{library/turtle more-drawing-control}@anchor{44a9}
@subsubsection さらなる描画の制御


@geindex reset() (turtle モジュール)
@anchor{library/turtle turtle reset}@anchor{4465}
@deffn {の関数} turtle.reset ()

タートルの描いたものをスクリーンから消し、タートルを中心に戻して、全ての変数をデフォルト値に設定し直します。

@example
>>> turtle.goto(0,-22)
>>> turtle.left(100)
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
@end example
@end deffn

@geindex clear() (turtle モジュール)
@anchor{library/turtle turtle clear}@anchor{4466}
@deffn {の関数} turtle.clear ()

タートルの描いたものをスクリーンから消します。タートルは動かしません。タートルの状態と位置、それに他のタートルたちの描いたものは影響を受けません。
@end deffn

@geindex write() (turtle モジュール)
@anchor{library/turtle turtle write}@anchor{4467}
@deffn {の関数} turtle.write (arg, move=False, align='left', font=('Arial', 8, 'normal'))

@*パラメータ: 

@itemize *

@item 
@code{arg} -- TurtleScreen に書かれるオブジェクト

@item 
@code{move} -- True/False

@item 
@code{align} -- 文字列 "left", "center", right" のどれか

@item 
@code{font} -- 三つ組み (fontname, fontsize, fonttype)
@end itemize


文字を書きます— `arg' の文字列表現を、現在のタートルの位置に、 `align' ("left", "center", "right" のどれか) に従って、 与えられたフォントで。 もし `move' が真ならば、ペンは書いた文の右下隅に移動します。 デフォルトでは、 `move' は @code{False} です。

@example
>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)
@end example
@end deffn

@node タートルの状態,イベントを利用する,Pen の制御<2>,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle turtle-state}@anchor{44aa}
@subsubsection タートルの状態


@menu
* 可視性:: 
* 見た目:: 

@end menu

@node 可視性,見た目,,タートルの状態
@anchor{library/turtle visibility}@anchor{44ab}
@subsubsection 可視性


@geindex hideturtle() (turtle モジュール)
@geindex ht() (turtle モジュール)
@anchor{library/turtle turtle hideturtle}@anchor{446a}
@deffn {の関数} turtle.hideturtle ()
@anchor{library/turtle turtle ht}@anchor{446b}
@deffnx {の関数} turtle.ht ()

タートルを見えなくします。 複雑な図を描いている途中、タートルが見えないようにするのは良い考えです。 というのもタートルを隠すことで描画が目に見えて速くなるからです。

@example
>>> turtle.hideturtle()
@end example
@end deffn

@geindex showturtle() (turtle モジュール)
@geindex st() (turtle モジュール)
@anchor{library/turtle turtle showturtle}@anchor{4468}
@deffn {の関数} turtle.showturtle ()
@anchor{library/turtle turtle st}@anchor{4469}
@deffnx {の関数} turtle.st ()

タートルが見えるようにします。

@example
>>> turtle.showturtle()
@end example
@end deffn

@geindex isvisible() (turtle モジュール)
@anchor{library/turtle turtle isvisible}@anchor{446c}
@deffn {の関数} turtle.isvisible ()

タートルが見えている状態ならば @code{True} を、隠されていれば @code{False} を返します。

@example
>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True
@end example
@end deffn

@node 見た目,,可視性,タートルの状態
@anchor{library/turtle appearance}@anchor{44ac}
@subsubsection 見た目


@geindex shape() (turtle モジュール)
@anchor{library/turtle turtle shape}@anchor{446d}
@deffn {の関数} turtle.shape (name=None)

@*パラメータ: 
@code{name} -- 形の名前(shapename)として正しい文字列


タートルの形を与えられた名前(`name')の形に設定するか、もしくは名前が与えられなければ現在の形の名前を返します。 `name' という名前の形は TurtleScreen の形の辞書に載っていなければなりません。最初は次の多角形が載っています: "arrow", "turtle", "circle", "square", "triangle", "classic"。形についての扱いを学ぶには Screen のメソッド @ref{4497,,register_shape()} を参照して下さい。

@example
>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
@end example
@end deffn

@geindex resizemode() (turtle モジュール)
@anchor{library/turtle turtle resizemode}@anchor{446e}
@deffn {の関数} turtle.resizemode (rmode=None)

@*パラメータ: 
@code{rmode} -- 文字列 "auto", "user", "noresize" のどれか


サイズ変更のモード(resizemode)を "auto", "user", "noresize" のどれかに設定します。もし `rmode' が与えられなければ、現在のサイズ変更モードを返します。それぞれのサイズ変更モードは以下の効果を持ちます:


@itemize -

@item 
"auto": ペンのサイズに対応してタートルの見た目を調整します。

@item 
"user": 伸長係数(stretchfactor)およびアウトライン幅(outlinewidth)の値に対応してタートルの見た目を調整します。これらの値は @ref{446f,,shapesize()} で設定します。

@item 
"noresize": タートルの見た目を調整しません。
@end itemize

@code{resizemode("user")} は @ref{446f,,shapesize()} に引数を渡したときに呼び出されます。

@example
>>> turtle.resizemode()
'noresize'
>>> turtle.resizemode("auto")
>>> turtle.resizemode()
'auto'
@end example
@end deffn

@geindex shapesize() (turtle モジュール)
@geindex turtlesize() (turtle モジュール)
@anchor{library/turtle turtle shapesize}@anchor{446f}
@deffn {の関数} turtle.shapesize (stretch_wid=None, stretch_len=None, outline=None)
@anchor{library/turtle turtle turtlesize}@anchor{4470}
@deffnx {の関数} turtle.turtlesize (stretch_wid=None, stretch_len=None, outline=None)

@*パラメータ: 

@itemize *

@item 
@code{stretch_wid} -- 正の数

@item 
@code{stretch_len} -- 正の数

@item 
@code{outline} -- 正の数
@end itemize


ペンの属性 x/y-伸長係数および/またはアウトラインを返すかまたは設定します。サイズ変更のモードは "user" に設定されます。サイズ変更のモードが "user" に設定されたときかつそのときに限り、タートルは伸長係数(stretchfactor)に従って伸長されて表示されます。 `stretch_wid' は進行方向に直交する向きの伸長係数で、 `stretch_len' は進行方向に沿ったの伸長係数、 `outline' は形のアウトラインの幅を決めるものです。

@example
>>> turtle.shapesize()
(1.0, 1.0, 1)
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize()
(5, 5, 12)
>>> turtle.shapesize(outline=8)
>>> turtle.shapesize()
(5, 5, 8)
@end example
@end deffn

@geindex shearfactor() (turtle モジュール)
@anchor{library/turtle turtle shearfactor}@anchor{4471}
@deffn {の関数} turtle.shearfactor (shear=None)

@*パラメータ: 
@code{shear} -- number (optional)


Set or return the current shearfactor. Shear the turtleshape according to
the given shearfactor shear, which is the tangent of the shear angle.
Do `not' change the turtle's heading (direction of movement).
If shear is not given: return the current shearfactor, i. e. the
tangent of the shear angle, by which lines parallel to the
heading of the turtle are sheared.

@example
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.shearfactor(0.5)
>>> turtle.shearfactor()
0.5
@end example
@end deffn

@geindex tilt() (turtle モジュール)
@anchor{library/turtle turtle tilt}@anchor{4472}
@deffn {の関数} turtle.tilt (angle)

@*パラメータ: 
@code{angle} -- 数


タートルの形(turtleshape)を現在の傾斜角から角度(`angle')だけ回転します。このときタートルの進む方向は `変わりません' 。

@example
>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)
@end example
@end deffn

@geindex tiltangle() (turtle モジュール)
@anchor{library/turtle turtle tiltangle}@anchor{92f}
@deffn {の関数} turtle.tiltangle (angle=None)

@*パラメータ: 
@code{angle} -- a number (optional)


Set or return the current tilt-angle. If angle is given, rotate the
turtleshape to point in the direction specified by angle,
regardless of its current tilt-angle. Do `not' change the turtle's
heading (direction of movement).
If angle is not given: return the current tilt-angle, i. e. the angle
between the orientation of the turtleshape and the heading of the
turtle (its direction of movement).

@example
>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(45)
>>> turtle.tiltangle()
45.0
@end example
@end deffn

@geindex shapetransform() (turtle モジュール)
@anchor{library/turtle turtle shapetransform}@anchor{4473}
@deffn {の関数} turtle.shapetransform (t11=None, t12=None, t21=None, t22=None)

@*パラメータ: 

@itemize *

@item 
@code{t11} -- a number (optional)

@item 
@code{t12} -- a number (optional)

@item 
@code{t21} -- a number (optional)

@item 
@code{t12} -- a number (optional)
@end itemize


Set or return the current transformation matrix of the turtle shape.

If none of the matrix elements are given, return the transformation
matrix as a tuple of 4 elements.
Otherwise set the given elements and transform the turtleshape
according to the matrix consisting of first row t11, t12 and
second row t21, t22. The determinant t11 * t22 - t12 * t21 must not be
zero, otherwise an error is raised.
Modify stretchfactor, shearfactor and tiltangle according to the
given matrix.

@example
>>> turtle = Turtle()
>>> turtle.shape("square")
>>> turtle.shapesize(4,2)
>>> turtle.shearfactor(-0.5)
>>> turtle.shapetransform()
(4.0, -1.0, -0.0, 2.0)
@end example
@end deffn

@geindex get_shapepoly() (turtle モジュール)
@anchor{library/turtle turtle get_shapepoly}@anchor{4474}
@deffn {の関数} turtle.get_shapepoly ()

Return the current shape polygon as tuple of coordinate pairs. This
can be used to define a new shape or components of a compound shape.

@example
>>> turtle.shape("square")
>>> turtle.shapetransform(4, -1, 0, 2)
>>> turtle.get_shapepoly()
((50, -20), (30, 20), (-50, 20), (-30, -20))
@end example
@end deffn

@node イベントを利用する,特別な Turtle のメソッド,タートルの状態,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle using-events}@anchor{44ad}
@subsubsection イベントを利用する



@deffn {の関数} turtle.onclick (fun, btn=1, add=None)

@*パラメータ: 

@itemize *

@item 
@code{fun} -- 2引数の関数でキャンバスのクリックされた点の座標を引数として呼び出されるものです

@item 
@code{btn} -- マウスボタンの番号、デフォルトは 1 (左マウスボタン)

@item 
@code{add} -- @code{True} または @code{False} -- @code{True} ならば、 新しい束縛が追加されますが、そうでなければ、 以前の束縛を置き換えます。
@end itemize


`fun' をタートルのマウスクリック(mouse-click)イベントに束縛します。 `fun' が @code{None} ならば、既存の束縛が取り除かれます。無名タートル、つまり手続き的なやり方の例です:

@example
>>> def turn(x, y):
...     left(180)
...
>>> onclick(turn)  # Now clicking into the turtle will turn it.
>>> onclick(None)  # event-binding will be removed
@end example
@end deffn

@geindex onrelease() (turtle モジュール)
@anchor{library/turtle turtle onrelease}@anchor{4476}
@deffn {の関数} turtle.onrelease (fun, btn=1, add=None)

@*パラメータ: 

@itemize *

@item 
@code{fun} -- 2引数の関数でキャンバスのクリックされた点の座標を引数として呼び出されるものです

@item 
@code{btn} -- マウスボタンの番号、デフォルトは 1 (左マウスボタン)

@item 
@code{add} -- @code{True} または @code{False} -- @code{True} ならば、 新しい束縛が追加されますが、そうでなければ、 以前の束縛を置き換えます。
@end itemize


`fun' をタートルのマウスボタンリリース(mouse-button-release)イベントに束縛します。 `fun' が @code{None} ならば、既存の束縛が取り除かれます。

@example
>>> class MyTurtle(Turtle):
...     def glow(self,x,y):
...         self.fillcolor("red")
...     def unglow(self,x,y):
...         self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
@end example
@end deffn

@geindex ondrag() (turtle モジュール)
@anchor{library/turtle turtle ondrag}@anchor{4477}
@deffn {の関数} turtle.ondrag (fun, btn=1, add=None)

@*パラメータ: 

@itemize *

@item 
@code{fun} -- 2引数の関数でキャンバスのクリックされた点の座標を引数として呼び出されるものです

@item 
@code{btn} -- マウスボタンの番号、デフォルトは 1 (左マウスボタン)

@item 
@code{add} -- @code{True} または @code{False} -- @code{True} ならば、 新しい束縛が追加されますが、そうでなければ、 以前の束縛を置き換えます。
@end itemize


`fun' をタートルのマウスムーブ(mouse-move)イベントに束縛します。 `fun' が @code{None} ならば、既存の束縛が取り除かれます。

注意: 全てのマウスムーブイベントのシーケンスに先立ってマウスクリックイベントが起こります。

@example
>>> turtle.ondrag(turtle.goto)
@end example

この後、タートルをクリックしてドラッグするとタートルはスクリーン上を動きそれによって(ペンが下りていれば)手書きの線ができあがります。
@end deffn

@node 特別な Turtle のメソッド,Compound shapes,イベントを利用する,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle special-turtle-methods}@anchor{44ae}
@subsubsection 特別な Turtle のメソッド


@geindex poly() (turtle モジュール)
@anchor{library/turtle turtle poly}@anchor{2a4}
@deffn {の関数} turtle.poly ()

Record the vertices of a polygon drawn in the @code{with turtle.poly():} block.
The first and last vertices will be connected.

@example
>>> with turtle.poly():
...     turtle.forward(100)
...     turtle.right(60)
...     turtle.forward(100)
@end example


Added in version 3.14.

@end deffn

@geindex begin_poly() (turtle モジュール)
@anchor{library/turtle turtle begin_poly}@anchor{4478}
@deffn {の関数} turtle.begin_poly ()

多角形の頂点の記録を開始します。現在のタートル位置が最初の頂点です。
@end deffn

@geindex end_poly() (turtle モジュール)
@anchor{library/turtle turtle end_poly}@anchor{4479}
@deffn {の関数} turtle.end_poly ()

多角形の頂点の記録を停止します。現在のタートル位置が最後の頂点です。この頂点が最初の頂点と結ばれます。
@end deffn

@geindex get_poly() (turtle モジュール)
@anchor{library/turtle turtle get_poly}@anchor{447a}
@deffn {の関数} turtle.get_poly ()

最後に記録された多角形を返します。

@example
>>> turtle.home()
>>> turtle.begin_poly()
>>> turtle.fd(100)
>>> turtle.left(20)
>>> turtle.fd(30)
>>> turtle.left(60)
>>> turtle.fd(50)
>>> turtle.end_poly()
>>> p = turtle.get_poly()
>>> register_shape("myFavouriteShape", p)
@end example
@end deffn

@geindex clone() (turtle モジュール)
@anchor{library/turtle turtle clone}@anchor{447b}
@deffn {の関数} turtle.clone ()

位置、向きその他のプロパティがそっくり同じタートルのクローンを作って返します。

@example
>>> mick = Turtle()
>>> joe = mick.clone()
@end example
@end deffn

@geindex getturtle() (turtle モジュール)
@geindex getpen() (turtle モジュール)
@anchor{library/turtle turtle getturtle}@anchor{447c}
@deffn {の関数} turtle.getturtle ()
@anchor{library/turtle turtle getpen}@anchor{447d}
@deffnx {の関数} turtle.getpen ()

Turtle オブジェクトそのものを返します。唯一の意味のある使い方: 無名タートルを返す関数として使う:

@example
>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x...>
@end example
@end deffn

@geindex getscreen() (turtle モジュール)
@anchor{library/turtle turtle getscreen}@anchor{447e}
@deffn {の関数} turtle.getscreen ()

タートルが描画中の @ref{44af,,TurtleScreen} オブジェクトを返します。 TurtleScreen のメソッドをそのオブジェクトに対して呼び出すことができます。

@example
>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")
@end example
@end deffn

@geindex setundobuffer() (turtle モジュール)
@anchor{library/turtle turtle setundobuffer}@anchor{447f}
@deffn {の関数} turtle.setundobuffer (size)

@*パラメータ: 
@code{size} -- 整数または @code{None}


アンドゥバッファを設定または無効化します。 `size' が整数ならばそのサイズの空のアンドゥバッファを用意します。 `size' の値はタートルのアクションを何度 @ref{444c,,undo()} メソッド/関数で取り消せるかの最大数を与えます。 `size' が @code{None} ならば、アンドゥバッファは無効化されます。

@example
>>> turtle.setundobuffer(42)
@end example
@end deffn

@geindex undobufferentries() (turtle モジュール)
@anchor{library/turtle turtle undobufferentries}@anchor{4480}
@deffn {の関数} turtle.undobufferentries ()

アンドゥバッファのエントリー数を返します。

@example
>>> while undobufferentries():
...     undo()
@end example
@end deffn

@node Compound shapes,,特別な Turtle のメソッド,RawTurtle/Turtle のメソッドと対応する関数
@anchor{library/turtle compound-shapes}@anchor{44b0}@anchor{library/turtle compoundshapes}@anchor{44b1}
@subsubsection Compound shapes


合成されたタートルの形、つまり幾つかの色の違う多角形から成るような形を使うには、以下のように補助クラス @ref{44b2,,Shape} を直接使わなければなりません:


@enumerate 

@item 
タイプ "compound" の空の Shape オブジェクトを作ります。

@item 
@ref{44b3,,addcomponent()} メソッドを使って、好きなだけここにコンポーネントを追加します。

例えば:

@example
>>> s = Shape("compound")
>>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s.addcomponent(poly1, "red", "blue")
>>> poly2 = ((0,0),(10,-5),(-10,-5))
>>> s.addcomponent(poly2, "blue", "red")
@end example

@item 
こうして作った Shape を Screen の形のリスト(shapelist) に追加して使います:

@example
>>> register_shape("myshape", s)
>>> shape("myshape")
@end example
@end enumerate

@cartouche
@quotation 注釈 
@ref{44b2,,Shape} クラスは @ref{4497,,register_shape()} の内部では違った使われ方をします。アプリケーションを書く人が Shape クラスを扱わなければならないのは、上で示したように合成された形を使うとき `だけ' です！
@end quotation
@end cartouche

@node TurtleScreen/Screen のメソッドと対応する関数,Public classes,RawTurtle/Turtle のメソッドと対応する関数,turtle --- Turtle graphics
@anchor{library/turtle methods-of-turtlescreen-screen-and-corresponding-functions}@anchor{44b4}
@subsubsection TurtleScreen/Screen のメソッドと対応する関数


この節のほとんどの例では @code{screen} という名前の TurtleScreen インスタンスを使います。

@c >>> screen = Screen()

@menu
* ウィンドウの制御:: 
* アニメーションの制御:: 
* スクリーンイベントを利用する:: 
* 入力メソッド:: 
* 設定と特殊なメソッド:: 
* Screen 独自のメソッド、TurtleScreen から継承したもの以外:: 

@end menu

@node ウィンドウの制御,アニメーションの制御,,TurtleScreen/Screen のメソッドと対応する関数
@anchor{library/turtle window-control}@anchor{44b5}
@subsubsection ウィンドウの制御


@geindex bgcolor() (turtle モジュール)
@anchor{library/turtle turtle bgcolor}@anchor{4482}
@deffn {の関数} turtle.bgcolor ()

@deffnx {の関数} turtle.bgcolor (color, /)

@deffnx {の関数} turtle.bgcolor (r, g, b, /)

Return or set the background color of the TurtleScreen.

4種類の入力形式が受け入れ可能です:


@table @asis

@item @code{bgcolor()}

Return the current background color as color specification string or
as a tuple (see example).  May be used as input to another
color/pencolor/fillcolor/bgcolor call.

@item @code{bgcolor(colorstring)}

Set the background color to `colorstring', which is a Tk color
specification string, such as @code{"red"}, @code{"yellow"}, or @code{"#33cc8c"}.

@item @code{bgcolor((r, g, b))}

Set the background color to the RGB color represented by the tuple of
`r', `g', and `b'.
Each of `r', `g', and `b' must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see @ref{4494,,colormode()}).

@item @code{bgcolor(r, g, b)}

Set the background color to the RGB color represented by `r', `g', and `b'.  Each of
`r', `g', and `b' must be in the range 0..colormode.
@end table

@example
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128.0, 0.0, 128.0)
@end example
@end deffn

@geindex bgpic() (turtle モジュール)
@anchor{library/turtle turtle bgpic}@anchor{4483}
@deffn {の関数} turtle.bgpic (picname=None)

@*パラメータ: 
@code{picname} -- a string, name of an image file (PNG, GIF, PGM, and PPM)
or @code{"nopic"}, or @code{None}


背景の画像を設定するかまたは現在の背景画像(backgroundimage)の名前を返します。 `picname' がファイル名ならば、その画像を背景に設定します。 `picname' が @code{"nopic"} ならば、(もしあれば)背景画像を削除します。 `picname' が @code{None} ならば、現在の背景画像のファイル名を返します。

@example
>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
"landscape.gif"
@end example
@end deffn


@deffn {の関数} turtle.clear ()

@cartouche
@quotation 注釈 
この TurtleScreen メソッドはグローバル関数としては @code{clearscreen} という名前でだけ使えます。グローバル関数 @code{clear} は Turtle メソッドの @code{clear} から派生した別ものです。
@end quotation
@end cartouche
@end deffn

@geindex clearscreen() (turtle モジュール)
@anchor{library/turtle turtle clearscreen}@anchor{4484}
@deffn {の関数} turtle.clearscreen ()

全ての図形と全てのタートルを TurtleScreen から削除します。そして空になった TurtleScreen をリセットして初期状態に戻します: 白い背景、背景画像もイベント束縛もなく、トレーシングはオンです。
@end deffn


@deffn {の関数} turtle.reset ()

@cartouche
@quotation 注釈 
この TurtleScreen メソッドはグローバル関数としては @code{resetscreen} という名前でだけ使えます。グローバル関数 @code{reset} は Turtle メソッドの @code{reset} から派生した別ものです。
@end quotation
@end cartouche
@end deffn

@geindex resetscreen() (turtle モジュール)
@anchor{library/turtle turtle resetscreen}@anchor{4485}
@deffn {の関数} turtle.resetscreen ()

スクリーン上の全てのタートルをリセットしその初期状態に戻します。
@end deffn

@geindex screensize() (turtle モジュール)
@anchor{library/turtle turtle screensize}@anchor{4486}
@deffn {の関数} turtle.screensize (canvwidth=None, canvheight=None, bg=None)

@*パラメータ: 

@itemize *

@item 
@code{canvwidth} -- 正の整数でピクセル単位の新しいキャンバス幅(canvaswidth)

@item 
@code{canvheight} -- 正の整数でピクセル単位の新しいキャンバス高さ(canvasheight)

@item 
@code{bg} -- 色文字列または色タプルで新しい背景色
@end itemize


引数が渡されなければ、現在の (キャンバス幅, キャンバス高さ) を返します。そうでなければタートルが描画するキャンバスのサイズを変更します。描画ウィンドウには影響しません。キャンバスの隠れた部分を見るためにはスクロールバーを使って下さい。このメソッドを使うと、以前はキャンバスの外にあったそうした図形の一部を見えるようにすることができます。

@example
>>> screen.screensize()
(400, 300)
>>> screen.screensize(2000,1500)
>>> screen.screensize()
(2000, 1500)
@end example

# 逃げ出してしまったタートルを探すためとかね ;-)
@end deffn

@geindex setworldcoordinates() (turtle モジュール)
@anchor{library/turtle turtle setworldcoordinates}@anchor{4487}
@deffn {の関数} turtle.setworldcoordinates (llx, lly, urx, ury)

@*パラメータ: 

@itemize *

@item 
@code{llx} -- 数でキャンバスの左下隅の x-座標

@item 
@code{lly} -- 数でキャンバスの左下隅の y-座標

@item 
@code{urx} -- 数でキャンバスの右上隅の x-座標

@item 
@code{ury} -- 数でキャンバスの右上隅の y-座標
@end itemize


ユーザー定義座標系を準備し必要ならばモードを "world" に切り替えます。この動作は @code{screen.reset()} を伴います。すでに "world" モードになっていた場合、全ての図形は新しい座標に従って再描画されます。

`重要なお知らせ': ユーザー定義座標系では角度が歪むかもしれません。

@example
>>> screen.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
>>> for _ in range(72):
...     left(10)
...
>>> for _ in range(8):
...     left(45); fd(2)   # a regular octagon
@end example

@c >>> screen.reset()
@c >>> for t in turtles():
@c ...      t.reset()
@end deffn

@node アニメーションの制御,スクリーンイベントを利用する,ウィンドウの制御,TurtleScreen/Screen のメソッドと対応する関数
@anchor{library/turtle animation-control}@anchor{44b6}
@subsubsection アニメーションの制御


@geindex no_animation() (turtle モジュール)
@anchor{library/turtle turtle no_animation}@anchor{2a5}
@deffn {の関数} turtle.no_animation ()

Temporarily disable turtle animation. The code written inside the
@code{no_animation} block will not be animated;
once the code block is exited, the drawing will appear.

@example
>>> with screen.no_animation():
...     for dist in range(2, 400, 2):
...         fd(dist)
...         rt(90)
@end example


Added in version 3.14.

@end deffn

@geindex delay() (turtle モジュール)
@anchor{library/turtle turtle delay}@anchor{4488}
@deffn {の関数} turtle.delay (delay=None)

@*パラメータ: 
@code{delay} -- 正の整数


描画の遅延(`delay')をミリ秒単位で設定するかまたはその値を返します。(これは概ね引き続くキャンバス更新の時間間隔です。) 遅延が大きくなると、アニメーションは遅くなります。

オプション引数:

@example
>>> screen.delay()
10
>>> screen.delay(5)
>>> screen.delay()
5
@end example
@end deffn

@geindex tracer() (turtle モジュール)
@anchor{library/turtle turtle tracer}@anchor{4489}
@deffn {の関数} turtle.tracer (n=None, delay=None)

@*パラメータ: 

@itemize *

@item 
@code{n} -- 非負整数

@item 
@code{delay} -- 非負整数
@end itemize


タートルのアニメーションをオン・オフし、描画更新の遅延を設定します。 `n' が与えられた場合、通常のスクリーン更新のうち 1/n しか実際に実行されません。 (複雑なグラフィックスの描画を加速するのに使えます。) 引数なしで呼び出されたなら、現在保存されている n の値を返します。二つ目の引数は遅延の値を設定します(@ref{4488,,delay()} も参照)。

@example
>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
...     fd(dist)
...     rt(90)
...     dist += 2
@end example
@end deffn

@geindex update() (turtle モジュール)
@anchor{library/turtle turtle update}@anchor{448a}
@deffn {の関数} turtle.update ()

TurtleScreen の更新を実行します。トレーサーがオフの時に使われます。
@end deffn

RawTurtle/Turtle のメソッド @ref{444d,,speed()} も参照して下さい。

@node スクリーンイベントを利用する,入力メソッド,アニメーションの制御,TurtleScreen/Screen のメソッドと対応する関数
@anchor{library/turtle using-screen-events}@anchor{44b7}
@subsubsection スクリーンイベントを利用する


@geindex listen() (turtle モジュール)
@anchor{library/turtle turtle listen}@anchor{448b}
@deffn {の関数} turtle.listen (xdummy=None, ydummy=None)

TurtleScreen に(キー・イベントを収集するために)フォーカスします。ダミー引数は @ref{448b,,listen()} を onclick メソッドに渡せるようにするためのものです。
@end deffn

@geindex onkey() (turtle モジュール)
@geindex onkeyrelease() (turtle モジュール)
@anchor{library/turtle turtle onkey}@anchor{448c}
@deffn {の関数} turtle.onkey (fun, key)
@anchor{library/turtle turtle onkeyrelease}@anchor{448d}
@deffnx {の関数} turtle.onkeyrelease (fun, key)

@*パラメータ: 

@itemize *

@item 
@code{fun} -- 引数なしの関数または @code{None}

@item 
@code{key} -- 文字列: キー (例 "a") またはキー・シンボル (例 "space")
@end itemize


`fun' を指定されたキーのキーリリース(key-release)イベントに束縛します。 `fun' が @code{None} ならばイベント束縛は除かれます。注意: キー・イベントを登録できるようにするためには TurtleScreen はフォーカスを持っていないとなりません(@ref{448b,,listen()} を参照)。

@example
>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
@end example
@end deffn

@geindex onkeypress() (turtle モジュール)
@anchor{library/turtle turtle onkeypress}@anchor{448e}
@deffn {の関数} turtle.onkeypress (fun, key=None)

@*パラメータ: 

@itemize *

@item 
@code{fun} -- 引数なしの関数または @code{None}

@item 
@code{key} -- 文字列: キー (例 "a") またはキー・シンボル (例 "space")
@end itemize


Bind `fun' to key-press event of key if key is given,
or to any key-press-event if no key is given.
Remark: in order to be able to register key-events, TurtleScreen
must have focus. (See method @ref{448b,,listen()}.)

@example
>>> def f():
...     fd(50)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
@end example
@end deffn

@geindex onclick() (turtle モジュール)
@geindex onscreenclick() (turtle モジュール)
@anchor{library/turtle turtle onclick}@anchor{4475}
@deffn {の関数} turtle.onclick (fun, btn=1, add=None)
@anchor{library/turtle turtle onscreenclick}@anchor{448f}
@deffnx {の関数} turtle.onscreenclick (fun, btn=1, add=None)

@*パラメータ: 

@itemize *

@item 
@code{fun} -- 2引数の関数でキャンバスのクリックされた点の座標を引数として呼び出されるものです

@item 
@code{btn} -- マウスボタンの番号、デフォルトは 1 (左マウスボタン)

@item 
@code{add} -- @code{True} または @code{False} -- @code{True} ならば、 新しい束縛が追加されますが、そうでなければ、 以前の束縛を置き換えます。
@end itemize


`fun' をタートルのマウスクリック(mouse-click)イベントに束縛します。 `fun' が @code{None} ならば、既存の束縛が取り除かれます。

Example for a @code{screen} という名の TurtleScreen インスタンスと @code{turtle} という名前の Turtle インスタンスの例:

@example
>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>>                             # make the turtle move to the clicked point.
>>> screen.onclick(None)        # remove event binding again
@end example

@cartouche
@quotation 注釈 
この TurtleScreen メソッドはグローバル関数としては @code{onscreenclick} という名前でだけ使えます。グローバル関数 @code{onclick} は Turtle メソッドの @code{onclick} から派生した別ものです。
@end quotation
@end cartouche
@end deffn

@geindex ontimer() (turtle モジュール)
@anchor{library/turtle turtle ontimer}@anchor{4490}
@deffn {の関数} turtle.ontimer (fun, t=0)

@*パラメータ: 

@itemize *

@item 
@code{fun} -- 引数なし関数

@item 
@code{t} -- 数 >= 0
@end itemize


`t' ミリ秒後に `fun' を呼び出すタイマーを仕掛けます。

@example
>>> running = True
>>> def f():
...     if running:
...         fd(50)
...         lt(60)
...         screen.ontimer(f, 250)
>>> f()   ### makes the turtle march around
>>> running = False
@end example
@end deffn

@geindex mainloop() (turtle モジュール)
@geindex done() (turtle モジュール)
@anchor{library/turtle turtle mainloop}@anchor{4491}
@deffn {の関数} turtle.mainloop ()
@anchor{library/turtle turtle done}@anchor{4492}
@deffnx {の関数} turtle.done ()

Starts event loop - calling Tkinter's mainloop function.
Must be the last statement in a turtle graphics program.
Must `not' be used if a script is run from within IDLE in -n mode
(No subprocess) - for interactive use of turtle graphics.

@example
>>> screen.mainloop()
@end example
@end deffn

@node 入力メソッド,設定と特殊なメソッド,スクリーンイベントを利用する,TurtleScreen/Screen のメソッドと対応する関数
@anchor{library/turtle input-methods}@anchor{44b8}
@subsubsection 入力メソッド


@geindex textinput() (turtle モジュール)
@anchor{library/turtle turtle textinput}@anchor{1c7a}
@deffn {の関数} turtle.textinput (title, prompt)

@*パラメータ: 

@itemize *

@item 
@code{title} -- string

@item 
@code{prompt} -- string
@end itemize


Pop up a dialog window for input of a string. Parameter title is
the title of the dialog window, prompt is a text mostly describing
what information to input.
Return the string input. If the dialog is canceled, return @code{None}.

@example
>>> screen.textinput("NIM", "Name of first player:")
@end example
@end deffn

@geindex numinput() (turtle モジュール)
@anchor{library/turtle turtle numinput}@anchor{1c7b}
@deffn {の関数} turtle.numinput (title, prompt, default=None, minval=None, maxval=None)

@*パラメータ: 

@itemize *

@item 
@code{title} -- string

@item 
@code{prompt} -- string

@item 
@code{default} -- number (optional)

@item 
@code{minval} -- number (optional)

@item 
@code{maxval} -- number (optional)
@end itemize


Pop up a dialog window for input of a number. title is the title of the
dialog window, prompt is a text mostly describing what numerical information
to input. default: default value, minval: minimum value for input,
maxval: maximum value for input.
The number input must be in the range minval .. maxval if these are
given. If not, a hint is issued and the dialog remains open for
correction.
Return the number input. If the dialog is canceled,  return @code{None}.

@example
>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
@end example
@end deffn

@node 設定と特殊なメソッド,Screen 独自のメソッド、TurtleScreen から継承したもの以外,入力メソッド,TurtleScreen/Screen のメソッドと対応する関数
@anchor{library/turtle settings-and-special-methods}@anchor{44b9}
@subsubsection 設定と特殊なメソッド


@geindex mode() (turtle モジュール)
@anchor{library/turtle turtle mode}@anchor{4493}
@deffn {の関数} turtle.mode (mode=None)

@*パラメータ: 
@code{mode} -- 文字列 "standard", "logo", "world" のいずれか


タートルのモード("standard", "logo", "world" のいずれか)を設定してリセットします。モードが渡されなければ現在のモードが返されます。

Mode "standard" is compatible with old @code{turtle}.  Mode "logo" is
compatible with most Logo turtle graphics.  Mode "world" uses user-defined
"world coordinates". `Attention': in this mode angles appear distorted if
@code{x/y} unit-ratio doesn't equal 1.


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} 
@headitem

モード

@tab

タートルの向きの初期値

@tab

正の角度

@item

"standard"

@tab

右 (東) 向き

@tab

反時計回り

@item

"logo"

@tab

上 (北) 向き

@tab

時計回り

@end multitable


@example
>>> mode("logo")   # resets turtle heading to north
>>> mode()
'logo'
@end example
@end deffn

@geindex colormode() (turtle モジュール)
@anchor{library/turtle turtle colormode}@anchor{4494}
@deffn {の関数} turtle.colormode (cmode=None)

@*パラメータ: 
@code{cmode} -- 1.0 か 255 のどちらかの値


色モード(colormode)を返すか、または 1.0 か 255 のどちらかの値に設定します。設定した後は、色トリプルの `r', `g', `b' 値は 0 から `cmode' の範囲になければなりません。

@example
>>> screen.colormode(1)
>>> turtle.pencolor(240, 160, 80)
Traceback (most recent call last):
     ...
TurtleGraphicsError: bad color sequence: (240, 160, 80)
>>> screen.colormode()
1.0
>>> screen.colormode(255)
>>> screen.colormode()
255
>>> turtle.pencolor(240,160,80)
@end example
@end deffn

@geindex getcanvas() (turtle モジュール)
@anchor{library/turtle turtle getcanvas}@anchor{4495}
@deffn {の関数} turtle.getcanvas ()

この TurtleScreen の Canvas を返します。Tkinter の Canvas を使って何をするか知っている人には有用です。

@example
>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas object ...>
@end example
@end deffn

@geindex getshapes() (turtle モジュール)
@anchor{library/turtle turtle getshapes}@anchor{4496}
@deffn {の関数} turtle.getshapes ()

現在使うことのできる全てのタートルの形のリストを返します。

@example
>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']
@end example
@end deffn

@geindex register_shape() (turtle モジュール)
@geindex addshape() (turtle モジュール)
@anchor{library/turtle turtle register_shape}@anchor{4497}
@deffn {の関数} turtle.register_shape (name, shape=None)
@anchor{library/turtle turtle addshape}@anchor{4498}
@deffnx {の関数} turtle.addshape (name, shape=None)

There are four different ways to call this function:


@enumerate 

@item 
`name' is the name of an image file (PNG, GIF, PGM, and PPM) and `shape' is @code{None}: Install the
corresponding image shape.

@example
>>> screen.register_shape("turtle.gif")
@end example

@cartouche
@quotation 注釈 
画像の形はタートルが向きを変えても `回転しません' ので、タートルがどちらを向いているか見ても判りません!
@end quotation
@end cartouche

@item 
`name' is an arbitrary string and `shape' is the name of an image file (PNG, GIF, PGM, and PPM): Install the
corresponding image shape.

@example
>>> screen.register_shape("turtle", "turtle.gif")
@end example

@cartouche
@quotation 注釈 
画像の形はタートルが向きを変えても `回転しません' ので、タートルがどちらを向いているか見ても判りません!
@end quotation
@end cartouche

@item 
`name' が任意の文字列で `shape' が座標ペアのタプル: 対応する多角形を取り込みます。

@example
>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
@end example

@item 
`name' が任意の文字列で `shape' が (合成形の) @ref{44b2,,Shape} オブジェクト: 対応する合成形を取り込みます。
@end enumerate

タートルの形を TurtleScreen の形リスト(shapelist)に加えます。このように登録された形だけが @code{shape(shapename)} コマンドに使えます。


バージョン 3.14 で変更: Added support for PNG, PGM, and PPM image formats.
Both a shape name and an image file name can be specified.

@end deffn

@geindex turtles() (turtle モジュール)
@anchor{library/turtle turtle turtles}@anchor{4499}
@deffn {の関数} turtle.turtles ()

スクリーン上のタートルのリストを返します。

@example
>>> for turtle in screen.turtles():
...     turtle.color("red")
@end example
@end deffn

@geindex window_height() (turtle モジュール)
@anchor{library/turtle turtle window_height}@anchor{449a}
@deffn {の関数} turtle.window_height ()

タートルウィンドウの高さを返します。

@example
>>> screen.window_height()
480
@end example
@end deffn

@geindex window_width() (turtle モジュール)
@anchor{library/turtle turtle window_width}@anchor{449b}
@deffn {の関数} turtle.window_width ()

タートルウィンドウの幅を返します。

@example
>>> screen.window_width()
640
@end example
@end deffn

@node Screen 独自のメソッド、TurtleScreen から継承したもの以外,,設定と特殊なメソッド,TurtleScreen/Screen のメソッドと対応する関数
@anchor{library/turtle methods-specific-to-screen-not-inherited-from-turtlescreen}@anchor{44ba}@anchor{library/turtle screenspecific}@anchor{44bb}
@subsubsection Screen 独自のメソッド、TurtleScreen から継承したもの以外


@geindex bye() (turtle モジュール)
@anchor{library/turtle turtle bye}@anchor{449c}
@deffn {の関数} turtle.bye ()

タートルグラフィックス(turtlegraphics)のウィンドウを閉じます。
@end deffn

@geindex exitonclick() (turtle モジュール)
@anchor{library/turtle turtle exitonclick}@anchor{449d}
@deffn {の関数} turtle.exitonclick ()

スクリーン上のマウスクリックに @code{bye()} メソッドを束縛します。

設定辞書中の "using_IDLE" の値が @code{False} (デフォルトです) の場合、さらにメインループ(mainloop)に入ります。注意: もし IDLE が @code{-n} スイッチ(サブプロセスなし)付きで使われているときは、この値は @code{turtle.cfg} の中で @code{True} とされているべきです。この場合、IDLE のメインループもクライアントスクリプトから見てアクティブです。
@end deffn

@geindex save() (turtle モジュール)
@anchor{library/turtle turtle save}@anchor{1970}
@deffn {の関数} turtle.save (filename, overwrite=False)

Save the current turtle drawing (and turtles) as a PostScript file.

@*パラメータ: 

@itemize *

@item 
@code{filename} -- the path of the saved PostScript file

@item 
@code{overwrite} -- if @code{False} and there already exists a file with the given
filename, then the function will raise a
@code{FileExistsError}. If it is @code{True}, the file will be
overwritten.
@end itemize


@example
>>> screen.save("my_drawing.ps")
>>> screen.save("my_drawing.ps", overwrite=True)
@end example


Added in version 3.14.

@end deffn

@geindex setup() (turtle モジュール)
@anchor{library/turtle turtle setup}@anchor{449e}
@deffn {の関数} turtle.setup (width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])

メインウィンドウのサイズとポジションを設定します。引数のデフォルト値は設定辞書に収められており、 @code{turtle.cfg} ファイルを通じて変更できます。

@*パラメータ: 

@itemize *

@item 
@code{width} -- 整数ならばピクセル単位のサイズ、浮動小数点数ならばスクリーンに対する割合 (スクリーンの 50% がデフォルト)

@item 
@code{height} -- 整数ならばピクセル単位の高さ、浮動小数点数ならばスクリーンに対する割合 (スクリーンの 75% がデフォルト)

@item 
@code{startx} -- 正の数ならばスクリーンの左端からピクセル単位で測った開始位置、 負の数ならば右端から、@code{None} ならば水平方向に真ん中

@item 
@code{starty} -- 正の数ならばスクリーンの上端からピクセル単位で測った開始位置、 負の数ならば下端から、@code{None} ならば垂直方向に真ん中
@end itemize


@example
>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>>              # sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
>>>              # sets window to 75% of screen by 50% of screen and centers
@end example
@end deffn

@geindex title() (turtle モジュール)
@anchor{library/turtle turtle title}@anchor{449f}
@deffn {の関数} turtle.title (titlestring)

@*パラメータ: 
@code{titlestring} -- タートルグラフィックスウィンドウのタイトルバーに表示される文字列


ウインドウのタイトルを `titlestring' に設定します。

@example
>>> screen.title("Welcome to the turtle zoo!")
@end example
@end deffn

@node Public classes,説明<2>,TurtleScreen/Screen のメソッドと対応する関数,turtle --- Turtle graphics
@anchor{library/turtle public-classes}@anchor{44bc}
@subsubsection Public classes


@geindex RawTurtle (turtle のクラス)
@geindex RawPen (turtle のクラス)
@anchor{library/turtle turtle RawTurtle}@anchor{44bd}
@deffn {クラス} turtle.RawTurtle (canvas)
@anchor{library/turtle turtle RawPen}@anchor{44be}
@deffnx {クラス} turtle.RawPen (canvas)

@*パラメータ: 
@code{canvas} -- a @code{tkinter.Canvas}, a @ref{44bf,,ScrolledCanvas} or a
@ref{44af,,TurtleScreen}


タートルを作ります。タートルには上の「Turtle/RawTurtle のメソッド」で説明した全てのメソッドがあります。
@end deffn

@geindex Turtle (turtle のクラス)
@anchor{library/turtle turtle Turtle}@anchor{44c0}
@deffn {クラス} turtle.Turtle

RawTurtle のサブクラスで同じインターフェイスを持ちますが、最初に必要になったとき自動的に作られる @ref{4434,,Screen} オブジェクトに描画します。
@end deffn

@geindex TurtleScreen (turtle のクラス)
@anchor{library/turtle turtle TurtleScreen}@anchor{44af}
@deffn {クラス} turtle.TurtleScreen (cv)

@*パラメータ: 
@code{cv} -- a @code{tkinter.Canvas}


上で説明した @ref{4482,,bgcolor()} のようなスクリーン向けのメソッドを提供します。
@end deffn

@geindex Screen (turtle のクラス)
@anchor{library/turtle turtle Screen}@anchor{4434}
@deffn {クラス} turtle.Screen

TurtleScreen のサブクラスで @ref{44bb,,4つのメソッドが加わっています} 。
@end deffn

@geindex ScrolledCanvas (turtle のクラス)
@anchor{library/turtle turtle ScrolledCanvas}@anchor{44bf}
@deffn {クラス} turtle.ScrolledCanvas (master)

@*パラメータ: 
@code{master} -- この ScrolledCanvas すなわちスクロールバーの付いた Tkinter canvas を収める Tkinter ウィジェット


タートルたちが遊び回る場所として自動的に ScrolledCanvas を提供する Screen クラスによって使われます。
@end deffn

@geindex Shape (turtle のクラス)
@anchor{library/turtle turtle Shape}@anchor{44b2}
@deffn {クラス} turtle.Shape (type_, data)

@*パラメータ: 
@code{type_} -- 文字列 "polygon", "image", "compound" のいずれか


形をモデル化するデータ構造。ペア @code{(type_, data)} は以下の仕様に従わなければなりません:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

`type_'

@tab

`data'

@item

"polygon"

@tab

多角形タプル、すなわち座標ペアのタプル

@item

"image"

@tab

画像  (この形式は内部的にのみ使用されます!)

@item

"compound"

@tab

@code{None} (合成形は @ref{44b3,,addcomponent()} メソッドを使って作らなければなりません)

@end multitable


@geindex addcomponent() (turtle.Shape のメソッド)
@anchor{library/turtle turtle Shape addcomponent}@anchor{44b3}
@deffn {メソッド} addcomponent (poly, fill, outline=None)

@*パラメータ: 

@itemize *

@item 
@code{poly} -- 多角形、すなわち数のペアのタプル

@item 
@code{fill} -- `poly' を塗りつぶす色

@item 
@code{outline} -- `poly' のアウトラインの色 (与えられた場合)
@end itemize


例:

@example
>>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s = Shape("compound")
>>> s.addcomponent(poly, "red", "blue")
>>> # ... add more components and then use register_shape()
@end example

@ref{44b1,,Compound shapes} を参照。
@end deffn
@end deffn

@geindex Vec2D (turtle のクラス)
@anchor{library/turtle turtle Vec2D}@anchor{44a2}
@deffn {クラス} turtle.Vec2D (x, y)

2次元ベクトルのクラスで、タートルグラフィックスを実装するための補助クラス。タートルグラフィックスを使ったプログラムでも有用でしょう。タプルから派生しているので、ベクターはタプルです!

以下の演算が使えます (`a', `b' はベクトル、 `k' は数):


@itemize *

@item 
@code{a + b} ベクトル和

@item 
@code{a - b} ベクトル差

@item 
@code{a * b} 内積

@item 
@code{k * a} および @code{a * k} スカラー倍

@item 
@code{abs(a)} a の絶対値

@item 
@code{a.rotate(angle)} 回転
@end itemize
@end deffn

@node 説明<2>,ヘルプと設定,Public classes,turtle --- Turtle graphics
@anchor{library/turtle explanation}@anchor{44c1}@anchor{library/turtle turtle-explanation}@anchor{4433}
@subsubsection 説明


A turtle object draws on a screen object, and there a number of key classes in
the turtle object-oriented interface that can be used to create them and relate
them to each other.

A @ref{44c0,,Turtle} instance will automatically create a @ref{4434,,Screen}
instance if one is not already present.

@code{Turtle} is a subclass of @ref{44bd,,RawTurtle}, which `doesn't' automatically
create a drawing surface - a `canvas' will need to be provided or created for
it. The `canvas' can be a @code{tkinter.Canvas}, @ref{44bf,,ScrolledCanvas}
or @ref{44af,,TurtleScreen}.

@ref{44af,,TurtleScreen} is the basic drawing surface for a
turtle. @ref{4434,,Screen} is a subclass of @code{TurtleScreen}, and
includes @ref{44bb,,some additional methods} for managing its
appearance (including size and title) and behaviour. @code{TurtleScreen}'s
constructor needs a @code{tkinter.Canvas} or a
@ref{44bf,,ScrolledCanvas} as an argument.

The functional interface for turtle graphics uses the various methods of
@code{Turtle} and @code{TurtleScreen}/@code{Screen}. Behind the scenes, a screen
object is automatically created whenever a function derived from a @code{Screen}
method is called. Similarly, a turtle object is automatically created
whenever any of the functions derived from a Turtle method is called.

To use multiple turtles on a screen, the object-oriented interface must be
used.

@node ヘルプと設定,turtledemo --- Demo scripts,説明<2>,turtle --- Turtle graphics
@anchor{library/turtle help-and-configuration}@anchor{44c2}
@subsubsection ヘルプと設定


@menu
* ヘルプの使い方:: 
* ドキュメント文字列の翻訳:: 
* Screen および Turtle の設定方法:: 

@end menu

@node ヘルプの使い方,ドキュメント文字列の翻訳,,ヘルプと設定
@anchor{library/turtle how-to-use-help}@anchor{44c3}
@subsubsection ヘルプの使い方


Screen と Turtle クラスのパブリックメソッドはドキュメント文字列で網羅的に文書化されていますので、Python のヘルプ機能を通じてオンラインヘルプとして利用できます:


@itemize -

@item 
IDLE を使っているときは、打ち込んだ関数/メソッド呼び出しのシグニチャとドキュメント文字列の一行目がツールチップとして表示されます。

@item 
@ref{ad4,,help()} をメソッドや関数に対して呼び出すとドキュメント文字列が表示されます:

@example
>>> help(Screen.bgcolor)
Help on method bgcolor in module turtle:

bgcolor(self, *args) unbound turtle.Screen method
    Set or return backgroundcolor of the TurtleScreen.

    Arguments (if given): a color string or three numbers
    in the range 0..colormode or a 3-tuple of such numbers.


    >>> screen.bgcolor("orange")
    >>> screen.bgcolor()
    "orange"
    >>> screen.bgcolor(0.5,0,0.5)
    >>> screen.bgcolor()
    "#800080"

>>> help(Turtle.penup)
Help on method penup in module turtle:

penup(self) unbound turtle.Turtle method
    Pull the pen up -- no drawing when moving.

    Aliases: penup | pu | up

    No argument

    >>> turtle.penup()
@end example

@item 
メソッドに由来する関数のドキュメント文字列は変更された形をとります:

@example
>>> help(bgcolor)
Help on function bgcolor in module turtle:

bgcolor(*args)
    Set or return backgroundcolor of the TurtleScreen.

    Arguments (if given): a color string or three numbers
    in the range 0..colormode or a 3-tuple of such numbers.

    Example::

      >>> bgcolor("orange")
      >>> bgcolor()
      "orange"
      >>> bgcolor(0.5,0,0.5)
      >>> bgcolor()
      "#800080"

>>> help(penup)
Help on function penup in module turtle:

penup()
    Pull the pen up -- no drawing when moving.

    Aliases: penup | pu | up

    No argument

    Example:
    >>> penup()
@end example
@end itemize

これらの変更されたドキュメント文字列はインポート時にメソッドから導出される関数定義と一緒に自動的に作られます。

@node ドキュメント文字列の翻訳,Screen および Turtle の設定方法,ヘルプの使い方,ヘルプと設定
@anchor{library/turtle translation-of-docstrings-into-different-languages}@anchor{44c4}
@subsubsection ドキュメント文字列の翻訳


Screen と Turtle クラスのパブリックメソッドについて、キーがメソッド名で値がドキュメント文字列である辞書を作るユーティリティがあります。

@geindex write_docstringdict() (turtle モジュール)
@anchor{library/turtle turtle write_docstringdict}@anchor{44c5}
@deffn {の関数} turtle.write_docstringdict (filename='turtle_docstringdict')

@*パラメータ: 
@code{filename} -- ファイル名として使われる文字列


ドキュメント文字列辞書(docstring-dictionary)を作って与えられたファイル名の Python スクリプトに書き込みます。この関数はわざわざ呼び出さなければなりません (タートルグラフィックスのクラスから使われることはありません)。ドキュメント文字列辞書は @code{`filename'.py} という Python スクリプトに書き込まれます。ドキュメント文字列の異なった言語への翻訳に対するテンプレートとして使われることを意図したものです。
@end deffn

If you (or your students) want to use @code{turtle} with online help in your
native language, you have to translate the docstrings and save the resulting
file as e.g. @code{turtle_docstringdict_german.py}.

さらに @code{turtle.cfg} ファイルで適切な設定をしておけば、このファイルがインポート時に読み込まれて元の英語のドキュメント文字列を置き換えます。

この文書を書いている時点ではドイツ語とイタリア語のドキュメント文字列辞書が存在します。 ( @email{glingl@@aon.at} にリクエストして下さい。)

@node Screen および Turtle の設定方法,,ドキュメント文字列の翻訳,ヘルプと設定
@anchor{library/turtle how-to-configure-screen-and-turtles}@anchor{44c6}
@subsubsection Screen および Turtle の設定方法


初期デフォルト設定では古い turtle の見た目と振る舞いを真似るようにして、互換性を最大限に保つようにしています。

このモジュールの特性を反映した、あるいは個々人の必要性 (たとえばクラスルームでの使用)に合致した、異なった設定を使いたい場合、設定ファイル @code{turtle.cfg} を用意してインポート時に読み込ませその設定に従わせることができます。

初期設定は以下の @code{turtle.cfg} に対応します:

@example
width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False
@end example

いくつかピックアップしたエントリーの短い説明:


@itemize -

@item 
最初の4行は @ref{449e,,Screen.setup} メソッドの引数に当たります。

@item 
5行目6行目は @ref{4486,,Screen.screensize} メソッドの引数に当たります。

@item 
`shape' は最初から用意されている形ならどれでも使えます(arrow, turtle など)。詳しくは @code{help(shape)} をお試し下さい。

@item 
塗りつぶしの色(fill color)を使いたくない(つまりタートルを透明にしたい)場合、 @code{fillcolor = ""} と書かなければなりません (しかし全ての空でない文字列は cfg ファイル中で引用符を付けてはいけません)。

@item 
タートルにその状態を反映させるためには @code{resizemode = auto} とします。

@item 
If you set e.g. @code{language = italian} the docstringdict
@code{turtle_docstringdict_italian.py} will be loaded at import time (if
present on the import path, e.g. in the same directory as @code{turtle}).

@item 
`exampleturtle' および `examplescreen' はこれらのオブジェクトのドキュメント文字列内での呼び名を決めます。メソッドのドキュメント文字列から関数のドキュメント文字列に変換する際に、これらの名前は取り除かれます。

@item 
`using_IDLE': IDLE とその @code{-n} スイッチ(サブプロセスなし)を常用するならば、この値を @code{True} に設定して下さい。これにより @ref{449d,,exitonclick()} がメインループ(mainloop)に入るのを阻止します。
@end itemize

There can be a @code{turtle.cfg} file in the directory where @code{turtle} is
stored and an additional one in the current working directory.  The latter will
override the settings of the first one.

@code{Lib/turtledemo} ディレクトリにも @code{turtle.cfg} ファイルがあります。 デモを実際に(できればデモビュワーからでなく)実行してそこに書かれたものとその効果を学びましょう。

@node turtledemo --- Demo scripts,python 2 6からの変更点,ヘルプと設定,turtle --- Turtle graphics
@anchor{library/turtle module-turtledemo}@anchor{108}@anchor{library/turtle turtledemo-demo-scripts}@anchor{44c7}
@subsubsection @code{turtledemo} --- Demo scripts


@geindex module; turtledemo

The @code{turtledemo} package includes a set of demo scripts.  These
scripts can be run and viewed using the supplied demo viewer as follows:

@example
python -m turtledemo
@end example

あるいは、個別にデモスクリプトを実行できます。たとえば 、:

@example
python -m turtledemo.bytedesign
@end example

The @code{turtledemo} package directory contains:


@itemize -

@item 
ソースコードを眺めつつスクリプトを実行できるデモビュワー @code{__main__.py} 。

@item 
Multiple scripts demonstrating different features of the @code{turtle}
module.  Examples can be accessed via the Examples menu.  They can also
be run standalone.

@item 
設定ファイルの書き方や使い方の例として参考にできる @code{turtle.cfg} ファイル。
@end itemize

デモスクリプトは以下の通りです:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名前

@tab

説明

@tab

フィーチャー

@item

@code{bytedesign}

@tab

複雑な古典的タートルグラフィックスパターン

@tab

@ref{4489,,tracer()}, @ref{4488,,delay()},
@ref{448a,,update()}

@item

@code{chaos}

@tab

verhust 力学系のグラフ化, コンピュータの計算が常識的な予想に反する場合があることを示します。

@tab

世界座標系

@item

@code{clock}

@tab

コンピュータの時間を示すアナログ時計

@tab

turtles as clock's
hands, @ref{4490,,ontimer()}

@item

@code{colormixer}

@tab

r, g, b の実験

@tab

@ref{4477,,ondrag()}

@item

@code{forest}

@tab

3 breadth-first trees

@tab

randomization

@item

@code{fractalcurves}

@tab

Hilbert & Koch 曲線

@tab

再帰

@item

@code{lindenmayer}

@tab

民俗的数学 (インド kolams)

@tab

L-システム

@item

@code{minimal_hanoi}

@tab

ハノイの塔

@tab

Rectangular Turtles
as Hanoi discs
(@ref{446d,,shape()}, @ref{446f,,shapesize()})

@item

@code{nim}

@tab

play the classical nim game
with three heaps of sticks
against the computer.

@tab

turtles as nimsticks,
event driven (mouse,
keyboard)

@item

@code{paint}

@tab

超極小主義的描画プログラム

@tab

@ref{4475,,onclick()}

@item

@code{peace}

@tab

初歩的

@tab

turtle: 見た目とアニメーション

@item

@code{penrose}

@tab

凧と矢による非周期的タイリング

@tab

@ref{4449,,stamp()}

@item

@code{planet_and_moon}

@tab

重力系のシミュレーション

@tab

合成形, @ref{44a2,,Vec2D}

@item

@code{rosette}

@tab

タートルグラフィックスについての wikipedia の記事の例

@tab

@ref{447b,,clone()},
@ref{444c,,undo()}

@item

@code{round_dance}

@tab

dancing turtles rotating
pairwise in opposite
direction

@tab

compound shapes, @ref{447b,,clone()}
@ref{446f,,shapesize()}, @ref{4472,,tilt()},
@ref{4474,,get_shapepoly()}, @ref{448a,,update()}

@item

@code{sorting_animate}

@tab

visual demonstration of
different sorting methods

@tab

simple alignment,
randomization

@item

@code{tree}

@tab

(図形的) 幅優先木 (ジェネレータを使って)

@tab

@ref{447b,,clone()}

@item

@code{two_canvases}

@tab

simple design

@tab

turtles on two
canvases

@item

@code{yinyang}

@tab

もう一つの初歩的な例

@tab

@ref{4447,,circle()}

@end multitable


楽しんでね!

@node python 2 6からの変更点,python 3 0からの変更点,turtledemo --- Demo scripts,turtle --- Turtle graphics
@anchor{library/turtle changes-since-python-2-6}@anchor{44c8}
@subsubsection python 2.6からの変更点



@itemize -

@item 
The methods @ref{4489,,Turtle.tracer}, @ref{449b,,Turtle.window_width} and
@ref{449a,,Turtle.window_height} have been eliminated.
Methods with these names and functionality are now available only
as methods of @ref{4434,,Screen}. The functions derived from these remain
available. (In fact already in Python 2.6 these methods were merely
duplications of the corresponding
@ref{44af,,TurtleScreen}/@ref{4434,,Screen} methods.)

@item 
The method @code{Turtle.fill()} has been eliminated.
The behaviour of @ref{442e,,begin_fill()} and @ref{442f,,end_fill()}
have changed slightly: now every filling process must be completed with an
@code{end_fill()} call.

@item 
A method @ref{4464,,Turtle.filling} has been added. It returns a boolean
value: @code{True} if a filling process is under way, @code{False} otherwise.
This behaviour corresponds to a @code{fill()} call without arguments in
Python 2.6.
@end itemize

@node python 3 0からの変更点,,python 2 6からの変更点,turtle --- Turtle graphics
@anchor{library/turtle changes-since-python-3-0}@anchor{44c9}
@subsubsection python 3.0からの変更点



@itemize -

@item 
The @ref{44c0,,Turtle} methods @ref{4471,,shearfactor()}, @ref{4473,,shapetransform()} and
@ref{4474,,get_shapepoly()} have been added. Thus the full range of
regular linear transforms is now available for transforming turtle shapes.
@ref{92f,,tiltangle()} has been enhanced in functionality: it now can
be used to get or set the tilt angle.

@item 
The @ref{4434,,Screen} method @ref{448e,,onkeypress()} has been added as a complement to
@ref{448c,,onkey()}. As the latter binds actions to the key release event,
an alias: @ref{448d,,onkeyrelease()} was also added for it.

@item 
The method @ref{4491,,Screen.mainloop} has been added,
so there is no longer a need to use the standalone @ref{4491,,mainloop()} function
when working with @ref{4434,,Screen} and @ref{44c0,,Turtle} objects.

@item 
Two input methods have been added: @ref{1c7a,,Screen.textinput} and
@ref{1c7b,,Screen.numinput}. These pop up input dialogs and return
strings and numbers respectively.
@end itemize

@c >>> for turtle in turtles():
@c ...      turtle.reset()
@c >>> turtle.penup()
@c >>> turtle.goto(-200,25)
@c >>> turtle.pendown()
@c >>> turtle.write("No one expects the Spanish Inquisition!",
@c ...      font=("Arial", 20, "normal"))
@c >>> turtle.penup()
@c >>> turtle.goto(-100,-50)
@c >>> turtle.pendown()
@c >>> turtle.write("Our two chief Turtles are...",
@c ...      font=("Arial", 16, "normal"))
@c >>> turtle.penup()
@c >>> turtle.goto(-450,-75)
@c >>> turtle.write(str(turtles()))

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Other sections I have in mind are
@c Tkinter internals
@c Freezing Tkinter applications

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 開発ツール,デバッグとプロファイル,Graphical user interfaces with Tk,Python 標準ライブラリ
@anchor{library/development doc}@anchor{44ca}@anchor{library/development development}@anchor{44cb}@anchor{library/development development-tools}@anchor{44cc}@anchor{library/development translation-repo}@anchor{44cd}
@section 開発ツール


この章で紹介されるモジュールはソフトウェアを書くことを支援します。たとえば、 @ref{ba,,pydoc} モジュールはモジュールの内容からドキュメントを生成します。 @ref{3e,,doctest} と @ref{10c,,unittest} モジュールでは、自動的に実行して予想通りの出力が生成されるか確認するユニットテストを書くことができます。

この章で解説されるモジュールのリスト:

@menu
* typing: typing --- Support for type hints. Support for type hints
* pydoc: pydoc --- ドキュメント生成とオンラインヘルプシステム. ドキュメント生成とオンラインヘルプシステム
* Python 開発モード:: 
* doctest: doctest --- 対話型の Python の例をテストする. 対話型の Python の例をテストする
* unittest: unittest --- ユニットテストフレームワーク. ユニットテストフレームワーク
* unittest.mock: unittest mock --- モックオブジェクトライブラリ. モックオブジェクトライブラリ
* unittest.mock: unittest mock --- 入門. 入門
* test: test --- Regression tests package for Python. Regression tests package for 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
* test.support.threading_helper: test support threading_helper --- Utilities for threading tests. Utilities for threading tests
* test.support.os_helper: test support os_helper --- Utilities for os tests. Utilities for os tests
* test.support.import_helper: test support import_helper --- Utilities for import tests. Utilities for import tests
* test.support.warnings_helper: test support warnings_helper --- Utilities for warnings tests. Utilities for warnings tests

@end menu

@node typing --- Support for type hints,pydoc --- ドキュメント生成とオンラインヘルプシステム,,開発ツール
@anchor{library/typing doc}@anchor{44ce}@anchor{library/typing typing-support-for-type-hints}@anchor{44cf}
@subsection @code{typing} --- Support for type hints


@c import typing
@c from dataclasses import dataclass
@c from typing import *

@geindex module; typing
@anchor{library/typing module-typing}@anchor{10a}

Added in version 3.5.


`ソースコード:' Lib/typing.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/typing.py}

@cartouche
@quotation 注釈 
Python ランタイムは、関数や変数の型アノテーションを強制しません。型アノテーションは、 @ref{574,,type checkers} や IDE、linterなどのサードパーティーツールで使われます。
@end quotation
@end cartouche


__________________________________________________________________


このモジュールは型ヒントの実行時サポートを提供します。

以下の関数を例に考えてみます:

@example
def surface_area_of_cube(edge_length: float) -> str:
    return f"The surface area of the cube is @{6 * edge_length ** 2@}."
@end example

@code{surface_area_of_cube} 関数は、@code{edge_length: float} という @ref{23cb,,type hint} で示されているように、引数が @ref{196,,float} のインスタンスであるという前提です。
そして、@code{-> str} というヒントにある通り、この関数は @ref{169,,str} のインスタンスを返すことになっています。

型ヒントは @ref{196,,float} や @ref{169,,str} のような単純な型を指定することもできますし、もっと複雑な型も指定できます。
@ref{10a,,typing} モジュールには、より高度な型ヒントを表現するためのいろいろな型が含まれています。

@code{typing} モジュールには新しい機能が頻繁に追加されます。
typing_extensions@footnote{https://pypi.org/project/typing_extensions/} パッケージを使うことで、古い Python バージョンからもその新機能を使うことができます。


@subsubheading 参考



@table @asis

@item Typing cheat sheet@footnote{https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html}

型ヒントの簡単な概要 (mypy ドキュメンテーション)

@item Type System Reference section of the mypy docs@footnote{https://mypy.readthedocs.io/en/stable/index.html}

Python の型システムの規格は PEP によって定められているので、このレファレンスはほとんどの Python 型チェッカーに適用できるはずです。(mypy のみに適用される部分もあるかもしれません。)

@item Static Typing with Python@footnote{https://typing.python.org/en/latest/}

コミュニティーによって書かれた、型システムの機能や便利な型関連のツール、型に関するベストプラクティスを詳しく説明している、特定の型チェッカーに依らないドキュメンテーション。
@end table


@menu
* Python 型システムの仕様:: 
* 型エイリアス:: 
* NewType:: 
* 呼び出し可能オブジェクトのアノテーション:: 
* ジェネリクス:: 
* タプルのアノテーション:: 
* クラスオブジェクトの型:: 
* Annotating generators and coroutines:: 
* ユーザー定義のジェネリック型:: 
* Any 型:: 
* 名前的部分型 vs 構造的部分型:: 
* モジュールの内容: モジュールの内容<3>. 
* メジャーな機能の非推奨時系列:: 

@end menu

@node Python 型システムの仕様,型エイリアス,,typing --- Support for type hints
@anchor{library/typing relevant-peps}@anchor{44d0}@anchor{library/typing specification-for-the-python-type-system}@anchor{44d1}
@subsubsection Python 型システムの仕様


The canonical, up-to-date specification of the Python type system can be
found at Specification for the Python type system@footnote{https://typing.python.org/en/latest/spec/index.html}.

@node 型エイリアス,NewType,Python 型システムの仕様,typing --- Support for type hints
@anchor{library/typing id2}@anchor{44d2}@anchor{library/typing type-aliases}@anchor{683}
@subsubsection 型エイリアス


型エイリアスは @ref{66d,,type} 文を用いて定義され、 @ref{2ae,,TypeAliasType} インスタンスが生成されます。 この例では、静的型チェッカーは @code{Vector} と @code{list[float]} を等しいものとして扱います

@example
type Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# floatのlistはVectorとして要件を満たすため、型チェックを通過する。
new_vector = scale(2.0, [1.0, -4.2, 5.4])
@end example

型エイリアスは複雑な型シグネチャを単純化するのに有用です。例えば:

@example
from collections.abc import Sequence

type ConnectionOptions = dict[str, str]
type Address = tuple[str, int]
type Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# 静的型チェッカーでは、上記の型アノテーションと
# 以下のアノテーションを同等のものとして扱う。
def broadcast_message(
    message: str,
    servers: Sequence[tuple[tuple[str, int], dict[str, str]]]
) -> None:
    ...
@end example

@ref{66d,,type} 文はPython3.12で新しく導入されました。後方互換性のために、単に代入によって型エイリアスを作成することもできます：

@example
Vector = list[float]
@end example

あるいは、 @ref{9cc,,TypeAlias} でマークすることで、これが通常の変数代入ではなく、型エイリアスであることを明示できます

@example
from typing import TypeAlias

Vector: TypeAlias = list[float]
@end example

@node NewType,呼び出し可能オブジェクトのアノテーション,型エイリアス,typing --- Support for type hints
@anchor{library/typing distinct}@anchor{44d3}@anchor{library/typing newtype}@anchor{44d4}
@subsubsection NewType


異なる型を作るためには @ref{ef1,,NewType} ヘルパークラスを使います:

@example
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
@end example

静的型チェッカーは新しい型を元々の型のサブクラスのように扱います。この振る舞いは論理的な誤りを見つける手助けとして役に立ちます。

@example
def get_user_name(user_id: UserId) -> str:
    ...

# 型チェックを通過する
user_a = get_user_name(UserId(42351))

# 型チェックに失敗する。int型はUserId型ではないため。
user_b = get_user_name(-1)
@end example

@code{UserId} 型の変数も @code{int} の全ての演算が行えますが、その結果は常に @code{int} 型になります。
この振る舞いにより、 @code{int} が期待されるところに @code{UserId} を渡せますが、不正な方法で @code{UserId} を作ってしまうことを防ぎます。

@example
# 'output' は'int'型となる。'UserId'型にはならない。
output = UserId(23413) + UserId(54341)
@end example

これらのチェックは静的型チェッカーのみによって強制されるということに注意してください。
実行時に @code{Derived = NewType('Derived', Base)} という文は渡された仮引数をただちに返す @code{Derived} callable を作ります。
つまり @code{Derived(some_value)} という式は新しいクラスを作ることはなく、通常の関数呼び出しより多くのオーバーヘッドがないということを意味します。

より正確に言うと、式 @code{some_value is Derived(some_value)} は実行時に常に真を返します。

@code{Derived} のサブタイプを作成することはできません

@example
from typing import NewType

UserId = NewType('UserId', int)

# 実行時にエラーとなり、型チェックも通らない
class AdminUserId(UserId): pass
@end example

しかし、 'derived' である @code{NewType} をもとにした @ref{ef1,,NewType} は作ることが出来ます:

@example
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
@end example

そして @code{ProUserId} に対する型検査は期待通りに動作します。

より詳しくは 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} を参照してください。

@cartouche
@quotation 注釈 
型エイリアスの使用は、2つの型が互いに等価であることを宣言することを思い出してください。 @code{type Alias = Original} とすると、静的型チェッカーは @code{Alias} を @code{Original} と"正確に等価な"ものとして扱います。これは、複雑な型シグネチャを単純化したい場合に便利です。

これに対し、 @code{NewType} はある型をもう一方の型の `サブタイプ' として宣言します。 @code{Derived = NewType('Derived', Original)} とすると静的型検査器は @code{Derived} を @code{Original} の `サブクラス' として扱います。つまり @code{Original} 型の値は @code{Derived} 型の値が期待される場所で使うことが出来ないということです。これは論理的な誤りを最小の実行時のコストで防ぎたい時に有用です。
@end quotation
@end cartouche


Added in version 3.5.2.



バージョン 3.10 で変更: @code{NewType} は関数ではなくクラスになりました。その結果、通常の関数よりも @code{NewType} を呼び出す際に多少の実行時コストが追加されます。



バージョン 3.11 で変更: @code{NewType} 呼び出し時のパフォーマンスが Python 3.9 のレベルに戻りました


@node 呼び出し可能オブジェクトのアノテーション,ジェネリクス,NewType,typing --- Support for type hints
@anchor{library/typing annotating-callable-objects}@anchor{44d5}@anchor{library/typing annotating-callables}@anchor{26cf}
@subsubsection 呼び出し可能オブジェクトのアノテーション


関数、または他の @ref{2d7b,,callable} なオブジェクトは、 @ref{9eb,,collections.abc.Callable} または @ref{9c8,,typing.Callable} を使ってアノテーションすることができます。 @code{Callable[[int], str]} は、 @ref{19b,,int} 型のパラメータを1つ受け取り、 @ref{169,,str} を返す関数を意味します。

例えば:

@example
from collections.abc import Callable, Awaitable

def feeder(get_next_item: Callable[[], str]) -> None:
    ...  # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    ...  # Body

async def on_update(value: str) -> None:
    ...  # Body

callback: Callable[[str], Awaitable[None]] = on_update
@end example

@geindex ...;ellipsisリテラル

The subscription syntax must always be used with exactly two values: the
argument list and the return type.  The argument list must be a list of types,
a @ref{487,,ParamSpec}, @ref{9c7,,Concatenate}, or an ellipsis (@code{...}). The return type must
be a single type.

もしellipsisリテラル @code{...} が引数リストとして与えられた場合、それは任意のパラメータリストを持つ呼び出し可能オブジェクトを受け入れることを示します。

@example
def concat(x: str, y: str) -> str:
    return x + y

x: Callable[..., str]
x = str     # OK
x = concat  # これもOK
@end example

@code{Callable} は可変引数、@ref{44d6,,オーバーロード関数}、キーワード専用引数などを含む複雑な型シグネチャを表現することはできません。
しかし、@ref{56b,,Protocol} クラスとその @ref{77a,,__call__()} メソッドを定義すれば表現することができます:

@example
from collections.abc import Iterable
from typing import Protocol

class Combiner(Protocol):
    def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...

def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
    for item in data:
        ...

def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
    ...
def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
    ...

batch_proc([], good_cb)  # OK
batch_proc([], bad_cb)   # Error! Argument 2 has incompatible type because of
                         # different name and kind in the callback
@end example

callable が別の callable を引数に取る場合は、@ref{487,,ParamSpec} を使えば両者のパラメータ引数の依存関係を表現することができます。
さらに、ある callable が別の callable から引数を追加したり削除したりする場合は、 @ref{9c7,,Concatenate} 演算子を使うことで表現できます。
その場合、callable の型は @code{Callable[ParamSpecVariable, ReturnType]} と @code{Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]} という形になります。


バージョン 3.10 で変更: @code{Callable} は @ref{487,,ParamSpec} と @ref{9c7,,Concatenate} をサポートしました。詳細は 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} を参照してください。



@subsubheading 参考


@ref{487,,ParamSpec} と @ref{9c7,,Concatenate} のドキュメントに、@code{Callable} での使用例が記載されています。


@node ジェネリクス,タプルのアノテーション,呼び出し可能オブジェクトのアノテーション,typing --- Support for type hints
@anchor{library/typing generics}@anchor{23c9}@anchor{library/typing id3}@anchor{44d7}
@subsubsection ジェネリクス


コンテナに含まれるオブジェクトに関する型情報は、一般的な方法で静的に推論することができないため、標準ライブラリの多くのコンテナクラスは、要素に期待する型を示す添字表記をサポートしています

@example
from collections.abc import Mapping, Sequence

class Employee: ...

# Sequence[Employee] indicates that all elements in the sequence
# must be instances of "Employee".
# Mapping[str, str] indicates that all keys and all values in the mapping
# must be strings.
def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
@end example

Generic functions and classes can be parameterized by using
@ref{5ad,,type parameter syntax}:

@example
from collections.abc import Sequence

def first[T](l: Sequence[T]) -> T:  # Function is generic over the TypeVar "T"
    return l[0]
@end example

Or by using the @ref{486,,TypeVar} factory directly:

@example
from collections.abc import Sequence
from typing import TypeVar

U = TypeVar('U')                  # Declare type variable "U"

def second(l: Sequence[U]) -> U:  # Function is generic over the TypeVar "U"
    return l[1]
@end example


バージョン 3.12 で変更: Syntactic support for generics is new in Python 3.12.


@node タプルのアノテーション,クラスオブジェクトの型,ジェネリクス,typing --- Support for type hints
@anchor{library/typing annotating-tuples}@anchor{26d0}@anchor{library/typing id4}@anchor{44d8}
@subsubsection タプルのアノテーション


For most containers in Python, the typing system assumes that all elements in
the container will be of the same type. For example:

@example
from collections.abc import Mapping

# Type checker will infer that all elements in `@w{`}x`@w{`} are meant to be ints
x: list[int] = []

# Type checker error: `@w{`}list`@w{`} only accepts a single type argument:
y: list[int, str] = [1, 'foo']

# Type checker will infer that all keys in `@w{`}z`@w{`} are meant to be strings,
# and that all values in `@w{`}z`@w{`} are meant to be either strings or ints
z: Mapping[str, str | int] = @{@}
@end example

@ref{24d,,list} は引数に1つの型のみ受け入れるので、型チェッカーは上記の @code{y} への代入でエラーを出力します。同様に、@ref{ac7,,Mapping} は引数に2つの型のみ受け入れます。1つ目はキーの型を示し、2つ目は値の型を示します。

しかし、他の多くのPythonのコンテナとは異なり、タプルがすべて同じ型ではない要素を持つことは、慣用的なPythonコードでは一般的です。このため、タプルはPythonの型システムの中でも特殊です。@ref{614,,tuple} は任意の数の引数を受け入れます

@example
# OK: `@w{`}x`@w{`} is assigned to a tuple of length 1 where the sole element is an int
x: tuple[int] = (5,)

# OK: `@w{`}y`@w{`} is assigned to a tuple of length 2;
# element 1 is an int, element 2 is a str
y: tuple[int, str] = (5, "foo")

# Error: the type annotation indicates a tuple of length 1,
# but `@w{`}z`@w{`} has been assigned to a tuple of length 3
z: tuple[int] = (1, 2, 3)
@end example

@geindex ...;ellipsisリテラル

To denote a tuple which could be of `any' length, and in which all elements are
of the same type @code{T}, use the literal ellipsis @code{...}: @code{tuple[T, ...]}.
To denote an empty tuple, use
@code{tuple[()]}. Using plain @code{tuple} as an annotation is equivalent to using
@code{tuple[Any, ...]}:

@example
x: tuple[int, ...] = (1, 2)
# These reassignments are OK: `@w{`}tuple[int, ...]`@w{`} indicates x can be of any length
x = (1, 2, 3)
x = ()
# This reassignment is an error: all elements in `@w{`}x`@w{`} must be ints
x = ("foo", "bar")

# `@w{`}y`@w{`} can only ever be assigned to an empty tuple
y: tuple[()] = ()

z: tuple = ("foo", "bar")
# These reassignments are OK: plain `@w{`}tuple`@w{`} is equivalent to `@w{`}tuple[Any, ...]`@w{`}
z = (1, 2, 3)
z = ()
@end example

@node クラスオブジェクトの型,Annotating generators and coroutines,タプルのアノテーション,typing --- Support for type hints
@anchor{library/typing the-type-of-class-objects}@anchor{44d9}@anchor{library/typing type-of-class-objects}@anchor{44da}
@subsubsection クラスオブジェクトの型


A variable annotated with @code{C} may accept a value of type @code{C}. In
contrast, a variable annotated with @code{type[C]} (or deprecated
@ref{44db,,typing.Type[C]}) may accept values that are classes
themselves -- specifically, it will accept the `class object' of @code{C}. For
example:

@example
a = 3         # Has type `@w{`}int`@w{`}
b = int       # Has type `@w{`}type[int]`@w{`}
c = type(a)   # Also has type `@w{`}type[int]`@w{`}
@end example

Note that @code{type[C]} is covariant:

@example
class User: ...
class ProUser(User): ...
class TeamUser(User): ...

def make_new_user(user_class: type[User]) -> User:
    # ...
    return user_class()

make_new_user(User)      # OK
make_new_user(ProUser)   # Also OK: `@w{`}type[ProUser]`@w{`} is a subtype of `@w{`}type[User]`@w{`}
make_new_user(TeamUser)  # Still fine
make_new_user(User())    # Error: expected `@w{`}type[User]`@w{`} but got `@w{`}User`@w{`}
make_new_user(int)       # Error: `@w{`}type[int]`@w{`} is not a subtype of `@w{`}type[User]`@w{`}
@end example

The only legal parameters for @ref{f44,,type} are classes, @ref{8bb,,Any},
@ref{23c9,,type variables}, and unions of any of these types.
For example:

@example
def new_non_team_user(user_class: type[BasicUser | ProUser]): ...

new_non_team_user(BasicUser)  # OK
new_non_team_user(ProUser)    # OK
new_non_team_user(TeamUser)   # Error: `@w{`}type[TeamUser]`@w{`} is not a subtype
                              # of `@w{`}type[BasicUser | ProUser]`@w{`}
new_non_team_user(User)       # Also an error
@end example

@code{type[Any]} is equivalent to @ref{f44,,type}, which is the root of Python's
@ref{23be,,metaclass hierarchy}.

@node Annotating generators and coroutines,ユーザー定義のジェネリック型,クラスオブジェクトの型,typing --- Support for type hints
@anchor{library/typing annotating-generators-and-coroutines}@anchor{299c}@anchor{library/typing id5}@anchor{44dc}
@subsubsection Annotating generators and coroutines


A generator can be annotated using the generic type
@ref{fdb,,Generator[YieldType@comma{} SendType@comma{} ReturnType]}.
For example:

@example
def echo_round() -> Generator[int, float, str]:
    sent = yield 0
    while sent >= 0:
        sent = yield round(sent)
    return 'Done'
@end example

Note that unlike many other generic classes in the standard library,
the @code{SendType} of @ref{fdb,,Generator} behaves
contravariantly, not covariantly or invariantly.

The @code{SendType} and @code{ReturnType} parameters default to @code{None}:

@example
def infinite_stream(start: int) -> Generator[int]:
    while True:
        yield start
        start += 1
@end example

It is also possible to set these types explicitly:

@example
def infinite_stream(start: int) -> Generator[int, None, None]:
    while True:
        yield start
        start += 1
@end example

Simple generators that only ever yield values can also be annotated
as having a return type of either
@ref{26ae,,Iterable[YieldType]}
or @ref{26af,,Iterator[YieldType]}:

@example
def infinite_stream(start: int) -> Iterator[int]:
    while True:
        yield start
        start += 1
@end example

Async generators are handled in a similar fashion, but don't
expect a @code{ReturnType} type argument
(@ref{e87,,AsyncGenerator[YieldType@comma{} SendType]}).
The @code{SendType} argument defaults to @code{None}, so the following definitions
are equivalent:

@example
async def infinite_stream(start: int) -> AsyncGenerator[int]:
    while True:
        yield start
        start = await increment(start)

async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
    while True:
        yield start
        start = await increment(start)
@end example

As in the synchronous case,
@ref{fdf,,AsyncIterable[YieldType]}
and @ref{fde,,AsyncIterator[YieldType]} are
available as well:

@example
async def infinite_stream(start: int) -> AsyncIterator[int]:
    while True:
        yield start
        start = await increment(start)
@end example

Coroutines can be annotated using
@ref{fdd,,Coroutine[YieldType@comma{} SendType@comma{} ReturnType]}.
Generic arguments correspond to those of @ref{fdb,,Generator},
for example:

@example
from collections.abc import Coroutine
c: Coroutine[list[str], str, int]  # Some coroutine defined elsewhere
x = c.send('hi')                   # Inferred type of 'x' is list[str]
async def bar() -> None:
    y = await c                    # Inferred type of 'y' is int
@end example

@node ユーザー定義のジェネリック型,Any 型,Annotating generators and coroutines,typing --- Support for type hints
@anchor{library/typing user-defined-generic-types}@anchor{44dd}@anchor{library/typing user-defined-generics}@anchor{6f6}
@subsubsection ユーザー定義のジェネリック型


ユーザー定義のクラスを、ジェネリッククラスとして定義できます。

@example
from logging import Logger

class LoggedVar[T]:
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value

    def set(self, new: T) -> None:
        self.log('Set ' + repr(self.value))
        self.value = new

    def get(self) -> T:
        self.log('Get ' + repr(self.value))
        return self.value

    def log(self, message: str) -> None:
        self.logger.info('%s: %s', self.name, message)
@end example

This syntax indicates that the class @code{LoggedVar} is parameterised around a
single @ref{44de,,type variable} @code{T} . This also makes @code{T} valid as
a type within the class body.

Generic classes implicitly inherit from @ref{17b6,,Generic}. For compatibility
with Python 3.11 and lower, it is also possible to inherit explicitly from
@ref{17b6,,Generic} to indicate a generic class:

@example
from typing import TypeVar, Generic

T = TypeVar('T')

class LoggedVar(Generic[T]):
    ...
@end example

Generic classes have @ref{943,,__class_getitem__()} methods, meaning they
can be parameterised at runtime (e.g. @code{LoggedVar[int]} below):

@example
from collections.abc import Iterable

def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
    for var in vars:
        var.set(0)
@end example

A generic type can have any number of type variables. All varieties of
@ref{486,,TypeVar} are permissible as parameters for a generic type:

@example
from typing import TypeVar, Generic, Sequence

class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:
    ...

OldT = TypeVar('OldT', contravariant=True)
OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)
OldS = TypeVar('OldS', int, str)

class OldWeirdTrio(Generic[OldT, OldB, OldS]):
    ...
@end example

@ref{17b6,,Generic} の引数のそれぞれの型変数は別のものでなければなりません。このため次のクラス定義は無効です:

@example
from typing import TypeVar, Generic
...

class Pair[M, M]:  # SyntaxError
    ...

T = TypeVar('T')

class Pair(Generic[T, T]):   # INVALID
    ...
@end example

Generic classes can also inherit from other classes:

@example
from collections.abc import Sized

class LinkedList[T](Sized):
    ...
@end example

When inheriting from generic classes, some type parameters could be fixed:

@example
from collections.abc import Mapping

class MyDict[T](Mapping[str, T]):
    ...
@end example

この場合では @code{MyDict} は仮引数 @code{T} を 1 つとります。

Using a generic class without specifying type parameters assumes
@ref{8bb,,Any} for each position. In the following example, @code{MyIterable} is
not generic but implicitly inherits from @code{Iterable[Any]}:

@example
from collections.abc import Iterable

class MyIterable(Iterable): # Same as Iterable[Any]
    ...
@end example

User-defined generic type aliases are also supported. Examples:

@example
from collections.abc import Iterable

type Response[S] = Iterable[S] | int

# Return type here is same as Iterable[str] | int
def response(query: str) -> Response[str]:
    ...

type Vec[T] = Iterable[tuple[T, T]]

def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
    return sum(x*y for x, y in v)
@end example

For backward compatibility, generic type aliases can also be created
through a simple assignment:

@example
from collections.abc import Iterable
from typing import TypeVar

S = TypeVar("S")
Response = Iterable[S] | int
@end example


バージョン 3.7 で変更: @ref{17b6,,Generic} にあった独自のメタクラスは無くなりました。



バージョン 3.12 で変更: Syntactic support for generics and type aliases is new in version 3.12.
Previously, generic classes had to explicitly inherit from @ref{17b6,,Generic}
or contain a type variable in one of their bases.


User-defined generics for parameter expressions are also supported via parameter
specification variables in the form @code{[**P]}.  The behavior is consistent
with type variables' described above as parameter specification variables are
treated by the @code{typing} module as a specialized type variable.  The one exception
to this is that a list of types can be used to substitute a @ref{487,,ParamSpec}:

@example
>>> class Z[T, **P]: ...  # T is a TypeVar; P is a ParamSpec
...
>>> Z[int, [dict, float]]
__main__.Z[int, [dict, float]]
@end example

Classes generic over a @ref{487,,ParamSpec} can also be created using explicit
inheritance from @ref{17b6,,Generic}. In this case, @code{**} is not used:

@example
from typing import ParamSpec, Generic

P = ParamSpec('P')

class Z(Generic[P]):
    ...
@end example

Another difference between @ref{486,,TypeVar} and @ref{487,,ParamSpec} is that a
generic with only one parameter specification variable will accept
parameter lists in the forms @code{X[[Type1, Type2, ...]]} and also
@code{X[Type1, Type2, ...]} for aesthetic reasons.  Internally, the latter is converted
to the former, so the following are equivalent:

@example
>>> class X[**P]: ...
...
>>> X[int, str]
__main__.X[[int, str]]
>>> X[[int, str]]
__main__.X[[int, str]]
@end example

Note that generics with @ref{487,,ParamSpec} may not have correct
@code{__parameters__} after substitution in some cases because they
are intended primarily for static type checking.


バージョン 3.10 で変更: @ref{17b6,,Generic} can now be parameterized over parameter expressions.
See @ref{487,,ParamSpec} and 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} for more details.


A user-defined generic class can have ABCs as base classes without a metaclass
conflict. Generic metaclasses are not supported. The outcome of parameterizing
generics is cached, and most types in the @code{typing} module are @ref{824,,hashable} and
comparable for equality.

@node Any 型,名前的部分型 vs 構造的部分型,ユーザー定義のジェネリック型,typing --- Support for type hints
@anchor{library/typing the-any-type}@anchor{44df}
@subsubsection @code{Any} 型


@ref{8bb,,Any} は特別な種類の型です。静的型検査器はすべての型を @ref{8bb,,Any} と互換として扱い、 @ref{8bb,,Any} をすべての型と互換として扱います。

これは、 @ref{8bb,,Any} 型の値では、任意の演算やメソッドの呼び出しが行えることを意味します:

@example
from typing import Any

a: Any = None
a = []          # OK
a = 2           # OK

s: str = '@w{'}
s = a           # OK

def foo(item: Any) -> int:
    # Passes type checking; 'item' could be any type,
    # and that type might have a 'bar' method
    item.bar()
    ...
@end example

@ref{8bb,,Any} 型の値をより詳細な型に代入する時に型検査が行われないことに注意してください。例えば、静的型検査器は @code{a} を @code{s} に代入する時、@code{s} が @ref{169,,str} 型として宣言されていて実行時に @ref{19b,,int} の値を受け取るとしても、エラーを報告しません。

さらに、返り値や引数の型のないすべての関数は暗黙的に @ref{8bb,,Any} を使用します。

@example
def legacy_parser(text):
    ...
    return data

# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
    ...
    return data
@end example

この挙動により、動的型付けと静的型付けが混在したコードを書かなければならない時に @ref{8bb,,Any} を `非常口' として使用することができます。

@ref{8bb,,Any} の挙動と @ref{c7e,,object} の挙動を対比しましょう。 @ref{8bb,,Any} と同様に、すべての型は @ref{c7e,,object} のサブタイプです。しかしながら、 @ref{8bb,,Any} と異なり、逆は成り立ちません: @ref{c7e,,object} はすべての他の型のサブタイプでは `ありません'。

これは、ある値の型が @ref{c7e,,object} のとき、型検査器はこれについてのほとんどすべての操作を拒否し、これをより特殊化された変数に代入する (または返り値として利用する) ことは型エラーになることを意味します。例えば:

@example
def hash_a(item: object) -> int:
    # Fails type checking; an object does not have a 'magic' method.
    item.magic()
    ...

def hash_b(item: Any) -> int:
    # Passes type checking
    item.magic()
    ...

# Passes type checking, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")

# Passes type checking, since Any is compatible with all types
hash_b(42)
hash_b("foo")
@end example

@ref{c7e,,object} は、ある値が型安全な方法で任意の型として使えることを示すために使用します。 @ref{8bb,,Any} はある値が動的に型付けられることを示すために使用します。

@node 名前的部分型 vs 構造的部分型,モジュールの内容<3>,Any 型,typing --- Support for type hints
@anchor{library/typing nominal-vs-structural-subtyping}@anchor{44e0}
@subsubsection 名前的部分型 vs 構造的部分型


初めは 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} は Python の静的型システムを `名前的部分型' を使って定義していました。
名前的部分型とは、クラス @code{B} が期待されているところにクラス @code{A} が許容されるのは @code{A} が @code{B} のサブクラスの場合かつその場合に限る、ということです。

前出の必要条件は、@ref{26ae,,Iterable} などの抽象基底クラスにも当て嵌まります。
この型付け手法の問題は、この手法をサポートするためにクラスに明確な型付けを行う必要があることで、これは pythonic ではなく、普段行っている 慣用的な Python コードへの動的型付けとは似ていません。
例えば、次のコードは 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} に従ったものです

@example
from collections.abc import Sized, Iterable, Iterator

class Bucket(Sized, Iterable[int]):
    ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[int]: ...
@end example

@geindex Python Enhancement Proposals; PEP 544
PEP 544@footnote{https://peps.python.org/pep-0544/} solves this problem by allowing users to write
the above code without explicit base classes in the class definition,
allowing @code{Bucket} to be implicitly considered a subtype of both @code{Sized}
and @code{Iterable[int]} by static type checkers. This is known as
`structural subtyping' (or static duck-typing):

@example
from collections.abc import Iterator, Iterable

class Bucket:  # Note: no base classes
    ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[int]: ...

def collect(items: Iterable[int]) -> int: ...
result = collect(Bucket())  # Passes type check
@end example

さらに、特別なクラス @ref{56b,,Protocol} のサブクラスを作ることで、新しい独自のプロトコルを作って構造的部分型というものを満喫できます。

@node モジュールの内容<3>,メジャーな機能の非推奨時系列,名前的部分型 vs 構造的部分型,typing --- Support for type hints
@anchor{library/typing module-contents}@anchor{44e1}
@subsubsection モジュールの内容


The @code{typing} module defines the following classes, functions and decorators.

@menu
* 特殊型付けプリミティブ:: 
* プロトコル: プロトコル<4>. 
* ABCs and Protocols for working with I/O:: 
* Functions and decorators:: 
* Introspection helpers:: 
* 定数: 定数<10>. 
* 非推奨のエイリアス:: 

@end menu

@node 特殊型付けプリミティブ,プロトコル<4>,,モジュールの内容<3>
@anchor{library/typing special-typing-primitives}@anchor{44e2}
@subsubsection 特殊型付けプリミティブ


@menu
* 特殊型:: 
* 特殊形式:: 
* Building generic types and type aliases:: 
* Other special directives:: 

@end menu

@node 特殊型,特殊形式,,特殊型付けプリミティブ
@anchor{library/typing special-types}@anchor{44e3}
@subsubsection 特殊型


These can be used as types in annotations. They do not support subscription
using @code{[]}.

@geindex Any (typing モジュール)
@anchor{library/typing typing Any}@anchor{8bb}
@deffn {データ} typing.Any

制約のない型であることを示す特別な型です。


@itemize *

@item 
任意の型は @ref{8bb,,Any} と互換です。

@item 
@ref{8bb,,Any} は任意の型と互換です。
@end itemize


バージョン 3.11 で変更: @ref{8bb,,Any} can now be used as a base class. This can be useful for
avoiding type checker errors with classes that can duck type anywhere or
are highly dynamic.

@end deffn

@geindex AnyStr (typing モジュール)
@anchor{library/typing typing AnyStr}@anchor{5ac}
@deffn {データ} typing.AnyStr

A @ref{44e4,,constrained type variable}.

Definition:

@example
AnyStr = TypeVar('AnyStr', str, bytes)
@end example

@code{AnyStr} is meant to be used for functions that may accept @ref{169,,str} or
@ref{192,,bytes} arguments but cannot allow the two to mix.

例えば:

@example
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

concat("foo", "bar")    # OK, output has type 'str'
concat(b"foo", b"bar")  # OK, output has type 'bytes'
concat("foo", b"bar")   # Error, cannot mix str and bytes
@end example

Note that, despite its name, @code{AnyStr} has nothing to do with the
@ref{8bb,,Any} type, nor does it mean "any string". In particular, @code{AnyStr}
and @code{str | bytes} are different from each other and have different use
cases:

@example
# Invalid use of AnyStr:
# The type variable is used only once in the function signature,
# so cannot be "solved" by the type checker
def greet_bad(cond: bool) -> AnyStr:
    return "hi there!" if cond else b"greetings!"

# The better way of annotating this function:
def greet_proper(cond: bool) -> str | bytes:
    return "hi there!" if cond else b"greetings!"
@end example


Deprecated since version 3.13, will be removed in version 3.18: Deprecated in favor of the new @ref{5ad,,type parameter syntax}.
Use @code{class A[T: (str, bytes)]: ...} instead of importing @code{AnyStr}. See
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} for more details.

In Python 3.16, @code{AnyStr} will be removed from @code{typing.__all__}, and
deprecation warnings will be emitted at runtime when it is accessed or
imported from @code{typing}. @code{AnyStr} will be removed from @code{typing}
in Python 3.18.

@end deffn

@geindex LiteralString (typing モジュール)
@anchor{library/typing typing LiteralString}@anchor{7e6}
@deffn {データ} typing.LiteralString

Special type that includes only literal strings.

Any string
literal is compatible with @code{LiteralString}, as is another
@code{LiteralString}. However, an object typed as just @code{str} is not.
A string created by composing @code{LiteralString}-typed objects
is also acceptable as a @code{LiteralString}.

例:

@example
def run_query(sql: LiteralString) -> None:
    ...

def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
    run_query("SELECT * FROM students")  # OK
    run_query(literal_string)  # OK
    run_query("SELECT * FROM " + literal_string)  # OK
    run_query(arbitrary_string)  # type checker error
    run_query(  # type checker error
        f"SELECT * FROM students WHERE name = @{arbitrary_string@}"
    )
@end example

@code{LiteralString} is useful for sensitive APIs where arbitrary user-generated
strings could generate problems. For example, the two cases above
that generate type checker errors could be vulnerable to an SQL
injection attack.

より詳しくは 
@geindex Python Enhancement Proposals; PEP 675
PEP 675@footnote{https://peps.python.org/pep-0675/} を参照してください。


Added in version 3.11.

@end deffn

@geindex Never (typing モジュール)
@geindex NoReturn (typing モジュール)
@anchor{library/typing typing Never}@anchor{8b7}
@deffn {データ} typing.Never
@anchor{library/typing typing NoReturn}@anchor{44e5}
@deffnx {データ} typing.NoReturn

@code{Never} and @code{NoReturn} represent the
bottom type@footnote{https://en.wikipedia.org/wiki/Bottom_type},
a type that has no members.

They can be used to indicate that a function never returns,
such as @ref{277,,sys.exit()}:

@example
from typing import Never  # or NoReturn

def stop() -> Never:
    raise RuntimeError('no way')
@end example

Or to define a function that should never be
called, as there are no valid arguments, such as
@ref{8b6,,assert_never()}:

@example
from typing import Never  # or NoReturn

def never_call_me(arg: Never) -> None:
    pass

def int_or_str(arg: int | str) -> None:
    never_call_me(arg)  # type checker error
    match arg:
        case int():
            print("It's an int")
        case str():
            print("It's a str")
        case _:
            never_call_me(arg)  # OK, arg is of type Never (or NoReturn)
@end example

@code{Never} and @code{NoReturn} have the same meaning in the type system
and static type checkers treat both equivalently.


Added in version 3.6.2: Added @ref{44e5,,NoReturn}.



Added in version 3.11: Added @ref{8b7,,Never}.

@end deffn

@geindex Self (typing モジュール)
@anchor{library/typing typing Self}@anchor{7e3}
@deffn {データ} typing.Self

Special type to represent the current enclosed class.

例えば:

@example
from typing import Self, reveal_type

class Foo:
    def return_self(self) -> Self:
        ...
        return self

class SubclassOfFoo(Foo): pass

reveal_type(Foo().return_self())  # Revealed type is "Foo"
reveal_type(SubclassOfFoo().return_self())  # Revealed type is "SubclassOfFoo"
@end example

This annotation is semantically equivalent to the following,
albeit in a more succinct fashion:

@example
from typing import TypeVar

Self = TypeVar("Self", bound="Foo")

class Foo:
    def return_self(self: Self) -> Self:
        ...
        return self
@end example

In general, if something returns @code{self}, as in the above examples, you
should use @code{Self} as the return annotation. If @code{Foo.return_self} was
annotated as returning @code{"Foo"}, then the type checker would infer the
object returned from @code{SubclassOfFoo.return_self} as being of type @code{Foo}
rather than @code{SubclassOfFoo}.

Other common use cases include:


@itemize -

@item 
@ref{48e,,classmethod}s that are used as alternative constructors and return instances
of the @code{cls} parameter.

@item 
Annotating an @ref{7e4,,__enter__()} method which returns self.
@end itemize

You should not use @code{Self} as the return annotation if the method is not
guaranteed to return an instance of a subclass when the class is
subclassed:

@example
class Eggs:
    # Self would be an incorrect return annotation here,
    # as the object returned is always an instance of Eggs,
    # even in subclasses
    def returns_eggs(self) -> "Eggs":
        return Eggs()
@end example

より詳しくは 
@geindex Python Enhancement Proposals; PEP 673
PEP 673@footnote{https://peps.python.org/pep-0673/} を参照してください。


Added in version 3.11.

@end deffn

@geindex TypeAlias (typing モジュール)
@anchor{library/typing typing TypeAlias}@anchor{9cc}
@deffn {データ} typing.TypeAlias

Special annotation for explicitly declaring a @ref{683,,type alias}.

例えば:

@example
from typing import TypeAlias

Factors: TypeAlias = list[int]
@end example

@code{TypeAlias} is particularly useful on older Python versions for annotating
aliases that make use of forward references, as it can be hard for type
checkers to distinguish these from normal variable assignments:

@example
from typing import Generic, TypeAlias, TypeVar

T = TypeVar("T")

# "Box" does not exist yet,
# so we have to use quotes for the forward reference on Python <3.12.
# Using `@w{`}TypeAlias`@w{`} tells the type checker that this is a type alias declaration,
# not a variable assignment to a string.
BoxOfStrings: TypeAlias = "Box[str]"

class Box(Generic[T]):
    @@classmethod
    def make_box_of_strings(cls) -> BoxOfStrings: ...
@end example

より詳しくは、 
@geindex Python Enhancement Proposals; PEP 613
PEP 613@footnote{https://peps.python.org/pep-0613/} をご覧ください。


Added in version 3.10.



バージョン 3.12 で非推奨: @ref{9cc,,TypeAlias} is deprecated in favor of the @ref{66d,,type} statement,
which creates instances of @ref{2ae,,TypeAliasType}
and which natively supports forward references.
Note that while @ref{9cc,,TypeAlias} and @ref{2ae,,TypeAliasType} serve
similar purposes and have similar names, they are distinct and the
latter is not the type of the former.
Removal of @ref{9cc,,TypeAlias} is not currently planned, but users
are encouraged to migrate to @ref{66d,,type} statements.

@end deffn

@node 特殊形式,Building generic types and type aliases,特殊型,特殊型付けプリミティブ
@anchor{library/typing special-forms}@anchor{44e6}
@subsubsection 特殊形式


これらはアノテーションの型として使用できます。これらは全て @code{[]} を使用した添字表記をサポートしますが、それぞれ固有の構文があります。

@geindex Union (typing のクラス)
@anchor{library/typing typing Union}@anchor{2a8}
@deffn {クラス} typing.Union

ユニオン型; @code{Union[X, Y]} は @code{X | Y} と等価で X または Y を表します。

To define a union, use e.g. @code{Union[int, str]} or the shorthand @code{int | str}. Using that shorthand is recommended. Details:


@itemize *

@item 
引数は型でなければならず、少なくとも一つ必要です。

@item 
ユニオン型のユニオン型は平滑化されます。例えば:

@example
Union[Union[int, str], float] == Union[int, str, float]
@end example

However, this does not apply to unions referenced through a type
alias, to avoid forcing evaluation of the underlying @ref{2ae,,TypeAliasType}:

@example
type A = Union[int, str]
Union[A, float] != Union[int, str, float]
@end example

@item 
引数が一つのユニオン型は消えます。例えば:

@example
Union[int] == int  # The constructor actually returns int
@end example

@item 
冗長な実引数は飛ばされます。例えば:

@example
Union[int, str, int] == Union[int, str] == int | str
@end example

@item 
ユニオン型を比較するとき引数の順序は無視されます。例えば:

@example
Union[int, str] == Union[str, int]
@end example

@item 
@code{Union} のサブクラスを作成したり、インスタンスを作成することは出来ません。

@item 
@code{Union[X][Y]} と書くことは出来ません。
@end itemize


バージョン 3.7 で変更: 明示的に書かれているサブクラスを、実行時に直和型から取り除かなくなりました。



バージョン 3.10 で変更: ユニオン型は @code{X | Y} のように書けるようになりました。 @ref{9c5,,union型の表現} を参照ください。



バージョン 3.14 で変更: @ref{2a7,,types.UnionType} is now an alias for @ref{2a8,,Union}, and both
@code{Union[int, str]} and @code{int | str} create instances of the same class.
To check whether an object is a @code{Union} at runtime, use
@code{isinstance(obj, Union)}. For compatibility with earlier versions of
Python, use
@code{get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType}.

@end deffn

@geindex Optional (typing モジュール)
@anchor{library/typing typing Optional}@anchor{8c2}
@deffn {データ} typing.Optional

@code{Optional[X]} は @code{X | None} (や @code{Union[X, None]}) と同等です。

これがデフォルト値を持つオプション引数とは同じ概念ではないということに注意してください。
デフォルト値を持つオプション引数はオプション引数であるために、型アノテーションに @code{Optional} 修飾子は必要ありません。
例えば次のようになります:

@example
def foo(arg: int = 0) -> None:
    ...
@end example

それとは逆に、 @code{None} という値が許されていることが明示されている場合は、引数がオプションであろうとなかろうと、 @code{Optional} を使うのが好ましいです。
例えば次のようになります:

@example
def foo(arg: Optional[int] = None) -> None:
    ...
@end example


バージョン 3.10 で変更: Optionalは @code{X | None} のように書けるようになりました。 ref:@cite{union型の表現 <types-union>} を参照ください。

@end deffn

@geindex Concatenate (typing モジュール)
@anchor{library/typing typing Concatenate}@anchor{9c7}
@deffn {データ} typing.Concatenate

Special form for annotating higher-order functions.

@geindex ...;ellipsisリテラル

@code{Concatenate} can be used in conjunction with @ref{26cf,,Callable} and
@ref{487,,ParamSpec} to annotate a higher-order callable which adds, removes,
or transforms parameters of another
callable.  Usage is in the form
@code{Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]}. @code{Concatenate}
is currently only valid when used as the first argument to a @ref{26cf,,Callable}.
The last parameter to @code{Concatenate} must be a @ref{487,,ParamSpec} or
ellipsis (@code{...}).

For example, to annotate a decorator @code{with_lock} which provides a
@ref{19f4,,threading.Lock} to the decorated function,  @code{Concatenate} can be
used to indicate that @code{with_lock} expects a callable which takes in a
@code{Lock} as the first argument, and returns a callable with a different type
signature.  In this case, the @ref{487,,ParamSpec} indicates that the returned
callable's parameter types are dependent on the parameter types of the
callable being passed in:

@example
from collections.abc import Callable
from threading import Lock
from typing import Concatenate

# Use this lock to ensure that only one thread is executing a function
# at any time.
my_lock = Lock()

def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
    '@w{'}'A type-safe decorator which provides a lock.'@w{'}'
    def inner(*args: P.args, **kwargs: P.kwargs) -> R:
        # Provide the lock as the first argument.
        return f(my_lock, *args, **kwargs)
    return inner

@@with_lock
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
    '@w{'}'Add a list of numbers together in a thread-safe manner.'@w{'}'
    with lock:
        return sum(numbers)

# We don't need to pass in the lock ourselves thanks to the decorator.
sum_threadsafe([1.1, 2.2, 3.3])
@end example


Added in version 3.10.



@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} -- Parameter Specification Variables (the PEP which introduced
@code{ParamSpec} and @code{Concatenate})

@item 
@ref{487,,ParamSpec}

@item 
@ref{26cf,,呼び出し可能オブジェクトのアノテーション}
@end itemize

@end deffn

@geindex Literal (typing モジュール)
@anchor{library/typing typing Literal}@anchor{a55}
@deffn {データ} typing.Literal

Special typing form to define "literal types".

@code{Literal} can be used to indicate to type checkers that the
annotated object has a value equivalent to one of the
provided literals.

例えば:

@example
def validate_simple(data: Any) -> Literal[True]:  # always returns True
    ...

type Mode = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: Mode) -> str:
    ...

open_helper('/some/path', 'r')      # Passes type check
open_helper('/other/path', 'typo')  # Error in type checker
@end example

@code{Literal[...]} はサブクラスにはできません。
実行時に、任意の値が @code{Literal[...]} の型引数として使えますが、型チェッカーが制約を課すことがあります。
リテラル型についてより詳しいことは 
@geindex Python Enhancement Proposals; PEP 586
PEP 586@footnote{https://peps.python.org/pep-0586/} を参照してください。

Additional details:


@itemize *

@item 
The arguments must be literal values and there must be at least one.

@item 
Nested @code{Literal} types are flattened, e.g.:

@example
assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3]
@end example

However, this does not apply to @code{Literal} types referenced through a type
alias, to avoid forcing evaluation of the underlying @ref{2ae,,TypeAliasType}:

@example
type A = Literal[1, 2]
assert Literal[A, 3] != Literal[1, 2, 3]
@end example

@item 
冗長な実引数は飛ばされます。例えば:

@example
assert Literal[1, 2, 1] == Literal[1, 2]
@end example

@item 
When comparing literals, the argument order is ignored, e.g.:

@example
assert Literal[1, 2] == Literal[2, 1]
@end example

@item 
You cannot subclass or instantiate a @code{Literal}.

@item 
You cannot write @code{Literal[X][Y]}.
@end itemize


Added in version 3.8.



バージョン 3.9.1 で変更: @code{Literal} ではパラメータの重複を解消するようになりました。@code{Literal} オブジェクトの等値比較は順序に依存しないようになりました。@code{Literal} オブジェクトは、等値比較する際に、パラメータのうち 1 つでも @ref{824,,hashable} でない場合は @ref{198,,TypeError} を送出するようになりました。

@end deffn

@geindex ClassVar (typing モジュール)
@anchor{library/typing typing ClassVar}@anchor{56d}
@deffn {データ} typing.ClassVar

クラス変数であることを示す特別な型構築子です。

@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} で導入された通り、 ClassVar でラップされた変数アノテーションによって、ある属性はクラス変数として使うつもりであり、そのクラスのインスタンスから設定すべきではないということを示せます。使い方は次のようになります:

@example
class Starship:
    stats: ClassVar[dict[str, int]] = @{@} # class variable
    damage: int = 10                     # instance variable
@end example

@ref{56d,,ClassVar} は型のみを受け入れ、それ以外は受け付けられません。

@ref{56d,,ClassVar} はクラスそのものではなく、@ref{2ad,,isinstance()} や @ref{9c4,,issubclass()} で使うべきではありません。
@ref{56d,,ClassVar} は Python の実行時の挙動を変えませんが、サードパーティの型検査器で使えます。
例えば、型チェッカーは次のコードをエラーとするかもしれません:

@example
enterprise_d = Starship(3000)
enterprise_d.stats = @{@} # Error, setting class variable on instance
Starship.stats = @{@}     # This is OK
@end example


Added in version 3.5.3.



バージョン 3.13 で変更: @ref{56d,,ClassVar} can now be nested in @ref{56e,,Final} and vice versa.

@end deffn

@geindex Final (typing モジュール)
@anchor{library/typing typing Final}@anchor{56e}
@deffn {データ} typing.Final

Special typing construct to indicate final names to type checkers.

Final names cannot be reassigned in any scope. Final names declared in class
scopes cannot be overridden in subclasses.

例えば:

@example
MAX_SIZE: Final = 9000
MAX_SIZE += 1  # Error reported by type checker

class Connection:
    TIMEOUT: Final[int] = 10

class FastConnector(Connection):
    TIMEOUT = 1  # Error reported by type checker
@end example

この機能は実行時には検査されません。詳細については 
@geindex Python Enhancement Proposals; PEP 591
PEP 591@footnote{https://peps.python.org/pep-0591/} を参照してください。


Added in version 3.8.



バージョン 3.13 で変更: @ref{56e,,Final} can now be nested in @ref{56d,,ClassVar} and vice versa.

@end deffn

@geindex Required (typing モジュール)
@anchor{library/typing typing Required}@anchor{7e0}
@deffn {データ} typing.Required

Special typing construct to mark a @ref{332,,TypedDict} key as required.

This is mainly useful for @code{total=False} TypedDicts. See @ref{332,,TypedDict}
and 
@geindex Python Enhancement Proposals; PEP 655
PEP 655@footnote{https://peps.python.org/pep-0655/} for more details.


Added in version 3.11.

@end deffn

@geindex NotRequired (typing モジュール)
@anchor{library/typing typing NotRequired}@anchor{7e1}
@deffn {データ} typing.NotRequired

Special typing construct to mark a @ref{332,,TypedDict} key as potentially
missing.

より詳しくは、 @ref{332,,TypedDict} と 
@geindex Python Enhancement Proposals; PEP 655
PEP 655@footnote{https://peps.python.org/pep-0655/} を参照してください。


Added in version 3.11.

@end deffn

@geindex ReadOnly (typing モジュール)
@anchor{library/typing typing ReadOnly}@anchor{48a}
@deffn {データ} typing.ReadOnly

A special typing construct to mark an item of a @ref{332,,TypedDict} as read-only.

例えば:

@example
class Movie(TypedDict):
   title: ReadOnly[str]
   year: int

def mutate_movie(m: Movie) -> None:
   m["year"] = 1999  # allowed
   m["title"] = "The Matrix"  # typechecker error
@end example

There is no runtime checking for this property.

See @ref{332,,TypedDict} and 
@geindex Python Enhancement Proposals; PEP 705
PEP 705@footnote{https://peps.python.org/pep-0705/} for more details.


Added in version 3.13.

@end deffn

@geindex Annotated (typing モジュール)
@anchor{library/typing typing Annotated}@anchor{b37}
@deffn {データ} typing.Annotated

Special typing form to add context-specific metadata to an annotation.

Add metadata @code{x} to a given type @code{T} by using the annotation
@code{Annotated[T, x]}. Metadata added using @code{Annotated} can be used by
static analysis tools or at runtime. At runtime, the metadata is stored
in a @code{__metadata__} attribute.

If a library or tool encounters an annotation @code{Annotated[T, x]} and has
no special logic for the metadata, it should ignore the metadata and simply
treat the annotation as @code{T}. As such, @code{Annotated} can be useful for code
that wants to use annotations for purposes outside Python's static typing
system.

Using @code{Annotated[T, x]} as an annotation still allows for static
typechecking of @code{T}, as type checkers will simply ignore the metadata @code{x}.
In this way, @code{Annotated} differs from the
@ref{8c3,,@@no_type_check} decorator, which can also be used for
adding annotations outside the scope of the typing system, but
completely disables typechecking for a function or class.

The responsibility of how to interpret the metadata
lies with the tool or library encountering an
@code{Annotated} annotation. A tool or library encountering an @code{Annotated} type
can scan through the metadata elements to determine if they are of interest
(e.g., using @ref{2ad,,isinstance()}).


@deffn {Describe} Annotated[<type>, <metadata>]
@end deffn

Here is an example of how you might use @code{Annotated} to add metadata to
type annotations if you were doing range analysis:

@example
@@dataclass
class ValueRange:
    lo: int
    hi: int

T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]
@end example

The first argument to @code{Annotated} must be a valid type. Multiple metadata
elements can be supplied as @code{Annotated} supports variadic arguments. The
order of the metadata elements is preserved and matters for equality checks:

@example
@@dataclass
class ctype:
     kind: str

a1 = Annotated[int, ValueRange(3, 10), ctype("char")]
a2 = Annotated[int, ctype("char"), ValueRange(3, 10)]

assert a1 != a2  # Order matters
@end example

It is up to the tool consuming the annotations to decide whether the
client is allowed to add multiple metadata elements to one annotation and how to
merge those annotations.

Nested @code{Annotated} types are flattened. The order of the metadata elements
starts with the innermost annotation:

@example
assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
    int, ValueRange(3, 10), ctype("char")
]
@end example

However, this does not apply to @code{Annotated} types referenced through a type
alias, to avoid forcing evaluation of the underlying @ref{2ae,,TypeAliasType}:

@example
type From3To10[T] = Annotated[T, ValueRange(3, 10)]
assert Annotated[From3To10[int], ctype("char")] != Annotated[
   int, ValueRange(3, 10), ctype("char")
]
@end example

Duplicated metadata elements are not removed:

@example
assert Annotated[int, ValueRange(3, 10)] != Annotated[
    int, ValueRange(3, 10), ValueRange(3, 10)
]
@end example

@code{Annotated} can be used with nested and generic aliases:

@quotation

@example
@@dataclass
class MaxLen:
    value: int

type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]

# When used in a type annotation, a type checker will treat "V" the same as
# `@w{`}Annotated[list[tuple[int, int]], MaxLen(10)]`@w{`}:
type V = Vec[int]
@end example
@end quotation

@code{Annotated} cannot be used with an unpacked @ref{488,,TypeVarTuple}:

@example
type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., Ann1]  # NOT valid
@end example

where @code{T1}, @code{T2}, ... are @ref{486,,TypeVars}. This is invalid as
only one type should be passed to Annotated.

By default, @ref{8c0,,get_type_hints()} strips the metadata from annotations.
Pass @code{include_extras=True} to have the metadata preserved:

@quotation

@example
>>> from typing import Annotated, get_type_hints
>>> def func(x: Annotated[int, "metadata"]) -> None: pass
...
>>> get_type_hints(func)
@{'x': <class 'int'>, 'return': <class 'NoneType'>@}
>>> get_type_hints(func, include_extras=True)
@{'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>@}
@end example
@end quotation

At runtime, the metadata associated with an @code{Annotated} type can be
retrieved via the @code{__metadata__} attribute:

@quotation

@example
>>> from typing import Annotated
>>> X = Annotated[int, "very", "important", "metadata"]
>>> X
typing.Annotated[int, 'very', 'important', 'metadata']
>>> X.__metadata__
('very', 'important', 'metadata')
@end example
@end quotation

If you want to retrieve the original type wrapped by @code{Annotated}, use the
@code{__origin__} attribute:

@quotation

@example
>>> from typing import Annotated, get_origin
>>> Password = Annotated[str, "secret"]
>>> Password.__origin__
<class 'str'>
@end example
@end quotation

Note that using @ref{2ab,,get_origin()} will return @code{Annotated} itself:

@quotation

@example
>>> get_origin(Password)
typing.Annotated
@end example
@end quotation


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 593

@item PEP 593@footnote{https://peps.python.org/pep-0593/} - Flexible function and variable annotations

The PEP introducing @code{Annotated} to the standard library.
@end table



Added in version 3.9.

@end deffn

@geindex TypeIs (typing モジュール)
@anchor{library/typing typing TypeIs}@anchor{48b}
@deffn {データ} typing.TypeIs

Special typing construct for marking user-defined type predicate functions.

@code{TypeIs} can be used to annotate the return type of a user-defined
type predicate function.  @code{TypeIs} only accepts a single type argument.
At runtime, functions marked this way should return a boolean and take at
least one positional argument.

@code{TypeIs} aims to benefit `type narrowing' -- a technique used by static
type checkers to determine a more precise type of an expression within a
program's code flow.  Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code.  The
conditional expression here is sometimes referred to as a "type predicate":

@example
def is_str(val: str | float):
    # "isinstance" type predicate
    if isinstance(val, str):
        # Type of `@w{`}val`@w{`} is narrowed to `@w{`}str`@w{`}
        ...
    else:
        # Else, type of `@w{`}val`@w{`} is narrowed to `@w{`}float`@w{`}.
        ...
@end example

Sometimes it would be convenient to use a user-defined boolean function
as a type predicate.  Such a function should use @code{TypeIs[...]} or
@ref{48c,,TypeGuard} as its return type to alert static type checkers to
this intention.  @code{TypeIs} usually has more intuitive behavior than
@code{TypeGuard}, but it cannot be used when the input and output types
are incompatible (e.g., @code{list[object]} to @code{list[int]}) or when the
function does not return @code{True} for all instances of the narrowed type.

Using  @code{-> TypeIs[NarrowedType]} tells the static type checker that for a given
function:


@enumerate 

@item 
The return value is a boolean.

@item 
If the return value is @code{True}, the type of its argument
is the intersection of the argument's original type and @code{NarrowedType}.

@item 
If the return value is @code{False}, the type of its argument
is narrowed to exclude @code{NarrowedType}.
@end enumerate

例えば:

@example
from typing import assert_type, final, TypeIs

class Parent: pass
class Child(Parent): pass
@@final
class Unrelated: pass

def is_parent(val: object) -> TypeIs[Parent]:
    return isinstance(val, Parent)

def run(arg: Child | Unrelated):
    if is_parent(arg):
        # Type of `@w{`}arg`@w{`} is narrowed to the intersection
        # of `@w{`}Parent`@w{`} and `@w{`}Child`@w{`}, which is equivalent to
        # `@w{`}Child`@w{`}.
        assert_type(arg, Child)
    else:
        # Type of `@w{`}arg`@w{`} is narrowed to exclude `@w{`}Parent`@w{`},
        # so only `@w{`}Unrelated`@w{`} is left.
        assert_type(arg, Unrelated)
@end example

The type inside @code{TypeIs} must be consistent with the type of the
function's argument; if it is not, static type checkers will raise
an error.  An incorrectly written @code{TypeIs} function can lead to
unsound behavior in the type system; it is the user's responsibility
to write such functions in a type-safe manner.

If a @code{TypeIs} function is a class or instance method, then the type in
@code{TypeIs} maps to the type of the second parameter (after @code{cls} or
@code{self}).

In short, the form @code{def foo(arg: TypeA) -> TypeIs[TypeB]: ...},
means that if @code{foo(arg)} returns @code{True}, then @code{arg} is an instance
of @code{TypeB}, and if it returns @code{False}, it is not an instance of @code{TypeB}.

@code{TypeIs} also works with type variables.  For more information, see
@geindex Python Enhancement Proposals; PEP 742
PEP 742@footnote{https://peps.python.org/pep-0742/} (Narrowing types with @code{TypeIs}).


Added in version 3.13.

@end deffn

@geindex TypeGuard (typing モジュール)
@anchor{library/typing typing TypeGuard}@anchor{48c}
@deffn {データ} typing.TypeGuard

Special typing construct for marking user-defined type predicate functions.

Type predicate functions are user-defined functions that return whether their
argument is an instance of a particular type.
@code{TypeGuard} works similarly to @ref{48b,,TypeIs}, but has subtly different
effects on type checking behavior (see below).

Using  @code{-> TypeGuard} tells the static type checker that for a given
function:


@enumerate 

@item 
The return value is a boolean.

@item 
If the return value is @code{True}, the type of its argument
is the type inside @code{TypeGuard}.
@end enumerate

@code{TypeGuard} also works with type variables.  See 
@geindex Python Enhancement Proposals; PEP 647
PEP 647@footnote{https://peps.python.org/pep-0647/} for more details.

例えば:

@example
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
    '@w{'}'Determines whether all objects in the list are strings'@w{'}'
    return all(isinstance(x, str) for x in val)

def func1(val: list[object]):
    if is_str_list(val):
        # Type of `@w{`}val`@w{`} is narrowed to `@w{`}list[str]`@w{`}.
        print(" ".join(val))
    else:
        # Type of `@w{`}val`@w{`} remains as `@w{`}list[object]`@w{`}.
        print("Not a list of strings!")
@end example

@code{TypeIs} and @code{TypeGuard} differ in the following ways:


@itemize *

@item 
@code{TypeIs} requires the narrowed type to be a subtype of the input type, while
@code{TypeGuard} does not.  The main reason is to allow for things like
narrowing @code{list[object]} to @code{list[str]} even though the latter
is not a subtype of the former, since @code{list} is invariant.

@item 
When a @code{TypeGuard} function returns @code{True}, type checkers narrow the type of the
variable to exactly the @code{TypeGuard} type. When a @code{TypeIs} function returns @code{True},
type checkers can infer a more precise type combining the previously known type of the
variable with the @code{TypeIs} type. (Technically, this is known as an intersection type.)

@item 
When a @code{TypeGuard} function returns @code{False}, type checkers cannot narrow the type of
the variable at all. When a @code{TypeIs} function returns @code{False}, type checkers can narrow
the type of the variable to exclude the @code{TypeIs} type.
@end itemize


Added in version 3.10.

@end deffn

@geindex Unpack (typing モジュール)
@anchor{library/typing typing Unpack}@anchor{19a6}
@deffn {データ} typing.Unpack

Typing operator to conceptually mark an object as having been unpacked.

For example, using the unpack operator @code{*} on a
@ref{44e7,,type variable tuple} is equivalent to using @code{Unpack}
to mark the type variable tuple as having been unpacked:

@example
Ts = TypeVarTuple('Ts')
tup: tuple[*Ts]
# Effectively does:
tup: tuple[Unpack[Ts]]
@end example

In fact, @code{Unpack} can be used interchangeably with @code{*} in the context
of @ref{488,,typing.TypeVarTuple} and
@ref{614,,builtins.tuple} types. You might see @code{Unpack} being used
explicitly in older versions of Python, where @code{*} couldn't be used in
certain places:

@example
# In older versions of Python, TypeVarTuple and Unpack
# are located in the `typing_extensions` backports package.
from typing_extensions import TypeVarTuple, Unpack

Ts = TypeVarTuple('Ts')
tup: tuple[*Ts]         # Syntax error on Python <= 3.10!
tup: tuple[Unpack[Ts]]  # Semantically equivalent, and backwards-compatible
@end example

@code{Unpack} can also be used along with @ref{332,,typing.TypedDict} for typing
@code{**kwargs} in a function signature:

@example
from typing import TypedDict, Unpack

class Movie(TypedDict):
    name: str
    year: int

# This function expects two keyword arguments - `name` of type `str`
# and `year` of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
@end example

See 
@geindex Python Enhancement Proposals; PEP 692
PEP 692@footnote{https://peps.python.org/pep-0692/} for more details on using @code{Unpack} for @code{**kwargs} typing.


Added in version 3.11.

@end deffn

@node Building generic types and type aliases,Other special directives,特殊形式,特殊型付けプリミティブ
@anchor{library/typing building-generic-types-and-type-aliases}@anchor{44e8}
@subsubsection Building generic types and type aliases


The following classes should not be used directly as annotations.
Their intended purpose is to be building blocks
for creating generic types and type aliases.

These objects can be created through special syntax
(@ref{5ad,,type parameter lists} and the @ref{66d,,type} statement).
For compatibility with Python 3.11 and earlier, they can also be created
without the dedicated syntax, as documented below.

@geindex Generic (typing のクラス)
@anchor{library/typing typing Generic}@anchor{17b6}
@deffn {クラス} typing.Generic

ジェネリック型のための抽象基底クラスです。

A generic type is typically declared by adding a list of type parameters
after the class name:

@example
class Mapping[KT, VT]:
    def __getitem__(self, key: KT) -> VT:
        ...
        # Etc.
@end example

Such a class implicitly inherits from @code{Generic}.
The runtime semantics of this syntax are discussed in the
@ref{2377,,Language Reference}.

このクラスは次のように使用することが出来ます:

@example
def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:
    try:
        return mapping[key]
    except KeyError:
        return default
@end example

Here the brackets after the function name indicate a
@ref{682,,generic function}.

For backwards compatibility, generic classes can also be
declared by explicitly inheriting from
@code{Generic}. In this case, the type parameters must be declared
separately:

@example
KT = TypeVar('KT')
VT = TypeVar('VT')

class Mapping(Generic[KT, VT]):
    def __getitem__(self, key: KT) -> VT:
        ...
        # Etc.
@end example
@end deffn

@geindex TypeVar (typing のクラス)
@anchor{library/typing typevar}@anchor{44de}@anchor{library/typing typing TypeVar}@anchor{486}
@deffn {クラス} typing.TypeVar (name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)

型変数です。

The preferred way to construct a type variable is via the dedicated syntax
for @ref{682,,generic functions},
@ref{2377,,generic classes}, and
@ref{684,,generic type aliases}:

@example
class Sequence[T]:  # T is a TypeVar
    ...
@end example

This syntax can also be used to create bounded and constrained type
variables:

@example
class StrSequence[S: str]:  # S is a TypeVar with a `str` upper bound;
    ...                     # we can say that S is "bounded by `str`"


class StrOrBytesSequence[A: (str, bytes)]:  # A is a TypeVar constrained to str or bytes
    ...
@end example

However, if desired, reusable type variables can also be constructed manually, like so:

@example
T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes
@end example

Type variables exist primarily for the benefit of static type
checkers.  They serve as the parameters for generic types as well
as for generic function and type alias definitions.
See @ref{17b6,,Generic} for more
information on generic types.  Generic functions work as follows:

@example
def repeat[T](x: T, n: int) -> Sequence[T]:
    """Return a list containing n references to x."""
    return [x]*n


def print_capitalized[S: str](x: S) -> S:
    """Print x capitalized, and return x."""
    print(x.capitalize())
    return x


def concatenate[A: (str, bytes)](x: A, y: A) -> A:
    """Add two strings or bytes objects together."""
    return x + y
@end example

Note that type variables can be `bounded', `constrained', or neither, but
cannot be both bounded `and' constrained.

The variance of type variables is inferred by type checkers when they are created
through the @ref{5ad,,type parameter syntax} or when
@code{infer_variance=True} is passed.
Manually created type variables may be explicitly marked covariant or contravariant by passing
@code{covariant=True} or @code{contravariant=True}.
By default, manually created type variables are invariant.
See 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} and 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/} for more details.

Bounded type variables and constrained type variables have different
semantics in several important ways. Using a `bounded' type variable means
that the @code{TypeVar} will be solved using the most specific type possible:

@example
x = print_capitalized('a string')
reveal_type(x)  # revealed type is str

class StringSubclass(str):
    pass

y = print_capitalized(StringSubclass('another string'))
reveal_type(y)  # revealed type is StringSubclass

z = print_capitalized(45)  # error: int is not a subtype of str
@end example

The upper bound of a type variable can be a concrete type, abstract type
(ABC or Protocol), or even a union of types:

@example
# Can be anything with an __abs__ method
def print_abs[T: SupportsAbs](arg: T) -> None:
    print("Absolute value:", abs(arg))

U = TypeVar('U', bound=str|bytes)  # Can be any subtype of the union str|bytes
V = TypeVar('V', bound=SupportsAbs)  # Can be anything with an __abs__ method
@end example
@anchor{library/typing typing-constrained-typevar}@anchor{44e4}
Using a `constrained' type variable, however, means that the @code{TypeVar}
can only ever be solved as being exactly one of the constraints given:

@example
a = concatenate('one', 'two')
reveal_type(a)  # revealed type is str

b = concatenate(StringSubclass('one'), StringSubclass('two'))
reveal_type(b)  # revealed type is str, despite StringSubclass being passed in

c = concatenate('one', b'two')  # error: type variable 'A' can be either str or bytes in a function call, but not both
@end example

At runtime, @code{isinstance(x, T)} will raise @ref{198,,TypeError}.

@geindex __name__ (typing.TypeVar の属性)
@anchor{library/typing typing TypeVar __name__}@anchor{44e9}
@deffn {の属性} __name__

The name of the type variable.
@end deffn

@geindex __covariant__ (typing.TypeVar の属性)
@anchor{library/typing typing TypeVar __covariant__}@anchor{44ea}
@deffn {の属性} __covariant__

Whether the type var has been explicitly marked as covariant.
@end deffn

@geindex __contravariant__ (typing.TypeVar の属性)
@anchor{library/typing typing TypeVar __contravariant__}@anchor{44eb}
@deffn {の属性} __contravariant__

Whether the type var has been explicitly marked as contravariant.
@end deffn

@geindex __infer_variance__ (typing.TypeVar の属性)
@anchor{library/typing typing TypeVar __infer_variance__}@anchor{44ec}
@deffn {の属性} __infer_variance__

Whether the type variable's variance should be inferred by type checkers.


Added in version 3.12.

@end deffn

@geindex __bound__ (typing.TypeVar の属性)
@anchor{library/typing typing TypeVar __bound__}@anchor{44ed}
@deffn {の属性} __bound__

The upper bound of the type variable, if any.


バージョン 3.12 で変更: For type variables created through @ref{5ad,,type parameter syntax},
the bound is evaluated only when the attribute is accessed, not when
the type variable is created (see @ref{685,,Lazy evaluation}).

@end deffn

@geindex evaluate_bound() (typing.TypeVar のメソッド)
@anchor{library/typing typing TypeVar evaluate_bound}@anchor{44ee}
@deffn {メソッド} evaluate_bound ()

An @ref{44ef,,evaluate function} corresponding to the @ref{44ed,,__bound__} attribute.
When called directly, this method supports only the @ref{15e,,VALUE}
format, which is equivalent to accessing the @ref{44ed,,__bound__} attribute directly,
but the method object can be passed to @ref{44f0,,annotationlib.call_evaluate_function()}
to evaluate the value in a different format.


Added in version 3.14.

@end deffn

@geindex __constraints__ (typing.TypeVar の属性)
@anchor{library/typing typing TypeVar __constraints__}@anchor{44f1}
@deffn {の属性} __constraints__

A tuple containing the constraints of the type variable, if any.


バージョン 3.12 で変更: For type variables created through @ref{5ad,,type parameter syntax},
the constraints are evaluated only when the attribute is accessed, not when
the type variable is created (see @ref{685,,Lazy evaluation}).

@end deffn

@geindex evaluate_constraints() (typing.TypeVar のメソッド)
@anchor{library/typing typing TypeVar evaluate_constraints}@anchor{44f2}
@deffn {メソッド} evaluate_constraints ()

An @ref{44ef,,evaluate function} corresponding to the @ref{44f1,,__constraints__} attribute.
When called directly, this method supports only the @ref{15e,,VALUE}
format, which is equivalent to accessing the @ref{44f1,,__constraints__} attribute directly,
but the method object can be passed to @ref{44f0,,annotationlib.call_evaluate_function()}
to evaluate the value in a different format.


Added in version 3.14.

@end deffn

@geindex __default__ (typing.TypeVar の属性)
@anchor{library/typing typing TypeVar __default__}@anchor{44f3}
@deffn {の属性} __default__

The default value of the type variable, or @ref{569,,typing.NoDefault} if it
has no default.


Added in version 3.13.

@end deffn

@geindex evaluate_default() (typing.TypeVar のメソッド)
@anchor{library/typing typing TypeVar evaluate_default}@anchor{44f4}
@deffn {メソッド} evaluate_default ()

An @ref{44ef,,evaluate function} corresponding to the @ref{44f3,,__default__} attribute.
When called directly, this method supports only the @ref{15e,,VALUE}
format, which is equivalent to accessing the @ref{44f3,,__default__} attribute directly,
but the method object can be passed to @ref{44f0,,annotationlib.call_evaluate_function()}
to evaluate the value in a different format.


Added in version 3.14.

@end deffn

@geindex has_default() (typing.TypeVar のメソッド)
@anchor{library/typing typing TypeVar has_default}@anchor{44f5}
@deffn {メソッド} has_default ()

Return whether or not the type variable has a default value. This is equivalent
to checking whether @ref{44f3,,__default__} is not the @ref{569,,typing.NoDefault}
singleton, except that it does not force evaluation of the
@ref{685,,lazily evaluated} default value.


Added in version 3.13.

@end deffn


バージョン 3.12 で変更: Type variables can now be declared using the
@ref{5ad,,type parameter} syntax introduced by 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}.
The @code{infer_variance} parameter was added.



バージョン 3.13 で変更: Support for default values was added.

@end deffn

@geindex TypeVarTuple (typing のクラス)
@anchor{library/typing typevartuple}@anchor{44e7}@anchor{library/typing typing TypeVarTuple}@anchor{488}
@deffn {クラス} typing.TypeVarTuple (name, *, default=typing.NoDefault)

Type variable tuple. A specialized form of @ref{44de,,type variable}
that enables `variadic' generics.

Type variable tuples can be declared in @ref{5ad,,type parameter lists}
using a single asterisk (@code{*}) before the name:

@example
def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
    return (*tup[1:], tup[0])
@end example

Or by explicitly invoking the @code{TypeVarTuple} constructor:

@example
T = TypeVar("T")
Ts = TypeVarTuple("Ts")

def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
    return (*tup[1:], tup[0])
@end example

A normal type variable enables parameterization with a single type. A type
variable tuple, in contrast, allows parameterization with an
`arbitrary' number of types by acting like an `arbitrary' number of type
variables wrapped in a tuple. For example:

@example
# T is bound to int, Ts is bound to ()
# Return value is (1,), which has type tuple[int]
move_first_element_to_last(tup=(1,))

# T is bound to int, Ts is bound to (str,)
# Return value is ('spam', 1), which has type tuple[str, int]
move_first_element_to_last(tup=(1, 'spam'))

# T is bound to int, Ts is bound to (str, float)
# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
move_first_element_to_last(tup=(1, 'spam', 3.0))

# This fails to type check (and fails at runtime)
# because tuple[()] is not compatible with tuple[T, *Ts]
# (at least one element is required)
move_first_element_to_last(tup=())
@end example

Note the use of the unpacking operator @code{*} in @code{tuple[T, *Ts]}.
Conceptually, you can think of @code{Ts} as a tuple of type variables
@code{(T1, T2, ...)}. @code{tuple[T, *Ts]} would then become
@code{tuple[T, *(T1, T2, ...)]}, which is equivalent to
@code{tuple[T, T1, T2, ...]}. (Note that in older versions of Python, you might
see this written using @ref{19a6,,Unpack} instead, as
@code{Unpack[Ts]}.)

Type variable tuples must `always' be unpacked. This helps distinguish type
variable tuples from normal type variables:

@example
x: Ts          # Not valid
x: tuple[Ts]   # Not valid
x: tuple[*Ts]  # The correct way to do it
@end example

Type variable tuples can be used in the same contexts as normal type
variables. For example, in class definitions, arguments, and return types:

@example
class Array[*Shape]:
    def __getitem__(self, key: tuple[*Shape]) -> float: ...
    def __abs__(self) -> "Array[*Shape]": ...
    def get_shape(self) -> tuple[*Shape]: ...
@end example

Type variable tuples can be happily combined with normal type variables:

@example
class Array[DType, *Shape]:  # This is fine
    pass

class Array2[*Shape, DType]:  # This would also be fine
    pass

class Height: ...
class Width: ...

float_array_1d: Array[float, Height] = Array()     # Totally fine
int_array_2d: Array[int, Height, Width] = Array()  # Yup, fine too
@end example

However, note that at most one type variable tuple may appear in a single
list of type arguments or type parameters:

@example
x: tuple[*Ts, *Ts]            # Not valid
class Array[*Shape, *Shape]:  # Not valid
    pass
@end example

Finally, an unpacked type variable tuple can be used as the type annotation
of @code{*args}:

@example
def call_soon[*Ts](
    callback: Callable[[*Ts], None],
    *args: *Ts
) -> None:
    ...
    callback(*args)
@end example

In contrast to non-unpacked annotations of @code{*args} - e.g. @code{*args: int},
which would specify that `all' arguments are @code{int} - @code{*args: *Ts}
enables reference to the types of the `individual' arguments in @code{*args}.
Here, this allows us to ensure the types of the @code{*args} passed
to @code{call_soon} match the types of the (positional) arguments of
@code{callback}.

See 
@geindex Python Enhancement Proposals; PEP 646
PEP 646@footnote{https://peps.python.org/pep-0646/} for more details on type variable tuples.

@geindex __name__ (typing.TypeVarTuple の属性)
@anchor{library/typing typing TypeVarTuple __name__}@anchor{44f6}
@deffn {の属性} __name__

The name of the type variable tuple.
@end deffn

@geindex __default__ (typing.TypeVarTuple の属性)
@anchor{library/typing typing TypeVarTuple __default__}@anchor{44f7}
@deffn {の属性} __default__

The default value of the type variable tuple, or @ref{569,,typing.NoDefault} if it
has no default.


Added in version 3.13.

@end deffn

@geindex evaluate_default() (typing.TypeVarTuple のメソッド)
@anchor{library/typing typing TypeVarTuple evaluate_default}@anchor{44f8}
@deffn {メソッド} evaluate_default ()

An @ref{44ef,,evaluate function} corresponding to the @ref{44f7,,__default__} attribute.
When called directly, this method supports only the @ref{15e,,VALUE}
format, which is equivalent to accessing the @ref{44f7,,__default__} attribute directly,
but the method object can be passed to @ref{44f0,,annotationlib.call_evaluate_function()}
to evaluate the value in a different format.


Added in version 3.14.

@end deffn

@geindex has_default() (typing.TypeVarTuple のメソッド)
@anchor{library/typing typing TypeVarTuple has_default}@anchor{44f9}
@deffn {メソッド} has_default ()

Return whether or not the type variable tuple has a default value. This is equivalent
to checking whether @ref{44f7,,__default__} is not the @ref{569,,typing.NoDefault}
singleton, except that it does not force evaluation of the
@ref{685,,lazily evaluated} default value.


Added in version 3.13.

@end deffn


Added in version 3.11.



バージョン 3.12 で変更: Type variable tuples can now be declared using the
@ref{5ad,,type parameter} syntax introduced by 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}.



バージョン 3.13 で変更: Support for default values was added.

@end deffn

@geindex ParamSpec (typing のクラス)
@anchor{library/typing typing ParamSpec}@anchor{487}
@deffn {クラス} typing.ParamSpec (name, *, bound=None, covariant=False, contravariant=False, default=typing.NoDefault)

Parameter specification variable.  A specialized version of
@ref{44de,,type variables}.

In @ref{5ad,,type parameter lists}, parameter specifications
can be declared with two asterisks (@code{**}):

@example
type IntFunc[**P] = Callable[P, int]
@end example

For compatibility with Python 3.11 and earlier, @code{ParamSpec} objects
can also be created as follows:

@example
P = ParamSpec('P')
@end example

Parameter specification variables exist primarily for the benefit of static
type checkers.  They are used to forward the parameter types of one
callable to another callable -- a pattern commonly found in higher order
functions and decorators.  They are only valid when used in @code{Concatenate},
or as the first argument to @code{Callable}, or as parameters for user-defined
Generics.  See @ref{17b6,,Generic} for more information on generic types.

For example, to add basic logging to a function, one can create a decorator
@code{add_logging} to log function calls.  The parameter specification variable
tells the type checker that the callable passed into the decorator and the
new callable returned by it have inter-dependent type parameters:

@example
from collections.abc import Callable
import logging

def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:
    '@w{'}'A type-safe decorator to add logging to a function.'@w{'}'
    def inner(*args: P.args, **kwargs: P.kwargs) -> T:
        logging.info(f'@{f.__name__@} was called')
        return f(*args, **kwargs)
    return inner

@@add_logging
def add_two(x: float, y: float) -> float:
    '@w{'}'Add two numbers together.'@w{'}'
    return x + y
@end example

Without @code{ParamSpec}, the simplest way to annotate this previously was to
use a @ref{486,,TypeVar} with upper bound @code{Callable[..., Any]}.  However this
causes two problems:


@enumerate 

@item 
The type checker can't type check the @code{inner} function because
@code{*args} and @code{**kwargs} have to be typed @ref{8bb,,Any}.

@item 
@ref{44fa,,cast()} may be required in the body of the @code{add_logging}
decorator when returning the @code{inner} function, or the static type
checker must be told to ignore the @code{return inner}.
@end enumerate

@geindex args (typing.ParamSpec の属性)
@anchor{library/typing typing ParamSpec args}@anchor{44fb}
@deffn {の属性} args
@end deffn

@geindex kwargs (typing.ParamSpec の属性)
@anchor{library/typing typing ParamSpec kwargs}@anchor{44fc}
@deffn {の属性} kwargs

Since @code{ParamSpec} captures both positional and keyword parameters,
@code{P.args} and @code{P.kwargs} can be used to split a @code{ParamSpec} into its
components.  @code{P.args} represents the tuple of positional parameters in a
given call and should only be used to annotate @code{*args}.  @code{P.kwargs}
represents the mapping of keyword parameters to their values in a given call,
and should be only be used to annotate @code{**kwargs}.  Both
attributes require the annotated parameter to be in scope. At runtime,
@code{P.args} and @code{P.kwargs} are instances respectively of
@ref{9c9,,ParamSpecArgs} and @ref{9ca,,ParamSpecKwargs}.
@end deffn

@geindex __name__ (typing.ParamSpec の属性)
@anchor{library/typing typing ParamSpec __name__}@anchor{44fd}
@deffn {の属性} __name__

The name of the parameter specification.
@end deffn

@geindex __default__ (typing.ParamSpec の属性)
@anchor{library/typing typing ParamSpec __default__}@anchor{44fe}
@deffn {の属性} __default__

The default value of the parameter specification, or @ref{569,,typing.NoDefault} if it
has no default.


Added in version 3.13.

@end deffn

@geindex evaluate_default() (typing.ParamSpec のメソッド)
@anchor{library/typing typing ParamSpec evaluate_default}@anchor{44ff}
@deffn {メソッド} evaluate_default ()

An @ref{44ef,,evaluate function} corresponding to the @ref{44fe,,__default__} attribute.
When called directly, this method supports only the @ref{15e,,VALUE}
format, which is equivalent to accessing the @ref{44fe,,__default__} attribute directly,
but the method object can be passed to @ref{44f0,,annotationlib.call_evaluate_function()}
to evaluate the value in a different format.


Added in version 3.14.

@end deffn

@geindex has_default() (typing.ParamSpec のメソッド)
@anchor{library/typing typing ParamSpec has_default}@anchor{4500}
@deffn {メソッド} has_default ()

Return whether or not the parameter specification has a default value. This is equivalent
to checking whether @ref{44fe,,__default__} is not the @ref{569,,typing.NoDefault}
singleton, except that it does not force evaluation of the
@ref{685,,lazily evaluated} default value.


Added in version 3.13.

@end deffn

Parameter specification variables created with @code{covariant=True} or
@code{contravariant=True} can be used to declare covariant or contravariant
generic types.  The @code{bound} argument is also accepted, similar to
@ref{486,,TypeVar}.  However the actual semantics of these keywords are yet to
be decided.


Added in version 3.10.



バージョン 3.12 で変更: Parameter specifications can now be declared using the
@ref{5ad,,type parameter} syntax introduced by 
@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}.



バージョン 3.13 で変更: Support for default values was added.


@cartouche
@quotation 注釈 
Only parameter specification variables defined in global scope can
be pickled.
@end quotation
@end cartouche


@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} -- Parameter Specification Variables (the PEP which introduced
@code{ParamSpec} and @code{Concatenate})

@item 
@ref{9c7,,Concatenate}

@item 
@ref{26cf,,呼び出し可能オブジェクトのアノテーション}
@end itemize

@end deffn

@geindex ParamSpecArgs (typing モジュール)
@geindex ParamSpecKwargs (typing モジュール)
@anchor{library/typing typing ParamSpecArgs}@anchor{9c9}
@deffn {データ} typing.ParamSpecArgs
@anchor{library/typing typing ParamSpecKwargs}@anchor{9ca}
@deffnx {データ} typing.ParamSpecKwargs

Arguments and keyword arguments attributes of a @ref{487,,ParamSpec}. The
@code{P.args} attribute of a @code{ParamSpec} is an instance of @code{ParamSpecArgs},
and @code{P.kwargs} is an instance of @code{ParamSpecKwargs}. They are intended
for runtime introspection and have no special meaning to static type checkers.

Calling @ref{2ab,,get_origin()} on either of these objects will return the
original @code{ParamSpec}:

@example
>>> from typing import ParamSpec, get_origin
>>> P = ParamSpec("P")
>>> get_origin(P.args) is P
True
>>> get_origin(P.kwargs) is P
True
@end example


Added in version 3.10.

@end deffn

@geindex TypeAliasType (typing のクラス)
@anchor{library/typing typing TypeAliasType}@anchor{2ae}
@deffn {クラス} typing.TypeAliasType (name, value, *, type_params=())

The type of type aliases created through the @ref{66d,,type} statement.

例:

@example
>>> type Alias = int
>>> type(Alias)
<class 'typing.TypeAliasType'>
@end example


Added in version 3.12.


@geindex __name__ (typing.TypeAliasType の属性)
@anchor{library/typing typing TypeAliasType __name__}@anchor{4501}
@deffn {の属性} __name__

The name of the type alias:

@example
>>> type Alias = int
>>> Alias.__name__
'Alias'
@end example
@end deffn

@geindex __module__ (typing.TypeAliasType の属性)
@anchor{library/typing typing TypeAliasType __module__}@anchor{4502}
@deffn {の属性} __module__

The name of the module in which the type alias was defined:

@example
>>> type Alias = int
>>> Alias.__module__
'__main__'
@end example
@end deffn

@geindex __type_params__ (typing.TypeAliasType の属性)
@anchor{library/typing typing TypeAliasType __type_params__}@anchor{4503}
@deffn {の属性} __type_params__

The type parameters of the type alias, or an empty tuple if the alias is
not generic:

@example
>>> type ListOrSet[T] = list[T] | set[T]
>>> ListOrSet.__type_params__
(T,)
>>> type NotGeneric = int
>>> NotGeneric.__type_params__
()
@end example
@end deffn

@geindex __value__ (typing.TypeAliasType の属性)
@anchor{library/typing typing TypeAliasType __value__}@anchor{4504}
@deffn {の属性} __value__

The type alias's value. This is @ref{685,,lazily evaluated},
so names used in the definition of the alias are not resolved until the
@code{__value__} attribute is accessed:

@example
>>> type Mutually = Recursive
>>> type Recursive = Mutually
>>> Mutually
Mutually
>>> Recursive
Recursive
>>> Mutually.__value__
Recursive
>>> Recursive.__value__
Mutually
@end example
@end deffn

@geindex evaluate_value() (typing.TypeAliasType のメソッド)
@anchor{library/typing typing TypeAliasType evaluate_value}@anchor{4505}
@deffn {メソッド} evaluate_value ()

An @ref{44ef,,evaluate function} corresponding to the @ref{4504,,__value__} attribute.
When called directly, this method supports only the @ref{15e,,VALUE}
format, which is equivalent to accessing the @ref{4504,,__value__} attribute directly,
but the method object can be passed to @ref{44f0,,annotationlib.call_evaluate_function()}
to evaluate the value in a different format:

@example
>>> type Alias = undefined
>>> Alias.__value__
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> from annotationlib import Format, call_evaluate_function
>>> Alias.evaluate_value(Format.VALUE)
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF)
ForwardRef('undefined')
@end example


Added in version 3.14.

@end deffn

@subsubheading 展開


Type aliases support star unpacking using the @code{*Alias} syntax.
This is equivalent to using @code{Unpack[Alias]} directly:

@example
>>> type Alias = tuple[int, str]
>>> type Unpacked = tuple[bool, *Alias]
>>> Unpacked.__value__
tuple[bool, typing.Unpack[Alias]]
@end example


Added in version 3.14.

@end deffn

@node Other special directives,,Building generic types and type aliases,特殊型付けプリミティブ
@anchor{library/typing other-special-directives}@anchor{4506}
@subsubsection Other special directives


These functions and classes should not be used directly as annotations.
Their intended purpose is to be building blocks for creating and declaring
types.

@geindex NamedTuple (typing のクラス)
@anchor{library/typing typing NamedTuple}@anchor{331}
@deffn {クラス} typing.NamedTuple

@ref{4e0,,collections.namedtuple()} の型付き版です。

使い方:

@example
class Employee(NamedTuple):
    name: str
    id: int
@end example

これは次と等価です:

@example
Employee = collections.namedtuple('Employee', ['name', 'id'])
@end example

フィールドにデフォルト値を与えるにはクラス本体で代入してください:

@example
class Employee(NamedTuple):
    name: str
    id: int = 3

employee = Employee('Guido')
assert employee.id == 3
@end example

デフォルト値のあるフィールドはデフォルト値のないフィールドの後でなければなりません。

最終的に出来上がるクラスには、フィールド名をフィールド型へ対応付ける辞書を提供する @code{__annotations__} 属性が追加されています。
(フィールド名は @code{_fields} 属性に、デフォルト値は @code{_field_defaults} 属性に格納されていて、両方とも @ref{4e0,,namedtuple()} API の一部分です。)

@code{NamedTuple} のサブクラスは docstring やメソッドも持てます:

@example
class Employee(NamedTuple):
    """Represents an employee."""
    name: str
    id: int = 3

    def __repr__(self) -> str:
        return f'<Employee @{self.name@}, id=@{self.id@}>'
@end example

@code{NamedTuple} subclasses can be generic:

@example
class Group[T](NamedTuple):
    key: T
    group: list[T]
@end example

後方互換な使用法:

@example
# For creating a generic NamedTuple on Python 3.11
T = TypeVar("T")

class Group(NamedTuple, Generic[T]):
    key: T
    group: list[T]

# A functional syntax is also supported
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
@end example


バージョン 3.6 で変更: 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} 変数アノテーションのシンタックスが追加されました。



バージョン 3.6.1 で変更: デフォルト値、メソッド、ドキュメンテーション文字列への対応が追加されました。



バージョン 3.8 で変更: @code{_field_types} 属性および @code{__annotations__} 属性は @code{OrderedDict} インスタンスではなく普通の辞書になりました。



バージョン 3.9 で変更: @code{_field_types} 属性は削除されました。代わりに同じ情報を持つより標準的な @code{__annotations__} 属性を使ってください。



バージョン 3.9 で変更: @code{NamedTuple} is now a function rather than a class.
It can still be used as a class base, as described above.



バージョン 3.11 で変更: Added support for generic namedtuples.



バージョン 3.14 で変更: Using @ref{1a6,,super()} (and the @code{__class__} @ref{1893,,closure variable}) in methods of @code{NamedTuple} subclasses
is unsupported and causes a @ref{198,,TypeError}.



Deprecated since version 3.13, will be removed in version 3.15: The undocumented keyword argument syntax for creating NamedTuple classes
(@code{NT = NamedTuple("NT", x=int)}) is deprecated, and will be disallowed
in 3.15. Use the class-based syntax or the functional syntax instead.



Deprecated since version 3.13, will be removed in version 3.15: When using the functional syntax to create a NamedTuple class, failing to
pass a value to the 'fields' parameter (@code{NT = NamedTuple("NT")}) is
deprecated. Passing @code{None} to the 'fields' parameter
(@code{NT = NamedTuple("NT", None)}) is also deprecated. Both will be
disallowed in Python 3.15. To create a NamedTuple class with 0 fields,
use @code{class NT(NamedTuple): pass} or @code{NT = NamedTuple("NT", [])}.

@end deffn

@geindex NewType (typing のクラス)
@anchor{library/typing typing NewType}@anchor{ef1}
@deffn {クラス} typing.NewType (name, tp)

Helper class to create low-overhead @ref{44d3,,distinct types}.

A @code{NewType} is considered a distinct type by a typechecker. At runtime,
however, calling a @code{NewType} returns its argument unchanged.

使い方:

@example
UserId = NewType('UserId', int)  # Declare the NewType "UserId"
first_user = UserId(1)  # "UserId" returns the argument unchanged at runtime
@end example

@geindex __module__ (typing.NewType の属性)
@anchor{library/typing typing NewType __module__}@anchor{4507}
@deffn {の属性} __module__

The name of the module in which the new type is defined.
@end deffn

@geindex __name__ (typing.NewType の属性)
@anchor{library/typing typing NewType __name__}@anchor{4508}
@deffn {の属性} __name__

The name of the new type.
@end deffn

@geindex __supertype__ (typing.NewType の属性)
@anchor{library/typing typing NewType __supertype__}@anchor{4509}
@deffn {の属性} __supertype__

The type that the new type is based on.
@end deffn


Added in version 3.5.2.



バージョン 3.10 で変更: @code{NewType} is now a class rather than a function.

@end deffn

@geindex Protocol (typing のクラス)
@anchor{library/typing typing Protocol}@anchor{56b}
@deffn {クラス} typing.Protocol (Generic)

Base class for protocol classes.

Protocol classes are defined like this:

@example
class Proto(Protocol):
    def meth(self) -> int:
        ...
@end example

このようなクラスは主に構造的部分型 (静的ダックタイピング) を認識する静的型チェッカーが使います。例えば:

@example
class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check
@end example

See 
@geindex Python Enhancement Proposals; PEP 544
PEP 544@footnote{https://peps.python.org/pep-0544/} for more details. Protocol classes decorated with
@ref{675,,runtime_checkable()} (described later) act as simple-minded runtime
protocols that check only the presence of given attributes, ignoring their
type signatures. Protocol classes without this decorator cannot be used
as the second argument to @ref{2ad,,isinstance()} or @ref{9c4,,issubclass()}.

プロトコルクラスはジェネリックにもできます。例えば:

@example
class GenProto[T](Protocol):
    def meth(self) -> T:
        ...
@end example

In code that needs to be compatible with Python 3.11 or older, generic
Protocols can be written as follows:

@example
T = TypeVar("T")

class GenProto(Protocol[T]):
    def meth(self) -> T:
        ...
@end example


Added in version 3.8.

@end deffn

@geindex runtime_checkable() (typing モジュール)
@anchor{library/typing typing runtime_checkable}@anchor{675}
@deffn {の関数} @@typing.runtime_checkable

Mark a protocol class as a runtime protocol.

Such a protocol can be used with @ref{2ad,,isinstance()} and @ref{9c4,,issubclass()}.
This allows a simple-minded structural check, very similar to "one trick ponies"
in @ref{1f,,collections.abc} such as @ref{26ae,,Iterable}.  For example:

@example
@@runtime_checkable
class Closable(Protocol):
    def close(self): ...

assert isinstance(open('/some/file'), Closable)

@@runtime_checkable
class Named(Protocol):
    name: str

import threading
assert isinstance(threading.Thread(name='Bob'), Named)
@end example

This decorator raises @ref{198,,TypeError} when applied to a non-protocol class.

@cartouche
@quotation 注釈 
@code{runtime_checkable()} will check only the presence of the required
methods or attributes, not their type signatures or types.
For example, @ref{d7a,,ssl.SSLObject}
is a class, therefore it passes an @ref{9c4,,issubclass()}
check against @ref{26cf,,Callable}. However, the
@code{ssl.SSLObject.__init__} method exists only to raise a
@ref{198,,TypeError} with a more informative message, therefore making
it impossible to call (instantiate) @ref{d7a,,ssl.SSLObject}.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
An @ref{2ad,,isinstance()} check against a runtime-checkable protocol can be
surprisingly slow compared to an @code{isinstance()} check against
a non-protocol class. Consider using alternative idioms such as
@ref{6f9,,hasattr()} calls for structural checks in performance-sensitive
code.
@end quotation
@end cartouche


Added in version 3.8.



バージョン 3.12 で変更: The internal implementation of @ref{2ad,,isinstance()} checks against
runtime-checkable protocols now uses @ref{6bc,,inspect.getattr_static()}
to look up attributes (previously, @ref{6f9,,hasattr()} was used).
As a result, some objects which used to be considered instances
of a runtime-checkable protocol may no longer be considered instances
of that protocol on Python 3.12+, and vice versa.
Most users are unlikely to be affected by this change.



バージョン 3.12 で変更: The members of a runtime-checkable protocol are now considered "frozen"
at runtime as soon as the class has been created. Monkey-patching
attributes onto a runtime-checkable protocol will still work, but will
have no impact on @ref{2ad,,isinstance()} checks comparing objects to the
protocol. See @ref{6f8,,What's new in Python 3.12}
for more details.

@end deffn

@geindex TypedDict (typing のクラス)
@anchor{library/typing typing TypedDict}@anchor{332}
@deffn {クラス} typing.TypedDict (dict)

Special construct to add type hints to a dictionary.
At runtime "@code{TypedDict} instances" are simply @ref{183,,dicts}.

@code{TypedDict} は、その全てのインスタンスにおいてキーの集合が固定されていて、各キーに対応する値が全てのインスタンスで同じ型を持つことが期待される辞書型を宣言します。
この期待は実行時にはチェックされず、型チェッカーでのみ強制されます。
使用方法は次の通りです:

@example
class Point2D(TypedDict):
    x: int
    y: int
    label: str

a: Point2D = @{'x': 1, 'y': 2, 'label': 'good'@}  # OK
b: Point2D = @{'z': 3, 'label': 'bad'@}           # Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
@end example

An alternative way to create a @code{TypedDict} is by using
function-call syntax. The second argument must be a literal @ref{183,,dict}:

@example
Point2D = TypedDict('Point2D', @{'x': int, 'y': int, 'label': str@})
@end example

This functional syntax allows defining keys which are not valid
@ref{22a0,,identifiers}, for example because they are
keywords or contain hyphens, or when key names must not be
@ref{20a3,,mangled} like regular private names:

@example
# raises SyntaxError
class Point2D(TypedDict):
    in: int  # 'in' is a keyword
    x-y: int  # name with hyphens

class Definition(TypedDict):
    __schema: str  # mangled to `_Definition__schema`

# OK, functional syntax
Point2D = TypedDict('Point2D', @{'in': int, 'x-y': int@})
Definition = TypedDict('Definition', @{'__schema': str@})  # not mangled
@end example

By default, all keys must be present in a @code{TypedDict}. It is possible to
mark individual keys as non-required using @ref{7e1,,NotRequired}:

@example
class Point2D(TypedDict):
    x: int
    y: int
    label: NotRequired[str]

# Alternative syntax
Point2D = TypedDict('Point2D', @{'x': int, 'y': int, 'label': NotRequired[str]@})
@end example

This means that a @code{Point2D} @code{TypedDict} can have the @code{label}
key omitted.

It is also possible to mark all keys as non-required by default
by specifying a totality of @code{False}:

@example
class Point2D(TypedDict, total=False):
    x: int
    y: int

# Alternative syntax
Point2D = TypedDict('Point2D', @{'x': int, 'y': int@}, total=False)
@end example

This means that a @code{Point2D} @code{TypedDict} can have any of the keys
omitted. A type checker is only expected to support a literal @code{False} or
@code{True} as the value of the @code{total} argument. @code{True} is the default,
and makes all items defined in the class body required.

Individual keys of a @code{total=False} @code{TypedDict} can be marked as
required using @ref{7e0,,Required}:

@example
class Point2D(TypedDict, total=False):
    x: Required[int]
    y: Required[int]
    label: str

# Alternative syntax
Point2D = TypedDict('Point2D', @{
    'x': Required[int],
    'y': Required[int],
    'label': str
@}, total=False)
@end example

It is possible for a @code{TypedDict} type to inherit from one or more other @code{TypedDict} types
using the class-based syntax.
Usage:

@example
class Point3D(Point2D):
    z: int
@end example

@code{Point3D} has three items: @code{x}, @code{y} and @code{z}. It is equivalent to this
definition:

@example
class Point3D(TypedDict):
    x: int
    y: int
    z: int
@end example

A @code{TypedDict} cannot inherit from a non-@code{TypedDict} class,
except for @ref{17b6,,Generic}. For example:

@example
class X(TypedDict):
    x: int

class Y(TypedDict):
    y: int

class Z(object): pass  # A non-TypedDict class

class XY(X, Y): pass  # OK

class XZ(X, Z): pass  # raises TypeError
@end example

A @code{TypedDict} can be generic:

@example
class Group[T](TypedDict):
    key: T
    group: list[T]
@end example

To create a generic @code{TypedDict} that is compatible with Python 3.11
or lower, inherit from @ref{17b6,,Generic} explicitly:

@example
T = TypeVar("T")

class Group(TypedDict, Generic[T]):
    key: T
    group: list[T]
@end example

A @code{TypedDict} can be introspected via annotations dicts
(see @ref{9d9,,Annotations Best Practices} for more information on annotations best practices),
@ref{450a,,__total__}, @ref{450b,,__required_keys__}, and @ref{450c,,__optional_keys__}.

@geindex __total__ (typing.TypedDict の属性)
@anchor{library/typing typing TypedDict __total__}@anchor{450a}
@deffn {の属性} __total__

@code{Point2D.__total__} gives the value of the @code{total} argument.
Example:

@example
>>> from typing import TypedDict
>>> class Point2D(TypedDict): pass
>>> Point2D.__total__
True
>>> class Point2D(TypedDict, total=False): pass
>>> Point2D.__total__
False
>>> class Point3D(Point2D): pass
>>> Point3D.__total__
True
@end example

This attribute reflects `only' the value of the @code{total} argument
to the current @code{TypedDict} class, not whether the class is semantically
total. For example, a @code{TypedDict} with @code{__total__} set to @code{True} may
have keys marked with @ref{7e1,,NotRequired}, or it may inherit from another
@code{TypedDict} with @code{total=False}. Therefore, it is generally better to use
@ref{450b,,__required_keys__} and @ref{450c,,__optional_keys__} for introspection.
@end deffn

@geindex __required_keys__ (typing.TypedDict の属性)
@anchor{library/typing typing TypedDict __required_keys__}@anchor{450b}
@deffn {の属性} __required_keys__


Added in version 3.9.

@end deffn

@geindex __optional_keys__ (typing.TypedDict の属性)
@anchor{library/typing typing TypedDict __optional_keys__}@anchor{450c}
@deffn {の属性} __optional_keys__

@code{Point2D.__required_keys__} and @code{Point2D.__optional_keys__} return
@ref{7f2,,frozenset} objects containing required and non-required keys, respectively.

Keys marked with @ref{7e0,,Required} will always appear in @code{__required_keys__}
and keys marked with @ref{7e1,,NotRequired} will always appear in @code{__optional_keys__}.

For backwards compatibility with Python 3.10 and below,
it is also possible to use inheritance to declare both required and
non-required keys in the same @code{TypedDict} . This is done by declaring a
@code{TypedDict} with one value for the @code{total} argument and then
inheriting from it in another @code{TypedDict} with a different value for
@code{total}:

@example
>>> class Point2D(TypedDict, total=False):
...     x: int
...     y: int
...
>>> class Point3D(Point2D):
...     z: int
...
>>> Point3D.__required_keys__ == frozenset(@{'z'@})
True
>>> Point3D.__optional_keys__ == frozenset(@{'x', 'y'@})
True
@end example


Added in version 3.9.


@cartouche
@quotation 注釈 
If @code{from __future__ import annotations} is used or if annotations
are given as strings, annotations are not evaluated when the
@code{TypedDict} is defined. Therefore, the runtime introspection that
@code{__required_keys__} and @code{__optional_keys__} rely on may not work
properly, and the values of the attributes may be incorrect.
@end quotation
@end cartouche
@end deffn

Support for @ref{48a,,ReadOnly} is reflected in the following attributes:

@geindex __readonly_keys__ (typing.TypedDict の属性)
@anchor{library/typing typing TypedDict __readonly_keys__}@anchor{450d}
@deffn {の属性} __readonly_keys__

A @ref{7f2,,frozenset} containing the names of all read-only keys. Keys
are read-only if they carry the @ref{48a,,ReadOnly} qualifier.


Added in version 3.13.

@end deffn

@geindex __mutable_keys__ (typing.TypedDict の属性)
@anchor{library/typing typing TypedDict __mutable_keys__}@anchor{450e}
@deffn {の属性} __mutable_keys__

A @ref{7f2,,frozenset} containing the names of all mutable keys. Keys
are mutable if they do not carry the @ref{48a,,ReadOnly} qualifier.


Added in version 3.13.

@end deffn

See the TypedDict@footnote{https://typing.python.org/en/latest/spec/typeddict.html#typeddict} section in the typing documentation for more examples and detailed rules.


Added in version 3.8.



バージョン 3.9 で変更: @code{TypedDict} is now a function rather than a class.
It can still be used as a class base, as described above.



バージョン 3.11 で変更: Added support for marking individual keys as @ref{7e0,,Required} or @ref{7e1,,NotRequired}.
See 
@geindex Python Enhancement Proposals; PEP 655
PEP 655@footnote{https://peps.python.org/pep-0655/}.



バージョン 3.11 で変更: Added support for generic @code{TypedDict}s.



バージョン 3.13 で変更: Removed support for the keyword-argument method of creating @code{TypedDict}s.



バージョン 3.13 で変更: Support for the @ref{48a,,ReadOnly} qualifier was added.



Deprecated since version 3.13, will be removed in version 3.15: When using the functional syntax to create a TypedDict class, failing to
pass a value to the 'fields' parameter (@code{TD = TypedDict("TD")}) is
deprecated. Passing @code{None} to the 'fields' parameter
(@code{TD = TypedDict("TD", None)}) is also deprecated. Both will be
disallowed in Python 3.15. To create a TypedDict class with 0 fields,
use @code{class TD(TypedDict): pass} or @code{TD = TypedDict("TD", @{@})}.

@end deffn

@node プロトコル<4>,ABCs and Protocols for working with I/O,特殊型付けプリミティブ,モジュールの内容<3>
@anchor{library/typing protocols}@anchor{450f}
@subsubsection プロトコル


The following protocols are provided by the @code{typing} module. All are decorated
with @ref{675,,@@runtime_checkable}.

@geindex SupportsAbs (typing のクラス)
@anchor{library/typing typing SupportsAbs}@anchor{4510}
@deffn {クラス} typing.SupportsAbs

返り値の型と共変な抽象メソッド @code{__abs__} を備えた ABC です。
@end deffn

@geindex SupportsBytes (typing のクラス)
@anchor{library/typing typing SupportsBytes}@anchor{800}
@deffn {クラス} typing.SupportsBytes

抽象メソッド @code{__bytes__} を備えた ABC です。
@end deffn

@geindex SupportsComplex (typing のクラス)
@anchor{library/typing typing SupportsComplex}@anchor{7ff}
@deffn {クラス} typing.SupportsComplex

抽象メソッド @code{__complex__} を備えた ABC です。
@end deffn

@geindex SupportsFloat (typing のクラス)
@anchor{library/typing typing SupportsFloat}@anchor{4511}
@deffn {クラス} typing.SupportsFloat

抽象メソッド @code{__float__} を備えた ABC です。
@end deffn

@geindex SupportsIndex (typing のクラス)
@anchor{library/typing typing SupportsIndex}@anchor{c3a}
@deffn {クラス} typing.SupportsIndex

抽象メソッド @code{__index__} を備えた ABC です。


Added in version 3.8.

@end deffn

@geindex SupportsInt (typing のクラス)
@anchor{library/typing typing SupportsInt}@anchor{c39}
@deffn {クラス} typing.SupportsInt

抽象メソッド @code{__int__} を備えた ABC です。
@end deffn

@geindex SupportsRound (typing のクラス)
@anchor{library/typing typing SupportsRound}@anchor{4512}
@deffn {クラス} typing.SupportsRound

返り値の型と共変な抽象メソッド @code{__round__} を備えた ABC です。
@end deffn

@node ABCs and Protocols for working with I/O,Functions and decorators,プロトコル<4>,モジュールの内容<3>
@anchor{library/typing abcs-and-protocols-for-working-with-i-o}@anchor{4513}@anchor{library/typing typing-io}@anchor{312a}
@subsubsection ABCs and Protocols for working with I/O


@geindex IO (typing のクラス)
@geindex TextIO (typing のクラス)
@geindex BinaryIO (typing のクラス)
@anchor{library/typing typing IO}@anchor{238}
@deffn {クラス} typing.IO [AnyStr]
@anchor{library/typing typing TextIO}@anchor{239}
@deffnx {クラス} typing.TextIO
@anchor{library/typing typing BinaryIO}@anchor{23a}
@deffnx {クラス} typing.BinaryIO

Generic class @code{IO[AnyStr]} and its subclasses @code{TextIO(IO[str])}
and @code{BinaryIO(IO[bytes])}
represent the types of I/O streams such as returned by
@ref{316,,open()}. Please note that these classes are not protocols, and
their interface is fairly broad.
@end deffn

The protocols @ref{236,,io.Reader} and @ref{237,,io.Writer} offer a simpler
alternative for argument types, when only the @code{read()} or @code{write()}
methods are accessed, respectively:

@example
def read_and_write(reader: Reader[str], writer: Writer[bytes]):
    data = reader.read()
    writer.write(data.encode())
@end example

Also consider using @ref{26ae,,collections.abc.Iterable} for iterating over
the lines of an input stream:

@example
def read_config(stream: Iterable[str]):
    for line in stream:
        ...
@end example

@node Functions and decorators,Introspection helpers,ABCs and Protocols for working with I/O,モジュールの内容<3>
@anchor{library/typing functions-and-decorators}@anchor{4514}
@subsubsection Functions and decorators


@geindex cast() (typing モジュール)
@anchor{library/typing typing cast}@anchor{44fa}
@deffn {の関数} typing.cast (typ, val)

値をある型にキャストします。

この関数は値を変更せずに返します。
型検査器に対して、返り値が指定された型を持っていることを通知しますが、実行時には意図的に何も検査しません。
(その理由は、処理をできる限り速くしたかったためです。)
@end deffn

@geindex assert_type() (typing モジュール)
@anchor{library/typing typing assert_type}@anchor{8ba}
@deffn {の関数} typing.assert_type (val, typ, /)

Ask a static type checker to confirm that `val' has an inferred type of `typ'.

At runtime this does nothing: it returns the first argument unchanged with no
checks or side effects, no matter the actual type of the argument.

When a static type checker encounters a call to @code{assert_type()}, it
emits an error if the value is not of the specified type:

@example
def greet(name: str) -> None:
    assert_type(name, str)  # OK, inferred type of `name` is `str`
    assert_type(name, int)  # type checker error
@end example

This function is useful for ensuring the type checker's understanding of a
script is in line with the developer's intentions:

@example
def complex_function(arg: object):
    # Do some complex type-narrowing logic,
    # after which we hope the inferred type will be `int`
    ...
    # Test whether the type checker correctly understands our function
    assert_type(arg, int)
@end example


Added in version 3.11.

@end deffn

@geindex assert_never() (typing モジュール)
@anchor{library/typing typing assert_never}@anchor{8b6}
@deffn {の関数} typing.assert_never (arg, /)

Ask a static type checker to confirm that a line of code is unreachable.

以下はプログラム例です:

@example
def int_or_str(arg: int | str) -> None:
    match arg:
        case int():
            print("It's an int")
        case str():
            print("It's a str")
        case _ as unreachable:
            assert_never(unreachable)
@end example

Here, the annotations allow the type checker to infer that the
last case can never execute, because @code{arg} is either
an @ref{19b,,int} or a @ref{169,,str}, and both options are covered by
earlier cases.

If a type checker finds that a call to @code{assert_never()} is
reachable, it will emit an error. For example, if the type annotation
for @code{arg} was instead @code{int | str | float}, the type checker would
emit an error pointing out that @code{unreachable} is of type @ref{196,,float}.
For a call to @code{assert_never} to pass type checking, the inferred type of
the argument passed in must be the bottom type, @ref{8b7,,Never}, and nothing
else.

At runtime, this throws an exception when called.


@subsubheading 参考


Unreachable Code and Exhaustiveness Checking@footnote{https://typing.python.org/en/latest/guides/unreachable.html} has more
information about exhaustiveness checking with static typing.



Added in version 3.11.

@end deffn

@geindex reveal_type() (typing モジュール)
@anchor{library/typing typing reveal_type}@anchor{8b9}
@deffn {の関数} typing.reveal_type (obj, /)

Ask a static type checker to reveal the inferred type of an expression.

When a static type checker encounters a call to this function,
it emits a diagnostic with the inferred type of the argument. For example:

@example
x: int = 1
reveal_type(x)  # Revealed type is "builtins.int"
@end example

This can be useful when you want to debug how your type checker
handles a particular piece of code.

At runtime, this function prints the runtime type of its argument to
@ref{b33,,sys.stderr} and returns the argument unchanged (allowing the call to
be used within an expression):

@example
x = reveal_type(1)  # prints "Runtime type is int"
print(x)  # prints "1"
@end example

Note that the runtime type may be different from (more or less specific
than) the type statically inferred by a type checker.

Most type checkers support @code{reveal_type()} anywhere, even if the
name is not imported from @code{typing}. Importing the name from
@code{typing}, however, allows your code to run without runtime errors and
communicates intent more clearly.


Added in version 3.11.

@end deffn

@geindex dataclass_transform() (typing モジュール)
@anchor{library/typing typing dataclass_transform}@anchor{6fb}
@deffn {の関数} @@typing.dataclass_transform (*, eq_default=True, order_default=False, kw_only_default=False, frozen_default=False, field_specifiers=(), **kwargs)

Decorator to mark an object as providing
@ref{4e1,,dataclass}-like behavior.

@code{dataclass_transform} may be used to
decorate a class, metaclass, or a function that is itself a decorator.
The presence of @code{@@dataclass_transform()} tells a static type checker that the
decorated object performs runtime "magic" that
transforms a class in a similar way to
@ref{4e1,,@@dataclasses.dataclass}.

Example usage with a decorator function:

@example
@@dataclass_transform()
def create_model[T](cls: type[T]) -> type[T]:
    ...
    return cls

@@create_model
class CustomerModel:
    id: int
    name: str
@end example

On a base class:

@example
@@dataclass_transform()
class ModelBase: ...

class CustomerModel(ModelBase):
    id: int
    name: str
@end example

On a metaclass:

@example
@@dataclass_transform()
class ModelMeta(type): ...

class ModelBase(metaclass=ModelMeta): ...

class CustomerModel(ModelBase):
    id: int
    name: str
@end example

The @code{CustomerModel} classes defined above will
be treated by type checkers similarly to classes created with
@ref{4e1,,@@dataclasses.dataclass}.
For example, type checkers will assume these classes have
@code{__init__} methods that accept @code{id} and @code{name}.

The decorated class, metaclass, or function may accept the following bool
arguments which type checkers will assume have the same effect as they
would have on the
@ref{4e1,,@@dataclasses.dataclass} decorator: @code{init},
@code{eq}, @code{order}, @code{unsafe_hash}, @code{frozen}, @code{match_args},
@code{kw_only}, and @code{slots}. It must be possible for the value of these
arguments (@code{True} or @code{False}) to be statically evaluated.

The arguments to the @code{dataclass_transform} decorator can be used to
customize the default behaviors of the decorated class, metaclass, or
function:

@*パラメータ: 

@itemize *

@item 
@code{eq_default} (@ref{3c3,,bool}) -- Indicates whether the @code{eq} parameter is assumed to be
@code{True} or @code{False} if it is omitted by the caller.
Defaults to @code{True}.

@item 
@code{order_default} (@ref{3c3,,bool}) -- Indicates whether the @code{order} parameter is
assumed to be @code{True} or @code{False} if it is omitted by the caller.
Defaults to @code{False}.

@item 
@code{kw_only_default} (@ref{3c3,,bool}) -- Indicates whether the @code{kw_only} parameter is
assumed to be @code{True} or @code{False} if it is omitted by the caller.
Defaults to @code{False}.

@item 
@code{frozen_default} (@ref{3c3,,bool}) -- 
Indicates whether the @code{frozen} parameter is
assumed to be @code{True} or @code{False} if it is omitted by the caller.
Defaults to @code{False}.


Added in version 3.12.



@item 
@code{field_specifiers} (@ref{614,,tuple}@code{[}@ref{9eb,,Callable}@code{[}@code{...}@code{, }@code{Any}@code{]}@code{, }@code{...}@code{]}) -- Specifies a static list of supported classes
or functions that describe fields, similar to @ref{195a,,dataclasses.field()}.
Defaults to @code{()}.

@item 
@code{**kwargs} (@code{Any}) -- Arbitrary other keyword arguments are accepted in order to allow for
possible future extensions.
@end itemize


Type checkers recognize the following optional parameters on field
specifiers:
`Recognised parameters for field specifiers'



@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Parameter name

@tab

説明

@item

@code{init}

@tab

Indicates whether the field should be included in the
synthesized @code{__init__} method. If unspecified, @code{init} defaults to
@code{True}.

@item

@code{default}

@tab

Provides the default value for the field.

@item

@code{default_factory}

@tab

Provides a runtime callback that returns the
default value for the field. If neither @code{default} nor
@code{default_factory} are specified, the field is assumed to have no
default value and must be provided a value when the class is
instantiated.

@item

@code{factory}

@tab

An alias for the @code{default_factory} parameter on field specifiers.

@item

@code{kw_only}

@tab

Indicates whether the field should be marked as
keyword-only. If @code{True}, the field will be keyword-only. If
@code{False}, it will not be keyword-only. If unspecified, the value of
the @code{kw_only} parameter on the object decorated with
@code{dataclass_transform} will be used, or if that is unspecified, the
value of @code{kw_only_default} on @code{dataclass_transform} will be used.

@item

@code{alias}

@tab

Provides an alternative name for the field. This alternative
name is used in the synthesized @code{__init__} method.

@end multitable


At runtime, this decorator records its arguments in the
@code{__dataclass_transform__} attribute on the decorated object.
It has no other runtime effect.

より詳しくは 
@geindex Python Enhancement Proposals; PEP 681
PEP 681@footnote{https://peps.python.org/pep-0681/} を参照してください。


Added in version 3.11.

@end deffn

@geindex overload() (typing モジュール)
@anchor{library/typing overload}@anchor{44d6}@anchor{library/typing typing overload}@anchor{4515}
@deffn {の関数} @@typing.overload

Decorator for creating overloaded functions and methods.

The @code{@@overload} decorator allows describing functions and methods
that support multiple different combinations of argument types. A series
of @code{@@overload}-decorated definitions must be followed by exactly one
non-@code{@@overload}-decorated definition (for the same function/method).

@code{@@overload}-decorated definitions are for the benefit of the
type checker only, since they will be overwritten by the
non-@code{@@overload}-decorated definition. The non-@code{@@overload}-decorated
definition, meanwhile, will be used at
runtime but should be ignored by a type checker.  At runtime, calling
an @code{@@overload}-decorated function directly will raise
@ref{36b,,NotImplementedError}.

An example of overload that gives a more
precise type than can be expressed using a union or a type variable:

@example
@@overload
def process(response: None) -> None:
    ...
@@overload
def process(response: int) -> tuple[int, str]:
    ...
@@overload
def process(response: bytes) -> str:
    ...
def process(response):
    ...  # actual implementation goes here
@end example

詳細と他の型付け意味論との比較は 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} を参照してください。


バージョン 3.11 で変更: Overloaded functions can now be introspected at runtime using
@ref{8bd,,get_overloads()}.

@end deffn

@geindex get_overloads() (typing モジュール)
@anchor{library/typing typing get_overloads}@anchor{8bd}
@deffn {の関数} typing.get_overloads (func)

Return a sequence of @ref{4515,,@@overload}-decorated definitions for
`func'.

`func' is the function object for the implementation of the
overloaded function. For example, given the definition of @code{process} in
the documentation for @ref{4515,,@@overload},
@code{get_overloads(process)} will return a sequence of three function objects
for the three defined overloads. If called on a function with no overloads,
@code{get_overloads()} returns an empty sequence.

@code{get_overloads()} can be used for introspecting an overloaded function at
runtime.


Added in version 3.11.

@end deffn

@geindex clear_overloads() (typing モジュール)
@anchor{library/typing typing clear_overloads}@anchor{8be}
@deffn {の関数} typing.clear_overloads ()

Clear all registered overloads in the internal registry.

This can be used to reclaim the memory used by the registry.


Added in version 3.11.

@end deffn

@geindex final() (typing モジュール)
@anchor{library/typing typing final}@anchor{8bc}
@deffn {の関数} @@typing.final

Decorator to indicate final methods and final classes.

Decorating a method with @code{@@final} indicates to a type checker that the
method cannot be overridden in a subclass. Decorating a class with @code{@@final}
indicates that it cannot be subclassed.

例えば:

@example
class Base:
    @@final
    def done(self) -> None:
        ...
class Sub(Base):
    def done(self) -> None:  # Error reported by type checker
        ...

@@final
class Leaf:
    ...
class Other(Leaf):  # Error reported by type checker
    ...
@end example

この機能は実行時には検査されません。詳細については 
@geindex Python Enhancement Proposals; PEP 591
PEP 591@footnote{https://peps.python.org/pep-0591/} を参照してください。


Added in version 3.8.



バージョン 3.11 で変更: The decorator will now attempt to set a @code{__final__} attribute to @code{True}
on the decorated object. Thus, a check like
@code{if getattr(obj, "__final__", False)} can be used at runtime
to determine whether an object @code{obj} has been marked as final.
If the decorated object does not support setting attributes,
the decorator returns the object unchanged without raising an exception.

@end deffn

@geindex no_type_check() (typing モジュール)
@anchor{library/typing typing no_type_check}@anchor{8c3}
@deffn {の関数} @@typing.no_type_check

アノテーションが型ヒントでないことを示すデコレータです。

This works as a class or function @ref{93a,,decorator}.  With a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses). Type
checkers will ignore all annotations in a function or class with this
decorator.

@code{@@no_type_check} mutates the decorated object in place.
@end deffn

@geindex no_type_check_decorator() (typing モジュール)
@anchor{library/typing typing no_type_check_decorator}@anchor{333}
@deffn {の関数} @@typing.no_type_check_decorator

別のデコレータに @ref{8c3,,no_type_check()} の効果を与えるデコレータです。

これは何かの関数をラップするデコレータを @ref{8c3,,no_type_check()} でラップします。


Deprecated since version 3.13, will be removed in version 3.15: No type checker ever added support for @code{@@no_type_check_decorator}. It
is therefore deprecated, and will be removed in Python 3.15.

@end deffn

@geindex override() (typing モジュール)
@anchor{library/typing typing override}@anchor{67d}
@deffn {の関数} @@typing.override

Decorator to indicate that a method in a subclass is intended to override a
method or attribute in a superclass.

Type checkers should emit an error if a method decorated with @code{@@override}
does not, in fact, override anything.
This helps prevent bugs that may occur when a base class is changed without
an equivalent change to a child class.

例えば:

@example
class Base:
    def log_status(self) -> None:
        ...

class Sub(Base):
    @@override
    def log_status(self) -> None:  # Okay: overrides Base.log_status
        ...

    @@override
    def done(self) -> None:  # Error reported by type checker
        ...
@end example

There is no runtime checking of this property.

The decorator will attempt to set an @code{__override__} attribute to @code{True} on
the decorated object. Thus, a check like
@code{if getattr(obj, "__override__", False)} can be used at runtime to determine
whether an object @code{obj} has been marked as an override.  If the decorated object
does not support setting attributes, the decorator returns the object unchanged
without raising an exception.

See 
@geindex Python Enhancement Proposals; PEP 698
PEP 698@footnote{https://peps.python.org/pep-0698/} for more details.


Added in version 3.12.

@end deffn

@geindex type_check_only() (typing モジュール)
@anchor{library/typing typing type_check_only}@anchor{4516}
@deffn {の関数} @@typing.type_check_only

Decorator to mark a class or function as unavailable at runtime.

このデコレータ自身は実行時には使えません。
このデコレータは主に、実装がプライベートクラスのインスタンスを返す場合に、型スタブファイルに定義されているクラスに対して印を付けるためのものです:

@example
@@type_check_only
class Response:  # private or not available at runtime
    code: int
    def get_header(self, name: str) -> str: ...

def fetch_response() -> Response: ...
@end example

プライベートクラスのインスタンスを返すのは推奨されません。
そのようなクラスは公開クラスにするのが望ましいです。
@end deffn

@node Introspection helpers,定数<10>,Functions and decorators,モジュールの内容<3>
@anchor{library/typing introspection-helpers}@anchor{4517}
@subsubsection Introspection helpers


@geindex get_type_hints() (typing モジュール)
@anchor{library/typing typing get_type_hints}@anchor{8c0}
@deffn {の関数} typing.get_type_hints (obj, globalns=None, localns=None, include_extras=False)

関数、メソッド、モジュールまたはクラスのオブジェクトの型ヒントを含む辞書を返します。

This is often the same as @code{obj.__annotations__}, but this function makes
the following changes to the annotations dictionary:


@itemize *

@item 
Forward references encoded as string literals or @ref{1bda,,ForwardRef}
objects are handled by evaluating them in `globalns', `localns', and
(where applicable) `obj''s @ref{5ad,,type parameter} namespace.
If `globalns' or `localns' is not given, appropriate namespace
dictionaries are inferred from `obj'.

@item 
@code{None} is replaced with @ref{a52,,types.NoneType}.

@item 
If @ref{8c3,,@@no_type_check} has been applied to `obj', an
empty dictionary is returned.

@item 
If `obj' is a class @code{C}, the function returns a dictionary that merges
annotations from @code{C}'s base classes with those on @code{C} directly. This
is done by traversing @ref{2378,,C.__mro__} and iteratively
combining
@code{__annotations__} dictionaries. Annotations on classes appearing
earlier in the @ref{25df,,method resolution order} always take precedence over
annotations on classes appearing later in the method resolution order.

@item 
The function recursively replaces all occurrences of
@code{Annotated[T, ...]}, @code{Required[T]}, @code{NotRequired[T]}, and @code{ReadOnly[T]}
with @code{T}, unless `include_extras' is set to @code{True} (see
@ref{b37,,Annotated} for more information).
@end itemize

See also @ref{459,,annotationlib.get_annotations()}, a lower-level function that
returns annotations more directly.

@cartouche
@quotation 注意 
This function may execute arbitrary code contained in annotations.
See @ref{4518,,Security implications of introspecting annotations} for more information.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
If any forward references in the annotations of `obj' are not resolvable
or are not valid Python code, this function will raise an exception
such as @ref{452,,NameError}. For example, this can happen with imported
@ref{683,,type aliases} that include forward references,
or with names imported under @ref{ef0,,if TYPE_CHECKING}.
@end quotation
@end cartouche


バージョン 3.9 で変更: Added @code{include_extras} parameter as part of 
@geindex Python Enhancement Proposals; PEP 593
PEP 593@footnote{https://peps.python.org/pep-0593/}.
See the documentation on @ref{b37,,Annotated} for more information.



バージョン 3.11 で変更: Previously, @code{Optional[t]} was added for function and method annotations
if a default value equal to @code{None} was set.
Now the annotation is returned unchanged.

@end deffn

@geindex get_origin() (typing モジュール)
@anchor{library/typing typing get_origin}@anchor{2ab}
@deffn {の関数} typing.get_origin (tp)

Get the unsubscripted version of a type: for a typing object of the form
@code{X[Y, Z, ...]} return @code{X}.

If @code{X} is a typing-module alias for a builtin or
@ref{1e,,collections} class, it will be normalized to the original class.
If @code{X} is an instance of @ref{9c9,,ParamSpecArgs} or @ref{9ca,,ParamSpecKwargs},
return the underlying @ref{487,,ParamSpec}.
Return @code{None} for unsupported objects.

例:

@example
assert get_origin(str) is None
assert get_origin(Dict[str, int]) is dict
assert get_origin(Union[int, str]) is Union
assert get_origin(Annotated[str, "metadata"]) is Annotated
P = ParamSpec('P')
assert get_origin(P.args) is P
assert get_origin(P.kwargs) is P
@end example


Added in version 3.8.

@end deffn

@geindex get_args() (typing モジュール)
@anchor{library/typing typing get_args}@anchor{2ac}
@deffn {の関数} typing.get_args (tp)

Get type arguments with all substitutions performed: for a typing object
of the form @code{X[Y, Z, ...]} return @code{(Y, Z, ...)}.

If @code{X} is a union or @ref{a55,,Literal} contained in another
generic type, the order of @code{(Y, Z, ...)} may be different from the order
of the original arguments @code{[Y, Z, ...]} due to type caching.
Return @code{()} for unsupported objects.

例:

@example
assert get_args(int) == ()
assert get_args(Dict[int, str]) == (int, str)
assert get_args(Union[int, str]) == (int, str)
@end example


Added in version 3.8.

@end deffn

@geindex get_protocol_members() (typing モジュール)
@anchor{library/typing typing get_protocol_members}@anchor{56a}
@deffn {の関数} typing.get_protocol_members (tp)

Return the set of members defined in a @ref{56b,,Protocol}.

@example
>>> from typing import Protocol, get_protocol_members
>>> class P(Protocol):
...     def a(self) -> str: ...
...     b: int
>>> get_protocol_members(P) == frozenset(@{'a', 'b'@})
True
@end example

Raise @ref{198,,TypeError} for arguments that are not Protocols.


Added in version 3.13.

@end deffn

@geindex is_protocol() (typing モジュール)
@anchor{library/typing typing is_protocol}@anchor{56c}
@deffn {の関数} typing.is_protocol (tp)

Determine if a type is a @ref{56b,,Protocol}.

例えば:

@example
class P(Protocol):
    def a(self) -> str: ...
    b: int

is_protocol(P)    # => True
is_protocol(int)  # => False
@end example


Added in version 3.13.

@end deffn

@geindex is_typeddict() (typing モジュール)
@anchor{library/typing typing is_typeddict}@anchor{a56}
@deffn {の関数} typing.is_typeddict (tp)

Check if a type is a @ref{332,,TypedDict}.

例えば:

@example
class Film(TypedDict):
    title: str
    year: int

assert is_typeddict(Film)
assert not is_typeddict(list | str)

# TypedDict is a factory for creating typed dicts,
# not a typed dict itself
assert not is_typeddict(TypedDict)
@end example


Added in version 3.10.

@end deffn

@geindex ForwardRef (typing のクラス)
@anchor{library/typing typing ForwardRef}@anchor{1bda}
@deffn {クラス} typing.ForwardRef

Class used for internal typing representation of string forward references.

For example, @code{List["SomeClass"]} is implicitly transformed into
@code{List[ForwardRef("SomeClass")]}.  @code{ForwardRef} should not be instantiated by
a user, but may be used by introspection tools.

@cartouche
@quotation 注釈 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} generic types such as @code{list["SomeClass"]} will not be
implicitly transformed into @code{list[ForwardRef("SomeClass")]} and thus
will not automatically resolve to @code{list[SomeClass]}.
@end quotation
@end cartouche


Added in version 3.7.4.



バージョン 3.14 で変更: This is now an alias for @ref{1776,,annotationlib.ForwardRef}. Several undocumented
behaviors of this class have been changed; for example, after a @code{ForwardRef} has
been evaluated, the evaluated value is no longer cached.

@end deffn

@geindex evaluate_forward_ref() (typing モジュール)
@anchor{library/typing typing evaluate_forward_ref}@anchor{1815}
@deffn {の関数} typing.evaluate_forward_ref (forward_ref, *, owner=None, globals=None, locals=None, type_params=None, format=annotationlib.Format.VALUE)

Evaluate an @ref{1776,,annotationlib.ForwardRef} as a @ref{23cb,,type hint}.

This is similar to calling @ref{17b2,,annotationlib.ForwardRef.evaluate()},
but unlike that method, @code{evaluate_forward_ref()} also
recursively evaluates forward references nested within the type hint.

See the documentation for @ref{17b2,,annotationlib.ForwardRef.evaluate()} for
the meaning of the `owner', `globals', `locals', `type_params', and `format' parameters.

@cartouche
@quotation 注意 
This function may execute arbitrary code contained in annotations.
See @ref{4518,,Security implications of introspecting annotations} for more information.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@geindex NoDefault (typing モジュール)
@anchor{library/typing typing NoDefault}@anchor{569}
@deffn {データ} typing.NoDefault

A sentinel object used to indicate that a type parameter has no default
value. For example:

@example
>>> T = TypeVar("T")
>>> T.__default__ is typing.NoDefault
True
>>> S = TypeVar("S", default=None)
>>> S.__default__ is None
True
@end example


Added in version 3.13.

@end deffn

@node 定数<10>,非推奨のエイリアス,Introspection helpers,モジュールの内容<3>
@anchor{library/typing constant}@anchor{4519}
@subsubsection 定数


@geindex TYPE_CHECKING (typing モジュール)
@anchor{library/typing typing TYPE_CHECKING}@anchor{ef0}
@deffn {データ} typing.TYPE_CHECKING

A special constant that is assumed to be @code{True} by 3rd party static
type checkers. It's @code{False} at runtime.

A module which is expensive to import, and which only contain types
used for typing annotations, can be safely imported inside an
@code{if TYPE_CHECKING:} block.  This prevents the module from actually
being imported at runtime; annotations aren't eagerly evaluated
(see 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}) so using undefined symbols in annotations is
harmless--as long as you don't later examine them.
Your static type analysis tool will set @code{TYPE_CHECKING} to
@code{True} during static type analysis, which means the module will
be imported and the types will be checked properly during such analysis.

使い方:

@example
if TYPE_CHECKING:
    import expensive_mod

def fun(arg: expensive_mod.SomeType) -> None:
    local_var: expensive_mod.AnotherType = other_fun()
@end example

If you occasionally need to examine type annotations at runtime
which may contain undefined symbols, use
@ref{459,,annotationlib.get_annotations()} with a @code{format} parameter
of @ref{160,,annotationlib.Format.STRING} or
@ref{15f,,annotationlib.Format.FORWARDREF} to safely retrieve the
annotations without raising @ref{452,,NameError}.


Added in version 3.5.2.

@end deffn
@anchor{library/typing generic-concrete-collections}@anchor{451a}
@node 非推奨のエイリアス,,定数<10>,モジュールの内容<3>
@anchor{library/typing deprecated-aliases}@anchor{451b}@anchor{library/typing id6}@anchor{451c}
@subsubsection 非推奨のエイリアス


This module defines several deprecated aliases to pre-existing
standard library classes. These were originally included in the @code{typing}
module in order to support parameterizing these generic classes using @code{[]}.
However, the aliases became redundant in Python 3.9 when the
corresponding pre-existing classes were enhanced to support @code{[]} (see
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/}).

The redundant types are deprecated as of Python 3.9. However, while the aliases
may be removed at some point, removal of these aliases is not currently
planned. As such, no deprecation warnings are currently issued by the
interpreter for these aliases.

If at some point it is decided to remove these deprecated aliases, a
deprecation warning will be issued by the interpreter for at least two releases
prior to removal. The aliases are guaranteed to remain in the @code{typing} module
without deprecation warnings until at least Python 3.14.

Type checkers are encouraged to flag uses of the deprecated types if the
program they are checking targets a minimum Python version of 3.9 or newer.

@menu
* Aliases to built-in types:: 
* Aliases to types in collections:: 
* Aliases to other concrete types:: 
* Aliases to container ABCs in collections.abc: Aliases to container ABCs in collections abc. 
* Aliases to asynchronous ABCs in collections.abc: Aliases to asynchronous ABCs in collections abc. 
* Aliases to other ABCs in collections.abc: Aliases to other ABCs in collections abc. 
* Aliases to contextlib ABCs:: 

@end menu

@node Aliases to built-in types,Aliases to types in collections,,非推奨のエイリアス
@anchor{library/typing aliases-to-built-in-types}@anchor{451d}@anchor{library/typing corresponding-to-built-in-types}@anchor{451e}
@subsubsection Aliases to built-in types


@geindex Dict (typing のクラス)
@anchor{library/typing typing Dict}@anchor{451f}
@deffn {クラス} typing.Dict (dict, MutableMapping[KT, VT])

@ref{183,,dict} の非推奨なエイリアス。

Note that to annotate arguments, it is preferred
to use an abstract collection type such as @ref{ac7,,Mapping}
rather than to use @ref{183,,dict} or @code{typing.Dict}.


バージョン 3.9 で非推奨: @ref{183,,builtins.dict} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex List (typing のクラス)
@anchor{library/typing typing List}@anchor{4520}
@deffn {クラス} typing.List (list, MutableSequence[T])

@ref{24d,,list} の非推奨なエイリアス。

Note that to annotate arguments, it is preferred
to use an abstract collection type such as
@ref{13dc,,Sequence} or @ref{26ae,,Iterable}
rather than to use @ref{24d,,list} or @code{typing.List}.


バージョン 3.9 で非推奨: @ref{24d,,builtins.list} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Set (typing のクラス)
@anchor{library/typing typing Set}@anchor{4521}
@deffn {クラス} typing.Set (set, MutableSet[T])

Deprecated alias to @ref{184,,builtins.set}.

Note that to annotate arguments, it is preferred
to use an abstract collection type such as @ref{26a6,,collections.abc.Set}
rather than to use @ref{184,,set} or @ref{4521,,typing.Set}.


バージョン 3.9 で非推奨: @ref{184,,builtins.set} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex FrozenSet (typing のクラス)
@anchor{library/typing typing FrozenSet}@anchor{4522}
@deffn {クラス} typing.FrozenSet (frozenset, AbstractSet[T_co])

Deprecated alias to @ref{7f2,,builtins.frozenset}.


バージョン 3.9 で非推奨: @ref{7f2,,builtins.frozenset} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Tuple (typing モジュール)
@anchor{library/typing typing Tuple}@anchor{4523}
@deffn {データ} typing.Tuple

@ref{614,,tuple} の非推奨なエイリアス。

@ref{614,,tuple} and @code{Tuple} are special-cased in the type system; see
@ref{26d0,,タプルのアノテーション} for more details.


バージョン 3.9 で非推奨: @ref{614,,builtins.tuple} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Type (typing のクラス)
@anchor{library/typing typing Type}@anchor{44db}
@deffn {クラス} typing.Type (Generic[CT_co])

@ref{f44,,type} の非推奨なエイリアス。

See @ref{44da,,クラスオブジェクトの型} for details on using @ref{f44,,type} or
@code{typing.Type} in type annotations.


Added in version 3.5.2.



バージョン 3.9 で非推奨: @ref{f44,,builtins.type} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@node Aliases to types in collections,Aliases to other concrete types,Aliases to built-in types,非推奨のエイリアス
@anchor{library/typing aliases-to-types-in-collections}@anchor{4524}@anchor{library/typing corresponding-to-types-in-collections}@anchor{4525}
@subsubsection Aliases to types in @code{collections}


@geindex DefaultDict (typing のクラス)
@anchor{library/typing typing DefaultDict}@anchor{4526}
@deffn {クラス} typing.DefaultDict (collections.defaultdict, MutableMapping[KT, VT])

@ref{13d4,,collections.defaultdict} の非推奨なエイリアス。


Added in version 3.5.2.



バージョン 3.9 で非推奨: @ref{13d4,,collections.defaultdict} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex OrderedDict (typing のクラス)
@anchor{library/typing typing OrderedDict}@anchor{4527}
@deffn {クラス} typing.OrderedDict (collections.OrderedDict, MutableMapping[KT, VT])

@ref{7f3,,collections.OrderedDict} の非推奨なエイリアス。


Added in version 3.7.2.



バージョン 3.9 で非推奨: @ref{7f3,,collections.OrderedDict} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex ChainMap (typing のクラス)
@anchor{library/typing typing ChainMap}@anchor{4528}
@deffn {クラス} typing.ChainMap (collections.ChainMap, MutableMapping[KT, VT])

@ref{e16,,collections.ChainMap} の非推奨なエイリアス。


Added in version 3.6.1.



バージョン 3.9 で非推奨: @ref{e16,,collections.ChainMap} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Counter (typing のクラス)
@anchor{library/typing typing Counter}@anchor{4529}
@deffn {クラス} typing.Counter (collections.Counter, Dict[T, int])

@ref{12a3,,collections.Counter} の非推奨なエイリアス。


Added in version 3.6.1.



バージョン 3.9 で非推奨: @ref{12a3,,collections.Counter} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Deque (typing のクラス)
@anchor{library/typing typing Deque}@anchor{452a}
@deffn {クラス} typing.Deque (deque, MutableSequence[T])

@ref{7f4,,collections.deque} の非推奨なエイリアス。


Added in version 3.6.1.



バージョン 3.9 で非推奨: @ref{7f4,,collections.deque} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@node Aliases to other concrete types,Aliases to container ABCs in collections abc,Aliases to types in collections,非推奨のエイリアス
@anchor{library/typing aliases-to-other-concrete-types}@anchor{452b}@anchor{library/typing other-concrete-types}@anchor{452c}
@subsubsection Aliases to other concrete types


@geindex Pattern (typing のクラス)
@geindex Match (typing のクラス)
@anchor{library/typing typing Pattern}@anchor{935}
@deffn {クラス} typing.Pattern
@anchor{library/typing typing Match}@anchor{452d}
@deffnx {クラス} typing.Match

Deprecated aliases corresponding to the return types from
@ref{dce,,re.compile()} and @ref{1445,,re.match()}.

These types (and the corresponding functions) are generic over
@ref{5ac,,AnyStr}. @code{Pattern} can be specialised as @code{Pattern[str]} or
@code{Pattern[bytes]}; @code{Match} can be specialised as @code{Match[str]} or
@code{Match[bytes]}.


バージョン 3.9 で非推奨: Classes @code{Pattern} and @code{Match} from @ref{be,,re} now support @code{[]}.
See 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} and @ref{8c1,,ジェネリックエイリアス型}.

@end deffn

@geindex Text (typing のクラス)
@anchor{library/typing typing Text}@anchor{360}
@deffn {クラス} typing.Text

Deprecated alias for @ref{169,,str}.

@code{Text} is provided to supply a forward
compatible path for Python 2 code: in Python 2, @code{Text} is an alias for
@code{unicode}.

@code{Text} は Python 2 と Python 3 の両方と互換性のある方法で値が unicode 文字列を含んでいなければならない場合に使用してください。

@example
def add_unicode_checkmark(text: Text) -> Text:
    return text + u' \u2713'
@end example


Added in version 3.5.2.



バージョン 3.11 で非推奨: Python 2 is no longer supported, and most type checkers also no longer
support type checking Python 2 code. Removal of the alias is not
currently planned, but users are encouraged to use
@ref{169,,str} instead of @code{Text}.

@end deffn
@anchor{library/typing abstract-base-classes}@anchor{452e}
@node Aliases to container ABCs in collections abc,Aliases to asynchronous ABCs in collections abc,Aliases to other concrete types,非推奨のエイリアス
@anchor{library/typing aliases-to-container-abcs-in-collections-abc}@anchor{452f}@anchor{library/typing corresponding-to-collections-in-collections-abc}@anchor{4530}
@subsubsection Aliases to container ABCs in @code{collections.abc}


@geindex AbstractSet (typing のクラス)
@anchor{library/typing typing AbstractSet}@anchor{4531}
@deffn {クラス} typing.AbstractSet (Collection[T_co])

@ref{26a6,,collections.abc.Set} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26a6,,collections.abc.Set} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex ByteString (typing のクラス)
@anchor{library/typing typing ByteString}@anchor{345}
@deffn {クラス} typing.ByteString (Sequence[int])

Deprecated alias to @ref{342,,collections.abc.ByteString}.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use in
type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview} were
also never understood as subtypes of @code{ByteString} (either at runtime
or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.


Deprecated since version 3.9, will be removed in version 3.17.

@end deffn

@geindex Collection (typing のクラス)
@anchor{library/typing typing Collection}@anchor{eef}
@deffn {クラス} typing.Collection (Sized, Iterable[T_co], Container[T_co])

@ref{e84,,collections.abc.Collection} の非推奨なエイリアス。


Added in version 3.6.



バージョン 3.9 で非推奨: @ref{e84,,collections.abc.Collection} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Container (typing のクラス)
@anchor{library/typing typing Container}@anchor{4532}
@deffn {クラス} typing.Container (Generic[T_co])

@ref{26b0,,collections.abc.Container} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26b0,,collections.abc.Container} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex ItemsView (typing のクラス)
@anchor{library/typing typing ItemsView}@anchor{4533}
@deffn {クラス} typing.ItemsView (MappingView, AbstractSet[tuple[KT_co, VT_co]])

@ref{26b4,,collections.abc.ItemsView} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26b4,,collections.abc.ItemsView} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex KeysView (typing のクラス)
@anchor{library/typing typing KeysView}@anchor{4534}
@deffn {クラス} typing.KeysView (MappingView, AbstractSet[KT_co])

@ref{26b3,,collections.abc.KeysView} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26b3,,collections.abc.KeysView} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Mapping (typing のクラス)
@anchor{library/typing typing Mapping}@anchor{4535}
@deffn {クラス} typing.Mapping (Collection[KT], Generic[KT, VT_co])

@ref{ac7,,collections.abc.Mapping} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{ac7,,collections.abc.Mapping} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex MappingView (typing のクラス)
@anchor{library/typing typing MappingView}@anchor{4536}
@deffn {クラス} typing.MappingView (Sized)

@ref{26b2,,collections.abc.MappingView} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26b2,,collections.abc.MappingView} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex MutableMapping (typing のクラス)
@anchor{library/typing typing MutableMapping}@anchor{4537}
@deffn {クラス} typing.MutableMapping (Mapping[KT, VT])

@ref{12c0,,collections.abc.MutableMapping} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{12c0,,collections.abc.MutableMapping} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex MutableSequence (typing のクラス)
@anchor{library/typing typing MutableSequence}@anchor{4538}
@deffn {クラス} typing.MutableSequence (Sequence[T])

@ref{4bf,,collections.abc.MutableSequence} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{4bf,,collections.abc.MutableSequence} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex MutableSet (typing のクラス)
@anchor{library/typing typing MutableSet}@anchor{4539}
@deffn {クラス} typing.MutableSet (AbstractSet[T])

@ref{26b1,,collections.abc.MutableSet} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26b1,,collections.abc.MutableSet} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Sequence (typing のクラス)
@anchor{library/typing typing Sequence}@anchor{453a}
@deffn {クラス} typing.Sequence (Reversible[T_co], Collection[T_co])

@ref{13dc,,collections.abc.Sequence} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{13dc,,collections.abc.Sequence} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex ValuesView (typing のクラス)
@anchor{library/typing typing ValuesView}@anchor{453b}
@deffn {クラス} typing.ValuesView (MappingView, Collection[_VT_co])

@ref{26b5,,collections.abc.ValuesView} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26b5,,collections.abc.ValuesView} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@node Aliases to asynchronous ABCs in collections abc,Aliases to other ABCs in collections abc,Aliases to container ABCs in collections abc,非推奨のエイリアス
@anchor{library/typing aliases-to-asynchronous-abcs-in-collections-abc}@anchor{453c}@anchor{library/typing asynchronous-programming}@anchor{453d}
@subsubsection Aliases to asynchronous ABCs in @code{collections.abc}


@geindex Coroutine (typing のクラス)
@anchor{library/typing typing Coroutine}@anchor{1d31}
@deffn {クラス} typing.Coroutine (Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType])

@ref{fdd,,collections.abc.Coroutine} の非推奨なエイリアス。

See @ref{299c,,Annotating generators and coroutines}
for details on using @ref{fdd,,collections.abc.Coroutine}
and @code{typing.Coroutine} in type annotations.


Added in version 3.5.3.



バージョン 3.9 で非推奨: @ref{fdd,,collections.abc.Coroutine} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex AsyncGenerator (typing のクラス)
@anchor{library/typing typing AsyncGenerator}@anchor{19a3}
@deffn {クラス} typing.AsyncGenerator (AsyncIterator[YieldType], Generic[YieldType, SendType])

@ref{e87,,collections.abc.AsyncGenerator} の非推奨なエイリアス。

See @ref{299c,,Annotating generators and coroutines}
for details on using @ref{e87,,collections.abc.AsyncGenerator}
and @code{typing.AsyncGenerator} in type annotations.


Added in version 3.6.1.



バージョン 3.9 で非推奨: @ref{e87,,collections.abc.AsyncGenerator} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。



バージョン 3.13 で変更: The @code{SendType} parameter now has a default.

@end deffn

@geindex AsyncIterable (typing のクラス)
@anchor{library/typing typing AsyncIterable}@anchor{453e}
@deffn {クラス} typing.AsyncIterable (Generic[T_co])

@ref{fdf,,collections.abc.AsyncIterable} の非推奨なエイリアス。


Added in version 3.5.2.



バージョン 3.9 で非推奨: @ref{fdf,,collections.abc.AsyncIterable} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex AsyncIterator (typing のクラス)
@anchor{library/typing typing AsyncIterator}@anchor{453f}
@deffn {クラス} typing.AsyncIterator (AsyncIterable[T_co])

@ref{fde,,collections.abc.AsyncIterator} の非推奨なエイリアス。


Added in version 3.5.2.



バージョン 3.9 で非推奨: @ref{fde,,collections.abc.AsyncIterator} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Awaitable (typing のクラス)
@anchor{library/typing typing Awaitable}@anchor{4540}
@deffn {クラス} typing.Awaitable (Generic[T_co])

@ref{fdc,,collections.abc.Awaitable} の非推奨なエイリアス。


Added in version 3.5.2.



バージョン 3.9 で非推奨: @ref{fdc,,collections.abc.Awaitable} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@node Aliases to other ABCs in collections abc,Aliases to contextlib ABCs,Aliases to asynchronous ABCs in collections abc,非推奨のエイリアス
@anchor{library/typing aliases-to-other-abcs-in-collections-abc}@anchor{4541}@anchor{library/typing corresponding-to-other-types-in-collections-abc}@anchor{4542}
@subsubsection Aliases to other ABCs in @code{collections.abc}


@geindex Iterable (typing のクラス)
@anchor{library/typing typing Iterable}@anchor{4543}
@deffn {クラス} typing.Iterable (Generic[T_co])

@ref{26ae,,collections.abc.Iterable} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26ae,,collections.abc.Iterable} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Iterator (typing のクラス)
@anchor{library/typing typing Iterator}@anchor{4544}
@deffn {クラス} typing.Iterator (Iterable[T_co])

@ref{26af,,collections.abc.Iterator} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{26af,,collections.abc.Iterator} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Callable (typing モジュール)
@anchor{library/typing typing Callable}@anchor{9c8}
@deffn {データ} typing.Callable

@ref{9eb,,collections.abc.Callable} の非推奨なエイリアス。

See @ref{26cf,,呼び出し可能オブジェクトのアノテーション} for details on how to use
@ref{9eb,,collections.abc.Callable} and @code{typing.Callable} in type annotations.


バージョン 3.9 で非推奨: @ref{9eb,,collections.abc.Callable} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。



バージョン 3.10 で変更: @code{Callable} は @ref{487,,ParamSpec} と @ref{9c7,,Concatenate} をサポートしました。詳細は 
@geindex Python Enhancement Proposals; PEP 612
PEP 612@footnote{https://peps.python.org/pep-0612/} を参照してください。

@end deffn

@geindex Generator (typing のクラス)
@anchor{library/typing typing Generator}@anchor{19a2}
@deffn {クラス} typing.Generator (Iterator[YieldType], Generic[YieldType, SendType, ReturnType])

@ref{fdb,,collections.abc.Generator} の非推奨なエイリアス。

See @ref{299c,,Annotating generators and coroutines}
for details on using @ref{fdb,,collections.abc.Generator}
and @code{typing.Generator} in type annotations.


バージョン 3.9 で非推奨: @ref{fdb,,collections.abc.Generator} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。



バージョン 3.13 で変更: Default values for the send and return types were added.

@end deffn

@geindex Hashable (typing のクラス)
@anchor{library/typing typing Hashable}@anchor{717}
@deffn {クラス} typing.Hashable

@ref{719,,collections.abc.Hashable} の非推奨なエイリアス。


バージョン 3.12 で非推奨: 代わりに @ref{719,,collections.abc.Hashable} を直接使用してください。

@end deffn

@geindex Reversible (typing のクラス)
@anchor{library/typing typing Reversible}@anchor{4545}
@deffn {クラス} typing.Reversible (Iterable[T_co])

@ref{e85,,collections.abc.Reversible} の非推奨なエイリアス。


バージョン 3.9 で非推奨: @ref{e85,,collections.abc.Reversible} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。

@end deffn

@geindex Sized (typing のクラス)
@anchor{library/typing typing Sized}@anchor{718}
@deffn {クラス} typing.Sized

@ref{71a,,collections.abc.Sized} の非推奨なエイリアス。


バージョン 3.12 で非推奨: 代わりに @ref{71a,,collections.abc.Sized} を直接使用してください。

@end deffn

@node Aliases to contextlib ABCs,,Aliases to other ABCs in collections abc,非推奨のエイリアス
@anchor{library/typing aliases-to-contextlib-abcs}@anchor{4546}@anchor{library/typing context-manager-types}@anchor{4547}
@subsubsection Aliases to @code{contextlib} ABCs


@geindex ContextManager (typing のクラス)
@anchor{library/typing typing ContextManager}@anchor{e8b}
@deffn {クラス} typing.ContextManager (Generic[T_co, ExitT_co])

@ref{e8a,,contextlib.AbstractContextManager} の非推奨なエイリアス。

The first type parameter, @code{T_co}, represents the type returned by
the @ref{7e4,,__enter__()} method. The optional second type parameter, @code{ExitT_co},
which defaults to @code{bool | None}, represents the type returned by the
@ref{1518,,__exit__()} method.


Added in version 3.5.4.



バージョン 3.9 で非推奨: @ref{e8a,,contextlib.AbstractContextManager} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。



バージョン 3.13 で変更: Added the optional second type parameter, @code{ExitT_co}.

@end deffn

@geindex AsyncContextManager (typing のクラス)
@anchor{library/typing typing AsyncContextManager}@anchor{19a0}
@deffn {クラス} typing.AsyncContextManager (Generic[T_co, AExitT_co])

@ref{d20,,contextlib.AbstractAsyncContextManager} の非推奨なエイリアス。

The first type parameter, @code{T_co}, represents the type returned by
the @ref{241d,,__aenter__()} method. The optional second type parameter, @code{AExitT_co},
which defaults to @code{bool | None}, represents the type returned by the
@ref{19a1,,__aexit__()} method.


Added in version 3.6.2.



バージョン 3.9 で非推奨: @ref{d20,,contextlib.AbstractAsyncContextManager} は添字表記 (@code{[]}) をサポートするようになりました。
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/} と @ref{8c1,,ジェネリックエイリアス型} を参照してください。



バージョン 3.13 で変更: Added the optional second type parameter, @code{AExitT_co}.

@end deffn

@node メジャーな機能の非推奨時系列,,モジュールの内容<3>,typing --- Support for type hints
@anchor{library/typing deprecation-timeline-of-major-features}@anchor{4548}
@subsubsection メジャーな機能の非推奨時系列


@code{typing} の機能の中には非推奨のものがあり、Python の将来のバージョンで削除される可能性があります。以下の表は主な非推奨機能をまとめたものです。これは変更される可能性があり、すべての非推奨機能がリストされているわけではありません。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

機能

@tab

非推奨となるバージョン

@tab

削除予定のバージョン

@tab

PEP/issue

@item

標準コレクションのエイリアス

@tab

3.9

@tab

未定（@ref{451b,,非推奨のエイリアス} を参照）

@tab

@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/}

@item

@ref{345,,typing.ByteString}

@tab

3.9

@tab

3.17

@tab

gh-91896@footnote{https://github.com/python/cpython/issues/91896}

@item

@ref{360,,typing.Text}

@tab

3.11

@tab

未定

@tab

gh-92332@footnote{https://github.com/python/cpython/issues/92332}

@item

@ref{717,,typing.Hashable}、@ref{718,,typing.Sized}

@tab

3.12

@tab

未定

@tab

gh-94309@footnote{https://github.com/python/cpython/issues/94309}

@item

@ref{9cc,,typing.TypeAlias}

@tab

3.12

@tab

未定

@tab

@geindex Python Enhancement Proposals; PEP 695
PEP 695@footnote{https://peps.python.org/pep-0695/}

@item

@ref{333,,@@typing.no_type_check_decorator}

@tab

3.13

@tab

3.15

@tab

gh-106309@footnote{https://github.com/python/cpython/issues/106309}

@item

@ref{5ac,,typing.AnyStr}

@tab

3.13

@tab

3.18

@tab

gh-105578@footnote{https://github.com/python/cpython/issues/105578}

@end multitable


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pydoc --- ドキュメント生成とオンラインヘルプシステム,Python 開発モード,typing --- Support for type hints,開発ツール
@anchor{library/pydoc doc}@anchor{4549}@anchor{library/pydoc module-pydoc}@anchor{ba}@anchor{library/pydoc pydoc-documentation-generator-and-online-help-system}@anchor{454a}@anchor{library/pydoc translation-repo}@anchor{454b}
@subsection @code{pydoc} --- ドキュメント生成とオンラインヘルプシステム


@geindex module; pydoc

`ソースコード:' Lib/pydoc.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pydoc.py}

@geindex documentation;generation
@geindex documentation;online
@geindex help;online


__________________________________________________________________


The @code{pydoc} module automatically generates documentation from Python
modules.  The documentation can be presented as pages of text on the console,
served to a web browser, or saved to HTML files.

For modules, classes, functions and methods, the displayed documentation is
derived from the docstring (i.e. the @ref{b21,,__doc__} attribute) of the object,
and recursively of its documentable members.  If there is no docstring,
@code{pydoc} tries to obtain a description from the block of comment lines just
above the definition of the class, function or method in the source file, or at
the top of the module (see @ref{1938,,inspect.getcomments()}).

The built-in function @ref{ad4,,help()} invokes the online help system in the
interactive interpreter, which uses @code{pydoc} to generate its documentation
as text on the console.  The same text documentation can also be viewed from
outside the Python interpreter by running @code{pydoc} as a script at the
operating system's command prompt. For example, running

@example
python -m pydoc sys
@end example

シェルから行うと @ref{df,,sys} モジュールのドキュメントを、Unix の @code{man} コマンドのような形式で表示させることができます。 @code{pydoc} の引数として与えることができるのは、関数名・モジュール名・パッケージ名、また、モジュールやパッケージ内のモジュールに含まれるクラス・メソッド・関数へのドット形式での参照です。 @code{pydoc} への引数がパスと解釈されるような場合で(オペレーティングシステムのパス区切り記号を含む場合です。例えばUnixならばスラッシュ含む場合になります)、さらに、そのパスがPythonのソースファイルを指しているなら、そのファイルに対するドキュメントが生成されます。

@cartouche
@quotation 注釈 
In order to find objects and their documentation, @code{pydoc} imports the
module(s) to be documented.  Therefore, any code on module level will be
executed on that occasion.  Use an @code{if __name__ == '__main__':} guard to
only execute code when a file is invoked as a script and not just imported.
@end quotation
@end cartouche

When printing output to the console, @code{pydoc} attempts to paginate the
output for easier reading.  If either the 
@geindex MANPAGER
@geindex 環境変数; MANPAGER
@code{MANPAGER} or the
@geindex PAGER
@geindex 環境変数; PAGER
@code{PAGER} environment variable is set, @code{pydoc} will use its
value as a pagination program. When both are set, 
@geindex MANPAGER
@geindex 環境変数; MANPAGER
@code{MANPAGER} is used.

引数の前に @code{-w} フラグを指定すると、コンソールにテキストを表示させるかわりにカレントディレクトリにHTMLドキュメントを生成します。

引数の前に @code{-k} フラグを指定すると、引数をキーワードとして利用可能な全てのモジュールの概要を検索します。検索のやりかたは、Unixの @code{man} コマンドと同様です。モジュールの概要というのは、モジュールのドキュメントの一行目のことです。

また、 @code{pydoc} を使うことでローカルマシンにウェブブラウザから閲覧可能なドキュメントを提供するHTTPサーバーを起動することもできます。 @code{python -m pydoc -p 1234} とすると、HTTPサーバーをポート1234に起動します。これで、お好きなウェブブラウザを使って @code{http://localhost:1234/} からドキュメントを見ることができます。ポート番号に @code{0} を指定すると、任意の空きポートが選択されます。

@code{python -m pydoc -n <hostname>} は、与えられたホスト名で listen するサーバーを起動します。
デフォルトではホスト名は 'localhost' ですが、他のマシンからサーバーへ疎通できるようにしたい場合は、サーバーが応答するホスト名を変更したいと思うでしょう。
開発作業中に、コンテナ内で pydoc を走らせたい場合は、これは特に便利です。

@code{python -m pydoc -b} では、サーバとして起動するとともにブラウザも起動し、モジュールインデクスページを開きます。提供されるページには、個別のヘルプページに飛ぶための `Get' ボタン、全モジュールから概要行に基くキーワード検索するための `Search' ボタン、と、`Module index', `Topics' , `Keywords' へのそれぞれリンクがついたナビゲーションバーがページの一番上に付きます。

@code{pydoc} でドキュメントを生成する場合、その時点での環境とパス情報に基づいてモジュールがどこにあるのか決定されます。そのため、 @code{pydoc spam} を実行した場合につくられるドキュメントは、 Pythonインタプリタを起動して @code{import spam} と入力したときに読み込まれるモジュールに対するドキュメントになります。

Module docs for core modules are assumed to reside in
@code{https://docs.python.org/X.Y/library/} where @code{X} and @code{Y} are the
major and minor version numbers of the Python interpreter.  This can
be overridden by setting the @code{PYTHONDOCS} environment variable
to a different URL or to a local directory containing the Library
Reference Manual pages.


バージョン 3.2 で変更: @code{-b} オプションが追加されました。



バージョン 3.3 で変更: @code{-g} コマンドラインオプションが削除されました。



バージョン 3.4 で変更: @code{pydoc} now uses @ref{22f,,inspect.signature()} rather than
@ref{941,,inspect.getfullargspec()} to extract signature information from
callables.



バージョン 3.7 で変更: @code{-n} オプションが追加されました。


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python 開発モード,doctest --- 対話型の Python の例をテストする,pydoc --- ドキュメント生成とオンラインヘルプシステム,開発ツール
@anchor{library/devmode doc}@anchor{454c}@anchor{library/devmode devmode}@anchor{508}@anchor{library/devmode python-development-mode}@anchor{454d}@anchor{library/devmode translation-repo}@anchor{454e}
@subsection Python 開発モード



Added in version 3.7.


The Python Development Mode introduces additional runtime checks that are too
expensive to be enabled by default. It should not be more verbose than the
default if the code is correct; new warnings are only emitted when an issue is
detected.

It can be enabled using the @ref{16f,,-X dev} command line option or by
setting the 
@geindex PYTHONDEVMODE
@geindex 環境変数; PYTHONDEVMODE
@ref{ce7,,PYTHONDEVMODE} environment variable to @code{1}.

See also @ref{509,,Python debug build}.

@menu
* Python 開発モードの影響:: 
* ResourceWarning の例:: 
* Bad file descriptor error example:: 

@end menu

@node Python 開発モードの影響,ResourceWarning の例,,Python 開発モード
@anchor{library/devmode effects-of-the-python-development-mode}@anchor{454f}
@subsubsection Python 開発モードの影響


Python 開発モードを有効化することは次のコマンドに似ていますが、以下で説明される追加の影響があります:

@example
PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python -W default -X faulthandler
@end example

Python 開発モードの影響:


@itemize *

@item 
@code{default} の @ref{212a,,警告フィルタ} を追加します。次の警告が表示されます:


@itemize *

@item 
@ref{1a3,,DeprecationWarning}

@item 
@ref{71e,,ImportWarning}

@item 
@ref{ac5,,PendingDeprecationWarning}

@item 
@ref{54c,,ResourceWarning}
@end itemize

通常、上記の警告は デフォルトの @ref{212a,,警告フィルタ} によりフィルタリングされます。

It behaves as if the @ref{ac6,,-W default} command line option is used.

Use the @ref{ac6,,-W error} command line option or set the
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} environment variable to @code{error} to treat warnings
as errors.

@item 
Install debug hooks on memory allocators to check for:


@itemize *

@item 
Buffer underflow

@item 
Buffer overflow

@item 
Memory allocator API violation

@item 
Unsafe usage of the GIL
@end itemize

See the @ref{e64,,PyMem_SetupDebugHooks()} C function.

It behaves as if the 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable is set to
@code{debug}.

To enable the Python Development Mode without installing debug hooks on
memory allocators, set the 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable to
@code{default}.

@item 
Call @ref{20f,,faulthandler.enable()} at Python startup to install handlers for
the @ref{128c,,SIGSEGV}, @ref{128d,,SIGFPE},
@ref{128e,,SIGABRT}, @ref{128f,,SIGBUS} and
@ref{1290,,SIGILL} signals to dump the Python traceback on a crash.

It behaves as if the @ref{16f,,-X faulthandler} command line option is
used or if the 
@geindex PYTHONFAULTHANDLER
@geindex 環境変数; PYTHONFAULTHANDLER
@ref{1291,,PYTHONFAULTHANDLER} environment variable is set to
@code{1}.

@item 
Enable @ref{213a,,asyncio debug mode}. For example,
@ref{b,,asyncio} checks for coroutines that were not awaited and logs them.

It behaves as if the 
@geindex PYTHONASYNCIODEBUG
@geindex 環境変数; PYTHONASYNCIODEBUG
@ref{2139,,PYTHONASYNCIODEBUG} environment variable is set
to @code{1}.

@item 
Check the `encoding' and `errors' arguments for string encoding and decoding
operations. Examples: @ref{316,,open()}, @ref{ad2,,str.encode()} and
@ref{ad3,,bytes.decode()}.

By default, for best performance, the `errors' argument is only checked at
the first encoding/decoding error and the `encoding' argument is sometimes
ignored for empty strings.

@item 
The @ref{505,,io.IOBase} destructor logs @code{close()} exceptions.

@item 
Set the @ref{1e82,,dev_mode} attribute of @ref{89c,,sys.flags} to
@code{True}.
@end itemize

The Python Development Mode does not enable the @ref{105,,tracemalloc} module by
default, because the overhead cost (to performance and memory) would be too
large. Enabling the @ref{105,,tracemalloc} module provides additional information
on the origin of some errors. For example, @ref{54c,,ResourceWarning} logs the
traceback where the resource was allocated, and a buffer overflow error logs
the traceback where the memory block was allocated.

The Python Development Mode does not prevent the @ref{18c,,-O} command line
option from removing @ref{b60,,assert} statements nor from setting
@ref{9da,,__debug__} to @code{False}.

The Python Development Mode can only be enabled at the Python startup. Its
value can be read from @ref{89c,,sys.flags.dev_mode}.


バージョン 3.8 で変更: The @ref{505,,io.IOBase} destructor now logs @code{close()} exceptions.



バージョン 3.9 で変更: The `encoding' and `errors' arguments are now checked for string encoding
and decoding operations.


@node ResourceWarning の例,Bad file descriptor error example,Python 開発モードの影響,Python 開発モード
@anchor{library/devmode resourcewarning-example}@anchor{4550}
@subsubsection ResourceWarning の例


Example of a script counting the number of lines of the text file specified in
the command line:

@example
import sys

def main():
    fp = open(sys.argv[1])
    nlines = len(fp.readlines())
    print(nlines)
    # ファイルは暗黙的に閉じられる

if __name__ == "__main__":
    main()
@end example

The script does not close the file explicitly. By default, Python does not emit
any warning. Example using README.txt, which has 269 lines:

@example
$ python script.py README.txt
269
@end example

Enabling the Python Development Mode displays a @ref{54c,,ResourceWarning} warning:

@example
$ python -X dev script.py README.txt
269
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
@end example

In addition, enabling @ref{105,,tracemalloc} shows the line where the file was
opened:

@example
$ python -X dev -X tracemalloc=5 script.py README.rst
269
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'>
  main()
Object allocated at (most recent call last):
  File "script.py", lineno 10
    main()
  File "script.py", lineno 4
    fp = open(sys.argv[1])
@end example

The fix is to close explicitly the file. Example using a context manager:

@example
def main():
    # ブロックを終了する際に明示的にファイルを閉じる
    with open(sys.argv[1]) as fp:
        nlines = len(fp.readlines())
    print(nlines)
@end example

Not closing a resource explicitly can leave a resource open for way longer than
expected; it can cause severe issues upon exiting Python. It is bad in
CPython, but it is even worse in PyPy. Closing resources explicitly makes an
application more deterministic and more reliable.

@node Bad file descriptor error example,,ResourceWarning の例,Python 開発モード
@anchor{library/devmode bad-file-descriptor-error-example}@anchor{4551}
@subsubsection Bad file descriptor error example


Script displaying the first line of itself:

@example
import os

def main():
    fp = open(__file__)
    firstline = fp.readline()
    print(firstline.rstrip())
    os.close(fp.fileno())
    # ファイルは暗黙的に閉じられる

main()
@end example

By default, Python does not emit any warning:

@example
$ python script.py
import os
@end example

The Python Development Mode shows a @ref{54c,,ResourceWarning} and logs a "Bad file
descriptor" error when finalizing the file object:

@example
$ python -X dev script.py
import os
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'>
Traceback (most recent call last):
  File "script.py", line 10, in <module>
    main()
OSError: [Errno 9] Bad file descriptor
@end example

@code{os.close(fp.fileno())} closes the file descriptor. When the file object
finalizer tries to close the file descriptor again, it fails with the @code{Bad
file descriptor} error. A file descriptor must be closed only once. In the
worst case scenario, closing it twice can lead to a crash (see bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748}
for an example).

The fix is to remove the @code{os.close(fp.fileno())} line, or open the file with
@code{closefd=False}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node doctest --- 対話型の Python の例をテストする,unittest --- ユニットテストフレームワーク,Python 開発モード,開発ツール
@anchor{library/doctest doc}@anchor{4552}@anchor{library/doctest doctest-test-interactive-python-examples}@anchor{4553}@anchor{library/doctest module-doctest}@anchor{3e}@anchor{library/doctest translation-repo}@anchor{4554}
@subsection @code{doctest} --- 対話型の Python の例をテストする


@geindex module; doctest

`ソースコード:' Lib/doctest.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/doctest.py}


__________________________________________________________________


The @code{doctest} module searches for pieces of text that look like interactive
Python sessions, and then executes those sessions to verify that they work
exactly as shown.  There are several common ways to use doctest:


@itemize *

@item 
モジュールの docstring (ドキュメンテーション文字列) 中にある対話実行例のすべてが書かれている通りに動作するか検証することで、docstring の内容が最新かどうかチェックする。

@item 
テストファイルやテストオブジェクト中の対話実行例が期待通りに動作するかを検証することで、回帰テストを実現します。

@item 
入出力例を豊富に使ったパッケージのチュートリアルドキュメントが書けます。入出力例と解説文のどちらに注目するかによって、ドキュメントは「読めるテスト」にも「実行できるドキュメント」にもなります。
@end itemize

以下に完全かつ短い実行例を示します:

@example
"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    >>> factorial(30.0)
    265252859812191058636308480000000

    It must also not be ridiculously large:
    >>> factorial(1e100)
    Traceback (most recent call last):
        ...
    OverflowError: n too large
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result


if __name__ == "__main__":
    import doctest
    doctest.testmod()
@end example

If you run @code{example.py} directly from the command line, @code{doctest}
works its magic:

@example
$ python example.py
$
@end example

There's no output!  That's normal, and it means all the examples worked.  Pass
@code{-v} to the script, and @code{doctest} prints a detailed log of what
it's trying, and prints a summary at the end:

@example
$ python example.py -v
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok
@end example

といった具合で、最後には:

@example
Trying:
    factorial(1e100)
Expecting:
    Traceback (most recent call last):
        ...
    OverflowError: n too large
ok
2 items passed all tests:
   1 test in __main__
   6 tests in __main__.factorial
7 tests in 2 items.
7 passed.
Test passed.
$
@end example

That's all you need to know to start making productive use of @code{doctest}!
Jump in.  The following sections provide full details.  Note that there are many
examples of doctests in the standard Python test suite and libraries.
Especially useful examples can be found in the standard test file
@code{Lib/test/test_doctest/test_doctest.py}.


Added in version 3.13: Output is colorized by default and can be
@ref{1b7,,controlled using environment variables}.


@menu
* 簡単な利用法; docstring 中の実行例をチェックする: 簡単な利用法 docstring 中の実行例をチェックする. 
* 簡単な利用法; テキストファイル中の実行例をチェックする: 簡単な利用法 テキストファイル中の実行例をチェックする. 
* コマンドラインでの使用: コマンドラインでの使用<6>. 
* doctest のからくり:: 
* 基本 API:: 
* 単体テスト API:: 
* 拡張 API:: 
* デバッグ:: 
* アドバイス:: 

@end menu

@node 簡単な利用法 docstring 中の実行例をチェックする,簡単な利用法 テキストファイル中の実行例をチェックする,,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest doctest-simple-testmod}@anchor{4555}@anchor{library/doctest simple-usage-checking-examples-in-docstrings}@anchor{4556}
@subsubsection 簡単な利用法: docstring 中の実行例をチェックする


doctest を試す簡単な方法 (とはいえ、いつもそうする必要はないのですが) は、各モジュール @code{M} の最後を、以下のようにして締めくくることです:

@example
if __name__ == "__main__":
    import doctest
    doctest.testmod()
@end example

こうすると、 @code{doctest} は @code{M} 中の docstring を検査します。

モジュールをスクリプトとして実行すると、docstring 中の実行例が実行され、検証されます:

@example
python M.py
@end example

docstring に書かれた実行例の実行が失敗しない限り、何も表示されません。失敗すると、失敗した実行例と、その原因が (場合によっては複数) 標準出力に印字され、最後に @code{***Test Failed*** N failures.} という行を出力します。ここで、`N' は失敗した実行例の数です。

一方、@code{-v} スイッチをつけて走らせると:

@example
python M.py -v
@end example

実行を試みたすべての実行例について詳細に報告し、最後に各種まとめを行った内容が標準出力に印字されます。

@code{verbose=True} を @ref{1686,,testmod()} に渡せば、詳細報告 (verbose) モードを強制できます。また、 @code{verbose=False} にすれば禁止できます。どちらの場合にも、 @ref{1686,,testmod()} は @ref{147c,,sys.argv} 上のスイッチを調べません。(したがって、 @code{-v} をつけても効果はありません)。

There is also a command line shortcut for running @ref{1686,,testmod()}, see section
@ref{4557,,コマンドラインでの使用}.

@ref{1686,,testmod()} の詳しい情報は @ref{4558,,基本 API} 節を参照してください。

@node 簡単な利用法 テキストファイル中の実行例をチェックする,コマンドラインでの使用<6>,簡単な利用法 docstring 中の実行例をチェックする,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest doctest-simple-testfile}@anchor{4559}@anchor{library/doctest simple-usage-checking-examples-in-a-text-file}@anchor{455a}
@subsubsection 簡単な利用法: テキストファイル中の実行例をチェックする


doctest のもう一つの簡単な用途は、テキストファイル中にある対話実行例に対するテストです。これには @ref{455b,,testfile()} 関数を使います:

@example
import doctest
doctest.testfile("example.txt")
@end example

この短いスクリプトは、 @code{example.txt} というファイルの中に入っている対話モードの Python 操作例すべてを実行して、その内容を検証します。ファイルの内容は一つの巨大な docstring であるかのように扱われます; ファイルが Python プログラムである必要はありません！例えば、 @code{example.txt} には以下のような内容が入っているとします:

@example
The `@w{`}example`@w{`} module
======================

Using `@w{`}factorial`@w{`}
-------------------

This is an example text file in reStructuredText format.  First import
`@w{`}factorial`@w{`} from the `@w{`}example`@w{`} module:

    >>> from example import factorial

Now use it:

    >>> factorial(6)
    120
@end example

@code{doctest.testfile("example.txt")} を実行すると、このドキュメント内のエラーを見つけ出します:

@example
File "./example.txt", line 14, in example.txt
Failed example:
    factorial(6)
Expected:
    120
Got:
    720
@end example

@ref{1686,,testmod()} と同じく、 @ref{455b,,testfile()} は実行例が失敗しない限り何も表示しません。実行例が失敗すると、失敗した実行例とその原因が (場合によっては複数) @code{testmod()} と同じ書式で標準出力に書き出されます。

デフォルトでは、 @ref{455b,,testfile()} は自分自身を呼び出したモジュールのあるディレクトリを探します。その他の場所にあるファイルを見に行くように @ref{455b,,testfile()} に指示するためのオプション引数についての説明は @ref{4558,,基本 API} 節を参照してください。

@ref{1686,,testmod()} と同様に @ref{455b,,testfile()} の冗長性 (verbosity) はコマンドラインスイッチ @code{-v} またはオプションのキーワード引数 `verbose' によって指定できます。

There is also a command line shortcut for running @ref{455b,,testfile()}, see section
@ref{4557,,コマンドラインでの使用}.

@ref{455b,,testfile()} の詳細は @ref{4558,,基本 API} 節を参照してください。

@node コマンドラインでの使用<6>,doctest のからくり,簡単な利用法 テキストファイル中の実行例をチェックする,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest command-line-usage}@anchor{455c}@anchor{library/doctest doctest-cli}@anchor{4557}
@subsubsection コマンドラインでの使用


The @code{doctest} module can be invoked as a script from the command line:

@example
python -m doctest [-v] [-o OPTION] [-f] file [file ...]
@end example

@geindex doctest コマンドラインオプション; -v
@geindex doctest コマンドラインオプション; --verbose
@anchor{library/doctest cmdoption-doctest-v}@anchor{455d}@anchor{library/doctest cmdoption-doctest-verbose}@anchor{455e}
@deffn {Option} @w{-}v, @w{-}@w{-}verbose

Detailed report of all examples tried is printed to standard output,
along with assorted summaries at the end:

@example
python -m doctest -v example.py
@end example

こうすると @code{example.py} を単体モジュールとしてインポートして、それに対して @ref{1686,,testmod()} を実行します。このファイルがパッケージの一部で他のサブモジュールをそのパッケージからインポートしている場合はうまく動かないことに注意してください。

If the file name does not end with @code{.py}, @code{doctest} infers
that it must be run with @ref{455b,,testfile()} instead:

@example
python -m doctest -v example.txt
@end example
@end deffn

@geindex doctest コマンドラインオプション; -o
@geindex doctest コマンドラインオプション; --option
@anchor{library/doctest cmdoption-doctest-o}@anchor{455f}@anchor{library/doctest cmdoption-doctest-option}@anchor{4560}
@deffn {Option} @w{-}o, @w{-}@w{-}option <option>

Option flags control various aspects of doctest's behavior, see section
@ref{1134,,オプションフラグ}.


Added in version 3.4.

@end deffn

@geindex doctest コマンドラインオプション; -f
@geindex doctest コマンドラインオプション; --fail-fast
@anchor{library/doctest cmdoption-doctest-f}@anchor{4561}@anchor{library/doctest cmdoption-doctest-fail-fast}@anchor{4562}
@deffn {Option} @w{-}f, @w{-}@w{-}fail@w{-}fast

This is shorthand for @code{-o FAIL_FAST}.


Added in version 3.4.

@end deffn

@node doctest のからくり,基本 API,コマンドラインでの使用<6>,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest doctest-how-it-works}@anchor{4563}@anchor{library/doctest how-it-works}@anchor{4564}
@subsubsection doctest のからくり


この節では、doctest のからくり: どの docstring を見に行くのか、どのように対話実行例を見つけ出すのか、どんな実行コンテキストを使うのか、例外をどう扱うか、上記の振る舞いを制御するためにどのようなオプションフラグを使うか、について詳しく吟味します。こうした情報は、doctest に対応した実行例を書くために必要な知識です; 書いた実行例に対して実際に doctest を実行する上で必要な情報については後続の節を参照してください。

@menu
* どの docstring が検証されるのか?:: 
* docstring 内の実行例をどのように認識するのか?:: 
* 実行コンテキストとは何か?:: 
* 例外はどう扱えばよいか?:: 
* オプションフラグ:: 
* ディレクティブ (Directives): ディレクティブ Directives. 
* 警告: 警告<2>. 

@end menu

@node どの docstring が検証されるのか?,docstring 内の実行例をどのように認識するのか?,,doctest のからくり
@anchor{library/doctest doctest-which-docstrings}@anchor{4565}@anchor{library/doctest which-docstrings-are-examined}@anchor{4566}
@subsubsection どの docstring が検証されるのか?


モジュールの docstring と、すべての関数、クラスおよびメソッドの docstring が検索されます。モジュールに import されたオブジェクトは検索されません。

@geindex __test__ (module の属性)
@anchor{library/doctest module __test__}@anchor{4567}
In addition, there are cases when you want tests to be part of a module but not part
of the help text, which requires that the tests not be included in the docstring.
Doctest looks for a module-level variable called @code{__test__} and uses it to locate other
tests. If @code{M.__test__} exists, it must be a dict, and each
entry maps a (string) name to a function object, class object, or string.
Function and class object docstrings found from @code{M.__test__} are searched, and
strings are treated as if they were docstrings.  In output, a key @code{K} in
@code{M.__test__} appears with name @code{M.__test__.K}.

For example, place this block of code at the top of @code{example.py}:

@example
__test__ = @{
    'numbers': """
>>> factorial(6)
720

>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
"""
@}
@end example

The value of @code{example.__test__["numbers"]} will be treated as a
docstring and all the tests inside it will be run. It is
important to note that the value can be mapped to a function,
class object, or module; if so, @code{doctest}
searches them recursively for docstrings, which are then scanned for tests.

検索中に見つかったクラスも同様に再帰的に検索が行われ、クラスに含まれているメソッドおよびネストされたクラスについて docstring のテストが行われます。

@cartouche
@quotation 注釈 
@code{doctest} can only automatically discover classes and functions that are
defined at the module level or inside other classes.

Since nested classes and functions only exist when an outer function
is called, they cannot be discovered. Define them outside to make them visible.
@end quotation
@end cartouche

@node docstring 内の実行例をどのように認識するのか?,実行コンテキストとは何か?,どの docstring が検証されるのか?,doctest のからくり
@anchor{library/doctest doctest-finding-examples}@anchor{4568}@anchor{library/doctest how-are-docstring-examples-recognized}@anchor{4569}
@subsubsection docstring 内の実行例をどのように認識するのか?


ほとんどの場合、対話コンソールセッション上でのコピー／ペーストはうまく動作します。とはいえ、@ref{3e,,doctest} は特定の Python シェルの振る舞いを正確にエミュレーションしようとするわけではありません。

@example
>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
...     print("yes")
... else:
...     print("no")
...     print("NO")
...     print("NO!!!")
...
no
NO
NO!!!
>>>
@end example

@geindex >>>;interpreter prompt
@geindex ...;interpreter prompt

コードを含む最後の @code{'>>> '} または @code{'... '} 行の直下に期待する出力結果が置かれます。(出力結果がもしあれば) それは次の @code{'>>> '} 行か、すべて空白文字の行まで続きます。

詳細事項:


@itemize *

@item 
期待する出力結果には、空白だけの行が入っていてはなりません。そのような行は期待する出力結果の終了を表すと見なされるからです。もし期待する出力結果の内容に空白行が入っている場合には、空白行が入るべき場所すべてに @code{<BLANKLINE>} を入れてください。

@item 
全てのタブ文字は 8 カラムのタブ位置でスペースに展開されます。テスト対象のコードが作成した出力にあるタブは変更されません。出力例にあるどんなタブも展開 `される' ので、コードの出力がハードタブを含んでいた場合、 doctest が通るには @ref{456a,,NORMALIZE_WHITESPACE} オプションか @ref{456b,,directive} を有効にするしかありません。そうする代わりに、テストが出力を読み取りテストの一部として期待される値と正しく比較するように、テストを書き直すこともできます。このソース中のタブの扱いは試行錯誤の結果であり、タブの扱いの中で最も問題の起きにくいものだということが分かっています。タブの扱いについては、独自の @ref{456c,,DocTestParser} クラスを実装して、別のアルゴリズムを使うこともできます。

@item 
標準出力への出力は取り込まれますが、標準エラーは取り込まれません (例外発生時のトレースバックは別の方法で取り込まれます)。

@item 
対話セッションにおいて、バックスラッシュを用いて次の行に続ける場合や、その他の理由でバックスラッシュを用いる場合、raw docstring を使ってバックスラッシュを入力どおりに扱わせるようにしなければなりません:

@example
>>> def f(x):
...     r'@w{'}'Backslashes in a raw docstring: m\n'@w{'}'
...
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
@end example

そうしない場合は、バックスラッシュは文字列の一部として解釈されます。例えば、上の @code{\n} は改行文字として解釈されてしまいます。それ以外の方法では、doctest にあるバックスラッシュを二重にする (そして raw string を使わない) という方法もあります:

@example
>>> def f(x):
...     '@w{'}'Backslashes in a raw docstring: m\\n'@w{'}'
...
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
@end example

@item 
開始カラムはどこでもかまいません:

@example
>>> assert "Easy!"
      >>> import math
          >>> math.floor(1.9)
          1
@end example

期待する出力結果の先頭部にある空白文字列は、実行例の開始部分にあたる @code{'>>> '} 行の先頭にある空白文字列と同じだけ取り除かれます。
@end itemize

@node 実行コンテキストとは何か?,例外はどう扱えばよいか?,docstring 内の実行例をどのように認識するのか?,doctest のからくり
@anchor{library/doctest doctest-execution-context}@anchor{456d}@anchor{library/doctest what-s-the-execution-context}@anchor{456e}
@subsubsection 実行コンテキストとは何か?


By default, each time @code{doctest} finds a docstring to test, it uses a
`shallow copy' of @code{M}'s globals, so that running tests doesn't change the
module's real globals, and so that one test in @code{M} can't leave behind
crumbs that accidentally allow another test to work.  This means examples can
freely use any names defined at top-level in @code{M}, and names defined earlier
in the docstring being run. Examples cannot see names defined in other
docstrings.

@ref{1686,,testmod()} や @ref{455b,,testfile()} に @code{globs=your_dict} を渡し、自前の辞書を実行コンテキストとして使うこともできます。

@node 例外はどう扱えばよいか?,オプションフラグ,実行コンテキストとは何か?,doctest のからくり
@anchor{library/doctest doctest-exceptions}@anchor{456f}@anchor{library/doctest what-about-exceptions}@anchor{4570}
@subsubsection 例外はどう扱えばよいか?


トレースバックが実行例によって生成される唯一の出力なら問題ありません。単にトレースバックを貼り付けてください。@footnote{
期待する出力結果と例外の両方を含んだ例はサポートされていません。一方の終わりと他方の始まりを見分けようとするのはエラーの元になりがちですし、解りにくいテストになってしまいます。
} トレースバックには、頻繁に変更されがちな情報 (例えばファイルパスや行番号など) が入っているものなので、これは受け入れるテスト結果に柔軟性を持たせようと doctest が苦労している部分の一つです。

簡単な例を示しましょう:

@example
>>> [1, 2, 3].remove(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
@end example

この doctest は、 @ref{2ec,,ValueError} が送出され、その詳細情報が @code{list.remove(x): x not in list} である場合に成功します。

例外が発生したときの期待する出力はトレースバックヘッダから始まっていなければなりません。トレースバックの形式は以下の二通りの行のいずれかで、実行例の最初の行と同じインデントでなければりません:

@example
Traceback (most recent call last):
Traceback (innermost last):
@end example

トレースバックヘッダの後ろにトレースバックスタックが続いてもかまいませんが、doctest はその内容を無視します。普通はトレースバックスタックを省略するか、対話セッションからそのままコピーしてきます。

トレースバックスタックの後ろにはもっとも有意義な部分、例外の型と詳細情報の入った行があります。これは通常トレースバックの最後の行ですが、例外が複数行の詳細情報を持っている場合、複数の行にわたることもあります:

@example
>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: multi
    line
detail
@end example

上の例では、最後の 3 行 (@ref{2ec,,ValueError} から始まる行) における例外の型と詳細情報だけが比較され、それ以外の部分は無視されます。

例外を扱うコツは、実行例をドキュメントとして読む上で明らかに価値のある情報でない限り、トレースバックスタックは省略する、ということです。したがって、先ほどの例は以下のように書くべきでしょう:

@example
>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
    ...
ValueError: multi
    line
detail
@end example

トレースバックの扱いは非常に特殊なので注意してください。特に、上の書き直した実行例では、 @code{...} の扱いは doctest の @ref{1687,,ELLIPSIS} オプションとは独立しています。この例での省略記号は何かの省略を表しているかもしれませんし、コンマや数字が 3 個 (または 300 個) かもしれませんし、 Monty Python のスキットをインデントして書き写したものかもしれません。

以下の詳細はずっと覚えておく必要はないのですが、一度目を通しておいてください:


@itemize *

@item 
doctest は期待する出力の出所が print 文なのか例外なのかを推測できません。したがって、例えば期待する出力が @code{ValueError: 42 is prime} であるような実行例は、 @ref{2ec,,ValueError} が実際に送出された場合と、万が一期待する出力と同じ文字列を print した場合の両方で成功してしまいます。現実的には、通常の出力がトレースバックヘッダから始まることはないので、実際に問題になることはないでしょう。

@item 
トレースバックスタック (がある場合) の各行は、実行例の最初の行よりも深くインデントされているか、`または' 英数文字以外で始まっていなければなりません。トレースバックヘッダ以後に現れる行のうち、インデントが等しく英数文字で始まる最初の行は例外の詳細情報が書かれた行とみなされるからです。もちろん、本物のトレースバックでは正しく動作します。

@item 
doctest のオプション @ref{1520,,IGNORE_EXCEPTION_DETAIL} を指定した場合、最も左端のコロン以後の全ての内容と、例外名の中の全てのモジュール情報が無視されます。

@item 
対話シェルでは、 @ref{18e,,SyntaxError} の場合にトレースバックヘッダが省略されることがあります。しかし doctest にとっては、例外を例外でないものと区別するためにトレースバックヘッダが必要です。そこで、トレースバックヘッダを省略するような @code{SyntaxError} をテストする必要があるというごく稀なケースでは、実行例にトレースバックヘッダを手作業で追加する必要があるでしょう。
@end itemize

@geindex ^ (キャレット);marker


@itemize *

@item 
For some exceptions, Python displays the position of the error using @code{^}
markers and tildes:

@example
>>> 1 + None
  File "<stdin>", line 1
    1 + None
    ~~^~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
@end example

例外の型と詳細情報の前にエラー位置を示す行がくるため、doctest はこの行を調べません。例えば、以下の例では、間違った場所に @code{^} マーカを入れても成功してしまいます:

@example
>>> 1 + None
  File "<stdin>", line 1
    1 + None
    ^~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
@end example
@end itemize
@anchor{library/doctest option-flags-and-directives}@anchor{4571}
@node オプションフラグ,ディレクティブ Directives,例外はどう扱えばよいか?,doctest のからくり
@anchor{library/doctest doctest-options}@anchor{1134}@anchor{library/doctest option-flags}@anchor{4572}
@subsubsection オプションフラグ


doctest の振る舞いは、数多くのオプションフラグによって様々な側面から制御されています。フラグのシンボル名はモジュールの定数として提供され、 @ref{24cd,,ビット単位論理和} でつないで様々な関数に渡すことができます。シンボル名は @ref{456b,,doctest directives} でも使用でき、doctest コマンドラインインターフェースに @code{-o} を通して与えることができます。

最初に説明するオプション群は、テストのセマンティクスを決めます。すなわち、実際にテストを実行したときの出力と実行例中の期待する出力とが一致しているかどうかを doctest がどのように判断するかを制御します:

@geindex DONT_ACCEPT_TRUE_FOR_1 (doctest モジュール)
@anchor{library/doctest doctest DONT_ACCEPT_TRUE_FOR_1}@anchor{4573}
@deffn {データ} doctest.DONT_ACCEPT_TRUE_FOR_1

デフォルトでは、期待する出力ブロックに単に @code{1} だけが入っており、実際の出力ブロックに @code{1} または @code{True} だけが入っていた場合、これらの出力は一致しているとみなされます。 @code{0} と @code{False} の場合も同様です。 @ref{4573,,DONT_ACCEPT_TRUE_FOR_1} を指定すると、こうした値の読み替えを行いません。デフォルトの挙動で読み替えを行うのは、最近の Python で多くの関数の戻り値型が整数型からブール型に変更されたことに対応するためです; 読み替えを行う場合、"通常の整数" の出力を期待する出力とするような doctest も動作します。このオプションはそのうちなくなるでしょうが、ここ数年はそのままでしょう。
@end deffn

@geindex <BLANKLINE>

@geindex DONT_ACCEPT_BLANKLINE (doctest モジュール)
@anchor{library/doctest doctest DONT_ACCEPT_BLANKLINE}@anchor{4574}
@deffn {データ} doctest.DONT_ACCEPT_BLANKLINE

デフォルトでは、期待する出力ブロックに @code{<BLANKLINE>} だけの入った行がある場合、その行は実際の出力における空行に一致するようになります。完全な空行を入れてしまうと期待する出力がそこで終わっているとみなされてしまうため、期待する出力に空行を入れたい場合にはこの方法を使わなければなりません。 @ref{4574,,DONT_ACCEPT_BLANKLINE} を指定すると、 @code{<BLANKLINE>} の読み替えを行わなくなります。
@end deffn

@geindex NORMALIZE_WHITESPACE (doctest モジュール)
@anchor{library/doctest doctest NORMALIZE_WHITESPACE}@anchor{456a}
@deffn {データ} doctest.NORMALIZE_WHITESPACE

このフラグを指定すると、連続する空白 (空白と改行文字) は互いに等価であるとみなします。期待する出力における任意の空白列は実際の出力における任意の空白と一致します。デフォルトでは、空白は厳密に一致しなければなりません。 @ref{456a,,NORMALIZE_WHITESPACE} は、期待する出力の内容が非常に長いために、ソースコード中でその内容を複数行に折り返して書きたい場合に特に便利です。
@end deffn

@geindex ...;in doctests

@geindex ELLIPSIS (doctest モジュール)
@anchor{library/doctest doctest ELLIPSIS}@anchor{1687}
@deffn {データ} doctest.ELLIPSIS

このフラグを指定すると、期待する出力中の省略記号マーカ (@code{...}) が実際の出力中の任意の部分文字列と一致するようになります。部分文字列は行境界にわたるものや空文字列を含みます。したがって、このフラグを使うのは単純な内容を対象にする場合にとどめましょう。複雑な使い方をすると、正規表現に @code{.*} を使ったときのように "しまった、マッチしすぎた！ (match too much!)" と驚くことになりかねません。
@end deffn

@geindex IGNORE_EXCEPTION_DETAIL (doctest モジュール)
@anchor{library/doctest doctest IGNORE_EXCEPTION_DETAIL}@anchor{1520}
@deffn {データ} doctest.IGNORE_EXCEPTION_DETAIL

When specified, doctests expecting exceptions pass so long as an exception
of the expected type is raised, even if the details
(message and fully qualified exception name) don't match.

For example, an example expecting @code{ValueError: 42} will pass if the actual
exception raised is @code{ValueError: 3*14}, but will fail if, say, a
@ref{198,,TypeError} is raised instead.
It will also ignore any fully qualified name included before the
exception class, which can vary between implementations and versions
of Python and the code/libraries in use.
Hence, all three of these variations will work with the flag specified:

@example
>>> raise Exception('message')
Traceback (most recent call last):
Exception: message

>>> raise Exception('message')
Traceback (most recent call last):
builtins.Exception: message

>>> raise Exception('message')
Traceback (most recent call last):
__main__.Exception: message
@end example

Note that @ref{1687,,ELLIPSIS} can also be used to ignore the
details of the exception message, but such a test may still fail based
on whether the module name is present or matches exactly.


バージョン 3.2 で変更: @ref{3e,,doctest} モジュールの @ref{1520,,IGNORE_EXCEPTION_DETAIL} フラグが、 テストされている例外を含むモジュールの名前を無視するようになりました。

@end deffn

@geindex SKIP (doctest モジュール)
@anchor{library/doctest doctest SKIP}@anchor{4575}
@deffn {データ} doctest.SKIP

このフラグを指定すると、実行例は一切実行されません。こうした機能は doctest の実行例がドキュメントとテストを兼ねていて、ドキュメントのためには含めておかなければならないけれどチェックされなくても良い、というような文脈で役に立ちます。例えば、実行例の出力がランダムであるとか、テストドライバーには利用できないリソースに依存している場合などです。

SKIP フラグは一時的に実行例を"コメントアウト"するのにも使えます。
@end deffn

@geindex COMPARISON_FLAGS (doctest モジュール)
@anchor{library/doctest doctest COMPARISON_FLAGS}@anchor{4576}
@deffn {データ} doctest.COMPARISON_FLAGS

上記の比較フラグすべての論理和をとったビットマスクです。
@end deffn

二つ目のオプション群は、テストの失敗を報告する方法を制御します:

@geindex REPORT_UDIFF (doctest モジュール)
@anchor{library/doctest doctest REPORT_UDIFF}@anchor{1688}
@deffn {データ} doctest.REPORT_UDIFF

このオプションを指定すると、期待する出力および実際の出力が複数行になるときにテストの失敗結果を unified diff 形式を使って表示します。
@end deffn

@geindex REPORT_CDIFF (doctest モジュール)
@anchor{library/doctest doctest REPORT_CDIFF}@anchor{1689}
@deffn {データ} doctest.REPORT_CDIFF

このオプションを指定すると、期待する出力および実際の出力が複数行になるときにテストの失敗結果を context diff 形式を使って表示します。
@end deffn

@geindex REPORT_NDIFF (doctest モジュール)
@anchor{library/doctest doctest REPORT_NDIFF}@anchor{168a}
@deffn {データ} doctest.REPORT_NDIFF

このオプションを指定すると、期待する出力と実際の出力との間の差分を @code{difflib.Differ} を使って算出します。使われているアルゴリズムは有名な @code{ndiff.py} ユーティリティと同じです。これは、行単位の差分と同じように行内の差分にマーカをつけられるようにする唯一の手段です。例えば、期待する出力のある行に数字の @code{1} が入っていて、実際の出力には @code{l} が入っている場合、不一致の起きているカラム位置を示すキャレットの入った行が一行挿入されます。
@end deffn

@geindex REPORT_ONLY_FIRST_FAILURE (doctest モジュール)
@anchor{library/doctest doctest REPORT_ONLY_FIRST_FAILURE}@anchor{4577}
@deffn {データ} doctest.REPORT_ONLY_FIRST_FAILURE

このオプションを指定すると、各 doctest で最初にエラーの起きた実行例だけを表示し、それ以後の実行例の出力を抑制します。これにより、正しく書かれた実行例が、それ以前の実行例の失敗によっておかしくなってしまった場合に、 doctest がそれを報告しないようになります。とはいえ、最初に失敗を引き起こした実行例とは関係なく誤って書かれた実行例の報告も抑制してしまいます。 @ref{4577,,REPORT_ONLY_FIRST_FAILURE} を指定した場合、実行例がどこかで失敗しても、それ以後の実行例を続けて実行し、失敗したテストの総数を報告します; 出力が抑制されるだけです。
@end deffn

@geindex FAIL_FAST (doctest モジュール)
@anchor{library/doctest doctest FAIL_FAST}@anchor{1135}
@deffn {データ} doctest.FAIL_FAST

このオプションを指定すると、最初に実行例が失敗した時点で終了し、残りの実行例を実行しません。つまり、報告される失敗の数はたかだか 1 つになります。最初の失敗より後の例はデバッグ出力を生成しないため、このフラグはデバッグの際に有用でしょう。
@end deffn

@geindex REPORTING_FLAGS (doctest モジュール)
@anchor{library/doctest doctest REPORTING_FLAGS}@anchor{4578}
@deffn {データ} doctest.REPORTING_FLAGS

上記のエラー報告に関するフラグすべての論理和をとったビットマスクです。
@end deffn

There is also a way to register new option flag names, though this isn't
useful unless you intend to extend @code{doctest} internals via subclassing:

@geindex register_optionflag() (doctest モジュール)
@anchor{library/doctest doctest register_optionflag}@anchor{4579}
@deffn {の関数} doctest.register_optionflag (name)

名前 `name' の新たなオプションフラグを作成し、作成されたフラグの整数値を返します。 @ref{4579,,register_optionflag()} は @ref{457a,,OutputChecker} や  @ref{457b,,DocTestRunner} をサブクラス化して、その中で新たに作成したオプションをサポートさせる際に使います。 @ref{4579,,register_optionflag()} は以下のような定形文で呼び出さなければなりません:

@example
MY_FLAG = register_optionflag('MY_FLAG')
@end example
@end deffn

@geindex # (hash);in doctests
@geindex + (プラス記号);in doctests
@geindex - (負符号);in doctests

@node ディレクティブ Directives,警告<2>,オプションフラグ,doctest のからくり
@anchor{library/doctest directives}@anchor{457c}@anchor{library/doctest doctest-directives}@anchor{456b}
@subsubsection ディレクティブ (Directives)


doctest ディレクティブは個々の実行例の @ref{1134,,オプションフラグ} を操作するために使われます。 doctest ディレクティブは後のソースコード例にあるような特殊な Python コメントです:

@example
@anchor{library/doctest grammar-token-doctest-directive}@anchor{457d}directive:             "#" "doctest:" @ref{457e,,directive_options}
@anchor{library/doctest grammar-token-doctest-directive_options}@anchor{457e}directive_options:     @ref{457f,,directive_option} ("," @ref{457f,,directive_option})*
@anchor{library/doctest grammar-token-doctest-directive_option}@anchor{457f}directive_option:      @ref{4580,,on_or_off} @ref{4581,,directive_option_name}
@anchor{library/doctest grammar-token-doctest-on_or_off}@anchor{4580}on_or_off:             "+" | "-"
@anchor{library/doctest grammar-token-doctest-directive_option_name}@anchor{4581}directive_option_name: "DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...
@end example

@code{+} や @code{-} とディレクティブオプション名の間に空白を入れてはなりません。ディレクティブオプション名は上で説明したオプションフラグ名のいずれかです。

ある実行例の doctest ディレクティブは、その実行例だけの doctest の振る舞いを変えます。ある特定の挙動を有効にしたければ @code{+} を、無効にしたければ @code{-} を使います。

例えば、以下のテストは成功します:

@example
>>> print(list(range(20)))  # doctest: +NORMALIZE_WHITESPACE
[0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
10,  11, 12, 13, 14, 15, 16, 17, 18, 19]
@end example

ディレクティブがない場合、実際の出力には一桁の数字の間に二つスペースが入っていないこと、実際の出力は 1 行になることから、テストは成功しないはずです。別のディレクティブを使って、このテストを成功させることもできます:

@example
>>> print(list(range(20)))  # doctest: +ELLIPSIS
[0, 1, ..., 18, 19]
@end example

複数のディレクティブは、一つの物理行の中にコンマで区切って指定できます:

@example
>>> print(list(range(20)))  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[0,    1, ...,   18,    19]
@end example

一つの実行例中で複数のディレクティブコメントを使った場合、それらは組み合わされます:

@example
>>> print(list(range(20)))  # doctest: +ELLIPSIS
...                         # doctest: +NORMALIZE_WHITESPACE
[0,    1, ...,   18,    19]
@end example

この実行例で分かるように、実行例にはディレクティブだけを含む @code{...} 行を追加することができます。この書きかたは、実行例が長すぎるためにディレクティブを同じ行に入れると収まりが悪い場合に便利です:

@example
>>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
... # doctest: +ELLIPSIS
[0, ..., 4, 10, ..., 19, 30, ..., 39]
@end example

フォルトではすべてのオプションが無効になっており、ディレクティブは特定の実行例だけに影響を及ぼすので、通常意味があるのは有効にするためのオプション (@code{+} のついたディレクティブ) だけです。とはいえ、doctest を実行する関数はオプションフラグを指定してデフォルトとは異なった挙動を実現できるので、そのような場合には @code{-} を使った無効化オプションも意味を持ちます。

@node 警告<2>,,ディレクティブ Directives,doctest のからくり
@anchor{library/doctest doctest-warnings}@anchor{4582}@anchor{library/doctest warnings}@anchor{4583}
@subsubsection 警告


@code{doctest} is serious about requiring exact matches in expected output.  If
even a single character doesn't match, the test fails.  This will probably
surprise you a few times, as you learn exactly what Python does and doesn't
guarantee about output.  For example, when printing a set, Python doesn't
guarantee that the element is printed in any particular order, so a test like

@example
>>> foo()
@{"spam", "eggs"@}
@end example

は失敗するかもしれないのです! 回避するには

@example
>>> foo() == @{"spam", "eggs"@}
True
@end example

とするのが一つのやり方です。別のやり方は

@example
>>> d = sorted(foo())
>>> d
['eggs', 'spam']
@end example

他のやり方もありますが、あとは自分で考えてみてください。

以下のように、オブジェクトアドレスを埋め込むような結果を print するのもよくありません :

@example
>>> id(1.0)  # certain to fail some of the time
7948648
>>> class C: pass
>>> C()  # the default repr() for instances embeds an address
<C object at 0x00AC18F0>
@end example

@ref{1687,,ELLIPSIS} ディレクティブを使うと、上のような例をうまく解決できます:

@example
>>> C()  # doctest: +ELLIPSIS
<C object at 0x...>
@end example

Floating-point numbers are also subject to small output variations across
platforms, because Python defers to the platform C library for some
floating-point calculations, and C libraries vary widely in quality here.

@example
>>> 1000**0.1  # risky
1.9952623149688797
>>> round(1000**0.1, 9) # safer
1.995262315
>>> print(f'@{1000**0.1:.4f@}') # much safer
1.9953
@end example

@code{I/2.**J} の形式になる数値はどのプラットフォームでもうまく動作するので、私はこの形式の数値を生成するように doctest の実行例を工夫しています:

@example
>>> 3./4  # utterly safe
0.75
@end example

単純な分数は人間にとっても理解しやすく、良いドキュメントを書くために役に立ちます。

@node 基本 API,単体テスト API,doctest のからくり,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest basic-api}@anchor{4584}@anchor{library/doctest doctest-basic-api}@anchor{4558}
@subsubsection 基本 API


数 @ref{1686,,testmod()} と @ref{455b,,testfile()} は、ほとんどの基本的な用途に十分な doctest インターフェースを提供しています。これら二つの関数についてあまり形式的でない入門が読みたければ、 @ref{4555,,簡単な利用法; docstring 中の実行例をチェックする} 節や @ref{4559,,簡単な利用法; テキストファイル中の実行例をチェックする} 節を参照してください。

@geindex testfile() (doctest モジュール)
@anchor{library/doctest doctest testfile}@anchor{455b}
@deffn {の関数} doctest.testfile (filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser(), encoding=None)

`filename' 以外の引数はすべてオプションで、キーワード引数形式で指定しなければなりません。

`filename' に指定したファイル内にある実行例をテストします。@code{(failure_count, test_count)} を返します。

オプション引数の `module_relative' は、ファイル名をどのように解釈するかを指定します:


@itemize *

@item 
`module_relative' が @code{True} (デフォルト) の場合、`filename' は OS に依存しないモジュールの相対パスになります。デフォルトでは、このパスは関数 @ref{455b,,testfile()} を呼び出しているモジュールからの相対パスになります; ただし、`package' 引数を指定した場合には、パッケージからの相対になります。OS への依存性を除くため、`filename'  ではパスを分割する文字に @code{/} を使わなければならず、絶対パスにしてはなりません (パス文字列を @code{/} で始めてはなりません)。

@item 
`module_relative' が @code{False} の場合、`filename' は OS 依存のパスを示します。パスは絶対パスでも相対パスでもかまいません; 相対パスにした場合、現在の作業ディレクトリを基準に解決します。
@end itemize

オプション引数 `name' には、テストの名前を指定します; デフォルトの場合や @code{None} を指定した場合、@code{os.path.basename(filename)} になります。

オプション引数 `package' には、Python パッケージを指定するか、モジュール相対のファイル名の場合には相対の基準ディレクトリとなる Python パッケージの名前を指定します。パッケージを指定しない場合、関数を呼び出しているモジュールのディレクトリを相対の基準ディレクトリとして使います。`module_relative' を @code{False} に指定している場合、`package' を指定するとエラーになります。

オプション引数 `globs' には辞書を指定します。この辞書は、実行例を実行する際のグローバル変数として用いられます。doctest はこの辞書の浅いコピーを生成するので、実行例は白紙の状態からスタートします。デフォルトの場合や @code{None} を指定した場合、新たな空の辞書になります。

オプション引数 `extraglobs' には辞書を指定します。この辞書は、実行例を実行する際にグローバル変数にマージされます。マージは @ref{167e,,dict.update()} のように振舞います: `globs' と `extraglobs' との間に同じキー値がある場合、両者を合わせた辞書中には `extraglobs' の方の値が入ります。デフォルト、または @code{None} であるとき、追加のグローバル変数は使われません。この仕様は、パラメータ付きで doctest を実行するという、やや進んだ機能です。例えば、一般的な名前を使って基底クラス向けに doctest を書いておき、その後で辞書で一般的な名前からテストしたいサブクラスへの対応付けを行う辞書を `extraglobs' に渡して、様々なサブクラスをテストできます。

オプション引数 `verbose' が真の場合、様々な情報を出力します。偽の場合にはテストの失敗だけを報告します。デフォルトの場合や @code{None} を指定した場合、@ref{147c,,sys.argv} に @code{'-v'} を指定しない限りこの値は真になりません。

オプション引数 `report' が真の場合、テストの最後にサマリを出力します。それ以外の場合には何も出力しません。verbose モードの場合、サマリには詳細な情報を出力しますが、そうでない場合にはサマリはとても簡潔になります (実際には、すべてのテストが成功した場合には何も出力しません)。

オプション引数 `optionflags' (デフォルト値 @code{0}) は、各オプションフラグの @ref{24cd,,ビット単位論理和} を取ります。 @ref{1134,,オプションフラグ} 節を参照してください。

オプション引数 `raise_on_error' の値はデフォルトでは偽です。真にすると、最初のテスト失敗や予期しない例外が起きたときに例外を送出します。このオプションを使うと、失敗の原因を検死デバッグ (post-mortem debug) できます。デフォルトの動作では、実行例の実行を継続します。

オプション引数 `parser' には、 @ref{456c,,DocTestParser} (またはそのサブクラス) を指定します。このクラスはファイルから実行例を抽出するために使われます。デフォルトでは通常のパーザ (@code{DocTestParser()}) です。

オプション引数 `encoding' にはファイルをユニコードに変換する際に使われるエンコーディングを指定します。
@end deffn

@geindex testmod() (doctest モジュール)
@anchor{library/doctest doctest testmod}@anchor{1686}
@deffn {の関数} 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' (`m' を指定しないか @code{None} にした場合には @ref{1,,__main__}) から到達可能な関数およびクラスの docstring 内にある実行例をテストします。 @code{m.__doc__} 内の実行例からテストを開始します。

Also test examples reachable from dict @code{m.__test__}, if it exists.
@code{m.__test__} maps names (strings) to functions, classes and
strings; function and class docstrings are searched for examples; strings are
searched directly, as if they were docstrings.

モジュール `m' に属するオブジェクトにつけられた docstring のみを検索します。

@code{(failure_count, test_count)} を返します。

オプション引数 `name' には、モジュールの名前を指定します。デフォルトの場合や @code{None} を指定した場合には、@code{m.__name__} を使います。

オプション引数 `exclude_empty' はデフォルトでは偽になっています。この値を真にすると、doctest を持たないオブジェクトを考慮から外します。デフォルトの設定は依存のバージョンとの互換性を考えたハックであり、@ref{4585,,doctest.master.summarize} と @ref{1686,,testmod()} を合わせて利用しているようなコードでも、テスト実行例を持たないオブジェクトから出力を得るようにしています。新たに追加された @ref{19a8,,DocTestFinder} のコンストラクタの `exclude_empty' はデフォルトで真になります。

オプション引数 `extraglobs', `verbose', `report', `optionflags', `raise_on_error', および `globs' は上で説明した @ref{455b,,testfile()} の引数と同じです。ただし、 `globs' のデフォルト値は @code{m.__dict__} になります。
@end deffn

@geindex run_docstring_examples() (doctest モジュール)
@anchor{library/doctest doctest run_docstring_examples}@anchor{4586}
@deffn {の関数} doctest.run_docstring_examples (f, globs, verbose=False, name='NoName', compileflags=None, optionflags=0)

オブジェクト `f' に関連付けられた実行例をテストします。 `f' は文字列、モジュール、関数、またはクラスオブジェクトです。

引数 `globs' に辞書を指定すると、その浅いコピーを実行コンテキストに使います。

オプション引数 `name' はテスト失敗時のメッセージに使われます。デフォルトの値は @code{'NoName'} です。

オプション引数 `verbose' の値を真にすると、テストが失敗しなくても出力を生成します。デフォルトでは、実行例のテストに失敗したときのみ出力を生成します。

オプション引数 `compileflags' には、実行例を実行するときに Python バイトコードコンパイラが使うフラグを指定します。デフォルトの場合や @code{None} を指定した場合、フラグは `globs' 内にある future 機能セットに対応したものになります。

オプション引数 `optionflags' は、上で述べた @ref{455b,,testfile()} と同様の働きをします。
@end deffn

@node 単体テスト API,拡張 API,基本 API,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest doctest-unittest-api}@anchor{4587}@anchor{library/doctest unittest-api}@anchor{4588}
@subsubsection 単体テスト API


As your collection of doctest'ed modules grows, you'll want a way to run all
their doctests systematically.  @code{doctest} provides two functions that can
be used to create @ref{10c,,unittest} test suites from modules and text files
containing doctests.  To integrate with @ref{10c,,unittest} test discovery, include
a @ref{4589,,load_tests} function in your test module:

@example
import unittest
import doctest
import my_module_with_doctests

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
    return tests
@end example

doctest の入ったテキストファイルやモジュールから @ref{ff5,,unittest.TestSuite} インスタンスを生成するための主な関数は二つあります:

@geindex DocFileSuite() (doctest モジュール)
@anchor{library/doctest doctest DocFileSuite}@anchor{458a}
@deffn {の関数} doctest.DocFileSuite (*paths, module_relative=True, package=None, setUp=None, tearDown=None, globs=None, optionflags=0, parser=DocTestParser(), encoding=None)

単一または複数のテキストファイルに入っている doctest 形式のテストを、 @ref{ff5,,unittest.TestSuite} インスタンスに変換します。

The returned @ref{ff5,,unittest.TestSuite} is to be run by the unittest framework
and runs the interactive examples in each file.  If an example in any file
fails, then the synthesized unit test fails, and a @ref{458b,,failureException}
exception is raised showing the name of the file containing the test and a
(sometimes approximate) line number.  If all the examples in a file are
skipped, then the synthesized unit test is also marked as skipped.

関数には、テストを行いたい一つまたは複数のファイルへのパスを (文字列で) 渡します。

@ref{458a,,DocFileSuite()} には、キーワード引数でオプションを指定できます:

オプション引数 `module_relative' は `paths' に指定したファイル名をどのように解釈するかを指定します:


@itemize *

@item 
`module_relative' が @code{True} (デフォルト) の場合、`paths' 中のファイル名は OS に依存しないモジュールの相対パスになります。デフォルトでは、このパスは呼び出し元のモジュールのディレクトリからの相対パスになります; ただし、`package' 引数を指定した場合には、パッケージからの相対になります。OS への依存性を除くため、各ファイル名はパスを分割するのに @code{/} 文字を使わなければならず、絶対パスにしてはなりません (パス文字列を @code{/} で始めてはなりません)。

@item 
`module_relative' が @code{False} の場合、`filename' は OS 依存のパスを示します。パスは絶対パスでも相対パスでもかまいません; 相対パスにした場合、現在の作業ディレクトリを基準に解決します。
@end itemize

オプション引数 `package' には、Python パッケージを指定するか、モジュール相対のファイル名の場合には相対の基準ディレクトリとなる Python パッケージの名前を指定します。パッケージを指定しない場合、関数を呼び出しているモジュールのディレクトリを相対の基準ディレクトリとして使います。`module_relative' を @code{False} に指定している場合、`package' を指定するとエラーになります。

オプション引数 `setUp' には、テストスイートのセットアップに使う関数を指定します。この関数は、各ファイルのテストを実行する前に呼び出されます。 setUp 関数は @ref{1a29,,DocTest} オブジェクトに引き渡されます。 `setUp' は @ref{458c,,globs} 属性を介してテストのグローバル変数にアクセスできます。

オプション引数 `tearDown' には、テストを解体 (tear-down) するための関数を指定します。この関数は、各ファイルのテストの実行を終了するたびに呼び出されます。 `tearDown' 関数は @ref{1a29,,DocTest}  オブジェクトに引き渡されます。 `tearDown' は @ref{458c,,globs} 属性を介してテストのグローバル変数にアクセスできます。

オプション引数 `globs' は辞書で、テストのグローバル変数の初期値が入ります。この辞書は各テストごとに新たにコピーして使われます。デフォルトでは `globs' は空の新たな辞書です。

オプション引数 `optionflags' には、テストを実行する際にデフォルトで適用される doctest オプションを OR で結合して指定します。 @ref{1134,,オプションフラグ} 節を参照してください。結果レポートに関するオプションを指定するより適切な方法は下記の @ref{458d,,set_unittest_reportflags()} の説明を参照してください。

オプション引数 `parser' には、 @ref{456c,,DocTestParser} (またはそのサブクラス) を指定します。このクラスはファイルから実行例を抽出するために使われます。デフォルトでは通常のパーザ (@code{DocTestParser()}) です。

オプション引数 `encoding' にはファイルをユニコードに変換する際に使われるエンコーディングを指定します。

@ref{458a,,DocFileSuite()} を使用してテキストファイルからロードされた doctests に提供される globals に、グローバル変数 @code{__file__} が追加されます。
@end deffn

@geindex DocTestSuite() (doctest モジュール)
@anchor{library/doctest doctest DocTestSuite}@anchor{ff4}
@deffn {の関数} doctest.DocTestSuite (module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, optionflags=0, checker=None)

doctest のテストを @ref{ff5,,unittest.TestSuite} に変換します。

The returned @ref{ff5,,unittest.TestSuite} is to be run by the unittest framework
and runs each doctest in the module.
Each docstring is run as a separate unit test.
If any of the doctests fail, then the synthesized unit test fails,
and a @ref{458b,,unittest.TestCase.failureException} exception is raised
showing the name of the file containing the test and a (sometimes approximate)
line number.  If all the examples in a docstring are skipped, then the

オプション引数 `module' には、テストしたいモジュールの名前を指定します。`module' にはモジュールオブジェクトまたは (ドット表記の) モジュール名を指定できます。`module' を指定しない場合、この関数を呼び出しているモジュールになります。

Optional argument `globs' is a dictionary containing the initial global
variables for the tests.  A new copy of this dictionary is created for each
test.  By default, `globs' is the module's @ref{236f,,__dict__}.

オプション引数 `extraglobs' には追加のグローバル変数セットを指定します。この変数セットは `globs' に統合されます。デフォルトでは、追加のグローバル変数はありません。

オプション引数 `test_finder' は、モジュールから doctest を抽出するための @ref{19a8,,DocTestFinder} オブジェクト (またはその代替となるオブジェクト) です。

Optional arguments `setUp', `tearDown', and `optionflags' are the same as for
function @ref{458a,,DocFileSuite()} above, but they are called for each docstring.

この関数は @ref{1686,,testmod()} と同じ検索方法を使います。


バージョン 3.5 で変更: `module' がドキュメンテーション文字列を含まない場合には、 @ref{ff4,,DocTestSuite()} は @ref{2ec,,ValueError} を送出するのではなく空の  @ref{ff5,,unittest.TestSuite} を返します。

@end deffn

Under the covers, @ref{ff4,,DocTestSuite()} creates a @ref{ff5,,unittest.TestSuite} out
of @code{doctest.DocTestCase} instances, and @code{DocTestCase} is a
subclass of @ref{2b3,,unittest.TestCase}. @code{DocTestCase} isn't documented
here (it's an internal detail), but studying its code can answer questions about
the exact details of @ref{10c,,unittest} integration.

Similarly, @ref{458a,,DocFileSuite()} creates a @ref{ff5,,unittest.TestSuite} out of
@code{doctest.DocFileCase} instances, and @code{DocFileCase} is a subclass
of @code{DocTestCase}.

So both ways of creating a @ref{ff5,,unittest.TestSuite} run instances of
@code{DocTestCase}.  This is important for a subtle reason: when you run
@code{doctest} functions yourself, you can control the @code{doctest} options in
use directly, by passing option flags to @code{doctest} functions.  However, if
you're writing a @ref{10c,,unittest} framework, @code{unittest} ultimately controls
when and how tests get run.  The framework author typically wants to control
@code{doctest} reporting options (perhaps, e.g., specified by command line
options), but there's no way to pass options through @code{unittest} to
@code{doctest} test runners.

For this reason, @code{doctest} also supports a notion of @code{doctest}
reporting flags specific to @ref{10c,,unittest} support, via this function:

@geindex set_unittest_reportflags() (doctest モジュール)
@anchor{library/doctest doctest set_unittest_reportflags}@anchor{458d}
@deffn {の関数} doctest.set_unittest_reportflags (flags)

Set the @code{doctest} reporting flags to use.

引数 `flags' はオプションフラグの @ref{24cd,,ビット単位論理和} を取ります。 @ref{1134,,オプションフラグ} 節を参照してください。「レポートフラグ」しか使えません。

This is a module-global setting, and affects all future doctests run by module
@ref{10c,,unittest}:  the @code{runTest()} method of @code{DocTestCase} looks at
the option flags specified for the test case when the @code{DocTestCase}
instance was constructed.  If no reporting flags were specified (which is the
typical and expected case), @code{doctest}'s @code{unittest} reporting flags are
@ref{24cd,,bitwise ORed} into the option flags, and the option flags
so augmented are passed to the @ref{457b,,DocTestRunner} instance created to
run the doctest.  If any reporting flags were specified when the
@code{DocTestCase} instance was constructed, @code{doctest}'s
@code{unittest} reporting flags are ignored.

この関数は、関数を呼び出す前に有効になっていた @ref{10c,,unittest} レポートフラグの値を返します。
@end deffn

@node 拡張 API,デバッグ,単体テスト API,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest advanced-api}@anchor{458e}@anchor{library/doctest doctest-advanced-api}@anchor{458f}
@subsubsection 拡張 API


基本 API は、doctest を使いやすくするための簡単なラッパであり、柔軟性があってほとんどのユーザの必要を満たしています; とはいえ、もっとテストをきめ細かに制御したい場合や、doctest の機能を拡張したい場合、拡張 API (advanced API) を使わなければなりません。

拡張 API は、doctest ケースから抽出した対話モードでの実行例を記憶するための二つのコンテナクラスを中心に構成されています:


@itemize *

@item 
@ref{4590,,Example}: 1つの Python @ref{2bfc,,文} と、その期待する出力をペアにしたもの。

@item 
@ref{1a29,,DocTest}: @ref{4590,,Example} の集まり。通常一つの docstring やテキストファイルから抽出されます。
@end itemize

その他に、doctest の実行例を検索、構文解析、実行、チェックするための処理クラスが以下のように定義されています:


@itemize *

@item 
@ref{19a8,,DocTestFinder}: 与えられたモジュールからすべての docstring を検索し、 @ref{456c,,DocTestParser} を使って対話モードでの実行例が入ったすべての docstring から @ref{1a29,,DocTest} を生成します。

@item 
@ref{456c,,DocTestParser}: (オブジェクトの docstring 等の) 文字列から @ref{1a29,,DocTest} オブジェクトを生成します。

@item 
@ref{457b,,DocTestRunner}: @ref{1a29,,DocTest} 内の実行例を実行し、 @ref{457a,,OutputChecker} を使って出力を検証します。

@item 
@ref{457a,,OutputChecker}: doctest 実行例から実際に出力された結果を期待する出力と比較し、両者が一致するか判別します。
@end itemize

これらの処理クラスの関係を図にまとめると、以下のようになります:

@example
                            list of:
+------+                   +---------+
|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
+------+    |        ^     +---------+     |       ^    (printed)
            |        |     | Example |     |       |
            v        |     |   ...   |     v       |
           DocTestParser   | Example |   OutputChecker
                           +---------+
@end example

@menu
* DocTest オブジェクト:: 
* Example オブジェクト:: 
* DocTestFinder オブジェクト:: 
* DocTestParser オブジェクト:: 
* TestResults objects:: 
* DocTestRunner オブジェクト:: 
* OutputChecker オブジェクト:: 

@end menu

@node DocTest オブジェクト,Example オブジェクト,,拡張 API
@anchor{library/doctest doctest-doctest}@anchor{4591}@anchor{library/doctest doctest-objects}@anchor{4592}
@subsubsection DocTest オブジェクト


@geindex DocTest (doctest のクラス)
@anchor{library/doctest doctest DocTest}@anchor{1a29}
@deffn {クラス} doctest.DocTest (examples, globs, name, filename, lineno, docstring)

単一の名前空間内で実行される doctest 実行例の集まりです。コンストラクタの引数は @ref{1a29,,DocTest} インスタンス中の同名の属性の初期化に使われます。

@ref{1a29,,DocTest} では、以下の属性を定義しています。これらの変数はコンストラクタで初期化されます。直接変更してはなりません。

@geindex examples (doctest.DocTest の属性)
@anchor{library/doctest doctest DocTest examples}@anchor{4593}
@deffn {の属性} examples

対話モードにおける実行例それぞれをエンコードしていて、テストで実行される、 @ref{4590,,Example} オブジェクトからなるリストです。
@end deffn

@geindex globs (doctest.DocTest の属性)
@anchor{library/doctest doctest DocTest globs}@anchor{458c}
@deffn {の属性} globs

実行例を実行する名前空間 (いわゆるグローバル変数) です。このメンバは、名前から値への対応付けを行っている辞書です。実行例が名前空間に対して (新たな変数を束縛するなど) 何らかの変更を行った場合、 @ref{458c,,globs} への反映はテストの実行後に起こります。
@end deffn

@geindex name (doctest.DocTest の属性)
@anchor{library/doctest doctest DocTest name}@anchor{4594}
@deffn {の属性} name

@ref{1a29,,DocTest} を識別する名前の文字列です。通常、この値はテストを取り出したオブジェクトかファイルの名前になります。
@end deffn

@geindex filename (doctest.DocTest の属性)
@anchor{library/doctest doctest DocTest filename}@anchor{4595}
@deffn {の属性} filename

The name of the file that this @ref{1a29,,DocTest} was extracted from; or
@code{None} if the filename is unknown, or if the @code{DocTest} was not
extracted from a file.
@end deffn

@geindex lineno (doctest.DocTest の属性)
@anchor{library/doctest doctest DocTest lineno}@anchor{17c7}
@deffn {の属性} lineno

@ref{4595,,filename} 中で @ref{1a29,,DocTest} のテスト実行例が始まっている行の行番号で、行番号が利用できなければ @code{None} です。行番号は、ファイルの先頭を 0 として数えます。
@end deffn

@geindex docstring (doctest.DocTest の属性)
@anchor{library/doctest doctest DocTest docstring}@anchor{4596}
@deffn {の属性} docstring

テストを取り出した docstring 自体を現す文字列です。docstring 文字列を得られない場合や、文字列からテスト実行例を取り出したのでない場合には @code{None} になります。
@end deffn
@end deffn

@node Example オブジェクト,DocTestFinder オブジェクト,DocTest オブジェクト,拡張 API
@anchor{library/doctest doctest-example}@anchor{4597}@anchor{library/doctest example-objects}@anchor{4598}
@subsubsection Example オブジェクト


@geindex Example (doctest のクラス)
@anchor{library/doctest doctest Example}@anchor{4590}
@deffn {クラス} doctest.Example (source, want, exc_msg=None, lineno=0, indent=0, options=None)

ひとつの Python 文と、それに対する期待する出力からなる、単一の対話的モードの実行例です。コンストラクタの引数は @ref{4590,,Example} インスタンス中の同名の属性の初期化に使われます。

@ref{4590,,Example} では、以下の属性を定義しています。これらの変数はコンストラクタで初期化されます。直接変更してはなりません。

@geindex source (doctest.Example の属性)
@anchor{library/doctest doctest Example source}@anchor{4599}
@deffn {の属性} source

実行例のソースコードが入った文字列です。ソースコードは単一の Python で、末尾は常に改行です。コンストラクタは必要に応じて改行を追加します。
@end deffn

@geindex want (doctest.Example の属性)
@anchor{library/doctest doctest Example want}@anchor{459a}
@deffn {の属性} want

実行例のソースコードを実行した際の期待する出力 (標準出力と、例外が生じた場合にはトレースバック) です。 @ref{459a,,want} の末尾は、期待する出力がまったくない場合を除いて常に改行になります。期待する出力がない場合には空文字列になります。コンストラクタは必要に応じて改行を追加します。
@end deffn

@geindex exc_msg (doctest.Example の属性)
@anchor{library/doctest doctest Example exc_msg}@anchor{459b}
@deffn {の属性} exc_msg

実行例が例外を生成すると期待される場合の例外メッセージです。例外を送出しない場合には @code{None} です。この例外メッセージは、 @ref{a4e,,traceback.format_exception_only()} の戻り値と比較されます。値が @code{None} でない限り、 @ref{459b,,exc_msg} は改行で終わっていなければなりません; コンストラクタは必要に応じて改行を追加します。
@end deffn

@geindex lineno (doctest.Example の属性)
@anchor{library/doctest doctest Example lineno}@anchor{459c}
@deffn {の属性} lineno

この実行例を含む文字列における実行例が始まる行番号です。行番号は文字列の先頭を 0 として数えます。
@end deffn

@geindex indent (doctest.Example の属性)
@anchor{library/doctest doctest Example indent}@anchor{459d}
@deffn {の属性} indent

実行例の入っている文字列のインデント、すなわち実行例の最初のプロンプトより前にある空白文字の数です。
@end deffn

@geindex options (doctest.Example の属性)
@anchor{library/doctest doctest Example options}@anchor{459e}
@deffn {の属性} options

A dictionary mapping from option flags to @code{True} or @code{False}, which is used
to override default options for this example.  Any option flags not contained
in this dictionary are left at their default value (as specified by the
@ref{457b,,DocTestRunner}'s @ref{1134,,optionflags}).
By default, no options are set.
@end deffn
@end deffn

@node DocTestFinder オブジェクト,DocTestParser オブジェクト,Example オブジェクト,拡張 API
@anchor{library/doctest doctest-doctestfinder}@anchor{459f}@anchor{library/doctest doctestfinder-objects}@anchor{45a0}
@subsubsection DocTestFinder オブジェクト


@geindex DocTestFinder (doctest のクラス)
@anchor{library/doctest doctest DocTestFinder}@anchor{19a8}
@deffn {クラス} doctest.DocTestFinder (verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True)

与えられたオブジェクトについて、そのオブジェクト自身の docstring か、そのオブジェクトに含まれるオブジェクトの docstring から @ref{1a29,,DocTest} を抽出する処理クラスです。モジュール、クラス、関数、メソッド、静的メソッド、クラスメソッド、プロパティから @ref{1a29,,DocTest} を抽出できます。

オプション引数 `verbose' を使うと、抽出処理の対象となるオブジェクトを表示できます。デフォルトは @code{False} (出力を行わない) です。

オプション引数 `parser' には、 docstring から @ref{1a29,,DocTest} を抽出するのに使う @ref{456c,,DocTestParser} オブジェクト (またはその代替となるオブジェクト) を指定します。

オプション引数 `recurse' が偽の場合、 @ref{1a6f,,DocTestFinder.find()} は与えられたオブジェクトだけを調べ、そのオブジェクトに含まれる他のオブジェクトを調べません。

オプション引数 `exclude_empty' が偽の場合、 @ref{1a6f,,DocTestFinder.find()} は空の docstring を持つオブジェクトもテスト対象に含めます。

@ref{19a8,,DocTestFinder} では以下のメソッドを定義しています:

@geindex find() (doctest.DocTestFinder のメソッド)
@anchor{library/doctest doctest DocTestFinder find}@anchor{1a6f}
@deffn {メソッド} find (obj[, name][, module][, globs][, extraglobs])

`obj' または `obj' 内に入っているオブジェクトの docstring 中で定義されている @ref{1a29,,DocTest} のリストを返します。

オプション引数 `name' には、オブジェクトの名前を指定します。この名前は、関数が返す @ref{1a29,,DocTest} の名前になります。 `name' を指定しない場合、 @code{obj.__name__} を使います。

オプションのパラメータ `module' は、指定したオブジェクトを収めているモジュールを指定します。
`module' を指定しないか、@code{None} を指定した場合には、正しいモジュールを自動的に決定しようと試みます。
オブジェクトのモジュールは以下のような役割を果たします:


@itemize *

@item 
`globs' を指定していない場合、オブジェクトのモジュールはデフォルトの名前空間になります。

@item 
他のモジュールから import されたオブジェクトに対して @ref{19a8,,DocTestFinder} が @ref{1a29,,DocTest} を抽出するのを避けるために使います。 (`module' 由来でないオブジェクトを無視します。)

@item 
オブジェクトの入っているファイル名を調べるために使います。

@item 
オブジェクトがファイル内の何行目にあるかを調べる手助けにします。
@end itemize

`module' が @code{False} の場合には、モジュールの検索を試みません。これは正確さを欠くような使い方で、通常 doctest 自体のテストにしか使いません。`module' が @code{False} の場合、または `module' が @code{None} で自動的に的確なモジュールを見つけ出せない場合には、すべてのオブジェクトは @code{(non-existent)} モジュールに属するとみなされ、そのオブジェクト内のすべてのオブジェクトに対して (再帰的に) doctest の検索を行います。

The globals for each @ref{1a29,,DocTest} is formed by combining `globs' and
`extraglobs' (bindings in `extraglobs' override bindings in `globs').  A new
shallow copy of the globals dictionary is created for each @code{DocTest}.
If `globs' is not specified, then it defaults to the module's
@ref{236f,,__dict__}, if specified, or @code{@{@}} otherwise.
If `extraglobs' is not specified, then it defaults to @code{@{@}}.
@end deffn
@end deffn

@node DocTestParser オブジェクト,TestResults objects,DocTestFinder オブジェクト,拡張 API
@anchor{library/doctest doctest-doctestparser}@anchor{45a1}@anchor{library/doctest doctestparser-objects}@anchor{45a2}
@subsubsection DocTestParser オブジェクト


@geindex DocTestParser (doctest のクラス)
@anchor{library/doctest doctest DocTestParser}@anchor{456c}
@deffn {クラス} doctest.DocTestParser

対話モードの実行例を文字列から抽出し、それを使って @ref{1a29,,DocTest} オブジェクトを生成するために使われる処理クラスです。

@ref{456c,,DocTestParser} では以下のメソッドを定義しています:

@geindex get_doctest() (doctest.DocTestParser のメソッド)
@anchor{library/doctest doctest DocTestParser get_doctest}@anchor{45a3}
@deffn {メソッド} get_doctest (string, globs, name, filename, lineno)

指定した文字列からすべての doctest 実行例を抽出し、 @ref{1a29,,DocTest} オブジェクト内に集めます。

`globs', `name', `filename', and `lineno' are attributes for the new
@code{DocTest} object.  See the documentation for @ref{1a29,,DocTest} for more
information.
@end deffn

@geindex get_examples() (doctest.DocTestParser のメソッド)
@anchor{library/doctest doctest DocTestParser get_examples}@anchor{45a4}
@deffn {メソッド} get_examples (string, name='<string>')

指定した文字列からすべての doctest 実行例を抽出し、 @ref{4590,,Example} オブジェクトからなるリストにして返します。各 @ref{4590,,Example} の行番号は 0 から数えます。オプション引数 `name' はこの文字列につける名前で、エラーメッセージにしか使われません。
@end deffn

@geindex parse() (doctest.DocTestParser のメソッド)
@anchor{library/doctest doctest DocTestParser parse}@anchor{45a5}
@deffn {メソッド} parse (string, name='<string>')

Divide the given string into examples and intervening text, and return them as
a list of alternating @ref{4590,,Example}s and strings. Line numbers for the
@code{Example}s are 0-based.  The optional argument `name' is a name
identifying this string, and is only used for error messages.
@end deffn
@end deffn

@node TestResults objects,DocTestRunner オブジェクト,DocTestParser オブジェクト,拡張 API
@anchor{library/doctest testresults-objects}@anchor{45a6}
@subsubsection TestResults objects


@geindex TestResults (doctest のクラス)
@anchor{library/doctest doctest TestResults}@anchor{45a7}
@deffn {クラス} doctest.TestResults (failed, attempted)

@geindex failed (doctest.TestResults の属性)
@anchor{library/doctest doctest TestResults failed}@anchor{45a8}
@deffn {の属性} failed

Number of failed tests.
@end deffn

@geindex attempted (doctest.TestResults の属性)
@anchor{library/doctest doctest TestResults attempted}@anchor{45a9}
@deffn {の属性} attempted

Number of attempted tests.
@end deffn

@geindex skipped (doctest.TestResults の属性)
@anchor{library/doctest doctest TestResults skipped}@anchor{4f0}
@deffn {の属性} skipped

Number of skipped tests.


Added in version 3.13.

@end deffn
@end deffn

@node DocTestRunner オブジェクト,OutputChecker オブジェクト,TestResults objects,拡張 API
@anchor{library/doctest doctest-doctestrunner}@anchor{45aa}@anchor{library/doctest doctestrunner-objects}@anchor{45ab}
@subsubsection DocTestRunner オブジェクト


@geindex DocTestRunner (doctest のクラス)
@anchor{library/doctest doctest DocTestRunner}@anchor{457b}
@deffn {クラス} doctest.DocTestRunner (checker=None, verbose=None, optionflags=0)

@ref{1a29,,DocTest} 内の対話モード実行例を実行し、検証する際に用いられる処理クラスです。

The comparison between expected outputs and actual outputs is done by an
@ref{457a,,OutputChecker}.  This comparison may be customized with a number of
option flags; see section @ref{1134,,オプションフラグ} for more information.  If the
option flags are insufficient, then the comparison may also be customized by
passing a subclass of @code{OutputChecker} to the constructor.

The test runner's display output can be controlled in two ways. First, an output
function can be passed to @ref{4ee,,run()}; this function will be called
with strings that should be displayed.  It defaults to @code{sys.stdout.write}.  If
capturing the output is not sufficient, then the display output can be also
customized by subclassing DocTestRunner, and overriding the methods
@ref{45ac,,report_start()}, @ref{45ad,,report_success()},
@ref{45ae,,report_unexpected_exception()}, and @ref{45af,,report_failure()}.

オプションのキーワード引数 `checker' には、 @ref{457a,,OutputChecker} オブジェクト (またはその代替となるオブジェクト) を指定します。このオブジェクトは doctest 実行例の期待する出力と実際の出力との比較を行う際に使われます。

オプションのキーワード引数 `verbose' は、 @ref{457b,,DocTestRunner} の出すメッセージの冗長性を制御します。 `verbose' が @code{True} の場合、各実行例を実行する都度、その実行例についての情報を出力します。 `verbose' が @code{False} の場合、テストの失敗だけを出力します。 `verbose' を指定しない場合や @code{None} を指定した場合、コマンドラインスイッチ @code{-v} を使った場合にのみ `verbose' 出力を適用します。

オプションのキーワード引数 `optionflags' を使うと、テストランナーが期待される出力と実際の出力を比較する方法や、テストの失敗を表示する方法を制御できます。詳しくは @ref{1134,,オプションフラグ} 節を参照してください。

The test runner accumulates statistics. The aggregated number of attempted,
failed and skipped examples is also available via the @ref{45b0,,tries},
@ref{45b1,,failures} and @ref{4ef,,skips} attributes. The @ref{4ee,,run()} and
@ref{4585,,summarize()} methods return a @ref{45a7,,TestResults} instance.

@ref{457b,,DocTestRunner} defines the following methods:

@geindex report_start() (doctest.DocTestRunner のメソッド)
@anchor{library/doctest doctest DocTestRunner report_start}@anchor{45ac}
@deffn {メソッド} report_start (out, test, example)

テストランナーが実行例を処理しようとしているときにレポートを出力します。 @ref{457b,,DocTestRunner} の出力をサブクラスでカスタマイズできるようにするためのメソッドです。直接呼び出してはなりません。

`example' is the example about to be processed.  `test' is the test
containing `example'.  `out' is the output function that was passed to
@ref{4ee,,DocTestRunner.run()}.
@end deffn

@geindex report_success() (doctest.DocTestRunner のメソッド)
@anchor{library/doctest doctest DocTestRunner report_success}@anchor{45ad}
@deffn {メソッド} report_success (out, test, example, got)

与えられた実行例が正しく動作したことを報告します。このメソッドは @ref{457b,,DocTestRunner} のサブクラスで出力をカスタマイズできるようにするために提供されています; 直接呼び出してはなりません。

`example' は処理する実行例です。 `got' は実行例から実際に得られた出力です。 `test' は `example' の入っているテストです。 `out' は出力用の関数で、 @ref{4ee,,DocTestRunner.run()} に渡されます。
@end deffn

@geindex report_failure() (doctest.DocTestRunner のメソッド)
@anchor{library/doctest doctest DocTestRunner report_failure}@anchor{45af}
@deffn {メソッド} report_failure (out, test, example, got)

与えられた実行例が正しく動作しなかったことを報告します。このメソッドは @ref{457b,,DocTestRunner} のサブクラスで出力をカスタマイズできるようにするために提供されています; 直接呼び出してはなりません。

`example' は処理する実行例です。 `got' は実行例から実際に得られた出力です。 `test' は `example' の入っているテストです。 `out' は出力用の関数で、 @ref{4ee,,DocTestRunner.run()} に渡されます。
@end deffn

@geindex report_unexpected_exception() (doctest.DocTestRunner のメソッド)
@anchor{library/doctest doctest DocTestRunner report_unexpected_exception}@anchor{45ae}
@deffn {メソッド} report_unexpected_exception (out, test, example, exc_info)

与えられた実行例が期待とは違う例外を送出したことを報告します。このメソッドは @ref{457b,,DocTestRunner} のサブクラスで出力をカスタマイズできるようにするために提供されています; 直接呼び出してはなりません。

`example' は処理する実行例です。 `exc_info' には予期せず送出された例外の情報を入れたタプル (@ref{89a,,sys.exc_info()} の返す内容) になります。 `test' は `example' の入っているテストです。 `out' は出力用の関数で、 @ref{4ee,,DocTestRunner.run()} に渡されます。
@end deffn

@geindex run() (doctest.DocTestRunner のメソッド)
@anchor{library/doctest doctest DocTestRunner run}@anchor{4ee}
@deffn {メソッド} run (test, compileflags=None, out=None, clear_globs=True)

Run the examples in `test' (a @ref{1a29,,DocTest} object), and display the
results using the writer function `out'. Return a @ref{45a7,,TestResults}
instance.

実行例は名前空間 @code{test.globs} の下で実行されます。`clear_globs' が真 (デフォルト) の場合、名前空間はテストの実行後に消去され、ガベージコレクションを促します。テストの実行完了後にその内容を調べたければ、`clear_globs=False' としてください。

`compileflags' には、実行例を実行する際に Python コンパイラに適用するフラグセットを指定します。`compileflags' を指定しない場合、デフォルト値は `globs' で適用されている future-import フラグセットになります。

The output of each example is checked using the @ref{457b,,DocTestRunner}'s
output checker, and the results are formatted by the
@code{DocTestRunner.report_*()} methods.
@end deffn

@geindex summarize() (doctest.DocTestRunner のメソッド)
@anchor{library/doctest doctest DocTestRunner summarize}@anchor{4585}
@deffn {メソッド} summarize (verbose=None)

Print a summary of all the test cases that have been run by this DocTestRunner,
and return a @ref{45a7,,TestResults} instance.

オプションの `verbose' 引数を使うと、どのくらいサマリを詳しくするかを制御できます。冗長度を指定しない場合、 @ref{457b,,DocTestRunner} 自体の冗長度を使います。
@end deffn

@ref{456c,,DocTestParser} has the following attributes:

@geindex tries (doctest.DocTestRunner の属性)
@anchor{library/doctest doctest DocTestRunner tries}@anchor{45b0}
@deffn {の属性} tries

Number of attempted examples.
@end deffn

@geindex failures (doctest.DocTestRunner の属性)
@anchor{library/doctest doctest DocTestRunner failures}@anchor{45b1}
@deffn {の属性} failures

Number of failed examples.
@end deffn

@geindex skips (doctest.DocTestRunner の属性)
@anchor{library/doctest doctest DocTestRunner skips}@anchor{4ef}
@deffn {の属性} skips

Number of skipped examples.


Added in version 3.13.

@end deffn
@end deffn

@node OutputChecker オブジェクト,,DocTestRunner オブジェクト,拡張 API
@anchor{library/doctest doctest-outputchecker}@anchor{45b2}@anchor{library/doctest outputchecker-objects}@anchor{45b3}
@subsubsection OutputChecker オブジェクト


@geindex OutputChecker (doctest のクラス)
@anchor{library/doctest doctest OutputChecker}@anchor{457a}
@deffn {クラス} doctest.OutputChecker

doctest 実行例を実際に実行したときの出力が期待する出力と一致するかどうかをチェックするために使われるクラスです。
@ref{457a,,OutputChecker} では、与えられた二つの出力を比較して、一致する場合には @code{True} を返す @ref{45b4,,check_output()} と、二つの出力間の違いを説明する文字列を返す @ref{45b5,,output_difference()} の、二つのメソッドがあります。

@ref{457a,,OutputChecker} では以下のメソッドを定義しています:

@geindex check_output() (doctest.OutputChecker のメソッド)
@anchor{library/doctest doctest OutputChecker check_output}@anchor{45b4}
@deffn {メソッド} check_output (want, got, optionflags)

実行例から実際に得られた出力 (`got') と、期待する出力 (`want') が一致する場合にのみ @code{True} を返します。二つの文字列がまったく同一の場合には常に一致するとみなしますが、テストランナーの使っているオプションフラグにより、厳密には同じ内容になっていなくても一致するとみなす場合もあります。オプションフラグについての詳しい情報は @ref{1134,,オプションフラグ} 節を参照してください。
@end deffn

@geindex output_difference() (doctest.OutputChecker のメソッド)
@anchor{library/doctest doctest OutputChecker output_difference}@anchor{45b5}
@deffn {メソッド} output_difference (example, got, optionflags)

与えられた実行例 (`example') の期待する出力と、実際に得られた出力 (`got') の間の差異を解説している文字列を返します。`optionflags' は `want' と `got' を比較する際に使われるオプションフラグのセットです。
@end deffn
@end deffn

@node デバッグ,アドバイス,拡張 API,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest debugging}@anchor{45b6}@anchor{library/doctest doctest-debugging}@anchor{45b7}
@subsubsection デバッグ


@ref{3e,,doctest} では、doctest 実行例をデバッグするメカニズムをいくつか提供しています:


@itemize *

@item 
doctest を実行可能な Python プログラムに変換し、 Python デバッガ @ref{aa,,pdb} で実行できるようにするための関数がいくつかあります。

@item 
@ref{457b,,DocTestRunner} のサブクラス @ref{45b8,,DebugRunner} クラスがあります。このクラスは、最初に失敗した実行例に対して例外を送出します。例外には実行例に関する情報が入っています。この情報は実行例の検死デバッグに利用できます。

@item 
@ref{ff4,,DocTestSuite()} の生成する @ref{10c,,unittest} テストケースは、 @ref{45b9,,debug()} メソッドをサポートしています。 @ref{45b9,,debug()} は @ref{2b3,,unittest.TestCase} で定義されています。

@item 
@ref{272,,pdb.set_trace()} を doctest 実行例の中で呼び出しておけば、その行が実行されたときに Python デバッガが組み込まれます。デバッガを組み込んだあとは、変数の現在の値などを調べられます。たとえば、以下のようなモジュールレベルの docstring の入ったファイル @code{a.py} があるとします:

@example
"""
>>> def f(x):
...     g(x*2)
>>> def g(x):
...     print(x+3)
...     import pdb; pdb.set_trace()
>>> f(3)
9
"""
@end example

対話セッションは以下のようになるでしょう:

@example
>>> import a, doctest
>>> doctest.testmod(a)
--Return--
> <doctest a[1]>(3)g()->None
-> import pdb; pdb.set_trace()
(Pdb) list
  1     def g(x):
  2         print(x+3)
  3  ->     import pdb; pdb.set_trace()
[EOF]
(Pdb) p x
6
(Pdb) step
--Return--
> <doctest a[0]>(2)f()->None
-> g(x*2)
(Pdb) list
  1     def f(x):
  2  ->     g(x*2)
[EOF]
(Pdb) p x
3
(Pdb) step
--Return--
> <doctest a[2]>(1)?()->None
-> f(3)
(Pdb) cont
(0, 3)
>>>
@end example
@end itemize

以下は、doctest を Python コードに変換して、できたコードをデバッガ下で実行できるようにするための関数です:

@geindex script_from_examples() (doctest モジュール)
@anchor{library/doctest doctest script_from_examples}@anchor{45ba}
@deffn {の関数} doctest.script_from_examples (s)

実行例の入ったテキストをスクリプトに変換します。

引数 `s' は doctest 実行例の入った文字列です。この文字列は Python スクリプトに変換され、その中では `s' の doctest 実行例が通常のコードに、それ以外は Python のコメント文になります。生成したスクリプトを文字列で返します。例えば、

@example
import doctest
print(doctest.script_from_examples(r"""
    Set x and y to 1 and 2.
    >>> x, y = 1, 2

    Print their sum:
    >>> print(x+y)
    3
"""))
@end example

は:

@example
# Set x and y to 1 and 2.
x, y = 1, 2
#
# Print their sum:
print(x+y)
# Expected:
## 3
@end example

この関数は内部的に他の関数から使われていますが (下記参照)、対話セッションを Python スクリプトに変換したいような場合にも便利でしょう。
@end deffn

@geindex testsource() (doctest モジュール)
@anchor{library/doctest doctest testsource}@anchor{45bb}
@deffn {の関数} doctest.testsource (module, name)

あるオブジェクトの doctest をスクリプトに変換します。

Argument `module' is a module object, or dotted name of a module, containing the
object whose doctests are of interest.  Argument `name' is the name (within the
module) of the object with the doctests of interest.  The result is a string,
containing the object's docstring converted to a Python script, as described for
@ref{45ba,,script_from_examples()} above.  For example, if module @code{a.py}
contains a top-level function @code{f()}, then

@example
import a, doctest
print(doctest.testsource(a, "a.f"))
@end example

prints a script version of function @code{f()}'s docstring, with doctests
converted to code, and the rest placed in comments.
@end deffn

@geindex debug() (doctest モジュール)
@anchor{library/doctest doctest debug}@anchor{45b9}
@deffn {の関数} doctest.debug (module, name, pm=False)

オブジェクトの持つ doctest をデバッグします。

`module' および `name' 引数は上の @ref{45bb,,testsource()} と同じです。指定したオブジェクトの docstring から合成された Python スクリプトは一時ファイルに書き出され、その後 Python デバッガ @ref{aa,,pdb} の制御下で実行されます。

ローカルおよびグローバルの実行コンテキストには、@code{module.__dict__} の浅いコピーが使われます。

オプション引数 `pm' は、検死デバッグを行うかどうかを指定します。 `pm' が真の場合、スクリプトファイルは直接実行され、スクリプトが送出した例外が処理されないまま終了した場合にのみデバッガが立ち入ります。その場合、 @ref{15f3,,pdb.post_mortem()} によって検死デバッグを起動し、処理されなかった例外から得られたトレースバックオブジェクトを渡します。 `pm' を指定しないか値を偽にした場合、 @ref{45bc,,pdb.run()} に適切な @ref{4a2,,exec()} 呼び出しを渡して、最初からデバッガの下でスクリプトを実行します。
@end deffn

@geindex debug_src() (doctest モジュール)
@anchor{library/doctest doctest debug_src}@anchor{45bd}
@deffn {の関数} doctest.debug_src (src, pm=False, globs=None)

文字列中の doctest をデバッグします。

上の @ref{45b9,,debug()} に似ていますが、doctest の入った文字列は `src' 引数で直接指定します。

オプション引数 `pm' は上の @ref{45b9,,debug()} と同じ意味です。

オプション引数 `globs' には、ローカルおよびグローバルな実行コンテキストの両方に使われる辞書を指定します。`globs' を指定しない場合や @code{None} にした場合、空の辞書を使います。辞書を指定した場合、実際の実行コンテキストには浅いコピーが使われます。
@end deffn

@ref{45b8,,DebugRunner} クラス自体や @ref{45b8,,DebugRunner} クラスが送出する特殊な例外は、テストフレームワークの作者にとって非常に興味のあるところですが、ここでは概要しか述べられません。詳しくはソースコード、とりわけ @ref{45b8,,DebugRunner} の docstring (それ自体 doctest です!) を参照してください:

@geindex DebugRunner (doctest のクラス)
@anchor{library/doctest doctest DebugRunner}@anchor{45b8}
@deffn {クラス} doctest.DebugRunner (checker=None, verbose=None, optionflags=0)

テストの失敗に遭遇するとすぐに例外を送出するようになっている @ref{457b,,DocTestRunner} のサブクラスです。予期しない例外が生じると、 @ref{45be,,UnexpectedException} 例外を送出します。この例外には、テスト、実行例、もともと送出された例外が入っています。期待する出力と実際の出力が一致しないために失敗した場合には、 @ref{45bf,,DocTestFailure} 例外を送出します。この例外には、テスト、実行例、実際の出力が入っています。

コンストラクタのパラメータやメソッドについては、 @ref{458f,,拡張 API} 節の @ref{457b,,DocTestRunner} のドキュメントを参照してください。
@end deffn

@ref{45b8,,DebugRunner} インスタンスの送出する例外には以下の二つがあります:

@geindex DocTestFailure
@anchor{library/doctest doctest DocTestFailure}@anchor{45bf}
@deffn {例外} doctest.DocTestFailure (test, example, got)

doctest 実行例の実際の出力が期待する出力と一致しなかったことを示すために @ref{457b,,DocTestRunner} が送出する例外です。コンストラクタの引数は、インスタンスの同名の属性を初期化するために使われます。
@end deffn

@ref{45bf,,DocTestFailure} では以下の属性を定義しています:

@geindex test (doctest.DocTestFailure の属性)
@anchor{library/doctest doctest DocTestFailure test}@anchor{45c0}
@deffn {の属性} DocTestFailure.test

実行例が失敗した時に実行されていた @ref{1a29,,DocTest} オブジェクトです。
@end deffn

@geindex example (doctest.DocTestFailure の属性)
@anchor{library/doctest doctest DocTestFailure example}@anchor{45c1}
@deffn {の属性} DocTestFailure.example

失敗した @ref{4590,,Example} オブジェクトです。
@end deffn

@geindex got (doctest.DocTestFailure の属性)
@anchor{library/doctest doctest DocTestFailure got}@anchor{45c2}
@deffn {の属性} DocTestFailure.got

実行例の実際の出力です。
@end deffn

@geindex UnexpectedException
@anchor{library/doctest doctest UnexpectedException}@anchor{45be}
@deffn {例外} doctest.UnexpectedException (test, example, exc_info)

doctest 実行例が予期しない例外を送出したことを示すために @ref{457b,,DocTestRunner} が送出する例外です。コンストラクタの引数は、インスタンスの同名の属性を初期化するために使われます。
@end deffn

@ref{45be,,UnexpectedException} では以下の属性を定義しています:

@geindex test (doctest.UnexpectedException の属性)
@anchor{library/doctest doctest UnexpectedException test}@anchor{45c3}
@deffn {の属性} UnexpectedException.test

実行例が失敗した時に実行されていた @ref{1a29,,DocTest} オブジェクトです。
@end deffn

@geindex example (doctest.UnexpectedException の属性)
@anchor{library/doctest doctest UnexpectedException example}@anchor{45c4}
@deffn {の属性} UnexpectedException.example

失敗した @ref{4590,,Example} オブジェクトです。
@end deffn

@geindex exc_info (doctest.UnexpectedException の属性)
@anchor{library/doctest doctest UnexpectedException exc_info}@anchor{45c5}
@deffn {の属性} UnexpectedException.exc_info

予期しない例外についての情報の入ったタプルで、 @ref{89a,,sys.exc_info()} が返すのと同じものです。
@end deffn

@node アドバイス,,デバッグ,doctest --- 対話型の Python の例をテストする
@anchor{library/doctest doctest-soapbox}@anchor{45c6}@anchor{library/doctest soapbox}@anchor{45c7}
@subsubsection アドバイス


As mentioned in the introduction, @code{doctest} has grown to have three primary
uses:


@enumerate 

@item 
docstring 内の実行例をチェックする。

@item 
回帰テストを行う。

@item 
実行可能なドキュメント/読めるテストの実現。
@end enumerate

これらの用途にはそれぞれ違った要求があるので、区別して考えるのが重要です。特に、docstring を曖昧なテストケースに埋もれさせてしまうとドキュメントとしては最悪です。

When writing a docstring, choose docstring examples with care. There's an art to
this that needs to be learned---it may not be natural at first.  Examples should
add genuine value to the documentation.  A good example can often be worth many
words. If done with care, the examples will be invaluable for your users, and
will pay back the time it takes to collect them many times over as the years go
by and things change.  I'm still amazed at how often one of my @code{doctest}
examples stops working after a "harmless" change.

説明テキストの作成をけちらなければ、@ref{3e,,doctest} は回帰テストの優れたツールにもなり得ます。説明文と実行例を交互に記述していけば、実際に何をどうしてテストしているのかもっと簡単に把握できるようになるでしょう。もちろん、コードベースのテストに詳しくコメントを入れるのも手ですが、そんなことをするプログラマはほとんどいません。多くの人々が、@ref{3e,,doctest} のアプローチをとった方がきれいにテストを書けると気づいています。おそらく、これは単にコード中にコメントを書くのが少し面倒だからという理由でしょう。私はもう少し穿った見方もしています。doctest ベースのテストを書くときの自然な態度は、自分のソフトウェアのよい点を説明しようとして、実行例を使って説明しようとするときの態度そのものだからだ、という理由です。それゆえに、テストファイルは自然と単純な機能の解説から始め、論理的により複雑で境界条件的なケースに進むような形になります。結果的に、一見ランダムに見えるような個別の機能をテストしている個別の関数の集まりではなく、首尾一貫した説明ができるようになるのです。@ref{3e,,doctest} によるテストの作成はまったく別の取り組み方であり、テストと説明の区別をなくして、まったく違う結果を生み出すのです。

回帰テストは特定のオブジェクトやファイルにまとめておくのがよいでしょう。回帰テストの組み方にはいくつか選択肢があります:


@itemize *

@item 
テストケースを対話モードの実行例にして入れたテキストファイルを書き、 @ref{455b,,testfile()} や @ref{458a,,DocFileSuite()} を使ってそのファイルをテストします。この方法をお勧めします。最初から doctest を使うようにしている新たなプロジェクトでは、この方法が一番簡単です。

@item 
@code{_regrtest_topic} という名前の関数を定義します。この関数には、あるトピックに対応するテストケースの入った docstring が一つだけ入っています。この関数はモジュールと同じファイルの中にも置けますし、別のテストファイルに分けてもかまいません。

@item 
Define a @ref{4567,,__test__} dictionary mapping from regression test topics to
docstrings containing test cases.
@end itemize

テストコードをモジュールに組み込むことで、そのモジュールは、モジュール自身がテストランナーになることができます。テストが失敗した場合には、問題箇所をデバッグする際に、失敗したdoctestだけを再度実行することで、作成したテストランナーを修正することができます。これがこのようなテストランナーの最小例となります。

@example
if __name__ == '__main__':
    import doctest
    flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
    if len(sys.argv) > 1:
        name = sys.argv[1]
        if name in globals():
            obj = globals()[name]
        else:
            obj = __test__[name]
        doctest.run_docstring_examples(obj, globals(), name=name,
                                       optionflags=flags)
    else:
        fail, total = doctest.testmod(optionflags=flags)
        print(f"@{fail@} failures out of @{total@} tests")
@end example

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node unittest --- ユニットテストフレームワーク,unittest mock --- モックオブジェクトライブラリ,doctest --- 対話型の Python の例をテストする,開発ツール
@anchor{library/unittest doc}@anchor{45c8}@anchor{library/unittest module-unittest}@anchor{10c}@anchor{library/unittest translation-repo}@anchor{45c9}@anchor{library/unittest unittest-unit-testing-framework}@anchor{45ca}
@subsection @code{unittest} --- ユニットテストフレームワーク


@geindex module; unittest

`ソースコード:' Lib/unittest/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/unittest/__init__.py}


__________________________________________________________________


(すでにテストの基本概念について詳しいようでしたら、この部分をとばして @ref{45cb,,アサートメソッド一覧} に進むと良いでしょう。)

The @code{unittest} unit testing framework was originally inspired by JUnit
and has a similar flavor as major unit testing frameworks in other
languages.  It supports test automation, sharing of setup and shutdown code
for tests, aggregation of tests into collections, and independence of the
tests from the reporting framework.

To achieve this, @code{unittest} supports some important concepts in an
object-oriented way:


@table @asis

@item テストフィクスチャ (test fixture)

テストフィクスチャ (`test fixture') とは、テスト実行のために必要な準備や終了処理を指します。例: テスト用データベースの作成・ディレクトリ・サーバプロセスの起動など。

@item テストケース (test case)

A `test case' is the individual unit of testing.  It checks for a specific
response to a particular set of inputs.  @code{unittest} provides a base class,
@ref{2b3,,TestCase}, which may be used to create new test cases.

@item テストスイート (test suite)

テストスイート (`test suite') はテストケースとテストスイートの集まりで、同時に実行しなければならないテストをまとめる場合に使用します。

@item テストランナー (test runner)

テストランナー (`test runner') はテストの実行を管理し結果を提供する要素です。ランナーはグラフィカルインターフェースやテキストインターフェースを使用しても構いませんし、テストの実行結果を示す特別な値を返しても構いません。
@end table


@subsubheading 参考



@table @asis

@item @ref{3e,,doctest} モジュール

テストをサポートするもうひとつのモジュールで、このモジュールとは趣きがだいぶ異なります。

@item Simple Smalltalk Testing: With Patterns@footnote{https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm}

Kent Beck's original paper on testing frameworks using the pattern shared
by @code{unittest}.

@item pytest@footnote{https://docs.pytest.org/}

サードパーティのユニットテストフレームワークでより軽量な構文でテストを書くことができます。例えば、@code{assert func(10) == 42}  のように書きます。

@item The Python Testing Tools Taxonomy@footnote{https://wiki.python.org/moin/PythonTestingToolsTaxonomy}

多くの Python のテストツールが一覧で紹介されています。ファンクショナルテストのフレームワークやモックライブラリも掲載されています。

@item Testing in Python メーリングリスト@footnote{http://lists.idyll.org/listinfo/testing-in-python}

Python でテストやテストツールについての議論に特化したグループです。
@end table

Python のソースコード配布物にあるスクリプト @code{Tools/unittestgui/unittestgui.py} はテストディスカバリとテスト実行のための GUI ツールです。
主な目的は単体テストの初心者が簡単に使えるようにすることです。
実際の生産環境では、 Buildbot@footnote{https://buildbot.net/}, Jenkins@footnote{https://www.jenkins.io/} 、 GitHub Actions@footnote{https://github.com/features/actions}, AppVeyor@footnote{https://www.appveyor.com/} のような継続的インテグレーションシステムでテストを実行することを推奨します。


@menu
* 基本的な例: 基本的な例<2>. 
* コマンドラインインターフェイス: コマンドラインインターフェイス<2>. 
* テストディスカバリ:: 
* テストコードの構成:: 
* 既存テストコードの再利用:: 
* テストのスキップと予期された失敗:: 
* サブテストを利用して繰り返しテストの区別を付ける:: 
* クラスと関数:: 
* クラスとモジュールのフィクスチャ:: 
* シグナルハンドリング:: 

@end menu

@node 基本的な例<2>,コマンドラインインターフェイス<2>,,unittest --- ユニットテストフレームワーク
@anchor{library/unittest basic-example}@anchor{45cc}@anchor{library/unittest unittest-minimal-example}@anchor{45cd}
@subsubsection 基本的な例


The @code{unittest} module provides a rich set of tools for constructing and
running tests.  This section demonstrates that a small subset of the tools
suffice to meet the needs of most users.

以下は、三つの文字列メソッドをテストするスクリプトです:

@example
import unittest

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if __name__ == '__main__':
    unittest.main()
@end example

テストケースは、 @ref{2b3,,unittest.TestCase} のサブクラスとして作成します。メソッド名が @code{test} で始まる三つのメソッドがテストです。テストランナーはこの命名規約によってテストを行うメソッドを検索します。

これらのテスト内では、予定の結果が得られていることを確かめるために @ref{74c,,assertEqual()} を、条件のチェックに @ref{74a,,assertTrue()} や @ref{74b,,assertFalse()} を、例外が発生する事を確認するために @ref{750,,assertRaises()} をそれぞれ呼び出しています。 @ref{b60,,assert} 文の代わりにこれらのメソッドを使用すると、テストランナーでテスト結果を集計してレポートを作成する事ができます。

@ref{1551,,setUp()} および @ref{1552,,tearDown()} メソッドによって各テストメソッドの前後に実行する命令を実装することが出来ます。
詳細は @ref{45ce,,テストコードの構成} を参照してください。

最後のブロックは簡単なテストの実行方法を示しています。 @ref{11e5,,unittest.main()} は、テストスクリプトのコマンドライン用インターフェースを提供します。コマンドラインから起動された場合、上記のスクリプトは以下のような結果を出力します:

@example
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK
@end example

@code{-v} オプションをテストスクリプトに渡すことで @ref{11e5,,unittest.main()} はより冗長になり、以下のような出力をします:

@example
test_isupper (__main__.TestStringMethods.test_isupper) ... ok
test_split (__main__.TestStringMethods.test_split) ... ok
test_upper (__main__.TestStringMethods.test_upper) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK
@end example

The above examples show the most commonly used @code{unittest} features which
are sufficient to meet many everyday testing needs.  The remainder of the
documentation explores the full feature set from first principles.


バージョン 3.11 で変更: テストメソッドが（デフォルトの`@w{`}None`@w{`}以外の）戻り値を返す挙動は現在非推奨です。


@node コマンドラインインターフェイス<2>,テストディスカバリ,基本的な例<2>,unittest --- ユニットテストフレームワーク
@anchor{library/unittest command-line-interface}@anchor{45cf}@anchor{library/unittest unittest-command-line-interface}@anchor{1136}
@subsubsection コマンドラインインターフェイス


ユニットテストモジュールはコマンドラインから使って、モジュール、クラス、あるいは個別のテストメソッドで定義されたテストを実行することが出来ます:

@example
python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method
@end example

モジュール名ならびに完全修飾されたクラス名やメソッド名の任意の組み合わせを一覧で渡すことが出来ます。

テストモジュールはファイルパスで指定することも出来ます:

@example
python -m unittest tests/test_something.py
@end example

そのため、テストモジュールを指定するのにシェルのファイル名補完が使えます。指定されたファイルはやはりモジュールとしてインポート可能でなければなりません。パスから '.py' を取り除き、パスセパレータを '.' に置き換えることでモジュール名に変換されます。モジュールとしてインポート可能でないテストファイルを実行したい場合は、代わりにそのファイルを直接実行するのが良いでしょう。

テスト実行時に (より冗長な) 詳細を表示するには -v フラグを渡します:

@example
python -m unittest -v test_module
@end example

引数無しで実行すると @ref{45d0,,テストディスカバリ} が開始されます:

@example
python -m unittest
@end example

コマンドラインプションの一覧を表示するには以下のコマンドを実行します:

@example
python -m unittest -h
@end example


バージョン 3.2 で変更: 以前のバージョンでは、個々のテストメソッドしか実行することができず、モジュール単位やクラス単位で実行することは不可能でした。



Added in version 3.14: Output is colorized by default and can be
@ref{1b7,,controlled using environment variables}.


@menu
* コマンドラインオプション: コマンドラインオプション<5>. 

@end menu

@node コマンドラインオプション<5>,,,コマンドラインインターフェイス<2>
@anchor{library/unittest command-line-options}@anchor{45d1}
@subsubsection コマンドラインオプション


@code{unittest} には以下のコマンドラインオプションがあります:

@geindex unittest コマンドラインオプション; -b
@geindex unittest コマンドラインオプション; --buffer
@anchor{library/unittest cmdoption-unittest-b}@anchor{1549}@anchor{library/unittest cmdoption-unittest-buffer}@anchor{45d2}
@deffn {Option} @w{-}b, @w{-}@w{-}buffer

標準出力と標準エラーのストリームをテストの実行中にバッファします。テストが成功している間は結果の出力は破棄されます。テストの失敗やエラーの場合、出力は通常通り表示され、エラーメッセージに追加されます。
@end deffn

@geindex unittest コマンドラインオプション; -c
@geindex unittest コマンドラインオプション; --catch
@anchor{library/unittest cmdoption-unittest-c}@anchor{154a}@anchor{library/unittest cmdoption-unittest-catch}@anchor{45d3}
@deffn {Option} @w{-}c, @w{-}@w{-}catch

@code{Control}-@code{C} を実行中のテストが終了するまで遅延させ、そこまでの結果を出力します。二回目の @code{Control}-@code{C} は、通常通り @ref{bc5,,KeyboardInterrupt} の例外を発生させます。

この機能の仕組みについては、@ref{45d4,,シグナルハンドリング} を参照してください。
@end deffn

@geindex unittest コマンドラインオプション; -f
@geindex unittest コマンドラインオプション; --failfast
@anchor{library/unittest cmdoption-unittest-f}@anchor{154c}@anchor{library/unittest cmdoption-unittest-failfast}@anchor{45d5}
@deffn {Option} @w{-}f, @w{-}@w{-}failfast

初回のエラーもしくは失敗の時にテストを停止します。
@end deffn

@geindex unittest コマンドラインオプション; -k
@anchor{library/unittest cmdoption-unittest-k}@anchor{45d6}
@deffn {Option} @w{-}k

パターンや部分文字列にマッチするテストメソッドとテストクラスのみ実行します。このオプションは複数回使うことができ、その場合はすべてのパターンにマッチするテストケースが実行対象に含まれます。

ワイルドカード(@code{*}) を含むパターンは @ref{1c55,,fnmatch.fnmatchcase()} を使用してテスト名と照合され、それ以外の場合は単純な大文字と小文字を区別した部分文字列マッチングが使用されます。

パターンは、テストローダがインポートする時の完全修飾されたテストメソッド名と照合されます。

たとえば、 @code{-k foo} は @code{foo_tests.SomeTest.test_something}, @code{bar_tests.SomeTest.test_foo} にマッチし、 @code{bar_tests.FooTest.test_something} はマッチしません。
@end deffn

@geindex unittest コマンドラインオプション; --locals
@anchor{library/unittest cmdoption-unittest-locals}@anchor{45d7}
@deffn {Option} @w{-}@w{-}locals

トレースバック内の局所変数を表示します。
@end deffn

@geindex unittest コマンドラインオプション; --durations
@anchor{library/unittest cmdoption-unittest-durations}@anchor{45d8}
@deffn {Option} @w{-}@w{-}durations N

Show the N slowest test cases (N=0 for all).
@end deffn


Added in version 3.2: コマンドラインオプションの @code{-b}、@code{-c}、@code{-f} が追加されました。



Added in version 3.5: コマンドラインオプション @code{--locals}。



Added in version 3.7: コマンドラインオプション @code{-k}。



Added in version 3.12: コマンドラインオプション @code{--durations}。


コマンドラインによってテストディスカバリ、すなわちプロジェクトの全テストを実行したりサブセットのみを実行したりすることも出来ます。

@node テストディスカバリ,テストコードの構成,コマンドラインインターフェイス<2>,unittest --- ユニットテストフレームワーク
@anchor{library/unittest test-discovery}@anchor{45d9}@anchor{library/unittest unittest-test-discovery}@anchor{45d0}
@subsubsection テストディスカバリ



Added in version 3.2.


unittest はシンプルなテストディスカバリをサポートします。このテストディスカバリに対応するために、テストが定義された全ファイルは @ref{203e,,modules} もしくは @ref{204e,,packages} としてプロジェクトの最上位のディスカバリでインポート可能である必要があります (つまり、これらのファイルは @ref{22a0,,identifiers} として有効である必要があるということです)。

テストディスカバリは @ref{11e7,,TestLoader.discover()} で実装されていますが、コマンドラインから使う事も出来ます。その基本的な使い方は:

@example
cd project_directory
python -m unittest discover
@end example

@cartouche
@quotation 注釈 
@code{python -m unittest} は @code{python -m unittest discover} と等価なショートカットです。テストディスカバリに引数を渡したい場合は、@code{discover} サブコマンドを明示的に使用しなければなりません。
@end quotation
@end cartouche

@code{discover} サブコマンドには以下のオプションがあります:

@geindex unittest-discover コマンドラインオプション; -v
@geindex unittest-discover コマンドラインオプション; --verbose
@anchor{library/unittest cmdoption-unittest-discover-v}@anchor{45da}@anchor{library/unittest cmdoption-unittest-discover-verbose}@anchor{45db}
@deffn {Option} @w{-}v, @w{-}@w{-}verbose

詳細な出力
@end deffn

@geindex unittest-discover コマンドラインオプション; -s
@geindex unittest-discover コマンドラインオプション; --start-directory
@anchor{library/unittest cmdoption-unittest-discover-s}@anchor{45dc}@anchor{library/unittest cmdoption-unittest-discover-start-directory}@anchor{45dd}
@deffn {Option} @w{-}s, @w{-}@w{-}start@w{-}directory directory

ディスカバリを開始するディレクトリ (デフォルトは @code{.})
@end deffn

@geindex unittest-discover コマンドラインオプション; -p
@geindex unittest-discover コマンドラインオプション; --pattern
@anchor{library/unittest cmdoption-unittest-discover-p}@anchor{45de}@anchor{library/unittest cmdoption-unittest-discover-pattern}@anchor{45df}
@deffn {Option} @w{-}p, @w{-}@w{-}pattern pattern

テストファイル名を識別するパターン (デフォルトは @code{test*.py})
@end deffn

@geindex unittest-discover コマンドラインオプション; -t
@geindex unittest-discover コマンドラインオプション; --top-level-directory
@anchor{library/unittest cmdoption-unittest-discover-t}@anchor{45e0}@anchor{library/unittest cmdoption-unittest-discover-top-level-directory}@anchor{45e1}
@deffn {Option} @w{-}t, @w{-}@w{-}top@w{-}level@w{-}directory directory

プロジェクトの最上位のディスカバリのディレクトリ (デフォルトは開始のディレクトリ)
@end deffn

@ref{45dc,,-s} 、 @ref{45de,,-p} 、および @ref{45e0,,-t} オプションは、この順番であれば位置引数として渡す事ができます。以下の二つのコマンドは等価です:

@example
python -m unittest discover -s project_directory -p "*_test.py"
python -m unittest discover project_directory "*_test.py"
@end example

パスと同様にパッケージ名を、例えば @code{myproject.subpackage.test} のように、開始ディレクトリとして渡すことができます。
指定したパッケージ名はインポートされ、そのファイルシステム上の場所が開始ディレクトリとして使われます。

@cartouche
@quotation 注意 
テストディスカバリはインポートによりテストを読み込みます。
一旦テストディスカバリが指定された開始ディレクトリから全テストファイルを見付けると、パスはインポートするパッケージ名に変換されます。
例えば、 @code{foo/bar/baz.py} は @code{foo.bar.baz} としてインポートされます。

グローバルにインストールされたパッケージがあり、それとは異なるコピーでディスカバリしようとしたとき、誤った場所からインポートが行われる `かもしれません'。
その場合テストディスカバリは警告し、停止します。

ディレクトリのパスではなくパッケージ名を開始ディレクトリに指定した場合、ディスカバリはインポートするいずれの場所も意図した場所とするため、警告を受けないはずです。
@end quotation
@end cartouche

テストモジュールとパッケージは、 @ref{45e2,,load_tests プロトコル} によってテストのロードとディスカバリをカスタマイズすることができます。


バージョン 3.4 で変更: ディスカバリが @ref{2b2,,名前空間パッケージ} をサポートしました。



バージョン 3.11 で変更: Test discovery dropped the @ref{2b2,,namespace packages}
support. It has been broken since Python 3.7.
Start directory and its subdirectories containing tests must be regular
package that have @code{__init__.py} file.

If the start directory is the dotted name of the package, the ancestor packages
can be namespace packages.



バージョン 3.14 で変更: Test discovery supports @ref{2b2,,namespace package} as start directory again.
To avoid scanning directories unrelated to Python,
tests are not searched in subdirectories that do not contain @code{__init__.py}.


@node テストコードの構成,既存テストコードの再利用,テストディスカバリ,unittest --- ユニットテストフレームワーク
@anchor{library/unittest organizing-test-code}@anchor{45e3}@anchor{library/unittest organizing-tests}@anchor{45ce}
@subsubsection テストコードの構成


The basic building blocks of unit testing are `test cases' --- single
scenarios that must be set up and checked for correctness.  In @code{unittest},
test cases are represented by @ref{2b3,,unittest.TestCase} instances.
To make your own test cases you must write subclasses of
@ref{2b3,,TestCase} or use @ref{1a79,,FunctionTestCase}.

@ref{2b3,,TestCase} インスタンスのテストコードは完全に独立していなければなりません。
すなわち単独でか、他の様々なテストケースの任意の組み合わせのいずれかで実行可能でなければなりません。

最も単純な @ref{2b3,,TestCase} のサブクラスは、特定のテストコードを実行するためのテストメソッド (すなわち名前が @code{test} で始まるメソッド) を実装するだけで簡単に書くことができます:

@example
import unittest

class DefaultWidgetSizeTestCase(unittest.TestCase):
    def test_default_widget_size(self):
        widget = Widget('The widget')
        self.assertEqual(widget.size(), (50, 50))
@end example

Note that in order to test something, we use one of the @ref{45cb,,assert* methods}
provided by the @ref{2b3,,TestCase} base class.  If the test fails, an
exception will be raised with an explanatory message, and @code{unittest}
will identify the test case as a `failure'.  Any other exceptions will be
treated as `errors'.

テストは多くなり、それらの設定は繰り返しになるかもしれません。
幸いにも、@ref{1551,,setUp()} メソッドを実装することで設定コードをくくり出すことができます。
テストフレームワークは実行するテストごとに自動的に @ref{1551,,setUp()} を呼びます:

@example
import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def test_default_widget_size(self):
        self.assertEqual(self.widget.size(), (50,50),
                         'incorrect default size')

    def test_widget_resize(self):
        self.widget.resize(100,150)
        self.assertEqual(self.widget.size(), (100,150),
                         'wrong size after resize')
@end example

@cartouche
@quotation 注釈 
いろいろなテストが実行される順序は、文字列の組み込みの順序でテストメソッド名をソートすることで決まります。
@end quotation
@end cartouche

テスト中に @ref{1551,,setUp()} メソッドで例外が発生した場合、フレームワークはそのテストに問題があるとみなし、そのテストメソッドは実行されません。

同様に、テストメソッド実行後に片付けをする @ref{1552,,tearDown()} メソッドを提供出来ます:

@example
import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def tearDown(self):
        self.widget.dispose()
@end example

@ref{1551,,setUp()} が成功した場合、テストメソッドが成功したかどうかに関わらず @ref{1552,,tearDown()} が実行されます。

そのようなテストコードのための作業環境は `テストフィクスチャ (test fixture)' と呼ばれます。
新しい TestCase インスタンスはある単一のテストフィクスチャとして作成され、個々のテストメソッドを実行するのに使われます。
従って、 @ref{1551,,setUp()}, @ref{1552,,tearDown()}, @code{TestCase.__init__()} は1回のテストにつき1回だけ呼び出されます。

It is recommended that you use TestCase implementations to group tests together
according to the features they test.  @code{unittest} provides a mechanism for
this: the `test suite', represented by @code{unittest}'s
@ref{ff5,,TestSuite} class.  In most cases, calling @ref{11e5,,unittest.main()} will do
the right thing and collect all the module's test cases for you and execute
them.

しかし、テストスイートの構築をカスタマイズしたい場合、自分ですることができます:

@example
def suite():
    suite = unittest.TestSuite()
    suite.addTest(WidgetTestCase('test_default_widget_size'))
    suite.addTest(WidgetTestCase('test_widget_resize'))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())
@end example

テストケースやテストコードの定義を (@code{widget.py} のような) テスト対象コードと同じモジュールに置くことが出来ますが、テストコードを (@code{test_widget.py} のような) 独立したモジュールに置くのには以下のような利点があります:


@itemize *

@item 
テストモジュールだけをコマンドラインから独立に実行することができる。

@item 
テストコードと出荷するコードをより簡単に分ける事ができる。

@item 
余程のことがない限り、テスト対象のコードに合わせてテストコードを変更することになりにくい。

@item 
テストコードは、テスト対象コードほど頻繁に変更されない。

@item 
テストコードをより簡単にリファクタリングすることができる。

@item 
Cで書いたモジュールのテストはどうせ独立したモジュールなのだから、同様にしない理由がない

@item 
テストの方策を変更した場合でも、ソースコードを変更する必要がない。
@end itemize

@node 既存テストコードの再利用,テストのスキップと予期された失敗,テストコードの構成,unittest --- ユニットテストフレームワーク
@anchor{library/unittest legacy-unit-tests}@anchor{45e4}@anchor{library/unittest re-using-old-test-code}@anchor{45e5}
@subsubsection 既存テストコードの再利用


Some users will find that they have existing test code that they would like to
run from @code{unittest}, without converting every old test function to a
@ref{2b3,,TestCase} subclass.

For this reason, @code{unittest} provides a @ref{1a79,,FunctionTestCase} class.
This subclass of @ref{2b3,,TestCase} can be used to wrap an existing test
function.  Set-up and tear-down functions can also be provided.

以下のテストコードがあった場合:

@example
def testSomething():
    something = makeSomething()
    assert something.name is not None
    # ...
@end example

オプションの set-up と tear-down メソッドを持った同等のテストケースインスタンスは次のように作成します:

@example
testcase = unittest.FunctionTestCase(testSomething,
                                     setUp=makeSomethingDB,
                                     tearDown=deleteSomethingDB)
@end example

@cartouche
@quotation 注釈 
Even though @ref{1a79,,FunctionTestCase} can be used to quickly convert an
existing test base over to a @code{unittest}-based system, this approach is
not recommended.  Taking the time to set up proper @ref{2b3,,TestCase}
subclasses will make future test refactorings infinitely easier.
@end quotation
@end cartouche

既存のテストが @ref{3e,,doctest} を使って書かれている場合もあるでしょう。その場合、 @ref{3e,,doctest} は @ref{ff4,,DocTestSuite} クラスを提供します。このクラスは、既存の @ref{3e,,doctest}ベースのテストから、自動的に @ref{ff5,,unittest.TestSuite} のインスタンスを作成します。

@node テストのスキップと予期された失敗,サブテストを利用して繰り返しテストの区別を付ける,既存テストコードの再利用,unittest --- ユニットテストフレームワーク
@anchor{library/unittest skipping-tests-and-expected-failures}@anchor{45e6}@anchor{library/unittest unittest-skipping}@anchor{45e7}
@subsubsection テストのスキップと予期された失敗



Added in version 3.1.


unittest は特定のテストメソッドやテストクラス全体をスキップする仕組みを備えています。さらに、この機能はテスト結果を「予期された失敗 (expected failure)」とすることができ、テストが失敗しても @ref{137f,,TestResult} の失敗数にはカウントされなくなります。

テストをスキップするには、 @ref{1dbe,,skip()} @ref{93a,,デコレータ} かその条件付きバージョンの一つを使うか、@ref{1551,,setUp()} やテストメソッドの中で @ref{45e8,,TestCase.skipTest()} を呼び出すか、あるいは直接 @ref{11e6,,SkipTest} を送出するだけです。

基本的なスキップは以下のようになります:

@example
class MyTestCase(unittest.TestCase):

    @@unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @@unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass

    def test_maybe_skipped(self):
        if not external_resource_available():
            self.skipTest("external resource not available")
        # test code that depends on the external resource
        pass
@end example

このサンプルを冗長モードで実行すると以下のように出力されます:

@example
test_format (__main__.MyTestCase.test_format) ... skipped 'not supported in this library version'
test_nothing (__main__.MyTestCase.test_nothing) ... skipped 'demonstrating skipping'
test_maybe_skipped (__main__.MyTestCase.test_maybe_skipped) ... skipped 'external resource not available'
test_windows_support (__main__.MyTestCase.test_windows_support) ... skipped 'requires Windows'

----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK (skipped=4)
@end example

テストクラスは以下のようにメソッドをスキップすることができます:

@example
@@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass
@end example

@ref{1551,,TestCase.setUp()} もスキップすることができます。この機能はセットアップの対象のリソースが使用不可能な時に便利です。

予期された失敗の機能を使用するには @ref{45e9,,expectedFailure()} デコレータを使います。

@example
class ExpectedFailureTestCase(unittest.TestCase):
    @@unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")
@end example

独自のスキップ用のデコレータの作成は簡単です。 そのためには、独自のデコレータのスキップしたい時点で @ref{1dbe,,skip()} を呼び出します。 以下のデコレータはオブジェクトに指定した属性が無い場合にテストをスキップします:

@example
def skipUnlessHasattr(obj, attr):
    if hasattr(obj, attr):
        return lambda func: func
    return unittest.skip("@{!r@} doesn't have @{!r@}".format(obj, attr))
@end example

以下のデコレータと例外はテストのスキップと予期された失敗を実装しています:

@geindex skip() (unittest モジュール)
@anchor{library/unittest unittest skip}@anchor{1dbe}
@deffn {の関数} @@unittest.skip (reason)

デコレートしたテストを無条件でスキップします。`reason' にはテストをスキップした理由を記載します。
@end deffn

@geindex skipIf() (unittest モジュール)
@anchor{library/unittest unittest skipIf}@anchor{45ea}
@deffn {の関数} @@unittest.skipIf (condition, reason)

`condition' が真の場合、デコレートしたテストをスキップします。
@end deffn

@geindex skipUnless() (unittest モジュール)
@anchor{library/unittest unittest skipUnless}@anchor{45eb}
@deffn {の関数} @@unittest.skipUnless (condition, reason)

`condition' が偽の場合、デコレートしたテストをスキップします。
@end deffn

@geindex expectedFailure() (unittest モジュール)
@anchor{library/unittest unittest expectedFailure}@anchor{45e9}
@deffn {の関数} @@unittest.expectedFailure

失敗またはエラーが予測されるものとしてテストをマークします。テストが失敗するか (`test fixture' メソッドのいずれかではなく、) テスト関数そのものでエラーとなった場合に成功したとみなされます。テストが成功した場合は失敗とみなされます。
@end deffn

@geindex SkipTest
@anchor{library/unittest unittest SkipTest}@anchor{11e6}
@deffn {例外} unittest.SkipTest (reason)

この例外はテストをスキップするために送出されます。

ふつうはこれを直接送出する代わりに @ref{45e8,,TestCase.skipTest()} やスキッピングデコレータの一つを使用出来ます。
@end deffn

スキップしたテストの前後では、 @ref{1551,,setUp()} および @ref{1552,,tearDown()} は実行されません。同様に、スキップしたクラスの前後では、 @ref{c43,,setUpClass()} および @ref{154f,,tearDownClass()} は実行されません。スキップしたモジュールの前後では、 @ref{c42,,setUpModule()} および @ref{154e,,tearDownModule()} は実行されません。

@node サブテストを利用して繰り返しテストの区別を付ける,クラスと関数,テストのスキップと予期された失敗,unittest --- ユニットテストフレームワーク
@anchor{library/unittest distinguishing-test-iterations-using-subtests}@anchor{45ec}@anchor{library/unittest subtests}@anchor{11e4}
@subsubsection サブテストを利用して繰り返しテストの区別を付ける



Added in version 3.4.


テストの間にとても小さな差異がある場合（例えばいくつかのパラメータなど）、unittestでは @ref{11e3,,subTest()} コンテキストマネージャを使用してテストメソッドの内部でそれらを区別することができます。

例えば以下のテストは:

@example
class NumbersTest(unittest.TestCase):

    def test_even(self):
        """
        Test that numbers between 0 and 5 are all even.
        """
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)
@end example

以下の出力をします:

@example
======================================================================
FAIL: test_even (__main__.NumbersTest.test_even) (i=1)
Test that numbers between 0 and 5 are all even.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 11, in test_even
    self.assertEqual(i % 2, 0)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest.test_even) (i=3)
Test that numbers between 0 and 5 are all even.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 11, in test_even
    self.assertEqual(i % 2, 0)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest.test_even) (i=5)
Test that numbers between 0 and 5 are all even.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 11, in test_even
    self.assertEqual(i % 2, 0)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 1 != 0
@end example

サブテスト無しの場合、最初の失敗で実行は停止し、@code{i} の値が表示されないためエラーの原因を突き止めるのは困難になります:

@example
======================================================================
FAIL: test_even (__main__.NumbersTest.test_even)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
@end example

@node クラスと関数,クラスとモジュールのフィクスチャ,サブテストを利用して繰り返しテストの区別を付ける,unittest --- ユニットテストフレームワーク
@anchor{library/unittest classes-and-functions}@anchor{45ed}@anchor{library/unittest unittest-contents}@anchor{45ee}
@subsubsection クラスと関数


This section describes in depth the API of @code{unittest}.

@menu
* テストクラス:: 
* テストのグループ化:: 
* テストのロードと起動:: 

@end menu

@node テストクラス,テストのグループ化,,クラスと関数
@anchor{library/unittest test-cases}@anchor{45ef}@anchor{library/unittest testcase-objects}@anchor{45f0}
@subsubsection テストクラス


@geindex TestCase (unittest のクラス)
@anchor{library/unittest unittest TestCase}@anchor{2b3}
@deffn {クラス} unittest.TestCase (methodName='runTest')

Instances of the @ref{2b3,,TestCase} class represent the logical test units
in the @code{unittest} 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.

@ref{2b3,,TestCase} の各インスタンスは `methodName' という名前の単一の基底メソッドを実行します。
@ref{2b3,,TestCase} を使用する大半の場合 `methodName' を変更したりデフォルトの @code{runTest()} メソッドを再実装することはありません。


バージョン 3.2 で変更: @ref{2b3,,TestCase} が `methodName' を指定しなくてもインスタンス化できるようになりました。これにより対話的インタプリタから @ref{2b3,,TestCase} を簡単に試せるようになりました。


@ref{2b3,,TestCase} のインスタンスのメソッドは3種類のグループを提供します。
1つ目のグループはテストの実行で使用されます。
2つ目のグループは条件のチェックおよび失敗のレポートを行うテストの実装で使用されます。
3つ目のグループである問い合わせ用のメソッドによってテスト自身の情報が収集されます。

はじめのグループ (テスト実行) に含まれるメソッドは以下の通りです:

@geindex setUp() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase setUp}@anchor{1551}
@deffn {メソッド} setUp ()

テストフィクスチャの準備のために呼び出されるメソッドです。テストメソッドの直前に呼び出されます。このメソッドで @ref{8b8,,AssertionError} や @ref{11e6,,SkipTest} 以外の例外が発生した場合、テストの失敗ではなくエラーとされます。デフォルトの実装では何も行いません。
@end deffn

@geindex tearDown() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase tearDown}@anchor{1552}
@deffn {メソッド} tearDown ()

テストメソッドが実行され、結果が記録された直後に呼び出されるメソッドです。
このメソッドはテストメソッドで例外が投げられても呼び出されます。
そのため、サブクラスでこのメソッドを実装する場合は、内部状態を確認することが必要になるでしょう。
このメソッドで @ref{8b8,,AssertionError} や @ref{11e6,,SkipTest} 以外の例外が発生した場合、テストの失敗とは別のエラーとみなされます (従って報告されるエラーの総数は増えます)。
このメソッドは、テストの結果に関わらず @ref{1551,,setUp()} が成功した場合にのみ呼ばれます。
デフォルトの実装では何も行いません。
@end deffn

@geindex setUpClass() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase setUpClass}@anchor{c43}
@deffn {メソッド} setUpClass ()

個別のクラス内のテストが実行される前に呼び出されるクラスメソッドです。 @code{setUpClass} はクラスを唯一の引数として取り、 @ref{48e,,classmethod()} でデコレートされていなければなりません:

@example
@@classmethod
def setUpClass(cls):
    ...
@end example

詳しくは @ref{45f1,,クラスとモジュールのフィクスチャ} を参照してください。


Added in version 3.2.

@end deffn

@geindex tearDownClass() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase tearDownClass}@anchor{154f}
@deffn {メソッド} tearDownClass ()

個別のクラス内のテストが実行された後に呼び出されるクラスメソッドです。 @code{tearDownClass} はクラスを唯一の引数として取り、 @ref{48e,,classmethod()} でデコレートされていなければなりません:

@example
@@classmethod
def tearDownClass(cls):
    ...
@end example

詳しくは @ref{45f1,,クラスとモジュールのフィクスチャ} を参照してください。


Added in version 3.2.

@end deffn

@geindex run() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase run}@anchor{137e}
@deffn {メソッド} run (result=None)

テストを実行し、テスト結果を `result' に指定された @ref{137f,,TestResult} オブジェクトにまとめます。 `result' が省略されるか @code{None} が渡された場合、 (@ref{45f2,,defaultTestResult()} メソッドを呼んで)  一時的な結果オブジェクトを生成し、使用します。 結果オブジェクトは @ref{137e,,run()} の呼び出し元に返されます。

このメソッドは、単に @ref{2b3,,TestCase} インスタンスを呼び出した場合と同様に振る舞います。


バージョン 3.3 で変更: 以前のバージョンの @code{run} は結果オブジェクトを返しませんでした。また @ref{2b3,,TestCase} インスタンスを呼び出した場合も同様でした。

@end deffn

@geindex skipTest() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase skipTest}@anchor{45e8}
@deffn {メソッド} skipTest (reason)

テストメソッドや @ref{1551,,setUp()} が現在のテストをスキップする間に呼ばれます。詳細については、 @ref{45e7,,テストのスキップと予期された失敗} を参照してください。


Added in version 3.1.

@end deffn

@geindex subTest() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase subTest}@anchor{11e3}
@deffn {メソッド} subTest (msg=None, **params)

このメソッドを囲っているブロックをサブテストとして実行するコンテキストマネージャを返します。
`msg' と `params' はサブテストが失敗したときに表示されるオプションの任意の値で、どんな値が使われたかを明確にするものです。

テストケースには subtest 宣言を幾らでも含めることができ、任意にネストすることができます。

詳細は @ref{11e4,,サブテストを利用して繰り返しテストの区別を付ける} を参照してください。


Added in version 3.4.

@end deffn

@geindex debug() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase debug}@anchor{1c49}
@deffn {メソッド} debug ()

テスト結果を収集せずにテストを実行します。例外が呼び出し元に通知されます。また、テストをデバッガで実行することができます。
@end deffn
@anchor{library/unittest assert-methods}@anchor{45cb}
@ref{2b3,,TestCase} クラスは失敗の検査と報告を行う多くのメソッドを提供しています。
以下の表は最も一般的に使われるメソッドを列挙しています (より多くのアサートメソッドについては表の下を見てください):


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

メソッド

@tab

確認事項

@tab

初出

@item

@ref{74c,,assertEqual(a@comma{} b)}

@tab

@code{a == b}

@tab

@item

@ref{74d,,assertNotEqual(a@comma{} b)}

@tab

@code{a != b}

@tab

@item

@ref{74a,,assertTrue(x)}

@tab

@code{bool(x) is True}

@tab

@item

@ref{74b,,assertFalse(x)}

@tab

@code{bool(x) is False}

@tab

@item

@ref{1553,,assertIs(a@comma{} b)}

@tab

@code{a is b}

@tab

3.1

@item

@ref{1554,,assertIsNot(a@comma{} b)}

@tab

@code{a is not b}

@tab

3.1

@item

@ref{14a2,,assertIsNone(x)}

@tab

@code{x is None}

@tab

3.1

@item

@ref{14a3,,assertIsNotNone(x)}

@tab

@code{x is not None}

@tab

3.1

@item

@ref{155c,,assertIn(a@comma{} b)}

@tab

@code{a in b}

@tab

3.1

@item

@ref{155d,,assertNotIn(a@comma{} b)}

@tab

@code{a not in b}

@tab

3.1

@item

@ref{1555,,assertIsInstance(a@comma{} b)}

@tab

@code{isinstance(a, b)}

@tab

3.2

@item

@ref{1556,,assertNotIsInstance(a@comma{} b)}

@tab

@code{not isinstance(a, b)}

@tab

3.2

@item

@ref{2b6,,assertIsSubclass(a@comma{} b)}

@tab

@code{issubclass(a, b)}

@tab

3.14

@item

@ref{2b7,,assertNotIsSubclass(a@comma{} b)}

@tab

@code{not issubclass(a, b)}

@tab

3.14

@end multitable


全てのアサートメソッドは `msg' 引数を受け取り、指定された場合、失敗時のエラーメッセージとして使われます。 (@ref{154d,,longMessage} も参照してください)。 `msg' キーワード引数は @ref{750,,assertRaises()} 、 @ref{752,,assertRaisesRegex()} 、 @ref{137c,,assertWarns()} 、 @ref{137d,,assertWarnsRegex()} には、そのメソッドをコンテキストマネージャとして使った場合にのみ使えます。

@geindex assertEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertEqual}@anchor{74c}
@deffn {メソッド} assertEqual (first, second, msg=None)

`first' と `second' が等しいことをテストします。両者が等しくない場合、テストは失敗です。

さらに、 `first' と `second' が厳密に同じ型であり、list、tuple、dict、set、frozenset もしくは str のいずれか、またはサブクラスが @ref{1560,,addTypeEqualityFunc()} に登録されている任意の型の場合、より有用なデフォルトのエラーメッセージを生成するために、その型特有の比較関数が呼ばれます（@ref{45f3,,型固有のメソッドの一覧} も参照してください）。


バージョン 3.1 で変更: 自動で型固有の比較関数が呼ばれるようになりました。



バージョン 3.2 で変更: 文字列比較のデフォルトの比較関数として @ref{155b,,assertMultiLineEqual()} が追加されました。

@end deffn

@geindex assertNotEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertNotEqual}@anchor{74d}
@deffn {メソッド} assertNotEqual (first, second, msg=None)

`first' と `second' が等しくないことをテストします。両者が等しい場合、テストは失敗です。
@end deffn

@geindex assertTrue() (unittest.TestCase のメソッド)
@geindex assertFalse() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertTrue}@anchor{74a}
@deffn {メソッド} assertTrue (expr, msg=None)
@anchor{library/unittest unittest TestCase assertFalse}@anchor{74b}
@deffnx {メソッド} assertFalse (expr, msg=None)

`expr' が真 (偽) であることをテストします。

このメソッドは、@code{bool(expr) is True} と等価であり、@code{expr is True} と等価ではないことに注意が必要です (後者のためには、@code{assertIs(expr, True)} が用意されています)。また、専用のメソッドが使用できる場合には、そちらを使用してください (例えば @code{assertTrue(a == b)} の代わりに @code{assertEqual(a, b)} を使用してください)。そうすることにより、テスト失敗時のエラーメッセージを詳細に表示することができます。
@end deffn

@geindex assertIs() (unittest.TestCase のメソッド)
@geindex assertIsNot() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertIs}@anchor{1553}
@deffn {メソッド} assertIs (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertIsNot}@anchor{1554}
@deffnx {メソッド} assertIsNot (first, second, msg=None)

`first' と `second' が同じオブジェクトであること (またはそうでないこと) をテストします。


Added in version 3.1.

@end deffn

@geindex assertIsNone() (unittest.TestCase のメソッド)
@geindex assertIsNotNone() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertIsNone}@anchor{14a2}
@deffn {メソッド} assertIsNone (expr, msg=None)
@anchor{library/unittest unittest TestCase assertIsNotNone}@anchor{14a3}
@deffnx {メソッド} assertIsNotNone (expr, msg=None)

`expr' が @code{None} であること (および、そうでないこと) をテストします。


Added in version 3.1.

@end deffn

@geindex assertIn() (unittest.TestCase のメソッド)
@geindex assertNotIn() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertIn}@anchor{155c}
@deffn {メソッド} assertIn (member, container, msg=None)
@anchor{library/unittest unittest TestCase assertNotIn}@anchor{155d}
@deffnx {メソッド} assertNotIn (member, container, msg=None)

`member' が `container' に含まれること (またはそうでないこと) をテストします。


Added in version 3.1.

@end deffn

@geindex assertIsInstance() (unittest.TestCase のメソッド)
@geindex assertNotIsInstance() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertIsInstance}@anchor{1555}
@deffn {メソッド} assertIsInstance (obj, cls, msg=None)
@anchor{library/unittest unittest TestCase assertNotIsInstance}@anchor{1556}
@deffnx {メソッド} assertNotIsInstance (obj, cls, msg=None)

`obj' が `cls' のインスタンスであること (あるいはそうでないこと) をテストします (この `cls' は、 @ref{2ad,,isinstance()} が扱うことのできる、クラスもしくはクラスのタプルである必要があります)。正確な型をチェックするためには、 @ref{1553,,assertIs(type(obj)@comma{} cls)} を使用してください。


Added in version 3.2.

@end deffn

@geindex assertIsSubclass() (unittest.TestCase のメソッド)
@geindex assertNotIsSubclass() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertIsSubclass}@anchor{2b6}
@deffn {メソッド} assertIsSubclass (cls, superclass, msg=None)
@anchor{library/unittest unittest TestCase assertNotIsSubclass}@anchor{2b7}
@deffnx {メソッド} assertNotIsSubclass (cls, superclass, msg=None)

Test that `cls' is (or is not) a subclass of `superclass' (which can be a
class or a tuple of classes, as supported by @ref{9c4,,issubclass()}).
To check for the exact type, use @ref{1553,,assertIs(cls@comma{} superclass)}.


Added in version 3.14.

@end deffn

以下のメソッドを使用して例外、警告、およびログメッセージの発生を確認することが出来ます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

メソッド

@tab

確認事項

@tab

初出

@item

@ref{750,,assertRaises(exc@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} が `exc' を送出する

@tab

@item

@ref{752,,assertRaisesRegex(exc@comma{} r@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} が `exc' を送出してメッセージが正規表現 `r' とマッチする

@tab

3.1

@item

@ref{137c,,assertWarns(warn@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} が `warn' を送出する

@tab

3.2

@item

@ref{137d,,assertWarnsRegex(warn@comma{} r@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} が `warn' を送出してメッセージが正規表現 `r' とマッチする

@tab

3.2

@item

@ref{a59,,assertLogs(logger@comma{} level)}

@tab

@code{with} ブロックが 最低 `level' で `logger' を使用する

@tab

3.4

@item

@ref{a58,,assertNoLogs(logger@comma{} level)}

@tab


@table @asis

@item The @code{with} block does not log on

`logger' with minimum `level'
@end table

@tab

3.10

@end multitable


@geindex assertRaises() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertRaises}@anchor{750}
@deffn {メソッド} assertRaises (exception, callable, *args, **kwds)

@deffnx {メソッド} assertRaises (exception, *, msg=None)

`callable' を呼び出した時に例外が発生することをテストします。 @ref{750,,assertRaises()} で指定した位置パラメータとキーワードパラメータを該当メソッドに渡します。 `exception' が送出された場合、テストは成功です。また、他の例外が投げられた場合はエラー、例外が送出されなかった場合は失敗になります。複数の例外をキャッチする場合には、例外クラスのタプルを `exception' に指定してください。

`exception' 引数のみ（またはそれに加えて `msg' 引数）が渡された場合には、コンテキストマネージャが返されます。これにより関数名を渡す形式ではなく、インラインでテスト対象のコードを書くことができます:

@example
with self.assertRaises(SomeException):
    do_something()
@end example

コンテキストマネージャとして使われたときは、 @ref{750,,assertRaises()} は加えて `msg' キーワード引数も受け付けます。

このコンテキストマネージャは @code{exception} で指定されたオブジェクトを格納します。これにより、例外発生時の詳細な確認をおこなうことができます:

@example
with self.assertRaises(SomeException) as cm:
    do_something()

the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
@end example


バージョン 3.1 で変更: @ref{750,,assertRaises()} がコンテキストマネージャとして使えるようになりました。



バージョン 3.2 で変更: @code{exception} 属性が追加されました。



バージョン 3.3 で変更: コンテキストマネージャとして使用したときに `msg' キーワード引数が追加されました。

@end deffn

@geindex assertRaisesRegex() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertRaisesRegex}@anchor{752}
@deffn {メソッド} assertRaisesRegex (exception, regex, callable, *args, **kwds)

@deffnx {メソッド} assertRaisesRegex (exception, regex, *, msg=None)

@ref{750,,assertRaises()} と同等ですが、例外の文字列表現が `regex' にマッチすることもテストします。 `regex' は正規表現オブジェクトか、 @ref{1444,,re.search()} が扱える正規表現が書かれた文字列である必要があります。例えば以下のようになります:

@example
self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
                       int, 'XYZ')
@end example

もしくは:

@example
with self.assertRaisesRegex(ValueError, 'literal'):
   int('XYZ')
@end example


Added in version 3.1: @code{assertRaisesRegexp} という名前で追加されました。



バージョン 3.2 で変更: @ref{752,,assertRaisesRegex()} にリネームされました。



バージョン 3.3 で変更: コンテキストマネージャとして使用したときに `msg' キーワード引数が追加されました。

@end deffn

@geindex assertWarns() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertWarns}@anchor{137c}
@deffn {メソッド} assertWarns (warning, callable, *args, **kwds)

@deffnx {メソッド} assertWarns (warning, *, msg=None)

`callable' を呼び出した時に警告が発生することをテストします。 @ref{137c,,assertWarns()} で指定した位置パラメータとキーワードパラメータを該当メソッドに渡します。 `warning' が発生した場合にテストが成功し、そうでなければ失敗になります。例外が送出された場合はエラーになります。複数の警告を捕捉する場合には、警告クラスのタプルを `warnings' に指定してください。

`warning' 引数のみ（またはそれに加えて `msg' 引数）が渡された場合には、コンテキストマネージャが返されます。これにより関数名を渡す形式ではなく、インラインでテスト対象のコードを書くことができます:

@example
with self.assertWarns(SomeWarning):
    do_something()
@end example

コンテキストマネージャとして使われたときは、 @ref{137c,,assertWarns()} は加えて `msg' キーワード引数も受け付けます。

このコンテキストマネージャは、捕捉した警告オブジェクトを @code{warning} 属性に、警告が発生したソース行を @code{filename} 属性と @code{lineno} 属性に格納します。これは警告発生時に捕捉された警告に対して追加の確認を行いたい場合に便利です:

@example
with self.assertWarns(SomeWarning) as cm:
    do_something()

self.assertIn('myfile.py', cm.filename)
self.assertEqual(320, cm.lineno)
@end example

このメソッドは呼び出されたときに警告フィルタを無視して動作します。


Added in version 3.2.



バージョン 3.3 で変更: コンテキストマネージャとして使用したときに `msg' キーワード引数が追加されました。

@end deffn

@geindex assertWarnsRegex() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertWarnsRegex}@anchor{137d}
@deffn {メソッド} assertWarnsRegex (warning, regex, callable, *args, **kwds)

@deffnx {メソッド} assertWarnsRegex (warning, regex, *, msg=None)

@ref{137c,,assertWarns()} と同等ですが、警告メッセージが `regex' にマッチすることもテストします。 `regex' は正規表現オブジェクトか、 @ref{1444,,re.search()} が扱える正規表現が書かれた文字列である必要があります。例えば以下のようになります:

@example
self.assertWarnsRegex(DeprecationWarning,
                      r'legacy_function\(\) is deprecated',
                      legacy_function, 'XYZ')
@end example

もしくは:

@example
with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
    frobnicate('/etc/passwd')
@end example


Added in version 3.2.



バージョン 3.3 で変更: コンテキストマネージャとして使用したときに `msg' キーワード引数が追加されました。

@end deffn

@geindex assertLogs() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertLogs}@anchor{a59}
@deffn {メソッド} assertLogs (logger=None, level=None)

`logger' かその子ロガーのうちの1つに、少なくとも1つのログメッセージが少なくとも与えられた `level' で出力されることをテストするコンテキストマネージャです。

If given, `logger' should be a @ref{d46,,logging.Logger} object or a
@ref{169,,str} 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.

`level' が与えられた場合、ログレベルを表す数値もしくはそれに相当する文字列 (例えば @code{"ERROR"} もしくは @ref{20e1,,logging.ERROR}) であるべきです。
デフォルトは @ref{20df,,logging.INFO} です。

@code{with} ブロック内で出たメッセージの少なくとも一つが `logger' および `level' 条件に合っている場合、このテストをパスします。それ以外の場合は失敗です。

コンテキストマネージャから返されるオブジェクトは、条件に該当するログメッセージを追跡し続ける記録のためのヘルパーです。
このオブジェクトには2つの属性があります:

@geindex records (unittest.TestCase の属性)
@anchor{library/unittest unittest TestCase records}@anchor{45f4}
@deffn {の属性} records

該当するログメッセージを表す @ref{11e8,,logging.LogRecord} オブジェクトのリスト。
@end deffn

@geindex output (unittest.TestCase の属性)
@anchor{library/unittest unittest TestCase output}@anchor{45f5}
@deffn {の属性} output

該当するメッセージ出力をフォーマットした @ref{169,,str} オブジェクトのリスト。
@end deffn

以下はプログラム例です:

@example
with self.assertLogs('foo', level='INFO') as cm:
    logging.getLogger('foo').info('first message')
    logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
@end example


Added in version 3.4.

@end deffn

@geindex assertNoLogs() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertNoLogs}@anchor{a58}
@deffn {メソッド} assertNoLogs (logger=None, level=None)

A context manager to test that no messages are logged on
the `logger' or one of its children, with at least the given
`level'.

`logger' が与えられた場合、 @ref{d46,,logging.Logger} オブジェクトもしくはロガーの名前である @ref{169,,str} であるべきです。
デフォルトはルートロガーで、これは全てのメッセージを掴まえます。

`level' が与えられた場合、ログレベルを表す数値もしくはそれに相当する文字列 (例えば @code{"ERROR"} もしくは @ref{20e1,,logging.ERROR}) であるべきです。
デフォルトは @ref{20df,,logging.INFO} です。

@ref{a59,,assertLogs()} と異なり、このコンテキストマネージャは何も返しません。


Added in version 3.10.

@end deffn

より具体的な確認を行うために以下のメソッドが用意されています:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
@headitem

メソッド

@tab

確認事項

@tab

初出

@item

@ref{74e,,assertAlmostEqual(a@comma{} b)}

@tab

@code{round(a-b, 7) == 0}

@tab

@item

@ref{74f,,assertNotAlmostEqual(a@comma{} b)}

@tab

@code{round(a-b, 7) != 0}

@tab

@item

@ref{1557,,assertGreater(a@comma{} b)}

@tab

@code{a > b}

@tab

3.1

@item

@ref{1558,,assertGreaterEqual(a@comma{} b)}

@tab

@code{a >= b}

@tab

3.1

@item

@ref{1559,,assertLess(a@comma{} b)}

@tab

@code{a < b}

@tab

3.1

@item

@ref{155a,,assertLessEqual(a@comma{} b)}

@tab

@code{a <= b}

@tab

3.1

@item

@ref{751,,assertRegex(s@comma{} r)}

@tab

@code{r.search(s)}

@tab

3.1

@item

@ref{753,,assertNotRegex(s@comma{} r)}

@tab

@code{not r.search(s)}

@tab

3.2

@item

@ref{1442,,assertCountEqual(a@comma{} b)}

@tab

`a' と `b' に、順番によらず同じ要素が同じ数だけある。

@tab

3.2

@item

@ref{2b8,,assertStartsWith(a@comma{} b)}

@tab

@code{a.startswith(b)}

@tab

3.14

@item

@ref{2b9,,assertNotStartsWith(a@comma{} b)}

@tab

@code{not a.startswith(b)}

@tab

3.14

@item

@ref{2ba,,assertEndsWith(a@comma{} b)}

@tab

@code{a.endswith(b)}

@tab

3.14

@item

@ref{2bb,,assertNotEndsWith(a@comma{} b)}

@tab

@code{not a.endswith(b)}

@tab

3.14

@item

@ref{2b4,,assertHasAttr(a@comma{} b)}

@tab

@code{hastattr(a, b)}

@tab

3.14

@item

@ref{2b5,,assertNotHasAttr(a@comma{} b)}

@tab

@code{not hastattr(a, b)}

@tab

3.14

@end multitable


@geindex assertAlmostEqual() (unittest.TestCase のメソッド)
@geindex assertNotAlmostEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertAlmostEqual}@anchor{74e}
@deffn {メソッド} assertAlmostEqual (first, second, places=7, msg=None, delta=None)
@anchor{library/unittest unittest TestCase assertNotAlmostEqual}@anchor{74f}
@deffnx {メソッド} assertNotAlmostEqual (first, second, places=7, msg=None, delta=None)

`first' と `second' が近似的に等しい (等しくない) ことをテストします。これは、`places' (デフォルト7) で指定した小数位で丸めた差分をゼロと比較することで行われます。これらのメソッドは (@ref{14f2,,round()} と同様に) `小数位' を指定するのであって、`有効桁数' を指定するのではないことに注意してください。

`places' の代わりに `delta' が渡された場合には、`first' と `second' の差分が `delta' 以下 (以上) であることをテストします。

`delta' と `places' の両方が指定された場合は @ref{198,,TypeError} が送出されます。


バージョン 3.2 で変更: @ref{74e,,assertAlmostEqual()} は、オブジェクトが等しい場合には自動で近似的に等しいとみなすようになりました。 @ref{74f,,assertNotAlmostEqual()} は、オブジェクトが等しい場合には自動的に失敗するようになりました。 `delta' 引数が追加されました。

@end deffn

@geindex assertGreater() (unittest.TestCase のメソッド)
@geindex assertGreaterEqual() (unittest.TestCase のメソッド)
@geindex assertLess() (unittest.TestCase のメソッド)
@geindex assertLessEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertGreater}@anchor{1557}
@deffn {メソッド} assertGreater (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertGreaterEqual}@anchor{1558}
@deffnx {メソッド} assertGreaterEqual (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertLess}@anchor{1559}
@deffnx {メソッド} assertLess (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertLessEqual}@anchor{155a}
@deffnx {メソッド} assertLessEqual (first, second, msg=None)

`first' が `second' と比べて、メソッド名に対応して >, >=, < もしくは <= であることをテストします。そうでない場合はテストは失敗です:

@example
>>> self.assertGreaterEqual(3, 4)
AssertionError: "3" unexpectedly not greater than or equal to "4"
@end example


Added in version 3.1.

@end deffn

@geindex assertRegex() (unittest.TestCase のメソッド)
@geindex assertNotRegex() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertRegex}@anchor{751}
@deffn {メソッド} assertRegex (text, regex, msg=None)
@anchor{library/unittest unittest TestCase assertNotRegex}@anchor{753}
@deffnx {メソッド} assertNotRegex (text, regex, msg=None)

`regex' の検索が `text' とマッチする (またはマッチしない) ことをテストします。テスト失敗時には、エラーメッセージにパターンと `text' が表示されます（もしくは、パターンと意図しないかたちでマッチした `text' の一部が表示されます）。 `regex' は正規表現オブジェクトか、 @ref{1444,,re.search()} が扱える正規表現が書かれた文字列である必要があります。


Added in version 3.1: @code{assertRegexpMatches} という名前で追加されました。



バージョン 3.2 で変更: メソッド @code{assertRegexpMatches()} は @ref{751,,assertRegex()} にリネームされました。



Added in version 3.2: @ref{753,,assertNotRegex()}。

@end deffn

@geindex assertCountEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertCountEqual}@anchor{1442}
@deffn {メソッド} assertCountEqual (first, second, msg=None)

シーケンス `first' が `second' と同じ要素を含んでいることをテストします。要素の順序はテスト結果に影響しません。要素が含まれていない場合には、シーケンスの差分がエラーメッセージとして表示されます。

`first' と `second' の比較では、重複した要素は無視 `されません'。両者に同じ数の要素が含まれていることを検証します。このメソッドは @code{assertEqual(Counter(list(first)), Counter(list(second)))} と同等に振る舞うことに加えて、ハッシュ化できないオブジェクトのシーケンスでも動作します。


Added in version 3.2.

@end deffn

@geindex assertStartsWith() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertStartsWith}@anchor{2b8}
@deffn {メソッド} assertStartsWith (s, prefix, msg=None)
@end deffn

@geindex assertNotStartsWith() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertNotStartsWith}@anchor{2b9}
@deffn {メソッド} assertNotStartsWith (s, prefix, msg=None)

Test that the Unicode or byte string `s' starts (or does not start)
with a `prefix'.
`prefix' can also be a tuple of strings to try.


Added in version 3.14.

@end deffn

@geindex assertEndsWith() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertEndsWith}@anchor{2ba}
@deffn {メソッド} assertEndsWith (s, suffix, msg=None)
@end deffn

@geindex assertNotEndsWith() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertNotEndsWith}@anchor{2bb}
@deffn {メソッド} assertNotEndsWith (s, suffix, msg=None)

Test that the Unicode or byte string `s' ends (or does not end)
with a `suffix'.
`suffix' can also be a tuple of strings to try.


Added in version 3.14.

@end deffn

@geindex assertHasAttr() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertHasAttr}@anchor{2b4}
@deffn {メソッド} assertHasAttr (obj, name, msg=None)
@end deffn

@geindex assertNotHasAttr() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertNotHasAttr}@anchor{2b5}
@deffn {メソッド} assertNotHasAttr (obj, name, msg=None)

Test that the object `obj' has (or has not) an attribute `name'.


Added in version 3.14.

@end deffn
@anchor{library/unittest type-specific-methods}@anchor{45f3}
@ref{74c,,assertEqual()} メソッドは、同じ型のオブジェクトの等価性確認のために、型ごとに特有のメソッドにディスパッチします。これらのメソッドは、ほとんどの組み込み型用のメソッドは既に実装されています。さらに、 @ref{1560,,addTypeEqualityFunc()} を使う事で新たなメソッドを登録することができます:

@geindex addTypeEqualityFunc() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase addTypeEqualityFunc}@anchor{1560}
@deffn {メソッド} addTypeEqualityFunc (typeobj, function)

@ref{74c,,assertEqual()} で呼び出される型特有のメソッドを登録します。登録するメソッドは、比較する2つのオブジェクトの型が厳密に `typeobj' と同じ (サブクラスでもいけません) の場合に等価性を確認します。 `function'  は @ref{74c,,assertEqual()} と同様に、2つの位置引数と、3番目に msg=None のキーワード引数を取れる必要があります。このメソッドは、始めの2つに指定したパラメータ間の差分を検出した時に @ref{458b,,self.failureException(msg)} の例外を投げる必要があります。この例外を投げる際は、出来る限り、エラーの内容が分かる有用な情報と差分の詳細をエラーメッセージに含めてください。


Added in version 3.1.

@end deffn

@ref{74c,,assertEqual()} が自動的に呼び出す型特有のメソッドの概要を以下の表示に記載しています。これらのメソッドは通常は直接呼び出す必要がないことに注意が必要です。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
@headitem

メソッド

@tab

比較の対象

@tab

初出

@item

@ref{155b,,assertMultiLineEqual(a@comma{} b)}

@tab

文字列

@tab

3.1

@item

@ref{14a1,,assertSequenceEqual(a@comma{} b)}

@tab

シーケンス

@tab

3.1

@item

@ref{149f,,assertListEqual(a@comma{} b)}

@tab

リスト

@tab

3.1

@item

@ref{14a0,,assertTupleEqual(a@comma{} b)}

@tab

タプル

@tab

3.1

@item

@ref{149d,,assertSetEqual(a@comma{} b)}

@tab

set または frozenset

@tab

3.1

@item

@ref{149e,,assertDictEqual(a@comma{} b)}

@tab

辞書

@tab

3.1

@end multitable


@geindex assertMultiLineEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertMultiLineEqual}@anchor{155b}
@deffn {メソッド} assertMultiLineEqual (first, second, msg=None)

複数行の文字列 `first' が文字列 `second' と等しいことをテストします。等しくない場合には、両者の差分がハイライトされてエラーメッセージに表示されます。このメソッドは、デフォルトで、 @ref{74c,,assertEqual()} が string を比較するときに自動的に使用します。


Added in version 3.1.

@end deffn

@geindex assertSequenceEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertSequenceEqual}@anchor{14a1}
@deffn {メソッド} assertSequenceEqual (first, second, msg=None, seq_type=None)

2つのシーケンスが等しいことをテストします。`seq_type' が指定された場合、`first' と `second' が `seq_type' のインスタンスで無い場合にはテストが失敗します。シーケンスどうしが異なる場合には、両者の差分がエラーメッセージに表示されます。

このメソッドは直接 @ref{74c,,assertEqual()} からは呼ばれませんが、 @ref{149f,,assertListEqual()} と @ref{14a0,,assertTupleEqual()} の実装で使われています。


Added in version 3.1.

@end deffn

@geindex assertListEqual() (unittest.TestCase のメソッド)
@geindex assertTupleEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertListEqual}@anchor{149f}
@deffn {メソッド} assertListEqual (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertTupleEqual}@anchor{14a0}
@deffnx {メソッド} assertTupleEqual (first, second, msg=None)

2つのリストまたはタプルが等しいかどうかをテストします。等しくない場合には、両者の差分を表示します。2つのパラメータの型が異なる場合にはテストがエラーになります。このメソッドは、デフォルトで、 @ref{74c,,assertEqual()} が list または tuple を比較するときに自動的に使用します。


Added in version 3.1.

@end deffn

@geindex assertSetEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertSetEqual}@anchor{149d}
@deffn {メソッド} assertSetEqual (first, second, msg=None)

2つのセットが等しいかどうかをテストします。等しくない場合には、両者の差分を表示します。このメソッドは、デフォルトで、 @ref{74c,,assertEqual()} が set もしくは frozenset を比較するときに自動的に使用します。

`first' or `second' のいずれかに @ref{2698,,difference()} が無い場合にはテストは失敗します。


Added in version 3.1.

@end deffn

@geindex assertDictEqual() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase assertDictEqual}@anchor{149e}
@deffn {メソッド} assertDictEqual (first, second, msg=None)

2つの辞書が等しいかどうかをテストします。等しくない場合には、両者の差分を表示します。このメソッドは、デフォルトで、 @ref{74c,,assertEqual()} が dict を比較するときに自動的に使用します。


Added in version 3.1.

@end deffn
@anchor{library/unittest other-methods-and-attrs}@anchor{45f6}
最後に、 @ref{2b3,,TestCase} の残りのメソッドと属性を紹介します:

@geindex fail() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase fail}@anchor{45f7}
@deffn {メソッド} fail (msg=None)

無条件にテストを失敗させます。エラーメッセージの表示に、`msg' または @code{None} が使われます。
@end deffn

@geindex failureException (unittest.TestCase の属性)
@anchor{library/unittest unittest TestCase failureException}@anchor{458b}
@deffn {の属性} failureException

@ref{e8,,test()} メソッドが送出する例外を指定するクラス属性です。例えばテストフレームワークで追加情報を付した特殊な例外が必要になる場合、この例外のサブクラスとして作成します。この属性の初期値は @ref{8b8,,AssertionError} です。
@end deffn

@geindex longMessage (unittest.TestCase の属性)
@anchor{library/unittest unittest TestCase longMessage}@anchor{154d}
@deffn {の属性} longMessage

このクラス属性は、失敗した assertXYY の呼び出しで独自の失敗時のメッセージが msg 引数として渡されていたときにどうするかを決定します。
@code{True} がデフォルト値です。
この場合、標準の失敗時のメッセージの後に独自のメッセージが追記されます。
@code{False} に設定したときは、標準のメッセージを独自のメッセージで置き換えます。

アサートメソッドを呼び出す前に、個別のテストメソッドの中でインスタンス属性 self.longMessage を @code{True} または @code{False} に設定して、この設定を上書きできます。

このクラスの設定はそれぞれのテストを呼び出す前にリセットされます。


Added in version 3.1.

@end deffn

@geindex maxDiff (unittest.TestCase の属性)
@anchor{library/unittest unittest TestCase maxDiff}@anchor{1443}
@deffn {の属性} maxDiff

この属性は、アサーションメソッドが失敗をレポートする時に表示する差分の長さをコントロールします。デフォルトは 80*8 文字です。この属性が影響するメソッドは、 @ref{14a1,,assertSequenceEqual()} (およびこのメソッドに委譲するシーケンス比較メソッド)、 @ref{149e,,assertDictEqual()} と @ref{155b,,assertMultiLineEqual()} です。

@code{maxDiff} を @code{None} に設定すると差分表示の上限がなくなります。


Added in version 3.2.

@end deffn

テストフレームワークは、テスト情報を収集するために以下のメソッドを使用します:

@geindex countTestCases() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase countTestCases}@anchor{45f8}
@deffn {メソッド} countTestCases ()

テストオブジェクトに含まれるテストの数を返します。 @ref{2b3,,TestCase} インスタンスは常に @code{1} を返します。
@end deffn

@geindex defaultTestResult() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase defaultTestResult}@anchor{45f2}
@deffn {メソッド} defaultTestResult ()

このテストケースクラスで使われるテスト結果クラスのインスタンスを (もし @ref{137e,,run()} メソッドに他の結果インスタンスが提供されないならば) 返します。

@ref{2b3,,TestCase} インスタンスに対しては、いつも @ref{137f,,TestResult} のインスタンスですので、 @ref{2b3,,TestCase} のサブクラスでは必要に応じてこのメソッドをオーバライドしてください。
@end deffn

@geindex id() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase id}@anchor{45f9}
@deffn {メソッド} id ()

テストケースを特定する文字列を返します。通常、`id' はモジュール名・クラス名を含む、テストメソッドのフルネームを指定します。
@end deffn

@geindex shortDescription() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase shortDescription}@anchor{45fa}
@deffn {メソッド} shortDescription ()

テストの説明を一行分、または説明がない場合には @code{None} を返します。デフォルトでは、テストメソッドの docstring の先頭の一行、または @code{None} を返します。


バージョン 3.1 で変更: 3.1で docstring があったとしても、返される短い説明文字列にテスト名が付けられるようになりました。
この変更によって unittest 拡張に互換性の問題が発生し、 Python 3.2 でテスト名が追加される場所は @ref{754,,TextTestResult} へ移動しました。

@end deffn

@geindex addCleanup() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase addCleanup}@anchor{c74}
@deffn {メソッド} addCleanup (function, /, *args, **kwargs)

@ref{1552,,tearDown()} の後に呼び出される関数を追加します。この関数はリソースのクリーンアップのために使用します。追加された関数は、追加された順と逆の順番で呼び出されます（@abbr{LIFO}）。 @ref{c74,,addCleanup()} に渡された引数とキーワード引数が追加された関数にも渡されます。

@ref{1551,,setUp()} が失敗した場合、つまり @ref{1552,,tearDown()} が呼ばれなかった場合でも、追加されたクリーンアップ関数は呼び出されます。


Added in version 3.1.

@end deffn

@geindex enterContext() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase enterContext}@anchor{8c8}
@deffn {メソッド} enterContext (cm)

Enter the supplied @ref{1e1,,context manager}.  If successful, also
add its @ref{1518,,__exit__()} method as a cleanup function by
@ref{c74,,addCleanup()} and return the result of the
@ref{7e4,,__enter__()} method.


Added in version 3.11.

@end deffn

@geindex doCleanups() (unittest.TestCase のメソッド)
@anchor{library/unittest unittest TestCase doCleanups}@anchor{1550}
@deffn {メソッド} doCleanups ()

このメソッドは、 @ref{1552,,tearDown()} の後、もしくは、 @ref{1551,,setUp()} が例外を投げた場合は @ref{1551,,setUp()} の後に、無条件で呼ばれます。

このメソッドは、 @ref{c74,,addCleanup()} で追加された関数を呼び出す責務を担います。もし、クリーンアップ関数を @ref{1552,,tearDown()} より前に呼び出す必要がある場合には、 @ref{1550,,doCleanups()} を明示的に呼び出してください。

@ref{1550,,doCleanups()} は、どこで呼び出されても、クリーンアップ関数をスタックから削除して実行します。


Added in version 3.1.

@end deffn

@geindex addClassCleanup() (unittest.TestCase のクラスメソッド)
@anchor{library/unittest unittest TestCase addClassCleanup}@anchor{c41}
@deffn {メソッド} classmethod addClassCleanup (function, /, *args, **kwargs)

@ref{154f,,tearDownClass()} の後に呼び出される関数を追加します。この関数はリソースのクリーンアップのために使用します。追加された関数は、追加された順と逆の順番で呼び出されます（@abbr{LIFO}）。 @ref{c41,,addClassCleanup()} に渡された引数とキーワード引数が追加された関数にも渡されます。

@ref{c43,,setUpClass()} が失敗した場合、つまり @ref{154f,,tearDownClass()} が呼ばれなかった場合でも、追加されたクリーンアップ関数は呼び出されます。


Added in version 3.8.

@end deffn

@geindex enterClassContext() (unittest.TestCase のクラスメソッド)
@anchor{library/unittest unittest TestCase enterClassContext}@anchor{8c9}
@deffn {メソッド} classmethod enterClassContext (cm)

Enter the supplied @ref{1e1,,context manager}.  If successful, also
add its @ref{1518,,__exit__()} method as a cleanup function by
@ref{c41,,addClassCleanup()} and return the result of the
@ref{7e4,,__enter__()} method.


Added in version 3.11.

@end deffn

@geindex doClassCleanups() (unittest.TestCase のクラスメソッド)
@anchor{library/unittest unittest TestCase doClassCleanups}@anchor{45fb}
@deffn {メソッド} classmethod doClassCleanups ()

このメソッドは、 @ref{154f,,tearDownClass()} の後、もしくは、 @ref{c43,,setUpClass()} が例外を投げた場合は @ref{c43,,setUpClass()} の後に、無条件で呼ばれます。

このメソッドは、 @ref{c41,,addClassCleanup()} で追加された関数を呼び出す責務を担います。もし、クリーンアップ関数を @ref{154f,,tearDownClass()} より前に呼び出す必要がある場合には、 @ref{45fb,,doClassCleanups()} を明示的に呼び出してください。

@ref{45fb,,doClassCleanups()} は、どこで呼び出されても、クリーンアップ関数をスタックから削除して実行します。


Added in version 3.8.

@end deffn
@end deffn

@geindex IsolatedAsyncioTestCase (unittest のクラス)
@anchor{library/unittest unittest IsolatedAsyncioTestCase}@anchor{361}
@deffn {クラス} unittest.IsolatedAsyncioTestCase (methodName='runTest')

このクラスは @ref{2b3,,TestCase} と似たAPIを提供し、テスト関数としてコルーチンも許容します。


Added in version 3.8.


@geindex loop_factory (unittest.IsolatedAsyncioTestCase の属性)
@anchor{library/unittest unittest IsolatedAsyncioTestCase loop_factory}@anchor{45fc}
@deffn {の属性} loop_factory

The `loop_factory' passed to @ref{2f5,,asyncio.Runner}. Override
in subclasses with @ref{1a67,,asyncio.EventLoop} to avoid using the
asyncio policy system.


Added in version 3.13.

@end deffn

@geindex asyncSetUp() (unittest.IsolatedAsyncioTestCase のメソッド)
@anchor{library/unittest unittest IsolatedAsyncioTestCase asyncSetUp}@anchor{45fd}
@deffn {メソッド} async asyncSetUp ()

テストフィクスチャを用意するために呼び出されるメソッドです。これは @ref{1551,,TestCase.setUp()} の後に呼び出されます。これはテストメソッドを呼び出す直前に呼び出されます。@ref{8b8,,AssertionError} と @ref{11e6,,SkipTest} を除いて、このメソッドのによって送出されたあらゆる例外はテストの失敗ではなくエラーとみなされます。デフォルトの実装では何もしません。
@end deffn

@geindex asyncTearDown() (unittest.IsolatedAsyncioTestCase のメソッド)
@anchor{library/unittest unittest IsolatedAsyncioTestCase asyncTearDown}@anchor{45fe}
@deffn {メソッド} async asyncTearDown ()

テストメソッドが呼び出され、その結果が記録された直後に呼び出されるメソッドです。これは @ref{1552,,tearDown()} の前に呼び出されます。これはテストメソッドが例外を送出した場合でも呼び出されるので、サブクラスの実装では内部状態のチェックに特に気を付ける必要があります。このメソッドで送出された @ref{8b8,,AssertionError} と @ref{11e6,,SkipTest} 以外の例外は、テストの失敗ではなく追加のエラーとみなされます(そのため、報告されるエラーの総数が増えることになります)。このメソッドはテストメソッドの結果に関係なく、@ref{45fd,,asyncSetUp()} が成功した場合にのみ呼び出されます。デフォルトの実装では何もしません。
@end deffn

@geindex addAsyncCleanup() (unittest.IsolatedAsyncioTestCase のメソッド)
@anchor{library/unittest unittest IsolatedAsyncioTestCase addAsyncCleanup}@anchor{45ff}
@deffn {メソッド} addAsyncCleanup (function, /, *args, **kwargs)

このメソッドはクリーンアップ関数として使用できるコルーチンを受け入れます。
@end deffn

@geindex enterAsyncContext() (unittest.IsolatedAsyncioTestCase のメソッド)
@anchor{library/unittest unittest IsolatedAsyncioTestCase enterAsyncContext}@anchor{8ca}
@deffn {メソッド} async enterAsyncContext (cm)

Enter the supplied @ref{7f0,,asynchronous context manager}.  If successful,
also add its @ref{19a1,,__aexit__()} method as a cleanup function by
@ref{45ff,,addAsyncCleanup()} and return the result of the
@ref{241d,,__aenter__()} method.


Added in version 3.11.

@end deffn

@geindex run() (unittest.IsolatedAsyncioTestCase のメソッド)
@anchor{library/unittest unittest IsolatedAsyncioTestCase run}@anchor{4600}
@deffn {メソッド} run (result=None)

テストを実行するための新しいイベントループを作成し、 `result' として渡された @ref{137f,,TestResult} オブジェクトに結果を収集します。`result' が省略された場合や @code{None} の場合は、一時的なresultオブジェクトが(@ref{45f2,,defaultTestResult()} メソッドの呼び出しによって)作成され、使用されます。このresultオブジェクトは @ref{4600,,run()} の呼び出し元に返されます。テスト終了時には、イベントループ内のすべてのタスクがキャンセルされます。
@end deffn

順番を示す例です:

@example
from unittest import IsolatedAsyncioTestCase

events = []


class Test(IsolatedAsyncioTestCase):


    def setUp(self):
        events.append("setUp")

    async def asyncSetUp(self):
        self._async_connection = await AsyncConnection()
        events.append("asyncSetUp")

    async def test_response(self):
        events.append("test_response")
        response = await self._async_connection.get("https://example.com")
        self.assertEqual(response.status_code, 200)
        self.addAsyncCleanup(self.on_cleanup)

    def tearDown(self):
        events.append("tearDown")

    async def asyncTearDown(self):
        await self._async_connection.close()
        events.append("asyncTearDown")

    async def on_cleanup(self):
        events.append("cleanup")

if __name__ == "__main__":
    unittest.main()
@end example

テスト実行後、@code{events} には @code{["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]} が含まれます。
@end deffn

@geindex FunctionTestCase (unittest のクラス)
@anchor{library/unittest unittest FunctionTestCase}@anchor{1a79}
@deffn {クラス} unittest.FunctionTestCase (testFunc, setUp=None, tearDown=None, description=None)

This class implements the portion of the @ref{2b3,,TestCase} 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
@code{unittest}-based test framework.
@end deffn

@node テストのグループ化,テストのロードと起動,テストクラス,クラスと関数
@anchor{library/unittest grouping-tests}@anchor{4601}@anchor{library/unittest testsuite-objects}@anchor{4602}
@subsubsection テストのグループ化


@geindex TestSuite (unittest のクラス)
@anchor{library/unittest unittest TestSuite}@anchor{ff5}
@deffn {クラス} unittest.TestSuite (tests=())

このクラスは、個々のテストケースやテストスイートの集合を表現しています。
通常のテストケースと同じようにテストランナーで実行するためのインターフェースを備えています。 @ref{ff5,,TestSuite} インスタンスを実行することはスイートをイテレートして得られる個々のテストを実行することと同じです。

引数 `tests' が指定された場合、それはテストケースに亘る繰り返し可能オブジェクトまたは内部でスイートを組み立てるための他のテストスイートでなければなりません。後からテストケースやスイートをコレクションに付け加えるためのメソッドも提供されています。

@ref{ff5,,TestSuite} は @ref{2b3,,TestCase} オブジェクトのように振る舞います。違いは、スイートにはテストを実装しない点にあります。代わりに、テストをまとめてグループ化して、同時に実行します。 @ref{ff5,,TestSuite} のインスタンスにテスト追加するためのメソッドが用意されています:

@geindex addTest() (unittest.TestSuite のメソッド)
@anchor{library/unittest unittest TestSuite addTest}@anchor{4603}
@deffn {メソッド} addTest (test)

@ref{2b3,,TestCase} 又は @ref{ff5,,TestSuite} のインスタンスをスイートに追加します。
@end deffn

@geindex addTests() (unittest.TestSuite のメソッド)
@anchor{library/unittest unittest TestSuite addTests}@anchor{4604}
@deffn {メソッド} addTests (tests)

イテラブル `tests' に含まれる全ての @ref{2b3,,TestCase} 又は @ref{ff5,,TestSuite} のインスタンスをスイートに追加します。

このメソッドは `tests' 上のイテレーションをしながらそれぞれの要素に @ref{4603,,addTest()} を呼び出すのと等価です。
@end deffn

@ref{ff5,,TestSuite} クラスは @ref{2b3,,TestCase} と以下のメソッドを共有します:

@geindex run() (unittest.TestSuite のメソッド)
@anchor{library/unittest unittest TestSuite run}@anchor{4605}
@deffn {メソッド} run (result)

スイート内のテストを実行し、結果を `result' で指定した結果オブジェクトに収集します。 @ref{137e,,TestCase.run()} と異なり、 @ref{4605,,TestSuite.run()} では必ず結果オブジェクトを指定する必要があります。
@end deffn

@geindex debug() (unittest.TestSuite のメソッド)
@anchor{library/unittest unittest TestSuite debug}@anchor{4606}
@deffn {メソッド} debug ()

このスイートに関連づけられたテストを結果を収集せずに実行します。これによりテストで送出された例外は呼び出し元に伝わるようになり、デバッガの下でのテスト実行をサポートできるようになります。
@end deffn

@geindex countTestCases() (unittest.TestSuite のメソッド)
@anchor{library/unittest unittest TestSuite countTestCases}@anchor{4607}
@deffn {メソッド} countTestCases ()

このテストオブジェクトによって表現されるテストの数を返します。これには個別のテストと下位のスイートも含まれます。
@end deffn

@geindex __iter__() (unittest.TestSuite のメソッド)
@anchor{library/unittest unittest TestSuite __iter__}@anchor{122a}
@deffn {メソッド} __iter__ ()

@ref{ff5,,TestSuite} でグループ化されたテストは反復アクセスできます。
サブクラスは @code{__iter__()} をオーバーライドすることで、遅延処理でテストを提供できます。
1つのスイート内でこのメソッドは何度も呼ばれる可能性があることに注意してください (例えば、テスト数のカウントや等価性の比較)。
そのため、 @ref{4605,,TestSuite.run()} を実行する前に反復アクセスを何度繰り返しても同じテスト群を返すようにしなければなりません。
呼び出し側が @code{TestSuite._removeTestAtIndex()} をオーバーライドしたサブクラスを使いテストへの参照を保存していない限り、 @ref{4605,,TestSuite.run()} を実行した後はこのメソッドが返すテスト群を信頼すべきではありません。


バージョン 3.2 で変更: 以前のバージョンでは @ref{ff5,,TestSuite} はイテレータではなく、直接テストにアクセスしていました。そのため、 @code{__iter__()} をオーバーラードしてもテストにアクセスできませんでした。



バージョン 3.4 で変更: 以前のバージョンでは、 @ref{4605,,TestSuite.run()} の実行後は @ref{ff5,,TestSuite} が各 @ref{2b3,,TestCase} への参照を保持していました。
サブクラスで @code{TestSuite._removeTestAtIndex()} をオーバーライドすることでこの振る舞いを復元できます。

@end deffn

通常、 @ref{ff5,,TestSuite} の @ref{4605,,run()} メソッドは @code{TestRunner} が起動するため、ユーザが直接実行する必要はありません。
@end deffn

@node テストのロードと起動,,テストのグループ化,クラスと関数
@anchor{library/unittest loading-and-running-tests}@anchor{4608}
@subsubsection テストのロードと起動


@geindex TestLoader (unittest のクラス)
@anchor{library/unittest unittest TestLoader}@anchor{593}
@deffn {クラス} unittest.TestLoader

The @ref{593,,TestLoader} class is used to create test suites from classes and
modules.  Normally, there is no need to create an instance of this class; the
@code{unittest} module provides an instance that can be shared as
@ref{4609,,unittest.defaultTestLoader}.  Using a subclass or instance, however,
allows customization of some configurable properties.

@ref{593,,TestLoader} オブジェクトには以下の属性があります:

@geindex errors (unittest.TestLoader の属性)
@anchor{library/unittest unittest TestLoader errors}@anchor{108c}
@deffn {の属性} errors

テストの読み込み中に起きた致命的でないエラーのリストです。
どの時点でもローダーからリセットされることはありません。
致命的なエラーは適切なメソッドが例外を送出して、呼び出し元に通知します。
致命的でないエラーも、実行したときのエラーを総合テストが通知してくれます。


Added in version 3.5.

@end deffn

@ref{593,,TestLoader} のオブジェクトには以下のメソッドがあります:

@geindex loadTestsFromTestCase() (unittest.TestLoader のメソッド)
@anchor{library/unittest unittest TestLoader loadTestsFromTestCase}@anchor{595}
@deffn {メソッド} loadTestsFromTestCase (testCaseClass)

@ref{2b3,,TestCase} の派生クラス @code{testCaseClass} に含まれる全テストケースのスイートを返します。

@ref{596,,getTestCaseNames()} で指定されたメソッドに対し、テストケースインスタンスが作成されます。
デフォルトでは @code{test} で始まる名前のメソッド群です。
@ref{596,,getTestCaseNames()} がメソッド名を返さなかったが、 @code{runTest()} メソッドが実装されている場合は、そのメソッドに対するテストケースが代わりに作成されます。
@end deffn

@geindex loadTestsFromModule() (unittest.TestLoader のメソッド)
@anchor{library/unittest unittest TestLoader loadTestsFromModule}@anchor{594}
@deffn {メソッド} loadTestsFromModule (module, *, pattern=None)

指定したモジュールに含まれる全テストケースのスイートを返します。このメソッドは `module' 内の @ref{2b3,,TestCase} 派生クラスを検索し、見つかったクラスのテストメソッドごとにクラスのインスタンスを作成します。

@cartouche
@quotation 注釈 
@ref{2b3,,TestCase} クラスを基底クラスとしてクラス階層を構築するとテストフィクスチャや補助的な関数をうまく共用することができますが、基底クラスに直接インスタンス化できないテストメソッドがあると、この @code{loadTestsFromModule()} を使うことができません。この場合でも、 fixture が全て別々で定義がサブクラスにある場合は使用することができます。
@end quotation
@end cartouche

モジュールが @code{load_tests} 関数を用意している場合、この関数がテストの読み込みに使われます。
これによりテストの読み込み処理がカスタマイズできます。
これが @ref{45e2,,load_tests プロトコル} です。
`pattern' 引数は @code{load_tests} に第3引数として渡されます。


バージョン 3.2 で変更: @code{load_tests} のサポートが追加されました。



バージョン 3.5 で変更: Support for a keyword-only argument `pattern' has been added.



バージョン 3.12 で変更: The undocumented and unofficial `use_load_tests' parameter has been
removed.

@end deffn

@geindex loadTestsFromName() (unittest.TestLoader のメソッド)
@anchor{library/unittest unittest TestLoader loadTestsFromName}@anchor{155e}
@deffn {メソッド} loadTestsFromName (name, module=None)

文字列で指定される全テストケースを含むスイートを返します。

`name' には "ドット修飾名" でモジュールかテストケースクラス、テストケースクラス内のメソッド、 @ref{ff5,,TestSuite} インスタンスまたは @ref{2b3,,TestCase} か @ref{ff5,,TestSuite} のインスタンスを返す呼び出し可能オブジェクトを指定します。このチェックはここで挙げた順番に行なわれます。すなわち、候補テストケースクラス内のメソッドは「呼び出し可能オブジェクト」としてではなく「テストケースクラス内のメソッド」として拾い出されます。

例えば  モジュールに @ref{2b3,,TestCase} から派生した  クラスがあり、 @code{SampleTestCase} にはテストメソッド @code{test_one()}、@code{test_two()}、@code{test_three()} があるとします。この場合、 `name' に @code{'SampleTests.SampleTestCase'} と指定すると、 @code{SampleTests} の三つのテストメソッドを実行するテストスイートが作成されます。 @code{'SampleTests.SampleTestCase.test_two'} と指定すれば、 @code{test_two()} だけを実行するテストスイートが作成されます。インポートされていないモジュールやパッケージ名を含んだ名前を指定した場合は自動的にインポートされます。

また、`module' を指定した場合、`module' 内の `name' を取得します。


バージョン 3.5 で変更: `name' を巡回している間に @ref{65b,,ImportError} か @ref{5f0,,AttributeError} が発生した場合、実行するとその例外を発生させるようなテストを合成して返します。それらのエラーは self.errors に集められます。

@end deffn

@geindex loadTestsFromNames() (unittest.TestLoader のメソッド)
@anchor{library/unittest unittest TestLoader loadTestsFromNames}@anchor{460a}
@deffn {メソッド} loadTestsFromNames (names, module=None)

@ref{155e,,loadTestsFromName()} と同じですが、名前を一つだけ指定するのではなく、複数の名前のシーケンスを指定する事ができます。戻り値は `names' 中の名前で指定されるテスト全てを含むテストスイートです。
@end deffn

@geindex getTestCaseNames() (unittest.TestLoader のメソッド)
@anchor{library/unittest unittest TestLoader getTestCaseNames}@anchor{596}
@deffn {メソッド} getTestCaseNames (testCaseClass)

`testCaseClass' 中の全てのメソッド名を含むソート済みシーケンスを返します。 `testCaseClass' は @ref{2b3,,TestCase} のサブクラスでなければなりません。
@end deffn

@geindex discover() (unittest.TestLoader のメソッド)
@anchor{library/unittest unittest TestLoader discover}@anchor{11e7}
@deffn {メソッド} discover (start_dir, pattern='test*.py', top_level_dir=None)

指定された開始ディレクトリからサブディレクトリに再帰することですべてのテストモジュールを検索し、それらを含む TestSuite オブジェクトを返します。`pattern' にマッチしたテストファイルだけがロードの対象になります。 (シェルスタイルのパターンマッチングが使われます)。その中で、インポート可能なもジュール (つまり Python の識別子として有効であるということです) がロードされます。

すべてのテストモジュールはプロジェクトのトップレベルからインポート可能である必要があります。開始ディレクトリがトップレベルディレクトリでない場合は、`top_level_dir' を個別に指定しなければなりません。

シンタックスエラーなどでモジュールのインポートに失敗した場合、エラーが記録され、ディスカバリ自体は続けられます。 import  の失敗が @ref{11e6,,SkipTest} 例外が発生したためだった場合は、そのモジュールはエラーではなく skip として記録されます。

パッケージ (@code{__init__.py} という名前のファイルがあるディレクトリ) が見付かった場合、そのパッケージに @code{load_tests} 関数があるかをチェックします。
関数があった場合、次に @code{package.load_tests(loader, tests, pattern)} が呼ばれます。
テストの検索の実行では、たとえ load_tests 関数自身が @code{loader.discover} を呼んだとしても、パッケージのチェックは1回のみとなることが保証されています。

@code{load_tests} が存在して、ディスカバリがパッケージ内を再帰的な検索を続けている途中で `ない' 場合、@code{load_tests} はそのパッケージ内の全てのテストをロードする責務を担います。

The pattern is deliberately not stored as a loader attribute so that
packages can continue discovery themselves.

`top_level_dir' is stored internally, and used as a default to any
nested calls to @code{discover()}. That is, if a package's @code{load_tests}
calls @code{loader.discover()}, it does not need to pass this argument.

`start_dir' はドット付のモジュール名でもディレクトリでも構いません。


Added in version 3.2.



バージョン 3.4 で変更: インポート時に @ref{11e6,,SkipTest} を送出するモジュールはエラーではなくスキップとして記録されます。

`start_dir' に @ref{2b2,,名前空間パッケージ} を指定できます。

ファイルシステムの順序がファイル名に従わないとしても実行順序が一定になるように、パスはインポートする前にソートされます。



バージョン 3.5 で変更: パッケージ名がデフォルトのパターンに適合するのは不可能なので、パスが `pattern' に適合するかどうかに関係無く、見付けたパッケージに @code{load_tests} があるかをチェックするようになりました。



バージョン 3.11 で変更: `start_dir' can not be a @ref{2b2,,namespace packages}.
It has been broken since Python 3.7, and Python 3.11 officially removes it.



バージョン 3.13 で変更: `top_level_dir' is only stored for the duration of `discover' call.



バージョン 3.14 で変更: `start_dir' can once again be a @ref{2b2,,namespace package}.

@end deffn

以下の属性は、サブクラス化またはインスタンスの属性値を変更して @ref{593,,TestLoader} をカスタマイズする場合に使用します:

@geindex testMethodPrefix (unittest.TestLoader の属性)
@anchor{library/unittest unittest TestLoader testMethodPrefix}@anchor{460b}
@deffn {の属性} testMethodPrefix

テストメソッドの名前と判断されるメソッド名の接頭語を示す文字列。デフォルト値は @code{'test'} です。

この値は @ref{596,,getTestCaseNames()} と全ての @code{loadTestsFrom*} メソッドに影響を与えます。
@end deffn

@geindex sortTestMethodsUsing (unittest.TestLoader の属性)
@anchor{library/unittest unittest TestLoader sortTestMethodsUsing}@anchor{460c}
@deffn {の属性} sortTestMethodsUsing

@ref{596,,getTestCaseNames()} および全ての @code{loadTestsFrom*} メソッドでメソッド名をソートする際に使用する比較関数。
@end deffn

@geindex suiteClass (unittest.TestLoader の属性)
@anchor{library/unittest unittest TestLoader suiteClass}@anchor{155f}
@deffn {の属性} suiteClass

テストのリストからテストスイートを構築する呼び出し可能オブジェクト。メソッドを持つ必要はありません。デフォルト値は @ref{ff5,,TestSuite} です。

この値は全ての @code{loadTestsFrom*} メソッドに影響を与えます。
@end deffn

@geindex testNamePatterns (unittest.TestLoader の属性)
@anchor{library/unittest unittest TestLoader testNamePatterns}@anchor{460d}
@deffn {の属性} testNamePatterns

テストメソッドがテストスイートに含まれるためにマッチしなければならないUnixシェルスタイルのワイルドカードテスト名パターンのリストです(@code{-k} オプションを参照)。

この属性が @code{None} (デフォルト)でない場合、テストスイートに含まれるすべてのテストメソッドはこのリストのパターンのいずれかにマッチしていなければなりません。マッチは常に @ref{1c55,,fnmatch.fnmatchcase()} を使用して実行されるため、@code{-k} オプションに渡されるパターンとは異なり、単純な部分文字列パターンは @code{*} ワイルドカードを使用して変換する必要があることに注意してください。

この値は全ての @code{loadTestsFrom*} メソッドに影響を与えます。


Added in version 3.7.

@end deffn
@end deffn

@geindex TestResult (unittest のクラス)
@anchor{library/unittest unittest TestResult}@anchor{137f}
@deffn {クラス} unittest.TestResult

このクラスはどのテストが成功しどのテストが失敗したかという情報を収集するのに使います。

@ref{137f,,TestResult} は、複数のテスト結果を記録します。 @ref{2b3,,TestCase} クラスと @ref{ff5,,TestSuite} クラスのテスト結果を正しく記録しますので、テスト開発者が独自にテスト結果を管理する処理を開発する必要はありません。

Testing frameworks built on top of @code{unittest} may want access to the
@ref{137f,,TestResult} object generated by running a set of tests for reporting
purposes; a @ref{137f,,TestResult} instance is returned by the
@code{TestRunner.run()} method for this purpose.

@ref{137f,,TestResult} インスタンスの以下の属性は、テストの実行結果を検査する際に使用することができます:

@geindex errors (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult errors}@anchor{460e}
@deffn {の属性} errors

@ref{2b3,,TestCase} と例外のトレースバック情報をフォーマットした文字列の 2 要素タプルからなるリスト。それぞれのタプルは予想外の例外を送出したテストに対応します。
@end deffn

@geindex failures (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult failures}@anchor{460f}
@deffn {の属性} failures

@ref{2b3,,TestCase} と例外のトレースバック情報をフォーマットした文字列の 2 要素タプルからなるリスト。それぞれのタプルは ref:@cite{assert* メソッド <assert-methods>} を使って見つけ出した失敗に対応します。
@end deffn

@geindex skipped (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult skipped}@anchor{4610}
@deffn {の属性} skipped

@ref{2b3,,TestCase} インスタンスとテストをスキップした理由を保持する文字列の2要素タプルからなるリストです。


Added in version 3.1.

@end deffn

@geindex expectedFailures (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult expectedFailures}@anchor{4611}
@deffn {の属性} expectedFailures

@ref{2b3,,TestCase} と例外のトレースバック情報をフォーマット済の文字列の 2 要素タプルからなるリストです。それぞれのタプルは予期された失敗またはエラーに対応します。
@end deffn

@geindex unexpectedSuccesses (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult unexpectedSuccesses}@anchor{4612}
@deffn {の属性} unexpectedSuccesses

予期された失敗とされていながら成功してしまった @ref{2b3,,TestCase} のインスタンスのリスト。
@end deffn

@geindex collectedDurations (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult collectedDurations}@anchor{1a7c}
@deffn {の属性} collectedDurations

A list containing 2-tuples of test case names and floats
representing the elapsed time of each test which was run.


Added in version 3.12.

@end deffn

@geindex shouldStop (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult shouldStop}@anchor{4613}
@deffn {の属性} shouldStop

@code{True} が設定されると @ref{4614,,stop()} によりテストの実行が停止します。
@end deffn

@geindex testsRun (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult testsRun}@anchor{4615}
@deffn {の属性} testsRun

これまでに実行したテストの総数です。
@end deffn

@geindex buffer (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult buffer}@anchor{4616}
@deffn {の属性} buffer

@code{True} が設定されると、 @code{sys.stdout} と @code{sys.stderr} は、 @ref{4617,,startTest()} から @ref{4618,,stopTest()} が呼ばれるまでの間バッファリングされます。実際に、結果が @code{sys.stdout} と @code{sys.stderr} に出力されるのは、テストが失敗するかエラーが発生した時になります。表示の際には、全ての失敗 / エラーメッセージが表示されます。


Added in version 3.2.

@end deffn

@geindex failfast (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult failfast}@anchor{4619}
@deffn {の属性} failfast

真の場合 @ref{4614,,stop()} が始めの失敗もしくはエラーの時に呼び出され、テストの実行が終了します。


Added in version 3.2.

@end deffn

@geindex tb_locals (unittest.TestResult の属性)
@anchor{library/unittest unittest TestResult tb_locals}@anchor{461a}
@deffn {の属性} tb_locals

真の場合、局所変数がトレースバックに表示されます。


Added in version 3.5.

@end deffn

@geindex wasSuccessful() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult wasSuccessful}@anchor{461b}
@deffn {メソッド} wasSuccessful ()

これまでに実行したテストが全て成功していれば @code{True} を、それ以外なら @code{False} を返します。


バージョン 3.4 で変更: @ref{45e9,,expectedFailure()} デコレ－タでマークされたテストに @ref{4612,,unexpectedSuccesses} があった場合 @code{False} を返します。

@end deffn

@geindex stop() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult stop}@anchor{4614}
@deffn {メソッド} stop ()

このメソッドを呼び出して @ref{137f,,TestResult} の @ref{4613,,shouldStop} 属性に @code{True} をセットすることで、実行中のテストは中断しなければならないというシグナルを送ることができます。 @code{TestRunner} オブジェクトはこのフラグを順守してそれ以上のテストを実行することなく復帰しなければなりません。

たとえばこの機能は、ユーザのキーボード割り込みを受け取って @ref{1ab6,,TextTestRunner} クラスがテストフレームワークを停止させるのに使えます。 @code{TestRunner} の実装を提供する対話的なツールでも同じように使用することができます。
@end deffn

@ref{137f,,TestResult} クラスの以下のメソッドは内部データ管理用のメソッドですが、対話的にテスト結果をレポートするテストツールを開発する場合などにはサブクラスで拡張することができます。

@geindex startTest() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult startTest}@anchor{4617}
@deffn {メソッド} startTest (test)

`test' を実行する直前に呼び出されます。
@end deffn

@geindex stopTest() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult stopTest}@anchor{4618}
@deffn {メソッド} stopTest (test)

`test' の実行直後に、テスト結果に関わらず呼び出されます。
@end deffn

@geindex startTestRun() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult startTestRun}@anchor{1561}
@deffn {メソッド} startTestRun ()

全てのテストが実行される前に一度だけ実行されます。


Added in version 3.1.

@end deffn

@geindex stopTestRun() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult stopTestRun}@anchor{1562}
@deffn {メソッド} stopTestRun ()

全てのテストが実行された後に一度だけ実行されます。


Added in version 3.1.

@end deffn

@geindex addError() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addError}@anchor{1c4c}
@deffn {メソッド} addError (test, err)

テスト `test' 実行中に、想定外の例外が発生した場合に呼び出されます。 `err' は @ref{89a,,sys.exc_info()} が返すタプル @code{(type, value, traceback)} です。

デフォルトの実装では、タプル、 @code{(test, formatted_err)} をインスタンスの @ref{460e,,errors} 属性に追加します。ここで、 `formatted_err' は、 `err' から導出される、整形されたトレースバックです。
@end deffn

@geindex addFailure() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addFailure}@anchor{1c4b}
@deffn {メソッド} addFailure (test, err)

テストケース `test' が失敗した場合に呼び出されます。 `err' は @ref{89a,,sys.exc_info()} が返すタプル @code{(type, value, traceback)} です。

デフォルトの実装では、タプル、 @code{(test, formatted_err)} をインスタンスの @ref{460f,,failures} 属性に追加します。ここで、 `formatted_err' は、 `err' から導出される、整形されたトレースバックです。
@end deffn

@geindex addSuccess() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addSuccess}@anchor{461c}
@deffn {メソッド} addSuccess (test)

テストケース `test' が成功した場合に呼び出されます。

デフォルトの実装では何もしません。
@end deffn

@geindex addSkip() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addSkip}@anchor{1c4d}
@deffn {メソッド} addSkip (test, reason)

`test' がスキップされた時に呼び出されます。`reason' はスキップの際に渡された理由の文字列です。

デフォルトの実装では、 @code{(test, reason)} のタプルをインスタンスの @ref{4610,,skipped} 属性に追加します。
@end deffn

@geindex addExpectedFailure() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addExpectedFailure}@anchor{461d}
@deffn {メソッド} addExpectedFailure (test, err)

@ref{45e9,,expectedFailure()} のデコレータでマークされた `test' が失敗またはエラーの時に呼び出されます。

デフォルトの実装では @code{(test, formatted_err)} のタプルをインスタンスの @ref{4611,,expectedFailures} に追加します。ここで `formatted_err' は `err' から派生した整形されたトレースバックです。
@end deffn

@geindex addUnexpectedSuccess() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addUnexpectedSuccess}@anchor{461e}
@deffn {メソッド} addUnexpectedSuccess (test)

@ref{45e9,,expectedFailure()} のデコレータでマークされた `test' が成功した時に呼び出されます。

デフォルトの実装ではテストをインスタンスの @ref{4612,,unexpectedSuccesses} 属性に追加します。
@end deffn

@geindex addSubTest() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addSubTest}@anchor{1c4e}
@deffn {メソッド} addSubTest (test, subtest, outcome)

サブテストが終了すると呼ばれます。
`test' はテストメソッドに対応するテストケースです。
`subtest' はサブテストを記述するカスタムの @ref{2b3,,TestCase} インスタンスです。

`outcome' が @ref{885,,None} の場合サブテストは成功です。
それ以外の場合は失敗で、@ref{89a,,sys.exc_info()} が返す形式 @code{(type, value, traceback)} の `outcome' を持つ例外を伴います。

結果が成功の場合デフォルトの実装では何もせず、サブテストの失敗を通常の失敗として報告します。


Added in version 3.4.

@end deffn

@geindex addDuration() (unittest.TestResult のメソッド)
@anchor{library/unittest unittest TestResult addDuration}@anchor{1ab7}
@deffn {メソッド} addDuration (test, elapsed)

Called when the test case finishes.  `elapsed' is the time represented in
seconds, and it includes the execution of cleanup functions.


Added in version 3.12.

@end deffn
@end deffn

@geindex TextTestResult (unittest のクラス)
@anchor{library/unittest unittest TextTestResult}@anchor{754}
@deffn {クラス} unittest.TextTestResult (stream, descriptions, verbosity, *, durations=None)

A concrete implementation of @ref{137f,,TestResult} used by the
@ref{1ab6,,TextTestRunner}. Subclasses should accept @code{**kwargs} to ensure
compatibility as the interface changes.


Added in version 3.2.



バージョン 3.12 で変更: `durations' キーワード引数が追加されました。

@end deffn

@geindex defaultTestLoader (unittest モジュール)
@anchor{library/unittest unittest defaultTestLoader}@anchor{4609}
@deffn {データ} unittest.defaultTestLoader

@ref{593,,TestLoader} のインスタンスで、共用することが目的です。 @ref{593,,TestLoader} をカスタマイズする必要がなければ、新しい @ref{593,,TestLoader} オブジェクトを作らずにこのインスタンスを使用します。
@end deffn

@geindex TextTestRunner (unittest のクラス)
@anchor{library/unittest unittest TextTestRunner}@anchor{1ab6}
@deffn {クラス} unittest.TextTestRunner (stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None, *, tb_locals=False, durations=None)

結果をストリームに出力する、基本的なテストランナーの実装です。
`stream' が @code{None} の場合、デフォルトで @ref{b33,,sys.stderr} が出力ストリームとして使われます。
このクラスはいくつかの設定項目があるだけで、基本的に非常に単純です。
グラフィカルなテスト実行アプリケーションでは、独自のテストランナーを実装してください。
テストランナーの実装は、 unittest に新しい機能が追加されランナーを構築するインターフェースが変更されたときに備えて @code{**kwargs} を受け取れるようにするべきです。

By default this runner shows @ref{1a3,,DeprecationWarning},
@ref{ac5,,PendingDeprecationWarning}, @ref{54c,,ResourceWarning} and
@ref{71e,,ImportWarning} even if they are @ref{461f,,ignored by default}.  This behavior can
be overridden using Python's @code{-Wd} or @code{-Wa} options
(see @ref{2129,,Warning control}) and leaving
`warnings' to @code{None}.


バージョン 3.2 で変更: `warnings' 引数が追加されました。



バージョン 3.2 で変更: インポート時でなくインスタンス化時にデフォルトのストリームが @ref{b33,,sys.stderr} に設定されます。



バージョン 3.5 で変更: `tb_locals' 引数が追加されました。



バージョン 3.12 で変更: `durations' 引数が追加されました。


@geindex _makeResult() (unittest.TextTestRunner のメソッド)
@anchor{library/unittest unittest TextTestRunner _makeResult}@anchor{4620}
@deffn {メソッド} _makeResult ()

このメソッドは @ref{4621,,run()} で使われる @code{TestResult} のインスタンスを返します。このメソッドは明示的に呼び出す必要はありませんが、サブクラスで @code{TestResult} をカスタマイズすることができます。

@code{_makeResult()} は、 @code{TextTestRunner} のコンストラクタで @code{resultclass} 引数として渡されたクラスもしくはコーラブルオブジェクトをインスタンス化します。 @code{resultclass} が指定されていない場合には、デフォルトで @ref{754,,TextTestResult} が使用されます。結果のクラスは以下の引数が渡されインスタンス化されます:

@example
stream, descriptions, verbosity
@end example
@end deffn

@geindex run() (unittest.TextTestRunner のメソッド)
@anchor{library/unittest unittest TextTestRunner run}@anchor{4621}
@deffn {メソッド} run (test)

このメソッドは @code{TextTestRunner} へのメインの公開インターフェースです。
このメソッドは @ref{ff5,,TestSuite} インスタンスあるいは @ref{2b3,,TestCase} インスタンスを受け取ります。
@ref{4620,,_makeResult()} が呼ばれて @ref{137f,,TestResult} が作成され、テストが実行され、結果が標準出力に表示されます。
@end deffn
@end deffn

@geindex main() (unittest モジュール)
@anchor{library/unittest unittest main}@anchor{11e5}
@deffn {の関数} unittest.main (module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None)

`module' から複数のテストを読み込んで実行するためのコマンドラインプログラム。この関数を使えば、簡単に実行可能なテストモジュールを作成する事ができます。一番簡単なこの関数の使い方は、以下の行をテストスクリプトの最後に置くことです:

@example
if __name__ == '__main__':
    unittest.main()
@end example

より詳細な情報は verbosity 引数を指定して実行すると得られます:

@example
if __name__ == '__main__':
    unittest.main(verbosity=2)
@end example

`defaultTest' 引数は、 `argv' にテスト名が指定されていない場合に実行する、ある1つのテストの名前もしくはテスト名のイテラブルです。
この引数を指定しないか @code{None} を指定し、かつ `argv' にテスト名が与えられない場合は、 `module' にある全てのテストを実行します。

`argv' 引数には、プログラムに渡されたオプションのリストを、最初の要素がプログラム名のままで渡せます。指定しないか @code{None} の場合は @ref{147c,,sys.argv} が使われます。

The `testRunner' argument can either be a test runner class or an already
created instance of it. By default @code{main} calls @ref{277,,sys.exit()} with
an exit code indicating success (0) or failure (1) of the tests run.
An exit code of 5 indicates that no tests were run or skipped.

`testLoader' 引数は @ref{593,,TestLoader} インスタンスでなければなりません。デフォルトは @ref{4609,,defaultTestLoader} です。

@code{main} は、 @code{exit=False} を指定する事で対話的なインタプリタから使用することもできます。この引数を指定すると、 @ref{277,,sys.exit()} を呼ばずに、結果のみを出力します:

@example
>>> from unittest import main
>>> main(module='test_module', exit=False)
@end example

`failfast', `catchbreak', `buffer' は、@ref{45d1,,コマンドラインオプション} にある同名のオプションと同じ効果のあるパラメータです。

`warnings' 引数では、テストの実行中に使うべき @ref{1b1,,警告フィルタ} を指定します。
この引数が指定されない場合には、 @code{-W} オプションが @code{python} に渡されていなければ @code{None} のまま (@ref{2129,,警告の制御} を参照してください) で、そうでなければ @code{'default'} が設定されます。

Calling @code{main} returns an object with the @code{result} attribute that contains
the result of the tests run as a @ref{137f,,unittest.TestResult}.


バージョン 3.1 で変更: `exit' パラメータが追加されました。



バージョン 3.2 で変更: `verbosity'、`failfast'、`catchbreak'、`buffer'、`warnings' 引数が追加されました。



バージョン 3.4 で変更: `defaultTest' 引数がテスト名のイテラブルも受け取るようになりました。

@end deffn

@menu
* load_tests プロトコル:: 

@end menu

@node load_tests プロトコル,,,テストのロードと起動
@anchor{library/unittest id1}@anchor{45e2}@anchor{library/unittest load-tests-protocol}@anchor{4589}
@subsubsection load_tests プロトコル



Added in version 3.2.


モジュールやパッケージには、@code{load_tests} と呼ばれる関数を実装できます。これにより、通常のテスト実行時やテストディスカバリ時のテストのロードされ方をカスタマイズできます。

テストモジュールが @code{load_tests} を定義していると、それが @ref{594,,TestLoader.loadTestsFromModule()} から呼ばれます。引数は以下です:

@example
load_tests(loader, standard_tests, pattern)
@end example

`pattern' は @code{loadTestsFromModule} からそのまま渡されます。デフォルトは @code{None} です。

これは @ref{ff5,,TestSuite} を返すべきです。

`loader' はローディングを行う @ref{593,,TestLoader} のインスタンスです。 `standard_tests' は、そのモジュールからデフォルトでロードされるテストです。これは、テストの標準セットのテストの追加や削除のみを行いたいテストモジュールに一般に使われます。第三引数は、パッケージをテストディスカバリの一部としてロードするときに使われます。

特定の @ref{2b3,,TestCase} クラスのセットからテストをロードする典型的な @code{load_tests} 関数は、このようになります:

@example
test_cases = (TestCase1, TestCase2, TestCase3)

def load_tests(loader, tests, pattern):
    suite = TestSuite()
    for test_class in test_cases:
        tests = loader.loadTestsFromTestCase(test_class)
        suite.addTests(tests)
    return suite
@end example

コマンドラインからでも @ref{11e7,,TestLoader.discover()} の呼び出しでも、パッケージを含むディレクトリで検索を始めた場合、そのパッケージの @code{__init__.py} をチェックして @code{load_tests} を探します。
その関数が存在しない場合、他のディレクトリであるかのようにパッケージの中を再帰的に検索します。
その関数が存在した場合、パッケージのテストの検索をそちらに任せ、 @code{load_tests} が次の引数で呼び出されます:

@example
load_tests(loader, standard_tests, pattern)
@end example

これはパッケージ内のすべてのテストを表す @ref{ff5,,TestSuite} を返すべきです。 (@code{standard_tests} には、 @code{__init__.py} から収集されたテストのみが含まれます。)

パターンは @code{load_tests} に渡されるので、パッケージは自由にテストディスカバリを継続 (必要なら変更) できます。テストパッケージに '何もしない' @code{load_tests} 関数は次のようになります:

@example
def load_tests(loader, standard_tests, pattern):
    # top level directory cached on loader instance
    this_dir = os.path.dirname(__file__)
    package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
    standard_tests.addTests(package_tests)
    return standard_tests
@end example


バージョン 3.5 で変更: パッケージ名がデフォルトのパターンに適合するのが不可能なため、検索ではパッケージ名が `pattern' に適合するかのチェックは行われなくなりました。


@node クラスとモジュールのフィクスチャ,シグナルハンドリング,クラスと関数,unittest --- ユニットテストフレームワーク
@anchor{library/unittest class-and-module-fixtures}@anchor{45f1}
@subsubsection クラスとモジュールのフィクスチャ


クラスレベルとモジュールレベルのフィクスチャが @ref{ff5,,TestSuite} に実装されました。
テストスイートが新しいクラスのテストを始める時、以前のクラス (あれば)の @ref{154f,,tearDownClass()} を呼び出し、その後に新しいクラスの @ref{c43,,setUpClass()} を呼び出します。

同様に、今回のテストのモジュールが前回のテストとは異なる場合、以前のモジュールの @code{tearDownModule} を実行し、次に新しいモジュールの @code{setUpModule} を実行します。

すべてのテストが実行された後、最後の @code{tearDownClass} と @code{tearDownModule} が実行されます。

なお、共有フィクスチャは、テストの並列化などの [潜在的な] 機能と同時にはうまくいかず、テストの分離を壊すので、気をつけて使うべきです。

unittest テストローダによるテスト作成のデフォルトの順序では、同じモジュールやクラスからのテストはすべて同じグループにまとめられます。これにより、@code{setUpClass} / @code{setUpModule} (など) は、一つのクラスやモジュールにつき一度だけ呼ばれます。この順序をバラバラにし、異なるモジュールやクラスのテストが並ぶようにすると、共有フィクスチャ関数は、一度のテストで複数回呼ばれるようにもなります。

共有フィクスチャは標準でない順序で実行されることを意図していません。
共有フィクスチャをサポートしたくないフレームワークのために、@code{BaseTestSuite} がまだ存在しています。

共有フィクスチャ関数のいずれかで例外が発生した場合、そのテストはエラーとして報告されます。
そのとき、対応するテストインスタンスが無いので(@ref{2b3,,TestCase} と同じインターフェースの) @code{_ErrorHolder} オブジェクトが生成され、エラーを表します。
標準 unittest テストランナーを使っている場合はこの詳細は問題になりませんが、あなたがフレームワークの作者である場合は注意してください。

@menu
* setUpClass と tearDownClass:: 
* setUpModule と tearDownModule:: 

@end menu

@node setUpClass と tearDownClass,setUpModule と tearDownModule,,クラスとモジュールのフィクスチャ
@anchor{library/unittest setupclass-and-teardownclass}@anchor{4622}
@subsubsection setUpClass と tearDownClass


これらはクラスメソッドとして実装されなければなりません:

@example
import unittest

class Test(unittest.TestCase):
    @@classmethod
    def setUpClass(cls):
        cls._connection = createExpensiveConnectionObject()

    @@classmethod
    def tearDownClass(cls):
        cls._connection.destroy()
@end example

基底クラスの @code{setUpClass} および @code{tearDownClass} を使いたいなら、それらを自分で呼び出さなければなりません。 @ref{2b3,,TestCase} の実装は空です。

@code{setUpClass} の中で例外が送出されたら、クラス内のテストは実行されず、 @code{tearDownClass} も実行されません。スキップされたクラスは @code{setUpClass} も @code{tearDownClass} も実行されません。例外が @ref{11e6,,SkipTest} 例外であれば、そのクラスはエラーではなくスキップされたものとして報告されます。

@node setUpModule と tearDownModule,,setUpClass と tearDownClass,クラスとモジュールのフィクスチャ
@anchor{library/unittest setupmodule-and-teardownmodule}@anchor{4623}
@subsubsection setUpModule と tearDownModule


@geindex setUpModule() (unittest モジュール)
@geindex tearDownModule() (unittest モジュール)
@anchor{library/unittest unittest setUpModule}@anchor{c42}
これらは関数として実装されなければなりません:

@example
def setUpModule():
    createConnection()

def tearDownModule():
    closeConnection()
@end example

@code{setUpModule} の中で例外が送出されたら、モジュール内のテストは実行されず、 @code{tearDownModule} も実行されません。例外が @ref{11e6,,SkipTest} 例外であれば、そのモジュールはエラーではなくスキップされたものとして報告されます。

例外が発生した場合でも実行しなければならないクリーンアップコードを追加するには`@w{`}addModuleCleanup`@w{`}を使用します:

@geindex addModuleCleanup() (unittest モジュール)
@anchor{library/unittest unittest addModuleCleanup}@anchor{c40}
@deffn {の関数} unittest.addModuleCleanup (function, /, *args, **kwargs)

@ref{154e,,tearDownModule()} の後に呼び出される関数を追加します。この関数はリソースのクリーンアップのために使用します。追加された関数は、追加された順と逆の順番で呼び出されます（@abbr{LIFO}）。 @ref{c40,,addModuleCleanup()} に渡された引数とキーワード引数が追加された関数にも渡されます。

@ref{c42,,setUpModule()} が失敗した場合、つまり @ref{154e,,tearDownModule()} が呼ばれなかった場合でも、追加されたクリーンアップ関数は呼び出されます。


Added in version 3.8.

@end deffn

@geindex enterModuleContext() (unittest モジュール)
@anchor{library/unittest unittest enterModuleContext}@anchor{8cb}
@deffn {の関数} unittest.enterModuleContext (cm)

Enter the supplied @ref{1e1,,context manager}.  If successful, also
add its @ref{1518,,__exit__()} method as a cleanup function by
@ref{c40,,addModuleCleanup()} and return the result of the
@ref{7e4,,__enter__()} method.


Added in version 3.11.

@end deffn

@geindex doModuleCleanups() (unittest モジュール)
@anchor{library/unittest unittest doModuleCleanups}@anchor{1bd3}
@deffn {の関数} unittest.doModuleCleanups ()

この関数は、 @ref{154e,,tearDownModule()} の後、もしくは、 @ref{c42,,setUpModule()} が例外を投げた場合は @ref{c42,,setUpModule()} の後に、無条件で呼ばれます。

このメソッドは、 @ref{c40,,addModuleCleanup()} で追加された関数を呼び出す責務を担います。もし、クリーンアップ関数を @ref{154e,,tearDownModule()} より前に呼び出す必要がある場合には、 @ref{1bd3,,doModuleCleanups()} を明示的に呼び出してください。

@ref{1bd3,,doModuleCleanups()} は、どこで呼び出されても、クリーンアップ関数をスタックから削除して実行します。


Added in version 3.8.

@end deffn

@node シグナルハンドリング,,クラスとモジュールのフィクスチャ,unittest --- ユニットテストフレームワーク
@anchor{library/unittest signal-handling}@anchor{45d4}
@subsubsection シグナルハンドリング



Added in version 3.2.


unittest の @ref{154a,,-c/--catch} コマンドラインオプションや、 @ref{11e5,,unittest.main()} の @code{catchbreak} パラメタは、テスト実行中の control-C の処理をよりフレンドリーにします。中断捕捉動作を有効である場合、 control-C が押されると、現在実行されているテストまで完了され、そのテストランが終わると今までの結果が報告されます。control-C がもう一度押されると、通常通り @ref{bc5,,KeyboardInterrupt} が送出されます。

シグナルハンドラを処理する control-c は、独自の @ref{253,,signal.SIGINT} ハンドラをインストールするコードやテストの互換性を保とうとします。 @code{unittest} ハンドラが呼ばれ、それがインストールされた @ref{253,,signal.SIGINT} ハンドラで `なければ' 、すなわちテスト中のシステムに置き換えられて移譲されたなら、それはデフォルトのハンドラを呼び出します。インストールされたハンドラを置き換えて委譲するようなコードは、通常その動作を期待するからです。 @code{unittest} の control-c 処理を無効にしたいような個別のテストには、 @ref{154b,,removeHandler()} デコレータが使えます。

フレームワークの作者がテストフレームワーク内で control-c 処理を有効にするための、いくつかのユーティリティ関数があります。

@geindex installHandler() (unittest モジュール)
@anchor{library/unittest unittest installHandler}@anchor{4624}
@deffn {の関数} unittest.installHandler ()

control-c ハンドラをインストールします。(主にユーザが control-c を押したことにより) @ref{253,,signal.SIGINT} が受け取られると、登録した結果すべてに @ref{4614,,stop()} が呼び出されます。
@end deffn

@geindex registerResult() (unittest モジュール)
@anchor{library/unittest unittest registerResult}@anchor{4625}
@deffn {の関数} unittest.registerResult (result)

control-c 処理のために @ref{137f,,TestResult} を登録します。結果を登録するとそれに対する弱参照が格納されるので、結果がガベージコレクトされるのを妨げません。

control-c 処理が有効でなければ、 @ref{137f,,TestResult} オブジェクトの登録には副作用がありません。ですからテストフレームワークは、処理が有効か無効かにかかわらず、作成する全ての結果を無条件に登録できます。
@end deffn

@geindex removeResult() (unittest モジュール)
@anchor{library/unittest unittest removeResult}@anchor{4626}
@deffn {の関数} unittest.removeResult (result)

登録された結果を削除します。一旦結果が削除されると、control-c が押された際にその結果オブジェクトに対して @ref{4614,,stop()} が呼び出されなくなります。
@end deffn

@geindex removeHandler() (unittest モジュール)
@anchor{library/unittest unittest removeHandler}@anchor{154b}
@deffn {の関数} unittest.removeHandler (function=None)

引数なしで呼び出されると、この関数はCtrl+Cのシグナルハンドラを（それがインストールされていた場合）削除します。また、この関数はテストが実行されている間、Ctrl+Cのハンドラを一時的に削除するテストデコレーターとしても使用できます。

@example
@@unittest.removeHandler
def test_signal_handling(self):
    ...
@end example
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node unittest mock --- モックオブジェクトライブラリ,unittest mock --- 入門,unittest --- ユニットテストフレームワーク,開発ツール
@anchor{library/unittest mock doc}@anchor{4627}@anchor{library/unittest mock module-unittest mock}@anchor{10d}@anchor{library/unittest mock translation-repo}@anchor{4628}@anchor{library/unittest mock unittest-mock-mock-object-library}@anchor{4629}
@subsection @code{unittest.mock} --- モックオブジェクトライブラリ


@geindex module; unittest.mock


Added in version 3.3.


`ソースコード:' Lib/unittest/mock.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/unittest/mock.py}


__________________________________________________________________


@code{unittest.mock} is a library for testing in Python. It allows you to
replace parts of your system under test with mock objects and make assertions
about how they have been used.

@code{unittest.mock} provides a core @ref{c3f,,Mock} class removing the need to
create a host of stubs throughout your test suite. After performing an
action, you can make assertions about which methods / attributes were used
and arguments they were called with. You can also specify return values and
set needed attributes in the normal way.

加えて、 mock はテストのスコープ内にあるモジュールやクラスの属性を変更する @ref{1092,,patch()} デコレータを提供します。さらに、ユニークなオブジェクトの作成には @ref{d99,,sentinel} が利用できます。 @ref{c3f,,Mock} や @ref{108f,,MagicMock} 、 @ref{1092,,patch()} の利用例は @ref{462a,,quick guide} を参照してください。

Mock は @ref{10c,,unittest} で利用するために設計されており、多くのモックフレームワークで使われる 'record -> replay' パターンの代わりに、 'action -> assertion' パターンに基づいています。

There is a backport of @code{unittest.mock} for earlier versions of Python,
available as mock@footnote{https://pypi.org/project/mock/} on PyPI.

@menu
* クイックガイド:: 
* Mock クラス:: 
* patcher:: 
* MagicMock と magic method のサポート:: 
* ヘルパー:: 
* Order of precedence of side_effect@comma{} return_value and wraps: Order of precedence of side_effect return_value and wraps. 

@end menu

@node クイックガイド,Mock クラス,,unittest mock --- モックオブジェクトライブラリ
@anchor{library/unittest mock quick-guide}@anchor{462a}
@subsubsection クイックガイド


@c class ProductionClass:
@c     def method(self, a, b, c):
@c         pass
@c 
@c class SomeClass:
@c     @staticmethod
@c     def static_method(args):
@c         return args
@c 
@c     @classmethod
@c     def class_method(cls, args):
@c         return args

@ref{c3f,,Mock} および @ref{108f,,MagicMock} オブジェクトはアクセスしたすべての属性とメソッドを作成し、どのように使用されたかについての詳細な情報を格納します。戻り値を指定したり利用できる属性を制限するために @ref{c3f,,Mock} および @ref{108f,,MagicMock} を設定でき、どのよう使用されたかについてアサートできます:

@example
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')
@end example

@ref{462b,,side_effect} によって、モック呼び出し時の例外発生などの副作用を実行できます:

@example
>>> from unittest.mock import Mock
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
 ...
KeyError: 'foo'
@end example

@example
>>> values = @{'a': 1, 'b': 2, 'c': 3@}
>>> def side_effect(arg):
...     return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)
@end example

モックには多くの設定法や挙動の制御法があります。例えば `spec' 引数によって別のオブジェクトからの仕様を受け取るよう設定できます。 spec にないモックの属性やメソッドにアクセスを試みた場合、 @ref{5f0,,AttributeError} で失敗します。

@ref{1092,,patch()} デコレータ / コンテキストマネージャーによってテスト対象のモジュール内のクラスやオブジェクトを簡単にモックできます。指定したオブジェクトはテスト中はモック (または別のオブジェクト) に置換され、テスト終了時に復元されます:

@example
>>> from unittest.mock import patch
>>> @@patch('module.ClassName2')
... @@patch('module.ClassName1')
... def test(MockClass1, MockClass2):
...     module.ClassName1()
...     module.ClassName2()
...     assert MockClass1 is module.ClassName1
...     assert MockClass2 is module.ClassName2
...     assert MockClass1.called
...     assert MockClass2.called
...
>>> test()
@end example

@cartouche
@quotation 注釈 
patch デコレータをネストした場合、モックは適用されるときと同じ順番 (デコレータを適用するときの通常の `Python' の順番) でデコレートされた関数に渡されます。 つまり下から順に適用されるため、上の例では @code{module.ClassName1} のモックが最初に渡されます。

@ref{1092,,patch()} では探索される名前空間内のオブジェクトにパッチをあてることが重要です。通常は単純ですが、詳しくは @ref{462c,,どこにパッチするか} を参照してください。
@end quotation
@end cartouche

@ref{1092,,patch()} デコレータと同様に with 文でコンテキストマネージャーとして使用できます:

@example
>>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
...     thing = ProductionClass()
...     thing.method(1, 2, 3)
...
>>> mock_method.assert_called_once_with(1, 2, 3)
@end example

また、 @ref{1967,,patch.dict()} を使うと、スコープ内だけで辞書に値を設定し、テスト終了時には元の状態に復元されます:

@example
>>> foo = @{'key': 'value'@}
>>> original = foo.copy()
>>> with patch.dict(foo, @{'newkey': 'newvalue'@}, clear=True):
...     assert foo == @{'newkey': 'newvalue'@}
...
>>> assert foo == original
@end example

mock は Python の @ref{462d,,マジックメソッド} のモックをサポートしています。 マジックメソッドのもっとも簡単な利用法は @ref{108f,,MagicMock} クラスと使うことです。以下のように利用します:

@example
>>> mock = MagicMock()
>>> mock.__str__.return_value = 'foobarbaz'
>>> str(mock)
'foobarbaz'
>>> mock.__str__.assert_called_with()
@end example

mock によってマジックメソッドに関数 (あるいは他の Mock インスタンス) を割り当てることができ、それらは適切に呼び出されます。
@ref{108f,,MagicMock} クラスは、すべてのマジックメソッドがあらかじめ作成されている点を除けば @ref{c3f,,Mock} クラスと一緒です (まあ、とにかく便利ってこと)。

以下は通常の Mock クラスでマジックメソッドを利用する例です:

@example
>>> mock = Mock()
>>> mock.__str__ = Mock(return_value='wheeeeee')
>>> str(mock)
'wheeeeee'
@end example

テスト内のモックオブジェクトが置換するオブジェクトと同じ API を持つことを保証するには、 @ref{462e,,auto-speccing} を使うことができます。パッチをあてる `autospec' 引数、または @ref{1934,,create_autospec()} 関数を通じて auto-speccing は行われます。
auto-speccing は置換するオブジェクトと同じ属性とメソッドを持つモックオブジェクトを作成し、すべての関数および (コンストラクタを含む) メソッドは本物のオブジェクトと同じ呼び出しシグネチャを持ちます。

誤って使用された場合、モックは製品コードと同じように失敗されることが保証されています:

@example
>>> from unittest.mock import create_autospec
>>> def function(a, b, c):
...     pass
...
>>> mock_function = create_autospec(function, return_value='fishy')
>>> mock_function(1, 2, 3)
'fishy'
>>> mock_function.assert_called_once_with(1, 2, 3)
>>> mock_function('wrong arguments')
Traceback (most recent call last):
 ...
TypeError: missing a required argument: 'b'
@end example

@ref{1934,,create_autospec()} はクラスにおいても利用でき、 @code{__init__} メソッドのシグニチャをコピーします。また、呼び出し可能オブジェクトについても @code{__call__}  メソッドのシグニチャをコピーします。

@node Mock クラス,patcher,クイックガイド,unittest mock --- モックオブジェクトライブラリ
@anchor{library/unittest mock the-mock-class}@anchor{462f}
@subsubsection Mock クラス


@c import asyncio
@c import inspect
@c import unittest
@c import threading
@c from unittest.mock import sentinel, DEFAULT, ANY
@c from unittest.mock import patch, call, Mock, MagicMock, PropertyMock, AsyncMock
@c from unittest.mock import ThreadingMock
@c from unittest.mock import mock_open

@ref{c3f,,Mock} は、コードにおけるスタブの使用やテストダブルを置き換えるための柔軟なモックオブジェクトです。モックは呼び出し可能で、属性にアクセスした場合それを新たなモックとして作成します @footnote{
例外は特殊メソッドと属性だけです (これらは2つのアンダースコアで開始・終了します)。モックはこれらの代わりに @ref{5f0,,AttributeError} を発生させます。これは、インタープリタが暗黙的にこれらのメソッドを要求するためであり、特殊メソッドを予測する際に `非常に' 混乱してしまいます。もし特殊メソッドのサポートが必要な場合は、 @ref{462d,,magic methods} を参照してください。
}。同じ属性にアクセスした場合は常に同じモックを返します。
モックはどのように使われたかを記録するので、コードがモックに行うことについてアサートできます。

@ref{108f,,MagicMock} は @ref{c3f,,Mock} のサブクラスで、すべてのマジックメソッドが事前に作成され、利用できます。また、呼び出し不可能なモックを作成する場合には、呼び出し不能な変種の @ref{4630,,NonCallableMock} や @ref{4631,,NonCallableMagicMock} があります。

@ref{1092,,patch()} デコレータによって特定のモジュール内のクラスを @ref{c3f,,Mock} オブジェクトで一時的に置換することが簡単にできます。デフォルトでは @ref{1092,,patch()} は @ref{108f,,MagicMock} を作成します。 @ref{1092,,patch()} に渡す `new_callable' 引数によって、別の @ref{c3f,,Mock} クラスを指定できます。

@geindex Mock (unittest.mock のクラス)
@anchor{library/unittest mock unittest mock Mock}@anchor{c3f}
@deffn {クラス} unittest.mock.Mock (spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)

新しい @ref{c3f,,Mock} オブジェクトを作成します。 @ref{c3f,,Mock} はモックオブジェクトの挙動を指定するオプション引数をいくつか取ります:


@itemize *

@item 
`spec': モックオブジェクトの仕様として働く文字列のリストもしくは存在するオブジェクト (クラスもしくはインスタンス) を指定します。オブジェクトを渡した場合には、 dir 関数によって文字列のリストが生成されます (サポートされない特殊属性や特殊メソッドは除く) 。このリストにない属性にアクセスした際には  @ref{5f0,,AttributeError} が発生します。

`spec' が (文字列のリストではなく) オブジェクトの場合、 @ref{16c6,,__class__} はスペックオブジェクトのクラスを返します。これによってモックが @ref{2ad,,isinstance()} テストに通るようになります。

@item 
`spec_set': より厳しい `spec' です。こちらを利用した場合、 `spec_set' に渡されたオブジェクトに存在しない属性に対し `設定' や取得をしようとした際に @ref{5f0,,AttributeError} が発生します。

@item 
`side_effect': モックが呼び出された際に呼び出される関数を指定します。 @ref{462b,,side_effect} 属性を参考にしてください。例外を発生させたり、動的に戻り値を変更する場合に便利です。関数には、モックと同じ引数が渡され、 @ref{4632,,DEFAULT} を返さない限りはこの関数の戻り値が使われます。

一方で、 `side_effect' には、例外クラスやインスタンスを指定できます。この場合は、モックが呼び出された際に指定された例外を発生します。

もし、 `side_effect' にイテレート可能オブジェクトを指定した場合には、モックの呼び出しごとに順に値を返します。

`side_effect' に @code{None} を指定した場合には、設定がクリアされます。

@item 
`return_value': モックが呼び出された際に返す値です。デフォルトでは (最初にアクセスされた際に生成される) 新しい Mock を返します。 @ref{4633,,return_value} を参照してください。

@item 
`unsafe': By default, accessing any attribute whose name starts with
`assert', `assret', `asert', `aseert' or `assrt' will raise an
@ref{5f0,,AttributeError}. Passing @code{unsafe=True} will allow access to
these attributes.


Added in version 3.5.


@item 
`wraps': このモックオブジェクトがラップするものです。 `wraps' が @code{None} でなければ、このモックを呼び出すと、その呼び出しがラップされたオブジェクトに渡され (て実際の結果を返し) ます。モックの属性アクセスは、ラップされたオブジェクトの対応する属性をラップする Mock オブジェクトを返します (なので、存在しない属性にアクセスしようとすると @ref{5f0,,AttributeError} を送出します)。

モックが明示的に `return_value' を設定されていると、呼び出しはラップされたオブジェクトに渡されず、代わりに `return_value' が返されます。

@item 
`name': モックに名前があるなら、それがモックの repr として使われます。これはデバッグの際に役立つでしょう。この名前は子のモックにも伝播します。
@end itemize

モックは、任意のキーワード引数を与えることができます。これらはモックの生成後、属性の設定に使われます。詳細は @ref{4634,,configure_mock()} を参照してください。

@geindex assert_called() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock assert_called}@anchor{ef4}
@deffn {メソッド} assert_called ()

モックが少なくとも一度は呼び出されたことをアサートします。

@example
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called()
@end example


Added in version 3.6.

@end deffn

@geindex assert_called_once() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock assert_called_once}@anchor{ef5}
@deffn {メソッド} assert_called_once ()

モックが一度だけ呼び出されたことをアサートします。

@example
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
Traceback (most recent call last):
...
AssertionError: Expected 'method' to have been called once. Called 2 times.
Calls: [call(), call()].
@end example


Added in version 3.6.

@end deffn

@geindex assert_called_with() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock assert_called_with}@anchor{1e03}
@deffn {メソッド} assert_called_with (*args, **kwargs)

This method is a convenient way of asserting that the last call has been
made in a particular way:

@example
>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')
@end example
@end deffn

@geindex assert_called_once_with() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock assert_called_once_with}@anchor{4635}
@deffn {メソッド} assert_called_once_with (*args, **kwargs)

モックが一度だけ呼び出され、かつ指定された引数で呼び出されたことをアサートします。

@example
>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recent call last):
  ...
AssertionError: Expected 'mock' to be called once. Called 2 times.
Calls: [call('foo', bar='baz'), call('other', bar='values')].
@end example
@end deffn

@geindex assert_any_call() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock assert_any_call}@anchor{4636}
@deffn {メソッド} assert_any_call (*args, **kwargs)

モックが特定の引数で呼び出されたことがあるのをアサートします。

The assert passes if the mock has `ever' been called, unlike
@ref{1e03,,assert_called_with()} and @ref{4635,,assert_called_once_with()} that
only pass if the call is the most recent one, and in the case of
@ref{4635,,assert_called_once_with()} it must also be the only call.

@example
>>> mock = Mock(return_value=None)
>>> mock(1, 2, arg='thing')
>>> mock('some', 'thing', 'else')
>>> mock.assert_any_call(1, 2, arg='thing')
@end example
@end deffn

@geindex assert_has_calls() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock assert_has_calls}@anchor{1a22}
@deffn {メソッド} assert_has_calls (calls, any_order=False)

モックが特定の呼び出しで呼ばれたことをアサートします。呼び出しでは @ref{4637,,mock_calls} のリストがチェックされます。

`any_order' が false の場合、呼び出しは連続していなければなりません。指定された呼び出しの前、あるいは呼び出しの後に余分な呼び出しがある場合があります。

`any_order' が true の場合、呼び出しは任意の順番でも構いませんが、それらがすべて @ref{4637,,mock_calls} に現われなければなりません。

@example
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
@end example
@end deffn

@geindex assert_not_called() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock assert_not_called}@anchor{108e}
@deffn {メソッド} assert_not_called ()

モックが一度も呼ばれなかったことをアサートします。

@example
>>> m = Mock()
>>> m.hello.assert_not_called()
>>> obj = m.hello()
>>> m.hello.assert_not_called()
Traceback (most recent call last):
  ...
AssertionError: Expected 'hello' to not have been called. Called 1 times.
Calls: [call()].
@end example


Added in version 3.5.

@end deffn

@geindex reset_mock() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock reset_mock}@anchor{ef6}
@deffn {メソッド} reset_mock (*, return_value=False, side_effect=False)

モックオブジェクトのすべての呼び出し属性をリセットします:

@example
>>> mock = Mock(return_value=None)
>>> mock('hello')
>>> mock.called
True
>>> mock.reset_mock()
>>> mock.called
False
@end example

This can be useful where you want to make a series of assertions that
reuse the same object.

`return_value' parameter when set to @code{True} resets @ref{4633,,return_value}:

@example
>>> mock = Mock(return_value=5)
>>> mock('hello')
5
>>> mock.reset_mock(return_value=True)
>>> mock('hello')
<Mock name='mock()' id='...'>
@end example

`side_effect' parameter when set to @code{True} resets @ref{462b,,side_effect}:

@example
>>> mock = Mock(side_effect=ValueError)
>>> mock('hello')
Traceback (most recent call last):
  ...
ValueError
>>> mock.reset_mock(side_effect=True)
>>> mock('hello')
<Mock name='mock()' id='...'>
@end example

Note that @ref{ef6,,reset_mock()} `doesn't' clear the
@ref{4633,,return_value}, @ref{462b,,side_effect} or any child attributes you have
set using normal assignment by default.

Child mocks are reset as well.


バージョン 3.6 で変更: 2つのキーワード専用引数が reset_mock 関数に追加されました。

@end deffn

@geindex mock_add_spec() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock mock_add_spec}@anchor{4638}
@deffn {メソッド} mock_add_spec (spec, spec_set=False)

モックに仕様を追加します。 `spec' にはオブジェクトもしくは文字列のリストを指定してください。 `spec' で設定した属性は、モックの属性としてのみアクセスできます。

`spec_set' が真なら、 spec 以外の属性は設定できません。
@end deffn

@geindex attach_mock() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock attach_mock}@anchor{1955}
@deffn {メソッド} attach_mock (mock, attribute)

属性として mock を設定して、その名前と親を入れ替えます。設定されたモックの呼び出しは、 @ref{4639,,method_calls} や @ref{4637,,mock_calls} 属性に記録されます。
@end deffn

@geindex configure_mock() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock configure_mock}@anchor{4634}
@deffn {メソッド} configure_mock (**kwargs)

モックの属性をキーワード引数で設定します。

属性に加え、子の戻り値や副作用もドット表記を用いて設定でき、辞書はメソッドの呼び出し時にアンパックされます:

@example
>>> mock = Mock()
>>> attrs = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> mock.configure_mock(**attrs)
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError
@end example

コンストラクタの呼び出しでも同様に行うことができます:

@example
>>> attrs = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError
@end example

@ref{4634,,configure_mock()} は、モック生成後のコンフィギュレーションを容易に行うために存在します。
@end deffn

@geindex __dir__() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock __dir__}@anchor{463a}
@deffn {メソッド} __dir__ ()

@ref{c3f,,Mock} オブジェクトは、有用な結果を得るために @code{dir(some_mock)} の結果を制限します。 `spec' を設定したモックに対しては、許可された属性のみを含みます。

このフィルタが何をしていて、どのように停止させるかは、 @ref{463b,,FILTER_DIR} を参照してください。
@end deffn

@geindex _get_child_mock() (unittest.mock.Mock のメソッド)
@anchor{library/unittest mock unittest mock Mock _get_child_mock}@anchor{463c}
@deffn {メソッド} _get_child_mock (**kw)

子のモックを作成し、その値を返すようにしてください。デフォルトでは親と同じタイプで作成されます。サブクラスで子モックの作成される方法をカスタマイズしたい場合には、このメソッドをオーバーライドします。

呼び出し不可能なモックに対しては、(カスタムのサブクラスではなく) 呼び出し可能なモックが使われます。
@end deffn

@geindex called (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock called}@anchor{463d}
@deffn {の属性} called

このモックが呼び出されたかどうかを表します:

@example
>>> mock = Mock(return_value=None)
>>> mock.called
False
>>> mock()
>>> mock.called
True
@end example
@end deffn

@geindex call_count (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock call_count}@anchor{1783}
@deffn {の属性} call_count

このモックオブジェクトが呼び出された回数を返します:

@example
>>> mock = Mock(return_value=None)
>>> mock.call_count
0
>>> mock()
>>> mock()
>>> mock.call_count
2
@end example
@end deffn

@geindex return_value (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock return_value}@anchor{4633}
@deffn {の属性} return_value

モックが呼び出された際に返す値を設定します:

@example
>>> mock = Mock()
>>> mock.return_value = 'fish'
>>> mock()
'fish'
@end example

デフォルトの戻り値はモックオブジェクトです。通常の方法で設定することもできます:

@example
>>> mock = Mock()
>>> mock.return_value.attribute = sentinel.Attribute
>>> mock.return_value()
<Mock name='mock()()' id='...'>
>>> mock.return_value.assert_called_with()
@end example

@ref{4633,,return_value} は生成時にも設定可能です:

@example
>>> mock = Mock(return_value=3)
>>> mock.return_value
3
>>> mock()
3
@end example
@end deffn

@geindex side_effect (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock side_effect}@anchor{462b}
@deffn {の属性} side_effect

このモックが呼ばれた際に呼び出される関数、イテラブル、もしくは発生させる例外 (クラスまたはインスタンス) を設定できます。

関数を渡した場合はモックと同じ引数で呼び出され、 @ref{4632,,DEFAULT} を返さない限りはその関数の戻り値が返されます。関数が @ref{4632,,DEFAULT} を返した場合は ( @ref{4633,,return_value} によって) モックの通常の値を返します。

iterable が渡された場合、その値はイテレータを取り出すために使用されます。イテレータは毎回の呼び出しにおいて値を yield しなければなりません。この値は、送出される例外インスタンスか、呼び出しからモックに返される値のいずれかです (@ref{4632,,DEFAULT} の処理は関数の場合と同一です)。

以下はモックが (API による例外の扱いをテストするために) 例外を発生させる例です:

@example
>>> mock = Mock()
>>> mock.side_effect = Exception('Boom!')
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!
@end example

@ref{462b,,side_effect} を使用して連続的に値を返します:

@example
>>> mock = Mock()
>>> mock.side_effect = [3, 2, 1]
>>> mock(), mock(), mock()
(3, 2, 1)
@end example

呼び出し可能オブジェクトを使います:

@example
>>> mock = Mock(return_value=3)
>>> def side_effect(*args, **kwargs):
...     return DEFAULT
...
>>> mock.side_effect = side_effect
>>> mock()
3
@end example

@ref{462b,,side_effect} は生成時にも設定可能です。呼び出し時の値に 1 を加えて返す例を以下に示します:

@example
>>> side_effect = lambda value: value + 1
>>> mock = Mock(side_effect=side_effect)
>>> mock(3)
4
>>> mock(-8)
-7
@end example

@ref{462b,,side_effect} に @code{None} を設定した場合はクリアされます:

@example
>>> m = Mock(side_effect=KeyError, return_value=3)
>>> m()
Traceback (most recent call last):
 ...
KeyError
>>> m.side_effect = None
>>> m()
3
@end example
@end deffn

@geindex call_args (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock call_args}@anchor{1d69}
@deffn {の属性} call_args

This is either @code{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 @code{args} property, is any positional arguments the mock was
called with (or an empty tuple) and the second member, which can
also be accessed through the @code{kwargs} property, is any keyword
arguments (or an empty dictionary).

@example
>>> mock = Mock(return_value=None)
>>> print(mock.call_args)
None
>>> mock()
>>> mock.call_args
call()
>>> mock.call_args == ()
True
>>> mock(3, 4)
>>> mock.call_args
call(3, 4)
>>> mock.call_args == ((3, 4),)
True
>>> mock.call_args.args
(3, 4)
>>> mock.call_args.kwargs
@{@}
>>> mock(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args
call(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args.args
(3, 4, 5)
>>> mock.call_args.kwargs
@{'key': 'fish', 'next': 'w00t!'@}
@end example

@ref{1d69,,call_args} は、 @ref{463e,,call_args_list} や @ref{4639,,method_calls} 、 @ref{4637,,mock_calls} と同様、 @ref{1db3,,call} オブジェクトです。これらはタプルとしてアンパックすることで個別に取り出すことができます。そして、より複雑なアサーションを行うことができます。 @ref{463f,,calls as tuples} を参照してください。


バージョン 3.8 で変更: @code{args} と @code{kwargs} 属性が追加されました。

@end deffn

@geindex call_args_list (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock call_args_list}@anchor{463e}
@deffn {の属性} call_args_list

モックの呼び出しを順に記録したリストです (よって、このリストの長さはモックが呼び出された回数と等しくなります)。モックを作成してから一度も呼び出しを行なっていない場合は、空のリストが返されます。 @ref{1db3,,call} オブジェクトは、 @ref{463e,,call_args_list} の比較対象となる呼び出しのリストを作成する際に便利です。

@example
>>> mock = Mock(return_value=None)
>>> mock()
>>> mock(3, 4)
>>> mock(key='fish', next='w00t!')
>>> mock.call_args_list
[call(), call(3, 4), call(key='fish', next='w00t!')]
>>> expected = [(), ((3, 4),), (@{'key': 'fish', 'next': 'w00t!'@},)]
>>> mock.call_args_list == expected
True
@end example

@ref{463e,,call_args_list} のメンバは @ref{1db3,,call} オブジェクトです。タプルとしてアンパックすることで個別に取り出すことができます。 @ref{463f,,calls as tuples} を参照してください。
@end deffn

@geindex method_calls (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock method_calls}@anchor{4639}
@deffn {の属性} method_calls

自身の呼び出しと同様に、モックはメソッドや属性、そして `それらの' メソッドや属性の呼び出しも追跡します:

@example
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.property.method.attribute()
<Mock name='mock.property.method.attribute()' id='...'>
>>> mock.method_calls
[call.method(), call.property.method.attribute()]
@end example

@ref{4639,,method_calls} のメンバは @ref{1db3,,call} オブジェクトです。タプルとしてアンパックすることで個別に取り出すことができます。 @ref{463f,,calls as tuples} を参照してください。
@end deffn

@geindex mock_calls (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock mock_calls}@anchor{4637}
@deffn {の属性} mock_calls

@ref{4637,,mock_calls} は、メソッド、特殊メソッド、 `そして' 戻り値のモックまで、モックオブジェクトに対する `すべての' 呼び出しを記録します。

@example
>>> mock = MagicMock()
>>> result = mock(1, 2, 3)
>>> mock.first(a=3)
<MagicMock name='mock.first()' id='...'>
>>> mock.second()
<MagicMock name='mock.second()' id='...'>
>>> int(mock)
1
>>> result(1)
<MagicMock name='mock()()' id='...'>
>>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
... call.__int__(), call()(1)]
>>> mock.mock_calls == expected
True
@end example

@ref{4637,,mock_calls} のメンバは @ref{1db3,,call} オブジェクトです。タプルとしてアンパックすることで個別に取り出すことができます。 @ref{463f,,calls as tuples} を参照してください。

@cartouche
@quotation 注釈 
The way @ref{4637,,mock_calls} are recorded means that where nested
calls are made, the parameters of ancestor calls are not recorded
and so will always compare equal:

@example
>>> mock = MagicMock()
>>> mock.top(a=3).bottom()
<MagicMock name='mock.top().bottom()' id='...'>
>>> mock.mock_calls
[call.top(a=3), call.top().bottom()]
>>> mock.mock_calls[-1] == call.top(a=-1).bottom()
True
@end example
@end quotation
@end cartouche
@end deffn

@geindex __class__ (unittest.mock.Mock の属性)
@anchor{library/unittest mock unittest mock Mock __class__}@anchor{4640}
@deffn {の属性} __class__

通常、オブジェクトの @code{__class__} 属性はその型を返します。 @code{spec} を設定したオブジェクトの場合、 @code{__class__} は代わりに @code{spec} のクラスを返します。これにより、置き換え / 偽装しているオブジェクトに対する @ref{2ad,,isinstance()} も通過することができます:

@example
>>> mock = Mock(spec=3)
>>> isinstance(mock, int)
True
@end example

@code{__class__} は書き換え可能で、 @ref{2ad,,isinstance()} を通るために必ず spec を使う必要はありません:

@example
>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True
@end example
@end deffn
@end deffn

@geindex NonCallableMock (unittest.mock のクラス)
@anchor{library/unittest mock unittest mock NonCallableMock}@anchor{4630}
@deffn {クラス} unittest.mock.NonCallableMock (spec=None, wraps=None, name=None, spec_set=None, **kwargs)

呼び出しができない @ref{c3f,,Mock} です。コンストラクタのパラメータは @ref{c3f,,Mock} と同様ですが、 `return_value' や `side_effect' は意味を持ちません。
@end deffn

@code{spec} か @code{spec_set} にクラスかインスタンスを渡した mock は @ref{2ad,,isinstance()} テストをパスします:

@example
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True
@end example

@ref{c3f,,Mock} クラスは、 特殊メソッドをサポートしています。すべての詳細は @ref{462d,,magic methods} を参照してください。

モッククラスや @ref{1092,,patch()} デコレータは、任意のキーワード引数を設定できます。 @ref{1092,,patch()} デコレータへのキーワード引数は、モックが作られる際のコンストラクタに渡されます。キーワード引数は、モックの属性を設定します:

@example
>>> m = MagicMock(attribute=3, other='fish')
>>> m.attribute
3
>>> m.other
'fish'
@end example

子の戻り値や副作用も、ドットで表記することで同様に設定できます。呼び出し時に直接ドットのついた名前を使用できないので、作成した辞書を @code{**} でアンパックする必要があります:

@example
>>> attrs = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError
@end example

`spec' (または `spec_set') によって作成された呼び出し可能なモックは、モックへの呼び出しがマッチしたときに仕様オブジェクトのシグネチャを内省します。したがって、引数を位置引数として渡したか名前で渡したかどうかに関わらず、実際の呼び出しの引数とマッチすることができます:

@example
>>> def f(a, b, c): pass
...
>>> mock = Mock(spec=f)
>>> mock(1, 2, c=3)
<Mock name='mock()' id='140161580456576'>
>>> mock.assert_called_with(1, 2, 3)
>>> mock.assert_called_with(a=1, b=2, c=3)
@end example

これは @ref{1e03,,assert_called_with()}, @ref{4635,,assert_called_once_with()}, @ref{1a22,,assert_has_calls()} and @ref{4636,,assert_any_call()} にも適用されます。 @ref{462e,,autospec を使う} と、 モックオブジェクトのメソッド呼び出しにも適用されます。


バージョン 3.4 で変更: spec や autospec を用いて生成されたモックオブジェクトは、シグネチャを考慮するようになりました。


@geindex PropertyMock (unittest.mock のクラス)
@anchor{library/unittest mock unittest mock PropertyMock}@anchor{4641}
@deffn {クラス} unittest.mock.PropertyMock (*args, **kwargs)

@ref{4b3,,property} もしくは:term:@cite{デスクリプタ <descriptor>} として使われるためのモックです。 @ref{4641,,PropertyMock} は、 @ref{1701,,__get__()} と @ref{23b5,,__set__()} メソッドを提供し、戻り値を指定することができます。

オブジェクトから @ref{4641,,PropertyMock} のインスタンスを取得することは、引数を与えないモックの呼び出しに相当します。設定は、 設定する値を伴った呼び出しになります。:

@example
>>> class Foo:
...     @@property
...     def foo(self):
...         return 'something'
...     @@foo.setter
...     def foo(self, value):
...         pass
...
>>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
...     mock_foo.return_value = 'mockity-mock'
...     this_foo = Foo()
...     print(this_foo.foo)
...     this_foo.foo = 6
...
mockity-mock
>>> mock_foo.mock_calls
[call(), call(6)]
@end example
@end deffn

@ref{4641,,PropertyMock} を直接モックに取り付ける方法は、モックの属性を保存する方法によりうまく動作しません。代わりに、モック型に取り付けてください:

@example
>>> m = MagicMock()
>>> p = PropertyMock(return_value=3)
>>> type(m).foo = p
>>> m.foo
3
>>> p.assert_called_once_with()
@end example

@cartouche
@quotation 注意 
If an @ref{5f0,,AttributeError} is raised by @ref{4641,,PropertyMock},
it will be interpreted as a missing descriptor and
@ref{6fa,,__getattr__()} will be called on the parent mock:

@example
>>> m = MagicMock()
>>> no_attribute = PropertyMock(side_effect=AttributeError)
>>> type(m).my_property = no_attribute
>>> m.my_property
<MagicMock name='mock.my_property' id='140165240345424'>
@end example

詳細は @ref{6fa,,__getattr__()} を参照してください。
@end quotation
@end cartouche

@geindex AsyncMock (unittest.mock のクラス)
@anchor{library/unittest mock unittest mock AsyncMock}@anchor{c3e}
@deffn {クラス} 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 @ref{108f,,MagicMock}. The @ref{c3e,,AsyncMock} object will
behave so the object is recognized as an async function, and the result of a
call is an awaitable.

@example
>>> mock = AsyncMock()
>>> inspect.iscoroutinefunction(mock)
True
>>> inspect.isawaitable(mock())
True
@end example

The result of @code{mock()} is an async function which will have the outcome
of @code{side_effect} or @code{return_value} after it has been awaited:


@itemize -

@item 
if @code{side_effect} is a function, the async function will return the
result of that function,

@item 
if @code{side_effect} is an exception, the async function will raise the
exception,

@item 
if @code{side_effect} is an iterable, the async function will return the
next value of the iterable, however, if the sequence of result is
exhausted, @code{StopAsyncIteration} is raised immediately,

@item 
if @code{side_effect} is not defined, the async function will return the
value defined by @code{return_value}, hence, by default, the async function
returns a new @ref{c3e,,AsyncMock} object.
@end itemize

Setting the `spec' of a @ref{c3f,,Mock} or @ref{108f,,MagicMock} to an async function
will result in a coroutine object being returned after calling.

@example
>>> async def async_func(): pass
...
>>> mock = MagicMock(async_func)
>>> mock
<MagicMock spec='function' id='...'>
>>> mock()
<coroutine object AsyncMockMixin._mock_call at ...>
@end example

Setting the `spec' of a @ref{c3f,,Mock}, @ref{108f,,MagicMock}, or @ref{c3e,,AsyncMock}
to a class with asynchronous and synchronous functions will automatically
detect the synchronous functions and set them as @ref{108f,,MagicMock} (if the
parent mock is @ref{c3e,,AsyncMock} or @ref{108f,,MagicMock}) or @ref{c3f,,Mock} (if
the parent mock is @ref{c3f,,Mock}). All asynchronous functions will be
@ref{c3e,,AsyncMock}.

@example
>>> class ExampleClass:
...     def sync_foo():
...         pass
...     async def async_foo():
...         pass
...
>>> a_mock = AsyncMock(ExampleClass)
>>> a_mock.sync_foo
<MagicMock name='mock.sync_foo' id='...'>
>>> a_mock.async_foo
<AsyncMock name='mock.async_foo' id='...'>
>>> mock = Mock(ExampleClass)
>>> mock.sync_foo
<Mock name='mock.sync_foo' id='...'>
>>> mock.async_foo
<AsyncMock name='mock.async_foo' id='...'>
@end example


Added in version 3.8.


@geindex assert_awaited() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited}@anchor{4642}
@deffn {メソッド} assert_awaited ()

Assert that the mock was awaited at least once. Note that this is separate
from the object having been called, the @code{await} keyword must be used:

@example
>>> mock = AsyncMock()
>>> async def main(coroutine_mock):
...     await coroutine_mock
...
>>> coroutine_mock = mock()
>>> mock.called
True
>>> mock.assert_awaited()
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited.
>>> asyncio.run(main(coroutine_mock))
>>> mock.assert_awaited()
@end example
@end deffn

@geindex assert_awaited_once() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited_once}@anchor{4643}
@deffn {メソッド} assert_awaited_once ()

Assert that the mock was awaited exactly once.

@example
>>> mock = AsyncMock()
>>> async def main():
...     await mock()
...
>>> asyncio.run(main())
>>> mock.assert_awaited_once()
>>> asyncio.run(main())
>>> mock.assert_awaited_once()
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited once. Awaited 2 times.
@end example
@end deffn

@geindex assert_awaited_with() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited_with}@anchor{4644}
@deffn {メソッド} assert_awaited_with (*args, **kwargs)

Assert that the last await was with the specified arguments.

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_with('foo', bar='bar')
>>> mock.assert_awaited_with('other')
Traceback (most recent call last):
...
AssertionError: expected await not found.
Expected: mock('other')
Actual: mock('foo', bar='bar')
@end example
@end deffn

@geindex assert_awaited_once_with() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited_once_with}@anchor{4645}
@deffn {メソッド} assert_awaited_once_with (*args, **kwargs)

Assert that the mock was awaited exactly once and with the specified
arguments.

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_once_with('foo', bar='bar')
>>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_once_with('foo', bar='bar')
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited once. Awaited 2 times.
@end example
@end deffn

@geindex assert_any_await() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock assert_any_await}@anchor{4646}
@deffn {メソッド} assert_any_await (*args, **kwargs)

Assert the mock has ever been awaited with the specified arguments.

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> asyncio.run(main('foo', bar='bar'))
>>> asyncio.run(main('hello'))
>>> mock.assert_any_await('foo', bar='bar')
>>> mock.assert_any_await('other')
Traceback (most recent call last):
...
AssertionError: mock('other') await not found
@end example
@end deffn

@geindex assert_has_awaits() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock assert_has_awaits}@anchor{4647}
@deffn {メソッド} assert_has_awaits (calls, any_order=False)

Assert the mock has been awaited with the specified calls.
The @ref{1d68,,await_args_list} 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 @ref{1d68,,await_args_list}.

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> calls = [call("foo"), call("bar")]
>>> mock.assert_has_awaits(calls)
Traceback (most recent call last):
...
AssertionError: Awaits not found.
Expected: [call('foo'), call('bar')]
Actual: []
>>> asyncio.run(main('foo'))
>>> asyncio.run(main('bar'))
>>> mock.assert_has_awaits(calls)
@end example
@end deffn

@geindex assert_not_awaited() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock assert_not_awaited}@anchor{4648}
@deffn {メソッド} assert_not_awaited ()

Assert that the mock was never awaited.

@example
>>> mock = AsyncMock()
>>> mock.assert_not_awaited()
@end example
@end deffn

@geindex reset_mock() (unittest.mock.AsyncMock のメソッド)
@anchor{library/unittest mock unittest mock AsyncMock reset_mock}@anchor{4649}
@deffn {メソッド} reset_mock (*args, **kwargs)

See @ref{ef6,,Mock.reset_mock()}. Also sets @ref{464a,,await_count} to 0,
@ref{464b,,await_args} to None, and clears the @ref{1d68,,await_args_list}.
@end deffn

@geindex await_count (unittest.mock.AsyncMock の属性)
@anchor{library/unittest mock unittest mock AsyncMock await_count}@anchor{464a}
@deffn {の属性} await_count

An integer keeping track of how many times the mock object has been awaited.

@example
>>> mock = AsyncMock()
>>> async def main():
...     await mock()
...
>>> asyncio.run(main())
>>> mock.await_count
1
>>> asyncio.run(main())
>>> mock.await_count
2
@end example
@end deffn

@geindex await_args (unittest.mock.AsyncMock の属性)
@anchor{library/unittest mock unittest mock AsyncMock await_args}@anchor{464b}
@deffn {の属性} await_args

This is either @code{None} (if the mock hasn’t been awaited), or the arguments that
the mock was last awaited with. Functions the same as @ref{1d69,,Mock.call_args}.

@example
>>> mock = AsyncMock()
>>> async def main(*args):
...     await mock(*args)
...
>>> mock.await_args
>>> asyncio.run(main('foo'))
>>> mock.await_args
call('foo')
>>> asyncio.run(main('bar'))
>>> mock.await_args
call('bar')
@end example
@end deffn

@geindex await_args_list (unittest.mock.AsyncMock の属性)
@anchor{library/unittest mock unittest mock AsyncMock await_args_list}@anchor{1d68}
@deffn {の属性} 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.

@example
>>> mock = AsyncMock()
>>> async def main(*args):
...     await mock(*args)
...
>>> mock.await_args_list
[]
>>> asyncio.run(main('foo'))
>>> mock.await_args_list
[call('foo')]
>>> asyncio.run(main('bar'))
>>> mock.await_args_list
[call('foo'), call('bar')]
@end example
@end deffn
@end deffn

@geindex ThreadingMock (unittest.mock のクラス)
@anchor{library/unittest mock unittest mock ThreadingMock}@anchor{464c}
@deffn {クラス} unittest.mock.ThreadingMock (spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, *, timeout=UNSET, **kwargs)

A version of @ref{108f,,MagicMock} for multithreading tests. The
@ref{464c,,ThreadingMock} object provides extra methods to wait for a call to
be invoked, rather than assert on it immediately.

The default timeout is specified by the @code{timeout} argument, or if unset by the
@ref{464d,,ThreadingMock.DEFAULT_TIMEOUT} attribute, which defaults to blocking (@code{None}).

You can configure the global default timeout by setting @ref{464d,,ThreadingMock.DEFAULT_TIMEOUT}.

@geindex wait_until_called() (unittest.mock.ThreadingMock のメソッド)
@anchor{library/unittest mock unittest mock ThreadingMock wait_until_called}@anchor{464e}
@deffn {メソッド} wait_until_called (*, timeout=UNSET)

Waits until the mock is called.

If a timeout was passed at the creation of the mock or if a timeout
argument is passed to this function, the function raises an
@ref{8b8,,AssertionError} if the call is not performed in time.

@example
>>> mock = ThreadingMock()
>>> thread = threading.Thread(target=mock)
>>> thread.start()
>>> mock.wait_until_called(timeout=1)
>>> thread.join()
@end example
@end deffn

@geindex wait_until_any_call_with() (unittest.mock.ThreadingMock のメソッド)
@anchor{library/unittest mock unittest mock ThreadingMock wait_until_any_call_with}@anchor{464f}
@deffn {メソッド} wait_until_any_call_with (*args, **kwargs)

Waits until the mock is called with the specified arguments.

If a timeout was passed at the creation of the mock
the function raises an @ref{8b8,,AssertionError} if the call is not performed in time.

@example
>>> mock = ThreadingMock()
>>> thread = threading.Thread(target=mock, args=("arg1", "arg2",), kwargs=@{"arg": "thing"@})
>>> thread.start()
>>> mock.wait_until_any_call_with("arg1", "arg2", arg="thing")
>>> thread.join()
@end example
@end deffn

@geindex DEFAULT_TIMEOUT (unittest.mock.ThreadingMock の属性)
@anchor{library/unittest mock unittest mock ThreadingMock DEFAULT_TIMEOUT}@anchor{464d}
@deffn {の属性} DEFAULT_TIMEOUT

Global default timeout in seconds to create instances of @ref{464c,,ThreadingMock}.
@end deffn


Added in version 3.13.

@end deffn

@menu
* 呼び出し:: 
* 属性の削除:: 
* Mock の名前と name 属性:: 
* 属性として設定されるモック:: 

@end menu

@node 呼び出し,属性の削除,,Mock クラス
@anchor{library/unittest mock calling}@anchor{4650}
@subsubsection 呼び出し


モックオブジェクトは呼び出し可能です。呼び出しの戻り値は @ref{4633,,return_value} 属性に設定された値です。デフォルトでは新しいモックオブジェクトを返します。この新しいモックは、属性に最初にアクセスした際に作成されます (明示もしくはモックの呼び出しによって)。 そしてそれは保存され、それ以降は同じものが返されます。

呼び出しはオブジェクトとして @ref{1d69,,call_args} や @ref{463e,,call_args_list} に記録されます。

If @ref{462b,,side_effect} is set then it will be called after the call has
been recorded, so if @code{side_effect} raises an exception the call is still
recorded.

呼び出された際に例外を発生させるモックを作成するためには、 @ref{462b,,side_effect} を例外クラスかインスタンスにする方法が最もシンプルです:

@example
>>> m = MagicMock(side_effect=IndexError)
>>> m(1, 2, 3)
Traceback (most recent call last):
  ...
IndexError
>>> m.mock_calls
[call(1, 2, 3)]
>>> m.side_effect = KeyError('Bang!')
>>> m('two', 'three', 'four')
Traceback (most recent call last):
  ...
KeyError: 'Bang!'
>>> m.mock_calls
[call(1, 2, 3), call('two', 'three', 'four')]
@end example

If @ref{462b,,side_effect} is a function then whatever that function returns is what
calls to the mock return. The @code{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:

@example
>>> def side_effect(value):
...     return value + 1
...
>>> m = MagicMock(side_effect=side_effect)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]
@end example

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
@ref{4633,,return_value} from inside @ref{462b,,side_effect}, or return @ref{4632,,DEFAULT}:

@example
>>> m = MagicMock()
>>> def side_effect(*args, **kwargs):
...     return m.return_value
...
>>> m.side_effect = side_effect
>>> m.return_value = 3
>>> m()
3
>>> def side_effect(*args, **kwargs):
...     return DEFAULT
...
>>> m.side_effect = side_effect
>>> m()
3
@end example

To remove a @ref{462b,,side_effect}, and return to the default behaviour, set the
@code{side_effect} to @code{None}:

@example
>>> m = MagicMock(return_value=6)
>>> def side_effect(*args, **kwargs):
...     return 3
...
>>> m.side_effect = side_effect
>>> m()
3
>>> m.side_effect = None
>>> m()
6
@end example

The @ref{462b,,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 @ref{df5,,StopIteration} is raised):

@example
>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
  ...
StopIteration
@end example

もしイテレート可能オブジェクトの要素が例外だった場合には、戻り値として返される代わりに例外が発生します:

@example
>>> iterable = (33, ValueError, 66)
>>> m = MagicMock(side_effect=iterable)
>>> m()
33
>>> m()
Traceback (most recent call last):
 ...
ValueError
>>> m()
66
@end example

@node 属性の削除,Mock の名前と name 属性,呼び出し,Mock クラス
@anchor{library/unittest mock deleting-attributes}@anchor{4651}@anchor{library/unittest mock id2}@anchor{4652}
@subsubsection 属性の削除


モックオブジェクトは要求に応じて属性を生成することで，任意のオブジェクトとして振る舞うことができます。

You may want a mock object to return @code{False} to a @ref{6f9,,hasattr()} call, or raise an
@ref{5f0,,AttributeError} when an attribute is fetched. You can do this by providing
an object as a @code{spec} for a mock, but that isn't always convenient.

属性を削除することで， @ref{5f0,,AttributeError} を発生させ，アクセスを "妨げる" ようになります．

@example
>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
    ...
AttributeError: f
@end example

@node Mock の名前と name 属性,属性として設定されるモック,属性の削除,Mock クラス
@anchor{library/unittest mock mock-names-and-the-name-attribute}@anchor{4653}
@subsubsection Mock の名前と name 属性


"name" は @ref{c3f,,Mock} コンストラクタの引数なので、モックオブジェクトが "name" 属性を持つことを望む場合、単に生成時にそれを渡すことはできません。2つの選択肢があります。1つのオプションは @ref{4634,,configure_mock()} を使用することです:

@example
>>> mock = MagicMock()
>>> mock.configure_mock(name='my_name')
>>> mock.name
'my_name'
@end example

より単純なオプションはモックの生成後に単に "name" 属性をセットすることです:

@example
>>> mock = MagicMock()
>>> mock.name = "foo"
@end example

@node 属性として設定されるモック,,Mock の名前と name 属性,Mock クラス
@anchor{library/unittest mock attaching-mocks-as-attributes}@anchor{4654}
@subsubsection 属性として設定されるモック


属性 (もしくは戻り値) に他のモックを設定した場合、このモックは "子" になります。この子に対する呼び出しは、親の @ref{4639,,method_calls} や @ref{4637,,mock_calls} に記録されます。これは、子のモックを構成し、親にそのモックを設定する際に有用です。また、親に対して設定したすべての子の呼び出しを記録するため、それらの間の順番を確認する際にも有用です:

@example
>>> parent = MagicMock()
>>> child1 = MagicMock(return_value=None)
>>> child2 = MagicMock(return_value=None)
>>> parent.child1 = child1
>>> parent.child2 = child2
>>> child1(1)
>>> child2(2)
>>> parent.mock_calls
[call.child1(1), call.child2(2)]
@end example

モックが名前をもつ場合は、例外的に扱われます。何らかの理由で "子守り" が発生してほしくないときに、それを防ぐことができます。

@example
>>> mock = MagicMock()
>>> not_a_child = MagicMock(name='not-a-child')
>>> mock.attribute = not_a_child
>>> mock.attribute()
<MagicMock name='not-a-child()' id='...'>
>>> mock.mock_calls
[]
@end example

@ref{1092,,patch()} を用いて作成したモックには、自動的に名前が与えられます。名前を持つモックを設定したい場合には、親に対して @ref{1955,,attach_mock()} メソッドを呼び出します:

@example
>>> thing1 = object()
>>> thing2 = object()
>>> parent = MagicMock()
>>> with patch('__main__.thing1', return_value=None) as child1:
...     with patch('__main__.thing2', return_value=None) as child2:
...         parent.attach_mock(child1, 'child1')
...         parent.attach_mock(child2, 'child2')
...         child1('one')
...         child2('two')
...
>>> parent.mock_calls
[call.child1('one'), call.child2('two')]
@end example

@node patcher,MagicMock と magic method のサポート,Mock クラス,unittest mock --- モックオブジェクトライブラリ
@anchor{library/unittest mock the-patchers}@anchor{4655}
@subsubsection patcher


patch デコレータは、その関数のスコープ内でパッチを適用するオブジェクトに対して使用されます。たとえ例外が発生したとしても、パッチは自動的に解除されます。これらすべての機能は文やクラスのデコレータとしても使用できます。

@menu
* patch:: 
* patch.object: patch object. 
* patch.dict: patch dict. 
* patch.multiple: patch multiple. 
* patch のメソッド; start と stop: patch のメソッド start と stop. 
* ビルトインをパッチする:: 
* TEST_PREFIX:: 
* patch デコレータをネストする:: 
* どこにパッチするか:: 
* デスクリプタやプロキシオブジェクトにパッチする:: 

@end menu

@node patch,patch object,,patcher
@anchor{library/unittest mock patch}@anchor{4656}
@subsubsection patch


@cartouche
@quotation 注釈 
重要なのは正しい名前空間に対して patch することです。@ref{4657,,where to patch} セクションを参照してください。
@end quotation
@end cartouche

@geindex patch() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock patch}@anchor{1092}
@deffn {の関数} unittest.mock.patch (target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

@ref{1092,,patch()} は関数デコレータ、クラスデコレータ、コンテキストマネージャーとして利用できます。関数や with 文の body では、 `target' は `new' オブジェクトにパッチされます。関数/with 文が終了すると、パッチは元に戻されます。

If `new' is omitted, then the target is replaced with an
@ref{c3e,,AsyncMock} if the patched object is an async function or
a @ref{108f,,MagicMock} otherwise.
If @ref{1092,,patch()} is used as a decorator and `new' is
omitted, the created mock is passed in as an extra argument to the
decorated function. If @ref{1092,,patch()} is used as a context manager the created
mock is returned by the context manager.

`target' は @code{'package.module.ClassName'} の形式の文字列でなければなりません。 @cite{target} はインポートされ、指定されたオブジェクトが @cite{new} オブジェクトに置き換えられます。なので、 `target' は @ref{1092,,patch()} を呼び出した環境からインポート可能でなければなりません。 target がインポートされるのは、デコレートした時ではなく、デコレートされた関数が呼び出された時です。

patch が @ref{108f,,MagicMock} を生成する場合、 `spec' と `spec_set' キーワード引数は @ref{108f,,MagicMock} に渡されます。

加えて、 @code{spec=True} もしくは @code{spec_set=True} を渡すことで、モック対象のオブジェクトが spec/spec_set に渡されます。

`new_callable' allows you to specify a different class, or callable object,
that will be called to create the `new' object. By default @ref{c3e,,AsyncMock}
is used for async functions and @ref{108f,,MagicMock} for the rest.

より強力な `spec' の形は `autospec' です。 @code{autospec=True} を指定した場合、 mock は置換対象となるオブジェクトから得られる spec で生成されます。 mock のすべての属性もまた置換対象となるオブジェクトの属性に応じた spec を持ちます。 mock されたメソッドや関数は引数をチェックし、間違ったシグネチャで呼び出された場合は @ref{198,,TypeError} を発生させます。クラスを置き換える mock の場合、その戻り値 (つまりインスタンス) はそのクラスと同じ spec を持ちます。 @ref{1934,,create_autospec()} 関数と @ref{462e,,autospec を使う} を参照してください。

置換対象ではなく任意のオブジェクトを spec として使うために、 @code{autospec=True} の代わりに、 @code{autospec=some_object} と指定することができます。

By default @ref{1092,,patch()} will fail to replace attributes that don't exist.
If you pass in @code{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!

@cartouche
@quotation 注釈 

バージョン 3.5 で変更: モジュールのビルトインにパッチを当てようとしているなら、 @code{create=True} を渡す必要はありません。それはデフォルトで追加されます。

@end quotation
@end cartouche

Patch can be used as a @ref{2b3,,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. @ref{1092,,patch()} finds
tests by looking for method names that start with @code{patch.TEST_PREFIX}.
By default this is @code{'test'}, which matches the way @ref{10c,,unittest} finds tests.
You can specify an alternative prefix by setting @code{patch.TEST_PREFIX}.

patch は with 文を使ってコンテキストマネージャーとして使うこともできます。その場合パッチは with 文のブロック内でのみ適用されます。 "as" を使って、 "as" に続いて指定した変数にパッチされたオブジェクトが代入されます。これは @ref{1092,,patch()} が mock オブジェクトを生成するときに便利です。

@ref{1092,,patch()} takes arbitrary keyword arguments. These will be passed to
@ref{c3e,,AsyncMock} if the patched object is asynchronous, to
@ref{108f,,MagicMock} otherwise or to `new_callable' if specified.

異なるユースケースのために、 @code{patch.dict(...)}, @code{patch.multiple(...)}, @code{patch.object(...)} が用意されています。
@end deffn

@ref{1092,,patch()} を関数デコレータとして利用し、 mock を生成してそれをデコレートされた関数に渡します:

@example
>>> @@patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
...     print(mock_class is SomeClass)
...
>>> function(None)
True
@end example

クラスをパッチするとそのクラスを @ref{108f,,MagicMock} の `インスタンス' に置き換えます。テスト中のコードからそのクラスがインスタンス化される場合、 mock の @ref{4633,,return_value} が利用されます。

クラスが複数回インスタンス化される場合、 @ref{462b,,side_effect} を利用して毎回新しい mock を返すようにできます。もしくは、 `return_value' に、何でも好きなものを設定できます。

To configure return values on methods of `instances' on the patched class
you must do this on the @ref{4633,,return_value}. For example:

@example
>>> class Class:
...     def method(self):
...         pass
...
>>> with patch('__main__.Class') as MockClass:
...     instance = MockClass.return_value
...     instance.method.return_value = 'foo'
...     assert Class() is instance
...     assert Class().method() == 'foo'
...
@end example

`spec' か `spec_set' を指定し、 @ref{1092,,patch()} が `クラス' を置換するとき、生成された mock の戻り値は同じ spec を持ちます。:

@example
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>> patcher.stop()
@end example

`new_callable' 引数は、デフォルトの @ref{108f,,MagicMock} の代わりに別のクラスをモックとして生成したい場合に便利です。例えば、 @ref{4630,,NonCallableMock} を利用したい場合:

@example
>>> thing = object()
>>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
...     assert thing is mock_thing
...     thing()
...
Traceback (most recent call last):
  ...
TypeError: 'NonCallableMock' object is not callable
@end example

別のユースケースとしては、オブジェクトを @ref{112a,,io.StringIO} インスタンスで置き換えることがあります:

@example
>>> from io import StringIO
>>> def foo():
...     print('Something')
...
>>> @@patch('sys.stdout', new_callable=StringIO)
... def test(mock_stdout):
...     foo()
...     assert mock_stdout.getvalue() == 'Something\n'
...
>>> test()
@end example

@ref{1092,,patch()} に mock を生成させる場合、たいてい最初に必要なことはその mock をセットアップすることです。幾らかのセットアップは patch の呼び出しから行うことができます。任意のキーワード引数が、生成された mock の属性に設定されます:

@example
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two'
@end example

生成された mock の属性のさらに属性、 @ref{4633,,return_value} @ref{462b,,side_effect} などもセットアップできます。これらはキーワード引数のシンタックスでは直接指定できませんが、それらをキーとする辞書を @code{**} を使って @ref{1092,,patch()} に渡すことができます:

@example
>>> config = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> patcher = patch('__main__.thing', **config)
>>> mock_thing = patcher.start()
>>> mock_thing.method()
3
>>> mock_thing.other()
Traceback (most recent call last):
  ...
KeyError
@end example

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 @ref{5f0,,AttributeError}:

@example
>>> @@patch('sys.non_existing_attribute', 42)
... def test():
...     assert sys.non_existing_attribute == 42
...
>>> test()
Traceback (most recent call last):
  ...
AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing_attribute'
@end example

but adding @code{create=True} in the call to @ref{1092,,patch()} will make the previous example
work as expected:

@example
>>> @@patch('sys.non_existing_attribute', 42, create=True)
... def test(mock_stdout):
...     assert sys.non_existing_attribute == 42
...
>>> test()
@end example


バージョン 3.8 で変更: @ref{1092,,patch()} now returns an @ref{c3e,,AsyncMock} if the target is an async function.


@node patch object,patch dict,patch,patcher
@anchor{library/unittest mock patch-object}@anchor{4658}
@subsubsection patch.object


@geindex patch.object() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock patch object}@anchor{1906}
@deffn {の関数} patch.object (target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

オブジェクト (`target') の指定された名前のメンバー (`attribute') を mock オブジェクトでパッチします。

@ref{1906,,patch.object()} はデコレータ、クラスデコレータ、コンテキストマネージャーとして利用できます。引数の `new', `spec', `create', `spec_set', `autospec', `new_callable' は @ref{1092,,patch()} と同じ意味を持ちます。 @ref{1092,,patch()} と同じく、 @ref{1906,,patch.object()} も mock を生成するための任意のキーワード引数を受け取ります。

クラスデコレータとして利用する場合、 @ref{1906,,patch.object()} は @code{patch.TEST_PREFIX} にしたがってラップするメソッドを選択します。
@end deffn

@ref{1906,,patch.object()} の呼び出しには3引数の形式と2引数の形式があります。 3引数の場合、 patch 対象のオブジェクト、属性名、その属性を置き換えるオブジェクトを取ります。

2引数の形式では、置き換えるオブジェクトを省略し、生成された mock がデコレート対象となる関数に追加の引数として渡されます:

@example
>>> @@patch.object(SomeClass, 'class_method')
... def test(mock_method):
...     SomeClass.class_method(3)
...     mock_method.assert_called_with(3)
...
>>> test()
@end example

`spec', `create' やその他の @ref{1906,,patch.object()} の引数は @ref{1092,,patch()} の引数と同じ意味を持ちます。

@node patch dict,patch multiple,patch object,patcher
@anchor{library/unittest mock patch-dict}@anchor{4659}
@subsubsection patch.dict


@geindex patch.dict() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock patch dict}@anchor{1967}
@deffn {の関数} 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, where the restored dictionary is a
copy of the dictionary as it was before the test.

`in_dict' は辞書やその他のマップ型のコンテナです。マップ型の場合、最低限 get, set, del 操作とキーに対するイテレートをサポートしている必要があります。

`in_dict' に辞書を指定する文字列を渡した場合、それをインポートして取得します。

`values' は対象の辞書にセットする値を含む、辞書か @code{(key, value)} ペアの iterable です。

`clear' が true なら、新しい値が設定される前に辞書がクリアされます。

@ref{1967,,patch.dict()} はまた、任意のキーワード引数を受け取って辞書に設定します。


バージョン 3.8 で変更: @ref{1967,,patch.dict()} now returns the patched dictionary when used as a context
manager.

@end deffn

@ref{1967,,patch.dict()} can be used as a context manager, decorator or class
decorator:

@example
>>> foo = @{@}
>>> @@patch.dict(foo, @{'newkey': 'newvalue'@})
... def test():
...     assert foo == @{'newkey': 'newvalue'@}
...
>>> test()
>>> assert foo == @{@}
@end example

When used as a class decorator @ref{1967,,patch.dict()} honours
@code{patch.TEST_PREFIX} (default to @code{'test'}) for choosing which methods to wrap:

@example
>>> import os
>>> import unittest
>>> from unittest.mock import patch
>>> @@patch.dict('os.environ', @{'newkey': 'newvalue'@})
... class TestSample(unittest.TestCase):
...     def test_sample(self):
...         self.assertEqual(os.environ['newkey'], 'newvalue')
@end example

If you want to use a different prefix for your test, you can inform the
patchers of the different prefix by setting @code{patch.TEST_PREFIX}. For
more details about how to change the value of see @ref{465a,,TEST_PREFIX}.

@ref{1967,,patch.dict()} を使うと、辞書にメンバーを追加するか、または単にテストが辞書を変更して、その後テストが終了した時にその辞書が確実に復元されるようにすることができます。

@example
>>> foo = @{@}
>>> with patch.dict(foo, @{'newkey': 'newvalue'@}) as patched_foo:
...     assert foo == @{'newkey': 'newvalue'@}
...     assert patched_foo == @{'newkey': 'newvalue'@}
...     # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
...     patched_foo['spam'] = 'eggs'
...
>>> assert foo == @{@}
>>> assert patched_foo == @{@}
@end example

@example
>>> import os
>>> with patch.dict('os.environ', @{'newkey': 'newvalue'@}):
...     print(os.environ['newkey'])
...
newvalue
>>> assert 'newkey' not in os.environ
@end example

@ref{1967,,patch.dict()} を呼び出すときにキーワード引数を使って辞書に値をセットすることができます。

@example
>>> mymodule = MagicMock()
>>> mymodule.function.return_value = 'fish'
>>> with patch.dict('sys.modules', mymodule=mymodule):
...     import mymodule
...     mymodule.function('some', 'args')
...
'fish'
@end example

@ref{1967,,patch.dict()} 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 @ref{588,,__getitem__()}, @ref{14e3,,__setitem__()},
@ref{14e4,,__delitem__()} and either @ref{20aa,,__iter__()} or
@ref{15d3,,__contains__()}.

@example
>>> class Container:
...     def __init__(self):
...         self.values = @{@}
...     def __getitem__(self, name):
...         return self.values[name]
...     def __setitem__(self, name, value):
...         self.values[name] = value
...     def __delitem__(self, name):
...         del self.values[name]
...     def __iter__(self):
...         return iter(self.values)
...
>>> thing = Container()
>>> thing['one'] = 1
>>> with patch.dict(thing, one=2, two=3):
...     assert thing['one'] == 2
...     assert thing['two'] == 3
...
>>> assert thing['one'] == 1
>>> assert list(thing) == ['one']
@end example

@node patch multiple,patch のメソッド start と stop,patch dict,patcher
@anchor{library/unittest mock patch-multiple}@anchor{465b}
@subsubsection patch.multiple


@geindex patch.multiple() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock patch multiple}@anchor{465c}
@deffn {の関数} patch.multiple (target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

1回の呼び出しで複数のパッチを実行します。パッチ対象のオブジェクト (あるいはそのオブジェクトをインポートするための文字列) と、パッチ用のキーワード引数を取ります:

@example
with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
    ...
@end example

@ref{465c,,patch.multiple()} に mock を生成させたい場合、キーワード引数の値に @ref{4632,,DEFAULT} を指定します。この場合生成されたモックはデコレート対象の関数にキーワード引数として渡され、コンテキストマネージャーとして @ref{465c,,patch.multiple()} が利用された場合は辞書として返します。

@ref{465c,,patch.multiple()} はデコレータ、クラスデコレータ、コンテキストマネージャーとして使えます。引数の `spec', `spec_set', `create', `autospec', `new_callable' は @ref{1092,,patch()} の引数と同じ意味を持ちます。これらの引数は @ref{465c,,patch.multiple()} によって適用される `すべての' パッチに対して適用されます。

クラスデコレータとして利用する場合、 @ref{465c,,patch.multiple()} は @code{patch.TEST_PREFIX} にしたがってラップするメソッドを選択します。
@end deffn

@ref{465c,,patch.multiple()} に mock を生成させたい場合、キーワード引数の値に @ref{4632,,DEFAULT} を指定します。@ref{465c,,patch.multiple()} をデコレータとして使った場合生成されたモックはデコレート対象の関数にキーワード引数として渡されます。:

@example
>>> thing = object()
>>> other = object()

>>> @@patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(thing, other):
...     assert isinstance(thing, MagicMock)
...     assert isinstance(other, MagicMock)
...
>>> test_function()
@end example

@ref{465c,,patch.multiple()} は他の @code{patch} デコレータとネストして利用できますが、キーワード引数は @ref{1092,,patch()} によって作られる通常の引数の `後ろ' で受け取る必要があります:

@example
>>> @@patch('sys.exit')
... @@patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
...     assert 'other' in repr(other)
...     assert 'thing' in repr(thing)
...     assert 'exit' in repr(mock_exit)
...
>>> test_function()
@end example

@ref{465c,,patch.multiple()} がコンテキストマネージャーとして利用される場合、コンテキストマネージャーが返す値は、名前がキーで値が生成された mock となる辞書です:

@example
>>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
...     assert 'other' in repr(values['other'])
...     assert 'thing' in repr(values['thing'])
...     assert values['thing'] is thing
...     assert values['other'] is other
...
@end example

@node patch のメソッド start と stop,ビルトインをパッチする,patch multiple,patcher
@anchor{library/unittest mock patch-methods-start-and-stop}@anchor{465d}@anchor{library/unittest mock start-and-stop}@anchor{465e}
@subsubsection patch のメソッド: start と stop


All the patchers have @code{start()} and @code{stop()} methods. These make it simpler to do
patching in @code{setUp} methods or where you want to do multiple patches without
nesting decorators or with statements.

To use them call @ref{1092,,patch()}, @ref{1906,,patch.object()} or @ref{1967,,patch.dict()} as
normal and keep a reference to the returned @code{patcher} object. You can then
call @code{start()} to put the patch in place and @code{stop()} to undo it.

@ref{1092,,patch()} に mock を生成させる場合、 @code{patcher.start} の呼び出しの戻り値として mock を受け取れます。:

@example
>>> patcher = patch('package.module.ClassName')
>>> from package import module
>>> original = module.ClassName
>>> new_mock = patcher.start()
>>> assert module.ClassName is not original
>>> assert module.ClassName is new_mock
>>> patcher.stop()
>>> assert module.ClassName is original
>>> assert module.ClassName is not new_mock
@end example

A typical use case for this might be for doing multiple patches in the @code{setUp}
method of a @ref{2b3,,TestCase}:

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         self.patcher1 = patch('package.module.Class1')
...         self.patcher2 = patch('package.module.Class2')
...         self.MockClass1 = self.patcher1.start()
...         self.MockClass2 = self.patcher2.start()
...
...     def tearDown(self):
...         self.patcher1.stop()
...         self.patcher2.stop()
...
...     def test_something(self):
...         assert package.module.Class1 is self.MockClass1
...         assert package.module.Class2 is self.MockClass2
...
>>> MyTest('test_something').run()
@end example

@cartouche
@quotation 注意 
この方式を使う場合、必ず @code{stop} メソッドを呼び出してパッチが解除する必要があります。 @code{setUp} の中で例外が発生した場合 @code{tearDown} が呼び出されないので、これは意外に面倒です。 @ref{c74,,unittest.TestCase.addCleanup()} を使うと簡単にできます:

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         patcher = patch('package.module.Class')
...         self.MockClass = patcher.start()
...         self.addCleanup(patcher.stop)
...
...     def test_something(self):
...         assert package.module.Class is self.MockClass
...
@end example

この方式を使うと @code{patcher} オブジェクトの参照を維持する必要がなくなるという特典も付きます。
@end quotation
@end cartouche

@ref{465f,,patch.stopall()} を利用してすべての start されたパッチを stop することもできます。

@geindex patch.stopall() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock patch stopall}@anchor{465f}
@deffn {の関数} patch.stopall ()

すべての有効なパッチを stop します。 @code{start} で開始したパッチしか stop しません。
@end deffn

@node ビルトインをパッチする,TEST_PREFIX,patch のメソッド start と stop,patcher
@anchor{library/unittest mock id4}@anchor{4660}@anchor{library/unittest mock patch-builtins}@anchor{4661}
@subsubsection ビルトインをパッチする


モジュール内の任意のビルトインに対してパッチを当てることができます。以下の例はビルトインの @ref{233b,,ord()} を修正します:

@example
>>> @@patch('__main__.ord')
... def test(mock_ord):
...     mock_ord.return_value = 101
...     print(ord('c'))
...
>>> test()
101
@end example

@node TEST_PREFIX,patch デコレータをネストする,ビルトインをパッチする,patcher
@anchor{library/unittest mock id5}@anchor{4662}@anchor{library/unittest mock test-prefix}@anchor{465a}
@subsubsection TEST_PREFIX


すべての patcher はクラスデコレータとして利用できます。この場合、そのクラスのすべてのテストメソッドをラップします。 patcher は @code{'test'} で始まる名前のメソッドをテストメソッドだと認識します。これはデフォルトで @ref{593,,unittest.TestLoader} がテストメソッドを見つける方法と同じです。

他の prefix を使う事もできます。その場合、 patcher にその prefix を @code{patch.TEST_PREFIX} に設定することで教えることができます:

@example
>>> patch.TEST_PREFIX = 'foo'
>>> value = 3
>>>
>>> @@patch('__main__.value', 'not three')
... class Thing:
...     def foo_one(self):
...         print(value)
...     def foo_two(self):
...         print(value)
...
>>>
>>> Thing().foo_one()
not three
>>> Thing().foo_two()
not three
>>> value
3
@end example

@node patch デコレータをネストする,どこにパッチするか,TEST_PREFIX,patcher
@anchor{library/unittest mock nesting-patch-decorators}@anchor{4663}
@subsubsection patch デコレータをネストする


複数のパッチを行いたい場合、シンプルにデコレータを重ねることができます。

次のパターンのように patch デコレータを重ねることができます:

@example
>>> @@patch.object(SomeClass, 'class_method')
... @@patch.object(SomeClass, 'static_method')
... def test(mock1, mock2):
...     assert SomeClass.static_method is mock1
...     assert SomeClass.class_method is mock2
...     SomeClass.static_method('foo')
...     SomeClass.class_method('bar')
...     return mock1, mock2
...
>>> mock1, mock2 = test()
>>> mock1.assert_called_once_with('foo')
>>> mock2.assert_called_once_with('bar')
@end example

デコレータは下から上へと適用されることに注意してください。これは Python がデコレータを適用する標準的な方法です。テスト関数に渡される生成された mock の順番もこれに一致します。

@node どこにパッチするか,デスクリプタやプロキシオブジェクトにパッチする,patch デコレータをネストする,patcher
@anchor{library/unittest mock id6}@anchor{4657}@anchor{library/unittest mock where-to-patch}@anchor{462c}
@subsubsection どこにパッチするか


@ref{1092,,patch()} は (一時的に) ある `名前' が参照しているオブジェクトを別のものに変更することで適用されます。任意のオブジェクトには、それを参照するたくさんの名前が存在しえます。なので、必ずテスト対象のシステムが使っている名前に対して patch しなければなりません。

基本的な原則は、オブジェクトが `ルックアップ' されるところにパッチすることです。その場所はオブジェクトが定義されたところとは限りません。これを説明するためにいくつかの例を挙げます。

次のような構造を持ったプロジェクトをテストしようとしていると仮定してください:

@example
a.py
    -> Defines SomeClass

b.py
    -> from a import SomeClass
    -> some_function instantiates SomeClass
@end example

Now we want to test @code{some_function} but we want to mock out @code{SomeClass} using
@ref{1092,,patch()}. The problem is that when we import module b, which we will have to
do when it imports @code{SomeClass} from module a. If we use @ref{1092,,patch()} to mock out
@code{a.SomeClass} then it will have no effect on our test; module b already has a
reference to the `real' @code{SomeClass} and it looks like our patching had no
effect.

重要なのは、 @code{SomeClass} が使われている (もしくはルックアップされている) 場所にパッチすることです。この場合、 @code{some_function} はモジュール b の中にインポートされた @code{SomeClass} をルックアップしています。なのでパッチは次のようにしなければなりません:

@example
@@patch('b.SomeClass')
@end example

ですが、別のシナリオとして、module b が @code{from a import SomeClass} ではなく @code{import a} をしていて、 @code{some_function} が @code{a.SomeClass} を利用していたとします。どちらのインポートも一般的なものです。この場合、パッチしたいクラスはそのモジュールからルックアップされているので、 @code{a.SomeClass} をパッチする必要があります:

@example
@@patch('a.SomeClass')
@end example

@node デスクリプタやプロキシオブジェクトにパッチする,,どこにパッチするか,patcher
@anchor{library/unittest mock patching-descriptors-and-proxy-objects}@anchor{4664}
@subsubsection デスクリプタやプロキシオブジェクトにパッチする


@ref{4656,,patch} と @ref{4658,,patch.object} はどちらも デスクリプタ (クラスメソッド、static メソッド、プロパティ) を正しく patch できます。デスクリプタに patch する場合、インスタンスではなく `class' にパッチする必要があります。これらはまた `幾らかの' 属性アクセスをプロキシするオブジェクト、例えば django の setttings オブジェクト@footnote{https://web.archive.org/web/20200603181648/http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198} に対しても機能します。

@node MagicMock と magic method のサポート,ヘルパー,patcher,unittest mock --- モックオブジェクトライブラリ
@anchor{library/unittest mock magicmock-and-magic-method-support}@anchor{4665}
@subsubsection MagicMock と magic method のサポート


@menu
* Magic Method をモックする:: 
* Magic Mock:: 

@end menu

@node Magic Method をモックする,Magic Mock,,MagicMock と magic method のサポート
@anchor{library/unittest mock magic-methods}@anchor{462d}@anchor{library/unittest mock mocking-magic-methods}@anchor{4666}
@subsubsection Magic Method をモックする


@ref{c3f,,Mock} supports mocking the Python protocol methods, also known as
@ref{4667,,"magic methods"}. This allows mock objects to replace
containers or other objects that implement Python protocols.

magic method は通常のメソッドとはルックアップ方法が異なるので @footnote{
Magic method はインスタンスではなくクラスからルックアップされるはずです。Python のバージョンによってこのルールが適用されるかどうかに違いがあります。サポートされているプロトコルメソッドは、サポートされているすべての Python のバージョンで動作するはずです。
}, magic method のサポートは特別に実装されています。そのため、サポートされているのは特定の magic method のみです。`ほとんど' すべてのメソッドをサポートしていますが、足りないものを見つけたら私達に教えてください。

magic method を mock するには、対象の method に対して関数や mock のインスタンスをセットします。もし関数を使う場合、それは第一引数に @code{self} を取る `必要があります' @footnote{
関数はクラスまで hook しますが、各 @code{Mock} インスタンス間の独立性は保たれます。
}.

@example
>>> def __str__(self):
...     return 'fooble'
...
>>> mock = Mock()
>>> mock.__str__ = __str__
>>> str(mock)
'fooble'
@end example

@example
>>> mock = Mock()
>>> mock.__str__ = Mock()
>>> mock.__str__.return_value = 'fooble'
>>> str(mock)
'fooble'
@end example

@example
>>> mock = Mock()
>>> mock.__iter__ = Mock(return_value=iter([]))
>>> list(mock)
[]
@end example

ユースケースの1つは @ref{186,,with} 文の中でコンテキストマネージャーとして使われるオブジェクトを mock することです。

@example
>>> mock = Mock()
>>> mock.__enter__ = Mock(return_value='foo')
>>> mock.__exit__ = Mock(return_value=False)
>>> with mock as m:
...     assert m == 'foo'
...
>>> mock.__enter__.assert_called_with()
>>> mock.__exit__.assert_called_with(None, None, None)
@end example

magic method の呼び出しは @ref{4639,,method_calls} に含まれませんが、 @ref{4637,,mock_calls} には記録されます。

@cartouche
@quotation 注釈 
mock を生成するのに `spec' キーワード引数を使った場合、 spec に含まれない magic method を設定しようとすると @ref{5f0,,AttributeError} が発生します。
@end quotation
@end cartouche

サポートしている magic method の完全なリスト:


@itemize *

@item 
@code{__hash__}, @code{__sizeof__}, @code{__repr__}, @code{__str__}

@item 
@code{__dir__}, @code{__format__}, @code{__subclasses__}

@item 
@code{__round__}, @code{__floor__}, @code{__trunc__} と @code{__ceil__}

@item 
比較: @code{__lt__}, @code{__gt__}, @code{__le__}, @code{__ge__}, @code{__eq__}, @code{__ne__}

@item 
コンテナメソッド: @code{__getitem__}, @code{__setitem__}, @code{__delitem__}, @code{__contains__}, @code{__len__}, @code{__iter__}, @code{__reversed__},  @code{__missing__}

@item 
Context manager: @code{__enter__}, @code{__exit__}, @code{__aenter__} and @code{__aexit__}

@item 
単項算術メソッド: @code{__neg__}, @code{__pos__}, @code{__invert__}

@item 
The numeric methods (including right hand and in-place variants):
@code{__add__}, @code{__sub__}, @code{__mul__}, @code{__matmul__}, @code{__truediv__},
@code{__floordiv__}, @code{__mod__}, @code{__divmod__}, @code{__lshift__},
@code{__rshift__}, @code{__and__}, @code{__xor__}, @code{__or__}, and @code{__pow__}

@item 
算術変換メソッド: @code{__complex__}, @code{__int__}, @code{__float__},  @code{__index__}

@item 
デスクリプタメソッド: @code{__get__}, @code{__set__}, @code{__delete__}

@item 
pickle: @code{__reduce__}, @code{__reduce_ex__}, @code{__getinitargs__}, @code{__getnewargs__}, @code{__getstate__}, @code{__setstate__}

@item 
File system path representation: @code{__fspath__}

@item 
Asynchronous iteration methods: @code{__aiter__} and @code{__anext__}
@end itemize


バージョン 3.8 で変更: Added support for @ref{e4c,,os.PathLike.__fspath__()}.



バージョン 3.8 で変更: Added support for @code{__aenter__}, @code{__aexit__}, @code{__aiter__} and @code{__anext__}.


以下のメソッドは存在しますが、mock が利用している、動的に設定不可能、その他の問題が発生する可能性があるなどの理由で `サポートされていません':


@itemize *

@item 
@code{__getattr__}, @code{__setattr__}, @code{__init__}, @code{__new__}

@item 
@code{__prepare__}, @code{__instancecheck__}, @code{__subclasscheck__}, @code{__del__}
@end itemize

@node Magic Mock,,Magic Method をモックする,MagicMock と magic method のサポート
@anchor{library/unittest mock magic-mock}@anchor{4668}
@subsubsection Magic Mock


@code{MagicMock} 系のクラスは2種類あります: @ref{108f,,MagicMock} と @ref{4631,,NonCallableMagicMock} です。

@geindex MagicMock (unittest.mock のクラス)
@anchor{library/unittest mock unittest mock MagicMock}@anchor{108f}
@deffn {クラス} unittest.mock.MagicMock (*args, **kw)

@code{MagicMock} is a subclass of @ref{c3f,,Mock} with default implementations
of most of the @ref{4667,,magic methods}. You can use
@code{MagicMock} without having to configure the magic methods yourself.

コンストラクタの引数は @ref{c3f,,Mock} と同じ意味を持っています。

`spec' か `spec_set' 引数を利用した場合、 spec に存在する magic method `のみ' が生成されます。
@end deffn

@geindex NonCallableMagicMock (unittest.mock のクラス)
@anchor{library/unittest mock unittest mock NonCallableMagicMock}@anchor{4631}
@deffn {クラス} unittest.mock.NonCallableMagicMock (*args, **kw)

callable でないバージョンの @ref{108f,,MagicMock}

コンストラクタの引数は @ref{108f,,MagicMock} と同じ意味を持ちますが、 `return_value' と `side_effect' は callable でない mock では意味を持ちません。
@end deffn

@ref{108f,,MagicMock} が magic method をセットアップするので、あとは通常の方法で構成したり利用したりできます:

@example
>>> mock = MagicMock()
>>> mock[3] = 'fish'
>>> mock.__setitem__.assert_called_with(3, 'fish')
>>> mock.__getitem__.return_value = 'result'
>>> mock[2]
'result'
@end example

デフォルトでは、多くのプロトコルメソッドは特定の型の戻り値を要求されます。それらのメソッドではその型のデフォルトの戻り値がデフォルトの戻り値として設定されているので、戻り値に興味が有る場合以外は何もしなくても利用可能です。デフォルトの値を変更したい場合は手動で戻り値を設定可能です。

メソッドとそのデフォルト値:


@itemize *

@item 
@code{__lt__}: @ref{1a2,,NotImplemented}

@item 
@code{__gt__}: @code{NotImplemented}

@item 
@code{__le__}: @code{NotImplemented}

@item 
@code{__ge__}: @code{NotImplemented}

@item 
@code{__int__}: @code{1}

@item 
@code{__contains__}: @code{False}

@item 
@code{__len__}: @code{0}

@item 
@code{__iter__}: @code{iter([])}

@item 
@code{__exit__}: @code{False}

@item 
@code{__aexit__}: @code{False}

@item 
@code{__complex__}: @code{1j}

@item 
@code{__float__}: @code{1.0}

@item 
@code{__bool__}: @code{True}

@item 
@code{__index__}: @code{1}

@item 
@code{__hash__}: mock のデフォルトの hash

@item 
@code{__str__}: mock のデフォルトの str

@item 
@code{__sizeof__}: mock のデフォルトの sizeof
@end itemize

例えば:

@example
>>> mock = MagicMock()
>>> int(mock)
1
>>> len(mock)
0
>>> list(mock)
[]
>>> object() in mock
False
@end example

The two equality methods, @code{__eq__()} and @code{__ne__()}, are special.
They do the default equality comparison on identity, using the
@ref{462b,,side_effect} attribute, unless you change their return value to
return something else:

@example
>>> MagicMock() == 3
False
>>> MagicMock() != 3
True
>>> mock = MagicMock()
>>> mock.__eq__.return_value = True
>>> mock == 3
True
@end example

@code{MagicMock.__iter__()} の return_value は任意の iterable で、イテレータである必要はありません:

@example
>>> mock = MagicMock()
>>> mock.__iter__.return_value = ['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
@end example

return_value が iterator であった場合、最初のイテレートでその iterator を消費してしまい、2回目以降のイテレートの結果が空になってしまいます:

@example
>>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
[]
@end example

@code{MagicMock} はいくつかの曖昧であったり時代遅れなものをのぞいて、対応している magic method を事前にセットアップします。自動でセットアップされていないものも必要なら手動でセットアップすることができます。

@code{MagicMock} がサポートしているもののデフォルトではセットアップしない magic method:


@itemize *

@item 
@code{__subclasses__}

@item 
@code{__dir__}

@item 
@code{__format__}

@item 
@code{__get__}, @code{__set__}, @code{__delete__}

@item 
@code{__reversed__}, @code{__missing__}

@item 
@code{__reduce__}, @code{__reduce_ex__}, @code{__getinitargs__}, @code{__getnewargs__}, @code{__getstate__}, @code{__setstate__}

@item 
@code{__getformat__}
@end itemize

@node ヘルパー,Order of precedence of side_effect return_value and wraps,MagicMock と magic method のサポート,unittest mock --- モックオブジェクトライブラリ
@anchor{library/unittest mock helpers}@anchor{4669}
@subsubsection ヘルパー


@menu
* sentinel:: 
* DEFAULT:: 
* call:: 
* create_autospec:: 
* ANY:: 
* FILTER_DIR:: 
* mock_open:: 
* autospec を使う:: 
* Sealing mocks:: 

@end menu

@node sentinel,DEFAULT,,ヘルパー
@anchor{library/unittest mock sentinel}@anchor{466a}
@subsubsection sentinel


@geindex sentinel (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock sentinel}@anchor{d99}
@deffn {データ} unittest.mock.sentinel

@code{sentinel} オブジェクトはテストで必要なユニークなオブジェクトを簡単に提供します。

属性はアクセス時にオンデマンドで生成されます。同じ属性に複数回アクセスすると必ず同じオブジェクトが返されます。返されるオブジェクトは、テスト失敗のメッセージがわかりやすくなるように気が利いた repr を持ちます。


バージョン 3.7 で変更: The @code{sentinel} attributes now preserve their identity when they are
@ref{29,,copied} or @ref{ab,,pickled}.

@end deffn

特定のオブジェクトが他のメソッドに引数として渡されることをテストしたり、返されることをテストしたい場合があります。このテストのために名前がついた sentinel オブジェクトを作るのが一般的です。 @ref{d99,,sentinel} はこのようなオブジェクトを生成し、同一性をテストするのに便利な方法を提供します。

次の例では、 @code{method} が @code{sentinel.some_object} を返すようにモンキーパッチしています:

@example
>>> real = ProductionClass()
>>> real.method = Mock(name="method")
>>> real.method.return_value = sentinel.some_object
>>> result = real.method()
>>> assert result is sentinel.some_object
>>> result
sentinel.some_object
@end example

@node DEFAULT,call,sentinel,ヘルパー
@anchor{library/unittest mock default}@anchor{466b}
@subsubsection DEFAULT


@geindex DEFAULT (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock DEFAULT}@anchor{4632}
@deffn {データ} unittest.mock.DEFAULT

@ref{4632,,DEFAULT} オブジェクトは事前に生成された sentinel (実際には @code{sentinel.DEFAULT}) オブジェクトです。 @ref{462b,,side_effect} 関数が、通常の戻り値を使うことを示すために使います。
@end deffn

@node call,create_autospec,DEFAULT,ヘルパー
@anchor{library/unittest mock call}@anchor{466c}
@subsubsection call


@geindex call() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock call}@anchor{1db3}
@deffn {の関数} unittest.mock.call (*args, **kwargs)

@ref{1db3,,call()} は @ref{1d69,,call_args}, @ref{463e,,call_args_list}, @ref{4637,,mock_calls}, @ref{4639,,method_calls} と比較してより簡単に assert できるようにするためのヘルパーオブジェクトです。 @ref{1db3,,call()} は @ref{1a22,,assert_has_calls()} と組み合わせて使うこともできます。

@example
>>> m = MagicMock(return_value=None)
>>> m(1, 2, a='foo', b='bar')
>>> m()
>>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
True
@end example
@end deffn

@geindex call_list() (unittest.mock.call のメソッド)
@anchor{library/unittest mock unittest mock call call_list}@anchor{466d}
@deffn {メソッド} call.call_list ()

複数回の呼び出しを表す call オブジェクトに対して、 @ref{466d,,call_list()} はすべての途中の呼び出しと最終の呼び出しを含むリストを返します。
@end deffn

@code{call_list} は特に "chained call" に対して assert するのに便利です。 "chained call" は1行のコードにおける複数の呼び出しです。この結果は mock の @ref{4637,,mock_calls} に複数の call エントリとして格納されます。この call のシーケンスを手動で構築するのは退屈な作業になります。

@ref{466d,,call_list()} は同じ chained call からその call のシーケンスを構築することができます:

@example
>>> m = MagicMock()
>>> m(1).method(arg='foo').other('bar')(2.0)
<MagicMock name='mock().method().other()()' id='...'>
>>> kall = call(1).method(arg='foo').other('bar')(2.0)
>>> kall.call_list()
[call(1),
 call().method(arg='foo'),
 call().method().other('bar'),
 call().method().other()(2.0)]
>>> m.mock_calls == kall.call_list()
True
@end example
@anchor{library/unittest mock calls-as-tuples}@anchor{463f}
@code{call} オブジェクトは、どう構築されたかによって、 (位置引数、キーワード引数) のタプルか、 (名前、位置引数、キーワード引数) のタプルになります。自分で call オブジェクトを構築するときはこれを意識する必要はありませんが、 @ref{1d69,,Mock.call_args}, @ref{463e,,Mock.call_args_list}, @ref{4637,,Mock.mock_calls} 属性の中の @code{call} オブジェクトを解析して個々の引数を解析することができます。

@ref{1d69,,Mock.call_args} と @ref{463e,,Mock.call_args_list} の中の @code{call} オブジェクトは (位置引数, キーワード引数) のタプルで、 @ref{4637,,Mock.mock_calls} の中の @code{call} オブジェクトや自分で構築したオブジェクトは (名前, 位置引数, キーワード引数) のタプルになります。

call オブジェクトの "タプル性" を使って、より複雑な内省とアサートを行うために各引数を取り出しすことができます。位置引数はタプル (位置引数が存在しない場合は空のタプル) で、キーワード引数は辞書になります:

@example
>>> m = MagicMock(return_value=None)
>>> m(1, 2, 3, arg='one', arg2='two')
>>> kall = m.call_args
>>> kall.args
(1, 2, 3)
>>> kall.kwargs
@{'arg': 'one', 'arg2': 'two'@}
>>> kall.args is kall[0]
True
>>> kall.kwargs is kall[1]
True
@end example

@example
>>> m = MagicMock()
>>> m.foo(4, 5, 6, arg='two', arg2='three')
<MagicMock name='mock.foo()' id='...'>
>>> kall = m.mock_calls[0]
>>> name, args, kwargs = kall
>>> name
'foo'
>>> args
(4, 5, 6)
>>> kwargs
@{'arg': 'two', 'arg2': 'three'@}
>>> name is m.mock_calls[0][0]
True
@end example

@node create_autospec,ANY,call,ヘルパー
@anchor{library/unittest mock create-autospec}@anchor{466e}
@subsubsection create_autospec


@geindex create_autospec() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock create_autospec}@anchor{1934}
@deffn {の関数} unittest.mock.create_autospec (spec, spec_set=False, instance=False, **kwargs)

他のオブジェクトを spec として利用して mock オブジェクトを作ります。 mock の属性も、 `spec' オブジェクトの該当する属性を spec として利用します。

mock された関数やメソッドは、正しいシグネチャで呼び出されたことを確認するために引数をチェックします。

`spec_set' が @code{True} のとき、 spec オブジェクトにない属性をセットしようとすると @ref{5f0,,AttributeError} を発生させます。

spec にクラスが指定された場合、 mock の戻り値 (そのクラスのインスタンス) は同じ spec を持ちます。 @code{instance=True} を指定すると、インスタンスオブジェクトの spec としてクラスを利用できます。返される mock は、モックのインスタンスが callable な場合にだけ callable となります。

@ref{1934,,create_autospec()} は任意のキーワード引数を受け取り、生成する mock のコンストラクタに渡します。
@end deffn

@ref{1934,,create_autospec()} や、 @ref{1092,,patch()} の `autospec' 引数で autospec を使うサンプルは @ref{462e,,autospec を使う} を参照してください。


バージョン 3.8 で変更: @ref{1934,,create_autospec()} now returns an @ref{c3e,,AsyncMock} if the target is
an async function.


@node ANY,FILTER_DIR,create_autospec,ヘルパー
@anchor{library/unittest mock any}@anchor{466f}
@subsubsection ANY


@geindex ANY (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock ANY}@anchor{1db1}
@deffn {データ} unittest.mock.ANY
@end deffn

mock の呼び出しのうち `幾つか' の引数に対して assert したいけれども、それ以外の引数は気にしない、あるいは @ref{1d69,,call_args} から個別に取り出してより高度な assert を行いたい場合があります。

特定の引数を無視するために、 `すべて' と等しくなるオブジェクトを使うことができます。そうすると、 @ref{1e03,,assert_called_with()} と @ref{4635,,assert_called_once_with()} は、実際の引数が何であったかに関わらず成功します。

@example
>>> mock = Mock(return_value=None)
>>> mock('foo', bar=object())
>>> mock.assert_called_once_with('foo', bar=ANY)
@end example

@ref{4637,,mock_calls} などの call list との比較に @ref{1db1,,ANY} を使うこともできます:

@example
>>> m = MagicMock(return_value=None)
>>> m(1)
>>> m(1, 2)
>>> m(object())
>>> m.mock_calls == [call(1), call(1, 2), ANY]
True
@end example

@ref{1db1,,ANY} is not limited to comparisons with call objects and so
can also be used in test assertions:

@example
class TestStringMethods(unittest.TestCase):

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', ANY])
@end example

@node FILTER_DIR,mock_open,ANY,ヘルパー
@anchor{library/unittest mock filter-dir}@anchor{4670}
@subsubsection FILTER_DIR


@geindex FILTER_DIR (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock FILTER_DIR}@anchor{463b}
@deffn {データ} unittest.mock.FILTER_DIR
@end deffn

@ref{463b,,FILTER_DIR} は mock オブジェクトが @ref{844,,dir()} に何を返すかを制御するためのモジュールレベル変数です。デフォルトは @code{True} で、以下に示すフィルタリングを行い、有用なメンバーだけを表示します。このフィルタリングが嫌な場合や、何かの診断のためにフィルタリングを切りたい場合は、 @code{mock.FILTER_DIR = False} と設定してください。

フィルタリングが有効な場合、 @code{dir(some_mock)} は有用な属性だけを表示し、また通常は表示されない動的に生成される属性も表示します。 mock が `spec' を使って(もちろん `autospec' でも)生成された場合、元のオブジェクトのすべての属性が、まだアクセスされていなかったとしても、表示されます。

@example
>>> dir(Mock())
['assert_any_call',
 'assert_called',
 'assert_called_once',
 'assert_called_once_with',
 'assert_called_with',
 'assert_has_calls',
 'assert_not_called',
 'attach_mock',
 ...
>>> from urllib import request
>>> dir(Mock(spec=request))
['AbstractBasicAuthHandler',
 'AbstractDigestAuthHandler',
 'AbstractHTTPHandler',
 'BaseHandler',
 ...
@end example

多くのあまり有用ではない (mock 対象のものではなく、 @ref{c3f,,Mock} 自身のプライベートな) 属性は、アンダースコアと2つのアンダースコアで prefix された属性は @ref{c3f,,Mock} に対して @ref{844,,dir()} した結果からフィルタリングされます。この動作が嫌な場合は、モジュールレベルの @ref{463b,,FILTER_DIR} スイッチを設定することでフィルターを切ることができます。

@example
>>> from unittest import mock
>>> mock.FILTER_DIR = False
>>> dir(mock.Mock())
['_NonCallableMock__get_return_value',
 '_NonCallableMock__get_side_effect',
 '_NonCallableMock__return_value_doc',
 '_NonCallableMock__set_return_value',
 '_NonCallableMock__set_side_effect',
 '__call__',
 '__class__',
 ...
@end example

Alternatively you can just use @code{vars(my_mock)} (instance members) and
@code{dir(type(my_mock))} (type members) to bypass the filtering irrespective of
@ref{463b,,FILTER_DIR}.

@node mock_open,autospec を使う,FILTER_DIR,ヘルパー
@anchor{library/unittest mock mock-open}@anchor{4671}
@subsubsection mock_open


@geindex mock_open() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock mock_open}@anchor{11e9}
@deffn {の関数} unittest.mock.mock_open (mock=None, read_data=None)

@ref{316,,open()} の利用を置き換えるための mock を作るヘルパー関数。 @ref{316,,open()} を直接呼んだりコンテキストマネージャーとして利用する場合に使うことができます。

`mock' 引数は構成する mock オブジェクトです。 @code{None} (デフォルト) なら、通常のファイルハンドルと同じ属性やメソッドにAPIが制限された @ref{108f,,MagicMock} が生成されます。

`read_data' is a string for the @ref{101d,,read()},
@ref{1541,,readline()}, and @ref{27a1,,readlines()} 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@footnote{https://pypi.org} can offer a realistic filesystem for testing.


バージョン 3.4 で変更: Added @ref{1541,,readline()} and @ref{27a1,,readlines()} support.
The mock of @ref{101d,,read()} changed to consume `read_data' rather
than returning it on each call.



バージョン 3.5 で変更: `read_data' は `mock' を呼び出す度に毎回リセットされるようになりました。



バージョン 3.8 で変更: Added @ref{20aa,,__iter__()} to implementation so that iteration
(such as in for loops) correctly consumes `read_data'.

@end deffn

@ref{316,,open()} をコンテキストマネージャーとして使う方法は、ファイルが必ず適切に閉じられるようにする素晴らしい方法で、今では一般的になっています:

@example
with open('/some/path', 'w') as f:
    f.write('something')
@end example

The issue is that even if you mock out the call to @ref{316,,open()} it is the
`returned object' that is used as a context manager (and has @ref{7e4,,__enter__()} and
@ref{1518,,__exit__()} called).

コンテキストマネージャーを @ref{108f,,MagicMock} でモックするのは一般的かつ面倒なので、ヘルパー関数を用意しています。:

@example
>>> m = mock_open()
>>> with patch('__main__.open', m):
...     with open('foo', 'w') as h:
...         h.write('some stuff')
...
>>> m.mock_calls
[call('foo', 'w'),
 call().__enter__(),
 call().write('some stuff'),
 call().__exit__(None, None, None)]
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
@end example

ファイルの読み込みをモックする例:

@example
>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h:
...         result = h.read()
...
>>> m.assert_called_once_with('foo')
>>> assert result == 'bibble'
@end example

@node autospec を使う,Sealing mocks,mock_open,ヘルパー
@anchor{library/unittest mock auto-speccing}@anchor{462e}@anchor{library/unittest mock autospeccing}@anchor{4672}
@subsubsection autospec を使う


Autospeccing is based on the existing @code{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 @ref{198,,TypeError} if they are
called incorrectly.

autospec の動作について説明する前に、それが必要となる背景から説明していきます。

@ref{c3f,,Mock} is a very powerful and flexible object, but it suffers from a flaw which
is 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.


バージョン 3.5 で変更: Before 3.5, tests with a typo in the word assert would silently pass when they should
raise an error. You can still achieve this behavior by passing @code{unsafe=True} to Mock.


各ユニットが互いにどのように接続されるかをテストしない場合、依然としてテストで見つけることができるバグの余地が多く残っています。

@code{unittest.mock} already provides a feature to help with this, called speccing. If you
use a class or instance as the @code{spec} for a mock then you can only access
attributes on the mock that exist on the real class:

@example
>>> from urllib import request
>>> mock = Mock(spec=request.Request)
>>> mock.assret_called_with  # Intentional typo!
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'assret_called_with'
@end example

spec はその mock 自体にしか適用されません。なので、同じ問題がその mock のすべてのメソッドに対して発生します:

@example
>>> mock.header_items()
<mock.Mock object at 0x...>
>>> mock.header_items.assret_called_with()  # Intentional typo!
@end example

autospec はこの問題を解決します。 @ref{1092,,patch()} か @ref{1906,,patch.object()} に @code{autospec=True} を渡すか、 @ref{1934,,create_autospec()} 関数を使って spec をもとに mock を作ることができます。 @ref{1092,,patch()} の引数に @code{autospec=True} を渡した場合、置換対象のオブジェクトが spec オブジェクトとして利用されます。 spec は遅延処理される (mock の属性にアクセスされた時に spec が生成される) ので、非常に複雑だったり深くネストしたオブジェクト (例えばモジュールをインポートするモジュールをインポートするモジュール) に対しても大きなパフォーマンスの問題なしに autospec を使うことができます。

autospec の利用例:

@example
>>> from urllib import request
>>> patcher = patch('__main__.request', autospec=True)
>>> mock_request = patcher.start()
>>> request is mock_request
True
>>> mock_request.Request
<MagicMock name='request.Request' spec='Request' id='...'>
@end example

You can see that @code{request.Request} has a spec. @code{request.Request} takes two
arguments in the constructor (one of which is `self'). Here's what happens if
we try to call it incorrectly:

@example
>>> req = request.Request()
Traceback (most recent call last):
 ...
TypeError: <lambda>() takes at least 2 arguments (1 given)
@end example

spec はクラスがインスタンス化されたとき (つまり spec が適用された mock の戻り値) にも適用されます:

@example
>>> req = request.Request('foo')
>>> req
<NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
@end example

@code{Request} objects are not callable, so the return value of instantiating our
mocked out @code{request.Request} is a non-callable mock. With the spec in place
any typos in our asserts will raise the correct error:

@example
>>> req.add_header('spam', 'eggs')
<MagicMock name='request.Request().add_header()' id='...'>
>>> req.add_header.assret_called_with  # Intentional typo!
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'assret_called_with'
>>> req.add_header.assert_called_with('spam', 'eggs')
@end example

多くの場合、単に既存の @ref{1092,,patch()} 呼び出しに @code{autospec=True} を加えるだけで、ミススペルやAPI変更に伴うバグから守られます。

@ref{1092,,patch()} を経由する以外にも、 @ref{1934,,create_autospec()} を使って `autospec' が適用された mock を直接作る方法もあります:

@example
>>> from urllib import request
>>> mock_request = create_autospec(request)
>>> mock_request.Request('foo', 'bar')
<NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
@end example

とはいえ、autospec には注意しなければならない点や制限があり、そのためデフォルトでは無効になっています。spec オブジェクトでどんな属性が使えるかどうかを調べるために、autospec は spec オブジェクトをイントロスペクト (実際に属性にアクセスする) 必要があります。mock の属性を利用するとき、水面下で元のオブジェクトに対しても同じ属性の探索が行われます。spec したオブジェクトのどれかがコードを実行するプロパティやデスクリプタを持っている場合、autospec は正しく動きません。もしくは、イントロスペクションしても安全なようにオブジェクトを設計するのがよいでしょう @footnote{
これはクラスやすでにインスタンス化されたオブジェクトにだけ当てはまります。 mock されたクラスを呼び出して mock インスタンスを作っても、実際のオブジェクトのインスタンスは生成されません。
mock は属性を - @ref{844,,dir()} を呼び出して - 検索するだけです。
}。

A more serious problem is that it is common for instance attributes to be
created in the @ref{8bf,,__init__()} 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.

@example
>>> class Something:
...   def __init__(self):
...     self.a = 33
...
>>> with patch('__main__.Something', autospec=True):
...   thing = Something()
...   thing.a
...
Traceback (most recent call last):
  ...
AttributeError: Mock object has no attribute 'a'
@end example

この問題を解決するためにいくつかの方法があります。一番簡単な、ただし一番面倒でないとは限らない方法は、必要とされる属性を mock が生成された後に設定することです。 `autospec' は属性を参照することを禁止しますが、設定することは禁止していません:

@example
>>> with patch('__main__.Something', autospec=True):
...   thing = Something()
...   thing.a = 33
...
@end example

`spec' と `autospec' にはよりアグレッシブなバージョンがあり、存在しない属性への設定も禁止します。これはコードが正しい属性にのみ代入することを保証したいときに便利ですが、もちろん先ほどの方法も制限されてしまいます:

@example
>>> with patch('__main__.Something', autospec=True, spec_set=True):
...   thing = Something()
...   thing.a = 33
...
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'a'
@end example

Probably the best way of solving the problem is to add class attributes as
default values for instance members initialised in @ref{8bf,,__init__()}.
Note that if
you are only setting default attributes in @code{__init__()} then providing them via
class attributes (shared between instances of course) is faster too. e.g.

@example
class Something:
    a = 33
@end example

クラス属性を使ってもまた別の問題があります。メンバーのデフォルト値に @code{None} を利用し、後から別の型のオブジェクトを代入するのは比較的よくあるパターンです。 spec として @code{None} を使うと `すべての' 属性やメソッドへのアクセスも許されなくなるので使い物になりません。 @code{None} を spec にすることが有用な場面は `決して' なく、おそらくそのメンバーは他の何かの型のメンバーになることを示すので、 autospec は @code{None} に設定されているメンバーには spec を使いません。その属性は通常の mock (MagicMocks) になります。

@example
>>> class Something:
...     member = None
...
>>> mock = create_autospec(Something)
>>> mock.member.foo.bar.baz()
<MagicMock name='mock.member.foo.bar.baz()' id='...'>
@end example

すでに利用されているクラスにデフォルト値属性を追加するのが嫌な場合は、他の選択肢もあります。選択肢の1つは、クラスではなくインスタンスを spec に使うことです。別の選択肢は、実際のクラスのサブクラスを作り、実際に利用されている方に影響を与えずにデフォルト値属性を追加することです。どちらの方法も spec として代替オブジェクトを利用することが必要です。 @ref{1092,,patch()} はこれをサポートしていて、 `autospec' 引数に代替オブジェクトを渡すことができます:

@example
>>> class Something:
...   def __init__(self):
...     self.a = 33
...
>>> class SomethingForTest(Something):
...   a = 33
...
>>> p = patch('__main__.Something', autospec=SomethingForTest)
>>> mock = p.start()
>>> mock.a
<NonCallableMagicMock name='Something.a' spec='int' id='...'>
@end example

@node Sealing mocks,,autospec を使う,ヘルパー
@anchor{library/unittest mock sealing-mocks}@anchor{4673}
@subsubsection Sealing mocks


@c from unittest.mock import seal

@geindex seal() (unittest.mock モジュール)
@anchor{library/unittest mock unittest mock seal}@anchor{d9a}
@deffn {の関数} 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.

@example
>>> mock = Mock()
>>> mock.submock.attribute1 = 2
>>> mock.not_submock = mock.Mock(name="sample_name")
>>> seal(mock)
>>> mock.new_attribute  # This will raise AttributeError.
>>> mock.submock.attribute2  # This will raise AttributeError.
>>> mock.not_submock.attribute2  # This won't raise.
@end example


Added in version 3.7.

@end deffn

@node Order of precedence of side_effect return_value and wraps,,ヘルパー,unittest mock --- モックオブジェクトライブラリ
@anchor{library/unittest mock order-of-precedence-of-side-effect-return-value-and-wraps}@anchor{4674}
@subsubsection Order of precedence of @code{side_effect}, @code{return_value} and `wraps'


The order of their precedence is:


@enumerate 

@item 
@ref{462b,,side_effect}

@item 
@ref{4633,,return_value}

@item 
`wraps'
@end enumerate

If all three are set, mock will return the value from @ref{462b,,side_effect},
ignoring @ref{4633,,return_value} and the wrapped object altogether. If any
two are set, the one with the higher precedence will return the value.
Regardless of the order of which was set first, the order of precedence
remains unchanged.

@example
>>> from unittest.mock import Mock
>>> class Order:
...     @@staticmethod
...     def get_value():
...         return "third"
...
>>> order_mock = Mock(spec=Order, wraps=Order)
>>> order_mock.get_value.side_effect = ["first"]
>>> order_mock.get_value.return_value = "second"
>>> order_mock.get_value()
'first'
@end example

As @code{None} is the default value of @ref{462b,,side_effect}, if you reassign
its value back to @code{None}, the order of precedence will be checked between
@ref{4633,,return_value} and the wrapped object, ignoring
@ref{462b,,side_effect}.

@example
>>> order_mock.get_value.side_effect = None
>>> order_mock.get_value()
'second'
@end example

If the value being returned by @ref{462b,,side_effect} is @ref{4632,,DEFAULT},
it is ignored and the order of precedence moves to the successor to obtain the
value to return.

@example
>>> from unittest.mock import DEFAULT
>>> order_mock.get_value.side_effect = [DEFAULT]
>>> order_mock.get_value()
'second'
@end example

When @ref{c3f,,Mock} wraps an object, the default value of
@ref{4633,,return_value} will be @ref{4632,,DEFAULT}.

@example
>>> order_mock = Mock(spec=Order, wraps=Order)
>>> order_mock.return_value
sentinel.DEFAULT
>>> order_mock.get_value.return_value
sentinel.DEFAULT
@end example

The order of precedence will ignore this value and it will move to the last
successor which is the wrapped object.

As the real call is being made to the wrapped object, creating an instance of
this mock will return the real instance of the class. The positional arguments,
if any, required by the wrapped object must be passed.

@example
>>> order_mock_instance = order_mock()
>>> isinstance(order_mock_instance, Order)
True
>>> order_mock_instance.get_value()
'third'
@end example

@example
>>> order_mock.get_value.return_value = DEFAULT
>>> order_mock.get_value()
'third'
@end example

@example
>>> order_mock.get_value.return_value = "second"
>>> order_mock.get_value()
'second'
@end example

But if you assign @code{None} to it, this will not be ignored as it is an
explicit assignment. So, the order of precedence will not move to the wrapped
object.

@example
>>> order_mock.get_value.return_value = None
>>> order_mock.get_value() is None
True
@end example

Even if you set all three at once when initializing the mock, the order of
precedence remains the same:

@example
>>> order_mock = Mock(spec=Order, wraps=Order,
...                   **@{"get_value.side_effect": ["first"],
...                      "get_value.return_value": "second"@}
...                   )
...
>>> order_mock.get_value()
'first'
>>> order_mock.get_value.side_effect = None
>>> order_mock.get_value()
'second'
>>> order_mock.get_value.return_value = DEFAULT
>>> order_mock.get_value()
'third'
@end example

If @ref{462b,,side_effect} is exhausted, the order of precedence will not
cause a value to be obtained from the successors. Instead, @code{StopIteration}
exception is raised.

@example
>>> order_mock = Mock(spec=Order, wraps=Order)
>>> order_mock.get_value.side_effect = ["first side effect value",
...                                     "another side effect value"]
>>> order_mock.get_value.return_value = "second"
@end example

@example
>>> order_mock.get_value()
'first side effect value'
>>> order_mock.get_value()
'another side effect value'
@end example

@example
>>> order_mock.get_value()
Traceback (most recent call last):
 ...
StopIteration
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node unittest mock --- 入門,test --- Regression tests package for Python,unittest mock --- モックオブジェクトライブラリ,開発ツール
@anchor{library/unittest mock-examples doc}@anchor{4675}@anchor{library/unittest mock-examples translation-repo}@anchor{4676}@anchor{library/unittest mock-examples unittest-mock-getting-started}@anchor{4677}
@subsection @code{unittest.mock} --- 入門



Added in version 3.3.

@anchor{library/unittest mock-examples getting-started}@anchor{4678}
@c import asyncio
@c import unittest
@c from unittest.mock import Mock, MagicMock, AsyncMock, patch, call, sentinel
@c 
@c class SomeClass:
@c     attribute = 'this is a doctest'
@c 
@c     @staticmethod
@c     def static_method():
@c         pass

@menu
* Mock を使う:: 
* patch デコレータ:: 
* さらなる例:: 

@end menu

@node Mock を使う,patch デコレータ,,unittest mock --- 入門
@anchor{library/unittest mock-examples using-mock}@anchor{4679}
@subsubsection Mock を使う


@menu
* Mock のパッチ用メソッド:: 
* オブジェクトのメソッド呼び出しに対するモック:: 
* クラスをモックする:: 
* モックに名前をつける:: 
* 全ての呼び出しのトラッキング:: 
* 戻り値や属性を設定する:: 
* モックから例外を発生させる:: 
* side_effect の関数と iterable:: 
* 非同期イテレータをモックする:: 
* 非同期コンテキストマネージャをモックする:: 
* 既存のオブジェクトから Mock を作る:: 
* Using side_effect to return per file content:: 

@end menu

@node Mock のパッチ用メソッド,オブジェクトのメソッド呼び出しに対するモック,,Mock を使う
@anchor{library/unittest mock-examples mock-patching-methods}@anchor{467a}
@subsubsection Mock のパッチ用メソッド


一般的な @ref{c3f,,Mock} の使い方の中には次のものがあります:


@itemize *

@item 
メソッドにパッチを当てる

@item 
オブジェクトに対するメソッド呼び出しを記録する
@end itemize

システムの他の部分からメソッドが正しい引数で呼び出されたかどうかを確認するために、そのオブジェクトのメソッドを置き換えることができます:

@example
>>> real = SomeClass()
>>> real.method = MagicMock(name='method')
>>> real.method(3, 4, 5, key='value')
<MagicMock name='method()' id='...'>
@end example

モック(上の例では @code{real.method})が利用された場合、どう使われたかを assert できるようにする属性やメソッドがモックにあります。

@cartouche
@quotation 注釈 
この例のような場合、たいてい @ref{c3f,,Mock} と @ref{108f,,MagicMock} は互換です。 @code{MagicMock} の方が強力なので、デフォルトではこちらを使うといいでしょう。
@end quotation
@end cartouche

モックが呼び出されると、その @ref{463d,,called} 属性が @code{True} に設定されます。そして @ref{1e03,,assert_called_with()} や @ref{4635,,assert_called_once_with()} メソッドを使ってそのメソッドが正しい引数で呼び出されたかどうかをチェックできます。

次の例では @code{ProductionClass().method} が @code{something} メソッドを呼び出したことをテストしています:

@example
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
@end example

@node オブジェクトのメソッド呼び出しに対するモック,クラスをモックする,Mock のパッチ用メソッド,Mock を使う
@anchor{library/unittest mock-examples mock-for-method-calls-on-an-object}@anchor{467b}
@subsubsection オブジェクトのメソッド呼び出しに対するモック


上の例ではオブジェクトのメソッドに対して直接パッチを当てて、それが正しく呼び出されていたかどうかをテストしていました。もう一つのよくあるユースケースが、モックをメソッド (またはテスト対象のシステムのどこか) に渡して、それが正しく利用されたかどうかをチェックする方法です。

次の例で、@code{ProductionClass} は @code{closer} メソッドを持っています。このメソッドは渡されたオブジェクトの @code{close} メソッドを呼び出します。

@example
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
@end example

ですからこれをテストするには、@code{close} メソッドを持ったオブジェクトを渡して、それが正しく呼び出されたかどうかをテストしなければなりません。

@example
>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
@end example

モックに @cite{close} メソッドを持たせるために何か準備する必要はありません。 @cite{close} メソッドにアクセスすると自動的にそれが作られます。なので、もし @cite{close} が呼び出されなかったとしてもテスト時に生成されるのですが、 @ref{1e03,,assert_called_with()} が failure 例外を発生させます。

@node クラスをモックする,モックに名前をつける,オブジェクトのメソッド呼び出しに対するモック,Mock を使う
@anchor{library/unittest mock-examples mocking-classes}@anchor{467c}
@subsubsection クラスをモックする


他のよくあるユースケースが、テスト対象のコードによってインスタンス化されているクラスをモックに置き換えることです。クラスに patch すると、そのクラスがモックに置き換えられます。インスタンスは `クラスを呼び出した時に' 作られます。なので、モックの戻り値を使うことで、「モックのインスタンス」にアクセスできます。

次の例では、 @code{some_function} という関数が @code{Foo} をインスタンス化し、その method を呼び出しています。 @ref{1092,,patch()} を呼び出すと @code{Foo} クラスをモックに置き換えます。 @code{Foo} のインスタンスはモックを呼び出して作られるので、モックの @ref{4633,,return_value} を変更することでカスタマイズできます。:

@example
>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
@end example

@node モックに名前をつける,全ての呼び出しのトラッキング,クラスをモックする,Mock を使う
@anchor{library/unittest mock-examples naming-your-mocks}@anchor{467d}
@subsubsection モックに名前をつける


モックに名前をつけると便利なことがあります。その名前はモックを repr したときに表示されるので、モックがテスト失敗のメッセージ内に現れた時に便利です。また、モックの名前はそのモックの属性やメソッドにも伝播します:

@example
>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
>>> mock.method
<MagicMock name='foo.method' id='...'>
@end example

@node 全ての呼び出しのトラッキング,戻り値や属性を設定する,モックに名前をつける,Mock を使う
@anchor{library/unittest mock-examples tracking-all-calls}@anchor{467e}
@subsubsection 全ての呼び出しのトラッキング


メソッドの複数回の呼び出しをトラックしたいことがあります。 @ref{4637,,mock_calls} 属性は、そのモックの子属性やさらにその子孫に対する呼び出しすべてを記録しています。

@example
>>> mock = MagicMock()
>>> mock.method()
<MagicMock name='mock.method()' id='...'>
>>> mock.attribute.method(10, x=53)
<MagicMock name='mock.attribute.method()' id='...'>
>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
@end example

@code{mock_calls} に対して assert すると、予期していないメソッド呼び出しがあったときにその assert が失敗します。これはあるメソッド呼び出しが期待通りに実行されたかどうかだけでなく、その呼び出し順序や期待した以外の呼び出しが起こらなかったことまでテストできるので便利です:

@code{mock_calls} と比較するリストを作るために @ref{1db3,,call} オブジェクトを利用できます:

@example
>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
@end example

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:

@example
>>> m = Mock()
>>> m.factory(important=True).deliver()
<Mock name='mock.factory().deliver()' id='...'>
>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
@end example

@node 戻り値や属性を設定する,モックから例外を発生させる,全ての呼び出しのトラッキング,Mock を使う
@anchor{library/unittest mock-examples setting-return-values-and-attributes}@anchor{467f}
@subsubsection 戻り値や属性を設定する


モックオブジェクトに戻り値を設定するのはとっても簡単です:

@example
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
@end example

もちろん同じことがモックのメソッドに対しても行えます:

@example
>>> mock = Mock()
>>> mock.method.return_value = 3
>>> mock.method()
3
@end example

コンストラクターで戻り値を設定することもできます:

@example
>>> mock = Mock(return_value=3)
>>> mock()
3
@end example

モックに属性を設定したかったら、普通に設定するだけです:

@example
>>> mock = Mock()
>>> mock.x = 3
>>> mock.x
3
@end example

@code{mock.connection.cursor().execute("SELECT 1")} のような複雑なケースでモックを使いたい場合もあります。この呼出があるリストを返すようにしたい場合、このネストした呼び出しを構成しなければなりません。

@ref{1db3,,call} を使って "chained call" 内の呼び出しを構成して、 assert で使うことができます:

@example
>>> mock = Mock()
>>> cursor = mock.connection.cursor.return_value
>>> cursor.execute.return_value = ['foo']
>>> mock.connection.cursor().execute("SELECT 1")
['foo']
>>> expected = call.connection.cursor().execute("SELECT 1").call_list()
>>> mock.mock_calls
[call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
>>> mock.mock_calls == expected
True
@end example

call object を chained call を表す list にするために @code{.call_list()} を使います。

@node モックから例外を発生させる,side_effect の関数と iterable,戻り値や属性を設定する,Mock を使う
@anchor{library/unittest mock-examples raising-exceptions-with-mocks}@anchor{4680}
@subsubsection モックから例外を発生させる


@ref{462b,,side_effect} という便利な属性があります。この属性に例外クラスやそのインスタンスを設定すると、モックが呼ばれた時にその例外を発生させます。

@example
>>> mock = Mock(side_effect=Exception('Boom!'))
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!
@end example

@node side_effect の関数と iterable,非同期イテレータをモックする,モックから例外を発生させる,Mock を使う
@anchor{library/unittest mock-examples side-effect-functions-and-iterables}@anchor{4681}
@subsubsection side_effect の関数と iterable


@code{side_effect} には関数や iterable を設定することもできます。@code{side_effect} に iterable を設定するユースケースは、そのモックが複数回呼び出され、そのたびに違う値を返したい場合です。@code{side_effect} に iterable を設定すると、そのモックに対するすべての呼び出しは iterable の次の値を返します:

@example
>>> mock = MagicMock(side_effect=[4, 5, 6])
>>> mock()
4
>>> mock()
5
>>> mock()
6
@end example

より高度なユースケースとして、mock が呼び出された時の引数によって戻り値を変化させたい場合は、@code{side_effect} に関数を設定することができます。その関数は mock と同じ引数で呼び出されます。その関数の戻り値がそのモック呼び出しの戻り値になります:

@example
>>> vals = @{(1, 2): 1, (2, 3): 2@}
>>> def side_effect(*args):
...     return vals[args]
...
>>> mock = MagicMock(side_effect=side_effect)
>>> mock(1, 2)
1
>>> mock(2, 3)
2
@end example

@node 非同期イテレータをモックする,非同期コンテキストマネージャをモックする,side_effect の関数と iterable,Mock を使う
@anchor{library/unittest mock-examples mocking-asynchronous-iterators}@anchor{4682}
@subsubsection 非同期イテレータをモックする


Python 3.8以降、@code{AsyncMock} と @code{MagicMock} は @code{__aiter__} を通じて @ref{f77,,非同期イテレータ (Asynchronous Iterator)} のモックをサポートしています。@code{__aiter__} の @ref{4633,,return_value} 属性はイテレーションに使用される戻り値を設定するために使用できます。

@example
>>> mock = MagicMock()  # AsyncMock also works here
>>> mock.__aiter__.return_value = [1, 2, 3]
>>> async def main():
...     return [i async for i in mock]
...
>>> asyncio.run(main())
[1, 2, 3]
@end example

@node 非同期コンテキストマネージャをモックする,既存のオブジェクトから Mock を作る,非同期イテレータをモックする,Mock を使う
@anchor{library/unittest mock-examples mocking-asynchronous-context-manager}@anchor{4683}
@subsubsection 非同期コンテキストマネージャをモックする


Python 3.8以降、@code{AsyncMock} と @code{MagicMock} は @code{__aenter__} と @code{__aexit__} を通じて @ref{812,,非同期コンテキストマネージャ (Asynchronous Context Manager)} のモックをサポートしています。デフォルトでは、 @code{__aenter__} と @code{__aexit__} は非同期関数を返す @code{AsyncMock} インスタンスです。

@example
>>> class AsyncContextManager:
...     async def __aenter__(self):
...         return self
...     async def __aexit__(self, exc_type, exc, tb):
...         pass
...
>>> mock_instance = MagicMock(AsyncContextManager())  # AsyncMock also works here
>>> async def main():
...     async with mock_instance as result:
...         pass
...
>>> asyncio.run(main())
>>> mock_instance.__aenter__.assert_awaited_once()
>>> mock_instance.__aexit__.assert_awaited_once()
@end example

@node 既存のオブジェクトから Mock を作る,Using side_effect to return per file content,非同期コンテキストマネージャをモックする,Mock を使う
@anchor{library/unittest mock-examples creating-a-mock-from-an-existing-object}@anchor{4684}
@subsubsection 既存のオブジェクトから Mock を作る


mock を使いすぎることの問題の一つは、テストが実際のコードではなく mock の実装をテストするようになってしまうことです。@code{some_method} というメソッドを実装したクラスがあるとします。他のクラスをテストするときに、@code{some_method} を提供する mock を使います。最初のクラスをリファクタリングして @code{some_method} がなくなった時、コードは壊れているのにテストは通る状態になってしまいます

@ref{c3f,,Mock} は `spec' というキーワード引数で mock の定義となるオブジェクトを指定できます。定義オブジェクトに存在しないメソッドや属性にアクセスすると AttributeError を発生させます。定義となるクラスの実装を変更した場合、テストの中でそのクラスをインスタンス化させなくても、テストを失敗させる事ができます。

@example
>>> mock = Mock(spec=SomeClass)
>>> mock.old_method()
Traceback (most recent call last):
   ...
AttributeError: Mock object has no attribute 'old_method'. Did you mean: 'class_method'?
@end example

また、定義を指定することで、パラメータが位置引数と名前付き引数のどちらで渡されたかに関わらず、モックへの呼び出しをよりスマートに照合することができます。

@example
>>> def f(a, b, c): pass
...
>>> mock = Mock(spec=f)
>>> mock(1, 2, 3)
<Mock name='mock()' id='140161580456576'>
>>> mock.assert_called_with(a=1, b=2, c=3)
@end example

このよりスマートなマッチングをモックのメソッド呼び出しにも適用したい場合は、@ref{462e,,auto-speccing} を使用します。

任意の属性の参照だけでなく代入も禁止するより強い定義を利用したい場合は、`spec' の代わりに `spec_set' を使います。

@node Using side_effect to return per file content,,既存のオブジェクトから Mock を作る,Mock を使う
@anchor{library/unittest mock-examples using-side-effect-to-return-per-file-content}@anchor{4685}
@subsubsection Using side_effect to return per file content


@ref{11e9,,mock_open()} is used to patch @ref{316,,open()} method. @ref{462b,,side_effect}
can be used to return a new Mock object per call. This can be used to return different
contents per file stored in a dictionary:

@example
DEFAULT = "default"
data_dict = @{"file1": "data1",
             "file2": "data2"@}

def open_side_effect(name):
    return mock_open(read_data=data_dict.get(name, DEFAULT))()

with patch("builtins.open", side_effect=open_side_effect):
    with open("file1") as file1:
        assert file1.read() == "data1"

    with open("file2") as file2:
        assert file2.read() == "data2"

    with open("file3") as file2:
        assert file2.read() == "default"
@end example

@node patch デコレータ,さらなる例,Mock を使う,unittest mock --- 入門
@anchor{library/unittest mock-examples patch-decorators}@anchor{4686}
@subsubsection patch デコレータ


@cartouche
@quotation 注釈 
@ref{1092,,patch()} では探索される名前空間内のオブジェクトにパッチをあてることが重要です。通常は単純ですが、クイックガイドには @ref{462c,,どこにパッチするか} を読んでください。
@end quotation
@end cartouche

テストの中でクラス属性やモジュール属性、例えば組み込み関数や、テスト対象モジュールにあるインスタンス化されるクラスに対してパッチしたいことがあります。モジュールやクラスは実際はグローバルなので、パッチするときは必ずテスト後にパッチを解除しないと、そのパッチが永続化されて他のテストに影響を与え、解析しにくい問題になります。

mock はこのために3つの便利なデコレータを提供しています: @ref{1092,,patch()}, @ref{1906,,patch.object()}, @ref{1967,,patch.dict()} です。@code{patch} はパッチ対象を指定する @code{package.module.Class.attribute} の形式の文字列を引数に取ります。オプションでその属性 (やクラスなど) を置き換えるオブジェクトを渡すことができます。 'patch.object' はオブジェクトとパッチしたい属性名、それにオプションで置き換えるオブジェクトを受け取ります。

@code{patch.object}:

@example
>>> original = SomeClass.attribute
>>> @@patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test():
...     assert SomeClass.attribute == sentinel.attribute
...
>>> test()
>>> assert SomeClass.attribute == original

>>> @@patch('package.module.attribute', sentinel.attribute)
... def test():
...     from package.module import attribute
...     assert attribute is sentinel.attribute
...
>>> test()
@end example

モジュール (@ref{13,,builtins} を含む) をパッチしようとする場合、 @ref{1906,,patch.object()} の代わりに @ref{1092,,patch()} を使用してください:

@example
>>> mock = MagicMock(return_value=sentinel.file_handle)
>>> with patch('builtins.open', mock):
...     handle = open('filename', 'r')
...
>>> mock.assert_called_with('filename', 'r')
>>> assert handle == sentinel.file_handle, "incorrect file handle returned"
@end example

モジュール名は必要に応じて @code{package.module} のようにドットを含むことができます:

@example
>>> @@patch('package.module.ClassName.attribute', sentinel.attribute)
... def test():
...     from package.module import ClassName
...     assert ClassName.attribute == sentinel.attribute
...
>>> test()
@end example

テストメソッド自体をデコレートするのは良いパターンです:

@example
>>> class MyTest(unittest.TestCase):
...     @@patch.object(SomeClass, 'attribute', sentinel.attribute)
...     def test_something(self):
...         self.assertEqual(SomeClass.attribute, sentinel.attribute)
...
>>> original = SomeClass.attribute
>>> MyTest('test_something').test_something()
>>> assert SomeClass.attribute == original
@end example

Mock を使ってパッチしたい場合は、 @ref{1092,,patch()} を1引数で (または @ref{1906,,patch.object()} を2引数で) 使うことができます。mock が自動で生成され、テスト関数/メソッドに渡されます:

@example
>>> class MyTest(unittest.TestCase):
...     @@patch.object(SomeClass, 'static_method')
...     def test_something(self, mock_method):
...         SomeClass.static_method()
...         mock_method.assert_called_with()
...
>>> MyTest('test_something').test_something()
@end example

次のパターンのように patch デコレータを重ねることができます:

@example
>>> class MyTest(unittest.TestCase):
...     @@patch('package.module.ClassName1')
...     @@patch('package.module.ClassName2')
...     def test_something(self, MockClass2, MockClass1):
...         self.assertIs(package.module.ClassName1, MockClass1)
...         self.assertIs(package.module.ClassName2, MockClass2)
...
>>> MyTest('test_something').test_something()
@end example

patch デコレータをネストした際、モックは (デコレータを適用する `Python' の通常の) 順に適用されます。つまり引数は下から上の順になり、よって上記の例では @code{test_module.ClassName2} が先になります。

また、 @ref{1967,,patch.dict()} を使うと、スコープ内だけで辞書に値を設定し、テスト終了時には元の状態に復元されます:

@example
>>> foo = @{'key': 'value'@}
>>> original = foo.copy()
>>> with patch.dict(foo, @{'newkey': 'newvalue'@}, clear=True):
...     assert foo == @{'newkey': 'newvalue'@}
...
>>> assert foo == original
@end example

@code{patch}, @code{patch.object}, @code{patch.dict} は全てコンテキストマネージャーとしても利用できます。

@ref{1092,,patch()} に mock を生成させる場合、その参照を with 文の as を使って受け取れます:

@example
>>> class ProductionClass:
...     def method(self):
...         pass
...
>>> with patch.object(ProductionClass, 'method') as mock_method:
...     mock_method.return_value = None
...     real = ProductionClass()
...     real.method(1, 2, 3)
...
>>> mock_method.assert_called_with(1, 2, 3)
@end example

他の方法として、@code{patch}, @code{patch.object}, @code{patch.dict} はクラスデコレータとしても利用できます。その場合、"test" で始まる全てのメソッドにデコレータを適用するのと同じになります。

@node さらなる例,,patch デコレータ,unittest mock --- 入門
@anchor{library/unittest mock-examples further-examples}@anchor{4687}@anchor{library/unittest mock-examples id1}@anchor{4688}
@subsubsection さらなる例


より高度なシナリオを想定した例をあげていきます。

@menu
* chained call をモックする:: 
* 部分的なモック:: 
* ジェネレータメソッドをモックする:: 
* 同じパッチを全てのメソッドに適用する:: 
* Unboundメソッドをモックする:: 
* モックで複数回の呼び出しをチェックする:: 
* ミュータブルな引数に対処する:: 
* patch をネストする:: 
* MagicMock で辞書をモックする:: 
* Mock のサブクラスと属性:: 
* patch.dict で import をモックする: patch dict で import をモックする. 
* Tracking order of calls and less verbose call assertions:: 
* More complex argument matching:: 

@end menu

@node chained call をモックする,部分的なモック,,さらなる例
@anchor{library/unittest mock-examples mocking-chained-calls}@anchor{4689}
@subsubsection chained call をモックする


chained call を mock するのは、一度 @ref{4633,,return_value} 属性を理解してしまえば簡単です。mock が最初に呼ばれた時や、呼び出される前に @code{return_value} を参照した場合、新しい @ref{c3f,,Mock} が生成されます。

つまり、戻り値のオブジェクトがどう利用されたかは、@code{return_value} mock を調べれば分かります:

@example
>>> mock = Mock()
>>> mock().foo(a=2, b=3)
<Mock name='mock().foo()' id='...'>
>>> mock.return_value.foo.assert_called_with(a=2, b=3)
@end example

これをもとに、mock を構成して chained call に対する assert を行うのは簡単です。もちろん、元のコードを最初からもっとテストしやすく書くという選択肢もありますが...

では、例として次のようなコードがあるとします:

@example
>>> class Something:
...     def __init__(self):
...         self.backend = BackendProvider()
...     def method(self):
...         response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
...         # more code
@end example

@code{BackendProvider} はすでに十分テストされているとします。@code{method()} をどうテストしましょうか？特に、response オブジェクトを使う @code{# more code} の部分のコードをテストしたいとします。

この chained call はインスタンス属性を起点にしているので、 @code{Something} インスタンスの @code{backend} 属性に対してモンキーパッチすることができます。今回の場合だと、最後の @code{start_call} の呼び出しが返す値にだけ興味があるので、あまり多くの構成は必要ありません。このメソッドが返すのが 'file-like' オブジェクトだとしましょう。そうすると、 response オブジェクトは組み込みの @ref{316,,open()} を @code{spec} として利用できます。

これをするために、backend のモックとしてモックインスタンスを作成し、それに対するモックの response オブジェクトを作成します。最終的な @code{start_call} の返り値として response をセットすると、このようにすることができます:

@example
mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
@end example

これより少し良いやり方として、返り値を直接セットする @ref{4634,,configure_mock()} メソッドを使用して次のようにすることができます:

@example
>>> something = Something()
>>> mock_response = Mock(spec=open)
>>> mock_backend = Mock()
>>> config = @{'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response@}
>>> mock_backend.configure_mock(**config)
@end example

これらによって「モックの backend」をその場で monkey patch して、実際の呼び出しを行うことができます:

@example
>>> something.backend = mock_backend
>>> something.method()
@end example

@ref{4637,,mock_calls} を使用すると、チェーンされた呼び出しを単一のアサーションでチェックすることができます。チェーンされた呼び出しは、1行のコードの中で行われる複数の呼び出しです。したがって、 @code{mock_calls} には複数のエントリーがあるでしょう。 @ref{466d,,call.call_list()} を使用することで、この呼び出しのリストを作成することができます:

@example
>>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
>>> call_list = chained.call_list()
>>> assert mock_backend.mock_calls == call_list
@end example

@node 部分的なモック,ジェネレータメソッドをモックする,chained call をモックする,さらなる例
@anchor{library/unittest mock-examples partial-mocking}@anchor{468a}
@subsubsection 部分的なモック


For some tests, you may want to mock out a call to @ref{16e3,,datetime.date.today()}
to return a known date, but don't want to prevent the code under test from
creating new date objects. Unfortunately @ref{1fa,,datetime.date} is written in C,
so you cannot just monkey-patch out the static @ref{16e3,,datetime.date.today()} method.

Instead, you can effectively wrap the date
class with a mock, while passing through calls to the constructor to the real
class (and returning real instances).

ここで、テスト対象のモジュール中の @code{date} クラスをモックするために @ref{1092,,patch decorator} が使用されています。そして、モックの date クラスの @ref{462b,,side_effect} 属性は、本物の date を返すラムダ関数にセットされます。モックの date クラスが呼ばれる時、 @code{side_effect} によって本物の date が構築されて返されます。:

@example
>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
...     mock_date.today.return_value = date(2010, 10, 8)
...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
...
...     assert mymodule.date.today() == date(2010, 10, 8)
...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
@end example

グローバルに @ref{1fa,,datetime.date} にパッチするのではなく、それを使用するモジュールの中の @code{date} にパッチしていることに留意してください。@ref{462c,,どこにパッチするか} を参照してください。

When @code{date.today()} is called a known date is returned, but calls to the
@code{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.

dateコンストラクタの呼び出しは、@code{mock_date} の属性(@code{call_count} とその仲間)に記録され、テストに役立つこともあります。

日付や他の組み込みクラスのモックに対処する別の方法は このブログエントリ@footnote{https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/}.で議論されています。

@node ジェネレータメソッドをモックする,同じパッチを全てのメソッドに適用する,部分的なモック,さらなる例
@anchor{library/unittest mock-examples mocking-a-generator-method}@anchor{468b}
@subsubsection ジェネレータメソッドをモックする


Pythonのジェネレータは、反復処理された時に一連の値を返す @ref{bc2,,yield} 文を使用した関数やメソッドです @footnote{
ジェネレータ式やジェネレータのより`高度な使い方 <@indicateurl{http://www.dabeaz.com/coroutines/index.html}>`_ もありますが、ここではそれらについては触れません。ジェネレータとその強力さについての非常に良い紹介記事があります: @uref{http://www.dabeaz.com/generators/,Generator Tricks for Systems Programmers}。
}。

ジェネレータメソッド/関数はジェネレータオブジェクトを返すために呼び出されます。そしてこのジェネレータオブジェクトが反復処理されます。イテレーションのためのプロトコルメソッドは @ref{20aa,,__iter__()} なので、@ref{108f,,MagicMock} を使ってこれをモックすることができます。

ここでは"iter"メソッドをジェネレータとして実装したクラスの例を紹介します:

@example
>>> class Foo:
...     def iter(self):
...         for i in [1, 2, 3]:
...             yield i
...
>>> foo = Foo()
>>> list(foo.iter())
[1, 2, 3]
@end example

このクラス、特に "iter"メソッドをどのようにモックするのでしょうか。

(@ref{24d,,list} の呼び出しの中での暗黙的な)イテレーションから返される値を設定するには、@code{foo.iter()} の呼び出しで返されるオブジェクトを設定する必要がある。

@example
>>> mock_foo = MagicMock()
>>> mock_foo.iter.return_value = iter([1, 2, 3])
>>> list(mock_foo.iter())
[1, 2, 3]
@end example

@node 同じパッチを全てのメソッドに適用する,Unboundメソッドをモックする,ジェネレータメソッドをモックする,さらなる例
@anchor{library/unittest mock-examples applying-the-same-patch-to-every-test-method}@anchor{468c}
@subsubsection 同じパッチを全てのメソッドに適用する


複数のテストメソッドに複数のパッチを適用したい場合、当然のことながらすべてのメソッドにパッチデコレータを適用することになります。これは不要な繰り返しのように感じられます。代わりに、(あらゆる形態の) @ref{1092,,patch()} をクラスデコレータとして使用することができます。これはそのクラスのすべてのテストメソッドにパッチを適用します。テストメソッドは名前が @code{test} で始まるメソッドで識別されます。

@example
>>> @@patch('mymodule.SomeClass')
... class MyTest(unittest.TestCase):
...
...     def test_one(self, MockSomeClass):
...         self.assertIs(mymodule.SomeClass, MockSomeClass)
...
...     def test_two(self, MockSomeClass):
...         self.assertIs(mymodule.SomeClass, MockSomeClass)
...
...     def not_a_test(self):
...         return 'something'
...
>>> MyTest('test_one').test_one()
>>> MyTest('test_two').test_two()
>>> MyTest('test_two').not_a_test()
'something'
@end example

パッチを管理する別の方法として、@ref{465e,,patch のメソッド; start と stop}.を使用する方法があります。これらを使うと、パッチを @code{setUp} と`@w{`}tearDown`@w{`}メソッドに移すことができます。

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         self.patcher = patch('mymodule.foo')
...         self.mock_foo = self.patcher.start()
...
...     def test_foo(self):
...         self.assertIs(mymodule.foo, self.mock_foo)
...
...     def tearDown(self):
...         self.patcher.stop()
...
>>> MyTest('test_foo').run()
@end example

この方式を使う場合、必ず @code{stop} メソッドを呼び出してパッチが解除する必要があります。setUp の中で例外が発生した場合 tearDown が呼び出されないので、これは意外に面倒です。 @ref{c74,,unittest.TestCase.addCleanup()} を使うと簡単にできます:

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         patcher = patch('mymodule.foo')
...         self.addCleanup(patcher.stop)
...         self.mock_foo = patcher.start()
...
...     def test_foo(self):
...         self.assertIs(mymodule.foo, self.mock_foo)
...
>>> MyTest('test_foo').run()
@end example

@node Unboundメソッドをモックする,モックで複数回の呼び出しをチェックする,同じパッチを全てのメソッドに適用する,さらなる例
@anchor{library/unittest mock-examples mocking-unbound-methods}@anchor{468d}
@subsubsection Unboundメソッドをモックする


Sometimes a test needs to patch an `unbound method', which means patching the
method on the class rather than on the instance. In order to make assertions
about which objects were calling this particular method, you need to pass
@code{self} as the first argument. 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 @code{self}
passed in. The workaround is to patch the unbound method with a real function
instead. The @ref{1092,,patch()} 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 @code{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 @code{self} passed in as the first argument, which is exactly what
was needed:

@example
>>> class Foo:
...   def foo(self):
...     pass
...
>>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
...   mock_foo.return_value = 'foo'
...   foo = Foo()
...   foo.foo()
...
'foo'
>>> mock_foo.assert_called_once_with(foo)
@end example

@code{autospec=True} を使用しない場合、束縛されていないメソッドは代わりにMockインスタンスでパッチされ、@code{self} で呼び出されることはありません。

@node モックで複数回の呼び出しをチェックする,ミュータブルな引数に対処する,Unboundメソッドをモックする,さらなる例
@anchor{library/unittest mock-examples checking-multiple-calls-with-mock}@anchor{468e}
@subsubsection モックで複数回の呼び出しをチェックする


モックには、モックオブジェクトがどのように使用されるかをアサートするための素晴らしいAPIがあります。

@example
>>> mock = Mock()
>>> mock.foo_bar.return_value = None
>>> mock.foo_bar('baz', spam='eggs')
>>> mock.foo_bar.assert_called_with('baz', spam='eggs')
@end example

If your mock is only being called once you can use the
@ref{4635,,assert_called_once_with()} method that also asserts that the
@ref{1783,,call_count} is one.

@example
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
>>> mock.foo_bar()
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
Traceback (most recent call last):
    ...
AssertionError: Expected 'foo_bar' to be called once. Called 2 times.
Calls: [call('baz', spam='eggs'), call()].
@end example

Both @code{assert_called_with} and @code{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
@ref{463e,,call_args_list}:

@example
>>> mock = Mock(return_value=None)
>>> mock(1, 2, 3)
>>> mock(4, 5, 6)
>>> mock()
>>> mock.call_args_list
[call(1, 2, 3), call(4, 5, 6), call()]
@end example

@ref{1db3,,call} ヘルパーを使えば、これらの呼び出しについて簡単にアサートすることができます。予想される呼び出しのリストを作成し、それを`@w{`}call_args_list`@w{`}と比較することができます。これは`@w{`}call_args_list`@w{`}のreprと驚くほど似ています:

@example
>>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
>>> mock.call_args_list == expected
True
@end example

@node ミュータブルな引数に対処する,patch をネストする,モックで複数回の呼び出しをチェックする,さらなる例
@anchor{library/unittest mock-examples coping-with-mutable-arguments}@anchor{468f}
@subsubsection ミュータブルな引数に対処する


稀ではありますが、問題となることがあるのはミュータブルな引数でモックが呼び出された場合です。@code{call_args} や`@w{`}call_args_list`@w{`} は引数への*参照*を保存します。もしテスト対象のコードによって引数が変更されてしまうと、モックが呼び出された時の値をアサートすることはできなくなります。

この問題を示すサンプルコードを示します。

@example
def frob(val):
    pass

def grob(val):
    "First frob and then clear val"
    frob(val)
    val.clear()
@end example

@code{grob} が`@w{`}frob`@w{`}を正しい引数で呼び出していることをテストしようとすると何が起こるか見てみましょう:

@example
>>> with patch('mymodule.frob') as mock_frob:
...     val = @{6@}
...     mymodule.grob(val)
...
>>> val
set()
>>> mock_frob.assert_called_with(@{6@})
Traceback (most recent call last):
    ...
AssertionError: Expected: ((@{6@},), @{@})
Called with: ((set(),), @{@})
@end example

一つの選択肢は、あなたが渡す引数をモックがコピーすることです。この方法は、オブジェクトidの同一性に依存したアサーションを行う場合に問題を引き起こす可能性があります。

Here's one solution that uses the @ref{462b,,side_effect}
functionality. If you provide a @code{side_effect} function for a mock then
@code{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.

@example
>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
>>> def copy_call_args(mock):
...     new_mock = Mock()
...     def side_effect(*args, **kwargs):
...         args = deepcopy(args)
...         kwargs = deepcopy(kwargs)
...         new_mock(*args, **kwargs)
...         return DEFAULT
...     mock.side_effect = side_effect
...     return new_mock
...
>>> with patch('mymodule.frob') as mock_frob:
...     new_mock = copy_call_args(mock_frob)
...     val = @{6@}
...     mymodule.grob(val)
...
>>> new_mock.assert_called_with(@{6@})
>>> new_mock.call_args
call(@{6@})
@end example

@code{copy_call_args} は、テストで呼び出されるモックとともに呼び出されます。この関数はアサーションで使用するための新しいモックを返します。@code{side_effect} 関数は引数のコピーを作成し、そのコピーを使って @code{new_mock} を呼び出します。

@cartouche
@quotation 注釈 
もしモックが一度しか使われないのであれば、呼び出された時点で引数をチェックする簡単な方法があります。単純に`@w{`}side_effect`@w{`}関数の中でチェックを行えばいいのです。

@example
>>> def side_effect(arg):
...     assert arg == @{6@}
...
>>> mock = Mock(side_effect=side_effect)
>>> mock(@{6@})
>>> mock(set())
Traceback (most recent call last):
    ...
AssertionError
@end example
@end quotation
@end cartouche

別の方法としては、（ @ref{d65,,copy.deepcopy()} を使用して）引数をコピーする、 @ref{c3f,,Mock} や @ref{108f,,MagicMock} のサブクラスを作成する方法があります。以下に実装例を示します。

@example
>>> from copy import deepcopy
>>> class CopyingMock(MagicMock):
...     def __call__(self, /, *args, **kwargs):
...         args = deepcopy(args)
...         kwargs = deepcopy(kwargs)
...         return super().__call__(*args, **kwargs)
...
>>> c = CopyingMock(return_value=None)
>>> arg = set()
>>> c(arg)
>>> arg.add(1)
>>> c.assert_called_with(set())
>>> c.assert_called_with(arg)
Traceback (most recent call last):
    ...
AssertionError: expected call not found.
Expected: mock(@{1@})
Actual: mock(set())
>>> c.foo
<CopyingMock name='mock.foo' id='...'>
@end example

When you subclass @code{Mock} or @code{MagicMock} all dynamically created attributes,
and the @code{return_value} will use your subclass automatically. That means all
children of a @code{CopyingMock} will also have the type @code{CopyingMock}.

@node patch をネストする,MagicMock で辞書をモックする,ミュータブルな引数に対処する,さらなる例
@anchor{library/unittest mock-examples nesting-patches}@anchor{4690}
@subsubsection patch をネストする


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:

@example
>>> class MyTest(unittest.TestCase):
...
...     def test_foo(self):
...         with patch('mymodule.Foo') as mock_foo:
...             with patch('mymodule.Bar') as mock_bar:
...                 with patch('mymodule.Spam') as mock_spam:
...                     assert mymodule.Foo is mock_foo
...                     assert mymodule.Bar is mock_bar
...                     assert mymodule.Spam is mock_spam
...
>>> original = mymodule.Foo
>>> MyTest('test_foo').test_foo()
>>> assert mymodule.Foo is original
@end example

With unittest @code{cleanup} functions and the @ref{465e,,patch のメソッド; start と stop} we can
achieve the same effect without the nested indentation. A simple helper
method, @code{create_patch}, puts the patch in place and returns the created mock
for us:

@example
>>> class MyTest(unittest.TestCase):
...
...     def create_patch(self, name):
...         patcher = patch(name)
...         thing = patcher.start()
...         self.addCleanup(patcher.stop)
...         return thing
...
...     def test_foo(self):
...         mock_foo = self.create_patch('mymodule.Foo')
...         mock_bar = self.create_patch('mymodule.Bar')
...         mock_spam = self.create_patch('mymodule.Spam')
...
...         assert mymodule.Foo is mock_foo
...         assert mymodule.Bar is mock_bar
...         assert mymodule.Spam is mock_spam
...
>>> original = mymodule.Foo
>>> MyTest('test_foo').run()
>>> assert mymodule.Foo is original
@end example

@node MagicMock で辞書をモックする,Mock のサブクラスと属性,patch をネストする,さらなる例
@anchor{library/unittest mock-examples mocking-a-dictionary-with-magicmock}@anchor{4691}
@subsubsection 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 @ref{108f,,MagicMock}, which will behave like a dictionary,
and using @ref{462b,,side_effect} to delegate dictionary access to a real
underlying dictionary that is under our control.

When the @ref{588,,__getitem__()} and @ref{14e3,,__setitem__()} methods
of our @code{MagicMock} are called
(normal dictionary access) then @code{side_effect} is called with the key (and in
the case of @code{__setitem__} the value too). We can also control what is returned.

After the @code{MagicMock} has been used we can use attributes like
@ref{463e,,call_args_list} to assert about how the dictionary was used:

@example
>>> my_dict = @{'a': 1, 'b': 2, 'c': 3@}
>>> def getitem(name):
...      return my_dict[name]
...
>>> def setitem(name, val):
...     my_dict[name] = val
...
>>> mock = MagicMock()
>>> mock.__getitem__.side_effect = getitem
>>> mock.__setitem__.side_effect = setitem
@end example

@cartouche
@quotation 注釈 
An alternative to using @code{MagicMock} is to use @code{Mock} and `only' provide
the magic methods you specifically want:

@example
>>> mock = Mock()
>>> mock.__getitem__ = Mock(side_effect=getitem)
>>> mock.__setitem__ = Mock(side_effect=setitem)
@end example

A `third' option is to use @code{MagicMock} but passing in @code{dict} as the `spec'
(or `spec_set') argument so that the @code{MagicMock} created only has
dictionary magic methods available:

@example
>>> mock = MagicMock(spec_set=dict)
>>> mock.__getitem__.side_effect = getitem
>>> mock.__setitem__.side_effect = setitem
@end example
@end quotation
@end cartouche

With these side effect functions in place, the @code{mock} will behave like a normal
dictionary but recording the access. It even raises a @ref{5e7,,KeyError} if you try
to access a key that doesn't exist.

@example
>>> mock['a']
1
>>> mock['c']
3
>>> mock['d']
Traceback (most recent call last):
    ...
KeyError: 'd'
>>> mock['b'] = 'fish'
>>> mock['d'] = 'eggs'
>>> mock['b']
'fish'
>>> mock['d']
'eggs'
@end example

After it has been used you can make assertions about the access using the normal
mock methods and attributes:

@example
>>> mock.__getitem__.call_args_list
[call('a'), call('c'), call('d'), call('b'), call('d')]
>>> mock.__setitem__.call_args_list
[call('b', 'fish'), call('d', 'eggs')]
>>> my_dict
@{'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'@}
@end example

@node Mock のサブクラスと属性,patch dict で import をモックする,MagicMock で辞書をモックする,さらなる例
@anchor{library/unittest mock-examples mock-subclasses-and-their-attributes}@anchor{4692}
@subsubsection Mock のサブクラスと属性


There are various reasons why you might want to subclass @ref{c3f,,Mock}. One
reason might be to add helper methods. Here's a silly example:

@example
>>> class MyMock(MagicMock):
...     def has_been_called(self):
...         return self.called
...
>>> mymock = MyMock(return_value=None)
>>> mymock
<MyMock id='...'>
>>> mymock.has_been_called()
False
>>> mymock()
>>> mymock.has_been_called()
True
@end example

The standard behaviour for @code{Mock} instances is that attributes and the return
value mocks are of the same type as the mock they are accessed on. This ensures
that @code{Mock} attributes are @code{Mocks} and @code{MagicMock} attributes are @code{MagicMocks}
@footnote{
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.
}. 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.

@example
>>> mymock.foo
<MyMock name='mock.foo' id='...'>
>>> mymock.foo.has_been_called()
False
>>> mymock.foo()
<MyMock name='mock.foo()' id='...'>
>>> mymock.foo.has_been_called()
True
@end example

Sometimes this is inconvenient. For example, one user@footnote{https://code.google.com/archive/p/mock/issues/105} is subclassing mock to
created a Twisted adaptor@footnote{https://twisted.org/documents/11.0.0/api/twisted.python.components.html}.
Having this applied to attributes too actually causes errors.

@code{Mock} (in all its flavours) uses a method called @code{_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 (@code{**kwargs}) which are then passed
onto the mock constructor:

@example
>>> class Subclass(MagicMock):
...     def _get_child_mock(self, /, **kwargs):
...         return MagicMock(**kwargs)
...
>>> mymock = Subclass()
>>> mymock.foo
<MagicMock name='mock.foo' id='...'>
>>> assert isinstance(mymock, Subclass)
>>> assert not isinstance(mymock.foo, Subclass)
>>> assert not isinstance(mymock(), Subclass)
@end example

@node patch dict で import をモックする,Tracking order of calls and less verbose call assertions,Mock のサブクラスと属性,さらなる例
@anchor{library/unittest mock-examples mocking-imports-with-patch-dict}@anchor{4693}
@subsubsection patch.dict で import をモックする


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 @code{mock} to affect the results of an import.
Importing fetches an `object' from the @ref{17e6,,sys.modules} 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 @code{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 @ref{1967,,patch.dict()} to `temporarily' put a mock in place
in @ref{17e6,,sys.modules}. 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 @code{patcher.stop()} is called) then whatever was there
previously will be restored safely.

Here's an example that mocks out the 'fooble' module.

@example
>>> import sys
>>> mock = Mock()
>>> with patch.dict('sys.modules', @{'fooble': mock@}):
...    import fooble
...    fooble.blob()
...
<Mock name='mock.blob()' id='...'>
>>> assert 'fooble' not in sys.modules
>>> mock.blob.assert_called_once_with()
@end example

As you can see the @code{import fooble} succeeds, but on exit there is no 'fooble'
left in @ref{17e6,,sys.modules}.

This also works for the @code{from module import name} form:

@example
>>> mock = Mock()
>>> with patch.dict('sys.modules', @{'fooble': mock@}):
...    from fooble import blob
...    blob.blip()
...
<Mock name='mock.blob.blip()' id='...'>
>>> mock.blob.blip.assert_called_once_with()
@end example

With slightly more work you can also mock package imports:

@example
>>> mock = Mock()
>>> modules = @{'package': mock, 'package.module': mock.module@}
>>> with patch.dict('sys.modules', modules):
...    from package.module import fooble
...    fooble()
...
<Mock name='mock.module.fooble()' id='...'>
>>> mock.module.fooble.assert_called_once_with()
@end example

@node Tracking order of calls and less verbose call assertions,More complex argument matching,patch dict で import をモックする,さらなる例
@anchor{library/unittest mock-examples tracking-order-of-calls-and-less-verbose-call-assertions}@anchor{4694}
@subsubsection Tracking order of calls and less verbose call assertions


The @ref{c3f,,Mock} class allows you to track the `order' of method calls on
your mock objects through the @ref{4639,,method_calls} attribute. This
doesn't allow you to track the order of calls between separate mock objects,
however we can use @ref{4637,,mock_calls} to achieve the same effect.

Because mocks track calls to child mocks in @code{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 @code{mock_calls} of the parent:

@example
>>> manager = Mock()
>>> mock_foo = manager.foo
>>> mock_bar = manager.bar
@end example

@example
>>> mock_foo.something()
<Mock name='mock.foo.something()' id='...'>
>>> mock_bar.other.thing()
<Mock name='mock.bar.other.thing()' id='...'>
@end example

@example
>>> manager.mock_calls
[call.foo.something(), call.bar.other.thing()]
@end example

We can then assert about the calls, including the order, by comparing with
the @code{mock_calls} attribute on the manager mock:

@example
>>> expected_calls = [call.foo.something(), call.bar.other.thing()]
>>> manager.mock_calls == expected_calls
True
@end example

If @code{patch} is creating, and putting in place, your mocks then you can attach
them to a manager mock using the @ref{1955,,attach_mock()} method. After
attaching calls will be recorded in @code{mock_calls} of the manager.

@example
>>> manager = MagicMock()
>>> with patch('mymodule.Class1') as MockClass1:
...     with patch('mymodule.Class2') as MockClass2:
...         manager.attach_mock(MockClass1, 'MockClass1')
...         manager.attach_mock(MockClass2, 'MockClass2')
...         MockClass1().foo()
...         MockClass2().bar()
<MagicMock name='mock.MockClass1().foo()' id='...'>
<MagicMock name='mock.MockClass2().bar()' id='...'>
>>> manager.mock_calls
[call.MockClass1(),
call.MockClass1().foo(),
call.MockClass2(),
call.MockClass2().bar()]
@end example

If many calls have been made, but you're only interested in a particular
sequence of them then an alternative is to use the
@ref{1a22,,assert_has_calls()} method. This takes a list of calls (constructed
with the @ref{1db3,,call} object). If that sequence of calls are in
@ref{4637,,mock_calls} then the assert succeeds.

@example
>>> m = MagicMock()
>>> m().foo().bar().baz()
<MagicMock name='mock().foo().bar().baz()' id='...'>
>>> m.one().two().three()
<MagicMock name='mock.one().two().three()' id='...'>
>>> calls = call.one().two().three().call_list()
>>> m.assert_has_calls(calls)
@end example

Even though the chained call @code{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 @code{any_order=True} to @code{assert_has_calls}:

@example
>>> m = MagicMock()
>>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
(...)
>>> calls = [call.fifty('50'), call(1), call.seven(7)]
>>> m.assert_has_calls(calls, any_order=True)
@end example

@node More complex argument matching,,Tracking order of calls and less verbose call assertions,さらなる例
@anchor{library/unittest mock-examples more-complex-argument-matching}@anchor{4695}
@subsubsection More complex argument matching


Using the same basic concept as @ref{1db1,,ANY} 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 @ref{1e03,,assert_called_with()} 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 @code{assert_called_with} isn't
sufficient:

@example
>>> class Foo:
...     def __init__(self, a, b):
...         self.a, self.b = a, b
...
>>> mock = Mock(return_value=None)
>>> mock(Foo(1, 2))
>>> mock.assert_called_with(Foo(1, 2))
Traceback (most recent call last):
    ...
AssertionError: expected call not found.
Expected: mock(<__main__.Foo object at 0x...>)
Actual: mock(<__main__.Foo object at 0x...>)
@end example

A comparison function for our @code{Foo} class might look something like this:

@example
>>> def compare(self, other):
...     if not type(self) == type(other):
...         return False
...     if self.a != other.a:
...         return False
...     if self.b != other.b:
...         return False
...     return True
...
@end example

And a matcher object that can use comparison functions like this for its
equality operation would look something like this:

@example
>>> class Matcher:
...     def __init__(self, compare, some_obj):
...         self.compare = compare
...         self.some_obj = some_obj
...     def __eq__(self, other):
...         return self.compare(self.some_obj, other)
...
@end example

全てをつなぎ合わせて:

@example
>>> match_foo = Matcher(compare, Foo(1, 2))
>>> mock.assert_called_with(match_foo)
@end example

The @code{Matcher} is instantiated with our compare function and the @code{Foo} object
we want to compare against. In @code{assert_called_with} the @code{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
@code{assert_called_with} passes, and if they don't an @ref{8b8,,AssertionError} is raised:

@example
>>> match_wrong = Matcher(compare, Foo(3, 4))
>>> mock.assert_called_with(match_wrong)
Traceback (most recent call last):
    ...
AssertionError: Expected: ((<Matcher object at 0x...>,), @{@})
Called with: ((<Foo object at 0x...>,), @{@})
@end example

With a bit of tweaking you could have the comparison function raise the
@ref{8b8,,AssertionError} directly and provide a more useful failure message.

As of version 1.5, the Python testing library PyHamcrest@footnote{https://pyhamcrest.readthedocs.io/} provides similar functionality,
that may be useful here, in the form of its equality matcher
(hamcrest.library.integration.match_equality@footnote{https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality}).

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node test --- Regression tests package for Python,test support --- Utilities for the Python test suite,unittest mock --- 入門,開発ツール
@anchor{library/test doc}@anchor{4696}@anchor{library/test module-test}@anchor{e8}@anchor{library/test test-regression-tests-package-for-python}@anchor{4697}@anchor{library/test translation-repo}@anchor{4698}
@subsection @code{test} --- Regression tests package for Python


@geindex module; test

@cartouche
@quotation 注釈 
The @code{test} package is meant for internal use by Python only. It is
documented for the benefit of the core developers of Python. Any use of
this package outside of Python's standard library is discouraged as code
mentioned here can change or be removed without notice between releases of
Python.
@end quotation
@end cartouche


__________________________________________________________________


The @code{test} package contains all regression tests for Python as well as the
modules @ref{ea,,test.support} and @ref{e9,,test.regrtest}.
@ref{ea,,test.support} is used to enhance your tests while
@ref{e9,,test.regrtest} drives the testing suite.

Each module in the @code{test} package whose name starts with @code{test_} is a
testing suite for a specific module or feature. All new tests should be written
using the @ref{10c,,unittest} or @ref{3e,,doctest} module.  Some older tests are
written using a "traditional" testing style that compares output printed to
@code{sys.stdout}; this style of test is considered deprecated.


@subsubheading 参考



@table @asis

@item @ref{10c,,unittest} モジュール

PyUnit 回帰テストを書く。

@item @ref{3e,,doctest} モジュール

ドキュメンテーション文字列に埋め込まれたテスト。
@end table


@menu
* Writing Unit Tests for the test package:: 
* コマンドラインインターフェースを利用してテストを実行する:: 

@end menu

@node Writing Unit Tests for the test package,コマンドラインインターフェースを利用してテストを実行する,,test --- Regression tests package for Python
@anchor{library/test writing-tests}@anchor{4699}@anchor{library/test writing-unit-tests-for-the-test-package}@anchor{469a}
@subsubsection Writing Unit Tests for the @code{test} package


@ref{10c,,unittest} モジュールを使ってテストを書く場合、幾つかのガイドラインに従うことが推奨されます。 1つは、テストモジュールの名前を、 @code{test_} で始め、テスト対象となるモジュール名で終えることです。テストモジュール中のテストメソッドは名前を @code{test_} で始めて、そのメソッドが何をテストしているかという説明で終えます。これはテスト実行プログラムが、そのメソッドをテストメソッドとして認識するために必要です。また、テストメソッドにはドキュメンテーション文字列を入れるべきではありません。コメント（例えば @code{# True あるいは False だけを返すテスト関数} ）を使用して、テストメソッドのドキュメントを記述してください。これは、ドキュメンテーション文字列が存在する場合はその内容が出力されてしまうため、どのテストを実行しているのかをいちいち表示したくないからです。

以下のような決まり文句を使います:

@example
import unittest
from test import support

class MyTestCase1(unittest.TestCase):

    # Only use setUp() and tearDown() if necessary

    def setUp(self):
        ... code to execute in preparation for tests ...

    def tearDown(self):
        ... code to execute to clean up after tests ...

    def test_feature_one(self):
        # Test feature one.
        ... testing code ...

    def test_feature_two(self):
        # Test feature two.
        ... testing code ...

    ... more test methods ...

class MyTestCase2(unittest.TestCase):
    ... same structure as MyTestCase1 ...

... more test classes ...

if __name__ == '__main__':
    unittest.main()
@end example

このコードのパターンを使うと @ref{e9,,test.regrtest} からテストスイートを実行でき、 @ref{10c,,unittest} のコマンドラインインターフェースをサポートしているスクリプトとして自分自身を起動したり、 @code{python -m unittest} というコマンドラインインターフェースを通して起動したりできます。

回帰テストの目的はコードを解き明かすことです。そのためには以下のいくつかのガイドラインに従ってください:


@itemize *

@item 
テストスイートから、すべてのクラス、関数および定数を実行するべきです。これには外部に公開される外部APIだけでなく「プライベートな」コードも含みます。

@item 
ホワイトボックス・テスト（対象のコードの詳細を元にテストを書くこと）を推奨します。ブラックボックス・テスト（公開されるインターフェース仕様だけをテストすること）は、すべての境界条件を確実にテストするには完全ではありません。

@item 
すべての取りうる値を、無効値も含めてテストするようにしてください。そのようなテストを書くことで、全ての有効値が通るだけでなく、不適切な値が正しく処理されることも確認できます。

@item 
コード内のできる限り多くのパスを網羅してください。分岐するように入力を調整したテストを書くことで、コードの多くのパスをたどることができます。

@item 
テスト対象のコードにバグが発見された場合は、明示的にテスト追加するようにしてください。そのようなテストを追加することで、将来コードを変更した際にエラーが再発することを防止できます。

@item 
テストの後始末 (例えば一時ファイルをすべて閉じたり削除したりすること) を必ず行ってください。

@item 
テストがオペレーティングシステムの特定の状況に依存する場合、テスト開始時に条件を満たしているかを検証してください。

@item 
インポートするモジュールをできるかぎり少なくし、可能な限り早期にインポートを行ってください。そうすることで、テストの外部依存性を最小限にし、モジュールのインポートによる副作用から生じる変則的な動作を最小限にできます。

@item 
できる限りテストコードを再利用するようにしましょう。時として、入力の違いだけを記述すれば良くなるくらい、テストコードを小さくすることができます。例えば以下のように、サブクラスで入力を指定することで、コードの重複を最小化することができます:

@example
class TestFuncAcceptsSequencesMixin:

    func = mySuperWhammyFunction

    def test_func(self):
        self.func(self.arg)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = (1, 2, 3)
@end example

When using this pattern, remember that all classes that inherit from
@ref{2b3,,unittest.TestCase} are run as tests.  The @code{TestFuncAcceptsSequencesMixin} class in the example above
does not have any data and so can't be run by itself, thus it does not
inherit from @ref{2b3,,unittest.TestCase}.
@end itemize


@subsubheading 参考



@table @asis

@item Test Driven Development

コードより前にテストを書く方法論に関する Kent Beck の著書。
@end table


@node コマンドラインインターフェースを利用してテストを実行する,,Writing Unit Tests for the test package,test --- Regression tests package for Python
@anchor{library/test module-test regrtest}@anchor{e9}@anchor{library/test regrtest}@anchor{120b}@anchor{library/test running-tests-using-the-command-line-interface}@anchor{469b}
@subsubsection コマンドラインインターフェースを利用してテストを実行する


@geindex module; test.regrtest

The @code{test} package can be run as a script to drive Python's regression
test suite, thanks to the @ref{23c,,-m} option: @code{python -m test}. Under
the hood, it uses @code{test.regrtest}; the call @code{python -m
test.regrtest} used in previous Python versions still works.  Running the
script by itself automatically starts running all regression tests in the
@code{test} package. It does this by finding all modules in the package whose
name starts with @code{test_}, importing them, and executing the function
@code{test_main()} if present or loading the tests via
unittest.TestLoader.loadTestsFromModule if @code{test_main} does not exist.  The
names of tests to execute may also be passed to the script. Specifying a single
regression test (@code{python -m test test_spam}) will minimize output and
only print whether the test passed or failed.

Running @code{test} directly allows what resources are available for
tests to use to be set. You do this by using the @code{-u} command-line
option. Specifying @code{all} as the value for the @code{-u} option enables all
possible resources: @code{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
@code{all}. The command @code{python -m test -uall,-audio,-largefile}
will run @code{test} with all resources except the @code{audio} and
@code{largefile} resources. For a list of all resources and more command-line
options, run @code{python -m test -h}.

テストを実行しようとするプラットフォームによっては、回帰テストを実行する別の方法があります。 Unix では、Python をビルドしたトップレベルディレクトリで @code{make test} を実行できます。 Windows上では、 @code{PCbuild} ディレクトリから @code{rt.bat} を実行すると、すべての回帰テストを実行します。


Added in version 3.14: Output is colorized by default and can be
@ref{1b7,,controlled using environment variables}.


@node test support --- Utilities for the Python test suite,test support socket_helper --- Utilities for socket tests,test --- Regression tests package for Python,開発ツール
@anchor{library/test module-test support}@anchor{ea}@anchor{library/test test-support-utilities-for-the-python-test-suite}@anchor{469c}
@subsection @code{test.support} --- Utilities for the Python test suite


@geindex module; test.support

The @code{test.support} module provides support for Python's regression
test suite.

@cartouche
@quotation 注釈 
@code{test.support} 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.
@end quotation
@end cartouche

このモジュールは次の例外を定義しています:

@geindex TestFailed
@anchor{library/test test support TestFailed}@anchor{469d}
@deffn {例外} test.support.TestFailed

テストが失敗したとき送出される例外です。これは、 @ref{10c,,unittest} ベースのテストでは廃止予定で、 @ref{2b3,,unittest.TestCase} の assertXXX メソッドが推奨されます。
@end deffn

@geindex ResourceDenied
@anchor{library/test test support ResourceDenied}@anchor{469e}
@deffn {例外} test.support.ResourceDenied

@ref{11e6,,unittest.SkipTest} のサブクラスです。 (ネットワーク接続のような) リソースが利用できないとき送出されます。 @ref{469f,,requires()} 関数によって送出されます。
@end deffn

The @code{test.support} module defines the following constants:

@geindex verbose (test.support モジュール)
@anchor{library/test test support verbose}@anchor{46a0}
@deffn {データ} test.support.verbose

冗長な出力が有効な場合は @code{True} です。実行中のテストについてのより詳細な情報が欲しいときにチェックします。 `verbose' は @ref{e9,,test.regrtest} によって設定されます。
@end deffn

@geindex is_jython (test.support モジュール)
@anchor{library/test test support is_jython}@anchor{46a1}
@deffn {データ} test.support.is_jython

実行中のインタプリタが Jython ならば @code{True} になります。
@end deffn

@geindex is_android (test.support モジュール)
@anchor{library/test test support is_android}@anchor{46a2}
@deffn {データ} test.support.is_android

@code{True} if @code{sys.platform} is @code{android}.
@end deffn

@geindex is_emscripten (test.support モジュール)
@anchor{library/test test support is_emscripten}@anchor{46a3}
@deffn {データ} test.support.is_emscripten

@code{True} if @code{sys.platform} is @code{emscripten}.
@end deffn

@geindex is_wasi (test.support モジュール)
@anchor{library/test test support is_wasi}@anchor{46a4}
@deffn {データ} test.support.is_wasi

@code{True} if @code{sys.platform} is @code{wasi}.
@end deffn

@geindex is_apple_mobile (test.support モジュール)
@anchor{library/test test support is_apple_mobile}@anchor{46a5}
@deffn {データ} test.support.is_apple_mobile

@code{True} if @code{sys.platform} is @code{ios}, @code{tvos}, or @code{watchos}.
@end deffn

@geindex is_apple (test.support モジュール)
@anchor{library/test test support is_apple}@anchor{46a6}
@deffn {データ} test.support.is_apple

@code{True} if @code{sys.platform} is @code{darwin} or @code{is_apple_mobile} is @code{True}.
@end deffn

@geindex unix_shell (test.support モジュール)
@anchor{library/test test support unix_shell}@anchor{46a7}
@deffn {データ} test.support.unix_shell

Windows 以外ではシェルのパスです; そうでない場合は @code{None} です。
@end deffn

@geindex LOOPBACK_TIMEOUT (test.support モジュール)
@anchor{library/test test support LOOPBACK_TIMEOUT}@anchor{1d9c}
@deffn {データ} test.support.LOOPBACK_TIMEOUT

Timeout in seconds for tests using a network server listening on the network
local loopback interface like @code{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 @ref{fa3,,connect()},
@ref{fa4,,recv()} and @ref{fa7,,send()} methods of
@ref{fa1,,socket.socket}.

デフォルト値は5秒です。

@ref{1d9d,,INTERNET_TIMEOUT} も参照してください。
@end deffn

@geindex INTERNET_TIMEOUT (test.support モジュール)
@anchor{library/test test support INTERNET_TIMEOUT}@anchor{1d9d}
@deffn {データ} test.support.INTERNET_TIMEOUT

Timeout in seconds for network requests going to the internet.

The timeout is short enough to prevent a test to wait for too long if the
internet request is blocked for whatever reason.

Usually, a timeout using @ref{1d9d,,INTERNET_TIMEOUT} should not mark a test as
failed, but skip the test instead: see
@ref{46a8,,transient_internet()}.

デフォルト値は1分です。

@ref{1d9c,,LOOPBACK_TIMEOUT} も参照してください。
@end deffn

@geindex SHORT_TIMEOUT (test.support モジュール)
@anchor{library/test test support SHORT_TIMEOUT}@anchor{1c63}
@deffn {データ} 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 @code{--timeout} command line option.

If a test using @ref{1c63,,SHORT_TIMEOUT} starts to fail randomly on slow
buildbots, use @ref{1d9e,,LONG_TIMEOUT} instead.

デフォルト値は30秒です。
@end deffn

@geindex LONG_TIMEOUT (test.support モジュール)
@anchor{library/test test support LONG_TIMEOUT}@anchor{1d9e}
@deffn {データ} 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 @code{--timeout} command
line option.

デフォルト値は5分です。

See also @ref{1d9c,,LOOPBACK_TIMEOUT}, @ref{1d9d,,INTERNET_TIMEOUT} and
@ref{1c63,,SHORT_TIMEOUT}.
@end deffn

@geindex PGO (test.support モジュール)
@anchor{library/test test support PGO}@anchor{46a9}
@deffn {データ} test.support.PGO

テストが PGO (Profile Guided Optimization) の役に立たないときにスキップできるなら設定します。
@end deffn

@geindex PIPE_MAX_SIZE (test.support モジュール)
@anchor{library/test test support PIPE_MAX_SIZE}@anchor{46aa}
@deffn {データ} test.support.PIPE_MAX_SIZE

書き込みをブロックするための、基底にある OS のパイプバッファサイズより大きいであろう定数。
@end deffn

@geindex Py_DEBUG (test.support モジュール)
@anchor{library/test test support Py_DEBUG}@anchor{46ab}
@deffn {データ} test.support.Py_DEBUG

@code{True} if Python was built with the @ref{1834,,Py_DEBUG} macro
defined, that is, if
Python was @ref{509,,built in debug mode}.


Added in version 3.12.

@end deffn

@geindex SOCK_MAX_SIZE (test.support モジュール)
@anchor{library/test test support SOCK_MAX_SIZE}@anchor{46ac}
@deffn {データ} test.support.SOCK_MAX_SIZE

書き込みをブロックするための、基底にある OS のソケットバッファサイズより大きいであろう定数。
@end deffn

@geindex TEST_SUPPORT_DIR (test.support モジュール)
@anchor{library/test test support TEST_SUPPORT_DIR}@anchor{46ad}
@deffn {データ} test.support.TEST_SUPPORT_DIR

Set to the top level directory that contains @code{test.support}.
@end deffn

@geindex TEST_HOME_DIR (test.support モジュール)
@anchor{library/test test support TEST_HOME_DIR}@anchor{46ae}
@deffn {データ} test.support.TEST_HOME_DIR

テストパッケージのトップディレクトリを設定します。
@end deffn

@geindex TEST_DATA_DIR (test.support モジュール)
@anchor{library/test test support TEST_DATA_DIR}@anchor{46af}
@deffn {データ} test.support.TEST_DATA_DIR

テストパッケージ内の @code{data} ディレクトリを設定します。
@end deffn

@geindex MAX_Py_ssize_t (test.support モジュール)
@anchor{library/test test support MAX_Py_ssize_t}@anchor{46b0}
@deffn {データ} test.support.MAX_Py_ssize_t

大量のメモリを使うテストのための  @ref{13dd,,sys.maxsize} を設定します。
@end deffn

@geindex max_memuse (test.support モジュール)
@anchor{library/test test support max_memuse}@anchor{46b1}
@deffn {データ} test.support.max_memuse

大量のメモリを使うテストのためのメモリ上限となる @ref{46b2,,set_memlimit()} を設定します。
@ref{46b0,,MAX_Py_ssize_t} が設定上限です。
@end deffn

@geindex real_max_memuse (test.support モジュール)
@anchor{library/test test support real_max_memuse}@anchor{46b3}
@deffn {データ} test.support.real_max_memuse

大量のメモリを使うテストのためのメモリ上限となる @ref{46b2,,set_memlimit()} を設定します。
@ref{46b0,,MAX_Py_ssize_t} の設定上限はありません。
@end deffn

@geindex MISSING_C_DOCSTRINGS (test.support モジュール)
@anchor{library/test test support MISSING_C_DOCSTRINGS}@anchor{46b4}
@deffn {データ} test.support.MISSING_C_DOCSTRINGS

Set to @code{True} if Python is built without docstrings (the
@code{WITH_DOC_STRINGS} macro is not defined).
See the @ref{21a2,,configure --without-doc-strings} option.

See also the @ref{46b5,,HAVE_DOCSTRINGS} variable.
@end deffn

@geindex HAVE_DOCSTRINGS (test.support モジュール)
@anchor{library/test test support HAVE_DOCSTRINGS}@anchor{46b5}
@deffn {データ} test.support.HAVE_DOCSTRINGS

Set to @code{True} if function docstrings are available.
See the @ref{18c,,python -OO} option, which strips docstrings of functions implemented in Python.

See also the @ref{46b4,,MISSING_C_DOCSTRINGS} variable.
@end deffn

@geindex TEST_HTTP_URL (test.support モジュール)
@anchor{library/test test support TEST_HTTP_URL}@anchor{46b6}
@deffn {データ} test.support.TEST_HTTP_URL

ネットワークテスト専用の HTTP サーバーの URL を定義します。
@end deffn

@geindex ALWAYS_EQ (test.support モジュール)
@anchor{library/test test support ALWAYS_EQ}@anchor{46b7}
@deffn {データ} test.support.ALWAYS_EQ

Object that is equal to anything.  Used to test mixed type comparison.
@end deffn

@geindex NEVER_EQ (test.support モジュール)
@anchor{library/test test support NEVER_EQ}@anchor{46b8}
@deffn {データ} test.support.NEVER_EQ

Object that is not equal to anything (even to @ref{46b7,,ALWAYS_EQ}).
Used to test mixed type comparison.
@end deffn

@geindex LARGEST (test.support モジュール)
@anchor{library/test test support LARGEST}@anchor{46b9}
@deffn {データ} test.support.LARGEST

Object that is greater than anything (except itself).
Used to test mixed type comparison.
@end deffn

@geindex SMALLEST (test.support モジュール)
@anchor{library/test test support SMALLEST}@anchor{46ba}
@deffn {データ} test.support.SMALLEST

Object that is less than anything (except itself).
Used to test mixed type comparison.
@end deffn

The @code{test.support} module defines the following functions:

@geindex busy_retry() (test.support モジュール)
@anchor{library/test test support busy_retry}@anchor{46bb}
@deffn {の関数} test.support.busy_retry (timeout, err_msg=None, /, *, error=True)

Run the loop body until @code{break} stops the loop.

After `timeout' seconds, raise an @ref{8b8,,AssertionError} if `error' is true,
or just stop the loop if `error' is false.

以下はプログラム例です:

@example
for _ in support.busy_retry(support.SHORT_TIMEOUT):
    if check():
        break
@end example

Example of error=False usage:

@example
for _ in support.busy_retry(support.SHORT_TIMEOUT, error=False):
    if check():
        break
else:
    raise RuntimeError('my custom error')
@end example
@end deffn

@geindex sleeping_retry() (test.support モジュール)
@anchor{library/test test support sleeping_retry}@anchor{46bc}
@deffn {の関数} test.support.sleeping_retry (timeout, err_msg=None, /, *, init_delay=0.010, max_delay=1.0, error=True)

Wait strategy that applies exponential backoff.

Run the loop body until @code{break} stops the loop. Sleep at each loop
iteration, but not at the first iteration. The sleep delay is doubled at
each iteration (up to `max_delay' seconds).

See @ref{46bb,,busy_retry()} documentation for the parameters usage.

Example raising an exception after SHORT_TIMEOUT seconds:

@example
for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
    if check():
        break
@end example

Example of error=False usage:

@example
for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False):
    if check():
        break
else:
    raise RuntimeError('my custom error')
@end example
@end deffn

@geindex is_resource_enabled() (test.support モジュール)
@anchor{library/test test support is_resource_enabled}@anchor{46bd}
@deffn {の関数} test.support.is_resource_enabled (resource)

`resource' が有効で利用可能ならば @code{True} を返します。利用可能なリソースのリストは、 @ref{e9,,test.regrtest} がテストを実行している間のみ設定されます。
@end deffn

@geindex get_resource_value() (test.support モジュール)
@anchor{library/test test support get_resource_value}@anchor{46be}
@deffn {の関数} test.support.get_resource_value (resource)

Return the value specified for `resource' (as @code{-u @var{resource}=@var{value}}).
Return @code{None} if `resource' is disabled or no value is specified.
@end deffn

@geindex python_is_optimized() (test.support モジュール)
@anchor{library/test test support python_is_optimized}@anchor{46bf}
@deffn {の関数} test.support.python_is_optimized ()

Return @code{True} if Python was not built with @code{-O0} or @code{-Og}.
@end deffn

@geindex with_pymalloc() (test.support モジュール)
@anchor{library/test test support with_pymalloc}@anchor{46c0}
@deffn {の関数} test.support.with_pymalloc ()

Return @code{_testcapi.WITH_PYMALLOC}.
@end deffn

@geindex requires() (test.support モジュール)
@anchor{library/test test support requires}@anchor{469f}
@deffn {の関数} test.support.requires (resource, msg=None)

`resource' が利用できなければ、 @ref{469e,,ResourceDenied} を送出します。その場合、 `msg' は @ref{469e,,ResourceDenied} の引数になります。 @code{__name__} が @code{'__main__'} である関数にから呼び出された場合には常に @code{True} を返します。テストを @ref{e9,,test.regrtest} から実行するときに使われます。
@end deffn

@geindex sortdict() (test.support モジュール)
@anchor{library/test test support sortdict}@anchor{46c1}
@deffn {の関数} test.support.sortdict (dict)

Return a repr of `dict' with keys sorted.
@end deffn

@geindex findfile() (test.support モジュール)
@anchor{library/test test support findfile}@anchor{46c2}
@deffn {の関数} test.support.findfile (filename, subdir=None)

`filename' という名前のファイルへのパスを返します。一致するものが見つからなければ、 `filename' 自体を返します。 `filename' 自体もファイルへのパスでありえるので、 `filename' が返っても失敗ではありません。

`subdir' を設定することで、パスのディレクトリを直接見に行くのではなく、相対パスを使って見付けにいくように指示できます。
@end deffn

@geindex get_pagesize() (test.support モジュール)
@anchor{library/test test support get_pagesize}@anchor{46c3}
@deffn {の関数} test.support.get_pagesize ()

Get size of a page in bytes.


Added in version 3.12.

@end deffn

@geindex setswitchinterval() (test.support モジュール)
@anchor{library/test test support setswitchinterval}@anchor{46c4}
@deffn {の関数} test.support.setswitchinterval (interval)

Set the @ref{b44,,sys.setswitchinterval()} to the given `interval'.  Defines
a minimum interval for Android systems to prevent the system from hanging.
@end deffn

@geindex check_impl_detail() (test.support モジュール)
@anchor{library/test test support check_impl_detail}@anchor{46c5}
@deffn {の関数} test.support.check_impl_detail (**guards)

Use this check to guard CPython's implementation-specific tests or to
run them only on the implementations guarded by the arguments.  This
function returns @code{True} or @code{False} depending on the host platform.
Example usage:

@example
check_impl_detail()               # Only on CPython (default).
check_impl_detail(jython=True)    # Only on Jython.
check_impl_detail(cpython=False)  # Everywhere except CPython.
@end example
@end deffn

@geindex set_memlimit() (test.support モジュール)
@anchor{library/test test support set_memlimit}@anchor{46b2}
@deffn {の関数} test.support.set_memlimit (limit)

Set the values for @ref{46b1,,max_memuse} and @ref{46b3,,real_max_memuse} for big
memory tests.
@end deffn

@geindex record_original_stdout() (test.support モジュール)
@anchor{library/test test support record_original_stdout}@anchor{46c6}
@deffn {の関数} test.support.record_original_stdout (stdout)

Store the value from `stdout'.  It is meant to hold the stdout at the
time the regrtest began.
@end deffn

@geindex get_original_stdout() (test.support モジュール)
@anchor{library/test test support get_original_stdout}@anchor{46c7}
@deffn {の関数} test.support.get_original_stdout ()

Return the original stdout set by @ref{46c6,,record_original_stdout()} or
@code{sys.stdout} if it's not set.
@end deffn

@geindex args_from_interpreter_flags() (test.support モジュール)
@anchor{library/test test support args_from_interpreter_flags}@anchor{46c8}
@deffn {の関数} test.support.args_from_interpreter_flags ()

Return a list of command line arguments reproducing the current settings
in @code{sys.flags} and @code{sys.warnoptions}.
@end deffn

@geindex optim_args_from_interpreter_flags() (test.support モジュール)
@anchor{library/test test support optim_args_from_interpreter_flags}@anchor{46c9}
@deffn {の関数} test.support.optim_args_from_interpreter_flags ()

Return a list of command line arguments reproducing the current
optimization settings in @code{sys.flags}.
@end deffn

@geindex captured_stdin() (test.support モジュール)
@geindex captured_stdout() (test.support モジュール)
@geindex captured_stderr() (test.support モジュール)
@anchor{library/test test support captured_stdin}@anchor{46ca}
@deffn {の関数} test.support.captured_stdin ()
@anchor{library/test test support captured_stdout}@anchor{46cb}
@deffnx {の関数} test.support.captured_stdout ()
@anchor{library/test test support captured_stderr}@anchor{1dd8}
@deffnx {の関数} test.support.captured_stderr ()

名前付きストリ－ムを @ref{112a,,io.StringIO} オブジェクトで一時的に置き換えるコンテキストマネージャです。

出力ストリームの使用例:

@example
with captured_stdout() as stdout, captured_stderr() as stderr:
    print("hello")
    print("error", file=sys.stderr)
assert stdout.getvalue() == "hello\n"
assert stderr.getvalue() == "error\n"
@end example

入力ストリ－ムの使用例:

@example
with captured_stdin() as stdin:
    stdin.write('hello\n')
    stdin.seek(0)
    # call test code that consumes from sys.stdin
    captured = input()
self.assertEqual(captured, "hello")
@end example
@end deffn

@geindex disable_faulthandler() (test.support モジュール)
@anchor{library/test test support disable_faulthandler}@anchor{46cc}
@deffn {の関数} test.support.disable_faulthandler ()

A context manager that temporary disables @ref{5c,,faulthandler}.
@end deffn

@geindex gc_collect() (test.support モジュール)
@anchor{library/test test support gc_collect}@anchor{46cd}
@deffn {の関数} 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 @code{__del__} methods may be called later than expected and weakrefs
may remain alive for longer than expected.
@end deffn

@geindex disable_gc() (test.support モジュール)
@anchor{library/test test support disable_gc}@anchor{46ce}
@deffn {の関数} test.support.disable_gc ()

A context manager that disables the garbage collector on entry. On
exit, the garbage collector is restored to its prior state.
@end deffn

@geindex swap_attr() (test.support モジュール)
@anchor{library/test test support swap_attr}@anchor{46cf}
@deffn {の関数} test.support.swap_attr (obj, attr, new_val)

Context manager to swap out an attribute with a new object.

使い方:

@example
with swap_attr(obj, "attr", 5):
    ...
@end example

This will set @code{obj.attr} to 5 for the duration of the @code{with} block,
restoring the old value at the end of the block.  If @code{attr} doesn't
exist on @code{obj}, it will be created and then deleted at the end of the
block.

The old value (or @code{None} if it doesn't exist) will be assigned to the
target of the "as" clause, if there is one.
@end deffn

@geindex swap_item() (test.support モジュール)
@anchor{library/test test support swap_item}@anchor{46d0}
@deffn {の関数} test.support.swap_item (obj, attr, new_val)

Context manager to swap out an item with a new object.

使い方:

@example
with swap_item(obj, "item", 5):
    ...
@end example

This will set @code{obj["item"]} to 5 for the duration of the @code{with} block,
restoring the old value at the end of the block. If @code{item} doesn't
exist on @code{obj}, it will be created and then deleted at the end of the
block.

The old value (or @code{None} if it doesn't exist) will be assigned to the
target of the "as" clause, if there is one.
@end deffn

@geindex flush_std_streams() (test.support モジュール)
@anchor{library/test test support flush_std_streams}@anchor{46d1}
@deffn {の関数} test.support.flush_std_streams ()

Call the @code{flush()} method on @ref{ccd,,sys.stdout} and then on
@ref{b33,,sys.stderr}. It can be used to make sure that the logs order is
consistent before writing into stderr.


Added in version 3.11.

@end deffn

@geindex print_warning() (test.support モジュール)
@anchor{library/test test support print_warning}@anchor{46d2}
@deffn {の関数} test.support.print_warning (msg)

Print a warning into @ref{46d3,,sys.__stderr__}. Format the message as:
@code{f"Warning -- @{msg@}"}. If `msg' is made of multiple lines, add
@code{"Warning -- "} prefix to each line.


Added in version 3.9.

@end deffn

@geindex wait_process() (test.support モジュール)
@anchor{library/test test support wait_process}@anchor{1d5d}
@deffn {の関数} test.support.wait_process (pid, *, exitcode, timeout=None)

Wait until process `pid' completes and check that the process exit code is
`exitcode'.

Raise an @ref{8b8,,AssertionError} if the process exit code is not equal to
`exitcode'.

If the process runs longer than `timeout' seconds (@ref{1c63,,SHORT_TIMEOUT} by
default), kill the process and raise an @ref{8b8,,AssertionError}. The timeout
feature is not available on Windows.


Added in version 3.9.

@end deffn

@geindex calcobjsize() (test.support モジュール)
@anchor{library/test test support calcobjsize}@anchor{46d4}
@deffn {の関数} test.support.calcobjsize (fmt)

Return the size of the @ref{5df,,PyObject} whose structure members are
defined by `fmt'. The returned value includes the size of the Python object header and alignment.
@end deffn

@geindex calcvobjsize() (test.support モジュール)
@anchor{library/test test support calcvobjsize}@anchor{46d5}
@deffn {の関数} test.support.calcvobjsize (fmt)

Return the size of the @ref{46d6,,PyVarObject} whose structure members are
defined by `fmt'. The returned value includes the size of the Python object header and alignment.
@end deffn

@geindex checksizeof() (test.support モジュール)
@anchor{library/test test support checksizeof}@anchor{46d7}
@deffn {の関数} test.support.checksizeof (test, o, size)

For testcase `test', assert that the @code{sys.getsizeof} for `o' plus the GC
header size equals `size'.
@end deffn

@geindex anticipate_failure() (test.support モジュール)
@anchor{library/test test support anticipate_failure}@anchor{46d8}
@deffn {の関数} @@test.support.anticipate_failure (condition)

ある条件で @ref{45e9,,unittest.expectedFailure()} の印をテストに付けるデコレータ。
このデコレータを使うときはいつも、関連する問題を指し示すコメントを付けておくべきです。
@end deffn

@geindex system_must_validate_cert() (test.support モジュール)
@anchor{library/test test support system_must_validate_cert}@anchor{46d9}
@deffn {の関数} test.support.system_must_validate_cert (f)

A decorator that skips the decorated test on TLS certification validation failures.
@end deffn

@geindex run_with_locale() (test.support モジュール)
@anchor{library/test test support run_with_locale}@anchor{46da}
@deffn {の関数} @@test.support.run_with_locale (catstr, *locales)

別のロケールで関数を実行し、完了したら適切に元の状態に戻すためのデコレータ。
`catstr' は (例えば @code{"LC_ALL"} のような) ロケールカテゴリを文字列で表したものです。
渡された `locales' が順々に試され、一番最初に出てきた妥当なロケールが使われます。
@end deffn

@geindex run_with_tz() (test.support モジュール)
@anchor{library/test test support run_with_tz}@anchor{46db}
@deffn {の関数} @@test.support.run_with_tz (tz)

A decorator for running a function in a specific timezone, correctly
resetting it after it has finished.
@end deffn

@geindex requires_freebsd_version() (test.support モジュール)
@anchor{library/test test support requires_freebsd_version}@anchor{46dc}
@deffn {の関数} @@test.support.requires_freebsd_version (*min_version)

Decorator for the minimum version when running test on FreeBSD.  If the
FreeBSD version is less than the minimum, the test is skipped.
@end deffn

@geindex requires_linux_version() (test.support モジュール)
@anchor{library/test test support requires_linux_version}@anchor{46dd}
@deffn {の関数} @@test.support.requires_linux_version (*min_version)

Decorator for the minimum version when running test on Linux.  If the
Linux version is less than the minimum, the test is skipped.
@end deffn

@geindex requires_mac_version() (test.support モジュール)
@anchor{library/test test support requires_mac_version}@anchor{46de}
@deffn {の関数} @@test.support.requires_mac_version (*min_version)

Decorator for the minimum version when running test on macOS.  If the
macOS version is less than the minimum, the test is skipped.
@end deffn

@geindex requires_gil_enabled() (test.support モジュール)
@anchor{library/test test support requires_gil_enabled}@anchor{46df}
@deffn {の関数} @@test.support.requires_gil_enabled

Decorator for skipping tests on the free-threaded build.  If the
@ref{164,,GIL} is disabled, the test is skipped.
@end deffn

@geindex requires_IEEE_754() (test.support モジュール)
@anchor{library/test test support requires_IEEE_754}@anchor{46e0}
@deffn {の関数} @@test.support.requires_IEEE_754

Decorator for skipping tests on non-IEEE 754 platforms.
@end deffn

@geindex requires_zlib() (test.support モジュール)
@anchor{library/test test support requires_zlib}@anchor{46e1}
@deffn {の関数} @@test.support.requires_zlib

Decorator for skipping tests if @ref{139,,zlib} doesn't exist.
@end deffn

@geindex requires_gzip() (test.support モジュール)
@anchor{library/test test support requires_gzip}@anchor{46e2}
@deffn {の関数} @@test.support.requires_gzip

Decorator for skipping tests if @ref{6b,,gzip} doesn't exist.
@end deffn

@geindex requires_bz2() (test.support モジュール)
@anchor{library/test test support requires_bz2}@anchor{46e3}
@deffn {の関数} @@test.support.requires_bz2

Decorator for skipping tests if @ref{14,,bz2} doesn't exist.
@end deffn

@geindex requires_lzma() (test.support モジュール)
@anchor{library/test test support requires_lzma}@anchor{46e4}
@deffn {の関数} @@test.support.requires_lzma

Decorator for skipping tests if @ref{8e,,lzma} doesn't exist.
@end deffn

@geindex requires_resource() (test.support モジュール)
@anchor{library/test test support requires_resource}@anchor{46e5}
@deffn {の関数} @@test.support.requires_resource (resource)

Decorator for skipping tests if `resource' is not available.
@end deffn

@geindex requires_docstrings() (test.support モジュール)
@anchor{library/test test support requires_docstrings}@anchor{46e6}
@deffn {の関数} @@test.support.requires_docstrings

Decorator for only running the test if @ref{46b5,,HAVE_DOCSTRINGS}.
@end deffn

@geindex requires_limited_api() (test.support モジュール)
@anchor{library/test test support requires_limited_api}@anchor{46e7}
@deffn {の関数} @@test.support.requires_limited_api

Decorator for only running the test if @ref{637,,Limited C API}
is available.
@end deffn

@geindex cpython_only() (test.support モジュール)
@anchor{library/test test support cpython_only}@anchor{46e8}
@deffn {の関数} @@test.support.cpython_only

Decorator for tests only applicable to CPython.
@end deffn

@geindex impl_detail() (test.support モジュール)
@anchor{library/test test support impl_detail}@anchor{46e9}
@deffn {の関数} @@test.support.impl_detail (msg=None, **guards)

Decorator for invoking @ref{46c5,,check_impl_detail()} on `guards'.  If that
returns @code{False}, then uses `msg' as the reason for skipping the test.
@end deffn

@geindex thread_unsafe() (test.support モジュール)
@anchor{library/test test support thread_unsafe}@anchor{46ea}
@deffn {の関数} @@test.support.thread_unsafe (reason=None)

Decorator for marking tests as thread-unsafe.  This test always runs in one
thread even when invoked with @code{--parallel-threads}.
@end deffn

@geindex no_tracing() (test.support モジュール)
@anchor{library/test test support no_tracing}@anchor{46eb}
@deffn {の関数} @@test.support.no_tracing

Decorator to temporarily turn off tracing for the duration of the test.
@end deffn

@geindex refcount_test() (test.support モジュール)
@anchor{library/test test support refcount_test}@anchor{46ec}
@deffn {の関数} @@test.support.refcount_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.
@end deffn

@geindex bigmemtest() (test.support モジュール)
@anchor{library/test test support bigmemtest}@anchor{46ed}
@deffn {の関数} @@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 @code{@@bigmemtest(size=_4G, memuse=2)}.

The `size' argument is normally passed to the decorated test method as an
extra argument.  If `dry_run' is @code{True}, the value passed to the test
method may be less than the requested value.  If `dry_run' is @code{False}, it
means the test doesn't support dummy runs when @code{-M} is not specified.
@end deffn

@geindex bigaddrspacetest() (test.support モジュール)
@anchor{library/test test support bigaddrspacetest}@anchor{46ee}
@deffn {の関数} @@test.support.bigaddrspacetest

Decorator for tests that fill the address space.
@end deffn

@geindex linked_to_musl() (test.support モジュール)
@anchor{library/test test support linked_to_musl}@anchor{46ef}
@deffn {の関数} test.support.linked_to_musl ()

Return @code{False} if there is no evidence the interpreter was compiled with
@code{musl}, otherwise return a version triple, either @code{(0, 0, 0)} if the
version is unknown, or the actual version if it is known.  Intended for use
in @code{skip} decorators.  @code{emscripten} and @code{wasi} are assumed to be
compiled with @code{musl}; otherwise @code{platform.libc_ver} is checked.
@end deffn

@geindex check_syntax_error() (test.support モジュール)
@anchor{library/test test support check_syntax_error}@anchor{46f0}
@deffn {の関数} test.support.check_syntax_error (testcase, statement, errtext='@w{'}, *, lineno=None, offset=None)

Test for syntax errors in `statement' by attempting to compile `statement'.
`testcase' is the @ref{10c,,unittest} instance for the test.  `errtext' is the
regular expression which should match the string representation of the
raised @ref{18e,,SyntaxError}.  If `lineno' is not @code{None}, compares to
the line of the exception.  If `offset' is not @code{None}, compares to
the offset of the exception.
@end deffn

@geindex open_urlresource() (test.support モジュール)
@anchor{library/test test support open_urlresource}@anchor{46f1}
@deffn {の関数} test.support.open_urlresource (url, *args, **kw)

Open `url'.  If open fails, raises @ref{469d,,TestFailed}.
@end deffn

@geindex reap_children() (test.support モジュール)
@anchor{library/test test support reap_children}@anchor{46f2}
@deffn {の関数} test.support.reap_children ()

Use this at the end of @code{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.
@end deffn

@geindex get_attribute() (test.support モジュール)
@anchor{library/test test support get_attribute}@anchor{46f3}
@deffn {の関数} test.support.get_attribute (obj, name)

Get an attribute, raising @ref{11e6,,unittest.SkipTest} if @ref{5f0,,AttributeError}
is raised.
@end deffn

@geindex catch_unraisable_exception() (test.support モジュール)
@anchor{library/test test support catch_unraisable_exception}@anchor{1dbd}
@deffn {の関数} test.support.catch_unraisable_exception ()

Context manager catching unraisable exception using
@ref{507,,sys.unraisablehook()}.

Storing the exception value (@code{cm.unraisable.exc_value}) creates a
reference cycle. The reference cycle is broken explicitly when the context
manager exits.

Storing the object (@code{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.

使い方:

@example
with support.catch_unraisable_exception() as cm:
    # code creating an "unraisable exception"
    ...

    # check the unraisable exception: use cm.unraisable
    ...

# cm.unraisable attribute no longer exists at this point
# (to break a reference cycle)
@end example


Added in version 3.8.

@end deffn

@geindex load_package_tests() (test.support モジュール)
@anchor{library/test test support load_package_tests}@anchor{46f4}
@deffn {の関数} test.support.load_package_tests (pkg_dir, loader, standard_tests, pattern)

Generic implementation of the @ref{10c,,unittest} @code{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
@code{load_tests}.  In simple cases, the test package's @code{__init__.py}
can be the following:

@example
import os
from test.support import load_package_tests

def load_tests(*args):
    return load_package_tests(os.path.dirname(__file__), *args)
@end example
@end deffn

@geindex detect_api_mismatch() (test.support モジュール)
@anchor{library/test test support detect_api_mismatch}@anchor{46f5}
@deffn {の関数} 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 '__'.


Added in version 3.5.

@end deffn

@geindex patch() (test.support モジュール)
@anchor{library/test test support patch}@anchor{46f6}
@deffn {の関数} 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'.
@end deffn

@geindex run_in_subinterp() (test.support モジュール)
@anchor{library/test test support run_in_subinterp}@anchor{46f7}
@deffn {の関数} test.support.run_in_subinterp (code)

Run `code' in subinterpreter.  Raise @ref{11e6,,unittest.SkipTest} if
@ref{105,,tracemalloc} is enabled.
@end deffn

@geindex check_free_after_iterating() (test.support モジュール)
@anchor{library/test test support check_free_after_iterating}@anchor{46f8}
@deffn {の関数} test.support.check_free_after_iterating (test, iter, cls, args=())

Assert instances of `cls' are deallocated after iterating.
@end deffn

@geindex missing_compiler_executable() (test.support モジュール)
@anchor{library/test test support missing_compiler_executable}@anchor{46f9}
@deffn {の関数} 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 @code{None} when none is found
missing.
@end deffn

@geindex check__all__() (test.support モジュール)
@anchor{library/test test support check__all__}@anchor{1d33}
@deffn {の関数} test.support.check__all__ (test_case, module, name_of_module=None, extra=(), not_exported=())

Assert that the @code{__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 @code{csv} and its @code{_csv}).

The `extra' argument can be a set of names that wouldn't otherwise be automatically
detected as "public", like objects without a proper @ref{26d7,,__module__}
attribute. If provided, it will be added to the automatically detected ones.

The `not_exported' argument can be a set of names that must not be treated
as part of the public API even though their names indicate otherwise.

使用例:

@example
import bar
import foo
import unittest
from test import support

class MiscTestCase(unittest.TestCase):
    def test__all__(self):
        support.check__all__(self, foo)

class OtherTestCase(unittest.TestCase):
    def test__all__(self):
        extra = @{'BAR_CONST', 'FOO_CONST'@}
        not_exported = @{'baz'@}  # Undocumented name.
        # bar imports part of its API from _bar.
        support.check__all__(self, bar, ('bar', '_bar'),
                             extra=extra, not_exported=not_exported)
@end example


Added in version 3.6.

@end deffn

@geindex skip_if_broken_multiprocessing_synchronize() (test.support モジュール)
@anchor{library/test test support skip_if_broken_multiprocessing_synchronize}@anchor{1d34}
@deffn {の関数} test.support.skip_if_broken_multiprocessing_synchronize ()

Skip tests if the @code{multiprocessing.synchronize} module is missing, if
there is no available semaphore implementation, or if creating a lock raises
an @ref{2c0,,OSError}.


Added in version 3.10.

@end deffn

@geindex check_disallow_instantiation() (test.support モジュール)
@anchor{library/test test support check_disallow_instantiation}@anchor{46fa}
@deffn {の関数} test.support.check_disallow_instantiation (test_case, tp, *args, **kwds)

Assert that type `tp' cannot be instantiated using `args' and `kwds'.


Added in version 3.10.

@end deffn

@geindex adjust_int_max_str_digits() (test.support モジュール)
@anchor{library/test test support adjust_int_max_str_digits}@anchor{46fb}
@deffn {の関数} test.support.adjust_int_max_str_digits (max_digits)

This function returns a context manager that will change the global
@ref{18f1,,sys.set_int_max_str_digits()} setting for the duration of the
context to allow execution of test code that needs a different limit
on the number of digits when converting between an integer and string.


Added in version 3.11.

@end deffn

The @code{test.support} module defines the following classes:

@geindex SuppressCrashReport (test.support のクラス)
@anchor{library/test test support SuppressCrashReport}@anchor{46fc}
@deffn {クラス} 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@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx}.

On UNIX, @ref{17c6,,resource.setrlimit()} is used to set
@ref{46fd,,resource.RLIMIT_CORE}'s soft limit to 0 to prevent coredump file
creation.

On both platforms, the old value is restored by @ref{1518,,__exit__()}.
@end deffn

@geindex SaveSignals (test.support のクラス)
@anchor{library/test test support SaveSignals}@anchor{46fe}
@deffn {クラス} test.support.SaveSignals

Class to save and restore signal handlers registered by the Python signal
handler.

@geindex save() (test.support.SaveSignals のメソッド)
@anchor{library/test test support SaveSignals save}@anchor{46ff}
@deffn {メソッド} save (self)

Save the signal handlers to a dictionary mapping signal numbers to the
current signal handler.
@end deffn

@geindex restore() (test.support.SaveSignals のメソッド)
@anchor{library/test test support SaveSignals restore}@anchor{4700}
@deffn {メソッド} restore (self)

Set the signal numbers from the @ref{46ff,,save()} dictionary to the saved
handler.
@end deffn
@end deffn

@geindex Matcher (test.support のクラス)
@anchor{library/test test support Matcher}@anchor{4701}
@deffn {クラス} test.support.Matcher

@geindex matches() (test.support.Matcher のメソッド)
@anchor{library/test test support Matcher matches}@anchor{4702}
@deffn {メソッド} matches (self, d, **kwargs)

Try to match a single dict with the supplied arguments.
@end deffn

@geindex match_value() (test.support.Matcher のメソッド)
@anchor{library/test test support Matcher match_value}@anchor{4703}
@deffn {メソッド} match_value (self, k, dv, v)

Try to match a single stored value (`dv') with a supplied value (`v').
@end deffn
@end deffn

@node test support socket_helper --- Utilities for socket tests,test support script_helper --- Utilities for the Python execution tests,test support --- Utilities for the Python test suite,開発ツール
@anchor{library/test module-test support socket_helper}@anchor{ef}@anchor{library/test test-support-socket-helper-utilities-for-socket-tests}@anchor{4704}
@subsection @code{test.support.socket_helper} --- Utilities for socket tests


@geindex module; test.support.socket_helper

The @code{test.support.socket_helper} module provides support for socket tests.


Added in version 3.9.


@geindex IPV6_ENABLED (test.support.socket_helper モジュール)
@anchor{library/test test support socket_helper IPV6_ENABLED}@anchor{4705}
@deffn {データ} test.support.socket_helper.IPV6_ENABLED

Set to @code{True} if IPv6 is enabled on this host, @code{False} otherwise.
@end deffn

@geindex find_unused_port() (test.support.socket_helper モジュール)
@anchor{library/test test support socket_helper find_unused_port}@anchor{4706}
@deffn {の関数} 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 @code{sock} parameter (default is @ref{1bad,,AF_INET},
@ref{150b,,SOCK_STREAM}),
and binding it to the specified host address (defaults to @code{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 @ref{4707,,bind_port()} 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 @code{-accept} argument to
openssl's s_server mode).  Always prefer @ref{4707,,bind_port()} over
@ref{4706,,find_unused_port()} 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.
@end deffn

@geindex bind_port() (test.support.socket_helper モジュール)
@anchor{library/test test support socket_helper bind_port}@anchor{4707}
@deffn {の関数} 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
@code{sock.family} is @ref{1bad,,AF_INET} and @code{sock.type} is
@ref{150b,,SOCK_STREAM}, and the socket has
@code{SO_REUSEADDR} or @code{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 @code{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.
@end deffn

@geindex bind_unix_socket() (test.support.socket_helper モジュール)
@anchor{library/test test support socket_helper bind_unix_socket}@anchor{4708}
@deffn {の関数} test.support.socket_helper.bind_unix_socket (sock, addr)

Bind a Unix socket, raising @ref{11e6,,unittest.SkipTest} if
@ref{f3e,,PermissionError} is raised.
@end deffn

@geindex skip_unless_bind_unix_socket() (test.support.socket_helper モジュール)
@anchor{library/test test support socket_helper skip_unless_bind_unix_socket}@anchor{4709}
@deffn {の関数} @@test.support.socket_helper.skip_unless_bind_unix_socket

A decorator for running tests that require a functional @code{bind()} for Unix
sockets.
@end deffn

@geindex transient_internet() (test.support.socket_helper モジュール)
@anchor{library/test test support socket_helper transient_internet}@anchor{46a8}
@deffn {の関数} test.support.socket_helper.transient_internet (resource_name, *, timeout=30.0, errnos=())

A context manager that raises @ref{469e,,ResourceDenied} when
various issues with the internet connection manifest themselves as
exceptions.
@end deffn

@node test support script_helper --- Utilities for the Python execution tests,test support bytecode_helper --- Support tools for testing correct bytecode generation,test support socket_helper --- Utilities for socket tests,開発ツール
@anchor{library/test module-test support script_helper}@anchor{ee}@anchor{library/test test-support-script-helper-utilities-for-the-python-execution-tests}@anchor{470a}
@subsection @code{test.support.script_helper} --- Utilities for the Python execution tests


@geindex module; test.support.script_helper

The @code{test.support.script_helper} module provides support for Python's
script execution tests.

@geindex interpreter_requires_environment() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper interpreter_requires_environment}@anchor{470b}
@deffn {の関数} test.support.script_helper.interpreter_requires_environment ()

Return @code{True} if @code{sys.executable interpreter} requires environment
variables in order to be able to run at all.

This is designed to be used with @code{@@unittest.skipIf()} to annotate tests
that need to use an @code{assert_python*()} function to launch an isolated
mode (@code{-I}) or no environment mode (@code{-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 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} is one way to get most of the testsuite to run
in that situation.  
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} or 
@geindex PYTHONUSERSITE
@geindex 環境変数; PYTHONUSERSITE
@code{PYTHONUSERSITE} are
other common environment variables that might impact whether or not the
interpreter can start.
@end deffn

@geindex run_python_until_end() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper run_python_until_end}@anchor{470c}
@deffn {の関数} 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 @code{__isolated}, @code{__cleanenv},
@code{__cwd}, and @code{TERM}.


バージョン 3.9 で変更: The function no longer strips whitespaces from `stderr'.

@end deffn

@geindex assert_python_ok() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper assert_python_ok}@anchor{470d}
@deffn {の関数} test.support.script_helper.assert_python_ok (*args, **env_vars)

Assert that running the interpreter with `args' and optional environment
variables `env_vars' succeeds (@code{rc == 0}) and return a @code{(return code,
stdout, stderr)} tuple.

If the `__cleanenv' keyword-only parameter is set, `env_vars' is used as a fresh
environment.

Python is started in isolated mode (command line option @code{-I}),
except if the `__isolated' keyword-only parameter is set to @code{False}.


バージョン 3.9 で変更: The function no longer strips whitespaces from `stderr'.

@end deffn

@geindex assert_python_failure() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper assert_python_failure}@anchor{470e}
@deffn {の関数} test.support.script_helper.assert_python_failure (*args, **env_vars)

Assert that running the interpreter with `args' and optional environment
variables `env_vars' fails (@code{rc != 0}) and return a @code{(return code,
stdout, stderr)} tuple.

See @ref{470d,,assert_python_ok()} for more options.


バージョン 3.9 で変更: The function no longer strips whitespaces from `stderr'.

@end deffn

@geindex spawn_python() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper spawn_python}@anchor{470f}
@deffn {の関数} 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 @ref{4b7,,subprocess.Popen()}. Returns a
@ref{4b7,,subprocess.Popen} object.
@end deffn

@geindex kill_python() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper kill_python}@anchor{4710}
@deffn {の関数} test.support.script_helper.kill_python (p)

Run the given @ref{4b7,,subprocess.Popen} process until completion and return
stdout.
@end deffn

@geindex make_script() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper make_script}@anchor{4711}
@deffn {の関数} 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 @code{False}, append @code{.py} to the name.  Return the full
script path.
@end deffn

@geindex make_zip_script() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper make_zip_script}@anchor{4712}
@deffn {の関数} 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 @code{zip} which
contains the files in `script_name'. `name_in_zip' is the archive name.
Return a tuple containing @code{(full path, full path of archive name)}.
@end deffn

@geindex make_pkg() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper make_pkg}@anchor{4713}
@deffn {の関数} test.support.script_helper.make_pkg (pkg_dir, init_source='@w{'})

Create a directory named `pkg_dir' containing an @code{__init__} file with
`init_source' as its contents.
@end deffn

@geindex make_zip_pkg() (test.support.script_helper モジュール)
@anchor{library/test test support script_helper make_zip_pkg}@anchor{4714}
@deffn {の関数} 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 @code{__init__} file and a file `script_basename'
containing the `source'.  If `compiled' is @code{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.
@end deffn

@node test support bytecode_helper --- Support tools for testing correct bytecode generation,test support threading_helper --- Utilities for threading tests,test support script_helper --- Utilities for the Python execution tests,開発ツール
@anchor{library/test module-test support bytecode_helper}@anchor{eb}@anchor{library/test test-support-bytecode-helper-support-tools-for-testing-correct-bytecode-generation}@anchor{4715}
@subsection @code{test.support.bytecode_helper} --- Support tools for testing correct bytecode generation


@geindex module; test.support.bytecode_helper

The @code{test.support.bytecode_helper} module provides support for testing
and inspecting bytecode generation.


Added in version 3.9.


The module defines the following class:

@geindex BytecodeTestCase (test.support.bytecode_helper のクラス)
@anchor{library/test test support bytecode_helper BytecodeTestCase}@anchor{4716}
@deffn {クラス} test.support.bytecode_helper.BytecodeTestCase (unittest.TestCase)

This class has custom assertion methods for inspecting bytecode.
@end deffn

@geindex get_disassembly_as_string() (test.support.bytecode_helper.BytecodeTestCase のメソッド)
@anchor{library/test test support bytecode_helper BytecodeTestCase get_disassembly_as_string}@anchor{4717}
@deffn {メソッド} BytecodeTestCase.get_disassembly_as_string (co)

Return the disassembly of `co' as string.
@end deffn

@geindex assertInBytecode() (test.support.bytecode_helper.BytecodeTestCase のメソッド)
@anchor{library/test test support bytecode_helper BytecodeTestCase assertInBytecode}@anchor{4718}
@deffn {メソッド} BytecodeTestCase.assertInBytecode (x, opname, argval=_UNSPECIFIED)

Return instr if `opname' is found, otherwise throws @ref{8b8,,AssertionError}.
@end deffn

@geindex assertNotInBytecode() (test.support.bytecode_helper.BytecodeTestCase のメソッド)
@anchor{library/test test support bytecode_helper BytecodeTestCase assertNotInBytecode}@anchor{4719}
@deffn {メソッド} BytecodeTestCase.assertNotInBytecode (x, opname, argval=_UNSPECIFIED)

Throws @ref{8b8,,AssertionError} if `opname' is found.
@end deffn

@node test support threading_helper --- Utilities for threading tests,test support os_helper --- Utilities for os tests,test support bytecode_helper --- Support tools for testing correct bytecode generation,開発ツール
@anchor{library/test module-test support threading_helper}@anchor{f0}@anchor{library/test test-support-threading-helper-utilities-for-threading-tests}@anchor{471a}
@subsection @code{test.support.threading_helper} --- Utilities for threading tests


@geindex module; test.support.threading_helper

The @code{test.support.threading_helper} module provides support for threading tests.


Added in version 3.10.


@geindex join_thread() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper join_thread}@anchor{471b}
@deffn {の関数} test.support.threading_helper.join_thread (thread, timeout=None)

Join a `thread' within `timeout'.  Raise an @ref{8b8,,AssertionError} if thread
is still alive after `timeout' seconds.
@end deffn

@geindex reap_threads() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper reap_threads}@anchor{471c}
@deffn {の関数} @@test.support.threading_helper.reap_threads

Decorator to ensure the threads are cleaned up even if the test fails.
@end deffn

@geindex start_threads() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper start_threads}@anchor{471d}
@deffn {の関数} test.support.threading_helper.start_threads (threads, unlock=None)

Context manager to start `threads', which is a sequence of threads.
`unlock' is a function called after the threads are started, even if an
exception was raised; an example would be @ref{3636,,threading.Event.set()}.
@code{start_threads} will attempt to join the started threads upon exit.
@end deffn

@geindex threading_cleanup() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper threading_cleanup}@anchor{471e}
@deffn {の関数} test.support.threading_helper.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.
@end deffn

@geindex threading_setup() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper threading_setup}@anchor{471f}
@deffn {の関数} test.support.threading_helper.threading_setup ()

Return current thread count and copy of dangling threads.
@end deffn

@geindex wait_threads_exit() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper wait_threads_exit}@anchor{4720}
@deffn {の関数} test.support.threading_helper.wait_threads_exit (timeout=None)

Context manager to wait until all threads created in the @code{with} statement
exit.
@end deffn

@geindex catch_threading_exception() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper catch_threading_exception}@anchor{4721}
@deffn {の関数} test.support.threading_helper.catch_threading_exception ()

Context manager catching @ref{176,,threading.Thread} exception using
@ref{a4b,,threading.excepthook()}.

Attributes set when an exception is caught:


@itemize *

@item 
@code{exc_type}

@item 
@code{exc_value}

@item 
@code{exc_traceback}

@item 
@code{thread}
@end itemize

See @ref{a4b,,threading.excepthook()} documentation.

These attributes are deleted at the context manager exit.

使い方:

@example
with threading_helper.catch_threading_exception() as cm:
    # code spawning a thread which raises an exception
    ...

    # check the thread exception, use cm attributes:
    # exc_type, exc_value, exc_traceback, thread
    ...

# exc_type, exc_value, exc_traceback, thread attributes of cm no longer
# exists at this point
# (to avoid reference cycles)
@end example


Added in version 3.8.

@end deffn

@geindex run_concurrently() (test.support.threading_helper モジュール)
@anchor{library/test test support threading_helper run_concurrently}@anchor{4722}
@deffn {の関数} test.support.threading_helper.run_concurrently (worker_func, nthreads, args=(), kwargs=@{@})

Run the worker function concurrently in multiple threads.
Re-raises an exception if any thread raises one, after all threads have
finished.
@end deffn

@node test support os_helper --- Utilities for os tests,test support import_helper --- Utilities for import tests,test support threading_helper --- Utilities for threading tests,開発ツール
@anchor{library/test module-test support os_helper}@anchor{ed}@anchor{library/test test-support-os-helper-utilities-for-os-tests}@anchor{4723}
@subsection @code{test.support.os_helper} --- Utilities for os tests


@geindex module; test.support.os_helper

The @code{test.support.os_helper} module provides support for os tests.


Added in version 3.10.


@geindex FS_NONASCII (test.support.os_helper モジュール)
@anchor{library/test test support os_helper FS_NONASCII}@anchor{4724}
@deffn {データ} test.support.os_helper.FS_NONASCII

@ref{e4f,,os.fsencode()} でエンコードできる 非 ASCII 文字。
@end deffn

@geindex SAVEDCWD (test.support.os_helper モジュール)
@anchor{library/test test support os_helper SAVEDCWD}@anchor{4725}
@deffn {データ} test.support.os_helper.SAVEDCWD

@ref{1909,,os.getcwd()} に設定されます。
@end deffn

@geindex TESTFN (test.support.os_helper モジュール)
@anchor{library/test test support os_helper TESTFN}@anchor{4726}
@deffn {データ} test.support.os_helper.TESTFN

テンポラリファイルの名前として安全に利用できる名前に設定されます。作成した一時ファイルは全て閉じ、unlink (削除) しなければなりません。
@end deffn

@geindex TESTFN_NONASCII (test.support.os_helper モジュール)
@anchor{library/test test support os_helper TESTFN_NONASCII}@anchor{4727}
@deffn {データ} test.support.os_helper.TESTFN_NONASCII

Set to a filename containing the @ref{4724,,FS_NONASCII} character, if it exists.
This guarantees that if the filename exists, it can be encoded and decoded
with the default filesystem encoding. This allows tests that require a
non-ASCII filename to be easily skipped on platforms where they can't work.
@end deffn

@geindex TESTFN_UNENCODABLE (test.support.os_helper モジュール)
@anchor{library/test test support os_helper TESTFN_UNENCODABLE}@anchor{4728}
@deffn {データ} test.support.os_helper.TESTFN_UNENCODABLE

strictモードのファイルシステムエンコーディングでエンコードできないファイル名（str型）に設定します。そのようなファイル名を生成できない場合は、 @code{None} になる可能性があります。
@end deffn

@geindex TESTFN_UNDECODABLE (test.support.os_helper モジュール)
@anchor{library/test test support os_helper TESTFN_UNDECODABLE}@anchor{4729}
@deffn {データ} test.support.os_helper.TESTFN_UNDECODABLE

strictモードのファイルシステムエンコーディングでデコードできないファイル名（bytes型）に設定します。そのようなファイル名を生成できない場合は、 @code{None} になる可能性があります。
@end deffn

@geindex TESTFN_UNICODE (test.support.os_helper モジュール)
@anchor{library/test test support os_helper TESTFN_UNICODE}@anchor{472a}
@deffn {データ} test.support.os_helper.TESTFN_UNICODE

非 ASCII 名を一時ファイルに設定します。
@end deffn

@geindex EnvironmentVarGuard (test.support.os_helper のクラス)
@anchor{library/test test support os_helper EnvironmentVarGuard}@anchor{15fb}
@deffn {クラス} test.support.os_helper.EnvironmentVarGuard

一時的に環境変数をセット・アンセットするためのクラスです。このクラスのインスタンスはコンテキストマネージャーとして利用されます。また、 @code{os.environ} に対する参照・更新を行う完全な辞書のインターフェースを持ちます。コンテキストマネージャーが終了した時、このインスタンス経由で環境変数へ行った全ての変更はロールバックされます。


バージョン 3.1 で変更: 辞書のインターフェースを追加しました。

@end deffn

@geindex FakePath (test.support.os_helper のクラス)
@anchor{library/test test support os_helper FakePath}@anchor{472b}
@deffn {クラス} test.support.os_helper.FakePath (path)

Simple @ref{5a1,,path-like object}.  It implements the
@ref{e4c,,__fspath__()}
method which just returns the `path' argument.  If `path' is an exception,
it will be raised in @code{__fspath__()}.
@end deffn

@geindex set() (test.support.os_helper.EnvironmentVarGuard のメソッド)
@anchor{library/test test support os_helper EnvironmentVarGuard set}@anchor{472c}
@deffn {メソッド} EnvironmentVarGuard.set (envvar, value)

一時的に、 @code{envvar} を @code{value} にセットします。
@end deffn

@geindex unset() (test.support.os_helper.EnvironmentVarGuard のメソッド)
@anchor{library/test test support os_helper EnvironmentVarGuard unset}@anchor{1872}
@deffn {メソッド} EnvironmentVarGuard.unset (envvar, *others)

Temporarily unset one or more environment variables.


バージョン 3.14 で変更: More than one environment variable can be unset.

@end deffn

@geindex can_symlink() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper can_symlink}@anchor{472d}
@deffn {の関数} test.support.os_helper.can_symlink ()

OS がシンボリックリンクをサポートする場合 @code{True} を返し、その他の場合は @code{False} を返します。
@end deffn

@geindex can_xattr() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper can_xattr}@anchor{472e}
@deffn {の関数} test.support.os_helper.can_xattr ()

Return @code{True} if the OS supports xattr, @code{False}
otherwise.
@end deffn

@geindex change_cwd() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper change_cwd}@anchor{472f}
@deffn {の関数} test.support.os_helper.change_cwd (path, quiet=False)

カレントディレクトリを一時的に `path' に変更し与えるコンテキストマネージャです。

`quiet' が @code{False} の場合、コンテキストマネージャはエラーが起きると例外を送出します。
それ以外の場合には、警告を出すだけでカレントディレクトリは同じままにしておきます。
@end deffn

@geindex create_empty_file() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper create_empty_file}@anchor{4730}
@deffn {の関数} test.support.os_helper.create_empty_file (filename)

Create an empty file with `filename'.  If it already exists, truncate it.
@end deffn

@geindex fd_count() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper fd_count}@anchor{4731}
@deffn {の関数} test.support.os_helper.fd_count ()

Count the number of open file descriptors.
@end deffn

@geindex fs_is_case_insensitive() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper fs_is_case_insensitive}@anchor{4732}
@deffn {の関数} test.support.os_helper.fs_is_case_insensitive (directory)

Return @code{True} if the file system for `directory' is case-insensitive.
@end deffn

@geindex make_bad_fd() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper make_bad_fd}@anchor{4733}
@deffn {の関数} test.support.os_helper.make_bad_fd ()

一時ファイルを開いた後に閉じ、そのファイル記述子を返すことで無効な記述子を作成します。
@end deffn

@geindex rmdir() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper rmdir}@anchor{4734}
@deffn {の関数} test.support.os_helper.rmdir (filename)

Call @ref{130b,,os.rmdir()} on `filename'.  On Windows platforms, this is
wrapped with a wait loop that checks for the existence of the file,
which is needed due to antivirus programs that can hold files open and prevent
deletion.
@end deffn

@geindex rmtree() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper rmtree}@anchor{4735}
@deffn {の関数} test.support.os_helper.rmtree (path)

Call @ref{356,,shutil.rmtree()} on `path' or call @ref{6c8,,os.lstat()} and
@ref{130b,,os.rmdir()} to remove a path and its contents.  As with @ref{4734,,rmdir()},
on Windows platforms
this is wrapped with a wait loop that checks for the existence of the files.
@end deffn

@geindex skip_unless_symlink() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper skip_unless_symlink}@anchor{4736}
@deffn {の関数} @@test.support.os_helper.skip_unless_symlink

シンボリックリンクのサポートが必要なテストを実行することを表すデコレータ。
@end deffn

@geindex skip_unless_xattr() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper skip_unless_xattr}@anchor{4737}
@deffn {の関数} @@test.support.os_helper.skip_unless_xattr

A decorator for running tests that require support for xattr.
@end deffn

@geindex temp_cwd() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper temp_cwd}@anchor{4738}
@deffn {の関数} test.support.os_helper.temp_cwd (name='tempcwd', quiet=False)

一時的に新しいディレクトリを作成し、カレントディレクトリ (current working directory, CWD) を変更するコンテキストマネージャです。

一時的にカレントディレクトリを変更する前に、カレントディレクトリに `name' という名前のディレクトリを作成します。
`name' が @code{None} の場合は、一時ディレクトリは @ref{52d,,tempfile.mkdtemp()} を使って作成されます。

`quiet' が @code{False} でカレントディレクトリの作成や変更ができない場合、例外を送出します。
それ以外の場合には、警告を出すだけで元のカレントディレクトリが使われます。
@end deffn

@geindex temp_dir() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper temp_dir}@anchor{4739}
@deffn {の関数} test.support.os_helper.temp_dir (path=None, quiet=False)

`path' に一時ディレクトリを作成し与えるコンテキストマネージャです。

If `path' is @code{None}, the temporary directory is created using
@ref{52d,,tempfile.mkdtemp()}.  If `quiet' is @code{False}, the context manager
raises an exception on error.  Otherwise, if `path' is specified and
cannot be created, only a warning is issued.
@end deffn

@geindex temp_umask() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper temp_umask}@anchor{473a}
@deffn {の関数} test.support.os_helper.temp_umask (umask)

一時的にプロセスの umask を設定するコンテキストマネージャ。
@end deffn

@geindex unlink() (test.support.os_helper モジュール)
@anchor{library/test test support os_helper unlink}@anchor{473b}
@deffn {の関数} test.support.os_helper.unlink (filename)

Call @ref{130d,,os.unlink()} on `filename'.  As with @ref{4734,,rmdir()},
on Windows platforms, this is
wrapped with a wait loop that checks for the existence of the file.
@end deffn

@node test support import_helper --- Utilities for import tests,test support warnings_helper --- Utilities for warnings tests,test support os_helper --- Utilities for os tests,開発ツール
@anchor{library/test module-test support import_helper}@anchor{ec}@anchor{library/test test-support-import-helper-utilities-for-import-tests}@anchor{473c}
@subsection @code{test.support.import_helper} --- Utilities for import tests


@geindex module; test.support.import_helper

The @code{test.support.import_helper} module provides support for import tests.


Added in version 3.10.


@geindex forget() (test.support.import_helper モジュール)
@anchor{library/test test support import_helper forget}@anchor{473d}
@deffn {の関数} test.support.import_helper.forget (module_name)

モジュール名 `module_name' を @code{sys.modules} から取り除き、モジュールのバイトコンパイル済みファイルを全て削除します。
@end deffn

@geindex import_fresh_module() (test.support.import_helper モジュール)
@anchor{library/test test support import_helper import_fresh_module}@anchor{1c62}
@deffn {の関数} test.support.import_helper.import_fresh_module (name, fresh=(), blocked=(), deprecated=False)

この関数は、 `name' で指定された Python モジュールを、インポート前に @code{sys.modules} から削除することで新規にインポートしてそのコピーを返します。 @code{reload()} 関数と違い、もとのモジュールはこの操作によって影響をうけません。

`fresh' は、同じようにインポート前に @code{sys.modules} から削除されるモジュール名の iterable です。

`blocked' もモジュール名のイテラブルで、インポート中にモジュールキャッシュ内でその名前を @code{None} に置き換えることで、そのモジュールをインポートしようとすると @ref{65b,,ImportError} を発生させます。

指定されたモジュールと `fresh' や `blocked' 引数内のモジュール名はインポート前に保存され、フレッシュなインポートが完了したら @code{sys.modules} に戻されます。

`deprecated' が @code{True} の場合、インポート中はモジュールとパッケージの廃止メッセージが抑制されます。

指定したモジュールがインポートできなかった場合に、この関数は @ref{65b,,ImportError} を送出します。

使用例:

@example
# Get copies of the warnings module for testing without affecting the
# version being used by the rest of the test suite. One copy uses the
# C implementation, the other is forced to use the pure Python fallback
# implementation
py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
@end example


Added in version 3.1.

@end deffn

@geindex import_module() (test.support.import_helper モジュール)
@anchor{library/test test support import_helper import_module}@anchor{473e}
@deffn {の関数} test.support.import_helper.import_module (name, deprecated=False, *, required_on=())

この関数は `name' で指定されたモジュールをインポートして返します。通常のインポートと異なり、この関数はモジュールをインポートできなかった場合に @ref{11e6,,unittest.SkipTest} 例外を発生させます。

Module and package deprecation messages are suppressed during this import
if `deprecated' is @code{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 @ref{291,,sys.platform}.


Added in version 3.1.

@end deffn

@geindex modules_setup() (test.support.import_helper モジュール)
@anchor{library/test test support import_helper modules_setup}@anchor{473f}
@deffn {の関数} test.support.import_helper.modules_setup ()

Return a copy of @ref{17e6,,sys.modules}.
@end deffn

@geindex modules_cleanup() (test.support.import_helper モジュール)
@anchor{library/test test support import_helper modules_cleanup}@anchor{4740}
@deffn {の関数} test.support.import_helper.modules_cleanup (oldmodules)

Remove modules except for `oldmodules' and @code{encodings} in order to
preserve internal cache.
@end deffn

@geindex unload() (test.support.import_helper モジュール)
@anchor{library/test test support import_helper unload}@anchor{4741}
@deffn {の関数} test.support.import_helper.unload (name)

@code{sys.modules} から `name' を削除します。
@end deffn

@geindex make_legacy_pyc() (test.support.import_helper モジュール)
@anchor{library/test test support import_helper make_legacy_pyc}@anchor{4742}
@deffn {の関数} test.support.import_helper.make_legacy_pyc (source)

Move a 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/}/
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} 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.
@end deffn

@geindex CleanImport (test.support.import_helper のクラス)
@anchor{library/test test support import_helper CleanImport}@anchor{4743}
@deffn {クラス} test.support.import_helper.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
@ref{1a3,,DeprecationWarning} on import.  Example usage:

@example
with CleanImport('foo'):
    importlib.import_module('foo')  # New reference.
@end example
@end deffn

@geindex DirsOnSysPath (test.support.import_helper のクラス)
@anchor{library/test test support import_helper DirsOnSysPath}@anchor{4744}
@deffn {クラス} test.support.import_helper.DirsOnSysPath (*paths)

A context manager to temporarily add directories to @ref{3e4,,sys.path}.

This makes a copy of @ref{3e4,,sys.path}, appends any directories given
as positional arguments, then reverts @ref{3e4,,sys.path} to the copied
settings when the context ends.

Note that `all' @ref{3e4,,sys.path} modifications in the body of the
context manager, including replacement of the object,
will be reverted at the end of the block.
@end deffn

@node test support warnings_helper --- Utilities for warnings tests,,test support import_helper --- Utilities for import tests,開発ツール
@anchor{library/test module-test support warnings_helper}@anchor{f1}@anchor{library/test test-support-warnings-helper-utilities-for-warnings-tests}@anchor{4745}
@subsection @code{test.support.warnings_helper} --- Utilities for warnings tests


@geindex module; test.support.warnings_helper

The @code{test.support.warnings_helper} module provides support for warnings tests.


Added in version 3.10.


@geindex ignore_warnings() (test.support.warnings_helper モジュール)
@anchor{library/test test support warnings_helper ignore_warnings}@anchor{4746}
@deffn {の関数} test.support.warnings_helper.ignore_warnings (*, category)

Suppress warnings that are instances of `category',
which must be @ref{2712,,Warning} or a subclass.
Roughly equivalent to @ref{179,,warnings.catch_warnings()}
with @ref{8d0,,warnings.simplefilter('ignore'@comma{} category=category)}.
For example:

@example
@@warning_helper.ignore_warnings(category=DeprecationWarning)
def test_suppress_warning():
    # do something
@end example


Added in version 3.8.

@end deffn

@geindex check_no_resource_warning() (test.support.warnings_helper モジュール)
@anchor{library/test test support warnings_helper check_no_resource_warning}@anchor{4747}
@deffn {の関数} test.support.warnings_helper.check_no_resource_warning (testcase)

Context manager to check that no @ref{54c,,ResourceWarning} was raised.  You
must remove the object which may emit @ref{54c,,ResourceWarning} before the
end of the context manager.
@end deffn

@geindex check_syntax_warning() (test.support.warnings_helper モジュール)
@anchor{library/test test support warnings_helper check_syntax_warning}@anchor{4748}
@deffn {の関数} test.support.warnings_helper.check_syntax_warning (testcase, statement, errtext='@w{'}, *, lineno=1, offset=None)

Test for syntax warning in `statement' by attempting to compile `statement'.
Test also that the @ref{1ae,,SyntaxWarning} is emitted only once, and that it
will be converted to a @ref{18e,,SyntaxError} when turned into error.
`testcase' is the @ref{10c,,unittest} instance for the test.  `errtext' is the
regular expression which should match the string representation of the
emitted @ref{1ae,,SyntaxWarning} and raised @ref{18e,,SyntaxError}.  If `lineno'
is not @code{None}, compares to the line of the warning and exception.
If `offset' is not @code{None}, compares to the offset of the exception.


Added in version 3.8.

@end deffn

@geindex check_warnings() (test.support.warnings_helper モジュール)
@anchor{library/test test support warnings_helper check_warnings}@anchor{4749}
@deffn {の関数} test.support.warnings_helper.check_warnings (*filters, quiet=True)

A convenience wrapper for @ref{179,,warnings.catch_warnings()} that makes it
easier to test that a warning was correctly raised.  It is approximately
equivalent to calling @code{warnings.catch_warnings(record=True)} with
@ref{8d0,,warnings.simplefilter()} set to @code{always} and with the option to
automatically validate the results that are recorded.

@code{check_warnings} は @code{("message regexp", WarningCategory)} の形をした 2要素タプルを位置引数として受け取ります。1つ以上の `filters' が与えられた場合や、オプションのキーワード引数 `quiet' が @code{False} の場合、警告が期待通りであるかどうかをチェックします。指定された各 filter は最低でも1回は囲われたコード内で発生した警告とマッチしなければテストが失敗しますし、指定されたどの filter ともマッチしない警告が発生してもテストが失敗します。前者のチェックを無効にするには、`quiet' を @code{True} にします。

引数が1つもない場合、デフォルトでは次のようになります:

@example
check_warnings(("", Warning), quiet=True)
@end example

この場合、全ての警告は補足され、エラーは発生しません。

コンテキストマネージャーに入る時、 @code{WarningRecorder} インスタンスが返されます。このレコーダーオブジェクトの @ref{118,,warnings} 属性から、 @ref{179,,catch_warnings()} から得られる警告のリストを取得することができます。便利さのために、レコーダーオブジェクトから直接、一番最近に発生した警告を表すオブジェクトの属性にアクセスできます(以下にある例を参照してください)。警告が1つも発生しなかった場合、それらの全ての属性は @code{None} を返します。

レコーダーオブジェクトの @code{reset()} メソッドは警告リストをクリアします。

コンテキストマネージャーは次のようにして使います:

@example
with check_warnings(("assertion is always true", SyntaxWarning),
                    ("", UserWarning)):
    exec('assert(False, "Hey!")')
    warnings.warn(UserWarning("Hide me!"))
@end example

この場合、どちらの警告も発生しなかった場合や、それ以外の警告が発生した場合は、 @ref{4749,,check_warnings()} はエラーを発生させます。

警告が発生したかどうかだけでなく、もっと詳しいチェックが必要な場合は、次のようなコードになります:

@example
with check_warnings(quiet=True) as w:
    warnings.warn("foo")
    assert str(w.args[0]) == "foo"
    warnings.warn("bar")
    assert str(w.args[0]) == "bar"
    assert str(w.warnings[0].args[0]) == "foo"
    assert str(w.warnings[1].args[0]) == "bar"
    w.reset()
    assert len(w.warnings) == 0
@end example

全ての警告をキャプチャし、テストコードがその警告を直接テストします。


バージョン 3.2 で変更: 新しいオプション引数 `filters' と `quiet'

@end deffn

@geindex WarningsRecorder (test.support.warnings_helper のクラス)
@anchor{library/test test support warnings_helper WarningsRecorder}@anchor{474a}
@deffn {クラス} test.support.warnings_helper.WarningsRecorder

ユニットテスト時に warning を記録するためのクラスです。上の、 @ref{4749,,check_warnings()} のドキュメントを参照してください。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node デバッグとプロファイル,ソフトウェア・パッケージと配布,開発ツール,Python 標準ライブラリ
@anchor{library/debug doc}@anchor{474b}@anchor{library/debug debugging-and-profiling}@anchor{474c}@anchor{library/debug translation-repo}@anchor{474d}
@section デバッグとプロファイル


ここに含まれるライブラリは Python での開発を手助けするものです。デバッガを使うと、コードのステップ実行や、スタックフレームの解析、ブレークポイントの設定などができます。プロファイラはコードを実行して実行時間の詳細を提供し、プログラムのボトルネックを特定できるようにします。

@geindex 監査イベント
@anchor{library/audit_events audit-events}@anchor{1c13}
@menu
* 監査イベント表:: 
* bdb: bdb --- デバッガーフレームワーク. デバッガーフレームワーク
* faulthandler: faulthandler --- Python トレースバックをダンプする. Python トレースバックをダンプする
* pdb: pdb --- The Python Debugger. The Python Debugger
* Python プロファイラ:: 
* timeit: timeit --- 小さなコードスニペットの実行時間計測. 小さなコードスニペットの実行時間計測
* trace: trace --- Python 文実行のトレースと追跡. Python 文実行のトレースと追跡
* tracemalloc: tracemalloc --- メモリ割り当ての追跡. メモリ割り当ての追跡

@end menu

@node 監査イベント表,bdb --- デバッガーフレームワーク,,デバッグとプロファイル
@anchor{library/audit_events doc}@anchor{474e}@anchor{library/audit_events audit-events-table}@anchor{474f}
@subsection 監査イベント表


この表は、 CPython ランタイムと標準ライブラリ全体で @ref{191b,,sys.audit()} または @ref{613,,PySys_Audit()} の呼び出しによって送出されるすべてのイベントを含んでいます。これらの呼び出しは、 3.8 以降に追加されました (
@geindex Python Enhancement Proposals; PEP 578
PEP 578@footnote{https://peps.python.org/pep-0578/} を参照) 。

これらのイベントの処理についての情報は @ref{4750,,sys.addaudithook()} と @ref{4751,,PySys_AddAuditHook()} を参照してください。

この表は CPython ドキュメントから生成されており、他の実装により送出されるイベントを表示していない可能性があります。実際に送出されるイベントは、ランタイム固有のドキュメントを参照してください。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

Audit event

@tab

Arguments

@tab

References

@item

_thread.start_new_thread

@tab

@code{function}, @code{args}, @code{kwargs}

@tab

@ref{4752,,[1]}

@item

array.__new__

@tab

@code{typecode}, @code{initializer}

@tab

@ref{4be,,[1]}

@item

builtins.breakpoint

@tab

@code{breakpointhook}

@tab

@ref{271,,[1]}

@item

builtins.id

@tab

@code{id}

@tab

@ref{163c,,[1]}

@item

builtins.input

@tab

@code{prompt}

@tab

@ref{14f0,,[1]}

@item

builtins.input/result

@tab

@code{result}

@tab

@ref{14f0,,[1]}

@item

code.__new__

@tab

@code{code}, @code{filename}, @code{name}, @code{argcount}, @code{posonlyargcount}, @code{kwonlyargcount}, @code{nlocals}, @code{stacksize}, @code{flags}

@tab

@ref{32f,,[1]}

@item

compile

@tab

@code{source}, @code{filename}

@tab

@ref{4b1,,[1]}

@item

cpython.PyConfig_Set

@tab

@code{name}, @code{value}

@tab

@ref{37d,,[1]}

@item

cpython.PyInterpreterState_Clear

@tab



@tab

@ref{4753,,[1]}

@item

cpython.PyInterpreterState_New

@tab



@tab

@ref{4754,,[1]}

@item

cpython._PySys_ClearAuditHooks

@tab



@tab

@ref{f11,,[1]}

@item

cpython.remote_debugger_script

@tab

@code{script_path}

@tab

@ref{4755,,[1]}

@item

cpython.run_command

@tab

@code{command}

@tab

@ref{1a8,,[1]}

@item

cpython.run_file

@tab

@code{filename}

@tab

@ref{4756,,[1]}

@item

cpython.run_interactivehook

@tab

@code{hook}

@tab

@ref{11ca,,[1]}

@item

cpython.run_module

@tab

@code{module-name}

@tab

@ref{23c,,[1]}

@item

cpython.run_startup

@tab

@code{filename}

@tab

@ref{1b8,,[1]}

@item

cpython.run_stdin

@tab



@tab

@ref{4757,,[1]}@ref{4758,,[2]}@ref{4759,,[3]}

@item

ctypes.addressof

@tab

@code{obj}

@tab

@ref{3335,,[1]}

@item

ctypes.call_function

@tab

@code{func_pointer}, @code{arguments}

@tab

@ref{332f,,[1]}

@item

ctypes.cdata

@tab

@code{address}

@tab

@ref{3340,,[1]}

@item

ctypes.cdata/buffer

@tab

@code{pointer}, @code{size}, @code{offset}

@tab

@ref{3345,,[1]}@ref{3346,,[2]}

@item

ctypes.create_string_buffer

@tab

@code{init}, @code{size}

@tab

@ref{32ed,,[1]}

@item

ctypes.create_unicode_buffer

@tab

@code{init}, @code{size}

@tab

@ref{1db4,,[1]}

@item

ctypes.dlopen

@tab

@code{name}

@tab

@ref{332d,,[1]}

@item

ctypes.dlsym

@tab

@code{library}, @code{name}

@tab

@ref{332d,,[1]}

@item

ctypes.dlsym/handle

@tab

@code{handle}, @code{name}

@tab

@ref{332d,,[1]}

@item

ctypes.get_errno

@tab



@tab

@ref{3327,,[1]}

@item

ctypes.get_last_error

@tab



@tab

@ref{3329,,[1]}

@item

ctypes.memoryview_at

@tab

@code{address}, @code{size}, @code{readonly}

@tab

@ref{475a,,[1]}

@item

ctypes.set_errno

@tab

@code{errno}

@tab

@ref{3328,,[1]}

@item

ctypes.set_exception

@tab

@code{code}

@tab

@ref{332f,,[1]}

@item

ctypes.set_last_error

@tab

@code{error}

@tab

@ref{332a,,[1]}

@item

ctypes.string_at

@tab

@code{ptr}, @code{size}

@tab

@ref{1ec,,[1]}

@item

ctypes.wstring_at

@tab

@code{ptr}, @code{size}

@tab

@ref{333f,,[1]}

@item

ensurepip.bootstrap

@tab

@code{root}

@tab

@ref{475b,,[1]}

@item

exec

@tab

@code{code_object}

@tab

@ref{4a3,,[1]}@ref{4a2,,[2]}

@item

fcntl.fcntl

@tab

@code{fd}, @code{cmd}, @code{arg}

@tab

@ref{1851,,[1]}

@item

fcntl.flock

@tab

@code{fd}, @code{operation}

@tab

@ref{475c,,[1]}

@item

fcntl.ioctl

@tab

@code{fd}, @code{request}, @code{arg}

@tab

@ref{1694,,[1]}

@item

fcntl.lockf

@tab

@code{fd}, @code{cmd}, @code{len}, @code{start}, @code{whence}

@tab

@ref{1605,,[1]}

@item

ftplib.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{3ffc,,[1]}

@item

ftplib.sendcmd

@tab

@code{self}, @code{cmd}

@tab

@ref{4001,,[1]}@ref{4002,,[2]}

@item

function.__new__

@tab

@code{code}

@tab

@ref{a83,,[1]}

@item

gc.get_objects

@tab

@code{generation}

@tab

@ref{a04,,[1]}

@item

gc.get_referents

@tab

@code{objs}

@tab

@ref{a06,,[1]}

@item

gc.get_referrers

@tab

@code{objs}

@tab

@ref{a05,,[1]}

@item

glob.glob

@tab

@code{pathname}, @code{recursive}

@tab

@ref{5a0,,[1]}@ref{a08,,[2]}

@item

glob.glob/2

@tab

@code{pathname}, @code{recursive}, @code{root_dir}, @code{dir_fd}

@tab

@ref{5a0,,[1]}@ref{a08,,[2]}

@item

http.client.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{3fdf,,[1]}

@item

http.client.send

@tab

@code{self}, @code{data}

@tab

@ref{3fe3,,[1]}

@item

imaplib.open

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{b01,,[1]}

@item

imaplib.send

@tab

@code{self}, @code{data}

@tab

@ref{4054,,[1]}

@item

import

@tab

@code{module}, @code{filename}, @code{sys.path}, @code{sys.meta_path}, @code{sys.path_hooks}

@tab

@ref{7f8,,[1]}

@item

marshal.dumps

@tab

@code{value}, @code{version}

@tab

@ref{2d43,,[1]}

@item

marshal.load

@tab



@tab

@ref{1df6,,[1]}

@item

marshal.loads

@tab

@code{bytes}

@tab

@ref{1df6,,[1]}

@item

mmap.__new__

@tab

@code{fileno}, @code{length}, @code{access}, @code{offset}

@tab

@ref{519,,[1]}

@item

msvcrt.get_osfhandle

@tab

@code{fd}

@tab

@ref{475d,,[1]}

@item

msvcrt.locking

@tab

@code{fd}, @code{mode}, @code{nbytes}

@tab

@ref{475e,,[1]}

@item

msvcrt.open_osfhandle

@tab

@code{handle}, @code{flags}

@tab

@ref{475f,,[1]}

@item

object.__delattr__

@tab

@code{obj}, @code{name}

@tab

@ref{237d,,[1]}

@item

object.__getattr__

@tab

@code{obj}, @code{name}

@tab

@ref{dcb,,[1]}

@item

object.__setattr__

@tab

@code{obj}, @code{name}, @code{value}

@tab

@ref{237c,,[1]}

@item

open

@tab

@code{path}, @code{mode}, @code{flags}

@tab

@ref{316,,[1]}@ref{740,,[2]}@ref{f92,,[3]}

@item

os.add_dll_directory

@tab

@code{path}

@tab

@ref{bdd,,[1]}

@item

os.chdir

@tab

@code{path}

@tab

@ref{821,,[1]}@ref{f89,,[2]}

@item

os.chflags

@tab

@code{path}, @code{flags}

@tab

@ref{1305,,[1]}@ref{307a,,[2]}

@item

os.chmod

@tab

@code{path}, @code{mode}, @code{dir_fd}

@tab

@ref{529,,[1]}@ref{52a,,[2]}@ref{528,,[3]}

@item

os.chown

@tab

@code{path}, @code{uid}, @code{gid}, @code{dir_fd}

@tab

@ref{1306,,[1]}@ref{f8a,,[2]}@ref{307b,,[3]}

@item

os.exec

@tab

@code{path}, @code{args}, @code{env}

@tab

@ref{30b4,,[1]}

@item

os.fork

@tab



@tab

@ref{4b5,,[1]}

@item

os.forkpty

@tab



@tab

@ref{4b6,,[1]}

@item

os.fwalk

@tab

@code{top}, @code{topdown}, @code{onerror}, @code{follow_symlinks}, @code{dir_fd}

@tab

@ref{d52,,[1]}

@item

os.getxattr

@tab

@code{path}, @code{attribute}

@tab

@ref{131c,,[1]}

@item

os.kill

@tab

@code{pid}, @code{sig}

@tab

@ref{157f,,[1]}

@item

os.killpg

@tab

@code{pgid}, @code{sig}

@tab

@ref{1dbb,,[1]}

@item

os.link

@tab

@code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd}

@tab

@ref{1307,,[1]}

@item

os.listdir

@tab

@code{path}

@tab

@ref{1312,,[1]}

@item

os.listdrives

@tab



@tab

@ref{6c5,,[1]}

@item

os.listmounts

@tab

@code{volume}

@tab

@ref{6c7,,[1]}

@item

os.listvolumes

@tab



@tab

@ref{6c6,,[1]}

@item

os.listxattr

@tab

@code{path}

@tab

@ref{131d,,[1]}

@item

os.lockf

@tab

@code{fd}, @code{cmd}, @code{len}

@tab

@ref{132b,,[1]}

@item

os.mkdir

@tab

@code{path}, @code{mode}, @code{dir_fd}

@tab

@ref{52c,,[1]}@ref{52b,,[2]}

@item

os.posix_spawn

@tab

@code{path}, @code{argv}, @code{env}

@tab

@ref{52e,,[1]}@ref{1e11,,[2]}

@item

os.putenv

@tab

@code{key}, @code{value}

@tab

@ref{25b,,[1]}

@item

os.remove

@tab

@code{path}, @code{dir_fd}

@tab

@ref{1308,,[1]}@ref{307f,,[2]}@ref{130d,,[3]}

@item

os.removexattr

@tab

@code{path}, @code{attribute}

@tab

@ref{131e,,[1]}

@item

os.rename

@tab

@code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd}

@tab

@ref{1309,,[1]}@ref{3080,,[2]}@ref{130a,,[3]}

@item

os.rmdir

@tab

@code{path}, @code{dir_fd}

@tab

@ref{130b,,[1]}

@item

os.scandir

@tab

@code{path}

@tab

@ref{c54,,[1]}

@item

os.setxattr

@tab

@code{path}, @code{attribute}, @code{value}, @code{flags}

@tab

@ref{131f,,[1]}

@item

os.spawn

@tab

@code{mode}, @code{path}, @code{args}, @code{env}

@tab

@ref{31b,,[1]}

@item

os.startfile

@tab

@code{path}, @code{operation}

@tab

@ref{1c83,,[1]}

@item

os.startfile/2

@tab

@code{path}, @code{operation}, @code{arguments}, @code{cwd}, @code{show_cmd}

@tab

@ref{1c83,,[1]}

@item

os.symlink

@tab

@code{src}, @code{dst}, @code{dir_fd}

@tab

@ref{130c,,[1]}

@item

os.system

@tab

@code{command}

@tab

@ref{1676,,[1]}

@item

os.truncate

@tab

@code{fd}, @code{length}

@tab

@ref{f8f,,[1]}@ref{103c,,[2]}

@item

os.unsetenv

@tab

@code{key}

@tab

@ref{25c,,[1]}

@item

os.utime

@tab

@code{path}, @code{times}, @code{ns}, @code{dir_fd}

@tab

@ref{130e,,[1]}

@item

os.walk

@tab

@code{top}, @code{topdown}, @code{onerror}, @code{followlinks}

@tab

@ref{6d0,,[1]}

@item

pathlib.Path.glob

@tab

@code{self}, @code{pattern}

@tab

@ref{537,,[1]}

@item

pathlib.Path.rglob

@tab

@code{self}, @code{pattern}

@tab

@ref{538,,[1]}

@item

pdb.Pdb

@tab



@tab

@ref{273,,[1]}

@item

pickle.find_class

@tab

@code{module}, @code{name}

@tab

@ref{2d19,,[1]}

@item

poplib.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{b1d,,[1]}@ref{b1e,,[2]}

@item

poplib.putline

@tab

@code{self}, @code{line}

@tab

@ref{b1d,,[1]}@ref{b1e,,[2]}

@item

pty.spawn

@tab

@code{argv}

@tab

@ref{1184,,[1]}

@item

resource.prlimit

@tab

@code{pid}, @code{resource}, @code{limits}

@tab

@ref{118c,,[1]}

@item

resource.setrlimit

@tab

@code{resource}, @code{limits}

@tab

@ref{17c6,,[1]}

@item

setopencodehook

@tab



@tab

@ref{1a9a,,[1]}

@item

shutil.chown

@tab

@code{path}, @code{user}, @code{group}

@tab

@ref{548,,[1]}

@item

shutil.copyfile

@tab

@code{src}, @code{dst}

@tab

@ref{c4f,,[1]}@ref{c50,,[2]}@ref{c4e,,[3]}

@item

shutil.copymode

@tab

@code{src}, @code{dst}

@tab

@ref{c4f,,[1]}@ref{1a24,,[2]}

@item

shutil.copystat

@tab

@code{src}, @code{dst}

@tab

@ref{c50,,[1]}@ref{1346,,[2]}

@item

shutil.copytree

@tab

@code{src}, @code{dst}

@tab

@ref{c1e,,[1]}

@item

shutil.make_archive

@tab

@code{base_name}, @code{format}, @code{root_dir}, @code{base_dir}

@tab

@ref{6da,,[1]}

@item

shutil.move

@tab

@code{src}, @code{dst}

@tab

@ref{c51,,[1]}

@item

shutil.rmtree

@tab

@code{path}, @code{dir_fd}

@tab

@ref{356,,[1]}

@item

shutil.unpack_archive

@tab

@code{filename}, @code{extract_dir}, @code{format}

@tab

@ref{696,,[1]}

@item

signal.pthread_kill

@tab

@code{thread_id}, @code{signalnum}

@tab

@ref{1349,,[1]}

@item

smtplib.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{1daf,,[1]}

@item

smtplib.send

@tab

@code{self}, @code{data}

@tab

@ref{b27,,[1]}

@item

socket.__new__

@tab

@code{self}, @code{family}, @code{type}, @code{protocol}

@tab

@ref{fa1,,[1]}

@item

socket.bind

@tab

@code{self}, @code{address}

@tab

@ref{12d7,,[1]}

@item

socket.connect

@tab

@code{self}, @code{address}

@tab

@ref{fa3,,[1]}@ref{1753,,[2]}

@item

socket.getaddrinfo

@tab

@code{host}, @code{port}, @code{family}, @code{type}, @code{protocol}

@tab

@ref{1ac3,,[1]}

@item

socket.gethostbyaddr

@tab

@code{ip_address}

@tab

@ref{1c84,,[1]}

@item

socket.gethostbyname

@tab

@code{hostname}

@tab

@ref{3996,,[1]}@ref{1c85,,[2]}

@item

socket.gethostname

@tab



@tab

@ref{3026,,[1]}

@item

socket.getnameinfo

@tab

@code{sockaddr}

@tab

@ref{1a3a,,[1]}

@item

socket.getservbyname

@tab

@code{servicename}, @code{protocolname}

@tab

@ref{3998,,[1]}

@item

socket.getservbyport

@tab

@code{port}, @code{protocolname}

@tab

@ref{3999,,[1]}

@item

socket.sendmsg

@tab

@code{self}, @code{address}

@tab

@ref{6a1,,[1]}

@item

socket.sendto

@tab

@code{self}, @code{address}

@tab

@ref{fa9,,[1]}

@item

socket.sethostname

@tab

@code{name}

@tab

@ref{1353,,[1]}

@item

sqlite3.connect

@tab

@code{database}

@tab

@ref{5a6,,[1]}

@item

sqlite3.connect/handle

@tab

@code{connection_handle}

@tab

@ref{5a6,,[1]}

@item

sqlite3.enable_load_extension

@tab

@code{connection}, @code{enabled}

@tab

@ref{a3f,,[1]}

@item

sqlite3.load_extension

@tab

@code{connection}, @code{path}

@tab

@ref{6df,,[1]}

@item

subprocess.Popen

@tab

@code{executable}, @code{args}, @code{cwd}, @code{env}

@tab

@ref{4b7,,[1]}

@item

sys._current_exceptions

@tab



@tab

@ref{6e9,,[1]}

@item

sys._current_frames

@tab



@tab

@ref{164c,,[1]}

@item

sys._getframe

@tab

@code{frame}

@tab

@ref{8f0,,[1]}

@item

sys._getframemodulename

@tab

@code{depth}

@tab

@ref{1adf,,[1]}

@item

sys.addaudithook

@tab



@tab

@ref{4751,,[1]}@ref{4750,,[2]}

@item

sys.excepthook

@tab

@code{hook}, @code{type}, @code{value}, @code{traceback}

@tab

@ref{a0c,,[1]}

@item

sys.monitoring.register_callback

@tab

@code{func}

@tab

@ref{4760,,[1]}

@item

sys.remote_exec

@tab

@code{pid}

@tab

@ref{4761,,[1]}

@item

sys.set_asyncgen_hooks_finalizer

@tab



@tab

@ref{199d,,[1]}

@item

sys.set_asyncgen_hooks_firstiter

@tab



@tab

@ref{199d,,[1]}

@item

sys.setprofile

@tab



@tab

@ref{1717,,[1]}

@item

sys.settrace

@tab



@tab

@ref{2e1,,[1]}

@item

sys.unraisablehook

@tab

@code{hook}, @code{unraisable}

@tab

@ref{507,,[1]}

@item

syslog.closelog

@tab



@tab

@ref{761,,[1]}

@item

syslog.openlog

@tab

@code{ident}, @code{logoption}, @code{facility}

@tab

@ref{760,,[1]}

@item

syslog.setlogmask

@tab

@code{maskpri}

@tab

@ref{4762,,[1]}

@item

syslog.syslog

@tab

@code{priority}, @code{message}

@tab

@ref{762,,[1]}

@item

tempfile.mkdtemp

@tab

@code{fullpath}

@tab

@ref{144c,,[1]}@ref{52d,,[2]}

@item

tempfile.mkstemp

@tab

@code{fullpath}

@tab

@ref{6ed,,[1]}@ref{2cc9,,[2]}@ref{2cca,,[3]}

@item

time.sleep

@tab

@code{secs}

@tab

@ref{4763,,[1]}

@item

urllib.Request

@tab

@code{fullurl}, @code{data}, @code{headers}, @code{method}

@tab

@ref{307,,[1]}

@item

webbrowser.open

@tab

@code{url}

@tab

@ref{1889,,[1]}

@item

winreg.ConnectRegistry

@tab

@code{computer_name}, @code{key}

@tab

@ref{4764,,[1]}

@item

winreg.CreateKey

@tab

@code{key}, @code{sub_key}, @code{access}

@tab

@ref{4765,,[1]}@ref{157a,,[2]}

@item

winreg.DeleteKey

@tab

@code{key}, @code{sub_key}, @code{access}

@tab

@ref{4766,,[1]}@ref{157b,,[2]}

@item

winreg.DeleteValue

@tab

@code{key}, @code{value}

@tab

@ref{4767,,[1]}

@item

winreg.DisableReflectionKey

@tab

@code{key}

@tab

@ref{157c,,[1]}

@item

winreg.EnableReflectionKey

@tab

@code{key}

@tab

@ref{157d,,[1]}

@item

winreg.EnumKey

@tab

@code{key}, @code{index}

@tab

@ref{4768,,[1]}

@item

winreg.EnumValue

@tab

@code{key}, @code{index}

@tab

@ref{4769,,[1]}

@item

winreg.ExpandEnvironmentStrings

@tab

@code{str}

@tab

@ref{1611,,[1]}

@item

winreg.LoadKey

@tab

@code{key}, @code{sub_key}, @code{file_name}

@tab

@ref{476a,,[1]}

@item

winreg.OpenKey

@tab

@code{key}, @code{sub_key}, @code{access}

@tab

@ref{476b,,[1]}

@item

winreg.OpenKey/result

@tab

@code{key}

@tab

@ref{4765,,[1]}@ref{157a,,[2]}@ref{476b,,[3]}

@item

winreg.PyHKEY.Detach

@tab

@code{key}

@tab

@ref{476c,,[1]}

@item

winreg.QueryInfoKey

@tab

@code{key}

@tab

@ref{476d,,[1]}

@item

winreg.QueryReflectionKey

@tab

@code{key}

@tab

@ref{157e,,[1]}

@item

winreg.QueryValue

@tab

@code{key}, @code{sub_key}, @code{value_name}

@tab

@ref{476e,,[1]}@ref{1784,,[2]}

@item

winreg.SaveKey

@tab

@code{key}, @code{file_name}

@tab

@ref{476f,,[1]}

@item

winreg.SetValue

@tab

@code{key}, @code{sub_key}, @code{type}, @code{value}

@tab

@ref{4770,,[1]}@ref{1b03,,[2]}

@end multitable


以下のイベントは内部で送出され、 CPython の公開 API に対応しません。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

監査イベント

@tab

引数

@item

_winapi.CreateFile

@tab

@code{file_name}, @code{desired_access},
@code{share_mode}, @code{creation_disposition},
@code{flags_and_attributes}

@item

_winapi.CreateJunction

@tab

@code{src_path}, @code{dst_path}

@item

_winapi.CreateNamedPipe

@tab

@code{name}, @code{open_mode}, @code{pipe_mode}

@item

_winapi.CreatePipe

@tab

@item

_winapi.CreateProcess

@tab

@code{application_name}, @code{command_line},
@code{current_directory}

@item

_winapi.OpenProcess

@tab

@code{process_id}, @code{desired_access}

@item

_winapi.TerminateProcess

@tab

@code{handle}, @code{exit_code}

@item

_posixsubprocess.fork_exec

@tab

@code{exec_list}, @code{args}, @code{env}

@item

ctypes.PyObj_FromPtr

@tab

@code{obj}

@end multitable



Added in version 3.14: The @code{_posixsubprocess.fork_exec} internal audit event.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node bdb --- デバッガーフレームワーク,faulthandler --- Python トレースバックをダンプする,監査イベント表,デバッグとプロファイル
@anchor{library/bdb doc}@anchor{4771}@anchor{library/bdb bdb-debugger-framework}@anchor{4772}@anchor{library/bdb module-bdb}@anchor{10}@anchor{library/bdb translation-repo}@anchor{4773}
@subsection @code{bdb} --- デバッガーフレームワーク


@geindex module; bdb

`ソースコード:' Lib/bdb.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/bdb.py}


__________________________________________________________________


The @code{bdb} module handles basic debugger functions, like setting breakpoints
or managing execution via the debugger.

以下の例外が定義されています:

@geindex BdbQuit
@anchor{library/bdb bdb BdbQuit}@anchor{278}
@deffn {例外} bdb.BdbQuit

@ref{2d5,,Bdb} クラスが、デバッガーを終了させるために投げる例外。
@end deffn

The @code{bdb} module also defines two classes:

@geindex Breakpoint (bdb のクラス)
@anchor{library/bdb bdb Breakpoint}@anchor{4774}
@deffn {クラス} bdb.Breakpoint (self, file, line, temporary=False, cond=None, funcname=None)

このクラスはテンポラリブレークポイント、無視するカウント、無効化と再有効化、条件付きブレークポイントを実装しています。

ブレークポイントは @ref{4775,,bpbynumber} という名前のリストで番号によりインデックスされ、 @ref{4776,,bplist} により @code{(file, line)} の形でインデックスされます。 @ref{4775,,bpbynumber} は @ref{4774,,Breakpoint} クラスのインスタンスを指しています。一方 @ref{4776,,bplist} は、同じ行に複数のブレークポイントが設定される場合があるので、インスタンスのリストを指しています。

ブレークポイントを作るとき、関連付けられる @ref{4777,,ファイル名} は正規化されていなければなりません。@ref{4778,,funcname} が定義されると、ブレークポイントの @ref{4779,,ヒット} はその関数の最初の行が実行されたときにカウントされます。@ref{477a,,条件付き} ブレークポイントは毎回 @ref{4779,,ヒット} をカウントします。

@ref{4774,,Breakpoint} インスタンスは以下のメソッドを持ちます:

@geindex deleteMe() (bdb.Breakpoint のメソッド)
@anchor{library/bdb bdb Breakpoint deleteMe}@anchor{477b}
@deffn {メソッド} deleteMe ()

このブレークポイントをファイル/行に関連付けられたリストから削除します。このブレークポイントがその行に設定された最後のブレークポイントだった場合、そのファイル/行に対するエントリ自体を削除します。
@end deffn

@geindex enable() (bdb.Breakpoint のメソッド)
@anchor{library/bdb bdb Breakpoint enable}@anchor{477c}
@deffn {メソッド} enable ()

このブレークポイントを有効にします。
@end deffn

@geindex disable() (bdb.Breakpoint のメソッド)
@anchor{library/bdb bdb Breakpoint disable}@anchor{477d}
@deffn {メソッド} disable ()

このブレークポイントを無効にします。
@end deffn

@geindex bpformat() (bdb.Breakpoint のメソッド)
@anchor{library/bdb bdb Breakpoint bpformat}@anchor{477e}
@deffn {メソッド} bpformat ()

ブレークポイントに関する情報を持つ文字列をフォーマットして返します:


@itemize *

@item 
Breakpoint number.

@item 
Temporary status (del or keep).

@item 
File/line position.

@item 
Break condition.

@item 
Number of times to ignore.

@item 
Number of times hit.
@end itemize


Added in version 3.2.

@end deffn

@geindex bpprint() (bdb.Breakpoint のメソッド)
@anchor{library/bdb bdb Breakpoint bpprint}@anchor{477f}
@deffn {メソッド} bpprint (out=None)

ファイル `out' に、またはそれが @code{None} の場合は標準出力に、 @ref{477e,,bpformat()} の出力を表示する。
@end deffn

@ref{4774,,Breakpoint} インスタンスは以下の属性を持ちます:

@geindex file (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint file}@anchor{4777}
@deffn {の属性} file

File name of the @ref{4774,,Breakpoint}.
@end deffn

@geindex line (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint line}@anchor{4780}
@deffn {の属性} line

Line number of the @ref{4774,,Breakpoint} within @ref{4777,,file}.
@end deffn

@geindex temporary (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint temporary}@anchor{4781}
@deffn {の属性} temporary

@code{True} if a @ref{4774,,Breakpoint} at (file, line) is temporary.
@end deffn

@geindex cond (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint cond}@anchor{477a}
@deffn {の属性} cond

Condition for evaluating a @ref{4774,,Breakpoint} at (file, line).
@end deffn

@geindex funcname (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint funcname}@anchor{4778}
@deffn {の属性} funcname

Function name that defines whether a @ref{4774,,Breakpoint} is hit upon
entering the function.
@end deffn

@geindex enabled (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint enabled}@anchor{4782}
@deffn {の属性} enabled

@code{True} if @ref{4774,,Breakpoint} is enabled.
@end deffn

@geindex bpbynumber (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint bpbynumber}@anchor{4775}
@deffn {の属性} bpbynumber

Numeric index for a single instance of a @ref{4774,,Breakpoint}.
@end deffn

@geindex bplist (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint bplist}@anchor{4776}
@deffn {の属性} bplist

Dictionary of @ref{4774,,Breakpoint} instances indexed by
(@ref{4777,,file}, @ref{4780,,line}) tuples.
@end deffn

@geindex ignore (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint ignore}@anchor{4783}
@deffn {の属性} ignore

Number of times to ignore a @ref{4774,,Breakpoint}.
@end deffn

@geindex hits (bdb.Breakpoint の属性)
@anchor{library/bdb bdb Breakpoint hits}@anchor{4779}
@deffn {の属性} hits

Count of the number of times a @ref{4774,,Breakpoint} has been hit.
@end deffn
@end deffn

@geindex Bdb (bdb のクラス)
@anchor{library/bdb bdb Bdb}@anchor{2d5}
@deffn {クラス} bdb.Bdb (skip=None, backend='settrace')

@ref{2d5,,Bdb} クラスは一般的なPythonデバッガーの基本クラスとして振舞います。

このクラスはトレース機能の詳細を扱います。ユーザーとのインタラクションは、派生クラスが実装するべきです。標準ライブラリのデバッガクラス (@ref{273,,pdb.Pdb}) がその利用例です。

`skip' 引数は、もし与えられたならグロブ形式のモジュール名パターンの iterable でなければなりません。デバッガはこれらのパターンのどれかにマッチするモジュールで発生したフレームにステップインしなくなります。フレームが特定のモジュールで発生したかどうかは、フレームのグローバル変数の @code{__name__} によって決定されます。

The `backend' argument specifies the backend to use for @ref{2d5,,Bdb}. It
can be either @code{'settrace'} or @code{'monitoring'}. @code{'settrace'} uses
@ref{2e1,,sys.settrace()} which has the best backward compatibility. The
@code{'monitoring'} backend uses the new @ref{e0,,sys.monitoring} that was
introduced in Python 3.12, which can be much more efficient because it
can disable unused events. We are trying to keep the exact interfaces
for both backends, but there are some differences. The debugger developers
are encouraged to use the @code{'monitoring'} backend to achieve better
performance.


バージョン 3.1 で変更: `skip' パラメータが追加されました。



バージョン 3.14 で変更: Added the `backend' parameter.


以下の @ref{2d5,,Bdb} のメソッドは、通常オーバーライドする必要はありません。

@geindex canonic() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb canonic}@anchor{4784}
@deffn {メソッド} canonic (filename)

Return canonical form of `filename'.

For real file names, the canonical form is an operating-system-dependent,
@ref{2c56,,case-normalized} @ref{1532,,absolute path}. A `filename' with angle brackets, such as @code{"<stdin>"}
generated in interactive mode, is returned unchanged.
@end deffn

@geindex start_trace() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb start_trace}@anchor{4785}
@deffn {メソッド} start_trace (self)

Start tracing. For @code{'settrace'} backend, this method is equivalent to
@code{sys.settrace(self.trace_dispatch)}


Added in version 3.14.

@end deffn

@geindex stop_trace() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb stop_trace}@anchor{4786}
@deffn {メソッド} stop_trace (self)

Stop tracing. For @code{'settrace'} backend, this method is equivalent to
@code{sys.settrace(None)}


Added in version 3.14.

@end deffn

@geindex reset() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb reset}@anchor{4787}
@deffn {メソッド} reset ()

Set the @code{botframe}, @code{stopframe}, @code{returnframe} and
@ref{4788,,quitting} attributes with values ready to start debugging.
@end deffn

@geindex trace_dispatch() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb trace_dispatch}@anchor{4789}
@deffn {メソッド} trace_dispatch (frame, event, arg)

この関数は、デバッグされているフレームのトレース関数としてインストールされます。戻り値は新しいトレース関数(殆どの場合はこの関数自身)です。

デフォルトの実装は、実行しようとしている `event' (文字列として渡されます) の種類に基づいてフレームのディスパッチ方法を決定します。`event' は次のうちのどれかです:


@itemize *

@item 
@code{"line"}: 新しい行を実行しようとしています。

@item 
@code{"call"}: 関数が呼び出されているか、別のコードブロックに入ります。

@item 
@code{"return"}: 関数か別のコードブロックからreturnしようとしています。

@item 
@code{"exception"}: 例外が発生しました。

@item 
@code{"c_call"}: C関数を呼び出そうとしています。

@item 
@code{"c_return"}: C関数からreturnしました。

@item 
@code{"c_exception"}: C関数が例外を発生させました。
@end itemize

Pythonのイベントに対しては、以下の専用の関数群が呼ばれます。Cのイベントに対しては何もしません。

`arg' 引数は以前のイベントに依存します。

トレース関数についてのより詳しい情報は、 @ref{2e1,,sys.settrace()} のドキュメントを参照してください。コードとフレームオブジェクトについてのより詳しい情報は、 @ref{232f,,標準型の階層} を参照してください。
@end deffn

@geindex dispatch_line() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb dispatch_line}@anchor{478a}
@deffn {メソッド} dispatch_line (frame)

If the debugger should stop on the current line, invoke the
@ref{478b,,user_line()} method (which should be overridden in subclasses).
Raise a @ref{278,,BdbQuit} exception if the @ref{4788,,quitting} flag is set
(which can be set from @ref{478b,,user_line()}).  Return a reference to the
@ref{4789,,trace_dispatch()} method for further tracing in that scope.
@end deffn

@geindex dispatch_call() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb dispatch_call}@anchor{478c}
@deffn {メソッド} dispatch_call (frame, arg)

If the debugger should stop on this function call, invoke the
@ref{478d,,user_call()} method (which should be overridden in subclasses).
Raise a @ref{278,,BdbQuit} exception if the @ref{4788,,quitting} flag is set
(which can be set from @ref{478d,,user_call()}).  Return a reference to the
@ref{4789,,trace_dispatch()} method for further tracing in that scope.
@end deffn

@geindex dispatch_return() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb dispatch_return}@anchor{478e}
@deffn {メソッド} dispatch_return (frame, arg)

If the debugger should stop on this function return, invoke the
@ref{478f,,user_return()} method (which should be overridden in subclasses).
Raise a @ref{278,,BdbQuit} exception if the @ref{4788,,quitting} flag is set
(which can be set from @ref{478f,,user_return()}).  Return a reference to the
@ref{4789,,trace_dispatch()} method for further tracing in that scope.
@end deffn

@geindex dispatch_exception() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb dispatch_exception}@anchor{4790}
@deffn {メソッド} dispatch_exception (frame, arg)

If the debugger should stop at this exception, invokes the
@ref{4791,,user_exception()} method (which should be overridden in subclasses).
Raise a @ref{278,,BdbQuit} exception if the @ref{4788,,quitting} flag is set
(which can be set from @ref{4791,,user_exception()}).  Return a reference to the
@ref{4789,,trace_dispatch()} method for further tracing in that scope.
@end deffn

通常、継承クラスは以下のメソッド群をオーバーライドしません。しかし、停止やブレークポイント機能を再定義したい場合には、オーバーライドすることもあります。

@geindex is_skipped_module() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb is_skipped_module}@anchor{4792}
@deffn {メソッド} is_skipped_module (module_name)

Return @code{True} if `module_name' matches any skip pattern.
@end deffn

@geindex stop_here() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb stop_here}@anchor{4793}
@deffn {メソッド} stop_here (frame)

Return @code{True} if `frame' is below the starting frame in the stack.
@end deffn

@geindex break_here() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb break_here}@anchor{4794}
@deffn {メソッド} break_here (frame)

Return @code{True} if there is an effective breakpoint for this line.

Check whether a line or function breakpoint exists and is in effect.  Delete temporary
breakpoints based on information from @ref{4795,,effective()}.
@end deffn

@geindex break_anywhere() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb break_anywhere}@anchor{4796}
@deffn {メソッド} break_anywhere (frame)

Return @code{True} if any breakpoint exists for `frame''s filename.
@end deffn

継承クラスはデバッガー操作をするために以下のメソッド群をオーバーライドするべきです。

@geindex user_call() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb user_call}@anchor{478d}
@deffn {メソッド} user_call (frame, argument_list)

Called from @ref{478c,,dispatch_call()} if a break might stop inside the
called function.

`argument_list' is not used anymore and will always be @code{None}.
The argument is kept for backwards compatibility.
@end deffn

@geindex user_line() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb user_line}@anchor{478b}
@deffn {メソッド} user_line (frame)

@ref{4793,,stop_here()} か @ref{4794,,break_here()} が @code{True} を返したときに、 @ref{478a,,dispatch_line()} から呼び出されます。
@end deffn

@geindex user_return() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb user_return}@anchor{478f}
@deffn {メソッド} user_return (frame, return_value)

@ref{4793,,stop_here()} が @code{True} を返したときに、 @ref{478e,,dispatch_return()} から呼び出されます。
@end deffn

@geindex user_exception() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb user_exception}@anchor{4791}
@deffn {メソッド} user_exception (frame, exc_info)

@ref{4793,,stop_here()} が @code{True} を返したときに、 @ref{4790,,dispatch_exception()} から呼び出されます。
@end deffn

@geindex do_clear() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb do_clear}@anchor{4797}
@deffn {メソッド} do_clear (arg)

ブレークポイントがテンポラリブレークポイントだったときに、それをどう削除するかを決定します。

継承クラスはこのメソッドを実装しなければなりません。
@end deffn

継承クラスとクライアントは、ステップ状態に影響を及ぼすために以下のメソッドを呼び出すことができます。

@geindex set_step() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_step}@anchor{4798}
@deffn {メソッド} set_step ()

コードの次の行でストップします。
@end deffn

@geindex set_next() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_next}@anchor{4799}
@deffn {メソッド} set_next (frame)

与えられたフレームかそれより下(のフレーム)にある、次の行でストップします。
@end deffn

@geindex set_return() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_return}@anchor{479a}
@deffn {メソッド} set_return (frame)

指定されたフレームから抜けるときにストップします。
@end deffn

@geindex set_until() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_until}@anchor{479b}
@deffn {メソッド} set_until (frame, lineno=None)

現在の行番号よりも大きい `lineno' に到達したとき、あるいは、現在のフレームから戻るときにストップします。
@end deffn

@geindex set_trace() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_trace}@anchor{479c}
@deffn {メソッド} set_trace ([frame])

`frame' からデバッグを開始します。`frame' が指定されなかった場合、デバッグは呼び出し元のフレームから開始します。


バージョン 3.13 で変更: @ref{479d,,set_trace()} will enter the debugger immediately, rather than
on the next line of code to be executed.

@end deffn

@geindex set_continue() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_continue}@anchor{479e}
@deffn {メソッド} set_continue ()

ブレークポイントに到達するか終了したときにストップします。もしブレークポイントが1つも無い場合、システムのトレース関数を @code{None} に設定します。
@end deffn

@geindex set_quit() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_quit}@anchor{4788}
@deffn {メソッド} set_quit ()

@geindex quitting (bdb.Bdb attribute)

Set the @code{quitting} attribute to @code{True}.  This raises @ref{278,,BdbQuit} in
the next call to one of the @code{dispatch_*()} methods.
@end deffn

継承クラスとクライアントは以下のメソッドをブレークポイント操作に利用できます。これらのメソッドは、何か悪いことがあればエラーメッセージを含む文字列を返し、すべてが順調であれば @code{None} を返します。

@geindex set_break() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb set_break}@anchor{479f}
@deffn {メソッド} set_break (filename, lineno, temporary=False, cond=None, funcname=None)

新しいブレークポイントを設定します。引数の `lineno' 行が `filename' に存在しない場合、エラーメッセージを返します。 `filename' は、 @ref{4784,,canonic()} メソッドで説明されているような、標準形である必要があります。
@end deffn

@geindex clear_break() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb clear_break}@anchor{47a0}
@deffn {メソッド} clear_break (filename, lineno)

`filename' の `lineno' 行にあるブレークポイントを削除します。もしブレークポイントが無かった場合、エラーメッセージを返します。
@end deffn

@geindex clear_bpbynumber() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb clear_bpbynumber}@anchor{47a1}
@deffn {メソッド} clear_bpbynumber (arg)

@ref{4775,,Breakpoint.bpbynumber} の中で `arg' のインデックスを持つブレークポイントを削除します。 `arg' が数値でないか範囲外の場合、エラーメッセージを返します。
@end deffn

@geindex clear_all_file_breaks() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb clear_all_file_breaks}@anchor{47a2}
@deffn {メソッド} clear_all_file_breaks (filename)

`filename' にあるすべてのブレークポイントを削除します。もしブレークポイントが無かった場合、エラーメッセージを返します。
@end deffn

@geindex clear_all_breaks() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb clear_all_breaks}@anchor{47a3}
@deffn {メソッド} clear_all_breaks ()

存在するすべてのブレークポイントを削除します。もしブレークポイントが無かった場合、エラーメッセージを返します。
@end deffn

@geindex get_bpbynumber() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb get_bpbynumber}@anchor{47a4}
@deffn {メソッド} get_bpbynumber (arg)

与えられた数値によって指定されるブレークポイントを返します。 `arg' が文字列なら数値に変換されます。 `arg' が非数値の文字列である場合、指定されたブレークポイントが存在しないか削除された場合、 @ref{2ec,,ValueError} が上げられます。


Added in version 3.2.

@end deffn

@geindex get_break() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb get_break}@anchor{47a5}
@deffn {メソッド} get_break (filename, lineno)

Return @code{True} if there is a breakpoint for `lineno' in `filename'.
@end deffn

@geindex get_breaks() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb get_breaks}@anchor{47a6}
@deffn {メソッド} get_breaks (filename, lineno)

`filename' の `lineno' にあるすべてのブレークポイントを返します。ブレークポイントが存在しない場合は空のリストを返します。
@end deffn

@geindex get_file_breaks() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb get_file_breaks}@anchor{47a7}
@deffn {メソッド} get_file_breaks (filename)

`filename' の中のすべてのブレークポイントを返します。ブレークポイントが存在しない場合は空のリストを返します。
@end deffn

@geindex get_all_breaks() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb get_all_breaks}@anchor{47a8}
@deffn {メソッド} get_all_breaks ()

セットされているすべてのブレークポイントを返します。
@end deffn

Derived classes and clients can call the following methods to disable and
restart events to achieve better performance. These methods only work
when using the @code{'monitoring'} backend.

@geindex disable_current_event() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb disable_current_event}@anchor{47a9}
@deffn {メソッド} disable_current_event ()

Disable the current event until the next time @ref{47aa,,restart_events()} is
called. This is helpful when the debugger is not interested in the current
line.


Added in version 3.14.

@end deffn

@geindex restart_events() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb restart_events}@anchor{47aa}
@deffn {メソッド} restart_events ()

Restart all the disabled events. This function is automatically called in
@code{dispatch_*} methods after @code{user_*} methods are called. If the
@code{dispatch_*} methods are not overridden, the disabled events will be
restarted after each user interaction.


Added in version 3.14.

@end deffn

継承クラスとクライアントは以下のメソッドを呼んでスタックトレースを表現するデータ構造を取得することができます。

@geindex get_stack() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb get_stack}@anchor{47ab}
@deffn {メソッド} get_stack (f, t)

Return a list of (frame, lineno) tuples in a stack trace, and a size.

The most recently called frame is last in the list. The size is the number
of frames below the frame where the debugger was invoked.
@end deffn

@geindex format_stack_entry() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb format_stack_entry}@anchor{47ac}
@deffn {メソッド} format_stack_entry (frame_lineno, lprefix=': ')

Return a string with information about a stack entry, which is a
@code{(frame, lineno)} tuple.  The return string contains:


@itemize *

@item 
The canonical filename which contains the frame.

@item 
関数名もしくは @code{"<lambda>"}。

@item 
入力された引数。

@item 
戻り値。

@item 
(あれば)その行のコード。
@end itemize
@end deffn

以下の2つのメソッドは、文字列として渡された @ref{2bfc,,文} をデバッグするもので、クライアントから利用されます。

@geindex run() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb run}@anchor{47ad}
@deffn {メソッド} run (cmd, globals=None, locals=None)

Debug a statement executed via the @ref{4a2,,exec()} function.  `globals'
defaults to @code{__main__.__dict__}, `locals' defaults to `globals'.
@end deffn

@geindex runeval() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb runeval}@anchor{47ae}
@deffn {メソッド} runeval (expr, globals=None, locals=None)

@ref{4a3,,eval()} 関数を利用して式を実行しデバッグします。 `globals' と `locals' は @ref{47ad,,run()} と同じ意味です。
@end deffn

@geindex runctx() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb runctx}@anchor{47af}
@deffn {メソッド} runctx (cmd, globals, locals)

後方互換性のためのメソッドです。 @ref{47ad,,run()} を使ってください。
@end deffn

@geindex runcall() (bdb.Bdb のメソッド)
@anchor{library/bdb bdb Bdb runcall}@anchor{c71}
@deffn {メソッド} runcall (func, /, *args, **kwds)

1つの関数呼び出しをデバッグし、その結果を返します。
@end deffn
@end deffn

最後に、このモジュールは以下の関数を提供しています:

@geindex checkfuncname() (bdb モジュール)
@anchor{library/bdb bdb checkfuncname}@anchor{47b0}
@deffn {の関数} bdb.checkfuncname (b, frame)

Return @code{True} if we should break here, depending on the way the
@ref{4774,,Breakpoint} `b' was set.

If it was set via line number, it checks if
@ref{4780,,b.line} is the same as the one in `frame'.
If the breakpoint was set via
@ref{4778,,function name}, we have to check we are in
the right `frame' (the right function) and if we are on its first executable
line.
@end deffn

@geindex effective() (bdb モジュール)
@anchor{library/bdb bdb effective}@anchor{4795}
@deffn {の関数} bdb.effective (file, line, frame)

Return @code{(active breakpoint, delete temporary flag)} or @code{(None, None)} as the
breakpoint to act upon.

The `active breakpoint' is the first entry in
@ref{4776,,bplist} for the
(@ref{4777,,file}, @ref{4780,,line})
(which must exist) that is @ref{4782,,enabled}, for
which @ref{47b0,,checkfuncname()} is true, and that has neither a false
@ref{477a,,condition} nor positive
@ref{4783,,ignore} count.  The `flag', meaning that a
temporary breakpoint should be deleted, is @code{False} only when the
@ref{477a,,cond} cannot be evaluated (in which case,
@ref{4783,,ignore} count is ignored).

If no such entry exists, then @code{(None, None)} is returned.
@end deffn

@geindex set_trace() (bdb モジュール)
@anchor{library/bdb bdb set_trace}@anchor{479d}
@deffn {の関数} bdb.set_trace ()

@ref{2d5,,Bdb} クラスのインスタンスを使って、呼び出し元のフレームからデバッグを開始します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node faulthandler --- Python トレースバックをダンプする,pdb --- The Python Debugger,bdb --- デバッガーフレームワーク,デバッグとプロファイル
@anchor{library/faulthandler doc}@anchor{47b1}@anchor{library/faulthandler faulthandler-dump-the-python-traceback}@anchor{47b2}@anchor{library/faulthandler module-faulthandler}@anchor{5c}@anchor{library/faulthandler translation-repo}@anchor{47b3}
@subsection @code{faulthandler} --- Python トレースバックをダンプする


@geindex module; faulthandler


Added in version 3.3.



__________________________________________________________________


このモジュールは、例外発生時、タイムアウト時、ユーザシグナルの発生時などのタイミングでpython tracebackを明示的にダンプするための関数を含んでいます。これらのシグナル、@ref{128c,,SIGSEGV}、@ref{128d,,SIGFPE}、@ref{128e,,SIGABRT}、@ref{128f,,SIGBUS}、@ref{1290,,SIGILL} に対するフォールトハンドラをインストールするには @ref{20f,,faulthandler.enable()} を実行してください。python起動時に有効にするには環境変数 
@geindex PYTHONFAULTHANDLER
@geindex 環境変数; PYTHONFAULTHANDLER
@ref{1291,,PYTHONFAULTHANDLER} を設定するか、コマンドライン引数に @ref{16f,,-X} @code{faulthandler} を指定してください。

Pythonのフォールトハンドラは、apportやWindowsのフォールトハンドラのようなシステムフォールトハンドラと互換性があります。このモジュールは @code{sigaltstack()} 関数が使用可能であればシグナルハンドラ用に代替スタックを利用します。これによってスタックオーバーフロー時にもトレースバックを出力することができます。

フォールトハンドラは絶望的なケースで呼び出されます。そのためシグナルセーフな関数しか使うことができません (例: ヒープメモリ上にメモリ確保はできません)。この制限により、tracebackのダンプ機能は通常のPythonのtracebackと比べてごく僅かなものです:


@itemize *

@item 
ASCIIのみサポートされます。エンコード時には @code{backslashreplace} エラーハンドラを使用します。

@item 
すべての文字列は500文字以内に制限されています。

@item 
ファイル名、関数名、行数のみ表示します。(ソースコードの表示はありません)

@item 
100フレーム、100スレッドに制限されています。

@item 
順番は保持されます: 最新の呼び出しが最初に表示されます。
@end itemize

デフォルトでは、Pythonのtracebackは @ref{b33,,sys.stderr} に書き出されます。tracebackを見るには、対象アプリケーションはターミナル上で実行しなければなりません。 @ref{20f,,faulthandler.enable()} に渡す引数によってログファイルを指定することができます。

モジュールはC言語で実装されているので、アプリのクラッシュ時でもPythonがデッドロックした場合でもダンプができます。

The @ref{508,,Python Development Mode} calls @ref{20f,,faulthandler.enable()}
at Python startup.


@subsubheading 参考



@table @asis

@item @ref{aa,,pdb} モジュール

Interactive source code debugger for Python programs.

@item @ref{104,,traceback} モジュール

Standard interface to extract, format and print stack traces of Python programs.
@end table


@menu
* tracebackのダンプ:: 
* Dumping the C stack:: 
* フォールトハンドラの状態:: 
* タイムアウト後にtracebackをダンプする:: 
* ユーザシグナルに対してtracebackをダンプする:: 
* ファイル記述子の問題:: 
* 使用例: 使用例<43>. 

@end menu

@node tracebackのダンプ,Dumping the C stack,,faulthandler --- Python トレースバックをダンプする
@anchor{library/faulthandler dumping-the-traceback}@anchor{47b4}
@subsubsection tracebackのダンプ


@geindex dump_traceback() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler dump_traceback}@anchor{fff}
@deffn {の関数} faulthandler.dump_traceback (file=sys.stderr, all_threads=True)

全スレッドのtracebackを `file' へダンプします。もし `all_threads' が @code{False} であれば、現在のスレッドのみダンプします。


@subsubheading 参考


@ref{1085,,traceback.print_tb()}, which can be used to print a traceback object.



バージョン 3.5 で変更: Added support for passing file descriptor to this function.

@end deffn

@node Dumping the C stack,フォールトハンドラの状態,tracebackのダンプ,faulthandler --- Python トレースバックをダンプする
@anchor{library/faulthandler dumping-the-c-stack}@anchor{47b5}
@subsubsection Dumping the C stack



Added in version 3.14.


@geindex dump_c_stack() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler dump_c_stack}@anchor{20e}
@deffn {の関数} faulthandler.dump_c_stack (file=sys.stderr)

Dump the C stack trace of the current thread into `file'.

If the Python build does not support it or the operating system
does not provide a stack trace, then this prints an error in place
of a dumped C stack.
@end deffn

@menu
* C Stack Compatibility:: 

@end menu

@node C Stack Compatibility,,,Dumping the C stack
@anchor{library/faulthandler c-stack-compatibility}@anchor{20d}@anchor{library/faulthandler id1}@anchor{47b6}
@subsubsection C Stack Compatibility


If the system does not support the C-level @code{backtrace(3)@footnote{https://manpages.debian.org/backtrace(3)}}
or @code{dladdr1(3)@footnote{https://manpages.debian.org/dladdr1(3)}}, then C stack dumps will not work.
An error will be printed instead of the stack.

Additionally, some compilers do not support @ref{905,,CPython's}
implementation of C stack dumps. As a result, a different error may be printed
instead of the stack, even if the operating system supports dumping stacks.

@cartouche
@quotation 注釈 
Dumping C stacks can be arbitrarily slow, depending on the DWARF level
of the binaries in the call stack.
@end quotation
@end cartouche

@node フォールトハンドラの状態,タイムアウト後にtracebackをダンプする,Dumping the C stack,faulthandler --- Python トレースバックをダンプする
@anchor{library/faulthandler fault-handler-state}@anchor{47b7}
@subsubsection フォールトハンドラの状態


@geindex enable() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler enable}@anchor{20f}
@deffn {の関数} faulthandler.enable (file=sys.stderr, all_threads=True, c_stack=True)

Enable the fault handler: install handlers for the @ref{128c,,SIGSEGV},
@ref{128d,,SIGFPE}, @ref{128e,,SIGABRT}, @ref{128f,,SIGBUS}
and @ref{1290,,SIGILL}
signals to dump the Python traceback. If `all_threads' is @code{True},
produce tracebacks for every running thread. Otherwise, dump only the current
thread.

The `file' must be kept open until the fault handler is disabled: see
@ref{47b8,,issue with file descriptors}.

If `c_stack' is @code{True}, then the C stack trace is printed after the Python
traceback, unless the system does not support it. See @ref{20e,,dump_c_stack()} for
more information on compatibility.


バージョン 3.5 で変更: Added support for passing file descriptor to this function.



バージョン 3.6 で変更: On Windows, a handler for Windows exception is also installed.



バージョン 3.10 で変更: The dump now mentions if a garbage collector collection is running
if `all_threads' is true.



バージョン 3.14 で変更: Only the current thread is dumped if the @ref{164,,GIL} is disabled to
prevent the risk of data races.



バージョン 3.14 で変更: The dump now displays the C stack trace if `c_stack' is true.

@end deffn

@geindex disable() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler disable}@anchor{47b9}
@deffn {の関数} faulthandler.disable ()

フォールトハンドラを無効にします: @ref{20f,,enable()} によってインストールされたシグナルハンドラをアンインストールします。
@end deffn

@geindex is_enabled() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler is_enabled}@anchor{47ba}
@deffn {の関数} faulthandler.is_enabled ()

フォールトハンドラが有効かどうかチェックします。
@end deffn

@node タイムアウト後にtracebackをダンプする,ユーザシグナルに対してtracebackをダンプする,フォールトハンドラの状態,faulthandler --- Python トレースバックをダンプする
@anchor{library/faulthandler dumping-the-tracebacks-after-a-timeout}@anchor{47bb}
@subsubsection タイムアウト後にtracebackをダンプする


@geindex dump_traceback_later() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler dump_traceback_later}@anchor{1000}
@deffn {の関数} faulthandler.dump_traceback_later (timeout, repeat=False, file=sys.stderr, exit=False)

Dump the tracebacks of all threads, after a timeout of `timeout' seconds, or
every `timeout' seconds if `repeat' is @code{True}.  If `exit' is @code{True}, call
@code{_exit()} with status=1 after dumping the tracebacks.  (Note
@code{_exit()} exits the process immediately, which means it doesn't do any
cleanup like flushing file buffers.) If the function is called twice, the new
call replaces previous parameters and resets the timeout. The timer has a
sub-second resolution.

The `file' must be kept open until the traceback is dumped or
@ref{47bc,,cancel_dump_traceback_later()} is called: see @ref{47b8,,issue with file descriptors}.

This function is implemented using a watchdog thread.


バージョン 3.5 で変更: Added support for passing file descriptor to this function.



バージョン 3.7 で変更: This function is now always available.

@end deffn

@geindex cancel_dump_traceback_later() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler cancel_dump_traceback_later}@anchor{47bc}
@deffn {の関数} faulthandler.cancel_dump_traceback_later ()

@ref{1000,,dump_traceback_later()} の最新の呼び出しをキャンセルします。
@end deffn

@node ユーザシグナルに対してtracebackをダンプする,ファイル記述子の問題,タイムアウト後にtracebackをダンプする,faulthandler --- Python トレースバックをダンプする
@anchor{library/faulthandler dumping-the-traceback-on-a-user-signal}@anchor{47bd}
@subsubsection ユーザシグナルに対してtracebackをダンプする


@geindex register() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler register}@anchor{ffe}
@deffn {の関数} faulthandler.register (signum, file=sys.stderr, all_threads=True, chain=False)

ユーザシグナルを登録します: すべてのスレッドでtracebackをダンプするために `signum' シグナルをインストールします。ただし `all_threads' が @code{False} であれば現在のスレッドのみ `file' にダンプします。もし chain が @code{True} であれば以前のハンドラも呼び出します。

The `file' must be kept open until the signal is unregistered by
@ref{47be,,unregister()}: see @ref{47b8,,issue with file descriptors}.

Windowsでは利用不可です。


バージョン 3.5 で変更: Added support for passing file descriptor to this function.

@end deffn

@geindex unregister() (faulthandler モジュール)
@anchor{library/faulthandler faulthandler unregister}@anchor{47be}
@deffn {の関数} faulthandler.unregister (signum)

ユーザシグナルを登録解除します: @ref{ffe,,register()} でインストールした `signum' シグナルハンドラをアンインストールします。シグナルが登録された場合は @code{True} を返し、そうでなければ @code{False} を返します。

Windowsでは利用不可です。
@end deffn

@node ファイル記述子の問題,使用例<43>,ユーザシグナルに対してtracebackをダンプする,faulthandler --- Python トレースバックをダンプする
@anchor{library/faulthandler faulthandler-fd}@anchor{47b8}@anchor{library/faulthandler issue-with-file-descriptors}@anchor{47bf}
@subsubsection ファイル記述子の問題


@ref{20f,,enable()}、@ref{1000,,dump_traceback_later()} ならびに @ref{ffe,,register()} は引数 `file' に渡されたファイル記述子を保持します。ファイルが閉じられファイル記述子が新しいファイルで再利用された場合や、@ref{d5a,,os.dup2()} の使用でファイル記述子が置き換えた場合、 traceback の結果は別のファイルへ書き込まれます。ファイルが置き換えられた場合は、毎回これらの関数を呼び出しなおしてください。

@node 使用例<43>,,ファイル記述子の問題,faulthandler --- Python トレースバックをダンプする
@anchor{library/faulthandler example}@anchor{47c0}
@subsubsection 使用例


フォールトハンドラを有効化・無効化したときの Linuxでのセグメンテーションフォールトの例:

@example
$ python -c "import ctypes; ctypes.string_at(0)"
Segmentation fault

$ python -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault

Current thread 0x00007fb899f39700 (most recent call first):
  File "/opt/python/Lib/ctypes/__init__.py", line 486 in string_at
  File "<stdin>", line 1 in <module>

Current thread's C stack trace (most recent call first):
  Binary file "/opt/python/python", at _Py_DumpStack+0x42 [0x5b27f7d7147e]
  Binary file "/opt/python/python", at +0x32dcbd [0x5b27f7d85cbd]
  Binary file "/opt/python/python", at +0x32df8a [0x5b27f7d85f8a]
  Binary file "/usr/lib/libc.so.6", at +0x3def0 [0x77b73226bef0]
  Binary file "/usr/lib/libc.so.6", at +0x17ef9c [0x77b7323acf9c]
  Binary file "/opt/python/build/lib.linux-x86_64-3.14/_ctypes.cpython-314d-x86_64-linux-gnu.so", at +0xcdf6 [0x77b7315dddf6]
  Binary file "/usr/lib/libffi.so.8", at +0x7976 [0x77b73158f976]
  Binary file "/usr/lib/libffi.so.8", at +0x413c [0x77b73158c13c]
  Binary file "/usr/lib/libffi.so.8", at ffi_call+0x12e [0x77b73158ef0e]
  Binary file "/opt/python/build/lib.linux-x86_64-3.14/_ctypes.cpython-314d-x86_64-linux-gnu.so", at +0x15a33 [0x77b7315e6a33]
  Binary file "/opt/python/build/lib.linux-x86_64-3.14/_ctypes.cpython-314d-x86_64-linux-gnu.so", at +0x164fa [0x77b7315e74fa]
  Binary file "/opt/python/build/lib.linux-x86_64-3.14/_ctypes.cpython-314d-x86_64-linux-gnu.so", at +0xc624 [0x77b7315dd624]
  Binary file "/opt/python/python", at _PyObject_MakeTpCall+0xce [0x5b27f7b73883]
  Binary file "/opt/python/python", at +0x11bab6 [0x5b27f7b73ab6]
  Binary file "/opt/python/python", at PyObject_Vectorcall+0x23 [0x5b27f7b73b04]
  Binary file "/opt/python/python", at _PyEval_EvalFrameDefault+0x490c [0x5b27f7cbb302]
  Binary file "/opt/python/python", at +0x2818e6 [0x5b27f7cd98e6]
  Binary file "/opt/python/python", at +0x281aab [0x5b27f7cd9aab]
  Binary file "/opt/python/python", at PyEval_EvalCode+0xc5 [0x5b27f7cd9ba3]
  Binary file "/opt/python/python", at +0x255957 [0x5b27f7cad957]
  Binary file "/opt/python/python", at +0x255ab4 [0x5b27f7cadab4]
  Binary file "/opt/python/python", at _PyEval_EvalFrameDefault+0x6c3e [0x5b27f7cbd634]
  Binary file "/opt/python/python", at +0x2818e6 [0x5b27f7cd98e6]
  Binary file "/opt/python/python", at +0x281aab [0x5b27f7cd9aab]
  Binary file "/opt/python/python", at +0x11b6e1 [0x5b27f7b736e1]
  Binary file "/opt/python/python", at +0x11d348 [0x5b27f7b75348]
  Binary file "/opt/python/python", at +0x11d626 [0x5b27f7b75626]
  Binary file "/opt/python/python", at PyObject_Call+0x20 [0x5b27f7b7565e]
  Binary file "/opt/python/python", at +0x32a67a [0x5b27f7d8267a]
  Binary file "/opt/python/python", at +0x32a7f8 [0x5b27f7d827f8]
  Binary file "/opt/python/python", at +0x32ac1b [0x5b27f7d82c1b]
  Binary file "/opt/python/python", at Py_RunMain+0x31 [0x5b27f7d82ebe]
  <truncated rest of calls>
Segmentation fault
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pdb --- The Python Debugger,Python プロファイラ,faulthandler --- Python トレースバックをダンプする,デバッグとプロファイル
@anchor{library/pdb doc}@anchor{47c1}@anchor{library/pdb debugger}@anchor{47c2}@anchor{library/pdb module-pdb}@anchor{aa}@anchor{library/pdb pdb-the-python-debugger}@anchor{47c3}@anchor{library/pdb translation-repo}@anchor{47c4}
@subsection @code{pdb} --- The Python Debugger


@geindex module; pdb

`ソースコード:' Lib/pdb.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pdb.py}

@geindex デバッグ


__________________________________________________________________


The module @code{pdb} defines an interactive source code debugger for Python
programs.  It supports setting (conditional) breakpoints and single stepping at
the source line level, inspection of stack frames, source code listing, and
evaluation of arbitrary Python code in the context of any stack frame.  It also
supports post-mortem debugging and can be called under program control.

@geindex Pdb (class in pdb)
@geindex module;bdb
@geindex module;cmd

デバッガーは拡張可能です -- 実際にはクラス @ref{273,,Pdb} として定義されています。現在これについてのドキュメントはありませんが、ソースを読めば簡単に理解できます。拡張インターフェースはモジュール @ref{10,,bdb} と @ref{1a,,cmd} を使っています。


@subsubheading 参考



@table @asis

@item @ref{5c,,faulthandler} モジュール

Used to dump Python tracebacks explicitly, on a fault, after a timeout,
or on a user signal.

@item @ref{104,,traceback} モジュール

Standard interface to extract, format and print stack traces of Python programs.
@end table


The typical usage to break into the debugger is to insert:

@example
import pdb; pdb.set_trace()
@end example

もしくは:

@example
breakpoint()
@end example

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 @ref{47c5,,continue} command.


バージョン 3.7 で変更: The built-in @ref{271,,breakpoint()}, when called with defaults, can be used
instead of @code{import pdb; pdb.set_trace()}.


@example
def double(x):
   breakpoint()
   return x * 2
val = 3
print(f"@{val@} * 2 is @{double(val)@}")
@end example

The debugger's prompt is @code{(Pdb)}, which is the indicator that you are in debug mode:

@example
> ...(2)double()
-> breakpoint()
(Pdb) p x
3
(Pdb) continue
3 * 2 is 6
@end example


バージョン 3.3 で変更: @ref{bf,,readline} モジュールによるコマンドおよびコマンド引数のタブ補完が利用できます。たとえば、@code{p} コマンドの引数では現在のグローバルおよびローカル名が候補として表示されます。


@menu
* コマンドライン・インターフェース: コマンドライン・インターフェース<8>. 
* Debugger commands:: 

@end menu

@node コマンドライン・インターフェース<8>,Debugger commands,,pdb --- The Python Debugger
@anchor{library/pdb command-line-interface}@anchor{47c6}@anchor{library/pdb pdb-cli}@anchor{2e2}
@subsubsection コマンドライン・インターフェース


You can also invoke @code{pdb} from the command line to debug other scripts.  For
example:

@example
python -m pdb [-c command] (-m module | -p pid | pyfile) [args ...]
@end example

モジュールとして pdb を起動すると、デバッグ中のプログラムが異常終了したときに pdb が自動的に事後デバッグモードに入ります。事後デバッグ後 (またはプログラムの正常終了後)、pdb はプログラムを再起動します。自動再起動を行った場合、pdb の状態 (ブレークポイントなど) はそのまま維持されるので、たいていの場合、プログラム終了時にデバッガーも終了させるよりも便利なはずです。

@geindex pdb コマンドラインオプション; -c
@geindex pdb コマンドラインオプション; --command
@anchor{library/pdb cmdoption-pdb-c}@anchor{47c7}@anchor{library/pdb cmdoption-pdb-command}@anchor{47c8}
@deffn {Option} @w{-}c, @w{-}@w{-}command <command>

To execute commands as if given in a @code{.pdbrc} file; see
@ref{47c9,,Debugger commands}.


バージョン 3.2 で変更: @code{-c} オプションが追加されました。

@end deffn

@geindex pdb コマンドラインオプション; -m
@anchor{library/pdb cmdoption-pdb-m}@anchor{47ca}
@deffn {Option} @w{-}m <module>

To execute modules similar to the way @code{python -m} does. As with a script,
the debugger will pause execution just before the first line of the module.


バージョン 3.7 で変更: @code{-m} オプションが追加されました。

@end deffn

@geindex pdb コマンドラインオプション; -p
@geindex pdb コマンドラインオプション; --pid
@anchor{library/pdb cmdoption-pdb-p}@anchor{270}@anchor{library/pdb cmdoption-pdb-pid}@anchor{47cb}
@deffn {Option} @w{-}p, @w{-}@w{-}pid <pid>

Attach to the process with the specified PID.


Added in version 3.14.

@end deffn

To attach to a running Python process for remote debugging, use the @code{-p} or
@code{--pid} option with the target process's PID:

@example
python -m pdb -p 1234
@end example

@cartouche
@quotation 注釈 
Attaching to a process that is blocked in a system call or waiting for I/O
will only work once the next bytecode instruction is executed or when the
process receives a signal.
@end quotation
@end cartouche

Typical usage to execute a statement under control of the debugger is:

@example
>>> import pdb
>>> def f(x):
...     print(1 / x)
>>> pdb.run("f(2)")
> <string>(1)<module>()
(Pdb) continue
0.5
>>>
@end example

クラッシュしたプログラムを調べるための典型的な使い方は以下のようになります:

@example
>>> import pdb
>>> def f(x):
...     print(1 / x)
...
>>> f(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
ZeroDivisionError: division by zero
>>> pdb.pm()
> <stdin>(2)f()
(Pdb) p x
0
(Pdb)
@end example


バージョン 3.13 で変更: The implementation of 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/} means that name assignments made via @code{pdb}
will immediately affect the active scope, even when running inside an
@ref{4a1,,optimized scope}.


このモジュールは以下の関数を定義しています。それぞれが少しづつ違った方法でデバッガに入ります:

@geindex run() (pdb モジュール)
@anchor{library/pdb pdb run}@anchor{45bc}
@deffn {の関数} pdb.run (statement, globals=None, locals=None)

デバッガーに制御された状態で (文字列またはコードオブジェクトとして与えられた) `statement' を実行します。あらゆるコードが実行される前にデバッガープロンプトが現れます。ブレークポイントを設定し、@ref{47c5,,continue} とタイプできます。あるいは、文を @ref{47cc,,step} や @ref{47cd,,next} を使って一つづつ実行することができます (これらのコマンドはすべて下で説明します)。オプションの `globals' と `locals' 引数はコードを実行する環境を指定します。デフォルトでは、モジュール @ref{1,,__main__} の辞書が使われます。(組み込み関数 @ref{4a2,,exec()} または @ref{4a3,,eval()} の説明を参照してください。)
@end deffn

@geindex runeval() (pdb モジュール)
@anchor{library/pdb pdb runeval}@anchor{47ce}
@deffn {の関数} pdb.runeval (expression, globals=None, locals=None)

デバッガーに制御された状態で (文字列またはコードオブジェクトとして与えられる) `expression' を評価します。@ref{47ce,,runeval()} から復帰するとき、式の値を返します。その他の点では、この関数は @ref{45bc,,run()} と同様です。
@end deffn

@geindex runcall() (pdb モジュール)
@anchor{library/pdb pdb runcall}@anchor{47cf}
@deffn {の関数} pdb.runcall (function, *args, **kwds)

`function' (関数またはメソッドオブジェクト、文字列ではありません) を与えられた引数とともに呼び出します。 @ref{47cf,,runcall()} から復帰するとき、関数呼び出しが返したものはなんでも返します。関数に入るとすぐにデバッガプロンプトが現れます。
@end deffn

@geindex set_trace() (pdb モジュール)
@anchor{library/pdb pdb set_trace}@anchor{272}
@deffn {の関数} pdb.set_trace (*, header=None, commands=None)

Enter the debugger at the calling stack frame.  This is useful to hard-code
a breakpoint at a given point in a program, even if the code is not
otherwise being debugged (e.g. when an assertion fails).  If given,
`header' is printed to the console just before debugging begins.
The `commands' argument, if given, is a list of commands to execute
when the debugger starts.


バージョン 3.7 で変更: `header' キーワード専用引数。



バージョン 3.13 で変更: @ref{272,,set_trace()} will enter the debugger immediately, rather than
on the next line of code to be executed.



Added in version 3.14: The `commands' argument.

@end deffn

@geindex set_trace_async() (pdb モジュール)
@anchor{library/pdb pdb set_trace_async}@anchor{279}
@deffn {の関数} awaitable pdb.set_trace_async (*, header=None, commands=None)

async version of @ref{272,,set_trace()}. This function should be used inside an
async function with @ref{18d,,await}.

@example
async def f():
    await pdb.set_trace_async()
@end example

@ref{18d,,await} statements are supported if the debugger is invoked by this function.


Added in version 3.14.

@end deffn

@geindex post_mortem() (pdb モジュール)
@anchor{library/pdb pdb post_mortem}@anchor{15f3}
@deffn {の関数} pdb.post_mortem (t=None)

Enter post-mortem debugging of the given exception or
@ref{cec,,traceback object}. If no value is given, it uses
the exception that is currently being handled, or raises @code{ValueError} if
there isn’t one.


バージョン 3.13 で変更: 例外オブジェクトのサポートが追加されました。

@end deffn

@geindex pm() (pdb モジュール)
@anchor{library/pdb pdb pm}@anchor{53f}
@deffn {の関数} pdb.pm ()

Enter post-mortem debugging of the exception found in
@ref{6e5,,sys.last_exc}.
@end deffn

@geindex set_default_backend() (pdb モジュール)
@anchor{library/pdb pdb set_default_backend}@anchor{47d0}
@deffn {の関数} pdb.set_default_backend (backend)

There are two supported backends for pdb: @code{'settrace'} and @code{'monitoring'}.
See @ref{2d5,,bdb.Bdb} for details. The user can set the default backend to
use if none is specified when instantiating @ref{273,,Pdb}. If no backend is
specified, the default is @code{'settrace'}.

@cartouche
@quotation 注釈 
@ref{271,,breakpoint()} and @ref{272,,set_trace()} will not be affected by this
function. They always use @code{'monitoring'} backend.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@geindex get_default_backend() (pdb モジュール)
@anchor{library/pdb pdb get_default_backend}@anchor{47d1}
@deffn {の関数} pdb.get_default_backend ()

Returns the default backend for pdb.


Added in version 3.14.

@end deffn

@code{run*} 関数と @ref{272,,set_trace()} は、 @ref{273,,Pdb} クラスをインスタンス化して同名のメソッドを実行することのエイリアス関数です。それ以上の機能を利用したい場合は、インスタンス化を自分で行わなければなりません:

@geindex Pdb (pdb のクラス)
@anchor{library/pdb pdb Pdb}@anchor{273}
@deffn {クラス} pdb.Pdb (completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True, mode=None, backend=None, colorize=False)

@ref{273,,Pdb} はデバッガクラスです。

`completekey', `stdin', `stdout' 引数は、基底にある @ref{184e,,cmd.Cmd} クラスに渡されます。そちらの解説を参照してください。

`skip' 引数が指定された場合、 glob スタイルのモジュール名パターンの iterable (イテレート可能オブジェクト) でなければなりません。デバッガはこのパターンのどれかにマッチするモジュールに属するフレームにはステップインしません。 @footnote{
フレームが属するモジュールは、そのフレームのグローバルの @code{__name__} によって決定されます。
}

デフォルトでは、Pdb は @ref{47c5,,continue} コマンドが投入されると、(ユーザーがコンソールから @code{Ctrl}-@code{C} を押したときに送られる) SIGINT シグナル用ハンドラーを設定します。これにより @code{Ctrl}-@code{C} を押すことで再度デバッガーを起動することができます。Pdb に SIGINT ハンドラーを変更させたくない場合は `nosigint' を true に設定してください。

`readrc' 引数はデフォルトでは真で、 Pdb が .pdbrc ファイルをファイルシステムから読み込むかどうかを制御します。

The `mode' argument specifies how the debugger was invoked.
It impacts the workings of some debugger commands.
Valid values are @code{'inline'} (used by the breakpoint() builtin),
@code{'cli'} (used by the command line invocation)
or @code{None} (for backwards compatible behaviour, as before the `mode'
argument was added).

The `backend' argument specifies the backend to use for the debugger. If @code{None}
is passed, the default backend will be used. See @ref{47d0,,set_default_backend()}.
Otherwise the supported backends are @code{'settrace'} and @code{'monitoring'}.

The `colorize' argument, if set to @code{True}, will enable colorized output in the
debugger, if color is supported. This will highlight source code displayed in pdb.

`skip' を使ってトレースする呼び出しの例:

@example
import pdb; pdb.Pdb(skip=['django.*']).set_trace()
@end example

引数無しで @ref{1c6e,,監査イベント} @code{pdb.Pdb} を送出します。


バージョン 3.1 で変更: `skip' パラメータが追加されました。



バージョン 3.2 で変更: Added the `nosigint' parameter.
Previously, a SIGINT handler was never set by Pdb.



バージョン 3.6 で変更: `readrc' 引数。



Added in version 3.14: `mode' 引数が追加されました。



Added in version 3.14: `backend' 引数が追加されました。



Added in version 3.14: `colorize' 引数が追加されました。



バージョン 3.14 で変更: Inline breakpoints like @ref{271,,breakpoint()} or @ref{272,,pdb.set_trace()} will
always stop the program at calling frame, ignoring the `skip' pattern (if any).


@geindex run() (pdb.Pdb のメソッド)
@geindex runeval() (pdb.Pdb のメソッド)
@geindex runcall() (pdb.Pdb のメソッド)
@geindex set_trace() (pdb.Pdb のメソッド)
@anchor{library/pdb pdb Pdb run}@anchor{47d2}
@deffn {メソッド} run (statement, globals=None, locals=None)
@anchor{library/pdb pdb Pdb runeval}@anchor{47d3}
@deffnx {メソッド} runeval (expression, globals=None, locals=None)
@anchor{library/pdb pdb Pdb runcall}@anchor{47d4}
@deffnx {メソッド} runcall (function, *args, **kwds)
@anchor{library/pdb pdb Pdb set_trace}@anchor{274}
@deffnx {メソッド} set_trace ()

前述のこれら関数のドキュメントを参照してください。
@end deffn
@end deffn

@node Debugger commands,,コマンドライン・インターフェース<8>,pdb --- The Python Debugger
@anchor{library/pdb debugger-commands}@anchor{47c9}@anchor{library/pdb id2}@anchor{47d5}
@subsubsection Debugger commands


デバッガーに認識されるコマンドは以下に一覧されています。たいていのコマンドは以下のように 1、2 文字に省略できます。例えば @code{h(elp)} は @code{h} か @code{help} がで help コマンドを呼び出すことを意味します (ただし @code{he}, @code{hel}, @code{H}, @code{Help}, @code{HELP} は使用できません)。コマンドの引数はホワイトスペース (スペースかタブ) で区切ってください。コマンド構文として任意の引数は大括弧 (@code{[]}) で括られています (実際に大括弧はタイプしないでください)。いくつかから選択できる引数は縦線 (@code{|}) で分割されて記述されています。

空行を入力すると入力された直前のコマンドを繰り返します。例外: 直前のコマンドが @ref{47d6,,list} コマンドならば、次の 11 行がリストされます。

デバッガが認識しないコマンドは Python 文とみなして、デバッグしているプログラムのコンテキストおいて実行されます。先頭にに感嘆符 (@code{!}) を付けることで Python 文であると明示することもできます。これはデバッグ中のプログラムを調査する強力な方法です。変数を変更したり関数を呼び出したりすることも可能です。このような文で例外が発生した場合には例外名が出力されますが、デバッガの状態は変化しません。


バージョン 3.13 で変更: Expressions/Statements whose prefix is a pdb command are now correctly
identified and executed.


デバッガーは @ref{47d7,,エイリアス} をサポートしています。エイリアスはデバッグ中のコンテキストに適用可能な一定レベルのパラメータを保持することができます。

Multiple commands may be entered on a single line, separated by @code{;;}.  (A
single @code{;} is not used as it is the separator for multiple commands in a line
that is passed to the Python parser.)  No intelligence is applied to separating
the commands; the input is split at the first @code{;;} pair, even if it is in the
middle of a quoted string. A workaround for strings with double semicolons
is to use implicit string concatenation @code{';'@w{'};'} or @code{";"";"}.

To set a temporary global variable, use a `convenience variable'. A `convenience
variable' is a variable whose name starts with @code{$}.  For example, @code{$foo = 1}
sets a global variable @code{$foo} which you can use in the debugger session.  The
`convenience variables' are cleared when the program resumes execution so it's
less likely to interfere with your program compared to using normal variables
like @code{foo = 1}.

There are four preset `convenience variables':


@itemize *

@item 
@code{$_frame}: the current frame you are debugging

@item 
@code{$_retval}: the return value if the frame is returning

@item 
@code{$_exception}: the exception if the frame is raising an exception

@item 
@code{$_asynctask}: the asyncio task if pdb stops in an async function
@end itemize


Added in version 3.12: Added the `convenience variable' feature.



Added in version 3.14: Added the @code{$_asynctask} convenience variable.


@geindex .pdbrc;ファイル
@geindex debugger;設定;ファイル

If a file @code{.pdbrc} exists in the user's home directory or in the current
directory, it is read with @code{'utf-8'} encoding and executed as if it had been
typed at the debugger prompt, with the exception that empty lines and lines
starting with @code{#} are ignored.  This is particularly useful for aliases.  If both
files exist, the one in the home directory is read first and aliases defined there
can be overridden by the local file.


バージョン 3.2 で変更: @code{.pdbrc} に @ref{47c5,,continue} や @ref{47cd,,next} のようなデバッグを続行するコマンドが使用できるようになりました。以前はこのようなコマンドは無視されていました。



バージョン 3.11 で変更: @code{.pdbrc} is now read with @code{'utf-8'} encoding. Previously, it was read
with the system locale encoding.


@geindex help (pdb command)
@anchor{library/pdb pdbcommand-help}@anchor{47d8}
@deffn {Pdbcommand} h(elp) [command]

引数を指定しない場合、利用できるコマンドの一覧が表示されます。引数として `command' が与えられた場合、そのコマンドのヘルプが表示されます。@code{help pdb} で完全なドキュメント (@ref{aa,,pdb} モジュールの doctring) が表示されます。`command' 引数は識別子でなければならないため、@code{!} コマンドのヘルプを表示するには @code{help exec} と入力します。
@end deffn

@geindex where (pdb command)
@anchor{library/pdb pdbcommand-where}@anchor{47d9}
@deffn {Pdbcommand} w(here) [count]

Print a stack trace, with the most recent frame at the bottom.  if `count'
is 0, print the current frame entry. If `count' is negative, print the least
recent - `count' frames. If `count' is positive, print the most recent
`count' frames.  An arrow (@code{>})
indicates the current frame, which determines the context of most commands.


バージョン 3.14 で変更: `count' argument is added.

@end deffn

@geindex down (pdb command)
@anchor{library/pdb pdbcommand-down}@anchor{47da}
@deffn {Pdbcommand} d(own) [count]

スタックフレーム内で現在のフレームを `count' レベル (デフォルトは 1) 新しいフレーム方向に移動します。
@end deffn

@geindex up (pdb command)
@anchor{library/pdb pdbcommand-up}@anchor{47db}
@deffn {Pdbcommand} u(p) [count]

スタックフレーム内で現在のフレームを `count' レベル (デフォルトは 1) 古いフレーム方向に移動します。
@end deffn

@geindex break (pdb command)
@anchor{library/pdb pdbcommand-break}@anchor{47dc}
@deffn {Pdbcommand} b(reak) [([filename:]lineno | function) [, condition]]

With a `lineno' argument, set a break at line `lineno' in the current file.
The line number may be prefixed with a `filename' and a colon,
to specify a breakpoint in another file (possibly one that hasn't been loaded
yet).  The file is searched on @ref{3e4,,sys.path}.  Acceptable forms of `filename'
are @code{/abspath/to/file.py}, @code{relpath/file.py}, @code{module} and
@code{package.module}.

With a `function' argument, set a break at the first executable statement within
that function. `function' can be any expression that evaluates to a function
in the current namespace.

第二引数を指定する場合、その値は式で、その評価値が真でなければブレークポイントは有効になりません。

引数なしの場合は、それぞれのブレークポイントに対して、そのブレークポイントに行き当たった回数、現在の通過カウント ( ignore count ) と、もしあれば関連条件を含めてすべてのブレークポイントをリストします。

Each breakpoint is assigned a number to which all the other
breakpoint commands refer.
@end deffn

@geindex tbreak (pdb command)
@anchor{library/pdb pdbcommand-tbreak}@anchor{47dd}
@deffn {Pdbcommand} tbreak [([filename:]lineno | function) [, condition]]

一時的なブレークポイントで、最初にそこに達したときに自動的に取り除かれます。引数は @ref{47dc,,break} と同じです。
@end deffn

@geindex clear (pdb command)
@anchor{library/pdb pdbcommand-clear}@anchor{47de}
@deffn {Pdbcommand} cl(ear) [filename:lineno | bpnumber ...]

`filename:lineno' 引数を与えると、その行にある全てのブレークポイントを解除します。スペースで区切られたブレークポイントナンバーのリストを与えると、それらのブレークポイントを解除します。引数なしの場合は、すべてのブレークポイントを解除します ( が、はじめに確認します ) 。
@end deffn

@geindex disable (pdb command)
@anchor{library/pdb pdbcommand-disable}@anchor{47df}
@deffn {Pdbcommand} disable bpnumber [bpnumber ...]

ブレークポイント番号 `bpnumber' のブレークポイントを無効にします。ブレークポイントを無効にすると、プログラムの実行を止めることができなくなりますが、ブレークポイントの解除と違いブレークポイントのリストに残っており、(再び) 有効にできます。
@end deffn

@geindex enable (pdb command)
@anchor{library/pdb pdbcommand-enable}@anchor{47e0}
@deffn {Pdbcommand} enable bpnumber [bpnumber ...]

指定したブレークポイントを有効にします。
@end deffn

@geindex ignore (pdb command)
@anchor{library/pdb pdbcommand-ignore}@anchor{47e1}
@deffn {Pdbcommand} ignore bpnumber [count]

与えられたブレークポイントナンバーに通過カウントを設定します。count が省略されると、通過カウントは 0 に設定されます。通過カウントがゼロになったとき、ブレークポイントが機能する状態になります。ゼロでないときは、そのブレークポイントが無効にされず、どんな関連条件も真に評価されていて、ブレークポイントに来るたびに `count' が減らされます。
@end deffn

@geindex condition (pdb command)
@anchor{library/pdb pdbcommand-condition}@anchor{47e2}
@deffn {Pdbcommand} condition bpnumber [condition]

ブレークポイントに新しい `condition' を設定します。`condition' はブレークポイントを制御する条件式で、この式が真を返す場合のみブレークポイントが有効になります。`condition' を指定しないと既存の条件が除去されます; ブレークポイントは常に有効になります。
@end deffn

@geindex commands (pdb command)
@anchor{library/pdb pdbcommand-commands}@anchor{276}
@deffn {Pdbcommand} commands [bpnumber]

ブレークポイントナンバー `bpnumber' にコマンドのリストを指定します。コマンドそのものはその後の行に続けます。@code{end} だけからなる行を入力することでコマンド群の終わりを示します。例を挙げます:

@example
(Pdb) commands 1
(com) p some_variable
(com) end
(Pdb)
@end example

ブレークポイントからコマンドを取り除くには、 @code{commands} のあとに @code{end} だけを続けます。つまり、コマンドを一つも指定しないようにします。

`bpnumber' 引数を指定しない場合、@code{commands} は最後にセットしたブレークポイントを参照します。

ブレークポイントコマンドはプログラムを走らせ直すのに使えます。単に @ref{47c5,,continue} コマンドや @ref{47cc,,step}、その他実行を再開するコマンドを使えば良いのです。

Specifying any command resuming execution
(currently @ref{47c5,,continue}, @ref{47cc,,step}, @ref{47cd,,next},
@ref{47e3,,return}, @ref{47e4,,until}, @ref{47e5,,jump}, @ref{47e6,,quit} and their abbreviations)
terminates the command list (as if
that command was immediately followed by end). This is because any time you
resume execution (even with a simple next or step), you may encounter another
breakpoint—which could have its own command list, leading to ambiguities about
which list to execute.

If the list of commands contains the @code{silent} command, or a command that
resumes execution, then the breakpoint message containing information about
the frame is not displayed.


バージョン 3.14 で変更: Frame information will not be displayed if a command that resumes execution
is present in the command list.

@end deffn

@geindex step (pdb command)
@anchor{library/pdb pdbcommand-step}@anchor{47cc}
@deffn {Pdbcommand} s(tep)

現在の行を実行し、最初に実行可能なものがあらわれたときに (呼び出された関数の中か、現在の関数の次の行で) 停止します。
@end deffn

@geindex next (pdb command)
@anchor{library/pdb pdbcommand-next}@anchor{47cd}
@deffn {Pdbcommand} n(ext)

現在の関数の次の行に達するか、あるいは関数が返るまで実行を継続します。 (@ref{47cd,,next} と @ref{47cc,,step} の差は @ref{47cc,,step} が呼び出された関数の内部で停止するのに対し、 @ref{47cd,,next} は呼び出された関数を (ほぼ) 全速力で実行し、現在の関数内の次の行で停止するだけです。)
@end deffn

@geindex until (pdb command)
@anchor{library/pdb pdbcommand-until}@anchor{47e4}
@deffn {Pdbcommand} unt(il) [lineno]

引数なしだと、現在の行から 1 行先まで実行します。

`lineno' を指定すると、番号が `lineno' 以上である行に到達するまで実行します。どちらにしても現在のフレームが返ってきた時点で停止します。


バージョン 3.2 で変更: 明示的に行数指定ができるようになりました。

@end deffn

@geindex return (pdb command)
@anchor{library/pdb pdbcommand-return}@anchor{47e3}
@deffn {Pdbcommand} r(eturn)

現在の関数が返るまで実行を継続します。
@end deffn

@geindex continue (pdb command)
@anchor{library/pdb pdbcommand-continue}@anchor{47c5}
@deffn {Pdbcommand} c(ont(inue))

ブレークポイントに出会うまで、実行を継続します。
@end deffn

@geindex jump (pdb command)
@anchor{library/pdb pdbcommand-jump}@anchor{47e5}
@deffn {Pdbcommand} j(ump) lineno

次に実行する行を指定します。最も底のフレーム中でのみ実行可能です。前に戻って実行したり、不要な部分をスキップして先の処理を実行する場合に使用します。

ジャンプには制限があり、例えば @ref{34a,,for} ループの中には飛び込めませんし、 @ref{1b0,,finally} 節の外にも飛ぶ事ができません。
@end deffn

@geindex list (pdb command)
@anchor{library/pdb pdbcommand-list}@anchor{47d6}
@deffn {Pdbcommand} l(ist) [first[, last]]

現在のファイルのソースコードを表示します。引数を指定しないと、現在の行の前後 11 行分を表示するか、直前の表示を続行します。引数に @code{.} を指定すると、現在の行の前後 11 行分を表示します。数値を 1 個指定すると、その行番号の前後 11 行分を表示します。数値を 2 個指定すると、開始行と最終行として表示します; 2 個めの引数が 1 個め未満だった場合、1 個目を開始行、2 個めを開始行からの行数とみなします。

現在のフレーム内の現在の行は @code{->} で表示されます。例外をデバッグ中の場合、例外が発生または伝搬した行は、それが現在の行とは異なるとき @code{>>} で表示されます。


バージョン 3.2 で変更: @code{>>} マーカーが追加されました。

@end deffn

@geindex ll (pdb command)
@anchor{library/pdb pdbcommand-ll}@anchor{47e7}
@deffn {Pdbcommand} ll | longlist

現在の関数またはフレームの全ソースコードを表示します。注目する行は @ref{47d6,,list} と同じようにマーカーがつきます。


Added in version 3.2.

@end deffn

@geindex args (pdb command)
@anchor{library/pdb pdbcommand-args}@anchor{47e8}
@deffn {Pdbcommand} a(rgs)

Print the arguments of the current function and their current values.
@end deffn

@geindex p (pdb command)
@anchor{library/pdb pdbcommand-p}@anchor{1178}
@deffn {Pdbcommand} p expression

現在のコンテキストにおいて `expression' を評価し、その値をプリントします。

@cartouche
@quotation 注釈 
@code{print()} も使えますが、これはデバッガーコマンドではありません --- これは Python の関数 @ref{1177,,print()} が実行されます。
@end quotation
@end cartouche
@end deffn

@geindex pp (pdb command)
@anchor{library/pdb pdbcommand-pp}@anchor{47e9}
@deffn {Pdbcommand} pp expression

@ref{1178,,p} コマンドに似ていますが、`expression' の値以外は @ref{b3,,pprint} モジュールを使用して "pretty-print" されます。
@end deffn

@geindex whatis (pdb command)
@anchor{library/pdb pdbcommand-whatis}@anchor{47ea}
@deffn {Pdbcommand} whatis expression

`expression' の型を表示します。
@end deffn

@geindex source (pdb command)
@anchor{library/pdb pdbcommand-source}@anchor{47eb}
@deffn {Pdbcommand} source expression

`expression' のソースコードの取得を試み、可能であれば表示します。


Added in version 3.2.

@end deffn

@geindex display (pdb command)
@anchor{library/pdb pdbcommand-display}@anchor{275}
@deffn {Pdbcommand} display [expression]

`expression' の値が変更されていれば表示します。毎回実行は現在のフレームで停止します。

`expression' を指定しない場合、現在のフレームのすべての式を表示します。

@cartouche
@quotation 注釈 
Display evaluates `expression' and compares to the result of the previous
evaluation of `expression', so when the result is mutable, display may not
be able to pick up the changes.
@end quotation
@end cartouche

以下はプログラム例です:

@example
lst = []
breakpoint()
pass
lst.append(1)
print(lst)
@end example

Display won't realize @code{lst} has been changed because the result of evaluation
is modified in place by @code{lst.append(1)} before being compared:

@example
> example.py(3)<module>()
-> pass
(Pdb) display lst
display lst: []
(Pdb) n
> example.py(4)<module>()
-> lst.append(1)
(Pdb) n
> example.py(5)<module>()
-> print(lst)
(Pdb)
@end example

You can do some tricks with copy mechanism to make it work:

@example
> example.py(3)<module>()
-> pass
(Pdb) display lst[:]
display lst[:]: []
(Pdb) n
> example.py(4)<module>()
-> lst.append(1)
(Pdb) n
> example.py(5)<module>()
-> print(lst)
display lst[:]: [1]  [old: []]
(Pdb)
@end example


Added in version 3.2.

@end deffn

@geindex undisplay (pdb command)
@anchor{library/pdb pdbcommand-undisplay}@anchor{47ec}
@deffn {Pdbcommand} undisplay [expression]

現在のフレーム内で `expression' をこれ以上表示しないようにします。`expression' を指定しない場合、現在のフレームで display 指定されている式を全てクリアします。


Added in version 3.2.

@end deffn

@geindex interact (pdb command)
@anchor{library/pdb pdbcommand-interact}@anchor{47ed}
@deffn {Pdbcommand} interact

Start an interactive interpreter (using the @ref{1b,,code} module) in a new
global namespace initialised from the local and global namespaces for the
current scope. Use @code{exit()} or @code{quit()} to exit the interpreter and
return to the debugger.

@cartouche
@quotation 注釈 
As @code{interact} creates a new dedicated namespace for code execution,
assignments to variables will not affect the original namespaces.
However, modifications to any referenced mutable objects will be reflected
in the original namespaces as usual.
@end quotation
@end cartouche


Added in version 3.2.



バージョン 3.13 で変更: @code{exit()} and @code{quit()} can be used to exit the @ref{47ed,,interact}
command.



バージョン 3.13 で変更: @ref{47ed,,interact} directs its output to the debugger's
output channel rather than @ref{b33,,sys.stderr}.

@end deffn

@geindex alias (pdb command)
@anchor{library/pdb debugger-aliases}@anchor{47d7}@anchor{library/pdb pdbcommand-alias}@anchor{47ee}
@deffn {Pdbcommand} alias [name [command]]

Create an alias called `name' that executes `command'.  The `command' must
`not' be enclosed in quotes.  Replaceable parameters can be indicated by
@code{%1}, @code{%2}, ... and @code{%9}, while @code{%*} is replaced by all the parameters.
If `command' is omitted, the current alias for `name' is shown. If no
arguments are given, all aliases are listed.

エイリアスは入れ子になってもよく、pdb プロンプトで合法的にタイプできるどんなものでも含めることができます。内部 pdb コマンドをエイリアスによって上書きすることが `できます'。そのとき、このようなコマンドはエイリアスが取り除かれるまで隠されます。エイリアス化はコマンド行の最初の語へ再帰的に適用されます。行の他のすべての語はそのままです。

例として、二つの便利なエイリアスがあります (特に @code{.pdbrc} ファイルに置かれたときに):

@example
# Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print(f"%1.@{k@} = @{%1.__dict__[k]@}")
# Print instance variables in self
alias ps pi self
@end example
@end deffn

@geindex unalias (pdb command)
@anchor{library/pdb pdbcommand-unalias}@anchor{47ef}
@deffn {Pdbcommand} unalias name

指定したエイリアス `name' を削除します。
@end deffn

@geindex ! (pdb command)
@anchor{library/pdb pdbcommand-0}@anchor{47f0}
@deffn {Pdbcommand} ! statement

Execute the (one-line) `statement' in the context of the current stack frame.
The exclamation point can be omitted unless the first word of the statement
resembles a debugger command, e.g.:

@example
(Pdb) ! n=42
(Pdb)
@end example

To set a global variable, you can prefix the assignment command with a
@ref{4ac,,global} statement on the same line, e.g.:

@example
(Pdb) global list_options; list_options = ['-l']
(Pdb)
@end example
@end deffn

@geindex run (pdb command)
@geindex restart (pdb command)
@anchor{library/pdb pdbcommand-run}@anchor{47f1}
@deffn {Pdbcommand} run [args ...]
@anchor{library/pdb pdbcommand-restart}@anchor{47f2}
@deffnx {Pdbcommand} restart [args ...]

デバッグ中の Python プログラムを再実行します。`args' が与えられると、 @ref{c9,,shlex} で分割され、結果が新しい @ref{147c,,sys.argv} として使われます。ヒストリー、ブレークポイント、アクション、そして、デバッガーオプションは引き継がれます。 @ref{47f2,,restart} は @ref{47f1,,run} の別名です。


バージョン 3.14 で変更: @ref{47f1,,run} and @ref{47f2,,restart} commands are disabled when the
debugger is invoked in @code{'inline'} mode.

@end deffn

@geindex quit (pdb command)
@anchor{library/pdb pdbcommand-quit}@anchor{47e6}
@deffn {Pdbcommand} q(uit)

Quit from the debugger.  The program being executed is aborted.
An end-of-file input is equivalent to @ref{47e6,,quit}.

A confirmation prompt will be shown if the debugger is invoked in
@code{'inline'} mode. Either @code{y}, @code{Y}, @code{<Enter>} or @code{EOF}
will confirm the quit.


バージョン 3.14 で変更: A confirmation prompt will be shown if the debugger is invoked in
@code{'inline'} mode. After the confirmation, the debugger will call
@ref{277,,sys.exit()} immediately, instead of raising @ref{278,,bdb.BdbQuit}
in the next trace event.

@end deffn

@geindex debug (pdb command)
@anchor{library/pdb pdbcommand-debug}@anchor{47f3}
@deffn {Pdbcommand} debug code

Enter a recursive debugger that steps through `code'
(which is an arbitrary expression or statement to be
executed in the current environment).
@end deffn

@geindex retval (pdb command)
@anchor{library/pdb pdbcommand-retval}@anchor{47f4}
@deffn {Pdbcommand} retval

Print the return value for the last return of the current function.
@end deffn

@geindex exceptions (pdb command)
@anchor{library/pdb pdbcommand-exceptions}@anchor{540}
@deffn {Pdbcommand} exceptions [excnumber]

List or jump between chained exceptions.

When using @code{pdb.pm()}  or @code{Pdb.post_mortem(...)} with a chained exception
instead of a traceback, it allows the user to move between the
chained exceptions using @code{exceptions} command to list exceptions, and
@code{exceptions <number>} to switch to that exception.

以下はプログラム例です:

@example
def out():
    try:
        middle()
    except Exception as e:
        raise ValueError("reraise middle() error") from e

def middle():
    try:
        return inner(0)
    except Exception as e:
        raise ValueError("Middle fail")

def inner(x):
    1 / x

 out()
@end example

calling @code{pdb.pm()} will allow to move between exceptions:

@example
> example.py(5)out()
-> raise ValueError("reraise middle() error") from e

(Pdb) exceptions
  0 ZeroDivisionError('division by zero')
  1 ValueError('Middle fail')
> 2 ValueError('reraise middle() error')

(Pdb) exceptions 0
> example.py(16)inner()
-> 1 / x

(Pdb) up
> example.py(10)middle()
-> return inner(0)
@end example


Added in version 3.13.

@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python プロファイラ,timeit --- 小さなコードスニペットの実行時間計測,pdb --- The Python Debugger,デバッグとプロファイル
@anchor{library/profile doc}@anchor{47f5}@anchor{library/profile profile}@anchor{47f6}@anchor{library/profile the-python-profilers}@anchor{47f7}@anchor{library/profile translation-repo}@anchor{47f8}
@subsection Python プロファイラ


`ソースコード:' Lib/profile.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/profile.py} と Lib/pstats.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pstats.py}


__________________________________________________________________


@menu
* プロファイラとは:: 
* かんたんユーザマニュアル:: 
* profile and cProfile Module Reference:: 
* Stats クラス:: 
* 決定論的プロファイリングとは:: 
* 制限事項: 制限事項<2>. 
* キャリブレーション (補正): キャリブレーション 補正. 
* カスタムな時刻取得用関数を使う:: 

@end menu

@node プロファイラとは,かんたんユーザマニュアル,,Python プロファイラ
@anchor{library/profile introduction-to-the-profilers}@anchor{47f9}@anchor{library/profile profiler-introduction}@anchor{47fa}
@subsubsection プロファイラとは


@geindex deterministic profiling
@geindex profiling@comma{} deterministic

@ref{2b,,cProfile} と @ref{b4,,profile} は `決定論的プロファイリング (deterministic profiling)' を行います。 `プロファイル (profile)' とは、プログラムの各部分がどれだけ頻繁に呼ばれたか、そして実行にどれだけ時間がかかったかという統計情報です。 @ref{b5,,pstats} モジュールを使ってこの統計情報をフォーマットし表示することができます。

Python 標準ライブラリは同じインターフェイスを提供するプロファイラの実装を2つ提供しています:


@enumerate 

@item 
@ref{2b,,cProfile} はほとんどのユーザーに推奨されるモジュールです。 C言語で書かれた拡張モジュールで、オーバーヘッドが少ないため長時間実行されるプログラムのプロファイルに適しています。 Brett Rosen と Ted Czotter によって提供された @code{lsprof} に基づいています。

@item 
@ref{b4,,profile} はピュア Python モジュールで、 @ref{2b,,cProfile} モジュールはこのモジュールのインターフェースを真似ています。対象プログラムに相当のオーバーヘッドが生じます。もしプロファイラに何らかの拡張をしたいのであれば、こちらのモジュールを拡張する方が簡単でしょう。このモジュールはもともと Jim Roskind により設計、実装されました。
@end enumerate

@cartouche
@quotation 注釈 
2つのプロファイラモジュールは、与えられたプログラムの実行時プロファイルを取得するために設計されており、ベンチマークのためのものではありません (ベンチマーク用途には @ref{f5,,timeit} のほうが正確な計測結果を求められます)。これは Python コードと C で書かれたコードをベンチマークするときに特に大きく影響します。プロファイラは Python コードに対してオーバーヘッドを発生しますが、C言語レベルの関数に対してはオーバーヘッドを生じません。なのでC言語で書かれたコードが、実際の速度と関係なく、Pythonで書かれたコードより速く見えるでしょう。
@end quotation
@end cartouche

@node かんたんユーザマニュアル,profile and cProfile Module Reference,プロファイラとは,Python プロファイラ
@anchor{library/profile instant-user-s-manual}@anchor{47fb}@anchor{library/profile profile-instant}@anchor{47fc}
@subsubsection かんたんユーザマニュアル


この節は "マニュアルなんか読みたくない人"のために書かれています。ここではきわめて簡単な概要説明とアプリケーションのプロファイリングを手っ取り早く行う方法だけを解説します。

1つの引数を取る関数をプロファイルしたい場合、次のようにできます:

@example
import cProfile
import re
cProfile.run('re.compile("foo|bar")')
@end example

(お使いのシステムで @ref{2b,,cProfile} が使えないときは代わりに @ref{b4,,profile} を使って下さい)

上のコードは @ref{dce,,re.compile()} を実行して、プロファイル結果を次のように表示します:

@example
      214 function calls (207 primitive calls) in 0.002 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.000    0.000    0.002    0.002 @{built-in method builtins.exec@}
     1    0.000    0.000    0.001    0.001 <string>:1(<module>)
     1    0.000    0.000    0.001    0.001 __init__.py:250(compile)
     1    0.000    0.000    0.001    0.001 __init__.py:289(_compile)
     1    0.000    0.000    0.000    0.000 _compiler.py:759(compile)
     1    0.000    0.000    0.000    0.000 _parser.py:937(parse)
     1    0.000    0.000    0.000    0.000 _compiler.py:598(_code)
     1    0.000    0.000    0.000    0.000 _parser.py:435(_parse_sub)
@end example

The first line indicates that 214 calls were monitored.  Of those calls, 207
were `primitive', meaning that the call was not induced via recursion. The
next line: @code{Ordered by: cumulative time} indicates the output is sorted
by the @code{cumtime} values. The column headings include:


@table @asis

@item ncalls

呼び出し回数

@item tottime

与えられた関数に消費された合計時間 (sub-function の呼び出しで消費された時間は除外されています)

@item percall

@code{tottime} を @code{ncalls} で割った値

@item cumtime

この関数と全ての subfunction に消費された累積時間 (起動から終了まで)。この数字は再帰関数に `ついても' 正確です。

@item percall

@code{cumtime} をプリミティブな呼び出し回数で割った値

@item filename:lineno(function)

その関数のファイル名、行番号、関数名
@end table

最初の行に 2 つの数字がある場合 (たとえば @code{3/1}) は、関数が再帰的に呼び出されたということです。2 つ目の数字はプリミティブな呼び出しの回数で、1 つ目の数字は総呼び出し回数です。関数が再帰的に呼び出されなかった場合、それらは同じ値で数字は 1 つしか表示されないことに留意してください。

@code{run()} 関数でファイル名を指定することで、プロファイル実行の終了時に出力を表示する代わりに、ファイルに保存することが出来ます。

@example
import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')
@end example

@ref{47fd,,pstats.Stats} クラスはファイルからプロファイルの結果を読み込んで様々な書式に整えます。
@anchor{library/profile profile-cli}@anchor{47fe}
ファイル @ref{2b,,cProfile} と @ref{b4,,profile} は他のスクリプトをプロファイルするためのスクリプトとして起動することも出来ます。例えば:

@example
python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)
@end example

@geindex cProfile コマンドラインオプション; -o
@anchor{library/profile cmdoption-cProfile-o}@anchor{47ff}
@deffn {Option} @w{-}o <output_file>

Writes the profile results to a file instead of to stdout.
@end deffn

@geindex cProfile コマンドラインオプション; -s
@anchor{library/profile cmdoption-cProfile-s}@anchor{4800}
@deffn {Option} @w{-}s <sort_order>

Specifies one of the @ref{4801,,sort_stats()} sort values
to sort the output by.
This only applies when @ref{47ff,,-o} is not supplied.
@end deffn

@geindex cProfile コマンドラインオプション; -m
@anchor{library/profile cmdoption-cProfile-m}@anchor{4802}
@deffn {Option} @w{-}m <module>

Specifies that a module is being profiled instead of a script.


Added in version 3.7: Added the @code{-m} option to @ref{2b,,cProfile}.



Added in version 3.8: Added the @code{-m} option to @ref{b4,,profile}.

@end deffn

@ref{b5,,pstats} モジュールの @ref{47fd,,Stats} クラスにはプロファイル結果のファイルに保存されているデータを処理して出力するための様々なメソッドがあります。

@example
import pstats
from pstats import SortKey
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()
@end example

@ref{4803,,strip_dirs()} メソッドによって全モジュール名から無関係なパスが取り除かれました。@ref{4801,,sort_stats()} メソッドにより、出力される標準的な モジュール/行/名前 文字列にしたがって全項目がソートされました。@ref{4804,,print_stats()} メソッドによって全統計が出力されました。以下のようなソート呼び出しを試すことができます:

@example
p.sort_stats(SortKey.NAME)
p.print_stats()
@end example

最初の行ではリストを関数名でソートしています。2行目で情報を出力しています。さらに次の内容も試してください:

@example
p.sort_stats(SortKey.CUMULATIVE).print_stats(10)
@end example

このようにすると、関数が消費した累計時間でソートして、さらにその上位10件だけを表示します。どのアルゴリズムが時間を多く消費しているのか知りたいときは、この方法が役に立つはずです。

ループで多くの時間を消費している関数はどれか調べたいときは、次のようにします:

@example
p.sort_stats(SortKey.TIME).print_stats(10)
@end example

上記はそれぞれの関数で消費された時間でソートして、上位10件の関数の情報が表示されます。

次の内容も試してください:

@example
p.sort_stats(SortKey.FILENAME).print_stats('__init__')
@end example

このようにするとファイル名でソートされ、そのうちクラスの初期化メソッド (メソッド名 @code{__init__}) に関する統計情報だけが表示されます:

@example
p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init')
@end example

上記は時間 (time) をプライマリキー、累計時間 (cumulative time) をセカンダリキーにしてソートした後でさらに条件を絞って統計情報を出力します。 @code{.5} は上位 50% だけを選択することを意味し、さらにその中から文字列 @code{init} を含むものだけが表示されます。

どの関数がどの関数を呼び出しているのかを知りたければ、次のようにします (@code{p} は最後に実行したときの状態でソートされています):

@example
p.print_callers(.5, 'init')
@end example

このようにすると、関数ごとの呼び出し側関数の一覧が得られます。

さらに詳しい機能を知りたければマニュアルを読むか、次の関数の実行結果から内容を推察してください:

@example
p.print_callees()
p.add('restats')
@end example

スクリプトとして起動した場合、 @ref{b5,,pstats} モジュールはプロファイルのダンプを読み込み、分析するための統計ブラウザとして動きます。シンプルな行指向のインターフェース (@ref{1a,,cmd} を使って実装) とヘルプ機能を備えています。

@node profile and cProfile Module Reference,Stats クラス,かんたんユーザマニュアル,Python プロファイラ
@anchor{library/profile module-cProfile}@anchor{2b}@anchor{library/profile profile-and-cprofile-module-reference}@anchor{4805}
@subsubsection @code{profile} and @code{cProfile} Module Reference


@geindex module; cProfile

@geindex module; profile
@anchor{library/profile module-profile}@anchor{b4}
Both the @ref{b4,,profile} and @code{cProfile} modules provide the following
functions:

@geindex run() (profile モジュール)
@anchor{library/profile profile run}@anchor{4806}
@deffn {の関数} profile.run (command, filename=None, sort=-1)

この関数は @ref{4a2,,exec()} 関数に渡せる一つの引数と、オプション引数としてファイル名を指定できます。全ての場合でこのルーチンは以下を実行します:

@example
exec(command, __main__.__dict__, __main__.__dict__)
@end example

そして実行結果からプロファイル情報を収集します。
ファイル名が指定されていない場合は、 @ref{47fd,,Stats} のインスタンスが自動的に作られ、簡単なプロファイルレポートが表示されます。
`sort' が指定されている場合は、 @ref{47fd,,Stats} インスタンスに渡され、結果をどのように並び替えるかを制御します。
@end deffn

@geindex runctx() (profile モジュール)
@anchor{library/profile profile runctx}@anchor{4807}
@deffn {の関数} profile.runctx (command, globals, locals, filename=None, sort=-1)

This function is similar to @ref{4806,,run()}, with added arguments to supply the
globals and locals mappings for the `command' string. This routine
executes:

@example
exec(command, globals, locals)
@end example

そしてプロファイル統計情報を @ref{4806,,run()} 同様に収集します。
@end deffn

@geindex Profile (profile のクラス)
@anchor{library/profile profile Profile}@anchor{bd6}
@deffn {クラス} profile.Profile (timer=None, timeunit=0.0, subcalls=True, builtins=True)

このクラスは普通、プロファイリングを @code{cProfile.run()} 関数が提供するもの以上に正確に制御したい場合にのみ使われます。

`timer' 引数に、コードの実行時間を計測するためのカスタムな時刻取得用関数を渡せます。これは現在時刻を表す単一の数値を返す関数でなければなりません。もしこれが整数を返す関数ならば、 `timeunit' には単位時間当たりの実際の持続時間を指定します。たとえば関数が 1000 分の 1 秒単位で計測した時間を返すとすると、 `timeunit' は @code{.001} でしょう。

@ref{bd6,,Profile} クラスを直接使うと、プロファイルデータをファイルに書き出すことなしに結果をフォーマット出来ます:

@example
import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
@end example

The @ref{bd6,,Profile} class can also be used as a context manager (supported
only in @code{cProfile} module. see @ref{240d,,コンテキストマネージャ型}):

@example
import cProfile

with cProfile.Profile() as pr:
    # ... do something ...

    pr.print_stats()
@end example


バージョン 3.8 で変更: コンテキストマネージャーサポートが追加されました。


@geindex enable() (profile.Profile のメソッド)
@anchor{library/profile profile Profile enable}@anchor{4808}
@deffn {メソッド} enable ()

Start collecting profiling data. Only in @code{cProfile}.
@end deffn

@geindex disable() (profile.Profile のメソッド)
@anchor{library/profile profile Profile disable}@anchor{4809}
@deffn {メソッド} disable ()

Stop collecting profiling data. Only in @code{cProfile}.
@end deffn

@geindex create_stats() (profile.Profile のメソッド)
@anchor{library/profile profile Profile create_stats}@anchor{480a}
@deffn {メソッド} create_stats ()

プロファイリングデータの収集を停止し、現在のプロファイルとして結果を内部で記録します。
@end deffn

@geindex print_stats() (profile.Profile のメソッド)
@anchor{library/profile profile Profile print_stats}@anchor{480b}
@deffn {メソッド} print_stats (sort=-1)

現在のプロファイルに基づいて @ref{47fd,,Stats} オブジェクトを作成し、結果を標準出力に出力します。

The `sort' parameter specifies the sorting order of the displayed
statistics. It accepts a single key or a tuple of keys to enable
multi-level sorting, as in @ref{4801,,Stats.sort_stats}.


Added in version 3.13: @ref{480b,,print_stats()} now accepts a tuple of keys.

@end deffn

@geindex dump_stats() (profile.Profile のメソッド)
@anchor{library/profile profile Profile dump_stats}@anchor{480c}
@deffn {メソッド} dump_stats (filename)

現在のプロファイルの結果を `filename' に書き出します。
@end deffn

@geindex run() (profile.Profile のメソッド)
@anchor{library/profile profile Profile run}@anchor{480d}
@deffn {メソッド} run (cmd)

@ref{4a2,,exec()} を用いて cmd をプロファイルします。
@end deffn

@geindex runctx() (profile.Profile のメソッド)
@anchor{library/profile profile Profile runctx}@anchor{480e}
@deffn {メソッド} runctx (cmd, globals, locals)

@ref{4a2,,exec()} を用いて指定されたグローバルおよびローカルな環境で cmd をプロファイルします。
@end deffn

@geindex runcall() (profile.Profile のメソッド)
@anchor{library/profile profile Profile runcall}@anchor{c70}
@deffn {メソッド} runcall (func, /, *args, **kwargs)

@code{func(*args, **kwargs)} をプロファイルします。
@end deffn
@end deffn

Note that profiling will only work if the called command/function actually
returns.  If the interpreter is terminated (e.g. via a @ref{277,,sys.exit()} call
during the called command/function execution) no profiling results will be
printed.

@node Stats クラス,決定論的プロファイリングとは,profile and cProfile Module Reference,Python プロファイラ
@anchor{library/profile profile-stats}@anchor{480f}@anchor{library/profile the-stats-class}@anchor{4810}
@subsubsection @code{Stats} クラス


@ref{47fd,,Stats} クラスを使用してプロファイラデータを解析します。

@geindex module; pstats

@geindex Stats (pstats のクラス)
@anchor{library/profile module-pstats}@anchor{b5}@anchor{library/profile pstats Stats}@anchor{47fd}
@deffn {クラス} pstats.Stats (*filenames or profile, stream=sys.stdout)

このコンストラクタは `filename' で指定した (単一または複数の) ファイルもしくは @code{Profile} のインスタンスから "統計情報オブジェクト" のインスタンスを生成します。出力は `stream' で指定したストリームに出力されます。

上記コンストラクタで指定するファイルは、使用する @ref{47fd,,Stats} に対応したバージョンの @ref{b4,,profile} または @ref{2b,,cProfile} で作成されたものでなければなりません。将来のバージョンのプロファイラとの互換性は `保証されておらず' 、他のプロファイラで生成されたファイルや異なるオペレーティングシステムで実行される同じプロファイルとの互換性もないことに注意してください。複数のファイルを指定した場合、同一の関数の統計情報はすべて合算され、複数のプロセスで構成される全体をひとつのレポートで検証することが可能になります。既存の @ref{47fd,,Stats} オブジェクトに別のファイルの情報を追加するときは、 @ref{4811,,add()} メソッドを使用します。

プロファイルデータをファイルから読み込む代わりに、 @code{cProfile.Profile} または @ref{bd6,,profile.Profile} オブジェクトをプロファイルデータのソースとして使うことができます。

@ref{47fd,,Stats} には次のメソッドがあります:

@geindex strip_dirs() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats strip_dirs}@anchor{4803}
@deffn {メソッド} strip_dirs ()

@ref{47fd,,Stats} クラスのこのメソッドは、ファイル名の前に付いているすべてのパス情報を取り除くためのものです。出力の幅を80文字以内に収めたいときに重宝します。このメソッドはオブジェクトを変更するため、取り除いたパス情報は失われます。パス情報除去の操作後、オブジェクトが保持するデータエントリは、オブジェクトの初期化、ロード直後と同じように "ランダムに" 並んでいます。 @ref{4803,,strip_dirs()} を実行した結果、2つの関数名が区別できない (両者が同じファイルの同じ行番号で同じ関数名となった) 場合、一つのエントリに合算されされます。
@end deffn

@geindex add() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats add}@anchor{4811}
@deffn {メソッド} add (*filenames)

@ref{47fd,,Stats} クラスのこのメソッドは、既存のプロファイリングオブジェクトに情報を追加します。引数は対応するバージョンの @ref{4806,,profile.run()} または @code{cProfile.run()} によって生成されたファイルの名前でなくてはなりません。関数の名前が区別できない (ファイル名、行番号、関数名が同じ) 場合、一つの関数の統計情報として合算されます。
@end deffn

@geindex dump_stats() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats dump_stats}@anchor{4812}
@deffn {メソッド} dump_stats (filename)

@ref{47fd,,Stats} オブジェクトに読み込まれたデータを、ファイル名 `filename' のファイルに保存します。ファイルが存在しない場合は新たに作成され、すでに存在する場合には上書きされます。このメソッドは @ref{bd6,,profile.Profile} クラスおよび @code{cProfile.Profile} クラスの同名のメソッドと等価です。
@end deffn

@geindex sort_stats() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats sort_stats}@anchor{4801}
@deffn {メソッド} sort_stats (*keys)

This method modifies the @ref{47fd,,Stats} object by sorting it according to
the supplied criteria.  The argument can be either a string or a SortKey
enum identifying the basis of a sort (example: @code{'time'}, @code{'name'},
@code{SortKey.TIME} or @code{SortKey.NAME}). The SortKey enums argument have
advantage over the string argument in that it is more robust and less
error prone.

2つ以上のキーが指定された場合、2つ目以降のキーは、それ以前のキーで等価となったデータエントリの再ソートに使われます。たとえば @code{sort_stats(SortKey.NAME, SortKey.FILE)} とした場合、まずすべてのエントリが関数名でソートされた後、同じ関数名で複数のエントリがあればファイル名でソートされます。

For the string argument, abbreviations can be used for any key names, as
long as the abbreviation is unambiguous.

The following are the valid string and SortKey:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Valid String Arg

@tab

Valid enum Arg

@tab

意味

@item

@code{'calls'}

@tab

SortKey.CALLS

@tab

呼び出し数

@item

@code{'cumulative'}

@tab

SortKey.CUMULATIVE

@tab

累積時間

@item

@code{'cumtime'}

@tab

N/A

@tab

累積時間

@item

@code{'file'}

@tab

N/A

@tab

ファイル名

@item

@code{'filename'}

@tab

SortKey.FILENAME

@tab

ファイル名

@item

@code{'module'}

@tab

N/A

@tab

ファイル名

@item

@code{'ncalls'}

@tab

N/A

@tab

呼び出し数

@item

@code{'pcalls'}

@tab

SortKey.PCALLS

@tab

プリミティブな呼び出し回数

@item

@code{'line'}

@tab

SortKey.LINE

@tab

行番号

@item

@code{'name'}

@tab

SortKey.NAME

@tab

関数名

@item

@code{'nfl'}

@tab

SortKey.NFL

@tab

関数名/ファイル名/行番号

@item

@code{'stdname'}

@tab

SortKey.STDNAME

@tab

標準名

@item

@code{'time'}

@tab

SortKey.TIME

@tab

内部時間

@item

@code{'tottime'}

@tab

N/A

@tab

内部時間

@end multitable


すべての統計情報のソート結果は降順 (最も多く時間を消費したものが一番上に来る) となることに注意してください。ただし、関数名、ファイル名、行数に関しては昇順 (アルファベット順) になります。 @code{SortKey.NFL} と @code{SortKey.STDNAME} には微妙な違いがあります。標準名 (standard name) とは表示された名前によるソートで、埋め込まれた行番号のソート順が特殊です。たとえば、 (ファイル名が同じで) 3、20、40という行番号のエントリがあった場合、20、3、40 の順に表示されます。一方 @code{SortKey.NFL} は行番号を数値として比較します。要するに、 @code{sort_stats(SortKey.NFL)} は @code{sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)} と指定した場合と同じになります。

後方互換性のため、数値を引数に使った @code{-1}, @code{0}, @code{1}, @code{2} の形式もサポートしています。それぞれ @code{'stdname'}, @code{'calls'}, @code{'time'}, @code{'cumulative'} として処理されます。引数をこの旧スタイルで指定した場合、最初のキー (数値キー) だけが使われ、複数のキーを指定しても2番目以降は無視されます。

@c For compatibility with the old profiler.


Added in version 3.7: Added the SortKey enum.

@end deffn

@geindex reverse_order() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats reverse_order}@anchor{4813}
@deffn {メソッド} reverse_order ()

@ref{47fd,,Stats} クラスのこのメソッドは、オブジェクト内の情報のリストを逆順にソートします。デフォルトでは選択したキーに応じて昇順、降順が適切に選ばれることに注意してください。

@c This method is provided primarily for compatibility with the old
@c profiler.
@end deffn

@geindex print_stats() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats print_stats}@anchor{4804}
@deffn {メソッド} print_stats (*restrictions)

@ref{47fd,,Stats} クラスのこのメソッドは、 @ref{4806,,profile.run()} の項で述べたプロファイルのレポートを出力します。

出力するデータの順序はオブジェクトに対し最後に行った @ref{4801,,sort_stats()} による操作に基づきます (@ref{4811,,add()} と @ref{4803,,strip_dirs()} による制限にも支配されます)。

The arguments provided (if any) can be used to limit the list down to the
significant entries.  Initially, the list is taken to be the complete set
of profiled functions.  Each restriction is either an integer (to select a
count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to
select a percentage of lines), or a string that will be interpreted as a
regular expression (to pattern match the standard name that is printed).
If several restrictions are provided, then they are applied sequentially.
For example:

@example
print_stats(.1, 'foo:')
@end example

上記の場合まず出力するリストは全体の10%に制限され、さらにファイル名の一部に文字列 @code{.*foo:} を持つ関数だけが出力されます:

@example
print_stats('foo:', .1)
@end example

こちらの例の場合、リストはまずファイル名に @code{.*foo:} を持つ関数だけに制限され、その中の最初の 10% だけが出力されます。
@end deffn

@geindex print_callers() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats print_callers}@anchor{4814}
@deffn {メソッド} print_callers (*restrictions)

@ref{47fd,,Stats} クラスのこのメソッドは、プロファイルのデータベースの中から何らかの関数呼び出しを行った関数をすべて出力します。出力の順序は @ref{4804,,print_stats()} によって与えられるものと同じです。出力を制限する引数も同じです。各呼び出し側関数についてそれぞれ一行ずつ表示されます。フォーマットは統計を作り出したプロファイラごとに微妙に異なります:


@itemize *

@item 
@ref{b4,,profile} の場合、呼び出し側関数の後に括弧で囲まれて表示される数値はその呼び出しが何回行われたかを示しています。利便性のため、 2番目の括弧なしで表示される数値によって、関数が消費した累積時間を表しています。

@item 
@ref{2b,,cProfile} の場合、各呼び出し側関数の後に3つの数字が付きます。呼び出しが何回行われたかと、この呼び出し側関数からの呼び出しによって現在の関数内で消費された合計時間および累積時間です。
@end itemize
@end deffn

@geindex print_callees() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats print_callees}@anchor{4815}
@deffn {メソッド} print_callees (*restrictions)

@ref{47fd,,Stats} クラスのこのメソッドは、指定した関数から呼び出された関数のリストを出力します。呼び出し側、呼び出される側の方向は逆ですが、引数と出力の順序に関しては @ref{4814,,print_callers()} と同じです。
@end deffn

@geindex get_stats_profile() (pstats.Stats のメソッド)
@anchor{library/profile pstats Stats get_stats_profile}@anchor{4816}
@deffn {メソッド} get_stats_profile ()

This method returns an instance of StatsProfile, which contains a mapping
of function names to instances of FunctionProfile. Each FunctionProfile
instance holds information related to the function's profile such as how
long the function took to run, how many times it was called, etc...


Added in version 3.9: Added the following dataclasses: StatsProfile, FunctionProfile.
Added the following function: get_stats_profile.

@end deffn
@end deffn

@node 決定論的プロファイリングとは,制限事項<2>,Stats クラス,Python プロファイラ
@anchor{library/profile deterministic-profiling}@anchor{4817}@anchor{library/profile what-is-deterministic-profiling}@anchor{4818}
@subsubsection 決定論的プロファイリングとは


`決定論的プロファイリング' とは、すべての `関数呼び出し', `関数からのリターン', `例外発生' をモニターし、正確なタイミングを記録することで、イベント間の時間、つまりどの時間にユーザコードが実行されているのかを計測するやり方です。もう一方の `統計的プロファイリング' (このモジュールでこの方法は採用していません) とは、有効なインストラクションポインタからランダムにサンプリングを行い、プログラムのどこで時間が使われているかを推定する方法です。後者の方法は、オーバヘッドが少ないものの、プログラムのどこで多くの時間が使われているか、その相対的な示唆に留まります。

Python の場合、実行中は必ずインタプリタが動作しているため、決定論的プロファイリングを行うために計測用のコードを追加する必要はありません。 Python は自動的に各イベントに `フック' (オプションのコールバック) を提供します。加えて Python のインタプリタという性質によって、実行時に大きなオーバーヘッドを伴う傾向がありますが、それに比べると一般的なアプリケーションでは決定論的プロファイリングで追加される処理のオーバーヘッドは少ない傾向にあります。結果的に、決定論的プロファイリングは少ないコストで Python プログラムの実行時間に関する詳細な統計を得られる方法となっているのです。

呼び出し回数はコード中のバグ発見にも使用できます (とんでもない数の呼び出しが行われている部分)。インライン拡張の対象とすべき部分を見つけるためにも使えます (呼び出し頻度の高い部分)。内部時間の統計は、注意深く最適化すべき"ホットループ"の発見にも役立ちます。累積時間の統計は、アルゴリズム選択に関連した高レベルのエラー検知に役立ちます。なお、このプロファイラは再帰的なアルゴリズム実装の累計時間を計ることが可能で、通常のループを使った実装と直接比較することもできるようになっています。

@node 制限事項<2>,キャリブレーション 補正,決定論的プロファイリングとは,Python プロファイラ
@anchor{library/profile limitations}@anchor{4819}@anchor{library/profile profile-limitations}@anchor{481a}
@subsubsection 制限事項


一つの制限はタイミング情報の正確さに関するものです。決定論的プロファイラには正確さに関する根本的問題があります。最も明白な制限は、 (一般に) "クロック"は .001 秒の精度しかないということです。これ以上の精度で計測することはできません。仮に充分な精度が得られたとしても、"誤差"が計測の平均値に影響を及ぼすことがあります。この最初の誤差を取り除いたとしても、それがまた別の誤差を引き起こす原因となります。

もう一つの問題として、イベントを検知してからプロファイラがその時刻を実際に `取得' するまでに "いくらかの時間がかかる" ことです。同様に、イベントハンドラが終了する時にも、時刻を取得して (そしてその値を保存して) から、ユーザコードが処理を再開するまでの間に遅延が発生します。結果的に多く呼び出される関数または多数の関数から呼び出される関数の情報にはこの種の誤差が蓄積する傾向にあります。このようにして蓄積される誤差は、典型的にはクロックの精度を下回ります (1クロック以下) が、一方でこの時間が累計して非常に大きな値になることも `あり得ます' 。

この問題はオーバーヘッドの小さい @ref{2b,,cProfile} よりも @ref{b4,,profile} においてより重要です。そのため、 @ref{b4,,profile} は誤差が確率的に (平均値で) 減少するようにプラットフォームごとに補正する機能を備えています。プロファイラに補正を施すと (最小二乗の意味で) 正確さが増しますが、ときには数値が負の値になってしまうこともあります (呼び出し回数が極めて少なく、確率の神があなたに意地悪をしたとき :-) )。プロファイルの結果に負の値が出力されても `驚かないでください' 。これは補正を行った場合にのみ生じることで、補正を行わない場合に比べて計測結果は実際にはより正確になっているはずだからです。

@node キャリブレーション 補正,カスタムな時刻取得用関数を使う,制限事項<2>,Python プロファイラ
@anchor{library/profile calibration}@anchor{481b}@anchor{library/profile profile-calibration}@anchor{481c}
@subsubsection キャリブレーション (補正)


@ref{b4,,profile} のプロファイラは time 関数呼び出しおよびその値を保存するためのオーバーヘッドを補正するために、各イベントの処理時間から定数を引きます。デフォルトでこの定数の値は 0 です。以下の手順で、プラットフォームに合った、より適切な定数が得られます (@ref{481a,,制限事項} 参照)。

@example
import profile
pr = profile.Profile()
for i in range(5):
    print(pr.calibrate(10000))
@end example

calibrate メソッドは引数として与えられた数だけ Python の呼び出しを行います。直接呼び出す場合と、プロファイラを使って呼び出す場合の両方が実施され、それぞれの時間が計測されます。その結果、プロファイラのイベントに隠されたオーバーヘッドが計算され、その値は浮動小数として返されます。たとえば、 1.8 GHz の Intel Core i5 で macOS を使用、 Python の time.process_time() をタイマとして使った場合、値はおよそ 4.04e-6 となります。

この手順で使用しているオブジェクトはほぼ一定の結果を返します。 `非常に' 早いコンピュータを使う場合、もしくはタイマの性能が貧弱な場合は、一定の結果を得るために引数に 100000 や 1000000 といった大きな値を指定する必要があるかもしれません。

一定の結果が得られたら、それを使う方法には3通りあります:

@example
import profile

# 1. Apply computed bias to all Profile instances created hereafter.
profile.Profile.bias = your_computed_bias

# 2. Apply computed bias to a specific Profile instance.
pr = profile.Profile()
pr.bias = your_computed_bias

# 3. Specify computed bias in instance constructor.
pr = profile.Profile(bias=your_computed_bias)
@end example

選択肢がある場合は、補正値は小さめに設定した方が良いでしょう。プロファイルの結果に負の値が表われる"頻度が低く"なるはずです。

@node カスタムな時刻取得用関数を使う,,キャリブレーション 補正,Python プロファイラ
@anchor{library/profile profile-timers}@anchor{481d}@anchor{library/profile using-a-custom-timer}@anchor{481e}
@subsubsection カスタムな時刻取得用関数を使う


プロファイラが時刻を取得する方法を変更したいなら (たとえば、実測時間やプロセスの経過時間を使いたい場合)、時刻取得用の関数を @code{Profile} クラスのコンストラクタに指定することができます:

@example
pr = profile.Profile(your_time_func)
@end example

この結果生成されるプロファイラは時刻取得に @code{your_time_func()} を呼び出すようになります。 @ref{bd6,,profile.Profile} と @code{cProfile.Profile} のどちらを使っているかにより、 @code{your_time_func} の戻り値は異なって解釈されます:


@table @asis

@item @ref{bd6,,profile.Profile}

@code{your_time_func()} は単一の数値、あるいは (@ref{132d,,os.times()} と同じように) その合計が累計時間を示すリストを返すようになっていなければなりません。関数が1つの数値、あるいは長さ2の数値のリストを返すようになっていれば、ディスパッチルーチンには特別な高速化バージョンが使われます。

Be warned that you should calibrate the profiler class for the timer function
that you choose (see @ref{481c,,キャリブレーション (補正)}).  For most machines, a timer
that returns a lone integer value will provide the best results in terms of
low overhead during profiling.  (@ref{132d,,os.times()} 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.

@item @code{cProfile.Profile}

@code{your_time_func()} は単一の数値を返すようになっていなければなりません。単一の整数を返すのであれば、クラスコンストラクタの第二引数に単位時間当たりの実際の持続時間を渡せます。例えば @code{your_integer_time_func} が 1000 分の 1 秒単位で計測した時間を返すとすると、 @code{Profile} インスタンスを以下のように構築出来ます:

@example
pr = cProfile.Profile(your_integer_time_func, 0.001)
@end example

As the @code{cProfile.Profile} class cannot be calibrated, custom timer
functions should be used with care and should be as fast as possible.  For
the best results with a custom timer, it might be necessary to hard-code it
in the C source of the internal @code{_lsprof} module.
@end table

Python 3.3 で @ref{f4,,time} に、プロセス時間や実時間の精密な計測に使える新しい関数が追加されました。
例えば、 @ref{c7a,,time.perf_counter()} を参照してください。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node timeit --- 小さなコードスニペットの実行時間計測,trace --- Python 文実行のトレースと追跡,Python プロファイラ,デバッグとプロファイル
@anchor{library/timeit doc}@anchor{481f}@anchor{library/timeit module-timeit}@anchor{f5}@anchor{library/timeit timeit-measure-execution-time-of-small-code-snippets}@anchor{4820}@anchor{library/timeit translation-repo}@anchor{4821}
@subsection @code{timeit} --- 小さなコードスニペットの実行時間計測


@geindex module; timeit

`ソースコード:' Lib/timeit.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/timeit.py}

@geindex ベンチマーク
@geindex 性能


__________________________________________________________________


このモジュールは小さい Python コードをの時間を計測するシンプルな手段を提供しています。@ref{4822,,コマンドラインインターフェイス} の他 @ref{4823,,呼び出しも可能} です。このモジュールは実行時間を計測するときに共通するいくつかの罠を回避します。O'Reilly 出版の `Python Cookbook' 第2版にある、Tim Peter による "Algorithms" 章も参照してください。

@menu
* 基本的な例: 基本的な例<3>. 
* Python インターフェイス:: 
* コマンドラインインターフェイス: コマンドラインインターフェイス<3>. 
* 使用例: 使用例<44>. 

@end menu

@node 基本的な例<3>,Python インターフェイス,,timeit --- 小さなコードスニペットの実行時間計測
@anchor{library/timeit basic-examples}@anchor{4824}
@subsubsection 基本的な例


次の例は @ref{4822,,コマンドラインインターフェイス} を使って 3 つの異なる式の時間を測定する方法を示しています。

@example
$ python -m timeit "'-'.join(str(n) for n in range(100))"
10000 loops, best of 5: 30.2 usec per loop
$ python -m timeit "'-'.join([str(n) for n in range(100)])"
10000 loops, best of 5: 27.5 usec per loop
$ python -m timeit "'-'.join(map(str, range(100)))"
10000 loops, best of 5: 23.2 usec per loop
@end example

同じ事を @ref{4823,,Python インターフェイス} を使って実現することもできます:

@example
>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237
@end example

呼び出し可能オブジェクトは @ref{4823,,Python インターフェイス} から渡すこともできます:

@example
>>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000)
0.19665591977536678
@end example

ただし、@ref{107e,,timeit()} はコマンドラインインターフェイスを使った時だけ繰り返し回数を自動で決定する事に注意してください。@ref{4825,,使用例} 節でより高度な例を説明しています。

@node Python インターフェイス,コマンドラインインターフェイス<3>,基本的な例<3>,timeit --- 小さなコードスニペットの実行時間計測
@anchor{library/timeit id1}@anchor{4826}@anchor{library/timeit python-interface}@anchor{4823}
@subsubsection Python インターフェイス


このモジュールは 3 つの有用な関数と 1 つの公開クラスを持っています:

@geindex timeit() (timeit モジュール)
@anchor{library/timeit timeit timeit}@anchor{107e}
@deffn {の関数} timeit.timeit (stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)

与えられた文、`setup' コードおよび `timer' 関数で @ref{16e1,,Timer} インスタンスを作成し、その @ref{ee9,,timeit()} メソッドを `number' 回実行します。
任意の `globals' 引数はコードを実行する名前空間を指定します。


バージョン 3.5 で変更: 任意の `globals' 引数が追加されました。

@end deffn

@geindex repeat() (timeit モジュール)
@anchor{library/timeit timeit repeat}@anchor{4827}
@deffn {の関数} timeit.repeat (stmt='pass', setup='pass', timer=<default timer>, repeat=5, number=1000000, globals=None)

与えられた文、`setup' コードおよび `timer' 関数で @ref{16e1,,Timer} インスタンスを作成し、その @ref{4828,,repeat()} メソッドを `repeat' 回繰り返すのを `number' 回実行します。
任意の `globals' 引数はコードを実行する名前空間を指定します。


バージョン 3.5 で変更: 任意の `globals' 引数が追加されました。



バージョン 3.7 で変更: `repeat' のデフォルト値が 3 から 5 へ変更されました。

@end deffn

@geindex default_timer() (timeit モジュール)
@anchor{library/timeit timeit default_timer}@anchor{4829}
@deffn {の関数} timeit.default_timer ()

浮動小数点数の秒数を返すデフォルトのタイマーで、常に time.perf_counter() でとなります。代わりに、 time.perf_counter_ns は整数のナノ秒を返します。


バージョン 3.3 で変更: デフォルトのタイマーが @ref{c7a,,time.perf_counter()} になりました。

@end deffn

@geindex Timer (timeit のクラス)
@anchor{library/timeit timeit Timer}@anchor{16e1}
@deffn {クラス} timeit.Timer (stmt='pass', setup='pass', timer=<timer function>, globals=None)

小さなコード片の実行時間を計測するためのクラスです。

コンストラクターは計測する文、セットアップのための追加の文、ならびにタイマー関数を取ります。
両文のデフォルトは @code{'pass'} です。
タイマー関数はプラットフォーム依存です (モジュールの doctring を参照)。
`stmt' および  `setup' には、複数行の文字列リテラルを含まない限り、 @code{;} や改行で区切られた複数の文でも構いません。
デフォルトでは文は timeit の名前空間内で実行されます。
この挙動は名前空間を `globals'  に渡すことで制御出来ます。

最初の命令文の実行時間を計測するには、@ref{ee9,,timeit()} メソッドを使用します。@ref{4828,,repeat()} と @ref{ee8,,autorange()} メソッドは @ref{ee9,,timeit()} を複数回呼び出したい時に使用します。

`setup' の実行時間は全実行時間から除外されています。

`stmt' および `setup' パラメータは、引数なしの呼び出し可能オブジェクトをとることもできます。呼び出し可能オブジェクトを指定すると、そのオブジェクトの呼び出しがタイマー関数に埋め込まれ、その関数が @ref{ee9,,timeit()} メソッドによって実行されます。この場合、関数呼び出しが増えるためにタイミングのオーバーヘッドが少し増える点に注意してください。


バージョン 3.5 で変更: 任意の `globals' 引数が追加されました。


@geindex timeit() (timeit.Timer のメソッド)
@anchor{library/timeit timeit Timer timeit}@anchor{ee9}
@deffn {メソッド} timeit (number=1000000)

メイン文を `number' 回実行した時間を計測します。このメソッドはセットアップ文を1回だけ実行し、メイン文を指定回数実行するのにかかった時間を返します。デフォルトのタイマーは秒数を浮動小数点数で返します。引数はループを何回実行するかの指定で、デフォルト値は 100万回です。メイン文、セットアップ文、タイマー関数はコンストラクターで指定されたものを使用します。

@cartouche
@quotation 注釈 
デフォルトでは、@ref{ee9,,timeit()} は計測中、一時的に @ref{17d8,,ガベージコレクション} を停止します。
この手法の利点は個々の計測結果がより比較しやすくなることです。
欠点は、ガベージコレクションが計測される関数の性能の重要な要素である場合があることです。
その場合、`setup' 文字列の最初の文でガベージコレクションを有効にできます。
以下に例を示します:

@example
timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
@end example
@end quotation
@end cartouche
@end deffn

@geindex autorange() (timeit.Timer のメソッド)
@anchor{library/timeit timeit Timer autorange}@anchor{ee8}
@deffn {メソッド} autorange (callback=None)

@ref{ee9,,timeit()} を呼び出す回数を自動的に決定します。

これは総時間が0.2秒以上になるように @ref{ee9,,timeit()} を繰り返し呼び出す便利な関数で、最終的な結果（ループ回数、ループ回数に要した時間）を返します。
要した時間が少なくとも0.2秒になるまで、シーケンス1, 2, 5, 10, 20, 50, ... から増加する回数で @ref{ee9,,timeit()} を呼び出します。

`callback' が与えられ、Noneでない場合は、 callback(number, time_taken) という2つの引数を指定して試行された後に呼び出されます。


Added in version 3.6.

@end deffn

@geindex repeat() (timeit.Timer のメソッド)
@anchor{library/timeit timeit Timer repeat}@anchor{4828}
@deffn {メソッド} repeat (repeat=5, number=1000000)

@ref{ee9,,timeit()} を複数回繰り返します。

これは @ref{ee9,,timeit()} を繰り返し呼び出したい時に有用で、結果をリストにして返します。最初の引数で何回 @ref{ee9,,timeit()} を呼ぶか指定します。第 2 引数で @ref{ee9,,timeit()} の引数 `number' を指定します。

@cartouche
@quotation 注釈 
結果のベクトルから平均値や標準偏差を計算して出力させたいと思うかもしれませんが、それはあまり意味がありません。多くの場合、最も低い値がそのマシンが与えられたコード断片を実行する場合の下限値です。結果のうち高めの値は、Python のスピードが一定しないために生じたものではなく、その他の計測精度に影響を及ぼすプロセスによるものです。したがって、結果のうち @ref{110b,,min()} だけが見るべき値となるでしょう。この点を押さえた上で、統計的な分析よりも常識的な判断で結果を見るようにしてください。
@end quotation
@end cartouche


バージョン 3.7 で変更: `repeat' のデフォルト値が 3 から 5 へ変更されました。

@end deffn

@geindex print_exc() (timeit.Timer のメソッド)
@anchor{library/timeit timeit Timer print_exc}@anchor{482a}
@deffn {メソッド} print_exc (file=None)

計測対象コードのトレースバックを出力するためのヘルパーです。

利用例:

@example
t = Timer(...)       # outside the try/except
try:
    t.timeit(...)    # or t.repeat(...)
except Exception:
    t.print_exc()
@end example

これの標準のトレースバックより優れた点は、コンパイルしたテンプレートのソース行が表示されることです。オプションの引数 `file' にはトレースバックの出力先を指定します。デフォルトは @ref{b33,,sys.stderr} になります。
@end deffn
@end deffn

@node コマンドラインインターフェイス<3>,使用例<44>,Python インターフェイス,timeit --- 小さなコードスニペットの実行時間計測
@anchor{library/timeit command-line-interface}@anchor{482b}@anchor{library/timeit timeit-command-line-interface}@anchor{4822}
@subsubsection コマンドラインインターフェイス


コマンドラインからプログラムとして呼び出す場合は、次の書式を使います:

@example
python -m timeit [-n N] [-r N] [-u U] [-s S] [-p] [-v] [-h] [statement ...]
@end example

以下のオプションが使用できます:

@geindex timeit コマンドラインオプション; -n
@geindex timeit コマンドラインオプション; --number
@anchor{library/timeit cmdoption-timeit-n}@anchor{482c}@anchor{library/timeit cmdoption-timeit-number}@anchor{482d}
@deffn {Option} @w{-}n N, @w{-}@w{-}number=N

'statement' を実行する回数
@end deffn

@geindex timeit コマンドラインオプション; -r
@geindex timeit コマンドラインオプション; --repeat
@anchor{library/timeit cmdoption-timeit-r}@anchor{482e}@anchor{library/timeit cmdoption-timeit-repeat}@anchor{482f}
@deffn {Option} @w{-}r N, @w{-}@w{-}repeat=N

timer を繰り返す回数（デフォルトは5）
@end deffn

@geindex timeit コマンドラインオプション; -s
@geindex timeit コマンドラインオプション; --setup
@anchor{library/timeit cmdoption-timeit-s}@anchor{4830}@anchor{library/timeit cmdoption-timeit-setup}@anchor{4831}
@deffn {Option} @w{-}s S, @w{-}@w{-}setup=S

最初に1回だけ実行する文 (デフォルトは @code{pass})
@end deffn

@geindex timeit コマンドラインオプション; -p
@geindex timeit コマンドラインオプション; --process
@anchor{library/timeit cmdoption-timeit-p}@anchor{4832}@anchor{library/timeit cmdoption-timeit-process}@anchor{4833}
@deffn {Option} @w{-}p, @w{-}@w{-}process

デフォルトの @ref{c7a,,time.perf_counter()} の代わり @ref{c7b,,time.process_time()} を利用して、実時間ではなくプロセス時間を計測します


Added in version 3.3.

@end deffn

@geindex timeit コマンドラインオプション; -u
@geindex timeit コマンドラインオプション; --unit
@anchor{library/timeit cmdoption-timeit-u}@anchor{4834}@anchor{library/timeit cmdoption-timeit-unit}@anchor{4835}
@deffn {Option} @w{-}u, @w{-}@w{-}unit=U

timer 出力の時間の単位を指定します。 @code{nsec}、@code{usec}、@code{msec}、@code{sec} を選択できます。


Added in version 3.5.

@end deffn

@geindex timeit コマンドラインオプション; -v
@geindex timeit コマンドラインオプション; --verbose
@anchor{library/timeit cmdoption-timeit-v}@anchor{4836}@anchor{library/timeit cmdoption-timeit-verbose}@anchor{4837}
@deffn {Option} @w{-}v, @w{-}@w{-}verbose

時間計測の結果をそのまま詳細な数値でくり返し表示する
@end deffn

@geindex timeit コマンドラインオプション; -h
@geindex timeit コマンドラインオプション; --help
@anchor{library/timeit cmdoption-timeit-h}@anchor{4838}@anchor{library/timeit cmdoption-timeit-help}@anchor{4839}
@deffn {Option} @w{-}h, @w{-}@w{-}help

簡単な使い方を表示して終了する
@end deffn

文は複数行指定することもできます。その場合、各行は独立した文として引数に指定されたものとして処理します。クォートと行頭のスペースを使って、インデントした文を使うことも可能です。この複数行のオプションは  @ref{4830,,-s} においても同じ形式で指定可能です。

オプション @ref{482c,,-n} でループの回数が指定されていない場合、1, 2, 5, 10, 20, 50, ... という数列で、少なくとも総時間が 0.2 秒になるまで回数を増やしていって、適切なループ回数が計算されます。

@ref{4829,,default_timer()} の測定値は、同じマシン上で実行されている他のプログラムの影響を受ける可能性があるため、正確な時間計測が必要な場合は、計測を数回繰り返し、最適な時間を使用することをおすすめします。 @ref{482e,,-r} オプションはこれに適しています。ほとんどの場合、デフォルトの5回の繰り返しで十分でしょう。 @ref{c7b,,time.process_time()} を使用すればCPU時間を測定できます。

@cartouche
@quotation 注釈 
pass 文の実行には基本的なオーバーヘッドが存在します。ここにあるコードはこの事実を隠そうとはしていませんが、注意する必要があります。基本的なオーバーヘッドは引数なしでプログラムを起動することにより計測でき、それは Python のバージョンによって異なるでしょう。
@end quotation
@end cartouche

@node 使用例<44>,,コマンドラインインターフェイス<3>,timeit --- 小さなコードスニペットの実行時間計測
@anchor{library/timeit examples}@anchor{483a}@anchor{library/timeit timeit-examples}@anchor{4825}
@subsubsection 使用例


最初に 1 回だけ実行されるセットアップ文を指定することが可能です:

@example
$ python -m timeit -s "text = 'sample string'; char = 'g'" "char in text"
5000000 loops, best of 5: 0.0877 usec per loop
$ python -m timeit -s "text = 'sample string'; char = 'g'" "text.find(char)"
1000000 loops, best of 5: 0.342 usec per loop
@end example

出力には、3つのフィールドがあります。ループ回数は、ループの反復ごとに何回文の内容が実行されたかを示します。反復回数 ('best of 5') は計時ループが何回繰り返されたかを示し、最後に文の内容が平均して計時ループの中の最良の反復で要した時間を示します。つまり、最速の反復をループ回数で割った時間です。

@example
>>> import timeit
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
0.41440500499993504
>>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
1.7246671520006203
@end example

同じことは @ref{16e1,,Timer} クラスとそのメソッドを使用して行うこともできます:

@example
>>> import timeit
>>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
>>> t.timeit()
0.3955516149999312
>>> t.repeat()
[0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886]
@end example

以下の例は、複数行を含んだ式を計測する方法を示しています。ここでは、オブジェクトの存在する属性と存在しない属性に対してテストするために @ref{6f9,,hasattr()} と @ref{8f8,,try}/@ref{1ab,,except} を使用した場合のコストを比較しています:

@example
$ python -m timeit "try:" "  str.__bool__" "except AttributeError:" "  pass"
20000 loops, best of 5: 15.7 usec per loop
$ python -m timeit "if hasattr(str, '__bool__'): pass"
50000 loops, best of 5: 4.26 usec per loop

$ python -m timeit "try:" "  int.__bool__" "except AttributeError:" "  pass"
200000 loops, best of 5: 1.43 usec per loop
$ python -m timeit "if hasattr(int, '__bool__'): pass"
100000 loops, best of 5: 2.23 usec per loop
@end example

@example
>>> import timeit
>>> # attribute is missing
>>> s = """\
... try:
...     str.__bool__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.9138244460009446
>>> s = "if hasattr(str, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.5829014980008651
>>>
>>> # attribute is present
>>> s = """\
... try:
...     int.__bool__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.04215312199994514
>>> s = "if hasattr(int, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.08588060699912603
@end example

To give the @code{timeit} module access to functions you define, you can pass a
`setup' parameter which contains an import statement:

@example
def test():
    """Stupid test function"""
    L = [i for i in range(100)]

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))
@end example

他のオプションは @ref{1c0a,,globals()} を `globals' 引数に渡すことです。
これによりコードはあなたのグローバル名前空間内で実行されます。
これはそれぞれでインポートするより 便利です:

@example
def f(x):
    return x**2
def g(x):
    return x**4
def h(x):
    return x**8

import timeit
print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals()))
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node trace --- Python 文実行のトレースと追跡,tracemalloc --- メモリ割り当ての追跡,timeit --- 小さなコードスニペットの実行時間計測,デバッグとプロファイル
@anchor{library/trace doc}@anchor{483b}@anchor{library/trace module-trace}@anchor{103}@anchor{library/trace trace-trace-or-track-python-statement-execution}@anchor{483c}@anchor{library/trace translation-repo}@anchor{483d}
@subsection @code{trace} --- Python 文実行のトレースと追跡


@geindex module; trace

`ソースコード:' Lib/trace.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/trace.py}


__________________________________________________________________


The @code{trace} module allows you to trace program execution, generate
annotated statement coverage listings, print caller/callee relationships and
list functions executed during a program run.  It can be used in another program
or from the command line.


@subsubheading 参考



@table @asis

@item Coverage.py@footnote{https://coverage.readthedocs.io/}

サードパーティの人気なカバレッジツールで、 HTML 出力に加えて分岐カバレッジのような高度な機能も提供しています。
@end table


@menu
* コマンドラインからの使用: コマンドラインからの使用<2>. 
* プログラミングインターフェース:: 

@end menu

@node コマンドラインからの使用<2>,プログラミングインターフェース,,trace --- Python 文実行のトレースと追跡
@anchor{library/trace command-line-usage}@anchor{483e}@anchor{library/trace trace-cli}@anchor{483f}
@subsubsection コマンドラインからの使用


The @code{trace} module can be invoked from the command line.  It can be as
simple as

@example
python -m trace --count -C . somefile.py ...
@end example

これで、 @code{somefile.py} の実行中に import された Python モジュールの注釈付きリストがカレントディレクトリに生成されます。

@geindex trace コマンドラインオプション; --help
@anchor{library/trace cmdoption-trace-help}@anchor{4840}
@deffn {Option} @w{-}@w{-}help

使い方を表示して終了します。
@end deffn

@geindex trace コマンドラインオプション; --version
@anchor{library/trace cmdoption-trace-version}@anchor{4841}
@deffn {Option} @w{-}@w{-}version

モジュールのバージョンを表示して終了します。
@end deffn


Added in version 3.8: Added @code{--module} option that allows running an executable module.


@menu
* 主要なオプション:: 
* 修飾的オプション:: 
* フィルターオプション:: 

@end menu

@node 主要なオプション,修飾的オプション,,コマンドラインからの使用<2>
@anchor{library/trace main-options}@anchor{4842}
@subsubsection 主要なオプション


At least one of the following options must be specified when invoking
@code{trace}.  The @ref{4843,,--listfuncs} option is mutually exclusive with
the @ref{4844,,--trace} and @ref{4845,,--count} options. When
@ref{4843,,--listfuncs} is provided, neither @ref{4845,,--count} nor
@ref{4844,,--trace} are accepted, and vice versa.

@geindex trace コマンドラインオプション; -c
@geindex trace コマンドラインオプション; --count
@anchor{library/trace cmdoption-trace-c}@anchor{4845}@anchor{library/trace cmdoption-trace-count}@anchor{4846}
@deffn {Option} @w{-}c, @w{-}@w{-}count

プログラム完了時に、それぞれの文が何回実行されたかを示す注釈付きリストのファイルを生成します。下記の @ref{4847,,--coverdir}, @ref{4848,,--file}, @ref{4849,,--no-report} も参照してください。
@end deffn

@geindex trace コマンドラインオプション; -t
@geindex trace コマンドラインオプション; --trace
@anchor{library/trace cmdoption-trace-t}@anchor{4844}@anchor{library/trace cmdoption-trace-trace}@anchor{484a}
@deffn {Option} @w{-}t, @w{-}@w{-}trace

実行された通りに行を表示します。
@end deffn

@geindex trace コマンドラインオプション; -l
@geindex trace コマンドラインオプション; --listfuncs
@anchor{library/trace cmdoption-trace-l}@anchor{4843}@anchor{library/trace cmdoption-trace-listfuncs}@anchor{484b}
@deffn {Option} @w{-}l, @w{-}@w{-}listfuncs

プログラム実行の際に実行された関数を表示します。
@end deffn

@geindex trace コマンドラインオプション; -r
@geindex trace コマンドラインオプション; --report
@anchor{library/trace cmdoption-trace-r}@anchor{484c}@anchor{library/trace cmdoption-trace-report}@anchor{484d}
@deffn {Option} @w{-}r, @w{-}@w{-}report

@ref{4845,,--count} と @ref{4848,,--file} 引数を使った過去のプログラム実行結果から、注釈付きリストのファイルを生成します。コードを実行するわけではありません。
@end deffn

@geindex trace コマンドラインオプション; -T
@geindex trace コマンドラインオプション; --trackcalls
@anchor{library/trace cmdoption-trace-T}@anchor{484e}@anchor{library/trace cmdoption-trace-trackcalls}@anchor{484f}
@deffn {Option} @w{-}T, @w{-}@w{-}trackcalls

プログラム実行によって明らかになった呼び出しの関係を表示します。
@end deffn

@node 修飾的オプション,フィルターオプション,主要なオプション,コマンドラインからの使用<2>
@anchor{library/trace modifiers}@anchor{4850}
@subsubsection 修飾的オプション


@geindex trace コマンドラインオプション; -f
@geindex trace コマンドラインオプション; --file
@anchor{library/trace cmdoption-trace-f}@anchor{4848}@anchor{library/trace cmdoption-trace-file}@anchor{4851}
@deffn {Option} @w{-}f, @w{-}@w{-}file=<file>

複数回にわたるトレース実行についてカウント (count) を累積するファイルに名前をつけます。 @ref{4845,,--count} オプションと一緒に使って下さい。
@end deffn

@geindex trace コマンドラインオプション; -C
@geindex trace コマンドラインオプション; --coverdir
@anchor{library/trace cmdoption-trace-C}@anchor{4847}@anchor{library/trace cmdoption-trace-coverdir}@anchor{4852}
@deffn {Option} @w{-}C, @w{-}@w{-}coverdir=<dir>

レポートファイルを保存するディレクトリを指定します。 @code{package.module} についてのカバレッジレポートは @code{`dir'/`package'/`module'.cover} に書き込まれます。
@end deffn

@geindex trace コマンドラインオプション; -m
@geindex trace コマンドラインオプション; --missing
@anchor{library/trace cmdoption-trace-m}@anchor{4853}@anchor{library/trace cmdoption-trace-missing}@anchor{4854}
@deffn {Option} @w{-}m, @w{-}@w{-}missing

注釈付きリストの生成時に、実行されなかった行に @code{>>>>>>} の印を付けます。
@end deffn

@geindex trace コマンドラインオプション; -s
@geindex trace コマンドラインオプション; --summary
@anchor{library/trace cmdoption-trace-s}@anchor{4855}@anchor{library/trace cmdoption-trace-summary}@anchor{4856}
@deffn {Option} @w{-}s, @w{-}@w{-}summary

@ref{4845,,--count} または @ref{484c,,--report} の利用時に、処理されたファイルそれぞれの簡潔な概要を標準出力 (stdout) に書き出します。
@end deffn

@geindex trace コマンドラインオプション; -R
@geindex trace コマンドラインオプション; --no-report
@anchor{library/trace cmdoption-trace-R}@anchor{4849}@anchor{library/trace cmdoption-trace-no-report}@anchor{4857}
@deffn {Option} @w{-}R, @w{-}@w{-}no@w{-}report

注釈付きリストを生成しません。これは @ref{4845,,--count} を何度か走らせてから最後に単一の注釈付きリストを生成するような場合に便利です。
@end deffn

@geindex trace コマンドラインオプション; -g
@geindex trace コマンドラインオプション; --timing
@anchor{library/trace cmdoption-trace-g}@anchor{4858}@anchor{library/trace cmdoption-trace-timing}@anchor{4859}
@deffn {Option} @w{-}g, @w{-}@w{-}timing

各行の先頭にプログラム開始からの時間を付けます。トレース中にだけ使われます。
@end deffn

@node フィルターオプション,,修飾的オプション,コマンドラインからの使用<2>
@anchor{library/trace filters}@anchor{485a}
@subsubsection フィルターオプション


これらのオプションは複数回指定できます。

@geindex trace コマンドラインオプション; --ignore-module
@anchor{library/trace cmdoption-trace-ignore-module}@anchor{485b}
@deffn {Option} @w{-}@w{-}ignore@w{-}module=<mod>

指定されたモジュールと（パッケージだった場合は）そのサブモジュールを無視します。引数はカンマ区切りのモジュール名リストです。
@end deffn

@geindex trace コマンドラインオプション; --ignore-dir
@anchor{library/trace cmdoption-trace-ignore-dir}@anchor{485c}
@deffn {Option} @w{-}@w{-}ignore@w{-}dir=<dir>

指定されたディレクトリとサブディレクトリ中のモジュールとパッケージを全て無視します。引数は @ref{2134,,os.pathsep} で区切られたディレクトリのリストです。
@end deffn

@node プログラミングインターフェース,,コマンドラインからの使用<2>,trace --- Python 文実行のトレースと追跡
@anchor{library/trace programmatic-interface}@anchor{485d}@anchor{library/trace trace-api}@anchor{485e}
@subsubsection プログラミングインターフェース


@geindex Trace (trace のクラス)
@anchor{library/trace trace Trace}@anchor{485f}
@deffn {クラス} trace.Trace (count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False)

文 (statement) や式 (expression) の実行をトレースするオブジェクトを作成します。引数は全てオプションです。`count' は行数を数えます。`trace' は行実行のトレースを行います。`countfuncs' は実行中に呼ばれた関数を列挙します。`countcallers' は呼び出しの関係を追跡します。`ignoremods' は無視するモジュールやパッケージのリストです。`ignoredirs' は無視するパッケージやモジュールを含むディレクトリのリストです。`infile' は保存された集計 (count) 情報を読むファイルの名前です。`outfile' は更新された集計 (count) 情報を書き出すファイルの名前です。`timing' は、タイムスタンプをトレース開始時点からの相対秒数で表示します。

@geindex run() (trace.Trace のメソッド)
@anchor{library/trace trace Trace run}@anchor{4860}
@deffn {メソッド} run (cmd)

コマンドを実行して、現在のトレースパラメータに基づいてその実行から統計情報を集めます。 `cmd' は、 @ref{4a2,,exec()} に渡せるような文字列か code オブジェクトです。
@end deffn

@geindex runctx() (trace.Trace のメソッド)
@anchor{library/trace trace Trace runctx}@anchor{4861}
@deffn {メソッド} runctx (cmd, globals=None, locals=None)

指定された globals と locals 環境下で、コマンドを実行して、現在のトレースパラメータに基づいてその実行から統計情報を集めます。定義しない場合、`globals' と `locals' はデフォルトで空の辞書となります。
@end deffn

@geindex runfunc() (trace.Trace のメソッド)
@anchor{library/trace trace Trace runfunc}@anchor{c72}
@deffn {メソッド} runfunc (func, /, *args, **kwds)

与えられた引数の `func' を、 @ref{485f,,Trace} オブジェクトのコントロール下で現在のトレースパラメタのもとに呼び出します。
@end deffn

@geindex results() (trace.Trace のメソッド)
@anchor{library/trace trace Trace results}@anchor{4862}
@deffn {メソッド} results ()

与えられた @ref{485f,,Trace} インスタンスの @code{run}, @code{runctx}, @code{runfunc} の以前の呼び出しについて集計した結果を納めた @ref{4863,,CoverageResults} オブジェクトを返します。蓄積されたトレース結果はリセットしません。
@end deffn
@end deffn

@geindex CoverageResults (trace のクラス)
@anchor{library/trace trace CoverageResults}@anchor{4863}
@deffn {クラス} trace.CoverageResults

カバレッジ結果のコンテナで、 @ref{4862,,Trace.results()} で生成されるものです。ユーザーが直接生成するものではありません。

@geindex update() (trace.CoverageResults のメソッド)
@anchor{library/trace trace CoverageResults update}@anchor{4864}
@deffn {メソッド} update (other)

別の @ref{4863,,CoverageResults} オブジェクトのデータを統合します。
@end deffn

@geindex write_results() (trace.CoverageResults のメソッド)
@anchor{library/trace trace CoverageResults write_results}@anchor{4865}
@deffn {メソッド} write_results (show_missing=True, summary=False, coverdir=None, *, ignore_missing_files=False)

カバレッジ結果を書き出します。ヒットしなかった行も出力するには `show_missing' を指定します。モジュールごとの概要を出力に含めるには `summary' を指定します。`coverdir' に指定するのは結果ファイルを出力するディレクトリです。@code{None} の場合は各ソースファイルごとの結果がそれぞれのディレクトリに置かれます。

`ignore_missing_files' が @code{True} の場合には、すでに存在しないファイルのカバレッジカウントはサイレントに無視されます。そうでなければ、ファイルが見つからないと @ref{264,,FileNotFoundError} が発生します。


バージョン 3.13 で変更: `ignore_missing_files' 引数が追加されました。

@end deffn
@end deffn

簡単な例でプログラミングインターフェースの使い方を見てみましょう:

@example
import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# run the new command using the given tracer
tracer.run('main()')

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tracemalloc --- メモリ割り当ての追跡,,trace --- Python 文実行のトレースと追跡,デバッグとプロファイル
@anchor{library/tracemalloc doc}@anchor{4866}@anchor{library/tracemalloc module-tracemalloc}@anchor{105}@anchor{library/tracemalloc tracemalloc-trace-memory-allocations}@anchor{4867}@anchor{library/tracemalloc translation-repo}@anchor{4868}
@subsection @code{tracemalloc} --- メモリ割り当ての追跡


@geindex module; tracemalloc


Added in version 3.4.


`ソースコード:' Lib/tracemalloc.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tracemalloc.py}


__________________________________________________________________


tracemallocモジュールは、Python が割り当てたメモリブロックをトレースするためのデバッグツールです。このモジュールは以下の情報を提供します。


@itemize *

@item 
オブジェクトが割り当てられた場所のトレースバック

@item 
ファイル名ごと、及び行ごとに割り当てられたメモリブロックの以下の統計を取ります：総サイズ、ブロック数、割り当てられたブロックの平均サイズ

@item 
メモリリークを検出するために2つのスナップショットの差を計算します。
@end itemize

Python が割り当てたメモリブロックの大半をトレースするには、 
@geindex PYTHONTRACEMALLOC
@geindex 環境変数; PYTHONTRACEMALLOC
@ref{212d,,PYTHONTRACEMALLOC} 環境変数を @code{1} に設定して可能な限り早くモジュールを開始させるか、@ref{16f,,-X} @code{tracemalloc} コマンドラインオプションを使用してください。実行時に @ref{212c,,tracemalloc.start()} を呼んで Python のメモリ割り当てのトレースを開始することが出来ます。

デフォルトでは、割り当てられたメモリブロック1つのトレースは最新1フレームを保存します。開始時に25フレームを保存するには、
@geindex PYTHONTRACEMALLOC
@geindex 環境変数; PYTHONTRACEMALLOC
@ref{212d,,PYTHONTRACEMALLOC} 環境変数を @code{25} に設定するか、@ref{16f,,-X} @code{tracemalloc=25} コマンドラインオプションを使用してください。

@menu
* 使用例: 使用例<45>. 
* API:: 

@end menu

@node 使用例<45>,API,,tracemalloc --- メモリ割り当ての追跡
@anchor{library/tracemalloc examples}@anchor{4869}
@subsubsection 使用例


@menu
* 上位10を表示する:: 
* 差を計算する:: 
* メモリブロックのトレースバックを取得する:: 
* top を整形化する:: 

@end menu

@node 上位10を表示する,差を計算する,,使用例<45>
@anchor{library/tracemalloc display-the-top-10}@anchor{486a}
@subsubsection 上位10を表示する


最も多くのメモリを割り当てているファイル10を表示します:

@example
import tracemalloc

tracemalloc.start()

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

print("[ Top 10 ]")
for stat in top_stats[:10]:
    print(stat)
@end example

Python テストスイートの出力例です:

@example
[ Top 10 ]
<frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
<frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 B
/usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B
/usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B
/usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B
/usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B
<frozen importlib._bootstrap>:1446: size=70.4 KiB, count=911, average=79 B
<frozen importlib._bootstrap>:1454: size=52.0 KiB, count=25, average=2131 B
<string>:5: size=49.7 KiB, count=148, average=344 B
/usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB
@end example

Python がモジュールから @code{4855 KiB} のデータ (バイトコードで定数) を読み込んでいることと、@ref{1e,,collections} モジュールが @ref{4e0,,namedtuple} 型をビルドするのに @code{244 KiB} を割り当てていることが分かります。

オプションの詳細については @ref{486b,,Snapshot.statistics()} を参照してください。

@node 差を計算する,メモリブロックのトレースバックを取得する,上位10を表示する,使用例<45>
@anchor{library/tracemalloc compute-differences}@anchor{486c}
@subsubsection 差を計算する


スナップショットを2つ取り、差を表示します:

@example
import tracemalloc
tracemalloc.start()
# ... start your application ...

snapshot1 = tracemalloc.take_snapshot()
# ... call the function leaking memory ...
snapshot2 = tracemalloc.take_snapshot()

top_stats = snapshot2.compare_to(snapshot1, 'lineno')

print("[ Top 10 differences ]")
for stat in top_stats[:10]:
    print(stat)
@end example

Python テストスイートのテストを実行する前後の出力例です:

@example
[ Top 10 differences ]
<frozen importlib._bootstrap>:716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B
/usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B
/usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B
<frozen importlib._bootstrap>:284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B
/usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B
/usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB
/usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B
/usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B
/usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B
/usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B
@end example

Python がモジュールデータ @code{8173 KiB} (バイトコードと定数) を読み込み、
前回スナップショットを取ったとき、すなわちテストの前に読み込んだ量より @code{4428 KiB} 多いということが分かります。
同様に、 @ref{89,,linecache} モジュールはトレースバックの書式化に Python ソースコード @code{940 KiB} をキャッシュし、その全ては前回のスナップショットの後に行われたことが分かります。

システムに空きメモリがほとんどない場合、スナップショットをオフラインで解析するための @ref{486d,,Snapshot.dump()} メソッドを使用して、スナップショットをディスクに書き込むことが出来ます。
そして @ref{486e,,Snapshot.load()} メソッドを使用してスナップショットを再読み込みします。

@node メモリブロックのトレースバックを取得する,top を整形化する,差を計算する,使用例<45>
@anchor{library/tracemalloc get-the-traceback-of-a-memory-block}@anchor{486f}
@subsubsection メモリブロックのトレースバックを取得する


最大のメモリブロックのトレースバックを表示するコードです:

@example
import tracemalloc

# Store 25 frames
tracemalloc.start(25)

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('traceback')

# pick the biggest memory block
stat = top_stats[0]
print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
for line in stat.traceback.format():
    print(line)
@end example

Python テストスイートの出力例です (トレースバックは 25 フレームに制限されています):

@example
903 memory blocks: 870.1 KiB
  File "<frozen importlib._bootstrap>", line 716
  File "<frozen importlib._bootstrap>", line 1036
  File "<frozen importlib._bootstrap>", line 934
  File "<frozen importlib._bootstrap>", line 1068
  File "<frozen importlib._bootstrap>", line 619
  File "<frozen importlib._bootstrap>", line 1581
  File "<frozen importlib._bootstrap>", line 1614
  File "/usr/lib/python3.4/doctest.py", line 101
    import pdb
  File "<frozen importlib._bootstrap>", line 284
  File "<frozen importlib._bootstrap>", line 938
  File "<frozen importlib._bootstrap>", line 1068
  File "<frozen importlib._bootstrap>", line 619
  File "<frozen importlib._bootstrap>", line 1581
  File "<frozen importlib._bootstrap>", line 1614
  File "/usr/lib/python3.4/test/support/__init__.py", line 1728
    import doctest
  File "/usr/lib/python3.4/test/test_pickletools.py", line 21
    support.run_doctest(pickletools)
  File "/usr/lib/python3.4/test/regrtest.py", line 1276
    test_runner()
  File "/usr/lib/python3.4/test/regrtest.py", line 976
    display_failure=not verbose)
  File "/usr/lib/python3.4/test/regrtest.py", line 761
    match_tests=ns.match_tests)
  File "/usr/lib/python3.4/test/regrtest.py", line 1563
    main()
  File "/usr/lib/python3.4/test/__main__.py", line 3
    regrtest.main_in_temp_cwd()
  File "/usr/lib/python3.4/runpy.py", line 73
    exec(code, run_globals)
  File "/usr/lib/python3.4/runpy.py", line 160
    "__main__", fname, loader, pkg_name)
@end example

We can see that the most memory was allocated in the @ref{7b,,importlib} module to
load data (bytecode and constants) from modules: @code{870.1 KiB}. The traceback is
where the @ref{7b,,importlib} loaded data most recently: on the @code{import pdb}
line of the @ref{3e,,doctest} module. The traceback may change if a new module is
loaded.

@node top を整形化する,,メモリブロックのトレースバックを取得する,使用例<45>
@anchor{library/tracemalloc pretty-top}@anchor{4870}
@subsubsection top を整形化する


@code{<frozen importlib._bootstrap>} および @code{<unknown>} ファイルを無視して、
メモリ割り当て量の上位10を整形化して表示するコードです:

@example
import linecache
import os
import tracemalloc

def display_top(snapshot, key_type='lineno', limit=10):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        print("#%s: %s:%s: %.1f KiB"
              % (index, frame.filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))

tracemalloc.start()

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
display_top(snapshot)
@end example

Python テストスイートの出力例です:

@example
Top 10 lines
#1: Lib/base64.py:414: 419.8 KiB
    _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
#2: Lib/base64.py:306: 419.8 KiB
    _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
#3: collections/__init__.py:368: 293.6 KiB
    exec(class_definition, namespace)
#4: Lib/abc.py:133: 115.2 KiB
    cls = super().__new__(mcls, name, bases, namespace)
#5: unittest/case.py:574: 103.1 KiB
    testMethod()
#6: Lib/linecache.py:127: 95.4 KiB
    lines = fp.readlines()
#7: urllib/parse.py:476: 71.8 KiB
    for a in _hexdig for b in _hexdig@}
#8: <string>:5: 62.0 KiB
#9: Lib/_weakrefset.py:37: 60.0 KiB
    self.data = set()
#10: Lib/base64.py:142: 59.8 KiB
    _b32tab2 = [a + b for a in _b32tab for b in _b32tab]
6220 other: 3602.8 KiB
Total allocated size: 5303.1 KiB
@end example

オプションの詳細については @ref{486b,,Snapshot.statistics()} を参照してください。

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

@end menu

@node Record the current and peak size of all traced memory blocks,,,top を整形化する
@anchor{library/tracemalloc record-the-current-and-peak-size-of-all-traced-memory-blocks}@anchor{4871}
@subsubsection Record the current and peak size of all traced memory blocks


The following code computes two sums like @code{0 + 1 + 2 + ...} inefficiently, by
creating a list of those numbers. This list consumes a lot of memory
temporarily. We can use @ref{4872,,get_traced_memory()} and @ref{b35,,reset_peak()} to
observe the small memory usage after the sum is computed as well as the peak
memory usage during the computations:

@example
import tracemalloc

tracemalloc.start()

# Example code: compute a sum with a large temporary list
large_sum = sum(list(range(100000)))

first_size, first_peak = tracemalloc.get_traced_memory()

tracemalloc.reset_peak()

# Example code: compute a sum with a small temporary list
small_sum = sum(list(range(1000)))

second_size, second_peak = tracemalloc.get_traced_memory()

print(f"@{first_size=@}, @{first_peak=@}")
print(f"@{second_size=@}, @{second_peak=@}")
@end example

出力:

@example
first_size=664, first_peak=3592984
second_size=804, second_peak=29704
@end example

Using @ref{b35,,reset_peak()} ensured we could accurately record the peak during the
computation of @code{small_sum}, even though it is much smaller than the overall
peak size of memory blocks since the @ref{212c,,start()} call. Without the call to
@ref{b35,,reset_peak()}, @code{second_peak} would still be the peak from the
computation @code{large_sum} (that is, equal to @code{first_peak}). In this case,
both peaks are much higher than the final memory usage, and which suggests we
could optimise (by removing the unnecessary call to @ref{24d,,list}, and writing
@code{sum(range(...))}).

@node API,,使用例<45>,tracemalloc --- メモリ割り当ての追跡
@anchor{library/tracemalloc api}@anchor{4873}
@subsubsection API


@menu
* 関数: 関数<11>. 
* DomainFilter:: 
* Filter:: 
* Frame:: 
* Snapshot:: 
* Statistic:: 
* StatisticDiff:: 
* Trace:: 
* Traceback:: 

@end menu

@node 関数<11>,DomainFilter,,API
@anchor{library/tracemalloc functions}@anchor{4874}
@subsubsection 関数


@geindex clear_traces() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc clear_traces}@anchor{4875}
@deffn {の関数} tracemalloc.clear_traces ()

Python が割り当てたメモリブロックのトレースを消去します。

@ref{18ad,,stop()} を参照してください。
@end deffn

@geindex get_object_traceback() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc get_object_traceback}@anchor{1f39}
@deffn {の関数} tracemalloc.get_object_traceback (obj)

Get the traceback where the Python object `obj' was allocated.
Return a @ref{d8f,,Traceback} instance, or @code{None} if the @code{tracemalloc}
module is not tracing memory allocations or did not trace the allocation of
the object.

@ref{a05,,gc.get_referrers()} や @ref{1adb,,sys.getsizeof()} 関数も参照してください。
@end deffn

@geindex get_traceback_limit() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc get_traceback_limit}@anchor{4876}
@deffn {の関数} tracemalloc.get_traceback_limit ()

トレースのトレースバック内に格納されている最大フレーム数を取得します。

The @code{tracemalloc} module must be tracing memory allocations to
get the limit, otherwise an exception is raised.

@ref{212c,,start()} 関数で上限を設定します。
@end deffn

@geindex get_traced_memory() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc get_traced_memory}@anchor{4872}
@deffn {の関数} tracemalloc.get_traced_memory ()

Get the current size and peak size of memory blocks traced by the
@code{tracemalloc} module as a tuple: @code{(current: int, peak: int)}.
@end deffn

@geindex reset_peak() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc reset_peak}@anchor{b35}
@deffn {の関数} tracemalloc.reset_peak ()

Set the peak size of memory blocks traced by the @code{tracemalloc} module
to the current size.

Do nothing if the @code{tracemalloc} module is not tracing memory
allocations.

This function only modifies the recorded peak size, and does not modify or
clear any traces, unlike @ref{4875,,clear_traces()}. Snapshots taken with
@ref{4877,,take_snapshot()} before a call to @ref{b35,,reset_peak()} can be
meaningfully compared to snapshots taken after the call.

@ref{4872,,get_traced_memory()} も参照してください。


Added in version 3.9.

@end deffn

@geindex get_tracemalloc_memory() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc get_tracemalloc_memory}@anchor{4878}
@deffn {の関数} tracemalloc.get_tracemalloc_memory ()

Get the memory usage in bytes of the @code{tracemalloc} module used to store
traces of memory blocks.
Return an @ref{19b,,int}.
@end deffn

@geindex is_tracing() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc is_tracing}@anchor{4879}
@deffn {の関数} tracemalloc.is_tracing ()

@code{True} if the @code{tracemalloc} module is tracing Python memory
allocations, @code{False} otherwise.

@ref{212c,,start()} ならびに @ref{18ad,,stop()} 関数も参照してください。
@end deffn

@geindex start() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc start}@anchor{212c}
@deffn {の関数} tracemalloc.start (nframe: int = 1)

Python のメモリ割り当てのトレースを開始します: Python メモリアロケータにフックします。
トレースの収集されたトレースバックは `nframe' フレームに制限されます。
デフォルトでは、あるブロックのトレースは最新のフレームのみを保存します、つまり上限は @code{1} です。
`nframe' は @code{1} 以上でなければなりません。

You can still read the original number of total frames that composed the
traceback by looking at the @ref{487a,,Traceback.total_nframe} attribute.

@code{1} より多くのフレームを保存するのは @code{'traceback'} でグループ化された統計や累積的な統計を計算する場合にのみ有用です。
@ref{487b,,Snapshot.compare_to()} および @ref{486b,,Snapshot.statistics()} メソッドを参照してください。

Storing more frames increases the memory and CPU overhead of the
@code{tracemalloc} module. Use the @ref{4878,,get_tracemalloc_memory()} function
to measure how much memory is used by the @code{tracemalloc} module.

@geindex PYTHONTRACEMALLOC
@geindex 環境変数; PYTHONTRACEMALLOC
@ref{212d,,PYTHONTRACEMALLOC} 環境変数 (@code{PYTHONTRACEMALLOC=NFRAME}) と  @ref{16f,,-X} @code{tracemalloc=NFRAME} コマンドラインオプションを使って実行開始時にトレースを始めることが出来ます。

@ref{18ad,,stop()}、@ref{4879,,is_tracing()}、@ref{4876,,get_traceback_limit()} 関数を参照してください。
@end deffn

@geindex stop() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc stop}@anchor{18ad}
@deffn {の関数} tracemalloc.stop ()

Python のメモリ割り当てのトレースを停止します。つまり、Python のメモリ割り当てへのフックをアンインストールします。 Python が割り当てたメモリブロックについてこれまで集めたトレースも全てクリアします。

トレースが全部クリアされる前にスナップショットを取りたい場合は @ref{4877,,take_snapshot()} 関数を呼んでください。

@ref{212c,,start()}、@ref{4879,,is_tracing()}、@ref{4875,,clear_traces()} 関数も参照してください。
@end deffn

@geindex take_snapshot() (tracemalloc モジュール)
@anchor{library/tracemalloc tracemalloc take_snapshot}@anchor{4877}
@deffn {の関数} tracemalloc.take_snapshot ()

Python が割り当てたメモリブロックのトレースのスナップショットを取ります。新しい @ref{487c,,Snapshot} インスタンスを返します。

The snapshot does not include memory blocks allocated before the
@code{tracemalloc} module started to trace memory allocations.

トレースのトレースバックは @ref{4876,,get_traceback_limit()} フレームに制限されています。より多くのフレームを保存するには @ref{212c,,start()} 関数の `nframe' 引数を使用してください。

The @code{tracemalloc} module must be tracing memory allocations to take a
snapshot, see the @ref{212c,,start()} function.

@ref{1f39,,get_object_traceback()} 関数を参照してください。
@end deffn

@node DomainFilter,Filter,関数<11>,API
@anchor{library/tracemalloc domainfilter}@anchor{487d}
@subsubsection DomainFilter


@geindex DomainFilter (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc DomainFilter}@anchor{eed}
@deffn {クラス} tracemalloc.DomainFilter (inclusive: bool, domain: int)

Filter traces of memory blocks by their address space (domain).


Added in version 3.6.


@geindex inclusive (tracemalloc.DomainFilter の属性)
@anchor{library/tracemalloc tracemalloc DomainFilter inclusive}@anchor{487e}
@deffn {の属性} inclusive

If `inclusive' is @code{True} (include), match memory blocks allocated
in the address space @ref{487f,,domain}.

If `inclusive' is @code{False} (exclude), match memory blocks not allocated
in the address space @ref{487f,,domain}.
@end deffn

@geindex domain (tracemalloc.DomainFilter の属性)
@anchor{library/tracemalloc tracemalloc DomainFilter domain}@anchor{487f}
@deffn {の属性} domain

Address space of a memory block (@code{int}). Read-only property.
@end deffn
@end deffn

@node Filter,Frame,DomainFilter,API
@anchor{library/tracemalloc filter}@anchor{4880}
@subsubsection Filter


@geindex Filter (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc Filter}@anchor{4881}
@deffn {クラス} tracemalloc.Filter (inclusive: bool, filename_pattern: str, lineno: int = None, all_frames: bool = False, domain: int = None)

メモリブロックのトレースをフィルターします。

`filename_pattern' のシンタックスについては @ref{1c54,,fnmatch.fnmatch()} 関数を参照してください。@code{'.pyc'} 拡張子は @code{'.py'} に置換されます。

例:


@itemize *

@item 
@code{Filter(True, subprocess.__file__)} は @ref{dc,,subprocess} モジュールのみを含みます

@item 
@code{Filter(False, tracemalloc.__file__)} excludes traces of the
@code{tracemalloc} module

@item 
@code{Filter(False, "<unknown>")} は空のトレースバックを除外します
@end itemize


バージョン 3.5 で変更: @code{'.pyo'} ファイル拡張子が @code{'.py'} に置換されることはもうありません。



バージョン 3.6 で変更: @ref{4882,,domain} 属性が追加されました。


@geindex domain (tracemalloc.Filter の属性)
@anchor{library/tracemalloc tracemalloc Filter domain}@anchor{4882}
@deffn {の属性} domain

Address space of a memory block (@code{int} or @code{None}).

tracemalloc uses the domain @code{0} to trace memory allocations made by
Python. C extensions can use other domains to trace other resources.
@end deffn

@geindex inclusive (tracemalloc.Filter の属性)
@anchor{library/tracemalloc tracemalloc Filter inclusive}@anchor{4883}
@deffn {の属性} inclusive

If `inclusive' is @code{True} (include), only match memory blocks allocated
in a file with a name matching @ref{4884,,filename_pattern} at line number
@ref{4885,,lineno}.

If `inclusive' is @code{False} (exclude), ignore memory blocks allocated in
a file with a name matching @ref{4884,,filename_pattern} at line number
@ref{4885,,lineno}.
@end deffn

@geindex lineno (tracemalloc.Filter の属性)
@anchor{library/tracemalloc tracemalloc Filter lineno}@anchor{4885}
@deffn {の属性} lineno

フィルタの行番号です (@code{int})。`lineno' が @code{None} の場合フィルタはあらゆる行番号にマッチします。
@end deffn

@geindex filename_pattern (tracemalloc.Filter の属性)
@anchor{library/tracemalloc tracemalloc Filter filename_pattern}@anchor{4884}
@deffn {の属性} filename_pattern

フィルタのファイル名のパターンです (@code{str})。読み出し専用のプロパティです。
@end deffn

@geindex all_frames (tracemalloc.Filter の属性)
@anchor{library/tracemalloc tracemalloc Filter all_frames}@anchor{4886}
@deffn {の属性} all_frames

`all_frames' が @code{True} の場合トレースバックの全てのフレームをチェックします。`all_frames' が @code{False} の場合最新のフレームをチェックします。

トレースバックの上限が @code{1} の場合この属性の影響はありません。
@ref{4876,,get_traceback_limit()} 関数と @ref{4887,,Snapshot.traceback_limit} 属性を参照してください。
@end deffn
@end deffn

@node Frame,Snapshot,Filter,API
@anchor{library/tracemalloc frame}@anchor{4888}
@subsubsection Frame


@geindex Frame (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc Frame}@anchor{4889}
@deffn {クラス} tracemalloc.Frame

トレースバックのフレームです。

@ref{d8f,,Traceback} クラスは @ref{4889,,Frame} インスタンスのシークエンスです。

@geindex filename (tracemalloc.Frame の属性)
@anchor{library/tracemalloc tracemalloc Frame filename}@anchor{488a}
@deffn {の属性} filename

ファイル名 (@code{str})。
@end deffn

@geindex lineno (tracemalloc.Frame の属性)
@anchor{library/tracemalloc tracemalloc Frame lineno}@anchor{488b}
@deffn {の属性} lineno

行番号 (@code{int})。
@end deffn
@end deffn

@node Snapshot,Statistic,Frame,API
@anchor{library/tracemalloc snapshot}@anchor{488c}
@subsubsection Snapshot


@geindex Snapshot (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc Snapshot}@anchor{487c}
@deffn {クラス} tracemalloc.Snapshot

Python が割り当てたメモリブロックのトレースのスナップショットです。

@ref{4877,,take_snapshot()} 関数はスナップショットのインスタンスを作ります。

@geindex compare_to() (tracemalloc.Snapshot のメソッド)
@anchor{library/tracemalloc tracemalloc Snapshot compare_to}@anchor{487b}
@deffn {メソッド} compare_to (old_snapshot: Snapshot, key_type: str, cumulative: bool = False)

古いスナップショットとの差を計算します。
`key_type' でグループ化された @ref{488d,,StatisticDiff} インスタンスのソート済みリストとして統計を取得します。

`key_type' および `cumulative' 引数については @ref{486b,,Snapshot.statistics()} メソッドを参照してください。

結果は降順でソートされます: キーは @ref{488e,,StatisticDiff.size_diff} の絶対値、 @ref{488f,,StatisticDiff.size}、 @ref{4890,,StatisticDiff.count_diff} の絶対置、 @ref{4891,,Statistic.count}、そして @ref{4892,,StatisticDiff.traceback} です。
@end deffn

@geindex dump() (tracemalloc.Snapshot のメソッド)
@anchor{library/tracemalloc tracemalloc Snapshot dump}@anchor{486d}
@deffn {メソッド} dump (filename)

スナップショットをファイルに書き込みます。

スナップショットをリロードするには @ref{486e,,load()} を使用します。
@end deffn

@geindex filter_traces() (tracemalloc.Snapshot のメソッド)
@anchor{library/tracemalloc tracemalloc Snapshot filter_traces}@anchor{4893}
@deffn {メソッド} filter_traces (filters)

Create a new @ref{487c,,Snapshot} instance with a filtered @ref{4894,,traces}
sequence, `filters' is a list of @ref{eed,,DomainFilter} and
@ref{4881,,Filter} instances.  If `filters' is an empty list, return a new
@ref{487c,,Snapshot} instance with a copy of the traces.

All inclusive filters are applied at once, a trace is ignored if no
inclusive filters match it. A trace is ignored if at least one exclusive
filter matches it.


バージョン 3.6 で変更: @ref{eed,,DomainFilter} instances are now also accepted in `filters'.

@end deffn

@geindex load() (tracemalloc.Snapshot のクラスメソッド)
@anchor{library/tracemalloc tracemalloc Snapshot load}@anchor{486e}
@deffn {メソッド} classmethod load (filename)

スナップショットをファイルからロードします。

@ref{486d,,dump()} を参照してください。
@end deffn

@geindex statistics() (tracemalloc.Snapshot のメソッド)
@anchor{library/tracemalloc tracemalloc Snapshot statistics}@anchor{486b}
@deffn {メソッド} statistics (key_type: str, cumulative: bool = False)

`key_type' でグループ化された @ref{4895,,Statistic} インスタンスのソート済みリストとして統計を取得します:


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

key_type

@tab

description

@item

@code{'filename'}

@tab

ファイル名

@item

@code{'lineno'}

@tab

ファイル名と行番号

@item

@code{'traceback'}

@tab

traceback

@end multitable


If `cumulative' is @code{True}, cumulate size and count of memory blocks of
all frames of the traceback of a trace, not only the most recent frame.
The cumulative mode can only be used with `key_type' equal to
@code{'filename'} and @code{'lineno'}.

結果は降順でソートされます: キーは @ref{4896,,Statistic.size}, @ref{4891,,Statistic.count}, @ref{4897,,Statistic.traceback} です。
@end deffn

@geindex traceback_limit (tracemalloc.Snapshot の属性)
@anchor{library/tracemalloc tracemalloc Snapshot traceback_limit}@anchor{4887}
@deffn {の属性} traceback_limit

@ref{4894,,traces} のトレースバック内に保存されるフレーム数の最大値です。
スナップショットが取られたときの @ref{4876,,get_traceback_limit()} の結果です。
@end deffn

@geindex traces (tracemalloc.Snapshot の属性)
@anchor{library/tracemalloc tracemalloc Snapshot traces}@anchor{4894}
@deffn {の属性} traces

Python が割り当てた全メモリブロックのトレースで、 @ref{4898,,Trace} インスタンスのシークェンスです。

シークェンスの順序は未定義です。統計のソート済みリストを取得するには @ref{486b,,Snapshot.statistics()} を使用してください。
@end deffn
@end deffn

@node Statistic,StatisticDiff,Snapshot,API
@anchor{library/tracemalloc statistic}@anchor{4899}
@subsubsection Statistic


@geindex Statistic (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc Statistic}@anchor{4895}
@deffn {クラス} tracemalloc.Statistic

メモリ割り当ての統計です。

@ref{486b,,Snapshot.statistics()} は @ref{4895,,Statistic} インスタンスの一覧を返します。

@ref{488d,,StatisticDiff} クラスも参照してください。

@geindex count (tracemalloc.Statistic の属性)
@anchor{library/tracemalloc tracemalloc Statistic count}@anchor{4891}
@deffn {の属性} count

メモリブロック数 (@code{int})。
@end deffn

@geindex size (tracemalloc.Statistic の属性)
@anchor{library/tracemalloc tracemalloc Statistic size}@anchor{4896}
@deffn {の属性} size

メモリブロックのバイト単位の総サイズ (@code{int})。
@end deffn

@geindex traceback (tracemalloc.Statistic の属性)
@anchor{library/tracemalloc tracemalloc Statistic traceback}@anchor{4897}
@deffn {の属性} traceback

メモリブロックが割り当てられているトレースバック。@ref{d8f,,Traceback} インスタンス。
@end deffn
@end deffn

@node StatisticDiff,Trace,Statistic,API
@anchor{library/tracemalloc statisticdiff}@anchor{489a}
@subsubsection StatisticDiff


@geindex StatisticDiff (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc StatisticDiff}@anchor{488d}
@deffn {クラス} tracemalloc.StatisticDiff

新旧 @ref{487c,,Snapshot} インスタンスのメモリ割り当ての統計差です。

@ref{487b,,Snapshot.compare_to()} は @ref{488d,,StatisticDiff} インスタンスのリストを返します。 @ref{4895,,Statistic} クラスも参照してください。

@geindex count (tracemalloc.StatisticDiff の属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff count}@anchor{489b}
@deffn {の属性} count

新しいスナップショット内のメモリブロックの数 (@code{int}) です。新しいスナップショット内でメモリブロックが解放された場合は @code{0} です。
@end deffn

@geindex count_diff (tracemalloc.StatisticDiff の属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff count_diff}@anchor{4890}
@deffn {の属性} count_diff

新旧スナップショットのメモリブロック数の差 (@code{int}) です。メモリブロックが新しいスナップショット内で割り当てられた場合は @code{0} です。
@end deffn

@geindex size (tracemalloc.StatisticDiff の属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff size}@anchor{488f}
@deffn {の属性} size

新しいスナップショット内のメモリブロックのバイト単位での総サイズ (@code{int}) です。新しいスナップショット内でメモリブロックが解放された場合は @code{0} です。
@end deffn

@geindex size_diff (tracemalloc.StatisticDiff の属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff size_diff}@anchor{488e}
@deffn {の属性} size_diff

新旧スナップショットのバイト単位での総サイズの差 (@code{int}) です。メモリブロックが新しいスナップショット内で割り当てられた場合は @code{0} です。
@end deffn

@geindex traceback (tracemalloc.StatisticDiff の属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff traceback}@anchor{4892}
@deffn {の属性} traceback

メモリブロックが割り当てられたトレースバックで、 @ref{d8f,,Traceback} のインスタンスです。
@end deffn
@end deffn

@node Trace,Traceback,StatisticDiff,API
@anchor{library/tracemalloc trace}@anchor{489c}
@subsubsection Trace


@geindex Trace (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc Trace}@anchor{4898}
@deffn {クラス} tracemalloc.Trace

メモリブロックをトレースします。

@ref{4894,,Snapshot.traces} 属性は @ref{4898,,Trace} インスタンスのシークエンスです。


バージョン 3.6 で変更: @ref{489d,,domain} 属性が追加されました。


@geindex domain (tracemalloc.Trace の属性)
@anchor{library/tracemalloc tracemalloc Trace domain}@anchor{489d}
@deffn {の属性} domain

Address space of a memory block (@code{int}). Read-only property.

tracemalloc uses the domain @code{0} to trace memory allocations made by
Python. C extensions can use other domains to trace other resources.
@end deffn

@geindex size (tracemalloc.Trace の属性)
@anchor{library/tracemalloc tracemalloc Trace size}@anchor{489e}
@deffn {の属性} size

メモリブロックのバイト単位のサイズ (@code{int})。
@end deffn

@geindex traceback (tracemalloc.Trace の属性)
@anchor{library/tracemalloc tracemalloc Trace traceback}@anchor{489f}
@deffn {の属性} traceback

メモリブロックが割り当てられているトレースバック。@ref{d8f,,Traceback} インスタンス。
@end deffn
@end deffn

@node Traceback,,Trace,API
@anchor{library/tracemalloc traceback}@anchor{48a0}
@subsubsection Traceback


@geindex Traceback (tracemalloc のクラス)
@anchor{library/tracemalloc tracemalloc Traceback}@anchor{d8f}
@deffn {クラス} tracemalloc.Traceback

Sequence of @ref{4889,,Frame} instances sorted from the oldest frame to the
most recent frame.

A traceback contains at least @code{1} frame. If the @code{tracemalloc} module
failed to get a frame, the filename @code{"<unknown>"} at line number @code{0} is
used.

When a snapshot is taken, tracebacks of traces are limited to
@ref{4876,,get_traceback_limit()} frames. See the @ref{4877,,take_snapshot()} function.
The original number of frames of the traceback is stored in the
@ref{487a,,Traceback.total_nframe} attribute. That allows one to know if a traceback
has been truncated by the traceback limit.

The @ref{489f,,Trace.traceback} attribute is a @ref{d8f,,Traceback} instance.


バージョン 3.7 で変更: Frames are now sorted from the oldest to the most recent, instead of most recent to oldest.


@geindex total_nframe (tracemalloc.Traceback の属性)
@anchor{library/tracemalloc tracemalloc Traceback total_nframe}@anchor{487a}
@deffn {の属性} total_nframe

Total number of frames that composed the traceback before truncation.
This attribute can be set to @code{None} if the information is not
available.
@end deffn


バージョン 3.9 で変更: @ref{487a,,Traceback.total_nframe} 属性が追加されました。


@geindex format() (tracemalloc.Traceback のメソッド)
@anchor{library/tracemalloc tracemalloc Traceback format}@anchor{d90}
@deffn {メソッド} format (limit=None, most_recent_first=False)

Format the traceback as a list of lines. Use the @ref{89,,linecache} 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
@code{abs(limit)} oldest frames. If `most_recent_first' is @code{True}, the order
of the formatted frames is reversed, returning the most recent frame first
instead of last.

Similar to the @ref{48a1,,traceback.format_tb()} function, except that
@ref{d90,,format()} does not include newlines.

以下はプログラム例です:

@example
print("Traceback (most recent call first):")
for line in traceback:
    print(line)
@end example

出力:

@example
Traceback (most recent call first):
  File "test.py", line 9
    obj = Object()
  File "test.py", line 12
    tb = tracemalloc.get_object_traceback(f())
@end example
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ソフトウェア・パッケージと配布,Python ランタイムサービス,デバッグとプロファイル,Python 標準ライブラリ
@anchor{library/distribution doc}@anchor{48a2}@anchor{library/distribution software-packaging-and-distribution}@anchor{48a3}@anchor{library/distribution translation-repo}@anchor{48a4}
@section ソフトウェア・パッケージと配布


以下のライブラリは Python で書かれたソフトウェアを配布、インストールするためのものです。これらのモジュールは Python Package Index@footnote{https://pypi.org} に対して動作するように設計されていますが、ローカルのインデックスサーバーや、インデックスサーバーなしに使うこともできます。

@menu
* ensurepip: ensurepip --- pip インストーラーのブートストラップ. pip インストーラーのブートストラップ
* venv: venv --- 仮想環境の作成. 仮想環境の作成
* zipapp: zipapp --- 実行可能な Python zip アーカイブを管理する. 実行可能な Python zip アーカイブを管理する

@end menu

@node ensurepip --- pip インストーラーのブートストラップ,venv --- 仮想環境の作成,,ソフトウェア・パッケージと配布
@anchor{library/ensurepip doc}@anchor{48a5}@anchor{library/ensurepip ensurepip-bootstrapping-the-pip-installer}@anchor{48a6}@anchor{library/ensurepip module-ensurepip}@anchor{59}
@subsection @code{ensurepip} --- @code{pip} インストーラーのブートストラップ


@geindex module; ensurepip


Added in version 3.4.


`ソースコード:' Lib/ensurepip@footnote{https://github.com/python/cpython/tree/3.14/Lib/ensurepip}


__________________________________________________________________


The @code{ensurepip} package provides support for bootstrapping the @code{pip}
installer into an existing Python installation or virtual environment. This
bootstrapping approach reflects the fact that @code{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.

ほとんどの場合、Python のエンドユーザーがこのモジュールを直接呼び出す必要はないでしょう(@code{pip} はデフォルトでブートストラップされるからです)。しかし、もし Python のインストール時に @code{pip} のインストールをスキップしたり、仮想環境を構築したり、明示的に @code{pip} をアンインストールした場合、直接呼び出す必要があるかもしれません。

@cartouche
@quotation 注釈 
このモジュールはインターネットに `アクセスしません'。@code{pip} のブートストラップに必要な全てはこのパッケージの一部として含まれています。
@end quotation
@end cartouche

This is an @ref{215a,,optional module}.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see @ref{2158,,オプションのモジュールの要件}.

@c Similar notes appear in the docs of the modules:
@c - zipfile
@c - tarfile


@subsubheading 参考



@table @asis

@item @ref{10f8,,Python モジュールのインストール}

エンドユーザーが Python パッケージをインストールする際のガイドです。

@geindex Python Enhancement Proposals; PEP 453

@item PEP 453@footnote{https://peps.python.org/pep-0453/}: Python インストールの際の明示的なpipのブートストラッピング

このモジュールのもともとの論拠と仕様。
@end table


@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

@menu
* コマンドライン・インターフェース: コマンドライン・インターフェース<9>. 
* モジュール API:: 

@end menu

@node コマンドライン・インターフェース<9>,モジュール API,,ensurepip --- pip インストーラーのブートストラップ
@anchor{library/ensurepip command-line-interface}@anchor{48a7}@anchor{library/ensurepip ensurepip-cli}@anchor{48a8}
@subsubsection コマンドライン・インターフェース


コマンドラインインターフェースを起動するには @code{-m} スイッチをつけてインタープリターを使用します。

最も簡単な起動方法は:

@example
python -m ensurepip
@end example

この起動方法は @code{pip} をインストールします。既にインストールされていた場合は何もしません。インストールされた @code{pip} のバージョンを @code{ensurepip} で利用できるもののうち、できるだけ新しいものにするためには、@code{--upgrade} オプションを追加して:

@example
python -m ensurepip --upgrade
@end example

デフォルトでは、@code{pip} は現在の仮想環境(もしアクティブなら)か、システムのサイトパッケージ(もしアクティブな仮想環境がなければ)にインストールされます。インストール先は２つの追加コマンドラインオプションで制御できます:

@geindex ensurepip コマンドラインオプション; --root
@anchor{library/ensurepip cmdoption-ensurepip-root}@anchor{48a9}
@deffn {Option} @w{-}@w{-}root <dir>

Installs @code{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.
@end deffn

@geindex ensurepip コマンドラインオプション; --user
@anchor{library/ensurepip cmdoption-ensurepip-user}@anchor{48aa}
@deffn {Option} @w{-}@w{-}user

Installs @code{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).
@end deffn

デフォルトでは @code{pipX} と @code{pipX.Y} がインストールされます(X.Yは @code{ensurepip} を起動したPythonのバージョン)。インストールされるスクリプトは2つの追加コマンドラインオプションで制御できます:

@geindex ensurepip コマンドラインオプション; --altinstall
@anchor{library/ensurepip cmdoption-ensurepip-altinstall}@anchor{48ab}
@deffn {Option} @w{-}@w{-}altinstall

If an alternate installation is requested, the @code{pipX} script will `not' be
installed.
@end deffn

@geindex ensurepip コマンドラインオプション; --default-pip
@anchor{library/ensurepip cmdoption-ensurepip-default-pip}@anchor{48ac}
@deffn {Option} @w{-}@w{-}default@w{-}pip

If a "default pip" installation is requested, the @code{pip} script will be
installed in addition to the two regular scripts.
@end deffn

2つのスクリプト選択オプションを指定すると例外が発生します。

@node モジュール API,,コマンドライン・インターフェース<9>,ensurepip --- pip インストーラーのブートストラップ
@anchor{library/ensurepip module-api}@anchor{48ad}
@subsubsection モジュール API


@code{ensurepip} exposes two functions for programmatic use:

@geindex version() (ensurepip モジュール)
@anchor{library/ensurepip ensurepip version}@anchor{48ae}
@deffn {の関数} ensurepip.version ()

環境にブートストラップする際にインストールされることになる利用可能な pip のバージョンを示す文字列を返します。
@end deffn

@geindex bootstrap() (ensurepip モジュール)
@anchor{library/ensurepip ensurepip bootstrap}@anchor{475b}
@deffn {の関数} ensurepip.bootstrap (root=None, upgrade=False, user=False, altinstall=False, default_pip=False, verbosity=0)

現在の環境あるいは指示された環境へ @code{pip} をブートストラップします。

`root' で、インストールの root ディレクトリを変更します。 `root' が @code{None} の場合は、インストールは現在の環境でのデフォルトの場所を使います。

`upgrade' で、 @code{pip} の利用可能なバージョンとして、インストール済みの以前のバージョンをアップグレードするかどうかを指定します。

`user' で、グローバルなインストールではなく user スキームを使うかどうかを指定します。

デフォルトではスクリプト @code{pipX} と @code{pipX.Y} はインストールされます(X.YはPythonの現在のバージョンです)。

`altinstall' が設定されていた場合は @code{pipX} はインストール `されません'。

`default_pip' がセットされていれば、 @code{pip} スクリプトが2つの標準スクリプトと共にインストールされます。

`altinstall' と `default_pip' の両方を指定すると、 @ref{2ec,,ValueError} を起こします。

`verbosity' でブートストラップ操作からの @ref{ccd,,sys.stdout} への出力の冗長レベルをコントロールします。

引数 @code{root} 付きで @ref{1c6e,,監査イベント} @code{ensurepip.bootstrap} を送出します。

@cartouche
@quotation 注釈 
ブートストラップ処理は @code{sys.path}, @code{os.environ} の両方に対して副作用を持ちます。代わりに、サブプロセスとしてコマンドラインインターフェイスを使うことで、これら副作用を避けることが出来ます。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
ブートストラップ処理は @code{pip} によって必要とされるモジュールを追加インストールするかもしれませんが、ほかのソフトウェアはそれら依存物がいつもデフォルトで存在していることを仮定すべきではありません(将来のバージョンの @code{pip} ではその依存はなくなるかもしれませんので)。
@end quotation
@end cartouche
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node venv --- 仮想環境の作成,zipapp --- 実行可能な Python zip アーカイブを管理する,ensurepip --- pip インストーラーのブートストラップ,ソフトウェア・パッケージと配布
@anchor{library/venv doc}@anchor{48af}@anchor{library/venv module-venv}@anchor{117}@anchor{library/venv translation-repo}@anchor{48b0}@anchor{library/venv venv-creation-of-virtual-environments}@anchor{48b1}
@subsection @code{venv} --- 仮想環境の作成


@geindex module; venv


Added in version 3.3.


`ソースコード:' Lib/venv/@footnote{https://github.com/python/cpython/tree/3.14/Lib/venv/}

@geindex 環境;仮想


__________________________________________________________________

@anchor{library/venv venv-def}@anchor{3e8}@anchor{library/venv venv-intro}@anchor{48b2}
The @code{venv} module supports creating lightweight "virtual environments",
each with their own independent set of Python packages installed in
their @ref{cc,,site} directories.
A virtual environment is created on top of an existing
Python installation, known as the virtual environment's "base" Python, and by
default is isolated from the packages in the base environment,
so that only those explicitly installed in the virtual environment are
available. See @ref{48b3,,Virtual Environments} and @ref{cc,,site}'s
@ref{48b4,,virtual environments documentation}
for more information.

仮想環境の中から使われると、 pip@footnote{https://pypi.org/project/pip/} のような一般的なインストールツールは明示的に指定しなくても仮想環境に Python パッケージをインストールします。

A virtual environment is (amongst other things):


@itemize *

@item 
Used to contain a specific Python interpreter and software libraries and
binaries which are needed to support a project (library or application). These
are by default isolated from software in other virtual environments and Python
interpreters and libraries installed in the operating system.

@item 
Contained in a directory, conventionally named @code{.venv} or @code{venv} in
the project directory, or under a container directory for lots of virtual
environments, such as @code{~/.virtualenvs}.

@item 
Not checked into source control systems such as Git.

@item 
Considered as disposable -- it should be simple to delete and recreate it from
scratch. You don't place any project code in the environment.

@item 
Not considered as movable or copyable -- you just recreate the same
environment in the target location.
@end itemize

Python仮想環境の背景についてより詳しくは 
@geindex Python Enhancement Proposals; PEP 405
PEP 405@footnote{https://peps.python.org/pep-0405/} を参照してください。


@subsubheading 参考


Python Packaging User Guide: Creating and using virtual environments@footnote{https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#create-and-use-virtual-environments}


@c include for modules that don't work on WASM or mobile platforms

@ref{213f,,Availability}: not Android, not iOS, not WASI.

このモジュールは @ref{225c,,モバイルプラットフォーム} と @ref{1b6a,,WebAssemblyプラットフォーム} をサポートしません。

@menu
* 仮想環境の作成: 仮想環境の作成<2>. 
* 仮想環境のしくみ:: 
* API: API<2>. 
* EnvBuilder を拡張する例:: 

@end menu

@node 仮想環境の作成<2>,仮想環境のしくみ,,venv --- 仮想環境の作成
@anchor{library/venv creating-virtual-environments}@anchor{48b5}
@subsubsection 仮想環境の作成


@ref{3e8,,Virtual environments} are created by executing the @code{venv}
module:

@example
python -m venv /path/to/new/virtual/environment
@end example

This creates the target directory (including parent directories as needed)
and places a @code{pyvenv.cfg} file in it with a @code{home} key
pointing to the Python installation from which the command was run.
It also creates a @code{bin} (or @code{Scripts} on Windows) subdirectory
containing a copy or symlink of the Python executable
(as appropriate for the platform or arguments used at environment creation time).
It also creates a @code{lib/pythonX.Y/site-packages} subdirectory
(on Windows, this is @code{Lib\site-packages}).
If an existing directory is specified, it will be re-used.


バージョン 3.5 で変更: 仮想環境の作成には、 @code{venv} の使用が今は推奨されています。



Deprecated since version 3.6, removed in version 3.8: @code{pyvenv} was the recommended tool for creating virtual environments
for Python 3.3 and 3.4, and replaced in 3.5 by executing @code{venv} directly.


Windows では、 @code{venv} コマンドは次のように実行します:

@example
PS> python -m venv C:\path\to\new\virtual\environment
@end example

このコマンドを @code{-h} をつけて実行すると利用できるオプションが表示されます:

@example
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            [--without-scm-ignore-files]
            ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
@end example

@geindex venv コマンドラインオプション; ENV_DIR
@anchor{library/venv venv-cli}@anchor{48b6}@anchor{library/venv cmdoption-venv-arg-ENV_DIR}@anchor{48b7}
@deffn {Option} ENV_DIR

A required argument specifying the directory to create the environment in.
@end deffn

@geindex venv コマンドラインオプション; --system-site-packages
@anchor{library/venv cmdoption-venv-system-site-packages}@anchor{48b8}
@deffn {Option} @w{-}@w{-}system@w{-}site@w{-}packages

Give the virtual environment access to the system site-packages directory.
@end deffn

@geindex venv コマンドラインオプション; --symlinks
@anchor{library/venv cmdoption-venv-symlinks}@anchor{48b9}
@deffn {Option} @w{-}@w{-}symlinks

Try to use symlinks rather than copies, when symlinks are not the default for the platform.
@end deffn

@geindex venv コマンドラインオプション; --copies
@anchor{library/venv cmdoption-venv-copies}@anchor{48ba}
@deffn {Option} @w{-}@w{-}copies

Try to use copies rather than symlinks, even when symlinks are the default for the platform.
@end deffn

@geindex venv コマンドラインオプション; --clear
@anchor{library/venv cmdoption-venv-clear}@anchor{48bb}
@deffn {Option} @w{-}@w{-}clear

Delete the contents of the environment directory if it already exists, before environment creation.
@end deffn

@geindex venv コマンドラインオプション; --upgrade
@anchor{library/venv cmdoption-venv-upgrade}@anchor{48bc}
@deffn {Option} @w{-}@w{-}upgrade

Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.
@end deffn

@geindex venv コマンドラインオプション; --without-pip
@anchor{library/venv cmdoption-venv-without-pip}@anchor{48bd}
@deffn {Option} @w{-}@w{-}without@w{-}pip

Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default).
@end deffn

@geindex venv コマンドラインオプション; --prompt
@anchor{library/venv cmdoption-venv-prompt}@anchor{48be}
@deffn {Option} @w{-}@w{-}prompt <PROMPT>

Provides an alternative prompt prefix for this environment.
@end deffn

@geindex venv コマンドラインオプション; --upgrade-deps
@anchor{library/venv cmdoption-venv-upgrade-deps}@anchor{48bf}
@deffn {Option} @w{-}@w{-}upgrade@w{-}deps

Upgrade core dependencies (pip) to the latest version in PyPI.
@end deffn

@geindex venv コマンドラインオプション; --without-scm-ignore-files
@anchor{library/venv cmdoption-venv-without-scm-ignore-files}@anchor{48c0}
@deffn {Option} @w{-}@w{-}without@w{-}scm@w{-}ignore@w{-}files

Skips adding SCM ignore files to the environment directory (Git is supported by default).
@end deffn


バージョン 3.4 で変更: デフォルトで pip をインストールします。@code{--without-pip} と @code{--copies} オプションを追加しました。



バージョン 3.4 で変更: 以前のバージョンでは、対象となるディレクトリが既に存在していた場合は、 @code{--clear} オプションや @code{--upgrade} オプションを付けない限りはエラーを送出していました。



バージョン 3.9 で変更: pip と setuptools を PyPI での最新版に更新するには、@code{--upgrade-deps} オプションを追加してください。



バージョン 3.12 で変更: @code{setuptools} is no longer a core venv dependency.



バージョン 3.13 で変更: @code{--without-scm-ignore-files} オプションが追加されました。



バージョン 3.13 で変更: @code{venv} now creates a @code{.gitignore} file for Git by default.


@cartouche
@quotation 注釈 
Windows でもシンボリックリンクはサポートされていますが、シンボリックリンクを使うのは推奨されません。
特に注目すべきなのは、ファイルエクスプローラ上で @code{python.exe} をダブルクリックすると、シンボリックリンクを貪欲に解決し仮想環境を無視するということです。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
Microsoft Windows では、ユーザー向けの実行ポリシーを設定して @code{Activate.ps1} スクリプトが使えるようにする必要があるかもしれません。
この設定は次の PowerShell コマンドでできます:

@example
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
@end example

さらに詳しくは About Execution Policies@footnote{https://go.microsoft.com/fwlink/?LinkID=135170} を参照してください。
@end quotation
@end cartouche

作成された @code{pyvenv.cfg} ファイルには、@code{include-system-site-packages} キーも含まれます。これは @code{venv} が @code{--system-site-packages} オプションをつけて実行されたなら @code{true} で、そうでなければ @code{false} です。

@code{--without-pip} オプションが与えられない限り、@code{pip} を仮想環境でブートするために @ref{59,,ensurepip} が呼ばれます。

@code{venv} には複数のパスを渡すことができ、その場合はそれぞれのパスに同一の仮想環境が作成されます。

@node 仮想環境のしくみ,API<2>,仮想環境の作成<2>,venv --- 仮想環境の作成
@anchor{library/venv how-venvs-work}@anchor{48c1}@anchor{library/venv venv-explanation}@anchor{67e}
@subsubsection 仮想環境のしくみ


Python インタプリタが仮想環境で実行しているとき、@ref{3e7,,sys.prefix} と @ref{3eb,,sys.exec_prefix} は仮想環境のディレクトリを指し示し、 @ref{3e6,,sys.base_prefix} と @ref{3ea,,sys.base_exec_prefix} は仮想環境の作成に使われたベース Python のディレクトリを指し示します。@code{sys.prefix != sys.base_prefix} を調べれば、現在のインタプリタが仮想環境で実行しているかを判定できます。

A virtual environment may be "activated" using a script in its binary directory
(@code{bin} on POSIX; @code{Scripts} on Windows).
This will prepend that directory to your 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}, so that running
@code{python} will invoke the environment's Python interpreter
and you can run installed scripts without having to use their full path.
The invocation of the activation script is platform-specific
(@code{@var{<venv>}} must be replaced by the path to the directory
containing the virtual environment):


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

プラットフォーム

@tab

シェル

@tab

仮想環境を有効化するためのコマンド

@item

POSIX

@tab

bash/zsh

@tab

@code{$ source @var{<venv>}/bin/activate}

@item

fish

@tab

@code{$ source @var{<venv>}/bin/activate.fish}

@item

csh/tcsh

@tab

@code{$ source @var{<venv>}/bin/activate.csh}

@item

pwsh

@tab

@code{$ @var{<venv>}/bin/Activate.ps1}

@item

Windows

@tab

cmd.exe

@tab

@code{C:\> @var{<venv>}\Scripts\activate.bat}

@item

PowerShell

@tab

@code{PS C:\> @var{<venv>}\Scripts\Activate.ps1}

@end multitable



Added in version 3.4: @code{fish} および @code{csh} の有効化スクリプト。



Added in version 3.8: PowerShell Core のサポートのために POSIX 環境にインストールされた、PowerShell 有効化スクリプト。


Python を呼び出すときに仮想環境の Python インタプリタへのフルパスを指定すれば良いだけなので、仮想環境をアクティベートする `必要' はありません。さらに、仮想環境にインストールされたすべてのスクリプトはアクティベートせずとも実行可能なはずです。

これを達成するため、仮想環境にインストールされたスクリプトは、仮想環境の Python インタープリターを指し示す "shebang" の行 @code{#!/@var{<path-to-venv>}/bin/python} を含みます。つまり、
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} の値に関係なくそのスクリプトはそのインタープリターを使って実行されます。Windows では、"shebang" の行の処理は @ref{7da,,Python install manager} がインストールされていれば可能です。したがって、Windows のエクスプローラのウィンドウで、インストールされたスクリプトをダブルクリックすると、仮想環境をアクティベートしたり 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} を編集したりしなくても、正しいインタープリターでスクリプトが実行されるはずです。

仮想環境がアクティベートされると、@code{VIRTUAL_ENV} 環境変数の値が仮想環境へのパスに設定されます。アクティベートしなくても仮想環境を使うことは可能なため、仮想環境が使われているか否かの判断を @code{VIRTUAL_ENV} に頼ることはできません。

@cartouche
@quotation 警告 
仮想環境にインストールされたスクリプトは仮想環境がアクティベートされていることを前提とすべきではないため、shebang の行は仮想環境のインタプリタへの絶対パスを含みます。このため、本質的に、仮想環境は一般の場合ポータブルではありません。いつでも仮想環境を再作成できる簡単な方法を持っておくべきです（例えば、@code{requirements.txt} という requirements ファイルがあれば、仮想環境の @code{pip} を用いて、@code{pip install -r requirements.txt} を呼び出すことで、仮想環境が必要とするすべてのパッケージをインストールできます）。何らかの理由で仮想環境を別の場所に移動する必要がある場合は、新しい場所で仮想環境を再作成し、古い場所にある仮想環境を削除してください。仮想環境の親ディレクトリを移動したため仮想環境も移動された場合は、新しい場所で仮想環境を再作成する必要があります。さもなくば、仮想環境にインストールされたソフトウェアが想定通りに動作しない可能性があります。
@end quotation
@end cartouche

シェルで @code{deactivate} と入力することで仮想環境を無効化できます。
厳密な仕組みはプラットフォーム固有であり、内部の実装詳細です (たいていはスクリプトかシェル関数が使われます)。

@node API<2>,EnvBuilder を拡張する例,仮想環境のしくみ,venv --- 仮想環境の作成
@anchor{library/venv api}@anchor{48c2}@anchor{library/venv venv-api}@anchor{10f5}
@subsubsection API


上述の高水準のメソッドは、サードパーティの仮想環境の作成者が環境の作成を必要に応じてカスタマイズするための機構を提供する簡素な API を利用します。それが @ref{571,,EnvBuilder} クラスです。

@geindex EnvBuilder (venv のクラス)
@anchor{library/venv venv EnvBuilder}@anchor{571}
@deffn {クラス} venv.EnvBuilder (system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None, upgrade_deps=False, *, scm_ignore_files=frozenset())

@ref{571,,EnvBuilder} クラスを実体化するときに、以下のキーワード引数を受け取ります:


@itemize *

@item 
`system_site_packages' -- 真偽値で、システムの Python の site-packages を仮想環境から利用できるかどうかを示します (デフォルト: @code{False})。

@item 
`clear' -- 真偽値で、真の場合環境を作成する前に既存の対象ディレクトリの中身を削除します。

@item 
`symlinks' -- 真偽値で、Python のバイナリをコピーせずにシンボリックの作成を試みるかどうかを示します。

@item 
`upgrade' -- 真偽値で、真の場合実行中の Python で既存の環境をアップグレードします。その Python がインプレースでアップグレードされたときに用います。デフォルトは @code{False} です。

@item 
`with_pip' -- 真偽値で、真の場合仮想環境に pip がインストールされていることを保証します。@code{--default-pip} オプションで  @ref{59,,ensurepip} を使用します。

@item 
`prompt' -- 仮想環境がアクティベートされたときに使う文字列（デフォルトは @code{None} のため、仮想環境のディレクトリ名が使われます）。もし特殊な文字列 @code{"."} が渡された場合、カレントディレクトリのベース名がプロンプトとして用いられます。

@item 
`upgrade_deps' -- venv のベースのモジュールを PyPI での最新版にアップデートします。

@item 
`scm_ignore_files' -- Create ignore files based for the specified source
control managers (SCM) in the iterable. Support is defined by having a
method named @code{create_@{scm@}_ignore_file}. The only value supported by
default is @code{"git"} via @ref{48c3,,create_git_ignore_file()}.
@end itemize


バージョン 3.4 で変更: @code{with_pip} 引数が追加されました。



バージョン 3.6 で変更: @code{prompt} 引数が追加されました。



バージョン 3.9 で変更: @code{upgrade_deps} 引数が追加されました。



バージョン 3.13 で変更: @code{scm_ignore_files} 引数が追加されました。


@ref{571,,EnvBuilder} may be used as a base class.

@geindex create() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder create}@anchor{48c4}
@deffn {メソッド} create (env_dir)

仮想環境を持つことになるターゲットディレクトリ (絶対パスあるいは現在のディレクトリからの相対パス) を指定し、仮想環境を作成します。
@code{create} メソッドは、指定されたディレクトリに仮想環境を構築するか、適切な例外を送出します。

@ref{571,,EnvBuilder} クラスの @code{create} メソッドは、サブクラスのカスタマイズに使えるフックを説明します:

@example
def create(self, env_dir):
    """
    Create a virtualized Python environment in a directory.
    env_dir is the target directory to create an environment in.
    """
    env_dir = os.path.abspath(env_dir)
    context = self.ensure_directories(env_dir)
    self.create_configuration(context)
    self.setup_python(context)
    self.setup_scripts(context)
    self.post_setup(context)
@end example

メソッド @ref{48c5,,ensure_directories()}, @ref{48c6,,create_configuration()}, @ref{48c7,,setup_python()}, @ref{48c8,,setup_scripts()}, @ref{48c9,,post_setup()} はそれぞれオーバーライドできます。
@end deffn

@geindex ensure_directories() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder ensure_directories}@anchor{48c5}
@deffn {メソッド} ensure_directories (env_dir)

仮想環境のディレクトリとすべての必要なサブディレクトリのうちまだ存在しないものを作成し、コンテキストオブジェクトを返します。このコンテキストオブジェクトは他のメソッドで使うために（パスなどの）属性を保持しているだけです。もし @ref{571,,EnvBuilder} が @code{clear=True} の引数で作成された場合、仮想環境のディレクトリの中身は消去され、すべての必要なサブディレクトリが再作成されます。

返されるコンテキストオブジェクトは以下の属性を持った @ref{4e5,,types.SimpleNamespace} です:


@itemize *

@item 
@code{env_dir} - 仮想環境の場所。アクティベートスクリプトの中の @code{__VENV_DIR__} で使われます（@ref{48ca,,install_scripts()} を参照してください）。

@item 
@code{env_name} - 仮想環境の名前。アクティベートスクリプトの中の @code{__VENV_NAME__} で使われます（@ref{48ca,,install_scripts()} を参照してください）。

@item 
@code{prompt} - アクティベートスクリプトで使われるプロンプト。アクティベートスクリプトの中の @code{__VENV_PROMPT__} で使われます（@ref{48ca,,install_scripts()} を参照してください）。

@item 
@code{executable} - 仮想環境の元になっている Python 実行可能ファイル。これは仮想環境が別の仮想環境から作られた場合も考慮に入れます。

@item 
@code{inc_path} - 仮想環境の include パス。

@item 
@code{lib_path} - 仮想環境の purelib パス。

@item 
@code{bin_path} - 仮想環境のスクリプトのパス。

@item 
@code{bin_name} - 仮想環境の場所に相対的な、スクリプトのパス。アクティベートスクリプトの中の @code{__VENV_BIN_NAME__} で使われます（@ref{48ca,,install_scripts()} を参照してください）。

@item 
@code{env_exe} - 仮想環境の中の Python インタプリタの名前。アクティベートスクリプトの中の @code{__VENV_PYTHON__} で使われます（@ref{48ca,,install_scripts()} を参照してください）。

@item 
@code{env_exec_cmd} - ファイルシステムのリダイレクトを考慮に入れた、Python インタプリタの名前。これは仮想環境の中で Python を実行するのに使えます。
@end itemize


バージョン 3.11 で変更: `venv' @ref{449,,システム構成インストールスキーム} は作成されたディレクトリのパスを構築するために使われます。



バージョン 3.12 で変更: コンテキストに @code{lib_path} 属性が追加され、コンテキストオブジェクトがドキュメントに追加されました。

@end deffn

@geindex create_configuration() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder create_configuration}@anchor{48c6}
@deffn {メソッド} create_configuration (context)

仮想環境に @code{pyvenv.cfg} 設定ファイルを作成します。
@end deffn

@geindex setup_python() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder setup_python}@anchor{48c7}
@deffn {メソッド} setup_python (context)

Python 実行ファイルのコピーまたはシンボリックリンクを仮想環境に作成します。
POSIX システムで、特定の @code{python3.x} 実行ファイルが使われている場合、同じ名前のファイルが既に存在していない限り、 @code{python} および @code{python3} へのシンボリックリンクがその実行ファイルを指すように作成されます。
@end deffn

@geindex setup_scripts() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder setup_scripts}@anchor{48c8}
@deffn {メソッド} setup_scripts (context)

プラットフォームに対応した有効化スクリプトを仮想環境にインストールします。
@end deffn

@geindex upgrade_dependencies() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder upgrade_dependencies}@anchor{48cb}
@deffn {メソッド} upgrade_dependencies (context)

仮想環境の中の venv のコア依存関係パッケージ（現在は @code{pip}）をアップグレードします。これは仮想環境の中の @code{pip} 実行可能ファイルによって行われます。


Added in version 3.9.



バージョン 3.12 で変更: setuptools@footnote{https://pypi.org/project/setuptools/} is no longer a core venv dependency.

@end deffn

@geindex post_setup() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder post_setup}@anchor{48c9}
@deffn {メソッド} post_setup (context)

サードパーティーライブラリがオーバーライドするための空のメソッドです。このメソッドをオーバーライドして、仮想環境構築後にパッケージのプリインストールなどのステップを実装できます。
@end deffn

@geindex install_scripts() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder install_scripts}@anchor{48ca}
@deffn {メソッド} install_scripts (context, path)

This method can be
called from @ref{48c8,,setup_scripts()} or @ref{48c9,,post_setup()} in subclasses to
assist in installing custom scripts into the virtual environment.

`path' は @code{common}, @code{posix}, @code{nt} ディレクトリを格納したディレクトリへのパスです。各サブディレクトリには仮想環境の @code{bin} ディレクトリにインストールするスクリプトを格納します。 @code{common} の中身と、 @ref{3003,,os.name} に一致するディレクトリの中身を、以下の置換処理を行いながらコピーします:


@itemize *

@item 
@code{__VENV_DIR__} は仮想環境ディレクトリの絶対パスに置換されます。

@item 
@code{__VENV_NAME__} は仮想環境の名前 (仮想環境ディレクトリのパスの最後の部分) に置換されます。

@item 
@code{__VENV_PROMPT__} はプロンプトに置換されます (括弧で囲まれ空白が続く環境名)。

@item 
@code{__VENV_BIN_NAME__} は bin ディレクトリ名 (@code{bin} か @code{Scripts}) に置換されます。

@item 
@code{__VENV_PYTHON__} は仮想環境の Python 実行ファイルの絶対パスに置換されます。
@end itemize

(既存環境のアップグレード中は) ディレクトリは存在しても構いません。
@end deffn

@geindex create_git_ignore_file() (venv.EnvBuilder のメソッド)
@anchor{library/venv venv EnvBuilder create_git_ignore_file}@anchor{48c3}
@deffn {メソッド} create_git_ignore_file (context)

Creates a @code{.gitignore} file within the virtual environment that causes
the entire directory to be ignored by the Git source control manager.


Added in version 3.13.

@end deffn


バージョン 3.7.2 で変更: Windows では、バイナリそのものをコピーするのではなく、@code{python[w].exe} にリダイレクトを行うスクリプトを使うようになりました。
3.7.2 でのみ、ソース群でビルドを実行しているのでなければ  @ref{48c7,,setup_python()} だけは何もしません。



バージョン 3.7.3 で変更: Windows では、 @ref{48c8,,setup_scripts()} の代わりに @ref{48c7,,setup_python()} の一部としてリダイレクトを行うスクリプトをコピーします。
これは 3.7.2 には当てはまりません。
シンボリックリンクを使ったときは、オリジナルの実行ファイルをコピーします。

@end deffn

モジュールレベルの簡易関数もあります:

@geindex create() (venv モジュール)
@anchor{library/venv venv create}@anchor{572}
@deffn {の関数} venv.create (env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None, upgrade_deps=False, *, scm_ignore_files=frozenset())

@ref{571,,EnvBuilder} を指定されたキーワード引数を使って作成し、その @ref{48c4,,create()} メソッドに `env_dir' 引数を渡して実行します。


Added in version 3.3.



バージョン 3.4 で変更: `with_pip' 引数が追加されました。



バージョン 3.6 で変更: `prompt' 引数が追加されました。



バージョン 3.9 で変更: `upgrade_deps' 引数が追加されました。



バージョン 3.13 で変更: `scm_ignore_files' 引数が追加されました。

@end deffn

@node EnvBuilder を拡張する例,,API<2>,venv --- 仮想環境の作成
@anchor{library/venv an-example-of-extending-envbuilder}@anchor{48cc}
@subsubsection @code{EnvBuilder} を拡張する例


次のスクリプトで、作成された仮想環境に setuptools と pip をインストールするサブクラスを実装して @ref{571,,EnvBuilder} を拡張する方法を示します:

@example
import os
import os.path
from subprocess import Popen, PIPE
import sys
from threading import Thread
from urllib.parse import urlsplit
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, _, _ = urlsplit(url)
        fn = os.path.split(path)[-1]
        binpath = context.bin_path
        distpath = os.path.join(binpath, fn)
        # Download script into the virtual environment's binaries folder
        urlretrieve(url, distpath)
        progress = self.progress
        if self.verbose:
            term = '\n'
        else:
            term = '@w{'}
        if progress is not None:
            progress('Installing %s ...%s' % (name, term), 'main')
        else:
            sys.stderr.write('Installing %s ...%s' % (name, term))
            sys.stderr.flush()
        # Install in the virtual environment
        args = [context.env_exe, fn]
        p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
        t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
        t1.start()
        t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
        t2.start()
        p.wait()
        t1.join()
        t2.join()
        if progress is not None:
            progress('done.', 'main')
        else:
            sys.stderr.write('done.\n')
        # Clean up - no longer needed
        os.unlink(distpath)

    def install_setuptools(self, context):
        """
        Install setuptools in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = "https://bootstrap.pypa.io/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):
    import argparse

    parser = argparse.ArgumentParser(prog=__name__,
                                     description='Creates virtual Python '
                                                 'environments in one or '
                                                 'more target '
                                                 'directories.')
    parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
                        help='A directory in which to create the '
                             'virtual environment.')
    parser.add_argument('--no-setuptools', default=False,
                        action='store_true', dest='nodist',
                        help="Don't install setuptools or pip in the "
                             "virtual environment.")
    parser.add_argument('--no-pip', default=False,
                        action='store_true', dest='nopip',
                        help="Don't install pip in the virtual "
                             "environment.")
    parser.add_argument('--system-site-packages', default=False,
                        action='store_true', dest='system_site',
                        help='Give the virtual environment access to the '
                             'system site-packages dir.')
    if os.name == 'nt':
        use_symlinks = False
    else:
        use_symlinks = True
    parser.add_argument('--symlinks', default=use_symlinks,
                        action='store_true', dest='symlinks',
                        help='Try to use symlinks rather than copies, '
                             'when symlinks are not the default for '
                             'the platform.')
    parser.add_argument('--clear', default=False, action='store_true',
                        dest='clear', help='Delete the contents of the '
                                           'virtual environment '
                                           'directory if it already '
                                           'exists, before virtual '
                                           'environment creation.')
    parser.add_argument('--upgrade', default=False, action='store_true',
                        dest='upgrade', help='Upgrade the virtual '
                                             'environment directory to '
                                             'use this version of '
                                             'Python, assuming Python '
                                             'has been upgraded '
                                             'in-place.')
    parser.add_argument('--verbose', default=False, action='store_true',
                        dest='verbose', help='Display the output '
                                             'from the scripts which '
                                             'install setuptools and pip.')
    options = parser.parse_args(args)
    if options.upgrade and options.clear:
        raise ValueError('you cannot supply --upgrade and --clear together.')
    builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
                                   clear=options.clear,
                                   symlinks=options.symlinks,
                                   upgrade=options.upgrade,
                                   nodist=options.nodist,
                                   nopip=options.nopip,
                                   verbose=options.verbose)
    for d in options.dirs:
        builder.create(d)

if __name__ == '__main__':
    rc = 1
    try:
        main()
        rc = 0
    except Exception as e:
        print('Error: %s' % e, file=sys.stderr)
    sys.exit(rc)
@end example

このスクリプトは オンライン@footnote{https://gist.github.com/vsajip/4673395} よりダウンロードすることも可能です。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node zipapp --- 実行可能な Python zip アーカイブを管理する,,venv --- 仮想環境の作成,ソフトウェア・パッケージと配布
@anchor{library/zipapp doc}@anchor{48cd}@anchor{library/zipapp module-zipapp}@anchor{136}@anchor{library/zipapp translation-repo}@anchor{48ce}@anchor{library/zipapp zipapp-manage-executable-python-zip-archives}@anchor{48cf}
@subsection @code{zipapp} --- 実行可能な Python zip アーカイブを管理する


@geindex module; zipapp


Added in version 3.5.


`ソースコード:' Lib/zipapp.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/zipapp.py}

@geindex Executable Zip Files


__________________________________________________________________


このモジュールは Python コードを含む zip ファイルの作成を行うツールを提供します。
zip ファイルは @ref{211b,,Python インタープリタで直接実行することが出来ます}。
このモジュールは @ref{48d0,,コマンドラインインターフェイス} と @ref{48d1,,Python API} の両方を提供します。

@menu
* 基本的な例: 基本的な例<4>. 
* コマンドラインインターフェイス: コマンドラインインターフェイス<4>. 
* Python API:: 
* 使用例: 使用例<46>. 
* インタープリタの指定:: 
* Creating Standalone Applications with zipapp:: 
* The Python Zip Application Archive Format:: 

@end menu

@node 基本的な例<4>,コマンドラインインターフェイス<4>,,zipapp --- 実行可能な Python zip アーカイブを管理する
@anchor{library/zipapp basic-example}@anchor{48d2}
@subsubsection 基本的な例


実行可能なアーカイブを Python コードを含むディレクトリから作成する為に @ref{48d0,,コマンドラインインターフェイス} をどのように利用することができるかを以下に例示します。アーカイブは実行時にアーカイブ内の @code{myapp} モジュールから @code{main} 関数を実行します。

@example
$ python -m zipapp myapp -m "myapp:main"
$ python myapp.pyz
<output from myapp>
@end example

@node コマンドラインインターフェイス<4>,Python API,基本的な例<4>,zipapp --- 実行可能な Python zip アーカイブを管理する
@anchor{library/zipapp command-line-interface}@anchor{48d3}@anchor{library/zipapp zipapp-command-line-interface}@anchor{48d0}
@subsubsection コマンドラインインターフェイス


コマンドラインからプログラムとして呼び出す場合は、次の形式を使用います:

@example
$ python -m zipapp source [options]
@end example

`source' がディレクトリである場合、 `source' ディレクトリの内容からアーカイブを作成します。
`source' がファイルである場合、 `source' ファイル自身をアーカイブ化し、保存先アーカイブへコピーします。(または --info オプションが指定されている場合はファイルのシェバン行が表示されます。)

以下のオプションが解釈されます:

@geindex zipapp コマンドラインオプション; -o
@geindex zipapp コマンドラインオプション; --output
@anchor{library/zipapp cmdoption-zipapp-o}@anchor{48d4}@anchor{library/zipapp cmdoption-zipapp-output}@anchor{48d5}
@deffn {Option} @w{-}o <output>, @w{-}@w{-}output=<output>

出力を `output' に指定した名前のファイルへ書込みます。このオプションが指定されていない場合、出力先ファイル名は入力元 `source' と同じになり、 @code{.pyz} 拡張子が付与されます。
ファイル名が明示的に指定されている場合は、指定されたファイル名を使用します。(必要であれば @code{.pyz} 拡張子が含まれます。)

`source' がアーカイブである場合は、出力先ファイル名を必ず指定しなければなりません。
(`source' がアーカイブである場合は `output' を必ず `source' とは別の名前にしてください。)
@end deffn

@geindex zipapp コマンドラインオプション; -p
@geindex zipapp コマンドラインオプション; --python
@anchor{library/zipapp cmdoption-zipapp-p}@anchor{48d6}@anchor{library/zipapp cmdoption-zipapp-python}@anchor{48d7}
@deffn {Option} @w{-}p <interpreter>, @w{-}@w{-}python=<interpreter>

実行コマンドとしての `interpreter' を指定する @code{#!} 行を書庫に追加します。
また、POSIX では書庫を実行可能にします。
デフォルトでは @code{#!} 行を書かず、ファイルを実行可能にはしません。
@end deffn

@geindex zipapp コマンドラインオプション; -m
@geindex zipapp コマンドラインオプション; --main
@anchor{library/zipapp cmdoption-zipapp-m}@anchor{48d8}@anchor{library/zipapp cmdoption-zipapp-main}@anchor{48d9}
@deffn {Option} @w{-}m <mainfn>, @w{-}@w{-}main=<mainfn>

`mainfn' を実行するアーカイブへ @code{__main__.py} ファイルを書込んでください。
`mainfn' 引数は "pkg.mod:fn" の形式で指定します。
"pkg.mod" の場所はアーカイブ内の package/module です。
"fn" は指定した module から呼出すことのできる関数です。
@code{__main__.py} ファイルが module から呼出すことのできる関数を実行します。

書庫をコピーする際、 @ref{48d8,,--main} を指定することは出来ません。
@end deffn

@geindex zipapp コマンドラインオプション; -c
@geindex zipapp コマンドラインオプション; --compress
@anchor{library/zipapp cmdoption-zipapp-c}@anchor{48da}@anchor{library/zipapp cmdoption-zipapp-compress}@anchor{48db}
@deffn {Option} @w{-}c, @w{-}@w{-}compress

Compress files with the deflate method, reducing the size of the output
file. By default, files are stored uncompressed in the archive.

書庫をコピーする際、 @ref{48da,,--compress} に効果はありません。


Added in version 3.7.

@end deffn

@geindex zipapp コマンドラインオプション; --info
@anchor{library/zipapp cmdoption-zipapp-info}@anchor{48dc}
@deffn {Option} @w{-}@w{-}info

診断するために書庫に埋め込まれたインタープリタを表示します。
この場合、他の全てのオプションは無視され、SOURCE はディレクトリではなく書庫でなければなりません。
@end deffn

@geindex zipapp コマンドラインオプション; -h
@geindex zipapp コマンドラインオプション; --help
@anchor{library/zipapp cmdoption-zipapp-h}@anchor{48dd}@anchor{library/zipapp cmdoption-zipapp-help}@anchor{48de}
@deffn {Option} @w{-}h, @w{-}@w{-}help

簡単な使用法を表示して終了します。
@end deffn

@node Python API,使用例<46>,コマンドラインインターフェイス<4>,zipapp --- 実行可能な Python zip アーカイブを管理する
@anchor{library/zipapp python-api}@anchor{48df}@anchor{library/zipapp zipapp-python-api}@anchor{48d1}
@subsubsection Python API


このモジュールは 2 つの簡便関数を定義しています:

@geindex create_archive() (zipapp モジュール)
@anchor{library/zipapp zipapp create_archive}@anchor{da9}
@deffn {の関数} zipapp.create_archive (source, target=None, interpreter=None, main=None, filter=None, compressed=False)

`source' からアプリケーション書庫を作成します。
ソースは以下のいずれかです:


@itemize *

@item 
ディレクトリ名、または
新しいアプリケーションアーカイブがディレクトリのコンテンツから作成される場合に
@ref{5a1,,path-like object} オブジェクトが参照するディレクトリ。

@item 
既存のアプリケーションアーカイブファイルの名前、
または(`interpreter' 引数に指定した値を反映し、修正する)アーカイブへ
ファイルがコピーされる場合に @ref{5a1,,path-like object} オブジェクトが参照するファイル。

@item 
バイトモードの読込みで開くファイルオブジェクト。
ファイルの内容がアプリケーションアーカイブとなり、
ファイルオブジェクトがアーカイブの起点となります。
@end itemize

`target' 引数は作成される書庫が書き込まれる場所を決めます:


@itemize *

@item 
ファイル名、または @ref{5a1,,path-like object} オブジェクトを指定した場合、アーカイブは指定したファイルへ書き込まれます。

@item 
開いているファイルオブジェクトを指定した場合、
アーカイブはそのファイルオブジェクトへ書込みを行ないます。
ファイルオブジェクトは必ずバイトモードの書込みで開いてください。

@item 
target を指定しないか @code{None} を渡した場合、 source は必ずディレクトリでなければならず、target は source のファイル名に @code{.pyz} 拡張子を付与したファイル名となります。
@end itemize

`interpreter' 引数はアーカイブが実行時に使用する Python インタープリタの名前を指定します。
インタープリタ名は "シェバン" 行としてアーカイブの起点に書込まれます。
POSIX では OS によってシェバンが解釈され、
Windows では Python ランチャーによって扱われます。
シェバン行が書込まれていない場合は `interpreter' の結果を無視します。
interpreter が指定されており、 target がファイル名である場合、
target ファイルの実行可能ビットが設定されます。

`main' 引数はアーカイブのメインプログラムとして使用する callable の名前を指定します。
`main' 引数は source がディレクトリであり、 source が既に @code{__main__.py} ファイルを保持していない場合に限り、指定することができます。
`main' 引数は "pkg.module:callable" の形式を取り、
アーカイブは "pkg.module" をインポートして実行され、
指定した callable を引数なしで実行します。
source がディレクトリであり、 @code{__main__.py} が含まれていない場合、
`main' は無視すべきエラーとなり、
作成されたアーカイブには実行可能ビットが設定されません。

The optional `filter' argument specifies a callback function that
is passed a Path object representing the path to the file being added
(relative to the source directory).  It should return @code{True} if the
file is to be added.

The optional `compressed' argument determines whether files are
compressed.  If set to @code{True}, files in the archive are compressed
with the deflate method; otherwise, files are stored uncompressed.
This argument has no effect when copying an existing archive.

`source' または `target' へファイルオブジェクトを指定した場合、
caller が create_archive の呼出し後にオブジェクトを閉じます。

既存のアーカイブをコピーする際、ファイルオブジェクトは @code{read} , @code{readline} , @code{write} メソッドのみを提供します。
アーカイブをディレクトリから作成する際、 target がファイルオブジェクトである場合は、
@code{zipfile.ZipFile} クラスへ渡されます。必ずクラスが必要とするメソッドを提供してください。


バージョン 3.7 で変更: Added the `filter' and `compressed' parameters.

@end deffn

@geindex get_interpreter() (zipapp モジュール)
@anchor{library/zipapp zipapp get_interpreter}@anchor{48e0}
@deffn {の関数} zipapp.get_interpreter (archive)

アーカイブの最初の行の @code{#!} に指定されたインタープリタを返します。
@code{#!} が無い場合は @ref{885,,None} を返します。
`archive' 引数は、ファイル名またはバイトモードの読込みで開いた
ファイルに準じるオブジェクトを指定することができ、アーカイブの起点で決定されます。
@end deffn

@node 使用例<46>,インタープリタの指定,Python API,zipapp --- 実行可能な Python zip アーカイブを管理する
@anchor{library/zipapp examples}@anchor{48e1}@anchor{library/zipapp zipapp-examples}@anchor{48e2}
@subsubsection 使用例


ディレクトリを書庫に圧縮し、実行します。

@example
$ python -m zipapp myapp
$ python myapp.pyz
<output from myapp>
@end example

同じことを @ref{da9,,create_archive()} 関数を使用して行うことができます:

@example
>>> import zipapp
>>> zipapp.create_archive('myapp', 'myapp.pyz')
@end example

POSIX でアプリケーションを直接実行可能にするには使用するインタープリタを指定します。

@example
$ python -m zipapp myapp -p "/usr/bin/env python"
$ ./myapp.pyz
<output from myapp>
@end example

シバン行を既存の書庫で置換するには、 @ref{da9,,create_archive()} function: を使用して変更された書庫を作成します:

@example
>>> import zipapp
>>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3')
@end example

アーカイブ内のファイルを更新するには @ref{10a4,,BytesIO} オブジェクトを使用してメモリーへ格納し、
元のファイルを上書きして置換してください。
ファイルを上書きする際にエラーが発生し、元のファイルが失われる危険性があることに注意してください。
このコードは上記のようなエラーからファイルを保護しませんが、プロダクションコードは保護するべきです。
この方法はアーカイブがメモリーに収まる場合にのみ動作します:

@example
>>> import zipapp
>>> import io
>>> temp = io.BytesIO()
>>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2')
>>> with open('myapp.pyz', 'wb') as f:
>>>     f.write(temp.getvalue())
@end example

@node インタープリタの指定,Creating Standalone Applications with zipapp,使用例<46>,zipapp --- 実行可能な Python zip アーカイブを管理する
@anchor{library/zipapp specifying-the-interpreter}@anchor{48e3}@anchor{library/zipapp zipapp-specifying-the-interpreter}@anchor{48e4}
@subsubsection インタープリタの指定


Note that if you specify an interpreter and then distribute your application
archive, you need to ensure that the interpreter used is portable.  The Python
launcher for Windows supports most common forms of POSIX @code{#!} line, but there
are other issues to consider:


@itemize *

@item 
If you use "/usr/bin/env python" (or other forms of the "python" command,
such as "/usr/bin/python"), you need to consider that your users may have
either Python 2 or Python 3 as their default, and write your code to work
under both versions.

@item 
If you use an explicit version, for example "/usr/bin/env python3" your
application will not work for users who do not have that version.  (This
may be what you want if you have not made your code Python 2 compatible).

@item 
There is no way to say "python X.Y or later", so be careful of using an
exact version like "/usr/bin/env python3.4" as you will need to change your
shebang line for users of Python 3.5, for example.
@end itemize

Typically, you should use an "/usr/bin/env python2" or "/usr/bin/env python3",
depending on whether your code is written for Python 2 or 3.

@node Creating Standalone Applications with zipapp,The Python Zip Application Archive Format,インタープリタの指定,zipapp --- 実行可能な Python zip アーカイブを管理する
@anchor{library/zipapp creating-standalone-applications-with-zipapp}@anchor{48e5}
@subsubsection Creating Standalone Applications with zipapp


Using the @code{zipapp} module, it is possible to create self-contained Python
programs, which can be distributed to end users who only need to have a
suitable version of Python installed on their system.  The key to doing this
is to bundle all of the application's dependencies into the archive, along
with the application code.

The steps to create a standalone archive are as follows:


@enumerate 

@item 
Create your application in a directory as normal, so you have a @code{myapp}
directory containing a @code{__main__.py} file, and any supporting application
code.

@item 
Install all of your application's dependencies into the @code{myapp} directory,
using pip:

@example
$ python -m pip install -r requirements.txt --target myapp
@end example

(this assumes you have your project requirements in a @code{requirements.txt}
file - if not, you can just list the dependencies manually on the pip command
line).

@item 
Package the application using:

@example
$ python -m zipapp -p "interpreter" myapp
@end example
@end enumerate

This will produce a standalone executable, which can be run on any machine with
the appropriate interpreter available. See @ref{48e4,,インタープリタの指定}
for details. It can be shipped to users as a single file.

On Unix, the @code{myapp.pyz} file is executable as it stands.  You can rename the
file to remove the @code{.pyz} extension if you prefer a "plain" command name.  On
Windows, the @code{myapp.pyz[w]} file is executable by virtue of the fact that
the Python interpreter registers the @code{.pyz} and @code{.pyzw} file extensions
when installed.

@menu
* Caveats:: 

@end menu

@node Caveats,,,Creating Standalone Applications with zipapp
@anchor{library/zipapp caveats}@anchor{48e6}
@subsubsection Caveats


If your application depends on a package that includes a C extension, that
package cannot be run from a zip file (this is an OS limitation, as executable
code must be present in the filesystem for the OS loader to load it). In this
case, you can exclude that dependency from the zipfile, and either require
your users to have it installed, or ship it alongside your zipfile and add code
to your @code{__main__.py} to include the directory containing the unzipped
module in @code{sys.path}. In this case, you will need to make sure to ship
appropriate binaries for your target architecture(s) (and potentially pick the
correct version to add to @code{sys.path} at runtime, based on the user's machine).

@node The Python Zip Application Archive Format,,Creating Standalone Applications with zipapp,zipapp --- 実行可能な Python zip アーカイブを管理する
@anchor{library/zipapp the-python-zip-application-archive-format}@anchor{48e7}
@subsubsection The Python Zip Application Archive Format


Python has been able to execute zip files which contain a @code{__main__.py} file
since version 2.6.  In order to be executed by Python, an application archive
simply has to be a standard zip file containing a @code{__main__.py} file which
will be run as the entry point for the application.  As usual for any Python
script, the parent of the script (in this case the zip file) will be placed on
@ref{3e4,,sys.path} and thus further modules can be imported from the zip file.

The zip file format allows arbitrary data to be prepended to a zip file.  The
zip application format uses this ability to prepend a standard POSIX "shebang"
line to the file (@code{#!/path/to/interpreter}).

Formally, the Python zip application format is therefore:


@enumerate 

@item 
An optional shebang line, containing the characters @code{b'#!'} followed by an
interpreter name, and then a newline (@code{b'\n'}) character.  The interpreter
name can be anything acceptable to the OS "shebang" processing, or the Python
launcher on Windows.  The interpreter should be encoded in UTF-8 on Windows,
and in @ref{e53,,sys.getfilesystemencoding()} on POSIX.

@item 
Standard zipfile data, as generated by the @ref{137,,zipfile} module.  The
zipfile content `must' include a file called @code{__main__.py} (which must be
in the "root" of the zipfile - i.e., it cannot be in a subdirectory).  The
zipfile data can be compressed or uncompressed.
@end enumerate

If an application archive has a shebang line, it may have the executable bit set
on POSIX systems, to allow it to be executed directly.

There is no requirement that the tools in this module are used to create
application archives - the module is a convenience, but archives in the above
format created by any means are acceptable to Python.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python ランタイムサービス,カスタム Python インタプリタ,ソフトウェア・パッケージと配布,Python 標準ライブラリ
@anchor{library/python doc}@anchor{48e8}@anchor{library/python python}@anchor{48e9}@anchor{library/python python-runtime-services}@anchor{48ea}@anchor{library/python translation-repo}@anchor{48eb}
@section Python ランタイムサービス


この章では、Python インタープリタや Python 環境に深く関連する各種の機能を解説します。以下に一覧を示します:

@menu
* sys: sys --- システム固有のパラメーターと関数. システム固有のパラメーターと関数
* sys.monitoring: sys monitoring --- 実行イベントモニタリング. 実行イベントモニタリング
* sysconfig: sysconfig --- Python の構成情報へのアクセスを提供する. Python の構成情報へのアクセスを提供する
* builtins: builtins --- 組み込みオブジェクト. 組み込みオブジェクト
* __main__: __main__ --- トップレベルのコード環境. トップレベルのコード環境
* warnings: warnings --- 警告の制御. 警告の制御
* dataclasses: dataclasses --- データクラス. データクラス
* contextlib: contextlib --- with 文コンテキスト用ユーティリティ. with 文コンテキスト用ユーティリティ
* abc: abc --- 抽象基底クラス. 抽象基底クラス
* atexit: atexit --- 終了ハンドラー. 終了ハンドラー
* traceback: traceback --- スタックトレースの表示または取得. スタックトレースの表示または取得
* __future__: __future__ --- future 文の定義. future 文の定義
* gc: gc --- ガベージコレクターインターフェース. ガベージコレクターインターフェース
* inspect: inspect --- 活動中のオブジェクトを調査する. 活動中のオブジェクトを調査する
* annotationlib: annotationlib --- Functionality for introspecting annotations. Functionality for introspecting annotations
* site: site --- サイト固有の設定フック. サイト固有の設定フック

@end menu

@node sys --- システム固有のパラメーターと関数,sys monitoring --- 実行イベントモニタリング,,Python ランタイムサービス
@anchor{library/sys doc}@anchor{48ec}@anchor{library/sys module-sys}@anchor{df}@anchor{library/sys sys-system-specific-parameters-and-functions}@anchor{48ed}
@subsection @code{sys} --- システム固有のパラメーターと関数


@geindex module; sys


__________________________________________________________________


This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter. It is
always available. Unless explicitly noted otherwise, all variables are read-only.

@geindex abiflags (sys モジュール)
@anchor{library/sys sys abiflags}@anchor{c59}
@deffn {データ} sys.abiflags

Python が標準的な @code{configure} でビルトされた POSIX システムにおいて、
@geindex Python Enhancement Proposals; PEP 3149
PEP 3149@footnote{https://peps.python.org/pep-3149/} に記述された ABI フラグを含みます。


Added in version 3.2.



バージョン 3.8 で変更: デフォルトのフラグは空文字列になりました。 (pymalloc のための @code{m} フラグが取り除かれました)


@ref{213f,,Availability}: Unix.
@end deffn

@geindex addaudithook() (sys モジュール)
@anchor{library/sys sys addaudithook}@anchor{4750}
@deffn {の関数} sys.addaudithook (hook)

呼び出し可能な `hook' を現在の(サブ)インタープリタのアクティブな監査用フックのリストに加えます。

When an auditing event is raised through the @ref{191b,,sys.audit()} function, each
hook will be called in the order it was added with the event name and the
tuple of arguments. Native hooks added by @ref{4751,,PySys_AddAuditHook()} are
called first, followed by hooks added in the current (sub)interpreter.  Hooks
can then log the event, raise an exception to abort the operation,
or terminate the process entirely.

Note that audit hooks are primarily for collecting information about internal
or otherwise unobservable actions, whether by Python or libraries written in
Python. They are not suitable for implementing a "sandbox". In particular,
malicious code can trivially disable or bypass hooks added using this
function. At a minimum, any security-sensitive hooks must be added using the
C API @ref{4751,,PySys_AddAuditHook()} before initialising the runtime, and any
modules allowing arbitrary memory modification (such as @ref{2e,,ctypes}) should
be completely removed or closely monitored.


Calling @ref{4750,,sys.addaudithook()} will itself raise an auditing event
named @code{sys.addaudithook} with no arguments. If any
existing hooks raise an exception derived from @ref{244,,RuntimeError}, the
new hook will not be added and the exception suppressed. As a result,
callers cannot assume that their hook has been added unless they control
all existing hooks.


See the @ref{1c13,,audit events table} for all events raised by
CPython, and 
@geindex Python Enhancement Proposals; PEP 578
PEP 578@footnote{https://peps.python.org/pep-0578/} for the original design discussion.


Added in version 3.8.



バージョン 3.8.1 で変更: @ref{244,,RuntimeError} ではない @ref{bcd,,Exception} は抑制されなくなりました。


`CPython 実装の詳細:' When tracing is enabled (see @ref{2e1,,settrace()}), Python hooks are only
traced if the callable has a @code{__cantrace__} member that is set to a
true value. Otherwise, trace functions will skip the hook.
@end deffn

@geindex argv (sys モジュール)
@anchor{library/sys sys argv}@anchor{147c}
@deffn {データ} sys.argv

Pythonスクリプトに渡されたコマンドライン引数のリスト。 @code{argv[0]} はスクリプトの名前となりますが、フルパス名かどうかは、OSによって異なります。コマンドライン引数に @ref{1a8,,-c} を付けて Pythonを起動した場合、 @code{argv[0]} は文字列 @code{'-c'} となります。スクリプト名なしでPythonを起動した場合、 @code{argv[0]} は空文字列になります。

標準入力もしくはコマンドライン引数で指定されたファイルのリストに渡ってループするには、 @ref{5f,,fileinput} モジュールを参照してください。

See also @ref{a41,,sys.orig_argv}.

@cartouche
@quotation 注釈 
Unix では、コマンドライン引数は OS からバイト列で渡されます。
Python はそれをファイルシステムエンコーディングと "surrogateescape" エラーハンドラを使ってデコードします。
オリジナルのバイト列が必要なときには、 @code{[os.fsencode(arg) for arg in sys.argv]} で取得できます。
@end quotation
@end cartouche
@end deffn

@geindex audit() (sys モジュール)
@anchor{library/sys auditing}@anchor{1c6e}@anchor{library/sys sys audit}@anchor{191b}
@deffn {の関数} sys.audit (event, *args)

@geindex auditing

Raise an auditing event and trigger any active auditing hooks.
`event' is a string identifying the event, and `args' may contain
optional arguments with more information about the event.  The
number and types of arguments for a given event are considered a
public and stable API and should not be modified between releases.

For example, one auditing event is named @code{os.chdir}. This event has
one argument called `path' that will contain the requested new
working directory.

@ref{191b,,sys.audit()} will call the existing auditing hooks, passing
the event name and arguments, and will re-raise the first exception
from any hook. In general, if an exception is raised, it should not
be handled and the process should be terminated as quickly as
possible. This allows hook implementations to decide how to respond
to particular events: they can merely log the event or abort the
operation by raising an exception.

Hooks are added using the @ref{4750,,sys.addaudithook()} or
@ref{4751,,PySys_AddAuditHook()} functions.

The native equivalent of this function is @ref{613,,PySys_Audit()}. Using the
native function is preferred when possible.

See the @ref{1c13,,audit events table} for all events raised by
CPython.


Added in version 3.8.

@end deffn

@geindex base_exec_prefix (sys モジュール)
@anchor{library/sys sys base_exec_prefix}@anchor{3ea}
@deffn {データ} sys.base_exec_prefix

Equivalent to @ref{3eb,,exec_prefix}, but referring to the base Python installation.

When running under @ref{48b3,,Virtual Environments},
@ref{3eb,,exec_prefix} gets overwritten to the virtual environment prefix.
@ref{3ea,,base_exec_prefix}, conversely, does not change, and always points to
the base Python installation.
Refer to @ref{48b3,,Virtual Environments} for more information.


Added in version 3.3.

@end deffn

@geindex base_prefix (sys モジュール)
@anchor{library/sys sys base_prefix}@anchor{3e6}
@deffn {データ} sys.base_prefix

Equivalent to @ref{3e7,,prefix}, but referring to the base Python installation.

When running under @ref{3e8,,virtual environment},
@ref{3e7,,prefix} gets overwritten to the virtual environment prefix.
@ref{3e6,,base_prefix}, conversely, does not change, and always points to
the base Python installation.
Refer to @ref{48b3,,Virtual Environments} for more information.


Added in version 3.3.

@end deffn

@geindex byteorder (sys モジュール)
@anchor{library/sys sys byteorder}@anchor{25f7}
@deffn {データ} sys.byteorder

プラットフォームのバイト順を示します。ビッグエンディアン (最上位バイトが先頭) のプラットフォームでは @code{'big'}, リトルエンディアン (最下位バイトが先頭) では @code{'little'} となります。
@end deffn

@geindex builtin_module_names (sys モジュール)
@anchor{library/sys sys builtin_module_names}@anchor{2047}
@deffn {データ} sys.builtin_module_names

コンパイル時にPythonインタプリタに組み込まれた、全てのモジュール名を含む文字列のタプル(この情報は、他の手段では取得することができません。 @code{modules.keys()} は、インポートされたモジュールのみのリストを返します。)

See also the @ref{a42,,sys.stdlib_module_names} list.
@end deffn

@geindex call_tracing() (sys モジュール)
@anchor{library/sys sys call_tracing}@anchor{1bc3}
@deffn {の関数} sys.call_tracing (func, args)

Call @code{func(*args)}, while tracing is enabled.  The tracing state is saved,
and restored afterwards.  This is intended to be called from a debugger from
a checkpoint, to recursively debug or profile some other code.

Tracing is suspended while calling a tracing function set by
@ref{2e1,,settrace()} or @ref{1717,,setprofile()} to avoid infinite recursion.
@code{call_tracing()} enables explicit recursion of the tracing function.
@end deffn

@geindex copyright (sys モジュール)
@anchor{library/sys sys copyright}@anchor{48ee}
@deffn {データ} sys.copyright

Python インタプリタの著作権を表示する文字列です。
@end deffn

@geindex _clear_type_cache() (sys モジュール)
@anchor{library/sys sys _clear_type_cache}@anchor{292}
@deffn {の関数} sys._clear_type_cache ()

内部の型キャッシュをクリアします。型キャッシュは属性とメソッドの検索を高速化するために利用されます。この関数は、参照リークをデバッグするときに不要な参照を削除するため `だけ' に利用してください。

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。


バージョン 3.13 で非推奨: Use the more general @ref{364,,_clear_internal_caches()} function instead.

@end deffn

@geindex _clear_internal_caches() (sys モジュール)
@anchor{library/sys sys _clear_internal_caches}@anchor{364}
@deffn {の関数} sys._clear_internal_caches ()

Clear all internal performance-related caches. Use this function `only' to
release unnecessary references and memory blocks when hunting for leaks.


Added in version 3.13.

@end deffn

@geindex _current_frames() (sys モジュール)
@anchor{library/sys sys _current_frames}@anchor{164c}
@deffn {の関数} sys._current_frames ()

各スレッドの識別子を関数が呼ばれた時点のそのスレッドでアクティブになっている一番上のスタックフレームに結びつける辞書を返します。モジュール @ref{104,,traceback} の関数を使えばそのように与えられたフレームのコールスタックを構築できます。

この関数はデッドロックをデバッグするのに非常に有効です。デッドロック状態のスレッドの協調動作を必要としませんし、そういったスレッドのコールスタックはデッドロックである限りフリーズしたままです。デッドロックにないスレッドのフレームについては、そのフレームを調べるコードを呼んだ時にはそのスレッドの現在の実行状況とは関係ないところを指し示しているかもしれません。

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。

引数無しで @ref{1c6e,,監査イベント} @code{sys._current_frames} を送出します。
@end deffn

@geindex _current_exceptions() (sys モジュール)
@anchor{library/sys sys _current_exceptions}@anchor{6e9}
@deffn {の関数} sys._current_exceptions ()

Return a dictionary mapping each thread's identifier to the topmost exception
currently active in that thread at the time the function is called.
If a thread is not currently handling an exception, it is not included in
the result dictionary.

This is most useful for statistical profiling.

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。

引数無しで @ref{1c6e,,監査イベント} @code{sys._current_exceptions} を送出します。


バージョン 3.12 で変更: Each value in the dictionary is now a single exception instance, rather
than a 3-tuple as returned from @code{sys.exc_info()}.

@end deffn

@geindex breakpointhook() (sys モジュール)
@anchor{library/sys sys breakpointhook}@anchor{cd1}
@deffn {の関数} sys.breakpointhook ()

このフック関数は組み込みの @ref{271,,breakpoint()} から呼ばれます。
デフォルトでは、この関数は @ref{aa,,pdb} デバッガに処理を移行させますが、他の関数を設定することもでき、使用するデバッガを選べます。

この関数のシグネチャは何を呼び出すかに依存します。
例えば、(@code{pdb.set_trace()} などの) デフォルトの結び付けでは引数は求められませんが、追加の引数 (位置引数およびキーワード引数) を求める関数に結び付けるかもしれません。
組み込みの @code{breakpoint()} 関数は、自身の @code{*args} と @code{**kws} をそのまま渡します。
@code{breakpointhooks()} の返り値が何であれ、そのまま @code{breakpoint()} から返されます。

デフォルトの実装では、最初に環境変数 
@geindex PYTHONBREAKPOINT
@geindex 環境変数; PYTHONBREAKPOINT
@ref{cd2,,PYTHONBREAKPOINT} を調べます。
それが @code{"0"} に設定されていた場合は、この関数はすぐに終了します。つまり何もしません。
この環境変数が設定されていないか、空文字列に設定されていた場合は、 @code{pdb.set_trace()} が呼ばれます。
それ以外の場合は、この変数は実行する関数の名前である必要があります。関数名の指定では、例えば @code{package.subpackage.module.function} のようなドットでつながれた Python のインポートの命名体系を使ったを使います。
この場合では、 @code{package.subpackage.module} がインポートされ、そのインポートされたモジュールには @code{function()} という呼び出し可能オブジェクトがなくてはなりません。
この関数が渡された @code{*args} と @code{**kws} で実行され、 @code{function()} の返り値が何であれ @code{sys.breakpointhook()} は組み込みの @ref{271,,breakpoint()} 関数にその値をそのまま返します。

@geindex PYTHONBREAKPOINT
@geindex 環境変数; PYTHONBREAKPOINT
@ref{cd2,,PYTHONBREAKPOINT} で指名された呼び出し可能オブジェクトのインポートで何かしら問題が起きた場合、 @ref{4d7,,RuntimeWarning} が報告されブレークポイントは無視されることに注意してください。

また、 @code{sys.breakpointhook()} がプログラム上で上書きされていた場合は 
@geindex PYTHONBREAKPOINT
@geindex 環境変数; PYTHONBREAKPOINT
@ref{cd2,,PYTHONBREAKPOINT} は `調べられない' ことにも注意してください。


Added in version 3.7.

@end deffn

@geindex _debugmallocstats() (sys モジュール)
@anchor{library/sys sys _debugmallocstats}@anchor{48ef}
@deffn {の関数} sys._debugmallocstats ()

CPython のメモリアロケータの状態に関する低レベルの情報を標準エラー出力に出力します。

If Python is @ref{509,,built in debug mode} (@ref{666,,configure --with-pydebug option}), it also performs some expensive
internal consistency checks.


Added in version 3.3.


この関数は CPython 固有です。正確な出力形式は定義されていませんし、変更されるかもしれません。
@end deffn

@geindex dllhandle (sys モジュール)
@anchor{library/sys sys dllhandle}@anchor{48f0}
@deffn {データ} sys.dllhandle

Python DLLのハンドルを示す整数です。

@ref{213f,,Availability}: Windows.
@end deffn

@geindex displayhook() (sys モジュール)
@anchor{library/sys sys displayhook}@anchor{1738}
@deffn {の関数} sys.displayhook (value)

`value' が @code{None} 以外の時、@code{repr(value)} を @code{sys.stdout} に出力し、@code{builtins._} に保存します。@code{repr(value)} がエラーハンドラを @code{sys.stdout.errors} (おそらく @code{'strict'}) として @code{sys.stdout.encoding} にエンコードできない場合、エラーハンドラを @code{'backslashreplace'} として @code{sys.stdout.encoding} にエンコードします。

@code{sys.displayhook} は、Pythonの対話セッションで入力された @ref{23cf,,式} が評価されたときに呼び出されます。対話セッションの出力をカスタマイズする場合、 @code{sys.displayhook} に引数の数が一つの関数を指定します。

擬似コード:

@example
def displayhook(value):
    if value is None:
        return
    # Set '_' to None to avoid recursion
    builtins._ = None
    text = repr(value)
    try:
        sys.stdout.write(text)
    except UnicodeEncodeError:
        bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
        if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(bytes)
        else:
            text = bytes.decode(sys.stdout.encoding, 'strict')
            sys.stdout.write(text)
    sys.stdout.write("\n")
    builtins._ = value
@end example


バージョン 3.2 で変更: @ref{887,,UnicodeEncodeError} には @code{'backslashreplace'} エラーハンドラを指定してください。

@end deffn

@geindex dont_write_bytecode (sys モジュール)
@anchor{library/sys sys dont_write_bytecode}@anchor{48f1}
@deffn {データ} sys.dont_write_bytecode

この値が真の時、Python はソースモジュールをインポートする時に @code{.pyc} ファイルを生成しません。この値は @ref{15e6,,-B} コマンドラインオプションと 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@ref{15e7,,PYTHONDONTWRITEBYTECODE} 環境変数の値によって、起動時に @code{True} か @code{False} に設定されますが、実行時にこの変数を変更してバイトコード生成を制御することもできます。
@end deffn

@geindex _emscripten_info (sys モジュール)
@anchor{library/sys sys _emscripten_info}@anchor{1b8e}
@deffn {データ} sys._emscripten_info

A @ref{85e,,named tuple} holding information about the environment on the
`wasm32-emscripten' platform. The named tuple is provisional and may change
in the future.

@geindex emscripten_version (sys._emscripten_info の属性)
@anchor{library/sys sys _emscripten_info emscripten_version}@anchor{48f2}
@deffn {の属性} _emscripten_info.emscripten_version

Emscripten version as tuple of ints (major, minor, micro), e.g. @code{(3, 1, 8)}.
@end deffn

@geindex runtime (sys._emscripten_info の属性)
@anchor{library/sys sys _emscripten_info runtime}@anchor{48f3}
@deffn {の属性} _emscripten_info.runtime

Runtime string, e.g. browser user agent, @code{'Node.js v14.18.2'}, or @code{'UNKNOWN'}.
@end deffn

@geindex pthreads (sys._emscripten_info の属性)
@anchor{library/sys sys _emscripten_info pthreads}@anchor{48f4}
@deffn {の属性} _emscripten_info.pthreads

@code{True} if Python is compiled with Emscripten pthreads support.
@end deffn

@geindex shared_memory (sys._emscripten_info の属性)
@anchor{library/sys sys _emscripten_info shared_memory}@anchor{48f5}
@deffn {の属性} _emscripten_info.shared_memory

@code{True} if Python is compiled with shared memory support.
@end deffn

@ref{213f,,Availability}: Emscripten.


Added in version 3.11.

@end deffn

@geindex pycache_prefix (sys モジュール)
@anchor{library/sys sys pycache_prefix}@anchor{b9c}
@deffn {データ} sys.pycache_prefix

If this is set (not @code{None}), Python will write bytecode-cache @code{.pyc}
files to (and read them from) a parallel directory tree rooted at this
directory, rather than from @code{__pycache__} directories in the source code
tree. Any @code{__pycache__} directories in the source code tree will be ignored
and new @code{.pyc} files written within the pycache prefix. Thus if you use
@ref{21,,compileall} as a pre-build step, you must ensure you run it with the
same pycache prefix (if any) that you will use at runtime.

A relative path is interpreted relative to the current working directory.

This value is initially set based on the value of the @ref{16f,,-X}
@code{pycache_prefix=PATH} command-line option or the
@geindex PYTHONPYCACHEPREFIX
@geindex 環境変数; PYTHONPYCACHEPREFIX
@ref{b9b,,PYTHONPYCACHEPREFIX} environment variable (command-line takes
precedence). If neither are set, it is @code{None}.


Added in version 3.8.

@end deffn

@geindex excepthook() (sys モジュール)
@anchor{library/sys sys excepthook}@anchor{a0c}
@deffn {の関数} sys.excepthook (type, value, traceback)

指定したトレースバックと例外を @code{sys.stderr} に出力します。

When an exception other than @ref{f3c,,SystemExit} is raised and uncaught, the interpreter calls
@code{sys.excepthook} with three arguments, the exception class, exception
instance, and a traceback object.  In an interactive session this happens just
before control is returned to the prompt; in a Python program this happens just
before the program exits.  The handling of such top-level exceptions can be
customized by assigning another three-argument function to @code{sys.excepthook}.


Raise an auditing event @code{sys.excepthook} with arguments @code{hook},
@code{type}, @code{value}, @code{traceback} when an uncaught exception occurs.
If no hook has been set, @code{hook} may be @code{None}. If any hook raises
an exception derived from @ref{244,,RuntimeError} the call to the hook will
be suppressed. Otherwise, the audit hook exception will be reported as
unraisable and @code{sys.excepthook} will be called.



@subsubheading 参考


The @ref{507,,sys.unraisablehook()} function handles unraisable exceptions
and the @ref{a4b,,threading.excepthook()} function handles exception raised
by @ref{c31,,threading.Thread.run()}.

@end deffn

@geindex __breakpointhook__ (sys モジュール)
@geindex __displayhook__ (sys モジュール)
@geindex __excepthook__ (sys モジュール)
@geindex __unraisablehook__ (sys モジュール)
@anchor{library/sys sys __breakpointhook__}@anchor{48f6}
@deffn {データ} sys.__breakpointhook__
@anchor{library/sys sys __displayhook__}@anchor{48f7}
@deffnx {データ} sys.__displayhook__
@anchor{library/sys sys __excepthook__}@anchor{48f8}
@deffnx {データ} sys.__excepthook__
@anchor{library/sys sys __unraisablehook__}@anchor{48f9}
@deffnx {データ} sys.__unraisablehook__

これらのオブジェクトはそれぞれ、プログラム起動時の @code{breakpointhook}, @code{displayhook}, @code{excepthook}, @code{unraisablehook} の値を保存しています。
この値は、 @code{breakpointhook}, @code{displayhook}, @code{excepthook}, @code{unraisablehook} に不正なオブジェクトや別のオブジェクトが指定された場合に、元の値に復旧するために使用します。


Added in version 3.7: __breakpointhook__



Added in version 3.8: __unraisablehook__

@end deffn

@geindex exception() (sys モジュール)
@anchor{library/sys sys exception}@anchor{89b}
@deffn {の関数} sys.exception ()

This function, when called while an exception handler is executing (such as
an @code{except} or @code{except*} clause), returns the exception instance that
was caught by this handler. When exception handlers are nested within one
another, only the exception handled by the innermost handler is accessible.

If no exception handler is executing, this function returns @code{None}.


Added in version 3.11.

@end deffn

@geindex exc_info() (sys モジュール)
@anchor{library/sys sys exc_info}@anchor{89a}
@deffn {の関数} sys.exc_info ()

This function returns the old-style representation of the handled
exception. If an exception @code{e} is currently handled (so
@ref{89b,,exception()} would return @code{e}), @ref{89a,,exc_info()} returns the
tuple @code{(type(e), e, e.__traceback__)}.
That is, a tuple containing the type of the exception (a subclass of
@ref{7d6,,BaseException}), the exception itself, and a @ref{cec,,traceback object} which typically encapsulates the call
stack at the point where the exception last occurred.

@geindex object;traceback

If no exception is being handled anywhere on the stack, this function
return a tuple containing three @code{None} values.


バージョン 3.11 で変更: The @code{type} and @code{traceback} fields are now derived from the @code{value}
(the exception instance), so when an exception is modified while it is
being handled, the changes are reflected in the results of subsequent
calls to @ref{89a,,exc_info()}.

@end deffn

@geindex exec_prefix (sys モジュール)
@anchor{library/sys sys exec_prefix}@anchor{3eb}
@deffn {データ} sys.exec_prefix

Python のプラットフォーム依存なファイルがインストールされているディレクトリ名を示す文字列です。この値はサイト固有であり、デフォルトは @code{'/usr/local'} ですが、ビルド時に @code{configure} の @code{--exec-prefix} 引数で指定することができます。すべての設定ファイル (@code{pyconfig.h} など) は @code{`exec_prefix'/lib/python`X.Y'/config} に、共有ライブラリは @code{`exec_prefix'/lib/python`X.Y'/lib-dynload} にインストールされます (`X.Y' は @code{3.2} のような Python のバージョン番号)。

@cartouche
@quotation 注釈 
If a @ref{3e8,,virtual environment} is in effect, this @ref{3eb,,exec_prefix}
will point to the virtual environment. The value for the Python installation
will still be available, via @ref{3ea,,base_exec_prefix}.
Refer to @ref{48b3,,Virtual Environments} for more information.
@end quotation
@end cartouche


バージョン 3.14 で変更: When running under a @ref{3e8,,virtual environment},
@ref{3e7,,prefix} and @ref{3eb,,exec_prefix} are now set to the virtual
environment prefix by the @ref{18dc,,path initialization},
instead of @ref{cc,,site}. This means that @ref{3e7,,prefix} and
@ref{3eb,,exec_prefix} always point to the virtual environment, even when
@ref{cc,,site} is disabled (@ref{13c0,,-S}).

@end deffn

@geindex executable (sys モジュール)
@anchor{library/sys sys executable}@anchor{3ed}
@deffn {データ} sys.executable

Python インタプリタの実行ファイルの絶対パスを示す文字列です。このような名前が意味を持つシステムで利用可能です。Python が自身の実行ファイルの実際のパスを取得できない場合、@ref{3ed,,sys.executable} は空の文字列または @code{None} になります。
@end deffn

@geindex exit() (sys モジュール)
@anchor{library/sys sys exit}@anchor{277}
@deffn {の関数} sys.exit ([arg])

Raise a @ref{f3c,,SystemExit} exception, signaling an intention to exit the interpreter.

The optional argument `arg' can be an integer giving the exit status
(defaulting to zero), or another type of object.  If it is an integer, zero
is considered "successful termination" and any nonzero value is considered
"abnormal termination" by shells and the like.  Most systems require it to be
in the range 0--127, and produce undefined results otherwise.  Some systems
have a convention for assigning specific meanings to specific exit codes, but
these are generally underdeveloped; Unix programs generally use 2 for command
line syntax errors and 1 for all other kinds of errors.  If another type of
object is passed, @code{None} is equivalent to passing zero, and any other
object is printed to @ref{b33,,stderr} and results in an exit code of 1.  In
particular, @code{sys.exit("some error message")} is a quick way to exit a
program when an error occurs.

Since @ref{25e7,,exit()} ultimately "only" raises an exception, it will only exit
the process when called from the main thread, and the exception is not
intercepted. Cleanup actions specified by finally clauses of @ref{8f8,,try} statements
are honored, and it is possible to intercept the exit attempt at an outer level.


バージョン 3.6 で変更: Python インタープリタが (バッファされたデータを標準ストリームに吐き出すときのエラーなどの) @ref{f3c,,SystemExit} を捕捉した後の後始末でエラーが起きた場合、終了ステータスは 120 に変更されます。

@end deffn

@geindex flags (sys モジュール)
@anchor{library/sys sys flags}@anchor{89c}
@deffn {データ} sys.flags

The @ref{85e,,named tuple} `flags' exposes the status of command line
flags.  Flags should only be accessed only by name and not by index.  The
attributes are read only.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@geindex debug (sys.flags の属性)
@anchor{library/sys sys flags debug}@anchor{48fa}
@deffn {の属性} flags.debug
@end deffn

@tab

@ref{2123,,-d}

@item

@geindex inspect (sys.flags の属性)
@anchor{library/sys sys flags inspect}@anchor{1790}
@deffn {の属性} flags.inspect
@end deffn

@tab

@ref{16f4,,-i}

@item

@geindex interactive (sys.flags の属性)
@anchor{library/sys sys flags interactive}@anchor{48fb}
@deffn {の属性} flags.interactive
@end deffn

@tab

@ref{16f4,,-i}

@item

@geindex isolated (sys.flags の属性)
@anchor{library/sys sys flags isolated}@anchor{48fc}
@deffn {の属性} flags.isolated
@end deffn

@tab

@ref{b57,,-I}

@item

@geindex optimize (sys.flags の属性)
@anchor{library/sys sys flags optimize}@anchor{48fd}
@deffn {の属性} flags.optimize
@end deffn

@tab

@ref{18c,,-O} または @ref{fb5,,-OO}

@item

@geindex dont_write_bytecode (sys.flags の属性)
@anchor{library/sys sys flags dont_write_bytecode}@anchor{48fe}
@deffn {の属性} flags.dont_write_bytecode
@end deffn

@tab

@ref{15e6,,-B}

@item

@geindex no_user_site (sys.flags の属性)
@anchor{library/sys sys flags no_user_site}@anchor{48ff}
@deffn {の属性} flags.no_user_site
@end deffn

@tab

@ref{15a6,,-s}

@item

@geindex no_site (sys.flags の属性)
@anchor{library/sys sys flags no_site}@anchor{4900}
@deffn {の属性} flags.no_site
@end deffn

@tab

@ref{13c0,,-S}

@item

@geindex ignore_environment (sys.flags の属性)
@anchor{library/sys sys flags ignore_environment}@anchor{4901}
@deffn {の属性} flags.ignore_environment
@end deffn

@tab

@ref{b56,,-E}

@item

@geindex verbose (sys.flags の属性)
@anchor{library/sys sys flags verbose}@anchor{4902}
@deffn {の属性} flags.verbose
@end deffn

@tab

@ref{163e,,-v}

@item

@geindex bytes_warning (sys.flags の属性)
@anchor{library/sys sys flags bytes_warning}@anchor{4903}
@deffn {の属性} flags.bytes_warning
@end deffn

@tab

@ref{7f9,,-b}

@item

@geindex quiet (sys.flags の属性)
@anchor{library/sys sys flags quiet}@anchor{4904}
@deffn {の属性} flags.quiet
@end deffn

@tab

@ref{177e,,-q}

@item

@geindex hash_randomization (sys.flags の属性)
@anchor{library/sys sys flags hash_randomization}@anchor{4905}
@deffn {の属性} flags.hash_randomization
@end deffn

@tab

@ref{1e78,,-R}

@item

@geindex dev_mode (sys.flags の属性)
@anchor{library/sys sys flags dev_mode}@anchor{1e82}
@deffn {の属性} flags.dev_mode
@end deffn

@tab

@ref{16f,,-X dev} (@ref{508,,Python Development Mode})

@item

@geindex utf8_mode (sys.flags の属性)
@anchor{library/sys sys flags utf8_mode}@anchor{4906}
@deffn {の属性} flags.utf8_mode
@end deffn

@tab

@ref{16f,,-X utf8}

@item

@geindex safe_path (sys.flags の属性)
@anchor{library/sys sys flags safe_path}@anchor{53e}
@deffn {の属性} flags.safe_path
@end deffn

@tab

@ref{7c1,,-P}

@item

@geindex int_max_str_digits (sys.flags の属性)
@anchor{library/sys sys flags int_max_str_digits}@anchor{26db}
@deffn {の属性} flags.int_max_str_digits
@end deffn

@tab

@ref{16f,,-X int_max_str_digits}
(@ref{80b,,integer string conversion length limitation})

@item

@geindex warn_default_encoding (sys.flags の属性)
@anchor{library/sys sys flags warn_default_encoding}@anchor{4907}
@deffn {の属性} flags.warn_default_encoding
@end deffn

@tab

@ref{16f,,-X warn_default_encoding}

@item

@geindex gil (sys.flags の属性)
@anchor{library/sys sys flags gil}@anchor{4908}
@deffn {の属性} flags.gil
@end deffn

@tab

@ref{16f,,-X gil} and 
@geindex PYTHON_GIL
@geindex 環境変数; PYTHON_GIL
@ref{49a,,PYTHON_GIL}

@item

@geindex thread_inherit_context (sys.flags の属性)
@anchor{library/sys sys flags thread_inherit_context}@anchor{175}
@deffn {の属性} flags.thread_inherit_context
@end deffn

@tab

@ref{16f,,-X thread_inherit_context} and
@geindex PYTHON_THREAD_INHERIT_CONTEXT
@geindex 環境変数; PYTHON_THREAD_INHERIT_CONTEXT
@ref{1868,,PYTHON_THREAD_INHERIT_CONTEXT}

@item

@geindex context_aware_warnings (sys.flags の属性)
@anchor{library/sys sys flags context_aware_warnings}@anchor{18a}
@deffn {の属性} flags.context_aware_warnings
@end deffn

@tab

@ref{16f,,-X context_aware_warnings} and
@geindex PYTHON_CONTEXT_AWARE_WARNINGS
@geindex 環境変数; PYTHON_CONTEXT_AWARE_WARNINGS
@ref{185b,,PYTHON_CONTEXT_AWARE_WARNINGS}

@end multitable



バージョン 3.2 で変更: 新しい @ref{177e,,-q} 向けに @code{quiet} 属性が追加されました。



Added in version 3.2.3: @code{hash_randomization} 属性が追加されました。



バージョン 3.3 で変更: 廃止済みの @code{division_warning} 属性を削除しました。



バージョン 3.4 で変更: @ref{b57,,-I} @code{isolated} フラグ向けに @code{isolated} 属性が追加されました。



バージョン 3.7 で変更: 新しい @ref{508,,Python 開発モード} 向けに @code{dev_mode} 属性が、新しい @ref{16f,,-X} @code{utf8} フラグ向けに @code{utf8_mode} 属性が追加されました。



バージョン 3.10 で変更: Added @code{warn_default_encoding} attribute for @ref{16f,,-X} @code{warn_default_encoding} flag.



バージョン 3.11 で変更: Added the @code{safe_path} attribute for @ref{7c1,,-P} option.



バージョン 3.11 で変更: Added the @code{int_max_str_digits} attribute.



バージョン 3.13 で変更: Added the @code{gil} attribute.



バージョン 3.14 で変更: Added the @code{thread_inherit_context} attribute.



バージョン 3.14 で変更: Added the @code{context_aware_warnings} attribute.

@end deffn

@geindex float_info (sys モジュール)
@anchor{library/sys sys float_info}@anchor{1dcf}
@deffn {データ} sys.float_info

float 型に関する情報を保持している @ref{85e,,名前付きタプル} です。精度と内部表現に関する低レベル情報を含んでいます。これらの値は 'C' 言語の標準ヘッダファイル @code{float.h} で定義されている様々な浮動小数点定数に対応しています。詳細は 1999 ISO/IEC C standard @ref{4909,,[C99]} の 5.2.4.2.2 節 'Characteristics of floating types' を参照してください。
Attributes of the @code{float_info} named tuple



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

float.h のマクロ

@tab

説明

@item

@geindex epsilon (sys.float_info の属性)
@anchor{library/sys sys float_info epsilon}@anchor{490a}
@deffn {の属性} float_info.epsilon
@end deffn

@tab

@code{DBL_EPSILON}

@tab

difference between 1.0 and the least value greater than 1.0 that is
representable as a float.

@ref{b0e,,math.ulp()} を参照してください。

@item

@geindex dig (sys.float_info の属性)
@anchor{library/sys sys float_info dig}@anchor{490b}
@deffn {の属性} float_info.dig
@end deffn

@tab

@code{DBL_DIG}

@tab

The maximum number of decimal digits that can be faithfully
represented in a float; see below.

@item

@geindex mant_dig (sys.float_info の属性)
@anchor{library/sys sys float_info mant_dig}@anchor{490c}
@deffn {の属性} float_info.mant_dig
@end deffn

@tab

@code{DBL_MANT_DIG}

@tab

Float precision: the number of base-@code{radix} digits in the
significand of a float.

@item

@geindex max (sys.float_info の属性)
@anchor{library/sys sys float_info max}@anchor{490d}
@deffn {の属性} float_info.max
@end deffn

@tab

@code{DBL_MAX}

@tab

The maximum representable positive finite float.

@item

@geindex max_exp (sys.float_info の属性)
@anchor{library/sys sys float_info max_exp}@anchor{490e}
@deffn {の属性} float_info.max_exp
@end deffn

@tab

@code{DBL_MAX_EXP}

@tab

The maximum integer `e' such that @code{radix**(e-1)} is a representable
finite float.

@item

@geindex max_10_exp (sys.float_info の属性)
@anchor{library/sys sys float_info max_10_exp}@anchor{490f}
@deffn {の属性} float_info.max_10_exp
@end deffn

@tab

@code{DBL_MAX_10_EXP}

@tab

The maximum integer `e' such that @code{10**e} is in the range of
representable finite floats.

@item

@geindex min (sys.float_info の属性)
@anchor{library/sys sys float_info min}@anchor{4910}
@deffn {の属性} float_info.min
@end deffn

@tab

@code{DBL_MIN}

@tab

The minimum representable positive `normalized' float.

Use @ref{b0e,,math.ulp(0.0)} to get the smallest positive
`denormalized' representable float.

@item

@geindex min_exp (sys.float_info の属性)
@anchor{library/sys sys float_info min_exp}@anchor{4911}
@deffn {の属性} float_info.min_exp
@end deffn

@tab

@code{DBL_MIN_EXP}

@tab

The minimum integer `e' such that @code{radix**(e-1)} is a normalized
float.

@item

@geindex min_10_exp (sys.float_info の属性)
@anchor{library/sys sys float_info min_10_exp}@anchor{4912}
@deffn {の属性} float_info.min_10_exp
@end deffn

@tab

@code{DBL_MIN_10_EXP}

@tab

The minimum integer `e' such that @code{10**e} is a normalized float.

@item

@geindex radix (sys.float_info の属性)
@anchor{library/sys sys float_info radix}@anchor{4913}
@deffn {の属性} float_info.radix
@end deffn

@tab

@code{FLT_RADIX}

@tab

The radix of exponent representation.

@item

@geindex rounds (sys.float_info の属性)
@anchor{library/sys sys float_info rounds}@anchor{4914}
@deffn {の属性} float_info.rounds
@end deffn

@tab

@code{FLT_ROUNDS}

@tab

An integer representing the rounding mode for floating-point arithmetic.
This reflects the value of the system @code{FLT_ROUNDS} macro
at interpreter startup time:


@itemize *

@item 
@code{-1}: indeterminable

@item 
@code{0}: toward zero

@item 
@code{1}: to nearest

@item 
@code{2}: toward positive infinity

@item 
@code{3}: toward negative infinity
@end itemize

All other values for @code{FLT_ROUNDS} characterize
implementation-defined rounding behavior.

@end multitable


The attribute @ref{490b,,sys.float_info.dig} needs further explanation.  If
@code{s} is any string representing a decimal number with at most
@code{sys.float_info.dig} significant digits, then converting @code{s} to a
float and back again will recover a string representing the same decimal
value:

@example
>>> import sys
>>> sys.float_info.dig
15
>>> s = '3.14159265358979'    # decimal string with 15 significant digits
>>> format(float(s), '.15g')  # convert to float and back -> same value
'3.14159265358979'
@end example

ただし、文字列が有効桁数 @ref{490b,,sys.float_info.dig} より大きい場合には、常に復元されるとは限りません:

@example
>>> s = '9876543211234567'    # 16 significant digits is too many!
>>> format(float(s), '.16g')  # conversion changes value
'9876543211234568'
@end example
@end deffn

@geindex float_repr_style (sys モジュール)
@anchor{library/sys sys float_repr_style}@anchor{1512}
@deffn {データ} sys.float_repr_style

@ref{1c1,,repr()} 関数が浮動小数点数に対してどう振る舞うかを示す文字列です。この文字列が値 @code{'short'} を持てば、有限の浮動小数点数 @code{x} に対して、@code{repr(x)} は @code{float(repr(x)) == x} を満たす短い文字列を返そうとします。これは、Python 3.1 以降での標準の振る舞いです。それ以外の場合、@code{float_repr_style} は値 @code{'legacy'} を持ち、@code{repr(x)} は 3.1 以前のバージョンの Python と同じように振る舞います。


Added in version 3.1.

@end deffn

@geindex getallocatedblocks() (sys モジュール)
@anchor{library/sys sys getallocatedblocks}@anchor{11c9}
@deffn {の関数} sys.getallocatedblocks ()

Return the number of memory blocks currently allocated by the interpreter,
regardless of their size.  This function is mainly useful for tracking
and debugging memory leaks.  Because of the interpreter's internal
caches, the result can vary from call to call; you may have to call
@ref{364,,_clear_internal_caches()} and @ref{1b3,,gc.collect()} to get more
predictable results.

If a Python build or implementation cannot reasonably compute this
information, @ref{11c9,,getallocatedblocks()} is allowed to return 0 instead.


Added in version 3.4.

@end deffn

@geindex getunicodeinternedsize() (sys モジュール)
@anchor{library/sys sys getunicodeinternedsize}@anchor{4915}
@deffn {の関数} sys.getunicodeinternedsize ()

Return the number of unicode objects that have been interned.


Added in version 3.12.

@end deffn

@geindex getandroidapilevel() (sys モジュール)
@anchor{library/sys sys getandroidapilevel}@anchor{d83}
@deffn {の関数} sys.getandroidapilevel ()

Return the build-time API level of Android as an integer. This represents the
minimum version of Android this build of Python can run on. For runtime
version information, see @ref{19c6,,platform.android_ver()}.

@ref{213f,,Availability}: Android.


Added in version 3.7.

@end deffn

@geindex getdefaultencoding() (sys モジュール)
@anchor{library/sys sys getdefaultencoding}@anchor{4916}
@deffn {の関数} sys.getdefaultencoding ()

Return @code{'utf-8'}. This is the name of the default string encoding, used
in methods like @ref{ad2,,str.encode()}.
@end deffn

@geindex getdlopenflags() (sys モジュール)
@anchor{library/sys sys getdlopenflags}@anchor{1727}
@deffn {の関数} sys.getdlopenflags ()

Return the current value of the flags that are used for
@code{dlopen()} calls.  Symbolic names for the flag values can be
found in the @ref{a5,,os} module (@code{RTLD_@var{xxx}} constants, e.g.
@ref{1330,,os.RTLD_LAZY}).

@ref{213f,,Availability}: Unix.
@end deffn

@geindex getfilesystemencoding() (sys モジュール)
@anchor{library/sys sys getfilesystemencoding}@anchor{e53}
@deffn {の関数} sys.getfilesystemencoding ()

Get the @ref{75d,,filesystem encoding}:
the encoding used with the @ref{75d,,filesystem error handler} to convert between Unicode filenames and bytes
filenames. The filesystem error handler is returned from
@ref{ee2,,getfilesystemencodeerrors()}.

最良の互換性のために、たとえファイル名の表現に bytes がサポートされていたとしても、全てのケースで str をファイル名に使うべきです。
ファイル名を受け取ったり返したりする関数は str と bytes をサポートし、すぐにシステムにとって好ましい表現に変換すべきです。

@ref{e4f,,os.fsencode()} や @ref{e4e,,os.fsdecode()} を、正しいエンコーディングやエラーモードが使われていることを保証するために使うべきです。

term:@cite{ファイルシステムのエンコーディングとエラーハンドラ <filesystem encoding and error handler>} は、Pythonの開始時に:c:func:@cite{PyConfig_Read} 関数により設定されます。 @ref{3f7,,PyConfig} のメンバー @ref{41b,,filesystem_encoding} と @ref{41c,,filesystem_errors} を参照してください。


バージョン 3.2 で変更: @ref{e53,,getfilesystemencoding()} の結果が @code{None} になることはなくなりました。



バージョン 3.6 で変更: Windows はもう @code{'mbcs'} を返す保証は無くなりました。
より詳しいことは 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} および @ref{33e,,_enablelegacywindowsfsencoding()} を参照してください。



バージョン 3.7 で変更: @ref{866,,Python UTF-8 モード} が有効なら @code{"utf-8"} を返します。

@end deffn

@geindex getfilesystemencodeerrors() (sys モジュール)
@anchor{library/sys sys getfilesystemencodeerrors}@anchor{ee2}
@deffn {の関数} sys.getfilesystemencodeerrors ()

Get the @ref{75d,,filesystem error handler}: the error handler used with the @ref{75d,,filesystem encoding} to convert between Unicode
filenames and bytes filenames. The filesystem encoding is returned from
@ref{e53,,getfilesystemencoding()}.

@ref{e4f,,os.fsencode()} や @ref{e4e,,os.fsdecode()} を、正しいエンコーディングやエラーモードが使われていることを保証するために使うべきです。

term:@cite{ファイルシステムのエンコーディングとエラーハンドラ <filesystem encoding and error handler>} は、Pythonの開始時に:c:func:@cite{PyConfig_Read} 関数により設定されます。 @ref{3f7,,PyConfig} のメンバー @ref{41b,,filesystem_encoding} と @ref{41c,,filesystem_errors} を参照してください。


Added in version 3.6.

@end deffn

@geindex get_int_max_str_digits() (sys モジュール)
@anchor{library/sys sys get_int_max_str_digits}@anchor{1818}
@deffn {の関数} sys.get_int_max_str_digits ()

Returns the current value for the @ref{80b,,integer string conversion length limitation}. See also @ref{18f1,,set_int_max_str_digits()}.


Added in version 3.11.

@end deffn

@geindex getrefcount() (sys モジュール)
@anchor{library/sys sys getrefcount}@anchor{2ce}
@deffn {の関数} sys.getrefcount (object)

`object' の参照数を返します。 `object' は (一時的に) @ref{2ce,,getrefcount()} からも参照されるため、参照数は予想される数よりも 1 多くなります。

戻り値は、実際に保持されているオブジェクトの参照の数を実際に反映しているとは限らないことに注意してください。例えば、一部のオブジェクトは永続 (@ref{290,,immortal}) であり、実際の参照の数を反映しない非常に高い参照数を持ちます。したがって、 0 か 1 の値以外では、正確な戻り値に頼らないでください。

`CPython 実装の詳細:' @ref{290,,Immortal} objects with a large reference count can be
identified via @ref{28f,,_is_immortal()}.


バージョン 3.12 で変更: Immortal objects have very large refcounts that do not match
the actual number of references to the object.

@end deffn

@geindex getrecursionlimit() (sys モジュール)
@anchor{library/sys sys getrecursionlimit}@anchor{6eb}
@deffn {の関数} sys.getrecursionlimit ()

現在の最大再帰数を返します。最大再帰数は、Python インタプリタスタックの最大の深さです。この制限は Python プログラムが無限に再帰し、C スタックがオーバーフローしてクラッシュすることを防止するために設けられています。この値は @ref{6ea,,setrecursionlimit()} で指定することができます。
@end deffn

@geindex getsizeof() (sys モジュール)
@anchor{library/sys sys getsizeof}@anchor{1adb}
@deffn {の関数} sys.getsizeof (object[, default])

`object' のサイズをバイト数で返します。`object' は任意の型のオブジェクトです。すべての組み込みオブジェクトは正しい値を返します。サードパーティー製の型については実装依存になります。

オブジェクトに直接起因するメモリ消費のみを表し、参照するオブジェクトは含みません。

オブジェクトがサイズを取得する手段を提供していない時は `default' が返されます。`default' が指定されていない場合は @ref{198,,TypeError} が送出されます。

@ref{1adb,,getsizeof()} は `object' の @code{__sizeof__} メソッドを呼び出し、そのオブジェクトがガベージコレクタに管理されていた場合はガベージコレクタのオーバーヘッドを増やします。

See recursive sizeof recipe@footnote{https://code.activestate.com/recipes/577504-compute-memory-footprint-of-an-object-and-its-cont/}
for an example of using @ref{1adb,,getsizeof()} recursively to find the size of
containers and all their contents.
@end deffn

@geindex getswitchinterval() (sys モジュール)
@anchor{library/sys sys getswitchinterval}@anchor{b43}
@deffn {の関数} sys.getswitchinterval ()

Return the interpreter's "thread switch interval" in seconds; see
@ref{b44,,setswitchinterval()}.


Added in version 3.2.

@end deffn

@geindex _getframe() (sys モジュール)
@anchor{library/sys sys _getframe}@anchor{8f0}
@deffn {の関数} sys._getframe ([depth])

コールスタックからフレームオブジェクトを返します。オプション引数 `depth' を指定すると、スタックのトップから `depth' だけ下のフレームオブジェクトを取得します。 `depth' がコールスタックよりも深ければ、 @ref{2ec,,ValueError} が発生します。 `depth' のデフォルト値は 0 で、この場合はコールスタックのトップのフレームを返します。

引数 @code{frame} で @ref{1c6e,,監査イベント} @code{sys._getframe} を送出します。

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。全ての Python 実装で存在することが保証されているわけではありません。
@end deffn

@geindex _getframemodulename() (sys モジュール)
@anchor{library/sys sys _getframemodulename}@anchor{1adf}
@deffn {の関数} sys._getframemodulename ([depth])

Return the name of a module from the call stack.  If optional integer `depth'
is given, return the module that many calls below the top of the stack.  If
that is deeper than the call stack, or if the module is unidentifiable,
@code{None} is returned.  The default for `depth' is zero, returning the
module at the top of the call stack.

Raises an @ref{1c6e,,auditing event} @code{sys._getframemodulename} with argument @code{depth}.

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。全ての Python 実装で存在することが保証されているわけではありません。


Added in version 3.12.

@end deffn

@geindex getobjects() (sys モジュール)
@anchor{library/sys sys getobjects}@anchor{28e}
@deffn {の関数} sys.getobjects (limit[, type])

This function only exists if CPython was built using the
specialized configure option @ref{636,,--with-trace-refs}.
It is intended only for debugging garbage-collection issues.

Return a list of up to `limit' dynamically allocated Python objects.
If `type' is given, only objects of that exact type (not subtypes)
are included.

Objects from the list are not safe to use.
Specifically, the result will include objects from all interpreters that
share their object allocator state (that is, ones created with
@ref{4917,,PyInterpreterConfig.use_main_obmalloc} set to 1
or using @ref{1b31,,Py_NewInterpreter()}, and the
@ref{163,,main interpreter}).
Mixing objects from different interpreters may lead to crashes
or other unexpected behavior.

`CPython 実装の詳細:' This function should be used for specialized purposes only.
It is not guaranteed to exist in all implementations of Python.


バージョン 3.14 で変更: The result may include objects from other interpreters.

@end deffn

@geindex getprofile() (sys モジュール)
@anchor{library/sys sys getprofile}@anchor{15f9}
@deffn {の関数} sys.getprofile ()

@geindex profile function
@geindex profiler

@ref{1717,,setprofile()} 関数で設定したプロファイラ関数を取得します。
@end deffn

@geindex gettrace() (sys モジュール)
@anchor{library/sys sys gettrace}@anchor{15fa}
@deffn {の関数} sys.gettrace ()

@geindex trace function
@geindex debugger

@ref{2e1,,settrace()} 関数で設定したトレース関数を取得します。

@ref{15fa,,gettrace()} 関数は、デバッガ、プロファイラ、カバレッジツールなどの実装に使うことのみを想定しています。この関数の振る舞いは言語定義ではなく実装プラットフォームの一部です。そのため、他の Python 実装では利用できないかもしれません。
@end deffn

@geindex getwindowsversion() (sys モジュール)
@anchor{library/sys sys getwindowsversion}@anchor{ee3}
@deffn {の関数} 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' は 3-タプル、それ以外は整数です。
この構成要素には名前でもアクセスできるので、 @code{sys.getwindowsversion()[0]} は @code{sys.getwindowsversion().major} と等価です。
先行のバージョンとの互換性のため、最初の 5 要素のみが添字の指定で取得できます。

`platform' will be @code{2} (VER_PLATFORM_WIN32_NT).

`product_type' は、以下の値のいずれかになります。:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定数

@tab

意味

@item

@code{1} (VER_NT_WORKSTATION)

@tab

システムはワークステーションです。

@item

@code{2} (VER_NT_DOMAIN_CONTROLLER)

@tab

システムはドメインコントローラです。

@item

@code{3} (VER_NT_SERVER)

@tab

システムはサーバですが、ドメインコントローラではありません。

@end multitable


This function wraps the Win32 @code{GetVersionEx()} function; see the
Microsoft documentation on @code{OSVERSIONINFOEX()} for more information
about these fields.

`platform_version' は、プロセスでエミュレートされているバージョンではなく、現在のオペレーティングシステムのメジャーバージョン、マイナーバージョン、ビルドナンバーを返します。
この関数は機能の検知ではなくロギングで使うためのものです。

@cartouche
@quotation 注釈 
`platform_version' derives the version from kernel32.dll which can be of a different
version than the OS version. Please use @ref{af,,platform} module for achieving accurate
OS version.
@end quotation
@end cartouche

@ref{213f,,Availability}: Windows.


バージョン 3.2 で変更: 名前付きタプルに変更され、 `service_pack_minor', `service_pack_major', `suite_mask', および `product_type' が追加されました。



バージョン 3.6 で変更: `platform_version' の追加

@end deffn

@geindex get_asyncgen_hooks() (sys モジュール)
@anchor{library/sys sys get_asyncgen_hooks}@anchor{1bc4}
@deffn {の関数} sys.get_asyncgen_hooks ()

`asyncgen_hooks' オブジェクトを返します。このオブジェクトは @code{(firstiter, finalizer)} という形の @ref{4e0,,namedtuple} に似た形をしています。 `firstiter' と `finalizer' は両方とも @code{None} か、 @ref{4918,,asynchronous generator iterator} を引数に取る関数と、イベントループが非同期ジェネレータの終了処理をスケジューリングするのに使う関数であることが求められます。


Added in version 3.6: より詳しくは 
@geindex Python Enhancement Proposals; PEP 525
PEP 525@footnote{https://peps.python.org/pep-0525/} を参照してください。


@cartouche
@quotation 注釈 
This function has been added on a provisional basis (see 
@geindex Python Enhancement Proposals; PEP 411
PEP 411@footnote{https://peps.python.org/pep-0411/}
for details.)
@end quotation
@end cartouche
@end deffn

@geindex get_coroutine_origin_tracking_depth() (sys モジュール)
@anchor{library/sys sys get_coroutine_origin_tracking_depth}@anchor{d84}
@deffn {の関数} sys.get_coroutine_origin_tracking_depth ()

Get the current coroutine origin tracking depth, as set by
@ref{d85,,set_coroutine_origin_tracking_depth()}.


Added in version 3.7.


@cartouche
@quotation 注釈 
This function has been added on a provisional basis (see 
@geindex Python Enhancement Proposals; PEP 411
PEP 411@footnote{https://peps.python.org/pep-0411/}
for details.)  Use it only for debugging purposes.
@end quotation
@end cartouche
@end deffn

@geindex hash_info (sys モジュール)
@anchor{library/sys sys hash_info}@anchor{1201}
@deffn {データ} sys.hash_info

数値のハッシュ実装のパラメータを与える @ref{85e,,named tuple} です。数値型のハッシュ化についての詳細は @ref{25fe,,数値型のハッシュ化} を参照してください。

@geindex width (sys.hash_info の属性)
@anchor{library/sys sys hash_info width}@anchor{4919}
@deffn {の属性} hash_info.width

The width in bits used for hash values
@end deffn

@geindex modulus (sys.hash_info の属性)
@anchor{library/sys sys hash_info modulus}@anchor{25ff}
@deffn {の属性} hash_info.modulus

The prime modulus P used for numeric hash scheme
@end deffn

@geindex inf (sys.hash_info の属性)
@anchor{library/sys sys hash_info inf}@anchor{491a}
@deffn {の属性} hash_info.inf

The hash value returned for a positive infinity
@end deffn

@geindex nan (sys.hash_info の属性)
@anchor{library/sys sys hash_info nan}@anchor{491b}
@deffn {の属性} hash_info.nan

(This attribute is no longer used)
@end deffn

@geindex imag (sys.hash_info の属性)
@anchor{library/sys sys hash_info imag}@anchor{491c}
@deffn {の属性} hash_info.imag

The multiplier used for the imaginary part of a complex number
@end deffn

@geindex algorithm (sys.hash_info の属性)
@anchor{library/sys sys hash_info algorithm}@anchor{491d}
@deffn {の属性} hash_info.algorithm

The name of the algorithm for hashing of str, bytes, and memoryview
@end deffn

@geindex hash_bits (sys.hash_info の属性)
@anchor{library/sys sys hash_info hash_bits}@anchor{491e}
@deffn {の属性} hash_info.hash_bits

The internal output size of the hash algorithm
@end deffn

@geindex seed_bits (sys.hash_info の属性)
@anchor{library/sys sys hash_info seed_bits}@anchor{491f}
@deffn {の属性} hash_info.seed_bits

The size of the seed key of the hash algorithm
@end deffn

@geindex cutoff (sys.hash_info の属性)
@anchor{library/sys sys hash_info cutoff}@anchor{4920}
@deffn {の属性} hash_info.cutoff

Cutoff for small string DJBX33A optimization in range @code{[1, cutoff)}.
@end deffn


Added in version 3.2.



バージョン 3.4 で変更: Added `algorithm', `hash_bits', `seed_bits', and `cutoff'.

@end deffn

@geindex hexversion (sys モジュール)
@anchor{library/sys sys hexversion}@anchor{4921}
@deffn {データ} sys.hexversion

単精度整数にエンコードされたバージョン番号。この値は新バージョン(正規リリース以外であっても)ごとにかならず増加します。例えば、Python 1.5.2 以降でのみ動作するプログラムでは、以下のようなチェックを行います。

@example
if sys.hexversion >= 0x010502F0:
    # use some advanced feature
    ...
else:
    # use an alternative implementation or warn the user
    ...
@end example

@code{hexversion} は @ref{14e7,,hex()} 関数を使って 16 進数に変換しなければ値の意味を持ちません。より読みやすいバージョン番号が必要な場合には @ref{85e,,named tuple} @ref{8af,,sys.version_info} を使用してください。

@code{hexversion} のより詳しい情報については @ref{4922,,API と ABI のバージョニング} を参照してください。
@end deffn

@geindex implementation (sys モジュール)
@anchor{library/sys sys implementation}@anchor{73b}
@deffn {データ} sys.implementation

現在起動している Python インタプリタに関する情報が格納されたオブジェクトです。すべての Python 実装において、以下の属性が存在することが要求されています。

`name' は実装の識別子です (例: @code{'cpython'})。実際の文字列は Python 実装によって定義されますが、小文字であることが保証されています。

`version' は @ref{8af,,sys.version_info} と同じ形式の、Python `実装' のバージョンを表す名前付きタプルです。これは現在起動しているインタプリタ固有のバージョンを意味します。@code{sys.version_info} は Python `言語' のバージョンであり、これはそのバージョンに準拠した `実装' のバージョンです。例えば、PyPy 1.8 の @code{sys.implementation.version} は @code{sys.version_info(1, 8, 0, 'final', 0)} になるのに対し、 @code{sys.version_info} は @code{sys.version_info(2, 7, 2, 'final', 0)} になります。CPython は、それがリファレンス実装であるため、両者は同じ値になります。

`hexversion' は @ref{4921,,sys.hexversion} と同形式の、16 進数での実装のバージョンです。

`cache_tag' は、キャッシュされたモジュールのファイル名に使用されるタグです。慣例により、これは実装名とバージョンを組み合わせた文字列になります (例: @code{'cpython-33'}) が、Python 実装はその他の適切な値を使う場合があります。@code{cache_tag} に @code{None} が設定された場合、モジュールのキャッシングが無効になっていることを示します。

`supports_isolated_interpreters' is a boolean value, whether
this implementation supports multiple isolated interpreters.
It is @code{True} for CPython on most platforms.  Platforms with
this support implement the low-level @code{_interpreters} module.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 684
PEP 684@footnote{https://peps.python.org/pep-0684/}, 
@geindex Python Enhancement Proposals; PEP 734
PEP 734@footnote{https://peps.python.org/pep-0734/}, and @ref{25,,concurrent.interpreters}.


@ref{73b,,sys.implementation} には Python 実装固有の属性を追加することができます。それら非標準属性の名前はアンダースコアから始めなくてはならず、そしてここでは説明されません。その内容に関係なく、@ref{73b,,sys.implementation} はインタプリタ起動中や実装のバージョン間で変更することはありません (ただし Python 言語のバージョン間についてはその限りではありません)。詳細は 
@geindex Python Enhancement Proposals; PEP 421
PEP 421@footnote{https://peps.python.org/pep-0421/} を参照してください。


Added in version 3.3.



バージョン 3.14 で変更: Added @code{supports_isolated_interpreters} field.


@cartouche
@quotation 注釈 
The addition of new required attributes must go through the normal PEP
process. See 
@geindex Python Enhancement Proposals; PEP 421
PEP 421@footnote{https://peps.python.org/pep-0421/} for more information.
@end quotation
@end cartouche
@end deffn

@geindex int_info (sys モジュール)
@anchor{library/sys sys int_info}@anchor{14ab}
@deffn {データ} sys.int_info

Python における整数の内部表現に関する情報を保持する、@ref{85e,,named tuple} です。この属性は読み出し専用です。

@geindex bits_per_digit (sys.int_info の属性)
@anchor{library/sys sys int_info bits_per_digit}@anchor{4923}
@deffn {の属性} int_info.bits_per_digit

The number of bits held in each digit.
Python integers are stored internally in base @code{2**int_info.bits_per_digit}.
@end deffn

@geindex sizeof_digit (sys.int_info の属性)
@anchor{library/sys sys int_info sizeof_digit}@anchor{4924}
@deffn {の属性} int_info.sizeof_digit

The size in bytes of the C type used to represent a digit.
@end deffn

@geindex default_max_str_digits (sys.int_info の属性)
@anchor{library/sys sys int_info default_max_str_digits}@anchor{26dc}
@deffn {の属性} int_info.default_max_str_digits

The default value for @ref{1818,,sys.get_int_max_str_digits()}
when it is not otherwise explicitly configured.
@end deffn

@geindex str_digits_check_threshold (sys.int_info の属性)
@anchor{library/sys sys int_info str_digits_check_threshold}@anchor{4925}
@deffn {の属性} int_info.str_digits_check_threshold

The minimum non-zero value for @ref{18f1,,sys.set_int_max_str_digits()},
@geindex PYTHONINTMAXSTRDIGITS
@geindex 環境変数; PYTHONINTMAXSTRDIGITS
@ref{1b3a,,PYTHONINTMAXSTRDIGITS}, or @ref{16f,,-X int_max_str_digits}.
@end deffn


Added in version 3.1.



バージョン 3.11 で変更: Added @ref{26dc,,default_max_str_digits} and
@ref{4925,,str_digits_check_threshold}.

@end deffn

@geindex __interactivehook__ (sys モジュール)
@anchor{library/sys sys __interactivehook__}@anchor{11ca}
@deffn {データ} sys.__interactivehook__

この属性が存在する場合、インタープリタが @ref{443,,対話モード} で起動したときに値は (引数なしで) 自動的に呼ばれます。これは 
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} ファイルの読み込み後に行われるため、それにこのフックを設定することが出来ます。@ref{cc,,site} モジュールで @ref{11cb,,設定します}。


Raises an @ref{1c6e,,auditing event}
@code{cpython.run_interactivehook} with the hook object as the argument when
the hook is called on startup.



Added in version 3.4.

@end deffn

@geindex intern() (sys モジュール)
@anchor{library/sys sys intern}@anchor{14f3}
@deffn {の関数} sys.intern (string)

`string' を "隔離" された文字列のテーブルに入力し、隔離された文字列を返します -- この文字列は `string' 自体かコピーです。隔離された文字列は辞書検索のパフォーマンスを少しだけ向上させるのに有効です -- 辞書中のキーが隔離されており、検索するキーが隔離されている場合、(ハッシュ化後の) キーの比較は文字列の比較ではなくポインタの比較で行うことができるからです。通常、Python プログラム内で利用されている名前は自動的に隔離され、モジュール、クラス、またはインスタンス属性を保持するための辞書は隔離されたキーを持っています。

Interned strings are not @ref{290,,immortal}; you must keep a reference to the
return value of @ref{14f3,,intern()} around to benefit from it.
@end deffn

@geindex _is_gil_enabled() (sys モジュール)
@anchor{library/sys sys _is_gil_enabled}@anchor{4926}
@deffn {の関数} sys._is_gil_enabled ()

Return @ref{e07,,True} if the @ref{164,,GIL} is enabled and @ref{d2b,,False} if
it is disabled.


Added in version 3.13.


`CPython 実装の詳細:' It is not guaranteed to exist in all implementations of Python.
@end deffn

@geindex is_finalizing() (sys モジュール)
@anchor{library/sys sys is_finalizing}@anchor{c80}
@deffn {の関数} sys.is_finalizing ()

Return @ref{e07,,True} if the main Python interpreter is
@ref{479,,shutting down}. Return @ref{d2b,,False} otherwise.

See also the @ref{47a,,PythonFinalizationError} exception.


Added in version 3.5.

@end deffn

@geindex _jit (sys モジュール)
@anchor{library/sys sys _jit}@anchor{293}
@deffn {データ} sys._jit

Utilities for observing just-in-time compilation.

`CPython 実装の詳細:' JIT compilation is an `experimental implementation detail' of CPython.
@code{sys._jit} is not guaranteed to exist or behave the same way in all
Python implementations, versions, or build configurations.


Added in version 3.14.


@geindex _jit.is_available() (sys モジュール)
@anchor{library/sys sys _jit is_available}@anchor{44f}
@deffn {の関数} _jit.is_available ()

Return @code{True} if the current Python executable supports JIT compilation,
and @code{False} otherwise.  This can be controlled by building CPython with
the @code{--experimental-jit} option on Windows, and the
@ref{44e,,--enable-experimental-jit} option on all other platforms.
@end deffn

@geindex _jit.is_enabled() (sys モジュール)
@anchor{library/sys sys _jit is_enabled}@anchor{450}
@deffn {の関数} _jit.is_enabled ()

Return @code{True} if JIT compilation is enabled for the current Python
process (implies @ref{44f,,sys._jit.is_available()}), and @code{False} otherwise.
If JIT compilation is available, this can be controlled by setting the
@geindex PYTHON_JIT
@geindex 環境変数; PYTHON_JIT
@ref{44d,,PYTHON_JIT} environment variable to @code{0} (disabled) or @code{1}
(enabled) at interpreter startup.
@end deffn

@geindex _jit.is_active() (sys モジュール)
@anchor{library/sys sys _jit is_active}@anchor{1861}
@deffn {の関数} _jit.is_active ()

Return @code{True} if the topmost Python frame is currently executing JIT
code (implies @ref{450,,sys._jit.is_enabled()}), and @code{False} otherwise.

@cartouche
@quotation 注釈 
This function is intended for testing and debugging the JIT itself.
It should be avoided for any other purpose.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
Due to the nature of tracing JIT compilers, repeated calls to this
function may give surprising results. For example, branching on its
return value will likely lead to unexpected behavior (if doing so
causes JIT code to be entered or exited):

@example
>>> for warmup in range(BIG_NUMBER):
...     # This line is "hot", and is eventually JIT-compiled:
...     if sys._jit.is_active():
...         # This line is "cold", and is run in the interpreter:
...         assert sys._jit.is_active()
...
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
    assert sys._jit.is_active()
           ~~~~~~~~~~~~~~~~~~^^
AssertionError
@end example
@end quotation
@end cartouche
@end deffn
@end deffn

@geindex last_exc (sys モジュール)
@anchor{library/sys sys last_exc}@anchor{6e5}
@deffn {データ} sys.last_exc

This variable is not always defined; it is set to the exception instance
when an exception is not handled and the interpreter prints an error message
and a stack traceback.  Its intended use is to allow an interactive user to
import a debugger module and engage in post-mortem debugging without having
to re-execute the command that caused the error.  (Typical use is
@code{import pdb; pdb.pm()} to enter the post-mortem debugger; see @ref{aa,,pdb}
module for more information.)


Added in version 3.12.

@end deffn

@geindex _is_immortal() (sys モジュール)
@anchor{library/sys sys _is_immortal}@anchor{28f}
@deffn {の関数} sys._is_immortal (op)

Return @ref{e07,,True} if the given object is @ref{290,,immortal}, @ref{d2b,,False}
otherwise.

@cartouche
@quotation 注釈 
Objects that are immortal (and thus return @code{True} upon being passed
to this function) are not guaranteed to be immortal in future versions,
and vice versa for mortal objects.
@end quotation
@end cartouche


Added in version 3.14.


`CPython 実装の詳細:' This function should be used for specialized purposes only.
It is not guaranteed to exist in all implementations of Python.
@end deffn

@geindex _is_interned() (sys モジュール)
@anchor{library/sys sys _is_interned}@anchor{559}
@deffn {の関数} sys._is_interned (string)

Return @ref{e07,,True} if the given string is "interned", @ref{d2b,,False}
otherwise.


Added in version 3.13.


`CPython 実装の詳細:' It is not guaranteed to exist in all implementations of Python.
@end deffn

@geindex last_type (sys モジュール)
@geindex last_value (sys モジュール)
@geindex last_traceback (sys モジュール)
@anchor{library/sys sys last_type}@anchor{6e6}
@deffn {データ} sys.last_type
@anchor{library/sys sys last_value}@anchor{6e7}
@deffnx {データ} sys.last_value
@anchor{library/sys sys last_traceback}@anchor{6e8}
@deffnx {データ} sys.last_traceback

These three variables are deprecated; use @ref{6e5,,sys.last_exc} instead.
They hold the legacy representation of @code{sys.last_exc}, as returned
from @ref{89a,,exc_info()} above.
@end deffn

@geindex maxsize (sys モジュール)
@anchor{library/sys sys maxsize}@anchor{13dd}
@deffn {データ} sys.maxsize

@ref{c55,,Py_ssize_t} 型の変数が取りうる最大値を示す整数です。通常、32 ビットプラットフォームでは @code{2**31 - 1}、64 ビットプラットフォームでは @code{2**63 - 1} になります。
@end deffn

@geindex maxunicode (sys モジュール)
@anchor{library/sys sys maxunicode}@anchor{1258}
@deffn {データ} sys.maxunicode

Unicode コードポイントの最大値を示す整数、すなわち @code{1114111} (16 進数で @code{0x10FFFF}) です。


バージョン 3.3 で変更: 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} 以前は、オプション設定にUnicode文字の保存形式がUCS-2とUCS-4のどちらを指定したかによって、 @code{sys.maxunicode} の値は @code{0xFFFF} が @code{0x10FFFF} になっていました。

@end deffn

@geindex meta_path (sys モジュール)
@anchor{library/sys sys meta_path}@anchor{f27}
@deffn {データ} sys.meta_path

A list of @ref{127c,,meta path finder} objects that have their
@ref{a68,,find_spec()} methods called to see if one
of the objects can find the module to be imported. By default, it holds entries
that implement Python's default import semantics. The
@ref{a68,,find_spec()} method is called with at
least the absolute name of the module being imported. If the module to be
imported is contained in a package, then the parent package's
@ref{2054,,__path__}
attribute is passed in as a second argument. The method returns a
@ref{2363,,module spec}, or @code{None} if the module cannot be found.


@subsubheading 参考



@table @asis

@item @ref{a6e,,importlib.abc.MetaPathFinder}

The abstract base class defining the interface of finder objects on
@ref{f27,,meta_path}.

@item @ref{226c,,importlib.machinery.ModuleSpec}

The concrete class which
@ref{a68,,find_spec()} should return
instances of.
@end table



バージョン 3.4 で変更: @ref{2363,,Module specs} were introduced in Python 3.4, by
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/}.



バージョン 3.12 で変更: Removed the fallback that looked for a @code{find_module()} method
if a @ref{f27,,meta_path} entry didn't have a
@ref{a68,,find_spec()} method.

@end deffn

@geindex modules (sys モジュール)
@anchor{library/sys sys modules}@anchor{17e6}
@deffn {データ} sys.modules

This is a dictionary that maps module names to modules which have already been
loaded.  This can be manipulated to force reloading of modules and other tricks.
However, replacing the dictionary will not necessarily work as expected and
deleting essential items from the dictionary may cause Python to fail.  If
you want to iterate over this global dictionary always use
@code{sys.modules.copy()} or @code{tuple(sys.modules)} to avoid exceptions as its
size may change during iteration as a side effect of code or activity in
other threads.
@end deffn

@geindex orig_argv (sys モジュール)
@anchor{library/sys sys orig_argv}@anchor{a41}
@deffn {データ} sys.orig_argv

The list of the original command line arguments passed to the Python
executable.

The elements of @ref{a41,,sys.orig_argv} are the arguments to the Python interpreter,
while the elements of @ref{147c,,sys.argv} are the arguments to the user's program.
Arguments consumed by the interpreter itself will be present in @ref{a41,,sys.orig_argv}
and missing from @ref{147c,,sys.argv}.


Added in version 3.10.

@end deffn

@geindex path (sys モジュール)
@anchor{library/sys sys path}@anchor{3e4}
@deffn {データ} sys.path

@geindex module;検索;パス

モジュールを検索するパスを示す文字列のリスト。 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} 環境変数と、インストール時に指定したデフォルトパスで初期化されます。

By default, as initialized upon program startup, a potentially unsafe path
is prepended to @ref{3e4,,sys.path} (`before' the entries inserted as a result
of 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH}):


@itemize *

@item 
@code{python -m module} command line: prepend the current working
directory.

@item 
@code{python script.py} command line: prepend the script's directory.
If it's a symbolic link, resolve symbolic links.

@item 
@code{python -c code} and @code{python} (REPL) command lines: prepend an empty
string, which means the current working directory.
@end itemize

To not prepend this potentially unsafe path, use the @ref{7c1,,-P} command
line option or the 
@geindex PYTHONSAFEPATH
@geindex 環境変数; PYTHONSAFEPATH
@ref{7c2,,PYTHONSAFEPATH} environment variable.

プログラムはその目的のために、このリストを自由に修正できます。文字列だけが @ref{3e4,,sys.path} に追加でき、 ほかの全てのデータ型はインポート中に無視されます。


@subsubheading 参考



@itemize *

@item 
@ref{cc,,site} モジュールのドキュメントで、 .pth ファイルを使って @ref{3e4,,sys.path} を拡張する方法を解説しています。
@end itemize

@end deffn

@geindex path_hooks (sys モジュール)
@anchor{library/sys sys path_hooks}@anchor{1225}
@deffn {データ} sys.path_hooks

path を引数にとって、その path に対する @ref{236a,,finder} の作成を試みる呼び出し可能オブジェクトのリスト。 finder の作成に成功したら、その呼出可能オブジェクトのは finder を返します。失敗した場合は、 @ref{65b,,ImportError} を発生させます。

オリジナルの仕様は 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} を参照してください。
@end deffn

@geindex path_importer_cache (sys モジュール)
@anchor{library/sys sys path_importer_cache}@anchor{7fa}
@deffn {データ} sys.path_importer_cache

@ref{236a,,finder} オブジェクトのキャッシュ機能を果たす辞書です。キーは @ref{1225,,sys.path_hooks} に渡されているパスで、値は見つかった finder になります。パスが正常なファイルシステムパスであり、finder が @ref{1225,,sys.path_hooks} 上に見つからない場合は @code{None} が格納されます。

オリジナルの仕様は 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} を参照してください。
@end deffn

@geindex platform (sys モジュール)
@anchor{library/sys sys platform}@anchor{291}
@deffn {データ} sys.platform

A string containing a platform identifier. Known values are:


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

システム

@tab

@code{platform} の値

@item

AIX

@tab

@code{'aix'}

@item

Android

@tab

@code{'android'}

@item

Emscripten

@tab

@code{'emscripten'}

@item

FreeBSD

@tab

@code{'freebsd'}

@item

iOS

@tab

@code{'ios'}

@item

Linux

@tab

@code{'linux'}

@item

macOS

@tab

@code{'darwin'}

@item

Windows

@tab

@code{'win32'}

@item

Windows/Cygwin

@tab

@code{'cygwin'}

@item

WASI

@tab

@code{'wasi'}

@end multitable


On Unix systems not listed in the table, the value is the lowercased OS name
as returned by @code{uname -s}, with the first part of the version as returned by
@code{uname -r} appended, e.g. @code{'sunos5'}, `at the time when Python was built'.
Unless you want to test for a specific system version, it is therefore
recommended to use the following idiom:

@example
if sys.platform.startswith('sunos'):
    # SunOS-specific code here...
@end example


バージョン 3.3 で変更: On Linux, @ref{291,,sys.platform} doesn't contain the major version anymore.
It is always @code{'linux'}, instead of @code{'linux2'} or @code{'linux3'}.



バージョン 3.8 で変更: On AIX, @ref{291,,sys.platform} doesn't contain the major version anymore.
It is always @code{'aix'}, instead of @code{'aix5'} or @code{'aix7'}.



バージョン 3.13 で変更: On Android, @ref{291,,sys.platform} now returns @code{'android'} rather than
@code{'linux'}.



バージョン 3.14 で変更: On FreeBSD, @ref{291,,sys.platform} doesn't contain the major version anymore.
It is always @code{'freebsd'}, instead of @code{'freebsd13'} or @code{'freebsd14'}.



@subsubheading 参考


@ref{3003,,os.name} has a coarser granularity.  @ref{132e,,os.uname()} gives
system-dependent version information.

@ref{af,,platform} モジュールはシステムの詳細な識別情報をチェックする機能を提供しています。

@end deffn

@geindex platlibdir (sys モジュール)
@anchor{library/sys sys platlibdir}@anchor{b32}
@deffn {データ} sys.platlibdir

Name of the platform-specific library directory. It is used to build the
path of standard library and the paths of installed extension modules.

It is equal to @code{"lib"} on most platforms. On Fedora and SuSE, it is equal
to @code{"lib64"} on 64-bit platforms which gives the following @code{sys.path}
paths (where @code{X.Y} is the Python @code{major.minor} version):


@itemize *

@item 
@code{/usr/lib64/pythonX.Y/}:
Standard library (like @code{os.py} of the @ref{a5,,os} module)

@item 
@code{/usr/lib64/pythonX.Y/lib-dynload/}:
C extension modules of the standard library (like the @ref{5b,,errno} module,
the exact filename is platform specific)

@item 
@code{/usr/lib/pythonX.Y/site-packages/} (always use @code{lib}, not
@ref{b32,,sys.platlibdir}): Third-party modules

@item 
@code{/usr/lib64/pythonX.Y/site-packages/}:
C extension modules of third-party packages
@end itemize


Added in version 3.9.

@end deffn

@geindex prefix (sys モジュール)
@anchor{library/sys sys prefix}@anchor{3e7}
@deffn {データ} sys.prefix

A string giving the site-specific directory prefix where the platform
independent Python files are installed; on Unix, the default is
@code{/usr/local}. This can be set at build time with the @ref{214f,,--prefix}
argument to the @code{configure} script.  See
@ref{449,,インストールパス} for derived paths.

@cartouche
@quotation 注釈 
If a @ref{3e8,,virtual environment} is in effect, this @ref{3e7,,prefix}
will point to the virtual environment. The value for the Python installation
will still be available, via @ref{3e6,,base_prefix}.
Refer to @ref{48b3,,Virtual Environments} for more information.
@end quotation
@end cartouche


バージョン 3.14 で変更: When running under a @ref{3e8,,virtual environment},
@ref{3e7,,prefix} and @ref{3eb,,exec_prefix} are now set to the virtual
environment prefix by the @ref{18dc,,path initialization},
instead of @ref{cc,,site}. This means that @ref{3e7,,prefix} and
@ref{3eb,,exec_prefix} always point to the virtual environment, even when
@ref{cc,,site} is disabled (@ref{13c0,,-S}).

@end deffn

@geindex ps1 (sys モジュール)
@geindex ps2 (sys モジュール)
@anchor{library/sys sys ps1}@anchor{2135}
@deffn {データ} sys.ps1
@anchor{library/sys sys ps2}@anchor{2136}
@deffnx {データ} sys.ps2

@geindex interpreter prompts
@geindex prompts@comma{} interpreter
@geindex >>>;interpreter prompt
@geindex ...;interpreter prompt

インタプリタの一次プロンプト、二次プロンプトを指定する文字列。対話モードで実行中のみ定義され、初期値は @code{'>>> '} と @code{'... '} です。文字列以外のオブジェクトを指定した場合、インタプリタが対話コマンドを読み込むごとにオブジェクトの @ref{169,,str()} を評価します。この機能は、動的に変化するプロンプトを実装する場合に利用します。
@end deffn

@geindex setdlopenflags() (sys モジュール)
@anchor{library/sys sys setdlopenflags}@anchor{1337}
@deffn {の関数} sys.setdlopenflags (n)

Set the flags used by the interpreter for @code{dlopen()} calls, such as when
the interpreter loads extension modules.  Among other things, this will enable a
lazy resolving of symbols when importing a module, if called as
@code{sys.setdlopenflags(0)}.  To share symbols across extension modules, call as
@code{sys.setdlopenflags(os.RTLD_GLOBAL)}.  Symbolic names for the flag values
can be found in the @ref{a5,,os} module (@code{RTLD_@var{xxx}} constants, e.g.
@ref{1330,,os.RTLD_LAZY}).

@ref{213f,,Availability}: Unix.
@end deffn

@geindex set_int_max_str_digits() (sys モジュール)
@anchor{library/sys sys set_int_max_str_digits}@anchor{18f1}
@deffn {の関数} sys.set_int_max_str_digits (maxdigits)

Set the @ref{80b,,integer string conversion length limitation} used by this interpreter. See also
@ref{1818,,get_int_max_str_digits()}.


Added in version 3.11.

@end deffn

@geindex setprofile() (sys モジュール)
@anchor{library/sys sys setprofile}@anchor{1717}
@deffn {の関数} sys.setprofile (profilefunc)

@geindex profile function
@geindex profiler

Set the system's profile function, which allows you to implement a Python source
code profiler in Python.  See chapter @ref{47f6,,Python プロファイラ} for more information on the
Python profiler.  The system's profile function is called similarly to the
system's trace function (see @ref{2e1,,settrace()}), but it is called with different events,
for example it isn't called for each executed line of code (only on call and return,
but the return event is reported even when an exception has been set). The function is
thread-specific, but there is no way for the profiler to know about context switches between
threads, so it does not make sense to use this in the presence of multiple threads. Also,
its return value is not used, so it can simply return @code{None}.  Error in the profile
function will cause itself unset.

@cartouche
@quotation 注釈 
The same tracing mechanism is used for @code{setprofile()} as @ref{2e1,,settrace()}.
To trace calls with @code{setprofile()} inside a tracing function
(e.g. in a debugger breakpoint), see @ref{1bc3,,call_tracing()}.
@end quotation
@end cartouche

Profile関数は 3 個の引数、`frame'、`event'、および `arg' を受け取る必要があります。`frame' は現在のスタックフレームです。`event' は文字列で、@code{'call'}, @code{'return'}, @code{'c_call'}, @code{'c_return'}, @code{'c_exception'} のどれかが渡されます。`arg' はイベントの種類によって異なります。

`event' には以下の意味があります。


@table @asis

@item @code{'call'}

関数が呼び出された(もしくは、何かのコードブロックに入った)。プロファイル関数が呼ばれる。 `arg' は @code{None} が渡される。

@item @code{'return'}

関数(あるいは別のコードブロック)から戻ろうとしている。プロファイル関数が呼ばれる。 `arg' は返されようとしている値、または、このイベントが例外が送出されることによって起こったなら @code{None} 。

@item @code{'c_call'}

C 関数(拡張関数かビルトイン関数)が呼ばれようとしている。 `arg' は C 関数オブジェクト。

@item @code{'c_return'}

C 関数から戻った。 `arg' は C の関数オブジェクト。

@item @code{'c_exception'}

C 関数が例外を発生させた。 `arg' は C の関数オブジェクト。
@end table

引数無しで @ref{1c6e,,監査イベント} @code{sys.setprofile} を送出します。
@end deffn

@geindex setrecursionlimit() (sys モジュール)
@anchor{library/sys sys setrecursionlimit}@anchor{6ea}
@deffn {の関数} sys.setrecursionlimit (limit)

Python インタプリタの、スタックの最大の深さを `limit' に設定します。この制限は Python プログラムが無限に再帰し、 C スタックがオーバーフローしてクラッシュすることを防止するために設けられています。

`limit' の最大値はプラットフォームによって異なります。深い再帰処理が必要な場合にはプラットフォームがサポートしている範囲内でより大きな値を指定することができますが、この値が大きすぎればクラッシュするので注意が必要です。

If the new limit is too low at the current recursion depth, a
@ref{f68,,RecursionError} exception is raised.


バージョン 3.5.1 で変更: A @ref{f68,,RecursionError} exception is now raised if the new limit is too
low at the current recursion depth.

@end deffn

@geindex setswitchinterval() (sys モジュール)
@anchor{library/sys sys setswitchinterval}@anchor{b44}
@deffn {の関数} sys.setswitchinterval (interval)

インタプリタのスレッド切り替え間隔を秒で指定します。この浮動小数点値が、並列に動作しているPythonスレッドに割り当てられたタイムスライスの理想的な処理時間です。特に長時間実行される内部関数やメソッドが実行されたとき、実際の値はより高くなることがあります。また、どのスレッドがスレッド切り替え間隔の終わりにスケジュールされる（次に実行される）かはオペレーティングシステムが決定します。インタプリタは自身のスケジューラを持ちません。


Added in version 3.2.

@end deffn

@geindex settrace() (sys モジュール)
@anchor{library/sys sys settrace}@anchor{2e1}
@deffn {の関数} sys.settrace (tracefunc)

@geindex trace function
@geindex debugger

Set the system's trace function, which allows you to implement a Python
source code debugger in Python.  The function is thread-specific; for a
debugger to support multiple threads, it must register a trace function using
@ref{2e1,,settrace()} for each thread being debugged or use @ref{a48,,threading.settrace()}.

Trace functions should have three arguments: `frame', `event', and
`arg'. `frame' is the @ref{8ef,,current stack frame}. `event' is a string: @code{'call'},
@code{'line'}, @code{'return'}, @code{'exception'} or @code{'opcode'}.  `arg' depends on
the event type.

trace 関数は (`event' に @code{'call'} を渡された状態で) 新しいローカルスコープに入るたびに呼ばれます。この場合、新しいスコープで利用するローカルの trace 関数への参照か、そのスコープを trace しないのであれば @code{None} を返します。

The local trace function should return a reference to itself, or to another
function which would then be used as the local trace function for the scope.

If there is any error occurred in the trace function, it will be unset, just
like @code{settrace(None)} is called.

@cartouche
@quotation 注釈 
Tracing is disabled while calling the trace function (e.g. a function set by
@code{settrace()}). For recursive tracing see @ref{1bc3,,call_tracing()}.
@end quotation
@end cartouche

`event' には以下の意味があります。


@table @asis

@item @code{'call'}

関数が呼び出された(もしくは、何かのコードブロックに入った)。グローバルの trace 関数が呼ばれる。 `arg' は @code{None} が渡される。戻り値はローカルの trace 関数。

@item @code{'line'}

The interpreter is about to execute a new line of code or re-execute the
condition of a loop.  The local trace function is called; `arg' is
@code{None}; the return value specifies the new local trace function.  See
@code{Objects/lnotab_notes.txt} for a detailed explanation of how this
works.
Per-line events may be disabled for a frame by setting
@ref{dd6,,f_trace_lines} to @ref{d2b,,False} on that
@ref{8ef,,frame}.

@item @code{'return'}

関数(あるいは別のコードブロック)から戻ろうとしている。ローカルの trace 関数が呼ばれる。 `arg' は返されようとしている値、または、このイベントが例外が送出されることによって起こったなら @code{None} 。 trace 関数の戻り値は無視される。

@item @code{'exception'}

例外が発生した。ローカルの trace 関数が呼ばれる。 `arg' は @code{(exception, value, traceback)} のタプル。戻り値は新しいローカルの trace 関数。

@item @code{'opcode'}

The interpreter is about to execute a new opcode (see @ref{3c,,dis} for
opcode details).  The local trace function is called; `arg' is
@code{None}; the return value specifies the new local trace function.
Per-opcode events are not emitted by default: they must be explicitly
requested by setting @ref{dd7,,f_trace_opcodes} to @ref{e07,,True} on the
@ref{8ef,,frame}.
@end table

例外が呼び出しチェインを辿って伝播していくことに注意してください。 @code{'exception'} イベントは各レベルで発生します。

For more fine-grained usage, it's possible to set a trace function by
assigning @code{frame.f_trace = tracefunc} explicitly, rather than relying on
it being set indirectly via the return value from an already installed
trace function. This is also required for activating the trace function on
the current frame, which @ref{2e1,,settrace()} doesn't do. Note that in order
for this to work, a global tracing function must have been installed
with @ref{2e1,,settrace()} in order to enable the runtime tracing machinery,
but it doesn't need to be the same tracing function (e.g. it could be a
low overhead tracing function that simply returns @code{None} to disable
itself immediately on each frame).

code と frame オブジェクトについては、 @ref{232f,,標準型の階層} を参照してください。

引数無しで @ref{1c6e,,監査イベント} @code{sys.settrace} を送出します。

@ref{2e1,,settrace()} 関数は、デバッガ、プロファイラ、カバレッジツール等で使うためだけのものです。この関数の挙動は言語定義よりも実装プラットフォームの分野の問題で、全ての Python 実装で利用できるとは限りません。


バージョン 3.7 で変更: @code{'opcode'} event type added; @ref{dd6,,f_trace_lines} and
@ref{dd7,,f_trace_opcodes} attributes added to frames

@end deffn

@geindex set_asyncgen_hooks() (sys モジュール)
@anchor{library/sys sys set_asyncgen_hooks}@anchor{199d}
@deffn {の関数} sys.set_asyncgen_hooks ([firstiter] [, finalizer])

Accepts two optional keyword arguments which are callables that accept an
@ref{4918,,asynchronous generator iterator} as an argument. The `firstiter'
callable will be called when an asynchronous generator is iterated for the
first time. The `finalizer' will be called when an asynchronous generator
is about to be garbage collected.

引数無しで @ref{1c6e,,監査イベント} @code{sys.set_asyncgen_hooks_firstiter} を送出します。

引数無しで @ref{1c6e,,監査イベント} @code{sys.set_asyncgen_hooks_finalizer} を送出します。

Two auditing events are raised because the underlying API consists of two
calls, each of which must raise its own event.


Added in version 3.6: See 
@geindex Python Enhancement Proposals; PEP 525
PEP 525@footnote{https://peps.python.org/pep-0525/} for more details, and for a reference example of a
`finalizer' method see the implementation of
@code{asyncio.Loop.shutdown_asyncgens} in
Lib/asyncio/base_events.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/asyncio/base_events.py}


@cartouche
@quotation 注釈 
This function has been added on a provisional basis (see 
@geindex Python Enhancement Proposals; PEP 411
PEP 411@footnote{https://peps.python.org/pep-0411/}
for details.)
@end quotation
@end cartouche
@end deffn

@geindex set_coroutine_origin_tracking_depth() (sys モジュール)
@anchor{library/sys sys set_coroutine_origin_tracking_depth}@anchor{d85}
@deffn {の関数} sys.set_coroutine_origin_tracking_depth (depth)

Allows enabling or disabling coroutine origin tracking. When
enabled, the @code{cr_origin} attribute on coroutine objects will
contain a tuple of (filename, line number, function name) tuples
describing the traceback where the coroutine object was created,
with the most recent call first. When disabled, @code{cr_origin} will
be @code{None}.

To enable, pass a `depth' value greater than zero; this sets the
number of frames whose information will be captured. To disable,
set `depth' to zero.

This setting is thread-specific.


Added in version 3.7.


@cartouche
@quotation 注釈 
This function has been added on a provisional basis (see 
@geindex Python Enhancement Proposals; PEP 411
PEP 411@footnote{https://peps.python.org/pep-0411/}
for details.)  Use it only for debugging purposes.
@end quotation
@end cartouche
@end deffn

@geindex activate_stack_trampoline() (sys モジュール)
@anchor{library/sys sys activate_stack_trampoline}@anchor{69a}
@deffn {の関数} sys.activate_stack_trampoline (backend, /)

Activate the stack profiler trampoline `backend'.
The only supported backend is @code{"perf"}.

Stack trampolines cannot be activated if the JIT is active.

@ref{213f,,Availability}: Linux.


Added in version 3.12.



@subsubheading 参考



@itemize *

@item 
@ref{4ae,,Python support for the Linux perf profiler}

@item 
@indicateurl{https://perf.wiki.kernel.org}
@end itemize

@end deffn

@geindex deactivate_stack_trampoline() (sys モジュール)
@anchor{library/sys sys deactivate_stack_trampoline}@anchor{69b}
@deffn {の関数} sys.deactivate_stack_trampoline ()

Deactivate the current stack profiler trampoline backend.

If no stack profiler is activated, this function has no effect.

@ref{213f,,Availability}: Linux.


Added in version 3.12.

@end deffn

@geindex is_stack_trampoline_active() (sys モジュール)
@anchor{library/sys sys is_stack_trampoline_active}@anchor{69c}
@deffn {の関数} sys.is_stack_trampoline_active ()

Return @code{True} if a stack profiler trampoline is active.

@ref{213f,,Availability}: Linux.


Added in version 3.12.

@end deffn

@geindex remote_exec() (sys モジュール)
@anchor{library/sys sys remote_exec}@anchor{16d}
@deffn {の関数} sys.remote_exec (pid, script)

Executes `script', a file containing Python code in the remote
process with the given `pid'.

This function returns immediately, and the code will be executed by the
target process's main thread at the next available opportunity, similarly
to how signals are handled. There is no interface to determine when the
code has been executed. The caller is responsible for making sure that
the file still exists whenever the remote process tries to read it and that
it hasn't been overwritten.

The remote process must be running a CPython interpreter of the same major
and minor version as the local process. If either the local or remote
interpreter is pre-release (alpha, beta, or release candidate) then the
local and remote interpreters must be the same exact version.

See @ref{4927,,Remote debugging attachment protocol} for more information about the remote debugging
mechanism.


When the code is executed in the remote process, an
@ref{1c6e,,auditing event} @code{sys.remote_exec} is raised with
the `pid' and the path to the script file.
This event is raised in the process that called @ref{16d,,sys.remote_exec()}.



When the script is executed in the remote process, an
@ref{1c6e,,auditing event}
@code{cpython.remote_debugger_script} is raised
with the path in the remote process.
This event is raised in the remote process, not the one
that called @ref{16d,,sys.remote_exec()}.


@ref{213f,,Availability}: Unix, Windows.


Added in version 3.14: See 
@geindex Python Enhancement Proposals; PEP 768
PEP 768@footnote{https://peps.python.org/pep-0768/} for more details.

@end deffn

@geindex _enablelegacywindowsfsencoding() (sys モジュール)
@anchor{library/sys sys _enablelegacywindowsfsencoding}@anchor{33e}
@deffn {の関数} sys._enablelegacywindowsfsencoding ()

Changes the @ref{75d,,filesystem encoding and error handler} to 'mbcs' and
'replace' respectively, for consistency with versions of Python prior to
3.6.

This is equivalent to defining the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING}
environment variable before launching Python.

See also @ref{e53,,sys.getfilesystemencoding()} and
@ref{ee2,,sys.getfilesystemencodeerrors()}.

@ref{213f,,Availability}: Windows.

@cartouche
@quotation 注釈 
Changing the filesystem encoding after Python startup is risky because
the old fsencoding or paths encoded by the old fsencoding may be cached
somewhere. Use 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} instead.
@end quotation
@end cartouche


Added in version 3.6: より詳しくは 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} を参照してください。



Deprecated since version 3.13, will be removed in version 3.16: Use 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} instead.

@end deffn

@geindex stdin (sys モジュール)
@geindex stdout (sys モジュール)
@geindex stderr (sys モジュール)
@anchor{library/sys sys stdin}@anchor{75f}
@deffn {データ} sys.stdin
@anchor{library/sys sys stdout}@anchor{ccd}
@deffnx {データ} sys.stdout
@anchor{library/sys sys stderr}@anchor{b33}
@deffnx {データ} sys.stderr

インタプリタが使用する、それぞれ標準入力、標準出力、および標準エラー出力の @ref{13db,,ファイルオブジェクト} です:


@itemize *

@item 
@code{stdin} は (@ref{14f0,,input()} の呼び出しも含む) すべての対話型入力に使われます。

@item 
@code{stdout} は @ref{1177,,print()} および @ref{23cf,,expression} 文の出力と、@ref{14f0,,input()} のプロンプトに使用されます。

@item 
インタプリタ自身のプロンプトおよびエラーメッセージは @code{stderr} に出力されます。
@end itemize

これらのストリームは @ref{316,,open()} が返すような通常の @ref{206d,,テキストファイル} です。引数は以下のように選択されます:


@itemize *

@item 
The encoding and error handling are is initialized from
@ref{644,,PyConfig.stdio_encoding} and @ref{4928,,PyConfig.stdio_errors}.

On Windows, UTF-8 is used for the console device.  Non-character
devices such as disk files and pipes use the system locale
encoding (i.e. the ANSI codepage).  Non-console character
devices such as NUL (i.e. where @code{isatty()} returns @code{True}) use the
value of the console input and output codepages at startup,
respectively for stdin and stdout/stderr. This defaults to the
system @ref{54a,,locale encoding} if the process is not initially attached
to a console.

The special behaviour of the console can be overridden
by setting the environment variable PYTHONLEGACYWINDOWSSTDIO
before starting Python. In that case, the console codepages are
used as for any other character device.

Under all platforms, you can override the character encoding by
setting the 
@geindex PYTHONIOENCODING
@geindex 環境変数; PYTHONIOENCODING
@ref{120c,,PYTHONIOENCODING} environment variable before
starting Python or by using the new @ref{16f,,-X} @code{utf8} command
line option and 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8} environment variable.  However,
for the Windows console, this only applies when
@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 環境変数; PYTHONLEGACYWINDOWSSTDIO
@ref{e55,,PYTHONLEGACYWINDOWSSTDIO} is also set.

@item 
When interactive, the @code{stdout} stream is line-buffered. Otherwise,
it is block-buffered like regular text files.  The @code{stderr} stream
is line-buffered in both cases.  You can make both streams unbuffered
by passing the @ref{1d8d,,-u} command-line option or setting the
@geindex PYTHONUNBUFFERED
@geindex 環境変数; PYTHONUNBUFFERED
@ref{1d8e,,PYTHONUNBUFFERED} environment variable.
@end itemize


バージョン 3.9 で変更: Non-interactive @code{stderr} is now line-buffered instead of fully
buffered.


@cartouche
@quotation 注釈 
標準ストリームにバイナリーデータの読み書きを行うには下位のバイナリー @ref{14bb,,buffer} オブジェクトを使用してください。例えば @ref{192,,bytes} を @ref{ccd,,stdout} に書き出す場合は @code{sys.stdout.buffer.write(b'abc')} を使用してください。

However, if you are writing a library (and do not control in which
context its code will be executed), be aware that the standard streams
may be replaced with file-like objects like @ref{112a,,io.StringIO} which
do not support the @code{buffer} attribute.
@end quotation
@end cartouche
@end deffn

@geindex __stdin__ (sys モジュール)
@geindex __stdout__ (sys モジュール)
@geindex __stderr__ (sys モジュール)
@anchor{library/sys sys __stdin__}@anchor{4929}
@deffn {データ} sys.__stdin__
@anchor{library/sys sys __stdout__}@anchor{2cfb}
@deffnx {データ} sys.__stdout__
@anchor{library/sys sys __stderr__}@anchor{46d3}
@deffnx {データ} sys.__stderr__

それぞれ起動時の @code{stdin}, @code{stderr}, @code{stdout} の値を保存しています。終了処理時に利用されます。また、 @code{sys.std*} オブジェクトが(訳注:別のファイルライクオブジェクトに)リダイレクトされている場合でも、実際の標準ストリームへの出力に利用できます。

また、標準ストリームが壊れたオブジェクトに置き換えられた場合に、動作する実際のファイルを復元するために利用することもできます。しかし、明示的に置き換え前のストリームを保存しておき、そのオブジェクトを復元する事を推奨します。

@cartouche
@quotation 注釈 
一部の条件下では、@code{stdin}, @code{stdout},  @code{stderr} も、オリジナルの @code{__stdin__}, @code{__stdout__},  @code{__stderr__} も @code{None} になることがあります。これはコンソールに接続しない Windows GUI アプリケーションであり、かつ @code{pythonw} で起動された Python アプリケーションが該当します。
@end quotation
@end cartouche
@end deffn

@geindex stdlib_module_names (sys モジュール)
@anchor{library/sys sys stdlib_module_names}@anchor{a42}
@deffn {データ} sys.stdlib_module_names

A frozenset of strings containing the names of standard library modules.

It is the same on all platforms. Modules which are not available on
some platforms and modules disabled at Python build are also listed.
All module kinds are listed: pure Python, built-in, frozen and extension
modules. Test modules are excluded.

For packages, only the main package is listed: sub-packages and sub-modules
are not listed. For example, the @code{email} package is listed, but the
@code{email.mime} sub-package and the @code{email.message} sub-module are not
listed.

See also the @ref{2047,,sys.builtin_module_names} list.


Added in version 3.10.

@end deffn

@geindex thread_info (sys モジュール)
@anchor{library/sys sys thread_info}@anchor{1368}
@deffn {データ} sys.thread_info

スレッドの実装に関する情報が格納された @ref{85e,,named tuple} です。

@geindex name (sys.thread_info の属性)
@anchor{library/sys sys thread_info name}@anchor{492a}
@deffn {の属性} thread_info.name

The name of the thread implementation:


@itemize *

@item 
@code{"nt"}: Windows threads

@item 
@code{"pthread"}: POSIX threads

@item 
@code{"pthread-stubs"}: stub POSIX threads
(on WebAssembly platforms without threading support)

@item 
@code{"solaris"}: Solaris threads
@end itemize
@end deffn

@geindex lock (sys.thread_info の属性)
@anchor{library/sys sys thread_info lock}@anchor{492b}
@deffn {の属性} thread_info.lock

The name of the lock implementation:


@itemize *

@item 
@code{"semaphore"}: a lock uses a semaphore

@item 
@code{"mutex+cond"}: a lock uses a mutex and a condition variable

@item 
@code{None} この情報が不明の場合
@end itemize
@end deffn

@geindex version (sys.thread_info の属性)
@anchor{library/sys sys thread_info version}@anchor{492c}
@deffn {の属性} thread_info.version

The name and version of the thread library.
It is a string, or @code{None} if this information is unknown.
@end deffn


Added in version 3.3.

@end deffn

@geindex tracebacklimit (sys モジュール)
@anchor{library/sys sys tracebacklimit}@anchor{1944}
@deffn {データ} sys.tracebacklimit

捕捉されない例外が発生した時、出力されるトレースバック情報の最大レベル数を指定する整数値(デフォルト値は @code{1000})。 @code{0} 以下の値が設定された場合、トレースバック情報は出力されず例外型と例外値のみが出力されます。
@end deffn

@geindex unraisablehook() (sys モジュール)
@anchor{library/sys sys unraisablehook}@anchor{507}
@deffn {の関数} sys.unraisablehook (unraisable, /)

Handle an unraisable exception.

Called when an exception has occurred but there is no way for Python to
handle it. For example, when a destructor raises an exception or during
garbage collection (@ref{1b3,,gc.collect()}).

The `unraisable' argument has the following attributes:


@itemize *

@item 
@code{exc_type}: Exception type.

@item 
@code{exc_value}: Exception value, can be @code{None}.

@item 
@code{exc_traceback}: Exception traceback, can be @code{None}.

@item 
@code{err_msg}: Error message, can be @code{None}.

@item 
@code{object}: Object causing the exception, can be @code{None}.
@end itemize

The default hook formats @code{err_msg} and @code{object} as:
@code{f'@{err_msg@}: @{object!r@}'}; use "Exception ignored in" error message
if @code{err_msg} is @code{None}.

@ref{507,,sys.unraisablehook()} can be overridden to control how unraisable
exceptions are handled.


@subsubheading 参考


@ref{a0c,,excepthook()} which handles uncaught exceptions.


@cartouche
@quotation 警告 
Storing @code{exc_value} using a custom hook can create a reference cycle.
It should be cleared explicitly to break the reference cycle when the
exception is no longer needed.

Storing @code{object} using a custom hook can resurrect it if it is set to an
object which is being finalized. Avoid storing @code{object} after the custom
hook completes to avoid resurrecting objects.
@end quotation
@end cartouche


Raise an auditing event @code{sys.unraisablehook} with arguments
`hook', `unraisable' when an exception that cannot be handled occurs.
The `unraisable' object is the same as what will be passed to the hook.
If no hook has been set, `hook' may be @code{None}.



Added in version 3.8.

@end deffn

@geindex version (sys モジュール)
@anchor{library/sys sys version}@anchor{49c}
@deffn {データ} sys.version

Python インタプリタのバージョン番号の他、ビルド番号や使用コンパイラなどの情報を示す文字列です。この文字列は Python 対話型インタプリタが起動した時に表示されます。バージョン情報はここから抜き出さずに、 @ref{8af,,version_info} および @ref{af,,platform} が提供する関数を使って下さい。
@end deffn

@geindex api_version (sys モジュール)
@anchor{library/sys sys api_version}@anchor{492d}
@deffn {データ} sys.api_version

The C API version, equivalent to the C macro @ref{492e,,PYTHON_API_VERSION}.
Defined for backwards compatibility.

Currently, this constant is not updated in new Python versions, and is not
useful for versioning. This may change in the future.
@end deffn

@geindex version_info (sys モジュール)
@anchor{library/sys sys version_info}@anchor{8af}
@deffn {データ} sys.version_info

バージョン番号を示す 5 要素タプル:`major', `minor', `micro', `releaselevel', `serial' 。 `releaselevel' 以外は全て整数です。 `releaselevel' の値は、 @code{'alpha'}, @code{'beta'}, @code{'candidate'}, @code{'final'} の何れかです。 Python 2.0 の @code{version_info} は、 @code{(2, 0, 0, 'final', 0)} となります。構成要素には名前でもアクセスできるので、 @code{sys.version_info[0]} は @code{sys.version_info.major} と等価、などになります。


バージョン 3.1 で変更: 名前を使った要素アクセスがサポートされました。

@end deffn

@geindex warnoptions (sys モジュール)
@anchor{library/sys sys warnoptions}@anchor{3f5}
@deffn {データ} sys.warnoptions

この値は、warnings フレームワーク内部のみ使用され、変更することはできません。詳細は @ref{118,,warnings} を参照してください。
@end deffn

@geindex winver (sys モジュール)
@anchor{library/sys sys winver}@anchor{492f}
@deffn {データ} sys.winver

The version number used to form registry keys on Windows platforms. This is
stored as string resource 1000 in the Python DLL.  The value is normally the
major and minor versions of the running Python interpreter.  It is provided in the @code{sys}
module for informational purposes; modifying this value has no effect on the
registry keys used by Python.

@ref{213f,,Availability}: Windows.
@end deffn


@deffn {データ} sys.monitoring

Namespace containing functions and constants for register callbacks
and controlling monitoring events.
See  @ref{e0,,sys.monitoring} for details.
@end deffn

@geindex _xoptions (sys モジュール)
@anchor{library/sys sys _xoptions}@anchor{2131}
@deffn {データ} sys._xoptions

コマンドラインオプション @ref{16f,,-X} で渡された様々な実装固有のフラグの辞書です。オプション名にはその値が明示されていればそれが、それ以外の場合は @ref{e07,,True} がマップされます。例えば:

@example
$ ./python -Xa=b -Xc
Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys._xoptions
@{'a': 'b', 'c': True@}
@end example

この @ref{16f,,-X} によって渡されたオプションにアクセスする方法は CPython 固有です。他の実装ではそれらは他の意味でエクスポートされるか、あるいは何もしません。


Added in version 3.2.

@end deffn

@subsubheading 出典


@anchor{library/sys c99}@anchor{4909}@w{(C99)} 
ISO/IEC 9899:1999.  "Programming languages -- C."  この標準のパブリックドラフトが参照できます: @indicateurl{https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf}。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node sys monitoring --- 実行イベントモニタリング,sysconfig --- Python の構成情報へのアクセスを提供する,sys --- システム固有のパラメーターと関数,Python ランタイムサービス
@anchor{library/sys monitoring doc}@anchor{4930}@anchor{library/sys monitoring module-sys monitoring}@anchor{e0}@anchor{library/sys monitoring sys-monitoring-execution-event-monitoring}@anchor{4931}@anchor{library/sys monitoring translation-repo}@anchor{4932}
@subsection @code{sys.monitoring} --- 実行イベントモニタリング


@geindex module; sys.monitoring


Added in version 3.12.



__________________________________________________________________


@cartouche
@quotation 注釈 
@code{sys.monitoring} is a namespace within the @ref{df,,sys} module,
not an independent module, so there is no need to
@code{import sys.monitoring}, simply @code{import sys} and then use
@code{sys.monitoring}.
@end quotation
@end cartouche

この名前空間は、イベントモニタリングの有効化と制御に必要な関数と定数へのアクセスを提供します。

As programs execute, events occur that might be of interest to tools that
monitor execution. The @code{sys.monitoring} namespace provides means to
receive callbacks when events of interest occur.

The monitoring API consists of three components:


@itemize *

@item 
@ref{4933,,Tool identifiers}

@item 
@ref{4934,,Events}

@item 
@ref{4935,,Callbacks}
@end itemize

@menu
* Tool identifiers:: 
* Events:: 
* Turning events on and off:: 
* Registering callback functions:: 

@end menu

@node Tool identifiers,Events,,sys monitoring --- 実行イベントモニタリング
@anchor{library/sys monitoring tool-identifiers}@anchor{4933}
@subsubsection Tool identifiers


A tool identifier is an integer and the associated name.
Tool identifiers are used to discourage tools from interfering with each
other and to allow multiple tools to operate at the same time.
Currently tools are completely independent and cannot be used to
monitor each other. This restriction may be lifted in the future.

Before registering or activating events, a tool should choose an identifier.
Identifiers are integers in the range 0 to 5 inclusive.

@menu
* Registering and using tools:: 

@end menu

@node Registering and using tools,,,Tool identifiers
@anchor{library/sys monitoring registering-and-using-tools}@anchor{4936}
@subsubsection Registering and using tools


@geindex use_tool_id() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring use_tool_id}@anchor{4937}
@deffn {の関数} sys.monitoring.use_tool_id (tool_id: int, name: str, /) -> None

Must be called before `tool_id' can be used.
`tool_id' must be in the range 0 to 5 inclusive.
Raises a @ref{2ec,,ValueError} if `tool_id' is in use.
@end deffn

@geindex clear_tool_id() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring clear_tool_id}@anchor{192e}
@deffn {の関数} sys.monitoring.clear_tool_id (tool_id: int, /) -> None

Unregister all events and callback functions associated with `tool_id'.
@end deffn

@geindex free_tool_id() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring free_tool_id}@anchor{4938}
@deffn {の関数} sys.monitoring.free_tool_id (tool_id: int, /) -> None

Should be called once a tool no longer requires `tool_id'.
Will call @ref{192e,,clear_tool_id()} before releasing `tool_id'.
@end deffn

@geindex get_tool() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring get_tool}@anchor{4939}
@deffn {の関数} sys.monitoring.get_tool (tool_id: int, /) -> str | None

Returns the name of the tool if `tool_id' is in use,
otherwise it returns @code{None}.
`tool_id' must be in the range 0 to 5 inclusive.
@end deffn

All IDs are treated the same by the VM with regard to events, but the
following IDs are pre-defined to make co-operation of tools easier:

@example
sys.monitoring.DEBUGGER_ID = 0
sys.monitoring.COVERAGE_ID = 1
sys.monitoring.PROFILER_ID = 2
sys.monitoring.OPTIMIZER_ID = 5
@end example

@node Events,Turning events on and off,Tool identifiers,sys monitoring --- 実行イベントモニタリング
@anchor{library/sys monitoring events}@anchor{4934}
@subsubsection Events


The following events are supported:

@geindex BRANCH_LEFT (monitoring event)
@anchor{library/sys monitoring monitoring-event-BRANCH_LEFT}@anchor{295}
@deffn {monitoring-event} sys.monitoring.events.BRANCH_LEFT

A conditional branch goes left.

It is up to the tool to determine how to present "left" and "right" branches.
There is no guarantee which branch is "left" and which is "right", except
that it will be consistent for the duration of the program.
@end deffn

@geindex BRANCH_RIGHT (monitoring event)
@anchor{library/sys monitoring monitoring-event-BRANCH_RIGHT}@anchor{296}
@deffn {monitoring-event} sys.monitoring.events.BRANCH_RIGHT

A conditional branch goes right.
@end deffn

@geindex CALL (monitoring event)
@anchor{library/sys monitoring monitoring-event-CALL}@anchor{19bd}
@deffn {monitoring-event} sys.monitoring.events.CALL

A call in Python code (event occurs before the call).
@end deffn

@geindex C_RAISE (monitoring event)
@anchor{library/sys monitoring monitoring-event-C_RAISE}@anchor{493a}
@deffn {monitoring-event} sys.monitoring.events.C_RAISE

An exception raised from any callable, except for Python functions (event occurs after the exit).
@end deffn

@geindex C_RETURN (monitoring event)
@anchor{library/sys monitoring monitoring-event-C_RETURN}@anchor{493b}
@deffn {monitoring-event} sys.monitoring.events.C_RETURN

Return from any callable, except for Python functions (event occurs after the return).
@end deffn

@geindex EXCEPTION_HANDLED (monitoring event)
@anchor{library/sys monitoring monitoring-event-EXCEPTION_HANDLED}@anchor{493c}
@deffn {monitoring-event} sys.monitoring.events.EXCEPTION_HANDLED

An exception is handled.
@end deffn

@geindex INSTRUCTION (monitoring event)
@anchor{library/sys monitoring monitoring-event-INSTRUCTION}@anchor{493d}
@deffn {monitoring-event} sys.monitoring.events.INSTRUCTION

A VM instruction is about to be executed.
@end deffn

@geindex JUMP (monitoring event)
@anchor{library/sys monitoring monitoring-event-JUMP}@anchor{493e}
@deffn {monitoring-event} sys.monitoring.events.JUMP

An unconditional jump in the control flow graph is made.
@end deffn

@geindex LINE (monitoring event)
@anchor{library/sys monitoring monitoring-event-LINE}@anchor{493f}
@deffn {monitoring-event} sys.monitoring.events.LINE

An instruction is about to be executed that has a different line number from the preceding instruction.
@end deffn

@geindex PY_RESUME (monitoring event)
@anchor{library/sys monitoring monitoring-event-PY_RESUME}@anchor{4940}
@deffn {monitoring-event} sys.monitoring.events.PY_RESUME

Resumption of a Python function (for generator and coroutine functions), except for @code{throw()} calls.
@end deffn

@geindex PY_RETURN (monitoring event)
@anchor{library/sys monitoring monitoring-event-PY_RETURN}@anchor{4941}
@deffn {monitoring-event} sys.monitoring.events.PY_RETURN

Return from a Python function (occurs immediately before the return, the callee's frame will be on the stack).
@end deffn

@geindex PY_START (monitoring event)
@anchor{library/sys monitoring monitoring-event-PY_START}@anchor{4942}
@deffn {monitoring-event} sys.monitoring.events.PY_START

Start of a Python function (occurs immediately after the call, the callee's frame will be on the stack)
@end deffn

@geindex PY_THROW (monitoring event)
@anchor{library/sys monitoring monitoring-event-PY_THROW}@anchor{1855}
@deffn {monitoring-event} sys.monitoring.events.PY_THROW

A Python function is resumed by a @code{throw()} call.
@end deffn

@geindex PY_UNWIND (monitoring event)
@anchor{library/sys monitoring monitoring-event-PY_UNWIND}@anchor{4943}
@deffn {monitoring-event} sys.monitoring.events.PY_UNWIND

Exit from a Python function during exception unwinding. This includes exceptions raised directly within the
function and that are allowed to continue to propagate.
@end deffn

@geindex PY_YIELD (monitoring event)
@anchor{library/sys monitoring monitoring-event-PY_YIELD}@anchor{4944}
@deffn {monitoring-event} sys.monitoring.events.PY_YIELD

Yield from a Python function (occurs immediately before the yield, the callee's frame will be on the stack).
@end deffn

@geindex RAISE (monitoring event)
@anchor{library/sys monitoring monitoring-event-RAISE}@anchor{1974}
@deffn {monitoring-event} sys.monitoring.events.RAISE

An exception is raised, except those that cause a @ref{4945,,STOP_ITERATION} event.
@end deffn

@geindex RERAISE (monitoring event)
@anchor{library/sys monitoring monitoring-event-RERAISE}@anchor{4946}
@deffn {monitoring-event} sys.monitoring.events.RERAISE

An exception is re-raised, for example at the end of a @ref{1b0,,finally} block.
@end deffn

@geindex STOP_ITERATION (monitoring event)
@anchor{library/sys monitoring monitoring-event-STOP_ITERATION}@anchor{4945}
@deffn {monitoring-event} sys.monitoring.events.STOP_ITERATION

An artificial @ref{df5,,StopIteration} is raised; see @ref{4947,,the STOP_ITERATION event}.
@end deffn

More events may be added in the future.

These events are attributes of the @code{sys.monitoring.events} namespace.
Each event is represented as a power-of-2 integer constant.
To define a set of events, simply bitwise OR the individual events together.
For example, to specify both @ref{4941,,PY_RETURN} and @ref{4942,,PY_START}
events, use the expression @code{PY_RETURN | PY_START}.

@geindex NO_EVENTS (monitoring event)
@anchor{library/sys monitoring monitoring-event-NO_EVENTS}@anchor{4948}
@deffn {monitoring-event} sys.monitoring.events.NO_EVENTS

An alias for @code{0} so users can do explicit comparisons like:

@example
if get_events(DEBUGGER_ID) == NO_EVENTS:
    ...
@end example

Setting this event deactivates all events.
@end deffn

@menu
* Local events:: 
* Deprecated event:: 
* Ancillary events:: 
* Other events:: 
* The STOP_ITERATION event:: 

@end menu

@node Local events,Deprecated event,,Events
@anchor{library/sys monitoring local-events}@anchor{4949}@anchor{library/sys monitoring monitoring-event-local}@anchor{494a}
@subsubsection Local events


Local events are associated with normal execution of the program and happen
at clearly defined locations. All local events can be disabled.
The local events are:


@itemize *

@item 
@ref{4942,,PY_START}

@item 
@ref{4940,,PY_RESUME}

@item 
@ref{4941,,PY_RETURN}

@item 
@ref{4944,,PY_YIELD}

@item 
@ref{19bd,,CALL}

@item 
@ref{493f,,LINE}

@item 
@ref{493d,,INSTRUCTION}

@item 
@ref{493e,,JUMP}

@item 
@ref{295,,BRANCH_LEFT}

@item 
@ref{296,,BRANCH_RIGHT}

@item 
@ref{4945,,STOP_ITERATION}
@end itemize

@node Deprecated event,Ancillary events,Local events,Events
@anchor{library/sys monitoring deprecated-event}@anchor{494b}
@subsubsection Deprecated event



@itemize *

@item 
@code{BRANCH}
@end itemize

The @code{BRANCH} event is deprecated in 3.14.
Using @ref{295,,BRANCH_LEFT} and @ref{296,,BRANCH_RIGHT}
events will give much better performance as they can be disabled
independently.

@node Ancillary events,Other events,Deprecated event,Events
@anchor{library/sys monitoring ancillary-events}@anchor{494c}
@subsubsection Ancillary events


Ancillary events can be monitored like other events, but are controlled
by another event:


@itemize *

@item 
@ref{493a,,C_RAISE}

@item 
@ref{493b,,C_RETURN}
@end itemize

The @ref{493b,,C_RETURN} and @ref{493a,,C_RAISE} events
are controlled by the @ref{19bd,,CALL} event.
@ref{493b,,C_RETURN} and @ref{493a,,C_RAISE} events will only be
seen if the corresponding @ref{19bd,,CALL} event is being monitored.

@node Other events,The STOP_ITERATION event,Ancillary events,Events
@anchor{library/sys monitoring monitoring-event-global}@anchor{494d}@anchor{library/sys monitoring other-events}@anchor{494e}
@subsubsection Other events


Other events are not necessarily tied to a specific location in the
program and cannot be individually disabled via @ref{494f,,DISABLE}.

The other events that can be monitored are:


@itemize *

@item 
@ref{1855,,PY_THROW}

@item 
@ref{4943,,PY_UNWIND}

@item 
@ref{1974,,RAISE}

@item 
@ref{493c,,EXCEPTION_HANDLED}
@end itemize

@node The STOP_ITERATION event,,Other events,Events
@anchor{library/sys monitoring the-stop-iteration-event}@anchor{4947}
@subsubsection The STOP_ITERATION event


@geindex Python Enhancement Proposals; PEP 380#use-of-stopiteration-to-return-values
PEP 380@footnote{https://peps.python.org/pep-0380/#use-of-stopiteration-to-return-values}
specifies that a @ref{df5,,StopIteration} exception is raised when returning a value
from a generator or coroutine. However, this is a very inefficient way to
return a value, so some Python implementations, notably CPython 3.12+, do not
raise an exception unless it would be visible to other code.

To allow tools to monitor for real exceptions without slowing down generators
and coroutines, the @ref{4945,,STOP_ITERATION} event is provided.
@ref{4945,,STOP_ITERATION} can be locally disabled, unlike
@ref{1974,,RAISE}.

Note that the @ref{4945,,STOP_ITERATION} event and the
@ref{1974,,RAISE} event for a @ref{df5,,StopIteration} exception are
equivalent, and are treated as interchangeable when generating events.
Implementations will favor @ref{4945,,STOP_ITERATION} for performance
reasons, but may generate a @ref{1974,,RAISE} event with a
@ref{df5,,StopIteration}.

@node Turning events on and off,Registering callback functions,Events,sys monitoring --- 実行イベントモニタリング
@anchor{library/sys monitoring turning-events-on-and-off}@anchor{4950}
@subsubsection Turning events on and off


In order to monitor an event, it must be turned on and a corresponding callback
must be registered. Events can be turned on or off by setting the events either
globally and/or for a particular code object. An event will trigger only once,
even if it is turned on both globally and locally.

@menu
* Setting events globally:: 
* Per code object events:: 
* Disabling events:: 

@end menu

@node Setting events globally,Per code object events,,Turning events on and off
@anchor{library/sys monitoring setting-events-globally}@anchor{4951}
@subsubsection Setting events globally


Events can be controlled globally by modifying the set of events being monitored.

@geindex get_events() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring get_events}@anchor{4952}
@deffn {の関数} sys.monitoring.get_events (tool_id: int, /) -> int

Returns the @code{int} representing all the active events.
@end deffn

@geindex set_events() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring set_events}@anchor{4953}
@deffn {の関数} sys.monitoring.set_events (tool_id: int, event_set: int, /) -> None

Activates all events which are set in `event_set'.
Raises a @ref{2ec,,ValueError} if `tool_id' is not in use.
@end deffn

No events are active by default.

@node Per code object events,Disabling events,Setting events globally,Turning events on and off
@anchor{library/sys monitoring per-code-object-events}@anchor{4954}
@subsubsection Per code object events


Events can also be controlled on a per code object basis. The functions
defined below which accept a @ref{32f,,types.CodeType} should be prepared
to accept a look-alike object from functions which are not defined
in Python (see @ref{485,,Monitoring C API}).

@geindex get_local_events() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring get_local_events}@anchor{4955}
@deffn {の関数} sys.monitoring.get_local_events (tool_id: int, code: CodeType, /) -> int

Returns all the @ref{494a,,local events} for `code'
@end deffn

@geindex set_local_events() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring set_local_events}@anchor{4956}
@deffn {の関数} sys.monitoring.set_local_events (tool_id: int, code: CodeType, event_set: int, /) -> None

Activates all the @ref{494a,,local events} for `code'
which are set in `event_set'. Raises a @ref{2ec,,ValueError} if `tool_id' is not
in use.
@end deffn

@node Disabling events,,Per code object events,Turning events on and off
@anchor{library/sys monitoring disabling-events}@anchor{4957}
@subsubsection Disabling events


@geindex DISABLE (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring DISABLE}@anchor{494f}
@deffn {データ} sys.monitoring.DISABLE

A special value that can be returned from a callback function to disable
events for the current code location.
@end deffn

@ref{494a,,Local events} can be disabled for a specific code
location by returning @ref{494f,,sys.monitoring.DISABLE} from a callback function.
This does not change which events are set, or any other code locations for the
same event.

Disabling events for specific locations is very important for high
performance monitoring. For example, a program can be run under a
debugger with no overhead if the debugger disables all monitoring
except for a few breakpoints.

If @ref{494f,,DISABLE} is returned by a callback for a
@ref{494d,,global event}, @ref{2ec,,ValueError} will be raised
by the interpreter in a non-specific location (that is, no traceback will be
provided).

@geindex restart_events() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring restart_events}@anchor{4958}
@deffn {の関数} sys.monitoring.restart_events () -> None

Enable all the events that were disabled by @ref{494f,,sys.monitoring.DISABLE}
for all tools.
@end deffn

@node Registering callback functions,,Turning events on and off,sys monitoring --- 実行イベントモニタリング
@anchor{library/sys monitoring callbacks}@anchor{4935}@anchor{library/sys monitoring registering-callback-functions}@anchor{4959}
@subsubsection Registering callback functions


@geindex register_callback() (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring register_callback}@anchor{4760}
@deffn {の関数} sys.monitoring.register_callback (tool_id: int, event: int, func: Callable | None, /) -> Callable | None

Registers the callable `func' for the `event' with the given `tool_id'

If another callback was registered for the given `tool_id' and `event',
it is unregistered and returned.
Otherwise @ref{4760,,register_callback()} returns @code{None}.

Raises an @ref{1c6e,,auditing event} @code{sys.monitoring.register_callback} with argument @code{func}.
@end deffn

Functions can be unregistered by calling
@code{sys.monitoring.register_callback(tool_id, event, None)}.

Callback functions can be registered and unregistered at any time.

Callbacks are called only once regardless if the event is turned on both
globally and locally. As such, if an event could be turned on for both global
and local events by your code then the callback needs to be written to handle
either trigger.

@menu
* Callback function arguments:: 

@end menu

@node Callback function arguments,,,Registering callback functions
@anchor{library/sys monitoring callback-function-arguments}@anchor{495a}
@subsubsection Callback function arguments


@geindex MISSING (sys.monitoring モジュール)
@anchor{library/sys monitoring sys monitoring MISSING}@anchor{495b}
@deffn {データ} sys.monitoring.MISSING

A special value that is passed to a callback function to indicate
that there are no arguments to the call.
@end deffn

When an active event occurs, the registered callback function is called.
Callback functions returning an object other than @ref{494f,,DISABLE} will have no effect.
Different events will provide the callback function with different arguments, as follows:


@itemize *

@item 
@ref{4942,,PY_START} and @ref{4940,,PY_RESUME}:

@example
func(code: CodeType, instruction_offset: int) -> object
@end example

@item 
@ref{4941,,PY_RETURN} and @ref{4944,,PY_YIELD}:

@example
func(code: CodeType, instruction_offset: int, retval: object) -> object
@end example

@item 
@ref{19bd,,CALL}, @ref{493a,,C_RAISE} and @ref{493b,,C_RETURN}
(`arg0' can be @ref{495b,,MISSING} specifically):

@example
func(code: CodeType, instruction_offset: int, callable: object, arg0: object) -> object
@end example

`code' represents the code object where the call is being made, while
`callable' is the object that is about to be called (and thus
triggered the event).
If there are no arguments, `arg0' is set to @ref{495b,,sys.monitoring.MISSING}.

For instance methods, `callable' will be the function object as found on the
class with `arg0' set to the instance (i.e. the @code{self} argument to the
method).

@item 
@ref{1974,,RAISE}, @ref{4946,,RERAISE}, @ref{493c,,EXCEPTION_HANDLED},
@ref{4943,,PY_UNWIND}, @ref{1855,,PY_THROW} and @ref{4945,,STOP_ITERATION}:

@example
func(code: CodeType, instruction_offset: int, exception: BaseException) -> object
@end example

@item 
@ref{493f,,LINE}:

@example
func(code: CodeType, line_number: int) -> object
@end example

@item 
@ref{295,,BRANCH_LEFT}, @ref{296,,BRANCH_RIGHT} and @ref{493e,,JUMP}:

@example
func(code: CodeType, instruction_offset: int, destination_offset: int) -> object
@end example

Note that the `destination_offset' is where the code will next execute.

@item 
@ref{493d,,INSTRUCTION}:

@example
func(code: CodeType, instruction_offset: int) -> object
@end example
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node sysconfig --- Python の構成情報へのアクセスを提供する,builtins --- 組み込みオブジェクト,sys monitoring --- 実行イベントモニタリング,Python ランタイムサービス
@anchor{library/sysconfig doc}@anchor{495c}@anchor{library/sysconfig module-sysconfig}@anchor{e1}@anchor{library/sysconfig sysconfig-provide-access-to-python-s-configuration-information}@anchor{495d}@anchor{library/sysconfig translation-repo}@anchor{495e}
@subsection @code{sysconfig} --- Python の構成情報へのアクセスを提供する


@geindex module; sysconfig


Added in version 3.2.


`ソースコード:' Lib/sysconfig@footnote{https://github.com/python/cpython/tree/3.14/Lib/sysconfig}

@geindex configuration information


__________________________________________________________________


The @code{sysconfig} module provides access to Python's configuration
information like the list of installation paths and the configuration variables
relevant for the current platform.

@menu
* 構成変数:: 
* インストールパス:: 
* User scheme:: 
* Home scheme:: 
* Prefix scheme:: 
* Installation path functions:: 
* その他の関数: その他の関数<3>. 
* コマンドラインでの使用: コマンドラインでの使用<7>. 

@end menu

@node 構成変数,インストールパス,,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig configuration-variables}@anchor{495f}
@subsubsection 構成変数


Python の配布物は、Python 自体のバイナリや、 @code{setuptools} によってコンパイルされるサードパーティの C 拡張をビルドするために必要な、@code{Makefile} と @code{pyconfig.h} ヘッダーファイルを含んでいます。

@code{sysconfig} puts all variables found in these files in a dictionary that
can be accessed using @ref{298,,get_config_vars()} or @ref{174,,get_config_var()}.

Windows では構成変数はだいぶ少なくなります。

@geindex get_config_vars() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_config_vars}@anchor{298}
@deffn {の関数} sysconfig.get_config_vars (*args)

引数がない場合、現在のプラットフォームに関するすべての構成変数の辞書を返します。

引数がある場合、各引数を構成変数辞書から検索した結果の変数のリストを返します。

各引数において、変数が見つからなかった場合は @code{None} が返されます。
@end deffn

@geindex get_config_var() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_config_var}@anchor{174}
@deffn {の関数} sysconfig.get_config_var (name)

1つの変数 `name' を返します。@code{get_config_vars().get(name)} と同じです。

`name' が見つからない場合、@code{None} を返します。
@end deffn

Example of usage:

@example
>>> import sysconfig
>>> sysconfig.get_config_var('Py_ENABLE_SHARED')
0
>>> sysconfig.get_config_var('LIBDIR')
'/usr/local/lib'
>>> sysconfig.get_config_vars('AR', 'CXX')
['ar', 'g++']
@end example

@node インストールパス,User scheme,構成変数,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig id1}@anchor{4960}@anchor{library/sysconfig installation-paths}@anchor{449}
@subsubsection インストールパス


Python uses an installation scheme that differs depending on the platform and on
the installation options.  These schemes are stored in @code{sysconfig} under
unique identifiers based on the value returned by @ref{3003,,os.name}.
The schemes are used by package installers to determine where to copy files to.

Python は現在9つのスキームをサポートしています:


@itemize -

@item 
`posix_prefix': Linux や macOS などの POSIX プラットフォーム用のスキームです。これは Python やコンポーネントをインストールするときに使われるデフォルトのスキームです。

@item 
`posix_home': scheme for POSIX platforms, when the `home' option is used.
This scheme defines paths located under a specific home prefix.

@item 
`posix_user': scheme for POSIX platforms, when the `user' option is used.
This scheme defines paths located under the user's home directory
(@ref{1534,,site.USER_BASE}).

@item 
`posix_venv': scheme for @ref{117,,Python virtual environments} on POSIX
platforms; by default it is the same as `posix_prefix'.

@item 
`nt': scheme for Windows.
This is the default scheme used when Python or a component is installed.

@item 
`nt_user': scheme for Windows, when the `user' option is used.

@item 
`nt_venv': scheme for @ref{117,,Python virtual environments} on Windows;
by default it is the same as `nt'.

@item 
`venv': a scheme with values from either `posix_venv' or `nt_venv' depending
on the platform Python runs on.

@item 
`osx_framework_user' オプションが利用された場合の、macOS 用のスキームです。
@end itemize

各スキームは、ユニークな識別子を持ったいくつかのパスの集合から成っています。現在 Python は8つのパスを利用します:


@itemize -

@item 
`stdlib': プラットフォーム非依存の、標準 Python ライブラリファイルを格納するディレクトリ.

@item 
`platstdlib': プラットフォーム依存の、標準 Python ライブラリファイルを格納するディレクトリ.

@item 
`platlib': プラットフォーム依存の、site ごとのファイルを格納するディレクトリ。

@item 
`purelib': directory for site-specific, non-platform-specific files ('pure' Python).

@item 
`include': directory for non-platform-specific header files for
the Python C-API.

@item 
`platinclude': directory for platform-specific header files for
the Python C-API.

@item 
`scripts': スクリプトファイルのためのディレクトリ。

@item 
`data': データファイルのためのディレクトリ。
@end itemize

@node User scheme,Home scheme,インストールパス,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig sysconfig-user-scheme}@anchor{2137}@anchor{library/sysconfig user-scheme}@anchor{4961}
@subsubsection 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.

Files will be installed into subdirectories of @ref{1534,,site.USER_BASE} (written
as @code{`userbase'} hereafter).  This scheme installs pure Python modules and
extension modules in the same location (also known as @ref{2126,,site.USER_SITE}).

@menu
* posix_user:: 
* nt_user:: 
* osx_framework_user:: 

@end menu

@node posix_user,nt_user,,User scheme
@anchor{library/sysconfig posix-user}@anchor{4962}
@subsubsection @code{posix_user}



@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Path

@tab

インストールディレクトリ

@item

`stdlib'

@tab

@code{`userbase'/lib/python`X.Y'}

@item

`platstdlib'

@tab

@code{`userbase'/lib/python`X.Y'}

@item

`platlib'

@tab

@code{`userbase'/lib/python`X.Y'/site-packages}

@item

`purelib'

@tab

@code{`userbase'/lib/python`X.Y'/site-packages}

@item

`include'

@tab

@code{`userbase'/include/python`X.Y'}

@item

`scripts'

@tab

@code{`userbase'/bin}

@item

`data'

@tab

@code{`userbase'}

@end multitable


@node nt_user,osx_framework_user,posix_user,User scheme
@anchor{library/sysconfig nt-user}@anchor{4963}
@subsubsection @code{nt_user}



@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Path

@tab

インストールディレクトリ

@item

`stdlib'

@tab

@code{`userbase'\Python`XY'}

@item

`platstdlib'

@tab

@code{`userbase'\Python`XY'}

@item

`platlib'

@tab

@code{`userbase'\Python`XY'\site-packages}

@item

`purelib'

@tab

@code{`userbase'\Python`XY'\site-packages}

@item

`include'

@tab

@code{`userbase'\Python`XY'\Include}

@item

`scripts'

@tab

@code{`userbase'\Python`XY'\Scripts}

@item

`data'

@tab

@code{`userbase'}

@end multitable


@node osx_framework_user,,nt_user,User scheme
@anchor{library/sysconfig osx-framework-user}@anchor{4964}
@subsubsection @code{osx_framework_user}



@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Path

@tab

インストールディレクトリ

@item

`stdlib'

@tab

@code{`userbase'/lib/python}

@item

`platstdlib'

@tab

@code{`userbase'/lib/python}

@item

`platlib'

@tab

@code{`userbase'/lib/python/site-packages}

@item

`purelib'

@tab

@code{`userbase'/lib/python/site-packages}

@item

`include'

@tab

@code{`userbase'/include/python`X.Y'}

@item

`scripts'

@tab

@code{`userbase'/bin}

@item

`data'

@tab

@code{`userbase'}

@end multitable


@node Home scheme,Prefix scheme,User scheme,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig home-scheme}@anchor{4965}@anchor{library/sysconfig sysconfig-home-scheme}@anchor{4966}
@subsubsection Home scheme


"home スキーム" の背後にある考え方は、Python モジュールを個人用のモジュール置き場でビルドし、維持するというものです。このスキームの名前は Unixの「ホーム」ディレクトリの概念からとりました。というのも、 Unixのユーザにとって、自分のホームディレクトリを @code{/usr/} や @code{/usr/local/} のようにレイアウトするのはよくあることだからです。とはいえ、このスキームはどのオペレーティングシステムのユーザでも使えます。

@menu
* posix_home:: 

@end menu

@node posix_home,,,Home scheme
@anchor{library/sysconfig posix-home}@anchor{4967}
@subsubsection @code{posix_home}



@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Path

@tab

インストールディレクトリ

@item

`stdlib'

@tab

@code{`home'/lib/python}

@item

`platstdlib'

@tab

@code{`home'/lib/python}

@item

`platlib'

@tab

@code{`home'/lib/python}

@item

`purelib'

@tab

@code{`home'/lib/python}

@item

`include'

@tab

@code{`home'/include/python}

@item

`platinclude'

@tab

@code{`home'/include/python}

@item

`scripts'

@tab

@code{`home'/bin}

@item

`data'

@tab

@code{`home'}

@end multitable


@node Prefix scheme,Installation path functions,Home scheme,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig prefix-scheme}@anchor{4968}@anchor{library/sysconfig sysconfig-prefix-scheme}@anchor{4969}
@subsubsection Prefix scheme


あるインストール済みの Python を使ってモジュールのビルド/インストールを (例えば setup スクリプトを実行して) 行いたいけれども、 別のインストール済みの Python のサードパーティ製モジュール置き場 (あるいは、そう見えるようなディレクトリ構造) に、ビルドされた モジュールをインストールしたい場合には、"prefix スキーム" が便利です。そんな作業はまったくありえそうにない、と思うなら、確かにその通りです --- "home スキーム" を先に説明したのもそのためです。とはいえ、prefix スキームが有用なケースは少なくとも二つあります。

First, consider that many Linux distributions put Python in @code{/usr}, rather
than the more traditional @code{/usr/local}.  This is entirely appropriate,
since in those cases Python is part of "the system" rather than a local add-on.
However, if you are installing Python modules from source, you probably want
them to go in @code{/usr/local/lib/python2.`X'} rather than
@code{/usr/lib/python2.`X'}.

Another possibility is a network filesystem where the name used to write to a
remote directory is different from the name used to read it: for example, the
Python interpreter accessed as @code{/usr/local/bin/python} might search for
modules in @code{/usr/local/lib/python2.`X'}, but those modules would have to
be installed to, say, @code{/mnt/`@@server'/export/lib/python2.`X'}.

@menu
* posix_prefix:: 
* nt:: 

@end menu

@node posix_prefix,nt,,Prefix scheme
@anchor{library/sysconfig posix-prefix}@anchor{496a}
@subsubsection @code{posix_prefix}



@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Path

@tab

インストールディレクトリ

@item

`stdlib'

@tab

@code{`prefix'/lib/python`X.Y'}

@item

`platstdlib'

@tab

@code{`prefix'/lib/python`X.Y'}

@item

`platlib'

@tab

@code{`prefix'/lib/python`X.Y'/site-packages}

@item

`purelib'

@tab

@code{`prefix'/lib/python`X.Y'/site-packages}

@item

`include'

@tab

@code{`prefix'/include/python`X.Y'}

@item

`platinclude'

@tab

@code{`prefix'/include/python`X.Y'}

@item

`scripts'

@tab

@code{`prefix'/bin}

@item

`data'

@tab

@code{`prefix'}

@end multitable


@node nt,,posix_prefix,Prefix scheme
@anchor{library/sysconfig nt}@anchor{496b}
@subsubsection @code{nt}



@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Path

@tab

インストールディレクトリ

@item

`stdlib'

@tab

@code{`prefix'\Lib}

@item

`platstdlib'

@tab

@code{`prefix'\Lib}

@item

`platlib'

@tab

@code{`prefix'\Lib\site-packages}

@item

`purelib'

@tab

@code{`prefix'\Lib\site-packages}

@item

`include'

@tab

@code{`prefix'\Include}

@item

`platinclude'

@tab

@code{`prefix'\Include}

@item

`scripts'

@tab

@code{`prefix'\Scripts}

@item

`data'

@tab

@code{`prefix'}

@end multitable


@node Installation path functions,その他の関数<3>,Prefix scheme,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig installation-path-functions}@anchor{496c}
@subsubsection Installation path functions


@code{sysconfig} provides some functions to determine these installation paths.

@geindex get_scheme_names() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_scheme_names}@anchor{496d}
@deffn {の関数} sysconfig.get_scheme_names ()

Return a tuple containing all schemes currently supported in
@code{sysconfig}.
@end deffn

@geindex get_default_scheme() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_default_scheme}@anchor{1bb5}
@deffn {の関数} sysconfig.get_default_scheme ()

Return the default scheme name for the current platform.


Added in version 3.10: This function was previously named @code{_get_default_scheme()} and
considered an implementation detail.



バージョン 3.11 で変更: When Python runs from a virtual environment,
the `venv' scheme is returned.

@end deffn

@geindex get_preferred_scheme() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_preferred_scheme}@anchor{89f}
@deffn {の関数} sysconfig.get_preferred_scheme (key)

Return a preferred scheme name for an installation layout specified by `key'.

`key' must be either @code{"prefix"}, @code{"home"}, or @code{"user"}.

The return value is a scheme name listed in @ref{496d,,get_scheme_names()}. It
can be passed to @code{sysconfig} functions that take a `scheme' argument,
such as @ref{340,,get_paths()}.


Added in version 3.10.



バージョン 3.11 で変更: When Python runs from a virtual environment and @code{key="prefix"},
the `venv' scheme is returned.

@end deffn

@geindex _get_preferred_schemes() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig _get_preferred_schemes}@anchor{496e}
@deffn {の関数} sysconfig._get_preferred_schemes ()

Return a dict containing preferred scheme names on the current platform.
Python implementers and redistributors may add their preferred schemes to
the @code{_INSTALL_SCHEMES} module-level global value, and modify this function
to return those scheme names, to e.g. provide different schemes for system
and language package managers to use, so packages installed by either do not
mix with those by the other.

End users should not use this function, but @ref{1bb5,,get_default_scheme()} and
@ref{89f,,get_preferred_scheme()} instead.


Added in version 3.10.

@end deffn

@geindex get_path_names() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_path_names}@anchor{496f}
@deffn {の関数} sysconfig.get_path_names ()

Return a tuple containing all path names currently supported in
@code{sysconfig}.
@end deffn

@geindex get_path() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_path}@anchor{1545}
@deffn {の関数} sysconfig.get_path (name[, scheme[, vars[, expand]]])

`scheme' で指定されたインストールスキームから、パス `name' に従ってインストールパスを返します。

`name' は @ref{496f,,get_path_names()} が返すリストに含まれる値でなければなりません。

@code{sysconfig} 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: @code{@{base@}/Lib}.

@ref{1545,,get_path()} はパスを展開するのに @ref{298,,get_config_vars()} が返す変数を利用します。すべての変数は各プラットフォームにおいてデフォルト値を持っていて、この関数を呼び出したときにデフォルト値を取得する場合があります。

`scheme' が指定された場合、@ref{496d,,get_scheme_names()} が返すリストに含まれる値でなければなりません。指定されなかった場合は、現在のプラットフォームでのデフォルトスキームが利用されます。

If `vars' is provided, it must be a dictionary of variables that will update
the dictionary returned by @ref{298,,get_config_vars()}.

`expand' が @code{False} に設定された場合、パスは変数を使って展開されません。

`name' が見つからない場合、@ref{5e7,,KeyError} を送出します。
@end deffn

@geindex get_paths() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_paths}@anchor{340}
@deffn {の関数} sysconfig.get_paths ([scheme[, vars[, expand]]])

インストールスキームに基づいたすべてのインストールパスを格納した辞書を返します。詳しい情報は @ref{1545,,get_path()} を参照してください。

`scheme' が指定されない場合、現在のプラットフォームでのデフォルトスキーマが使用されます。

`vars' を指定する場合、パスを展開するために使用される辞書を更新する値の辞書でなければなりません。

`expand' に偽を指定すると、パスは展開されません。

`scheme' が実在するスキームでなかった場合、@ref{340,,get_paths()} は @ref{5e7,,KeyError} を発生させます。
@end deffn

@node その他の関数<3>,コマンドラインでの使用<7>,Installation path functions,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig other-functions}@anchor{4970}
@subsubsection その他の関数


@geindex get_python_version() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_python_version}@anchor{145b}
@deffn {の関数} sysconfig.get_python_version ()

@code{MAJOR.MINOR} の型の Python バージョン番号文字列を返します。@code{'%d.%d' % sys.version_info[:2]} に似ています。
@end deffn

@geindex get_platform() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_platform}@anchor{145a}
@deffn {の関数} sysconfig.get_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 @ref{132e,,os.uname()}), although the
exact information included depends on the OS; e.g., on Linux, the kernel
version isn't particularly important.

返される値の例:

Windows:


@itemize -

@item 
win-amd64 (64-bit Windows on AMD64, aka x86_64, Intel64, and EM64T)

@item 
win-arm64 (64-bit Windows on ARM64, aka AArch64)

@item 
win32 (その他すべて - 具体的には sys.platform が返す値)
@end itemize

POSIX based OS:


@itemize -

@item 
linux-x86_64

@item 
macosx-15.5-arm64

@item 
macosx-26.0-universal2 (macOS on Apple Silicon or Intel)

@item 
android-24-arm64_v8a
@end itemize

その他の非 POSIX プラットフォームでは、現在のところ単に @ref{291,,sys.platform} を返します。
@end deffn

@geindex is_python_build() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig is_python_build}@anchor{32d}
@deffn {の関数} sysconfig.is_python_build ()

実行中の Python インタプリタがソースからビルドされ、かつそのビルドされた場所から実行されている場合に @code{True} を返します。
@code{make install} を実行した場所からの実行やバイナリインストーラによるインストールではいけません。
@end deffn

@geindex parse_config_h() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig parse_config_h}@anchor{4971}
@deffn {の関数} sysconfig.parse_config_h (fp[, vars])

@code{config.h} スタイルのファイルを解析します。

`fp' は @code{config.h} スタイルのファイルを指すファイルライクオブジェクトです。

name/value ペアを格納した辞書を返します。第二引数にオプションの辞書が渡された場合、新しい辞書ではなくその辞書を利用し、ファイルから読み込んだ値で更新します。
@end deffn

@geindex get_config_h_filename() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_config_h_filename}@anchor{4972}
@deffn {の関数} sysconfig.get_config_h_filename ()

@code{pyconfig.h} のパスを返します。
@end deffn

@geindex get_makefile_filename() (sysconfig モジュール)
@anchor{library/sysconfig sysconfig get_makefile_filename}@anchor{4973}
@deffn {の関数} sysconfig.get_makefile_filename ()

@code{Makefile} のパスを返します。
@end deffn
@anchor{library/sysconfig sysconfig-cli}@anchor{4974}
@node コマンドラインでの使用<7>,,その他の関数<3>,sysconfig --- Python の構成情報へのアクセスを提供する
@anchor{library/sysconfig command-line-usage}@anchor{4975}@anchor{library/sysconfig using-sysconfig-as-a-script}@anchor{4976}
@subsubsection コマンドラインでの使用


You can use @code{sysconfig} as a script with Python's `-m' option:

@example
$ python -m sysconfig
Platform: "macosx-10.4-i386"
Python version: "3.2"
Current installation scheme: "posix_prefix"

Paths:
        data = "/usr/local"
        include = "/Users/tarek/Dev/svn.python.org/py3k/Include"
        platinclude = "."
        platlib = "/usr/local/lib/python3.2/site-packages"
        platstdlib = "/usr/local/lib/python3.2"
        purelib = "/usr/local/lib/python3.2/site-packages"
        scripts = "/usr/local/bin"
        stdlib = "/usr/local/lib/python3.2"

Variables:
        AC_APPLE_UNIVERSAL_BUILD = "0"
        AIX_GENUINE_CPLUSPLUS = "0"
        AR = "ar"
        ARFLAGS = "rc"
        ...
@end example

これは、@ref{145a,,get_platform()}、@ref{145b,,get_python_version()}、@ref{1545,,get_path()} および @ref{298,,get_config_vars()} が返す情報を標準出力に出力します。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node builtins --- 組み込みオブジェクト,__main__ --- トップレベルのコード環境,sysconfig --- Python の構成情報へのアクセスを提供する,Python ランタイムサービス
@anchor{library/builtins doc}@anchor{4977}@anchor{library/builtins builtins-built-in-objects}@anchor{4978}@anchor{library/builtins module-builtins}@anchor{13}@anchor{library/builtins translation-repo}@anchor{4979}
@subsection @code{builtins} --- 組み込みオブジェクト


@geindex module; builtins


__________________________________________________________________


This module provides direct access to all 'built-in' identifiers of Python; for
example, @code{builtins.open} is the full name for the built-in function @ref{316,,open()}.

通常このモジュールはほとんどのアプリケーションで明示的にアクセスされることはありませんが、組み込みの値と同じ名前のオブジェクトを提供するモジュールが同時にその名前の組み込みオブジェクトも必要とするような場合には有用です。たとえば、組み込みの @ref{316,,open()} をラップした @ref{316,,open()} という関数を実装したいモジュールがあったとすると、このモジュールは次のように直接的に使われます:

@example
import builtins

def open(path):
    f = builtins.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '@w{'}'Wrapper around a file that converts output to uppercase.'@w{'}'

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

    # ...
@end example

ほとんどのモジュールではグローバル変数の一部として @code{__builtins__} が利用できるようになっています。 @code{__builtins__} の内容は通常このモジュールそのものか、あるいはこのモジュールの @ref{77d,,__dict__} 属性です。これは実装の詳細部分なので、異なる Python の実装では @code{__builtins__} は使われていないこともあります。


@subsubheading 参考



@itemize *

@item 
@ref{2477,,組み込み定数}

@item 
@ref{1c27,,組み込み例外}

@item 
@ref{1474,,組み込み関数}

@item 
@ref{25e9,,組み込み型}
@end itemize


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node __main__ --- トップレベルのコード環境,warnings --- 警告の制御,builtins --- 組み込みオブジェクト,Python ランタイムサービス
@anchor{library/__main__ doc}@anchor{497a}@anchor{library/__main__ main-top-level-code-environment}@anchor{497b}@anchor{library/__main__ module-__main__}@anchor{1}@anchor{library/__main__ translation-repo}@anchor{497c}
@subsection @code{__main__} --- トップレベルのコード環境


@geindex module; __main__


__________________________________________________________________


Python では、 @code{__main__} という特別な名前が次の二つの重要な用途で使われます:


@enumerate 

@item 
プログラムのトップレベル環境の名前。
@code{__name__ == '__main__'} という式でチェックすることができる。

@item 
Python パッケージにおける @code{__main__.py} ファイル。
@end enumerate

どちらも Python のモジュールに関わる機能です。
１つ目はユーザーがどうモジュールを使うか、２つ目はモジュールとモジュールがどうやりとりするかに関係します。
詳細は以下で説明します。
Python モジュールがどういうものかについては、 @ref{203e,,モジュール} を参照してください。

@menu
* __name__ == '__main__':: 
* __main__.py in Python Packages: __main__ py in Python Packages. 
* import __main__:: 

@end menu

@node __name__ == '__main__',__main__ py in Python Packages,,__main__ --- トップレベルのコード環境
@anchor{library/__main__ name-equals-main}@anchor{497d}@anchor{library/__main__ name-main}@anchor{497e}
@subsubsection @code{__name__ == '__main__'}


Python モジュールやパッケージがインポートされるとき、 @code{__name__} の値はそのモジュールの名前となります。
通常、インポートされる Python ファイル自体のファイル名から拡張子 @code{.py} を除いたものとなります:

@example
>>> import configparser
>>> configparser.__name__
'configparser'
@end example

インポートされるファイルがパッケージの一部である場合は、 @code{__name__} にはそのパッケージのパスも含まれます:

@example
>>> from concurrent.futures import process
>>> process.__name__
'concurrent.futures.process'
@end example

しかし、モジュールがトップレベルのスクリプト環境で実行される場合は、 @code{__name__} が @code{'__main__'} という文字列になります。

@menu
* 「トップレベルのスクリプト環境」とは:: 
* 通常の使われ方:: 
* パッケージングで考慮すべき点:: 

@end menu

@node 「トップレベルのスクリプト環境」とは,通常の使われ方,,__name__ == '__main__'
@anchor{library/__main__ what-is-the-top-level-code-environment}@anchor{497f}
@subsubsection 「トップレベルのスクリプト環境」とは


@code{__main__} は、トップレベルのコードが実行される環境の名前です。 "トップレベルのコード" は、実行を開始する最初のユーザー指定の Python モジュールです。これは、このモジュールがプログラムに必要なすべての他のモジュールをインポートするために、 "トップレベル" なのです。時折、 "トップレベルのコード" は、アプリケーションには `エントリーポイント' と呼ばれます。

以下のものがトップレベルのスクリプト環境となります:


@itemize *

@item 
インタラクティブプロンプトのスコープ:

@example
>>> __name__
'__main__'
@end example

@item 
Python インタープリタにファイル引数として渡される Python モジュール:

@example
$ python helloworld.py
Hello, world!
@end example

@item 
Python インタープリタにPython @ref{23c,,-m} オプションとして渡される Python モジュールまたはパッケージ:

@example
$ python -m tarfile
usage: tarfile.py [-h] [-v] (...)
@end example

@item 
標準入力から Python インタープリタが読み込む Python コード:

@example
$ echo "import this" | python
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
...
@end example

@item 
Python インタープリタに @ref{1a8,,-c} オプションで渡される Python コード:

@example
$ python -c "import this"
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
...
@end example
@end itemize

上記それぞれの場合で、トップレベルのモジュールの @code{__name__} の値が @code{'__main__'} となります。

これにより、 @code{__name__} をチェックすれば各モジュールは自分がトップレベル環境で実行されているかどうかを知ることができます。
このことから、モジュールが import 文で初期化された場合以外の場合でのみコードを実行するため、次のコードがしばしば用いられます:

@example
if __name__ == '__main__':
    # Execute when the module is not initialized from an import statement.
    ...
@end example


@subsubheading 参考


あらゆる場合に @code{__name__} の値がどうセットされるのかについて、詳しくはチュートリアルの @ref{203e,,モジュール} セクションを参照してください。


@node 通常の使われ方,パッケージングで考慮すべき点,「トップレベルのスクリプト環境」とは,__name__ == '__main__'
@anchor{library/__main__ idiomatic-usage}@anchor{4980}
@subsubsection 通常の使われ方


一部のモジュールでは、コマンドライン引数をパースしたり標準入力からデータを取得したなど、スクリプト用途のみのコードが含まれています。
このようなモジュールが、例えばユニットテストのため、別のモジュールからインポートされると、そのスクリプト用コードが意図に反して実行されてしまいます。

@code{if __name__ == '__main__'} というコードは、このようなときに役立ちます。
このブロックの中にあるコードは、当該のモジュールがトップレベル環境で実行されていない限り、実行されません。

@code{if __name__ == '__main__'} の下のブロックにあるコードはできるだけ少なくした方が、コードの分かりやすさや正確さにつながります。
最もよくあるのが、プログラムの主要な処理を @code{main} 関数の中にカプセル化することです:

@example
# echo.py

import shlex
import sys

def echo(phrase: str) -> None:
   """A dummy wrapper around print."""
   # for demonstration purposes, you can imagine that there is some
   # valuable and reusable logic inside this function
   print(phrase)

def main() -> int:
    """Echo the input arguments to standard output"""
    phrase = shlex.join(sys.argv)
    echo(phrase)
    return 0

if __name__ == '__main__':
    sys.exit(main())  # next section explains the use of sys.exit
@end example

注意すべき点として、もし @code{main} 関数内のコードをカプセル化せず @code{if __name__ == '__main__'} の下に直接書いた場合、 @code{phrase} 変数はモジュール全体からグローバルにアクセスできてしまいます。
モジュール内の他の関数が意図せずローカル変数ではなくそのグローバル変数を使用してしまう可能性があるため、ミスにつながります。
@code{main} 関数を用意することでこの問題は解決できます。

@code{main} 関数を使うことのもう一つのメリットとして、 @code{echo} 関数が分離し、別の場所からインポートできるようになることです。
@code{echo.py} がインポートされるとき、 @code{echo} 関数と @code{main} 関数が定義されますが、 @code{__name__ != '__main__'} であるため、どちらの関数も呼び出されません。

@node パッケージングで考慮すべき点,,通常の使われ方,__name__ == '__main__'
@anchor{library/__main__ packaging-considerations}@anchor{4981}
@subsubsection パッケージングで考慮すべき点


@code{main} functions are often used to create command-line tools by specifying
them as entry points for console scripts.  When this is done,
pip@footnote{https://pip.pypa.io/} inserts the function call into a template script,
where the return value of @code{main} is passed into @ref{277,,sys.exit()}.
For example:

@example
sys.exit(main())
@end example

Since the call to @code{main} is wrapped in @ref{277,,sys.exit()}, the expectation is
that your function will return some value acceptable as an input to
@ref{277,,sys.exit()}; typically, an integer or @code{None} (which is implicitly
returned if your function does not have a return statement).

By proactively following this convention ourselves, our module will have the
same behavior when run directly (i.e. @code{python echo.py}) as it will have if
we later package it as a console script entry-point in a pip-installable
package.

In particular, be careful about returning strings from your @code{main} function.
@ref{277,,sys.exit()} will interpret a string argument as a failure message, so
your program will have an exit code of @code{1}, indicating failure, and the
string will be written to @ref{b33,,sys.stderr}.  The @code{echo.py} example from
earlier exemplifies using the @code{sys.exit(main())} convention.


@subsubheading 参考


Python Packaging User Guide@footnote{https://packaging.python.org/}
contains a collection of tutorials and references on how to distribute and
install Python packages with modern tools.


@node __main__ py in Python Packages,import __main__,__name__ == '__main__',__main__ --- トップレベルのコード環境
@anchor{library/__main__ main-py-in-python-packages}@anchor{4982}
@subsubsection @code{__main__.py} in Python Packages


If you are not familiar with Python packages, see section @ref{204e,,パッケージ}
of the tutorial.  Most commonly, the @code{__main__.py} file is used to provide
a command-line interface for a package. Consider the following hypothetical
package, "bandclass":

@example
bandclass
  ├── __init__.py
  ├── __main__.py
  └── student.py
@end example

@code{__main__.py} will be executed when the package itself is invoked
directly from the command line using the @ref{23c,,-m} flag. For example:

@example
$ python -m bandclass
@end example

This command will cause @code{__main__.py} to run. How you utilize this mechanism
will depend on the nature of the package you are writing, but in this
hypothetical case, it might make sense to allow the teacher to search for
students:

@example
# bandclass/__main__.py

import sys
from .student import search_students

student_name = sys.argv[1] if len(sys.argv) >= 2 else '@w{'}
print(f'Found student: @{search_students(student_name)@}')
@end example

Note that @code{from .student import search_students} is an example of a relative
import.  This import style can be used when referencing modules within a
package.  For more details, see @ref{2052,,パッケージ内参照} in the
@ref{203e,,モジュール} section of the tutorial.

@menu
* 通常の使われ方: 通常の使われ方<2>. 

@end menu

@node 通常の使われ方<2>,,,__main__ py in Python Packages
@anchor{library/__main__ id1}@anchor{4983}
@subsubsection 通常の使われ方


The content of @code{__main__.py} typically isn't fenced with an
@code{if __name__ == '__main__'} block.  Instead, those files are kept
short and import functions to execute from other modules.  Those other modules can then be
easily unit-tested and are properly reusable.

If used, an @code{if __name__ == '__main__'} block will still work as expected
for a @code{__main__.py} file within a package, because its @code{__name__}
attribute will include the package's path if imported:

@example
>>> import asyncio.__main__
>>> asyncio.__main__.__name__
'asyncio.__main__'
@end example

This won't work for @code{__main__.py} files in the root directory of a
@code{.zip} file though.  Hence, for consistency, a minimal @code{__main__.py}
without a @code{__name__} check is preferred.


@subsubheading 参考


See @ref{117,,venv} for an example of a package with a minimal @code{__main__.py}
in the standard library. It doesn't contain a @code{if __name__ == '__main__'}
block. You can invoke it with @code{python -m venv [directory]}.

See @ref{c3,,runpy} for more details on the @ref{23c,,-m} flag to the
interpreter executable.

See @ref{136,,zipapp} for how to run applications packaged as `.zip' files. In
this case Python looks for a @code{__main__.py} file in the root directory of
the archive.


@node import __main__,,__main__ py in Python Packages,__main__ --- トップレベルのコード環境
@anchor{library/__main__ import-main}@anchor{4984}
@subsubsection @code{import __main__}


Regardless of which module a Python program was started with, other modules
running within that same program can import the top-level environment's scope
(@ref{203f,,namespace}) by importing the @code{__main__} module.  This doesn't import
a @code{__main__.py} file but rather whichever module that received the special
name @code{'__main__'}.

Here is an example module that consumes the @code{__main__} namespace:

@example
# namely.py

import __main__

def did_user_define_their_name():
    return 'my_name' in dir(__main__)

def print_user_name():
    if not did_user_define_their_name():
        raise ValueError('Define the variable `my_name`!')

    print(__main__.my_name)
@end example

Example usage of this module could be as follows:

@example
# start.py

import sys

from namely import print_user_name

# my_name = "Dinsdale"

def main():
    try:
        print_user_name()
    except ValueError as ve:
        return str(ve)

if __name__ == "__main__":
    sys.exit(main())
@end example

Now, if we started our program, the result would look like this:

@example
$ python start.py
Define the variable `my_name`!
@end example

The exit code of the program would be 1, indicating an error. Uncommenting the
line with @code{my_name = "Dinsdale"} fixes the program and now it exits with
status code 0, indicating success:

@example
$ python start.py
Dinsdale
@end example

Note that importing @code{__main__} doesn't cause any issues with unintentionally
running top-level code meant for script use which is put in the
@code{if __name__ == "__main__"} block of the @code{start} module. Why does this work?

Python inserts an empty @code{__main__} module in @ref{17e6,,sys.modules} at
interpreter startup, and populates it by running top-level code. In our example
this is the @code{start} module which runs line by line and imports @code{namely}.
In turn, @code{namely} imports @code{__main__} (which is really @code{start}). That's an
import cycle! Fortunately, since the partially populated @code{__main__}
module is present in @ref{17e6,,sys.modules}, Python passes that to @code{namely}.
See @ref{245f,,Special considerations for __main__} in the
import system's reference for details on how this works.

The Python REPL is another example of a "top-level environment", so anything
defined in the REPL becomes part of the @code{__main__} scope:

@example
>>> import namely
>>> namely.did_user_define_their_name()
False
>>> namely.print_user_name()
Traceback (most recent call last):
...
ValueError: Define the variable `my_name`!
>>> my_name = 'Jabberwocky'
>>> namely.did_user_define_their_name()
True
>>> namely.print_user_name()
Jabberwocky
@end example

The @code{__main__} scope is used in the implementation of @ref{aa,,pdb} and
@ref{c2,,rlcompleter}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node warnings --- 警告の制御,dataclasses --- データクラス,__main__ --- トップレベルのコード環境,Python ランタイムサービス
@anchor{library/warnings doc}@anchor{4985}@anchor{library/warnings module-warnings}@anchor{118}@anchor{library/warnings translation-repo}@anchor{4986}@anchor{library/warnings warnings-warning-control}@anchor{4987}
@subsection @code{warnings} --- 警告の制御


@geindex module; warnings

`ソースコード:' Lib/warnings.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/warnings.py}

@geindex warnings


__________________________________________________________________


警告メッセージは一般に、ユーザに警告しておいた方がよいような状況下にプログラムが置かれているが、その状況は (通常は) 例外を送出したりそのプログラムを終了させるほどの正当な理由がないといった状況で発されます。例えば、プログラムが古いモジュールを使っている場合には警告を発したくなるかもしれません。

Python プログラマは、このモジュールの @ref{1732,,warn()} 関数を使って警告を発することができます。(C 言語のプログラマは @ref{1665,,PyErr_WarnEx()} を使います; 詳細は @ref{4988,,例外処理} を参照してください)。

警告メッセージは通常 @ref{b33,,sys.stderr} に出力されますが、すべての警告を無視したり、警告を例外にしたりと、その処理を柔軟に変更することができます。 警告の処理は @ref{2711,,warning category} 、警告メッセージのテキスト、警告が発行されたソースの位置に基づいて変化します。 同じソースの位置で特定の警告が繰り返された場合、通常は抑制されます。

警告制御には 2 つの段階 (stage) があります: 第一に、警告が発されるたびに、メッセージを出力すべきかどうかの決定が行われます; 次に、メッセージを出力するなら、メッセージはユーザによって設定が可能なフックを使って書式化され印字されます。

警告メッセージを出力するかどうかの決定は、 @ref{1b1,,警告フィルタ} によって制御されます。警告フィルタは一致規則 (matching rule)と動作からなるシーケンスです。 @ref{16c2,,filterwarnings()} を呼び出して一致規則をフィルタに追加することができ、 @ref{4989,,resetwarnings()} を呼び出してフィルタを標準設定の状態にリセットすることができます。

警告メッセージの印字は @ref{498a,,showwarning()} を呼び出して行うことができ、この関数は上書きすることができます; この関数の標準の実装では、 @ref{1df8,,formatwarning()} を呼び出して警告メッセージを書式化しますが、この関数についても自作の実装を使うことができます。


@subsubheading 参考


@ref{31a4,,logging.captureWarnings()} を使うことで、標準ロギング基盤ですべての警告を扱うことができます。


@menu
* 警告カテゴリ:: 
* 警告フィルタ:: 
* 一時的に警告を抑制する:: 
* 警告のテスト:: 
* Updating Code For New Versions of Dependencies:: 
* 利用可能な関数:: 
* 利用可能なコンテキストマネージャー:: 
* Concurrent safety of Context Managers:: 

@end menu

@node 警告カテゴリ,警告フィルタ,,warnings --- 警告の制御
@anchor{library/warnings id1}@anchor{498b}@anchor{library/warnings warning-categories}@anchor{2711}
@subsubsection 警告カテゴリ


警告カテゴリを表現する組み込み例外は数多くあります。このカテゴリ化は警告をグループごとフィルタする上で便利です。

これらは厳密に言えば @ref{270f,,組み込み例外} ですが、概念的には警告メカニズムに属しているのでここで記述されています。

標準の警告カテゴリをユーザの作成したコード上でサブクラス化することで、さらに別の警告カテゴリを定義することができます。警告カテゴリは常に @ref{2712,,Warning} クラスのサブクラスでなければなりません。

現在以下の警告カテゴリクラスが定義されています:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

クラス

@tab

説明

@item

@ref{2712,,Warning}

@tab

すべての警告カテゴリクラスの基底クラスです。 @ref{bcd,,Exception} のサブクラスです。

@item

@ref{2713,,UserWarning}

@tab

@ref{1732,,warn()} の標準のカテゴリです。

@item

@ref{1a3,,DeprecationWarning}

@tab

他の Python 開発者へ向けて警告を発するときの、非推奨の機能についての警告の基底カテゴリです(@code{__main__} によって引き起こされない限り通常は無視されます)。

@item

@ref{1ae,,SyntaxWarning}

@tab

Base category for warnings about dubious
syntactic features (typically emitted when
compiling Python source code, and hence
may not be suppressed by runtime filters)

@item

@ref{4d7,,RuntimeWarning}

@tab

そのランタイム機能があいまいであることを示す警告カテゴリの基底クラスです。

@item

@ref{659,,FutureWarning}

@tab

Python で書かれたアプリケーションのエンドユーザーへ向けて警告を発するときの、非推奨の機能についての警告の基底カテゴリです。

@item

@ref{ac5,,PendingDeprecationWarning}

@tab

将来その機能が非推奨になることを示す警告カテゴリの基底クラスです(デフォルトでは無視されます)。

@item

@ref{71e,,ImportWarning}

@tab

モジュールのインポート処理中に引き起こされる警告カテゴリの基底クラスです (デフォルトでは無視されます)。

@item

@ref{163d,,UnicodeWarning}

@tab

Unicode に関係した警告カテゴリの基底クラスです。

@item

@ref{e1c,,BytesWarning}

@tab

@ref{192,,bytes} や @ref{344,,bytearray} に関連した警告カテゴリの基底クラスです。

@item

@ref{54c,,ResourceWarning}

@tab

リソースの使用に関連した警告カテゴリの基底クラスです (デフォルトでは無視されます)。

@end multitable



バージョン 3.7 で変更: Previously @ref{1a3,,DeprecationWarning} and @ref{659,,FutureWarning} were
distinguished based on whether a feature was being removed entirely or
changing its behaviour. They are now distinguished based on their
intended audience and the way they're handled by the default warnings
filters.


@node 警告フィルタ,一時的に警告を抑制する,警告カテゴリ,warnings --- 警告の制御
@anchor{library/warnings the-warnings-filter}@anchor{498c}@anchor{library/warnings warning-filter}@anchor{1b1}
@subsubsection 警告フィルタ


警告フィルタは、ある警告を無視すべきか、表示すべきか、あるいは (例外を送出する) エラーにするべきかを制御します。

概念的には、警告フィルタは複数のフィルタ仕様からなる順番リストを維持しています; 何らかの特定の警告が生じると、一致するものが見つかるまでリスト中の各フィルタとの照合が行われます; 一致したフィルタ仕様がその警告の処理方法を決定します。フィルタの各エントリは (`action', `message', `category', `module', `lineno') からなるタプルです。ここで:


@itemize *

@item 
`action' は以下の文字列のうちの一つです:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

値

@tab

処理方法

@item

@code{"default"}

@tab

print the first occurrence of matching
warnings for each location (module +
line number) where the warning is issued

@item

@code{"error"}

@tab

一致した警告を例外に変えます

@item

@code{"ignore"}

@tab

一致した警告を出力しません

@item

@code{"always"}

@tab

一致した警告を常に出力します

@item

@code{"all"}

@tab

alias to "always"

@item

@code{"module"}

@tab

print the first occurrence of matching
warnings for each module where the warning
is issued (regardless of line number)

@item

@code{"once"}

@tab

一致した警告のうち、警告の原因になった場所にかかわらず最初の警告のみ出力します

@end multitable


@item 
`message' is a string containing a regular expression that the start of
the warning message must match, case-insensitively.  In @ref{ac6,,-W} and
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS}, `message' is a literal string that the start of the
warning message must contain (case-insensitively), ignoring any whitespace at
the start or end of `message'.

@item 
`category' はクラス (@ref{2712,,Warning} のサブクラス) です。警告クラスはこのクラスのサブクラスに一致しなければなりません。

@item 
`module' is a string containing a regular expression that the start of the
fully qualified module name must match, case-sensitively.  In @ref{ac6,,-W} and
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS}, `module' is a literal string that the
fully qualified module name must be equal to (case-sensitively), ignoring any
whitespace at the start or end of `module'.

@item 
`lineno' は整数で、警告が発生した場所の行番号に一致しなければなりません。@code{0} の場合はすべての行と一致します。
@end itemize

@ref{2712,,Warning} クラスは組み込みの @ref{bcd,,Exception} クラスから派生しているので、警告をエラーに変換するには単に @code{category(message)} を @code{raise} します。

If a warning is reported and doesn't match any registered filter then the
"default" action is applied (hence its name).

@menu
* Repeated Warning Suppression Criteria:: 
* Describing Warning Filters:: 
* デフォルトの警告フィルタ:: 
* Overriding the default filter:: 

@end menu

@node Repeated Warning Suppression Criteria,Describing Warning Filters,,警告フィルタ
@anchor{library/warnings id2}@anchor{498d}@anchor{library/warnings repeated-warning-suppression-criteria}@anchor{498e}
@subsubsection Repeated Warning Suppression Criteria


The filters that suppress repeated warnings apply the following criteria to determine if a warning is considered a repeat:


@itemize -

@item 
@code{"default"}: A warning is considered a repeat only if the (`message', `category', `module', `lineno') are all the same.

@item 
@code{"module"}: A warning is considered a repeat if the (`message', `category', `module') are the same, ignoring the line number.

@item 
@code{"once"}: A warning is considered a repeat if the (`message', `category') are the same, ignoring the module and line number.
@end itemize

@node Describing Warning Filters,デフォルトの警告フィルタ,Repeated Warning Suppression Criteria,警告フィルタ
@anchor{library/warnings describing-warning-filters}@anchor{212a}@anchor{library/warnings id3}@anchor{498f}
@subsubsection Describing Warning Filters


The warnings filter is initialized by @ref{ac6,,-W} options passed to the Python
interpreter command line and the 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} environment variable.
The interpreter saves the arguments for all supplied entries without
interpretation in @ref{3f5,,sys.warnoptions}; the @code{warnings} module parses these
when it is first imported (invalid options are ignored, after printing a
message to @ref{b33,,sys.stderr}).

Individual warnings filters are specified as a sequence of fields separated by
colons:

@example
action:message:category:module:line
@end example

The meaning of each of these fields is as described in @ref{1b1,,警告フィルタ}.
When listing multiple filters on a single line (as for
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS}), the individual filters are separated by commas and
the filters listed later take precedence over those listed before them (as
they're applied left-to-right, and the most recently applied filters take
precedence over earlier ones).

Commonly used warning filters apply to either all warnings, warnings in a
particular category, or warnings raised by particular modules or packages.
Some examples:

@example
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
@end example

@node デフォルトの警告フィルタ,Overriding the default filter,Describing Warning Filters,警告フィルタ
@anchor{library/warnings default-warning-filter}@anchor{4990}@anchor{library/warnings id4}@anchor{4991}
@subsubsection デフォルトの警告フィルタ


デフォルトで、 Python はいくつかの警告フィルタをインストールします。これは @ref{ac6,,-W} コマンドラインオプション、
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} 環境変数または @ref{16c2,,filterwarnings()} の呼び出しでオーバーライドできます。

In regular release builds, the default warning filter has the following entries
(in order of precedence):

@example
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
@end example

In a @ref{509,,debug build}, the list of default warning filters is empty.


バージョン 3.2 で変更: @ref{ac5,,PendingDeprecationWarning} に加えて、 @ref{1a3,,DeprecationWarning} もデフォルトで無視されるようになりました。



バージョン 3.7 で変更: @ref{1a3,,DeprecationWarning} is once again shown by default when triggered
directly by code in @code{__main__}.



バージョン 3.7 で変更: @ref{e1c,,BytesWarning} no longer appears in the default filter list and is
instead configured via @ref{3f5,,sys.warnoptions} when @ref{7f9,,-b} is specified
twice.


@node Overriding the default filter,,デフォルトの警告フィルタ,警告フィルタ
@anchor{library/warnings overriding-the-default-filter}@anchor{4992}@anchor{library/warnings warning-disable}@anchor{4993}
@subsubsection Overriding the default filter


Developers of applications written in Python may wish to hide `all' Python level
warnings from their users by default, and only display them when running tests
or otherwise working on the application. The @ref{3f5,,sys.warnoptions} attribute
used to pass filter configurations to the interpreter can be used as a marker to
indicate whether or not warnings should be disabled:

@example
import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")
@end example

Developers of test runners for Python code are advised to instead ensure that
`all' warnings are displayed by default for the code under test, using code
like:

@example
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
@end example

Finally, developers of interactive shells that run user code in a namespace
other than @code{__main__} are advised to ensure that @ref{1a3,,DeprecationWarning}
messages are made visible by default, using code like the following (where
@code{user_ns} is the module used to execute code entered interactively):

@example
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
@end example

@node 一時的に警告を抑制する,警告のテスト,警告フィルタ,warnings --- 警告の制御
@anchor{library/warnings temporarily-suppressing-warnings}@anchor{4994}@anchor{library/warnings warning-suppress}@anchor{4995}
@subsubsection 一時的に警告を抑制する


If you are using code that you know will raise a warning, such as a deprecated
function, but do not want to see the warning (even when warnings have been
explicitly configured via the command line), then it is possible to suppress
the warning using the @ref{179,,catch_warnings} context manager:

@example
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
@end example

While within the context manager all warnings will simply be ignored. This
allows you to use known-deprecated code without having to see the warning while
not suppressing the warning for other code that might not be aware of its use
of deprecated code.

@quotation

@cartouche
@quotation 注釈 
See @ref{4996,,Concurrent safety of Context Managers} for details on the
concurrency-safety of the @ref{179,,catch_warnings} context manager when
used in programs using multiple threads or async functions.
@end quotation
@end cartouche
@end quotation

@node 警告のテスト,Updating Code For New Versions of Dependencies,一時的に警告を抑制する,warnings --- 警告の制御
@anchor{library/warnings testing-warnings}@anchor{4997}@anchor{library/warnings warning-testing}@anchor{4998}
@subsubsection 警告のテスト


コードが警告を発生させることをテストするには、 @ref{179,,catch_warnings} コンテキストマネージャーを利用します。このクラスを使うと、一時的に警告フィルタを操作してテストに利用できます。例えば、次のコードでは、発生したすべての警告を取得してチェックしています:

@example
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)
@end example

@code{always} の代わりに @code{error} を利用することで、すべての警告で例外を発生させることができます。1つ気をつけないといけないのは、一度 @code{once}/@code{default} ルールによって発生した警告は、フィルタに何をセットしているかにかかわらず、警告レジストリをクリアしない限りは 2度と発生しません。

Once the context manager exits, the warnings filter is restored to its state
when the context was entered. This prevents tests from changing the warnings
filter in unexpected ways between tests and leading to indeterminate test
results.

@quotation

@cartouche
@quotation 注釈 
See @ref{4996,,Concurrent safety of Context Managers} for details on the
concurrency-safety of the @ref{179,,catch_warnings} context manager when
used in programs using multiple threads or async functions.
@end quotation
@end cartouche
@end quotation

同じ種類の警告を発生させる複数の操作をテストする場合、各操作が新しい警告を発生させている事を確認するのは大切な事です (例えば、警告を例外として発生させて各操作が例外を発生させることを確認したり、警告リストの長さが各操作で増加していることを確認したり、警告リストを各操作の前に毎回クリアする事ができます)。

@node Updating Code For New Versions of Dependencies,利用可能な関数,警告のテスト,warnings --- 警告の制御
@anchor{library/warnings updating-code-for-new-versions-of-dependencies}@anchor{4999}@anchor{library/warnings warning-ignored}@anchor{461f}
@subsubsection Updating Code For New Versions of Dependencies


Warning categories that are primarily of interest to Python developers (rather
than end users of applications written in Python) are ignored by default.

Notably, this "ignored by default" list includes @ref{1a3,,DeprecationWarning}
(for every module except @code{__main__}), which means developers should make sure
to test their code with typically ignored warnings made visible in order to
receive timely notifications of future breaking API changes (whether in the
standard library or third party packages).

In the ideal case, the code will have a suitable test suite, and the test runner
will take care of implicitly enabling all warnings when running tests
(the test runner provided by the @ref{10c,,unittest} module does this).

In less ideal cases, applications can be checked for use of deprecated
interfaces by passing @ref{ac6,,-Wd} to the Python interpreter (this is
shorthand for @code{-W default}) or setting @code{PYTHONWARNINGS=default} in
the environment. This enables default handling for all warnings, including those
that are ignored by default. To change what action is taken for encountered
warnings you can change what argument is passed to @ref{ac6,,-W} (e.g.
@code{-W error}). See the @ref{ac6,,-W} flag for more details on what is
possible.

@node 利用可能な関数,利用可能なコンテキストマネージャー,Updating Code For New Versions of Dependencies,warnings --- 警告の制御
@anchor{library/warnings available-functions}@anchor{499a}@anchor{library/warnings warning-functions}@anchor{499b}
@subsubsection 利用可能な関数


@geindex warn() (warnings モジュール)
@anchor{library/warnings warnings warn}@anchor{1732}
@deffn {の関数} warnings.warn (message, category=None, stacklevel=1, source=None, *, skip_file_prefixes=())

警告を発するか、無視するか、あるいは例外を送出します。 `category' 引数が与えられた場合、 @ref{2711,,警告カテゴリクラス} でなければなりません; 標準の値は @ref{2713,,UserWarning} です。 `message' を @ref{2712,,Warning} インスタンスで代用することもできますが、この場合 `category' は無視され、 @code{message.__class__} が使われ、メッセージ文は @code{str(message)} になります。発された例外が前述した @ref{1b1,,警告フィルタ} によってエラーに変更された場合、この関数は例外を送出します。引数 `stacklevel' は Python でラッパー関数を書く際に利用することができます。例えば:

@example
def deprecated_api(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
@end example

This makes the warning refer to @code{deprecated_api}'s caller, rather than to
the source of @code{deprecated_api} itself (since the latter would defeat the
purpose of the warning message).

The `skip_file_prefixes' keyword argument can be used to indicate which
stack frames are ignored when counting stack levels. This can be useful when
you want the warning to always appear at call sites outside of a package
when a constant `stacklevel' does not fit all call paths or is otherwise
challenging to maintain. If supplied, it must be a tuple of strings. When
prefixes are supplied, stacklevel is implicitly overridden to be @code{max(2,
stacklevel)}. To cause a warning to be attributed to the caller from
outside of the current package you might write:

@example
# example/lower.py
_warn_skips = (os.path.dirname(__file__),)

def one_way(r_luxury_yacht=None, t_wobbler_mangrove=None):
    if r_luxury_yacht:
        warnings.warn("Please migrate to t_wobbler_mangrove=.",
                      skip_file_prefixes=_warn_skips)

# example/higher.py
from . import lower

def another_way(**kw):
    lower.one_way(**kw)
@end example

This makes the warning refer to both the @code{example.lower.one_way()} and
@code{example.higher.another_way()} call sites only from calling code living
outside of @code{example} package.

`source' 引数が与えられた場合、これは @ref{54c,,ResourceWarning} を発生させた破壊されたオブジェクトです。


バージョン 3.6 で変更: `source' 引数を追加しました。



バージョン 3.12 で変更: Added `skip_file_prefixes'.

@end deffn

@geindex warn_explicit() (warnings モジュール)
@anchor{library/warnings warnings warn_explicit}@anchor{efd}
@deffn {の関数} warnings.warn_explicit (message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)

This is a low-level interface to the functionality of @ref{1732,,warn()}, passing in
explicitly the message, category, filename and line number, and optionally
other arguments.
`message' must be a string and `category' a subclass of @ref{2712,,Warning} or
`message' may be a @ref{2712,,Warning} instance, in which case `category' will be
ignored.

`module', if supplied, should be the module name.
If no module is passed, the filename with @code{.py} stripped is used.

`registry', if supplied, should be the @code{__warningregistry__} dictionary
of the module.
If no registry is passed, each warning is treated as the first occurrence,
that is, filter actions @code{"default"}, @code{"module"} and @code{"once"} are
handled as @code{"always"}.

`module_globals' は、もし与えられるならば、警告が発せられるコードが使っているグローバル名前空間でなければなりません (この引数は zipfile やその他の非ファイルシステムのインポート元の中にあるモジュールのソースを表示することをサポートするためのものです)。

`source' 引数が与えられた場合、これは @ref{54c,,ResourceWarning} を発生させた破壊されたオブジェクトです。


バージョン 3.6 で変更: `source' 引数を追加しました。

@end deffn

@geindex showwarning() (warnings モジュール)
@anchor{library/warnings warnings showwarning}@anchor{498a}
@deffn {の関数} warnings.showwarning (message, category, filename, lineno, file=None, line=None)

警告をファイルに書き込みます。標準の実装では、 @code{formatwarning(message, category, filename, lineno, line)} を呼び出し、返された文字列を `file' に書き込みます。 `file' は標準では @ref{b33,,sys.stderr} です。この関数は @code{warnings.showwarning} に任意の呼び出し可能オブジェクトを代入して置き換えることができます。 `line' は警告メッセージに含めるソースコードの1行です。 `line' が与えられない場合、 @ref{498a,,showwarning()} は `filename' と `lineno' から行を取得することを試みます。
@end deffn

@geindex formatwarning() (warnings モジュール)
@anchor{library/warnings warnings formatwarning}@anchor{1df8}
@deffn {の関数} warnings.formatwarning (message, category, filename, lineno, line=None)

警告を通常の方法で書式化します。返される文字列内には改行が埋め込まれている可能性があり、かつ文字列は改行で終端されています。 `line' は警告メッセージに含まれるソースコードの1行です。 `line' が渡されない場合、 @ref{1df8,,formatwarning()} は `filename' と `lineno' から行の取得を試みます。
@end deffn

@geindex filterwarnings() (warnings モジュール)
@anchor{library/warnings warnings filterwarnings}@anchor{16c2}
@deffn {の関数} warnings.filterwarnings (action, message='@w{'}, category=Warning, module='@w{'}, lineno=0, append=False)

@ref{1b1,,警告フィルタ仕様} のリストにエントリを一つ挿入します。標準ではエントリは先頭に挿入されます; `append' が真ならば、末尾に挿入されます。この関数は引数の型をチェックし、 `message' および `module' の正規表現をコンパイルしてから、これらをタプルにして警告フィルタのリストに挿入します。二つのエントリが特定の警告に合致した場合、リストの先頭に近い方のエントリが後方にあるエントリに優先します。引数が省略されると、標準ではすべてにマッチする値に設定されます。
@end deffn

@geindex simplefilter() (warnings モジュール)
@anchor{library/warnings warnings simplefilter}@anchor{8d0}
@deffn {の関数} warnings.simplefilter (action, category=Warning, lineno=0, append=False)

単純なエントリを @ref{1b1,,警告フィルタ仕様} のリストに挿入します。引数の意味は @ref{16c2,,filterwarnings()} と同じですが、この関数により挿入されるフィルタはカテゴリと行番号が一致していればすべてのモジュールのすべてのメッセージに合致しますので、正規表現は必要ありません。
@end deffn

@geindex resetwarnings() (warnings モジュール)
@anchor{library/warnings warnings resetwarnings}@anchor{4989}
@deffn {の関数} warnings.resetwarnings ()

警告フィルタをリセットします。これにより、 @ref{ac6,,-W} コマンドラインオプションによるもの @ref{8d0,,simplefilter()} 呼び出しによるものを含め、 @ref{16c2,,filterwarnings()} の呼び出しによる影響はすべて無効化されます。
@end deffn

@geindex deprecated() (warnings モジュール)
@anchor{library/warnings warnings deprecated}@anchor{489}
@deffn {の関数} @@warnings.deprecated (msg, *, category=DeprecationWarning, stacklevel=1)

Decorator to indicate that a class, function or overload is deprecated.

When this decorator is applied to an object,
deprecation warnings may be emitted at runtime when the object is used.
@ref{574,,static type checkers}
will also generate a diagnostic on usage of the deprecated object.

使い方:

@example
from warnings import deprecated
from typing import overload

@@deprecated("Use B instead")
class A:
    pass

@@deprecated("Use g instead")
def f():
    pass

@@overload
@@deprecated("int support is deprecated")
def g(x: int) -> int: ...
@@overload
def g(x: str) -> int: ...
@end example

The warning specified by `category' will be emitted at runtime
on use of deprecated objects. For functions, that happens on calls;
for classes, on instantiation and on creation of subclasses.
If the `category' is @code{None}, no warning is emitted at runtime.
The `stacklevel' determines where the
warning is emitted. If it is @code{1} (the default), the warning
is emitted at the direct caller of the deprecated object; if it
is higher, it is emitted further up the stack.
Static type checker behavior is not affected by the `category'
and `stacklevel' arguments.

The deprecation message passed to the decorator is saved in the
@code{__deprecated__} attribute on the decorated object.
If applied to an overload, the decorator
must be after the @ref{4515,,@@~typing.overload} decorator
for the attribute to exist on the overload as returned by
@ref{8bd,,typing.get_overloads()}.


Added in version 3.13: See 
@geindex Python Enhancement Proposals; PEP 702
PEP 702@footnote{https://peps.python.org/pep-0702/}.

@end deffn

@node 利用可能なコンテキストマネージャー,Concurrent safety of Context Managers,利用可能な関数,warnings --- 警告の制御
@anchor{library/warnings available-context-managers}@anchor{499c}
@subsubsection 利用可能なコンテキストマネージャー


@geindex catch_warnings (warnings のクラス)
@anchor{library/warnings warnings catch_warnings}@anchor{179}
@deffn {クラス} warnings.catch_warnings (*, record=False, module=None, action=None, category=Warning, lineno=0, append=False)

警告フィルタと @ref{498a,,showwarning()} 関数をコピーし、終了時に復元するコンテキストマネージャーです。 `record' 引数が @ref{d2b,,False} (デフォルト値)だった場合、コンテキスト開始時には @ref{885,,None} を返します。もし `record' が @ref{e07,,True} だった場合、リストを返します。このリストにはカスタムの @ref{498a,,showwarning()} 関数(この関数は同時に @code{sys.stdout} への出力を抑制します)によってオブジェクトが継続的に追加されます。リストの中の各オブジェクトは、 @ref{498a,,showwarning()} 関数の引数と同じ名前の属性を持っています。

The `module' argument takes a module that will be used instead of the
module returned when you import @code{warnings} whose filter will be
protected. This argument exists primarily for testing the @code{warnings}
module itself.

If the `action' argument is not @code{None}, the remaining arguments are
passed to @ref{8d0,,simplefilter()} as if it were called immediately on
entering the context.

See @ref{1b1,,警告フィルタ} for the meaning of the `category' and `lineno'
parameters.

@cartouche
@quotation 注釈 
See @ref{4996,,Concurrent safety of Context Managers} for details on the
concurrency-safety of the @ref{179,,catch_warnings} context manager when
used in programs using multiple threads or async functions.
@end quotation
@end cartouche


バージョン 3.11 で変更: Added the `action', `category', `lineno', and `append' parameters.

@end deffn

@node Concurrent safety of Context Managers,,利用可能なコンテキストマネージャー,warnings --- 警告の制御
@anchor{library/warnings concurrent-safety-of-context-managers}@anchor{499d}@anchor{library/warnings warning-concurrent-safe}@anchor{4996}
@subsubsection Concurrent safety of Context Managers


The behavior of @ref{179,,catch_warnings} context manager depends on the
@ref{18a,,sys.flags.context_aware_warnings} flag.  If the flag is true, the
context manager behaves in a concurrent-safe fashion and otherwise not.
Concurrent-safe means that it is both thread-safe and safe to use within
@ref{37b8,,asyncio coroutines} and tasks.  Being thread-safe means
that behavior is predictable in a multi-threaded program.  The flag defaults
to true for free-threaded builds and false otherwise.

If the @ref{18a,,context_aware_warnings} flag is false, then
@ref{179,,catch_warnings} will modify the global attributes of the
@code{warnings} module.  This is not safe if used within a concurrent program
(using multiple threads or using asyncio coroutines).  For example, if two
or more threads use the @ref{179,,catch_warnings} class at the same time, the
behavior is undefined.

If the flag is true, @ref{179,,catch_warnings} will not modify global
attributes and will instead use a @ref{1875,,ContextVar} to
store the newly established warning filtering state.  A context variable
provides thread-local storage and it makes the use of @ref{179,,catch_warnings}
thread-safe.

The `record' parameter of the context handler also behaves differently
depending on the value of the flag.  When `record' is true and the flag is
false, the context manager works by replacing and then later restoring the
module's @ref{498a,,showwarning()} function.  That is not concurrent-safe.

When `record' is true and the flag is true, the @ref{498a,,showwarning()} function
is not replaced.  Instead, the recording status is indicated by an internal
property in the context variable.  In this case, the @ref{498a,,showwarning()}
function will not be restored when exiting the context handler.

The @ref{18a,,context_aware_warnings} flag can be set the @ref{16f,,-X context_aware_warnings} command-line option or by the
@geindex PYTHON_CONTEXT_AWARE_WARNINGS
@geindex 環境変数; PYTHON_CONTEXT_AWARE_WARNINGS
@ref{185b,,PYTHON_CONTEXT_AWARE_WARNINGS} environment variable.

@quotation

@cartouche
@quotation 注釈 
It is likely that most programs that desire thread-safe
behaviour of the warnings module will also want to set the
@ref{175,,thread_inherit_context} flag to true.  That flag
causes threads created by @ref{176,,threading.Thread} to start
with a copy of the context variables from the thread starting
it.  When true, the context established by @ref{179,,catch_warnings}
in one thread will also apply to new threads started by it.  If false,
new threads will start with an empty warnings context variable,
meaning that any filtering that was established by a
@ref{179,,catch_warnings} context manager will no longer be active.
@end quotation
@end cartouche
@end quotation


バージョン 3.14 で変更: Added the @ref{18a,,sys.flags.context_aware_warnings} flag and the use of a
context variable for @ref{179,,catch_warnings} if the flag is true.  Previous
versions of Python acted as if the flag was always set to false.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node dataclasses --- データクラス,contextlib --- with 文コンテキスト用ユーティリティ,warnings --- 警告の制御,Python ランタイムサービス
@anchor{library/dataclasses doc}@anchor{499e}@anchor{library/dataclasses dataclasses-data-classes}@anchor{499f}@anchor{library/dataclasses module-dataclasses}@anchor{33}@anchor{library/dataclasses translation-repo}@anchor{49a0}
@subsection @code{dataclasses} --- データクラス


@geindex module; dataclasses

`ソースコード:' Lib/dataclasses.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/dataclasses.py}


__________________________________________________________________


このモジュールは、@ref{8bf,,__init__()} や @ref{82f,,__repr__()} のような @ref{1c60,,特殊メソッド} を生成し、ユーザー定義のクラスに自動的に追加するデコレーターや関数を提供します。このモジュールは元々、 
@geindex Python Enhancement Proposals; PEP 557
PEP 557@footnote{https://peps.python.org/pep-0557/} で説明されていました。

これらの生成されたメソッドで利用されるメンバー変数は 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} 型アノテーションを用いて定義されます。例えば、このコードでは:

@example
from dataclasses import dataclass

@@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand
@end example

とりわけ、以下のような @code{__init__()} が追加されます:

@example
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand
@end example

このメソッドは自動的にクラスに追加される点に留意して下さい。上記の @code{InventoryItem} クラスの定義中にこのメソッドが直接明記されるわけではありません。


Added in version 3.7.


@menu
* モジュールの内容: モジュールの内容<4>. 
* 初期化後の処理:: 
* クラス変数:: 
* 初期化限定変数:: 
* 凍結されたインスタンス:: 
* 継承: 継承<2>. 
* Re-ordering of keyword-only parameters in __init__(): Re-ordering of keyword-only parameters in __init__. 
* デフォルトファクトリ関数:: 
* 可変なデフォルト値:: 
* Descriptor-typed fields:: 

@end menu

@node モジュールの内容<4>,初期化後の処理,,dataclasses --- データクラス
@anchor{library/dataclasses module-contents}@anchor{49a1}
@subsubsection モジュールの内容


@geindex dataclass() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses dataclass}@anchor{4e1}
@deffn {の関数} @@dataclasses.dataclass (*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)

この関数は、後述する @ref{1c60,,特殊メソッド} を生成し、クラスに追加する @ref{93a,,decorator} です。

@code{@@dataclass} デコレータは、@code{field} を探すためにクラスを検査します。@code{field} は @ref{f51,,型アノテーション} を持つクラス変数として定義されます。後述する２つの例外を除き、 @code{@@dataclass} は変数アノテーションで指定した型を検査しません。

生成されるすべてのメソッドの中でのフィールドの順序は、それらのフィールドがクラス定義に現れた順序です。

@code{@@dataclass} デコレータは、後述する様々な "ダンダー" メソッド (訳注：dunderはdouble underscoreの略で、メソッド名の前後にアンダースコアが2つ付いているメソッド) をクラスに追加します。クラスに既にこれらのメソッドが存在する場合の動作は、後述する引数によって異なります。デコレータは呼び出した際に指定したクラスと同じクラスを返します。新しいクラスは生成されません。

If @code{@@dataclass} is used just as a simple decorator with no parameters,
it acts as if it has the default values documented in this
signature.  That is, these three uses of @code{@@dataclass} are
equivalent:

@example
@@dataclass
class C:
    ...

@@dataclass()
class C:
    ...

@@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False,
           match_args=True, kw_only=False, slots=False, weakref_slot=False)
class C:
    ...
@end example

The parameters to @code{@@dataclass} are:


@itemize -

@item 
`init': If true (the default), a @ref{8bf,,__init__()} method will be
generated.

If the class already defines @code{__init__()}, this parameter is
ignored.

@item 
`repr': If true (the default), a @ref{82f,,__repr__()} method will be
generated.  The generated repr string will have the class name and
the name and repr of each field, in the order they are defined in
the class.  Fields that are marked as being excluded from the repr
are not included.  For example:
@code{InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)}.

If the class already defines @code{__repr__()}, this parameter is
ignored.

@item 
`eq': If true (the default), an @ref{cf2,,__eq__()} method will be
generated.  This method compares the class as if it were a tuple
of its fields, in order.  Both instances in the comparison must
be of the identical type.

If the class already defines @code{__eq__()}, this parameter is
ignored.

@item 
`order': If true (the default is @code{False}), @ref{14b8,,__lt__()},
@ref{1522,,__le__()}, @ref{1523,,__gt__()}, and @ref{1524,,__ge__()} methods will be
generated.  These compare the class as if it were a tuple of its
fields, in order.  Both instances in the comparison must be of the
identical type.  If `order' is true and `eq' is false, a
@ref{2ec,,ValueError} is raised.

If the class already defines any of @code{__lt__()},
@code{__le__()}, @code{__gt__()}, or @code{__ge__()}, then
@ref{198,,TypeError} is raised.

@item 
`unsafe_hash': If true, force @code{dataclasses} to create a
@ref{cf3,,__hash__()} method, even though it may not be safe to do so.
Otherwise, generate a @ref{cf3,,__hash__()} method according to how
`eq' and `frozen' are set.
The default value is @code{False}.

@code{__hash__()} is used by built-in @ref{801,,hash()}, and when objects are
added to hashed collections such as dictionaries and sets.  Having a
@code{__hash__()} implies that instances of the class are immutable.
Mutability is a complicated property that depends on the programmer's
intent, the existence and behavior of @code{__eq__()}, and the values of
the `eq' and `frozen' flags in the @code{@@dataclass} decorator.

By default, @code{@@dataclass} will not implicitly add a @ref{cf3,,__hash__()}
method unless it is safe to do so.  Neither will it add or change an
existing explicitly defined @code{__hash__()} method.  Setting the class
attribute @code{__hash__ = None} has a specific meaning to Python, as
described in the @code{__hash__()} documentation.

If @code{__hash__()} is not explicitly defined, or if it is set to @code{None},
then @code{@@dataclass} `may' add an implicit @code{__hash__()} method.
Although not recommended, you can force @code{@@dataclass} to create a
@code{__hash__()} method with @code{unsafe_hash=True}. This might be the case
if your class is logically immutable but can still be mutated.
This is a specialized use case and should be considered carefully.

Here are the rules governing implicit creation of a @code{__hash__()}
method.  Note that you cannot both have an explicit @code{__hash__()}
method in your dataclass and set @code{unsafe_hash=True}; this will result
in a @ref{198,,TypeError}.

If `eq' and `frozen' are both true, by default @code{@@dataclass} will
generate a @code{__hash__()} method for you.  If `eq' is true and
`frozen' is false, @code{__hash__()} will be set to @code{None}, marking it
unhashable (which it is, since it is mutable).  If `eq' is false,
@code{__hash__()} will be left untouched meaning the @code{__hash__()}
method of the superclass will be used (if the superclass is
@ref{c7e,,object}, this means it will fall back to id-based hashing).

@item 
`frozen': If true (the default is @code{False}), assigning to fields will
generate an exception.  This emulates read-only frozen instances.
See the @ref{49a2,,discussion} below.

If @ref{237c,,__setattr__()} or @ref{237d,,__delattr__()} is defined in the class
and `frozen' is true, then @ref{198,,TypeError} is raised.

@item 
`match_args': If true (the default is @code{True}), the
@ref{1c75,,__match_args__} tuple will be created from the list of
non keyword-only parameters to the generated @ref{8bf,,__init__()} method (even if
@code{__init__()} is not generated, see above).  If false, or if
@code{__match_args__} is already defined in the class, then
@code{__match_args__} will not be generated.
@end itemize

@quotation


Added in version 3.10.

@end quotation


@itemize -

@item 
`kw_only': If true (the default value is @code{False}), then all
fields will be marked as keyword-only.  If a field is marked as
keyword-only, then the only effect is that the @ref{8bf,,__init__()}
parameter generated from a keyword-only field must be specified
with a keyword when @code{__init__()} is called. See the @ref{234b,,parameter}
glossary entry for details.  Also see the
@ref{49a3,,KW_ONLY} section.

Keyword-only fields are not included in @code{__match_args__}.
@end itemize

@quotation


Added in version 3.10.

@end quotation


@itemize -

@item 
`slots': If true (the default is @code{False}), @ref{1704,,__slots__} attribute
will be generated and new class will be returned instead of the original one.
If @code{__slots__} is already defined in the class, then @ref{198,,TypeError}
is raised.
@end itemize

@quotation

@cartouche
@quotation 警告 
Passing parameters to a base class @ref{843,,__init_subclass__()}
when using @code{slots=True} will result in a @ref{198,,TypeError}.
Either use @code{__init_subclass__} with no parameters
or use default values as a workaround.
See gh-91126@footnote{https://github.com/python/cpython/issues/91126} for full details.
@end quotation
@end cartouche


Added in version 3.10.



バージョン 3.11 で変更: If a field name is already included in the @code{__slots__}
of a base class, it will not be included in the generated @code{__slots__}
to prevent @ref{23ba,,overriding them}.
Therefore, do not use @code{__slots__} to retrieve the field names of a
dataclass. Use @ref{1935,,fields()} instead.
To be able to determine inherited slots,
base class @code{__slots__} may be any iterable, but `not' an iterator.

@end quotation


@itemize -

@item 
`weakref_slot': If true (the default is @code{False}), add a slot
named "__weakref__", which is required to make an instance
@ref{11f2,,weakref-able}.
It is an error to specify @code{weakref_slot=True}
without also specifying @code{slots=True}.
@end itemize

@quotation


Added in version 3.11.

@end quotation

@code{フィールド} には、通常の Python の文法でデフォルト値を指定できます。

@example
@@dataclass
class C:
    a: int       # 'a' has no default value
    b: int = 0   # assign a default value for 'b'
@end example

In this example, both @code{a} and @code{b} will be included in the added
@ref{8bf,,__init__()} method, which will be defined as:

@example
def __init__(self, a: int, b: int = 0):
@end example

デフォルト値を指定しないフィールドを、デフォルト値を指定したフィールドの後ろに定義すると、 @ref{198,,TypeError} が送出されます。これは、単一のクラスであっても、クラス継承の結果でも起きえます。
@end deffn

@geindex field() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses field}@anchor{195a}
@deffn {の関数} dataclasses.field (*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING, doc=None)

For common and simple use cases, no other functionality is
required.  There are, however, some dataclass features that
require additional per-field information.  To satisfy this need for
additional information, you can replace the default field value
with a call to the provided @code{field()} function.  For example:

@example
@@dataclass
class C:
    mylist: list[int] = field(default_factory=list)

c = C()
c.mylist += [1, 2, 3]
@end example

As shown above, the @ref{49a4,,MISSING} value is a sentinel object used to
detect if some parameters are provided by the user. This sentinel is
used because @code{None} is a valid value for some parameters with
a distinct meaning.  No code should directly use the @ref{49a4,,MISSING} value.

The parameters to @code{field()} are:


@itemize -

@item 
`default': If provided, this will be the default value for this
field.  This is needed because the @code{field()} call itself
replaces the normal position of the default value.

@item 
`default_factory': If provided, it must be a zero-argument
callable that will be called when a default value is needed for
this field.  Among other purposes, this can be used to specify
fields with mutable default values, as discussed below.  It is an
error to specify both `default' and `default_factory'.

@item 
`init': If true (the default), this field is included as a
parameter to the generated @ref{8bf,,__init__()} method.

@item 
`repr': If true (the default), this field is included in the
string returned by the generated @ref{82f,,__repr__()} method.

@item 
`hash': This can be a bool or @code{None}.  If true, this field is
included in the generated @ref{cf3,,__hash__()} method.  If false,
this field is excluded from the generated @ref{cf3,,__hash__()}.
If @code{None} (the default), use the value of `compare': this would
normally be the expected behavior, since a field should be included
in the hash if it's used for comparisons.  Setting this value to anything
other than @code{None} is discouraged.

フィールドのハッシュ値を計算するコストが高い場合に、 @code{hash=False} だが @code{compare=True} と設定する理由が 1 つあるとすれば、フィールドが等価検査に必要かつ、その型のハッシュ値を計算するのに他のフィールドも使われることです。
フィールドがハッシュから除外されていたとしても、比較には使えます。

@item 
`compare': If true (the default), this field is included in the
generated equality and comparison methods (@ref{cf2,,__eq__()},
@ref{1523,,__gt__()}, et al.).

@item 
`metadata': This can be a mapping or @code{None}. @code{None} is treated as
an empty dict.  This value is wrapped in
@ref{698,,MappingProxyType()} to make it read-only, and exposed
on the @ref{195b,,Field} object. It is not used at all by Data
Classes, and is provided as a third-party extension mechanism.
Multiple third-parties can each have their own key, to use as a
namespace in the metadata.

@item 
`kw_only': If true, this field will be marked as keyword-only.
This is used when the generated @ref{8bf,,__init__()} method's
parameters are computed.

Keyword-only fields are also not included in @code{__match_args__}.
@end itemize

@quotation


Added in version 3.10.

@end quotation


@itemize -

@item 
`doc': optional docstring for this field.
@end itemize

@quotation


Added in version 3.14.

@end quotation

If the default value of a field is specified by a call to
@code{field()}, then the class attribute for this field will be
replaced by the specified `default' value.  If `default' is not
provided, then the class attribute will be deleted.  The intent is
that after the @ref{4e1,,@@dataclass} decorator runs, the class
attributes will all contain the default values for the fields, just
as if the default value itself were specified.  For example,
after:

@example
@@dataclass
class C:
    x: int
    y: int = field(repr=False)
    z: int = field(repr=False, default=10)
    t: int = 20
@end example

The class attribute @code{C.z} will be @code{10}, the class attribute
@code{C.t} will be @code{20}, and the class attributes @code{C.x} and
@code{C.y} will not be set.
@end deffn

@geindex Field (dataclasses のクラス)
@anchor{library/dataclasses dataclasses Field}@anchor{195b}
@deffn {クラス} dataclasses.Field

@code{Field} objects describe each defined field. These objects
are created internally, and are returned by the @ref{1935,,fields()}
module-level method (see below).  Users should never instantiate a
@code{Field} object directly.  Its documented attributes are:


@itemize -

@item 
@code{name}: The name of the field.

@item 
@code{type}: The type of the field.

@item 
@code{default}, @code{default_factory}, @code{init}, @code{repr}, @code{hash},
@code{compare}, @code{metadata}, and @code{kw_only} have the identical
meaning and values as they do in the @ref{195a,,field()} function.
@end itemize

他の属性があることもありますが、それらはプライベートであり、調べたり、依存したりしてはなりません。
@end deffn

@geindex InitVar (dataclasses のクラス)
@anchor{library/dataclasses dataclasses InitVar}@anchor{1bb4}
@deffn {クラス} dataclasses.InitVar

@code{InitVar[T]} type annotations describe variables that are @ref{49a5,,init-only}. Fields annotated with @code{InitVar}
are considered pseudo-fields, and thus are neither returned by the
@ref{1935,,fields()} function nor used in any way except adding them as
parameters to @ref{8bf,,__init__()} and an optional
@ref{49a6,,__post_init__()}.
@end deffn

@geindex fields() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses fields}@anchor{1935}
@deffn {の関数} dataclasses.fields (class_or_instance)

このデータクラスのフィールドを定義する @ref{195b,,Field} オブジェクトをタプルで返します。
データクラスあるいはデータクラスのインスタンスを受け付けます。
データクラスやデータクラスのインスタンスが渡されなかった場合は、 @ref{198,,TypeError} を送出します。
@code{ClassVar} や @code{InitVar} といった疑似フィールドは返しません。
@end deffn

@geindex asdict() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses asdict}@anchor{1a95}
@deffn {の関数} 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 @code{name: value} pairs.  dataclasses, dicts,
lists, and tuples are recursed into.  Other objects are copied with
@ref{d65,,copy.deepcopy()}.

Example of using @code{asdict()} on nested dataclasses:

@example
@@dataclass
class Point:
     x: int
     y: int

@@dataclass
class C:
     mylist: list[Point]

p = Point(10, 20)
assert asdict(p) == @{'x': 10, 'y': 20@}

c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == @{'mylist': [@{'x': 0, 'y': 0@}, @{'x': 10, 'y': 4@}]@}
@end example

To create a shallow copy, the following workaround may be used:

@example
@{field.name: getattr(obj, field.name) for field in fields(obj)@}
@end example

@code{asdict()} raises @ref{198,,TypeError} if `obj' is not a dataclass
instance.
@end deffn

@geindex astuple() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses astuple}@anchor{1a9e}
@deffn {の関数} 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
@ref{d65,,copy.deepcopy()}.

1つ前の例の続きです:

@example
assert astuple(p) == (10, 20)
assert astuple(c) == ([(0, 0), (10, 4)],)
@end example

To create a shallow copy, the following workaround may be used:

@example
tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))
@end example

@code{astuple()} raises @ref{198,,TypeError} if `obj' is not a dataclass
instance.
@end deffn

@geindex make_dataclass() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses make_dataclass}@anchor{185c}
@deffn {の関数} dataclasses.make_dataclass (cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False, module=None, decorator=dataclass)

Creates a new dataclass with name `cls_name', fields as defined
in `fields', base classes as given in `bases', and initialized
with a namespace as given in `namespace'.  `fields' is an
iterable whose elements are each either @code{name}, @code{(name, type)},
or @code{(name, type, Field)}.  If just @code{name} is supplied,
@ref{8bb,,typing.Any} is used for @code{type}.  The values of `init',
`repr', `eq', `order', `unsafe_hash', `frozen',
`match_args', `kw_only', `slots', and `weakref_slot' have
the same meaning as they do in @ref{4e1,,@@dataclass}.

If `module' is defined, the @code{__module__} attribute
of the dataclass is set to that value.
By default, it is set to the module name of the caller.

The `decorator' parameter is a callable that will be used to create the dataclass.
It should take the class object as a first argument and the same keyword arguments
as @ref{4e1,,@@dataclass}. By default, the @ref{4e1,,@@dataclass}
function is used.

This function is not strictly required, because any Python
mechanism for creating a new class with @ref{458,,__annotations__} can
then apply the @ref{4e1,,@@dataclass} function to convert that class to
a dataclass.  This function is provided as a convenience.  For
example:

@example
C = make_dataclass('C',
                   [('x', int),
                     'y',
                    ('z', int, field(default=5))],
                   namespace=@{'add_one': lambda self: self.x + 1@})
@end example

は、次のコードと等しいです:

@example
@@dataclass
class C:
    x: int
    y: 'typing.Any'
    z: int = 5

    def add_one(self):
        return self.x + 1
@end example


Added in version 3.14: Added the `decorator' parameter.

@end deffn

@geindex replace() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses replace}@anchor{1a6a}
@deffn {の関数} 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 @ref{198,,TypeError}.  If keys in `changes' are not
field names of the given dataclass, raises @ref{198,,TypeError}.

The newly returned object is created by calling the @ref{8bf,,__init__()}
method of the dataclass.  This ensures that
@ref{49a6,,__post_init__()}, if present, is also called.

Init-only variables without default values, if any exist, must be
specified on the call to @code{replace()} so that they can be passed to
@code{__init__()} and @ref{49a6,,__post_init__()}.

It is an error for `changes' to contain any fields that are
defined as having @code{init=False}.  A @ref{2ec,,ValueError} will be raised
in this case.

Be forewarned about how @code{init=False} fields work during a call to
@code{replace()}.  They are not copied from the source object, but
rather are initialized in @ref{49a6,,__post_init__()}, if they're
initialized at all.  It is expected that @code{init=False} fields will
be rarely and judiciously used.  If they are used, it might be wise
to have alternate class constructors, or perhaps a custom
@code{replace()} (or similarly named) method which handles instance
copying.

Dataclass instances are also supported by generic function @ref{1c0,,copy.replace()}.
@end deffn

@geindex is_dataclass() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses is_dataclass}@anchor{1c17}
@deffn {の関数} dataclasses.is_dataclass (obj)

Return @code{True} if its parameter is a dataclass (including subclasses of a
dataclass) or an instance of one, otherwise return @code{False}.

引数がデータクラスのインスタンスである (そして、データクラスそのものではない) かどうかを知る必要がある場合は、 @code{not isinstance(obj, type)} で追加のチェックをしてください:

@example
def is_dataclass_instance(obj):
    return is_dataclass(obj) and not isinstance(obj, type)
@end example
@end deffn

@geindex MISSING (dataclasses モジュール)
@anchor{library/dataclasses dataclasses MISSING}@anchor{49a4}
@deffn {データ} dataclasses.MISSING

デフォルト値やdefault_factoryが設定されてない場合の番兵の値を設定します。
@end deffn

@geindex KW_ONLY (dataclasses モジュール)
@anchor{library/dataclasses dataclasses KW_ONLY}@anchor{49a3}
@deffn {データ} dataclasses.KW_ONLY

A sentinel value used as a type annotation.  Any fields after a
pseudo-field with the type of @code{KW_ONLY} are marked as
keyword-only fields.  Note that a pseudo-field of type
@code{KW_ONLY} is otherwise completely ignored.  This includes the
name of such a field.  By convention, a name of @code{_} is used for a
@code{KW_ONLY} field.  Keyword-only fields signify
@ref{8bf,,__init__()} parameters that must be specified as keywords when
the class is instantiated.

このサンプルでは @code{y} と @code{z} がキーワード専用フィールドとなります:

@example
@@dataclass
class Point:
    x: float
    _: KW_ONLY
    y: float
    z: float

p = Point(0, y=1.5, z=2.0)
@end example

In a single dataclass, it is an error to specify more than one
field whose type is @code{KW_ONLY}.


Added in version 3.10.

@end deffn

@geindex FrozenInstanceError
@anchor{library/dataclasses dataclasses FrozenInstanceError}@anchor{49a7}
@deffn {例外} dataclasses.FrozenInstanceError

@code{frozen=True} 付きで定義されたデータクラスで、暗黙的に定義された @ref{237c,,__setattr__()} または @ref{237d,,__delattr__()} が呼び出されたときに送出されます。これは @ref{5f0,,AttributeError} のサブクラスです。
@end deffn

@node 初期化後の処理,クラス変数,モジュールの内容<4>,dataclasses --- データクラス
@anchor{library/dataclasses id1}@anchor{49a8}@anchor{library/dataclasses post-init-processing}@anchor{49a9}
@subsubsection 初期化後の処理


@geindex __post_init__() (dataclasses モジュール)
@anchor{library/dataclasses dataclasses __post_init__}@anchor{49a6}
@deffn {の関数} dataclasses.__post_init__ ()

When defined on the class, it will be called by the generated
@ref{8bf,,__init__()}, normally as @code{self.__post_init__()}.
However, if any @code{InitVar} fields are defined, they will also be
passed to @code{__post_init__()} in the order they were defined in the
class.  If no @code{__init__()} method is generated, then
@code{__post_init__()} will not automatically be called.

他の機能と組み合わせることで、他の 1 つ以上のフィールドに依存しているフィールドが初期化できます。
例えば次のようにできます:

@example
@@dataclass
class C:
    a: float
    b: float
    c: float = field(init=False)

    def __post_init__(self):
        self.c = self.a + self.b
@end example
@end deffn

The @ref{8bf,,__init__()} method generated by @ref{4e1,,@@dataclass} does not call base
class @code{__init__()} methods. If the base class has an @code{__init__()} method
that has to be called, it is common to call this method in a
@ref{49a6,,__post_init__()} method:

@example
class Rectangle:
    def __init__(self, height, width):
        self.height = height
        self.width = width

@@dataclass
class Square(Rectangle):
    side: float

    def __post_init__(self):
        super().__init__(self.side, self.side)
@end example

Note, however, that in general the dataclass-generated @code{__init__()} methods
don't need to be called, since the derived dataclass will take care of
initializing all fields of any base class that is a dataclass itself.

下にある初期化限定変数についての節で、 @code{__post_init__()} にパラメータを渡す方法を参照してください。
@ref{1a6a,,replace()} が @code{init=False} であるフィールドをどう取り扱うかについての警告も参照してください。

@node クラス変数,初期化限定変数,初期化後の処理,dataclasses --- データクラス
@anchor{library/dataclasses class-variables}@anchor{49aa}@anchor{library/dataclasses dataclasses-class-variables}@anchor{49ab}
@subsubsection クラス変数


One of the few places where @ref{4e1,,@@dataclass} actually inspects the type
of a field is to determine if a field is a class variable as defined
in 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/}.  It does this by checking if the type of the field is
@ref{56d,,typing.ClassVar}.  If a field is a @code{ClassVar}, it is excluded
from consideration as a field and is ignored by the dataclass
mechanisms.  Such @code{ClassVar} pseudo-fields are not returned by the
module-level @ref{1935,,fields()} function.

@node 初期化限定変数,凍結されたインスタンス,クラス変数,dataclasses --- データクラス
@anchor{library/dataclasses dataclasses-init-only-variables}@anchor{49a5}@anchor{library/dataclasses init-only-variables}@anchor{49ac}
@subsubsection 初期化限定変数


Another place where @ref{4e1,,@@dataclass} inspects a type annotation is to
determine if a field is an init-only variable.  It does this by seeing
if the type of a field is of type @ref{1bb4,,InitVar}.  If a field
is an @ref{1bb4,,InitVar}, it is considered a pseudo-field called an init-only
field.  As it is not a true field, it is not returned by the
module-level @ref{1935,,fields()} function.  Init-only fields are added as
parameters to the generated @ref{8bf,,__init__()} method, and are passed to
the optional @ref{49a6,,__post_init__()} method.  They are not otherwise used
by dataclasses.

例えば、あるフィールドがデータベースから初期化されると仮定して、クラスを作成するときには値が与えられない次の場合を考えます:

@example
@@dataclass
class C:
    i: int
    j: int | None = None
    database: InitVar[DatabaseType | None] = None

    def __post_init__(self, database):
        if self.j is None and database is not None:
            self.j = database.lookup('j')

c = C(10, database=my_database)
@end example

In this case, @ref{1935,,fields()} will return @ref{195b,,Field} objects for @code{i} and
@code{j}, but not for @code{database}.

@node 凍結されたインスタンス,継承<2>,初期化限定変数,dataclasses --- データクラス
@anchor{library/dataclasses dataclasses-frozen}@anchor{49a2}@anchor{library/dataclasses frozen-instances}@anchor{49ad}
@subsubsection 凍結されたインスタンス


It is not possible to create truly immutable Python objects.  However,
by passing @code{frozen=True} to the @ref{4e1,,@@dataclass} decorator you can
emulate immutability.  In that case, dataclasses will add
@ref{237c,,__setattr__()} and @ref{237d,,__delattr__()} methods to the class.  These
methods will raise a @ref{49a7,,FrozenInstanceError} when invoked.

There is a tiny performance penalty when using @code{frozen=True}:
@ref{8bf,,__init__()} cannot use simple assignment to initialize fields, and
must use @code{object.__setattr__()}.

@c Make sure to not remove "object" from "object.__setattr__" in the above markup!

@node 継承<2>,Re-ordering of keyword-only parameters in __init__,凍結されたインスタンス,dataclasses --- データクラス
@anchor{library/dataclasses dataclasses-inheritance}@anchor{49ae}@anchor{library/dataclasses inheritance}@anchor{49af}
@subsubsection 継承


When the dataclass is being created by the @ref{4e1,,@@dataclass} decorator,
it looks through all of the class's base classes in reverse MRO (that
is, starting at @ref{c7e,,object}) and, for each dataclass that it finds,
adds the fields from that base class to an ordered mapping of fields.
After all of the base class fields are added, it adds its own fields
to the ordered mapping.  All of the generated methods will use this
combined, calculated ordered mapping of fields.  Because the fields
are in insertion order, derived classes override base classes.  An
example:

@example
@@dataclass
class Base:
    x: Any = 15.0
    y: int = 0

@@dataclass
class C(Base):
    z: int = 10
    x: int = 15
@end example

The final list of fields is, in order, @code{x}, @code{y}, @code{z}.  The final
type of @code{x} is @ref{19b,,int}, as specified in class @code{C}.

The generated @ref{8bf,,__init__()} method for @code{C} will look like:

@example
def __init__(self, x: int = 15, y: int = 0, z: int = 10):
@end example

@node Re-ordering of keyword-only parameters in __init__,デフォルトファクトリ関数,継承<2>,dataclasses --- データクラス
@anchor{library/dataclasses re-ordering-of-keyword-only-parameters-in-init}@anchor{49b0}
@subsubsection Re-ordering of keyword-only parameters in @code{__init__()}


@ref{8bf,,__init__()} で必要なパラメータが算出されると、キーワード専用引数は他の一般的な（非キーワード専用）パラメータの後に移動します。これは、すべてのキーワード専用引数は、非キーワード専用パラメータの末尾にこなければならないという、キーワード専用パラメータのPythonの実装の都合で必要なことです。

In this example, @code{Base.y}, @code{Base.w}, and @code{D.t} are keyword-only
fields, and @code{Base.x} and @code{D.z} are regular fields:

@example
@@dataclass
class Base:
    x: Any = 15.0
    _: KW_ONLY
    y: int = 0
    w: int = 1

@@dataclass
class D(Base):
    z: int = 10
    t: int = field(kw_only=True, default=0)
@end example

The generated @code{__init__()} method for @code{D} will look like:

@example
def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0):
@end example

パラメータは、フィールドのリストの表示方法によって並べ替えられます。通常のフィールドから派生したパラメータの後に、キーワードのみのフィールドから派生したパラメータが続きます。

The relative ordering of keyword-only parameters is maintained in the
re-ordered @code{__init__()} parameter list.

@node デフォルトファクトリ関数,可変なデフォルト値,Re-ordering of keyword-only parameters in __init__,dataclasses --- データクラス
@anchor{library/dataclasses default-factory-functions}@anchor{49b1}
@subsubsection デフォルトファクトリ関数


If a @ref{195a,,field()} specifies a `default_factory', it is called with
zero arguments when a default value for the field is needed.  For
example, to create a new instance of a list, use:

@example
mylist: list = field(default_factory=list)
@end example

If a field is excluded from @ref{8bf,,__init__()} (using @code{init=False})
and the field also specifies `default_factory', then the default
factory function will always be called from the generated
@code{__init__()} function.  This happens because there is no other
way to give the field an initial value.

@node 可変なデフォルト値,Descriptor-typed fields,デフォルトファクトリ関数,dataclasses --- データクラス
@anchor{library/dataclasses mutable-default-values}@anchor{49b2}
@subsubsection 可変なデフォルト値


Python はメンバ変数のデフォルト値をクラス属性に保持します。
データクラスを使っていない、この例を考えてみましょう:

@example
class C:
    x = []
    def add(self, element):
        self.x.append(element)

o1 = C()
o2 = C()
o1.add(1)
o2.add(2)
assert o1.x == [1, 2]
assert o1.x is o2.x
@end example

Note that the two instances of class @code{C} share the same class
variable @code{x}, as expected.

データクラスを使っているこのコードが `もし仮に' 有効なものだとしたら:

@example
@@dataclass
class D:
    x: list = []      # This code raises ValueError
    def add(self, element):
        self.x.append(element)
@end example

データクラスは次のようなコードを生成するでしょう:

@example
class D:
    x = []
    def __init__(self, x=x):
        self.x = x
    def add(self, element):
        self.x.append(element)

assert D().x is D().x
@end example

This has the same issue as the original example using class @code{C}.
That is, two instances of class @code{D} that do not specify a value
for @code{x} when creating a class instance will share the same copy
of @code{x}.  Because dataclasses just use normal Python class
creation they also share this behavior.  There is no general way
for Data Classes to detect this condition.  Instead, the
@ref{4e1,,@@dataclass} decorator will raise a @ref{2ec,,ValueError} if it
detects an unhashable default parameter.  The assumption is that if
a value is unhashable, it is mutable.  This is a partial solution,
but it does protect against many common errors.

デフォルトファクトリ関数を使うのが、フィールドのデフォルト値として可変な型の新しいインスタンスを作成する手段です:

@example
@@dataclass
class D:
    x: list = field(default_factory=list)

assert D().x is not D().x
@end example


バージョン 3.11 で変更: Instead of looking for and disallowing objects of type @ref{24d,,list},
@ref{183,,dict}, or @ref{184,,set}, unhashable objects are now not allowed as
default values.  Unhashability is used to approximate
mutability.


@node Descriptor-typed fields,,可変なデフォルト値,dataclasses --- データクラス
@anchor{library/dataclasses descriptor-typed-fields}@anchor{49b3}
@subsubsection Descriptor-typed fields


Fields that are assigned @ref{e49,,descriptor objects} as their
default value have the following special behaviors:


@itemize *

@item 
The value for the field passed to the dataclass's @ref{8bf,,__init__()} method is
passed to the descriptor's @ref{23b5,,__set__()} method rather than overwriting the
descriptor object.

@item 
Similarly, when getting or setting the field, the descriptor's
@ref{1701,,__get__()} or @code{__set__()} method is called rather than returning or
overwriting the descriptor object.

@item 
To determine whether a field contains a default value, @ref{4e1,,@@dataclass}
will call the descriptor's @code{__get__()} method using its class access
form: @code{descriptor.__get__(obj=None, type=cls)}.  If the
descriptor returns a value in this case, it will be used as the
field's default. On the other hand, if the descriptor raises
@ref{5f0,,AttributeError} in this situation, no default value will be
provided for the field.
@end itemize

@example
class IntConversionDescriptor:
    def __init__(self, *, default):
        self._default = default

    def __set_name__(self, owner, name):
        self._name = "_" + name

    def __get__(self, obj, type):
        if obj is None:
            return self._default

        return getattr(obj, self._name, self._default)

    def __set__(self, obj, value):
        setattr(obj, self._name, int(value))

@@dataclass
class InventoryItem:
    quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)

i = InventoryItem()
print(i.quantity_on_hand)   # 100
i.quantity_on_hand = 2.5    # calls __set__ with 2.5
print(i.quantity_on_hand)   # 2
@end example

Note that if a field is annotated with a descriptor type, but is not assigned
a descriptor object as its default value, the field will act like a normal
field.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node contextlib --- with 文コンテキスト用ユーティリティ,abc --- 抽象基底クラス,dataclasses --- データクラス,Python ランタイムサービス
@anchor{library/contextlib doc}@anchor{49b4}@anchor{library/contextlib contextlib-utilities-for-with-statement-contexts}@anchor{49b5}@anchor{library/contextlib module-contextlib}@anchor{27}@anchor{library/contextlib translation-repo}@anchor{49b6}
@subsection @code{contextlib} --- @code{with} 文コンテキスト用ユーティリティ


@geindex module; contextlib

`ソースコード:' Lib/contextlib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/contextlib.py}


__________________________________________________________________


このモジュールは @ref{186,,with} 文に関わる一般的なタスクのためのユーティリティを提供します。詳しい情報は、 @ref{240d,,コンテキストマネージャ型} と @ref{240b,,with文とコンテキストマネージャ} を参照してください。

@menu
* ユーティリティ:: 
* 例とレシピ: 例とレシピ<3>. 
* 単回使用、再利用可能、およびリエントラントなコンテキストマネージャ:: 

@end menu

@node ユーティリティ,例とレシピ<3>,,contextlib --- with 文コンテキスト用ユーティリティ
@anchor{library/contextlib utilities}@anchor{49b7}
@subsubsection ユーティリティ


以下の関数とクラスを提供しています:

@geindex AbstractContextManager (contextlib のクラス)
@anchor{library/contextlib contextlib AbstractContextManager}@anchor{e8a}
@deffn {クラス} contextlib.AbstractContextManager

@ref{7e4,,object.__enter__()} と @ref{1518,,object.__exit__()} の2つのメソッドを実装した抽象基底クラス (@ref{13ce,,abstract base class}) です。 @ref{7e4,,object.__enter__()} は @code{self} を返すデフォルトの実装が提供されるいっぽう、 @ref{1518,,object.__exit__()} はデフォルトで @code{None} を返す抽象メソッドです。 @ref{240d,,コンテキストマネージャ型} の定義も参照してください。


Added in version 3.6.

@end deffn

@geindex AbstractAsyncContextManager (contextlib のクラス)
@anchor{library/contextlib contextlib AbstractAsyncContextManager}@anchor{d20}
@deffn {クラス} contextlib.AbstractAsyncContextManager

@ref{241d,,object.__aenter__()} と @ref{19a1,,object.__aexit__()} の2つのメソッドを実装するクラスのための抽象基底クラス (@ref{13ce,,abstract base class}) です。 @ref{241d,,object.__aenter__()} は @code{self} を返すデフォルト実装が提供されるいっぽう、 @ref{19a1,,object.__aexit__()} はデフォルトで @code{None} を返す抽象メソッドです。 @ref{812,,非同期コンテキストマネージャ (Asynchronous Context Manager)} の定義も参照してください。


Added in version 3.7.

@end deffn

@geindex contextmanager() (contextlib モジュール)
@anchor{library/contextlib contextlib contextmanager}@anchor{141b}
@deffn {の関数} @@contextlib.contextmanager

この関数は @ref{186,,with} 文コンテキストマネージャのファクトリ関数を定義するために利用できる @ref{93a,,デコレータ} です。新しいクラスや @ref{7e4,,__enter__()} と @ref{1518,,__exit__()} メソッドを別々に定義しなくても、ファクトリ関数を定義することができます。

While many objects natively support use in with statements, sometimes a
resource needs to be managed that isn't a context manager in its own right,
and doesn't implement a @code{close()} method for use with @code{contextlib.closing}.

リソースを正しく管理するよう保証する抽象的な例は以下のようなものでしょう:

@example
from contextlib import contextmanager

@@contextmanager
def managed_resource(*args, **kwds):
    # Code to acquire resource, e.g.:
    resource = acquire_resource(*args, **kwds)
    try:
        yield resource
    finally:
        # Code to release resource, e.g.:
        release_resource(resource)
@end example

このとき、関数は次のように使うことができます:

@example
>>> with managed_resource(timeout=3600) as resource:
...     # Resource is released at the end of this block,
...     # even if code in the block raises an exception
@end example

デコレート対象の関数は呼び出されたときに @ref{126c,,ジェネレータ}-イテレータを返す必要があります。このイテレータは必ず値を1つ yield しなければなりません。 @ref{186,,with} 文の @code{as} 節が存在するなら、その値は as 節のターゲットへ束縛されることになります。

ジェネレータが yield を実行した箇所で @ref{186,,with} 文のネストされたブロックが実行されます。ブロックから抜けた後でジェネレータは再開されます。ブロック内で処理されない例外が発生した場合は、ジェネレータ内部の yield を実行した箇所で例外が再送出されます。なので、(もしあれば) エラーを捕捉したり、クリーンアップ処理を確実に実行したりするために、@ref{8f8,,try}...@ref{1ab,,except}...@ref{1b0,,finally} 構文を使用できます。例外を捕捉する目的が、(完全に例外を抑制してしまうのではなく) 単に例外のログをとるため、もしくはあるアクションを実行するためなら、ジェネレータはその例外を再送出しなければなりません。例外を再送出しない場合、ジェネレータのコンテキストマネージャは @code{with} 文に対して例外が処理されたことを示し、@code{with} 文の直後の文から実行を再開します。

@ref{141b,,contextmanager()} は @ref{141a,,ContextDecorator} を使っているので、 @ref{141b,,contextmanager()} で作ったコンテキストマネージャは @ref{186,,with} 文だけでなくデコレータとしても利用できます。デコレーターとして利用された場合、新しい generator インスタンスが関数呼び出しのたびに暗黙に生成されます (このことによって、 @ref{141b,,contextmanager()} によって作られたなにがしか「単発」コンテキストマネージャを、コンテキストマネージャがデコレータとして使われるためには多重に呼び出されることをサポートする必要がある、という要件に合致させることが出来ます。)


バージョン 3.2 で変更: @ref{141a,,ContextDecorator} の使用。

@end deffn

@geindex asynccontextmanager() (contextlib モジュール)
@anchor{library/contextlib contextlib asynccontextmanager}@anchor{d1f}
@deffn {の関数} @@contextlib.asynccontextmanager

@ref{141b,,contextmanager()} と似ていますが、 @ref{812,,非同期コンテキストマネージャ (asynchronous context manager)} を生成します。

この関数は @ref{185,,async with} 文のための非同期コンテキストマネージャのファクトリ関数を定義するために利用できるデコレータ (@ref{93a,,decorator}) です。新しいクラスや  @ref{241d,,__aenter__()} と @ref{19a1,,__aexit__()} メソッドを個別に定義する必要はありません。このデコレータは非同期ジェネレータ (@ref{249b,,asynchronous generator}) 関数に適用しなければなりません。

簡単な例:

@example
from contextlib import asynccontextmanager

@@asynccontextmanager
async def get_connection():
    conn = await acquire_db_connection()
    try:
        yield conn
    finally:
        await release_db_connection(conn)

async def get_all_users():
    async with get_connection() as conn:
        return conn.query('SELECT ...')
@end example


Added in version 3.7.


@ref{d1f,,asynccontextmanager()} とともに定義されたコンテキストマネージャは、デコレータとして使うことも @ref{185,,async with} 文と組み合わせて使うこともできます:

@example
import time
from contextlib import asynccontextmanager

@@asynccontextmanager
async def timeit():
    now = time.monotonic()
    try:
        yield
    finally:
        print(f'it took @{time.monotonic() - now@}s to run')

@@timeit()
async def main():
    # ... async code ...
@end example

デコレータとして使われた場合は、各関数呼び出しに対して暗黙のうちに新しいジェネレータインスタンスが生成されます。これにより、 @ref{d1f,,asynccontextmanager()} で生成された単回使用のコンテキストマネージャが複数回呼び出し可能となり、コンテキストマネージャをデコレータとして使うことができるための要件を満たすようにすることができます。


バージョン 3.10 で変更: @ref{d1f,,asynccontextmanager()} により生成された非同期コンテキストマネージャをデコレータとして使うことができるようになりました。

@end deffn

@geindex closing() (contextlib モジュール)
@anchor{library/contextlib contextlib closing}@anchor{15a1}
@deffn {の関数} contextlib.closing (thing)

ブロックの完了時に `thing' を close するコンテキストマネージャを返します。これは基本的に以下と等価です:

@example
from contextlib import contextmanager

@@contextmanager
def closing(thing):
    try:
        yield thing
    finally:
        thing.close()
@end example

そして、明示的に @code{page} を close する必要なしに、次のように書くことができます:

@example
from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('https://www.python.org')) as page:
    for line in page:
        print(line)
@end example

@code{page} を明示的に close する必要は無く、エラーが発生した場合でも、 @ref{186,,with} ブロックを出るときに @code{page.close()} が呼ばれます。

@cartouche
@quotation 注釈 
Most types managing resources support the @ref{1e1,,context manager} protocol,
which closes `thing' on leaving the @ref{186,,with} statement.
As such, @code{closing()} is most useful for third party types that don't
support context managers.
This example is purely for illustration purposes,
as @ref{307,,urlopen()} would normally be used in a context manager.
@end quotation
@end cartouche
@end deffn

@geindex aclosing() (contextlib モジュール)
@anchor{library/contextlib contextlib aclosing}@anchor{9ee}
@deffn {の関数} contextlib.aclosing (thing)

ブロックの完了時に `thing' の @code{aclose()} メソッドを呼び出すような非同期コンテキストマネージャを返します。これは基本的に以下と等価です:

@example
from contextlib import asynccontextmanager

@@asynccontextmanager
async def aclosing(thing):
    try:
        yield thing
    finally:
        await thing.aclose()
@end example

重要なことは、たとえば次の例のように @ref{17f,,break} や例外によって早期にブロックが終了した場合に、 @code{aclosing()} は非同期ジェネレータの決定論的なクリーンアップをサポートすることです:

@example
from contextlib import aclosing

async with aclosing(my_generator()) as values:
    async for value in values:
        if value == 42:
            break
@end example

このパターンは、ジェネレータの非同期な終了のコードがイテレーション処理と同じコンテキストの中で実行されることを保証します (すなわち例外とコンテキスト変数は期待通りに動作し、またジェネレータが依存するタスクの寿命が尽きたあとに終了のコードが実行されることもありません)。


Added in version 3.10.

@end deffn

@geindex nullcontext() (contextlib モジュール)
@anchor{library/contextlib simplifying-support-for-single-optional-context-managers}@anchor{49b8}@anchor{library/contextlib contextlib nullcontext}@anchor{9ef}
@deffn {の関数} contextlib.nullcontext (enter_result=None)

`enter_result' を @code{__enter__} メソッドが返すだけで、その他は何もしないコンテキストマネージャを返します。たとえば以下のように、ある機能を持った別のコンテキストマネージャに対する、選択可能な代役として使われることが意図されています:

@example
def myfunction(arg, ignore_exceptions=False):
    if ignore_exceptions:
        # Use suppress to ignore all exceptions.
        cm = contextlib.suppress(Exception)
    else:
        # Do not ignore any exceptions, cm has no effect.
        cm = contextlib.nullcontext()
    with cm:
        # Do something
@end example

`enter_result' を使った例です:

@example
def process_file(file_or_path):
    if isinstance(file_or_path, str):
        # If string, open file
        cm = open(file_or_path)
    else:
        # Caller is responsible for closing file
        cm = nullcontext(file_or_path)

    with cm as file:
        # Perform processing on the file
@end example

@ref{812,,非同期コンテキストマネージャ} の代役として使うこともできます:

@example
async def send_http(session=None):
    if not session:
        # If no http session, create it with aiohttp
        cm = aiohttp.ClientSession()
    else:
        # Caller is responsible for closing the session
        cm = nullcontext(session)

    async with cm as session:
        # Send http requests with session
@end example


Added in version 3.7.



バージョン 3.10 で変更: 非同期コンテキストマネージャ (@ref{7f0,,asynchronous context manager}) のサポートが追加されました。

@end deffn

@geindex suppress() (contextlib モジュール)
@anchor{library/contextlib contextlib suppress}@anchor{1129}
@deffn {の関数} contextlib.suppress (*exceptions)

@code{with} 文の内部で指定された例外の発生を抑えるコンテキストマネージャを返します。 @code{with} 文の後に続く最初の文から処理が再開されます。

ほかの完全に例外を抑制するメカニズム同様、このコンテキストマネージャは、黙ってプログラム実行を続けることが正しいことであるとわかっている、非常に限定的なエラーをカバーする以上の使い方はしてはいけません。

例えば:

@example
from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

with suppress(FileNotFoundError):
    os.remove('someotherfile.tmp')
@end example

これは以下と等価です:

@example
try:
    os.remove('somefile.tmp')
except FileNotFoundError:
    pass

try:
    os.remove('someotherfile.tmp')
except FileNotFoundError:
    pass
@end example

このコンテキストマネージャは @ref{49b9,,再入可能(リエントラント)} です。

If the code within the @code{with} block raises a
@ref{566,,BaseExceptionGroup}, suppressed exceptions are removed from the
group.  Any exceptions of the group which are not suppressed are re-raised in
a new group which is created using the original group's @ref{1a37,,derive()}
method.


Added in version 3.4.



バージョン 3.12 で変更: @code{suppress} now supports suppressing exceptions raised as
part of a @ref{566,,BaseExceptionGroup}.

@end deffn

@geindex redirect_stdout() (contextlib モジュール)
@anchor{library/contextlib contextlib redirect_stdout}@anchor{fe7}
@deffn {の関数} contextlib.redirect_stdout (new_target)

@ref{ccd,,sys.stdout} を一時的に別のファイルまたは file-like オブジェクトにリダイレクトするコンテキストマネージャです。

このツールは、出力先が標準出力 (stdout) に固定されている既存の関数やクラスに出力先の柔軟性を追加します。

たとえば、 @ref{ad4,,help()} の出力は通常標準出力 (`sys.stdout') に送られます。出力される文字列を @ref{112a,,io.StringIO} オブジェクトにリダイレクトすることによって捕捉することができます。代替の出力ストリームは @code{__enter__} メソッドによって返されるので、 @ref{186,,with} 文のターゲットとして利用可能です:

@example
with redirect_stdout(io.StringIO()) as f:
    help(pow)
s = f.getvalue()
@end example

@ref{ad4,,help()} の出力をディスク上のファイルに送るためには、出力を通常のファイルにリダイレクトします:

@example
with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)
@end example

@ref{ad4,,help()} の出力を標準エラー出力 (`sys.stderr') に送るには以下のようにします:

@example
with redirect_stdout(sys.stderr):
    help(pow)
@end example

@ref{ccd,,sys.stdout} のシステム全体にわたる副作用により、このコンテキストマネージャはライブラリコードやマルチスレッドアプリケーションでの使用には適していません。また、サブプロセスの出力に対しても効果がありません。そのような制限はありますが、それでも多くのユーティリティスクリプトに対して有用なアプローチです。

このコンテキストマネージャは @ref{49b9,,再入可能(リエントラント)} です。


Added in version 3.4.

@end deffn

@geindex redirect_stderr() (contextlib モジュール)
@anchor{library/contextlib contextlib redirect_stderr}@anchor{fe6}
@deffn {の関数} contextlib.redirect_stderr (new_target)

@ref{fe7,,redirect_stdout()} と同じですが、標準エラー出力 (@ref{b33,,sys.stderr}) を別のファイルや file-like オブジェクトにリダイレクトします。

このコンテキストマネージャは @ref{49b9,,再入可能(リエントラント)} です。


Added in version 3.5.

@end deffn

@geindex chdir() (contextlib モジュール)
@anchor{library/contextlib contextlib chdir}@anchor{820}
@deffn {の関数} contextlib.chdir (path)

現在の作業ディレクトリを変更するパラレル非安全なコンテキストマネージャです。グローバルな状態である作業ディレクトリを変更するため、ほとんどのマルチスレッドまたは非同期のコンテキストに対する利用は適切ではありません。また、プログラムの実行権限を一時的に放棄するジェネレータのような、直線的でないコードを実行する場合も適切ではありません -- 明確に必要でないかぎり、このコンテキストマネージャがアクティブな状態で yield すべきではありません。

これは @ref{821,,chdir()} の単純なラッパーで、コンテキストに入るときに現在の作業ディレクトリを変更し、終了時に元の作業ディレクトリを復元します。

このコンテキストマネージャは @ref{49b9,,再入可能(リエントラント)} です。


Added in version 3.11.

@end deffn

@geindex ContextDecorator (contextlib のクラス)
@anchor{library/contextlib contextlib ContextDecorator}@anchor{141a}
@deffn {クラス} contextlib.ContextDecorator

コンテキストマネージャをデコレータとしても使用できるようにする基底クラスです。

@code{ContextDecorator} から継承したコンテキストマネージャは、通常のコンテキストマネージャーと同じく @code{__enter__} および @code{__exit__} を実装する必要があります。@code{__exit__} はデコレータとして使用された場合でも例外をオプションの引数として受け取ります。

@ref{141b,,contextmanager()} は @code{ContextDecorator} を利用しているので、自動的にデコレーターとしても利用できるようになります。

@code{ContextDecorator} の例:

@example
from contextlib import ContextDecorator

class mycontext(ContextDecorator):
    def __enter__(self):
        print('Starting')
        return self

    def __exit__(self, *exc):
        print('Finishing')
        return False
@end example

このとき、クラスは次のように使うことができます:

@example
>>> @@mycontext()
... def function():
...     print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...     print('The bit in the middle')
...
Starting
The bit in the middle
Finishing
@end example

これは次のような形のコードに対するシンタックスシュガーになります:

@example
def f():
    with cm():
        # Do stuff
@end example

@code{ContextDecorator} を使うと代わりに次のように書けます:

@example
@@cm()
def f():
    # Do stuff
@end example

デコレーターを使うと、@code{cm} が関数の一部ではなく全体に適用されていることが明確になります (インデントレベルを1つ節約できるのもメリットです)。

すでに基底クラスを持っているコンテキストマネージャーも、@code{ContextDecorator} を mixin クラスとして利用することで拡張できます:

@example
from contextlib import ContextDecorator

class mycontext(ContextBaseClass, ContextDecorator):
    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False
@end example

@cartouche
@quotation 注釈 
デコレートされた関数が複数回呼び出せるように、内部のコンテキストマネージャーは複数の @ref{186,,with} 文に対応する必要があります。そうでないなら、明示的な @code{with} 文を関数内で利用するべきです。
@end quotation
@end cartouche


Added in version 3.2.

@end deffn

@geindex AsyncContextDecorator (contextlib のクラス)
@anchor{library/contextlib contextlib AsyncContextDecorator}@anchor{9f0}
@deffn {クラス} contextlib.AsyncContextDecorator

@ref{141a,,ContextDecorator} と同じですが、非同期関数専用のクラスです。

@code{AsyncContextDecorator} の使用例:

@example
from asyncio import run
from contextlib import AsyncContextDecorator

class mycontext(AsyncContextDecorator):
    async def __aenter__(self):
        print('Starting')
        return self

    async def __aexit__(self, *exc):
        print('Finishing')
        return False
@end example

このとき、クラスは次のように使うことができます:

@example
>>> @@mycontext()
... async def function():
...     print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing

>>> async def function():
...    async with mycontext():
...         print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing
@end example


Added in version 3.10.

@end deffn

@geindex ExitStack (contextlib のクラス)
@anchor{library/contextlib contextlib ExitStack}@anchor{d1e}
@deffn {クラス} contextlib.ExitStack

他の、特にオプションであったり入力に依存するようなコンテキストマネージャーやクリーンアップ関数を動的に組み合わせるためのコンテキストマネージャーです。

例えば、複数のファイルを1つの with 文で簡単に扱うことができます:

@example
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception
@end example

The @ref{7e4,,__enter__()} method returns the @ref{d1e,,ExitStack} instance, and
performs no additional operations.

各インスタンスは登録されたコールバックのスタックを管理し、インスタンスが (明示的に、あるいは @ref{186,,with} 文の終わりに暗黙的に)  close されるときに逆順でそれを呼び出します。コンテキストスタックのインスタンスが暗黙的にガベージコレクトされたときには callback は呼び出され `ません' 。

このスタックモデルは、(file オブジェクトのように) @code{__init__} メソッドでリソースを確保するコンテキストマネージャーを正しく扱うためのものです。

登録されたコールバックが登録の逆順で実行されるので、複数のネストされた @ref{186,,with} 文を利用するのと同じ振る舞いをします。これは例外処理にも適用されます。内側のコールバックが例外を抑制したり置き換えたりした場合、外側のコールバックには更新された状態に応じた引数が渡されます。

これは正しく exit callback の stack を巻き戻すための、比較的低レベルな API です。アプリケーション独自のより高レベルなコンテキストマネージャーを作るための基板として使うのに適しています。


Added in version 3.3.


@geindex enter_context() (contextlib.ExitStack のメソッド)
@anchor{library/contextlib contextlib ExitStack enter_context}@anchor{7ee}
@deffn {メソッド} enter_context (cm)

Enters a new context manager and adds its @ref{1518,,__exit__()} method to
the callback stack. The return value is the result of the context
manager's own @ref{7e4,,__enter__()} method.

コンテキストマネージャーは、普段 @ref{186,,with} 文で利用された時と同じように、例外を抑制することができます。


バージョン 3.11 で変更: `cm' がコンテキストマネージャでなかった場合、 @ref{5f0,,AttributeError} の代わりに @ref{198,,TypeError} 例外を送出します。

@end deffn

@geindex push() (contextlib.ExitStack のメソッド)
@anchor{library/contextlib contextlib ExitStack push}@anchor{49ba}
@deffn {メソッド} push (exit)

Adds a context manager's @ref{1518,,__exit__()} method to the callback stack.

As @code{__enter__} is `not' invoked, this method can be used to cover
part of an @ref{7e4,,__enter__()} implementation with a context manager's own
@ref{1518,,__exit__()} 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
@ref{1518,,__exit__()} method and adds it directly to the callback stack.

By returning true values, these callbacks can suppress exceptions the
same way context manager @ref{1518,,__exit__()} methods can.

この関数はデコレータとしても使えるように、受け取ったオブジェクトをそのまま返します。
@end deffn

@geindex callback() (contextlib.ExitStack のメソッド)
@anchor{library/contextlib contextlib ExitStack callback}@anchor{c76}
@deffn {メソッド} callback (callback, /, *args, **kwds)

任意の関数と引数を受け取り、コールバックスタックに追加します。

他のメソッドと異なり、このメソッドで追加されたコールバックは例外を抑制しません (例外の詳細も渡されません)。

この関数はデコレータとしても使えるように、受け取った callback をそのまま返します。
@end deffn

@geindex pop_all() (contextlib.ExitStack のメソッド)
@anchor{library/contextlib contextlib ExitStack pop_all}@anchor{49bb}
@deffn {メソッド} pop_all ()

コールバックスタックを新しい @ref{d1e,,ExitStack} インスタンスに移して、それを返します。このメソッドは callback を実行しません。代わりに、新しい stack が (明示的に、あるいは @ref{186,,with} 文の終わりに暗黙的に) close されるときに実行されます。

例えば、複数のファイルを "all or nothing" に開く処理を次のように書けます:

@example
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Hold onto the close method, but don't call it yet.
    close_files = stack.pop_all().close
    # If opening any file fails, all previously opened files will be
    # closed automatically. If all files are opened successfully,
    # they will remain open even after the with statement ends.
    # close_files() can then be invoked explicitly to close them all.
@end example
@end deffn

@geindex close() (contextlib.ExitStack のメソッド)
@anchor{library/contextlib contextlib ExitStack close}@anchor{49bc}
@deffn {メソッド} close ()

すぐにコールバックスタックを巻き戻し、コールバック関数を登録の逆順に呼び出します。登録されたすべてのコンテキストマネージャーと終了 callback に、例外が起こらなかった場合の引数が渡されます。
@end deffn
@end deffn

@geindex AsyncExitStack (contextlib のクラス)
@anchor{library/contextlib contextlib AsyncExitStack}@anchor{d21}
@deffn {クラス} contextlib.AsyncExitStack

@ref{d1e,,ExitStack} に似た @ref{812,,非同期コンテキストマネージャ} です。スタック上で同期と非同期の両方のコンテキストマネージャの組み合わせをサポートします。また、後処理のためのコルーチンも持っています。

The @ref{49bc,,close()} method is not implemented; @ref{49bd,,aclose()} must be used
instead.

@geindex enter_async_context() (contextlib.AsyncExitStack のメソッド)
@anchor{library/contextlib contextlib AsyncExitStack enter_async_context}@anchor{7ef}
@deffn {メソッド} async enter_async_context (cm)

Similar to @ref{7ee,,ExitStack.enter_context()} but expects an asynchronous context
manager.


バージョン 3.11 で変更: `cm' が非同期コンテキストマネージャでなかった場合、 @ref{5f0,,AttributeError} の代わりに @ref{198,,TypeError} 例外を送出します。

@end deffn

@geindex push_async_exit() (contextlib.AsyncExitStack のメソッド)
@anchor{library/contextlib contextlib AsyncExitStack push_async_exit}@anchor{49be}
@deffn {メソッド} push_async_exit (exit)

Similar to @ref{49ba,,ExitStack.push()} but expects either an asynchronous context manager
or a coroutine function.
@end deffn

@geindex push_async_callback() (contextlib.AsyncExitStack のメソッド)
@anchor{library/contextlib contextlib AsyncExitStack push_async_callback}@anchor{c77}
@deffn {メソッド} push_async_callback (callback, /, *args, **kwds)

Similar to @ref{c76,,ExitStack.callback()} but expects a coroutine function.
@end deffn

@geindex aclose() (contextlib.AsyncExitStack のメソッド)
@anchor{library/contextlib contextlib AsyncExitStack aclose}@anchor{49bd}
@deffn {メソッド} async aclose ()

Similar to @ref{49bc,,ExitStack.close()} but properly handles awaitables.
@end deffn

@ref{d1f,,asynccontextmanager()} の使用例の続きです:

@example
async with AsyncExitStack() as stack:
    connections = [await stack.enter_async_context(get_connection())
        for i in range(5)]
    # All opened connections will automatically be released at the end of
    # the async with statement, even if attempts to open a connection
    # later in the list raise an exception.
@end example


Added in version 3.7.

@end deffn

@node 例とレシピ<3>,単回使用、再利用可能、およびリエントラントなコンテキストマネージャ,ユーティリティ,contextlib --- with 文コンテキスト用ユーティリティ
@anchor{library/contextlib examples-and-recipes}@anchor{49bf}
@subsubsection 例とレシピ


This section describes some examples and recipes for making effective use of
the tools provided by @code{contextlib}.

@menu
* 可変数個のコンテキストマネージャーをサポートする:: 
* __enter__ メソッドからの例外をキャッチする:: 
* __enter__ 実装内のクリーンアップ:: 
* try-finally + flag 変数パターンを置き換える:: 
* コンテキストマネージャーを関数デコレーターとして使う:: 

@end menu

@node 可変数個のコンテキストマネージャーをサポートする,__enter__ メソッドからの例外をキャッチする,,例とレシピ<3>
@anchor{library/contextlib supporting-a-variable-number-of-context-managers}@anchor{49c0}
@subsubsection 可変数個のコンテキストマネージャーをサポートする


@ref{d1e,,ExitStack} の第一のユースケースは、クラスのドキュメントにかかれている通り、一つの @ref{186,,with} 文で可変数個のコンテキストマネージャーや他のクリーンアップ関数をサポートすることです。ユーザーの入力 (指定された複数個のファイルを開く場合など) に応じて複数個のコンテキストマネージャーが必要となる場合や、いくつかのコンテキストマネージャーがオプションとなる場合に、可変数個のコンテキストマネージャーが必要になります:

@example
with ExitStack() as stack:
    for resource in resources:
        stack.enter_context(resource)
    if need_special_resource():
        special = acquire_special_resource()
        stack.callback(release_special_resource, special)
    # Perform operations that use the acquired resources
@end example

上の例にあるように、 @ref{d1e,,ExitStack} はコンテキストマネージャープロトコルをサポートしていないリソースの管理を @ref{186,,with} 文を使って簡単に行えるようにします。

@node __enter__ メソッドからの例外をキャッチする,__enter__ 実装内のクリーンアップ,可変数個のコンテキストマネージャーをサポートする,例とレシピ<3>
@anchor{library/contextlib catching-exceptions-from-enter-methods}@anchor{49c1}
@subsubsection @code{__enter__} メソッドからの例外をキャッチする


稀に、 @code{__enter__} メソッドからの例外を、 @ref{186,,with} 文の body やコンテキストマネージャーの @code{__exit__} メソッドからの例外は間違えて捕まえないように、 catch したい場合があります。 @ref{d1e,,ExitStack} を使って、コンテキストマネージャープロトコル内のステップを分離することができます:

@example
stack = ExitStack()
try:
    x = stack.enter_context(cm)
except Exception:
    # handle __enter__ exception
else:
    with stack:
        # Handle normal case
@end example

実際のところ、このようなコードが必要になるのならば、利用している API 側で @ref{8f8,,try}/@ref{1ab,,except}/@ref{1b0,,finally} 文を使った直接的なリソース管理インターフェースを提供するべきです。しかし、すべての API がそのようによく設計されているとは限りません。もしコンテキストマネージャーが提供されている唯一のリソース管理APIであるなら、 @ref{d1e,,ExitStack} を使って @ref{186,,with} 文を使って処理することができない様々なシチュエーションの処理をすることができます。

@node __enter__ 実装内のクリーンアップ,try-finally + flag 変数パターンを置き換える,__enter__ メソッドからの例外をキャッチする,例とレシピ<3>
@anchor{library/contextlib cleaning-up-in-an-enter-implementation}@anchor{49c2}
@subsubsection @code{__enter__} 実装内のクリーンアップ


As noted in the documentation of @ref{49ba,,ExitStack.push()}, this
method can be useful in cleaning up an already allocated resource if later
steps in the @ref{7e4,,__enter__()} implementation fail.

次の例では、リソースの確保と開放の関数に加えて、オプションのバリデーション関数を受け取るコンテキストマネージャーで、この方法を使ってコンテキストマネージャープロトコルを提供しています:

@example
from contextlib import contextmanager, AbstractContextManager, ExitStack

class ResourceManager(AbstractContextManager):

    def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
        self.acquire_resource = acquire_resource
        self.release_resource = release_resource
        if check_resource_ok is None:
            def check_resource_ok(resource):
                return True
        self.check_resource_ok = check_resource_ok

    @@contextmanager
    def _cleanup_on_error(self):
        with ExitStack() as stack:
            stack.push(self)
            yield
            # The validation check passed and didn't raise an exception
            # Accordingly, we want to keep the resource, and pass it
            # back to our caller
            stack.pop_all()

    def __enter__(self):
        resource = self.acquire_resource()
        with self._cleanup_on_error():
            if not self.check_resource_ok(resource):
                msg = "Failed validation for @{!r@}"
                raise RuntimeError(msg.format(resource))
        return resource

    def __exit__(self, *exc_details):
        # We don't need to duplicate any of our resource release logic
        self.release_resource()
@end example

@node try-finally + flag 変数パターンを置き換える,コンテキストマネージャーを関数デコレーターとして使う,__enter__ 実装内のクリーンアップ,例とレシピ<3>
@anchor{library/contextlib replacing-any-use-of-try-finally-and-flag-variables}@anchor{49c3}
@subsubsection @code{try-finally} + flag 変数パターンを置き換える


@code{try-finally} 文に、@code{finally} 句の内容を実行するかどうかを示すフラグ変数を組み合わせたパターンを目にすることがあるかもしれません。一番シンプルな (単に @code{except} 句を使うだけでは処理できない) ケースでは次のようなコードになります:

@example
cleanup_needed = True
try:
    result = perform_operation()
    if result:
        cleanup_needed = False
finally:
    if cleanup_needed:
        cleanup_resources()
@end example

@code{try} 文を使ったコードでは、セットアップとクリーンアップのコードが任意の長さのコードで分離してしまうので、開発者やレビューアにとって問題になりえます。

@ref{d1e,,ExitStack} を使えば、代わりに @code{with} 文の終わりに実行されるコールバックを登録し、後でそのコールバックをスキップするかどうかを決定できます:

@example
from contextlib import ExitStack

with ExitStack() as stack:
    stack.callback(cleanup_resources)
    result = perform_operation()
    if result:
        stack.pop_all()
@end example

This allows the intended cleanup behaviour to be made explicit up front,
rather than requiring a separate flag variable.

もしあるアプリケーションがこのパターンを多用するのであれば、小さいヘルパークラスを導入してよりシンプルにすることができます:

@example
from contextlib import ExitStack

class Callback(ExitStack):
    def __init__(self, callback, /, *args, **kwds):
        super().__init__()
        self.callback(callback, *args, **kwds)

    def cancel(self):
        self.pop_all()

with Callback(cleanup_resources) as cb:
    result = perform_operation()
    if result:
        cb.cancel()
@end example

もしリソースのクリーンアップが単体の関数にまとまってない場合でも、 @ref{c76,,ExitStack.callback()} のデコレーター形式を利用してリソース開放処理を宣言することができます:

@example
from contextlib import ExitStack

with ExitStack() as stack:
    @@stack.callback
    def cleanup_resources():
        ...
    result = perform_operation()
    if result:
        stack.pop_all()
@end example

デコレータープロトコルの使用上、このように宣言されたコールバック関数は引数を取ることができません。その代わりに、リリースするリソースをクロージャー変数としてアクセスできる必要があります。

@node コンテキストマネージャーを関数デコレーターとして使う,,try-finally + flag 変数パターンを置き換える,例とレシピ<3>
@anchor{library/contextlib using-a-context-manager-as-a-function-decorator}@anchor{49c4}
@subsubsection コンテキストマネージャーを関数デコレーターとして使う


@ref{141a,,ContextDecorator} はコンテキストマネージャーを通常の @code{with} 文に加えて関数デコレーターとしても利用できるようにします。

例えば、関数やまとまった文を、そこに入った時と出た時の時間をトラックするロガーでラップしたい場合があります。そのために関数デコレーターとコンテキストマネージャーを別々に書く代わりに、 @ref{141a,,ContextDecorator} を継承すると1つの定義で両方の機能を提供できます:

@example
from contextlib import ContextDecorator
import logging

logging.basicConfig(level=logging.INFO)

class track_entry_and_exit(ContextDecorator):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        logging.info('Entering: %s', self.name)

    def __exit__(self, exc_type, exc, exc_tb):
        logging.info('Exiting: %s', self.name)
@end example

このクラスのインスタンスはコンテキストマネージャーとしても利用でき:

@example
with track_entry_and_exit('widget loader'):
    print('Some time consuming activity goes here')
    load_widget()
@end example

また関数デコレーターとしても利用できます:

@example
@@track_entry_and_exit('widget loader')
def activity():
    print('Some time consuming activity goes here')
    load_widget()
@end example

Note that there is one additional limitation when using context managers
as function decorators: there's no way to access the return value of
@ref{7e4,,__enter__()}. If that value is needed, then it is still necessary to use
an explicit @code{with} statement.


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 343

@item PEP 343@footnote{https://peps.python.org/pep-0343/} - "with" ステートメント

Python の @ref{186,,with} 文の仕様、背景、および例が記載されています。
@end table


@node 単回使用、再利用可能、およびリエントラントなコンテキストマネージャ,,例とレシピ<3>,contextlib --- with 文コンテキスト用ユーティリティ
@anchor{library/contextlib single-use-reusable-and-reentrant-cms}@anchor{112b}@anchor{library/contextlib single-use-reusable-and-reentrant-context-managers}@anchor{49c5}
@subsubsection 単回使用、再利用可能、およびリエントラントなコンテキストマネージャ


ほとんどのコンテキストマネージャは、 @ref{186,,with} 文の中で一度だけ使われるような場合に効果的になるように書かれています。これら単回使用のコンテキストマネージャは毎回新規に生成されなければなりません - それらを再利用しようとすると、例外を引き起こすか、正しく動作しません。

この共通の制限が意味することは、コンテキストマネージャは (上記すべての使用例に示すとおり) 一般に @ref{186,,with} 文のヘッダ部分で直接生成することが推奨されるということです。

ファイルオブジェクトは単回使用のコンテキストマネージャ有効に利用した例です。最初の @ref{186,,with} 文によりファイルがクローズされ、それ以降そのファイルオブジェクトに対するすべての IO 操作を防止します。

@ref{141b,,contextmanager()} により生成されたコンテキストマネージャも単回使用のコンテキスト  マネージャです。二回目に使おうとした場合、内部にあるジェネレータが値の生成に失敗したと訴えるでしょう:

@example
>>> from contextlib import contextmanager
>>> @@contextmanager
... def singleuse():
...     print("Before")
...     yield
...     print("After")
...
>>> cm = singleuse()
>>> with cm:
...     pass
...
Before
After
>>> with cm:
...     pass
...
Traceback (most recent call last):
    ...
RuntimeError: generator didn't yield
@end example

@menu
* リエントラントなコンテキストマネージャ:: 
* 再利用可能なコンテキストマネージャ:: 

@end menu

@node リエントラントなコンテキストマネージャ,再利用可能なコンテキストマネージャ,,単回使用、再利用可能、およびリエントラントなコンテキストマネージャ
@anchor{library/contextlib reentrant-cms}@anchor{49b9}@anchor{library/contextlib reentrant-context-managers}@anchor{49c6}
@subsubsection リエントラントなコンテキストマネージャ


より洗練されたコンテキストマネージャには"リエントラント"なものがあります。そのようなコンテキストマネージャは、複数の @ref{186,,with} 文で使えるだけでなく、同じコンテキストマネージャをすでに使っている @code{with} 文の `内部' でも使うことができます。

@ref{32e,,threading.RLock} はリエントラントなコンテキストマネージャの例であり、また @ref{1129,,suppress()}, @ref{fe7,,redirect_stdout()}, そして @ref{820,,chdir()} もリエントラントです。以下はリエントラントな利用法の非常に単純な例です:

@example
>>> from contextlib import redirect_stdout
>>> from io import StringIO
>>> stream = StringIO()
>>> write_to_stream = redirect_stdout(stream)
>>> with write_to_stream:
...     print("This is written to the stream rather than stdout")
...     with write_to_stream:
...         print("This is also written to the stream")
...
>>> print("This is written directly to stdout")
This is written directly to stdout
>>> print(stream.getvalue())
This is written to the stream rather than stdout
This is also written to the stream
@end example

リエントラントな性質の実例はお互いを呼び出しあう複数の関数を含んでいる可能性が高く、したがってこの例よりもはるかに複雑です。

リエントラントであることはスレッドセーフであることと同じ `ではない' ことには注意が必要です。たとえば @ref{fe7,,redirect_stdout()} は、 @ref{ccd,,sys.stdout} を異なるストリームに束縛することによりシステムの状態に対してグローバルな変更を行うことから、明らかにスレッドセーフではありません。

@node 再利用可能なコンテキストマネージャ,,リエントラントなコンテキストマネージャ,単回使用、再利用可能、およびリエントラントなコンテキストマネージャ
@anchor{library/contextlib reusable-cms}@anchor{49c7}@anchor{library/contextlib reusable-context-managers}@anchor{49c8}
@subsubsection 再利用可能なコンテキストマネージャ


単回使用のコンテキストマネージャとリエントラントなコンテキストマネージャのいずれとも異なるタイプに "再利用可能" なコンテキストマネージャがあります (あるいは、より明確には、"再利用可能だがリエントラントでない" コンテキストマネージャです。リエントラントなコンテキストマネージャもまた再利用可能だからです)。再利用可能なコンテキストマネージャは複数回利用をサポートしますが、同じコンテキストマネージャのインスタンスがすでに with 文で使われている場合には失敗します (もしくは正しく動作しません)。

@ref{19f4,,threading.Lock} は再利用可能だがリエントラントでないコンテキストマネージャの例です (リエントラントなロックのためには @ref{32e,,threading.RLock} を代わりに使う必要があります)。

再利用可能だがリエントラントでないコンテキストマネージャのもうひとつの例は @ref{d1e,,ExitStack} です。これは現在登録されている `全ての' コールバック関数を、どこで登録されたかにかかわらず、呼び出します:

@example
>>> from contextlib import ExitStack
>>> stack = ExitStack()
>>> with stack:
...     stack.callback(print, "Callback: from first context")
...     print("Leaving first context")
...
Leaving first context
Callback: from first context
>>> with stack:
...     stack.callback(print, "Callback: from second context")
...     print("Leaving second context")
...
Leaving second context
Callback: from second context
>>> with stack:
...     stack.callback(print, "Callback: from outer context")
...     with stack:
...         stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Callback: from outer context
Leaving outer context
@end example

例における出力が示すように、ひとつのスタックオブジェクトを複数の with 文で再利用しても正しく動作します。しかし入れ子にして使った場合は、一番内側の with 文を抜ける際にスタックが空になります。これは望ましい動作とは思えません。

ひとつの @ref{d1e,,ExitStack} インスタンスを再利用する代わりに複数のインスタンスを使うことにより、この問題は回避することができます:

@example
>>> from contextlib import ExitStack
>>> with ExitStack() as outer_stack:
...     outer_stack.callback(print, "Callback: from outer context")
...     with ExitStack() as inner_stack:
...         inner_stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Leaving outer context
Callback: from outer context
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node abc --- 抽象基底クラス,atexit --- 終了ハンドラー,contextlib --- with 文コンテキスト用ユーティリティ,Python ランタイムサービス
@anchor{library/abc doc}@anchor{49c9}@anchor{library/abc abc-abstract-base-classes}@anchor{49ca}@anchor{library/abc module-abc}@anchor{4}@anchor{library/abc translation-repo}@anchor{49cb}
@subsection @code{abc} --- 抽象基底クラス


@geindex module; abc

@c much of the content adapted from docstrings

`ソースコード:' Lib/abc.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/abc.py}


__________________________________________________________________


このモジュールは Python に 
@geindex Python Enhancement Proposals; PEP 3119
PEP 3119@footnote{https://peps.python.org/pep-3119/} で概要が示された @ref{13ce,,抽象基底クラス} (ABC) を定義する基盤を提供します。なぜこれが Python に付け加えられたかについてはその PEP を参照してください。 (ABC に基づいた数の型階層を扱った 
@geindex Python Enhancement Proposals; PEP 3141
PEP 3141@footnote{https://peps.python.org/pep-3141/} と @ref{a2,,numbers} モジュールも参照してください。)

@ref{1e,,collections} モジュール には、抽象基底クラス から派生するいくつかの具象クラスがある。もちろん、これらはさらに派生させることができる。さらに、@code{collections.抽象基底クラス} サブモジュールには、クラスやインスタンス が特定のインターフェース 、たとえば 、:term:>>`<<hashable`であるか、:term:>>`<<mapping`であるかをテストするために使用できる抽象基底クラス があります。

このモジュールは、 抽象基底クラスを定義するためのメタクラス @ref{111c,,ABCMeta} と、 継承を利用して抽象基底クラスを代替的に定義するヘルパークラス @ref{111b,,ABC} を提供します。

@geindex ABC (abc のクラス)
@anchor{library/abc abc ABC}@anchor{111b}
@deffn {クラス} abc.ABC

メタクラスとして @ref{111c,,ABCMeta} を持つヘルパークラスです。このクラスを使うことで、@code{ABC} を継承するだけで抽象基底クラスを作成でき、しばしば混乱しがちなメタクラスの使用を避けることができます。例えば:

@example
from abc import ABC

class MyABC(ABC):
    pass
@end example

Note that the type of @code{ABC} is still @ref{111c,,ABCMeta}, therefore
inheriting from @code{ABC} requires the usual precautions regarding
metaclass usage, as multiple inheritance may lead to metaclass conflicts.
One may also define an abstract base class by passing the metaclass
keyword and using @code{ABCMeta} directly, for example:

@example
from abc import ABCMeta

class MyABC(metaclass=ABCMeta):
    pass
@end example


Added in version 3.4.

@end deffn

@geindex ABCMeta (abc のクラス)
@anchor{library/abc abc ABCMeta}@anchor{111c}
@deffn {クラス} abc.ABCMeta

抽象基底クラス(ABC)を定義するためのメタクラス。

ABC を作るときにこのメタクラスを使います。ABC は直接的にサブクラス化することができ、ミックスイン(mix-in)クラスのように振る舞います。また、無関係な具象クラス(組み込み型でも構いません)と無関係な ABC を "仮想的サブクラス" として登録できます -- これらとその子孫は組み込み関数 @ref{9c4,,issubclass()} によって登録した ABC のサブクラスと判定されますが、登録した ABC は MRO (Method Resolution Order, メソッド解決順)には現れませんし、この ABC のメソッド実装が(@ref{1a6,,super()} を通してだけでなく)呼び出し可能になるわけでもありません。 @footnote{
C++ プログラマは Python の仮想的基底クラスの概念は C++ のものと同じではないということを銘記すべきです。
}

Classes created with a metaclass of @code{ABCMeta} have the following method:

@geindex register() (abc.ABCMeta のメソッド)
@anchor{library/abc abc ABCMeta register}@anchor{129a}
@deffn {メソッド} register (subclass)

`subclass' を "仮想的サブクラス" としてこの ABC に登録します。たとえば:

@example
from abc import ABC

class MyABC(ABC):
    pass

MyABC.register(tuple)

assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
@end example


バージョン 3.3 で変更: クラスデコレータとして使うことができるように、登録されたサブクラスを返します。



バージョン 3.4 で変更: To detect calls to @code{register()}, you can use the
@ref{111a,,get_cache_token()} function.

@end deffn

また、次のメソッドを抽象基底クラスの中でオーバーライドできます:

@geindex __subclasshook__() (abc.ABCMeta のメソッド)
@anchor{library/abc abc ABCMeta __subclasshook__}@anchor{299a}
@deffn {メソッド} __subclasshook__ (subclass)

(クラスメソッドとして定義しなければなりません。)

Check whether `subclass' is considered a subclass of this ABC.  This means
that you can customize the behavior of @ref{9c4,,issubclass()} further without the
need to call @ref{129a,,register()} on every class you want to consider a
subclass of the ABC.  (This class method is called from the
@ref{23c7,,__subclasscheck__()} method of the ABC.)

This method should return @code{True}, @code{False} or @ref{1a2,,NotImplemented}.  If
it returns @code{True}, the `subclass' is considered a subclass of this ABC.
If it returns @code{False}, the `subclass' is not considered a subclass of
this ABC, even if it would normally be one.  If it returns
@code{NotImplemented}, the subclass check is continued with the usual
mechanism.

@c XXX explain the "usual mechanism"
@end deffn

この概念のデモとして、次の ABC 定義の例を見てください:

@example
class Foo:
    def __getitem__(self, index):
        ...
    def __len__(self):
        ...
    def get_iterator(self):
        return iter(self)

class MyIterable(ABC):

    @@abstractmethod
    def __iter__(self):
        while False:
            yield None

    def get_iterator(self):
        return self.__iter__()

    @@classmethod
    def __subclasshook__(cls, C):
        if cls is MyIterable:
            if any("__iter__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

MyIterable.register(Foo)
@end example

The ABC @code{MyIterable} defines the standard iterable method,
@ref{e69,,__iter__()}, as an abstract method.  The implementation given
here can still be called from subclasses.  The @code{get_iterator()} method
is also part of the @code{MyIterable} abstract base class, but it does not have
to be overridden in non-abstract derived classes.

The @ref{299a,,__subclasshook__()} class method defined here says that any class
that has an @ref{e69,,__iter__()} method in its
@ref{77d,,__dict__} (or in that of one of its base classes, accessed
via the @ref{2378,,__mro__} list) is considered a @code{MyIterable} too.

Finally, the last line makes @code{Foo} a virtual subclass of @code{MyIterable},
even though it does not define an @ref{e69,,__iter__()} method (it uses
the old-style iterable protocol, defined in terms of @ref{178f,,__len__()} and
@ref{588,,__getitem__()}).  Note that this will not make @code{get_iterator}
available as a method of @code{Foo}, so it is provided separately.
@end deffn

The @code{abc} module also provides the following decorator:

@geindex abstractmethod() (abc モジュール)
@anchor{library/abc abc abstractmethod}@anchor{1297}
@deffn {の関数} @@abc.abstractmethod

抽象メソッドを示すデコレータです。

Using this decorator requires that the class's metaclass is @ref{111c,,ABCMeta}
or is derived from it.  A class that has a metaclass derived from
@code{ABCMeta} cannot be instantiated unless all of its abstract methods
and properties are overridden.  The abstract methods can be called using any
of the normal 'super' call mechanisms.  @code{abstractmethod()} may be used
to declare abstract methods for properties and descriptors.

Dynamically adding abstract methods to a class, or attempting to modify the
abstraction status of a method or class once it is created, are only
supported using the @ref{49cc,,update_abstractmethods()} function.  The
@code{abstractmethod()} only affects subclasses derived using regular
inheritance; "virtual subclasses" registered with the ABC's
@ref{129a,,register()} method are not affected.

When @code{abstractmethod()} is applied in combination with other method
descriptors, it should be applied as the innermost decorator, as shown in
the following usage examples:

@example
class C(ABC):
    @@abstractmethod
    def my_abstract_method(self, arg1):
        ...
    @@classmethod
    @@abstractmethod
    def my_abstract_classmethod(cls, arg2):
        ...
    @@staticmethod
    @@abstractmethod
    def my_abstract_staticmethod(arg3):
        ...

    @@property
    @@abstractmethod
    def my_abstract_property(self):
        ...
    @@my_abstract_property.setter
    @@abstractmethod
    def my_abstract_property(self, val):
        ...

    @@abstractmethod
    def _get_x(self):
        ...
    @@abstractmethod
    def _set_x(self, val):
        ...
    x = property(_get_x, _set_x)
@end example

In order to correctly interoperate with the abstract base class machinery,
the descriptor must identify itself as abstract using
@code{__isabstractmethod__}. In general, this attribute should be @code{True}
if any of the methods used to compose the descriptor are abstract. For
example, Python's built-in @ref{4b3,,property} does the equivalent of:

@example
class Descriptor:
    ...
    @@property
    def __isabstractmethod__(self):
        return any(getattr(f, '__isabstractmethod__', False) for
                   f in (self._fget, self._fset, self._fdel))
@end example

@cartouche
@quotation 注釈 
Java の抽象メソッドと違い、これらの抽象メソッドは実装を持ち得ます。この実装は @ref{1a6,,super()} メカニズムを通してそれをオーバーライドしたクラスから呼び出すことができます。これは協調的多重継承を使ったフレームワークにおいて super 呼び出しの終点として有効です。
@end quotation
@end cartouche
@end deffn

The @code{abc} module also supports the following legacy decorators:

@geindex abstractclassmethod() (abc モジュール)
@anchor{library/abc abc abstractclassmethod}@anchor{1298}
@deffn {の関数} @@abc.abstractclassmethod


Added in version 3.2.



バージョン 3.3 で非推奨: @ref{48e,,classmethod} を @ref{1297,,abstractmethod()} と一緒に使えるようになったため、このデコレータは冗長になりました。


組み込みの @ref{48e,,classmethod()} のサブクラスで、抽象クラスメソッドであることを示します。それ以外は @ref{1297,,abstractmethod()} と同じです。

この特殊ケースは @ref{48e,,classmethod()} デコレータが抽象メソッドに適用された場合に抽象的だと正しく認識されるようになったため撤廃されます:

@example
class C(ABC):
    @@classmethod
    @@abstractmethod
    def my_abstract_classmethod(cls, arg):
        ...
@end example
@end deffn

@geindex abstractstaticmethod() (abc モジュール)
@anchor{library/abc abc abstractstaticmethod}@anchor{1299}
@deffn {の関数} @@abc.abstractstaticmethod


Added in version 3.2.



バージョン 3.3 で非推奨: @ref{453,,staticmethod} を @ref{1297,,abstractmethod()} と一緒に使えるようになったため、このデコレータは冗長になりました。


組み込みの @ref{453,,staticmethod()} のサブクラスで、抽象静的メソッドであることを示します。それ以外は @ref{1297,,abstractmethod()} と同じです。

この特殊ケースは @ref{453,,staticmethod()} デコレータが抽象メソッドに適用された場合に抽象的だと正しく認識されるようになったため撤廃されます:

@example
class C(ABC):
    @@staticmethod
    @@abstractmethod
    def my_abstract_staticmethod(arg):
        ...
@end example
@end deffn

@geindex abstractproperty() (abc モジュール)
@anchor{library/abc abc abstractproperty}@anchor{1296}
@deffn {の関数} @@abc.abstractproperty


バージョン 3.3 で非推奨: @ref{4b3,,property} 、 @ref{19d9,,property.getter()} 、 @ref{19da,,property.setter()} および @ref{19db,,property.deleter()}  を @ref{1297,,abstractmethod()} と一緒に使えるようになったため、このデコレータは冗長になりました。


組み込みの @ref{4b3,,property()} のサブクラスで、抽象プロパティであることを示します。

この特殊ケースは @ref{4b3,,property()} デコレータが抽象メソッドに適用された場合に抽象的だと正しく認識されるようになったため撤廃されます:

@example
class C(ABC):
    @@property
    @@abstractmethod
    def my_abstract_property(self):
        ...
@end example

この例は読み出し専用のプロパティを定義しています。プロパティを構成するメソッドの1つ以上を abstract にすることで、読み書きできる抽象プロパティを定義することができます:

@example
class C(ABC):
    @@property
    def x(self):
        ...

    @@x.setter
    @@abstractmethod
    def x(self, val):
        ...
@end example

構成するメソッド全てが abstract でない場合、abstract と定義されたメソッドのみが、具象サブクラスによってオーバーライドする必要があります:

@example
class D(C):
    @@C.x.setter
    def x(self, val):
        ...
@end example
@end deffn

The @code{abc} module also provides the following functions:

@geindex get_cache_token() (abc モジュール)
@anchor{library/abc abc get_cache_token}@anchor{111a}
@deffn {の関数} abc.get_cache_token ()

現在の抽象基底クラスのキャッシュトークンを返します。

このトークンは、仮想サブクラスのための抽象基底クラスの現在のバージョンを特定する (等価性検査をサポートしている) 不透明なオブジェクトです。
任意のABCでの @ref{129a,,ABCMeta.register()} の呼び出しごとに、トークンは変更されます。


Added in version 3.4.

@end deffn

@geindex update_abstractmethods() (abc モジュール)
@anchor{library/abc abc update_abstractmethods}@anchor{49cc}
@deffn {の関数} abc.update_abstractmethods (cls)

A function to recalculate an abstract class's abstraction status. This
function should be called if a class's abstract methods have been
implemented or changed after it was created. Usually, this function should
be called from within a class decorator.

Returns `cls', to allow usage as a class decorator.

If `cls' is not an instance of @ref{111c,,ABCMeta}, does nothing.

@cartouche
@quotation 注釈 
This function assumes that `cls''s superclasses are already updated.
It does not update any subclasses.
@end quotation
@end cartouche


Added in version 3.10.

@end deffn

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node atexit --- 終了ハンドラー,traceback --- スタックトレースの表示または取得,abc --- 抽象基底クラス,Python ランタイムサービス
@anchor{library/atexit doc}@anchor{49cd}@anchor{library/atexit atexit-exit-handlers}@anchor{49ce}@anchor{library/atexit module-atexit}@anchor{d}@anchor{library/atexit translation-repo}@anchor{49cf}
@subsection @code{atexit} --- 終了ハンドラー


@geindex module; atexit


__________________________________________________________________


The @code{atexit} module defines functions to register and unregister cleanup
functions.  Functions thus registered are automatically executed upon normal
interpreter termination.  @code{atexit} runs these functions in the `reverse'
order in which they were registered; if you register @code{A}, @code{B}, and @code{C},
at interpreter termination time they will be run in the order @code{C}, @code{B},
@code{A}.

`注意:' このモジュールを使用して登録された関数は、プログラムが Python が扱わないシグナルによって kill された場合、Python 内部で致命的なエラーが検出された場合、あるいは @ref{26f9,,os._exit()} が呼び出された場合は実行されません。

`注意:' クリーンアップ関数内からの関数の登録・登録解除効果は定義されていません。


バージョン 3.7 で変更: C-API のサブインタープリタで使われているとき、登録された関数は登録先のインタープリタのローカルな関数になります。


@geindex register() (atexit モジュール)
@anchor{library/atexit atexit register}@anchor{a7e}
@deffn {の関数} atexit.register (func, *args, **kwargs)

`func' を終了時に実行する関数として登録します。`func' に渡す引数は @ref{a7e,,register()} の引数として指定しなければなりません。同じ関数を同じ引数で複数回登録できます。

通常のプログラムの終了時、例えば @ref{277,,sys.exit()} が呼び出されるとき、あるいは、メインモジュールの実行が完了したときに、登録された全ての関数を、最後に登録されたものから順に呼び出します。通常、より低レベルのモジュールはより高レベルのモジュールより前に import されるので、後で後始末が行われるという仮定に基づいています。

終了ハンドラの実行中に例外が発生すると、(@ref{f3c,,SystemExit} 以外の場合は)トレースバックを表示して、例外の情報を保存します。全ての終了ハンドラに動作するチャンスを与えた後に、最後に送出された例外を再送出します。

この関数は `func' を返し、これをデコレータとして利用できます。

@cartouche
@quotation 警告 
登録された関数から新しいスレッドを開始したり、 @ref{4b5,,os.fork()} を呼び出したりすると、メインの Python ランタイムスレッドがスレッド状態を開放する一方で、内部の @ref{f3,,threading} ルーチンや新しいプロセスがそのスレッド状態を使用しようと試みる競合が発生します。これはクリーンなシャットダウンではなく、クラッシュにつながる恐れがあります。
@end quotation
@end cartouche


バージョン 3.12 で変更: 登録された関数から新しいスレッドの開始または新しいプロセスの @ref{4b5,,os.fork()} が試みられた場合は、 @ref{244,,RuntimeError} が発生するようになりました。

@end deffn

@geindex unregister() (atexit モジュール)
@anchor{library/atexit atexit unregister}@anchor{177f}
@deffn {の関数} atexit.unregister (func)

Remove `func' from the list of functions to be run at interpreter shutdown.
@ref{177f,,unregister()} silently does nothing if `func' was not previously
registered.  If `func' has been registered more than once, every occurrence
of that function in the @code{atexit} call stack will be removed.  Equality
comparisons (@code{==}) are used internally during unregistration, so function
references do not need to have matching identities.
@end deffn


@subsubheading 参考



@table @asis

@item @ref{bf,,readline} モジュール

Useful example of @code{atexit} to read and write @ref{bf,,readline} history
files.
@end table


@menu
* atexit Example:: 

@end menu

@node atexit Example,,,atexit --- 終了ハンドラー
@anchor{library/atexit atexit-example}@anchor{49d0}@anchor{library/atexit id1}@anchor{49d1}
@subsubsection @code{atexit} Example


次の簡単な例では、あるモジュールを import した時にカウンタを初期化しておき、プログラムが終了するときにアプリケーションがこのモジュールを明示的に呼び出さなくてもカウンタが更新されるようにする方法を示しています。

@example
try:
    with open('counterfile') as infile:
        _count = int(infile.read())
except FileNotFoundError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    with open('counterfile', 'w') as outfile:
        outfile.write('%d' % _count)

import atexit

atexit.register(savecounter)
@end example

@ref{a7e,,register()} に指定した位置引数とキーワード引数は登録した関数を呼び出す際に渡されます:

@example
def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
@end example

@ref{93a,,デコレータ} として利用する例:

@example
import atexit

@@atexit.register
def goodbye():
    print('You are now leaving the Python sector.')
@end example

デコレータとして利用できるのは、その関数が引数なしで呼び出された場合に限られます。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node traceback --- スタックトレースの表示または取得,__future__ --- future 文の定義,atexit --- 終了ハンドラー,Python ランタイムサービス
@anchor{library/traceback doc}@anchor{49d2}@anchor{library/traceback module-traceback}@anchor{104}@anchor{library/traceback traceback-print-or-retrieve-a-stack-traceback}@anchor{49d3}@anchor{library/traceback translation-repo}@anchor{49d4}
@subsection @code{traceback} --- スタックトレースの表示または取得


@geindex module; traceback

`ソースコード:' Lib/traceback.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/traceback.py}


__________________________________________________________________


This module provides a standard interface to extract, format and print
stack traces of Python programs. It is more flexible than the
interpreter's default traceback display, and therefore makes it
possible to configure certain aspects of the output. Finally,
it contains a utility for capturing enough information about an
exception to print it later, without the need to save a reference
to the actual exception. Since exceptions can be the roots of large
objects graph, this utility can significantly improve
memory management.

@geindex object;traceback

The module uses @ref{cec,,traceback objects} --- these are
objects of type @ref{cea,,types.TracebackType},
which are assigned to the @ref{14de,,__traceback__} field of
@ref{7d6,,BaseException} instances.


@subsubheading 参考



@table @asis

@item @ref{5c,,faulthandler} モジュール

Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal.

@item @ref{aa,,pdb} モジュール

Interactive source code debugger for Python programs.
@end table


The module's API can be divided into two parts:


@itemize *

@item 
Module-level functions offering basic functionality, which are useful for interactive
inspection of exceptions and tracebacks.

@item 
@ref{563,,TracebackException} class and its helper classes
@ref{1083,,StackSummary} and @ref{1084,,FrameSummary}. These offer both more
flexibility in the output generated and the ability to store the information
necessary for later formatting without holding references to actual exception
and traceback objects.
@end itemize


Added in version 3.13: Output is colorized by default and can be
@ref{1b7,,controlled using environment variables}.


@menu
* モジュールレベルの関数: モジュールレベルの関数<2>. 
* TracebackException オブジェクト:: 
* StackSummary オブジェクト:: 
* FrameSummary オブジェクト:: 
* Examples of Using the Module-Level Functions:: 
* Examples of Using TracebackException:: 

@end menu

@node モジュールレベルの関数<2>,TracebackException オブジェクト,,traceback --- スタックトレースの表示または取得
@anchor{library/traceback module-level-functions}@anchor{49d5}
@subsubsection モジュールレベルの関数


@geindex print_tb() (traceback モジュール)
@anchor{library/traceback traceback print_tb}@anchor{1085}
@deffn {の関数} traceback.print_tb (tb, limit=None, file=None)

Print up to `limit' stack trace entries from
@ref{cec,,traceback object} `tb' (starting
from the caller's frame) if `limit' is positive.  Otherwise, print the last
@code{abs(limit)} entries.  If `limit' is omitted or @code{None}, all entries are
printed.  If `file' is omitted or @code{None}, the output goes to
@ref{b33,,sys.stderr}; otherwise it should be an open
@ref{13db,,file} or @ref{17ac,,file-like object} to
receive the output.

@cartouche
@quotation 注釈 
The meaning of the `limit' parameter is different than the meaning
of @ref{1944,,sys.tracebacklimit}. A negative `limit' value corresponds to
a positive value of @code{sys.tracebacklimit}, whereas the behaviour of
a positive `limit' value cannot be achieved with
@code{sys.tracebacklimit}.
@end quotation
@end cartouche


バージョン 3.5 で変更: 負の `limit' がサポートされました。

@end deffn

@geindex print_exception() (traceback モジュール)
@anchor{library/traceback traceback print_exception}@anchor{a4f}
@deffn {の関数} traceback.print_exception (exc, /[, value, tb], limit=None, file=None, chain=True)

@ref{cec,,トレースバックオブジェクト} `tb' から例外の情報とスタックトレースの項目を `file' に出力します。
この関数は以下の点で @ref{1085,,print_tb()} と異なります:


@itemize *

@item 
`tb' が @code{None} でない場合ヘッダ @code{Traceback (most recent call last):} を出力します

@item 
スタックトレースの後に例外タイプと `value' を出力します
@end itemize

@geindex ^ (キャレット);marker


@itemize *

@item 
`type(value)' が @ref{18e,,SyntaxError} であり、 `value' が適切な形式を持っていれば、そのエラーのおおよその位置を示すマークと共にシンタックスエラーが発生した行が表示されます。
@end itemize

Since Python 3.10, instead of passing `value' and `tb', an exception object
can be passed as the first argument. If `value' and `tb' are provided, the
first argument is ignored in order to provide backwards compatibility.

オプション引数 `limit' の意味は  @ref{1085,,print_tb()} のものと同じです。
`chain' が真の場合 (デフォルト)、連鎖した例外 (例外の @ref{14e0,,__cause__} か @ref{14df,,__context__} 属性) も出力されます。
これはインタープリタ自身が処理されていない例外を出力するときと同じです。


バージョン 3.5 で変更: 引数 `etype' は無視され、 `value' の型から推論されます。



バージョン 3.10 で変更: The `etype' parameter has been renamed to `exc' and is now
positional-only.

@end deffn

@geindex print_exc() (traceback モジュール)
@anchor{library/traceback traceback print_exc}@anchor{1c24}
@deffn {の関数} traceback.print_exc (limit=None, file=None, chain=True)

@code{print_exception(sys.exception(), limit=limit, file=file, chain=chain)} の省略表現です。
@end deffn

@geindex print_last() (traceback モジュール)
@anchor{library/traceback traceback print_last}@anchor{49d6}
@deffn {の関数} traceback.print_last (limit=None, file=None, chain=True)

@code{print_exception(sys.last_exc, limit=limit, file=file, chain=chain)} の省略表現です。
一般に、例外が対話的なプロンプトに達した後にのみ機能します (@ref{6e5,,sys.last_exc} 参照)。
@end deffn

@geindex print_stack() (traceback モジュール)
@anchor{library/traceback traceback print_stack}@anchor{1086}
@deffn {の関数} traceback.print_stack (f=None, limit=None, file=None)

`limit' が正の場合、最大 `limit' 個のスタックトレース項目 (呼び出し地点から開始) を出力します。 そうでない場合、最新の @code{abs(limit)} 個を出力します。 `limit' が省略されるか @code{None} の場合、すべての項目が出力されます。オプションの `f' 引数は、開始する @ref{8ef,,スタックフレーム} を指定するために用いることができます。オプションの `file' 引数は @ref{1085,,print_tb()} の `file' 引数と同様の意味を持っています。


バージョン 3.5 で変更: 負の `limit' がサポートされました。

@end deffn

@geindex extract_tb() (traceback モジュール)
@anchor{library/traceback traceback extract_tb}@anchor{49d7}
@deffn {の関数} traceback.extract_tb (tb, limit=None)

@ref{cec,,トレースバックオブジェクト} `tb' から取り出された "前処理済み" スタックトレース項目のリストを表す @ref{1083,,StackSummary} オブジェクトを返します。これはスタックトレースの異なる書式化を行うために役に立ちます。オプションの `limit' 引数は @ref{1085,,print_tb()} の `limit' 引数と同様の意味を持っています。 "前処理済み" スタックトレース項目は 属性 @ref{49d8,,filename}, @ref{49d9,,lineno}, @ref{49da,,name}, および @ref{49db,,line} を含む @ref{1084,,FrameSummary} オブジェクトで、スタックトレースに対して通常出力される情報を表しています。
@end deffn

@geindex extract_stack() (traceback モジュール)
@anchor{library/traceback traceback extract_stack}@anchor{49dc}
@deffn {の関数} traceback.extract_stack (f=None, limit=None)

現在の @ref{8ef,,スタックフレーム} から生のトレースバックを取り出します。戻り値は @ref{49d7,,extract_tb()} と同じ形式です。オプションの `f' と `limit' 引数は @ref{1086,,print_stack()} と同じ意味を持ちます。
@end deffn

@geindex print_list() (traceback モジュール)
@anchor{library/traceback traceback print_list}@anchor{18ef}
@deffn {の関数} traceback.print_list (extracted_list, file=None)

Print the list of tuples as returned by @ref{49d7,,extract_tb()} or
@ref{49dc,,extract_stack()} as a formatted stack trace to the given file.
If `file' is @code{None}, the output is written to @ref{b33,,sys.stderr}.
@end deffn

@geindex format_list() (traceback モジュール)
@anchor{library/traceback traceback format_list}@anchor{49dd}
@deffn {の関数} traceback.format_list (extracted_list)

@ref{49d7,,extract_tb()} または @ref{49dc,,extract_stack()} が返すタプルのリストまたは @ref{1084,,FrameSummary} オブジェクトが与えられると、出力の準備を整えた文字列のリストを返します。結果として生じるリストの中の各文字列は、引数リストの中の同じインデックスの要素に対応します。各文字列は末尾に改行が付いています。さらに、ソーステキスト行が @code{None} でないそれらの要素に対しては、文字列は内部に改行を含んでいるかもしれません。
@end deffn

@geindex format_exception_only() (traceback モジュール)
@anchor{library/traceback traceback format_exception_only}@anchor{a4e}
@deffn {の関数} traceback.format_exception_only (exc, /[, value], *, show_group=False)

Format the exception part of a traceback using an exception value such as
given by @ref{6e7,,sys.last_value}.  The return value is a list of strings, each
ending in a newline.  The list contains the exception's message, which is
normally a single string; however, for @ref{18e,,SyntaxError} exceptions, it
contains several lines that (when printed) display detailed information
about where the syntax error occurred. Following the message, the list
contains the exception's @ref{26e4,,notes}.

Since Python 3.10, instead of passing `value', an exception object
can be passed as the first argument.  If `value' is provided, the first
argument is ignored in order to provide backwards compatibility.

When `show_group' is @code{True}, and the exception is an instance of
@ref{566,,BaseExceptionGroup}, the nested exceptions are included as
well, recursively, with indentation relative to their nesting depth.


バージョン 3.10 で変更: The `etype' parameter has been renamed to `exc' and is now
positional-only.



バージョン 3.11 で変更: The returned list now includes any
@ref{26e4,,notes} attached to the exception.



バージョン 3.13 で変更: `show_group' 引数が追加されました。

@end deffn

@geindex format_exception() (traceback モジュール)
@anchor{library/traceback traceback format_exception}@anchor{a4d}
@deffn {の関数} traceback.format_exception (exc, /[, value, tb], limit=None, chain=True)

スタックトレースと例外情報を書式化します。引数は @ref{a4f,,print_exception()} の対応する引数と同じ意味を持ちます。戻り値は文字列のリストで、それぞれの文字列は改行で終わり、そのいくつかは内部に改行を含みます。これらの行が連結されて出力される場合は、厳密に @ref{a4f,,print_exception()} と同じテキストが出力されます。


バージョン 3.5 で変更: 引数 `etype' は無視され、 `value' の型から推論されます。



バージョン 3.10 で変更: This function's behavior and signature were modified to match
@ref{a4f,,print_exception()}.

@end deffn

@geindex format_exc() (traceback モジュール)
@anchor{library/traceback traceback format_exc}@anchor{49de}
@deffn {の関数} traceback.format_exc (limit=None, chain=True)

これは、@code{print_exc(limit)} に似ていますが、ファイルに出力する代わりに文字列を返します。
@end deffn

@geindex format_tb() (traceback モジュール)
@anchor{library/traceback traceback format_tb}@anchor{48a1}
@deffn {の関数} traceback.format_tb (tb, limit=None)

@code{format_list(extract_tb(tb, limit))} の省略表現です。
@end deffn

@geindex format_stack() (traceback モジュール)
@anchor{library/traceback traceback format_stack}@anchor{49df}
@deffn {の関数} traceback.format_stack (f=None, limit=None)

@code{format_list(extract_stack(f, limit))} の省略表現です。
@end deffn

@geindex clear_frames() (traceback モジュール)
@anchor{library/traceback traceback clear_frames}@anchor{11d6}
@deffn {の関数} traceback.clear_frames (tb)

Clears the local variables of all the stack frames in a
@ref{cec,,traceback} `tb'
by calling the @ref{585,,clear()} method of each
@ref{8ef,,frame object}.


Added in version 3.4.

@end deffn

@geindex walk_stack() (traceback モジュール)
@anchor{library/traceback traceback walk_stack}@anchor{1081}
@deffn {の関数} traceback.walk_stack (f)

Walk a stack following @ref{98f,,f.f_back} from the given frame,
yielding the frame
and line number for each frame. If `f' is @code{None}, the current stack is
used. This helper is used with @ref{49e0,,StackSummary.extract()}.


Added in version 3.5.



バージョン 3.14 で変更: This function previously returned a generator that would walk the stack
when first iterated over. The generator returned now is the state of the
stack when @code{walk_stack} is called.

@end deffn

@geindex walk_tb() (traceback モジュール)
@anchor{library/traceback traceback walk_tb}@anchor{1082}
@deffn {の関数} traceback.walk_tb (tb)

Walk a traceback following @ref{ceb,,tb_next} yielding the frame and
line number
for each frame. This helper is used with @ref{49e0,,StackSummary.extract()}.


Added in version 3.5.

@end deffn

@node TracebackException オブジェクト,StackSummary オブジェクト,モジュールレベルの関数<2>,traceback --- スタックトレースの表示または取得
@anchor{library/traceback tracebackexception-objects}@anchor{49e1}
@subsubsection @code{TracebackException} オブジェクト



Added in version 3.5.


@code{TracebackException} objects are created from actual exceptions to
capture data for later printing.  They offer a more lightweight method of
storing this information by avoiding holding references to
@ref{cec,,traceback} and @ref{8ef,,frame} objects.
In addition, they expose more options to configure the output compared to
the module-level functions described above.

@geindex TracebackException (traceback のクラス)
@anchor{library/traceback traceback TracebackException}@anchor{563}
@deffn {クラス} traceback.TracebackException (exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, compact=False, max_group_width=15, max_group_depth=10)

Capture an exception for later rendering. The meaning of `limit',
`lookup_lines' and `capture_locals' are as for the @ref{1083,,StackSummary}
class.

If `compact' is true, only data that is required by
@code{TracebackException}'s @ref{199,,format()} method
is saved in the class attributes. In particular, the
@ref{49e2,,__context__} field is calculated only if @ref{49e3,,__cause__} is
@code{None} and @ref{49e4,,__suppress_context__} is false.

局所変数がキャプチャされたとき、それらはトレースバックに表示されることに注意してください。

`max_group_width' and `max_group_depth' control the formatting of exception
groups (see @ref{566,,BaseExceptionGroup}). The depth refers to the nesting
level of the group, and the width refers to the size of a single exception
group's exceptions array. The formatted output is truncated when either
limit is exceeded.


バージョン 3.10 で変更: `compact' 引数が追加されました。



バージョン 3.11 で変更: `max_group_width' と `max_group_depth' 引数が追加されました。


@geindex __cause__ (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException __cause__}@anchor{49e3}
@deffn {の属性} __cause__

元々の @ref{14e0,,__cause__} の @code{TracebackException}。
@end deffn

@geindex __context__ (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException __context__}@anchor{49e2}
@deffn {の属性} __context__

元々の @ref{14df,,__context__} の @code{TracebackException}。
@end deffn

@geindex exceptions (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException exceptions}@anchor{49e5}
@deffn {の属性} exceptions

If @code{self} represents an @ref{4d2,,ExceptionGroup}, this field holds a list of
@code{TracebackException} instances representing the nested exceptions.
Otherwise it is @code{None}.


Added in version 3.11.

@end deffn

@geindex __suppress_context__ (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException __suppress_context__}@anchor{49e4}
@deffn {の属性} __suppress_context__

元々の例外からの @ref{2514,,__suppress_context__}。
@end deffn

@geindex __notes__ (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException __notes__}@anchor{49e6}
@deffn {の属性} __notes__

The @ref{26e4,,__notes__} value from the original exception,
or @code{None}
if the exception does not have any notes. If it is not @code{None}
is it formatted in the traceback after the exception string.


Added in version 3.11.

@end deffn

@geindex stack (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException stack}@anchor{49e7}
@deffn {の属性} stack

トレースバックを表す @ref{1083,,StackSummary}。
@end deffn

@geindex exc_type (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException exc_type}@anchor{564}
@deffn {の属性} exc_type

元々のトレースバックのクラス。


バージョン 3.13 で非推奨.

@end deffn

@geindex exc_type_str (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException exc_type_str}@anchor{562}
@deffn {の属性} exc_type_str

String display of the class of the original exception.


Added in version 3.13.

@end deffn

@geindex filename (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException filename}@anchor{49e8}
@deffn {の属性} filename

構文エラー用 - エラーが発生したファイルの名前。
@end deffn

@geindex lineno (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException lineno}@anchor{49e9}
@deffn {の属性} lineno

構文エラー用 - エラーが発生した行番号。
@end deffn

@geindex end_lineno (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException end_lineno}@anchor{49ea}
@deffn {の属性} end_lineno

For syntax errors - the end line number where the error occurred.
Can be @code{None} if not present.


Added in version 3.10.

@end deffn

@geindex text (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException text}@anchor{49eb}
@deffn {の属性} text

構文エラー用 - エラーが発生したテクスト。
@end deffn

@geindex offset (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException offset}@anchor{49ec}
@deffn {の属性} offset

構文エラー用 - エラーが発生したテクストへのオフセット。
@end deffn

@geindex end_offset (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException end_offset}@anchor{49ed}
@deffn {の属性} end_offset

For syntax errors - the end offset into the text where the error occurred.
Can be @code{None} if not present.


Added in version 3.10.

@end deffn

@geindex msg (traceback.TracebackException の属性)
@anchor{library/traceback traceback TracebackException msg}@anchor{49ee}
@deffn {の属性} msg

構文エラー用 - コンパイラのエラーメッセージ。
@end deffn

@geindex from_exception() (traceback.TracebackException のクラスメソッド)
@anchor{library/traceback traceback TracebackException from_exception}@anchor{49ef}
@deffn {メソッド} classmethod from_exception (exc, *, limit=None, lookup_lines=True, capture_locals=False)

後のレンダリングのために例外をキャプチャします。
`limit'、`lookup_lines'、`capture_locals' は @ref{1083,,StackSummary} class のものです。

局所変数がキャプチャされたとき、それらはトレースバックに表示されることに注意してください。
@end deffn

@geindex print() (traceback.TracebackException のメソッド)
@anchor{library/traceback traceback TracebackException print}@anchor{8b3}
@deffn {メソッド} print (*, file=None, chain=True)

Print to `file' (default @code{sys.stderr}) the exception information returned by
@ref{199,,format()}.


Added in version 3.11.

@end deffn

@geindex format() (traceback.TracebackException のメソッド)
@anchor{library/traceback traceback TracebackException format}@anchor{49f0}
@deffn {メソッド} format (*, chain=True)

例外を書式化します。

`chain' が @code{True} でない場合 @ref{49e3,,__cause__} と @ref{49e2,,__context__} は書式化されません。

返り値は文字列のジェネレータで、それぞれ改行で終わりますが、内部に改行を持つものもあります。
@ref{a4f,,print_exception()} はこのメソッドのラッパで、単にファイルに出力します。
@end deffn

@geindex format_exception_only() (traceback.TracebackException のメソッド)
@anchor{library/traceback traceback TracebackException format_exception_only}@anchor{565}
@deffn {メソッド} format_exception_only (*, show_group=False)

トレースバックの例外部を書式化します。

返り値は文字列のジェネレータで、それぞれ改行で終わります。

When `show_group' is @code{False}, the generator emits the exception's
message followed by its notes (if it has any). The exception message
is normally a single string; however, for @ref{18e,,SyntaxError} exceptions,
it consists of several lines that (when printed) display detailed
information about where the syntax error occurred.

When `show_group' is @code{True}, and the exception is an instance of
@ref{566,,BaseExceptionGroup}, the nested exceptions are included as
well, recursively, with indentation relative to their nesting depth.


バージョン 3.11 で変更: The exception's @ref{26e4,,notes} are now
included in the output.



バージョン 3.13 で変更: `show_group' パラメータが追加されました。

@end deffn
@end deffn

@node StackSummary オブジェクト,FrameSummary オブジェクト,TracebackException オブジェクト,traceback --- スタックトレースの表示または取得
@anchor{library/traceback stacksummary-objects}@anchor{49f1}
@subsubsection @code{StackSummary} オブジェクト



Added in version 3.5.


@code{StackSummary} オブジェクトは書式化の準備ができているコールスタックを表します。

@geindex StackSummary (traceback のクラス)
@anchor{library/traceback traceback StackSummary}@anchor{1083}
@deffn {クラス} traceback.StackSummary

@geindex extract() (traceback.StackSummary のクラスメソッド)
@anchor{library/traceback traceback StackSummary extract}@anchor{49e0}
@deffn {メソッド} classmethod extract (frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)

ジェネレータ (例えば @ref{1081,,walk_stack()} や @ref{1082,,walk_tb()} が返すもの) から @code{StackSummary} を構築します。

If `limit' is supplied, only this many frames are taken from `frame_gen'.
If `lookup_lines' is @code{False}, the returned @ref{1084,,FrameSummary}
objects will not have read their lines in yet, making the cost of
creating the @code{StackSummary} cheaper (which may be valuable if it
may not actually get formatted). If `capture_locals' is @code{True} the
local variables in each @code{FrameSummary} are captured as object
representations.


バージョン 3.12 で変更: Exceptions raised from @ref{1c1,,repr()} on a local variable (when
`capture_locals' is @code{True}) are no longer propagated to the caller.

@end deffn

@geindex from_list() (traceback.StackSummary のクラスメソッド)
@anchor{library/traceback traceback StackSummary from_list}@anchor{49f2}
@deffn {メソッド} classmethod from_list (a_list)

Construct a @code{StackSummary} object from a supplied list of
@ref{1084,,FrameSummary} objects or old-style list of tuples.  Each tuple
should be a 4-tuple with `filename', `lineno', `name', `line' as the
elements.
@end deffn

@geindex format() (traceback.StackSummary のメソッド)
@anchor{library/traceback traceback StackSummary format}@anchor{49f3}
@deffn {メソッド} format ()

Returns a list of strings ready for printing.  Each string in the
resulting list corresponds to a single @ref{8ef,,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.

@end deffn

@geindex format_frame_summary() (traceback.StackSummary のメソッド)
@anchor{library/traceback traceback StackSummary format_frame_summary}@anchor{8b2}
@deffn {メソッド} format_frame_summary (frame_summary)

Returns a string for printing one of the @ref{8ef,,frames}
involved in the stack.
This method is called for each @ref{1084,,FrameSummary} object to be
printed by @ref{49f3,,StackSummary.format()}. If it returns @code{None}, the
frame is omitted from the output.


Added in version 3.11.

@end deffn
@end deffn

@node FrameSummary オブジェクト,Examples of Using the Module-Level Functions,StackSummary オブジェクト,traceback --- スタックトレースの表示または取得
@anchor{library/traceback framesummary-objects}@anchor{49f4}
@subsubsection @code{FrameSummary} オブジェクト



Added in version 3.5.


A @code{FrameSummary} object represents a single @ref{8ef,,frame}
in a @ref{cec,,traceback}.

@geindex FrameSummary (traceback のクラス)
@anchor{library/traceback traceback FrameSummary}@anchor{1084}
@deffn {クラス} traceback.FrameSummary (filename, lineno, name, *, lookup_line=True, locals=None, line=None, end_lineno=None, colno=None, end_colno=None)

Represents a single @ref{8ef,,frame} in the
@ref{cec,,traceback} or stack that is being formatted
or printed. It may optionally have a stringified version of the frame's
locals included in it. If `lookup_line' is @code{False}, the source code is not
looked up until the @code{FrameSummary} has the @ref{49db,,line}
attribute accessed (which also happens when casting it to a @ref{614,,tuple}).
@ref{49db,,line} may be directly provided, and will prevent line
lookups happening at all. `locals' is an optional local variable
mapping, and if supplied the variable representations are stored in the
summary for later display.

@code{FrameSummary} インスタンスは以下の属性を持ちます:

@geindex filename (traceback.FrameSummary の属性)
@anchor{library/traceback traceback FrameSummary filename}@anchor{49d8}
@deffn {の属性} filename

The filename of the source code for this frame. Equivalent to accessing
@ref{1585,,f.f_code.co_filename} on a
@ref{8ef,,frame object} `f'.
@end deffn

@geindex lineno (traceback.FrameSummary の属性)
@anchor{library/traceback traceback FrameSummary lineno}@anchor{49d9}
@deffn {の属性} lineno

The line number of the source code for this frame.
@end deffn

@geindex name (traceback.FrameSummary の属性)
@anchor{library/traceback traceback FrameSummary name}@anchor{49da}
@deffn {の属性} name

Equivalent to accessing @ref{2385,,f.f_code.co_name} on
a @ref{8ef,,frame object} `f'.
@end deffn

@geindex line (traceback.FrameSummary の属性)
@anchor{library/traceback traceback FrameSummary line}@anchor{49db}
@deffn {の属性} line

A string representing the source code for this frame, with leading and
trailing whitespace stripped.
If the source is not available, it is @code{None}.
@end deffn

@geindex end_lineno (traceback.FrameSummary の属性)
@anchor{library/traceback traceback FrameSummary end_lineno}@anchor{49f5}
@deffn {の属性} end_lineno

The last line number of the source code for this frame.
By default, it is set to @code{lineno} and indexation starts from 1.


バージョン 3.13 で変更: The default value changed from @code{None} to @code{lineno}.

@end deffn

@geindex colno (traceback.FrameSummary の属性)
@anchor{library/traceback traceback FrameSummary colno}@anchor{49f6}
@deffn {の属性} colno

The column number of the source code for this frame.
By default, it is @code{None} and indexation starts from 0.
@end deffn

@geindex end_colno (traceback.FrameSummary の属性)
@anchor{library/traceback traceback FrameSummary end_colno}@anchor{49f7}
@deffn {の属性} end_colno

The last column number of the source code for this frame.
By default, it is @code{None} and indexation starts from 0.
@end deffn
@end deffn

@node Examples of Using the Module-Level Functions,Examples of Using TracebackException,FrameSummary オブジェクト,traceback --- スタックトレースの表示または取得
@anchor{library/traceback examples-of-using-the-module-level-functions}@anchor{49f8}@anchor{library/traceback traceback-example}@anchor{49f9}
@subsubsection Examples of Using the Module-Level Functions


この簡単な例では基本的な read-eval-print ループを実装しています。標準的な Python の対話インタープリタループに似ていますが、 Python のものより便利ではありません。インタープリタループのより完全な実装については、 @ref{1b,,code} モジュールを参照してください。

@example
import sys, traceback

def run_user_code(envdir):
    source = input(">>> ")
    try:
        exec(source, envdir)
    except Exception:
        print("Exception in user code:")
        print("-"*60)
        traceback.print_exc(file=sys.stdout)
        print("-"*60)

envdir = @{@}
while True:
    run_user_code(envdir)
@end example

次の例は例外とトレースバックの出力並びに形式が異なることを示します:

@example
import sys, traceback

def lumberjack():
    bright_side_of_life()

def bright_side_of_life():
    return tuple()[0]

try:
    lumberjack()
except IndexError as exc:
    print("*** print_tb:")
    traceback.print_tb(exc.__traceback__, limit=1, file=sys.stdout)
    print("*** print_exception:")
    traceback.print_exception(exc, 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:")
    print(repr(traceback.format_exception(exc)))
    print("*** extract_tb:")
    print(repr(traceback.extract_tb(exc.__traceback__)))
    print("*** format_tb:")
    print(repr(traceback.format_tb(exc.__traceback__)))
    print("*** tb_lineno:", exc.__traceback__.tb_lineno)
@end example

この例の出力は次のようになります:

@example
*** print_tb:
  File "<doctest...>", line 10, in <module>
    lumberjack()
    ~~~~~~~~~~^^
*** print_exception:
Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
    ~~~~~~~~~~^^
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_life()
    ~~~~~~~~~~~~~~~~~~~^^
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_life()
    ~~~~~~~~~~~~~~~~~~~^^
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 default[0]>", line 10, in <module>\n    lumberjack()\n    ~~~~~~~~~~^^\n',
 '  File "<doctest default[0]>", line 4, in lumberjack\n    bright_side_of_life()\n    ~~~~~~~~~~~~~~~~~~~^^\n',
 '  File "<doctest default[0]>", line 7, in bright_side_of_life\n    return tuple()[0]\n           ~~~~~~~^^^\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_life>]
*** format_tb:
['  File "<doctest default[0]>", line 10, in <module>\n    lumberjack()\n    ~~~~~~~~~~^^\n',
 '  File "<doctest default[0]>", line 4, in lumberjack\n    bright_side_of_life()\n    ~~~~~~~~~~~~~~~~~~~^^\n',
 '  File "<doctest default[0]>", line 7, in bright_side_of_life\n    return tuple()[0]\n           ~~~~~~~^^^\n']
*** tb_lineno: 10
@end example

次の例は、スタックの print と format の違いを示しています:

@example
>>> import traceback
>>> def another_function():
...     lumberstack()
...
>>> def lumberstack():
...     traceback.print_stack()
...     print(repr(traceback.extract_stack()))
...     print(repr(traceback.format_stack()))
...
>>> another_function()
  File "<doctest>", line 10, in <module>
    another_function()
  File "<doctest>", line 3, in another_function
    lumberstack()
  File "<doctest>", line 6, in lumberstack
    traceback.print_stack()
[('<doctest>', 10, '<module>', 'another_function()'),
 ('<doctest>', 3, 'another_function', 'lumberstack()'),
 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
['  File "<doctest>", line 10, in <module>\n    another_function()\n',
 '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
 '  File "<doctest>", line 8, in lumberstack\n    print(repr(traceback.format_stack()))\n']
@end example

最後の例は、残りの幾つかの関数のデモをします:

@example
>>> import traceback
>>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
 '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
>>> an_error = IndexError('tuple index out of range')
>>> traceback.format_exception_only(an_error)
['IndexError: tuple index out of range\n']
@end example

@node Examples of Using TracebackException,,Examples of Using the Module-Level Functions,traceback --- スタックトレースの表示または取得
@anchor{library/traceback examples-of-using-tracebackexception}@anchor{49fa}
@subsubsection Examples of Using @code{TracebackException}


With the helper class, we have more options:

@example
>>> import sys
>>> from traceback import TracebackException
>>>
>>> def lumberjack():
...     bright_side_of_life()
...
>>> def bright_side_of_life():
...     t = "bright", "side", "of", "life"
...     return t[5]
...
>>> try:
...     lumberjack()
... except IndexError as e:
...     exc = e
...
>>> try:
...     try:
...         lumberjack()
...     except:
...         1/0
... except Exception as e:
...     chained_exc = e
...
>>> # limit works as with the module-level functions
>>> TracebackException.from_exception(exc, limit=-2).print()
Traceback (most recent call last):
  File "<python-input-1>", line 6, in lumberjack
    bright_side_of_life()
    ~~~~~~~~~~~~~~~~~~~^^
  File "<python-input-1>", line 10, in bright_side_of_life
    return t[5]
           ~^^^
IndexError: tuple index out of range

>>> # capture_locals adds local variables in frames
>>> TracebackException.from_exception(exc, limit=-2, capture_locals=True).print()
Traceback (most recent call last):
  File "<python-input-1>", line 6, in lumberjack
    bright_side_of_life()
    ~~~~~~~~~~~~~~~~~~~^^
  File "<python-input-1>", line 10, in bright_side_of_life
    return t[5]
           ~^^^
    t = ("bright", "side", "of", "life")
IndexError: tuple index out of range

>>> # The *chain* kwarg to print() controls whether chained
>>> # exceptions are displayed
>>> TracebackException.from_exception(chained_exc).print()
Traceback (most recent call last):
  File "<python-input-19>", line 4, in <module>
    lumberjack()
    ~~~~~~~~~~^^
  File "<python-input-8>", line 7, in lumberjack
    bright_side_of_life()
    ~~~~~~~~~~~~~~~~~~~^^
  File "<python-input-8>", line 11, in bright_side_of_life
    return t[5]
           ~^^^
IndexError: tuple index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<python-input-19>", line 6, in <module>
    1/0
    ~^~
ZeroDivisionError: division by zero

>>> TracebackException.from_exception(chained_exc).print(chain=False)
Traceback (most recent call last):
  File "<python-input-19>", line 6, in <module>
    1/0
    ~^~
ZeroDivisionError: division by zero
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node __future__ --- future 文の定義,gc --- ガベージコレクターインターフェース,traceback --- スタックトレースの表示または取得,Python ランタイムサービス
@anchor{library/__future__ doc}@anchor{49fb}@anchor{library/__future__ future-future-statement-definitions}@anchor{49fc}@anchor{library/__future__ module-__future__}@anchor{0}@anchor{library/__future__ translation-repo}@anchor{49fd}
@subsection @code{__future__} --- future 文の定義


@geindex module; __future__

`ソースコード:' Lib/__future__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/__future__.py}


__________________________________________________________________


@code{from __future__ import feature} の形式でのインポートは @ref{45d,,future 文} の定義と呼ばれています。これらは特殊なケースで、 Python の新機能が標準になるリリースの前に Python コンパイラーが future 文を含むモジュールで Python の新機能を使用できるようにします。

While these future statements are given additional special meaning by the
Python compiler, they are still executed like any other import statement and
the @code{__future__} exists and is handled by the import system the same way
any other Python module would be. This design serves three purposes:


@itemize *

@item 
import 文を解析する既存のツールを混乱させることを避け、インポートしようとしているモジュールを見つけられるようにするため。

@item 
To document when incompatible changes were introduced, and when they will be
--- or were --- made mandatory.  This is a form of executable documentation, and
can be inspected programmatically via importing @code{__future__} and examining
its contents.

@item 
To ensure that @ref{45d,,future statements} run under releases prior to
Python 2.1 at least yield runtime exceptions (the import of @code{__future__}
will fail, because there was no module of that name prior to 2.1).
@end itemize

@menu
* モジュールコンテンツ: モジュールコンテンツ<5>. 

@end menu

@node モジュールコンテンツ<5>,,,__future__ --- future 文の定義
@anchor{library/__future__ module-contents}@anchor{49fe}
@subsubsection モジュールコンテンツ


No feature description will ever be deleted from @code{__future__}. Since its
introduction in Python 2.1 the following features have found their way into the
language using this mechanism:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

feature

@tab

optional in

@tab

mandatory in

@tab

effect

@item

@geindex nested_scopes (__future__ モジュール)
@anchor{library/__future__ future__ nested_scopes}@anchor{49ff}
@deffn {データ} __future__.nested_scopes
@end deffn

@tab

2.1.0b1

@tab

2.2

@tab

@geindex Python Enhancement Proposals; PEP 227
PEP 227@footnote{https://peps.python.org/pep-0227/}: `Statically Nested Scopes'

@item

@geindex generators (__future__ モジュール)
@anchor{library/__future__ future__ generators}@anchor{4a00}
@deffn {データ} __future__.generators
@end deffn

@tab

2.2.0a1

@tab

2.3

@tab

@geindex Python Enhancement Proposals; PEP 255
PEP 255@footnote{https://peps.python.org/pep-0255/}: `Simple Generators'

@item

@geindex division (__future__ モジュール)
@anchor{library/__future__ future__ division}@anchor{4a01}
@deffn {データ} __future__.division
@end deffn

@tab

2.2.0a2

@tab

3.0

@tab

@geindex Python Enhancement Proposals; PEP 238
PEP 238@footnote{https://peps.python.org/pep-0238/}: `Changing the Division Operator'

@item

@geindex absolute_import (__future__ モジュール)
@anchor{library/__future__ future__ absolute_import}@anchor{4a02}
@deffn {データ} __future__.absolute_import
@end deffn

@tab

2.5.0a1

@tab

3.0

@tab

@geindex Python Enhancement Proposals; PEP 328
PEP 328@footnote{https://peps.python.org/pep-0328/}: `Imports: Multi-Line and Absolute/Relative'

@item

@geindex with_statement (__future__ モジュール)
@anchor{library/__future__ future__ with_statement}@anchor{4a03}
@deffn {データ} __future__.with_statement
@end deffn

@tab

2.5.0a1

@tab

2.6

@tab

@geindex Python Enhancement Proposals; PEP 343
PEP 343@footnote{https://peps.python.org/pep-0343/}: `The “with” Statement'

@item

@geindex print_function (__future__ モジュール)
@anchor{library/__future__ future__ print_function}@anchor{4a04}
@deffn {データ} __future__.print_function
@end deffn

@tab

2.6.0a2

@tab

3.0

@tab

@geindex Python Enhancement Proposals; PEP 3105
PEP 3105@footnote{https://peps.python.org/pep-3105/}: `Make print a function'

@item

@geindex unicode_literals (__future__ モジュール)
@anchor{library/__future__ future__ unicode_literals}@anchor{4a05}
@deffn {データ} __future__.unicode_literals
@end deffn

@tab

2.6.0a2

@tab

3.0

@tab

@geindex Python Enhancement Proposals; PEP 3112
PEP 3112@footnote{https://peps.python.org/pep-3112/}: `Bytes literals in Python 3000'

@item

@geindex generator_stop (__future__ モジュール)
@anchor{library/__future__ future__ generator_stop}@anchor{4a06}
@deffn {データ} __future__.generator_stop
@end deffn

@tab

3.5.0b1

@tab

3.7

@tab

@geindex Python Enhancement Proposals; PEP 479
PEP 479@footnote{https://peps.python.org/pep-0479/}: `StopIteration handling inside generators'

@item

@geindex annotations (__future__ モジュール)
@anchor{library/__future__ future__ annotations}@anchor{4a07}
@deffn {データ} __future__.annotations
@end deffn

@tab

3.7.0b1

@tab

Never @footnote{
@code{from __future__ import annotations} was previously scheduled to
become mandatory in Python 3.10, but the change was delayed and ultimately
canceled. This feature will eventually be deprecated and removed. See
@geindex Python Enhancement Proposals; PEP 649
@uref{https://peps.python.org/pep-0649/,PEP 649} and 
@geindex Python Enhancement Proposals; PEP 749
@uref{https://peps.python.org/pep-0749/,PEP 749}.
}

@tab

@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/}: `Postponed evaluation of annotations',
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/}: `Deferred evaluation of annotations using descriptors'

@end multitable


@c XXX Adding a new entry?  Remember to update simple_stmts.rst, too.

@geindex _Feature (__future__ のクラス)
@anchor{library/__future__ future-classes}@anchor{4a08}@anchor{library/__future__ future__ _Feature}@anchor{25c8}
@deffn {クラス} __future__._Feature

@code{__future__.py} のそれぞれの文は次のような形式をしています:

@example
FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                       CompilerFlag)
@end example

ここで、普通は、 `OptionalRelease' は `MandatoryRelease' より小さく、2つとも @ref{8af,,sys.version_info} と同じフォーマットの5つのタプルからなります:

@example
(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
 PY_MINOR_VERSION, # the 1; an int
 PY_MICRO_VERSION, # the 0; an int
 PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
 PY_RELEASE_SERIAL # the 3; an int
)
@end example
@end deffn

@geindex getOptionalRelease() (__future__._Feature のメソッド)
@anchor{library/__future__ future__ _Feature getOptionalRelease}@anchor{4a09}
@deffn {メソッド} _Feature.getOptionalRelease ()

`OptionalRelease' はその機能が導入された最初のリリースを記録します。
@end deffn

@geindex getMandatoryRelease() (__future__._Feature のメソッド)
@anchor{library/__future__ future__ _Feature getMandatoryRelease}@anchor{4a0a}
@deffn {メソッド} _Feature.getMandatoryRelease ()

まだ時期が来ていない `MandatoryRelease' の場合、`MandatoryRelease' はその機能が言語の一部となるリリースを記します。

その他の場合、`MandatoryRelease' はその機能がいつ言語の一部になったのかを記録します。そのリリースから、あるいはそれ以降のリリースでは、この機能を使う際に future 文は必要ではありませんが、future 文を使い続けても構いません。

`MandatoryRelease' は @code{None} になるかもしれません。つまり、予定された機能が破棄されたか、まだ決定されていないということです。
@end deffn

@geindex compiler_flag (__future__._Feature の属性)
@anchor{library/__future__ future__ _Feature compiler_flag}@anchor{2393}
@deffn {の属性} _Feature.compiler_flag

`CompilerFlag' は、動的にコンパイルされるコードでその機能を有効にするために、組み込み関数 @ref{4b1,,compile()} の第4引数に渡す(ビットフィールド)フラグです。このフラグは @ref{25c8,,_Feature} インスタンスの @ref{2393,,_Feature.compiler_flag} 属性に保存されています。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{45d,,future 文 (future statement)}

コンパイラがどのように future インポートを扱うか。

@geindex Python Enhancement Proposals; PEP 236

@item PEP 236@footnote{https://peps.python.org/pep-0236/} - Back to the __future__

__future__ 機構の原案
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node gc --- ガベージコレクターインターフェース,inspect --- 活動中のオブジェクトを調査する,__future__ --- future 文の定義,Python ランタイムサービス
@anchor{library/gc doc}@anchor{4a0b}@anchor{library/gc gc-garbage-collector-interface}@anchor{4a0c}@anchor{library/gc module-gc}@anchor{64}@anchor{library/gc translation-repo}@anchor{4a0d}
@subsection @code{gc} --- ガベージコレクターインターフェース


@geindex module; gc


__________________________________________________________________


このモジュールは、循環ガベージコレクタの無効化・検出頻度の調整・デバッグオブションの設定などを行うインターフェースを提供します。また、検出した到達不能オブジェクトのうち、解放する事ができないオブジェクトを参照する事もできます。循環ガベージコレクタはPythonの参照カウントを補うためのものなので、もしプログラム中で循環参照が発生しない事が明らかな場合には検出をする必要はありません。自動検出は、 @code{gc.disable()} で停止する事ができます。メモリリークをデバッグするときには、 @code{gc.set_debug(gc.DEBUG_LEAK)} とします。これは @code{gc.DEBUG_SAVEALL} を含んでいることに注意しましょう。ガベージとして検出されたオブジェクトは、インスペクション用に gc.garbage に保存されます。

The @code{gc} module provides the following functions:

@geindex enable() (gc モジュール)
@anchor{library/gc gc enable}@anchor{4a0e}
@deffn {の関数} gc.enable ()

自動ガベージコレクションを有効にします。
@end deffn

@geindex disable() (gc モジュール)
@anchor{library/gc gc disable}@anchor{4a0f}
@deffn {の関数} gc.disable ()

自動ガベージコレクションを無効にします。
@end deffn

@geindex isenabled() (gc モジュール)
@anchor{library/gc gc isenabled}@anchor{4a10}
@deffn {の関数} gc.isenabled ()

自動ガベージコレクションが有効なら @code{True} を返します。
@end deffn

@geindex collect() (gc モジュール)
@anchor{library/gc gc collect}@anchor{1b3}
@deffn {の関数} gc.collect (generation=2)

Perform a collection.  The optional argument `generation'
may be an integer specifying which generation to collect (from 0 to 2).  A
@ref{2ec,,ValueError} is raised if the generation number is invalid. The sum of
collected objects and uncollectable objects is returned.

Calling @code{gc.collect(0)} will perform a GC collection on the young generation.

Calling @code{gc.collect(1)} will perform a GC collection on the young generation
and an increment of the old generation.

Calling @code{gc.collect(2)} or @code{gc.collect()} performs a full collection

ビルトイン型が持っている free list は、フルGCか最高世代(2)のGCの時にクリアされます。 @ref{196,,float} など、実装によって幾つかの free list では全ての要素が解放されるわけではありません。

The effect of calling @code{gc.collect()} while the interpreter is already
performing a collection is undefined.


バージョン 3.14 で変更: @code{generation=1} performs an increment of collection.

@end deffn

@geindex set_debug() (gc モジュール)
@anchor{library/gc gc set_debug}@anchor{4a11}
@deffn {の関数} gc.set_debug (flags)

ガベージコレクションのデバッグフラグを設定します。デバッグ情報は @code{sys.stderr} に出力されます。デバッグフラグは、下の値の組み合わせを指定する事ができます。
@end deffn

@geindex get_debug() (gc モジュール)
@anchor{library/gc gc get_debug}@anchor{4a12}
@deffn {の関数} gc.get_debug ()

現在のデバッグフラグを返します。
@end deffn

@geindex get_objects() (gc モジュール)
@anchor{library/gc gc get_objects}@anchor{a04}
@deffn {の関数} gc.get_objects (generation=None)

Returns a list of all objects tracked by the collector, excluding the list
returned. If `generation' is not @code{None}, return only the objects as follows:


@itemize *

@item 
0: All objects in the young generation

@item 
1: No objects, as there is no generation 1 (as of Python 3.14)

@item 
2: All objects in the old generation
@end itemize


バージョン 3.8 で変更: 新しい `generation' パラメータ。



バージョン 3.14 で変更: Generation 1 is removed


引数 @code{generation} で @ref{1c6e,,監査イベント} @code{gc.get_objects} を送出します。
@end deffn

@geindex get_stats() (gc モジュール)
@anchor{library/gc gc get_stats}@anchor{2dc}
@deffn {の関数} gc.get_stats ()

インタプリタが開始してからの、世代ごと回収統計を持つ辞書の、3 世代ぶんのリストを返します。キーの数は将来変わるかもしれませんが、現在のところそれぞれの辞書には以下の項目が含まれています:


@itemize *

@item 
@code{collections} は、この世代が検出を行った回数です;

@item 
@code{collected} は、この世代内で回収されたオブジェクトの総数です;

@item 
@code{uncollectable} は、この世代内で回収不能であることがわかった (そしてそれゆえに @ref{13d9,,garbage} リストに移動した) オブジェクトの総数です。
@end itemize


Added in version 3.4.

@end deffn

@geindex set_threshold() (gc モジュール)
@anchor{library/gc gc set_threshold}@anchor{2da}
@deffn {の関数} gc.set_threshold (threshold0[, threshold1[, threshold2]])

ガベージコレクションの閾値（検出頻度）を指定します。 `threshold0' を 0 にすると、検出は行われません。

The GC classifies objects into two generations depending on whether they have
survived a collection. New objects are placed in the young generation. If an
object survives a collection it is moved into the old generation.

In order to decide when to run, the collector keeps track of the number of object
allocations and deallocations since the last collection.  When the number of
allocations minus the number of deallocations exceeds `threshold0', collection
starts. For each collection, all the objects in the young generation and some
fraction of the old generation is collected.

In the free-threaded build, the increase in process memory usage is also
checked before running the collector.  If the memory usage has not increased
by 10% since the last collection and the net number of object allocations
has not exceeded 40 times `threshold0', the collection is not run.

The fraction of the old generation that is collected is `inversely' proportional
to `threshold1'. The larger `threshold1' is, the slower objects in the old generation
are collected.
For the default value of 10, 1% of the old generation is scanned during each collection.

`threshold2' is ignored.

See Garbage collector design@footnote{https://github.com/python/cpython/blob/3.14/InternalDocs/garbage_collector.md} for more information.


バージョン 3.14 で変更: `threshold2' is ignored

@end deffn

@geindex get_count() (gc モジュール)
@anchor{library/gc gc get_count}@anchor{2db}
@deffn {の関数} gc.get_count ()

現在の検出数を、 @code{(count0, count1, count2)} のタプルで返します。
@end deffn

@geindex get_threshold() (gc モジュール)
@anchor{library/gc gc get_threshold}@anchor{2d9}
@deffn {の関数} gc.get_threshold ()

現在の検出閾値を、 @code{(threshold0, threshold1, threshold2)} のタプルで返します。
@end deffn

@geindex get_referrers() (gc モジュール)
@anchor{library/gc gc get_referrers}@anchor{a05}
@deffn {の関数} gc.get_referrers (*objs)

objsで指定したオブジェクトのいずれかを参照しているオブジェクトのリストを返します。この関数では、ガベージコレクションをサポートしているコンテナのみを返します。他のオブジェクトを参照していても、ガベージコレクションをサポートしていない拡張型は含まれません。

尚、戻り値のリストには、すでに参照されなくなっているが、循環参照の一部でまだガベージコレクションで回収されていないオブジェクトも含まれるので注意が必要です。有効なオブジェクトのみを取得する場合、 @ref{a05,,get_referrers()} の前に @ref{1b3,,collect()} を呼び出してください。

@cartouche
@quotation 警告 
@ref{a05,,get_referrers()} から返されるオブジェクトは作りかけや利用できない状態である場合があるので、利用する際には注意が必要です。 @ref{a05,,get_referrers()} をデバッグ以外の目的で利用するのは避けてください。
@end quotation
@end cartouche

引数 @code{objs} を指定して @ref{1c6e,,監査イベント} @code{gc.get_referrers} を送出します。
@end deffn

@geindex get_referents() (gc モジュール)
@anchor{library/gc gc get_referents}@anchor{a06}
@deffn {の関数} gc.get_referents (*objs)

引数で指定したオブジェクトのいずれかから参照されている、全てのオブジェクトのリストを返します。参照先のオブジェクトは、引数で指定したオブジェクトの Cレベルメソッド @ref{982,,tp_traverse} で取得し、全てのオブジェクトが直接到達可能な全てのオブジェクトを返すわけではありません。 @ref{982,,tp_traverse} はガベージコレクションをサポートするオブジェクトのみが実装しており、ここで取得できるオブジェクトは循環参照の一部となる可能性のあるオブジェクトのみです。従って、例えば整数オブジェクトが直接到達可能であっても、このオブジェクトは戻り値には含まれません。

引数 @code{objs} を指定して @ref{1c6e,,監査イベント} @code{gc.get_referents} を送出します。
@end deffn

@geindex is_tracked() (gc モジュール)
@anchor{library/gc gc is_tracked}@anchor{1525}
@deffn {の関数} gc.is_tracked (obj)

@code{obj} がガベージコレクタに管理されていたら @code{True} を返し、それ以外の場合は @code{False} を返します。
一般的なルールとして、アトミックな (訳注: 他のオブジェクトを参照しないで単一で値を表す型。 int や str など) 型のインスタンスは管理されず、それ以外の型 (コンテナ型、ユーザー定義型など) のインスタンスは管理されます。
しかし、いくつかの型では専用の最適化を行い、シンプルなインスタンスの場合に GCのオーバーヘッドを減らしています。
(例: 全ての key と value がアトミック型の値である dict)

@example
>>> gc.is_tracked(0)
False
>>> gc.is_tracked("a")
False
>>> gc.is_tracked([])
True
>>> gc.is_tracked(@{@})
False
>>> gc.is_tracked(@{"a": 1@})
True
@end example


Added in version 3.1.

@end deffn

@geindex is_finalized() (gc モジュール)
@anchor{library/gc gc is_finalized}@anchor{af9}
@deffn {の関数} gc.is_finalized (obj)

Returns @code{True} if the given object has been finalized by the
garbage collector, @code{False} otherwise.

@example
>>> x = None
>>> class Lazarus:
...     def __del__(self):
...         global x
...         x = self
...
>>> lazarus = Lazarus()
>>> gc.is_finalized(lazarus)
False
>>> del lazarus
>>> gc.is_finalized(x)
True
@end example


Added in version 3.9.

@end deffn

@geindex freeze() (gc モジュール)
@anchor{library/gc gc freeze}@anchor{d2e}
@deffn {の関数} gc.freeze ()

Freeze all the objects tracked by the garbage collector; move them to a
permanent generation and ignore them in all the future collections.

If a process will @code{fork()} without @code{exec()}, avoiding unnecessary
copy-on-write in child processes will maximize memory sharing and reduce
overall memory usage. This requires both avoiding creation of freed "holes"
in memory pages in the parent process and ensuring that GC collections in
child processes won't touch the @code{gc_refs} counter of long-lived objects
originating in the parent process. To accomplish both, call @code{gc.disable()}
early in the parent process, @code{gc.freeze()} right before @code{fork()}, and
@code{gc.enable()} early in child processes.


Added in version 3.7.

@end deffn

@geindex unfreeze() (gc モジュール)
@anchor{library/gc gc unfreeze}@anchor{d2f}
@deffn {の関数} gc.unfreeze ()

Permanent世代領域にあるオブジェクトを解凍します。つまり、最も古い世代へ戻します。


Added in version 3.7.

@end deffn

@geindex get_freeze_count() (gc モジュール)
@anchor{library/gc gc get_freeze_count}@anchor{d30}
@deffn {の関数} gc.get_freeze_count ()

Permanent世代領域にあるオブジェクトの数を返します。


Added in version 3.7.

@end deffn

以下の変数は読み出し専用アクセスのために提供されています。(この変数を操作することはできますが、その値は記憶されません):

@geindex garbage (gc モジュール)
@anchor{library/gc gc garbage}@anchor{13d9}
@deffn {データ} gc.garbage

到達不能であることが検出されたが、解放する事ができないオブジェクトのリスト（回収不能オブジェクト）。Python 3.4 からは、@code{NULL} でない @code{tp_del} スロットを持つ C 拡張型のインスタンスを使っている場合を除き、このリストはほとんど常に空であるはずです。

@ref{4a13,,DEBUG_SAVEALL} が設定されている場合、全ての到達不能オブジェクトは解放されずにこのリストに格納されます。


バージョン 3.2 で変更: @ref{479,,インタプリタシャットダウン} 時にこのリストが空でない場合、(デフォルトでは黙りますが) @ref{54c,,ResourceWarning} が発行されます。 @ref{13da,,DEBUG_UNCOLLECTABLE} がセットされていると、加えて回収不能オブジェクトを出力します。



バージョン 3.4 で変更: Following 
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/}, objects with a @ref{11ff,,__del__()} method don't end
up in @ref{13d9,,gc.garbage} anymore.

@end deffn

@geindex callbacks (gc モジュール)
@anchor{library/gc gc callbacks}@anchor{12de}
@deffn {データ} gc.callbacks

ガベージコレクタの起動前と終了後に呼び出されるコールバック関数のリスト。コールバックは `phase' と `info' の2つの引数で呼び出されます。

`phase' は以下 2 つのいずれかです:

@quotation

"start": ガベージコレクションを始めます。

"stop": ガベージコレクションが終了しました。
@end quotation

`info' はコールバックに付加情報を提供する辞書です。現在のところ以下のキーが定義されています:

@quotation

"generation": 回収される最も古い世代。

"collected": `phase' が "stop" のとき、正常に回収されたオブジェクトの数。

"uncollectable": `phase' が "stop" のとき、回収出来ずに @ref{13d9,,garbage} リストに入れられたオブジェクトの数。
@end quotation

アプリケーションは自身のコールバックをこのリストに追加出来ます。基本的なユースケースは以下のようなものでしょう:

@quotation

世代が回収される頻度やガベージコレクションにかかった時間の長さといった、ガベージコレクションの統計情報を集めます。

@ref{13d9,,garbage} に回収できない独自の型のオブジェクトが現れたとき、アプリケーションがそれらを特定し消去できるようにする。
@end quotation


Added in version 3.3.

@end deffn

以下は @ref{4a11,,set_debug()} に指定することのできる定数です:

@geindex DEBUG_STATS (gc モジュール)
@anchor{library/gc gc DEBUG_STATS}@anchor{4a14}
@deffn {データ} gc.DEBUG_STATS

検出中に統計情報を出力します。この情報は、検出頻度を最適化する際に有益です。
@end deffn

@geindex DEBUG_COLLECTABLE (gc モジュール)
@anchor{library/gc gc DEBUG_COLLECTABLE}@anchor{4a15}
@deffn {データ} gc.DEBUG_COLLECTABLE

見つかった回収可能オブジェクトの情報を出力します。
@end deffn

@geindex DEBUG_UNCOLLECTABLE (gc モジュール)
@anchor{library/gc gc DEBUG_UNCOLLECTABLE}@anchor{13da}
@deffn {データ} gc.DEBUG_UNCOLLECTABLE

見つかった回収不能オブジェクト（到達不能だが、ガベージコレクションで解放する事ができないオブジェクト）の情報を出力します。回収不能オブジェクトは、 @code{garbage} リストに追加されます。


バージョン 3.2 で変更: @ref{479,,インタプリタシャットダウン} 時に @ref{13d9,,garbage} リストが空でない場合に、その中身の出力も行います。

@end deffn

@geindex DEBUG_SAVEALL (gc モジュール)
@anchor{library/gc gc DEBUG_SAVEALL}@anchor{4a13}
@deffn {データ} gc.DEBUG_SAVEALL

設定されている場合、全ての到達不能オブジェクトは解放されずに `garbage' に追加されます。これはプログラムのメモリリークをデバッグするときに便利です。
@end deffn

@geindex DEBUG_LEAK (gc モジュール)
@anchor{library/gc gc DEBUG_LEAK}@anchor{4a16}
@deffn {データ} gc.DEBUG_LEAK

プログラムのメモリリークをデバッグするときに指定します（ @code{DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL} と同じ）。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node inspect --- 活動中のオブジェクトを調査する,annotationlib --- Functionality for introspecting annotations,gc --- ガベージコレクターインターフェース,Python ランタイムサービス
@anchor{library/inspect doc}@anchor{4a17}@anchor{library/inspect inspect-inspect-live-objects}@anchor{4a18}@anchor{library/inspect translation-repo}@anchor{4a19}
@subsection @code{inspect} --- 活動中のオブジェクトを調査する


@c import inspect
@c from inspect import *

@geindex module; inspect
@anchor{library/inspect module-inspect}@anchor{82}
`ソースコード:' Lib/inspect.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/inspect.py}


__________________________________________________________________


The @code{inspect} module provides several useful functions to help get
information about live objects such as modules, classes, methods, functions,
tracebacks, frame objects, and code objects.  For example, it can help you
examine the contents of a class, retrieve the source code of a method, extract
and format the argument list for a function, or get all the information you need
to display a detailed traceback.

このモジュールの機能は4種類に分類することができます。型チェック、ソースコードの情報取得、クラスや関数からの情報取得、インタープリタのスタック情報の調査です。

@menu
* 型とメンバー:: 
* ソースコードの情報取得:: 
* Signature オブジェクトで呼び出し可能オブジェクトを内省する:: 
* クラスと関数: クラスと関数<2>. 
* インタープリタスタック:: 
* 属性の静的なフェッチ:: 
* Current State of Generators@comma{} Coroutines@comma{} and Asynchronous Generators: Current State of Generators Coroutines and Asynchronous Generators. 
* Code Objects Bit Flags:: 
* Buffer flags:: 
* コマンドライン・インターフェース: コマンドライン・インターフェース<10>. 

@end menu

@node 型とメンバー,ソースコードの情報取得,,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect inspect-types}@anchor{1d92}@anchor{library/inspect types-and-members}@anchor{4a1a}
@subsubsection 型とメンバー


@ref{1bf1,,getmembers()} は、クラスやモジュールなどのオブジェクトからメンバーを取得します。名前が "is" で始まる関数は、主に @ref{1bf1,,getmembers()} の第2引数として利用するために提供されています。以下のような特殊属性を参照できるかどうか調べる時にも使えるでしょう (モジュール属性については @ref{2361,,Import-related attributes on module objects} を参照してください):

@c this function name is too big to fit in the ascii-art table below


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

型

@tab

属性

@tab

説明

@item

クラス

@tab

__doc__

@tab

ドキュメント文字列

@item

@tab

__name__

@tab

クラスの定義名

@item

@tab

__qualname__

@tab

qualified name

@item

@tab

__module__

@tab

クラスを定義しているモジュールの名前

@item

@tab

__type_params__

@tab

ジェネリッククラスの @ref{5ad,,型パラメータ (type parameters)} を含むタプル

@item

メソッド

@tab

__doc__

@tab

ドキュメント文字列

@item

@tab

__name__

@tab

メソッドの定義名

@item

@tab

__qualname__

@tab

qualified name

@item

@tab

__func__

@tab

メソッドを実装している関数オブジェクト

@item

@tab

__self__

@tab

メソッドに結合しているインスタンス、または @code{None}

@item

@tab

__module__

@tab

このメソッドが定義されているモジュールの名前

@item

関数

@tab

__doc__

@tab

ドキュメント文字列

@item

@tab

__name__

@tab

関数の定義名

@item

@tab

__qualname__

@tab

qualified name

@item

@tab

__code__

@tab

関数をコンパイルした @ref{4aa,,バイトコード} を格納するコードオブジェクト

@item

@tab

__defaults__

@tab

位置またはキーワード引数の全ての既定値のタプル

@item

@tab

__kwdefaults__

@tab

キーワード専用引数の全ての既定値のマッピング

@item

@tab

__globals__

@tab

関数が定義されたグローバル名前空間

@item

@tab

__builtins__

@tab

組み込みモジュールの名前空間

@item

@tab

__annotations__

@tab

仮引数名からアノテーションへのマッピング; @code{"return"} キーは return アノテーションに予約されています

@item

@tab

__type_params__

@tab

ジェネリック関数の @ref{5ad,,型パラメータ (type parameters)} を含むタプル

@item

@tab

__module__

@tab

この関数が定義されているモジュールの名前

@item

traceback

@tab

tb_frame

@tab

このレベルのフレームオブジェクト

@item

@tab

tb_lasti

@tab

最後に実行しようとしたバイトコード中のインストラクションを示すインデックス

@item

@tab

tb_lineno

@tab

現在の Python ソースコードの行番号

@item

@tab

tb_next

@tab

このオブジェクトの内側 (このレベルから呼び出された) のトレースバックオブジェクト

@item

フレーム

@tab

f_back

@tab

外側 (このフレームを呼び出した) のフレームオブジェクト

@item

@tab

f_builtins

@tab

このフレームで参照している組み込み名前空間

@item

@tab

f_code

@tab

このフレームで実行しているコードオブジェクト

@item

@tab

f_globals

@tab

このフレームで参照しているグローバル名前空間

@item

@tab

f_lasti

@tab

最後に実行しようとしたバイトコード中のインストラクションを示すインデックス

@item

@tab

f_lineno

@tab

現在の Python ソースコードの行番号

@item

@tab

f_locals

@tab

このフレームで参照しているローカル名前空間

@item

@tab

f_generator

@tab

returns the generator or
coroutine object that
owns this frame, or
@code{None} if the frame is
of a regular function

@item

@tab

f_trace

@tab

このフレームのトレース関数、または @code{None}

@item

@tab

f_trace_lines

@tab

indicate whether a
tracing event is
triggered for each source
source line

@item

@tab

f_trace_opcodes

@tab

indicate whether
per-opcode events are
requested

@item

@tab

clear()

@tab

used to clear all
references to local
variables

@item

コード

@tab

co_argcount

@tab

引数の数 (キーワード限定引数、および * や ** は含まない)

@item

@tab

co_code

@tab

コンパイルされたバイトコードそのままの文字列

@item

@tab

co_cellvars

@tab

(自身が包含するスコープから参照される) セル変数の名前のタプル

@item

@tab

co_consts

@tab

バイトコード中で使用している定数のタプル

@item

@tab

co_filename

@tab

コードオブジェクトを生成したファイルのファイル名

@item

@tab

co_firstlineno

@tab

Python ソースコードの先頭行

@item

@tab

co_flags

@tab

@code{CO_*} ビットフラグのマップ。詳細は @ref{2392,,こちら} を参照。

@item

@tab

co_lnotab

@tab

行番号からバイトコードインデックスへの変換表を文字列にエンコードしたもの

@item

@tab

co_freevars

@tab

(関数のクロージャを介して参照される) 自由変数の名前のタプル

@item

@tab

co_posonlyargcount

@tab

位置専用引数の数

@item

@tab

co_kwonlyargcount

@tab

キーワード専用引数 (** 引数を含まない) の数

@item

@tab

co_name

@tab

コードオブジェクトが定義されたときの名前

@item

@tab

co_qualname

@tab

このコードオブジェクトが定義されたときの完全修飾名 (fully qualified name)

@item

@tab

co_names

@tab

関数の引数でもローカル変数でもない名前のタプル

@item

@tab

co_nlocals

@tab

ローカル変数の数

@item

@tab

co_stacksize

@tab

必要とされる仮想マシンのスタックスペース

@item

@tab

co_varnames

@tab

引数名とローカル変数名のタプル

@item

@tab

co_lines()

@tab

returns an iterator that
yields successive
bytecode ranges

@item

@tab

co_positions()

@tab

returns an iterator of
source code positions for
each bytecode instruction

@item

@tab

replace()

@tab

returns a copy of the
code object with new
values

@item

ジェネレータ

@tab

__name__

@tab

name

@item

@tab

__qualname__

@tab

qualified name

@item

@tab

gi_frame

@tab

フレーム

@item

@tab

gi_running

@tab

ジェネレータが実行中かどうか

@item

@tab

gi_suspended

@tab

is the generator
suspended?

@item

@tab

gi_code

@tab

コード

@item

@tab

gi_yieldfrom

@tab

@code{yield from} でイテレートされているオブジェクト、または @code{None}

@item

非同期ジェネレータ

@tab

__name__

@tab

name

@item

@tab

__qualname__

@tab

qualified name

@item

@tab

ag_await

@tab

待機されているオブジェクト、または @code{None}

@item

@tab

ag_frame

@tab

フレーム

@item

@tab

ag_running

@tab

ジェネレータが実行中かどうか

@item

@tab

ag_suspended

@tab

is the generator
suspended?

@item

@tab

ag_code

@tab

コード

@item

コルーチン

@tab

__name__

@tab

name

@item

@tab

__qualname__

@tab

qualified name

@item

@tab

cr_await

@tab

待機されているオブジェクト、または @code{None}

@item

@tab

cr_frame

@tab

フレーム

@item

@tab

cr_running

@tab

コルーチンが実行中かどうか

@item

@tab

cr_suspended

@tab

is the coroutine
suspended?

@item

@tab

cr_code

@tab

コード

@item

@tab

cr_origin

@tab

@code{None} またはコルーチンが生成された場所。 @ref{d85,,sys.set_coroutine_origin_tracking_depth()} を参照。

@item

組み込み

@tab

__doc__

@tab

ドキュメント文字列

@item

@tab

__name__

@tab

関数、メソッドの元々の名前

@item

@tab

__qualname__

@tab

qualified name

@item

@tab

__self__

@tab

メソッドが結合しているインスタンス、または @code{None}

@end multitable



バージョン 3.5 で変更: ジェネレータに @code{__qualname__} と @code{gi_yieldfrom} 属性が追加されました。

ジェネレータの @code{__name__} 属性がコード名ではなく関数名から設定されるようになり、変更できるようになりました。



バージョン 3.7 で変更: コルーチンに @code{cr_origin} 属性を追加しました。



バージョン 3.10 で変更: 関数に @code{__builtins__} 属性を追加しました。



バージョン 3.11 で変更: Add @code{gi_suspended} attribute to generators.



バージョン 3.11 で変更: Add @code{cr_suspended} attribute to coroutines.



バージョン 3.12 で変更: Add @code{ag_suspended} attribute to async generators.



バージョン 3.14 で変更: Add @code{f_generator} attribute to frames.


@geindex getmembers() (inspect モジュール)
@anchor{library/inspect inspect getmembers}@anchor{1bf1}
@deffn {の関数} inspect.getmembers (object[, predicate])

オブジェクトの全てのメンバーを @code{(name, value)} ペアのリストで返します。リストは名前 (name) でソートされます。オプション引数 `predicate' が指定された場合、各メンバーの @code{value} オブジェクトを引数として `predicate' が呼ばれ、その戻り値が真となるとなるメンバーだけがリストに含まれます。

@cartouche
@quotation 注釈 
引数がクラスでその属性がメタクラスで特別に定義された @ref{17e2,,__dir__()} に列挙されている場合、@ref{1bf1,,getmembers()} はメタクラスで定義されたクラス属性のみを返します。
@end quotation
@end cartouche
@end deffn

@geindex getmembers_static() (inspect モジュール)
@anchor{library/inspect inspect getmembers_static}@anchor{859}
@deffn {の関数} inspect.getmembers_static (object[, predicate])

オブジェクトの全てのメンバーを @code{(name, value)} ペアのリストで返します。ただし、デスクリプタプロトコルの __getattr__ や __getattribute__ を介した動的なルックアップは行いません。オプションとして、引数に与えられた predicate を満たすメンバーのみを返すこともできます。

@cartouche
@quotation 注釈 
@ref{859,,getmembers_static()} は getmembers が取得できるメンバーの全てを取り出すことはできないかもしれません (たとえば動的に生成された属性など)が、逆に getmembers が見つけることのできなかったメンバーを取得できることもあります (AttributeError を送出するデスクリプタなど)。また、時にはインスタンスメンバーの代わりにデスクリプタオブジェクトを返すこともあります。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex getmodulename() (inspect モジュール)
@anchor{library/inspect inspect getmodulename}@anchor{f34}
@deffn {の関数} inspect.getmodulename (path)

ファイル `path' で指定されたモジュールの名前を、そのモジュールを含むパッケージの名前を含まない形で返します。ファイル拡張子は、 @ref{4a1b,,importlib.machinery.all_suffixes()} の全てのエントリに対して一致するかどうかをチェックされます。拡張子が一致した場合、最後のパス成分から拡張子を除いたものを返します。それ以外の場合は @code{None} を返します。

この関数は、実際の Python モジュールとして意味のある名前 `だけ' を返します。すなわち、 Python パッケージを指している可能性のあるパスに対しては、依然として @code{None} を返します。


バージョン 3.3 で変更: この関数は直接 @ref{7b,,importlib} に依存するようになりました。

@end deffn

@geindex ismodule() (inspect モジュール)
@anchor{library/inspect inspect ismodule}@anchor{4a1c}
@deffn {の関数} inspect.ismodule (object)

オブジェクトがモジュールの場合 @code{True} を返します。
@end deffn

@geindex isclass() (inspect モジュール)
@anchor{library/inspect inspect isclass}@anchor{4a1d}
@deffn {の関数} inspect.isclass (object)

オブジェクトが組み込みか Python が生成したクラスの場合に @code{True} を返します。
@end deffn

@geindex ismethod() (inspect モジュール)
@anchor{library/inspect inspect ismethod}@anchor{4a1e}
@deffn {の関数} inspect.ismethod (object)

オブジェクトがメソッドの場合 @code{True} を返します。
@end deffn

@geindex ispackage() (inspect モジュール)
@anchor{library/inspect inspect ispackage}@anchor{232}
@deffn {の関数} inspect.ispackage (object)

Return @code{True} if the object is a @ref{233,,package}.


Added in version 3.14.

@end deffn

@geindex isfunction() (inspect モジュール)
@anchor{library/inspect inspect isfunction}@anchor{4a1f}
@deffn {の関数} inspect.isfunction (object)

オブジェクトが、 @ref{2bb3,,lambda} 式で生成されたものを含む Python 関数の場合に @code{True} を返します。
@end deffn

@geindex isgeneratorfunction() (inspect モジュール)
@anchor{library/inspect inspect isgeneratorfunction}@anchor{1b5b}
@deffn {の関数} inspect.isgeneratorfunction (object)

オブジェクトが Python のジェネレータ関数の場合 @code{True} を返します。


バージョン 3.8 で変更: @ref{217,,functools.partial()} でラップした関数に対して、ラップされた関数が Python のジェネレータ関数である場合は @code{True} を返すようになりました。



バージョン 3.13 で変更: @ref{218,,functools.partialmethod()} でラップした関数に対して、ラップされた関数が Python のジェネレータ関数である場合は @code{True} を返すようになりました。

@end deffn

@geindex isgenerator() (inspect モジュール)
@anchor{library/inspect inspect isgenerator}@anchor{4a20}
@deffn {の関数} inspect.isgenerator (object)

オブジェクトがジェネレータの場合 @code{True} を返します。
@end deffn

@geindex iscoroutinefunction() (inspect モジュール)
@anchor{library/inspect inspect iscoroutinefunction}@anchor{30d}
@deffn {の関数} inspect.iscoroutinefunction (object)

オブジェクトがコルーチン関数 @ref{f73,,coroutine function} (@ref{7ed,,async def} 構文で定義された関数)、コルーチン関数 @ref{f73,,coroutine function} をラップしている @ref{217,,functools.partial()} もしくは @ref{6b8,,markcoroutinefunction()} とマークされた同期関数のいずれかの場合に @code{True} を返します


Added in version 3.5.



バージョン 3.8 で変更: @ref{217,,functools.partial()} でラップした関数に対して、ラップされた関数が コルーチン関数 @ref{f73,,coroutine function} である場合は @code{True} を返すようになりました。



バージョン 3.12 で変更: @ref{6b8,,markcoroutinefunction()} とマークされた同期関数に対して @code{True} を返すようになりました。



バージョン 3.13 で変更: @ref{218,,functools.partialmethod()} でラップした関数に対して、ラップされた関数がコルーチン関数 @ref{f73,,coroutine function} である場合は @code{True} を返すようになりました。

@end deffn

@geindex markcoroutinefunction() (inspect モジュール)
@anchor{library/inspect inspect markcoroutinefunction}@anchor{6b8}
@deffn {の関数} inspect.markcoroutinefunction (func)

そのままであれば @ref{30d,,iscoroutinefunction()} がコルーチン関数と判定しないような呼び出し可能オブジェクトを、コルーチン関数 @ref{f73,,coroutine function} とマークするためのデコレータです。

これは、コルーチン @ref{6b9,,coroutine} を返す同期関数が、 @ref{30d,,iscoroutinefunction()} が真であることを要求するAPIに渡される場合に役に立つかもしれません。

可能なら、 @ref{7ed,,async def} を使った関数定義が好ましいです。また、関数を呼び出した上でその戻り値を @ref{1017,,iscoroutine()} でテストする方法も容認できます。


Added in version 3.12.

@end deffn

@geindex iscoroutine() (inspect モジュール)
@anchor{library/inspect inspect iscoroutine}@anchor{1017}
@deffn {の関数} inspect.iscoroutine (object)

オブジェクトが @ref{7ed,,async def} で生成された @ref{6b9,,コルーチン} の場合 @code{True} を返します。


Added in version 3.5.

@end deffn

@geindex isawaitable() (inspect モジュール)
@anchor{library/inspect inspect isawaitable}@anchor{1018}
@deffn {の関数} inspect.isawaitable (object)

オブジェクトを @ref{18d,,await} 式内で使用できる場合 @code{True} を返します。

ジェネレータベースのコルーチンと通常のジェネレータを区別するのにも使えます:

@example
import types

def gen():
    yield
@@types.coroutine
def gen_coro():
    yield

assert not isawaitable(gen())
assert isawaitable(gen_coro())
@end example


Added in version 3.5.

@end deffn

@geindex isasyncgenfunction() (inspect モジュール)
@anchor{library/inspect inspect isasyncgenfunction}@anchor{1b5c}
@deffn {の関数} inspect.isasyncgenfunction (object)

オブジェクトが非同期ジェネレータ @ref{249b,,asynchronous generator} 関数である場合に @code{True} を返します。使用例:

@example
>>> async def agen():
...     yield 1
...
>>> inspect.isasyncgenfunction(agen)
True
@end example


Added in version 3.6.



バージョン 3.8 で変更: @ref{217,,functools.partial()} でラップされた関数でも、元の関数が非同期ジェネレータ @ref{249b,,asynchronous generator} 関数であれば @code{True} を返すようになりました。



バージョン 3.13 で変更: Functions wrapped in @ref{218,,functools.partialmethod()} now return @code{True}
if the wrapped function is a @ref{249b,,asynchronous generator} function.

@end deffn

@geindex isasyncgen() (inspect モジュール)
@anchor{library/inspect inspect isasyncgen}@anchor{4a21}
@deffn {の関数} inspect.isasyncgen (object)

オブジェクトが @ref{249b,,asynchronous generator} 関数によって生成された @ref{4918,,asynchronous generator iterator} である場合に @code{True} を返します。


Added in version 3.6.

@end deffn

@geindex istraceback() (inspect モジュール)
@anchor{library/inspect inspect istraceback}@anchor{4a22}
@deffn {の関数} inspect.istraceback (object)

オブジェクトがトレースバックの場合は @code{True} を返します。
@end deffn

@geindex isframe() (inspect モジュール)
@anchor{library/inspect inspect isframe}@anchor{4a23}
@deffn {の関数} inspect.isframe (object)

オブジェクトがフレームの場合は @code{True} を返します。
@end deffn

@geindex iscode() (inspect モジュール)
@anchor{library/inspect inspect iscode}@anchor{4a24}
@deffn {の関数} inspect.iscode (object)

オブジェクトがコードの場合は @code{True} を返します。
@end deffn

@geindex isbuiltin() (inspect モジュール)
@anchor{library/inspect inspect isbuiltin}@anchor{4a25}
@deffn {の関数} inspect.isbuiltin (object)

オブジェクトが組み込み関数か束縛済みの組み込みメソッドの場合に @code{True} を返します。
@end deffn

@geindex ismethodwrapper() (inspect モジュール)
@anchor{library/inspect inspect ismethodwrapper}@anchor{85a}
@deffn {の関数} inspect.ismethodwrapper (object)

オブジェクトの型が @ref{85b,,MethodWrapperType} である場合に @code{True} を返します。

真を返すのは @ref{85b,,MethodWrapperType} のインスタンスで、 @ref{830,,__str__()}, @ref{cf2,,__eq__()},  @ref{82f,,__repr__()} などです。


Added in version 3.11.

@end deffn

@geindex isroutine() (inspect モジュール)
@anchor{library/inspect inspect isroutine}@anchor{1bdd}
@deffn {の関数} inspect.isroutine (object)

オブジェクトがユーザ定義か組み込みの関数またはメソッドの場合は @code{True} を返します。
@end deffn

@geindex isabstract() (inspect モジュール)
@anchor{library/inspect inspect isabstract}@anchor{4a26}
@deffn {の関数} inspect.isabstract (object)

オブジェクトが抽象基底クラスであるときに @code{True} を返します。
@end deffn

@geindex ismethoddescriptor() (inspect モジュール)
@anchor{library/inspect inspect ismethoddescriptor}@anchor{194e}
@deffn {の関数} inspect.ismethoddescriptor (object)

オブジェクトがメソッドデスクリプタであり、 @ref{4a1e,,ismethod()}, @ref{4a1d,,isclass()}, @ref{4a1f,,isfunction()}, @ref{4a25,,isbuiltin()} でない場合に @code{True} を返します。

これはたとえば、 @code{int.__add__} で真を返します。この関数によるテストをパスする（真を返す）オブジェクトは @ref{1701,,__get__()} メソッドを持ちますが、 @ref{23b5,,__set__()} メソッドや @ref{194f,,__delete__()} メソッドは持ちません。それ以外の属性の有無はさまざまです。 @ref{1272,,__name__} 属性は普通は存在しますし、 @ref{b21,,__doc__} 属性もしばしば見られます。

デスクリプタによって実装されたメソッドがこのメソッド以外のテストをパスする場合、 @ref{194e,,ismethoddescriptor()} によるテストでは @code{False} を返します。これは単純に、他のテストはより多くを約束するからです -- たとえば、あるオブジェクトが @ref{4a1e,,ismethod()} のテストをパスするとき、そのオブジェクトが @ref{1514,,__func__} 属性 (など) を持っていることを期待することができます。


バージョン 3.13 で変更: この関数は、 @ref{1701,,__get__()} 属性と @ref{194f,,__delete__()} 属性を持ち、 @ref{23b5,,__set__()} 属性を持たないオブジェクトをメソッドデスクリプタであると不正に報告することはなくなりました (そのようなオブジェクトはデータデスクリプタであって、メソッドデスクリプタではありません)。

@end deffn

@geindex isdatadescriptor() (inspect モジュール)
@anchor{library/inspect inspect isdatadescriptor}@anchor{4a27}
@deffn {の関数} inspect.isdatadescriptor (object)

オブジェクトがデータデスクリプタの場合に @code{True} を返します。

データデスクリプタは @ref{23b5,,__set__} メソッドか @ref{194f,,__delete__} メソッドのいずれかを持ちます。例としては、 (Python で定義された) プロパティ、 getset デスクリプタ、メンバーデスクリプタがあります。後者2つは C で定義されており、それぞれの型に対して特別なテストが存在します。それらのテストは、全ての Python 実装に対して堅牢です。概して、データデスクリプタは @ref{1272,,__name__} 属性や @code{__doc__} 属性も持ちますが、このことは保証されてはいません (一方でプロパティ、 getset デスクリプタ、メンバーデスクリプタはこれら2つの属性を両方持っています)。
@end deffn

@geindex isgetsetdescriptor() (inspect モジュール)
@anchor{library/inspect inspect isgetsetdescriptor}@anchor{4a28}
@deffn {の関数} inspect.isgetsetdescriptor (object)

オブジェクトが getset デスクリプタの場合に @code{True} を返します。

getset とは、拡張モジュールで @ref{db2,,PyGetSetDef} 構造体を用いて定義された属性のことです。そのような型を持たない Python 実装の場合は、このメソッドは常に @code{False} を返します。
@end deffn

@geindex ismemberdescriptor() (inspect モジュール)
@anchor{library/inspect inspect ismemberdescriptor}@anchor{4a29}
@deffn {の関数} inspect.ismemberdescriptor (object)

オブジェクトがメンバーデスクリプタの場合に @code{True} を返します。

メンバーデスクリプタとは、拡張モジュールで @ref{771,,PyMemberDef} 構造体を用いて定義された属性のことです。そのような型を持たない Python 実装の場合は、このメソッドは常に @code{False} を返します。
@end deffn

@node ソースコードの情報取得,Signature オブジェクトで呼び出し可能オブジェクトを内省する,型とメンバー,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect inspect-source}@anchor{4a2a}@anchor{library/inspect retrieving-source-code}@anchor{4a2b}
@subsubsection ソースコードの情報取得


@geindex getdoc() (inspect モジュール)
@anchor{library/inspect inspect getdoc}@anchor{bed}
@deffn {の関数} inspect.getdoc (object)

オブジェクトのドキュメンテーション文字列を、 @ref{1a2c,,cleandoc()} で整理した上で取得します。オブジェクトに対するドキュメンテーション文字列が与えられていない場合で、かつオブジェクトがクラス、メソッド、プロパティ、デスクリプタのいずれかである場合、継承の階層構造からドキュメンテーション文字列を探し出して返します。ドキュメンテーション文字列がないか、または不正な場合は @code{None} を返します。


バージョン 3.5 で変更: ドキュメンテーション文字列がオーバーライドされていない場合は継承されるようになりました。

@end deffn

@geindex getcomments() (inspect モジュール)
@anchor{library/inspect inspect getcomments}@anchor{1938}
@deffn {の関数} inspect.getcomments (object)

オブジェクトのソースコード直前 (クラス、関数、メソッドの場合) または Python ソースファイルの先頭 (モジュールの場合) の任意の行数にわたるコメントを、ひとつの文字列として返します。オブジェクトのソースコードが存在しない場合は @code{None} を返します。オブジェクトが C で定義されている場合や、対話型シェルで定義したオブジェクトの場合にこのようなことが起こり得ます。
@end deffn

@geindex getfile() (inspect モジュール)
@anchor{library/inspect inspect getfile}@anchor{1e85}
@deffn {の関数} inspect.getfile (object)

オブジェクトを定義している (テキストまたはバイナリの) ファイルの名前を返します。オブジェクトが組み込みモジュール、クラス、関数の場合は @ref{198,,TypeError} 例外が発生します。
@end deffn

@geindex getmodule() (inspect モジュール)
@anchor{library/inspect inspect getmodule}@anchor{1b6d}
@deffn {の関数} inspect.getmodule (object)

オブジェクトが定義されているモジュールの推定を試みます。モジュールが決められない場合は @code{None} を返します。
@end deffn

@geindex getsourcefile() (inspect モジュール)
@anchor{library/inspect inspect getsourcefile}@anchor{1b6e}
@deffn {の関数} inspect.getsourcefile (object)

オブジェクトが定義されている Python ソースファイルの名前を返します。ソースを取得する方法がない場合は @code{None} を返します。組み込みのモジュール、クラス、関数に対しては @ref{198,,TypeError} で失敗します。
@end deffn

@geindex getsourcelines() (inspect モジュール)
@anchor{library/inspect inspect getsourcelines}@anchor{17b7}
@deffn {の関数} inspect.getsourcelines (object)

オブジェクトを定義しているソースコードの行のリストと、定義の開始行番号を返します。引数にはモジュール、クラス、メソッド、関数、トレースバック、またはコードオブジェクトを渡すことができます。オブジェクトに対応するソースコードが行のリストとして返されます。また行番号は、元のソースファイル中でコードが見つかった最初の行を示します。ソースコードを探し出すことができなかった場合、 @ref{2c0,,OSError} 例外が送出されます。オブジェクトが組み込みのモジュール、クラス、または関数である場合は @ref{198,,TypeError} 例外が送出されます。


バージョン 3.3 で変更: @ref{125e,,IOError} の代わりに @ref{2c0,,OSError} を送出します。前者は後者のエイリアスです。

@end deffn

@geindex getsource() (inspect モジュール)
@anchor{library/inspect inspect getsource}@anchor{17c3}
@deffn {の関数} inspect.getsource (object)

オブジェクトを定義しているソースコードのテキストを返します。引数にはモジュール、クラス、メソッド、関数、トレースバック、フレーム、またはコードオブジェクトを渡すことができます。ソースコードはひとつの文字列として返されます。ソースコードを探し出すことができなかった場合、 @ref{2c0,,OSError} 例外が送出されます。オブジェクトが組み込みのモジュール、クラス、または関数である場合は @ref{198,,TypeError} 例外が送出されます。


バージョン 3.3 で変更: @ref{125e,,IOError} の代わりに @ref{2c0,,OSError} を送出します。前者は後者のエイリアスです。

@end deffn

@geindex cleandoc() (inspect モジュール)
@anchor{library/inspect inspect cleandoc}@anchor{1a2c}
@deffn {の関数} inspect.cleandoc (doc)

コードブロックと位置を合わせるためのインデントを docstring から削除します。

先頭行の行頭の空白文字は全て削除されます。
2行目以降では全行で同じ数の行頭の空白文字が、削除できるだけ削除されます。
その後、先頭と末尾の空白行が削除され、全てのタブが空白に展開されます。
@end deffn

@node Signature オブジェクトで呼び出し可能オブジェクトを内省する,クラスと関数<2>,ソースコードの情報取得,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect inspect-signature-object}@anchor{4a2c}@anchor{library/inspect introspecting-callables-with-the-signature-object}@anchor{4a2d}
@subsubsection Signature オブジェクトで呼び出し可能オブジェクトを内省する



Added in version 3.3.


@ref{4e3,,Signature} オブジェクトは、呼び出し可能オブジェクトの呼び出しシグネチャと戻り値のアノテーションを表現します。 @code{Signature} オブジェクトを取得するには、 @code{signature()} 関数を使ってください。

@geindex signature() (inspect モジュール)
@anchor{library/inspect inspect signature}@anchor{22f}
@deffn {の関数} inspect.signature (callable, *, follow_wrapped=True, globals=None, locals=None, eval_str=False, annotation_format=Format.VALUE)

`callable' で与えられたオブジェクトに対する @ref{4e3,,Signature} オブジェクトを返します:

@example
>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b: int, **kwargs)'

>>> str(sig.parameters['b'])
'b: int'

>>> sig.parameters['b'].annotation
<class 'int'>
@end example

単純な関数やクラスから、 @ref{217,,functools.partial()} オブジェクトまで、幅広い Python の呼び出し可能なオブジェクトを受け付けます。

アノテーションのいくつかが (たとえば @code{from __future__ import annotations} が使われていることを理由に) 文字列である場合、 @ref{22f,,signature()} は @ref{459,,annotationlib.get_annotations()} を使って「非文字列化」すなわち文字列アノテーションを解決して本来のアノテーションに戻すことを試みます。アノテーションの解決を行う際には `globals', `locals', および `eval_str' パラメータが @code{annotationlib.get_annotations()} に渡されます; これらのパラメータを使う方法についての説明は @code{annotationlib.get_annotations()} のドキュメンテーションを参照してください。返されるアノテーションの形式を制御するため、 `annotation_format' パラメータには @ref{230,,annotationlib.Format} 列挙型のメンバーを渡すことができます。たとえばアノテーションを文字列形式で返すためには @code{annotation_format=annotationlib.Format.STRING} を使ってください。

シグネチャを提供できない場合は @ref{2ec,,ValueError} 例外を送出します。またオブジェクトの型がサポートされていない場合は @ref{198,,TypeError} 例外を送出します。さらに、アノテーションが文字列化されており、 `eval_str' が偽でない場合、アノテーションを「非文字列化」するために @ref{459,,annotationlib.get_annotations()} 内部で呼ばれる @code{eval()} により、いかなる種類の例外も送出される可能性があります。

関数シグネチャにおけるスラッシュ (/) は、それより前のパラメータが位置専用引数であることを示します。より詳しい情報は、 @ref{25d6,,位置専用引数に関する FAQ エントリ} を参照してください。


バージョン 3.5 で変更: `follow_wrapped' パラメータが追加されました。parameter was added. 特に `callable' そのものについてのシグネチャを取得するためには @code{False} を指定してください (そうすることで、デコレータで修飾された呼び出し可能オブジェクトに対して`@w{`}callable.__wrapped__`@w{`} が使われなくなります)。



バージョン 3.10 で変更: `globals', `locals', および `eval_str' パラメータが追加されました。



バージョン 3.14 で変更: `annotation_format' パラメータが追加されました。


@cartouche
@quotation 注釈 
いくつかの呼び出し可能オブジェクトは、ある Python 実装の下ではイントロスペクション (実行時オブジェクト調査) ができないかもしれません。たとえば CPython では、 C で定義されたいくつかの組み込み関数はそれらの引数に関するメタデータを提供しません。
@end quotation
@end cartouche

渡されたオブジェクトが @code{__signature__} 属性を持つ場合、それにもとづいてシグネチャを作ることができるかもしれません。厳密なセマンティクスは実装レベルの詳細であり、予告なく変更される可能性があります。現在のセマンティクスについてはソースコードをを参照してください。
@end deffn

@geindex Signature (inspect のクラス)
@anchor{library/inspect inspect Signature}@anchor{4e3}
@deffn {クラス} inspect.Signature (parameters=None, *, return_annotation=Signature.empty)

@code{Signature} オブジェクトは、関数の呼び出しシグネチャと戻り値のアノテーションを表現します。このオブジェクトは @ref{4a2e,,parameters} 集合として、関数が受け取るパラメータそれぞれについての @ref{4e4,,Parameter} オブジェクトを保存します。

オプション引数 `parameters' は @ref{4e4,,Parameter} オブジェクトのシーケンスで、重複した名前のパラメータはないか、パラメータの並び順は正しいか、すなわち位置専用引数からはじまり次に位置引数としてもキーワード引数としても指定可能なパラメータが続くかどうか、またデフォルト値のあるパラメータがデフォルト値のないパラメータの後にあるかどうか、といった項目をチェックするための検証が行われます。

オプション引数 `return_annotation' は任意の Python オブジェクトをとることができます。この引数は、呼び出し可能オブジェクトの "戻り値" に対するアノテーションを表します。

@code{Signature} オブジェクトは `immutable' すなわち変更不可能です。変更されたコピーを生成するためには、 @ref{4a2f,,Signature.replace()} または @ref{1c0,,copy.replace()} を使ってください。


バージョン 3.5 で変更: @code{Signature} オブジェクトは pickle 可能かつ ハッシュ可能 になりました。


@geindex empty (inspect.Signature の属性)
@anchor{library/inspect inspect Signature empty}@anchor{4a30}
@deffn {の属性} empty

return アノテーションがないことを指すクラスレベルの特殊マーカです。
@end deffn

@geindex parameters (inspect.Signature の属性)
@anchor{library/inspect inspect Signature parameters}@anchor{4a2e}
@deffn {の属性} parameters

パラメータの名前と対応する @ref{4e4,,Parameter} オブジェクトの、順序ありマッピングです。パラメータは、キーワード専用パラメータも含めて、厳密な定義順に現れます。


バージョン 3.7 で変更: バージョン 3.7 までは、Python はキーワード専用パラメータだけしか順序を保つことを明確に保証していませんでした。とはいえ Python 3 では事実上パラメータの順序は維持されていました。

@end deffn

@geindex return_annotation (inspect.Signature の属性)
@anchor{library/inspect inspect Signature return_annotation}@anchor{4a31}
@deffn {の属性} return_annotation

呼び出し可能オブジェクトの "return" アノテーションです。呼び出し可能オブジェクトに "return" アノテーションがない場合、この属性は @ref{4a30,,Signature.empty} に設定されます。
@end deffn

@geindex bind() (inspect.Signature のメソッド)
@anchor{library/inspect inspect Signature bind}@anchor{1892}
@deffn {メソッド} bind (*args, **kwargs)

位置引数およびキーワード引数からパラメータへのマッピングを生成します。 @code{*args} と @code{**kwargs} がシグネチャに一致した場合 @ref{1275,,BoundArguments} を返します。引数がシグネチャと一致しない場合は @ref{198,,TypeError} 例外を送出します。
@end deffn

@geindex bind_partial() (inspect.Signature のメソッド)
@anchor{library/inspect inspect Signature bind_partial}@anchor{4a32}
@deffn {メソッド} bind_partial (*args, **kwargs)

@ref{1892,,Signature.bind()} と同様に動作しますが、いくつかの必要な引数を省略することができます (@ref{217,,functools.partial()} の振る舞いによく似たものです) 。 @ref{1275,,BoundArguments} を返します。引数がシグネチャと一致しない場合は @ref{198,,TypeError} 例外を送出します。
@end deffn

@geindex replace() (inspect.Signature のメソッド)
@anchor{library/inspect inspect Signature replace}@anchor{4a2f}
@deffn {メソッド} replace (*[, parameters][, return_annotation])

@ref{4a2f,,replace()} メソッドが呼び出されたインスタンスから、新しい @ref{4e3,,Signature} インスタンスを生成します。元になるシグネチャのプロパティをオーバーライドするために異なる `parameters' や `return_annotation' を渡すことが可能です。 @code{return_annotation} をコピーされた @code{Signature} インスタンスから削除したい場合、 @ref{4a30,,Signature.empty} を渡してください。

@example
>>> def test(a, b):
...     pass
...
>>> sig = signature(test)
>>> new_sig = sig.replace(return_annotation="new return anno")
>>> str(new_sig)
"(a, b) -> 'new return anno'"
@end example

@ref{4e3,,Signature} オブジェクトのコピーは、汎用の関数 @ref{1c0,,copy.replace()} でもサポートされています。
@end deffn

@geindex format() (inspect.Signature のメソッド)
@anchor{library/inspect inspect Signature format}@anchor{231}
@deffn {メソッド} format (*, max_width=None, quote_annotation_strings=True)

@ref{4e3,,Signature} オブジェクトの文字列表現を生成します。

`max_width' が指定されると、メソッドはシグネチャをそれぞれの行が最大 `max_width' 文字になるようにフォーマットを試みます。シグネチャが `max_width' よりも長くなってしまう場合は、全てのパラメータごとに改行されます。

`quote_annotation_strings' が偽の場合、文字列で表されたシグネチャの中の @ref{15c,,アノテーション} は、最初と最後のクォート記号無しで表示されます。この挙動は、シグネチャが @ref{160,,STRING} フォーマットで作られた場合や @code{from __future__ import annotations} が使われた場合に有用です。


Added in version 3.13.



バージョン 3.14 で変更: `unquote_annotations' パラメータが追加されました。

@end deffn

@geindex from_callable() (inspect.Signature のクラスメソッド)
@anchor{library/inspect inspect Signature from_callable}@anchor{942}
@deffn {メソッド} classmethod from_callable (obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)

与えられた呼び出し可能オブジェクト `obj' に対する @ref{4e3,,Signature} (またはそのサブクラスの) オブジェクトを返します。

このメソッドは @ref{4e3,,Signature} からサブクラスを作る作業を簡素化します:

@example
class MySignature(Signature):
    pass
sig = MySignature.from_callable(sum)
assert isinstance(sig, MySignature)
@end example

このメソッドの振る舞いは、上記を除けば @ref{22f,,signature()} と同じです。


Added in version 3.5.



バージョン 3.10 で変更: `globals', `locals', および `eval_str' パラメータが追加されました。

@end deffn
@end deffn

@geindex Parameter (inspect のクラス)
@anchor{library/inspect inspect Parameter}@anchor{4e4}
@deffn {クラス} inspect.Parameter (name, kind, *, default=Parameter.empty, annotation=Parameter.empty)

@code{Parameter} オブジェクトはイミュータブル (`immutable') すなわち変更不可能です。 @code{Parameter} オブジェクトを変更する代わりに、 @ref{4a33,,Parameter.replace()} や @ref{1c0,,copy.replace()} を使ってオブジェクトの内容を変更したコピーを作成することができます。


バージョン 3.5 で変更: Parameter オブジェクトはピックル化可能 (picklable) かつ ハッシュ化可能 (@ref{824,,hashable}) になりました。


@geindex empty (inspect.Parameter の属性)
@anchor{library/inspect inspect Parameter empty}@anchor{4a34}
@deffn {の属性} empty

デフォルト値とアノテーションがないことを指すクラスレベルの特殊マーカです。
@end deffn

@geindex name (inspect.Parameter の属性)
@anchor{library/inspect inspect Parameter name}@anchor{4a35}
@deffn {の属性} name

仮引数名 (文字列) です。名前は有効な Python 識別子でなければなりません。

CPython は内包表記やジェネレータ式を実装するためのコードオブジェクトにおいて、 @code{.0} という形式で暗黙のパラメータ名を生成します。


バージョン 3.6 で変更: このモジュールにより、これら暗黙のパラメータ名は @code{implicit0} のような名前で公開されるようになりました。

@end deffn

@geindex default (inspect.Parameter の属性)
@anchor{library/inspect inspect Parameter default}@anchor{4a36}
@deffn {の属性} default

引数のデフォルト値です。引数にデフォルト値がない場合、この属性は @ref{4a34,,Parameter.empty} に設定されます。
@end deffn

@geindex annotation (inspect.Parameter の属性)
@anchor{library/inspect inspect Parameter annotation}@anchor{4a37}
@deffn {の属性} annotation

引数のアノテーションです。引数にアノテーションがない場合、この属性は @ref{4a34,,Parameter.empty} に設定されます。
@end deffn

@geindex kind (inspect.Parameter の属性)
@anchor{library/inspect inspect Parameter kind}@anchor{4a38}
@deffn {の属性} kind

引数の値がどのようにパラメータと紐付けられるかを記述します。指定可能な値は @ref{4e4,,Parameter} を介して (@code{Parameter.KEYWORD_ONLY} のように) アクセス可能で、以下に示す順番で比較や順序付けをサポートしています:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名前

@tab

意味

@item

`POSITIONAL_ONLY'

@tab

値は位置引数として渡されなければなりません。 Python の関数定義において、位置専用引数は (もし存在すれば) @code{/} エントリの前に現れるものを指します。

@item

`POSITIONAL_OR_KEYWORD'

@tab

値をキーワードまたは位置引数として渡すことができます (これは Python で実装された関数の標準的な束縛動作です)。

@item

`VAR_POSITIONAL'

@tab

その他の仮引数に束縛されていない位置引数のタプルです。Python の関数定義における @code{*args} 仮引数に対応します。

@item

`KEYWORD_ONLY'

@tab

値をキーワード引数として渡さなければなりません。キーワード専用引数は Python の関数定義において @code{*} や @code{*args} の後に現れる引数です。

@item

`VAR_KEYWORD'

@tab

その他の仮引数に束縛されていないキーワード引数の辞書です。Python の関数定義における @code{**kwargs} 仮引数に対応します。

@end multitable


例: デフォルト値を持たないキーワード専用引数を全て出力します:

@example
>>> def foo(a, b, *, c, d=10):
...     pass

>>> sig = signature(foo)
>>> for param in sig.parameters.values():
...     if (param.kind == param.KEYWORD_ONLY and
...                        param.default is param.empty):
...         print('Parameter:', param)
Parameter: c
@end example
@end deffn

@geindex description (inspect.Parameter.kind の属性)
@anchor{library/inspect inspect Parameter kind description}@anchor{4a39}
@deffn {の属性} kind.description

@ref{4a38,,Parameter.kind} 列挙型の各定数を説明します。


Added in version 3.8.


例: 全ての引数に対する説明を出力します:

@example
>>> def foo(a, b, *, c, d=10):
...     pass

>>> sig = signature(foo)
>>> for param in sig.parameters.values():
...     print(param.kind.description)
positional or keyword
positional or keyword
keyword-only
keyword-only
@end example
@end deffn

@geindex replace() (inspect.Parameter のメソッド)
@anchor{library/inspect inspect Parameter replace}@anchor{4a33}
@deffn {メソッド} replace (*[, name][, kind][, default][, annotation])

このメソッドの呼び出し元のインスタンスをもとにして、新たな @ref{4e4,,Parameter} インスタンスを生成します。 @code{Parameter} の属性をオーバーライドするには、対応する引数をこのメソッドに渡してください。 @code{Parameter} からデフォルト値やアノテーションを取り除きたい場合は、 @ref{4a34,,Parameter.empty} を渡してください。

@example
>>> from inspect import Parameter
>>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
>>> str(param)
'foo=42'

>>> str(param.replace()) # Will create a shallow copy of 'param'
'foo=42'

>>> str(param.replace(default=Parameter.empty, annotation='spam'))
"foo: 'spam'"
@end example

@ref{4e4,,Parameter} オブジェクトは汎用関数 @ref{1c0,,copy.replace()} でもサポートされています。
@end deffn


バージョン 3.4 で変更: Python 3.3 では、@code{kind} が @code{POSITIONAL_ONLY} の場合に限り、 @code{name} が @code{None} であるような @ref{4e4,,Parameter} オブジェクトが許されていました。ですが、そのようなオブジェクトはもはや許可されていません。

@end deffn

@geindex BoundArguments (inspect のクラス)
@anchor{library/inspect inspect BoundArguments}@anchor{1275}
@deffn {クラス} inspect.BoundArguments

@ref{1892,,Signature.bind()} または @ref{4a32,,Signature.bind_partial()} を呼び出して得られる結果です。引数と関数のパラメータとの間のマッピング情報を保持します。

@geindex arguments (inspect.BoundArguments の属性)
@anchor{library/inspect inspect BoundArguments arguments}@anchor{b08}
@deffn {の属性} arguments

パラメータの名前と引数の値との間のミュータブルなマッピングです。明示的に紐付けされた引数だけを含みます。 @ref{b08,,arguments} に対する変更は @ref{4a3a,,args} と @ref{4a3b,,kwargs} に反映されます。

いかなる引数処理の目的でも、 @ref{4a2e,,Signature.parameters} とあわせて使うようにしてください。

@cartouche
@quotation 注釈 
@ref{1892,,Signature.bind()} または @ref{4a32,,Signature.bind_partial()} でデフォルト値をあてにするとされた引数は、スキップされます。それらをマッピングに加えたい場合は、必要に応じて @ref{1016,,BoundArguments.apply_defaults()} を使ってください。
@end quotation
@end cartouche


バージョン 3.9 で変更: @ref{b08,,arguments} の型が @ref{183,,dict} になりました。以前は @ref{7f3,,collections.OrderedDict} 型でした。

@end deffn

@geindex args (inspect.BoundArguments の属性)
@anchor{library/inspect inspect BoundArguments args}@anchor{4a3a}
@deffn {の属性} args

位置引数の値のタプルです。@ref{b08,,arguments} 属性から動的に計算されます。
@end deffn

@geindex kwargs (inspect.BoundArguments の属性)
@anchor{library/inspect inspect BoundArguments kwargs}@anchor{4a3b}
@deffn {の属性} kwargs

キーワード引数の値の辞書です。 @ref{b08,,arguments} 属性から動的に計算されます。位置引数として渡すことができる引数は、 @ref{4a3a,,args} に含まれることに注意してください。
@end deffn

@geindex signature (inspect.BoundArguments の属性)
@anchor{library/inspect inspect BoundArguments signature}@anchor{4a3c}
@deffn {の属性} signature

親の @ref{4e3,,Signature} オブジェクトへの参照です。
@end deffn

@geindex apply_defaults() (inspect.BoundArguments のメソッド)
@anchor{library/inspect inspect BoundArguments apply_defaults}@anchor{1016}
@deffn {メソッド} apply_defaults ()

存在しない引数のデフォルト値を設定します。

可変長位置引数 (@code{*args}) に対するデフォルト値は、空のタプルです。

可変長キーワード引数 (@code{**kwargs}) に対するデフォルト値は、空の辞書です。

@example
>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
@{'a': 'spam', 'b': 'ham', 'args': ()@}
@end example


Added in version 3.5.

@end deffn

@ref{4a3a,,args} と @ref{4a3b,,kwargs} の2つのプロパティは、関数の呼び出しに使うことができます:

@example
def test(a, *, b):
    ...

sig = signature(test)
ba = sig.bind(10, b=20)
test(*ba.args, **ba.kwargs)
@end example
@end deffn


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 362

@item PEP 362@footnote{https://peps.python.org/pep-0362/}: - 関数シグニチャオブジェクト

仕様の詳細、実装の詳細および使用例を示しています。
@end table


@node クラスと関数<2>,インタープリタスタック,Signature オブジェクトで呼び出し可能オブジェクトを内省する,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect classes-and-functions}@anchor{4a3d}@anchor{library/inspect inspect-classes-functions}@anchor{4a3e}
@subsubsection クラスと関数


@geindex getclasstree() (inspect モジュール)
@anchor{library/inspect inspect getclasstree}@anchor{4a3f}
@deffn {の関数} inspect.getclasstree (classes, unique=False)

リストで指定したクラスの継承関係から、ネストしたリストを作成します。ネストしたリストには、直前の要素から派生したクラスが格納されます。各要素は長さ2のタプルで、クラスと基底クラスのタプルを格納しています。`unique' が真の場合、各クラスは戻り値のリスト内に一つだけしか格納されません。真でなければ、多重継承を利用したクラスとその派生クラスは複数回格納される場合があります。
@end deffn

@geindex getfullargspec() (inspect モジュール)
@anchor{library/inspect inspect getfullargspec}@anchor{941}
@deffn {の関数} inspect.getfullargspec (func)

Python 関数のパラメータの名前とデフォルト値を取得します。 @ref{85e,,named tuple} を返します:

@code{FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
annotations)}

`args' は位置引数の名前のリストです。 `varargs' は @code{*} で始まる可変長位置引数の名前で、この引数を受け付けない場合は @code{None} です。 `varkw' は @code{**} で始まる可変長キーワード引数の名前で、この引数を受け付けない場合は @code{None} です。 `defaults' は末尾 `n' 個の位置引数に対応するデフォルト引数の `n'-タプルで、 そのようなデフォルト値が定義されていない場合は @code{None} です。 `kwonlyargs' は宣言順に並んだキーワード専用引数の名前のリストです。 `kwonlydefaults' はそれらに対して値が渡されなかった場合の、 `kwonlyargs' の名前からデフォルト値へのマッピングを行う辞書です。 `annotations' 引数名からアノテーションへのマッピングを行う辞書です。特殊キー @code{"return"} は (もしあれば) 関数の戻り値に対するアノテーションを伝えるために使われます。

@ref{22f,,signature()} と @ref{4a2c,,Signature オブジェクト} が呼び出し可能オブジェクトのイントロスペクション (実行時オブジェクト調査) のための推奨される API を提供しており、かつ拡張モジュール API でときどき遭遇する追加の振る舞い (位置専用引数など) もサポートしていることに注意してください。この関数は、主に Python 2 の @code{inspect} モジュール API との互換性を維持することが必要なコードで利用されるために残されています。


バージョン 3.4 で変更: この関数は @ref{22f,,signature()} をもとに実装されています。ただし、 @code{__wrapped__} 属性を無視します。また、束縛されたメソッドに対するシグネチャの出力において、すでに束縛された最初のパラメータを含みます。



バージョン 3.6 で変更: This method was previously documented as deprecated in favour of
@ref{22f,,signature()} 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
@code{getargspec()} API.



バージョン 3.7 で変更: バージョン 3.7 までは、Python はキーワード専用パラメータだけしか順序を保つことを明確に保証していませんでした。とはいえ Python 3 では事実上パラメータの順序は維持されていました。

@end deffn

@geindex getargvalues() (inspect モジュール)
@anchor{library/inspect inspect getargvalues}@anchor{10bf}
@deffn {の関数} inspect.getargvalues (frame)

指定したフレームに渡された引数の情報を取得します。戻り値は @ref{85e,,名前付きタプル} @code{ArgInfo(args, varargs, keywords, locals)} です。`args' は引数名のリストです。 `varargs' と `keywords' は @code{*} 引数と @code{**} 引数の名前で、引数がなければ @code{None} となります。 `locals' は指定したフレームのローカル変数の辞書です。

@cartouche
@quotation 注釈 
この関数は Python 3.5 において、不注意により非推奨とされていました。
@end quotation
@end cartouche
@end deffn

@geindex formatargvalues() (inspect モジュール)
@anchor{library/inspect inspect formatargvalues}@anchor{10c0}
@deffn {の関数} inspect.formatargvalues (args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])

@ref{10bf,,getargvalues()} で取得した4つの値を読みやすく整形します。 format* 引数はオプションで、名前と値を文字列に変換する整形関数を指定することができます。

@cartouche
@quotation 注釈 
この関数は Python 3.5 において、不注意により非推奨とされていました。
@end quotation
@end cartouche
@end deffn

@geindex getmro() (inspect モジュール)
@anchor{library/inspect inspect getmro}@anchor{4a40}
@deffn {の関数} inspect.getmro (cls)

`cls' クラスの基底クラス (`cls' 自身も含む) を、メソッドの優先順位順に並べたタプルを返します。結果のリスト内で各クラスは一度だけ格納されます。メソッドの優先順位はクラスの型によって異なります。非常に特殊なユーザ定義のメタクラスを使用していない限り、`cls' が戻り値の先頭要素となります。
@end deffn

@geindex getcallargs() (inspect モジュール)
@anchor{library/inspect inspect getcallargs}@anchor{10be}
@deffn {の関数} inspect.getcallargs (func, /, *args, **kwds)

`args' と `kwds' を、あたかもそれらをパラメータとして呼ばれたかのように、 Python 関数またはメソッド `func' に束縛します。また、第一引数 (通常 @code{self} という名前です) を関連するインスタンスに束縛します。引数名 (もし存在すれば @code{*} や @code{**} で始まる引数も含む) を `args' および `kwds' で与えられた値にマッピングする辞書を返します。 `func' を不正に呼び出した場合、すなわち @code{func(*args, **kwds)} の呼び出しが不完全なシグネチャにより例外を送出するような場合は、同じ型の例外を同一またはよく似たメッセージとともに送出します。以下は使用例です:

@example
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
...     pass
...
>>> getcallargs(f, 1, 2, 3) == @{'a': 1, 'named': @{@}, 'b': 2, 'pos': (3,)@}
True
>>> getcallargs(f, a=2, x=4) == @{'a': 2, 'named': @{'x': 4@}, 'b': 1, 'pos': ()@}
True
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'
@end example


Added in version 3.2.



バージョン 3.5 で非推奨: 代わりに @ref{1892,,Signature.bind()} や @ref{4a32,,Signature.bind_partial()} を使ってください。

@end deffn

@geindex getclosurevars() (inspect モジュール)
@anchor{library/inspect inspect getclosurevars}@anchor{12ec}
@deffn {の関数} inspect.getclosurevars (func)

Python 関数またはメソッド `func' の外部の名前参照と、それらの現在の値のマッピングを取得します。 @ref{85e,,named tuple} @code{ClosureVars(nonlocals, globals, builtins, unbound)} を返します。参照名を、 `nonlocals' はレキシカルクロージャ変数、すなわち外側のスコープで定義された変数の値にマップし、 `globals' は関数が属するモジュールのグローバル変数にマップし、 `builtins' は関数本体から見える組み込み変数にマップします。 `unbound' は、現在のモジュールにおけるグローバル変数や組み込み変数において解決できないにもかかわらず、関数内で参照されている名前の集合です。

`func' が Python の関数やメソッドでない場合 @ref{198,,TypeError} が送出されます。


Added in version 3.3.

@end deffn

@geindex unwrap() (inspect モジュール)
@anchor{library/inspect inspect unwrap}@anchor{115e}
@deffn {の関数} inspect.unwrap (func, *, stop=None)

`func' によりラップされたオブジェクトを取得します。 @code{__wrapped__} 属性の連鎖をたどり、ラップの連鎖の最後にあるオブジェクトを返します。

`stop' はオプションで指定可能なコールバック関数で、ラッパーの連鎖におけるオブジェクトをただひとつの引数として取ります。このコールバック関数が真値を返した段階で、オブジェクトのアンラップを早期に終了させることができます。コールバック関数が真値を返さない場合は、通常通りラッパーの連鎖における最後のオブジェクトを返します。例えば、 @ref{22f,,signature()} は、オブジェクトに @code{__signature__} 属性が定義されていたらオブジェクトのアンラップを停止するために、このオプションを使っています。

循環を検知した場合は @ref{2ec,,ValueError} を送出します。


Added in version 3.4.

@end deffn

@geindex get_annotations() (inspect モジュール)
@anchor{library/inspect inspect get_annotations}@anchor{a14}
@deffn {の関数} inspect.get_annotations (obj, *, globals=None, locals=None, eval_str=False, format=annotationlib.Format.VALUE)

オブジェクトに対するアノテーション辞書を計算します。

これは @ref{459,,annotationlib.get_annotations()} のエイリアスです; 詳細はその関数のドキュメントを参照してください。

@cartouche
@quotation 注意 
This function may execute arbitrary code contained in annotations.
See @ref{4518,,Security implications of introspecting annotations} for more information.
@end quotation
@end cartouche


Added in version 3.10.



バージョン 3.14 で変更: この関数は @ref{459,,annotationlib.get_annotations()} のエイリアスになりました。 @code{inspect.get_annotations} として呼び出しても、引き続き正しく動作します。

@end deffn

@node インタープリタスタック,属性の静的なフェッチ,クラスと関数<2>,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect inspect-stack}@anchor{4a41}@anchor{library/inspect the-interpreter-stack}@anchor{4a42}
@subsubsection インタープリタスタック


以下の関数のうちいくつかは @ref{85c,,FrameInfo} オブジェクトを返します。これらのオブジェクトは、後方互換性のために @code{positions} を除く全ての属性に対して、タプル的な演算を許可します。この振る舞いは非推奨と考えられており、将来削除されるかもしれません。

@geindex FrameInfo (inspect のクラス)
@anchor{library/inspect inspect FrameInfo}@anchor{85c}
@deffn {クラス} inspect.FrameInfo

@geindex frame (inspect.FrameInfo の属性)
@anchor{library/inspect inspect FrameInfo frame}@anchor{4a43}
@deffn {の属性} frame

そのレコードに相当する @ref{8ef,,フレームオブジェクト} です。
@end deffn

@geindex filename (inspect.FrameInfo の属性)
@anchor{library/inspect inspect FrameInfo filename}@anchor{4a44}
@deffn {の属性} filename

このレコードに相当するフレームによって実行されるコードのファイル名です。
@end deffn

@geindex lineno (inspect.FrameInfo の属性)
@anchor{library/inspect inspect FrameInfo lineno}@anchor{4a45}
@deffn {の属性} lineno

このレコードに相当するフレームによって実行されるコードの、現在の行の行番号です。
@end deffn

@geindex function (inspect.FrameInfo の属性)
@anchor{library/inspect inspect FrameInfo function}@anchor{4a46}
@deffn {の属性} function

このレコードに相当するフレームによって実行される関数名です。
@end deffn

@geindex code_context (inspect.FrameInfo の属性)
@anchor{library/inspect inspect FrameInfo code_context}@anchor{4a47}
@deffn {の属性} code_context

このレコードに相当するフレームによって実行される、ソースコードから生成されたコンテキストの行のリストです。
@end deffn

@geindex index (inspect.FrameInfo の属性)
@anchor{library/inspect inspect FrameInfo index}@anchor{4a48}
@deffn {の属性} index

@ref{4a47,,code_context} リストにおいて実行される現在の行のインデックスです。
@end deffn

@geindex positions (inspect.FrameInfo の属性)
@anchor{library/inspect inspect FrameInfo positions}@anchor{4a49}
@deffn {の属性} positions

このレコードに相当するフレームによって実行される命令に結びついた @ref{1940,,dis.Positions} オブジェクトで、開始行番号、終了行番号、開始カラムオフセット、終了カラムオフセットを含んでいます。
@end deffn


バージョン 3.5 で変更: @ref{614,,tuple} ではなく @ref{85e,,named tuple} を返すようになりました。



バージョン 3.11 で変更: @code{FrameInfo} はクラスインスタンスになりました (ただしそれ以前の @ref{85e,,named tuple} とは後方互換です) 。

@end deffn

@geindex Traceback (inspect のクラス)
@anchor{library/inspect inspect Traceback}@anchor{85d}
@deffn {クラス} inspect.Traceback

@geindex filename (inspect.Traceback の属性)
@anchor{library/inspect inspect Traceback filename}@anchor{4a4a}
@deffn {の属性} filename

このトレースバックに対応するフレームによって実行されるコードのファイル名です。
@end deffn

@geindex lineno (inspect.Traceback の属性)
@anchor{library/inspect inspect Traceback lineno}@anchor{4a4b}
@deffn {の属性} lineno

このトレースバックに対応するフレームによって実行されるコードの、現在の行の行番号です。
@end deffn

@geindex function (inspect.Traceback の属性)
@anchor{library/inspect inspect Traceback function}@anchor{4a4c}
@deffn {の属性} function

このトレースバックに対応するフレームによって実行される関数名です。
@end deffn

@geindex code_context (inspect.Traceback の属性)
@anchor{library/inspect inspect Traceback code_context}@anchor{4a4d}
@deffn {の属性} code_context

このトレースバックに対応するフレームによって実行される、ソースコードから生成されたコンテキストの行のリストです。
@end deffn

@geindex index (inspect.Traceback の属性)
@anchor{library/inspect inspect Traceback index}@anchor{4a4e}
@deffn {の属性} index

@ref{4a4d,,code_context} リストにおいて実行される現在の行のインデックスです。
@end deffn

@geindex positions (inspect.Traceback の属性)
@anchor{library/inspect inspect Traceback positions}@anchor{4a4f}
@deffn {の属性} positions

このトレースバックに対応するフレームによって実行される命令の開始行番号、終了行番号、開始カラムオフセット、終了カラムオフセットを含む @ref{1940,,dis.Positions} オブジェクトです。
@end deffn


バージョン 3.11 で変更: @code{Traceback} はクラスインスタンスになりました (ただしそれ以前の @ref{85e,,named tuple} とは後方互換です) 。

@end deffn

@cartouche
@quotation 注釈 
フレームレコードの最初の要素などのフレームオブジェクトへの参照を保存すると、循環参照になってしまう場合があります。循環参照ができると、Python の循環参照検出機能を有効にしていたとしても関連するオブジェクトが参照しているすべてのオブジェクトが解放されにくくなり、明示的に参照を削除しないとメモリ消費量が増大する恐れがあります。

参照の削除を Python の循環参照検出機能にまかせることもできますが、 @ref{1b0,,finally} 節で循環参照を解除すれば確実にフレーム (とそのローカル変数) は削除されます。また、循環参照検出機能は Python のコンパイルオプションや @ref{4a0f,,gc.disable()} で無効とされている場合がありますので注意が必要です。例:

@example
def handle_stackframe_without_leak():
    frame = inspect.currentframe()
    try:
        # フレーム上で何か処理をします
    finally:
        del frame
@end example

(たとえばトレースバックをあとで表示したいなどの理由で) フレームを削除せずにとっておきたい場合は、 @ref{585,,frame.clear()} メソッドを使って循環参照を壊すこともできます。
@end quotation
@end cartouche

以下の関数でオプション引数 `context' には、戻り値のソース行リストに何行分のソースを含めるかを指定します。ソース行リストには、実行中の行を中心として指定された行数分のリストを返します。

@geindex getframeinfo() (inspect モジュール)
@anchor{library/inspect inspect getframeinfo}@anchor{85f}
@deffn {の関数} inspect.getframeinfo (frame, context=1)

フレームまたはトレースバックオブジェクトの情報を取得します。 @ref{85d,,Traceback} オブジェクトが返されます。


バージョン 3.11 で変更: 名前付きタプルの代わりに @ref{85d,,Traceback} オブジェクトが返されるようになりました。

@end deffn

@geindex getouterframes() (inspect モジュール)
@anchor{library/inspect inspect getouterframes}@anchor{860}
@deffn {の関数} inspect.getouterframes (frame, context=1)

指定したフレームと、その外側の全フレームの @ref{85c,,FrameInfo} オブジェクトのリストを取得します。外側のフレームとは `frame' が生成されるまでのすべての関数呼び出しを示します。戻り値のリストの先頭は `frame' のフレームレコードで、末尾の要素は `frame' のスタックにある最も外側のフレームのフレームレコードとなります。


バージョン 3.5 で変更: @ref{85e,,名前付きタプル} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} のリストが返されます。



バージョン 3.11 で変更: @ref{85c,,FrameInfo} オブジェクトのリストが返されるようになりました。

@end deffn

@geindex getinnerframes() (inspect モジュール)
@anchor{library/inspect inspect getinnerframes}@anchor{861}
@deffn {の関数} inspect.getinnerframes (traceback, context=1)

トレースバックのフレームと、その内側の全フレームの  @ref{85c,,FrameInfo} オブジェクトのリストを取得します。内のフレームとは `frame' から続く一連の関数呼び出しを示します。戻り値のリストの先頭は `traceback' のフレームレコードで、末尾の要素は例外が発生した位置を示します。


バージョン 3.5 で変更: @ref{85e,,名前付きタプル} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} のリストが返されます。



バージョン 3.11 で変更: @ref{85c,,FrameInfo} オブジェクトのリストが返されるようになりました。

@end deffn

@geindex currentframe() (inspect モジュール)
@anchor{library/inspect inspect currentframe}@anchor{8f1}
@deffn {の関数} inspect.currentframe ()

呼び出し元のフレームオブジェクトを返します。

この関数はインタプリタの Python スタックフレームサポートに依存します。これは Python のすべての実装に存在している保証はありません。Python スタックフレームサポートのない環境では、この関数は @code{None} を返します。
@end deffn

@geindex stack() (inspect モジュール)
@anchor{library/inspect inspect stack}@anchor{862}
@deffn {の関数} inspect.stack (context=1)

呼び出し元スタックの @ref{85c,,FrameInfo} オブジェクトのリストを返します。最初の要素は呼び出し元のフレームレコードで、末尾の要素はスタックにある最も外側のフレームのフレームレコードとなります。


バージョン 3.5 で変更: @ref{85e,,名前付きタプル} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} のリストが返されます。



バージョン 3.11 で変更: @ref{85c,,FrameInfo} オブジェクトのリストが返されるようになりました。

@end deffn

@geindex trace() (inspect モジュール)
@anchor{library/inspect inspect trace}@anchor{863}
@deffn {の関数} inspect.trace (context=1)

実行中のフレームと処理中の例外が発生したフレームの間の @ref{85c,,FrameInfo} オブジェクトのリストを返します。最初の要素は呼び出し元のフレームレコードで、末尾の要素は例外が発生した位置を示します。


バージョン 3.5 で変更: @ref{85e,,名前付きタプル} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} のリストが返されます。



バージョン 3.11 で変更: @ref{85c,,FrameInfo} オブジェクトのリストが返されるようになりました。

@end deffn

@node 属性の静的なフェッチ,Current State of Generators Coroutines and Asynchronous Generators,インタープリタスタック,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect fetching-attributes-statically}@anchor{4a50}
@subsubsection 属性の静的なフェッチ


@ref{dca,,getattr()} や @ref{6f9,,hasattr()} は属性の存在確認や属性値の取得に際してコードの実行を伴うことがあります。プロパティなどのデスクリプタが呼び出され、また @ref{6fa,,__getattr__()} や @ref{dcb,,__getattribute__()} が呼び出されたりするかもしれません。

たとえばドキュメントツールのように受動的なイントロスペクションをしたい場合、この振る舞いは不便です。 @ref{6bc,,getattr_static()} は @ref{dca,,getattr()} と同じシグネチャを持ちますが、属性値を取得する際にコードの実行をしないようにします。

@geindex getattr_static() (inspect モジュール)
@anchor{library/inspect inspect getattr_static}@anchor{6bc}
@deffn {の関数} inspect.getattr_static (obj, attr, default=None)

Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, @ref{6fa,,__getattr__()}
or @ref{dcb,,__getattribute__()}.

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 @ref{77d,,__dict__} is shadowed by another member (for
example a property) then this function will be unable to find instance
members.


Added in version 3.2.

@end deffn

@ref{6bc,,getattr_static()} 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
# example code for resolving the builtin descriptor types
class _foo:
    __slots__ = ['foo']

slot_descriptor = type(_foo.foo)
getset_descriptor = type(type(open(__file__)).name)
wrapper_descriptor = type(str.__dict__['__add__'])
descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)

result = getattr_static(some_object, 'foo')
if type(result) in descriptor_types:
    try:
        result = result.__get__()
    except AttributeError:
        # descriptors can raise AttributeError to
        # indicate there is no underlying value
        # in which case the descriptor itself will
        # have to do
        pass
@end example

@node Current State of Generators Coroutines and Asynchronous Generators,Code Objects Bit Flags,属性の静的なフェッチ,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect current-state-of-generators-coroutines-and-asynchronous-generators}@anchor{4a51}
@subsubsection Current State of Generators, Coroutines, and Asynchronous Generators


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. @ref{144e,,getgeneratorstate()} allows the current state of a
generator to be determined easily.

@geindex getgeneratorstate() (inspect モジュール)
@anchor{library/inspect inspect getgeneratorstate}@anchor{144e}
@deffn {の関数} inspect.getgeneratorstate (generator)

ジェネレータイテレータの現在の状態を取得します。

取り得る状態は:


@itemize *

@item 
GEN_CREATED: 実行開始を待機しています。

@item 
GEN_RUNNING: インタープリタによって現在実行されています。

@item 
GEN_SUSPENDED: yield 式で現在サスペンドされています。

@item 
GEN_CLOSED: 実行が完了しました。
@end itemize


Added in version 3.2.

@end deffn

@geindex getcoroutinestate() (inspect モジュール)
@anchor{library/inspect inspect getcoroutinestate}@anchor{101a}
@deffn {の関数} inspect.getcoroutinestate (coroutine)

Get current state of a coroutine object.  The function is intended to be
used with coroutine objects created by @ref{7ed,,async def} functions, but
will accept any coroutine-like object that has @code{cr_running} and
@code{cr_frame} attributes.

取り得る状態は:


@itemize *

@item 
CORO_CREATED: 実行開始を待機しています。

@item 
CORO_RUNNING: インタープリタにより現在実行中です。

@item 
CORO_SUSPENDED: await 式により現在停止中です。

@item 
CORO_CLOSED: 実行が完了しました。
@end itemize


Added in version 3.5.

@end deffn

@geindex getasyncgenstate() (inspect モジュール)
@anchor{library/inspect inspect getasyncgenstate}@anchor{6ba}
@deffn {の関数} inspect.getasyncgenstate (agen)

Get current state of an asynchronous generator object.  The function is
intended to be used with asynchronous iterator objects created by
@ref{7ed,,async def} functions which use the @ref{bc2,,yield} statement,
but will accept any asynchronous generator-like object that has
@code{ag_running} and @code{ag_frame} attributes.

取り得る状態は:


@itemize *

@item 
AGEN_CREATED: Waiting to start execution.

@item 
AGEN_RUNNING: Currently being executed by the interpreter.

@item 
AGEN_SUSPENDED: Currently suspended at a yield expression.

@item 
AGEN_CLOSED: Execution has completed.
@end itemize


Added in version 3.12.

@end deffn

ジェネレータの現在の内部状態を問い合わせることも出来ます。これは主に内部状態が期待通り更新されているかどうかを確認するためのテストの目的に有用です。

@geindex getgeneratorlocals() (inspect モジュール)
@anchor{library/inspect inspect getgeneratorlocals}@anchor{12ed}
@deffn {の関数} 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 @ref{46f,,locals()} in the body of the
generator, and all the same caveats apply.

If `generator' is a @ref{126c,,generator} with no currently associated frame,
then an empty dictionary is returned.  @ref{198,,TypeError} is raised if
`generator' is not a Python generator object.

`CPython 実装の詳細:' 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.


Added in version 3.3.

@end deffn

@geindex getcoroutinelocals() (inspect モジュール)
@anchor{library/inspect inspect getcoroutinelocals}@anchor{1019}
@deffn {の関数} inspect.getcoroutinelocals (coroutine)

This function is analogous to @ref{12ed,,getgeneratorlocals()}, but
works for coroutine objects created by @ref{7ed,,async def} functions.


Added in version 3.5.

@end deffn

@geindex getasyncgenlocals() (inspect モジュール)
@anchor{library/inspect inspect getasyncgenlocals}@anchor{6bb}
@deffn {の関数} inspect.getasyncgenlocals (agen)

This function is analogous to @ref{12ed,,getgeneratorlocals()}, but
works for asynchronous generator objects created by @ref{7ed,,async def}
functions which use the @ref{bc2,,yield} statement.


Added in version 3.12.

@end deffn

@node Code Objects Bit Flags,Buffer flags,Current State of Generators Coroutines and Asynchronous Generators,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect code-objects-bit-flags}@anchor{4a52}@anchor{library/inspect inspect-module-co-flags}@anchor{2392}
@subsubsection Code Objects Bit Flags


Python code objects have a @ref{18db,,co_flags} attribute,
which is a bitmap of the following flags:

@geindex CO_OPTIMIZED (inspect モジュール)
@anchor{library/inspect inspect CO_OPTIMIZED}@anchor{4a53}
@deffn {データ} inspect.CO_OPTIMIZED

The code object is optimized, using fast locals.
@end deffn

@geindex CO_NEWLOCALS (inspect モジュール)
@anchor{library/inspect inspect CO_NEWLOCALS}@anchor{4a54}
@deffn {データ} inspect.CO_NEWLOCALS

If set, a new dict will be created for the frame's @ref{4a5,,f_locals}
when the code object is executed.
@end deffn

@geindex CO_VARARGS (inspect モジュール)
@anchor{library/inspect inspect CO_VARARGS}@anchor{4a55}
@deffn {データ} inspect.CO_VARARGS

The code object has a variable positional parameter (@code{*args}-like).
@end deffn

@geindex CO_VARKEYWORDS (inspect モジュール)
@anchor{library/inspect inspect CO_VARKEYWORDS}@anchor{4a56}
@deffn {データ} inspect.CO_VARKEYWORDS

The code object has a variable keyword parameter (@code{**kwargs}-like).
@end deffn

@geindex CO_NESTED (inspect モジュール)
@anchor{library/inspect inspect CO_NESTED}@anchor{4a57}
@deffn {データ} inspect.CO_NESTED

The flag is set when the code object is a nested function.
@end deffn

@geindex CO_GENERATOR (inspect モジュール)
@anchor{library/inspect inspect CO_GENERATOR}@anchor{4a58}
@deffn {データ} 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.
@end deffn

@geindex CO_COROUTINE (inspect モジュール)
@anchor{library/inspect inspect CO_COROUTINE}@anchor{4a59}
@deffn {データ} 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 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} for more details.


Added in version 3.5.

@end deffn

@geindex CO_ITERABLE_COROUTINE (inspect モジュール)
@anchor{library/inspect inspect CO_ITERABLE_COROUTINE}@anchor{4a5a}
@deffn {データ} inspect.CO_ITERABLE_COROUTINE

The flag is used to transform generators into generator-based
coroutines.  Generator objects with this flag can be used in
@code{await} expression, and can @code{yield from} coroutine objects.
See 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} for more details.


Added in version 3.5.

@end deffn

@geindex CO_ASYNC_GENERATOR (inspect モジュール)
@anchor{library/inspect inspect CO_ASYNC_GENERATOR}@anchor{4a5b}
@deffn {データ} 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 
@geindex Python Enhancement Proposals; PEP 525
PEP 525@footnote{https://peps.python.org/pep-0525/} for more details.


Added in version 3.6.

@end deffn

@geindex CO_HAS_DOCSTRING (inspect モジュール)
@anchor{library/inspect inspect CO_HAS_DOCSTRING}@anchor{2394}
@deffn {データ} inspect.CO_HAS_DOCSTRING

The flag is set when there is a docstring for the code object in
the source code. If set, it will be the first item in
@ref{189b,,co_consts}.


Added in version 3.14.

@end deffn

@geindex CO_METHOD (inspect モジュール)
@anchor{library/inspect inspect CO_METHOD}@anchor{4a5c}
@deffn {データ} inspect.CO_METHOD

The flag is set when the code object is a function defined in class
scope.


Added in version 3.14.

@end deffn

@cartouche
@quotation 注釈 
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 @code{inspect} module
for any introspection needs.
@end quotation
@end cartouche

@node Buffer flags,コマンドライン・インターフェース<10>,Code Objects Bit Flags,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect buffer-flags}@anchor{4a5d}
@subsubsection Buffer flags


@geindex BufferFlags (inspect のクラス)
@anchor{library/inspect inspect BufferFlags}@anchor{68d}
@deffn {クラス} inspect.BufferFlags

This is an @ref{e9a,,enum.IntFlag} that represents the flags that
can be passed to the @ref{68c,,__buffer__()} method of objects
implementing the @ref{260,,buffer protocol}.

The meaning of the flags is explained at @ref{1249,,バッファリクエストのタイプ}.

@geindex SIMPLE (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags SIMPLE}@anchor{4a5e}
@deffn {の属性} SIMPLE
@end deffn

@geindex WRITABLE (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags WRITABLE}@anchor{4a5f}
@deffn {の属性} WRITABLE
@end deffn

@geindex FORMAT (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags FORMAT}@anchor{4a60}
@deffn {の属性} FORMAT
@end deffn

@geindex ND (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags ND}@anchor{4a61}
@deffn {の属性} ND
@end deffn

@geindex STRIDES (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags STRIDES}@anchor{4a62}
@deffn {の属性} STRIDES
@end deffn

@geindex C_CONTIGUOUS (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags C_CONTIGUOUS}@anchor{4a63}
@deffn {の属性} C_CONTIGUOUS
@end deffn

@geindex F_CONTIGUOUS (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags F_CONTIGUOUS}@anchor{4a64}
@deffn {の属性} F_CONTIGUOUS
@end deffn

@geindex ANY_CONTIGUOUS (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags ANY_CONTIGUOUS}@anchor{4a65}
@deffn {の属性} ANY_CONTIGUOUS
@end deffn

@geindex INDIRECT (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags INDIRECT}@anchor{4a66}
@deffn {の属性} INDIRECT
@end deffn

@geindex CONTIG (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags CONTIG}@anchor{4a67}
@deffn {の属性} CONTIG
@end deffn

@geindex CONTIG_RO (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags CONTIG_RO}@anchor{4a68}
@deffn {の属性} CONTIG_RO
@end deffn

@geindex STRIDED (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags STRIDED}@anchor{4a69}
@deffn {の属性} STRIDED
@end deffn

@geindex STRIDED_RO (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags STRIDED_RO}@anchor{4a6a}
@deffn {の属性} STRIDED_RO
@end deffn

@geindex RECORDS (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags RECORDS}@anchor{4a6b}
@deffn {の属性} RECORDS
@end deffn

@geindex RECORDS_RO (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags RECORDS_RO}@anchor{4a6c}
@deffn {の属性} RECORDS_RO
@end deffn

@geindex FULL (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags FULL}@anchor{4a6d}
@deffn {の属性} FULL
@end deffn

@geindex FULL_RO (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags FULL_RO}@anchor{4a6e}
@deffn {の属性} FULL_RO
@end deffn

@geindex READ (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags READ}@anchor{18f5}
@deffn {の属性} READ
@end deffn

@geindex WRITE (inspect.BufferFlags の属性)
@anchor{library/inspect inspect BufferFlags WRITE}@anchor{18f6}
@deffn {の属性} WRITE
@end deffn


Added in version 3.12.

@end deffn

@node コマンドライン・インターフェース<10>,,Buffer flags,inspect --- 活動中のオブジェクトを調査する
@anchor{library/inspect command-line-interface}@anchor{4a6f}@anchor{library/inspect inspect-module-cli}@anchor{115d}
@subsubsection コマンドライン・インターフェース


The @code{inspect} 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.

@geindex inspect コマンドラインオプション; --details
@anchor{library/inspect cmdoption-inspect-details}@anchor{4a70}
@deffn {Option} @w{-}@w{-}details

Print information about the specified object rather than the source code
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node annotationlib --- Functionality for introspecting annotations,site --- サイト固有の設定フック,inspect --- 活動中のオブジェクトを調査する,Python ランタイムサービス
@anchor{library/annotationlib doc}@anchor{4a71}@anchor{library/annotationlib annotationlib-functionality-for-introspecting-annotations}@anchor{4a72}@anchor{library/annotationlib module-annotationlib}@anchor{6}@anchor{library/annotationlib translation-repo}@anchor{4a73}
@subsection @code{annotationlib} --- Functionality for introspecting annotations


@geindex module; annotationlib


Added in version 3.14.


`Source code:' Lib/annotationlib.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/annotationlib.py}

@c import annotationlib
@c from annotationlib import *


__________________________________________________________________


The @code{annotationlib} module provides tools for introspecting
@ref{15c,,annotations} on modules, classes, and functions.

Annotations are @ref{685,,lazily evaluated} and often contain
forward references to objects that are not yet defined when the annotation
is created. This module provides a set of low-level tools that can be used to retrieve annotations in a reliable way, even
in the presence of forward references and other edge cases.

This module supports retrieving annotations in three main formats
(see @ref{230,,Format}), each of which works best for different use cases:


@itemize *

@item 
@ref{15e,,VALUE} evaluates the annotations and returns their value.
This is most straightforward to work with, but it may raise errors,
for example if the annotations contain references to undefined names.

@item 
@ref{15f,,FORWARDREF} returns @ref{1776,,ForwardRef} objects
for annotations that cannot be resolved, allowing you to inspect the
annotations without evaluating them. This is useful when you need to
work with annotations that may contain unresolved forward references.

@item 
@ref{160,,STRING} returns the annotations as a string, similar
to how it would appear in the source file. This is useful for documentation
generators that want to display annotations in a readable way.
@end itemize

The @ref{459,,get_annotations()} function is the main entry point for
retrieving annotations. Given a function, class, or module, it returns
an annotations dictionary in the requested format. This module also provides
functionality for working directly with the @ref{15d,,annotate function}
that is used to evaluate annotations, such as @ref{45b,,get_annotate_from_class_namespace()}
and @ref{17be,,call_annotate_function()}, as well as the
@ref{44f0,,call_evaluate_function()} function for working with
@ref{44ef,,evaluate functions}.

@cartouche
@quotation 注意 
Most functionality in this module can execute arbitrary code; see
@ref{4518,,the security section} for more information.
@end quotation
@end cartouche


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} proposed the current model for how annotations work in Python.

@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/} expanded on various aspects of 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} and introduced the
@code{annotationlib} module.

@ref{9d9,,Annotations Best Practices} provides best practices for working with
annotations.

typing-extensions@footnote{https://pypi.org/project/typing-extensions/} provides a backport of @ref{459,,get_annotations()}
that works on earlier versions of Python.


@menu
* Annotation semantics:: 
* クラス: クラス<5>. 
* 関数: 関数<12>. 
* レシピ: レシピ<3>. 
* Limitations of the STRING format:: 
* Limitations of the FORWARDREF format:: 
* Security implications of introspecting annotations:: 

@end menu

@node Annotation semantics,クラス<5>,,annotationlib --- Functionality for introspecting annotations
@anchor{library/annotationlib annotation-semantics}@anchor{4a74}
@subsubsection Annotation semantics


The way annotations are evaluated has changed over the history of Python 3,
and currently still depends on a @ref{45d,,future import}.
There have been execution models for annotations:


@itemize *

@item 
`Stock semantics' (default in Python 3.0 through 3.13; see 
@geindex Python Enhancement Proposals; PEP 3107
PEP 3107@footnote{https://peps.python.org/pep-3107/}
and 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/}): Annotations are evaluated eagerly, as they are
encountered in the source code.

@item 
`Stringified annotations' (used with @code{from __future__ import annotations}
in Python 3.7 and newer; see 
@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/}): Annotations are stored as
strings only.

@item 
`Deferred evaluation' (default in Python 3.14 and newer; see 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} and
@geindex Python Enhancement Proposals; PEP 749
PEP 749@footnote{https://peps.python.org/pep-0749/}): Annotations are evaluated lazily, only when they are accessed.
@end itemize

As an example, consider the following program:

@example
def func(a: Cls) -> None:
    print(a)

class Cls: pass

print(func.__annotations__)
@end example

This will behave as follows:


@itemize *

@item 
Under stock semantics (Python 3.13 and earlier), it will throw a
@ref{452,,NameError} at the line where @code{func} is defined,
because @code{Cls} is an undefined name at that point.

@item 
Under stringified annotations (if @code{from __future__ import annotations}
is used), it will print @code{@{'a': 'Cls', 'return': 'None'@}}.

@item 
Under deferred evaluation (Python 3.14 and later), it will print
@code{@{'a': <class 'Cls'>, 'return': None@}}.
@end itemize

Stock semantics were used when function annotations were first introduced
in Python 3.0 (by 
@geindex Python Enhancement Proposals; PEP 3107
PEP 3107@footnote{https://peps.python.org/pep-3107/}) because this was the simplest, most obvious
way to implement annotations. The same execution model was used when variable
annotations were introduced in Python 3.6 (by 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/}). However,
stock semantics caused problems when using annotations as type hints,
such as a need to refer to names that are not yet defined when the
annotation is encountered. In addition, there were performance problems
with executing annotations at module import time. Therefore, in Python 3.7,
@geindex Python Enhancement Proposals; PEP 563
PEP 563@footnote{https://peps.python.org/pep-0563/} introduced the ability to store annotations as strings using the
@code{from __future__ import annotations} syntax. The plan at the time was to
eventually make this behavior the default, but a problem appeared:
stringified annotations are more difficult to process for those who
introspect annotations at runtime. An alternative proposal, 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/},
introduced the third execution model, deferred evaluation, and was implemented
in Python 3.14. Stringified annotations are still used if
@code{from __future__ import annotations} is present, but this behavior will
eventually be removed.

@node クラス<5>,関数<12>,Annotation semantics,annotationlib --- Functionality for introspecting annotations
@anchor{library/annotationlib classes}@anchor{4a75}
@subsubsection クラス


@geindex Format (annotationlib のクラス)
@anchor{library/annotationlib annotationlib Format}@anchor{230}
@deffn {クラス} annotationlib.Format

An @ref{edb,,IntEnum} describing the formats in which annotations
can be returned. Members of the enum, or their equivalent integer values,
can be passed to @ref{459,,get_annotations()} and other functions in this
module, as well as to @ref{1983,,__annotate__} functions.

@geindex VALUE (annotationlib.Format の属性)
@anchor{library/annotationlib annotationlib Format VALUE}@anchor{15e}
@deffn {の属性} VALUE = 1

Values are the result of evaluating the annotation expressions.
@end deffn

@geindex VALUE_WITH_FAKE_GLOBALS (annotationlib.Format の属性)
@anchor{library/annotationlib annotationlib Format VALUE_WITH_FAKE_GLOBALS}@anchor{4a76}
@deffn {の属性} VALUE_WITH_FAKE_GLOBALS = 2

Special value used to signal that an annotate function is being
evaluated in a special environment with fake globals. When passed this
value, annotate functions should either return the same value as for
the @ref{15e,,Format.VALUE} format, or raise @ref{36b,,NotImplementedError}
to signal that they do not support execution in this environment.
This format is only used internally and should not be passed to
the functions in this module.
@end deffn

@geindex FORWARDREF (annotationlib.Format の属性)
@anchor{library/annotationlib annotationlib Format FORWARDREF}@anchor{15f}
@deffn {の属性} FORWARDREF = 3

Values are real annotation values (as per @ref{15e,,Format.VALUE} format)
for defined values, and @ref{1776,,ForwardRef} proxies for undefined
values. Real objects may contain references to @ref{1776,,ForwardRef}
proxy objects.
@end deffn

@geindex STRING (annotationlib.Format の属性)
@anchor{library/annotationlib annotationlib Format STRING}@anchor{160}
@deffn {の属性} STRING = 4

Values are the text string of the annotation as it appears in the
source code, up to modifications including, but not restricted to,
whitespace normalizations and constant values optimizations.

The exact values of these strings may change in future versions of Python.
@end deffn


Added in version 3.14.

@end deffn

@geindex ForwardRef (annotationlib のクラス)
@anchor{library/annotationlib annotationlib ForwardRef}@anchor{1776}
@deffn {クラス} annotationlib.ForwardRef

A proxy object for forward references in annotations.

Instances of this class are returned when the @ref{15f,,FORWARDREF}
format is used and annotations contain a name that cannot be resolved.
This can happen when a forward reference is used in an annotation, such as
when a class is referenced before it is defined.

@geindex __forward_arg__ (annotationlib.ForwardRef の属性)
@anchor{library/annotationlib annotationlib ForwardRef __forward_arg__}@anchor{4a77}
@deffn {の属性} __forward_arg__

A string containing the code that was evaluated to produce the
@ref{1776,,ForwardRef}. The string may not be exactly equivalent
to the original source.
@end deffn

@geindex evaluate() (annotationlib.ForwardRef のメソッド)
@anchor{library/annotationlib annotationlib ForwardRef evaluate}@anchor{17b2}
@deffn {メソッド} evaluate (*, owner=None, globals=None, locals=None, type_params=None, format=Format.VALUE)

Evaluate the forward reference, returning its value.

If the `format' argument is @ref{15e,,VALUE} (the default),
this method may throw an exception, such as @ref{452,,NameError}, if the forward
reference refers to a name that cannot be resolved. The arguments to this
method can be used to provide bindings for names that would otherwise
be undefined. If the `format' argument is @ref{15f,,FORWARDREF},
the method will never throw an exception, but may return a @ref{1776,,ForwardRef}
instance. For example, if the forward reference object contains the code
@code{list[undefined]}, where @code{undefined} is a name that is not defined,
evaluating it with the @ref{15f,,FORWARDREF} format will return
@code{list[ForwardRef('undefined')]}. If the `format' argument is
@ref{160,,STRING}, the method will return @ref{4a77,,__forward_arg__}.

The `owner' parameter provides the preferred mechanism for passing scope
information to this method. The owner of a @ref{1776,,ForwardRef} is the
object that contains the annotation from which the @ref{1776,,ForwardRef}
derives, such as a module object, type object, or function object.

The `globals', `locals', and `type_params' parameters provide a more precise
mechanism for influencing the names that are available when the @ref{1776,,ForwardRef}
is evaluated. `globals' and `locals' are passed to @ref{4a3,,eval()}, representing
the global and local namespaces in which the name is evaluated.
The `type_params' parameter is relevant for objects created using the native
syntax for @ref{2377,,generic classes} and @ref{682,,functions}.
It is a tuple of @ref{5ad,,type parameters} that are in scope
while the forward reference is being evaluated. For example, if evaluating a
@ref{1776,,ForwardRef} retrieved from an annotation found in the class namespace
of a generic class @code{C}, `type_params' should be set to @code{C.__type_params__}.

@ref{1776,,ForwardRef} instances returned by @ref{459,,get_annotations()}
retain references to information about the scope they originated from,
so calling this method with no further arguments may be sufficient to
evaluate such objects. @ref{1776,,ForwardRef} instances created by other
means may not have any information about their scope, so passing
arguments to this method may be necessary to evaluate them successfully.

If no `owner', `globals', `locals', or `type_params' are provided and the
@ref{1776,,ForwardRef} does not contain information about its origin,
empty globals and locals dictionaries are used.
@end deffn


Added in version 3.14.

@end deffn

@node 関数<12>,レシピ<3>,クラス<5>,annotationlib --- Functionality for introspecting annotations
@anchor{library/annotationlib functions}@anchor{4a78}
@subsubsection 関数


@geindex annotations_to_string() (annotationlib モジュール)
@anchor{library/annotationlib annotationlib annotations_to_string}@anchor{4a79}
@deffn {の関数} annotationlib.annotations_to_string (annotations)

Convert an annotations dict containing runtime values to a
dict containing only strings. If the values are not already strings,
they are converted using @ref{1856,,type_repr()}.
This is meant as a helper for user-provided
annotate functions that support the @ref{160,,STRING} format but
do not have access to the code creating the annotations.

For example, this is used to implement the @ref{160,,STRING} for
@ref{332,,typing.TypedDict} classes created through the functional syntax:

@example
>>> from typing import TypedDict
>>> Movie = TypedDict("movie", @{"name": str, "year": int@})
>>> get_annotations(Movie, format=Format.STRING)
@{'name': 'str', 'year': 'int'@}
@end example


Added in version 3.14.

@end deffn

@geindex call_annotate_function() (annotationlib モジュール)
@anchor{library/annotationlib annotationlib call_annotate_function}@anchor{17be}
@deffn {の関数} annotationlib.call_annotate_function (annotate, format, *, owner=None)

Call the @ref{15d,,annotate function} `annotate' with the given `format',
a member of the @ref{230,,Format} enum, and return the annotations
dictionary produced by the function.

This helper function is required because annotate functions generated by
the compiler for functions, classes, and modules only support
the @ref{15e,,VALUE} format when called directly.
To support other formats, this function calls the annotate function
in a special environment that allows it to produce annotations in the
other formats. This is a useful building block when implementing
functionality that needs to partially evaluate annotations while a class
is being constructed.

`owner' is the object that owns the annotation function, usually
a function, class, or module. If provided, it is used in the
@ref{15f,,FORWARDREF} format to produce a @ref{1776,,ForwardRef}
object that carries more information.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 649#the-stringizer-and-the-fake-globals-environment
PEP 649@footnote{https://peps.python.org/pep-0649/#the-stringizer-and-the-fake-globals-environment}
contains an explanation of the implementation technique used by this
function.



Added in version 3.14.

@end deffn

@geindex call_evaluate_function() (annotationlib モジュール)
@anchor{library/annotationlib annotationlib call_evaluate_function}@anchor{44f0}
@deffn {の関数} annotationlib.call_evaluate_function (evaluate, format, *, owner=None)

Call the @ref{44ef,,evaluate function} `evaluate' with the given `format',
a member of the @ref{230,,Format} enum, and return the value produced by
the function. This is similar to @ref{17be,,call_annotate_function()},
but the latter always returns a dictionary mapping strings to annotations,
while this function returns a single value.

This is intended for use with the evaluate functions generated for lazily
evaluated elements related to type aliases and type parameters:


@itemize *

@item 
@ref{4505,,typing.TypeAliasType.evaluate_value()}, the value of type aliases

@item 
@ref{44ee,,typing.TypeVar.evaluate_bound()}, the bound of type variables

@item 
@ref{44f2,,typing.TypeVar.evaluate_constraints()}, the constraints of
type variables

@item 
@ref{44f4,,typing.TypeVar.evaluate_default()}, the default value of
type variables

@item 
@ref{44ff,,typing.ParamSpec.evaluate_default()}, the default value of
parameter specifications

@item 
@ref{44f8,,typing.TypeVarTuple.evaluate_default()}, the default value of
type variable tuples
@end itemize

`owner' is the object that owns the evaluate function, such as the type
alias or type variable object.

`format' can be used to control the format in which the value is returned:

@example
>>> type Alias = undefined
>>> call_evaluate_function(Alias.evaluate_value, Format.VALUE)
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF)
ForwardRef('undefined')
>>> call_evaluate_function(Alias.evaluate_value, Format.STRING)
'undefined'
@end example


Added in version 3.14.

@end deffn

@geindex get_annotate_from_class_namespace() (annotationlib モジュール)
@anchor{library/annotationlib annotationlib get_annotate_from_class_namespace}@anchor{45b}
@deffn {の関数} annotationlib.get_annotate_from_class_namespace (namespace)

Retrieve the @ref{15d,,annotate function} from a class namespace dictionary `namespace'.
Return @code{None} if the namespace does not contain an annotate function.
This is primarily useful before the class has been fully created (e.g., in a metaclass);
after the class exists, the annotate function can be retrieved with @code{cls.__annotate__}.
See @ref{4a7a,,below} for an example using this function in a metaclass.


Added in version 3.14.

@end deffn

@geindex get_annotations() (annotationlib モジュール)
@anchor{library/annotationlib annotationlib get_annotations}@anchor{459}
@deffn {の関数} annotationlib.get_annotations (obj, *, globals=None, locals=None, eval_str=False, format=Format.VALUE)

オブジェクトに対するアノテーション辞書を計算します。

`obj' may be a callable, class, module, or other object with
@ref{1983,,__annotate__} or @ref{458,,__annotations__} attributes.
Passing any other object raises @ref{198,,TypeError}.

The `format' parameter controls the format in which annotations are returned,
and must be a member of the @ref{230,,Format} enum or its integer equivalent.
The different formats work as follows:


@itemize *

@item 
VALUE: @code{object.__annotations__} is tried first; if that does not exist,
the @code{object.__annotate__} function is called if it exists.

@item 
FORWARDREF: If @code{object.__annotations__} exists and can be evaluated successfully,
it is used; otherwise, the @code{object.__annotate__} function is called. If it
does not exist either, @code{object.__annotations__} is tried again and any error
from accessing it is re-raised.


@itemize *

@item 
When calling @code{object.__annotate__} it is first called with @ref{15f,,FORWARDREF}.
If this is not implemented, it will then check if @ref{4a76,,VALUE_WITH_FAKE_GLOBALS}
is supported and use that in the fake globals environment.
If neither of these formats are supported, it will fall back to using @ref{15e,,VALUE}.
If @ref{15e,,VALUE} fails, the error from this call will be raised.
@end itemize

@item 
STRING: If @code{object.__annotate__} exists, it is called first;
otherwise, @code{object.__annotations__} is used and stringified
using @ref{4a79,,annotations_to_string()}.


@itemize *

@item 
When calling @code{object.__annotate__} it is first called with @ref{160,,STRING}.
If this is not implemented, it will then check if @ref{4a76,,VALUE_WITH_FAKE_GLOBALS}
is supported and use that in the fake globals environment.
If neither of these formats are supported, it will fall back to using @ref{15e,,VALUE}
with the result converted using @ref{4a79,,annotations_to_string()}.
If @ref{15e,,VALUE} fails, the error from this call will be raised.
@end itemize
@end itemize

Returns a dict. @code{get_annotations()} returns a new dict every time
it's called; calling it twice on the same object will return two
different but equivalent dicts.

This function handles several details for you:


@itemize *

@item 
If `eval_str' is true, values of type @code{str} will
be un-stringized using @ref{4a3,,eval()}. This is intended
for use with stringized annotations
(@code{from __future__ import annotations}). It is an error
to set `eval_str' to true with formats other than @ref{15e,,Format.VALUE}.

@item 
If `obj' doesn't have an annotations dict, returns an
empty dict. (Functions and methods always have an
annotations dict; classes, modules, and other types of
callables may not.)

@item 
Ignores inherited annotations on classes, as well as annotations
on metaclasses. If a class
doesn't have its own annotations dict, returns an empty dict.

@item 
All accesses to object members and dict values are done
using @code{getattr()} and @code{dict.get()} for safety.
@end itemize

`eval_str' controls whether or not values of type @code{str} are
replaced with the result of calling @ref{4a3,,eval()} on those values:


@itemize *

@item 
If eval_str is true, @ref{4a3,,eval()} is called on values of type
@code{str}. (Note that @code{get_annotations()} doesn't catch
exceptions; if @ref{4a3,,eval()} raises an exception, it will unwind
the stack past the @code{get_annotations()} call.)

@item 
If `eval_str' is false (the default), values of type @code{str} are
unchanged.
@end itemize

`globals' and `locals' are passed in to @ref{4a3,,eval()}; see the documentation
for @ref{4a3,,eval()} for more information. If `globals' or `locals'
is @code{None}, this function may replace that value with a
context-specific default, contingent on @code{type(obj)}:


@itemize *

@item 
If `obj' is a module, `globals' defaults to @code{obj.__dict__}.

@item 
If `obj' is a class, `globals' defaults to
@code{sys.modules[obj.__module__].__dict__} and `locals' defaults
to the `obj' class namespace.

@item 
If `obj' is a callable, `globals' defaults to
@ref{14eb,,obj.__globals__},
although if `obj' is a wrapped function (using
@ref{1223,,functools.update_wrapper()}) or a @ref{217,,functools.partial} object,
it is unwrapped until a non-wrapped function is found.
@end itemize

Calling @code{get_annotations()} is best practice for accessing the
annotations dict of any object. See @ref{9d9,,Annotations Best Practices} for
more information on annotations best practices.

@example
>>> def f(a: int, b: str) -> float:
...     pass
>>> get_annotations(f)
@{'a': <class 'int'>, 'b': <class 'str'>, 'return': <class 'float'>@}
@end example


Added in version 3.14.

@end deffn

@geindex type_repr() (annotationlib モジュール)
@anchor{library/annotationlib annotationlib type_repr}@anchor{1856}
@deffn {の関数} annotationlib.type_repr (value)

Convert an arbitrary Python value to a format suitable for use by the
@ref{160,,STRING} format. This calls @ref{1c1,,repr()} for most
objects, but has special handling for some objects, such as type objects.

This is meant as a helper for user-provided
annotate functions that support the @ref{160,,STRING} format but
do not have access to the code creating the annotations. It can also
be used to provide a user-friendly string representation for other
objects that contain values that are commonly encountered in annotations.


Added in version 3.14.

@end deffn

@node レシピ<3>,Limitations of the STRING format,関数<12>,annotationlib --- Functionality for introspecting annotations
@anchor{library/annotationlib recipes}@anchor{4a7b}
@subsubsection レシピ


@menu
* Using annotations in a metaclass:: 

@end menu

@node Using annotations in a metaclass,,,レシピ<3>
@anchor{library/annotationlib annotationlib-metaclass}@anchor{4a7a}@anchor{library/annotationlib using-annotations-in-a-metaclass}@anchor{4a7c}
@subsubsection Using annotations in a metaclass


A @ref{23be,,metaclass} may want to inspect or even modify the annotations
in a class body during class creation. Doing so requires retrieving annotations
from the class namespace dictionary. For classes created with
@code{from __future__ import annotations}, the annotations will be in the @code{__annotations__}
key of the dictionary. For other classes with annotations,
@ref{45b,,get_annotate_from_class_namespace()} can be used to get the
annotate function, and @ref{17be,,call_annotate_function()} can be used to call it and
retrieve the annotations. Using the @ref{15f,,FORWARDREF} format will usually
be best, because this allows the annotations to refer to names that cannot yet be
resolved when the class is created.

To modify the annotations, it is best to create a wrapper annotate function
that calls the original annotate function, makes any necessary adjustments, and
returns the result.

Below is an example of a metaclass that filters out all @ref{56d,,typing.ClassVar}
annotations from the class and puts them in a separate attribute:

@example
import annotationlib
import typing

class ClassVarSeparator(type):
   def __new__(mcls, name, bases, ns):
      if "__annotations__" in ns:  # from __future__ import annotations
         annotations = ns["__annotations__"]
         classvar_keys = @{
            key for key, value in annotations.items()
            # Use string comparison for simplicity; a more robust solution
            # could use annotationlib.ForwardRef.evaluate
            if value.startswith("ClassVar")
         @}
         classvars = @{key: annotations[key] for key in classvar_keys@}
         ns["__annotations__"] = @{
            key: value for key, value in annotations.items()
            if key not in classvar_keys
         @}
         wrapped_annotate = None
      elif annotate := annotationlib.get_annotate_from_class_namespace(ns):
         annotations = annotationlib.call_annotate_function(
            annotate, format=annotationlib.Format.FORWARDREF
         )
         classvar_keys = @{
            key for key, value in annotations.items()
            if typing.get_origin(value) is typing.ClassVar
         @}
         classvars = @{key: annotations[key] for key in classvar_keys@}

         def wrapped_annotate(format):
            annos = annotationlib.call_annotate_function(annotate, format, owner=typ)
            return @{key: value for key, value in annos.items() if key not in classvar_keys@}

      else:  # no annotations
         classvars = @{@}
         wrapped_annotate = None
      typ = super().__new__(mcls, name, bases, ns)

      if wrapped_annotate is not None:
         # Wrap the original __annotate__ with a wrapper that removes ClassVars
         typ.__annotate__ = wrapped_annotate
      typ.classvars = classvars  # Store the ClassVars in a separate attribute
      return typ
@end example

@node Limitations of the STRING format,Limitations of the FORWARDREF format,レシピ<3>,annotationlib --- Functionality for introspecting annotations
@anchor{library/annotationlib limitations-of-the-string-format}@anchor{4a7d}
@subsubsection Limitations of the @code{STRING} format


The @ref{160,,STRING} format is meant to approximate the source code
of the annotation, but the implementation strategy used means that it is not
always possible to recover the exact source code.

First, the stringifier of course cannot recover any information that is not present in
the compiled code, including comments, whitespace, parenthesization, and operations that
get simplified by the compiler.

Second, the stringifier can intercept almost all operations that involve names looked
up in some scope, but it cannot intercept operations that operate fully on constants.
As a corollary, this also means it is not safe to request the @code{STRING} format on
untrusted code: Python is powerful enough that it is possible to achieve arbitrary
code execution even with no access to any globals or builtins. For example:

@example
>>> def f(x: (1).__class__.__base__.__subclasses__()[-1].__init__.__builtins__["print"]("Hello world")): pass
...
>>> annotationlib.get_annotations(f, format=annotationlib.Format.STRING)
Hello world
@{'x': 'None'@}
@end example

@cartouche
@quotation 注釈 
This particular example works as of the time of writing, but it relies on
implementation details and is not guaranteed to work in the future.
@end quotation
@end cartouche

Among the different kinds of expressions that exist in Python,
as represented by the @ref{9,,ast} module, some expressions are supported,
meaning that the @code{STRING} format can generally recover the original source code;
others are unsupported, meaning that they may result in incorrect output or an error.

The following are supported (sometimes with caveats):


@itemize *

@item 
@ref{1db2,,ast.BinOp}

@item 
@ref{4a7e,,ast.UnaryOp}


@itemize *

@item 
@ref{4a7f,,ast.Invert} (@code{~}), @ref{4a80,,ast.UAdd} (@code{+}), and @ref{4a81,,ast.USub} (@code{-}) are supported

@item 
@ref{4a82,,ast.Not} (@code{not}) is not supported
@end itemize

@item 
@ref{1d49,,ast.Dict} (except when using @code{**} unpacking)

@item 
@ref{4a83,,ast.Set}

@item 
@ref{4a84,,ast.Compare}


@itemize *

@item 
@ref{4a85,,ast.Eq} and @ref{4a86,,ast.NotEq} are supported

@item 
@ref{4a87,,ast.Lt}, @ref{4a88,,ast.LtE}, @ref{4a89,,ast.Gt}, and @ref{4a8a,,ast.GtE} are supported, but the operand may be flipped

@item 
@ref{4a8b,,ast.Is}, @ref{4a8c,,ast.IsNot}, @ref{4a8d,,ast.In}, and @ref{4a8e,,ast.NotIn} are not supported
@end itemize

@item 
@ref{4a8f,,ast.Call} (except when using @code{**} unpacking)

@item 
@ref{2ef,,ast.Constant} (though not the exact representation of the constant; for example, escape
sequences in strings are lost; hexadecimal numbers are converted to decimal)

@item 
@ref{4a90,,ast.Attribute} (assuming the value is not a constant)

@item 
@ref{4a91,,ast.Subscript} (assuming the value is not a constant)

@item 
@ref{4a92,,ast.Starred} (@code{*} unpacking)

@item 
@ref{1d22,,ast.Name}

@item 
@ref{4a93,,ast.List}

@item 
@ref{4a94,,ast.Tuple}

@item 
@ref{4a95,,ast.Slice}
@end itemize

The following are unsupported, but throw an informative error when encountered by the
stringifier:


@itemize *

@item 
@ref{4a96,,ast.FormattedValue} (f-strings; error is not detected if conversion specifiers like @code{!r}
are used)

@item 
@ref{1a5c,,ast.JoinedStr} (f-strings)
@end itemize

The following are unsupported and result in incorrect output:


@itemize *

@item 
@ref{4a97,,ast.BoolOp} (@code{and} and @code{or})

@item 
@ref{4a98,,ast.IfExp}

@item 
@ref{4a99,,ast.Lambda}

@item 
@ref{4a9a,,ast.ListComp}

@item 
@ref{4a9b,,ast.SetComp}

@item 
@ref{4a9c,,ast.DictComp}

@item 
@ref{4a9d,,ast.GeneratorExp}
@end itemize

The following are disallowed in annotation scopes and therefore not relevant:


@itemize *

@item 
@ref{4a9e,,ast.NamedExpr} (@code{:=})

@item 
@ref{4a9f,,ast.Await}

@item 
@ref{4aa0,,ast.Yield}

@item 
@ref{4aa1,,ast.YieldFrom}
@end itemize

@node Limitations of the FORWARDREF format,Security implications of introspecting annotations,Limitations of the STRING format,annotationlib --- Functionality for introspecting annotations
@anchor{library/annotationlib limitations-of-the-forwardref-format}@anchor{4aa2}
@subsubsection Limitations of the @code{FORWARDREF} format


The @ref{15f,,FORWARDREF} format aims to produce real values as much
as possible, with anything that cannot be resolved replaced with
@ref{1776,,ForwardRef} objects. It is affected by broadly the same Limitations
as the @ref{160,,STRING} format: annotations that perform operations on
literals or that use unsupported expression types may raise exceptions when
evaluated using the @ref{15f,,FORWARDREF} format.

Below are a few examples of the behavior with unsupported expressions:

@example
>>> from annotationlib import get_annotations, Format
>>> def zerodiv(x: 1 / 0): ...
>>> get_annotations(zerodiv, format=Format.STRING)
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero
>>> get_annotations(zerodiv, format=Format.FORWARDREF)
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero
>>> def ifexp(x: 1 if y else 0): ...
>>> get_annotations(ifexp, format=Format.STRING)
@{'x': '1'@}
@end example

@node Security implications of introspecting annotations,,Limitations of the FORWARDREF format,annotationlib --- Functionality for introspecting annotations
@anchor{library/annotationlib annotationlib-security}@anchor{4518}@anchor{library/annotationlib security-implications-of-introspecting-annotations}@anchor{4aa3}
@subsubsection Security implications of introspecting annotations


Much of the functionality in this module involves executing code related to annotations,
which can then do arbitrary things. For example,
@ref{459,,get_annotations()} may call an arbitrary @ref{15d,,annotate function}, and
@ref{17b2,,ForwardRef.evaluate()} may call @ref{4a3,,eval()} on an arbitrary string. Code contained
in an annotation might make arbitrary system calls, enter an infinite loop, or perform any
other operation. This is also true for any access of the @ref{458,,__annotations__} attribute,
and for various functions in the @ref{10a,,typing} module that work with annotations, such as
@ref{8c0,,typing.get_type_hints()}.

Any security issue arising from this also applies immediately after importing
code that may contain untrusted annotations: importing code can always cause arbitrary operations
to be performed. However, it is unsafe to accept strings or other input from an untrusted source and
pass them to any of the APIs for introspecting annotations, for example by editing an
@code{__annotations__} dictionary or directly creating a @ref{1776,,ForwardRef} object.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node site --- サイト固有の設定フック,,annotationlib --- Functionality for introspecting annotations,Python ランタイムサービス
@anchor{library/site doc}@anchor{4aa4}@anchor{library/site module-site}@anchor{cc}@anchor{library/site site-site-specific-configuration-hook}@anchor{4aa5}@anchor{library/site translation-repo}@anchor{4aa6}
@subsection @code{site} --- サイト固有の設定フック


@geindex module; site

`ソースコード:' Lib/site.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/site.py}


__________________________________________________________________


`このモジュールは初期化中に自動的にインポートされます。' 自動インポートはインタプリタの @ref{13c0,,-S} オプションで禁止できます。

@geindex module;検索;パス

Importing this module normally appends site-specific paths to the module search path
and adds @ref{25e5,,callables}, including @ref{ad4,,help()} to the built-in
namespace. However, Python startup option @ref{13c0,,-S} blocks this and this module
can be safely imported with no automatic modifications to the module search path
or additions to the builtins.  To explicitly trigger the usual site-specific
additions, call the @ref{2127,,main()} function.


バージョン 3.3 で変更: 以前は @ref{13c0,,-S} を使っているときでも、モジュールをインポートするとパス変更が起動されていました。


@geindex site-packages;ディレクトリ

It starts by constructing up to four directories from a head and a tail part.
For the head part, it uses @code{sys.prefix} and @code{sys.exec_prefix}; empty heads
are skipped.  For the tail part, it uses the empty string and then
@code{lib/site-packages} (on Windows) or
@code{lib/python`X.Y[t]'/site-packages} (on Unix and macOS). (The
optional suffix "t" indicates the @ref{176d,,free-threaded build}, and is
appended if @code{"t"} is present in the @ref{c59,,sys.abiflags} constant.)
For each
of the distinct head-tail combinations, it sees if it refers to an existing
directory, and if so, adds it to @code{sys.path} and also inspects the newly
added path for configuration files.


バージョン 3.5 で変更: "site-python" ディレクトリのサポートは削除されました。



バージョン 3.13 で変更: On Unix, @ref{1f4,,Free threading} Python installations are
identified by the "t" suffix in the version-specific directory name, such as
@code{lib/python3.13t/}.



バージョン 3.14 で変更: @code{site} is no longer responsible for updating @ref{3e7,,sys.prefix} and
@ref{3eb,,sys.exec_prefix} on @ref{48b3,,Virtual Environments}. This is
now done during the @ref{18dc,,path initialization}. As a result,
under @ref{48b3,,Virtual Environments}, @ref{3e7,,sys.prefix} and
@ref{3eb,,sys.exec_prefix} no longer depend on the @code{site} initialization,
and are therefore unaffected by @ref{13c0,,-S}.

@anchor{library/site site-virtual-environments-configuration}@anchor{48b4}
When running under a @ref{48b3,,virtual environment},
the @code{pyvenv.cfg} file in @ref{3e7,,sys.prefix} is checked for site-specific
configurations. If the @code{include-system-site-packages} key exists and is set to
@code{true} (case-insensitive), the system-level prefixes will be searched for
site-packages, otherwise they won't.

@geindex # (hash);コメント
@geindex statement;import

パス設定ファイルは @code{`name'.pth} という形式の名前をもつファイルで、上の4つのディレクトリのひとつにあります。その内容は @code{sys.path} に追加される追加項目(一行に一つ)です。存在しない項目は @code{sys.path} へは決して追加されませんが、項目がファイルではなくディレクトリを参照しているかどうかはチェックされません。項目が @code{sys.path} へ二回以上追加されることはありません。空行と @code{#} で始まる行は読み飛ばされます。 @code{import} で始まる(そしてその後ろにスペースかタブが続く)行は実行されます。

@cartouche
@quotation 注釈 
@code{.pth} ファイル内の実行可能な行は、特定のモジュールが実際に使用されるかどうかに関係なく、Pythonの起動時に毎回実行されます。したがって、その影響は最小限に抑えられるべきです。実行可能な行の主な目的は、対応するモジュールをインポート可能にすることです(サードパーティ製インポートフックのロード、 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} の調整など)。その他の初期化は、モジュールが実際にインポートされたときに行われます。コードのチャンクを1行に制限することは、より複雑なものをここに入れないようにするための意図的な手段です。
@end quotation
@end cartouche


バージョン 3.13 で変更: @code{.pth} ファイルは、最初に UTF-8 で、失敗した場合は @ref{54a,,locale encoding} でデコードされるようになります。


@geindex package
@geindex パス;設定;ファイル

例えば、 @code{sys.prefix} と @code{sys.exec_prefix} が @code{/usr/local} に設定されていると仮定します。そのときPython X.Y ライブラリは @code{/usr/local/lib/python`X.Y'} にインストールされています。ここにはサブディレクトリ @code{/usr/local/lib/python`X.Y'/site-packages} があり、その中に三つのサブディレクトリ @code{foo}, @code{bar} および @code{spam} と二つのパス設定ファイル @code{foo.pth} と @code{bar.pth} をもつと仮定します。 @code{foo.pth} には以下のものが記載されていると想定してください:

@example
# foo package configuration

foo
bar
bletch
@end example

また、 @code{bar.pth} には:

@example
# bar package configuration

bar
@end example

が記載されているとします。そのとき、次のバージョンごとのディレクトリが @code{sys.path} へこの順番で追加されます:

@example
/usr/local/lib/pythonX.Y/site-packages/bar
/usr/local/lib/pythonX.Y/site-packages/foo
@end example

@code{bletch} は存在しないため省略されるということに注意してください。 @code{bar} ディレクトリは @code{foo} ディレクトリの前に来ます。なぜなら、 @code{bar.pth} がアルファベット順で @code{foo.pth} の前に来るからです。また、 @code{spam} はどちらのパス設定ファイルにも記載されていないため、省略されます。

@menu
* sitecustomize:: 
* usercustomize:: 
* readline の設定:: 
* モジュールの内容: モジュールの内容<5>. 
* コマンドライン・インターフェース: コマンドライン・インターフェース<11>. 

@end menu

@node sitecustomize,usercustomize,,site --- サイト固有の設定フック
@anchor{library/site module-sitecustomize}@anchor{cd}@anchor{library/site sitecustomize}@anchor{4aa7}
@subsubsection @code{sitecustomize}


@geindex module; sitecustomize

After these path manipulations, an attempt is made to import a module named
@code{sitecustomize}, which can perform arbitrary site-specific customizations.
It is typically created by a system administrator in the site-packages
directory.  If this import fails with an @ref{65b,,ImportError} or its subclass
exception, and the exception's @ref{26ea,,name}
attribute equals @code{'sitecustomize'},
it is silently ignored.  If Python is started without output streams available, as
with @code{pythonw.exe} on Windows (which is used by default to start IDLE),
attempted output from @code{sitecustomize} is ignored.  Any other exception
causes a silent and perhaps mysterious failure of the process.

@node usercustomize,readline の設定,sitecustomize,site --- サイト固有の設定フック
@anchor{library/site module-usercustomize}@anchor{114}@anchor{library/site usercustomize}@anchor{4aa8}
@subsubsection @code{usercustomize}


@geindex module; usercustomize

After this, an attempt is made to import a module named @code{usercustomize},
which can perform arbitrary user-specific customizations, if
@ref{4aa9,,ENABLE_USER_SITE} is true.  This file is intended to be created in the
user site-packages directory (see below), which is part of @code{sys.path} unless
disabled by @ref{15a6,,-s}.  If this import fails with an @ref{65b,,ImportError} or
its subclass exception, and the exception's @ref{26ea,,name}
attribute equals @code{'usercustomize'}, it is silently ignored.

Note that for some non-Unix systems, @code{sys.prefix} and @code{sys.exec_prefix} are
empty, and the path manipulations are skipped; however the import of
@ref{cd,,sitecustomize} and @code{usercustomize} is still attempted.

@node readline の設定,モジュールの内容<5>,usercustomize,site --- サイト固有の設定フック
@anchor{library/site readline-configuration}@anchor{4aaa}@anchor{library/site rlcompleter-config}@anchor{11cb}
@subsubsection readline の設定


On systems that support @ref{bf,,readline}, this module will also import and
configure the @ref{c2,,rlcompleter} module, if Python is started in
@ref{443,,interactive mode} and without the @ref{13c0,,-S} option.
The default behavior is to enable tab completion and to use
@code{~/.python_history} as the history save file.  To disable it, delete (or
override) the @ref{11ca,,sys.__interactivehook__} attribute in your
@ref{cd,,sitecustomize} or @ref{114,,usercustomize} module or your
@geindex PYTHONSTARTUP
@geindex 環境変数; PYTHONSTARTUP
@ref{1b8,,PYTHONSTARTUP} file.


バージョン 3.4 で変更: rlcompleter とhistory のアクティベーションが自動で行われるようになりました。


@node モジュールの内容<5>,コマンドライン・インターフェース<11>,readline の設定,site --- サイト固有の設定フック
@anchor{library/site module-contents}@anchor{4aab}
@subsubsection モジュールの内容


@geindex PREFIXES (site モジュール)
@anchor{library/site site PREFIXES}@anchor{4aac}
@deffn {データ} site.PREFIXES

siteパッケージディレクトリのprefixのリスト。
@end deffn

@geindex ENABLE_USER_SITE (site モジュール)
@anchor{library/site site ENABLE_USER_SITE}@anchor{4aa9}
@deffn {データ} site.ENABLE_USER_SITE

ユーザサイトディレクトリのステータスを示すフラグ。 @code{True} の場合、ユーザサイトディレクトリが有効で @code{sys.path} に追加されていることを意味しています。 @code{False} の場合、ユーザによるリクエスト(オプション @ref{15a6,,-s} か 
@geindex PYTHONNOUSERSITE
@geindex 環境変数; PYTHONNOUSERSITE
@ref{15a7,,PYTHONNOUSERSITE})によって、 @code{None} の場合セキュリティ上の理由(ユーザまたはグループIDと実効IDの間のミスマッチ)あるいは管理者によって、ユーザサイトディレクトリが無効になっていることを示しています。
@end deffn

@geindex USER_SITE (site モジュール)
@anchor{library/site site USER_SITE}@anchor{2126}
@deffn {データ} site.USER_SITE

Path to the user site-packages for the running Python.  Can be @code{None} if
@ref{1458,,getusersitepackages()} hasn't been called yet.  Default value is
@code{~/.local/lib/python`X.Y'[t]/site-packages} for UNIX and non-framework
macOS builds, @code{~/Library/Python/`X.Y'/lib/python/site-packages} for macOS
framework builds, and @code{`%APPDATA%'\Python\Python`XY'\site-packages}
on Windows.  The optional "t" indicates the free-threaded build.  This
directory is a site directory, which means that @code{.pth} files in it
will be processed.
@end deffn

@geindex USER_BASE (site モジュール)
@anchor{library/site site USER_BASE}@anchor{1534}
@deffn {データ} site.USER_BASE

ユーザの site-packages のベースとなるディレクトリへのパスです。 @ref{1457,,getuserbase()} がまだ呼び出されていなければ @code{None} かもしれません。デフォルト値は  UNIX と frameworkなしの macOS ビルドでは @code{~/.local} 、macOS framework ビルドでは @code{~/Library/Python/`X.Y'} 、Windows では @code{`%APPDATA%'\Python} です。この値は、スクリプト、データファイル、Python モジュールなどのインストール先のディレクトリを @ref{2137,,ユーザーインストールスキーム} で計算するのに使われます。 
@geindex PYTHONUSERBASE
@geindex 環境変数; PYTHONUSERBASE
@ref{15a5,,PYTHONUSERBASE} も参照してください。
@end deffn

@geindex main() (site モジュール)
@anchor{library/site site main}@anchor{2127}
@deffn {の関数} site.main ()

モジュール検索パスに標準のサイト固有ディレクトリを追加します。この関数は、Python インタプリタが @ref{13c0,,-S} で開始されていない限り、このモジュールインポート時に自動的に呼び出されます。


バージョン 3.3 で変更: この関数は以前は無条件に呼び出されていました。

@end deffn

@geindex addsitedir() (site モジュール)
@anchor{library/site site addsitedir}@anchor{2272}
@deffn {の関数} site.addsitedir (sitedir, known_paths=None)

sys.path にディレクトリを追加し、その @code{.pth} ファイル群を処理します。典型的には @ref{cd,,sitecustomize} か @ref{114,,usercustomize} 内で使われます(上述)。
@end deffn

@geindex getsitepackages() (site モジュール)
@anchor{library/site site getsitepackages}@anchor{1456}
@deffn {の関数} site.getsitepackages ()

全てのグローバルな site-packages ディレクトリのリストを返します。


Added in version 3.2.

@end deffn

@geindex getuserbase() (site モジュール)
@anchor{library/site site getuserbase}@anchor{1457}
@deffn {の関数} site.getuserbase ()

ユーザのベースディレクトリへのパス @ref{1534,,USER_BASE} を返します。未初期化であればこの関数は 
@geindex PYTHONUSERBASE
@geindex 環境変数; PYTHONUSERBASE
@ref{15a5,,PYTHONUSERBASE} を参考にして、設定もします。


Added in version 3.2.

@end deffn

@geindex getusersitepackages() (site モジュール)
@anchor{library/site site getusersitepackages}@anchor{1458}
@deffn {の関数} site.getusersitepackages ()

ユーザ固有の site パッケージのディレクトリへのパス @ref{2126,,USER_SITE} を返します。未初期化であればこの関数は @ref{1534,,USER_BASE} を参考にして、設定もします。
ユーザ固有の site パッケージが @code{sys.path} に追加されたかどうかを確認するには @ref{4aa9,,ENABLE_USER_SITE} を使ってください。


Added in version 3.2.

@end deffn

@node コマンドライン・インターフェース<11>,,モジュールの内容<5>,site --- サイト固有の設定フック
@anchor{library/site command-line-interface}@anchor{4aad}@anchor{library/site site-commandline}@anchor{4aae}
@subsubsection コマンドライン・インターフェース


The @code{site} module also provides a way to get the user directories from the
command line:

@example
$ python -m site --user-site
/home/user/.local/lib/python3.11/site-packages
@end example

引数なしで呼び出された場合、@ref{3e4,,sys.path} の中身を表示し、続けて @ref{1534,,USER_BASE} とそのディレクトリが存在するかどうか、 @ref{2126,,USER_SITE} とそのディレクトリが存在するかどうか、最後に @ref{4aa9,,ENABLE_USER_SITE} の値を、標準出力に出力します。

@geindex site コマンドラインオプション; --user-base
@anchor{library/site cmdoption-site-user-base}@anchor{4aaf}
@deffn {Option} @w{-}@w{-}user@w{-}base

ユーザのベースディレクトリを表示します。
@end deffn

@geindex site コマンドラインオプション; --user-site
@anchor{library/site cmdoption-site-user-site}@anchor{4ab0}
@deffn {Option} @w{-}@w{-}user@w{-}site

ユーザの site-packages ディレクトリを表示します。
@end deffn

両方のオプションが指定された場合、ユーザのベースとユーザの site が(常にこの順序で) @ref{2134,,os.pathsep} 区切りで表示されます。

いずれかのオプションが与えられた場合に、このスクリプトは次のいずれかの終了コードで終了します: ユーザの site-packages が有効ならば @code{0} 、ユーザにより無効にされていれば @code{1} 、セキュリティ的な理由あるいは管理者によって無効にされている場合 @code{2} 、そして何かエラーがあった場合は 2 より大きな値。


@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 370
PEP 370@footnote{https://peps.python.org/pep-0370/} -- ユーザごとの @code{site-packages} ディレクトリ

@item 
@ref{18dc,,sys.path モジュール検索パスの初期化} -- @ref{3e4,,sys.path}. の初期化。
@end itemize


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)


@subsubheading 参考



@itemize *

@item 
See the @ref{25,,concurrent.interpreters} module, which similarly
exposes core runtime functionality.
@end itemize


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node カスタム Python インタプリタ,モジュールのインポート,Python ランタイムサービス,Python 標準ライブラリ
@anchor{library/custominterp doc}@anchor{4ab1}@anchor{library/custominterp custom-python-interpreters}@anchor{4ab2}@anchor{library/custominterp custominterp}@anchor{4ab3}@anchor{library/custominterp translation-repo}@anchor{4ab4}
@section カスタム Python インタプリタ


この章で解説されるモジュールで Python の対話型インタープリターに似たインターフェースを書くことができます。もし Python そのもの以外に何か特殊な機能をサポートした Python インタープリターを作りたければ、 @ref{1b,,code} モジュールを参照してください。 (@ref{1d,,codeop} モジュールはより低レベルで、不完全かもしれない Python コード断片のコンパイルをサポートするために使われます。)

この章で解説されるモジュールの完全な一覧は:

@menu
* code: code --- インタープリター基底クラス. インタープリター基底クラス
* codeop: codeop --- Python コードをコンパイルする. Python コードをコンパイルする

@end menu

@node code --- インタープリター基底クラス,codeop --- Python コードをコンパイルする,,カスタム Python インタプリタ
@anchor{library/code doc}@anchor{4ab5}@anchor{library/code code-interpreter-base-classes}@anchor{4ab6}@anchor{library/code module-code}@anchor{1b}
@subsection @code{code} --- インタープリター基底クラス


@geindex module; code

`ソースコード:' Lib/code.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/code.py}


__________________________________________________________________


@code{code} モジュールはread-eval-print (読み込み-評価-表示)ループをPythonで実装するための機能を提供します。対話的なインタプリタプロンプトを提供するアプリケーションを作るために使える二つのクラスと便利な関数が含まれています。

@geindex InteractiveInterpreter (code のクラス)
@anchor{library/code code InteractiveInterpreter}@anchor{1943}
@deffn {クラス} code.InteractiveInterpreter (locals=None)

このクラスは構文解析とインタープリター状態(ユーザの名前空間)を取り扱います。入力バッファリングやプロンプト出力、または入力ファイル指定を扱いません(ファイル名は常に明示的に渡されます)。オプションの `locals' 引数はその中でコードが実行される名前空間として使用されるマッピングを指定します。その初期値は、キー @code{'__name__'} が @code{'__console__'} に設定され、キー @code{'__doc__'} が @code{None} に設定された新しく作られた辞書です。

Note that functions and classes objects created under an
@code{InteractiveInterpreter} instance will belong to the namespace
specified by `locals'.
They are only pickleable if `locals' is the namespace of an existing
module.
@end deffn

@geindex InteractiveConsole (code のクラス)
@anchor{library/code code InteractiveConsole}@anchor{2807}
@deffn {クラス} code.InteractiveConsole (locals=None, filename='<console>', local_exit=False)

Python の対話型インタープリターの振る舞いを忠実にエミュレートします。このクラスは @ref{1943,,InteractiveInterpreter} を継承しており、よく知られた @code{sys.ps1} と @code{sys.ps2} を使用してプロンプトと入力バッファリングを追加します。 `local_exit' が真の場合、コンソールでの @code{exit()} と @code{quit()} は @ref{f3c,,SystemExit} を送出せず、代わりに呼び出し元のコードに戻ります。


バージョン 3.13 で変更: `local_exit' 引数が追加されました。

@end deffn

@geindex interact() (code モジュール)
@anchor{library/code code interact}@anchor{1890}
@deffn {の関数} code.interact (banner=None, readfunc=None, local=None, exitmsg=None, local_exit=False)

read-eval-print ループを実行するための便利な関数。これは @ref{2807,,InteractiveConsole} の新しいインスタンスを作り、 `readfunc' が与えられた場合は @ref{4ab7,,InteractiveConsole.raw_input()} メソッドとして使われるように設定します。 `local' が与えられた場合は、インタープリターループのデフォルト名前空間として使うために @ref{2807,,InteractiveConsole} コンストラクタへ渡されます。 `local_exit' が与えられた場合は、 @ref{2807,,InteractiveConsole} コンストラクタへ渡されます。そして、インスタンスの @ref{4ab8,,interact()} メソッドは、もし提供されていれば、見出しと終了メッセージして使うために `banner' と `exitmsg' を受け取り実行されます。コンソールオブジェクトは使われた後捨てられます。


バージョン 3.6 で変更: `exitmsg' 引数が追加されました.



バージョン 3.13 で変更: `local_exit' 引数が追加されました。

@end deffn

@geindex compile_command() (code モジュール)
@anchor{library/code code compile_command}@anchor{4ab9}
@deffn {の関数} code.compile_command (source, filename='<input>', symbol='single')

この関数はPythonのインタプリタメインループ(別名、read-eval-printループ)をエミュレートしようとするプログラムにとって役に立ちます。扱いにくい部分は、ユーザが(完全なコマンドや構文エラーではなく)さらにテキストを入力すれば完全になりうる不完全なコマンドを入力したときを決定することです。この関数は `ほとんど' の場合に実際のインタプリタメインループと同じ決定を行います。

`source' はソース文字列です。`filename' はオプションのソースが読み出されたファイル名で、デフォルトで @code{'<input>'} です。`symbol' はオプションの文法の開始記号で、@code{'single'} (デフォルト)または @code{'eval'} か @code{'exec'} にすべきです。

コマンドが完全で有効ならば、コードオブジェクトを返します(@code{compile(source, filename, symbol)} と同じ)。コマンドが完全でないならば、 @code{None} を返します。コマンドが完全で構文エラーを含む場合は、 @ref{18e,,SyntaxError} を発生させます。または、コマンドが無効なリテラルを含む場合は、 @ref{a81,,OverflowError} もしくは @ref{2ec,,ValueError} を発生させます。
@end deffn

@menu
* 対話的なインタプリタオブジェクト:: 
* 対話的なコンソールオブジェクト:: 

@end menu

@node 対話的なインタプリタオブジェクト,対話的なコンソールオブジェクト,,code --- インタープリター基底クラス
@anchor{library/code interactive-interpreter-objects}@anchor{4aba}@anchor{library/code interpreter-objects}@anchor{4abb}
@subsubsection 対話的なインタプリタオブジェクト


@geindex runsource() (code.InteractiveInterpreter のメソッド)
@anchor{library/code code InteractiveInterpreter runsource}@anchor{4abc}
@deffn {メソッド} InteractiveInterpreter.runsource (source, filename='<input>', symbol='single')

インタプリタ内のあるソースをコンパイルし実行します。引数は @ref{4ab9,,compile_command()} のものと同じです。 `filename' のデフォルトは @code{'<input>'} で、 `symbol' は @code{'single'} です。あるいくつかのことが起きる可能性があります:


@itemize *

@item 
入力が不正。 @ref{4ab9,,compile_command()} が例外(@ref{18e,,SyntaxError} か @ref{a81,,OverflowError})を起こした場合。 @ref{4abd,,showsyntaxerror()} メソッドの呼び出によって、構文トレースバックが表示されるでしょう。 @ref{4abc,,runsource()} は @code{False} を返します。

@item 
入力が完全でなく、さらに入力が必要。 @ref{4ab9,,compile_command()} が @code{None} を返した場合。 @ref{4abc,,runsource()} は @code{True} を返します。

@item 
入力が完全。 @ref{4ab9,,compile_command()} がコードオブジェクトを返した場合。 (@ref{f3c,,SystemExit} を除く実行時例外も処理する) @ref{4abe,,runcode()} を呼び出すことによって、コードは実行されます。 @ref{4abc,,runsource()} は @code{False} を返します。
@end itemize

戻り値は、次の行のプロンプトに @code{sys.ps1} か @code{sys.ps2} のどちらを使うのか判断するために使えます。
@end deffn

@geindex runcode() (code.InteractiveInterpreter のメソッド)
@anchor{library/code code InteractiveInterpreter runcode}@anchor{4abe}
@deffn {メソッド} InteractiveInterpreter.runcode (code)

コードオブジェクトを実行します。例外が生じたときは、トレースバックを表示するために @ref{fce,,showtraceback()} が呼び出されます。伝搬することが許されている @ref{f3c,,SystemExit} を除くすべての例外が捉えられます。

@ref{bc5,,KeyboardInterrupt} についての注意。このコードの他の場所でこの例外が生じる可能性がありますし、常に捕らえることができるとは限りません。呼び出し側はそれを処理するために準備しておくべきです。
@end deffn

@geindex showsyntaxerror() (code.InteractiveInterpreter のメソッド)
@anchor{library/code code InteractiveInterpreter showsyntaxerror}@anchor{4abd}
@deffn {メソッド} InteractiveInterpreter.showsyntaxerror (filename=None)

起きたばかりの構文エラーを表示します。複数の構文エラーに対して一つあるのではないため、これはスタックトレースを表示しません。 `filename' が与えられた場合は、Pythonのパーサが与えるデフォルトのファイル名の代わりに例外の中へ入れられます。なぜなら、文字列から読み込んでいるときはパーサは常に @code{'<string>'} を使うからです。出力は @ref{4abf,,write()} メソッドによって書き込まれます。
@end deffn

@geindex showtraceback() (code.InteractiveInterpreter のメソッド)
@anchor{library/code code InteractiveInterpreter showtraceback}@anchor{fce}
@deffn {メソッド} InteractiveInterpreter.showtraceback ()

起きたばかりの例外を表示します。スタックの最初の項目を取り除きます。なぜなら、それはインタプリタオブジェクトの実装の内部にあるからです。出力は @ref{4abf,,write()} メソッドによって書き込まれます。


バージョン 3.5 で変更: 最初のトレースバックではなく、完全なトレースバックの連鎖が表示されます。

@end deffn

@geindex write() (code.InteractiveInterpreter のメソッド)
@anchor{library/code code InteractiveInterpreter write}@anchor{4abf}
@deffn {メソッド} InteractiveInterpreter.write (data)

文字列を標準エラーストリーム(@code{sys.stderr})へ書き込みます。必要に応じて適切な出力処理を提供するために、派生クラスはこれをオーバーライドすべきです。
@end deffn

@node 対話的なコンソールオブジェクト,,対話的なインタプリタオブジェクト,code --- インタープリター基底クラス
@anchor{library/code console-objects}@anchor{4ac0}@anchor{library/code interactive-console-objects}@anchor{4ac1}
@subsubsection 対話的なコンソールオブジェクト


@ref{2807,,InteractiveConsole} クラスは @ref{1943,,InteractiveInterpreter} のサブクラスです。以下の追加メソッドだけでなく、インタプリタオブジェクトのすべてのメソッドも提供します。

@geindex interact() (code.InteractiveConsole のメソッド)
@anchor{library/code code InteractiveConsole interact}@anchor{4ab8}
@deffn {メソッド} InteractiveConsole.interact (banner=None, exitmsg=None)

対話的な Python コンソールをそっくりにエミュレートします。オプションの `banner' 引数は最初のやりとりの前に表示するバナーを指定します。デフォルトでは、標準 Python インタプリタが表示するものと同じようなバナーを表示します。それに続けて、実際のインタプリタと混乱しないように (とても似ているから!) 括弧の中にコンソールオブジェクトのクラス名を表示します。

オプション引数の `exitmsg' は、終了時に出力される終了メッセージを指定します。空文字列を渡すと、出力メッセージを抑止します。もし、 `exitmsg' が与えられないか、@code{None} の場合は、デフォルトのメッセージが出力されます。


バージョン 3.4 で変更: バナーの表示を抑制するには、空の文字列を渡してください。



バージョン 3.6 で変更: 終了時に、終了メッセージを表示します。

@end deffn

@geindex push() (code.InteractiveConsole のメソッド)
@anchor{library/code code InteractiveConsole push}@anchor{4ac2}
@deffn {メソッド} InteractiveConsole.push (line)

ソーステキストの一行をインタープリターへ送ります。その行の末尾に改行がついていてはいけません。内部に改行を持っているかもしれません。その行はバッファへ追加され、ソースとして連結されたバッファの内容が渡されインタープリターの @ref{4abc,,runsource()} メソッドが呼び出されます。コマンドが実行されたか、有効であることをこれが示している場合は、バッファはリセットされます。そうでなければ、コマンドが不完全で、その行が付加された後のままバッファは残されます。さらに入力が必要ならば、戻り値は @code{True} です。その行がある方法で処理されたならば、 @code{False} です(これは @code{runsource()} と同じです)。
@end deffn

@geindex resetbuffer() (code.InteractiveConsole のメソッド)
@anchor{library/code code InteractiveConsole resetbuffer}@anchor{4ac3}
@deffn {メソッド} InteractiveConsole.resetbuffer ()

入力バッファから処理されていないソーステキストを取り除きます。
@end deffn

@geindex raw_input() (code.InteractiveConsole のメソッド)
@anchor{library/code code InteractiveConsole raw_input}@anchor{4ab7}
@deffn {メソッド} InteractiveConsole.raw_input (prompt='@w{'})

プロンプトを書き込み、一行を読み込みます。返る行は末尾に改行を含みません。ユーザがEOFキーシーケンスを入力したときは、 @ref{14f1,,EOFError} を発生させます。基本実装では、 @code{sys.stdin} から読み込みます。サブクラスはこれを異なる実装と置き換えるかもしれません。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node codeop --- Python コードをコンパイルする,,code --- インタープリター基底クラス,カスタム Python インタプリタ
@anchor{library/codeop doc}@anchor{4ac4}@anchor{library/codeop codeop-compile-python-code}@anchor{4ac5}@anchor{library/codeop module-codeop}@anchor{1d}@anchor{library/codeop translation-repo}@anchor{4ac6}
@subsection @code{codeop} --- Python コードをコンパイルする


@geindex module; codeop

`ソースコード:' Lib/codeop.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/codeop.py}


__________________________________________________________________


The @code{codeop} module provides utilities upon which the Python
read-eval-print loop can be emulated, as is done in the @ref{1b,,code} module.  As
a result, you probably don't want to use the module directly; if you want to
include such a loop in your program you probably want to use the @ref{1b,,code}
module instead.

この仕事には二つの部分があります:


@enumerate 

@item 
入力の一行がPythonの文として完全であるかどうかを見分けられること: 簡単に言えば、次が '@code{>>>}' か、あるいは '@code{...}' かどうかを見分けます。

@item 
どのfuture文をユーザが入力したのかを覚えていること。したがって、実質的にそれに続く入力をこれらとともにコンパイルすることができます。
@end enumerate

The @code{codeop} module provides a way of doing each of these things, and a way
of doing them both.

前者は実行するには:

@geindex compile_command() (codeop モジュール)
@anchor{library/codeop codeop compile_command}@anchor{1b53}
@deffn {の関数} codeop.compile_command (source, filename='<input>', symbol='single')

Pythonコードの文字列であるべき `source' をコンパイルしてみて、`source' が有効なPythonコードの場合はコードオブジェクトを返します。このような場合、コードオブジェクトのファイル名属性は、デフォルトで @code{'<input>'} である `filename' でしょう。`source' が有効なPythonコードでは `ない' が、有効なPythonコードの接頭語である場合には、@code{None} を返します。

`source' に問題がある場合は、例外を発生させます。無効なPython構文がある場合は、 @ref{18e,,SyntaxError} を発生させます。また、無効なリテラルがある場合は、 @ref{a81,,OverflowError} または @ref{2ec,,ValueError} を発生させます。

`symbol' 引数は `source' が文としてコンパイルされるか(@code{'single'} 、デフォルト) 、@ref{2bfc,,文} のシーケンスとしてか (@code{'exec'}) 、または @ref{23cf,,式} としてコンパイルされるかを決定します(@code{'eval'})。他のどんな値も @ref{2ec,,ValueError} を送出させます。

@cartouche
@quotation 注釈 
ソースの終わりに達する前に、成功した結果をもってパーサは構文解析を止めることがあります。このような場合、後ろに続く記号はエラーとならずに無視されます。例えば、バックスラッシュの後ろに改行が2つあって、その後ろにゴミがあるかもしれません。パーサのAPIがより良くなればすぐに、この挙動は修正されるでしょう。
@end quotation
@end cartouche
@end deffn

@geindex Compile (codeop のクラス)
@anchor{library/codeop codeop Compile}@anchor{4ac7}
@deffn {クラス} codeop.Compile

このクラスのインスタンスは組み込み関数 @ref{4b1,,compile()} とシグネチャが一致する @ref{77a,,__call__()} メソッドを持っていますが、インスタンスが @ref{0,,__future__} 文を含むプログラムテキストをコンパイルする場合は、インスタンスは有効なその文とともに続くすべてのプログラムテキストを'覚えていて'コンパイルするという違いがあります。
@end deffn

@geindex CommandCompiler (codeop のクラス)
@anchor{library/codeop codeop CommandCompiler}@anchor{4ac8}
@deffn {クラス} codeop.CommandCompiler

このクラスのインスタンスは @ref{1b53,,compile_command()} とシグネチャが一致する @ref{77a,,__call__()} メソッドを持っています。インスタンスが @ref{0,,__future__} 文を含むプログラムテキストをコンパイルする場合に、インスタンスは有効なその文とともにそれに続くすべてのプログラムテキストを'覚えていて'コンパイルするという違いがあります。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node モジュールのインポート,Python言語サービス,カスタム Python インタプリタ,Python 標準ライブラリ
@anchor{library/modules doc}@anchor{4ac9}@anchor{library/modules importing-modules}@anchor{4aca}@anchor{library/modules modules}@anchor{4acb}@anchor{library/modules translation-repo}@anchor{4acc}
@section モジュールのインポート


この章で解説されるモジュールは他のPythonモジュールをインポートする新しい方法と、インポート処理をカスタマイズするためのフックを提供します。

この章で解説されるモジュールの完全な一覧は:

@menu
* zipimport: zipimport --- Zip アーカイブからモジュールをインポートする. Zip アーカイブからモジュールをインポートする
* pkgutil: pkgutil --- パッケージ拡張ユーティリティ. パッケージ拡張ユーティリティ
* modulefinder: modulefinder --- スクリプト中で使用されているモジュールの検索. スクリプト中で使用されているモジュールの検索
* runpy: runpy --- Python モジュールの位置特定と実行. Python モジュールの位置特定と実行
* importlib: importlib --- import の実装. import の実装
* importlib.resources: importlib resources -- パッケージリソースの読み取り、オープン、アクセス. パッケージリソースの読み取り、オープン、アクセス
* importlib.resources.abc: importlib resources abc -- リソースの抽象基底クラス. リソースの抽象基底クラス
* importlib.metadata: importlib metadata -- パッケージメタデータへのアクセス. パッケージメタデータへのアクセス
* sys.path モジュール検索パスの初期化: sys path モジュール検索パスの初期化. 

@end menu

@node zipimport --- Zip アーカイブからモジュールをインポートする,pkgutil --- パッケージ拡張ユーティリティ,,モジュールのインポート
@anchor{library/zipimport doc}@anchor{4acd}@anchor{library/zipimport module-zipimport}@anchor{138}@anchor{library/zipimport zipimport-import-modules-from-zip-archives}@anchor{4ace}
@subsection @code{zipimport} --- Zip アーカイブからモジュールをインポートする


@geindex module; zipimport

`ソースコード:' Lib/zipimport.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/zipimport.py}


__________________________________________________________________


This module adds the ability to import Python modules (@code{*.py},
@code{*.pyc}) and packages from ZIP-format archives. It is usually not
needed to use the @code{zipimport} module explicitly; it is automatically used
by the built-in @ref{7f8,,import} mechanism for @ref{3e4,,sys.path} items that are paths
to ZIP archives.

普通、 @ref{3e4,,sys.path} はディレクトリ名の文字列からなるリストです。このモジュールを使うと、 @ref{3e4,,sys.path} の要素に ZIP ファイルアーカイブを示す文字列を使えるようになります。ZIP アーカイブにはサブディレクトリ構造を含めることができ、パッケージの import をサポートさせたり、アーカイブ内のパスを指定してサブディレクトリ下から import を行わせたりできます。例えば、 @code{example.zip/lib/} のように指定すると、アーカイブ中の  @code{lib/} サブディレクトリ下だけから import を行います。

ZIP アーカイブ内にはどんなファイルを置いてもかまいませんが、インポートは @code{.py} および @code{.pyc} ファイルにのみ呼び出されます。動的モジュール (@code{.pyd}, @code{.so}) の ZIP インポートは行えません。アーカイブ内に @code{.py} ファイルしかない場合、 Python は対応する @code{.pyc} ファイルを追加してアーカイブを変更しようとはしません。つまり、 ZIP アーカイブ内に @code{.pyc} がない場合は、インポートが多少遅くなるかもしれないので注意してください。


バージョン 3.13 で変更: ZIP64 is supported



バージョン 3.8 で変更: 以前は、アーカイブコメント付きの ZIP アーカイブはサポートされていませんでした。



@subsubheading 参考



@table @asis

@item PKZIP Application Note@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT}

ZIP ファイルフォーマットおよびアルゴリズムを作成した Phil Katz によるドキュメント。

@geindex Python Enhancement Proposals; PEP 273

@item PEP 273@footnote{https://peps.python.org/pep-0273/} - Zip アーカイブからモジュールをインポートする

このモジュールの実装も行った、James C. Ahlstrom による PEP です。Python 2.3 は 
@geindex Python Enhancement Proposals; PEP 273
PEP 273@footnote{https://peps.python.org/pep-0273/} の仕様に従っていますが、Just van Rossum の書いた import フックによる実装を使っています。インポートフックは 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} で解説されています。

@item @ref{7b,,importlib} - @ref{7f8,,import} の実装

Package providing the relevant protocols for all importers to
implement.
@end table


このモジュールでは例外を一つ定義しています:

@geindex ZipImportError
@anchor{library/zipimport zipimport ZipImportError}@anchor{4acf}
@deffn {例外} zipimport.ZipImportError

zipimporter オブジェクトが送出する例外です。 @ref{65b,,ImportError} のサブクラスなので、 @ref{65b,,ImportError} としても捕捉できます。
@end deffn

@menu
* zipimporter オブジェクト:: 
* 使用例: 使用例<47>. 

@end menu

@node zipimporter オブジェクト,使用例<47>,,zipimport --- Zip アーカイブからモジュールをインポートする
@anchor{library/zipimport id1}@anchor{4ad0}@anchor{library/zipimport zipimporter-objects}@anchor{4ad1}
@subsubsection zipimporter オブジェクト


@ref{4ad2,,zipimporter} は ZIP ファイルを import するためのクラスです。

@geindex zipimporter (zipimport のクラス)
@anchor{library/zipimport zipimport zipimporter}@anchor{4ad2}
@deffn {クラス} zipimport.zipimporter (archivepath)

新たな zipimporter インスタンスを生成します。 `archivepath' は ZIP ファイルへのパスまたは ZIP ファイル中の特定のパスへのパスでなければなりません。たとえば、 @code{foo/bar.zip/lib} という `archivepath' の場合、 @code{foo/bar.zip} という ZIP ファイルの中の @code{lib} ディレクトリにあるモジュールを (存在するものとして) 検索します。

`archivepath' が有効な ZIP アーカイブを指していない場合、 @ref{4acf,,ZipImportError} を送出します。


バージョン 3.12 で変更: Methods @code{find_loader()} and @code{find_module()}, deprecated in 3.10 are
now removed.  Use @ref{a5e,,find_spec()} instead.


@geindex create_module() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter create_module}@anchor{a5f}
@deffn {メソッド} create_module (spec)

Implementation of @ref{eac,,importlib.abc.Loader.create_module()} that returns
@ref{885,,None} to explicitly request the default semantics.


Added in version 3.10.

@end deffn

@geindex exec_module() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter exec_module}@anchor{339}
@deffn {メソッド} exec_module (module)

@ref{a6a,,importlib.abc.Loader.exec_module()} の実装です。


Added in version 3.10.

@end deffn

@geindex find_spec() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter find_spec}@anchor{a5e}
@deffn {メソッド} find_spec (fullname, target=None)

@ref{a6c,,importlib.abc.PathEntryFinder.find_spec()} の実装です。


Added in version 3.10.

@end deffn

@geindex get_code() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter get_code}@anchor{4ad3}
@deffn {メソッド} get_code (fullname)

`fullname' に指定したモジュールのコードオブジェクトを返します。モジュールがインポートできなかった場合には @ref{4acf,,ZipImportError} を送出します。
@end deffn

@geindex get_data() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter get_data}@anchor{4ad4}
@deffn {メソッド} get_data (pathname)

`pathname' に関連付けられたデータを返します。該当するファイルが見つからなかった場合には @ref{2c0,,OSError} を送出します。


バージョン 3.3 で変更: 以前は @ref{125e,,IOError} が送出されました; それは現在 @ref{2c0,,OSError} のエイリアスです。

@end deffn

@geindex get_filename() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter get_filename}@anchor{4ad5}
@deffn {メソッド} get_filename (fullname)

指定されたモジュールが import された場合、そのモジュールに設定した @code{__file__} の値を返します。モジュールがインポートできなかった場合、 @ref{4acf,,ZipImportError} を送出します。


Added in version 3.1.

@end deffn

@geindex get_source() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter get_source}@anchor{4ad6}
@deffn {メソッド} get_source (fullname)

`fullname' で指定されたモジュールのソースコードを返します。モジュールが見つからない場合、@ref{4acf,,ZipImportError} を送出します。アーカイブにはモジュールがあるもののソースコードがない場合、 @ref{885,,None} を返します。
@end deffn

@geindex is_package() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter is_package}@anchor{4ad7}
@deffn {メソッド} is_package (fullname)

`fullname' で指定されたモジュールがパッケージの場合 @code{True} を返します。モジュールを見つけられない場合 @ref{4acf,,ZipImportError} を送出します。
@end deffn

@geindex load_module() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter load_module}@anchor{338}
@deffn {メソッド} load_module (fullname)

Load the module specified by `fullname'. `fullname' must be the fully
qualified (dotted) module name. Returns the imported module on success,
raises @ref{4acf,,ZipImportError} on failure.


Deprecated since version 3.10, will be removed in version 3.15: 代わりに @ref{339,,exec_module()} を使用してください。

@end deffn

@geindex invalidate_caches() (zipimport.zipimporter のメソッド)
@anchor{library/zipimport zipimport zipimporter invalidate_caches}@anchor{a60}
@deffn {メソッド} invalidate_caches ()

Clear out the internal cache of information about files found within
the ZIP archive.


Added in version 3.10.

@end deffn

@geindex archive (zipimport.zipimporter の属性)
@anchor{library/zipimport zipimport zipimporter archive}@anchor{4ad8}
@deffn {の属性} archive

importer に関連付けられた ZIP ファイルのファイル名です。サブパスは含まれません。
@end deffn

@geindex prefix (zipimport.zipimporter の属性)
@anchor{library/zipimport zipimport zipimporter prefix}@anchor{4ad9}
@deffn {の属性} prefix

モジュールを検索する ZIP ファイル中のサブパスです。この文字列は ZIP ファイルのルートを指している zipimporter オブジェクトでは空です。
@end deffn

スラッシュでつなげると、@ref{4ad8,,archive} と @ref{4ad9,,prefix} 属性は @ref{4ad2,,zipimporter} コンストラクタに渡された元々の `archivepath' 引数と等しくなります。
@end deffn

@node 使用例<47>,,zipimporter オブジェクト,zipimport --- Zip アーカイブからモジュールをインポートする
@anchor{library/zipimport examples}@anchor{4ada}@anchor{library/zipimport zipimport-examples}@anchor{4adb}
@subsubsection 使用例


Here is an example that imports a module from a ZIP archive - note that the
@code{zipimport} module is not explicitly used.

@example
$ unzip -l example_archive.zip
Archive:  example_archive.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  01-01-00 12:30   example.py
 --------                   -------
     8467                   1 file
@end example

@example
>>> import sys
>>> # Add the archive to the front of the module search path
>>> sys.path.insert(0, 'example_archive.zip')
>>> import example
>>> example.__file__
'example_archive.zip/example.py'
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pkgutil --- パッケージ拡張ユーティリティ,modulefinder --- スクリプト中で使用されているモジュールの検索,zipimport --- Zip アーカイブからモジュールをインポートする,モジュールのインポート
@anchor{library/pkgutil doc}@anchor{4adc}@anchor{library/pkgutil module-pkgutil}@anchor{ae}@anchor{library/pkgutil pkgutil-package-extension-utility}@anchor{4add}@anchor{library/pkgutil translation-repo}@anchor{4ade}
@subsection @code{pkgutil} --- パッケージ拡張ユーティリティ


@geindex module; pkgutil

`ソースコード:' Lib/pkgutil.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pkgutil.py}


__________________________________________________________________


このモジュールはインポートシステムの、特にパッケージサポートに関するユーティリティです。

@geindex ModuleInfo (pkgutil のクラス)
@anchor{library/pkgutil pkgutil ModuleInfo}@anchor{f48}
@deffn {クラス} pkgutil.ModuleInfo (module_finder, name, ispkg)

モジュールの概要情報を格納する namedtuple


Added in version 3.6.

@end deffn

@geindex extend_path() (pkgutil モジュール)
@anchor{library/pkgutil pkgutil extend_path}@anchor{1924}
@deffn {の関数} pkgutil.extend_path (path, name)

パッケージを構成するモジュールの検索パスを拡張します。パッケージの @code{__init__.py} で次のように書くことを意図したものです:

@example
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
@end example

For each directory on @ref{3e4,,sys.path} that has a subdirectory that matches the
package name, add the subdirectory to the package's
@ref{2054,,__path__}. This is useful
if one wants to distribute different parts of a single logical package as multiple
directories.

It also looks for @code{*.pkg} files beginning where @code{*} matches the
`name' argument.  This feature is similar to @code{*.pth} files (see the
@ref{cc,,site} module for more information), except that it doesn't special-case
lines starting with @code{import}.  A @code{*.pkg} file is trusted at face
value: apart from skipping blank lines and ignoring comments, all entries
found in a @code{*.pkg} file are added to the path, regardless of whether
they exist on the filesystem (this is a feature).

入力パスがリストでない場合(フリーズされたパッケージのとき)は何もせずにリターンします。入力パスが変更されていなければ、アイテムを末尾に追加しただけのコピーを返します。

@ref{3e4,,sys.path} はシーケンスであることが前提になっています。 @ref{3e4,,sys.path} の要素の内、実在するディレクトリを指す文字列となっていないものは無視されます。ファイル名として使ったときにエラーが発生する @ref{3e4,,sys.path} の Unicode要素がある場合、この関数(@ref{c05,,os.path.isdir()} を実行している行) で例外が発生する可能性があります。
@end deffn

@geindex get_importer() (pkgutil モジュール)
@anchor{library/pkgutil pkgutil get_importer}@anchor{4adf}
@deffn {の関数} pkgutil.get_importer (path_item)

指定された `path_item' に対する @ref{236a,,finder} を取得します。

path hook により新しい finder が作成された場合は、それは @ref{7fa,,sys.path_importer_cache} にキャッシュされます。

キャッシュ (やその一部) は、 @ref{1225,,sys.path_hooks} のリスキャンが必要になった場合は手動でクリアすることができます。


バージョン 3.3 で変更: パッケージ内部の 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} エミュレーションに依存するのではなく直接的に @ref{7b,,importlib} に基くように更新されました。

@end deffn

@geindex iter_importers() (pkgutil モジュール)
@anchor{library/pkgutil pkgutil iter_importers}@anchor{13b1}
@deffn {の関数} pkgutil.iter_importers (fullname='@w{'})

Yield @ref{236a,,finder} objects for the given module name.

If `fullname' contains a @code{'.'}, the finders will be for the package
containing `fullname', otherwise they will be all registered top level
finders (i.e. those on both @ref{f27,,sys.meta_path} and @ref{1225,,sys.path_hooks}).

その名前のついたモジュールがパッケージ内に含まれている場合、この関数を実行した副作用としてそのパッケージが import されます。

モジュール名が指定されない場合は全てのトップレベルの finder が生成されます。


バージョン 3.3 で変更: パッケージ内部の 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} エミュレーションに依存するのではなく直接的に @ref{7b,,importlib} に基くように更新されました。

@end deffn

@geindex iter_modules() (pkgutil モジュール)
@anchor{library/pkgutil pkgutil iter_modules}@anchor{f47}
@deffn {の関数} pkgutil.iter_modules (path=None, prefix='@w{'})

`path' を指定すればそのすべてのサブモジュールに対して、 `path' が @code{None} なら @ref{3e4,,sys.path} のすべてのトップレベルモジュールに対して、@ref{f48,,ModuleInfo} を yield します。

`path' は @code{None} か、モジュールを検索する path のリストのどちらかでなければなりません。

`prefix' は出力の全てのモジュール名の頭に出力する文字列です。

@cartouche
@quotation 注釈 
これは @code{iter_modules()} メソッドを定義している @ref{236a,,finder} に対してのみ動作します。このインターフェイスは非標準なので、モジュールは @ref{127e,,importlib.machinery.FileFinder} と @ref{4ad2,,zipimport.zipimporter} の実装も提供します。
@end quotation
@end cartouche


バージョン 3.3 で変更: パッケージ内部の 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} エミュレーションに依存するのではなく直接的に @ref{7b,,importlib} に基くように更新されました。

@end deffn

@geindex walk_packages() (pkgutil モジュール)
@anchor{library/pkgutil pkgutil walk_packages}@anchor{df9}
@deffn {の関数} pkgutil.walk_packages (path=None, prefix='@w{'}, onerror=None)

`path' を指定すれば再帰的にその中のモジュールすべてに対して、 `path' が @code{None} ならばアクセスできるすべてのモジュールに対して、@ref{f48,,ModuleInfo} を yield します。

`path' は @code{None} か、モジュールを検索する path のリストのどちらかでなければなりません。

`prefix' は出力の全てのモジュール名の頭に出力する文字列です。

この関数は与えられた `path' 上の全ての `パッケージ' (全てのモジュール `ではない') を、サブモジュールを検索するのに必要な @code{__path__} 属性にアクセスするために import します。

`onerror' は、パッケージを import しようとしたときに何かの例外が発生した場合に、 1つの引数 (import しようとしていたパッケージの名前) で呼び出される関数です。 `onerror' 関数が提供されない場合、 @ref{65b,,ImportError} は補足され無視されます。それ以外の全ての例外は伝播し、検索を停止させます。

例:

@example
# list all modules python can access
walk_packages()

# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__ + '.')
@end example

@cartouche
@quotation 注釈 
これは @code{iter_modules()} メソッドを定義している @ref{236a,,finder} に対してのみ動作します。このインターフェイスは非標準なので、モジュールは @ref{127e,,importlib.machinery.FileFinder} と @ref{4ad2,,zipimport.zipimporter} の実装も提供します。
@end quotation
@end cartouche


バージョン 3.3 で変更: パッケージ内部の 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} エミュレーションに依存するのではなく直接的に @ref{7b,,importlib} に基くように更新されました。

@end deffn

@geindex get_data() (pkgutil モジュール)
@anchor{library/pkgutil pkgutil get_data}@anchor{4ae0}
@deffn {の関数} pkgutil.get_data (package, resource)

パッケージからリソースを取得します。

この関数は @ref{1a28,,loader} @ref{4ae1,,get_data} API のラッパーです。 `package' 引数は標準的なモジュール形式 (@code{foo.bar}) のパッケージ名でなければなりません。 `resource' 引数は @code{/} をパス区切りに使った相対ファイル名の形式です。親ディレクトリを @code{..} としたり、ルートからの (@code{/} で始まる) 名前を使うことはできません。

この関数が返すのは指定されたリソースの内容であるバイナリ文字列です。

ファイルシステム中に位置するパッケージで既にインポートされているものに対しては、次と大体同じです:

@example
d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()
@end example

If the package cannot be located or loaded, or it uses a @ref{1a28,,loader}
which does not support @ref{4ae1,,get_data},
then @code{None} is returned.  In particular, the @ref{1a28,,loader} for
@ref{2b2,,namespace packages} does not support
@ref{4ae1,,get_data}.
@end deffn

@geindex resolve_name() (pkgutil モジュール)
@anchor{library/pkgutil pkgutil resolve_name}@anchor{4ae2}
@deffn {の関数} pkgutil.resolve_name (name)

Resolve a name to an object.

This functionality is used in numerous places in the standard library (see
bpo-12915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12915}) - 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:


@itemize *

@item 
@code{W(.W)*}

@item 
@code{W(.W)*:(W(.W)*)?}
@end itemize

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:

@ref{2ec,,ValueError} -- if `name' isn't in a recognised format.

@ref{65b,,ImportError} -- if an import failed when it shouldn't have.

@ref{5f0,,AttributeError} -- If a failure occurred when traversing the object
hierarchy within the imported package to get to the desired object.


Added in version 3.9.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node modulefinder --- スクリプト中で使用されているモジュールの検索,runpy --- Python モジュールの位置特定と実行,pkgutil --- パッケージ拡張ユーティリティ,モジュールのインポート
@anchor{library/modulefinder doc}@anchor{4ae3}@anchor{library/modulefinder module-modulefinder}@anchor{95}@anchor{library/modulefinder modulefinder-find-modules-used-by-a-script}@anchor{4ae4}@anchor{library/modulefinder translation-repo}@anchor{4ae5}
@subsection @code{modulefinder} --- スクリプト中で使用されているモジュールの検索


@geindex module; modulefinder

`ソースコード:' Lib/modulefinder.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/modulefinder.py}


__________________________________________________________________


このモジュールでは、スクリプト中で import されているモジュールセットを調べるために使える @ref{1de5,,ModuleFinder} クラスを提供しています。 @code{modulefinder.py} はまた、Python スクリプトのファイル名を引数に指定してスクリプトとして実行し、 import されているモジュールのレポートを出力させることもできます。

@geindex AddPackagePath() (modulefinder モジュール)
@anchor{library/modulefinder modulefinder AddPackagePath}@anchor{4ae6}
@deffn {の関数} modulefinder.AddPackagePath (pkg_name, path)

`pkg_name' という名前のパッケージの在り処が `path' であることを記録します。
@end deffn

@geindex ReplacePackage() (modulefinder モジュール)
@anchor{library/modulefinder modulefinder ReplacePackage}@anchor{4ae7}
@deffn {の関数} modulefinder.ReplacePackage (oldname, newname)

実際にはパッケージ内で `oldname' という名前になっているモジュールを `newname' という名前で指定できるようにします。
@end deffn

@geindex ModuleFinder (modulefinder のクラス)
@anchor{library/modulefinder modulefinder ModuleFinder}@anchor{1de5}
@deffn {クラス} modulefinder.ModuleFinder (path=None, debug=0, excludes=[], replace_paths=[])

このクラスでは @ref{4ae8,,run_script()} および @ref{4ae9,,report()}  メソッドを提供しています。これらのメソッドは何らかのスクリプト中で import されているモジュールの集合を調べます。 `path' はモジュールを検索する先のディレクトリ名からなるリストです。 `path' を指定しない場合、 @code{sys.path} を使います。 `debug' にはデバッグレベルを設定します; 値を大きくすると、実行している内容を表すデバッグメッセージを出力します。 `excludes' は検索から除外するモジュール名です。 `replace_paths' には、モジュールパス内で置き換えられるパスをタプル @code{(oldpath, newpath)} からなるリストで指定します。

@geindex report() (modulefinder.ModuleFinder のメソッド)
@anchor{library/modulefinder modulefinder ModuleFinder report}@anchor{4ae9}
@deffn {メソッド} report ()

スクリプトで import しているモジュールと、そのパスからなるリストを列挙したレポートを標準出力に出力します。モジュールを見つけられなかったり、モジュールがないように見える場合にも報告します。
@end deffn

@geindex run_script() (modulefinder.ModuleFinder のメソッド)
@anchor{library/modulefinder modulefinder ModuleFinder run_script}@anchor{4ae8}
@deffn {メソッド} run_script (pathname)

`pathname' に指定したファイルの内容を解析します。ファイルには Python コードが入っていなければなりません。
@end deffn

@geindex modules (modulefinder.ModuleFinder の属性)
@anchor{library/modulefinder modulefinder ModuleFinder modules}@anchor{4aea}
@deffn {の属性} modules

モジュール名をモジュールに結びつける辞書。 @ref{4aeb,,ModuleFinder の使用例} を参照して下さい。
@end deffn
@end deffn

@menu
* ModuleFinder の使用例:: 

@end menu

@node ModuleFinder の使用例,,,modulefinder --- スクリプト中で使用されているモジュールの検索
@anchor{library/modulefinder example-usage-of-modulefinder}@anchor{4aec}@anchor{library/modulefinder modulefinder-example}@anchor{4aeb}
@subsubsection @code{ModuleFinder} の使用例


解析対象のスクリプトはこれ (bacon.py) です:

@example
import re, itertools

try:
    import baconhameggs
except ImportError:
    pass

try:
    import guido.python.ham
except ImportError:
    pass
@end example

bacon.py のレポートを出力するスクリプトです:

@example
from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('bacon.py')

print('Loaded modules:')
for name, mod in finder.modules.items():
    print('%s: ' % name, end='@w{'})
    print(','.join(list(mod.globalnames.keys())[:3]))

print('-'*50)
print('Modules not imported:')
print('\n'.join(finder.badmodules.keys()))
@end example

出力例です (アーキテクチャに依って違ってくるかもしれません):

@example
Loaded modules:
_types:
copyreg:  _inverted_registry,_slotnames,__all__
re._compiler:  isstring,_sre,_optimize_unicode
_sre:
re._constants:  REPEAT_ONE,makedict,AT_END_LINE
sys:
re:  __module__,finditer,_expand
itertools:
__main__:  re,itertools,baconhameggs
re._parser:  _PATTERNENDERS,SRE_FLAG_UNICODE
array:
types:  __module__,IntType,TypeType
---------------------------------------------------
Modules not imported:
guido.python.ham
baconhameggs
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node runpy --- Python モジュールの位置特定と実行,importlib --- import の実装,modulefinder --- スクリプト中で使用されているモジュールの検索,モジュールのインポート
@anchor{library/runpy doc}@anchor{4aed}@anchor{library/runpy module-runpy}@anchor{c3}@anchor{library/runpy runpy-locating-and-executing-python-modules}@anchor{4aee}@anchor{library/runpy translation-repo}@anchor{4aef}
@subsection @code{runpy} --- Python モジュールの位置特定と実行


@geindex module; runpy

`ソースコード:' Lib/runpy.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/runpy.py}


__________________________________________________________________


The @code{runpy} module is used to locate and run Python modules without
importing them first. Its main use is to implement the @ref{23c,,-m} command
line switch that allows scripts to be located using the Python module
namespace rather than the filesystem.

これはサンドボックスモジュール `ではない' ことに注意してください。すべてのコードは現在のプロセスで実行され、あらゆる副作用 (たとえば他のモジュールのキャッシュされたインポート等) は関数から戻った後にそのまま残ります。

Furthermore, any functions and classes defined by the executed code are not
guaranteed to work correctly after a @code{runpy} function has returned.
If that limitation is not acceptable for a given use case, @ref{7b,,importlib}
is likely to be a more suitable choice than this module.

The @code{runpy} module provides two functions:

@geindex run_module() (runpy モジュール)
@anchor{library/runpy runpy run_module}@anchor{1b97}
@deffn {の関数} runpy.run_module (mod_name, init_globals=None, run_name=None, alter_sys=False)

@geindex module;__main__

Execute the code of the specified module and return the resulting module's
globals dictionary. The module's code is first located using the standard
import mechanism (refer to 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} for details) and then executed in a
fresh module namespace.

The `mod_name' argument should be an absolute module name.
If the module name refers to a package rather than a normal
module, then that package is imported and the @ref{1,,__main__} submodule within
that package is then executed and the resulting module globals dictionary
returned.

The optional dictionary argument `init_globals' may be used to pre-populate
the module's globals dictionary before the code is executed.
`init_globals' will not be modified. If any of the special global variables
below are defined in `init_globals', those definitions are
overridden by @ref{1b97,,run_module()}.

The special global variables @code{__name__}, @code{__spec__}, @code{__file__},
@code{__cached__}, @code{__loader__} and @code{__package__} are set in the globals
dictionary before the module code is executed. (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail.)

@code{__name__} は、オプション引数 `run_name' が @ref{885,,None} でない場合、指定されたモジュールがパッケージであれば @code{mod_name + '.__main__'} に、そうでなければ `mod_name' 引数の値がセットされます。

@code{__spec__} will be set appropriately for the `actually' imported
module (that is, @code{__spec__.name} will always be `mod_name' or
@code{mod_name + '.__main__'}, never `run_name').

@code{__file__}, @code{__cached__}, @code{__loader__} and @code{__package__} are
@ref{2361,,set as normal} based on the module spec.

引数 `alter_sys' が与えられて @ref{e07,,True} に評価されるならば、 @code{sys.argv[0]} は @code{__file__} の値で更新され @code{sys.modules[__name__]} は実行されるモジュールの一時的モジュールオブジェクトで更新されます。 @code{sys.argv[0]} と @code{sys.modules[__name__]} はどちらも関数が処理を戻す前にもとの値に復旧します。

Note that this manipulation of @ref{df,,sys} is not thread-safe. Other threads
may see the partially initialised module, as well as the altered list of
arguments. It is recommended that the @code{sys} module be left alone when
invoking this function from threaded code.


@subsubheading 参考


コマンドラインから、 @ref{23c,,-m} オプションを与えることで同じ機能を実現出来ます。



バージョン 3.1 で変更: Added ability to execute packages by looking for a @ref{1,,__main__} submodule.



バージョン 3.2 で変更: @code{__cached__} グローバル変数が追加されました (
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} を参照)。



バージョン 3.4 で変更: Updated to take advantage of the module spec feature added by
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/}. This allows @code{__cached__} to be set correctly for modules
run this way, as well as ensuring the real module name is always
accessible as @code{__spec__.name}.



バージョン 3.12 で変更: The setting of @code{__cached__}, @code{__loader__}, and
@code{__package__} are deprecated. See
@ref{226c,,ModuleSpec} for alternatives.

@end deffn

@geindex run_path() (runpy モジュール)
@anchor{library/runpy runpy run_path}@anchor{4a4}
@deffn {の関数} runpy.run_path (path_name, init_globals=None, run_name=None)

@geindex module;__main__

Execute the code at the named filesystem location and return the resulting
module's globals dictionary. As with a script name supplied to the CPython
command line, `file_path' may refer to a Python source file, a
compiled bytecode file or a valid @ref{3e4,,sys.path} entry containing a
@ref{1,,__main__} module
(e.g. a zipfile containing a top-level @code{__main__.py} file).

For a simple script, the specified code is simply executed in a fresh
module namespace. For a valid @ref{3e4,,sys.path} entry (typically a zipfile or
directory), the entry is first added to the beginning of @code{sys.path}. The
function then looks for and executes a @ref{1,,__main__} module using the
updated path. Note that there is no special protection against invoking
an existing @code{__main__} entry located elsewhere on @code{sys.path} if
there is no such module at the specified location.

The optional dictionary argument `init_globals' may be used to pre-populate
the module's globals dictionary before the code is executed.
`init_globals' will not be modified. If any of the special global variables
below are defined in `init_globals', those definitions are
overridden by @ref{4a4,,run_path()}.

The special global variables @code{__name__}, @code{__spec__}, @code{__file__},
@code{__cached__}, @code{__loader__} and @code{__package__} are set in the globals
dictionary before the module code is executed. (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail.)

@code{__name__} は、オプション引数 `run_name' が @ref{885,,None} でない場合、 `run_name' に設定され、それ以外の場合は @code{'<run_path>'} に設定されます。

If `file_path' directly references a script file (whether as source
or as precompiled byte code), then @code{__file__} will be set to
`file_path', and @code{__spec__}, @code{__cached__}, @code{__loader__} and
@code{__package__} will all be set to @ref{885,,None}.

If `file_path' is a reference to a valid @ref{3e4,,sys.path} entry, then
@code{__spec__} will be set appropriately for the imported @ref{1,,__main__}
module (that is, @code{__spec__.name} will always be @code{__main__}).
@code{__file__}, @code{__cached__}, @code{__loader__} and @code{__package__} will be
@ref{2361,,set as normal} based on the module spec.

A number of alterations are also made to the @ref{df,,sys} module. Firstly,
@ref{3e4,,sys.path} may be altered as described above. @code{sys.argv[0]} is updated
with the value of `file_path' and @code{sys.modules[__name__]} is updated
with a temporary module object for the module being executed. All
modifications to items in @ref{df,,sys} are reverted before the function
returns.

Note that, unlike @ref{1b97,,run_module()}, the alterations made to @ref{df,,sys}
are not optional in this function as these adjustments are essential to
allowing the execution of @ref{3e4,,sys.path} entries. As the thread-safety
limitations still apply, use of this function in threaded code should be
either serialised with the import lock or delegated to a separate process.


@subsubheading 参考


コマンドラインから @ref{211b,,インターフェイスオプション} で同じ機能を使えます (@code{python path/to/script})。



Added in version 3.2.



バージョン 3.4 で変更: Updated to take advantage of the module spec feature added by
@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/}. This allows @code{__cached__} to be set correctly in the
case where @code{__main__} is imported from a valid @ref{3e4,,sys.path} entry rather
than being executed directly.



バージョン 3.12 で変更: The setting of @code{__cached__}, @code{__loader__}, and
@code{__package__} are deprecated.

@end deffn


@subsubheading 参考



@table @asis

@geindex Python Enhancement Proposals; PEP 338

@item PEP 338@footnote{https://peps.python.org/pep-0338/} - モジュールをスクリプトとして実行する

PEP written and implemented by Nick Coghlan.

@geindex Python Enhancement Proposals; PEP 366

@item PEP 366@footnote{https://peps.python.org/pep-0366/} - main モジュールの明示的な相対インポート

PEP written and implemented by Nick Coghlan.

@geindex Python Enhancement Proposals; PEP 451

@item PEP 451@footnote{https://peps.python.org/pep-0451/} -- インポートシステムのための ModuleSpec 型

PEP written and implemented by Eric Snow
@end table

@ref{1da7,,コマンドラインと環境} - CPython コマンドライン詳細

@ref{73c,,importlib.import_module()} 関数


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node importlib --- import の実装,importlib resources -- パッケージリソースの読み取り、オープン、アクセス,runpy --- Python モジュールの位置特定と実行,モジュールのインポート
@anchor{library/importlib doc}@anchor{4af0}@anchor{library/importlib importlib-the-implementation-of-import}@anchor{4af1}@anchor{library/importlib module-importlib}@anchor{7b}@anchor{library/importlib translation-repo}@anchor{4af2}
@subsection @code{importlib} --- @code{import} の実装


@geindex module; importlib


Added in version 3.1.


`ソースコード:' Lib/importlib/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/importlib/__init__.py}


__________________________________________________________________


@menu
* はじめに: はじめに<13>. 
* 関数: 関数<13>. 
* importlib.abc: importlib abc -- Abstract base classes related to import. Abstract base classes related to import
* importlib.machinery: importlib machinery -- Importers and path hooks. Importers and path hooks
* importlib.util: importlib util -- Utility code for importers. Utility code for importers
* 使用例: 使用例<48>. 

@end menu

@node はじめに<13>,関数<13>,,importlib --- import の実装
@anchor{library/importlib introduction}@anchor{4af3}
@subsubsection はじめに


The purpose of the @code{importlib} package is three-fold.

1つ目は Python ソースコード中にある @ref{7f8,,import} 文の(そして、拡張として、 @ref{ad1,,__import__()} 関数の)実装を提供することです。このパッケージは @code{import} 文の、どの Python インタープリターでも動作する実装を提供します。また、 Python 以外の言語で実装されたどの実装よりも把握しやすい実装を提供します。

2つ目の目的は、このパッケージが公開している @ref{7f8,,import} を実装するための要素を利用して、(@ref{2448,,インポーター} として知られる) インポートプロセスで動作するカスタムのオブジェクトを実装しやすくすることです。

Three, the package contains modules exposing additional functionality for
managing aspects of Python packages:


@itemize *

@item 
@ref{7e,,importlib.metadata} presents access to metadata from third-party
distributions.

@item 
@ref{7f,,importlib.resources} provides routines for accessing non-code
"resources" from Python packages.
@end itemize


@subsubheading 参考



@table @asis

@item @ref{7f8,,import 文}

@ref{7f8,,import} 文の言語リファレンス。

@item Packages specification@footnote{https://www.python.org/doc/essays/packages/}

パッケージの元の仕様。幾つかの動作はこの仕様が書かれた頃から変更されています (例: @ref{17e6,,sys.modules} で @code{None} に基づくリダイレクト)。

@item @ref{1279,,__import__()} 関数

@ref{7f8,,import} 文はこの関数のシンタックスシュガーです。

@item @ref{18dc,,sys.path モジュール検索パスの初期化}

The initialization of @ref{3e4,,sys.path}.

@geindex Python Enhancement Proposals; PEP 235

@item PEP 235@footnote{https://peps.python.org/pep-0235/}

大文字小文字を区別しないプラットフォームでのインポート

@geindex Python Enhancement Proposals; PEP 263

@item PEP 263@footnote{https://peps.python.org/pep-0263/}

Python のソースコードのエンコーディング

@geindex Python Enhancement Proposals; PEP 302

@item PEP 302@footnote{https://peps.python.org/pep-0302/}

新しいインポートフック

@geindex Python Enhancement Proposals; PEP 328

@item PEP 328@footnote{https://peps.python.org/pep-0328/}

複数行のインポートと、絶対/相対インポート

@geindex Python Enhancement Proposals; PEP 366

@item PEP 366@footnote{https://peps.python.org/pep-0366/}

main モジュールの明示的な相対インポート

@geindex Python Enhancement Proposals; PEP 420

@item PEP 420@footnote{https://peps.python.org/pep-0420/}

暗黙的な名前空間パッケージ

@geindex Python Enhancement Proposals; PEP 451

@item PEP 451@footnote{https://peps.python.org/pep-0451/}

インポートシステムのための ModuleSpec 型

@geindex Python Enhancement Proposals; PEP 488

@item PEP 488@footnote{https://peps.python.org/pep-0488/}

PYO ファイルの撤廃

@geindex Python Enhancement Proposals; PEP 489

@item PEP 489@footnote{https://peps.python.org/pep-0489/}

複数フェーズでの拡張モジュールの初期化

@geindex Python Enhancement Proposals; PEP 552

@item PEP 552@footnote{https://peps.python.org/pep-0552/}

決定論的 pyc

@geindex Python Enhancement Proposals; PEP 3120

@item PEP 3120@footnote{https://peps.python.org/pep-3120/}

デフォルトのソースエンコーディングとして UTF-8 を使用

@geindex Python Enhancement Proposals; PEP 3147

@item PEP 3147@footnote{https://peps.python.org/pep-3147/}

PYC リポジトリディレクトリ
@end table


@node 関数<13>,importlib abc -- Abstract base classes related to import,はじめに<13>,importlib --- import の実装
@anchor{library/importlib functions}@anchor{4af4}
@subsubsection 関数


@geindex __import__() (importlib モジュール)
@anchor{library/importlib importlib __import__}@anchor{1279}
@deffn {の関数} importlib.__import__ (name, globals=None, locals=None, fromlist=(), level=0)

組み込みの @ref{ad1,,__import__()} 関数の実装です。

@cartouche
@quotation 注釈 
プログラムからモジュールをインポートする場合はこの関数の代わりに @ref{73c,,import_module()} を使ってください。
@end quotation
@end cartouche
@end deffn

@geindex import_module() (importlib モジュール)
@anchor{library/importlib importlib import_module}@anchor{73c}
@deffn {の関数} importlib.import_module (name, package=None)

モジュールをインポートします。`name' 引数は、インポートするモジュールを絶対または相対表現 (例えば @code{pkg.mod} または @code{..mod}) で指定します。name が相対表現で与えられたら、`package' 引数を、パッケージ名を解決するためのアンカーとなるパッケージの名前に設定する必要があります (例えば @code{import_module('..mod', 'pkg.subpkg')} は @code{pkg.mod} をインポートします)。

@ref{73c,,import_module()} 関数は @ref{1279,,importlib.__import__()} を単純化するラッパーとして働きます。つまり、この関数のすべての意味は @ref{1279,,importlib.__import__()} から受け継いでいます。これらの2つの関数の最も重要な違いは、 @ref{73c,,import_module()} が指定されたパッケージやモジュール (例えば @code{pkg.mod}) を返すのに対し、 @ref{ad1,,__import__()} はトップレベルのパッケージやモジュール (例えば @code{pkg}) を返すことです。

もしモジュールを動的にインポートしていて、インタープリタの実行開始後にモジュールが作成された (例えば、 Python ソースファイルを作成した) 場合、インポートシステムが新しいモジュールを見つけられるように、 @ref{e0a,,invalidate_caches()} を呼ぶ必要があるでしょう。


バージョン 3.3 で変更: 親パッケージは自動的にインポートされます。

@end deffn

@geindex invalidate_caches() (importlib モジュール)
@anchor{library/importlib importlib invalidate_caches}@anchor{e0a}
@deffn {の関数} importlib.invalidate_caches ()

@ref{f27,,sys.meta_path} に保存されたファインダーの内部キャッシュを無効にします。ファインダーが @code{invalidate_caches()} を実装していれば、無効化を行うためにそれが呼び出されます。すべてのファインダーが新しいモジュールの存在に気づくことを保証しているプログラムの実行中に、モジュールが作成またはインストールされたなら、この関数が呼び出されるべきです。


Added in version 3.3.



バージョン 3.10 で変更: Namespace packages created/installed in a different @ref{3e4,,sys.path}
location after the same namespace was already imported are noticed.

@end deffn

@geindex reload() (importlib モジュール)
@anchor{library/importlib importlib reload}@anchor{73d}
@deffn {の関数} importlib.reload (module)

以前にインポートされた `module' をリロードします。引数はモジュールオブジェクトでなければならず、したがってそれ以前に必ずインポートに成功していなければなりません。この関数は、モジュールのソースファイルを外部エディタで編集していて Python インタープリタから離れることなく新しいバージョンを試したい際に便利です。戻り値はモジュールオブジェクトです。 (もし再インポートが異なるオブジェクトを @ref{17e6,,sys.modules} に配置したら、元の `module' とは異なるかもしれません。)

@ref{73d,,reload()} が実行された場合:


@itemize *

@item 
Python モジュールのコードは再コンパイルされ、モジュールレベルのコードが再度実行されます。モジュールの辞書中にある何らかの名前に結び付けられたオブジェクトは、そのモジュールを最初にロードしたときの @ref{1a28,,ローダー} を再利用して新たに定義されます。拡張モジュールの @code{init} 関数が二度呼び出されることはありません。

@item 
Python における他のオブジェクトと同様、以前のオブジェクトのメモリ領域は、参照カウントがゼロにならないかぎり再利用されません。

@item 
モジュール名前空間内の名前は新しいオブジェクト (または更新されたオブジェクト) を指すよう更新されます。

@item 
以前のオブジェクトが (外部の他のモジュールなどからの) 参照を受けている場合、それらを新たなオブジェクトに再束縛し直すことはないので、必要なら自分で名前空間を更新しなければなりません。
@end itemize

いくつか補足説明があります:

モジュールが再ロードされた際、その辞書 (モジュールのグローバル変数を含みます) はそのまま残ります。名前の再定義を行うと、以前の定義を上書きするので、一般的には問題はありません。新たなバージョンのモジュールが古いバージョンで定義された名前を定義していない場合、古い定義がそのまま残ります。辞書がグローバルテーブルやオブジェクトのキャッシュを維持していれば、この機能をモジュールを有効性を引き出すために使うことができます --- つまり、 @ref{8f8,,try} 文を使えば、必要に応じてテーブルがあるかどうかをテストし、その初期化を飛ばすことができます:

@example
try:
    cache
except NameError:
    cache = @{@}
@end example

組み込みモジュールや動的にロードされるモジュールを再ロードすることは、一般的にそれほど便利ではありません。 @ref{df,,sys}, @ref{1,,__main__}, @ref{13,,builtins} やその他重要なモジュールの再ロードはお勧め出来ません。多くの場合、拡張モジュールは 1 度以上初期化されるようには設計されておらず、再ロードされた場合には何らかの理由で失敗するかもしれません。

一方のモジュールが @ref{14c3,,from} ... @ref{7f8,,import} ... を使って、オブジェクトを他方のモジュールからインポートしているなら、他方のモジュールを @ref{73d,,reload()} で呼び出しても、そのモジュールからインポートされたオブジェクトを再定義することはできません --- この問題を回避する一つの方法は、 @ref{14c3,,from} 文を再度実行することで、もう一つの方法は @code{from} 文の代わりに @code{import} と限定的な名前 (`module.name') を使うことです。

あるモジュールがクラスのインスタンスを生成している場合、そのクラスを定義しているモジュールの再ロードはそれらインスタンスのメソッド定義に影響しません --- それらは古いクラス定義を使い続けます。これは派生クラスの場合でも同じです。


Added in version 3.4.



バージョン 3.7 で変更: リロードされたモジュールの @ref{226c,,ModuleSpec} が欠けていたときは @ref{d3d,,ModuleNotFoundError} が送出されます。


@cartouche
@quotation 警告 
This function is not thread-safe. Calling it from multiple threads can result
in unexpected behavior. It's recommended to use the @ref{19f4,,threading.Lock}
or other synchronization primitives for thread-safe module reloading.
@end quotation
@end cartouche
@end deffn

@node importlib abc -- Abstract base classes related to import,importlib machinery -- Importers and path hooks,関数<13>,importlib --- import の実装
@anchor{library/importlib importlib-abc-abstract-base-classes-related-to-import}@anchor{4af5}@anchor{library/importlib module-importlib abc}@anchor{7c}
@subsubsection @code{importlib.abc} -- Abstract base classes related to import


@geindex module; importlib.abc

`ソースコード:' Lib/importlib/abc.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/importlib/abc.py}


__________________________________________________________________


The @code{importlib.abc} module contains all of the core abstract base classes
used by @ref{7f8,,import}. Some subclasses of the core abstract base classes
are also provided to help in implementing the core ABCs.

抽象基底クラス階層:

@example
object
 +-- MetaPathFinder
 +-- PathEntryFinder
 +-- Loader
      +-- ResourceLoader --------+
      +-- InspectLoader          |
           +-- ExecutionLoader --+
                                 +-- FileLoader
                                 +-- SourceLoader
@end example

@geindex MetaPathFinder (importlib.abc のクラス)
@anchor{library/importlib importlib abc MetaPathFinder}@anchor{a6e}
@deffn {クラス} importlib.abc.MetaPathFinder

@ref{127c,,meta path finder} を表す抽象基底クラスです。


Added in version 3.3.



バージョン 3.10 で変更: No longer a subclass of @code{Finder}.


@geindex find_spec() (importlib.abc.MetaPathFinder のメソッド)
@anchor{library/importlib importlib abc MetaPathFinder find_spec}@anchor{a68}
@deffn {メソッド} find_spec (fullname, path, target=None)

An abstract method for finding a @ref{2363,,spec} for
the specified module.  If this is a top-level import, `path' will
be @code{None}.  Otherwise, this is a search for a subpackage or
module and `path' will be the value of @ref{2054,,__path__} from the
parent package. If a spec cannot be found, @code{None} is returned.
When passed in, @code{target} is a module object that the finder may
use to make a more educated guess about what spec to return.
@ref{a6d,,importlib.util.spec_from_loader()} may be useful for implementing
concrete @code{MetaPathFinders}.


Added in version 3.4.

@end deffn

@geindex invalidate_caches() (importlib.abc.MetaPathFinder のメソッド)
@anchor{library/importlib importlib abc MetaPathFinder invalidate_caches}@anchor{4af6}
@deffn {メソッド} invalidate_caches ()

このファインダーで使われている内部キャッシュがあれば無効にするオプションのメソッドです。 @ref{f27,,sys.meta_path} 上のすべてのファインダーのキャッシュを無効化する際、 @ref{e0a,,importlib.invalidate_caches()} によって使われます。


バージョン 3.4 で変更: Returns @code{None} when called instead of @ref{1a2,,NotImplemented}.

@end deffn
@end deffn

@geindex PathEntryFinder (importlib.abc のクラス)
@anchor{library/importlib importlib abc PathEntryFinder}@anchor{a6f}
@deffn {クラス} importlib.abc.PathEntryFinder

@ref{127d,,path entry finder} を表す抽象基底クラスです。 @ref{a6e,,MetaPathFinder} と似ているところがありますが、 @code{PathEntryFinder} は @ref{1224,,importlib.machinery.PathFinder} が提供するパスに基づく import サブシステムの中でのみ使うことが意図されています。


Added in version 3.3.



バージョン 3.10 で変更: No longer a subclass of @code{Finder}.


@geindex find_spec() (importlib.abc.PathEntryFinder のメソッド)
@anchor{library/importlib importlib abc PathEntryFinder find_spec}@anchor{a6c}
@deffn {メソッド} find_spec (fullname, target=None)

指定されたモジュールに対応する @ref{2363,,スペック} を検索する抽象メソッド。ファインダーは、割り当てられている @ref{2458,,パス・エントリー} 内のモジュールだけを検索します。スペックが見つからなければ @code{None} が返されます。 @code{target} は、渡されてきたならモジュールオブジェクトです。これはファインダーがどのようなスペックを返せばよいか推測するために使用します。具体的な @code{PathEntryFinders} を実装するためには @ref{a6d,,importlib.util.spec_from_loader()} が便利かもしれません。


Added in version 3.4.

@end deffn

@geindex invalidate_caches() (importlib.abc.PathEntryFinder のメソッド)
@anchor{library/importlib importlib abc PathEntryFinder invalidate_caches}@anchor{4af7}
@deffn {メソッド} invalidate_caches ()

このファインダーで使われている内部キャッシュがあれば無効にするオプションのメソッドです。キャッシュされたすべてのファインダーの無効化する際、 @ref{e09,,importlib.machinery.PathFinder.invalidate_caches()} によって使われます。
@end deffn
@end deffn

@geindex Loader (importlib.abc のクラス)
@anchor{library/importlib importlib abc Loader}@anchor{10c7}
@deffn {クラス} importlib.abc.Loader

@ref{1a28,,loader} の抽象基底クラスです。ローダーの厳密な定義は 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} を参照してください。

リソースの読み出しをサポートさせたいローダーには、 @ref{4af8,,importlib.resources.abc.ResourceReader} で指定されている @code{get_resource_reader()} メソッドを実装してください。


バージョン 3.7 で変更: オプションの @code{get_resource_reader()} メソッドが導入されました。


@geindex create_module() (importlib.abc.Loader のメソッド)
@anchor{library/importlib importlib abc Loader create_module}@anchor{eac}
@deffn {メソッド} create_module (spec)

モジュールをインポートする際に使用されるモジュールオブジェクトを返すメソッド。このメソッドは @code{None} を戻すことができ、その場合はデフォルトのモジュール作成のセマンティクスが適用されることを示します。


Added in version 3.4.



バージョン 3.6 で変更: @ref{a6a,,exec_module()} が定義されている場合は、このメソッドはオプションではなくなりました。

@end deffn

@geindex exec_module() (importlib.abc.Loader のメソッド)
@anchor{library/importlib importlib abc Loader exec_module}@anchor{a6a}
@deffn {メソッド} exec_module (module)

モジュールがインポートまたはリロードされる際に、そのモジュールをモジュール自身の名前空間の中で実行する抽象的なメソッド。
@ref{a6a,,exec_module()} が呼ばれる時点で、モジュールはすでに初期設定されている必要があります。
このメソッドが存在するときは、 @ref{eac,,create_module()} の定義が必須です。


Added in version 3.4.



バージョン 3.6 で変更: @ref{eac,,create_module()} の定義が必須となりました。

@end deffn

@geindex load_module() (importlib.abc.Loader のメソッド)
@anchor{library/importlib importlib abc Loader load_module}@anchor{a69}
@deffn {メソッド} load_module (fullname)

モジュールをロードするためのレガシーなメソッドです。モジュールがロードできなければ @ref{65b,,ImportError} を送出し、ロードできればロードされたモジュールを返します。

If the requested module already exists in @ref{17e6,,sys.modules}, that
module should be used and reloaded.
Otherwise the loader should create a new module and insert it into
@ref{17e6,,sys.modules} before any loading begins, to prevent recursion
from the import.  If the loader inserted a module and the load fails, it
must be removed by the loader from @ref{17e6,,sys.modules}; modules already
in @ref{17e6,,sys.modules} before the loader began execution should be left
alone.

ローダーはモジュールにいくつかの属性を設定する必要があります。(なお、これらの属性には、モジュールがリロードされた際に変化するものがあります):


@itemize -

@item 
@ref{15a3,,module.__name__}

@item 
@ref{2369,,module.__file__}

@item 
@ref{321,,module.__cached__} `(deprecated)'

@item 
@ref{2054,,module.__path__}

@item 
@ref{323,,module.__package__} `(deprecated)'

@item 
@ref{33b,,module.__loader__} `(deprecated)'
@end itemize

@ref{a6a,,exec_module()} が利用可能な場合、後方互換な機能が提供されます。


バージョン 3.4 で変更: Raise @ref{65b,,ImportError} when called instead of
@ref{36b,,NotImplementedError}.  Functionality provided when
@ref{a6a,,exec_module()} is available.



Deprecated since version 3.4, will be removed in version 3.15: モジュールをロードするための推奨される API は、 @ref{a6a,,exec_module()} (および @ref{eac,,create_module()}) です。ローダーは @ref{a69,,load_module()} の代わりにそれを実装するべきです。 @ref{a6a,,exec_module()} が実装されている場合、インポート機構は @ref{a69,,load_module()} の他のすべての責任を肩代わりします。

@end deffn
@end deffn

@geindex ResourceLoader (importlib.abc のクラス)
@anchor{library/importlib importlib abc ResourceLoader}@anchor{de2}
@deffn {クラス} importlib.abc.ResourceLoader

`TraversableResources に取って代わられました'

@quotation

@ref{1a28,,loader} の抽象基底クラスで、ストレージバックエンドから任意のリソースをロードするオプションの 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} プロトコルを実装します。


バージョン 3.7 で非推奨: This ABC is deprecated in favour of supporting resource loading
through @ref{2f9,,importlib.resources.abc.TraversableResources}.
This class exists for backwards compatibility only with other ABCs in
this module.


@geindex get_data() (importlib.abc.ResourceLoader のメソッド)
@anchor{library/importlib importlib abc ResourceLoader get_data}@anchor{4ae1}
@deffn {メソッド} abstractmethod get_data (path)

@quotation

An abstract method to return the bytes for the data located at `path'.
Loaders that have a file-like storage back-end
that allows storing arbitrary data
can implement this abstract method to give direct access
to the data stored. @ref{2c0,,OSError} is to be raised if the `path' cannot
be found. The `path' is expected to be constructed using a module's
@ref{2369,,__file__} attribute or an item from a package's
@ref{2054,,__path__}.


バージョン 3.4 で変更: @ref{36b,,NotImplementedError} の代わりに @ref{2c0,,OSError} を送出します。

@end quotation
@end deffn
@end quotation
@end deffn

@geindex InspectLoader (importlib.abc のクラス)
@anchor{library/importlib importlib abc InspectLoader}@anchor{1156}
@deffn {クラス} importlib.abc.InspectLoader

@ref{1a28,,loader} の抽象基底クラスで、ローダーがモジュールを検査するためのオプションの 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} プロトコルを実装します。

@geindex get_code() (importlib.abc.InspectLoader のメソッド)
@anchor{library/importlib importlib abc InspectLoader get_code}@anchor{1157}
@deffn {メソッド} get_code (fullname)

モジュールの @ref{1b,,code} オブジェクトを返すか、 (例えば組み込みモジュールの場合に) モジュールがコードオブジェクトを持たなければ @code{None} を返します。要求されたモジュールをローダーが見つけられなかった場合は @ref{65b,,ImportError} を送出します。

@cartouche
@quotation 注釈 
このメソッドにはデフォルト実装がありますが、とはいえパフォーマンスのために、可能ならばオーバライドしたほうが良いです。
@end quotation
@end cartouche

@geindex universal newlines;importlib.abc.InspectLoader.get_source メソッド


バージョン 3.4 で変更: このメソッドはもはや抽象メソッドではなく、具象実装が提供されます。

@end deffn

@geindex get_source() (importlib.abc.InspectLoader のメソッド)
@anchor{library/importlib importlib abc InspectLoader get_source}@anchor{115a}
@deffn {メソッド} abstractmethod get_source (fullname)

@quotation

モジュールのソースを返す抽象メソッドです。これは認識されたすべての行セパレータを @code{'\n'} 文字に変換し、 @ref{f35,,universal newlines} を使ったテキスト文字列として返されます。利用できるソースがなければ (例えば組み込みモジュール)、 @code{None} を返します。指定されたモジュールが見つからなければ、 @ref{65b,,ImportError} を送出します。


バージョン 3.4 で変更: @ref{36b,,NotImplementedError} の代わりに @ref{65b,,ImportError} を送出します。

@end quotation
@end deffn

@geindex is_package() (importlib.abc.InspectLoader のメソッド)
@anchor{library/importlib importlib abc InspectLoader is_package}@anchor{4af9}
@deffn {メソッド} is_package (fullname)

モジュールがパッケージであれば True を返し、そうでなければ False を返すオプションのメソッドです。 @ref{1a28,,ローダー} がモジュールを見つけられなかったなら @ref{65b,,ImportError} が送出されます。


バージョン 3.4 で変更: @ref{36b,,NotImplementedError} の代わりに @ref{65b,,ImportError} を送出します。

@end deffn

@geindex source_to_code() (importlib.abc.InspectLoader の静的メソッド)
@anchor{library/importlib importlib abc InspectLoader source_to_code}@anchor{1012}
@deffn {メソッド} static source_to_code (data, path='<string>')

Python のソースからコードオブジェクトを作ります。

`data' 引数は @ref{4b1,,compile()} 関数がサポートするもの (すなわち文字列かバイト) なら何でも構いません。`path' 引数はソースコードの元々の場所への "パス" でなければなりませんが、抽象概念 (例えば zip ファイル内の場所) でも構いません。

結果のコードオブジェクトを使って、 @code{exec(code, module.__dict__)} を呼ぶことでモジュール内でコードを実行できます。


Added in version 3.4.



バージョン 3.5 で変更: スタティックメソッドになりました。

@end deffn

@geindex exec_module() (importlib.abc.InspectLoader のメソッド)
@anchor{library/importlib importlib abc InspectLoader exec_module}@anchor{1214}
@deffn {メソッド} exec_module (module)

@ref{a6a,,Loader.exec_module()} の実装です。


Added in version 3.4.

@end deffn

@geindex load_module() (importlib.abc.InspectLoader のメソッド)
@anchor{library/importlib importlib abc InspectLoader load_module}@anchor{4afa}
@deffn {メソッド} load_module (fullname)

@ref{a69,,Loader.load_module()} の実装です。


Deprecated since version 3.4, will be removed in version 3.15: 代わりに @ref{1214,,exec_module()} を使用してください。

@end deffn
@end deffn

@geindex ExecutionLoader (importlib.abc のクラス)
@anchor{library/importlib importlib abc ExecutionLoader}@anchor{4afb}
@deffn {クラス} importlib.abc.ExecutionLoader

@ref{1156,,InspectLoader} から継承された抽象基底クラスで、実装されていれば、モジュールをスクリプトとして実行する助けになります。この抽象基底クラスはオプションの 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/} プロトコルを表します。

@geindex get_filename() (importlib.abc.ExecutionLoader のメソッド)
@anchor{library/importlib importlib abc ExecutionLoader get_filename}@anchor{4afc}
@deffn {メソッド} abstractmethod get_filename (fullname)

@quotation

An abstract method that is to return the value of
@ref{2369,,__file__} for the specified module. If no path is
available, @ref{65b,,ImportError} is raised.

ソースコードが利用できるなら、そのモジュールのロードにバイトコードが使われたかにかかわらず、このメソッドはそのソースファイルへのパスを返す必要があります。


バージョン 3.4 で変更: @ref{36b,,NotImplementedError} の代わりに @ref{65b,,ImportError} を送出します。

@end quotation
@end deffn
@end deffn

@geindex FileLoader (importlib.abc のクラス)
@anchor{library/importlib importlib abc FileLoader}@anchor{127f}
@deffn {クラス} importlib.abc.FileLoader (fullname, path)

@ref{de2,,ResourceLoader} と @ref{4afb,,ExecutionLoader} から継承された抽象基底クラスで、 @ref{4ae1,,ResourceLoader.get_data()} および @ref{4afc,,ExecutionLoader.get_filename()} の具象実装を提供します。

`fullname' 引数は、ローダーが解決しようとするモジュールの、完全に解決された名前です。`path' 引数は、モジュールのファイルへのパスです。


Added in version 3.3.


@geindex name (importlib.abc.FileLoader の属性)
@anchor{library/importlib importlib abc FileLoader name}@anchor{4afd}
@deffn {の属性} name

ローダーが扱えるモジュールの名前です。
@end deffn

@geindex path (importlib.abc.FileLoader の属性)
@anchor{library/importlib importlib abc FileLoader path}@anchor{4afe}
@deffn {の属性} path

モジュールのファイルへのパスです。
@end deffn

@geindex load_module() (importlib.abc.FileLoader のメソッド)
@anchor{library/importlib importlib abc FileLoader load_module}@anchor{4aff}
@deffn {メソッド} load_module (fullname)

親クラスの @code{load_module()} を呼び出します。


Deprecated since version 3.4, will be removed in version 3.15: 代わりに @ref{a6a,,Loader.exec_module()} を使用してください。

@end deffn

@geindex get_filename() (importlib.abc.FileLoader のメソッド)
@anchor{library/importlib importlib abc FileLoader get_filename}@anchor{4b00}
@deffn {メソッド} abstractmethod get_filename (fullname)

@ref{4afe,,path} を返します。
@end deffn

@geindex get_data() (importlib.abc.FileLoader のメソッド)
@anchor{library/importlib importlib abc FileLoader get_data}@anchor{4b01}
@deffn {メソッド} abstractmethod get_data (path)

`path' をバイナリファイルとして読み込み、そのバイト列を返します。
@end deffn
@end deffn

@geindex SourceLoader (importlib.abc のクラス)
@anchor{library/importlib importlib abc SourceLoader}@anchor{4b02}
@deffn {クラス} importlib.abc.SourceLoader

ソース (オプションでバイトコード) ファイルのロードを実装する抽象基底クラスです。このクラスは、 @ref{de2,,ResourceLoader} と @ref{4afb,,ExecutionLoader} の両方を継承し、以下の実装が必要です:


@itemize *

@item 
@ref{4ae1,,ResourceLoader.get_data()}

@item 

@table @asis

@item @ref{4afc,,ExecutionLoader.get_filename()}

ソースファイルへのパスのみを返す必要があります。ソースなしのロードはサポートされていません。
@end table
@end itemize

このクラスでこれらの抽象メソッドを定義することで、バイトコードファイルを追加でサポートします。これらのメソッドを定義しなければ (またはそのモジュールが @ref{36b,,NotImplementedError} を送出すれば)、このローダーはソースコードに対してのみ働きます。これらのメソッドを実装することで、ローダーはソースとバイトコードファイル `の組み合わせ' に対して働きます。バイトコードのみを与えた `ソースのない' ロードは認められません。バイトコードファイルは、 Python コンパイラによる解析の工程をなくして速度を上げる最適化です。ですから、バイトコード特有の API は公開されていません。

@geindex path_stats() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader path_stats}@anchor{13a1}
@deffn {メソッド} path_stats (path)

指定されたパスについてのメタデータを含む @ref{183,,dict} を返す、オプションの抽象メソッドです。サポートされる辞書のキーは:


@itemize -

@item 
@code{'mtime'} (必須): ソースコードの更新時刻を表す整数または浮動小数点数です。

@item 
@code{'size'} (任意): バイト数で表したソースコードのサイズです。
@end itemize

未来の拡張のため、辞書内の他のキーは無視されます。パスが扱えなければ、 @ref{2c0,,OSError} が送出されます。


Added in version 3.3.



バージョン 3.4 で変更: @ref{36b,,NotImplementedError} の代わりに @ref{2c0,,OSError} を送出します。

@end deffn

@geindex path_mtime() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader path_mtime}@anchor{13a2}
@deffn {メソッド} path_mtime (path)

指定されたパスの更新時刻を返す、オプションの抽象メソッドです。


バージョン 3.3 で非推奨: このメソッドは廃止され、 @ref{13a1,,path_stats()} が推奨されます。このモジュールを実装する必要はありませんが、互換性のため現在も利用できます。パスが扱えなければ、 @ref{2c0,,OSError} が送出されます。



バージョン 3.4 で変更: @ref{36b,,NotImplementedError} の代わりに @ref{2c0,,OSError} を送出します。

@end deffn

@geindex set_data() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader set_data}@anchor{4b03}
@deffn {メソッド} set_data (path, data)

ファイルパスに指定されたバイト列を書き込むオプションの抽象メソッドです。存在しない中間ディレクトリがあれば、自動で作成されます。

When writing to the path fails because the path is read-only
(@ref{270c,,errno.EACCES}/@ref{f3e,,PermissionError}), do not propagate the
exception.


バージョン 3.4 で変更: 呼ばれたときに @ref{36b,,NotImplementedError} を送出することは最早ありません。

@end deffn

@geindex get_code() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader get_code}@anchor{4b04}
@deffn {メソッド} get_code (fullname)

@ref{1157,,InspectLoader.get_code()} の具象実装です。
@end deffn

@geindex exec_module() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader exec_module}@anchor{1215}
@deffn {メソッド} exec_module (module)

@ref{a6a,,Loader.exec_module()} の具象実装です。


Added in version 3.4.

@end deffn

@geindex load_module() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader load_module}@anchor{4b05}
@deffn {メソッド} load_module (fullname)

@ref{a69,,Loader.load_module()} の具象実装です。


Deprecated since version 3.4, will be removed in version 3.15: 代わりに @ref{1215,,exec_module()} を使用してください。

@end deffn

@geindex get_source() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader get_source}@anchor{1222}
@deffn {メソッド} get_source (fullname)

@ref{115a,,InspectLoader.get_source()} の具象実装です。
@end deffn

@geindex is_package() (importlib.abc.SourceLoader のメソッド)
@anchor{library/importlib importlib abc SourceLoader is_package}@anchor{4b06}
@deffn {メソッド} is_package (fullname)

@ref{4af9,,InspectLoader.is_package()} の具象実装です。モジュールは、次の `両方' を満たすならパッケージであると決定されます。モジュールの (@ref{4afc,,ExecutionLoader.get_filename()} で与えられる) ファイルパスが、ファイル拡張子を除くと @code{__init__} という名のファイルであること。モジュール名自体が @code{__init__} で終わらないこと。
@end deffn
@end deffn

@node importlib machinery -- Importers and path hooks,importlib util -- Utility code for importers,importlib abc -- Abstract base classes related to import,importlib --- import の実装
@anchor{library/importlib importlib-machinery-importers-and-path-hooks}@anchor{4b07}@anchor{library/importlib module-importlib machinery}@anchor{7d}
@subsubsection @code{importlib.machinery} -- Importers and path hooks


@geindex module; importlib.machinery

`ソースコード:' Lib/importlib/machinery.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/importlib/machinery.py}


__________________________________________________________________


このモジュールには、 @ref{7f8,,import} がモジュールを検索してロードするのに役立つ様々なオブジェクトがあります。

@geindex SOURCE_SUFFIXES (importlib.machinery モジュール)
@anchor{library/importlib importlib machinery SOURCE_SUFFIXES}@anchor{738}
@deffn {データ} importlib.machinery.SOURCE_SUFFIXES

認識されているソースモジュールのファイル接尾辞を表す文字列のリストです。


Added in version 3.3.

@end deffn

@geindex DEBUG_BYTECODE_SUFFIXES (importlib.machinery モジュール)
@anchor{library/importlib importlib machinery DEBUG_BYTECODE_SUFFIXES}@anchor{18b0}
@deffn {データ} importlib.machinery.DEBUG_BYTECODE_SUFFIXES

最適化されていないバイトコードモジュールのファイル接尾辞を表す文字列のリストです。


Added in version 3.3.



バージョン 3.5 で非推奨: Use @ref{73a,,BYTECODE_SUFFIXES} instead.

@end deffn

@geindex OPTIMIZED_BYTECODE_SUFFIXES (importlib.machinery モジュール)
@anchor{library/importlib importlib machinery OPTIMIZED_BYTECODE_SUFFIXES}@anchor{18b1}
@deffn {データ} importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES

最適化されたバイトコードモジュールのファイル接尾辞を表す文字列のリストです。


Added in version 3.3.



バージョン 3.5 で非推奨: Use @ref{73a,,BYTECODE_SUFFIXES} instead.

@end deffn

@geindex BYTECODE_SUFFIXES (importlib.machinery モジュール)
@anchor{library/importlib importlib machinery BYTECODE_SUFFIXES}@anchor{73a}
@deffn {データ} importlib.machinery.BYTECODE_SUFFIXES

認識されているバイトコードモジュールのファイル接尾辞を表す文字列のリストです (先頭のドットを含みます)。


Added in version 3.3.



バージョン 3.5 で変更: この値は @code{__debug__} に依存しなくなりました。

@end deffn

@geindex EXTENSION_SUFFIXES (importlib.machinery モジュール)
@anchor{library/importlib importlib machinery EXTENSION_SUFFIXES}@anchor{739}
@deffn {データ} importlib.machinery.EXTENSION_SUFFIXES

認識されている最適化された拡張モジュールのファイル接尾辞を表す文字列のリストです。


Added in version 3.3.

@end deffn

@geindex all_suffixes() (importlib.machinery モジュール)
@anchor{library/importlib importlib machinery all_suffixes}@anchor{4a1b}
@deffn {の関数} importlib.machinery.all_suffixes ()

標準のインポート機構によって認識されているすべてのファイル接尾辞を表す文字列の組み合わせられたリストを返します。これが役立つのは、あるファイルシステムパスがモジュールを参照する可能性があるかだけを知りたくて、そのモジュールの種類を詳しく知る必要はないコード (例えば @ref{f34,,inspect.getmodulename()}) です。


Added in version 3.3.

@end deffn

@geindex BuiltinImporter (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery BuiltinImporter}@anchor{ead}
@deffn {クラス} importlib.machinery.BuiltinImporter

組み込みモジュールの @ref{2448,,importer} です。すべての既知のモジュールは @ref{2047,,sys.builtin_module_names} に列挙されています。このクラスは @ref{a6e,,importlib.abc.MetaPathFinder} および @ref{1156,,importlib.abc.InspectLoader} 抽象基底クラスを実装します。

インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。


バージョン 3.5 で変更: 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} の一環として、ビルトインインポーターは @code{Loader.create_module()} と @code{Loader.exec_module()} を実装しています。

@end deffn

@geindex FrozenImporter (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery FrozenImporter}@anchor{1220}
@deffn {クラス} importlib.machinery.FrozenImporter

フリーズされたモジュールの @ref{2448,,インポーター} です。このクラスは @ref{a6e,,importlib.abc.MetaPathFinder} および @ref{1156,,importlib.abc.InspectLoader} 抽象基底クラスを実装します。

インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。


バージョン 3.4 で変更: Gained @code{create_module()} and @code{exec_module()}
methods.

@end deffn

@geindex WindowsRegistryFinder (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery WindowsRegistryFinder}@anchor{f26}
@deffn {クラス} importlib.machinery.WindowsRegistryFinder

Windows レジストリで宣言されたモジュールの @ref{236a,,finder} です。このクラスは @ref{a6e,,importlib.abc.MetaPathFinder} 抽象基底クラスを実装します。

インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。


Added in version 3.3.



バージョン 3.6 で非推奨: 代わりに @ref{cc,,site} の設定を使ってください。
Python の将来のバージョンでは、デフォルトでこのファインダーが使えなくなるかもしれません。

@end deffn

@geindex PathFinder (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery PathFinder}@anchor{1224}
@deffn {クラス} importlib.machinery.PathFinder

@ref{3e4,,sys.path} およびパッケージの @code{__path__} 属性の @ref{236a,,Finder} です。このクラスは @ref{a6e,,importlib.abc.MetaPathFinder} 抽象基底クラスを実装します。

インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。

@geindex find_spec() (importlib.machinery.PathFinder のクラスメソッド)
@anchor{library/importlib importlib machinery PathFinder find_spec}@anchor{1213}
@deffn {メソッド} classmethod find_spec (fullname, path=None, target=None)

@ref{3e4,,sys.path} または定義されていれば `path' から、 `fullname' で指定されたモジュールの @ref{2363,,スペック} の検索を試みるクラスメソッドです。検索されるそれぞれのパスエントリに対して @ref{7fa,,sys.path_importer_cache} が検査されます。偽でないオブジェクトが見つかれば、それが目的のモジュールを検索するための @ref{127d,,パスエントリ・ファインダー} として使われます。 @ref{7fa,,sys.path_importer_cache} に目的のエントリが見つからなければ、パスエントリに対するファインダーが @ref{1225,,sys.path_hooks} から検索され、見つかれば、それが @ref{7fa,,sys.path_importer_cache} に保管されるとともに、モジュールについて問い合わせられます。それでもファインダーが見つからなければ @code{None} が保管され、また返されます。


Added in version 3.4.



バージョン 3.5 で変更: もしカレントワーキングディレクトリ -- 空の文字列によって表されている -- がすでに有効でなければ、 @code{None} が返されますが値は @ref{7fa,,sys.path_importer_cache} にキャッシュされません。

@end deffn

@geindex invalidate_caches() (importlib.machinery.PathFinder のクラスメソッド)
@anchor{library/importlib importlib machinery PathFinder invalidate_caches}@anchor{e09}
@deffn {メソッド} classmethod invalidate_caches ()

Calls @ref{4af7,,importlib.abc.PathEntryFinder.invalidate_caches()} on all
finders stored in @ref{7fa,,sys.path_importer_cache} that define the method.
Otherwise entries in @ref{7fa,,sys.path_importer_cache} set to @code{None} are
deleted.


バージョン 3.7 で変更: Entries of @code{None} in @ref{7fa,,sys.path_importer_cache} are deleted.

@end deffn


バージョン 3.4 で変更: @code{'@w{'}} (すなわち空の文字列) に対してはカレントワーキングディレクトリとともに @ref{1225,,sys.path_hooks} のオブジェクトを呼び出します。

@end deffn

@geindex FileFinder (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery FileFinder}@anchor{127e}
@deffn {クラス} importlib.machinery.FileFinder (path, *loader_details)

ファイルシステムからの結果をキャッシュする @ref{a6f,,importlib.abc.PathEntryFinder} の具象実装です。

`path' 引数は検索を担当するファインダーのディレクトリです。

`loader_details' 引数は、可変個の 2 要素タプルで、それぞれがローダーとローダーが認識するファイル接尾辞のシーケンスとを含みます。ローダーは、呼び出し可能でモジュール名と見つかったファイルのパスとの 2 引数を受け付けることを期待されます。

ファインダーはモジュール検索のたびに stat を呼び出し、必要に応じてディレクトリの内容をキャッシュすることで、コードキャッシュが古くなっていないことを確かめます。キャッシュの古さはオペレーティングシステムのファイルシステムのステート情報の粒度に依存しますから、モジュールを検索し、新しいファイルを作成し、その後に新しいファイルが表すモジュールを検索する、という競合状態の可能性があります。この操作が stat の呼び出しの粒度に収まるほど速く起こると、モジュールの検索が失敗します。これを防ぐためには、モジュールを動的に作成する際に、必ず @ref{e0a,,importlib.invalidate_caches()} を呼び出してください。


Added in version 3.3.


@geindex path (importlib.machinery.FileFinder の属性)
@anchor{library/importlib importlib machinery FileFinder path}@anchor{4b08}
@deffn {の属性} path

ファインダーが検索されるパスです。
@end deffn

@geindex find_spec() (importlib.machinery.FileFinder のメソッド)
@anchor{library/importlib importlib machinery FileFinder find_spec}@anchor{10c6}
@deffn {メソッド} find_spec (fullname, target=None)

@ref{4b08,,path} 内で `fullname' を扱うスペックの探索を試みます。


Added in version 3.4.

@end deffn

@geindex invalidate_caches() (importlib.machinery.FileFinder のメソッド)
@anchor{library/importlib importlib machinery FileFinder invalidate_caches}@anchor{4b09}
@deffn {メソッド} invalidate_caches ()

内部キャッシュを完全に消去します。
@end deffn

@geindex path_hook() (importlib.machinery.FileFinder のクラスメソッド)
@anchor{library/importlib importlib machinery FileFinder path_hook}@anchor{4b0a}
@deffn {メソッド} classmethod path_hook (*loader_details)

A class method which returns a closure for use on @ref{1225,,sys.path_hooks}.
An instance of @ref{127e,,FileFinder} is returned by the closure using the
path argument given to the closure directly and `loader_details'
indirectly.

クロージャへの引数が存在するディレクトリでなければ、 @ref{65b,,ImportError} が送出されます。
@end deffn
@end deffn

@geindex SourceFileLoader (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery SourceFileLoader}@anchor{1280}
@deffn {クラス} importlib.machinery.SourceFileLoader (fullname, path)

@ref{127f,,importlib.abc.FileLoader} を継承し、その他いくつかのメソッドの具象実装を提供する、 @ref{4b02,,importlib.abc.SourceLoader} の具象実装です。


Added in version 3.3.


@geindex name (importlib.machinery.SourceFileLoader の属性)
@anchor{library/importlib importlib machinery SourceFileLoader name}@anchor{4b0b}
@deffn {の属性} name

このローダーが扱うモジュールの名前です。
@end deffn

@geindex path (importlib.machinery.SourceFileLoader の属性)
@anchor{library/importlib importlib machinery SourceFileLoader path}@anchor{4b0c}
@deffn {の属性} path

ソースファイルへのパスです。
@end deffn

@geindex is_package() (importlib.machinery.SourceFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourceFileLoader is_package}@anchor{4b0d}
@deffn {メソッド} is_package (fullname)

@ref{4b0c,,path} がパッケージを表すとき @code{True} を返します。
@end deffn

@geindex path_stats() (importlib.machinery.SourceFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourceFileLoader path_stats}@anchor{4b0e}
@deffn {メソッド} path_stats (path)

@ref{13a1,,importlib.abc.SourceLoader.path_stats()} の具象実装です。
@end deffn

@geindex set_data() (importlib.machinery.SourceFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourceFileLoader set_data}@anchor{4b0f}
@deffn {メソッド} set_data (path, data)

@ref{4b03,,importlib.abc.SourceLoader.set_data()} の具象実装です。
@end deffn

@geindex load_module() (importlib.machinery.SourceFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourceFileLoader load_module}@anchor{f24}
@deffn {メソッド} load_module (name=None)

ロードするモジュールの名前指定がオプションの、 @ref{a69,,importlib.abc.Loader.load_module()} の具象実装です。


Deprecated since version 3.6, will be removed in version 3.15: 代わりに @ref{a6a,,importlib.abc.Loader.exec_module()} を使用してください。

@end deffn
@end deffn

@geindex SourcelessFileLoader (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery SourcelessFileLoader}@anchor{1281}
@deffn {クラス} importlib.machinery.SourcelessFileLoader (fullname, path)

バイトコードファイル (すなわちソースコードファイルが存在しない) をインポートできる @ref{127f,,importlib.abc.FileLoader} の具象実装です。

注意として、バイトコードを直接使う (つまりソースコードファイルがない) と、そのモジュールはすべての Python 実装では使用できないし、新しいバージョンの Python ではバイトコードフォーマットが変更されていたら使用できません。


Added in version 3.3.


@geindex name (importlib.machinery.SourcelessFileLoader の属性)
@anchor{library/importlib importlib machinery SourcelessFileLoader name}@anchor{4b10}
@deffn {の属性} name

ローダーが扱うモジュールの名前です。
@end deffn

@geindex path (importlib.machinery.SourcelessFileLoader の属性)
@anchor{library/importlib importlib machinery SourcelessFileLoader path}@anchor{4b11}
@deffn {の属性} path

バイトコードファイルへのパスです。
@end deffn

@geindex is_package() (importlib.machinery.SourcelessFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourcelessFileLoader is_package}@anchor{4b12}
@deffn {メソッド} is_package (fullname)

そのモジュールがパッケージであるかを @ref{4b11,,path} に基づいて決定します。
@end deffn

@geindex get_code() (importlib.machinery.SourcelessFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourcelessFileLoader get_code}@anchor{4b13}
@deffn {メソッド} get_code (fullname)

@ref{4b11,,path} から作成された @ref{4b10,,name} のコードオブジェクトを返します。
@end deffn

@geindex get_source() (importlib.machinery.SourcelessFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourcelessFileLoader get_source}@anchor{4b14}
@deffn {メソッド} get_source (fullname)

このローダーが使われたとき、バイトコードファイルのソースがなければ @code{None} を返します。
@end deffn

@geindex load_module() (importlib.machinery.SourcelessFileLoader のメソッド)
@anchor{library/importlib importlib machinery SourcelessFileLoader load_module}@anchor{f25}
@deffn {メソッド} load_module (name=None)
@end deffn

ロードするモジュールの名前指定がオプションの、 @ref{a69,,importlib.abc.Loader.load_module()} の具象実装です。


Deprecated since version 3.6, will be removed in version 3.15: 代わりに @ref{a6a,,importlib.abc.Loader.exec_module()} を使用してください。

@end deffn

@geindex ExtensionFileLoader (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery ExtensionFileLoader}@anchor{eae}
@deffn {クラス} importlib.machinery.ExtensionFileLoader (fullname, path)

拡張モジュールのための @ref{4afb,,importlib.abc.ExecutionLoader} の具象実装です。

`fullname' 引数はローダーがサポートするモジュールの名前を指定します。`path' 引数は拡張モジュールのファイルへのパスです。

Note that, by default, importing an extension module will fail
in subinterpreters if it doesn't implement multi-phase init
(see 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}), even if it would otherwise import successfully.


Added in version 3.3.



バージョン 3.12 で変更: Multi-phase init is now required for use in subinterpreters.


@geindex name (importlib.machinery.ExtensionFileLoader の属性)
@anchor{library/importlib importlib machinery ExtensionFileLoader name}@anchor{4b15}
@deffn {の属性} name

ローダーがサポートするモジュールの名前です。
@end deffn

@geindex path (importlib.machinery.ExtensionFileLoader の属性)
@anchor{library/importlib importlib machinery ExtensionFileLoader path}@anchor{4b16}
@deffn {の属性} path

拡張モジュールへのパスです。
@end deffn

@geindex create_module() (importlib.machinery.ExtensionFileLoader のメソッド)
@anchor{library/importlib importlib machinery ExtensionFileLoader create_module}@anchor{4b17}
@deffn {メソッド} create_module (spec)

与えられたスペックから 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} に従ってモジュールオブジェクトを作成します。


Added in version 3.5.

@end deffn

@geindex exec_module() (importlib.machinery.ExtensionFileLoader のメソッド)
@anchor{library/importlib importlib machinery ExtensionFileLoader exec_module}@anchor{4b18}
@deffn {メソッド} exec_module (module)

与えられたモジュールオブジェクトを 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} に従って初期化します。


Added in version 3.5.

@end deffn

@geindex is_package() (importlib.machinery.ExtensionFileLoader のメソッド)
@anchor{library/importlib importlib machinery ExtensionFileLoader is_package}@anchor{4b19}
@deffn {メソッド} is_package (fullname)

Returns @code{True} if the file path points to a package's @code{__init__}
module based on @ref{739,,EXTENSION_SUFFIXES}.
@end deffn

@geindex get_code() (importlib.machinery.ExtensionFileLoader のメソッド)
@anchor{library/importlib importlib machinery ExtensionFileLoader get_code}@anchor{4b1a}
@deffn {メソッド} get_code (fullname)

拡張モジュールにコードオブジェクトがなければ @code{None} を返します。
@end deffn

@geindex get_source() (importlib.machinery.ExtensionFileLoader のメソッド)
@anchor{library/importlib importlib machinery ExtensionFileLoader get_source}@anchor{4b1b}
@deffn {メソッド} get_source (fullname)

拡張モジュールにソースコードがなければ @code{None} を返します。
@end deffn

@geindex get_filename() (importlib.machinery.ExtensionFileLoader のメソッド)
@anchor{library/importlib importlib machinery ExtensionFileLoader get_filename}@anchor{115b}
@deffn {メソッド} get_filename (fullname)

@ref{4b16,,path} を返します。


Added in version 3.4.

@end deffn
@end deffn

@geindex NamespaceLoader (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery NamespaceLoader}@anchor{1158}
@deffn {クラス} importlib.machinery.NamespaceLoader (name, path, path_finder)

A concrete implementation of @ref{1156,,importlib.abc.InspectLoader} for
namespace packages.  This is an alias for a private class and is only made
public for introspecting the @code{__loader__} attribute on namespace
packages:

@example
>>> from importlib.machinery import NamespaceLoader
>>> import my_namespace
>>> isinstance(my_namespace.__loader__, NamespaceLoader)
True
>>> import importlib.abc
>>> isinstance(my_namespace.__loader__, importlib.abc.Loader)
True
@end example


Added in version 3.11.

@end deffn

@geindex ModuleSpec (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery ModuleSpec}@anchor{226c}
@deffn {クラス} importlib.machinery.ModuleSpec (name, loader, *, origin=None, loader_state=None, is_package=None)

A specification for a module's import-system-related state.  This is
typically exposed as the module's @ref{2364,,__spec__} attribute.  Many
of these attributes are also available directly on a module: for example,
@code{module.__spec__.origin == module.__file__}.  Note, however, that
while the `values' are usually equivalent, they can differ since there is
no synchronization between the two objects.  For example, it is possible to
update the module's @ref{2369,,__file__} at runtime and this will not be
automatically reflected in the module's
@ref{4b1c,,__spec__.origin}, and vice versa.


Added in version 3.4.


@geindex name (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec name}@anchor{2365}
@deffn {の属性} name

The module's fully qualified name (see @ref{15a3,,module.__name__}).
The @ref{236a,,finder} should always set this attribute to a non-empty string.
@end deffn

@geindex loader (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec loader}@anchor{33c}
@deffn {の属性} loader

The @ref{1a28,,loader} used to load the module (see @ref{33b,,module.__loader__}).
The @ref{236a,,finder} should always set this attribute.
@end deffn

@geindex origin (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec origin}@anchor{4b1c}
@deffn {の属性} origin

The location the @ref{1a28,,loader} should use to load the module
(see @ref{2369,,module.__file__}).
For example, for modules loaded from a @code{.py} file this is the filename.
The @ref{236a,,finder} should always set this attribute to a meaningful value
for the @ref{1a28,,loader} to use.  In the uncommon case that there is not one
(like for namespace packages), it should be set to @code{None}.
@end deffn

@geindex submodule_search_locations (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec submodule_search_locations}@anchor{2368}
@deffn {の属性} submodule_search_locations

A (possibly empty) @ref{716,,sequence} of strings enumerating the locations
in which a package's submodules will be found
(see @ref{2054,,module.__path__}). Most of the time there will only be a
single directory in this list.

The @ref{236a,,finder} should set this attribute to a sequence, even an empty
one, to indicate
to the import system that the module is a package.  It should be set to @code{None} for
non-package modules.  It is set automatically later to a special object for
namespace packages.
@end deffn

@geindex loader_state (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec loader_state}@anchor{4b1d}
@deffn {の属性} loader_state

The @ref{236a,,finder} may set this attribute to an object containing additional,
module-specific data to use when loading the module.  Otherwise it should be
set to @code{None}.
@end deffn

@geindex cached (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec cached}@anchor{322}
@deffn {の属性} cached

The filename of a compiled version of the module's code
(see @ref{321,,module.__cached__}).
The @ref{236a,,finder} should always set this attribute but it may be @code{None}
for modules that do not need compiled code stored.
@end deffn

@geindex parent (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec parent}@anchor{324}
@deffn {の属性} parent

(Read-only) The fully qualified name of the package the module is in (or the
empty string for a top-level module).
See @ref{323,,module.__package__}.
If the module is a package then this is the same as @ref{2365,,name}.
@end deffn

@geindex has_location (importlib.machinery.ModuleSpec の属性)
@anchor{library/importlib importlib machinery ModuleSpec has_location}@anchor{4b1e}
@deffn {の属性} has_location

@code{True} if the spec's @ref{4b1c,,origin} refers to a loadable location,
@code{False} otherwise.  This value impacts how @code{origin} is interpreted
and how the module's @ref{2369,,__file__} is populated.
@end deffn
@end deffn

@geindex AppleFrameworkLoader (importlib.machinery のクラス)
@anchor{library/importlib importlib machinery AppleFrameworkLoader}@anchor{226b}
@deffn {クラス} importlib.machinery.AppleFrameworkLoader (name, path)

フレームワーク形式の拡張モジュールを読み込み事ができる、特殊な @ref{eae,,importlib.machinery.ExtensionFileLoader} です。

iOS App Store との互換性のため、 iOS アプリの `すべての' バイナリモジュールは、パッケージ化されたアプリの @code{Frameworks} フォルダーに保存された、適切なメタデータ付きのフレームワークにある動的ライブラリである必要があります。フレームワークごとにバイナリは一つだけで、 Frameworks フォルダーの外に実行可能バイナリデータを設置することはできません。

To accommodate this requirement, when running on iOS, extension module
binaries are `not' packaged as @code{.so} files on @code{sys.path}, but as
individual standalone frameworks. To discover those frameworks, this loader
is registered against the @code{.fwork} file extension, with a @code{.fwork}
file acting as a placeholder in the original location of the binary on
@code{sys.path}. The @code{.fwork} file contains the path of the actual binary in
the @code{Frameworks} folder, relative to the app bundle. To allow for
resolving a framework-packaged binary back to the original location, the
framework is expected to contain a @code{.origin} file that contains the
location of the @code{.fwork} file, relative to the app bundle.

例えば、@code{from foo.bar import _whiz} をインポートする場合を考えてみましょう。 @code{_whiz} がバイナリモジュール @code{sources/foo/bar/_whiz.abi3.so} で実装されており、 @code{sources} のアプリケーションバンドルからの相対パスが @code{sys.path} に登録されています。このモジュールは @code{Frameworks/foo.bar._whiz.framework/foo.bar._whiz} （フレームワーク名はモジュールの完全なインポートパスから命名されています）として、 @code{Info.plist} ファイルをバイナリをフレームワークとして識別する @code{.framework} ディレクトリ内に設置して配布しなければなりません。 @code{foo.bar._whiz} モジュールは、元の場所で、 @code{Frameworks/foo.bar._whiz/foo.bar._whiz} のパスを含む @code{sources/foo/bar/_whiz.abi3.fwork} マーカーファイルに記述されます。 また、フレームワークは、 @code{.fwork} へのパスを含む @code{Frameworks/foo.bar._whiz.framework/foo.bar._whiz.origin} も含まなければなりません。

When a module is loaded with this loader, the @code{__file__} for the module
will report as the location of the @code{.fwork} file. This allows code to use
the @code{__file__} of a  module as an anchor for file system traversal.
However, the spec origin will reference the location of the `actual' binary
in the @code{.framework} folder.

The Xcode project building the app is responsible for converting any @code{.so}
files from wherever they exist in the @code{PYTHONPATH} into frameworks in the
@code{Frameworks} folder (including stripping extensions from the module file,
the addition of framework metadata, and signing the resulting framework),
and creating the @code{.fwork} and @code{.origin} files. This will usually be done
with a build step in the Xcode project; see the iOS documentation for
details on how to construct this build step.


Added in version 3.13.


@ref{213f,,Availability}: iOS.

@geindex name (importlib.machinery.AppleFrameworkLoader の属性)
@anchor{library/importlib importlib machinery AppleFrameworkLoader name}@anchor{4b1f}
@deffn {の属性} name

ローダーがサポートするモジュールの名前です。
@end deffn

@geindex path (importlib.machinery.AppleFrameworkLoader の属性)
@anchor{library/importlib importlib machinery AppleFrameworkLoader path}@anchor{4b20}
@deffn {の属性} path

拡張モジュールの @code{.fwork} ファイルへのパス。
@end deffn
@end deffn

@node importlib util -- Utility code for importers,使用例<48>,importlib machinery -- Importers and path hooks,importlib --- import の実装
@anchor{library/importlib importlib-util-utility-code-for-importers}@anchor{4b21}@anchor{library/importlib module-importlib util}@anchor{81}
@subsubsection @code{importlib.util} -- Utility code for importers


@geindex module; importlib.util

`ソースコード:' Lib/importlib/util.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/importlib/util.py}


__________________________________________________________________


このモジュールには、 @ref{2448,,インポーター} の構築を助ける様々なオブジェクトがあります。

@geindex MAGIC_NUMBER (importlib.util モジュール)
@anchor{library/importlib importlib util MAGIC_NUMBER}@anchor{737}
@deffn {データ} importlib.util.MAGIC_NUMBER

バイトコードバージョン番号を表しているバイト列。バイトコードのロード／書き込みについてヘルプが必要なら @ref{4b02,,importlib.abc.SourceLoader} を参照してください。


Added in version 3.4.

@end deffn

@geindex cache_from_source() (importlib.util モジュール)
@anchor{library/importlib importlib util cache_from_source}@anchor{353}
@deffn {の関数} importlib.util.cache_from_source (path, debug_override=None, *, optimization=None)

ソース `path' に関連付けられたバイトコンパイルされたファイルの 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/}/
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} パスを返します。例えば、 `path' が @code{/foo/bar/baz.py} なら、 Python 3.2 の場合返り値は @code{/foo/bar/__pycache__/baz.cpython-32.pyc} になります。 @code{cpython-32} という文字列は、現在のマジックタグから得られます (マジックタグについては @code{get_tag()} を参照; @code{sys.implementation.cache_tag} が未定義なら @ref{36b,,NotImplementedError} が送出されます。)

`optimization' パラメータは、バイトコードファイルの最適化レベルを指定するために使われます。空文字列は最適化しないことを表します。したがって、 `optimization' が @code{'@w{'}} のとき @code{/foo/bar/baz.py} に対して @code{/foo/bar/__pycache__/baz.cpython-32.pyc} というバイトコードパスが返ります。 @code{None} にするとインタープリタの最適化レベルが使われます。それ以外では値の文字列表現が使われます。したがって、 `optimization' が @code{2} のとき  @code{/foo/bar/baz.py} に対して @code{/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc} というバイトコードパスが返ります。 `optimization' の文字列表現は英数字だけが可能で、そうでなければ @ref{2ec,,ValueError} が上げられます。

`debug_override' パラメータは deprecated で、システムの @code{__debug__} 値をオーバーライドするために使用できます。 @code{True} 値は `optimization' を空文字列に設定するのと等価です。 @code{False} 値は `optimization' を @code{1} に設定するのと同等です。もし `debug_override' と `optimization' のどちらも @code{None} 以外であれば @ref{198,,TypeError} が上げられます。


Added in version 3.4.



バージョン 3.5 で変更: `optimization' パラメータが追加され、 `debug_override' パラメータは deprecated になりました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex source_from_cache() (importlib.util モジュール)
@anchor{library/importlib importlib util source_from_cache}@anchor{73e}
@deffn {の関数} importlib.util.source_from_cache (path)

@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} ファイル名への `path' が与えられると、関連するソースコードのファイルパスを返します。例えば、 `path' が @code{/foo/bar/__pycache__/baz.cpython-32.pyc} なら、返されるパスは @code{/foo/bar/baz.py} になります。 `path' は存在する必要はありませんが、 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} または 
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} フォーマットに一致しない場合は @ref{2ec,,ValueError} が送出されます。 @code{sys.implementation.cache_tag} が定義されていない場合、 @ref{36b,,NotImplementedError} が送出されます。


Added in version 3.4.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex decode_source() (importlib.util モジュール)
@anchor{library/importlib importlib util decode_source}@anchor{1159}
@deffn {の関数} importlib.util.decode_source (source_bytes)

与えられたソースコードを表すバイト列をデコードして、文字列としてそれを一般的な改行形式 (universal newlines) で返します (@ref{115a,,importlib.abc.InspectLoader.get_source()} で要求されるように)。


Added in version 3.4.

@end deffn

@geindex resolve_name() (importlib.util モジュール)
@anchor{library/importlib importlib util resolve_name}@anchor{b06}
@deffn {の関数} importlib.util.resolve_name (name, package)

相対的なモジュール名を解決して絶対的なものにします。

`name' の先頭にドットがなければ、単に `name' が返されます。これにより、例えば @code{importlib.util.resolve_name('sys', __spec__.parent)} を使うときに `package' 変数が必要かどうかを確認する必要がなくなります。

`name' が相対的なモジュール名であるにもかかわらず `package' が偽値 (例えば @code{None} や空文字列) ならば、 @ref{65b,,ImportError} が送出されます。相対的な名前がそれを含むパッケージから抜け出る (例えば @code{spam} パッケージ内から @code{..bacon} を要求する) 場合にも @ref{65b,,ImportError} が送出されます。


Added in version 3.3.



バージョン 3.9 で変更: To improve consistency with import statements, raise
@ref{65b,,ImportError} instead of @ref{2ec,,ValueError} for invalid relative
import attempts.

@end deffn

@geindex find_spec() (importlib.util モジュール)
@anchor{library/importlib importlib util find_spec}@anchor{5af}
@deffn {の関数} importlib.util.find_spec (name, package=None)

Find the @ref{2363,,spec} for a module, optionally relative to
the specified `package' name. If the module is in @ref{17e6,,sys.modules},
then @code{sys.modules[name].__spec__} is returned (unless the spec would be
@code{None} or is not set, in which case @ref{2ec,,ValueError} is raised).
Otherwise a search using @ref{f27,,sys.meta_path} is done. @code{None} is
returned if no spec is found.

`name' がサブモジュールを示している  (ドットを含む) 場合、親モジュールは自動的にインポートされます。

`name' と `package' は @code{import_module()} に対するものと同じように機能します。


Added in version 3.4.



バージョン 3.7 で変更: Raises @ref{d3d,,ModuleNotFoundError} instead of @ref{5f0,,AttributeError} if
`package' is in fact not a package (i.e. lacks a
@ref{2054,,__path__} attribute).

@end deffn

@geindex module_from_spec() (importlib.util モジュール)
@anchor{library/importlib importlib util module_from_spec}@anchor{1013}
@deffn {の関数} importlib.util.module_from_spec (spec)

`spec' と @ref{eac,,spec.loader.create_module} に基づいて新しいモジュールを作ります。

@ref{eac,,spec.loader.create_module} が @code{None} を返さない場合は、既に存在するどの属性もリセットされません。また、 `spec' にアクセスしたり属性をモジュールに設定したりする際に @ref{5f0,,AttributeError} 例外が起きても例外は送出されません。

この関数は、新しいモジュールを作る方法として @ref{1014,,types.ModuleType} よりも推奨されます。なぜなら、できるだけ多くのインポートコントロールされた属性をモジュールに設定するために `spec' が使用されるからです。


Added in version 3.5.

@end deffn

@geindex spec_from_loader() (importlib.util モジュール)
@anchor{library/importlib importlib util spec_from_loader}@anchor{a6d}
@deffn {の関数} importlib.util.spec_from_loader (name, loader, *, origin=None, is_package=None)

この関数は、スペックに不足している情報を埋めるために @ref{226c,,ModuleSpec} のような利用可能な @ref{1a28,,loader} API を使います。


Added in version 3.4.

@end deffn

@geindex spec_from_file_location() (importlib.util モジュール)
@anchor{library/importlib importlib util spec_from_file_location}@anchor{eaf}
@deffn {の関数} importlib.util.spec_from_file_location (name, location, *, loader=None, submodule_search_locations=None)

ファイルへのパスにもとづいて @ref{226c,,ModuleSpec} インスタンスを生成するためのファクトリー関数。不足している情報は、ローダー API を利用してスペックから得られる情報と、モジュールがファイルベースであるという暗黙的な情報によって埋められます。


Added in version 3.4.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex source_hash() (importlib.util モジュール)
@anchor{library/importlib importlib util source_hash}@anchor{d3e}
@deffn {の関数} importlib.util.source_hash (source_bytes)

Return the hash of `source_bytes' as bytes. A hash-based @code{.pyc} file embeds
the @ref{d3e,,source_hash()} of the corresponding source file's contents in its
header.


Added in version 3.7.

@end deffn

@geindex _incompatible_extension_module_restrictions() (importlib.util モジュール)
@anchor{library/importlib importlib util _incompatible_extension_module_restrictions}@anchor{4b22}
@deffn {の関数} importlib.util._incompatible_extension_module_restrictions (*, disable_check)

A context manager that can temporarily skip the compatibility check
for extension modules.  By default the check is enabled and will fail
when a single-phase init module is imported in a subinterpreter.
It will also fail for a multi-phase init module that doesn't
explicitly support a per-interpreter GIL, when imported
in an interpreter with its own GIL.

Note that this function is meant to accommodate an unusual case;
one which is likely to eventually go away.  There's is a pretty good
chance this is not what you were looking for.

You can get the same effect as this function by implementing the
basic interface of multi-phase init (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}) and lying about
support for multiple interpreters (or per-interpreter GIL).

@cartouche
@quotation 警告 
Using this function to disable the check can lead to
unexpected behavior and even crashes.  It should only be used during
extension module development.
@end quotation
@end cartouche


Added in version 3.12.

@end deffn

@geindex LazyLoader (importlib.util のクラス)
@anchor{library/importlib importlib util LazyLoader}@anchor{eab}
@deffn {クラス} importlib.util.LazyLoader (loader)

モジュールが属性アクセスできるようになるまで、モジュールのローダーの実行を遅延するクラス。

This class `only' works with loaders that define
@ref{a6a,,exec_module()} as control over what module type
is used for the module is required. For those same reasons, the loader's
@ref{eac,,create_module()} method must return @code{None} or a
type for which its @code{__class__} attribute can be mutated along with not
using @ref{7f7,,slots}. Finally, modules which substitute the object
placed into @ref{17e6,,sys.modules} will not work as there is no way to properly
replace the module references throughout the interpreter safely;
@ref{2ec,,ValueError} is raised if such a substitution is detected.

@cartouche
@quotation 注釈 
起動時間が重要なプロジェクトでは、もし決して使われないモジュールがあれば、このクラスを使ってモジュールをロードするコストを最小化できるかもしれません。スタートアップ時間が重要でないプロジェクトでは、遅延されたロードの際に発生して文脈の外で起こるエラーメッセージのため、このクラスの使用は `著しく' 推奨されません。
@end quotation
@end cartouche


Added in version 3.5.



バージョン 3.6 で変更: Began calling @ref{eac,,create_module()}, removing the
compatibility warning for @ref{ead,,importlib.machinery.BuiltinImporter} and
@ref{eae,,importlib.machinery.ExtensionFileLoader}.


@geindex factory() (importlib.util.LazyLoader のクラスメソッド)
@anchor{library/importlib importlib util LazyLoader factory}@anchor{4b23}
@deffn {メソッド} classmethod factory (loader)

遅延ローダを生成する callable を返すクラスメソッド。これは、ローダーをインスタンスとしてではなくクラスとして渡すような状況において使われることを意図しています。

@example
suffixes = importlib.machinery.SOURCE_SUFFIXES
loader = importlib.machinery.SourceFileLoader
lazy_loader = importlib.util.LazyLoader.factory(loader)
finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
@end example
@end deffn
@end deffn

@node 使用例<48>,,importlib util -- Utility code for importers,importlib --- import の実装
@anchor{library/importlib examples}@anchor{4b24}@anchor{library/importlib importlib-examples}@anchor{4b25}
@subsubsection 使用例


@menu
* プログラムからのインポート:: 
* モジュールがインポートできるか確認する:: 
* ソースファイルから直接インポートする:: 
* Implementing lazy imports:: 
* インポーターのセットアップ:: 
* Approximating importlib.import_module(): Approximating importlib import_module. 

@end menu

@node プログラムからのインポート,モジュールがインポートできるか確認する,,使用例<48>
@anchor{library/importlib importing-programmatically}@anchor{4b26}
@subsubsection プログラムからのインポート


プログラムからモジュールをインポートするには、 @ref{73c,,importlib.import_module()} を使ってください。

@example
import importlib

itertools = importlib.import_module('itertools')
@end example

@node モジュールがインポートできるか確認する,ソースファイルから直接インポートする,プログラムからのインポート,使用例<48>
@anchor{library/importlib checking-if-a-module-can-be-imported}@anchor{4b27}
@subsubsection モジュールがインポートできるか確認する


インポートを実際に行わずに、あるモジュールがインポートできるかを知る必要がある場合は、 @ref{5af,,importlib.util.find_spec()} を使ってください。

Note that if @code{name} is a submodule (contains a dot),
@ref{5af,,importlib.util.find_spec()} will import the parent module.

@example
import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"@{name!r@} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you chose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"@{name!r@} has been imported")
else:
    print(f"can't find the @{name!r@} module")
@end example

@node ソースファイルから直接インポートする,Implementing lazy imports,モジュールがインポートできるか確認する,使用例<48>
@anchor{library/importlib importing-a-source-file-directly}@anchor{4b28}
@subsubsection ソースファイルから直接インポートする


This recipe should be used with caution: it is an approximation of an import
statement where the file path is specified directly, rather than
@ref{3e4,,sys.path} being searched. Alternatives should first be considered first,
such as modifying @ref{3e4,,sys.path} when a proper module is required, or using
@ref{4a4,,runpy.run_path()} when the global namespace resulting from running a Python
file is appropriate.

To import a Python source file directly from a path, use the following recipe:

@example
import importlib.util
import sys


def import_from_path(module_name, file_path):
    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)
    return module


# For illustrative purposes only (use of `json` is arbitrary).
import json
file_path = json.__file__
module_name = json.__name__

# Similar outcome as `import json`.
json = import_from_path(module_name, file_path)
@end example

@node Implementing lazy imports,インポーターのセットアップ,ソースファイルから直接インポートする,使用例<48>
@anchor{library/importlib implementing-lazy-imports}@anchor{4b29}
@subsubsection Implementing lazy imports


The example below shows how to implement lazy imports:

@example
>>> import importlib.util
>>> import sys
>>> def lazy_import(name):
...     spec = importlib.util.find_spec(name)
...     loader = importlib.util.LazyLoader(spec.loader)
...     spec.loader = loader
...     module = importlib.util.module_from_spec(spec)
...     sys.modules[name] = module
...     loader.exec_module(module)
...     return module
...
>>> lazy_typing = lazy_import("typing")
>>> #lazy_typing is a real module object,
>>> #but it is not loaded in memory yet.
>>> lazy_typing.TYPE_CHECKING
False
@end example

@node インポーターのセットアップ,Approximating importlib import_module,Implementing lazy imports,使用例<48>
@anchor{library/importlib setting-up-an-importer}@anchor{4b2a}
@subsubsection インポーターのセットアップ


For deep customizations of import, you typically want to implement an
@ref{2448,,importer}. This means managing both the @ref{236a,,finder} and @ref{1a28,,loader}
side of things. For finders there are two flavours to choose from depending on
your needs: a @ref{127c,,meta path finder} or a @ref{127d,,path entry finder}. The
former is what you would put on @ref{f27,,sys.meta_path} while the latter is what
you create using a @ref{245a,,path entry hook} on @ref{1225,,sys.path_hooks} which works
with @ref{3e4,,sys.path} entries to potentially create a finder. This example will
show you how to register your own importers so that import will use them (for
creating an importer for yourself, read the documentation for the appropriate
classes defined within this package):

@example
import importlib.machinery
import sys

# For illustrative purposes only.
SpamMetaPathFinder = importlib.machinery.PathFinder
SpamPathEntryFinder = importlib.machinery.FileFinder
loader_details = (importlib.machinery.SourceFileLoader,
                  importlib.machinery.SOURCE_SUFFIXES)

# Setting up a meta path finder.
# Make sure to put the finder in the proper location in the list in terms of
# priority.
sys.meta_path.append(SpamMetaPathFinder)

# Setting up a path entry finder.
# Make sure to put the path hook in the proper location in the list in terms
# of priority.
sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))
@end example

@node Approximating importlib import_module,,インポーターのセットアップ,使用例<48>
@anchor{library/importlib approximating-importlib-import-module}@anchor{4b2b}
@subsubsection Approximating @code{importlib.import_module()}


Import itself is implemented in Python code, making it possible to
expose most of the import machinery through importlib. The following
helps illustrate the various APIs that importlib exposes by providing an
approximate implementation of
@ref{73c,,importlib.import_module()}:

@example
import importlib.util
import sys

def import_module(name, package=None):
    """An approximate implementation of import."""
    absolute_name = importlib.util.resolve_name(name, package)
    try:
        return sys.modules[absolute_name]
    except KeyError:
        pass

    path = None
    if '.' in absolute_name:
        parent_name, _, child_name = absolute_name.rpartition('.')
        parent_module = import_module(parent_name)
        path = parent_module.__spec__.submodule_search_locations
    for finder in sys.meta_path:
        spec = finder.find_spec(absolute_name, path)
        if spec is not None:
            break
    else:
        msg = f'No module named @{absolute_name!r@}'
        raise ModuleNotFoundError(msg, name=absolute_name)
    module = importlib.util.module_from_spec(spec)
    sys.modules[absolute_name] = module
    spec.loader.exec_module(module)
    if path is not None:
        setattr(parent_module, child_name, module)
    return module
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node importlib resources -- パッケージリソースの読み取り、オープン、アクセス,importlib resources abc -- リソースの抽象基底クラス,importlib --- import の実装,モジュールのインポート
@anchor{library/importlib resources doc}@anchor{4b2c}@anchor{library/importlib resources importlib-resources-package-resource-reading-opening-and-access}@anchor{4b2d}@anchor{library/importlib resources module-importlib resources}@anchor{7f}@anchor{library/importlib resources translation-repo}@anchor{4b2e}
@subsection @code{importlib.resources} -- パッケージリソースの読み取り、オープン、アクセス


@geindex module; importlib.resources

`ソースコード:' Lib/importlib/resources/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/importlib/resources/__init__.py}


__________________________________________________________________



Added in version 3.7.


This module leverages Python's import system to provide access to `resources'
within `packages'.

"Resources" are file-like resources associated with a module or package in
Python. The resources may be contained directly in a package, within a
subdirectory contained in that package, or adjacent to modules outside a
package. Resources may be text or binary. As a result, a package's Python
module sources (.py), compilation artifacts (pycache), and installation
artifacts (like @ref{32b,,reserved filenames}
in directories) are technically de-facto resources of that package.
In practice, however, resources are primarily those non-Python artifacts
exposed specifically by the package author.

Resources can be opened or read in either binary or text mode.

リソースは大体ディレクトリの中のファイルに似ていますが、これは単なる例え話であることを頭に入れておくことが重要です。例えば、パッケージとそのリソースは @ref{138,,zipimport} を使って zip ファイルからインポートすることができます。

@cartouche
@quotation 注釈 
このモジュールは、 pkg_resources@footnote{https://setuptools.readthedocs.io/en/latest/pkg_resources.html} Basic Resource Access@footnote{https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access} に似た機能を、そのパッケージのパフォーマンスのオーバーヘッドを伴わずに提供します。 これにより、パッケージに含まれるリソースの読み込みがより簡単になり、より安定した一貫した意味付けができるようになります。

このモジュールのスタンドアローンバックポートでは、 importlib.resources の使用@footnote{https://importlib-resources.readthedocs.io/en/latest/using.html} と pkg_resources から importlib.resources への移行@footnote{https://importlib-resources.readthedocs.io/en/latest/migration.html} についての詳細情報を提供しています。
@end quotation
@end cartouche

@ref{10c7,,Loaders} でリソースの読み込みをサポートしたい場合は、 @ref{4af8,,importlib.resources.abc.ResourceReader} で指定された @code{get_resource_reader(fullname)} メソッドを実装しなければいけません。

@geindex Anchor (importlib.resources のクラス)
@anchor{library/importlib resources importlib resources Anchor}@anchor{4b2f}
@deffn {クラス} importlib.resources.Anchor

Represents an anchor for resources, either a @ref{1014,,module object} or a module name as a string. Defined as
@code{Union[str, ModuleType]}.
@end deffn

@geindex files() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources files}@anchor{6b6}
@deffn {の関数} importlib.resources.files (anchor: Anchor | None = None)

Returns a @ref{2fa,,Traversable} object
representing the resource container (think directory) and its resources
(think files). A Traversable may contain other containers (think
subdirectories).

`anchor' is an optional @ref{4b2f,,Anchor}. If the anchor is a
package, resources are resolved from that package. If a module,
resources are resolved adjacent to that module (in the same package
or the package root). If the anchor is omitted, the caller's module
is used.


Added in version 3.9.



バージョン 3.12 で変更: `package' parameter was renamed to `anchor'. `anchor' can now
be a non-package module and if omitted will default to the caller's
module. `package' is still accepted for compatibility but will raise
a @ref{1a3,,DeprecationWarning}. Consider passing the anchor positionally or
using @code{importlib_resources >= 5.10} for a compatible interface
on older Pythons.

@end deffn

@geindex as_file() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources as_file}@anchor{6b5}
@deffn {の関数} importlib.resources.as_file (traversable)

Given a @ref{2fa,,Traversable} object representing
a file or directory, typically from @ref{6b6,,importlib.resources.files()},
return a context manager for use in a @ref{186,,with} statement.
The context manager provides a @ref{266,,pathlib.Path} object.

Exiting the context manager cleans up any temporary file or directory
created when the resource was extracted from e.g. a zip file.

Use @code{as_file} when the Traversable methods
(@code{read_text}, etc) are insufficient and an actual file or directory on
the file system is required.


Added in version 3.9.



バージョン 3.12 で変更: Added support for `traversable' representing a directory.

@end deffn

@menu
* 関数 API:: 

@end menu

@node 関数 API,,,importlib resources -- パッケージリソースの読み取り、オープン、アクセス
@anchor{library/importlib resources functional-api}@anchor{4b30}@anchor{library/importlib resources importlib-resources-functional}@anchor{4b31}
@subsubsection 関数 API


A set of simplified, backwards-compatible helpers is available.
These allow common operations in a single function call.

For all the following functions:


@itemize -

@item 
`anchor' is an @ref{4b2f,,Anchor},
as in @ref{6b6,,files()}.
Unlike in @code{files}, it may not be omitted.

@item 
`path_names' are components of a resource's path name, relative to
the anchor.
For example, to get the text of resource named @code{info.txt}, use:

@example
importlib.resources.read_text(my_module, "info.txt")
@end example

Like @ref{2fa,,Traversable.joinpath},
The individual components should use forward slashes (@code{/})
as path separators.
For example, the following are equivalent:

@example
importlib.resources.read_binary(my_module, "pics/painting.png")
importlib.resources.read_binary(my_module, "pics", "painting.png")
@end example

For backward compatibility reasons, functions that read text require
an explicit `encoding' argument if multiple `path_names' are given.
For example, to get the text of @code{info/chapter1.txt}, use:

@example
importlib.resources.read_text(my_module, "info", "chapter1.txt",
                              encoding='utf-8')
@end example
@end itemize

@geindex open_binary() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources open_binary}@anchor{4fe}
@deffn {の関数} importlib.resources.open_binary (anchor, *path_names)

Open the named resource for binary reading.

See @ref{4b31,,the introduction} for
details on `anchor' and `path_names'.

This function returns a @ref{23a,,BinaryIO} object,
that is, a binary stream open for reading.

This function is roughly equivalent to:

@example
files(anchor).joinpath(*path_names).open('rb')
@end example


バージョン 3.13 で変更: Multiple `path_names' are accepted.

@end deffn

@geindex open_text() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources open_text}@anchor{4ff}
@deffn {の関数} importlib.resources.open_text (anchor, *path_names, encoding='utf-8', errors='strict')

Open the named resource for text reading.
By default, the contents are read as strict UTF-8.

See @ref{4b31,,the introduction} for
details on `anchor' and `path_names'.
`encoding' and `errors' have the same meaning as in built-in @ref{316,,open()}.

For backward compatibility reasons, the `encoding' argument must be given
explicitly if there are multiple `path_names'.
This limitation is scheduled to be removed in Python 3.15.

This function returns a @ref{239,,TextIO} object,
that is, a text stream open for reading.

This function is roughly equivalent to:

@example
files(anchor).joinpath(*path_names).open('r', encoding=encoding)
@end example


バージョン 3.13 で変更: Multiple `path_names' are accepted.
`encoding' and `errors' must be given as keyword arguments.

@end deffn

@geindex read_binary() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources read_binary}@anchor{501}
@deffn {の関数} importlib.resources.read_binary (anchor, *path_names)

Read and return the contents of the named resource as @ref{192,,bytes}.

See @ref{4b31,,the introduction} for
details on `anchor' and `path_names'.

This function is roughly equivalent to:

@example
files(anchor).joinpath(*path_names).read_bytes()
@end example


バージョン 3.13 で変更: Multiple `path_names' are accepted.

@end deffn

@geindex read_text() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources read_text}@anchor{502}
@deffn {の関数} importlib.resources.read_text (anchor, *path_names, encoding='utf-8', errors='strict')

Read and return the contents of the named resource as @ref{169,,str}.
By default, the contents are read as strict UTF-8.

See @ref{4b31,,the introduction} for
details on `anchor' and `path_names'.
`encoding' and `errors' have the same meaning as in built-in @ref{316,,open()}.

For backward compatibility reasons, the `encoding' argument must be given
explicitly if there are multiple `path_names'.
This limitation is scheduled to be removed in Python 3.15.

This function is roughly equivalent to:

@example
files(anchor).joinpath(*path_names).read_text(encoding=encoding)
@end example


バージョン 3.13 で変更: Multiple `path_names' are accepted.
`encoding' and `errors' must be given as keyword arguments.

@end deffn

@geindex path() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources path}@anchor{500}
@deffn {の関数} importlib.resources.path (anchor, *path_names)

Provides the path to the `resource' as an actual file system path.  This
function returns a context manager for use in a @ref{186,,with} statement.
The context manager provides a @ref{266,,pathlib.Path} object.

Exiting the context manager cleans up any temporary files created, e.g.
when the resource needs to be extracted from a zip file.

For example, the @ref{a24,,stat()} method requires
an actual file system path; it can be used like this:

@example
with importlib.resources.path(anchor, "resource.txt") as fspath:
    result = fspath.stat()
@end example

See @ref{4b31,,the introduction} for
details on `anchor' and `path_names'.

This function is roughly equivalent to:

@example
as_file(files(anchor).joinpath(*path_names))
@end example


バージョン 3.13 で変更: Multiple `path_names' are accepted.
`encoding' and `errors' must be given as keyword arguments.

@end deffn

@geindex is_resource() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources is_resource}@anchor{4fd}
@deffn {の関数} importlib.resources.is_resource (anchor, *path_names)

Return @code{True} if the named resource exists, otherwise @code{False}.
This function does not consider directories to be resources.

See @ref{4b31,,the introduction} for
details on `anchor' and `path_names'.

This function is roughly equivalent to:

@example
files(anchor).joinpath(*path_names).is_file()
@end example


バージョン 3.13 で変更: Multiple `path_names' are accepted.

@end deffn

@geindex contents() (importlib.resources モジュール)
@anchor{library/importlib resources importlib resources contents}@anchor{503}
@deffn {の関数} importlib.resources.contents (anchor, *path_names)

Return an iterable over the named items within the package or path.
The iterable returns names of resources (e.g. files) and non-resources
(e.g. directories) as @ref{169,,str}.
The iterable does not recurse into subdirectories.

See @ref{4b31,,the introduction} for
details on `anchor' and `path_names'.

This function is roughly equivalent to:

@example
for resource in files(anchor).joinpath(*path_names).iterdir():
    yield resource.name
@end example


バージョン 3.11 で非推奨: Prefer @code{iterdir()} as above, which offers more control over the
results and richer functionality.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node importlib resources abc -- リソースの抽象基底クラス,importlib metadata -- パッケージメタデータへのアクセス,importlib resources -- パッケージリソースの読み取り、オープン、アクセス,モジュールのインポート
@anchor{library/importlib resources abc doc}@anchor{4b32}@anchor{library/importlib resources abc importlib-resources-abc-abstract-base-classes-for-resources}@anchor{4b33}@anchor{library/importlib resources abc module-importlib resources abc}@anchor{80}@anchor{library/importlib resources abc translation-repo}@anchor{4b34}
@subsection @code{importlib.resources.abc} -- リソースの抽象基底クラス


@geindex module; importlib.resources.abc

`ソースコード:' Lib/importlib/resources/abc.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/importlib/resources/abc.py}


__________________________________________________________________



Added in version 3.11.


@geindex ResourceReader (importlib.resources.abc のクラス)
@anchor{library/importlib resources abc importlib resources abc ResourceReader}@anchor{4af8}
@deffn {クラス} importlib.resources.abc.ResourceReader

`TraversableResources に取って代わられました'

`resources' の読み出し機能を提供する @ref{13ce,,抽象基底クラス (abstract base class@comma{} ABC)} です。

From the perspective of this ABC, a `resource' is a binary
artifact that is shipped within a package. Typically this is
something like a data file that lives next to the @code{__init__.py}
file of the package. The purpose of this class is to help abstract
out the accessing of such data files so that it does not matter if
the package and its data file(s) are stored e.g. in a zip file
versus on the file system.

For any of methods of this class, a `resource' argument is
expected to be a @ref{5a1,,path-like object} which represents
conceptually just a file name. This means that no subdirectory
paths should be included in the `resource' argument. This is
because the location of the package the reader is for, acts as the
"directory". Hence the metaphor for directories and file
names is packages and resources, respectively. This is also why
instances of this class are expected to directly correlate to
a specific package (instead of potentially representing multiple
packages or a module).

Loaders that wish to support resource reading are expected to
provide a method called @code{get_resource_reader(fullname)} which
returns an object implementing this ABC's interface. If the module
specified by fullname is not a package, this method should return
@ref{885,,None}. An object compatible with this ABC should only be
returned when the specified module is a package.


バージョン 3.12 で非推奨: Use @ref{2f9,,importlib.resources.abc.TraversableResources} instead.


@geindex open_resource() (importlib.resources.abc.ResourceReader のメソッド)
@anchor{library/importlib resources abc importlib resources abc ResourceReader open_resource}@anchor{4b35}
@deffn {メソッド} abstractmethod open_resource (resource)

Returns an opened, @ref{17ac,,file-like object} for binary reading
of the `resource'.

リソースが見付からない場合は、 @ref{264,,FileNotFoundError} が送出されます。
@end deffn

@geindex resource_path() (importlib.resources.abc.ResourceReader のメソッド)
@anchor{library/importlib resources abc importlib resources abc ResourceReader resource_path}@anchor{4b36}
@deffn {メソッド} abstractmethod resource_path (resource)

`resource' へのファイルシステムパスを返します。

リソースの実体がファイルシステムに存在しない場合、 @ref{264,,FileNotFoundError} が送出されます。
@end deffn

@geindex is_resource() (importlib.resources.abc.ResourceReader のメソッド)
@anchor{library/importlib resources abc importlib resources abc ResourceReader is_resource}@anchor{4b37}
@deffn {メソッド} abstractmethod is_resource (path)

Returns @code{True} if the named `path' is considered a resource.
@ref{264,,FileNotFoundError} is raised if `path' does not exist.


バージョン 3.10 で変更: The argument `name' was renamed to `path'.

@end deffn

@geindex contents() (importlib.resources.abc.ResourceReader のメソッド)
@anchor{library/importlib resources abc importlib resources abc ResourceReader contents}@anchor{4b38}
@deffn {メソッド} abstractmethod contents ()

Returns an @ref{12f1,,iterable} of strings over the contents of
the package. Do note that it is not required that all names
returned by the iterator be actual resources, e.g. it is
acceptable to return names for which @ref{4b37,,is_resource()} would
be false.

Allowing non-resource names to be returned is to allow for
situations where how a package and its resources are stored
are known a priori and the non-resource names would be useful.
For instance, returning subdirectory names is allowed so that
when it is known that the package and resources are stored on
the file system then those subdirectory names can be used
directly.

The abstract method returns an iterable of no items.
@end deffn
@end deffn

@geindex Traversable (importlib.resources.abc のクラス)
@anchor{library/importlib resources abc importlib resources abc Traversable}@anchor{2fa}
@deffn {クラス} importlib.resources.abc.Traversable

An object with a subset of @ref{266,,pathlib.Path} methods suitable for
traversing directories and opening files.

For a representation of the object on the file-system, use
@ref{6b5,,importlib.resources.as_file()}.

@geindex name (importlib.resources.abc.Traversable の属性)
@anchor{library/importlib resources abc importlib resources abc Traversable name}@anchor{4b39}
@deffn {の属性} name

Abstract. The base name of this object without any parent references.
@end deffn

@geindex iterdir() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable iterdir}@anchor{4b3a}
@deffn {メソッド} abstractmethod iterdir ()

Yield Traversable objects in self.
@end deffn

@geindex is_dir() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable is_dir}@anchor{4b3b}
@deffn {メソッド} abstractmethod is_dir ()

Return @code{True} if self is a directory.
@end deffn

@geindex is_file() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable is_file}@anchor{4b3c}
@deffn {メソッド} abstractmethod is_file ()

Return @code{True} if self is a file.
@end deffn

@geindex joinpath() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable joinpath}@anchor{4b3d}
@deffn {メソッド} abstractmethod joinpath (*pathsegments)

Traverse directories according to `pathsegments' and return
the result as @code{Traversable}.

Each `pathsegments' argument may contain multiple names separated by
forward slashes (@code{/}, @code{posixpath.sep} ).
For example, the following are equivalent:

@example
files.joinpath('subdir', 'subsuddir', 'file.txt')
files.joinpath('subdir/subsuddir/file.txt')
@end example

Note that some @code{Traversable} implementations
might not be updated to the latest version of the protocol.
For compatibility with such implementations, provide a single argument
without path separators to each call to @code{joinpath}. For example:

@example
files.joinpath('subdir').joinpath('subsubdir').joinpath('file.txt')
@end example


バージョン 3.11 で変更: @code{joinpath} accepts multiple `pathsegments', and these segments
may contain forward slashes as path separators.
Previously, only a single `child' argument was accepted.

@end deffn

@geindex __truediv__() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable __truediv__}@anchor{4b3e}
@deffn {メソッド} abstractmethod __truediv__ (child)

Return Traversable child in self.
Equivalent to @code{joinpath(child)}.
@end deffn

@geindex open() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable open}@anchor{4b3f}
@deffn {メソッド} 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 @ref{2c3a,,pathlib.Path.open}).

When opening as text, accepts encoding parameters such as those
accepted by @ref{9be,,io.TextIOWrapper}.
@end deffn

@geindex read_bytes() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable read_bytes}@anchor{4b40}
@deffn {メソッド} read_bytes ()

Read contents of self as bytes.
@end deffn

@geindex read_text() (importlib.resources.abc.Traversable のメソッド)
@anchor{library/importlib resources abc importlib resources abc Traversable read_text}@anchor{4b41}
@deffn {メソッド} read_text (encoding=None)

Read contents of self as text.
@end deffn
@end deffn

@geindex TraversableResources (importlib.resources.abc のクラス)
@anchor{library/importlib resources abc importlib resources abc TraversableResources}@anchor{2f9}
@deffn {クラス} importlib.resources.abc.TraversableResources

An abstract base class for resource readers capable of serving
the @ref{6b6,,importlib.resources.files()} interface. Subclasses
@ref{4af8,,ResourceReader} and provides
concrete implementations of the @code{ResourceReader}'s
abstract methods. Therefore, any loader supplying
@code{TraversableResources} also supplies @code{ResourceReader}.

Loaders that wish to support resource reading are expected to
implement this interface.

@geindex files() (importlib.resources.abc.TraversableResources のメソッド)
@anchor{library/importlib resources abc importlib resources abc TraversableResources files}@anchor{4b42}
@deffn {メソッド} abstractmethod files ()

Returns a @ref{2fa,,importlib.resources.abc.Traversable} object for the loaded
package.
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node importlib metadata -- パッケージメタデータへのアクセス,sys path モジュール検索パスの初期化,importlib resources abc -- リソースの抽象基底クラス,モジュールのインポート
@anchor{library/importlib metadata doc}@anchor{4b43}@anchor{library/importlib metadata importlib-metadata-accessing-package-metadata}@anchor{4b44}@anchor{library/importlib metadata module-importlib metadata}@anchor{7e}@anchor{library/importlib metadata translation-repo}@anchor{4b45}@anchor{library/importlib metadata using}@anchor{4b46}
@subsection @code{importlib.metadata} -- パッケージメタデータへのアクセス


@geindex module; importlib.metadata


Added in version 3.8.



バージョン 3.10 で変更: @code{importlib.metadata} は暫定的なものではなくなりました。


`ソースコード:' Lib/importlib/metadata/__init__.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/importlib/metadata/__init__.py}

@code{importlib.metadata} is a library that provides access to
the metadata of an installed Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package},
such as its entry points
or its top-level names (Import Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Import-Package}s, modules, if any).
Built in part on Python's import system, this library
intends to replace similar functionality in the entry point API@footnote{https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points} and metadata API@footnote{https://setuptools.readthedocs.io/en/latest/pkg_resources.html#metadata-api} of @code{pkg_resources}. Along with
@ref{7f,,importlib.resources},
this package can eliminate the need to use the older and less efficient
@code{pkg_resources} package.

@code{importlib.metadata} は、Pythonの @code{site-packages} ディレクトリに pip@footnote{https://pypi.org/project/pip/} などのツールでインストールしたサードパーティの `配布パッケージ' に対して動作します。具体的には、 @code{dist-info} や @code{egg-info} ディレクトリを持つ配布物や、 コアとなるメタデータの仕様@footnote{https://packaging.python.org/ja/latest/specifications/core-metadata/#core-metadata} で定義されたメタデータを検出できるようにします。

@cartouche
@quotation 重要 
これらはPythonコード内でインポートできるトップレベルの `パッケージ' 名と `必ずしも' 同等であったり、1:1 で対応するものではありません。1つの `配布パッケージ' は複数の `パッケージ' (および単一のモジュール) を含むことができ、1つのトップレベルの `パッケージ' は、それが名前空間パッケージであれば複数の `配布パッケージ' にマップすることができます。これらのマッピングを得るには @ref{a11,,packages_distributions()}  を使用します。
@end quotation
@end cartouche

By default, distribution metadata can live on the file system
or in zip archives on
@ref{3e4,,sys.path}. Through an extension mechanism, the metadata can live almost
anywhere.


@subsubheading 参考



@table @asis

@item @indicateurl{https://importlib-metadata.readthedocs.io/}

@code{importlib_metadata} のドキュメントは @code{importlib.metadata} のバックポートです。これには、このモジュールのクラスと関数の APIリファレンス@footnote{https://importlib-metadata.readthedocs.io/en/latest/api.html} と、 @code{pkg_resources} の既存のユーザーのための 移行ガイド@footnote{https://importlib-metadata.readthedocs.io/en/latest/migration.html} があります。
@end table


@menu
* 概要: 概要<3>. 
* 機能 API:: 
* Distributions:: 
* Distribution Discovery:: 
* Implementing Custom Providers:: 

@end menu

@node 概要<3>,機能 API,,importlib metadata -- パッケージメタデータへのアクセス
@anchor{library/importlib metadata overview}@anchor{4b47}
@subsubsection 概要


Let's say you wanted to get the version string for a
Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package} you've installed
using @code{pip}. We start by creating a virtual environment and installing
something into it:

@example
$ python -m venv example
$ source example/bin/activate
(example) $ python -m pip install wheel
@end example

以下のように実行することで、@code{wheel} のバージョン文字列を取得することができます:

@example
(example) $ python
>>> from importlib.metadata import version
>>> version('wheel')
'0.32.3'
@end example

You can also get a collection of entry points selectable by properties of the EntryPoint (typically 'group' or 'name'), such as
@code{console_scripts}, @code{distutils.commands} and others. Each group contains a
collection of @ref{589,,EntryPoint} objects.

@ref{4b48,,ディストリビューションのメタデータ} を取得することができます。:

@example
>>> list(metadata('wheel'))
['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'Maintainer', 'Maintainer-email', 'License', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Provides-Extra', 'Requires-Dist', 'Requires-Dist']
@end example

また、 @ref{4b49,,配布物のバージョン番号} を取得し、 @ref{4b4a,,構成ファイル} をリストアップし、配布物の @ref{4b4b,,配布物の要件} のリストを取得することができます。

@geindex PackageNotFoundError
@anchor{library/importlib metadata importlib metadata PackageNotFoundError}@anchor{4b4c}
@deffn {例外} importlib.metadata.PackageNotFoundError

Subclass of @ref{d3d,,ModuleNotFoundError} raised by several functions in this
module when queried for a distribution package which is not installed in the
current Python environment.
@end deffn

@node 機能 API,Distributions,概要<3>,importlib metadata -- パッケージメタデータへのアクセス
@anchor{library/importlib metadata functional-api}@anchor{4b4d}
@subsubsection 機能 API


本パッケージは、公開APIを通じて以下の機能を提供します。

@menu
* エントリポイント:: 
* 配布物メタデータ:: 
* 配布物バージョン:: 
* 配布物ファイル:: 
* 配布物の要件:: 
* Mapping import to distribution packages:: 

@end menu

@node エントリポイント,配布物メタデータ,,機能 API
@anchor{library/importlib metadata entry-points}@anchor{589}@anchor{library/importlib metadata id2}@anchor{4b4e}
@subsubsection エントリポイント


@geindex entry_points() (importlib.metadata モジュール)
@anchor{library/importlib metadata importlib metadata entry_points}@anchor{4b4f}
@deffn {の関数} importlib.metadata.entry_points (**select_params)

Returns a @ref{4b50,,EntryPoints} instance describing entry points for the
current environment. Any given keyword parameters are passed to the
@code{select()} method for comparison to the attributes of
the individual entry point definitions.

Note: it is not currently possible to query for entry points based on
their @code{EntryPoint.dist} attribute (as different @code{Distribution}
instances do not currently compare equal, even if they have the same attributes)
@end deffn

@geindex EntryPoints (importlib.metadata のクラス)
@anchor{library/importlib metadata importlib metadata EntryPoints}@anchor{4b50}
@deffn {クラス} importlib.metadata.EntryPoints

Details of a collection of installed entry points.

Also provides a @code{.groups} attribute that reports all identified entry
point groups, and a @code{.names} attribute that reports all identified entry
point names.
@end deffn

@geindex EntryPoint (importlib.metadata のクラス)
@anchor{library/importlib metadata importlib metadata EntryPoint}@anchor{4b51}
@deffn {クラス} importlib.metadata.EntryPoint

Details of an installed entry point.

Each @code{EntryPoint} instance has @code{.name}, @code{.group}, and @code{.value}
attributes and a @code{.load()} method to resolve the value. There are also
@code{.module}, @code{.attr}, and @code{.extras} attributes for getting the
components of the @code{.value} attribute, and @code{.dist} for obtaining
information regarding the distribution package that provides the entry point.
@end deffn

すべてのエントリポイントに問い合わせる:

@example
>>> eps = entry_points()
@end example

The @code{entry_points()} function returns a @code{EntryPoints} object,
a collection of all @code{EntryPoint} objects with @code{names} and @code{groups}
attributes for convenience:

@example
>>> sorted(eps.groups)
['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation']
@end example

@code{EntryPoints} has a @code{select()} method to select entry points
matching specific properties. Select entry points in the
@code{console_scripts} group:

@example
>>> scripts = eps.select(group='console_scripts')
@end example

Equivalently, since @code{entry_points()} passes keyword arguments
through to select:

@example
>>> scripts = entry_points(group='console_scripts')
@end example

"wheel" という名前の特定のスクリプトを選択します。(wheelプロジェクトにあります):

@example
>>> 'wheel' in scripts.names
True
>>> wheel = scripts['wheel']
@end example

同様に、選択時にそのエントリポイントを問い合わせます:

@example
>>> (wheel,) = entry_points(group='console_scripts', name='wheel')
>>> (wheel,) = entry_points().select(group='console_scripts', name='wheel')
@end example

解決したエントリポイントを検証する:

@example
>>> wheel
EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')
>>> wheel.module
'wheel.cli'
>>> wheel.attr
'main'
>>> wheel.extras
[]
>>> main = wheel.load()
>>> main
<function main at 0x103528488>
@end example

The @code{group} and @code{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@footnote{https://setuptools.pypa.io/en/latest/userguide/entry_point.html}
for more information on entry points, their definition, and usage.


バージョン 3.12 で変更: The "selectable" entry points were introduced in @code{importlib_metadata}
3.6 and Python 3.10. Prior to those changes, @code{entry_points} accepted
no parameters and always returned a dictionary of entry points, keyed
by group. With @code{importlib_metadata} 5.0 and Python 3.12,
@code{entry_points} always returns an @code{EntryPoints} object. See
backports.entry_points_selectable@footnote{https://pypi.org/project/backports.entry_points_selectable/}
for compatibility options.



バージョン 3.13 で変更: @code{EntryPoint} objects no longer present a tuple-like interface
(@ref{588,,__getitem__()}).


@node 配布物メタデータ,配布物バージョン,エントリポイント,機能 API
@anchor{library/importlib metadata distribution-metadata}@anchor{4b52}@anchor{library/importlib metadata metadata}@anchor{4b48}
@subsubsection 配布物メタデータ


@geindex metadata() (importlib.metadata モジュール)
@anchor{library/importlib metadata importlib metadata metadata}@anchor{4b53}
@deffn {の関数} importlib.metadata.metadata (distribution_name)

Return the distribution metadata corresponding to the named
distribution package as a @ref{4b54,,PackageMetadata} instance.

Raises @ref{4b4c,,PackageNotFoundError} if the named distribution
package is not installed in the current Python environment.
@end deffn

@geindex PackageMetadata (importlib.metadata のクラス)
@anchor{library/importlib metadata importlib metadata PackageMetadata}@anchor{4b54}
@deffn {クラス} importlib.metadata.PackageMetadata

A concrete implementation of the
PackageMetadata protocol@footnote{https://importlib-metadata.readthedocs.io/en/latest/api.html#importlib_metadata.PackageMetadata}.

In addition to providing the defined protocol methods and attributes, subscripting
the instance is equivalent to calling the @code{get()} method.
@end deffn

Every Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package}
includes some metadata, which you can extract using the @code{metadata()} function:

@example
>>> wheel_metadata = metadata('wheel')
@end example

The keys of the returned data structure name the metadata keywords, and
the values are returned unparsed from the distribution metadata:

@example
>>> wheel_metadata['Requires-Python']
'>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
@end example

@ref{4b54,,PackageMetadata} also presents a @code{json} attribute that returns
all the metadata in a JSON-compatible form per 
@geindex Python Enhancement Proposals; PEP 566
PEP 566@footnote{https://peps.python.org/pep-0566/}:

@example
>>> wheel_metadata.json['requires_python']
'>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
@end example

The full set of available metadata is not described here.
See the PyPA Core metadata specification@footnote{https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata} for additional details.


バージョン 3.10 で変更: ペイロードを通して提示されるとき、 @code{Description} がメタデータに含まれるようになりました。行の継続文字は削除されました。

@code{json} 属性が追加されました。


@node 配布物バージョン,配布物ファイル,配布物メタデータ,機能 API
@anchor{library/importlib metadata distribution-versions}@anchor{4b55}@anchor{library/importlib metadata version}@anchor{4b49}
@subsubsection 配布物バージョン


@geindex version() (importlib.metadata モジュール)
@anchor{library/importlib metadata importlib metadata version}@anchor{1966}
@deffn {の関数} importlib.metadata.version (distribution_name)

Return the installed distribution package
version@footnote{https://packaging.python.org/en/latest/specifications/core-metadata/#version}
for the named distribution package.

Raises @ref{4b4c,,PackageNotFoundError} if the named distribution
package is not installed in the current Python environment.
@end deffn

The @code{version()} function is the quickest way to get a
Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package}'s version
number, as a string:

@example
>>> version('wheel')
'0.32.3'
@end example

@node 配布物ファイル,配布物の要件,配布物バージョン,機能 API
@anchor{library/importlib metadata distribution-files}@anchor{4b56}@anchor{library/importlib metadata files}@anchor{4b4a}
@subsubsection 配布物ファイル


@geindex files() (importlib.metadata モジュール)
@anchor{library/importlib metadata importlib metadata files}@anchor{4b57}
@deffn {の関数} importlib.metadata.files (distribution_name)

Return the full set of files contained within the named
distribution package.

Raises @ref{4b4c,,PackageNotFoundError} if the named distribution
package is not installed in the current Python environment.

Returns @ref{885,,None} if the distribution is found but the installation
database records reporting the files associated with the distribution package
are missing.
@end deffn

@geindex PackagePath (importlib.metadata のクラス)
@anchor{library/importlib metadata importlib metadata PackagePath}@anchor{4b58}
@deffn {クラス} importlib.metadata.PackagePath

A @ref{6cd,,pathlib.PurePath} derived object with additional @code{dist},
@code{size}, and @code{hash} properties corresponding to the distribution
package's installation metadata for that file.
@end deffn

The @code{files()} function takes a
Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package}
name and returns all of the files installed by this distribution. Each file is reported
as a @ref{4b58,,PackagePath} instance. For example:

@example
>>> util = [p for p in files('wheel') if 'util.py' in str(p)][0]
>>> util
PackagePath('wheel/util.py')
>>> util.size
859
>>> util.dist
<importlib.metadata._hooks.PathDistribution object at 0x101e0cef0>
>>> util.hash
<FileHash mode: sha256 value: bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI>
@end example

ファイルを取得したら、その内容を読むこともできます:

@example
>>> print(util.read_text())
import base64
import sys
...
def as_bytes(s):
    if isinstance(s, text_type):
        return s.encode('utf-8')
    return s
@end example

You can also use the @code{locate()} method to get the absolute
path to the file:

@example
>>> util.locate()
PosixPath('/home/gustav/example/lib/site-packages/wheel/util.py')
@end example

In the case where the metadata file listing files
(@code{RECORD} or @code{SOURCES.txt}) is missing, @code{files()} will
return @ref{885,,None}. The caller may wish to wrap calls to
@code{files()} in always_iterable@footnote{https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable}
or otherwise guard against this condition if the target
distribution is not known to have the metadata present.

@node 配布物の要件,Mapping import to distribution packages,配布物ファイル,機能 API
@anchor{library/importlib metadata distribution-requirements}@anchor{4b59}@anchor{library/importlib metadata requirements}@anchor{4b4b}
@subsubsection 配布物の要件


@geindex requires() (importlib.metadata モジュール)
@anchor{library/importlib metadata importlib metadata requires}@anchor{4b5a}
@deffn {の関数} importlib.metadata.requires (distribution_name)

Return the declared dependency specifiers for the named
distribution package.

Raises @ref{4b4c,,PackageNotFoundError} if the named distribution
package is not installed in the current Python environment.
@end deffn

To get the full set of requirements for a Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package},
use the @code{requires()}
function:

@example
>>> requires('wheel')
["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]
@end example
@anchor{library/importlib metadata package-distributions}@anchor{a11}
@node Mapping import to distribution packages,,配布物の要件,機能 API
@anchor{library/importlib metadata import-distribution-package-mapping}@anchor{4b5b}@anchor{library/importlib metadata mapping-import-to-distribution-packages}@anchor{4b5c}
@subsubsection Mapping import to distribution packages


@geindex packages_distributions() (importlib.metadata モジュール)
@anchor{library/importlib metadata importlib metadata packages_distributions}@anchor{4b5d}
@deffn {の関数} importlib.metadata.packages_distributions ()

Return a mapping from the top level module and import package
names found via @ref{f27,,sys.meta_path} to the names of the distribution
packages (if any) that provide the corresponding files.

To allow for namespace packages (which may have members provided by
multiple distribution packages), each top level import name maps to a
list of distribution names rather than mapping directly to a single name.
@end deffn

インポート可能なトップレベルのPythonモジュールまたは パッケージ@footnote{https://packaging.python.org/ja/latest/glossary/#term-Import-Package} を提供する 配布パッケージ@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package} 名(名前空間パッケージの場合はその名前)を解決する便利なメソッドです:

@example
>>> packages_distributions()
@{'importlib_metadata': ['importlib-metadata'], 'yaml': ['PyYAML'], 'jaraco': ['jaraco.classes', 'jaraco.functools'], ...@}
@end example

Some editable installs, do not supply top-level names@footnote{https://github.com/pypa/packaging-problems/issues/609}, and thus this
function is not reliable with such installs.


Added in version 3.10.


@node Distributions,Distribution Discovery,機能 API,importlib metadata -- パッケージメタデータへのアクセス
@anchor{library/importlib metadata distributions}@anchor{a12}@anchor{library/importlib metadata id9}@anchor{4b5e}
@subsubsection Distributions


@geindex distribution() (importlib.metadata モジュール)
@anchor{library/importlib metadata importlib metadata distribution}@anchor{4b5f}
@deffn {の関数} importlib.metadata.distribution (distribution_name)

Return a @ref{4b60,,Distribution} instance describing the named
distribution package.

Raises @ref{4b4c,,PackageNotFoundError} if the named distribution
package is not installed in the current Python environment.
@end deffn

@geindex Distribution (importlib.metadata のクラス)
@anchor{library/importlib metadata importlib metadata Distribution}@anchor{4b60}
@deffn {クラス} importlib.metadata.Distribution

Details of an installed distribution package.

Note: different @code{Distribution} instances do not currently compare
equal, even if they relate to the same installed distribution and
accordingly have the same attributes.
@end deffn

While the module level API described above is the most common and convenient usage,
you can get all of that information from the @code{Distribution} class.
@code{Distribution} is an abstract object that represents the metadata for
a Python Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package}.
You can get the concrete @code{Distribution} subclass instance for an installed
distribution package by calling the @ref{4b5f,,distribution()} function:

@example
>>> from importlib.metadata import distribution
>>> dist = distribution('wheel')
>>> type(dist)
<class 'importlib.metadata.PathDistribution'>
@end example

Thus, an alternative way to get the version number is through the
@code{Distribution} instance:

@example
>>> dist.version
'0.32.3'
@end example

There are all kinds of additional metadata available on @code{Distribution}
instances:

@example
>>> dist.metadata['Requires-Python']
'>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
>>> dist.metadata['License']
'MIT'
@end example

For editable packages, an @code{origin} property may present 
@geindex Python Enhancement Proposals; PEP 610
PEP 610@footnote{https://peps.python.org/pep-0610/}
metadata:

@example
>>> dist.origin.url
'file:///path/to/wheel-0.32.3.editable-py3-none-any.whl'
@end example

The full set of available metadata is not described here.
See the PyPA Core metadata specification@footnote{https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata} for additional details.


Added in version 3.13: The @code{.origin} property was added.


@node Distribution Discovery,Implementing Custom Providers,Distributions,importlib metadata -- パッケージメタデータへのアクセス
@anchor{library/importlib metadata distribution-discovery}@anchor{4b61}
@subsubsection Distribution Discovery


デフォルトでは、このパッケージは組み込みで、ファイルシステムおよび zip ファイル 配布パッケージ@footnote{https://packaging.python.org/ja/latest/glossary/#term-Distribution-Package} のメタデータを発見するためのサポートを提供します。このメタデータ検索のデフォルトは @code{sys.path} ですが、その値をどのように解釈するかは、他のインポート機構が行う方法とは若干異なります。具体的には:


@itemize -

@item 
@code{importlib.metadata} は @code{sys.path} の @ref{192,,bytes} オブジェクトを受け入れません。

@item 
@code{importlib.metadata} は、インポート時には無視されますが、 @code{sys.path} 上の @ref{266,,pathlib.Path} オブジェクトを優先的に使用します。
@end itemize

@node Implementing Custom Providers,,Distribution Discovery,importlib metadata -- パッケージメタデータへのアクセス
@anchor{library/importlib metadata implementing-custom-providers}@anchor{4b62}
@subsubsection Implementing Custom Providers


@code{importlib.metadata} address two API surfaces, one for `consumers'
and another for `providers'. Most users are consumers, consuming
metadata provided by the packages. There are other use-cases, however,
where users wish to expose metadata through some other mechanism,
such as alongside a custom importer. Such a use case calls for a
`custom provider'.

Because Distribution Package@footnote{https://packaging.python.org/en/latest/glossary/#term-Distribution-Package} metadata
is not available through @ref{3e4,,sys.path} searches, or
package loaders directly,
the metadata for a distribution is found through import
system @ref{2446,,finders}. To find a distribution package's metadata,
@code{importlib.metadata} queries the list of @ref{127c,,meta path finders} on
@ref{f27,,sys.meta_path}.

The implementation has hooks integrated into the @code{PathFinder},
serving metadata for distribution packages found on the file system.

抽象クラス @ref{a6e,,importlib.abc.MetaPathFinder} はPythonの importシステムによってファインダーに期待されるインターフェイスを定義しています。 @code{importlib.metadata} はこのプロトコルを拡張し、 @ref{f27,,sys.meta_path} からファインダーにオプションの @code{find_distributions} を呼び出すことができるようにし、この拡張インターフェースを @code{DistributionFinder} 抽象基底クラスとして提示し、この抽象メソッドを定義しています:

@example
@@abc.abstractmethod
def find_distributions(context=DistributionFinder.Context()) -> Iterable[Distribution]:
    """Return an iterable of all Distribution instances capable of
    loading the metadata for packages for the indicated `@w{`}context`@w{`}.
    """
@end example

The @code{DistributionFinder.Context} object provides @code{.path} and @code{.name}
properties indicating the path to search and name to match and may
supply other relevant context sought by the consumer.

In practice, to support finding distribution package
metadata in locations other than the file system, subclass
@code{Distribution} and implement the abstract methods. Then from
a custom finder, return instances of this derived @code{Distribution} in the
@code{find_distributions()} method.

@menu
* 使用例: 使用例<49>. 

@end menu

@node 使用例<49>,,,Implementing Custom Providers
@anchor{library/importlib metadata example}@anchor{4b63}
@subsubsection 使用例


Imagine a custom finder that loads Python modules from a database:

@example
class DatabaseImporter(importlib.abc.MetaPathFinder):
    def __init__(self, db):
        self.db = db

    def find_spec(self, fullname, target=None) -> ModuleSpec:
        return self.db.spec_from_name(fullname)

sys.meta_path.append(DatabaseImporter(connect_db(...)))
@end example

That importer now presumably provides importable modules from a
database, but it provides no metadata or entry points. For this
custom importer to provide metadata, it would also need to implement
@code{DistributionFinder}:

@example
from importlib.metadata import DistributionFinder

class DatabaseImporter(DistributionFinder):
    ...

    def find_distributions(self, context=DistributionFinder.Context()):
        query = dict(name=context.name) if context.name else @{@}
        for dist_record in self.db.query_distributions(query):
            yield DatabaseDistribution(dist_record)
@end example

In this way, @code{query_distributions} would return records for
each distribution served by the database matching the query. For
example, if @code{requests-1.0} is in the database, @code{find_distributions}
would yield a @code{DatabaseDistribution} for @code{Context(name='requests')}
or @code{Context(name=None)}.

For the sake of simplicity, this example ignores @code{context.path}. The
@code{path} attribute defaults to @code{sys.path} and is the set of import paths to
be considered in the search. A @code{DatabaseImporter} could potentially function
without any concern for a search path. Assuming the importer does no
partitioning, the "path" would be irrelevant. In order to illustrate the
purpose of @code{path}, the example would need to illustrate a more complex
@code{DatabaseImporter} whose behavior varied depending on
@code{sys.path}/@code{PYTHONPATH}. In that case, the @code{find_distributions} should
honor the @code{context.path} and only yield @code{Distribution}s pertinent to that
path.

@code{DatabaseDistribution}, then, would look something like:

@example
class DatabaseDistribution(importlib.metadata.Distribution):
    def __init__(self, record):
        self.record = record

    def read_text(self, filename):
        """
        Read a file like "METADATA" for the current distribution.
        """
        if filename == "METADATA":
            return f"""Name: @{self.record.name@}
Version: @{self.record.version@}
"""
        if filename == "entry_points.txt":
            return "\n".join(
              f"""[@{ep.group@}]\n@{ep.name@}=@{ep.value@}"""
              for ep in self.record.entry_points)

    def locate_file(self, path):
        raise RuntimeError("This distribution has no file system")
@end example

This basic implementation should provide metadata and entry points for
packages served by the @code{DatabaseImporter}, assuming that the
@code{record} supplies suitable @code{.name}, @code{.version}, and
@code{.entry_points} attributes.

The @code{DatabaseDistribution} may also provide other metadata files, like
@code{RECORD} (required for @code{Distribution.files}) or override the
implementation of @code{Distribution.files}. See the source for more inspiration.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node sys path モジュール検索パスの初期化,,importlib metadata -- パッケージメタデータへのアクセス,モジュールのインポート
@anchor{library/sys_path_init doc}@anchor{4b64}@anchor{library/sys_path_init sys-path-init}@anchor{18dc}@anchor{library/sys_path_init the-initialization-of-the-sys-path-module-search-path}@anchor{4b65}@anchor{library/sys_path_init translation-repo}@anchor{4b66}
@subsection @code{sys.path} モジュール検索パスの初期化


モジュール検索パスは Python の開始時に初期化されます。このモジュール検索パスは、 @ref{3e4,,sys.path} でアクセス可能です。

The first entry in the module search path is the directory that contains the
input script, if there is one. Otherwise, the first entry is the current
directory, which is the case when executing the interactive shell, a @ref{1a8,,-c}
command, or @ref{23c,,-m} module.

The 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} environment variable is often used to add directories
to the search path. If this environment variable is found then the contents are
added to the module search path.

@cartouche
@quotation 注釈 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} will affect all installed Python versions/environments.
Be wary of setting this in your shell profile or global environment variables.
The @ref{cc,,site} module offers more nuanced techniques as mentioned below.
@end quotation
@end cartouche

The next items added are the directories containing standard Python modules as
well as any @ref{2251,,extension module}s that these modules depend on. Extension
modules are @code{.pyd} files on Windows and @code{.so} files on other platforms. The
directory with the platform-independent Python modules is called @code{prefix}.
The directory with the extension modules is called @code{exec_prefix}.

The 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable may be used to set the @code{prefix}
and @code{exec_prefix} locations. Otherwise these directories are found by using
the Python executable as a starting point and then looking for various 'landmark'
files and directories. Note that any symbolic links are followed so the real
Python executable location is used as the search starting point. The Python
executable location is called @code{home}.

Once @code{home} is determined, the @code{prefix} directory is found by first looking
for @code{python`majorversion'`minorversion'.zip} (@code{python311.zip}). On Windows
the zip archive is searched for in @code{home} and on Unix the archive is expected
to be in @code{lib}. Note that the expected zip archive location is added to the
module search path even if the archive does not exist. If no archive was found,
Python on Windows will continue the search for @code{prefix} by looking for @code{Lib\os.py}.
Python on Unix will look for @code{lib/python`majorversion'.`minorversion'/os.py}
(@code{lib/python3.11/os.py}). On Windows @code{prefix} and @code{exec_prefix} are the same,
however on other platforms @code{lib/python`majorversion'.`minorversion'/lib-dynload}
(@code{lib/python3.11/lib-dynload}) is searched for and used as an anchor for
@code{exec_prefix}. On some platforms @code{lib} may be @code{lib64} or another value,
see @ref{b32,,sys.platlibdir} and 
@geindex PYTHONPLATLIBDIR
@geindex 環境変数; PYTHONPLATLIBDIR
@ref{1d23,,PYTHONPLATLIBDIR}.

Once found, @code{prefix} and @code{exec_prefix} are available at
@ref{3e6,,sys.base_prefix} and @ref{3ea,,sys.base_exec_prefix} respectively.

If 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} is not set, and a @code{pyvenv.cfg} file is found alongside
the main executable, or in its parent directory, @ref{3e7,,sys.prefix} and
@ref{3eb,,sys.exec_prefix} get set to the directory containing @code{pyvenv.cfg},
otherwise they are set to the same value as @ref{3e6,,sys.base_prefix} and
@ref{3ea,,sys.base_exec_prefix}, respectively.
This is used by @ref{48b3,,Virtual Environments}.

Finally, the @ref{cc,,site} module is processed and @code{site-packages} directories
are added to the module search path. A common way to customize the search path is
to create @ref{cd,,sitecustomize} or @ref{114,,usercustomize} modules as described in
the @ref{cc,,site} module documentation.

@cartouche
@quotation 注釈 
Certain command line options may further affect path calculations.
See @ref{b56,,-E}, @ref{b57,,-I}, @ref{15a6,,-s} and @ref{13c0,,-S} for further details.
@end quotation
@end cartouche


バージョン 3.14 で変更: @ref{3e7,,sys.prefix} and @ref{3eb,,sys.exec_prefix} are now set to the
@code{pyvenv.cfg} directory during the path initialization. This was previously
done by @ref{cc,,site}, therefore affected by @ref{13c0,,-S}.


@menu
* Virtual Environments:: 
* _pth files:: 
* 埋め込みの Python:: 

@end menu

@node Virtual Environments,_pth files,,sys path モジュール検索パスの初期化
@anchor{library/sys_path_init sys-path-init-virtual-environments}@anchor{48b3}@anchor{library/sys_path_init virtual-environments}@anchor{4b67}
@subsubsection Virtual Environments


Virtual environments place a @code{pyvenv.cfg} file in their prefix, which causes
@ref{3e7,,sys.prefix} and @ref{3eb,,sys.exec_prefix} to point to them, instead of the
base installation.

The @code{prefix} and @code{exec_prefix} values of the base installation are available
at @ref{3e6,,sys.base_prefix} and @ref{3ea,,sys.base_exec_prefix}.

As well as being used as a marker to identify virtual environments,
@code{pyvenv.cfg} may also be used to configure the @ref{cc,,site} initialization.
Please refer to @ref{cc,,site}'s
@ref{48b4,,virtual environments documentation}.

@cartouche
@quotation 注釈 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} overrides the @code{pyvenv.cfg} detection.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
There are other ways how "virtual environments" could be implemented, this
documentation refers implementations based on the @code{pyvenv.cfg} mechanism,
such as @ref{117,,venv}. Most virtual environment implementations follow the
model set by @ref{117,,venv}, but there may be exotic implementations that
diverge from it.
@end quotation
@end cartouche

@node _pth files,埋め込みの Python,Virtual Environments,sys path モジュール検索パスの初期化
@anchor{library/sys_path_init pth-files}@anchor{4b68}
@subsubsection _pth files


To completely override @ref{3e4,,sys.path} create a @code{._pth} file with the same
name as the shared library or executable (@code{python._pth} or @code{python311._pth}).
The shared library path is always known on Windows, however it may not be
available on other platforms. In the @code{._pth} file specify one line for each path
to add to @ref{3e4,,sys.path}. The file based on the shared library name overrides
the one based on the executable, which allows paths to be restricted for any
program loading the runtime if desired.

ファイルが存在したときは、全てのレジストリと環境変数は無視され、隔離モードになり、そのファイルに @code{import site} と指定していない限りは @ref{cc,,site} がインポートできなくなります。
空行と @code{#} で始まる行は無視されます。
それぞれのパスはファイルの場所を指す絶対パスあるいは相対パスです。
@code{site} 以外のインポート文は許可されておらず、任意のコードも書けません。

@code{import site} を指定したときは、(アンダースコアが前に付かない) @code{.pth} ファイルは @ref{cc,,site} モジュールにより通常通り処理されることに注意してください。

@node 埋め込みの Python,,_pth files,sys path モジュール検索パスの初期化
@anchor{library/sys_path_init embedded-python}@anchor{4b69}
@subsubsection 埋め込みの Python


Python が他のアプリケーションに埋め込まれている場合は、 @ref{3f6,,Py_InitializeFromConfig()} と @ref{3f7,,PyConfig} 構造体が Python の初期化に使用可能です。パス固有の詳細は、 @ref{aaa,,Python Path Configuration} で説明されています。


@subsubheading 参考



@itemize *

@item 
Windows の詳細についてのメモは、 @ref{e1a,,モジュールの検索} を参照。

@item 
Unix の詳細は、 @ref{2144,,Unix プラットフォームで Python を使う} を参照。
@end itemize


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python言語サービス,MS Windows 固有のサービス,モジュールのインポート,Python 標準ライブラリ
@anchor{library/language doc}@anchor{4b6a}@anchor{library/language language}@anchor{4b6b}@anchor{library/language python-language-services}@anchor{4b6c}@anchor{library/language translation-repo}@anchor{4b6d}
@section Python言語サービス


PythonにはPython言語を使って作業するときに役に立つモジュールがたくさん提供されています。これらのモジュールはトークンの切り出し、パース、構文解析、バイトコードのディスアセンブリおよびその他のさまざまな機能をサポートしています。

これらのモジュールには、次のものが含まれています:

@menu
* ast: ast --- Abstract syntax trees. Abstract syntax trees
* symtable: symtable --- コンパイラーの記号表へのアクセス. コンパイラーの記号表へのアクセス
* token: token --- Python 解析木で使われる定数. Python 解析木で使われる定数
* keyword: keyword --- Python キーワードのテスト. Python キーワードのテスト
* tokenize: tokenize --- Python ソース用のトークナイザー. Python ソース用のトークナイザー
* tabnanny: tabnanny --- あいまいなインデントの検出. あいまいなインデントの検出
* pyclbr: pyclbr --- Python モジュールブラウザーサポート. Python モジュールブラウザーサポート
* py_compile: py_compile --- Python ソースファイルをコンパイルする. Python ソースファイルをコンパイルする
* compileall: compileall --- Python ライブラリをバイトコンパイルする. Python ライブラリをバイトコンパイルする
* dis: dis --- Python バイトコードの逆アセンブラー. Python バイトコードの逆アセンブラー
* pickletools: pickletools --- pickle 開発者用のツール群. pickle 開発者用のツール群

@end menu

@node ast --- Abstract syntax trees,symtable --- コンパイラーの記号表へのアクセス,,Python言語サービス
@anchor{library/ast doc}@anchor{4b6e}@anchor{library/ast ast-abstract-syntax-trees}@anchor{4b6f}@anchor{library/ast module-ast}@anchor{9}
@subsection @code{ast} --- Abstract syntax trees


@geindex module; ast

@c import ast

`ソースコード:' Lib/ast.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/ast.py}


__________________________________________________________________


The @code{ast} module helps Python applications to process trees of the Python
abstract syntax grammar.  The abstract syntax itself might change with each
Python release; this module helps to find out programmatically what the current
grammar looks like.

抽象構文木を作成するには、 @ref{4b70,,ast.PyCF_ONLY_AST} を組み込み関数 @ref{4b1,,compile()} のフラグとして渡すか、あるいはこのモジュールで提供されているヘルパー関数 @ref{1c2,,parse()} を使います。その結果は、 @ref{4c3,,ast.AST} を継承したクラスのオブジェクトのツリーとなります。抽象構文木は組み込み関数 @ref{4b1,,compile()} を使って Python コード・オブジェクトにコンパイルすることができます。

@menu
* Abstract grammar:: 
* Node クラス:: 
* ast helpers:: 
* Compiler flags: Compiler flags<2>. 
* コマンドラインでの使用: コマンドラインでの使用<8>. 

@end menu

@node Abstract grammar,Node クラス,,ast --- Abstract syntax trees
@anchor{library/ast abstract-grammar}@anchor{4b71}@anchor{library/ast id1}@anchor{4b72}
@subsubsection Abstract grammar


抽象文法は、現在次のように定義されています:

@example
-- ASDL's 4 builtin types are:
-- identifier, int, string, constant

module Python
@{
    mod = Module(stmt* body, type_ignore* type_ignores)
        | Interactive(stmt* body)
        | Expression(expr body)
        | FunctionType(expr* argtypes, expr returns)

    stmt = FunctionDef(identifier name, arguments args,
                       stmt* body, expr* decorator_list, expr? returns,
                       string? type_comment, type_param* type_params)
          | AsyncFunctionDef(identifier name, arguments args,
                             stmt* body, expr* decorator_list, expr? returns,
                             string? type_comment, type_param* type_params)

          | ClassDef(identifier name,
             expr* bases,
             keyword* keywords,
             stmt* body,
             expr* decorator_list,
             type_param* type_params)
          | Return(expr? value)

          | Delete(expr* targets)
          | Assign(expr* targets, expr value, string? type_comment)
          | TypeAlias(expr name, type_param* type_params, expr value)
          | 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)

          | Match(expr subject, match_case* cases)

          | Raise(expr? exc, expr? cause)
          | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
          | TryStar(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)
         | Interpolation(expr value, constant str, int conversion, expr? format_spec)
         | JoinedStr(expr* values)
         | TemplateStr(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)
             attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    withitem = (expr context_expr, expr? optional_vars)

    match_case = (pattern pattern, expr? guard, stmt* body)

    pattern = MatchValue(expr value)
            | MatchSingleton(constant value)
            | MatchSequence(pattern* patterns)
            | MatchMapping(expr* keys, pattern* patterns, identifier? rest)
            | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)

            | MatchStar(identifier? name)
            -- The optional "rest" MatchMapping parameter handles capturing extra mapping keys

            | MatchAs(pattern? pattern, identifier? name)
            | MatchOr(pattern* patterns)

             attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)

    type_ignore = TypeIgnore(int lineno, string tag)

    type_param = TypeVar(identifier name, expr? bound, expr? default_value)
               | ParamSpec(identifier name, expr? default_value)
               | TypeVarTuple(identifier name, expr? default_value)
               attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
@}
@end example

@node Node クラス,ast helpers,Abstract grammar,ast --- Abstract syntax trees
@anchor{library/ast node-classes}@anchor{4b73}
@subsubsection Node クラス


@geindex AST (ast のクラス)
@anchor{library/ast ast AST}@anchor{4c3}
@deffn {クラス} ast.AST

This is the base of all AST node classes.  The actual node classes are
derived from the @code{Parser/Python.asdl} file, which is reproduced
@ref{4b71,,above}.  They are defined in the @code{_ast} C
module and re-exported in @code{ast}.

抽象文法の左辺のシンボル一つずつにそれぞれ一つのクラスがあります (たとえば @code{ast.stmt} や @code{ast.expr})。それに加えて、右辺のコンストラクタ一つずつにそれぞれ一つのクラスがあり、これらのクラスは左辺のツリーのクラスを継承しています。たとえば、 @ref{1db2,,ast.BinOp} は @code{ast.expr} から継承しています。代替を伴った生成規則 (production rules with alternatives) (別名 "sums") の場合、左辺は抽象クラスとなり、特定のコンストラクタ・ノードのインスタンスのみが作成されます。

@geindex ? (クエスチョンマーク);in AST grammar

@geindex * (アスタリスク);in AST grammar

@geindex _fields (ast.AST の属性)
@anchor{library/ast ast AST _fields}@anchor{17d7}
@deffn {の属性} _fields

各具象クラスは属性 @code{_fields} を持っており、すべての子ノードの名前をそこに保持しています。

具象クラスのインスタンスは、各子ノードに対してそれぞれひとつの属性を持っています。この属性は、文法で定義された型となります。たとえば @ref{1db2,,ast.BinOp} のインスタンスは @code{left} という属性を持っており、その型は @code{ast.expr} です。

これらの属性が、文法上 (クエスチョンマークを用いて) オプションであるとマークされている場合は、その値が @code{None} となることもあります。属性が0個以上の複数の値をとりうる場合 (アスタリスクでマークされている場合) は、値は Python のリストで表されます。全ての属性は AST を @ref{4b1,,compile()} でコンパイルする際には存在しなければならず、そして妥当な値でなければなりません。
@end deffn

@geindex _field_types (ast.AST の属性)
@anchor{library/ast ast AST _field_types}@anchor{4c4}
@deffn {の属性} _field_types

The @code{_field_types} attribute on each concrete class is a dictionary
mapping field names (as also listed in @ref{17d7,,_fields}) to their types.

@example
>>> ast.TypeVar._field_types
@{'name': <class 'str'>, 'bound': ast.expr | None, 'default_value': ast.expr | None@}
@end example


Added in version 3.13.

@end deffn

@geindex lineno (ast.AST の属性)
@geindex col_offset (ast.AST の属性)
@geindex end_lineno (ast.AST の属性)
@geindex end_col_offset (ast.AST の属性)
@anchor{library/ast ast AST lineno}@anchor{4b74}
@deffn {の属性} lineno
@anchor{library/ast ast AST col_offset}@anchor{4b75}
@deffnx {の属性} col_offset
@anchor{library/ast ast AST end_lineno}@anchor{4b76}
@deffnx {の属性} end_lineno
@anchor{library/ast ast AST end_col_offset}@anchor{4b77}
@deffnx {の属性} end_col_offset

@code{ast.expr} や @code{ast.stmt} のサブクラスのインスタンスは @ref{4b74,,lineno}, @ref{4b75,,col_offset}, @ref{4b76,,end_lineno}, および @ref{4b77,,end_col_offset} 属性を持ちます。 @ref{4b74,,lineno} と @ref{4b76,,end_lineno} はソーステキストの範囲を最初と最後の行番号で表し (1 から数え始めるので、最初の行の行番号は 1 となります)、 @ref{4b75,,col_offset} と @ref{4b77,,end_col_offset} はノードが生成した最初と最後のトークンの UTF-8 バイトオフセットです。 UTF-8 オフセットはパーサが内部で使用するので記録されます。

コンパイラは終了位置を必要としないことに注意してください。このため終了位置は省略可能です。終了位置を示すオフセットは最後のシンボルの `後の位置' になります。例えば一行で書かれた式のソースコードのセグメントは @code{source_line[node.col_offset : node.end_col_offset]} により取得できます。
@end deffn

クラス @code{ast.T} のコンストラクタは引数を次のように解析します:


@itemize *

@item 
位置引数があるとすれば、 @code{T._fields} にあるのと同じだけの個数が無ければなりません。これらの引数はそこにある名前を持った属性として割り当てられます。

@item 
キーワード引数があるとすれば、それらはその名前の属性にその値を割り当てられます。
@end itemize

たとえば、 @ref{4a7e,,ast.UnaryOp} ノードを生成して属性を埋めるには、次のようにすることができます

@example
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
                   lineno=0, col_offset=0)
@end example

If a field that is optional in the grammar is omitted from the constructor,
it defaults to @code{None}. If a list field is omitted, it defaults to the empty
list. If a field of type @code{ast.expr_context} is omitted, it defaults to
@ref{4c2,,Load()}. If any other field is omitted, a @ref{1a3,,DeprecationWarning} is raised
and the AST node will not have this field. In Python 3.15, this condition will
raise an error.
@end deffn


バージョン 3.8 で変更: @ref{2ef,,ast.Constant} が全ての定数に使われるようになりました。



バージョン 3.9 で変更: 単純なインデックスはその値で表現され、幅を持つスライスはタプルで表現されます。



バージョン 3.14 で変更: The @ref{82f,,__repr__()} output of @ref{4c3,,AST} nodes includes
the values of the node fields.



Deprecated since version 3.8, removed in version 3.14: Previous versions of Python provided the AST classes @code{ast.Num},
@code{ast.Str}, @code{ast.Bytes}, @code{ast.NameConstant} and
@code{ast.Ellipsis}, which were deprecated in Python 3.8. These classes
were removed in Python 3.14, and their functionality has been replaced with
@ref{2ef,,ast.Constant}.



バージョン 3.9 で非推奨: Old classes @code{ast.Index} and @code{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.



Deprecated since version 3.13, will be removed in version 3.15: Previous versions of Python allowed the creation of AST nodes that were missing
required fields. Similarly, AST node constructors allowed arbitrary keyword
arguments that were set as attributes of the AST node, even if they did not
match any of the fields of the AST node. This behavior is deprecated and will
be removed in Python 3.15.


@cartouche
@quotation 注釈 
ここに示されている特定のノードクラスについての記述は、素晴らしい Green Tree Snakes@footnote{https://greentreesnakes.readthedocs.io/en/latest/} プロジェクトとそのすべての貢献者の成果物をもとにしています。
@end quotation
@end cartouche

@menu
* Root nodes:: 
* リテラル: リテラル<3>. 
* 変数:: 
* 式 (expression): 式 expression<2>. 
* 文 (Statements): 文 Statements. 
* 制御フロー:: 
* Pattern matching:: 
* Type annotations:: 
* Type parameters:: 
* 関数およびクラス定義:: 
* async と await:: 

@end menu

@node Root nodes,リテラル<3>,,Node クラス
@anchor{library/ast ast-root-nodes}@anchor{4b78}@anchor{library/ast root-nodes}@anchor{4b79}
@subsubsection Root nodes


@geindex Module (ast のクラス)
@anchor{library/ast ast Module}@anchor{4b7a}
@deffn {クラス} ast.Module (body, type_ignores)

A Python module, as with @ref{259e,,file input}.
Node type generated by @ref{1c2,,ast.parse()} in the default @code{"exec"} `mode'.

@code{body} is a @ref{24d,,list} of the module's @ref{4b7b,,文 (Statements)}.

@code{type_ignores} is a @ref{24d,,list} of the module's type ignore comments;
see @ref{1c2,,ast.parse()} for more details.

@example
>>> print(ast.dump(ast.parse('x = 1'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='x', ctx=Store())],
            value=Constant(value=1))])
@end example
@end deffn

@geindex Expression (ast のクラス)
@anchor{library/ast ast Expression}@anchor{4b7c}
@deffn {クラス} ast.Expression (body)

A single Python @ref{25a4,,expression input}.
Node type generated by @ref{1c2,,ast.parse()} when `mode' is @code{"eval"}.

@code{body} is a single node,
one of the @ref{4b7d,,expression types}.

@example
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
    body=Constant(value=123))
@end example
@end deffn

@geindex Interactive (ast のクラス)
@anchor{library/ast ast Interactive}@anchor{1879}
@deffn {クラス} ast.Interactive (body)

A single @ref{25a1,,interactive input}, like in @ref{494,,対話モード}.
Node type generated by @ref{1c2,,ast.parse()} when `mode' is @code{"single"}.

@code{body} is a @ref{24d,,list} of @ref{4b7b,,statement nodes}.

@example
>>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))
Interactive(
    body=[
        Assign(
            targets=[
                Name(id='x', ctx=Store())],
            value=Constant(value=1)),
        Assign(
            targets=[
                Name(id='y', ctx=Store())],
            value=Constant(value=2))])
@end example
@end deffn

@geindex FunctionType (ast のクラス)
@anchor{library/ast ast FunctionType}@anchor{4b7e}
@deffn {クラス} ast.FunctionType (argtypes, returns)

A representation of an old-style type comments for functions,
as Python versions prior to 3.5 didn't support 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} annotations.
Node type generated by @ref{1c2,,ast.parse()} when `mode' is @code{"func_type"}.

Such type comments would look like this:

@example
def sum_two_number(a, b):
    # type: (int, int) -> int
    return a + b
@end example

@code{argtypes} is a @ref{24d,,list} of @ref{4b7d,,expression nodes}.

@code{returns} is a single @ref{4b7d,,expression node}.

@example
>>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4))
FunctionType(
    argtypes=[
        Name(id='int', ctx=Load()),
        Name(id='str', ctx=Load())],
    returns=Subscript(
        value=Name(id='List', ctx=Load()),
        slice=Name(id='int', ctx=Load()),
        ctx=Load()))
@end example


Added in version 3.8.

@end deffn

@node リテラル<3>,変数,Root nodes,Node クラス
@anchor{library/ast literals}@anchor{4b7f}
@subsubsection リテラル


@geindex Constant (ast のクラス)
@anchor{library/ast ast Constant}@anchor{2ef}
@deffn {クラス} ast.Constant (value)

A constant value. The @code{value} attribute of the @code{Constant} literal contains the
Python object it represents. The values represented can be instances of @ref{169,,str},
@ref{192,,bytes}, @ref{19b,,int}, @ref{196,,float}, @ref{197,,complex}, and @ref{3c3,,bool},
and the constants @ref{885,,None} and @ref{2328,,Ellipsis}.

@example
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
    body=Constant(value=123))
@end example
@end deffn

@geindex FormattedValue (ast のクラス)
@anchor{library/ast ast FormattedValue}@anchor{4a96}
@deffn {クラス} ast.FormattedValue (value, conversion, format_spec)

このノードは f-string における単一の書式指定置換フィールドを表現します。文字列が単一の置換フィールドしか持たず、他に何も含まない場合は、ノードは単独で存在できます。そうでない場合は  @ref{1a5c,,JoinedStr} の一部としてあらわれます。


@itemize *

@item 
@code{value} は式ツリーのノードのいずれか (リテラル、変数、関数呼び出しなど) です。

@item 
@code{conversion} は整数です:


@itemize *

@item 
-1: 書式指定なし

@item 
97 (@code{ord('a')}): @code{!a} @ref{15ff,,ASCII} formatting

@item 
114 (@code{ord('r')}): @code{!r} @ref{1c1,,repr()} formatting

@item 
115 (@code{ord('s')}): @code{!s} @ref{169,,string} formatting
@end itemize

@item 
@code{format_spec} は値の書式指定を表現する @ref{1a5c,,JoinedStr} ノード、もしくは書式指定がない場合は @code{None} です。 @code{conversion} と @code{format_spec} を同時に設定することができます。
@end itemize
@end deffn

@geindex JoinedStr (ast のクラス)
@anchor{library/ast ast JoinedStr}@anchor{1a5c}
@deffn {クラス} ast.JoinedStr (values)

@ref{4a96,,FormattedValue} ノードと @ref{2ef,,Constant} ノードの集まりからなる f-string です。

@example
>>> print(ast.dump(ast.parse('f"sin(@{a@}) is @{sin(a):.3@}"', mode='eval'), indent=4))
Expression(
    body=JoinedStr(
        values=[
            Constant(value='sin('),
            FormattedValue(
                value=Name(id='a', ctx=Load()),
                conversion=-1),
            Constant(value=') is '),
            FormattedValue(
                value=Call(
                    func=Name(id='sin', ctx=Load()),
                    args=[
                        Name(id='a', ctx=Load())]),
                conversion=-1,
                format_spec=JoinedStr(
                    values=[
                        Constant(value='.3')]))]))
@end example
@end deffn

@geindex TemplateStr (ast のクラス)
@anchor{library/ast ast TemplateStr}@anchor{4b80}
@deffn {クラス} ast.TemplateStr (values, /)


Added in version 3.14.


Node representing a template string literal, comprising a series of
@ref{17b5,,Interpolation} and @ref{2ef,,Constant} nodes.
These nodes may be any order, and do not need to be interleaved.

@example
>>> expr = ast.parse('t"@{name@} finished @{place:ordinal@}"', mode='eval')
>>> print(ast.dump(expr, indent=4))
Expression(
    body=TemplateStr(
        values=[
            Interpolation(
                value=Name(id='name', ctx=Load()),
                str='name',
                conversion=-1),
            Constant(value=' finished '),
            Interpolation(
                value=Name(id='place', ctx=Load()),
                str='place',
                conversion=-1,
                format_spec=JoinedStr(
                    values=[
                        Constant(value='ordinal')]))]))
@end example
@end deffn

@geindex Interpolation (ast のクラス)
@anchor{library/ast ast Interpolation}@anchor{17b5}
@deffn {クラス} ast.Interpolation (value, str, conversion, format_spec=None)


Added in version 3.14.


Node representing a single interpolation field in a template string literal.


@itemize *

@item 
@code{value} is any expression node (such as a literal, a variable, or a
function call).
This has the same meaning as @code{FormattedValue.value}.

@item 
@code{str} is a constant containing the text of the interpolation expression.

If @code{str} is set to @code{None}, then @code{value} is used to generate code
when calling @ref{ae2,,ast.unparse()}. This no longer guarantees that the
generated code is identical to the original and is intended for code
generation.

@item 
@code{conversion} は整数です:


@itemize *

@item 
-1: no conversion

@item 
97 (@code{ord('a')}): @code{!a} @ref{15ff,,ASCII} conversion

@item 
114 (@code{ord('r')}): @code{!r} @ref{1c1,,repr()} conversion

@item 
115 (@code{ord('s')}): @code{!s} @ref{169,,string} conversion
@end itemize

This has the same meaning as @code{FormattedValue.conversion}.

@item 
@code{format_spec} is a @ref{1a5c,,JoinedStr} node representing the formatting
of the value, or @code{None} if no format was specified. Both
@code{conversion} and @code{format_spec} can be set at the same time.
This has the same meaning as @code{FormattedValue.format_spec}.
@end itemize
@end deffn

@geindex List (ast のクラス)
@geindex Tuple (ast のクラス)
@anchor{library/ast ast List}@anchor{4a93}
@deffn {クラス} ast.List (elts, ctx)
@anchor{library/ast ast Tuple}@anchor{4a94}
@deffnx {クラス} ast.Tuple (elts, ctx)

リストまたはタプルをあらわします。 @code{elts} は内包する要素を表現するノードのリストを保持します。 @code{ctx} はコンテナが代入のターゲットである場合 (たとえば @code{(x,y)=something} のような場合) は @ref{4b81,,Store} であり、そうでない場合は @ref{4c2,,Load} です。

@example
>>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
Expression(
    body=List(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))
>>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
Expression(
    body=Tuple(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))
@end example
@end deffn

@geindex Set (ast のクラス)
@anchor{library/ast ast Set}@anchor{4a83}
@deffn {クラス} ast.Set (elts)

集合 (set) をあらわします。 @code{elts} は集合の各要素を表現するノードのリストを保持します。

@example
>>> print(ast.dump(ast.parse('@{1, 2, 3@}', mode='eval'), indent=4))
Expression(
    body=Set(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)]))
@end example
@end deffn

@geindex Dict (ast のクラス)
@anchor{library/ast ast Dict}@anchor{1d49}
@deffn {クラス} ast.Dict (keys, values)

辞書をあらわします。 @code{keys} と @code{values} はそれぞれキーと値のノードのリスト を順序が一致した形で (それぞれ @code{dictionary.keys()} と @code{dictionary.values()} を呼び出したときに返される順序で) 保持します。

辞書リテラルを使って辞書を展開した場合、展開された式ツリーにおいて辞書は @code{values} リストに入り、 @code{keys} の対応する位置には @code{None} が入ります。

@example
>>> print(ast.dump(ast.parse('@{"a":1, **d@}', mode='eval'), indent=4))
Expression(
    body=Dict(
        keys=[
            Constant(value='a'),
            None],
        values=[
            Constant(value=1),
            Name(id='d', ctx=Load())]))
@end example
@end deffn

@node 変数,式 expression<2>,リテラル<3>,Node クラス
@anchor{library/ast variables}@anchor{4b82}
@subsubsection 変数


@geindex Name (ast のクラス)
@anchor{library/ast ast Name}@anchor{1d22}
@deffn {クラス} ast.Name (id, ctx)

変数名をあらわします。 @code{id} は変数名を文字列で保持し、 @code{ctx} は以下に示す型のいずれかです。
@end deffn

@geindex Load (ast のクラス)
@geindex Store (ast のクラス)
@geindex Del (ast のクラス)
@anchor{library/ast ast Load}@anchor{4c2}
@deffn {クラス} ast.Load
@anchor{library/ast ast Store}@anchor{4b81}
@deffnx {クラス} ast.Store
@anchor{library/ast ast Del}@anchor{4b83}
@deffnx {クラス} ast.Del

変数の参照は変数の値をロードするか、新しい値を割り当てるか、または値を削除するために使うことができます。変数の参照はこれら3つの場合を区別するためのコンテキストによって与えられます。

@example
>>> print(ast.dump(ast.parse('a'), indent=4))
Module(
    body=[
        Expr(
            value=Name(id='a', ctx=Load()))])

>>> print(ast.dump(ast.parse('a = 1'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='a', ctx=Store())],
            value=Constant(value=1))])

>>> print(ast.dump(ast.parse('del a'), indent=4))
Module(
    body=[
        Delete(
            targets=[
                Name(id='a', ctx=Del())])])
@end example
@end deffn

@geindex Starred (ast のクラス)
@anchor{library/ast ast Starred}@anchor{4a92}
@deffn {クラス} ast.Starred (value, ctx)

@code{*var} 形式の変数の参照をあらわします。 @code{value} は変数、典型的には @ref{1d22,,Name} ノード、を保持します。この型は @code{*args} を伴う関数呼び出しノード @ref{4a8f,,Call} を構築する際に使用します。

@example
>>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Tuple(
                    elts=[
                        Name(id='a', ctx=Store()),
                        Starred(
                            value=Name(id='b', ctx=Store()),
                            ctx=Store())],
                    ctx=Store())],
            value=Name(id='it', ctx=Load()))])
@end example
@end deffn

@node 式 expression<2>,文 Statements,変数,Node クラス
@anchor{library/ast ast-expressions}@anchor{4b7d}@anchor{library/ast expressions}@anchor{4b84}
@subsubsection 式 (expression)


@geindex Expr (ast のクラス)
@anchor{library/ast ast Expr}@anchor{4b85}
@deffn {クラス} ast.Expr (value)

関数呼び出しのような式がそれ自身で文となり、戻り値が使われないかまたは保存されないとき、その式はこのコンテナでラップされます。 @code{value} はこの節で説明する他のノード、 @ref{2ef,,Constant} ノード、 @ref{1d22,,Name} ノード、 @ref{4a99,,Lambda} ノード @ref{4aa0,,Yield} ノードまたは @ref{4aa1,,YieldFrom} ノードのいずれかを保持します。

@example
>>> print(ast.dump(ast.parse('-a'), indent=4))
Module(
    body=[
        Expr(
            value=UnaryOp(
                op=USub(),
                operand=Name(id='a', ctx=Load())))])
@end example
@end deffn

@geindex UnaryOp (ast のクラス)
@anchor{library/ast ast UnaryOp}@anchor{4a7e}
@deffn {クラス} ast.UnaryOp (op, operand)

単項演算をあらわします。 @code{op} は演算子で、 @code{operand} は任意の式ツリーのノードです。
@end deffn

@geindex UAdd (ast のクラス)
@geindex USub (ast のクラス)
@geindex Not (ast のクラス)
@geindex Invert (ast のクラス)
@anchor{library/ast ast UAdd}@anchor{4a80}
@deffn {クラス} ast.UAdd
@anchor{library/ast ast USub}@anchor{4a81}
@deffnx {クラス} ast.USub
@anchor{library/ast ast Not}@anchor{4a82}
@deffnx {クラス} ast.Not
@anchor{library/ast ast Invert}@anchor{4a7f}
@deffnx {クラス} ast.Invert

単項演算の演算子をあらわします。 @ref{4a82,,Not} は論理否定キーワード @code{not} であり、 @ref{4a7f,,Invert} はビット反転演算子 @code{~} です。

@example
>>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
    body=UnaryOp(
        op=Not(),
        operand=Name(id='x', ctx=Load())))
@end example
@end deffn

@geindex BinOp (ast のクラス)
@anchor{library/ast ast BinOp}@anchor{1db2}
@deffn {クラス} ast.BinOp (left, op, right)

(加算や減算のような) 二項演算をあらわします。 @code{op} は演算子、 @code{left} と @code{right} は任意の式ツリーのノードです。

@example
>>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
Expression(
    body=BinOp(
        left=Name(id='x', ctx=Load()),
        op=Add(),
        right=Name(id='y', ctx=Load())))
@end example
@end deffn

@geindex Add (ast のクラス)
@geindex Sub (ast のクラス)
@geindex Mult (ast のクラス)
@geindex Div (ast のクラス)
@geindex FloorDiv (ast のクラス)
@geindex Mod (ast のクラス)
@geindex Pow (ast のクラス)
@geindex LShift (ast のクラス)
@geindex RShift (ast のクラス)
@geindex BitOr (ast のクラス)
@geindex BitXor (ast のクラス)
@geindex BitAnd (ast のクラス)
@geindex MatMult (ast のクラス)
@anchor{library/ast ast Add}@anchor{4b86}
@deffn {クラス} ast.Add
@anchor{library/ast ast Sub}@anchor{4b87}
@deffnx {クラス} ast.Sub
@anchor{library/ast ast Mult}@anchor{4b88}
@deffnx {クラス} ast.Mult
@anchor{library/ast ast Div}@anchor{4b89}
@deffnx {クラス} ast.Div
@anchor{library/ast ast FloorDiv}@anchor{4b8a}
@deffnx {クラス} ast.FloorDiv
@anchor{library/ast ast Mod}@anchor{4b8b}
@deffnx {クラス} ast.Mod
@anchor{library/ast ast Pow}@anchor{4b8c}
@deffnx {クラス} ast.Pow
@anchor{library/ast ast LShift}@anchor{4b8d}
@deffnx {クラス} ast.LShift
@anchor{library/ast ast RShift}@anchor{4b8e}
@deffnx {クラス} ast.RShift
@anchor{library/ast ast BitOr}@anchor{4b8f}
@deffnx {クラス} ast.BitOr
@anchor{library/ast ast BitXor}@anchor{4b90}
@deffnx {クラス} ast.BitXor
@anchor{library/ast ast BitAnd}@anchor{4b91}
@deffnx {クラス} ast.BitAnd
@anchor{library/ast ast MatMult}@anchor{4b92}
@deffnx {クラス} ast.MatMult

二項演算の演算子をあらわします。
@end deffn

@geindex BoolOp (ast のクラス)
@anchor{library/ast ast BoolOp}@anchor{4a97}
@deffn {クラス} ast.BoolOp (op, values)

'or' や 'and' のような論理演算をあらわします。 @code{op} は @ref{4b93,,Or} または @ref{4b94,,And} です。 @code{values} は必要な値のリストです。 @code{a or b or c} のように同じ演算子を使う連続した演算は、複数の値を持った単一のノードとして表現されます。

@code{not} は単項演算 @ref{4a7e,,UnaryOp} のため、ここには含まれません。

@example
>>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
Expression(
    body=BoolOp(
        op=Or(),
        values=[
            Name(id='x', ctx=Load()),
            Name(id='y', ctx=Load())]))
@end example
@end deffn

@geindex And (ast のクラス)
@geindex Or (ast のクラス)
@anchor{library/ast ast And}@anchor{4b94}
@deffn {クラス} ast.And
@anchor{library/ast ast Or}@anchor{4b93}
@deffnx {クラス} ast.Or

論理演算の演算子をあらわします。
@end deffn

@geindex Compare (ast のクラス)
@anchor{library/ast ast Compare}@anchor{4a84}
@deffn {クラス} ast.Compare (left, ops, comparators)

2つ以上の値の比較をあらわします。 @code{left} 比較の中の最初の値、@code{ops} は演算子のリスト、 @code{comparators} は2つ目以降の値のリストです。

@example
>>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))
Expression(
    body=Compare(
        left=Constant(value=1),
        ops=[
            LtE(),
            Lt()],
        comparators=[
            Name(id='a', ctx=Load()),
            Constant(value=10)]))
@end example
@end deffn

@geindex Eq (ast のクラス)
@geindex NotEq (ast のクラス)
@geindex Lt (ast のクラス)
@geindex LtE (ast のクラス)
@geindex Gt (ast のクラス)
@geindex GtE (ast のクラス)
@geindex Is (ast のクラス)
@geindex IsNot (ast のクラス)
@geindex In (ast のクラス)
@geindex NotIn (ast のクラス)
@anchor{library/ast ast Eq}@anchor{4a85}
@deffn {クラス} ast.Eq
@anchor{library/ast ast NotEq}@anchor{4a86}
@deffnx {クラス} ast.NotEq
@anchor{library/ast ast Lt}@anchor{4a87}
@deffnx {クラス} ast.Lt
@anchor{library/ast ast LtE}@anchor{4a88}
@deffnx {クラス} ast.LtE
@anchor{library/ast ast Gt}@anchor{4a89}
@deffnx {クラス} ast.Gt
@anchor{library/ast ast GtE}@anchor{4a8a}
@deffnx {クラス} ast.GtE
@anchor{library/ast ast Is}@anchor{4a8b}
@deffnx {クラス} ast.Is
@anchor{library/ast ast IsNot}@anchor{4a8c}
@deffnx {クラス} ast.IsNot
@anchor{library/ast ast In}@anchor{4a8d}
@deffnx {クラス} ast.In
@anchor{library/ast ast NotIn}@anchor{4a8e}
@deffnx {クラス} ast.NotIn

比較演算の演算子をあらわします。
@end deffn

@geindex Call (ast のクラス)
@anchor{library/ast ast Call}@anchor{4a8f}
@deffn {クラス} ast.Call (func, args, keywords)

関数呼び出しをあらわします。 @code{func} は関数で、多くの場合 @ref{1d22,,Name} または @ref{4a90,,Attribute} のオブジェクトです。 関数呼び出しの引数:


@itemize *

@item 
@code{args} は位置引数のリストを保持します。

@item 
@code{keywords} holds a list of @ref{4b95,,keyword} objects representing
arguments passed by keyword.
@end itemize

The @code{args} and @code{keywords} arguments are optional and default to empty lists.

@example
>>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
Expression(
    body=Call(
        func=Name(id='func', ctx=Load()),
        args=[
            Name(id='a', ctx=Load()),
            Starred(
                value=Name(id='d', ctx=Load()),
                ctx=Load())],
        keywords=[
            keyword(
                arg='b',
                value=Name(id='c', ctx=Load())),
            keyword(
                value=Name(id='e', ctx=Load()))]))
@end example
@end deffn

@geindex keyword (ast のクラス)
@anchor{library/ast ast keyword}@anchor{4b95}
@deffn {クラス} ast.keyword (arg, value)

関数呼び出しまたはクラス定義のキーワード引数をあらわします。 @code{arg} はパラメータ名をあらわす文字列、 @code{value} は引数に渡す値をあらわすノードです。
@end deffn

@geindex IfExp (ast のクラス)
@anchor{library/ast ast IfExp}@anchor{4a98}
@deffn {クラス} ast.IfExp (test, body, orelse)

@code{a if b else c} のような式をあらわします。各フィールドは単一のノードを保持します。以下の例では、3つの式ノードはすべて @ref{1d22,,Name} ノードです。

@example
>>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
Expression(
    body=IfExp(
        test=Name(id='b', ctx=Load()),
        body=Name(id='a', ctx=Load()),
        orelse=Name(id='c', ctx=Load())))
@end example
@end deffn

@geindex Attribute (ast のクラス)
@anchor{library/ast ast Attribute}@anchor{4a90}
@deffn {クラス} ast.Attribute (value, attr, ctx)

たとえば @code{d.keys} のような属性へのアクセスです。 @code{value} はノードで、典型的には @ref{1d22,,Name} です。 @code{attr} は属性名を与える生の文字列で、 @code{ctx} はその属性がどのように振る舞うかに応じて @ref{4c2,,Load}、 @ref{4b81,,Store} または @ref{4b83,,Del} のいずれかです。

@example
>>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
Expression(
    body=Attribute(
        value=Name(id='snake', ctx=Load()),
        attr='colour',
        ctx=Load()))
@end example
@end deffn

@geindex NamedExpr (ast のクラス)
@anchor{library/ast ast NamedExpr}@anchor{4a9e}
@deffn {クラス} ast.NamedExpr (target, value)

代入式です。この AST ノードは代入式演算子（ウォルラス演算子、または「セイウチ演算子」としても知られています）によって生成されます。第一引数が複数のノードであってもよい @ref{4b96,,Assign} ノードと異なり、このノードの場合は @code{target} と @code{value} の両方が単一のノードでなければなりません。

@example
>>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
Expression(
    body=NamedExpr(
        target=Name(id='x', ctx=Store()),
        value=Constant(value=4)))
@end example


Added in version 3.8.

@end deffn

@menu
* 配列要素の参照 (Subscripting): 配列要素の参照 Subscripting. 
* 内包表記 (Comprehension): 内包表記 Comprehension. 

@end menu

@node 配列要素の参照 Subscripting,内包表記 Comprehension,,式 expression<2>
@anchor{library/ast subscripting}@anchor{4b97}
@subsubsection 配列要素の参照 (Subscripting)


@geindex Subscript (ast のクラス)
@anchor{library/ast ast Subscript}@anchor{4a91}
@deffn {クラス} ast.Subscript (value, slice, ctx)

@code{l[1]} のような配列要素の参照をあらわします。 @code{value} は参照元のオブジェクトです (通常シーケンス型またはマッピング型)。 @code{slice} はインデックス、スライス、またはキーです。 @ref{4a95,,Slice} を含む @ref{4a94,,Tuple} でもかまいません。 @code{ctx} は要素の参照により実行されるアクションに応じて @ref{4c2,,Load}、 @ref{4b81,,Store} または @ref{4b83,,Del} のいずれかです。

@example
>>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Tuple(
            elts=[
                Slice(
                    lower=Constant(value=1),
                    upper=Constant(value=2)),
                Constant(value=3)],
            ctx=Load()),
        ctx=Load()))
@end example
@end deffn

@geindex Slice (ast のクラス)
@anchor{library/ast ast Slice}@anchor{4a95}
@deffn {クラス} ast.Slice (lower, upper, step)

基本的なスライス操作 (@code{lower:upper} や @code{lower:upper:step} の形式) をあらわします。 @ref{4a91,,Subscript} の `slice' フィールドでの直接指定か、または @ref{4a94,,Tuple} の要素として指定する場合のみ利用可能です。

@example
>>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Slice(
            lower=Constant(value=1),
            upper=Constant(value=2)),
        ctx=Load()))
@end example
@end deffn

@node 内包表記 Comprehension,,配列要素の参照 Subscripting,式 expression<2>
@anchor{library/ast comprehensions}@anchor{4b98}
@subsubsection 内包表記 (Comprehension)


@geindex ListComp (ast のクラス)
@geindex SetComp (ast のクラス)
@geindex GeneratorExp (ast のクラス)
@geindex DictComp (ast のクラス)
@anchor{library/ast ast ListComp}@anchor{4a9a}
@deffn {クラス} ast.ListComp (elt, generators)
@anchor{library/ast ast SetComp}@anchor{4a9b}
@deffnx {クラス} ast.SetComp (elt, generators)
@anchor{library/ast ast GeneratorExp}@anchor{4a9d}
@deffnx {クラス} ast.GeneratorExp (elt, generators)
@anchor{library/ast ast DictComp}@anchor{4a9c}
@deffnx {クラス} ast.DictComp (key, value, generators)

リストや集合の内包表記、ジェネレータ、および辞書の内包表記です。 @code{elt} (または @code{key} と @code{value}) は各要素として評価される部品をあらわす単一のノードです。

@code{generators} は @ref{4b99,,comprehension} ノードのリストです。

@example
>>> print(ast.dump(
...     ast.parse('[x for x in numbers]', mode='eval'),
...     indent=4,
... ))
Expression(
    body=ListComp(
        elt=Name(id='x', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                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()),
                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()),
                is_async=0)]))
@end example
@end deffn

@geindex comprehension (ast のクラス)
@anchor{library/ast ast comprehension}@anchor{4b99}
@deffn {クラス} ast.comprehension (target, iter, ifs, is_async)

内包表記におけるひとつの @code{for} 節をあらわします。 @code{target} は各要素への参照です - 典型的には @ref{1d22,,Name} または @ref{4a94,,Tuple} ノードです。 @code{iter} はイテレートする対象のオブジェクトです。 @code{ifs} は条件節のリストです: 各 @code{for} 節は複数の @code{ifs} を持つことができます。

@code{is_async} は内包表記が非同期であることを示します (@code{async for} を @code{for} の代わりに使います)。値は整数です (0 または 1)。

@example
>>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
...                indent=4)) # Multiple comprehensions in one.
Expression(
    body=ListComp(
        elt=Call(
            func=Name(id='ord', ctx=Load()),
            args=[
                Name(id='c', ctx=Load())]),
        generators=[
            comprehension(
                target=Name(id='line', ctx=Store()),
                iter=Name(id='file', ctx=Load()),
                is_async=0),
            comprehension(
                target=Name(id='c', ctx=Store()),
                iter=Name(id='line', ctx=Load()),
                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()),
                is_async=1)]))
@end example
@end deffn

@node 文 Statements,制御フロー,式 expression<2>,Node クラス
@anchor{library/ast ast-statements}@anchor{4b7b}@anchor{library/ast statements}@anchor{4b9a}
@subsubsection 文 (Statements)


@geindex Assign (ast のクラス)
@anchor{library/ast ast Assign}@anchor{4b96}
@deffn {クラス} ast.Assign (targets, value, type_comment)

代入です。 @code{targets} はノードのリスト、 @code{value} は単一のノードです。

@code{targets} の複数のノードは、それぞれに対して同じ値を代入することをあらわします。分割代入は @code{targets} 内に @ref{4a94,,Tuple} または @ref{4a93,,List} を置くことで表現されます。

@geindex type_comment (ast.Assign の属性)
@anchor{library/ast ast Assign type_comment}@anchor{4b9b}
@deffn {の属性} type_comment

@code{type_comment} はコメントとして型アノテーションをあらわすオプション文字列です。
@end deffn

@example
>>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
Module(
    body=[
        Assign(
            targets=[
                Name(id='a', ctx=Store()),
                Name(id='b', ctx=Store())],
            value=Constant(value=1))])

>>> 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()))])
@end example
@end deffn

@geindex AnnAssign (ast のクラス)
@anchor{library/ast ast AnnAssign}@anchor{4b9c}
@deffn {クラス} ast.AnnAssign (target, annotation, value, simple)

An assignment with a type annotation. @code{target} is a single node and can
be a @ref{1d22,,Name}, an @ref{4a90,,Attribute} or a @ref{4a91,,Subscript}.
@code{annotation} is the annotation, such as a @ref{2ef,,Constant} or @ref{1d22,,Name}
node. @code{value} is a single optional node.

@code{simple} is always either 0 (indicating a "complex" target) or 1
(indicating a "simple" target). A "simple" target consists solely of a
@ref{1d22,,Name} node that does not appear between parentheses; all other
targets are considered complex. Only simple targets appear in
the @ref{458,,__annotations__} dictionary of modules and classes.

@example
>>> print(ast.dump(ast.parse('c: int'), indent=4))
Module(
    body=[
        AnnAssign(
            target=Name(id='c', ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            simple=1)])

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

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

>>> 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)])
@end example
@end deffn

@geindex AugAssign (ast のクラス)
@anchor{library/ast ast AugAssign}@anchor{4b9d}
@deffn {クラス} ast.AugAssign (target, op, value)

@code{a += 1} のような累積代入をあらわします。下記の例では、 @code{target} は (@ref{4b81,,Store} コンテキストを伴う) @code{x} のための @ref{1d22,,Name} ノード、 @code{op} は @ref{4b86,,Add} 演算子、そして @code{value} は定数1をあらわす @ref{2ef,,Constant} ノードです。

@ref{4b96,,Assign} と異なり、 @code{target} 属性は class @ref{4a94,,Tuple} や @ref{4a93,,List} であってはいけません。

@example
>>> print(ast.dump(ast.parse('x += 2'), indent=4))
Module(
    body=[
        AugAssign(
            target=Name(id='x', ctx=Store()),
            op=Add(),
            value=Constant(value=2))])
@end example
@end deffn

@geindex Raise (ast のクラス)
@anchor{library/ast ast Raise}@anchor{4b9e}
@deffn {クラス} ast.Raise (exc, cause)

@code{raise} 文をあらわします。 @code{exc} は送出される例外オブジェクトで、通常は @ref{4a8f,,Call} または @ref{1d22,,Name}、 もしくは単独の @code{raise} では @code{None} を指定します。 @code{cause} はオプションで、 @code{raise x from y} の @code{y} にあたります。

@example
>>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Module(
    body=[
        Raise(
            exc=Name(id='x', ctx=Load()),
            cause=Name(id='y', ctx=Load()))])
@end example
@end deffn

@geindex Assert (ast のクラス)
@anchor{library/ast ast Assert}@anchor{4b9f}
@deffn {クラス} ast.Assert (test, msg)

アサーションです。 @code{test} は @ref{4a84,,Compare} ノードなどのような条件を保持します。 @code{msg} は失敗した時のメッセージを保持します。

@example
>>> print(ast.dump(ast.parse('assert x,y'), indent=4))
Module(
    body=[
        Assert(
            test=Name(id='x', ctx=Load()),
            msg=Name(id='y', ctx=Load()))])
@end example
@end deffn

@geindex Delete (ast のクラス)
@anchor{library/ast ast Delete}@anchor{4ba0}
@deffn {クラス} ast.Delete (targets)

@code{del} 文をあらわします。 @code{targets} は @ref{1d22,,Name}, @ref{4a90,,Attribute},  @ref{4a91,,Subscript} などのノードのリストです。

@example
>>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
Module(
    body=[
        Delete(
            targets=[
                Name(id='x', ctx=Del()),
                Name(id='y', ctx=Del()),
                Name(id='z', ctx=Del())])])
@end example
@end deffn

@geindex Pass (ast のクラス)
@anchor{library/ast ast Pass}@anchor{4ba1}
@deffn {クラス} ast.Pass

@code{pass} 文をあらわします。

@example
>>> print(ast.dump(ast.parse('pass'), indent=4))
Module(
    body=[
        Pass()])
@end example
@end deffn

@geindex TypeAlias (ast のクラス)
@anchor{library/ast ast TypeAlias}@anchor{1a55}
@deffn {クラス} ast.TypeAlias (name, type_params, value)

A @ref{683,,type alias} created through the @ref{66d,,type}
statement. @code{name} is the name of the alias, @code{type_params} is a list of
@ref{4ba2,,type parameters}, and @code{value} is the value of the
type alias.

@example
>>> print(ast.dump(ast.parse('type Alias = int'), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            value=Name(id='int', ctx=Load()))])
@end example


Added in version 3.12.

@end deffn

関数またはループの内部でのみ適用可能な他の文は、別のセクションで説明します。

@menu
* インポート:: 

@end menu

@node インポート,,,文 Statements
@anchor{library/ast imports}@anchor{4ba3}
@subsubsection インポート


@geindex Import (ast のクラス)
@anchor{library/ast ast Import}@anchor{4ba4}
@deffn {クラス} ast.Import (names)

インポート文です。 @code{names} は @ref{1c74,,alias} ノードのリストです。

@example
>>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
Module(
    body=[
        Import(
            names=[
                alias(name='x'),
                alias(name='y'),
                alias(name='z')])])
@end example
@end deffn

@geindex ImportFrom (ast のクラス)
@anchor{library/ast ast ImportFrom}@anchor{4ba5}
@deffn {クラス} ast.ImportFrom (module, names, level)

@code{from x import y} をあらわします。 @code{module} は 'from' でインポートする先頭がドットでないモジュール名をあらわす文字列か、または @code{from . import foo} のような構文の場合は @code{None} を指定します。 @code{level} は相対インポートのレベルを表す整数を保持します (0 は絶対インポートを意味します)。

@example
>>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Module(
    body=[
        ImportFrom(
            module='y',
            names=[
                alias(name='x'),
                alias(name='y'),
                alias(name='z')],
            level=0)])
@end example
@end deffn

@geindex alias (ast のクラス)
@anchor{library/ast ast alias}@anchor{1c74}
@deffn {クラス} ast.alias (name, asname)

いずれのパラメータも名前をあらわす生の文字列です。 @code{asname} は標準の名前を使う場合は @code{None} を指定できます。

@example
>>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Module(
    body=[
        ImportFrom(
            module='foo.bar',
            names=[
                alias(name='a', asname='b'),
                alias(name='c')],
            level=2)])
@end example
@end deffn

@node 制御フロー,Pattern matching,文 Statements,Node クラス
@anchor{library/ast control-flow}@anchor{4ba6}
@subsubsection 制御フロー


@cartouche
@quotation 注釈 
@code{else} 節のようなオプションの節が存在しない場合は、空のリストとして保存されます。
@end quotation
@end cartouche

@geindex If (ast のクラス)
@anchor{library/ast ast If}@anchor{4ba7}
@deffn {クラス} ast.If (test, body, orelse)

@code{if} 文です。 @code{test} は @ref{4a84,,Compare} ノードなどの単一のノードを保持します。 @code{body} と @code{orelse} はそれぞれノードのリストを保持します。

@code{elif} 節は AST において固有の表現を持たず、先行する節をあらわすノードの @code{orelse} セクションに追加の @ref{4ba7,,If} ノードとして現れます。

@example
>>> print(ast.dump(ast.parse("""
... if x:
...    ...
... elif y:
...    ...
... else:
...    ...
... """), indent=4))
Module(
    body=[
        If(
            test=Name(id='x', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                If(
                    test=Name(id='y', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))],
                    orelse=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example
@end deffn

@geindex For (ast のクラス)
@anchor{library/ast ast For}@anchor{4ba8}
@deffn {クラス} ast.For (target, iter, body, orelse, type_comment)

A @code{for} loop. @code{target} holds the variable(s) the loop assigns to, as a
single @ref{1d22,,Name}, @ref{4a94,,Tuple}, @ref{4a93,,List}, @ref{4a90,,Attribute} or
@ref{4a91,,Subscript} node. @code{iter} holds the item to be looped over, again
as a single node. @code{body} and @code{orelse} contain lists of nodes to execute.
Those in @code{orelse} are executed if the loop finishes normally, rather than
via a @code{break} statement.

@geindex type_comment (ast.For の属性)
@anchor{library/ast ast For type_comment}@anchor{4ba9}
@deffn {の属性} type_comment

@code{type_comment} はコメントとして型アノテーションをあらわすオプション文字列です。
@end deffn

@example
>>> print(ast.dump(ast.parse("""
... for x in y:
...     ...
... else:
...     ...
... """), indent=4))
Module(
    body=[
        For(
            target=Name(id='x', ctx=Store()),
            iter=Name(id='y', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))])])
@end example
@end deffn

@geindex While (ast のクラス)
@anchor{library/ast ast While}@anchor{4baa}
@deffn {クラス} ast.While (test, body, orelse)

@code{while} ループです。 @code{test} は @ref{4a84,,Compare} のような条件をあらわすノードを保持します。

@example
>>> print(ast.dump(ast.parse("""
... while x:
...    ...
... else:
...    ...
... """), indent=4))
Module(
    body=[
        While(
            test=Name(id='x', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))])])
@end example
@end deffn

@geindex Break (ast のクラス)
@geindex Continue (ast のクラス)
@anchor{library/ast ast Break}@anchor{4bab}
@deffn {クラス} ast.Break
@anchor{library/ast ast Continue}@anchor{4bac}
@deffnx {クラス} ast.Continue

@code{break} 文および @code{continue} 文です。

@example
>>> print(ast.dump(ast.parse("""\
... for a in b:
...     if a > 5:
...         break
...     else:
...         continue
...
... """), indent=4))
Module(
    body=[
        For(
            target=Name(id='a', ctx=Store()),
            iter=Name(id='b', ctx=Load()),
            body=[
                If(
                    test=Compare(
                        left=Name(id='a', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=5)]),
                    body=[
                        Break()],
                    orelse=[
                        Continue()])])])
@end example
@end deffn

@geindex Try (ast のクラス)
@anchor{library/ast ast Try}@anchor{4bad}
@deffn {クラス} ast.Try (body, handlers, orelse, finalbody)

@code{try} ブロックです。 @ref{4bae,,ExceptHandler} ノードのリストである @code{handlers} を除き、全ての属性はそれぞれの節で実行するノードのリストです。

@example
>>> print(ast.dump(ast.parse("""
... try:
...    ...
... except Exception:
...    ...
... except OtherException as e:
...    ...
... else:
...    ...
... finally:
...    ...
... """), indent=4))
Module(
    body=[
        Try(
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            handlers=[
                ExceptHandler(
                    type=Name(id='Exception', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                ExceptHandler(
                    type=Name(id='OtherException', ctx=Load()),
                    name='e',
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))],
            finalbody=[
                Expr(
                    value=Constant(value=Ellipsis))])])
@end example
@end deffn

@geindex TryStar (ast のクラス)
@anchor{library/ast ast TryStar}@anchor{4baf}
@deffn {クラス} ast.TryStar (body, handlers, orelse, finalbody)

@code{try} blocks which are followed by @code{except*} clauses. The attributes are the
same as for @ref{4bad,,Try} but the @ref{4bae,,ExceptHandler} nodes in @code{handlers}
are interpreted as @code{except*} blocks rather then @code{except}.

@example
>>> print(ast.dump(ast.parse("""
... try:
...    ...
... except* Exception:
...    ...
... """), indent=4))
Module(
    body=[
        TryStar(
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            handlers=[
                ExceptHandler(
                    type=Name(id='Exception', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.11.

@end deffn

@geindex ExceptHandler (ast のクラス)
@anchor{library/ast ast ExceptHandler}@anchor{4bae}
@deffn {クラス} ast.ExceptHandler (type, name, body)

単一の @code{except} 節をあらわします。 @code{type} はこの節にマッチする例外のタイプで、典型的には @ref{1d22,,Name} ノードです (@code{None} を指定すると全ての例外をキャッチする @code{except:} 節をあらわします)。 @code{name} は例外オブジェクトを保持する変数の名前をあらわす生の文字列で、 @code{as foo} を持たない節の場合は @code{None} を指定します。 @code{body} はノードのリストです。

@example
>>> print(ast.dump(ast.parse("""\
... try:
...     a + 1
... except TypeError:
...     pass
... """), indent=4))
Module(
    body=[
        Try(
            body=[
                Expr(
                    value=BinOp(
                        left=Name(id='a', ctx=Load()),
                        op=Add(),
                        right=Constant(value=1)))],
            handlers=[
                ExceptHandler(
                    type=Name(id='TypeError', ctx=Load()),
                    body=[
                        Pass()])])])
@end example
@end deffn

@geindex With (ast のクラス)
@anchor{library/ast ast With}@anchor{4bb0}
@deffn {クラス} ast.With (items, body, type_comment)

@code{with} ブロックです。 @code{items} は @ref{4bb1,,withitem} ノードのリストで、コンテキストマネージャのリストをあらわします。また @code{body} はコンテキスト内にインデントされたブロックです。

@geindex type_comment (ast.With の属性)
@anchor{library/ast ast With type_comment}@anchor{4bb2}
@deffn {の属性} type_comment

@code{type_comment} はコメントとして型アノテーションをあらわすオプション文字列です。
@end deffn
@end deffn

@geindex withitem (ast のクラス)
@anchor{library/ast ast withitem}@anchor{4bb1}
@deffn {クラス} ast.withitem (context_expr, optional_vars)

@code{with} ブロックにおける単一のコンテキストマネージャをあらわします。 @code{context_expr} はコンテキストマネージャで、しばしば @ref{4a8f,,Call} ノードが設定されます。 @code{optional_vars} は @code{as foo} に相当する @ref{1d22,,Name}, @ref{4a94,,Tuple} または @ref{4a93,,List} のいずれかのノードか、または、この部分が不要な場合は @code{None} を設定します。

@example
>>> print(ast.dump(ast.parse("""\
... with a as b, c as d:
...    something(b, d)
... """), indent=4))
Module(
    body=[
        With(
            items=[
                withitem(
                    context_expr=Name(id='a', ctx=Load()),
                    optional_vars=Name(id='b', ctx=Store())),
                withitem(
                    context_expr=Name(id='c', ctx=Load()),
                    optional_vars=Name(id='d', ctx=Store()))],
            body=[
                Expr(
                    value=Call(
                        func=Name(id='something', ctx=Load()),
                        args=[
                            Name(id='b', ctx=Load()),
                            Name(id='d', ctx=Load())]))])])
@end example
@end deffn

@node Pattern matching,Type annotations,制御フロー,Node クラス
@anchor{library/ast pattern-matching}@anchor{4bb3}
@subsubsection Pattern matching


@geindex Match (ast のクラス)
@anchor{library/ast ast Match}@anchor{4bb4}
@deffn {クラス} ast.Match (subject, cases)

A @code{match} statement. @code{subject} holds the subject of the match (the object
that is being matched against the cases) and @code{cases} contains an iterable of
@ref{4bb5,,match_case} nodes with the different cases.


Added in version 3.10.

@end deffn

@geindex match_case (ast のクラス)
@anchor{library/ast ast match_case}@anchor{4bb5}
@deffn {クラス} ast.match_case (pattern, guard, body)

A single case pattern in a @code{match} statement. @code{pattern} contains the
match pattern that the subject will be matched against. Note that the
@ref{4c3,,AST} nodes produced for patterns differ from those produced for
expressions, even when they share the same syntax.

The @code{guard} attribute contains an expression that will be evaluated if
the pattern matches the subject.

@code{body} contains a list of nodes to execute if the pattern matches and
the result of evaluating the guard expression is true.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case [x] if x>0:
...         ...
...     case tuple():
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchAs(name='x')]),
                    guard=Compare(
                        left=Name(id='x', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=0)]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='tuple', ctx=Load())),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchValue (ast のクラス)
@anchor{library/ast ast MatchValue}@anchor{4bb6}
@deffn {クラス} ast.MatchValue (value)

A match literal or value pattern that compares by equality. @code{value} is
an expression node. Permitted value nodes are restricted as described in
the match statement documentation. This pattern succeeds if the match
subject is equal to the evaluated value.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case "Relevant":
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchValue(
                        value=Constant(value='Relevant')),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchSingleton (ast のクラス)
@anchor{library/ast ast MatchSingleton}@anchor{4bb7}
@deffn {クラス} ast.MatchSingleton (value)

A match literal pattern that compares by identity. @code{value} is the
singleton to be compared against: @code{None}, @code{True}, or @code{False}. This
pattern succeeds if the match subject is the given constant.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case None:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSingleton(value=None),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchSequence (ast のクラス)
@anchor{library/ast ast MatchSequence}@anchor{4bb8}
@deffn {クラス} ast.MatchSequence (patterns)

A match sequence pattern. @code{patterns} contains the patterns to be matched
against the subject elements if the subject is a sequence. Matches a variable
length sequence if one of the subpatterns is a @code{MatchStar} node, otherwise
matches a fixed length sequence.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case [1, 2]:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchValue(
                                value=Constant(value=1)),
                            MatchValue(
                                value=Constant(value=2))]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchStar (ast のクラス)
@anchor{library/ast ast MatchStar}@anchor{4bb9}
@deffn {クラス} ast.MatchStar (name)

Matches the rest of the sequence in a variable length match sequence pattern.
If @code{name} is not @code{None}, a list containing the remaining sequence
elements is bound to that name if the overall sequence pattern is successful.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case [1, 2, *rest]:
...         ...
...     case [*_]:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchValue(
                                value=Constant(value=1)),
                            MatchValue(
                                value=Constant(value=2)),
                            MatchStar(name='rest')]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchStar()]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchMapping (ast のクラス)
@anchor{library/ast ast MatchMapping}@anchor{4bba}
@deffn {クラス} ast.MatchMapping (keys, patterns, rest)

A match mapping pattern. @code{keys} is a sequence of expression nodes.
@code{patterns} is a corresponding sequence of pattern nodes. @code{rest} is an
optional name that can be specified to capture the remaining mapping elements.
Permitted key expressions are restricted as described in the match statement
documentation.

This pattern succeeds if the subject is a mapping, all evaluated key
expressions are present in the mapping, and the value corresponding to each
key matches the corresponding subpattern. If @code{rest} is not @code{None}, a dict
containing the remaining mapping elements is bound to that name if the overall
mapping pattern is successful.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case @{1: _, 2: _@}:
...         ...
...     case @{**rest@}:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchMapping(
                        keys=[
                            Constant(value=1),
                            Constant(value=2)],
                        patterns=[
                            MatchAs(),
                            MatchAs()]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchMapping(rest='rest'),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchClass (ast のクラス)
@anchor{library/ast ast MatchClass}@anchor{4bbb}
@deffn {クラス} ast.MatchClass (cls, patterns, kwd_attrs, kwd_patterns)

A match class pattern. @code{cls} is an expression giving the nominal class to
be matched. @code{patterns} is a sequence of pattern nodes to be matched against
the class defined sequence of pattern matching attributes. @code{kwd_attrs} is a
sequence of additional attributes to be matched (specified as keyword arguments
in the class pattern), @code{kwd_patterns} are the corresponding patterns
(specified as keyword values in the class pattern).

This pattern succeeds if the subject is an instance of the nominated class,
all positional patterns match the corresponding class-defined attributes, and
any specified keyword attributes match their corresponding pattern.

Note: classes may define a property that returns self in order to match a
pattern node against the instance being matched. Several builtin types are
also matched that way, as described in the match statement documentation.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case Point2D(0, 0):
...         ...
...     case Point3D(x=0, y=0, z=0):
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='Point2D', ctx=Load()),
                        patterns=[
                            MatchValue(
                                value=Constant(value=0)),
                            MatchValue(
                                value=Constant(value=0))]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='Point3D', ctx=Load()),
                        kwd_attrs=[
                            'x',
                            'y',
                            'z'],
                        kwd_patterns=[
                            MatchValue(
                                value=Constant(value=0)),
                            MatchValue(
                                value=Constant(value=0)),
                            MatchValue(
                                value=Constant(value=0))]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchAs (ast のクラス)
@anchor{library/ast ast MatchAs}@anchor{4bbc}
@deffn {クラス} ast.MatchAs (pattern, name)

A match "as-pattern", capture pattern or wildcard pattern. @code{pattern}
contains the match pattern that the subject will be matched against.
If the pattern is @code{None}, the node represents a capture pattern (i.e a
bare name) and will always succeed.

The @code{name} attribute contains the name that will be bound if the pattern
is successful. If @code{name} is @code{None}, @code{pattern} must also be @code{None}
and the node represents the wildcard pattern.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case [x] as y:
...         ...
...     case _:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchAs(
                        pattern=MatchSequence(
                            patterns=[
                                MatchAs(name='x')]),
                        name='y'),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchAs(),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@geindex MatchOr (ast のクラス)
@anchor{library/ast ast MatchOr}@anchor{4bbd}
@deffn {クラス} ast.MatchOr (patterns)

A match "or-pattern". An or-pattern matches each of its subpatterns in turn
to the subject, until one succeeds. The or-pattern is then deemed to
succeed. If none of the subpatterns succeed the or-pattern fails. The
@code{patterns} attribute contains a list of match pattern nodes that will be
matched against the subject.

@example
>>> print(ast.dump(ast.parse("""
... match x:
...     case [x] | (y):
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchOr(
                        patterns=[
                            MatchSequence(
                                patterns=[
                                    MatchAs(name='x')]),
                            MatchAs(name='y')]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])
@end example


Added in version 3.10.

@end deffn

@node Type annotations,Type parameters,Pattern matching,Node クラス
@anchor{library/ast type-annotations}@anchor{4bbe}
@subsubsection Type annotations


@geindex TypeIgnore (ast のクラス)
@anchor{library/ast ast TypeIgnore}@anchor{1b0e}
@deffn {クラス} ast.TypeIgnore (lineno, tag)

A @code{# type: ignore} comment located at `lineno'.
`tag' is the optional tag specified by the form @code{# type: ignore <tag>}.

@example
>>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='x', ctx=Store())],
            value=Constant(value=1))],
    type_ignores=[
        TypeIgnore(lineno=1, tag='@w{'})])
>>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', type_comments=True), indent=4))
Module(
    body=[
        AnnAssign(
            target=Name(id='x', ctx=Store()),
            annotation=Name(id='bool', ctx=Load()),
            value=Constant(value=1),
            simple=1)],
    type_ignores=[
        TypeIgnore(lineno=1, tag='[assignment]')])
@end example

@cartouche
@quotation 注釈 
@code{TypeIgnore} nodes are not generated when the `type_comments' parameter
is set to @code{False} (default).  See @ref{1c2,,ast.parse()} for more details.
@end quotation
@end cartouche


Added in version 3.8.

@end deffn

@node Type parameters,関数およびクラス定義,Type annotations,Node クラス
@anchor{library/ast ast-type-params}@anchor{4ba2}@anchor{library/ast type-parameters}@anchor{4bbf}
@subsubsection Type parameters


@ref{5ad,,Type parameters} can exist on classes, functions, and type
aliases.

@geindex TypeVar (ast のクラス)
@anchor{library/ast ast TypeVar}@anchor{4bc0}
@deffn {クラス} ast.TypeVar (name, bound, default_value)

A @ref{486,,typing.TypeVar}. @code{name} is the name of the type variable.
@code{bound} is the bound or constraints, if any. If @code{bound} is a @ref{4a94,,Tuple},
it represents constraints; otherwise it represents the bound. @code{default_value}
is the default value; if the @code{TypeVar} has no default, this
attribute will be set to @code{None}.

@example
>>> print(ast.dump(ast.parse("type Alias[T: int = bool] = list[T]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                TypeVar(
                    name='T',
                    bound=Name(id='int', ctx=Load()),
                    default_value=Name(id='bool', ctx=Load()))],
            value=Subscript(
                value=Name(id='list', ctx=Load()),
                slice=Name(id='T', ctx=Load()),
                ctx=Load()))])
@end example


Added in version 3.12.



バージョン 3.13 で変更: Added the `default_value' parameter.

@end deffn

@geindex ParamSpec (ast のクラス)
@anchor{library/ast ast ParamSpec}@anchor{4bc1}
@deffn {クラス} ast.ParamSpec (name, default_value)

A @ref{487,,typing.ParamSpec}. @code{name} is the name of the parameter specification.
@code{default_value} is the default value; if the @code{ParamSpec} has no default,
this attribute will be set to @code{None}.

@example
>>> print(ast.dump(ast.parse("type Alias[**P = [int, str]] = Callable[P, int]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                ParamSpec(
                    name='P',
                    default_value=List(
                        elts=[
                            Name(id='int', ctx=Load()),
                            Name(id='str', ctx=Load())],
                        ctx=Load()))],
            value=Subscript(
                value=Name(id='Callable', ctx=Load()),
                slice=Tuple(
                    elts=[
                        Name(id='P', ctx=Load()),
                        Name(id='int', ctx=Load())],
                    ctx=Load()),
                ctx=Load()))])
@end example


Added in version 3.12.



バージョン 3.13 で変更: Added the `default_value' parameter.

@end deffn

@geindex TypeVarTuple (ast のクラス)
@anchor{library/ast ast TypeVarTuple}@anchor{4bc2}
@deffn {クラス} ast.TypeVarTuple (name, default_value)

A @ref{488,,typing.TypeVarTuple}. @code{name} is the name of the type variable tuple.
@code{default_value} is the default value; if the @code{TypeVarTuple} has no
default, this attribute will be set to @code{None}.

@example
>>> print(ast.dump(ast.parse("type Alias[*Ts = ()] = tuple[*Ts]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                TypeVarTuple(
                    name='Ts',
                    default_value=Tuple(ctx=Load()))],
            value=Subscript(
                value=Name(id='tuple', ctx=Load()),
                slice=Tuple(
                    elts=[
                        Starred(
                            value=Name(id='Ts', ctx=Load()),
                            ctx=Load())],
                    ctx=Load()),
                ctx=Load()))])
@end example


Added in version 3.12.



バージョン 3.13 で変更: Added the `default_value' parameter.

@end deffn

@node 関数およびクラス定義,async と await,Type parameters,Node クラス
@anchor{library/ast function-and-class-definitions}@anchor{4bc3}
@subsubsection 関数およびクラス定義


@geindex FunctionDef (ast のクラス)
@anchor{library/ast ast FunctionDef}@anchor{1a78}
@deffn {クラス} ast.FunctionDef (name, args, body, decorator_list, returns, type_comment, type_params)

関数定義です。


@itemize *

@item 
@code{name} は関数名をあらわす生の文字列です。

@item 
@code{args} は引数をあらわす @ref{4bc4,,arguments} ノードです。

@item 
@code{body} は関数の本体をあらわすノードのリストです。

@item 
@code{decorator_list} は関数に適用されるデコレータのリストで、外側のデコレータがリストの先頭に保存されます (すなわち、リストの先頭にあるデコレータが最後に適用されます)。

@item 
@code{returns} は戻り値に対する注釈です。

@item 
@code{type_params} is a list of @ref{4ba2,,type parameters}.
@end itemize

@geindex type_comment (ast.FunctionDef の属性)
@anchor{library/ast ast FunctionDef type_comment}@anchor{4bc5}
@deffn {の属性} type_comment

@code{type_comment} はコメントとして型アノテーションをあらわすオプション文字列です。
@end deffn


バージョン 3.12 で変更: Added @code{type_params}.

@end deffn

@geindex Lambda (ast のクラス)
@anchor{library/ast ast Lambda}@anchor{4a99}
@deffn {クラス} ast.Lambda (args, body)

@code{lambda} は式の中で使うことができる最小限の関数定義です。 @ref{1a78,,FunctionDef} ノードと異なり、 @code{body} は単一のノードとなります。

@example
>>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Module(
    body=[
        Expr(
            value=Lambda(
                args=arguments(
                    args=[
                        arg(arg='x'),
                        arg(arg='y')]),
                body=Constant(value=Ellipsis)))])
@end example
@end deffn

@geindex arguments (ast のクラス)
@anchor{library/ast ast arguments}@anchor{4bc4}
@deffn {クラス} ast.arguments (posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)

関数の引数


@itemize *

@item 
@code{posonlyargs}, @code{args} および @code{kwonlyargs} はそれぞれ @ref{4bc6,,arg} ノードのリストです。

@item 
@code{vararg} と @code{kwarg} はそれぞれ単一の @ref{4bc6,,arg} ノードで、 @code{*args, **kwargs} パラメータに相当します。

@item 
@code{kw_defaults} はキーワード専用引数に対するデフォルト値のリストです。値が @code{None} の場合、対応する引数は必須となります。

@item 
@code{defaults} は位置引数として渡すことのできる引数に対するデフォルト値のリストです。デフォルト値の数nが位置引数の数より少ない場合、それらは最後のn個の引数に割り当てられます。
@end itemize
@end deffn

@geindex arg (ast のクラス)
@anchor{library/ast ast arg}@anchor{4bc6}
@deffn {クラス} ast.arg (arg, annotation, type_comment)

A single argument in a list. @code{arg} is a raw string of the argument
name; @code{annotation} is its annotation, such as a @ref{1d22,,Name} node.

@geindex type_comment (ast.arg の属性)
@anchor{library/ast ast arg type_comment}@anchor{4bc7}
@deffn {の属性} type_comment

@code{type_comment} はコメントとして型アノテーションをあらわすオプション文字列です。
@end deffn

@example
>>> print(ast.dump(ast.parse("""\
... @@decorator1
... @@decorator2
... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
...     pass
... """), indent=4))
Module(
    body=[
        FunctionDef(
            name='f',
            args=arguments(
                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'))])
@end example
@end deffn

@geindex Return (ast のクラス)
@anchor{library/ast ast Return}@anchor{4bc8}
@deffn {クラス} ast.Return (value)

@code{return} 文です。

@example
>>> print(ast.dump(ast.parse('return 4'), indent=4))
Module(
    body=[
        Return(
            value=Constant(value=4))])
@end example
@end deffn

@geindex Yield (ast のクラス)
@geindex YieldFrom (ast のクラス)
@anchor{library/ast ast Yield}@anchor{4aa0}
@deffn {クラス} ast.Yield (value)
@anchor{library/ast ast YieldFrom}@anchor{4aa1}
@deffnx {クラス} ast.YieldFrom (value)

A @code{yield} or @code{yield from} expression. Because these are expressions, they
must be wrapped in an @ref{4b85,,Expr} node if the value sent back is not used.

@example
>>> print(ast.dump(ast.parse('yield x'), indent=4))
Module(
    body=[
        Expr(
            value=Yield(
                value=Name(id='x', ctx=Load())))])

>>> print(ast.dump(ast.parse('yield from x'), indent=4))
Module(
    body=[
        Expr(
            value=YieldFrom(
                value=Name(id='x', ctx=Load())))])
@end example
@end deffn

@geindex Global (ast のクラス)
@geindex Nonlocal (ast のクラス)
@anchor{library/ast ast Global}@anchor{4bc9}
@deffn {クラス} ast.Global (names)
@anchor{library/ast ast Nonlocal}@anchor{4bca}
@deffnx {クラス} ast.Nonlocal (names)

@code{global} および @code{nonlocal} 文です。 @code{names} は生の文字列のリストです。

@example
>>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
Module(
    body=[
        Global(
            names=[
                'x',
                'y',
                'z'])])

>>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Module(
    body=[
        Nonlocal(
            names=[
                'x',
                'y',
                'z'])])
@end example
@end deffn

@geindex ClassDef (ast のクラス)
@anchor{library/ast ast ClassDef}@anchor{1a76}
@deffn {クラス} ast.ClassDef (name, bases, keywords, body, decorator_list, type_params)

クラス定義です。


@itemize *

@item 
@code{name} はクラス名をあらわす生の文字列です。

@item 
@code{bases} は明示的に指定された基底クラスをあらわすノードのリストです。

@item 
@code{keywords} is a list of @ref{4b95,,keyword} nodes, principally for 'metaclass'.
Other keywords will be passed to the metaclass, as per 
@geindex Python Enhancement Proposals; PEP 3115
PEP 3115@footnote{https://peps.python.org/pep-3115/}.

@item 
@code{body} はクラス定義に含まれるコードをあらわすノードのリストです。

@item 
@code{decorator_list} はノードのリストで、関数定義 @ref{1a78,,FunctionDef} の場合と同様に解釈されます。

@item 
@code{type_params} is a list of @ref{4ba2,,type parameters}.
@end itemize

@example
>>> print(ast.dump(ast.parse("""\
... @@decorator1
... @@decorator2
... class Foo(base1, base2, metaclass=meta):
...     pass
... """), indent=4))
Module(
    body=[
        ClassDef(
            name='Foo',
            bases=[
                Name(id='base1', ctx=Load()),
                Name(id='base2', ctx=Load())],
            keywords=[
                keyword(
                    arg='metaclass',
                    value=Name(id='meta', ctx=Load()))],
            body=[
                Pass()],
            decorator_list=[
                Name(id='decorator1', ctx=Load()),
                Name(id='decorator2', ctx=Load())])])
@end example


バージョン 3.12 で変更: Added @code{type_params}.

@end deffn

@node async と await,,関数およびクラス定義,Node クラス
@anchor{library/ast async-and-await}@anchor{4bcb}
@subsubsection async と await


@geindex AsyncFunctionDef (ast のクラス)
@anchor{library/ast ast AsyncFunctionDef}@anchor{1a77}
@deffn {クラス} ast.AsyncFunctionDef (name, args, body, decorator_list, returns, type_comment, type_params)

@code{async def} 形式の関数定義です。通常の関数定義 @ref{1a78,,FunctionDef} と同じフィールドを持ちます。


バージョン 3.12 で変更: Added @code{type_params}.

@end deffn

@geindex Await (ast のクラス)
@anchor{library/ast ast Await}@anchor{4a9f}
@deffn {クラス} ast.Await (value)

@code{await} 式をあらわします。 @code{value} は待ち受ける値です。 @ref{1a77,,AsyncFunctionDef} の本体 (body) の中でのみ有効です。
@end deffn

@example
>>> print(ast.dump(ast.parse("""\
... async def f():
...     await other_func()
... """), indent=4))
Module(
    body=[
        AsyncFunctionDef(
            name='f',
            args=arguments(),
            body=[
                Expr(
                    value=Await(
                        value=Call(
                            func=Name(id='other_func', ctx=Load()))))])])
@end example

@geindex AsyncFor (ast のクラス)
@geindex AsyncWith (ast のクラス)
@anchor{library/ast ast AsyncFor}@anchor{4bcc}
@deffn {クラス} ast.AsyncFor (target, iter, body, orelse, type_comment)
@anchor{library/ast ast AsyncWith}@anchor{4bcd}
@deffnx {クラス} ast.AsyncWith (items, body, type_comment)

@code{async for} ループと @code{async with} コンテキストマネージャです。それぞれ @ref{4ba8,,For} および @ref{4bb0,,With} と同じフィールドを持ちます。 @ref{1a77,,AsyncFunctionDef} の本体 (body) の中でのみ有効です。
@end deffn

@cartouche
@quotation 注釈 
When a string is parsed by @ref{1c2,,ast.parse()}, operator nodes (subclasses
of @code{ast.operator}, @code{ast.unaryop}, @code{ast.cmpop},
@code{ast.boolop} and @code{ast.expr_context}) on the returned tree
will be singletons. Changes to one will be reflected in all other
occurrences of the same value (for example, @ref{4b86,,ast.Add}).
@end quotation
@end cartouche

@node ast helpers,Compiler flags<2>,Node クラス,ast --- Abstract syntax trees
@anchor{library/ast ast-helpers}@anchor{4bce}
@subsubsection @code{ast} helpers


Apart from the node classes, the @code{ast} module defines these utility functions
and classes for traversing abstract syntax trees:

@geindex parse() (ast モジュール)
@anchor{library/ast ast parse}@anchor{1c2}
@deffn {の関数} ast.parse (source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1)

Parse the source into an AST node.  Equivalent to @code{compile(source,
filename, mode, flags=FLAGS_VALUE, optimize=optimize)},
where @code{FLAGS_VALUE} is @code{ast.PyCF_ONLY_AST} if @code{optimize <= 0}
and @code{ast.PyCF_OPTIMIZED_AST} otherwise.

If @code{type_comments=True} is given, the parser is modified to check
and return type comments as specified by 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} and 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/}.
This is equivalent to adding @ref{4bcf,,ast.PyCF_TYPE_COMMENTS} to the
flags passed to @ref{4b1,,compile()}.  This will report syntax errors
for misplaced type comments.  Without this flag, type comments will
be ignored, and the @code{type_comment} field on selected AST nodes
will always be @code{None}.  In addition, the locations of @code{# type:
ignore} comments will be returned as the @code{type_ignores}
attribute of @ref{4b7a,,Module} (otherwise it is always an empty list).

さらに @code{mode} が @code{'func_type'} の場合、入力構文は、たとえば @code{(str, int) -> List[str]} のような 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} の "シグネチャ型コメント (signature type comments)" に対応するように修正されます。

Setting @code{feature_version} to a tuple @code{(major, minor)} will result in
a "best-effort" attempt to parse using that Python version's grammar.
For example, setting @code{feature_version=(3, 9)} will attempt to disallow
parsing of @ref{a0e,,match} statements.
Currently @code{major} must equal to @code{3}. The lowest supported version is
@code{(3, 7)} (and this may increase in future Python versions);
the highest is @code{sys.version_info[0:2]}. "Best-effort" attempt means there
is no guarantee that the parse (or success of the parse) is the same as
when run on the Python version corresponding to @code{feature_version}.

If source contains a null character (@code{\0}), @ref{2ec,,ValueError} is raised.

@cartouche
@quotation 警告 
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 @ref{18e,,SyntaxError}
exceptions. For instance, the source @code{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, @ref{1c2,,ast.parse()} won't do any scoping checks, which the
compilation step does.
@end quotation
@end cartouche

@cartouche
@quotation 警告 
十分に大きい文字列や複雑な文字列によって Python の抽象構文木コンパイラのスタックの深さの限界を越えることで、 Python インタプリタをクラッシュさせることができます。
@end quotation
@end cartouche


バージョン 3.8 で変更: @code{type_comments}、@code{mode='func_type'}、@code{feature_version} が追加されました。



バージョン 3.13 で変更: The minimum supported version for @code{feature_version} is now @code{(3, 7)}.
The @code{optimize} argument was added.

@end deffn

@geindex unparse() (ast モジュール)
@anchor{library/ast ast unparse}@anchor{ae2}
@deffn {の関数} ast.unparse (ast_obj)

@ref{4c3,,ast.AST} オブジェクトを逆に構文解析して、 @ref{1c2,,ast.parse()} が元の @ref{4c3,,ast.AST} と等価なオブジェクトを生成できるような文字列を生成します。

@cartouche
@quotation 警告 
生成されたコード文字列は、生成元のコードである @ref{4c3,,ast.AST} オブジェクトと必ずしも等価であるとは限りません (定数タプルや frozenset などに対するコンパイラ最適化なしのコードです)。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
非常に複雑な式を逆構文解析すると @ref{f68,,RecursionError} となることがあります。
@end quotation
@end cartouche


Added in version 3.9.

@end deffn

@geindex literal_eval() (ast モジュール)
@anchor{library/ast ast literal_eval}@anchor{e12}
@deffn {の関数} ast.literal_eval (node_or_string)

Python のリテラルやコンテナ表現のみを含む式ノードまたは文字列を評価します。与えられる文字列またはノードは次の Python リテラル構造のみからなるものに限られます: 文字列、バイト列、数、タプル、リスト、辞書、集合、ブール値、@code{None}、@code{Ellipsis}。

この関数は Python の式を含んだ文字列を、値自身を解析することなしに評価するのに使えます。この関数は、例えば演算や添え字を含んだ任意の複雑な表現を評価するのには使えません。

This function had been documented as "safe" in the past without defining
what that meant. That was misleading. This is specifically designed not to
execute Python code, unlike the more general @ref{4a3,,eval()}. There is no
namespace, no name lookups, or ability to call out. But it is not free from
attack: A relatively small input can lead to memory exhaustion or to C stack
exhaustion, crashing the process. There is also the possibility for
excessive CPU consumption denial of service on some inputs. Calling it on
untrusted data is thus not recommended.

@cartouche
@quotation 警告 
Python の抽象構文木コンパイラのスタックの深さの限界を越えることで、 Python インタプリタをクラッシュさせる可能性があります。

It can raise @ref{2ec,,ValueError}, @ref{198,,TypeError}, @ref{18e,,SyntaxError},
@ref{179e,,MemoryError} and @ref{f68,,RecursionError} depending on the malformed
input.
@end quotation
@end cartouche


バージョン 3.2 で変更: バイト列リテラルと集合リテラルが受け取れるようになりました。



バージョン 3.9 で変更: @code{'set()'} による空の集合の生成をサポートするようになりました。



バージョン 3.10 で変更: For string inputs, leading spaces and tabs are now stripped.

@end deffn

@geindex get_docstring() (ast モジュール)
@anchor{library/ast ast get_docstring}@anchor{1e3b}
@deffn {の関数} ast.get_docstring (node, clean=True)

与えられた `node' (これは @ref{1a78,,FunctionDef}, @ref{1a77,,AsyncFunctionDef}, @ref{1a76,,ClassDef}, @ref{4b7a,,Module} のいずれかのノードでなければなりません) のドキュメント文字列を返します。もしドキュメント文字列が無ければ @code{None} を返します。 `clean' が真ならば、ドキュメント文字列のインデントを @ref{1a2c,,inspect.cleandoc()} を用いて一掃します。


バージョン 3.5 で変更: @ref{1a77,,AsyncFunctionDef} がサポートされました。

@end deffn

@geindex get_source_segment() (ast モジュール)
@anchor{library/ast ast get_source_segment}@anchor{bcb}
@deffn {の関数} ast.get_source_segment (source, node, *, padded=False)

Get source code segment of the `source' that generated `node'.
If some location information (@ref{4b74,,lineno}, @ref{4b76,,end_lineno},
@ref{4b75,,col_offset}, or @ref{4b77,,end_col_offset}) is missing, return @code{None}.

`padded' が @code{True} の場合、複数行にわたる文の最初の行が元の位置に一致するように空白文字でパディングされます。


Added in version 3.8.

@end deffn

@geindex fix_missing_locations() (ast モジュール)
@anchor{library/ast ast fix_missing_locations}@anchor{4bd0}
@deffn {の関数} ast.fix_missing_locations (node)

When you compile a node tree with @ref{4b1,,compile()}, the compiler expects
@ref{4b74,,lineno} and @ref{4b75,,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'.
@end deffn

@geindex increment_lineno() (ast モジュール)
@anchor{library/ast ast increment_lineno}@anchor{1b0d}
@deffn {の関数} ast.increment_lineno (node, n=1)

`node' で始まるツリー内の各ノードの行番号と終了行番号を `n' ずつ増やします。これはファイルの中で別の場所に "コードを移動する" ときに便利です。
@end deffn

@geindex copy_location() (ast モジュール)
@anchor{library/ast ast copy_location}@anchor{4bd1}
@deffn {の関数} ast.copy_location (new_node, old_node)

Copy source location (@ref{4b74,,lineno}, @ref{4b75,,col_offset}, @ref{4b76,,end_lineno},
and @ref{4b77,,end_col_offset}) from `old_node' to `new_node' if possible,
and return `new_node'.
@end deffn

@geindex iter_fields() (ast モジュール)
@anchor{library/ast ast iter_fields}@anchor{4bd2}
@deffn {の関数} ast.iter_fields (node)

`node' にある @code{node._fields} のそれぞれのフィールドを @code{(フィールド名, 値)} のタプルとして yield します。
@end deffn

@geindex iter_child_nodes() (ast モジュール)
@anchor{library/ast ast iter_child_nodes}@anchor{4bd3}
@deffn {の関数} ast.iter_child_nodes (node)

`node' の直接の子ノード全てを yield します。すなわち、yield されるのは、ノードであるような全てのフィールドおよびノードのリストであるようなフィールドの全てのアイテムです。
@end deffn

@geindex walk() (ast モジュール)
@anchor{library/ast ast walk}@anchor{4bd4}
@deffn {の関数} ast.walk (node)

`node' の全ての子孫ノード(`node' 自体を含む)を再帰的に yield します。順番は決められていません。この関数はノードをその場で変更するだけで文脈を気にしないような場合に便利です。
@end deffn

@geindex NodeVisitor (ast のクラス)
@anchor{library/ast ast NodeVisitor}@anchor{2f0}
@deffn {クラス} ast.NodeVisitor

抽象構文木を渡り歩いてビジター関数を見つけたノードごとに呼び出すノード・ビジターの基底クラスです。この関数は @ref{4bd5,,visit()} メソッドに送られる値を返してもかまいません。

このクラスはビジター・メソッドを付け加えたサブクラスを派生させることを意図しています。

@geindex visit() (ast.NodeVisitor のメソッド)
@anchor{library/ast ast NodeVisitor visit}@anchor{4bd5}
@deffn {メソッド} visit (node)

ノードを訪れます。デフォルトの実装では @code{self.visit_@var{classname}} というメソッド (ここで `classname' はノードのクラス名です) を呼び出すか、そのメソッドがなければ @ref{4bd6,,generic_visit()} を呼び出します。
@end deffn

@geindex generic_visit() (ast.NodeVisitor のメソッド)
@anchor{library/ast ast NodeVisitor generic_visit}@anchor{4bd6}
@deffn {メソッド} generic_visit (node)

このビジターはノードの全ての子について @ref{4bd5,,visit()} を呼び出します。

注意して欲しいのは、専用のビジター・メソッドを具えたノードの子ノードは、このビジターが @ref{4bd6,,generic_visit()} を呼び出すかそれ自身で子ノードを訪れない限り訪れられないということです。
@end deffn

@geindex visit_Constant() (ast.NodeVisitor のメソッド)
@anchor{library/ast ast NodeVisitor visit_Constant}@anchor{c63}
@deffn {メソッド} visit_Constant (node)

Handles all constant nodes.
@end deffn

トラバースの途中でノードを変化させたいならば @ref{2f0,,NodeVisitor} を使ってはいけません。そうした目的のために変更を許す特別なビジター (@ref{4bd7,,NodeTransformer}) があります。


Deprecated since version 3.8, removed in version 3.14: Methods @code{visit_Num()}, @code{visit_Str()}, @code{visit_Bytes()},
@code{visit_NameConstant()} and @code{visit_Ellipsis()} will not be called
in Python 3.14+.  Add the @ref{c63,,visit_Constant()} method instead to handle
all constant nodes.

@end deffn

@geindex NodeTransformer (ast のクラス)
@anchor{library/ast ast NodeTransformer}@anchor{4bd7}
@deffn {クラス} ast.NodeTransformer

@ref{2f0,,NodeVisitor} のサブクラスで抽象構文木を渡り歩きながらノードを変更することを許すものです。

@ref{4bd7,,NodeTransformer} は抽象構文木(AST)を渡り歩き、ビジター・メソッドの戻り値を使って古いノードを置き換えたり削除したりします。ビジター・メソッドの戻り値が @code{None} ならば、ノードはその場から取り去られ、そうでなければ戻り値で置き換えられます。置き換えない場合は戻り値が元のノードそのものであってもかまいません。

それでは例を示しましょう。Name (たとえば @code{foo}) を見つけるたび全て @code{data['foo']} に書き換える変換器 (transformer) です:

@example
class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return Subscript(
            value=Name(id='data', ctx=Load()),
            slice=Constant(value=node.id),
            ctx=node.ctx
        )
@end example

Keep in mind that if the node you're operating on has child nodes you must
either transform the child nodes yourself or call the @ref{4bd6,,generic_visit()}
method for the node first.

文のコレクションであるようなノード (全ての文のノードが当てはまります) に対して、このビジターは単独のノードではなくノードのリストを返すかもしれません。

If @ref{4bd7,,NodeTransformer} introduces new nodes (that weren't part of
original tree) without giving them location information (such as
@ref{4b74,,lineno}), @ref{4bd0,,fix_missing_locations()} should be called with
the new sub-tree to recalculate the location information:

@example
tree = ast.parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))
@end example

たいてい、変換器の使い方は次のようになります:

@example
node = YourTransformer().visit(node)
@end example
@end deffn

@geindex dump() (ast モジュール)
@anchor{library/ast ast dump}@anchor{ae1}
@deffn {の関数} ast.dump (node, annotate_fields=True, include_attributes=False, *, indent=None, show_empty=False)

`node' 内のツリーのフォーマットされたダンプを返します。主な使い道はデバッグです。 `annotate_fields' が true の場合 (デフォルト)、返される文字列はフィールドの名前と値を示します。 `annotate_fields' が false の場合、あいまいさのないフィールド名を省略することにより、結果文字列はよりコンパクトになります。行番号や列オフセットのような属性はデフォルトではダンプされません。これが必要であれば、 `include_attributes' を true にすると表示できます。

`indent' が非負の整数または文字列の場合、ツリーは指定されたインデントレベルで整形されて出力されます (pretty-printed)。インデントレベルがゼロ、負の数、または @code{""} の場合は改行だけを挿入します。 @code{None} (デフォルト値) は単一行での表記になります。正の整数を指定すると各インデントレベルでその数だけの空白でインデントされます。 `indent' が文字列 (@code{"\t"} など) の場合、その文字列が各レベルのインデントに使われます。

If `show_empty' is false (the default), optional empty lists will be
omitted from the output.
Optional @code{None} values are always omitted.


バージョン 3.9 で変更: `indent' オプションを追加しました。



バージョン 3.13 で変更: Added the `show_empty' option.

@example
>>> print(ast.dump(ast.parse("""\
... async def f():
...     await other_func()
... """), indent=4, show_empty=True))
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_params=[])],
    type_ignores=[])
@end example

@end deffn

@node Compiler flags<2>,コマンドラインでの使用<8>,ast helpers,ast --- Abstract syntax trees
@anchor{library/ast ast-compiler-flags}@anchor{25c7}@anchor{library/ast compiler-flags}@anchor{4bd8}
@subsubsection Compiler flags


以下のフラグはプログラムのコンパイルにおける効果を変更するために @ref{4b1,,compile()} に渡すことができます:

@geindex PyCF_ALLOW_TOP_LEVEL_AWAIT (ast モジュール)
@anchor{library/ast ast PyCF_ALLOW_TOP_LEVEL_AWAIT}@anchor{4bd9}
@deffn {データ} ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

トップレベルの @code{await}, @code{async for}, @code{async with} および async 内包表記のサポートを有効化します。


Added in version 3.8.

@end deffn

@geindex PyCF_ONLY_AST (ast モジュール)
@anchor{library/ast ast PyCF_ONLY_AST}@anchor{4b70}
@deffn {データ} ast.PyCF_ONLY_AST

コンパイルされたコードオブジェクトの代わりに抽象構文木を生成して返します。
@end deffn

@geindex PyCF_OPTIMIZED_AST (ast モジュール)
@anchor{library/ast ast PyCF_OPTIMIZED_AST}@anchor{4bda}
@deffn {データ} ast.PyCF_OPTIMIZED_AST

The returned AST is optimized according to the `optimize' argument
in @ref{4b1,,compile()} or @ref{1c2,,ast.parse()}.


Added in version 3.13.

@end deffn

@geindex PyCF_TYPE_COMMENTS (ast モジュール)
@anchor{library/ast ast PyCF_TYPE_COMMENTS}@anchor{4bcf}
@deffn {データ} ast.PyCF_TYPE_COMMENTS

@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} および 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} 形式の型コメント (@code{# type: <type>}, @code{# type: ignore <stuff>}) のサポートを有効化します。


Added in version 3.8.

@end deffn

@geindex compare() (ast モジュール)
@anchor{library/ast ast compare}@anchor{1bf}
@deffn {の関数} ast.compare (a, b, /, *, compare_attributes=False)

Recursively compares two ASTs.

`compare_attributes' affects whether AST attributes are considered
in the comparison. If `compare_attributes' is @code{False} (default), then
attributes are ignored. Otherwise they must all be equal. This
option is useful to check whether the ASTs are structurally equal but
differ in whitespace or similar details. Attributes include line numbers
and column offsets.


Added in version 3.14.

@end deffn

@node コマンドラインでの使用<8>,,Compiler flags<2>,ast --- Abstract syntax trees
@anchor{library/ast ast-cli}@anchor{4bdb}@anchor{library/ast command-line-usage}@anchor{4bdc}
@subsubsection コマンドラインでの使用



Added in version 3.9.


The @code{ast} module can be executed as a script from the command line.
It is as simple as:

@example
python -m ast [-m <mode>] [-a] [infile]
@end example

以下のオプションが使用できます:

@geindex ast コマンドラインオプション; -h
@geindex ast コマンドラインオプション; --help
@anchor{library/ast cmdoption-ast-h}@anchor{4bdd}@anchor{library/ast cmdoption-ast-help}@anchor{4bde}
@deffn {Option} @w{-}h, @w{-}@w{-}help

ヘルプメッセージを表示して終了します。
@end deffn

@geindex ast コマンドラインオプション; -m
@geindex ast コマンドラインオプション; --mode
@anchor{library/ast cmdoption-ast-m}@anchor{4bdf}
@deffn {Option} @w{-}m <mode>
@anchor{library/ast cmdoption-ast-mode}@anchor{4be0}
@deffnx {Option} @w{-}@w{-}mode <mode>

@ref{1c2,,parse()} 関数の `mode' 引数と同様、コンパイルするコードの種類を指定します。
@end deffn

@geindex ast コマンドラインオプション; --no-type-comments
@anchor{library/ast cmdoption-ast-no-type-comments}@anchor{4be1}
@deffn {Option} @w{-}@w{-}no@w{-}type@w{-}comments

型コメントをパースしません。
@end deffn

@geindex ast コマンドラインオプション; -a
@geindex ast コマンドラインオプション; --include-attributes
@anchor{library/ast cmdoption-ast-a}@anchor{4be2}@anchor{library/ast cmdoption-ast-include-attributes}@anchor{4be3}
@deffn {Option} @w{-}a, @w{-}@w{-}include@w{-}attributes

行番号や列オフセットなどの属性を含めます。
@end deffn

@geindex ast コマンドラインオプション; -i
@geindex ast コマンドラインオプション; --indent
@anchor{library/ast cmdoption-ast-i}@anchor{4be4}
@deffn {Option} @w{-}i <indent>
@anchor{library/ast cmdoption-ast-indent}@anchor{4be5}
@deffnx {Option} @w{-}@w{-}indent <indent>

AST におけるノードのインデント (空白の数) です。
@end deffn

@geindex ast コマンドラインオプション; --feature-version
@anchor{library/ast cmdoption-ast-feature-version}@anchor{1c3}
@deffn {Option} @w{-}@w{-}feature@w{-}version <version>

Python version in the format 3.x (for example, 3.10). Defaults to the
current version of the interpreter.


Added in version 3.14.

@end deffn

@geindex ast コマンドラインオプション; -O
@geindex ast コマンドラインオプション; --optimize
@anchor{library/ast cmdoption-ast-O}@anchor{4be6}
@deffn {Option} @w{-}O <level>
@anchor{library/ast cmdoption-ast-optimize}@anchor{1c4}
@deffnx {Option} @w{-}@w{-}optimize <level>

Optimization level for parser. Defaults to no optimization.


Added in version 3.14.

@end deffn

@geindex ast コマンドラインオプション; --show-empty
@anchor{library/ast cmdoption-ast-show-empty}@anchor{1c5}
@deffn {Option} @w{-}@w{-}show@w{-}empty

Show empty lists and fields that are @code{None}. Defaults to not showing empty
objects.


Added in version 3.14.

@end deffn

@code{infile} を指定するとその内容が AST にパースされて標準出力に出力されます。そうでない場合は標準入力から入力を読み込みます。


@subsubheading 参考


外部ドキュメント Green Tree Snakes@footnote{https://greentreesnakes.readthedocs.io/} には Python AST についての詳細が書かれています。

ASTTokens@footnote{https://asttokens.readthedocs.io/en/latest/user-guide.html} は Python AST を、生成元のソースコードのトークン位置やテキストで注解します。これはソースコード変換を行うツールで有用です。

leoAst.py@footnote{https://leo-editor.github.io/leo-editor/appendices.html#leoast-py}
unifies the
token-based and parse-tree-based views of python programs by inserting
two-way links between tokens and ast nodes.

LibCST@footnote{https://libcst.readthedocs.io/} はコードを ast ツリーに似た構文木 (Concrete Syntax Tree) にパースし、かつ全ての書式設定の詳細を保持します。これは自動リファクタリングアプリケーション (codemod) やリンタを作成する際に有用です。

Parso@footnote{https://parso.readthedocs.io} 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.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node symtable --- コンパイラーの記号表へのアクセス,token --- Python 解析木で使われる定数,ast --- Abstract syntax trees,Python言語サービス
@anchor{library/symtable doc}@anchor{4be7}@anchor{library/symtable module-symtable}@anchor{de}@anchor{library/symtable symtable-access-to-the-compiler-s-symbol-tables}@anchor{4be8}@anchor{library/symtable translation-repo}@anchor{4be9}
@subsection @code{symtable} --- コンパイラーの記号表へのアクセス


@geindex module; symtable

`ソースコード:' Lib/symtable.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/symtable.py}


__________________________________________________________________


Symbol tables are generated by the compiler from AST just before bytecode is
generated.  The symbol table is responsible for calculating the scope of every
identifier in the code.  @code{symtable} provides an interface to examine these
tables.

@menu
* 記号表の生成:: 
* 記号表の検査:: 
* コマンドラインからの使用: コマンドラインからの使用<3>. 

@end menu

@node 記号表の生成,記号表の検査,,symtable --- コンパイラーの記号表へのアクセス
@anchor{library/symtable generating-symbol-tables}@anchor{4bea}
@subsubsection 記号表の生成


@geindex symtable() (symtable モジュール)
@anchor{library/symtable symtable symtable}@anchor{1dd1}
@deffn {の関数} symtable.symtable (code, filename, compile_type)

Python ソース `code' に対するトップレベルの @ref{4beb,,SymbolTable} を返します。 `filename' はコードを収めてあるファイルの名前です。 `compile_type' は @ref{4b1,,compile()} の `mode' 引数のようなものです。
@end deffn

@node 記号表の検査,コマンドラインからの使用<3>,記号表の生成,symtable --- コンパイラーの記号表へのアクセス
@anchor{library/symtable examining-symbol-tables}@anchor{4bec}
@subsubsection 記号表の検査


@geindex SymbolTableType (symtable のクラス)
@anchor{library/symtable symtable SymbolTableType}@anchor{1952}
@deffn {クラス} symtable.SymbolTableType

An enumeration indicating the type of a @ref{4beb,,SymbolTable} object.

@geindex MODULE (symtable.SymbolTableType の属性)
@anchor{library/symtable symtable SymbolTableType MODULE}@anchor{4bed}
@deffn {の属性} MODULE = "module"

Used for the symbol table of a module.
@end deffn

@geindex FUNCTION (symtable.SymbolTableType の属性)
@anchor{library/symtable symtable SymbolTableType FUNCTION}@anchor{4bee}
@deffn {の属性} FUNCTION = "function"

Used for the symbol table of a function.
@end deffn

@geindex CLASS (symtable.SymbolTableType の属性)
@anchor{library/symtable symtable SymbolTableType CLASS}@anchor{4bef}
@deffn {の属性} CLASS = "class"

Used for the symbol table of a class.
@end deffn

The following members refer to different flavors of
@ref{4ab,,annotation scopes}.

@geindex ANNOTATION (symtable.SymbolTableType の属性)
@anchor{library/symtable symtable SymbolTableType ANNOTATION}@anchor{4bf0}
@deffn {の属性} ANNOTATION = "annotation"

Used for annotations if @code{from __future__ import annotations} is active.
@end deffn

@geindex TYPE_ALIAS (symtable.SymbolTableType の属性)
@anchor{library/symtable symtable SymbolTableType TYPE_ALIAS}@anchor{4bf1}
@deffn {の属性} TYPE_ALIAS = "type alias"

Used for the symbol table of @ref{66d,,type} constructions.
@end deffn

@geindex TYPE_PARAMETERS (symtable.SymbolTableType の属性)
@anchor{library/symtable symtable SymbolTableType TYPE_PARAMETERS}@anchor{4bf2}
@deffn {の属性} TYPE_PARAMETERS = "type parameters"

Used for the symbol table of @ref{682,,generic functions}
or @ref{2377,,generic classes}.
@end deffn

@geindex TYPE_VARIABLE (symtable.SymbolTableType の属性)
@anchor{library/symtable symtable SymbolTableType TYPE_VARIABLE}@anchor{4bf3}
@deffn {の属性} TYPE_VARIABLE = "type variable"

Used for the symbol table of the bound, the constraint tuple or the
default value of a single type variable in the formal sense, i.e.,
a TypeVar, a TypeVarTuple or a ParamSpec object (the latter two do
not support a bound or a constraint tuple).
@end deffn


Added in version 3.13.

@end deffn

@geindex SymbolTable (symtable のクラス)
@anchor{library/symtable symtable SymbolTable}@anchor{4beb}
@deffn {クラス} symtable.SymbolTable

ブロックに対する名前空間の記号表。コンストラクタはパブリックではありません。

@geindex get_type() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable get_type}@anchor{1953}
@deffn {メソッド} get_type ()

Return the type of the symbol table.  Possible values are members
of the @ref{1952,,SymbolTableType} enumeration.


バージョン 3.12 で変更: Added @code{'annotation'},  @code{'TypeVar bound'}, @code{'type alias'},
and @code{'type parameter'} as possible return values.



バージョン 3.13 で変更: Return values are members of the @ref{1952,,SymbolTableType} enumeration.

The exact values of the returned string may change in the future,
and thus, it is recommended to use @ref{1952,,SymbolTableType} members
instead of hard-coded strings.

@end deffn

@geindex get_id() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable get_id}@anchor{4bf4}
@deffn {メソッド} get_id ()

記号表の識別子を返します。
@end deffn

@geindex get_name() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable get_name}@anchor{4bf5}
@deffn {メソッド} get_name ()

Return the table's name.  This is the name of the class if the table is
for a class, the name of the function if the table is for a function, or
@code{'top'} if the table is global (@ref{1953,,get_type()} returns @code{'module'}).
For type parameter scopes (which are used for generic classes, functions,
and type aliases), it is the name of the underlying class, function, or
type alias. For type alias scopes, it is the name of the type alias.
For @ref{486,,TypeVar} bound scopes, it is the name of the @code{TypeVar}.
@end deffn

@geindex get_lineno() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable get_lineno}@anchor{4bf6}
@deffn {メソッド} get_lineno ()

この記号表に対応するブロックの一行目の行番号を返します。
@end deffn

@geindex is_optimized() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable is_optimized}@anchor{4bf7}
@deffn {メソッド} is_optimized ()

この記号表に含まれるローカル変数が最適化できるならば @code{True} を返します。
@end deffn

@geindex is_nested() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable is_nested}@anchor{4bf8}
@deffn {メソッド} is_nested ()

ブロックが入れ子のクラスまたは関数のとき @code{True} を返します。
@end deffn

@geindex has_children() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable has_children}@anchor{4bf9}
@deffn {メソッド} has_children ()

ブロックが入れ子の名前空間を含んでいるならば @code{True} を返します。入れ子の名前空間は @ref{4bfa,,get_children()} で得られます。
@end deffn

@geindex get_identifiers() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable get_identifiers}@anchor{4bfb}
@deffn {メソッド} get_identifiers ()

Return a view object containing the names of symbols in the table.
See the @ref{2618,,documentation of view objects}.
@end deffn

@geindex lookup() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable lookup}@anchor{4bfc}
@deffn {メソッド} lookup (name)

記号表から名前 `name' を見つけ出して @ref{289,,Symbol} インスタンスとして返します。
@end deffn

@geindex get_symbols() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable get_symbols}@anchor{4bfd}
@deffn {メソッド} get_symbols ()

記号表中の名前を表す @ref{289,,Symbol} インスタンスのリストを返します。
@end deffn

@geindex get_children() (symtable.SymbolTable のメソッド)
@anchor{library/symtable symtable SymbolTable get_children}@anchor{4bfa}
@deffn {メソッド} get_children ()

入れ子になった記号表のリストを返します。
@end deffn
@end deffn

@geindex Function (symtable のクラス)
@anchor{library/symtable symtable Function}@anchor{4bfe}
@deffn {クラス} symtable.Function

A namespace for a function or method.  This class inherits from
@ref{4beb,,SymbolTable}.

@geindex get_parameters() (symtable.Function のメソッド)
@anchor{library/symtable symtable Function get_parameters}@anchor{4bff}
@deffn {メソッド} get_parameters ()

この関数の引数名からなるタプルを返します。
@end deffn

@geindex get_locals() (symtable.Function のメソッド)
@anchor{library/symtable symtable Function get_locals}@anchor{4c00}
@deffn {メソッド} get_locals ()

この関数のローカル変数の名前からなるタプルを返します。
@end deffn

@geindex get_globals() (symtable.Function のメソッド)
@anchor{library/symtable symtable Function get_globals}@anchor{4c01}
@deffn {メソッド} get_globals ()

この関数のグローバル変数の名前からなるタプルを返します。
@end deffn

@geindex get_nonlocals() (symtable.Function のメソッド)
@anchor{library/symtable symtable Function get_nonlocals}@anchor{4c02}
@deffn {メソッド} get_nonlocals ()

Return a tuple containing names of explicitly declared nonlocals in this function.
@end deffn

@geindex get_frees() (symtable.Function のメソッド)
@anchor{library/symtable symtable Function get_frees}@anchor{4c03}
@deffn {メソッド} get_frees ()

Return a tuple containing names of @ref{1893,,free (closure) variables}
in this function.
@end deffn
@end deffn

@geindex Class (symtable のクラス)
@anchor{library/symtable symtable Class}@anchor{4c04}
@deffn {クラス} symtable.Class

A namespace of a class.  This class inherits from @ref{4beb,,SymbolTable}.

@geindex get_methods() (symtable.Class のメソッド)
@anchor{library/symtable symtable Class get_methods}@anchor{31d}
@deffn {メソッド} get_methods ()

Return a tuple containing the names of method-like functions declared
in the class.

Here, the term 'method' designates `any' function defined in the class
body via @ref{1673,,def} or @ref{7ed,,async def}.

Functions defined in a deeper scope (e.g., in an inner class) are not
picked up by @ref{31d,,get_methods()}.

例えば:

@c import warnings
@c context = warnings.catch_warnings()
@c context.__enter__()
@c warnings.simplefilter("ignore", category=DeprecationWarning)

@c context.__exit__()

@example
>>> import symtable
>>> st = symtable.symtable('@w{'}'
... def outer(): pass
...
... class A:
...    def f():
...        def w(): pass
...
...    def g(self): pass
...
...    @@classmethod
...    async def h(cls): pass
...
...    global outer
...    def outer(self): pass
... '@w{'}', 'test', 'exec')
>>> class_A = st.get_children()[2]
>>> class_A.get_methods()
('f', 'g', 'h')
@end example

Although @code{A().f()} raises @ref{198,,TypeError} at runtime, @code{A.f} is still
considered as a method-like function.


Deprecated since version 3.14, will be removed in version 3.16.

@end deffn
@end deffn

@geindex Symbol (symtable のクラス)
@anchor{library/symtable symtable Symbol}@anchor{289}
@deffn {クラス} symtable.Symbol

@ref{4beb,,SymbolTable} のエントリーでソースの識別子に対応するものです。コンストラクタはパブリックではありません。

@geindex get_name() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol get_name}@anchor{4c05}
@deffn {メソッド} get_name ()

記号の名前を返します。
@end deffn

@geindex is_referenced() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_referenced}@anchor{4c06}
@deffn {メソッド} is_referenced ()

記号がそのブロックの中で使われていれば @code{True} を返します。
@end deffn

@geindex is_imported() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_imported}@anchor{4c07}
@deffn {メソッド} is_imported ()

記号が import 文で作られたものならば @code{True} を返します。
@end deffn

@geindex is_parameter() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_parameter}@anchor{4c08}
@deffn {メソッド} is_parameter ()

記号がパラメータならば @code{True} を返します。
@end deffn

@geindex is_type_parameter() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_type_parameter}@anchor{1954}
@deffn {メソッド} is_type_parameter ()

Return @code{True} if the symbol is a type parameter.


Added in version 3.14.

@end deffn

@geindex is_global() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_global}@anchor{4c09}
@deffn {メソッド} is_global ()

記号がグローバルならば @code{True} を返します。
@end deffn

@geindex is_nonlocal() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_nonlocal}@anchor{1e0d}
@deffn {メソッド} is_nonlocal ()

記号が非ローカルならば @code{True} を返します。
@end deffn

@geindex is_declared_global() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_declared_global}@anchor{153d}
@deffn {メソッド} is_declared_global ()

記号が global 文によってグローバルであると宣言されているなら @code{True} を返します。
@end deffn

@geindex is_local() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_local}@anchor{4c0a}
@deffn {メソッド} is_local ()

記号がそのブロックに対してローカルならば @code{True} を返します。
@end deffn

@geindex is_annotated() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_annotated}@anchor{4c0b}
@deffn {メソッド} is_annotated ()

記号が注釈付きならば @code{True} を返します。


Added in version 3.6.

@end deffn

@geindex is_free() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_free}@anchor{4c0c}
@deffn {メソッド} is_free ()

記号がそのブロックの中で参照されていて、しかし代入は行われないならば @code{True} を返します。
@end deffn

@geindex is_free_class() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_free_class}@anchor{28c}
@deffn {メソッド} is_free_class ()

Return `True' if a class-scoped symbol is free from
the perspective of a method.

次に示す例について考えてみてください。:

@example
def f():
    x = 1  # function-scoped
    class C:
        x = 2  # class-scoped
        def method(self):
            return x
@end example

In this example, the class-scoped symbol @code{x} is considered to
be free from the perspective of @code{C.method}, thereby allowing
the latter to return `1' at runtime and not `2'.


Added in version 3.14.

@end deffn

@geindex is_assigned() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_assigned}@anchor{4c0d}
@deffn {メソッド} is_assigned ()

記号がそのブロックの中で代入されているならば @code{True} を返します。
@end deffn

@geindex is_comp_iter() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_comp_iter}@anchor{28b}
@deffn {メソッド} is_comp_iter ()

Return @code{True} if the symbol is a comprehension iteration variable.


Added in version 3.14.

@end deffn

@geindex is_comp_cell() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_comp_cell}@anchor{28a}
@deffn {メソッド} is_comp_cell ()

Return @code{True} if the symbol is a cell in an inlined comprehension.


Added in version 3.14.

@end deffn

@geindex is_namespace() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol is_namespace}@anchor{4c0e}
@deffn {メソッド} is_namespace ()

名前の束縛が新たな名前空間を導入するならば @code{True} を返します。

名前が関数または class 文のターゲットとして使われるならば、真です。

例えば:

@example
>>> table = symtable.symtable("def some_func(): pass", "string", "exec")
>>> table.lookup("some_func").is_namespace()
True
@end example

一つの名前が複数のオブジェクトに束縛されうることに注意しましょう。結果が @code{True} であったとしても、その名前は他のオブジェクトにも束縛されるかもしれず、それがたとえば整数やリストであれば、そこでは新たな名前空間は導入されません。
@end deffn

@geindex get_namespaces() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol get_namespaces}@anchor{4c0f}
@deffn {メソッド} get_namespaces ()

この名前に束縛された名前空間のリストを返します。
@end deffn

@geindex get_namespace() (symtable.Symbol のメソッド)
@anchor{library/symtable symtable Symbol get_namespace}@anchor{4c10}
@deffn {メソッド} get_namespace ()

この名前に束縛された名前空間を返します。この名前に束縛された名前空間が複数あるか一つもないなら @ref{2ec,,ValueError} が送出されます。
@end deffn
@end deffn

@node コマンドラインからの使用<3>,,記号表の検査,symtable --- コンパイラーの記号表へのアクセス
@anchor{library/symtable command-line-usage}@anchor{4c11}@anchor{library/symtable symtable-cli}@anchor{4c12}
@subsubsection コマンドラインからの使用



Added in version 3.13.


The @code{symtable} module can be executed as a script from the command line.

@example
python -m symtable [infile...]
@end example

Symbol tables are generated for the specified Python source files and
dumped to stdout.
If no input file is specified, the content is read from stdin.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node token --- Python 解析木で使われる定数,keyword --- Python キーワードのテスト,symtable --- コンパイラーの記号表へのアクセス,Python言語サービス
@anchor{library/token doc}@anchor{4c13}@anchor{library/token module-token}@anchor{100}@anchor{library/token token-constants-used-with-python-parse-trees}@anchor{4c14}@anchor{library/token translation-repo}@anchor{4c15}
@subsection @code{token} --- Python 解析木で使われる定数


@geindex module; token

`ソースコード:' Lib/token.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/token.py}


__________________________________________________________________


このモジュールは解析木の葉ノード(終端記号)の数値を表す定数を提供します。言語の文法のコンテキストにおける名前の定義については、 Python ディストリビューションのファイル file:@cite{Grammar/Tokens} を参照してください。名前がマップする特定の数値は Python のバージョン間で変わります。

このモジュールは、数値コードから名前へのマッピングと、いくつかの関数も提供しています。関数は Python の C ヘッダファイルの定義を反映します。

Note that a token's value may depend on tokenizer options. For example, a
@code{"+"} token may be reported as either @ref{4c16,,PLUS} or @ref{228a,,OP}, or
a @code{"match"} token may be either @ref{22b9,,NAME} or @ref{4c17,,SOFT_KEYWORD}.

@geindex tok_name (token モジュール)
@anchor{library/token token tok_name}@anchor{4c18}
@deffn {データ} token.tok_name

ディクショナリはこのモジュールで定義されている定数の数値を名前の文字列へマップし、より人が読みやすいように解析木を表現します。
@end deffn

@geindex ISTERMINAL() (token モジュール)
@anchor{library/token token ISTERMINAL}@anchor{4c19}
@deffn {の関数} token.ISTERMINAL (x)

終端トークンの値に対して @code{True} を返します。
@end deffn

@geindex ISNONTERMINAL() (token モジュール)
@anchor{library/token token ISNONTERMINAL}@anchor{4c1a}
@deffn {の関数} token.ISNONTERMINAL (x)

非終端トークンの値に対して @code{True} を返します。
@end deffn

@geindex ISEOF() (token モジュール)
@anchor{library/token token ISEOF}@anchor{4c1b}
@deffn {の関数} token.ISEOF (x)

`x' が入力の終わりを示すマーカーならば、 @code{True} を返します。
@end deffn

token の定数一覧:

@geindex NAME (token モジュール)
@anchor{library/token token NAME}@anchor{22b9}
@deffn {データ} token.NAME

Token value that indicates an @ref{22a0,,identifier or keyword}.
@end deffn

@geindex NUMBER (token モジュール)
@anchor{library/token token NUMBER}@anchor{22ba}
@deffn {データ} token.NUMBER

Token value that indicates a @ref{22a1,,numeric literal}
@end deffn

@geindex STRING (token モジュール)
@anchor{library/token token STRING}@anchor{22bb}
@deffn {データ} token.STRING

Token value that indicates a @ref{229f,,string or byte literal},
excluding @ref{19a,,formatted string literals}.
The token string is not interpreted:
it includes the surrounding quotation marks and the prefix (if given);
backslashes are included literally, without processing escape sequences.
@end deffn

@geindex OP (token モジュール)
@anchor{library/token token OP}@anchor{228a}
@deffn {データ} token.OP

A generic token value that indicates an
@ref{228c,,operator} or @ref{228b,,delimiter}.

`CPython 実装の詳細:' This value is only reported by the @ref{101,,tokenize} module.
Internally, the tokenizer uses
@ref{231e,,exact token types} instead.
@end deffn

@geindex COMMENT (token モジュール)
@anchor{library/token token COMMENT}@anchor{4c1c}
@deffn {データ} token.COMMENT

Token value used to indicate a comment.
The parser ignores @code{COMMENT} tokens.
@end deffn

@geindex NEWLINE (token モジュール)
@anchor{library/token token NEWLINE}@anchor{2294}
@deffn {データ} token.NEWLINE

Token value that indicates the end of a @ref{22a5,,logical line}.
@end deffn

@geindex NL (token モジュール)
@anchor{library/token token NL}@anchor{4c1d}
@deffn {データ} token.NL

Token value used to indicate a non-terminating newline.
@code{NL} tokens are generated when a logical line of code is continued
over multiple physical lines. The parser ignores @code{NL} tokens.
@end deffn

@geindex INDENT (token モジュール)
@anchor{library/token token INDENT}@anchor{20fd}
@deffn {データ} token.INDENT

Token value used at the beginning of a @ref{22a5,,logical line}
to indicate the start of an @ref{229c,,indented block}.
@end deffn

@geindex DEDENT (token モジュール)
@anchor{library/token token DEDENT}@anchor{22b2}
@deffn {データ} token.DEDENT

Token value used at the beginning of a @ref{22a5,,logical line}
to indicate the end of an @ref{229c,,indented block}.
@end deffn

@geindex FSTRING_START (token モジュール)
@anchor{library/token token FSTRING_START}@anchor{22f1}
@deffn {データ} token.FSTRING_START

Token value used to indicate the beginning of an
@ref{19a,,f-string literal}.

`CPython 実装の詳細:' The token string includes the prefix and the opening quote(s), but none
of the contents of the literal.
@end deffn

@geindex FSTRING_MIDDLE (token モジュール)
@anchor{library/token token FSTRING_MIDDLE}@anchor{22f2}
@deffn {データ} token.FSTRING_MIDDLE

Token value used for literal text inside an @ref{19a,,f-string literal},
including format specifications.

`CPython 実装の詳細:' Replacement fields (that is, the non-literal parts of f-strings) use
the same tokens as other expressions, and are delimited by
@ref{4c1e,,LBRACE}, @ref{4c1f,,RBRACE}, @ref{4c20,,EXCLAMATION} and @ref{4c21,,COLON}
tokens.
@end deffn

@geindex FSTRING_END (token モジュール)
@anchor{library/token token FSTRING_END}@anchor{22f3}
@deffn {データ} token.FSTRING_END

Token value used to indicate the end of a @ref{19a,,f-string}.

`CPython 実装の詳細:' The token string contains the closing quote(s).
@end deffn

@geindex TSTRING_START (token モジュール)
@anchor{library/token token TSTRING_START}@anchor{4c22}
@deffn {データ} token.TSTRING_START

Token value used to indicate the beginning of a template string literal.

`CPython 実装の詳細:' The token string includes the prefix and the opening quote(s), but none
of the contents of the literal.


Added in version 3.14.

@end deffn

@geindex TSTRING_MIDDLE (token モジュール)
@anchor{library/token token TSTRING_MIDDLE}@anchor{4c23}
@deffn {データ} token.TSTRING_MIDDLE

Token value used for literal text inside a template string literal
including format specifications.

`CPython 実装の詳細:' Replacement fields (that is, the non-literal parts of t-strings) use
the same tokens as other expressions, and are delimited by
@ref{4c1e,,LBRACE}, @ref{4c1f,,RBRACE}, @ref{4c20,,EXCLAMATION} and @ref{4c21,,COLON}
tokens.


Added in version 3.14.

@end deffn

@geindex TSTRING_END (token モジュール)
@anchor{library/token token TSTRING_END}@anchor{4c24}
@deffn {データ} token.TSTRING_END

Token value used to indicate the end of a template string literal.

`CPython 実装の詳細:' The token string contains the closing quote(s).


Added in version 3.14.

@end deffn

@geindex ENDMARKER (token モジュール)
@anchor{library/token token ENDMARKER}@anchor{22b6}
@deffn {データ} token.ENDMARKER

Token value that indicates the end of input.
Used in @ref{259a,,top-level grammar rules}.
@end deffn

@geindex ENCODING (token モジュール)
@anchor{library/token token ENCODING}@anchor{4c25}
@deffn {データ} token.ENCODING

ソースの bytes をテキストにデコードするために使われるエンコーディングを示すトークン値。@ref{700,,tokenize.tokenize()} は常に最初に ENCODING トークンを返します。

`CPython 実装の詳細:' This token type isn't used by the C tokenizer but is needed for
the @ref{101,,tokenize} module.
@end deffn

The following token types are not produced by the @ref{101,,tokenize} module,
and are defined for special uses in the tokenizer or parser:

@geindex TYPE_IGNORE (token モジュール)
@anchor{library/token token TYPE_IGNORE}@anchor{4c26}
@deffn {データ} token.TYPE_IGNORE

Token value indicating that a @code{type: ignore} comment was recognized.
Such tokens are produced instead of regular @ref{4c1c,,COMMENT} tokens only
with the @ref{4bcf,,PyCF_TYPE_COMMENTS} flag.
@end deffn

@geindex TYPE_COMMENT (token モジュール)
@anchor{library/token token TYPE_COMMENT}@anchor{4c27}
@deffn {データ} token.TYPE_COMMENT

Token value indicating that a type comment was recognized.
Such tokens are produced instead of regular @ref{4c1c,,COMMENT} tokens only
with the @ref{4bcf,,PyCF_TYPE_COMMENTS} flag.
@end deffn

@geindex SOFT_KEYWORD (token モジュール)
@anchor{library/token token SOFT_KEYWORD}@anchor{4c17}
@deffn {データ} token.SOFT_KEYWORD

Token value indicating a @ref{a0d,,soft keyword}.

The tokenizer never produces this value.
To check for a soft keyword, pass a @ref{22b9,,NAME} token's string to
@ref{4c28,,keyword.issoftkeyword()}.
@end deffn

@geindex ERRORTOKEN (token モジュール)
@anchor{library/token token ERRORTOKEN}@anchor{4c29}
@deffn {データ} token.ERRORTOKEN

Token value used to indicate wrong input.

The @ref{101,,tokenize} module generally indicates errors by
raising exceptions instead of emitting this token.
It can also emit tokens such as @ref{228a,,OP} or @ref{22b9,,NAME} with strings that
are later rejected by the parser.
@end deffn
@anchor{library/token token-operators-delimiters}@anchor{231e}
The remaining tokens represent specific @ref{228c,,operators} and
@ref{228b,,delimiters}.
(The @ref{101,,tokenize} module reports these as @ref{228a,,OP}; see @code{exact_type}
in the @ref{101,,tokenize} documentation for details.)

@c Auto-generated by Tools/build/generate_token.py


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Token

@tab

値

@item

@geindex LPAR (token モジュール)
@anchor{library/token token LPAR}@anchor{4c2a}
@deffn {データ} token.LPAR
@end deffn

@tab

@code{"("}

@item

@geindex RPAR (token モジュール)
@anchor{library/token token RPAR}@anchor{4c2b}
@deffn {データ} token.RPAR
@end deffn

@tab

@code{")"}

@item

@geindex LSQB (token モジュール)
@anchor{library/token token LSQB}@anchor{4c2c}
@deffn {データ} token.LSQB
@end deffn

@tab

@code{"["}

@item

@geindex RSQB (token モジュール)
@anchor{library/token token RSQB}@anchor{4c2d}
@deffn {データ} token.RSQB
@end deffn

@tab

@code{"]"}

@item

@geindex COLON (token モジュール)
@anchor{library/token token COLON}@anchor{4c21}
@deffn {データ} token.COLON
@end deffn

@tab

@code{":"}

@item

@geindex COMMA (token モジュール)
@anchor{library/token token COMMA}@anchor{4c2e}
@deffn {データ} token.COMMA
@end deffn

@tab

@code{","}

@item

@geindex SEMI (token モジュール)
@anchor{library/token token SEMI}@anchor{4c2f}
@deffn {データ} token.SEMI
@end deffn

@tab

@code{";"}

@item

@geindex PLUS (token モジュール)
@anchor{library/token token PLUS}@anchor{4c16}
@deffn {データ} token.PLUS
@end deffn

@tab

@code{"+"}

@item

@geindex MINUS (token モジュール)
@anchor{library/token token MINUS}@anchor{4c30}
@deffn {データ} token.MINUS
@end deffn

@tab

@code{"-"}

@item

@geindex STAR (token モジュール)
@anchor{library/token token STAR}@anchor{4c31}
@deffn {データ} token.STAR
@end deffn

@tab

@code{"*"}

@item

@geindex SLASH (token モジュール)
@anchor{library/token token SLASH}@anchor{4c32}
@deffn {データ} token.SLASH
@end deffn

@tab

@code{"/"}

@item

@geindex VBAR (token モジュール)
@anchor{library/token token VBAR}@anchor{4c33}
@deffn {データ} token.VBAR
@end deffn

@tab

@code{"|"}

@item

@geindex AMPER (token モジュール)
@anchor{library/token token AMPER}@anchor{4c34}
@deffn {データ} token.AMPER
@end deffn

@tab

@code{"&"}

@item

@geindex LESS (token モジュール)
@anchor{library/token token LESS}@anchor{4c35}
@deffn {データ} token.LESS
@end deffn

@tab

@code{"<"}

@item

@geindex GREATER (token モジュール)
@anchor{library/token token GREATER}@anchor{4c36}
@deffn {データ} token.GREATER
@end deffn

@tab

@code{">"}

@item

@geindex EQUAL (token モジュール)
@anchor{library/token token EQUAL}@anchor{4c37}
@deffn {データ} token.EQUAL
@end deffn

@tab

@code{"="}

@item

@geindex DOT (token モジュール)
@anchor{library/token token DOT}@anchor{4c38}
@deffn {データ} token.DOT
@end deffn

@tab

@code{"."}

@item

@geindex PERCENT (token モジュール)
@anchor{library/token token PERCENT}@anchor{4c39}
@deffn {データ} token.PERCENT
@end deffn

@tab

@code{"%"}

@item

@geindex LBRACE (token モジュール)
@anchor{library/token token LBRACE}@anchor{4c1e}
@deffn {データ} token.LBRACE
@end deffn

@tab

@code{"@{"}

@item

@geindex RBRACE (token モジュール)
@anchor{library/token token RBRACE}@anchor{4c1f}
@deffn {データ} token.RBRACE
@end deffn

@tab

@code{"@}"}

@item

@geindex EQEQUAL (token モジュール)
@anchor{library/token token EQEQUAL}@anchor{4c3a}
@deffn {データ} token.EQEQUAL
@end deffn

@tab

@code{"=="}

@item

@geindex NOTEQUAL (token モジュール)
@anchor{library/token token NOTEQUAL}@anchor{4c3b}
@deffn {データ} token.NOTEQUAL
@end deffn

@tab

@code{"!="}

@item

@geindex LESSEQUAL (token モジュール)
@anchor{library/token token LESSEQUAL}@anchor{4c3c}
@deffn {データ} token.LESSEQUAL
@end deffn

@tab

@code{"<="}

@item

@geindex GREATEREQUAL (token モジュール)
@anchor{library/token token GREATEREQUAL}@anchor{4c3d}
@deffn {データ} token.GREATEREQUAL
@end deffn

@tab

@code{">="}

@item

@geindex TILDE (token モジュール)
@anchor{library/token token TILDE}@anchor{4c3e}
@deffn {データ} token.TILDE
@end deffn

@tab

@code{"~"}

@item

@geindex CIRCUMFLEX (token モジュール)
@anchor{library/token token CIRCUMFLEX}@anchor{4c3f}
@deffn {データ} token.CIRCUMFLEX
@end deffn

@tab

@code{"^"}

@item

@geindex LEFTSHIFT (token モジュール)
@anchor{library/token token LEFTSHIFT}@anchor{4c40}
@deffn {データ} token.LEFTSHIFT
@end deffn

@tab

@code{"<<"}

@item

@geindex RIGHTSHIFT (token モジュール)
@anchor{library/token token RIGHTSHIFT}@anchor{4c41}
@deffn {データ} token.RIGHTSHIFT
@end deffn

@tab

@code{">>"}

@item

@geindex DOUBLESTAR (token モジュール)
@anchor{library/token token DOUBLESTAR}@anchor{4c42}
@deffn {データ} token.DOUBLESTAR
@end deffn

@tab

@code{"**"}

@item

@geindex PLUSEQUAL (token モジュール)
@anchor{library/token token PLUSEQUAL}@anchor{4c43}
@deffn {データ} token.PLUSEQUAL
@end deffn

@tab

@code{"+="}

@item

@geindex MINEQUAL (token モジュール)
@anchor{library/token token MINEQUAL}@anchor{4c44}
@deffn {データ} token.MINEQUAL
@end deffn

@tab

@code{"-="}

@item

@geindex STAREQUAL (token モジュール)
@anchor{library/token token STAREQUAL}@anchor{4c45}
@deffn {データ} token.STAREQUAL
@end deffn

@tab

@code{"*="}

@item

@geindex SLASHEQUAL (token モジュール)
@anchor{library/token token SLASHEQUAL}@anchor{4c46}
@deffn {データ} token.SLASHEQUAL
@end deffn

@tab

@code{"/="}

@item

@geindex PERCENTEQUAL (token モジュール)
@anchor{library/token token PERCENTEQUAL}@anchor{4c47}
@deffn {データ} token.PERCENTEQUAL
@end deffn

@tab

@code{"%="}

@item

@geindex AMPEREQUAL (token モジュール)
@anchor{library/token token AMPEREQUAL}@anchor{4c48}
@deffn {データ} token.AMPEREQUAL
@end deffn

@tab

@code{"&="}

@item

@geindex VBAREQUAL (token モジュール)
@anchor{library/token token VBAREQUAL}@anchor{4c49}
@deffn {データ} token.VBAREQUAL
@end deffn

@tab

@code{"|="}

@item

@geindex CIRCUMFLEXEQUAL (token モジュール)
@anchor{library/token token CIRCUMFLEXEQUAL}@anchor{4c4a}
@deffn {データ} token.CIRCUMFLEXEQUAL
@end deffn

@tab

@code{"^="}

@item

@geindex LEFTSHIFTEQUAL (token モジュール)
@anchor{library/token token LEFTSHIFTEQUAL}@anchor{4c4b}
@deffn {データ} token.LEFTSHIFTEQUAL
@end deffn

@tab

@code{"<<="}

@item

@geindex RIGHTSHIFTEQUAL (token モジュール)
@anchor{library/token token RIGHTSHIFTEQUAL}@anchor{4c4c}
@deffn {データ} token.RIGHTSHIFTEQUAL
@end deffn

@tab

@code{">>="}

@item

@geindex DOUBLESTAREQUAL (token モジュール)
@anchor{library/token token DOUBLESTAREQUAL}@anchor{4c4d}
@deffn {データ} token.DOUBLESTAREQUAL
@end deffn

@tab

@code{"**="}

@item

@geindex DOUBLESLASH (token モジュール)
@anchor{library/token token DOUBLESLASH}@anchor{4c4e}
@deffn {データ} token.DOUBLESLASH
@end deffn

@tab

@code{"//"}

@item

@geindex DOUBLESLASHEQUAL (token モジュール)
@anchor{library/token token DOUBLESLASHEQUAL}@anchor{4c4f}
@deffn {データ} token.DOUBLESLASHEQUAL
@end deffn

@tab

@code{"//="}

@item

@geindex AT (token モジュール)
@anchor{library/token token AT}@anchor{4c50}
@deffn {データ} token.AT
@end deffn

@tab

@code{"@@"}

@item

@geindex ATEQUAL (token モジュール)
@anchor{library/token token ATEQUAL}@anchor{4c51}
@deffn {データ} token.ATEQUAL
@end deffn

@tab

@code{"@@="}

@item

@geindex RARROW (token モジュール)
@anchor{library/token token RARROW}@anchor{4c52}
@deffn {データ} token.RARROW
@end deffn

@tab

@code{"->"}

@item

@geindex ELLIPSIS (token モジュール)
@anchor{library/token token ELLIPSIS}@anchor{4c53}
@deffn {データ} token.ELLIPSIS
@end deffn

@tab

@code{"..."}

@item

@geindex COLONEQUAL (token モジュール)
@anchor{library/token token COLONEQUAL}@anchor{4c54}
@deffn {データ} token.COLONEQUAL
@end deffn

@tab

@code{":="}

@item

@geindex EXCLAMATION (token モジュール)
@anchor{library/token token EXCLAMATION}@anchor{4c20}
@deffn {データ} token.EXCLAMATION
@end deffn

@tab

@code{"!"}

@end multitable


The following non-token constants are provided:

@geindex N_TOKENS (token モジュール)
@anchor{library/token token N_TOKENS}@anchor{4c55}
@deffn {データ} token.N_TOKENS

The number of token types defined in this module.
@end deffn

@c NT_OFFSET is deliberately undocumented; if you need it you should be
@c reading the source

@geindex EXACT_TOKEN_TYPES (token モジュール)
@anchor{library/token token EXACT_TOKEN_TYPES}@anchor{18e7}
@deffn {データ} token.EXACT_TOKEN_TYPES

A dictionary mapping the string representation of a token to its numeric code.


Added in version 3.8.

@end deffn


バージョン 3.5 で変更: Added @code{AWAIT} and @code{ASYNC} tokens.



バージョン 3.7 で変更: @ref{4c1c,,COMMENT} 、@ref{4c1d,,NL}、@ref{4c25,,ENCODING} トークンが追加されました。



バージョン 3.7 で変更: Removed @code{AWAIT} and @code{ASYNC} tokens. "async" and "await" are
now tokenized as @ref{22b9,,NAME} tokens.



バージョン 3.8 で変更: Added @ref{4c27,,TYPE_COMMENT}, @ref{4c26,,TYPE_IGNORE}, @ref{4c54,,COLONEQUAL}.
Added @code{AWAIT} and @code{ASYNC} tokens back (they're needed
to support parsing older Python versions for @ref{1c2,,ast.parse()} with
@code{feature_version} set to 6 or lower).



バージョン 3.12 で変更: Added @ref{4c20,,EXCLAMATION}.



バージョン 3.13 で変更: Removed @code{AWAIT} and @code{ASYNC} tokens again.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node keyword --- Python キーワードのテスト,tokenize --- Python ソース用のトークナイザー,token --- Python 解析木で使われる定数,Python言語サービス
@anchor{library/keyword doc}@anchor{4c56}@anchor{library/keyword keyword-testing-for-python-keywords}@anchor{4c57}@anchor{library/keyword module-keyword}@anchor{88}@anchor{library/keyword translation-repo}@anchor{4c58}
@subsection @code{keyword} --- Python キーワードのテスト


@geindex module; keyword

`ソースコード:' Lib/keyword.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/keyword.py}


__________________________________________________________________


このモジュールでは、Python プログラムで文字列が @ref{2289,,キーワード} や @ref{a0d,,ソフトキーワード} か否かをチェックする機能を提供します。

@geindex iskeyword() (keyword モジュール)
@anchor{library/keyword keyword iskeyword}@anchor{2654}
@deffn {の関数} keyword.iskeyword (s)

`s' が Python の @ref{2289,,キーワード} であれば @code{True} を返します。
@end deffn

@geindex kwlist (keyword モジュール)
@anchor{library/keyword keyword kwlist}@anchor{4c59}
@deffn {データ} keyword.kwlist

インタープリタで定義している全ての @ref{2289,,キーワード} のシーケンス。特定の @ref{0,,__future__} 宣言がなければ有効ではないキーワードでもこのリストには含まれます。
@end deffn

@geindex issoftkeyword() (keyword モジュール)
@anchor{library/keyword keyword issoftkeyword}@anchor{4c28}
@deffn {の関数} keyword.issoftkeyword (s)

`s' が Python の @ref{a0d,,ソフトキーワード} であれば @code{True} を返します。


Added in version 3.9.

@end deffn

@geindex softkwlist (keyword モジュール)
@anchor{library/keyword keyword softkwlist}@anchor{4c5a}
@deffn {データ} keyword.softkwlist

インタープリタで定義している全ての @ref{a0d,,ソフトキーワード} のシーケンス。特定の @ref{0,,__future__} 宣言がなければ有効ではないソフトキーワードでもこのリストには含まれます。


Added in version 3.9.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tokenize --- Python ソース用のトークナイザー,tabnanny --- あいまいなインデントの検出,keyword --- Python キーワードのテスト,Python言語サービス
@anchor{library/tokenize doc}@anchor{4c5b}@anchor{library/tokenize module-tokenize}@anchor{101}@anchor{library/tokenize tokenize-tokenizer-for-python-source}@anchor{4c5c}@anchor{library/tokenize translation-repo}@anchor{4c5d}
@subsection @code{tokenize} --- Python ソース用のトークナイザー


@geindex module; tokenize

`ソースコード:' Lib/tokenize.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tokenize.py}


__________________________________________________________________


The @code{tokenize} module provides a lexical scanner for Python source code,
implemented in Python.  The scanner in this module returns comments as tokens
as well, making it useful for implementing "pretty-printers", including
colorizers for on-screen displays.

トークン・ストリームの扱いをシンプルにするために、全ての @ref{228c,,operator} と @ref{228b,,delimiter} トークンおよび @ref{2328,,Ellipsis} はジェネリックな @ref{228a,,OP} トークンタイプとして返されます。正確な型は @ref{700,,tokenize.tokenize()} が返す @ref{85e,,named tuple} の @code{exact_type} プロパティをチェックすれば解ります。

@cartouche
@quotation 警告 
Note that the functions in this module are only designed to parse
syntactically valid Python code (code that does not raise when parsed
using @ref{1c2,,ast.parse()}).  The behavior of the functions in this module is
`undefined' when providing invalid Python code and it can change at any
point.
@end quotation
@end cartouche

@menu
* 入力のトークナイズ:: 
* コマンドラインからの使用: コマンドラインからの使用<4>. 
* 使用例: 使用例<50>. 

@end menu

@node 入力のトークナイズ,コマンドラインからの使用<4>,,tokenize --- Python ソース用のトークナイザー
@anchor{library/tokenize tokenizing-input}@anchor{4c5e}
@subsubsection 入力のトークナイズ


第一のエントリポイントは @ref{126c,,ジェネレータ} です:

@geindex tokenize() (tokenize モジュール)
@anchor{library/tokenize tokenize tokenize}@anchor{700}
@deffn {の関数} tokenize.tokenize (readline)

@ref{700,,tokenize()} ジェネレータは一つの引数 `readline' を必要とします。この引数は呼び出し可能オブジェクトで、ファイルオブジェクトの @ref{1541,,io.IOBase.readline()} メソッドと同じインタフェースを提供している必要があります。この関数は呼び出しのたびに入力の一行を bytes で返さなければなりません。

このジェネレータは次の5要素のタプルを返します; トークンタイプ; トークン文字列; ソース内でそのトークンがどの行、列で開始するかを示す int の @code{(srow, scol)} タプル; どの行、列で終了するかを示す int の @code{(erow, ecol)} タプル; トークンが見つかった行。 (タプルの最後の要素にある) 行は `物理' 行です。この5要素のタプルは @ref{85e,,named tuple} として返され、フィールド名は @code{type string start end line} になります。

返される @ref{85e,,named tuple} は追加のプロパティ @code{exact_type} を持ちます。このプロパティは @ref{228a,,OP} トークンに対して正確な演算子のタイプを持ちます。それ以外のトークンタイプについては、 @code{exact_type} は @code{type} フィールドと同じ値を持ちます。


バージョン 3.1 で変更: named tuple のサポートを追加。



バージョン 3.3 で変更: @code{exact_type} のサポートを追加。


@ref{700,,tokenize()} は 
@geindex Python Enhancement Proposals; PEP 263
PEP 263@footnote{https://peps.python.org/pep-0263/} にしたがって、ソースのエンコーディングを UTF-8 BOM か encoding cookie を見つけて決定します。
@end deffn

@geindex generate_tokens() (tokenize モジュール)
@anchor{library/tokenize tokenize generate_tokens}@anchor{701}
@deffn {の関数} tokenize.generate_tokens (readline)

Tokenize a source reading unicode strings instead of bytes.

Like @ref{700,,tokenize()}, the `readline' argument is a callable returning
a single line of input. However, @ref{701,,generate_tokens()} expects `readline'
to return a str object rather than bytes.

The result is an iterator yielding named tuples, exactly like
@ref{700,,tokenize()}. It does not yield an @ref{4c25,,ENCODING} token.
@end deffn

All constants from the @ref{100,,token} module are also exported from
@code{tokenize}.

もう一つの関数がトークン化プロセスを逆転するために提供されています。これは、スクリプトを字句解析し、トークンのストリームに変更を加え、変更されたスクリプトを書き戻すようなツールを作成する際に便利です。

@geindex untokenize() (tokenize モジュール)
@anchor{library/tokenize tokenize untokenize}@anchor{18b3}
@deffn {の関数} tokenize.untokenize (iterable)

トークンの列を Python ソースコードに変換します。 `iterable' は少なくとも二つの要素、トークンタイプおよびトークン文字列、からなるシーケンスを返さなければいけません。 その他のシーケンスの要素は無視されます。

The result is guaranteed to tokenize back to match the input so that the
conversion is lossless and round-trips are assured.  The guarantee applies
only to the token type and token string as the spacing between tokens
(column positions) may change.

It returns bytes, encoded using the @ref{4c25,,ENCODING} token, which
is the first token sequence output by @ref{700,,tokenize()}. If there is no
encoding token in the input, it returns a str instead.
@end deffn

@ref{700,,tokenize()} はトークナイズしようとしているソースファイルのエンコーディングを検出する必要があります。これを行うために使っている関数が公開されています:

@geindex detect_encoding() (tokenize モジュール)
@anchor{library/tokenize tokenize detect_encoding}@anchor{17b8}
@deffn {の関数} tokenize.detect_encoding (readline)

@ref{17b8,,detect_encoding()} 関数は Python のソースファイルをデコードするのに使うエンコーディングを検出するために使われます。 @ref{700,,tokenize()} ジェネレータと同じ readline を引数として取ります。

readline を最大2回呼び出し、利用するエンコーディング (文字列として) と、読み込んだ行を (bytes からデコードされないままの状態で) 返します。

UTF-8 BOM か 
@geindex Python Enhancement Proposals; PEP 263
PEP 263@footnote{https://peps.python.org/pep-0263/} で定義されている encoding cookie からエンコーディングを検出します。BOMと cookie の両方が存在し、一致していない場合、@ref{18e,,SyntaxError} が送出されます。 BOM が見つかった場合はエンコーディングとして @code{'utf-8-sig'} が返されます。

エンコーディングが指定されていない場合、デフォルトの @code{'utf-8'} が返されます。

Python のソースファイルを開くには @ref{2cdf,,open()} を使ってください。これは @ref{17b8,,detect_encoding()} を利用してファイルエンコーディングを検出します。
@end deffn

@geindex open() (tokenize モジュール)
@anchor{library/tokenize tokenize open}@anchor{2cdf}
@deffn {の関数} tokenize.open (filename)

@ref{17b8,,detect_encoding()} を使って検出したエンコーディングを利用して、ファイルを読み出し専用モードで開きます。


Added in version 3.2.

@end deffn

@geindex TokenError
@anchor{library/tokenize tokenize TokenError}@anchor{764}
@deffn {例外} tokenize.TokenError

docstring や複数行にわたることが許される式がファイル内のどこかで終わっていない場合に送出されます。例えば:

@example
"""Beginning of
docstring
@end example

もしくは:

@example
[1,
 2,
 3
@end example
@end deffn

@node コマンドラインからの使用<4>,使用例<50>,入力のトークナイズ,tokenize --- Python ソース用のトークナイザー
@anchor{library/tokenize command-line-usage}@anchor{4c5f}@anchor{library/tokenize tokenize-cli}@anchor{4c60}
@subsubsection コマンドラインからの使用



Added in version 3.3.


The @code{tokenize} module can be executed as a script from the command line.
It is as simple as:

@example
python -m tokenize [-e] [filename.py]
@end example

以下のオプションが使用できます:

@geindex tokenize コマンドラインオプション; -h
@geindex tokenize コマンドラインオプション; --help
@anchor{library/tokenize cmdoption-tokenize-h}@anchor{4c61}@anchor{library/tokenize cmdoption-tokenize-help}@anchor{4c62}
@deffn {Option} @w{-}h, @w{-}@w{-}help

このヘルプメッセージを出力して終了します
@end deffn

@geindex tokenize コマンドラインオプション; -e
@geindex tokenize コマンドラインオプション; --exact
@anchor{library/tokenize cmdoption-tokenize-e}@anchor{4c63}@anchor{library/tokenize cmdoption-tokenize-exact}@anchor{4c64}
@deffn {Option} @w{-}e, @w{-}@w{-}exact

exact type を使ってトークン名を表示します
@end deffn

@code{filename.py} が指定された場合、その内容がトークナイズされ stdout に出力されます。指定されなかった場合は stdin からトークナイズします。

@node 使用例<50>,,コマンドラインからの使用<4>,tokenize --- Python ソース用のトークナイザー
@anchor{library/tokenize examples}@anchor{4c65}
@subsubsection 使用例


スクリプト書き換えの例で、浮動小数点数リテラルを Decimal オブジェクトに変換します:

@example
from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
from io import BytesIO

def decistmt(s):
    """Substitute Decimals for floats in a string of statements.

    >>> from decimal import Decimal
    >>> s = 'print(+21.3e-5*-.1234/81.7)'
    >>> decistmt(s)
    "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"

    The format of the exponent is inherited from the platform C library.
    Known cases are "e-007" (Windows) and "e-07" (not Windows).  Since
    we're only showing 12 digits, and the 13th isn't close to 5, the
    rest of the output should be platform-independent.

    >>> exec(s)  #doctest: +ELLIPSIS
    -3.21716034272e-0...7

    Output from calculations with Decimal should be identical across all
    platforms.

    >>> exec(decistmt(s))
    -3.217160342717258261933904529E-7
    """
    result = []
    g = tokenize(BytesIO(s.encode('utf-8')).readline)  # tokenize the string
    for toknum, tokval, _, _, _ in g:
        if toknum == NUMBER and '.' in tokval:  # replace NUMBER tokens
            result.extend([
                (NAME, 'Decimal'),
                (OP, '('),
                (STRING, repr(tokval)),
                (OP, ')')
            ])
        else:
            result.append((toknum, tokval))
    return untokenize(result).decode('utf-8')
@end example

コマンドラインからトークナイズする例。次のスクリプトが:

@example
def say_hello():
    print("Hello, World!")

say_hello()
@end example

トークナイズされて次のような出力になります。最初のカラムはトークンが現れた行／カラム、次のカラムはトークンの名前、最後のカラムは (あれば) トークンの値です

@example
$ python -m tokenize hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          OP             '('
1,14-1,15:          OP             ')'
1,15-1,16:          OP             ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           OP             '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          OP             ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         '@w{'}
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           OP             '('
4,10-4,11:          OP             ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      '@w{'}
@end example

トークンの exact_type 名は @ref{4c63,,-e} オプションで表示できます:

@example
$ python -m tokenize -e hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          LPAR           '('
1,14-1,15:          RPAR           ')'
1,15-1,16:          COLON          ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           LPAR           '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          RPAR           ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         '@w{'}
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           LPAR           '('
4,10-4,11:          RPAR           ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      '@w{'}
@end example

Example of tokenizing a file programmatically, reading unicode
strings instead of bytes with @ref{701,,generate_tokens()}:

@example
import tokenize

with tokenize.open('hello.py') as f:
    tokens = tokenize.generate_tokens(f.readline)
    for token in tokens:
        print(token)
@end example

Or reading bytes directly with @ref{700,,tokenize()}:

@example
import tokenize

with open('hello.py', 'rb') as f:
    tokens = tokenize.tokenize(f.readline)
    for token in tokens:
        print(token)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tabnanny --- あいまいなインデントの検出,pyclbr --- Python モジュールブラウザーサポート,tokenize --- Python ソース用のトークナイザー,Python言語サービス
@anchor{library/tabnanny doc}@anchor{4c66}@anchor{library/tabnanny module-tabnanny}@anchor{e3}@anchor{library/tabnanny tabnanny-detection-of-ambiguous-indentation}@anchor{4c67}@anchor{library/tabnanny translation-repo}@anchor{4c68}
@subsection @code{tabnanny} --- あいまいなインデントの検出


@geindex module; tabnanny

@c rudimentary documentation based on module comments

`ソースコード:' Lib/tabnanny.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tabnanny.py}


__________________________________________________________________


差し当たり、このモジュールはスクリプトとして呼び出すことを意図しています。しかし、IDE 上にインポートして下で説明する関数 @ref{4c69,,check()} を使うことができます。

@cartouche
@quotation 注釈 
このモジュールが提供する API を将来のリリースで変更する確率が高いです。このような変更は後方互換性がないかもしれません。
@end quotation
@end cartouche

@geindex check() (tabnanny モジュール)
@anchor{library/tabnanny tabnanny check}@anchor{4c69}
@deffn {の関数} tabnanny.check (file_or_dir)

`file_or_dir' がディレクトリであってシンボリックリンクでないときに、 `file_or_dir' という名前のディレクトリツリーを再帰的に下って行き、この通り道に沿ってすべての @code{.py} ファイルをチェックします。 `file_or_dir' が通常の Python ソースファイルの場合には、問題のある空白をチェックします。診断メッセージは @ref{1177,,print()} 関数を使って標準出力に書き込まれます。
@end deffn

@geindex verbose (tabnanny モジュール)
@anchor{library/tabnanny tabnanny verbose}@anchor{4c6a}
@deffn {データ} tabnanny.verbose

冗長なメッセージをプリントするかどうかを示すフラグ。スクリプトとして呼び出された場合は、@code{-v} オプションによって増加します。
@end deffn

@geindex filename_only (tabnanny モジュール)
@anchor{library/tabnanny tabnanny filename_only}@anchor{4c6b}
@deffn {データ} tabnanny.filename_only

問題のある空白を含むファイルのファイル名のみをプリントするかどうかを示すフラグ。スクリプトとして呼び出された場合は、@code{-q} オプションによって真に設定されます。
@end deffn

@geindex NannyNag
@anchor{library/tabnanny tabnanny NannyNag}@anchor{4c6c}
@deffn {例外} tabnanny.NannyNag

あいまいなインデントを検出した場合に @ref{4c6d,,process_tokens()} が送出します。
この例外は @ref{4c69,,check()} で捕捉され処理されます。
@end deffn

@geindex process_tokens() (tabnanny モジュール)
@anchor{library/tabnanny tabnanny process_tokens}@anchor{4c6d}
@deffn {の関数} tabnanny.process_tokens (tokens)

この関数は、 @ref{101,,tokenize} モジュールによって生成されたトークンを @ref{4c69,,check()} が処理するために使われます。
@end deffn

@c XXX document errprint, format_witnesses, Whitespace, check_equal, indents,
@c reset_globals


@subsubheading 参考



@table @asis

@item @ref{101,,tokenize} モジュール

Pythonソースコードの字句解析器。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pyclbr --- Python モジュールブラウザーサポート,py_compile --- Python ソースファイルをコンパイルする,tabnanny --- あいまいなインデントの検出,Python言語サービス
@anchor{library/pyclbr doc}@anchor{4c6e}@anchor{library/pyclbr module-pyclbr}@anchor{b9}@anchor{library/pyclbr pyclbr-python-module-browser-support}@anchor{4c6f}@anchor{library/pyclbr translation-repo}@anchor{4c70}
@subsection @code{pyclbr} --- Python モジュールブラウザーサポート


@geindex module; pyclbr

`ソースコード:' Lib/pyclbr.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pyclbr.py}


__________________________________________________________________


The @code{pyclbr} module provides limited information about the
functions, classes, and methods defined in a Python-coded module.  The
information is sufficient to implement a module browser.  The
information is extracted from the Python source code rather than by
importing the module, so this module is safe to use with untrusted code.
This restriction makes it impossible to use this module with modules not
implemented in Python, including all standard and optional extension
modules.

@geindex readmodule() (pyclbr モジュール)
@anchor{library/pyclbr pyclbr readmodule}@anchor{a2c}
@deffn {の関数} pyclbr.readmodule (module, path=None)

Return a dictionary mapping module-level class names to class
descriptors.  If possible, descriptors for imported base classes are
included.  Parameter `module' is a string with the name of the module
to read; it may be the name of a module within a package.  If given,
`path' is a sequence of directory paths prepended to @code{sys.path},
which is used to locate the module source code.

This function is the original interface and is only kept for back
compatibility.  It returns a filtered version of the following.
@end deffn

@geindex readmodule_ex() (pyclbr モジュール)
@anchor{library/pyclbr pyclbr readmodule_ex}@anchor{a2d}
@deffn {の関数} pyclbr.readmodule_ex (module, path=None)

Return a dictionary-based tree containing a function or class
descriptors for each function and class defined in the module with a
@code{def} or @code{class} statement.  The returned dictionary maps
module-level function and class names to their descriptors.  Nested
objects are entered into the children dictionary of their parent.  As
with readmodule, `module' names the module to be read and `path' is
prepended to sys.path.  If the module being read is a package, the
returned dictionary has a key @code{'__path__'} whose value is a list
containing the package search path.
@end deffn


Added in version 3.7: Descriptors for nested definitions.  They are accessed through the
new children attribute.  Each has a new parent attribute.


The descriptors returned by these functions are instances of
Function and Class classes.  Users are not expected to create instances
of these classes.

@menu
* Function オブジェクト:: 
* クラスオブジェクト: クラスオブジェクト<2>. 

@end menu

@node Function オブジェクト,クラスオブジェクト<2>,,pyclbr --- Python モジュールブラウザーサポート
@anchor{library/pyclbr function-objects}@anchor{4c71}@anchor{library/pyclbr pyclbr-function-objects}@anchor{4c72}
@subsubsection Function オブジェクト


@geindex Function (pyclbr のクラス)
@anchor{library/pyclbr pyclbr Function}@anchor{4c73}
@deffn {クラス} pyclbr.Function

Class @code{Function} instances describe functions defined by def
statements.  They have the following attributes:

@geindex file (pyclbr.Function の属性)
@anchor{library/pyclbr pyclbr Function file}@anchor{4c74}
@deffn {の属性} file

Name of the file in which the function is defined.
@end deffn

@geindex module (pyclbr.Function の属性)
@anchor{library/pyclbr pyclbr Function module}@anchor{4c75}
@deffn {の属性} module

The name of the module defining the function described.
@end deffn

@geindex name (pyclbr.Function の属性)
@anchor{library/pyclbr pyclbr Function name}@anchor{4c76}
@deffn {の属性} name

関数の名前です。
@end deffn

@geindex lineno (pyclbr.Function の属性)
@anchor{library/pyclbr pyclbr Function lineno}@anchor{4c77}
@deffn {の属性} lineno

The line number in the file where the definition starts.
@end deffn

@geindex parent (pyclbr.Function の属性)
@anchor{library/pyclbr pyclbr Function parent}@anchor{4c78}
@deffn {の属性} parent

For top-level functions, @code{None}.  For nested functions, the parent.


Added in version 3.7.

@end deffn

@geindex children (pyclbr.Function の属性)
@anchor{library/pyclbr pyclbr Function children}@anchor{4c79}
@deffn {の属性} children

A @ref{183,,dictionary} mapping names to descriptors for nested functions and
classes.


Added in version 3.7.

@end deffn

@geindex is_async (pyclbr.Function の属性)
@anchor{library/pyclbr pyclbr Function is_async}@anchor{4c7a}
@deffn {の属性} is_async

@code{True} for functions that are defined with the
@ref{7ed,,async} prefix, @code{False} otherwise.


Added in version 3.10.

@end deffn
@end deffn

@node クラスオブジェクト<2>,,Function オブジェクト,pyclbr --- Python モジュールブラウザーサポート
@anchor{library/pyclbr class-objects}@anchor{4c7b}@anchor{library/pyclbr pyclbr-class-objects}@anchor{4c7c}
@subsubsection クラスオブジェクト


@geindex Class (pyclbr のクラス)
@anchor{library/pyclbr pyclbr Class}@anchor{4c7d}
@deffn {クラス} pyclbr.Class

Class @code{Class} instances describe classes defined by class
statements.  They have the same attributes as @ref{4c73,,Functions}
and two more.

@geindex file (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class file}@anchor{4c7e}
@deffn {の属性} file

Name of the file in which the class is defined.
@end deffn

@geindex module (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class module}@anchor{4c7f}
@deffn {の属性} module

The name of the module defining the class described.
@end deffn

@geindex name (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class name}@anchor{4c80}
@deffn {の属性} name

クラスの名前です。
@end deffn

@geindex lineno (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class lineno}@anchor{4c81}
@deffn {の属性} lineno

The line number in the file where the definition starts.
@end deffn

@geindex parent (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class parent}@anchor{4c82}
@deffn {の属性} parent

For top-level classes, @code{None}.  For nested classes, the parent.


Added in version 3.7.

@end deffn

@geindex children (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class children}@anchor{4c83}
@deffn {の属性} children

A dictionary mapping names to descriptors for nested functions and
classes.


Added in version 3.7.

@end deffn

@geindex super (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class super}@anchor{4c84}
@deffn {の属性} super

A list of @code{Class} objects which describe the immediate base
classes of the class being described.  Classes which are named as
superclasses but which are not discoverable by @ref{a2d,,readmodule_ex()}
are listed as a string with the class name instead of as
@code{Class} objects.
@end deffn

@geindex methods (pyclbr.Class の属性)
@anchor{library/pyclbr pyclbr Class methods}@anchor{4c85}
@deffn {の属性} methods

A @ref{183,,dictionary} mapping method names to line numbers.
This can be derived from the newer @ref{4c83,,children} dictionary,
but remains for
back-compatibility.
@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node py_compile --- Python ソースファイルをコンパイルする,compileall --- Python ライブラリをバイトコンパイルする,pyclbr --- Python モジュールブラウザーサポート,Python言語サービス
@anchor{library/py_compile doc}@anchor{4c86}@anchor{library/py_compile module-py_compile}@anchor{b8}@anchor{library/py_compile py-compile-compile-python-source-files}@anchor{4c87}@anchor{library/py_compile translation-repo}@anchor{4c88}
@subsection @code{py_compile} --- Python ソースファイルをコンパイルする


@geindex module; py_compile

@c documentation based on module docstrings

`ソースコード:' Lib/py_compile.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/py_compile.py}

@geindex ファイル;バイトコード


__________________________________________________________________


The @code{py_compile} module provides a function to generate a byte-code file
from a source file, and another function used when the module source file is
invoked as a script.

頻繁に必要となるわけではありませんが、共有ライブラリとしてモジュールをインストールする場合や、特にソースコードのあるディレクトリにバイトコードのキャッシュファイルを書き込む権限がないユーザがいるときには、この関数は役に立ちます。

@geindex PyCompileError
@anchor{library/py_compile py_compile PyCompileError}@anchor{4c89}
@deffn {例外} py_compile.PyCompileError

ファイルをコンパイル中にエラーが発生すると送出される例外。
@end deffn

@geindex compile() (py_compile モジュール)
@anchor{library/py_compile py_compile compile}@anchor{c1a}
@deffn {の関数} py_compile.compile (file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0)

Compile a source file to byte-code and write out the byte-code cache file.
The source code is loaded from the file named `file'.  The byte-code is
written to `cfile', which defaults to the 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/}/
@geindex Python Enhancement Proposals; PEP 488
PEP 488@footnote{https://peps.python.org/pep-0488/} path, ending
in @code{.pyc}.
For example, if `file' is @code{/foo/bar/baz.py} `cfile' will default to
@code{/foo/bar/__pycache__/baz.cpython-32.pyc} for Python 3.2.  If `dfile' is
specified, it is used instead of `file' as the name of the source file from
which source lines are obtained for display in exception tracebacks.
If `doraise' is true, a @ref{4c89,,PyCompileError} is raised
when an error is encountered while compiling `file'. If `doraise' is false
(the default), an error string is written to @code{sys.stderr}, but no exception
is raised.  This function returns the path to byte-compiled file, i.e.
whatever `cfile' value was used.

The `doraise' and `quiet' arguments determine how errors are handled while
compiling file. If `quiet' is 0 or 1, and `doraise' is false, the default
behaviour is enabled: an error string is written to @code{sys.stderr}, and the
function returns @code{None} instead of a path. If `doraise' is true,
a @ref{4c89,,PyCompileError} is raised instead. However if `quiet' is 2,
no message is written, and `doraise' has no effect.

(明示的に指定されたか計算された結果の) `cfile' のパスがシンボリックリンクだったり通常のファイルでなかったりした場合は、 @ref{1221,,FileExistsError} が送出されます。この動作は、それらのパスにバイトコンパイルされたファイルを書き込む権限がある場合、インポートのときにそのパスを通常のファイルに変えてしまうことを警告するためのものです。これはリネームを使ってバイトコンパイルされたファイルを配置するインポートで、同時にファイル書き込みをしてしまう問題を避けるための副作用です。

`optimize' は最適化レベルを制御するもので、組み込みの @ref{4b1,,compile()} 関数に渡されます。デフォルトは現在のインタープリタの最適化レベルを選ぶ @code{-1} です。

`invalidation_mode' should be a member of the @ref{4c8a,,PycInvalidationMode}
enum and controls how the generated bytecode cache is invalidated at
runtime.  The default is @ref{4c8b,,PycInvalidationMode.CHECKED_HASH} if
the 
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable is set, otherwise
the default is @ref{4c8c,,PycInvalidationMode.TIMESTAMP}.


バージョン 3.2 で変更: 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} に準拠し `cfile' のデフォルト値を変更しました。以前のデフォルトは `file' + @code{'c'} (最適化が有効な場合は @code{'o'}) でした。同時に `optimize' パラメータも追加されました。



バージョン 3.4 で変更: バイトコードをキャッシュするファイルへの書き込みに @ref{7b,,importlib} を使うようにコードを変更しました。これにより、例えば権限や write-and-move セマンティクスなどの、ファイルの作成や書き込みの動作が @ref{7b,,importlib} と一致するようになりました。 `cfile' がシンボリックリンクであるか通常のファイルでない場合、 @ref{1221,,FileExistsError} を送出するという注意書きも追加されました。



バージョン 3.7 で変更: The `invalidation_mode' parameter was added as specified in 
@geindex Python Enhancement Proposals; PEP 552
PEP 552@footnote{https://peps.python.org/pep-0552/}.
If the 
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable is set,
`invalidation_mode' will be forced to
@ref{4c8b,,PycInvalidationMode.CHECKED_HASH}.



バージョン 3.7.2 で変更: The 
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable no longer
overrides the value of the `invalidation_mode' argument, and determines
its default value instead.



バージョン 3.8 で変更: `quiet' パラメータが追加されました。

@end deffn

@geindex PycInvalidationMode (py_compile のクラス)
@anchor{library/py_compile py_compile PycInvalidationMode}@anchor{4c8a}
@deffn {クラス} py_compile.PycInvalidationMode

An enumeration of possible methods the interpreter can use to determine
whether a bytecode file is up to date with a source file. The @code{.pyc} file
indicates the desired invalidation mode in its header. See
@ref{802,,キャッシュされたバイトコードの無効化} for more information on how Python invalidates
@code{.pyc} files at runtime.


Added in version 3.7.


@geindex TIMESTAMP (py_compile.PycInvalidationMode の属性)
@anchor{library/py_compile py_compile PycInvalidationMode TIMESTAMP}@anchor{4c8c}
@deffn {の属性} TIMESTAMP

The @code{.pyc} file includes the timestamp and size of the source file,
which Python will compare against the metadata of the source file at
runtime to determine if the @code{.pyc} file needs to be regenerated.
@end deffn

@geindex CHECKED_HASH (py_compile.PycInvalidationMode の属性)
@anchor{library/py_compile py_compile PycInvalidationMode CHECKED_HASH}@anchor{4c8b}
@deffn {の属性} CHECKED_HASH

The @code{.pyc} file includes a hash of the source file content, which Python
will compare against the source at runtime to determine if the @code{.pyc}
file needs to be regenerated.
@end deffn

@geindex UNCHECKED_HASH (py_compile.PycInvalidationMode の属性)
@anchor{library/py_compile py_compile PycInvalidationMode UNCHECKED_HASH}@anchor{4c8d}
@deffn {の属性} UNCHECKED_HASH

Like @ref{4c8b,,CHECKED_HASH}, the @code{.pyc} file includes a hash of the source
file content. However, Python will at runtime assume the @code{.pyc} file is
up to date and not validate the @code{.pyc} against the source file at all.

This option is useful when the @code{.pycs} are kept up to date by some
system external to Python like a build system.
@end deffn
@end deffn

@menu
* コマンドラインインターフェイス: コマンドラインインターフェイス<5>. 

@end menu

@node コマンドラインインターフェイス<5>,,,py_compile --- Python ソースファイルをコンパイルする
@anchor{library/py_compile command-line-interface}@anchor{4c8e}@anchor{library/py_compile py-compile-cli}@anchor{4c8f}
@subsubsection コマンドラインインターフェイス


This module can be invoked as a script to compile several source
files.  The files named in `filenames' are compiled and the resulting
bytecode is cached in the normal manner.  This program does not search
a directory structure to locate source files; it only compiles files
named explicitly. The exit status is nonzero if one of the files could
not be compiled.

@geindex python--m-py_compile コマンドラインオプション; <file>
@geindex python--m-py_compile コマンドラインオプション; -
@anchor{library/py_compile cmdoption-python-m-py_compile-arg-file}@anchor{4c90}
@deffn {Option} <file> ... <fileN>
@anchor{library/py_compile cmdoption-python-m-py_compile}@anchor{4c91}
@deffnx {Option} @w{-}

Positional arguments are files to compile.  If @code{-} is the only
parameter, the list of files is taken from standard input.
@end deffn

@geindex python--m-py_compile コマンドラインオプション; -q
@geindex python--m-py_compile コマンドラインオプション; --quiet
@anchor{library/py_compile cmdoption-python-m-py_compile-q}@anchor{4c92}@anchor{library/py_compile cmdoption-python-m-py_compile-quiet}@anchor{4c93}
@deffn {Option} @w{-}q, @w{-}@w{-}quiet

Suppress errors output.
@end deffn


バージョン 3.2 で変更: @code{-} のサポートが追加されました。



バージョン 3.10 で変更: @ref{4c92,,-q} のサポートが追加されました。



@subsubheading 参考



@table @asis

@item @ref{21,,compileall} モジュール

ディレクトリツリー内の Python ソースファイルを全てコンパイルするライブラリ。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node compileall --- Python ライブラリをバイトコンパイルする,dis --- Python バイトコードの逆アセンブラー,py_compile --- Python ソースファイルをコンパイルする,Python言語サービス
@anchor{library/compileall doc}@anchor{4c94}@anchor{library/compileall compileall-byte-compile-python-libraries}@anchor{4c95}@anchor{library/compileall module-compileall}@anchor{21}@anchor{library/compileall translation-repo}@anchor{4c96}
@subsection @code{compileall} --- Python ライブラリをバイトコンパイルする


@geindex module; compileall

`ソースコード:' Lib/compileall.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/compileall.py}


__________________________________________________________________


このモジュールは、Python ライブラリのインストールを助けるユーティリティ関数群を提供します。この関数群は、ディレクトリツリー内の Python ソースファイルをコンパイルします。このモジュールを使って、キャッシュされたバイトコードファイルをライブラリのインストール時に生成することで、ライブラリディレクトリに書き込み権限をもたないユーザでも、これらを利用できるようになります。

@c include for modules that don't work on WASM

@ref{213f,,Availability}: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、@ref{1b6a,,WebAssembly プラットフォーム} を見てください。

@menu
* コマンドラインでの使用: コマンドラインでの使用<9>. 
* パブリックな関数:: 

@end menu

@node コマンドラインでの使用<9>,パブリックな関数,,compileall --- Python ライブラリをバイトコンパイルする
@anchor{library/compileall command-line-use}@anchor{4c97}@anchor{library/compileall compileall-cli}@anchor{4c98}
@subsubsection コマンドラインでの使用


このモジュールは、 (@code{python -m compileall} を使って) Python ソースをコンパイルするスクリプトとして機能します。

@geindex compileall コマンドラインオプション; directory
@geindex compileall コマンドラインオプション; file
@anchor{library/compileall cmdoption-compileall-arg-directory}@anchor{4c99}
@deffn {Option} directory ...
@anchor{library/compileall cmdoption-compileall-arg-file}@anchor{4c9a}
@deffnx {Option} file ...

位置引数は、コンパイルするファイル群か、再帰的に横断されるディレクトリでソースファイル群を含むものです。引数が与えられなければ、 @code{-l @var{<directories from sys.path>}} を渡したのと同じように動作します。
@end deffn

@geindex compileall コマンドラインオプション; -l
@anchor{library/compileall cmdoption-compileall-l}@anchor{4c9b}
@deffn {Option} @w{-}l

サブディレクトリを再帰処理せず、指名または暗示されたディレクトリ群に含まれるソースコードファイル群だけをコンパイルします。
@end deffn

@geindex compileall コマンドラインオプション; -f
@anchor{library/compileall cmdoption-compileall-f}@anchor{4c9c}
@deffn {Option} @w{-}f

タイムスタンプが最新であってもリビルドを強制します。
@end deffn

@geindex compileall コマンドラインオプション; -q
@anchor{library/compileall cmdoption-compileall-q}@anchor{4c9d}
@deffn {Option} @w{-}q

コンパイルされたファイルのリストを出力しません。
一つ渡された場合でもエラーメッセージは出力されます。
二つ (@code{-qq}) の場合全ての出力は抑制されます。
@end deffn

@geindex compileall コマンドラインオプション; -d
@anchor{library/compileall cmdoption-compileall-d}@anchor{4c9e}
@deffn {Option} @w{-}d destdir

コンパイルされるそれぞれのファイルへのパスの先頭に、ディレクトリを追加します。これはコンパイル時トレースバックに使われ、バイトコードファイルが実行される時点でソースファイルが存在しない場合に、トレースバックやその他のメッセージに使われるバイトコードファイルにもコンパイルされます。
@end deffn

@geindex compileall コマンドラインオプション; -s
@anchor{library/compileall cmdoption-compileall-s}@anchor{4c9f}
@deffn {Option} @w{-}s strip_prefix

Remove the given prefix from paths recorded in the @code{.pyc} files.
Paths are made relative to the prefix.

This option can be used with @code{-p} but not with @code{-d}.
@end deffn

@geindex compileall コマンドラインオプション; -p
@anchor{library/compileall cmdoption-compileall-p}@anchor{4ca0}
@deffn {Option} @w{-}p prepend_prefix

Prepend the given prefix to paths recorded in the @code{.pyc} files.
Use @code{-p /} to make the paths absolute.

This option can be used with @code{-s} but not with @code{-d}.
@end deffn

@geindex compileall コマンドラインオプション; -x
@anchor{library/compileall cmdoption-compileall-x}@anchor{4ca1}
@deffn {Option} @w{-}x regex

regex を使って、コンパイル候補のそれぞれのファイルのフルパスを検索し、regex がマッチしたファイルを除外します。
@end deffn

@geindex compileall コマンドラインオプション; -i
@anchor{library/compileall cmdoption-compileall-i}@anchor{4ca2}
@deffn {Option} @w{-}i list

ファイル @code{list} を読み込み、そのファイルのそれぞれの行を、コンパイルするファイルとディレクトリのリストに加えます。@code{list} が @code{-} なら、@code{stdin} の行を読み込みます。
@end deffn

@geindex compileall コマンドラインオプション; -b
@anchor{library/compileall cmdoption-compileall-b}@anchor{4ca3}
@deffn {Option} @w{-}b

バイトコードファイルを、他のバージョンの Python によって生成されたバイトコードファイルを上書きするかもしれない、レガシーな場所に生成します。デフォルトでは 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} で決められた場所と名前を使い、複数のバージョンの Python が共存できるようにします。
@end deffn

@geindex compileall コマンドラインオプション; -r
@anchor{library/compileall cmdoption-compileall-r}@anchor{4ca4}
@deffn {Option} @w{-}r

サブディレクトリの最大再起深度を制御します。
このオプションが与えられた場合、@code{-l} オプションは無視されます。
@code{python -m compileall <directory> -r 0} は @code{python -m compileall <directory> -l} と等価です。
@end deffn

@geindex compileall コマンドラインオプション; -j
@anchor{library/compileall cmdoption-compileall-j}@anchor{4ca5}
@deffn {Option} @w{-}j N

Use `N' workers to compile the files within the given directory.
If @code{0} is used, then the result of @ref{4da,,os.process_cpu_count()}
will be used.
@end deffn

@geindex compileall コマンドラインオプション; --invalidation-mode
@anchor{library/compileall cmdoption-compileall-invalidation-mode}@anchor{4ca6}
@deffn {Option} @w{-}@w{-}invalidation@w{-}mode [timestamp|checked@w{-}hash|unchecked@w{-}hash]

生成したバイトコードファイルを実行時に無効化する方法を制御します。@code{timestamp} を指定すると、生成した`@w{`}.pyc`@w{`} ファイルにソースファイルのタイムスタンプとサイズを埋め込みます。@code{checked-hash} と @code{unchecked-hash} を指定すると、ハッシュベースの pycファイルが生成されます。ハッシュベースのpycファイルは、ソースファイルにタイムスタンプではなくハッシュ値を埋め込みます。Python がバイトコードキャッシュファイルを実行時に検証する方法の詳細を知るには、@ref{802,,キャッシュされたバイトコードの無効化} を参照してください。デフォルト値は、
@geindex SOURCE_DATE_EPOCH
@geindex 環境変数; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} 環境変数が設定されていなければ @code{timestamp} で、@code{SOURCE_DATE_EPOCH} 環境変数が設定されていれば、@code{checked-hash} になります。
@end deffn

@geindex compileall コマンドラインオプション; -o
@anchor{library/compileall cmdoption-compileall-o}@anchor{4ca7}
@deffn {Option} @w{-}o level

Compile with the given optimization level. May be used multiple times
to compile for multiple levels at a time (for example,
@code{compileall -o 1 -o 2}).
@end deffn

@geindex compileall コマンドラインオプション; -e
@anchor{library/compileall cmdoption-compileall-e}@anchor{4ca8}
@deffn {Option} @w{-}e dir

Ignore symlinks pointing outside the given directory.
@end deffn

@geindex compileall コマンドラインオプション; --hardlink-dupes
@anchor{library/compileall cmdoption-compileall-hardlink-dupes}@anchor{4ca9}
@deffn {Option} @w{-}@w{-}hardlink@w{-}dupes

If two @code{.pyc} files with different optimization level have
the same content, use hard links to consolidate duplicate files.
@end deffn


バージョン 3.2 で変更: @code{-i}, @code{-b}, @code{-h} オプションを追加。



バージョン 3.5 で変更: @code{-j}, @code{-r}, @code{-qq} オプションが追加されました。@code{-q} オプションが複数のレベルの値に変更されました。@code{-b} は常に拡張子 @code{.pyc} のバイトエンコーディングファイルを生成し、@code{.pyo} を作りません。



バージョン 3.7 で変更: @code{--invalidation-mode} オプションが追加されました。



バージョン 3.9 で変更: Added the @code{-s}, @code{-p}, @code{-e} and @code{--hardlink-dupes} options.
Raised the default recursion limit from 10 to
@ref{6eb,,sys.getrecursionlimit()}.
Added the possibility to specify the @code{-o} option multiple times.


@ref{4b1,,compile()} 関数で利用される最適化レベルを制御するコマンドラインオプションはありません。 Python インタプリタ自体のオプションを使ってください: @code{python -O -m compileall}.

Similarly, the @ref{4b1,,compile()} function respects the @ref{b9c,,sys.pycache_prefix}
setting. The generated bytecode cache will only be useful if @ref{4b1,,compile()} is
run with the same @ref{b9c,,sys.pycache_prefix} (if any) that will be used at
runtime.

@node パブリックな関数,,コマンドラインでの使用<9>,compileall --- Python ライブラリをバイトコンパイルする
@anchor{library/compileall public-functions}@anchor{4caa}
@subsubsection パブリックな関数


@geindex compile_dir() (compileall モジュール)
@anchor{library/compileall compileall compile_dir}@anchor{d1b}
@deffn {の関数} compileall.compile_dir (dir, maxlevels=sys.getrecursionlimit(), ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)

`dir' という名前のディレクトリーツリーをたどり、途中で見つけた全ての @code{.py} をコンパイルします。全ファイルのコンパイルが成功した場合は真を、それ以外の場合は偽を返します。

`maxlevels' パラメータで最大再帰深度を制限します。デフォルトは @code{sys.getrecursionlimit()} です。

`ddir' が与えられた場合、コンパイルされるそれぞれのファイルへのパスの先頭に、そのディレクトリを追加します。これはコンパイル時トレースバックに使われ、バイトコードファイルが実行される時点でソースファイルが存在しない場合に、トレースバックやその他のメッセージに使われるバイトコードファイルにもコンパイルされます。

`force' が真の場合、タイムスタンプが最新のであってもモジュールは再コンパイルされます。

If `rx' is given, its @code{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 @ref{1189,,re.Pattern} object.

`quiet' が @code{False} か @code{0} (デフォルト) の場合、ファイル名とその他の情報は標準出力に表示されます。
@code{1} の場合エラーのみが表示されます。
@code{2} の場合出力はすべて抑制されます。

`legacy' が真の時、バイトコードファイルは古い場所と名前に書かれ、他のバージョンの Python によって作られたバイトコードファイルを上書きする可能性があります。デフォルトは 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} で決められた場所と名前を使い、複数のバージョンの Python のバイトコードファイルが共存できるようにします。

`optimize' specifies the optimization level for the compiler.  It is passed to
the built-in @ref{4b1,,compile()} function. Accepts also a sequence of optimization
levels which lead to multiple compilations of one @code{.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 @code{0}, a @ref{2ec,,ValueError} will be raised.

`invalidation_mode' は、@ref{4c8a,,py_compile.PycInvalidationMode} のメンバーでなければならず、生成されたpycファイルを実行時に無効化する方法を制御します。

The `stripdir', `prependdir' and `limit_sl_dest' arguments correspond to
the @code{-s}, @code{-p} and @code{-e} options described above.
They may be specified as @code{str} or @ref{e4b,,os.PathLike}.

If `hardlink_dupes' is true and two @code{.pyc} files with different optimization
level have the same content, use hard links to consolidate duplicate files.


バージョン 3.2 で変更: `legacy' と `optimize' 引数が追加されました。



バージョン 3.5 で変更: @code{workers} パラメータが追加されました。



バージョン 3.5 で変更: `quiet' 引数が複数のレベルの値に変更されました。



バージョン 3.5 で変更: `optimize' の値に関わらず、`legacy' 引数は @code{.pyc} ファイルのみを書き出し、@code{.pyo} ファイルを書き出さないようになりました。



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。



バージョン 3.7 で変更: `invalidation_mode' 引数を追加しました。



バージョン 3.7.2 で変更: The `invalidation_mode' parameter's default value is updated to @code{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 @code{10} to @code{sys.getrecursionlimit()}

@end deffn

@geindex compile_file() (compileall モジュール)
@anchor{library/compileall compileall compile_file}@anchor{fe1}
@deffn {の関数} compileall.compile_file (fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)

パス `fullname' のファイルをコンパイルします。コンパイルが成功すれば真を、そうでなければ偽を返します。

`ddir' が与えられた場合、コンパイルされるファイルのパスの先頭にそのディレクトリを追加します。これはコンパイル時トレースバックに使われ、バイトコードファイルが実行される時点でソースファイルが存在しない場合に、トレースバックやその他のメッセージに使われるバイトコードファイルにもコンパイルされます。

If `rx' is given, its @code{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 @code{True} is returned. This can be used to exclude files matching
a regular expression, given as a @ref{1189,,re.Pattern} object.

`quiet' が @code{False} か @code{0} (デフォルト) の場合、ファイル名とその他の情報は標準出力に表示されます。
@code{1} の場合エラーのみが表示されます。
@code{2} の場合出力はすべて抑制されます。

`legacy' が真の時、バイトコードファイルは古い場所と名前に書かれ、他のバージョンの Python によって作られたバイトコードファイルを上書きする可能性があります。デフォルトは 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} で決められた場所と名前を使い、複数のバージョンの Python のバイトコードファイルが共存できるようにします。

`optimize' specifies the optimization level for the compiler.  It is passed to
the built-in @ref{4b1,,compile()} function. Accepts also a sequence of optimization
levels which lead to multiple compilations of one @code{.py} file in one call.

`invalidation_mode' は、@ref{4c8a,,py_compile.PycInvalidationMode} のメンバーでなければならず、生成されたpycファイルを実行時に無効化する方法を制御します。

The `stripdir', `prependdir' and `limit_sl_dest' arguments correspond to
the @code{-s}, @code{-p} and @code{-e} options described above.
They may be specified as @code{str} or @ref{e4b,,os.PathLike}.

If `hardlink_dupes' is true and two @code{.pyc} files with different optimization
level have the same content, use hard links to consolidate duplicate files.


Added in version 3.2.



バージョン 3.5 で変更: `quiet' 引数が複数のレベルの値に変更されました。



バージョン 3.5 で変更: `optimize' の値に関わらず、`legacy' 引数は @code{.pyc} ファイルのみを書き出し、@code{.pyo} ファイルを書き出さないようになりました。



バージョン 3.7 で変更: `invalidation_mode' 引数を追加しました。



バージョン 3.7.2 で変更: The `invalidation_mode' parameter's default value is updated to @code{None}.



バージョン 3.9 で変更: 引数 `stripdir' 、 `prependdir' 、 `limit_sl_dest' 、および `hardlink_dupes' を追加しました。

@end deffn

@geindex compile_path() (compileall モジュール)
@anchor{library/compileall compileall compile_path}@anchor{fe2}
@deffn {の関数} compileall.compile_path (skip_curdir=True, maxlevels=0, force=False, quiet=0, legacy=False, optimize=-1, invalidation_mode=None)

@code{sys.path} からたどって見つけたすべての @code{.py} ファイルをバイトコンパイルします。
すべてのファイルを問題なくコンパイルできたときに真を、それ以外のときに偽を返します。

`skip_curdir' が真(デフォルト)のとき、カレントディレクトリは走査から除外されます。
それ以外のすべての引数は @ref{d1b,,compile_dir()} 関数に渡されます。
その他の compile 関数群と異なり、 @code{maxlevels} のデフォルトが @code{0} になっていることに注意してください。


バージョン 3.2 で変更: `legacy' と `optimize' 引数が追加されました。



バージョン 3.5 で変更: `quiet' 引数が複数のレベルの値に変更されました。



バージョン 3.5 で変更: `optimize' の値に関わらず、`legacy' 引数は @code{.pyc} ファイルのみを書き出し、@code{.pyo} ファイルを書き出さないようになりました。



バージョン 3.7 で変更: `invalidation_mode' 引数を追加しました。



バージョン 3.7.2 で変更: The `invalidation_mode' parameter's default value is updated to @code{None}.

@end deffn

@code{Lib/} ディレクトリ以下にある全ての @code{.py} ファイルを強制的に再コンパイルするには、以下のようにします:

@example
import compileall

compileall.compile_dir('Lib/', force=True)

# Perform same compilation, excluding files in .svn directories.
import re
compileall.compile_dir('Lib/', rx=re.compile(r'[/\\][.]svn'), force=True)

# pathlib.Path objects can also be used.
import pathlib
compileall.compile_dir(pathlib.Path('Lib/'), force=True)
@end example


@subsubheading 参考



@table @asis

@item Module @ref{b8,,py_compile}

一つのソースファイルをバイトコンパイルします。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node dis --- Python バイトコードの逆アセンブラー,pickletools --- pickle 開発者用のツール群,compileall --- Python ライブラリをバイトコンパイルする,Python言語サービス
@anchor{library/dis doc}@anchor{4cab}@anchor{library/dis dis-disassembler-for-python-bytecode}@anchor{4cac}@anchor{library/dis module-dis}@anchor{3c}@anchor{library/dis translation-repo}@anchor{4cad}
@subsection @code{dis} --- Python バイトコードの逆アセンブラー


@geindex module; dis

`ソースコード:' Lib/dis.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/dis.py}

@c import dis
@c def myfunc(alist):
@c     return len(alist)


__________________________________________________________________


The @code{dis} module supports the analysis of CPython @ref{4aa,,bytecode} by
disassembling it. The CPython bytecode which this module takes as an input is
defined in the file @code{Include/opcode.h} and used by the compiler and the
interpreter.

バイトコードは CPython インタプリタの実装詳細です。Python のバージョン間でバイトコードの追加や、削除、変更がないという保証はありません。このモジュールを使用することによって Python の異なる VM または異なるリリースの間で動作すると考えるべきではありません。


バージョン 3.6 で変更: 従来は使用されるバイト数は命令ごとに異なりましたが、このモジュールでは各々一つの命令につき2バイト使用することとなっています。



バージョン 3.10 で変更: The argument of jump, exception handling and loop instructions is now
the instruction offset rather than the byte offset.



バージョン 3.11 で変更: Some instructions are accompanied by one or more inline cache entries,
which take the form of @ref{908,,CACHE} instructions. These instructions
are hidden by default, but can be shown by passing @code{show_caches=True} to
any @code{dis} utility. Furthermore, the interpreter now adapts the
bytecode to specialize it for different runtime conditions. The
adaptive bytecode can be shown by passing @code{adaptive=True}.



バージョン 3.12 で変更: The argument of a jump is the offset of the target instruction relative
to the instruction that appears immediately after the jump instruction's
@ref{908,,CACHE} entries.

As a consequence, the presence of the @ref{908,,CACHE} instructions is
transparent for forward jumps but needs to be taken into account when
reasoning about backward jumps.



バージョン 3.13 で変更: The output shows logical labels rather than instruction offsets
for jump targets and exception handlers. The @code{-O} command line
option and the @code{show_offsets} argument were added.



バージョン 3.14 で変更: The @ref{208,,-P} command-line option
and the @code{show_positions} argument were added.

The @ref{209,,-S} command-line option is added.


Example: Given the function @code{myfunc()}:

@example
def myfunc(alist):
    return len(alist)
@end example

the following command can be used to display the disassembly of
@code{myfunc()}:

@example
>>> dis.dis(myfunc)
  2           RESUME                   0

  3           LOAD_GLOBAL              1 (len + NULL)
              LOAD_FAST_BORROW         0 (alist)
              CALL                     1
              RETURN_VALUE
@end example

("2" は行番号です)。

@menu
* コマンドライン・インターフェース: コマンドライン・インターフェース<12>. 
* バイトコード解析:: 
* 解析関数:: 
* Python バイトコード命令:: 
* 命令コードコレクション:: 

@end menu

@node コマンドライン・インターフェース<12>,バイトコード解析,,dis --- Python バイトコードの逆アセンブラー
@anchor{library/dis command-line-interface}@anchor{4cae}@anchor{library/dis dis-cli}@anchor{4caf}
@subsubsection コマンドライン・インターフェース


The @code{dis} module can be invoked as a script from the command line:

@example
python -m dis [-h] [-C] [-O] [-P] [-S] [infile]
@end example

以下のオプションが使用できます:

@geindex dis コマンドラインオプション; -h
@geindex dis コマンドラインオプション; --help
@anchor{library/dis cmdoption-dis-h}@anchor{4cb0}@anchor{library/dis cmdoption-dis-help}@anchor{4cb1}
@deffn {Option} @w{-}h, @w{-}@w{-}help

使い方を表示して終了します。
@end deffn

@geindex dis コマンドラインオプション; -C
@geindex dis コマンドラインオプション; --show-caches
@anchor{library/dis cmdoption-dis-C}@anchor{4cb2}@anchor{library/dis cmdoption-dis-show-caches}@anchor{4cb3}
@deffn {Option} @w{-}C, @w{-}@w{-}show@w{-}caches

Show inline caches.


Added in version 3.13.

@end deffn

@geindex dis コマンドラインオプション; -O
@geindex dis コマンドラインオプション; --show-offsets
@anchor{library/dis cmdoption-dis-O}@anchor{4eb}@anchor{library/dis cmdoption-dis-show-offsets}@anchor{4cb4}
@deffn {Option} @w{-}O, @w{-}@w{-}show@w{-}offsets

Show offsets of instructions.


Added in version 3.13.

@end deffn

@geindex dis コマンドラインオプション; -P
@geindex dis コマンドラインオプション; --show-positions
@anchor{library/dis cmdoption-dis-P}@anchor{208}@anchor{library/dis cmdoption-dis-show-positions}@anchor{4cb5}
@deffn {Option} @w{-}P, @w{-}@w{-}show@w{-}positions

Show positions of instructions in the source code.


Added in version 3.14.

@end deffn

@geindex dis コマンドラインオプション; -S
@geindex dis コマンドラインオプション; --specialized
@anchor{library/dis cmdoption-dis-S}@anchor{209}@anchor{library/dis cmdoption-dis-specialized}@anchor{4cb6}
@deffn {Option} @w{-}S, @w{-}@w{-}specialized

Show specialized bytecode.


Added in version 3.14.

@end deffn

If @code{infile} is specified, its disassembled code will be written to stdout.
Otherwise, disassembly is performed on compiled source code received from stdin.

@node バイトコード解析,解析関数,コマンドライン・インターフェース<12>,dis --- Python バイトコードの逆アセンブラー
@anchor{library/dis bytecode-analysis}@anchor{4cb7}
@subsubsection バイトコード解析



Added in version 3.4.


バイトコード解析の API を使うと、 Python のコード片を @ref{204,,Bytecode} オブジェクトでラップでき、コンパイルされたコードの細かいところに簡単にアクセスできます。

@geindex Bytecode (dis のクラス)
@anchor{library/dis dis Bytecode}@anchor{204}
@deffn {クラス} dis.Bytecode (x, *, first_line=None, current_offset=None, show_caches=False, adaptive=False, show_offsets=False, show_positions=False)

関数、ジェネレータ、非同期ジェネレータ、コルーチン、メソッド、ソースコード文字列、(@ref{4b1,,compile()} が返すような) コードオブジェクトに対応するバイトコードを解析します。

これは、下で並べられている関数の多くのものをまとめた便利なラッパーです。
とりわけ目立つのは @ref{4ec,,get_instructions()} で、 @ref{204,,Bytecode} インスタンスに対し反復処理をしながら、バイトコード命令を @ref{203,,Instruction} インスタンスとして返します。

`first_line' が @code{None} でない場合は、それを逆アセンブルしたコードのソースの最初の行に表示する行番号とします。
そうでない場合は、ソースの行の情報 (もしあれば) を逆アセンブルされたコードオブジェクトから直接取得します。

`current_offset' が @code{None} でない場合は、逆アセンブルされたコードでのあるインストラクションのオフセット位置を示します。
これを設定すると、 @ref{1130,,dis()} の出力において、指定された命令コード (opcode) に "現在の命令 (instruction)" を表す印が表示されます。

If `show_caches' is @code{True}, @ref{1130,,dis()} will display inline cache
entries used by the interpreter to specialize the bytecode.

If `adaptive' is @code{True}, @ref{1130,,dis()} will display specialized bytecode
that may be different from the original bytecode.

If `show_offsets' is @code{True}, @ref{1130,,dis()} will include instruction
offsets in the output.

If `show_positions' is @code{True}, @ref{1130,,dis()} will include instruction
source code positions in the output.

@geindex from_traceback() (dis.Bytecode のクラスメソッド)
@anchor{library/dis dis Bytecode from_traceback}@anchor{1131}
@deffn {メソッド} classmethod from_traceback (tb, *, show_caches=False)

与えられたトレースバックから @ref{204,,Bytecode} インスタンスを構築し、 `current_offset' がその例外の原因となった命令となるよう設定します。
@end deffn

@geindex Bytecode.codeobj (dis モジュール)
@anchor{library/dis dis Bytecode codeobj}@anchor{4cb8}
@deffn {データ} codeobj

コンパイルされたコードオブジェクト。
@end deffn

@geindex Bytecode.first_line (dis モジュール)
@anchor{library/dis dis Bytecode first_line}@anchor{4cb9}
@deffn {データ} first_line

コードオブジェクトのソースの最初の行 (利用可能であれば)
@end deffn

@geindex dis() (dis.Bytecode のメソッド)
@anchor{library/dis dis Bytecode dis}@anchor{1130}
@deffn {メソッド} dis ()

バイトコード命令の整形された表示を返します (@ref{205,,dis.dis()} と同じ出力になりますが、複数行文字列として返されます)。
@end deffn

@geindex info() (dis.Bytecode のメソッド)
@anchor{library/dis dis Bytecode info}@anchor{4cba}
@deffn {メソッド} info ()

@ref{1451,,code_info()} のようなコードオブジェクトの詳細を含んだ整形された複数行文字列を返します。
@end deffn


バージョン 3.7 で変更: This can now handle coroutine and asynchronous generator objects.



バージョン 3.11 で変更: Added the `show_caches' and `adaptive' parameters.



バージョン 3.13 で変更: Added the `show_offsets' parameter



バージョン 3.14 で変更: Added the `show_positions' parameter.

@end deffn

例:

@example
>>> bytecode = dis.Bytecode(myfunc)
>>> for instr in bytecode:
...     print(instr.opname)
...
RESUME
LOAD_GLOBAL
LOAD_FAST_BORROW
CALL
RETURN_VALUE
@end example

@node 解析関数,Python バイトコード命令,バイトコード解析,dis --- Python バイトコードの逆アセンブラー
@anchor{library/dis analysis-functions}@anchor{4cbb}
@subsubsection 解析関数


The @code{dis} module also defines the following analysis functions that convert
the input directly to the desired output. They can be useful if only a single
operation is being performed, so the intermediate analysis object isn't useful:

@geindex code_info() (dis モジュール)
@anchor{library/dis dis code_info}@anchor{1451}
@deffn {の関数} dis.code_info (x)

渡された関数、ジェネレータ、非同期ジェネレータ、コルーチン、メソッド、ソースコード文字列、コードオブジェクトに対する、詳細なコードオブジェクトの情報を、整形された複数行の文字列として返します。

この結果は実装に強く依存しており、Python VM や Python のバージョンによって異なることがあります。


Added in version 3.2.



バージョン 3.7 で変更: This can now handle coroutine and asynchronous generator objects.

@end deffn

@geindex show_code() (dis モジュール)
@anchor{library/dis dis show_code}@anchor{112f}
@deffn {の関数} dis.show_code (x, *, file=None)

渡された関数、メソッド、ソースコード文字列、コードオブジェクトに対する、詳細なコードオブジェクトの情報を、`file' (または `file' が指定されていなければ @code{sys.stdout}) に表示します。

これは、インタラクティブシェル上で使うことを想定した、@code{print(code_info(x), file=file)} の便利なショートカットです。


Added in version 3.2.



バージョン 3.4 で変更: `file' 引数が追加されました。

@end deffn

@geindex dis() (dis モジュール)
@anchor{library/dis dis dis}@anchor{205}
@deffn {の関数} dis.dis (x=None, *, file=None, depth=None, show_caches=False, adaptive=False, show_offsets=False, show_positions=False)

Disassemble the `x' object.  `x' can denote either a module, a class, a
method, a function, a generator, an asynchronous generator, a coroutine,
a code object, a string of source code or a byte sequence of raw bytecode.
For a module, it disassembles all functions. For a class, it disassembles
all methods (including class and static methods). For a code object or
sequence of raw bytecode, it prints one line per bytecode instruction.
It also recursively disassembles nested code objects. These can include
generator expressions, nested functions, the bodies of nested classes,
and the code objects used for @ref{4ab,,annotation scopes}.
Strings are first compiled to code objects with the @ref{4b1,,compile()}
built-in function before being disassembled.  If no object is provided, this
function disassembles the last traceback.

`file' 引数が渡された場合は、アセンブリをそこに書き込みます。
そうでない場合は @code{sys.stdout} に出力します。

The maximal depth of recursion is limited by `depth' unless it is @code{None}.
@code{depth=0} means no recursion.

If `show_caches' is @code{True}, this function will display inline cache
entries used by the interpreter to specialize the bytecode.

If `adaptive' is @code{True}, this function will display specialized bytecode
that may be different from the original bytecode.


バージョン 3.4 で変更: `file' 引数が追加されました。



バージョン 3.7 で変更: Implemented recursive disassembling and added `depth' parameter.



バージョン 3.7 で変更: This can now handle coroutine and asynchronous generator objects.



バージョン 3.11 で変更: Added the `show_caches' and `adaptive' parameters.



バージョン 3.13 で変更: Added the `show_offsets' parameter.



バージョン 3.14 で変更: Added the `show_positions' parameter.

@end deffn

@geindex distb() (dis モジュール)
@anchor{library/dis dis distb}@anchor{206}
@deffn {の関数} dis.distb (tb=None, *, file=None, show_caches=False, adaptive=False, show_offset=False, show_positions=False)

トレースバックのスタックの先頭の関数を逆アセンブルします。Noneが渡された場合は最後のトレースバックを使います。例外を引き起こした命令が表示されます。

`file' 引数が渡された場合は、アセンブリをそこに書き込みます。
そうでない場合は @code{sys.stdout} に出力します。


バージョン 3.4 で変更: `file' 引数が追加されました。



バージョン 3.11 で変更: Added the `show_caches' and `adaptive' parameters.



バージョン 3.13 で変更: Added the `show_offsets' parameter.



バージョン 3.14 で変更: Added the `show_positions' parameter.

@end deffn

@geindex disassemble() (dis モジュール)
@geindex disco() (dis モジュール)
@anchor{library/dis dis disassemble}@anchor{207}
@deffn {の関数} dis.disassemble (code, lasti=-1, *, file=None, show_caches=False, adaptive=False, show_offsets=False, show_positions=False)
@anchor{library/dis dis disco}@anchor{4cbc}
@deffnx {の関数} dis.disco (code, lasti=-1, *, file=None, show_caches=False, adaptive=False, show_offsets=False, show_positions=False)

コードオブジェクトを逆アセンブルします。`lasti' が与えられた場合は、最後の命令を示します。出力は次のようなカラムに分割されます:


@enumerate 

@item 
the source code location of the instruction. Complete location information
is shown if `show_positions' is true. Otherwise (the default) only the
line number is displayed.

@item 
現在の命令。 @code{-->} として示されます。

@item 
ラベル付けされた命令。 @code{>>} とともに表示されます。

@item 
命令のアドレス。

@item 
命令コード名。

@item 
命令パラメタ。

@item 
パラメタの解釈を括弧で囲んだもの。
@end enumerate

パラメタの解釈は、ローカル変数とグローバル変数の名前、定数の値、 分岐先、比較命令を認識します。

`file' 引数が渡された場合は、アセンブリをそこに書き込みます。
そうでない場合は @code{sys.stdout} に出力します。


バージョン 3.4 で変更: `file' 引数が追加されました。



バージョン 3.11 で変更: Added the `show_caches' and `adaptive' parameters.



バージョン 3.13 で変更: Added the `show_offsets' parameter.



バージョン 3.14 で変更: Added the `show_positions' parameter.

@end deffn

@geindex get_instructions() (dis モジュール)
@anchor{library/dis dis get_instructions}@anchor{4ec}
@deffn {の関数} dis.get_instructions (x, *, first_line=None, show_caches=False, adaptive=False)

渡された関数、メソッド、ソースコード文字列、コードオブジェクトにある命令のイテレータを返します。

イテレータは、与えられたコードの各命令の詳細情報を保持する名前付きタプル @ref{203,,Instruction} からなる列を生成します。

`first_line' が @code{None} でない場合は、それを逆アセンブルしたコードのソースの最初の行に表示する行番号とします。
そうでない場合は、ソースの行の情報 (もしあれば) を逆アセンブルされたコードオブジェクトから直接取得します。

The `adaptive' parameter works as it does in @ref{3c,,dis()}.


Added in version 3.4.



バージョン 3.11 で変更: Added the `show_caches' and `adaptive' parameters.



バージョン 3.13 で変更: The `show_caches' parameter is deprecated and has no effect. The iterator
generates the @ref{203,,Instruction} instances with the `cache_info'
field populated (regardless of the value of `show_caches') and it no longer
generates separate items for the cache entries.

@end deffn

@geindex findlinestarts() (dis モジュール)
@anchor{library/dis dis findlinestarts}@anchor{4cbd}
@deffn {の関数} dis.findlinestarts (code)

This generator function uses the @ref{350,,co_lines()} method
of the @ref{4e6,,code object} `code' to find the offsets which
are starts of
lines in the source code.  They are generated as @code{(offset, lineno)} pairs.


バージョン 3.6 で変更: Line numbers can be decreasing. Before, they were always increasing.



バージョン 3.10 で変更: The 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/} @ref{350,,co_lines()} method is used instead of the
@ref{2390,,co_firstlineno} and @ref{330,,co_lnotab}
attributes of the @ref{4e6,,code object}.



バージョン 3.13 で変更: Line numbers can be @code{None} for bytecode that does not map to source lines.

@end deffn

@geindex findlabels() (dis モジュール)
@anchor{library/dis dis findlabels}@anchor{4cbe}
@deffn {の関数} dis.findlabels (code)

Detect all offsets in the raw compiled bytecode string `code' which are jump targets, and
return a list of these offsets.
@end deffn

@geindex stack_effect() (dis モジュール)
@anchor{library/dis dis stack_effect}@anchor{1132}
@deffn {の関数} dis.stack_effect (opcode, oparg=None, *, jump=None)

`opcode' と引数 `oparg' がスタックに与える影響を計算します。

If the code has a jump target and `jump' is @code{True}, @ref{1132,,stack_effect()}
will return the stack effect of jumping.  If `jump' is @code{False},
it will return the stack effect of not jumping. And if `jump' is
@code{None} (default), it will return the maximal stack effect of both cases.


Added in version 3.4.



バージョン 3.8 で変更: Added `jump' parameter.



バージョン 3.13 で変更: If @code{oparg} is omitted (or @code{None}), the stack effect is now returned
for @code{oparg=0}. Previously this was an error for opcodes that use their
arg. It is also no longer an error to pass an integer @code{oparg} when
the @code{opcode} does not use it; the @code{oparg} in this case is ignored.

@end deffn

@node Python バイトコード命令,命令コードコレクション,解析関数,dis --- Python バイトコードの逆アセンブラー
@anchor{library/dis bytecodes}@anchor{7cf}@anchor{library/dis python-bytecode-instructions}@anchor{4cbf}
@subsubsection Python バイトコード命令


@ref{4ec,,get_instructions()} 関数と @ref{204,,Bytecode} クラスはバイトコード命令の詳細を @ref{203,,Instruction} インスタンスの形で提供します:

@geindex Instruction (dis のクラス)
@anchor{library/dis dis Instruction}@anchor{203}
@deffn {クラス} dis.Instruction

バイトコード命令の詳細

@geindex Instruction.opcode (dis モジュール)
@anchor{library/dis dis Instruction opcode}@anchor{4cc0}
@deffn {データ} opcode

以下の命令コードの値と @ref{4cc1,,命令コードコレクション} のバイトコードの値に対応する、命令の数値コードです。
@end deffn

@geindex Instruction.opname (dis モジュール)
@anchor{library/dis dis Instruction opname}@anchor{4cc2}
@deffn {データ} opname

人間が読むための命令名
@end deffn

@geindex Instruction.baseopcode (dis モジュール)
@anchor{library/dis dis Instruction baseopcode}@anchor{4cc3}
@deffn {データ} baseopcode

numeric code for the base operation if operation is specialized;
otherwise equal to @ref{4cc0,,opcode}
@end deffn

@geindex Instruction.baseopname (dis モジュール)
@anchor{library/dis dis Instruction baseopname}@anchor{4cc4}
@deffn {データ} baseopname

human readable name for the base operation if operation is specialized;
otherwise equal to @ref{4cc5,,opname}
@end deffn

@geindex Instruction.arg (dis モジュール)
@anchor{library/dis dis Instruction arg}@anchor{4cc6}
@deffn {データ} arg

(ある場合は) 命令の数値引数、無ければ @code{None}
@end deffn

@geindex Instruction.oparg (dis モジュール)
@anchor{library/dis dis Instruction oparg}@anchor{4cc7}
@deffn {データ} oparg

alias for @ref{4cc6,,arg}
@end deffn

@geindex Instruction.argval (dis モジュール)
@anchor{library/dis dis Instruction argval}@anchor{4cc8}
@deffn {データ} argval

resolved arg value (if any), otherwise @code{None}
@end deffn

@geindex Instruction.argrepr (dis モジュール)
@anchor{library/dis dis Instruction argrepr}@anchor{4cc9}
@deffn {データ} argrepr

human readable description of operation argument (if any),
otherwise an empty string.
@end deffn

@geindex Instruction.offset (dis モジュール)
@anchor{library/dis dis Instruction offset}@anchor{4cca}
@deffn {データ} offset

バイトコード列の中での命令の開始位置
@end deffn

@geindex Instruction.start_offset (dis モジュール)
@anchor{library/dis dis Instruction start_offset}@anchor{4ccb}
@deffn {データ} start_offset

start index of operation within bytecode sequence, including prefixed
@code{EXTENDED_ARG} operations if present; otherwise equal to @ref{4cca,,offset}
@end deffn

@geindex Instruction.cache_offset (dis モジュール)
@anchor{library/dis dis Instruction cache_offset}@anchor{4ccc}
@deffn {データ} cache_offset

start index of the cache entries following the operation
@end deffn

@geindex Instruction.end_offset (dis モジュール)
@anchor{library/dis dis Instruction end_offset}@anchor{4ccd}
@deffn {データ} end_offset

end index of the cache entries following the operation
@end deffn

@geindex Instruction.starts_line (dis モジュール)
@anchor{library/dis dis Instruction starts_line}@anchor{4cce}
@deffn {データ} starts_line

@code{True} if this opcode starts a source line, otherwise @code{False}
@end deffn

@geindex Instruction.line_number (dis モジュール)
@anchor{library/dis dis Instruction line_number}@anchor{4ccf}
@deffn {データ} line_number

source line number associated with this opcode (if any), otherwise @code{None}
@end deffn

@geindex Instruction.is_jump_target (dis モジュール)
@anchor{library/dis dis Instruction is_jump_target}@anchor{4cd0}
@deffn {データ} is_jump_target

他のコードからここへジャンプする場合は @code{True} 、そうでない場合は @code{False}
@end deffn

@geindex Instruction.jump_target (dis モジュール)
@anchor{library/dis dis Instruction jump_target}@anchor{4cd1}
@deffn {データ} jump_target

bytecode index of the jump target if this is a jump operation,
otherwise @code{None}
@end deffn

@geindex Instruction.positions (dis モジュール)
@anchor{library/dis dis Instruction positions}@anchor{4cd2}
@deffn {データ} positions

@ref{1940,,dis.Positions} object holding the
start and end locations that are covered by this instruction.
@end deffn

@geindex Instruction.cache_info (dis モジュール)
@anchor{library/dis dis Instruction cache_info}@anchor{4cd3}
@deffn {データ} cache_info

Information about the cache entries of this instruction, as
triplets of the form @code{(name, size, data)}, where the @code{name}
and @code{size} describe the cache format and data is the contents
of the cache. @code{cache_info} is @code{None} if the instruction does not have
caches.
@end deffn


Added in version 3.4.



バージョン 3.11 で変更: Field @code{positions} is added.



バージョン 3.13 で変更: Changed field @code{starts_line}.

Added fields @code{start_offset}, @code{cache_offset}, @code{end_offset},
@code{baseopname}, @code{baseopcode}, @code{jump_target}, @code{oparg},
@code{line_number} and @code{cache_info}.

@end deffn

@geindex Positions (dis のクラス)
@anchor{library/dis dis Positions}@anchor{1940}
@deffn {クラス} dis.Positions

In case the information is not available, some fields might be @code{None}.

@geindex Positions.lineno (dis モジュール)
@anchor{library/dis dis Positions lineno}@anchor{4cd4}
@deffn {データ} lineno
@end deffn

@geindex Positions.end_lineno (dis モジュール)
@anchor{library/dis dis Positions end_lineno}@anchor{4cd5}
@deffn {データ} end_lineno
@end deffn

@geindex Positions.col_offset (dis モジュール)
@anchor{library/dis dis Positions col_offset}@anchor{4cd6}
@deffn {データ} col_offset
@end deffn

@geindex Positions.end_col_offset (dis モジュール)
@anchor{library/dis dis Positions end_col_offset}@anchor{4cd7}
@deffn {データ} end_col_offset
@end deffn


Added in version 3.11.

@end deffn

現在 Python コンパイラは次のバイトコード命令を生成します。

`一般的な命令'

In the following, We will refer to the interpreter stack as @code{STACK} and describe
operations on it as if it was a Python list. The top of the stack corresponds to
@code{STACK[-1]} in this language.

@geindex NOP (opcode)
@anchor{library/dis opcode-NOP}@anchor{4cd8}
@deffn {Opcode} NOP

Do nothing code.  Used as a placeholder by the bytecode optimizer, and to
generate line tracing events.
@end deffn

@geindex NOT_TAKEN (opcode)
@anchor{library/dis opcode-NOT_TAKEN}@anchor{376}
@deffn {Opcode} NOT_TAKEN

Do nothing code.
Used by the interpreter to record @ref{295,,BRANCH_LEFT}
and @ref{296,,BRANCH_RIGHT} events for @ref{e0,,sys.monitoring}.


Added in version 3.14.

@end deffn

@geindex POP_ITER (opcode)
@anchor{library/dis opcode-POP_ITER}@anchor{370}
@deffn {Opcode} POP_ITER

Removes the iterator from the top of the stack.


Added in version 3.14.

@end deffn

@geindex POP_TOP (opcode)
@anchor{library/dis opcode-POP_TOP}@anchor{4cd9}
@deffn {Opcode} POP_TOP

Removes the top-of-stack item:

@example
STACK.pop()
@end example
@end deffn

@geindex END_FOR (opcode)
@anchor{library/dis opcode-END_FOR}@anchor{4cda}
@deffn {Opcode} END_FOR

Removes the top-of-stack item.
Equivalent to @code{POP_TOP}.
Used to clean up at the end of loops, hence the name.


Added in version 3.12.

@end deffn

@geindex END_SEND (opcode)
@anchor{library/dis opcode-END_SEND}@anchor{4cdb}
@deffn {Opcode} END_SEND

Implements @code{del STACK[-2]}.
Used to clean up when a generator exits.


Added in version 3.12.

@end deffn

@geindex COPY (opcode)
@anchor{library/dis opcode-COPY}@anchor{917}
@deffn {Opcode} COPY (i)

Push the i-th item to the top of the stack without removing it from its original
location:

@example
assert i > 0
STACK.append(STACK[-i])
@end example


Added in version 3.11.

@end deffn

@geindex SWAP (opcode)
@anchor{library/dis opcode-SWAP}@anchor{918}
@deffn {Opcode} SWAP (i)

Swap the top of the stack with the i-th element:

@example
STACK[-i], STACK[-1] = STACK[-1], STACK[-i]
@end example


Added in version 3.11.

@end deffn

@geindex CACHE (opcode)
@anchor{library/dis opcode-CACHE}@anchor{908}
@deffn {Opcode} CACHE

Rather than being an actual instruction, this opcode is used to mark extra
space for the interpreter to cache useful data directly in the bytecode
itself. It is automatically hidden by all @code{dis} utilities, but can be
viewed with @code{show_caches=True}.

Logically, this space is part of the preceding instruction. Many opcodes
expect to be followed by an exact number of caches, and will instruct the
interpreter to skip over them at runtime.

Populated caches can look like arbitrary instructions, so great care should
be taken when reading or modifying raw, adaptive bytecode containing
quickened data.


Added in version 3.11.

@end deffn

`1オペランド命令'

1オペランド命令はスタックの先頭を取り出して操作を適用し、結果をスタックへプッシュし戻します。

@geindex UNARY_NEGATIVE (opcode)
@anchor{library/dis opcode-UNARY_NEGATIVE}@anchor{4cdc}
@deffn {Opcode} UNARY_NEGATIVE

Implements @code{STACK[-1] = -STACK[-1]}.
@end deffn

@geindex UNARY_NOT (opcode)
@anchor{library/dis opcode-UNARY_NOT}@anchor{1a61}
@deffn {Opcode} UNARY_NOT

Implements @code{STACK[-1] = not STACK[-1]}.


バージョン 3.13 で変更: This instruction now requires an exact @ref{3c3,,bool} operand.

@end deffn

@geindex UNARY_INVERT (opcode)
@anchor{library/dis opcode-UNARY_INVERT}@anchor{4cdd}
@deffn {Opcode} UNARY_INVERT

Implements @code{STACK[-1] = ~STACK[-1]}.
@end deffn

@geindex GET_ITER (opcode)
@anchor{library/dis opcode-GET_ITER}@anchor{4cde}
@deffn {Opcode} GET_ITER

Implements @code{STACK[-1] = iter(STACK[-1])}.
@end deffn

@geindex GET_YIELD_FROM_ITER (opcode)
@anchor{library/dis opcode-GET_YIELD_FROM_ITER}@anchor{4cdf}
@deffn {Opcode} GET_YIELD_FROM_ITER

If @code{STACK[-1]} is a @ref{dd9,,generator iterator} or @ref{6b9,,coroutine} object
it is left as is.  Otherwise, implements @code{STACK[-1] = iter(STACK[-1])}.


Added in version 3.5.

@end deffn

@geindex TO_BOOL (opcode)
@anchor{library/dis opcode-TO_BOOL}@anchor{1a5e}
@deffn {Opcode} TO_BOOL

Implements @code{STACK[-1] = bool(STACK[-1])}.


Added in version 3.13.

@end deffn

`Binary and in-place operations'

Binary operations remove the top two items from the stack (@code{STACK[-1]} and
@code{STACK[-2]}). They perform the operation, then put the result back on the stack.

In-place operations are like binary operations, but the operation is done in-place
when @code{STACK[-2]} supports it, and the resulting @code{STACK[-1]} may be (but does
not have to be) the original @code{STACK[-2]}.

@geindex BINARY_OP (opcode)
@anchor{library/dis opcode-BINARY_OP}@anchor{366}
@deffn {Opcode} BINARY_OP (op)

Implements the binary and in-place operators (depending on the value of
`op'):

@example
rhs = STACK.pop()
lhs = STACK.pop()
STACK.append(lhs op rhs)
@end example


Added in version 3.11.



バージョン 3.14 で変更: With oparg :@code{NB_SUBSCR}, implements binary subscript (replaces opcode @code{BINARY_SUBSCR})

@end deffn

@geindex STORE_SUBSCR (opcode)
@anchor{library/dis opcode-STORE_SUBSCR}@anchor{1bab}
@deffn {Opcode} STORE_SUBSCR

Implements:

@example
key = STACK.pop()
container = STACK.pop()
value = STACK.pop()
container[key] = value
@end example
@end deffn

@geindex DELETE_SUBSCR (opcode)
@anchor{library/dis opcode-DELETE_SUBSCR}@anchor{4ce0}
@deffn {Opcode} DELETE_SUBSCR

Implements:

@example
key = STACK.pop()
container = STACK.pop()
del container[key]
@end example
@end deffn

@geindex BINARY_SLICE (opcode)
@anchor{library/dis opcode-BINARY_SLICE}@anchor{705}
@deffn {Opcode} BINARY_SLICE

Implements:

@example
end = STACK.pop()
start = STACK.pop()
container = STACK.pop()
STACK.append(container[start:end])
@end example


Added in version 3.12.

@end deffn

@geindex STORE_SLICE (opcode)
@anchor{library/dis opcode-STORE_SLICE}@anchor{706}
@deffn {Opcode} STORE_SLICE

Implements:

@example
end = STACK.pop()
start = STACK.pop()
container = STACK.pop()
value = STACK.pop()
container[start:end] = value
@end example


Added in version 3.12.

@end deffn

`コルーチン命令コード'

@geindex GET_AWAITABLE (opcode)
@anchor{library/dis opcode-GET_AWAITABLE}@anchor{1bc7}
@deffn {Opcode} GET_AWAITABLE (where)

Implements @code{STACK[-1] = get_awaitable(STACK[-1])}, where @code{get_awaitable(o)}
returns @code{o} if @code{o} is a coroutine object or a generator object with
the @ref{4a5a,,CO_ITERABLE_COROUTINE} flag, or resolves
@code{o.__await__}.

@quotation

If the @code{where} operand is nonzero, it indicates where the instruction
occurs:


@itemize *

@item 
@code{1}: After a call to @code{__aenter__}

@item 
@code{2}: After a call to @code{__aexit__}
@end itemize
@end quotation


Added in version 3.5.



バージョン 3.11 で変更: Previously, this instruction did not have an oparg.

@end deffn

@geindex GET_AITER (opcode)
@anchor{library/dis opcode-GET_AITER}@anchor{4ce1}
@deffn {Opcode} GET_AITER

Implements @code{STACK[-1] = STACK[-1].__aiter__()}.


Added in version 3.5.



バージョン 3.7 で変更: Returning awaitable objects from @code{__aiter__} is no longer
supported.

@end deffn

@geindex GET_ANEXT (opcode)
@anchor{library/dis opcode-GET_ANEXT}@anchor{4ce2}
@deffn {Opcode} GET_ANEXT

Implement @code{STACK.append(get_awaitable(STACK[-1].__anext__()))} to the stack.
See @code{GET_AWAITABLE} for details about @code{get_awaitable}.


Added in version 3.5.

@end deffn

@geindex END_ASYNC_FOR (opcode)
@anchor{library/dis opcode-END_ASYNC_FOR}@anchor{ca0}
@deffn {Opcode} END_ASYNC_FOR

Terminates an @ref{ca1,,async for} loop.  Handles an exception raised
when awaiting a next item. The stack contains the async iterable in
@code{STACK[-2]} and the raised exception in @code{STACK[-1]}. Both are popped.
If the exception is not @ref{1e0f,,StopAsyncIteration}, it is re-raised.


Added in version 3.8.



バージョン 3.11 で変更: Exception representation on the stack now consist of one, not three, items.

@end deffn

@geindex CLEANUP_THROW (opcode)
@anchor{library/dis opcode-CLEANUP_THROW}@anchor{709}
@deffn {Opcode} CLEANUP_THROW

Handles an exception raised during a @ref{71c,,throw()} or
@ref{1793,,close()} call through the current frame.  If @code{STACK[-1]} is an
instance of @ref{df5,,StopIteration}, pop three values from the stack and push
its @code{value} member.  Otherwise, re-raise @code{STACK[-1]}.


Added in version 3.12.

@end deffn

`その他の命令コード'

@geindex SET_ADD (opcode)
@anchor{library/dis opcode-SET_ADD}@anchor{4ce3}
@deffn {Opcode} SET_ADD (i)

Implements:

@example
item = STACK.pop()
set.add(STACK[-i], item)
@end example

Used to implement set comprehensions.
@end deffn

@geindex LIST_APPEND (opcode)
@anchor{library/dis opcode-LIST_APPEND}@anchor{4ce4}
@deffn {Opcode} LIST_APPEND (i)

Implements:

@example
item = STACK.pop()
list.append(STACK[-i], item)
@end example

Used to implement list comprehensions.
@end deffn

@geindex MAP_ADD (opcode)
@anchor{library/dis opcode-MAP_ADD}@anchor{ca2}
@deffn {Opcode} MAP_ADD (i)

Implements:

@example
value = STACK.pop()
key = STACK.pop()
dict.__setitem__(STACK[-i], key, value)
@end example

Used to implement dict comprehensions.


Added in version 3.1.



バージョン 3.8 で変更: Map value is @code{STACK[-1]} and map key is @code{STACK[-2]}. Before, those
were reversed.

@end deffn

@ref{4ce3,,SET_ADD}, @ref{4ce4,,LIST_APPEND}, @ref{ca2,,MAP_ADD} は、追加した値または key/value ペアをスタックから取り除きますが、コンテナオブジェクトはループの次のイテレーションで利用できるようにスタックに残しておきます。

@geindex RETURN_VALUE (opcode)
@anchor{library/dis opcode-RETURN_VALUE}@anchor{1b20}
@deffn {Opcode} RETURN_VALUE

Returns with @code{STACK[-1]} to the caller of the function.
@end deffn

@geindex YIELD_VALUE (opcode)
@anchor{library/dis opcode-YIELD_VALUE}@anchor{5ba}
@deffn {Opcode} YIELD_VALUE

Yields @code{STACK.pop()} from a @ref{126c,,generator}.


バージョン 3.11 で変更: oparg set to be the stack depth.



バージョン 3.12 で変更: oparg set to be the exception block depth, for efficient closing of generators.



バージョン 3.13 で変更: oparg is @code{1} if this instruction is part of a yield-from or await, and @code{0}
otherwise.

@end deffn

@geindex SETUP_ANNOTATIONS (opcode)
@anchor{library/dis opcode-SETUP_ANNOTATIONS}@anchor{f50}
@deffn {Opcode} SETUP_ANNOTATIONS

Checks whether @code{__annotations__} is defined in @code{locals()}, if not it is
set up to an empty @code{dict}. This opcode is only emitted if a class
or module body contains @ref{f51,,variable annotations}
statically.


Added in version 3.6.

@end deffn

@geindex POP_EXCEPT (opcode)
@anchor{library/dis opcode-POP_EXCEPT}@anchor{4ce5}
@deffn {Opcode} POP_EXCEPT

Pops a value from the stack, which is used to restore the exception state.


バージョン 3.11 で変更: Exception representation on the stack now consist of one, not three, items.

@end deffn

@geindex RERAISE (opcode)
@anchor{library/dis opcode-RERAISE}@anchor{4ce6}
@deffn {Opcode} RERAISE

Re-raises the exception currently on top of the stack. If oparg is non-zero,
pops an additional value from the stack which is used to set
@ref{a88,,f_lasti} of the current frame.


Added in version 3.9.



バージョン 3.11 で変更: Exception representation on the stack now consist of one, not three, items.

@end deffn

@geindex PUSH_EXC_INFO (opcode)
@anchor{library/dis opcode-PUSH_EXC_INFO}@anchor{912}
@deffn {Opcode} PUSH_EXC_INFO

Pops a value from the stack. Pushes the current exception to the top of the stack.
Pushes the value originally popped back to the stack.
Used in exception handlers.


Added in version 3.11.

@end deffn

@geindex CHECK_EXC_MATCH (opcode)
@anchor{library/dis opcode-CHECK_EXC_MATCH}@anchor{919}
@deffn {Opcode} CHECK_EXC_MATCH

Performs exception matching for @code{except}. Tests whether the @code{STACK[-2]}
is an exception matching @code{STACK[-1]}. Pops @code{STACK[-1]} and pushes the boolean
result of the test.


Added in version 3.11.

@end deffn

@geindex CHECK_EG_MATCH (opcode)
@anchor{library/dis opcode-CHECK_EG_MATCH}@anchor{911}
@deffn {Opcode} CHECK_EG_MATCH

Performs exception matching for @code{except*}. Applies @code{split(STACK[-1])} on
the exception group representing @code{STACK[-2]}.

In case of a match, pops two items from the stack and pushes the
non-matching subgroup (@code{None} in case of full match) followed by the
matching subgroup. When there is no match, pops one item (the match
type) and pushes @code{None}.


Added in version 3.11.

@end deffn

@geindex WITH_EXCEPT_START (opcode)
@anchor{library/dis opcode-WITH_EXCEPT_START}@anchor{4ce7}
@deffn {Opcode} WITH_EXCEPT_START

Calls the function in position 4 on the stack with arguments (type, val, tb)
representing the exception at the top of the stack.
Used to implement the call @code{context_manager.__exit__(*exc_info())} when an exception
has occurred in a @ref{186,,with} statement.


Added in version 3.9.



バージョン 3.11 で変更: The @code{__exit__} function is in position 4 of the stack rather than 7.
Exception representation on the stack now consist of one, not three, items.

@end deffn

@geindex LOAD_COMMON_CONSTANT (opcode)
@anchor{library/dis opcode-LOAD_COMMON_CONSTANT}@anchor{36a}
@deffn {Opcode} LOAD_COMMON_CONSTANT

Pushes a common constant onto the stack. The interpreter contains a hardcoded
list of constants supported by this instruction.  Used by the @ref{b60,,assert}
statement to load @ref{8b8,,AssertionError}.


Added in version 3.14.

@end deffn

@geindex LOAD_BUILD_CLASS (opcode)
@anchor{library/dis opcode-LOAD_BUILD_CLASS}@anchor{4ce8}
@deffn {Opcode} LOAD_BUILD_CLASS

Pushes @code{builtins.__build_class__()} onto the stack.  It is later called
to construct a class.
@end deffn

@geindex GET_LEN (opcode)
@anchor{library/dis opcode-GET_LEN}@anchor{4ce9}
@deffn {Opcode} GET_LEN

Perform @code{STACK.append(len(STACK[-1]))}. Used in @ref{a0e,,match} statements where
comparison with structure of pattern is needed.


Added in version 3.10.

@end deffn

@geindex MATCH_MAPPING (opcode)
@anchor{library/dis opcode-MATCH_MAPPING}@anchor{4cea}
@deffn {Opcode} MATCH_MAPPING

If @code{STACK[-1]} is an instance of @ref{ac7,,collections.abc.Mapping} (or, more
technically: if it has the @ref{1c58,,Py_TPFLAGS_MAPPING} flag set in its
@ref{1c71,,tp_flags}), push @code{True} onto the stack.  Otherwise,
push @code{False}.


Added in version 3.10.

@end deffn

@geindex MATCH_SEQUENCE (opcode)
@anchor{library/dis opcode-MATCH_SEQUENCE}@anchor{4ceb}
@deffn {Opcode} MATCH_SEQUENCE

If @code{STACK[-1]} is an instance of @ref{13dc,,collections.abc.Sequence} and is `not' an instance
of @ref{169,,str}/@ref{192,,bytes}/@ref{344,,bytearray} (or, more technically: if it has
the @ref{1c59,,Py_TPFLAGS_SEQUENCE} flag set in its @ref{1c71,,tp_flags}),
push @code{True} onto the stack.  Otherwise, push @code{False}.


Added in version 3.10.

@end deffn

@geindex MATCH_KEYS (opcode)
@anchor{library/dis opcode-MATCH_KEYS}@anchor{920}
@deffn {Opcode} MATCH_KEYS

@code{STACK[-1]} is a tuple of mapping keys, and @code{STACK[-2]} is the match subject.
If @code{STACK[-2]} contains all of the keys in @code{STACK[-1]}, push a @ref{614,,tuple}
containing the corresponding values. Otherwise, push @code{None}.


Added in version 3.10.



バージョン 3.11 で変更: Previously, this instruction also pushed a boolean value indicating
success (@code{True}) or failure (@code{False}).

@end deffn

@geindex STORE_NAME (opcode)
@anchor{library/dis opcode-STORE_NAME}@anchor{4cec}
@deffn {Opcode} STORE_NAME (namei)

Implements @code{name = STACK.pop()}. `namei' is the index of `name' in the attribute
@ref{238f,,co_names} of the @ref{4e6,,code object}.
The compiler tries to use @ref{1a63,,STORE_FAST} or @ref{4ced,,STORE_GLOBAL} if possible.
@end deffn

@geindex DELETE_NAME (opcode)
@anchor{library/dis opcode-DELETE_NAME}@anchor{4cee}
@deffn {Opcode} DELETE_NAME (namei)

Implements @code{del name}, where `namei' is the index into @ref{238f,,co_names}
attribute of the @ref{4e6,,code object}.
@end deffn

@geindex UNPACK_SEQUENCE (opcode)
@anchor{library/dis opcode-UNPACK_SEQUENCE}@anchor{1bc9}
@deffn {Opcode} UNPACK_SEQUENCE (count)

Unpacks @code{STACK[-1]} into `count' individual values, which are put onto the stack
right-to-left. Require there to be exactly `count' values.:

@example
assert(len(STACK[-1]) == count)
STACK.extend(STACK.pop()[:-count-1:-1])
@end example
@end deffn

@geindex UNPACK_EX (opcode)
@anchor{library/dis opcode-UNPACK_EX}@anchor{4cef}
@deffn {Opcode} UNPACK_EX (counts)

Implements assignment with a starred target: Unpacks an iterable in @code{STACK[-1]}
into individual values, where the total number of values can be smaller than the
number of items in the iterable: one of the new values will be a list of all
leftover items.

The number of values before and after the list value is limited to 255.

The number of values before the list value is encoded in the argument of the
opcode. The number of values after the list if any is encoded using an
@code{EXTENDED_ARG}. As a consequence, the argument can be seen as a two bytes values
where the low byte of `counts' is the number of values before the list value, the
high byte of `counts' the number of values after it.

The extracted values are put onto the stack right-to-left, i.e. @code{a, *b, c = d}
will be stored after execution as @code{STACK.extend((a, b, c))}.
@end deffn

@geindex STORE_ATTR (opcode)
@anchor{library/dis opcode-STORE_ATTR}@anchor{1bc8}
@deffn {Opcode} STORE_ATTR (namei)

Implements:

@example
obj = STACK.pop()
value = STACK.pop()
obj.name = value
@end example

where `namei' is the index of name in @ref{238f,,co_names} of the
@ref{4e6,,code object}.
@end deffn

@geindex DELETE_ATTR (opcode)
@anchor{library/dis opcode-DELETE_ATTR}@anchor{4cf0}
@deffn {Opcode} DELETE_ATTR (namei)

Implements:

@example
obj = STACK.pop()
del obj.name
@end example

where `namei' is the index of name into @ref{238f,,co_names} of the
@ref{4e6,,code object}.
@end deffn

@geindex STORE_GLOBAL (opcode)
@anchor{library/dis opcode-STORE_GLOBAL}@anchor{4ced}
@deffn {Opcode} STORE_GLOBAL (namei)

@ref{4cec,,STORE_NAME} と同じように動作しますが、 name をグローバルとして保存します。
@end deffn

@geindex DELETE_GLOBAL (opcode)
@anchor{library/dis opcode-DELETE_GLOBAL}@anchor{4cf1}
@deffn {Opcode} DELETE_GLOBAL (namei)

@ref{4cee,,DELETE_NAME} と同じように動作しますが、グローバルの name を削除します。
@end deffn

@geindex LOAD_CONST (opcode)
@anchor{library/dis opcode-LOAD_CONST}@anchor{4cf2}
@deffn {Opcode} LOAD_CONST (consti)

@code{co_consts[consti]} をスタックにプッシュします。
@end deffn

@geindex LOAD_SMALL_INT (opcode)
@anchor{library/dis opcode-LOAD_SMALL_INT}@anchor{36e}
@deffn {Opcode} LOAD_SMALL_INT (i)

Pushes the integer @code{i} onto the stack.
@code{i} must be in @code{range(256)}


Added in version 3.14.

@end deffn

@geindex LOAD_NAME (opcode)
@anchor{library/dis opcode-LOAD_NAME}@anchor{4cf3}
@deffn {Opcode} LOAD_NAME (namei)

Pushes the value associated with @code{co_names[namei]} onto the stack.
The name is looked up within the locals, then the globals, then the builtins.
@end deffn

@geindex LOAD_LOCALS (opcode)
@anchor{library/dis opcode-LOAD_LOCALS}@anchor{70e}
@deffn {Opcode} LOAD_LOCALS

Pushes a reference to the locals dictionary onto the stack.  This is used
to prepare namespace dictionaries for @ref{70c,,LOAD_FROM_DICT_OR_DEREF}
and @ref{70d,,LOAD_FROM_DICT_OR_GLOBALS}.


Added in version 3.12.

@end deffn

@geindex LOAD_FROM_DICT_OR_GLOBALS (opcode)
@anchor{library/dis opcode-LOAD_FROM_DICT_OR_GLOBALS}@anchor{70d}
@deffn {Opcode} LOAD_FROM_DICT_OR_GLOBALS (i)

Pops a mapping off the stack and looks up the value for @code{co_names[namei]}.
If the name is not found there, looks it up in the globals and then the builtins,
similar to @ref{1a5a,,LOAD_GLOBAL}.
This is used for loading global variables in
@ref{4ab,,annotation scopes} within class bodies.


Added in version 3.12.

@end deffn

@geindex BUILD_TEMPLATE (opcode)
@anchor{library/dis opcode-BUILD_TEMPLATE}@anchor{368}
@deffn {Opcode} BUILD_TEMPLATE

Constructs a new @ref{16a,,Template} instance from a tuple
of strings and a tuple of interpolations and pushes the resulting object
onto the stack:

@example
interpolations = STACK.pop()
strings = STACK.pop()
STACK.append(_build_template(strings, interpolations))
@end example


Added in version 3.14.

@end deffn

@geindex BUILD_INTERPOLATION (opcode)
@anchor{library/dis opcode-BUILD_INTERPOLATION}@anchor{367}
@deffn {Opcode} BUILD_INTERPOLATION (format)

Constructs a new @ref{16b,,Interpolation} instance from a
value and its source expression and pushes the resulting object onto the
stack.

If no conversion or format specification is present, @code{format} is set to
@code{2}.

If the low bit of @code{format} is set, it indicates that the interpolation
contains a format specification.

If @code{format >> 2} is non-zero, it indicates that the interpolation
contains a conversion. The value of @code{format >> 2} is the conversion type
(@code{0} for no conversion, @code{1} for @code{!s}, @code{2} for @code{!r}, and
@code{3} for @code{!a}):

@example
conversion = format >> 2
if format & 1:
    format_spec = STACK.pop()
else:
    format_spec = None
expression = STACK.pop()
value = STACK.pop()
STACK.append(_build_interpolation(value, expression, conversion, format_spec))
@end example


Added in version 3.14.

@end deffn

@geindex BUILD_TUPLE (opcode)
@anchor{library/dis opcode-BUILD_TUPLE}@anchor{4cf4}
@deffn {Opcode} BUILD_TUPLE (count)

Creates a tuple consuming `count' items from the stack, and pushes the
resulting tuple onto the stack:

@example
if count == 0:
    value = ()
else:
    value = tuple(STACK[-count:])
    STACK = STACK[:-count]

STACK.append(value)
@end example
@end deffn

@geindex BUILD_LIST (opcode)
@anchor{library/dis opcode-BUILD_LIST}@anchor{4cf5}
@deffn {Opcode} BUILD_LIST (count)

@ref{4cf4,,BUILD_TUPLE} と同じように動作しますが、この命令はリストを作り出します。
@end deffn

@geindex BUILD_SET (opcode)
@anchor{library/dis opcode-BUILD_SET}@anchor{4cf6}
@deffn {Opcode} BUILD_SET (count)

@ref{4cf4,,BUILD_TUPLE} と同じように動作しますが、この命令は set を作り出します。
@end deffn

@geindex BUILD_MAP (opcode)
@anchor{library/dis opcode-BUILD_MAP}@anchor{369}
@deffn {Opcode} BUILD_MAP (count)

Pushes a new dictionary object onto the stack.  Pops @code{2 * count} items
so that the dictionary holds `count' entries:
@code{@{..., STACK[-4]: STACK[-3], STACK[-2]: STACK[-1]@}}.


バージョン 3.5 で変更: The dictionary is created from stack items instead of creating an
empty dictionary pre-sized to hold `count' items.

@end deffn

@geindex BUILD_STRING (opcode)
@anchor{library/dis opcode-BUILD_STRING}@anchor{f4d}
@deffn {Opcode} BUILD_STRING (count)

Concatenates `count' strings from the stack and pushes the resulting string
onto the stack.


Added in version 3.6.

@end deffn

@geindex LIST_EXTEND (opcode)
@anchor{library/dis opcode-LIST_EXTEND}@anchor{4cf7}
@deffn {Opcode} LIST_EXTEND (i)

Implements:

@example
seq = STACK.pop()
list.extend(STACK[-i], seq)
@end example

Used to build lists.


Added in version 3.9.

@end deffn

@geindex SET_UPDATE (opcode)
@anchor{library/dis opcode-SET_UPDATE}@anchor{4cf8}
@deffn {Opcode} SET_UPDATE (i)

Implements:

@example
seq = STACK.pop()
set.update(STACK[-i], seq)
@end example

Used to build sets.


Added in version 3.9.

@end deffn

@geindex DICT_UPDATE (opcode)
@anchor{library/dis opcode-DICT_UPDATE}@anchor{4cf9}
@deffn {Opcode} DICT_UPDATE (i)

Implements:

@example
map = STACK.pop()
dict.update(STACK[-i], map)
@end example

Used to build dicts.


Added in version 3.9.

@end deffn

@geindex DICT_MERGE (opcode)
@anchor{library/dis opcode-DICT_MERGE}@anchor{4cfa}
@deffn {Opcode} DICT_MERGE (i)

Like @ref{4cf9,,DICT_UPDATE} but raises an exception for duplicate keys.


Added in version 3.9.

@end deffn

@geindex LOAD_ATTR (opcode)
@anchor{library/dis opcode-LOAD_ATTR}@anchor{704}
@deffn {Opcode} LOAD_ATTR (namei)

If the low bit of @code{namei} is not set, this replaces @code{STACK[-1]} with
@code{getattr(STACK[-1], co_names[namei>>1])}.

If the low bit of @code{namei} is set, this will attempt to load a method named
@code{co_names[namei>>1]} from the @code{STACK[-1]} object. @code{STACK[-1]} is popped.
This bytecode distinguishes two cases: if @code{STACK[-1]} has a method with the
correct name, the bytecode pushes the unbound method and @code{STACK[-1]}.
@code{STACK[-1]} will be used as the first argument (@code{self}) by @ref{915,,CALL}
or @ref{372,,CALL_KW} when calling the unbound method.
Otherwise, @code{NULL} and the object returned by
the attribute lookup are pushed.


バージョン 3.12 で変更: If the low bit of @code{namei} is set, then a @code{NULL} or @code{self} is
pushed to the stack before the attribute or unbound method respectively.

@end deffn

@geindex LOAD_SUPER_ATTR (opcode)
@anchor{library/dis opcode-LOAD_SUPER_ATTR}@anchor{702}
@deffn {Opcode} LOAD_SUPER_ATTR (namei)

This opcode implements @ref{1a6,,super()}, both in its zero-argument and
two-argument forms (e.g. @code{super().method()}, @code{super().attr} and
@code{super(cls, self).method()}, @code{super(cls, self).attr}).

It pops three values from the stack (from top of stack down):


@itemize *

@item 
@code{self}: the first argument to the current method

@item 
@code{cls}: the class within which the current method was defined

@item 
the global @code{super}
@end itemize

With respect to its argument, it works similarly to @ref{704,,LOAD_ATTR},
except that @code{namei} is shifted left by 2 bits instead of 1.

The low bit of @code{namei} signals to attempt a method load, as with
@ref{704,,LOAD_ATTR}, which results in pushing @code{NULL} and the loaded method.
When it is unset a single value is pushed to the stack.

The second-low bit of @code{namei}, if set, means that this was a two-argument
call to @ref{1a6,,super()} (unset means zero-argument).


Added in version 3.12.

@end deffn

@geindex COMPARE_OP (opcode)
@anchor{library/dis opcode-COMPARE_OP}@anchor{b61}
@deffn {Opcode} COMPARE_OP (opname)

Performs a Boolean operation.  The operation name can be found in
@code{cmp_op[opname >> 5]}. If the fifth-lowest bit of @code{opname} is set
(@code{opname & 16}), the result should be coerced to @code{bool}.


バージョン 3.13 で変更: The fifth-lowest bit of the oparg now indicates a forced conversion to
@ref{3c3,,bool}.

@end deffn

@geindex IS_OP (opcode)
@anchor{library/dis opcode-IS_OP}@anchor{193c}
@deffn {Opcode} IS_OP (invert)

Performs @code{is} comparison, or @code{is not} if @code{invert} is 1.


Added in version 3.9.

@end deffn

@geindex CONTAINS_OP (opcode)
@anchor{library/dis opcode-CONTAINS_OP}@anchor{193b}
@deffn {Opcode} CONTAINS_OP (invert)

Performs @code{in} comparison, or @code{not in} if @code{invert} is 1.


Added in version 3.9.

@end deffn

@geindex IMPORT_NAME (opcode)
@anchor{library/dis opcode-IMPORT_NAME}@anchor{4cfb}
@deffn {Opcode} IMPORT_NAME (namei)

Imports the module @code{co_names[namei]}.  @code{STACK[-1]} and @code{STACK[-2]} are
popped and provide the `fromlist' and `level' arguments of @ref{ad1,,__import__()}.
The module object is pushed onto the stack.  The current namespace is not affected: for a proper import statement, a subsequent @ref{1a63,,STORE_FAST} instruction
modifies the namespace.
@end deffn

@geindex IMPORT_FROM (opcode)
@anchor{library/dis opcode-IMPORT_FROM}@anchor{4cfc}
@deffn {Opcode} IMPORT_FROM (namei)

Loads the attribute @code{co_names[namei]} from the module found in @code{STACK[-1]}.
The resulting object is pushed onto the stack, to be subsequently stored by a
@ref{1a63,,STORE_FAST} instruction.
@end deffn

@geindex JUMP_FORWARD (opcode)
@anchor{library/dis opcode-JUMP_FORWARD}@anchor{1972}
@deffn {Opcode} JUMP_FORWARD (delta)

バイトコードカウンタを `delta' だけ増加させます。
@end deffn

@geindex JUMP_BACKWARD (opcode)
@anchor{library/dis opcode-JUMP_BACKWARD}@anchor{91a}
@deffn {Opcode} JUMP_BACKWARD (delta)

Decrements bytecode counter by `delta'. Checks for interrupts.


Added in version 3.11.

@end deffn

@geindex JUMP_BACKWARD_NO_INTERRUPT (opcode)
@anchor{library/dis opcode-JUMP_BACKWARD_NO_INTERRUPT}@anchor{90e}
@deffn {Opcode} JUMP_BACKWARD_NO_INTERRUPT (delta)

Decrements bytecode counter by `delta'. Does not check for interrupts.


Added in version 3.11.

@end deffn

@geindex POP_JUMP_IF_TRUE (opcode)
@anchor{library/dis opcode-POP_JUMP_IF_TRUE}@anchor{1a5f}
@deffn {Opcode} POP_JUMP_IF_TRUE (delta)

If @code{STACK[-1]} is true, increments the bytecode counter by `delta'.
@code{STACK[-1]} is popped.


バージョン 3.11 で変更: The oparg is now a relative delta rather than an absolute target.
This opcode is a pseudo-instruction, replaced in final bytecode by
the directed versions (forward/backward).



バージョン 3.12 で変更: This is no longer a pseudo-instruction.



バージョン 3.13 で変更: This instruction now requires an exact @ref{3c3,,bool} operand.

@end deffn

@geindex POP_JUMP_IF_FALSE (opcode)
@anchor{library/dis opcode-POP_JUMP_IF_FALSE}@anchor{1a60}
@deffn {Opcode} POP_JUMP_IF_FALSE (delta)

If @code{STACK[-1]} is false, increments the bytecode counter by `delta'.
@code{STACK[-1]} is popped.


バージョン 3.11 で変更: The oparg is now a relative delta rather than an absolute target.
This opcode is a pseudo-instruction, replaced in final bytecode by
the directed versions (forward/backward).



バージョン 3.12 で変更: This is no longer a pseudo-instruction.



バージョン 3.13 で変更: This instruction now requires an exact @ref{3c3,,bool} operand.

@end deffn

@geindex POP_JUMP_IF_NOT_NONE (opcode)
@anchor{library/dis opcode-POP_JUMP_IF_NOT_NONE}@anchor{1b80}
@deffn {Opcode} POP_JUMP_IF_NOT_NONE (delta)

If @code{STACK[-1]} is not @code{None}, increments the bytecode counter by `delta'.
@code{STACK[-1]} is popped.


Added in version 3.11.



バージョン 3.12 で変更: This is no longer a pseudo-instruction.

@end deffn

@geindex POP_JUMP_IF_NONE (opcode)
@anchor{library/dis opcode-POP_JUMP_IF_NONE}@anchor{1b7f}
@deffn {Opcode} POP_JUMP_IF_NONE (delta)

If @code{STACK[-1]} is @code{None}, increments the bytecode counter by `delta'.
@code{STACK[-1]} is popped.


Added in version 3.11.



バージョン 3.12 で変更: This is no longer a pseudo-instruction.

@end deffn

@geindex FOR_ITER (opcode)
@anchor{library/dis opcode-FOR_ITER}@anchor{1ac2}
@deffn {Opcode} FOR_ITER (delta)

@code{STACK[-1]} is an @ref{4c8,,iterator}.  Call its @ref{14e5,,__next__()} method.
If this yields a new value, push it on the stack (leaving the iterator below
it).  If the iterator indicates it is exhausted then the byte code counter is
incremented by `delta'.


バージョン 3.12 で変更: Up until 3.11 the iterator was popped when it was exhausted.

@end deffn

@geindex LOAD_GLOBAL (opcode)
@anchor{library/dis opcode-LOAD_GLOBAL}@anchor{1a5a}
@deffn {Opcode} LOAD_GLOBAL (namei)

@code{co_names[namei>>1]} という名前のグローバルをスタック上にロードします。


バージョン 3.11 で変更: If the low bit of @code{namei} is set, then a @code{NULL} is pushed to the
stack before the global variable.

@end deffn

@geindex LOAD_FAST (opcode)
@anchor{library/dis opcode-LOAD_FAST}@anchor{4cfd}
@deffn {Opcode} LOAD_FAST (var_num)

ローカルな @code{co_varnames[var_num]} への参照をスタックにプッシュします。


バージョン 3.12 で変更: This opcode is now only used in situations where the local variable is
guaranteed to be initialized. It cannot raise @ref{174f,,UnboundLocalError}.

@end deffn

@geindex LOAD_FAST_BORROW (opcode)
@anchor{library/dis opcode-LOAD_FAST_BORROW}@anchor{36c}
@deffn {Opcode} LOAD_FAST_BORROW (var_num)

Pushes a borrowed reference to the local @code{co_varnames[var_num]} onto the
stack.


Added in version 3.14.

@end deffn

@geindex LOAD_FAST_LOAD_FAST (opcode)
@anchor{library/dis opcode-LOAD_FAST_LOAD_FAST}@anchor{4cfe}
@deffn {Opcode} LOAD_FAST_LOAD_FAST (var_nums)

Pushes references to @code{co_varnames[var_nums >> 4]} and
@code{co_varnames[var_nums & 15]} onto the stack.


Added in version 3.13.

@end deffn

@geindex LOAD_FAST_BORROW_LOAD_FAST_BORROW (opcode)
@anchor{library/dis opcode-LOAD_FAST_BORROW_LOAD_FAST_BORROW}@anchor{36d}
@deffn {Opcode} LOAD_FAST_BORROW_LOAD_FAST_BORROW (var_nums)

Pushes borrowed references to @code{co_varnames[var_nums >> 4]} and
@code{co_varnames[var_nums & 15]} onto the stack.


Added in version 3.14.

@end deffn

@geindex LOAD_FAST_CHECK (opcode)
@anchor{library/dis opcode-LOAD_FAST_CHECK}@anchor{70b}
@deffn {Opcode} LOAD_FAST_CHECK (var_num)

Pushes a reference to the local @code{co_varnames[var_num]} onto the stack,
raising an @ref{174f,,UnboundLocalError} if the local variable has not been
initialized.


Added in version 3.12.

@end deffn

@geindex LOAD_FAST_AND_CLEAR (opcode)
@anchor{library/dis opcode-LOAD_FAST_AND_CLEAR}@anchor{70a}
@deffn {Opcode} LOAD_FAST_AND_CLEAR (var_num)

Pushes a reference to the local @code{co_varnames[var_num]} onto the stack (or
pushes @code{NULL} onto the stack if the local variable has not been
initialized) and sets @code{co_varnames[var_num]} to @code{NULL}.


Added in version 3.12.

@end deffn

@geindex STORE_FAST (opcode)
@anchor{library/dis opcode-STORE_FAST}@anchor{1a63}
@deffn {Opcode} STORE_FAST (var_num)

Stores @code{STACK.pop()} into the local @code{co_varnames[var_num]}.
@end deffn

@geindex STORE_FAST_STORE_FAST (opcode)
@anchor{library/dis opcode-STORE_FAST_STORE_FAST}@anchor{4cff}
@deffn {Opcode} STORE_FAST_STORE_FAST (var_nums)

Stores @code{STACK[-1]} into @code{co_varnames[var_nums >> 4]}
and @code{STACK[-2]} into @code{co_varnames[var_nums & 15]}.


Added in version 3.13.

@end deffn

@geindex STORE_FAST_LOAD_FAST (opcode)
@anchor{library/dis opcode-STORE_FAST_LOAD_FAST}@anchor{4d00}
@deffn {Opcode} STORE_FAST_LOAD_FAST (var_nums)

Stores @code{STACK.pop()} into the local @code{co_varnames[var_nums >> 4]}
and pushes a reference to the local @code{co_varnames[var_nums & 15]}
onto the stack.


Added in version 3.13.

@end deffn

@geindex DELETE_FAST (opcode)
@anchor{library/dis opcode-DELETE_FAST}@anchor{4d01}
@deffn {Opcode} DELETE_FAST (var_num)

ローカルな @code{co_varnames[var_num]} を削除します。
@end deffn

@geindex MAKE_CELL (opcode)
@anchor{library/dis opcode-MAKE_CELL}@anchor{90f}
@deffn {Opcode} MAKE_CELL (i)

Creates a new cell in slot @code{i}.  If that slot is nonempty then
that value is stored into the new cell.


Added in version 3.11.

@end deffn

@geindex LOAD_DEREF (opcode)
@anchor{library/dis opcode-LOAD_DEREF}@anchor{4d02}
@deffn {Opcode} LOAD_DEREF (i)

Loads the cell contained in slot @code{i} of the "fast locals" storage.
Pushes a reference to the object the cell contains on the stack.


バージョン 3.11 で変更: @code{i} is no longer offset by the length of @ref{238b,,co_varnames}.

@end deffn

@geindex LOAD_FROM_DICT_OR_DEREF (opcode)
@anchor{library/dis opcode-LOAD_FROM_DICT_OR_DEREF}@anchor{70c}
@deffn {Opcode} LOAD_FROM_DICT_OR_DEREF (i)

Pops a mapping off the stack and looks up the name associated with
slot @code{i} of the "fast locals" storage in this mapping.
If the name is not found there, loads it from the cell contained in
slot @code{i}, similar to @ref{4d02,,LOAD_DEREF}. This is used for loading
@ref{1893,,closure variables} in class bodies (which previously used
@code{LOAD_CLASSDEREF}) and in
@ref{4ab,,annotation scopes} within class bodies.


Added in version 3.12.

@end deffn

@geindex STORE_DEREF (opcode)
@anchor{library/dis opcode-STORE_DEREF}@anchor{4d03}
@deffn {Opcode} STORE_DEREF (i)

Stores @code{STACK.pop()} into the cell contained in slot @code{i} of the "fast locals"
storage.


バージョン 3.11 で変更: @code{i} is no longer offset by the length of @ref{238b,,co_varnames}.

@end deffn

@geindex DELETE_DEREF (opcode)
@anchor{library/dis opcode-DELETE_DEREF}@anchor{4d04}
@deffn {Opcode} DELETE_DEREF (i)

Empties the cell contained in slot @code{i} of the "fast locals" storage.
Used by the @ref{1b1f,,del} statement.


Added in version 3.2.



バージョン 3.11 で変更: @code{i} is no longer offset by the length of @ref{238b,,co_varnames}.

@end deffn

@geindex COPY_FREE_VARS (opcode)
@anchor{library/dis opcode-COPY_FREE_VARS}@anchor{90d}
@deffn {Opcode} COPY_FREE_VARS (n)

Copies the @code{n} @ref{1893,,free (closure) variables} from the closure
into the frame. Removes the need for special code on the caller's side when calling
closures.


Added in version 3.11.

@end deffn

@geindex RAISE_VARARGS (opcode)
@anchor{library/dis opcode-RAISE_VARARGS}@anchor{4d05}
@deffn {Opcode} RAISE_VARARGS (argc)

Raises an exception using one of the 3 forms of the @code{raise} statement,
depending on the value of `argc':


@itemize *

@item 
0: @code{raise} (re-raise previous exception)

@item 
1: @code{raise STACK[-1]} (raise exception instance or type at @code{STACK[-1]})

@item 
2: @code{raise STACK[-2] from STACK[-1]} (raise exception instance or type at
@code{STACK[-2]} with @code{__cause__} set to @code{STACK[-1]})
@end itemize
@end deffn

@geindex CALL (opcode)
@anchor{library/dis opcode-CALL}@anchor{915}
@deffn {Opcode} CALL (argc)

Calls a callable object with the number of arguments specified by @code{argc}.
On the stack are (in ascending order):


@itemize *

@item 
The callable

@item 
@code{self} or @code{NULL}

@item 
The remaining positional arguments
@end itemize

@code{argc} is the total of the positional arguments, excluding @code{self}.

@code{CALL} pops all arguments and the callable object off the stack,
calls the callable object with those arguments, and pushes the return value
returned by the callable object.


Added in version 3.11.



バージョン 3.13 で変更: The callable now always appears at the same position on the stack.



バージョン 3.13 で変更: Calls with keyword arguments are now handled by @ref{372,,CALL_KW}.

@end deffn

@geindex CALL_KW (opcode)
@anchor{library/dis opcode-CALL_KW}@anchor{372}
@deffn {Opcode} CALL_KW (argc)

Calls a callable object with the number of arguments specified by @code{argc},
including one or more named arguments. On the stack are (in ascending order):


@itemize *

@item 
The callable

@item 
@code{self} or @code{NULL}

@item 
The remaining positional arguments

@item 
The named arguments

@item 
A @ref{614,,tuple} of keyword argument names
@end itemize

@code{argc} is the total of the positional and named arguments, excluding @code{self}.
The length of the tuple of keyword argument names is the number of named arguments.

@code{CALL_KW} pops all arguments, the keyword names, and the callable object
off the stack, calls the callable object with those arguments, and pushes the
return value returned by the callable object.


Added in version 3.13.

@end deffn

@geindex CALL_FUNCTION_EX (opcode)
@anchor{library/dis opcode-CALL_FUNCTION_EX}@anchor{f4f}
@deffn {Opcode} CALL_FUNCTION_EX (flags)

Calls a callable object with variable set of positional and keyword
arguments.  If the lowest bit of `flags' is set, the top of the stack
contains a mapping object containing additional keyword arguments.
Before the callable is called, the mapping object and iterable object
are each "unpacked" and their contents passed in as keyword and
positional arguments respectively.
@code{CALL_FUNCTION_EX} pops all arguments and the callable object off the stack,
calls the callable object with those arguments, and pushes the return value
returned by the callable object.


Added in version 3.6.

@end deffn

@geindex PUSH_NULL (opcode)
@anchor{library/dis opcode-PUSH_NULL}@anchor{916}
@deffn {Opcode} PUSH_NULL

Pushes a @code{NULL} to the stack.
Used in the call sequence to match the @code{NULL} pushed by
@code{LOAD_METHOD} for non-method calls.


Added in version 3.11.

@end deffn

@geindex MAKE_FUNCTION (opcode)
@anchor{library/dis opcode-MAKE_FUNCTION}@anchor{f4e}
@deffn {Opcode} MAKE_FUNCTION

Pushes a new function object on the stack built from the code object at @code{STACK[-1]}.


バージョン 3.10 で変更: Flag value @code{0x04} is a tuple of strings instead of dictionary



バージョン 3.11 で変更: Qualified name at @code{STACK[-1]} was removed.



バージョン 3.13 で変更: Extra function attributes on the stack, signaled by oparg flags, were
removed. They now use @ref{4d06,,SET_FUNCTION_ATTRIBUTE}.

@end deffn

@geindex SET_FUNCTION_ATTRIBUTE (opcode)
@anchor{library/dis opcode-SET_FUNCTION_ATTRIBUTE}@anchor{4d06}
@deffn {Opcode} SET_FUNCTION_ATTRIBUTE (flag)

Sets an attribute on a function object. Expects the function at @code{STACK[-1]}
and the attribute value to set at @code{STACK[-2]}; consumes both and leaves the
function at @code{STACK[-1]}. The flag determines which attribute to set:


@itemize *

@item 
@code{0x01} a tuple of default values for positional-only and
positional-or-keyword parameters in positional order

@item 
@code{0x02} a dictionary of keyword-only parameters' default values

@item 
@code{0x04} a tuple of strings containing parameters' annotations

@item 
@code{0x08} a tuple containing cells for free variables, making a closure

@item 
@code{0x10} the @ref{15d,,annotate function} for the function object
@end itemize


Added in version 3.13.



バージョン 3.14 で変更: Added @code{0x10} to indicate the annotate function for the function object.

@end deffn

@geindex BUILD_SLICE (opcode)
@anchor{library/dis opcode-BUILD_SLICE}@anchor{4d07}
@deffn {Opcode} BUILD_SLICE (argc)

@geindex 組み込み関数;slice

Pushes a slice object on the stack.  `argc' must be 2 or 3.  If it is 2, implements:

@example
end = STACK.pop()
start = STACK.pop()
STACK.append(slice(start, end))
@end example

if it is 3, implements:

@example
step = STACK.pop()
end = STACK.pop()
start = STACK.pop()
STACK.append(slice(start, end, step))
@end example

See the @ref{694,,slice()} built-in function for more information.
@end deffn

@geindex EXTENDED_ARG (opcode)
@anchor{library/dis opcode-EXTENDED_ARG}@anchor{1b1e}
@deffn {Opcode} EXTENDED_ARG (ext)

Prefixes any opcode which has an argument too big to fit into the default one
byte. `ext' holds an additional byte which act as higher bits in the argument.
For each opcode, at most three prefixal @code{EXTENDED_ARG} are allowed, forming
an argument from two-byte to four-byte.
@end deffn

@geindex CONVERT_VALUE (opcode)
@anchor{library/dis opcode-CONVERT_VALUE}@anchor{4d08}
@deffn {Opcode} CONVERT_VALUE (oparg)

Convert value to a string, depending on @code{oparg}:

@example
value = STACK.pop()
result = func(value)
STACK.append(result)
@end example


@itemize *

@item 
@code{oparg == 1}: call @ref{169,,str()} on `value'

@item 
@code{oparg == 2}: call @ref{1c1,,repr()} on `value'

@item 
@code{oparg == 3}: call @ref{15ff,,ascii()} on `value'
@end itemize

Used for implementing formatted string literals (f-strings).


Added in version 3.13.

@end deffn

@geindex FORMAT_SIMPLE (opcode)
@anchor{library/dis opcode-FORMAT_SIMPLE}@anchor{4d09}
@deffn {Opcode} FORMAT_SIMPLE

Formats the value on top of stack:

@example
value = STACK.pop()
result = value.__format__("")
STACK.append(result)
@end example

Used for implementing formatted string literals (f-strings).


Added in version 3.13.

@end deffn

@geindex FORMAT_WITH_SPEC (opcode)
@anchor{library/dis opcode-FORMAT_WITH_SPEC}@anchor{4d0a}
@deffn {Opcode} FORMAT_WITH_SPEC

Formats the given value with the given format spec:

@example
spec = STACK.pop()
value = STACK.pop()
result = value.__format__(spec)
STACK.append(result)
@end example

Used for implementing formatted string literals (f-strings).


Added in version 3.13.

@end deffn

@geindex MATCH_CLASS (opcode)
@anchor{library/dis opcode-MATCH_CLASS}@anchor{91f}
@deffn {Opcode} MATCH_CLASS (count)

@code{STACK[-1]} is a tuple of keyword attribute names, @code{STACK[-2]} is the class
being matched against, and @code{STACK[-3]} is the match subject.  `count' is the
number of positional sub-patterns.

Pop @code{STACK[-1]}, @code{STACK[-2]}, and @code{STACK[-3]}. If @code{STACK[-3]} is an
instance of @code{STACK[-2]} and has the positional and keyword attributes
required by `count' and @code{STACK[-1]}, push a tuple of extracted attributes.
Otherwise, push @code{None}.


Added in version 3.10.



バージョン 3.11 で変更: Previously, this instruction also pushed a boolean value indicating
success (@code{True}) or failure (@code{False}).

@end deffn

@geindex RESUME (opcode)
@anchor{library/dis opcode-RESUME}@anchor{5bb}
@deffn {Opcode} RESUME (context)

A no-op. Performs internal tracing, debugging and optimization checks.

The @code{context} operand consists of two parts. The lowest two bits
indicate where the @code{RESUME} occurs:


@itemize *

@item 
@code{0} The start of a function, which is neither a generator, coroutine
nor an async generator

@item 
@code{1} After a @code{yield} expression

@item 
@code{2} After a @code{yield from} expression

@item 
@code{3} After an @code{await} expression
@end itemize

The next bit is @code{1} if the RESUME is at except-depth @code{1}, and @code{0}
otherwise.


Added in version 3.11.



バージョン 3.13 で変更: The oparg value changed to include information about except-depth

@end deffn

@geindex RETURN_GENERATOR (opcode)
@anchor{library/dis opcode-RETURN_GENERATOR}@anchor{90b}
@deffn {Opcode} RETURN_GENERATOR

Create a generator, coroutine, or async generator from the current frame.
Used as first opcode of in code object for the above mentioned callables.
Clear the current frame and return the newly created generator.


Added in version 3.11.

@end deffn

@geindex SEND (opcode)
@anchor{library/dis opcode-SEND}@anchor{90c}
@deffn {Opcode} SEND (delta)

Equivalent to @code{STACK[-1] = STACK[-2].send(STACK[-1])}. Used in @code{yield from}
and @code{await} statements.

If the call raises @ref{df5,,StopIteration}, pop the top value from the stack,
push the exception's @code{value} attribute, and increment the bytecode counter
by `delta'.


Added in version 3.11.

@end deffn

@geindex HAVE_ARGUMENT (opcode)
@anchor{library/dis opcode-HAVE_ARGUMENT}@anchor{6b1}
@deffn {Opcode} HAVE_ARGUMENT

This is not really an opcode.  It identifies the dividing line between
opcodes in the range [0,255] which don't use their argument and those
that do (@code{< HAVE_ARGUMENT} and @code{>= HAVE_ARGUMENT}, respectively).

If your application uses pseudo instructions or specialized instructions,
use the @ref{59f,,hasarg} collection instead.


バージョン 3.6 で変更: Now every instruction has an argument, but opcodes @code{< HAVE_ARGUMENT}
ignore it. Before, only opcodes @code{>= HAVE_ARGUMENT} had an argument.



バージョン 3.12 で変更: Pseudo instructions were added to the @code{dis} module, and for them
it is not true that comparison with @code{HAVE_ARGUMENT} indicates whether
they use their arg.



バージョン 3.13 で非推奨: Use @ref{59f,,hasarg} instead.

@end deffn

@geindex CALL_INTRINSIC_1 (opcode)
@anchor{library/dis opcode-CALL_INTRINSIC_1}@anchor{707}
@deffn {Opcode} CALL_INTRINSIC_1

Calls an intrinsic function with one argument. Passes @code{STACK[-1]} as the
argument and sets @code{STACK[-1]} to the result. Used to implement
functionality that is not performance critical.

The operand determines which intrinsic function is called:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Operand

@tab

説明

@item

@code{INTRINSIC_1_INVALID}

@tab

Not valid

@item

@code{INTRINSIC_PRINT}

@tab

Prints the argument to standard
out. Used in the REPL.

@item

@code{INTRINSIC_IMPORT_STAR}

@tab

Performs @code{import *} for the
named module.

@item

@code{INTRINSIC_STOPITERATION_ERROR}

@tab

Extracts the return value from a
@code{StopIteration} exception.

@item

@code{INTRINSIC_ASYNC_GEN_WRAP}

@tab

Wraps an async generator value

@item

@code{INTRINSIC_UNARY_POSITIVE}

@tab

Performs the unary @code{+}
operation

@item

@code{INTRINSIC_LIST_TO_TUPLE}

@tab

Converts a list to a tuple

@item

@code{INTRINSIC_TYPEVAR}

@tab

Creates a @ref{486,,typing.TypeVar}

@item

@code{INTRINSIC_PARAMSPEC}

@tab

Creates a
@ref{487,,typing.ParamSpec}

@item

@code{INTRINSIC_TYPEVARTUPLE}

@tab

Creates a
@ref{488,,typing.TypeVarTuple}

@item

@code{INTRINSIC_SUBSCRIPT_GENERIC}

@tab

Returns @ref{17b6,,typing.Generic}
subscripted with the argument

@item

@code{INTRINSIC_TYPEALIAS}

@tab

Creates a
@ref{2ae,,typing.TypeAliasType};
used in the @ref{66d,,type}
statement. The argument is a tuple
of the type alias's name,
type parameters, and value.

@end multitable



Added in version 3.12.

@end deffn

@geindex CALL_INTRINSIC_2 (opcode)
@anchor{library/dis opcode-CALL_INTRINSIC_2}@anchor{708}
@deffn {Opcode} CALL_INTRINSIC_2

Calls an intrinsic function with two arguments. Used to implement functionality
that is not performance critical:

@example
arg2 = STACK.pop()
arg1 = STACK.pop()
result = intrinsic2(arg1, arg2)
STACK.append(result)
@end example

The operand determines which intrinsic function is called:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Operand

@tab

説明

@item

@code{INTRINSIC_2_INVALID}

@tab

Not valid

@item

@code{INTRINSIC_PREP_RERAISE_STAR}

@tab

Calculates the
@ref{4d2,,ExceptionGroup} to raise
from a @code{try-except*}.

@item

@code{INTRINSIC_TYPEVAR_WITH_BOUND}

@tab

Creates a @ref{486,,typing.TypeVar}
with a bound.

@item

@code{INTRINSIC_TYPEVAR_WITH_CONSTRAINTS}

@tab

Creates a
@ref{486,,typing.TypeVar} with
constraints.

@item

@code{INTRINSIC_SET_FUNCTION_TYPE_PARAMS}

@tab

Sets the @code{__type_params__}
attribute of a function.

@end multitable



Added in version 3.12.

@end deffn

@geindex LOAD_SPECIAL (opcode)
@anchor{library/dis opcode-LOAD_SPECIAL}@anchor{36f}
@deffn {Opcode} LOAD_SPECIAL

Performs special method lookup on @code{STACK[-1]}.
If @code{type(STACK[-1]).__xxx__} is a method, leave
@code{type(STACK[-1]).__xxx__; STACK[-1]} on the stack.
If @code{type(STACK[-1]).__xxx__} is not a method, leave
@code{STACK[-1].__xxx__; NULL} on the stack.


Added in version 3.14.

@end deffn

`Pseudo-instructions'

These opcodes do not appear in Python bytecode. They are used by the compiler
but are replaced by real opcodes or removed before bytecode is generated.

@geindex SETUP_FINALLY (opcode)
@anchor{library/dis opcode-SETUP_FINALLY}@anchor{4d0b}
@deffn {Opcode} SETUP_FINALLY (target)

Set up an exception handler for the following code block. If an exception
occurs, the value stack level is restored to its current state and control
is transferred to the exception handler at @code{target}.
@end deffn

@geindex SETUP_CLEANUP (opcode)
@anchor{library/dis opcode-SETUP_CLEANUP}@anchor{4d0c}
@deffn {Opcode} SETUP_CLEANUP (target)

Like @code{SETUP_FINALLY}, but in case of an exception also pushes the last
instruction (@code{lasti}) to the stack so that @code{RERAISE} can restore it.
If an exception occurs, the value stack level and the last instruction on
the frame are restored to their current state, and control is transferred
to the exception handler at @code{target}.
@end deffn

@geindex SETUP_WITH (opcode)
@anchor{library/dis opcode-SETUP_WITH}@anchor{4d0d}
@deffn {Opcode} SETUP_WITH (target)

Like @code{SETUP_CLEANUP}, but in case of an exception one more item is popped
from the stack before control is transferred to the exception handler at
@code{target}.

This variant is used in @ref{186,,with} and @ref{185,,async with}
constructs, which push the return value of the context manager's
@ref{7e4,,__enter__()} or @ref{241d,,__aenter__()} to the stack.
@end deffn

@geindex POP_BLOCK (opcode)
@anchor{library/dis opcode-POP_BLOCK}@anchor{4d0e}
@deffn {Opcode} POP_BLOCK

Marks the end of the code block associated with the last @code{SETUP_FINALLY},
@code{SETUP_CLEANUP} or @code{SETUP_WITH}.
@end deffn

@geindex LOAD_CONST_IMMORTAL (opcode)
@anchor{library/dis opcode-LOAD_CONST_IMMORTAL}@anchor{375}
@deffn {Opcode} LOAD_CONST_IMMORTAL (consti)

Works as @ref{4cf2,,LOAD_CONST}, but is more efficient for immortal objects.
@end deffn

@geindex JUMP (opcode)
@geindex JUMP_NO_INTERRUPT (opcode)
@anchor{library/dis opcode-JUMP}@anchor{4d0f}
@deffn {Opcode} JUMP
@anchor{library/dis opcode-JUMP_NO_INTERRUPT}@anchor{1ba5}
@deffnx {Opcode} JUMP_NO_INTERRUPT

Undirected relative jump instructions which are replaced by their
directed (forward/backward) counterparts by the assembler.
@end deffn

@geindex JUMP_IF_TRUE (opcode)
@geindex JUMP_IF_FALSE (opcode)
@anchor{library/dis opcode-JUMP_IF_TRUE}@anchor{373}
@deffn {Opcode} JUMP_IF_TRUE
@anchor{library/dis opcode-JUMP_IF_FALSE}@anchor{374}
@deffnx {Opcode} JUMP_IF_FALSE

Conditional jumps which do not impact the stack. Replaced by the sequence
@code{COPY 1}, @code{TO_BOOL}, @code{POP_JUMP_IF_TRUE/FALSE}.
@end deffn

@geindex LOAD_CLOSURE (opcode)
@anchor{library/dis opcode-LOAD_CLOSURE}@anchor{1a5d}
@deffn {Opcode} LOAD_CLOSURE (i)

Pushes a reference to the cell contained in slot @code{i} of the "fast locals"
storage.

Note that @code{LOAD_CLOSURE} is replaced with @code{LOAD_FAST} in the assembler.


バージョン 3.13 で変更: This opcode is now a pseudo-instruction.

@end deffn

@node 命令コードコレクション,,Python バイトコード命令,dis --- Python バイトコードの逆アセンブラー
@anchor{library/dis id1}@anchor{4d10}@anchor{library/dis opcode-collections}@anchor{4cc1}
@subsubsection 命令コードコレクション


これらのコレクションは、自動でバイトコード命令を解析するために提供されています:


バージョン 3.12 で変更: The collections now contain pseudo instructions and instrumented
instructions as well. These are opcodes with values @code{>= MIN_PSEUDO_OPCODE}
and @code{>= MIN_INSTRUMENTED_OPCODE}.


@geindex opname (dis モジュール)
@anchor{library/dis dis opname}@anchor{4cc5}
@deffn {データ} dis.opname

命令コード名のリスト。
バイトコードをインデックスに使って参照できます。
@end deffn

@geindex opmap (dis モジュール)
@anchor{library/dis dis opmap}@anchor{4d11}
@deffn {データ} dis.opmap

命令コード名をバイトコードに対応づける辞書。
@end deffn

@geindex cmp_op (dis モジュール)
@anchor{library/dis dis cmp_op}@anchor{4d12}
@deffn {データ} dis.cmp_op

すべての比較命令の名前のリスト。
@end deffn

@geindex hasarg (dis モジュール)
@anchor{library/dis dis hasarg}@anchor{59f}
@deffn {データ} dis.hasarg

Sequence of bytecodes that use their argument.


Added in version 3.12.

@end deffn

@geindex hasconst (dis モジュール)
@anchor{library/dis dis hasconst}@anchor{4d13}
@deffn {データ} dis.hasconst

定数にアクセスするバイトコードのリスト。
@end deffn

@geindex hasfree (dis モジュール)
@anchor{library/dis dis hasfree}@anchor{4d14}
@deffn {データ} dis.hasfree

Sequence of bytecodes that access a @ref{1893,,free (closure) variable}.
'free' in this context refers to names in the current scope that are
referenced by inner scopes or names in outer scopes that are referenced
from this scope.  It does `not' include references to global or builtin scopes.
@end deffn

@geindex hasname (dis モジュール)
@anchor{library/dis dis hasname}@anchor{4d15}
@deffn {データ} dis.hasname

名前によって属性にアクセスするバイトコードのリスト。
@end deffn

@geindex hasjump (dis モジュール)
@anchor{library/dis dis hasjump}@anchor{4d16}
@deffn {データ} dis.hasjump

Sequence of bytecodes that have a jump target. All jumps
are relative.


Added in version 3.13.

@end deffn

@geindex haslocal (dis モジュール)
@anchor{library/dis dis haslocal}@anchor{4d17}
@deffn {データ} dis.haslocal

ローカル変数にアクセスするバイトコードのリスト。
@end deffn

@geindex hascompare (dis モジュール)
@anchor{library/dis dis hascompare}@anchor{4d18}
@deffn {データ} dis.hascompare

ブール命令のバイトコードのリスト。
@end deffn

@geindex hasexc (dis モジュール)
@anchor{library/dis dis hasexc}@anchor{6b2}
@deffn {データ} dis.hasexc

Sequence of bytecodes that set an exception handler.


Added in version 3.12.

@end deffn

@geindex hasjrel (dis モジュール)
@anchor{library/dis dis hasjrel}@anchor{4d19}
@deffn {データ} dis.hasjrel

相対ジャンプ先を持つバイトコードのリスト。


バージョン 3.13 で非推奨: All jumps are now relative. Use @ref{4d16,,hasjump}.

@end deffn

@geindex hasjabs (dis モジュール)
@anchor{library/dis dis hasjabs}@anchor{4d1a}
@deffn {データ} dis.hasjabs

絶対ジャンプ先を持つバイトコードのリスト。


バージョン 3.13 で非推奨: All jumps are now relative. This list is empty.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pickletools --- pickle 開発者用のツール群,,dis --- Python バイトコードの逆アセンブラー,Python言語サービス
@anchor{library/pickletools doc}@anchor{4d1b}@anchor{library/pickletools module-pickletools}@anchor{ac}@anchor{library/pickletools pickletools-tools-for-pickle-developers}@anchor{4d1c}@anchor{library/pickletools translation-repo}@anchor{4d1d}
@subsection @code{pickletools} --- pickle 開発者用のツール群


@geindex module; pickletools

`ソースコード:' Lib/pickletools.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pickletools.py}


__________________________________________________________________


This module contains various constants relating to the intimate details of the
@ref{ab,,pickle} module, some lengthy comments about the implementation, and a
few useful functions for analyzing pickled data.  The contents of this module
are useful for Python core developers who are working on the @ref{ab,,pickle};
ordinary users of the @ref{ab,,pickle} module probably won't find the
@code{pickletools} module relevant.

@menu
* コマンドラインでの使用: コマンドラインでの使用<10>. 
* Programmatic interface:: 

@end menu

@node コマンドラインでの使用<10>,Programmatic interface,,pickletools --- pickle 開発者用のツール群
@anchor{library/pickletools command-line-usage}@anchor{4d1e}@anchor{library/pickletools pickletools-cli}@anchor{2d2f}
@subsubsection コマンドラインでの使用



Added in version 3.2.


コマンドラインから実行するとき、@code{python -m pickletools} は 1 つもしくは複数の pickle ファイルの内容を逆アセンブルします。pickle 形式の詳細ではなく pickle に保存された Python オブジェクトを見たい場合は、そのコマンドではなく @code{-m pickle} を使いたいと思うかもしれません。しかし、調べたい pickle ファイルが信頼できないソースから来たものであるとき、@code{-m pickletools} は pickle のバイトコードを実行しないので、より安全な選択肢です。

例えば、 @code{x.pickle} ファイルに pickle 化されているタプル @code{(1, 2)} に対して実行すると次のようになります:

@example
$ python -m pickle x.pickle
(1, 2)

$ python -m pickletools x.pickle
    0: \x80 PROTO      3
    2: K    BININT1    1
    4: K    BININT1    2
    6: \x86 TUPLE2
    7: q    BINPUT     0
    9: .    STOP
highest protocol among opcodes = 2
@end example

@menu
* コマンドラインオプション: コマンドラインオプション<6>. 

@end menu

@node コマンドラインオプション<6>,,,コマンドラインでの使用<10>
@anchor{library/pickletools command-line-options}@anchor{4d1f}
@subsubsection コマンドラインオプション


@geindex pickletools コマンドラインオプション; -a
@geindex pickletools コマンドラインオプション; --annotate
@anchor{library/pickletools cmdoption-pickletools-a}@anchor{4d20}@anchor{library/pickletools cmdoption-pickletools-annotate}@anchor{4d21}
@deffn {Option} @w{-}a, @w{-}@w{-}annotate

注釈として短い命令コードの説明を各行に表示します。
@end deffn

@geindex pickletools コマンドラインオプション; -o
@geindex pickletools コマンドラインオプション; --output
@anchor{library/pickletools cmdoption-pickletools-o}@anchor{4d22}@anchor{library/pickletools cmdoption-pickletools-output}@anchor{4d23}
@deffn {Option} @w{-}o, @w{-}@w{-}output=<file>

出力結果を書き込むファイル名。
@end deffn

@geindex pickletools コマンドラインオプション; -l
@geindex pickletools コマンドラインオプション; --indentlevel
@anchor{library/pickletools cmdoption-pickletools-l}@anchor{4d24}@anchor{library/pickletools cmdoption-pickletools-indentlevel}@anchor{4d25}
@deffn {Option} @w{-}l, @w{-}@w{-}indentlevel=<num>

新しい MARK レベルのインデントに使われる空白の数。
@end deffn

@geindex pickletools コマンドラインオプション; -m
@geindex pickletools コマンドラインオプション; --memo
@anchor{library/pickletools cmdoption-pickletools-m}@anchor{4d26}@anchor{library/pickletools cmdoption-pickletools-memo}@anchor{4d27}
@deffn {Option} @w{-}m, @w{-}@w{-}memo

複数のオブジェクトが逆アセンブルされたとき、逆アセンブリ間でメモを保持します。
@end deffn

@geindex pickletools コマンドラインオプション; -p
@geindex pickletools コマンドラインオプション; --preamble
@anchor{library/pickletools cmdoption-pickletools-p}@anchor{4d28}@anchor{library/pickletools cmdoption-pickletools-preamble}@anchor{4d29}
@deffn {Option} @w{-}p, @w{-}@w{-}preamble=<preamble>

When more than one pickle file is specified, print given preamble
before each disassembly.
@end deffn

@geindex pickletools コマンドラインオプション; pickle_file
@anchor{library/pickletools cmdoption-pickletools-arg-pickle_file}@anchor{4d2a}
@deffn {Option} pickle_file

A pickle file to read, or @code{-} to indicate reading from standard input.
@end deffn

@node Programmatic interface,,コマンドラインでの使用<10>,pickletools --- pickle 開発者用のツール群
@anchor{library/pickletools programmatic-interface}@anchor{4d2b}
@subsubsection Programmatic interface


@geindex dis() (pickletools モジュール)
@anchor{library/pickletools pickletools dis}@anchor{ebe}
@deffn {の関数} pickletools.dis (pickle, out=None, memo=None, indentlevel=4, annotate=0)

pickle の抽象的な逆アセンブリを file-like オブジェクト `out' (デフォルトは @code{sys.stdout}) に出力します。`pickle' は文字列または file-like オブジェクトです。`memo' は Python の辞書で、pickle のメモとして使われます; これは、pickle 処理を行う 1 つのオブジェクトが、複数の pickle にわたって逆アセンブルを行うために使われます。ストリーム上の @code{MARK} 命令コードが示す後続のレベルは、`indentlevel' 個の空白でインデントされます。`annotate' に非ゼロの値が与えられた場合、出力される各命令コードは短い命令コードに注釈が付けられます。`annotate' の値は、注釈の先頭の位置のヒントとして使われます。


バージョン 3.2 で変更: `annotate' パラメーターを追加しました。

@end deffn

@geindex genops() (pickletools モジュール)
@anchor{library/pickletools pickletools genops}@anchor{4d2c}
@deffn {の関数} pickletools.genops (pickle)

pickle 内の全ての opcode を取り出す @ref{4c8,,イテレータ} を返します。このイテレータは @code{(opcode, arg, pos)} の三つ組みからなる配列を返します。 `opcode' は @code{OpcodeInfo} クラスのインスタンスのクラスです。 `arg' は `opcode' の引数としてデコードされた Python オブジェクトの値です。 `pos' は `opcode' の場所を表す値です。 `pickle' は文字列でもファイル類似オブジェクトでもかまいません。
@end deffn

@geindex optimize() (pickletools モジュール)
@anchor{library/pickletools pickletools optimize}@anchor{2d16}
@deffn {の関数} pickletools.optimize (picklestring)

使われていない @code{PUT} 命令コードを除去した上で、その新しい pickle 文字列を返します。最適化された pickle は、長さがより短く、転送時間がより少なく、必要とするストレージ領域がより狭く、unpickle 化がより効率的になります。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node MS Windows 固有のサービス,Unix-specific services,Python言語サービス,Python 標準ライブラリ
@anchor{library/windows doc}@anchor{4d2d}@anchor{library/windows ms-windows-specific-services}@anchor{4d2e}@anchor{library/windows mswin-specific-services}@anchor{2220}@anchor{library/windows translation-repo}@anchor{4d2f}
@section MS Windows 固有のサービス


この章では、MS Windows プラットフォーム上でのみ利用可能なモジュール群について記述します。

@menu
* msvcrt: msvcrt --- MS VC++ ランタイムの有用なルーチン群. MS VC++ ランタイムの有用なルーチン群
* winreg: winreg --- Windows レジストリへのアクセス. Windows レジストリへのアクセス
* winsound: winsound --- Windows 用の音声再生インターフェース. Windows 用の音声再生インターフェース

@end menu

@node msvcrt --- MS VC++ ランタイムの有用なルーチン群,winreg --- Windows レジストリへのアクセス,,MS Windows 固有のサービス
@anchor{library/msvcrt doc}@anchor{4d30}@anchor{library/msvcrt module-msvcrt}@anchor{97}@anchor{library/msvcrt msvcrt-useful-routines-from-the-ms-vc-runtime}@anchor{4d31}
@subsection @code{msvcrt} --- MS VC++ ランタイムの有用なルーチン群


@geindex module; msvcrt


__________________________________________________________________


このモジュールの関数は、 Windows プラットフォームの便利な機能のいくつかに対するアクセス機構を提供しています。高レベルモジュールのいくつかは、提供するサービスを Windows で実装するために、これらの関数を使っています。例えば、 @ref{66,,getpass} モジュールは関数 @ref{66,,getpass()} を実装するためにこのモジュールの関数を使います。

ここに挙げた関数の詳細なドキュメントについては、プラットフォーム API ドキュメントで見つけることができます。

このモジュールは、通常版とワイド文字列版の両方のコンソールI/O APIを実装しています。通常版の API は ASCII 文字列のためのもので、国際化アプリケーションでは利用が制限されます。可能な限りワイド文字列版APIを利用するべきです。

@ref{213f,,Availability}: Windows.


バージョン 3.3 で変更: このモジュールの操作で以前は @ref{125e,,IOError} が送出されていたところで @ref{2c0,,OSError} が送出されるようになりました。


@menu
* ファイル操作関連:: 
* コンソール I/O 関連:: 
* その多の関数:: 

@end menu

@node ファイル操作関連,コンソール I/O 関連,,msvcrt --- MS VC++ ランタイムの有用なルーチン群
@anchor{library/msvcrt file-operations}@anchor{4d32}@anchor{library/msvcrt msvcrt-files}@anchor{4d33}
@subsubsection ファイル操作関連


@geindex locking() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt locking}@anchor{475e}
@deffn {の関数} msvcrt.locking (fd, mode, nbytes)

Lock part of a file based on file descriptor `fd' from the C runtime. Raises
@ref{2c0,,OSError} on failure. The locked region of the file extends from the
current file position for `nbytes' bytes, and may continue beyond the end of the
file. `mode' must be one of the @code{LK_*} constants listed below. Multiple
regions in a file may be locked at the same time, but may not overlap. Adjacent
regions are not merged; they must be unlocked individually.

引数 @code{fd}, @code{mode}, @code{nbytes} を指定して @ref{1c6e,,監査イベント} @code{msvcrt.locking} を送出します。
@end deffn

@geindex LK_LOCK (msvcrt モジュール)
@geindex LK_RLCK (msvcrt モジュール)
@anchor{library/msvcrt msvcrt LK_LOCK}@anchor{4d34}
@deffn {データ} msvcrt.LK_LOCK
@anchor{library/msvcrt msvcrt LK_RLCK}@anchor{4d35}
@deffnx {データ} msvcrt.LK_RLCK

Locks the specified bytes. If the bytes cannot be locked, the program
immediately tries again after 1 second. If, after 10 attempts, the bytes cannot
be locked, @ref{2c0,,OSError} is raised.
@end deffn

@geindex LK_NBLCK (msvcrt モジュール)
@geindex LK_NBRLCK (msvcrt モジュール)
@anchor{library/msvcrt msvcrt LK_NBLCK}@anchor{4d36}
@deffn {データ} msvcrt.LK_NBLCK
@anchor{library/msvcrt msvcrt LK_NBRLCK}@anchor{4d37}
@deffnx {データ} msvcrt.LK_NBRLCK

指定されたバイト列にロックをかけます。指定領域がロックできなかった場合、 @ref{2c0,,OSError} が送出されます。
@end deffn

@geindex LK_UNLCK (msvcrt モジュール)
@anchor{library/msvcrt msvcrt LK_UNLCK}@anchor{4d38}
@deffn {データ} msvcrt.LK_UNLCK

指定されたバイト列のロックを解除します。指定領域はあらかじめロックされていなければなりません。
@end deffn

@geindex setmode() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt setmode}@anchor{4d39}
@deffn {の関数} msvcrt.setmode (fd, flags)

ファイル記述子 `fd' に対して、行末文字の変換モードを設定します。テキストモードに設定するには、 `flags' を @ref{3054,,os.O_TEXT} にします; バイナリモードにするには @ref{3045,,os.O_BINARY} にします。
@end deffn

@geindex open_osfhandle() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt open_osfhandle}@anchor{475f}
@deffn {の関数} msvcrt.open_osfhandle (handle, flags)

Create a C runtime file descriptor from the file handle `handle'. The `flags'
parameter should be a bitwise OR of @ref{3047,,os.O_APPEND},
@ref{3043,,os.O_RDONLY}, @ref{3054,,os.O_TEXT} and @ref{304f,,os.O_NOINHERIT}.
The returned file descriptor may be used as a parameter
to @ref{2381,,os.fdopen()} to create a file object.

The file descriptor is inheritable by default. Pass @ref{304f,,os.O_NOINHERIT}
flag to make it non inheritable.

引数 @code{handle}, @code{flags} を指定して @ref{1c6e,,監査イベント} @code{msvcrt.open_osfhandle} を送出します。
@end deffn

@geindex get_osfhandle() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt get_osfhandle}@anchor{475d}
@deffn {の関数} msvcrt.get_osfhandle (fd)

Return the file handle for the file descriptor `fd'. Raises @ref{2c0,,OSError} if
`fd' is not recognized.

引数 @code{fd} を指定して @ref{1c6e,,監査イベント} @code{msvcrt.get_osfhandle} を送出します。
@end deffn

@node コンソール I/O 関連,その多の関数,ファイル操作関連,msvcrt --- MS VC++ ランタイムの有用なルーチン群
@anchor{library/msvcrt console-i-o}@anchor{4d3a}@anchor{library/msvcrt msvcrt-console}@anchor{4d3b}
@subsubsection コンソール I/O 関連


@geindex kbhit() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt kbhit}@anchor{4d3c}
@deffn {の関数} msvcrt.kbhit ()

Returns a nonzero value if a keypress is waiting to be read. Otherwise,
return 0.
@end deffn

@geindex getch() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt getch}@anchor{4d3d}
@deffn {の関数} msvcrt.getch ()

Read a keypress and return the resulting character as a byte string.
Nothing is echoed to the console. This call will block if a keypress
is not already available, but will not wait for @code{Enter} to be
pressed. If the pressed key was a special function key, this will
return @code{'\000'} or @code{'\xe0'}; the next call will return the keycode.
The @code{Control}-@code{C} keypress cannot be read with this function.
@end deffn

@geindex getwch() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt getwch}@anchor{160e}
@deffn {の関数} msvcrt.getwch ()

@ref{4d3d,,getch()} のワイド文字列版。Unicode の値を返します。
@end deffn

@geindex getche() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt getche}@anchor{4d3e}
@deffn {の関数} msvcrt.getche ()

Similar to @ref{4d3d,,getch()}, but the keypress will be echoed if it represents a
printable character.
@end deffn

@geindex getwche() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt getwche}@anchor{160f}
@deffn {の関数} msvcrt.getwche ()

@ref{4d3e,,getche()} のワイド文字列版。Unicode の値を返します。
@end deffn

@geindex putch() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt putch}@anchor{4d3f}
@deffn {の関数} msvcrt.putch (char)

バイト文字列 `char' をバッファリングを行わないでコンソールに出力します。
@end deffn

@geindex putwch() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt putwch}@anchor{1610}
@deffn {の関数} msvcrt.putwch (unicode_char)

@ref{4d3f,,putch()} のワイド文字列版。Unicode の値を引数に取ります。
@end deffn

@geindex ungetch() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt ungetch}@anchor{4d40}
@deffn {の関数} msvcrt.ungetch (char)

バイト文字列 `char' をコンソールバッファに "押し戻し (push back)" ます; これにより、押し戻された文字は @ref{4d3d,,getch()} や @ref{4d3e,,getche()} で次に読み出される文字になります。
@end deffn

@geindex ungetwch() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt ungetwch}@anchor{4d41}
@deffn {の関数} msvcrt.ungetwch (unicode_char)

@ref{4d40,,ungetch()} のワイド文字列版。Unicode の値を引数に取ります。
@end deffn

@node その多の関数,,コンソール I/O 関連,msvcrt --- MS VC++ ランタイムの有用なルーチン群
@anchor{library/msvcrt msvcrt-other}@anchor{4d42}@anchor{library/msvcrt other-functions}@anchor{4d43}
@subsubsection その多の関数


@geindex heapmin() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt heapmin}@anchor{4d44}
@deffn {の関数} msvcrt.heapmin ()

Force the @code{malloc()} heap to clean itself up and return unused blocks to
the operating system. On failure, this raises @ref{2c0,,OSError}.
@end deffn

@geindex set_error_mode() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt set_error_mode}@anchor{4d45}
@deffn {の関数} msvcrt.set_error_mode (mode)

Changes the location where the C runtime writes an error message for an error
that might end the program. `mode' must be one of the @code{OUT_*}
constants listed below  or @ref{4d46,,REPORT_ERRMODE}. Returns the old setting
or -1 if an error occurs. Only available in
@ref{509,,debug build of Python}.
@end deffn

@geindex OUT_TO_DEFAULT (msvcrt モジュール)
@anchor{library/msvcrt msvcrt OUT_TO_DEFAULT}@anchor{4d47}
@deffn {データ} msvcrt.OUT_TO_DEFAULT

Error sink is determined by the app's type. Only available in
@ref{509,,debug build of Python}.
@end deffn

@geindex OUT_TO_STDERR (msvcrt モジュール)
@anchor{library/msvcrt msvcrt OUT_TO_STDERR}@anchor{4d48}
@deffn {データ} msvcrt.OUT_TO_STDERR

Error sink is a standard error. Only available in
@ref{509,,debug build of Python}.
@end deffn

@geindex OUT_TO_MSGBOX (msvcrt モジュール)
@anchor{library/msvcrt msvcrt OUT_TO_MSGBOX}@anchor{4d49}
@deffn {データ} msvcrt.OUT_TO_MSGBOX

Error sink is a message box. Only available in
@ref{509,,debug build of Python}.
@end deffn

@geindex REPORT_ERRMODE (msvcrt モジュール)
@anchor{library/msvcrt msvcrt REPORT_ERRMODE}@anchor{4d46}
@deffn {データ} msvcrt.REPORT_ERRMODE

Report the current error mode value. Only available in
@ref{509,,debug build of Python}.
@end deffn

@geindex CrtSetReportMode() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CrtSetReportMode}@anchor{4d4a}
@deffn {の関数} msvcrt.CrtSetReportMode (type, mode)

Specifies the destination or destinations for a specific report type
generated by @code{_CrtDbgReport()} in the MS VC++ runtime. `type' must be
one of the @code{CRT_*} constants listed below. `mode' must be one of the
@code{CRTDBG_*} constants listed below. Only available in
@ref{509,,debug build of Python}.
@end deffn

@geindex CrtSetReportFile() (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CrtSetReportFile}@anchor{4d4b}
@deffn {の関数} msvcrt.CrtSetReportFile (type, file)

After you use @ref{4d4a,,CrtSetReportMode()} to specify @ref{4d4c,,CRTDBG_MODE_FILE},
you can specify the file handle to receive the message text. `type' must be
one of the @code{CRT_*} constants listed below. `file' should be the file
handle your want specified. Only available in
@ref{509,,debug build of Python}.
@end deffn

@geindex CRT_WARN (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRT_WARN}@anchor{4d4d}
@deffn {データ} msvcrt.CRT_WARN

Warnings, messages, and information that doesn't need immediate attention.
@end deffn

@geindex CRT_ERROR (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRT_ERROR}@anchor{4d4e}
@deffn {データ} msvcrt.CRT_ERROR

Errors, unrecoverable problems, and issues that require immediate attention.
@end deffn

@geindex CRT_ASSERT (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRT_ASSERT}@anchor{4d4f}
@deffn {データ} msvcrt.CRT_ASSERT

Assertion failures.
@end deffn

@geindex CRTDBG_MODE_DEBUG (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRTDBG_MODE_DEBUG}@anchor{4d50}
@deffn {データ} msvcrt.CRTDBG_MODE_DEBUG

Writes the message to the debugger's output window.
@end deffn

@geindex CRTDBG_MODE_FILE (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRTDBG_MODE_FILE}@anchor{4d4c}
@deffn {データ} msvcrt.CRTDBG_MODE_FILE

Writes the message to a user-supplied file handle. @ref{4d4b,,CrtSetReportFile()}
should be called to define the specific file or stream to use as
the destination.
@end deffn

@geindex CRTDBG_MODE_WNDW (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRTDBG_MODE_WNDW}@anchor{4d51}
@deffn {データ} msvcrt.CRTDBG_MODE_WNDW

Creates a message box to display the message along with the @code{Abort},
@code{Retry}, and @code{Ignore} buttons.
@end deffn

@geindex CRTDBG_REPORT_MODE (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRTDBG_REPORT_MODE}@anchor{4d52}
@deffn {データ} msvcrt.CRTDBG_REPORT_MODE

Returns current `mode' for the specified `type'.
@end deffn

@geindex CRT_ASSEMBLY_VERSION (msvcrt モジュール)
@anchor{library/msvcrt msvcrt CRT_ASSEMBLY_VERSION}@anchor{1577}
@deffn {データ} msvcrt.CRT_ASSEMBLY_VERSION

The CRT Assembly version, from the @code{crtassem.h} header file.
@end deffn

@geindex VC_ASSEMBLY_PUBLICKEYTOKEN (msvcrt モジュール)
@anchor{library/msvcrt msvcrt VC_ASSEMBLY_PUBLICKEYTOKEN}@anchor{1578}
@deffn {データ} msvcrt.VC_ASSEMBLY_PUBLICKEYTOKEN

The VC Assembly public key token, from the @code{crtassem.h} header file.
@end deffn

@geindex LIBRARIES_ASSEMBLY_NAME_PREFIX (msvcrt モジュール)
@anchor{library/msvcrt msvcrt LIBRARIES_ASSEMBLY_NAME_PREFIX}@anchor{1579}
@deffn {データ} msvcrt.LIBRARIES_ASSEMBLY_NAME_PREFIX

The Libraries Assembly name prefix, from the @code{crtassem.h} header file.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node winreg --- Windows レジストリへのアクセス,winsound --- Windows 用の音声再生インターフェース,msvcrt --- MS VC++ ランタイムの有用なルーチン群,MS Windows 固有のサービス
@anchor{library/winreg doc}@anchor{4d53}@anchor{library/winreg module-winreg}@anchor{11c}@anchor{library/winreg translation-repo}@anchor{4d54}@anchor{library/winreg winreg-windows-registry-access}@anchor{4d55}
@subsection @code{winreg} --- Windows レジストリへのアクセス


@geindex module; winreg


__________________________________________________________________


これらの関数は Windows レジストリ API を Python から使えるようにします。プログラマがレジストリハンドルを明示的にクローズするのを忘れた場合でも、確実にハンドルがクローズされるようにするために、レジストリハンドルとして整数値ではなく @ref{4d56,,ハンドルオブジェクト} が使われます。

@ref{213f,,Availability}: Windows.
@anchor{library/winreg exception-changed}@anchor{4d57}

バージョン 3.3 で変更: このモジュールのいくつかの関数は以前は @ref{1260,,WindowsError} を送出していました。それは今では @ref{2c0,,OSError} の別名です。


@menu
* 関数: 関数<14>. 
* 定数: 定数<11>. 
* レジストリハンドルオブジェクト:: 

@end menu

@node 関数<14>,定数<11>,,winreg --- Windows レジストリへのアクセス
@anchor{library/winreg functions}@anchor{4d58}@anchor{library/winreg id1}@anchor{4d59}
@subsubsection 関数


このモジュールでは以下の関数を提供します:

@geindex CloseKey() (winreg モジュール)
@anchor{library/winreg winreg CloseKey}@anchor{4d5a}
@deffn {の関数} winreg.CloseKey (hkey)

以前開かれたレジストリキーを閉じます。`hkey' 引数は以前開かれたレジストリキーを指定します。

@cartouche
@quotation 注釈 
このメソッドを使って (または @ref{4d5b,,hkey.Close()} によって) `hkey' が閉じられなかった場合、Python が `hkey' オブジェクトを破壊する際に閉じられます。
@end quotation
@end cartouche
@end deffn

@geindex ConnectRegistry() (winreg モジュール)
@anchor{library/winreg winreg ConnectRegistry}@anchor{4764}
@deffn {の関数} winreg.ConnectRegistry (computer_name, key)

他のコンピュータ上にある事前に定義されたレジストリハンドルとの接続を確立し、 @ref{4d56,,ハンドルオブジェクト} を返します。

`computer_name' はリモートコンピュータの名前で、@code{r"\\computername"} の形式をとります。@code{None} の場合、ローカルのコンピュータが使われます。

`key' は、事前に定義された接続先のハンドルです。

戻り値は開かれたキーのハンドルです。関数が失敗した場合、 @ref{2c0,,OSError} 例外が送出されます。

引数 @code{computer_name}, @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.ConnectRegistry} を送出します。


バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex CreateKey() (winreg モジュール)
@anchor{library/winreg winreg CreateKey}@anchor{4765}
@deffn {の関数} winreg.CreateKey (key, sub_key)

指定されたキーを生成するか開き、 @ref{4d56,,ハンドルオブジェクト} を返します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`sub_key' はこのメソッドが開く、または新規作成するキーの名前です。

`key' が事前に定義されたキーのうちの一つなら、`sub_key' は @code{None} でかまいません。その場合、この関数に渡されるキーハンドルと同じハンドルが返されます。

キーがすでに存在する場合、この関数はその既存のキーを開きます。

戻り値は開かれたキーのハンドルです。関数が失敗した場合、 @ref{2c0,,OSError} 例外が送出されます。

引数 @code{key}, @code{sub_key}, @code{access} を指定して @ref{1c6e,,監査イベント} @code{winreg.CreateKey} を送出します。

引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.OpenKey/result} を送出します。


バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex CreateKeyEx() (winreg モジュール)
@anchor{library/winreg winreg CreateKeyEx}@anchor{157a}
@deffn {の関数} winreg.CreateKeyEx (key, sub_key, reserved=0, access=KEY_WRITE)

指定されたキーを生成するか開き、 @ref{4d56,,ハンドルオブジェクト} を返します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`sub_key' はこのメソッドが開く、または新規作成するキーの名前です。

`reserved' は予約された整数で、 0 でなくてはなりません。デフォルト値は 0 です。

`access' は、 key に対して想定されるセキュリティアクセスを示すアクセスマスクを指定する整数です。デフォルトは @ref{4d5d,,KEY_WRITE} です。その他の利用可能な値については @ref{4d5e,,アクセス権} を参照してください。

`key' が事前に定義されたキーのうちの一つなら、`sub_key' は @code{None} でかまいません。その場合、この関数に渡されるキーハンドルと同じハンドルが返されます。

キーがすでに存在する場合、この関数はその既存のキーを開きます。

戻り値は開かれたキーのハンドルです。関数が失敗した場合、 @ref{2c0,,OSError} 例外が送出されます。

引数 @code{key}, @code{sub_key}, @code{access} を指定して @ref{1c6e,,監査イベント} @code{winreg.CreateKey} を送出します。

引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.OpenKey/result} を送出します。


Added in version 3.2.



バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex DeleteKey() (winreg モジュール)
@anchor{library/winreg winreg DeleteKey}@anchor{4766}
@deffn {の関数} winreg.DeleteKey (key, sub_key)

指定されたキーを削除します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`sub_key'  は文字列で、`key' 引数によって指定されたキーのサブキーでなければなりません。この値は @code{None} であってはならず、キーはサブキーを持っていなくてもかまいません。

`このメソッドはサブキーをもつキーを削除することはできません。'

このメソッドの実行が成功すると、キー全体が、その値すべてを含めて削除されます。このメソッドが失敗した場合、 @ref{2c0,,OSError} 例外が送出されます。

Raises an @ref{1c6e,,auditing event} @code{winreg.DeleteKey} with arguments @code{key}, @code{sub_key}, @code{access}.


バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex DeleteKeyEx() (winreg モジュール)
@anchor{library/winreg winreg DeleteKeyEx}@anchor{157b}
@deffn {の関数} winreg.DeleteKeyEx (key, sub_key, access=KEY_WOW64_64KEY, reserved=0)

指定されたキーを削除します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`sub_key' は `key' 引数によって指定された key の subkey でなければなりません。この値は @code{None} であってはなりません。また、key は subkey を持たないかもしれません。

`reserved' は予約された整数で、 0 でなくてはなりません。デフォルト値は 0 です。

`access' は、 key に対して想定されるセキュリティアクセスを示すアクセスマスクを指定する整数です。デフォルトは @ref{4d5f,,KEY_WOW64_64KEY} です。32 bit Windows では、WOW64 定数は無視されます。その他の利用可能な値については @ref{4d5e,,アクセス権} を参照してください。

`このメソッドはサブキーをもつキーを削除することはできません。'

このメソッドの実行が成功すると、キー全体が、その値すべてを含めて削除されます。このメソッドが失敗した場合、 @ref{2c0,,OSError} 例外が送出されます。

サポートされていない Windows バージョンでは、 @ref{36b,,NotImplementedError} 例外を発生させます。

Raises an @ref{1c6e,,auditing event} @code{winreg.DeleteKey} with arguments @code{key}, @code{sub_key}, @code{access}.


Added in version 3.2.



バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex DeleteValue() (winreg モジュール)
@anchor{library/winreg winreg DeleteValue}@anchor{4767}
@deffn {の関数} winreg.DeleteValue (key, value)

レジストリキーから指定された名前つきの値を削除します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`value' は削除したい値を指定するための文字列です。

引数 @code{key}, @code{value} を指定して @ref{1c6e,,監査イベント} @code{winreg.DeleteValue} を送出します。
@end deffn

@geindex EnumKey() (winreg モジュール)
@anchor{library/winreg winreg EnumKey}@anchor{4768}
@deffn {の関数} winreg.EnumKey (key, index)

開かれているレジストリキーのサブキーを列挙し、文字列で返します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`index' は整数値で、取得するキーのインデクスを指定します。

この関数は、呼び出されるたびに一つのサブキーの名前を取得します。この関数は通常、これ以上値がないことを示す @ref{2c0,,OSError} 例外が送出されるまで繰り返し呼び出されます。

引数 @code{key}, @code{index} を指定して @ref{1c6e,,監査イベント} @code{winreg.EnumKey} を送出します。


バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex EnumValue() (winreg モジュール)
@anchor{library/winreg winreg EnumValue}@anchor{4769}
@deffn {の関数} winreg.EnumValue (key, index)

開かれているレジストリキーの値を列挙し、タプルで返します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`index' は整数値で、取得する値のインデクスを指定します。

この関数は、呼び出されるたびに一つのサブキーの名前を取得します。この関数は通常、これ以上値がないことを示す @ref{2c0,,OSError} 例外が送出されるまで繰り返し呼び出されます。

結果は 3 要素のタプルになります:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

意味

@item

@code{0}

@tab

値の名前を指定する文字列

@item

@code{1}

@tab

値のデータを保持するためのオブジェクトで、その型は背後のレジストリ型に依存します

@item

@code{2}

@tab

値のデータ型を指定する整数です (@ref{1b03,,SetValueEx()} のドキュメント内のテーブルを参照してください)

@end multitable


引数 @code{key}, @code{index} を指定して @ref{1c6e,,監査イベント} @code{winreg.EnumValue} を送出します。


バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex % (パーセント);environment variables expansion (Windows)

@geindex ExpandEnvironmentStrings() (winreg モジュール)
@anchor{library/winreg winreg ExpandEnvironmentStrings}@anchor{1611}
@deffn {の関数} winreg.ExpandEnvironmentStrings (str)

@ref{4d60,,REG_EXPAND_SZ} のように、環境変数プレースホルダ @code{%NAME%} を文字列で展開します:

@example
>>> ExpandEnvironmentStrings('%windir%')
'C:\\Windows'
@end example

引数 @code{str} を指定して @ref{1c6e,,監査イベント} @code{winreg.ExpandEnvironmentStrings} を送出します。
@end deffn

@geindex FlushKey() (winreg モジュール)
@anchor{library/winreg winreg FlushKey}@anchor{4d61}
@deffn {の関数} winreg.FlushKey (key)

キーのすべての属性をレジストリに書き込みます。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

キーを変更するために @ref{4d61,,FlushKey()} を呼ぶ必要はありません。レジストリの変更は怠惰なフラッシュ機構 (lazy flusher) を使ってフラッシュされます。また、システムの遮断時にもディスクにフラッシュされます。 @ref{4d5a,,CloseKey()} と違って、 @ref{4d61,,FlushKey()} メソッドはレジストリに全てのデータを書き終えたときにのみ返ります。アプリケーションは、レジストリへの変更を絶対に確実にディスク上に反映させる必要がある場合にのみ、 @ref{4d61,,FlushKey()} を呼ぶべきです。

@cartouche
@quotation 注釈 
@ref{4d61,,FlushKey()} を呼び出す必要があるかどうか分からない場合、おそらくその必要はありません。
@end quotation
@end cartouche
@end deffn

@geindex LoadKey() (winreg モジュール)
@anchor{library/winreg winreg LoadKey}@anchor{476a}
@deffn {の関数} winreg.LoadKey (key, sub_key, file_name)

指定されたキーの下にサブキーを生成し、サブキーに指定されたファイルのレジストリ情報を記録します。

`key' は @ref{4764,,ConnectRegistry()} が返したハンドルか、定数 @ref{4d62,,HKEY_USERS} と @ref{4d63,,HKEY_LOCAL_MACHINE} のどちらかです。

`sub_key' は記録先のサブキーを指定する文字列です。

`file_name' はレジストリデータを読み出すためのファイル名です。このファイルは @ref{476f,,SaveKey()} 関数で生成されたファイルでなくてはなりません。ファイル割り当てテーブル (FAT) ファイルシステム下では、ファイル名は拡張子を持っていてはなりません。

A call to @ref{476a,,LoadKey()} fails if the calling process does not have the
@code{SE_RESTORE_PRIVILEGE} privilege.  Note that privileges are different
from permissions -- see the RegLoadKey documentation@footnote{https://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx} for
more details.

`key' が @ref{4764,,ConnectRegistry()} によって返されたハンドルの場合、 `file_name' に指定されたパスはリモートコンピュータに対する相対パス名になります。

引数 @code{key}, @code{sub_key}, @code{file_name} を指定して @ref{1c6e,,監査イベント} @code{winreg.LoadKey} を送出します。
@end deffn

@geindex OpenKey() (winreg モジュール)
@geindex OpenKeyEx() (winreg モジュール)
@anchor{library/winreg winreg OpenKey}@anchor{476b}
@deffn {の関数} winreg.OpenKey (key, sub_key, reserved=0, access=KEY_READ)
@anchor{library/winreg winreg OpenKeyEx}@anchor{4d64}
@deffnx {の関数} winreg.OpenKeyEx (key, sub_key, reserved=0, access=KEY_READ)

指定されたキーを開き、 @ref{4d56,,ハンドルオブジェクト} を返します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`sub_key' は開くサブキーを指定する文字列です。

`reserved' は予約された整数で、 0 でなくてはなりません。デフォルト値は 0 です。

`access' は、 key に対して想定されるセキュリティアクセスを示すアクセスマスクを指定する整数です。デフォルトは @ref{4d65,,KEY_READ} です。その他の利用可能な値については @ref{4d5e,,アクセス権} を参照してください。

指定されたキーへの新しいハンドルが返されます。

この関数が失敗すると、 @ref{2c0,,OSError} が送出されます。

引数 @code{key}, @code{sub_key}, @code{access} を指定して @ref{1c6e,,監査イベント} @code{winreg.OpenKey} を送出します。

引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.OpenKey/result} を送出します。


バージョン 3.2 で変更: 名前付き引数が使用できるようになりました。



バージョン 3.3 で変更: @ref{4d57,,上記} を参照。

@end deffn

@geindex QueryInfoKey() (winreg モジュール)
@anchor{library/winreg winreg QueryInfoKey}@anchor{476d}
@deffn {の関数} winreg.QueryInfoKey (key)

キーに関する情報をタプルとして返します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

結果は 3 要素のタプルになります:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

意味

@item

@code{0}

@tab

このキーが持つサブキーの数を表す整数。

@item

@code{1}

@tab

このキーが持つ値の数を表す整数。

@item

@code{2}

@tab

最後のキーの変更が (あれば) いつだったかを表す整数で、1601 年 1 月 1 日からの 100 ナノ秒単位で数えたもの。

@end multitable


引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.QueryInfoKey} を送出します。
@end deffn

@geindex QueryValue() (winreg モジュール)
@anchor{library/winreg winreg QueryValue}@anchor{476e}
@deffn {の関数} winreg.QueryValue (key, sub_key)

キーに対する、名前付けられていない値を文字列で取得します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`sub_key' は値が関連付けられているサブキーの名前を保持する文字列です。この引数が @code{None} または空文字列の場合、この関数は `key' で指定されたキーに対して @ref{4770,,SetValue()} メソッドで設定された値を取得します。

レジストリ中の値は名前、型、およびデータから構成されています。このメソッドはあるキーのデータ中で、名前 @code{NULL} をもつ最初の値を取得します。しかし背後のAPI 呼び出しは型情報を返しません。なので、可能ならいつでも @ref{1784,,QueryValueEx()} を使うべきです。

引数 @code{key}, @code{sub_key}, @code{value_name} を指定して @ref{1c6e,,監査イベント} @code{winreg.QueryValue} を送出します。
@end deffn

@geindex QueryValueEx() (winreg モジュール)
@anchor{library/winreg winreg QueryValueEx}@anchor{1784}
@deffn {の関数} winreg.QueryValueEx (key, value_name)

開かれたレジストリキーに関連付けられている、指定した名前の値に対して、型およびデータを取得します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`value_name' は要求する値を指定する文字列です。

結果は 2 つの要素からなるタプルです:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

意味

@item

@code{0}

@tab

レジストリ要素の値。

@item

@code{1}

@tab

この値のレジストリ型を表す整数。 (@ref{1b03,,SetValueEx()} のドキュメント内のテーブルを参照してください。)

@end multitable


引数 @code{key}, @code{sub_key}, @code{value_name} を指定して @ref{1c6e,,監査イベント} @code{winreg.QueryValue} を送出します。
@end deffn

@geindex SaveKey() (winreg モジュール)
@anchor{library/winreg winreg SaveKey}@anchor{476f}
@deffn {の関数} winreg.SaveKey (key, file_name)

指定されたキーと、そのサブキー全てを指定したファイルに保存します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`file_name' はレジストリデータを保存するファイルの名前です、このファイルはすでに存在していてはいけません。このファイル名が拡張子を含んでいる場合、 @ref{476a,,LoadKey()} メソッドは、FAT ファイルシステムを使うことができません。

If `key' represents a key on a remote computer, the path described by
`file_name' is relative to the remote computer. The caller of this method must
possess the `SeBackupPrivilege' security privilege.  Note that
privileges are different than permissions -- see the
Conflicts Between User Rights and Permissions documentation@footnote{https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx}
for more details.

この関数は `security_attributes' を @code{NULL} にして API に渡します。

引数 @code{key}, @code{file_name} を指定して @ref{1c6e,,監査イベント} @code{winreg.SaveKey} を送出します。
@end deffn

@geindex SetValue() (winreg モジュール)
@anchor{library/winreg winreg SetValue}@anchor{4770}
@deffn {の関数} winreg.SetValue (key, sub_key, type, value)

値を指定したキーに関連付けます。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`sub_key' は値が関連付けられているサブキーの名前を表す文字列です。

`type' はデータの型を指定する整数です。現状では、この値は @ref{4d66,,REG_SZ} でなければならず、これは文字列だけがサポートされていることを示します。他のデータ型をサポートするには @ref{1b03,,SetValueEx()} を使ってください。

`value' は新たな値を指定する文字列です。

`sub_key' 引数で指定されたキーが存在しなければ、SetValue 関数で生成されます。

値の長さは利用可能なメモリによって制限されます。(2048 バイト以上の) 長い値はファイルに保存して、そのファイル名を設定レジストリに保存するべきです。そうすればレジストリを効率的に動作させる役に立ちます。

`key' 引数に指定されたキーは @ref{4d67,,KEY_SET_VALUE} アクセスで開かれていなければなりません。

引数 @code{key}, @code{sub_key}, @code{type}, @code{value} を指定して @ref{1c6e,,監査イベント} @code{winreg.SetValue} を送出します。
@end deffn

@geindex SetValueEx() (winreg モジュール)
@anchor{library/winreg winreg SetValueEx}@anchor{1b03}
@deffn {の関数} winreg.SetValueEx (key, value_name, reserved, type, value)

開かれたレジストリキーの値フィールドにデータを記録します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

`value_name' は値が関連付けられているサブキーの名前を表す文字列です。

`reserved' は何もしません - API には常にゼロが渡されます。

`type' はデータの型を指定する整数です。利用できる型については @ref{4d68,,値の型} を参照してください。

`value' は新たな値を指定する文字列です。

このメソッドではまた、指定されたキーに対して、さらに別の値や型情報を設定することができます。 `key' 引数で指定されたキーは @ref{4d67,,KEY_SET_VALUE} アクセスで開かれていなければなりません。

キーを開くには、 @ref{4765,,CreateKey()} または @ref{476b,,OpenKey()} メソッドを使ってください。

値の長さは利用可能なメモリによって制限されます。(2048 バイト以上の) 長い値はファイルに保存して、そのファイル名を設定レジストリに保存するべきです。そうすればレジストリを効率的に動作させる役に立ちます。

引数 @code{key}, @code{sub_key}, @code{type}, @code{value} を指定して @ref{1c6e,,監査イベント} @code{winreg.SetValue} を送出します。
@end deffn

@geindex DisableReflectionKey() (winreg モジュール)
@anchor{library/winreg winreg DisableReflectionKey}@anchor{157c}
@deffn {の関数} winreg.DisableReflectionKey (key)

64ビット OS上で動作している 32bit プロセスに対するレジストリリフレクションを無効にします。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

32bit OS上では一般的に @ref{36b,,NotImplementedError} 例外を発生させます。

key がリフレクションリストに無い場合は、この関数は成功しますが効果はありません。あるキーのリフレクションを無効にしても、そのキーのサブキーのリフレクションには全く影響しません。

引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.DisableReflectionKey} を送出します。
@end deffn

@geindex EnableReflectionKey() (winreg モジュール)
@anchor{library/winreg winreg EnableReflectionKey}@anchor{157d}
@deffn {の関数} winreg.EnableReflectionKey (key)

指定された、リフレクションが無効にされたキーのリフレクションを再び有効にします。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

32bit OS上では一般的に @ref{36b,,NotImplementedError} 例外を発生させます。

あるキーのリフレクションを再開しても、その全てのサブキーには影響しません。

引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.EnableReflectionKey} を送出します。
@end deffn

@geindex QueryReflectionKey() (winreg モジュール)
@anchor{library/winreg winreg QueryReflectionKey}@anchor{157e}
@deffn {の関数} winreg.QueryReflectionKey (key)

指定されたキーのリフレクション状態を確認します。

`key' はすでに開かれたキーか、既定の @ref{4d5c,,HKEY_* 定数} のうちの一つです。

リフレクションが無効になっている場合、@code{True} を返します。

32bit OS上では一般的に @ref{36b,,NotImplementedError} 例外を発生させます。

引数 @code{key} を指定して @ref{1c6e,,監査イベント} @code{winreg.QueryReflectionKey} を送出します。
@end deffn

@node 定数<11>,レジストリハンドルオブジェクト,関数<14>,winreg --- Windows レジストリへのアクセス
@anchor{library/winreg constants}@anchor{4d69}@anchor{library/winreg id2}@anchor{4d6a}
@subsubsection 定数


The following constants are defined for use in many @code{winreg} functions.

@menu
* HKEY_* 定数:: 
* アクセス権限:: 
* 値の型:: 

@end menu

@node HKEY_* 定数,アクセス権限,,定数<11>
@anchor{library/winreg hkey-constants}@anchor{4d5c}@anchor{library/winreg id3}@anchor{4d6b}
@subsubsection HKEY_* 定数


@geindex HKEY_CLASSES_ROOT (winreg モジュール)
@anchor{library/winreg winreg HKEY_CLASSES_ROOT}@anchor{4d6c}
@deffn {データ} winreg.HKEY_CLASSES_ROOT

このキー以下のレジストリエントリは、ドキュメントのタイプ（またはクラス）や、それに関連付けられたプロパティを定義しています。シェルと COM アプリケーションがこの情報を利用します。
@end deffn

@geindex HKEY_CURRENT_USER (winreg モジュール)
@anchor{library/winreg winreg HKEY_CURRENT_USER}@anchor{4d6d}
@deffn {データ} winreg.HKEY_CURRENT_USER

このキー以下のレジストリエントリは、現在のユーザーの設定を定義します。この設定には、環境変数、プログラムグループに関するデータ、カラー、プリンター、ネットワーク接続、アプリケーション設定などが含まれます。
@end deffn

@geindex HKEY_LOCAL_MACHINE (winreg モジュール)
@anchor{library/winreg winreg HKEY_LOCAL_MACHINE}@anchor{4d63}
@deffn {データ} winreg.HKEY_LOCAL_MACHINE

このキー以下のレジストリエントリは、コンピュータの物理的な状態を定義します。これには、バスタイプ、システムメモリ、インストールされているソフトウェアやハードウェアが含まれます。
@end deffn

@geindex HKEY_USERS (winreg モジュール)
@anchor{library/winreg winreg HKEY_USERS}@anchor{4d62}
@deffn {データ} winreg.HKEY_USERS

このキー以下のレジストリエントリは、ローカルコンピュータの新規ユーザーのためのデフォルト設定や、現在のユーザーの設定を定義しています。
@end deffn

@geindex HKEY_PERFORMANCE_DATA (winreg モジュール)
@anchor{library/winreg winreg HKEY_PERFORMANCE_DATA}@anchor{4d6e}
@deffn {データ} winreg.HKEY_PERFORMANCE_DATA

このキー以下のレジストリエントリは、パフォーマンスデータへのアクセスを可能にしています。実際にはデータはレジストリには格納されていません。レジストリ関数がシステムにソースからデータを集めさせます。
@end deffn

@geindex HKEY_CURRENT_CONFIG (winreg モジュール)
@anchor{library/winreg winreg HKEY_CURRENT_CONFIG}@anchor{4d6f}
@deffn {データ} winreg.HKEY_CURRENT_CONFIG

ローカルコンピュータシステムの現在のハードウェアプロファイルに関する情報を含みます。
@end deffn

@geindex HKEY_DYN_DATA (winreg モジュール)
@anchor{library/winreg winreg HKEY_DYN_DATA}@anchor{4d70}
@deffn {データ} winreg.HKEY_DYN_DATA

このキーは Windows の 98 以降のバージョンでは利用されていません。
@end deffn

@node アクセス権限,値の型,HKEY_* 定数,定数<11>
@anchor{library/winreg access-rights}@anchor{4d5e}@anchor{library/winreg id4}@anchor{4d71}
@subsubsection アクセス権限


より詳しい情報については、 Registry Key Security and Access@footnote{https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx} を参照してください。

@geindex KEY_ALL_ACCESS (winreg モジュール)
@anchor{library/winreg winreg KEY_ALL_ACCESS}@anchor{4d72}
@deffn {データ} winreg.KEY_ALL_ACCESS

STANDARD_RIGHTS_REQUIRED (@ref{4d73,,KEY_QUERY_VALUE}, @ref{4d67,,KEY_SET_VALUE}, @ref{4d74,,KEY_CREATE_SUB_KEY}, @ref{4d75,,KEY_ENUMERATE_SUB_KEYS}, @ref{4d76,,KEY_NOTIFY}, @ref{4d77,,KEY_CREATE_LINK}) アクセス権限の組み合わせ。
@end deffn

@geindex KEY_WRITE (winreg モジュール)
@anchor{library/winreg winreg KEY_WRITE}@anchor{4d5d}
@deffn {データ} winreg.KEY_WRITE

STANDARD_RIGHTS_WRITE (@ref{4d67,,KEY_SET_VALUE}, @ref{4d74,,KEY_CREATE_SUB_KEY}) アクセス権限の組み合わせ。
@end deffn

@geindex KEY_READ (winreg モジュール)
@anchor{library/winreg winreg KEY_READ}@anchor{4d65}
@deffn {データ} winreg.KEY_READ

STANDARD_RIGHTS_READ (@ref{4d73,,KEY_QUERY_VALUE}, @ref{4d75,,KEY_ENUMERATE_SUB_KEYS}, @ref{4d76,,KEY_NOTIFY}) アクセス権限の組み合わせ。
@end deffn

@geindex KEY_EXECUTE (winreg モジュール)
@anchor{library/winreg winreg KEY_EXECUTE}@anchor{4d78}
@deffn {データ} winreg.KEY_EXECUTE

@ref{4d65,,KEY_READ} と同じ。
@end deffn

@geindex KEY_QUERY_VALUE (winreg モジュール)
@anchor{library/winreg winreg KEY_QUERY_VALUE}@anchor{4d73}
@deffn {データ} winreg.KEY_QUERY_VALUE

レジストリキーの値を問い合わせるのに必要。
@end deffn

@geindex KEY_SET_VALUE (winreg モジュール)
@anchor{library/winreg winreg KEY_SET_VALUE}@anchor{4d67}
@deffn {データ} winreg.KEY_SET_VALUE

レジストリの値を作成、削除、設定するのに必要。
@end deffn

@geindex KEY_CREATE_SUB_KEY (winreg モジュール)
@anchor{library/winreg winreg KEY_CREATE_SUB_KEY}@anchor{4d74}
@deffn {データ} winreg.KEY_CREATE_SUB_KEY

レジストリキーのサブキーを作るのに必要。
@end deffn

@geindex KEY_ENUMERATE_SUB_KEYS (winreg モジュール)
@anchor{library/winreg winreg KEY_ENUMERATE_SUB_KEYS}@anchor{4d75}
@deffn {データ} winreg.KEY_ENUMERATE_SUB_KEYS

レジストリキーのサブキーを列挙するのに必要。
@end deffn

@geindex KEY_NOTIFY (winreg モジュール)
@anchor{library/winreg winreg KEY_NOTIFY}@anchor{4d76}
@deffn {データ} winreg.KEY_NOTIFY

レジストリキーやそのサブキーに対する変更通知を要求するのに必要。
@end deffn

@geindex KEY_CREATE_LINK (winreg モジュール)
@anchor{library/winreg winreg KEY_CREATE_LINK}@anchor{4d77}
@deffn {データ} winreg.KEY_CREATE_LINK

システムでの利用のために予約されている。
@end deffn

@menu
* 64-bit 特有のアクセス権:: 

@end menu

@node 64-bit 特有のアクセス権,,,アクセス権限
@anchor{library/winreg bit-access-rights}@anchor{4d79}@anchor{library/winreg bit-specific}@anchor{4d7a}
@subsubsection 64-bit 特有のアクセス権


より詳しい情報については、 Accessing an Alternate Registry View@footnote{https://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx} を参照してください。

@geindex KEY_WOW64_64KEY (winreg モジュール)
@anchor{library/winreg winreg KEY_WOW64_64KEY}@anchor{4d5f}
@deffn {データ} winreg.KEY_WOW64_64KEY

64 bit Windows 上のアプリケーションが、64 bit のレジストリビュー上で操作する事を示します。32 bit Windows では、この定数は無視されます。
@end deffn

@geindex KEY_WOW64_32KEY (winreg モジュール)
@anchor{library/winreg winreg KEY_WOW64_32KEY}@anchor{4d7b}
@deffn {データ} winreg.KEY_WOW64_32KEY

64 bit Windows 上のアプリケーションが、32 bit のレジストリビュー上で操作する事を示します。32 bit Windows では、この定数は無視されます。
@end deffn

@node 値の型,,アクセス権限,定数<11>
@anchor{library/winreg id5}@anchor{4d7c}@anchor{library/winreg value-types}@anchor{4d68}
@subsubsection 値の型


より詳しい情報については、 Registry Value Types@footnote{https://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx} を参照してください。

@geindex REG_BINARY (winreg モジュール)
@anchor{library/winreg winreg REG_BINARY}@anchor{4d7d}
@deffn {データ} winreg.REG_BINARY

何らかの形式のバイナリデータ。
@end deffn

@geindex REG_DWORD (winreg モジュール)
@anchor{library/winreg winreg REG_DWORD}@anchor{4d7e}
@deffn {データ} winreg.REG_DWORD

32 ビットの数。
@end deffn

@geindex REG_DWORD_LITTLE_ENDIAN (winreg モジュール)
@anchor{library/winreg winreg REG_DWORD_LITTLE_ENDIAN}@anchor{4d7f}
@deffn {データ} winreg.REG_DWORD_LITTLE_ENDIAN

32 ビットのリトルエンディアン形式の数。@ref{4d7e,,REG_DWORD} と等価。
@end deffn

@geindex REG_DWORD_BIG_ENDIAN (winreg モジュール)
@anchor{library/winreg winreg REG_DWORD_BIG_ENDIAN}@anchor{4d80}
@deffn {データ} winreg.REG_DWORD_BIG_ENDIAN

32 ビットのビッグエンディアン形式の数。
@end deffn

@geindex REG_EXPAND_SZ (winreg モジュール)
@anchor{library/winreg winreg REG_EXPAND_SZ}@anchor{4d60}
@deffn {データ} winreg.REG_EXPAND_SZ

環境変数を参照している、ヌル文字で終端された文字列。(@code{%PATH%})。
@end deffn

@geindex REG_LINK (winreg モジュール)
@anchor{library/winreg winreg REG_LINK}@anchor{4d81}
@deffn {データ} winreg.REG_LINK

Unicode のシンボリックリンク。
@end deffn

@geindex REG_MULTI_SZ (winreg モジュール)
@anchor{library/winreg winreg REG_MULTI_SZ}@anchor{1dc3}
@deffn {データ} winreg.REG_MULTI_SZ

ヌル文字で終端された文字列からなり、二つのヌル文字で終端されている配列。 (Python はこの終端の処理を自動的に行います。)
@end deffn

@geindex REG_NONE (winreg モジュール)
@anchor{library/winreg winreg REG_NONE}@anchor{4d82}
@deffn {データ} winreg.REG_NONE

定義されていない値の形式。
@end deffn

@geindex REG_QWORD (winreg モジュール)
@anchor{library/winreg winreg REG_QWORD}@anchor{eff}
@deffn {データ} winreg.REG_QWORD

64 ビットの数。


Added in version 3.6.

@end deffn

@geindex REG_QWORD_LITTLE_ENDIAN (winreg モジュール)
@anchor{library/winreg winreg REG_QWORD_LITTLE_ENDIAN}@anchor{4d83}
@deffn {データ} winreg.REG_QWORD_LITTLE_ENDIAN

64 ビットのリトルエンディアン形式の数。@ref{eff,,REG_QWORD} と等価。


Added in version 3.6.

@end deffn

@geindex REG_RESOURCE_LIST (winreg モジュール)
@anchor{library/winreg winreg REG_RESOURCE_LIST}@anchor{4d84}
@deffn {データ} winreg.REG_RESOURCE_LIST

デバイスドライバリソースのリスト。
@end deffn

@geindex REG_FULL_RESOURCE_DESCRIPTOR (winreg モジュール)
@anchor{library/winreg winreg REG_FULL_RESOURCE_DESCRIPTOR}@anchor{4d85}
@deffn {データ} winreg.REG_FULL_RESOURCE_DESCRIPTOR

ハードウェアセッティング。
@end deffn

@geindex REG_RESOURCE_REQUIREMENTS_LIST (winreg モジュール)
@anchor{library/winreg winreg REG_RESOURCE_REQUIREMENTS_LIST}@anchor{4d86}
@deffn {データ} winreg.REG_RESOURCE_REQUIREMENTS_LIST

ハードウェアリソースリスト。
@end deffn

@geindex REG_SZ (winreg モジュール)
@anchor{library/winreg winreg REG_SZ}@anchor{4d66}
@deffn {データ} winreg.REG_SZ

ヌル文字で終端された文字列。
@end deffn

@node レジストリハンドルオブジェクト,,定数<11>,winreg --- Windows レジストリへのアクセス
@anchor{library/winreg handle-object}@anchor{4d56}@anchor{library/winreg registry-handle-objects}@anchor{4d87}
@subsubsection レジストリハンドルオブジェクト


このオブジェクトは Windows の HKEY オブジェクトをラップし、オブジェクトが破壊されたときに自動的にハンドルを閉じます。オブジェクトの @ref{4d5b,,Close()} メソッドと @ref{4d5a,,CloseKey()} 関数のどちらも、後始末がきちんと行われることを保証するために呼び出すことができます。

このモジュールのレジストリ関数は全て、これらのハンドルオブジェクトの一つを返します。

このモジュールのレジストリ関数でハンドルオブジェクトを受理するものは全て整数も受理しますが、ハンドルオブジェクトを利用することを推奨します。

Handle objects provide semantics for @ref{14ed,,__bool__()} -- thus

@example
if handle:
    print("Yes")
@end example

は、ハンドルが現在有効な (閉じられたり切り離されたりしていない) 場合には @code{Yes} となります。

ハンドルオブジェクトは (例えば組み込みの @ref{19b,,int()} 関数を使って) 整数に変換することができます。この場合、背後の Windows ハンドル値が返されます、また、 @ref{476c,,Detach()}  メソッドを使って整数のハンドル値を返させると同時に、ハンドルオブジェクトから Windows ハンドルを切り離すこともできます。

@geindex Close() (winreg.PyHKEY のメソッド)
@anchor{library/winreg winreg PyHKEY Close}@anchor{4d5b}
@deffn {メソッド} PyHKEY.Close ()

背後の Windows ハンドルを閉じます。

ハンドルがすでに閉じられていてもエラーは送出されません。
@end deffn

@geindex Detach() (winreg.PyHKEY のメソッド)
@anchor{library/winreg winreg PyHKEY Detach}@anchor{476c}
@deffn {メソッド} PyHKEY.Detach ()

ハンドルオブジェクトから Windows ハンドルを切り離します。

切り離される以前にそのハンドルを保持していた整数オブジェクトが返されます。ハンドルがすでに切り離されていたり閉じられていたりした場合、ゼロが返されます。

この関数を呼び出した後、ハンドルは確実に無効化されますが、閉じられるわけではありません。背後の Win32 ハンドルがハンドルオブジェクトよりも長く維持される必要がある場合にはこの関数を呼び出すとよいでしょう。

Raises an @ref{1c6e,,auditing event} @code{winreg.PyHKEY.Detach} with argument @code{key}.
@end deffn

@geindex __enter__() (winreg.PyHKEY のメソッド)
@geindex __exit__() (winreg.PyHKEY のメソッド)
@anchor{library/winreg winreg PyHKEY __enter__}@anchor{4d88}
@deffn {メソッド} PyHKEY.__enter__ ()
@anchor{library/winreg winreg PyHKEY __exit__}@anchor{4d89}
@deffnx {メソッド} PyHKEY.__exit__ (*exc_info)

HKEY オブジェクトは @ref{7e4,,__enter__()}, @ref{1518,,__exit__()} メソッドを実装していて、 @ref{186,,with} 文のためのコンテキストプロトコルをサポートしています:

@example
with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
    ...  # work with key
@end example

このコードは、 @ref{186,,with} ブロックから抜けるときに自動的に `key' を閉じます。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node winsound --- Windows 用の音声再生インターフェース,,winreg --- Windows レジストリへのアクセス,MS Windows 固有のサービス
@anchor{library/winsound doc}@anchor{4d8a}@anchor{library/winsound module-winsound}@anchor{11d}@anchor{library/winsound translation-repo}@anchor{4d8b}@anchor{library/winsound winsound-sound-playing-interface-for-windows}@anchor{4d8c}
@subsection @code{winsound} --- Windows 用の音声再生インターフェース


@geindex module; winsound


__________________________________________________________________


The @code{winsound} module provides access to the basic sound-playing machinery
provided by Windows platforms.  It includes functions and several constants.

@ref{213f,,Availability}: Windows.

@geindex Beep() (winsound モジュール)
@anchor{library/winsound winsound Beep}@anchor{f01}
@deffn {の関数} winsound.Beep (frequency, duration)

PC のスピーカを鳴らします。引数 `frequency' は鳴らす音の周波数の指定で、単位は Hz です。値は 37 から 32,767 でなくてはなりません。引数 `duration' は音を何ミリ秒鳴らすかの指定です。システムがスピーカを鳴らすことができない場合、例外 @ref{244,,RuntimeError} が送出されます。
@end deffn

@geindex PlaySound() (winsound モジュール)
@anchor{library/winsound winsound PlaySound}@anchor{f03}
@deffn {の関数} winsound.PlaySound (sound, flags)

プラットフォームの API から関数 @code{PlaySound()} を呼び出します。引数 `sound' はファイル名、システム音エイリアス、音声データの @ref{193,,bytes-like オブジェクト}、または @code{None} をとり得ます。 `sound' の解釈は `flags' の値に依存します。この値は以下に述べる定数をビット単位OR して組み合わせたものになります。 `sound' 引数が @code{None} だった場合、現在再生中のWave形式サウンドの再生を停止します。システムのエラーが発生した場合、例外 @ref{244,,RuntimeError} が送出されます。
@end deffn

@geindex MessageBeep() (winsound モジュール)
@anchor{library/winsound winsound MessageBeep}@anchor{f02}
@deffn {の関数} winsound.MessageBeep (type=MB_OK)

根底にある @code{MessageBeep()} 関数をプラットフォームの API から呼び出します。この関数は音声をレジストリの指定に従って再生します。 `type' 引数はどの音声を再生するかを指定します; とり得る値は @code{-1}, @code{MB_ICONASTERISK}, @code{MB_ICONEXCLAMATION}, @code{MB_ICONHAND}, @code{MB_ICONQUESTION},および @code{MB_OK} で、全て以下に記述されています。値 @code{-1} は "単純なビープ音" を再生します; この値は他の場合で音声を再生することができなかった際の最終的な代替音です。システムがエラーを示したら、@ref{244,,RuntimeError} が送出されます。
@end deffn

@geindex SND_FILENAME (winsound モジュール)
@anchor{library/winsound winsound SND_FILENAME}@anchor{4d8d}
@deffn {データ} winsound.SND_FILENAME

`sound' パラメタが WAV ファイル名であることを示します。 @ref{4d8e,,SND_ALIAS} と同時に使ってはいけません。
@end deffn

@geindex SND_ALIAS (winsound モジュール)
@anchor{library/winsound winsound SND_ALIAS}@anchor{4d8e}
@deffn {データ} winsound.SND_ALIAS

引数 `sound' はレジストリにある音声データに関連付けられた名前であることを示します。指定した名前がレジストリ上にない場合、定数 @ref{4d8f,,SND_NODEFAULT} が同時に指定されていない限り、システム標準の音声データが再生されます。標準の音声データが登録されていない場合、例外 @ref{244,,RuntimeError} が送出されます。 @ref{4d8d,,SND_FILENAME} と同時に使ってはいけません。

全ての Win32 システムは少なくとも以下の名前をサポートします; ほとんどのシステムでは他に多数あります:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@ref{f03,,PlaySound()} `name'

@tab

対応するコントロールパネルでの音声名

@item

@code{'SystemAsterisk'}

@tab

Asterisk

@item

@code{'SystemExclamation'}

@tab

Exclamation

@item

@code{'SystemExit'}

@tab

Exit Windows

@item

@code{'SystemHand'}

@tab

Critical Stop

@item

@code{'SystemQuestion'}

@tab

Question

@end multitable


例えば:

@example
import winsound
# Play Windows exit sound.
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

# Probably play Windows default sound, if any is registered (because
# "*" probably isn't the registered name of any sound).
winsound.PlaySound("*", winsound.SND_ALIAS)
@end example
@end deffn

@geindex SND_LOOP (winsound モジュール)
@anchor{library/winsound winsound SND_LOOP}@anchor{4d90}
@deffn {データ} winsound.SND_LOOP

音声データを繰り返し再生します。システムがブロックしないようにするため、 @ref{4d91,,SND_ASYNC} フラグを同時に使わなくてはなりません。 @ref{4d92,,SND_MEMORY} と同時に使うことはできません。
@end deffn

@geindex SND_MEMORY (winsound モジュール)
@anchor{library/winsound winsound SND_MEMORY}@anchor{4d92}
@deffn {データ} winsound.SND_MEMORY

@ref{f03,,PlaySound()} の引数 `sound' が @ref{193,,bytes-like オブジェクト} の形式をとった WAV ファイルのメモリ上のイメージであることを示します。

@cartouche
@quotation 注釈 
このモジュールはメモリ上のイメージを非同期に再生する機能をサポートしていません。従って、このフラグと @ref{4d91,,SND_ASYNC} を組み合わせると例外 @ref{244,,RuntimeError} が送出されます。
@end quotation
@end cartouche
@end deffn

@geindex SND_PURGE (winsound モジュール)
@anchor{library/winsound winsound SND_PURGE}@anchor{4d93}
@deffn {データ} winsound.SND_PURGE

指定した音声の全てのインスタンスについて再生処理を停止します。

@cartouche
@quotation 注釈 
このフラグは現代のWindowsプラットフォームではサポートされていません。
@end quotation
@end cartouche
@end deffn

@geindex SND_ASYNC (winsound モジュール)
@anchor{library/winsound winsound SND_ASYNC}@anchor{4d91}
@deffn {データ} winsound.SND_ASYNC

音声を非同期に再生するようにして、関数呼び出しを即座に返します。
@end deffn

@geindex SND_NODEFAULT (winsound モジュール)
@anchor{library/winsound winsound SND_NODEFAULT}@anchor{4d8f}
@deffn {データ} winsound.SND_NODEFAULT

指定した音声が見つからなかった場合にシステム標準の音声を鳴らさないようにします。
@end deffn

@geindex SND_NOSTOP (winsound モジュール)
@anchor{library/winsound winsound SND_NOSTOP}@anchor{4d94}
@deffn {データ} winsound.SND_NOSTOP

現在鳴っている音声を中断させないようにします。
@end deffn

@geindex SND_NOWAIT (winsound モジュール)
@anchor{library/winsound winsound SND_NOWAIT}@anchor{4d95}
@deffn {データ} winsound.SND_NOWAIT

サウンドドライバがビジー状態にある場合、関数がすぐ返るようにします。

@cartouche
@quotation 注釈 
このフラグは現代のWindowsプラットフォームではサポートされていません。
@end quotation
@end cartouche
@end deffn

@geindex SND_APPLICATION (winsound モジュール)
@anchor{library/winsound winsound SND_APPLICATION}@anchor{4d96}
@deffn {データ} winsound.SND_APPLICATION

The `sound' parameter is an application-specific alias in the registry.
This flag can be combined with the @ref{4d8e,,SND_ALIAS} flag
to specify an application-defined sound alias.
@end deffn

@geindex SND_SENTRY (winsound モジュール)
@anchor{library/winsound winsound SND_SENTRY}@anchor{4d97}
@deffn {データ} winsound.SND_SENTRY

Triggers a SoundSentry event when the sound is played.


Added in version 3.14.

@end deffn

@geindex SND_SYNC (winsound モジュール)
@anchor{library/winsound winsound SND_SYNC}@anchor{4d98}
@deffn {データ} winsound.SND_SYNC

The sound is played synchronously.  This is the default behavior.


Added in version 3.14.

@end deffn

@geindex SND_SYSTEM (winsound モジュール)
@anchor{library/winsound winsound SND_SYSTEM}@anchor{4d99}
@deffn {データ} winsound.SND_SYSTEM

Assign the sound to the audio session for system notification sounds.


Added in version 3.14.

@end deffn

@geindex MB_ICONASTERISK (winsound モジュール)
@anchor{library/winsound winsound MB_ICONASTERISK}@anchor{4d9a}
@deffn {データ} winsound.MB_ICONASTERISK

音声 @code{SystemDefault} を再生します。
@end deffn

@geindex MB_ICONEXCLAMATION (winsound モジュール)
@anchor{library/winsound winsound MB_ICONEXCLAMATION}@anchor{4d9b}
@deffn {データ} winsound.MB_ICONEXCLAMATION

音声 @code{SystemExclamation} を再生します。
@end deffn

@geindex MB_ICONHAND (winsound モジュール)
@anchor{library/winsound winsound MB_ICONHAND}@anchor{4d9c}
@deffn {データ} winsound.MB_ICONHAND

音声 @code{SystemHand} を再生します。
@end deffn

@geindex MB_ICONQUESTION (winsound モジュール)
@anchor{library/winsound winsound MB_ICONQUESTION}@anchor{4d9d}
@deffn {データ} winsound.MB_ICONQUESTION

音声 @code{SystemQuestion} を再生します。
@end deffn

@geindex MB_OK (winsound モジュール)
@anchor{library/winsound winsound MB_OK}@anchor{4d9e}
@deffn {データ} winsound.MB_OK

音声 @code{SystemDefault} を再生します。
@end deffn

@geindex MB_ICONERROR (winsound モジュール)
@anchor{library/winsound winsound MB_ICONERROR}@anchor{4d9f}
@deffn {データ} winsound.MB_ICONERROR

音声 @code{SystemHand} を再生します。


Added in version 3.14.

@end deffn

@geindex MB_ICONINFORMATION (winsound モジュール)
@anchor{library/winsound winsound MB_ICONINFORMATION}@anchor{4da0}
@deffn {データ} winsound.MB_ICONINFORMATION

音声 @code{SystemDefault} を再生します。


Added in version 3.14.

@end deffn

@geindex MB_ICONSTOP (winsound モジュール)
@anchor{library/winsound winsound MB_ICONSTOP}@anchor{4da1}
@deffn {データ} winsound.MB_ICONSTOP

音声 @code{SystemHand} を再生します。


Added in version 3.14.

@end deffn

@geindex MB_ICONWARNING (winsound モジュール)
@anchor{library/winsound winsound MB_ICONWARNING}@anchor{4da2}
@deffn {データ} winsound.MB_ICONWARNING

音声 @code{SystemExclamation} を再生します。


Added in version 3.14.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Unix-specific services,モジュールのコマンドラインインターフェース CLI,MS Windows 固有のサービス,Python 標準ライブラリ
@anchor{library/unix doc}@anchor{4da3}@anchor{library/unix translation-repo}@anchor{4da4}@anchor{library/unix unix}@anchor{4da5}@anchor{library/unix unix-specific-services}@anchor{4da6}
@section Unix-specific services


本章に記述されたモジュールは、Unix オペレーティングシステム、あるいはそれから派生した多くのものに固有の機能のためのインターフェースを提供します。その概要を以下に述べます:

@menu
* shlex: shlex --- 単純な字句解析. 単純な字句解析
* posix: posix --- 最も一般的な POSIX システムコール群. 最も一般的な POSIX システムコール群
* pwd: pwd --- パスワードデータベース. パスワードデータベース
* grp: grp --- グループデータベース. グループデータベース
* termios: termios --- POSIX スタイルの端末制御. POSIX スタイルの端末制御
* tty: tty --- 端末制御用の関数群. 端末制御用の関数群
* pty: pty --- 擬似端末ユーティリティ. 擬似端末ユーティリティ
* fcntl: fcntl --- fcntl および ioctl システムコール. fcntl および ioctl システムコール
* resource: resource --- リソース使用情報. リソース使用情報
* syslog: syslog --- Unix syslog ライブラリルーチン群. Unix syslog ライブラリルーチン群

@end menu

@node shlex --- 単純な字句解析,posix --- 最も一般的な POSIX システムコール群,,Unix-specific services
@anchor{library/shlex doc}@anchor{4da7}@anchor{library/shlex module-shlex}@anchor{c9}@anchor{library/shlex shlex-simple-lexical-analysis}@anchor{4da8}
@subsection @code{shlex} --- 単純な字句解析


@geindex module; shlex

`ソースコード:' Lib/shlex.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/shlex.py}


__________________________________________________________________


@ref{ec8,,shlex} クラスは Unix シェルに似た、単純な構文に対する字句解析器を簡単に書けるようにします。このクラスはしばしば、 Python アプリケーションのための実行制御ファイルのような小規模言語を書く上で便利です。

The @code{shlex} module defines the following functions:

@geindex split() (shlex モジュール)
@anchor{library/shlex shlex split}@anchor{75e}
@deffn {の関数} shlex.split (s, comments=False, posix=True)

シェルに似た文法を使って、文字列 `s' を分割します。 `comments' が @ref{d2b,,False} (デフォルト値) の場合、受理した文字列内のコメントを解析しません (@ref{ec8,,shlex} インスタンスの @ref{4da9,,commenters} メンバの値を空文字列にします)。この関数はデフォルトでは POSIX モードで動作し、 `posix' 引数が偽の場合は非 POSIX モードで動作します。


バージョン 3.12 で変更: Passing @code{None} for `s' argument now raises an exception, rather than
reading @ref{75f,,sys.stdin}.

@end deffn

@geindex join() (shlex モジュール)
@anchor{library/shlex shlex join}@anchor{c1c}
@deffn {の関数} shlex.join (split_command)

Concatenate the tokens of the list `split_command' and return a string.
This function is the inverse of @ref{75e,,split()}.

@example
>>> from shlex import join
>>> print(join(['echo', '-n', 'Multiple words']))
echo -n 'Multiple words'
@end example

The returned value is shell-escaped to protect against injection
vulnerabilities (see @ref{582,,quote()}).


Added in version 3.8.

@end deffn

@geindex quote() (shlex モジュール)
@anchor{library/shlex shlex quote}@anchor{582}
@deffn {の関数} shlex.quote (s)

文字列 `s' をシェルエスケープして返します。戻り値は、リストを使えないようなケースで、シェルコマンドライン内で一つのトークンとして安全に利用出来る文字列です。
@anchor{library/shlex shlex-quote-warning}@anchor{3757}
@cartouche
@quotation 警告 
The @code{shlex} module is `only designed for Unix shells'.

The @ref{582,,quote()} function is not guaranteed to be correct on non-POSIX
compliant shells or shells from other operating systems such as Windows.
Executing commands quoted by this module on such shells can open up the
possibility of a command injection vulnerability.

Consider using functions that pass command arguments with lists such as
@ref{d7f,,subprocess.run()} with @code{shell=False}.
@end quotation
@end cartouche

以下のイディオムは安全ではないかもしれません:

@example
>>> filename = 'somefile; rm -rf ~'
>>> command = 'ls -l @{@}'.format(filename)
>>> print(command)  # executed by a shell: boom!
ls -l somefile; rm -rf ~
@end example

@ref{582,,quote()} がそのセキュリティホールをふさぎます:

@example
>>> from shlex import quote
>>> command = 'ls -l @{@}'.format(quote(filename))
>>> print(command)
ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home @{@}'.format(quote(command))
>>> print(remote_command)
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"'@w{'}
@end example

クォーティングは UNIX シェルならびに @ref{75e,,split()} と互換です:

@example
>>> from shlex import split
>>> remote_command = split(remote_command)
>>> remote_command
['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
>>> command = split(remote_command[-1])
>>> command
['ls', '-l', 'somefile; rm -rf ~']
@end example


Added in version 3.3.

@end deffn

The @code{shlex} module defines the following class:

@geindex shlex (shlex のクラス)
@anchor{library/shlex shlex shlex}@anchor{ec8}
@deffn {クラス} shlex.shlex (instream=None, infile=None, posix=False, punctuation_chars=False)

A @ref{ec8,,shlex} instance or subclass instance is a lexical analyzer
object.  The initialization argument, if present, specifies where to read
characters from.  It must be a file-/stream-like object with
@ref{206c,,read()} and @ref{20a6,,readline()} methods, or
a string.  If no argument is given, input will be taken from @code{sys.stdin}.
The second optional argument is a filename string, which sets the initial
value of the @ref{4daa,,infile} attribute.  If the `instream'
argument is omitted or equal to @code{sys.stdin}, this second argument
defaults to "stdin".  The `posix' argument defines the operational mode:
when `posix' is not true (default), the @ref{ec8,,shlex} instance will
operate in compatibility mode.  When operating in POSIX mode,
@ref{ec8,,shlex} will try to be as close as possible to the POSIX shell
parsing rules.  The `punctuation_chars' argument provides a way to make the
behaviour even closer to how real shells parse.  This can take a number of
values: the default value, @code{False}, preserves the behaviour seen under
Python 3.5 and earlier.  If set to @code{True}, then parsing of the characters
@code{();<>|&} is changed: any run of these characters (considered punctuation
characters) is returned as a single token.  If set to a non-empty string of
characters, those characters will be used as the punctuation characters.  Any
characters in the @ref{4dab,,wordchars} attribute that appear in
`punctuation_chars' will be removed from @ref{4dab,,wordchars}.  See
@ref{ec9,,Improved Compatibility with Shells} for more information. `punctuation_chars'
can be set only upon @ref{ec8,,shlex} instance creation and can't be
modified later.


バージョン 3.6 で変更: `punctuation_chars' 引数が追加されました。

@end deffn


@subsubheading 参考



@table @asis

@item @ref{26,,configparser} モジュール

Windows @code{.ini} ファイルに似た設定ファイルのパーザ。
@end table


@menu
* shlex オブジェクト:: 
* 解析規則:: 
* Improved Compatibility with Shells:: 

@end menu

@node shlex オブジェクト,解析規則,,shlex --- 単純な字句解析
@anchor{library/shlex id1}@anchor{4dac}@anchor{library/shlex shlex-objects}@anchor{4dad}
@subsubsection shlex オブジェクト


@ref{ec8,,shlex} インスタンスは以下のメソッドを持っています:

@geindex get_token() (shlex.shlex のメソッド)
@anchor{library/shlex shlex shlex get_token}@anchor{4dae}
@deffn {メソッド} shlex.get_token ()

トークンを一つ返します。トークンが @ref{4daf,,push_token()} で使ってスタックに積まれていた場合、トークンをスタックからポップします。そうでない場合、トークンを一つ入力ストリームから読み出します。読み出し即時にファイル終了子に遭遇した場合、 @ref{4db0,,eof} (非 POSIX モードでは空文字列 (@code{'@w{'}})、POSIX モードでは @code{None}) が返されます。
@end deffn

@geindex push_token() (shlex.shlex のメソッド)
@anchor{library/shlex shlex shlex push_token}@anchor{4daf}
@deffn {メソッド} shlex.push_token (str)

トークンスタックに引数文字列をスタックします。
@end deffn

@geindex read_token() (shlex.shlex のメソッド)
@anchor{library/shlex shlex shlex read_token}@anchor{4db1}
@deffn {メソッド} shlex.read_token ()

生 (raw) のトークンを読み出します。プッシュバックスタックを無視し、かつソースリクエストを解釈しません (通常これは便利なエントリポイントではありません。完全性のためにここで記述されています)。
@end deffn

@geindex sourcehook() (shlex.shlex のメソッド)
@anchor{library/shlex shlex shlex sourcehook}@anchor{4db2}
@deffn {メソッド} shlex.sourcehook (filename)

@ref{ec8,,shlex} がソースリクエスト (下の @ref{4db3,,source} を参照してください) を検出した際、このメソッドはその後に続くトークンを引数として渡され、ファイル名と開かれたファイル類似オブジェクトからなるタプルを返すとされています。

通常、このメソッドはまず引数から何らかのクオートを取り除きます。処理後の引数が絶対パス名であった場合か、以前に有効になったソースリクエストが存在しない場合か、以前のソースが (@code{sys.stdin} のような) ストリームであった場合、この結果はそのままにされます。そうでない場合で、処理後の引数が相対パス名の場合、ソースインクルードスタックにある直前のファイル名からディレクトリ部分が取り出され、相対パスの前の部分に追加されます (この動作は C 言語プリプロセッサにおける @code{#include "file.h"} の扱いと同様です)。

これらの操作の結果はファイル名として扱われ、タプルの最初の要素として返されます。同時にこのファイル名で @ref{316,,open()} を呼び出した結果が二つ目の要素になります (注意: インスタンス初期化のときとは引数の並びが逆になっています！)

このフックはディレクトリサーチパスや、ファイル拡張子の追加、その他の名前空間に関するハックを実装できるようにするために公開されています。 'close' フックに対応するものはありませんが、shlex インスタンスはソースリクエストされている入力ストリームが EOF を返した時には @ref{506,,close()} を呼び出します。

ソーススタックをより明示的に操作するには、 @ref{4db4,,push_source()} および @ref{4db5,,pop_source()} メソッドを使ってください。
@end deffn

@geindex push_source() (shlex.shlex のメソッド)
@anchor{library/shlex shlex shlex push_source}@anchor{4db4}
@deffn {メソッド} shlex.push_source (newstream, newfile=None)

入力ソースストリームを入力スタックにプッシュします。ファイル名引数が指定された場合、以後のエラーメッセージ中で利用することができます。 @ref{4db2,,sourcehook()} メソッドが内部で使用しているのと同じメソッドです。
@end deffn

@geindex pop_source() (shlex.shlex のメソッド)
@anchor{library/shlex shlex shlex pop_source}@anchor{4db5}
@deffn {メソッド} shlex.pop_source ()

最後にプッシュされた入力ソースを入力スタックからポップします。字句解析器がスタック上の入力ストリームの EOF に到達した際に利用するメソッドと同じです。
@end deffn

@geindex error_leader() (shlex.shlex のメソッド)
@anchor{library/shlex shlex shlex error_leader}@anchor{4db6}
@deffn {メソッド} shlex.error_leader (infile=None, lineno=None)

このメソッドはエラーメッセージの論述部分を Unix C コンパイラエラーラベルの形式で生成します; この書式は @code{'"%s", line %d: '} で、 @code{%s} は現在のソースファイル名で置き換えられ、 @code{%d} は現在の入力行番号で置き換えられます (オプションの引数を使ってこれらを上書きすることもできます)。

This convenience is provided to encourage @code{shlex} users to generate error
messages in the standard, parseable format understood by Emacs and other Unix
tools.
@end deffn

@ref{ec8,,shlex} サブクラスのインスタンスは、字句解析を制御したり、デバッグに使えるような public なインスタンス変数を持っています:

@geindex commenters (shlex.shlex の属性)
@anchor{library/shlex shlex shlex commenters}@anchor{4da9}
@deffn {の属性} shlex.commenters

コメントの開始として認識される文字列です。コメントの開始から行末までのすべてのキャラクタ文字は無視されます。標準では単に @code{'#'} が入っています。
@end deffn

@geindex wordchars (shlex.shlex の属性)
@anchor{library/shlex shlex shlex wordchars}@anchor{4dab}
@deffn {の属性} shlex.wordchars

The string of characters that will accumulate into multi-character tokens.  By
default, includes all ASCII alphanumerics and underscore.  In POSIX mode, the
accented characters in the Latin-1 set are also included.  If
@ref{1db6,,punctuation_chars} is not empty, the characters @code{~-./*?=}, which can
appear in filename specifications and command line parameters, will also be
included in this attribute, and any characters which appear in
@code{punctuation_chars} will be removed from @code{wordchars} if they are present
there. If @ref{4db7,,whitespace_split} is set to @code{True}, this will have no
effect.
@end deffn

@geindex whitespace (shlex.shlex の属性)
@anchor{library/shlex shlex shlex whitespace}@anchor{4db8}
@deffn {の属性} shlex.whitespace

空白と見なされ、読み飛ばされる文字群です。空白はトークンの境界を作ります。標準では、スペース、タブ、改行 (linefeed) および復帰 (carriage-return) が入っています。
@end deffn

@geindex escape (shlex.shlex の属性)
@anchor{library/shlex shlex shlex escape}@anchor{4db9}
@deffn {の属性} shlex.escape

エスケープ文字と見なされる文字群です。これは POSIX モードでのみ使われ、デフォルトでは @code{'\'} だけが入っています。
@end deffn

@geindex quotes (shlex.shlex の属性)
@anchor{library/shlex shlex shlex quotes}@anchor{4dba}
@deffn {の属性} shlex.quotes

文字列引用符と見なされる文字群です。トークンを構成する際、同じクオートが再び出現するまで文字をバッファに蓄積します (すなわち、異なるクオート形式はシェル中で互いに保護し合う関係にあります)。標準では、ASCII 単引用符および二重引用符が入っています。
@end deffn

@geindex escapedquotes (shlex.shlex の属性)
@anchor{library/shlex shlex shlex escapedquotes}@anchor{4dbb}
@deffn {の属性} shlex.escapedquotes

@ref{4dba,,quotes} のうち、 @ref{4db9,,escape} で定義されたエスケープ文字を解釈する文字群です。これは POSIX モードでのみ使われ、デフォルトでは @code{'"'} だけが入っています。
@end deffn

@geindex whitespace_split (shlex.shlex の属性)
@anchor{library/shlex shlex shlex whitespace_split}@anchor{4db7}
@deffn {の属性} shlex.whitespace_split

If @code{True}, tokens will only be split in whitespaces.  This is useful, for
example, for parsing command lines with @ref{ec8,,shlex}, getting
tokens in a similar way to shell arguments.  When used in combination with
@ref{1db6,,punctuation_chars}, tokens will be split on whitespace in addition to
those characters.


バージョン 3.8 で変更: The @ref{1db6,,punctuation_chars} attribute was made compatible with the
@ref{4db7,,whitespace_split} attribute.

@end deffn

@geindex infile (shlex.shlex の属性)
@anchor{library/shlex shlex shlex infile}@anchor{4daa}
@deffn {の属性} shlex.infile

現在の入力ファイル名です。クラスのインスタンス化時に初期設定されるか、その後のソースリクエストでスタックされます。エラーメッセージを構成する際にこの値を調べると便利なことがあります。
@end deffn

@geindex instream (shlex.shlex の属性)
@anchor{library/shlex shlex shlex instream}@anchor{4dbc}
@deffn {の属性} shlex.instream

@ref{ec8,,shlex} インスタンスが文字を読み出している入力ストリームです。
@end deffn

@geindex source (shlex.shlex の属性)
@anchor{library/shlex shlex shlex source}@anchor{4db3}
@deffn {の属性} shlex.source

このメンバ変数は標準で @ref{885,,None} を取ります。この値に文字列を代入すると、その文字列は多くのシェルにおける @code{source} キーワードに似た、字句解析レベルでのインクルード要求として認識されます。すなわち、その直後に現れるトークンをファイル名として新たなストリームを開き、そのストリームを入力として、EOF に到達するまで読み込まれます。新たなストリームの EOF に到達した時点で @ref{506,,close()} が呼び出され、入力は元の入力ストリームに戻されます。ソースリクエストは任意のレベルの深さまでスタックしてかまいません。
@end deffn

@geindex debug (shlex.shlex の属性)
@anchor{library/shlex shlex shlex debug}@anchor{4dbd}
@deffn {の属性} shlex.debug

このメンバ変数が数値で、かつ @code{1} またはそれ以上の値の場合、 @ref{ec8,,shlex} インスタンスは動作に関する冗長な進捗報告を出力します。この出力を使いたいなら、モジュールのソースコードを読めば詳細を学ぶことができます。
@end deffn

@geindex lineno (shlex.shlex の属性)
@anchor{library/shlex shlex shlex lineno}@anchor{4dbe}
@deffn {の属性} shlex.lineno

ソース行番号 (遭遇した改行の数に 1 を加えたもの) です。
@end deffn

@geindex token (shlex.shlex の属性)
@anchor{library/shlex shlex shlex token}@anchor{4dbf}
@deffn {の属性} shlex.token

トークンバッファです。例外を捕捉した際にこの値を調べると便利なことがあります。
@end deffn

@geindex eof (shlex.shlex の属性)
@anchor{library/shlex shlex shlex eof}@anchor{4db0}
@deffn {の属性} shlex.eof

ファイルの終端を決定するのに使われるトークンです。非 POSIX モードでは空文字列 (@code{'@w{'}}) 、POSIX モードでは @code{None} が入ります。
@end deffn

@geindex punctuation_chars (shlex.shlex の属性)
@anchor{library/shlex shlex shlex punctuation_chars}@anchor{1db6}
@deffn {の属性} shlex.punctuation_chars

A read-only property. Characters that will be considered punctuation. Runs of
punctuation characters will be returned as a single token. However, note that no
semantic validity checking will be performed: for example, '>>>' could be
returned as a token, even though it may not be recognised as such by shells.


Added in version 3.6.

@end deffn

@node 解析規則,Improved Compatibility with Shells,shlex オブジェクト,shlex --- 単純な字句解析
@anchor{library/shlex parsing-rules}@anchor{4dc0}@anchor{library/shlex shlex-parsing-rules}@anchor{4dc1}
@subsubsection 解析規則


When operating in non-POSIX mode, @ref{ec8,,shlex} will try to obey the
following rules.


@itemize *

@item 
ワード内の引用符を認識しない (@code{Do"Not"Separate} は単一ワード @code{Do"Not"Separate} として解析されます)

@item 
エスケープ文字を認識しない

@item 
引用符で囲まれた文字列は、引用符内の全ての文字リテラルを保持する

@item 
閉じ引用符でワードを区切る (@code{"Do"Separate} は、 @code{"Do"} と @code{Separate} であると解析されます)

@item 
@ref{4db7,,whitespace_split} が @code{False} の場合、wordchar、 whitespace または quote として宣言されていない全ての文字を、単一の文字トークンとして返す。 @code{True} の場合、 @ref{ec8,,shlex} は空白文字でのみ単語を区切る。

@item 
空文字列 (@code{'@w{'}}) で EOF を送出する

@item 
引用符に囲んであっても、空文字列を解析しない
@end itemize

When operating in POSIX mode, @ref{ec8,,shlex} will try to obey the
following parsing rules.


@itemize *

@item 
引用符を取り除き、引用符で単語を分解しない (@code{"Do"Not"Separate"} は単一ワード @code{DoNotSeparate} として解析されます)

@item 
引用符で囲まれないエスケープ文字群 (@code{'\'} など) は直後に続く文字のリテラル値を保持する

@item 
@ref{4dbb,,escapedquotes} でない引用符文字 (@code{"'"} など) で囲まれている全ての文字のリテラル値を保持する

@item 
Enclosing characters in quotes which are part of
@ref{4dbb,,escapedquotes} (e.g. @code{'"'}) preserves the literal value
of all characters within the quotes, with the exception of the characters
mentioned in @ref{4db9,,escape}.  The escape characters retain their
special meaning only when followed by the quote in use, or the escape
character itself. Otherwise the escape character will be considered a
normal character.

@item 
@ref{885,,None} で EOF を送出する

@item 
引用符に囲まれた空文字列 (@code{'@w{'}}) を許す。
@end itemize

@node Improved Compatibility with Shells,,解析規則,shlex --- 単純な字句解析
@anchor{library/shlex improved-compatibility-with-shells}@anchor{4dc2}@anchor{library/shlex improved-shell-compatibility}@anchor{ec9}
@subsubsection Improved Compatibility with Shells



Added in version 3.6.


The @ref{c9,,shlex} class provides compatibility with the parsing performed by
common Unix shells like @code{bash}, @code{dash}, and @code{sh}.  To take advantage of
this compatibility, specify the @code{punctuation_chars} argument in the
constructor.  This defaults to @code{False}, which preserves pre-3.6 behaviour.
However, if it is set to @code{True}, then parsing of the characters @code{();<>|&}
is changed: any run of these characters is returned as a single token.  While
this is short of a full parser for shells (which would be out of scope for the
standard library, given the multiplicity of shells out there), it does allow
you to perform processing of command lines more easily than you could
otherwise.  To illustrate, you can see the difference in the following snippet:

@example
>>> import shlex
>>> text = "a && b; c && d || e; f >'abc'; (def \"ghi\")"
>>> s = shlex.shlex(text, posix=True)
>>> s.whitespace_split = True
>>> list(s)
['a', '&&', 'b;', 'c', '&&', 'd', '||', 'e;', 'f', '>abc;', '(def', 'ghi)']
>>> s = shlex.shlex(text, posix=True, punctuation_chars=True)
>>> s.whitespace_split = True
>>> list(s)
['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', 'abc', ';',
'(', 'def', 'ghi', ')']
@end example

Of course, tokens will be returned which are not valid for shells, and you'll
need to implement your own error checks on the returned tokens.

Instead of passing @code{True} as the value for the punctuation_chars parameter,
you can pass a string with specific characters, which will be used to determine
which characters constitute punctuation. For example:

@example
>>> import shlex
>>> s = shlex.shlex("a && b || c", punctuation_chars="|")
>>> list(s)
['a', '&', '&', 'b', '||', 'c']
@end example

@cartouche
@quotation 注釈 
When @code{punctuation_chars} is specified, the @ref{4dab,,wordchars}
attribute is augmented with the characters @code{~-./*?=}.  That is because these
characters can appear in file names (including wildcards) and command-line
arguments (e.g. @code{--color=auto}). Hence:

@example
>>> import shlex
>>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?',
...                 punctuation_chars=True)
>>> list(s)
['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?']
@end example

However, to match the shell as closely as possible, it is recommended to
always use @code{posix} and @ref{4db7,,whitespace_split} when using
@ref{1db6,,punctuation_chars}, which will negate
@ref{4dab,,wordchars} entirely.
@end quotation
@end cartouche

For best effect, @code{punctuation_chars} should be set in conjunction with
@code{posix=True}. (Note that @code{posix=False} is the default for
@ref{ec8,,shlex}.)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node posix --- 最も一般的な POSIX システムコール群,pwd --- パスワードデータベース,shlex --- 単純な字句解析,Unix-specific services
@anchor{library/posix doc}@anchor{4dc3}@anchor{library/posix module-posix}@anchor{b2}@anchor{library/posix posix-the-most-common-posix-system-calls}@anchor{4dc4}@anchor{library/posix translation-repo}@anchor{4dc5}
@subsection @code{posix} --- 最も一般的な POSIX システムコール群


@geindex module; posix


__________________________________________________________________


このモジュールはオペレーティングシステムの機能のうち、C 言語標準および  (Unix インターフェースをほんの少し隠蔽した) POSIX 標準で標準化されている機能に対するアクセス機構を提供します。

@ref{213f,,Availability}: Unix.

@geindex module;os

`Do not import this module directly.'  Instead, import the module @ref{a5,,os},
which provides a `portable' version of this interface.  On Unix, the @ref{a5,,os}
module provides a superset of the @code{posix} interface.  On non-Unix operating
systems the @code{posix} module is not available, but a subset is always
available through the @ref{a5,,os} interface.  Once @ref{a5,,os} is imported, there is
`no' performance penalty in using it instead of @code{posix}.  In addition,
@ref{a5,,os} provides some additional functionality, such as automatically calling
@ref{25b,,putenv()} when an entry in @code{os.environ} is changed.

エラーは例外として報告されます; よくある例外は型エラーです。一方、システムコールから報告されたエラーは以下に述べるように @ref{2c0,,OSError} を送出します。

@menu
* ラージファイルのサポート:: 
* 注目すべきモジュールの内容:: 

@end menu

@node ラージファイルのサポート,注目すべきモジュールの内容,,posix --- 最も一般的な POSIX システムコール群
@anchor{library/posix large-file-support}@anchor{4dc6}@anchor{library/posix posix-large-files}@anchor{4dc7}
@subsubsection ラージファイルのサポート


@geindex large files
@geindex ファイル;large files

いくつかのオペレーティングシステム (AIX および Solaris が含まれます) は、 int および long を 32 ビット値とする C プログラムモデルで 2GB を超えるサイズのファイルのサポートを提供しています。このサポートは典型的には関連するサイズとオフセットの組合せを 64-bit 値として定義することで実現しています。このようなファイルは時にラージファイル (`large files') と呼ばれます。

Python では、 @code{off_t} のサイズが long より大きく、かつ long long が少なくとも @code{off_t} と同じくらい大きなサイズであるとき、ラージファイルのサポートが有効になります。
この場合、ファイルのサイズ、オフセットおよび Python の通常整数型の範囲を超えるような値の表現には Python の長整数型が使われます。
このモードを有効にするのに、 @code{configure} で Python のコンパイルに特定のコンパイルフラグを必要とするかもしれません。
例えば、Solaris 2.6 および 2.7 では、以下のようにする必要があります:

@example
CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \
        ./configure
@end example

ラージファイル対応の Linux システムでは、以下のようにすれば良いでしょう:

@example
CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \
        ./configure
@end example

@node 注目すべきモジュールの内容,,ラージファイルのサポート,posix --- 最も一般的な POSIX システムコール群
@anchor{library/posix notable-module-contents}@anchor{4dc8}@anchor{library/posix posix-contents}@anchor{4dc9}
@subsubsection 注目すべきモジュールの内容


In addition to many functions described in the @ref{a5,,os} module documentation,
@code{posix} defines the following data item:

@geindex environ (posix モジュール)
@anchor{library/posix posix environ}@anchor{4dca}
@deffn {データ} posix.environ

インタプリタが起動したときの環境を表す文字列辞書です。キーと値は Unix ではバイト列、 Windows では文字列です。例えば、 @code{environ[b'HOME']} (Windows では @code{environ['HOME']}) はホームディレクトリのパス名で、 C の @code{getenv("HOME")} と同じ値です。

この辞書を編集しても、 @ref{3019,,execv()} 、 @ref{31a,,popen()} 、 @ref{1676,,system()} で渡された環境変数文字列には影響は与えません; 環境変数を変更したい場合は、 @code{environ} を @ref{1311,,execve()} に渡すか、変数への代入文と export 文を @ref{1676,,system()} や @ref{31a,,popen()} に渡すコマンド文字列に追加してください。


バージョン 3.2 で変更: Unix ではキーと値はバイト列になりました。


@cartouche
@quotation 注釈 
The @ref{a5,,os} module provides an alternate implementation of @code{environ}
which updates the environment on modification. Note also that updating
@ref{259,,os.environ} will render this dictionary obsolete. Use of the
@ref{a5,,os} module version of this is recommended over direct access to the
@code{posix} module.
@end quotation
@end cartouche
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pwd --- パスワードデータベース,grp --- グループデータベース,posix --- 最も一般的な POSIX システムコール群,Unix-specific services
@anchor{library/pwd doc}@anchor{4dcb}@anchor{library/pwd module-pwd}@anchor{b7}@anchor{library/pwd pwd-the-password-database}@anchor{4dcc}@anchor{library/pwd translation-repo}@anchor{4dcd}
@subsection @code{pwd} --- パスワードデータベース


@geindex module; pwd


__________________________________________________________________


このモジュールは Unix のユーザアカウントとパスワードのデータベースへのアクセスを提供します。全ての Unix 系 OS で利用できます。

@ref{213f,,Availability}: Unix, not WASI, not iOS.

パスワードデータベースの各エントリはタプルのようなオブジェクトで提供され、それぞれの属性は @code{passwd} 構造体のメンバに対応しています(下の属性欄については、@code{<pwd.h>} を見てください):


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

属性

@tab

意味

@item

0

@tab

@code{pw_name}

@tab

ログイン名

@item

1

@tab

@code{pw_passwd}

@tab

暗号化されたパスワード(optional))

@item

2

@tab

@code{pw_uid}

@tab

ユーザID(UID)

@item

3

@tab

@code{pw_gid}

@tab

グループID(GID)

@item

4

@tab

@code{pw_gecos}

@tab

実名またはコメント

@item

5

@tab

@code{pw_dir}

@tab

ホームディレクトリ

@item

6

@tab

@code{pw_shell}

@tab

シェル

@end multitable


UIDとGIDは整数で、それ以外は全て文字列です。検索したエントリが見つからないと @ref{5e7,,KeyError} が発生します。

@cartouche
@quotation 注釈 
伝統的なUnixでは、 @code{pw_passwd} フィールドはDES由来のアルゴリズムで暗号化されたパスワードが含まれています。しかし、近代的なUNIX系OSでは `シャドウパスワード' とよばれる仕組みを利用しています。この場合には `pw_passwd' フィールドにはアスタリスク(@code{'*'})か、 @code{'x'} という一文字だけが含まれており、暗号化されたパスワードは、一般には見えない @code{/etc/shadow} というファイルに入っています。 `pw_passwd' フィールドに有用な値が入っているかはシステムに依存します。
@end quotation
@end cartouche

このモジュールでは以下の内容を定義しています:

@geindex getpwuid() (pwd モジュール)
@anchor{library/pwd pwd getpwuid}@anchor{1e12}
@deffn {の関数} pwd.getpwuid (uid)

与えられたUIDに対応するパスワードデータベースのエントリを返します。
@end deffn

@geindex getpwnam() (pwd モジュール)
@anchor{library/pwd pwd getpwnam}@anchor{3747}
@deffn {の関数} pwd.getpwnam (name)

与えられたユーザ名に対応するパスワードデータベースのエントリを返します。
@end deffn

@geindex getpwall() (pwd モジュール)
@anchor{library/pwd pwd getpwall}@anchor{4dce}
@deffn {の関数} pwd.getpwall ()

パスワードデータベースの全てのエントリを、任意の順番で並べたリストを返します。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{6a,,grp} モジュール

このモジュールに似た、グループデータベースへのアクセスを提供するモジュール。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node grp --- グループデータベース,termios --- POSIX スタイルの端末制御,pwd --- パスワードデータベース,Unix-specific services
@anchor{library/grp doc}@anchor{4dcf}@anchor{library/grp grp-the-group-database}@anchor{4dd0}@anchor{library/grp module-grp}@anchor{6a}@anchor{library/grp translation-repo}@anchor{4dd1}
@subsection @code{grp} --- グループデータベース


@geindex module; grp


__________________________________________________________________


このモジュールでは Unix グループ (group) データベースへのアクセス機構を提供します。全ての Unix バージョンで利用可能です。

@ref{213f,,Availability}: Unix, not WASI, not Android, not iOS.

このモジュールはグループデータベースのエントリをタプルに似たオブジェクトとして報告されます。このオブジェクトの属性は @code{group} 構造体の各メンバ (以下の属性フィールド、@code{<grp.h>} を参照) に対応します:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

属性

@tab

意味

@item

0

@tab

gr_name

@tab

グループ名

@item

1

@tab

gr_passwd

@tab

(暗号化された) グループパスワード; しばしば空文字列になります

@item

2

@tab

gr_gid

@tab

数字のグループ ID

@item

3

@tab

gr_mem

@tab

グループメンバの全てのユーザ名

@end multitable


gid は整数、名前およびパスワードは文字列、そしてメンバリストは文字列からなるリストです。 (ほとんどのユーザは、パスワードデータベースで自分が入れられているグループのメンバとしてグループデータベース内では明示的に列挙されていないので注意してください。完全なメンバ情報を取得するには両方のデータベースを調べてください。また、 @code{+} や @code{-} で始まる @code{gr_name} は YP/NIS 参照である可能性があり、 @ref{3746,,getgrnam()} や @ref{f22,,getgrgid()} でアクセスできないかもしれないことにも注意してください。)

このモジュールでは以下の内容を定義しています:

@geindex getgrgid() (grp モジュール)
@anchor{library/grp grp getgrgid}@anchor{f22}
@deffn {の関数} grp.getgrgid (id)

与えられたグループ ID に対するグループデータベースエントリを返します。要求したエントリが見つからなかった場合、 @ref{5e7,,KeyError} が送出されます。


バージョン 3.10 で変更: 浮動小数点数や文字列のような、整数でない引数には @ref{198,,TypeError} が送出されます。

@end deffn

@geindex getgrnam() (grp モジュール)
@anchor{library/grp grp getgrnam}@anchor{3746}
@deffn {の関数} grp.getgrnam (name)

与えられたグループ名に対するグループデータベースエントリを返します。要求したエントリが見つからなかった場合、 @ref{5e7,,KeyError} が送出されます。
@end deffn

@geindex getgrall() (grp モジュール)
@anchor{library/grp grp getgrall}@anchor{18e9}
@deffn {の関数} grp.getgrall ()

全ての入手可能なグループエントリを返します。順番は決まっていません。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{b7,,pwd} モジュール

このモジュールと類似の、ユーザデータベースへのインターフェース。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node termios --- POSIX スタイルの端末制御,tty --- 端末制御用の関数群,grp --- グループデータベース,Unix-specific services
@anchor{library/termios doc}@anchor{4dd2}@anchor{library/termios module-termios}@anchor{e7}@anchor{library/termios termios-posix-style-tty-control}@anchor{4dd3}@anchor{library/termios translation-repo}@anchor{4dd4}
@subsection @code{termios} --- POSIX スタイルの端末制御


@geindex module; termios

@geindex POSIX;I/O control
@geindex tty;I/O control


__________________________________________________________________


このモジュールでは端末 I/O 制御のための POSIX 準拠の関数呼び出しインターフェースを提供します。これら呼び出しのための完全な記述については、 Unix マニュアルページの @code{termios(3)@footnote{https://manpages.debian.org/termios(3)}} を参照してください。これは POSIX `termios' 形式の端末制御をサポートしていてインストール時に有効にした Unix のバージョンでのみ利用可能です。

@ref{213f,,Availability}: Unix.

このモジュールの関数は全て、ファイル記述子 `fd' を最初の引数としてとります。この値は、 @code{sys.stdin.fileno()} が返すような整数のファイル記述子でも、 @code{sys.stdin} 自体のような @ref{13db,,file object} でもかまいません。

このモジュールではまた、モジュールで提供されている関数を使う上で必要となる全ての定数を定義しています; これらの定数は C の対応する関数と同じ名前を持っています。これらの端末制御インターフェースを利用する上でのさらなる情報については、あなたのシステムのドキュメンテーションを参考にしてください。

このモジュールには、以下の関数が定義されています:

@geindex tcgetattr() (termios モジュール)
@anchor{library/termios termios tcgetattr}@anchor{19f3}
@deffn {の関数} termios.tcgetattr (fd)

Return a list containing the tty attributes for file descriptor `fd', as
follows: @code{[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]} where `cc' is a
list of the tty special characters (each a string of length 1, except the
items with indices @code{VMIN} and @code{VTIME}, which are integers when
these fields are defined).  The interpretation of the flags and the speeds as
well as the indexing in the `cc' array must be done using the symbolic
constants defined in the @code{termios} module.
@end deffn

@geindex tcsetattr() (termios モジュール)
@anchor{library/termios termios tcsetattr}@anchor{1a69}
@deffn {の関数} termios.tcsetattr (fd, when, attributes)

Set the tty attributes for file descriptor `fd' from the `attributes', which is
a list like the one returned by @ref{19f3,,tcgetattr()}.  The `when' argument
determines when the attributes are changed:

@geindex TCSANOW (termios モジュール)
@anchor{library/termios termios TCSANOW}@anchor{4dd5}
@deffn {データ} termios.TCSANOW

Change attributes immediately.
@end deffn

@geindex TCSADRAIN (termios モジュール)
@anchor{library/termios termios TCSADRAIN}@anchor{4dd6}
@deffn {データ} termios.TCSADRAIN

Change attributes after transmitting all queued output.
@end deffn

@geindex TCSAFLUSH (termios モジュール)
@anchor{library/termios termios TCSAFLUSH}@anchor{4dd7}
@deffn {データ} termios.TCSAFLUSH

Change attributes after transmitting all queued output and
discarding all queued input.
@end deffn
@end deffn

@geindex tcsendbreak() (termios モジュール)
@anchor{library/termios termios tcsendbreak}@anchor{4dd8}
@deffn {の関数} termios.tcsendbreak (fd, duration)

ファイル記述子 `fd' にブレークを送信します。`duration' をゼロにすると、0.25〜0.5 秒間のブレークを送信します; `duration' の値がゼロでない場合、その意味はシステム依存です。
@end deffn

@geindex tcdrain() (termios モジュール)
@anchor{library/termios termios tcdrain}@anchor{4dd9}
@deffn {の関数} termios.tcdrain (fd)

ファイル記述子 `fd' に書き込まれた全ての出力が転送されるまで待ちます。
@end deffn

@geindex tcflush() (termios モジュール)
@anchor{library/termios termios tcflush}@anchor{4dda}
@deffn {の関数} termios.tcflush (fd, queue)

ファイル記述子 `fd' にキューされたデータを無視します。どのキューかは `queue' セレクタで指定します: @code{TCIFLUSH} は入力キュー、 @code{TCOFLUSH} は出力キュー、 @code{TCIOFLUSH} は両方のキューです。
@end deffn

@geindex tcflow() (termios モジュール)
@anchor{library/termios termios tcflow}@anchor{4ddb}
@deffn {の関数} termios.tcflow (fd, action)

ファイル記述子 `fd' の入力または出力をサスペンドしたりレジュームしたりします。引数 `action' は出力をサスペンドする @code{TCOOFF} 、出力をレジュームする @code{TCOON} 、入力をサスペンドする @code{TCIOFF} 、入力をレジュームする @code{TCION} をとることができます。
@end deffn

@geindex tcgetwinsize() (termios モジュール)
@anchor{library/termios termios tcgetwinsize}@anchor{4ddc}
@deffn {の関数} termios.tcgetwinsize (fd)

Return a tuple @code{(ws_row, ws_col)} containing the tty window size for file
descriptor `fd'. Requires @code{termios.TIOCGWINSZ} or
@code{termios.TIOCGSIZE}.


Added in version 3.11.

@end deffn

@geindex tcsetwinsize() (termios モジュール)
@anchor{library/termios termios tcsetwinsize}@anchor{4ddd}
@deffn {の関数} termios.tcsetwinsize (fd, winsize)

Set the tty window size for file descriptor `fd' from `winsize', which is
a two-item tuple @code{(ws_row, ws_col)} like the one returned by
@ref{4ddc,,tcgetwinsize()}. Requires at least one of the pairs
(@code{termios.TIOCGWINSZ}, @code{termios.TIOCSWINSZ});
(@code{termios.TIOCGSIZE}, @code{termios.TIOCSSIZE}) to be defined.


Added in version 3.11.

@end deffn


@subsubheading 参考



@table @asis

@item @ref{106,,tty} モジュール

一般的な端末制御操作のための便利な関数。
@end table


@menu
* 使用例: 使用例<51>. 

@end menu

@node 使用例<51>,,,termios --- POSIX スタイルの端末制御
@anchor{library/termios example}@anchor{4dde}@anchor{library/termios termios-example}@anchor{4ddf}
@subsubsection 使用例


以下はエコーバックを切った状態でパスワード入力を促す関数です。ユーザの入力に関わらず以前の端末属性を正確に回復するために、二つの @ref{19f3,,tcgetattr()} と @ref{8f8,,try} ... @ref{1b0,,finally} 文によるテクニックが使われています:

@example
def getpass(prompt="Password: "):
    import termios, sys
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        passwd = input(prompt)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return passwd
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node tty --- 端末制御用の関数群,pty --- 擬似端末ユーティリティ,termios --- POSIX スタイルの端末制御,Unix-specific services
@anchor{library/tty doc}@anchor{4de0}@anchor{library/tty module-tty}@anchor{106}@anchor{library/tty translation-repo}@anchor{4de1}@anchor{library/tty tty-terminal-control-functions}@anchor{4de2}
@subsection @code{tty} --- 端末制御用の関数群


@geindex module; tty

`ソースコード:' Lib/tty.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/tty.py}


__________________________________________________________________


The @code{tty} module defines functions for putting the tty into cbreak and raw
modes.

@ref{213f,,Availability}: Unix.

このモジュールは @ref{e7,,termios} モジュールを必要とするため、 Unix でしか動作しません。

The @code{tty} module defines the following functions:

@geindex cfmakeraw() (tty モジュール)
@anchor{library/tty tty cfmakeraw}@anchor{1a42}
@deffn {の関数} tty.cfmakeraw (mode)

Convert the tty attribute list `mode', which is a list like the one returned
by @ref{19f3,,termios.tcgetattr()}, to that of a tty in raw mode.


Added in version 3.12.

@end deffn

@geindex cfmakecbreak() (tty モジュール)
@anchor{library/tty tty cfmakecbreak}@anchor{19f6}
@deffn {の関数} tty.cfmakecbreak (mode)

Convert the tty attribute list `mode', which is a list like the one returned
by @ref{19f3,,termios.tcgetattr()}, to that of a tty in cbreak mode.

This clears the @code{ECHO} and @code{ICANON} local mode flags in `mode' as well
as setting the minimum input to 1 byte with no delay.


Added in version 3.12.



バージョン 3.12.2 で変更: The @code{ICRNL} flag is no longer cleared. This matches Linux and macOS
@code{stty cbreak} behavior and what @ref{19f5,,setcbreak()} historically did.

@end deffn

@geindex setraw() (tty モジュール)
@anchor{library/tty tty setraw}@anchor{1a41}
@deffn {の関数} tty.setraw (fd, when=termios.TCSAFLUSH)

Change the mode of the file descriptor `fd' to raw. If `when' is omitted, it
defaults to @ref{4dd7,,termios.TCSAFLUSH}, and is passed to
@ref{1a69,,termios.tcsetattr()}. The return value of @ref{19f3,,termios.tcgetattr()}
is saved before setting `fd' to raw mode; this value is returned.


バージョン 3.12 で変更: The return value is now the original tty attributes, instead of @code{None}.

@end deffn

@geindex setcbreak() (tty モジュール)
@anchor{library/tty tty setcbreak}@anchor{19f5}
@deffn {の関数} tty.setcbreak (fd, when=termios.TCSAFLUSH)

Change the mode of file descriptor `fd' to cbreak. If `when' is omitted, it
defaults to @ref{4dd7,,termios.TCSAFLUSH}, and is passed to
@ref{1a69,,termios.tcsetattr()}. The return value of @ref{19f3,,termios.tcgetattr()}
is saved before setting `fd' to cbreak mode; this value is returned.

This clears the @code{ECHO} and @code{ICANON} local mode flags as well as setting
the minimum input to 1 byte with no delay.


バージョン 3.12 で変更: The return value is now the original tty attributes, instead of @code{None}.



バージョン 3.12.2 で変更: The @code{ICRNL} flag is no longer cleared. This restores the behavior
of Python 3.11 and earlier as well as matching what Linux, macOS, & BSDs
describe in their @code{stty(1)} man pages regarding cbreak mode.

@end deffn


@subsubheading 参考



@table @asis

@item モジュール @ref{e7,,termios}

低水準端末制御インターフェース。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pty --- 擬似端末ユーティリティ,fcntl --- fcntl および ioctl システムコール,tty --- 端末制御用の関数群,Unix-specific services
@anchor{library/pty doc}@anchor{4de3}@anchor{library/pty module-pty}@anchor{b6}@anchor{library/pty pty-pseudo-terminal-utilities}@anchor{4de4}@anchor{library/pty translation-repo}@anchor{4de5}
@subsection @code{pty} --- 擬似端末ユーティリティ


@geindex module; pty

`ソースコード:' Lib/pty.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/pty.py}


__________________________________________________________________


The @code{pty} module defines operations for handling the pseudo-terminal
concept: starting another process and being able to write to and read from its
controlling terminal programmatically.

@ref{213f,,Availability}: Unix.

Pseudo-terminal handling is highly platform dependent. This code is mainly
tested on Linux, FreeBSD, and macOS (it is supposed to work on other POSIX
platforms but it's not been thoroughly tested).

The @code{pty} module defines the following functions:

@geindex fork() (pty モジュール)
@anchor{library/pty pty fork}@anchor{1ac9}
@deffn {の関数} pty.fork ()

forkします。子プロセスの制御端末を擬似端末に接続します。返り値は @code{(pid, fd)} です。子プロセスは `pid' として0、`fd' として `invalid' をそれぞれ受けとります。親プロセスは `pid' として子プロセスのPID、`fd' として子プロセスの制御端末 (子プロセスの標準入出力に接続されている)のファイル記述子を受けとります。

@cartouche
@quotation 警告 
On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using @ref{111,,urllib.request}.
@end quotation
@end cartouche
@end deffn

@geindex openpty() (pty モジュール)
@anchor{library/pty pty openpty}@anchor{301}
@deffn {の関数} pty.openpty ()

新しい擬似端末のペアを開きます。利用できるなら @ref{305a,,os.openpty()} を使い、利用できなければ一般的なUnixシステム用のエミュレーションコードを使います。マスター、スレーブそれぞれのためのファイル記述子、 @code{(master, slave)} のタプルを返します。
@end deffn

@geindex spawn() (pty モジュール)
@anchor{library/pty pty spawn}@anchor{1184}
@deffn {の関数} pty.spawn (argv[, master_read[, stdin_read]])

Spawn a process, and connect its controlling terminal with the current
process's standard io. This is often used to baffle programs which insist on
reading from the controlling terminal. It is expected that the process
spawned behind the pty will eventually terminate, and when it does `spawn'
will return.

A loop copies STDIN of the current process to the child and data received
from the child to STDOUT of the current process. It is not signaled to the
child if STDIN of the current process closes down.

The functions `master_read' and `stdin_read' are passed a file descriptor
which they should read from, and they should always return a byte string. In
order to force spawn to return before the child process exits an
empty byte array should be returned to signal end of file.

The default implementation for both functions will read and return up to 1024
bytes each time the function is called. The `master_read' callback is passed
the pseudoterminal’s master file descriptor to read output from the child
process, and `stdin_read' is passed file descriptor 0, to read from the
parent process's standard input.

Returning an empty byte string from either callback is interpreted as an
end-of-file (EOF) condition, and that callback will not be called after
that. If `stdin_read' signals EOF the controlling terminal can no longer
communicate with the parent process OR the child process. Unless the child
process will quit without any input, `spawn' will then loop forever. If
`master_read' signals EOF the same behavior results (on linux at least).

Return the exit status value from @ref{f9a,,os.waitpid()} on the child process.

@ref{b17,,os.waitstatus_to_exitcode()} can be used to convert the exit status into
an exit code.

引数 @code{argv} を指定して @ref{1c6e,,監査イベント} @code{pty.spawn} を送出します。


バージョン 3.4 で変更: @ref{1184,,spawn()} が @ref{f9a,,os.waitpid()} が返す子プロセスのステータス値を返すようになりました。

@end deffn

@menu
* 使用例: 使用例<52>. 

@end menu

@node 使用例<52>,,,pty --- 擬似端末ユーティリティ
@anchor{library/pty example}@anchor{4de6}
@subsubsection 使用例


下記のプログラムは Unix コマンド @code{script(1)@footnote{https://manpages.debian.org/script(1)}} のように動作します。疑似端末を使用して、端末セッションのすべての入出力を "typescript" に記録します。

@example
import argparse
import os
import pty
import sys
import time

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='append', action='store_true')
parser.add_argument('-p', dest='use_python', action='store_true')
parser.add_argument('filename', nargs='?', default='typescript')
options = parser.parse_args()

shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
filename = options.filename
mode = 'ab' if options.append else 'wb'

with open(filename, mode) as script:
    def read(fd):
        data = os.read(fd, 1024)
        script.write(data)
        return data

    print('Script started, file is', filename)
    script.write(('Script started on %s\n' % time.asctime()).encode())

    pty.spawn(shell, read)

    script.write(('Script done on %s\n' % time.asctime()).encode())
    print('Script done, file is', filename)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node fcntl --- fcntl および ioctl システムコール,resource --- リソース使用情報,pty --- 擬似端末ユーティリティ,Unix-specific services
@anchor{library/fcntl doc}@anchor{4de7}@anchor{library/fcntl fcntl-the-fcntl-and-ioctl-system-calls}@anchor{4de8}@anchor{library/fcntl module-fcntl}@anchor{5d}@anchor{library/fcntl translation-repo}@anchor{4de9}
@subsection @code{fcntl} --- @code{fcntl} および @code{ioctl} システムコール


@geindex module; fcntl

@geindex UNIX;file control
@geindex UNIX;I/O control


__________________________________________________________________


This module performs file and I/O control on file descriptors. It is an
interface to the @code{fcntl()} and @code{ioctl()} Unix routines.
See the @code{fcntl(2)@footnote{https://manpages.debian.org/fcntl(2)}} and @code{ioctl(2)@footnote{https://manpages.debian.org/ioctl(2)}} Unix manual pages
for full details.

@ref{213f,,Availability}: Unix, not WASI.

このモジュール内の全ての関数はファイル記述子 `fd' を最初の引数に取ります。 この値は @code{sys.stdin.fileno()} が返すような整数のファイル記述子でも、 @code{sys.stdin} 自体のような、純粋にファイル記述子だけを返す @ref{17ad,,fileno()} メソッドを提供している @ref{505,,io.IOBase}  オブジェクトでもかまいません。


バージョン 3.3 で変更: 以前は @ref{125e,,IOError} を送出していたこのモジュールの操作が、 @ref{2c0,,OSError} を送出するようになりました。



バージョン 3.8 で変更: The @code{fcntl} module now contains @code{F_ADD_SEALS}, @code{F_GET_SEALS}, and
@code{F_SEAL_*} constants for sealing of @ref{bfe,,os.memfd_create()} file
descriptors.



バージョン 3.9 で変更: On macOS, the @code{fcntl} module exposes the @code{F_GETPATH} constant,
which obtains the path of a file from a file descriptor.
On Linux(>=3.15), the @code{fcntl} module exposes the @code{F_OFD_GETLK},
@code{F_OFD_SETLK} and @code{F_OFD_SETLKW} constants, which are used when working
with open file description locks.



バージョン 3.10 で変更: On Linux >= 2.6.11, the @code{fcntl} module exposes the @code{F_GETPIPE_SZ} and
@code{F_SETPIPE_SZ} constants, which allow to check and modify a pipe's size
respectively.



バージョン 3.11 で変更: On FreeBSD, the @code{fcntl} module exposes the @code{F_DUP2FD} and
@code{F_DUP2FD_CLOEXEC} constants, which allow to duplicate a file descriptor,
the latter setting @code{FD_CLOEXEC} flag in addition.



バージョン 3.12 で変更: On Linux >= 4.5, the @code{fcntl} module exposes the @code{FICLONE} and
@code{FICLONERANGE} constants, which allow to share some data of one file with
another file by reflinking on some filesystems (e.g., btrfs, OCFS2, and
XFS). This behavior is commonly referred to as "copy-on-write".



バージョン 3.13 で変更: On Linux >= 2.6.32, the @code{fcntl} module exposes the
@code{F_GETOWN_EX}, @code{F_SETOWN_EX}, @code{F_OWNER_TID}, @code{F_OWNER_PID}, @code{F_OWNER_PGRP} constants, which allow to direct I/O availability signals
to a specific thread, process, or process group.
On Linux >= 4.13, the @code{fcntl} module exposes the
@code{F_GET_RW_HINT}, @code{F_SET_RW_HINT}, @code{F_GET_FILE_RW_HINT},
@code{F_SET_FILE_RW_HINT}, and @code{RWH_WRITE_LIFE_*} constants, which allow
to inform the kernel about the relative expected lifetime of writes on
a given inode or via a particular open file description.
On Linux >= 5.1 and NetBSD, the @code{fcntl} module exposes the
@code{F_SEAL_FUTURE_WRITE} constant for use with @code{F_ADD_SEALS} and
@code{F_GET_SEALS} operations.
On FreeBSD, the @code{fcntl} module exposes the @code{F_READAHEAD}, @code{F_ISUNIONSTACK}, and @code{F_KINFO} constants.
On macOS and FreeBSD, the @code{fcntl} module exposes the @code{F_RDAHEAD}
constant.
On NetBSD and AIX, the @code{fcntl} module exposes the @code{F_CLOSEM}
constant.
On NetBSD, the @code{fcntl} module exposes the @code{F_MAXFD} constant.
On macOS and NetBSD, the @code{fcntl} module exposes the @code{F_GETNOSIGPIPE}
and @code{F_SETNOSIGPIPE} constant.



バージョン 3.14 で変更: On Linux >= 6.1, the @code{fcntl} module exposes the @code{F_DUPFD_QUERY}
to query a file descriptor pointing to the same file.


このモジュールには、以下の関数が定義されています:

@geindex fcntl() (fcntl モジュール)
@anchor{library/fcntl fcntl fcntl}@anchor{1851}
@deffn {の関数} fcntl.fcntl (fd, cmd, arg=0, /)

Perform the operation `cmd' on file descriptor `fd' (file objects providing
a @ref{17ad,,fileno()} method are accepted as well).  The values used
for `cmd' are operating system dependent, and are available as constants
in the @code{fcntl} module, using the same names as used in the relevant C
header files. The argument `arg' can either be an integer value, a
@ref{193,,bytes-like object}, or a string.
The type and size of `arg' must match the type and size of
the argument of the operation as specified in the relevant C documentation.

When `arg' is an integer, the function returns the integer
return value of the C @code{fcntl()} call.

When the argument is bytes-like object, it represents a binary structure,
for example, created by @ref{148e,,struct.pack()}.
A string value is encoded to binary using the UTF-8 encoding.
The binary data is copied to a buffer whose address is
passed to the C @code{fcntl()} call.  The return value after a successful
call is the contents of the buffer, converted to a @ref{192,,bytes} object.
The length of the returned object will be the same as the length of the
`arg' argument. This is limited to 1024 bytes.

If the @code{fcntl()} call fails, an @ref{2c0,,OSError} is raised.

@cartouche
@quotation 注釈 
If the type or the size of `arg' does not match the type or size
of the argument of the operation (for example, if an integer is
passed when a pointer is expected, or the information returned in
the buffer by the operating system is larger than 1024 bytes),
this is most likely to result in a segmentation violation or
a more subtle data corruption.
@end quotation
@end cartouche

引数 @code{fd}, @code{cmd}, @code{arg} を指定して @ref{1c6e,,監査イベント} @code{fcntl.fcntl} を送出します。


バージョン 3.14 で変更: Add support of arbitrary @ref{193,,bytes-like objects},
not only @ref{192,,bytes}.

@end deffn

@geindex ioctl() (fcntl モジュール)
@anchor{library/fcntl fcntl ioctl}@anchor{1694}
@deffn {の関数} fcntl.ioctl (fd, request, arg=0, mutate_flag=True, /)

この関数は @ref{1851,,fcntl()} 関数と同じですが、引数の扱いがより複雑であるところが異なります。

The `request' parameter is limited to values that can fit in 32-bits
or 64-bits, depending on the platform.
Additional constants of interest for use as the `request' argument can be
found in the @ref{e7,,termios} module, under the same names as used in
the relevant C header files.

The parameter `arg' can be an integer, a @ref{193,,bytes-like object},
or a string.
The type and size of `arg' must match the type and size of
the argument of the operation as specified in the relevant C documentation.

If `arg' does not support the read-write buffer interface or
the `mutate_flag' is false, behavior is as for the @ref{1851,,fcntl()}
function.

If `arg' supports the read-write buffer interface (like @ref{344,,bytearray})
and `mutate_flag' is true (the default), then the buffer is (in effect) passed
to the underlying @code{ioctl()} system call, the latter's return code is
passed back to the calling Python, and the buffer's new contents reflect the
action of the @code{ioctl()}.  This is a slight simplification, because if the
supplied buffer is less than 1024 bytes long it is first copied into a static
buffer 1024 bytes long which is then passed to @ref{1694,,ioctl()} and copied back
into the supplied buffer.

If the @code{ioctl()} call fails, an @ref{2c0,,OSError} exception is raised.

@cartouche
@quotation 注釈 
If the type or size of `arg' does not match the type or size
of the operation's argument (for example, if an integer is
passed when a pointer is expected, or the information returned in
the buffer by the operating system is larger than 1024 bytes,
or the size of the mutable bytes-like object is too small),
this is most likely to result in a segmentation violation or
a more subtle data corruption.
@end quotation
@end cartouche

以下に例を示します:

@example
>>> import array, fcntl, struct, termios, os
>>> os.getpgrp()
13341
>>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, "  "))[0]
13341
>>> buf = array.array('h', [0])
>>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)
0
>>> buf
array('h', [13341])
@end example

引数 @code{fd}, @code{request}, @code{arg} を指定して @ref{1c6e,,監査イベント} @code{fcntl.ioctl} を送出します。


バージョン 3.14 で変更: The GIL is always released during a system call.
System calls failing with EINTR are automatically retried.

@end deffn

@geindex flock() (fcntl モジュール)
@anchor{library/fcntl fcntl flock}@anchor{475c}
@deffn {の関数} fcntl.flock (fd, operation, /)

ファイル記述子 `fd' (@ref{17ad,,fileno()} メソッドを提供しているファイルオブジェクトも含む) に対してロック操作 `operation' を実行します。 詳細は Unix マニュアルの @code{flock(2)@footnote{https://manpages.debian.org/flock(2)}} を参照してください (システムによっては、この関数は @code{fcntl()} を使ってエミュレーションされています)。

If the @code{flock()} call fails, an @ref{2c0,,OSError} exception is raised.

引数 @code{fd}, @code{operation} を指定して @ref{1c6e,,監査イベント} @code{fcntl.flock} を送出します。
@end deffn

@geindex lockf() (fcntl モジュール)
@anchor{library/fcntl fcntl lockf}@anchor{1605}
@deffn {の関数} fcntl.lockf (fd, cmd, len=0, start=0, whence=0, /)

本質的に @ref{1851,,fcntl()} によるロッキングの呼び出しをラップしたものです。 `fd' はロックまたはアンロックするファイルのファイル記述子 (@ref{17ad,,fileno()} メソッドを提供するファイルオブジェクトも受け付けられます) で、 `cmd' は以下の値のうちいずれかになります:

@geindex LOCK_UN (fcntl モジュール)
@anchor{library/fcntl fcntl LOCK_UN}@anchor{4dea}
@deffn {データ} fcntl.LOCK_UN

Release an existing lock.
@end deffn

@geindex LOCK_SH (fcntl モジュール)
@anchor{library/fcntl fcntl LOCK_SH}@anchor{4deb}
@deffn {データ} fcntl.LOCK_SH

Acquire a shared lock.
@end deffn

@geindex LOCK_EX (fcntl モジュール)
@anchor{library/fcntl fcntl LOCK_EX}@anchor{4dec}
@deffn {データ} fcntl.LOCK_EX

Acquire an exclusive lock.
@end deffn

@geindex LOCK_NB (fcntl モジュール)
@anchor{library/fcntl fcntl LOCK_NB}@anchor{4ded}
@deffn {データ} fcntl.LOCK_NB

Bitwise OR with any of the other three @code{LOCK_*} constants to make
the request non-blocking.
@end deffn

If @code{LOCK_NB} is used and the lock cannot be acquired, an
@ref{2c0,,OSError} will be raised and the exception will have an `errno'
attribute set to @ref{270c,,EACCES} or @ref{26fd,,EAGAIN} (depending on the
operating system; for portability, check for both values).  On at least some
systems, @code{LOCK_EX} can only be used if the file descriptor refers to a
file opened for writing.

`len' はロックを行いたいバイト数、 `start' はロック領域先頭の `whence' からの相対的なバイトオフセット、 `whence' は @ref{14a4,,io.IOBase.seek()} と同じで、具体的には:


@itemize *

@item 
@code{0} -- relative to the start of the file (@ref{14a5,,os.SEEK_SET})

@item 
@code{1} -- relative to the current buffer position (@ref{14a6,,os.SEEK_CUR})

@item 
@code{2} -- relative to the end of the file (@ref{14a7,,os.SEEK_END})
@end itemize

`start' の標準の値は 0 で、ファイルの先頭から開始することを意味します。`len' の標準の値は 0 で、ファイルの終了までロックすることを表します。`whence' の標準の値も 0 です。

引数 @code{fd}, @code{cmd}, @code{len}, @code{start}, @code{whence} を指定して @ref{1c6e,,監査イベント} @code{fcntl.lockf} を送出します。
@end deffn

以下に (全ての SVR4 互換システムでの) 例を示します:

@example
import struct, fcntl, os

f = open(...)
rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)

lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)
@end example

最初の例では、戻り値 `rv' は整数値を保持しています; 二つ目の例では @ref{192,,bytes} オブジェクトを保持しています。 `lockdata' 変数の構造体レイアウトはシステム依存です --- 従って @ref{475c,,flock()} を呼ぶ方が良いでしょう。


@subsubheading 参考



@table @asis

@item @ref{a5,,os} モジュール

If the locking flags @ref{1648,,O_SHLOCK} and @ref{1649,,O_EXLOCK} are
present in the @ref{a5,,os} module (on BSD only), the @ref{f92,,os.open()}
function provides an alternative to the @ref{1605,,lockf()} and @ref{475c,,flock()}
functions.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node resource --- リソース使用情報,syslog --- Unix syslog ライブラリルーチン群,fcntl --- fcntl および ioctl システムコール,Unix-specific services
@anchor{library/resource doc}@anchor{4dee}@anchor{library/resource module-resource}@anchor{c1}@anchor{library/resource resource-resource-usage-information}@anchor{4def}@anchor{library/resource translation-repo}@anchor{4df0}
@subsection @code{resource} --- リソース使用情報


@geindex module; resource


__________________________________________________________________


このモジュールでは、プログラムによって使用されているシステムリソースを計測したり制御するための基本的なメカニズムを提供します。

@ref{213f,,Availability}: Unix, not WASI.

特定のシステムリソースを指定したり、現在のプロセスやその子プロセスのリソース使用情報を要求するためにシンボル定数が使われます。

システムコールが失敗した場合 @ref{2c0,,OSError} を送出します。

@geindex error
@anchor{library/resource resource error}@anchor{4df1}
@deffn {例外} resource.error

@ref{2c0,,OSError} の非推奨のエイリアスです。


バージョン 3.3 で変更: 
@geindex Python Enhancement Proposals; PEP 3151
PEP 3151@footnote{https://peps.python.org/pep-3151/} に基づき、このクラスは @ref{2c0,,OSError} のエイリアスになりました。

@end deffn

@menu
* リソースの制限:: 
* リソースの使用状態:: 

@end menu

@node リソースの制限,リソースの使用状態,,resource --- リソース使用情報
@anchor{library/resource resource-limits}@anchor{4df2}
@subsubsection リソースの制限


リソースの使用は下に述べる @ref{17c6,,setrlimit()} 関数を使って制限することができます。各リソースは二つ組の制限値: ソフトリミット (soft limit) 、およびハードリミット (hard limit) 、で制御されます。ソフトリミットは現在の制限値で、時間とともにプロセスによって下げたり上げたりできます。ソフトリミットはハードリミットを超えることはできません。ハードリミットはソフトリミットよりも高い任意の値まで下げることができますが、上げることはできません。 (スーパユーザの有効な UID を持つプロセスのみがハードリミットを上げることができます。)

制限をかけるべく指定できるリソースはシステムに依存します。指定できるリソースは @code{getrlimit(2)@footnote{https://manpages.debian.org/getrlimit(2)}} マニュアルページで解説されています。以下に列挙するリソースは背後のオペレーティングシステムがサポートする場合にサポートされています; オペレーティングシステム側で値を調べたり制御したりできないリソースは、そのプラットフォーム向けのこのモジュール内では定義されていません。

@geindex RLIM_INFINITY (resource モジュール)
@anchor{library/resource resource RLIM_INFINITY}@anchor{17c5}
@deffn {データ} resource.RLIM_INFINITY

無制限のリソースの上限を示すための定数です。
@end deffn

@geindex getrlimit() (resource モジュール)
@anchor{library/resource resource getrlimit}@anchor{17c4}
@deffn {の関数} resource.getrlimit (resource)

`resource' の現在のソフトおよびハードリミットを表すタプル @code{(soft, hard)} を返します。無効なリソースが指定された場合には @ref{2ec,,ValueError} が、背後のシステムコールが予期せず失敗した場合には @ref{4df1,,error} が送出されます。
@end deffn

@geindex setrlimit() (resource モジュール)
@anchor{library/resource resource setrlimit}@anchor{17c6}
@deffn {の関数} resource.setrlimit (resource, limits)

Sets new limits of consumption of `resource'. The `limits' argument must be a
tuple @code{(soft, hard)} of two integers describing the new limits. A value of
@ref{17c5,,RLIM_INFINITY} can be used to request a limit that is
unlimited.

Raises @ref{2ec,,ValueError} if an invalid resource is specified, if the new soft
limit exceeds the hard limit, or if a process tries to raise its hard limit.
Specifying a limit of @ref{17c5,,RLIM_INFINITY} when the hard or
system limit for that resource is not unlimited will result in a
@ref{2ec,,ValueError}.  A process with the effective UID of super-user can
request any valid limit value, including unlimited, but @ref{2ec,,ValueError}
will still be raised if the requested limit exceeds the system imposed
limit.

@code{setrlimit} は背後のシステムコールが予期せず失敗した場合に、 @ref{4df1,,error} を送出する場合があります。

VxWorks only supports setting @ref{4df3,,RLIMIT_NOFILE}.

引数 @code{src}, @code{dst`, `@w{`}limits} を指定して @ref{1c6e,,監査イベント} @code{resource.setrlimit} を送出します。
@end deffn

@geindex prlimit() (resource モジュール)
@anchor{library/resource resource prlimit}@anchor{118c}
@deffn {の関数} resource.prlimit (pid, resource[, limits])

1つの関数の中で @ref{17c6,,setrlimit()} と @ref{17c4,,getrlimit()} を組み合わせ、任意のプロセスのリソースの制限値を取得したり設定したりします。
`pid' が 0 の場合は、現在のプロセスに適用されます。
`resource' および `limits' は、 `limits' がオプションであることを除けば、 @ref{17c6,,setrlimit()} と同じ意味です。

`limits' が与えられないときは、関数はプロセス `pid' の `resource' の制限値を返します。
`limits' が与えられたときは、プロセスの `resource' の制限値が設定され、設定が変更される前のリソースの制限値が返されます。

`pid' が見付からないときは @ref{1266,,ProcessLookupError} を、ユーザがプロセスの @code{CAP_SYS_RESOURCE} を持ってないときは @ref{f3e,,PermissionError} を送出します。

引数 @code{pid}, @code{dst`, `@w{`}limits} を指定して @ref{1c6e,,監査イベント} @code{resource.prlimit} を送出します。

@ref{213f,,Availability}: Linux >= 2.6.36 with glibc >= 2.13.


Added in version 3.4.

@end deffn

以下のシンボルは、後に述べる関数 @ref{17c6,,setrlimit()} および @ref{17c4,,getrlimit()} を使って消費量を制御することができるリソースを定義しています。これらのシンボルの値は、C プログラムで使われているシンボルと全く同じです。

@code{getrlimit(2)@footnote{https://manpages.debian.org/getrlimit(2)}} の Unix マニュアルページには、指定可能なリソースが列挙されています。全てのシステムで同じシンボルが使われているわけではなく、また同じリソースを表すために同じ値が使われているとも限らないので注意してください。このモジュールはプラットフォーム間の相違を隠蔽しようとはしていません --- あるプラットフォームで定義されていないシンボルは、そのプラットフォーム向けの本モジュールでは利用することができません。

@geindex RLIMIT_CORE (resource モジュール)
@anchor{library/resource resource RLIMIT_CORE}@anchor{46fd}
@deffn {データ} resource.RLIMIT_CORE

現在のプロセスが生成できるコアファイルの最大 (バイト) サイズです。プロセスの全体イメージを入れるためにこの値より大きなサイズのコアファイルが要求された結果、部分的なコアファイルが生成される可能性があります。
@end deffn

@geindex RLIMIT_CPU (resource モジュール)
@anchor{library/resource resource RLIMIT_CPU}@anchor{4df4}
@deffn {データ} resource.RLIMIT_CPU

The maximum amount of processor time (in seconds) that a process can use. If
this limit is exceeded, a @ref{3a70,,SIGXCPU} signal is sent to the process. (See
the @ref{cb,,signal} module documentation for information about how to catch this
signal and do something useful, e.g. flush open files to disk.)
@end deffn

@geindex RLIMIT_FSIZE (resource モジュール)
@anchor{library/resource resource RLIMIT_FSIZE}@anchor{4df5}
@deffn {データ} resource.RLIMIT_FSIZE

プロセスが作成するファイルの最大サイズです。
@end deffn

@geindex RLIMIT_DATA (resource モジュール)
@anchor{library/resource resource RLIMIT_DATA}@anchor{4df6}
@deffn {データ} resource.RLIMIT_DATA

プロセスのヒープの最大 (バイト) サイズです。
@end deffn

@geindex RLIMIT_STACK (resource モジュール)
@anchor{library/resource resource RLIMIT_STACK}@anchor{4df7}
@deffn {データ} resource.RLIMIT_STACK

現在のプロセスのコールスタックの最大サイズ (バイト単位) です。
これはマルチスレッドプロセスのメインスレッドのスタックのみに影響します。
@end deffn

@geindex RLIMIT_RSS (resource モジュール)
@anchor{library/resource resource RLIMIT_RSS}@anchor{4df8}
@deffn {データ} resource.RLIMIT_RSS

プロセスが取りうる最大 RAM 常駐ページサイズ (resident set size) です。
@end deffn

@geindex RLIMIT_NPROC (resource モジュール)
@anchor{library/resource resource RLIMIT_NPROC}@anchor{4df9}
@deffn {データ} resource.RLIMIT_NPROC

現在のプロセスが生成できるプロセスの上限です。
@end deffn

@geindex RLIMIT_NOFILE (resource モジュール)
@anchor{library/resource resource RLIMIT_NOFILE}@anchor{4df3}
@deffn {データ} resource.RLIMIT_NOFILE

現在のプロセスが開けるファイル記述子の上限です。
@end deffn

@geindex RLIMIT_OFILE (resource モジュール)
@anchor{library/resource resource RLIMIT_OFILE}@anchor{4dfa}
@deffn {データ} resource.RLIMIT_OFILE

@ref{4df3,,RLIMIT_NOFILE} の BSD での名称です。
@end deffn

@geindex RLIMIT_MEMLOCK (resource モジュール)
@anchor{library/resource resource RLIMIT_MEMLOCK}@anchor{4dfb}
@deffn {データ} resource.RLIMIT_MEMLOCK

メモリ中でロックできる最大アドレス空間です。
@end deffn

@geindex RLIMIT_VMEM (resource モジュール)
@anchor{library/resource resource RLIMIT_VMEM}@anchor{4dfc}
@deffn {データ} resource.RLIMIT_VMEM

The largest area of mapped memory which the process may occupy.
Usually an alias of @ref{4dfd,,RLIMIT_AS}.

@ref{213f,,Availability}: Solaris, FreeBSD, NetBSD.
@end deffn

@geindex RLIMIT_AS (resource モジュール)
@anchor{library/resource resource RLIMIT_AS}@anchor{4dfd}
@deffn {データ} resource.RLIMIT_AS

アドレス空間でプロセスが占有できる最大領域 (バイト単位) です。
@end deffn

@geindex RLIMIT_MSGQUEUE (resource モジュール)
@anchor{library/resource resource RLIMIT_MSGQUEUE}@anchor{118d}
@deffn {データ} resource.RLIMIT_MSGQUEUE

POSIX メッセージキューに割り当てることの出来るバイト数です。

@ref{213f,,Availability}: Linux >= 2.6.8.


Added in version 3.4.

@end deffn

@geindex RLIMIT_NICE (resource モジュール)
@anchor{library/resource resource RLIMIT_NICE}@anchor{118e}
@deffn {データ} resource.RLIMIT_NICE

プロセスの nice の上限です (20 - rlim_cur)。

@ref{213f,,Availability}: Linux >= 2.6.12.


Added in version 3.4.

@end deffn

@geindex RLIMIT_RTPRIO (resource モジュール)
@anchor{library/resource resource RLIMIT_RTPRIO}@anchor{118f}
@deffn {データ} resource.RLIMIT_RTPRIO

リアルタイム優先順位の上限です。

@ref{213f,,Availability}: Linux >= 2.6.12.


Added in version 3.4.

@end deffn

@geindex RLIMIT_RTTIME (resource モジュール)
@anchor{library/resource resource RLIMIT_RTTIME}@anchor{1190}
@deffn {データ} resource.RLIMIT_RTTIME

リアルタイムスケジューリングにおいて、プロセスがブロッキングシステムコールを行わずに使用できるCPU時間の制限値（マイクロ秒単位）。

@ref{213f,,Availability}: Linux >= 2.6.25.


Added in version 3.4.

@end deffn

@geindex RLIMIT_SIGPENDING (resource モジュール)
@anchor{library/resource resource RLIMIT_SIGPENDING}@anchor{1191}
@deffn {データ} resource.RLIMIT_SIGPENDING

プロセスがキュー出来るシグナルの数です。

@ref{213f,,Availability}: Linux >= 2.6.8.


Added in version 3.4.

@end deffn

@geindex RLIMIT_SBSIZE (resource モジュール)
@anchor{library/resource resource RLIMIT_SBSIZE}@anchor{1192}
@deffn {データ} resource.RLIMIT_SBSIZE

このユーザが使用するソケットバッファの最大サイズ(バイト単位)。これは、このユーザが常に保持できるネットワークメモリの量、つまり mbuf の量を制限します。

@ref{213f,,Availability}: FreeBSD, NetBSD.


Added in version 3.4.

@end deffn

@geindex RLIMIT_SWAP (resource モジュール)
@anchor{library/resource resource RLIMIT_SWAP}@anchor{1193}
@deffn {データ} resource.RLIMIT_SWAP

このユーザ ID のすべてのプロセスで予約または使用できるスワップスペースの最大サイズ (バイト単位)。この制限は vm.overcommit sysctl のビット 1 が設定されている場合のみ適用されます。この sysctl の完全な説明については tuning(7)@footnote{https://man.freebsd.org/cgi/man.cgi?query=tuning&sektion=7} を参照してください。

@ref{213f,,Availability}: FreeBSD >= 8.


Added in version 3.4.

@end deffn

@geindex RLIMIT_NPTS (resource モジュール)
@anchor{library/resource resource RLIMIT_NPTS}@anchor{1194}
@deffn {データ} resource.RLIMIT_NPTS

このユーザ ID が作成する擬似端末の数の上限です。

@ref{213f,,Availability}: FreeBSD >= 8.


Added in version 3.4.

@end deffn

@geindex RLIMIT_KQUEUES (resource モジュール)
@anchor{library/resource resource RLIMIT_KQUEUES}@anchor{1ca6}
@deffn {データ} resource.RLIMIT_KQUEUES

The maximum number of kqueues this user id is allowed to create.

@ref{213f,,Availability}: FreeBSD >= 11.


Added in version 3.10.

@end deffn

@node リソースの使用状態,,リソースの制限,resource --- リソース使用情報
@anchor{library/resource resource-usage}@anchor{4dfe}
@subsubsection リソースの使用状態


以下の関数はリソース使用情報を取得するために使われます:

@geindex getrusage() (resource モジュール)
@anchor{library/resource resource getrusage}@anchor{164a}
@deffn {の関数} resource.getrusage (who)

This function returns an object that describes the resources consumed by either
the current process or its children, as specified by the `who' parameter.  The
`who' parameter should be specified using one of the @code{RUSAGE_*}
constants described below.

簡単な例:

@example
from resource import *
import time

# a non CPU-bound task
time.sleep(3)
print(getrusage(RUSAGE_SELF))

# a CPU-bound task
for i in range(10 ** 8):
   _ = 1 + 1
print(getrusage(RUSAGE_SELF))
@end example

The fields of the return value each describe how a particular system resource
has been used, e.g. amount of time spent running in user mode or number of times
the process was swapped out of main memory. Some values are dependent on the
clock tick interval, e.g. the amount of memory the process is using.

以前のバージョンとの互換性のため、返される値は 16 要素からなるタプルとしてアクセスすることもできます。

The fields @code{ru_utime} and @code{ru_stime} of the return value are
floating-point values representing the amount of time spent executing in user
mode and the amount of time spent executing in system mode, respectively. The
remaining values are integers. Consult the @code{getrusage(2)@footnote{https://manpages.debian.org/getrusage(2)}} man page for
detailed information about these values. A brief summary is presented here:


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

インデックス

@tab

フィールド

@tab

リソース

@item

@code{0}

@tab

@code{ru_utime}

@tab

time in user mode (float seconds)

@item

@code{1}

@tab

@code{ru_stime}

@tab

time in system mode (float seconds)

@item

@code{2}

@tab

@code{ru_maxrss}

@tab

最大常駐ページサイズ

@item

@code{3}

@tab

@code{ru_ixrss}

@tab

共有メモリサイズ

@item

@code{4}

@tab

@code{ru_idrss}

@tab

非共有メモリサイズ

@item

@code{5}

@tab

@code{ru_isrss}

@tab

非共有スタックサイズ

@item

@code{6}

@tab

@code{ru_minflt}

@tab

I/O を必要としないページフォールト数

@item

@code{7}

@tab

@code{ru_majflt}

@tab

I/O を必要とするページフォールト数

@item

@code{8}

@tab

@code{ru_nswap}

@tab

スワップアウト回数

@item

@code{9}

@tab

@code{ru_inblock}

@tab

ブロック入力操作数

@item

@code{10}

@tab

@code{ru_oublock}

@tab

ブロック出力操作数

@item

@code{11}

@tab

@code{ru_msgsnd}

@tab

送信メッセージ数

@item

@code{12}

@tab

@code{ru_msgrcv}

@tab

受信メッセージ数

@item

@code{13}

@tab

@code{ru_nsignals}

@tab

受信シグナル数

@item

@code{14}

@tab

@code{ru_nvcsw}

@tab

自発的な実行コンテキスト切り替え数

@item

@code{15}

@tab

@code{ru_nivcsw}

@tab

非自発的な実行コンテキスト切り替え数

@end multitable


この関数は無効な `who' 引数を指定した場合には @ref{2ec,,ValueError} を送出します。また、異常が発生した場合には @ref{4df1,,error} 例外が送出される可能性があります。
@end deffn

@geindex getpagesize() (resource モジュール)
@anchor{library/resource resource getpagesize}@anchor{4dff}
@deffn {の関数} resource.getpagesize ()

システムページ内のバイト数を返します。(ハードウェアページサイズと同じとは限りません。)
@end deffn

The following @code{RUSAGE_*} symbols are passed to the @ref{164a,,getrusage()}
function to specify which processes information should be provided for.

@geindex RUSAGE_SELF (resource モジュール)
@anchor{library/resource resource RUSAGE_SELF}@anchor{4e00}
@deffn {データ} resource.RUSAGE_SELF

@ref{164a,,getrusage()} に渡すと呼び出し中のプロセスが消費しているリソースを要求します。そのプロセスの全スレッドが使用するリソースの合計です。
@end deffn

@geindex RUSAGE_CHILDREN (resource モジュール)
@anchor{library/resource resource RUSAGE_CHILDREN}@anchor{4e01}
@deffn {データ} resource.RUSAGE_CHILDREN

呼び出し元のプロセスの子プロセスが消費するリソースを要求するために、 @ref{164a,,getrusage()} に渡して終了させ、待機させることができます。
@end deffn

@geindex RUSAGE_BOTH (resource モジュール)
@anchor{library/resource resource RUSAGE_BOTH}@anchor{4e02}
@deffn {データ} resource.RUSAGE_BOTH

@ref{164a,,getrusage()} に渡すと現在のプロセスおよび子プロセスの両方が消費しているリソースを要求します。全てのシステムで利用可能なわけではありません。
@end deffn

@geindex RUSAGE_THREAD (resource モジュール)
@anchor{library/resource resource RUSAGE_THREAD}@anchor{4e03}
@deffn {データ} resource.RUSAGE_THREAD

@ref{164a,,getrusage()} に渡すと現在のスレッドが消費しているリソースを要求します。全てのシステムで利用可能なわけではありません。


Added in version 3.2.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node syslog --- Unix syslog ライブラリルーチン群,,resource --- リソース使用情報,Unix-specific services
@anchor{library/syslog doc}@anchor{4e04}@anchor{library/syslog module-syslog}@anchor{e2}@anchor{library/syslog syslog-unix-syslog-library-routines}@anchor{4e05}@anchor{library/syslog translation-repo}@anchor{4e06}
@subsection @code{syslog} --- Unix syslog ライブラリルーチン群


@geindex module; syslog


__________________________________________________________________


このモジュールでは Unix @code{syslog} ライブラリルーチン群へのインターフェースを提供します。@code{syslog} の便宜レベルに関する詳細な記述は Unix マニュアルページを参照してください。

@ref{213f,,Availability}: Unix, not WASI, not iOS.

このモジュールはシステムの @code{syslog} ファミリのルーチンをラップしています。 syslog サーバーと通信できる pure Python のライブラリが、 @ref{8d,,logging.handlers} モジュールの @ref{86c,,SysLogHandler} にあります。

このモジュールには、以下の関数が定義されています:

@geindex syslog() (syslog モジュール)
@anchor{library/syslog syslog syslog}@anchor{762}
@deffn {の関数} syslog.syslog (message)

@deffnx {の関数} syslog.syslog (priority, message)

文字列 `message' をシステムログ機構に送信します。末尾の改行文字は必要に応じて追加されます。各メッセージは `facility' および `level' からなる優先度でタグ付けされます。オプションの `priority' 引数はメッセージの優先度を定義します。標準の値は @ref{4e07,,LOG_INFO} です。 `priority' 中に、便宜レベルが  (@code{LOG_INFO | LOG_USER} のように) 論理和を使ってコード化されていない場合、 @ref{760,,openlog()} を呼び出した際の値が使われます。

@ref{e2,,syslog()} が呼び出される前に @ref{760,,openlog()} が呼び出されなかった場合、 @ref{760,,openlog()} が引数なしで呼び出されます。

引数 @code{priority}, @code{message} を指定して @ref{1c6e,,監査イベント} @code{syslog.syslog} を送出します。


バージョン 3.2 で変更: In previous versions, @ref{760,,openlog()} would not be called automatically if
it wasn't called prior to the call to @ref{e2,,syslog()}, deferring to the syslog
implementation to call @code{openlog()}.



バージョン 3.12 で変更: This function is restricted in subinterpreters.
(Only code that runs in multiple interpreters is affected and
the restriction is not relevant for most users.)
@ref{760,,openlog()} must be called in the main interpreter before @ref{e2,,syslog()} may be used
in a subinterpreter.  Otherwise it will raise @ref{244,,RuntimeError}.

@end deffn

@geindex openlog() (syslog モジュール)
@anchor{library/syslog syslog openlog}@anchor{760}
@deffn {の関数} syslog.openlog ([ident[, logoption[, facility]]])

@ref{760,,openlog()} 関数を呼び出すことで以降の @ref{e2,,syslog()} の呼び出しに対するログオプションを設定することができます。ログがまだ開かれていない状態で @ref{e2,,syslog()} を呼び出すと @ref{760,,openlog()} が引数なしで呼び出されます。

オプションの `ident' キーワード引数は全てのメッセージの先頭に付く文字列で、デフォルトでは @code{sys.argv[0]} から前方のパス部分を取り除いたものです。オプションの `logoption' キーワード引数 (デフォルトは 0) はビットフィールドです。組み合わせられる値については下記を参照してください。オプションの `facility' キーワード引数 (デフォルトは @ref{4e08,,LOG_USER}) は明示的に facility が encode されていないメッセージに設定される facility です。

引数 @code{ident}, @cite{logoptiona`}, @code{facility} を指定して @ref{1c6e,,監査イベント} @code{syslog.openlog} を送出します。


バージョン 3.2 で変更: In previous versions, keyword arguments were not allowed, and `ident' was
required.



バージョン 3.12 で変更: This function is restricted in subinterpreters.
(Only code that runs in multiple interpreters is affected and
the restriction is not relevant for most users.)
This may only be called in the main interpreter.
It will raise @ref{244,,RuntimeError} if called in a subinterpreter.

@end deffn

@geindex closelog() (syslog モジュール)
@anchor{library/syslog syslog closelog}@anchor{761}
@deffn {の関数} syslog.closelog ()

syslog モジュールの値をリセットし、システムライブラリの @code{closelog()} を呼び出します。

この関数を呼ぶと、モジュールが最初に import されたときと同じようにふるまいます。例えば、(@ref{760,,openlog()} を呼び出さないで) @ref{e2,,syslog()} を最初に呼び出したときに、 @ref{760,,openlog()} が呼び出され、 `ident' やその他の @ref{760,,openlog()} の引数はデフォルト値にリセットされます。

引数無しで @ref{1c6e,,監査イベント} @code{syslog.closelog} を送出します。


バージョン 3.12 で変更: This function is restricted in subinterpreters.
(Only code that runs in multiple interpreters is affected and
the restriction is not relevant for most users.)
This may only be called in the main interpreter.
It will raise @ref{244,,RuntimeError} if called in a subinterpreter.

@end deffn

@geindex setlogmask() (syslog モジュール)
@anchor{library/syslog syslog setlogmask}@anchor{4762}
@deffn {の関数} syslog.setlogmask (maskpri)

優先度マスクを `maskpri' に設定し、以前のマスク値を返します。 `maskpri' に設定されていない優先度レベルを持った @ref{e2,,syslog()} の呼び出しは無視されます。標準では全ての優先度をログ出力します。関数 @code{LOG_MASK(pri)} は個々の優先度 `pri' に対する優先度マスクを計算します。関数 @code{LOG_UPTO(pri)} は優先度 `pri' までの全ての優先度を含むようなマスクを計算します。

引数 @code{maskpri} を指定して @ref{1c6e,,監査イベント} @code{socket.setlogmask} を送出します。
@end deffn

このモジュールでは以下の定数を定義しています:

@geindex LOG_EMERG (syslog モジュール)
@geindex LOG_ALERT (syslog モジュール)
@geindex LOG_CRIT (syslog モジュール)
@geindex LOG_ERR (syslog モジュール)
@geindex LOG_WARNING (syslog モジュール)
@geindex LOG_NOTICE (syslog モジュール)
@geindex LOG_INFO (syslog モジュール)
@geindex LOG_DEBUG (syslog モジュール)
@anchor{library/syslog syslog LOG_EMERG}@anchor{4e09}
@deffn {データ} syslog.LOG_EMERG
@anchor{library/syslog syslog LOG_ALERT}@anchor{4e0a}
@deffnx {データ} syslog.LOG_ALERT
@anchor{library/syslog syslog LOG_CRIT}@anchor{4e0b}
@deffnx {データ} syslog.LOG_CRIT
@anchor{library/syslog syslog LOG_ERR}@anchor{4e0c}
@deffnx {データ} syslog.LOG_ERR
@anchor{library/syslog syslog LOG_WARNING}@anchor{4e0d}
@deffnx {データ} syslog.LOG_WARNING
@anchor{library/syslog syslog LOG_NOTICE}@anchor{4e0e}
@deffnx {データ} syslog.LOG_NOTICE
@anchor{library/syslog syslog LOG_INFO}@anchor{4e07}
@deffnx {データ} syslog.LOG_INFO
@anchor{library/syslog syslog LOG_DEBUG}@anchor{4e0f}
@deffnx {データ} syslog.LOG_DEBUG

優先度 (高いものから低いもの) 。
@end deffn

@geindex LOG_AUTH (syslog モジュール)
@geindex LOG_AUTHPRIV (syslog モジュール)
@geindex LOG_CRON (syslog モジュール)
@geindex LOG_DAEMON (syslog モジュール)
@geindex LOG_FTP (syslog モジュール)
@geindex LOG_INSTALL (syslog モジュール)
@geindex LOG_KERN (syslog モジュール)
@geindex LOG_LAUNCHD (syslog モジュール)
@geindex LOG_LPR (syslog モジュール)
@geindex LOG_MAIL (syslog モジュール)
@geindex LOG_NETINFO (syslog モジュール)
@geindex LOG_NEWS (syslog モジュール)
@geindex LOG_RAS (syslog モジュール)
@geindex LOG_REMOTEAUTH (syslog モジュール)
@geindex LOG_SYSLOG (syslog モジュール)
@geindex LOG_USER (syslog モジュール)
@geindex LOG_UUCP (syslog モジュール)
@geindex LOG_LOCAL0 (syslog モジュール)
@geindex LOG_LOCAL1 (syslog モジュール)
@geindex LOG_LOCAL2 (syslog モジュール)
@geindex LOG_LOCAL3 (syslog モジュール)
@geindex LOG_LOCAL4 (syslog モジュール)
@geindex LOG_LOCAL5 (syslog モジュール)
@geindex LOG_LOCAL6 (syslog モジュール)
@geindex LOG_LOCAL7 (syslog モジュール)
@anchor{library/syslog syslog LOG_AUTH}@anchor{4e10}
@deffn {データ} syslog.LOG_AUTH
@anchor{library/syslog syslog LOG_AUTHPRIV}@anchor{4e11}
@deffnx {データ} syslog.LOG_AUTHPRIV
@anchor{library/syslog syslog LOG_CRON}@anchor{4e12}
@deffnx {データ} syslog.LOG_CRON
@anchor{library/syslog syslog LOG_DAEMON}@anchor{4e13}
@deffnx {データ} syslog.LOG_DAEMON
@anchor{library/syslog syslog LOG_FTP}@anchor{4e14}
@deffnx {データ} syslog.LOG_FTP
@anchor{library/syslog syslog LOG_INSTALL}@anchor{4e15}
@deffnx {データ} syslog.LOG_INSTALL
@anchor{library/syslog syslog LOG_KERN}@anchor{4e16}
@deffnx {データ} syslog.LOG_KERN
@anchor{library/syslog syslog LOG_LAUNCHD}@anchor{4e17}
@deffnx {データ} syslog.LOG_LAUNCHD
@anchor{library/syslog syslog LOG_LPR}@anchor{4e18}
@deffnx {データ} syslog.LOG_LPR
@anchor{library/syslog syslog LOG_MAIL}@anchor{4e19}
@deffnx {データ} syslog.LOG_MAIL
@anchor{library/syslog syslog LOG_NETINFO}@anchor{4e1a}
@deffnx {データ} syslog.LOG_NETINFO
@anchor{library/syslog syslog LOG_NEWS}@anchor{4e1b}
@deffnx {データ} syslog.LOG_NEWS
@anchor{library/syslog syslog LOG_RAS}@anchor{4e1c}
@deffnx {データ} syslog.LOG_RAS
@anchor{library/syslog syslog LOG_REMOTEAUTH}@anchor{4e1d}
@deffnx {データ} syslog.LOG_REMOTEAUTH
@anchor{library/syslog syslog LOG_SYSLOG}@anchor{4e1e}
@deffnx {データ} syslog.LOG_SYSLOG
@anchor{library/syslog syslog LOG_USER}@anchor{4e08}
@deffnx {データ} syslog.LOG_USER
@anchor{library/syslog syslog LOG_UUCP}@anchor{4e1f}
@deffnx {データ} syslog.LOG_UUCP
@anchor{library/syslog syslog LOG_LOCAL0}@anchor{4e20}
@deffnx {データ} syslog.LOG_LOCAL0
@anchor{library/syslog syslog LOG_LOCAL1}@anchor{4e21}
@deffnx {データ} syslog.LOG_LOCAL1
@anchor{library/syslog syslog LOG_LOCAL2}@anchor{4e22}
@deffnx {データ} syslog.LOG_LOCAL2
@anchor{library/syslog syslog LOG_LOCAL3}@anchor{4e23}
@deffnx {データ} syslog.LOG_LOCAL3
@anchor{library/syslog syslog LOG_LOCAL4}@anchor{4e24}
@deffnx {データ} syslog.LOG_LOCAL4
@anchor{library/syslog syslog LOG_LOCAL5}@anchor{4e25}
@deffnx {データ} syslog.LOG_LOCAL5
@anchor{library/syslog syslog LOG_LOCAL6}@anchor{4e26}
@deffnx {データ} syslog.LOG_LOCAL6
@anchor{library/syslog syslog LOG_LOCAL7}@anchor{4e27}
@deffnx {データ} syslog.LOG_LOCAL7

Facilities, depending on availability in @code{<syslog.h>} for @ref{4e11,,LOG_AUTHPRIV},
@ref{4e14,,LOG_FTP}, @ref{4e1a,,LOG_NETINFO}, @ref{4e1d,,LOG_REMOTEAUTH},
@ref{4e15,,LOG_INSTALL} and @ref{4e1c,,LOG_RAS}.


バージョン 3.13 で変更: Added @ref{4e14,,LOG_FTP}, @ref{4e1a,,LOG_NETINFO}, @ref{4e1d,,LOG_REMOTEAUTH},
@ref{4e15,,LOG_INSTALL}, @ref{4e1c,,LOG_RAS}, and @ref{4e17,,LOG_LAUNCHD}.

@end deffn

@geindex LOG_PID (syslog モジュール)
@geindex LOG_CONS (syslog モジュール)
@geindex LOG_NDELAY (syslog モジュール)
@geindex LOG_ODELAY (syslog モジュール)
@geindex LOG_NOWAIT (syslog モジュール)
@geindex LOG_PERROR (syslog モジュール)
@anchor{library/syslog syslog LOG_PID}@anchor{4e28}
@deffn {データ} syslog.LOG_PID
@anchor{library/syslog syslog LOG_CONS}@anchor{4e29}
@deffnx {データ} syslog.LOG_CONS
@anchor{library/syslog syslog LOG_NDELAY}@anchor{4e2a}
@deffnx {データ} syslog.LOG_NDELAY
@anchor{library/syslog syslog LOG_ODELAY}@anchor{4e2b}
@deffnx {データ} syslog.LOG_ODELAY
@anchor{library/syslog syslog LOG_NOWAIT}@anchor{4e2c}
@deffnx {データ} syslog.LOG_NOWAIT
@anchor{library/syslog syslog LOG_PERROR}@anchor{4e2d}
@deffnx {データ} syslog.LOG_PERROR

Log options, depending on availability in @code{<syslog.h>} for
@ref{4e2b,,LOG_ODELAY}, @ref{4e2c,,LOG_NOWAIT} and @ref{4e2d,,LOG_PERROR}.
@end deffn

@menu
* 使用例: 使用例<53>. 

@end menu

@node 使用例<53>,,,syslog --- Unix syslog ライブラリルーチン群
@anchor{library/syslog examples}@anchor{4e2e}
@subsubsection 使用例


@menu
* シンプルな例:: 

@end menu

@node シンプルな例,,,使用例<53>
@anchor{library/syslog simple-example}@anchor{4e2f}
@subsubsection シンプルな例


1つ目のシンプルな例:

@example
import syslog

syslog.syslog('Processing started')
if error:
    syslog.syslog(syslog.LOG_ERR, 'Processing started')
@end example

いくつかのログオプションを設定する例。ログメッセージにプロセスIDを含み、メッセージをメールのログ用の facility にメッセージを書きます:

@example
syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
syslog.syslog('E-mail processing initiated...')
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node モジュールのコマンドラインインターフェース CLI,取って代わられたモジュール群,Unix-specific services,Python 標準ライブラリ
@anchor{library/cmdline doc}@anchor{4e30}@anchor{library/cmdline library-cmdline}@anchor{4e31}@anchor{library/cmdline modules-command-line-interface-cli}@anchor{4e32}@anchor{library/cmdline translation-repo}@anchor{4e33}
@section モジュールのコマンドラインインターフェース (CLI)


以下のモジュールにはコマンドラインインターフェースがあります。


@itemize *

@item 
@ref{4bdb,,ast}

@item 
@ref{37c2,,asyncio}

@item 
@ref{f,,base64}

@item 
@ref{1d0,,calendar}

@item 
@ref{1b,,code}

@item 
@ref{4c98,,compileall}

@item 
@ref{2b,,cProfile}: @ref{47fe,,profile} を参照

@item 
@ref{4caf,,dis}

@item 
@ref{4557,,doctest}

@item 
@code{encodings.rot_13}

@item 
@ref{48a8,,ensurepip}

@item 
@ref{5e,,filecmp}

@item 
@ref{5f,,fileinput}

@item 
@ref{62,,ftplib}

@item 
@ref{2e5a,,gzip}

@item 
@ref{1153,,http.server}

@item 
@ref{4408,,idlelib}

@item 
@ref{115d,,inspect}

@item 
@ref{23e,,json}

@item 
@ref{247,,mimetypes}

@item 
@ref{2e2,,pdb}

@item 
@ref{2d2e,,pickle}

@item 
@ref{2d2f,,pickletools}

@item 
@ref{3244,,platform}

@item 
@ref{b1,,poplib}

@item 
@ref{47fe,,profile}

@item 
@ref{b5,,pstats}

@item 
@ref{4c8f,,py_compile}

@item 
@ref{b9,,pyclbr}

@item 
@ref{ba,,pydoc}

@item 
@ref{bc,,quopri}

@item 
@ref{47f,,random}

@item 
@ref{c3,,runpy}

@item 
@ref{4aae,,site}

@item 
@ref{674,,sqlite3}

@item 
@ref{4c12,,symtable}

@item 
@ref{4974,,sysconfig}

@item 
@ref{e3,,tabnanny}

@item 
@ref{11cd,,tarfile}

@item 
@code{this}

@item 
@ref{4822,,timeit}

@item 
@ref{4c60,,tokenize}

@item 
@ref{483f,,trace}

@item 
@ref{108,,turtledemo}

@item 
@ref{1136,,unittest}

@item 
@ref{676,,uuid}

@item 
@ref{48b6,,venv}

@item 
@ref{3ec3,,webbrowser}

@item 
@ref{48d0,,zipapp}

@item 
@ref{2ec9,,zipfile}
@end itemize

@ref{1da7,,Python コマンドラインインターフェース} も参照してください。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 取って代わられたモジュール群,削除されたモジュール,モジュールのコマンドラインインターフェース CLI,Python 標準ライブラリ
@anchor{library/superseded doc}@anchor{4e34}@anchor{library/superseded superseded}@anchor{4e35}@anchor{library/superseded superseded-modules}@anchor{4e36}@anchor{library/superseded translation-repo}@anchor{4e37}
@section 取って代わられたモジュール群


The modules described in this chapter have been superseded by other modules
for most use cases, and are retained primarily to preserve backwards compatibility.

Modules may appear in this chapter because they only cover a limited subset of
a problem space, and a more generally applicable solution is available elsewhere
in the standard library (for example, @ref{65,,getopt} covers the very specific
task of "mimic the C @code{getopt()} API in Python", rather than the broader
command line option parsing and argument parsing capabilities offered by
@ref{a4,,optparse} and @ref{7,,argparse}).

Alternatively, modules may appear in this chapter because they are deprecated
outright, and awaiting removal in a future release, or they are
@ref{23d,,soft deprecated} and their use is actively discouraged in new projects.
With the removal of various obsolete modules through 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}, there are
currently no modules in this latter category.

@menu
* getopt: getopt --- C-style parser for command line options. C-style parser for command line options

@end menu

@node getopt --- C-style parser for command line options,,,取って代わられたモジュール群
@anchor{library/getopt doc}@anchor{4e38}@anchor{library/getopt getopt-c-style-parser-for-command-line-options}@anchor{4e39}@anchor{library/getopt module-getopt}@anchor{65}
@subsection @code{getopt} --- C-style parser for command line options


@geindex module; getopt

`ソースコード:' Lib/getopt.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/getopt.py}

@cartouche
@quotation 注釈 
This module is considered feature complete. A more declarative and
extensible alternative to this API is provided in the @ref{a4,,optparse}
module. Further functional enhancements for command line parameter
processing are provided either as third party modules on PyPI,
or else as features in the @ref{7,,argparse} module.
@end quotation
@end cartouche


__________________________________________________________________


This module helps scripts to parse the command line arguments in @code{sys.argv}.
It supports the same conventions as the Unix @code{getopt()} function (including
the special meanings of arguments of the form '@code{-}' and '@code{--}').  Long
options similar to those supported by GNU software may be used as well via an
optional third argument.

Users who are unfamiliar with the Unix @code{getopt()} function should consider
using the @ref{7,,argparse} module instead. Users who are familiar with the Unix
@code{getopt()} function, but would like to get equivalent behavior while
writing less code and getting better help and error messages should consider
using the @ref{a4,,optparse} module. See @ref{336b,,Choosing an argument parsing library} for
additional details.

このモジュールは2つの関数と1つの例外を提供しています:

@geindex getopt() (getopt モジュール)
@anchor{library/getopt getopt getopt}@anchor{16d4}
@deffn {の関数} getopt.getopt (args, shortopts, longopts=[])

Parses command line options and parameter list.  `args' is the argument list to
be parsed, without the leading reference to the running program. Typically, this
means @code{sys.argv[1:]}. `shortopts' is the string of option letters that the
script wants to recognize, with options that require an argument followed by a
colon (@code{':'}) and options that accept an optional argument followed by
two colons (@code{'::'}); i.e., the same format that Unix @code{getopt()} uses.

@cartouche
@quotation 注釈 
Unlike GNU @code{getopt()}, after a non-option argument, all further
arguments are considered also non-options. This is similar to the way
non-GNU Unix systems work.
@end quotation
@end cartouche

`longopts', if specified, must be a list of strings with the names of the
long options which should be supported.  The leading @code{'--'} characters
should not be included in the option name.  Long options which require an
argument should be followed by an equal sign (@code{'='}).
Long options which accept an optional argument should be followed by
an equal sign and question mark (@code{'=?'}).
To accept only long options, `shortopts' should be an
empty string.  Long options on the command line can be recognized so long as
they provide a prefix of the option name that matches exactly one of the
accepted options.  For example, if `longopts' is @code{['foo', 'frob']}, the
option @code{--fo} will match as @code{--foo}, but @code{--f} will
not match uniquely, so @ref{18ea,,GetoptError} will be raised.

返り値は2つの要素から成っています: 最初は @code{(option, value)} のタプルのリスト、2つ目はオプションリストを取り除いたあとに残ったプログラムの引数リストです (`args' の末尾部分のスライスになります)。それぞれの引数と値のタプルの最初の要素は、短形式の時はハイフン 1つで始まる文字列 (例: @code{'-x'})、長形式の時はハイフン2つで始まる文字列 (例: @code{'--long-option'}) となり、引数が2番目の要素になります。引数をとらない場合には空文字列が入ります。オプションは見つかった順に並んでいて、複数回同じオプションを指定できます。長形式と短形式のオプションは混在できます。


バージョン 3.14 で変更: Optional arguments are supported.

@end deffn

@geindex gnu_getopt() (getopt モジュール)
@anchor{library/getopt getopt gnu_getopt}@anchor{16d3}
@deffn {の関数} getopt.gnu_getopt (args, shortopts, longopts=[])

この関数はデフォルトで GNU スタイルのスキャンモードを使う以外は @ref{65,,getopt()} と同じように動作します。つまり、オプションとオプションでない引数とを混在させることができます。@ref{65,,getopt()} 関数はオプションでない引数を見つけると解析を停止します。

If the first character of the option string is @code{'+'}, or if the environment
variable @code{POSIXLY_CORRECT} is set, then option processing stops as
soon as a non-option argument is encountered.

If the first character of the option string is @code{'-'}, non-option arguments
that are followed by options are added to the list of option-and-value pairs
as a pair that has @code{None} as its first element and the list of non-option
arguments as its second element.
The second element of the @code{gnu_getopt()} result is a list of
program arguments after the last option.


バージョン 3.14 で変更: Support for returning intermixed options and non-option arguments in order.

@end deffn

@geindex GetoptError
@anchor{library/getopt getopt GetoptError}@anchor{18ea}
@deffn {例外} getopt.GetoptError

This is raised when an unrecognized option is found in the argument list or when
an option requiring an argument is given none. The argument to the exception is
a string indicating the cause of the error.  For long options, an argument given
to an option which does not require one will also cause this exception to be
raised.  The attributes @code{msg} and @code{opt} give the error message and
related option; if there is no specific option to which the exception relates,
@code{opt} is an empty string.
@end deffn

@c XXX deprecated?

@geindex error
@anchor{library/getopt getopt error}@anchor{4e3a}
@deffn {例外} getopt.error

@ref{18ea,,GetoptError} へのエイリアスです。後方互換性のために残されています。
@end deffn

Unix スタイルのオプションを使った例です:

@example
>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', '@w{'}), ('-b', '@w{'}), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
@end example

長形式のオプションを使っても同様です:

@example
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
...     'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', '@w{'}), ('--output-file', 'abc.def'), ('-x', '@w{'})]
>>> args
['a1', 'a2']
@end example

Optional arguments should be specified explicitly:

@example
>>> s = '-Con -C --color=off --color a1 a2'
>>> args = s.split()
>>> args
['-Con', '-C', '--color=off', '--color', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'C::', ['color=?'])
>>> optlist
[('-C', 'on'), ('-C', '@w{'}), ('--color', 'off'), ('--color', '@w{'})]
>>> args
['a1', 'a2']
@end example

The order of options and non-option arguments can be preserved:

@example
>>> s = 'a1 -x a2 a3 a4 --long a5 a6'
>>> args = s.split()
>>> args
['a1', '-x', 'a2', 'a3', 'a4', '--long', 'a5', 'a6']
>>> optlist, args = getopt.gnu_getopt(args, '-x:', ['long='])
>>> optlist
[(None, ['a1']), ('-x', 'a2'), (None, ['a3', 'a4']), ('--long', 'a5')]
>>> args
['a6']
@end example

In a script, typical usage is something like this:

@example
import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    process(args, output=output, verbose=verbose)

if __name__ == "__main__":
    main()
@end example

Note that an equivalent command line interface could be produced with less code
and more informative help and error messages by using the @ref{a4,,optparse} module:

@example
import optparse

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('-o', '--output')
    parser.add_option('-v', dest='verbose', action='store_true')
    opts, args = parser.parse_args()
    process(args, output=opts.output, verbose=opts.verbose)
@end example

A roughly equivalent command line interface for this case can also be
produced by using the @ref{7,,argparse} module:

@example
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output')
    parser.add_argument('-v', dest='verbose', action='store_true')
    parser.add_argument('rest', nargs='*')
    args = parser.parse_args()
    process(args.rest, output=args.output, verbose=args.verbose)
@end example

See @ref{336b,,Choosing an argument parsing library} for details on how the @code{argparse}
version of this code differs in behaviour from the @code{optparse} (and
@code{getopt}) version.


@subsubheading 参考



@table @asis

@item Module @ref{a4,,optparse}

Declarative command line option parsing.

@item @ref{7,,argparse} モジュール

More opinionated command line option and argument parsing library.
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 削除されたモジュール,セキュリティで考慮すべき点<6>,取って代わられたモジュール群,Python 標準ライブラリ
@anchor{library/removed doc}@anchor{4e3b}@anchor{library/removed removed}@anchor{4e3c}@anchor{library/removed removed-modules}@anchor{4e3d}@anchor{library/removed translation-repo}@anchor{4e3e}
@section 削除されたモジュール


この章で説明されているモジュールは Python 標準ライブラリから削除されました。代替を探す手助けとなるよう、ここに記載されています。

@menu
* aifc: aifc --- Read and write AIFF and AIFC files. Read and write AIFF and AIFC files
* asynchat: asynchat --- Asynchronous socket command/response handler. Asynchronous socket command/response handler
* asyncore: asyncore --- Asynchronous socket handler. Asynchronous socket handler
* audioop: audioop --- Manipulate raw audio data. Manipulate raw audio data
* cgi: cgi --- Common Gateway Interface のサポート. Common Gateway Interface のサポート
* cgitb: cgitb --- Traceback manager for CGI scripts. Traceback manager for CGI scripts
* chunk: chunk --- Read IFF chunked data. Read IFF chunked data
* crypt: crypt --- Function to check Unix passwords. Function to check Unix passwords
* distutils: distutils --- Building and installing Python modules. Building and installing Python modules
* imghdr: imghdr --- Determine the type of an image. Determine the type of an image
* imp: imp --- Access the import internals. Access the import internals
* mailcap: mailcap --- Mailcap file handling. Mailcap file handling
* msilib: msilib --- Read and write Microsoft Installer files. Read and write Microsoft Installer files
* nis: nis --- Interface to Sun’s NIS Yellow Pages. Interface to Sun’s NIS (Yellow Pages)
* nntplib: nntplib --- NNTP protocol client. NNTP protocol client
* ossaudiodev: ossaudiodev --- Access to OSS-compatible audio devices. Access to OSS-compatible audio devices
* pipes: pipes --- Interface to shell pipelines. Interface to shell pipelines
* smtpd: smtpd --- SMTP Server. SMTP Server
* sndhdr: sndhdr --- Determine type of sound file. Determine type of sound file
* spwd: spwd --- The shadow password database. The shadow password database
* sunau: sunau --- Read and write Sun AU files. Read and write Sun AU files
* telnetlib: telnetlib --- Telnet client. Telnet client
* uu: uu --- Encode and decode uuencode files. Encode and decode uuencode files
* xdrlib: xdrlib --- Encode and decode XDR data. Encode and decode XDR data

@end menu

@node aifc --- Read and write AIFF and AIFC files,asynchat --- Asynchronous socket command/response handler,,削除されたモジュール
@anchor{library/aifc doc}@anchor{4e3f}@anchor{library/aifc aifc-read-and-write-aiff-and-aifc-files}@anchor{4e40}@anchor{library/aifc module-aifc}@anchor{5}
@subsection @code{aifc} --- Read and write AIFF and AIFC files


@geindex module; aifc


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{aifc} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/aifc.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node asynchat --- Asynchronous socket command/response handler,asyncore --- Asynchronous socket handler,aifc --- Read and write AIFF and AIFC files,削除されたモジュール
@anchor{library/asynchat doc}@anchor{4e41}@anchor{library/asynchat asynchat-asynchronous-socket-command-response-handler}@anchor{4e42}@anchor{library/asynchat module-asynchat}@anchor{a}@anchor{library/asynchat translation-repo}@anchor{4e43}
@subsection @code{asynchat} --- Asynchronous socket command/response handler


@geindex module; asynchat


Deprecated since version 3.6, removed in version 3.12.


This module is no longer part of the Python standard library.
It was @ref{726,,removed in Python 3.12} after
being deprecated in Python 3.6.  The removal was decided in 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}.

Applications should use the @ref{b,,asyncio} module instead.

The last version of Python that provided the @code{asynchat} module was
Python 3.11@footnote{https://docs.python.org/3.11/library/asynchat.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node asyncore --- Asynchronous socket handler,audioop --- Manipulate raw audio data,asynchat --- Asynchronous socket command/response handler,削除されたモジュール
@anchor{library/asyncore doc}@anchor{4e44}@anchor{library/asyncore asyncore-asynchronous-socket-handler}@anchor{4e45}@anchor{library/asyncore module-asyncore}@anchor{c}@anchor{library/asyncore translation-repo}@anchor{4e46}
@subsection @code{asyncore} --- Asynchronous socket handler


@geindex module; asyncore


Deprecated since version 3.6, removed in version 3.12.


This module is no longer part of the Python standard library.
It was @ref{726,,removed in Python 3.12} after
being deprecated in Python 3.6.  The removal was decided in 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}.

Applications should use the @ref{b,,asyncio} module instead.

The last version of Python that provided the @code{asyncore} module was
Python 3.11@footnote{https://docs.python.org/3.11/library/asyncore.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node audioop --- Manipulate raw audio data,cgi --- Common Gateway Interface のサポート,asyncore --- Asynchronous socket handler,削除されたモジュール
@anchor{library/audioop doc}@anchor{4e47}@anchor{library/audioop audioop-manipulate-raw-audio-data}@anchor{4e48}@anchor{library/audioop module-audioop}@anchor{e}@anchor{library/audioop translation-repo}@anchor{4e49}
@subsection @code{audioop} --- Manipulate raw audio data


@geindex module; audioop


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{audioop} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/audioop.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node cgi --- Common Gateway Interface のサポート,cgitb --- Traceback manager for CGI scripts,audioop --- Manipulate raw audio data,削除されたモジュール
@anchor{library/cgi doc}@anchor{4e4a}@anchor{library/cgi cgi-common-gateway-interface-support}@anchor{4e4b}@anchor{library/cgi module-cgi}@anchor{16}@anchor{library/cgi translation-repo}@anchor{4e4c}
@subsection @code{cgi} --- Common Gateway Interface のサポート


@geindex module; cgi


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、 @ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

代替として、PyPI 上にあるこのモジュールのフォーク legacy-cgi@footnote{https://pypi.org/project/legacy-cgi/} を利用できます。これは cgi モジュールのコピーであり、もはやコア Python チームによってメンテナンスもサポートもされていません。

@code{cgi} モジュールを提供していた最後の Python バージョンは Python 3.12@footnote{https://docs.python.org/3.12/library/cgi.html} です。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node cgitb --- Traceback manager for CGI scripts,chunk --- Read IFF chunked data,cgi --- Common Gateway Interface のサポート,削除されたモジュール
@anchor{library/cgitb doc}@anchor{4e4d}@anchor{library/cgitb cgitb-traceback-manager-for-cgi-scripts}@anchor{4e4e}@anchor{library/cgitb module-cgitb}@anchor{17}@anchor{library/cgitb translation-repo}@anchor{4e4f}
@subsection @code{cgitb} --- Traceback manager for CGI scripts


@geindex module; cgitb


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

A fork of the module on PyPI can now be used instead: legacy-cgi@footnote{https://pypi.org/project/legacy-cgi/}.
This is a copy of the cgi module, no longer maintained or supported by the core
Python team.

The last version of Python that provided the @code{cgitb} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/cgitb.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node chunk --- Read IFF chunked data,crypt --- Function to check Unix passwords,cgitb --- Traceback manager for CGI scripts,削除されたモジュール
@anchor{library/chunk doc}@anchor{4e50}@anchor{library/chunk chunk-read-iff-chunked-data}@anchor{4e51}@anchor{library/chunk module-chunk}@anchor{18}@anchor{library/chunk translation-repo}@anchor{4e52}
@subsection @code{chunk} --- Read IFF chunked data


@geindex module; chunk


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{chunk} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/chunk.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node crypt --- Function to check Unix passwords,distutils --- Building and installing Python modules,chunk --- Read IFF chunked data,削除されたモジュール
@anchor{library/crypt doc}@anchor{4e53}@anchor{library/crypt crypt-function-to-check-unix-passwords}@anchor{4e54}@anchor{library/crypt module-crypt}@anchor{2c}@anchor{library/crypt translation-repo}@anchor{4e55}
@subsection @code{crypt} --- Function to check Unix passwords


@geindex module; crypt


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

Applications can use the @ref{6c,,hashlib} module from the standard library.
Other possible replacements are third-party libraries from PyPI:
legacycrypt@footnote{https://pypi.org/project/legacycrypt/}, bcrypt@footnote{https://pypi.org/project/bcrypt/}, or argon2-cffi@footnote{https://pypi.org/project/argon2-cffi/}.
These are not supported or maintained by the Python core team.

The last version of Python that provided the @code{crypt} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/crypt.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node distutils --- Building and installing Python modules,imghdr --- Determine the type of an image,crypt --- Function to check Unix passwords,削除されたモジュール
@anchor{library/distutils doc}@anchor{4e56}@anchor{library/distutils distutils-building-and-installing-python-modules}@anchor{4e57}@anchor{library/distutils module-distutils}@anchor{3d}@anchor{library/distutils translation-repo}@anchor{4e58}
@subsection @code{distutils} --- Building and installing Python modules


@geindex module; distutils


Deprecated since version 3.10, removed in version 3.12.


This module is no longer part of the Python standard library.
It was @ref{72c,,removed in Python 3.12} after
being deprecated in Python 3.10.  The removal was decided in 
@geindex Python Enhancement Proposals; PEP 632
PEP 632@footnote{https://peps.python.org/pep-0632/},
which has migration advice@footnote{https://peps.python.org/pep-0632/#migration-advice}.

The last version of Python that provided the @code{distutils} module was
Python 3.11@footnote{https://docs.python.org/3.11/library/distutils.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node imghdr --- Determine the type of an image,imp --- Access the import internals,distutils --- Building and installing Python modules,削除されたモジュール
@anchor{library/imghdr doc}@anchor{4e59}@anchor{library/imghdr imghdr-determine-the-type-of-an-image}@anchor{4e5a}@anchor{library/imghdr module-imghdr}@anchor{79}@anchor{library/imghdr translation-repo}@anchor{4e5b}
@subsection @code{imghdr} --- Determine the type of an image


@geindex module; imghdr


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

Possible replacements are third-party libraries from PyPI:
filetype@footnote{https://pypi.org/project/filetype/}, puremagic@footnote{https://pypi.org/project/puremagic/}, or python-magic@footnote{https://pypi.org/project/python-magic/}.
These are not supported or maintained by the Python core team.

The last version of Python that provided the @code{imghdr} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/imghdr.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node imp --- Access the import internals,mailcap --- Mailcap file handling,imghdr --- Determine the type of an image,削除されたモジュール
@anchor{library/imp doc}@anchor{4e5c}@anchor{library/imp imp-access-the-import-internals}@anchor{4e5d}@anchor{library/imp module-imp}@anchor{7a}@anchor{library/imp translation-repo}@anchor{4e5e}
@subsection @code{imp} --- Access the import internals


@geindex module; imp


Deprecated since version 3.4, removed in version 3.12.


This module is no longer part of the Python standard library.
It was @ref{736,,removed in Python 3.12} after
being deprecated in Python 3.4.

The @ref{736,,removal notice} includes guidance for
migrating code from @code{imp} to @ref{7b,,importlib}.

The last version of Python that provided the @code{imp} module was
Python 3.11@footnote{https://docs.python.org/3.11/library/imp.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node mailcap --- Mailcap file handling,msilib --- Read and write Microsoft Installer files,imp --- Access the import internals,削除されたモジュール
@anchor{library/mailcap doc}@anchor{4e5f}@anchor{library/mailcap mailcap-mailcap-file-handling}@anchor{4e60}@anchor{library/mailcap module-mailcap}@anchor{90}@anchor{library/mailcap translation-repo}@anchor{4e61}
@subsection @code{mailcap} --- Mailcap file handling


@geindex module; mailcap


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{mailcap} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/mailcap.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node msilib --- Read and write Microsoft Installer files,nis --- Interface to Sun’s NIS Yellow Pages,mailcap --- Mailcap file handling,削除されたモジュール
@anchor{library/msilib doc}@anchor{4e62}@anchor{library/msilib module-msilib}@anchor{96}@anchor{library/msilib msilib-read-and-write-microsoft-installer-files}@anchor{4e63}@anchor{library/msilib translation-repo}@anchor{4e64}
@subsection @code{msilib} --- Read and write Microsoft Installer files


@geindex module; msilib


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{msilib} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/msilib.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node nis --- Interface to Sun’s NIS Yellow Pages,nntplib --- NNTP protocol client,msilib --- Read and write Microsoft Installer files,削除されたモジュール
@anchor{library/nis doc}@anchor{4e65}@anchor{library/nis module-nis}@anchor{a0}@anchor{library/nis nis-interface-to-suns-nis-yellow-pages}@anchor{4e66}@anchor{library/nis translation-repo}@anchor{4e67}
@subsection @code{nis} --- Interface to Sun’s NIS (Yellow Pages)


@geindex module; nis


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{nis} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/nis.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node nntplib --- NNTP protocol client,ossaudiodev --- Access to OSS-compatible audio devices,nis --- Interface to Sun’s NIS Yellow Pages,削除されたモジュール
@anchor{library/nntplib doc}@anchor{4e68}@anchor{library/nntplib module-nntplib}@anchor{a1}@anchor{library/nntplib nntplib-nntp-protocol-client}@anchor{4e69}@anchor{library/nntplib translation-repo}@anchor{4e6a}
@subsection @code{nntplib} --- NNTP protocol client


@geindex module; nntplib


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{nntplib} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/nntplib.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ossaudiodev --- Access to OSS-compatible audio devices,pipes --- Interface to shell pipelines,nntplib --- NNTP protocol client,削除されたモジュール
@anchor{library/ossaudiodev doc}@anchor{4e6b}@anchor{library/ossaudiodev module-ossaudiodev}@anchor{a7}@anchor{library/ossaudiodev ossaudiodev-access-to-oss-compatible-audio-devices}@anchor{4e6c}@anchor{library/ossaudiodev translation-repo}@anchor{4e6d}
@subsection @code{ossaudiodev} --- Access to OSS-compatible audio devices


@geindex module; ossaudiodev


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{ossaudiodev} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/ossaudiodev.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node pipes --- Interface to shell pipelines,smtpd --- SMTP Server,ossaudiodev --- Access to OSS-compatible audio devices,削除されたモジュール
@anchor{library/pipes doc}@anchor{4e6e}@anchor{library/pipes module-pipes}@anchor{ad}@anchor{library/pipes pipes-interface-to-shell-pipelines}@anchor{4e6f}@anchor{library/pipes translation-repo}@anchor{4e70}
@subsection @code{pipes} --- Interface to shell pipelines


@geindex module; pipes


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

Applications should use the @ref{dc,,subprocess} module instead.

The last version of Python that provided the @code{pipes} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/pipes.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node smtpd --- SMTP Server,sndhdr --- Determine type of sound file,pipes --- Interface to shell pipelines,削除されたモジュール
@anchor{library/smtpd doc}@anchor{4e71}@anchor{library/smtpd module-smtpd}@anchor{ce}@anchor{library/smtpd smtpd-smtp-server}@anchor{4e72}@anchor{library/smtpd translation-repo}@anchor{4e73}
@subsection @code{smtpd} --- SMTP Server


@geindex module; smtpd


Deprecated since version 3.6, removed in version 3.12.


This module is no longer part of the Python standard library.
It was @ref{726,,removed in Python 3.12} after
being deprecated in Python 3.6.  The removal was decided in 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/}.

A possible replacement is the third-party aiosmtpd@footnote{https://pypi.org/project/aiosmtpd/} library. This
library is not maintained or supported by the Python core team.

The last version of Python that provided the @code{smtpd} module was
Python 3.11@footnote{https://docs.python.org/3.11/library/smtpd.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node sndhdr --- Determine type of sound file,spwd --- The shadow password database,smtpd --- SMTP Server,削除されたモジュール
@anchor{library/sndhdr doc}@anchor{4e74}@anchor{library/sndhdr module-sndhdr}@anchor{d0}@anchor{library/sndhdr sndhdr-determine-type-of-sound-file}@anchor{4e75}@anchor{library/sndhdr translation-repo}@anchor{4e76}
@subsection @code{sndhdr} --- Determine type of sound file


@geindex module; sndhdr


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

Possible replacements are third-party modules from PyPI:
filetype@footnote{https://pypi.org/project/filetype/}, puremagic@footnote{https://pypi.org/project/puremagic/}, or python-magic@footnote{https://pypi.org/project/python-magic/}.
These are not supported or maintained by the Python core team.

The last version of Python that provided the @code{sndhdr} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/sndhdr.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node spwd --- The shadow password database,sunau --- Read and write Sun AU files,sndhdr --- Determine type of sound file,削除されたモジュール
@anchor{library/spwd doc}@anchor{4e77}@anchor{library/spwd module-spwd}@anchor{d3}@anchor{library/spwd spwd-the-shadow-password-database}@anchor{4e78}@anchor{library/spwd translation-repo}@anchor{4e79}
@subsection @code{spwd} --- The shadow password database


@geindex module; spwd


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

A possible replacement is the third-party library python-pam@footnote{https://pypi.org/project/python-pam/}.
This library is not supported or maintained by the Python core team.

The last version of Python that provided the @code{spwd} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/spwd.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node sunau --- Read and write Sun AU files,telnetlib --- Telnet client,spwd --- The shadow password database,削除されたモジュール
@anchor{library/sunau doc}@anchor{4e7a}@anchor{library/sunau module-sunau}@anchor{dd}@anchor{library/sunau sunau-read-and-write-sun-au-files}@anchor{4e7b}@anchor{library/sunau translation-repo}@anchor{4e7c}
@subsection @code{sunau} --- Read and write Sun AU files


@geindex module; sunau


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{sunau} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/sunau.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node telnetlib --- Telnet client,uu --- Encode and decode uuencode files,sunau --- Read and write Sun AU files,削除されたモジュール
@anchor{library/telnetlib doc}@anchor{4e7d}@anchor{library/telnetlib module-telnetlib}@anchor{e5}@anchor{library/telnetlib telnetlib-telnet-client}@anchor{4e7e}@anchor{library/telnetlib translation-repo}@anchor{4e7f}
@subsection @code{telnetlib} --- Telnet client


@geindex module; telnetlib


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

Possible replacements are third-party libraries from PyPI: telnetlib3@footnote{https://pypi.org/project/telnetlib3/}
or Exscript@footnote{https://pypi.org/project/Exscript/}.  These are not supported or maintained by the Python core
team.

The last version of Python that provided the @code{telnetlib} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/telnetlib.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node uu --- Encode and decode uuencode files,xdrlib --- Encode and decode XDR data,telnetlib --- Telnet client,削除されたモジュール
@anchor{library/uu doc}@anchor{4e80}@anchor{library/uu module-uu}@anchor{115}@anchor{library/uu translation-repo}@anchor{4e81}@anchor{library/uu uu-encode-and-decode-uuencode-files}@anchor{4e82}
@subsection @code{uu} --- Encode and decode uuencode files


@geindex module; uu


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{uu} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/uu.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node xdrlib --- Encode and decode XDR data,,uu --- Encode and decode uuencode files,削除されたモジュール
@anchor{library/xdrlib doc}@anchor{4e83}@anchor{library/xdrlib module-xdrlib}@anchor{125}@anchor{library/xdrlib translation-repo}@anchor{4e84}@anchor{library/xdrlib xdrlib-encode-and-decode-xdr-data}@anchor{4e85}
@subsection @code{xdrlib} --- Encode and decode XDR data


@geindex module; xdrlib


Deprecated since version 3.11, removed in version 3.13.


このモジュールは今や Python 標準ライブラリの一部ではありません。このモジュールは Python 3.11 で非推奨となったあと、@ref{471,,Python 3.13 で削除} されました。削除の決定は 
@geindex Python Enhancement Proposals; PEP 594
PEP 594@footnote{https://peps.python.org/pep-0594/} でなされました。

The last version of Python that provided the @code{xdrlib} module was
Python 3.12@footnote{https://docs.python.org/3.12/library/xdrlib.html}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@geindex security considerations
@anchor{library/security_warnings security-warnings}@anchor{4e86}
@node セキュリティで考慮すべき点<6>,,削除されたモジュール,Python 標準ライブラリ
@anchor{library/security_warnings doc}@anchor{4e87}@anchor{library/security_warnings security-considerations}@anchor{4e88}@anchor{library/security_warnings translation-repo}@anchor{4e89}
@section セキュリティで考慮すべき点


The following modules have specific security considerations:


@itemize *

@item 
@ref{f,,base64}: @ref{3cb5,,base64 security considerations} in
@geindex RFC; RFC 4648
RFC 4648@footnote{https://datatracker.ietf.org/doc/html/rfc4648.html}

@item 
@ref{6c,,hashlib}: @ref{2fc8,,all constructors take a "usedforsecurity" keyword-only argument disabling known insecure and blocked algorithms}

@item 
@ref{76,,http.server} is not suitable for production use, only implementing
basic security checks. See the @ref{40e8,,security considerations}.

@item 
@ref{8b,,logging}: @ref{31ac,,Logging configuration uses eval()}

@item 
@ref{98,,multiprocessing}: @ref{3686,,Connection.recv() uses pickle}

@item 
@ref{ab,,pickle}: @ref{2d1a,,Restricting globals in pickle}

@item 
@ref{bd,,random} shouldn't be used for security purposes, use @ref{c5,,secrets}
instead

@item 
@ref{c8,,shelve}: @ref{2d3c,,shelve is based on pickle and thus unsuitable for dealing with untrusted sources}

@item 
@ref{d5,,ssl}: @ref{3895,,SSL/TLS security considerations}

@item 
@ref{dc,,subprocess}: @ref{3756,,Subprocess security considerations}

@item 
@ref{e6,,tempfile}: @ref{2cd4,,mktemp is deprecated due to vulnerability to race conditions}

@item 
@ref{126,,xml}: @ref{3ce9,,XML security}

@item 
@ref{137,,zipfile}: @ref{2ed8,,maliciously prepared .zip files can cause disk volume exhaustion}
@end itemize

The @ref{b57,,-I} command line option can be used to run Python in isolated
mode. When it cannot be used, the @ref{7c1,,-P} option or the
@geindex PYTHONSAFEPATH
@geindex 環境変数; PYTHONSAFEPATH
@ref{7c2,,PYTHONSAFEPATH} environment variable can be used to not prepend a
potentially unsafe path to @ref{3e4,,sys.path} such as the current directory, the
script's directory or an empty string.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python インタプリタの拡張と埋め込み,Python/C API リファレンスマニュアル,Python 標準ライブラリ,Top
@anchor{extending/index doc}@anchor{4e8a}@anchor{extending/index extending-and-embedding-the-python-interpreter}@anchor{4e8b}@anchor{extending/index extending-index}@anchor{1fbd}@anchor{extending/index translation-repo}@anchor{4e8c}
@chapter Python インタプリタの拡張と埋め込み


このドキュメントでは、Pythonインタプリンタを拡張する新しいモジュールをで C またはC++ で書く方法を解説しています。このようなモジュールでは新しい関数を定義するだけではなく、新しい型や、そのメソッドを定義することができます。ドキュメントでは他のアプリケーションでPythonを拡張言語として使用するために、Pythonインタプリタをアプリケーションに埋め込む方法についても解説します。最後に、下層のオペレーティングシステムが動的(実行時)ロードをサポートしていれば、拡張モジュールが動的にライブラリにロードされるように、モジュールをコンパイルしリンクする方法について解説します。

このドキュメントでは、読者は Python について基礎的な知識を持ち合わせているものと仮定しています。形式ばらない Python 言語の入門には、 @ref{1fbc,,Python チュートリアル} を読んでください。 @ref{14a,,Python 言語リファレンス} を読めば、 Python 言語についてより形式的な定義を得られます。また、 @ref{149,,Python 標準ライブラリ} では、Python に広い適用範囲をもたらしている既存のオブジェクト型、関数、および (組み込み、および Python で書かれたものの両方の) モジュールについて解説しています。

Python/C API 全体の詳しい説明は、別のドキュメントである、 @ref{1fbe,,Python/C API リファレンスマニュアル} を参照してください。

@menu
* おすすめのサードパーティツール:: 
* サードパーティツールなしで拡張を作る:: 
* 大規模なアプリケーションへの Python ランタイムの埋め込み:: 

@end menu

@node おすすめのサードパーティツール,サードパーティツールなしで拡張を作る,,Python インタプリタの拡張と埋め込み
@anchor{extending/index recommended-third-party-tools}@anchor{4e8d}
@section おすすめのサードパーティツール


このガイドは、このバージョンの CPython の一部として提供されている拡張作成用の基礎的なツールのみをカバーしています。 Python 用の C と C++ 拡張を作成するより単純で高度なアプローチを提供する @ref{4e8e,,サードパーティのツール} もあります。

@node サードパーティツールなしで拡張を作る,大規模なアプリケーションへの Python ランタイムの埋め込み,おすすめのサードパーティツール,Python インタプリタの拡張と埋め込み
@anchor{extending/index creating-extensions-without-third-party-tools}@anchor{4e8f}
@section サードパーティツールなしで拡張を作る


ガイドのこの節ではサードパーティツールの補助無しに C および C++ 拡張を作成する方法を説明します。
これは自分自身の C 拡張を作成するおすすめの方法というよりも、主にそれらのツールを作成する人向けのものです。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} -- 拡張モジュールの多段階初期化


@menu
* C や C++ による Python の拡張:: 
* 拡張の型の定義; チュートリアル: 拡張の型の定義 チュートリアル. 
* 拡張の型の定義; 雑多なトピック: 拡張の型の定義 雑多なトピック. 
* C および C++ 拡張のビルド:: 
* Windows 上での C および C++ 拡張モジュールのビルド:: 

@end menu

@node C や C++ による Python の拡張,拡張の型の定義 チュートリアル,,サードパーティツールなしで拡張を作る
@anchor{extending/extending doc}@anchor{4e90}@anchor{extending/extending extending-intro}@anchor{4e91}@anchor{extending/extending extending-python-with-c-or-c}@anchor{4e92}
@subsection C や C++ による Python の拡張


C プログラムの書き方を知っているなら、Python に新たな組み込みモジュールを追加するのはきわめて簡単です。この新たなモジュール、拡張モジュール (`extension module') を使うと、Python が直接行えない二つのこと: 新しい組み込みオブジェクトの実装、そして全ての C ライブラリ関数とシステムコールに対する呼び出し、ができるようになります。

拡張モジュールをサポートするため、Python API (Application Programmer's Interface) では一連の関数、マクロおよび変数を提供していて、Python ランタイムシステムのほとんどの側面へのアクセス手段を提供しています。 Python API は、ヘッダ @code{"Python.h"} をインクルードして C ソースに取り込みます。

拡張モジュールのコンパイル方法は、モジュールの用途やシステムの設定方法に依存します。詳細は後の章で説明します。

@cartouche
@quotation 注釈 
C 拡張のインターフェイスは CPython に固有のものであり、これによる拡張モジュールはほかの Python 実装では動作しません。多くの場合、C 拡張を書くことを避けてほかの Python 実装のために移植性を確保することは可能です。たとえば、あなたがしたいことが C ライブラリの関数やシステムコールを呼び出すことである場合、 @ref{2e,,ctypes} あるいは cffi@footnote{https://cffi.readthedocs.io/} ライブラリの利用を検討すべきです。これらのモジュールは C コードとインターフェイスし、C 拡張を書いてコンパイルするのに較べて Python 実装間のより高い移植性をもった Python コードを書かせてくれます。
@end quotation
@end cartouche

@menu
* 簡単な例:: 
* 幕間小話; エラーと例外: 幕間小話 エラーと例外. 
* 例に戻る:: 
* モジュールのメソッドテーブルと初期化関数:: 
* コンパイルとリンク:: 
* C から Python 関数を呼び出す:: 
* 拡張モジュール関数でのパラメタ展開:: 
* 拡張モジュール関数のキーワードパラメタ:: 
* 任意の値を構築する:: 
* 参照カウント法:: 
* C++での拡張モジュール作成:: 
* 拡張モジュールに C API を提供する:: 

@end menu

@node 簡単な例,幕間小話 エラーと例外,,C や C++ による Python の拡張
@anchor{extending/extending a-simple-example}@anchor{4e93}@anchor{extending/extending extending-simpleexample}@anchor{4e94}
@subsubsection 簡単な例


@code{spam} (Monty Python ファンの好物ですね) という名の拡張モジュールを作成することにして、C ライブラリ関数 @code{system()} に対する Python インターフェイスを作成したいとします。 @footnote{
この関数へのインターフェースはすでに標準モジュール @ref{a5,,os} にあります --- この関数を選んだのは、単純で直接的な例を示したいからです。
} この関数は null で終端されたキャラクタ文字列を引数にとり、整数を返します。この関数を以下のようにして Python から呼び出せるようにしたいとします。

@example
>>> import spam
>>> status = spam.system("ls -l")
@end example

まずは @code{spammodule.c} を作成するところから始めます。 (伝統として、 @code{spam} という名前のモジュールを作成する場合、モジュールの実装が入った C ファイルを @code{spammodule.c} と呼ぶことになっています; @code{spammify} のように長すぎるモジュール名の場合には、単に @code{spammify.c} にもできます。)

このファイルの最初の 2 行は以下のようにします:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
@end example

これで、Python API を取り込みます (必要なら、モジュールの用途に関する説明や、著作権表示を追加します)。

@cartouche
@quotation 注釈 
Python は、システムによっては標準ヘッダの定義に影響するようなプリプロセッサ定義を行っているので、 @code{Python.h} をいずれの標準ヘッダよりも前にインクルード `せねばなりません' 。

@code{#define PY_SSIZE_T_CLEAN} は、いくつかの API では @code{int} の代わりに @code{Py_ssize_t} が使われるべきであることを示すために使われていました。これは Python 3.13 以降では不要となりましたが、後方互換性のために維持されています。このマクロの説明は @ref{62c,,文字列とバッファ} にあります。
@end quotation
@end cartouche

All user-visible symbols defined by @code{Python.h} have a prefix of @code{Py} or
@code{PY}, except those defined in standard header files.

@cartouche
@quotation Tip 
For backward compatibility, @code{Python.h} includes several standard header files.
C extensions should include the standard headers that they use,
and should not rely on these implicit includes.
If using the limited C API version 3.13 or newer, the implicit includes are:


@itemize *

@item 
@code{<assert.h>}

@item 
@code{<intrin.h>} (on Windows)

@item 
@code{<inttypes.h>}

@item 
@code{<limits.h>}

@item 
@code{<math.h>}

@item 
@code{<stdarg.h>}

@item 
@code{<wchar.h>}

@item 
@code{<sys/types.h>} (if present)
@end itemize

If @ref{660,,Py_LIMITED_API} is not defined, or is set to version 3.12 or older,
the headers below are also included:


@itemize *

@item 
@code{<ctype.h>}

@item 
@code{<unistd.h>} (on POSIX)
@end itemize

If @ref{660,,Py_LIMITED_API} is not defined, or is set to version 3.10 or older,
the headers below are also included:


@itemize *

@item 
@code{<errno.h>}

@item 
@code{<stdio.h>}

@item 
@code{<stdlib.h>}

@item 
@code{<string.h>}
@end itemize
@end quotation
@end cartouche

次にファイルに追加する内容は、Python 式 @code{spam.system(string)} を評価する際に呼び出されることになる C 関数です (この関数を最終的にどのように呼び出すかは、後ですぐわかります):

@example
static PyObject *
spam_system(PyObject *self, PyObject *args)
@{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return PyLong_FromLong(sts);
@}
@end example

ここでは、Python の引数リスト (例えば、単一の式 @code{"ls -l"}) から C 関数に渡す引数にそのまま変換しています。 C 関数は常に二つの引数を持ち、便宜的に `self' および `args' と呼ばれます。

`self' 引数には、モジュールレベルの関数であればモジュールが、メソッドにはオブジェクトインスタンスが渡されます。

`args' 引数は、引数の入った Python タプルオブジェクトへのポインタになります。タプル内の各要素は、呼び出しの際の引数リストにおける各引数に対応します。引数は Python オブジェクトです --- C 関数で引数を使って何かを行うには、オブジェクトから C の値に変換せねばなりません。Python API の関数 @ref{3c1,,PyArg_ParseTuple()} は引数の型をチェックし、C の値に変換します。 @ref{3c1,,PyArg_ParseTuple()} はテンプレート文字列を使って、引数オブジェクトの型と、変換された値を入れる C 変数の型を判別します。これについては後で詳しく説明します。

@ref{3c1,,PyArg_ParseTuple()} は、全ての引数が正しい型を持っていて、アドレス渡しされた各変数に各引数要素を保存したときに真 (非ゼロ) を返します。この関数は不正な引数リストを渡すと偽 (ゼロ) を返します。後者の場合、関数は適切な例外を送出するので、呼び出し側は (例にもあるように) すぐに @code{NULL} を返すようにしてください。

@node 幕間小話 エラーと例外,例に戻る,簡単な例,C や C++ による Python の拡張
@anchor{extending/extending extending-errors}@anchor{4e95}@anchor{extending/extending intermezzo-errors-and-exceptions}@anchor{4e96}
@subsubsection 幕間小話: エラーと例外


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 @code{-1} or a @code{NULL} pointer).  Exception information is stored in
three members of the interpreter's thread state.  These are @code{NULL} if
there is no exception.  Otherwise they are the C equivalents of the members
of the Python tuple returned by @ref{89a,,sys.exc_info()}.  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 では、様々な型の例外をセットするための関数をいくつか定義しています。

もっともよく用いられるのは @ref{79c,,PyErr_SetString()} です。引数は例外オブジェクトと C 文字列です。例外オブジェクトは通常、 @ref{4e97,,PyExc_ZeroDivisionError} のような定義済みのオブジェクトです。 C 文字列はエラーの原因を示し、Python 文字列オブジェクトに変換されて例外の "付属値" に保存されます。

もう一つ有用な関数として @ref{4e98,,PyErr_SetFromErrno()} があります。この関数は引数に例外だけをとり、付属値はグローバル変数 @code{errno} から構築します。もっとも汎用的な関数は @ref{79b,,PyErr_SetObject()} で、二つのオブジェクト、例外と付属値を引数にとります。これら関数に渡すオブジェクトには @ref{78f,,Py_INCREF()} を使う必要はありません。

例外がセットされているかどうかは、 @ref{1caf,,PyErr_Occurred()} を使って非破壊的に調べられます。この関数は現在の例外オブジェクトを返します。例外が発生していない場合には @code{NULL} を返します。通常は、関数の戻り値からエラーが発生したかを判別できるはずなので、 @ref{1caf,,PyErr_Occurred()} を呼び出す必要はありません。

関数 `g' を呼び出す `f' が、前者の関数の呼び出しに失敗したことを検出すると、 `f' 自体はエラー値 (大抵は @code{NULL} や @code{-1}) を返さねばなりません。しかし、 @code{PyErr_*} 関数群のいずれかを呼び出す必要は `ありません' --- なぜなら、 `g' がすでに呼び出しているからです。次いで `f' を呼び出したコードもエラーを示す値を `自らを呼び出したコード' に返すことになりますが、同様に @code{PyErr_*} は `呼び出しません' 。以下同様に続きます --- エラーの最も詳しい原因は、最初にエラーを検出した関数がすでに報告しているからです。エラーが Python インタプリタのメインループに到達すると、現在実行中の Python コードは一時停止し、 Python プログラマが指定した例外ハンドラを探し出そうとします。

(モジュールが @code{PyErr_*} 関数をもう一度呼び出して、より詳細なエラーメッセージを提供するような状況があります。このような状況ではそうすべきです。とはいえ、一般的な規則としては、この関数を何度も呼び出す必要はなく、ともすればエラーの原因に関する情報を失う結果になりがちです: これにより、ほとんどの操作が様々な理由から失敗するかもしれません)

ある関数呼び出しでの処理の失敗によってセットされた例外を無視するには、 @ref{1232,,PyErr_Clear()} を呼び出して例外状態を明示的に消去しなくてはなりません。エラーをインタプリタには渡したくなく、自前で (何か他の作業を行ったり、何も起こらなかったかのように見せかけるような) エラー処理を完全に行う場合にのみ、 @ref{1232,,PyErr_Clear()} を呼び出すようにすべきです。

@code{malloc()} の呼び出し失敗は、常に例外にしなくてはなりません --- @code{malloc()} (または @code{realloc()}) を直接呼び出しているコードは、 @ref{4e99,,PyErr_NoMemory()} を呼び出して、失敗を示す値を返さねばなりません。オブジェクトを生成する全ての関数 (例えば @ref{1bd0,,PyLong_FromLong()}) は @ref{4e99,,PyErr_NoMemory()} の呼び出しを済ませてしまうので、この規則が関係するのは直接 @code{malloc()} を呼び出すコードだけです。

また、 @ref{3c1,,PyArg_ParseTuple()} という重要な例外を除いて、整数の状態コードを返す関数はたいてい、Unix のシステムコールと同じく、処理が成功した際にはゼロまたは正の値を返し、失敗した場合には @code{-1} を返します。

最後に、エラー標示値を返す際に、(エラーが発生するまでに既に生成してしまったオブジェクトに対して @ref{992,,Py_XDECREF()} や @ref{790,,Py_DECREF()} を呼び出して) ごみ処理を注意深く行ってください!

The choice of which exception to raise is entirely yours.  There are predeclared
C objects corresponding to all built-in Python exceptions, such as
@ref{4e97,,PyExc_ZeroDivisionError}, which you can use directly. Of course, you
should choose exceptions wisely --- don't use @ref{4e9a,,PyExc_TypeError} to mean
that a file couldn't be opened (that should probably be @ref{4e9b,,PyExc_OSError}).
If something's wrong with the argument list, the @ref{3c1,,PyArg_ParseTuple()}
function usually raises @ref{4e9a,,PyExc_TypeError}.  If you have an argument whose
value must be in a particular range or must satisfy other conditions,
@ref{4e9c,,PyExc_ValueError} is appropriate.

You can also define a new exception that is unique to your module.
The simplest way to do this is to declare a static global object variable at
the beginning of the file:

@example
static PyObject *SpamError = NULL;
@end example

and initialize it by calling @ref{1481,,PyErr_NewException()} in the module's
@ref{b75,,Py_mod_exec} function (@code{spam_module_exec()}):

@example
SpamError = PyErr_NewException("spam.error", NULL, NULL);
@end example

Since @code{SpamError} is a global variable, it will be overwritten every time
the module is reinitialized, when the @ref{b75,,Py_mod_exec} function is called.

For now, let's avoid the issue: we will block repeated initialization by raising an
@ref{65b,,ImportError}:

@example
static PyObject *SpamError = NULL;

static int
spam_module_exec(PyObject *m)
@{
    if (SpamError != NULL) @{
        PyErr_SetString(PyExc_ImportError,
                        "cannot initialize spam module more than once");
        return -1;
    @}
    SpamError = PyErr_NewException("spam.error", NULL, NULL);
    if (PyModule_AddObjectRef(m, "SpamError", SpamError) < 0) @{
        return -1;
    @}

    return 0;
@}

static PyModuleDef_Slot spam_module_slots[] = @{
    @{Py_mod_exec, spam_module_exec@},
    @{0, NULL@}
@};

static struct PyModuleDef spam_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "spam",
    .m_size = 0,  // non-negative
    .m_slots = spam_module_slots,
@};

PyMODINIT_FUNC
PyInit_spam(void)
@{
    return PyModuleDef_Init(&spam_module);
@}
@end example

Note that the Python name for the exception object is @code{spam.error}.  The
@ref{1481,,PyErr_NewException()} function may create a class with the base class
being @ref{bcd,,Exception} (unless another class is passed in instead of @code{NULL}),
described in @ref{1c27,,組み込み例外}.

Note also that the @code{SpamError} variable retains a reference to the newly
created exception class; this is intentional!  Since the exception could be
removed from the module by external code, an owned reference to the class is
needed to ensure that it will not be discarded, causing @code{SpamError} to
become a dangling pointer. Should it become a dangling pointer, C code which
raises the exception could cause a core dump or other unintended side effects.

For now, the @ref{790,,Py_DECREF()} call to remove this reference is missing.
Even when the Python interpreter shuts down, the global @code{SpamError}
variable will not be garbage-collected. It will "leak".
We did, however, ensure that this will happen at most once per process.

We discuss the use of @ref{16ec,,PyMODINIT_FUNC} as a function return type later in this
sample.

The @code{spam.error} exception can be raised in your extension module using a
call to @ref{79c,,PyErr_SetString()} as shown below:

@example
static PyObject *
spam_system(PyObject *self, PyObject *args)
@{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    if (sts < 0) @{
        PyErr_SetString(SpamError, "System command failed");
        return NULL;
    @}
    return PyLong_FromLong(sts);
@}
@end example

@node 例に戻る,モジュールのメソッドテーブルと初期化関数,幕間小話 エラーと例外,C や C++ による Python の拡張
@anchor{extending/extending back-to-the-example}@anchor{4e9d}@anchor{extending/extending backtoexample}@anchor{4e9e}
@subsubsection 例に戻る


先ほどの関数の例に戻ると、今度は以下の実行文を理解できるはずです:

@example
if (!PyArg_ParseTuple(args, "s", &command))
    return NULL;
@end example

It returns @code{NULL} (the error indicator for functions returning object pointers)
if an error is detected in the argument list, relying on the exception set by
@ref{3c1,,PyArg_ParseTuple()}.  Otherwise the string value of the argument has been
copied to the local variable @code{command}.  This is a pointer assignment and
you are not supposed to modify the string to which it points (so in Standard C,
the variable @code{command} should properly be declared as @code{const char
*command}).

次の文では、 @ref{3c1,,PyArg_ParseTuple()} で得た文字列を渡して Unix 関数 @code{system()} を呼び出しています:

@example
sts = system(command);
@end example

Our @code{spam.system()} function must return the value of @code{sts} as a
Python object.  This is done using the function @ref{1bd0,,PyLong_FromLong()}.

@example
return PyLong_FromLong(sts);
@end example

上の場合では、整数オブジェクトを返します。(そう、整数ですら、 Python においてはヒープ上のオブジェクトなのです! )

何ら有用な値を返さない関数 (void を返す関数) に対応する Python の関数は @code{None} を返さねばなりません。関数に @code{None} を返させるには、以下のような慣用句を使います (この慣用句は @ref{168c,,Py_RETURN_NONE} マクロに実装されています):

@example
Py_INCREF(Py_None);
return Py_None;
@end example

@ref{4e9f,,Py_None} は特殊な Pyhton オブジェクトである @code{None} に対応する C での名前です。これまで見てきたようにほとんどのコンテキストで "エラー" を意味する @code{NULL} ポインタとは違い、 @code{None} は純粋な Python のオブジェクトです。

@node モジュールのメソッドテーブルと初期化関数,コンパイルとリンク,例に戻る,C や C++ による Python の拡張
@anchor{extending/extending methodtable}@anchor{4ea0}@anchor{extending/extending the-module-s-method-table-and-initialization-function}@anchor{4ea1}
@subsubsection モジュールのメソッドテーブルと初期化関数


I promised to show how @code{spam_system()} is called from Python programs.
First, we need to list its name and address in a "method table":

@example
static PyMethodDef spam_methods[] = @{
    ...
    @{"system",  spam_system, METH_VARARGS,
     "Execute a shell command."@},
    ...
    @{NULL, NULL, 0, NULL@}        /* Sentinel */
@};
@end example

リスト要素の三つ目のエントリ (@code{METH_VARARGS}) に注意してください。このエントリは、C 関数が使う呼び出し規約をインタプリタに教えるためのフラグです。通常この値は @code{METH_VARARGS} か @code{METH_VARARGS | METH_KEYWORDS} のはずです; @code{0} は旧式の @ref{3c1,,PyArg_ParseTuple()} の変化形が使われることを意味します。

@code{METH_VARARGS} だけを使う場合、C 関数は、Python レベルでの引数が @ref{3c1,,PyArg_ParseTuple()} が受理できるタプルの形式で渡されるものと想定しなければなりません; この関数についての詳細は下で説明します。

The @ref{4ea2,,METH_KEYWORDS} bit may be set in the third field if keyword
arguments should be passed to the function.  In this case, the C function should
accept a third @code{PyObject *} parameter which will be a dictionary of keywords.
Use @ref{624,,PyArg_ParseTupleAndKeywords()} to parse the arguments to such a
function.

メソッドテーブルはモジュール定義の構造体から参照されていなければなりません:

@example
static struct PyModuleDef spam_module = @{
    ...
    .m_methods = spam_methods,
    ...
@};
@end example

This structure, in turn, must be passed to the interpreter in the module's
initialization function.  The initialization function must be named
@code{PyInit_name()}, where `name' is the name of the module, and should be the
only non-@code{static} item defined in the module file:

@example
PyMODINIT_FUNC
PyInit_spam(void)
@{
    return PyModuleDef_Init(&spam_module);
@}
@end example

Note that @ref{16ec,,PyMODINIT_FUNC} declares the function as @code{PyObject *} return type,
declares any special linkage declarations required by the platform, and for C++
declares the function as @code{extern "C"}.

@code{PyInit_spam()} is called when each interpreter imports its module
@code{spam} for the first time.  (See below for comments about embedding Python.)
A pointer to the module definition must be returned via @ref{4ea3,,PyModuleDef_Init()},
so that the import machinery can create the module and store it in @code{sys.modules}.

When embedding Python, the @code{PyInit_spam()} function is not called
automatically unless there's an entry in the @ref{1b1b,,PyImport_Inittab} table.
To add the module to the initialization table, use @ref{1b1c,,PyImport_AppendInittab()},
optionally followed by an import of the module:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
@{
    PyStatus status;
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* 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 */
    status = PyConfig_SetBytesString(&config, &config.program_name, argv[0]);
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}

    /* Initialize the Python interpreter.  Required.
       If this step fails, it will be a fatal error. */
    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}
    PyConfig_Clear(&config);

    /* 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");
    @}

    // ... use Python C API here ...

    return 0;

  exception:
     PyConfig_Clear(&config);
     Py_ExitStatusException(status);
@}
@end example

@cartouche
@quotation 注釈 
If you declare a global variable or a local static one, the module may
experience unintended side-effects on re-initialisation, for example when
removing entries from @code{sys.modules} or importing compiled modules into
multiple interpreters within a process
(or following a @code{fork()} without an intervening @code{exec()}).
If module state is not yet fully @ref{166,,isolated},
authors should consider marking the module as having no support for subinterpreters
(via @ref{4ea4,,Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}).
@end quotation
@end cartouche

A more substantial example module is included in the Python source distribution
as @code{Modules/xxlimited.c}.  This file may be used as a template or simply
read as an example.

@node コンパイルとリンク,C から Python 関数を呼び出す,モジュールのメソッドテーブルと初期化関数,C や C++ による Python の拡張
@anchor{extending/extending compilation}@anchor{4ea5}@anchor{extending/extending compilation-and-linkage}@anchor{4ea6}
@subsubsection コンパイルとリンク


新しい拡張モジュールを使えるようになるまで、まだ二つの作業: コンパイルと、Python システムへのリンク、が残っています。動的読み込み (dynamic loading) を使っているのなら、作業の詳細は自分のシステムが使っている動的読み込みの形式によって変わるかもしれません; 詳しくは、拡張モジュールのビルドに関する章 (@ref{4ea7,,C および C++ 拡張のビルド} 章) や、Windows におけるビルドに関係する追加情報の章 (@ref{2224,,Windows 上での C および C++ 拡張モジュールのビルド} 章) を参照してください。

動的読み込みを使えなかったり、モジュールを常時 Python インタプリタの一部にしておきたい場合には、インタプリタのビルド設定を変更して再ビルドしなければならなくなるでしょう。Unixでは、幸運なことにこの作業はとても単純です: 単に自作のモジュールファイル (例えば @code{spammodule.c}) を展開したソース配布物の @code{Modules/}  ディレクトリに置き、 @code{Modules/Setup.local} に自分のファイルを説明する以下の一行:

@example
spam spammodule.o
@end example

を追加して、トップレベルのディレクトリで @code{make} を実行して、インタプリタを再ビルドするだけです。 @code{Modules/} サブディレクトリでも @code{make} を実行できますが、前もって '@code{make} Makefile' を実行して @code{Makefile} を再ビルドしておかなければならりません。(この作業は @code{Setup} ファイルを変更するたびに必要です。)

モジュールが別のライブラリとリンクされている必要がある場合、ライブラリも設定ファイルに列挙できます。例えば以下のようにします。

@example
spam spammodule.o -lX11
@end example

@node C から Python 関数を呼び出す,拡張モジュール関数でのパラメタ展開,コンパイルとリンク,C や C++ による Python の拡張
@anchor{extending/extending calling-python-functions-from-c}@anchor{4ea8}@anchor{extending/extending callingpython}@anchor{4ea9}
@subsubsection C から Python 関数を呼び出す


これまでは、Python からの C 関数の呼び出しに重点を置いて述べてきました。ところでこの逆: C からの Python 関数の呼び出しもまた有用です。とりわけ、いわゆる "コールバック" 関数をサポートするようなライブラリを作成する際にはこの機能が便利です。ある C インターフェースがコールバックを利用している場合、同等の機能を提供する Python コードでは、しばしば Python プログラマにコールバック機構を提供する必要があります; このとき実装では、 C で書かれたコールバック関数から Python で書かれたコールパック関数を呼び出すようにする必要があるでしょう。もちろん、他の用途も考えられます。

幸運なことに、Python インタプリタは簡単に再帰呼び出しでき、 Python 関数を呼び出すための標準インターフェースもあります。 (Python パーザを特定の入力文字を使って呼び出す方法について詳説するつもりはありません --- この方法に興味があるなら、 Python ソースコードの @code{Modules/main.c} にある、コマンドラインオプション @ref{1a8,,-c} の実装を見てください)

Python 関数の呼び出しは簡単です。まず、C のコードに対してコールバックを登録しようとする Python プログラムは、何らかの方法で Python の関数オブジェクトを渡さねばなりません。このために、コールバック登録関数 (またはその他のインターフェース) を提供せねばなりません。このコールバック登録関数が呼び出された際に、引き渡された Python 関数オブジェクトへのポインタをグローバル変数に --- あるいは、どこか適切な場所に --- 保存します (関数オブジェクトを @ref{78f,,Py_INCREF()} するようよく注意してください!)。例えば、以下のような関数がモジュールの一部になっていることでしょう:

@example
static PyObject *my_callback = NULL;

static PyObject *
my_set_callback(PyObject *dummy, PyObject *args)
@{
    PyObject *result = NULL;
    PyObject *temp;

    if (PyArg_ParseTuple(args, "O:set_callback", &temp)) @{
        if (!PyCallable_Check(temp)) @{
            PyErr_SetString(PyExc_TypeError, "parameter must be callable");
            return NULL;
        @}
        Py_XINCREF(temp);         /* Add a reference to new callback */
        Py_XDECREF(my_callback);  /* Dispose of previous callback */
        my_callback = temp;       /* Remember new callback */
        /* Boilerplate to return "None" */
        Py_INCREF(Py_None);
        result = Py_None;
    @}
    return result;
@}
@end example

This function must be registered with the interpreter using the
@ref{1721,,METH_VARARGS} flag; this is described in section @ref{4ea0,,モジュールのメソッドテーブルと初期化関数}.  The
@ref{3c1,,PyArg_ParseTuple()} function and its arguments are documented in section
@ref{4eaa,,拡張モジュール関数でのパラメタ展開}.

@ref{c5a,,Py_XINCREF()} および @ref{992,,Py_XDECREF()} は、オブジェクトに対する参照カウントをインクリメント/デクリメントするためのマクロで、 @code{NULL} ポインタが渡されても安全に操作できる形式です (とはいえ、上の流れでは `temp' が @code{NULL} になることはありません)。これらのマクロと参照カウントについては、 @ref{4eab,,参照カウント法} で説明しています。

@geindex PyObject_CallObject (C function)

その後、コールバック関数を呼び出す時が来たら、C 関数 @ref{4eac,,PyObject_CallObject()} を呼び出します。この関数には二つの引数: Python 関数と Python 関数の引数リストがあり、いずれも任意の Python オブジェクトを表すポインタ型です。引数リストは常にタプルオブジェクトでなければならず、その長さは引数の数になります。Python 関数を引数なしで呼び出すのなら、 @code{NULL} か空のタプルを渡します; 単一の引数で関数を呼び出すのなら、単要素 (singleton) のタプルを渡します。 @ref{3c2,,Py_BuildValue()} の書式文字列中に、ゼロ個または一個以上の書式化コードが入った丸括弧がある場合、この関数はタプルを返します。以下に例を示します:

@example
int arg;
PyObject *arglist;
PyObject *result;
...
arg = 123;
...
/* Time to call the callback */
arglist = Py_BuildValue("(i)", arg);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);
@end example

@ref{4eac,,PyObject_CallObject()} は Python オブジェクトへのポインタを返します: これは Python 関数からの戻り値になります。 @ref{4eac,,PyObject_CallObject()} は、引数に対して "参照カウント中立 (reference-count- neutral)" です。上の例ではタプルを生成して引数リストとして提供しており、このタプルは @ref{4eac,,PyObject_CallObject()} の呼び出し直後に @ref{790,,Py_DECREF()} されています。

@ref{4eac,,PyObject_CallObject()} は戻り値として "新しい" オブジェクト: 新規に作成されたオブジェクトか、既存のオブジェクトの参照カウントをインクリメントしたものを返します。従って、このオブジェクトをグローバル変数に保存したいのでないかぎり、たとえこの戻り値に興味がなくても (むしろ、そうであればなおさら!) 何がしかの方法で戻り値オブジェクトを @ref{790,,Py_DECREF()} しなければなりません。

とはいえ、戻り値を @ref{790,,Py_DECREF()} する前には、値が @code{NULL} でないかチェックしておくことが重要です。もし @code{NULL} なら、呼び出した Python 関数は例外を送出して終了させられています。 @ref{4eac,,PyObject_CallObject()} を呼び出しているコード自体もまた Python から呼び出されているのであれば、今度は C コードが自分を呼び出している Python コードにエラー標示値を返さねばなりません。それにより、インタプリタはスタックトレースを出力したり、例外を処理するための Python コードを呼び出したりできます。例外の送出が不可能だったり、したくないのなら、 @ref{1232,,PyErr_Clear()} を呼んで例外を消去しておかねばなりません。例えば以下のようにします:

@example
if (result == NULL)
    return NULL; /* Pass error back */
...use result...
Py_DECREF(result);
@end example

Python コールバック関数をどんなインターフェースにしたいかによっては、引数リストを @ref{4eac,,PyObject_CallObject()} に与えなければならない場合もあります。あるケースでは、コールバック関数を指定したのと同じインターフェースを介して、引数リストも渡されているかもしれません。また別のケースでは、新しいタプルを構築して引数リストを渡さねばならないかもしれません。この場合最も簡単なのは @ref{3c2,,Py_BuildValue()} を呼ぶやり方です。例えば、整数のイベントコードを渡したければ、以下のようなコードを使うことになるでしょう:

@example
PyObject *arglist;
...
arglist = Py_BuildValue("(l)", eventcode);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);
if (result == NULL)
    return NULL; /* Pass error back */
/* Here maybe use the result */
Py_DECREF(result);
@end example

@code{Py_DECREF(arglist)} が呼び出しの直後、エラーチェックよりも前に置かれていることに注意してください! また、厳密に言えば、このコードは完全ではありません: @ref{3c2,,Py_BuildValue()} はメモリ不足におちいるかもしれず、チェックしておくべきです。

通常の引数とキーワード引数をサポートする @ref{63d,,PyObject_Call()} を使って、キーワード引数を伴う関数呼び出しをすることができます。上の例と同じように、 @ref{3c2,,Py_BuildValue()} を作って辞書を作ります。

@example
PyObject *dict;
...
dict = Py_BuildValue("@{s:i@}", "name", val);
result = PyObject_Call(my_callback, NULL, dict);
Py_DECREF(dict);
if (result == NULL)
    return NULL; /* Pass error back */
/* Here maybe use the result */
Py_DECREF(result);
@end example

@node 拡張モジュール関数でのパラメタ展開,拡張モジュール関数のキーワードパラメタ,C から Python 関数を呼び出す,C や C++ による Python の拡張
@anchor{extending/extending extracting-parameters-in-extension-functions}@anchor{4ead}@anchor{extending/extending parsetuple}@anchor{4eaa}
@subsubsection 拡張モジュール関数でのパラメタ展開


@geindex PyArg_ParseTuple (C function)

@ref{3c1,,PyArg_ParseTuple()} 関数は以下のように宣言されています:

@example
int PyArg_ParseTuple(PyObject *arg, const char *format, ...);
@end example

引数 `arg' は C 関数から Python に渡される引数リストが入ったタプルオブジェクトでなければなりません。 `format' 引数は書式文字列で、 Python/C API リファレンスマニュアルの @ref{3d5,,引数の解釈と値の構築} で解説されている書法に従わねばなりません。残りの引数は、それぞれの変数のアドレスで、書式化文字列から決まる型になっていなければなりません。

@ref{3c1,,PyArg_ParseTuple()} は Python 側から与えられた引数が必要な型になっているか調べるのに対し、 @ref{3c1,,PyArg_ParseTuple()} は呼び出しの際に渡された C 変数のアドレスが有効な値を持つか調べられないことに注意してください: ここで間違いを犯すと、コードがクラッシュするかもしれませんし、少なくともでたらめなビットをメモリに上書きしてしまいます。慎重に!

呼び出し側に提供されるオブジェクトへの参照はすべて `借用' 参照 (borrowed reference) になります; これらのオブジェクトの参照カウントをデクリメントしてはなりません!

以下にいくつかの呼び出し例を示します:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
@end example

@example
int ok;
int i, j;
long k, l;
const char *s;
Py_ssize_t size;

ok = PyArg_ParseTuple(args, ""); /* No arguments */
    /* Python call: f() */
@end example

@example
ok = PyArg_ParseTuple(args, "s", &s); /* A string */
    /* Possible Python call: f('whoops!') */
@end example

@example
ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
    /* Possible Python call: f(1, 2, 'three') */
@end example

@example
ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
    /* A pair of ints and a string, whose size is also returned */
    /* Possible Python call: f((1, 2), 'three') */
@end example

@example
@{
    const char *file;
    const char *mode = "r";
    int bufsize = 0;
    ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
    /* A string, and optionally another string and an integer */
    /* Possible Python calls:
       f('spam')
       f('spam', 'w')
       f('spam', 'wb', 100000) */
@}
@end example

@example
@{
    int left, top, right, bottom, h, v;
    ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
             &left, &top, &right, &bottom, &h, &v);
    /* A rectangle and a point */
    /* Possible Python call:
       f(((0, 0), (400, 300)), (10, 10)) */
@}
@end example

@example
@{
    Py_complex c;
    ok = PyArg_ParseTuple(args, "D:myfunction", &c);
    /* a complex, also providing a function name for errors */
    /* Possible Python call: myfunction(1+2j) */
@}
@end example

@node 拡張モジュール関数のキーワードパラメタ,任意の値を構築する,拡張モジュール関数でのパラメタ展開,C や C++ による Python の拡張
@anchor{extending/extending keyword-parameters-for-extension-functions}@anchor{4eae}@anchor{extending/extending parsetupleandkeywords}@anchor{4eaf}
@subsubsection 拡張モジュール関数のキーワードパラメタ


@geindex PyArg_ParseTupleAndKeywords (C function)

@ref{624,,PyArg_ParseTupleAndKeywords()} は、以下のように宣言されています:

@example
int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                const char *format, char * const *kwlist, ...);
@end example

`arg' と `format' パラメタは @ref{3c1,,PyArg_ParseTuple()} のものと同じです。 `kwdict' パラメタはキーワード引数の入った辞書で、 Python ランタイムシステムから第三パラメタとして受け取ります。 `kwlist' パラメタは各パラメタを識別するための文字列からなる、 @code{NULL} 終端されたリストです; 各パラメタ名は `format' 中の型情報に対して左から右の順に照合されます。成功すると @ref{624,,PyArg_ParseTupleAndKeywords()} は真を返し、それ以外の場合には適切な例外を送出して偽を返します。

@cartouche
@quotation 注釈 
キーワード引数を使っている場合、タプルは入れ子にして使えません! `kwlist' 内に存在しないキーワードパラメタが渡された場合、 @ref{198,,TypeError} の送出を引き起こします。
@end quotation
@end cartouche

@geindex Philbrick@comma{} Geoff

以下にキーワードを使ったモジュール例を示します。これは Geoff Philbrick (@email{philbrick@@hks.com}) によるプログラム例をもとにしています:

@example
#define PY_SSIZE_T_CLEAN
#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 keywdarg_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "keywdarg",
    .m_size = 0,
    .m_methods = keywdarg_methods,
@};

PyMODINIT_FUNC
PyInit_keywdarg(void)
@{
    return PyModuleDef_Init(&keywdarg_module);
@}
@end example

@node 任意の値を構築する,参照カウント法,拡張モジュール関数のキーワードパラメタ,C や C++ による Python の拡張
@anchor{extending/extending building-arbitrary-values}@anchor{4eb0}@anchor{extending/extending buildvalue}@anchor{4eb1}
@subsubsection 任意の値を構築する


@ref{3c2,,Py_BuildValue()} は @ref{3c1,,PyArg_ParseTuple()} の対極に位置するものです。この関数は以下のように定義されています:

@example
PyObject *Py_BuildValue(const char *format, ...);
@end example

@ref{3c2,,Py_BuildValue()} は、 @ref{3c1,,PyArg_ParseTuple()} の認識する一連の書式単位に似た書式単位を認識します。ただし (関数への出力ではなく、入力に使われる) 引数はポインタではなく、ただの値でなければなりません。 Python から呼び出された C 関数が返す値として適切な、新たな Python オブジェクトを返します。

@ref{3c1,,PyArg_ParseTuple()} とは一つ違う点があります: @ref{3c1,,PyArg_ParseTuple()} は第一引数をタプルにする必要があります (Python の引数リストは内部的には常にタプルとして表現されるからです) が、 @ref{3c2,,Py_BuildValue()} はタプルを生成するとは限りません。 @ref{3c2,,Py_BuildValue()} は書式文字列中に書式単位が二つかそれ以上入っている場合にのみタプルを構築します。書式文字列が空なら、 @code{None} を返します。きっかり一つの書式単位なら、その書式単位が記述している何らかのオブジェクトになります。サイズが 0 や 1 のタプル返させたいのなら、書式文字列を丸括弧で囲います。

以下に例を示します (左に呼び出し例を、右に構築される Python 値を示します):

@example
Py_BuildValue("")                        None
Py_BuildValue("i", 123)                  123
Py_BuildValue("iii", 123, 456, 789)      (123, 456, 789)
Py_BuildValue("s", "hello")              'hello'
Py_BuildValue("y", "hello")              b'hello'
Py_BuildValue("ss", "hello", "world")    ('hello', 'world')
Py_BuildValue("s#", "hello", 4)          'hell'
Py_BuildValue("y#", "hello", 4)          b'hell'
Py_BuildValue("()")                      ()
Py_BuildValue("(i)", 123)                (123,)
Py_BuildValue("(ii)", 123, 456)          (123, 456)
Py_BuildValue("(i,i)", 123, 456)         (123, 456)
Py_BuildValue("[i,i]", 123, 456)         [123, 456]
Py_BuildValue("@{s:i,s:i@}",
              "abc", 123, "def", 456)    @{'abc': 123, 'def': 456@}
Py_BuildValue("((ii)(ii)) (ii)",
              1, 2, 3, 4, 5, 6)          (((1, 2), (3, 4)), (5, 6))
@end example

@node 参照カウント法,C++での拡張モジュール作成,任意の値を構築する,C や C++ による Python の拡張
@anchor{extending/extending refcounts}@anchor{4eab}@anchor{extending/extending reference-counts}@anchor{4eb2}
@subsubsection 参照カウント法


C や C++のような言語では、プログラマはヒープ上のメモリを動的に確保したり解放したりする責任があります。こうした作業は C では関数 @code{malloc()} や @code{free()} で行います。C++では本質的に同じ意味で演算子 @code{new} や @code{delete} が使われます。そこで、以下の議論は C の場合に限定して行います。

Every block of memory allocated with @code{malloc()} should eventually be
returned to the pool of available memory by exactly one call to @code{free()}.
It is important to call @code{free()} at the right time.  If a block's address
is forgotten but @code{free()} is not called for it, the memory it occupies
cannot be reused until the program terminates.  This is called a `memory
leak'.  On the other hand, if a program calls @code{free()} for a block and then
continues to use the block, it creates a conflict with reuse of the block
through another @code{malloc()} call.  This is called `using freed memory'.
It has the same bad consequences as referencing uninitialized data --- core
dumps, wrong results, mysterious crashes.

よくあるメモリリークの原因はコード中の普通でない処理経路です。例えば、ある関数があるメモリブロックを確保し、何らかの計算を行って、再度ブロックを解放するとします。さて、関数の要求仕様を変更して、計算に対するテストを追加すると、エラー条件を検出し、関数の途中で処理を戻すようになるかもしれません。この途中での終了が起きるとき、確保されたメモリブロックは解放し忘れやすいのです。コードが後で追加された場合には特にそうです。このようなメモリリークが一旦紛れ込んでしまうと、長い間検出されないままになることがよくあります: エラーによる関数の終了は、全ての関数呼び出しのに対してほんのわずかな割合しか起きず、その一方でほとんどの近代的な計算機は相当量の仮想記憶を持っているため、メモリリークが明らかになるのは、長い間動作していたプロセスがリークを起こす関数を何度も使った場合に限られるからです。従って、この種のエラーを最小限にとどめるようなコーディング規約や戦略を設けて、不慮のメモリリークを避けることが重要なのです。

Python は @code{malloc()} や @code{free()} を非常によく利用するため、メモリリークの防止に加え、解放されたメモリの使用を防止する戦略が必要です。このために選ばれたのが参照カウント法 (`reference counting') と呼ばれる手法です。参照カウント法の原理は簡単です: 全てのオブジェクトにはカウンタがあり、オブジェクトに対する参照がどこかに保存されたらカウンタをインクリメントし、オブジェクトに対する参照が削除されたらデクリメントします。カウンタがゼロになったら、オブジェクトへの最後の参照が削除されたことになり、オブジェクトは解放されます。

もう一つの戦略は自動ガベージコレクション (`automatic garbage collection') と呼ばれています。 (参照カウント法はガベージコレクション戦略の一つとして挙げられることもあるので、二つを区別するために筆者は "自動 (automatic)" を使っています。) 自動ガベージコレクションの大きな利点は、ユーザが @code{free()} を明示的によばなくてよいことにあります。 (速度やメモリの有効利用性も利点として主張されています --- が、これは確たる事実ではありません。) C における自動ガベージコレクションの欠点は、真に可搬性のあるガベージコレクタが存在しないということです。それに対し、参照カウント法は可搬性のある実装ができます (@code{malloc()} や @code{free()} を利用できるのが前提です --- C 標準はこれを保証しています)。いつの日か、十分可搬性のあるガベージコレクタが C で使えるようになるかもしれませんが、それまでは参照カウント法でやっていく以外にはないのです。

Python では、伝統的な参照カウント法の実装を行っている一方で、参照の循環を検出するために働く循環参照検出機構 (cycle detector) も提供しています。循環参照検出機構のおかげで、直接、間接にかかわらず循環参照の生成を気にせずにアプリケーションを構築できます; というのも、参照カウント法だけを使ったガベージコレクション実装にとって循環参照は弱点だからです。循環参照は、(間接参照の場合も含めて) 相互への参照が入ったオブジェクトから形成されるため、循環内のオブジェクトは各々非ゼロの参照カウントを持ちます。典型的な参照カウント法の実装では、たとえ循環参照を形成するオブジェクトに対して他に全く参照がないとしても、循環参照内のどのオブジェクトに属するメモリも再利用できません。

循環参照検出機構はそのようなガベージサイクル (前述したような循環参照オブジェクト) を検出して回収することができます。
@ref{64,,gc} モジュールそのような検出機構の実行 (@ref{1b3,,collect()} 関数) を提供するとともに、設定のためのインタフェースおよび検出機構を実行時に無効にする方法も提供しています。

@menu
* Python における参照カウント法:: 
* 所有権にまつわる規則:: 
* 薄氷:: 
* NULL ポインタ:: 

@end menu

@node Python における参照カウント法,所有権にまつわる規則,,参照カウント法
@anchor{extending/extending refcountsinpython}@anchor{4eb3}@anchor{extending/extending reference-counting-in-python}@anchor{4eb4}
@subsubsection Python における参照カウント法


Python には、参照カウントのインクリメントやデクリメントを処理する二つのマクロ、 @code{Py_INCREF(x)} と @code{Py_DECREF(x)} があります。 @ref{790,,Py_DECREF()} は、参照カウントがゼロに到達した際に、オブジェクトのメモリ解放も行います。柔軟性を持たせるために、 @code{free()} を直接呼び出しません --- その代わりにオブジェクトの型オブジェクト (`type object') を介します。このために (他の目的もありますが)、全てのオブジェクトには自身の型オブジェクトに対するポインタが入っています。

さて、まだ重大な疑問が残っています: いつ @code{Py_INCREF(x)} や @code{Py_DECREF(x)} を使えばよいのでしょうか? まず、いくつかの用語説明から始めさせてください。まず、オブジェクトは "占有 (own)" されることはありません; しかし、あるオブジェクトに対する参照の所有 `own a reference' はできます。オブジェクトの参照カウントは、そのオブジェクトが参照の所有を受けている回数と定義されています。参照の所有者は、参照が必要なくなった際に @ref{790,,Py_DECREF()} を呼び出す役割を担います。参照の所有権は委譲 (transfer) できます。所有参照 (owned reference) の放棄には、渡す、保存する、 @ref{790,,Py_DECREF()} を呼び出す、という三つの方法があります。所有参照を処理し忘れると、メモリリークを引き起こします。

オブジェクトに対する参照は、借用 (`borrow') も可能です。 @footnote{
参照を "借用する" というメタファは厳密には正しくありません: なぜなら、参照の所有者は依然として参照のコピーを持っているからです。
} 参照の借用者は、 @ref{790,,Py_DECREF()} を呼んではなりません。借用者は、参照の所有者から借用した期間を超えて参照を保持し続けてはなりません。所有者が参照を放棄した後で借用参照を使うと、解放済みメモリを使用してしまう危険があるので、絶対に避けねばなりません。 @footnote{
参照カウントが 1 以上かどうか調べる方法は `うまくいきません' --- 参照カウント自体も解放されたメモリ上にあるため、その領域が他のオブジェクトに使われている可能性があります!
}

参照の借用が参照の所有よりも優れている点は、コードがとりうるあらゆる処理経路で参照を廃棄しておくよう注意しなくて済むことです --- 別の言い方をすれば、借用参照の場合には、処理の途中で関数を終了してもメモリリークの危険を冒すことがない、ということです。逆に、所有よりも不利な点は、ごくまともに見えるコードが、実際には参照の借用元で放棄されてしまった後にその参照を使うかもしれないような微妙な状況があるということです。

@ref{78f,,Py_INCREF()} を呼び出すと、借用参照を所有参照に変更できます。この操作は参照の借用元の状態には影響しません --- @ref{78f,,Py_INCREF()} は新たな所有参照を生成し、参照の所有者が担うべき全ての責任を課します (つまり、新たな参照の所有者は、以前の所有者と同様、参照の放棄を適切に行わねばなりません)。

@node 所有権にまつわる規則,薄氷,Python における参照カウント法,参照カウント法
@anchor{extending/extending ownership-rules}@anchor{4eb5}@anchor{extending/extending ownershiprules}@anchor{4eb6}
@subsubsection 所有権にまつわる規則


オブジェクトへの参照を関数の内外に渡す場合には、オブジェクトの所有権が参照と共に渡されるか否かが常に関数インターフェース仕様の一部となります。

オブジェクトへの参照を返すほとんどの関数は、参照とともに所有権も渡します。特に、 @ref{1bd0,,PyLong_FromLong()} や @ref{3c2,,Py_BuildValue()} のように、新しいオブジェクトを生成する関数は全て所有権を相手に渡します。オブジェクトが実際には新たなオブジェクトでなくても、そのオブジェクトに対する新たな参照の所有権を得ます。例えば、 @ref{1bd0,,PyLong_FromLong()} はよく使う値をキャッシュしており、キャッシュされた値への参照を返すことがあります。

@ref{5ef,,PyObject_GetAttrString()} のように、あるオブジェクトから別のオブジェクトを抽出するような関数もまた、参照とともに所有権を委譲します。こちらの方はやや理解しにくいかもしれません。というのはよく使われるルーチンのいくつかが例外となっているからです: @ref{4eb7,,PyTuple_GetItem()} 、 @ref{5ff,,PyList_GetItem()} 、 @ref{628,,PyDict_GetItem()} 、および @ref{629,,PyDict_GetItemString()} は全て、タプル、リスト、または辞書から借用参照を返します。

@ref{5fc,,PyImport_AddModule()} は、実際にはオブジェクトを生成して返すことがあるにもかかわらず、借用参照を返します: これが可能なのは、生成されたオブジェクトに対する所有参照は @code{sys.modules} に保持されるからです。

オブジェクトへの参照を別の関数に渡す場合、一般的には、関数側は呼び出し手から参照を借用します --- 参照を保存する必要があるなら、関数側は @ref{78f,,Py_INCREF()} を呼び出して独立した所有者になります。とはいえ、この規則には二つの重要な例外: @ref{4eb8,,PyTuple_SetItem()} と @ref{18ba,,PyList_SetItem()} があります。これらの関数は、渡された引数要素に対して所有権を乗っ取り (take over) ます --- たとえ失敗してもです! (@ref{4eb9,,PyDict_SetItem()} とその仲間は所有権を乗っ取りません --- これらはいわば "普通の" 関数です。)

Python から C 関数が呼び出される際には、C 関数は呼び出し側から引数への参照を借用します。C 関数の呼び出し側はオブジェクトへの参照を所有しているので、借用参照の生存期間が保証されるのは関数が処理を返すまでです。このようにして借用参照を保存したり他に渡したりしたい場合にのみ、 @ref{78f,,Py_INCREF()} を使って所有参照にする必要があります。

Python から呼び出された C 関数が返す参照は所有参照でなければなりません --- 所有権は関数から呼び出し側へと委譲されます。

@node 薄氷,NULL ポインタ,所有権にまつわる規則,参照カウント法
@anchor{extending/extending thin-ice}@anchor{4eba}@anchor{extending/extending thinice}@anchor{4ebb}
@subsubsection 薄氷


数少ない状況において、一見無害に見える借用参照の利用が問題をひきおこすことがあります。この問題はすべて、インタプリタが非明示的に呼び出され、インタプリタが参照の所有者に参照を放棄させてしまう状況と関係しています。

知っておくべきケースのうち最初の、そして最も重要なものは、リスト要素に対する参照を借りている際に起きる、関係ないオブジェクトに対する @ref{790,,Py_DECREF()} の使用です。例えば:

@example
void
bug(PyObject *list)
@{
    PyObject *item = PyList_GetItem(list, 0);

    PyList_SetItem(list, 1, PyLong_FromLong(0L));
    PyObject_Print(item, stdout, 0); /* BUG! */
@}
@end example

上の関数はまず、 @code{list[0]} への参照を借用し、次に @code{list[1]} を値 @code{0} で置き換え、最後にさきほど借用した参照を出力しています。何も問題ないように見えますね? でもそうではないのです!

Let's follow the control flow into @ref{18ba,,PyList_SetItem()}.  The list owns
references to all its items, so when item 1 is replaced, it has to dispose of
the original item 1.  Now let's suppose the original item 1 was an instance of a
user-defined class, and let's further suppose that the class defined a
@code{__del__()} method.  If this class instance has a reference count of 1,
disposing of it will call its @code{__del__()} method. Internally,
@ref{18ba,,PyList_SetItem()} calls @ref{790,,Py_DECREF()} on the replaced item,
which invokes replaced item's corresponding
@ref{4ebc,,tp_dealloc} function. During
deallocation, @ref{4ebc,,tp_dealloc} calls
@ref{c9d,,tp_finalize}, which is mapped to the
@code{__del__()} method for class instances (see 
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/}). This entire
sequence happens synchronously within the @ref{18ba,,PyList_SetItem()} call.

Since it is written in Python, the @code{__del__()} method can execute arbitrary
Python code.  Could it perhaps do something to invalidate the reference to
@code{item} in @code{bug()}?  You bet!  Assuming that the list passed into
@code{bug()} is accessible to the @code{__del__()} method, it could execute a
statement to the effect of @code{del list[0]}, and assuming this was the last
reference to that object, it would free the memory associated with it, thereby
invalidating @code{item}.

問題の原因が分かれば、解決は簡単です。一時的に参照回数を増やせばよいのです。正しく動作するバージョンは以下のようになります:

@example
void
no_bug(PyObject *list)
@{
    PyObject *item = PyList_GetItem(list, 0);

    Py_INCREF(item);
    PyList_SetItem(list, 1, PyLong_FromLong(0L));
    PyObject_Print(item, stdout, 0);
    Py_DECREF(item);
@}
@end example

This is a true story.  An older version of Python contained variants of this bug
and someone spent a considerable amount of time in a C debugger to figure out
why his @code{__del__()} methods would fail...

The second case of problems with a borrowed reference is a variant involving
threads.  Normally, multiple threads in the Python interpreter can't get in each
other's way, because there is a @ref{474,,global lock}
protecting Python's entire object space.
However, it is possible to temporarily release this lock using the macro
@ref{4ebd,,Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using
@ref{c7f,,Py_END_ALLOW_THREADS}.  This is common around blocking I/O calls, to
let other threads use the processor while waiting for the I/O to complete.
Obviously, the following function has the same problem as the previous one:

@example
void
bug(PyObject *list)
@{
    PyObject *item = PyList_GetItem(list, 0);
    Py_BEGIN_ALLOW_THREADS
    ...some blocking I/O call...
    Py_END_ALLOW_THREADS
    PyObject_Print(item, stdout, 0); /* BUG! */
@}
@end example

@node NULL ポインタ,,薄氷,参照カウント法
@anchor{extending/extending null-pointers}@anchor{4ebe}@anchor{extending/extending nullpointers}@anchor{4ebf}
@subsubsection NULL ポインタ


一般論として、オブジェクトへの参照を引数にとる関数はユーザが @code{NULL} ポインタを渡すとは予想しておらず、渡そうとするとコアダンプになる (か、あとでコアダンプを引き起こす) ことでしょう。一方、オブジェクトへの参照を返すような関数は一般に、例外の発生を示す場合にのみ @code{NULL} を返します。引数に対して @code{NULL} テストを行わない理由は、関数はしばしば受け取ったオブジェクトを他の関数へと引き渡すからです --- 各々の関数が @code{NULL} テストを行えば、冗長なテストが大量に行われ、コードはより低速に動くことになります。

従って、 @code{NULL} のテストはオブジェクトの "発生源"、すなわち値が @code{NULL} になるかもしれないポインタを受け取ったときだけにしましょう。 @code{malloc()} や、例外を送出する可能性のある関数がその例です。

マクロ @ref{78f,,Py_INCREF()} および @ref{790,,Py_DECREF()} は @code{NULL} ポインタのチェックを行いません --- しかし、これらのマクロの変化形である @ref{c5a,,Py_XINCREF()} および @ref{992,,Py_XDECREF()} はチェックを行います。

特定のオブジェクト型について調べるマクロ (@code{Pytype_Check()}) は `NULL' ポインタのチェックを行いません --- 繰り返しますが、様々な異なる型を想定してオブジェクトの型を調べる際には、こうしたマクロを続けて呼び出す必要があるので、個別に @code{NULL} ポインタのチェックをすると冗長なテストになってしまうのです。型を調べるマクロには、 @code{NULL} チェックを行う変化形はありません。

Python から C 関数を呼び出す機構は、C 関数に渡される引数リスト (例でいうところの @code{args}) が決して @code{NULL} にならないよう保証しています --- 実際には、常にタプル型になるよう保証しています。@footnote{
"旧式の" 呼び出し規約を使っている場合には、この保証は適用されません --- 既存のコードにはいまだに旧式の呼び出し規約が多々あります。
}

@code{NULL} ポインタを Python ユーザレベルに "逃がし" てしまうと、深刻なエラーを引き起こします。

@c Frank Stajano:
@c A pedagogically buggy example, along the lines of the previous listing, would
@c be helpful here -- showing in more concrete terms what sort of actions could
@c cause the problem. I can't very well imagine it from the description.

@node C++での拡張モジュール作成,拡張モジュールに C API を提供する,参照カウント法,C や C++ による Python の拡張
@anchor{extending/extending cplusplus}@anchor{4ec0}@anchor{extending/extending writing-extensions-in-c}@anchor{4ec1}
@subsubsection C++での拡張モジュール作成


C++でも拡張モジュールは作成できます。ただしいくつか制限があります。メインプログラム (Python インタプリタ) は C コンパイラでコンパイルされリンクされているので、グローバル変数や静的オブジェクトをコンストラクタで作成できません。メインプログラムが C++ コンパイラでリンクされているならこれは問題ではありません。 Python インタプリタから呼び出される関数 (特にモジュール初期化関数) は、 @code{extern "C"} を使って宣言しなければなりません。また、Python ヘッダファイルを @code{extern "C" @{...@}} に入れる必要はありません--- シンボル @code{__cplusplus} (最近の C++ コンパイラは全てこのシンボルを定義しています) が定義されているときに @code{extern "C" @{...@}} が行われるように、ヘッダファイル内にすでに書かれているからです。

@node 拡張モジュールに C API を提供する,,C++での拡張モジュール作成,C や C++ による Python の拡張
@anchor{extending/extending providing-a-c-api-for-an-extension-module}@anchor{4ec2}@anchor{extending/extending using-capsules}@anchor{1575}
@subsubsection 拡張モジュールに C API を提供する


多くの拡張モジュールは単に Python から使える新たな関数や型を提供するだけですが、時に拡張モジュール内のコードが他の拡張モジュールでも便利なことがあります。例えば、あるモジュールでは順序概念のないリストのように動作する "コレクション (collection)" クラスを実装しているかもしれません。ちょうどリストを生成したり操作したりできる C API を備えた標準の Python リスト型のように、この新たなコレクション型も他の拡張モジュールから直接操作できるようにするには一連の C 関数を持っていなければなりません。

一見するとこれは簡単なこと: 単に関数を (もちろん @code{static} などとは宣言せずに) 書いて、適切なヘッダファイルを提供し、C API を書けばよいだけ、に思えます。そして実際のところ、全ての拡張モジュールが Python インタプリタに常に静的にリンクされている場合にはうまく動作します。ところがモジュールが共有ライブラリの場合には、一つのモジュールで定義されているシンボルが他のモジュールから不可視なことがあります。可視性の詳細はオペレーティングシステムによります; あるシステムは Python インタプリタと全ての拡張モジュール用に単一のグローバルな名前空間を用意しています (例えば Windows)。別のシステムはモジュールのリンク時に取り込まれるシンボルを明示的に指定する必要があります (AIX がその一例です)、また別のシステム (ほとんどの Unix) では、違った戦略を選択肢として提供しています。そして、たとえシンボルがグローバル変数として可視であっても、呼び出したい関数の入ったモジュールがまだロードされていないことだってあります!

従って、可搬性の点からシンボルの可視性には何ら仮定をしてはならないことになります。つまり拡張モジュール中の全てのシンボルは @code{static} と宣言せねばなりません。例外はモジュールの初期化関数で、これは (@ref{4ea0,,モジュールのメソッドテーブルと初期化関数} で述べたように) 他の拡張モジュールとの間で名前が衝突するのを避けるためです。また、他の拡張モジュールからアクセスを `受けるべきではない' シンボルは別のやり方で公開せねばなりません。

Python はある拡張モジュールの C レベルの情報 (ポインタ) を別のモジュールに渡すための特殊な機構: Capsule (カプセル)を提供しています。 Capsule はポインタ (void*) を記憶する Python のデータ型です。 Capsule は C API を介してのみ生成したりアクセスしたりできますが、他の Python オブジェクトと同じように受け渡しできます。とりわけ、Capsule は拡張モジュールの名前空間内にある名前に代入できます。他の拡張モジュールはこのモジュールを import でき、次に名前を取得し、最後にCapsule へのポインタを取得します。

拡張モジュールの C API を公開するために、様々な方法で Capsule が使われます。各関数を1つのオブジェクトに入れたり、全ての C API のポインタ配列を Capsule に入れることができます。そして、ポインタに対する保存や取得といった様々な作業は、コードを提供しているモジュールとクライアントモジュールとの間では異なる方法で分散できます。

どの方法を選ぶにしても、 Capsule の name を正しく設定することは重要です。 @ref{4ec3,,PyCapsule_New()} は name 引数 (const char*) を取ります。 @code{NULL} を name に渡すことも許可されていますが、 name を設定することを強く推奨します。正しく名前を付けられた Capsule はある程度の実行時型安全性を持ちます。名前を付けられていない Capsule を他の Capsule と区別する現実的な方法はありません。

特に、 C API を公開するための Capsule には次のルールに従った名前を付けるべきです:

@example
modulename.attributename
@end example

@ref{1c10,,PyCapsule_Import()} という便利関数は、 Capsule の名前がこのルールに一致しているときにのみ、簡単に Capsule 経由で公開されている C API をロードすることができます。この挙動により、 C API のユーザーが、確実に正しい C API を格納している Capsule をロードできたことを確かめることができます。

以下の例では、名前を公開するモジュールの作者にほとんどの負荷が掛かりますが、よく使われるライブラリを作る際に適切なアプローチを実演します。このアプローチでは、全ての C API ポインタ (例中では一つだけですが!) を、 Capsule の値となる void ポインタの配列に保存します。拡張モジュールに対応するヘッダファイルは、モジュールの import と C API ポインタを取得するよう手配するマクロを提供します; クライアントモジュールは、C API にアクセスする前にこのマクロを呼ぶだけです。

The exporting module is a modification of the @code{spam} module from section
@ref{4e94,,簡単な例}. The function @code{spam.system()} does not call
the C library function @code{system()} directly, but a function
@code{PySpam_System()}, which would of course do something more complicated in
reality (such as adding "spam" to every command). This function
@code{PySpam_System()} is also exported to other extension modules.

The function @code{PySpam_System()} is a plain C function, declared
@code{static} like everything else:

@example
static int
PySpam_System(const char *command)
@{
    return system(command);
@}
@end example

The function @code{spam_system()} is modified in a trivial way:

@example
static PyObject *
spam_system(PyObject *self, PyObject *args)
@{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = PySpam_System(command);
    return PyLong_FromLong(sts);
@}
@end example

モジュールの先頭にある以下の行

@example
#include <Python.h>
@end example

の直後に、以下の二行を必ず追加してください:

@example
#define SPAM_MODULE
#include "spammodule.h"
@end example

The @code{#define} is used to tell the header file that it is being included in the
exporting module, not a client module. Finally, the module's @ref{b75,,mod_exec} function must take care of initializing the C API pointer array:

@example
static int
spam_module_exec(PyObject *m)
@{
    static void *PySpam_API[PySpam_API_pointers];
    PyObject *c_api_object;

    /* 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_Add(m, "_C_API", c_api_object) < 0) @{
        return -1;
    @}

    return 0;
@}
@end example

Note that @code{PySpam_API} is declared @code{static}; otherwise the pointer
array would disappear when @code{PyInit_spam()} terminates!

からくりの大部分はヘッダファイル @code{spammodule.h} 内にあり、以下のようになっています:

@example
#ifndef Py_SPAMMODULE_H
#define Py_SPAMMODULE_H
#ifdef __cplusplus
extern "C" @{
#endif

/* Header file for spammodule */

/* C API functions */
#define PySpam_System_NUM 0
#define PySpam_System_RETURN int
#define PySpam_System_PROTO (const char *command)

/* Total number of C API pointers */
#define PySpam_API_pointers 1


#ifdef SPAM_MODULE
/* This section is used when compiling spammodule.c */

static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;

#else
/* This section is used in modules that use spammodule's API */

static void **PySpam_API;

#define PySpam_System \
 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])

/* Return -1 on error, 0 on success.
 * PyCapsule_Import will set an exception if there's an error.
 */
static int
import_spam(void)
@{
    PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
    return (PySpam_API != NULL) ? 0 : -1;
@}

#endif

#ifdef __cplusplus
@}
#endif

#endif /* !defined(Py_SPAMMODULE_H) */
@end example

All that a client module must do in order to have access to the function
@code{PySpam_System()} is to call the function (or rather macro)
@code{import_spam()} in its @ref{b75,,mod_exec} function:

@example
static int
client_module_exec(PyObject *m)
@{
    if (import_spam() < 0) @{
        return -1;
    @}
    /* additional initialization can happen here */
    return 0;
@}
@end example

このアプローチの主要な欠点は、 @code{spammodule.h} がやや難解になるということです。とはいえ、各関数の基本的な構成は公開されるものと同じなので、書き方を一度だけ学べばすみます。

最後に、Capsule は、自身に保存されているポインタをメモリ確保したり解放したりする際に特に便利な、もう一つの機能を提供しているということに触れておかねばなりません。詳細は Python/C API リファレンスマニュアルの @ref{29f3,,カプセル}, および Capsule の実装部分 (Python ソースコード配布物中のファイル @code{Include/pycapsule.h} および @code{Objects/pycapsule.c} に述べられています。

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 拡張の型の定義 チュートリアル,拡張の型の定義 雑多なトピック,C や C++ による Python の拡張,サードパーティツールなしで拡張を作る
@anchor{extending/newtypes_tutorial doc}@anchor{1bbb}@anchor{extending/newtypes_tutorial defining-extension-types-tutorial}@anchor{4ec4}@anchor{extending/newtypes_tutorial defining-new-types}@anchor{4ec5}@anchor{extending/newtypes_tutorial translation-repo}@anchor{4ec6}
@subsection 拡張の型の定義: チュートリアル


Python では、組み込みの @ref{169,,str} 型や @ref{24d,,list} 型のような Python コードから操作できる新しい型を C 拡張モジュールの作者が定義できます。
全ての拡張の型のコードはあるパターンに従うのですが、書き始める前に理解しておくべき細かいことがあります。
このドキュメントはその話題についてのやさしい入門です。

@menu
* 基本的なこと:: 
* 基本のサンプルにデータとメソッドを追加する:: 
* データ属性をこまかく制御する:: 
* 循環ガベージコレクションをサポートする:: 
* 他の型のサブクラスを作る:: 

@end menu

@node 基本的なこと,基本のサンプルにデータとメソッドを追加する,,拡張の型の定義 チュートリアル
@anchor{extending/newtypes_tutorial dnt-basics}@anchor{4ec7}@anchor{extending/newtypes_tutorial the-basics}@anchor{4ec8}
@subsubsection 基本的なこと


@ref{905,,CPython} ランタイムは Python の全てのオブジェクトを、 Python の全てのオブジェクトの "基底型 (base type)" である @ref{5df,,PyObject}* 型の変数と見なします。 @ref{5df,,PyObject} 構造体自身は @ref{4ec9,,参照カウント} と、オブジェクトの "型オブジェクト" へのポインタのみを持ちます。ここには動作が定義されています; 型オブジェクトは、例えば、ある属性があるオブジェクトから検索されたり、メソッドが呼ばれたり、他のオブジェクトによって操作されたりしたときに、どの (C) 関数がインタープリターから呼ばれるのかを決定します。これらの C 関数は "型メソッド (type method)" と呼ばれます。

それなので、新しい拡張の型を定義したいときは、新しい型オブジェクトを作成すればよいわけです。

この手のことは例を見たほうが早いでしょうから、以下に C 拡張モジュール @code{custom} にある @code{Custom} という名前の新しい型を定義する、最小限ながら完全なモジュールをあげておきます:

@cartouche
@quotation 注釈 
ここで紹介している例は、 `静的な' 拡張の型を定義する伝統的な実装方法です。
これはほとんどの場面で十分なものなのです。
C API では、 @ref{79d,,PyType_FromSpec()} 関数を使い、ヒープ上に配置された拡張の型も定義できますが、これについてはこのチュートリアルでは扱いません。
@end quotation
@end cartouche

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

typedef struct @{
    PyObject_HEAD
    /* Type-specific fields go here. */
@} CustomObject;

static PyTypeObject CustomType = @{
    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
@};

static int
custom_module_exec(PyObject *m)
@{
    if (PyType_Ready(&CustomType) < 0) @{
        return -1;
    @}

    if (PyModule_AddObjectRef(m, "Custom", (PyObject *) &CustomType) < 0) @{
        return -1;
    @}

    return 0;
@}

static PyModuleDef_Slot custom_module_slots[] = @{
    @{Py_mod_exec, custom_module_exec@},
    // Just use this while using static types
    @{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED@},
    @{0, NULL@}
@};

static PyModuleDef custom_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "custom",
    .m_doc = "Example module that creates an extension type.",
    .m_size = 0,
    .m_slots = custom_module_slots,
@};

PyMODINIT_FUNC
PyInit_custom(void)
@{
    return PyModuleDef_Init(&custom_module);
@}
@end example

一度に把握するにはちょっと量が多いですが、前の章よりはとっつきやすくなっていることと思います。このファイルでは、3つの要素が定義されています:


@enumerate 

@item 
@code{Custom} `オブジェクト' が何を含んでいるか: これが @code{CustomObject} 構造体で、 @code{Custom} インスタンスごとに1回だけメモリ確保が行われます。

@item 
@code{Custom} `型' がどのように振る舞うか: これが @code{CustomType} 構造体で、フラグと関数ポインタの集まりを定義しています。特定の操作が要求されたときに、この関数ポインタをインタープリターが見に行きます。

@item 
How to define and execute the @code{custom} module: this is the
@code{PyInit_custom} function and the associated @code{custom_module} struct for
defining the module, and the @code{custom_module_exec} function to set up
a fresh module object.
@end enumerate

まず最初はこれです:

@example
typedef struct @{
    PyObject_HEAD
@} CustomObject;
@end example

これが Custom オブジェクトの内容です。 @code{PyObject_HEAD} はそれぞれのオブジェクト構造体の先頭に必須なもので、 @ref{5df,,PyObject} 型の @code{ob_base} という名前のフィールドを定義します。 @ref{5df,,PyObject} 型には (それぞれ @ref{3c9,,Py_TYPE} マクロおよび @ref{2cf,,Py_REFCNT} マクロからアクセスできる) 型オブジェクトへのポインタと参照カウントが格納されています。このマクロが用意されている理由は、構造体のレイアウトを抽象化し、デバッグビルドでフィールドを追加できるようにするためです。

@cartouche
@quotation 注釈 
上の例では @ref{14f5,,PyObject_HEAD} マクロの後にセミコロンはありません。
うっかりセミコロンを追加しないように気を付けてください: これを警告するコンパイラもあります。
@end quotation
@end cartouche

もちろん、一般的にはオブジェクトは標準的な @code{PyObject_HEAD} ボイラープレートの他にもデータを保持しています; 例えば、これは Python 標準の浮動小数点数の定義です:

@example
typedef struct @{
    PyObject_HEAD
    double ob_fval;
@} PyFloatObject;
@end example

2つ目は型オブジェクトの定義です。

@example
static PyTypeObject CustomType = @{
    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
@};
@end example

@cartouche
@quotation 注釈 
上にあるように C99 スタイルの指示付き初期化子を使って、 @ref{c9c,,PyTypeObject} の特に関心の無いフィールドまで全て並べたり、フィールドを宣言する順序に気を使ったりせずに済ませるのをお薦めします。
@end quotation
@end cartouche

@code{object.h} にある実際の @ref{c9c,,PyTypeObject} の定義には上の定義にあるよりももっと多くの @ref{b84,,フィールド} があります。
ここに出てきていないフィールドは C コンパイラによってゼロで埋められるので、必要でない限り明示的には値の指定をしないのが一般的な作法になっています。

一度に1つずつフィールドを取り上げていきましょう:

@example
.ob_base = PyVarObject_HEAD_INIT(NULL, 0)
@end example

この行は、上で触れた @code{ob_base} フィールドの初期化に必須のボイラープレートです。

@example
.tp_name = "custom.Custom",
@end example

実装している型の名前です。
これは、オブジェクトのデフォルトの文字列表現やエラーメッセージに現れます。例えば次の通りです:

@example
>>> "" + custom.Custom()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "custom.Custom") to str
@end example

型の名前が、モジュール名とモジュールにおける型の名前の両方をドットでつないだ名前になっていることに注意してください。この場合は、モジュールは @code{custom} で型は @code{Custom} なので、型の名前を @code{custom.Custom} に設定しました。実際のドット付きのインポートパスを使うのは、 @ref{ba,,pydoc} モジュールや @ref{ab,,pickle} モジュールと互換性を持たせるために重要なのです。

@example
.tp_basicsize = sizeof(CustomObject),
.tp_itemsize = 0,
@end example

これは、新しい @code{Custom} インスタンスを作るときに Python が割り当てるべきメモリがどのくらいなのかを知るためのものです。 @ref{23bb,,tp_itemsize} は可変サイズのオブジェクトでのみ使うものなので、サイズが可変でないオブジェクトでは 0 にすべきです。

@cartouche
@quotation 注釈 
If you want your type to be subclassable from Python, and your type has the same
@ref{b7e,,tp_basicsize} as its base type, you may have problems with multiple
inheritance.  A Python subclass of your type will have to list your type first
in its @ref{16c5,,__bases__}, or else it will not be able to call your type's
@ref{7a0,,__new__()} method without getting an error.  You can avoid this problem by
ensuring that your type has a larger value for @ref{b7e,,tp_basicsize} than its
base type does.  Most of the time, this will be true anyway, because either your
base type will be @ref{c7e,,object}, or else you will be adding data members to
your base type, and therefore increasing its size.
@end quotation
@end cartouche

@ref{4eca,,Py_TPFLAGS_DEFAULT} にクラスフラグを設定します。

@example
.tp_flags = Py_TPFLAGS_DEFAULT,
@end example

すべての型はフラグにこの定数を含めておく必要があります。これは最低でも Python 3.3 までに定義されているすべてのメンバを許可します。それ以上のメンバが必要なら、対応するフラグの OR をとる必要があります。

この型の docstring は @ref{4ecb,,tp_doc} に入れます。

@example
.tp_doc = PyDoc_STR("Custom objects"),
@end example

オブジェクトが生成できるように、 @ref{79f,,tp_new} ハンドラを提供する必要があります。これは Python のメソッド @ref{7a0,,__new__()} と同等のものですが、明示的に与える必要があります。今の場合では、 API 関数の @ref{4ecc,,PyType_GenericNew()} として提供されるデフォルトの実装をそのまま使えます。

@example
.tp_new = PyType_GenericNew,
@end example

Everything else in the file should be familiar, except for some code in
@code{custom_module_exec()}:

@example
if (PyType_Ready(&CustomType) < 0) @{
    return -1;
@}
@end example

これは、 @code{NULL} に初期化された @ref{4ecd,,ob_type} も含めて、いくつかのメンバーを適切なデフォルト値で埋めて、 @code{Custom} 型を初期化します。

@example
if (PyModule_AddObjectRef(m, "Custom", (PyObject *) &CustomType) < 0) @{
    return -1;
@}
@end example

これは型をモジュールの辞書に追加します。こうすることで @code{Custom} クラスの呼び出しで @code{Custom} インスタンスが作成できるようになります:

@example
>>> import custom
>>> mycustom = custom.Custom()
@end example

以上です!残りの作業はビルドだけです; @code{custom.c} という名前のファイルにここまでのコードを書き込み、

@example
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

[project]
name = "custom"
version = "1"
@end example

@code{pyproject.toml} というファイルにこれを書き込み、

@example
from setuptools import Extension, setup
setup(ext_modules=[Extension("custom", ["custom.c"])])
@end example

そして @code{setup.py} というファイルにこのように書き込み、そして、以下のように

@example
$ python -m pip install .
@end example

シェルに入力します。これにより、サブディレクトリに @code{custom.so} が生成され、インストールされます。これで、 Python を立ち上げて、 @code{import custom} すると @code{Custom} オブジェクトで遊べるようになっているはずです。

そんなにむずかしくありません、よね?

もちろん、現在の Custom 型は面白みに欠けています。何もデータを持っていないし、何もできません。継承してサブクラスを作ることさえできないのです。

@node 基本のサンプルにデータとメソッドを追加する,データ属性をこまかく制御する,基本的なこと,拡張の型の定義 チュートリアル
@anchor{extending/newtypes_tutorial adding-data-and-methods-to-the-basic-example}@anchor{4ece}
@subsubsection 基本のサンプルにデータとメソッドを追加する


この基本のサンプルにデータとメソッドを追加してみましょう。ついでに、この型を基底クラスとしても利用できるようにします。ここでは新しいモジュール @code{custom2} をつくり、これらの機能を追加します:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stddef.h> /* for offsetof() */

typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;

static void
Custom_dealloc(PyObject *op)
@{
    CustomObject *self = (CustomObject *) op;
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free(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 = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}

static int
Custom_init(PyObject *op, PyObject *args, PyObject *kwds)
@{
    CustomObject *self = (CustomObject *) op;
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        Py_XSETREF(self->first, Py_NewRef(first));
    @}
    if (last) @{
        Py_XSETREF(self->last, Py_NewRef(last));
    @}
    return 0;
@}

static PyMemberDef Custom_members[] = @{
    @{"first", Py_T_OBJECT_EX, offsetof(CustomObject, first), 0,
     "first name"@},
    @{"last", Py_T_OBJECT_EX, offsetof(CustomObject, last), 0,
     "last name"@},
    @{"number", Py_T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_name(PyObject *op, PyObject *Py_UNUSED(dummy))
@{
    CustomObject *self = (CustomObject *) op;
    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", Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};

static PyTypeObject CustomType = @{
    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom2.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_new = Custom_new,
    .tp_init = Custom_init,
    .tp_dealloc = Custom_dealloc,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
@};

static int
custom_module_exec(PyObject *m)
@{
    if (PyType_Ready(&CustomType) < 0) @{
        return -1;
    @}

    if (PyModule_AddObjectRef(m, "Custom", (PyObject *) &CustomType) < 0) @{
        return -1;
    @}

    return 0;
@}

static PyModuleDef_Slot custom_module_slots[] = @{
    @{Py_mod_exec, custom_module_exec@},
    @{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED@},
    @{0, NULL@}
@};

static PyModuleDef custom_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "custom2",
    .m_doc = "Example module that creates an extension type.",
    .m_size = 0,
    .m_slots = custom_module_slots,
@};

PyMODINIT_FUNC
PyInit_custom2(void)
@{
    return PyModuleDef_Init(&custom_module);
@}
@end example

モジュールのこのバージョンでは、いくつもの変更をおこないます。

@code{Custom} 型は そのC構造体に 3つのデータ属性 `first' 、 `last' 、および `number' をもつようになりました。 `first' と `last' 属性はファーストネームとラストネームを格納した Python 文字列で、 `number' 属性は C言語での整数の値です。

これにしたがうと、オブジェクトの構造体は次のようになります:

@example
typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;
@end example

いまや管理すべきデータができたので、オブジェクトの割り当てと解放に際してはより慎重になる必要があります。最低限、オブジェクトの解放メソッドが必要です:

@example
static void
Custom_dealloc(PyObject *op)
@{
    CustomObject *self = (CustomObject *) op;
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free(self);
@}
@end example

この関数は @ref{4ebc,,tp_dealloc} メンバに代入されます。

@example
.tp_dealloc = Custom_dealloc,
@end example

このメソッドは、まず二つのPython 属性の参照カウントをクリアします。 @ref{992,,Py_XDECREF()} は引数が @code{NULL} のケースを正しく扱えます (これは、@code{tp_new} が途中で失敗した場合に起こりえます) 。このメソッドは、つぎにオブジェクトの型 (@code{Py_TYPE(self)} で算出します) のメンバ @ref{4ecf,,tp_free} を呼び出し、オブジェクトのメモリを開放します。オブジェクトの型が @code{CustomType} であるとは限らない点に注意してください。なぜなら、オブジェクトはサブクラスのインスタンスかもしれないからです。

@cartouche
@quotation 注釈 
The explicit cast to @code{CustomObject *} above is needed because we defined
@code{Custom_dealloc} to take a @code{PyObject *} argument, as the @code{tp_dealloc}
function pointer expects to receive a @code{PyObject *} argument.
By assigning to the @code{tp_dealloc} slot of a type, we declare
that it can only be called with instances of our @code{CustomObject}
class, so the cast to @code{(CustomObject *)} is safe.
This is object-oriented polymorphism, in C!

In existing code, or in previous versions of this tutorial,
you might see similar functions take a pointer to the subtype
object structure (@code{CustomObject*}) directly, like this:

@example
Custom_dealloc(CustomObject *self)
@{
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free((PyObject *) self);
@}
...
.tp_dealloc = (destructor) Custom_dealloc,
@end example

This does the same thing on all architectures that CPython
supports, but according to the C standard, it invokes
undefined behavior.
@end quotation
@end cartouche

ファーストネームとラストネームを空文字列に初期化しておきたいので、@code{tp_new} の実装を追加することにしましょう:

@example
static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) @{
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}
@end example

そしてこれを @ref{79f,,tp_new} メンバとしてインストールします:

@example
.tp_new = Custom_new,
@end example

The @code{tp_new} handler is responsible for creating (as opposed to initializing)
objects of the type.  It is exposed in Python as the @ref{7a0,,__new__()} method.
It is not required to define a @code{tp_new} member, and indeed many extension
types will simply reuse @ref{4ecc,,PyType_GenericNew()} as done in the first
version of the @code{Custom} type above.  In this case, we use the @code{tp_new}
handler to initialize the @code{first} and @code{last} attributes to non-@code{NULL}
default values.

@code{tp_new} is passed the type being instantiated (not necessarily @code{CustomType},
if a subclass is instantiated) and any arguments passed when the type was
called, and is expected to return the instance created.  @code{tp_new} handlers
always accept positional and keyword arguments, but they often ignore the
arguments, leaving the argument handling to initializer (a.k.a. @code{tp_init}
in C or @code{__init__} in Python) methods.

@cartouche
@quotation 注釈 
@code{tp_new} は明示的に @code{tp_init} を呼び出してはいけません、これはインタープリタが自分で行うためです。
@end quotation
@end cartouche

この @code{tp_new} の実装は、@ref{4ed0,,tp_alloc} スロットを呼び出してメモリを割り当てます:

@example
self = (CustomObject *) type->tp_alloc(type, 0);
@end example

メモリ割り当ては失敗するかもしれないので、先に進む前に @ref{4ed0,,tp_alloc} の結果が @code{NULL} でないかチェックしなければなりません。

@cartouche
@quotation 注釈 
We didn't fill the @ref{4ed0,,tp_alloc} slot ourselves. Rather
@ref{980,,PyType_Ready()} fills it for us by inheriting it from our base class,
which is @ref{c7e,,object} by default.  Most types use the default allocation
strategy.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
もし協力的な @ref{79f,,tp_new} (基底タイプの @ref{79f,,tp_new} または @ref{7a0,,__new__()} を呼んでいるもの) を作りたいのならば、実行時のメソッド解決順序をつかってどのメソッドを呼びだすかを決定しようとしては `いけません' 。常に呼び出す型を静的に決めておき、直接その @ref{79f,,tp_new} を呼び出すか、あるいは @code{type->tp_base->tp_new} を経由してください。こうしないと、あなたが作成したタイプの Python サブクラスが他の Python で定義されたクラスも継承している場合にうまく動かない場合があります。 (とりわけ、そのようなサブクラスのインスタンスを @ref{198,,TypeError} を出さずに作ることが不可能になります。)
@end quotation
@end cartouche

We also define an initialization function which accepts arguments to provide
initial values for our instance:

@example
static int
Custom_init(PyObject *op, PyObject *args, PyObject *kwds)
@{
    CustomObject *self = (CustomObject *) op;
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_XDECREF(tmp);
    @}
    if (last) @{
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_XDECREF(tmp);
    @}
    return 0;
@}
@end example

これは @ref{7a1,,tp_init} メンバに代入されます。

@example
.tp_init = Custom_init,
@end example

The @ref{7a1,,tp_init} slot is exposed in Python as the
@ref{8bf,,__init__()} method.  It is used to initialize an object after it's
created.  Initializers always accept positional and keyword arguments,
and they should return either @code{0} on success or @code{-1} on error.

Unlike the @code{tp_new} handler, there is no guarantee that @code{tp_init}
is called at all (for example, the @ref{ab,,pickle} module by default
doesn't call @ref{8bf,,__init__()} on unpickled instances).  It can also be
called multiple times.  Anyone can call the @code{__init__()} method on
our objects.  For this reason, we have to be extra careful when assigning
the new attribute values.  We might be tempted, for example to assign the
@code{first} member like this:

@example
if (first) @{
    Py_XDECREF(self->first);
    Py_INCREF(first);
    self->first = first;
@}
@end example

But this would be risky.  Our type doesn't restrict the type of the
@code{first} member, so it could be any kind of object.  It could have a
destructor that causes code to be executed that tries to access the
@code{first} member; or that destructor could detach the
@ref{4ed1,,thread state} and let arbitrary code run in other
threads that accesses and modifies our object.

To be paranoid and protect ourselves against this possibility, we almost
always reassign members before decrementing their reference counts.  When
don't we have to do this?


@itemize *

@item 
その参照カウントが 1 より大きいと確信できる場合

@item 
when we know that deallocation of the object @footnote{
これはそのオブジェクトが文字列や実数などの基本タイプであるような時に成り立ちます。
} will neither detach
the @ref{4ed1,,thread state} nor cause any calls back into our type's code;

@item 
when decrementing a reference count in a @ref{4ebc,,tp_dealloc}
handler on a type which doesn't support cyclic garbage collection @footnote{
We relied on this in the @ref{4ebc,,tp_dealloc} handler
in this example, because our type doesn't support garbage collection.
}.
@end itemize

ここではインスタンス変数を属性として見えるようにしたいのですが、これにはいくつもの方法があります。もっとも簡単な方法は、メンバの定義を与えることです:

@example
static PyMemberDef Custom_members[] = @{
    @{"first", Py_T_OBJECT_EX, offsetof(CustomObject, first), 0,
     "first name"@},
    @{"last", Py_T_OBJECT_EX, offsetof(CustomObject, last), 0,
     "last name"@},
    @{"number", Py_T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};
@end example

そして、この定義を @ref{4ed2,,tp_members} スロットに入れましょう:

@example
.tp_members = Custom_members,
@end example

Each member definition has a member name, type, offset, access flags and
documentation string.  See the @ref{4ed3,,総称的な属性を管理する} section
below for details.

A disadvantage of this approach is that it doesn't provide a way to restrict the
types of objects that can be assigned to the Python attributes.  We expect the
first and last names to be strings, but any Python objects can be assigned.
Further, the attributes can be deleted, setting the C pointers to @code{NULL}.  Even
though we can make sure the members are initialized to non-@code{NULL} values, the
members can be set to @code{NULL} if the attributes are deleted.

We define a single method, @code{Custom.name()}, that outputs the objects name as the
concatenation of the first and last names.

@example
static PyObject *
Custom_name(PyObject *op, PyObject *Py_UNUSED(dummy))
@{
    CustomObject *self = (CustomObject *) op;
    if (self->first == NULL) @{
        PyErr_SetString(PyExc_AttributeError, "first");
        return NULL;
    @}
    if (self->last == NULL) @{
        PyErr_SetString(PyExc_AttributeError, "last");
        return NULL;
    @}
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
@}
@end example

The method is implemented as a C function that takes a @code{Custom} (or
@code{Custom} subclass) instance as the first argument.  Methods always take an
instance as the first argument. Methods often take positional and keyword
arguments as well, but in this case we don't take any and don't need to accept
a positional argument tuple or keyword argument dictionary. This method is
equivalent to the Python method:

@example
def name(self):
    return "%s %s" % (self.first, self.last)
@end example

Note that we have to check for the possibility that our @code{first} and
@code{last} members are @code{NULL}.  This is because they can be deleted, in which
case they are set to @code{NULL}.  It would be better to prevent deletion of these
attributes and to restrict the attribute values to be strings.  We'll see how to
do that in the next section.

さて、メソッドを定義したので、ここでメソッド定義用の配列を作成する必要があります:

@example
static PyMethodDef Custom_methods[] = @{
    @{"name", Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};
@end example

(note that we used the @ref{16ed,,METH_NOARGS} flag to indicate that the method
is expecting no arguments other than `self')

and assign it to the @ref{4ed4,,tp_methods} slot:

@example
.tp_methods = Custom_methods,
@end example

Finally, we'll make our type usable as a base class for subclassing.  We've
written our methods carefully so far so that they don't make any assumptions
about the type of the object being created or used, so all we need to do is
to add the @ref{4ed5,,Py_TPFLAGS_BASETYPE} to our class flag definition:

@example
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
@end example

We rename @code{PyInit_custom()} to @code{PyInit_custom2()}, update the
module name in the @ref{b74,,PyModuleDef} struct, and update the full class
name in the @ref{c9c,,PyTypeObject} struct.

Finally, we update our @code{setup.py} file to include the new module,

@example
from setuptools import Extension, setup
setup(ext_modules=[
    Extension("custom", ["custom.c"]),
    Extension("custom2", ["custom2.c"]),
])
@end example

and then we re-install so that we can @code{import custom2}:

@example
$ python -m pip install .
@end example

@node データ属性をこまかく制御する,循環ガベージコレクションをサポートする,基本のサンプルにデータとメソッドを追加する,拡張の型の定義 チュートリアル
@anchor{extending/newtypes_tutorial providing-finer-control-over-data-attributes}@anchor{4ed6}
@subsubsection データ属性をこまかく制御する


In this section, we'll provide finer control over how the @code{first} and
@code{last} attributes are set in the @code{Custom} example. In the previous
version of our module, the instance variables @code{first} and @code{last}
could be set to non-string values or even deleted. We want to make sure that
these attributes always contain strings.

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stddef.h> /* for offsetof() */

typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;

static void
Custom_dealloc(PyObject *op)
@{
    CustomObject *self = (CustomObject *) op;
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free(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 = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}

static int
Custom_init(PyObject *op, PyObject *args, PyObject *kwds)
@{
    CustomObject *self = (CustomObject *) op;
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        Py_SETREF(self->first, Py_NewRef(first));
    @}
    if (last) @{
        Py_SETREF(self->last, Py_NewRef(last));
    @}
    return 0;
@}

static PyMemberDef Custom_members[] = @{
    @{"number", Py_T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_getfirst(PyObject *op, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    return Py_NewRef(self->first);
@}

static int
Custom_setfirst(PyObject *op, PyObject *value, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    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_SETREF(self->first, Py_NewRef(value));
    return 0;
@}

static PyObject *
Custom_getlast(PyObject *op, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    return Py_NewRef(self->last);
@}

static int
Custom_setlast(PyObject *op, PyObject *value, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    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_SETREF(self->last, Py_NewRef(value));
    return 0;
@}

static PyGetSetDef Custom_getsetters[] = @{
    @{"first", Custom_getfirst, Custom_setfirst,
     "first name", NULL@},
    @{"last", Custom_getlast, Custom_setlast,
     "last name", NULL@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_name(PyObject *op, PyObject *Py_UNUSED(dummy))
@{
    CustomObject *self = (CustomObject *) op;
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
@}

static PyMethodDef Custom_methods[] = @{
    @{"name", Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};

static PyTypeObject CustomType = @{
    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom3.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_new = Custom_new,
    .tp_init = Custom_init,
    .tp_dealloc = Custom_dealloc,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
    .tp_getset = Custom_getsetters,
@};

static int
custom_module_exec(PyObject *m)
@{
    if (PyType_Ready(&CustomType) < 0) @{
        return -1;
    @}

    if (PyModule_AddObjectRef(m, "Custom", (PyObject *) &CustomType) < 0) @{
        return -1;
    @}

    return 0;
@}

static PyModuleDef_Slot custom_module_slots[] = @{
    @{Py_mod_exec, custom_module_exec@},
    @{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED@},
    @{0, NULL@}
@};

static PyModuleDef custom_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "custom3",
    .m_doc = "Example module that creates an extension type.",
    .m_size = 0,
    .m_slots = custom_module_slots,
@};

PyMODINIT_FUNC
PyInit_custom3(void)
@{
    return PyModuleDef_Init(&custom_module);
@}
@end example

To provide greater control, over the @code{first} and @code{last} attributes,
we'll use custom getter and setter functions.  Here are the functions for
getting and setting the @code{first} attribute:

@example
static PyObject *
Custom_getfirst(PyObject *op, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    Py_INCREF(self->first);
    return self->first;
@}

static int
Custom_setfirst(PyObject *op, PyObject *value, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    PyObject *tmp;
    if (value == NULL) @{
        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
        return -1;
    @}
    if (!PyUnicode_Check(value)) @{
        PyErr_SetString(PyExc_TypeError,
                        "The first attribute value must be a string");
        return -1;
    @}
    tmp = self->first;
    Py_INCREF(value);
    self->first = value;
    Py_DECREF(tmp);
    return 0;
@}
@end example

The getter function is passed a @code{Custom} object and a "closure", which is
a void pointer.  In this case, the closure is ignored.  (The closure supports an
advanced usage in which definition data is passed to the getter and setter. This
could, for example, be used to allow a single set of getter and setter functions
that decide the attribute to get or set based on data in the closure.)

The setter function is passed the @code{Custom} object, the new value, and the
closure.  The new value may be @code{NULL}, in which case the attribute is being
deleted.  In our setter, we raise an error if the attribute is deleted or if its
new value is not a string.

ここでは @ref{db2,,PyGetSetDef} 構造体の配列をつくります:

@example
static PyGetSetDef Custom_getsetters[] = @{
    @{"first", Custom_getfirst, Custom_setfirst,
     "first name", NULL@},
    @{"last", Custom_getlast, Custom_setlast,
     "last name", NULL@},
    @{NULL@}  /* Sentinel */
@};
@end example

そしてこれを @ref{4ed7,,tp_getset} スロットに登録します:

@example
.tp_getset = Custom_getsetters,
@end example

The last item in a @ref{db2,,PyGetSetDef} structure is the "closure" mentioned
above.  In this case, we aren't using a closure, so we just pass @code{NULL}.

また、メンバ定義からはこれらの属性を除いておきましょう:

@example
static PyMemberDef Custom_members[] = @{
    @{"number", Py_T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};
@end example

また、ここでは @ref{7a1,,tp_init} ハンドラも渡されるものとして文字列のみを許可するように修正する必要があります @footnote{
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.
}:

@example
static int
Custom_init(PyObject *op, PyObject *args, PyObject *kwds)
@{
    CustomObject *self = (CustomObject *) op;
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_DECREF(tmp);
    @}
    if (last) @{
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_DECREF(tmp);
    @}
    return 0;
@}
@end example

With these changes, we can assure that the @code{first} and @code{last} members are
never @code{NULL} so we can remove checks for @code{NULL} values in almost all cases.
This means that most of the @ref{992,,Py_XDECREF()} calls can be converted to
@ref{790,,Py_DECREF()} calls.  The only place we can't change these calls is in
the @code{tp_dealloc} implementation, where there is the possibility that the
initialization of these members failed in @code{tp_new}.

さて、先ほどもしたように、このモジュール初期化関数と初期化関数内にあるモジュール名を変更しましょう。そして @code{setup.py} ファイルに追加の定義をくわえます。

@node 循環ガベージコレクションをサポートする,他の型のサブクラスを作る,データ属性をこまかく制御する,拡張の型の定義 チュートリアル
@anchor{extending/newtypes_tutorial supporting-cyclic-garbage-collection}@anchor{4ed8}
@subsubsection 循環ガベージコレクションをサポートする


Python は @ref{17d8,,循環ガベージコレクタ (GC) 機能} をもっており、これは不要なオブジェクトを、たとえ参照カウントがゼロでなくても発見することができます。そのような状況はオブジェクトの参照が循環しているときに起こりえます。たとえば以下の例を考えてください:

@example
>>> l = []
>>> l.append(l)
>>> del l
@end example

この例では、自分自身をふくむリストを作りました。たとえこのリストを 削除しても、それは自分自身への参照をまだ持ちつづけますから、参照カウントはゼロにはなりません。嬉しいことに Python には循環ガベージコレクタは最終的にはこのリストが不要であることを検出し、解放できます。

In the second version of the @code{Custom} example, we allowed any kind of
object to be stored in the @code{first} or @code{last} attributes @footnote{
Also, even with our attributes restricted to strings instances, the user
could pass arbitrary @ref{169,,str} subclasses and therefore still create
reference cycles.
}.
Besides, in the second and third versions, we allowed subclassing
@code{Custom}, and subclasses may add arbitrary attributes.  For any of
those two reasons, @code{Custom} objects can participate in cycles:

@example
>>> import custom3
>>> class Derived(custom3.Custom): pass
...
>>> n = Derived()
>>> n.some_attribute = n
@end example

To allow a @code{Custom} instance participating in a reference cycle to
be properly detected and collected by the cyclic GC, our @code{Custom} type
needs to fill two additional slots and to enable a flag that enables these slots:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stddef.h> /* for offsetof() */

typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;

static int
Custom_traverse(PyObject *op, visitproc visit, void *arg)
@{
    CustomObject *self = (CustomObject *) op;
    Py_VISIT(self->first);
    Py_VISIT(self->last);
    return 0;
@}

static int
Custom_clear(PyObject *op)
@{
    CustomObject *self = (CustomObject *) op;
    Py_CLEAR(self->first);
    Py_CLEAR(self->last);
    return 0;
@}

static void
Custom_dealloc(PyObject *op)
@{
    PyObject_GC_UnTrack(op);
    (void)Custom_clear(op);
    Py_TYPE(op)->tp_free(op);
@}

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) @{
        self->first = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}

static int
Custom_init(PyObject *op, PyObject *args, PyObject *kwds)
@{
    CustomObject *self = (CustomObject *) op;
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        Py_SETREF(self->first, Py_NewRef(first));
    @}
    if (last) @{
        Py_SETREF(self->last, Py_NewRef(last));
    @}
    return 0;
@}

static PyMemberDef Custom_members[] = @{
    @{"number", Py_T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_getfirst(PyObject *op, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    return Py_NewRef(self->first);
@}

static int
Custom_setfirst(PyObject *op, PyObject *value, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    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_XSETREF(self->first, Py_NewRef(value));
    return 0;
@}

static PyObject *
Custom_getlast(PyObject *op, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    return Py_NewRef(self->last);
@}

static int
Custom_setlast(PyObject *op, PyObject *value, void *closure)
@{
    CustomObject *self = (CustomObject *) op;
    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_XSETREF(self->last, Py_NewRef(value));
    return 0;
@}

static PyGetSetDef Custom_getsetters[] = @{
    @{"first", Custom_getfirst, Custom_setfirst,
     "first name", NULL@},
    @{"last", Custom_getlast, Custom_setlast,
     "last name", NULL@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_name(PyObject *op, PyObject *Py_UNUSED(dummy))
@{
    CustomObject *self = (CustomObject *) op;
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
@}

static PyMethodDef Custom_methods[] = @{
    @{"name", Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};

static PyTypeObject CustomType = @{
    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom4.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
    .tp_new = Custom_new,
    .tp_init = Custom_init,
    .tp_dealloc = Custom_dealloc,
    .tp_traverse = Custom_traverse,
    .tp_clear = Custom_clear,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
    .tp_getset = Custom_getsetters,
@};

static int
custom_module_exec(PyObject *m)
@{
    if (PyType_Ready(&CustomType) < 0) @{
        return -1;
    @}

    if (PyModule_AddObjectRef(m, "Custom", (PyObject *) &CustomType) < 0) @{
        return -1;
    @}

    return 0;
@}

static PyModuleDef_Slot custom_module_slots[] = @{
    @{Py_mod_exec, custom_module_exec@},
    @{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED@},
    @{0, NULL@}
@};

static PyModuleDef custom_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "custom4",
    .m_doc = "Example module that creates an extension type.",
    .m_size = 0,
    .m_slots = custom_module_slots,
@};

PyMODINIT_FUNC
PyInit_custom4(void)
@{
    return PyModuleDef_Init(&custom_module);
@}
@end example

First, the traversal method lets the cyclic GC know about subobjects that could
participate in cycles:

@example
static int
Custom_traverse(PyObject *op, visitproc visit, void *arg)
@{
    CustomObject *self = (CustomObject *) op;
    int vret;
    if (self->first) @{
        vret = visit(self->first, arg);
        if (vret != 0)
            return vret;
    @}
    if (self->last) @{
        vret = visit(self->last, arg);
        if (vret != 0)
            return vret;
    @}
    return 0;
@}
@end example

For each subobject that can participate in cycles, we need to call the
@code{visit()} function, which is passed to the traversal method. The
@code{visit()} function takes as arguments the subobject and the extra argument
`arg' passed to the traversal method.  It returns an integer value that must be
returned if it is non-zero.

Python provides a @ref{4ed9,,Py_VISIT()} macro that automates calling visit
functions.  With @ref{4ed9,,Py_VISIT()}, we can minimize the amount of boilerplate
in @code{Custom_traverse}:

@example
static int
Custom_traverse(PyObject *op, visitproc visit, void *arg)
@{
    CustomObject *self = (CustomObject *) op;
    Py_VISIT(self->first);
    Py_VISIT(self->last);
    return 0;
@}
@end example

@cartouche
@quotation 注釈 
The @ref{982,,tp_traverse} implementation must name its
arguments exactly `visit' and `arg' in order to use @ref{4ed9,,Py_VISIT()}.
@end quotation
@end cartouche

Second, we need to provide a method for clearing any subobjects that can
participate in cycles:

@example
static int
Custom_clear(PyObject *op)
@{
    CustomObject *self = (CustomObject *) op;
    Py_CLEAR(self->first);
    Py_CLEAR(self->last);
    return 0;
@}
@end example

Notice the use of the @ref{798,,Py_CLEAR()} macro.  It is the recommended and safe
way to clear data attributes of arbitrary types while decrementing
their reference counts.  If you were to call @ref{992,,Py_XDECREF()} instead
on the attribute before setting it to @code{NULL}, there is a possibility
that the attribute's destructor would call back into code that reads the
attribute again (`especially' if there is a reference cycle).

@cartouche
@quotation 注釈 
You could emulate @ref{798,,Py_CLEAR()} by writing:

@example
PyObject *tmp;
tmp = self->first;
self->first = NULL;
Py_XDECREF(tmp);
@end example

Nevertheless, it is much easier and less error-prone to always
use @ref{798,,Py_CLEAR()} when deleting an attribute.  Don't
try to micro-optimize at the expense of robustness!
@end quotation
@end cartouche

The deallocator @code{Custom_dealloc} may call arbitrary code when clearing
attributes.  It means the circular GC can be triggered inside the function.
Since the GC assumes reference count is not zero, we need to untrack the object
from the GC by calling @ref{171e,,PyObject_GC_UnTrack()} before clearing members.
Here is our reimplemented deallocator using @ref{171e,,PyObject_GC_UnTrack()}
and @code{Custom_clear}:

@example
static void
Custom_dealloc(PyObject *op)
@{
    PyObject_GC_UnTrack(op);
    (void)Custom_clear(op);
    Py_TYPE(op)->tp_free(op);
@}
@end example

Finally, we add the @ref{981,,Py_TPFLAGS_HAVE_GC} flag to the class flags:

@example
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
@end example

これで完了です。 @ref{4ed0,,tp_alloc} スロットまたは @ref{4ecf,,tp_free} ハンドラが書かれていれば、それらを循環ガベージコレクションに使えるよう修正すればよいのです。ほとんどの拡張機能は自動的に提供されるバージョンを使うでしょう。

@node 他の型のサブクラスを作る,,循環ガベージコレクションをサポートする,拡張の型の定義 チュートリアル
@anchor{extending/newtypes_tutorial subclassing-other-types}@anchor{4eda}
@subsubsection 他の型のサブクラスを作る


既存の型を継承した新しい拡張型を作成することができます。組み込み型から継承するのは特に簡単です。必要な @ref{c9c,,PyTypeObject} を簡単に利用できるからです。それに比べて、 @ref{c9c,,PyTypeObject} 構造体を拡張モジュール間で共有するのは難しいです。

In this example we will create a @code{SubList} type that inherits from the
built-in @ref{24d,,list} type. The new type will be completely compatible with
regular lists, but will have an additional @code{increment()} method that
increases an internal counter:

@example
>>> import sublist
>>> s = sublist.SubList(range(3))
>>> s.extend(s)
>>> print(len(s))
6
>>> print(s.increment())
1
>>> print(s.increment())
2
@end example

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

typedef struct @{
    PyListObject list;
    int state;
@} SubListObject;

static PyObject *
SubList_increment(PyObject *op, PyObject *Py_UNUSED(dummy))
@{
    SubListObject *self = (SubListObject *) op;
    self->state++;
    return PyLong_FromLong(self->state);
@}

static PyMethodDef SubList_methods[] = @{
    @{"increment", SubList_increment, METH_NOARGS,
     PyDoc_STR("increment state counter")@},
    @{NULL@},
@};

static int
SubList_init(PyObject *op, PyObject *args, PyObject *kwds)
@{
    SubListObject *self = (SubListObject *) op;
    if (PyList_Type.tp_init(op, args, kwds) < 0)
        return -1;
    self->state = 0;
    return 0;
@}

static PyTypeObject SubListType = @{
    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "sublist.SubList",
    .tp_doc = PyDoc_STR("SubList objects"),
    .tp_basicsize = sizeof(SubListObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_init = SubList_init,
    .tp_methods = SubList_methods,
@};

static int
sublist_module_exec(PyObject *m)
@{
    SubListType.tp_base = &PyList_Type;
    if (PyType_Ready(&SubListType) < 0) @{
        return -1;
    @}

    if (PyModule_AddObjectRef(m, "SubList", (PyObject *) &SubListType) < 0) @{
        return -1;
    @}

    return 0;
@}

static PyModuleDef_Slot sublist_module_slots[] = @{
    @{Py_mod_exec, sublist_module_exec@},
    @{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED@},
    @{0, NULL@}
@};

static PyModuleDef sublist_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "sublist",
    .m_doc = "Example module that creates an extension type.",
    .m_size = 0,
    .m_slots = sublist_module_slots,
@};

PyMODINIT_FUNC
PyInit_sublist(void)
@{
    return PyModuleDef_Init(&sublist_module);
@}
@end example

As you can see, the source code closely resembles the @code{Custom} examples in
previous sections. We will break down the main differences between them.

@example
typedef struct @{
    PyListObject list;
    int state;
@} SubListObject;
@end example

The primary difference for derived type objects is that the base type's
object structure must be the first value.  The base type will already include
the @ref{14f5,,PyObject_HEAD()} at the beginning of its structure.

When a Python object is a @code{SubList} instance, its @code{PyObject *} pointer
can be safely cast to both @code{PyListObject *} and @code{SubListObject *}:

@example
static int
SubList_init(PyObject *op, PyObject *args, PyObject *kwds)
@{
    SubListObject *self = (SubListObject *) op;
    if (PyList_Type.tp_init(op, args, kwds) < 0)
        return -1;
    self->state = 0;
    return 0;
@}
@end example

We see above how to call through to the @ref{8bf,,__init__()} method of the base
type.

This pattern is important when writing a type with custom
@ref{79f,,tp_new} and @ref{4ebc,,tp_dealloc}
members.  The @ref{79f,,tp_new} handler should not actually
create the memory for the object with its @ref{4ed0,,tp_alloc},
but let the base class handle it by calling its own @ref{79f,,tp_new}.

The @ref{c9c,,PyTypeObject} struct supports a @ref{2375,,tp_base}
specifying the type's concrete base class.  Due to cross-platform compiler
issues, you can't fill that field directly with a reference to
@ref{4edb,,PyList_Type}; it should be done in the @ref{b75,,Py_mod_exec}
function:

@example
static int
sublist_module_exec(PyObject *m)
@{
    SubListType.tp_base = &PyList_Type;
    if (PyType_Ready(&SubListType) < 0) @{
        return -1;
    @}

    if (PyModule_AddObjectRef(m, "SubList", (PyObject *) &SubListType) < 0) @{
        return -1;
    @}

    return 0;
@}
@end example

@code{PyType_Read()} を呼ぶ前に、型の構造体の @ref{2375,,tp_base} スロットは埋められていなければなりません。既存の型を継承する際には、 @ref{4ed0,,tp_alloc} スロットを @ref{4ecc,,PyType_GenericNew()} で埋める必要はありません。 -- 基底型のアロケーション関数が継承されます。

After that, calling @ref{980,,PyType_Ready()} and adding the type object to the
module is the same as with the basic @code{Custom} examples.

@subsubheading 脚注


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 拡張の型の定義 雑多なトピック,C および C++ 拡張のビルド,拡張の型の定義 チュートリアル,サードパーティツールなしで拡張を作る
@anchor{extending/newtypes doc}@anchor{4edc}@anchor{extending/newtypes defining-extension-types-assorted-topics}@anchor{4edd}@anchor{extending/newtypes new-types-topics}@anchor{4ede}@anchor{extending/newtypes translation-repo}@anchor{4edf}
@subsection 拡張の型の定義: 雑多なトピック

@anchor{extending/newtypes dnt-type-methods}@anchor{4ee0}
この節ではさまざまな実装可能なタイプメソッドと、それらが何をするものであるかについて、ざっと説明します。

以下は @ref{c9c,,PyTypeObject} の定義です。 @ref{509,,デバッグビルド} でしか使われないいくつかのメンバは省いてあります:

@example
typedef struct _typeobject @{
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    Py_ssize_t tp_vectorcall_offset;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* Assigned meaning in release 2.0 */
    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* Assigned meaning in release 2.1 */
    /* 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 */
    PyMethodDef *tp_methods;
    PyMemberDef *tp_members;
    PyGetSetDef *tp_getset;
    // Strong reference on a heap type, borrowed reference on a static type
    PyTypeObject *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; /* no longer used */
    void *tp_subclasses;  /* for static builtin types this is an index */
    PyObject *tp_weaklist; /* not used for static builtin types */
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6.
     * If zero, the cache is invalid and must be initialized.
     */
    unsigned int tp_version_tag;

    destructor tp_finalize;
    vectorcallfunc tp_vectorcall;

    /* bitset of which type-watchers care about this type */
    unsigned char tp_watched;

    /* Number of tp_version_tag values used.
     * Set to _Py_ATTR_CACHE_UNUSED if the attribute cache is
     * disabled for this type (e.g. due to custom MRO entries).
     * Otherwise, limited to MAX_VERSIONS_PER_CLASS (defined elsewhere).
     */
    uint16_t tp_versions_used;
@} PyTypeObject;
@end example

`たくさんの' メソッドがありますね。でもそんなに心配する必要はありません。定義したい型があるなら、実装するのはこのうちのごくわずかですむことがほとんどです。

すでに予想されているでしょうが、この構造体について入念に見ていき、様々なハンドラについてより詳しい情報を提供します。
しかしこれらのメンバが構造体中で定義されている順番は無視します。というのは、これらのメンバの現れる順序は歴史的な遺産によるものだからです。
多くの場合いちばん簡単なのは、必要とするメンバがすべて含まれている例をとってきて、新しく作る型に合わせて値を変更することです。

@example
const char *tp_name; /* For printing */
@end example

これは型の名前です。前の章で説明したように、これは色々な場面で現れ、ほとんどは診断目的で使われるものです。
それなので、そのような場面で役に立つであろう名前を選んでください!

@example
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
@end example

これらのフィールドは、この型のオブジェクトが新しく作成されるときにどれだけのメモリを割り当てればよいのかをランタイムに指示します。Python には可変長の構造体 (文字列やタプルなどを想像してください) に対する組み込みのサポートがある程度あり、ここで @ref{23bb,,tp_itemsize} メンバが使われます。これらについてはあとでふれます。

@example
const char *tp_doc;
@end example

ここには Python スクリプトリファレンス @code{obj.__doc__} が doc string を返すときの文字列 (あるいはそのアドレス) を入れます。

では次に、型の基本的なメソッドに進みます。ほとんどの拡張の型がこのメソッドを実装します。

@menu
* ファイナライズとメモリ解放:: 
* オブジェクト表現:: 
* 属性を管理する:: 
* オブジェクトの比較:: 
* 抽象的なプロトコルのサポート:: 
* 弱参照(Weak Reference)のサポート: 弱参照 Weak Reference のサポート. 
* その他いろいろ:: 

@end menu

@node ファイナライズとメモリ解放,オブジェクト表現,,拡張の型の定義 雑多なトピック
@anchor{extending/newtypes finalization-and-de-allocation}@anchor{4ee1}
@subsubsection ファイナライズとメモリ解放


@geindex object;deallocation
@geindex deallocation@comma{} object
@geindex object;finalization
@geindex finalization@comma{} of objects

@example
destructor tp_dealloc;
@end example

型のインスタンスの参照カウントがゼロになり、Python インタプリタがそれを潰して再利用したくなると、この関数が呼ばれます。解放すべきメモリをその型が保持していたり、それ以外にも実行すべき後処理がある場合は、それらをここに入れられます。オブジェクトそれ自体もここで解放される必要があります。この関数の例は、以下のようなものです:

@example
static void
newdatatype_dealloc(PyObject *op)
@{
    newdatatypeobject *self = (newdatatypeobject *) op;
    free(self->obj_UnderlyingDatatypePtr);
    Py_TYPE(self)->tp_free(self);
@}
@end example

If your type supports garbage collection, the destructor should call
@ref{171e,,PyObject_GC_UnTrack()} before clearing any member fields:

@example
static void
newdatatype_dealloc(PyObject *op)
@{
    newdatatypeobject *self = (newdatatypeobject *) op;
    PyObject_GC_UnTrack(op);
    Py_CLEAR(self->other_obj);
    ...
    Py_TYPE(self)->tp_free(self);
@}
@end example

@geindex PyErr_Fetch (C function)
@geindex PyErr_Restore (C function)

メモリ解放関数でひとつ重要なのは、処理待ちの例外にいっさい手をつけないことです。なぜなら、解放用の関数は Python インタプリタがスタックを元の状態に戻すときに呼ばれることが多いからです。そして (通常の関数からの復帰でなく) 例外のためにスタックが巻き戻されるときは、すでに発生している例外からメモリ解放関数を守るものはありません。解放用の関数がおこなう動作が追加の Python のコードを実行してしまうと、それらは例外が発生していることを検知するかもしれません。これはインタプリタが誤解させるエラーを発生させることにつながります。これを防ぐ正しい方法は、安全でない操作を実行する前に処理待ちの例外を保存しておき、終わったらそれを元に戻すことです。これは @ref{428,,PyErr_Fetch()} および @ref{42b,,PyErr_Restore()} 関数を使うことによって可能になります:

@example
static void
my_dealloc(PyObject *obj)
@{
    MyObject *self = (MyObject *) obj;
    PyObject *cbresult;

    if (self->my_callback != NULL) @{
        PyObject *err_type, *err_value, *err_traceback;

        /* This saves the current exception state */
        PyErr_Fetch(&err_type, &err_value, &err_traceback);

        cbresult = PyObject_CallNoArgs(self->my_callback);
        if (cbresult == NULL) @{
           PyErr_WriteUnraisable(self->my_callback);
        @}
        else @{
            Py_DECREF(cbresult);
        @}

        /* This restores the saved exception state */
        PyErr_Restore(err_type, err_value, err_traceback);

        Py_DECREF(self->my_callback);
    @}
    Py_TYPE(self)->tp_free(self);
@}
@end example

@cartouche
@quotation 注釈 
メモリ解放関数の中で安全に行えることにはいくつか制限があります。
1つ目は、その型が (@ref{982,,tp_traverse} および @ref{4ee2,,tp_clear} を使って) ガベージコレクションをサポートしている場合、 @ref{4ebc,,tp_dealloc} が呼び出されるまでに、消去されファイナライズされてしまうオブジェクトのメンバーが有り得ることです。
2つ目は、 @ref{4ebc,,tp_dealloc} の中ではオブジェクトは不安定な状態にあることです: つまり参照カウントが0であるということです。
(上の例にあるような) 複雑なオブジェクトや API の呼び出しでは、 @ref{4ebc,,tp_dealloc} を再度呼び出し、二重解放からクラッシュすることになるかもしれません。

Python 3.4 からは、複雑なファイナライズのコードは @ref{4ebc,,tp_dealloc} に置かず、代わりに新しく導入された @ref{c9d,,tp_finalize} という型メソッドを使うことが推奨されています。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/} で新しいファイナライズの仕組みが説明されています。

@end quotation
@end cartouche

@geindex string;object representation
@geindex 組み込み関数;repr

@node オブジェクト表現,属性を管理する,ファイナライズとメモリ解放,拡張の型の定義 雑多なトピック
@anchor{extending/newtypes object-presentation}@anchor{4ee3}
@subsubsection オブジェクト表現


Python では、オブジェクトの文字列表現を生成するのに 2つのやり方があります: @ref{1c1,,repr()} 関数を使う方法と、 @ref{169,,str()}  関数を使う方法です。 (@ref{1177,,print()} 関数は単に @ref{169,,str()} を呼び出します。) これらのハンドラはどちらも省略できます。

@example
reprfunc tp_repr;
reprfunc tp_str;
@end example

@ref{4ee4,,tp_repr} ハンドラは呼び出されたインスタンスの文字列表現を格納した文字列オブジェクトを返す必要があります。簡単な例は以下のようなものです:

@example
static PyObject *
newdatatype_repr(PyObject *op)
@{
    newdatatypeobject *self = (newdatatypeobject *) op;
    return PyUnicode_FromFormat("Repr-ified_newdatatype@{@{size:%d@}@}",
                                self->obj_UnderlyingDatatypePtr->size);
@}
@end example

If no @ref{4ee4,,tp_repr} handler is specified, the interpreter will supply a
representation that uses the type's @ref{1cb0,,tp_name} and a uniquely identifying
value for the object.

@ref{4ee5,,tp_str} ハンドラと @ref{169,,str()} の関係は、上の @ref{4ee4,,tp_repr} ハンドラと @ref{1c1,,repr()} の関係に相当します。つまり、これは Python のコードがオブジェクトのインスタンスに対して @ref{169,,str()} を呼び出したときに呼ばれます。この関数の実装は @ref{4ee4,,tp_repr} ハンドラのそれと非常に似ていますが、得られる文字列表現は人間が読むことを意図されています。 @ref{4ee5,,tp_str} が指定されていない場合、かわりに @ref{4ee4,,tp_repr} ハンドラが使われます。

以下は簡単な例です:

@example
static PyObject *
newdatatype_str(PyObject *op)
@{
    newdatatypeobject *self = (newdatatypeobject *) op;
    return PyUnicode_FromFormat("Stringified_newdatatype@{@{size:%d@}@}",
                                self->obj_UnderlyingDatatypePtr->size);
@}
@end example

@node 属性を管理する,オブジェクトの比較,オブジェクト表現,拡張の型の定義 雑多なトピック
@anchor{extending/newtypes attribute-management}@anchor{4ee6}
@subsubsection 属性を管理する


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 @code{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 @ref{5df,,PyObject}*.  Each type can use whichever pair makes more
sense for the implementation's convenience.

@example
getattrfunc  tp_getattr;        /* char * version */
setattrfunc  tp_setattr;
/* ... */
getattrofunc tp_getattro;       /* PyObject * version */
setattrofunc tp_setattro;
@end example

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 @ref{5df,,PyObject}* 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
* 総称的な属性を管理する:: 
* 特定の型に特化した属性の管理:: 

@end menu

@node 総称的な属性を管理する,特定の型に特化した属性の管理,,属性を管理する
@anchor{extending/newtypes generic-attribute-management}@anchor{4ed3}@anchor{extending/newtypes id1}@anchor{4ee7}
@subsubsection 総称的な属性を管理する


ほとんどの型は `単純な' 属性を使うだけです。では、どのような属性が単純だといえるのでしょうか? それが満たすべき条件はごくわずかです:


@enumerate 

@item 
@ref{980,,PyType_Ready()} が呼ばれたとき、すでに属性の名前がわかっていること。

@item 
属性を参照したり設定したりするときに、特別な記録のための処理が必要でなく、また参照したり設定した値に対してどんな操作も実行する必要がないこと。
@end enumerate

これらの条件は、属性の値や、値が計算されるタイミング、または格納されたデータがどの程度妥当なものであるかといったことになんら制約を課すものではないことに注意してください。

When @ref{980,,PyType_Ready()} is called, it uses three tables referenced by the
type object to create @ref{1881,,descriptor}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 @code{NULL}, instances of
the type will only have attributes that are inherited from their base type, and
should leave the @ref{1a64,,tp_getattro} and @ref{4ee8,,tp_setattro} fields @code{NULL} as
well, allowing the base type to handle attributes.

テーブルはタイプオブジェクト中の 3つのメンバとして宣言されています:

@example
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
@end example

If @ref{4ed4,,tp_methods} is not @code{NULL}, it must refer to an array of
@ref{16f0,,PyMethodDef} structures.  Each entry in the table is an instance of this
structure:

@example
typedef struct PyMethodDef @{
    const char  *ml_name;       /* method name */
    PyCFunction  ml_meth;       /* implementation function */
    int          ml_flags;      /* flags */
    const char  *ml_doc;        /* docstring */
@} PyMethodDef;
@end example

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
@ref{4ee9,,ml_name} field of the sentinel must be @code{NULL}.

2番目のテーブルは、インスタンス中に格納されるデータと直接対応づけられた属性を定義するのに使います。いくつもの C の原始的な型がサポートされており、アクセスを読み出し専用にも読み書き可能にもできます。このテーブルで使われる構造体は次のように定義されています:

@example
typedef struct PyMemberDef @{
    const char *name;
    int         type;
    int         offset;
    int         flags;
    const char *doc;
@} PyMemberDef;
@end example

For each entry in the table, a @ref{1881,,descriptor} will be constructed and added to the
type which will be able to extract a value from the instance structure.  The
@ref{4eea,,type} field should contain a type code like @ref{7ac,,Py_T_INT} or
@ref{7ad,,Py_T_DOUBLE}; the value will be used to determine how to
convert Python values to and from C values.  The @ref{4eeb,,flags} field is used to
store flags which control how the attribute can be accessed: you can set it to
@ref{7ae,,Py_READONLY} to prevent Python code from setting it.

An interesting advantage of using the @ref{4ed2,,tp_members} 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 @ref{2095,,__doc__} attribute.

As with the @ref{4ed4,,tp_methods} table, a sentinel entry with a @ref{4ee9,,ml_name} value
of @code{NULL} is required.

@c XXX Descriptors need to be explained in more detail somewhere, but not here.
@c 
@c Descriptor objects have two handler functions which correspond to the
@c \member{tp_getattro} and \member{tp_setattro} handlers.  The
@c \method{__get__()} handler is a function which is passed the descriptor,
@c instance, and type objects, and returns the value of the attribute, or it
@c returns \NULL{} and sets an exception.  The \method{__set__()} handler is
@c passed the descriptor, instance, type, and new value;

@node 特定の型に特化した属性の管理,,総称的な属性を管理する,属性を管理する
@anchor{extending/newtypes type-specific-attribute-management}@anchor{4eec}
@subsubsection 特定の型に特化した属性の管理


For simplicity, only the char* version will be demonstrated here; the
type of the name parameter is the only difference between the char*
and @ref{5df,,PyObject}* 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 @ref{4eed,,tp_getattr} handler is called when the object requires an attribute
look-up.  It is called in the same situations where the @ref{6fa,,__getattr__()}
method of a class would be called.

以下に例を示します。:

@example
static PyObject *
newdatatype_getattr(PyObject *op, char *name)
@{
    newdatatypeobject *self = (newdatatypeobject *) op;
    if (strcmp(name, "data") == 0) @{
        return PyLong_FromLong(self->data);
    @}

    PyErr_Format(PyExc_AttributeError,
                 "'%.100s' object has no attribute '%.400s'",
                 Py_TYPE(self)->tp_name, name);
    return NULL;
@}
@end example

The @ref{4eee,,tp_setattr} handler is called when the @ref{237c,,__setattr__()} or
@ref{237d,,__delattr__()} method of a class instance would be called.  When an
attribute should be deleted, the third parameter will be @code{NULL}.  Here is an
example that simply raises an exception; if this were really all you wanted, the
@ref{4eee,,tp_setattr} handler should be set to @code{NULL}.

@example
static int
newdatatype_setattr(PyObject *op, char *name, PyObject *v)
@{
    PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name);
    return -1;
@}
@end example

@node オブジェクトの比較,抽象的なプロトコルのサポート,属性を管理する,拡張の型の定義 雑多なトピック
@anchor{extending/newtypes object-comparison}@anchor{4eef}
@subsubsection オブジェクトの比較


@example
richcmpfunc tp_richcompare;
@end example

The @ref{4ef0,,tp_richcompare} handler is called when comparisons are needed.  It is
analogous to the @ref{23ae,,rich comparison methods}, like
@code{__lt__()}, and also called by @ref{4ef1,,PyObject_RichCompare()} and
@ref{1d8c,,PyObject_RichCompareBool()}.

This function is called with two Python objects and the operator as arguments,
where the operator is one of @code{Py_EQ}, @code{Py_NE}, @code{Py_LE}, @code{Py_GE},
@code{Py_LT} or @code{Py_GT}.  It should compare the two objects with respect to the
specified operator and return @code{Py_True} or @code{Py_False} if the comparison is
successful, @code{Py_NotImplemented} to indicate that comparison is not
implemented and the other object's comparison method should be tried, or @code{NULL}
if an exception was set.

これは内部ポインタのサイズが等しければ等しいと見なすデータ型のサンプル実装です:

@example
static PyObject *
newdatatype_richcmp(PyObject *lhs, PyObject *rhs, int op)
@{
    newdatatypeobject *obj1 = (newdatatypeobject *) lhs;
    newdatatypeobject *obj2 = (newdatatypeobject *) rhs;
    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;
    return Py_NewRef(result);
 @}
@end example

@node 抽象的なプロトコルのサポート,弱参照 Weak Reference のサポート,オブジェクトの比較,拡張の型の定義 雑多なトピック
@anchor{extending/newtypes abstract-protocol-support}@anchor{4ef2}
@subsubsection 抽象的なプロトコルのサポート


Python はいくつもの `抽象的な' “プロトコル”をサポートしています。これらを使用する特定のインターフェイスについては @ref{4ef3,,抽象オブジェクトレイヤ (Abstract Objects Layer)} で解説されています。

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-@code{NULL}. The flag may be set
to indicate the presence of a slot, but a slot may still be unfilled.)

@example
PyNumberMethods   *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods  *tp_as_mapping;
@end example

お使いのオブジェクトを数値やシーケンス、あるいは辞書のようにふるまうようにしたいならば、それぞれに C の @ref{1637,,PyNumberMethods} 構造体、 @ref{4ef4,,PySequenceMethods} 構造体、または @ref{4ef5,,PyMappingMethods} 構造体のアドレスを入れます。これらに適切な値を入れても入れなくてもかまいません。これらを使った例は Python の配布ソースにある @code{Objects} でみつけることができるでしょう。

@example
hashfunc tp_hash;
@end example

この関数は、もし使うことにしたならば、データ型のインスタンスのハッシュ番号を返すようにします。次のは単純な例です:

@example
static Py_hash_t
newdatatype_hash(PyObject *op)
@{
    newdatatypeobject *self = (newdatatypeobject *) op;
    Py_hash_t result;
    result = self->some_size + 32767 * self->some_number;
    if (result == -1) @{
        result = -2;
    @}
    return result;
@}
@end example

@ref{147b,,Py_hash_t} is a signed integer type with a platform-varying width.
Returning @code{-1} from @ref{4ef6,,tp_hash} indicates an error,
which is why you should be careful to avoid returning it when hash computation
is successful, as seen above.

@example
ternaryfunc tp_call;
@end example

この関数は、その型のインスタンスが「関数として呼び出される」ときに呼ばれます。たとえばもし @code{obj1} にそのインスタンスが入っていて、Python スクリプトで @code{obj1('hello')} を実行したとすると、 @ref{77b,,tp_call} ハンドラが呼ばれます。

この関数は 3つの引数をとります:


@enumerate 

@item 
`self' は呼び出しの対象となるデータ型のインスタンスです。
たとえば呼び出しが @code{obj1('hello')} の場合、`self' は @code{obj1} になります。

@item 
`args' は呼び出しの引数を格納しているタプルです。ここから引数を取り出すには @ref{3c1,,PyArg_ParseTuple()} を使います。

@item 
`kwds' is a dictionary of keyword arguments that were passed. If this is
non-@code{NULL} and you support keyword arguments, use
@ref{624,,PyArg_ParseTupleAndKeywords()} to extract the arguments.  If you
do not want to support keyword arguments and this is non-@code{NULL}, raise a
@ref{198,,TypeError} with a message saying that keyword arguments are not supported.
@end enumerate

以下は @code{tp_call} の簡易な実装です:

@example
static PyObject *
newdatatype_call(PyObject *op, PyObject *args, PyObject *kwds)
@{
    newdatatypeobject *self = (newdatatypeobject *) op;
    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",
        self->obj_UnderlyingDatatypePtr->size,
        arg1, arg2, arg3);
    return result;
@}
@end example

@example
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
@end example

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 @code{NULL}.  @ref{1708,,tp_iter} corresponds
to the Python @ref{e69,,__iter__()} method, while @ref{1709,,tp_iternext}
corresponds to the Python @ref{14e5,,__next__()} method.

Any @ref{12f1,,iterable} object must implement the @ref{1708,,tp_iter}
handler, which must return an @ref{4c8,,iterator} object.  Here the same guidelines
apply as for Python classes:


@itemize *

@item 
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 @ref{1708,,tp_iter}.

@item 
Objects which can only be iterated over once (usually due to side effects of
iteration, such as file objects) can implement @ref{1708,,tp_iter}
by returning a new reference to themselves -- and should also therefore
implement the @ref{1709,,tp_iternext}  handler.
@end itemize

Any @ref{4c8,,iterator} object should implement both @ref{1708,,tp_iter}
and @ref{1709,,tp_iternext}.  An iterator's
@ref{1708,,tp_iter} handler should return a new reference
to the iterator.  Its @ref{1709,,tp_iternext} handler should
return a new reference to the next object in the iteration, if there is one.
If the iteration has reached the end, @ref{1709,,tp_iternext}
may return @code{NULL} without setting an exception, or it may set
@ref{df5,,StopIteration} `in addition' to returning @code{NULL}; avoiding
the exception can yield slightly better performance.  If an actual error
occurs, @ref{1709,,tp_iternext} should always set an exception
and return @code{NULL}.

@node 弱参照 Weak Reference のサポート,その他いろいろ,抽象的なプロトコルのサポート,拡張の型の定義 雑多なトピック
@anchor{extending/newtypes weak-reference-support}@anchor{4ef7}@anchor{extending/newtypes weakref-support}@anchor{29cf}
@subsubsection 弱参照(Weak Reference)のサポート


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


@subsubheading 参考


Documentation for the @ref{11a,,weakref} module.


For an object to be weakly referenceable, the extension type must set the
@code{Py_TPFLAGS_MANAGED_WEAKREF} bit of the @ref{1c71,,tp_flags}
field. The legacy @ref{b7f,,tp_weaklistoffset} field should
be left as zero.

Concretely, here is how the statically declared type object would look:

@example
static PyTypeObject TrivialType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    /* ... other members omitted for brevity ... */
    .tp_flags = Py_TPFLAGS_MANAGED_WEAKREF | ...,
@};
@end example

The only further addition is that @code{tp_dealloc} needs to clear any weak
references (by calling @ref{796,,PyObject_ClearWeakRefs()}):

@example
static void
Trivial_dealloc(PyObject *op)
@{
    /* Clear weakrefs first before calling any destructors */
    PyObject_ClearWeakRefs(op);
    /* ... remainder of destruction code omitted for brevity ... */
    Py_TYPE(op)->tp_free(op);
@}
@end example

@node その他いろいろ,,弱参照 Weak Reference のサポート,拡張の型の定義 雑多なトピック
@anchor{extending/newtypes more-suggestions}@anchor{4ef8}
@subsubsection その他いろいろ


In order to learn how to implement any specific method for your new data type,
get the @ref{905,,CPython} source code.  Go to the @code{Objects} directory,
then search the C source files for @code{tp_} plus the function you want
(for example, @code{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 @ref{1cb5,,PyObject_TypeCheck()} function.  A sample of
its use might be something like the following:

@example
if (!PyObject_TypeCheck(some_object, &MyType)) @{
    PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
    return NULL;
@}
@end example


@subsubheading 参考



@table @asis

@item Download CPython source releases.

@indicateurl{https://www.python.org/downloads/source/}

@item The CPython project on GitHub, where the CPython source code is developed.

@indicateurl{https://github.com/python/cpython}
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node C および C++ 拡張のビルド,Windows 上での C および C++ 拡張モジュールのビルド,拡張の型の定義 雑多なトピック,サードパーティツールなしで拡張を作る
@anchor{extending/building doc}@anchor{4ef9}@anchor{extending/building building}@anchor{4ea7}@anchor{extending/building building-c-and-c-extensions}@anchor{4efa}@anchor{extending/building translation-repo}@anchor{4efb}
@subsection C および C++ 拡張のビルド


A C extension for CPython is a shared library (for example, a @code{.so} file on
Linux, @code{.pyd} on Windows), which exports an `initialization function'.

See @ref{4efc,,拡張モジュールの定義} for details.
@anchor{extending/building install-index}@anchor{10f9}
@menu
* setuptools による C および C++ 拡張のビルド:: 

@end menu

@node setuptools による C および C++ 拡張のビルド,,,C および C++ 拡張のビルド
@anchor{extending/building building-c-and-c-extensions-with-setuptools}@anchor{4efd}@anchor{extending/building setuptools-index}@anchor{10fa}
@subsubsection setuptools による C および C++ 拡張のビルド


拡張モジュールのビルド、パッケージ化および配布には、サードパーティのツールが最適であり、このドキュメントの範囲外です。適切なツールの一つは Setuptools であり、ドキュメントは @indicateurl{https://setuptools.pypa.io/en/latest/setuptools.html} にあります。

The @ref{3d,,distutils} module, which was included in the standard library
until Python 3.12, is now maintained as part of Setuptools.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Windows 上での C および C++ 拡張モジュールのビルド,,C および C++ 拡張のビルド,サードパーティツールなしで拡張を作る
@anchor{extending/windows doc}@anchor{4efe}@anchor{extending/windows building-c-and-c-extensions-on-windows}@anchor{4eff}@anchor{extending/windows building-on-windows}@anchor{2224}@anchor{extending/windows translation-repo}@anchor{4f00}
@subsection Windows 上での C および C++ 拡張モジュールのビルド


この章では Windows 向けの Python 拡張モジュールを Microsoft Visual C++ を使って作成する方法について簡単に述べ、その後に拡張モジュールのビルドがどのように動作するのかについて詳しい背景を述べます。この説明は、Python 拡張モジュールを作成する Windows プログラマと、Unix と Windows の双方でうまくビルドできるようなソフトウェアの作成に興味がある Unix プログラマの双方にとって有用です。

モジュールの作者には、この節で説明している方法よりも、distutils によるアプローチで拡張モジュールをビルドするよう勧めます。また、Python をビルドした際に使われた C コンパイラが必要です; 通常は Microsoft Visual C++です。

@cartouche
@quotation 注釈 
この章では、Python のバージョン番号が符号化されて入っているたくさんのファイル名について触れます。これらのファイル名は @code{XY} で表されるバージョン名付きで表現されます; @code{'X'} は使っている Python リリースのメジャーバージョン番号、@code{'Y'} はマイナーバージョン番号です。例えば、Python 2.2.1 を使っているなら、@code{XY} は実際には @code{22} になります。
@end quotation
@end cartouche

@menu
* 型どおりのアプローチ:: 
* Unix と Windows の相違点:: 
* DLL 使用の実際:: 

@end menu

@node 型どおりのアプローチ,Unix と Windows の相違点,,Windows 上での C および C++ 拡張モジュールのビルド
@anchor{extending/windows a-cookbook-approach}@anchor{4f01}@anchor{extending/windows win-cookbook}@anchor{4f02}
@subsubsection 型どおりのアプローチ


There are two approaches to building extension modules on Windows, just as there
are on Unix: use the @code{setuptools} package to control the build process, or
do things manually.  The setuptools approach works well for most extensions;
documentation on using @code{setuptools} to build and package extension modules
is available in @ref{10fa,,setuptools による C および C++ 拡張のビルド}.  If you find you really need to do
things manually, it may be instructive to study the project file for the
winsound@footnote{https://github.com/python/cpython/tree/3.14/PCbuild/winsound.vcxproj} standard library module.

@node Unix と Windows の相違点,DLL 使用の実際,型どおりのアプローチ,Windows 上での C および C++ 拡張モジュールのビルド
@anchor{extending/windows differences-between-unix-and-windows}@anchor{4f03}@anchor{extending/windows dynamic-linking}@anchor{4f04}
@subsubsection Unix と Windows の相違点


Unix と Windows では、コードの実行時読み込みに全く異なるパラダイムを用いています。動的ロードされるようなモジュールをビルドしようとする前に、自分のシステムがどのように動作するか知っておいてください。

Unix では、共有オブジェクト (@code{.so}) ファイルにプログラムが使うコード、そしてプログラム内で使う関数名やデータが入っています。ファイルがプログラムに結合されると、これらの関数やデータに対するファイルのコード内の全ての参照は、メモリ内で関数やデータが配置されている、プログラム中の実際の場所を指すように変更されます。これは基本的にはリンク操作にあたります。

Windows では、動的リンクライブラリ (@code{.dll}) ファイルにはぶら下がり参照 (dangling reference) はありません。その代わり、関数やデータへのアクセスはルックアップテーブルを介します。従って DLL コードの場合、実行時にポインタがプログラムメモリ上の正しい場所を指すように修正する必要はありません; その代わり、コードは常に DLL のルックアップテーブルを使い、ルックアップテーブル自体は実行時に実際の関数やデータを指すように修正されます。

Unix には、唯一のライブラリファイル形式 (@code{.a}) しかありません。 @code{.a} ファイルには複数のオブジェクトファイル (@code{.o}) 由来のコードが入っています。共有オブジェクトファイル (@code{.so}) を作成するリンク処理の段階中に、リンカは定義場所の不明な識別子に遭遇することがあります。このときリンカはライブラリ内のオブジェクトファイルを検索します; もし識別子が見つかると、リンカはそのオブジェクトファイルから全てのコードを取り込みます。

Windows では、二つの形式のライブラリ、静的ライブラリとインポートライブラリがあります (どちらも @code{.lib} と呼ばれています)。静的ライブラリは Unix における @code{.a} ファイルに似ています; このファイルには、必要に応じて取り込まれるようなコードが入っています。インポートライブラリは、基本的には特定の識別子が不正ではなく、 DLL がロードされた時点で存在することを保証するためにだけ使われます。リンカはインポートライブラリからの情報を使ってルックアップテーブルを作成し、DLL に入っていない識別子を使えるようにします。アプリケーションや DLL がリンクされるさい、インポートライブラリが生成されることがあります。このライブラリは、アプリケーションや DLL 内のシンボルに依存するような、将来作成される全ての DLL で使うために必要になります。

二つの動的ロードモジュール、B と C を作成し、別のコードブロック A を共有するとします。Unix では、 @code{A.a} を @code{B.so} や @code{C.so}  をビルドするときのリンカに渡したりは `しません' ; そんなことをすれば、コードは二度取り込まれ、B と C のそれぞれが自分用のコピーを持ってしまいます。 Windows では、 @code{A.dll} をビルドすると @code{A.lib} もビルドされます。 B や C のリンクには @code{A.lib} を渡します。 @code{A.lib} にはコードは入っていません; 単に A のコードにアクセスするするために実行時に用いられる情報が入っているだけです。

Windows ではインポートライブラリの使用は @code{import spam} とするようなものです; この操作によって spam の名前にアクセスできますが、コードのコピーを個別に作成したりはしません。Unix では、ライブラリとのリンクはむしろ @code{from spam import *} に似ています;  この操作では個別にコードのコピーを生成します。

@geindex Py_NO_LINK_LIB (C macro)
@anchor{extending/windows c Py_NO_LINK_LIB}@anchor{444}
@deffn {C のマクロ} Py_NO_LINK_LIB

Turn off the implicit, @code{#pragma}-based linkage with the Python
library, performed inside CPython header files.


Added in version 3.14.

@end deffn

@node DLL 使用の実際,,Unix と Windows の相違点,Windows 上での C および C++ 拡張モジュールのビルド
@anchor{extending/windows using-dlls-in-practice}@anchor{4f05}@anchor{extending/windows win-dlls}@anchor{4f06}
@subsubsection DLL 使用の実際


Windows Python is built in Microsoft Visual C++; using other compilers may or
may not work.  The rest of this section is MSVC++ specific.

When creating DLLs in Windows, you can use the CPython library in two ways:


@enumerate 

@item 
By default, inclusion of @code{PC/pyconfig.h} directly or via
@code{Python.h} triggers an implicit, configure-aware link with the
library.  The header file chooses @code{pythonXY_d.lib} for Debug,
@code{pythonXY.lib} for Release, and @code{pythonX.lib} for Release with
the @ref{4f07,,Limited API} enabled.

To build two DLLs, spam and ni (which uses C functions found in spam), you
could use these commands:

@example
cl /LD /I/python/include spam.c
cl /LD /I/python/include ni.c spam.lib
@end example

The first command created three files: @code{spam.obj}, @code{spam.dll}
and @code{spam.lib}.  @code{Spam.dll} does not contain any Python
functions (such as @ref{3c1,,PyArg_ParseTuple()}), but it does know how to find
the Python code thanks to the implicitly linked @code{pythonXY.lib}.

二つ目のコマンドでは、 @code{ni.dll} (および @code{.obj} と @code{.lib}) ができ、このライブラリは spam と Python 実行形式中の必要な関数をどうやって見つければよいか知っています。

@item 
Manually by defining @ref{444,,Py_NO_LINK_LIB} macro before including
@code{Python.h}. You must pass @code{pythonXY.lib} to the linker.

To build two DLLs, spam and ni (which uses C functions found in spam), you
could use these commands:

@example
cl /LD /DPy_NO_LINK_LIB /I/python/include spam.c ../libs/pythonXY.lib
cl /LD /DPy_NO_LINK_LIB /I/python/include ni.c spam.lib ../libs/pythonXY.lib
@end example

最初のコマンドで、三つのファイル: @code{spam.obj} 、 @code{spam.dll}  および @code{spam.lib} ができます。 @code{Spam.dll} には (@ref{3c1,,PyArg_ParseTuple()} のような) Python 関数は全く入っていませんが、 @code{pythonXY.lib} のおかげで Python コードを見つけることはできます。

二つ目のコマンドでは、 @code{ni.dll} (および @code{.obj} と @code{.lib}) ができ、このライブラリは spam と Python 実行形式中の必要な関数をどうやって見つければよいか知っています。
@end enumerate

全ての識別子がルックアップテーブル上に公開されるわけではありません。他のモジュール (Python 自体を含みます) から、自作の識別子が見えるようにするには、@code{void _declspec(dllexport) initspam(void)} や @code{PyObject _declspec(dllexport) *NiGetSpamData(void)} のように、@code{_declspec(dllexport)} で宣言せねばなりません。

Developer Studio will throw in a lot of import libraries that you do not really
need, adding about 100K to your executable.  To get rid of them, use the Project
Settings dialog, Link tab, to specify `ignore default libraries'.  Add the
correct @code{msvcrt`xx'.lib} to the list of libraries.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 大規模なアプリケーションへの Python ランタイムの埋め込み,,サードパーティツールなしで拡張を作る,Python インタプリタの拡張と埋め込み
@anchor{extending/index embedding-the-cpython-runtime-in-a-larger-application}@anchor{4f08}
@section 大規模なアプリケーションへの Python ランタイムの埋め込み


Python インタープリタの中でメインアプリケーションとして実行される拡張を作るのではなく、 CPython をより大きなアプリケーションの中に埋め込む方が望ましいことがあります。
この節ではその上手い埋め込みに関わる詳細について説明します。

@menu
* 他のアプリケーションへの Python の埋め込み:: 

@end menu

@node 他のアプリケーションへの Python の埋め込み,,,大規模なアプリケーションへの Python ランタイムの埋め込み
@anchor{extending/embedding doc}@anchor{4f09}@anchor{extending/embedding embedding}@anchor{225b}@anchor{extending/embedding embedding-python-in-another-application}@anchor{4f0a}
@subsection 他のアプリケーションへの Python の埋め込み


前章では、 Python を拡張する方法、すなわち C 関数のライブラリを Python に結びつけて機能を拡張する方法について述べました。同じようなことを別の方法でも実行できます: それは、自分の C/C++ アプリケーションに Python を埋め込んで機能を強化する、というものです。埋め込みを行うことで、アプリケーションの何らかの機能を C や C++ の代わりに Python で実装できるようになります。埋め込みは多くの用途で利用できます; ユーザが Python でスクリプトを書き、アプリケーションを自分好みに仕立てられるようにする、というのがその一例です。プログラマが、特定の機能を Python でより楽に書ける場合に自分自身のために埋め込みを行うこともできます。

Python の埋め込みは Python の拡張と似ていますが、全く同じというわけではありません。その違いは、Python を拡張した場合にはアプリケーションのメインプログラムは依然として Python インタプリタである一方、 Python を組み込みんだ場合には、メインプログラムには Python が関係しない --- その代わりに、アプリケーションのある一部分が時折 Python インタプリタを呼び出して何らかの Python コードを実行させる --- かもしれない、ということです。

従って、 Python の埋め込みを行う場合、自作のメインプログラムを提供しなければなりません。メインプログラムがやらなければならないことの一つに、 Python インタプリタの初期化があります。とにかく少なくとも関数 @ref{460,,Py_Initialize()} を呼び出さねばなりません。オプションとして、Python 側にコマンドライン引数を渡すために関数呼び出しを行います。その後、アプリケーションのどこでもインタプリタを呼び出せるようになります。

インタプリタを呼び出すには、異なるいくつかの方法があります: Python 文が入った文字列を @ref{4f0b,,PyRun_SimpleString()} に渡す、 stdio ファイルポインタとファイル名 (これはエラーメッセージ内でコードを識別するためだけのものです) を @ref{4f0c,,PyRun_SimpleFile()} に渡す、といった具合です。これまでの各章で説明した低水準の操作を呼び出して、Python オブジェクトを構築したり使用したりもできます。


@subsubheading 参考



@table @asis

@item @ref{1fbe,,Python/C API リファレンスマニュアル}

Python C インターフェースの詳細はこのマニュアルに書かれています。必要な情報の大部分はここにあるはずです。
@end table


@menu
* 高水準の埋め込み:: 
* 超高水準の埋め込みから踏み出す; 概要: 超高水準の埋め込みから踏み出す 概要. 
* 純粋な埋め込み:: 
* 埋め込まれた Python の拡張:: 
* C++による Python の埋め込み:: 
* Unix 系システムにおけるコンパイルとリンク:: 

@end menu

@node 高水準の埋め込み,超高水準の埋め込みから踏み出す 概要,,他のアプリケーションへの Python の埋め込み
@anchor{extending/embedding high-level-embedding}@anchor{4f0d}@anchor{extending/embedding very-high-level-embedding}@anchor{4f0e}
@subsubsection 高水準の埋め込み


Python の埋め込みの最も簡単な形式は、超高水準インターフェースの利用です。このインターフェースは、アプリケーションとやり取りする必要がない Python スクリプトを実行するためのものです。例えばこれは、一つのファイル上で何らかの操作を実現するのに利用できます。

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
@{
    PyStatus status;
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* optional but recommended */
    status = PyConfig_SetBytesString(&config, &config.program_name, argv[0]);
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}
    PyConfig_Clear(&config);

    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is', ctime(time()))\n");
    if (Py_FinalizeEx() < 0) @{
        exit(120);
    @}
    return 0;

  exception:
     PyConfig_Clear(&config);
     Py_ExitStatusException(status);
@}
@end example

@cartouche
@quotation 注釈 
@code{#define PY_SSIZE_T_CLEAN} は、いくつかの API では @code{int} の代わりに @code{Py_ssize_t} が使われるべきであることを示すために使われていました。これは Python 3.13 以降では不要となりましたが、後方互換性のために維持されています。このマクロの説明は @ref{62c,,文字列とバッファ} にあります。
@end quotation
@end cartouche

Setting @ref{3f2,,PyConfig.program_name} should be called before
@ref{3f6,,Py_InitializeFromConfig()} to inform the interpreter about paths to Python run-time
libraries.  Next, the Python interpreter is initialized with
@ref{460,,Py_Initialize()}, followed by the execution of a hard-coded Python script
that prints the date and time.  Afterwards, the @ref{f11,,Py_FinalizeEx()} call shuts
the interpreter down, followed by the end of the program.  In a real program,
you may want to get the Python script from another source, perhaps a text-editor
routine, a file, or a database.  Getting the Python code from a file can better
be done by using the @ref{4f0c,,PyRun_SimpleFile()} function, which saves you the
trouble of allocating memory space and loading the file contents.

@node 超高水準の埋め込みから踏み出す 概要,純粋な埋め込み,高水準の埋め込み,他のアプリケーションへの Python の埋め込み
@anchor{extending/embedding beyond-very-high-level-embedding-an-overview}@anchor{4f0f}@anchor{extending/embedding lower-level-embedding}@anchor{4f10}
@subsubsection 超高水準の埋め込みから踏み出す: 概要


高水準インターフェースは、断片的な Python コードをアプリケーションから実行できるようにしてくれますが、アプリケーションと Python コードの間でのデータのやり取りは、控えめに言っても煩わしいものです。データのやり取りをしたいなら、より低水準のインターフェース呼び出しを利用しなくてはなりません。より多く C コードを書かねばならない代わりに、ほぼ何でもできるようになります。

Python の拡張と埋め込みは、趣旨こそ違え、同じ作業であるということに注意せねばなりません。これまでの章で議論してきたトピックのほとんどが埋め込みでもあてはまります。これを示すために、 Python から C への拡張を行うコードが実際には何をするか考えてみましょう:


@enumerate 

@item 
データ値を Python から C に変換する。

@item 
変換された値を使って C ルーチンの関数呼び出しを行い、

@item 
呼び出しで得られたデータ値 C から Python に変換する。
@end enumerate

Python を埋め込む場合には、インターフェースコードが行う作業は以下のようになります:


@enumerate 

@item 
データ値を C から Python に変換する。

@item 
変換された値を使って Python インターフェースルーチンの関数呼び出しを行い、

@item 
呼び出しで得られたデータ値 Python から C に変換する。
@end enumerate

一見して分かるように、データ変換のステップは、言語間でデータを転送する方向が変わったのに合わせて単に入れ替えただけです。唯一の相違点は、データ変換の間にあるルーチンです。拡張を行う際には C ルーチンを呼び出しますが、埋め込みの際には Python ルーチンを呼び出します。

この章では、Python から C へ、そしてその逆へとデータを変換する方法については議論しません。また、正しい参照の使い方やエラーの扱い方についてすでに理解しているものと仮定します。これらの側面についてはインタプリタの拡張と何ら変わるところがないので、必要な情報については以前の章を参照できます。

@node 純粋な埋め込み,埋め込まれた Python の拡張,超高水準の埋め込みから踏み出す 概要,他のアプリケーションへの Python の埋め込み
@anchor{extending/embedding id1}@anchor{4f11}@anchor{extending/embedding pure-embedding}@anchor{4f12}
@subsubsection 純粋な埋め込み


最初に例示するプログラムは、Python スクリプト内の関数を実行するためのものです。超高水準インターフェースに関する節で挙げた例と同様に、Python インタプリタはアプリケーションと直接やりとりはしません (が、次の節でやりとりするよう変更します)。

Python スクリプト内で定義されている関数を実行するためのコードは以下のようになります:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
@{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) @{
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    @}

    Py_Initialize();
    pName = PyUnicode_DecodeFSDefault(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) @{
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) @{
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) @{
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) @{
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                @}
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            @}
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) @{
                printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            @}
            else @{
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            @}
        @}
        else @{
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        @}
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    @}
    else @{
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    @}
    if (Py_FinalizeEx() < 0) @{
        return 120;
    @}
    return 0;
@}
@end example

このコードは @code{argv[1]} を使って Python スクリプトをロードし、 @code{argv[2]} 内に指定された名前の関数を呼び出します。関数の整数引数は @code{argv} 配列中の他の値になります。このプログラムを @ref{4f13,,コンパイルしてリンク} し (できた実行可能形式を @code{call} と呼びましょう)、以下のような Python スクリプトを実行することにします:

@example
def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c
@end example

実行結果は以下のようになるはずです:

@example
$ call multiply multiply 3 2
Will compute 3 times 2
Result of call: 6
@end example

この程度の機能を実現するにはプログラムがいささか大きすぎますが、ほとんどは Python から C へのデータ変換やエラー報告のためのコードです。Python の埋め込みという観点から最も興味深い部分は以下のコードから始まる部分です:

@example
Py_Initialize();
pName = PyUnicode_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
@end example

After initializing the interpreter, the script is loaded using
@ref{1615,,PyImport_Import()}.  This routine needs a Python string as its argument,
which is constructed using the @ref{1a88,,PyUnicode_DecodeFSDefault()} data
conversion routine.

@example
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) @{
    ...
@}
Py_XDECREF(pFunc);
@end example

ひとたびスクリプトが読み込まれると、 @ref{5ef,,PyObject_GetAttrString()} を使って必要な名前を取得できます。名前がスクリプト中に存在し、取得したオブジェクトが呼び出し可能オブジェクトであれば、このオブジェクトが関数であると考えて差し支えないでしょう。そこでプログラムは定石どおりに引数のタプル構築に進みます。その後、Python 関数を以下のコードで呼び出します:

@example
pValue = PyObject_CallObject(pFunc, pArgs);
@end example

関数が処理を戻す際、 @code{pValue} は @code{NULL} になるか、関数の戻り値への参照が入っています。値を調べた後には忘れずに参照を解放してください。

@node 埋め込まれた Python の拡張,C++による Python の埋め込み,純粋な埋め込み,他のアプリケーションへの Python の埋め込み
@anchor{extending/embedding extending-embedded-python}@anchor{4f14}@anchor{extending/embedding extending-with-embedding}@anchor{4f15}
@subsubsection 埋め込まれた Python の拡張


ここまでは、埋め込み Python インタプリタはアプリケーション本体の機能にアクセスする手段がありませんでした。 Python API を使うと、埋め込みインタプリタを拡張することでアプリケーション本体へのアクセスを可能にします。つまり、アプリケーションで提供されているルーチンを使って、埋め込みインタプリタを拡張するのです。複雑なことのように思えますが、それほどひどいわけではありません。さしあたって、アプリケーションが Python インタプリタを起動したということをちょっと忘れてみてください。その代わり、アプリケーションがサブルーチンの集まりで、あたかも普通の Python 拡張モジュールを書くかのように、Python から各ルーチンにアクセスできるようにするグルー(glue, 糊) コードを書くと考えてください。例えば以下のようにです:

@example
static int numargs=0;

/* Return the number of arguments of the application command line */
static PyObject*
emb_numargs(PyObject *self, PyObject *args)
@{
    if(!PyArg_ParseTuple(args, ":numargs"))
        return NULL;
    return PyLong_FromLong(numargs);
@}

static PyMethodDef emb_module_methods[] = @{
    @{"numargs", emb_numargs, METH_VARARGS,
     "Return the number of arguments received by the process."@},
    @{NULL, NULL, 0, NULL@}
@};

static struct PyModuleDef emb_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "emb",
    .m_size = 0,
    .m_methods = emb_module_methods,
@};

static PyObject*
PyInit_emb(void)
@{
    return PyModuleDef_Init(&emb_module);
@}
@end example

上のコードを @code{main()} 関数のすぐ上に挿入します。また、以下の二つの文を @ref{460,,Py_Initialize()} の呼び出しの前に挿入します:

@example
numargs = argc;
PyImport_AppendInittab("emb", &PyInit_emb);
@end example

These two lines initialize the @code{numargs} variable, and make the
@code{emb.numargs()} function accessible to the embedded Python interpreter.
With these extensions, the Python script can do things like

@example
import emb
print("Number of arguments", emb.numargs())
@end example

実際のアプリケーションでは、こうしたメソッドでアプリケーション内の API を Python に公開することになります。

@c TODO: threads, code examples do not really behave well if errors happen
@c (what to watch out for)

@node C++による Python の埋め込み,Unix 系システムにおけるコンパイルとリンク,埋め込まれた Python の拡張,他のアプリケーションへの Python の埋め込み
@anchor{extending/embedding embedding-python-in-c}@anchor{4f16}@anchor{extending/embedding embeddingincplusplus}@anchor{4f17}
@subsubsection C++による Python の埋め込み


C++ プログラム中にも Python を埋め込めます; 厳密に言うと、どうやって埋め込むかは使っているC++ 処理系の詳細に依存します; 一般的には、メインプログラムをC++で書き、C++ コンパイラを使ってプログラムをコンパイル・リンクする必要があるでしょう。 Python 自体を C++でコンパイルしなおす必要はありません。

@node Unix 系システムにおけるコンパイルとリンク,,C++による Python の埋め込み,他のアプリケーションへの Python の埋め込み
@anchor{extending/embedding compiling}@anchor{4f13}@anchor{extending/embedding compiling-and-linking-under-unix-like-systems}@anchor{4f18}
@subsubsection Unix 系システムにおけるコンパイルとリンク


Python インタプリタをアプリケーションに埋め込むためにコンパイラ (とリンカ) に渡すべき正しいフラグを見出すのは簡単でないかもしれません。これは特に、Python がライブラリモジュールに対してリンクされた C 動的拡張 (@code{.so} ファイル) として実装されたものをロードする必要があるためです。

必要なコンパイル・リンクのオプションを知るために、 @code{python`X.Y'-config} スクリプトが使えます(これは Python インストール時に生成されたもので、 @code{python3-config} スクリプトも利用出来るかもしれません)。このスクリプトにはオプションが多くありますが、直接的に有用なのはこれでしょう:


@itemize *

@item 
@code{pythonX.Y-config --cflags} は推奨のコンパイルオプションを出力します:

@example
$ /opt/bin/python3.11-config --cflags
-I/opt/include/python3.11 -I/opt/include/python3.11 -Wsign-compare  -DNDEBUG -g -fwrapv -O3 -Wall
@end example

@item 
@code{pythonX.Y-config --ldflags --embed} は推奨のリンクオプションを出力します:

@example
$ /opt/bin/python3.11-config --ldflags --embed
-L/opt/lib/python3.11/config-3.11-x86_64-linux-gnu -L/opt/lib -lpython3.11 -lpthread -ldl  -lutil -lm
@end example
@end itemize

@cartouche
@quotation 注釈 
複数 Python バージョン共存(とりわけシステムの Python とあなた自身でビルドした Python)での混乱を避けるために、上での例のように @code{python`X.Y'-config} は絶対パスで起動したほうが良いです。
@end quotation
@end cartouche

もしこの手順でうまくいかなければ(たしかにこれは全ての Unix 的なプラットフォームで動作することを保障するものではないですが、 @ref{4f19,,bug reports} は歓迎です)、あなたのシステムのダイナミックリンクについてのドキュメントを読み、Python の @code{Makefile} のコンパイルオプションを調べる必要があるでしょう(Makefile の場所を調べるには @ref{4973,,sysconfig.get_makefile_filename()} を使ってください)。この場合、 @ref{e1,,sysconfig} モジュールが役に立つ道具になります。これによってあなたが付け加えたいコンパイル・リンクのオプション構成をプログラム的に抽出できます。例えば:

@example
>>> import sysconfig
>>> sysconfig.get_config_var('LIBS')
'-lpthread -ldl  -lutil'
>>> sysconfig.get_config_var('LINKFORSHARED')
'-Xlinker -export-dynamic'
@end example

@c XXX similar documentation for Windows missing

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python/C API リファレンスマニュアル,Python モジュールのインストール,Python インタプリタの拡張と埋め込み,Top
@anchor{c-api/index doc}@anchor{4f1a}@anchor{c-api/index c-api-index}@anchor{1fbe}@anchor{c-api/index python-c-api-reference-manual}@anchor{4f1b}@anchor{c-api/index translation-repo}@anchor{4f1c}
@chapter Python/C API リファレンスマニュアル


このマニュアルでは、拡張モジュールを書いたり Python インタプリタをアプリケーションに埋め込んだりしたい C/C++ プログラマが利用できる API について述べています。 @ref{1fbd,,Python インタプリタの拡張と埋め込み} は拡張モジュールを書く際の一般的な決まりごとについて記述していますが、 API の詳細までは記述していないので、このドキュメントが手引きになります。

@menu
* はじめに: はじめに<14>. 
* C API の安定性:: 
* 超高水準レイヤ:: 
* 参照カウント:: 
* 例外処理:: 
* 拡張モジュールの定義:: 
* ユーティリティ: ユーティリティ<2>. 
* 抽象オブジェクトレイヤ (Abstract Objects Layer): 抽象オブジェクトレイヤ Abstract Objects Layer. 
* 具象オブジェクト (concrete object) レイヤ: 具象オブジェクト concrete object レイヤ. 
* 初期化 (initialization)、終了処理 (finalization)、スレッド: 初期化 initialization 、終了処理 finalization 、スレッド. 
* Python 初期化設定:: 
* メモリ管理:: 
* オブジェクト実装サポート (object implementation support): オブジェクト実装サポート object implementation support. 
* API と ABI のバージョニング:: 
* Monitoring C API:: 
* Generating Execution Events:: 

@end menu

@node はじめに<14>,C API の安定性,,Python/C API リファレンスマニュアル
@anchor{c-api/intro doc}@anchor{4f1d}@anchor{c-api/intro api-intro}@anchor{4f1e}@anchor{c-api/intro introduction}@anchor{4f1f}
@section はじめに


Python のアプリケーションプログラマ用インタフェース (Application Programmer's Interface, API) は、 Python インタプリタに対する様々なレベルでのアクセス手段を C や C++ のプログラマに提供しています。この API は通常 C++ からも全く同じように利用できるのですが、簡潔な呼び名にするために Python/C API と名づけられています。根本的に異なる二つの目的から、 Python/C API が用いられます。第一は、特定用途の `拡張モジュール (extension module)' 、すなわち Python インタプリタを拡張する C で書かれたモジュールを記述する、という目的です。第二は、より大規模なアプリケーション内で Python を構成要素 (component) として利用するという目的です; このテクニックは、一般的にはアプリケーションへの Python の埋め込み (`embedding') と呼びます。

拡張モジュールの作成は比較的わかりやすいプロセスで、 "手引書 (cookbook)" 的なアプローチでうまく実現できます。作業をある程度まで自動化してくれるツールもいくつかあります。一方、他のアプリケーションへの Python の埋め込みは、Python ができてから早い時期から行われてきましたが、拡張モジュールの作成に比べるとやや難解です。

多くの API 関数は、Python の埋め込みであるか拡張であるかに関わらず役立ちます; とはいえ、Python を埋め込んでいるほとんどのアプリケーションは、同時に自作の拡張モジュールも提供する必要が生じることになるでしょうから、Python を実際にアプリケーションに埋め込んでみる前に拡張モジュールの書き方に詳しくなっておくのはよい考えだと思います。

@menu
* 言語バージョン互換性:: 
* コーディング基準:: 
* インクルードファイル:: 
* 便利なマクロ:: 
* オブジェクト、型および参照カウント:: 
* 例外: 例外<24>. 
* Python の埋め込み: Python の埋め込み<2>. 
* デバッグ版ビルド (Debugging Builds): デバッグ版ビルド Debugging Builds. 
* おすすめのサードパーティツール: おすすめのサードパーティツール<2>. 

@end menu

@node 言語バージョン互換性,コーディング基準,,はじめに<14>
@anchor{c-api/intro language-version-compatibility}@anchor{4f20}
@subsection 言語バージョン互換性


Pythonの C API は C11 や C++11 バージョンの C と C++ に互換性があります。

This is a lower limit: the C API does not require features from later
C/C++ versions.
You do `not' need to enable your compiler's "c11 mode".

@node コーディング基準,インクルードファイル,言語バージョン互換性,はじめに<14>
@anchor{c-api/intro coding-standards}@anchor{4f21}
@subsection コーディング基準


CPython に含める C コードを書いている場合は、 
@geindex Python Enhancement Proposals; PEP 7
PEP 7@footnote{https://peps.python.org/pep-0007/} のガイドラインと基準に従わなければ `なりません' 。
このガイドラインは、コントリビュート対象の Python のバージョンに関係無く適用されます。
自身のサードパーティーのモジュールでは、それをいつか Python にコントリビュートするつもりでなければ、この慣習に従う必要はありません。

@node インクルードファイル,便利なマクロ,コーディング基準,はじめに<14>
@anchor{c-api/intro api-includes}@anchor{987}@anchor{c-api/intro include-files}@anchor{4f22}
@subsection インクルードファイル


Python/C API を使うために必要な、関数、型およびマクロの全ての定義をインクルードするには、以下の行:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
@end example

をソースコードに記述します。この行を記述すると、標準ヘッダ: @code{<stdio.h>}, @code{<string.h>}, @code{<errno.h>}, @code{<limits.h>}, @code{<assert.h>}, @code{<stdlib.h>} を (利用できれば) インクルードします。

@cartouche
@quotation 注釈 
Python は、システムによっては標準ヘッダの定義に影響するようなプリプロセッサ定義を行っているので、 @code{Python.h} をいずれの標準ヘッダよりも前にインクルード `せねばなりません' 。

@code{Python.h} をインクルードする前に、常に @code{PY_SSIZE_T_CLEAN} を定義することが推奨されます。
このマクロの解説については @ref{3d5,,引数の解釈と値の構築} を参照してください。
@end quotation
@end cartouche

Python.h で定義されている、ユーザから見える名前全て (Python.h がインクルードしている標準ヘッダの名前は除きます) には、接頭文字列 @code{Py} または @code{_Py} が付きます。@code{_Py} で始まる名前は Python 実装で内部使用するための名前で、拡張モジュールの作者は使ってはなりません。構造体のメンバには予約済みの接頭文字列はありません。

@cartouche
@quotation 注釈 
API のユーザは、@code{Py} や @code{_Py} で始まる名前を定義するコードを絶対に書いてはなりません。
後からコードを読む人を混乱させたり、将来の Python のバージョンで同じ名前が定義されて、ユーザの書いたコードの可搬性を危うくする可能性があります。
@end quotation
@end cartouche

ヘッダファイル群は通常 Python と共にインストールされます。 Unixでは @code{`prefix'/include/pythonversion/} および @code{`exec_prefix'/include/pythonversion/} に置かれます。 @ref{214f,,prefix} と @ref{2150,,exec_prefix} は Python をビルドする際の @code{configure} スクリプトに与えたパラメタに対応し、 `version' は @code{'%d.%d' % sys.version_info[:2]} に対応します。 Windows では、ヘッダは @code{`prefix'/include} に置かれます。 @code{prefix} はインストーラに指定したインストールディレクトリです。

ヘッダをインクルードするには、各ヘッダの入ったディレクトリ (別々のディレクトリの場合は両方) を、コンパイラがインクルードファイルを検索するためのパスに入れます。親ディレクトリをサーチパスに入れて、 @code{#include <pythonX.Y/Python.h>} のようにしては `なりません' ; @ref{214f,,prefix} 内のプラットフォームに依存しないヘッダは、 @ref{2150,,exec_prefix} からプラットフォーム依存のヘッダをインクルードしているので、このような操作を行うと複数のプラットフォームでのビルドができなくなります。

C++ users should note that although the API is defined entirely using C, the
header files properly declare the entry points to be @code{extern "C"}. As a result,
there is no need to do anything special to use the API from C++.

@node 便利なマクロ,オブジェクト、型および参照カウント,インクルードファイル,はじめに<14>
@anchor{c-api/intro useful-macros}@anchor{4f23}
@subsection 便利なマクロ


Several useful macros are defined in the Python header files.  Many are
defined closer to where they are useful (for example, @ref{168c,,Py_RETURN_NONE},
@ref{16ec,,PyMODINIT_FUNC}).
Others of a more general utility are defined here.  This is not necessarily a
complete listing.

@geindex Py_CAN_START_THREADS (C macro)
@anchor{c-api/intro c Py_CAN_START_THREADS}@anchor{4f24}
@deffn {C のマクロ} Py_CAN_START_THREADS

If this macro is defined, then the current system is able to start threads.

Currently, all systems supported by CPython (per 
@geindex Python Enhancement Proposals; PEP 11
PEP 11@footnote{https://peps.python.org/pep-0011/}), with the
exception of some WebAssembly platforms, support starting threads.


Added in version 3.13.

@end deffn

@geindex Py_GETENV (C macro)
@anchor{c-api/intro c Py_GETENV}@anchor{4f25}
@deffn {C のマクロ} Py_GETENV (s)

Like @code{getenv(@var{s})}, but returns @code{NULL} if @ref{b56,,-E} was passed
on the command line (see @ref{40b,,PyConfig.use_environment}).
@end deffn

@menu
* Docstring macros:: 
* General utility macros:: 
* Declaration utilities:: 
* Outdated macros:: 

@end menu

@node Docstring macros,General utility macros,,便利なマクロ
@anchor{c-api/intro docstring-macros}@anchor{4f26}
@subsubsection Docstring macros


@geindex PyDoc_STRVAR (C macro)
@anchor{c-api/intro c PyDoc_STRVAR}@anchor{1d5b}
@deffn {C のマクロ} PyDoc_STRVAR (name, str)

Creates a variable with name `name' that can be used in docstrings.
If Python is built without docstrings (@ref{21a2,,--without-doc-strings}),
the value will be an empty string.

以下はプログラム例です:

@example
PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

static PyMethodDef deque_methods[] = @{
    // ...
    @{"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc@},
    // ...
@}
@end example

Expands to @code{PyDoc_VAR(@var{name}) = PyDoc_STR(@var{str})}.
@end deffn

@geindex PyDoc_STR (C macro)
@anchor{c-api/intro c PyDoc_STR}@anchor{1b96}
@deffn {C のマクロ} PyDoc_STR (str)

Expands to the given input string, or an empty string
if docstrings are disabled (@ref{21a2,,--without-doc-strings}).

以下はプログラム例です:

@example
static PyMethodDef pysqlite_row_methods[] = @{
    @{"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
        PyDoc_STR("Returns the keys of the row.")@},
    @{NULL, NULL@}
@};
@end example
@end deffn

@geindex PyDoc_VAR (C macro)
@anchor{c-api/intro c PyDoc_VAR}@anchor{1df0}
@deffn {C のマクロ} PyDoc_VAR (name)

Declares a static character array variable with the given `name'.
Expands to @code{static const char @var{name}[]}

例えば:

@example
PyDoc_VAR(python_doc) = PyDoc_STR(
   "A genus of constricting snakes in the Pythonidae family native "
   "to the tropics and subtropics of the Eastern Hemisphere.");
@end example
@end deffn

@node General utility macros,Declaration utilities,Docstring macros,便利なマクロ
@anchor{c-api/intro general-utility-macros}@anchor{4f27}
@subsubsection General utility macros


The following macros are for common tasks not specific to Python.

@geindex Py_UNUSED (C macro)
@anchor{c-api/intro c Py_UNUSED}@anchor{1a8a}
@deffn {C のマクロ} Py_UNUSED (arg)

コンパイラ警告を抑えるために関数定義の使用されない引数に使用してください。例えば: @code{int func(int a, int Py_UNUSED(b)) @{ return a; @}} 。


Added in version 3.4.

@end deffn

@geindex Py_GCC_ATTRIBUTE (C macro)
@anchor{c-api/intro c Py_GCC_ATTRIBUTE}@anchor{4f28}
@deffn {C のマクロ} Py_GCC_ATTRIBUTE (name)

Use a GCC attribute `name', hiding it from compilers that don't support GCC
attributes (such as MSVC).

This expands to @code{__attribute__((@var{name)})} on a GCC compiler,
and expands to nothing on compilers that don't support GCC attributes.
@end deffn

@menu
* Numeric utilities:: 
* Assertion utilities:: 
* Type size utilities:: 
* Macro definition utilities:: 

@end menu

@node Numeric utilities,Assertion utilities,,General utility macros
@anchor{c-api/intro numeric-utilities}@anchor{4f29}
@subsubsection Numeric utilities


@geindex Py_ABS (C macro)
@anchor{c-api/intro c Py_ABS}@anchor{4f2a}
@deffn {C のマクロ} Py_ABS (x)

@code{x} の絶対値を返します。

The argument may be evaluated more than once.
Consequently, do not pass an expression with side-effects directly
to this macro.

If the result cannot be represented (for example, if @code{x} has
@code{INT_MIN} value for int type), the behavior is
undefined.

Corresponds roughly to @code{((@var{x}) < 0 ? -(@var{x}) : (@var{x}))}


Added in version 3.3.

@end deffn

@geindex Py_MAX (C macro)
@geindex Py_MIN (C macro)
@anchor{c-api/intro c Py_MAX}@anchor{4f2b}
@deffn {C のマクロ} Py_MAX (x, y)
@anchor{c-api/intro c Py_MIN}@anchor{4f2c}
@deffnx {C のマクロ} Py_MIN (x, y)

Return the larger or smaller of the arguments, respectively.

Any arguments may be evaluated more than once.
Consequently, do not pass an expression with side-effects directly
to this macro.

@code{Py_MAX} corresponds roughly to
@code{(((@var{x}) > (@var{y})) ? (@var{x}) : (@var{y}))}.


Added in version 3.3.

@end deffn

@geindex Py_ARITHMETIC_RIGHT_SHIFT (C macro)
@anchor{c-api/intro c Py_ARITHMETIC_RIGHT_SHIFT}@anchor{4f2d}
@deffn {C のマクロ} Py_ARITHMETIC_RIGHT_SHIFT (type, integer, positions)

Similar to @code{@var{integer} >> @var{positions}}, but forces sign extension,
as the C standard does not define whether a right-shift of a signed
integer will perform sign extension or a zero-fill.

`integer' should be any signed integer type.
`positions' is the number of positions to shift to the right.

Both `integer' and `positions' can be evaluated more than once;
consequently, avoid directly passing a function call or some other
operation with side-effects to this macro. Instead, store the result as a
variable and then pass it.

`type' is unused and only kept for backwards compatibility. Historically,
`type' was used to cast `integer'.


バージョン 3.1 で変更: This macro is now valid for all signed integer types, not just those for
which @code{unsigned type} is legal. As a result, `type' is no longer
used.

@end deffn

@geindex Py_CHARMASK (C macro)
@anchor{c-api/intro c Py_CHARMASK}@anchor{4f2e}
@deffn {C のマクロ} Py_CHARMASK (c)

引数は文字か、[-128, 127] あるいは [0, 255] の範囲の整数でなければなりません。
このマクロは @code{符号なし文字} にキャストした @code{c} を返します。
@end deffn

@node Assertion utilities,Type size utilities,Numeric utilities,General utility macros
@anchor{c-api/intro assertion-utilities}@anchor{4f2f}
@subsubsection Assertion utilities


@geindex Py_UNREACHABLE (C macro)
@anchor{c-api/intro c Py_UNREACHABLE}@anchor{dae}
@deffn {C のマクロ} Py_UNREACHABLE ()

Use this when you have a code path that cannot be reached by design.
For example, in the @code{default:} clause in a @code{switch} statement for which
all possible values are covered in @code{case} statements.  Use this in places
where you might be tempted to put an @code{assert(0)} or @code{abort()} call.

In release mode, the macro helps the compiler to optimize the code, and
avoids a warning about unreachable code.  For example, the macro is
implemented with @code{__builtin_unreachable()} on GCC in release mode.

In debug mode, and on unsupported compilers, the macro expands to a call to
@ref{b7a,,Py_FatalError()}.

A use for @code{Py_UNREACHABLE()} is following a call to a function that
never returns but that is not declared @code{_Noreturn}.

If a code path is very unlikely code but can be reached under exceptional
case, this macro must not be used.  For example, under low memory condition
or if a system call returns a value out of the expected range.  In this
case, it's better to report the error to the caller.  If the error cannot
be reported to caller, @ref{b7a,,Py_FatalError()} can be used.


Added in version 3.7.

@end deffn

@geindex Py_SAFE_DOWNCAST (C macro)
@anchor{c-api/intro c Py_SAFE_DOWNCAST}@anchor{4f30}
@deffn {C のマクロ} Py_SAFE_DOWNCAST (value, larger, smaller)

Cast `value' to type `smaller' from type `larger', validating that no
information was lost.

On release builds of Python, this is roughly equivalent to
@code{((@var{smaller}) @var{value})}
(in C++, @code{static_cast<@var{smaller}>(@var{value})} will be used instead).

On debug builds (implying that @ref{1834,,Py_DEBUG} is defined), this asserts
that no information was lost with the cast from `larger' to `smaller'.

`value', `larger', and `smaller' may all be evaluated more than once in the
expression; consequently, do not pass an expression with side-effects
directly to this macro.
@end deffn

@geindex Py_BUILD_ASSERT (C macro)
@anchor{c-api/intro c Py_BUILD_ASSERT}@anchor{19b3}
@deffn {C のマクロ} Py_BUILD_ASSERT (cond)

Asserts a compile-time condition `cond', as a statement.
The build will fail if the condition is false or cannot be evaluated at compile time.

Corresponds roughly to @code{static_assert(@var{cond})} on C23 and above.

例えば:

@example
Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(int64_t));
@end example


Added in version 3.3.

@end deffn

@geindex Py_BUILD_ASSERT_EXPR (C macro)
@anchor{c-api/intro c Py_BUILD_ASSERT_EXPR}@anchor{19b4}
@deffn {C のマクロ} Py_BUILD_ASSERT_EXPR (cond)

Asserts a compile-time condition `cond', as an expression that evaluates to @code{0}.
The build will fail if the condition is false or cannot be evaluated at compile time.

例えば:

@example
#define foo_to_char(foo) \
    ((char *)(foo) + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))
@end example


Added in version 3.3.

@end deffn

@node Type size utilities,Macro definition utilities,Assertion utilities,General utility macros
@anchor{c-api/intro type-size-utilities}@anchor{4f31}
@subsubsection Type size utilities


@geindex Py_ARRAY_LENGTH (C macro)
@anchor{c-api/intro c Py_ARRAY_LENGTH}@anchor{4f32}
@deffn {C のマクロ} Py_ARRAY_LENGTH (array)

Compute the length of a statically allocated C array at compile time.

The `array' argument must be a C array with a size known at compile time.
Passing an array with an unknown size, such as a heap-allocated array,
will result in a compilation error on some compilers, or otherwise produce
incorrect results.

This is roughly equivalent to:

@example
sizeof(array) / sizeof((array)[0])
@end example
@end deffn

@geindex Py_MEMBER_SIZE (C macro)
@anchor{c-api/intro c Py_MEMBER_SIZE}@anchor{4f33}
@deffn {C のマクロ} Py_MEMBER_SIZE (type, member)

Return the size of a structure (`type') `member' in bytes.

Corresponds roughly to @code{sizeof(((@var{type} *)NULL)->@var{member})}.


Added in version 3.6.

@end deffn

@node Macro definition utilities,,Type size utilities,General utility macros
@anchor{c-api/intro macro-definition-utilities}@anchor{4f34}
@subsubsection Macro definition utilities


@geindex Py_FORCE_EXPANSION (C macro)
@anchor{c-api/intro c Py_FORCE_EXPANSION}@anchor{4f35}
@deffn {C のマクロ} Py_FORCE_EXPANSION (X)

This is equivalent to @code{@var{X}}, which is useful for token-pasting in
macros, as macro expansions in `X' are forcefully evaluated by the
preprocessor.
@end deffn

@geindex Py_STRINGIFY (C macro)
@anchor{c-api/intro c Py_STRINGIFY}@anchor{4f36}
@deffn {C のマクロ} Py_STRINGIFY (x)

Convert @code{x} to a C string.  For example, @code{Py_STRINGIFY(123)} returns
@code{"123"}.


Added in version 3.4.

@end deffn

@node Declaration utilities,Outdated macros,General utility macros,便利なマクロ
@anchor{c-api/intro declaration-utilities}@anchor{4f37}
@subsubsection Declaration utilities


The following macros can be used in declarations.
They are most useful for defining the C API itself, and have limited use
for extension authors.
Most of them expand to compiler-specific spellings of common extensions
to the C language.

@geindex Py_ALWAYS_INLINE (C macro)
@anchor{c-api/intro c Py_ALWAYS_INLINE}@anchor{1c6b}
@deffn {C のマクロ} Py_ALWAYS_INLINE

Ask the compiler to always inline a static inline function. The compiler can
ignore it and decide to not inline the function.

Corresponds to @code{always_inline} attribute in GCC and @code{__forceinline}
in MSVC.

It can be used to inline performance critical static inline functions when
building Python in debug mode with function inlining disabled. For example,
MSC disables function inlining when building in debug mode.

Marking blindly a static inline function with Py_ALWAYS_INLINE can result in
worse performances (due to increased code size for example). The compiler is
usually smarter than the developer for the cost/benefit analysis.

If Python is @ref{509,,built in debug mode} (if the @ref{1834,,Py_DEBUG}
macro is defined), the @ref{1c6b,,Py_ALWAYS_INLINE} macro does nothing.

It must be specified before the function return type. Usage:

@example
static inline Py_ALWAYS_INLINE int random(void) @{ return 4; @}
@end example


Added in version 3.11.

@end deffn

@geindex Py_NO_INLINE (C macro)
@anchor{c-api/intro c Py_NO_INLINE}@anchor{1802}
@deffn {C のマクロ} Py_NO_INLINE

Disable inlining on a function. For example, it reduces the C stack
consumption: useful on LTO+PGO builds which heavily inline code (see
bpo-33720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33720}).

Corresponds to the @code{noinline} attribute/specification on GCC and MSVC.

使い方:

@example
Py_NO_INLINE static int random(void) @{ return 4; @}
@end example


Added in version 3.11.

@end deffn

@geindex Py_DEPRECATED (C macro)
@anchor{c-api/intro c Py_DEPRECATED}@anchor{c9b}
@deffn {C のマクロ} Py_DEPRECATED (version)

Use this to declare APIs that were deprecated in a specific CPython version.
The macro must be placed before the symbol name.

以下はプログラム例です:

@example
Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
@end example


バージョン 3.8 で変更: MSVC サポートが追加されました。

@end deffn

@geindex Py_LOCAL (C macro)
@anchor{c-api/intro c Py_LOCAL}@anchor{1663}
@deffn {C のマクロ} Py_LOCAL (type)

Declare a function returning the specified `type' using a fast-calling
qualifier for functions that are local to the current file.
Semantically, this is equivalent to @code{static @var{type}}.
@end deffn

@geindex Py_LOCAL_INLINE (C macro)
@anchor{c-api/intro c Py_LOCAL_INLINE}@anchor{1664}
@deffn {C のマクロ} Py_LOCAL_INLINE (type)

Equivalent to @ref{1663,,Py_LOCAL} but additionally requests the function
be inlined.
@end deffn

@geindex Py_LOCAL_SYMBOL (C macro)
@anchor{c-api/intro c Py_LOCAL_SYMBOL}@anchor{4f38}
@deffn {C のマクロ} Py_LOCAL_SYMBOL

Macro used to declare a symbol as local to the shared library (hidden).
On supported platforms, it ensures the symbol is not exported.

On compatible versions of GCC/Clang, it
expands to @code{__attribute__((visibility("hidden")))}.
@end deffn

@geindex Py_EXPORTED_SYMBOL (C macro)
@anchor{c-api/intro c Py_EXPORTED_SYMBOL}@anchor{4f39}
@deffn {C のマクロ} Py_EXPORTED_SYMBOL

Macro used to declare a symbol (function or data) as exported.
On Windows, this expands to @code{__declspec(dllexport)}.
On compatible versions of GCC/Clang, it
expands to @code{__attribute__((visibility("default")))}.
This macro is for defining the C API itself; extension modules should not use it.
@end deffn

@geindex Py_IMPORTED_SYMBOL (C macro)
@anchor{c-api/intro c Py_IMPORTED_SYMBOL}@anchor{4f3a}
@deffn {C のマクロ} Py_IMPORTED_SYMBOL

Macro used to declare a symbol as imported.
On Windows, this expands to @code{__declspec(dllimport)}.
This macro is for defining the C API itself; extension modules should not use it.
@end deffn

@geindex PyAPI_FUNC (C macro)
@anchor{c-api/intro c PyAPI_FUNC}@anchor{4f3b}
@deffn {C のマクロ} PyAPI_FUNC (type)

Macro used by CPython to declare a function as part of the C API.
Its expansion depends on the platform and build configuration.
This macro is intended for defining CPython's C API itself;
extension modules should not use it for their own symbols.
@end deffn

@geindex PyAPI_DATA (C macro)
@anchor{c-api/intro c PyAPI_DATA}@anchor{4f3c}
@deffn {C のマクロ} PyAPI_DATA (type)

Macro used by CPython to declare a public global variable as part of the C API.
Its expansion depends on the platform and build configuration.
This macro is intended for defining CPython's C API itself;
extension modules should not use it for their own symbols.
@end deffn

@node Outdated macros,,Declaration utilities,便利なマクロ
@anchor{c-api/intro outdated-macros}@anchor{4f3d}
@subsubsection Outdated macros


The following macros have been used to features that have been standardized
in C11.

@geindex Py_ALIGNED (C macro)
@anchor{c-api/intro c Py_ALIGNED}@anchor{4f3e}
@deffn {C のマクロ} Py_ALIGNED (num)

Specify alignment to `num' bytes on compilers that support it.

Consider using the C11 standard @code{_Alignas} specifier over this macro.
@end deffn

@geindex Py_LL (C macro)
@geindex Py_ULL (C macro)
@anchor{c-api/intro c Py_LL}@anchor{4f3f}
@deffn {C のマクロ} Py_LL (number)
@anchor{c-api/intro c Py_ULL}@anchor{4f40}
@deffnx {C のマクロ} Py_ULL (number)

Use `number' as a @code{long long} or @code{unsigned long long} integer literal,
respectively.

Expands to `number' followed by @code{LL} or @code{LLU}, respectively, but will
expand to some compiler-specific suffixes on some older compilers.

Consider using the C99 standard suffixes @code{LL} and @code{LLU} directly.
@end deffn

@geindex Py_MEMCPY (C macro)
@anchor{c-api/intro c Py_MEMCPY}@anchor{1990}
@deffn {C のマクロ} Py_MEMCPY (dest, src, n)

This is a @ref{23d,,soft deprecated} alias to @code{memcpy()}.
Use @code{memcpy()} directly instead.


バージョン 3.14 で非推奨: The macro is @ref{23d,,soft deprecated}.

@end deffn

@geindex Py_VA_COPY (C macro)
@anchor{c-api/intro c Py_VA_COPY}@anchor{4f41}
@deffn {C のマクロ} Py_VA_COPY

This is a @ref{23d,,soft deprecated} alias to the C99-standard @code{va_copy}
function.

Historically, this would use a compiler-specific method to copy a @code{va_list}.


バージョン 3.6 で変更: This is now an alias to @code{va_copy}.

@end deffn

@node オブジェクト、型および参照カウント,例外<24>,便利なマクロ,はじめに<14>
@anchor{c-api/intro api-objects}@anchor{4f42}@anchor{c-api/intro objects-types-and-reference-counts}@anchor{4f43}
@subsection オブジェクト、型および参照カウント


@geindex object;type

Python/C API 関数は、 @ref{5df,,PyObject}* 型の一つ以上の引数と戻り値を持ちます。この型は、任意の Python オブジェクトを表現する不透明 (opaque) なデータ型へのポインタです。 Python 言語は、全ての Python オブジェクト型をほとんどの状況 (例えば代入、スコープ規則 (scope rule)、引数渡し) で同様に扱います。ほとんど全ての Python オブジェクトはヒープ (heap) 上に置かれます: このため、 @ref{5df,,PyObject} 型のオブジェクトは、自動記憶 (automatic) としても静的記憶 (static) としても宣言できません。 @ref{5df,,PyObject}* 型のポインタ変数のみ宣言できます。唯一の例外は、型オブジェクトです; 型オブジェクトはメモリ解放 (deallocate) してはならないので、通常は静的記憶の @ref{c9c,,PyTypeObject} オブジェクトにします。

全ての Python オブジェクトには (Python 整数型ですら) 型 (`type')  と参照カウント (`reference count') があります。あるオブジェクトの型は、そのオブジェクトがどの種類のオブジェクトか (例えば整数、リスト、ユーザ定義関数、など; その他多数については @ref{232f,,標準型の階層} で説明しています) を決定します。よく知られている型については、各々マクロが存在して、あるオブジェクトがその型かどうか調べられます; 例えば、 @code{PyList_Check(a)} は、 `a' で示されたオブジェクトが Python リスト型のとき (かつそのときに限り) 真値を返します。

@menu
* 参照カウント法: 参照カウント法<2>. 
* 型: 型<2>. 

@end menu

@node 参照カウント法<2>,型<2>,,オブジェクト、型および参照カウント
@anchor{c-api/intro api-refcounts}@anchor{4f44}@anchor{c-api/intro reference-counts}@anchor{4f45}
@subsubsection 参照カウント法


The reference count is important because today's computers have a  finite
(and often severely limited) memory size; it counts how many different
places there are that have a @ref{5e2,,strong reference} to an object.
Such a place could be another object, or a global (or static) C variable,
or a local variable in some C function.
When the last @ref{5e2,,strong reference} to an object is released
(i.e. its reference count becomes zero), the object is deallocated.
If it contains references to other objects, those references are released.
Those other objects may be deallocated in turn, if there are no more
references to them, and so on.  (There's an obvious problem  with
objects that reference each other here; for now, the solution
is "don't do that.")

@geindex Py_INCREF (C function)
@geindex Py_DECREF (C function)

Reference counts are always manipulated explicitly.  The normal way is
to use the macro @ref{78f,,Py_INCREF()} to take a new reference to an
object (i.e. increment its reference count by one),
and @ref{790,,Py_DECREF()} to release that reference (i.e. decrement the
reference count by one).  The @ref{790,,Py_DECREF()} macro
is considerably more complex than the incref one, since it must check whether
the reference count becomes zero and then cause the object's deallocator to be
called.  The deallocator is a function pointer contained in the object's type
structure.  The type-specific deallocator takes care of releasing references
for other objects contained in the object if this is a compound
object type, such as a list, as well as performing any additional finalization
that's needed.  There's no chance that the reference count can overflow; at
least as many bits are used to hold the reference count as there are distinct
memory locations in virtual memory (assuming @code{sizeof(Py_ssize_t) >= sizeof(void*)}).
Thus, the reference count increment is a simple operation.

It is not necessary to hold a @ref{5e2,,strong reference} (i.e. increment
the reference count) for every local variable that contains a pointer
to an object.  In theory, the  object's
reference count goes up by one when the variable is made to  point to it and it
goes down by one when the variable goes out of  scope.  However, these two
cancel each other out, so at the end the  reference count hasn't changed.  The
only real reason to use the  reference count is to prevent the object from being
deallocated as  long as our variable is pointing to it.  If we know that there
is at  least one other reference to the object that lives at least as long as
our variable, there is no need to take a new @ref{5e2,,strong reference}
(i.e. increment the reference count) temporarily.
An important situation where this arises is in objects  that are passed as
arguments to C functions in an extension module  that are called from Python;
the call mechanism guarantees to hold a  reference to every argument for the
duration of the call.

However, a common pitfall is to extract an object from a list and hold on to it
for a while without taking a new reference.  Some other operation might
conceivably remove the object from the list, releasing that reference,
and possibly deallocating it. The real danger is that innocent-looking
operations may invoke arbitrary Python code which could do this; there is a code
path which allows control to flow back to the user from a @ref{790,,Py_DECREF()}, so
almost any operation is potentially dangerous.

A safe approach is to always use the generic operations (functions  whose name
begins with @code{PyObject_}, @code{PyNumber_}, @code{PySequence_} or @code{PyMapping_}).
These operations always create a new @ref{5e2,,strong reference}
(i.e. increment the reference count) of the object they return.
This leaves the caller with the responsibility to call @ref{790,,Py_DECREF()} when
they are done with the result; this soon becomes second nature.

@menu
* 参照カウントの詳細:: 

@end menu

@node 参照カウントの詳細,,,参照カウント法<2>
@anchor{c-api/intro api-refcountdetails}@anchor{4f46}@anchor{c-api/intro reference-count-details}@anchor{4f47}
@subsubsection 参照カウントの詳細


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 releasing it by calling @ref{790,,Py_DECREF()} or @ref{992,,Py_XDECREF()}
when it's no longer needed---or passing on this responsibility (usually to its
caller). When a function passes ownership of a reference on to its caller, the
caller is said to receive a `new' reference.  When no ownership is transferred,
the caller is said to `borrow' the reference. Nothing needs to be done for a
@ref{3d7,,borrowed reference}.

逆に、ある関数呼び出しで、あるオブジェクトへの参照を呼び出される関数に渡す際には、二つの可能性: 関数がオブジェクトへの参照を `盗み取る' (steal) 場合と、そうでない場合があります。`参照を盗む' とは、関数に参照を渡したときに、参照の所有者がその関数になったと仮定し、関数の呼び出し元には所有権がなくなるということです。

@geindex PyList_SetItem (C function)
@geindex PyTuple_SetItem (C function)

参照を盗み取る関数はほとんどありません; 例外としてよく知られているのは、 @ref{18ba,,PyList_SetItem()} と @ref{4eb8,,PyTuple_SetItem()} で、これらはシーケンスに入れる要素に対する参照を盗み取ります (しかし、要素の入る先のタプルやリストの参照は盗み取りません!)。これらの関数は、リストやタプルの中に新たに作成されたオブジェクトを入れていく際の常套的な書き方をしやすくするために、参照を盗み取るように設計されています; 例えば、 @code{(1, 2, "three")} というタプルを生成するコードは以下のようになります (とりあえず例外処理のことは忘れておきます; もっとよい書き方を後で示します):

@example
PyObject *t;

t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
@end example

ここで、 @ref{1bd0,,PyLong_FromLong()} は新しい参照を返し、すぐに @ref{4eb8,,PyTuple_SetItem()} に盗まれます。参照が盗まれた後もそのオブジェクトを利用したい場合は、参照盗む関数を呼び出す前に、 @ref{78f,,Py_INCREF()} を利用してもう一つの参照を取得してください。

ちなみに、 @ref{4eb8,,PyTuple_SetItem()} はタプルに値をセットするための `唯一の' 方法です; タプルは変更不能なデータ型なので、 @ref{1e35,,PySequence_SetItem()} や @ref{4f48,,PyObject_SetItem()} を使うと上の操作は拒否されてしまいます。自分でタプルの値を入れていくつもりなら、 @ref{4eb8,,PyTuple_SetItem()} だけしか使えません。

同じく、リストに値を入れていくコードは @ref{4f49,,PyList_New()} と @ref{18ba,,PyList_SetItem()} で書けます。

しかし実際には、タプルやリストを生成して値を入れる際には、上記のような方法はほとんど使いません。より汎用性のある関数、 @ref{3c2,,Py_BuildValue()} があり、ほとんどの主要なオブジェクトをフォーマット文字列 `format string' の指定に基づいて C の値から生成できます。例えば、上の二種類のコードブロックは、以下のように置き換えられます (エラーチェックにも配慮しています):

@example
PyObject *tuple, *list;

tuple = Py_BuildValue("(iis)", 1, 2, "three");
list = Py_BuildValue("[iis]", 1, 2, "three");
@end example

It is much more common to use @ref{4f48,,PyObject_SetItem()} 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 references
is much saner, since you don't have to take a new reference just so you
can give that reference away ("have it be stolen").  For example, this function
sets all items of a list (actually, any mutable sequence) to a given item:

@example
int
set_all(PyObject *target, PyObject *item)
@{
    Py_ssize_t i, n;

    n = PyObject_Length(target);
    if (n < 0)
        return -1;
    for (i = 0; i < n; i++) @{
        PyObject *index = PyLong_FromSsize_t(i);
        if (!index)
            return -1;
        if (PyObject_SetItem(target, index, item) < 0) @{
            Py_DECREF(index);
            return -1;
        @}
        Py_DECREF(index);
    @}
    return 0;
@}
@end example

@geindex set_all()

関数の戻り値の場合には、状況は少し異なります。ほとんどの関数については、参照を渡してもその参照に対する所有権が変わることがない一方で、あるオブジェクトに対する参照を返すような多くの関数は、参照に対する所有権を呼び出し側に与えます。理由は簡単です: 多くの場合、関数が返すオブジェクトはその場で (on the fly) 生成されるため、呼び出し側が得る参照は生成されたオブジェクトに対する唯一の参照になるからです。従って、 @ref{5ea,,PyObject_GetItem()} や @ref{1e34,,PySequence_GetItem()} のように、オブジェクトに対する参照を返す汎用の関数は、常に新たな参照を返します (呼び出し側が参照の所有者になります)。

重要なのは、関数が返す参照の所有権を持てるかどうかは、どの関数を呼び出すかだけによる、と理解することです --- 関数呼び出し時の `お飾り' (関数に引数として渡したオブジェクトの型) は `この問題には関係ありません!' 従って、 @ref{5ff,,PyList_GetItem()} を使ってリスト内の要素を得た場合には、参照の所有者にはなりません --- が、同じ要素を同じリストから @ref{1e34,,PySequence_GetItem()} (図らずもこの関数は全く同じ引数をとります) を使って取り出すと、返されたオブジェクトに対する参照を得ます。

@geindex PyList_GetItem (C function)
@geindex PySequence_GetItem (C function)

以下は、整数からなるリストに対して各要素の合計を計算する関数をどのようにして書けるかを示した例です; 一つは @ref{5ff,,PyList_GetItem()} を使っていて、もう一つは @ref{1e34,,PySequence_GetItem()} を使っています。

@example
long
sum_list(PyObject *list)
@{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;

    n = PyList_Size(list);
    if (n < 0)
        return -1; /* Not a list */
    for (i = 0; i < n; i++) @{
        item = PyList_GetItem(list, i); /* Can't fail */
        if (!PyLong_Check(item)) continue; /* Skip non-integers */
        value = PyLong_AsLong(item);
        if (value == -1 && PyErr_Occurred())
            /* Integer too big to fit in a C long, bail out */
            return -1;
        total += value;
    @}
    return total;
@}
@end example

@geindex sum_list()

@example
long
sum_sequence(PyObject *sequence)
@{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;
    n = PySequence_Length(sequence);
    if (n < 0)
        return -1; /* Has no length */
    for (i = 0; i < n; i++) @{
        item = PySequence_GetItem(sequence, i);
        if (item == NULL)
            return -1; /* Not a sequence, or other failure */
        if (PyLong_Check(item)) @{
            value = PyLong_AsLong(item);
            Py_DECREF(item);
            if (value == -1 && PyErr_Occurred())
                /* Integer too big to fit in a C long, bail out */
                return -1;
            total += value;
        @}
        else @{
            Py_DECREF(item); /* Discard reference ownership */
        @}
    @}
    return total;
@}
@end example

@geindex sum_sequence()

@node 型<2>,,参照カウント法<2>,オブジェクト、型および参照カウント
@anchor{c-api/intro api-types}@anchor{4f4a}@anchor{c-api/intro types}@anchor{4f4b}
@subsubsection 型


他にも Python/C API において重要な役割を持つデータ型がいくつかあります; ほとんどは int, long,  double, および char* といった、単なる C のデータ型です。また、モジュールで公開している関数を列挙する際に用いられる静的なテーブルや、新しいオブジェクト型におけるデータ属性を記述したり、複素数の値を記述したりするために構造体をいくつか使っています。これらの型については、その型を使う関数とともに説明してゆきます。

@geindex Py_ssize_t (C type)
@anchor{c-api/intro c Py_ssize_t}@anchor{c55}
@deffn {C のデータ型} type Py_ssize_t
` 次に属します: @ref{775,,Stable ABI}.'
A signed integral type such that @code{sizeof(Py_ssize_t) == sizeof(size_t)}.
C99 doesn't define such a thing directly (size_t is an unsigned integral type).
See 
@geindex Python Enhancement Proposals; PEP 353
PEP 353@footnote{https://peps.python.org/pep-0353/} for details. @code{PY_SSIZE_T_MAX} is the largest positive value
of type @ref{c55,,Py_ssize_t}.
@end deffn

@node 例外<24>,Python の埋め込み<2>,オブジェクト、型および参照カウント,はじめに<14>
@anchor{c-api/intro api-exceptions}@anchor{4f4c}@anchor{c-api/intro exceptions}@anchor{4f4d}
@subsection 例外


Python プログラマは、特定のエラー処理が必要なときだけしか例外を扱う必要はありません; 処理しなかった例外は、処理の呼び出し側、そのまた呼び出し側、といった具合に、トップレベルのインタプリタ層まで自動的に伝播します。インタプリタ層は、スタックトレースバックと合わせて例外をユーザに報告します。

@geindex PyErr_Occurred (C function)

ところが、 C プログラマの場合、エラーチェックは常に明示的に行わねばなりません。 Python/C API の全ての関数は、関数のドキュメントで明確に説明がない限り例外を発行する可能性があります。一般的な話として、ある関数が何らかのエラーに遭遇すると、関数は例外を設定して、関数内における参照の所有権を全て放棄し、エラー値 (error indicator) を返します。ドキュメントに書かれてない場合、このエラー値は関数の戻り値の型によって、 @code{NULL} か @code{-1} のどちらかになります。いくつかの関数ではブール型で真/偽を返し、偽はエラーを示します。きわめて少数の関数では明確なエラー指標を返さなかったり、あいまいな戻り値を返したりするので、 @ref{1caf,,PyErr_Occurred()} で明示的にエラーテストを行う必要があります。これらの例外は常に明示的にドキュメント化されます。

@geindex PyErr_SetString (C function)
@geindex PyErr_Clear (C function)

例外時の状態情報 (exception state)は、スレッド単位に用意された記憶領域 (per-thread storage) 内で管理されます (この記憶領域は、スレッドを使わないアプリケーションではグローバルな記憶領域と同じです)。一つのスレッドは二つの状態のどちらか: 例外が発生したか、まだ発生していないか、をとります。関数 @ref{1caf,,PyErr_Occurred()} を使うと、この状態を調べられます: この関数は例外が発生した際にはその例外型オブジェクトに対する借用参照 (borrowed reference) を返し、そうでないときには @code{NULL} を返します。例外状態を設定する関数は数多くあります: @ref{79c,,PyErr_SetString()} はもっともよく知られている (が、もっとも汎用性のない) 例外を設定するための関数で、 @ref{1232,,PyErr_Clear()} は例外状態情報を消し去る関数です。

完全な例外状態情報は、3 つのオブジェクト: 例外の型、例外の値、そしてトレースバック、からなります  (どのオブジェクトも @code{NULL} を取り得ます)。これらの情報は、 Python の @code{sys.exc_info()} の結果と同じ意味を持ちます; とはいえ、 C と Python の例外状態情報は全く同じではありません: Python における例外オブジェクトは、Python の @ref{8f8,,try} ...  @ref{1ab,,except} 文で最近処理したオブジェクトを表す一方、 C レベルの例外状態情報が存続するのは、渡された例外情報を @code{sys.exc_info()} その他に転送するよう取り計らう Python のバイトコードインタプリタのメインループに到達するまで、例外が関数の間で受け渡しされている間だけです。

@geindex exc_info (sys モジュール)

Python 1.5 からは、Python で書かれたコードから例外状態情報にアクセスする方法として、推奨されていてスレッドセーフな方法は @ref{89a,,sys.exc_info()} になっているので注意してください。この関数は Python コードの実行されているスレッドにおける例外状態情報を返します。また、これらの例外状態情報に対するアクセス手段は、両方とも意味づけ (semantics) が変更され、ある関数が例外を捕捉すると、その関数を実行しているスレッドの例外状態情報を保存して、呼び出し側の例外状態情報を維持するようになりました。この変更によって、無害そうに見える関数が現在扱っている例外を上書きすることで引き起こされる、例外処理コードでよくおきていたバグを抑止しています; また、トレースバック内のスタックフレームで参照されているオブジェクトがしばしば不必要に寿命を永らえていたのをなくしています。

一般的な原理として、ある関数が別の関数を呼び出して何らかの作業をさせるとき、呼び出し先の関数が例外を送出していないか調べなくてはならず、もし送出していれば、その例外状態情報は呼び出し側に渡されなければなりません。呼び出し元の関数はオブジェクト参照の所有権をすべて放棄し、エラー指標を返さなくてはなりませんが、余計に例外を設定する必要は `ありません' --- そんなことをすれば、たった今送出されたばかりの例外を上書きしてしまい、エラーの原因そのものに関する重要な情報を失うことになります。

@geindex sum_sequence()

A simple example of detecting exceptions and passing them on is shown in the
@code{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:

@example
def incr_item(dict, key):
    try:
        item = dict[key]
    except KeyError:
        item = 0
    dict[key] = item + 1
@end example

@geindex incr_item()

以下は対応するコードを C で完璧に書いたものです:

@example
int
incr_item(PyObject *dict, PyObject *key)
@{
    /* Objects all initialized to NULL for Py_XDECREF */
    PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
    int rv = -1; /* Return value initialized to -1 (failure) */

    item = PyObject_GetItem(dict, key);
    if (item == NULL) @{
        /* Handle KeyError only: */
        if (!PyErr_ExceptionMatches(PyExc_KeyError))
            goto error;

        /* Clear the error and use zero: */
        PyErr_Clear();
        item = PyLong_FromLong(0L);
        if (item == NULL)
            goto error;
    @}
    const_one = PyLong_FromLong(1L);
    if (const_one == NULL)
        goto error;

    incremented_item = PyNumber_Add(item, const_one);
    if (incremented_item == NULL)
        goto error;

    if (PyObject_SetItem(dict, key, incremented_item) < 0)
        goto error;
    rv = 0; /* Success */
    /* Continue with cleanup code */

 error:
    /* Cleanup code, shared by success and failure path */

    /* Use Py_XDECREF() to ignore NULL references */
    Py_XDECREF(item);
    Py_XDECREF(const_one);
    Py_XDECREF(incremented_item);

    return rv; /* -1 for error, 0 for success */
@}
@end example

@geindex incr_item()

@geindex PyErr_ExceptionMatches (C function)
@geindex PyErr_Clear (C function)
@geindex Py_XDECREF (C function)

なんとこの例は C で @code{goto} 文を使うお勧めの方法まで示していますね! この例では、特定の例外を処理するために @ref{4f4e,,PyErr_ExceptionMatches()}  および @ref{1232,,PyErr_Clear()} をどう使うかを示しています。また、所有権を持っている参照で、値が @code{NULL} になるかもしれないものを捨てるために  @ref{992,,Py_XDECREF()} をどう使うかも示しています (関数名に @code{'X'} が付いていることに注意してください; @ref{790,,Py_DECREF()} は @code{NULL} 参照に出くわすとクラッシュします)。正しく動作させるためには、所有権を持つ参照を保持するための変数を @code{NULL} で初期化することが重要です; 同様に、あらかじめ戻り値を定義する際には値を @code{-1} (失敗) で初期化しておいて、最後の関数呼び出しまでうまくいった場合にのみ @code{0} (成功) に設定します。

@node Python の埋め込み<2>,デバッグ版ビルド Debugging Builds,例外<24>,はじめに<14>
@anchor{c-api/intro api-embedding}@anchor{4f4f}@anchor{c-api/intro embedding-python}@anchor{4f50}
@subsection Python の埋め込み


Python インタプリタの埋め込みを行う人 (いわば拡張モジュールの書き手の対極) が気にかけなければならない重要なタスクは、Python インタプリタの初期化処理 (initialization)、そしておそらくは終了処理 (finalization) です。インタプリタのほとんどの機能は、インタプリタの起動後しか使えません。

@geindex Py_Initialize (C function)
@geindex module;builtins
@geindex module;__main__
@geindex module;sys
@geindex module;検索;パス
@geindex path (sys モジュール)

基本的な初期化処理を行う関数は @ref{460,,Py_Initialize()} です。この関数はロード済みのモジュールからなるテーブルを作成し、土台となるモジュール @ref{13,,builtins}, @ref{1,,__main__}, および @ref{df,,sys} を作成します。また、モジュール検索パス (@code{sys.path})    の初期化も行います。

@ref{460,,Py_Initialize()} does not set the "script argument list"  (@code{sys.argv}).
If this variable is needed by Python code that will be executed later, setting
@ref{3f1,,PyConfig.argv} and @ref{1cf1,,PyConfig.parse_argv} must be set: see
@ref{646,,Python Initialization Configuration}.

ほとんどのシステムでは (特に Unix と Windows は、詳細がわずかに異なりはしますが)、 @ref{460,,Py_Initialize()} は標準の Python インタプリタ実行形式の場所に対する推定結果に基づいて、 Python のライブラリが Python インタプリタ実行形式からの相対パスで見つかるという仮定の下にモジュール検索パスを計算します。とりわけこの検索では、シェルコマンド検索パス (環境変数 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH}) 上に見つかった @code{python} という名前の実行ファイルの置かれているディレクトリの親ディレクトリからの相対で、 @code{lib/python`X.Y'} という名前のディレクトリを探します。

例えば、 Python 実行形式が @code{/usr/local/bin/python} で見つかったとすると、ライブラリが @code{/usr/local/lib/python`X.Y'} にあるものと仮定します。 (実際には、このパスは "フォールバック (fallback)" のライブラリ位置でもあり、 @code{python} が 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} 上に無い場合に使われます。) ユーザは 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} を設定することでこの動作をオーバーライドしたり、 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} を設定して追加のディレクトリを標準モジュール検索パスの前に挿入したりできます。

@geindex Py_GetPath (C function)
@geindex Py_GetPrefix (C function)
@geindex Py_GetExecPrefix (C function)
@geindex Py_GetProgramFullPath (C function)

The embedding application can steer the search by setting
@ref{3f2,,PyConfig.program_name} `before' calling
@ref{3f6,,Py_InitializeFromConfig()}. Note that
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} still overrides this and 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} is still
inserted in front of the standard path.  An application that requires total
control has to provide its own implementation of @ref{3e3,,Py_GetPath()},
@ref{3e5,,Py_GetPrefix()}, @ref{3e9,,Py_GetExecPrefix()}, and
@ref{3ec,,Py_GetProgramFullPath()} (all defined in @code{Modules/getpath.c}).

@geindex Py_IsInitialized (C function)

たまに、 Python を初期化前の状態にもどしたいことがあります。例えば、あるアプリケーションでは実行を最初からやりなおし (start over) させる (@ref{460,,Py_Initialize()} をもう一度呼び出させる) ようにしたいかもしれません。あるいは、アプリケーションが Python を一旦使い終えて、Python が確保したメモリを解放させたいかもしれません。 @ref{f11,,Py_FinalizeEx()} を使うとこうした処理を実現できます。また、関数 @ref{4f51,,Py_IsInitialized()}  は、Python が現在初期化済みの状態にある場合に真を返します。これらの関数についてのさらなる情報は、後の章で説明します。 @ref{f11,,Py_FinalizeEx()} がPythonインタプリタに確保された全てのメモリを `解放するわけではない' ことに注意してください。例えば、拡張モジュールによって確保されたメモリは、現在のところ解放する事ができません。

@node デバッグ版ビルド Debugging Builds,おすすめのサードパーティツール<2>,Python の埋め込み<2>,はじめに<14>
@anchor{c-api/intro api-debugging}@anchor{4f52}@anchor{c-api/intro debugging-builds}@anchor{4f53}
@subsection デバッグ版ビルド (Debugging Builds)


インタプリタと拡張モジュールに対しての追加チェックをするためのいくつかのマクロを有効にしてPythonをビルドすることができます。これらのチェックは、実行時に大きなオーバーヘッドを生じる傾向があります。なので、デフォルトでは有効にされていません。

Pythonデバッグ版ビルドの全ての種類のリストが、Pythonソース配布(source distribution)の中の @code{Misc/SpecialBuilds.txt} にあります。参照カウントのトレース、メモリアロケータのデバッグ、インタプリタのメインループの低レベルプロファイリングが利用可能です。よく使われるビルドについてのみ、この節の残りの部分で説明します。

@geindex Py_DEBUG (C macro)
@anchor{c-api/intro c Py_DEBUG}@anchor{1834}
@deffn {C のマクロ} Py_DEBUG
@end deffn

Compiling the interpreter with the @code{Py_DEBUG} macro defined produces
what is generally meant by @ref{509,,a debug build of Python}.
@code{Py_DEBUG} is enabled in the Unix build by adding
@ref{666,,--with-pydebug} to the @code{./configure} command.
It is also implied by the presence of the
not-Python-specific @code{_DEBUG} macro.  When @code{Py_DEBUG} is enabled
in the Unix build, compiler optimization is disabled.

In addition to the reference count debugging described below, extra checks are
performed, see @ref{509,,Python Debug Build}.

@code{Py_TRACE_REFS} を宣言すると、参照トレースが有効になります (@ref{636,,configure --with-trace-refs オプション} を参照してください)。全ての @ref{5df,,PyObject} に二つのフィールドを追加することで、使用中のオブジェクトの循環二重連結リストが管理されます。全ての割り当て(allocation)がトレースされます。終了時に、全ての残っているオブジェクトが表示されます。 (インタラクティブモードでは、インタプリタによる文の実行のたびに表示されます。)

より詳しい情報については、Pythonのソース配布(source distribution)の中の @code{Misc/SpecialBuilds.txt} を参照してください。

@node おすすめのサードパーティツール<2>,,デバッグ版ビルド Debugging Builds,はじめに<14>
@anchor{c-api/intro c-api-tools}@anchor{4e8e}@anchor{c-api/intro recommended-third-party-tools}@anchor{4f54}
@subsection おすすめのサードパーティツール


The following third party tools offer both simpler and more sophisticated
approaches to creating C, C++ and Rust extensions for Python:


@itemize *

@item 
Cython@footnote{https://cython.org/}

@item 
cffi@footnote{https://cffi.readthedocs.io}

@item 
HPy@footnote{https://hpyproject.org/}

@item 
nanobind@footnote{https://github.com/wjakob/nanobind} (C++)

@item 
Numba@footnote{https://numba.pydata.org/}

@item 
pybind11@footnote{https://pybind11.readthedocs.io/} (C++)

@item 
PyO3@footnote{https://pyo3.rs/} (Rust)

@item 
SWIG@footnote{https://www.swig.org}
@end itemize

Using tools such as these can help avoid writing code that is tightly bound to
a particular version of CPython, avoid reference counting errors, and focus
more on your own code than on using the CPython API. In general, new versions
of Python can be supported by updating the tool, and your code will often use
newer and more efficient APIs automatically. Some tools also support compiling
for other implementations of Python from a single set of sources.

These projects are not supported by the same people who maintain Python, and
issues need to be raised with the projects directly. Remember to check that the
project is still maintained and supported, as the list above may become
outdated.


@subsubheading 参考



@table @asis

@item Python Packaging User Guide: Binary Extensions@footnote{https://packaging.python.org/guides/packaging-binary-extensions/}

Python Packaging User Guideはバイナリ拡張の作成が簡単になる便利なツールをカバーしているだけではなく、まず始めになぜ拡張モジュールを作ることが望ましいかの様々な理由について議論しています。
@end table


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node C API の安定性,超高水準レイヤ,はじめに<14>,Python/C API リファレンスマニュアル
@anchor{c-api/stable doc}@anchor{4f55}@anchor{c-api/stable c-api-stability}@anchor{4f56}@anchor{c-api/stable stable}@anchor{775}@anchor{c-api/stable translation-repo}@anchor{4f57}
@section C API の安定性


Unless documented otherwise, Python's C API is covered by the Backwards
Compatibility Policy, 
@geindex Python Enhancement Proposals; PEP 387
PEP 387@footnote{https://peps.python.org/pep-0387/}.
Most changes to it are source-compatible (typically by only adding new API).
Changing existing API or removing API is only done after a deprecation period
or to fix serious issues.

CPython's Application Binary Interface (ABI) is forward- and
backwards-compatible across a minor release (if these are compiled the same
way; see @ref{4f58,,プラットフォームで考慮すべき点} below).
So, code compiled for Python 3.10.0 will work on 3.10.8 and vice versa,
but will need to be compiled separately for 3.9.x and 3.11.x.

There are two tiers of C API with different stability expectations:


@itemize -

@item 
@ref{769,,Unstable API}, may change in minor versions without
a deprecation period. It is marked by the @code{PyUnstable} prefix in names.

@item 
@ref{637,,Limited API}, is compatible across several minor releases.
When @ref{660,,Py_LIMITED_API} is defined, only this subset is exposed
from @code{Python.h}.
@end itemize

These are discussed in more detail below.

Names prefixed by an underscore, such as @code{_Py_InternalState},
are private API that can change without notice even in patch releases.
If you need to use this API, consider reaching out to
CPython developers@footnote{https://discuss.python.org/c/core-dev/c-api/30}
to discuss adding public API for your use case.

@menu
* Unstable C API:: 
* 安定 ABI (Stable Appliction Binary Interface): 安定 ABI Stable Appliction Binary Interface. 
* プラットフォームで考慮すべき点:: 
* 限定版APIの内容:: 

@end menu

@node Unstable C API,安定 ABI Stable Appliction Binary Interface,,C API の安定性
@anchor{c-api/stable id1}@anchor{4f59}@anchor{c-api/stable unstable-c-api}@anchor{769}
@subsection Unstable C API


@geindex PyUnstable

Any API named with the @code{PyUnstable} prefix exposes CPython implementation
details, and may change in every minor release (e.g. from 3.9 to 3.10) without
any deprecation warnings.
However, it will not change in a bugfix release (e.g. from 3.10.0 to 3.10.1).

It is generally intended for specialized, low-level tools like debuggers.

Projects that use this API are expected to follow
CPython development and spend extra effort adjusting to changes.

@node 安定 ABI Stable Appliction Binary Interface,プラットフォームで考慮すべき点,Unstable C API,C API の安定性
@anchor{c-api/stable id2}@anchor{4f5a}@anchor{c-api/stable stable-application-binary-interface}@anchor{4f07}
@subsection 安定 ABI (Stable Appliction Binary Interface)


For simplicity, this document talks about `extensions', but the Limited API
and Stable ABI work the same way for all uses of the API – for example,
embedding Python.

@menu
* Limited C API:: 
* Stable ABI:: 
* APIスコープとパフォーマンスの制限:: 
* 制限付きAPIの注意点:: 

@end menu

@node Limited C API,Stable ABI,,安定 ABI Stable Appliction Binary Interface
@anchor{c-api/stable id3}@anchor{4f5b}@anchor{c-api/stable limited-c-api}@anchor{637}
@subsubsection Limited C API


Python 3.2 introduced the `Limited API', a subset of Python's C API.
Extensions that only use the Limited API can be
compiled once and be loaded on multiple versions of Python.
Contents of the Limited API are @ref{99d,,listed below}.

@geindex Py_LIMITED_API (C macro)
@anchor{c-api/stable c Py_LIMITED_API}@anchor{660}
@deffn {C のマクロ} Py_LIMITED_API

このマクロを @code{Python.h} をインクルードする前に定義することで、 Limited API のみを使用することを選択し、 Limited API バージョンを選択することができます。

Define @code{Py_LIMITED_API} to the value of @ref{382,,PY_VERSION_HEX}
corresponding to the lowest Python version your extension supports.
The extension will be ABI-compatible with all Python 3 releases
from the specified one onward, and can use Limited API introduced up to that
version.

@code{PY_VERSION_HEX} マクロを直接使うのではなく、将来の Python のバージョンでコンパイルするときの安定性のために、最小のマイナーバージョン(例えば、 Python 3.10なら @code{0x030A0000} )をハードコードします。

また、 @code{Py_LIMITED_API} を @code{3} に定義することができます。これは @code{0x03020000} (Python 3.2, Limited API が導入されたバージョン)と同じように動作します。
@end deffn

@node Stable ABI,APIスコープとパフォーマンスの制限,Limited C API,安定 ABI Stable Appliction Binary Interface
@anchor{c-api/stable id4}@anchor{4f5c}@anchor{c-api/stable stable-abi}@anchor{4f5d}
@subsubsection Stable ABI


To enable this, Python provides a `Stable ABI': a set of symbols that will
remain ABI-compatible across Python 3.x versions.

@cartouche
@quotation 注釈 
The Stable ABI prevents ABI issues, like linker errors due to missing
symbols or data corruption due to changes in structure layouts or function
signatures.
However, other changes in Python can change the `behavior' of extensions.
See Python's Backwards Compatibility Policy (
@geindex Python Enhancement Proposals; PEP 387
PEP 387@footnote{https://peps.python.org/pep-0387/}) for details.
@end quotation
@end cartouche

The Stable ABI contains symbols exposed in the @ref{637,,Limited API}, but also other ones – for example, functions necessary to
support older versions of the Limited API.

Windows では、 Stable ABI を使用する拡張機能は、 @code{python39.dll} のようなバージョン固有のライブラリではなく、 @code{python3.dll} に対してリンクする必要があります。

いくつかのプラットフォームでは、 Python は @code{abi3} タグで名付けられた共有ライブラリファイルを探して読み込みます(例: @code{mymodule.abi3.so})。このような拡張モジュールが Stable ABI に適合しているかどうかはチェックされません。ユーザー(またはそのパッケージングツール)は、たとえば 3.10+ Limited API でビルドされた拡張モジュールが、それ以下のバージョンの Python にインストールされないことを確認する必要があります。

Stable ABI に含まれるすべての関数は、マクロとしてだけでなく、 Python の共有ライブラリの関数として存在します。そのため、Cプリプロセッサを使用しない言語から使用することができます。

@node APIスコープとパフォーマンスの制限,制限付きAPIの注意点,Stable ABI,安定 ABI Stable Appliction Binary Interface
@anchor{c-api/stable limited-api-scope-and-performance}@anchor{4f5e}
@subsubsection APIスコープとパフォーマンスの制限


Limited API の目標は、フル C API で可能なすべてのことを実現することですが、おそらく性能上の制約があります。

例えば、 @ref{5ff,,PyList_GetItem()} は利用可能ですが、その “unsafe” マクロの変種 @ref{4f5f,,PyList_GET_ITEM()} は利用できません。このマクロは、リストオブジェクトのバージョン固有の実装の詳細に依存することができるため、より高速に処理することができます。

@code{Py_LIMITED_API} を定義しないと、いくつかの C API 関数がインライン化されたり、マクロに置き換わったりします。@code{Py_LIMITED_API} を定義すると、このインライン化が無効になり、 Python のデータ構造が改善されても安定した動作が可能になりますが、性能が低下する可能性があります。

@code{Py_LIMITED_API} の定義を省くことで、 Limited API 拡張をバージョン固有の ABI でコンパイルすることが可能です。これにより、その Python のバージョンでパフォーマンスを向上させることができますが、互換性は制限されます。@code{Py_LIMITED_API} でコンパイルすると、バージョンに依存しない拡張機能が利用できない場合、例えば、次期 Python バージョンのプレリリースに対応した拡張モジュールを配布することができるようになります。

@node 制限付きAPIの注意点,,APIスコープとパフォーマンスの制限,安定 ABI Stable Appliction Binary Interface
@anchor{c-api/stable limited-api-caveats}@anchor{4f60}
@subsubsection 制限付きAPIの注意点


Note that compiling with @code{Py_LIMITED_API} is `not' a complete guarantee that
code conforms to the @ref{637,,Limited API} or the @ref{4f5d,,Stable ABI}. @code{Py_LIMITED_API} only covers definitions, but an API also
includes other issues, such as expected semantics.

@code{Py_LIMITED_API} が防げない問題の1つは、 Python の下位バージョンでは無効な引数を持つ関数を呼び出すことです。例えば、引数に @code{NULL} を受け取る関数を考えてみましょう。Python 3.9 では @code{NULL} はデフォルトの挙動を選択しますが、Python 3.8 ではこの引数は直接使用され、 @code{NULL} の参照外れを起こしクラッシュします。同様の引数は、構造体のフィールドに対しても機能します。

もう一つの問題は、一部の構造体フィールドがLimited APIの一部であるにもかかわらず、 @code{Py_LIMITED_API} が定義されたときに現在非表示になっていないことです。

これらの理由から、私たちは拡張モジュールがサポートする `すべての' マイナーな Python バージョンでテストすること、そしてできれば `最も低い' バージョンでビルドすることを推奨します。

また、使用するすべての API のドキュメントを確認し、それが明示的に Limited API の一部であるかどうかをチェックすることをお勧めします。@code{Py_LIMITED_API} が定義されていても、技術的な理由で(あるいはバグとして意図せず)いくつかのプライベート宣言が公開されることがあります。

Python 3.8 で @code{Py_LIMITED_API} をコンパイルすると、その拡張モジュールは Python 3.12 で動作しますが、必ずしも Python 3.12 で `コンパイル' できるとは限らないことに注意してください。特に、Limited API の一部は、 Stable ABI が安定している限り、非推奨で削除されるかもしれません。

@node プラットフォームで考慮すべき点,限定版APIの内容,安定 ABI Stable Appliction Binary Interface,C API の安定性
@anchor{c-api/stable platform-considerations}@anchor{4f61}@anchor{c-api/stable stable-abi-platform}@anchor{4f58}
@subsection プラットフォームで考慮すべき点


ABI stability depends not only on Python, but also on the compiler used,
lower-level libraries and compiler options. For the purposes of
the @ref{4f5d,,Stable ABI}, these details define a “platform”. They
usually depend on the OS type and processor architecture

特定のプラットフォーム上のすべての Python バージョンが安定版 ABI を破壊しない方法でビルドされていることを保証するのは、 Python の各特定配布者の責任です。これは @code{python.org} や多くのサードパーティーの配布元からの Windows と macOS のリリースの場合です。

@node 限定版APIの内容,,プラットフォームで考慮すべき点,C API の安定性
@anchor{c-api/stable contents-of-limited-api}@anchor{4f62}@anchor{c-api/stable limited-api-list}@anchor{99d}
@subsection 限定版APIの内容


Currently, the @ref{637,,Limited API} includes the following items:



@itemize *

@item 
@ref{16ee,,METH_CLASS}

@item 
@ref{1690,,METH_COEXIST}

@item 
@ref{199e,,METH_FASTCALL}

@item 
@ref{b68,,METH_METHOD}

@item 
@ref{16ed,,METH_NOARGS}

@item 
@ref{1720,,METH_O}

@item 
@ref{16ef,,METH_STATIC}

@item 
@ref{1721,,METH_VARARGS}

@item 
@ref{780,,PY_VECTORCALL_ARGUMENTS_OFFSET}

@item 
@ref{4f63,,PyAIter_Check()}

@item 
@ref{180e,,PyArg_Parse()}

@item 
@ref{3c1,,PyArg_ParseTuple()}

@item 
@ref{624,,PyArg_ParseTupleAndKeywords()}

@item 
@ref{171f,,PyArg_UnpackTuple()}

@item 
@ref{4f64,,PyArg_VaParse()}

@item 
@ref{625,,PyArg_VaParseTupleAndKeywords()}

@item 
@ref{4f65,,PyArg_ValidateKeywordArguments()}

@item 
@ref{4f66,,PyBUF_ANY_CONTIGUOUS}

@item 
@ref{4f67,,PyBUF_CONTIG}

@item 
@ref{4f68,,PyBUF_CONTIG_RO}

@item 
@ref{15d0,,PyBUF_C_CONTIGUOUS}

@item 
@ref{4f69,,PyBUF_FORMAT}

@item 
@ref{4f6a,,PyBUF_FULL}

@item 
@ref{4f6b,,PyBUF_FULL_RO}

@item 
@ref{15d1,,PyBUF_F_CONTIGUOUS}

@item 
@ref{4f6c,,PyBUF_INDIRECT}

@item 
@ref{4f6d,,PyBUF_MAX_NDIM}

@item 
@ref{4f6e,,PyBUF_ND}

@item 
@ref{1a0b,,PyBUF_READ}

@item 
@ref{4f6f,,PyBUF_RECORDS}

@item 
@ref{4f70,,PyBUF_RECORDS_RO}

@item 
@ref{4f71,,PyBUF_SIMPLE}

@item 
@ref{4f72,,PyBUF_STRIDED}

@item 
@ref{4f73,,PyBUF_STRIDED_RO}

@item 
@ref{4f74,,PyBUF_STRIDES}

@item 
@ref{15cf,,PyBUF_WRITABLE}

@item 
@ref{1a0c,,PyBUF_WRITE}

@item 
@ref{4f75,,PyBaseObject_Type}

@item 
@ref{4f76,,PyBool_FromLong()}

@item 
@ref{4f77,,PyBool_Type}

@item 
@ref{963,,PyBuffer_FillContiguousStrides()}

@item 
@ref{964,,PyBuffer_FillInfo()}

@item 
@ref{960,,PyBuffer_FromContiguous()}

@item 
@ref{95d,,PyBuffer_GetPointer()}

@item 
@ref{962,,PyBuffer_IsContiguous()}

@item 
@ref{63b,,PyBuffer_Release()}

@item 
@ref{95e,,PyBuffer_SizeFromFormat()}

@item 
@ref{95f,,PyBuffer_ToContiguous()}

@item 
@ref{4f78,,PyByteArrayIter_Type}

@item 
@ref{4f79,,PyByteArray_AsString()}

@item 
@ref{4f7a,,PyByteArray_Concat()}

@item 
@ref{15c2,,PyByteArray_FromObject()}

@item 
@ref{15c3,,PyByteArray_FromStringAndSize()}

@item 
@ref{4f7b,,PyByteArray_Resize()}

@item 
@ref{4f7c,,PyByteArray_Size()}

@item 
@ref{4f7d,,PyByteArray_Type}

@item 
@ref{4f7e,,PyBytesIter_Type}

@item 
@ref{a87,,PyBytes_AsString()}

@item 
@ref{4f7f,,PyBytes_AsStringAndSize()}

@item 
@ref{4f80,,PyBytes_Concat()}

@item 
@ref{4f81,,PyBytes_ConcatAndDel()}

@item 
@ref{4f82,,PyBytes_DecodeEscape()}

@item 
@ref{1e0b,,PyBytes_FromFormat()}

@item 
@ref{4f83,,PyBytes_FromFormatV()}

@item 
@ref{4f84,,PyBytes_FromObject()}

@item 
@ref{4f85,,PyBytes_FromString()}

@item 
@ref{15b8,,PyBytes_FromStringAndSize()}

@item 
@ref{4f86,,PyBytes_Repr()}

@item 
@ref{4f87,,PyBytes_Size()}

@item 
@ref{4f88,,PyBytes_Type}

@item 
@ref{1691,,PyCFunction}

@item 
@ref{4f89,,PyCFunctionFast}

@item 
@ref{4f8a,,PyCFunctionFastWithKeywords}

@item 
@ref{4f8b,,PyCFunctionWithKeywords}

@item 
@ref{4f8c,,PyCFunction_GetFlags()}

@item 
@ref{4f8d,,PyCFunction_GetFunction()}

@item 
@ref{4f8e,,PyCFunction_GetSelf()}

@item 
@ref{1cb1,,PyCFunction_New()}

@item 
@ref{1d76,,PyCFunction_NewEx()}

@item 
@ref{4f8f,,PyCFunction_Type}

@item 
@ref{1cab,,PyCMethod_New()}

@item 
@ref{4f90,,PyCallIter_New()}

@item 
@ref{4f91,,PyCallIter_Type}

@item 
@ref{4f92,,PyCallable_Check()}

@item 
@ref{4f93,,PyCapsule_Destructor}

@item 
@ref{4f94,,PyCapsule_GetContext()}

@item 
@ref{4f95,,PyCapsule_GetDestructor()}

@item 
@ref{4f96,,PyCapsule_GetName()}

@item 
@ref{4f97,,PyCapsule_GetPointer()}

@item 
@ref{1c10,,PyCapsule_Import()}

@item 
@ref{1574,,PyCapsule_IsValid()}

@item 
@ref{4ec3,,PyCapsule_New()}

@item 
@ref{4f98,,PyCapsule_SetContext()}

@item 
@ref{4f99,,PyCapsule_SetDestructor()}

@item 
@ref{4f9a,,PyCapsule_SetName()}

@item 
@ref{4f9b,,PyCapsule_SetPointer()}

@item 
@ref{4f9c,,PyCapsule_Type}

@item 
@ref{4f9d,,PyClassMethodDescr_Type}

@item 
@ref{4f9e,,PyCodec_BackslashReplaceErrors()}

@item 
@ref{3e1,,PyCodec_Decode()}

@item 
@ref{4f9f,,PyCodec_Decoder()}

@item 
@ref{3e2,,PyCodec_Encode()}

@item 
@ref{4fa0,,PyCodec_Encoder()}

@item 
@ref{4fa1,,PyCodec_IgnoreErrors()}

@item 
@ref{4fa2,,PyCodec_IncrementalDecoder()}

@item 
@ref{4fa3,,PyCodec_IncrementalEncoder()}

@item 
@ref{4fa4,,PyCodec_KnownEncoding()}

@item 
@ref{4fa5,,PyCodec_LookupError()}

@item 
@ref{10af,,PyCodec_NameReplaceErrors()}

@item 
@ref{4fa6,,PyCodec_Register()}

@item 
@ref{4fa7,,PyCodec_RegisterError()}

@item 
@ref{4fa8,,PyCodec_ReplaceErrors()}

@item 
@ref{4fa9,,PyCodec_StreamReader()}

@item 
@ref{4faa,,PyCodec_StreamWriter()}

@item 
@ref{4fab,,PyCodec_StrictErrors()}

@item 
@ref{a97,,PyCodec_Unregister()}

@item 
@ref{4fac,,PyCodec_XMLCharRefReplaceErrors()}

@item 
@ref{4fad,,PyComplex_FromDoubles()}

@item 
@ref{1a13,,PyComplex_ImagAsDouble()}

@item 
@ref{1a12,,PyComplex_RealAsDouble()}

@item 
@ref{4fae,,PyComplex_Type}

@item 
@ref{4faf,,PyDescr_NewClassMethod()}

@item 
@ref{4fb0,,PyDescr_NewGetSet()}

@item 
@ref{4fb1,,PyDescr_NewMember()}

@item 
@ref{1d75,,PyDescr_NewMethod()}

@item 
@ref{4fb2,,PyDictItems_Type}

@item 
@ref{4fb3,,PyDictIterItem_Type}

@item 
@ref{4fb4,,PyDictIterKey_Type}

@item 
@ref{4fb5,,PyDictIterValue_Type}

@item 
@ref{4fb6,,PyDictKeys_Type}

@item 
@ref{4fb7,,PyDictProxy_New()}

@item 
@ref{4fb8,,PyDictProxy_Type}

@item 
@ref{4fb9,,PyDictRevIterItem_Type}

@item 
@ref{4fba,,PyDictRevIterKey_Type}

@item 
@ref{4fbb,,PyDictRevIterValue_Type}

@item 
@ref{4fbc,,PyDictValues_Type}

@item 
@ref{4fbd,,PyDict_Clear()}

@item 
@ref{5de,,PyDict_Contains()}

@item 
@ref{662,,PyDict_Copy()}

@item 
@ref{4fbe,,PyDict_DelItem()}

@item 
@ref{4fbf,,PyDict_DelItemString()}

@item 
@ref{628,,PyDict_GetItem()}

@item 
@ref{5e0,,PyDict_GetItemRef()}

@item 
@ref{629,,PyDict_GetItemString()}

@item 
@ref{421,,PyDict_GetItemStringRef()}

@item 
@ref{5e1,,PyDict_GetItemWithError()}

@item 
@ref{4fc0,,PyDict_Items()}

@item 
@ref{4fc1,,PyDict_Keys()}

@item 
@ref{4fc2,,PyDict_Merge()}

@item 
@ref{4fc3,,PyDict_MergeFromSeq2()}

@item 
@ref{4fc4,,PyDict_New()}

@item 
@ref{198f,,PyDict_Next()}

@item 
@ref{4eb9,,PyDict_SetItem()}

@item 
@ref{198d,,PyDict_SetItemString()}

@item 
@ref{4fc5,,PyDict_Size()}

@item 
@ref{4fc6,,PyDict_Type}

@item 
@ref{4fc7,,PyDict_Update()}

@item 
@ref{4fc8,,PyDict_Values()}

@item 
@ref{4fc9,,PyEllipsis_Type}

@item 
@ref{4fca,,PyEnum_Type}

@item 
@ref{4fcb,,PyErr_BadArgument()}

@item 
@ref{4fcc,,PyErr_BadInternalCall()}

@item 
@ref{693,,PyErr_CheckSignals()}

@item 
@ref{1232,,PyErr_Clear()}

@item 
@code{PyErr_Display()}

@item 
@ref{435,,PyErr_DisplayException()}

@item 
@ref{4f4e,,PyErr_ExceptionMatches()}

@item 
@ref{428,,PyErr_Fetch()}

@item 
@ref{10b1,,PyErr_Format()}

@item 
@ref{10b0,,PyErr_FormatV()}

@item 
@ref{976,,PyErr_GetExcInfo()}

@item 
@ref{973,,PyErr_GetHandledException()}

@item 
@ref{429,,PyErr_GetRaisedException()}

@item 
@ref{4fcd,,PyErr_GivenExceptionMatches()}

@item 
@ref{1481,,PyErr_NewException()}

@item 
@ref{1480,,PyErr_NewExceptionWithDoc()}

@item 
@ref{4e99,,PyErr_NoMemory()}

@item 
@ref{42a,,PyErr_NormalizeException()}

@item 
@ref{1caf,,PyErr_Occurred()}

@item 
@ref{1d2c,,PyErr_Print()}

@item 
@ref{4fce,,PyErr_PrintEx()}

@item 
@ref{4fcf,,PyErr_ProgramText()}

@item 
@ref{f13,,PyErr_ResourceWarning()}

@item 
@ref{42b,,PyErr_Restore()}

@item 
@ref{4fd0,,PyErr_SetExcFromWindowsErr()}

@item 
@ref{1a86,,PyErr_SetExcFromWindowsErrWithFilename()}

@item 
@ref{4fd1,,PyErr_SetExcFromWindowsErrWithFilenameObject()}

@item 
@ref{4fd2,,PyErr_SetExcFromWindowsErrWithFilenameObjects()}

@item 
@ref{975,,PyErr_SetExcInfo()}

@item 
@ref{4e98,,PyErr_SetFromErrno()}

@item 
@ref{1a85,,PyErr_SetFromErrnoWithFilename()}

@item 
@ref{4fd3,,PyErr_SetFromErrnoWithFilenameObject()}

@item 
@ref{4fd4,,PyErr_SetFromErrnoWithFilenameObjects()}

@item 
@ref{4fd5,,PyErr_SetFromWindowsErr()}

@item 
@ref{1a87,,PyErr_SetFromWindowsErrWithFilename()}

@item 
@ref{974,,PyErr_SetHandledException()}

@item 
@ref{f39,,PyErr_SetImportError()}

@item 
@ref{f12,,PyErr_SetImportErrorSubclass()}

@item 
@ref{4fd6,,PyErr_SetInterrupt()}

@item 
@ref{a9e,,PyErr_SetInterruptEx()}

@item 
@ref{4fd7,,PyErr_SetNone()}

@item 
@ref{79b,,PyErr_SetObject()}

@item 
@ref{42c,,PyErr_SetRaisedException()}

@item 
@ref{79c,,PyErr_SetString()}

@item 
@ref{4fd8,,PyErr_SyntaxLocation()}

@item 
@ref{4fd9,,PyErr_SyntaxLocationEx()}

@item 
@ref{1665,,PyErr_WarnEx()}

@item 
@ref{1a8d,,PyErr_WarnExplicit()}

@item 
@ref{4fda,,PyErr_WarnFormat()}

@item 
@ref{5f2,,PyErr_WriteUnraisable()}

@item 
@ref{649,,PyEval_AcquireThread()}

@item 
@ref{a86,,PyEval_EvalCode()}

@item 
@ref{1ada,,PyEval_EvalCodeEx()}

@item 
@ref{4fdb,,PyEval_EvalFrame()}

@item 
@ref{122f,,PyEval_EvalFrameEx()}

@item 
@ref{5f4,,PyEval_GetBuiltins()}

@item 
@ref{1b39,,PyEval_GetFrame()}

@item 
@ref{5f3,,PyEval_GetFrameBuiltins()}

@item 
@ref{5f5,,PyEval_GetFrameGlobals()}

@item 
@ref{5f7,,PyEval_GetFrameLocals()}

@item 
@ref{4fdc,,PyEval_GetFuncDesc()}

@item 
@ref{4fdd,,PyEval_GetFuncName()}

@item 
@ref{5f6,,PyEval_GetGlobals()}

@item 
@ref{5f8,,PyEval_GetLocals()}

@item 
@ref{19b9,,PyEval_InitThreads()}

@item 
@ref{4fde,,PyEval_ReleaseThread()}

@item 
@ref{648,,PyEval_RestoreThread()}

@item 
@ref{647,,PyEval_SaveThread()}

@item 
@ref{4fdf,,PyExc_ArithmeticError}

@item 
@ref{4fe0,,PyExc_AssertionError}

@item 
@ref{4fe1,,PyExc_AttributeError}

@item 
@ref{4fe2,,PyExc_BaseException}

@item 
@ref{4fe3,,PyExc_BaseExceptionGroup}

@item 
@ref{4fe4,,PyExc_BlockingIOError}

@item 
@ref{4fe5,,PyExc_BrokenPipeError}

@item 
@ref{4fe6,,PyExc_BufferError}

@item 
@ref{4fe7,,PyExc_BytesWarning}

@item 
@ref{4fe8,,PyExc_ChildProcessError}

@item 
@ref{4fe9,,PyExc_ConnectionAbortedError}

@item 
@ref{4fea,,PyExc_ConnectionError}

@item 
@ref{4feb,,PyExc_ConnectionRefusedError}

@item 
@ref{4fec,,PyExc_ConnectionResetError}

@item 
@ref{4fed,,PyExc_DeprecationWarning}

@item 
@ref{4fee,,PyExc_EOFError}

@item 
@ref{4fef,,PyExc_EncodingWarning}

@item 
@ref{4ff0,,PyExc_EnvironmentError}

@item 
@ref{4ff1,,PyExc_Exception}

@item 
@ref{4ff2,,PyExc_FileExistsError}

@item 
@ref{4ff3,,PyExc_FileNotFoundError}

@item 
@ref{4ff4,,PyExc_FloatingPointError}

@item 
@ref{4ff5,,PyExc_FutureWarning}

@item 
@ref{4ff6,,PyExc_GeneratorExit}

@item 
@ref{4ff7,,PyExc_IOError}

@item 
@ref{4ff8,,PyExc_ImportError}

@item 
@ref{4ff9,,PyExc_ImportWarning}

@item 
@ref{4ffa,,PyExc_IndentationError}

@item 
@ref{4ffb,,PyExc_IndexError}

@item 
@ref{4ffc,,PyExc_InterruptedError}

@item 
@ref{4ffd,,PyExc_IsADirectoryError}

@item 
@ref{4ffe,,PyExc_KeyError}

@item 
@ref{4fff,,PyExc_KeyboardInterrupt}

@item 
@ref{5000,,PyExc_LookupError}

@item 
@ref{5001,,PyExc_MemoryError}

@item 
@ref{5002,,PyExc_ModuleNotFoundError}

@item 
@ref{5003,,PyExc_NameError}

@item 
@ref{5004,,PyExc_NotADirectoryError}

@item 
@ref{5005,,PyExc_NotImplementedError}

@item 
@ref{4e9b,,PyExc_OSError}

@item 
@ref{5006,,PyExc_OverflowError}

@item 
@ref{5007,,PyExc_PendingDeprecationWarning}

@item 
@ref{5008,,PyExc_PermissionError}

@item 
@ref{5009,,PyExc_ProcessLookupError}

@item 
@ref{10b2,,PyExc_RecursionError}

@item 
@ref{500a,,PyExc_ReferenceError}

@item 
@ref{500b,,PyExc_ResourceWarning}

@item 
@ref{500c,,PyExc_RuntimeError}

@item 
@ref{500d,,PyExc_RuntimeWarning}

@item 
@ref{500e,,PyExc_StopAsyncIteration}

@item 
@ref{500f,,PyExc_StopIteration}

@item 
@ref{5010,,PyExc_SyntaxError}

@item 
@ref{5011,,PyExc_SyntaxWarning}

@item 
@ref{5012,,PyExc_SystemError}

@item 
@ref{5013,,PyExc_SystemExit}

@item 
@ref{5014,,PyExc_TabError}

@item 
@ref{5015,,PyExc_TimeoutError}

@item 
@ref{4e9a,,PyExc_TypeError}

@item 
@ref{5016,,PyExc_UnboundLocalError}

@item 
@ref{5017,,PyExc_UnicodeDecodeError}

@item 
@ref{5018,,PyExc_UnicodeEncodeError}

@item 
@ref{5019,,PyExc_UnicodeError}

@item 
@ref{501a,,PyExc_UnicodeTranslateError}

@item 
@ref{501b,,PyExc_UnicodeWarning}

@item 
@ref{501c,,PyExc_UserWarning}

@item 
@ref{4e9c,,PyExc_ValueError}

@item 
@ref{501d,,PyExc_Warning}

@item 
@ref{501e,,PyExc_WindowsError}

@item 
@ref{4e97,,PyExc_ZeroDivisionError}

@item 
@ref{c5b,,PyExceptionClass_Name()}

@item 
@ref{78b,,PyException_GetArgs()}

@item 
@ref{501f,,PyException_GetCause()}

@item 
@ref{5020,,PyException_GetContext()}

@item 
@ref{5021,,PyException_GetTraceback()}

@item 
@ref{78c,,PyException_SetArgs()}

@item 
@ref{5022,,PyException_SetCause()}

@item 
@ref{5023,,PyException_SetContext()}

@item 
@ref{1dce,,PyException_SetTraceback()}

@item 
@ref{5024,,PyFile_FromFd()}

@item 
@ref{5025,,PyFile_GetLine()}

@item 
@ref{5026,,PyFile_WriteObject()}

@item 
@ref{5027,,PyFile_WriteString()}

@item 
@ref{5028,,PyFilter_Type}

@item 
@ref{c5f,,PyFloat_AsDouble()}

@item 
@ref{5029,,PyFloat_FromDouble()}

@item 
@ref{502a,,PyFloat_FromString()}

@item 
@ref{1609,,PyFloat_GetInfo()}

@item 
@ref{1607,,PyFloat_GetMax()}

@item 
@ref{1608,,PyFloat_GetMin()}

@item 
@ref{502b,,PyFloat_Type}

@item 
@ref{98c,,PyFrameObject}

@item 
@ref{98d,,PyFrame_GetCode()}

@item 
@ref{98e,,PyFrame_GetLineNumber()}

@item 
@ref{165e,,PyFrozenSet_New()}

@item 
@ref{502c,,PyFrozenSet_Type}

@item 
@ref{b85,,PyGC_Collect()}

@item 
@ref{aa5,,PyGC_Disable()}

@item 
@ref{aa4,,PyGC_Enable()}

@item 
@ref{aa6,,PyGC_IsEnabled()}

@item 
@ref{64a,,PyGILState_Ensure()}

@item 
@ref{502d,,PyGILState_GetThisThreadState()}

@item 
@ref{64b,,PyGILState_Release()}

@item 
@ref{502e,,PyGILState_STATE}

@item 
@ref{db2,,PyGetSetDef}

@item 
@ref{502f,,PyGetSetDescr_Type}

@item 
@ref{5fc,,PyImport_AddModule()}

@item 
@ref{5030,,PyImport_AddModuleObject()}

@item 
@ref{5fb,,PyImport_AddModuleRef()}

@item 
@ref{1b1c,,PyImport_AppendInittab()}

@item 
@ref{5031,,PyImport_ExecCodeModule()}

@item 
@ref{5032,,PyImport_ExecCodeModuleEx()}

@item 
@ref{5033,,PyImport_ExecCodeModuleObject()}

@item 
@ref{5034,,PyImport_ExecCodeModuleWithPathnames()}

@item 
@ref{1a84,,PyImport_GetImporter()}

@item 
@ref{13bb,,PyImport_GetMagicNumber()}

@item 
@ref{5035,,PyImport_GetMagicTag()}

@item 
@ref{dac,,PyImport_GetModule()}

@item 
@ref{5036,,PyImport_GetModuleDict()}

@item 
@ref{1615,,PyImport_Import()}

@item 
@ref{5037,,PyImport_ImportFrozenModule()}

@item 
@ref{5038,,PyImport_ImportFrozenModuleObject()}

@item 
@ref{3dc,,PyImport_ImportModule()}

@item 
@ref{13bc,,PyImport_ImportModuleLevel()}

@item 
@ref{5039,,PyImport_ImportModuleLevelObject()}

@item 
@ref{3db,,PyImport_ImportModuleNoBlock()}

@item 
@ref{503a,,PyImport_ReloadModule()}

@item 
@ref{b81,,PyIndex_Check()}

@item 
@ref{aba,,PyInterpreterState}

@item 
@ref{4753,,PyInterpreterState_Clear()}

@item 
@ref{503b,,PyInterpreterState_Delete()}

@item 
@ref{64c,,PyInterpreterState_Get()}

@item 
@ref{503c,,PyInterpreterState_GetDict()}

@item 
@ref{dbf,,PyInterpreterState_GetID()}

@item 
@ref{4754,,PyInterpreterState_New()}

@item 
@ref{1cb2,,PyIter_Check()}

@item 
@ref{399,,PyIter_Next()}

@item 
@ref{398,,PyIter_NextItem()}

@item 
@ref{a98,,PyIter_Send()}

@item 
@ref{503d,,PyListIter_Type}

@item 
@ref{503e,,PyListRevIter_Type}

@item 
@ref{503f,,PyList_Append()}

@item 
@ref{5040,,PyList_AsTuple()}

@item 
@ref{5ff,,PyList_GetItem()}

@item 
@ref{5fe,,PyList_GetItemRef()}

@item 
@ref{5041,,PyList_GetSlice()}

@item 
@ref{18b9,,PyList_Insert()}

@item 
@ref{4f49,,PyList_New()}

@item 
@ref{5042,,PyList_Reverse()}

@item 
@ref{18ba,,PyList_SetItem()}

@item 
@ref{5043,,PyList_SetSlice()}

@item 
@ref{1633,,PyList_Size()}

@item 
@ref{5044,,PyList_Sort()}

@item 
@ref{4edb,,PyList_Type}

@item 
@ref{39e,,PyLongObject}

@item 
@ref{5045,,PyLongRangeIter_Type}

@item 
@ref{1975,,PyLong_AsDouble()}

@item 
@ref{604,,PyLong_AsInt()}

@item 
@ref{39f,,PyLong_AsInt32()}

@item 
@ref{3a0,,PyLong_AsInt64()}

@item 
@ref{605,,PyLong_AsLong()}

@item 
@ref{147d,,PyLong_AsLongAndOverflow()}

@item 
@ref{5046,,PyLong_AsLongLong()}

@item 
@ref{147e,,PyLong_AsLongLongAndOverflow()}

@item 
@ref{606,,PyLong_AsNativeBytes()}

@item 
@ref{5047,,PyLong_AsSize_t()}

@item 
@ref{5048,,PyLong_AsSsize_t()}

@item 
@ref{3a1,,PyLong_AsUInt32()}

@item 
@ref{3a2,,PyLong_AsUInt64()}

@item 
@ref{5049,,PyLong_AsUnsignedLong()}

@item 
@ref{14ac,,PyLong_AsUnsignedLongLong()}

@item 
@ref{1dca,,PyLong_AsUnsignedLongLongMask()}

@item 
@ref{504a,,PyLong_AsUnsignedLongMask()}

@item 
@ref{504b,,PyLong_AsVoidPtr()}

@item 
@ref{b3c,,PyLong_FromDouble()}

@item 
@ref{3a3,,PyLong_FromInt32()}

@item 
@ref{3a4,,PyLong_FromInt64()}

@item 
@ref{1bd0,,PyLong_FromLong()}

@item 
@ref{1bd1,,PyLong_FromLongLong()}

@item 
@ref{607,,PyLong_FromNativeBytes()}

@item 
@ref{18bf,,PyLong_FromSize_t()}

@item 
@ref{189e,,PyLong_FromSsize_t()}

@item 
@ref{504c,,PyLong_FromString()}

@item 
@ref{3a5,,PyLong_FromUInt32()}

@item 
@ref{3a6,,PyLong_FromUInt64()}

@item 
@ref{18bd,,PyLong_FromUnsignedLong()}

@item 
@ref{18be,,PyLong_FromUnsignedLongLong()}

@item 
@ref{608,,PyLong_FromUnsignedNativeBytes()}

@item 
@ref{504d,,PyLong_FromVoidPtr()}

@item 
@ref{504e,,PyLong_GetInfo()}

@item 
@ref{504f,,PyLong_Type}

@item 
@ref{5050,,PyMap_Type}

@item 
@ref{5051,,PyMapping_Check()}

@item 
@ref{5eb,,PyMapping_GetItemString()}

@item 
@ref{5e8,,PyMapping_GetOptionalItem()}

@item 
@ref{5e9,,PyMapping_GetOptionalItemString()}

@item 
@ref{620,,PyMapping_HasKey()}

@item 
@ref{622,,PyMapping_HasKeyString()}

@item 
@ref{621,,PyMapping_HasKeyStringWithError()}

@item 
@ref{61f,,PyMapping_HasKeyWithError()}

@item 
@ref{db7,,PyMapping_Items()}

@item 
@ref{db5,,PyMapping_Keys()}

@item 
@ref{5052,,PyMapping_Length()}

@item 
@ref{5053,,PyMapping_SetItemString()}

@item 
@ref{1e37,,PyMapping_Size()}

@item 
@ref{db6,,PyMapping_Values()}

@item 
@ref{10ad,,PyMem_Calloc()}

@item 
@ref{165b,,PyMem_Free()}

@item 
@ref{e5f,,PyMem_Malloc()}

@item 
@ref{632,,PyMem_RawCalloc()}

@item 
@ref{634,,PyMem_RawFree()}

@item 
@ref{631,,PyMem_RawMalloc()}

@item 
@ref{633,,PyMem_RawRealloc()}

@item 
@ref{1233,,PyMem_Realloc()}

@item 
@ref{771,,PyMemberDef}

@item 
@ref{5054,,PyMemberDescr_Type}

@item 
@ref{7aa,,PyMember_GetOne()}

@item 
@ref{7ab,,PyMember_SetOne()}

@item 
@ref{965,,PyMemoryView_FromBuffer()}

@item 
@ref{1388,,PyMemoryView_FromMemory()}

@item 
@ref{5055,,PyMemoryView_FromObject()}

@item 
@ref{5056,,PyMemoryView_GetContiguous()}

@item 
@ref{5057,,PyMemoryView_Type}

@item 
@ref{16f0,,PyMethodDef}

@item 
@ref{5058,,PyMethodDescr_Type}

@item 
@ref{b74,,PyModuleDef}

@item 
@code{PyModuleDef_Base}

@item 
@ref{4ea3,,PyModuleDef_Init()}

@item 
@ref{5059,,PyModuleDef_Slot}

@item 
@code{PyModuleDef_Type}

@item 
@ref{609,,PyModule_Add()}

@item 
@ref{505a,,PyModule_AddFunctions()}

@item 
@ref{1755,,PyModule_AddIntConstant()}

@item 
@ref{60b,,PyModule_AddObject()}

@item 
@ref{60a,,PyModule_AddObjectRef()}

@item 
@ref{1756,,PyModule_AddStringConstant()}

@item 
@ref{b6c,,PyModule_AddType()}

@item 
@ref{505b,,PyModule_Create2()}

@item 
@ref{10b5,,PyModule_ExecDef()}

@item 
@ref{10b4,,PyModule_FromDefAndSpec2()}

@item 
@ref{505c,,PyModule_GetDef()}

@item 
@ref{505d,,PyModule_GetDict()}

@item 
@ref{42d,,PyModule_GetFilename()}

@item 
@ref{42e,,PyModule_GetFilenameObject()}

@item 
@ref{505e,,PyModule_GetName()}

@item 
@ref{505f,,PyModule_GetNameObject()}

@item 
@ref{b77,,PyModule_GetState()}

@item 
@ref{5060,,PyModule_New()}

@item 
@ref{5061,,PyModule_NewObject()}

@item 
@ref{5062,,PyModule_SetDocString()}

@item 
@ref{5063,,PyModule_Type}

@item 
@ref{5064,,PyNumber_Absolute()}

@item 
@ref{5065,,PyNumber_Add()}

@item 
@ref{5066,,PyNumber_And()}

@item 
@ref{5067,,PyNumber_AsSsize_t()}

@item 
@ref{c5c,,PyNumber_Check()}

@item 
@ref{5068,,PyNumber_Divmod()}

@item 
@ref{c5e,,PyNumber_Float()}

@item 
@ref{5069,,PyNumber_FloorDivide()}

@item 
@ref{506a,,PyNumber_InPlaceAdd()}

@item 
@ref{506b,,PyNumber_InPlaceAnd()}

@item 
@ref{506c,,PyNumber_InPlaceFloorDivide()}

@item 
@ref{506d,,PyNumber_InPlaceLshift()}

@item 
@ref{10b7,,PyNumber_InPlaceMatrixMultiply()}

@item 
@ref{506e,,PyNumber_InPlaceMultiply()}

@item 
@ref{506f,,PyNumber_InPlaceOr()}

@item 
@ref{5070,,PyNumber_InPlacePower()}

@item 
@ref{5071,,PyNumber_InPlaceRemainder()}

@item 
@ref{5072,,PyNumber_InPlaceRshift()}

@item 
@ref{5073,,PyNumber_InPlaceSubtract()}

@item 
@ref{5074,,PyNumber_InPlaceTrueDivide()}

@item 
@ref{5075,,PyNumber_InPlaceXor()}

@item 
@ref{a93,,PyNumber_Index()}

@item 
@ref{5076,,PyNumber_Invert()}

@item 
@ref{c5d,,PyNumber_Long()}

@item 
@ref{5077,,PyNumber_Lshift()}

@item 
@ref{10b6,,PyNumber_MatrixMultiply()}

@item 
@ref{5078,,PyNumber_Multiply()}

@item 
@ref{5079,,PyNumber_Negative()}

@item 
@ref{507a,,PyNumber_Or()}

@item 
@ref{507b,,PyNumber_Positive()}

@item 
@ref{507c,,PyNumber_Power()}

@item 
@ref{507d,,PyNumber_Remainder()}

@item 
@ref{507e,,PyNumber_Rshift()}

@item 
@ref{507f,,PyNumber_Subtract()}

@item 
@ref{1b73,,PyNumber_ToBase()}

@item 
@ref{5080,,PyNumber_TrueDivide()}

@item 
@ref{5081,,PyNumber_Xor()}

@item 
@ref{42f,,PyOS_AfterFork()}

@item 
@ref{430,,PyOS_AfterFork_Child()}

@item 
@ref{db9,,PyOS_AfterFork_Parent()}

@item 
@ref{db8,,PyOS_BeforeFork()}

@item 
@ref{1ba1,,PyOS_CheckStack()}

@item 
@ref{f14,,PyOS_FSPath()}

@item 
@ref{7a4,,PyOS_InputHook}

@item 
@ref{1d42,,PyOS_InterruptOccurred()}

@item 
@ref{5082,,PyOS_double_to_string()}

@item 
@ref{1757,,PyOS_getsig()}

@item 
@ref{1d3b,,PyOS_mystricmp()}

@item 
@ref{1d3a,,PyOS_mystrnicmp()}

@item 
@ref{1758,,PyOS_setsig()}

@item 
@ref{5083,,PyOS_sighandler_t}

@item 
@ref{1722,,PyOS_snprintf()}

@item 
@ref{14ad,,PyOS_string_to_double()}

@item 
@ref{5084,,PyOS_strtol()}

@item 
@ref{5085,,PyOS_strtoul()}

@item 
@ref{1723,,PyOS_vsnprintf()}

@item 
@ref{5df,,PyObject}

@item 
@ref{a9f,,PyObject.ob_refcnt}

@item 
@ref{4ecd,,PyObject.ob_type}

@item 
@ref{5086,,PyObject_ASCII()}

@item 
@ref{5087,,PyObject_AsFileDescriptor()}

@item 
@ref{5088,,PyObject_Bytes()}

@item 
@ref{63d,,PyObject_Call()}

@item 
@ref{63f,,PyObject_CallFunction()}

@item 
@ref{5089,,PyObject_CallFunctionObjArgs()}

@item 
@ref{640,,PyObject_CallMethod()}

@item 
@ref{1ddf,,PyObject_CallMethodObjArgs()}

@item 
@ref{63c,,PyObject_CallNoArgs()}

@item 
@ref{4eac,,PyObject_CallObject()}

@item 
@ref{10ae,,PyObject_Calloc()}

@item 
@ref{639,,PyObject_CheckBuffer()}

@item 
@ref{796,,PyObject_ClearWeakRefs()}

@item 
@ref{961,,PyObject_CopyData()}

@item 
@ref{1831,,PyObject_DelAttr()}

@item 
@ref{1832,,PyObject_DelAttrString()}

@item 
@ref{508a,,PyObject_DelItem()}

@item 
@ref{508b,,PyObject_DelItemString()}

@item 
@ref{508c,,PyObject_Dir()}

@item 
@ref{508d,,PyObject_Format()}

@item 
@ref{e60,,PyObject_Free()}

@item 
@ref{171c,,PyObject_GC_Del()}

@item 
@ref{b6e,,PyObject_GC_IsFinalized()}

@item 
@ref{b6d,,PyObject_GC_IsTracked()}

@item 
@ref{171d,,PyObject_GC_Track()}

@item 
@ref{171e,,PyObject_GC_UnTrack()}

@item 
@ref{508e,,PyObject_GenericGetAttr()}

@item 
@ref{1d05,,PyObject_GenericGetDict()}

@item 
@ref{508f,,PyObject_GenericSetAttr()}

@item 
@ref{5090,,PyObject_GenericSetDict()}

@item 
@ref{5091,,PyObject_GetAIter()}

@item 
@ref{5ee,,PyObject_GetAttr()}

@item 
@ref{5ef,,PyObject_GetAttrString()}

@item 
@ref{63a,,PyObject_GetBuffer()}

@item 
@ref{5ea,,PyObject_GetItem()}

@item 
@ref{5092,,PyObject_GetIter()}

@item 
@ref{5ec,,PyObject_GetOptionalAttr()}

@item 
@ref{5ed,,PyObject_GetOptionalAttrString()}

@item 
@ref{76b,,PyObject_GetTypeData()}

@item 
@ref{61c,,PyObject_HasAttr()}

@item 
@ref{61e,,PyObject_HasAttrString()}

@item 
@ref{61d,,PyObject_HasAttrStringWithError()}

@item 
@ref{61b,,PyObject_HasAttrWithError()}

@item 
@ref{436,,PyObject_Hash()}

@item 
@ref{15e0,,PyObject_HashNotImplemented()}

@item 
@ref{c60,,PyObject_Init()}

@item 
@ref{1d40,,PyObject_InitVar()}

@item 
@ref{10a6,,PyObject_IsInstance()}

@item 
@ref{10a7,,PyObject_IsSubclass()}

@item 
@ref{5093,,PyObject_IsTrue()}

@item 
@ref{5094,,PyObject_Length()}

@item 
@ref{e62,,PyObject_Malloc()}

@item 
@ref{5095,,PyObject_Not()}

@item 
@ref{165c,,PyObject_Realloc()}

@item 
@ref{1230,,PyObject_Repr()}

@item 
@ref{4ef1,,PyObject_RichCompare()}

@item 
@ref{1d8c,,PyObject_RichCompareBool()}

@item 
@ref{5096,,PyObject_SelfIter()}

@item 
@ref{5097,,PyObject_SetAttr()}

@item 
@ref{198e,,PyObject_SetAttrString()}

@item 
@ref{4f48,,PyObject_SetItem()}

@item 
@ref{5098,,PyObject_Size()}

@item 
@ref{1231,,PyObject_Str()}

@item 
@ref{5099,,PyObject_Type()}

@item 
@ref{77e,,PyObject_Vectorcall()}

@item 
@ref{77f,,PyObject_VectorcallMethod()}

@item 
@ref{509a,,PyProperty_Type}

@item 
@ref{509b,,PyRangeIter_Type}

@item 
@ref{509c,,PyRange_Type}

@item 
@ref{509d,,PyReversed_Type}

@item 
@ref{509e,,PySeqIter_New()}

@item 
@ref{509f,,PySeqIter_Type}

@item 
@ref{50a0,,PySequence_Check()}

@item 
@ref{50a1,,PySequence_Concat()}

@item 
@ref{3d9,,PySequence_Contains()}

@item 
@ref{50a2,,PySequence_Count()}

@item 
@ref{1e36,,PySequence_DelItem()}

@item 
@ref{50a3,,PySequence_DelSlice()}

@item 
@ref{18a2,,PySequence_Fast()}

@item 
@ref{1e34,,PySequence_GetItem()}

@item 
@ref{50a4,,PySequence_GetSlice()}

@item 
@ref{3d8,,PySequence_In()}

@item 
@ref{50a5,,PySequence_InPlaceConcat()}

@item 
@ref{50a6,,PySequence_InPlaceRepeat()}

@item 
@ref{50a7,,PySequence_Index()}

@item 
@ref{50a8,,PySequence_Length()}

@item 
@ref{50a9,,PySequence_List()}

@item 
@ref{50aa,,PySequence_Repeat()}

@item 
@ref{1e35,,PySequence_SetItem()}

@item 
@ref{50ab,,PySequence_SetSlice()}

@item 
@ref{1e33,,PySequence_Size()}

@item 
@ref{50ac,,PySequence_Tuple()}

@item 
@ref{50ad,,PySetIter_Type}

@item 
@ref{165f,,PySet_Add()}

@item 
@ref{50ae,,PySet_Clear()}

@item 
@ref{1661,,PySet_Contains()}

@item 
@ref{1660,,PySet_Discard()}

@item 
@ref{165d,,PySet_New()}

@item 
@ref{50af,,PySet_Pop()}

@item 
@ref{1662,,PySet_Size()}

@item 
@ref{50b0,,PySet_Type}

@item 
@ref{433,,PySlice_AdjustIndices()}

@item 
@ref{50b1,,PySlice_GetIndices()}

@item 
@ref{431,,PySlice_GetIndicesEx()}

@item 
@ref{50b2,,PySlice_New()}

@item 
@ref{50b3,,PySlice_Type}

@item 
@ref{432,,PySlice_Unpack()}

@item 
@ref{50b4,,PyState_AddModule()}

@item 
@ref{50b5,,PyState_FindModule()}

@item 
@ref{50b6,,PyState_RemoveModule()}

@item 
@ref{db4,,PyStructSequence_Desc}

@item 
@ref{db3,,PyStructSequence_Field}

@item 
@ref{50b7,,PyStructSequence_GetItem()}

@item 
@ref{50b8,,PyStructSequence_New()}

@item 
@ref{50b9,,PyStructSequence_NewType()}

@item 
@ref{50ba,,PyStructSequence_SetItem()}

@item 
@ref{b79,,PyStructSequence_UnnamedField}

@item 
@ref{50bb,,PySuper_Type}

@item 
@ref{613,,PySys_Audit()}

@item 
@ref{612,,PySys_AuditTuple()}

@item 
@ref{50bc,,PySys_FormatStderr()}

@item 
@ref{50bd,,PySys_FormatStdout()}

@item 
@ref{62a,,PySys_GetObject()}

@item 
@ref{50be,,PySys_GetXOptions()}

@item 
@ref{3f4,,PySys_ResetWarnOptions()}

@item 
@ref{19b8,,PySys_SetArgv()}

@item 
@ref{19b7,,PySys_SetArgvEx()}

@item 
@ref{50bf,,PySys_SetObject()}

@item 
@ref{50c0,,PySys_WriteStderr()}

@item 
@ref{50c1,,PySys_WriteStdout()}

@item 
@ref{990,,PyThreadState}

@item 
@ref{1991,,PyThreadState_Clear()}

@item 
@ref{1d89,,PyThreadState_Delete()}

@item 
@ref{615,,PyThreadState_Get()}

@item 
@ref{50c2,,PyThreadState_GetDict()}

@item 
@ref{991,,PyThreadState_GetFrame()}

@item 
@ref{b6a,,PyThreadState_GetID()}

@item 
@ref{b69,,PyThreadState_GetInterpreter()}

@item 
@ref{50c3,,PyThreadState_New()}

@item 
@ref{dbd,,PyThreadState_SetAsyncExc()}

@item 
@ref{50c4,,PyThreadState_Swap()}

@item 
@ref{50c5,,PyThread_GetInfo()}

@item 
@ref{441,,PyThread_ReInitTLS()}

@item 
@ref{50c6,,PyThread_acquire_lock()}

@item 
@ref{50c7,,PyThread_acquire_lock_timed()}

@item 
@ref{50c8,,PyThread_allocate_lock()}

@item 
@ref{437,,PyThread_create_key()}

@item 
@ref{439,,PyThread_delete_key()}

@item 
@ref{43f,,PyThread_delete_key_value()}

@item 
@ref{50c9,,PyThread_exit_thread()}

@item 
@ref{50ca,,PyThread_free_lock()}

@item 
@ref{43d,,PyThread_get_key_value()}

@item 
@ref{50cb,,PyThread_get_stacksize()}

@item 
@ref{50cc,,PyThread_get_thread_ident()}

@item 
@ref{1ba2,,PyThread_get_thread_native_id()}

@item 
@ref{50cd,,PyThread_init_thread()}

@item 
@ref{50ce,,PyThread_release_lock()}

@item 
@ref{43b,,PyThread_set_key_value()}

@item 
@ref{50cf,,PyThread_set_stacksize()}

@item 
@ref{1e2b,,PyThread_start_new_thread()}

@item 
@ref{438,,PyThread_tss_alloc()}

@item 
@ref{50d0,,PyThread_tss_create()}

@item 
@ref{440,,PyThread_tss_delete()}

@item 
@ref{43a,,PyThread_tss_free()}

@item 
@ref{43e,,PyThread_tss_get()}

@item 
@ref{50d1,,PyThread_tss_is_created()}

@item 
@ref{43c,,PyThread_tss_set()}

@item 
@ref{50d2,,PyTraceBack_Here()}

@item 
@ref{50d3,,PyTraceBack_Print()}

@item 
@ref{50d4,,PyTraceBack_Type}

@item 
@ref{50d5,,PyTupleIter_Type}

@item 
@ref{4eb7,,PyTuple_GetItem()}

@item 
@ref{50d6,,PyTuple_GetSlice()}

@item 
@ref{63e,,PyTuple_New()}

@item 
@ref{50d7,,PyTuple_Pack()}

@item 
@ref{4eb8,,PyTuple_SetItem()}

@item 
@ref{50d8,,PyTuple_Size()}

@item 
@ref{50d9,,PyTuple_Type}

@item 
@ref{c9c,,PyTypeObject}

@item 
@ref{50da,,PyType_ClearCache()}

@item 
@ref{3af,,PyType_Freeze()}

@item 
@ref{772,,PyType_FromMetaclass()}

@item 
@ref{773,,PyType_FromModuleAndSpec()}

@item 
@ref{79d,,PyType_FromSpec()}

@item 
@ref{79e,,PyType_FromSpecWithBases()}

@item 
@ref{c61,,PyType_GenericAlloc()}

@item 
@ref{4ecc,,PyType_GenericNew()}

@item 
@ref{3b0,,PyType_GetBaseByToken()}

@item 
@ref{1d3d,,PyType_GetFlags()}

@item 
@ref{616,,PyType_GetFullyQualifiedName()}

@item 
@ref{b66,,PyType_GetModule()}

@item 
@ref{635,,PyType_GetModuleByDef()}

@item 
@ref{618,,PyType_GetModuleName()}

@item 
@ref{b67,,PyType_GetModuleState()}

@item 
@ref{958,,PyType_GetName()}

@item 
@ref{959,,PyType_GetQualName()}

@item 
@ref{a9c,,PyType_GetSlot()}

@item 
@ref{76c,,PyType_GetTypeDataSize()}

@item 
@ref{50db,,PyType_IsSubtype()}

@item 
@ref{1b7b,,PyType_Modified()}

@item 
@ref{980,,PyType_Ready()}

@item 
@ref{50dc,,PyType_Slot}

@item 
@ref{1a89,,PyType_Spec}

@item 
@ref{76f,,PyType_Type}

@item 
@ref{50dd,,PyUnicodeDecodeError_Create()}

@item 
@ref{50de,,PyUnicodeDecodeError_GetEncoding()}

@item 
@ref{50df,,PyUnicodeDecodeError_GetEnd()}

@item 
@ref{50e0,,PyUnicodeDecodeError_GetObject()}

@item 
@ref{50e1,,PyUnicodeDecodeError_GetReason()}

@item 
@ref{50e2,,PyUnicodeDecodeError_GetStart()}

@item 
@ref{50e3,,PyUnicodeDecodeError_SetEnd()}

@item 
@ref{50e4,,PyUnicodeDecodeError_SetReason()}

@item 
@ref{50e5,,PyUnicodeDecodeError_SetStart()}

@item 
@ref{50e6,,PyUnicodeEncodeError_GetEncoding()}

@item 
@ref{18fb,,PyUnicodeEncodeError_GetEnd()}

@item 
@ref{50e7,,PyUnicodeEncodeError_GetObject()}

@item 
@ref{50e8,,PyUnicodeEncodeError_GetReason()}

@item 
@ref{18fe,,PyUnicodeEncodeError_GetStart()}

@item 
@ref{50e9,,PyUnicodeEncodeError_SetEnd()}

@item 
@ref{50ea,,PyUnicodeEncodeError_SetReason()}

@item 
@ref{50eb,,PyUnicodeEncodeError_SetStart()}

@item 
@ref{50ec,,PyUnicodeIter_Type}

@item 
@ref{50ed,,PyUnicodeTranslateError_GetEnd()}

@item 
@ref{50ee,,PyUnicodeTranslateError_GetObject()}

@item 
@ref{50ef,,PyUnicodeTranslateError_GetReason()}

@item 
@ref{50f0,,PyUnicodeTranslateError_GetStart()}

@item 
@ref{50f1,,PyUnicodeTranslateError_SetEnd()}

@item 
@ref{50f2,,PyUnicodeTranslateError_SetReason()}

@item 
@ref{50f3,,PyUnicodeTranslateError_SetStart()}

@item 
@ref{50f4,,PyUnicode_Append()}

@item 
@ref{50f5,,PyUnicode_AppendAndDel()}

@item 
@ref{13aa,,PyUnicode_AsASCIIString()}

@item 
@ref{50f6,,PyUnicode_AsCharmapString()}

@item 
@code{PyUnicode_AsDecodedObject()}

@item 
@code{PyUnicode_AsDecodedUnicode()}

@item 
@code{PyUnicode_AsEncodedObject()}

@item 
@ref{50f7,,PyUnicode_AsEncodedString()}

@item 
@code{PyUnicode_AsEncodedUnicode()}

@item 
@ref{13a9,,PyUnicode_AsLatin1String()}

@item 
@ref{13ab,,PyUnicode_AsMBCSString()}

@item 
@ref{13a8,,PyUnicode_AsRawUnicodeEscapeString()}

@item 
@ref{1390,,PyUnicode_AsUCS4()}

@item 
@ref{ab8,,PyUnicode_AsUCS4Copy()}

@item 
@ref{50f8,,PyUnicode_AsUTF16String()}

@item 
@ref{50f9,,PyUnicode_AsUTF32String()}

@item 
@ref{a99,,PyUnicode_AsUTF8AndSize()}

@item 
@ref{13a6,,PyUnicode_AsUTF8String()}

@item 
@ref{13a7,,PyUnicode_AsUnicodeEscapeString()}

@item 
@ref{1e38,,PyUnicode_AsWideChar()}

@item 
@ref{ab9,,PyUnicode_AsWideCharString()}

@item 
@ref{1a62,,PyUnicode_BuildEncodingMap()}

@item 
@ref{ab4,,PyUnicode_Compare()}

@item 
@ref{147f,,PyUnicode_CompareWithASCIIString()}

@item 
@ref{13b9,,PyUnicode_Concat()}

@item 
@ref{50fa,,PyUnicode_Contains()}

@item 
@ref{50fb,,PyUnicode_Count()}

@item 
@ref{1dc7,,PyUnicode_Decode()}

@item 
@ref{50fc,,PyUnicode_DecodeASCII()}

@item 
@ref{50fd,,PyUnicode_DecodeCharmap()}

@item 
@ref{50fe,,PyUnicode_DecodeCodePageStateful()}

@item 
@ref{1a88,,PyUnicode_DecodeFSDefault()}

@item 
@ref{50ff,,PyUnicode_DecodeFSDefaultAndSize()}

@item 
@ref{5100,,PyUnicode_DecodeLatin1()}

@item 
@ref{5101,,PyUnicode_DecodeLocale()}

@item 
@ref{dc2,,PyUnicode_DecodeLocaleAndSize()}

@item 
@ref{5102,,PyUnicode_DecodeMBCS()}

@item 
@ref{5103,,PyUnicode_DecodeMBCSStateful()}

@item 
@ref{5104,,PyUnicode_DecodeRawUnicodeEscape()}

@item 
@ref{5105,,PyUnicode_DecodeUTF16()}

@item 
@ref{5106,,PyUnicode_DecodeUTF16Stateful()}

@item 
@ref{5107,,PyUnicode_DecodeUTF32()}

@item 
@ref{5108,,PyUnicode_DecodeUTF32Stateful()}

@item 
@ref{5109,,PyUnicode_DecodeUTF7()}

@item 
@ref{510a,,PyUnicode_DecodeUTF7Stateful()}

@item 
@ref{510b,,PyUnicode_DecodeUTF8()}

@item 
@ref{1b17,,PyUnicode_DecodeUTF8Stateful()}

@item 
@ref{510c,,PyUnicode_DecodeUnicodeEscape()}

@item 
@ref{13ac,,PyUnicode_EncodeCodePage()}

@item 
@ref{1e31,,PyUnicode_EncodeFSDefault()}

@item 
@ref{dc3,,PyUnicode_EncodeLocale()}

@item 
@ref{3b2,,PyUnicode_Equal()}

@item 
@ref{61a,,PyUnicode_EqualToUTF8()}

@item 
@ref{619,,PyUnicode_EqualToUTF8AndSize()}

@item 
@ref{f15,,PyUnicode_FSConverter()}

@item 
@ref{797,,PyUnicode_FSDecoder()}

@item 
@ref{510d,,PyUnicode_Find()}

@item 
@ref{ab6,,PyUnicode_FindChar()}

@item 
@ref{510e,,PyUnicode_Format()}

@item 
@ref{510f,,PyUnicode_FromEncodedObject()}

@item 
@ref{62b,,PyUnicode_FromFormat()}

@item 
@ref{794,,PyUnicode_FromFormatV()}

@item 
@ref{5110,,PyUnicode_FromObject()}

@item 
@ref{5111,,PyUnicode_FromOrdinal()}

@item 
@ref{5112,,PyUnicode_FromString()}

@item 
@ref{5113,,PyUnicode_FromStringAndSize()}

@item 
@ref{13a4,,PyUnicode_FromWideChar()}

@item 
@ref{5114,,PyUnicode_GetDefaultEncoding()}

@item 
@ref{ab0,,PyUnicode_GetLength()}

@item 
@ref{198c,,PyUnicode_InternFromString()}

@item 
@ref{aae,,PyUnicode_InternInPlace()}

@item 
@ref{1d86,,PyUnicode_IsIdentifier()}

@item 
@ref{13ba,,PyUnicode_Join()}

@item 
@ref{1898,,PyUnicode_Partition()}

@item 
@ref{1899,,PyUnicode_RPartition()}

@item 
@ref{1897,,PyUnicode_RSplit()}

@item 
@ref{1389,,PyUnicode_ReadChar()}

@item 
@ref{5115,,PyUnicode_Replace()}

@item 
@ref{5116,,PyUnicode_Resize()}

@item 
@ref{5117,,PyUnicode_RichCompare()}

@item 
@ref{5118,,PyUnicode_Split()}

@item 
@ref{5119,,PyUnicode_Splitlines()}

@item 
@ref{ab3,,PyUnicode_Substring()}

@item 
@ref{ab5,,PyUnicode_Tailmatch()}

@item 
@ref{511a,,PyUnicode_Translate()}

@item 
@ref{511b,,PyUnicode_Type}

@item 
@ref{138a,,PyUnicode_WriteChar()}

@item 
@ref{46d6,,PyVarObject}

@item 
@code{PyVarObject.ob_base}

@item 
@ref{511c,,PyVarObject.ob_size}

@item 
@ref{778,,PyVectorcall_Call()}

@item 
@ref{777,,PyVectorcall_NARGS()}

@item 
@code{PyWeakReference}

@item 
@ref{3dd,,PyWeakref_GetObject()}

@item 
@ref{3df,,PyWeakref_GetRef()}

@item 
@ref{511d,,PyWeakref_NewProxy()}

@item 
@ref{1be6,,PyWeakref_NewRef()}

@item 
@ref{511e,,PyWrapperDescr_Type}

@item 
@ref{511f,,PyWrapper_New()}

@item 
@ref{5120,,PyZip_Type}

@item 
@ref{5121,,Py_ASNATIVEBYTES_ALLOW_INDEX}

@item 
@ref{5122,,Py_ASNATIVEBYTES_BIG_ENDIAN}

@item 
@ref{5123,,Py_ASNATIVEBYTES_DEFAULTS}

@item 
@ref{5124,,Py_ASNATIVEBYTES_LITTLE_ENDIAN}

@item 
@ref{5125,,Py_ASNATIVEBYTES_NATIVE_ENDIAN}

@item 
@ref{5126,,Py_ASNATIVEBYTES_REJECT_NEGATIVE}

@item 
@ref{5127,,Py_ASNATIVEBYTES_UNSIGNED_BUFFER}

@item 
@ref{7af,,Py_AUDIT_READ}

@item 
@ref{b78,,Py_AddPendingCall()}

@item 
@ref{5128,,Py_AtExit()}

@item 
@ref{4ebd,,Py_BEGIN_ALLOW_THREADS}

@item 
@ref{5129,,Py_BLOCK_THREADS}

@item 
@ref{3c2,,Py_BuildValue()}

@item 
@ref{bb8,,Py_BytesMain()}

@item 
@ref{a85,,Py_CompileString()}

@item 
@ref{512a,,Py_DecRef()}

@item 
@ref{dc0,,Py_DecodeLocale()}

@item 
@ref{c7f,,Py_END_ALLOW_THREADS}

@item 
@ref{dc1,,Py_EncodeLocale()}

@item 
@ref{1845,,Py_EndInterpreter()}

@item 
@ref{3d2,,Py_EnterRecursiveCall()}

@item 
@ref{f4b,,Py_Exit()}

@item 
@ref{b7a,,Py_FatalError()}

@item 
@code{Py_FileSystemDefaultEncodeErrors}

@item 
@code{Py_FileSystemDefaultEncoding}

@item 
@ref{45f,,Py_Finalize()}

@item 
@ref{f11,,Py_FinalizeEx()}

@item 
@ref{512b,,Py_GenericAlias()}

@item 
@ref{512c,,Py_GenericAliasType}

@item 
@ref{164b,,Py_GetBuildInfo()}

@item 
@ref{512d,,Py_GetCompiler()}

@item 
@ref{5f9,,Py_GetConstant()}

@item 
@ref{5fa,,Py_GetConstantBorrowed()}

@item 
@ref{512e,,Py_GetCopyright()}

@item 
@ref{3e9,,Py_GetExecPrefix()}

@item 
@ref{3e3,,Py_GetPath()}

@item 
@ref{512f,,Py_GetPlatform()}

@item 
@ref{3e5,,Py_GetPrefix()}

@item 
@ref{3ec,,Py_GetProgramFullPath()}

@item 
@ref{3ee,,Py_GetProgramName()}

@item 
@ref{3ef,,Py_GetPythonHome()}

@item 
@ref{5130,,Py_GetRecursionLimit()}

@item 
@ref{5131,,Py_GetVersion()}

@item 
@code{Py_HasFileSystemDefaultEncoding}

@item 
@ref{5132,,Py_IncRef()}

@item 
@ref{460,,Py_Initialize()}

@item 
@ref{5133,,Py_InitializeEx()}

@item 
@ref{aa0,,Py_Is()}

@item 
@ref{aa3,,Py_IsFalse()}

@item 
@ref{5fd,,Py_IsFinalizing()}

@item 
@ref{4f51,,Py_IsInitialized()}

@item 
@ref{aa1,,Py_IsNone()}

@item 
@ref{aa2,,Py_IsTrue()}

@item 
@ref{b6b,,Py_LeaveRecursiveCall()}

@item 
@ref{e1e,,Py_Main()}

@item 
@ref{5134,,Py_MakePendingCalls()}

@item 
@ref{1b31,,Py_NewInterpreter()}

@item 
@ref{a9a,,Py_NewRef()}

@item 
@ref{380,,Py_PACK_FULL_VERSION()}

@item 
@ref{37f,,Py_PACK_VERSION()}

@item 
@ref{7ae,,Py_READONLY}

@item 
@ref{2cf,,Py_REFCNT()}

@item 
@ref{770,,Py_RELATIVE_OFFSET}

@item 
@ref{5135,,Py_ReprEnter()}

@item 
@ref{5136,,Py_ReprLeave()}

@item 
@ref{19b6,,Py_SetProgramName()}

@item 
@ref{19b5,,Py_SetPythonHome()}

@item 
@ref{5137,,Py_SetRecursionLimit()}

@item 
@ref{4ed5,,Py_TPFLAGS_BASETYPE}

@item 
@ref{4eca,,Py_TPFLAGS_DEFAULT}

@item 
@ref{981,,Py_TPFLAGS_HAVE_GC}

@item 
@ref{776,,Py_TPFLAGS_HAVE_VECTORCALL}

@item 
@ref{76d,,Py_TPFLAGS_ITEMS_AT_END}

@item 
@ref{5138,,Py_TPFLAGS_METHOD_DESCRIPTOR}

@item 
@ref{5139,,Py_TP_USE_SPEC}

@item 
@ref{3c9,,Py_TYPE()}

@item 
@ref{513a,,Py_T_BOOL}

@item 
@ref{513b,,Py_T_BYTE}

@item 
@ref{513c,,Py_T_CHAR}

@item 
@ref{7ad,,Py_T_DOUBLE}

@item 
@ref{513d,,Py_T_FLOAT}

@item 
@ref{7ac,,Py_T_INT}

@item 
@ref{513e,,Py_T_LONG}

@item 
@ref{513f,,Py_T_LONGLONG}

@item 
@ref{7b1,,Py_T_OBJECT_EX}

@item 
@ref{5140,,Py_T_PYSSIZET}

@item 
@ref{5141,,Py_T_SHORT}

@item 
@ref{5142,,Py_T_STRING}

@item 
@ref{5143,,Py_T_STRING_INPLACE}

@item 
@ref{5144,,Py_T_UBYTE}

@item 
@ref{5145,,Py_T_UINT}

@item 
@ref{5146,,Py_T_ULONG}

@item 
@ref{5147,,Py_T_ULONGLONG}

@item 
@ref{5148,,Py_T_USHORT}

@item 
@ref{33d,,Py_UCS4}

@item 
@ref{5149,,Py_UNBLOCK_THREADS}

@item 
@code{Py_UTF8Mode}

@item 
@ref{514a,,Py_VaBuildValue()}

@item 
@ref{381,,Py_Version}

@item 
@ref{a9b,,Py_XNewRef()}

@item 
@ref{514b,,Py_am_aiter}

@item 
@ref{514c,,Py_am_anext}

@item 
@ref{514d,,Py_am_await}

@item 
@ref{514e,,Py_am_send}

@item 
@ref{514f,,Py_bf_getbuffer}

@item 
@ref{5150,,Py_bf_releasebuffer}

@item 
@ref{95c,,Py_buffer}

@item 
@code{Py_intptr_t}

@item 
@ref{5151,,Py_mod_create}

@item 
@ref{b75,,Py_mod_exec}

@item 
@ref{482,,Py_mod_gil}

@item 
@ref{5152,,Py_mod_multiple_interpreters}

@item 
@ref{5153,,Py_mp_ass_subscript}

@item 
@ref{5154,,Py_mp_length}

@item 
@ref{5155,,Py_mp_subscript}

@item 
@ref{5156,,Py_nb_absolute}

@item 
@ref{5157,,Py_nb_add}

@item 
@ref{5158,,Py_nb_and}

@item 
@ref{5159,,Py_nb_bool}

@item 
@ref{515a,,Py_nb_divmod}

@item 
@ref{515b,,Py_nb_float}

@item 
@ref{515c,,Py_nb_floor_divide}

@item 
@ref{515d,,Py_nb_index}

@item 
@ref{515e,,Py_nb_inplace_add}

@item 
@ref{515f,,Py_nb_inplace_and}

@item 
@ref{5160,,Py_nb_inplace_floor_divide}

@item 
@ref{5161,,Py_nb_inplace_lshift}

@item 
@ref{5162,,Py_nb_inplace_matrix_multiply}

@item 
@ref{5163,,Py_nb_inplace_multiply}

@item 
@ref{5164,,Py_nb_inplace_or}

@item 
@ref{5165,,Py_nb_inplace_power}

@item 
@ref{5166,,Py_nb_inplace_remainder}

@item 
@ref{5167,,Py_nb_inplace_rshift}

@item 
@ref{5168,,Py_nb_inplace_subtract}

@item 
@ref{5169,,Py_nb_inplace_true_divide}

@item 
@ref{516a,,Py_nb_inplace_xor}

@item 
@ref{516b,,Py_nb_int}

@item 
@ref{516c,,Py_nb_invert}

@item 
@ref{516d,,Py_nb_lshift}

@item 
@ref{516e,,Py_nb_matrix_multiply}

@item 
@ref{516f,,Py_nb_multiply}

@item 
@ref{5170,,Py_nb_negative}

@item 
@ref{5171,,Py_nb_or}

@item 
@ref{5172,,Py_nb_positive}

@item 
@ref{5173,,Py_nb_power}

@item 
@ref{5174,,Py_nb_remainder}

@item 
@ref{5175,,Py_nb_rshift}

@item 
@ref{5176,,Py_nb_subtract}

@item 
@ref{5177,,Py_nb_true_divide}

@item 
@ref{5178,,Py_nb_xor}

@item 
@ref{5179,,Py_sq_ass_item}

@item 
@ref{517a,,Py_sq_concat}

@item 
@ref{517b,,Py_sq_contains}

@item 
@ref{517c,,Py_sq_inplace_concat}

@item 
@ref{517d,,Py_sq_inplace_repeat}

@item 
@ref{517e,,Py_sq_item}

@item 
@ref{517f,,Py_sq_length}

@item 
@ref{5180,,Py_sq_repeat}

@item 
@ref{c55,,Py_ssize_t}

@item 
@ref{5181,,Py_tp_alloc}

@item 
@ref{5182,,Py_tp_base}

@item 
@ref{5183,,Py_tp_bases}

@item 
@ref{5184,,Py_tp_call}

@item 
@ref{5185,,Py_tp_clear}

@item 
@ref{5186,,Py_tp_dealloc}

@item 
@ref{5187,,Py_tp_del}

@item 
@ref{5188,,Py_tp_descr_get}

@item 
@ref{5189,,Py_tp_descr_set}

@item 
@ref{518a,,Py_tp_doc}

@item 
@ref{518b,,Py_tp_finalize}

@item 
@ref{518c,,Py_tp_free}

@item 
@ref{518d,,Py_tp_getattr}

@item 
@ref{518e,,Py_tp_getattro}

@item 
@ref{518f,,Py_tp_getset}

@item 
@ref{5190,,Py_tp_hash}

@item 
@ref{5191,,Py_tp_init}

@item 
@ref{5192,,Py_tp_is_gc}

@item 
@ref{5193,,Py_tp_iter}

@item 
@ref{5194,,Py_tp_iternext}

@item 
@ref{5195,,Py_tp_members}

@item 
@ref{5196,,Py_tp_methods}

@item 
@ref{5197,,Py_tp_new}

@item 
@ref{5198,,Py_tp_repr}

@item 
@ref{5199,,Py_tp_richcompare}

@item 
@ref{519a,,Py_tp_setattr}

@item 
@ref{519b,,Py_tp_setattro}

@item 
@ref{519c,,Py_tp_str}

@item 
@ref{3b1,,Py_tp_token}

@item 
@ref{519d,,Py_tp_traverse}

@item 
@ref{519e,,Py_tp_vectorcall}

@item 
@code{Py_uintptr_t}

@item 
@ref{519f,,allocfunc}

@item 
@ref{51a0,,binaryfunc}

@item 
@ref{51a1,,descrgetfunc}

@item 
@ref{51a2,,descrsetfunc}

@item 
@ref{51a3,,destructor}

@item 
@ref{51a4,,getattrfunc}

@item 
@ref{51a5,,getattrofunc}

@item 
@ref{51a6,,getbufferproc}

@item 
@ref{51a7,,getiterfunc}

@item 
@ref{51a8,,getter}

@item 
@ref{51a9,,hashfunc}

@item 
@ref{51aa,,initproc}

@item 
@ref{51ab,,inquiry}

@item 
@ref{51ac,,iternextfunc}

@item 
@ref{51ad,,lenfunc}

@item 
@ref{51ae,,newfunc}

@item 
@ref{51af,,objobjargproc}

@item 
@ref{51b0,,objobjproc}

@item 
@ref{51b1,,releasebufferproc}

@item 
@ref{51b2,,reprfunc}

@item 
@ref{51b3,,richcmpfunc}

@item 
@ref{51b4,,setattrfunc}

@item 
@ref{51b5,,setattrofunc}

@item 
@ref{51b6,,setter}

@item 
@ref{51b7,,ssizeargfunc}

@item 
@ref{51b8,,ssizeobjargproc}

@item 
@code{ssizessizeargfunc}

@item 
@code{ssizessizeobjargproc}

@item 
@code{symtable}

@item 
@ref{51b9,,ternaryfunc}

@item 
@ref{51ba,,traverseproc}

@item 
@ref{51bb,,unaryfunc}

@item 
@ref{779,,vectorcallfunc}

@item 
@ref{51bc,,visitproc}
@end itemize


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 超高水準レイヤ,参照カウント,C API の安定性,Python/C API リファレンスマニュアル
@anchor{c-api/veryhigh doc}@anchor{51bd}@anchor{c-api/veryhigh the-very-high-level-layer}@anchor{51be}@anchor{c-api/veryhigh translation-repo}@anchor{51bf}@anchor{c-api/veryhigh veryhigh}@anchor{51c0}
@section 超高水準レイヤ


この章の関数を使うとファイルまたはバッファにある Python ソースコードを実行できますが、より詳細なやり取りをインタプリタとすることはできないでしょう。

Several of these functions accept a start symbol from the grammar as a
parameter.  The available start symbols are @ref{51c1,,Py_eval_input},
@ref{51c2,,Py_file_input}, @ref{51c3,,Py_single_input}, and
@ref{51c4,,Py_func_type_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 @code{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.

@geindex PyRun_AnyFile (C function)
@anchor{c-api/veryhigh c PyRun_AnyFile}@anchor{51c5}
@deffn {C の関数} int PyRun_AnyFile (FILE *fp, const char *filename)

下記の @ref{51c6,,PyRun_AnyFileExFlags()} の `closeit' を @code{0} に、 `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_AnyFileFlags (C function)
@anchor{c-api/veryhigh c PyRun_AnyFileFlags}@anchor{51c7}
@deffn {C の関数} int PyRun_AnyFileFlags (FILE *fp, const char *filename, PyCompilerFlags *flags)

下記の @ref{51c6,,PyRun_AnyFileExFlags()} の `closeit' を @code{0} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_AnyFileEx (C function)
@anchor{c-api/veryhigh c PyRun_AnyFileEx}@anchor{51c8}
@deffn {C の関数} int PyRun_AnyFileEx (FILE *fp, const char *filename, int closeit)

下記の @ref{51c6,,PyRun_AnyFileExFlags()} の `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_AnyFileExFlags (C function)
@anchor{c-api/veryhigh c PyRun_AnyFileExFlags}@anchor{51c6}
@deffn {C の関数} int PyRun_AnyFileExFlags (FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)

`fp' が対話的デバイス (コンソールや端末入力あるいは Unix 仮想端末) と関連づけられたファイルを参照している場合は、 @ref{51c9,,PyRun_InteractiveLoop()} の値を返します。それ以外の場合は、 @ref{4f0c,,PyRun_SimpleFile()} の結果を返します。 `filename' はファイルシステムのエンコーディング (@ref{e53,,sys.getfilesystemencoding()}) でデコードされます。 `filename' が @code{NULL} ならば、この関数はファイル名として @code{"???"} を使います。`closeit' が真なら、ファイルは @code{PyRun_SimpleFileExFlags()} が処理を戻す前に閉じられます。
@end deffn

@geindex PyRun_SimpleString (C function)
@anchor{c-api/veryhigh c PyRun_SimpleString}@anchor{4f0b}
@deffn {C の関数} int PyRun_SimpleString (const char *command)

下記の @ref{51ca,,PyRun_SimpleStringFlags()} の @ref{c98,,PyCompilerFlags}* を @code{NULL} にして単純化したインタフェースです。
@end deffn

@geindex PyRun_SimpleStringFlags (C function)
@anchor{c-api/veryhigh c PyRun_SimpleStringFlags}@anchor{51ca}
@deffn {C の関数} int PyRun_SimpleStringFlags (const char *command, PyCompilerFlags *flags)

@ref{1,,__main__} モジュールの中で `flags' に従って `command' に含まれる Python ソースコードを実行します。 @ref{1,,__main__} がまだ存在しない場合は作成されます。正常終了の場合は @code{0} を返し、また例外が発生した場合は @code{-1} を返します。エラーがあっても、例外情報を得る方法はありません。 `flags' の意味については、後述します。

Note that if an otherwise unhandled @ref{f3c,,SystemExit} is raised, this
function will not return @code{-1}, but exit the process, as long as
@ref{401,,PyConfig.inspect} is zero.
@end deffn

@geindex PyRun_SimpleFile (C function)
@anchor{c-api/veryhigh c PyRun_SimpleFile}@anchor{4f0c}
@deffn {C の関数} int PyRun_SimpleFile (FILE *fp, const char *filename)

下記の @ref{1cca,,PyRun_SimpleFileExFlags()} の `closeit' を @code{0} に、 `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_SimpleFileEx (C function)
@anchor{c-api/veryhigh c PyRun_SimpleFileEx}@anchor{51cb}
@deffn {C の関数} int PyRun_SimpleFileEx (FILE *fp, const char *filename, int closeit)

下記の @ref{1cca,,PyRun_SimpleFileExFlags()} の `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_SimpleFileExFlags (C function)
@anchor{c-api/veryhigh c PyRun_SimpleFileExFlags}@anchor{1cca}
@deffn {C の関数} int PyRun_SimpleFileExFlags (FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)

@ref{51ca,,PyRun_SimpleStringFlags()} と似ていますが、Pythonソースコードをメモリ内の文字列ではなく `fp' から読み込みます。 `filename' はそのファイルの名前でなければならず、 @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} でデコードされます。 `closeit' に真を指定した場合は、@code{PyRun_SimpleFileExFlags()} が処理を戻す前にファイルを閉じます。

@cartouche
@quotation 注釈 
Windowsでは、 `fp' はバイナリモードで開くべきです (例えば @code{fopen(filename, "rb")})。
そうしない場合は、 Python は行末が LF のスクリプトを正しく扱えないでしょう。
@end quotation
@end cartouche
@end deffn

@geindex PyRun_InteractiveOneObject (C function)
@anchor{c-api/veryhigh c PyRun_InteractiveOneObject}@anchor{51cc}
@deffn {C の関数} int PyRun_InteractiveOneObject (FILE *fp, PyObject *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 @code{sys.ps1} and @code{sys.ps2}. `filename' must be a Python
@ref{169,,str} object.

入力が正常に実行されたときは @code{0} を返します。例外が発生した場合は @code{-1} を返します。パースエラーの場合はPythonの一部として配布されている @code{errcode.h} インクルードファイルにあるエラーコードを返します。 (@code{Python.h} は @code{errcode.h} をインクルードしません。従って、 必要な場合はその都度インクルードしなければならないことに注意してください。)
@end deffn

@geindex PyRun_InteractiveOne (C function)
@anchor{c-api/veryhigh c PyRun_InteractiveOne}@anchor{51cd}
@deffn {C の関数} int PyRun_InteractiveOne (FILE *fp, const char *filename)

下記の @ref{51ce,,PyRun_InteractiveOneFlags()} の `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_InteractiveOneFlags (C function)
@anchor{c-api/veryhigh c PyRun_InteractiveOneFlags}@anchor{51ce}
@deffn {C の関数} int PyRun_InteractiveOneFlags (FILE *fp, const char *filename, PyCompilerFlags *flags)

Similar to @ref{51cc,,PyRun_InteractiveOneObject()}, but `filename' is a
const char*, which is decoded from the
@ref{75d,,filesystem encoding and error handler}.
@end deffn

@geindex PyRun_InteractiveLoop (C function)
@anchor{c-api/veryhigh c PyRun_InteractiveLoop}@anchor{51c9}
@deffn {C の関数} int PyRun_InteractiveLoop (FILE *fp, const char *filename)

下記の @ref{51cf,,PyRun_InteractiveLoopFlags()} の `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_InteractiveLoopFlags (C function)
@anchor{c-api/veryhigh c PyRun_InteractiveLoopFlags}@anchor{51cf}
@deffn {C の関数} int PyRun_InteractiveLoopFlags (FILE *fp, const char *filename, PyCompilerFlags *flags)

対話的デバイスに関連付けられたファイルから EOF に達するまで文を読み込み実行します。
@code{sys.ps1} と @code{sys.ps2} を使って、ユーザにプロンプトを表示します。
`filename' は @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} でデコードされます。
EOFに達すると @code{0} を返すか、失敗したら負の数を返します。
@end deffn

@geindex PyOS_InputHook (C var)
@anchor{c-api/veryhigh c PyOS_InputHook}@anchor{7a4}
@deffn {C 変数} int (*PyOS_InputHook)(void)
` 次に属します: @ref{775,,Stable ABI}.'
Can be set to point to a function with the prototype
@code{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 @code{Modules/_tkinter.c} in the
Python source code.


バージョン 3.12 で変更: This function is only called from the
@ref{163,,main interpreter}.

@end deffn

@geindex PyOS_ReadlineFunctionPointer (C var)
@anchor{c-api/veryhigh c PyOS_ReadlineFunctionPointer}@anchor{7a5}
@deffn {C 変数} char *(*PyOS_ReadlineFunctionPointer)(FILE*, FILE*, const char*)

@code{char *func(FILE *stdin, FILE *stdout, char *prompt)} というプロトタイプの関数へのポインタが設定でき、デフォルトの関数を上書きすることでインタプリタのプロンプトへの入力を1行だけ読めます。
この関数は、文字列 `prompt' が @code{NULL} でない場合は `prompt' を出力し、与えられた標準入力ファイルから入力を1行読み、結果の文字列を返すという動作が期待されています。
例えば、 @ref{bf,,readline} モジュールはこのフックを設定して、行編集機能やタブ補完機能を提供しています。

返り値は @ref{631,,PyMem_RawMalloc()} または @ref{633,,PyMem_RawRealloc()} でメモリ確保した文字列、あるいはエラーが起きた場合には @code{NULL} でなければなりません。


バージョン 3.4 で変更: 返り値は、 @ref{e5f,,PyMem_Malloc()} や @ref{1233,,PyMem_Realloc()} ではなく、 @ref{631,,PyMem_RawMalloc()} または @ref{633,,PyMem_RawRealloc()} でメモリ確保したものでなければなりません。



バージョン 3.12 で変更: This function is only called from the
@ref{163,,main interpreter}.

@end deffn

@geindex PyRun_String (C function)
@anchor{c-api/veryhigh c PyRun_String}@anchor{1dc0}
@deffn {C の関数} @ref{5df,,PyObject} *PyRun_String (const char *str, int start, PyObject *globals, PyObject *locals)
`戻り値: 新しい参照。'
下記の @ref{51d0,,PyRun_StringFlags()} の `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_StringFlags (C function)
@anchor{c-api/veryhigh c PyRun_StringFlags}@anchor{51d0}
@deffn {C の関数} @ref{5df,,PyObject} *PyRun_StringFlags (const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)
`戻り値: 新しい参照。'
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 symbol and must be one of the @ref{51d1,,available start symbols}.

コードを実行した結果をPythonオブジェクトとして返します。または、例外が発生したならば @code{NULL} を返します。
@end deffn

@geindex PyRun_File (C function)
@anchor{c-api/veryhigh c PyRun_File}@anchor{51d2}
@deffn {C の関数} @ref{5df,,PyObject} *PyRun_File (FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
`戻り値: 新しい参照。'
下記の @ref{51d3,,PyRun_FileExFlags()} の `closeit' を @code{0} にし、 `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_FileEx (C function)
@anchor{c-api/veryhigh c PyRun_FileEx}@anchor{51d4}
@deffn {C の関数} @ref{5df,,PyObject} *PyRun_FileEx (FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit)
`戻り値: 新しい参照。'
下記の @ref{51d3,,PyRun_FileExFlags()} の `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_FileFlags (C function)
@anchor{c-api/veryhigh c PyRun_FileFlags}@anchor{51d5}
@deffn {C の関数} @ref{5df,,PyObject} *PyRun_FileFlags (FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)
`戻り値: 新しい参照。'
下記の @ref{51d3,,PyRun_FileExFlags()} の `closeit' を @code{0} にして単純化したインターフェースです。
@end deffn

@geindex PyRun_FileExFlags (C function)
@anchor{c-api/veryhigh c PyRun_FileExFlags}@anchor{51d3}
@deffn {C の関数} @ref{5df,,PyObject} *PyRun_FileExFlags (FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags)
`戻り値: 新しい参照。'
@ref{51d0,,PyRun_StringFlags()} と似ていますが、Pythonソースコードをメモリ内の文字列ではなく `fp' から読み込みます。 `filename' はそのファイルの名前でなければならず、 @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} でデコードされます。 `closeit' に真を指定した場合は、@ref{51d3,,PyRun_FileExFlags()} が処理を戻す前にファイルを閉じます。
@end deffn

@geindex Py_CompileString (C function)
@anchor{c-api/veryhigh c Py_CompileString}@anchor{a85}
@deffn {C の関数} @ref{5df,,PyObject} *Py_CompileString (const char *str, const char *filename, int start)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
下記の @ref{51d6,,Py_CompileStringFlags()} の `flags' を @code{NULL} にして単純化したインターフェースです。
@end deffn

@geindex Py_CompileStringFlags (C function)
@anchor{c-api/veryhigh c Py_CompileStringFlags}@anchor{51d6}
@deffn {C の関数} @ref{5df,,PyObject} *Py_CompileStringFlags (const char *str, const char *filename, int start, PyCompilerFlags *flags)
`戻り値: 新しい参照。'
下記の @ref{51d7,,Py_CompileStringExFlags()} の `optimize' を @code{-1} にして単純化したインターフェースです。
@end deffn

@geindex Py_CompileStringObject (C function)
@anchor{c-api/veryhigh c Py_CompileStringObject}@anchor{51d8}
@deffn {C の関数} @ref{5df,,PyObject} *Py_CompileStringObject (const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize)
`戻り値: 新しい参照。'
Parse and compile the Python source code in `str', returning the resulting code
object.  The start symbol is given by `start'; this can be used to constrain the
code which can be compiled and should be @ref{51d1,,available start symbols}.  The filename specified by
`filename' is used to construct the code object and may appear in tracebacks or
@ref{18e,,SyntaxError} exception messages.  This returns @code{NULL} if the code
cannot be parsed or compiled.

整数 `optimize' は、コンパイラの最適化レベルを指定します;  @code{-1} は、インタプリタの @ref{18c,,-O} オプションで与えられるのと同じ最適化レベルを選びます。明示的なレベルは、 @code{0} (最適化なし、 @code{__debug__} は真)、 @code{1} (assert は取り除かれ、 @code{__debug__} は偽)、 @code{2} (docstring も取り除かれる) です。


Added in version 3.4.

@end deffn

@geindex Py_CompileStringExFlags (C function)
@anchor{c-api/veryhigh c Py_CompileStringExFlags}@anchor{51d7}
@deffn {C の関数} @ref{5df,,PyObject} *Py_CompileStringExFlags (const char *str, const char *filename, int start, PyCompilerFlags *flags, int optimize)
`戻り値: 新しい参照。'
@ref{51d8,,Py_CompileStringObject()} と似ていますが、 `filename' は @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} でデコードされたバイト文字列です。


Added in version 3.2.

@end deffn

@geindex PyEval_EvalCode (C function)
@anchor{c-api/veryhigh c PyEval_EvalCode}@anchor{a86}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_EvalCode (PyObject *co, PyObject *globals, PyObject *locals)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{1ada,,PyEval_EvalCodeEx()} のシンプルなインターフェースで、コードオブジェクトと、グローバル変数とローカル変数だけを受け取ります。
他の引数には @code{NULL} が渡されます。
@end deffn

@geindex PyEval_EvalCodeEx (C function)
@anchor{c-api/veryhigh c PyEval_EvalCodeEx}@anchor{1ada}
@deffn {C の関数} @ref{5df,,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)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた特定の環境で、コンパイル済みのコードオブジェクトを評価します。この環境はグローバル変数の辞書と、ローカル変数のマッピングオブジェクト、引数の配列、キーワードとデフォルト値、@ref{5a5,,キーワード専用} 引数のデフォルト値の辞書と、セルのクロージャタプルで構成されます。
@end deffn

@geindex PyEval_EvalFrame (C function)
@anchor{c-api/veryhigh c PyEval_EvalFrame}@anchor{4fdb}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_EvalFrame (PyFrameObject *f)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
実行フレームを評価します。これは @ref{122f,,PyEval_EvalFrameEx()} に対するシンプルなインターフェースで、後方互換性のためのものです。
@end deffn

@geindex PyEval_EvalFrameEx (C function)
@anchor{c-api/veryhigh c PyEval_EvalFrameEx}@anchor{122f}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_EvalFrameEx (PyFrameObject *f, int throwflag)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Python のインタープリタの主要な、直接的な関数です。実行フレーム `f' に関連付けられたコードオブジェクトを実行します。 バイトコードを解釈して、必要に応じて呼び出しを実行します。 追加の `throwflag' 引数はほとんど無視できます。 - もし true なら、 すぐに例外を発生させます。これはジェネレータオブジェクトの @ref{71c,,throw()} メソッドで利用されます。


バージョン 3.4 で変更: アクティブな例外を黙って捨てないことを保証するのに便利なように、この関数はデバッグアサーションを含むようになりました。

@end deffn

@geindex PyEval_MergeCompilerFlags (C function)
@anchor{c-api/veryhigh c PyEval_MergeCompilerFlags}@anchor{51d9}
@deffn {C の関数} int PyEval_MergeCompilerFlags (PyCompilerFlags *cf)

現在の評価フレームのフラグを変更します。成功したら true を、失敗したら false を返します。
@end deffn

@geindex PyCompilerFlags (C struct)
@anchor{c-api/veryhigh c PyCompilerFlags}@anchor{c98}
@deffn {C Struct} struct PyCompilerFlags

コンパイラフラグを収めておくための構造体です。コードをコンパイルするだけの場合、この構造体が @code{int flags} として渡されます。コードを実行する場合には @code{PyCompilerFlags *flags} として渡されます。この場合、@code{from __future__ import} は `flags' の内容を変更できます。

Whenever @code{PyCompilerFlags *flags} is @code{NULL}, @ref{51da,,cf_flags} is treated as
equal to @code{0}, and any modification due to @code{from __future__ import} is
discarded.

@geindex PyCompilerFlags.cf_flags (C member)
@anchor{c-api/veryhigh c PyCompilerFlags cf_flags}@anchor{51da}
@deffn {C のメンバ変数} int cf_flags

コンパイラフラグ。
@end deffn

@geindex PyCompilerFlags.cf_feature_version (C member)
@anchor{c-api/veryhigh c PyCompilerFlags cf_feature_version}@anchor{51db}
@deffn {C のメンバ変数} int cf_feature_version

`cf_feature_version' is the minor Python version. It should be
initialized to @code{PY_MINOR_VERSION}.

The field is ignored by default, it is used if and only if
@code{PyCF_ONLY_AST} flag is set in @ref{51da,,cf_flags}.
@end deffn


バージョン 3.8 で変更: Added `cf_feature_version' field.


The available compiler flags are accessible as macros:

@geindex PyCF_ALLOW_TOP_LEVEL_AWAIT (C macro)
@geindex PyCF_ONLY_AST (C macro)
@geindex PyCF_OPTIMIZED_AST (C macro)
@geindex PyCF_TYPE_COMMENTS (C macro)
@anchor{c-api/veryhigh c PyCF_ALLOW_TOP_LEVEL_AWAIT}@anchor{51dc}
@deffn {C のマクロ} PyCF_ALLOW_TOP_LEVEL_AWAIT
@anchor{c-api/veryhigh c PyCF_ONLY_AST}@anchor{51dd}
@deffnx {C のマクロ} PyCF_ONLY_AST
@anchor{c-api/veryhigh c PyCF_OPTIMIZED_AST}@anchor{51de}
@deffnx {C のマクロ} PyCF_OPTIMIZED_AST
@anchor{c-api/veryhigh c PyCF_TYPE_COMMENTS}@anchor{51df}
@deffnx {C のマクロ} PyCF_TYPE_COMMENTS

See @ref{25c7,,compiler flags} in documentation of the
@code{ast} Python module, which exports these constants under
the same names.
@end deffn

The "@code{PyCF}" flags above can be combined with "@code{CO_FUTURE}" flags such
as @ref{51e0,,CO_FUTURE_ANNOTATIONS} to enable features normally
selectable using @ref{45d,,future statements}.
See @ref{51e1,,Code Object Flags} for a complete list.
@end deffn

@menu
* Available start symbols:: 
* Stack Effects:: 

@end menu

@node Available start symbols,Stack Effects,,超高水準レイヤ
@anchor{c-api/veryhigh available-start-symbols}@anchor{51e2}@anchor{c-api/veryhigh start-symbols}@anchor{51d1}
@subsection Available start symbols


@geindex Py_eval_input (C var)
@anchor{c-api/veryhigh c Py_eval_input}@anchor{51c1}
@deffn {C 変数} int Py_eval_input

@geindex Py_CompileString (C function)

単独の式に対するPython文法の開始記号で、 @ref{a85,,Py_CompileString()} と一緒に使います。
@end deffn

@geindex Py_file_input (C var)
@anchor{c-api/veryhigh c Py_file_input}@anchor{51c2}
@deffn {C 変数} int Py_file_input

@geindex Py_CompileString (C function)

ファイルあるいは他のソースから読み込まれた文の並びに対するPython文法の開始記号で、 @ref{a85,,Py_CompileString()} と一緒に使います。これは任意の長さのPythonソースコードをコンパイルするときに使う記号です。
@end deffn

@geindex Py_single_input (C var)
@anchor{c-api/veryhigh c Py_single_input}@anchor{51c3}
@deffn {C 変数} int Py_single_input

@geindex Py_CompileString (C function)

単一の文に対するPython文法の開始記号で、 @ref{a85,,Py_CompileString()} と一緒に使います。これは対話式のインタプリタループのための記号です。
@end deffn

@geindex Py_func_type_input (C var)
@anchor{c-api/veryhigh c Py_func_type_input}@anchor{51c4}
@deffn {C 変数} int Py_func_type_input

@geindex Py_CompileString (C function)

The start symbol from the Python grammar for a function type; for use with
@ref{a85,,Py_CompileString()}. This is used to parse "signature type comments"
from 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/}.

This requires the @ref{51dd,,PyCF_ONLY_AST} flag to be set.


@subsubheading 参考



@itemize *

@item 
@ref{4b7e,,ast.FunctionType}

@item 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/}
@end itemize



Added in version 3.8.

@end deffn

@node Stack Effects,,Available start symbols,超高水準レイヤ
@anchor{c-api/veryhigh stack-effects}@anchor{51e3}
@subsection Stack Effects



@subsubheading 参考


@ref{1132,,dis.stack_effect()}


@geindex PY_INVALID_STACK_EFFECT (C macro)
@anchor{c-api/veryhigh c PY_INVALID_STACK_EFFECT}@anchor{51e4}
@deffn {C のマクロ} PY_INVALID_STACK_EFFECT

Sentinel value representing an invalid stack effect.

This is currently equivalent to @code{INT_MAX}.


Added in version 3.8.

@end deffn

@geindex PyCompile_OpcodeStackEffect (C function)
@anchor{c-api/veryhigh c PyCompile_OpcodeStackEffect}@anchor{51e5}
@deffn {C の関数} int PyCompile_OpcodeStackEffect (int opcode, int oparg)

`opcode' と引数 `oparg' がスタックに与える影響を計算します。

On success, this function returns the stack effect; on failure, this
returns @ref{51e4,,PY_INVALID_STACK_EFFECT}.


Added in version 3.4.

@end deffn

@geindex PyCompile_OpcodeStackEffectWithJump (C function)
@anchor{c-api/veryhigh c PyCompile_OpcodeStackEffectWithJump}@anchor{1e32}
@deffn {C の関数} int PyCompile_OpcodeStackEffectWithJump (int opcode, int oparg, int jump)

Similar to @ref{51e5,,PyCompile_OpcodeStackEffect()}, but don't include the
stack effect of jumping if `jump' is zero.

If `jump' is @code{0}, this will not include the stack effect of jumping, but
if `jump' is @code{1} or @code{-1}, this will include it.

On success, this function returns the stack effect; on failure, this
returns @ref{51e4,,PY_INVALID_STACK_EFFECT}.


Added in version 3.8.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 参照カウント,例外処理,超高水準レイヤ,Python/C API リファレンスマニュアル
@anchor{c-api/refcounting doc}@anchor{51e6}@anchor{c-api/refcounting countingrefs}@anchor{51e7}@anchor{c-api/refcounting reference-counting}@anchor{51e8}@anchor{c-api/refcounting translation-repo}@anchor{51e9}
@section 参照カウント


このセクションにある関数とマクロは、 Python オブジェクトの参照カウントの管理に使用されます。

@geindex Py_REFCNT (C function)
@anchor{c-api/refcounting c Py_REFCNT}@anchor{2cf}
@deffn {C の関数} @ref{c55,,Py_ssize_t} Py_REFCNT (PyObject *o)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Python オブジェクト `o' の参照カウントを取得します。

戻り値は、実際に保持されているオブジェクトの参照の数を実際に反映しているとは限らないことに注意してください。例えば、一部のオブジェクトは永続 (@ref{290,,immortal}) であり、実際の参照の数を反映しない非常に高い参照数を持ちます。したがって、 0 か 1 の値以外では、正確な戻り値に頼らないでください。

オブジェクトの参照カウントを設定するためには、 @ref{aa8,,Py_SET_REFCNT()} 関数を使用してください。

@cartouche
@quotation 注釈 
On @ref{176d,,free-threaded builds} of Python, returning 1
isn't sufficient to determine if it's safe to treat `o' as having no
access by other threads. Use @ref{3c6,,PyUnstable_Object_IsUniquelyReferenced()}
for that instead.

See also the function @ref{3c7,,PyUnstable_Object_IsUniqueReferencedTemporary()}.
@end quotation
@end cartouche


バージョン 3.10 で変更: @ref{2cf,,Py_REFCNT()} は static なインライン関数に変更されました。



バージョン 3.11 で変更: 引数の型は const @ref{5df,,PyObject}* ではなくなりました。

@end deffn

@geindex Py_SET_REFCNT (C function)
@anchor{c-api/refcounting c Py_SET_REFCNT}@anchor{aa8}
@deffn {C の関数} void Py_SET_REFCNT (PyObject *o, Py_ssize_t refcnt)

オブジェクト `o' の参照カウントを `refcnt' に設定します。

@ref{216e,,フリースレッドな Python ビルド} では、 `refcnt' が @code{UINT32_MAX} より大きい場合、オブジェクトは永続 (@ref{290,,immortal}) となります。

この関数は永続 (@ref{290,,immortal}) オブジェクトには何もしません。


Added in version 3.9.



バージョン 3.12 で変更: 永続オブジェクトは変更されません。

@end deffn

@geindex Py_INCREF (C function)
@anchor{c-api/refcounting c Py_INCREF}@anchor{78f}
@deffn {C の関数} void Py_INCREF (PyObject *o)

オブジェクト `o' への新しい @ref{5e2,,強参照} を取得し、それが使用中で破棄されてはならないことを示します。

この関数は永続 (@ref{290,,immortal}) オブジェクトには何もしません。

This function is usually used to convert a @ref{3d7,,borrowed reference} to a
@ref{5e2,,strong reference} in-place. The @ref{a9a,,Py_NewRef()} function can be
used to create a new @ref{5e2,,strong reference}.

When done using the object, release is by calling @ref{790,,Py_DECREF()}.

オブジェクトが @code{NULL} であってはいけません。それが @code{NULL} ではないと確信が持てないならば、 @ref{c5a,,Py_XINCREF()} を使ってください。

Do not expect this function to actually modify `o' in any way.
For at least 
@geindex Python Enhancement Proposals; PEP 0683
some objects@footnote{https://peps.python.org/pep-0683/},
this function has no effect.


バージョン 3.12 で変更: 永続オブジェクトは変更されません。

@end deffn

@geindex Py_XINCREF (C function)
@anchor{c-api/refcounting c Py_XINCREF}@anchor{c5a}
@deffn {C の関数} void Py_XINCREF (PyObject *o)

Similar to @ref{78f,,Py_INCREF()}, but the object `o' can be @code{NULL},
in which case this has no effect.

See also @ref{a9b,,Py_XNewRef()}.
@end deffn

@geindex Py_NewRef (C function)
@anchor{c-api/refcounting c Py_NewRef}@anchor{a9a}
@deffn {C の関数} @ref{5df,,PyObject} *Py_NewRef (PyObject *o)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Create a new @ref{5e2,,strong reference} to an object:
call @ref{78f,,Py_INCREF()} on `o' and return the object `o'.

When the @ref{5e2,,strong reference} is no longer needed, @ref{790,,Py_DECREF()}
should be called on it to release the reference.

The object `o' must not be @code{NULL}; use @ref{a9b,,Py_XNewRef()} if `o' can be
@code{NULL}.

例えば:

@example
Py_INCREF(obj);
self->attr = obj;
@end example

can be written as:

@example
self->attr = Py_NewRef(obj);
@end example

See also @ref{78f,,Py_INCREF()}.


Added in version 3.10.

@end deffn

@geindex Py_XNewRef (C function)
@anchor{c-api/refcounting c Py_XNewRef}@anchor{a9b}
@deffn {C の関数} @ref{5df,,PyObject} *Py_XNewRef (PyObject *o)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Similar to @ref{a9a,,Py_NewRef()}, but the object `o' can be NULL.

If the object `o' is @code{NULL}, the function just returns @code{NULL}.


Added in version 3.10.

@end deffn

@geindex Py_DECREF (C function)
@anchor{c-api/refcounting c Py_DECREF}@anchor{790}
@deffn {C の関数} void Py_DECREF (PyObject *o)

Release a @ref{5e2,,strong reference} to object `o', indicating the
reference is no longer used.

この関数は永続 (@ref{290,,immortal}) オブジェクトには何もしません。

Once the last @ref{5e2,,strong reference} is released
(i.e. the object's reference count reaches 0),
the object's type's deallocation
function (which must not be @code{NULL}) is invoked.

This function is usually used to delete a @ref{5e2,,strong reference} before
exiting its scope.

オブジェクトが @code{NULL} であってはいけません。それが @code{NULL} ではないと確信が持てないならば、 @ref{992,,Py_XDECREF()} を使ってください。

Do not expect this function to actually modify `o' in any way.
For at least 
@geindex Python Enhancement Proposals; PEP 683
some objects@footnote{https://peps.python.org/pep-0683/},
this function has no effect.

@cartouche
@quotation 警告 
The deallocation function can cause arbitrary Python code to be invoked (e.g.
when a class instance with a @ref{11ff,,__del__()} method is deallocated).  While
exceptions in such code are not propagated, the executed code has free access to
all Python global variables.  This means that any object that is reachable from
a global variable should be in a consistent state before @ref{790,,Py_DECREF()} is
invoked.  For example, code to delete an object from a list should copy a
reference to the deleted object in a temporary variable, update the list data
structure, and then call @ref{790,,Py_DECREF()} for the temporary variable.
@end quotation
@end cartouche


バージョン 3.12 で変更: 永続オブジェクトは変更されません。

@end deffn

@geindex Py_XDECREF (C function)
@anchor{c-api/refcounting c Py_XDECREF}@anchor{992}
@deffn {C の関数} void Py_XDECREF (PyObject *o)

Similar to @ref{790,,Py_DECREF()}, but the object `o' can be @code{NULL},
in which case this has no effect.
The same warning from @ref{790,,Py_DECREF()} applies here as well.
@end deffn

@geindex Py_CLEAR (C function)
@anchor{c-api/refcounting c Py_CLEAR}@anchor{798}
@deffn {C の関数} void Py_CLEAR (PyObject *o)

Release a @ref{5e2,,strong reference} for object `o'.
The object may be @code{NULL}, in
which case the macro has no effect; otherwise the effect is the same as for
@ref{790,,Py_DECREF()}, except that the argument is also set to @code{NULL}.  The warning
for @ref{790,,Py_DECREF()} does not apply with respect to the object passed because
the macro carefully uses a temporary variable and sets the argument to @code{NULL}
before releasing the reference.

It is a good idea to use this macro whenever releasing a reference
to an object that might be traversed during garbage collection.


バージョン 3.12 で変更: The macro argument is now only evaluated once. If the argument has side
effects, these are no longer duplicated.

@end deffn

@geindex Py_IncRef (C function)
@anchor{c-api/refcounting c Py_IncRef}@anchor{5132}
@deffn {C の関数} void Py_IncRef (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
Indicate taking a new @ref{5e2,,strong reference} to object `o'.
A function version of @ref{c5a,,Py_XINCREF()}.
It can be used for runtime dynamic embedding of Python.
@end deffn

@geindex Py_DecRef (C function)
@anchor{c-api/refcounting c Py_DecRef}@anchor{512a}
@deffn {C の関数} void Py_DecRef (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
Release a @ref{5e2,,strong reference} to object `o'.
A function version of @ref{992,,Py_XDECREF()}.
It can be used for runtime dynamic embedding of Python.
@end deffn

@geindex Py_SETREF (C macro)
@anchor{c-api/refcounting c Py_SETREF}@anchor{799}
@deffn {C のマクロ} Py_SETREF (dst, src)

Macro safely releasing a @ref{5e2,,strong reference} to object `dst'
and setting `dst' to `src'.

As in case of @ref{798,,Py_CLEAR()}, "the obvious" code can be deadly:

@example
Py_DECREF(dst);
dst = src;
@end example

The safe way is:

@example
Py_SETREF(dst, src);
@end example

That arranges to set `dst' to `src' `before' releasing the reference
to the old value of `dst', so that any code triggered as a side-effect
of `dst' getting torn down no longer believes `dst' points
to a valid object.


Added in version 3.6.



バージョン 3.12 で変更: The macro arguments are now only evaluated once. If an argument has side
effects, these are no longer duplicated.

@end deffn

@geindex Py_XSETREF (C macro)
@anchor{c-api/refcounting c Py_XSETREF}@anchor{79a}
@deffn {C のマクロ} Py_XSETREF (dst, src)

Variant of @ref{799,,Py_SETREF} macro that uses @ref{992,,Py_XDECREF()} instead
of @ref{790,,Py_DECREF()}.


Added in version 3.6.



バージョン 3.12 で変更: The macro arguments are now only evaluated once. If an argument has side
effects, these are no longer duplicated.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 例外処理,拡張モジュールの定義,参照カウント,Python/C API リファレンスマニュアル
@anchor{c-api/exceptions doc}@anchor{51ea}@anchor{c-api/exceptions exception-handling}@anchor{51eb}@anchor{c-api/exceptions exceptionhandling}@anchor{4988}@anchor{c-api/exceptions translation-repo}@anchor{51ec}
@section 例外処理


この章で説明する関数を使うと、 Python の例外の処理や例外の送出ができるようになります。 Python の例外処理の基本をいくらか理解することが大切です。例外は POSIX @code{errno} 変数にやや似た機能を果たします: 発生した中で最も新しいエラーの (スレッド毎の) グローバルなインジケータがあります。実行に成功した場合にはほとんどの C API 関数がこれをクリアしませんが、失敗したときにはエラーの原因を示すために設定します。ほとんどの C API 関数はエラーインジケータも返し、通常は関数がポインタを返すことになっている場合は @code{NULL} であり、関数が整数を返す場合は @code{-1} です。(例外: @code{PyArg_*} 関数は実行に成功したときに @code{1} を返し、失敗したときに @code{0} を返します).

具体的には、エラーインジケータは、例外の型、例外の値、トレースバックオブジェクトの３つのオブジェクトポインタで構成されます。これらのポインタはどれでも、設定されない場合は @code{NULL} になりえます（ただし、いくつかの組み合わせは禁止されており、例えば、例外の型が @code{NULL} の場合は、トレースバックは非 @code{NULL} の値になりません）

ある関数が呼び出した関数がいくつか失敗したために、その関数が失敗しなければならないとき、一般的にエラーインジケータを設定しません。呼び出した関数がすでに設定しています。エラーを処理して例外をクリアするか、あるいは (オブジェクト参照またはメモリ割り当てのような)それが持つどんなリソースも取り除いた後に戻るかのどちらか一方を行う責任があります。エラーを処理する準備をしていなければ、普通に続けるべきでは `ありません'。エラーのために戻る場合は、エラーが設定されていると呼び出し元に知らせることが大切です。エラーが処理されていない場合または丁寧に伝えられている場合には、Python/C APIのさらなる呼び出しは意図した通りには動かない可能性があり、不可解な形で失敗するかもしれません。

@cartouche
@quotation 注釈 
The error indicator is `not' the result of @ref{89a,,sys.exc_info()}.
The former corresponds to an exception that is not yet caught (and is
therefore still propagating), while the latter returns an exception after
it is caught (and has therefore stopped propagating).
@end quotation
@end cartouche

@menu
* 出力とクリア:: 
* 例外の送出:: 
* 警告: 警告<3>. 
* エラーインジケータの問い合わせ:: 
* シグナルハンドリング: シグナルハンドリング<2>. 
* 例外クラス: 例外クラス<2>. 
* 例外オブジェクト:: 
* Unicode 例外オブジェクト:: 
* 再帰の管理:: 
* Exception and warning types:: 
* Tracebacks:: 

@end menu

@node 出力とクリア,例外の送出,,例外処理
@anchor{c-api/exceptions printing-and-clearing}@anchor{51ed}
@subsection 出力とクリア


@geindex PyErr_Clear (C function)
@anchor{c-api/exceptions c PyErr_Clear}@anchor{1232}
@deffn {C の関数} void PyErr_Clear ()
` 次に属します: @ref{775,,Stable ABI}.'
エラーインジケータをクリアします。エラーインジケータが設定されていないならば、効果はありません。
@end deffn

@geindex PyErr_PrintEx (C function)
@anchor{c-api/exceptions c PyErr_PrintEx}@anchor{4fce}
@deffn {C の関数} void PyErr_PrintEx (int set_sys_last_vars)
` 次に属します: @ref{775,,Stable ABI}.'
標準のトレースバックを @code{sys.stderr} に出力し、エラーインジケータをクリアします。
ただし、エラーが @code{SystemExit} `である場合を除いて' です。
その場合、トレースバックは出力されず、 Python プロセスは @code{SystemExit} インスタンスで指定されたエラーコードで終了します。

エラーインジケータが設定されているときに `だけ'、この関数を呼び出してください。
それ以外の場合、致命的なエラーを引き起こすでしょう!

If `set_sys_last_vars' is nonzero, the variable @ref{6e5,,sys.last_exc} is
set to the printed exception. For backwards compatibility, the
deprecated variables @ref{6e6,,sys.last_type}, @ref{6e7,,sys.last_value} and
@ref{6e8,,sys.last_traceback} are also set to the type, value and traceback
of this exception, respectively.


バージョン 3.12 で変更: The setting of @ref{6e5,,sys.last_exc} was added.

@end deffn

@geindex PyErr_Print (C function)
@anchor{c-api/exceptions c PyErr_Print}@anchor{1d2c}
@deffn {C の関数} void PyErr_Print ()
` 次に属します: @ref{775,,Stable ABI}.'
@code{PyErr_PrintEx(1)} のエイリアスです。
@end deffn

@geindex PyErr_WriteUnraisable (C function)
@anchor{c-api/exceptions c PyErr_WriteUnraisable}@anchor{5f2}
@deffn {C の関数} void PyErr_WriteUnraisable (PyObject *obj)
` 次に属します: @ref{775,,Stable ABI}.'
現在の例外と `obj' 引数で @ref{507,,sys.unraisablehook()} を呼び出します。

This utility function prints a warning message to @code{sys.stderr} when an
exception has been set but it is impossible for the interpreter to actually
raise the exception.  It is used, for example, when an exception occurs in an
@ref{11ff,,__del__()} method.

The function is called with a single argument `obj' that identifies the context
in which the unraisable exception occurred. If possible,
the repr of `obj' will be printed in the warning message.
If `obj' is @code{NULL}, only the traceback is printed.

この関数を呼び出すときには、例外がセットされていなければなりません。


バージョン 3.4 で変更: Print a traceback. Print only traceback if `obj' is @code{NULL}.



バージョン 3.8 で変更: Use @ref{507,,sys.unraisablehook()}.

@end deffn

@geindex PyErr_FormatUnraisable (C function)
@anchor{c-api/exceptions c PyErr_FormatUnraisable}@anchor{5f1}
@deffn {C の関数} void PyErr_FormatUnraisable (const char *format, ...)

Similar to @ref{5f2,,PyErr_WriteUnraisable()}, but the `format' and subsequent
parameters help format the warning message; they have the same meaning and
values as in @ref{62b,,PyUnicode_FromFormat()}.
@code{PyErr_WriteUnraisable(obj)} is roughly equivalent to
@code{PyErr_FormatUnraisable("Exception ignored in: %R", obj)}.
If `format' is @code{NULL}, only the traceback is printed.


Added in version 3.13.

@end deffn

@geindex PyErr_DisplayException (C function)
@anchor{c-api/exceptions c PyErr_DisplayException}@anchor{435}
@deffn {C の関数} void PyErr_DisplayException (PyObject *exc)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Print the standard traceback display of @code{exc} to @code{sys.stderr}, including
chained exceptions and notes.


Added in version 3.12.

@end deffn

@node 例外の送出,警告<3>,出力とクリア,例外処理
@anchor{c-api/exceptions raising-exceptions}@anchor{51ee}
@subsection 例外の送出


以下の関数は、現在のスレッドのエラーインジケータの設定を補助します。利便性のため、これらの関数のいくつかは、 @code{return} 文で利用できるように常に @code{NULL} ポインタを返します。

@geindex PyErr_SetString (C function)
@anchor{c-api/exceptions c PyErr_SetString}@anchor{79c}
@deffn {C の関数} void PyErr_SetString (PyObject *type, const char *message)
` 次に属します: @ref{775,,Stable ABI}.'
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. @ref{500c,,PyExc_RuntimeError}.  You need not create a new
@ref{5e2,,strong reference} to it (e.g. with @ref{78f,,Py_INCREF()}).
The second argument is an error message; it is decoded from @code{'utf-8'}.
@end deffn

@geindex PyErr_SetObject (C function)
@anchor{c-api/exceptions c PyErr_SetObject}@anchor{79b}
@deffn {C の関数} void PyErr_SetObject (PyObject *type, PyObject *value)
` 次に属します: @ref{775,,Stable ABI}.'
この関数は @ref{79c,,PyErr_SetString()} に似ていますが、例外の "値(value)" として任意のPythonオブジェクトを指定することができます。
@end deffn

@geindex PyErr_Format (C function)
@anchor{c-api/exceptions c PyErr_Format}@anchor{10b1}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_Format (PyObject *exception, const char *format, ...)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI}.'
この関数はエラーインジケータを設定し @code{NULL} を返します。 `exception' はPython例外クラスであるべきです。 `format' と以降の引数はエラーメッセージを作るためのもので, @ref{62b,,PyUnicode_FromFormat()} の引数と同じ意味を持っています。 `format' は ASCII エンコードされた文字列です。
@end deffn

@geindex PyErr_FormatV (C function)
@anchor{c-api/exceptions c PyErr_FormatV}@anchor{10b0}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_FormatV (PyObject *exception, const char *format, va_list vargs)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.5 より).'
@ref{10b1,,PyErr_Format()} と同じですが、可変長引数の代わりに @code{va_list} 引数を受け取ります。


Added in version 3.5.

@end deffn

@geindex PyErr_SetNone (C function)
@anchor{c-api/exceptions c PyErr_SetNone}@anchor{4fd7}
@deffn {C の関数} void PyErr_SetNone (PyObject *type)
` 次に属します: @ref{775,,Stable ABI}.'
これは @code{PyErr_SetObject(type, Py_None)} を省略したものです。
@end deffn

@geindex PyErr_BadArgument (C function)
@anchor{c-api/exceptions c PyErr_BadArgument}@anchor{4fcb}
@deffn {C の関数} int PyErr_BadArgument ()
` 次に属します: @ref{775,,Stable ABI}.'
これは @code{PyErr_SetString(PyExc_TypeError, message)} を省略したもので、ここで `message' は組み込み操作が不正な引数で呼び出されたということを表しています。主に内部で使用するためのものです。
@end deffn

@geindex PyErr_NoMemory (C function)
@anchor{c-api/exceptions c PyErr_NoMemory}@anchor{4e99}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_NoMemory ()
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI}.'
これは @code{PyErr_SetNone(PyExc_MemoryError)} を省略したもので、@code{NULL} を返します。したがって、メモリ不足になったとき、オブジェクト割り当て関数は @code{return PyErr_NoMemory();} と書くことができます。
@end deffn

@geindex PyErr_SetFromErrno (C function)
@anchor{c-api/exceptions c PyErr_SetFromErrno}@anchor{4e98}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetFromErrno (PyObject *type)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex strerror (C function)

This is a convenience function to raise an exception when a C library function
has returned an error and set the C variable @code{errno}.  It constructs a
tuple object whose first item is the integer @code{errno} value and whose
second item is the corresponding error message (gotten from @code{strerror()}),
and then calls @code{PyErr_SetObject(type, object)}.  On Unix, when the
@code{errno} value is @code{EINTR}, indicating an interrupted system call,
this calls @ref{693,,PyErr_CheckSignals()}, and if that set the error indicator,
leaves it set to that.  The function always returns @code{NULL}, so a wrapper
function around a system call can write @code{return PyErr_SetFromErrno(type);}
when the system call returns an error.
@end deffn

@geindex PyErr_SetFromErrnoWithFilenameObject (C function)
@anchor{c-api/exceptions c PyErr_SetFromErrnoWithFilenameObject}@anchor{4fd3}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetFromErrnoWithFilenameObject (PyObject *type, PyObject *filenameObject)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI}.'
Similar to @ref{4e98,,PyErr_SetFromErrno()}, with the additional behavior that if
`filenameObject' is not @code{NULL}, it is passed to the constructor of `type' as
a third parameter.  In the case of @ref{2c0,,OSError} exception,
this is used to define the @code{filename} attribute of the
exception instance.
@end deffn

@geindex PyErr_SetFromErrnoWithFilenameObjects (C function)
@anchor{c-api/exceptions c PyErr_SetFromErrnoWithFilenameObjects}@anchor{4fd4}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetFromErrnoWithFilenameObjects (PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@ref{4fd3,,PyErr_SetFromErrnoWithFilenameObject()} に似てますが、ファイル名を2つ取る関数が失敗したときに例外を送出するために、2つ目のファイル名オブジェクトを受け取ります。


Added in version 3.4.

@end deffn

@geindex PyErr_SetFromErrnoWithFilename (C function)
@anchor{c-api/exceptions c PyErr_SetFromErrnoWithFilename}@anchor{1a85}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetFromErrnoWithFilename (PyObject *type, const char *filename)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{4fd3,,PyErr_SetFromErrnoWithFilenameObject()} に似ていますが、ファイル名は C 文字列として与えられます。
`filename' は @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} でデコードされます。
@end deffn

@geindex PyErr_SetFromWindowsErr (C function)
@anchor{c-api/exceptions c PyErr_SetFromWindowsErr}@anchor{4fd5}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetFromWindowsErr (int ierr)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
This is a convenience function to raise @ref{2c0,,OSError}. If called with
`ierr' of @code{0}, the error code returned by a call to @code{GetLastError()}
is used instead.  It calls the Win32 function @code{FormatMessage()} to retrieve
the Windows description of error code given by `ierr' or @code{GetLastError()},
then it constructs a @ref{2c0,,OSError} object with the @ref{26ef,,winerror}
attribute set to the error code, the @ref{26f0,,strerror} attribute
set to the corresponding error message (gotten from
@code{FormatMessage()}), and then calls @code{PyErr_SetObject(PyExc_OSError,
object)}. This function always returns @code{NULL}.

@ref{213f,,Availability}: Windows.
@end deffn

@geindex PyErr_SetExcFromWindowsErr (C function)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErr}@anchor{4fd0}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetExcFromWindowsErr (PyObject *type, int ierr)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
@ref{4fd5,,PyErr_SetFromWindowsErr()} に似ていますが、送出する例外の型を指定する引数が追加されています。

@ref{213f,,Availability}: Windows.
@end deffn

@geindex PyErr_SetFromWindowsErrWithFilename (C function)
@anchor{c-api/exceptions c PyErr_SetFromWindowsErrWithFilename}@anchor{1a87}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetFromWindowsErrWithFilename (int ierr, const char *filename)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
Similar to @ref{4fd5,,PyErr_SetFromWindowsErr()}, with the additional behavior
that if `filename' is not @code{NULL}, it is decoded from the filesystem
encoding (@ref{e4e,,os.fsdecode()}) and passed to the constructor of
@ref{2c0,,OSError} as a third parameter to be used to define the
@code{filename} attribute of the exception instance.

@ref{213f,,Availability}: Windows.
@end deffn

@geindex PyErr_SetExcFromWindowsErrWithFilenameObject (C function)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObject}@anchor{4fd1}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetExcFromWindowsErrWithFilenameObject (PyObject *type, int ierr, PyObject *filename)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
Similar to @ref{4fd0,,PyErr_SetExcFromWindowsErr()}, with the additional behavior
that if `filename' is not @code{NULL}, it is passed to the constructor of
@ref{2c0,,OSError} as a third parameter to be used to define the
@code{filename} attribute of the exception instance.

@ref{213f,,Availability}: Windows.
@end deffn

@geindex PyErr_SetExcFromWindowsErrWithFilenameObjects (C function)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObjects}@anchor{4fd2}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetExcFromWindowsErrWithFilenameObjects (PyObject *type, int ierr, PyObject *filename, PyObject *filename2)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
@ref{4fd1,,PyErr_SetExcFromWindowsErrWithFilenameObject()} に似てますが、2つ目のファイル名オブジェクトを受け取ります。

@ref{213f,,Availability}: Windows.


Added in version 3.4.

@end deffn

@geindex PyErr_SetExcFromWindowsErrWithFilename (C function)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilename}@anchor{1a86}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetExcFromWindowsErrWithFilename (PyObject *type, int ierr, const char *filename)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
@ref{1a87,,PyErr_SetFromWindowsErrWithFilename()} に似ていますが、送出する例外の型を指定する引数が追加されています。

@ref{213f,,Availability}: Windows.
@end deffn

@geindex PyErr_SetImportError (C function)
@anchor{c-api/exceptions c PyErr_SetImportError}@anchor{f39}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetImportError (PyObject *msg, PyObject *name, PyObject *path)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@ref{65b,,ImportError} を簡単に送出するための関数です。 `msg' は例外のメッセージ文字列としてセットされます。 `name' と `path' はどちらも @code{NULL} にしてよく、それぞれ @ref{65b,,ImportError} の @code{name} 属性と @code{path} 属性としてセットされます。


Added in version 3.3.

@end deffn

@geindex PyErr_SetImportErrorSubclass (C function)
@anchor{c-api/exceptions c PyErr_SetImportErrorSubclass}@anchor{f12}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_SetImportErrorSubclass (PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.6 より).'
@ref{f39,,PyErr_SetImportError()} とよく似ていますが、この関数は送出する例外として、 @ref{65b,,ImportError} のサブクラスを指定できます。


Added in version 3.6.

@end deffn

@geindex PyErr_SyntaxLocationObject (C function)
@anchor{c-api/exceptions c PyErr_SyntaxLocationObject}@anchor{51ef}
@deffn {C の関数} void PyErr_SyntaxLocationObject (PyObject *filename, int lineno, int col_offset)

現在の例外のファイル、行、オフセットの情報をセットします。
現在の例外が @ref{18e,,SyntaxError} でない場合は、例外を表示するサブシステムが、例外が @ref{18e,,SyntaxError} であると思えるように属性を追加します。


Added in version 3.4.

@end deffn

@geindex PyErr_RangedSyntaxLocationObject (C function)
@anchor{c-api/exceptions c PyErr_RangedSyntaxLocationObject}@anchor{51f0}
@deffn {C の関数} void PyErr_RangedSyntaxLocationObject (PyObject *filename, int lineno, int col_offset, int end_lineno, int end_col_offset)

Similar to @ref{51ef,,PyErr_SyntaxLocationObject()}, but also sets the
`end_lineno' and `end_col_offset' information for the current exception.


Added in version 3.10.

@end deffn

@geindex PyErr_SyntaxLocationEx (C function)
@anchor{c-api/exceptions c PyErr_SyntaxLocationEx}@anchor{4fd9}
@deffn {C の関数} void PyErr_SyntaxLocationEx (const char *filename, int lineno, int col_offset)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@ref{51ef,,PyErr_SyntaxLocationObject()} と似ていますが、 `filename' は @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} でデコードされたバイト文字列です。


Added in version 3.2.

@end deffn

@geindex PyErr_SyntaxLocation (C function)
@anchor{c-api/exceptions c PyErr_SyntaxLocation}@anchor{4fd8}
@deffn {C の関数} void PyErr_SyntaxLocation (const char *filename, int lineno)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{4fd9,,PyErr_SyntaxLocationEx()} と似ていますが、 `col_offset' 引数が除去されています。
@end deffn

@geindex PyErr_BadInternalCall (C function)
@anchor{c-api/exceptions c PyErr_BadInternalCall}@anchor{4fcc}
@deffn {C の関数} void PyErr_BadInternalCall ()
` 次に属します: @ref{775,,Stable ABI}.'
@code{PyErr_SetString(PyExc_SystemError, message)} を省略したものです。ここで `message' は内部操作(例えば、Python/C API関数)が不正な引数とともに呼び出されたということを示しています。主に内部で使用するためのものです。
@end deffn

@geindex PyErr_ProgramTextObject (C function)
@anchor{c-api/exceptions c PyErr_ProgramTextObject}@anchor{51f1}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_ProgramTextObject (PyObject *filename, int lineno)

Get the source line in `filename' at line `lineno'. `filename' should be a
Python @ref{169,,str} object.

On success, this function returns a Python string object with the found line.
On failure, this function returns @code{NULL} without an exception set.
@end deffn

@geindex PyErr_ProgramText (C function)
@anchor{c-api/exceptions c PyErr_ProgramText}@anchor{4fcf}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_ProgramText (const char *filename, int lineno)
` 次に属します: @ref{775,,Stable ABI}.'
Similar to @ref{51f1,,PyErr_ProgramTextObject()}, but `filename' is a
const char*, which is decoded with the
@ref{75d,,filesystem encoding and error handler}, instead of a
Python object reference.
@end deffn

@node 警告<3>,エラーインジケータの問い合わせ,例外の送出,例外処理
@anchor{c-api/exceptions issuing-warnings}@anchor{51f2}
@subsection 警告


以下の関数を使い、 C コードで起きた警告を報告します。
Python の @ref{118,,warnings} モジュールで公開されている同様の関数とよく似てます。
これらの関数は通常警告メッセージを `sys.stderr' へ出力しますが、ユーザが警告をエラーへ変更するように指定することもでき、その場合は、関数は例外を送出します。
警告機構がもつ問題のためにその関数が例外を送出するということも有り得ます。
例外が送出されない場合は戻り値は @code{0} で、例外が送出された場合は @code{-1} です。
(警告メッセージが実際に出力されるか、およびその例外の原因が何かについては判断できません; これは意図的なものです。)
例外が送出された場合、呼び出し元は通常の例外処理を行います (例えば、保持していた参照に対し @ref{790,,Py_DECREF()} を行い、エラー値を返します)。

@geindex PyErr_WarnEx (C function)
@anchor{c-api/exceptions c PyErr_WarnEx}@anchor{1665}
@deffn {C の関数} int PyErr_WarnEx (PyObject *category, const char *message, Py_ssize_t stack_level)
` 次に属します: @ref{775,,Stable ABI}.'
警告メッセージを発行します。 `category' 引数は警告カテゴリ(以下を参照) かまたは @code{NULL} で、 `message' 引数は UTF-8 エンコードされた文字列です。 `stacklevel' はスタックフレームの数を示す正の整数です; 警告はそのスタックフレームの中の実行している行から発行されます。 `stacklevel' が 1 だと @ref{1665,,PyErr_WarnEx()} を呼び出している関数が、2 だとその上の関数が Warning の発行元になります。

警告カテゴリは @ref{501d,,PyExc_Warning} のサブクラスでなければなりません。 @ref{501d,,PyExc_Warning} は @ref{4ff1,,PyExc_Exception} のサブクラスです。
デフォルトの警告カテゴリは @ref{500d,,PyExc_RuntimeWarning} です。
標準の Python 警告カテゴリは、 @ref{51f3,,Warning types} で名前が列挙されているグローバル変数として利用可能です。

警告をコントロールするための情報については、 @ref{118,,warnings} モジュールのドキュメンテーションとコマンドライン・ドキュメンテーションの @ref{ac6,,-W} オプションを参照してください。警告コントロールのためのC APIはありません。
@end deffn

@geindex PyErr_WarnExplicitObject (C function)
@anchor{c-api/exceptions c PyErr_WarnExplicitObject}@anchor{51f4}
@deffn {C の関数} int PyErr_WarnExplicitObject (PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)

すべての警告の属性を明示的に制御した警告メッセージを出します。これは Python 関数 @ref{efd,,warnings.warn_explicit()} の直接的なラッパーで、さらに情報を得るにはそちらを参照してください。そこに説明されているデフォルトの効果を得るために、 `module' と `registry' 引数は @code{NULL} に設定することができます。


Added in version 3.4.

@end deffn

@geindex PyErr_WarnExplicit (C function)
@anchor{c-api/exceptions c PyErr_WarnExplicit}@anchor{1a8d}
@deffn {C の関数} int PyErr_WarnExplicit (PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{51f4,,PyErr_WarnExplicitObject()} に似ていますが、 `message' と `module' が UTF-8 エンコードされた文字列であるところが異なり、 `filename' は @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} でデコードされます。
@end deffn

@geindex PyErr_WarnFormat (C function)
@anchor{c-api/exceptions c PyErr_WarnFormat}@anchor{4fda}
@deffn {C の関数} int PyErr_WarnFormat (PyObject *category, Py_ssize_t stack_level, const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{1665,,PyErr_WarnEx()} に似たような関数ですが、警告メッセージをフォーマットするのに @ref{62b,,PyUnicode_FromFormat()} を使用します。 `format' は ASCII にエンコードされた文字列です。


Added in version 3.2.

@end deffn

@geindex PyErr_WarnExplicitFormat (C function)
@anchor{c-api/exceptions c PyErr_WarnExplicitFormat}@anchor{51f5}
@deffn {C の関数} int PyErr_WarnExplicitFormat (PyObject *category, const char *filename, int lineno, const char *module, PyObject *registry, const char *format, ...)

Similar to @ref{1a8d,,PyErr_WarnExplicit()}, but uses
@ref{62b,,PyUnicode_FromFormat()} to format the warning message. `format' is
an ASCII-encoded string.


Added in version 3.2.

@end deffn

@geindex PyErr_ResourceWarning (C function)
@anchor{c-api/exceptions c PyErr_ResourceWarning}@anchor{f13}
@deffn {C の関数} int PyErr_ResourceWarning (PyObject *source, Py_ssize_t stack_level, const char *format, ...)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.6 より).'
Function similar to @ref{4fda,,PyErr_WarnFormat()}, but `category' is
@ref{54c,,ResourceWarning} and it passes `source' to @code{warnings.WarningMessage}.


Added in version 3.6.

@end deffn

@node エラーインジケータの問い合わせ,シグナルハンドリング<2>,警告<3>,例外処理
@anchor{c-api/exceptions querying-the-error-indicator}@anchor{51f6}
@subsection エラーインジケータの問い合わせ


@geindex PyErr_Occurred (C function)
@anchor{c-api/exceptions c PyErr_Occurred}@anchor{1caf}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_Occurred ()
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
エラーインジケータが設定されているかテストします。設定されている場合は、例外の `型' (@code{PyErr_Set*} 関数の一つあるいは @ref{42b,,PyErr_Restore()} への最も新しい呼び出しに対する第一引数)を返します。設定されていない場合は @code{NULL} を返します。あなたは戻り値への参照を持っていませんので、それに @ref{790,,Py_DECREF()} する必要はありません。

The caller must have an @ref{4ed1,,attached thread state}.

@cartouche
@quotation 注釈 
戻り値を特定の例外と比較しないでください。その代わりに、下に示す @ref{4f4e,,PyErr_ExceptionMatches()} を使ってください。(比較は簡単に失敗するでしょう。なぜなら、例外はクラスではなくインスタンスかもしれないし、あるいは、クラス例外の場合は期待される例外のサブクラスかもしれないからです。)
@end quotation
@end cartouche
@end deffn

@geindex PyErr_ExceptionMatches (C function)
@anchor{c-api/exceptions c PyErr_ExceptionMatches}@anchor{4f4e}
@deffn {C の関数} int PyErr_ExceptionMatches (PyObject *exc)
` 次に属します: @ref{775,,Stable ABI}.'
@code{PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)} と同じ。例外が実際に設定されたときにだけ、これを呼び出だすべきです。例外が発生していないならば、メモリアクセス違反が起きるでしょう。
@end deffn

@geindex PyErr_GivenExceptionMatches (C function)
@anchor{c-api/exceptions c PyErr_GivenExceptionMatches}@anchor{4fcd}
@deffn {C の関数} int PyErr_GivenExceptionMatches (PyObject *given, PyObject *exc)
` 次に属します: @ref{775,,Stable ABI}.'
例外 `given' が `exc' の例外型と適合する場合に真を返します。
`exc' がクラスオブジェクトである場合も、 `given' がサブクラスのインスタンスであるときに真を返します。
`exc' がタプルの場合は、タプルにある (およびそのサブタプルに再帰的にある) すべての例外型が適合するか調べられます。
@end deffn

@geindex PyErr_GetRaisedException (C function)
@anchor{c-api/exceptions c PyErr_GetRaisedException}@anchor{429}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_GetRaisedException (void)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
現在発生している例外を返し、同時にエラーインジケータを消去します。エラーインジケータが設定されていない場合は @code{NULL} を返します。

この関数は、例外をキャッチする必要があるコード、または一時的にエラーインジケータを保存・復元する必要があるコードに使用されます。

例えば:

@example
@{
   PyObject *exc = PyErr_GetRaisedException();

   /* ... 他のエラーを発生させる可能性があるコード ... */

   PyErr_SetRaisedException(exc);
@}
@end example


@subsubheading 参考


@ref{973,,PyErr_GetHandledException()},
to save the exception currently being handled.



Added in version 3.12.

@end deffn

@geindex PyErr_SetRaisedException (C function)
@anchor{c-api/exceptions c PyErr_SetRaisedException}@anchor{42c}
@deffn {C の関数} void PyErr_SetRaisedException (PyObject *exc)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Set `exc' as the exception currently being raised,
clearing the existing exception if one is set.

@cartouche
@quotation 警告 
This call steals a reference to `exc', which must be a valid exception.
@end quotation
@end cartouche


Added in version 3.12.

@end deffn

@geindex PyErr_Fetch (C function)
@anchor{c-api/exceptions c PyErr_Fetch}@anchor{428}
@deffn {C の関数} void PyErr_Fetch (PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
` 次に属します: @ref{775,,Stable ABI}.'

バージョン 3.12 で非推奨: Use @ref{429,,PyErr_GetRaisedException()} instead.


エラーインジケータをアドレスを渡す三つの変数の中へ取り出します。エラーインジケータが設定されていない場合は、三つすべての変数を @code{NULL} に設定します。エラーインジケータが設定されている場合はクリアされ、あなたは取り出されたそれぞれのオブジェクトへの参照を持つことになります。型オブジェクトが @code{NULL} でないときでさえ、その値とトレースバックオブジェクトは @code{NULL} かもしれません。

@cartouche
@quotation 注釈 
This function is normally only used by legacy code that needs to catch
exceptions or save and restore the error indicator temporarily.

例えば:

@example
@{
   PyObject *type, *value, *traceback;
   PyErr_Fetch(&type, &value, &traceback);

   /* ... code that might produce other errors ... */

   PyErr_Restore(type, value, traceback);
@}
@end example
@end quotation
@end cartouche
@end deffn

@geindex PyErr_Restore (C function)
@anchor{c-api/exceptions c PyErr_Restore}@anchor{42b}
@deffn {C の関数} void PyErr_Restore (PyObject *type, PyObject *value, PyObject *traceback)
` 次に属します: @ref{775,,Stable ABI}.'

バージョン 3.12 で非推奨: Use @ref{42c,,PyErr_SetRaisedException()} instead.


Set the error indicator from the three objects,
`type', `value', and `traceback',
clearing the existing exception if one is set.
If the objects are @code{NULL}, the error
indicator is cleared.  Do not pass a @code{NULL} type and non-@code{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.)

@cartouche
@quotation 注釈 
This function is normally only used by legacy code that needs to
save and restore the error indicator temporarily.
Use @ref{428,,PyErr_Fetch()} to save the current error indicator.
@end quotation
@end cartouche
@end deffn

@geindex PyErr_NormalizeException (C function)
@anchor{c-api/exceptions c PyErr_NormalizeException}@anchor{42a}
@deffn {C の関数} void PyErr_NormalizeException (PyObject **exc, PyObject **val, PyObject **tb)
` 次に属します: @ref{775,,Stable ABI}.'

バージョン 3.12 で非推奨: Use @ref{429,,PyErr_GetRaisedException()} instead,
to avoid any possible de-normalization.


ある状況では、以下の @ref{428,,PyErr_Fetch()} が返す値は "正規化されていない" 可能性があります。つまり、 @code{*exc} はクラスオブジェクトだが @code{*val} は同じクラスのインスタンスではないという意味です。この関数はそのような場合にそのクラスをインスタンス化するために使われます。その値がすでに正規化されている場合は何も起きません。遅延正規化はパフォーマンスを改善するために実装されています。

@cartouche
@quotation 注釈 
This function `does not' implicitly set the
@ref{14de,,__traceback__}
attribute on the exception value. If setting the traceback
appropriately is desired, the following additional snippet is needed:

@example
if (tb != NULL) @{
  PyException_SetTraceback(val, tb);
@}
@end example
@end quotation
@end cartouche
@end deffn

@geindex PyErr_GetHandledException (C function)
@anchor{c-api/exceptions c PyErr_GetHandledException}@anchor{973}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_GetHandledException (void)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Retrieve the active exception instance, as would be returned by @ref{89b,,sys.exception()}.
This refers to an exception that was `already caught', not to an exception that was
freshly raised. Returns a new reference to the exception or @code{NULL}.
Does not modify the interpreter's exception state.

@cartouche
@quotation 注釈 
この関数は、通常は例外を扱うコードでは使用されません。正確に言うと、これは例外の状態を一時的に保存し、元に戻す必要があるコードで使用することができます。例外の状態を元に戻す、もしくはクリアするには @ref{974,,PyErr_SetHandledException()} を使ってください。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex PyErr_SetHandledException (C function)
@anchor{c-api/exceptions c PyErr_SetHandledException}@anchor{974}
@deffn {C の関数} void PyErr_SetHandledException (PyObject *exc)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Set the active exception, as known from @code{sys.exception()}.  This refers
to an exception that was `already caught', not to an exception that was
freshly raised.
To clear the exception state, pass @code{NULL}.

@cartouche
@quotation 注釈 
この関数は、通常は例外を扱うコードでは使用されません。正確に言うと、これは例外の状態を一時的に保存し、元に戻す必要があるコードで使用することができます。例外の状態を取得するには @ref{973,,PyErr_GetHandledException()} を使ってください。
@end quotation
@end cartouche


Added in version 3.11.

@end deffn

@geindex PyErr_GetExcInfo (C function)
@anchor{c-api/exceptions c PyErr_GetExcInfo}@anchor{976}
@deffn {C の関数} void PyErr_GetExcInfo (PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Retrieve the old-style representation of the exception info, as known from
@ref{89a,,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 @code{NULL}.  Does not modify the exception
info state.  This function is kept for backwards compatibility. Prefer using
@ref{973,,PyErr_GetHandledException()}.

@cartouche
@quotation 注釈 
この関数は、通常は例外を扱うコードでは使用されません。正確に言うと、これは例外の状態を一時的に保存し、元に戻す必要があるコードで使用することができます。例外の状態を元に戻す、もしくはクリアするには @ref{975,,PyErr_SetExcInfo()} を使ってください。
@end quotation
@end cartouche


Added in version 3.3.

@end deffn

@geindex PyErr_SetExcInfo (C function)
@anchor{c-api/exceptions c PyErr_SetExcInfo}@anchor{975}
@deffn {C の関数} void PyErr_SetExcInfo (PyObject *type, PyObject *value, PyObject *traceback)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Set the exception info, as known from @code{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 @code{NULL} for all three arguments.
This function is kept for backwards compatibility. Prefer using
@ref{974,,PyErr_SetHandledException()}.

@cartouche
@quotation 注釈 
この関数は、通常は例外を扱うコードでは使用されません。正確に言うと、これは例外の状態を一時的に保存し、元に戻す必要があるコードで使用することができます。例外の状態を取得するには @ref{976,,PyErr_GetExcInfo()} を使ってください。
@end quotation
@end cartouche


Added in version 3.3.



バージョン 3.11 で変更: The @code{type} and @code{traceback} arguments are no longer used and
can be NULL. The interpreter now derives them from the exception
instance (the @code{value} argument). The function still steals
references of all three arguments.

@end deffn

@node シグナルハンドリング<2>,例外クラス<2>,エラーインジケータの問い合わせ,例外処理
@anchor{c-api/exceptions signal-handling}@anchor{51f7}
@subsection シグナルハンドリング


@geindex PyErr_CheckSignals (C function)
@anchor{c-api/exceptions c PyErr_CheckSignals}@anchor{693}
@deffn {C の関数} int PyErr_CheckSignals ()
` 次に属します: @ref{775,,Stable ABI}.'
@geindex module;signal
@geindex SIGINT (C macro)
@geindex KeyboardInterrupt (組み込み例外)

This function interacts with Python's signal handling.

If the function is called from the main thread and under the main Python
interpreter, it checks whether a signal has been sent to the processes
and if so, invokes the corresponding signal handler.  If the @ref{cb,,signal}
module is supported, this can invoke a signal handler written in Python.

The function attempts to handle all pending signals, and then returns @code{0}.
However, if a Python signal handler raises an exception, the error
indicator is set and the function returns @code{-1} immediately (such that
other pending signals may not have been handled yet: they will be on the
next @ref{693,,PyErr_CheckSignals()} invocation).

If the function is called from a non-main thread, or under a non-main
Python interpreter, it does nothing and returns @code{0}.

This function can be called by long-running C code that wants to
be interruptible by user requests (such as by pressing Ctrl-C).

@cartouche
@quotation 注釈 
The default Python signal handler for @code{SIGINT} raises the
@ref{bc5,,KeyboardInterrupt} exception.
@end quotation
@end cartouche
@end deffn

@geindex PyErr_SetInterrupt (C function)
@anchor{c-api/exceptions c PyErr_SetInterrupt}@anchor{4fd6}
@deffn {C の関数} void PyErr_SetInterrupt ()
` 次に属します: @ref{775,,Stable ABI}.'
@geindex module;signal
@geindex SIGINT (C macro)
@geindex KeyboardInterrupt (組み込み例外)

Simulate the effect of a @code{SIGINT} signal arriving.
This is equivalent to @code{PyErr_SetInterruptEx(SIGINT)}.

@cartouche
@quotation 注釈 
This function is async-signal-safe.  It can be called without
an @ref{4ed1,,attached thread state} and from a C signal handler.
@end quotation
@end cartouche
@end deffn

@geindex PyErr_SetInterruptEx (C function)
@anchor{c-api/exceptions c PyErr_SetInterruptEx}@anchor{a9e}
@deffn {C の関数} int PyErr_SetInterruptEx (int signum)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
@geindex module;signal
@geindex KeyboardInterrupt (組み込み例外)

シグナルが到達した効果をシミュレートします。
次に @ref{693,,PyErr_CheckSignals()} が呼ばれたとき、与えられたシグナル番号用の Python のシグナルハンドラが呼び出されます。

This function can be called by C code that sets up its own signal handling
and wants Python signal handlers to be invoked as expected when an
interruption is requested (for example when the user presses Ctrl-C
to interrupt an operation).

If the given signal isn't handled by Python (it was set to
@ref{1bb2,,signal.SIG_DFL} or @ref{1bb1,,signal.SIG_IGN}), it will be ignored.

If `signum' is outside of the allowed range of signal numbers, @code{-1}
is returned.  Otherwise, @code{0} is returned.  The error indicator is
never changed by this function.

@cartouche
@quotation 注釈 
This function is async-signal-safe.  It can be called without
an @ref{4ed1,,attached thread state} and from a C signal handler.
@end quotation
@end cartouche


Added in version 3.10.

@end deffn

@geindex PySignal_SetWakeupFd (C function)
@anchor{c-api/exceptions c PySignal_SetWakeupFd}@anchor{15f4}
@deffn {C の関数} int PySignal_SetWakeupFd (int fd)

このユーティリティ関数は、シグナルを受け取ったときにシグナル番号をバイトとして書き込むファイル記述子を指定します。
`fd' はノンブロッキングでなければなりません。
この関数は、1つ前のファイル記述子を返します。

値 @code{-1} を渡すと、この機能を無効にします; これが初期状態です。
この関数は Python の @ref{d67,,signal.set_wakeup_fd()} と同等ですが、どんなエラーチェックも行いません。
`fd' は有効なファイル記述子であるべきです。
この関数はメインスレッドからのみ呼び出されるべきです。


バージョン 3.5 で変更: Windowsで、この関数はソケットハンドルをサポートするようになりました。

@end deffn

@node 例外クラス<2>,例外オブジェクト,シグナルハンドリング<2>,例外処理
@anchor{c-api/exceptions exception-classes}@anchor{51f8}
@subsection 例外クラス


@geindex PyErr_NewException (C function)
@anchor{c-api/exceptions c PyErr_NewException}@anchor{1481}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_NewException (const char *name, PyObject *base, PyObject *dict)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
このユーティリティ関数は新しい例外クラスを作成して返します。 `name' 引数は新しい例外の名前、 @code{module.classname} 形式の C文字列でなければならない。 `base' と `dict' 引数は通常 @code{NULL} です。これはすべての例外のためのルート、組み込み名 @ref{bcd,,Exception} (Cでは @ref{4ff1,,PyExc_Exception} としてアクセス可能)をルートとして派生したクラスオブジェクトを作成します。

The @ref{617,,__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.
@end deffn

@geindex PyErr_NewExceptionWithDoc (C function)
@anchor{c-api/exceptions c PyErr_NewExceptionWithDoc}@anchor{1480}
@deffn {C の関数} @ref{5df,,PyObject} *PyErr_NewExceptionWithDoc (const char *name, const char *doc, PyObject *base, PyObject *dict)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{1481,,PyErr_NewException()} とほぼ同じですが、新しい例外クラスに簡単に docstring を設定できます。 `doc' が @code{NULL} で無い場合、それが例外クラスの docstring になります。


Added in version 3.2.

@end deffn

@geindex PyExceptionClass_Check (C function)
@anchor{c-api/exceptions c PyExceptionClass_Check}@anchor{51f9}
@deffn {C の関数} int PyExceptionClass_Check (PyObject *ob)

Return non-zero if `ob' is an exception class, zero otherwise. This function always succeeds.
@end deffn

@geindex PyExceptionClass_Name (C function)
@anchor{c-api/exceptions c PyExceptionClass_Name}@anchor{c5b}
@deffn {C の関数} const char *PyExceptionClass_Name (PyObject *ob)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
Return @ref{1cb0,,tp_name} of the exception class `ob'.
@end deffn

@node 例外オブジェクト,Unicode 例外オブジェクト,例外クラス<2>,例外処理
@anchor{c-api/exceptions exception-objects}@anchor{51fa}
@subsection 例外オブジェクト


@geindex PyExceptionInstance_Check (C function)
@anchor{c-api/exceptions c PyExceptionInstance_Check}@anchor{51fb}
@deffn {C の関数} int PyExceptionInstance_Check (PyObject *op)

Return true if `op' is an instance of @ref{7d6,,BaseException}, false
otherwise. This function always succeeds.
@end deffn

@geindex PyExceptionInstance_Class (C macro)
@anchor{c-api/exceptions c PyExceptionInstance_Class}@anchor{51fc}
@deffn {C のマクロ} PyExceptionInstance_Class (op)

Equivalent to @ref{3c9,,Py_TYPE(op)}.
@end deffn

@geindex PyException_GetTraceback (C function)
@anchor{c-api/exceptions c PyException_GetTraceback}@anchor{5021}
@deffn {C の関数} @ref{5df,,PyObject} *PyException_GetTraceback (PyObject *ex)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Python で @ref{14de,,__traceback__} 属性からアクセスできるものと同じ、例外に関する traceback の新しい参照を返します。関係する traceback が無い場合は、 @code{NULL} を返します。
@end deffn

@geindex PyException_SetTraceback (C function)
@anchor{c-api/exceptions c PyException_SetTraceback}@anchor{1dce}
@deffn {C の関数} int PyException_SetTraceback (PyObject *ex, PyObject *tb)
` 次に属します: @ref{775,,Stable ABI}.'
その例外に関する traceback に `tb' をセットします。クリアするには @code{Py_None} を使用してください。
@end deffn

@geindex PyException_GetContext (C function)
@anchor{c-api/exceptions c PyException_GetContext}@anchor{5020}
@deffn {C の関数} @ref{5df,,PyObject} *PyException_GetContext (PyObject *ex)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
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 the @ref{14df,,__context__} attribute.
If there is no context associated, this returns @code{NULL}.
@end deffn

@geindex PyException_SetContext (C function)
@anchor{c-api/exceptions c PyException_SetContext}@anchor{5023}
@deffn {C の関数} void PyException_SetContext (PyObject *ex, PyObject *ctx)
` 次に属します: @ref{775,,Stable ABI}.'
例外に関するコンテキストに `ctx' をセットします。クリアするには @code{NULL} を使用してください。`ctx' が例外インスタンスかどうかを確かめる型チェックは行われません。これは `ctx' への参照を盗みます。
@end deffn

@geindex PyException_GetCause (C function)
@anchor{c-api/exceptions c PyException_GetCause}@anchor{501f}
@deffn {C の関数} @ref{5df,,PyObject} *PyException_GetCause (PyObject *ex)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return the cause (either an exception instance, or @code{None},
set by @code{raise ... from ...}) associated with the exception as a new
reference, as accessible from Python through the
@ref{14e0,,__cause__} attribute.
@end deffn

@geindex PyException_SetCause (C function)
@anchor{c-api/exceptions c PyException_SetCause}@anchor{5022}
@deffn {C の関数} void PyException_SetCause (PyObject *ex, PyObject *cause)
` 次に属します: @ref{775,,Stable ABI}.'
Set the cause associated with the exception to `cause'.  Use @code{NULL} to clear
it.  There is no type check to make sure that `cause' is either an exception
instance or @code{None}.  This steals a reference to `cause'.

The @ref{2514,,__suppress_context__} attribute is implicitly set
to @code{True} by this function.
@end deffn

@geindex PyException_GetArgs (C function)
@anchor{c-api/exceptions c PyException_GetArgs}@anchor{78b}
@deffn {C の関数} @ref{5df,,PyObject} *PyException_GetArgs (PyObject *ex)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Return @ref{78d,,args} of exception `ex'.
@end deffn

@geindex PyException_SetArgs (C function)
@anchor{c-api/exceptions c PyException_SetArgs}@anchor{78c}
@deffn {C の関数} void PyException_SetArgs (PyObject *ex, PyObject *args)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Set @ref{78d,,args} of exception `ex' to `args'.
@end deffn

@geindex PyUnstable_Exc_PrepReraiseStar (C function)
@anchor{c-api/exceptions c PyUnstable_Exc_PrepReraiseStar}@anchor{51fd}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnstable_Exc_PrepReraiseStar (PyObject *orig, PyObject *excs)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Implement part of the interpreter's implementation of @code{except*}.
`orig' is the original exception that was caught, and `excs' is the list of
the exceptions that need to be raised. This list contains the unhandled
part of `orig', if any, as well as the exceptions that were raised from the
@code{except*} clauses (so they have a different traceback from `orig') and
those that were reraised (and have the same traceback as `orig').
Return the @ref{4d2,,ExceptionGroup} that needs to be reraised in the end, or
@code{None} if there is nothing to reraise.


Added in version 3.12.

@end deffn

@node Unicode 例外オブジェクト,再帰の管理,例外オブジェクト,例外処理
@anchor{c-api/exceptions unicode-exception-objects}@anchor{51fe}@anchor{c-api/exceptions unicodeexceptions}@anchor{461}
@subsection Unicode 例外オブジェクト


以下の関数は C言語から Unicode 例外を作ったり修正したりするために利用します。

@geindex PyUnicodeDecodeError_Create (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_Create}@anchor{50dd}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicodeDecodeError_Create (const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`encoding', `object', `length', `start', `end', `reason' 属性をもった @ref{c08,,UnicodeDecodeError} オブジェクトを作成します。 `encoding' および `reason' は UTF-8 エンコードされた文字列です。
@end deffn

@geindex PyUnicodeDecodeError_GetEncoding (C function)
@geindex PyUnicodeEncodeError_GetEncoding (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetEncoding}@anchor{50de}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicodeDecodeError_GetEncoding (PyObject *exc)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetEncoding}@anchor{50e6}
@deffnx {C の関数} @ref{5df,,PyObject} *PyUnicodeEncodeError_GetEncoding (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた例外オブジェクトの `encoding' 属性を返します。
@end deffn

@geindex PyUnicodeDecodeError_GetObject (C function)
@geindex PyUnicodeEncodeError_GetObject (C function)
@geindex PyUnicodeTranslateError_GetObject (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetObject}@anchor{50e0}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicodeDecodeError_GetObject (PyObject *exc)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetObject}@anchor{50e7}
@deffnx {C の関数} @ref{5df,,PyObject} *PyUnicodeEncodeError_GetObject (PyObject *exc)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetObject}@anchor{50ee}
@deffnx {C の関数} @ref{5df,,PyObject} *PyUnicodeTranslateError_GetObject (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた例外オブジェクトの `object' 属性を返します。
@end deffn

@geindex PyUnicodeDecodeError_GetStart (C function)
@geindex PyUnicodeEncodeError_GetStart (C function)
@geindex PyUnicodeTranslateError_GetStart (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetStart}@anchor{50e2}
@deffn {C の関数} int PyUnicodeDecodeError_GetStart (PyObject *exc, Py_ssize_t *start)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetStart}@anchor{18fe}
@deffnx {C の関数} int PyUnicodeEncodeError_GetStart (PyObject *exc, Py_ssize_t *start)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetStart}@anchor{50f0}
@deffnx {C の関数} int PyUnicodeTranslateError_GetStart (PyObject *exc, Py_ssize_t *start)
` 次に属します: @ref{775,,Stable ABI}.'
渡された例外オブジェクトから `start' 属性を取得して `*start' に格納します。`start' は @code{NULL} であってはなりません。成功したら @code{0} を、失敗したら @code{-1} を返します。

If the @ref{18fc,,UnicodeError.object} is an empty sequence, the resulting
`start' is @code{0}. Otherwise, it is clipped to @code{[0, len(object) - 1]}.


@subsubheading 参考


@ref{18c0,,UnicodeError.start}

@end deffn

@geindex PyUnicodeDecodeError_SetStart (C function)
@geindex PyUnicodeEncodeError_SetStart (C function)
@geindex PyUnicodeTranslateError_SetStart (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_SetStart}@anchor{50e5}
@deffn {C の関数} int PyUnicodeDecodeError_SetStart (PyObject *exc, Py_ssize_t start)
@anchor{c-api/exceptions c PyUnicodeEncodeError_SetStart}@anchor{50eb}
@deffnx {C の関数} int PyUnicodeEncodeError_SetStart (PyObject *exc, Py_ssize_t start)
@anchor{c-api/exceptions c PyUnicodeTranslateError_SetStart}@anchor{50f3}
@deffnx {C の関数} int PyUnicodeTranslateError_SetStart (PyObject *exc, Py_ssize_t start)
` 次に属します: @ref{775,,Stable ABI}.'
Set the `start' attribute of the given exception object to `start'.
Return @code{0} on success, @code{-1} on failure.

@cartouche
@quotation 注釈 
While passing a negative `start' does not raise an exception,
the corresponding getters will not consider it as a relative
offset.
@end quotation
@end cartouche
@end deffn

@geindex PyUnicodeDecodeError_GetEnd (C function)
@geindex PyUnicodeEncodeError_GetEnd (C function)
@geindex PyUnicodeTranslateError_GetEnd (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetEnd}@anchor{50df}
@deffn {C の関数} int PyUnicodeDecodeError_GetEnd (PyObject *exc, Py_ssize_t *end)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetEnd}@anchor{18fb}
@deffnx {C の関数} int PyUnicodeEncodeError_GetEnd (PyObject *exc, Py_ssize_t *end)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetEnd}@anchor{50ed}
@deffnx {C の関数} int PyUnicodeTranslateError_GetEnd (PyObject *exc, Py_ssize_t *end)
` 次に属します: @ref{775,,Stable ABI}.'
渡された例外オブジェクトから `end' 属性を取得して `*end' に格納します。`end' は @code{NULL} であってはなりません。成功したら @code{0} を、失敗したら @code{-1} を返します。

If the @ref{18fc,,UnicodeError.object} is an empty sequence, the resulting
`end' is @code{0}. Otherwise, it is clipped to @code{[1, len(object)]}.
@end deffn

@geindex PyUnicodeDecodeError_SetEnd (C function)
@geindex PyUnicodeEncodeError_SetEnd (C function)
@geindex PyUnicodeTranslateError_SetEnd (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_SetEnd}@anchor{50e3}
@deffn {C の関数} int PyUnicodeDecodeError_SetEnd (PyObject *exc, Py_ssize_t end)
@anchor{c-api/exceptions c PyUnicodeEncodeError_SetEnd}@anchor{50e9}
@deffnx {C の関数} int PyUnicodeEncodeError_SetEnd (PyObject *exc, Py_ssize_t end)
@anchor{c-api/exceptions c PyUnicodeTranslateError_SetEnd}@anchor{50f1}
@deffnx {C の関数} int PyUnicodeTranslateError_SetEnd (PyObject *exc, Py_ssize_t end)
` 次に属します: @ref{775,,Stable ABI}.'
渡された例外オブジェクトの `end' 属性を `end' に設定します。成功したら @code{0} を、失敗したら @code{-1} を返します。


@subsubheading 参考


@ref{18c1,,UnicodeError.end}

@end deffn

@geindex PyUnicodeDecodeError_GetReason (C function)
@geindex PyUnicodeEncodeError_GetReason (C function)
@geindex PyUnicodeTranslateError_GetReason (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetReason}@anchor{50e1}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicodeDecodeError_GetReason (PyObject *exc)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetReason}@anchor{50e8}
@deffnx {C の関数} @ref{5df,,PyObject} *PyUnicodeEncodeError_GetReason (PyObject *exc)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetReason}@anchor{50ef}
@deffnx {C の関数} @ref{5df,,PyObject} *PyUnicodeTranslateError_GetReason (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
渡された例外オブジェクトの `reason' 属性を返します。
@end deffn

@geindex PyUnicodeDecodeError_SetReason (C function)
@geindex PyUnicodeEncodeError_SetReason (C function)
@geindex PyUnicodeTranslateError_SetReason (C function)
@anchor{c-api/exceptions c PyUnicodeDecodeError_SetReason}@anchor{50e4}
@deffn {C の関数} int PyUnicodeDecodeError_SetReason (PyObject *exc, const char *reason)
@anchor{c-api/exceptions c PyUnicodeEncodeError_SetReason}@anchor{50ea}
@deffnx {C の関数} int PyUnicodeEncodeError_SetReason (PyObject *exc, const char *reason)
@anchor{c-api/exceptions c PyUnicodeTranslateError_SetReason}@anchor{50f2}
@deffnx {C の関数} int PyUnicodeTranslateError_SetReason (PyObject *exc, const char *reason)
` 次に属します: @ref{775,,Stable ABI}.'
渡された例外オブジェクトの `reason' 属性を `reason' に設定します。成功したら @code{0} を、失敗したら @code{-1} を返します。
@end deffn

@node 再帰の管理,Exception and warning types,Unicode 例外オブジェクト,例外処理
@anchor{c-api/exceptions recursion}@anchor{51ff}@anchor{c-api/exceptions recursion-control}@anchor{5200}
@subsection 再帰の管理


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 @ref{7a3,,call protocol} takes care of recursion handling.

@geindex Py_EnterRecursiveCall (C function)
@anchor{c-api/exceptions c Py_EnterRecursiveCall}@anchor{3d2}
@deffn {C の関数} int Py_EnterRecursiveCall (const char *where)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
C レベルの再帰呼び出しをしようとしているところに印を付けます。

The function then checks if the stack limit is reached.  If this is the
case, a @ref{f68,,RecursionError} is set and a nonzero value is returned.
Otherwise, zero is returned.

`where' は @code{" in instance check"} のような UTF-8 エンコードされた文字列にして、再帰の深さの限界に達したことで送出される @ref{f68,,RecursionError} のメッセージに連結できるようにすべきです。


@subsubheading 参考


The @ref{466,,PyUnstable_ThreadState_SetStackProtection()} function.



バージョン 3.9 で変更: This function is now also available in the @ref{637,,limited API}.

@end deffn

@geindex Py_LeaveRecursiveCall (C function)
@anchor{c-api/exceptions c Py_LeaveRecursiveCall}@anchor{b6b}
@deffn {C の関数} void Py_LeaveRecursiveCall (void)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
@ref{3d2,,Py_EnterRecursiveCall()} を終了させます。 @ref{3d2,,Py_EnterRecursiveCall()} の `成功した' 呼び出しに対し 1 回呼ばなければなりません。


バージョン 3.9 で変更: This function is now also available in the @ref{637,,limited API}.

@end deffn

コンテナ型に対し @ref{4ee4,,tp_repr} を適切に実装するには、特殊な再帰の処理が求められます。スタックの防護に加え、 @ref{4ee4,,tp_repr} は循環処理を避けるためにオブジェクトを辿っていく必要があります。次の 2 つの関数はその機能を容易にします。実質的には、これらは @ref{140c,,reprlib.recursive_repr()} と同等な C の実装です。

@geindex Py_ReprEnter (C function)
@anchor{c-api/exceptions c Py_ReprEnter}@anchor{5135}
@deffn {C の関数} int Py_ReprEnter (PyObject *object)
` 次に属します: @ref{775,,Stable ABI}.'
循環処理を検知するために、 @ref{4ee4,,tp_repr} の実装の先頭で呼び出します。

そのオブジェクトが既に処理されたものだった場合、この関数は正の整数を返します。その場合、 @ref{4ee4,,tp_repr} の実装は、循環を示す文字列オブジェクトを返すべきです。例えば、 @ref{183,,dict} オブジェクトは @code{@{...@}} を返しますし、  @ref{24d,,list} オブジェクトは @code{[...]} を返します。

再帰回数の上限に達した場合は、この関数は負の整数を返します。この場合、 @ref{4ee4,,tp_repr} の実装は一般的には @code{NULL} を返すべきです。

それ以外の場合は、関数はゼロを返し、 @ref{4ee4,,tp_repr} の実装は通常どおり処理を続けてかまいません。
@end deffn

@geindex Py_ReprLeave (C function)
@anchor{c-api/exceptions c Py_ReprLeave}@anchor{5136}
@deffn {C の関数} void Py_ReprLeave (PyObject *object)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{5135,,Py_ReprEnter()} を終了させます。 0 を返した @ref{5135,,Py_ReprEnter()} の呼び出しに対し 1 回呼ばなければなりません。
@end deffn

@geindex Py_GetRecursionLimit (C function)
@anchor{c-api/exceptions c Py_GetRecursionLimit}@anchor{5130}
@deffn {C の関数} int Py_GetRecursionLimit (void)
` 次に属します: @ref{775,,Stable ABI}.'
Get the recursion limit for the current interpreter. It can be set with
@ref{5137,,Py_SetRecursionLimit()}. The recursion limit prevents the
Python interpreter stack from growing infinitely.

This function cannot fail, and the caller must hold an
@ref{4ed1,,attached thread state}.


@subsubheading 参考


@ref{6eb,,sys.getrecursionlimit()}

@end deffn

@geindex Py_SetRecursionLimit (C function)
@anchor{c-api/exceptions c Py_SetRecursionLimit}@anchor{5137}
@deffn {C の関数} void Py_SetRecursionLimit (int new_limit)
` 次に属します: @ref{775,,Stable ABI}.'
Set the recursion limit for the current interpreter.

This function cannot fail, and the caller must hold an
@ref{4ed1,,attached thread state}.


@subsubheading 参考


@ref{6ea,,sys.setrecursionlimit()}

@end deffn

@node Exception and warning types,Tracebacks,再帰の管理,例外処理
@anchor{c-api/exceptions exception-and-warning-types}@anchor{5201}@anchor{c-api/exceptions standardexceptions}@anchor{5202}
@subsection Exception and warning types


All standard Python exceptions and warning categories are available as global
variables whose names are @code{PyExc_} followed by the Python exception name.
These have the type @ref{5df,,PyObject}*; they are all class objects.

For completeness, here are all the variables:

@menu
* Exception types:: 
* OSError aliases:: 
* Warning types:: 

@end menu

@node Exception types,OSError aliases,,Exception and warning types
@anchor{c-api/exceptions exception-types}@anchor{5203}
@subsubsection Exception types



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

C name

@tab

Python name

@item

@geindex PyExc_BaseException (C var)
@anchor{c-api/exceptions c PyExc_BaseException}@anchor{4fe2}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_BaseException
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{7d6,,BaseException}

@item

@geindex PyExc_BaseExceptionGroup (C var)
@anchor{c-api/exceptions c PyExc_BaseExceptionGroup}@anchor{4fe3}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_BaseExceptionGroup
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

@ref{566,,BaseExceptionGroup}

@item

@geindex PyExc_Exception (C var)
@anchor{c-api/exceptions c PyExc_Exception}@anchor{4ff1}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_Exception
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{bcd,,Exception}

@item

@geindex PyExc_ArithmeticError (C var)
@anchor{c-api/exceptions c PyExc_ArithmeticError}@anchor{4fdf}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ArithmeticError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{26e5,,ArithmeticError}

@item

@geindex PyExc_AssertionError (C var)
@anchor{c-api/exceptions c PyExc_AssertionError}@anchor{4fe0}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_AssertionError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{8b8,,AssertionError}

@item

@geindex PyExc_AttributeError (C var)
@anchor{c-api/exceptions c PyExc_AttributeError}@anchor{4fe1}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_AttributeError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{5f0,,AttributeError}

@item

@geindex PyExc_BlockingIOError (C var)
@anchor{c-api/exceptions c PyExc_BlockingIOError}@anchor{4fe4}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_BlockingIOError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{235,,BlockingIOError}

@item

@geindex PyExc_BrokenPipeError (C var)
@anchor{c-api/exceptions c PyExc_BrokenPipeError}@anchor{4fe5}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_BrokenPipeError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1267,,BrokenPipeError}

@item

@geindex PyExc_BufferError (C var)
@anchor{c-api/exceptions c PyExc_BufferError}@anchor{4fe6}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_BufferError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{1797,,BufferError}

@item

@geindex PyExc_ChildProcessError (C var)
@anchor{c-api/exceptions c PyExc_ChildProcessError}@anchor{4fe8}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ChildProcessError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1263,,ChildProcessError}

@item

@geindex PyExc_ConnectionAbortedError (C var)
@anchor{c-api/exceptions c PyExc_ConnectionAbortedError}@anchor{4fe9}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ConnectionAbortedError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1268,,ConnectionAbortedError}

@item

@geindex PyExc_ConnectionError (C var)
@anchor{c-api/exceptions c PyExc_ConnectionError}@anchor{4fea}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ConnectionError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{100b,,ConnectionError}

@item

@geindex PyExc_ConnectionRefusedError (C var)
@anchor{c-api/exceptions c PyExc_ConnectionRefusedError}@anchor{4feb}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ConnectionRefusedError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1269,,ConnectionRefusedError}

@item

@geindex PyExc_ConnectionResetError (C var)
@anchor{c-api/exceptions c PyExc_ConnectionResetError}@anchor{4fec}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ConnectionResetError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{126a,,ConnectionResetError}

@item

@geindex PyExc_EOFError (C var)
@anchor{c-api/exceptions c PyExc_EOFError}@anchor{4fee}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_EOFError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{14f1,,EOFError}

@item

@geindex PyExc_FileExistsError (C var)
@anchor{c-api/exceptions c PyExc_FileExistsError}@anchor{4ff2}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_FileExistsError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1221,,FileExistsError}

@item

@geindex PyExc_FileNotFoundError (C var)
@anchor{c-api/exceptions c PyExc_FileNotFoundError}@anchor{4ff3}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_FileNotFoundError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{264,,FileNotFoundError}

@item

@geindex PyExc_FloatingPointError (C var)
@anchor{c-api/exceptions c PyExc_FloatingPointError}@anchor{4ff4}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_FloatingPointError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{26e6,,FloatingPointError}

@item

@geindex PyExc_GeneratorExit (C var)
@anchor{c-api/exceptions c PyExc_GeneratorExit}@anchor{4ff6}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_GeneratorExit
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{15e1,,GeneratorExit}

@item

@geindex PyExc_ImportError (C var)
@anchor{c-api/exceptions c PyExc_ImportError}@anchor{4ff8}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ImportError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{65b,,ImportError}

@item

@geindex PyExc_IndentationError (C var)
@anchor{c-api/exceptions c PyExc_IndentationError}@anchor{4ffa}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_IndentationError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{1750,,IndentationError}

@item

@geindex PyExc_IndexError (C var)
@anchor{c-api/exceptions c PyExc_IndexError}@anchor{4ffb}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_IndexError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{174e,,IndexError}

@item

@geindex PyExc_InterruptedError (C var)
@anchor{c-api/exceptions c PyExc_InterruptedError}@anchor{4ffc}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_InterruptedError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{f88,,InterruptedError}

@item

@geindex PyExc_IsADirectoryError (C var)
@anchor{c-api/exceptions c PyExc_IsADirectoryError}@anchor{4ffd}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_IsADirectoryError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1264,,IsADirectoryError}

@item

@geindex PyExc_KeyError (C var)
@anchor{c-api/exceptions c PyExc_KeyError}@anchor{4ffe}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_KeyError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{5e7,,KeyError}

@item

@geindex PyExc_KeyboardInterrupt (C var)
@anchor{c-api/exceptions c PyExc_KeyboardInterrupt}@anchor{4fff}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_KeyboardInterrupt
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{bc5,,KeyboardInterrupt}

@item

@geindex PyExc_LookupError (C var)
@anchor{c-api/exceptions c PyExc_LookupError}@anchor{5000}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_LookupError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{23e5,,LookupError}

@item

@geindex PyExc_MemoryError (C var)
@anchor{c-api/exceptions c PyExc_MemoryError}@anchor{5001}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_MemoryError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{179e,,MemoryError}

@item

@geindex PyExc_ModuleNotFoundError (C var)
@anchor{c-api/exceptions c PyExc_ModuleNotFoundError}@anchor{5002}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ModuleNotFoundError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.6 より).'
@end deffn

@tab

@ref{d3d,,ModuleNotFoundError}

@item

@geindex PyExc_NameError (C var)
@anchor{c-api/exceptions c PyExc_NameError}@anchor{5003}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_NameError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{452,,NameError}

@item

@geindex PyExc_NotADirectoryError (C var)
@anchor{c-api/exceptions c PyExc_NotADirectoryError}@anchor{5004}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_NotADirectoryError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1265,,NotADirectoryError}

@item

@geindex PyExc_NotImplementedError (C var)
@anchor{c-api/exceptions c PyExc_NotImplementedError}@anchor{5005}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_NotImplementedError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{36b,,NotImplementedError}

@item

@geindex PyExc_OSError (C var)
@anchor{c-api/exceptions c PyExc_OSError}@anchor{4e9b}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_OSError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{2c0,,OSError}

@item

@geindex PyExc_OverflowError (C var)
@anchor{c-api/exceptions c PyExc_OverflowError}@anchor{5006}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_OverflowError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{a81,,OverflowError}

@item

@geindex PyExc_PermissionError (C var)
@anchor{c-api/exceptions c PyExc_PermissionError}@anchor{5008}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_PermissionError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{f3e,,PermissionError}

@item

@geindex PyExc_ProcessLookupError (C var)
@anchor{c-api/exceptions c PyExc_ProcessLookupError}@anchor{5009}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ProcessLookupError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1266,,ProcessLookupError}

@item

@geindex PyExc_PythonFinalizationError (C var)
@anchor{c-api/exceptions c PyExc_PythonFinalizationError}@anchor{5204}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_PythonFinalizationError
@end deffn

@tab

@ref{47a,,PythonFinalizationError}

@item

@geindex PyExc_RecursionError (C var)
@anchor{c-api/exceptions c PyExc_RecursionError}@anchor{10b2}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_RecursionError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{f68,,RecursionError}

@item

@geindex PyExc_ReferenceError (C var)
@anchor{c-api/exceptions c PyExc_ReferenceError}@anchor{500a}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ReferenceError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{1726,,ReferenceError}

@item

@geindex PyExc_RuntimeError (C var)
@anchor{c-api/exceptions c PyExc_RuntimeError}@anchor{500c}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_RuntimeError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{244,,RuntimeError}

@item

@geindex PyExc_StopAsyncIteration (C var)
@anchor{c-api/exceptions c PyExc_StopAsyncIteration}@anchor{500e}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_StopAsyncIteration
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{1e0f,,StopAsyncIteration}

@item

@geindex PyExc_StopIteration (C var)
@anchor{c-api/exceptions c PyExc_StopIteration}@anchor{500f}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_StopIteration
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{df5,,StopIteration}

@item

@geindex PyExc_SyntaxError (C var)
@anchor{c-api/exceptions c PyExc_SyntaxError}@anchor{5010}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_SyntaxError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{18e,,SyntaxError}

@item

@geindex PyExc_SystemError (C var)
@anchor{c-api/exceptions c PyExc_SystemError}@anchor{5012}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_SystemError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{795,,SystemError}

@item

@geindex PyExc_SystemExit (C var)
@anchor{c-api/exceptions c PyExc_SystemExit}@anchor{5013}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_SystemExit
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{f3c,,SystemExit}

@item

@geindex PyExc_TabError (C var)
@anchor{c-api/exceptions c PyExc_TabError}@anchor{5014}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_TabError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{765,,TabError}

@item

@geindex PyExc_TimeoutError (C var)
@anchor{c-api/exceptions c PyExc_TimeoutError}@anchor{5015}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_TimeoutError
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{a36,,TimeoutError}

@item

@geindex PyExc_TypeError (C var)
@anchor{c-api/exceptions c PyExc_TypeError}@anchor{4e9a}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_TypeError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{198,,TypeError}

@item

@geindex PyExc_UnboundLocalError (C var)
@anchor{c-api/exceptions c PyExc_UnboundLocalError}@anchor{5016}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_UnboundLocalError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{174f,,UnboundLocalError}

@item

@geindex PyExc_UnicodeDecodeError (C var)
@anchor{c-api/exceptions c PyExc_UnicodeDecodeError}@anchor{5017}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_UnicodeDecodeError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{c08,,UnicodeDecodeError}

@item

@geindex PyExc_UnicodeEncodeError (C var)
@anchor{c-api/exceptions c PyExc_UnicodeEncodeError}@anchor{5018}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_UnicodeEncodeError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{887,,UnicodeEncodeError}

@item

@geindex PyExc_UnicodeError (C var)
@anchor{c-api/exceptions c PyExc_UnicodeError}@anchor{5019}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_UnicodeError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{462,,UnicodeError}

@item

@geindex PyExc_UnicodeTranslateError (C var)
@anchor{c-api/exceptions c PyExc_UnicodeTranslateError}@anchor{501a}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_UnicodeTranslateError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{18fd,,UnicodeTranslateError}

@item

@geindex PyExc_ValueError (C var)
@anchor{c-api/exceptions c PyExc_ValueError}@anchor{4e9c}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ValueError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{2ec,,ValueError}

@item

@geindex PyExc_ZeroDivisionError (C var)
@anchor{c-api/exceptions c PyExc_ZeroDivisionError}@anchor{4e97}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ZeroDivisionError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{b3f,,ZeroDivisionError}

@end multitable



Added in version 3.3: @ref{4fe4,,PyExc_BlockingIOError} 、 @ref{4fe5,,PyExc_BrokenPipeError} 、 @ref{4fe8,,PyExc_ChildProcessError} 、 @ref{4fea,,PyExc_ConnectionError} 、 @ref{4fe9,,PyExc_ConnectionAbortedError} 、 @ref{4feb,,PyExc_ConnectionRefusedError} 、 @ref{4fec,,PyExc_ConnectionResetError} 、 @ref{4ff2,,PyExc_FileExistsError} 、 @ref{4ff3,,PyExc_FileNotFoundError} 、 @ref{4ffc,,PyExc_InterruptedError} 、 @ref{4ffd,,PyExc_IsADirectoryError} 、 @ref{5004,,PyExc_NotADirectoryError} 、 @ref{5008,,PyExc_PermissionError} 、 @ref{5009,,PyExc_ProcessLookupError}  、 @ref{5015,,PyExc_TimeoutError} は 
@geindex Python Enhancement Proposals; PEP 3151
PEP 3151@footnote{https://peps.python.org/pep-3151/} により導入されました。



Added in version 3.5: @ref{500e,,PyExc_StopAsyncIteration} および @ref{10b2,,PyExc_RecursionError} 。



Added in version 3.6: @ref{5002,,PyExc_ModuleNotFoundError}.



Added in version 3.11: @ref{4fe3,,PyExc_BaseExceptionGroup}.


@node OSError aliases,Warning types,Exception types,Exception and warning types
@anchor{c-api/exceptions oserror-aliases}@anchor{5205}
@subsubsection OSError aliases


The following are a compatibility aliases to @ref{4e9b,,PyExc_OSError}.


バージョン 3.3 で変更: これらのエイリアスは例外の種類を分けるために使われます。



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

C name

@tab

Python name

@tab

注釈

@item

@geindex PyExc_EnvironmentError (C var)
@anchor{c-api/exceptions c PyExc_EnvironmentError}@anchor{4ff0}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_EnvironmentError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{2c0,,OSError}

@tab

@item

@geindex PyExc_IOError (C var)
@anchor{c-api/exceptions c PyExc_IOError}@anchor{4ff7}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_IOError
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{2c0,,OSError}

@tab

@item

@geindex PyExc_WindowsError (C var)
@anchor{c-api/exceptions c PyExc_WindowsError}@anchor{501e}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_WindowsError
` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
@end deffn

@tab

@ref{2c0,,OSError}

@tab

@ref{5206,,[win]}

@end multitable


注釈:

@anchor{c-api/exceptions win}@anchor{5206}@w{(win)} 
@code{PyExc_WindowsError} is only defined on Windows; protect code that uses this by testing that the preprocessor macro @code{MS_WINDOWS} is defined.

@node Warning types,,OSError aliases,Exception and warning types
@anchor{c-api/exceptions standardwarningcategories}@anchor{51f3}@anchor{c-api/exceptions warning-types}@anchor{5207}
@subsubsection Warning types



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

C name

@tab

Python name

@item

@geindex PyExc_Warning (C var)
@anchor{c-api/exceptions c PyExc_Warning}@anchor{501d}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_Warning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{2712,,Warning}

@item

@geindex PyExc_BytesWarning (C var)
@anchor{c-api/exceptions c PyExc_BytesWarning}@anchor{4fe7}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_BytesWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{e1c,,BytesWarning}

@item

@geindex PyExc_DeprecationWarning (C var)
@anchor{c-api/exceptions c PyExc_DeprecationWarning}@anchor{4fed}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_DeprecationWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{1a3,,DeprecationWarning}

@item

@geindex PyExc_EncodingWarning (C var)
@anchor{c-api/exceptions c PyExc_EncodingWarning}@anchor{4fef}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_EncodingWarning
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
@end deffn

@tab

@ref{212e,,EncodingWarning}

@item

@geindex PyExc_FutureWarning (C var)
@anchor{c-api/exceptions c PyExc_FutureWarning}@anchor{4ff5}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_FutureWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{659,,FutureWarning}

@item

@geindex PyExc_ImportWarning (C var)
@anchor{c-api/exceptions c PyExc_ImportWarning}@anchor{4ff9}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ImportWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{71e,,ImportWarning}

@item

@geindex PyExc_PendingDeprecationWarning (C var)
@anchor{c-api/exceptions c PyExc_PendingDeprecationWarning}@anchor{5007}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_PendingDeprecationWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{ac5,,PendingDeprecationWarning}

@item

@geindex PyExc_ResourceWarning (C var)
@anchor{c-api/exceptions c PyExc_ResourceWarning}@anchor{500b}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_ResourceWarning
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@end deffn

@tab

@ref{54c,,ResourceWarning}

@item

@geindex PyExc_RuntimeWarning (C var)
@anchor{c-api/exceptions c PyExc_RuntimeWarning}@anchor{500d}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_RuntimeWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{4d7,,RuntimeWarning}

@item

@geindex PyExc_SyntaxWarning (C var)
@anchor{c-api/exceptions c PyExc_SyntaxWarning}@anchor{5011}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_SyntaxWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{1ae,,SyntaxWarning}

@item

@geindex PyExc_UnicodeWarning (C var)
@anchor{c-api/exceptions c PyExc_UnicodeWarning}@anchor{501b}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_UnicodeWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{163d,,UnicodeWarning}

@item

@geindex PyExc_UserWarning (C var)
@anchor{c-api/exceptions c PyExc_UserWarning}@anchor{501c}
@deffn {C 変数} @ref{5df,,PyObject} *PyExc_UserWarning
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{2713,,UserWarning}

@end multitable



Added in version 3.2: @ref{500b,,PyExc_ResourceWarning}.



Added in version 3.10: @ref{4fef,,PyExc_EncodingWarning}.


@node Tracebacks,,Exception and warning types,例外処理
@anchor{c-api/exceptions tracebacks}@anchor{5208}
@subsection Tracebacks


@geindex PyTraceBack_Type (C var)
@anchor{c-api/exceptions c PyTraceBack_Type}@anchor{50d4}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyTraceBack_Type
` 次に属します: @ref{775,,Stable ABI}.'
Type object for traceback objects. This is available as
@ref{cea,,types.TracebackType} in the Python layer.
@end deffn

@geindex PyTraceBack_Check (C function)
@anchor{c-api/exceptions c PyTraceBack_Check}@anchor{5209}
@deffn {C の関数} int PyTraceBack_Check (PyObject *op)

Return true if `op' is a traceback object, false otherwise. This function
does not account for subtypes.
@end deffn

@geindex PyTraceBack_Here (C function)
@anchor{c-api/exceptions c PyTraceBack_Here}@anchor{50d2}
@deffn {C の関数} int PyTraceBack_Here (PyFrameObject *f)
` 次に属します: @ref{775,,Stable ABI}.'
Replace the @ref{14de,,__traceback__} attribute on the current
exception with a new traceback prepending `f' to the existing chain.

Calling this function without an exception set is undefined behavior.

This function returns @code{0} on success, and returns @code{-1} with an
exception set on failure.
@end deffn

@geindex PyTraceBack_Print (C function)
@anchor{c-api/exceptions c PyTraceBack_Print}@anchor{50d3}
@deffn {C の関数} int PyTraceBack_Print (PyObject *tb, PyObject *f)
` 次に属します: @ref{775,,Stable ABI}.'
Write the traceback `tb' into the file `f'.

This function returns @code{0} on success, and returns @code{-1} with an
exception set on failure.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 拡張モジュールの定義,ユーティリティ<2>,例外処理,Python/C API リファレンスマニュアル
@anchor{c-api/extension-modules doc}@anchor{520a}@anchor{c-api/extension-modules defining-extension-modules}@anchor{520b}@anchor{c-api/extension-modules extension-modules}@anchor{4efc}@anchor{c-api/extension-modules translation-repo}@anchor{520c}
@section 拡張モジュールの定義


CPython の C 拡張は、共有ライブラリ (例えば、 Linux では @code{.so} ファイル、 Windows では @code{.pyd} DLL) であり、 Python プロセスで読み込み可能 (例えば、互換性のあるコンパイラ設定でコンパイルされている) で、 @ref{520d,,初期化関数} をエクスポートするものです。

デフォルトで (つまり、 @ref{eae,,importlib.machinery.ExtensionFileLoader} によって) インポート可能であるためには、共有ライブラリは @ref{3e4,,sys.path} 上で利用可能である必要があり、モジュール名と @ref{739,,importlib.machinery.EXTENSION_SUFFIXES}. に含まれる拡張子で命名する必要があります。

@cartouche
@quotation 注釈 
拡張モジュールのビルド、パッケージ化および配布には、サードパーティのツールが最適であり、このドキュメントの範囲外です。適切なツールの一つは Setuptools であり、ドキュメントは @indicateurl{https://setuptools.pypa.io/en/latest/setuptools.html} にあります。
@end quotation
@end cartouche

通常、初期化関数は @ref{4ea3,,PyModuleDef_Init()} を用いて初期化されたモジュール定義を返します。これにより、作成プロセスをいくつかの段階に分割することができます:


@itemize -

@item 
Before any substantial code is executed, Python can determine which
capabilities the module supports, and it can adjust the environment or
refuse loading an incompatible extension.

@item 
By default, Python itself creates the module object -- that is, it does
the equivalent of @ref{7a0,,object.__new__()} for classes.
It also sets initial attributes like @ref{323,,__package__} and
@ref{33b,,__loader__}.

@item 
Afterwards, the module object is initialized using extension-specific
code -- the equivalent of @ref{8bf,,__init__()} on classes.
@end itemize

This is called `multi-phase initialization' to distinguish it from the legacy
(but still supported) `single-phase initialization' scheme,
where the initialization function returns a fully constructed module.
See the @ref{520e,,single-phase-initialization section below}
for details.


バージョン 3.5 で変更: 多段階初期化 (
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}) のサポートを追加しました。


@menu
* 複数のモジュールインスタンス:: 
* 初期化関数:: 
* 多段階初期化:: 
* 従来の一段階初期化:: 

@end menu

@node 複数のモジュールインスタンス,初期化関数,,拡張モジュールの定義
@anchor{c-api/extension-modules multiple-module-instances}@anchor{520f}
@subsection 複数のモジュールインスタンス


By default, extension modules are not singletons.
For example, if the @ref{17e6,,sys.modules} entry is removed and the module
is re-imported, a new module object is created, and typically populated with
fresh method and type objects.
The old module is subject to normal garbage collection.
This mirrors the behavior of pure-Python modules.

Additional module instances may be created in
@ref{163,,sub-interpreters}
or after Python runtime reinitialization
(@ref{45f,,Py_Finalize()} and @ref{460,,Py_Initialize()}).
In these cases, sharing Python objects between module instances would likely
cause crashes or undefined behavior.

To avoid such issues, each instance of an extension module should
be `isolated': changes to one instance should not implicitly affect the others,
and all state owned by the module, including references to Python objects,
should be specific to a particular module instance.
See @ref{166,,拡張モジュールを分離する} for more details and a practical guide.

A simpler way to avoid these issues is
@ref{5210,,raising an error on repeated initialization}.

All modules are expected to support
@ref{163,,sub-interpreters}, or otherwise explicitly
signal a lack of support.
This is usually achieved by isolation or blocking repeated initialization,
as above.
A module may also be limited to the main interpreter using
the @ref{5152,,Py_mod_multiple_interpreters} slot.

@node 初期化関数,多段階初期化,複数のモジュールインスタンス,拡張モジュールの定義
@anchor{c-api/extension-modules extension-export-hook}@anchor{520d}@anchor{c-api/extension-modules initialization-function}@anchor{5211}
@subsection 初期化関数


拡張モジュールによって定義された初期化関数は、次のシグネチャを持ちます:

@geindex PyInit_modulename (C function)
@anchor{c-api/extension-modules c PyInit_modulename}@anchor{5212}
@deffn {C の関数} @ref{5df,,PyObject} *PyInit_modulename (void)
@end deffn

名前が @code{PyInit_@var{<name>}} であり、 @code{<name>} はモジュール名です。

For modules with ASCII-only names, the function must instead be named
@code{PyInit_@var{<name>}}, with @code{<name>} replaced by the name of the module.
When using @ref{5213,,多段階初期化}, non-ASCII module names
are allowed. In this case, the initialization function name is
@code{PyInitU_@var{<name>}}, with @code{<name>} encoded using Python's
`punycode' encoding with hyphens replaced by underscores. In Python:

@example
def initfunc_name(name):
    try:
        suffix = b'_' + name.encode('ascii')
    except UnicodeEncodeError:
        suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
    return b'PyInit' + suffix
@end example

初期化関数は、ヘルパーマクロを使用して定義することが推奨されます:

@geindex PyMODINIT_FUNC (C macro)
@anchor{c-api/extension-modules c PyMODINIT_FUNC}@anchor{16ec}
@deffn {C のマクロ} PyMODINIT_FUNC

Declare an extension module initialization function.
This macro:


@itemize *

@item 
specifies the @ref{5df,,PyObject}* return type,

@item 
adds any special linkage declarations required by the platform, and

@item 
for C++, declares the function as @code{extern "C"}.
@end itemize
@end deffn

For example, a module called @code{spam} would be defined like this:

@example
static struct PyModuleDef spam_module = @{
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "spam",
    ...
@};

PyMODINIT_FUNC
PyInit_spam(void)
@{
    return PyModuleDef_Init(&spam_module);
@}
@end example

It is possible to export multiple modules from a single shared library by
defining multiple initialization functions. However, importing them requires
using symbolic links or a custom importer, because by default only the
function corresponding to the filename is found.
See the Multiple modules in one library@footnote{https://peps.python.org/pep-0489/#multiple-modules-in-one-library}
section in 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/} for details.

The initialization function is typically the only non-@code{static}
item defined in the module's C source.

@node 多段階初期化,従来の一段階初期化,初期化関数,拡張モジュールの定義
@anchor{c-api/extension-modules id1}@anchor{5214}@anchor{c-api/extension-modules multi-phase-initialization}@anchor{5213}
@subsection 多段階初期化


Normally, the @ref{520d,,initialization function}
(@code{PyInit_modulename}) returns a @ref{b74,,PyModuleDef} instance with
non-@code{NULL} @ref{5215,,m_slots}.
Before it is returned, the @code{PyModuleDef} instance must be initialized
using the following function:

@geindex PyModuleDef_Init (C function)
@anchor{c-api/extension-modules c PyModuleDef_Init}@anchor{4ea3}
@deffn {C の関数} @ref{5df,,PyObject} *PyModuleDef_Init (PyModuleDef *def)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.5 より).'
Ensure a module definition is a properly initialized Python object that
correctly reports its type and a reference count.

Return `def' cast to @code{PyObject*}, or @code{NULL} if an error occurred.

Calling this function is required for @ref{5213,,多段階初期化}.
It should not be used in other contexts.

Note that Python assumes that @code{PyModuleDef} structures are statically
allocated.
This function may return either a new reference or a borrowed one;
this reference must not be released.


Added in version 3.5.

@end deffn

@node 従来の一段階初期化,,多段階初期化,拡張モジュールの定義
@anchor{c-api/extension-modules legacy-single-phase-initialization}@anchor{5216}@anchor{c-api/extension-modules single-phase-initialization}@anchor{520e}
@subsection 従来の一段階初期化


@cartouche
@quotation 注意 
Single-phase initialization is a legacy mechanism to initialize extension
modules, with known drawbacks and design flaws. Extension module authors
are encouraged to use multi-phase initialization instead.
@end quotation
@end cartouche

In single-phase initialization, the
@ref{520d,,initialization function} (@code{PyInit_modulename})
should create, populate and return a module object.
This is typically done using @ref{5217,,PyModule_Create()} and functions like
@ref{60a,,PyModule_AddObjectRef()}.

Single-phase initialization differs from the @ref{5213,,default}
in the following ways:


@itemize *

@item 
Single-phase modules are, or rather `contain', “singletons”.

When the module is first initialized, Python saves the contents of
the module's @code{__dict__} (that is, typically, the module's functions and
types).

For subsequent imports, Python does not call the initialization function
again.
Instead, it creates a new module object with a new @code{__dict__}, and copies
the saved contents to it.
For example, given a single-phase module @code{_testsinglephase}
@footnote{
@code{_testsinglephase} is an internal module used
in CPython's self-test suite; your installation may or may not
include it.
} that defines a function @code{sum} and an exception class
@code{error}:

@example
>>> import sys
>>> import _testsinglephase as one
>>> del sys.modules['_testsinglephase']
>>> import _testsinglephase as two
>>> one is two
False
>>> one.__dict__ is two.__dict__
False
>>> one.sum is two.sum
True
>>> one.error is two.error
True
@end example

The exact behavior should be considered a CPython implementation detail.

@item 
To work around the fact that @code{PyInit_modulename} does not take a `spec'
argument, some state of the import machinery is saved and applied to the
first suitable module created during the @code{PyInit_modulename} call.
Specifically, when a sub-module is imported, this mechanism prepends the
parent package name to the name of the module.

A single-phase @code{PyInit_modulename} function should create “its” module
object as soon as possible, before any other module objects can be created.

@item 
Non-ASCII module names (@code{PyInitU_modulename}) are not supported.

@item 
Single-phase modules support module lookup functions like
@ref{50b5,,PyState_FindModule()}.
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ユーティリティ<2>,抽象オブジェクトレイヤ Abstract Objects Layer,拡張モジュールの定義,Python/C API リファレンスマニュアル
@anchor{c-api/utilities doc}@anchor{5218}@anchor{c-api/utilities id1}@anchor{5219}@anchor{c-api/utilities translation-repo}@anchor{521a}@anchor{c-api/utilities utilities}@anchor{521b}
@section ユーティリティ


この章の関数は、C で書かれたコードをプラットフォーム間で可搬性のあるものにする上で役立つものから、C から Python モジュールを使うもの、そして関数の引数を解釈したり、C の値から Python の値を構築するものまで、様々なユーティリティ的タスクを行います。

@menu
* オペレーティングシステム関連のユーティリティ:: 
* システム関数:: 
* プロセス制御:: 
* モジュールのインポート: モジュールのインポート<2>. 
* データ整列化 (data marshalling) のサポート: データ整列化 data marshalling のサポート. 
* 引数の解釈と値の構築:: 
* 文字列の変換と書式化:: 
* Character classification and conversion:: 
* PyHash API:: 
* リフレクション:: 
* codec レジストリとサポート関数:: 
* PyTime C API:: 
* Support for Perf Maps:: 

@end menu

@node オペレーティングシステム関連のユーティリティ,システム関数,,ユーティリティ<2>
@anchor{c-api/sys doc}@anchor{521c}@anchor{c-api/sys operating-system-utilities}@anchor{521d}@anchor{c-api/sys os}@anchor{521e}
@subsection オペレーティングシステム関連のユーティリティ


@geindex PyOS_FSPath (C function)
@anchor{c-api/sys c PyOS_FSPath}@anchor{f14}
@deffn {C の関数} @ref{5df,,PyObject} *PyOS_FSPath (PyObject *path)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.6 より).'
Return the file system representation for `path'. If the object is a
@ref{169,,str} or @ref{192,,bytes} object, then a new
@ref{5e2,,strong reference} is returned.
If the object implements the @ref{e4b,,os.PathLike} interface,
then @ref{e4c,,__fspath__()} is returned as long as it is a
@ref{169,,str} or @ref{192,,bytes} object. Otherwise @ref{198,,TypeError} is raised
and @code{NULL} is returned.


Added in version 3.6.

@end deffn

@geindex Py_FdIsInteractive (C function)
@anchor{c-api/sys c Py_FdIsInteractive}@anchor{521f}
@deffn {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 @code{isatty(fileno(fp))}
is true.  If the @ref{3ff,,PyConfig.interactive} is non-zero, this function
also returns true if the `filename' pointer is @code{NULL} or if the name is equal to
one of the strings @code{'<stdin>'} or @code{'???'}.

This function must not be called before Python is initialized.
@end deffn

@geindex PyOS_BeforeFork (C function)
@anchor{c-api/sys c PyOS_BeforeFork}@anchor{db8}
@deffn {C の関数} void PyOS_BeforeFork ()
` 次に属します: @ref{775,,Stable ABI} on platforms with fork() (バージョン 3.7 より).'
プロセスがフォークする前に、いくつかの内部状態を準備するための関数です。@code{fork()} や現在のプロセスを複製するその他の類似の関数を呼び出す前にこの関数を呼びださなければなりません。@code{fork()} が定義されているシステムでのみ利用できます。

@cartouche
@quotation 警告 
The C @code{fork()} call should only be made from the
@ref{5220,,"main" thread} (of the
@ref{163,,"main" interpreter}).  The same is
true for @code{PyOS_BeforeFork()}.
@end quotation
@end cartouche


Added in version 3.7.

@end deffn

@geindex PyOS_AfterFork_Parent (C function)
@anchor{c-api/sys c PyOS_AfterFork_Parent}@anchor{db9}
@deffn {C の関数} void PyOS_AfterFork_Parent ()
` 次に属します: @ref{775,,Stable ABI} on platforms with fork() (バージョン 3.7 より).'
プロセスがフォークした後に内部状態を更新するための関数です。 @code{fork()} や、現在のプロセスを複製するその他の類似の関数を呼び出した後に、プロセスの複製が成功したかどうかにかかわらず、親プロセスからこの関数を呼び出さなければなりません。@code{fork()} が定義されているシステムでのみ利用できます。

@cartouche
@quotation 警告 
The C @code{fork()} call should only be made from the
@ref{5220,,"main" thread} (of the
@ref{163,,"main" interpreter}).  The same is
true for @code{PyOS_AfterFork_Parent()}.
@end quotation
@end cartouche


Added in version 3.7.

@end deffn

@geindex PyOS_AfterFork_Child (C function)
@anchor{c-api/sys c PyOS_AfterFork_Child}@anchor{430}
@deffn {C の関数} void PyOS_AfterFork_Child ()
` 次に属します: @ref{775,,Stable ABI} on platforms with fork() (バージョン 3.7 より).'
Function to update internal interpreter state after a process fork.
This must be called from the child process after calling @code{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 @code{fork()} is defined.

@cartouche
@quotation 警告 
The C @code{fork()} call should only be made from the
@ref{5220,,"main" thread} (of the
@ref{163,,"main" interpreter}).  The same is
true for @code{PyOS_AfterFork_Child()}.
@end quotation
@end cartouche


Added in version 3.7.



@subsubheading 参考


@ref{355,,os.register_at_fork()} を利用すると @ref{db8,,PyOS_BeforeFork()}、@ref{db9,,PyOS_AfterFork_Parent()} @ref{430,,PyOS_AfterFork_Child()} によって呼び出されるカスタムのPython関数を登録できます。

@end deffn

@geindex PyOS_AfterFork (C function)
@anchor{c-api/sys c PyOS_AfterFork}@anchor{42f}
@deffn {C の関数} void PyOS_AfterFork ()
` 次に属します: @ref{775,,Stable ABI} on platforms with fork().'
プロセスが fork した後の内部状態を更新するための関数です; fork 後 Python インタプリタを使い続ける場合、新たなプロセス内でこの関数を呼び出さねばなりません。新たなプロセスに新たな実行可能物をロードする場合、この関数を呼び出す必要はありません。


バージョン 3.7 で非推奨: この関数は @ref{430,,PyOS_AfterFork_Child()} によって置き換えられました。

@end deffn

@geindex PyOS_CheckStack (C function)
@anchor{c-api/sys c PyOS_CheckStack}@anchor{1ba1}
@deffn {C の関数} int PyOS_CheckStack ()
` 次に属します: @ref{775,,Stable ABI} on platforms with USE_STACKCHECK (バージョン 3.7 より).'
@geindex USE_STACKCHECK (C macro)

Return true when the interpreter runs out of stack space.  This is a reliable
check, but is only available when @code{USE_STACKCHECK} is defined (currently
on certain versions of Windows using the Microsoft Visual C++ compiler).
@code{USE_STACKCHECK} will be defined automatically; you should never
change the definition in your own code.
@end deffn

@geindex PyOS_sighandler_t (C type)
@anchor{c-api/sys c PyOS_sighandler_t}@anchor{5083}
@deffn {C のデータ型} typedef void (*PyOS_sighandler_t)(int)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyOS_getsig (C function)
@anchor{c-api/sys c PyOS_getsig}@anchor{1757}
@deffn {C の関数} @ref{5083,,PyOS_sighandler_t} PyOS_getsig (int i)
` 次に属します: @ref{775,,Stable ABI}.'
Return the current signal handler for signal `i'.  This is a thin wrapper around
either @code{sigaction()} or @code{signal()}.  Do not call those functions
directly!
@end deffn

@geindex PyOS_setsig (C function)
@anchor{c-api/sys c PyOS_setsig}@anchor{1758}
@deffn {C の関数} @ref{5083,,PyOS_sighandler_t} PyOS_setsig (int i, PyOS_sighandler_t h)
` 次に属します: @ref{775,,Stable ABI}.'
Set the signal handler for signal `i' to be `h'; return the old signal handler.
This is a thin wrapper around either @code{sigaction()} or @code{signal()}.  Do
not call those functions directly!
@end deffn

@geindex PyOS_InterruptOccurred (C function)
@anchor{c-api/sys c PyOS_InterruptOccurred}@anchor{1d42}
@deffn {C の関数} int PyOS_InterruptOccurred (void)
` 次に属します: @ref{775,,Stable ABI}.'
Check if a @code{SIGINT} signal has been received.

Returns @code{1} if a @code{SIGINT} has occurred and clears the signal flag,
or @code{0} otherwise.

In most cases, you should prefer @ref{693,,PyErr_CheckSignals()} over this function.
@code{PyErr_CheckSignals()} invokes the appropriate signal handlers
for all pending signals, allowing Python code to handle the signal properly.
This function only detects @code{SIGINT} and does not invoke any Python
signal handlers.

This function is async-signal-safe and this function cannot fail.
The caller must hold an @ref{4ed1,,attached thread state}.
@end deffn

@geindex Py_DecodeLocale (C function)
@anchor{c-api/sys c Py_DecodeLocale}@anchor{dc0}
@deffn {C の関数} wchar_t *Py_DecodeLocale (const char *arg, size_t *size)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@cartouche
@quotation 警告 
This function should not be called directly: use the @ref{3f7,,PyConfig}
API with the @ref{bab,,PyConfig_SetBytesString()} function which ensures
that @ref{42c8,,Python is preinitialized}.

This function must not be called before @ref{42c8,,Python is preinitialized} and so that the LC_CTYPE locale is properly configured: see
the @ref{41e,,Py_PreInitialize()} function.
@end quotation
@end cartouche

@ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} からバイト文字列をデコードします。エラーハンドラが @ref{2853,,surrogateescape エラーハンドラ} なら、
デコードできないバイトは U+DC80 から U+DCFF までの範囲の文字としてデコードされ、バイト列がサロゲート文字としてデコードできる場合は、デコードするのではなく surrogateescape エラーハンドラを使ってバイト列がエスケープされます。

新しくメモリ確保されたワイドキャラクター文字列へのポインタを返します。
このメモリを解放するのには @ref{634,,PyMem_RawFree()} を使ってください。
引数 size が @code{NULL} でない場合は、 null 文字以外のワイドキャラクターの数を @code{*size} へ書き込みます。

デコードもしくはメモリ確保でエラーが起きると @code{NULL} を返します。
`size' が @code{NULL} でない場合は、メモリエラーのときは @code{(size_t)-1} を、デコードでのエラーのときは @code{(size_t)-2} を @code{*size} に設定します。

The @ref{75d,,filesystem encoding and error handler} are selected by
@ref{993,,PyConfig_Read()}: see @ref{41b,,filesystem_encoding} and
@ref{41c,,filesystem_errors} members of @ref{3f7,,PyConfig}.

C ライブラリーにバグがない限り、デコードでのエラーは起こりえません。

キャラクター文字列をバイト文字列に戻すには @ref{dc1,,Py_EncodeLocale()} 関数を使ってください。


@subsubheading 参考


@ref{50ff,,PyUnicode_DecodeFSDefaultAndSize()} および @ref{dc2,,PyUnicode_DecodeLocaleAndSize()} 関数。



Added in version 3.5.



バージョン 3.7 で変更: この関数は、@ref{866,,Python UTF-8 Mode} ではUTF-8エンコーディングを利用するようになりました。



バージョン 3.8 で変更: The function now uses the UTF-8 encoding on Windows if
@ref{418,,PyPreConfig.legacy_windows_fs_encoding} is zero;

@end deffn

@geindex Py_EncodeLocale (C function)
@anchor{c-api/sys c Py_EncodeLocale}@anchor{dc1}
@deffn {C の関数} char *Py_EncodeLocale (const wchar_t *text, size_t *error_pos)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
ワイドキャラクター文字列を @ref{75d,,ファイルシステムのエンコーディングとエラーハンドラ} にエンコードします。エラーハンドラが @ref{2853,,surrogateescape エラーハンドラ} なら、
U+DC80 から U+DCFF までの範囲のサロゲート文字は 0x80 から 0xFF までのバイトに変換されます。

新しくメモリ確保されたバイト文字列へのポインタを返します。
このメモリを解放するのには @ref{165b,,PyMem_Free()} を使ってください。
エンコードエラーかメモリ確保エラーのときは @code{NULL} を返します。

If error_pos is not @code{NULL}, @code{*error_pos} is set to @code{(size_t)-1} on
success,  or set to the index of the invalid character on encoding error.

The @ref{75d,,filesystem encoding and error handler} are selected by
@ref{993,,PyConfig_Read()}: see @ref{41b,,filesystem_encoding} and
@ref{41c,,filesystem_errors} members of @ref{3f7,,PyConfig}.

バイト文字列をワイドキャラクター文字列に戻すには @ref{dc0,,Py_DecodeLocale()} 関数を使ってください。

@cartouche
@quotation 警告 
This function must not be called before @ref{42c8,,Python is preinitialized} and so that the LC_CTYPE locale is properly configured: see
the @ref{41e,,Py_PreInitialize()} function.
@end quotation
@end cartouche


@subsubheading 参考


@ref{1e31,,PyUnicode_EncodeFSDefault()} および @ref{dc3,,PyUnicode_EncodeLocale()} 関数。



Added in version 3.5.



バージョン 3.7 で変更: この関数は、@ref{866,,Python UTF-8 Mode} ではUTF-8エンコーディングを利用するようになりました。



バージョン 3.8 で変更: The function now uses the UTF-8 encoding on Windows if
@ref{418,,PyPreConfig.legacy_windows_fs_encoding} is zero.

@end deffn

@geindex Py_fopen (C function)
@anchor{c-api/sys c Py_fopen}@anchor{393}
@deffn {C の関数} FILE *Py_fopen (PyObject *path, const char *mode)

Similar to @code{fopen()}, but `path' is a Python object and
an exception is set on error.

`path' must be a @ref{169,,str} object, a @ref{192,,bytes} object,
or a @ref{5a1,,path-like object}.

On success, return the new file pointer.
On error, set an exception and return @code{NULL}.

The file must be closed by @ref{394,,Py_fclose()} rather than calling directly
@code{fclose()}.

The file descriptor is created non-inheritable (
@geindex Python Enhancement Proposals; PEP 446
PEP 446@footnote{https://peps.python.org/pep-0446/}).

The caller must have an @ref{4ed1,,attached thread state}.


Added in version 3.14.

@end deffn

@geindex Py_fclose (C function)
@anchor{c-api/sys c Py_fclose}@anchor{394}
@deffn {C の関数} int Py_fclose (FILE *file)

Close a file that was opened by @ref{393,,Py_fopen()}.

On success, return @code{0}.
On error, return @code{EOF} and @code{errno} is set to indicate the error.
In either case, any further access (including another call to
@ref{394,,Py_fclose()}) to the stream results in undefined behavior.


Added in version 3.14.

@end deffn

@node システム関数,プロセス制御,オペレーティングシステム関連のユーティリティ,ユーティリティ<2>
@anchor{c-api/sys system-functions}@anchor{5221}@anchor{c-api/sys systemfunctions}@anchor{5222}
@subsection システム関数


@ref{df,,sys} モジュールが提供している機能にCのコードからアクセスする関数です。すべての関数は現在のインタプリタスレッドの @ref{df,,sys} モジュールの辞書に対して動作します。この辞書は内部のスレッド状態構造体に格納されています。

@geindex PySys_GetObject (C function)
@anchor{c-api/sys c PySys_GetObject}@anchor{62a}
@deffn {C の関数} @ref{5df,,PyObject} *PySys_GetObject (const char *name)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{df,,sys} モジュールの `name' オブジェクトを返すか、存在しなければ例外を設定せずに @code{NULL} を返します。
@end deffn

@geindex PySys_SetObject (C function)
@anchor{c-api/sys c PySys_SetObject}@anchor{50bf}
@deffn {C の関数} int PySys_SetObject (const char *name, PyObject *v)
` 次に属します: @ref{775,,Stable ABI}.'
`v' が @code{NULL} で無い場合、 @ref{df,,sys} モジュールの `name' に `v' を設定します。 `v' が @code{NULL} なら、 sys モジュールから `name' を削除します。成功したら @code{0} を、エラー時は @code{-1} を返します。
@end deffn

@geindex PySys_ResetWarnOptions (C function)
@anchor{c-api/sys c PySys_ResetWarnOptions}@anchor{3f4}
@deffn {C の関数} void PySys_ResetWarnOptions ()
` 次に属します: @ref{775,,Stable ABI}.'
Reset @ref{3f5,,sys.warnoptions} to an empty list. This function may be
called prior to @ref{460,,Py_Initialize()}.


Deprecated since version 3.13, will be removed in version 3.15: Clear @ref{3f5,,sys.warnoptions} and @code{warnings.filters} instead.

@end deffn

@geindex PySys_WriteStdout (C function)
@anchor{c-api/sys c PySys_WriteStdout}@anchor{50c1}
@deffn {C の関数} void PySys_WriteStdout (const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
`format' で指定された出力文字列を @ref{ccd,,sys.stdout} に出力します。切り詰めが起こった場合を含め、例外は一切発生しません (後述)。

`format' は、フォーマット後の出力文字列のトータルの大きさを1000バイト以下に抑えるべきです。-- 1000 バイト以降の出力文字列は切り詰められます。特に、制限のない "%s" フォーマットを使うべきではありません。"%.<N>s" のようにして N に10進数の値を指定し、<N> + その他のフォーマット後の最大サイズが1000を超えないように設定するべきです。同じように "%f" にも気を付ける必要があります。非常に大きい数値に対して、数百の数字を出力する可能性があります。

問題が発生したり、 @ref{ccd,,sys.stdout} が設定されていなかった場合、フォーマット後のメッセージは本物の(Cレベルの) `stdout' に出力されます。
@end deffn

@geindex PySys_WriteStderr (C function)
@anchor{c-api/sys c PySys_WriteStderr}@anchor{50c0}
@deffn {C の関数} void PySys_WriteStderr (const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{50c1,,PySys_WriteStdout()} と同じですが、 @ref{b33,,sys.stderr} もしくは `stderr' に出力します。
@end deffn

@geindex PySys_FormatStdout (C function)
@anchor{c-api/sys c PySys_FormatStdout}@anchor{50bd}
@deffn {C の関数} void PySys_FormatStdout (const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
PySys_WriteStdout() に似た関数ですが、 @ref{794,,PyUnicode_FromFormatV()} を使ってメッセージをフォーマットし、メッセージを任意の長さに切り詰めたりはしません。


Added in version 3.2.

@end deffn

@geindex PySys_FormatStderr (C function)
@anchor{c-api/sys c PySys_FormatStderr}@anchor{50bc}
@deffn {C の関数} void PySys_FormatStderr (const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{50bd,,PySys_FormatStdout()} と同じですが、 @ref{b33,,sys.stderr} もしくは `stderr' に出力します。


Added in version 3.2.

@end deffn

@geindex PySys_GetXOptions (C function)
@anchor{c-api/sys c PySys_GetXOptions}@anchor{50be}
@deffn {C の関数} @ref{5df,,PyObject} *PySys_GetXOptions ()
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@ref{2131,,sys._xoptions} と同様、 @ref{16f,,-X} オプションの現在の辞書を返します。エラーが起きると、 @code{NULL} が返され、例外がセットされます。


Added in version 3.2.

@end deffn

@geindex PySys_Audit (C function)
@anchor{c-api/sys c PySys_Audit}@anchor{613}
@deffn {C の関数} int PySys_Audit (const char *event, const char *format, ...)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Raise an auditing event with any active hooks. Return zero for success
and non-zero with an exception set on failure.

The `event' string argument must not be `NULL'.

If any hooks have been added, `format' and other arguments will be used
to construct a tuple to pass. Apart from @code{N}, the same format characters
as used in @ref{3c2,,Py_BuildValue()} are available. If the built value is not
a tuple, it will be added into a single-element tuple.

The @code{N} format option must not be used. It 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 @code{#} format characters should always be treated as
@ref{c55,,Py_ssize_t}, regardless of whether @code{PY_SSIZE_T_CLEAN} was defined.

@ref{191b,,sys.audit()} performs the same function from Python code.

See also @ref{612,,PySys_AuditTuple()}.


Added in version 3.8.



バージョン 3.8.2 で変更: Require @ref{c55,,Py_ssize_t} for @code{#} format characters. Previously, an
unavoidable deprecation warning was raised.

@end deffn

@geindex PySys_AuditTuple (C function)
@anchor{c-api/sys c PySys_AuditTuple}@anchor{612}
@deffn {C の関数} int PySys_AuditTuple (const char *event, PyObject *args)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Similar to @ref{613,,PySys_Audit()}, but pass arguments as a Python object.
`args' must be a @ref{614,,tuple}. To pass no arguments, `args' can be `NULL'.


Added in version 3.13.

@end deffn

@geindex PySys_AddAuditHook (C function)
@anchor{c-api/sys c PySys_AddAuditHook}@anchor{4751}
@deffn {C の関数} int PySys_AddAuditHook (Py_AuditHookFunction hook, void *userData)

Append the callable `hook' to the list of active auditing hooks.
Return zero on 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 @ref{460,,Py_Initialize()}. When called
after runtime initialization, existing audit hooks are notified and may
silently abort the operation by raising an error subclassed from
@ref{bcd,,Exception} (other errors will not be silenced).

The hook function is always called with an @ref{4ed1,,attached thread state} by
the Python interpreter that raised the event.

See 
@geindex Python Enhancement Proposals; PEP 578
PEP 578@footnote{https://peps.python.org/pep-0578/} for a detailed description of auditing.  Functions in the
runtime and standard library that raise events are listed in the
@ref{1c13,,audit events table}.
Details are in each function's documentation.


If the interpreter is initialized, this function raises an auditing event
@code{sys.addaudithook} with no arguments. If any existing hooks raise an
exception derived from @ref{bcd,,Exception}, the new hook will not be
added and the exception is cleared. As a result, callers cannot assume
that their hook has been added unless they control all existing hooks.


@geindex Py_AuditHookFunction (C type)
@anchor{c-api/sys c Py_AuditHookFunction}@anchor{5223}
@deffn {C のデータ型} typedef int (*Py_AuditHookFunction)(const char *event, @ref{5df,,PyObject} *args, void *userData)

The type of the hook function.
`event' is the C string event argument passed to @ref{613,,PySys_Audit()} or
@ref{612,,PySys_AuditTuple()}.
`args' is guaranteed to be a @ref{5224,,PyTupleObject}.
`userData' is the argument passed to PySys_AddAuditHook().
@end deffn


Added in version 3.8.

@end deffn

@node プロセス制御,モジュールのインポート<2>,システム関数,ユーティリティ<2>
@anchor{c-api/sys process-control}@anchor{5225}@anchor{c-api/sys processcontrol}@anchor{5226}
@subsection プロセス制御


@geindex Py_FatalError (C function)
@anchor{c-api/sys c Py_FatalError}@anchor{b7a}
@deffn {C の関数} void Py_FatalError (const char *message)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex abort (C function)

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 @code{abort()} is called which will attempt to produce a @code{core}
file.

The @code{Py_FatalError()} function is replaced with a macro which logs
automatically the name of the current function, unless the
@code{Py_LIMITED_API} macro is defined.


バージョン 3.9 で変更: Log the function name automatically.

@end deffn

@geindex Py_Exit (C function)
@anchor{c-api/sys c Py_Exit}@anchor{f4b}
@deffn {C の関数} void Py_Exit (int status)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex Py_FinalizeEx (C function)
@geindex exit (C function)

現在のプロセスを終了します。@ref{f11,,Py_FinalizeEx()} を呼び出した後、標準Cライブラリ関数の @code{exit(status)} を呼び出します。@ref{f11,,Py_FinalizeEx()} がエラーになった場合、終了ステータスは 120に設定されます。


バージョン 3.6 で変更: 終了処理のエラーは無視されなくなりました。

@end deffn

@geindex Py_AtExit (C function)
@anchor{c-api/sys c Py_AtExit}@anchor{5128}
@deffn {C の関数} int Py_AtExit (void (*func)())
` 次に属します: @ref{775,,Stable ABI}.'
@geindex Py_FinalizeEx (C function)
@geindex cleanup functions

@ref{f11,,Py_FinalizeEx()} から呼び出される後始末処理を行う関数 (cleanup function) を登録します。後始末関数は引数無しで呼び出され、値を返しません。最大で 32 の後始末処理関数を登録できます。登録に成功すると、 @ref{5128,,Py_AtExit()} は @code{0} を返します;  失敗すると @code{-1} を返します。最後に登録した後始末処理関数から先に呼び出されます。各関数は高々一度しか呼び出されません。 Python の内部的な終了処理は後始末処理関数より以前に完了しているので、 `func' からはいかなる Python API も呼び出してはなりません。


@subsubheading 参考


@ref{18fa,,PyUnstable_AtExit()} for passing a @code{void *data} argument.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node モジュールのインポート<2>,データ整列化 data marshalling のサポート,プロセス制御,ユーティリティ<2>
@anchor{c-api/import doc}@anchor{5227}@anchor{c-api/import importing}@anchor{5228}@anchor{c-api/import importing-modules}@anchor{5229}@anchor{c-api/import translation-repo}@anchor{522a}
@subsection モジュールのインポート


@geindex PyImport_ImportModule (C function)
@anchor{c-api/import c PyImport_ImportModule}@anchor{3dc}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ImportModule (const char *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex package variable;__all__
@geindex __all__ (package variable)
@geindex modules (in module sys)

This is a wrapper around @ref{1615,,PyImport_Import()} which takes a
const char* as an argument instead of a @ref{5df,,PyObject}*.
@end deffn

@geindex PyImport_ImportModuleNoBlock (C function)
@anchor{c-api/import c PyImport_ImportModuleNoBlock}@anchor{3db}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ImportModuleNoBlock (const char *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
この関数は、 @ref{3dc,,PyImport_ImportModule()} の廃止予定のエイリアスです。


バージョン 3.3 で変更: この関数は、従来は別のスレッドによってインポートロックが行われていた場合は即座に失敗していました。しかし Python 3.3 では、大部分の目的でロックスキームがモジュールごとのロックに移行したので、この関数の特別な振る舞いはもはや必要ではありません。



Deprecated since version 3.13, will be removed in version 3.15: Use @ref{3dc,,PyImport_ImportModule()} instead.

@end deffn

@geindex PyImport_ImportModuleEx (C function)
@anchor{c-api/import c PyImport_ImportModuleEx}@anchor{13bd}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ImportModuleEx (const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)
`戻り値: 新しい参照。'
@geindex 組み込み関数;__import__

モジュールをインポートします。モジュールのインポートについては組み込みの Python 関数 @ref{ad1,,__import__()} を読むとよくわかります。

戻り値は、インポートされたモジュールかトップレベルパッケージへの新しい参照か、失敗した場合は例外を設定して @code{NULL} を返します。
@ref{ad1,,__import__()} と同じように、パッケージのサブモジュールが要求されたときは、空でない `fromlist' を渡された時以外は、トップレベルのパッケージを返します。

インポートが失敗した場合は、@ref{3dc,,PyImport_ImportModule()} と同様に不完全なモジュールのオブジェクトを削除します。
@end deffn

@geindex PyImport_ImportModuleLevelObject (C function)
@anchor{c-api/import c PyImport_ImportModuleLevelObject}@anchor{5039}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ImportModuleLevelObject (PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
モジュールをインポートします。モジュールのインポートについては組み込みの Python 関数 @ref{ad1,,__import__()} を読むとよく分かります。というのも、標準の @ref{ad1,,__import__()}  はこの関数を直接呼び出しているからです。

戻り値は、インポートされたモジュールかトップレベルパッケージへの新しい参照か、失敗した場合は例外を設定して @code{NULL} を返します。
@ref{ad1,,__import__()} と同じように、パッケージのサブモジュールが要求されたときは、空でない `fromlist' を渡された時以外は、トップレベルのパッケージを返します。


Added in version 3.3.

@end deffn

@geindex PyImport_ImportModuleLevel (C function)
@anchor{c-api/import c PyImport_ImportModuleLevel}@anchor{13bc}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ImportModuleLevel (const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{5039,,PyImport_ImportModuleLevelObject()} と似ていますが、name が Unicode オブジェクトではなく UTF-8 でエンコードされた文字列である点で異なります。


バージョン 3.3 で変更: `level' にはもはや負の値は使用できません。

@end deffn

@geindex PyImport_Import (C function)
@anchor{c-api/import c PyImport_Import}@anchor{1615}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_Import (PyObject *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
現在の "インポートフック関数" を呼び出すための高水準のインターフェースです (`level' に 0 を明示すると、絶対インポートを意味します)。 この関数は現在のグローバル変数辞書内の @code{__builtins__} から @ref{ad1,,__import__()} 関数を呼び出します。すなわち、現在の環境にインストールされているインポートフック使ってインポートを行います。

この関数は常に絶対インポートを使用します。
@end deffn

@geindex PyImport_ReloadModule (C function)
@anchor{c-api/import c PyImport_ReloadModule}@anchor{503a}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ReloadModule (PyObject *m)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
モジュールを再ロード (reload) します。戻り値は再ロードしたモジュールかトップレベルパッケージへの新たな参照になります。
失敗した場合には例外をセットし、@code{NULL} を返します (その場合でも、モジュールは生成されている場合があります)。
@end deffn

@geindex PyImport_AddModuleRef (C function)
@anchor{c-api/import c PyImport_AddModuleRef}@anchor{5fb}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_AddModuleRef (const char *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return the module object corresponding to a module name.

The `name' argument may be of the form @code{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 a @ref{5e2,,strong reference} to the module on success. Return @code{NULL}
with an exception set on failure.

The module name `name' is decoded from UTF-8.

This function does not load or import the module; if the module wasn't
already loaded, you will get an empty module object. Use
@ref{3dc,,PyImport_ImportModule()} 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.


Added in version 3.13.

@end deffn

@geindex PyImport_AddModuleObject (C function)
@anchor{c-api/import c PyImport_AddModuleObject}@anchor{5030}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_AddModuleObject (PyObject *name)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Similar to @ref{5fb,,PyImport_AddModuleRef()}, but return a @ref{3d7,,borrowed reference} and `name' is a Python @ref{169,,str} object.


Added in version 3.3.

@end deffn

@geindex PyImport_AddModule (C function)
@anchor{c-api/import c PyImport_AddModule}@anchor{5fc}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_AddModule (const char *name)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
Similar to @ref{5fb,,PyImport_AddModuleRef()}, but return a @ref{3d7,,borrowed reference}.
@end deffn

@geindex PyImport_ExecCodeModule (C function)
@anchor{c-api/import c PyImport_ExecCodeModule}@anchor{5031}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ExecCodeModule (const char *name, PyObject *co)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;コンパイル

Given a module name (possibly of the form @code{package.module}) and a code object
read from a Python bytecode file or obtained from the built-in function
@ref{4b1,,compile()}, load the module.  Return a new reference to the module object,
or @code{NULL} with an exception set if an error occurred.  `name'
is removed from @ref{17e6,,sys.modules} in error cases, even if `name' was already
in @ref{17e6,,sys.modules} on entry to @ref{5031,,PyImport_ExecCodeModule()}.  Leaving
incompletely initialized modules in @ref{17e6,,sys.modules} 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 @ref{2364,,__spec__} and @ref{33b,,__loader__} will be
set, if not set already, with the appropriate values.  The spec's loader
will be set to the module's @code{__loader__} (if set) and to an instance
of @ref{1280,,SourceFileLoader} otherwise.

The module's @ref{2369,,__file__} attribute will be set to the code
object's @ref{1585,,co_filename}.  If applicable,
@ref{321,,__cached__} will also be set.

この関数は、すでにインポートされているモジュールの場合には再ロードを行います。意図的にモジュールの再ロードを行う方法は @ref{503a,,PyImport_ReloadModule()} を参照してください。

`name' が @code{package.module} 形式のドット名表記であった場合、まだ作成されていないパッケージ構造はその作成されないままになります。

@ref{5032,,PyImport_ExecCodeModuleEx()} と @ref{5034,,PyImport_ExecCodeModuleWithPathnames()} も参照してください。


バージョン 3.12 で変更: The setting of @ref{321,,__cached__} and @ref{33b,,__loader__}
is deprecated. See @ref{226c,,ModuleSpec} for
alternatives.

@end deffn

@geindex PyImport_ExecCodeModuleEx (C function)
@anchor{c-api/import c PyImport_ExecCodeModuleEx}@anchor{5032}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ExecCodeModuleEx (const char *name, PyObject *co, const char *pathname)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Like @ref{5031,,PyImport_ExecCodeModule()}, but the @ref{2369,,__file__}
attribute of the module object is set to `pathname' if it is non-@code{NULL}.

@ref{5034,,PyImport_ExecCodeModuleWithPathnames()} も参照してください。
@end deffn

@geindex PyImport_ExecCodeModuleObject (C function)
@anchor{c-api/import c PyImport_ExecCodeModuleObject}@anchor{5033}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ExecCodeModuleObject (PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Like @ref{5032,,PyImport_ExecCodeModuleEx()}, but the @ref{321,,__cached__}
attribute of the module object is set to `cpathname' if it is
non-@code{NULL}.  Of the three functions, this is the preferred one to use.


Added in version 3.3.



バージョン 3.12 で変更: Setting @ref{321,,__cached__} is deprecated. See
@ref{226c,,ModuleSpec} for alternatives.

@end deffn

@geindex PyImport_ExecCodeModuleWithPathnames (C function)
@anchor{c-api/import c PyImport_ExecCodeModuleWithPathnames}@anchor{5034}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ExecCodeModuleWithPathnames (const char *name, PyObject *co, const char *pathname, const char *cpathname)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{5033,,PyImport_ExecCodeModuleObject()} と似ていますが、 `name' と `pathname'、 `cpathname' が UTF-8 でエンコードされた文字列である点が異なります。もし `pathname' が @code{NULL} の場合、`cpathname' から、`pathname' どのような値になるべきかを知る試みもなされます。


Added in version 3.2.



バージョン 3.3 で変更: Uses @code{imp.source_from_cache()} in calculating the source path if
only the bytecode path is provided.



バージョン 3.12 で変更: No longer uses the removed @code{imp} module.

@end deffn

@geindex PyImport_GetMagicNumber (C function)
@anchor{c-api/import c PyImport_GetMagicNumber}@anchor{13bb}
@deffn {C の関数} long PyImport_GetMagicNumber ()
` 次に属します: @ref{775,,Stable ABI}.'
Python バイトコードファイル (別名 @code{.pyc} ファイル) のマジックナンバーを返します。マジックナンバーはバイトコードファイルの最初の4バイトに、リトルエンディアンバイトオーダーで現れるべきです。エラーの場合は @code{-1} を返します。


バージョン 3.3 で変更: 失敗した場合は @code{-1} の値を返します。

@end deffn

@geindex PyImport_GetMagicTag (C function)
@anchor{c-api/import c PyImport_GetMagicTag}@anchor{5035}
@deffn {C の関数} const char *PyImport_GetMagicTag ()
` 次に属します: @ref{775,,Stable ABI}.'
マジックタグ文字列を Python バイトコードファイル名の 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} フォーマットで返します。@code{sys.implementation.cache_tag} の値が信頼でき、かつこの関数の代わりに使用すべきであることを肝に命じましょう。


Added in version 3.2.

@end deffn

@geindex PyImport_GetModuleDict (C function)
@anchor{c-api/import c PyImport_GetModuleDict}@anchor{5036}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_GetModuleDict ()
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
モジュール管理のための辞書 (いわゆる @code{sys.modules})を返します。この辞書はインタプリタごとに一つだけある変数なので注意してください。
@end deffn

@geindex PyImport_GetModule (C function)
@anchor{c-api/import c PyImport_GetModule}@anchor{dac}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_GetModule (PyObject *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
与えられた名前の既にインポート済みのモジュールを返します。
モジュールがインポートされていなかった場合は、 @code{NULL} を返しますが、エラーはセットしません。
モジュールの検索に失敗した場合は、 @code{NULL} を返し、エラーをセットします。


Added in version 3.7.

@end deffn

@geindex PyImport_GetImporter (C function)
@anchor{c-api/import c PyImport_GetImporter}@anchor{1a84}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_GetImporter (PyObject *path)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a finder object for a @ref{3e4,,sys.path}/@code{pkg.__path__} item
`path', possibly by fetching it from the @ref{7fa,,sys.path_importer_cache}
dict.  If it wasn't yet cached, traverse @ref{1225,,sys.path_hooks} until a hook
is found that can handle the path item.  Return @code{None} if no hook could;
this tells our caller that the @ref{244d,,path based finder} could not find a
finder for this path item. Cache the result in @ref{7fa,,sys.path_importer_cache}.
Return a new reference to the finder object.
@end deffn

@geindex PyImport_ImportFrozenModuleObject (C function)
@anchor{c-api/import c PyImport_ImportFrozenModuleObject}@anchor{5038}
@deffn {C の関数} int PyImport_ImportFrozenModuleObject (PyObject *name)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
`name' という名前のフリーズ (freeze) されたモジュールをロードします。成功すると @code{1} を、モジュールが見つからなかった場合には @code{0} を、初期化が失敗した場合には例外をセットして @code{-1} を返します。ロードに成功したモジュールにアクセスするには @ref{3dc,,PyImport_ImportModule()} を使ってください。 (Note この関数はいささか誤解を招く名前です --- この関数はモジュールがすでにインポートされていたらリロードしてしまいます。)


Added in version 3.3.



バージョン 3.4 で変更: @code{__file__} 属性はもうモジュールにセットされません。

@end deffn

@geindex PyImport_ImportFrozenModule (C function)
@anchor{c-api/import c PyImport_ImportFrozenModule}@anchor{5037}
@deffn {C の関数} int PyImport_ImportFrozenModule (const char *name)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{5038,,PyImport_ImportFrozenModuleObject()} と似ていますが、name は UTF-8 でエンコードされた文字列の代わりに、 Unicode オブジェクトを使用する点が異なります。
@end deffn

@geindex _frozen (C struct)
@anchor{c-api/import c _frozen}@anchor{979}
@deffn {C Struct} struct _frozen

@geindex 凍結ユーティリティ

@code{freeze} ユーティリティが生成するようなフリーズ化モジュールデスクリプタの構造体型定義です。 (Python ソース配布物の @code{Tools/freeze/} を参照してください) この構造体の定義は @code{Include/import.h} にあり、以下のようになっています:

@example
struct _frozen @{
    const char *name;
    const unsigned char *code;
    int size;
    bool is_package;
@};
@end example


バージョン 3.11 で変更: The new @code{is_package} field indicates whether the module is a package or not.
This replaces setting the @code{size} field to a negative value.

@end deffn

@geindex PyImport_FrozenModules (C var)
@anchor{c-api/import c PyImport_FrozenModules}@anchor{3318}
@deffn {C 変数} const struct @ref{979,,_frozen} *PyImport_FrozenModules

このポインタは @ref{979,,_frozen} のレコードからなり、終端の要素のメンバが @code{NULL} かゼロになっているような配列を指すよう初期化されます。
フリーズされたモジュールをインポートするとき、このテーブルを検索します。
サードパーティ製のコードからこのポインタに仕掛けを講じて、動的に生成されたフリーズ化モジュールの集合を提供するようにできます。
@end deffn

@geindex PyImport_AppendInittab (C function)
@anchor{c-api/import c PyImport_AppendInittab}@anchor{1b1c}
@deffn {C の関数} int PyImport_AppendInittab (const char *name, PyObject *(*initfunc)(void))
` 次に属します: @ref{775,,Stable ABI}.'
既存の組み込みモジュールテーブルに単一のモジュールを追加します。この関数は利便性を目的とした @ref{1b1d,,PyImport_ExtendInittab()} のラッパー関数で、テーブルが拡張できないときには @code{-1} を返します。新たなモジュールは `name' でインポートでき、最初にインポートを試みた際に呼び出される関数として `initfunc' を使います。 @ref{460,,Py_Initialize()} よりも前に呼び出さなければなりません。
@end deffn

@geindex _inittab (C struct)
@anchor{c-api/import c _inittab}@anchor{522b}
@deffn {C Struct} struct _inittab

Structure describing a single entry in the list of built-in modules.
Programs which
embed Python may use an array of these structures in conjunction with
@ref{1b1d,,PyImport_ExtendInittab()} to provide additional built-in modules.
The structure consists of two members:

@geindex _inittab.name (C member)
@anchor{c-api/import c _inittab name}@anchor{522c}
@deffn {C のメンバ変数} const char *name

The module name, as an ASCII encoded string.
@end deffn

@geindex _inittab.initfunc (C member)
@anchor{c-api/import c _inittab initfunc}@anchor{522d}
@deffn {C のメンバ変数} @ref{5df,,PyObject} *(*initfunc)(void)

Initialization function for a module built into the interpreter.
@end deffn
@end deffn

@geindex PyImport_ExtendInittab (C function)
@anchor{c-api/import c PyImport_ExtendInittab}@anchor{1b1d}
@deffn {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 @code{NULL} for the @ref{522c,,name}
field; failure to provide the sentinel value can result in a memory fault.
Returns @code{0} on success or @code{-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 @ref{460,,Py_Initialize()}.

Python が複数回初期化される場合、@ref{1b1c,,PyImport_AppendInittab()} または @ref{1b1d,,PyImport_ExtendInittab()} は、それぞれの初期化の前に呼び出される必要があります。
@end deffn

@geindex PyImport_Inittab (C var)
@anchor{c-api/import c PyImport_Inittab}@anchor{1b1b}
@deffn {C 変数} struct @ref{522b,,_inittab} *PyImport_Inittab

The table of built-in modules used by Python initialization. Do not use this directly;
use @ref{1b1c,,PyImport_AppendInittab()} and @ref{1b1d,,PyImport_ExtendInittab()}
instead.
@end deffn

@geindex PyImport_ImportModuleAttr (C function)
@anchor{c-api/import c PyImport_ImportModuleAttr}@anchor{396}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ImportModuleAttr (PyObject *mod_name, PyObject *attr_name)
`戻り値: 新しい参照。'
Import the module `mod_name' and get its attribute `attr_name'.

Names must be Python @ref{169,,str} objects.

Helper function combining @ref{1615,,PyImport_Import()} and
@ref{5ee,,PyObject_GetAttr()}. For example, it can raise @ref{65b,,ImportError} if
the module is not found, and @ref{5f0,,AttributeError} if the attribute doesn't
exist.


Added in version 3.14.

@end deffn

@geindex PyImport_ImportModuleAttrString (C function)
@anchor{c-api/import c PyImport_ImportModuleAttrString}@anchor{397}
@deffn {C の関数} @ref{5df,,PyObject} *PyImport_ImportModuleAttrString (const char *mod_name, const char *attr_name)
`戻り値: 新しい参照。'
Similar to @ref{396,,PyImport_ImportModuleAttr()}, but names are UTF-8 encoded
strings instead of Python @ref{169,,str} objects.


Added in version 3.14.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node データ整列化 data marshalling のサポート,引数の解釈と値の構築,モジュールのインポート<2>,ユーティリティ<2>
@anchor{c-api/marshal doc}@anchor{522e}@anchor{c-api/marshal data-marshalling-support}@anchor{522f}@anchor{c-api/marshal marshalling-utils}@anchor{5230}@anchor{c-api/marshal translation-repo}@anchor{5231}
@subsection データ整列化 (data marshalling) のサポート


以下のルーチン群は、 @ref{91,,marshal} モジュールと同じ形式を使った整列化オブジェクトを C コードから使えるようにします。整列化形式でデータを書き出す関数に加えて、データを読み戻す関数もあります。整列化されたデータを記録するファイルはバイナリモードで開かれていなければなりません。

数値は最小桁が先にくるように記録されます。

The module supports several versions of the data format; see
the @ref{91,,Python module documentation} for details.

@geindex Py_MARSHAL_VERSION (C macro)
@anchor{c-api/marshal c Py_MARSHAL_VERSION}@anchor{5232}
@deffn {C のマクロ} Py_MARSHAL_VERSION

The current format version. See @ref{2d42,,marshal.version}.
@end deffn

@geindex PyMarshal_WriteLongToFile (C function)
@anchor{c-api/marshal c PyMarshal_WriteLongToFile}@anchor{999}
@deffn {C の関数} void PyMarshal_WriteLongToFile (long value, FILE *file, int version)

long 型の整数値 `value' を `file' へ整列化します。この関数は `value' の下桁 32 ビットを書き込むだけです; ネイティブの long 型サイズには関知しません。 `version' はファイルフォーマットを示します。

この関数は失敗することがあり、その場合はエラー指示子を設定します。それを確認するために @ref{1caf,,PyErr_Occurred()} を使います。
@end deffn

@geindex PyMarshal_WriteObjectToFile (C function)
@anchor{c-api/marshal c PyMarshal_WriteObjectToFile}@anchor{99a}
@deffn {C の関数} void PyMarshal_WriteObjectToFile (PyObject *value, FILE *file, int version)

Python オブジェクト `value' を `file' へ整列化します。`version' はファイルフォーマットを示します。

この関数は失敗することがあり、その場合はエラー指示子を設定します。それを確認するために @ref{1caf,,PyErr_Occurred()} を使います。
@end deffn

@geindex PyMarshal_WriteObjectToString (C function)
@anchor{c-api/marshal c PyMarshal_WriteObjectToString}@anchor{99c}
@deffn {C の関数} @ref{5df,,PyObject} *PyMarshal_WriteObjectToString (PyObject *value, int version)
`戻り値: 新しい参照。'
`value' の整列化表現が入ったバイト列オブジェクトを返します。`version' はファイルフォーマットを示します。
@end deffn

以下の関数を使うと、整列化された値を読み戻せます。

@geindex PyMarshal_ReadLongFromFile (C function)
@anchor{c-api/marshal c PyMarshal_ReadLongFromFile}@anchor{5233}
@deffn {C の関数} long PyMarshal_ReadLongFromFile (FILE *file)

読み出し用に開かれた FILE* 内のデータストリームから、 C の long 型データを読み出して返します。この関数は、ネイティブの long のサイズに関係なく、 32 ビットの値だけを読み出せます。

エラーの場合、適切な例外 (@ref{14f1,,EOFError}) を設定し @code{-1} を返します。
@end deffn

@geindex PyMarshal_ReadShortFromFile (C function)
@anchor{c-api/marshal c PyMarshal_ReadShortFromFile}@anchor{5234}
@deffn {C の関数} int PyMarshal_ReadShortFromFile (FILE *file)

読み出し用に開かれた FILE* 内のデータストリームから、 C の short 型データを読み出して返します。この関数は、ネイティブの short のサイズに関係なく、 16 ビットの値だけを読み出せます。

エラーの場合、適切な例外 (@ref{14f1,,EOFError}) を設定し @code{-1} を返します。
@end deffn

@geindex PyMarshal_ReadObjectFromFile (C function)
@anchor{c-api/marshal c PyMarshal_ReadObjectFromFile}@anchor{5235}
@deffn {C の関数} @ref{5df,,PyObject} *PyMarshal_ReadObjectFromFile (FILE *file)
`戻り値: 新しい参照。'
読み出し用に開かれた FILE* 内のデータストリームから Python オブジェクトを返します。

エラーの場合、適切な例外 (@ref{14f1,,EOFError}, @ref{2ec,,ValueError}, @ref{198,,TypeError}) を設定し @code{NULL} を返します。
@end deffn

@geindex PyMarshal_ReadLastObjectFromFile (C function)
@anchor{c-api/marshal c PyMarshal_ReadLastObjectFromFile}@anchor{5236}
@deffn {C の関数} @ref{5df,,PyObject} *PyMarshal_ReadLastObjectFromFile (FILE *file)
`戻り値: 新しい参照。'
Return a Python object from the data stream in a FILE* opened for
reading.  Unlike @ref{5235,,PyMarshal_ReadObjectFromFile()}, this function
assumes that no further objects will be read from the file, allowing it to
aggressively load file data into memory so that the de-serialization can
operate from data in memory rather than reading a byte at a time from the
file.  Only use this variant if you are certain that you won't be reading
anything else from the file.

エラーの場合、適切な例外 (@ref{14f1,,EOFError}, @ref{2ec,,ValueError}, @ref{198,,TypeError}) を設定し @code{NULL} を返します。
@end deffn

@geindex PyMarshal_ReadObjectFromString (C function)
@anchor{c-api/marshal c PyMarshal_ReadObjectFromString}@anchor{99b}
@deffn {C の関数} @ref{5df,,PyObject} *PyMarshal_ReadObjectFromString (const char *data, Py_ssize_t len)
`戻り値: 新しい参照。'
`data' が指す `len' バイトのバイト列バッファ内のデータストリームから Python オブジェクトを返します。

エラーの場合、適切な例外 (@ref{14f1,,EOFError}, @ref{2ec,,ValueError}, @ref{198,,TypeError}) を設定し @code{NULL} を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 引数の解釈と値の構築,文字列の変換と書式化,データ整列化 data marshalling のサポート,ユーティリティ<2>
@anchor{c-api/arg doc}@anchor{5237}@anchor{c-api/arg arg-parsing}@anchor{3d5}@anchor{c-api/arg parsing-arguments-and-building-values}@anchor{5238}@anchor{c-api/arg translation-repo}@anchor{5239}
@subsection 引数の解釈と値の構築


These functions are useful when creating your own extension functions and
methods.  Additional information and examples are available in
@ref{1fbd,,Python インタプリタの拡張と埋め込み}.

最初に説明する 3 つの関数、 @ref{3c1,,PyArg_ParseTuple()}, @ref{624,,PyArg_ParseTupleAndKeywords()},および @ref{180e,,PyArg_Parse()} はいずれも `書式文字列 (format string)' を使います。書式文字列は、関数が受け取るはずの引数に関する情報を伝えるのに用いられます。いずれの関数における書式文字列も、同じ書式を使っています。

@menu
* 引数を解析する: 引数を解析する<2>. 
* 値の構築:: 

@end menu

@node 引数を解析する<2>,値の構築,,引数の解釈と値の構築
@anchor{c-api/arg parsing-arguments}@anchor{523a}
@subsubsection 引数を解析する


書式文字列は、ゼロ個またはそれ以上の "書式単位 (format unit)" から成り立ちます。 1つの書式単位は1つの Python オブジェクトを表します; 通常は単一の文字か、書式単位からなる文字列を括弧で囲ったものになります。例外として、括弧で囲われていない書式単位文字列が単一のアドレス引数に対応する場合がいくつかあります。以下の説明では、引用符のついた形式は書式単位です; (丸)括弧で囲った部分は書式単位に対応する Python のオブジェクト型です; [角] 括弧は値をアドレス渡しする際に使う C の変数型です。

@menu
* 文字列とバッファ:: 
* 数: 数<2>. 
* その他のオブジェクト:: 
* API 関数:: 

@end menu

@node 文字列とバッファ,数<2>,,引数を解析する<2>
@anchor{c-api/arg arg-parsing-string-and-buffers}@anchor{62c}@anchor{c-api/arg strings-and-buffers}@anchor{523b}
@subsubsection 文字列とバッファ


@cartouche
@quotation 注釈 
Python 3.12 以前では、以下で説明された全ての @code{#} の種類 (@code{s#}, @code{y#} など) を使用するために @code{PY_SSIZE_T_CLEAN} マクロを @code{Python.h} のインクルードの前に定義しなければなりません。これは Python 3.13 以降では不要です。
@end quotation
@end cartouche

以下のフォーマットはオブジェクトに連続したメモリチャンクとしてアクセスするためのものです。返される unicode や bytes のために生のストレージを用意する必要はありません。

特に言及されていない場合、バッファーは NUL 終端されていません。

文字列とバッファをCに変換する方法は3つあります：


@itemize *

@item 
形式としては @code{y*} そして @code{s*} 埋める @ref{95c,,Py_buffer} 構造体。これはロックします 根底 バッファ これにより、呼び出し元はその後、バッファを内部でも使用できるようになります:c:type:@cite{Py_BEGIN_ALLOW_THREADS}  ブロック リスクなしに 可変 データが再サイズ化または破壊される。その結果、`電話をかけなければならない' @ref{63b,,PyBuffer_Release()} データ処理が完了した後（または早期終了の場合）。

@item 
その @code{es}, @code{es#}, @code{et} そして @code{et#} フォーマットは結果を割り当てます バッファ. `必ず電話をかけてください' @ref{165b,,PyMem_Free()} データ処理が完了した後（または早期終了の場合）。

@item @anchor{c-api/arg c-arg-borrowed-buffer}@anchor{3d6}
他の形式では @ref{169,,str} または 読み出し専用 bytes-like オブジェクト、例えば   @ref{192,,bytes}, および提供する @code{const char *} ポインタ その バッファ. この場合 バッファ「借用」されています：これは対応するPythonオブジェクトによって管理され、このオブジェクトのライフサイクルを共有します。メモリを自分で解放する必要はありません。

以下のことを確実にするため 根底 バッファ 安全に借りることができます, 対象の @ref{967,,PyBufferProcs.bf_releasebuffer} フィールドは必須です。 @code{NULL}. これは一般的な 可変 次のようなオブジェクト @ref{344,,bytearray}, また、いくつかの 読み出し専用 次のようなオブジェクト @ref{165,,memoryview} の @ref{192,,bytes}.

これに加えて @code{bf_releasebuffer}  要件として、入力が有効かどうかを確認するチェックはありません 対象は 不変 （例：請求に応じるかどうか 書き込み可能 バッファ,  または、別のスレッドがデータを変更できるかどうか)。
@end itemize


@table @asis

@item @code{s} (@ref{169,,str}) [const char *]

Unicode オブジェクトを、キャラクタ文字列を指す C のポインタに変換します。キャラクタ型ポインタ変数のアドレスを渡すと、すでに存在している文字列へのポインタをその変数に記録します。C 文字列は NUL で終端されています。Python の文字列型は、 null コードポイントが途中に埋め込まれていてはなりません; もし埋め込まれていれば @ref{2ec,,ValueError} 例外を送出します。Unicode オブジェクトは @code{'utf-8'} を使って C 文字列に変換されます。変換に失敗すると @ref{462,,UnicodeError} を送出します。

@cartouche
@quotation 注釈 
このフォーマットは @ref{193,,bytes-like objects} をサポートしません。
ファイルシステムパスを受け取って C 言語の文字列に変換したい場合は、 @code{O&} フォーマットを、
`converter' に @ref{f15,,PyUnicode_FSConverter()} を指定して利用すると良いです。
@end quotation
@end cartouche


バージョン 3.5 で変更: 以前は Python 文字列に null コードポイントが埋め込まれていたときに @ref{198,,TypeError} を送出していました。


@item @code{s*} (@ref{169,,str} または @ref{193,,bytes-like object}) [Py_buffer]

このフォーマットは Unicode オブジェクトと bytes-like object を受け付けて、呼び出し元から渡された @ref{95c,,Py_buffer} 構造体に値を格納します。
結果の C 文字列は NUL バイトを含むかもしれません。
Unicode オブジェクトは @code{'utf-8'} エンコーディングで C 文字列に変換されます。

@item @code{s#} (@ref{169,,str}, 読み取り専用の @ref{193,,bytes-like object}) [const char *, @ref{c55,,Py_ssize_t}]

のように @code{s*}, ただし、それは @ref{3d6,,借用された バッファ}. 結果は2つのC変数に格納されます。最初の変数はC文字列へのポインター、2つ目の変数はその長さです。文字列には埋め込まれたヌルバイトが含まれる可能性があります。Unicodeオブジェクトは、C文字列に変換されます @code{'utf-8'} エンコード。

@item @code{z} (@ref{169,,str} または @code{None}) [const char *]

@code{s} に似ていますが、Python オブジェクトは @code{None} でもよく、その場合には C のポインタは @code{NULL} にセットされます。

@item @code{z*} (@ref{169,,str}, @ref{193,,bytes-like object} または @code{None}) [Py_buffer]

@code{s*} と同じですが、 Python の @code{None} オブジェクトを受け取ることができます。その場合、 @ref{95c,,Py_buffer} 構造体の @code{buf} メンバーは @code{NULL} になります。

@item @code{z#} (@ref{169,,str}, 読み出し専用の @ref{193,,bytes-like object} または @code{None}) [const char *, @ref{c55,,Py_ssize_t}]

@code{s#} に似ていますが、Python オブジェクトは @code{None} でもよく、その場合には C のポインタは @code{NULL} にセットされます。

@item @code{y} (読み出し専用の @ref{193,,bytes-like object}) [const char *]

この形式は bytes-like Cポインタへのオブジェクトへの参照を拒否する @ref{3d6,,borrowed} 文字列; Unicode オブジェクトは受け付けません。 バイトバッファには埋め込みのヌルバイトを含んではいけません。もし含まれている場合 @ref{2ec,,ValueError} 例外が発生します。


バージョン 3.5 で変更: 以前は bytes バッファにヌルバイトが埋め込まれていたときに @ref{198,,TypeError} を送出していました。


@item @code{y*} (@ref{193,,bytes-like object}) [Py_buffer]

@code{s*} の変形で、 Unicode オブジェクトを受け付けず、 bytes-like object のみを受け付けます。
`バイナリデータを受け付ける目的には、このフォーマットを使うことを推奨します。'

@item @code{y#} (読み出し専用の @ref{193,,bytes-like object}) [const char *, @ref{c55,,Py_ssize_t}]

@code{s#} の変形で、 Unicode オブジェクトを受け付けず、bytes-like object だけを受け付けます。

@item @code{S} (@ref{192,,bytes}) [PyBytesObject *]

Pythonオブジェクトとして、 @ref{192,,bytes} オブジェクトを要求し、いかなる変換も行いません。オブジェクトが bytes オブジェクトでなければ、 @ref{198,,TypeError} を送出します。C 変数は @ref{5df,,PyObject}* と宣言しても構いません。

@item @code{Y} (@ref{344,,bytearray}) [PyByteArrayObject *]

Python オブジェクトとして @ref{344,,bytearray} オブジェクトを要求し、いかなる変換もおこないません。 もしオブジェクトが @ref{344,,bytearray} でなければ、 @ref{198,,TypeError} を送出します。C 変数は @ref{5df,,PyObject}* として宣言しても構いません。

@item @code{U} (@ref{169,,str}) [PyObject *]

Python オブジェクトとして Unicode オブジェクトを要求し、いかなる変換も行いません。オブジェクトが Unicode オブジェクトではない場合、 @ref{198,,TypeError} が送出されます。C変数は @ref{5df,,PyObject}* として宣言しても構いません。

@item @code{w*} (読み書き可能な @ref{193,,bytes-like object}) [Py_buffer]

This format accepts any object which implements the read-write buffer
interface. It fills a @ref{95c,,Py_buffer} structure provided by the caller.
The buffer may contain embedded null bytes. The caller has to call
@ref{63b,,PyBuffer_Release()} when it is done with the buffer.

@item @code{es} (@ref{169,,str}) [const char *encoding, char **buffer]

これは @code{s} の変化形で、Unicodeをキャラクタ型バッファにエンコードするために用いられます。NULバイトが埋め込まれていないデータでのみ動作します。

この書式には二つの引数が必要です。一つ目は入力にのみ用いられ、 NUL で終端されたエンコード名文字列を指す const char* 型または、 @code{'utf-8'} が使われることを表す @code{NULL} でなければなりません。指定したエンコード名を Python が理解できない場合には例外を送出します。第二の引数は char** でなければなりません; この引数が参照しているポインタの値は、引数に指定したテキストの内容が入ったバッファへのポインタになります。テキストは最初の引数に指定したエンコード方式でエンコードされます。

@ref{3c1,,PyArg_ParseTuple()} を使うと、必要なサイズのバッファを確保し、そのバッファにエンコード後のデータをコピーして、 `*buffer' がこの新たに確保された記憶領域を指すように変更します。呼び出し側には、確保されたバッファを使い終わった後に @ref{165b,,PyMem_Free()} で解放する責任があります。

@item @code{et} (@ref{169,,str}, @ref{192,,bytes} または @ref{344,,bytearray}) [const char *encoding, char **buffer]

@code{es} と同じです。ただし、バイト文字列オブジェクトをエンコードし直さずに渡します。その代わり、実装ではバイト文字列オブジェクトがパラメタに渡したエンコードを使っているものと仮定します。

@item @code{es#} (@ref{169,,str}) [const char *encoding, char **buffer, @ref{c55,,Py_ssize_t} *buffer_length]

@code{s#} の変化形で、Unicode をキャラクタ型バッファにエンコードするために用いられます。@code{es} 書式違って、この変化形はバイトが埋め込まれていてもかまいません。

この書式には三つの引数が必要です。一つ目は入力にのみ用いられ、 NUL で終端されたエンコード名文字列を指す const char* 型か @code{NULL} でなければなりません。 @code{NULL} の場合には @code{'utf-8'} を使います。指定したエンコード名を Python が理解できない場合には例外を送出します。第二の引数は char** でなければなりません; この引数が参照しているポインタの値は、引数に指定したテキストの内容が入ったバッファへのポインタになります。テキストは最初の引数に指定したエンコード方式でエンコードされます。第三の引数は整数へのポインタでなければなりません; ポインタが参照している整数の値は出力バッファ内のバイト数にセットされます。

この書式の処理には二つのモードがあります:

`*buffer' が @code{NULL} ポインタを指している場合、関数は必要なサイズのバッファを確保し、そのバッファにエンコード後のデータをコピーして、 `*buffer' がこの新たに確保された記憶領域を指すように変更します。呼び出し側には、確保されたバッファを使い終わった後に @ref{165b,,PyMem_Free()} で解放する責任があります。

`*buffer' が非 @code{NULL} のポインタ (すでにメモリ確保済みのバッファ) を指している場合、 @ref{3c1,,PyArg_ParseTuple()} はこのメモリ位置をバッファとして用い、 `*buffer_length' の初期値をバッファサイズとして用います。 PyArg_ParseTuple は次にエンコード済みのデータをバッファにコピーして、NUL で終端します。バッファの大きさが足りなければ @ref{2ec,,ValueError} がセットされます。

どちらの場合も、 `*buffer_length' は終端の NUL バイトを含まないエンコード済みデータの長さにセットされます。

@item @code{et#} (@ref{169,,str}, @ref{192,,bytes} または @ref{344,,bytearray}) [const char *encoding, char **buffer, @ref{c55,,Py_ssize_t} *buffer_length]

@code{es#} と同じです。ただし、バイト文字列オブジェクトをエンコードし直さずに渡します。その代わり、実装ではバイト文字列オブジェクトがパラメタに渡したエンコードを使っているものと仮定します。
@end table


バージョン 3.12 で変更: @code{u}, @code{u#}, @code{Z}, and @code{Z#} are removed because they used a legacy
@code{Py_UNICODE*} representation.


@node 数<2>,その他のオブジェクト,文字列とバッファ,引数を解析する<2>
@anchor{c-api/arg numbers}@anchor{523c}
@subsubsection 数


These formats allow representing Python numbers or single characters as C numbers.
Formats that require @ref{19b,,int}, @ref{196,,float} or @ref{197,,complex} can
also use the corresponding special methods @ref{19e,,__index__()},
@ref{bc1,,__float__()} or @ref{7fd,,__complex__()} to convert
the Python object to the required type.

For signed integer formats, @ref{a81,,OverflowError} is raised if the value
is out of range for the C type.
For unsigned integer formats, no range checking is done --- the
most significant bits are silently truncated when the receiving field is too
small to receive the value.


@table @asis

@item @code{b} (@ref{19b,,int}) [unsigned char]

Convert a nonnegative Python integer to an unsigned tiny integer, stored in a C
unsigned char.

@item @code{B} (@ref{19b,,int}) [unsigned char]

Convert a Python integer to a tiny integer without overflow checking, stored in a C
unsigned char.

@item @code{h} (@ref{19b,,int}) [short int]

Python の整数を、 C の short int 型に変換します。

@item @code{H} (@ref{19b,,int}) [unsigned short int]

Python の整数を、オーバフローチェックを行わずに、 C の unsigned short int 型に変換します。

@item @code{i} (@ref{19b,,int}) [int]

Python の整数を、 C の int 型に変換します。

@item @code{I} (@ref{19b,,int}) [unsigned int]

Python の整数を、オーバフローチェックを行わずに、 C の unsigned int 型に変換します。

@item @code{l} (@ref{19b,,int}) [long int]

Python の整数を、 C の long int 型に変換します。

@item @code{k} (@ref{19b,,int}) [unsigned long]

Python の整数を、オーバフローチェックを行わずに、 C の unsigned long 型に変換します。


バージョン 3.14 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。


@item @code{L} (@ref{19b,,int}) [long long]

Python の整数を、 C の long long 型に変換します。

@item @code{K} (@ref{19b,,int}) [unsigned long long]

PythonのintをC unsigned long long へオーバーフローの確認をせず変換する


バージョン 3.14 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。


@item @code{n} (@ref{19b,,int}) [@ref{c55,,Py_ssize_t}]

Python の整数をCの @ref{c55,,Py_ssize_t} 型に変換します。

@item @code{c} (長さ 1 の、 @ref{192,,bytes} または @ref{344,,bytearray}) [char]

長さ 1 の @ref{192,,bytes} または @ref{344,,bytearray} オブジェクトとして表現されている Python バイトを C の char 型に変換します。


バージョン 3.3 で変更: @ref{344,,bytearray} を受け付けるようになりました。


@item @code{C} (長さ 1 の @ref{169,,str}) [int]

長さ 1 の @ref{169,,str} オブジェクトとして表現されている Python キャラクタを C の int 型に変換します。

@item @code{f} (@ref{196,,float}) [float]

Convert a Python floating-point number to a C float.

@item @code{d} (@ref{196,,float}) [double]

Convert a Python floating-point number to a C double.

@item @code{D} (@ref{197,,complex}) [Py_complex]

Python の複素数型を、 C の @ref{523d,,Py_complex} 構造体に変換します。
@end table

@node その他のオブジェクト,API 関数,数<2>,引数を解析する<2>
@anchor{c-api/arg other-objects}@anchor{523e}
@subsubsection その他のオブジェクト



@table @asis

@item @code{O} (object) [PyObject *]

Python オブジェクトを（変換なしで）C オブジェクトのポインターに格納します。 これにより、C プログラムは渡された実際のオブジェクトを受け取ります。新しい :term: 強参照 オブジェクトが作成されていません （すなわち、その参照カウント 増加しません)。その ポインタ 保存されていない @code{NULL}.

@item @code{O!} (object) [`typeobject', PyObject *]

Python オブジェクトを C の Python オブジェクト型ポインタに保存します。 @code{O} に似ていますが、二つの C の引数をとります: 一つ目の引数は Python の型オブジェクトへのアドレスで、二つ目の引数はオブジェクトへのポインタが保存されている (@ref{5df,,PyObject}* の) C の変数へのアドレスです。Python オブジェクトが指定した型ではない場合、 @ref{198,,TypeError} を送出します。
@end table
@anchor{c-api/arg o-ampersand}@anchor{523f}

@table @asis

@item @code{O&} (object) [`converter', `address']

Python オブジェクトを `converter' 関数を介して C の変数に変換します。二つの引数をとります: 一つ目は関数で、二つ目は (任意の型の) C 変数へのアドレスを void* 型に変換したものです。 `converter' は以下のようにして呼び出されます:

@example
status = converter(object, address);
@end example

ここで `object' は変換対象の Python オブジェクトで、 `address' は @code{PyArg_Parse*} に渡した void*  型の引数です。戻り値 `status' は変換に成功した際に @code{1},失敗した場合には @code{0} になります。変換に失敗した場合、 `converter' 関数は `address' の内容を変更せずに例外を送出しなくてはなりません。

@geindex Py_CLEANUP_SUPPORTED (C macro)
@anchor{c-api/arg c Py_CLEANUP_SUPPORTED}@anchor{5240}
If the `converter' returns @code{Py_CLEANUP_SUPPORTED}, it may get called a
second time if the argument parsing eventually fails, giving the converter a
chance to release any memory that it had already allocated. In this second
call, the `object' parameter will be @code{NULL}; `address' will have the same value
as in the original call.

Examples of converters: @ref{f15,,PyUnicode_FSConverter()} and
@ref{797,,PyUnicode_FSDecoder()}.


バージョン 3.1 で変更: @code{Py_CLEANUP_SUPPORTED} was added.


@item @code{p} (@ref{3c3,,bool}) [int]

真偽値が求められる箇所 (a boolean `p'redicate) に渡された値を判定し、その結果を等価な C の true/false 整数値に変換します。
もし式が真なら int には @code{1} が、偽なら @code{0} が設定されます。この関数は任意の有効なPython値を受け付けます。
Pythonが値の真偽をどのように判定するかを知りたければ、 @ref{1858,,真理値判定} を参照してください。


Added in version 3.3.


@item @code{(items)} (sequence) [`matching-items']

The object must be a Python sequence (except @ref{169,,str}, @ref{192,,bytes}
or @ref{344,,bytearray}) whose length is the number of format units
in `items'.  The C arguments must correspond to the individual format units in
`items'.  Format units for sequences may be nested.

If `items' contains format units which store a @ref{3d6,,borrowed buffer} (@code{s}, @code{s#}, @code{z}, @code{z#}, @code{y}, or @code{y#})
or a @ref{3d7,,borrowed reference} (@code{S}, @code{Y}, @code{U}, @code{O}, or @code{O!}),
the object must be a Python tuple.
The `converter' for the @code{O&} format unit in `items' must not store
a borrowed buffer or a borrowed reference.


バージョン 3.14 で変更: @ref{169,,str} and @ref{344,,bytearray} objects no longer accepted as a sequence.



バージョン 3.14 で非推奨: Non-tuple sequences are deprecated if `items' contains format units
which store a borrowed buffer or a borrowed reference.

@end table

その他、書式文字列において意味を持つ文字がいくつかあります。それらの文字は括弧による入れ子内には使えません。以下に文字を示します:


@table @asis

@item @code{|}

Python 引数リスト中で、この文字以降の引数がオプションであることを示します。オプションの引数に対応する C の変数はデフォルトの値で初期化しておかなければなりません --- オプションの引数が省略された場合、 @ref{3c1,,PyArg_ParseTuple()} は対応する C 変数の内容に手を加えません。

@item @code{$}

@ref{624,,PyArg_ParseTupleAndKeywords()} でのみ使用可能: 後続のPython引数がキーワード専用であることを示します。
現在、すべてのキーワード専用引数は任意の引数でなければならず、そのため フォーマット文字列中の @code{|} は常に @code{$} より前に指定されなければなりません。


Added in version 3.3.


@item @code{:}

この文字があると、書式単位の記述はそこで終わります; コロン以降の文字列は、エラーメッセージにおける関数名 (@ref{3c1,,PyArg_ParseTuple()} が送出する例外の "付属値 (associated value)") として使われます。

@item @code{;}

この文字があると、書式単位の記述はそこで終わります; セミコロン以降の文字列は、デフォルトエラーメッセージを `置き換える' エラーメッセージとして使われます。 @code{:} と @code{;} は相互に排他の文字です。
@end table

注意：呼び出し元に渡されるPythonオブジェクトの参照はすべて*借用*された参照です。これらを解放しないでください（つまり、参照カウントを減らさないでください）！

以下の関数に渡す補助引数 (additional argument) は、書式文字列から決定される型へのアドレスでなければなりません; 補助引数に指定したアドレスは、タプルから入力された値を保存するために使います。上の書式単位のリストで説明したように、補助引数を入力値として使う場合がいくつかあります; その場合、対応する書式単位の指定する形式に従うようにしなければなりません。

変換を正しく行うためには、 `arg' オブジェクトは書式文字に一致しなければならず、かつ書式文字列内の書式単位に全て値が入るようにしなければなりません。成功すると、 @code{PyArg_Parse*} 関数は真を返します。それ以外の場合には偽を返し、適切な例外を送出します。書式単位のどれかの変換失敗により @code{PyArg_Parse*} が失敗した場合、失敗した書式単位に対応するアドレスとそれ以降のアドレスの内容は変更されません。

@node API 関数,,その他のオブジェクト,引数を解析する<2>
@anchor{c-api/arg api-functions}@anchor{5241}
@subsubsection API 関数


@geindex PyArg_ParseTuple (C function)
@anchor{c-api/arg c PyArg_ParseTuple}@anchor{3c1}
@deffn {C の関数} int PyArg_ParseTuple (PyObject *args, const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
位置引数のみを引数にとる関数のパラメタを解釈して、ローカルな変数に変換します。成功すると真を返します;失敗すると偽を返し、適切な例外を送出します。
@end deffn

@geindex PyArg_VaParse (C function)
@anchor{c-api/arg c PyArg_VaParse}@anchor{4f64}
@deffn {C の関数} int PyArg_VaParse (PyObject *args, const char *format, va_list vargs)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{3c1,,PyArg_ParseTuple()} と同じですが、可変長の引数ではなく `va_list' を引数にとります。
@end deffn

@geindex PyArg_ParseTupleAndKeywords (C function)
@anchor{c-api/arg c PyArg_ParseTupleAndKeywords}@anchor{624}
@deffn {C の関数} int PyArg_ParseTupleAndKeywords (PyObject *args, PyObject *kw, const char *format, char *const *keywords, ...)
` 次に属します: @ref{775,,Stable ABI}.'
Parse the parameters of a function that takes both positional and keyword
parameters into local variables.
The `keywords' argument is a @code{NULL}-terminated array of keyword parameter
names specified as null-terminated ASCII or UTF-8 encoded C strings.
Empty names denote
@ref{c78,,positional-only parameters}.
Returns true on success; on failure, it returns false and raises the
appropriate exception.

@cartouche
@quotation 注釈 
The `keywords' parameter declaration is char *const* in C and
const char *const* in C++.
This can be overridden with the @ref{626,,PY_CXX_CONST} macro.
@end quotation
@end cartouche


バージョン 3.6 で変更: @ref{c78,,位置専用引数} を追加した。



バージョン 3.13 で変更: The `keywords' parameter has now type char *const* in C and
const char *const* in C++, instead of char**.
Added support for non-ASCII keyword parameter names.

@end deffn

@geindex PyArg_VaParseTupleAndKeywords (C function)
@anchor{c-api/arg c PyArg_VaParseTupleAndKeywords}@anchor{625}
@deffn {C の関数} int PyArg_VaParseTupleAndKeywords (PyObject *args, PyObject *kw, const char *format, char *const *keywords, va_list vargs)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{624,,PyArg_ParseTupleAndKeywords()} と同じですが、可変長の引数ではなく `va_list' を引数にとります。
@end deffn

@geindex PyArg_ValidateKeywordArguments (C function)
@anchor{c-api/arg c PyArg_ValidateKeywordArguments}@anchor{4f65}
@deffn {C の関数} int PyArg_ValidateKeywordArguments (PyObject*)
` 次に属します: @ref{775,,Stable ABI}.'
キーワード引数を格納した辞書のキーが文字列であることを確認します。この関数は @ref{624,,PyArg_ParseTupleAndKeywords()} を使用しないときにのみ必要で、その理由は後者の関数は同様のチェックを実施するためです。


Added in version 3.2.

@end deffn

@geindex PyArg_Parse (C function)
@anchor{c-api/arg c PyArg_Parse}@anchor{180e}
@deffn {C の関数} int PyArg_Parse (PyObject *args, const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
Parse the parameter of a function that takes a single positional parameter
into a local variable.  Returns true on success; on failure, it returns
false and raises the appropriate exception.

以下はプログラム例です:

@example
// Function using METH_O calling convention
static PyObject*
my_function(PyObject *module, PyObject *arg)
@{
    int value;
    if (!PyArg_Parse(arg, "i:my_function", &value)) @{
        return NULL;
    @}
    // ... use value ...
@}
@end example
@end deffn

@geindex PyArg_UnpackTuple (C function)
@anchor{c-api/arg c PyArg_UnpackTuple}@anchor{171f}
@deffn {C の関数} int PyArg_UnpackTuple (PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
` 次に属します: @ref{775,,Stable ABI}.'
パラメーターの取得方法のよりシンプルな形式で、使用しないもの a 書式文字列 引数の型を指定する 。関数 これを使用する メソッド 彼らの パラメータ 次のように宣言する必要があります @ref{1721,,METH_VARARGS} に 関数 にメソッド テーブル。実際のパラメーターを含むタプルは `args' として渡す必要があります。必ずタプルでなければなりません。タプルの長さは、`min*以上で*max*以下でなければなりません。*min*と*max*は等しい場合もあります。関数には追加の引数を渡す必要があり、各引数はポインターでなければならない ～へ:c:expr:`PyObject*` 変数；これらは*args*の値で埋められる；これらは:term:を含む :term:`借用参照 <borrowed reference>`。*args' で指定されていないオプションパラメーターに対応する変数は初期化されません。これらの変数は呼び出し元で初期化する必要があります。これ 関数 成功した場合にtrueを返し、>>*<<args*がタプルでない場合または要素の数が間違っている場合にfalseを返します。失敗した場合、例外が設定されます。

これは、この関数の使用例で、ソースコードから抜粋したものです:mod:>>`<<!_weakref`弱参照用のヘルパーモジュール:

@example
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
@{
    PyObject *object;
    PyObject *callback = NULL;
    PyObject *result = NULL;

    if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) @{
        result = PyWeakref_NewRef(object, callback);
    @}
    return result;
@}
@end example

この例における @ref{171f,,PyArg_UnpackTuple()} 呼び出しは、 @ref{3c1,,PyArg_ParseTuple()} を使った以下の呼び出しと全く等価です:

@example
PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
@end example
@end deffn

@geindex PY_CXX_CONST (C macro)
@anchor{c-api/arg c PY_CXX_CONST}@anchor{626}
@deffn {C のマクロ} PY_CXX_CONST

The value to be inserted, if any, before char *const*
in the `keywords' parameter declaration of
@ref{624,,PyArg_ParseTupleAndKeywords()} and
@ref{625,,PyArg_VaParseTupleAndKeywords()}.
Default empty for C and @code{const} for C++
(const char *const*).
To override, define it to the desired value before including
@code{Python.h}.


Added in version 3.13.

@end deffn

@node 値の構築,,引数を解析する<2>,引数の解釈と値の構築
@anchor{c-api/arg building-values}@anchor{5242}
@subsubsection 値の構築


@geindex Py_BuildValue (C function)
@anchor{c-api/arg c Py_BuildValue}@anchor{3c2}
@deffn {C の関数} @ref{5df,,PyObject} *Py_BuildValue (const char *format, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@code{PyArg_Parse*} ファミリの関数が受け取るのと似た形式の書式文字列および値列に基づいて、新たな値を生成します。生成した値を返します。エラーの場合には @code{NULL} を返します; @code{NULL} を返す場合、例外を送出するでしょう。

@ref{3c2,,Py_BuildValue()} は常にタプルを生成するとは限りません。この関数がタプルを生成するのは、書式文字列に二つ以上の書式単位が入っているときだけです。書式文字列が空の場合 @code{None} を返します; 書式単位が厳密に一つだけ入っている場合、書式単位で指定されている何らかのオブジェクト単体を返します。サイズがゼロや 1 のタプルを返すように強制するには、丸括弧で囲われた書式文字列を使います。

書式単位 @code{s} や @code{s#} の場合のように、オブジェクトを構築する際にデータを供給するためにメモリバッファをパラメタとして渡す場合には、指定したデータはコピーされます。 @ref{3c2,,Py_BuildValue()} が生成したオブジェクトは、呼び出し側が提供したバッファを決して参照しません。別の言い方をすれば、 @code{malloc()} を呼び出してメモリを確保し、それを @ref{3c2,,Py_BuildValue()} に渡した場合、コード内で @ref{3c2,,Py_BuildValue()} が返った後で @code{free()} を呼び出す責任があるということです。

以下の説明では、引用符のついた形式は書式単位です; (丸)括弧で囲った部分は書式単位が返す Python のオブジェクト型です; [角] 括弧は関数に渡す値の C 変数型です。

書式文字列内では、(@code{s#} のような書式単位を除いて) スペース、タブ、コロンおよびコンマは無視されます。これらの文字を使うと、長い書式文字列をちょっとだけ読みやすくできます。


@table @asis

@item @code{s} (@ref{169,,str} または @code{None}) [const char *]

null終端された C 文字列を、 @code{'utf-8'} エンコーディングを用いて、 Python @ref{169,,str} オブジェクトに変換します。もし C 文字列ポインタが @code{NULL} の場合、 @code{None} になります。

@item @code{s#} (@ref{169,,str} or @code{None}) [const char *, @ref{c55,,Py_ssize_t}]

C 文字列とその長さを @code{'utf-8'} エンコーディングを使って Python @ref{169,,str} オブジェクトに変換します。C 文字列ポインタが @code{NULL} の場合、長さは無視され、 @code{None} になります。

@item @code{y} (@ref{192,,bytes}) [const char *]

C 文字列をPython @ref{192,,bytes} オブジェクトに変換します。もしC 文字列ポインタが @code{NULL} だった場合、@code{None} を返します。

@item @code{y#} (@ref{192,,bytes}) [const char *, @ref{c55,,Py_ssize_t}]

これは C 文字列とその長さから Python オブジェクトに変換します。C 文字列ポインタが @code{NULL} の場合、長さは無視され @code{None} になります。

@item @code{z} (@ref{169,,str} または @code{None}) [const char *]

@code{s} と同じです。

@item @code{z#} (@ref{169,,str} または @code{None}) [const char *, @ref{c55,,Py_ssize_t}]

@code{s#} と同じです。

@item @code{u} (@ref{169,,str}) [const wchar_t *]

null 終端された Unicode (UTF-16 または UCS-4) データの @code{wchar_t} バッファから Python Unicode オブジェクトに変換します。 Unicode バッファポインタが @code{NULL} の場合、 @code{None} になります。

@item @code{u#} (@ref{169,,str}) [const wchar_t *, @ref{c55,,Py_ssize_t}]

Unicode (UTF-16 または UCS-4) データのバッファとその長さから Python Unicode オブジェクトに変換します。 Unicode バッファポインタが @code{NULL} の場合、長さは無視され @code{None} になります。

@item @code{U} (@ref{169,,str} または @code{None}) [const char *]

@code{s} と同じです。

@item @code{U#} (@ref{169,,str} または @code{None}) [const char *, @ref{c55,,Py_ssize_t}]

@code{s#} と同じです。

@item @code{i} (@ref{19b,,int}) [int]

通常の C の int を Python の整数オブジェクトに変換します。

@item @code{b} (@ref{19b,,int}) [char]

通常のC の char を Python の整数オブジェクトに変換します。

@item @code{h} (@ref{19b,,int}) [short int]

通常のC の short int を Python の整数オブジェクトに変換します。

@item @code{l} (@ref{19b,,int}) [long int]

C の long int を Python の整数オブジェクトに変換します。

@item @code{B} (@ref{19b,,int}) [unsigned char]

C の unsigned char を Python の整数オブジェクトに変換します。

@item @code{H} (@ref{19b,,int}) [unsigned short int]

C の unsigned short int を Python の整数オブジェクトに変換します。

@item @code{I} (@ref{19b,,int}) [unsigned int]

C の unsigned int を Python の整数オブジェクトに変換します。

@item @code{k} (@ref{19b,,int}) [unsigned long]

C の unsigned long を Python の整数オブジェクトに変換します。

@item @code{L} (@ref{19b,,int}) [long long]

C の long long を Python の整数オブジェクトに変換します。
@end table
@anchor{c-api/arg capi-py-buildvalue-format-k}@anchor{186b}

@table @asis

@item @code{K} (@ref{19b,,int}) [unsigned long long]

C unsigned long long をPythonのintオブジェクトへ変換する。

@item @code{n} (@ref{19b,,int}) [@ref{c55,,Py_ssize_t}]

C の @ref{c55,,Py_ssize_t} を Python の整数オブジェクトに変換します。

@item @code{p} (@ref{3c3,,bool}) [int]

Convert a C int to a Python @ref{3c3,,bool} object.

Be aware that this format requires an @code{int} argument.
Unlike most other contexts in C, variadic arguments are not coerced to
a suitable type automatically.
You can convert another type (for example, a pointer or a float) to a
suitable @code{int} value using @code{(x) ? 1 : 0} or @code{!!x}.


Added in version 3.14.


@item @code{c} (長さが 1 の @ref{192,,bytes}) [char]

バイトを表す通常の C の int を、長さ 1 の Python の @ref{192,,bytes} オブジェクトに変換します。

@item @code{C} (長さ 1 の @ref{169,,str}) [int]

文字を表す通常の C の int を、長さ 1 の Python の @ref{169,,str} オブジェクトに変換します。

@item @code{d} (@ref{196,,float}) [double]

Convert a C double to a Python floating-point number.

@item @code{f} (@ref{196,,float}) [float]

Convert a C float to a Python floating-point number.

@item @code{D} (@ref{197,,complex}) [Py_complex *]

C の @ref{523d,,Py_complex} 構造体を Python の複素数型に変換します。

@item @code{O} (object) [PyObject *]

Python オブジェクトをそのまま渡すものの、それに対する新しい 強参照 を作成する（つまり、その参照カウントが1増加します）。渡されたオブジェクトが @code{NULL} ポインタ, この問題は、引数を生成する呼び出しがエラーを検出し、例外を設定したため発生したものと推測されます。したがって、@ref{3c2,,Py_BuildValue()} 戻ってきます @code{NULL} しかし、そうはならない 送出 例外。 例外がまだ発生していない場合、@ref{795,,SystemError} 設定されています。

@item @code{S} (object) [PyObject *]

@code{O} と同じです。

@item @code{N} (object) [PyObject *]

同じです @code{O}, ただし、新しい 強参照 を作成しません。オブジェクトが引数リスト内のオブジェクトコンストラクターの呼び出しによって作成される場合に便利です。

@item @code{O&} (object) [`converter', `anything']

`anything' を `converter' 関数を介して Python オブジェクトに変換します。この関数は `anything' (void* と互換の型でなければなりません) を引数にして呼び出され、"新たな" オブジェクトを返すか、失敗した場合には @code{NULL} を返すようにしなければなりません。

@item @code{(items)} (@ref{614,,tuple}) [`matching-items']

C の値からなる配列を、同じ要素数を持つ Python のタプルに変換します。

@item @code{[items]} (@ref{24d,,list}) [`matching-items']

C の値からなる配列を、同じ要素数を持つ Python のリストに変換します。

@item @code{@{items@}} (@ref{183,,dict}) [`matching-items']

C の値からなる配列を Python の辞書に変換します。一連のペアからなる C の値が、それぞれキーおよび値となって辞書に追加されます。
@end table

書式文字列に関するエラーが生じると、 @ref{795,,SystemError} 例外をセットして @code{NULL} を返します。
@end deffn

@geindex Py_VaBuildValue (C function)
@anchor{c-api/arg c Py_VaBuildValue}@anchor{514a}
@deffn {C の関数} @ref{5df,,PyObject} *Py_VaBuildValue (const char *format, va_list vargs)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{3c2,,Py_BuildValue()} と同じですが、可変長引数の代わりに va_list を受け取ります。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 文字列の変換と書式化,Character classification and conversion,引数の解釈と値の構築,ユーティリティ<2>
@anchor{c-api/conversion doc}@anchor{5243}@anchor{c-api/conversion string-conversion}@anchor{5244}@anchor{c-api/conversion string-conversion-and-formatting}@anchor{5245}@anchor{c-api/conversion translation-repo}@anchor{5246}
@subsection 文字列の変換と書式化


数値変換と、書式化文字列出力のための関数群。

@geindex PyOS_snprintf (C function)
@anchor{c-api/conversion c PyOS_snprintf}@anchor{1722}
@deffn {C の関数} int PyOS_snprintf (char *str, size_t size, const char *format, ...)
` 次に属します: @ref{775,,Stable ABI}.'
書式文字列 `format' と追加の引数から、 `size' バイトを超えない文字列を `str' に出力します。 Unix man page の @code{snprintf(3)@footnote{https://manpages.debian.org/snprintf(3)}} を参照してください。
@end deffn

@geindex PyOS_vsnprintf (C function)
@anchor{c-api/conversion c PyOS_vsnprintf}@anchor{1723}
@deffn {C の関数} int PyOS_vsnprintf (char *str, size_t size, const char *format, va_list va)
` 次に属します: @ref{775,,Stable ABI}.'
書式文字列 `format' と可変長引数リスト `va' から、 `size' バイトを超えない文字列を `str' に出力します。 Unix man page の @code{vsnprintf(3)@footnote{https://manpages.debian.org/vsnprintf(3)}} を参照してください。
@end deffn

@ref{1722,,PyOS_snprintf()} と @ref{1723,,PyOS_vsnprintf()} は標準Cライブラリの @code{snprintf()} と @code{vsnprintf()} 関数をラップします。これらの関数の目的は、C標準ライブラリが保証していないコーナーケースでの動作を保証することです。

The wrappers ensure that @code{str[size-1]} is always @code{'\0'} upon return. They
never write more than `size' bytes (including the trailing @code{'\0'}) into str.
Both functions require that @code{str != NULL}, @code{size > 0}, @code{format != NULL}
and @code{size < INT_MAX}. Note that this means there is no equivalent to the C99
@code{n = snprintf(NULL, 0, ...)} which would determine the necessary buffer size.

これらの関数の戻り値 (以下では `rv' とします) は以下の意味を持ちます:


@itemize *

@item 
@code{0 <= rv < size} のとき、変換出力は成功して、(最後の @code{str[rv]} にある @code{'\0'} を除いて) `rv' 文字が `str' に出力された。

@item 
@code{rv >= size} のとき、変換出力は切り詰められており、成功するためには @code{rv + 1} バイトが必要だったことを示します。@code{str[size-1]} は @code{'\0'} です。

@item 
When @code{rv < 0}, the output conversion failed and @code{str[size-1]} is @code{'\0'} in
this case too, but the rest of `str' is undefined. The exact cause of the error
depends on the underlying platform.
@end itemize

以下の関数は locale 非依存な文字列から数値への変換を行ないます。

@geindex PyOS_strtoul (C function)
@anchor{c-api/conversion c PyOS_strtoul}@anchor{5085}
@deffn {C の関数} unsigned long PyOS_strtoul (const char *str, char **ptr, int base)
` 次に属します: @ref{775,,Stable ABI}.'
Convert the initial part of the string in @code{str} to an unsigned long value according to the given @code{base}, which must be between @code{2} and
@code{36} inclusive, or be the special value @code{0}.

Leading white space and case of characters are ignored.  If @code{base} is zero
it looks for a leading @code{0b}, @code{0o} or @code{0x} to tell which base.  If
these are absent it defaults to @code{10}.  Base must be 0 or between 2 and 36
(inclusive).  If @code{ptr} is non-@code{NULL} it will contain a pointer to the
end of the scan.

If the converted value falls out of range of corresponding return type,
range error occurs (@code{errno} is set to @code{ERANGE}) and
@code{ULONG_MAX} is returned.  If no conversion can be performed, @code{0}
is returned.

See also the Unix man page @code{strtoul(3)@footnote{https://manpages.debian.org/strtoul(3)}}.


Added in version 3.2.

@end deffn

@geindex PyOS_strtol (C function)
@anchor{c-api/conversion c PyOS_strtol}@anchor{5084}
@deffn {C の関数} long PyOS_strtol (const char *str, char **ptr, int base)
` 次に属します: @ref{775,,Stable ABI}.'
Convert the initial part of the string in @code{str} to an long value
according to the given @code{base}, which must be between @code{2} and @code{36}
inclusive, or be the special value @code{0}.

Same as @ref{5085,,PyOS_strtoul()}, but return a long value instead
and @code{LONG_MAX} on overflows.

See also the Unix man page @code{strtol(3)@footnote{https://manpages.debian.org/strtol(3)}}.


Added in version 3.2.

@end deffn

@geindex PyOS_string_to_double (C function)
@anchor{c-api/conversion c PyOS_string_to_double}@anchor{14ad}
@deffn {C の関数} double PyOS_string_to_double (const char *s, char **endptr, PyObject *overflow_exception)
` 次に属します: @ref{775,,Stable ABI}.'
文字列 @code{s} を double に変換します。失敗したときは Python の例外を発生させます。受け入れられる文字列は、 Python の @ref{196,,float()} コンストラクタが受け付ける文字列に準拠しますが、 @code{s} の先頭と末尾に空白文字があってはならないという部分が異なります。この変換は現在のロケールに依存しません。

@code{endptr} が @code{NULL} の場合、変換は文字列全体に対して行われます。文字列が正しい浮動小数点数の表現になっていない場合は @code{-1.0} を返して @ref{2ec,,ValueError} を発生させます。

endptr が @code{NULL} で無い場合、文字列を可能な範囲で変換して、@code{*endptr} に最初の変換されなかった文字へのポインタを格納します。文字列の先頭に正しい浮動小数点数の表現が無かった場合、@code{*endptr} を文字列の先頭に設定して、ValueError を発生させ、@code{-1.0} を返します。

If @code{s} represents a value that is too large to store in a float
(for example, @code{"1e500"} is such a string on many platforms) then
if @code{overflow_exception} is @code{NULL} return @code{Py_INFINITY} (with
an appropriate sign) and don't set any exception.  Otherwise,
@code{overflow_exception} must point to a Python exception object;
raise that exception and return @code{-1.0}.  In both cases, set
@code{*endptr} to point to the first character after the converted value.

それ以外のエラーが変換中に発生した場合(例えば out-of-memory エラー)、適切な Python の例外を設定して @code{-1.0} を返します。


Added in version 3.1.

@end deffn

@geindex PyOS_double_to_string (C function)
@anchor{c-api/conversion c PyOS_double_to_string}@anchor{5082}
@deffn {C の関数} char *PyOS_double_to_string (double val, char format_code, int precision, int flags, int *ptype)
` 次に属します: @ref{775,,Stable ABI}.'
double `val' を指定された `format_code', `precision', `flags' に基づいて文字列に変換します。

`format_code' は @code{'e'}, @code{'E'}, @code{'f'}, @code{'F'}, @code{'g'}, @code{'G'}, @code{'r'} のどれかでなければなりません。 @code{'r'} の場合、 `precision' は 0 でなければならず、無視されます。 @code{'r'} フォーマットコードは標準の @ref{1c1,,repr()} フォーマットを指定しています。

`flags' can be zero or more of the following values or-ed together:

@geindex Py_DTSF_SIGN (C macro)
@anchor{c-api/conversion c Py_DTSF_SIGN}@anchor{5247}
@deffn {C のマクロ} Py_DTSF_SIGN

Always precede the returned string with a sign
character, even if `val' is non-negative.
@end deffn

@geindex Py_DTSF_ADD_DOT_0 (C macro)
@anchor{c-api/conversion c Py_DTSF_ADD_DOT_0}@anchor{5248}
@deffn {C のマクロ} Py_DTSF_ADD_DOT_0

Ensure that the returned string will not look like an integer.
@end deffn

@geindex Py_DTSF_ALT (C macro)
@anchor{c-api/conversion c Py_DTSF_ALT}@anchor{5249}
@deffn {C のマクロ} Py_DTSF_ALT

Apply "alternate" formatting rules.
See the documentation for the @ref{1722,,PyOS_snprintf()} @code{'#'} specifier for
details.
@end deffn

@geindex Py_DTSF_NO_NEG_0 (C macro)
@anchor{c-api/conversion c Py_DTSF_NO_NEG_0}@anchor{524a}
@deffn {C のマクロ} Py_DTSF_NO_NEG_0

Negative zero is converted to positive zero.


Added in version 3.11.

@end deffn

If `ptype' is non-@code{NULL}, then the value it points to will be set to one
of the following constants depending on the type of `val':


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

`*ptype'

@tab

type of `val'

@item

@geindex Py_DTST_FINITE (C macro)
@anchor{c-api/conversion c Py_DTST_FINITE}@anchor{524b}
@deffn {C のマクロ} Py_DTST_FINITE
@end deffn

@tab

finite number

@item

@geindex Py_DTST_INFINITE (C macro)
@anchor{c-api/conversion c Py_DTST_INFINITE}@anchor{524c}
@deffn {C のマクロ} Py_DTST_INFINITE
@end deffn

@tab

infinite number

@item

@geindex Py_DTST_NAN (C macro)
@anchor{c-api/conversion c Py_DTST_NAN}@anchor{524d}
@deffn {C のマクロ} Py_DTST_NAN
@end deffn

@tab

not a number

@end multitable


戻り値は変換後の文字列が格納された `buffer' へのポインタか、変換が失敗した場合は @code{NULL} です。
呼び出し側は、返された文字列を @ref{165b,,PyMem_Free()} を使って解放する責任があります。


Added in version 3.1.

@end deffn

@geindex PyOS_mystricmp (C function)
@geindex PyOS_mystrnicmp (C function)
@anchor{c-api/conversion c PyOS_mystricmp}@anchor{1d3b}
@deffn {C の関数} int PyOS_mystricmp (const char *str1, const char *str2)
@anchor{c-api/conversion c PyOS_mystrnicmp}@anchor{1d3a}
@deffnx {C の関数} int PyOS_mystrnicmp (const char *str1, const char *str2, Py_ssize_t size)
` 次に属します: @ref{775,,Stable ABI}.'
Case insensitive comparison of strings. These functions work almost
identically to @code{strcmp()} and @code{strncmp()} (respectively),
except that they ignore the case of ASCII characters.

Return @code{0} if the strings are equal, a negative value if `str1' sorts
lexicographically before `str2', or a positive value if it sorts after.

In the `str1' or `str2' arguments, a NUL byte marks the end of the string.
For @code{PyOS_mystrnicmp()}, the `size' argument gives the maximum size
of the string, as if NUL was present at the index given by `size'.

These functions do not use the locale.
@end deffn

@geindex PyOS_stricmp (C function)
@geindex PyOS_strnicmp (C function)
@anchor{c-api/conversion c PyOS_stricmp}@anchor{524e}
@deffn {C の関数} int PyOS_stricmp (const char *str1, const char *str2)
@anchor{c-api/conversion c PyOS_strnicmp}@anchor{524f}
@deffnx {C の関数} int PyOS_strnicmp (const char *str1, const char *str2, Py_ssize_t size)

Case insensitive comparison of strings.

On Windows, these are aliases of @code{stricmp()} and @code{strnicmp()},
respectively.

On other platforms, they are aliases of @ref{1d3b,,PyOS_mystricmp()} and
@ref{1d3a,,PyOS_mystrnicmp()}, respectively.
@end deffn

@node Character classification and conversion,PyHash API,文字列の変換と書式化,ユーティリティ<2>
@anchor{c-api/conversion character-classification-and-conversion}@anchor{5250}
@subsection Character classification and conversion


The following macros provide locale-independent (unlike the C standard library
@code{ctype.h}) character classification and conversion.
The argument must be a signed or unsigned char.

@geindex Py_ISALNUM (C macro)
@anchor{c-api/conversion c Py_ISALNUM}@anchor{1569}
@deffn {C のマクロ} Py_ISALNUM (c)

Return true if the character `c' is an alphanumeric character.
@end deffn

@geindex Py_ISALPHA (C macro)
@anchor{c-api/conversion c Py_ISALPHA}@anchor{156a}
@deffn {C のマクロ} Py_ISALPHA (c)

Return true if the character `c' is an alphabetic character (@code{a-z} and @code{A-Z}).
@end deffn

@geindex Py_ISDIGIT (C macro)
@anchor{c-api/conversion c Py_ISDIGIT}@anchor{156b}
@deffn {C のマクロ} Py_ISDIGIT (c)

Return true if the character `c' is a decimal digit (@code{0-9}).
@end deffn

@geindex Py_ISLOWER (C macro)
@anchor{c-api/conversion c Py_ISLOWER}@anchor{156c}
@deffn {C のマクロ} Py_ISLOWER (c)

Return true if the character `c' is a lowercase ASCII letter (@code{a-z}).
@end deffn

@geindex Py_ISUPPER (C macro)
@anchor{c-api/conversion c Py_ISUPPER}@anchor{156e}
@deffn {C のマクロ} Py_ISUPPER (c)

Return true if the character `c' is an uppercase ASCII letter (@code{A-Z}).
@end deffn

@geindex Py_ISSPACE (C macro)
@anchor{c-api/conversion c Py_ISSPACE}@anchor{156d}
@deffn {C のマクロ} Py_ISSPACE (c)

Return true if the character `c' is a whitespace character (space, tab,
carriage return, newline, vertical tab, or form feed).
@end deffn

@geindex Py_ISXDIGIT (C macro)
@anchor{c-api/conversion c Py_ISXDIGIT}@anchor{156f}
@deffn {C のマクロ} Py_ISXDIGIT (c)

Return true if the character `c' is a hexadecimal digit (@code{0-9}, @code{a-f}, and
@code{A-F}).
@end deffn

@geindex Py_TOLOWER (C macro)
@anchor{c-api/conversion c Py_TOLOWER}@anchor{1570}
@deffn {C のマクロ} Py_TOLOWER (c)

Return the lowercase equivalent of the character `c'.
@end deffn

@geindex Py_TOUPPER (C macro)
@anchor{c-api/conversion c Py_TOUPPER}@anchor{1571}
@deffn {C のマクロ} Py_TOUPPER (c)

Return the uppercase equivalent of the character `c'.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node PyHash API,リフレクション,Character classification and conversion,ユーティリティ<2>
@anchor{c-api/hash doc}@anchor{5251}@anchor{c-api/hash pyhash-api}@anchor{5252}@anchor{c-api/hash translation-repo}@anchor{5253}
@subsection PyHash API


@ref{4ef6,,PyTypeObject.tp_hash} メンバや @ref{25fe,,数値型のハッシュ化} も参照してください。

@geindex Py_hash_t (C type)
@anchor{c-api/hash c Py_hash_t}@anchor{147b}
@deffn {C のデータ型} type Py_hash_t

ハッシュ値型: 符号付き整数。


Added in version 3.2.

@end deffn

@geindex Py_uhash_t (C type)
@anchor{c-api/hash c Py_uhash_t}@anchor{5254}
@deffn {C のデータ型} type Py_uhash_t

ハッシュ値型: 符号なし整数。


Added in version 3.2.

@end deffn

@geindex Py_HASH_ALGORITHM (C macro)
@anchor{c-api/hash c Py_HASH_ALGORITHM}@anchor{5255}
@deffn {C のマクロ} Py_HASH_ALGORITHM

@ref{169,,str} 、 @ref{192,,bytes} や @ref{165,,memoryview} のハッシュ用アルゴリズムを示す数値型。

アルゴリズム名は @ref{491d,,sys.hash_info.algorithm} により公開されます。


Added in version 3.4.

@end deffn

@geindex Py_HASH_FNV (C macro)
@geindex Py_HASH_SIPHASH24 (C macro)
@geindex Py_HASH_SIPHASH13 (C macro)
@anchor{c-api/hash c Py_HASH_FNV}@anchor{5256}
@deffn {C のマクロ} Py_HASH_FNV
@anchor{c-api/hash c Py_HASH_SIPHASH24}@anchor{5257}
@deffnx {C のマクロ} Py_HASH_SIPHASH24
@anchor{c-api/hash c Py_HASH_SIPHASH13}@anchor{5258}
@deffnx {C のマクロ} Py_HASH_SIPHASH13

Numerical values to compare to @ref{5255,,Py_HASH_ALGORITHM} to determine
which algorithm is used for hashing. The hash algorithm can be configured
via the configure @ref{21b6,,--with-hash-algorithm} option.


Added in version 3.4: Add @code{Py_HASH_FNV} and @code{Py_HASH_SIPHASH24}.



Added in version 3.11: Add @code{Py_HASH_SIPHASH13}.

@end deffn

@geindex Py_HASH_CUTOFF (C macro)
@anchor{c-api/hash c Py_HASH_CUTOFF}@anchor{5259}
@deffn {C のマクロ} Py_HASH_CUTOFF

Buffers of length in range @code{[1, Py_HASH_CUTOFF)} are hashed using DJBX33A
instead of the algorithm described by @ref{5255,,Py_HASH_ALGORITHM}.


@itemize -

@item 
A @code{Py_HASH_CUTOFF} of 0 disables the optimization.

@item 
@code{Py_HASH_CUTOFF} must be non-negative and less or equal than 7.
@end itemize

32-bit platforms should use a cutoff smaller than 64-bit platforms because
it is easier to create colliding strings. A cutoff of 7 on 64-bit platforms
and 5 on 32-bit platforms should provide a decent safety margin.

This corresponds to the @ref{4920,,sys.hash_info.cutoff} constant.


Added in version 3.4.

@end deffn

@geindex PyHASH_MODULUS (C macro)
@anchor{c-api/hash c PyHASH_MODULUS}@anchor{19e8}
@deffn {C のマクロ} PyHASH_MODULUS

The Mersenne prime@footnote{https://en.wikipedia.org/wiki/Mersenne_prime} @code{P = 2**n -1},
used for numeric hash scheme.

This corresponds to the @ref{25ff,,sys.hash_info.modulus} constant.


Added in version 3.13.

@end deffn

@geindex PyHASH_BITS (C macro)
@anchor{c-api/hash c PyHASH_BITS}@anchor{19e9}
@deffn {C のマクロ} PyHASH_BITS

The exponent @code{n} of @code{P} in @ref{19e8,,PyHASH_MODULUS}.


Added in version 3.13.

@end deffn

@geindex PyHASH_MULTIPLIER (C macro)
@anchor{c-api/hash c PyHASH_MULTIPLIER}@anchor{1994}
@deffn {C のマクロ} PyHASH_MULTIPLIER

Prime multiplier used in string and various other hashes.


Added in version 3.13.

@end deffn

@geindex PyHASH_INF (C macro)
@anchor{c-api/hash c PyHASH_INF}@anchor{19ea}
@deffn {C のマクロ} PyHASH_INF

The hash value returned for a positive infinity.

This corresponds to the @ref{491a,,sys.hash_info.inf} constant.


Added in version 3.13.

@end deffn

@geindex PyHASH_IMAG (C macro)
@anchor{c-api/hash c PyHASH_IMAG}@anchor{19eb}
@deffn {C のマクロ} PyHASH_IMAG

The multiplier used for the imaginary part of a complex number.

This corresponds to the @ref{491c,,sys.hash_info.imag} constant.


Added in version 3.13.

@end deffn

@geindex PyHash_FuncDef (C type)
@anchor{c-api/hash c PyHash_FuncDef}@anchor{525a}
@deffn {C のデータ型} type PyHash_FuncDef

Hash function definition used by @ref{525b,,PyHash_GetFuncDef()}.

@geindex PyHash_FuncDef.hash (C member)
@anchor{c-api/hash c PyHash_FuncDef hash}@anchor{525c}
@deffn {C のメンバ変数} @ref{147b,,Py_hash_t} (*const hash)(const void*, @ref{c55,,Py_ssize_t})

Hash function.
@end deffn

@geindex PyHash_FuncDef.name (C member)
@anchor{c-api/hash c PyHash_FuncDef name}@anchor{525d}
@deffn {C のメンバ変数} const char *name

Hash function name (UTF-8 encoded string).

This corresponds to the @ref{491d,,sys.hash_info.algorithm} constant.
@end deffn

@geindex PyHash_FuncDef.hash_bits (C member)
@anchor{c-api/hash c PyHash_FuncDef hash_bits}@anchor{525e}
@deffn {C のメンバ変数} const int hash_bits

Internal size of the hash value in bits.

This corresponds to the @ref{491e,,sys.hash_info.hash_bits} constant.
@end deffn

@geindex PyHash_FuncDef.seed_bits (C member)
@anchor{c-api/hash c PyHash_FuncDef seed_bits}@anchor{525f}
@deffn {C のメンバ変数} const int seed_bits

Size of seed input in bits.

This corresponds to the @ref{491f,,sys.hash_info.seed_bits} constant.
@end deffn


Added in version 3.4.

@end deffn

@geindex PyHash_GetFuncDef (C function)
@anchor{c-api/hash c PyHash_GetFuncDef}@anchor{525b}
@deffn {C の関数} @ref{525a,,PyHash_FuncDef} *PyHash_GetFuncDef (void)

Get the hash function definition.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 456
PEP 456@footnote{https://peps.python.org/pep-0456/} "Secure and interchangeable hash algorithm".



Added in version 3.4.

@end deffn

@geindex Py_HashPointer (C function)
@anchor{c-api/hash c Py_HashPointer}@anchor{425}
@deffn {C の関数} @ref{147b,,Py_hash_t} Py_HashPointer (const void *ptr)

Hash a pointer value: process the pointer value as an integer (cast it to
@code{uintptr_t} internally). The pointer is not dereferenced.

The function cannot fail: it cannot return @code{-1}.


Added in version 3.13.

@end deffn

@geindex Py_HashBuffer (C function)
@anchor{c-api/hash c Py_HashBuffer}@anchor{395}
@deffn {C の関数} @ref{147b,,Py_hash_t} Py_HashBuffer (const void *ptr, Py_ssize_t len)

Compute and return the hash value of a buffer of `len' bytes
starting at address `ptr'. The hash is guaranteed to match that of
@ref{192,,bytes}, @ref{165,,memoryview}, and other built-in objects
that implement the @ref{260,,buffer protocol}.

Use this function to implement hashing for immutable objects whose
@ref{4ef0,,tp_richcompare} function compares to another
object's buffer.

`len' must be greater than or equal to @code{0}.

This function always succeeds.


Added in version 3.14.

@end deffn

@geindex PyObject_GenericHash (C function)
@anchor{c-api/hash c PyObject_GenericHash}@anchor{60c}
@deffn {C の関数} @ref{147b,,Py_hash_t} PyObject_GenericHash (PyObject *obj)

Generic hashing function that is meant to be put into a type
object's @code{tp_hash} slot.
Its result only depends on the object's identity.

`CPython 実装の詳細:' In CPython, it is equivalent to @ref{425,,Py_HashPointer()}.


Added in version 3.13.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node リフレクション,codec レジストリとサポート関数,PyHash API,ユーティリティ<2>
@anchor{c-api/reflection doc}@anchor{5260}@anchor{c-api/reflection id1}@anchor{5261}@anchor{c-api/reflection reflection}@anchor{5262}@anchor{c-api/reflection translation-repo}@anchor{5263}
@subsection リフレクション


@geindex PyEval_GetBuiltins (C function)
@anchor{c-api/reflection c PyEval_GetBuiltins}@anchor{5f4}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_GetBuiltins (void)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'

バージョン 3.13 で非推奨: Use @ref{5f3,,PyEval_GetFrameBuiltins()} instead.


現在の実行フレーム内のビルトインの辞書か、もし実行中のフレームがなければスレッド状態のインタプリタのビルトイン辞書を返します。
@end deffn

@geindex PyEval_GetLocals (C function)
@anchor{c-api/reflection c PyEval_GetLocals}@anchor{5f8}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_GetLocals (void)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'

バージョン 3.13 で非推奨: Use either @ref{5f7,,PyEval_GetFrameLocals()} to obtain the same behaviour as calling
@ref{46f,,locals()} in Python code, or else call @ref{661,,PyFrame_GetLocals()} on the result
of @ref{1b39,,PyEval_GetFrame()} to access the @ref{4a5,,f_locals} attribute of the
currently executing frame.


Return a mapping providing access to the local variables in the current execution frame,
or @code{NULL} if no frame is currently executing.

Refer to @ref{46f,,locals()} for details of the mapping returned at different scopes.

As this function returns a @ref{3d7,,borrowed reference}, the dictionary returned for
@ref{4a1,,optimized scopes} is cached on the frame object and will remain
alive as long as the frame object does. Unlike @ref{5f7,,PyEval_GetFrameLocals()} and
@ref{46f,,locals()}, subsequent calls to this function in the same frame will update the
contents of the cached dictionary to reflect changes in the state of the local variables
rather than returning a new snapshot.


バージョン 3.13 で変更: As part of 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}, @ref{661,,PyFrame_GetLocals()}, @ref{46f,,locals()}, and
@ref{4a5,,FrameType.f_locals} no longer make use of the shared cache
dictionary. Refer to the @ref{470,,What's New entry} for
additional details.

@end deffn

@geindex PyEval_GetGlobals (C function)
@anchor{c-api/reflection c PyEval_GetGlobals}@anchor{5f6}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_GetGlobals (void)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'

バージョン 3.13 で非推奨: Use @ref{5f5,,PyEval_GetFrameGlobals()} instead.


現在の実行フレーム内のグローバル変数の辞書か、実行中のフレームがなければ @code{NULL} を返します。
@end deffn

@geindex PyEval_GetFrame (C function)
@anchor{c-api/reflection c PyEval_GetFrame}@anchor{1b39}
@deffn {C の関数} @ref{98c,,PyFrameObject} *PyEval_GetFrame (void)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return the @ref{4ed1,,attached thread state}'s frame, which is @code{NULL} if no frame is
currently executing.

See also @ref{991,,PyThreadState_GetFrame()}.
@end deffn

@geindex PyEval_GetFrameBuiltins (C function)
@anchor{c-api/reflection c PyEval_GetFrameBuiltins}@anchor{5f3}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_GetFrameBuiltins (void)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
現在の実行フレーム内のビルトインの辞書か、もし実行中のフレームがなければスレッド状態のインタプリタのビルトイン辞書を返します。


Added in version 3.13.

@end deffn

@geindex PyEval_GetFrameLocals (C function)
@anchor{c-api/reflection c PyEval_GetFrameLocals}@anchor{5f7}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_GetFrameLocals (void)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return a dictionary of the local variables in the current execution frame,
or @code{NULL} if no frame is currently executing. Equivalent to calling
@ref{46f,,locals()} in Python code.

To access @ref{4a5,,f_locals} on the current frame without making an independent
snapshot in @ref{4a1,,optimized scopes}, call @ref{661,,PyFrame_GetLocals()}
on the result of @ref{1b39,,PyEval_GetFrame()}.


Added in version 3.13.

@end deffn

@geindex PyEval_GetFrameGlobals (C function)
@anchor{c-api/reflection c PyEval_GetFrameGlobals}@anchor{5f5}
@deffn {C の関数} @ref{5df,,PyObject} *PyEval_GetFrameGlobals (void)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return a dictionary of the global variables in the current execution frame,
or @code{NULL} if no frame is currently executing. Equivalent to calling
@ref{1c0a,,globals()} in Python code.


Added in version 3.13.

@end deffn

@geindex PyEval_GetFuncName (C function)
@anchor{c-api/reflection c PyEval_GetFuncName}@anchor{4fdd}
@deffn {C の関数} const char *PyEval_GetFuncName (PyObject *func)
` 次に属します: @ref{775,,Stable ABI}.'
`func' が関数、クラス、インスタンスオブジェクトであればその名前を、そうでなければ `func' の型を返します。
@end deffn

@geindex PyEval_GetFuncDesc (C function)
@anchor{c-api/reflection c PyEval_GetFuncDesc}@anchor{4fdc}
@deffn {C の関数} const char *PyEval_GetFuncDesc (PyObject *func)
` 次に属します: @ref{775,,Stable ABI}.'
`func' の型に依存する、解説文字列(description string)を返します。戻り値は、関数とメソッドに対しては "()", " constructor", " instance", " object" です。 @ref{4fdd,,PyEval_GetFuncName()} と連結された結果、 `func' の解説になります。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node codec レジストリとサポート関数,PyTime C API,リフレクション,ユーティリティ<2>
@anchor{c-api/codec doc}@anchor{5264}@anchor{c-api/codec codec-registry}@anchor{f30}@anchor{c-api/codec codec-registry-and-support-functions}@anchor{5265}@anchor{c-api/codec translation-repo}@anchor{5266}
@subsection codec レジストリとサポート関数


@geindex PyCodec_Register (C function)
@anchor{c-api/codec c PyCodec_Register}@anchor{4fa6}
@deffn {C の関数} int PyCodec_Register (PyObject *search_function)
` 次に属します: @ref{775,,Stable ABI}.'
新しい codec 検索関数を登録します。

As a side effect, this tries to load the @code{encodings} package, if not yet
done, to make sure that it is always first in the list of search functions.
@end deffn

@geindex PyCodec_Unregister (C function)
@anchor{c-api/codec c PyCodec_Unregister}@anchor{a97}
@deffn {C の関数} int PyCodec_Unregister (PyObject *search_function)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
コーデック検索関数の登録を解除し、レジストリのキャッシュをクリアします。 検索関数が登録されていない場合は何もしません。 成功したら0を返します。 エラーの場合は例外を送出させ、-1を返します。


Added in version 3.10.

@end deffn

@geindex PyCodec_KnownEncoding (C function)
@anchor{c-api/codec c PyCodec_KnownEncoding}@anchor{4fa4}
@deffn {C の関数} int PyCodec_KnownEncoding (const char *encoding)
` 次に属します: @ref{775,,Stable ABI}.'
`encoding' のための登録された codec が存在するかどうかに応じて @code{1} か @code{0} を返します。
この関数は常に成功します。
@end deffn

@geindex PyCodec_Encode (C function)
@anchor{c-api/codec c PyCodec_Encode}@anchor{3e2}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_Encode (PyObject *object, const char *encoding, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
汎用の codec ベースの encode API.

`encoding' に応じて見つかったエンコーダ関数に対して `object' を渡します。
エラーハンドリングメソッドは `errors' で指定します。
`errors' は @code{NULL} でもよく、その場合はその codec のデフォルトのメソッドが利用されます。
エンコーダが見つからなかった場合は @ref{23e5,,LookupError} を発生させます。
@end deffn

@geindex PyCodec_Decode (C function)
@anchor{c-api/codec c PyCodec_Decode}@anchor{3e1}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_Decode (PyObject *object, const char *encoding, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
汎用の codec ベースのデコード API.

`object' is passed through the decoder function found for the given
`encoding' using the error handling method defined by `errors'.  `errors' may
be @code{NULL} to use the default method defined for the codec.  Raises a
@ref{23e5,,LookupError} if no decoder can be found.
@end deffn

@menu
* コーデック検索API:: 
* Unicode エラーハンドラ用レジストリ API:: 
* Codec utility variables:: 

@end menu

@node コーデック検索API,Unicode エラーハンドラ用レジストリ API,,codec レジストリとサポート関数
@anchor{c-api/codec codec-lookup-api}@anchor{5267}
@subsubsection コーデック検索API


次の関数では、文字列 `encoding' は全て小文字に変換することで、効率的に、大文字小文字を無視した検索をします。
コーデックが見つからない場合、 @ref{5e7,,KeyError} を設定して @code{NULL} を返します。

@geindex PyCodec_Encoder (C function)
@anchor{c-api/codec c PyCodec_Encoder}@anchor{4fa0}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_Encoder (const char *encoding)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた `encoding' のエンコーダ関数を返します。
@end deffn

@geindex PyCodec_Decoder (C function)
@anchor{c-api/codec c PyCodec_Decoder}@anchor{4f9f}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_Decoder (const char *encoding)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた `encoding' のデコーダ関数を返します。
@end deffn

@geindex PyCodec_IncrementalEncoder (C function)
@anchor{c-api/codec c PyCodec_IncrementalEncoder}@anchor{4fa3}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_IncrementalEncoder (const char *encoding, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた `encoding' の @ref{2836,,IncrementalEncoder} オブジェクトを返します。
@end deffn

@geindex PyCodec_IncrementalDecoder (C function)
@anchor{c-api/codec c PyCodec_IncrementalDecoder}@anchor{4fa2}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_IncrementalDecoder (const char *encoding, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた `encoding' の @ref{2837,,IncrementalDecoder} オブジェクトを返します。
@end deffn

@geindex PyCodec_StreamReader (C function)
@anchor{c-api/codec c PyCodec_StreamReader}@anchor{4fa9}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_StreamReader (const char *encoding, PyObject *stream, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた `encoding' の @ref{283b,,StreamReader} ファクトリ関数を返します。
@end deffn

@geindex PyCodec_StreamWriter (C function)
@anchor{c-api/codec c PyCodec_StreamWriter}@anchor{4faa}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_StreamWriter (const char *encoding, PyObject *stream, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた `encoding' の @ref{283a,,StreamWriter} ファクトリ関数を返します。
@end deffn

@node Unicode エラーハンドラ用レジストリ API,Codec utility variables,コーデック検索API,codec レジストリとサポート関数
@anchor{c-api/codec registry-api-for-unicode-encoding-error-handlers}@anchor{5268}
@subsubsection Unicode エラーハンドラ用レジストリ API


@geindex PyCodec_RegisterError (C function)
@anchor{c-api/codec c PyCodec_RegisterError}@anchor{4fa7}
@deffn {C の関数} int PyCodec_RegisterError (const char *name, PyObject *error)
` 次に属します: @ref{775,,Stable ABI}.'
エラーハンドルのためのコールバック関数 `error' を `name' で登録します。このコールバック関数は、コーデックがエンコードできない文字/デコードできないバイトに遭遇した時に、そのエンコード/デコード関数の呼び出しで `name' が指定されていたら呼び出されます。

コールバックは1つの引数として、 @ref{887,,UnicodeEncodeError}, @ref{c08,,UnicodeDecodeError}, @ref{18fd,,UnicodeTranslateError} のどれかのインスタンスを受け取ります。このインスタンスは問題のある文字列やバイト列に関する情報と、その元の文字列中のオフセットを持っています。(その情報を取得するための関数については @ref{461,,Unicode 例外オブジェクト} を参照してください。) コールバックは渡された例外を発生させるか、2要素のタプルに問題のシーケンスの代替と、 encode/decode を再開する元の文字列中のオフセットとなる整数を格納して返します。

成功したら @code{0} を、エラー時は @code{-1} を返します。
@end deffn

@geindex PyCodec_LookupError (C function)
@anchor{c-api/codec c PyCodec_LookupError}@anchor{4fa5}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_LookupError (const char *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`name' で登録されたエラーハンドリングコールバック関数を検索します。
特別な場合として、@code{NULL} が渡された場合、"strict" のエラーハンドリングコールバック関数を返します。
@end deffn

@geindex PyCodec_StrictErrors (C function)
@anchor{c-api/codec c PyCodec_StrictErrors}@anchor{4fab}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_StrictErrors (PyObject *exc)
`戻り値: 常に NULL 。'` 次に属します: @ref{775,,Stable ABI}.'
`exc' を例外として発生させます。
@end deffn

@geindex PyCodec_IgnoreErrors (C function)
@anchor{c-api/codec c PyCodec_IgnoreErrors}@anchor{4fa1}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_IgnoreErrors (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
unicode エラーを無視し、問題の入力をスキップします。
@end deffn

@geindex PyCodec_ReplaceErrors (C function)
@anchor{c-api/codec c PyCodec_ReplaceErrors}@anchor{4fa8}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_ReplaceErrors (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
unicode エラーを @code{?} か @code{U+FFFD} で置き換えます。
@end deffn

@geindex PyCodec_XMLCharRefReplaceErrors (C function)
@anchor{c-api/codec c PyCodec_XMLCharRefReplaceErrors}@anchor{4fac}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_XMLCharRefReplaceErrors (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
unicode encode エラーを XML文字参照で置き換えます。
@end deffn

@geindex PyCodec_BackslashReplaceErrors (C function)
@anchor{c-api/codec c PyCodec_BackslashReplaceErrors}@anchor{4f9e}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_BackslashReplaceErrors (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
unicode encode エラーをバックスラッシュエスケープ (@code{\x}, @code{\u}, @code{\U}) で置き換えます。
@end deffn

@geindex PyCodec_NameReplaceErrors (C function)
@anchor{c-api/codec c PyCodec_NameReplaceErrors}@anchor{10af}
@deffn {C の関数} @ref{5df,,PyObject} *PyCodec_NameReplaceErrors (PyObject *exc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
unicode encode エラーを @code{\N@{...@}} で置き換えます。


Added in version 3.5.

@end deffn

@node Codec utility variables,,Unicode エラーハンドラ用レジストリ API,codec レジストリとサポート関数
@anchor{c-api/codec codec-utility-variables}@anchor{5269}
@subsubsection Codec utility variables


@geindex Py_hexdigits (C var)
@anchor{c-api/codec c Py_hexdigits}@anchor{526a}
@deffn {C 変数} const char *Py_hexdigits

A string constant containing the lowercase hexadecimal digits: @code{"0123456789abcdef"}.


Added in version 3.3.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node PyTime C API,Support for Perf Maps,codec レジストリとサポート関数,ユーティリティ<2>
@anchor{c-api/time doc}@anchor{483}@anchor{c-api/time c-api-time}@anchor{5d2}@anchor{c-api/time pytime-c-api}@anchor{526b}@anchor{c-api/time translation-repo}@anchor{526c}
@subsection PyTime C API



Added in version 3.13.


クロック C API は、システムクロックへのアクセスを提供します。これは Python の @ref{f4,,time} モジュールに似ています。

@ref{34,,datetime} モジュールに関連する C API については、@ref{526d,,DateTime オブジェクト} を参照してください。

@menu
* 型: 型<3>. 
* Clock Functions:: 
* Raw Clock Functions:: 
* Conversion functions:: 

@end menu

@node 型<3>,Clock Functions,,PyTime C API
@anchor{c-api/time types}@anchor{526e}
@subsubsection 型


@geindex PyTime_t (C type)
@anchor{c-api/time c PyTime_t}@anchor{5d3}
@deffn {C のデータ型} type PyTime_t

A timestamp or duration in nanoseconds, represented as a signed 64-bit
integer.

The reference point for timestamps depends on the clock used. For example,
@ref{5db,,PyTime_Time()} returns timestamps relative to the UNIX epoch.

The supported range is around [-292.3 years; +292.3 years].
Using the Unix epoch (January 1st, 1970) as reference, the supported date
range is around [1677-09-21; 2262-04-11].
The exact limits are exposed as constants:
@end deffn

@geindex PyTime_MIN (C var)
@anchor{c-api/time c PyTime_MIN}@anchor{5d4}
@deffn {C 変数} @ref{5d3,,PyTime_t} PyTime_MIN

Minimum value of @ref{5d3,,PyTime_t}.
@end deffn

@geindex PyTime_MAX (C var)
@anchor{c-api/time c PyTime_MAX}@anchor{5d5}
@deffn {C 変数} @ref{5d3,,PyTime_t} PyTime_MAX

Maximum value of @ref{5d3,,PyTime_t}.
@end deffn

@node Clock Functions,Raw Clock Functions,型<3>,PyTime C API
@anchor{c-api/time clock-functions}@anchor{526f}
@subsubsection Clock Functions


The following functions take a pointer to a @ref{5d3,,PyTime_t} that they
set to the value of a particular clock.
Details of each clock are given in the documentation of the corresponding
Python function.

The functions return @code{0} on success, or @code{-1} (with an exception set)
on failure.

On integer overflow, they set the @ref{5006,,PyExc_OverflowError} exception and
set @code{*result} to the value clamped to the @code{[PyTime_MIN; PyTime_MAX]}
range.
(On current systems, integer overflows are likely caused by misconfigured
system time.)

As any other C API (unless otherwise specified), the functions must be called
with an @ref{4ed1,,attached thread state}.

@geindex PyTime_Monotonic (C function)
@anchor{c-api/time c PyTime_Monotonic}@anchor{5d7}
@deffn {C の関数} int PyTime_Monotonic (PyTime_t *result)

Read the monotonic clock.
See @ref{55c,,time.monotonic()} for important details on this clock.
@end deffn

@geindex PyTime_PerfCounter (C function)
@anchor{c-api/time c PyTime_PerfCounter}@anchor{5d9}
@deffn {C の関数} int PyTime_PerfCounter (PyTime_t *result)

Read the performance counter.
See @ref{c7a,,time.perf_counter()} for important details on this clock.
@end deffn

@geindex PyTime_Time (C function)
@anchor{c-api/time c PyTime_Time}@anchor{5db}
@deffn {C の関数} int PyTime_Time (PyTime_t *result)

Read the “wall clock” time.
See @ref{55d,,time.time()} for details important on this clock.
@end deffn

@node Raw Clock Functions,Conversion functions,Clock Functions,PyTime C API
@anchor{c-api/time raw-clock-functions}@anchor{5270}
@subsubsection Raw Clock Functions


Similar to clock functions, but don't set an exception on error and don't
require the caller to have an @ref{4ed1,,attached thread state}.

On success, the functions return @code{0}.

On failure, they set @code{*result} to @code{0} and return @code{-1}, `without' setting
an exception. To get the cause of the error, @ref{4ed1,,attach} a @ref{1846,,thread state},
and call the regular (non-@code{Raw}) function. Note that the regular function may succeed after
the @code{Raw} one failed.

@geindex PyTime_MonotonicRaw (C function)
@anchor{c-api/time c PyTime_MonotonicRaw}@anchor{5d8}
@deffn {C の関数} int PyTime_MonotonicRaw (PyTime_t *result)

Similar to @ref{5d7,,PyTime_Monotonic()},
but don't set an exception on error and don't require an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyTime_PerfCounterRaw (C function)
@anchor{c-api/time c PyTime_PerfCounterRaw}@anchor{5da}
@deffn {C の関数} int PyTime_PerfCounterRaw (PyTime_t *result)

Similar to @ref{5d9,,PyTime_PerfCounter()},
but don't set an exception on error and don't require an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyTime_TimeRaw (C function)
@anchor{c-api/time c PyTime_TimeRaw}@anchor{5dc}
@deffn {C の関数} int PyTime_TimeRaw (PyTime_t *result)

Similar to @ref{5db,,PyTime_Time()},
but don't set an exception on error and don't require an @ref{4ed1,,attached thread state}.
@end deffn

@node Conversion functions,,Raw Clock Functions,PyTime C API
@anchor{c-api/time conversion-functions}@anchor{5271}
@subsubsection Conversion functions


@geindex PyTime_AsSecondsDouble (C function)
@anchor{c-api/time c PyTime_AsSecondsDouble}@anchor{5d6}
@deffn {C の関数} double PyTime_AsSecondsDouble (PyTime_t t)

Convert a timestamp to a number of seconds as a C double.

The function cannot fail, but note that double has limited
accuracy for large values.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Support for Perf Maps,,PyTime C API,ユーティリティ<2>
@anchor{c-api/perfmaps doc}@anchor{5272}@anchor{c-api/perfmaps perfmaps}@anchor{5273}@anchor{c-api/perfmaps support-for-perf-maps}@anchor{5274}@anchor{c-api/perfmaps translation-repo}@anchor{5275}
@subsection Support for Perf Maps


On supported platforms (as of this writing, only Linux), the runtime can take
advantage of `perf map files' to make Python functions visible to an external
profiling tool (such as perf@footnote{https://perf.wiki.kernel.org/index.php/Main_Page}).
A running process may create a file in the @code{/tmp} directory, which contains entries
that can map a section of executable code to a name. This interface is described in the
documentation of the Linux Perf tool@footnote{https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/perf/Documentation/jit-interface.txt}.

In Python, these helper APIs can be used by libraries and features that rely
on generating machine code on the fly.

Note that holding an @ref{4ed1,,attached thread state} is not required for these APIs.

@geindex PyUnstable_PerfMapState_Init (C function)
@anchor{c-api/perfmaps c PyUnstable_PerfMapState_Init}@anchor{1aaa}
@deffn {C の関数} int PyUnstable_PerfMapState_Init (void)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Open the @code{/tmp/perf-$pid.map} file, unless it's already opened, and create
a lock to ensure thread-safe writes to the file (provided the writes are
done through @ref{1aa9,,PyUnstable_WritePerfMapEntry()}). Normally, there's no need
to call this explicitly; just use @ref{1aa9,,PyUnstable_WritePerfMapEntry()}
and it will initialize the state on first call.

Returns @code{0} on success, @code{-1} on failure to create/open the perf map file,
or @code{-2} on failure to create a lock. Check @code{errno} for more information
about the cause of a failure.
@end deffn

@geindex PyUnstable_WritePerfMapEntry (C function)
@anchor{c-api/perfmaps c PyUnstable_WritePerfMapEntry}@anchor{1aa9}
@deffn {C の関数} int PyUnstable_WritePerfMapEntry (const void *code_addr, unsigned int code_size, const char *entry_name)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Write one single entry to the @code{/tmp/perf-$pid.map} file. This function is
thread safe. Here is what an example entry looks like:

@example
# address      size  name
7f3529fcf759 b     py::bar:/run/t.py
@end example

Will call @ref{1aaa,,PyUnstable_PerfMapState_Init()} before writing the entry, if
the perf map file is not already opened. Returns @code{0} on success, or the
same error codes as @ref{1aaa,,PyUnstable_PerfMapState_Init()} on failure.
@end deffn

@geindex PyUnstable_PerfMapState_Fini (C function)
@anchor{c-api/perfmaps c PyUnstable_PerfMapState_Fini}@anchor{1aab}
@deffn {C の関数} void PyUnstable_PerfMapState_Fini (void)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Close the perf map file opened by @ref{1aaa,,PyUnstable_PerfMapState_Init()}.
This is called by the runtime itself during interpreter shut-down. In
general, there shouldn't be a reason to explicitly call this, except to
handle specific scenarios such as forking.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 抽象オブジェクトレイヤ Abstract Objects Layer,具象オブジェクト concrete object レイヤ,ユーティリティ<2>,Python/C API リファレンスマニュアル
@anchor{c-api/abstract doc}@anchor{5276}@anchor{c-api/abstract abstract}@anchor{4ef3}@anchor{c-api/abstract abstract-objects-layer}@anchor{5277}@anchor{c-api/abstract translation-repo}@anchor{5278}
@section 抽象オブジェクトレイヤ (Abstract Objects Layer)


この章で説明する関数は、オブジェクトの型に依存しないような Python オブジェクトの操作や、(数値型全て、シーケンス型全てといった) 大まかな型のオブジェクトに対する操作を行ないます。関数を適用対象でないオブジェクトに対して使った場合、Python の例外が送出されることになります。

これらの関数は、 @ref{4f49,,PyList_New()} で作成された後に @code{NULL} 以外の値を設定されていないリストのような、適切に初期化されていないオブジェクトに対して使うことはできません。

@menu
* オブジェクトプロトコル (object protocol): オブジェクトプロトコル object protocol. 
* Call プロトコル:: 
* 数値型プロトコル (number protocol): 数値型プロトコル number protocol. 
* シーケンス型プロトコル (sequence protocol): シーケンス型プロトコル sequence protocol. 
* マップ型プロトコル (mapping protocol): マップ型プロトコル mapping protocol. 
* イテレータプロトコル (iterator protocol): イテレータプロトコル iterator protocol. 
* バッファプロトコル (buffer Protocol): バッファプロトコル buffer Protocol. 

@end menu

@node オブジェクトプロトコル object protocol,Call プロトコル,,抽象オブジェクトレイヤ Abstract Objects Layer
@anchor{c-api/object doc}@anchor{5279}@anchor{c-api/object object}@anchor{527a}@anchor{c-api/object object-protocol}@anchor{527b}
@subsection オブジェクトプロトコル (object protocol)


@geindex Py_GetConstant (C function)
@anchor{c-api/object c Py_GetConstant}@anchor{5f9}
@deffn {C の関数} @ref{5df,,PyObject} *Py_GetConstant (unsigned int constant_id)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Get a @ref{5e2,,strong reference} to a constant.

Set an exception and return @code{NULL} if `constant_id' is invalid.

`constant_id' must be one of these constant identifiers:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Constant Identifier

@tab

値

@tab

Returned object

@item

@geindex Py_CONSTANT_NONE (C macro)
@anchor{c-api/object c Py_CONSTANT_NONE}@anchor{527c}
@deffn {C のマクロ} Py_CONSTANT_NONE
@end deffn

@tab

@code{0}

@tab

@ref{885,,None}

@item

@geindex Py_CONSTANT_FALSE (C macro)
@anchor{c-api/object c Py_CONSTANT_FALSE}@anchor{527d}
@deffn {C のマクロ} Py_CONSTANT_FALSE
@end deffn

@tab

@code{1}

@tab

@ref{d2b,,False}

@item

@geindex Py_CONSTANT_TRUE (C macro)
@anchor{c-api/object c Py_CONSTANT_TRUE}@anchor{527e}
@deffn {C のマクロ} Py_CONSTANT_TRUE
@end deffn

@tab

@code{2}

@tab

@ref{e07,,True}

@item

@geindex Py_CONSTANT_ELLIPSIS (C macro)
@anchor{c-api/object c Py_CONSTANT_ELLIPSIS}@anchor{527f}
@deffn {C のマクロ} Py_CONSTANT_ELLIPSIS
@end deffn

@tab

@code{3}

@tab

@ref{2328,,Ellipsis}

@item

@geindex Py_CONSTANT_NOT_IMPLEMENTED (C macro)
@anchor{c-api/object c Py_CONSTANT_NOT_IMPLEMENTED}@anchor{5280}
@deffn {C のマクロ} Py_CONSTANT_NOT_IMPLEMENTED
@end deffn

@tab

@code{4}

@tab

@ref{1a2,,NotImplemented}

@item

@geindex Py_CONSTANT_ZERO (C macro)
@anchor{c-api/object c Py_CONSTANT_ZERO}@anchor{5281}
@deffn {C のマクロ} Py_CONSTANT_ZERO
@end deffn

@tab

@code{5}

@tab

@code{0}

@item

@geindex Py_CONSTANT_ONE (C macro)
@anchor{c-api/object c Py_CONSTANT_ONE}@anchor{5282}
@deffn {C のマクロ} Py_CONSTANT_ONE
@end deffn

@tab

@code{6}

@tab

@code{1}

@item

@geindex Py_CONSTANT_EMPTY_STR (C macro)
@anchor{c-api/object c Py_CONSTANT_EMPTY_STR}@anchor{5283}
@deffn {C のマクロ} Py_CONSTANT_EMPTY_STR
@end deffn

@tab

@code{7}

@tab

@code{'@w{'}}

@item

@geindex Py_CONSTANT_EMPTY_BYTES (C macro)
@anchor{c-api/object c Py_CONSTANT_EMPTY_BYTES}@anchor{5284}
@deffn {C のマクロ} Py_CONSTANT_EMPTY_BYTES
@end deffn

@tab

@code{8}

@tab

@code{b'@w{'}}

@item

@geindex Py_CONSTANT_EMPTY_TUPLE (C macro)
@anchor{c-api/object c Py_CONSTANT_EMPTY_TUPLE}@anchor{5285}
@deffn {C のマクロ} Py_CONSTANT_EMPTY_TUPLE
@end deffn

@tab

@code{9}

@tab

@code{()}

@end multitable


Numeric values are only given for projects which cannot use the constant
identifiers.


Added in version 3.13.


`CPython 実装の詳細:' In CPython, all of these constants are @ref{290,,immortal}.
@end deffn

@geindex Py_GetConstantBorrowed (C function)
@anchor{c-api/object c Py_GetConstantBorrowed}@anchor{5fa}
@deffn {C の関数} @ref{5df,,PyObject} *Py_GetConstantBorrowed (unsigned int constant_id)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Similar to @ref{5f9,,Py_GetConstant()}, but return a @ref{3d7,,borrowed reference}.

This function is primarily intended for backwards compatibility:
using @ref{5f9,,Py_GetConstant()} is recommended for new code.

The reference is borrowed from the interpreter, and is valid until the
interpreter finalization.


Added in version 3.13.

@end deffn

@geindex Py_NotImplemented (C var)
@anchor{c-api/object c Py_NotImplemented}@anchor{5286}
@deffn {C 変数} @ref{5df,,PyObject} *Py_NotImplemented

与えられたオブジェクトとメソッドの引数の型の組み合わせの処理が未実装である印として使われる、 @code{未実装 (NotImplemented)} シングルトン。
@end deffn

@geindex Py_RETURN_NOTIMPLEMENTED (C macro)
@anchor{c-api/object c Py_RETURN_NOTIMPLEMENTED}@anchor{17e7}
@deffn {C のマクロ} Py_RETURN_NOTIMPLEMENTED

Properly handle returning @ref{5286,,Py_NotImplemented} from within a C
function (that is, create a new @ref{5e2,,strong reference}
to @ref{1a2,,NotImplemented} and return it).
@end deffn

@geindex Py_PRINT_RAW (C macro)
@anchor{c-api/object c Py_PRINT_RAW}@anchor{5287}
@deffn {C のマクロ} Py_PRINT_RAW

Flag to be used with multiple functions that print the object (like
@ref{198b,,PyObject_Print()} and @ref{5026,,PyFile_WriteObject()}).
If passed, these functions use the @ref{169,,str()} of the object
instead of the @ref{1c1,,repr()}.
@end deffn

@geindex PyObject_Print (C function)
@anchor{c-api/object c PyObject_Print}@anchor{198b}
@deffn {C の関数} int PyObject_Print (PyObject *o, FILE *fp, int flags)

Print an object `o', on file `fp'.  Returns @code{-1} on error.  The flags argument
is used to enable certain printing options.  The only option currently supported
is @ref{5287,,Py_PRINT_RAW}; if given, the @ref{169,,str()} of the object is written
instead of the @ref{1c1,,repr()}.
@end deffn

@geindex PyObject_HasAttrWithError (C function)
@anchor{c-api/object c PyObject_HasAttrWithError}@anchor{61b}
@deffn {C の関数} int PyObject_HasAttrWithError (PyObject *o, PyObject *attr_name)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Returns @code{1} if `o' has the attribute `attr_name', and @code{0} otherwise.
This is equivalent to the Python expression @code{hasattr(o, attr_name)}.
On failure, return @code{-1}.


Added in version 3.13.

@end deffn

@geindex PyObject_HasAttrStringWithError (C function)
@anchor{c-api/object c PyObject_HasAttrStringWithError}@anchor{61d}
@deffn {C の関数} int PyObject_HasAttrStringWithError (PyObject *o, const char *attr_name)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
This is the same as @ref{61b,,PyObject_HasAttrWithError()}, but `attr_name' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.


Added in version 3.13.

@end deffn

@geindex PyObject_HasAttr (C function)
@anchor{c-api/object c PyObject_HasAttr}@anchor{61c}
@deffn {C の関数} int PyObject_HasAttr (PyObject *o, PyObject *attr_name)
` 次に属します: @ref{775,,Stable ABI}.'
Returns @code{1} if `o' has the attribute `attr_name', and @code{0} otherwise.
This function always succeeds.

@cartouche
@quotation 注釈 
Exceptions that occur when this calls @ref{6fa,,__getattr__()} and
@ref{dcb,,__getattribute__()} methods aren't propagated,
but instead given to @ref{507,,sys.unraisablehook()}.
For proper error handling, use @ref{61b,,PyObject_HasAttrWithError()},
@ref{5ec,,PyObject_GetOptionalAttr()} or @ref{5ee,,PyObject_GetAttr()} instead.
@end quotation
@end cartouche
@end deffn

@geindex PyObject_HasAttrString (C function)
@anchor{c-api/object c PyObject_HasAttrString}@anchor{61e}
@deffn {C の関数} int PyObject_HasAttrString (PyObject *o, const char *attr_name)
` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{61c,,PyObject_HasAttr()}, but `attr_name' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.

@cartouche
@quotation 注釈 
Exceptions that occur when this calls @ref{6fa,,__getattr__()} and
@ref{dcb,,__getattribute__()} methods or while creating the temporary
@ref{169,,str} object are silently ignored.
For proper error handling, use @ref{61d,,PyObject_HasAttrStringWithError()},
@ref{5ed,,PyObject_GetOptionalAttrString()}
or @ref{5ef,,PyObject_GetAttrString()} instead.
@end quotation
@end cartouche
@end deffn

@geindex PyObject_GetAttr (C function)
@anchor{c-api/object c PyObject_GetAttr}@anchor{5ee}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_GetAttr (PyObject *o, PyObject *attr_name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `o' から、名前 `attr_name' の属性を取得します。成功すると属性値を返し失敗すると @code{NULL} を返します。この関数は Python の式 @code{o.attr_name} と同じです。

If the missing attribute should not be treated as a failure, you can use
@ref{5ec,,PyObject_GetOptionalAttr()} instead.
@end deffn

@geindex PyObject_GetAttrString (C function)
@anchor{c-api/object c PyObject_GetAttrString}@anchor{5ef}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_GetAttrString (PyObject *o, const char *attr_name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{5ee,,PyObject_GetAttr()}, but `attr_name' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.

If the missing attribute should not be treated as a failure, you can use
@ref{5ed,,PyObject_GetOptionalAttrString()} instead.
@end deffn

@geindex PyObject_GetOptionalAttr (C function)
@anchor{c-api/object c PyObject_GetOptionalAttr}@anchor{5ec}
@deffn {C の関数} int PyObject_GetOptionalAttr (PyObject *obj, PyObject *attr_name, PyObject **result);
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Variant of @ref{5ee,,PyObject_GetAttr()} which doesn't raise
@ref{5f0,,AttributeError} if the attribute is not found.

If the attribute is found, return @code{1} and set `*result' to a new
@ref{5e2,,strong reference} to the attribute.
If the attribute is not found, return @code{0} and set `*result' to @code{NULL};
the @ref{5f0,,AttributeError} is silenced.
If an error other than @ref{5f0,,AttributeError} is raised, return @code{-1} and
set `*result' to @code{NULL}.


Added in version 3.13.

@end deffn

@geindex PyObject_GetOptionalAttrString (C function)
@anchor{c-api/object c PyObject_GetOptionalAttrString}@anchor{5ed}
@deffn {C の関数} int PyObject_GetOptionalAttrString (PyObject *obj, const char *attr_name, PyObject **result);
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
This is the same as @ref{5ec,,PyObject_GetOptionalAttr()}, but `attr_name' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.


Added in version 3.13.

@end deffn

@geindex PyObject_GenericGetAttr (C function)
@anchor{c-api/object c PyObject_GenericGetAttr}@anchor{508e}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_GenericGetAttr (PyObject *o, PyObject *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
型オブジェクトの @code{tp_getattro} スロットに置かれる、属性を取得する総称的な関数です。この関数は、 (もし存在すれば) オブジェクトの属性 @ref{77d,,__dict__} に加え、オブジェクトの MRO にあるクラスの辞書にあるデスクリプタを探します。 @ref{e49,,デスクリプタ (descriptor) の実装} で概要が述べられている通り、データのデスクリプタはインスタンスの属性より優先され、非データデスクリプタは後回しにされます。見付からなかった場合は @ref{5f0,,AttributeError} を送出します。
@end deffn

@geindex PyObject_SetAttr (C function)
@anchor{c-api/object c PyObject_SetAttr}@anchor{5097}
@deffn {C の関数} int PyObject_SetAttr (PyObject *o, PyObject *attr_name, PyObject *v)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `o' の `attr_name' という名の属性に、値 `v' を設定します。
失敗すると例外を送出し @code{-1} を返します; 成功すると @code{0} を返します。
この関数は Python の式 @code{o.attr_name = v} と同じです。

`v' が @code{NULL} のとき、アトリビュートは削除されます。この動作は @ref{1831,,PyObject_DelAttr()} のため、非推奨となっていますが、削除される予定はありません。
@end deffn

@geindex PyObject_SetAttrString (C function)
@anchor{c-api/object c PyObject_SetAttrString}@anchor{198e}
@deffn {C の関数} int PyObject_SetAttrString (PyObject *o, const char *attr_name, PyObject *v)
` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{5097,,PyObject_SetAttr()}, but `attr_name' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.

`v' が @code{NULL} の場合は属性が削除されますが、この機能は非推奨であり @ref{1832,,PyObject_DelAttrString()} を使うのが望ましいです。

The number of different attribute names passed to this function
should be kept small, usually by using a statically allocated string
as `attr_name'.
For attribute names that aren't known at compile time, prefer calling
@ref{5112,,PyUnicode_FromString()} and @ref{5097,,PyObject_SetAttr()} directly.
For more details, see @ref{198c,,PyUnicode_InternFromString()}, which may be
used internally to create a key object.
@end deffn

@geindex PyObject_GenericSetAttr (C function)
@anchor{c-api/object c PyObject_GenericSetAttr}@anchor{508f}
@deffn {C の関数} int PyObject_GenericSetAttr (PyObject *o, PyObject *name, PyObject *value)
` 次に属します: @ref{775,,Stable ABI}.'
属性の設定と削除を行う汎用的な関数で、型オブジェクトの @ref{4ee8,,tp_setattro} スロットに置かれます。
オブジェクトの MRO にあるクラスの辞書からデータディスクリプタを探し、見付かった場合はインスタンスの辞書にある属性の設定や削除よりも優先されます。
そうでない場合は、(もし存在すれば) オブジェクトの @ref{77d,,__dict__} に属性を設定もしくは削除します。
成功すると @code{0} が返され、そうでない場合は @ref{5f0,,AttributeError} が送出され @code{-1} が返されます。
@end deffn

@geindex PyObject_DelAttr (C function)
@anchor{c-api/object c PyObject_DelAttr}@anchor{1831}
@deffn {C の関数} int PyObject_DelAttr (PyObject *o, PyObject *attr_name)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
オブジェクト `o' の `attr_name' という名の属性を削除します。失敗すると @code{-1} を返します。この関数は Python の文 @code{del o.attr_name} と同じです。
@end deffn

@geindex PyObject_DelAttrString (C function)
@anchor{c-api/object c PyObject_DelAttrString}@anchor{1832}
@deffn {C の関数} int PyObject_DelAttrString (PyObject *o, const char *attr_name)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
This is the same as @ref{1831,,PyObject_DelAttr()}, but `attr_name' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.

The number of different attribute names passed to this function
should be kept small, usually by using a statically allocated string
as `attr_name'.
For attribute names that aren't known at compile time, prefer calling
@ref{5112,,PyUnicode_FromString()} and @ref{1831,,PyObject_DelAttr()} directly.
For more details, see @ref{198c,,PyUnicode_InternFromString()}, which may be
used internally to create a key object for lookup.
@end deffn

@geindex PyObject_GenericGetDict (C function)
@anchor{c-api/object c PyObject_GenericGetDict}@anchor{1d05}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_GenericGetDict (PyObject *o, void *context)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
@code{__dict__} デスクリプタの getter の総称的な実装です。必要な場合は、辞書を作成します。

This function may also be called to get the @ref{77d,,__dict__}
of the object `o'. Pass @code{NULL} for `context' when calling it.
Since this function may need to allocate memory for the
dictionary, it may be more efficient to call @ref{5ee,,PyObject_GetAttr()}
when accessing an attribute on the object.

On failure, returns @code{NULL} with an exception set.


Added in version 3.3.

@end deffn

@geindex PyObject_GenericSetDict (C function)
@anchor{c-api/object c PyObject_GenericSetDict}@anchor{5090}
@deffn {C の関数} int PyObject_GenericSetDict (PyObject *o, PyObject *value, void *context)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@code{__dict__} デスクリプタの setter の総称的な実装です。この実装では辞書を削除することは許されていません。


Added in version 3.3.

@end deffn

@geindex _PyObject_GetDictPtr (C function)
@anchor{c-api/object c _PyObject_GetDictPtr}@anchor{5288}
@deffn {C の関数} @ref{5df,,PyObject} **_PyObject_GetDictPtr (PyObject *obj)

Return a pointer to @ref{77d,,__dict__} of the object `obj'.
If there is no @code{__dict__}, return @code{NULL} without setting an exception.

This function may need to allocate memory for the
dictionary, so it may be more efficient to call @ref{5ee,,PyObject_GetAttr()}
when accessing an attribute on the object.
@end deffn

@geindex PyObject_RichCompare (C function)
@anchor{c-api/object c PyObject_RichCompare}@anchor{4ef1}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_RichCompare (PyObject *o1, PyObject *o2, int opid)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Compare the values of `o1' and `o2' using the operation specified by `opid',
which must be one of @ref{5289,,Py_LT}, @ref{528a,,Py_LE}, @ref{528b,,Py_EQ},
@ref{528c,,Py_NE}, @ref{528d,,Py_GT}, or @ref{528e,,Py_GE}, corresponding to @code{<},
@code{<=}, @code{==}, @code{!=}, @code{>}, or @code{>=} respectively. This is the equivalent of
the Python expression @code{o1 op o2}, where @code{op} is the operator corresponding
to `opid'. Returns the value of the comparison on success, or @code{NULL} on failure.
@end deffn

@geindex PyObject_RichCompareBool (C function)
@anchor{c-api/object c PyObject_RichCompareBool}@anchor{1d8c}
@deffn {C の関数} int PyObject_RichCompareBool (PyObject *o1, PyObject *o2, int opid)
` 次に属します: @ref{775,,Stable ABI}.'
Compare the values of `o1' and `o2' using the operation specified by `opid',
like @ref{4ef1,,PyObject_RichCompare()}, but returns @code{-1} on error, @code{0} if
the result is false, @code{1} otherwise.
@end deffn

@cartouche
@quotation 注釈 
If `o1' and `o2' are the same object, @ref{1d8c,,PyObject_RichCompareBool()}
will always return @code{1} for @ref{528b,,Py_EQ} and @code{0} for @ref{528c,,Py_NE}.
@end quotation
@end cartouche

@geindex PyObject_Format (C function)
@anchor{c-api/object c PyObject_Format}@anchor{508d}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Format (PyObject *obj, PyObject *format_spec)
` 次に属します: @ref{775,,Stable ABI}.'
Format `obj' using `format_spec'. This is equivalent to the Python
expression @code{format(obj, format_spec)}.

`format_spec' may be @code{NULL}. In this case the call is equivalent
to @code{format(obj)}.
Returns the formatted string on success, @code{NULL} on failure.
@end deffn

@geindex PyObject_Repr (C function)
@anchor{c-api/object c PyObject_Repr}@anchor{1230}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Repr (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;repr

オブジェクト `o' の文字列表現を計算します。成功すると文字列表現を返し、失敗すると @code{NULL} を返します。 Python 式 @code{repr(o)} と同じです。この関数は組み込み関数 @ref{1c1,,repr()} の処理で呼び出されます。


バージョン 3.4 で変更: アクティブな例外を黙って捨てないことを保証するのに便利なように、この関数はデバッグアサーションを含むようになりました。

@end deffn

@geindex PyObject_ASCII (C function)
@anchor{c-api/object c PyObject_ASCII}@anchor{5086}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_ASCII (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;ascii

@ref{1230,,PyObject_Repr()} と同様、オブジェクト `o' の文字列表現を計算しますが、 @ref{1230,,PyObject_Repr()} によって返された文字列に含まれる非 ASCII 文字を、エスケープ文字 @code{\x} 、 @code{\u} 、 @code{\U} でエスケープします。この関数は Pythoh 2 の @ref{1230,,PyObject_Repr()} が返す文字列と同じ文字列を生成します。 @ref{15ff,,ascii()} によって呼び出されます。

@geindex string;PyObject_Str (C 関数)
@end deffn

@geindex PyObject_Str (C function)
@anchor{c-api/object c PyObject_Str}@anchor{1231}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Str (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `o' の文字列表現を計算します。成功すると文字列表現を返し、失敗すると @code{NULL} を返します。 Python 式 @code{str(o)} と同じです。この関数は組み込み関数 @ref{169,,str()} や、 @ref{1177,,print()} 関数の処理で呼び出されます。


バージョン 3.4 で変更: アクティブな例外を黙って捨てないことを保証するのに便利なように、この関数はデバッグアサーションを含むようになりました。

@end deffn

@geindex PyObject_Bytes (C function)
@anchor{c-api/object c PyObject_Bytes}@anchor{5088}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Bytes (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;bytes

オブジェクト `o' のバイト列表現を計算します。失敗すると @code{NULL} を返し、成功すると bytes オブジェクトを返します。 `o' が整数でないときの、 Python 式 @code{bytes(o)} と同じです。 @code{bytes(o)} と違って、 `o' が整数のときには、ゼロで初期化された bytes オブジェクトを返すのではなく TypeError が送出されます。
@end deffn

@geindex PyObject_IsSubclass (C function)
@anchor{c-api/object c PyObject_IsSubclass}@anchor{10a7}
@deffn {C の関数} int PyObject_IsSubclass (PyObject *derived, PyObject *cls)
` 次に属します: @ref{775,,Stable ABI}.'
クラス `derived' がクラス `cls' と同一であるか、そこから派生したクラスである場合は @code{1} を返し、そうでない場合は @code{0} を返します。
エラーが起きた場合は @code{-1} を返します。

`cls' がタプルの場合、 `cls' の全ての要素に対してチェックします。
少なくとも1つのチェックで @code{1} が返ったとき、結果は @code{1} となり、それ以外のとき @code{0} になります。

If `cls' has a @ref{23c7,,__subclasscheck__()} method, it will be called to
determine the subclass status as described in 
@geindex Python Enhancement Proposals; PEP 3119
PEP 3119@footnote{https://peps.python.org/pep-3119/}.  Otherwise,
`derived' is a subclass of `cls' if it is a direct or indirect subclass,
i.e. contained in @ref{2378,,cls.__mro__}.

Normally only class objects, i.e. instances of @ref{f44,,type} or a derived
class, are considered classes.  However, objects can override this by having
a @ref{16c5,,__bases__} attribute (which must be a tuple of base classes).
@end deffn

@geindex PyObject_IsInstance (C function)
@anchor{c-api/object c PyObject_IsInstance}@anchor{10a6}
@deffn {C の関数} int PyObject_IsInstance (PyObject *inst, PyObject *cls)
` 次に属します: @ref{775,,Stable ABI}.'
`inst' がクラス `cls' もしくは `cls' の子クラスのインスタンスである場合に @code{1} を返し、そうでない場合に @code{0} を返します。
エラーが起きると @code{-1} を返し例外を設定します。

`cls' がタプルの場合、 `cls' の全ての要素に対してチェックします。
少なくとも1つのチェックで @code{1} が返ったとき、結果は @code{1} となり、それ以外のとき @code{0} になります。

If `cls' has a @ref{23c6,,__instancecheck__()} method, it will be called to
determine the subclass status as described in 
@geindex Python Enhancement Proposals; PEP 3119
PEP 3119@footnote{https://peps.python.org/pep-3119/}.  Otherwise, `inst'
is an instance of `cls' if its class is a subclass of `cls'.

An instance `inst' can override what is considered its class by having a
@ref{16c6,,__class__} attribute.

An object `cls' can override if it is considered a class, and what its base
classes are, by having a @ref{16c5,,__bases__} attribute (which must be a tuple
of base classes).
@end deffn

@geindex PyObject_Hash (C function)
@anchor{c-api/object c PyObject_Hash}@anchor{436}
@deffn {C の関数} @ref{147b,,Py_hash_t} PyObject_Hash (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;hash

オブジェクト `o' のハッシュ値を計算して返します。失敗すると @code{-1} を返します。 Python の式 @code{hash(o)} と同じです。


バージョン 3.2 で変更: 返り値の型が Py_hash_t になりました。この型は、 @ref{c55,,Py_ssize_t} と同じサイズをもつ符号付き整数です。

@end deffn

@geindex PyObject_HashNotImplemented (C function)
@anchor{c-api/object c PyObject_HashNotImplemented}@anchor{15e0}
@deffn {C の関数} @ref{147b,,Py_hash_t} PyObject_HashNotImplemented (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
Set a @ref{198,,TypeError} indicating that @code{type(o)} is not @ref{824,,hashable} and return @code{-1}.
This function receives special treatment when stored in a @code{tp_hash} slot,
allowing a type to explicitly indicate to the interpreter that it is not
hashable.
@end deffn

@geindex PyObject_IsTrue (C function)
@anchor{c-api/object c PyObject_IsTrue}@anchor{5093}
@deffn {C の関数} int PyObject_IsTrue (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
`o' が真を表すとみなせる場合には @code{1} を、そうでないときには @code{0} を返します。   Python の式 @code{not not o} と同じです。失敗すると @code{-1} を返します。
@end deffn

@geindex PyObject_Not (C function)
@anchor{c-api/object c PyObject_Not}@anchor{5095}
@deffn {C の関数} int PyObject_Not (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
`o' が真を表すとみなせる場合には @code{0} を、そうでないときには @code{1} を返します。   Python の式 @code{not o} と同じです。失敗すると @code{-1} を返します。
@end deffn

@geindex PyObject_Type (C function)
@anchor{c-api/object c PyObject_Type}@anchor{5099}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Type (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;type

When `o' is non-@code{NULL}, returns a type object corresponding to the object type
of object `o'. On failure, raises @ref{795,,SystemError} and returns @code{NULL}.  This
is equivalent to the Python expression @code{type(o)}.
This function creates a new @ref{5e2,,strong reference} to the return value.
There's really no reason to use this
function instead of the @ref{3c9,,Py_TYPE()} function, which returns a
pointer of type @ref{c9c,,PyTypeObject}*, except when a new
@ref{5e2,,strong reference} is needed.
@end deffn

@geindex PyObject_TypeCheck (C function)
@anchor{c-api/object c PyObject_TypeCheck}@anchor{1cb5}
@deffn {C の関数} int PyObject_TypeCheck (PyObject *o, PyTypeObject *type)

Return non-zero if the object `o' is of type `type' or a subtype of `type', and
@code{0} otherwise.  Both parameters must be non-@code{NULL}.
@end deffn

@geindex PyObject_Size (C function)
@geindex PyObject_Length (C function)
@anchor{c-api/object c PyObject_Size}@anchor{5098}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyObject_Size (PyObject *o)
@anchor{c-api/object c PyObject_Length}@anchor{5094}
@deffnx {C の関数} @ref{c55,,Py_ssize_t} PyObject_Length (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;len

`o' の長さを返します。ただしオブジェクト `o' がシーケンス型プロトコルとマップ型プロトコルの両方を提供している場合、シーケンスとしての長さを返します。エラーが生じると @code{-1} を返します。 Python の式 @code{len(o)} と同じです。
@end deffn

@geindex PyObject_LengthHint (C function)
@anchor{c-api/object c PyObject_LengthHint}@anchor{1206}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyObject_LengthHint (PyObject *o, Py_ssize_t defaultvalue)

オブジェクト `o' の概算の長さを返します。
最初に実際の長さを、次に @ref{110f,,__length_hint__()} を使って概算の長さを、そして最後にデフォルトの値を返そうとします。
この関数は Python の式 @code{operator.length_hint(o, defaultvalue)} と同じです。


Added in version 3.4.

@end deffn

@geindex PyObject_GetItem (C function)
@anchor{c-api/object c PyObject_GetItem}@anchor{5ea}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_GetItem (PyObject *o, PyObject *key)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `key' に対応する `o' の要素を返します。失敗すると @code{NULL} を返します。Python の式 @code{o[key]} と同じです。
@end deffn

@geindex PyObject_SetItem (C function)
@anchor{c-api/object c PyObject_SetItem}@anchor{4f48}
@deffn {C の関数} int PyObject_SetItem (PyObject *o, PyObject *key, PyObject *v)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `key' を値 `v' に対応付けます。
失敗すると、例外を送出し @code{-1} を返します。成功すると @code{0} を返します。
これは Python の文 @code{o[key] = v} と同等です。
この関数は `v' への参照を `盗み取りません' 。
@end deffn

@geindex PyObject_DelItem (C function)
@anchor{c-api/object c PyObject_DelItem}@anchor{508a}
@deffn {C の関数} int PyObject_DelItem (PyObject *o, PyObject *key)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `o' から `key' に関する対応付けを削除します。失敗すると @code{-1} を返します。Python の文 @code{del o[key]} と同じです。
@end deffn

@geindex PyObject_DelItemString (C function)
@anchor{c-api/object c PyObject_DelItemString}@anchor{508b}
@deffn {C の関数} int PyObject_DelItemString (PyObject *o, const char *key)
` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{508a,,PyObject_DelItem()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.
@end deffn

@geindex PyObject_Dir (C function)
@anchor{c-api/object c PyObject_Dir}@anchor{508c}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Dir (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
この関数は Python の式 @code{dir(o)} と同じで、オブジェクトの変数名に割り当てている文字列からなるリスト (空の場合もあります) を返します。エラーの場合には @code{NULL} を返します。引数を @code{NULL} にすると、Python における @code{dir()} と同様に、現在のローカルな名前を返します; この場合、アクティブな実行フレームがなければ @code{NULL} を返しますが、 @ref{1caf,,PyErr_Occurred()} は偽を返します。
@end deffn

@geindex PyObject_GetIter (C function)
@anchor{c-api/object c PyObject_GetIter}@anchor{5092}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_GetIter (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Python の式 @code{iter(o)} と同じです。引数にとったオブジェクトに対する新たなイテレータか、オブジェクトがすでにイテレータの場合にはオブジェクト自身を返します。オブジェクトが反復処理不可能であった場合には @ref{198,,TypeError} を送出して @code{NULL} を返します。
@end deffn

@geindex PyObject_SelfIter (C function)
@anchor{c-api/object c PyObject_SelfIter}@anchor{5096}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_SelfIter (PyObject *obj)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
This is equivalent to the Python @code{__iter__(self): return self} method.
It is intended for @ref{4c8,,iterator} types, to be used in the @ref{1708,,PyTypeObject.tp_iter} slot.
@end deffn

@geindex PyObject_GetAIter (C function)
@anchor{c-api/object c PyObject_GetAIter}@anchor{5091}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_GetAIter (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
This is the equivalent to the Python expression @code{aiter(o)}. Takes an
@code{AsyncIterable} object and returns an @code{AsyncIterator} for it.
This is typically a new iterator but if the argument is an
@code{AsyncIterator}, this returns itself. Raises @ref{198,,TypeError} and
returns @code{NULL} if the object cannot be iterated.


Added in version 3.10.

@end deffn

@geindex PyObject_GetTypeData (C function)
@anchor{c-api/object c PyObject_GetTypeData}@anchor{76b}
@deffn {C の関数} void *PyObject_GetTypeData (PyObject *o, PyTypeObject *cls)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Get a pointer to subclass-specific data reserved for `cls'.

The object `o' must be an instance of `cls', and `cls' must have been
created using negative @ref{76a,,PyType_Spec.basicsize}.
Python does not check this.

On error, set an exception and return @code{NULL}.


Added in version 3.12.

@end deffn

@geindex PyType_GetTypeDataSize (C function)
@anchor{c-api/object c PyType_GetTypeDataSize}@anchor{76c}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyType_GetTypeDataSize (PyTypeObject *cls)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Return the size of the instance memory space reserved for `cls', i.e. the size of the
memory @ref{76b,,PyObject_GetTypeData()} returns.

This may be larger than requested using @ref{76a,,-PyType_Spec.basicsize};
it is safe to use this larger size (e.g. with @code{memset()}).

The type `cls' `must' have been created using
negative @ref{76a,,PyType_Spec.basicsize}.
Python does not check this.

On error, set an exception and return a negative value.


Added in version 3.12.

@end deffn

@geindex PyObject_GetItemData (C function)
@anchor{c-api/object c PyObject_GetItemData}@anchor{76e}
@deffn {C の関数} void *PyObject_GetItemData (PyObject *o)

Get a pointer to per-item data for a class with
@ref{76d,,Py_TPFLAGS_ITEMS_AT_END}.

On error, set an exception and return @code{NULL}.
@ref{198,,TypeError} is raised if `o' does not have
@ref{76d,,Py_TPFLAGS_ITEMS_AT_END} set.


Added in version 3.12.

@end deffn

@geindex PyObject_VisitManagedDict (C function)
@anchor{c-api/object c PyObject_VisitManagedDict}@anchor{60d}
@deffn {C の関数} int PyObject_VisitManagedDict (PyObject *obj, visitproc visit, void *arg)

Visit the managed dictionary of `obj'.

This function must only be called in a traverse function of the type which
has the @ref{60f,,Py_TPFLAGS_MANAGED_DICT} flag set.


Added in version 3.13.

@end deffn

@geindex PyObject_ClearManagedDict (C function)
@anchor{c-api/object c PyObject_ClearManagedDict}@anchor{60e}
@deffn {C の関数} void PyObject_ClearManagedDict (PyObject *obj)

Clear the managed dictionary of `obj'.

This function must only be called in a clear function of the type which
has the @ref{60f,,Py_TPFLAGS_MANAGED_DICT} flag set.


Added in version 3.13.

@end deffn

@geindex PyUnstable_Object_EnableDeferredRefcount (C function)
@anchor{c-api/object c PyUnstable_Object_EnableDeferredRefcount}@anchor{3c5}
@deffn {C の関数} int PyUnstable_Object_EnableDeferredRefcount (PyObject *obj)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Enable deferred reference counting@footnote{https://peps.python.org/pep-0703/#deferred-reference-counting} on `obj',
if supported by the runtime.  In the @ref{1f4,,free-threaded} build,
this allows the interpreter to avoid reference count adjustments to `obj',
which may improve multi-threaded performance.  The tradeoff is
that `obj' will only be deallocated by the tracing garbage collector, and
not when the interpreter no longer has any references to it.

This function returns @code{1} if deferred reference counting is enabled on `obj',
and @code{0} if deferred reference counting is not supported or if the hint was
ignored by the interpreter, such as when deferred reference counting is already
enabled on `obj'. This function is thread-safe, and cannot fail.

This function does nothing on builds with the @ref{164,,GIL} enabled, which do
not support deferred reference counting. This also does nothing if `obj' is not
an object tracked by the garbage collector (see @ref{1525,,gc.is_tracked()} and
@ref{b6d,,PyObject_GC_IsTracked()}).

This function is intended to be used soon after `obj' is created,
by the code that creates it, such as in the object's @ref{79f,,tp_new}
slot.


Added in version 3.14.

@end deffn

@geindex PyUnstable_Object_IsUniqueReferencedTemporary (C function)
@anchor{c-api/object c PyUnstable_Object_IsUniqueReferencedTemporary}@anchor{3c7}
@deffn {C の関数} int PyUnstable_Object_IsUniqueReferencedTemporary (PyObject *obj)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Check if `obj' is a unique temporary object.
Returns @code{1} if `obj' is known to be a unique temporary object,
and @code{0} otherwise.  This function cannot fail, but the check is
conservative, and may return @code{0} in some cases even if `obj' is a unique
temporary object.

If an object is a unique temporary, it is guaranteed that the current code
has the only reference to the object. For arguments to C functions, this
should be used instead of checking if the reference count is @code{1}. Starting
with Python 3.14, the interpreter internally avoids some reference count
modifications when loading objects onto the operands stack by
@ref{3d7,,borrowing} references when possible, which means
that a reference count of @code{1} by itself does not guarantee that a function
argument uniquely referenced.

In the example below, @code{my_func} is called with a unique temporary object
as its argument:

@example
my_func([1, 2, 3])
@end example

In the example below, @code{my_func} is `not' called with a unique temporary
object as its argument, even if its refcount is @code{1}:

@example
my_list = [1, 2, 3]
my_func(my_list)
@end example

See also the function @ref{2cf,,Py_REFCNT()}.


Added in version 3.14.

@end deffn

@geindex PyUnstable_IsImmortal (C function)
@anchor{c-api/object c PyUnstable_IsImmortal}@anchor{3c4}
@deffn {C の関数} int PyUnstable_IsImmortal (PyObject *obj)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

This function returns non-zero if `obj' is @ref{290,,immortal}, and zero
otherwise. This function cannot fail.

@cartouche
@quotation 注釈 
Objects that are immortal in one CPython version are not guaranteed to
be immortal in another.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@geindex PyUnstable_TryIncRef (C function)
@anchor{c-api/object c PyUnstable_TryIncRef}@anchor{18c9}
@deffn {C の関数} int PyUnstable_TryIncRef (PyObject *obj)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Increments the reference count of `obj' if it is not zero.  Returns @code{1}
if the object's reference count was successfully incremented. Otherwise,
this function returns @code{0}.

@ref{18ca,,PyUnstable_EnableTryIncRef()} must have been called
earlier on `obj' or this function may spuriously return @code{0} in the
@ref{176d,,free-threaded build}.

This function is logically equivalent to the following C code, except that
it behaves atomically in the @ref{176d,,free-threaded build}:

@example
if (Py_REFCNT(op) > 0) @{
   Py_INCREF(op);
   return 1;
@}
return 0;
@end example

This is intended as a building block for managing weak references
without the overhead of a Python @ref{528f,,weak reference object}.

Typically, correct use of this function requires support from `obj''s
deallocator (@ref{4ebc,,tp_dealloc}).
For example, the following sketch could be adapted to implement a
"weakmap" that works like a @ref{192a,,WeakValueDictionary}
for a specific type:

@example
PyMutex mutex;

PyObject *
add_entry(weakmap_key_type *key, PyObject *value)
@{
    PyUnstable_EnableTryIncRef(value);
    weakmap_type weakmap = ...;
    PyMutex_Lock(&mutex);
    weakmap_add_entry(weakmap, key, value);
    PyMutex_Unlock(&mutex);
    Py_RETURN_NONE;
@}

PyObject *
get_value(weakmap_key_type *key)
@{
    weakmap_type weakmap = ...;
    PyMutex_Lock(&mutex);
    PyObject *result = weakmap_find(weakmap, key);
    if (PyUnstable_TryIncRef(result)) @{
        // `result` is safe to use
        PyMutex_Unlock(&mutex);
        return result;
    @}
    // if we get here, `result` is starting to be garbage-collected,
    // but has not been removed from the weakmap yet
    PyMutex_Unlock(&mutex);
    return NULL;
@}

// tp_dealloc function for weakmap values
void
value_dealloc(PyObject *value)
@{
    weakmap_type weakmap = ...;
    PyMutex_Lock(&mutex);
    weakmap_remove_value(weakmap, value);

    ...
    PyMutex_Unlock(&mutex);
@}
@end example


Added in version 3.14.

@end deffn

@geindex PyUnstable_EnableTryIncRef (C function)
@anchor{c-api/object c PyUnstable_EnableTryIncRef}@anchor{18ca}
@deffn {C の関数} void PyUnstable_EnableTryIncRef (PyObject *obj)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Enables subsequent uses of @ref{18c9,,PyUnstable_TryIncRef()} on `obj'.  The
caller must hold a @ref{5e2,,strong reference} to `obj' when calling this.


Added in version 3.14.

@end deffn

@geindex PyUnstable_Object_IsUniquelyReferenced (C function)
@anchor{c-api/object c PyUnstable_Object_IsUniquelyReferenced}@anchor{3c6}
@deffn {C の関数} int PyUnstable_Object_IsUniquelyReferenced (PyObject *op)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Determine if `op' only has one reference.

On GIL-enabled builds, this function is equivalent to
@ref{2cf,,Py_REFCNT}(@ref{3c6,,op}) == 1.

On a @ref{176d,,free-threaded build}, this checks if `op''s
@ref{4ec9,,reference count} is equal to one and additionally checks if `op'
is only used by this thread. @ref{2cf,,Py_REFCNT}(@ref{3c6,,op}) == 1 is `not'
thread-safe on free-threaded builds; prefer this function.

The caller must hold an @ref{4ed1,,attached thread state}, despite the fact
that this function doesn't call into the Python interpreter. This function
cannot fail.


Added in version 3.14.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Call プロトコル,数値型プロトコル number protocol,オブジェクトプロトコル object protocol,抽象オブジェクトレイヤ Abstract Objects Layer
@anchor{c-api/call doc}@anchor{5290}@anchor{c-api/call call}@anchor{7a3}@anchor{c-api/call call-protocol}@anchor{5291}@anchor{c-api/call translation-repo}@anchor{5292}
@subsection Call プロトコル


CPython supports two different calling protocols:
`tp_call' and vectorcall.

@menu
* The tp_call Protocol:: 
* The Vectorcall Protocol:: 
* Object Calling API:: 
* Call Support API:: 

@end menu

@node The tp_call Protocol,The Vectorcall Protocol,,Call プロトコル
@anchor{c-api/call the-tp-call-protocol}@anchor{5293}
@subsubsection The `tp_call' Protocol


Instances of classes that set @ref{77b,,tp_call} are callable.
The signature of the slot is:

@example
PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);
@end example

A call is made using a tuple for the positional arguments
and a dict for the keyword arguments, similarly to
@code{callable(*args, **kwargs)} in Python code.
`args' must be non-NULL (use an empty tuple if there are no arguments)
but `kwargs' may be `NULL' if there are no keyword arguments.

This convention is not only used by `tp_call':
@ref{79f,,tp_new} and @ref{7a1,,tp_init}
also pass arguments this way.

To call an object, use @ref{63d,,PyObject_Call()} or another
@ref{5294,,call API}.

@node The Vectorcall Protocol,Object Calling API,The tp_call Protocol,Call プロトコル
@anchor{c-api/call the-vectorcall-protocol}@anchor{5295}@anchor{c-api/call vectorcall}@anchor{774}
@subsubsection The Vectorcall Protocol



Added in version 3.9.


The vectorcall protocol was introduced in 
@geindex Python Enhancement Proposals; PEP 590
PEP 590@footnote{https://peps.python.org/pep-0590/} as an additional protocol
for making calls more efficient.

As rule of thumb, CPython will prefer the vectorcall for internal calls
if the callable supports it. However, this is not a hard rule.
Additionally, some third-party extensions use `tp_call' directly
(rather than using @ref{63d,,PyObject_Call()}).
Therefore, a class supporting vectorcall must also implement
@ref{77b,,tp_call}.
Moreover, the callable must behave the same
regardless of which protocol is used.
The recommended way to achieve this is by setting
@ref{77b,,tp_call} to @ref{778,,PyVectorcall_Call()}.
This bears repeating:

@cartouche
@quotation 警告 
A class supporting vectorcall `must' also implement
@ref{77b,,tp_call} with the same semantics.
@end quotation
@end cartouche


バージョン 3.12 で変更: The @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag is now removed from a class
when the class's @ref{77a,,__call__()} method is reassigned.
(This internally sets @ref{77b,,tp_call} only, and thus
may make it behave differently than the vectorcall function.)
In earlier Python versions, vectorcall should only be used with
@ref{3cf,,immutable} or static types.


A class should not implement vectorcall if that would be slower
than `tp_call'. For example, if the callee needs to convert
the arguments to an args tuple and kwargs dict anyway, then there is no point
in implementing vectorcall.

Classes can implement the vectorcall protocol by enabling the
@ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag and setting
@ref{5296,,tp_vectorcall_offset} to the offset inside the
object structure where a `vectorcallfunc' appears.
This is a pointer to a function with the following signature:

@geindex vectorcallfunc (C type)
@anchor{c-api/call c vectorcallfunc}@anchor{779}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*vectorcallfunc)(@ref{5df,,PyObject} *callable, @ref{5df,,PyObject} *const *args, size_t nargsf, @ref{5df,,PyObject} *kwnames)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn


@itemize -

@item 
`callable' is the object being called.

@item 

@table @asis

@item `args' is a C array consisting of the positional arguments followed by the

values of the keyword arguments.
This can be `NULL' if there are no arguments.
@end table

@item 

@table @asis

@item `nargsf' is the number of positional arguments plus possibly the

@ref{780,,PY_VECTORCALL_ARGUMENTS_OFFSET} flag.
To get the actual number of positional arguments from `nargsf',
use @ref{777,,PyVectorcall_NARGS()}.
@end table

@item 

@table @asis

@item `kwnames' is a tuple containing the names of the keyword arguments;

in other words, the keys of the kwargs dict.
These names must be strings (instances of @code{str} or a subclass)
and they must be unique.
If there are no keyword arguments, then `kwnames' can instead be `NULL'.
@end table
@end itemize

@geindex PY_VECTORCALL_ARGUMENTS_OFFSET (C macro)
@anchor{c-api/call c PY_VECTORCALL_ARGUMENTS_OFFSET}@anchor{780}
@deffn {C のマクロ} PY_VECTORCALL_ARGUMENTS_OFFSET
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
If this flag is set in a vectorcall `nargsf' argument, the callee is allowed
to temporarily change @code{args[-1]}. In other words, `args' points to
argument 1 (not 0) in the allocated vector.
The callee must restore the value of @code{args[-1]} before returning.

For @ref{77f,,PyObject_VectorcallMethod()}, this flag means instead that
@code{args[0]} may be changed.

Whenever they can do so cheaply (without additional allocation), callers
are encouraged to use @ref{780,,PY_VECTORCALL_ARGUMENTS_OFFSET}.
Doing so will allow callables such as bound methods to make their onward
calls (which include a prepended `self' argument) very efficiently.


Added in version 3.8.

@end deffn

To call an object that implements vectorcall, use a @ref{5294,,call API}
function as with any other callable.
@ref{77e,,PyObject_Vectorcall()} will usually be most efficient.

@menu
* 再帰の管理: 再帰の管理<2>. 
* Vectorcall Support API:: 

@end menu

@node 再帰の管理<2>,Vectorcall Support API,,The Vectorcall Protocol
@anchor{c-api/call recursion-control}@anchor{5297}
@subsubsection 再帰の管理


When using `tp_call', callees do not need to worry about
@ref{51ff,,recursion}: CPython uses
@ref{3d2,,Py_EnterRecursiveCall()} and @ref{b6b,,Py_LeaveRecursiveCall()}
for calls made using `tp_call'.

For efficiency, this is not the case for calls done using vectorcall:
the callee should use `Py_EnterRecursiveCall' and `Py_LeaveRecursiveCall'
if needed.

@node Vectorcall Support API,,再帰の管理<2>,The Vectorcall Protocol
@anchor{c-api/call vectorcall-support-api}@anchor{5298}
@subsubsection Vectorcall Support API


@geindex PyVectorcall_NARGS (C function)
@anchor{c-api/call c PyVectorcall_NARGS}@anchor{777}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyVectorcall_NARGS (size_t nargsf)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Given a vectorcall `nargsf' argument, return the actual number of
arguments.
Currently equivalent to:

@example
(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)
@end example

However, the function @code{PyVectorcall_NARGS} should be used to allow
for future extensions.


Added in version 3.8.

@end deffn

@geindex PyVectorcall_Function (C function)
@anchor{c-api/call c PyVectorcall_Function}@anchor{5299}
@deffn {C の関数} @ref{779,,vectorcallfunc} PyVectorcall_Function (PyObject *op)

If `op' does not support the vectorcall protocol (either because the type
does not or because the specific instance does not), return `NULL'.
Otherwise, return the vectorcall function pointer stored in `op'.
This function never raises an exception.

This is mostly useful to check whether or not `op' supports vectorcall,
which can be done by checking @code{PyVectorcall_Function(op) != NULL}.


Added in version 3.9.

@end deffn

@geindex PyVectorcall_Call (C function)
@anchor{c-api/call c PyVectorcall_Call}@anchor{778}
@deffn {C の関数} @ref{5df,,PyObject} *PyVectorcall_Call (PyObject *callable, PyObject *tuple, PyObject *dict)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Call `callable''s @ref{779,,vectorcallfunc} with positional and keyword
arguments given in a tuple and dict, respectively.

This is a specialized function, intended to be put in the
@ref{77b,,tp_call} slot or be used in an implementation of @code{tp_call}.
It does not check the @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag
and it does not fall back to @code{tp_call}.


Added in version 3.8.

@end deffn

@node Object Calling API,Call Support API,The Vectorcall Protocol,Call プロトコル
@anchor{c-api/call capi-call}@anchor{5294}@anchor{c-api/call object-calling-api}@anchor{529a}
@subsubsection Object Calling 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.

The following table summarizes the available functions;
please see individual documentation for details.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

関数

@tab

callable

@tab

@code{args}

@tab

@code{kwargs}

@item

@ref{63d,,PyObject_Call()}

@tab

@code{PyObject *}

@tab

tuple

@tab

dict/@code{NULL}

@item

@ref{63c,,PyObject_CallNoArgs()}

@tab

@code{PyObject *}

@tab

---

@tab

---

@item

@ref{b6f,,PyObject_CallOneArg()}

@tab

@code{PyObject *}

@tab

1 object

@tab

---

@item

@ref{4eac,,PyObject_CallObject()}

@tab

@code{PyObject *}

@tab

tuple/@code{NULL}

@tab

---

@item

@ref{63f,,PyObject_CallFunction()}

@tab

@code{PyObject *}

@tab

format

@tab

---

@item

@ref{640,,PyObject_CallMethod()}

@tab

obj + @code{char*}

@tab

format

@tab

---

@item

@ref{5089,,PyObject_CallFunctionObjArgs()}

@tab

@code{PyObject *}

@tab

variadic

@tab

---

@item

@ref{1ddf,,PyObject_CallMethodObjArgs()}

@tab

obj + name

@tab

variadic

@tab

---

@item

@ref{529b,,PyObject_CallMethodNoArgs()}

@tab

obj + name

@tab

---

@tab

---

@item

@ref{529c,,PyObject_CallMethodOneArg()}

@tab

obj + name

@tab

1 object

@tab

---

@item

@ref{77e,,PyObject_Vectorcall()}

@tab

@code{PyObject *}

@tab

vectorcall

@tab

vectorcall

@item

@ref{529d,,PyObject_VectorcallDict()}

@tab

@code{PyObject *}

@tab

vectorcall

@tab

dict/@code{NULL}

@item

@ref{77f,,PyObject_VectorcallMethod()}

@tab

arg + name

@tab

vectorcall

@tab

vectorcall

@end multitable


@geindex PyObject_Call (C function)
@anchor{c-api/call c PyObject_Call}@anchor{63d}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Call (PyObject *callable, PyObject *args, PyObject *kwargs)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
呼び出し可能な Python のオブジェクト `callable' を、タプル `args' として与えられる引数と辞書 `kwargs' として与えられる名前付き引数とともに呼び出します。

`args' は `NULL' であってはならず、引数を必要としない場合は空のタプルを使ってください。
`kwargs' は `NULL' でも構いません。

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。

これは次の Python の式と同等です: @code{callable(*args, **kwargs)} 。
@end deffn

@geindex PyObject_CallNoArgs (C function)
@anchor{c-api/call c PyObject_CallNoArgs}@anchor{63c}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallNoArgs (PyObject *callable)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Call a callable Python object `callable' without any arguments. It is the
most efficient way to call a callable Python object without any argument.

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。


Added in version 3.9.

@end deffn

@geindex PyObject_CallOneArg (C function)
@anchor{c-api/call c PyObject_CallOneArg}@anchor{b6f}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallOneArg (PyObject *callable, PyObject *arg)
`戻り値: 新しい参照。'
Call a callable Python object `callable' with exactly 1 positional argument
`arg' and no keyword arguments.

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。


Added in version 3.9.

@end deffn

@geindex PyObject_CallObject (C function)
@anchor{c-api/call c PyObject_CallObject}@anchor{4eac}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallObject (PyObject *callable, PyObject *args)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
呼び出し可能な Python のオブジェクト `callable' を、タプル `args' として与えられる引数とともに呼び出します。
引数が必要な場合は、 `args' は `NULL' で構いません。

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。

これは次の Python の式と同等です: @code{callable(*args)} 。
@end deffn

@geindex PyObject_CallFunction (C function)
@anchor{c-api/call c PyObject_CallFunction}@anchor{63f}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallFunction (PyObject *callable, const char *format, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
呼び出し可能な Python オブジェクト `callable' を可変数個の C 引数とともに呼び出します。
C 引数は @ref{3c2,,Py_BuildValue()} 形式のフォーマット文字列を使って記述します。
`format' は `NULL' かもしれず、与える引数がないことを表します。

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。

これは次の Python の式と同等です: @code{callable(*args)} 。

@ref{5df,,PyObject}* args だけを引数に渡す場合は、 @ref{5089,,PyObject_CallFunctionObjArgs()} がより速い方法であることを覚えておいてください。


バージョン 3.4 で変更: `format' の型が @code{char *} から変更されました。

@end deffn

@geindex PyObject_CallMethod (C function)
@anchor{c-api/call c PyObject_CallMethod}@anchor{640}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallMethod (PyObject *obj, const char *name, const char *format, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `obj' の `name' という名前のメソッドを、いくつかの C 引数とともに呼び出します。
C 引数はタプルを生成する @ref{3c2,,Py_BuildValue()} 形式のフォーマット文字列で記述されています。

`format' は `NULL' でもよく、引数が与えられないことを表します。

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。

これは次の Python の式と同等です: @code{obj.name(arg1, arg2, ...)} 。

@ref{5df,,PyObject}* args だけを引数に渡す場合は、 @ref{1ddf,,PyObject_CallMethodObjArgs()} がより速い方法であることを覚えておいてください。


バージョン 3.4 で変更: `name' と `format' の型が @code{char *} から変更されました。

@end deffn

@geindex PyObject_CallFunctionObjArgs (C function)
@anchor{c-api/call c PyObject_CallFunctionObjArgs}@anchor{5089}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallFunctionObjArgs (PyObject *callable, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
呼び出し可能な Python オブジェクト `callable' を可変数個の @ref{5df,,PyObject}* 引数とともに呼び出します。引数列は末尾に `NULL' がついた可変数個のパラメタとして与えます。

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。

これは次の Python の式と同等です: @code{callable(arg1, arg2, ...)} 。
@end deffn

@geindex PyObject_CallMethodObjArgs (C function)
@anchor{c-api/call c PyObject_CallMethodObjArgs}@anchor{1ddf}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallMethodObjArgs (PyObject *obj, PyObject *name, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Python オブジェクト `obj' のメソッドを呼び出します、メソッド名は Python 文字列オブジェクト `name' で与えます。可変数個の @ref{5df,,PyObject}* 引数と共に呼び出されます. 引数列は末尾に `NULL' がついた可変数個のパラメタとして与えます。

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。
@end deffn

@geindex PyObject_CallMethodNoArgs (C function)
@anchor{c-api/call c PyObject_CallMethodNoArgs}@anchor{529b}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallMethodNoArgs (PyObject *obj, PyObject *name)

Call a method of the Python object `obj' without arguments,
where the name of the method is given as a Python string object in `name'.

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。


Added in version 3.9.

@end deffn

@geindex PyObject_CallMethodOneArg (C function)
@anchor{c-api/call c PyObject_CallMethodOneArg}@anchor{529c}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_CallMethodOneArg (PyObject *obj, PyObject *name, PyObject *arg)

Call a method of the Python object `obj' with a single positional argument
`arg', where the name of the method is given as a Python string object in
`name'.

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。


Added in version 3.9.

@end deffn

@geindex _PyObject_Vectorcall (C function)

@geindex PyObject_Vectorcall (C function)
@anchor{c-api/call c _PyObject_Vectorcall}@anchor{529e}@anchor{c-api/call c PyObject_Vectorcall}@anchor{77e}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Vectorcall (PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Call a callable Python object `callable'.
The arguments are the same as for @ref{779,,vectorcallfunc}.
If `callable' supports @ref{774,,vectorcall}, this directly calls
the vectorcall function stored in `callable'.

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。


Added in version 3.8: as @code{_PyObject_Vectorcall}



バージョン 3.9 で変更: Renamed to the current name, without the leading underscore.
The old provisional name is @ref{23d,,soft deprecated}.

@end deffn

@geindex PyObject_VectorcallDict (C function)
@anchor{c-api/call c PyObject_VectorcallDict}@anchor{529d}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_VectorcallDict (PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwdict)

Call `callable' with positional arguments passed exactly as in the @ref{774,,vectorcall} protocol,
but with keyword arguments passed as a dictionary `kwdict'.
The `args' array contains only the positional arguments.

Regardless of which protocol is used internally,
a conversion of arguments needs to be done.
Therefore, this function should only be used if the caller
already has a dictionary ready to use for the keyword arguments,
but not a tuple for the positional arguments.


Added in version 3.9.

@end deffn

@geindex PyObject_VectorcallMethod (C function)
@anchor{c-api/call c PyObject_VectorcallMethod}@anchor{77f}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_VectorcallMethod (PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Call a method using the vectorcall calling convention. The name of the method
is given as a Python string `name'. The object whose method is called is
`args[0]', and the `args' array starting at `args[1]' represents the arguments
of the call. There must be at least one positional argument.
`nargsf' is the number of positional arguments including `args[0]',
plus @ref{780,,PY_VECTORCALL_ARGUMENTS_OFFSET} if the value of @code{args[0]} may
temporarily be changed. Keyword arguments can be passed just like in
@ref{77e,,PyObject_Vectorcall()}.

If the object has the @ref{5138,,Py_TPFLAGS_METHOD_DESCRIPTOR} feature,
this will call the unbound method object with the full
`args' vector as arguments.

成功したら呼び出しの結果を返し、失敗したら例外を送出し `NULL' を返します。


Added in version 3.9.

@end deffn

@node Call Support API,,Object Calling API,Call プロトコル
@anchor{c-api/call call-support-api}@anchor{529f}
@subsubsection Call Support API


@geindex PyCallable_Check (C function)
@anchor{c-api/call c PyCallable_Check}@anchor{4f92}
@deffn {C の関数} int PyCallable_Check (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `o' が呼び出し可能オブジェクトかどうか調べます。オブジェクトが呼び出し可能であるときに @code{1} を返し、そうでないときには @code{0} を返します。この関数呼び出しは常に成功します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 数値型プロトコル number protocol,シーケンス型プロトコル sequence protocol,Call プロトコル,抽象オブジェクトレイヤ Abstract Objects Layer
@anchor{c-api/number doc}@anchor{52a0}@anchor{c-api/number number}@anchor{52a1}@anchor{c-api/number number-protocol}@anchor{52a2}@anchor{c-api/number translation-repo}@anchor{52a3}
@subsection 数値型プロトコル (number protocol)


@geindex PyNumber_Check (C function)
@anchor{c-api/number c PyNumber_Check}@anchor{c5c}
@deffn {C の関数} int PyNumber_Check (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `o' が数値型プロトコルを提供している場合に @code{1} を返し、そうでないときには偽を返します。この関数呼び出しは常に成功します。


バージョン 3.8 で変更: `o' がインデックス整数だった場合、 @code{1} を返します。

@end deffn

@geindex PyNumber_Add (C function)
@anchor{c-api/number c PyNumber_Add}@anchor{5065}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Add (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' を加算した結果を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 + o2} と同じです。
@end deffn

@geindex PyNumber_Subtract (C function)
@anchor{c-api/number c PyNumber_Subtract}@anchor{507f}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Subtract (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' から `o2' を減算した結果を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 - o2} と同じです。
@end deffn

@geindex PyNumber_Multiply (C function)
@anchor{c-api/number c PyNumber_Multiply}@anchor{5078}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Multiply (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' を乗算した結果を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 * o2} と同じです。
@end deffn

@geindex PyNumber_MatrixMultiply (C function)
@anchor{c-api/number c PyNumber_MatrixMultiply}@anchor{10b6}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_MatrixMultiply (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
成功すると `o1' と `o2' を行列乗算した結果を返し、失敗すると @code{NULL} を返します。
Python の式 @code{o1 @@ o2} と同じです。


Added in version 3.5.

@end deffn

@geindex PyNumber_FloorDivide (C function)
@anchor{c-api/number c PyNumber_FloorDivide}@anchor{5069}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_FloorDivide (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return the floor of `o1' divided by `o2', or @code{NULL} on failure.  This is
the equivalent of the Python expression @code{o1 // o2}.
@end deffn

@geindex PyNumber_TrueDivide (C function)
@anchor{c-api/number c PyNumber_TrueDivide}@anchor{5080}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_TrueDivide (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a reasonable approximation for the mathematical value of `o1' divided by
`o2', or @code{NULL} on failure.  The return value is "approximate" because binary
floating-point numbers are approximate; it is not possible to represent all real
numbers in base two.  This function can return a floating-point value when
passed two integers.  This is the equivalent of the Python expression @code{o1 / o2}.
@end deffn

@geindex PyNumber_Remainder (C function)
@anchor{c-api/number c PyNumber_Remainder}@anchor{507d}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Remainder (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' を `o2' で除算した剰余を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 % o2} と同じです。
@end deffn

@geindex PyNumber_Divmod (C function)
@anchor{c-api/number c PyNumber_Divmod}@anchor{5068}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Divmod (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;divmod

組み込み関数 @ref{b99,,divmod()} を参照してください。失敗すると @code{NULL} を返します。 Python の式 @code{divmod(o1, o2)} と同じです。
@end deffn

@geindex PyNumber_Power (C function)
@anchor{c-api/number c PyNumber_Power}@anchor{507c}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Power (PyObject *o1, PyObject *o2, PyObject *o3)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;pow

組み込み関数 @ref{1a4,,pow()} を参照してください。失敗すると @code{NULL} を返します。 Python の式 @code{pow(o1, o2, o3)} と同じです。 `o3' はオプションです。 `o3' を無視させたいなら、 @ref{4e9f,,Py_None} を入れてください (`o3' に @code{NULL} を渡すと、不正なメモリアクセスを引き起こすことがあります)。
@end deffn

@geindex PyNumber_Negative (C function)
@anchor{c-api/number c PyNumber_Negative}@anchor{5079}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Negative (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o' の符号反転を返し、失敗すると @code{NULL} を返します。Python の式 @code{-o} と同じです。
@end deffn

@geindex PyNumber_Positive (C function)
@anchor{c-api/number c PyNumber_Positive}@anchor{507b}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Positive (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o' を返し、失敗すると @code{NULL} を返します。Python の式 @code{+o} と同じです。
@end deffn

@geindex PyNumber_Absolute (C function)
@anchor{c-api/number c PyNumber_Absolute}@anchor{5064}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Absolute (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;abs

成功すると `o' の絶対値を返し、失敗すると @code{NULL} を返します。Python の式 @code{abs(o)} と同じです。
@end deffn

@geindex PyNumber_Invert (C function)
@anchor{c-api/number c PyNumber_Invert}@anchor{5076}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Invert (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o' のビット単位反転 (bitwise negation) を返し、失敗すると @code{NULL} を返します。Python の式 @code{~o} と同じです。
@end deffn

@geindex PyNumber_Lshift (C function)
@anchor{c-api/number c PyNumber_Lshift}@anchor{5077}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Lshift (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' を `o2' だけ左シフトした結果を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 << o2} と同じです。
@end deffn

@geindex PyNumber_Rshift (C function)
@anchor{c-api/number c PyNumber_Rshift}@anchor{507e}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Rshift (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' を `o2' だけ右シフトした結果を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 >> o2} と同じです。
@end deffn

@geindex PyNumber_And (C function)
@anchor{c-api/number c PyNumber_And}@anchor{5066}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_And (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の "ビット単位論理積 (bitwise and)" を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 & o2} と同じです。
@end deffn

@geindex PyNumber_Xor (C function)
@anchor{c-api/number c PyNumber_Xor}@anchor{5081}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Xor (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の  "ビット単位排他的論理和 (bitwise exclusive or)" を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 ^ o2} と同じです。
@end deffn

@geindex PyNumber_Or (C function)
@anchor{c-api/number c PyNumber_Or}@anchor{507a}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Or (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の "ビット単位論理和 (bitwise or)" を返し失敗すると @code{NULL} を返します。Python の式 @code{o1 | o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceAdd (C function)
@anchor{c-api/number c PyNumber_InPlaceAdd}@anchor{506a}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceAdd (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' を加算した結果を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 += o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceSubtract (C function)
@anchor{c-api/number c PyNumber_InPlaceSubtract}@anchor{5073}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceSubtract (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' から `o2' を減算した結果を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 -= o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceMultiply (C function)
@anchor{c-api/number c PyNumber_InPlaceMultiply}@anchor{506e}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceMultiply (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' を乗算した結果を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 *= o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceMatrixMultiply (C function)
@anchor{c-api/number c PyNumber_InPlaceMatrixMultiply}@anchor{10b7}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceMatrixMultiply (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
成功すると `o1' と `o2' を行列乗算した結果を返し、失敗すると @code{NULL} を返します。
`o1' が `in-place' 演算をサポートする場合、 in-place 演算を行います。
Python の文 @code{o1 @@= o2} と同じです。


Added in version 3.5.

@end deffn

@geindex PyNumber_InPlaceFloorDivide (C function)
@anchor{c-api/number c PyNumber_InPlaceFloorDivide}@anchor{506c}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceFloorDivide (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' を `o2' で除算した切捨て値を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 //= o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceTrueDivide (C function)
@anchor{c-api/number c PyNumber_InPlaceTrueDivide}@anchor{5074}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceTrueDivide (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a reasonable approximation for the mathematical value of `o1' divided by
`o2', or @code{NULL} on failure.  The return value is "approximate" because binary
floating-point numbers are approximate; it is not possible to represent all real
numbers in base two.  This function can return a floating-point value when
passed two integers.  The operation is done `in-place' when `o1' supports it.
This is the equivalent of the Python statement @code{o1 /= o2}.
@end deffn

@geindex PyNumber_InPlaceRemainder (C function)
@anchor{c-api/number c PyNumber_InPlaceRemainder}@anchor{5071}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceRemainder (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' を `o2' で除算した剰余を返し、, 失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 %= o2} と同じです。
@end deffn

@geindex PyNumber_InPlacePower (C function)
@anchor{c-api/number c PyNumber_InPlacePower}@anchor{5070}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlacePower (PyObject *o1, PyObject *o2, PyObject *o3)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;pow

組み込み関数 @ref{1a4,,pow()} を参照してください。失敗すると @code{NULL} を返します。 `o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。この関数は `o3' が @ref{4e9f,,Py_None} の場合は Python 文 @code{o1 **= o2} と同じで、それ以外の場合は @code{pow(o1, o2, o3)} の in-place 版です。 `o3' を無視させたいなら、 @ref{4e9f,,Py_None} を入れてください (`o3' に @code{NULL} を渡すと、不正なメモリアクセスを引き起こすことがあります)。
@end deffn

@geindex PyNumber_InPlaceLshift (C function)
@anchor{c-api/number c PyNumber_InPlaceLshift}@anchor{506d}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceLshift (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' を `o2' だけ左シフトした結果を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 <<= o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceRshift (C function)
@anchor{c-api/number c PyNumber_InPlaceRshift}@anchor{5072}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceRshift (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' を `o2' だけ右シフトした結果を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 >>= o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceAnd (C function)
@anchor{c-api/number c PyNumber_InPlaceAnd}@anchor{506b}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceAnd (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の "ビット単位論理積 (bitwise and)" を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 &= o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceXor (C function)
@anchor{c-api/number c PyNumber_InPlaceXor}@anchor{5075}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceXor (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の "ビット単位排他的論理和  (bitwise exclusive or)" を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 ^= o2} と同じです。
@end deffn

@geindex PyNumber_InPlaceOr (C function)
@anchor{c-api/number c PyNumber_InPlaceOr}@anchor{506f}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_InPlaceOr (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の "ビット単位論理和 (bitwise or)" を返し失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の文 @code{o1 |= o2} と同じです。
@end deffn

@geindex PyNumber_Long (C function)
@anchor{c-api/number c PyNumber_Long}@anchor{c5d}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Long (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;int

成功すると `o' を整数に変換したものを返し、失敗すると @code{NULL} を返します。Python の式 @code{int(o)} と同じです。
@end deffn

@geindex PyNumber_Float (C function)
@anchor{c-api/number c PyNumber_Float}@anchor{c5e}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Float (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;浮動小数点数

成功すると `o' を浮動小数点数に変換したものを返し、失敗すると @code{NULL} を返します。Python の式 @code{float(o)} と同じです。
@end deffn

@geindex PyNumber_Index (C function)
@anchor{c-api/number c PyNumber_Index}@anchor{a93}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_Index (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`o' をPythonのint型に変換し、成功したらその値を返します。失敗したら @code{NULL} が返され、 @ref{198,,TypeError} 例外が送出されます。


バージョン 3.10 で変更: 結果は常に厳密な @ref{19b,,int} 型です。
以前は、結果は @code{int} のサブクラスのインスタンスのこともありました。

@end deffn

@geindex PyNumber_ToBase (C function)
@anchor{c-api/number c PyNumber_ToBase}@anchor{1b73}
@deffn {C の関数} @ref{5df,,PyObject} *PyNumber_ToBase (PyObject *n, int base)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`base' 進数に変換された整数 `n' を文字列として返します。 `base' 引数は2, 8, 10または16のいずれかでなければなりません。  基数2、8、16について、返される文字列の先頭には基数マーカー @code{'0b'} 、 @code{'0o'} または @code{'0x'} が、それぞれ付与されます。  もし `n' が Python のint型でなければ、まず @ref{a93,,PyNumber_Index()} で変換されます。
@end deffn

@geindex PyNumber_AsSsize_t (C function)
@anchor{c-api/number c PyNumber_AsSsize_t}@anchor{5067}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyNumber_AsSsize_t (PyObject *o, PyObject *exc)
` 次に属します: @ref{775,,Stable ABI}.'
`o' を整数として解釈可能だった場合、@ref{c55,,Py_ssize_t} 型の値に変換して返します。呼び出しが失敗したら、例外が送出され、 @code{-1} が返されます。

もし `o' がPythonのintに変換できたのに、@ref{c55,,Py_ssize_t} への変換が @ref{a81,,OverflowError} になる場合は、 `exc' 引数で渡された型 (普通は @ref{174e,,IndexError} か @ref{a81,,OverflowError}) の例外を送出します。もし、 `exc' が @code{NULL} なら、例外はクリアされて、値が負の場合は @code{PY_SSIZE_T_MIN} へ、正の場合は @code{PY_SSIZE_T_MAX} へと制限されます。
@end deffn

@geindex PyIndex_Check (C function)
@anchor{c-api/number c PyIndex_Check}@anchor{b81}
@deffn {C の関数} int PyIndex_Check (PyObject *o)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
`o' がインデックス整数である場合 (@code{tp_as_number} 構造体の @code{nb_index} スロットが埋まっている場合) に @code{1} を返し、そうでない場合に @code{0} を返します。
この関数は常に成功します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node シーケンス型プロトコル sequence protocol,マップ型プロトコル mapping protocol,数値型プロトコル number protocol,抽象オブジェクトレイヤ Abstract Objects Layer
@anchor{c-api/sequence doc}@anchor{52a4}@anchor{c-api/sequence sequence}@anchor{52a5}@anchor{c-api/sequence sequence-protocol}@anchor{52a6}@anchor{c-api/sequence translation-repo}@anchor{52a7}
@subsection シーケンス型プロトコル (sequence protocol)


@geindex PySequence_Check (C function)
@anchor{c-api/sequence c PySequence_Check}@anchor{50a0}
@deffn {C の関数} int PySequence_Check (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
Return @code{1} if the object provides the sequence protocol, and @code{0} otherwise.
Note that it returns @code{1} for Python classes with a @ref{588,,__getitem__()}
method, unless they are @ref{183,,dict} subclasses, since in general it
is impossible to determine what type of keys the class supports.  This
function always succeeds.
@end deffn

@geindex PySequence_Size (C function)
@geindex PySequence_Length (C function)
@anchor{c-api/sequence c PySequence_Size}@anchor{1e33}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PySequence_Size (PyObject *o)
@anchor{c-api/sequence c PySequence_Length}@anchor{50a8}
@deffnx {C の関数} @ref{c55,,Py_ssize_t} PySequence_Length (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;len

成功するとシーケンス `o' 中のオブジェクトの数を返し、失敗すると @code{-1} を返します。これは、Python の式 @code{len(o)} と同じになります。
@end deffn

@geindex PySequence_Concat (C function)
@anchor{c-api/sequence c PySequence_Concat}@anchor{50a1}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_Concat (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の連結 (concatenation) を返し、失敗すると @code{NULL} を返します。Python の式 @code{o1 + o2} と同じです。
@end deffn

@geindex PySequence_Repeat (C function)
@anchor{c-api/sequence c PySequence_Repeat}@anchor{50aa}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_Repeat (PyObject *o, Py_ssize_t count)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功するとオブジェクト `o' の `count' 回繰り返しを返し、失敗すると @code{NULL} を返します。Python の式 @code{o * count} と同じです。
@end deffn

@geindex PySequence_InPlaceConcat (C function)
@anchor{c-api/sequence c PySequence_InPlaceConcat}@anchor{50a5}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_InPlaceConcat (PyObject *o1, PyObject *o2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o1' と `o2' の連結 (concatenation) を返し、失敗すると @code{NULL} を返します。`o1' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の式 @code{o1 += o2} と同じです。
@end deffn

@geindex PySequence_InPlaceRepeat (C function)
@anchor{c-api/sequence c PySequence_InPlaceRepeat}@anchor{50a6}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_InPlaceRepeat (PyObject *o, Py_ssize_t count)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功するとオブジェクト `o' の `count' 回繰り返しを返し、失敗すると @code{NULL} を返します。`o' が `in-place' 演算をサポートする場合、in-place 演算を行います。Python の式 @code{o *= count} と同じです。
@end deffn

@geindex PySequence_GetItem (C function)
@anchor{c-api/sequence c PySequence_GetItem}@anchor{1e34}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_GetItem (PyObject *o, Py_ssize_t i)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o' の `i' 番目の要素を返し、失敗すると @code{NULL} を返します。Python の式 @code{o[i]} と同じです。
@end deffn

@geindex PySequence_GetSlice (C function)
@anchor{c-api/sequence c PySequence_GetSlice}@anchor{50a4}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_GetSlice (PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功すると `o' の `i1' から `i2' までの間のスライスを返し、失敗すると @code{NULL} を返します。Python の式 @code{o[i1:i2]} と同じです。
@end deffn

@geindex PySequence_SetItem (C function)
@anchor{c-api/sequence c PySequence_SetItem}@anchor{1e35}
@deffn {C の関数} int PySequence_SetItem (PyObject *o, Py_ssize_t i, PyObject *v)
` 次に属します: @ref{775,,Stable ABI}.'
`o' の `i' 番目の要素に `v' を代入します。
失敗すると、例外を送出し @code{-1} を返します;
成功すると @code{0} を返します。
これは Python の文 @code{o[i] = v} と同じです。
この関数は `v' への参照を `盗み取りません' 。

`v' が @code{NULL} の場合はその要素が削除されますが、この機能は非推奨であり、 @ref{1831,,PyObject_DelAttr()} を使うのが望ましいです。
@end deffn

@geindex PySequence_DelItem (C function)
@anchor{c-api/sequence c PySequence_DelItem}@anchor{1e36}
@deffn {C の関数} int PySequence_DelItem (PyObject *o, Py_ssize_t i)
` 次に属します: @ref{775,,Stable ABI}.'
`o' の `i' 番目の要素を削除します。失敗すると @code{-1} を返します。Python の文 @code{del o[i]} と同じです。
@end deffn

@geindex PySequence_SetSlice (C function)
@anchor{c-api/sequence c PySequence_SetSlice}@anchor{50ab}
@deffn {C の関数} int PySequence_SetSlice (PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)
` 次に属します: @ref{775,,Stable ABI}.'
`o' の `i1' から `i2' までの間のスライスに `v' を代入します。Python の文 @code{o[i1:i2] = v} と同じです。
@end deffn

@geindex PySequence_DelSlice (C function)
@anchor{c-api/sequence c PySequence_DelSlice}@anchor{50a3}
@deffn {C の関数} int PySequence_DelSlice (PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
` 次に属します: @ref{775,,Stable ABI}.'
シーケンスオブジェクト `o' の `i1' から `i2' までの間のスライスを削除します。失敗すると @code{-1} を返します。Python の文 @code{del o[i1:i2]} と同じです。
@end deffn

@geindex PySequence_Count (C function)
@anchor{c-api/sequence c PySequence_Count}@anchor{50a2}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PySequence_Count (PyObject *o, PyObject *value)
` 次に属します: @ref{775,,Stable ABI}.'
`o' における `value' の出現回数、すなわち  @code{o[key] == value} となる `key' の個数を返します。失敗すると @code{-1} を返します。Python の式 @code{o.count(value)} と同じです。
@end deffn

@geindex PySequence_Contains (C function)
@anchor{c-api/sequence c PySequence_Contains}@anchor{3d9}
@deffn {C の関数} int PySequence_Contains (PyObject *o, PyObject *value)
` 次に属します: @ref{775,,Stable ABI}.'
`o' に `value' が入っているか判定します。`o' のある要素が `value' と等価 (equal) ならば @code{1} を返し、それ以外の場合には @code{0} を返します。エラーが発生すると @code{-1} を返します。Python の式 @code{value in o} と同じです。
@end deffn

@geindex PySequence_In (C function)
@anchor{c-api/sequence c PySequence_In}@anchor{3d8}
@deffn {C の関数} int PySequence_In (PyObject *o, PyObject *value)
` 次に属します: @ref{775,,Stable ABI}.'
Alias for @ref{3d9,,PySequence_Contains()}.


バージョン 3.14 で非推奨: The function is @ref{23d,,soft deprecated} and should no longer be used to
write new code.

@end deffn

@geindex PySequence_Index (C function)
@anchor{c-api/sequence c PySequence_Index}@anchor{50a7}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PySequence_Index (PyObject *o, PyObject *value)
` 次に属します: @ref{775,,Stable ABI}.'
@code{o[i] == value} となる最初に見つかったインデクス `i' を返します。エラーが発生すると @code{-1} を返します。Python の式 @code{o.index(value)} と同じです。
@end deffn

@geindex PySequence_List (C function)
@anchor{c-api/sequence c PySequence_List}@anchor{50a9}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_List (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
シーケンスもしくはイテラブル `o' と同じ内容を持つリストオブジェクトを返します。
失敗したら @code{NULL} を返します。
返されるリストは新しく作られたことが保証されています。
これは Python の式 @code{list(o)} と同等です。
@end deffn

@geindex PySequence_Tuple (C function)
@anchor{c-api/sequence c PySequence_Tuple}@anchor{50ac}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_Tuple (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;tuple

シーケンスあるいはイテラブルである `o' と同じ内容を持つタプルオブジェクトを返します。
失敗したら @code{NULL} を返します。`o' がタプルの場合、新たな参照を返します。
それ以外の場合、適切な内容が入ったタプルを構築して返します。
Pythonの式 @code{tuple(o)} と同等です。
@end deffn

@geindex PySequence_Fast (C function)
@anchor{c-api/sequence c PySequence_Fast}@anchor{18a2}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_Fast (PyObject *o, const char *m)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
シーケンスまたはイテラブルの `o' を @code{PySequence_Fast*} ファミリの関数で利用できるオブジェクトとして返します。オブジェクトがシーケンスでもイテラブルでもない場合は、メッセージ `m' を持つ、 @ref{198,,TypeError} を送出します。失敗したら @code{NULL} を返します。

@code{PySequence_Fast*} ファミリの関数は、`o' が @ref{5224,,PyTupleObject} または @ref{52a8,,PyListObject} と仮定し、`o' のデータフィールドに直接アクセスするため、そのように名付けられています。

CPythonの実装では、もし `o' が 既にシーケンスかタプルであれば、`o' そのものを返します。
@end deffn

@geindex PySequence_Fast_GET_SIZE (C function)
@anchor{c-api/sequence c PySequence_Fast_GET_SIZE}@anchor{3ca}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PySequence_Fast_GET_SIZE (PyObject *o)

`o' が @code{NULL} でなく、 @ref{18a2,,PySequence_Fast()} が返したオブジェクトであると仮定して、 `o' の長さを返します。 `o' のサイズは @ref{1e33,,PySequence_Size()} を呼び出しても得られますが、 @ref{3ca,,PySequence_Fast_GET_SIZE()} の方が `o' をリストかタプルであると仮定して処理するため、より高速です。
@end deffn

@geindex PySequence_Fast_GET_ITEM (C function)
@anchor{c-api/sequence c PySequence_Fast_GET_ITEM}@anchor{3cb}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_Fast_GET_ITEM (PyObject *o, Py_ssize_t i)
`戻り値: 借用参照。'
`o' が @code{NULL} でなく、 @ref{18a2,,PySequence_Fast()} が返したオブジェクトであり、かつ `i' がインデクスの範囲内にあると仮定して、 `o' の `i' 番目の要素を返します。
@end deffn

@geindex PySequence_Fast_ITEMS (C function)
@anchor{c-api/sequence c PySequence_Fast_ITEMS}@anchor{3cc}
@deffn {C の関数} @ref{5df,,PyObject} **PySequence_Fast_ITEMS (PyObject *o)

PyObject ポインタの背後にあるアレイを返します。この関数では、 `o' は @ref{18a2,,PySequence_Fast()} の返したオブジェクトであり、 @code{NULL} でないものと仮定しています。

リストのサイズが変更されるとき、メモリ再確保が要素の配列を再配置するかもしれないことに注意してください。そのため、シーケンスの変更が発生しないコンテキストでのみ背後にあるポインタを使ってください。
@end deffn

@geindex PySequence_ITEM (C function)
@anchor{c-api/sequence c PySequence_ITEM}@anchor{52a9}
@deffn {C の関数} @ref{5df,,PyObject} *PySequence_ITEM (PyObject *o, Py_ssize_t i)
`戻り値: 新しい参照。'
`o' の `i' 番目の要素を返し、失敗すると @code{NULL} を返します。 @ref{1e34,,PySequence_GetItem()} の高速版であり、@ref{50a0,,PySequence_Check()} で `o' が真を返すかどうかの検証や、負の添え字の調整を行いません。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node マップ型プロトコル mapping protocol,イテレータプロトコル iterator protocol,シーケンス型プロトコル sequence protocol,抽象オブジェクトレイヤ Abstract Objects Layer
@anchor{c-api/mapping doc}@anchor{52aa}@anchor{c-api/mapping mapping}@anchor{52ab}@anchor{c-api/mapping mapping-protocol}@anchor{52ac}@anchor{c-api/mapping translation-repo}@anchor{52ad}
@subsection マップ型プロトコル (mapping protocol)


@ref{5ea,,PyObject_GetItem()}, @ref{4f48,,PyObject_SetItem()}, @ref{508a,,PyObject_DelItem()} も参照してください。

@geindex PyMapping_Check (C function)
@anchor{c-api/mapping c PyMapping_Check}@anchor{5051}
@deffn {C の関数} int PyMapping_Check (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
Return @code{1} if the object provides the mapping protocol or supports slicing,
and @code{0} otherwise.  Note that it returns @code{1} for Python classes with
a @ref{588,,__getitem__()} method, since in general it is impossible to
determine what type of keys the class supports. This function always succeeds.
@end deffn

@geindex PyMapping_Size (C function)
@geindex PyMapping_Length (C function)
@anchor{c-api/mapping c PyMapping_Size}@anchor{1e37}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyMapping_Size (PyObject *o)
@anchor{c-api/mapping c PyMapping_Length}@anchor{5052}
@deffnx {C の関数} @ref{c55,,Py_ssize_t} PyMapping_Length (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;len

成功するとオブジェクト `o' 中のキーの数を返し、失敗すると @code{-1} を返します。これは、Python の式 @code{len(o)} と同じになります。
@end deffn

@geindex PyMapping_GetItemString (C function)
@anchor{c-api/mapping c PyMapping_GetItemString}@anchor{5eb}
@deffn {C の関数} @ref{5df,,PyObject} *PyMapping_GetItemString (PyObject *o, const char *key)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{5ea,,PyObject_GetItem()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.
@end deffn

@geindex PyMapping_GetOptionalItem (C function)
@anchor{c-api/mapping c PyMapping_GetOptionalItem}@anchor{5e8}
@deffn {C の関数} int PyMapping_GetOptionalItem (PyObject *obj, PyObject *key, PyObject **result)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Variant of @ref{5ea,,PyObject_GetItem()} which doesn't raise
@ref{5e7,,KeyError} if the key is not found.

If the key is found, return @code{1} and set `*result' to a new
@ref{5e2,,strong reference} to the corresponding value.
If the key is not found, return @code{0} and set `*result' to @code{NULL};
the @ref{5e7,,KeyError} is silenced.
If an error other than @ref{5e7,,KeyError} is raised, return @code{-1} and
set `*result' to @code{NULL}.


Added in version 3.13.

@end deffn

@geindex PyMapping_GetOptionalItemString (C function)
@anchor{c-api/mapping c PyMapping_GetOptionalItemString}@anchor{5e9}
@deffn {C の関数} int PyMapping_GetOptionalItemString (PyObject *obj, const char *key, PyObject **result)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
This is the same as @ref{5e8,,PyMapping_GetOptionalItem()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.


Added in version 3.13.

@end deffn

@geindex PyMapping_SetItemString (C function)
@anchor{c-api/mapping c PyMapping_SetItemString}@anchor{5053}
@deffn {C の関数} int PyMapping_SetItemString (PyObject *o, const char *key, PyObject *v)
` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{4f48,,PyObject_SetItem()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.
@end deffn

@geindex PyMapping_DelItem (C function)
@anchor{c-api/mapping c PyMapping_DelItem}@anchor{52ae}
@deffn {C の関数} int PyMapping_DelItem (PyObject *o, PyObject *key)

This is an alias of @ref{508a,,PyObject_DelItem()}.
@end deffn

@geindex PyMapping_DelItemString (C function)
@anchor{c-api/mapping c PyMapping_DelItemString}@anchor{52af}
@deffn {C の関数} int PyMapping_DelItemString (PyObject *o, const char *key)

This is the same as @ref{508a,,PyObject_DelItem()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.
@end deffn

@geindex PyMapping_HasKeyWithError (C function)
@anchor{c-api/mapping c PyMapping_HasKeyWithError}@anchor{61f}
@deffn {C の関数} int PyMapping_HasKeyWithError (PyObject *o, PyObject *key)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return @code{1} if the mapping object has the key `key' and @code{0} otherwise.
This is equivalent to the Python expression @code{key in o}.
On failure, return @code{-1}.


Added in version 3.13.

@end deffn

@geindex PyMapping_HasKeyStringWithError (C function)
@anchor{c-api/mapping c PyMapping_HasKeyStringWithError}@anchor{621}
@deffn {C の関数} int PyMapping_HasKeyStringWithError (PyObject *o, const char *key)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
This is the same as @ref{61f,,PyMapping_HasKeyWithError()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.


Added in version 3.13.

@end deffn

@geindex PyMapping_HasKey (C function)
@anchor{c-api/mapping c PyMapping_HasKey}@anchor{620}
@deffn {C の関数} int PyMapping_HasKey (PyObject *o, PyObject *key)
` 次に属します: @ref{775,,Stable ABI}.'
マップ型オブジェクトがキー `key' を持つ場合に @code{1} を返し、そうでないときには @code{0} を返します。これは、Python の式 @code{key in o} と等価です。この関数呼び出しは常に成功します。

@cartouche
@quotation 注釈 
Exceptions which occur when this calls the @ref{588,,__getitem__()}
method are silently ignored.
For proper error handling, use @ref{61f,,PyMapping_HasKeyWithError()},
@ref{5e8,,PyMapping_GetOptionalItem()} or @ref{5ea,,PyObject_GetItem()} instead.
@end quotation
@end cartouche
@end deffn

@geindex PyMapping_HasKeyString (C function)
@anchor{c-api/mapping c PyMapping_HasKeyString}@anchor{622}
@deffn {C の関数} int PyMapping_HasKeyString (PyObject *o, const char *key)
` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{620,,PyMapping_HasKey()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.

@cartouche
@quotation 注釈 
Exceptions that occur when this calls the @ref{588,,__getitem__()}
method or while creating the temporary @ref{169,,str}
object are silently ignored.
For proper error handling, use @ref{621,,PyMapping_HasKeyStringWithError()},
@ref{5e9,,PyMapping_GetOptionalItemString()} or
@ref{5eb,,PyMapping_GetItemString()} instead.
@end quotation
@end cartouche
@end deffn

@geindex PyMapping_Keys (C function)
@anchor{c-api/mapping c PyMapping_Keys}@anchor{db5}
@deffn {C の関数} @ref{5df,,PyObject} *PyMapping_Keys (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功するとオブジェクト `o' のキーからなるリストを返します。
失敗すると @code{NULL} を返します。


バージョン 3.7 で変更: 以前は、関数はリストもしくはタプルを返していました。

@end deffn

@geindex PyMapping_Values (C function)
@anchor{c-api/mapping c PyMapping_Values}@anchor{db6}
@deffn {C の関数} @ref{5df,,PyObject} *PyMapping_Values (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功するとオブジェクト `o' の値からなるリストを返します。
失敗すると @code{NULL} を返します。


バージョン 3.7 で変更: 以前は、関数はリストもしくはタプルを返していました。

@end deffn

@geindex PyMapping_Items (C function)
@anchor{c-api/mapping c PyMapping_Items}@anchor{db7}
@deffn {C の関数} @ref{5df,,PyObject} *PyMapping_Items (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功するとオブジェクト `o' の要素からなるリストを返し、各要素はキーと値のペアが入ったタプルになっています。
失敗すると @code{NULL} を返します。


バージョン 3.7 で変更: 以前は、関数はリストもしくはタプルを返していました。

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node イテレータプロトコル iterator protocol,バッファプロトコル buffer Protocol,マップ型プロトコル mapping protocol,抽象オブジェクトレイヤ Abstract Objects Layer
@anchor{c-api/iter doc}@anchor{52b0}@anchor{c-api/iter iterator}@anchor{52b1}@anchor{c-api/iter iterator-protocol}@anchor{52b2}@anchor{c-api/iter translation-repo}@anchor{52b3}
@subsection イテレータプロトコル (iterator protocol)


イテレータを扱うための固有の関数は二つあります。

@geindex PyIter_Check (C function)
@anchor{c-api/iter c PyIter_Check}@anchor{1cb2}
@deffn {C の関数} int PyIter_Check (PyObject *o)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
Return non-zero if the object `o' can be safely passed to
@ref{398,,PyIter_NextItem()} and @code{0} otherwise.
This function always succeeds.
@end deffn

@geindex PyAIter_Check (C function)
@anchor{c-api/iter c PyAIter_Check}@anchor{4f63}
@deffn {C の関数} int PyAIter_Check (PyObject *o)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Return non-zero if the object `o' provides the @code{AsyncIterator}
protocol, and @code{0} otherwise.  This function always succeeds.


Added in version 3.10.

@end deffn

@geindex PyIter_NextItem (C function)
@anchor{c-api/iter c PyIter_NextItem}@anchor{398}
@deffn {C の関数} int PyIter_NextItem (PyObject *iter, PyObject **item)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Return @code{1} and set `item' to a @ref{5e2,,strong reference} of the
next value of the iterator `iter' on success.
Return @code{0} and set `item' to @code{NULL} if there are no remaining values.
Return @code{-1}, set `item' to @code{NULL} and set an exception on error.


Added in version 3.14.

@end deffn

@geindex PyIter_Next (C function)
@anchor{c-api/iter c PyIter_Next}@anchor{399}
@deffn {C の関数} @ref{5df,,PyObject} *PyIter_Next (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
This is an older version of @code{PyIter_NextItem()},
which is retained for backwards compatibility.
Prefer @ref{398,,PyIter_NextItem()}.

Return the next value from the iterator `o'.  The object must be an iterator
according to @ref{1cb2,,PyIter_Check()} (it is up to the caller to check this).
If there are no remaining values, returns @code{NULL} with no exception set.
If an error occurs while retrieving the item, returns @code{NULL} and passes
along the exception.
@end deffn

@geindex PySendResult (C type)
@anchor{c-api/iter c PySendResult}@anchor{52b4}
@deffn {C のデータ型} type PySendResult

The enum value used to represent different results of @ref{a98,,PyIter_Send()}.


Added in version 3.10.

@end deffn

@geindex PyIter_Send (C function)
@anchor{c-api/iter c PyIter_Send}@anchor{a98}
@deffn {C の関数} @ref{52b4,,PySendResult} PyIter_Send (PyObject *iter, PyObject *arg, PyObject **presult)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Sends the `arg' value into the iterator `iter'. Returns:


@itemize -

@item 
@code{PYGEN_RETURN} if iterator returns. Return value is returned via `presult'.

@item 
@code{PYGEN_NEXT} if iterator yields. Yielded value is returned via `presult'.

@item 
@code{PYGEN_ERROR} if iterator has raised and exception. `presult' is set to @code{NULL}.
@end itemize


Added in version 3.10.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@geindex buffer protocol
@geindex buffer interface;(see buffer protocol)
@geindex buffer object;(see buffer protocol)

@node バッファプロトコル buffer Protocol,,イテレータプロトコル iterator protocol,抽象オブジェクトレイヤ Abstract Objects Layer
@anchor{c-api/buffer doc}@anchor{52b5}@anchor{c-api/buffer buffer-protocol}@anchor{52b6}@anchor{c-api/buffer bufferobjects}@anchor{260}@anchor{c-api/buffer translation-repo}@anchor{52b7}
@subsection バッファプロトコル (buffer Protocol)


Pythonで利用可能ないくつかのオブジェクトは、下層にあるメモリ配列または `buffer' へのアクセスを提供します。このようなオブジェクトとして、組み込みの @ref{192,,bytes} や @ref{344,,bytearray} 、 @ref{4be,,array.array} のようないくつかの拡張型が挙げられます。サードバーティのライブラリは画像処理や数値解析のような特別な目的のために、それら自身の型を定義することができます。

それぞれの型はそれ自身のセマンティクスを持ちますが、おそらく大きなメモリバッファからなるという共通の特徴を共有します。いくつかの状況では仲介するコピーを行うことなく直接バッファにアクセスすることが望まれます。

Python provides such a facility at the C and Python level in the form of the
@ref{260,,buffer protocol}.  This protocol has two sides:

@geindex PyBufferProcs (C type)


@itemize -

@item 
on the producer side, a type can export a "buffer interface" which allows
objects of that type to expose information about their underlying buffer.
This interface is described in the section @ref{1248,,バッファオブジェクト構造体 (buffer object structure)}; for
Python see @ref{2411,,Emulating buffer types}.

@item 
on the consumer side, several means are available to obtain a pointer to
the raw underlying data of an object (for example a method parameter). For
Python see @ref{165,,memoryview}.
@end itemize

@ref{192,,bytes} や @ref{344,,bytearray} などのシンプルなオブジェクトは、内部のバッファーをバイト列の形式で公開します。
バイト列以外の形式も利用可能です。例えば、 @ref{4be,,array.array} が公開する要素はマルチバイト値になることがあります。

bufferインターフェースの利用者の一例は、ファイルオブジェクトの @ref{ed7,,write()} メソッドです: bufferインターフェースを通して一連のバイト列を提供できるどんなオブジェクトでもファイルに書き込むことができます。 @code{write()} は、その引数として渡されたオブジェクトの内部要素に対する読み出し専用アクセスのみを必要としますが、 @ref{1895,,readinto()} のような他のメソッドでは、その引数の内容に対する書き込みアクセスが必要です。bufferインターフェースにより、オブジェクトは読み書き両方、読み出し専用バッファへのアクセスを許可するかそれとも拒否するか選択することができます。

bufferインターフェースの利用者には、対象となるオブジェクトのバッファを得る二つの方法があります:


@itemize *

@item 
正しい引数で @ref{63a,,PyObject_GetBuffer()} を呼び出す;

@item 
@ref{3c1,,PyArg_ParseTuple()} (またはその同族のひとつ) を @code{y*} 、 @code{w*} または @code{s*} @ref{3d5,,format codes} のいずれかとともに呼び出す。
@end itemize

どちらのケースでも、bufferが必要なくなった時に @ref{63b,,PyBuffer_Release()} を呼び出さなければなりません。これを怠ると、リソースリークのような様々な問題につながる恐れがあります。


Added in version 3.12: The buffer protocol is now accessible in Python, see
@ref{2411,,Emulating buffer types} and @ref{165,,memoryview}.


@menu
* buffer 構造体:: 
* バッファリクエストのタイプ:: 
* 複雑な配列:: 
* バッファ関連の関数:: 

@end menu

@node buffer 構造体,バッファリクエストのタイプ,,バッファプロトコル buffer Protocol
@anchor{c-api/buffer buffer-structure}@anchor{52b8}@anchor{c-api/buffer id1}@anchor{52b9}
@subsubsection buffer 構造体


バッファ構造体（または単純に "buffers"）は別のオブジェクトのバイナリデータをPythonプログラマに提供するのに便利です。これはまた、ゼロコピースライシング機構としても使用できます。このメモリブロックを参照する機能を使うことで、どんなデータでもとても簡単にPythonプログラマに提供することができます。メモリは、C 拡張の大きな配列定数かもしれませんし、オペレーティングシステムライブラリに渡す前のメモリブロックかもしれませんし、構造化データをネイティブのインメモリ形式受け渡すのに使用されるかもしれません。

Pythonインタプリタによって提供される多くのデータ型とは異なり、バッファは @ref{5df,,PyObject} ポインタではなく、シンプルなC 構造体です。そのため、作成とコピーが非常に簡単に行えます。バッファの一般的なラッパーが必要なときは、 @ref{52ba,,memoryview} オブジェクトが作成されます。

エクスポートされるオブジェクトを書く方法の短い説明には、 @ref{1248,,Buffer Object Structures} を参照してください。バッファを取得するには、 @ref{63a,,PyObject_GetBuffer()} を参照してください。

@geindex Py_buffer (C type)
@anchor{c-api/buffer c Py_buffer}@anchor{95c}
@deffn {C のデータ型} type Py_buffer
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む) (バージョン 3.11 より).'
@geindex Py_buffer.buf (C member)
@anchor{c-api/buffer c Py_buffer buf}@anchor{52bb}
@deffn {C のメンバ変数} void *buf

バッファフィールドが表している論理構造の先頭を指すポインタ。
バッファを提供するオブジェクトの下層物理メモリブロック中のどの位置にもなりえます。
例えば @ref{52bc,,strides} が負だと、この値はメモリブロックの末尾かもしれません。

@ref{124e,,連続} 配列の場合この値はメモリブロックの先頭を指します。
@end deffn

@geindex Py_buffer.obj (C member)
@anchor{c-api/buffer c Py_buffer obj}@anchor{52bd}
@deffn {C のメンバ変数} @ref{5df,,PyObject} *obj

エクスポート対象オブジェクトへの新しい参照。この参照は消費者によって所有され、自動的に解放されます（つまり、参照カウントが減少します）し、設定されます @code{NULL} by @ref{63b,,PyBuffer_Release()}. このフィールドは、標準のC-API関数の戻り値に相当します。

@ref{965,,PyMemoryView_FromBuffer()} または @ref{964,,PyBuffer_FillInfo()} によってラップされた `一時的な' バッファである特別なケースでは、このフィールドは @code{NULL} です。一般的に、エクスポートオブジェクトはこの方式を使用してはなりません。
@end deffn

@geindex Py_buffer.len (C member)
@anchor{c-api/buffer c Py_buffer len}@anchor{52be}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} len

@code{product(shape) * itemsize}。contiguous配列では、下層のメモリブロックの長さになります。非contiguous 配列では、contiguous表現にコピーされた場合に論理構造がもつ長さです。

@code{((char *)buf)[0]} から @code{((char *)buf)[len-1]} の範囲へのアクセスは、連続性 (contiguity) を保証するリクエストによって取得されたバッファに対してのみ許されます。
多くの場合に、そのようなリクエストは @ref{4f71,,PyBUF_SIMPLE} または @ref{15cf,,PyBUF_WRITABLE} です。
@end deffn

@geindex Py_buffer.readonly (C member)
@anchor{c-api/buffer c Py_buffer readonly}@anchor{52bf}
@deffn {C のメンバ変数} int readonly

バッファが読み出し専用であるか示します。このフィールドは @ref{15cf,,PyBUF_WRITABLE} フラグで制御できます。
@end deffn

@geindex Py_buffer.itemsize (C member)
@anchor{c-api/buffer c Py_buffer itemsize}@anchor{52c0}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} itemsize

要素一つ分のbyte単位のサイズ。
@ref{1da9,,struct.calcsize()} を非 @code{NULL} の @ref{52c1,,format} 値に対して呼び出した結果と同じです。

重要な例外: 消費者が @ref{4f69,,PyBUF_FORMAT} フラグを設定することなくバッファを要求した場合、 @code{format} は @code{NULL} に設定されます。
しかし @ref{52c0,,itemsize} は元のフォーマットに従った値を保持します。

@ref{52c2,,shape} が存在する場合、 @code{product(shape) * itemsize == len} の等式が守られ、利用者は @ref{52c0,,itemsize} を buffer を読むために利用できます。

@ref{4f71,,PyBUF_SIMPLE} または @ref{15cf,,PyBUF_WRITABLE} で要求した結果、 @ref{52c2,,shape} が @code{NULL} であれば、消費者は @ref{52c0,,itemsize} を無視して @code{itemsize == 1} と見なさなければなりません。
@end deffn

@geindex Py_buffer.format (C member)
@anchor{c-api/buffer c Py_buffer format}@anchor{52c1}
@deffn {C のメンバ変数} char *format

A `NULL' terminated string in @ref{db,,struct} module style syntax describing
the contents of a single item. If this is @code{NULL}, @code{"B"} (unsigned bytes)
is assumed.

このフィールドは @ref{4f69,,PyBUF_FORMAT} フラグによって制御されます。
@end deffn

@geindex Py_buffer.ndim (C member)
@anchor{c-api/buffer c Py_buffer ndim}@anchor{52c3}
@deffn {C のメンバ変数} int ndim

The number of dimensions the memory represents as an n-dimensional array.
If it is @code{0}, @ref{52bb,,buf} points to a single item representing
a scalar. In this case, @ref{52c2,,shape}, @ref{52bc,,strides}
and @ref{52c4,,suboffsets} MUST be @code{NULL}.
The maximum number of dimensions is given by @ref{4f6d,,PyBUF_MAX_NDIM}.
@end deffn

@geindex Py_buffer.shape (C member)
@anchor{c-api/buffer c Py_buffer shape}@anchor{52c2}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} *shape

メモリ上のN次元配列の形を示す、長さが @ref{52c3,,ndim} である @ref{c55,,Py_ssize_t} の配列です。
@code{shape[0] * ... * shape[ndim-1] * itemsize} は @ref{52be,,len} と等しくなければなりません。

shape の値は @code{shape[n] >= 0} に制限されます。 @code{shape[n] == 0} の場合に特に注意が必要です。
詳細は @ref{52c5,,complex arrays} を参照してください。

shepe (形状) 配列は利用者からは読み出し専用です。
@end deffn

@geindex Py_buffer.strides (C member)
@anchor{c-api/buffer c Py_buffer strides}@anchor{52bc}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} *strides

各次元において新しい値を得るためにスキップするバイト数を示す、長さ @ref{52c3,,ndim} の @ref{c55,,Py_ssize_t} の配列。

ストライド値は、任意の整数を指定できます。規定の配列では、ストライドは通常でいけば有効です。しかし利用者は、@code{strides[n] <= 0} のケースを処理することができる必要があります。詳細については @ref{52c5,,complex arrays} を参照してください。

消費者にとって、この strides 配列は読み出し専用です。
@end deffn

@geindex Py_buffer.suboffsets (C member)
@anchor{c-api/buffer c Py_buffer suboffsets}@anchor{52c4}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} *suboffsets

@ref{c55,,Py_ssize_t} 型の要素を持つ長さ @ref{52c3,,ndim} の配列。
@code{suboffsets[n] >= 0} の場合は、 n 番目の次元に沿って保存されている値はポインタで、 suboffset 値は各ポインタの参照を解決した後に何バイト加えればいいかを示しています。
suboffset の値が負の数の場合は、ポインタの参照解決は不要 (連続したメモリブロック内に直接配置されいる) ということになります。

全ての suboffset が負数の場合 (つまり参照解決が不要) な場合、このフィールドは @code{NULL} (デフォルト値) でなければなりません。

この種の配列表現は Python Imaging Library (PIL) で使われています。
このような配列で要素にアクセスする方法についてさらに詳しことは @ref{52c5,,complex arrays} を参照してください。

消費者にとって、suboffsets 配列は読み出し専用です。
@end deffn

@geindex Py_buffer.internal (C member)
@anchor{c-api/buffer c Py_buffer internal}@anchor{52c6}
@deffn {C のメンバ変数} void *internal

バッファを提供する側のオブジェクトが内部的に利用するための変数です。例えば、提供側はこの変数に整数型をキャストして、shape, strides, suboffsets といった配列をバッファを開放するときに同時に解放するべきかどうかを管理するフラグに使うことができるでしょう。バッファを受け取る側は、この値を決して変更してはなりません。
@end deffn
@end deffn

Constants:

@geindex PyBUF_MAX_NDIM (C macro)
@anchor{c-api/buffer c PyBUF_MAX_NDIM}@anchor{4f6d}
@deffn {C のマクロ} PyBUF_MAX_NDIM
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
The maximum number of dimensions the memory represents.
Exporters MUST respect this limit, consumers of multi-dimensional
buffers SHOULD be able to handle up to @code{PyBUF_MAX_NDIM} dimensions.
Currently set to 64.
@end deffn

@node バッファリクエストのタイプ,複雑な配列,buffer 構造体,バッファプロトコル buffer Protocol
@anchor{c-api/buffer buffer-request-types}@anchor{1249}@anchor{c-api/buffer id2}@anchor{52c7}
@subsubsection バッファリクエストのタイプ


バッファは通常、 @ref{63a,,PyObject_GetBuffer()} を使うことで、エクスポートするオブジェクトにバッファリクエストを送ることで得られます。メモリの論理的な構造の複雑性は多岐にわたるため、消費者は `flags' 引数を使って、自身が扱えるバッファの種類を指定します。

@ref{95c,,Py_buffer} の全フィールドは、リクエストの種類によって曖昧さを残さずに定義されます。

@menu
* リクエストに依存しないフィールド:: 
* readonly@comma{} format: readonly format. 
* shape@comma{} strides@comma{} suboffsets: shape strides suboffsets. 
* 隣接性のリクエスト:: 
* 複合リクエスト:: 

@end menu

@node リクエストに依存しないフィールド,readonly format,,バッファリクエストのタイプ
@anchor{c-api/buffer request-independent-fields}@anchor{52c8}
@subsubsection リクエストに依存しないフィールド


下記のフィールドは `flags' の影響を受けずに、常に正しい値で設定されます。: @ref{52bd,,obj}, @ref{52bb,,buf}, @ref{52be,,len}, @ref{52c0,,itemsize}, @ref{52c3,,ndim}.

@node readonly format,shape strides suboffsets,リクエストに依存しないフィールド,バッファリクエストのタイプ
@anchor{c-api/buffer readonly-format}@anchor{52c9}
@subsubsection readonly, format


@quotation

@geindex PyBUF_WRITABLE (C macro)
@anchor{c-api/buffer c PyBUF_WRITABLE}@anchor{15cf}
@deffn {C のマクロ} PyBUF_WRITABLE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Controls the @ref{52bf,,readonly} field. If set, the exporter
MUST provide a writable buffer or else report failure. Otherwise, the
exporter MAY provide either a read-only or writable buffer, but the choice
MUST be consistent for all consumers. For example, @ref{4f71,,PyBUF_SIMPLE} | @ref{15cf,,PyBUF_WRITABLE}
can be used to request a simple writable buffer.
@end deffn

@geindex PyBUF_WRITEABLE (C macro)
@anchor{c-api/buffer c PyBUF_WRITEABLE}@anchor{52ca}
@deffn {C のマクロ} PyBUF_WRITEABLE

This is a @ref{23d,,soft deprecated} alias to @ref{15cf,,PyBUF_WRITABLE}.
@end deffn

@geindex PyBUF_FORMAT (C macro)
@anchor{c-api/buffer c PyBUF_FORMAT}@anchor{4f69}
@deffn {C のマクロ} PyBUF_FORMAT
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@ref{52c1,,format} フィールドを制御します。もしフラグが設定されていれば、このフィールドを正しく埋めなければなりません。フラグが設定されていなければ、このフィールドを @code{NULL} に設定しなければなりません。
@end deffn
@end quotation

@ref{15cf,,PyBUF_WRITABLE} は、次の節に出てくるどのフラグとも | を取ってかまいません。
@ref{4f71,,PyBUF_SIMPLE} は 0 と定義されているので、 @ref{15cf,,PyBUF_WRITABLE} は単純な書き込み可能なバッファを要求する単独のフラグとして使えます。

@ref{4f69,,PyBUF_FORMAT} must be |'d to any of the flags except @ref{4f71,,PyBUF_SIMPLE}, because
the latter already implies format @code{B} (unsigned bytes). @code{PyBUF_FORMAT} cannot be
used on its own.

@node shape strides suboffsets,隣接性のリクエスト,readonly format,バッファリクエストのタイプ
@anchor{c-api/buffer shape-strides-suboffsets}@anchor{52cb}
@subsubsection shape, strides, suboffsets


このフラグは、以下で複雑性が大きい順に並べたメモリの論理的な構造を制御します。個々のフラグは、それより下に記載されたフラグのすべてのビットを含むことに注意してください。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

リクエスト

@tab

shape

@tab

strides

@tab

suboffsets

@item

@geindex PyBUF_INDIRECT (C macro)
@anchor{c-api/buffer c PyBUF_INDIRECT}@anchor{4f6c}
@deffn {C のマクロ} PyBUF_INDIRECT
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

必要な場合

@item

@geindex PyBUF_STRIDES (C macro)
@anchor{c-api/buffer c PyBUF_STRIDES}@anchor{4f74}
@deffn {C のマクロ} PyBUF_STRIDES
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@item

@geindex PyBUF_ND (C macro)
@anchor{c-api/buffer c PyBUF_ND}@anchor{4f6e}
@deffn {C のマクロ} PyBUF_ND
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

NULL

@tab

NULL

@item

@geindex PyBUF_SIMPLE (C macro)
@anchor{c-api/buffer c PyBUF_SIMPLE}@anchor{4f71}
@deffn {C のマクロ} PyBUF_SIMPLE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

NULL

@tab

NULL

@tab

NULL

@end multitable


@geindex contiguous
@geindex C-contiguous
@geindex Fortran contiguous

@node 隣接性のリクエスト,複合リクエスト,shape strides suboffsets,バッファリクエストのタイプ
@anchor{c-api/buffer contiguity-requests}@anchor{52cc}
@subsubsection 隣接性のリクエスト


ストライドの情報があってもなくても、C または Fortran の @ref{124e,,連続性} が明確に要求される可能性があります。
ストライド情報なしに、バッファーは C と隣接している必要があります。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxx} 
@headitem

リクエスト

@tab

shape

@tab

strides

@tab

suboffsets

@tab

contig

@item

@geindex PyBUF_C_CONTIGUOUS (C macro)
@anchor{c-api/buffer c PyBUF_C_CONTIGUOUS}@anchor{15d0}
@deffn {C のマクロ} PyBUF_C_CONTIGUOUS
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@tab

C

@item

@geindex PyBUF_F_CONTIGUOUS (C macro)
@anchor{c-api/buffer c PyBUF_F_CONTIGUOUS}@anchor{15d1}
@deffn {C のマクロ} PyBUF_F_CONTIGUOUS
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@tab

F

@item

@geindex PyBUF_ANY_CONTIGUOUS (C macro)
@anchor{c-api/buffer c PyBUF_ANY_CONTIGUOUS}@anchor{4f66}
@deffn {C のマクロ} PyBUF_ANY_CONTIGUOUS
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@tab

C か F

@item

@ref{4f6e,,PyBUF_ND}

@tab

yes

@tab

NULL

@tab

NULL

@tab

C

@end multitable


@node 複合リクエスト,,隣接性のリクエスト,バッファリクエストのタイプ
@anchor{c-api/buffer compound-requests}@anchor{52cd}
@subsubsection 複合リクエスト


有り得る全てのリクエストの値は、前の節でのフラグの組み合わせで網羅的に定義されています。
便利なように、バッファープロトコルでは頻繁に使用される組み合わせを単一のフラグとして提供してます。

次のテーブルの `U' は連続性が未定義であることを表します。
利用者は @ref{962,,PyBuffer_IsContiguous()} を呼び出して連続性を判定する必要があるでしょう。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxx} 
@headitem

リクエスト

@tab

shape

@tab

strides

@tab

suboffsets

@tab

contig

@tab

readonly

@tab

format

@item

@geindex PyBUF_FULL (C macro)
@anchor{c-api/buffer c PyBUF_FULL}@anchor{4f6a}
@deffn {C のマクロ} PyBUF_FULL
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

必要な場合

@tab

U

@tab

0

@tab

yes

@item

@geindex PyBUF_FULL_RO (C macro)
@anchor{c-api/buffer c PyBUF_FULL_RO}@anchor{4f6b}
@deffn {C のマクロ} PyBUF_FULL_RO
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

必要な場合

@tab

U

@tab

1 か 0

@tab

yes

@item

@geindex PyBUF_RECORDS (C macro)
@anchor{c-api/buffer c PyBUF_RECORDS}@anchor{4f6f}
@deffn {C のマクロ} PyBUF_RECORDS
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@tab

U

@tab

0

@tab

yes

@item

@geindex PyBUF_RECORDS_RO (C macro)
@anchor{c-api/buffer c PyBUF_RECORDS_RO}@anchor{4f70}
@deffn {C のマクロ} PyBUF_RECORDS_RO
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@tab

U

@tab

1 か 0

@tab

yes

@item

@geindex PyBUF_STRIDED (C macro)
@anchor{c-api/buffer c PyBUF_STRIDED}@anchor{4f72}
@deffn {C のマクロ} PyBUF_STRIDED
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@tab

U

@tab

0

@tab

NULL

@item

@geindex PyBUF_STRIDED_RO (C macro)
@anchor{c-api/buffer c PyBUF_STRIDED_RO}@anchor{4f73}
@deffn {C のマクロ} PyBUF_STRIDED_RO
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

yes

@tab

NULL

@tab

U

@tab

1 か 0

@tab

NULL

@item

@geindex PyBUF_CONTIG (C macro)
@anchor{c-api/buffer c PyBUF_CONTIG}@anchor{4f67}
@deffn {C のマクロ} PyBUF_CONTIG
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

NULL

@tab

NULL

@tab

C

@tab

0

@tab

NULL

@item

@geindex PyBUF_CONTIG_RO (C macro)
@anchor{c-api/buffer c PyBUF_CONTIG_RO}@anchor{4f68}
@deffn {C のマクロ} PyBUF_CONTIG_RO
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
@end deffn

@tab

yes

@tab

NULL

@tab

NULL

@tab

C

@tab

1 か 0

@tab

NULL

@end multitable


@node 複雑な配列,バッファ関連の関数,バッファリクエストのタイプ,バッファプロトコル buffer Protocol
@anchor{c-api/buffer complex-arrays}@anchor{52c5}
@subsubsection 複雑な配列


@menu
* NumPy スタイル; shape@comma{} strides: NumPy スタイル shape strides. 
* PIL スタイル; shape@comma{} strides@comma{} suboffsets: PIL スタイル shape strides suboffsets. 

@end menu

@node NumPy スタイル shape strides,PIL スタイル shape strides suboffsets,,複雑な配列
@anchor{c-api/buffer numpy-style-shape-and-strides}@anchor{52ce}
@subsubsection NumPy スタイル: shape, strides


NumPy スタイルの配列の論理的構造は @ref{52c0,,itemsize}, @ref{52c3,,ndim}, @ref{52c2,,shape}, @ref{52bc,,strides} で定義されます。

@code{ndim == 0} の場合は、 @ref{52bb,,buf} が指すメモリの場所は、サイズが @ref{52c0,,itemsize} のスカラ値として解釈されます。
この場合、 @ref{52c2,,shape} と @ref{52bc,,strides} の両方とも @code{NULL} です。

@ref{52bc,,strides} が @code{NULL} の場合は、配列は標準の n 次元 C 配列として解釈されます。
そうでない場合は、利用者は次のように n 次元配列にアクセスしなければなりません:

@example
ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
item = *((typeof(item) *)ptr);
@end example

上記のように、 @ref{52bb,,buf} はメモリブロック内のどの場所でも指すことが可能です。エクスポーターはこの関数を使用することによってバッファの妥当性を確認出来ます。

@example
def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
    """Verify that the parameters represent a valid array within
       the bounds of the allocated memory:
           char *mem: start of the physical memory block
           memlen: length of the physical memory block
           offset: (char *)buf - mem
    """
    if offset % itemsize:
        return False
    if offset < 0 or offset+itemsize > memlen:
        return False
    if any(v % itemsize for v in strides):
        return False

    if ndim <= 0:
        return ndim == 0 and not shape and not strides
    if 0 in shape:
        return True

    imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
               if strides[j] <= 0)
    imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
               if strides[j] > 0)

    return 0 <= offset+imin and offset+imax+itemsize <= memlen
@end example

@node PIL スタイル shape strides suboffsets,,NumPy スタイル shape strides,複雑な配列
@anchor{c-api/buffer pil-style-shape-strides-and-suboffsets}@anchor{52cf}
@subsubsection PIL スタイル: shape, strides, suboffsets


PIL スタイルの配列では通常の要素の他に、ある次元の上で次の要素を取得するために辿るポインタを持てます。
例えば、通常の3次元 C 配列 @code{char v[2][2][3]} は、2次元配列への 2 つのポインタからなる配列 @code{char (*v[2])[2][3]} と見ることもできます。
suboffset 表現では、これらの 2 つのポインタは @ref{52bb,,buf} の先頭に埋め込め、メモリのどこにでも配置できる 2 つの @code{char x[2][3]} 配列を指します。

次の例は、 strides も suboffsets も @code{NULL} でない場合の、N 次元インデックスによって指されている N 次元配列内の要素へのポインタを返す関数です:

@example
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
                       Py_ssize_t *suboffsets, Py_ssize_t *indices) @{
    char *pointer = (char*)buf;
    int i;
    for (i = 0; i < ndim; i++) @{
        pointer += strides[i] * indices[i];
        if (suboffsets[i] >=0 ) @{
            pointer = *((char**)pointer) + suboffsets[i];
        @}
    @}
    return (void*)pointer;
@}
@end example

@node バッファ関連の関数,,複雑な配列,バッファプロトコル buffer Protocol
@anchor{c-api/buffer buffer-related-functions}@anchor{52d0}
@subsubsection バッファ関連の関数


@geindex PyObject_CheckBuffer (C function)
@anchor{c-api/buffer c PyObject_CheckBuffer}@anchor{639}
@deffn {C の関数} int PyObject_CheckBuffer (PyObject *obj)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
`obj' がbuffer インターフェースをサポートしている場合は @code{1} を返し、そうでない場合は @code{0} を返します。
@code{1} を返したとしても、 @ref{63a,,PyObject_GetBuffer()} が成功することは保証されません。
この関数は常に成功します。
@end deffn

@geindex PyObject_GetBuffer (C function)
@anchor{c-api/buffer c PyObject_GetBuffer}@anchor{63a}
@deffn {C の関数} int PyObject_GetBuffer (PyObject *exporter, Py_buffer *view, int flags)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
`exporter' に `flags' で指定された方法で `view' を埋めるように要求します。もし exporter が指定されたとおりにバッファを提供できない場合、 @ref{1797,,BufferError} を送出し、 @code{view->obj} を @code{NULL} に設定した上で、 @code{-1} を返さなければなりません。

成功したときは、 `view' を埋め、 @code{view->obj} に `exporter' への新しい参照を設定し、0を返します。チェイン状のバッファプロバイダがリクエストを単一のオブジェクトにリダイレクトするケースでは、 @code{view->obj} は `exporter' の代わりにこのオブジェクトを参照します (@ref{1248,,バッファオブジェクト構造体} を参照してください)。

@code{malloc()} と @code{free()} のように、呼び出しに成功した @ref{63a,,PyObject_GetBuffer()} と対になる @ref{63b,,PyBuffer_Release()} の呼び出しがなけれなればなりません。
従って、バッファの利用が済んだら @ref{63b,,PyBuffer_Release()} が厳密に1回だけ呼び出されなければなりません。
@end deffn

@geindex PyBuffer_Release (C function)
@anchor{c-api/buffer c PyBuffer_Release}@anchor{63b}
@deffn {C の関数} void PyBuffer_Release (Py_buffer *view)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Release the buffer `view' and release the @ref{5e2,,strong reference}
(i.e. decrement the reference count) to the view's supporting object,
@code{view->obj}. This function MUST be called when the buffer
is no longer being used, otherwise reference leaks may occur.

@ref{63a,,PyObject_GetBuffer()} を通して取得していないバッファに対してこの関数を呼び出すのは間違いです。
@end deffn

@geindex PyBuffer_SizeFromFormat (C function)
@anchor{c-api/buffer c PyBuffer_SizeFromFormat}@anchor{95e}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyBuffer_SizeFromFormat (const char *format)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Return the implied @ref{52c0,,itemsize} from @ref{52c1,,format}.
On error, raise an exception and return -1.


Added in version 3.9.

@end deffn

@geindex PyBuffer_IsContiguous (C function)
@anchor{c-api/buffer c PyBuffer_IsContiguous}@anchor{962}
@deffn {C の関数} int PyBuffer_IsContiguous (const Py_buffer *view, char order)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
`view' で定義されているメモリが、 C スタイル (`order' == @code{'C'}) のときか、 Fortran スタイル (`order' == @code{'F'}) @ref{124e,,連続} のときか、そのいずれか (`order' == @code{'A'}) であれば @code{1} を返します。
それ以外の場合は @code{0} を返します。
この関数は常に成功します。
@end deffn

@geindex PyBuffer_GetPointer (C function)
@anchor{c-api/buffer c PyBuffer_GetPointer}@anchor{95d}
@deffn {C の関数} void *PyBuffer_GetPointer (const Py_buffer *view, const Py_ssize_t *indices)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
与えられた `view' 内にある `indices' が指すメモリ領域を取得します。
`indices' は @code{view->ndim} 個のインデックスからなる配列を指していなければなりません。
@end deffn

@geindex PyBuffer_FromContiguous (C function)
@anchor{c-api/buffer c PyBuffer_FromContiguous}@anchor{960}
@deffn {C の関数} int PyBuffer_FromContiguous (const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
連続する `len' バイトを `buf' から `view' にコピーします。`fort' には @code{'C'} か @code{'F'} を指定できます（それぞれC言語スタイルとFortranスタイルの順序を表します)。成功時には @code{0}、エラー時には @code{-1} を返します。
@end deffn

@geindex PyBuffer_ToContiguous (C function)
@anchor{c-api/buffer c PyBuffer_ToContiguous}@anchor{95f}
@deffn {C の関数} int PyBuffer_ToContiguous (void *buf, const Py_buffer *src, Py_ssize_t len, char order)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
`src' から `len' バイトを連続表現で `buf' 上にコピーします。
`order' は @code{'C'} または @code{'F'} または @code{'A'} (C スタイル順序または Fortran スタイル順序またはそれ以外) が指定できます。
成功したら @code{0} が返り、エラーなら @code{-1} が返ります。

`len' != `src->len' の場合、この関数は失敗します。
@end deffn

@geindex PyObject_CopyData (C function)
@anchor{c-api/buffer c PyObject_CopyData}@anchor{961}
@deffn {C の関数} int PyObject_CopyData (PyObject *dest, PyObject *src)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Copy data from `src' to `dest' buffer. Can convert between C-style and
or Fortran-style buffers.

成功したら @code{0} が、エラー時には @code{-1} が返されます。
@end deffn

@geindex PyBuffer_FillContiguousStrides (C function)
@anchor{c-api/buffer c PyBuffer_FillContiguousStrides}@anchor{963}
@deffn {C の関数} void PyBuffer_FillContiguousStrides (int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char order)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
`strides' 配列を、 `itemsize' の大きさの要素がバイト単位の、 `shape' の形をした @ref{124e,,連続な} (`order' が @code{'C'} なら C-style 、 @code{'F'} なら Fortran-style の) 多次元配列として埋める。
@end deffn

@geindex PyBuffer_FillInfo (C function)
@anchor{c-api/buffer c PyBuffer_FillInfo}@anchor{964}
@deffn {C の関数} int PyBuffer_FillInfo (Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int flags)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
サイズが `len' の `buf' を `readonly' に従った書き込み可/不可の設定で公開するバッファリクエストを処理します。
`buf' は符号無しバイトの列として解釈されます。

`flags' 引数はリクエストのタイプを示します。
この関数は、 `buf' が読み出し専用と指定されていて、 `flags' に @ref{15cf,,PyBUF_WRITABLE} が設定されていない限り、常にフラグに指定された通りに `view' を埋めます。

On success, set @code{view->obj} to a new reference to `exporter' and
return 0. Otherwise, raise @ref{1797,,BufferError}, set
@code{view->obj} to @code{NULL} and return @code{-1};

この関数を @ref{1248,,getbufferproc} の一部として使う場合には、 `exporter' はエクスポートするオブジェクトに設定しなければならず、さらに `flags' は変更せずに渡さなければなりません。
そうでない場合は、 `exporter' は @code{NULL} でなければなりません。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 具象オブジェクト concrete object レイヤ,初期化 initialization 、終了処理 finalization 、スレッド,抽象オブジェクトレイヤ Abstract Objects Layer,Python/C API リファレンスマニュアル
@anchor{c-api/concrete doc}@anchor{52d1}@anchor{c-api/concrete concrete}@anchor{52d2}@anchor{c-api/concrete concrete-objects-layer}@anchor{52d3}@anchor{c-api/concrete translation-repo}@anchor{52d4}
@section 具象オブジェクト (concrete object) レイヤ


この章では、特定の Python オブジェクト型固有の関数について述べています。これらの関数に間違った型のオブジェクトを渡すのは良い考えではありません; Python プログラムから何らかのオブジェクトを受け取ったとき、そのオブジェクトが正しい型になっているか確信をもてないのなら、まず型チェックを行わなければなりません; 例えば、あるオブジェクトが辞書型か調べるには、 @ref{52d5,,PyDict_Check()} を使います。この章は Python のオブジェクト型における "家計図" に従って構成されています。

@cartouche
@quotation 警告 
この章で述べている関数は、渡されたオブジェクトの型を注意深くチェックしはするものの、多くの関数は渡されたオブジェクトが有効な @code{NULL} なのか有効なオブジェクトなのかをチェックしません。これらの関数に @code{NULL} を渡させてしまうと、関数はメモリアクセス違反を起こして、インタプリタを即座に終了させてしまうはずです。
@end quotation
@end cartouche

@menu
* 基本オブジェクト (fundamental object): 基本オブジェクト fundamental object. 
* 数値型オブジェクト (numeric object): 数値型オブジェクト numeric object. 
* シーケンスオブジェクト (sequence object): シーケンスオブジェクト sequence object. 
* Container オブジェクト:: 
* Function オブジェクト: Function オブジェクト<2>. 
* その他のオブジェクト: その他のオブジェクト<2>. 
* C API for extension modules:: 

@end menu

@node 基本オブジェクト fundamental object,数値型オブジェクト numeric object,,具象オブジェクト concrete object レイヤ
@anchor{c-api/concrete fundamental}@anchor{52d6}@anchor{c-api/concrete fundamental-objects}@anchor{52d7}
@subsection 基本オブジェクト (fundamental object)


この節では、Python の型オブジェクトとシングルトン(singleton)オブジェクト @code{None} について述べます。

@menu
* 型オブジェクト: 型オブジェクト<2>. 
* None オブジェクト:: 

@end menu

@node 型オブジェクト<2>,None オブジェクト,,基本オブジェクト fundamental object
@anchor{c-api/type doc}@anchor{52d8}@anchor{c-api/type type-objects}@anchor{52d9}@anchor{c-api/type typeobjects}@anchor{52da}
@subsubsection 型オブジェクト


@geindex object;type

@geindex PyTypeObject (C type)
@anchor{c-api/type c PyTypeObject}@anchor{c9c}
@deffn {C のデータ型} type PyTypeObject
` 次に属します: @ref{775,,Limited API} (不透明な構造体として).'
組み込み型を記述する際に用いられる、オブジェクトを表す C 構造体です。
@end deffn

@geindex PyType_Type (C var)
@anchor{c-api/type c PyType_Type}@anchor{76f}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyType_Type
` 次に属します: @ref{775,,Stable ABI}.'
型オブジェクト自身の型オブジェクトです。Python レイヤにおける @ref{f44,,type} と同じオブジェクトです。
@end deffn

@geindex PyType_Check (C function)
@anchor{c-api/type c PyType_Check}@anchor{1d87}
@deffn {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.
@end deffn

@geindex PyType_CheckExact (C function)
@anchor{c-api/type c PyType_CheckExact}@anchor{1d88}
@deffn {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.
@end deffn

@geindex PyType_ClearCache (C function)
@anchor{c-api/type c PyType_ClearCache}@anchor{50da}
@deffn {C の関数} unsigned int PyType_ClearCache ()
` 次に属します: @ref{775,,Stable ABI}.'
内部の検索キャッシュをクリアします。現在のバージョンタグを返します。
@end deffn

@geindex PyType_GetFlags (C function)
@anchor{c-api/type c PyType_GetFlags}@anchor{1d3d}
@deffn {C の関数} unsigned long PyType_GetFlags (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI}.'
Return the @ref{1c71,,tp_flags} member of `type'. This function is primarily
meant for use with @code{Py_LIMITED_API}; the individual flag bits are
guaranteed to be stable across Python releases, but access to
@ref{1c71,,tp_flags} itself is not part of the @ref{637,,limited API}.


Added in version 3.2.



バージョン 3.4 で変更: 返り値の型が @code{long} ではなく @code{unsigned long} になりました。

@end deffn

@geindex PyType_GetDict (C function)
@anchor{c-api/type c PyType_GetDict}@anchor{1a8b}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GetDict (PyTypeObject *type)

Return the type object's internal namespace, which is otherwise only
exposed via a read-only proxy (@ref{e57,,cls.__dict__}).
This is a
replacement for accessing @ref{1a8c,,tp_dict} directly.
The returned dictionary must be treated as read-only.

This function is meant for specific embedding and language-binding cases,
where direct access to the dict is necessary and indirect access
(e.g. via the proxy or @ref{5ee,,PyObject_GetAttr()}) isn't adequate.

Extension modules should continue to use @code{tp_dict},
directly or indirectly, when setting up their own types.


Added in version 3.12.

@end deffn

@geindex PyType_Modified (C function)
@anchor{c-api/type c PyType_Modified}@anchor{1b7b}
@deffn {C の関数} void PyType_Modified (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI}.'
内部の検索キャッシュを、その type とすべてのサブタイプに対して無効にします。この関数は type の属性や基底クラス列を変更したあとに手動で呼び出さなければなりません。
@end deffn

@geindex PyType_AddWatcher (C function)
@anchor{c-api/type c PyType_AddWatcher}@anchor{785}
@deffn {C の関数} int PyType_AddWatcher (PyType_WatchCallback callback)

Register `callback' as a type watcher. Return a non-negative integer ID
which must be passed to future calls to @ref{786,,PyType_Watch()}. In case of
error (e.g. no more watcher IDs available), return @code{-1} and set an
exception.

In free-threaded builds, @ref{785,,PyType_AddWatcher()} is not thread-safe,
so it must be called at start up (before spawning the first thread).


Added in version 3.12.

@end deffn

@geindex PyType_ClearWatcher (C function)
@anchor{c-api/type c PyType_ClearWatcher}@anchor{52db}
@deffn {C の関数} int PyType_ClearWatcher (int watcher_id)

Clear watcher identified by `watcher_id' (previously returned from
@ref{785,,PyType_AddWatcher()}). Return @code{0} on success, @code{-1} on error (e.g.
if `watcher_id' was never registered.)

An extension should never call @code{PyType_ClearWatcher} with a `watcher_id'
that was not returned to it by a previous call to
@ref{785,,PyType_AddWatcher()}.


Added in version 3.12.

@end deffn

@geindex PyType_Watch (C function)
@anchor{c-api/type c PyType_Watch}@anchor{786}
@deffn {C の関数} int PyType_Watch (int watcher_id, PyObject *type)

Mark `type' as watched. The callback granted `watcher_id' by
@ref{785,,PyType_AddWatcher()} will be called whenever
@ref{1b7b,,PyType_Modified()} reports a change to `type'. (The callback may be
called only once for a series of consecutive modifications to `type', if
@code{_PyType_Lookup()} is not called on `type' between the modifications;
this is an implementation detail and subject to change.)

An extension should never call @code{PyType_Watch} with a `watcher_id' that was
not returned to it by a previous call to @ref{785,,PyType_AddWatcher()}.


Added in version 3.12.

@end deffn

@geindex PyType_Unwatch (C function)
@anchor{c-api/type c PyType_Unwatch}@anchor{52dc}
@deffn {C の関数} int PyType_Unwatch (int watcher_id, PyObject *type)

Mark `type' as not watched. This undoes a previous call to
@ref{786,,PyType_Watch()}. `type' must not be @code{NULL}.

An extension should never call this function with a `watcher_id' that was
not returned to it by a previous call to @ref{785,,PyType_AddWatcher()}.

On success, this function returns @code{0}. On failure, this function returns
@code{-1} with an exception set.


Added in version 3.12.

@end deffn

@geindex PyType_WatchCallback (C type)
@anchor{c-api/type c PyType_WatchCallback}@anchor{52dd}
@deffn {C のデータ型} typedef int (*PyType_WatchCallback)(@ref{5df,,PyObject} *type)

Type of a type-watcher callback function.

The callback must not modify `type' or cause @ref{1b7b,,PyType_Modified()} to be
called on `type' or any type in its MRO; violating this rule could cause
infinite recursion.


Added in version 3.12.

@end deffn

@geindex PyType_HasFeature (C function)
@anchor{c-api/type c PyType_HasFeature}@anchor{1d3c}
@deffn {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.
@end deffn

@geindex PyType_FastSubclass (C function)
@anchor{c-api/type c PyType_FastSubclass}@anchor{52de}
@deffn {C の関数} int PyType_FastSubclass (PyTypeObject *type, int flag)

Return non-zero if the type object `type' sets the subclass flag `flag'.
Subclass flags are denoted by
@ref{52df,,Py_TPFLAGS_*_SUBCLASS}.
This function is used by many @code{_Check} functions for common types.


@subsubheading 参考


@ref{1cb5,,PyObject_TypeCheck()}, which is used as a slower alternative in
@code{_Check} functions for types that don't come with subclass flags.

@end deffn

@geindex PyType_IS_GC (C function)
@anchor{c-api/type c PyType_IS_GC}@anchor{52e0}
@deffn {C の関数} int PyType_IS_GC (PyTypeObject *o)

Return true if the type object includes support for the cycle detector; this
tests the type flag @ref{981,,Py_TPFLAGS_HAVE_GC}.
@end deffn

@geindex PyType_IsSubtype (C function)
@anchor{c-api/type c PyType_IsSubtype}@anchor{50db}
@deffn {C の関数} int PyType_IsSubtype (PyTypeObject *a, PyTypeObject *b)
` 次に属します: @ref{775,,Stable ABI}.'
`a' が `b' のサブタイプの場合に真を返します。

This function only checks for actual subtypes, which means that
@ref{23c7,,__subclasscheck__()} is not called on `b'.  Call
@ref{10a7,,PyObject_IsSubclass()} to do the same check that @ref{9c4,,issubclass()}
would do.
@end deffn

@geindex PyType_GenericAlloc (C function)
@anchor{c-api/type c PyType_GenericAlloc}@anchor{c61}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GenericAlloc (PyTypeObject *type, Py_ssize_t nitems)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Generic handler for the @ref{4ed0,,tp_alloc} slot of a type
object.  Uses Python's default memory allocation mechanism to allocate memory
for a new instance, zeros the memory, then initializes the memory as if by
calling @ref{c60,,PyObject_Init()} or @ref{1d40,,PyObject_InitVar()}.

Do not call this directly to allocate memory for an object; call the type's
@ref{4ed0,,tp_alloc} slot instead.

For types that support garbage collection (i.e., the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag is set), this function behaves like
@ref{c99,,PyObject_GC_New} or @ref{c9a,,PyObject_GC_NewVar} (except the
memory is guaranteed to be zeroed before initialization), and should be
paired with @ref{171c,,PyObject_GC_Del()} in @ref{4ecf,,tp_free}.
Otherwise, it behaves like @ref{b7c,,PyObject_New} or
@ref{b7d,,PyObject_NewVar} (except the memory is guaranteed to be zeroed
before initialization) and should be paired with @ref{e60,,PyObject_Free()} in
@ref{4ecf,,tp_free}.
@end deffn

@geindex PyType_GenericNew (C function)
@anchor{c-api/type c PyType_GenericNew}@anchor{4ecc}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GenericNew (PyTypeObject *type, PyObject *args, PyObject *kwds)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Generic handler for the @ref{79f,,tp_new} slot of a type
object.  Creates a new instance using the type's
@ref{4ed0,,tp_alloc} slot and returns the resulting object.
@end deffn

@geindex PyType_Ready (C function)
@anchor{c-api/type c PyType_Ready}@anchor{980}
@deffn {C の関数} int PyType_Ready (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI}.'
型オブジェクトのファイナライズを行います。この関数は全てのオブジェクトで初期化を完了するために呼び出されなくてはなりません。この関数は、基底クラス型から継承したスロットを型オブジェクトに追加する役割があります。成功した場合には @code{0} を返し、エラーの場合には @code{-1} を返して例外情報を設定します。

@cartouche
@quotation 注釈 
If some of the base classes implements the GC protocol and the provided
type does not include the @ref{981,,Py_TPFLAGS_HAVE_GC} in its flags, then
the GC protocol will be automatically implemented from its parents. On
the contrary, if the type being created does include
@ref{981,,Py_TPFLAGS_HAVE_GC} in its flags then it `must' implement the
GC protocol itself by at least implementing the
@ref{982,,tp_traverse} handle.
@end quotation
@end cartouche
@end deffn

@geindex PyType_GetName (C function)
@anchor{c-api/type c PyType_GetName}@anchor{958}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GetName (PyTypeObject *type)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Return the type's name. Equivalent to getting the type's
@ref{16c4,,__name__} attribute.


Added in version 3.11.

@end deffn

@geindex PyType_GetQualName (C function)
@anchor{c-api/type c PyType_GetQualName}@anchor{959}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GetQualName (PyTypeObject *type)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Return the type's qualified name. Equivalent to getting the
type's @ref{2373,,__qualname__} attribute.


Added in version 3.11.

@end deffn

@geindex PyType_GetFullyQualifiedName (C function)
@anchor{c-api/type c PyType_GetFullyQualifiedName}@anchor{616}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GetFullyQualifiedName (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return the type's fully qualified name. Equivalent to
@code{f"@{type.__module__@}.@{type.__qualname__@}"}, or @ref{2373,,type.__qualname__}
if @ref{617,,type.__module__} is not a string or is equal to @code{"builtins"}.


Added in version 3.13.

@end deffn

@geindex PyType_GetModuleName (C function)
@anchor{c-api/type c PyType_GetModuleName}@anchor{618}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GetModuleName (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return the type's module name. Equivalent to getting the
@ref{617,,type.__module__} attribute.


Added in version 3.13.

@end deffn

@geindex PyType_GetSlot (C function)
@anchor{c-api/type c PyType_GetSlot}@anchor{a9c}
@deffn {C の関数} void *PyType_GetSlot (PyTypeObject *type, int slot)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.4 より).'
与えられたスロットに格納されている関数ポインタを返します。返り値が @code{NULL} の場合は、スロットが @code{NULL} か、関数が不正な引数で呼ばれたことを示します。通常、呼び出し側は返り値のポインタを適切な関数型にキャストします。

See @ref{52e1,,PyType_Slot.slot} for possible values of the `slot' argument.


Added in version 3.4.



バージョン 3.10 で変更: @ref{a9c,,PyType_GetSlot()} can now accept all types.
Previously, it was limited to @ref{b5e,,heap types}.

@end deffn

@geindex PyType_GetModule (C function)
@anchor{c-api/type c PyType_GetModule}@anchor{b66}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GetModule (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Return the module object associated with the given type when the type was
created using @ref{773,,PyType_FromModuleAndSpec()}.

If no module is associated with the given type, sets @ref{198,,TypeError}
and returns @code{NULL}.

This function is usually used to get the module in which a method is defined.
Note that in such a method, @code{PyType_GetModule(Py_TYPE(self))}
may not return the intended result.
@code{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 @ref{968,,PyCMethod} to get the class that defines the method.
See @ref{635,,PyType_GetModuleByDef()} for cases when @code{PyCMethod} cannot
be used.


Added in version 3.9.

@end deffn

@geindex PyType_GetModuleState (C function)
@anchor{c-api/type c PyType_GetModuleState}@anchor{b67}
@deffn {C の関数} void *PyType_GetModuleState (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Return the state of the module object associated with the given type.
This is a shortcut for calling @ref{b77,,PyModule_GetState()} on the result
of @ref{b66,,PyType_GetModule()}.

If no module is associated with the given type, sets @ref{198,,TypeError}
and returns @code{NULL}.

If the `type' has an associated module but its state is @code{NULL},
returns @code{NULL} without setting an exception.


Added in version 3.9.

@end deffn

@geindex PyType_GetModuleByDef (C function)
@anchor{c-api/type c PyType_GetModuleByDef}@anchor{635}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_GetModuleByDef (PyTypeObject *type, struct PyModuleDef *def)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Find the first superclass whose module was created from
the given @ref{b74,,PyModuleDef} `def', and return that module.

If no module is found, raises a @ref{198,,TypeError} and returns @code{NULL}.

This function is intended to be used together with
@ref{b77,,PyModule_GetState()} to get module state from slot methods (such as
@ref{7a1,,tp_init} or @ref{52e2,,nb_add})
and other places where a method's defining class cannot be passed using the
@ref{968,,PyCMethod} calling convention.

The returned reference is @ref{3d7,,borrowed} from `type',
and will be valid as long as you hold a reference to `type'.
Do not release it with @ref{790,,Py_DECREF()} or similar.


Added in version 3.11.

@end deffn

@geindex PyType_GetBaseByToken (C function)
@anchor{c-api/type c PyType_GetBaseByToken}@anchor{3b0}
@deffn {C の関数} int PyType_GetBaseByToken (PyTypeObject *type, void *token, PyTypeObject **result)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Find the first superclass in `type''s @ref{25df,,method resolution order} whose
@ref{3b1,,Py_tp_token} token is equal to the given one.


@itemize *

@item 
If found, set `*result' to a new @ref{5e2,,strong reference}
to it and return @code{1}.

@item 
If not found, set `*result' to @code{NULL} and return @code{0}.

@item 
On error, set `*result' to @code{NULL} and return @code{-1} with an
exception set.
@end itemize

The `result' argument may be @code{NULL}, in which case `*result' is not set.
Use this if you need only the return value.

The `token' argument may not be @code{NULL}.


Added in version 3.14.

@end deffn

@geindex PyUnstable_Type_AssignVersionTag (C function)
@anchor{c-api/type c PyUnstable_Type_AssignVersionTag}@anchor{52e3}
@deffn {C の関数} int PyUnstable_Type_AssignVersionTag (PyTypeObject *type)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Attempt to assign a version tag to the given type.

Returns 1 if the type already had a valid version tag or a new one was
assigned, or 0 if a new tag could not be assigned.


Added in version 3.12.

@end deffn

@geindex PyType_SUPPORTS_WEAKREFS (C function)
@anchor{c-api/type c PyType_SUPPORTS_WEAKREFS}@anchor{52e4}
@deffn {C の関数} int PyType_SUPPORTS_WEAKREFS (PyTypeObject *type)

Return true if instances of `type' support creating weak references, false
otherwise. This function always succeeds. `type' must not be @code{NULL}.


@subsubheading 参考



@itemize *

@item 
@ref{528f,,弱参照オブジェクト}

@item 
@ref{11a,,weakref}
@end itemize

@end deffn

@menu
* Creating Heap-Allocated Types:: 

@end menu

@node Creating Heap-Allocated Types,,,型オブジェクト<2>
@anchor{c-api/type creating-heap-allocated-types}@anchor{52e5}
@subsubsection Creating Heap-Allocated Types


The following functions and structs are used to create
@ref{b5e,,heap types}.

@geindex PyType_FromMetaclass (C function)
@anchor{c-api/type c PyType_FromMetaclass}@anchor{772}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_FromMetaclass (PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Create and return a @ref{b5e,,heap type} from the `spec'
(see @ref{aac,,Py_TPFLAGS_HEAPTYPE}).

The metaclass `metaclass' is used to construct the resulting type object.
When `metaclass' is @code{NULL}, the metaclass is derived from `bases'
(or `Py_tp_base[s]' slots if `bases' is @code{NULL}, see below).

Metaclasses that override @ref{79f,,tp_new} are not
supported, except if @code{tp_new} is @code{NULL}.

The `bases' argument can be used to specify base classes; it can either
be only one class or a tuple of classes.
If `bases' is @code{NULL}, the @ref{5183,,Py_tp_bases} slot is used instead.
If that also is @code{NULL}, the @ref{5182,,Py_tp_base} slot is used instead.
If that also is @code{NULL}, the new type derives from @ref{c7e,,object}.

The `module' argument can be used to record the module in which the new
class is defined. It must be a module object or @code{NULL}.
If not @code{NULL}, the module is associated with the new type and can later be
retrieved with @ref{b66,,PyType_GetModule()}.
The associated module is not inherited by subclasses; it must be specified
for each class individually.

This function calls @ref{980,,PyType_Ready()} on the new type.

Note that this function does `not' fully match the behavior of
calling @ref{f44,,type()} or using the @ref{14ef,,class} statement.
With user-provided base types or metaclasses, prefer
@ref{5294,,calling} @ref{f44,,type} (or the metaclass)
over @code{PyType_From*} functions.
Specifically:


@itemize *

@item 
@ref{7a0,,__new__()} is not called on the new class
(and it must be set to @code{type.__new__}).

@item 
@ref{8bf,,__init__()} is not called on the new class.

@item 
@ref{843,,__init_subclass__()} is not called on any bases.

@item 
@ref{e48,,__set_name__()} is not called on new descriptors.
@end itemize


Added in version 3.12.

@end deffn

@geindex PyType_FromModuleAndSpec (C function)
@anchor{c-api/type c PyType_FromModuleAndSpec}@anchor{773}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_FromModuleAndSpec (PyObject *module, PyType_Spec *spec, PyObject *bases)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Equivalent to @code{PyType_FromMetaclass(NULL, module, spec, bases)}.


Added in version 3.9.



バージョン 3.10 で変更: The function now accepts a single class as the `bases' argument and
@code{NULL} as the @code{tp_doc} slot.



バージョン 3.12 で変更: The function now finds and uses a metaclass corresponding to the provided
base classes.  Previously, only @ref{f44,,type} instances were returned.

The @ref{79f,,tp_new} of the metaclass is `ignored'.
which may result in incomplete initialization.
Creating classes whose metaclass overrides
@ref{79f,,tp_new} is deprecated.



バージョン 3.14 で変更: Creating classes whose metaclass overrides
@ref{79f,,tp_new} is no longer allowed.

@end deffn

@geindex PyType_FromSpecWithBases (C function)
@anchor{c-api/type c PyType_FromSpecWithBases}@anchor{79e}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_FromSpecWithBases (PyType_Spec *spec, PyObject *bases)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.3 より).'
Equivalent to @code{PyType_FromMetaclass(NULL, NULL, spec, bases)}.


Added in version 3.3.



バージョン 3.12 で変更: The function now finds and uses a metaclass corresponding to the provided
base classes.  Previously, only @ref{f44,,type} instances were returned.

The @ref{79f,,tp_new} of the metaclass is `ignored'.
which may result in incomplete initialization.
Creating classes whose metaclass overrides
@ref{79f,,tp_new} is deprecated.



バージョン 3.14 で変更: Creating classes whose metaclass overrides
@ref{79f,,tp_new} is no longer allowed.

@end deffn

@geindex PyType_FromSpec (C function)
@anchor{c-api/type c PyType_FromSpec}@anchor{79d}
@deffn {C の関数} @ref{5df,,PyObject} *PyType_FromSpec (PyType_Spec *spec)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Equivalent to @code{PyType_FromMetaclass(NULL, NULL, spec, NULL)}.


バージョン 3.12 で変更: The function now finds and uses a metaclass corresponding to the
base classes provided in `Py_tp_base[s]' slots.
Previously, only @ref{f44,,type} instances were returned.

The @ref{79f,,tp_new} of the metaclass is `ignored'.
which may result in incomplete initialization.
Creating classes whose metaclass overrides
@ref{79f,,tp_new} is deprecated.



バージョン 3.14 で変更: Creating classes whose metaclass overrides
@ref{79f,,tp_new} is no longer allowed.

@end deffn

@geindex PyType_Freeze (C function)
@anchor{c-api/type c PyType_Freeze}@anchor{3af}
@deffn {C の関数} int PyType_Freeze (PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Make a type immutable: set the @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} flag.

All base classes of `type' must be immutable.

On success, return @code{0}.
On error, set an exception and return @code{-1}.

The type must not be used before it's made immutable. For example, type
instances must not be created before the type is made immutable.


Added in version 3.14.

@end deffn

@geindex PyType_Spec (C type)
@anchor{c-api/type c PyType_Spec}@anchor{1a89}
@deffn {C のデータ型} type PyType_Spec
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
Structure defining a type's behavior.

@geindex PyType_Spec.name (C member)
@anchor{c-api/type c PyType_Spec name}@anchor{52e6}
@deffn {C のメンバ変数} const char *name

Name of the type, used to set @ref{1cb0,,PyTypeObject.tp_name}.
@end deffn

@geindex PyType_Spec.basicsize (C member)
@anchor{c-api/type c PyType_Spec basicsize}@anchor{76a}
@deffn {C のメンバ変数} int basicsize

If positive, specifies the size of the instance in bytes.
It is used to set @ref{b7e,,PyTypeObject.tp_basicsize}.

If zero, specifies that @ref{b7e,,tp_basicsize}
should be inherited.

If negative, the absolute value specifies how much space instances of the
class need `in addition' to the superclass.
Use @ref{76b,,PyObject_GetTypeData()} to get a pointer to subclass-specific
memory reserved this way.
For negative @code{basicsize}, Python will insert padding when
needed to meet @ref{b7e,,tp_basicsize}'s alignment
requirements.


バージョン 3.12 で変更: Previously, this field could not be negative.

@end deffn

@geindex PyType_Spec.itemsize (C member)
@anchor{c-api/type c PyType_Spec itemsize}@anchor{52e7}
@deffn {C のメンバ変数} int itemsize

Size of one element of a variable-size type, in bytes.
Used to set @ref{23bb,,PyTypeObject.tp_itemsize}.
See @code{tp_itemsize} documentation for caveats.

If zero, @ref{23bb,,tp_itemsize} is inherited.
Extending arbitrary variable-sized classes is dangerous,
since some types use a fixed offset for variable-sized memory,
which can then overlap fixed-sized memory used by a subclass.
To help prevent mistakes, inheriting @code{itemsize} is only possible
in the following situations:


@itemize -

@item 
The base is not variable-sized (its
@ref{23bb,,tp_itemsize}).

@item 
The requested @ref{76a,,PyType_Spec.basicsize} is positive,
suggesting that the memory layout of the base class is known.

@item 
The requested @ref{76a,,PyType_Spec.basicsize} is zero,
suggesting that the subclass does not access the instance's memory
directly.

@item 
With the @ref{76d,,Py_TPFLAGS_ITEMS_AT_END} flag.
@end itemize
@end deffn

@geindex PyType_Spec.flags (C member)
@anchor{c-api/type c PyType_Spec flags}@anchor{52e8}
@deffn {C のメンバ変数} unsigned int flags

Type flags, used to set @ref{1c71,,PyTypeObject.tp_flags}.

If the @code{Py_TPFLAGS_HEAPTYPE} flag is not set,
@ref{79e,,PyType_FromSpecWithBases()} sets it automatically.
@end deffn

@geindex PyType_Spec.slots (C member)
@anchor{c-api/type c PyType_Spec slots}@anchor{52e9}
@deffn {C のメンバ変数} @ref{50dc,,PyType_Slot} *slots

Array of @ref{50dc,,PyType_Slot} structures.
Terminated by the special slot value @code{@{0, NULL@}}.

Each slot ID should be specified at most once.
@end deffn
@end deffn

@geindex PyType_Slot (C type)
@anchor{c-api/type c PyType_Slot}@anchor{50dc}
@deffn {C のデータ型} type PyType_Slot
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
Structure defining optional functionality of a type, containing a slot ID
and a value pointer.

@geindex PyType_Slot.slot (C member)
@anchor{c-api/type c PyType_Slot slot}@anchor{52e1}
@deffn {C のメンバ変数} int slot

A slot ID.

Slot IDs are named like the field names of the structures
@ref{c9c,,PyTypeObject}, @ref{1637,,PyNumberMethods},
@ref{4ef4,,PySequenceMethods}, @ref{4ef5,,PyMappingMethods} and
@ref{52ea,,PyAsyncMethods} with an added @code{Py_} prefix.
For example, use:


@itemize *

@item 
@ref{5186,,Py_tp_dealloc} to set @ref{4ebc,,PyTypeObject.tp_dealloc}

@item 
@ref{5157,,Py_nb_add} to set @ref{52e2,,PyNumberMethods.nb_add}

@item 
@ref{517f,,Py_sq_length} to set @ref{52eb,,PySequenceMethods.sq_length}
@end itemize

An additional slot is supported that does not correspond to a
@code{PyTypeObject} struct field:


@itemize *

@item 
@ref{3b1,,Py_tp_token}
@end itemize

The following “offset” fields cannot be set using @ref{50dc,,PyType_Slot}:


@itemize *

@item 
@ref{b7f,,tp_weaklistoffset}
(use @ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF} instead if possible)

@item 
@ref{52ec,,tp_dictoffset}
(use @ref{60f,,Py_TPFLAGS_MANAGED_DICT} instead if possible)

@item 
@ref{5296,,tp_vectorcall_offset}
(use @code{"__vectorcalloffset__"} in
@ref{52ed,,PyMemberDef})
@end itemize

If it is not possible to switch to a @code{MANAGED} flag (for example,
for vectorcall or to support Python older than 3.12), specify the
offset in @ref{5195,,Py_tp_members}.
See @ref{52ed,,PyMemberDef documentation}
for details.

The following internal fields cannot be set at all when creating a heap
type:


@itemize *

@item 
@ref{1a8c,,tp_dict},
@ref{52ee,,tp_mro},
@ref{52ef,,tp_cache},
@ref{792,,tp_subclasses}, and
@ref{52f0,,tp_weaklist}.
@end itemize

Setting @ref{5183,,Py_tp_bases} or @ref{5182,,Py_tp_base} may be
problematic on some platforms.
To avoid issues, use the `bases' argument of
@ref{79e,,PyType_FromSpecWithBases()} instead.


バージョン 3.9 で変更: Slots in @ref{52f1,,PyBufferProcs} may be set in the unlimited API.



バージョン 3.11 で変更: @ref{966,,bf_getbuffer} and
@ref{967,,bf_releasebuffer} are now available
under the @ref{637,,limited API}.



バージョン 3.14 で変更: The field @ref{198a,,tp_vectorcall} can now be set
using @ref{519e,,Py_tp_vectorcall}.  See the field's documentation
for details.

@end deffn

@geindex PyType_Slot.pfunc (C member)
@anchor{c-api/type c PyType_Slot pfunc}@anchor{52f2}
@deffn {C のメンバ変数} void *pfunc

The desired value of the slot. In most cases, this is a pointer
to a function.

`pfunc' values may not be @code{NULL}, except for the following slots:


@itemize *

@item 
@ref{518a,,Py_tp_doc}

@item 
@ref{3b1,,Py_tp_token} (for clarity, prefer @ref{5139,,Py_TP_USE_SPEC}
rather than @code{NULL})
@end itemize
@end deffn
@end deffn

@geindex Py_tp_token (C macro)
@anchor{c-api/type c Py_tp_token}@anchor{3b1}
@deffn {C のマクロ} Py_tp_token
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
A @ref{52e1,,slot} that records a static memory layout ID
for a class.

If the @ref{1a89,,PyType_Spec} of the class is statically
allocated, the token can be set to the spec using the special value
@ref{5139,,Py_TP_USE_SPEC}:

@example
static PyType_Slot foo_slots[] = @{
   @{Py_tp_token, Py_TP_USE_SPEC@},
@end example

It can also be set to an arbitrary pointer, but you must ensure that:


@itemize *

@item 
The pointer outlives the class, so it's not reused for something else
while the class exists.

@item 
It "belongs" to the extension module where the class lives, so it will not
clash with other extensions.
@end itemize

Use @ref{3b0,,PyType_GetBaseByToken()} to check if a class's superclass has
a given token -- that is, check whether the memory layout is compatible.

To get the token for a given class (without considering superclasses),
use @ref{a9c,,PyType_GetSlot()} with @code{Py_tp_token}.


Added in version 3.14.


@geindex Py_TP_USE_SPEC (C macro)
@anchor{c-api/type c Py_TP_USE_SPEC}@anchor{5139}
@deffn {C のマクロ} Py_TP_USE_SPEC
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Used as a value with @ref{3b1,,Py_tp_token} to set the token to the
class's @ref{1a89,,PyType_Spec}.
Expands to @code{NULL}.


Added in version 3.14.

@end deffn
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node None オブジェクト,,型オブジェクト<2>,基本オブジェクト fundamental object
@anchor{c-api/none doc}@anchor{52f3}@anchor{c-api/none noneobject}@anchor{52f4}@anchor{c-api/none the-none-object}@anchor{52f5}@anchor{c-api/none translation-repo}@anchor{52f6}
@subsubsection @code{None} オブジェクト


@geindex オブジェクト;None

@code{None} に対する @ref{c9c,,PyTypeObject} は、 Python/C API では直接公開されていないので注意してください。 @code{None} は単量子 (singleton) なので、オブジェクトの同一性テスト (C では @code{==}) を使うだけで十分だからです。同じ理由から、 @code{PyNone_Check()} 関数はありません。

@geindex Py_None (C var)
@anchor{c-api/none c Py_None}@anchor{4e9f}
@deffn {C 変数} @ref{5df,,PyObject} *Py_None

値の欠如を示す、 Python の @code{None} オブジェクト。このオブジェクトはメソッドを持たず、 @ref{290,,immortal} です。


バージョン 3.12 で変更: @ref{4e9f,,Py_None} は @ref{290,,immortal} です。

@end deffn

@geindex Py_RETURN_NONE (C macro)
@anchor{c-api/none c Py_RETURN_NONE}@anchor{168c}
@deffn {C のマクロ} Py_RETURN_NONE

関数から @ref{4e9f,,Py_None} を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 数値型オブジェクト numeric object,シーケンスオブジェクト sequence object,基本オブジェクト fundamental object,具象オブジェクト concrete object レイヤ
@anchor{c-api/concrete numeric-objects}@anchor{52f7}@anchor{c-api/concrete numericobjects}@anchor{52f8}
@subsection 数値型オブジェクト (numeric object)


@geindex object;数値

@menu
* 整数型オブジェクト (integer object): 整数型オブジェクト integer object. 
* Boolean オブジェクト:: 
* Floating-Point Objects:: 
* 複素数オブジェクト:: 

@end menu

@node 整数型オブジェクト integer object,Boolean オブジェクト,,数値型オブジェクト numeric object
@anchor{c-api/long doc}@anchor{52f9}@anchor{c-api/long integer-objects}@anchor{52fa}@anchor{c-api/long longobjects}@anchor{52fb}
@subsubsection 整数型オブジェクト (integer object)


@geindex object;long integer
@geindex object;整数

すべての整数は任意の長さをもつ "long" 整数として実装されます。

エラーが起きると、ほとんどの @code{PyLong_As*} API は @code{(return type)-1} を返しますが、これは数値と見分けが付きません。
見分けを付けるためには @ref{1caf,,PyErr_Occurred()} を使ってください。

@geindex PyLongObject (C type)
@anchor{c-api/long c PyLongObject}@anchor{39e}
@deffn {C のデータ型} type PyLongObject
` 次に属します: @ref{775,,Limited API} (不透明な構造体として).'
この @ref{5df,,PyObject} のサブタイプは整数型を表現します。
@end deffn

@geindex PyLong_Type (C var)
@anchor{c-api/long c PyLong_Type}@anchor{504f}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyLong_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは Python 整数型を表現します。これは Python レイヤにおける @ref{19b,,int} と同じオブジェクトです。
@end deffn

@geindex PyLong_Check (C function)
@anchor{c-api/long c PyLong_Check}@anchor{52fc}
@deffn {C の関数} int PyLong_Check (PyObject *p)

引数が @ref{39e,,PyLongObject} か @ref{39e,,PyLongObject} のサブタイプであるときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyLong_CheckExact (C function)
@anchor{c-api/long c PyLong_CheckExact}@anchor{52fd}
@deffn {C の関数} int PyLong_CheckExact (PyObject *p)

引数が @ref{39e,,PyLongObject} であるが @ref{39e,,PyLongObject} のサブタイプでないときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyLong_FromLong (C function)
@anchor{c-api/long c PyLong_FromLong}@anchor{1bd0}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromLong (long v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`v' から新たな @ref{39e,,PyLongObject} オブジェクトを生成して返します。失敗のときには @code{NULL} を返します。

`CPython 実装の詳細:' CPython keeps an array of integer objects for all integers
between @code{-5} and @code{256}.  When you create an int in that range
you actually just get back a reference to the existing object.
@end deffn

@geindex PyLong_FromUnsignedLong (C function)
@anchor{c-api/long c PyLong_FromUnsignedLong}@anchor{18bd}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromUnsignedLong (unsigned long v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Cの unsigned long から新たな @ref{39e,,PyLongObject} オブジェクトを生成して返します。失敗した際には @code{NULL} を返します。
@end deffn

@geindex PyLong_FromSsize_t (C function)
@anchor{c-api/long c PyLong_FromSsize_t}@anchor{189e}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromSsize_t (Py_ssize_t v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
C の @ref{c55,,Py_ssize_t} 型から新たな @ref{39e,,PyLongObject} オブジェクトを生成して返します。 失敗のときには @code{NULL} を返します。
@end deffn

@geindex PyLong_FromSize_t (C function)
@anchor{c-api/long c PyLong_FromSize_t}@anchor{18bf}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromSize_t (size_t v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
C の @code{size_t} 型から新たな @ref{39e,,PyLongObject} オブジェクトを生成して返します。 失敗のときには @code{NULL} を返します。
@end deffn

@geindex PyLong_FromLongLong (C function)
@anchor{c-api/long c PyLong_FromLongLong}@anchor{1bd1}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromLongLong (long long v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
C の long long 型から新たな @ref{39e,,PyLongObject} オブジェクトを生成して返します。失敗のときには @code{NULL} を返します。
@end deffn

@geindex PyLong_FromInt32 (C function)
@geindex PyLong_FromInt64 (C function)
@anchor{c-api/long c PyLong_FromInt32}@anchor{3a3}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromInt32 (int32_t value)
@anchor{c-api/long c PyLong_FromInt64}@anchor{3a4}
@deffnx {C の関数} @ref{5df,,PyObject} *PyLong_FromInt64 (int64_t value)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Return a new @ref{39e,,PyLongObject} object from a signed C
int32_t or int64_t, or @code{NULL}
with an exception set on failure.


Added in version 3.14.

@end deffn

@geindex PyLong_FromUnsignedLongLong (C function)
@anchor{c-api/long c PyLong_FromUnsignedLongLong}@anchor{18be}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromUnsignedLongLong (unsigned long long v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
C の unsigned long long 型から新たな @ref{39e,,PyLongObject} オブジェクトを生成して返します。失敗のときには @code{NULL} を返します。
@end deffn

@geindex PyLong_FromUInt32 (C function)
@geindex PyLong_FromUInt64 (C function)
@anchor{c-api/long c PyLong_FromUInt32}@anchor{3a5}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromUInt32 (uint32_t value)
@anchor{c-api/long c PyLong_FromUInt64}@anchor{3a6}
@deffnx {C の関数} @ref{5df,,PyObject} *PyLong_FromUInt64 (uint64_t value)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Return a new @ref{39e,,PyLongObject} object from an unsigned C
uint32_t or uint64_t, or @code{NULL}
with an exception set on failure.


Added in version 3.14.

@end deffn

@geindex PyLong_FromDouble (C function)
@anchor{c-api/long c PyLong_FromDouble}@anchor{b3c}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromDouble (double v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`v' の整数部から新たな @ref{39e,,PyLongObject} オブジェクトを生成して返します。失敗のときには @code{NULL} を返します。
@end deffn

@geindex PyLong_FromString (C function)
@anchor{c-api/long c PyLong_FromString}@anchor{504c}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromString (const char *str, char **pend, int base)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a new @ref{39e,,PyLongObject} based on the string value in `str', which
is interpreted according to the radix in `base', or @code{NULL} on failure.  If
`pend' is non-@code{NULL}, `*pend' will point to the end of `str' on success or
to the first character that could not be processed on error.  If `base' is @code{0},
`str' is interpreted using the @ref{230b,,整数リテラル} definition; in this case, leading
zeros in a non-zero decimal number raises a @ref{2ec,,ValueError}.  If `base' is not
@code{0}, it must be between @code{2} and @code{36}, inclusive.  Leading and trailing
whitespace and single underscores after a base specifier and between digits are
ignored.  If there are no digits or `str' is not NULL-terminated following the
digits and trailing whitespace, @ref{2ec,,ValueError} will be raised.


@subsubheading 参考


@ref{606,,PyLong_AsNativeBytes()} and
@ref{607,,PyLong_FromNativeBytes()} functions can be used to convert
a @ref{39e,,PyLongObject} to/from an array of bytes in base @code{256}.

@end deffn

@geindex PyLong_FromUnicodeObject (C function)
@anchor{c-api/long c PyLong_FromUnicodeObject}@anchor{ab7}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromUnicodeObject (PyObject *u, int base)
`戻り値: 新しい参照。'
Convert a sequence of Unicode digits in the string `u' to a Python integer
value.


Added in version 3.3.

@end deffn

@geindex PyLong_FromVoidPtr (C function)
@anchor{c-api/long c PyLong_FromVoidPtr}@anchor{504d}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromVoidPtr (void *p)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
ポインタ `p' から Python 整数値を生成します。ポインタの値は @ref{504b,,PyLong_AsVoidPtr()} を適用した結果から取得されます。
@end deffn

@geindex PyLong_FromNativeBytes (C function)
@anchor{c-api/long c PyLong_FromNativeBytes}@anchor{607}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromNativeBytes (const void *buffer, size_t n_bytes, int flags)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Create a Python integer from the value contained in the first `n_bytes' of
`buffer', interpreted as a two's-complement signed number.

`flags' are as for @ref{606,,PyLong_AsNativeBytes()}. Passing @code{-1} will select
the native endian that CPython was compiled with and assume that the
most-significant bit is a sign bit. Passing
@code{Py_ASNATIVEBYTES_UNSIGNED_BUFFER} will produce the same result as calling
@ref{608,,PyLong_FromUnsignedNativeBytes()}. Other flags are ignored.


Added in version 3.13.

@end deffn

@geindex PyLong_FromUnsignedNativeBytes (C function)
@anchor{c-api/long c PyLong_FromUnsignedNativeBytes}@anchor{608}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_FromUnsignedNativeBytes (const void *buffer, size_t n_bytes, int flags)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Create a Python integer from the value contained in the first `n_bytes' of
`buffer', interpreted as an unsigned number.

`flags' are as for @ref{606,,PyLong_AsNativeBytes()}. Passing @code{-1} will select
the native endian that CPython was compiled with and assume that the
most-significant bit is not a sign bit. Flags other than endian are ignored.


Added in version 3.13.

@end deffn

@geindex PyLong_FromPid (C macro)
@anchor{c-api/long c PyLong_FromPid}@anchor{52fe}
@deffn {C のマクロ} PyLong_FromPid (pid)

Macro for creating a Python integer from a process identifier.

This can be defined as an alias to @ref{1bd0,,PyLong_FromLong()} or
@ref{1bd1,,PyLong_FromLongLong()}, depending on the size of the system's
PID type.


Added in version 3.2.

@end deffn

@geindex PyLong_AsLong (C function)
@anchor{c-api/long c PyLong_AsLong}@anchor{605}
@deffn {C の関数} long PyLong_AsLong (PyObject *obj)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex LONG_MAX (C macro)
@geindex OverflowError (組み込み例外)

Return a C long representation of `obj'.  If `obj' is not an
instance of @ref{39e,,PyLongObject}, first call its @ref{19e,,__index__()} method
(if present) to convert it to a @ref{39e,,PyLongObject}.

もし `obj' の値が long の範囲外であれば、 @ref{a81,,OverflowError} を送出します。

エラーが起きたときに @code{-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。


バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。



バージョン 3.10 で変更: This function will no longer use @ref{19d,,__int__()}.


@geindex PyLong_AS_LONG (C function)
@anchor{c-api/long c PyLong_AS_LONG}@anchor{52ff}
@deffn {C の関数} long PyLong_AS_LONG (PyObject *obj)

A @ref{23d,,soft deprecated} alias.
Exactly equivalent to the preferred @code{PyLong_AsLong}. In particular,
it can fail with @ref{a81,,OverflowError} or another exception.


バージョン 3.14 で非推奨: The function is soft deprecated.

@end deffn
@end deffn

@geindex PyLong_AsInt (C function)
@anchor{c-api/long c PyLong_AsInt}@anchor{604}
@deffn {C の関数} int PyLong_AsInt (PyObject *obj)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Similar to @ref{605,,PyLong_AsLong()}, but store the result in a C
int instead of a C long.


Added in version 3.13.

@end deffn

@geindex PyLong_AsLongAndOverflow (C function)
@anchor{c-api/long c PyLong_AsLongAndOverflow}@anchor{147d}
@deffn {C の関数} long PyLong_AsLongAndOverflow (PyObject *obj, int *overflow)
` 次に属します: @ref{775,,Stable ABI}.'
Return a C long representation of `obj'.  If `obj' is not an
instance of @ref{39e,,PyLongObject}, first call its @ref{19e,,__index__()}
method (if present) to convert it to a @ref{39e,,PyLongObject}.

If the value of `obj' is greater than @code{LONG_MAX} or less than
@code{LONG_MIN}, set `*overflow' to @code{1} or @code{-1}, respectively, and
return @code{-1}; otherwise, set `*overflow' to @code{0}.  If any other exception
occurs set `*overflow' to @code{0} and return @code{-1} as usual.

エラーが起きたときに @code{-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。


バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。



バージョン 3.10 で変更: This function will no longer use @ref{19d,,__int__()}.

@end deffn

@geindex PyLong_AsLongLong (C function)
@anchor{c-api/long c PyLong_AsLongLong}@anchor{5046}
@deffn {C の関数} long long PyLong_AsLongLong (PyObject *obj)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex OverflowError (組み込み例外)

Return a C long long representation of `obj'.  If `obj' is not an
instance of @ref{39e,,PyLongObject}, first call its @ref{19e,,__index__()} method
(if present) to convert it to a @ref{39e,,PyLongObject}.

もし `obj' の値が long long の範囲外であれば、 @ref{a81,,OverflowError} を送出します。

エラーが起きたときに @code{-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。


バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。



バージョン 3.10 で変更: This function will no longer use @ref{19d,,__int__()}.

@end deffn

@geindex PyLong_AsLongLongAndOverflow (C function)
@anchor{c-api/long c PyLong_AsLongLongAndOverflow}@anchor{147e}
@deffn {C の関数} long long PyLong_AsLongLongAndOverflow (PyObject *obj, int *overflow)
` 次に属します: @ref{775,,Stable ABI}.'
Return a C long long representation of `obj'.  If `obj' is not an
instance of @ref{39e,,PyLongObject}, first call its @ref{19e,,__index__()} method
(if present) to convert it to a @ref{39e,,PyLongObject}.

If the value of `obj' is greater than @code{LLONG_MAX} or less than
@code{LLONG_MIN}, set `*overflow' to @code{1} or @code{-1}, respectively,
and return @code{-1}; otherwise, set `*overflow' to @code{0}.  If any other
exception occurs set `*overflow' to @code{0} and return @code{-1} as usual.

エラーが起きたときに @code{-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。


Added in version 3.2.



バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。



バージョン 3.10 で変更: This function will no longer use @ref{19d,,__int__()}.

@end deffn

@geindex PyLong_AsSsize_t (C function)
@anchor{c-api/long c PyLong_AsSsize_t}@anchor{5048}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyLong_AsSsize_t (PyObject *pylong)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex PY_SSIZE_T_MAX (C macro)
@geindex OverflowError (組み込み例外)

`pylong' を表す C の @ref{c55,,Py_ssize_t} を返します。 `pylong' は @ref{39e,,PyLongObject} のインスタンスでなければなりません。

もし `pylong' の値が @ref{c55,,Py_ssize_t} の範囲外であれば、 @ref{a81,,OverflowError} を送出します。

エラーが起きたときに @code{-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。
@end deffn

@geindex PyLong_AsUnsignedLong (C function)
@anchor{c-api/long c PyLong_AsUnsignedLong}@anchor{5049}
@deffn {C の関数} unsigned long PyLong_AsUnsignedLong (PyObject *pylong)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex ULONG_MAX (C macro)
@geindex OverflowError (組み込み例外)

`pylong' を表す C の unsigned long を返します。 `pylong' は @ref{39e,,PyLongObject} のインスタンスでなければなりません。

もし `pylong' の値が unsigned long の範囲外であれば、 @ref{a81,,OverflowError} を送出します。

エラーが起きたときに @code{(unsigned long)-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。
@end deffn

@geindex PyLong_AsSize_t (C function)
@anchor{c-api/long c PyLong_AsSize_t}@anchor{5047}
@deffn {C の関数} size_t PyLong_AsSize_t (PyObject *pylong)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex SIZE_MAX (C macro)
@geindex OverflowError (組み込み例外)

`pylong' を表す C の @code{size_t} を返します。 `pylong' は @ref{39e,,PyLongObject} のインスタンスでなければなりません。

もし `pylong' の値が @code{size_t} の範囲外であれば、 @ref{a81,,OverflowError} を送出します。

エラーが起きたときに @code{(size_t)-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。
@end deffn

@geindex PyLong_AsUnsignedLongLong (C function)
@anchor{c-api/long c PyLong_AsUnsignedLongLong}@anchor{14ac}
@deffn {C の関数} unsigned long long PyLong_AsUnsignedLongLong (PyObject *pylong)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex OverflowError (組み込み例外)

`pylong' を表す C の unsigned long long を返します。 `pylong' は @ref{39e,,PyLongObject} のインスタンスでなければなりません。

もし `pylong' の値が unsigned long long の範囲外であれば、 @ref{a81,,OverflowError} を送出します。

エラーが起きたときに @code{(unsigned long long)-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。


バージョン 3.1 で変更: 負 `pylong' を指定した際に @ref{198,,TypeError} ではなく、 @ref{a81,,OverflowError} を送出するようになりました。

@end deffn

@geindex PyLong_AsUnsignedLongMask (C function)
@anchor{c-api/long c PyLong_AsUnsignedLongMask}@anchor{504a}
@deffn {C の関数} unsigned long PyLong_AsUnsignedLongMask (PyObject *obj)
` 次に属します: @ref{775,,Stable ABI}.'
Return a C unsigned long representation of `obj'.  If `obj' is not
an instance of @ref{39e,,PyLongObject}, first call its @ref{19e,,__index__()}
method (if present) to convert it to a @ref{39e,,PyLongObject}.

`obj' の値が unsigned long の範囲から外れていた場合は、 @code{ULONG_MAX + 1} を法とした剰余を返します。

エラーが起きたときに @code{(unsigned long)-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。


バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。



バージョン 3.10 で変更: This function will no longer use @ref{19d,,__int__()}.

@end deffn

@geindex PyLong_AsUnsignedLongLongMask (C function)
@anchor{c-api/long c PyLong_AsUnsignedLongLongMask}@anchor{1dca}
@deffn {C の関数} unsigned long long PyLong_AsUnsignedLongLongMask (PyObject *obj)
` 次に属します: @ref{775,,Stable ABI}.'
Return a C unsigned long long representation of `obj'.  If `obj'
is not an instance of @ref{39e,,PyLongObject}, first call its
@ref{19e,,__index__()} method (if present) to convert it to a
@ref{39e,,PyLongObject}.

`obj' の値が unsigned long long の範囲から外れていた場合は、 @code{ULLONG_MAX + 1} を法とした剰余を返します。

エラーが起きたときに @code{(unsigned long long)-1} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。


バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。



バージョン 3.10 で変更: This function will no longer use @ref{19d,,__int__()}.

@end deffn

@geindex PyLong_AsInt32 (C function)
@geindex PyLong_AsInt64 (C function)
@anchor{c-api/long c PyLong_AsInt32}@anchor{39f}
@deffn {C の関数} int PyLong_AsInt32 (PyObject *obj, int32_t *value)
@anchor{c-api/long c PyLong_AsInt64}@anchor{3a0}
@deffnx {C の関数} int PyLong_AsInt64 (PyObject *obj, int64_t *value)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Set `*value' to a signed C int32_t or int64_t
representation of `obj'.

If `obj' is not an instance of @ref{39e,,PyLongObject}, first call its
@ref{19e,,__index__()} method (if present) to convert it to a
@ref{39e,,PyLongObject}.

If the `obj' value is out of range, raise an @ref{a81,,OverflowError}.

Set `*value' and return @code{0} on success.
Set an exception and return @code{-1} on error.

`value' must not be @code{NULL}.


Added in version 3.14.

@end deffn

@geindex PyLong_AsUInt32 (C function)
@geindex PyLong_AsUInt64 (C function)
@anchor{c-api/long c PyLong_AsUInt32}@anchor{3a1}
@deffn {C の関数} int PyLong_AsUInt32 (PyObject *obj, uint32_t *value)
@anchor{c-api/long c PyLong_AsUInt64}@anchor{3a2}
@deffnx {C の関数} int PyLong_AsUInt64 (PyObject *obj, uint64_t *value)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Set `*value' to an unsigned C uint32_t or uint64_t
representation of `obj'.

If `obj' is not an instance of @ref{39e,,PyLongObject}, first call its
@ref{19e,,__index__()} method (if present) to convert it to a
@ref{39e,,PyLongObject}.


@itemize *

@item 
If `obj' is negative, raise a @ref{2ec,,ValueError}.

@item 
If the `obj' value is out of range, raise an @ref{a81,,OverflowError}.
@end itemize

Set `*value' and return @code{0} on success.
Set an exception and return @code{-1} on error.

`value' must not be @code{NULL}.


Added in version 3.14.

@end deffn

@geindex PyLong_AsDouble (C function)
@anchor{c-api/long c PyLong_AsDouble}@anchor{1975}
@deffn {C の関数} double PyLong_AsDouble (PyObject *pylong)
` 次に属します: @ref{775,,Stable ABI}.'
`pylong' を表す C の double を返します。 `pylong' は @ref{39e,,PyLongObject} のインスタンスでなければなりません。

もし `pylong' の値が double の範囲外であれば、 @ref{a81,,OverflowError} を送出します。

エラーが起きたときに @code{-1.0} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。
@end deffn

@geindex PyLong_AsVoidPtr (C function)
@anchor{c-api/long c PyLong_AsVoidPtr}@anchor{504b}
@deffn {C の関数} void *PyLong_AsVoidPtr (PyObject *pylong)
` 次に属します: @ref{775,,Stable ABI}.'
Python の整数型を指す `pylong' を、 C の void ポインタに変換します。 `pylong' を変換できなければ、 @ref{a81,,OverflowError} を送出します。この関数は @ref{504d,,PyLong_FromVoidPtr()} で値を生成するときに使うような void ポインタ型を生成できるだけです。

エラーが起きたときに @code{NULL} を返します。
見分けを付けるためには  @ref{1caf,,PyErr_Occurred()} を使ってください。
@end deffn

@geindex PyLong_AsNativeBytes (C function)
@anchor{c-api/long c PyLong_AsNativeBytes}@anchor{606}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyLong_AsNativeBytes (PyObject *pylong, void *buffer, Py_ssize_t n_bytes, int flags)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Copy the Python integer value `pylong' to a native `buffer' of size
`n_bytes'. The `flags' can be set to @code{-1} to behave similarly to a C cast,
or to values documented below to control the behavior.

Returns @code{-1} with an exception raised on error.  This may happen if
`pylong' cannot be interpreted as an integer, or if `pylong' was negative
and the @code{Py_ASNATIVEBYTES_REJECT_NEGATIVE} flag was set.

Otherwise, returns the number of bytes required to store the value.
If this is equal to or less than `n_bytes', the entire value was copied.
All `n_bytes' of the buffer are written: remaining bytes filled by
copies of the sign bit.

If the returned value is greater than `n_bytes', the value was
truncated: as many of the lowest bits of the value as could fit are written,
and the higher bits are ignored. This matches the typical behavior
of a C-style downcast.

@cartouche
@quotation 注釈 
Overflow is not considered an error. If the returned value
is larger than `n_bytes', most significant bits were discarded.
@end quotation
@end cartouche

@code{0} will never be returned.

Values are always copied as two's-complement.

Usage example:

@example
int32_t value;
Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1);
if (bytes < 0) @{
    // Failed. A Python exception was set with the reason.
    return NULL;
@}
else if (bytes <= (Py_ssize_t)sizeof(value)) @{
    // Success!
@}
else @{
    // Overflow occurred, but 'value' contains the truncated
    // lowest bits of pylong.
@}
@end example

Passing zero to `n_bytes' will return the size of a buffer that would
be large enough to hold the value. This may be larger than technically
necessary, but not unreasonably so. If `n_bytes=0', `buffer' may be
@code{NULL}.

@cartouche
@quotation 注釈 
Passing `n_bytes=0' to this function is not an accurate way to determine
the bit length of the value.
@end quotation
@end cartouche

To get at the entire Python value of an unknown size, the function can be
called twice: first to determine the buffer size, then to fill it:

@example
// Ask how much space we need.
Py_ssize_t expected = PyLong_AsNativeBytes(pylong, NULL, 0, -1);
if (expected < 0) @{
    // Failed. A Python exception was set with the reason.
    return NULL;
@}
assert(expected != 0);  // Impossible per the API definition.
uint8_t *bignum = malloc(expected);
if (!bignum) @{
    PyErr_SetString(PyExc_MemoryError, "bignum malloc failed.");
    return NULL;
@}
// Safely get the entire value.
Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, bignum, expected, -1);
if (bytes < 0) @{  // Exception has been set.
    free(bignum);
    return NULL;
@}
else if (bytes > expected) @{  // This should not be possible.
    PyErr_SetString(PyExc_RuntimeError,
        "Unexpected bignum truncation after a size check.");
    free(bignum);
    return NULL;
@}
// The expected success given the above pre-check.
// ... use bignum ...
free(bignum);
@end example

`flags' is either @code{-1} (@code{Py_ASNATIVEBYTES_DEFAULTS}) to select defaults
that behave most like a C cast, or a combination of the other flags in
the table below.
Note that @code{-1} cannot be combined with other flags.

Currently, @code{-1} corresponds to
@code{Py_ASNATIVEBYTES_NATIVE_ENDIAN | Py_ASNATIVEBYTES_UNSIGNED_BUFFER}.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxx} 
@headitem

Flag

@tab

値

@item

@geindex Py_ASNATIVEBYTES_DEFAULTS (C macro)
@anchor{c-api/long c Py_ASNATIVEBYTES_DEFAULTS}@anchor{5123}
@deffn {C のマクロ} Py_ASNATIVEBYTES_DEFAULTS
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
@end deffn

@tab

@code{-1}

@item

@geindex Py_ASNATIVEBYTES_BIG_ENDIAN (C macro)
@anchor{c-api/long c Py_ASNATIVEBYTES_BIG_ENDIAN}@anchor{5122}
@deffn {C のマクロ} Py_ASNATIVEBYTES_BIG_ENDIAN
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
@end deffn

@tab

@code{0}

@item

@geindex Py_ASNATIVEBYTES_LITTLE_ENDIAN (C macro)
@anchor{c-api/long c Py_ASNATIVEBYTES_LITTLE_ENDIAN}@anchor{5124}
@deffn {C のマクロ} Py_ASNATIVEBYTES_LITTLE_ENDIAN
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
@end deffn

@tab

@code{1}

@item

@geindex Py_ASNATIVEBYTES_NATIVE_ENDIAN (C macro)
@anchor{c-api/long c Py_ASNATIVEBYTES_NATIVE_ENDIAN}@anchor{5125}
@deffn {C のマクロ} Py_ASNATIVEBYTES_NATIVE_ENDIAN
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
@end deffn

@tab

@code{3}

@item

@geindex Py_ASNATIVEBYTES_UNSIGNED_BUFFER (C macro)
@anchor{c-api/long c Py_ASNATIVEBYTES_UNSIGNED_BUFFER}@anchor{5127}
@deffn {C のマクロ} Py_ASNATIVEBYTES_UNSIGNED_BUFFER
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
@end deffn

@tab

@code{4}

@item

@geindex Py_ASNATIVEBYTES_REJECT_NEGATIVE (C macro)
@anchor{c-api/long c Py_ASNATIVEBYTES_REJECT_NEGATIVE}@anchor{5126}
@deffn {C のマクロ} Py_ASNATIVEBYTES_REJECT_NEGATIVE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
@end deffn

@tab

@code{8}

@item

@geindex Py_ASNATIVEBYTES_ALLOW_INDEX (C macro)
@anchor{c-api/long c Py_ASNATIVEBYTES_ALLOW_INDEX}@anchor{5121}
@deffn {C のマクロ} Py_ASNATIVEBYTES_ALLOW_INDEX
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
@end deffn

@tab

@code{16}

@end multitable


Specifying @code{Py_ASNATIVEBYTES_NATIVE_ENDIAN} will override any other endian
flags. Passing @code{2} is reserved.

By default, sufficient buffer will be requested to include a sign bit.
For example, when converting 128 with `n_bytes=1', the function will return
2 (or more) in order to store a zero sign bit.

If @code{Py_ASNATIVEBYTES_UNSIGNED_BUFFER} is specified, a zero sign bit
will be omitted from size calculations. This allows, for example, 128 to fit
in a single-byte buffer. If the destination buffer is later treated as
signed, a positive input value may become negative.
Note that the flag does not affect handling of negative values: for those,
space for a sign bit is always requested.

Specifying @code{Py_ASNATIVEBYTES_REJECT_NEGATIVE} causes an exception to be set
if `pylong' is negative. Without this flag, negative values will be copied
provided there is enough space for at least one sign bit, regardless of
whether @code{Py_ASNATIVEBYTES_UNSIGNED_BUFFER} was specified.

If @code{Py_ASNATIVEBYTES_ALLOW_INDEX} is specified and a non-integer value is
passed, its @ref{19e,,__index__()} method will be called first. This may
result in Python code executing and other threads being allowed to run, which
could cause changes to other objects or values in use. When `flags' is
@code{-1}, this option is not set, and non-integer values will raise
@ref{198,,TypeError}.

@cartouche
@quotation 注釈 
With the default `flags' (@code{-1}, or `UNSIGNED_BUFFER'  without
`REJECT_NEGATIVE'), multiple Python integers can map to a single value
without overflow. For example, both @code{255} and @code{-1} fit a single-byte
buffer and set all its bits.
This matches typical C cast behavior.
@end quotation
@end cartouche


Added in version 3.13.

@end deffn

@geindex PyLong_AsPid (C macro)
@anchor{c-api/long c PyLong_AsPid}@anchor{19cf}
@deffn {C のマクロ} PyLong_AsPid (pid)

Macro for converting a Python integer into a process identifier.

This can be defined as an alias to @ref{605,,PyLong_AsLong()},
@ref{1bd1,,PyLong_FromLongLong()}, or @ref{604,,PyLong_AsInt()}, depending on the
size of the system's PID type.


Added in version 3.2.

@end deffn

@geindex PyLong_GetSign (C function)
@anchor{c-api/long c PyLong_GetSign}@anchor{39a}
@deffn {C の関数} int PyLong_GetSign (PyObject *obj, int *sign)

Get the sign of the integer object `obj'.

On success, set `*sign' to the integer sign  (0, -1 or +1 for zero, negative or
positive integer, respectively) and return 0.

On failure, return -1 with an exception set.  This function always succeeds
if `obj' is a @ref{39e,,PyLongObject} or its subtype.


Added in version 3.14.

@end deffn

@geindex PyLong_IsPositive (C function)
@anchor{c-api/long c PyLong_IsPositive}@anchor{39b}
@deffn {C の関数} int PyLong_IsPositive (PyObject *obj)

Check if the integer object `obj' is positive (@code{obj > 0}).

If `obj' is an instance of @ref{39e,,PyLongObject} or its subtype,
return @code{1} when it's positive and @code{0} otherwise.  Else set an
exception and return @code{-1}.


Added in version 3.14.

@end deffn

@geindex PyLong_IsNegative (C function)
@anchor{c-api/long c PyLong_IsNegative}@anchor{39c}
@deffn {C の関数} int PyLong_IsNegative (PyObject *obj)

Check if the integer object `obj' is negative (@code{obj < 0}).

If `obj' is an instance of @ref{39e,,PyLongObject} or its subtype,
return @code{1} when it's negative and @code{0} otherwise.  Else set an
exception and return @code{-1}.


Added in version 3.14.

@end deffn

@geindex PyLong_IsZero (C function)
@anchor{c-api/long c PyLong_IsZero}@anchor{39d}
@deffn {C の関数} int PyLong_IsZero (PyObject *obj)

Check if the integer object `obj' is zero.

If `obj' is an instance of @ref{39e,,PyLongObject} or its subtype,
return @code{1} when it's zero and @code{0} otherwise.  Else set an
exception and return @code{-1}.


Added in version 3.14.

@end deffn

@geindex PyLong_GetInfo (C function)
@anchor{c-api/long c PyLong_GetInfo}@anchor{504e}
@deffn {C の関数} @ref{5df,,PyObject} *PyLong_GetInfo (void)
` 次に属します: @ref{775,,Stable ABI}.'
On success, return a read only @ref{85e,,named tuple}, that holds
information about Python's internal representation of integers.
See @ref{14ab,,sys.int_info} for description of individual fields.

On failure, return @code{NULL} with an exception set.


Added in version 3.1.

@end deffn

@geindex PyUnstable_Long_IsCompact (C function)
@anchor{c-api/long c PyUnstable_Long_IsCompact}@anchor{7a6}
@deffn {C の関数} int PyUnstable_Long_IsCompact (const PyLongObject *op)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Return 1 if `op' is compact, 0 otherwise.

This function makes it possible for performance-critical code to implement
a “fast path” for small integers. For compact values use
@ref{7a7,,PyUnstable_Long_CompactValue()}; for others fall back to a
@ref{5047,,PyLong_As*} function or
@ref{606,,PyLong_AsNativeBytes()}.

The speedup is expected to be negligible for most users.

Exactly what values are considered compact is an implementation detail
and is subject to change.


Added in version 3.12.

@end deffn

@geindex PyUnstable_Long_CompactValue (C function)
@anchor{c-api/long c PyUnstable_Long_CompactValue}@anchor{7a7}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnstable_Long_CompactValue (const PyLongObject *op)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

If `op' is compact, as determined by @ref{7a6,,PyUnstable_Long_IsCompact()},
return its value.

Otherwise, the return value is undefined.


Added in version 3.12.

@end deffn

@menu
* Export API:: 
* PyLongWriter API:: 
* Deprecated API:: 

@end menu

@node Export API,PyLongWriter API,,整数型オブジェクト integer object
@anchor{c-api/long export-api}@anchor{5300}
@subsubsection Export API



Added in version 3.14.


@geindex PyLongLayout (C struct)
@anchor{c-api/long c PyLongLayout}@anchor{5301}
@deffn {C Struct} struct PyLongLayout

Layout of an array of "digits" ("limbs" in the GMP terminology), used to
represent absolute value for arbitrary precision integers.

Use @ref{3a7,,PyLong_GetNativeLayout()} to get the native layout of Python
@ref{19b,,int} objects, used internally for integers with "big enough"
absolute value.

See also @ref{14ab,,sys.int_info} which exposes similar information in Python.

@geindex PyLongLayout.bits_per_digit (C member)
@anchor{c-api/long c PyLongLayout bits_per_digit}@anchor{5302}
@deffn {C のメンバ変数} uint8_t bits_per_digit

Bits per digit. For example, a 15 bit digit means that bits 0-14 contain
meaningful information.
@end deffn

@geindex PyLongLayout.digit_size (C member)
@anchor{c-api/long c PyLongLayout digit_size}@anchor{5303}
@deffn {C のメンバ変数} uint8_t digit_size

Digit size in bytes. For example, a 15 bit digit will require at least 2
bytes.
@end deffn

@geindex PyLongLayout.digits_order (C member)
@anchor{c-api/long c PyLongLayout digits_order}@anchor{5304}
@deffn {C のメンバ変数} int8_t digits_order

Digits order:


@itemize -

@item 
@code{1} for most significant digit first

@item 
@code{-1} for least significant digit first
@end itemize
@end deffn

@geindex PyLongLayout.digit_endianness (C member)
@anchor{c-api/long c PyLongLayout digit_endianness}@anchor{5305}
@deffn {C のメンバ変数} int8_t digit_endianness

Digit endianness:


@itemize -

@item 
@code{1} for most significant byte first (big endian)

@item 
@code{-1} for least significant byte first (little endian)
@end itemize
@end deffn
@end deffn

@geindex PyLong_GetNativeLayout (C function)
@anchor{c-api/long c PyLong_GetNativeLayout}@anchor{3a7}
@deffn {C の関数} const @ref{5301,,PyLongLayout} *PyLong_GetNativeLayout (void)

Get the native layout of Python @ref{19b,,int} objects.

See the @ref{5301,,PyLongLayout} structure.

The function must not be called before Python initialization nor after
Python finalization. The returned layout is valid until Python is
finalized. The layout is the same for all Python sub-interpreters
in a process, and so it can be cached.
@end deffn

@geindex PyLongExport (C struct)
@anchor{c-api/long c PyLongExport}@anchor{5306}
@deffn {C Struct} struct PyLongExport

Export of a Python @ref{19b,,int} object.

There are two cases:


@itemize *

@item 
If @ref{5307,,digits} is @code{NULL}, only use the @ref{5308,,value} member.

@item 
If @ref{5307,,digits} is not @code{NULL}, use @ref{5309,,negative},
@ref{530a,,ndigits} and @ref{5307,,digits} members.
@end itemize

@geindex PyLongExport.value (C member)
@anchor{c-api/long c PyLongExport value}@anchor{5308}
@deffn {C のメンバ変数} int64_t value

The native integer value of the exported @ref{19b,,int} object.
Only valid if @ref{5307,,digits} is @code{NULL}.
@end deffn

@geindex PyLongExport.negative (C member)
@anchor{c-api/long c PyLongExport negative}@anchor{5309}
@deffn {C のメンバ変数} uint8_t negative

@code{1} if the number is negative, @code{0} otherwise.
Only valid if @ref{5307,,digits} is not @code{NULL}.
@end deffn

@geindex PyLongExport.ndigits (C member)
@anchor{c-api/long c PyLongExport ndigits}@anchor{530a}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} ndigits

Number of digits in @ref{5307,,digits} array.
Only valid if @ref{5307,,digits} is not @code{NULL}.
@end deffn

@geindex PyLongExport.digits (C member)
@anchor{c-api/long c PyLongExport digits}@anchor{5307}
@deffn {C のメンバ変数} const void *digits

Read-only array of unsigned digits. Can be @code{NULL}.
@end deffn
@end deffn

@geindex PyLong_Export (C function)
@anchor{c-api/long c PyLong_Export}@anchor{3a8}
@deffn {C の関数} int PyLong_Export (PyObject *obj, PyLongExport *export_long)

Export a Python @ref{19b,,int} object.

`export_long' must point to a @ref{5306,,PyLongExport} structure allocated
by the caller. It must not be @code{NULL}.

On success, fill in `*export_long' and return @code{0}.
On error, set an exception and return @code{-1}.

@ref{3a9,,PyLong_FreeExport()} must be called when the export is no longer
needed.

@quotation

`CPython 実装の詳細:' This function always succeeds if `obj' is a Python @ref{19b,,int} object
or a subclass.
@end quotation
@end deffn

@geindex PyLong_FreeExport (C function)
@anchor{c-api/long c PyLong_FreeExport}@anchor{3a9}
@deffn {C の関数} void PyLong_FreeExport (PyLongExport *export_long)

Release the export `export_long' created by @ref{3a8,,PyLong_Export()}.

`CPython 実装の詳細:' Calling @ref{3a9,,PyLong_FreeExport()} is optional if `export_long->digits'
is @code{NULL}.
@end deffn

@node PyLongWriter API,Deprecated API,Export API,整数型オブジェクト integer object
@anchor{c-api/long pylongwriter-api}@anchor{530b}
@subsubsection PyLongWriter API


The @ref{530c,,PyLongWriter} API can be used to import an integer.


Added in version 3.14.


@geindex PyLongWriter (C struct)
@anchor{c-api/long c PyLongWriter}@anchor{530c}
@deffn {C Struct} struct PyLongWriter

A Python @ref{19b,,int} writer instance.

The instance must be destroyed by @ref{3ab,,PyLongWriter_Finish()} or
@ref{3ac,,PyLongWriter_Discard()}.
@end deffn

@geindex PyLongWriter_Create (C function)
@anchor{c-api/long c PyLongWriter_Create}@anchor{3aa}
@deffn {C の関数} @ref{530c,,PyLongWriter} *PyLongWriter_Create (int negative, Py_ssize_t ndigits, void **digits)

Create a @ref{530c,,PyLongWriter}.

On success, allocate `*digits' and return a writer.
On error, set an exception and return @code{NULL}.

`negative' is @code{1} if the number is negative, or @code{0} otherwise.

`ndigits' is the number of digits in the `digits' array. It must be
greater than 0.

`digits' must not be NULL.

After a successful call to this function, the caller should fill in the
array of digits `digits' and then call @ref{3ab,,PyLongWriter_Finish()} to get
a Python @ref{19b,,int}.
The layout of `digits' is described by @ref{3a7,,PyLong_GetNativeLayout()}.

Digits must be in the range [@code{0}; @code{(1 << bits_per_digit) - 1}]
(where the @ref{5302,,bits_per_digit} is the number of bits
per digit).
Any unused most significant digits must be set to @code{0}.

Alternately, call @ref{3ac,,PyLongWriter_Discard()} to destroy the writer
instance without creating an @ref{19b,,int} object.
@end deffn

@geindex PyLongWriter_Finish (C function)
@anchor{c-api/long c PyLongWriter_Finish}@anchor{3ab}
@deffn {C の関数} @ref{5df,,PyObject} *PyLongWriter_Finish (PyLongWriter *writer)
`戻り値: 新しい参照。'
Finish a @ref{530c,,PyLongWriter} created by @ref{3aa,,PyLongWriter_Create()}.

On success, return a Python @ref{19b,,int} object.
On error, set an exception and return @code{NULL}.

The function takes care of normalizing the digits and converts the object
to a compact integer if needed.

The writer instance and the `digits' array are invalid after the call.
@end deffn

@geindex PyLongWriter_Discard (C function)
@anchor{c-api/long c PyLongWriter_Discard}@anchor{3ac}
@deffn {C の関数} void PyLongWriter_Discard (PyLongWriter *writer)

Discard a @ref{530c,,PyLongWriter} created by @ref{3aa,,PyLongWriter_Create()}.

If `writer' is @code{NULL}, no operation is performed.

The writer instance and the `digits' array are invalid after the call.
@end deffn

@node Deprecated API,,PyLongWriter API,整数型オブジェクト integer object
@anchor{c-api/long deprecated-api}@anchor{530d}
@subsubsection Deprecated API


These macros are @ref{23d,,soft deprecated}. They describe parameters
of the internal representation of @ref{39e,,PyLongObject} instances.

Use @ref{3a7,,PyLong_GetNativeLayout()} instead, along with @ref{3a8,,PyLong_Export()}
to read integer data or @ref{530c,,PyLongWriter} to write it.
These currently use the same layout, but are designed to continue working correctly
even if CPython's internal integer representation changes.

@geindex PyLong_SHIFT (C macro)
@anchor{c-api/long c PyLong_SHIFT}@anchor{530e}
@deffn {C のマクロ} PyLong_SHIFT

This is equivalent to @ref{5302,,bits_per_digit} in
the output of @ref{3a7,,PyLong_GetNativeLayout()}.
@end deffn

@geindex PyLong_BASE (C macro)
@anchor{c-api/long c PyLong_BASE}@anchor{1c00}
@deffn {C のマクロ} PyLong_BASE

This is currently equivalent to 1 << @ref{530e,,PyLong_SHIFT}.
@end deffn

@geindex PyLong_MASK (C macro)
@anchor{c-api/long c PyLong_MASK}@anchor{530f}
@deffn {C のマクロ} PyLong_MASK

This is currently equivalent to (1 << @ref{530e,,PyLong_SHIFT}) - 1
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Boolean オブジェクト,Floating-Point Objects,整数型オブジェクト integer object,数値型オブジェクト numeric object
@anchor{c-api/bool doc}@anchor{5310}@anchor{c-api/bool boolean-objects}@anchor{5311}@anchor{c-api/bool boolobjects}@anchor{5312}@anchor{c-api/bool translation-repo}@anchor{5313}
@subsubsection Boolean オブジェクト


Python の Bool 型は整数のサブクラスとして実装されています。ブール型の値は、 @ref{5314,,Py_False} と @ref{5315,,Py_True} の 2 つしかありません。従って、通常の生成／削除関数はブール型にはあてはまりません。とはいえ、以下のマクロが利用できます。

@geindex PyBool_Type (C var)
@anchor{c-api/bool c PyBool_Type}@anchor{4f77}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyBool_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは Python の boolean 型を表現します; Python レイヤにおける @ref{3c3,,bool} と同じオブジェクトです。
@end deffn

@geindex PyBool_Check (C function)
@anchor{c-api/bool c PyBool_Check}@anchor{5316}
@deffn {C の関数} int PyBool_Check (PyObject *o)

`o' が @ref{4f77,,PyBool_Type} 型の場合に真を返します。この関数は常に成功します。
@end deffn

@geindex Py_False (C var)
@anchor{c-api/bool c Py_False}@anchor{5314}
@deffn {C 変数} @ref{5df,,PyObject} *Py_False

Python の @code{False} オブジェクト。このオブジェクトはメソッドを持たず、 @ref{290,,immortal} です。


バージョン 3.12 で変更: @ref{5314,,Py_False} は @ref{290,,immortal} です。

@end deffn

@geindex Py_True (C var)
@anchor{c-api/bool c Py_True}@anchor{5315}
@deffn {C 変数} @ref{5df,,PyObject} *Py_True

Python の @code{True} オブジェクト。このオブジェクトはメソッドを持たず、 @ref{290,,immortal} です。


バージョン 3.12 で変更: @ref{5315,,Py_True} は @ref{290,,immortal} です。

@end deffn

@geindex Py_RETURN_FALSE (C macro)
@anchor{c-api/bool c Py_RETURN_FALSE}@anchor{168e}
@deffn {C のマクロ} Py_RETURN_FALSE

関数から @ref{5314,,Py_False} を返します。
@end deffn

@geindex Py_RETURN_TRUE (C macro)
@anchor{c-api/bool c Py_RETURN_TRUE}@anchor{168d}
@deffn {C のマクロ} Py_RETURN_TRUE

関数から @ref{5315,,Py_True} を返します。
@end deffn

@geindex PyBool_FromLong (C function)
@anchor{c-api/bool c PyBool_FromLong}@anchor{4f76}
@deffn {C の関数} @ref{5df,,PyObject} *PyBool_FromLong (long v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`v' の真理値に応じて @ref{5315,,Py_True} または @ref{5314,,Py_False} を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Floating-Point Objects,複素数オブジェクト,Boolean オブジェクト,数値型オブジェクト numeric object
@anchor{c-api/float doc}@anchor{5317}@anchor{c-api/float floating-point-objects}@anchor{5318}@anchor{c-api/float floatobjects}@anchor{5319}@anchor{c-api/float translation-repo}@anchor{531a}
@subsubsection Floating-Point Objects


@geindex object;浮動小数点

@geindex PyFloatObject (C type)
@anchor{c-api/float c PyFloatObject}@anchor{531b}
@deffn {C のデータ型} type PyFloatObject

This subtype of @ref{5df,,PyObject} represents a Python floating-point object.
@end deffn

@geindex PyFloat_Type (C var)
@anchor{c-api/float c PyFloat_Type}@anchor{502b}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyFloat_Type
` 次に属します: @ref{775,,Stable ABI}.'
This instance of @ref{c9c,,PyTypeObject} represents the Python floating-point
type.  This is the same object as @ref{196,,float} in the Python layer.
@end deffn

@geindex PyFloat_Check (C function)
@anchor{c-api/float c PyFloat_Check}@anchor{531c}
@deffn {C の関数} int PyFloat_Check (PyObject *p)

引数が @ref{531b,,PyFloatObject} か @ref{531b,,PyFloatObject} のサブタイプであるときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyFloat_CheckExact (C function)
@anchor{c-api/float c PyFloat_CheckExact}@anchor{531d}
@deffn {C の関数} int PyFloat_CheckExact (PyObject *p)

引数が @ref{531b,,PyFloatObject} であるが @ref{531b,,PyFloatObject} のサブタイプでないときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyFloat_FromString (C function)
@anchor{c-api/float c PyFloat_FromString}@anchor{502a}
@deffn {C の関数} @ref{5df,,PyObject} *PyFloat_FromString (PyObject *str)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`str' の文字列値をもとに @ref{531b,,PyFloatObject} オブジェクトを生成します。失敗すると @code{NULL} を返します。
@end deffn

@geindex PyFloat_FromDouble (C function)
@anchor{c-api/float c PyFloat_FromDouble}@anchor{5029}
@deffn {C の関数} @ref{5df,,PyObject} *PyFloat_FromDouble (double v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`v' から @ref{531b,,PyFloatObject} オブジェクトを生成して返します。
失敗すると @code{NULL} を返します。
@end deffn

@geindex PyFloat_AsDouble (C function)
@anchor{c-api/float c PyFloat_AsDouble}@anchor{c5f}
@deffn {C の関数} double PyFloat_AsDouble (PyObject *pyfloat)
` 次に属します: @ref{775,,Stable ABI}.'
Return a C double representation of the contents of `pyfloat'.  If
`pyfloat' is not a Python floating-point object but has a @ref{bc1,,__float__()}
method, this method will first be called to convert `pyfloat' into a float.
If @code{__float__()} is not defined then it falls back to @ref{19e,,__index__()}.
This method returns @code{-1.0} upon failure, so one should call
@ref{1caf,,PyErr_Occurred()} to check for errors.


バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。

@end deffn

@geindex PyFloat_AS_DOUBLE (C function)
@anchor{c-api/float c PyFloat_AS_DOUBLE}@anchor{531e}
@deffn {C の関数} double PyFloat_AS_DOUBLE (PyObject *pyfloat)

`pyfloat' の指す値を、 C の double 型表現で返しますが、エラーチェックを行いません。
@end deffn

@geindex PyFloat_GetInfo (C function)
@anchor{c-api/float c PyFloat_GetInfo}@anchor{1609}
@deffn {C の関数} @ref{5df,,PyObject} *PyFloat_GetInfo (void)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
float の精度、最小値、最大値に関する情報を含む structseq インスタンスを返します。これは、 @code{float.h} ファイルの薄いラッパーです。
@end deffn

@geindex PyFloat_GetMax (C function)
@anchor{c-api/float c PyFloat_GetMax}@anchor{1607}
@deffn {C の関数} double PyFloat_GetMax ()
` 次に属します: @ref{775,,Stable ABI}.'
float の表現できる最大限解値 `DBL_MAX' を C の double 型で返します。
@end deffn

@geindex PyFloat_GetMin (C function)
@anchor{c-api/float c PyFloat_GetMin}@anchor{1608}
@deffn {C の関数} double PyFloat_GetMin ()
` 次に属します: @ref{775,,Stable ABI}.'
float の正規化された最小の正の値 `DBL_MIN' を C の double 型で返します。
@end deffn

@geindex Py_INFINITY (C macro)
@anchor{c-api/float c Py_INFINITY}@anchor{531f}
@deffn {C のマクロ} Py_INFINITY

This macro expands to a constant expression of type double, that
represents the positive infinity.

On most platforms, this is equivalent to the @code{INFINITY} macro from
the C11 standard @code{<math.h>} header.
@end deffn

@geindex Py_NAN (C macro)
@anchor{c-api/float c Py_NAN}@anchor{5320}
@deffn {C のマクロ} Py_NAN

This macro expands to a constant expression of type double, that
represents a quiet not-a-number (qNaN) value.

On most platforms, this is equivalent to the @code{NAN} macro from
the C11 standard @code{<math.h>} header.
@end deffn

@geindex Py_HUGE_VAL (C macro)
@anchor{c-api/float c Py_HUGE_VAL}@anchor{5321}
@deffn {C のマクロ} Py_HUGE_VAL

Equivalent to @code{INFINITY}.


バージョン 3.14 で非推奨: The macro is @ref{23d,,soft deprecated}.

@end deffn

@geindex Py_MATH_E (C macro)
@anchor{c-api/float c Py_MATH_E}@anchor{5322}
@deffn {C のマクロ} Py_MATH_E

The definition (accurate for a double type) of the @ref{2a82,,math.e} constant.
@end deffn

@geindex Py_MATH_El (C macro)
@anchor{c-api/float c Py_MATH_El}@anchor{5323}
@deffn {C のマクロ} Py_MATH_El

High precision (long double) definition of @ref{2a82,,e} constant.
@end deffn

@geindex Py_MATH_PI (C macro)
@anchor{c-api/float c Py_MATH_PI}@anchor{5324}
@deffn {C のマクロ} Py_MATH_PI

The definition (accurate for a double type) of the @ref{2a81,,math.pi} constant.
@end deffn

@geindex Py_MATH_PIl (C macro)
@anchor{c-api/float c Py_MATH_PIl}@anchor{5325}
@deffn {C のマクロ} Py_MATH_PIl

High precision (long double) definition of @ref{2a81,,pi} constant.
@end deffn

@geindex Py_MATH_TAU (C macro)
@anchor{c-api/float c Py_MATH_TAU}@anchor{5326}
@deffn {C のマクロ} Py_MATH_TAU

The definition (accurate for a double type) of the @ref{2a83,,math.tau} constant.


Added in version 3.6.

@end deffn

@geindex Py_RETURN_NAN (C macro)
@anchor{c-api/float c Py_RETURN_NAN}@anchor{5327}
@deffn {C のマクロ} Py_RETURN_NAN

Return @ref{873,,math.nan} from a function.

On most platforms, this is equivalent to @code{return PyFloat_FromDouble(NAN)}.
@end deffn

@geindex Py_RETURN_INF (C macro)
@anchor{c-api/float c Py_RETURN_INF}@anchor{5328}
@deffn {C のマクロ} Py_RETURN_INF (sign)

Return @ref{e7e,,math.inf} or @ref{e7e,,-math.inf} from a function,
depending on the sign of `sign'.

On most platforms, this is equivalent to the following:

@example
return PyFloat_FromDouble(copysign(INFINITY, sign));
@end example
@end deffn

@geindex Py_IS_FINITE (C macro)
@anchor{c-api/float c Py_IS_FINITE}@anchor{5329}
@deffn {C のマクロ} Py_IS_FINITE (X)

Return @code{1} if the given floating-point number `X' is finite,
that is, it is normal, subnormal or zero, but not infinite or NaN.
Return @code{0} otherwise.


バージョン 3.14 で非推奨: The macro is @ref{23d,,soft deprecated}.  Use @code{isfinite} instead.

@end deffn

@geindex Py_IS_INFINITY (C macro)
@anchor{c-api/float c Py_IS_INFINITY}@anchor{532a}
@deffn {C のマクロ} Py_IS_INFINITY (X)

Return @code{1} if the given floating-point number `X' is positive or negative
infinity.  Return @code{0} otherwise.


バージョン 3.14 で非推奨: The macro is @ref{23d,,soft deprecated}.  Use @code{isinf} instead.

@end deffn

@geindex Py_IS_NAN (C macro)
@anchor{c-api/float c Py_IS_NAN}@anchor{168f}
@deffn {C のマクロ} Py_IS_NAN (X)

Return @code{1} if the given floating-point number `X' is a not-a-number (NaN)
value.  Return @code{0} otherwise.


バージョン 3.14 で非推奨: The macro is @ref{23d,,soft deprecated}.  Use @code{isnan} instead.

@end deffn

@menu
* Pack and Unpack functions:: 

@end menu

@node Pack and Unpack functions,,,Floating-Point Objects
@anchor{c-api/float pack-and-unpack-functions}@anchor{532b}
@subsubsection Pack and Unpack functions


The pack and unpack functions provide an efficient platform-independent way to
store floating-point values as byte strings. The Pack routines produce a bytes
string from a C double, and the Unpack routines produce a C
double from such a bytes string. The suffix (2, 4 or 8) specifies the
number of bytes in the bytes string.

On platforms that appear to use IEEE 754 formats these functions work by
copying bits. On other platforms, the 2-byte format is identical to the IEEE
754 binary16 half-precision format, the 4-byte format (32-bit) is identical to
the IEEE 754 binary32 single precision format, and the 8-byte format to the
IEEE 754 binary64 double precision format, although the packing of INFs and
NaNs (if such things exist on the platform) isn't handled correctly, and
attempting to unpack a bytes string containing an IEEE INF or NaN will raise an
exception.

Note that NaNs type may not be preserved on IEEE platforms (signaling NaN become
quiet NaN), for example on x86 systems in 32-bit mode.

On non-IEEE platforms with more precision, or larger dynamic range, than IEEE
754 supports, not all values can be packed; on non-IEEE platforms with less
precision, or smaller dynamic range, not all values can be unpacked. What
happens in such cases is partly accidental (alas).


Added in version 3.11.


@menu
* Pack functions:: 
* Unpack functions:: 

@end menu

@node Pack functions,Unpack functions,,Pack and Unpack functions
@anchor{c-api/float pack-functions}@anchor{532c}
@subsubsection Pack functions


The pack routines write 2, 4 or 8 bytes, starting at `p'. `le' is an
int argument, non-zero if you want the bytes string in little-endian
format (exponent last, at @code{p+1}, @code{p+3}, or @code{p+6} @code{p+7}), zero if you
want big-endian format (exponent first, at `p'). The @code{PY_BIG_ENDIAN}
constant can be used to use the native endian: it is equal to @code{1} on big
endian processor, or @code{0} on little endian processor.

Return value: @code{0} if all is OK, @code{-1} if error (and an exception is set,
most likely @ref{a81,,OverflowError}).

There are two problems on non-IEEE platforms:


@itemize *

@item 
What this does is undefined if `x' is a NaN or infinity.

@item 
@code{-0.0} and @code{+0.0} produce the same bytes string.
@end itemize

@geindex PyFloat_Pack2 (C function)
@anchor{c-api/float c PyFloat_Pack2}@anchor{969}
@deffn {C の関数} int PyFloat_Pack2 (double x, char *p, int le)

Pack a C double as the IEEE 754 binary16 half-precision format.
@end deffn

@geindex PyFloat_Pack4 (C function)
@anchor{c-api/float c PyFloat_Pack4}@anchor{96a}
@deffn {C の関数} int PyFloat_Pack4 (double x, char *p, int le)

Pack a C double as the IEEE 754 binary32 single precision format.
@end deffn

@geindex PyFloat_Pack8 (C function)
@anchor{c-api/float c PyFloat_Pack8}@anchor{96b}
@deffn {C の関数} int PyFloat_Pack8 (double x, char *p, int le)

Pack a C double as the IEEE 754 binary64 double precision format.
@end deffn

@node Unpack functions,,Pack functions,Pack and Unpack functions
@anchor{c-api/float unpack-functions}@anchor{532d}
@subsubsection Unpack functions


The unpack routines read 2, 4 or 8 bytes, starting at `p'.  `le' is an
int argument, non-zero if the bytes string is in little-endian format
(exponent last, at @code{p+1}, @code{p+3} or @code{p+6} and @code{p+7}), zero if big-endian
(exponent first, at `p'). The @code{PY_BIG_ENDIAN} constant can be used to
use the native endian: it is equal to @code{1} on big endian processor, or @code{0}
on little endian processor.

Return value: The unpacked double.  On error, this is @code{-1.0} and
@ref{1caf,,PyErr_Occurred()} is true (and an exception is set, most likely
@ref{a81,,OverflowError}).

Note that on a non-IEEE platform this will refuse to unpack a bytes string that
represents a NaN or infinity.

@geindex PyFloat_Unpack2 (C function)
@anchor{c-api/float c PyFloat_Unpack2}@anchor{96c}
@deffn {C の関数} double PyFloat_Unpack2 (const char *p, int le)

Unpack the IEEE 754 binary16 half-precision format as a C double.
@end deffn

@geindex PyFloat_Unpack4 (C function)
@anchor{c-api/float c PyFloat_Unpack4}@anchor{96d}
@deffn {C の関数} double PyFloat_Unpack4 (const char *p, int le)

Unpack the IEEE 754 binary32 single precision format as a C double.
@end deffn

@geindex PyFloat_Unpack8 (C function)
@anchor{c-api/float c PyFloat_Unpack8}@anchor{96e}
@deffn {C の関数} double PyFloat_Unpack8 (const char *p, int le)

Unpack the IEEE 754 binary64 double precision format as a C double.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 複素数オブジェクト,,Floating-Point Objects,数値型オブジェクト numeric object
@anchor{c-api/complex doc}@anchor{532e}@anchor{c-api/complex complex-number-objects}@anchor{532f}@anchor{c-api/complex complexobjects}@anchor{5330}@anchor{c-api/complex translation-repo}@anchor{5331}
@subsubsection 複素数オブジェクト


@geindex object;complex number

Python の複素数オブジェクトは、C API 側から見ると二つの別個の型として実装されています: 一方は Python プログラムに対して公開されている Python のオブジェクトで、他方は実際の複素数値を表現する C の構造体です。API では、これら双方を扱う関数を提供しています。

@menu
* C 構造体としての複素数:: 
* Python オブジェクトとしての複素数型:: 

@end menu

@node C 構造体としての複素数,Python オブジェクトとしての複素数型,,複素数オブジェクト
@anchor{c-api/complex complex-numbers-as-c-structures}@anchor{5332}
@subsubsection C 構造体としての複素数


複素数の C 構造体を引数として受理したり、戻り値として返したりする関数は、ポインタ渡しを行うのではなく `値渡し' を行うので注意してください。これは API 全体を通して一貫しています。

@geindex Py_complex (C type)
@anchor{c-api/complex c Py_complex}@anchor{523d}
@deffn {C のデータ型} type Py_complex

The C structure which corresponds to the value portion of a Python complex
number object.  Most of the functions for dealing with complex number objects
use structures of this type as input or output values, as appropriate.

@geindex Py_complex.real (C member)
@geindex Py_complex.imag (C member)
@anchor{c-api/complex c Py_complex real}@anchor{5333}
@deffn {C のメンバ変数} double real
@anchor{c-api/complex c Py_complex imag}@anchor{5334}
@deffnx {C のメンバ変数} double imag
@end deffn

The structure is defined as:

@example
typedef struct @{
    double real;
    double imag;
@} Py_complex;
@end example
@end deffn

@geindex _Py_c_sum (C function)
@anchor{c-api/complex c _Py_c_sum}@anchor{5335}
@deffn {C の関数} @ref{523d,,Py_complex} _Py_c_sum (Py_complex left, Py_complex right)

二つの複素数の和を C の @ref{523d,,Py_complex} 型で返します。
@end deffn

@geindex _Py_c_diff (C function)
@anchor{c-api/complex c _Py_c_diff}@anchor{5336}
@deffn {C の関数} @ref{523d,,Py_complex} _Py_c_diff (Py_complex left, Py_complex right)

二つの複素数の差を C の @ref{523d,,Py_complex} 型で返します。
@end deffn

@geindex _Py_c_neg (C function)
@anchor{c-api/complex c _Py_c_neg}@anchor{5337}
@deffn {C の関数} @ref{523d,,Py_complex} _Py_c_neg (Py_complex num)

複素数 `num' の符号反転 C の @ref{523d,,Py_complex} 型で返します。
@end deffn

@geindex _Py_c_prod (C function)
@anchor{c-api/complex c _Py_c_prod}@anchor{5338}
@deffn {C の関数} @ref{523d,,Py_complex} _Py_c_prod (Py_complex left, Py_complex right)

二つの複素数の積を C の @ref{523d,,Py_complex} 型で返します。
@end deffn

@geindex _Py_c_quot (C function)
@anchor{c-api/complex c _Py_c_quot}@anchor{5339}
@deffn {C の関数} @ref{523d,,Py_complex} _Py_c_quot (Py_complex dividend, Py_complex divisor)

二つの複素数の商を C の @ref{523d,,Py_complex} 型で返します。

`divisor' が null の場合は、このメソッドはゼロを返し、 @code{errno} に @code{EDOM} をセットします。
@end deffn

@geindex _Py_c_pow (C function)
@anchor{c-api/complex c _Py_c_pow}@anchor{18f2}
@deffn {C の関数} @ref{523d,,Py_complex} _Py_c_pow (Py_complex num, Py_complex exp)

指数 `exp' の `num' 乗を C の @ref{523d,,Py_complex} 型で返します。

`num' が null で `exp' が正の実数でない場合は、このメソッドはゼロを返し、 @code{errno} に @code{EDOM} をセットします。

Set @code{errno} to @code{ERANGE} on overflows.
@end deffn

@node Python オブジェクトとしての複素数型,,C 構造体としての複素数,複素数オブジェクト
@anchor{c-api/complex complex-numbers-as-python-objects}@anchor{533a}
@subsubsection Python オブジェクトとしての複素数型


@geindex PyComplexObject (C type)
@anchor{c-api/complex c PyComplexObject}@anchor{533b}
@deffn {C のデータ型} type PyComplexObject

この @ref{5df,,PyObject} のサブタイプは Python の複素数型を表現します。
@end deffn

@geindex PyComplex_Type (C var)
@anchor{c-api/complex c PyComplex_Type}@anchor{4fae}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyComplex_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは Python の複素数型を表現します。 Pythonレイヤの @ref{197,,complex} と同じオブジェクトです。
@end deffn

@geindex PyComplex_Check (C function)
@anchor{c-api/complex c PyComplex_Check}@anchor{533c}
@deffn {C の関数} int PyComplex_Check (PyObject *p)

引数が @ref{533b,,PyComplexObject} か @ref{533b,,PyComplexObject} のサブタイプであるときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyComplex_CheckExact (C function)
@anchor{c-api/complex c PyComplex_CheckExact}@anchor{533d}
@deffn {C の関数} int PyComplex_CheckExact (PyObject *p)

引数が @ref{533b,,PyComplexObject} であるが @ref{533b,,PyComplexObject} のサブタイプでないときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyComplex_FromCComplex (C function)
@anchor{c-api/complex c PyComplex_FromCComplex}@anchor{533e}
@deffn {C の関数} @ref{5df,,PyObject} *PyComplex_FromCComplex (Py_complex v)
`戻り値: 新しい参照。'
Create a new Python complex number object from a C @ref{523d,,Py_complex} value.
Return @code{NULL} with an exception set on error.
@end deffn

@geindex PyComplex_FromDoubles (C function)
@anchor{c-api/complex c PyComplex_FromDoubles}@anchor{4fad}
@deffn {C の関数} @ref{5df,,PyObject} *PyComplex_FromDoubles (double real, double imag)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a new @ref{533b,,PyComplexObject} object from `real' and `imag'.
Return @code{NULL} with an exception set on error.
@end deffn

@geindex PyComplex_RealAsDouble (C function)
@anchor{c-api/complex c PyComplex_RealAsDouble}@anchor{1a12}
@deffn {C の関数} double PyComplex_RealAsDouble (PyObject *op)
` 次に属します: @ref{775,,Stable ABI}.'
`op' の実数部分を C の double 型で返します。

If `op' is not a Python complex number object but has a
@ref{7fd,,__complex__()} method, this method will first be called to
convert `op' to a Python complex number object.  If @code{__complex__()} is
not defined then it falls back to call @ref{c5f,,PyFloat_AsDouble()} and
returns its result.

Upon failure, this method returns @code{-1.0} with an exception set, so one
should call @ref{1caf,,PyErr_Occurred()} to check for errors.


バージョン 3.13 で変更: Use @ref{7fd,,__complex__()} if available.

@end deffn

@geindex PyComplex_ImagAsDouble (C function)
@anchor{c-api/complex c PyComplex_ImagAsDouble}@anchor{1a13}
@deffn {C の関数} double PyComplex_ImagAsDouble (PyObject *op)
` 次に属します: @ref{775,,Stable ABI}.'
`op' の虚数部分を C の double 型で返します。

If `op' is not a Python complex number object but has a
@ref{7fd,,__complex__()} method, this method will first be called to
convert `op' to a Python complex number object.  If @code{__complex__()} is
not defined then it falls back to call @ref{c5f,,PyFloat_AsDouble()} and
returns @code{0.0} on success.

Upon failure, this method returns @code{-1.0} with an exception set, so one
should call @ref{1caf,,PyErr_Occurred()} to check for errors.


バージョン 3.13 で変更: Use @ref{7fd,,__complex__()} if available.

@end deffn

@geindex PyComplex_AsCComplex (C function)
@anchor{c-api/complex c PyComplex_AsCComplex}@anchor{160a}
@deffn {C の関数} @ref{523d,,Py_complex} PyComplex_AsCComplex (PyObject *op)

複素数値 `op' から @ref{523d,,Py_complex} 型を生成します。

If `op' is not a Python complex number object but has a @ref{7fd,,__complex__()}
method, this method will first be called to convert `op' to a Python complex
number object.  If @code{__complex__()} is not defined then it falls back to
@ref{bc1,,__float__()}.  If @code{__float__()} is not defined then it falls back
to @ref{19e,,__index__()}.

Upon failure, this method returns @ref{523d,,Py_complex}
with @ref{5333,,real} set to @code{-1.0} and with an exception set, so one
should call @ref{1caf,,PyErr_Occurred()} to check for errors.


バージョン 3.8 で変更: 可能であれば @ref{19e,,__index__()} を使うようになりました。

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node シーケンスオブジェクト sequence object,Container オブジェクト,数値型オブジェクト numeric object,具象オブジェクト concrete object レイヤ
@anchor{c-api/concrete sequence-objects}@anchor{533f}@anchor{c-api/concrete sequenceobjects}@anchor{5340}
@subsection シーケンスオブジェクト (sequence object)


@geindex object;sequence

シーケンスオブジェクトに対する一般的な操作については前の章ですでに述べました; この節では、Python 言語にもともと備わっている特定のシーケンスオブジェクトについて扱います。

@c XXX sort out unicode, str, bytes and bytearray

@menu
* バイトオブジェクト: バイトオブジェクト<2>. 
* bytearray オブジェクト: bytearray オブジェクト<2>. 
* Unicode オブジェクトと codec:: 
* タプルオブジェクト (tuple object): タプルオブジェクト tuple object. 
* Struct Sequence オブジェクト:: 
* リストオブジェクト:: 

@end menu

@node バイトオブジェクト<2>,bytearray オブジェクト<2>,,シーケンスオブジェクト sequence object
@anchor{c-api/bytes doc}@anchor{5341}@anchor{c-api/bytes bytes-objects}@anchor{5342}@anchor{c-api/bytes bytesobjects}@anchor{5343}
@subsubsection バイトオブジェクト


下記の関数は、バイトオブジェクトを期待している引数にバイトオブジェクトでないパラメタを指定して呼び出されると、 @ref{198,,TypeError} を送出します。

@geindex object;bytes

@geindex PyBytesObject (C type)
@anchor{c-api/bytes c PyBytesObject}@anchor{995}
@deffn {C のデータ型} type PyBytesObject

この @ref{5df,,PyObject} のサブタイプは、Python バイトオブジェクトを表します。
@end deffn

@geindex PyBytes_Type (C var)
@anchor{c-api/bytes c PyBytes_Type}@anchor{4f88}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyBytes_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは、Python バイト型を表します; Pythonレイヤの @ref{192,,bytes} と同じオブジェクトです。
@end deffn

@geindex PyBytes_Check (C function)
@anchor{c-api/bytes c PyBytes_Check}@anchor{15b7}
@deffn {C の関数} int PyBytes_Check (PyObject *o)

オブジェクト `o' が bytes オブジェクトか bytes 型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyBytes_CheckExact (C function)
@anchor{c-api/bytes c PyBytes_CheckExact}@anchor{5344}
@deffn {C の関数} int PyBytes_CheckExact (PyObject *o)

オブジェクト `o' が bytes オブジェクトだが bytes 型のサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyBytes_FromString (C function)
@anchor{c-api/bytes c PyBytes_FromString}@anchor{4f85}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_FromString (const char *v)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功時に、文字列 `v' のコピーを値とする新しいバイトオブジェクトを返し、失敗時に @code{NULL} を返します。
引数 `v' は @code{NULL} であってはなりません; そのチェックは行われません。
@end deffn

@geindex PyBytes_FromStringAndSize (C function)
@anchor{c-api/bytes c PyBytes_FromStringAndSize}@anchor{15b8}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_FromStringAndSize (const char *v, Py_ssize_t len)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
成功時に、文字列 `v' のコピーを値とする長さ `len' の新しいバイトオブジェクトを返し、失敗時に @code{NULL} を返します。
引数 `v' が @code{NULL} の場合、バイトオブジェクトの中身は初期化されていません。
@end deffn

@geindex PyBytes_FromFormat (C function)
@anchor{c-api/bytes c PyBytes_FromFormat}@anchor{1e0b}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_FromFormat (const char *format, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
C 関数の @code{printf()} スタイルの `format' 文字列と可変長の引数を取り、結果のPython バイトオブジェクトのサイズを計算し、値を指定した書式にしたがって変換したバイトオブジェクトを返します。可変長の引数は C のデータ型でなければならず、 `format' 文字列中のフォーマット文字と厳密に関連付けられていなければなりません。下記のフォーマット文字が使用できます:

@c % XXX: This should be exactly the same as the table in PyErr_Format.

@c % One should just refer to the other.


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

書式指定文字

@tab

型

@tab

備考

@item

@code{%%}

@tab

`n/a'

@tab

リテラルの % 文字

@item

@code{%c}

@tab

int

@tab

C の整数型で表現される単一のバイト。

@item

@code{%d}

@tab

int

@tab

@code{printf("%d")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%u}

@tab

unsigned int

@tab

@code{printf("%u")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%ld}

@tab

long

@tab

@code{printf("%ld")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%lu}

@tab

unsigned long

@tab

@code{printf("%lu")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%zd}

@tab

@ref{c55,,Py_ssize_t}

@tab

@code{printf("%zd")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%zu}

@tab

size_t

@tab

@code{printf("%zu")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%i}

@tab

int

@tab

@code{printf("%i")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%x}

@tab

int

@tab

@code{printf("%x")} と同等。 @footnote{
整数指定子 (d, u, ld, lu, zd, zu, i, x): 精度が与えられていても、0指定子は有効です。
}

@item

@code{%s}

@tab

const char*

@tab

null で終端された C の文字列。

@item

@code{%p}

@tab

const void*

@tab

C ポインタの 16 進表記。@code{printf("%p")} とほとんど同じですが、プラットフォームにおける @code{printf} の定義に関わりなく先頭にリテラル @code{0x} が付きます。

@end multitable


識別できない書式指定文字があった場合、残りの書式文字列はそのまま結果のオブジェクトにコピーされ、残りの引数は無視されます。
@end deffn

@geindex PyBytes_FromFormatV (C function)
@anchor{c-api/bytes c PyBytes_FromFormatV}@anchor{4f83}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_FromFormatV (const char *format, va_list vargs)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
ちょうど２つの引数を取ることを除いて、 @ref{1e0b,,PyBytes_FromFormat()} と同じです。
@end deffn

@geindex PyBytes_FromObject (C function)
@anchor{c-api/bytes c PyBytes_FromObject}@anchor{4f84}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_FromObject (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
バッファプロトコルを実装するオブジェクト `o' のバイト表現を返します。
@end deffn

@geindex PyBytes_Size (C function)
@anchor{c-api/bytes c PyBytes_Size}@anchor{4f87}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyBytes_Size (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
バイトオブジェクト `o' のバイト単位の長さを返します。
@end deffn

@geindex PyBytes_GET_SIZE (C function)
@anchor{c-api/bytes c PyBytes_GET_SIZE}@anchor{5345}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyBytes_GET_SIZE (PyObject *o)

@ref{4f87,,PyBytes_Size()} に似ていますが、エラーチェックを行いません。
@end deffn

@geindex PyBytes_AsString (C function)
@anchor{c-api/bytes c PyBytes_AsString}@anchor{a87}
@deffn {C の関数} char *PyBytes_AsString (PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
`o' の中身へのポインタを返します。
ポインタは、 @code{len(o) + 1} バイトからなる `o' の内部バッファを参照します。
他に null のバイトがあるかどうかにかかわらず、バッファの最後のバイトは必ず null になります。
@code{PyBytes_FromStringAndSize(NULL, size)} で生成された場合を除いて、データを修正してはなりません。
またポインタを解放（deallocated）してはなりません。
もし、 `o' が bytes オブジェクトでなければ、 @ref{a87,,PyBytes_AsString()} は @code{NULL} を返し @ref{198,,TypeError} を送出します。
@end deffn

@geindex PyBytes_AS_STRING (C function)
@anchor{c-api/bytes c PyBytes_AS_STRING}@anchor{5346}
@deffn {C の関数} char *PyBytes_AS_STRING (PyObject *string)

@ref{a87,,PyBytes_AsString()} に似ていますが、エラーチェックを行いません。
@end deffn

@geindex PyBytes_AsStringAndSize (C function)
@anchor{c-api/bytes c PyBytes_AsStringAndSize}@anchor{4f7f}
@deffn {C の関数} int PyBytes_AsStringAndSize (PyObject *obj, char **buffer, Py_ssize_t *length)
` 次に属します: @ref{775,,Stable ABI}.'
Return the null-terminated contents of the object `obj'
through the output variables `buffer' and `length'.
Returns @code{0} on success.

`length' の値が @code{NULL} の場合、バイトオブジェクトが  null バイトを含まない可能性があります。その場合、関数は @code{-1} を返し、 @ref{2ec,,ValueError} を送出します。

buffer は `obj' の内部バッファを参照していて、これには末尾の null バイトも含んでいます (これは `length' には数えられません)。
オブジェクトが @code{PyBytes_FromStringAndSize(NULL, size)} で生成された場合を除いて、何があってもデータを改変してはいけません。
オブジェクトを解放 (deallocate) してもいけません。
`obj' が bytes オブジェクトでなかった場合は、 @ref{4f7f,,PyBytes_AsStringAndSize()} は @code{-1} を返し @ref{198,,TypeError} を送出します。


バージョン 3.5 で変更: 以前は bytes オブジェクトにヌルバイトが埋め込まれていたときに @ref{198,,TypeError} を送出していました。

@end deffn

@geindex PyBytes_Concat (C function)
@anchor{c-api/bytes c PyBytes_Concat}@anchor{4f80}
@deffn {C の関数} void PyBytes_Concat (PyObject **bytes, PyObject *newpart)
` 次に属します: @ref{775,,Stable ABI}.'
`newpart' の内容を `bytes' の後ろに連結した新しいバイトオブジェクトを `*bytes' に生成します。呼び出し側は新しい参照を所有します。
`bytes' の古い値の参照は盗まれます。
もし新しいオブジェクトが生成できない場合、古い `bytes' の参照は放棄され、 `*bytes' の値は @code{NULL} に設定されます; 適切な例外が設定されます。
@end deffn

@geindex PyBytes_ConcatAndDel (C function)
@anchor{c-api/bytes c PyBytes_ConcatAndDel}@anchor{4f81}
@deffn {C の関数} void PyBytes_ConcatAndDel (PyObject **bytes, PyObject *newpart)
` 次に属します: @ref{775,,Stable ABI}.'
Create a new bytes object in `*bytes' containing the contents of `newpart'
appended to `bytes'.  This version releases the @ref{5e2,,strong reference}
to `newpart' (i.e. decrements its reference count).
@end deffn

@geindex PyBytes_Join (C function)
@anchor{c-api/bytes c PyBytes_Join}@anchor{383}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_Join (PyObject *sep, PyObject *iterable)

Similar to @code{sep.join(iterable)} in Python.

`sep' must be Python @ref{192,,bytes} object.
(Note that @ref{13ba,,PyUnicode_Join()} accepts @code{NULL} separator and treats
it as a space, whereas @ref{383,,PyBytes_Join()} doesn't accept @code{NULL}
separator.)

`iterable' must be an iterable object yielding objects that implement the
@ref{260,,buffer protocol}.

On success, return a new @ref{192,,bytes} object.
On error, set an exception and return @code{NULL}.


Added in version 3.14.

@end deffn

@geindex _PyBytes_Resize (C function)
@anchor{c-api/bytes c _PyBytes_Resize}@anchor{19ce}
@deffn {C の関数} int _PyBytes_Resize (PyObject **bytes, Py_ssize_t newsize)

Resize a bytes object. `newsize' will be the new length of the bytes object.
You can think of it as creating a new bytes object and destroying the old
one, only more efficiently.
Pass the address of an
existing bytes object as an lvalue (it may be written into), and the new size
desired.  On success, `*bytes' holds the resized bytes object and @code{0} is
returned; the address in `*bytes' may differ from its input value.  If the
reallocation fails, the original bytes object at `*bytes' is deallocated,
`*bytes' is set to @code{NULL}, @ref{179e,,MemoryError} is set, and @code{-1} is
returned.
@end deffn

@geindex PyBytes_Repr (C function)
@anchor{c-api/bytes c PyBytes_Repr}@anchor{4f86}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_Repr (PyObject *bytes, int smartquotes)
` 次に属します: @ref{775,,Stable ABI}.'
Get the string representation of `bytes'. This function is currently used to
implement @code{bytes.__repr__()} in Python.

This function does not do type checking; it is undefined behavior to pass
`bytes' as a non-bytes object or @code{NULL}.

If `smartquotes' is true, the representation will use a double-quoted string
instead of single-quoted string when single-quotes are present in `bytes'.
For example, the byte string @code{'Python'} would be represented as
@code{b"'Python'"} when `smartquotes' is true, or @code{b'\'Python\'@w{'}} when it is
false.

On success, this function returns a @ref{5e2,,strong reference} to a
@ref{169,,str} object containing the representation. On failure, this
returns @code{NULL} with an exception set.
@end deffn

@geindex PyBytes_DecodeEscape (C function)
@anchor{c-api/bytes c PyBytes_DecodeEscape}@anchor{4f82}
@deffn {C の関数} @ref{5df,,PyObject} *PyBytes_DecodeEscape (const char *s, Py_ssize_t len, const char *errors, Py_ssize_t unicode, const char *recode_encoding)
` 次に属します: @ref{775,,Stable ABI}.'
Unescape a backslash-escaped string `s'. `s' must not be @code{NULL}.
`len' must be the size of `s'.

`errors' must be one of @code{"strict"}, @code{"replace"}, or @code{"ignore"}. If
`errors' is @code{NULL}, then @code{"strict"} is used by default.

On success, this function returns a @ref{5e2,,strong reference} to a Python
@ref{192,,bytes} object containing the unescaped string. On failure, this
function returns @code{NULL} with an exception set.


バージョン 3.9 で変更: `unicode' and `recode_encoding' are now unused.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node bytearray オブジェクト<2>,Unicode オブジェクトと codec,バイトオブジェクト<2>,シーケンスオブジェクト sequence object
@anchor{c-api/bytearray doc}@anchor{5347}@anchor{c-api/bytearray byte-array-objects}@anchor{5348}@anchor{c-api/bytearray bytearrayobjects}@anchor{5349}@anchor{c-api/bytearray translation-repo}@anchor{534a}
@subsubsection bytearray オブジェクト


@geindex object;bytearray

@geindex PyByteArrayObject (C type)
@anchor{c-api/bytearray c PyByteArrayObject}@anchor{534b}
@deffn {C のデータ型} type PyByteArrayObject

この @ref{5df,,PyObject} のサブタイプは Python の bytearray オブジェクトを表します。
@end deffn

@geindex PyByteArray_Type (C var)
@anchor{c-api/bytearray c PyByteArray_Type}@anchor{4f7d}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyByteArray_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは、 Python bytearray 型を示します。 Python レイヤでの @ref{344,,bytearray} と同じオブジェクトです。
@end deffn

@menu
* 型チェックマクロ:: 
* ダイレクト API 関数:: 
* マクロ:: 

@end menu

@node 型チェックマクロ,ダイレクト API 関数,,bytearray オブジェクト<2>
@anchor{c-api/bytearray type-check-macros}@anchor{534c}
@subsubsection 型チェックマクロ


@geindex PyByteArray_Check (C function)
@anchor{c-api/bytearray c PyByteArray_Check}@anchor{534d}
@deffn {C の関数} int PyByteArray_Check (PyObject *o)

オブジェクト `o' が bytearray オブジェクトか bytearray 型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyByteArray_CheckExact (C function)
@anchor{c-api/bytearray c PyByteArray_CheckExact}@anchor{534e}
@deffn {C の関数} int PyByteArray_CheckExact (PyObject *o)

オブジェクト `o' が bytearray オブジェクトだが bytearray 型のサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。
@end deffn

@node ダイレクト API 関数,マクロ,型チェックマクロ,bytearray オブジェクト<2>
@anchor{c-api/bytearray direct-api-functions}@anchor{534f}
@subsubsection ダイレクト API 関数


@geindex PyByteArray_FromObject (C function)
@anchor{c-api/bytearray c PyByteArray_FromObject}@anchor{15c2}
@deffn {C の関数} @ref{5df,,PyObject} *PyByteArray_FromObject (PyObject *o)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{260,,buffer protocol} を実装した任意のオブジェクト `o' から、新しいbytearrayオブジェクトを作成し、返します。

On failure, return @code{NULL} with an exception set.
@end deffn

@geindex PyByteArray_FromStringAndSize (C function)
@anchor{c-api/bytearray c PyByteArray_FromStringAndSize}@anchor{15c3}
@deffn {C の関数} @ref{5df,,PyObject} *PyByteArray_FromStringAndSize (const char *string, Py_ssize_t len)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a new bytearray object from `string' and its length, `len'.

On failure, return @code{NULL} with an exception set.
@end deffn

@geindex PyByteArray_Concat (C function)
@anchor{c-api/bytearray c PyByteArray_Concat}@anchor{4f7a}
@deffn {C の関数} @ref{5df,,PyObject} *PyByteArray_Concat (PyObject *a, PyObject *b)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
bytearray `a' と `b' を連結した結果を新しい bytearray として返します。

On failure, return @code{NULL} with an exception set.
@end deffn

@geindex PyByteArray_Size (C function)
@anchor{c-api/bytearray c PyByteArray_Size}@anchor{4f7c}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyByteArray_Size (PyObject *bytearray)
` 次に属します: @ref{775,,Stable ABI}.'
@code{NULL} ポインタチェックの後に `bytearray' のサイズを返します。
@end deffn

@geindex PyByteArray_AsString (C function)
@anchor{c-api/bytearray c PyByteArray_AsString}@anchor{4f79}
@deffn {C の関数} char *PyByteArray_AsString (PyObject *bytearray)
` 次に属します: @ref{775,,Stable ABI}.'
@code{NULL} ポインタチェックの後に `bytearray' の内容を char 配列として返します。
返される配列には、常に余分な null バイトが追加されます。
@end deffn

@geindex PyByteArray_Resize (C function)
@anchor{c-api/bytearray c PyByteArray_Resize}@anchor{4f7b}
@deffn {C の関数} int PyByteArray_Resize (PyObject *bytearray, Py_ssize_t len)
` 次に属します: @ref{775,,Stable ABI}.'
Resize the internal buffer of `bytearray' to `len'.
Failure is a @code{-1} return with an exception set.


バージョン 3.14 で変更: A negative `len' will now result in an exception being set and -1 returned.

@end deffn

@node マクロ,,ダイレクト API 関数,bytearray オブジェクト<2>
@anchor{c-api/bytearray macros}@anchor{5350}
@subsubsection マクロ


以下のマクロは、ポインタのチェックをしないことにより安全性を犠牲にしてスピードを優先しています。

@geindex PyByteArray_AS_STRING (C function)
@anchor{c-api/bytearray c PyByteArray_AS_STRING}@anchor{5351}
@deffn {C の関数} char *PyByteArray_AS_STRING (PyObject *bytearray)

@ref{4f79,,PyByteArray_AsString()} に似ていますが、エラーチェックを行いません。
@end deffn

@geindex PyByteArray_GET_SIZE (C function)
@anchor{c-api/bytearray c PyByteArray_GET_SIZE}@anchor{5352}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyByteArray_GET_SIZE (PyObject *bytearray)

@ref{4f7c,,PyByteArray_Size()} に似ていますが、エラーチェックを行いません。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Unicode オブジェクトと codec,タプルオブジェクト tuple object,bytearray オブジェクト<2>,シーケンスオブジェクト sequence object
@anchor{c-api/unicode doc}@anchor{13b8}@anchor{c-api/unicode translation-repo}@anchor{5353}@anchor{c-api/unicode unicode-objects-and-codecs}@anchor{5354}@anchor{c-api/unicode unicodeobjects}@anchor{5355}
@subsubsection Unicode オブジェクトと codec


@menu
* Unicode オブジェクト:: 
* 組み込み codec (built-in codec): 組み込み codec built-in codec. 
* メソッドおよびスロット関数 (slot function): メソッドおよびスロット関数 slot function. 
* PyUnicodeWriter:: 
* Deprecated API: Deprecated API<2>. 

@end menu

@node Unicode オブジェクト,組み込み codec built-in codec,,Unicode オブジェクトと codec
@anchor{c-api/unicode unicode-objects}@anchor{5356}
@subsubsection Unicode オブジェクト


Python3.3 の 
@geindex Python Enhancement Proposals; PEP 393
PEP 393@footnote{https://peps.python.org/pep-0393/} 実装から、メモリ効率を維持しながらUnicode文字の完全な範囲を扱えるように、Unicodeオブジェクトは内部的に多様な表現形式を用いています。すべてのコードポイントが128、256または65536以下の文字列に対して特別なケースが存在しますが、それ以外ではコードポイントは1114112以下 (これはすべてのUnicode範囲です) でなければなりません。

UTF-8 representation is created on demand and cached in the Unicode object.

@cartouche
@quotation 注釈 
The @ref{3e0,,Py_UNICODE} representation has been removed since Python 3.12
with deprecated APIs.
See 
@geindex Python Enhancement Proposals; PEP 623
PEP 623@footnote{https://peps.python.org/pep-0623/} for more information.
@end quotation
@end cartouche

@menu
* Unicode 型:: 
* Unicode 文字プロパティ:: 
* Unicode 文字列の生成とアクセス:: 
* ロケールエンコーディング:: 
* ファイルシステムエンコーディング:: 
* wchar_t サポート:: 

@end menu

@node Unicode 型,Unicode 文字プロパティ,,Unicode オブジェクト
@anchor{c-api/unicode unicode-type}@anchor{5357}
@subsubsection Unicode 型


以下は Python の Unicode 実装に用いられている基本 Unicode オブジェクト型です:

@geindex PyUnicode_Type (C var)
@anchor{c-api/unicode c PyUnicode_Type}@anchor{511b}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyUnicode_Type
` 次に属します: @ref{775,,Stable ABI}.'
This instance of @ref{c9c,,PyTypeObject} represents the Python Unicode type.
It is exposed to Python code as @ref{169,,str}.
@end deffn

@geindex PyUnicodeIter_Type (C var)
@anchor{c-api/unicode c PyUnicodeIter_Type}@anchor{50ec}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyUnicodeIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
This instance of @ref{c9c,,PyTypeObject} represents the Python Unicode
iterator type. It is used to iterate over Unicode string objects.
@end deffn

@geindex Py_UCS4 (C type)
@geindex Py_UCS2 (C type)
@geindex Py_UCS1 (C type)
@anchor{c-api/unicode c Py_UCS4}@anchor{33d}
@deffn {C のデータ型} type Py_UCS4
@anchor{c-api/unicode c Py_UCS2}@anchor{138c}
@deffnx {C のデータ型} type Py_UCS2
@anchor{c-api/unicode c Py_UCS1}@anchor{138b}
@deffnx {C のデータ型} type Py_UCS1
` 次に属します: @ref{775,,Stable ABI}.'
これらの型は、それぞれ、32ビット、16ビット、そして8ビットの文字を保持するのに充分な幅を持つ符号なしの整数型のtypedefです。単一のUnicode文字を扱う場合は、 @ref{33d,,Py_UCS4} を用いてください。


Added in version 3.3.

@end deffn

@geindex PyASCIIObject (C type)
@geindex PyCompactUnicodeObject (C type)
@geindex PyUnicodeObject (C type)
@anchor{c-api/unicode c PyASCIIObject}@anchor{138d}
@deffn {C のデータ型} type PyASCIIObject
@anchor{c-api/unicode c PyCompactUnicodeObject}@anchor{138e}
@deffnx {C のデータ型} type PyCompactUnicodeObject
@anchor{c-api/unicode c PyUnicodeObject}@anchor{997}
@deffnx {C のデータ型} type PyUnicodeObject

これらの @ref{5df,,PyObject} のサブタイプは Python Unicode オブジェクトを表現します。
Unicode オブジェクトを扱う全ての API 関数は @ref{5df,,PyObject} へのポインタを受け取って PyObject へのポインタを返すので、ほとんどの場合、これらの型を直接使うべきではありません。


Added in version 3.3.


The structure of a particular object can be determined using the following
macros.
The macros cannot fail; their behavior is undefined if their argument
is not a Python Unicode object.

@geindex PyUnicode_IS_COMPACT (C macro)
@anchor{c-api/unicode c PyUnicode_IS_COMPACT}@anchor{5358}
@deffn {C のマクロ} PyUnicode_IS_COMPACT (o)

True if `o' uses the @ref{138e,,PyCompactUnicodeObject} structure.


Added in version 3.3.

@end deffn

@geindex PyUnicode_IS_COMPACT_ASCII (C macro)
@anchor{c-api/unicode c PyUnicode_IS_COMPACT_ASCII}@anchor{5359}
@deffn {C のマクロ} PyUnicode_IS_COMPACT_ASCII (o)

True if `o' uses the @ref{138d,,PyASCIIObject} structure.


Added in version 3.3.

@end deffn
@end deffn

The following APIs are C macros and static inlined functions for fast checks and
access to internal read-only data of Unicode objects:

@geindex PyUnicode_Check (C function)
@anchor{c-api/unicode c PyUnicode_Check}@anchor{535a}
@deffn {C の関数} int PyUnicode_Check (PyObject *obj)

オブジェクト `obj' が Unicode オブジェクトか Unicode 型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyUnicode_CheckExact (C function)
@anchor{c-api/unicode c PyUnicode_CheckExact}@anchor{535b}
@deffn {C の関数} int PyUnicode_CheckExact (PyObject *obj)

オブジェクト `obj' が Unicode オブジェクトだがサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyUnicode_GET_LENGTH (C function)
@anchor{c-api/unicode c PyUnicode_GET_LENGTH}@anchor{ab1}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_GET_LENGTH (PyObject *unicode)

Unicode 文字列のコードポイントでの長さを返します。
`unicode' は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。


Added in version 3.3.

@end deffn

@geindex PyUnicode_1BYTE_DATA (C function)
@geindex PyUnicode_2BYTE_DATA (C function)
@geindex PyUnicode_4BYTE_DATA (C function)
@anchor{c-api/unicode c PyUnicode_1BYTE_DATA}@anchor{1392}
@deffn {C の関数} @ref{138b,,Py_UCS1} *PyUnicode_1BYTE_DATA (PyObject *unicode)
@anchor{c-api/unicode c PyUnicode_2BYTE_DATA}@anchor{1393}
@deffnx {C の関数} @ref{138c,,Py_UCS2} *PyUnicode_2BYTE_DATA (PyObject *unicode)
@anchor{c-api/unicode c PyUnicode_4BYTE_DATA}@anchor{1394}
@deffnx {C の関数} @ref{33d,,Py_UCS4} *PyUnicode_4BYTE_DATA (PyObject *unicode)

文字に直接アクセスするために、 UCS1, UCS2, UCS4 のいずれかの整数型にキャストされた正統な表現形式へのポインタを返します。
正統な表現が適正な文字サイズになっているかどうかのチェックはしません;
@ref{1395,,PyUnicode_KIND()} を使って正しい関数を選んでください。


Added in version 3.3.

@end deffn

@geindex PyUnicode_1BYTE_KIND (C macro)
@geindex PyUnicode_2BYTE_KIND (C macro)
@geindex PyUnicode_4BYTE_KIND (C macro)
@anchor{c-api/unicode c PyUnicode_1BYTE_KIND}@anchor{1396}
@deffn {C のマクロ} PyUnicode_1BYTE_KIND
@anchor{c-api/unicode c PyUnicode_2BYTE_KIND}@anchor{1397}
@deffnx {C のマクロ} PyUnicode_2BYTE_KIND
@anchor{c-api/unicode c PyUnicode_4BYTE_KIND}@anchor{1398}
@deffnx {C のマクロ} PyUnicode_4BYTE_KIND

@ref{1395,,PyUnicode_KIND()} マクロの返り値です。


Added in version 3.3.



バージョン 3.12 で変更: @code{PyUnicode_WCHAR_KIND} は削除されました。

@end deffn

@geindex PyUnicode_KIND (C function)
@anchor{c-api/unicode c PyUnicode_KIND}@anchor{1395}
@deffn {C の関数} int PyUnicode_KIND (PyObject *unicode)

この Unicode がデータを保存するのに1文字あたり何バイト使っているかを示す PyUnicode 種別の定数 (上を読んでください) のうち1つを返します。
`unicode' は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。


Added in version 3.3.

@end deffn

@geindex PyUnicode_DATA (C function)
@anchor{c-api/unicode c PyUnicode_DATA}@anchor{1391}
@deffn {C の関数} void *PyUnicode_DATA (PyObject *unicode)

生の Unicode バッファへの void ポインタを返します。
`unicode' は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。


Added in version 3.3.

@end deffn

@geindex PyUnicode_WRITE (C function)
@anchor{c-api/unicode c PyUnicode_WRITE}@anchor{139b}
@deffn {C の関数} void PyUnicode_WRITE (int kind, void *data, Py_ssize_t index, Py_UCS4 value)

Write the code point `value' to the given zero-based `index' in a string.

The `kind' value and `data' pointer must have been obtained from a
string using @ref{1395,,PyUnicode_KIND()} and @ref{1391,,PyUnicode_DATA()}
respectively. You must hold a reference to that string while calling
@code{PyUnicode_WRITE()}. All requirements of
@ref{138a,,PyUnicode_WriteChar()} also apply.

The function performs no checks for any of its requirements,
and is intended for usage in loops.


Added in version 3.3.

@end deffn

@geindex PyUnicode_READ (C function)
@anchor{c-api/unicode c PyUnicode_READ}@anchor{1399}
@deffn {C の関数} @ref{33d,,Py_UCS4} PyUnicode_READ (int kind, void *data, Py_ssize_t index)

正統な表現形式となっている (@ref{1391,,PyUnicode_DATA()} で取得した) `data' からコードポイントを読み取ります。
チェックや事前確認のマクロ呼び出しは一切行われません。


Added in version 3.3.

@end deffn

@geindex PyUnicode_READ_CHAR (C function)
@anchor{c-api/unicode c PyUnicode_READ_CHAR}@anchor{139a}
@deffn {C の関数} @ref{33d,,Py_UCS4} PyUnicode_READ_CHAR (PyObject *unicode, Py_ssize_t index)

Unicode オブジェクト `unicode' から文字を読み取ります。
この Unicode オブジェクトは "正統な" 表現形式でなければなりません。
何度も連続して読み取る場合には、このマクロは @ref{1399,,PyUnicode_READ()} よりも非効率的です。


Added in version 3.3.

@end deffn

@geindex PyUnicode_MAX_CHAR_VALUE (C function)
@anchor{c-api/unicode c PyUnicode_MAX_CHAR_VALUE}@anchor{139c}
@deffn {C の関数} @ref{33d,,Py_UCS4} PyUnicode_MAX_CHAR_VALUE (PyObject *unicode)

`unicode' に基づいて他の文字列を作るのに適した最大のコードポイントを返します。
この Unicode オブジェクトは "正統な" 表現形式でなければなりません。
この値は常に概算値ですが、文字列全体を調べるよりも効率的です。


Added in version 3.3.

@end deffn

@geindex PyUnicode_IsIdentifier (C function)
@anchor{c-api/unicode c PyUnicode_IsIdentifier}@anchor{1d86}
@deffn {C の関数} int PyUnicode_IsIdentifier (PyObject *unicode)
` 次に属します: @ref{775,,Stable ABI}.'
文字列が、 @ref{22a0,,Names (identifiers and keywords)} 節の言語定義における有効な識別子であれば @code{1} を返します。それ以外の場合は @code{0} を返します。


バージョン 3.9 で変更: The function does not call @ref{b7a,,Py_FatalError()} anymore if the string
is not ready.

@end deffn

@geindex PyUnicode_IS_ASCII (C function)
@anchor{c-api/unicode c PyUnicode_IS_ASCII}@anchor{535c}
@deffn {C の関数} unsigned int PyUnicode_IS_ASCII (PyObject *unicode)

Return true if the string only contains ASCII characters.
Equivalent to @ref{ce9,,str.isascii()}.


Added in version 3.2.

@end deffn

@node Unicode 文字プロパティ,Unicode 文字列の生成とアクセス,Unicode 型,Unicode オブジェクト
@anchor{c-api/unicode unicode-character-properties}@anchor{535d}
@subsubsection Unicode 文字プロパティ


Unicode は数多くの異なる文字プロパティ (character property) を提供しています。よく使われる文字プロパティは、以下のマクロで利用できます。これらのマクロは Python の設定に応じて、各々 C の関数に対応付けられています。

@geindex Py_UNICODE_ISSPACE (C function)
@anchor{c-api/unicode c Py_UNICODE_ISSPACE}@anchor{1cc5}
@deffn {C の関数} int Py_UNICODE_ISSPACE (Py_UCS4 ch)

`ch' が空白文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISLOWER (C function)
@anchor{c-api/unicode c Py_UNICODE_ISLOWER}@anchor{535e}
@deffn {C の関数} int Py_UNICODE_ISLOWER (Py_UCS4 ch)

`ch' が小文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISUPPER (C function)
@anchor{c-api/unicode c Py_UNICODE_ISUPPER}@anchor{535f}
@deffn {C の関数} int Py_UNICODE_ISUPPER (Py_UCS4 ch)

`ch' が大文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISTITLE (C function)
@anchor{c-api/unicode c Py_UNICODE_ISTITLE}@anchor{5360}
@deffn {C の関数} int Py_UNICODE_ISTITLE (Py_UCS4 ch)

`ch' がタイトルケース文字 (titlecase character) かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISLINEBREAK (C function)
@anchor{c-api/unicode c Py_UNICODE_ISLINEBREAK}@anchor{5361}
@deffn {C の関数} int Py_UNICODE_ISLINEBREAK (Py_UCS4 ch)

`ch' が改行文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISDECIMAL (C function)
@anchor{c-api/unicode c Py_UNICODE_ISDECIMAL}@anchor{5362}
@deffn {C の関数} int Py_UNICODE_ISDECIMAL (Py_UCS4 ch)

`ch' が decimal 文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISDIGIT (C function)
@anchor{c-api/unicode c Py_UNICODE_ISDIGIT}@anchor{5363}
@deffn {C の関数} int Py_UNICODE_ISDIGIT (Py_UCS4 ch)

`ch' が digit 文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISNUMERIC (C function)
@anchor{c-api/unicode c Py_UNICODE_ISNUMERIC}@anchor{5364}
@deffn {C の関数} int Py_UNICODE_ISNUMERIC (Py_UCS4 ch)

`ch' が数字 (numeric) 文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISALPHA (C function)
@anchor{c-api/unicode c Py_UNICODE_ISALPHA}@anchor{5365}
@deffn {C の関数} int Py_UNICODE_ISALPHA (Py_UCS4 ch)

`ch' がアルファベット文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISALNUM (C function)
@anchor{c-api/unicode c Py_UNICODE_ISALNUM}@anchor{5366}
@deffn {C の関数} int Py_UNICODE_ISALNUM (Py_UCS4 ch)

`ch' が英数文字かどうかに応じて @code{1} または @code{0} を返します。
@end deffn

@geindex Py_UNICODE_ISPRINTABLE (C function)
@anchor{c-api/unicode c Py_UNICODE_ISPRINTABLE}@anchor{5367}
@deffn {C の関数} int Py_UNICODE_ISPRINTABLE (Py_UCS4 ch)

Return @code{1} or @code{0} depending on whether `ch' is a printable character,
in the sense of @ref{fd8,,str.isprintable()}.
@end deffn

以下の API は、高速に直接文字変換を行うために使われます:

@geindex Py_UNICODE_TOLOWER (C function)
@anchor{c-api/unicode c Py_UNICODE_TOLOWER}@anchor{5368}
@deffn {C の関数} @ref{33d,,Py_UCS4} Py_UNICODE_TOLOWER (Py_UCS4 ch)

`ch' を小文字に変換したものを返します。
@end deffn

@geindex Py_UNICODE_TOUPPER (C function)
@anchor{c-api/unicode c Py_UNICODE_TOUPPER}@anchor{5369}
@deffn {C の関数} @ref{33d,,Py_UCS4} Py_UNICODE_TOUPPER (Py_UCS4 ch)

`ch' を大文字に変換したものを返します。
@end deffn

@geindex Py_UNICODE_TOTITLE (C function)
@anchor{c-api/unicode c Py_UNICODE_TOTITLE}@anchor{536a}
@deffn {C の関数} @ref{33d,,Py_UCS4} Py_UNICODE_TOTITLE (Py_UCS4 ch)

`ch' をタイトルケース文字に変換したものを返します。
@end deffn

@geindex Py_UNICODE_TODECIMAL (C function)
@anchor{c-api/unicode c Py_UNICODE_TODECIMAL}@anchor{536b}
@deffn {C の関数} int Py_UNICODE_TODECIMAL (Py_UCS4 ch)

Return the character `ch' converted to a decimal positive integer.  Return
@code{-1} if this is not possible.  This function does not raise exceptions.
@end deffn

@geindex Py_UNICODE_TODIGIT (C function)
@anchor{c-api/unicode c Py_UNICODE_TODIGIT}@anchor{536c}
@deffn {C の関数} int Py_UNICODE_TODIGIT (Py_UCS4 ch)

Return the character `ch' converted to a single digit integer. Return @code{-1} if
this is not possible.  This function does not raise exceptions.
@end deffn

@geindex Py_UNICODE_TONUMERIC (C function)
@anchor{c-api/unicode c Py_UNICODE_TONUMERIC}@anchor{536d}
@deffn {C の関数} double Py_UNICODE_TONUMERIC (Py_UCS4 ch)

`ch' を double に変換したものを返します。不可能ならば @code{-1.0} を返します。この関数は例外を送出しません。
@end deffn

これらの API はサロゲートにも使えます:

@geindex Py_UNICODE_IS_SURROGATE (C function)
@anchor{c-api/unicode c Py_UNICODE_IS_SURROGATE}@anchor{536e}
@deffn {C の関数} int Py_UNICODE_IS_SURROGATE (Py_UCS4 ch)

`ch' がサロゲートかどうか (@code{0xD800 <= ch <= 0xDFFF}) をチェックします。
@end deffn

@geindex Py_UNICODE_IS_HIGH_SURROGATE (C function)
@anchor{c-api/unicode c Py_UNICODE_IS_HIGH_SURROGATE}@anchor{536f}
@deffn {C の関数} int Py_UNICODE_IS_HIGH_SURROGATE (Py_UCS4 ch)

`ch' が上位サロゲートかどうか (@code{0xD800 <= ch <= 0xDBFF}) をチェックします。
@end deffn

@geindex Py_UNICODE_IS_LOW_SURROGATE (C function)
@anchor{c-api/unicode c Py_UNICODE_IS_LOW_SURROGATE}@anchor{5370}
@deffn {C の関数} int Py_UNICODE_IS_LOW_SURROGATE (Py_UCS4 ch)

`ch' が下位サロゲートかどうか (@code{0xDC00 <= ch <= 0xDFFF}) をチェックします。
@end deffn

@geindex Py_UNICODE_HIGH_SURROGATE (C function)
@anchor{c-api/unicode c Py_UNICODE_HIGH_SURROGATE}@anchor{5371}
@deffn {C の関数} @ref{33d,,Py_UCS4} Py_UNICODE_HIGH_SURROGATE (Py_UCS4 ch)

Return the high UTF-16 surrogate (@code{0xD800} to @code{0xDBFF}) for a Unicode
code point in the range @code{[0x10000; 0x10FFFF]}.
@end deffn

@geindex Py_UNICODE_LOW_SURROGATE (C function)
@anchor{c-api/unicode c Py_UNICODE_LOW_SURROGATE}@anchor{5372}
@deffn {C の関数} @ref{33d,,Py_UCS4} Py_UNICODE_LOW_SURROGATE (Py_UCS4 ch)

Return the low UTF-16 surrogate (@code{0xDC00} to @code{0xDFFF}) for a Unicode
code point in the range @code{[0x10000; 0x10FFFF]}.
@end deffn

@geindex Py_UNICODE_JOIN_SURROGATES (C function)
@anchor{c-api/unicode c Py_UNICODE_JOIN_SURROGATES}@anchor{5373}
@deffn {C の関数} @ref{33d,,Py_UCS4} Py_UNICODE_JOIN_SURROGATES (Py_UCS4 high, Py_UCS4 low)

Join two surrogate code points and return a single @ref{33d,,Py_UCS4} value.
`high' and `low' are respectively the leading and trailing surrogates in a
surrogate pair. `high' must be in the range @code{[0xD800; 0xDBFF]} and `low' must
be in the range @code{[0xDC00; 0xDFFF]}.
@end deffn

@node Unicode 文字列の生成とアクセス,ロケールエンコーディング,Unicode 文字プロパティ,Unicode オブジェクト
@anchor{c-api/unicode creating-and-accessing-unicode-strings}@anchor{5374}
@subsubsection Unicode 文字列の生成とアクセス


Unicode オブジェクトを生成したり、Unicode のシーケンスとしての基本的なプロパティにアクセスしたりするには、以下の API を使ってください:

@geindex PyUnicode_New (C function)
@anchor{c-api/unicode c PyUnicode_New}@anchor{aa9}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_New (Py_ssize_t size, Py_UCS4 maxchar)
`戻り値: 新しい参照。'
新しい Unicode オブジェクトを生成します。
`maxchar' は文字列に並べるコードポイントの正しい最大値にすべきです。
その値は概算値として 127, 255, 65535, 1114111 の一番近い値に切り上げられます。

On error, set an exception and return @code{NULL}.

After creation, the string can be filled by @ref{138a,,PyUnicode_WriteChar()},
@ref{ab2,,PyUnicode_CopyCharacters()}, @ref{13a5,,PyUnicode_Fill()},
@ref{139b,,PyUnicode_WRITE()} or similar.
Since strings are supposed to be immutable, take care to not “use” the
result while it is being modified. In particular, before it's filled
with its final contents, a string:


@itemize -

@item 
must not be hashed,

@item 
must not be @ref{a99,,converted to UTF-8},
or another non-"canonical" representation,

@item 
must not have its reference count changed,

@item 
must not be shared with code that might do one of the above.
@end itemize

This list is not exhaustive. Avoiding these uses is your responsibility;
Python does not always check these requirements.

To avoid accidentally exposing a partially-written string object, prefer
using the @ref{3b3,,PyUnicodeWriter} API, or one of the @code{PyUnicode_From*}
functions below.


Added in version 3.3.

@end deffn

@geindex PyUnicode_FromKindAndData (C function)
@anchor{c-api/unicode c PyUnicode_FromKindAndData}@anchor{138f}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromKindAndData (int kind, const void *buffer, Py_ssize_t size)
`戻り値: 新しい参照。'
与えられた `kind' (取り得る値は @ref{1396,,PyUnicode_1BYTE_KIND} などの @ref{1395,,PyUnicode_KIND()} が返す値です) の Unicode オブジェクトを生成します。
`buffer' は、与えられた kind に従って1文字あたり 1, 2, 4 バイトのいずれかを単位として、長さ `size' の配列へのポインタでなければなりません。

If necessary, the input `buffer' is copied and transformed into the
canonical representation.  For example, if the `buffer' is a UCS4 string
(@ref{1398,,PyUnicode_4BYTE_KIND}) and it consists only of codepoints in
the UCS1 range, it will be transformed into UCS1
(@ref{1396,,PyUnicode_1BYTE_KIND}).


Added in version 3.3.

@end deffn

@geindex PyUnicode_FromStringAndSize (C function)
@anchor{c-api/unicode c PyUnicode_FromStringAndSize}@anchor{5113}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromStringAndSize (const char *str, Py_ssize_t size)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode object from the char buffer `str'.  The bytes will be
interpreted as being UTF-8 encoded.  The buffer is copied into the new
object.
The return value might be a shared object, i.e. modification of the data is
not allowed.

This function raises @ref{795,,SystemError} when:


@itemize *

@item 
`size' < 0,

@item 
`str' is @code{NULL} and `size' > 0
@end itemize


バージョン 3.12 で変更: `str' == @code{NULL} with `size' > 0 is not allowed anymore.

@end deffn

@geindex PyUnicode_FromString (C function)
@anchor{c-api/unicode c PyUnicode_FromString}@anchor{5112}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromString (const char *str)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
UTF-8 エンコードされたnull終端のchar 型バッファ `str' から Unicode オブジェクトを生成します。
@end deffn

@geindex PyUnicode_FromFormat (C function)
@anchor{c-api/unicode c PyUnicode_FromFormat}@anchor{62b}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromFormat (const char *format, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Take a C @code{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.

一つの変換指定子は 2 またはそれ以上の文字を含み、その構成要素は以下からなりますが、示した順に出現しなければなりません:


@enumerate 

@item 
指定子の開始を示す文字 @code{'%'} 。

@item 
変換フラグ (オプション)。一部の変換型の結果に影響します。

@item 
Minimum field width (optional).
If specified as an @code{'*'} (asterisk), the actual width is given in the
next argument, which must be of type int, and the object to
convert comes after the minimum field width and optional precision.

@item 
Precision (optional), given as a @code{'.'} (dot) followed by the precision.
If specified as @code{'*'} (an asterisk), the actual precision is given in
the next argument, which must be of type int, and the value to
convert comes after the precision.

@item 
精度長変換子 (オプション)。

@item 
変換型。
@end enumerate

変換フラグ文字を以下に示します:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@item

@code{0}

@tab

数値型に対してゼロによるパディングを行います。

@item

@code{-}

@tab

The converted value is left adjusted (overrides the @code{0}
flag if both are given).

@end multitable


The length modifiers for following integer conversions (@code{d}, @code{i},
@code{o}, @code{u}, @code{x}, or @code{X}) specify the type of the argument
(int by default):


@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

修飾子

@tab

型

@item

@code{l}

@tab

long または unsigned long

@item

@code{ll}

@tab

long long または unsigned long long

@item

@code{j}

@tab

@code{intmax_t} or @code{uintmax_t}

@item

@code{z}

@tab

@code{size_t} or @code{ssize_t}

@item

@code{t}

@tab

@code{ptrdiff_t}

@end multitable


The length modifier @code{l} for following conversions @code{s} or @code{V} specify
that the type of the argument is const wchar_t*.

The conversion specifiers are:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Conversion Specifier

@tab

型

@tab

備考

@item

@code{%}

@tab

`n/a'

@tab

The literal @code{%} character.

@item

@code{d}, @code{i}

@tab

Specified by the length modifier

@tab

The decimal representation of a signed C integer.

@item

@code{u}

@tab

Specified by the length modifier

@tab

The decimal representation of an unsigned C integer.

@item

@code{o}

@tab

Specified by the length modifier

@tab

The octal representation of an unsigned C integer.

@item

@code{x}

@tab

Specified by the length modifier

@tab

The hexadecimal representation of an unsigned C integer (lowercase).

@item

@code{X}

@tab

Specified by the length modifier

@tab

The hexadecimal representation of an unsigned C integer (uppercase).

@item

@code{c}

@tab

int

@tab

A single character.

@item

@code{s}

@tab

const char* または const wchar_t*

@tab

null で終端された C の文字列。

@item

@code{p}

@tab

const void*

@tab

C ポインタの 16 進表記。@code{printf("%p")} とほとんど同じですが、プラットフォームにおける @code{printf} の定義に関わりなく先頭にリテラル @code{0x} が付きます。

@item

@code{A}

@tab

@ref{5df,,PyObject}*

@tab

@ref{15ff,,ascii()} の戻り値。

@item

@code{U}

@tab

@ref{5df,,PyObject}*

@tab

Unicode オブジェクト。

@item

@code{V}

@tab

@ref{5df,,PyObject}*, const char* or const wchar_t*

@tab

A Unicode object (which may be @code{NULL}) and a null-terminated
C character array as a second parameter (which will be used,
if the first parameter is @code{NULL}).

@item

@code{S}

@tab

@ref{5df,,PyObject}*

@tab

@ref{1231,,PyObject_Str()} の戻り値。

@item

@code{R}

@tab

@ref{5df,,PyObject}*

@tab

@ref{1230,,PyObject_Repr()} の戻り値。

@item

@code{T}

@tab

@ref{5df,,PyObject}*

@tab

Get the fully qualified name of an object type;
call @ref{616,,PyType_GetFullyQualifiedName()}.

@item

@code{#T}

@tab

@ref{5df,,PyObject}*

@tab

Similar to @code{T} format, but use a colon (@code{:}) as separator between
the module name and the qualified name.

@item

@code{N}

@tab

@ref{c9c,,PyTypeObject}*

@tab

Get the fully qualified name of a type;
call @ref{616,,PyType_GetFullyQualifiedName()}.

@item

@code{#N}

@tab

@ref{c9c,,PyTypeObject}*

@tab

Similar to @code{N} format, but use a colon (@code{:}) as separator between
the module name and the qualified name.

@end multitable


@cartouche
@quotation 注釈 
The width formatter unit is number of characters rather than bytes.
The precision formatter unit is number of bytes or @code{wchar_t}
items (if the length modifier @code{l} is used) for @code{"%s"} and
@code{"%V"} (if the @code{PyObject*} argument is @code{NULL}), and a number of
characters for @code{"%A"}, @code{"%U"}, @code{"%S"}, @code{"%R"} and @code{"%V"}
(if the @code{PyObject*} argument is not @code{NULL}).
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
Unlike to C @code{printf()} the @code{0} flag has effect even when
a precision is given for integer conversions (@code{d}, @code{i}, @code{u}, @code{o},
@code{x}, or @code{X}).
@end quotation
@end cartouche


バージョン 3.2 で変更: @code{"%lld"}, @code{"%llu"} のサポートが追加されました。



バージョン 3.3 で変更: @code{"%li"}, @code{"%lli"}, @code{"%zi"} のサポートが追加されました。



バージョン 3.4 で変更: @code{"%s"}, @code{"%A"}, @code{"%U"}, @code{"%V"}, @code{"%S"}, @code{"%R"} での幅フォーマッタおよび精度フォーマッタのサポートが追加されました。



バージョン 3.12 で変更: Support for conversion specifiers @code{o} and @code{X}.
Support for length modifiers @code{j} and @code{t}.
Length modifiers are now applied to all integer conversions.
Length modifier @code{l} is now applied to conversion specifiers @code{s} and @code{V}.
Support for variable width and precision @code{*}.
Support for flag @code{-}.

An unrecognized format character now sets a @ref{795,,SystemError}.
In previous versions it caused all the rest of the format string to be
copied as-is to the result string, and any extra arguments discarded.



バージョン 3.13 で変更: Support for @code{%T}, @code{%#T}, @code{%N} and @code{%#N} formats added.

@end deffn

@geindex PyUnicode_FromFormatV (C function)
@anchor{c-api/unicode c PyUnicode_FromFormatV}@anchor{794}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromFormatV (const char *format, va_list vargs)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
ちょうど２つの引数を取ることを除いて、 @ref{62b,,PyUnicode_FromFormat()} と同じです。
@end deffn

@geindex PyUnicode_FromObject (C function)
@anchor{c-api/unicode c PyUnicode_FromObject}@anchor{5110}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromObject (PyObject *obj)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
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 a new @ref{5e2,,strong reference} to the object.

Unicode やそのサブタイプ以外のオブジェクトでは @ref{198,,TypeError} が引き起こされます。
@end deffn

@geindex PyUnicode_FromOrdinal (C function)
@anchor{c-api/unicode c PyUnicode_FromOrdinal}@anchor{5111}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromOrdinal (int ordinal)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode Object from the given Unicode code point `ordinal'.

The ordinal must be in @code{range(0x110000)}. A @ref{2ec,,ValueError} is
raised in the case it is not.
@end deffn

@geindex PyUnicode_FromEncodedObject (C function)
@anchor{c-api/unicode c PyUnicode_FromEncodedObject}@anchor{510f}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromEncodedObject (PyObject *obj, const char *encoding, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
エンコードされている `obj' を Unicode オブジェクトにデコードします。

@ref{192,,bytes} や @ref{344,,bytearray} や他の @ref{193,,bytes-like objects} は、与えられた `encoding' に従ってデコードされ、 `errors' で定義されたエラーハンドリングが使われます。
これらの引数は両方とも @code{NULL} にでき、その場合この API はデフォルト値を使います (詳しことは @ref{5375,,組み込み codec (built-in codec)} を参照してください)。

その他のUnicodeオブジェクトを含むオブジェクトは @ref{198,,TypeError} 例外を引き起こします。

この API は、エラーが生じたときには @code{NULL} を返します。呼び出し側は返されたオブジェクトに対し参照カウンタを 1 つ減らす (decref) する責任があります。
@end deffn

@geindex PyUnicode_Append (C function)
@anchor{c-api/unicode c PyUnicode_Append}@anchor{50f4}
@deffn {C の関数} void PyUnicode_Append (PyObject **p_left, PyObject *right)
` 次に属します: @ref{775,,Stable ABI}.'
Append the string `right' to the end of `p_left'.
`p_left' must point to a @ref{5e2,,strong reference} to a Unicode object;
@code{PyUnicode_Append()} releases ("steals") this reference.

On error, set `*p_left' to @code{NULL} and set an exception.

On success, set `*p_left' to a new strong reference to the result.
@end deffn

@geindex PyUnicode_AppendAndDel (C function)
@anchor{c-api/unicode c PyUnicode_AppendAndDel}@anchor{50f5}
@deffn {C の関数} void PyUnicode_AppendAndDel (PyObject **p_left, PyObject *right)
` 次に属します: @ref{775,,Stable ABI}.'
The function is similar to @ref{50f4,,PyUnicode_Append()}, with the only
difference being that it decrements the reference count of `right' by one.
@end deffn

@geindex PyUnicode_BuildEncodingMap (C function)
@anchor{c-api/unicode c PyUnicode_BuildEncodingMap}@anchor{1a62}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_BuildEncodingMap (PyObject *string)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a mapping suitable for decoding a custom single-byte encoding.
Given a Unicode string `string' of up to 256 characters representing an encoding
table, returns either a compact internal mapping object or a dictionary
mapping character ordinals to byte values. Raises a @ref{198,,TypeError} and
return @code{NULL} on invalid input.


Added in version 3.2.

@end deffn

@geindex PyUnicode_GetDefaultEncoding (C function)
@anchor{c-api/unicode c PyUnicode_GetDefaultEncoding}@anchor{5114}
@deffn {C の関数} const char *PyUnicode_GetDefaultEncoding (void)
` 次に属します: @ref{775,,Stable ABI}.'
Return the name of the default string encoding, @code{"utf-8"}.
See @ref{4916,,sys.getdefaultencoding()}.

The returned string does not need to be freed, and is valid
until interpreter shutdown.
@end deffn

@geindex PyUnicode_GetLength (C function)
@anchor{c-api/unicode c PyUnicode_GetLength}@anchor{ab0}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_GetLength (PyObject *unicode)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Unicode オブジェクトの長さをコードポイントで返します。

On error, set an exception and return @code{-1}.


Added in version 3.3.

@end deffn

@geindex PyUnicode_CopyCharacters (C function)
@anchor{c-api/unicode c PyUnicode_CopyCharacters}@anchor{ab2}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_CopyCharacters (PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)

ある Unicode オブジェクトから他へ文字をコピーします。
この関数は必要なときに文字変換を行い、可能な場合は @code{memcpy()} へ差し戻します。
失敗のときには @code{-1} を返し、例外を設定します。そうでない場合は、コピーした文字数を返します。

The string must not have been “used” yet.
See @ref{aa9,,PyUnicode_New()} for details.


Added in version 3.3.

@end deffn

@geindex PyUnicode_Resize (C function)
@anchor{c-api/unicode c PyUnicode_Resize}@anchor{5116}
@deffn {C の関数} int PyUnicode_Resize (PyObject **unicode, Py_ssize_t length);
` 次に属します: @ref{775,,Stable ABI}.'
Resize a Unicode object `*unicode' to the new `length' in code points.

Try to resize the string in place (which is usually faster than allocating
a new string and copying characters), or create a new string.

`*unicode' is modified to point to the new (resized) object and @code{0} is
returned on success. Otherwise, @code{-1} is returned and an exception is set,
and `*unicode' is left untouched.

The function doesn't check string content, the result may not be a
string in canonical representation.
@end deffn

@geindex PyUnicode_Fill (C function)
@anchor{c-api/unicode c PyUnicode_Fill}@anchor{13a5}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_Fill (PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)

文字列を文字で埋めます: @code{unicode[start:start+length]} で `fill_char' を埋めることになります。

`fill_char' が文字列の最大文字よりも大きい場合や、文字列2つ以上の参照を持ってた場合は失敗します。

The string must not have been “used” yet.
See @ref{aa9,,PyUnicode_New()} for details.

書き込んだ文字数を返すか、失敗のときには @code{-1} を返し例外を送出します。


Added in version 3.3.

@end deffn

@geindex PyUnicode_WriteChar (C function)
@anchor{c-api/unicode c PyUnicode_WriteChar}@anchor{138a}
@deffn {C の関数} int PyUnicode_WriteChar (PyObject *unicode, Py_ssize_t index, Py_UCS4 character)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Write a `character' to the string `unicode' at the zero-based `index'.
Return @code{0} on success, @code{-1} on error with an exception set.

This function checks that `unicode' is a Unicode object, that the index is
not out of bounds, and that the object's reference count is one.
See @ref{139b,,PyUnicode_WRITE()} for a version that skips these checks,
making them your responsibility.

The string must not have been “used” yet.
See @ref{aa9,,PyUnicode_New()} for details.


Added in version 3.3.

@end deffn

@geindex PyUnicode_ReadChar (C function)
@anchor{c-api/unicode c PyUnicode_ReadChar}@anchor{1389}
@deffn {C の関数} @ref{33d,,Py_UCS4} PyUnicode_ReadChar (PyObject *unicode, Py_ssize_t index)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
文字列から文字を読み取ります。
エラーチェックを行わない @ref{139a,,PyUnicode_READ_CHAR()} とは対照的に、この関数は `unicode' が Unicode オブジェクトであること、インデックスが範囲内であることをチェックします。

Return character on success, @code{-1} on error with an exception set.


Added in version 3.3.

@end deffn

@geindex PyUnicode_Substring (C function)
@anchor{c-api/unicode c PyUnicode_Substring}@anchor{ab3}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Substring (PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Return a substring of `unicode', from character index `start' (included) to
character index `end' (excluded).  Negative indices are not supported.
On error, set an exception and return @code{NULL}.


Added in version 3.3.

@end deffn

@geindex PyUnicode_AsUCS4 (C function)
@anchor{c-api/unicode c PyUnicode_AsUCS4}@anchor{1390}
@deffn {C の関数} @ref{33d,,Py_UCS4} *PyUnicode_AsUCS4 (PyObject *unicode, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Copy the string `unicode' into a UCS4 buffer, including a null character, if
`copy_null' is set.  Returns @code{NULL} and sets an exception on error (in
particular, a @ref{795,,SystemError} if `buflen' is smaller than the length of
`unicode').  `buffer' is returned on success.


Added in version 3.3.

@end deffn

@geindex PyUnicode_AsUCS4Copy (C function)
@anchor{c-api/unicode c PyUnicode_AsUCS4Copy}@anchor{ab8}
@deffn {C の関数} @ref{33d,,Py_UCS4} *PyUnicode_AsUCS4Copy (PyObject *unicode)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
文字列 `unicode' を @ref{e5f,,PyMem_Malloc()} でメモリ確保された新しい UCS4 型のバッファにコピーします。
これが失敗した場合は、 @code{NULL} を返し @ref{179e,,MemoryError} をセットします。
返されたバッファは必ず null コードポイントが追加されています。


Added in version 3.3.

@end deffn

@node ロケールエンコーディング,ファイルシステムエンコーディング,Unicode 文字列の生成とアクセス,Unicode オブジェクト
@anchor{c-api/unicode locale-encoding}@anchor{5376}
@subsubsection ロケールエンコーディング


現在のロケールエンコーディングはオペレーティングシステムのテキストをデコードするのに使えます。

@geindex PyUnicode_DecodeLocaleAndSize (C function)
@anchor{c-api/unicode c PyUnicode_DecodeLocaleAndSize}@anchor{dc2}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeLocaleAndSize (const char *str, Py_ssize_t length, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Decode a string from UTF-8 on Android and VxWorks, or from the current
locale encoding on other platforms. The supported
error handlers are @code{"strict"} and @code{"surrogateescape"}
(
@geindex Python Enhancement Proposals; PEP 383
PEP 383@footnote{https://peps.python.org/pep-0383/}). The decoder uses @code{"strict"} error handler if
`errors' is @code{NULL}.  `str' must end with a null character but
cannot contain embedded null characters.

Use @ref{50ff,,PyUnicode_DecodeFSDefaultAndSize()} to decode a string from
the @ref{75d,,filesystem encoding and error handler}.

This function ignores the @ref{866,,Python UTF-8 Mode}.


@subsubheading 参考


@ref{dc0,,Py_DecodeLocale()} 関数。



Added in version 3.3.



バージョン 3.7 で変更: この関数は、 Android 以外では現在のロケールエンコーディングを @code{surrogateescape} エラーハンドラで使うようになりました。
以前は、 @ref{dc0,,Py_DecodeLocale()} が @code{surrogateescape} で使われ、現在のロケールエンコーディングは @code{strict} で使われていました。

@end deffn

@geindex PyUnicode_DecodeLocale (C function)
@anchor{c-api/unicode c PyUnicode_DecodeLocale}@anchor{5101}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeLocale (const char *str, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Similar to @ref{dc2,,PyUnicode_DecodeLocaleAndSize()}, but compute the string
length using @code{strlen()}.


Added in version 3.3.

@end deffn

@geindex PyUnicode_EncodeLocale (C function)
@anchor{c-api/unicode c PyUnicode_EncodeLocale}@anchor{dc3}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_EncodeLocale (PyObject *unicode, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current
locale encoding on other platforms. The
supported error handlers are @code{"strict"} and @code{"surrogateescape"}
(
@geindex Python Enhancement Proposals; PEP 383
PEP 383@footnote{https://peps.python.org/pep-0383/}). The encoder uses @code{"strict"} error handler if
`errors' is @code{NULL}. Return a @ref{192,,bytes} object. `unicode' cannot
contain embedded null characters.

Use @ref{1e31,,PyUnicode_EncodeFSDefault()} to encode a string to the
@ref{75d,,filesystem encoding and error handler}.

This function ignores the @ref{866,,Python UTF-8 Mode}.


@subsubheading 参考


@ref{dc1,,Py_EncodeLocale()} 関数。



Added in version 3.3.



バージョン 3.7 で変更: この関数は、 Android 以外では現在のロケールエンコーディングを @code{surrogateescape} エラーハンドラで使うようになりました。
以前は、 @ref{dc1,,Py_EncodeLocale()} が @code{surrogateescape} で使われ、現在のロケールエンコーディングは @code{strict} で使われていました。

@end deffn

@node ファイルシステムエンコーディング,wchar_t サポート,ロケールエンコーディング,Unicode オブジェクト
@anchor{c-api/unicode file-system-encoding}@anchor{5377}
@subsubsection ファイルシステムエンコーディング


Functions encoding to and decoding from the @ref{75d,,filesystem encoding and error handler} (
@geindex Python Enhancement Proposals; PEP 383
PEP 383@footnote{https://peps.python.org/pep-0383/} and 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/}).

To encode file names to @ref{192,,bytes} during argument parsing, the @code{"O&"}
converter should be used, passing @code{PyUnicode_FSConverter()} as the
conversion function:

@geindex PyUnicode_FSConverter (C function)
@anchor{c-api/unicode c PyUnicode_FSConverter}@anchor{f15}
@deffn {C の関数} int PyUnicode_FSConverter (PyObject *obj, void *result)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{3d5,,PyArg_Parse* converter}: encode @ref{169,,str} objects -- obtained directly or
through the @ref{e4b,,os.PathLike} interface -- to @ref{192,,bytes} using
@ref{1e31,,PyUnicode_EncodeFSDefault()}; @ref{192,,bytes} objects are output as-is.
`result' must be an address of a C variable of type @ref{5df,,PyObject}*
(or @ref{995,,PyBytesObject}*).
On success, set the variable to a new @ref{5e2,,strong reference} to
a @ref{5343,,bytes object} which must be released
when it is no longer used and return a non-zero value
(@ref{5240,,Py_CLEANUP_SUPPORTED}).
Embedded null bytes are not allowed in the result.
On failure, return @code{0} with an exception set.

If `obj' is @code{NULL}, the function releases a strong reference
stored in the variable referred by `result' and returns @code{1}.


Added in version 3.1.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

To decode file names to @ref{169,,str} during argument parsing, the @code{"O&"}
converter should be used, passing @code{PyUnicode_FSDecoder()} as the
conversion function:

@geindex PyUnicode_FSDecoder (C function)
@anchor{c-api/unicode c PyUnicode_FSDecoder}@anchor{797}
@deffn {C の関数} int PyUnicode_FSDecoder (PyObject *obj, void *result)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{3d5,,PyArg_Parse* converter}: decode @ref{192,,bytes} objects -- obtained either
directly or indirectly through the @ref{e4b,,os.PathLike} interface -- to
@ref{169,,str} using @ref{50ff,,PyUnicode_DecodeFSDefaultAndSize()}; @ref{169,,str}
objects are output as-is.
`result' must be an address of a C variable of type @ref{5df,,PyObject}*
(or @ref{997,,PyUnicodeObject}*).
On success, set the variable to a new @ref{5e2,,strong reference} to
a @ref{5355,,Unicode object} which must be released
when it is no longer used and return a non-zero value
(@ref{5240,,Py_CLEANUP_SUPPORTED}).
Embedded null characters are not allowed in the result.
On failure, return @code{0} with an exception set.

If `obj' is @code{NULL}, release the strong reference
to the object referred to by `result' and return @code{1}.


Added in version 3.2.



バージョン 3.6 で変更: @ref{5a1,,path-like object} を受け入れるようになりました。

@end deffn

@geindex PyUnicode_DecodeFSDefaultAndSize (C function)
@anchor{c-api/unicode c PyUnicode_DecodeFSDefaultAndSize}@anchor{50ff}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeFSDefaultAndSize (const char *str, Py_ssize_t size)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Decode a string from the @ref{75d,,filesystem encoding and error handler}.

If you need to decode a string from the current locale encoding, use
@ref{dc2,,PyUnicode_DecodeLocaleAndSize()}.


@subsubheading 参考


@ref{dc0,,Py_DecodeLocale()} 関数。



バージョン 3.6 で変更: The @ref{75d,,filesystem error handler} is now used.

@end deffn

@geindex PyUnicode_DecodeFSDefault (C function)
@anchor{c-api/unicode c PyUnicode_DecodeFSDefault}@anchor{1a88}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeFSDefault (const char *str)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Decode a null-terminated string from the @ref{75d,,filesystem encoding and error handler}.

If the string length is known, use
@ref{50ff,,PyUnicode_DecodeFSDefaultAndSize()}.


バージョン 3.6 で変更: The @ref{75d,,filesystem error handler} is now used.

@end deffn

@geindex PyUnicode_EncodeFSDefault (C function)
@anchor{c-api/unicode c PyUnicode_EncodeFSDefault}@anchor{1e31}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_EncodeFSDefault (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Encode a Unicode object to the @ref{75d,,filesystem encoding and error handler}, and return @ref{192,,bytes}. Note that the resulting @ref{192,,bytes}
object can contain null bytes.

If you need to encode a string to the current locale encoding, use
@ref{dc3,,PyUnicode_EncodeLocale()}.


@subsubheading 参考


@ref{dc1,,Py_EncodeLocale()} 関数。



Added in version 3.2.



バージョン 3.6 で変更: The @ref{75d,,filesystem error handler} is now used.

@end deffn

@node wchar_t サポート,,ファイルシステムエンコーディング,Unicode オブジェクト
@anchor{c-api/unicode wchar-t-support}@anchor{5378}
@subsubsection wchar_t サポート


@code{wchar_t} をサポートするプラットフォームでの wchar_t サポート:

@geindex PyUnicode_FromWideChar (C function)
@anchor{c-api/unicode c PyUnicode_FromWideChar}@anchor{13a4}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_FromWideChar (const wchar_t *wstr, Py_ssize_t size)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode object from the @code{wchar_t} buffer `wstr' of the given `size'.
Passing @code{-1} as the `size' indicates that the function must itself compute the length,
using @code{wcslen()}.
Return @code{NULL} on failure.
@end deffn

@geindex PyUnicode_AsWideChar (C function)
@anchor{c-api/unicode c PyUnicode_AsWideChar}@anchor{1e38}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_AsWideChar (PyObject *unicode, wchar_t *wstr, Py_ssize_t size)
` 次に属します: @ref{775,,Stable ABI}.'
Copy the Unicode object contents into the @code{wchar_t} buffer `wstr'.  At most
`size' @code{wchar_t} characters are copied (excluding a possibly trailing
null termination character).  Return the number of @code{wchar_t} characters
copied or @code{-1} in case of an error.

When `wstr' is @code{NULL}, instead return the `size' that would be required
to store all of `unicode' including a terminating null.

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.
@end deffn

@geindex PyUnicode_AsWideCharString (C function)
@anchor{c-api/unicode c PyUnicode_AsWideCharString}@anchor{ab9}
@deffn {C の関数} wchar_t *PyUnicode_AsWideCharString (PyObject *unicode, Py_ssize_t *size)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Convert the Unicode object to a wide character string. The output string
always ends with a null character. If `size' is not @code{NULL}, write the number
of wide characters (excluding the trailing null termination character) into
`*size'. Note that the resulting @code{wchar_t} string might contain
null characters, which would cause the string to be truncated when used with
most C functions. If `size' is @code{NULL} and the wchar_t* string
contains null characters a @ref{2ec,,ValueError} is raised.

Returns a buffer allocated by @ref{173d,,PyMem_New} (use
@ref{165b,,PyMem_Free()} to free it) on success. On error, returns @code{NULL}
and `*size' is undefined. Raises a @ref{179e,,MemoryError} if memory allocation
is failed.


Added in version 3.2.



バージョン 3.7 で変更: Raises a @ref{2ec,,ValueError} if `size' is @code{NULL} and the wchar_t*
string contains null characters.

@end deffn

@node 組み込み codec built-in codec,メソッドおよびスロット関数 slot function,Unicode オブジェクト,Unicode オブジェクトと codec
@anchor{c-api/unicode built-in-codecs}@anchor{5379}@anchor{c-api/unicode builtincodecs}@anchor{5375}
@subsubsection 組み込み codec (built-in codec)


Python には、処理速度を高めるために C で書かれた codec が揃えてあります。これら全ての codec は以下の関数を介して直接利用できます。

以下の API の多くが、 `encoding' と `errors' という二つの引数をとります。これらのパラメータは、組み込みの文字列コンストラクタである @ref{169,,str()} における同名のパラメータと同じ意味を持ちます。

Setting encoding to @code{NULL} causes the default encoding to be used
which is UTF-8.  The file system calls should use
@ref{f15,,PyUnicode_FSConverter()} for encoding file names. This uses the
@ref{75d,,filesystem encoding and error handler} internally.

`errors' で指定するエラー処理もまた、 @code{NULL} を指定できます。 @code{NULL} を指定すると、codec で定義されているデフォルト処理の使用を意味します。全ての組み込み codec で、デフォルトのエラー処理は "strict" (@ref{2ec,,ValueError} を送出する) になっています。

個々の codec は全て同様のインターフェースを使っています。個別の codec の説明では、説明を簡単にするために以下の汎用のインターフェースとの違いだけを説明しています。

@menu
* 汎用 codec:: 
* 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:: 
* Windows 用の MBCS codec:: 

@end menu

@node 汎用 codec,UTF-8 Codecs,,組み込み codec built-in codec
@anchor{c-api/unicode generic-codecs}@anchor{537a}
@subsubsection 汎用 codec


The following macro is provided:

@geindex Py_UNICODE_REPLACEMENT_CHARACTER (C macro)
@anchor{c-api/unicode c Py_UNICODE_REPLACEMENT_CHARACTER}@anchor{537b}
@deffn {C のマクロ} Py_UNICODE_REPLACEMENT_CHARACTER

The Unicode code point @code{U+FFFD} (replacement character).

This Unicode character is used as the replacement character during
decoding if the `errors' argument is set to "replace".
@end deffn

以下は汎用 codec の API です:

@geindex PyUnicode_Decode (C function)
@anchor{c-api/unicode c PyUnicode_Decode}@anchor{1dc7}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Decode (const char *str, Py_ssize_t size, const char *encoding, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode object by decoding `size' bytes of the encoded string `str'.
`encoding' and `errors' have the same meaning as the parameters of the same name
in the @ref{169,,str()} built-in function.  The codec to be used is looked up
using the Python codec registry.  Return @code{NULL} if an exception was raised by
the codec.
@end deffn

@geindex PyUnicode_AsEncodedString (C function)
@anchor{c-api/unicode c PyUnicode_AsEncodedString}@anchor{50f7}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsEncodedString (PyObject *unicode, const char *encoding, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Unicode オブジェクトをエンコードし、その結果を Python の bytes オブジェクトとして返します。
`encoding' および `errors' は Unicode 型の @ref{ad2,,encode()} メソッドに与える同名のパラメータと同じ意味を持ちます。
使用する codec の検索は、 Python の codec レジストリを使って行います。
codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@node UTF-8 Codecs,UTF-32 Codecs,汎用 codec,組み込み codec built-in codec
@anchor{c-api/unicode utf-8-codecs}@anchor{537c}
@subsubsection UTF-8 Codecs


以下は UTF-8 codec の APIです:

@geindex PyUnicode_DecodeUTF8 (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF8}@anchor{510b}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF8 (const char *str, Py_ssize_t size, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
UTF-8 でエンコードされた `size' バイトの文字列 `str' から Unicode オブジェクトを生成します。codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@geindex PyUnicode_DecodeUTF8Stateful (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF8Stateful}@anchor{1b17}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF8Stateful (const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`consumed' が @code{NULL} の場合、 @ref{510b,,PyUnicode_DecodeUTF8()} と同じように動作します。 `consumed' が @code{NULL} でない場合、末尾の不完全な UTF-8 バイト列はエラーとみなされません。これらのバイト列はデコードされず、デコードされたバイト数は `consumed' に格納されます。
@end deffn

@geindex PyUnicode_AsUTF8String (C function)
@anchor{c-api/unicode c PyUnicode_AsUTF8String}@anchor{13a6}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsUTF8String (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
UTF-8 で Unicode オブジェクトをエンコードし、結果を Python バイト列オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には @code{NULL} を返します。

The function fails if the string contains surrogate code points
(@code{U+D800} - @code{U+DFFF}).
@end deffn

@geindex PyUnicode_AsUTF8AndSize (C function)
@anchor{c-api/unicode c PyUnicode_AsUTF8AndSize}@anchor{a99}
@deffn {C の関数} const char *PyUnicode_AsUTF8AndSize (PyObject *unicode, Py_ssize_t *size)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Unicode オブジェクトを UTF-8 でエンコードしたものへのポインタを返し、エンコードされた表現形式でのサイズ (バイト単位) を `size' に格納します。
`size' 引数は @code{NULL} でも構いません; その場合はサイズは格納されません。
返されるバッファには、 null コードポイントがあるかどうかに関わらず、常に null バイトが終端に付加されています (これは `size' には勘定されません)。

On error, set an exception, set `size' to @code{-1} (if it's not NULL) and
return @code{NULL}.

The function fails if the string contains surrogate code points
(@code{U+D800} - @code{U+DFFF}).

This caches the UTF-8 representation of the string in the Unicode object, and
subsequent calls will return a pointer to the same buffer.  The caller is not
responsible for deallocating the buffer. The buffer is deallocated and
pointers to it become invalid when the Unicode object is garbage collected.


Added in version 3.3.



バージョン 3.7 で変更: 返り値の型が @code{char *} ではなく @code{const char *} になりました。



バージョン 3.10 で変更: This function is a part of the @ref{637,,limited API}.

@end deffn

@geindex PyUnicode_AsUTF8 (C function)
@anchor{c-api/unicode c PyUnicode_AsUTF8}@anchor{424}
@deffn {C の関数} const char *PyUnicode_AsUTF8 (PyObject *unicode)

@ref{a99,,PyUnicode_AsUTF8AndSize()} とほぼ同じですが、サイズを格納しません。

@cartouche
@quotation 警告 
This function does not have any special behavior for
null characters@footnote{https://en.wikipedia.org/wiki/Null_character} embedded within
`unicode'. As a result, strings containing null characters will remain in the returned
string, which some C functions might interpret as the end of the string, leading to
truncation. If truncation is an issue, it is recommended to use @ref{a99,,PyUnicode_AsUTF8AndSize()}
instead.
@end quotation
@end cartouche


Added in version 3.3.



バージョン 3.7 で変更: 返り値の型が @code{char *} ではなく @code{const char *} になりました。

@end deffn

@node UTF-32 Codecs,UTF-16 Codecs,UTF-8 Codecs,組み込み codec built-in codec
@anchor{c-api/unicode utf-32-codecs}@anchor{537d}
@subsubsection UTF-32 Codecs


以下は UTF-32 codec API です:

@geindex PyUnicode_DecodeUTF32 (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF32}@anchor{5107}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF32 (const char *str, Py_ssize_t size, const char *errors, int *byteorder)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
UTF-32 でエンコードされたバッファ文字列から `size' バイトをデコードし、 Unicodeオブジェクトとして返します。 `errors' は (@code{NULL} でないなら) エラーハンドラを指定します。デフォルトは "strict" です。

`byteorder' が @code{NULL} でない時、デコーダは与えられたバイトオーダーでデコードを開始します。

@example
*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian
@end example

@code{*byteorder} が 0 で、入力データの最初の 4 バイトが byte order mark (BOM) ならば、デコーダはこのバイトオーダーに切り替え、BOM は結果の Unicode 文字列にコピーされません。 @code{*byteorder} が @code{-1} または @code{1} ならば、全ての byte order mark は出力にコピーされます。

デコードが完了した後、入力データの終端に来た時点でのバイトオーダーを `*byteorder' にセットします。

`byteorder' が @code{NULL} のとき、 codec は native order モードで開始します。

codec が例外を発生させたときは @code{NULL} を返します。
@end deffn

@geindex PyUnicode_DecodeUTF32Stateful (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF32Stateful}@anchor{5108}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF32Stateful (const char *str, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`consumed' が @code{NULL} のとき、 @ref{5107,,PyUnicode_DecodeUTF32()} と同じように振る舞います。 `consumed' が @code{NULL} でないとき、 @ref{5108,,PyUnicode_DecodeUTF32Stateful()} は末尾の不完全な (4 で割り切れない長さのバイト列などの) UTF-32 バイト列をエラーとして扱いません。末尾の不完全なバイト列はデコードされず、デコードされたバイト数が `consumed' に格納されます。
@end deffn

@geindex PyUnicode_AsUTF32String (C function)
@anchor{c-api/unicode c PyUnicode_AsUTF32String}@anchor{50f9}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsUTF32String (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
ネイティブバイトオーダーで UTF-32 エンコーディングされた Python バイト文字列を返します。
文字列は常に BOM マークで始まります。
エラーハンドラは "strict" です。
codec が例外を発生させたときは @code{NULL} を返します。
@end deffn

@node UTF-16 Codecs,UTF-7 Codecs,UTF-32 Codecs,組み込み codec built-in codec
@anchor{c-api/unicode utf-16-codecs}@anchor{537e}
@subsubsection UTF-16 Codecs


以下は UTF-16 codec の APIです:

@geindex PyUnicode_DecodeUTF16 (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF16}@anchor{5105}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF16 (const char *str, Py_ssize_t size, const char *errors, int *byteorder)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
UTF-16 でエンコードされたバッファ `s' から `size' バイトだけデコードして、結果を Unicode オブジェクトで返します。 `errors' は (@code{NULL} でない場合) エラー処理方法を定義します。デフォルト値は "strict" です。

`byteorder' が @code{NULL} でない時、デコーダは与えられたバイトオーダーでデコードを開始します。

@example
*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian
@end example

@code{*byteorder} が 0 で、入力データの先頭2バイトがバイトオーダーマーク (BOM) だった場合、デコーダは BOM が示すバイトオーダーに切り替え、そのBOMを結果の Unicode 文字列にコピーしません。 @code{*byteorder} が @code{-1} か @code{1} だった場合、すべてのBOMは出力へコピーされます (出力では @code{\ufeff} か @code{\ufffe} のどちらかになるでしょう)。

デコードが完了した後、入力データの終端に来た時点でのバイトオーダーを @code{*byteorder} にセットします。

`byteorder' が @code{NULL} のとき、 codec は native order モードで開始します。

codec が例外を発生させたときは @code{NULL} を返します。
@end deffn

@geindex PyUnicode_DecodeUTF16Stateful (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF16Stateful}@anchor{5106}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF16Stateful (const char *str, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`consumed' が @code{NULL} の場合、 @ref{5105,,PyUnicode_DecodeUTF16()} と同じように動作します。 `consumed' が @code{NULL} でない場合、 @ref{5106,,PyUnicode_DecodeUTF16Stateful()} は末尾の不完全な UTF-16 バイト列 (奇数長のバイト列や分割されたサロゲートペア) をエラーとみなしません。これらのバイト列はデコードされず、デコードされたバイト数を `consumed' に返します。
@end deffn

@geindex PyUnicode_AsUTF16String (C function)
@anchor{c-api/unicode c PyUnicode_AsUTF16String}@anchor{50f8}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsUTF16String (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
ネイティブバイトオーダーで UTF-16 エンコーディングされた Python バイト文字列を返します。
文字列は常に BOM マークで始まります。
エラーハンドラは "strict" です。
codec が例外を発生させたときは @code{NULL} を返します。
@end deffn

@node UTF-7 Codecs,Unicode-Escape Codecs,UTF-16 Codecs,組み込み codec built-in codec
@anchor{c-api/unicode utf-7-codecs}@anchor{537f}
@subsubsection UTF-7 Codecs


以下は UTF-7 codec の API です:

@geindex PyUnicode_DecodeUTF7 (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF7}@anchor{5109}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF7 (const char *str, Py_ssize_t size, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode object by decoding `size' bytes of the UTF-7 encoded string
`str'.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_DecodeUTF7Stateful (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUTF7Stateful}@anchor{510a}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUTF7Stateful (const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`consumed' が @code{NULL} のとき、 @ref{5109,,PyUnicode_DecodeUTF7()} と同じように動作します。 `consumed' が @code{NULL} でないとき、末尾の不完全な UTF-7 base-64 部分をエラーとしません。不完全な部分のバイト列はデコードせずに、デコードしたバイト数を `consumed' に格納します。
@end deffn

@node Unicode-Escape Codecs,Raw-Unicode-Escape Codecs,UTF-7 Codecs,組み込み codec built-in codec
@anchor{c-api/unicode unicode-escape-codecs}@anchor{5380}
@subsubsection Unicode-Escape Codecs


以下は "Unicode Escape" codec の API です:

@geindex PyUnicode_DecodeUnicodeEscape (C function)
@anchor{c-api/unicode c PyUnicode_DecodeUnicodeEscape}@anchor{510c}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeUnicodeEscape (const char *str, Py_ssize_t size, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode object by decoding `size' bytes of the Unicode-Escape encoded
string `str'.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_AsUnicodeEscapeString (C function)
@anchor{c-api/unicode c PyUnicode_AsUnicodeEscapeString}@anchor{13a7}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsUnicodeEscapeString (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Unicode-Escape を使い Unicode オブジェクトをエンコードし、結果を bytes オブジェクトとして返します。
エラー処理は "strict" です。
codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@node Raw-Unicode-Escape Codecs,Latin-1 Codecs,Unicode-Escape Codecs,組み込み codec built-in codec
@anchor{c-api/unicode raw-unicode-escape-codecs}@anchor{5381}
@subsubsection Raw-Unicode-Escape Codecs


以下は "Raw Unicode Escape" codec の APIです:

@geindex PyUnicode_DecodeRawUnicodeEscape (C function)
@anchor{c-api/unicode c PyUnicode_DecodeRawUnicodeEscape}@anchor{5104}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeRawUnicodeEscape (const char *str, Py_ssize_t size, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode object by decoding `size' bytes of the Raw-Unicode-Escape
encoded string `str'.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_AsRawUnicodeEscapeString (C function)
@anchor{c-api/unicode c PyUnicode_AsRawUnicodeEscapeString}@anchor{13a8}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsRawUnicodeEscapeString (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Raw-Unicode-Escape を使い Unicode オブジェクトをエンコードし、結果を bytes オブジェクトとして返します。
エラー処理は "strict" です。
codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@node Latin-1 Codecs,ASCII Codecs,Raw-Unicode-Escape Codecs,組み込み codec built-in codec
@anchor{c-api/unicode latin-1-codecs}@anchor{5382}
@subsubsection Latin-1 Codecs


以下は Latin-1 codec の APIです: Latin-1 は、 Unicode 序数の最初の 256 個に対応し、エンコード時にはこの 256 個だけを受理します。

@geindex PyUnicode_DecodeLatin1 (C function)
@anchor{c-api/unicode c PyUnicode_DecodeLatin1}@anchor{5100}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeLatin1 (const char *str, Py_ssize_t size, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Latin-1 でエンコードされた `size' バイトの文字列 `str' から Unicode オブジェクトを生成します。codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@geindex PyUnicode_AsLatin1String (C function)
@anchor{c-api/unicode c PyUnicode_AsLatin1String}@anchor{13a9}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsLatin1String (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Latin-1 で Unicode オブジェクトをエンコードし、結果を Python bytes オブジェクトとして返します。
エラー処理は "strict" です。 codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@node ASCII Codecs,Character Map Codecs,Latin-1 Codecs,組み込み codec built-in codec
@anchor{c-api/unicode ascii-codecs}@anchor{5383}
@subsubsection ASCII Codecs


以下は ASCII codec の APIです。 7 ビットの ASCII データだけを受理します。その他のコードはエラーになります。

@geindex PyUnicode_DecodeASCII (C function)
@anchor{c-api/unicode c PyUnicode_DecodeASCII}@anchor{50fc}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeASCII (const char *str, Py_ssize_t size, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Create a Unicode object by decoding `size' bytes of the ASCII encoded string
`str'.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_AsASCIIString (C function)
@anchor{c-api/unicode c PyUnicode_AsASCIIString}@anchor{13aa}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsASCIIString (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
ASCII で Unicode オブジェクトをエンコードし、結果を Python bytes オブジェクトとして返します。
エラー処理は "strict" です。
codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@node Character Map Codecs,Windows 用の MBCS codec,ASCII Codecs,組み込み codec built-in codec
@anchor{c-api/unicode character-map-codecs}@anchor{5384}
@subsubsection Character Map Codecs


この codec は、多くの様々な codec を実装する際に使われるという点で特殊な codec です (実際、 @code{encodings} パッケージに入っている標準 codecs のほとんどは、この codec を使っています)。
この codec は、文字のエンコードやデコードに対応表を使います。
提供される対応表のオブジェクトは @ref{588,,__getitem__()} マッピングインターフェースをサポートしていなければなりません; 辞書やシーケンスがそれに適しています。

以下は mapping codec の APIです:

@geindex PyUnicode_DecodeCharmap (C function)
@anchor{c-api/unicode c PyUnicode_DecodeCharmap}@anchor{50fd}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeCharmap (const char *str, Py_ssize_t length, PyObject *mapping, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
与えられた `mapping' オブジェクトを使って、 `size' バイトのエンコードされた文字列 `str' をデコードして Unicode オブジェクトを作成します。
codec が例外を発生させたときは @code{NULL} を返します。

If `mapping' is @code{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 @code{None}.  Unmapped data bytes -- ones which cause a
@ref{23e5,,LookupError}, as well as ones which get mapped to @code{None},
@code{0xFFFE} or @code{'\ufffe'}, are treated as undefined mappings and cause
an error.
@end deffn

@geindex PyUnicode_AsCharmapString (C function)
@anchor{c-api/unicode c PyUnicode_AsCharmapString}@anchor{50f6}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsCharmapString (PyObject *unicode, PyObject *mapping)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Unicode オブジェクトを `mapping' に指定されたオブジェクトを使ってエンコードし、結果を bytes オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には @code{NULL} を返します。

The `mapping' object must map Unicode ordinal integers to bytes objects,
integers in the range from 0 to 255 or @code{None}.  Unmapped character
ordinals (ones which cause a @ref{23e5,,LookupError}) as well as mapped to
@code{None} are treated as "undefined mapping" and cause an error.
@end deffn

以下の codec API は Unicode から Unicode への対応付けを行う特殊なものです。

@geindex PyUnicode_Translate (C function)
@anchor{c-api/unicode c PyUnicode_Translate}@anchor{511a}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Translate (PyObject *unicode, PyObject *table, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
文字列に文字対応表 `table' を適用して変換し、変換結果を Unicode オブジェクトで返します。codec が例外を発行した場合には @code{NULL} を返します。

対応表は、Unicode 序数を表す整数を Unicode 序数を表す整数または @code{None} (その文字を削除する) に対応付けなければなりません。

Mapping tables need only provide the @ref{588,,__getitem__()} interface; dictionaries
and sequences work well.  Unmapped character ordinals (ones which cause a
@ref{23e5,,LookupError}) are left untouched and are copied as-is.

`errors' は codecs で通常使われるのと同じ意味を持ちます。 `errors' は @code{NULL} にしてもよく、デフォルトエラー処理の使用を意味します。
@end deffn

@node Windows 用の MBCS codec,,Character Map Codecs,組み込み codec built-in codec
@anchor{c-api/unicode mbcs-codecs-for-windows}@anchor{5385}
@subsubsection Windows 用の MBCS codec


以下は MBCS codec の API です。この codec は現在のところ、 Windows 上だけで利用でき、変換の実装には Win32 MBCS 変換機構 (Win32 MBCS converter) を使っています。 MBCS (または DBCS) はエンコード方式の種類 (class) を表す言葉で、単一のエンコード方式を表すわけでなないので注意してください。利用されるエンコード方式 (target encoding) は、 codec を動作させているマシン上のユーザ設定で定義されています。

@geindex PyUnicode_DecodeMBCS (C function)
@anchor{c-api/unicode c PyUnicode_DecodeMBCS}@anchor{5102}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeMBCS (const char *str, Py_ssize_t size, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
Create a Unicode object by decoding `size' bytes of the MBCS encoded string `str'.
Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_DecodeMBCSStateful (C function)
@anchor{c-api/unicode c PyUnicode_DecodeMBCSStateful}@anchor{5103}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeMBCSStateful (const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
`consumed' が @code{NULL} のとき、 @ref{5102,,PyUnicode_DecodeMBCS()} と同じ動作をします。 `consumed' が @code{NULL} でないとき、 @ref{5103,,PyUnicode_DecodeMBCSStateful()} は文字列の最後にあるマルチバイト文字の前半バイトをデコードせず、 `consumed' にデコードしたバイト数を格納します。
@end deffn

@geindex PyUnicode_DecodeCodePageStateful (C function)
@anchor{c-api/unicode c PyUnicode_DecodeCodePageStateful}@anchor{50fe}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_DecodeCodePageStateful (int code_page, const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
Similar to @ref{5103,,PyUnicode_DecodeMBCSStateful()}, except uses the code page
specified by `code_page'.
@end deffn

@geindex PyUnicode_AsMBCSString (C function)
@anchor{c-api/unicode c PyUnicode_AsMBCSString}@anchor{13ab}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_AsMBCSString (PyObject *unicode)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
MBCS で Unicode オブジェクトをエンコードし、結果を Python バイト列オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には @code{NULL} を返します。
@end deffn

@geindex PyUnicode_EncodeCodePage (C function)
@anchor{c-api/unicode c PyUnicode_EncodeCodePage}@anchor{13ac}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_EncodeCodePage (int code_page, PyObject *unicode, const char *errors)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} on Windows (バージョン 3.7 より).'
Encode the Unicode object using the specified code page and return a Python
bytes object.  Return @code{NULL} if an exception was raised by the codec. Use
@code{CP_ACP} code page to get the MBCS encoder.


Added in version 3.3.

@end deffn

@node メソッドおよびスロット関数 slot function,PyUnicodeWriter,組み込み codec built-in codec,Unicode オブジェクトと codec
@anchor{c-api/unicode methods-and-slot-functions}@anchor{5386}@anchor{c-api/unicode unicodemethodsandslots}@anchor{5387}
@subsubsection メソッドおよびスロット関数 (slot function)


以下の API は Unicode オブジェクトおよび文字列を入力に取り (説明では、どちらも文字列と表記しています)、場合に応じて Unicode オブジェクトか整数を返す機能を持っています。

これらの関数は全て、例外が発生した場合には @code{NULL} または @code{-1} を返します。

@geindex PyUnicode_Concat (C function)
@anchor{c-api/unicode c PyUnicode_Concat}@anchor{13b9}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Concat (PyObject *left, PyObject *right)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
二つの文字列を結合して、新たな Unicode 文字列を生成します。
@end deffn

@geindex PyUnicode_Split (C function)
@anchor{c-api/unicode c PyUnicode_Split}@anchor{5118}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Split (PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Unicode 文字列のリストを分割して、 Unicode 文字列からなるリストを返します。 `sep' が @code{NULL} の場合、全ての空白文字を使って分割を行います。それ以外の場合、指定された文字を使って分割を行います。最大で `maxsplit' 個までの分割を行います。 `maxsplit' が負ならば分割数に制限を設けません。分割結果のリスト内には分割文字は含みません。

On error, return @code{NULL} with an exception set.

Equivalent to @ref{10aa,,str.split()}.
@end deffn

@geindex PyUnicode_RSplit (C function)
@anchor{c-api/unicode c PyUnicode_RSplit}@anchor{1897}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_RSplit (PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Similar to @ref{5118,,PyUnicode_Split()}, but splitting will be done beginning
at the end of the string.

On error, return @code{NULL} with an exception set.

Equivalent to @ref{146d,,str.rsplit()}.
@end deffn

@geindex PyUnicode_Splitlines (C function)
@anchor{c-api/unicode c PyUnicode_Splitlines}@anchor{5119}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Splitlines (PyObject *unicode, int keepends)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Split a Unicode string at line breaks, returning a list of Unicode strings.
CRLF is considered to be one line break.  If `keepends' is @code{0}, the Line break
characters are not included in the resulting strings.
@end deffn

@geindex PyUnicode_Partition (C function)
@anchor{c-api/unicode c PyUnicode_Partition}@anchor{1898}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Partition (PyObject *unicode, PyObject *sep)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Split a Unicode string at the first occurrence of `sep', and return
a 3-tuple containing the part before the separator, the separator itself,
and the part after the separator. If the separator is not found,
return a 3-tuple containing the string itself, followed by two empty strings.

`sep' must not be empty.

On error, return @code{NULL} with an exception set.

Equivalent to @ref{10ab,,str.partition()}.
@end deffn

@geindex PyUnicode_RPartition (C function)
@anchor{c-api/unicode c PyUnicode_RPartition}@anchor{1899}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_RPartition (PyObject *unicode, PyObject *sep)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Similar to @ref{1898,,PyUnicode_Partition()}, but split a Unicode string at the
last occurrence of `sep'. If the separator is not found, return a 3-tuple
containing two empty strings, followed by the string itself.

`sep' must not be empty.

On error, return @code{NULL} with an exception set.

Equivalent to @ref{1470,,str.rpartition()}.
@end deffn

@geindex PyUnicode_Join (C function)
@anchor{c-api/unicode c PyUnicode_Join}@anchor{13ba}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Join (PyObject *separator, PyObject *seq)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
指定した `separator' で文字列からなるシーケンスを連結 (join) し、連結結果を Unicode 文字列で返します。
@end deffn

@geindex PyUnicode_Tailmatch (C function)
@anchor{c-api/unicode c PyUnicode_Tailmatch}@anchor{ab5}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_Tailmatch (PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
` 次に属します: @ref{775,,Stable ABI}.'
Return @code{1} if `substr' matches @code{unicode[start:end]} at the given tail end
(`direction' == @code{-1} means to do a prefix match, `direction' == @code{1} a suffix match),
@code{0} otherwise. Return @code{-1} if an error occurred.
@end deffn

@geindex PyUnicode_Find (C function)
@anchor{c-api/unicode c PyUnicode_Find}@anchor{510d}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_Find (PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
` 次に属します: @ref{775,,Stable ABI}.'
@code{unicode[start:end]} 中に `substr' が最初に出現する場所を返します。
このとき指定された検索方向 `direction' (`direction' == @code{1} は順方向検索、 `direction' == @code{-1} は逆方向検索) で検索します。
戻り値は最初にマッチが見つかった場所のインデックスです; 戻り値 @code{-1} はマッチが見つからなかったことを表し、 @code{-2} はエラーが発生して例外情報が設定されていることを表します。
@end deffn

@geindex PyUnicode_FindChar (C function)
@anchor{c-api/unicode c PyUnicode_FindChar}@anchor{ab6}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_FindChar (PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@code{unicode[start:end]} 中に文字 `ch' が最初に出現する場所を返します。
このとき指定された検索方向 `direction' (`direction' == @code{1} は順方向検索、 `direction' == @code{-1} は逆方向検索) で検索します。
戻り値は最初にマッチが見つかった場所のインデックスです; 戻り値 @code{-1} はマッチが見つからなかったことを表し、 @code{-2} はエラーが発生して例外情報が設定されていることを表します。


Added in version 3.3.



バージョン 3.7 で変更: `start' and `end' are now adjusted to behave like @code{unicode[start:end]}.

@end deffn

@geindex PyUnicode_Count (C function)
@anchor{c-api/unicode c PyUnicode_Count}@anchor{50fb}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnicode_Count (PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
` 次に属します: @ref{775,,Stable ABI}.'
@code{unicode[start:end]} に `substr' が重複することなく出現する回数を返します。エラーが発生した場合には @code{-1} を返します。
@end deffn

@geindex PyUnicode_Replace (C function)
@anchor{c-api/unicode c PyUnicode_Replace}@anchor{5115}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Replace (PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`unicode' 中に出現する `substr' を最大で `maxcount' 個 `replstr' に置換し、置換結果である Unicode オブジェクトを返します。
`maxcount' == @code{-1} にすると、文字列中に現れる全ての `substr' を置換します。
@end deffn

@geindex PyUnicode_Compare (C function)
@anchor{c-api/unicode c PyUnicode_Compare}@anchor{ab4}
@deffn {C の関数} int PyUnicode_Compare (PyObject *left, PyObject *right)
` 次に属します: @ref{775,,Stable ABI}.'
二つの文字列を比較して、左引数が右引数より小さい場合、左右引数が等価の場合、左引数が右引数より大きい場合に対して、それぞれ @code{-1}, @code{0}, @code{1} を返します。

この関数は、失敗したときに @code{-1} を返すので、 @ref{1caf,,PyErr_Occurred()} を呼び出して、エラーをチェックすべきです。


@subsubheading 参考


The @ref{3b2,,PyUnicode_Equal()} function.

@end deffn

@geindex PyUnicode_Equal (C function)
@anchor{c-api/unicode c PyUnicode_Equal}@anchor{3b2}
@deffn {C の関数} int PyUnicode_Equal (PyObject *a, PyObject *b)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Test if two strings are equal:


@itemize *

@item 
Return @code{1} if `a' is equal to `b'.

@item 
Return @code{0} if `a' is not equal to `b'.

@item 
Set a @ref{198,,TypeError} exception and return @code{-1} if `a' or `b' is not a
@ref{169,,str} object.
@end itemize

The function always succeeds if `a' and `b' are @ref{169,,str} objects.

The function works for @ref{169,,str} subclasses, but does not honor custom
@code{__eq__()} method.


@subsubheading 参考


The @ref{ab4,,PyUnicode_Compare()} function.



Added in version 3.14.

@end deffn

@geindex PyUnicode_EqualToUTF8AndSize (C function)
@anchor{c-api/unicode c PyUnicode_EqualToUTF8AndSize}@anchor{619}
@deffn {C の関数} int PyUnicode_EqualToUTF8AndSize (PyObject *unicode, const char *string, Py_ssize_t size)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Compare a Unicode object with a char buffer which is interpreted as
being UTF-8 or ASCII encoded and return true (@code{1}) if they are equal,
or false (@code{0}) otherwise.
If the Unicode object contains surrogate code points
(@code{U+D800} - @code{U+DFFF}) or the C string is not valid UTF-8,
false (@code{0}) is returned.

この関数は例外を送出しません。


Added in version 3.13.

@end deffn

@geindex PyUnicode_EqualToUTF8 (C function)
@anchor{c-api/unicode c PyUnicode_EqualToUTF8}@anchor{61a}
@deffn {C の関数} int PyUnicode_EqualToUTF8 (PyObject *unicode, const char *string)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Similar to @ref{619,,PyUnicode_EqualToUTF8AndSize()}, but compute `string'
length using @code{strlen()}.
If the Unicode object contains null characters, false (@code{0}) is returned.


Added in version 3.13.

@end deffn

@geindex PyUnicode_CompareWithASCIIString (C function)
@anchor{c-api/unicode c PyUnicode_CompareWithASCIIString}@anchor{147f}
@deffn {C の関数} int PyUnicode_CompareWithASCIIString (PyObject *unicode, const char *string)
` 次に属します: @ref{775,,Stable ABI}.'
Unicode オブジェクト `unicode' と `string' を比較して、左引数が右引数より小さい場合、左右引数が等価の場合、左引数が右引数より大きい場合に対して、それぞれ @code{-1}, @code{0}, @code{1} を返します。
ASCII エンコードされた文字列だけを渡すのが最も良いですが、入力文字列に非 ASCII 文字が含まれている場合は ISO-8859-1 として解釈します。

この関数は例外を送出しません。
@end deffn

@geindex PyUnicode_RichCompare (C function)
@anchor{c-api/unicode c PyUnicode_RichCompare}@anchor{5117}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_RichCompare (PyObject *left, PyObject *right, int op)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
二つのUnicode文字列を比較して、下のうちの一つを返します:


@itemize *

@item 
@code{NULL} を、例外が発生したときに返します。

@item 
@ref{5315,,Py_True} もしくは @ref{5314,,Py_False} を、正しく比較できた時に返します。

@item 
@ref{5286,,Py_NotImplemented} in case the type combination is unknown
@end itemize

Possible values for `op' are @ref{528d,,Py_GT}, @ref{528e,,Py_GE}, @ref{528b,,Py_EQ},
@ref{528c,,Py_NE}, @ref{5289,,Py_LT}, and @ref{528a,,Py_LE}.
@end deffn

@geindex PyUnicode_Format (C function)
@anchor{c-api/unicode c PyUnicode_Format}@anchor{510e}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_Format (PyObject *format, PyObject *args)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
新たな文字列オブジェクトを `format' および `args' から生成して返します; このメソッドは @code{format % args} のようなものです。
@end deffn

@geindex PyUnicode_Contains (C function)
@anchor{c-api/unicode c PyUnicode_Contains}@anchor{50fa}
@deffn {C の関数} int PyUnicode_Contains (PyObject *unicode, PyObject *substr)
` 次に属します: @ref{775,,Stable ABI}.'
`substr' が `unicode' 内にあるか調べ、その結果に応じて真または偽を返します。

`substr' は単要素の Unicode 文字に型強制できなければなりません。エラーが生じた場合には @code{-1} を返します。
@end deffn

@geindex PyUnicode_InternInPlace (C function)
@anchor{c-api/unicode c PyUnicode_InternInPlace}@anchor{aae}
@deffn {C の関数} void PyUnicode_InternInPlace (PyObject **p_unicode)
` 次に属します: @ref{775,,Stable ABI}.'
Intern the argument *@ref{aae,,p_unicode} 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 *@ref{aae,,p_unicode}, it sets *@ref{aae,,p_unicode} to
it (releasing the reference to the old string object and creating a new
@ref{5e2,,strong reference} to the interned string object), otherwise it leaves
*@ref{aae,,p_unicode} alone and interns it.

(Clarification: even though there is a lot of talk about references, think
of this function as reference-neutral. You must own the object you pass in;
after the call you no longer own the passed-in reference, but you newly own
the result.)

This function never raises an exception.
On error, it leaves its argument unchanged without interning it.

Instances of subclasses of @ref{169,,str} may not be interned, that is,
@ref{535b,,PyUnicode_CheckExact}(*@ref{aae,,p_unicode}) must be true. If it is not,
then -- as with any other error -- the argument is left unchanged.

Note that interned strings are not “immortal”.
You must keep a reference to the result to benefit from interning.
@end deffn

@geindex PyUnicode_InternFromString (C function)
@anchor{c-api/unicode c PyUnicode_InternFromString}@anchor{198c}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicode_InternFromString (const char *str)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
A combination of @ref{5112,,PyUnicode_FromString()} and
@ref{aae,,PyUnicode_InternInPlace()}, meant for statically allocated strings.

Return a new ("owned") reference to either a new Unicode string object
that has been interned, or an earlier interned string object with the
same value.

Python may keep a reference to the result, or make it @ref{290,,immortal},
preventing it from being garbage-collected promptly.
For interning an unbounded number of different strings, such as ones coming
from user input, prefer calling @ref{5112,,PyUnicode_FromString()} and
@ref{aae,,PyUnicode_InternInPlace()} directly.
@end deffn

@geindex PyUnicode_CHECK_INTERNED (C function)
@anchor{c-api/unicode c PyUnicode_CHECK_INTERNED}@anchor{5388}
@deffn {C の関数} unsigned int PyUnicode_CHECK_INTERNED (PyObject *str)

Return a non-zero value if `str' is interned, zero if not.
The `str' argument must be a string; this is not checked.
This function always succeeds.

`CPython 実装の詳細:' A non-zero return value may carry additional information
about `how' the string is interned.
The meaning of such non-zero values, as well as each specific string's
intern-related details, may change between CPython versions.
@end deffn

@node PyUnicodeWriter,Deprecated API<2>,メソッドおよびスロット関数 slot function,Unicode オブジェクトと codec
@anchor{c-api/unicode pyunicodewriter}@anchor{5389}
@subsubsection PyUnicodeWriter


The @ref{3b3,,PyUnicodeWriter} API can be used to create a Python @ref{169,,str}
object.


Added in version 3.14.


@geindex PyUnicodeWriter (C type)
@anchor{c-api/unicode c PyUnicodeWriter}@anchor{3b3}
@deffn {C のデータ型} type PyUnicodeWriter

A Unicode writer instance.

The instance must be destroyed by @ref{3b7,,PyUnicodeWriter_Finish()} on
success, or @ref{3b6,,PyUnicodeWriter_Discard()} on error.
@end deffn

@geindex PyUnicodeWriter_Create (C function)
@anchor{c-api/unicode c PyUnicodeWriter_Create}@anchor{3b4}
@deffn {C の関数} @ref{3b3,,PyUnicodeWriter} *PyUnicodeWriter_Create (Py_ssize_t length)

Create a Unicode writer instance.

`length' must be greater than or equal to @code{0}.

If `length' is greater than @code{0}, preallocate an internal buffer of
`length' characters.

Set an exception and return @code{NULL} on error.
@end deffn

@geindex PyUnicodeWriter_Finish (C function)
@anchor{c-api/unicode c PyUnicodeWriter_Finish}@anchor{3b7}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnicodeWriter_Finish (PyUnicodeWriter *writer)

Return the final Python @ref{169,,str} object and destroy the writer instance.

Set an exception and return @code{NULL} on error.

The writer instance is invalid after this call.
@end deffn

@geindex PyUnicodeWriter_Discard (C function)
@anchor{c-api/unicode c PyUnicodeWriter_Discard}@anchor{3b6}
@deffn {C の関数} void PyUnicodeWriter_Discard (PyUnicodeWriter *writer)

Discard the internal Unicode buffer and destroy the writer instance.

If `writer' is @code{NULL}, no operation is performed.

The writer instance is invalid after this call.
@end deffn

@geindex PyUnicodeWriter_WriteChar (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteChar}@anchor{3ba}
@deffn {C の関数} int PyUnicodeWriter_WriteChar (PyUnicodeWriter *writer, Py_UCS4 ch)

Write the single Unicode character `ch' into `writer'.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.
@end deffn

@geindex PyUnicodeWriter_WriteUTF8 (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteUTF8}@anchor{3bf}
@deffn {C の関数} int PyUnicodeWriter_WriteUTF8 (PyUnicodeWriter *writer, const char *str, Py_ssize_t size)

Decode the string `str' from UTF-8 in strict mode and write the output into `writer'.

`size' is the string length in bytes. If `size' is equal to @code{-1}, call
@code{strlen(str)} to get the string length.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.

See also @ref{3b5,,PyUnicodeWriter_DecodeUTF8Stateful()}.
@end deffn

@geindex PyUnicodeWriter_WriteASCII (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteASCII}@anchor{3b9}
@deffn {C の関数} int PyUnicodeWriter_WriteASCII (PyUnicodeWriter *writer, const char *str, Py_ssize_t size)

Write the ASCII string `str' into `writer'.

`size' is the string length in bytes. If `size' is equal to @code{-1}, call
@code{strlen(str)} to get the string length.

`str' must only contain ASCII characters. The behavior is undefined if
`str' contains non-ASCII characters.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.


Added in version 3.14.

@end deffn

@geindex PyUnicodeWriter_WriteWideChar (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteWideChar}@anchor{3c0}
@deffn {C の関数} int PyUnicodeWriter_WriteWideChar (PyUnicodeWriter *writer, const wchar_t *str, Py_ssize_t size)

Write the wide string `str' into `writer'.

`size' is a number of wide characters. If `size' is equal to @code{-1}, call
@code{wcslen(str)} to get the string length.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.
@end deffn

@geindex PyUnicodeWriter_WriteUCS4 (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteUCS4}@anchor{3be}
@deffn {C の関数} int PyUnicodeWriter_WriteUCS4 (PyUnicodeWriter *writer, Py_UCS4 *str, Py_ssize_t size)

Writer the UCS4 string `str' into `writer'.

`size' is a number of UCS4 characters.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.
@end deffn

@geindex PyUnicodeWriter_WriteStr (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteStr}@anchor{3bc}
@deffn {C の関数} int PyUnicodeWriter_WriteStr (PyUnicodeWriter *writer, PyObject *obj)

Call @ref{1231,,PyObject_Str()} on `obj' and write the output into `writer'.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.
@end deffn

@geindex PyUnicodeWriter_WriteRepr (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteRepr}@anchor{3bb}
@deffn {C の関数} int PyUnicodeWriter_WriteRepr (PyUnicodeWriter *writer, PyObject *obj)

Call @ref{1230,,PyObject_Repr()} on `obj' and write the output into `writer'.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.
@end deffn

@geindex PyUnicodeWriter_WriteSubstring (C function)
@anchor{c-api/unicode c PyUnicodeWriter_WriteSubstring}@anchor{3bd}
@deffn {C の関数} int PyUnicodeWriter_WriteSubstring (PyUnicodeWriter *writer, PyObject *str, Py_ssize_t start, Py_ssize_t end)

Write the substring @code{str[start:end]} into `writer'.

`str' must be Python @ref{169,,str} object. `start' must be greater than or
equal to 0, and less than or equal to `end'. `end' must be less than or
equal to `str' length.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.
@end deffn

@geindex PyUnicodeWriter_Format (C function)
@anchor{c-api/unicode c PyUnicodeWriter_Format}@anchor{3b8}
@deffn {C の関数} int PyUnicodeWriter_Format (PyUnicodeWriter *writer, const char *format, ...)

Similar to @ref{62b,,PyUnicode_FromFormat()}, but write the output directly into `writer'.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.
@end deffn

@geindex PyUnicodeWriter_DecodeUTF8Stateful (C function)
@anchor{c-api/unicode c PyUnicodeWriter_DecodeUTF8Stateful}@anchor{3b5}
@deffn {C の関数} int PyUnicodeWriter_DecodeUTF8Stateful (PyUnicodeWriter *writer, const char *string, Py_ssize_t length, const char *errors, Py_ssize_t *consumed)

Decode the string `str' from UTF-8 with `errors' error handler and write the
output into `writer'.

`size' is the string length in bytes. If `size' is equal to @code{-1}, call
@code{strlen(str)} to get the string length.

`errors' is an @ref{1b6f,,error handler} name, such as
@code{"replace"}. If `errors' is @code{NULL}, use the strict error handler.

If `consumed' is not @code{NULL}, set `*consumed' to the number of decoded
bytes on success.
If `consumed' is @code{NULL}, treat trailing incomplete UTF-8 byte sequences
as an error.

On success, return @code{0}.
On error, set an exception, leave the writer unchanged, and return @code{-1}.

See also @ref{3bf,,PyUnicodeWriter_WriteUTF8()}.
@end deffn

@node Deprecated API<2>,,PyUnicodeWriter,Unicode オブジェクトと codec
@anchor{c-api/unicode deprecated-api}@anchor{538a}
@subsubsection Deprecated API


The following API is deprecated.

@geindex Py_UNICODE (C type)
@anchor{c-api/unicode c Py_UNICODE}@anchor{3e0}
@deffn {C のデータ型} type Py_UNICODE

This is a typedef of @code{wchar_t}, which is a 16-bit type or 32-bit type
depending on the platform.
Please use @code{wchar_t} directly instead.


バージョン 3.3 で変更: 以前のバージョンでは、Pythonをビルドした際に "narrow" または "wide" Unicode バージョンのどちらを選択したかによって、 16ビットか32ビットのどちらかの型になっていました。



Deprecated since version 3.13, will be removed in version 3.15.

@end deffn

@geindex PyUnicode_READY (C function)
@anchor{c-api/unicode c PyUnicode_READY}@anchor{434}
@deffn {C の関数} int PyUnicode_READY (PyObject *unicode)

Do nothing and return @code{0}.
This API is kept only for backward compatibility, but there are no plans
to remove it.


Added in version 3.3.



バージョン 3.10 で非推奨: This API does nothing since Python 3.12.
Previously, this needed to be called for each string created using
the old API (@code{PyUnicode_FromUnicode()} or similar).

@end deffn

@geindex PyUnicode_IS_READY (C function)
@anchor{c-api/unicode c PyUnicode_IS_READY}@anchor{538b}
@deffn {C の関数} unsigned int PyUnicode_IS_READY (PyObject *unicode)

Do nothing and return @code{1}.
This API is kept only for backward compatibility, but there are no plans
to remove it.


Added in version 3.3.



バージョン 3.14 で非推奨: This API does nothing since Python 3.12.
Previously, this could be called to check if
@ref{434,,PyUnicode_READY()} is necessary.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node タプルオブジェクト tuple object,Struct Sequence オブジェクト,Unicode オブジェクトと codec,シーケンスオブジェクト sequence object
@anchor{c-api/tuple doc}@anchor{538c}@anchor{c-api/tuple translation-repo}@anchor{538d}@anchor{c-api/tuple tuple-objects}@anchor{538e}@anchor{c-api/tuple tupleobjects}@anchor{538f}
@subsubsection タプルオブジェクト (tuple object)


@geindex object;tuple

@geindex PyTupleObject (C type)
@anchor{c-api/tuple c PyTupleObject}@anchor{5224}
@deffn {C のデータ型} type PyTupleObject

この @ref{5df,,PyObject} のサブタイプは Python のタプルオブジェクトを表現します。
@end deffn

@geindex PyTuple_Type (C var)
@anchor{c-api/tuple c PyTuple_Type}@anchor{50d9}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyTuple_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは Python のタプル型を表現します; Python レイヤにおける @ref{614,,tuple} と同じオブジェクトです。
@end deffn

@geindex PyTuple_Check (C function)
@anchor{c-api/tuple c PyTuple_Check}@anchor{5390}
@deffn {C の関数} int PyTuple_Check (PyObject *p)

`p' がタプルオブジェクトかタプル型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyTuple_CheckExact (C function)
@anchor{c-api/tuple c PyTuple_CheckExact}@anchor{5391}
@deffn {C の関数} int PyTuple_CheckExact (PyObject *p)

`p' がタプルオブジェクトだがタプル型のサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyTuple_New (C function)
@anchor{c-api/tuple c PyTuple_New}@anchor{63e}
@deffn {C の関数} @ref{5df,,PyObject} *PyTuple_New (Py_ssize_t len)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a new tuple object of size `len',
or @code{NULL} with an exception set on failure.
@end deffn

@geindex PyTuple_Pack (C function)
@anchor{c-api/tuple c PyTuple_Pack}@anchor{50d7}
@deffn {C の関数} @ref{5df,,PyObject} *PyTuple_Pack (Py_ssize_t n, ...)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a new tuple object of size `n',
or @code{NULL} with an exception set on failure. The tuple values
are initialized to the subsequent `n' C arguments pointing to Python objects.
@code{PyTuple_Pack(2, a, b)} is equivalent to @code{Py_BuildValue("(OO)", a, b)}.
@end deffn

@geindex PyTuple_Size (C function)
@anchor{c-api/tuple c PyTuple_Size}@anchor{50d8}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyTuple_Size (PyObject *p)
` 次に属します: @ref{775,,Stable ABI}.'
Take a pointer to a tuple object, and return the size of that tuple.
On error, return @code{-1} with an exception set.
@end deffn

@geindex PyTuple_GET_SIZE (C function)
@anchor{c-api/tuple c PyTuple_GET_SIZE}@anchor{5392}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyTuple_GET_SIZE (PyObject *p)

Like @ref{50d8,,PyTuple_Size()}, but without error checking.
@end deffn

@geindex PyTuple_GetItem (C function)
@anchor{c-api/tuple c PyTuple_GetItem}@anchor{4eb7}
@deffn {C の関数} @ref{5df,,PyObject} *PyTuple_GetItem (PyObject *p, Py_ssize_t pos)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
`p' の指すタプルオブジェクト内の、位置 `pos' にあるオブジェクトを返します。 `pos' が負であるか範囲を超えている場合、 @code{NULL} を返して @ref{174e,,IndexError} 例外をセットします。

The returned reference is borrowed from the tuple `p'
(that is: it is only valid as long as you hold a reference to `p').
To get a @ref{5e2,,strong reference}, use
@ref{a9a,,Py_NewRef(PyTuple_GetItem(...))}
or @ref{1e34,,PySequence_GetItem()}.
@end deffn

@geindex PyTuple_GET_ITEM (C function)
@anchor{c-api/tuple c PyTuple_GET_ITEM}@anchor{5393}
@deffn {C の関数} @ref{5df,,PyObject} *PyTuple_GET_ITEM (PyObject *p, Py_ssize_t pos)
`戻り値: 借用参照。'
@ref{4eb7,,PyTuple_GetItem()} に似ていますが、引数に対するエラーチェックを行いません。
@end deffn

@geindex PyTuple_GetSlice (C function)
@anchor{c-api/tuple c PyTuple_GetSlice}@anchor{50d6}
@deffn {C の関数} @ref{5df,,PyObject} *PyTuple_GetSlice (PyObject *p, Py_ssize_t low, Py_ssize_t high)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return the slice of the tuple pointed to by `p' between `low' and `high',
or @code{NULL} with an exception set on failure.

This is the equivalent of the Python expression @code{p[low:high]}.
Indexing from the end of the tuple is not supported.
@end deffn

@geindex PyTuple_SetItem (C function)
@anchor{c-api/tuple c PyTuple_SetItem}@anchor{4eb8}
@deffn {C の関数} int PyTuple_SetItem (PyObject *p, Py_ssize_t pos, PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
`p' の指すタプルオブジェクト内の、位置 `pos' にあるオブジェクトへの参照を入れます。成功すれば @code{0} を返します。 `pos' が範囲を超えている場合、 @code{-1} を返して @ref{174e,,IndexError} 例外をセットします。

@cartouche
@quotation 注釈 
この関数は `o' への参照を "盗み取り" ます。また、変更先のインデクスにすでに別の要素が入っている場合、その要素に対する参照を放棄します。
@end quotation
@end cartouche
@end deffn

@geindex PyTuple_SET_ITEM (C function)
@anchor{c-api/tuple c PyTuple_SET_ITEM}@anchor{62e}
@deffn {C の関数} void PyTuple_SET_ITEM (PyObject *p, Py_ssize_t pos, PyObject *o)

@ref{4eb8,,PyTuple_SetItem()} に似ていますが、エラーチェックを行わず、新たなタプルに値を入れるとき `以外には使ってはなりません' 。

Bounds checking is performed as an assertion if Python is built in
@ref{509,,debug mode} or @ref{62d,,with assertions}.

@cartouche
@quotation 注釈 
この関数は `o' への参照を "盗み取り" ます。また、 @ref{4eb8,,PyTuple_SetItem()} と違って、要素の置き換えが生じても置き換えられるオブジェクトへの参照を放棄 `しません' ; その結果、タプル中の位置 `pos' で参照されていたオブジェクトがメモリリークを引き起こします。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
This macro should `only' be used on tuples that are newly created.
Using this macro on a tuple that is already in use (or in other words, has
a refcount > 1) could lead to undefined behavior.
@end quotation
@end cartouche
@end deffn

@geindex _PyTuple_Resize (C function)
@anchor{c-api/tuple c _PyTuple_Resize}@anchor{1724}
@deffn {C の関数} int _PyTuple_Resize (PyObject **p, Py_ssize_t newsize)

タプルをリサイズする際に使えます。 `newsize' はタプルの新たな長さです。タプルは変更不能なオブジェクト `ということになっている' ので、この関数はこのオブジェクトに対してただ一つしか参照がない時以外には使ってはなりません。タプルがコード中の他の部分ですでに参照されている場合には、この関数を `使ってはなりません' 。タプルは常に指定サイズの末尾まで伸縮します。成功した場合には @code{0} を返します。クライアントコードは、 @code{*p} の値が呼び出し前と同じになると期待してはなりません。 @code{*p} が置き換えられた場合、オリジナルの @code{*p} は破壊されます。失敗すると @code{-1} を返し、 @code{*p} を @code{NULL} に設定して、  @ref{179e,,MemoryError} または @ref{795,,SystemError} を送出します。
@end deffn

@node Struct Sequence オブジェクト,リストオブジェクト,タプルオブジェクト tuple object,シーケンスオブジェクト sequence object
@anchor{c-api/tuple id1}@anchor{5394}@anchor{c-api/tuple struct-sequence-objects}@anchor{13d7}
@subsubsection Struct Sequence オブジェクト


struct sequence オブジェクトは @ref{4e0,,namedtuple()} オブジェクトと等価なC オブジェクトです。 つまり、その要素に属性を通してアクセスすることができるシーケンスです。 struct sequence を生成するには、まず特定のstruct sequence 型を生成しなければなりません。

@geindex PyStructSequence_NewType (C function)
@anchor{c-api/tuple c PyStructSequence_NewType}@anchor{50b9}
@deffn {C の関数} @ref{c9c,,PyTypeObject} *PyStructSequence_NewType (PyStructSequence_Desc *desc)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
後述の `desc' 中のデータから新しい struct sequence 型を生成します。返される型のインスタンスは @ref{50b8,,PyStructSequence_New()} で生成できます。

Return @code{NULL} with an exception set on failure.
@end deffn

@geindex PyStructSequence_InitType (C function)
@anchor{c-api/tuple c PyStructSequence_InitType}@anchor{1204}
@deffn {C の関数} void PyStructSequence_InitType (PyTypeObject *type, PyStructSequence_Desc *desc)

struct sequence 型である `type' を `desc' をもとにその場で初期化します。
@end deffn

@geindex PyStructSequence_InitType2 (C function)
@anchor{c-api/tuple c PyStructSequence_InitType2}@anchor{1205}
@deffn {C の関数} int PyStructSequence_InitType2 (PyTypeObject *type, PyStructSequence_Desc *desc)

Like @ref{1204,,PyStructSequence_InitType()}, but returns @code{0} on success
and @code{-1} with an exception set on failure.


Added in version 3.4.

@end deffn

@geindex PyStructSequence_Desc (C type)
@anchor{c-api/tuple c PyStructSequence_Desc}@anchor{db4}
@deffn {C のデータ型} type PyStructSequence_Desc
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
生成するstruct sequence 型のメタデータを保持します。

@geindex PyStructSequence_Desc.name (C member)
@anchor{c-api/tuple c PyStructSequence_Desc name}@anchor{5395}
@deffn {C のメンバ変数} const char *name

Fully qualified name of the type; null-terminated UTF-8 encoded.
The name must contain the module name.
@end deffn

@geindex PyStructSequence_Desc.doc (C member)
@anchor{c-api/tuple c PyStructSequence_Desc doc}@anchor{5396}
@deffn {C のメンバ変数} const char *doc

Pointer to docstring for the type or @code{NULL} to omit.
@end deffn

@geindex PyStructSequence_Desc.fields (C member)
@anchor{c-api/tuple c PyStructSequence_Desc fields}@anchor{5397}
@deffn {C のメンバ変数} @ref{db3,,PyStructSequence_Field} *fields

Pointer to @code{NULL}-terminated array with field names of the new type.
@end deffn

@geindex PyStructSequence_Desc.n_in_sequence (C member)
@anchor{c-api/tuple c PyStructSequence_Desc n_in_sequence}@anchor{5398}
@deffn {C のメンバ変数} int n_in_sequence

Number of fields visible to the Python side (if used as tuple).
@end deffn
@end deffn

@geindex PyStructSequence_Field (C type)
@anchor{c-api/tuple c PyStructSequence_Field}@anchor{db3}
@deffn {C のデータ型} type PyStructSequence_Field
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
Describes a field of a struct sequence. As a struct sequence is modeled as a
tuple, all fields are typed as @ref{5df,,PyObject}*.  The index in the
@ref{5397,,fields} array of
the @ref{db4,,PyStructSequence_Desc} determines which
field of the struct sequence is described.

@geindex PyStructSequence_Field.name (C member)
@anchor{c-api/tuple c PyStructSequence_Field name}@anchor{5399}
@deffn {C のメンバ変数} const char *name

Name for the field or @code{NULL} to end the list of named fields,
set to @ref{b79,,PyStructSequence_UnnamedField} to leave unnamed.
@end deffn

@geindex PyStructSequence_Field.doc (C member)
@anchor{c-api/tuple c PyStructSequence_Field doc}@anchor{539a}
@deffn {C のメンバ変数} const char *doc

Field docstring or @code{NULL} to omit.
@end deffn
@end deffn

@geindex PyStructSequence_UnnamedField (C var)
@anchor{c-api/tuple c PyStructSequence_UnnamedField}@anchor{b79}
@deffn {C 変数} const char *const PyStructSequence_UnnamedField
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
フィールド名を名前がないままするための特殊な値。


バージョン 3.9 で変更: 型が @code{char *} から変更されました。

@end deffn

@geindex PyStructSequence_New (C function)
@anchor{c-api/tuple c PyStructSequence_New}@anchor{50b8}
@deffn {C の関数} @ref{5df,,PyObject} *PyStructSequence_New (PyTypeObject *type)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`type' のインスタンスを生成します。 `type' は @ref{50b9,,PyStructSequence_NewType()} によって事前に生成していなければなりません。

Return @code{NULL} with an exception set on failure.
@end deffn

@geindex PyStructSequence_GetItem (C function)
@anchor{c-api/tuple c PyStructSequence_GetItem}@anchor{50b7}
@deffn {C の関数} @ref{5df,,PyObject} *PyStructSequence_GetItem (PyObject *p, Py_ssize_t pos)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return the object at position `pos' in the struct sequence pointed to by `p'.

Bounds checking is performed as an assertion if Python is built in
@ref{509,,debug mode} or @ref{62d,,with assertions}.
@end deffn

@geindex PyStructSequence_GET_ITEM (C function)
@anchor{c-api/tuple c PyStructSequence_GET_ITEM}@anchor{539b}
@deffn {C の関数} @ref{5df,,PyObject} *PyStructSequence_GET_ITEM (PyObject *p, Py_ssize_t pos)
`戻り値: 借用参照。'
Alias to @ref{50b7,,PyStructSequence_GetItem()}.


バージョン 3.13 で変更: Now implemented as an alias to @ref{50b7,,PyStructSequence_GetItem()}.

@end deffn

@geindex PyStructSequence_SetItem (C function)
@anchor{c-api/tuple c PyStructSequence_SetItem}@anchor{50ba}
@deffn {C の関数} void PyStructSequence_SetItem (PyObject *p, Py_ssize_t pos, PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
struct sequence `p' の `pos' の位置にあるフィールドに値 `o' を設定します。@ref{62e,,PyTuple_SET_ITEM()} のように、生成したてのインスタンスに対してのみ使用すべきです。

Bounds checking is performed as an assertion if Python is built in
@ref{509,,debug mode} or @ref{62d,,with assertions}.

@cartouche
@quotation 注釈 
この関数は `o' への参照を "盗み取り" ます。
@end quotation
@end cartouche
@end deffn

@geindex PyStructSequence_SET_ITEM (C function)
@anchor{c-api/tuple c PyStructSequence_SET_ITEM}@anchor{539c}
@deffn {C の関数} void PyStructSequence_SET_ITEM (PyObject *p, Py_ssize_t *pos, PyObject *o)

Alias to @ref{50ba,,PyStructSequence_SetItem()}.


バージョン 3.13 で変更: Now implemented as an alias to @ref{50ba,,PyStructSequence_SetItem()}.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node リストオブジェクト,,Struct Sequence オブジェクト,シーケンスオブジェクト sequence object
@anchor{c-api/list doc}@anchor{539d}@anchor{c-api/list list-objects}@anchor{539e}@anchor{c-api/list listobjects}@anchor{539f}@anchor{c-api/list translation-repo}@anchor{53a0}
@subsubsection リストオブジェクト


@geindex object;list

@geindex PyListObject (C type)
@anchor{c-api/list c PyListObject}@anchor{52a8}
@deffn {C のデータ型} type PyListObject

この @ref{5df,,PyObject} のサブタイプは Python のリストオブジェクトを表現します。
@end deffn

@geindex PyList_Type (C var)
@anchor{c-api/list c PyList_Type}@anchor{4edb}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyList_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは Python のリスト型を表現します。これは Python レイヤにおける @ref{24d,,list} と同じオブジェクトです。
@end deffn

@geindex PyList_Check (C function)
@anchor{c-api/list c PyList_Check}@anchor{53a1}
@deffn {C の関数} int PyList_Check (PyObject *p)

`p' がリストオブジェクトかリスト型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyList_CheckExact (C function)
@anchor{c-api/list c PyList_CheckExact}@anchor{53a2}
@deffn {C の関数} int PyList_CheckExact (PyObject *p)

`p' がリストオブジェクトだがリスト型のサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyList_New (C function)
@anchor{c-api/list c PyList_New}@anchor{4f49}
@deffn {C の関数} @ref{5df,,PyObject} *PyList_New (Py_ssize_t len)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
サイズが `len' 新たなリストオブジェクトを返します。
失敗すると @code{NULL} を返します。

@cartouche
@quotation 注釈 
If `len' is greater than zero, the returned list object's items are
set to @code{NULL}. Thus you cannot use abstract API functions such as
@ref{1e35,,PySequence_SetItem()} or expose the object to Python code before
setting all items to a real object with @ref{18ba,,PyList_SetItem()} or
@ref{62f,,PyList_SET_ITEM()}. The following APIs are safe APIs before
the list is fully initialized: @ref{18ba,,PyList_SetItem()} and @ref{62f,,PyList_SET_ITEM()}.
@end quotation
@end cartouche
@end deffn

@geindex PyList_Size (C function)
@anchor{c-api/list c PyList_Size}@anchor{1633}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyList_Size (PyObject *list)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;len

リストオブジェクト `list' の長さを返します; リストオブジェクトにおける @code{len(list)} と同じです。
@end deffn

@geindex PyList_GET_SIZE (C function)
@anchor{c-api/list c PyList_GET_SIZE}@anchor{53a3}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyList_GET_SIZE (PyObject *list)

@ref{1633,,PyList_Size()} に似ていますが、エラーチェックを行いません。
@end deffn

@geindex PyList_GetItemRef (C function)
@anchor{c-api/list c PyList_GetItemRef}@anchor{5fe}
@deffn {C の関数} @ref{5df,,PyObject} *PyList_GetItemRef (PyObject *list, Py_ssize_t index)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return the object at position `index' in the list pointed to by `list'.  The
position must be non-negative; indexing from the end of the list is not
supported.  If `index' is out of bounds (@code{<0 or >=len(list)}),
return @code{NULL} and set an @ref{174e,,IndexError} exception.


Added in version 3.13.

@end deffn

@geindex PyList_GetItem (C function)
@anchor{c-api/list c PyList_GetItem}@anchor{5ff}
@deffn {C の関数} @ref{5df,,PyObject} *PyList_GetItem (PyObject *list, Py_ssize_t index)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
Like @ref{5fe,,PyList_GetItemRef()}, but returns a
@ref{3d7,,borrowed reference} instead of a @ref{5e2,,strong reference}.
@end deffn

@geindex PyList_GET_ITEM (C function)
@anchor{c-api/list c PyList_GET_ITEM}@anchor{4f5f}
@deffn {C の関数} @ref{5df,,PyObject} *PyList_GET_ITEM (PyObject *list, Py_ssize_t i)
`戻り値: 借用参照。'
@ref{5ff,,PyList_GetItem()} に似ていますが、エラーチェックを行いません。
@end deffn

@geindex PyList_SetItem (C function)
@anchor{c-api/list c PyList_SetItem}@anchor{18ba}
@deffn {C の関数} int PyList_SetItem (PyObject *list, Py_ssize_t index, PyObject *item)
` 次に属します: @ref{775,,Stable ABI}.'
リストオブジェクト内の位置 `index' に、オブジェクト `item' を挿入します。
成功した場合には @code{0} を返します。
`index' が範囲を越えている場合、 @code{-1} を返して @ref{174e,,IndexError} をセットします。

@cartouche
@quotation 注釈 
この関数は `item' への参照を "盗み取り" ます。また、変更先のインデクスにすでに別の要素が入っている場合、その要素に対する参照を放棄します。
@end quotation
@end cartouche
@end deffn

@geindex PyList_SET_ITEM (C function)
@anchor{c-api/list c PyList_SET_ITEM}@anchor{62f}
@deffn {C の関数} void PyList_SET_ITEM (PyObject *list, Py_ssize_t i, PyObject *o)

@ref{18ba,,PyList_SetItem()} をマクロによる実装で、エラーチェックを行いません。このマクロは、新たなリストのまだ要素を入れたことのない位置に要素を入れるときにのみ使います。

Bounds checking is performed as an assertion if Python is built in
@ref{509,,debug mode} or @ref{62d,,with assertions}.

@cartouche
@quotation 注釈 
このマクロは `item' への参照を "盗み取り" ます。また、 @ref{18ba,,PyList_SetItem()} と違って、要素の置き換えが生じても置き換えられるオブジェクトへの参照を放棄 `しません' ; その結果、 `list' 中の位置 `i' で参照されていたオブジェクトがメモリリークを引き起こします。
@end quotation
@end cartouche
@end deffn

@geindex PyList_Insert (C function)
@anchor{c-api/list c PyList_Insert}@anchor{18b9}
@deffn {C の関数} int PyList_Insert (PyObject *list, Py_ssize_t index, PyObject *item)
` 次に属します: @ref{775,,Stable ABI}.'
要素 `item' をリスト `list' のインデックス `index' の前に挿入します。成功すると @code{0} を返します。失敗すると @code{-1} を返し、例外をセットします。@code{list.insert(index, item)} に類似した機能です。
@end deffn

@geindex PyList_Append (C function)
@anchor{c-api/list c PyList_Append}@anchor{503f}
@deffn {C の関数} int PyList_Append (PyObject *list, PyObject *item)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `item' を `list' の末尾に追加します。成功すると @code{0} を返します; 失敗すると @code{-1} を返し、例外をセットします。@code{list.append(item)}  に類似した機能です。
@end deffn

@geindex PyList_GetSlice (C function)
@anchor{c-api/list c PyList_GetSlice}@anchor{5041}
@deffn {C の関数} @ref{5df,,PyObject} *PyList_GetSlice (PyObject *list, Py_ssize_t low, Py_ssize_t high)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`list' 内の、`low' から `high' `までの' オブジェクトからなるリストを返します。
失敗すると @code{NULL} を返し、例外をセットします。
@code{list[low:high]} に類似した機能です。
ただし、リストの末尾からのインデックスはサポートされていません。
@end deffn

@geindex PyList_SetSlice (C function)
@anchor{c-api/list c PyList_SetSlice}@anchor{5043}
@deffn {C の関数} int PyList_SetSlice (PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)
` 次に属します: @ref{775,,Stable ABI}.'
`low' から `high' までの `list' のスライスを、 `itemlist' の内容にします。
@code{list[low:high] = itemlist} と類似の機能です。
`itemlist' は @code{NULL} でもよく、空リストの代入 (指定スライスの削除) になります。
成功した場合には @code{0} を、失敗した場合には @code{-1} を返します。
ただし、リストの末尾からのインデックスはサポートされていません。
@end deffn

@geindex PyList_Extend (C function)
@anchor{c-api/list c PyList_Extend}@anchor{600}
@deffn {C の関数} int PyList_Extend (PyObject *list, PyObject *iterable)

Extend `list' with the contents of `iterable'.  This is the same as
@code{PyList_SetSlice(list, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable)}
and analogous to @code{list.extend(iterable)} or @code{list += iterable}.

Raise an exception and return @code{-1} if `list' is not a @ref{24d,,list}
object. Return 0 on success.


Added in version 3.13.

@end deffn

@geindex PyList_Clear (C function)
@anchor{c-api/list c PyList_Clear}@anchor{601}
@deffn {C の関数} int PyList_Clear (PyObject *list)

Remove all items from `list'.  This is the same as
@code{PyList_SetSlice(list, 0, PY_SSIZE_T_MAX, NULL)} and analogous to
@code{list.clear()} or @code{del list[:]}.

Raise an exception and return @code{-1} if `list' is not a @ref{24d,,list}
object.  Return 0 on success.


Added in version 3.13.

@end deffn

@geindex PyList_Sort (C function)
@anchor{c-api/list c PyList_Sort}@anchor{5044}
@deffn {C の関数} int PyList_Sort (PyObject *list)
` 次に属します: @ref{775,,Stable ABI}.'
`list' の内容をインプレースでソートします。成功した場合には @code{0} を、失敗した場合には @code{-1} を返します。@code{list.sort()} と同じです。
@end deffn

@geindex PyList_Reverse (C function)
@anchor{c-api/list c PyList_Reverse}@anchor{5042}
@deffn {C の関数} int PyList_Reverse (PyObject *list)
` 次に属します: @ref{775,,Stable ABI}.'
`list' の要素をインプレースで反転します。成功した場合には @code{0} を、失敗した場合には @code{-1} を返します。@code{list.reverse()} と同じです。
@end deffn

@geindex PyList_AsTuple (C function)
@anchor{c-api/list c PyList_AsTuple}@anchor{5040}
@deffn {C の関数} @ref{5df,,PyObject} *PyList_AsTuple (PyObject *list)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;tuple

`list' の内容が入った新たなタプルオブジェクトを返します; @code{tuple(list)} と同じです。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Container オブジェクト,Function オブジェクト<2>,シーケンスオブジェクト sequence object,具象オブジェクト concrete object レイヤ
@anchor{c-api/concrete container-objects}@anchor{53a4}@anchor{c-api/concrete mapobjects}@anchor{53a5}
@subsection Container オブジェクト


@geindex object;mapping

@menu
* 辞書オブジェクト (dictionary object): 辞書オブジェクト dictionary object. 
* Set オブジェクト:: 

@end menu

@node 辞書オブジェクト dictionary object,Set オブジェクト,,Container オブジェクト
@anchor{c-api/dict doc}@anchor{53a6}@anchor{c-api/dict dictionary-objects}@anchor{53a7}@anchor{c-api/dict dictobjects}@anchor{53a8}
@subsubsection 辞書オブジェクト (dictionary object)


@geindex object;dictionary

@geindex PyDictObject (C type)
@anchor{c-api/dict c PyDictObject}@anchor{64f}
@deffn {C のデータ型} type PyDictObject

この @ref{5df,,PyObject} のサブタイプは Python の辞書オブジェクトを表現します。
@end deffn

@geindex PyDict_Type (C var)
@anchor{c-api/dict c PyDict_Type}@anchor{4fc6}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDict_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは Python の辞書を表現します。このオブジェクトは、Python レイヤにおける @ref{183,,dict} と同じオブジェクトです。
@end deffn

@geindex PyDict_Check (C function)
@anchor{c-api/dict c PyDict_Check}@anchor{52d5}
@deffn {C の関数} int PyDict_Check (PyObject *p)

`p' が辞書オブジェクトか辞書型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyDict_CheckExact (C function)
@anchor{c-api/dict c PyDict_CheckExact}@anchor{53a9}
@deffn {C の関数} int PyDict_CheckExact (PyObject *p)

`p' が辞書オブジェクトだが辞書型のサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyDict_New (C function)
@anchor{c-api/dict c PyDict_New}@anchor{4fc4}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_New ()
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
空の新たな辞書を返します。
失敗すると @code{NULL} を返します。
@end deffn

@geindex PyDictProxy_New (C function)
@anchor{c-api/dict c PyDictProxy_New}@anchor{4fb7}
@deffn {C の関数} @ref{5df,,PyObject} *PyDictProxy_New (PyObject *mapping)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
あるマップ型オブジェクトに対して、読み出し専用に制限された @ref{698,,types.MappingProxyType} オブジェクトを返します。通常、この関数は動的でないクラス型 (non-dynamic class type) のクラス辞書が変更されないようにビューを作成するために使われます。
@end deffn

@geindex PyDictProxy_Type (C var)
@anchor{c-api/dict c PyDictProxy_Type}@anchor{4fb8}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictProxy_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for mapping proxy objects created by
@ref{4fb7,,PyDictProxy_New()} and for the read-only @code{__dict__} attribute
of many built-in types. A @ref{4fb8,,PyDictProxy_Type} instance provides a
dynamic, read-only view of an underlying dictionary: changes to the
underlying dictionary are reflected in the proxy, but the proxy itself
does not support mutation operations. This corresponds to
@ref{698,,types.MappingProxyType} in Python.
@end deffn

@geindex PyDict_Clear (C function)
@anchor{c-api/dict c PyDict_Clear}@anchor{4fbd}
@deffn {C の関数} void PyDict_Clear (PyObject *p)
` 次に属します: @ref{775,,Stable ABI}.'
現在辞書に入っている全てのキーと値のペアを除去して空にします。
@end deffn

@geindex PyDict_Contains (C function)
@anchor{c-api/dict c PyDict_Contains}@anchor{5de}
@deffn {C の関数} int PyDict_Contains (PyObject *p, PyObject *key)
` 次に属します: @ref{775,,Stable ABI}.'
Determine if dictionary `p' contains `key'.  If an item in `p' matches
`key', return @code{1}, otherwise return @code{0}.  On error, return @code{-1}.
This is equivalent to the Python expression @code{key in p}.
@end deffn

@geindex PyDict_ContainsString (C function)
@anchor{c-api/dict c PyDict_ContainsString}@anchor{5dd}
@deffn {C の関数} int PyDict_ContainsString (PyObject *p, const char *key)

This is the same as @ref{5de,,PyDict_Contains()}, but `key' is specified as a
const char* UTF-8 encoded bytes string, rather than a
@ref{5df,,PyObject}*.


Added in version 3.13.

@end deffn

@geindex PyDict_Copy (C function)
@anchor{c-api/dict c PyDict_Copy}@anchor{662}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_Copy (PyObject *p)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`p' と同じキーと値のペアが入った新たな辞書を返します。
@end deffn

@geindex PyDict_SetItem (C function)
@anchor{c-api/dict c PyDict_SetItem}@anchor{4eb9}
@deffn {C の関数} int PyDict_SetItem (PyObject *p, PyObject *key, PyObject *val)
` 次に属します: @ref{775,,Stable ABI}.'
辞書 `p' に、 `key' をキーとして値 `val' を挿入します。
`key' はハッシュ可能(@ref{824,,hashable})でなければなりません。ハッシュ可能でない場合、 @ref{198,,TypeError} を送出します。
成功した場合には @code{0} を、失敗した場合には @code{-1} を返します。
この関数は `val' への参照を盗み取り `ません'。
@end deffn

@geindex PyDict_SetItemString (C function)
@anchor{c-api/dict c PyDict_SetItemString}@anchor{198d}
@deffn {C の関数} int PyDict_SetItemString (PyObject *p, const char *key, PyObject *val)
` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{4eb9,,PyDict_SetItem()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.
@end deffn

@geindex PyDict_DelItem (C function)
@anchor{c-api/dict c PyDict_DelItem}@anchor{4fbe}
@deffn {C の関数} int PyDict_DelItem (PyObject *p, PyObject *key)
` 次に属します: @ref{775,,Stable ABI}.'
辞書 `p' から `key' をキーとするエントリを除去します。 `key' は @ref{824,,ハッシュ可能} でなければなりません;  ハッシュ可能でない場合、 @ref{198,,TypeError} を送出します。`key' が辞書になければ、@ref{5e7,,KeyError} を送出します。成功した場合には @code{0} を、失敗した場合には @code{-1} を返します。
@end deffn

@geindex PyDict_DelItemString (C function)
@anchor{c-api/dict c PyDict_DelItemString}@anchor{4fbf}
@deffn {C の関数} int PyDict_DelItemString (PyObject *p, const char *key)
` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{4fbe,,PyDict_DelItem()}, but `key' is
specified as a const char* UTF-8 encoded bytes string,
rather than a @ref{5df,,PyObject}*.
@end deffn

@geindex PyDict_GetItemRef (C function)
@anchor{c-api/dict c PyDict_GetItemRef}@anchor{5e0}
@deffn {C の関数} int PyDict_GetItemRef (PyObject *p, PyObject *key, PyObject **result)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return a new @ref{5e2,,strong reference} to the object from dictionary `p'
which has a key `key':


@itemize *

@item 
If the key is present, set `*result' to a new @ref{5e2,,strong reference}
to the value and return @code{1}.

@item 
If the key is missing, set `*result' to @code{NULL} and return @code{0}.

@item 
エラーの場合例外を送出し @code{-1} を返します。
@end itemize


Added in version 3.13.


See also the @ref{5ea,,PyObject_GetItem()} function.
@end deffn

@geindex PyDict_GetItem (C function)
@anchor{c-api/dict c PyDict_GetItem}@anchor{628}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_GetItem (PyObject *p, PyObject *key)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a @ref{3d7,,borrowed reference} to the object from dictionary `p' which
has a key `key'.  Return @code{NULL} if the key `key' is missing `without'
setting an exception.

@cartouche
@quotation 注釈 
Exceptions that occur while this calls @ref{cf3,,__hash__()} and
@ref{cf2,,__eq__()} methods are silently ignored.
Prefer the @ref{5e1,,PyDict_GetItemWithError()} function instead.
@end quotation
@end cartouche


バージョン 3.10 で変更: Calling this API without an @ref{4ed1,,attached thread state} had been allowed for historical
reason. It is no longer allowed.

@end deffn

@geindex PyDict_GetItemWithError (C function)
@anchor{c-api/dict c PyDict_GetItemWithError}@anchor{5e1}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_GetItemWithError (PyObject *p, PyObject *key)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{628,,PyDict_GetItem()} の変種で例外を隠しません。
例外が発生した場合は、例外をセット `した上で' @code{NULL} を返します。
キーが存在しなかった場合は、例外をセット `せずに' @code{NULL} を返します。
@end deffn

@geindex PyDict_GetItemString (C function)
@anchor{c-api/dict c PyDict_GetItemString}@anchor{629}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_GetItemString (PyObject *p, const char *key)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
This is the same as @ref{628,,PyDict_GetItem()}, but `key' is specified as a
const char* UTF-8 encoded bytes string, rather than a
@ref{5df,,PyObject}*.

@cartouche
@quotation 注釈 
Exceptions that occur while this calls @ref{cf3,,__hash__()} and
@ref{cf2,,__eq__()} methods or while creating the temporary @ref{169,,str}
object are silently ignored.
Prefer using the @ref{5e1,,PyDict_GetItemWithError()} function with your own
@ref{5112,,PyUnicode_FromString()} `key' instead.
@end quotation
@end cartouche
@end deffn

@geindex PyDict_GetItemStringRef (C function)
@anchor{c-api/dict c PyDict_GetItemStringRef}@anchor{421}
@deffn {C の関数} int PyDict_GetItemStringRef (PyObject *p, const char *key, PyObject **result)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Similar to @ref{5e0,,PyDict_GetItemRef()}, but `key' is specified as a
const char* UTF-8 encoded bytes string, rather than a
@ref{5df,,PyObject}*.


Added in version 3.13.

@end deffn

@geindex PyDict_SetDefault (C function)
@anchor{c-api/dict c PyDict_SetDefault}@anchor{5e4}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_SetDefault (PyObject *p, PyObject *key, PyObject *defaultobj)
`戻り値: 借用参照。'
これは Python レベルの @ref{1285,,dict.setdefault()} と同じです。
もしあれば、辞書 `p' から `key' に対応する値を返します。
キーが辞書になければ、値 `defaultobj' を挿入し `defaultobj' を返します。
この関数は、 `key' のハッシュ値を検索と挿入ごとに別々に評価するのではなく、一度だけしか評価しません。


Added in version 3.4.

@end deffn

@geindex PyDict_SetDefaultRef (C function)
@anchor{c-api/dict c PyDict_SetDefaultRef}@anchor{5e3}
@deffn {C の関数} int PyDict_SetDefaultRef (PyObject *p, PyObject *key, PyObject *default_value, PyObject **result)

Inserts `default_value' into the dictionary `p' with a key of `key' if the
key is not already present in the dictionary. If `result' is not @code{NULL},
then `*result' is set to a @ref{5e2,,strong reference} to either
`default_value', if the key was not present, or the existing value, if `key'
was already present in the dictionary.
Returns @code{1} if the key was present and `default_value' was not inserted,
or @code{0} if the key was not present and `default_value' was inserted.
On failure, returns @code{-1}, sets an exception, and sets @code{*result}
to @code{NULL}.

For clarity: if you have a strong reference to `default_value' before
calling this function, then after it returns, you hold a strong reference
to both `default_value' and `*result' (if it's not @code{NULL}).
These may refer to the same object: in that case you hold two separate
references to it.


Added in version 3.13.

@end deffn

@geindex PyDict_Pop (C function)
@anchor{c-api/dict c PyDict_Pop}@anchor{422}
@deffn {C の関数} int PyDict_Pop (PyObject *p, PyObject *key, PyObject **result)

Remove `key' from dictionary `p' and optionally return the removed value.
Do not raise @ref{5e7,,KeyError} if the key is missing.


@itemize -

@item 
If the key is present, set `*result' to a new reference to the removed
value if `result' is not @code{NULL}, and return @code{1}.

@item 
If the key is missing, set `*result' to @code{NULL} if `result' is not
@code{NULL}, and return @code{0}.

@item 
エラーの場合例外を送出し @code{-1} を返します。
@end itemize

Similar to @ref{5e6,,dict.pop()}, but without the default value and
not raising @ref{5e7,,KeyError} if the key is missing.


Added in version 3.13.

@end deffn

@geindex PyDict_PopString (C function)
@anchor{c-api/dict c PyDict_PopString}@anchor{5e5}
@deffn {C の関数} int PyDict_PopString (PyObject *p, const char *key, PyObject **result)

Similar to @ref{422,,PyDict_Pop()}, but `key' is specified as a
const char* UTF-8 encoded bytes string, rather than a
@ref{5df,,PyObject}*.


Added in version 3.13.

@end deffn

@geindex PyDict_Items (C function)
@anchor{c-api/dict c PyDict_Items}@anchor{4fc0}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_Items (PyObject *p)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
辞書内の全ての要素対が入った @ref{52a8,,PyListObject} を返します。
@end deffn

@geindex PyDict_Keys (C function)
@anchor{c-api/dict c PyDict_Keys}@anchor{4fc1}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_Keys (PyObject *p)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
辞書内の全てのキーが入った @ref{52a8,,PyListObject} を返します。
@end deffn

@geindex PyDict_Values (C function)
@anchor{c-api/dict c PyDict_Values}@anchor{4fc8}
@deffn {C の関数} @ref{5df,,PyObject} *PyDict_Values (PyObject *p)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
辞書 `p' 内の全ての値が入った @ref{52a8,,PyListObject} を返します。
@end deffn

@geindex PyDict_Size (C function)
@anchor{c-api/dict c PyDict_Size}@anchor{4fc5}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyDict_Size (PyObject *p)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;len

辞書内の要素の数を返します。辞書に対して @code{len(p)} を実行するのと同じです。
@end deffn

@geindex PyDict_GET_SIZE (C function)
@anchor{c-api/dict c PyDict_GET_SIZE}@anchor{53aa}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyDict_GET_SIZE (PyObject *p)

Similar to @ref{4fc5,,PyDict_Size()}, but without error checking.
@end deffn

@geindex PyDict_Next (C function)
@anchor{c-api/dict c PyDict_Next}@anchor{198f}
@deffn {C の関数} int PyDict_Next (PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
` 次に属します: @ref{775,,Stable ABI}.'
辞書 `p' 内の全てのキー/値のペアにわたる反復処理を行います。
`ppos' が参照している @ref{c55,,Py_ssize_t} 型は、この関数で反復処理を開始する際に、最初に関数を呼び出すよりも前に @code{0} に初期化しておかなければなりません。この関数は辞書内の各ペアを取り上げるごとに真を返し、全てのペアを取り上げたことが分かると偽を返します。
パラメーター `pkey' および `pvalue' には、それぞれ辞書の各々のキーと値が埋められた @ref{5df,,PyObject}* 変数を指すポインタか、または @code{NULL} が入ります。
この関数から返される参照はすべて借用参照になります。
反復処理中に `ppos' を変更してはなりません。
この値は内部的な辞書構造体のオフセットを表現しており、構造体はスパースなので、オフセットの値に一貫性がないためです。

例えば:

@example
PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) @{
    /* do something interesting with the values... */
    ...
@}
@end example

反復処理中に辞書 `p' を変更してはなりません。辞書を反復処理する際に、キーに対応する値を変更しても大丈夫になりましたが、キーの集合を変更しないことが前提です。以下に例を示します:

@example
PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) @{
    long i = PyLong_AsLong(value);
    if (i == -1 && PyErr_Occurred()) @{
        return -1;
    @}
    PyObject *o = PyLong_FromLong(i + 1);
    if (o == NULL)
        return -1;
    if (PyDict_SetItem(self->dict, key, o) < 0) @{
        Py_DECREF(o);
        return -1;
    @}
    Py_DECREF(o);
@}
@end example

The function is not thread-safe in the @ref{1f4,,free-threaded}
build without external synchronization.  You can use
@ref{53ab,,Py_BEGIN_CRITICAL_SECTION} to lock the dictionary while iterating
over it:

@example
Py_BEGIN_CRITICAL_SECTION(self->dict);
while (PyDict_Next(self->dict, &pos, &key, &value)) @{
    ...
@}
Py_END_CRITICAL_SECTION();
@end example

@cartouche
@quotation 注釈 
On the free-threaded build, this function can be used safely inside a
critical section. However, the references returned for `pkey' and `pvalue'
are @ref{3d7,,borrowed} and are only valid while the
critical section is held. If you need to use these objects outside the
critical section or when the critical section can be suspended, create a
@ref{5e2,,strong reference} (for example, using
@ref{a9a,,Py_NewRef()}).
@end quotation
@end cartouche
@end deffn

@geindex PyDict_Merge (C function)
@anchor{c-api/dict c PyDict_Merge}@anchor{4fc2}
@deffn {C の関数} int PyDict_Merge (PyObject *a, PyObject *b, int override)
` 次に属します: @ref{775,,Stable ABI}.'
マップ型オブジェクト `b' の全ての要素にわたって、反復的にキー/値のペアを辞書 `a' に追加します。 `b' は辞書か、 @ref{db5,,PyMapping_Keys()} または @ref{5ea,,PyObject_GetItem()} をサポートする何らかのオブジェクトにできます。 `override' が真ならば、 `a' のキーと一致するキーが `b' にある際に、既存のペアを置き換えます。それ以外の場合は、 `b' のキーに一致するキーが `a' にないときのみ追加を行います。成功した場合には @code{0} を返し、例外が送出された場合には @code{-1} を返します。
@end deffn

@geindex PyDict_Update (C function)
@anchor{c-api/dict c PyDict_Update}@anchor{4fc7}
@deffn {C の関数} int PyDict_Update (PyObject *a, PyObject *b)
` 次に属します: @ref{775,,Stable ABI}.'
C で表せば @code{PyDict_Merge(a, b, 1)} と同じで、また Python の @code{a.update(b)} と似ていますが、 @ref{4fc7,,PyDict_Update()} は第二引数が "keys" 属性を持たない場合にキー/値ペアのシーケンスを反復することはありません。成功した場合には @code{0} を返し、例外が送出された場合には @code{-1} を返します。
@end deffn

@geindex PyDict_MergeFromSeq2 (C function)
@anchor{c-api/dict c PyDict_MergeFromSeq2}@anchor{4fc3}
@deffn {C の関数} int PyDict_MergeFromSeq2 (PyObject *a, PyObject *seq2, int override)
` 次に属します: @ref{775,,Stable ABI}.'
`seq2' 内のキー/値ペアを使って、辞書 `a' の内容を更新したり統合したりします。`seq2' は、キー/値のペアとみなせる長さ 2 の反復可能オブジェクト(iterable object) を生成する反復可能オブジェクトでなければなりません。重複するキーが存在する場合、`override' が真ならば先に出現したキーを使い、そうでない場合は後に出現したキーを使います。成功した場合には @code{0} を返し、例外が送出された場合には @code{-1} を返します。(戻り値以外は) 等価な Python コードを書くと、以下のようになります:

@example
def PyDict_MergeFromSeq2(a, seq2, override):
    for key, value in seq2:
        if override or key not in a:
            a[key] = value
@end example
@end deffn

@geindex PyDict_AddWatcher (C function)
@anchor{c-api/dict c PyDict_AddWatcher}@anchor{3d0}
@deffn {C の関数} int PyDict_AddWatcher (PyDict_WatchCallback callback)

Register `callback' as a dictionary watcher. Return a non-negative integer
id which must be passed to future calls to @ref{784,,PyDict_Watch()}. In case
of error (e.g. no more watcher IDs available), return @code{-1} and set an
exception.


Added in version 3.12.

@end deffn

@geindex PyDict_ClearWatcher (C function)
@anchor{c-api/dict c PyDict_ClearWatcher}@anchor{53ac}
@deffn {C の関数} int PyDict_ClearWatcher (int watcher_id)

Clear watcher identified by `watcher_id' previously returned from
@ref{3d0,,PyDict_AddWatcher()}. Return @code{0} on success, @code{-1} on error (e.g.
if the given `watcher_id' was never registered.)


Added in version 3.12.

@end deffn

@geindex PyDict_Watch (C function)
@anchor{c-api/dict c PyDict_Watch}@anchor{784}
@deffn {C の関数} int PyDict_Watch (int watcher_id, PyObject *dict)

Mark dictionary `dict' as watched. The callback granted `watcher_id' by
@ref{3d0,,PyDict_AddWatcher()} will be called when `dict' is modified or
deallocated. Return @code{0} on success or @code{-1} on error.


Added in version 3.12.

@end deffn

@geindex PyDict_Unwatch (C function)
@anchor{c-api/dict c PyDict_Unwatch}@anchor{53ad}
@deffn {C の関数} int PyDict_Unwatch (int watcher_id, PyObject *dict)

Mark dictionary `dict' as no longer watched. The callback granted
`watcher_id' by @ref{3d0,,PyDict_AddWatcher()} will no longer be called when
`dict' is modified or deallocated. The dict must previously have been
watched by this watcher. Return @code{0} on success or @code{-1} on error.


Added in version 3.12.

@end deffn

@geindex PyDict_WatchEvent (C type)
@anchor{c-api/dict c PyDict_WatchEvent}@anchor{53ae}
@deffn {C のデータ型} type PyDict_WatchEvent

Enumeration of possible dictionary watcher events: @code{PyDict_EVENT_ADDED},
@code{PyDict_EVENT_MODIFIED}, @code{PyDict_EVENT_DELETED}, @code{PyDict_EVENT_CLONED},
@code{PyDict_EVENT_CLEARED}, or @code{PyDict_EVENT_DEALLOCATED}.


Added in version 3.12.

@end deffn

@geindex PyDict_WatchCallback (C type)
@anchor{c-api/dict c PyDict_WatchCallback}@anchor{53af}
@deffn {C のデータ型} typedef int (*PyDict_WatchCallback)(@ref{53ae,,PyDict_WatchEvent} event, @ref{5df,,PyObject} *dict, @ref{5df,,PyObject} *key, @ref{5df,,PyObject} *new_value)

Type of a dict watcher callback function.

If `event' is @code{PyDict_EVENT_CLEARED} or @code{PyDict_EVENT_DEALLOCATED}, both
`key' and `new_value' will be @code{NULL}. If `event' is @code{PyDict_EVENT_ADDED}
or @code{PyDict_EVENT_MODIFIED}, `new_value' will be the new value for `key'.
If `event' is @code{PyDict_EVENT_DELETED}, `key' is being deleted from the
dictionary and `new_value' will be @code{NULL}.

@code{PyDict_EVENT_CLONED} occurs when `dict' was previously empty and another
dict is merged into it. To maintain efficiency of this operation, per-key
@code{PyDict_EVENT_ADDED} events are not issued in this case; instead a
single @code{PyDict_EVENT_CLONED} is issued, and `key' will be the source
dictionary.

The callback may inspect but must not modify `dict'; doing so could have
unpredictable effects, including infinite recursion. Do not trigger Python
code execution in the callback, as it could modify the dict as a side effect.

If `event' is @code{PyDict_EVENT_DEALLOCATED}, taking a new reference in the
callback to the about-to-be-destroyed dictionary will resurrect it and
prevent it from being freed at this time. When the resurrected object is
destroyed later, any watcher callbacks active at that time will be called
again.

Callbacks occur before the notified modification to `dict' takes place, so
the prior state of `dict' can be inspected.

If the callback sets an exception, it must return @code{-1}; this exception will
be printed as an unraisable exception using @ref{5f2,,PyErr_WriteUnraisable()}.
Otherwise it should return @code{0}.

There may already be a pending exception set on entry to the callback. In
this case, the callback should return @code{0} with the same exception still
set. This means the callback may not call any other API that can set an
exception unless it saves and clears the exception state first, and restores
it before returning.


Added in version 3.12.

@end deffn

@menu
* Dictionary View Objects:: 
* Ordered Dictionaries:: 

@end menu

@node Dictionary View Objects,Ordered Dictionaries,,辞書オブジェクト dictionary object
@anchor{c-api/dict dictionary-view-objects}@anchor{53b0}
@subsubsection Dictionary View Objects


@geindex PyDictViewSet_Check (C function)
@anchor{c-api/dict c PyDictViewSet_Check}@anchor{53b1}
@deffn {C の関数} int PyDictViewSet_Check (PyObject *op)

Return true if `op' is a view of a set inside a dictionary. This is currently
equivalent to @ref{53b2,,PyDictKeys_Check}(@ref{53b1,,op}) || @ref{53b3,,PyDictItems_Check}(@ref{53b1,,op}). This
function always succeeds.
@end deffn

@geindex PyDictKeys_Type (C var)
@anchor{c-api/dict c PyDictKeys_Type}@anchor{4fb6}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictKeys_Type
` 次に属します: @ref{775,,Stable ABI}.'
Type object for a view of dictionary keys. In Python, this is the type of
the object returned by @ref{9d0,,dict.keys()}.
@end deffn

@geindex PyDictKeys_Check (C function)
@anchor{c-api/dict c PyDictKeys_Check}@anchor{53b2}
@deffn {C の関数} int PyDictKeys_Check (PyObject *op)

Return true if `op' is an instance of a dictionary keys view. This function
always succeeds.
@end deffn

@geindex PyDictValues_Type (C var)
@anchor{c-api/dict c PyDictValues_Type}@anchor{4fbc}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictValues_Type
` 次に属します: @ref{775,,Stable ABI}.'
Type object for a view of dictionary values. In Python, this is the type of
the object returned by @ref{9d1,,dict.values()}.
@end deffn

@geindex PyDictValues_Check (C function)
@anchor{c-api/dict c PyDictValues_Check}@anchor{53b4}
@deffn {C の関数} int PyDictValues_Check (PyObject *op)

Return true if `op' is an instance of a dictionary values view. This function
always succeeds.
@end deffn

@geindex PyDictItems_Type (C var)
@anchor{c-api/dict c PyDictItems_Type}@anchor{4fb2}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictItems_Type
` 次に属します: @ref{775,,Stable ABI}.'
Type object for a view of dictionary items. In Python, this is the type of
the object returned by @ref{9d2,,dict.items()}.
@end deffn

@geindex PyDictItems_Check (C function)
@anchor{c-api/dict c PyDictItems_Check}@anchor{53b3}
@deffn {C の関数} int PyDictItems_Check (PyObject *op)

Return true if `op' is an instance of a dictionary items view. This function
always succeeds.
@end deffn

@node Ordered Dictionaries,,Dictionary View Objects,辞書オブジェクト dictionary object
@anchor{c-api/dict ordered-dictionaries}@anchor{53b5}
@subsubsection Ordered Dictionaries


Python's C API provides interface for @ref{7f3,,collections.OrderedDict} from C.
Since Python 3.7, dictionaries are ordered by default, so there is usually
little need for these functions; prefer @code{PyDict*} where possible.

@geindex PyODict_Type (C var)
@anchor{c-api/dict c PyODict_Type}@anchor{53b6}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyODict_Type

Type object for ordered dictionaries. This is the same object as
@ref{7f3,,collections.OrderedDict} in the Python layer.
@end deffn

@geindex PyODict_Check (C function)
@anchor{c-api/dict c PyODict_Check}@anchor{53b7}
@deffn {C の関数} int PyODict_Check (PyObject *od)

Return true if `od' is an ordered dictionary object or an instance of a
subtype of the @ref{7f3,,OrderedDict} type.  This function
always succeeds.
@end deffn

@geindex PyODict_CheckExact (C function)
@anchor{c-api/dict c PyODict_CheckExact}@anchor{53b8}
@deffn {C の関数} int PyODict_CheckExact (PyObject *od)

Return true if `od' is an ordered dictionary object, but not an instance of
a subtype of the @ref{7f3,,OrderedDict} type.
This function always succeeds.
@end deffn

@geindex PyODictKeys_Type (C var)
@anchor{c-api/dict c PyODictKeys_Type}@anchor{53b9}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyODictKeys_Type

Analogous to @ref{4fb6,,PyDictKeys_Type} for ordered dictionaries.
@end deffn

@geindex PyODictValues_Type (C var)
@anchor{c-api/dict c PyODictValues_Type}@anchor{53ba}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyODictValues_Type

Analogous to @ref{4fbc,,PyDictValues_Type} for ordered dictionaries.
@end deffn

@geindex PyODictItems_Type (C var)
@anchor{c-api/dict c PyODictItems_Type}@anchor{53bb}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyODictItems_Type

Analogous to @ref{4fb2,,PyDictItems_Type} for ordered dictionaries.
@end deffn

@geindex PyODict_New (C function)
@anchor{c-api/dict c PyODict_New}@anchor{53bc}
@deffn {C の関数} @ref{5df,,PyObject} *PyODict_New (void)

Return a new empty ordered dictionary, or @code{NULL} on failure.

This is analogous to @ref{4fc4,,PyDict_New()}.
@end deffn

@geindex PyODict_SetItem (C function)
@anchor{c-api/dict c PyODict_SetItem}@anchor{53bd}
@deffn {C の関数} int PyODict_SetItem (PyObject *od, PyObject *key, PyObject *value)

Insert `value' into the ordered dictionary `od' with a key of `key'.
Return @code{0} on success or @code{-1} with an exception set on failure.

This is analogous to @ref{4eb9,,PyDict_SetItem()}.
@end deffn

@geindex PyODict_DelItem (C function)
@anchor{c-api/dict c PyODict_DelItem}@anchor{53be}
@deffn {C の関数} int PyODict_DelItem (PyObject *od, PyObject *key)

Remove the entry in the ordered dictionary `od' with key `key'.
Return @code{0} on success or @code{-1} with an exception set on failure.

This is analogous to @ref{4fbe,,PyDict_DelItem()}.
@end deffn

These are @ref{23d,,soft deprecated} aliases to @code{PyDict} APIs:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@code{PyODict}

@tab

@code{PyDict}

@item

@geindex PyODict_GetItem (C macro)
@anchor{c-api/dict c PyODict_GetItem}@anchor{53bf}
@deffn {C のマクロ} PyODict_GetItem (od, key)
@end deffn

@tab

@ref{628,,PyDict_GetItem()}

@item

@geindex PyODict_GetItemWithError (C macro)
@anchor{c-api/dict c PyODict_GetItemWithError}@anchor{53c0}
@deffn {C のマクロ} PyODict_GetItemWithError (od, key)
@end deffn

@tab

@ref{5e1,,PyDict_GetItemWithError()}

@item

@geindex PyODict_GetItemString (C macro)
@anchor{c-api/dict c PyODict_GetItemString}@anchor{53c1}
@deffn {C のマクロ} PyODict_GetItemString (od, key)
@end deffn

@tab

@ref{629,,PyDict_GetItemString()}

@item

@geindex PyODict_Contains (C macro)
@anchor{c-api/dict c PyODict_Contains}@anchor{53c2}
@deffn {C のマクロ} PyODict_Contains (od, key)
@end deffn

@tab

@ref{5de,,PyDict_Contains()}

@item

@geindex PyODict_Size (C macro)
@anchor{c-api/dict c PyODict_Size}@anchor{53c3}
@deffn {C のマクロ} PyODict_Size (od)
@end deffn

@tab

@ref{4fc5,,PyDict_Size()}

@item

@geindex PyODict_SIZE (C macro)
@anchor{c-api/dict c PyODict_SIZE}@anchor{53c4}
@deffn {C のマクロ} PyODict_SIZE (od)
@end deffn

@tab

@ref{53aa,,PyDict_GET_SIZE()}

@end multitable


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Set オブジェクト,,辞書オブジェクト dictionary object,Container オブジェクト
@anchor{c-api/set doc}@anchor{53c5}@anchor{c-api/set set-objects}@anchor{53c6}@anchor{c-api/set setobjects}@anchor{53c7}@anchor{c-api/set translation-repo}@anchor{53c8}
@subsubsection Set オブジェクト


@geindex object;集合
@geindex object;frozenset

このセクションでは @ref{184,,set} と @ref{7f2,,frozenset} の公開 API について詳しく述べます。以降で説明していない機能は、抽象オブジェクトプロトコル (@ref{640,,PyObject_CallMethod()}, @ref{1d8c,,PyObject_RichCompareBool()}, @ref{436,,PyObject_Hash()}, @ref{1230,,PyObject_Repr()}, @ref{5093,,PyObject_IsTrue()}, @ref{198b,,PyObject_Print()}, @ref{5092,,PyObject_GetIter()} を含む) か抽象数値プロトコル (@ref{5066,,PyNumber_And()}, @ref{507f,,PyNumber_Subtract()}, @ref{507a,,PyNumber_Or()}, @ref{5081,,PyNumber_Xor()}, @ref{506b,,PyNumber_InPlaceAnd()}, @ref{5073,,PyNumber_InPlaceSubtract()}, @ref{506f,,PyNumber_InPlaceOr()}, @ref{5075,,PyNumber_InPlaceXor()} を含む) を使って利用できます。

@geindex PySetObject (C type)
@anchor{c-api/set c PySetObject}@anchor{53c9}
@deffn {C のデータ型} type PySetObject

この @ref{5df,,PyObject} を継承した型は、 @ref{184,,set} と @ref{7f2,,frozenset} 両方の内部データを保存するのに用いられます。 @ref{64f,,PyDictObject} と同じように、小さい集合(set)に対しては(タプルのように)固定サイズであり、そうでない集合に対しては(リストと同じように)可変長のメモリブロックを用います。この構造体のどのフィールドも、公開されていると考えるべきではなく、変更される可能性があります。すべてのアクセスは、構造体の中の値を直接操作するのではなく、ドキュメントされた API を用いて行うべきです。
@end deffn

@geindex PySet_Type (C var)
@anchor{c-api/set c PySet_Type}@anchor{50b0}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PySet_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは、Python の @ref{184,,set} 型を表します。
@end deffn

@geindex PyFrozenSet_Type (C var)
@anchor{c-api/set c PyFrozenSet_Type}@anchor{502c}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyFrozenSet_Type
` 次に属します: @ref{775,,Stable ABI}.'
この @ref{c9c,,PyTypeObject} のインスタンスは、Python の @ref{7f2,,frozenset} 型を表します。
@end deffn

以降の型チェックマクロはすべての Python オブジェクトに対するポインタに対して動作します。同様に、コンストラクタはすべてのイテレート可能な Python オブジェクトに対して動作します。

@geindex PySet_Check (C function)
@anchor{c-api/set c PySet_Check}@anchor{53ca}
@deffn {C の関数} int PySet_Check (PyObject *p)

`p' が @ref{184,,set} かそのサブタイプのオブジェクトであるときに true を返します。この関数は常に成功します。
@end deffn

@geindex PyFrozenSet_Check (C function)
@anchor{c-api/set c PyFrozenSet_Check}@anchor{53cb}
@deffn {C の関数} int PyFrozenSet_Check (PyObject *p)

`p' が @ref{7f2,,frozenset} かそのサブタイプのオブジェクトであるときに true を返します。この関数は常に成功します。
@end deffn

@geindex PyAnySet_Check (C function)
@anchor{c-api/set c PyAnySet_Check}@anchor{53cc}
@deffn {C の関数} int PyAnySet_Check (PyObject *p)

`p' が @ref{184,,set} か @ref{7f2,,frozenset} 、あるいはそのサブタイプのオブジェクトであれば、true を返します。この関数は常に成功します。
@end deffn

@geindex PySet_CheckExact (C function)
@anchor{c-api/set c PySet_CheckExact}@anchor{a9d}
@deffn {C の関数} int PySet_CheckExact (PyObject *p)

`p' が @ref{184,,set} オブジェクトだがサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。


Added in version 3.10.

@end deffn

@geindex PyAnySet_CheckExact (C function)
@anchor{c-api/set c PyAnySet_CheckExact}@anchor{53cd}
@deffn {C の関数} int PyAnySet_CheckExact (PyObject *p)

`p' が @ref{184,,set} か @ref{7f2,,frozenset} のどちらかのオブジェクトであるときに true を返します。サブタイプのオブジェクトは含みません。この関数は常に成功します。
@end deffn

@geindex PyFrozenSet_CheckExact (C function)
@anchor{c-api/set c PyFrozenSet_CheckExact}@anchor{53ce}
@deffn {C の関数} int PyFrozenSet_CheckExact (PyObject *p)

`p' が @ref{7f2,,frozenset} オブジェクトだがサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PySet_New (C function)
@anchor{c-api/set c PySet_New}@anchor{165d}
@deffn {C の関数} @ref{5df,,PyObject} *PySet_New (PyObject *iterable)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`iterable' が返すオブジェクトを含む新しい @ref{184,,set} を返します。
`iterable' が @code{NULL} のときは、空の set を返します。
成功したら新しい set を、失敗したら @code{NULL} を返します。
`iterable' がイテレート可能でない場合は、 @ref{198,,TypeError} を送出します。
このコンストラクタは set をコピーするときにも使えます (@code{c=set(s)})。
@end deffn

@geindex PyFrozenSet_New (C function)
@anchor{c-api/set c PyFrozenSet_New}@anchor{165e}
@deffn {C の関数} @ref{5df,,PyObject} *PyFrozenSet_New (PyObject *iterable)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`iterable' が返すオブジェクトを含む新しい @ref{7f2,,frozenset} を返します。
`iterable' が @code{NULL} のときは、空の frozenset を返します。
成功時には新しい set を、失敗時には @code{NULL} を返します。
`iterable' がイテレート可能でない場合は、 @ref{198,,TypeError} を送出します。
@end deffn

以降の関数やマクロは、 @ref{184,,set} と @ref{7f2,,frozenset} とそのサブタイプのインスタンスに対して利用できます。

@geindex PySet_Size (C function)
@anchor{c-api/set c PySet_Size}@anchor{1662}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PySet_Size (PyObject *anyset)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;len

Return the length of a @ref{184,,set} or @ref{7f2,,frozenset} object. Equivalent to
@code{len(anyset)}.  Raises a @ref{795,,SystemError} if `anyset' is not a
@ref{184,,set}, @ref{7f2,,frozenset}, or an instance of a subtype.
@end deffn

@geindex PySet_GET_SIZE (C function)
@anchor{c-api/set c PySet_GET_SIZE}@anchor{53cf}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PySet_GET_SIZE (PyObject *anyset)

エラーチェックを行わない、 @ref{1662,,PySet_Size()} のマクロ形式。
@end deffn

@geindex PySet_Contains (C function)
@anchor{c-api/set c PySet_Contains}@anchor{1661}
@deffn {C の関数} int PySet_Contains (PyObject *anyset, PyObject *key)
` 次に属します: @ref{775,,Stable ABI}.'
Return @code{1} if found, @code{0} if not found, and @code{-1} if an error is encountered.  Unlike
the Python @ref{15d3,,__contains__()} method, this function does not automatically
convert unhashable sets into temporary frozensets.  Raise a @ref{198,,TypeError} if
the `key' is unhashable. Raise @ref{795,,SystemError} if `anyset' is not a
@ref{184,,set}, @ref{7f2,,frozenset}, or an instance of a subtype.
@end deffn

@geindex PySet_Add (C function)
@anchor{c-api/set c PySet_Add}@anchor{165f}
@deffn {C の関数} int PySet_Add (PyObject *set, PyObject *key)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{184,,set} のインスタンスに `key' を追加します。
@ref{7f2,,frozenset} に対しても動作します (@ref{4eb8,,PyTuple_SetItem()} のように、他のコードに見える前の新しい frozenset の値を埋めるために使用できます)。
成功したら @code{0} を、失敗したら @code{-1} を返します。
`key' がハッシュ可能でない場合は、 @ref{198,,TypeError} を送出します。
`set' を大きくする余裕がない場合は、 @ref{179e,,MemoryError} を送出します。
`set' が @ref{184,,set} かそのサブタイプのインスタンスでない場合は、 @ref{795,,SystemError} を送出します。
@end deffn

以降の関数は、 @ref{184,,set} とそのサブタイプに対して利用可能です。 @ref{7f2,,frozenset} とそのサブタイプには利用できません。

@geindex PySet_Discard (C function)
@anchor{c-api/set c PySet_Discard}@anchor{1660}
@deffn {C の関数} int PySet_Discard (PyObject *set, PyObject *key)
` 次に属します: @ref{775,,Stable ABI}.'
Return @code{1} if found and removed, @code{0} if not found (no action taken), and @code{-1} if an
error is encountered.  Does not raise @ref{5e7,,KeyError} for missing keys.  Raise a
@ref{198,,TypeError} if the `key' is unhashable.  Unlike the Python @ref{26a0,,discard()}
method, this function does not automatically convert unhashable sets into
temporary frozensets. Raise @ref{795,,SystemError} if `set' is not an
instance of @ref{184,,set} or its subtype.
@end deffn

@geindex PySet_Pop (C function)
@anchor{c-api/set c PySet_Pop}@anchor{50af}
@deffn {C の関数} @ref{5df,,PyObject} *PySet_Pop (PyObject *set)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`set' の中の要素のどれかに対する新しい参照を返し、そのオブジェクトを `set' から削除します。
失敗したら @code{NULL} を返します。
set が空の場合には @ref{5e7,,KeyError} を送出します。
`set' が @ref{184,,set} とそのサブタイプのインスタンスでない場合は、 @ref{795,,SystemError} を送出します。
@end deffn

@geindex PySet_Clear (C function)
@anchor{c-api/set c PySet_Clear}@anchor{50ae}
@deffn {C の関数} int PySet_Clear (PyObject *set)
` 次に属します: @ref{775,,Stable ABI}.'
Empty an existing set of all elements. Return @code{0} on
success. Return @code{-1} and raise @ref{795,,SystemError} if `set' is not an instance of
@ref{184,,set} or its subtype.
@end deffn

@menu
* Deprecated API: Deprecated API<3>. 

@end menu

@node Deprecated API<3>,,,Set オブジェクト
@anchor{c-api/set deprecated-api}@anchor{53d0}
@subsubsection Deprecated API


@geindex PySet_MINSIZE (C macro)
@anchor{c-api/set c PySet_MINSIZE}@anchor{53d1}
@deffn {C のマクロ} PySet_MINSIZE

A @ref{23d,,soft deprecated} constant representing the size of an internal
preallocated table inside @ref{53c9,,PySetObject} instances.

This is documented solely for completeness, as there are no guarantees
that a given version of CPython uses preallocated tables with a fixed
size.
In code that does not deal with unstable set internals,
@code{PySet_MINSIZE} can be replaced with a small constant like @code{8}.

If looking for the size of a set, use @ref{1662,,PySet_Size()} instead.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Function オブジェクト<2>,その他のオブジェクト<2>,Container オブジェクト,具象オブジェクト concrete object レイヤ
@anchor{c-api/concrete function-objects}@anchor{53d2}@anchor{c-api/concrete otherobjects}@anchor{53d3}
@subsection Function オブジェクト


@menu
* Function オブジェクト: Function オブジェクト<3>. 
* インスタンスメソッドオブジェクト(Instance Method Objects): インスタンスメソッドオブジェクト Instance Method Objects. 
* メソッドオブジェクト: メソッドオブジェクト<2>. 
* セルオブジェクト (cell object): セルオブジェクト cell object. 
* コードオブジェクト: コードオブジェクト<3>. 
* Code Object Flags:: 
* Extra information:: 

@end menu

@node Function オブジェクト<3>,インスタンスメソッドオブジェクト Instance Method Objects,,Function オブジェクト<2>
@anchor{c-api/function doc}@anchor{53d4}@anchor{c-api/function function-objects}@anchor{53d5}@anchor{c-api/function id1}@anchor{53d6}
@subsubsection Function オブジェクト


@geindex object;関数

Functionオブジェクト固有の関数はわずかです。

@geindex PyFunctionObject (C type)
@anchor{c-api/function c PyFunctionObject}@anchor{783}
@deffn {C のデータ型} type PyFunctionObject

関数に使われるCの構造体。
@end deffn

@geindex PyFunction_Type (C var)
@anchor{c-api/function c PyFunction_Type}@anchor{53d7}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyFunction_Type

@geindex MethodType (in module types)

@ref{c9c,,PyTypeObject} 型のインスタンスで、 Python の関数型を表します。これは Python プログラムに @code{types.FunctionType} として公開されています。
@end deffn

@geindex PyFunction_Check (C function)
@anchor{c-api/function c PyFunction_Check}@anchor{53d8}
@deffn {C の関数} int PyFunction_Check (PyObject *o)

`o' が関数オブジェクト (@ref{53d7,,PyFunction_Type} 型である) 場合に真を返します。パラメータは @code{NULL} にできません。この関数は常に成功します。
@end deffn

@geindex PyFunction_New (C function)
@anchor{c-api/function c PyFunction_New}@anchor{53d9}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_New (PyObject *code, PyObject *globals)
`戻り値: 新しい参照。'
コードオブジェクト `code' に関連付けられた新しい関数オブジェクトを返します。`globals' はこの関数からアクセスできるグローバル変数の辞書でなければなりません。

関数のドキュメント文字列と名前はコードオブジェクトから取得されます。
@ref{234a,,__module__} は `globals' から取得されます。
引数のデフォルト値やアノテーション、クロージャは @code{NULL} に設定されます。 @ref{2349,,__qualname__} はコードオブジェクトの @ref{2386,,co_qualname} フィールドと同じ値に設定されます。
@end deffn

@geindex PyFunction_NewWithQualName (C function)
@anchor{c-api/function c PyFunction_NewWithQualName}@anchor{53da}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_NewWithQualName (PyObject *code, PyObject *globals, PyObject *qualname)
`戻り値: 新しい参照。'
@ref{53d9,,PyFunction_New()} に似ていますが、関数オブジェクトの @ref{2349,,__qualname__} 属性に値をセットできます。
`qualname' はユニコードオブジェクトか @code{NULL} でなくてはなりません。@code{NULL} だった場合、 @code{__qualname__} 属性にはコードオブジェクトの @ref{2386,,co_qualname} フィールドと同じ値がセットされます。


Added in version 3.3.

@end deffn

@geindex PyFunction_GetCode (C function)
@anchor{c-api/function c PyFunction_GetCode}@anchor{53db}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GetCode (PyObject *op)
`戻り値: 借用参照。'
関数オブジェクト `op' に関連付けられたコードオブジェクトを返します。
@end deffn

@geindex PyFunction_GetGlobals (C function)
@anchor{c-api/function c PyFunction_GetGlobals}@anchor{53dc}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GetGlobals (PyObject *op)
`戻り値: 借用参照。'
関数オブジェクト `op' に関連付けられたglobals辞書を返します。
@end deffn

@geindex PyFunction_GetModule (C function)
@anchor{c-api/function c PyFunction_GetModule}@anchor{53dd}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GetModule (PyObject *op)
`戻り値: 借用参照。'
Return a @ref{3d7,,borrowed reference} to the @ref{234a,,__module__}
attribute of the @ref{59c,,function object} `op'.
It can be `NULL'.

This is normally a @ref{169,,string} containing the module name,
but can be set to any other object by Python code.
@end deffn

@geindex PyFunction_GetDefaults (C function)
@anchor{c-api/function c PyFunction_GetDefaults}@anchor{53de}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GetDefaults (PyObject *op)
`戻り値: 借用参照。'
関数オブジェクト `op' の引数のデフォルト値を返します。
引数のタプルか @code{NULL} になります。
@end deffn

@geindex PyFunction_SetDefaults (C function)
@anchor{c-api/function c PyFunction_SetDefaults}@anchor{53df}
@deffn {C の関数} int PyFunction_SetDefaults (PyObject *op, PyObject *defaults)

関数オブジェクト `op' の引数のデフォルト値を設定します。
`defaults' は @code{Py_None} かタプルでなければいけません。

失敗した時は、 @ref{795,,SystemError} を発生させ、 @code{-1} を返します。
@end deffn

@geindex PyFunction_SetVectorcall (C function)
@anchor{c-api/function c PyFunction_SetVectorcall}@anchor{782}
@deffn {C の関数} void PyFunction_SetVectorcall (PyFunctionObject *func, vectorcallfunc vectorcall)

Set the vectorcall field of a given function object `func'.

Warning: extensions using this API must preserve the behavior
of the unaltered (default) vectorcall function!


Added in version 3.12.

@end deffn

@geindex PyFunction_GetKwDefaults (C function)
@anchor{c-api/function c PyFunction_GetKwDefaults}@anchor{53e0}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GetKwDefaults (PyObject *op)
`戻り値: 借用参照。'
Return the keyword-only argument default values of the function object `op'. This can be a
dictionary of arguments or @code{NULL}.
@end deffn

@geindex PyFunction_SetKwDefaults (C function)
@anchor{c-api/function c PyFunction_SetKwDefaults}@anchor{53e1}
@deffn {C の関数} int PyFunction_SetKwDefaults (PyObject *op, PyObject *defaults)

Set the keyword-only argument default values of the function object `op'.
`defaults' must be a dictionary of keyword-only arguments or @code{Py_None}.

This function returns @code{0} on success, and returns @code{-1} with an exception
set on failure.
@end deffn

@geindex PyFunction_GetClosure (C function)
@anchor{c-api/function c PyFunction_GetClosure}@anchor{53e2}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GetClosure (PyObject *op)
`戻り値: 借用参照。'
関数オブジェクト `op' に設定されたクロージャを返します。
@code{NULL} か cell オブジェクトのタプルです。
@end deffn

@geindex PyFunction_SetClosure (C function)
@anchor{c-api/function c PyFunction_SetClosure}@anchor{53e3}
@deffn {C の関数} int PyFunction_SetClosure (PyObject *op, PyObject *closure)

関数オブジェクト `op' にクロージャを設定します。
`closure' は、@code{Py_None} もしくは cell オブジェクトのタプルでなければなりません。

失敗した時は、 @ref{795,,SystemError} を発生させ、 @code{-1} を返します。
@end deffn

@geindex PyFunction_GetAnnotations (C function)
@anchor{c-api/function c PyFunction_GetAnnotations}@anchor{1b37}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GetAnnotations (PyObject *op)
`戻り値: 借用参照。'
関数オブジェクト `op' のアノテーションを返します。
返り値は修正可能な辞書か @code{NULL} になります。
@end deffn

@geindex PyFunction_SetAnnotations (C function)
@anchor{c-api/function c PyFunction_SetAnnotations}@anchor{53e4}
@deffn {C の関数} int PyFunction_SetAnnotations (PyObject *op, PyObject *annotations)

関数オブジェクト `op' のアノテーションを設定します。
`annotations' は辞書か、@code{Py_None} でなければなりません。

失敗した時は、 @ref{795,,SystemError} を発生させ、 @code{-1} を返します。
@end deffn

@geindex PyFunction_GET_CODE (C function)
@geindex PyFunction_GET_GLOBALS (C function)
@geindex PyFunction_GET_MODULE (C function)
@geindex PyFunction_GET_DEFAULTS (C function)
@geindex PyFunction_GET_KW_DEFAULTS (C function)
@geindex PyFunction_GET_CLOSURE (C function)
@geindex PyFunction_GET_ANNOTATIONS (C function)
@anchor{c-api/function c PyFunction_GET_CODE}@anchor{53e5}
@deffn {C の関数} @ref{5df,,PyObject} *PyFunction_GET_CODE (PyObject *op)
@anchor{c-api/function c PyFunction_GET_GLOBALS}@anchor{53e6}
@deffnx {C の関数} @ref{5df,,PyObject} *PyFunction_GET_GLOBALS (PyObject *op)
@anchor{c-api/function c PyFunction_GET_MODULE}@anchor{53e7}
@deffnx {C の関数} @ref{5df,,PyObject} *PyFunction_GET_MODULE (PyObject *op)
@anchor{c-api/function c PyFunction_GET_DEFAULTS}@anchor{53e8}
@deffnx {C の関数} @ref{5df,,PyObject} *PyFunction_GET_DEFAULTS (PyObject *op)
@anchor{c-api/function c PyFunction_GET_KW_DEFAULTS}@anchor{53e9}
@deffnx {C の関数} @ref{5df,,PyObject} *PyFunction_GET_KW_DEFAULTS (PyObject *op)
@anchor{c-api/function c PyFunction_GET_CLOSURE}@anchor{53ea}
@deffnx {C の関数} @ref{5df,,PyObject} *PyFunction_GET_CLOSURE (PyObject *op)
@anchor{c-api/function c PyFunction_GET_ANNOTATIONS}@anchor{53eb}
@deffnx {C の関数} @ref{5df,,PyObject} *PyFunction_GET_ANNOTATIONS (PyObject *op)
`戻り値: 借用参照。'
These functions are similar to their @code{PyFunction_Get*} counterparts, but
do not do type checking. Passing anything other than an instance of
@ref{53d7,,PyFunction_Type} is undefined behavior.
@end deffn

@geindex PyFunction_AddWatcher (C function)
@anchor{c-api/function c PyFunction_AddWatcher}@anchor{53ec}
@deffn {C の関数} int PyFunction_AddWatcher (PyFunction_WatchCallback callback)

Register `callback' as a function watcher for the current interpreter.
Return an ID which may be passed to @ref{53ed,,PyFunction_ClearWatcher()}.
In case of error (e.g. no more watcher IDs available),
return @code{-1} and set an exception.


Added in version 3.12.

@end deffn

@geindex PyFunction_ClearWatcher (C function)
@anchor{c-api/function c PyFunction_ClearWatcher}@anchor{53ed}
@deffn {C の関数} int PyFunction_ClearWatcher (int watcher_id)

Clear watcher identified by `watcher_id' previously returned from
@ref{53ec,,PyFunction_AddWatcher()} for the current interpreter.
Return @code{0} on success, or @code{-1} and set an exception on error
(e.g.  if the given `watcher_id' was never registered.)


Added in version 3.12.

@end deffn

@geindex PyFunction_WatchEvent (C type)
@anchor{c-api/function c PyFunction_WatchEvent}@anchor{53ee}
@deffn {C のデータ型} type PyFunction_WatchEvent

@quotation

Enumeration of possible function watcher events:


@itemize -

@item 
@code{PyFunction_EVENT_CREATE}

@item 
@code{PyFunction_EVENT_DESTROY}

@item 
@code{PyFunction_EVENT_MODIFY_CODE}

@item 
@code{PyFunction_EVENT_MODIFY_DEFAULTS}

@item 
@code{PyFunction_EVENT_MODIFY_KWDEFAULTS}
@end itemize
@end quotation


Added in version 3.12.

@end deffn

@geindex PyFunction_WatchCallback (C type)
@anchor{c-api/function c PyFunction_WatchCallback}@anchor{53ef}
@deffn {C のデータ型} typedef int (*PyFunction_WatchCallback)(@ref{53ee,,PyFunction_WatchEvent} event, @ref{783,,PyFunctionObject} *func, @ref{5df,,PyObject} *new_value)

Type of a function watcher callback function.

If `event' is @code{PyFunction_EVENT_CREATE} or @code{PyFunction_EVENT_DESTROY}
then `new_value' will be @code{NULL}. Otherwise, `new_value' will hold a
@ref{3d7,,borrowed reference} to the new value that is about to be stored in
`func' for the attribute that is being modified.

The callback may inspect but must not modify `func'; doing so could have
unpredictable effects, including infinite recursion.

If `event' is @code{PyFunction_EVENT_CREATE}, then the callback is invoked
after `func' has been fully initialized. Otherwise, the callback is invoked
before the modification to `func' takes place, so the prior state of `func'
can be inspected. The runtime is permitted to optimize away the creation of
function objects when possible. In such cases no event will be emitted.
Although this creates the possibility of an observable difference of
runtime behavior depending on optimization decisions, it does not change
the semantics of the Python code being executed.

If `event' is @code{PyFunction_EVENT_DESTROY},  Taking a reference in the
callback to the about-to-be-destroyed function will resurrect it, preventing
it from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.

If the callback sets an exception, it must return @code{-1}; this exception will
be printed as an unraisable exception using @ref{5f2,,PyErr_WriteUnraisable()}.
Otherwise it should return @code{0}.

There may already be a pending exception set on entry to the callback. In
this case, the callback should return @code{0} with the same exception still
set. This means the callback may not call any other API that can set an
exception unless it saves and clears the exception state first, and restores
it before returning.


Added in version 3.12.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node インスタンスメソッドオブジェクト Instance Method Objects,メソッドオブジェクト<2>,Function オブジェクト<3>,Function オブジェクト<2>
@anchor{c-api/method doc}@anchor{53f0}@anchor{c-api/method instance-method-objects}@anchor{53f1}@anchor{c-api/method instancemethod-objects}@anchor{53f2}@anchor{c-api/method translation-repo}@anchor{53f3}
@subsubsection インスタンスメソッドオブジェクト(Instance Method Objects)


@geindex object;instancemethod

An instance method is a wrapper for a @ref{1691,,PyCFunction} and the new way
to bind a @ref{1691,,PyCFunction} to a class object. It replaces the former call
@code{PyMethod_New(func, NULL, class)}.

@geindex PyInstanceMethod_Type (C var)
@anchor{c-api/method c PyInstanceMethod_Type}@anchor{53f4}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyInstanceMethod_Type

@ref{c9c,,PyTypeObject} のインスタンスは Python のインスタンスメソッドの型を表現します。これは Python のプログラムには公開されません。
@end deffn

@geindex PyInstanceMethod_Check (C function)
@anchor{c-api/method c PyInstanceMethod_Check}@anchor{53f5}
@deffn {C の関数} int PyInstanceMethod_Check (PyObject *o)

`o' がインスタンスメソッドオブジェクト (@ref{53f4,,PyInstanceMethod_Type} 型である) 場合に真を返します。パラメータは @code{NULL} にできません。この関数は常に成功します。
@end deffn

@geindex PyInstanceMethod_New (C function)
@anchor{c-api/method c PyInstanceMethod_New}@anchor{53f6}
@deffn {C の関数} @ref{5df,,PyObject} *PyInstanceMethod_New (PyObject *func)
`戻り値: 新しい参照。'
任意の呼び出し可能オブジェクト `func' を使った新たなインスタンスメソッドオブジェクトを返します。`func' はインスタンスメソッドが呼び出されたときに呼び出される関数です。
@end deffn

@geindex PyInstanceMethod_Function (C function)
@anchor{c-api/method c PyInstanceMethod_Function}@anchor{53f7}
@deffn {C の関数} @ref{5df,,PyObject} *PyInstanceMethod_Function (PyObject *im)
`戻り値: 借用参照。'
インスタンスメソッド `im' に関連付けられた関数オブジェクトを返します。
@end deffn

@geindex PyInstanceMethod_GET_FUNCTION (C function)
@anchor{c-api/method c PyInstanceMethod_GET_FUNCTION}@anchor{53f8}
@deffn {C の関数} @ref{5df,,PyObject} *PyInstanceMethod_GET_FUNCTION (PyObject *im)
`戻り値: 借用参照。'
@ref{53f7,,PyInstanceMethod_Function()} のマクロ版で、エラーチェックを行いません。
@end deffn

@node メソッドオブジェクト<2>,セルオブジェクト cell object,インスタンスメソッドオブジェクト Instance Method Objects,Function オブジェクト<2>
@anchor{c-api/method id1}@anchor{53f9}@anchor{c-api/method method-objects}@anchor{53fa}
@subsubsection メソッドオブジェクト


@geindex object;メソッド

メソッドは関数オブジェクトに束縛されています。メソッドは常にあるユーザー定義のクラスに束縛されているのです。束縛されていないメソッド(クラスオブジェクトに束縛されたメソッド)は利用することができません。

@geindex PyMethod_Type (C var)
@anchor{c-api/method c PyMethod_Type}@anchor{53fb}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyMethod_Type

@geindex MethodType (in module types)

この @ref{c9c,,PyTypeObject} のインスタンスは Python のメソッド型を表現します。このオブジェクトは、 @code{types.MethodType}  として Python プログラムに公開されています。
@end deffn

@geindex PyMethod_Check (C function)
@anchor{c-api/method c PyMethod_Check}@anchor{53fc}
@deffn {C の関数} int PyMethod_Check (PyObject *o)

`o' がメソッドオブジェクト (@ref{53fb,,PyMethod_Type} 型である) 場合に真を返します。パラメータは @code{NULL} にできません。この関数は常に成功します。
@end deffn

@geindex PyMethod_New (C function)
@anchor{c-api/method c PyMethod_New}@anchor{53fd}
@deffn {C の関数} @ref{5df,,PyObject} *PyMethod_New (PyObject *func, PyObject *self)
`戻り値: 新しい参照。'
任意の呼び出し可能オブジェクト `func' とメソッドが束縛されるべきインスタンス `self' を使った新たなメソッドオブジェクトを返します。
関数 `func' は、メソッドが呼び出された時に呼び出されるオブジェクトです。
`self' は @code{NULL} にできません。
@end deffn

@geindex PyMethod_Function (C function)
@anchor{c-api/method c PyMethod_Function}@anchor{53fe}
@deffn {C の関数} @ref{5df,,PyObject} *PyMethod_Function (PyObject *meth)
`戻り値: 借用参照。'
メソッド `meth' に関連付けられている関数オブジェクトを返します。
@end deffn

@geindex PyMethod_GET_FUNCTION (C function)
@anchor{c-api/method c PyMethod_GET_FUNCTION}@anchor{53ff}
@deffn {C の関数} @ref{5df,,PyObject} *PyMethod_GET_FUNCTION (PyObject *meth)
`戻り値: 借用参照。'
@ref{53fe,,PyMethod_Function()} のマクロ版で、エラーチェックを行いません。
@end deffn

@geindex PyMethod_Self (C function)
@anchor{c-api/method c PyMethod_Self}@anchor{5400}
@deffn {C の関数} @ref{5df,,PyObject} *PyMethod_Self (PyObject *meth)
`戻り値: 借用参照。'
メソッド `meth' に関連付けられたインスタンスを返します。
@end deffn

@geindex PyMethod_GET_SELF (C function)
@anchor{c-api/method c PyMethod_GET_SELF}@anchor{5401}
@deffn {C の関数} @ref{5df,,PyObject} *PyMethod_GET_SELF (PyObject *meth)
`戻り値: 借用参照。'
@ref{5400,,PyMethod_Self()} のマクロ版で、エラーチェックを行いません。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node セルオブジェクト cell object,コードオブジェクト<3>,メソッドオブジェクト<2>,Function オブジェクト<2>
@anchor{c-api/cell doc}@anchor{5402}@anchor{c-api/cell cell-objects}@anchor{910}@anchor{c-api/cell id1}@anchor{5403}@anchor{c-api/cell translation-repo}@anchor{5404}
@subsubsection セルオブジェクト (cell object)


"Cell" objects are used to implement variables referenced by multiple scopes.
For each such variable, a cell object is created to store the value; the local
variables of each stack frame that references the value contain a reference to
the cells from outer scopes which also use that variable.  When the value is
accessed, the value contained in the cell is used instead of the cell object
itself.  This de-referencing of the cell object requires support from the
generated byte-code; these are not automatically de-referenced when accessed.
Cell objects are not likely to be useful elsewhere.

@geindex PyCellObject (C type)
@anchor{c-api/cell c PyCellObject}@anchor{5405}
@deffn {C のデータ型} type PyCellObject

セルオブジェクトに使われる C 構造体です。
@end deffn

@geindex PyCell_Type (C var)
@anchor{c-api/cell c PyCell_Type}@anchor{5406}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCell_Type

セルオブジェクトに対応する型オブジェクトです。
@end deffn

@geindex PyCell_Check (C function)
@anchor{c-api/cell c PyCell_Check}@anchor{5407}
@deffn {C の関数} int PyCell_Check (PyObject *ob)

`ob' がセルオブジェクトの場合に真を返します; `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyCell_New (C function)
@anchor{c-api/cell c PyCell_New}@anchor{5408}
@deffn {C の関数} @ref{5df,,PyObject} *PyCell_New (PyObject *ob)
`戻り値: 新しい参照。'
値 `ob' の入った新たなセルオブジェクトを生成して返します。
引数を @code{NULL} にしてもかまいません。
@end deffn

@geindex PyCell_Get (C function)
@anchor{c-api/cell c PyCell_Get}@anchor{5409}
@deffn {C の関数} @ref{5df,,PyObject} *PyCell_Get (PyObject *cell)
`戻り値: 新しい参照。'
Return the contents of the cell `cell', which can be @code{NULL}.
If `cell' is not a cell object, returns @code{NULL} with an exception set.
@end deffn

@geindex PyCell_GET (C function)
@anchor{c-api/cell c PyCell_GET}@anchor{540a}
@deffn {C の関数} @ref{5df,,PyObject} *PyCell_GET (PyObject *cell)
`戻り値: 借用参照。'
`cell' の内容を返しますが、`cell' が非 @code{NULL} かつセルオブジェクトであるかどうかはチェックしません。
@end deffn

@geindex PyCell_Set (C function)
@anchor{c-api/cell c PyCell_Set}@anchor{540b}
@deffn {C の関数} int PyCell_Set (PyObject *cell, PyObject *value)

Set the contents of the cell object `cell' to `value'.  This releases the
reference to any current content of the cell. `value' may be @code{NULL}.  `cell'
must be non-@code{NULL}.

On success, return @code{0}.
If `cell' is not a cell object, set an exception and return @code{-1}.
@end deffn

@geindex PyCell_SET (C function)
@anchor{c-api/cell c PyCell_SET}@anchor{aab}
@deffn {C の関数} void PyCell_SET (PyObject *cell, PyObject *value)

セルオブジェクト `cell' の値を `value' に設定します。
参照カウントに対する変更はなく、安全のためのチェックは何も行いません。`cell' は非 @code{NULL} でなければならず、かつセルオブジェクトでなければなりません。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@geindex オブジェクト;コード
@geindex コードオブジェクト

@node コードオブジェクト<3>,Code Object Flags,セルオブジェクト cell object,Function オブジェクト<2>
@anchor{c-api/code doc}@anchor{540c}@anchor{c-api/code code-objects}@anchor{540d}@anchor{c-api/code codeobjects}@anchor{7d2}@anchor{c-api/code translation-repo}@anchor{540e}
@subsubsection コードオブジェクト


コードオブジェクト(Code objects)は CPython 実装の低レベルな詳細部分です。各オブジェクトは関数に束縛されていない実行可能コードの塊を表現しています。

@geindex PyCodeObject (C type)
@anchor{c-api/code c PyCodeObject}@anchor{97b}
@deffn {C のデータ型} type PyCodeObject

コードオブジェクトを表現するために利用されるC構造体。この型のフィールドは何時でも変更され得ます。
@end deffn

@geindex PyCode_Type (C var)
@anchor{c-api/code c PyCode_Type}@anchor{540f}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCode_Type

This is an instance of @ref{c9c,,PyTypeObject} representing the Python
@ref{4e6,,code object}.
@end deffn

@geindex PyCode_Check (C function)
@anchor{c-api/code c PyCode_Check}@anchor{5410}
@deffn {C の関数} int PyCode_Check (PyObject *co)

Return true if `co' is a @ref{4e6,,code object}.
This function always succeeds.
@end deffn

@geindex PyCode_GetNumFree (C function)
@anchor{c-api/code c PyCode_GetNumFree}@anchor{5411}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyCode_GetNumFree (PyCodeObject *co)

Return the number of @ref{1893,,free (closure) variables}
in a code object.
@end deffn

@geindex PyUnstable_Code_GetFirstFree (C function)
@anchor{c-api/code c PyUnstable_Code_GetFirstFree}@anchor{627}
@deffn {C の関数} int PyUnstable_Code_GetFirstFree (PyCodeObject *co)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Return the position of the first @ref{1893,,free (closure) variable}
in a code object.


バージョン 3.13 で変更: Renamed from @code{PyCode_GetFirstFree} as part of @ref{769,,Unstable C API}.
The old name is deprecated, but will remain available until the
signature changes again.

@end deffn

@geindex PyUnstable_Code_New (C function)
@anchor{c-api/code c PyUnstable_Code_New}@anchor{5412}
@deffn {C の関数} @ref{97b,,PyCodeObject} *PyUnstable_Code_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, PyObject *qualname, int firstlineno, PyObject *linetable, PyObject *exceptiontable)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Return a new code object.  If you need a dummy code object to create a frame,
use @ref{1568,,PyCode_NewEmpty()} instead.

Since the definition of the bytecode changes often, calling
@ref{5412,,PyUnstable_Code_New()} directly can bind you to a precise Python version.

The many arguments of this function are inter-dependent in complex
ways, meaning that subtle changes to values are likely to result in incorrect
execution or VM crashes. Use this function only with extreme care.


バージョン 3.11 で変更: Added @code{qualname} and @code{exceptiontable} parameters.


@geindex PyCode_New (C 関数)


バージョン 3.12 で変更: Renamed from @code{PyCode_New} as part of @ref{769,,Unstable C API}.
The old name is deprecated, but will remain available until the
signature changes again.

@end deffn

@geindex PyCode_NewWithPosOnlyArgs (C function)

@geindex PyUnstable_Code_NewWithPosOnlyArgs (C function)
@anchor{c-api/code c PyCode_NewWithPosOnlyArgs}@anchor{5413}@anchor{c-api/code c PyUnstable_Code_NewWithPosOnlyArgs}@anchor{5414}
@deffn {C の関数} @ref{97b,,PyCodeObject} *PyUnstable_Code_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, PyObject *qualname, int firstlineno, PyObject *linetable, PyObject *exceptiontable)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Similar to @ref{5412,,PyUnstable_Code_New()}, but with an extra "posonlyargcount" for positional-only arguments.
The same caveats that apply to @code{PyUnstable_Code_New} also apply to this function.


Added in version 3.8: as @code{PyCode_NewWithPosOnlyArgs}



バージョン 3.11 で変更: Added @code{qualname} and  @code{exceptiontable} parameters.



バージョン 3.12 で変更: Renamed to @code{PyUnstable_Code_NewWithPosOnlyArgs}.
The old name is deprecated, but will remain available until the
signature changes again.

@end deffn

@geindex PyCode_NewEmpty (C function)
@anchor{c-api/code c PyCode_NewEmpty}@anchor{1568}
@deffn {C の関数} @ref{97b,,PyCodeObject} *PyCode_NewEmpty (const char *filename, const char *funcname, int firstlineno)
`戻り値: 新しい参照。'
Return a new empty code object with the specified filename,
function name, and first line number. The resulting code
object will raise an @code{Exception} if executed.
@end deffn

@geindex PyCode_Addr2Line (C function)
@anchor{c-api/code c PyCode_Addr2Line}@anchor{a89}
@deffn {C の関数} int PyCode_Addr2Line (PyCodeObject *co, int byte_offset)

Return the line number of the instruction that occurs on or before @code{byte_offset} and ends after it.
If you just need the line number of a frame, use @ref{98e,,PyFrame_GetLineNumber()} instead.

For efficiently iterating over the line numbers in a code object, use 
@geindex Python Enhancement Proposals; PEP 0626#out-of-process-debuggers-and-profilers
the API described in PEP 626@footnote{https://peps.python.org/pep-0626/#out-of-process-debuggers-and-profilers}.
@end deffn

@geindex PyCode_Addr2Location (C function)
@anchor{c-api/code c PyCode_Addr2Location}@anchor{7d1}
@deffn {C の関数} int PyCode_Addr2Location (PyObject *co, int byte_offset, int *start_line, int *start_column, int *end_line, int *end_column)

Sets the passed @code{int} pointers to the source code line and column numbers
for the instruction at @code{byte_offset}. Sets the value to @code{0} when
information is not available for any particular element.

Returns @code{1} if the function succeeds and 0 otherwise.


Added in version 3.11.

@end deffn

@geindex PyCode_GetCode (C function)
@anchor{c-api/code c PyCode_GetCode}@anchor{97c}
@deffn {C の関数} @ref{5df,,PyObject} *PyCode_GetCode (PyCodeObject *co)

Equivalent to the Python code @code{getattr(co, 'co_code')}.
Returns a strong reference to a @ref{995,,PyBytesObject} representing the
bytecode in a code object. On error, @code{NULL} is returned and an exception
is raised.

This @code{PyBytesObject} may be created on-demand by the interpreter and does
not necessarily represent the bytecode actually executed by CPython. The
primary use case for this function is debuggers and profilers.


Added in version 3.11.

@end deffn

@geindex PyCode_GetVarnames (C function)
@anchor{c-api/code c PyCode_GetVarnames}@anchor{97d}
@deffn {C の関数} @ref{5df,,PyObject} *PyCode_GetVarnames (PyCodeObject *co)

Equivalent to the Python code @code{getattr(co, 'co_varnames')}.
Returns a new reference to a @ref{5224,,PyTupleObject} containing the names of
the local variables. On error, @code{NULL} is returned and an exception
is raised.


Added in version 3.11.

@end deffn

@geindex PyCode_GetCellvars (C function)
@anchor{c-api/code c PyCode_GetCellvars}@anchor{97e}
@deffn {C の関数} @ref{5df,,PyObject} *PyCode_GetCellvars (PyCodeObject *co)

Equivalent to the Python code @code{getattr(co, 'co_cellvars')}.
Returns a new reference to a @ref{5224,,PyTupleObject} containing the names of
the local variables that are referenced by nested functions. On error, @code{NULL}
is returned and an exception is raised.


Added in version 3.11.

@end deffn

@geindex PyCode_GetFreevars (C function)
@anchor{c-api/code c PyCode_GetFreevars}@anchor{97f}
@deffn {C の関数} @ref{5df,,PyObject} *PyCode_GetFreevars (PyCodeObject *co)

Equivalent to the Python code @code{getattr(co, 'co_freevars')}.
Returns a new reference to a @ref{5224,,PyTupleObject} containing the names of
the @ref{1893,,free (closure) variables}. On error, @code{NULL} is returned
and an exception is raised.


Added in version 3.11.

@end deffn

@geindex PyCode_AddWatcher (C function)
@anchor{c-api/code c PyCode_AddWatcher}@anchor{787}
@deffn {C の関数} int PyCode_AddWatcher (PyCode_WatchCallback callback)

Register `callback' as a code object watcher for the current interpreter.
Return an ID which may be passed to @ref{788,,PyCode_ClearWatcher()}.
In case of error (e.g. no more watcher IDs available),
return @code{-1} and set an exception.


Added in version 3.12.

@end deffn

@geindex PyCode_ClearWatcher (C function)
@anchor{c-api/code c PyCode_ClearWatcher}@anchor{788}
@deffn {C の関数} int PyCode_ClearWatcher (int watcher_id)

Clear watcher identified by `watcher_id' previously returned from
@ref{787,,PyCode_AddWatcher()} for the current interpreter.
Return @code{0} on success, or @code{-1} and set an exception on error
(e.g. if the given `watcher_id' was never registered.)


Added in version 3.12.

@end deffn

@geindex PyCodeEvent (C type)
@anchor{c-api/code c PyCodeEvent}@anchor{5415}
@deffn {C のデータ型} type PyCodeEvent

Enumeration of possible code object watcher events:
- @code{PY_CODE_EVENT_CREATE}
- @code{PY_CODE_EVENT_DESTROY}


Added in version 3.12.

@end deffn

@geindex PyCode_WatchCallback (C type)
@anchor{c-api/code c PyCode_WatchCallback}@anchor{5416}
@deffn {C のデータ型} typedef int (*PyCode_WatchCallback)(@ref{5415,,PyCodeEvent} event, @ref{97b,,PyCodeObject} *co)

Type of a code object watcher callback function.

If `event' is @code{PY_CODE_EVENT_CREATE}, then the callback is invoked
after `co' has been fully initialized. Otherwise, the callback is invoked
before the destruction of `co' takes place, so the prior state of `co'
can be inspected.

If `event' is @code{PY_CODE_EVENT_DESTROY}, taking a reference in the callback
to the about-to-be-destroyed code object will resurrect it and prevent it
from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.

Users of this API should not rely on internal runtime implementation
details. Such details may include, but are not limited to, the exact
order and timing of creation and destruction of code objects. While
changes in these details may result in differences observable by watchers
(including whether a callback is invoked or not), it does not change
the semantics of the Python code being executed.

If the callback sets an exception, it must return @code{-1}; this exception will
be printed as an unraisable exception using @ref{5f2,,PyErr_WriteUnraisable()}.
Otherwise it should return @code{0}.

There may already be a pending exception set on entry to the callback. In
this case, the callback should return @code{0} with the same exception still
set. This means the callback may not call any other API that can set an
exception unless it saves and clears the exception state first, and restores
it before returning.


Added in version 3.12.

@end deffn

@geindex PyCode_Optimize (C function)
@anchor{c-api/code c PyCode_Optimize}@anchor{5417}
@deffn {C の関数} @ref{5df,,PyObject} *PyCode_Optimize (PyObject *code, PyObject *consts, PyObject *names, PyObject *lnotab_obj)

This is a @ref{23d,,soft deprecated} function that does nothing.

Prior to Python 3.10, this function would perform basic optimizations to a
code object.


バージョン 3.10 で変更: This function now does nothing.

@end deffn

@node Code Object Flags,Extra information,コードオブジェクト<3>,Function オブジェクト<2>
@anchor{c-api/code c-codeobject-flags}@anchor{51e1}@anchor{c-api/code code-object-flags}@anchor{5418}
@subsubsection Code Object Flags


Code objects contain a bit-field of flags, which can be retrieved as the
@ref{18db,,co_flags} Python attribute (for example using
@ref{5ef,,PyObject_GetAttrString()}), and set using a `flags' argument to
@ref{5412,,PyUnstable_Code_New()} and similar functions.

Flags whose names start with @code{CO_FUTURE_} correspond to features normally
selectable by @ref{45d,,future statements}. These flags can be used in
@ref{51da,,PyCompilerFlags.cf_flags}.
Note that many @code{CO_FUTURE_} flags are mandatory in current versions of
Python, and setting them has no effect.

The following flags are available.
For their meaning, see the linked documentation of their Python equivalents.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@item

@geindex CO_OPTIMIZED (C macro)
@anchor{c-api/code c CO_OPTIMIZED}@anchor{5419}
@deffn {C のマクロ} CO_OPTIMIZED
@end deffn

@tab

@ref{4a53,,inspect.CO_OPTIMIZED}

@item

@geindex CO_NEWLOCALS (C macro)
@anchor{c-api/code c CO_NEWLOCALS}@anchor{541a}
@deffn {C のマクロ} CO_NEWLOCALS
@end deffn

@tab

@ref{4a54,,inspect.CO_NEWLOCALS}

@item

@geindex CO_VARARGS (C macro)
@anchor{c-api/code c CO_VARARGS}@anchor{541b}
@deffn {C のマクロ} CO_VARARGS
@end deffn

@tab

@ref{4a55,,inspect.CO_VARARGS}

@item

@geindex CO_VARKEYWORDS (C macro)
@anchor{c-api/code c CO_VARKEYWORDS}@anchor{541c}
@deffn {C のマクロ} CO_VARKEYWORDS
@end deffn

@tab

@ref{4a56,,inspect.CO_VARKEYWORDS}

@item

@geindex CO_NESTED (C macro)
@anchor{c-api/code c CO_NESTED}@anchor{541d}
@deffn {C のマクロ} CO_NESTED
@end deffn

@tab

@ref{4a57,,inspect.CO_NESTED}

@item

@geindex CO_GENERATOR (C macro)
@anchor{c-api/code c CO_GENERATOR}@anchor{541e}
@deffn {C のマクロ} CO_GENERATOR
@end deffn

@tab

@ref{4a58,,inspect.CO_GENERATOR}

@item

@geindex CO_COROUTINE (C macro)
@anchor{c-api/code c CO_COROUTINE}@anchor{541f}
@deffn {C のマクロ} CO_COROUTINE
@end deffn

@tab

@ref{4a59,,inspect.CO_COROUTINE}

@item

@geindex CO_ITERABLE_COROUTINE (C macro)
@anchor{c-api/code c CO_ITERABLE_COROUTINE}@anchor{5420}
@deffn {C のマクロ} CO_ITERABLE_COROUTINE
@end deffn

@tab

@ref{4a5a,,inspect.CO_ITERABLE_COROUTINE}

@item

@geindex CO_ASYNC_GENERATOR (C macro)
@anchor{c-api/code c CO_ASYNC_GENERATOR}@anchor{5421}
@deffn {C のマクロ} CO_ASYNC_GENERATOR
@end deffn

@tab

@ref{4a5b,,inspect.CO_ASYNC_GENERATOR}

@item

@geindex CO_HAS_DOCSTRING (C macro)
@anchor{c-api/code c CO_HAS_DOCSTRING}@anchor{5422}
@deffn {C のマクロ} CO_HAS_DOCSTRING
@end deffn

@tab

@ref{2394,,inspect.CO_HAS_DOCSTRING}

@item

@geindex CO_METHOD (C macro)
@anchor{c-api/code c CO_METHOD}@anchor{5423}
@deffn {C のマクロ} CO_METHOD
@end deffn

@tab

@ref{4a5c,,inspect.CO_METHOD}

@item

@geindex CO_FUTURE_DIVISION (C macro)
@anchor{c-api/code c CO_FUTURE_DIVISION}@anchor{5424}
@deffn {C のマクロ} CO_FUTURE_DIVISION
@end deffn

@tab

no effect (@ref{4a01,,__future__.division})

@item

@geindex CO_FUTURE_ABSOLUTE_IMPORT (C macro)
@anchor{c-api/code c CO_FUTURE_ABSOLUTE_IMPORT}@anchor{5425}
@deffn {C のマクロ} CO_FUTURE_ABSOLUTE_IMPORT
@end deffn

@tab

no effect (@ref{4a02,,__future__.absolute_import})

@item

@geindex CO_FUTURE_WITH_STATEMENT (C macro)
@anchor{c-api/code c CO_FUTURE_WITH_STATEMENT}@anchor{5426}
@deffn {C のマクロ} CO_FUTURE_WITH_STATEMENT
@end deffn

@tab

no effect (@ref{4a03,,__future__.with_statement})

@item

@geindex CO_FUTURE_PRINT_FUNCTION (C macro)
@anchor{c-api/code c CO_FUTURE_PRINT_FUNCTION}@anchor{5427}
@deffn {C のマクロ} CO_FUTURE_PRINT_FUNCTION
@end deffn

@tab

no effect (@ref{4a04,,__future__.print_function})

@item

@geindex CO_FUTURE_UNICODE_LITERALS (C macro)
@anchor{c-api/code c CO_FUTURE_UNICODE_LITERALS}@anchor{5428}
@deffn {C のマクロ} CO_FUTURE_UNICODE_LITERALS
@end deffn

@tab

no effect (@ref{4a05,,__future__.unicode_literals})

@item

@geindex CO_FUTURE_GENERATOR_STOP (C macro)
@anchor{c-api/code c CO_FUTURE_GENERATOR_STOP}@anchor{5429}
@deffn {C のマクロ} CO_FUTURE_GENERATOR_STOP
@end deffn

@tab

no effect (@ref{4a06,,__future__.generator_stop})

@item

@geindex CO_FUTURE_ANNOTATIONS (C macro)
@anchor{c-api/code c CO_FUTURE_ANNOTATIONS}@anchor{51e0}
@deffn {C のマクロ} CO_FUTURE_ANNOTATIONS
@end deffn

@tab

@ref{4a07,,__future__.annotations}

@end multitable


@node Extra information,,Code Object Flags,Function オブジェクト<2>
@anchor{c-api/code extra-information}@anchor{542a}
@subsubsection Extra information


To support low-level extensions to frame evaluation, such as external
just-in-time compilers, it is possible to attach arbitrary extra data to
code objects.

These functions are part of the unstable C API tier:
this functionality is a CPython implementation detail, and the API
may change without deprecation warnings.

@geindex _PyEval_RequestCodeExtraIndex (C function)

@geindex PyUnstable_Eval_RequestCodeExtraIndex (C function)
@anchor{c-api/code c _PyEval_RequestCodeExtraIndex}@anchor{542b}@anchor{c-api/code c PyUnstable_Eval_RequestCodeExtraIndex}@anchor{542c}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyUnstable_Eval_RequestCodeExtraIndex (freefunc free)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Return a new opaque index value used to adding data to code objects.

You generally call this function once (per interpreter) and use the result
with @code{PyCode_GetExtra} and @code{PyCode_SetExtra} to manipulate
data on individual code objects.

If `free' is not @code{NULL}: when a code object is deallocated,
`free' will be called on non-@code{NULL} data stored under the new index.
Use @ref{512a,,Py_DecRef()} when storing @ref{5df,,PyObject}.


Added in version 3.6: as @code{_PyEval_RequestCodeExtraIndex}



バージョン 3.12 で変更: Renamed to @code{PyUnstable_Eval_RequestCodeExtraIndex}.
The old private name is deprecated, but will be available until the API
changes.

@end deffn

@geindex _PyCode_GetExtra (C function)

@geindex PyUnstable_Code_GetExtra (C function)
@anchor{c-api/code c _PyCode_GetExtra}@anchor{542d}@anchor{c-api/code c PyUnstable_Code_GetExtra}@anchor{542e}
@deffn {C の関数} int PyUnstable_Code_GetExtra (PyObject *code, Py_ssize_t index, void **extra)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Set `extra' to the extra data stored under the given index.
Return 0 on success. Set an exception and return -1 on failure.

If no data was set under the index, set `extra' to @code{NULL} and return
0 without setting an exception.


Added in version 3.6: as @code{_PyCode_GetExtra}



バージョン 3.12 で変更: Renamed to @code{PyUnstable_Code_GetExtra}.
The old private name is deprecated, but will be available until the API
changes.

@end deffn

@geindex _PyCode_SetExtra (C function)

@geindex PyUnstable_Code_SetExtra (C function)
@anchor{c-api/code c _PyCode_SetExtra}@anchor{542f}@anchor{c-api/code c PyUnstable_Code_SetExtra}@anchor{5430}
@deffn {C の関数} int PyUnstable_Code_SetExtra (PyObject *code, Py_ssize_t index, void *extra)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Set the extra data stored under the given index to `extra'.
Return 0 on success. Set an exception and return -1 on failure.


Added in version 3.6: as @code{_PyCode_SetExtra}



バージョン 3.12 で変更: Renamed to @code{PyUnstable_Code_SetExtra}.
The old private name is deprecated, but will be available until the API
changes.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node その他のオブジェクト<2>,C API for extension modules,Function オブジェクト<2>,具象オブジェクト concrete object レイヤ
@anchor{c-api/concrete other-objects}@anchor{5431}
@subsection その他のオブジェクト


@menu
* ファイルオブジェクト:: 
* モジュールオブジェクト (module object): モジュールオブジェクト module object. 
* Module definitions:: 
* Creating extension modules dynamically:: 
* サポート関数:: 
* イテレータオブジェクト (iterator object): イテレータオブジェクト iterator object. 
* デスクリプタオブジェクト (descriptor object): デスクリプタオブジェクト descriptor object. 
* スライスオブジェクト (slice object): スライスオブジェクト slice object. 
* memoryview オブジェクト:: 
* Pickle buffer objects:: 
* 弱参照オブジェクト: 弱参照オブジェクト<2>. 
* カプセル: カプセル<2>. 
* フレーム (frame) オブジェクト: フレーム frame オブジェクト<2>. 
* ジェネレータオブジェクト:: 
* コルーチンオブジェクト: コルーチンオブジェクト<2>. 
* コンテキスト変数オブジェクト:: 
* 型ヒントのためのオブジェクト:: 

@end menu

@node ファイルオブジェクト,モジュールオブジェクト module object,,その他のオブジェクト<2>
@anchor{c-api/file doc}@anchor{5432}@anchor{c-api/file file-objects}@anchor{5433}@anchor{c-api/file fileobjects}@anchor{5434}
@subsubsection ファイルオブジェクト


@geindex object;ファイル

これらの API は、 Python 2 の組み込みのファイルオブジェクトの C API を最低限エミュレートするためのものです。それらは、標準 C ライブラリでサポートされているバッファ付き I/O (FILE*) に頼るために使われます。 Python 3 では、ファイルとストリームは新しい @ref{83,,io} モジュールを使用され、そこに OS の低レベルなバッファ付き I/O の上にいくつかの層が定義されています。下で解説されている関数は、それらの新しい API の便利な C ラッパーであり、インタプリタでの内部的なエラー通知に向いています; サードパーティーのコードは代わりに @ref{83,,io} の API を使うことが推奨されます。

@geindex PyFile_FromFd (C function)
@anchor{c-api/file c PyFile_FromFd}@anchor{5024}
@deffn {C の関数} @ref{5df,,PyObject} *PyFile_FromFd (int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
既に開かれているファイル `fd' のファイルディスクリプタから Python のファイルオブジェクトを作成します。
引数 `name' 、 `encoding' 、 `errors' 、 `newline' には、デフォルトの値として @code{NULL} が使えます。
`buffering' には `-1' を指定してデフォルトの値を使うことができます。
`name' は無視されるのですが、後方互換性のために残されています。
失敗すると @code{NULL} を返します。
より包括的な引数の解説は、 @ref{740,,io.open()} 関数のドキュメントを参照してください。

@cartouche
@quotation 警告 
Python ストリームは自身のバッファリング層を持つため、ファイル記述子のOSレベルのバッファリングと併用すると、様々な問題 (予期せぬデータ順) などを引き起こします。
@end quotation
@end cartouche


バージョン 3.2 で変更: `name' 属性の無視。

@end deffn

@geindex PyObject_AsFileDescriptor (C function)
@anchor{c-api/file c PyObject_AsFileDescriptor}@anchor{5087}
@deffn {C の関数} int PyObject_AsFileDescriptor (PyObject *p)
` 次に属します: @ref{775,,Stable ABI}.'
`p' に関連づけられる ファイルディスクリプタを int として返します。オブジェクトが整数なら、その値を返します。 整数でない場合、オブジェクトに @ref{17ad,,fileno()} メソッドがあれば呼び出します; このメソッドの返り値は、ファイル記述子の値として返される整数でなければなりません。失敗すると例外を設定して @code{-1} を返します。
@end deffn

@geindex PyFile_GetLine (C function)
@anchor{c-api/file c PyFile_GetLine}@anchor{5025}
@deffn {C の関数} @ref{5df,,PyObject} *PyFile_GetLine (PyObject *p, int n)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex EOFError (組み込み例外)

@code{p.readline([n])} と同じで、この関数はオブジェクト `p' の各行を読み出します。 `p' はファイルオブジェクトか、 @ref{1541,,readline()} メソッドを持つ何らかのオブジェクトでかまいません。 `n' が @code{0} の場合、行の長さに関係なく正確に 1 行だけ読み出します。 `n' が @code{0} より大きければ、 `n' バイト以上のデータは読み出しません; 従って、行の一部だけが返される場合があります。 どちらの場合でも、読み出し後すぐにファイルの終端に到達した場合には空文字列を 返します。 `n' が @code{0} より小さければ、長さに関わらず 1 行だけを 読み出しますが、すぐにファイルの終端に到達した場合には @ref{14f1,,EOFError} を送出します。
@end deffn

@geindex PyFile_SetOpenCodeHook (C function)
@anchor{c-api/file c PyFile_SetOpenCodeHook}@anchor{1a9a}
@deffn {C の関数} int PyFile_SetOpenCodeHook (Py_OpenCodeHookFunction handler)

@ref{1a98,,io.open_code()} の通常の振る舞いを上書きして、そのパラメーターを提供されたハンドラで渡します。

ハンドラーは次の型の関数です。

@geindex Py_OpenCodeHookFunction (C type)
@anchor{c-api/file c Py_OpenCodeHookFunction}@anchor{5435}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*Py_OpenCodeHookFunction)(@ref{5df,,PyObject}*, void*)

@ref{5df,,PyObject} *(*)(@ref{5df,,PyObject} *path, void *userData) と等価で、 `path' は @ref{997,,PyUnicodeObject} であることが保証されています。
@end deffn

`userData' ポインタはフック関数に渡されます。
フック関数は別なランタイムから呼び出されるかもしれないので、このポインタは直接 Python の状態を参照すべきではありません。

このフック関数はインポート中に使われることを意図しているため、モジュールが frozen なモジュールであるか @code{sys.modules} にある利用可能なモジュールであることが分かっている場合を除いては、フック関数の実行中に新しいモジュールをインポートするのは避けてください。

いったんフック関数が設定されたら、削除や置き換えもできず、後からの @ref{1a9a,,PyFile_SetOpenCodeHook()} の呼び出しは失敗します。
この関数が失敗したときは、インタープリタが初期化されていた場合、 -1 を返して例外をセットします。

この関数は @ref{460,,Py_Initialize()} より前に呼び出しても安全です。

引数無しで @ref{1c6e,,監査イベント} @code{setopencodehook} を送出します。


Added in version 3.8.

@end deffn

@geindex PyFile_OpenCodeObject (C function)
@anchor{c-api/file c PyFile_OpenCodeObject}@anchor{5436}
@deffn {C の関数} @ref{5df,,PyObject} *PyFile_OpenCodeObject (PyObject *path)

Open `path' with the mode @code{'rb'}. `path' must be a Python @ref{169,,str}
object. The behavior of this function may be overridden by
@ref{1a9a,,PyFile_SetOpenCodeHook()} to allow for some preprocessing of the
text.

This is analogous to @ref{1a98,,io.open_code()} in Python.

On success, this function returns a @ref{5e2,,strong reference} to a Python
file object. On failure, this function returns @code{NULL} with an exception
set.


Added in version 3.8.

@end deffn

@geindex PyFile_OpenCode (C function)
@anchor{c-api/file c PyFile_OpenCode}@anchor{5437}
@deffn {C の関数} @ref{5df,,PyObject} *PyFile_OpenCode (const char *path)

Similar to @ref{5436,,PyFile_OpenCodeObject()}, but `path' is a
UTF-8 encoded const char*.


Added in version 3.8.

@end deffn

@geindex PyFile_WriteObject (C function)
@anchor{c-api/file c PyFile_WriteObject}@anchor{5026}
@deffn {C の関数} int PyFile_WriteObject (PyObject *obj, PyObject *p, int flags)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex Py_PRINT_RAW (Cのマクロ)

オブジェクト `obj' をファイルオブジェクト `p' に書き込みます。 `flags' がサポートするフラグは @ref{5287,,Py_PRINT_RAW} だけです; このフラグを指定すると、オブジェクトに @ref{1c1,,repr()} ではなく @ref{169,,str()} を適用した結果をファイルに書き出します。成功した場合には @code{0} を返し、失敗すると @code{-1} を返して適切な例外をセットします。
@end deffn

@geindex PyFile_WriteString (C function)
@anchor{c-api/file c PyFile_WriteString}@anchor{5027}
@deffn {C の関数} int PyFile_WriteString (const char *s, PyObject *p)
` 次に属します: @ref{775,,Stable ABI}.'
文字列 `s' をファイルオブジェクト `p' に書き出します。成功した場合には @code{0} を返し、失敗すると @code{-1} を返して適切な例外をセットします。
@end deffn

@menu
* Deprecated API: Deprecated API<4>. 

@end menu

@node Deprecated API<4>,,,ファイルオブジェクト
@anchor{c-api/file deprecated-api}@anchor{5438}
@subsubsection Deprecated API


These are @ref{23d,,soft deprecated} APIs that were included in Python's C API
by mistake. They are documented solely for completeness; use other
@code{PyFile*} APIs instead.

@geindex PyFile_NewStdPrinter (C function)
@anchor{c-api/file c PyFile_NewStdPrinter}@anchor{5439}
@deffn {C の関数} @ref{5df,,PyObject} *PyFile_NewStdPrinter (int fd)

Use @ref{5024,,PyFile_FromFd()} with defaults (@code{fd, NULL, "w", -1, NULL, NULL, NULL, 0}) instead.
@end deffn

@geindex PyStdPrinter_Type (C var)
@anchor{c-api/file c PyStdPrinter_Type}@anchor{543a}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyStdPrinter_Type

Type of file-like objects used internally at Python startup when @ref{83,,io} is
not yet available.
Use Python @ref{316,,open()} or @ref{5024,,PyFile_FromFd()} to create file objects instead.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node モジュールオブジェクト module object,Module definitions,ファイルオブジェクト,その他のオブジェクト<2>
@anchor{c-api/module doc}@anchor{543b}@anchor{c-api/module module-objects}@anchor{543c}@anchor{c-api/module moduleobjects}@anchor{543d}@anchor{c-api/module translation-repo}@anchor{543e}
@subsubsection モジュールオブジェクト (module object)


@geindex object;module

@geindex PyModule_Type (C var)
@anchor{c-api/module c PyModule_Type}@anchor{5063}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyModule_Type
` 次に属します: @ref{775,,Stable ABI}.'
@geindex ModuleType (in module types)

This instance of @ref{c9c,,PyTypeObject} represents the Python module type.  This
is exposed to Python programs as @ref{1014,,types.ModuleType}.
@end deffn

@geindex PyModule_Check (C function)
@anchor{c-api/module c PyModule_Check}@anchor{543f}
@deffn {C の関数} int PyModule_Check (PyObject *p)

`p' がモジュールオブジェクトかモジュールオブジェクトのサブタイプであるときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyModule_CheckExact (C function)
@anchor{c-api/module c PyModule_CheckExact}@anchor{5440}
@deffn {C の関数} int PyModule_CheckExact (PyObject *p)

`p' がモジュールオブジェクトで、かつ @ref{5063,,PyModule_Type} のサブタイプでないときに真を返します。この関数は常に成功します。
@end deffn

@geindex PyModule_NewObject (C function)
@anchor{c-api/module c PyModule_NewObject}@anchor{5061}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_NewObject (PyObject *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@geindex __name__ (モジュール属性)
@geindex __doc__ (モジュール属性)
@geindex __file__ (モジュール属性)
@geindex __package__ (module attribute)
@geindex __loader__ (module attribute)

Return a new module object with @ref{15a3,,module.__name__} set to `name'.
The module's @code{__name__}, @ref{1bef,,__doc__},
@ref{323,,__package__} and @ref{33b,,__loader__} attributes are
filled in (all but @code{__name__} are set to @code{None}). The caller is
responsible for setting a @ref{2369,,__file__} attribute.

Return @code{NULL} with an exception set on error.


Added in version 3.3.



バージョン 3.4 で変更: @ref{323,,__package__} and @ref{33b,,__loader__} are now set to
@code{None}.

@end deffn

@geindex PyModule_New (C function)
@anchor{c-api/module c PyModule_New}@anchor{5060}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_New (const char *name)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{5061,,PyModule_NewObject()} に似ていますが、 name は Unicode オブジェクトではなく UTF-8 でエンコードされた文字列です。
@end deffn

@geindex PyModule_GetDict (C function)
@anchor{c-api/module c PyModule_GetDict}@anchor{505d}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_GetDict (PyObject *module)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex __dict__ (モジュール属性)

`module' の名前空間を実装する辞書オブジェクトを返します;
このオブジェクトは、モジュールオブジェクトの @ref{77d,,__dict__} 属性と同じものです。
`module' がモジュールオブジェクト (もしくはモジュールオブジェクトのサブタイプ) でない場合は、 @ref{795,,SystemError} が送出され @code{NULL} が返されます。

拡張モジュールでは、モジュールの @ref{77d,,__dict__} を直接操作するよりも、 @code{PyModule_*} および @code{PyObject_*} 関数を使う方が推奨されます。

The returned reference is borrowed from the module; it is valid until
the module is destroyed.
@end deffn

@geindex PyModule_GetNameObject (C function)
@anchor{c-api/module c PyModule_GetNameObject}@anchor{505f}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_GetNameObject (PyObject *module)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
@geindex __name__ (モジュール属性)
@geindex SystemError (組み込み例外)

Return `module''s @ref{15a3,,__name__} value.  If the module does not
provide one, or if it is not a string, @ref{795,,SystemError} is raised and
@code{NULL} is returned.


Added in version 3.3.

@end deffn

@geindex PyModule_GetName (C function)
@anchor{c-api/module c PyModule_GetName}@anchor{505e}
@deffn {C の関数} const char *PyModule_GetName (PyObject *module)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{505f,,PyModule_GetNameObject()} に似ていますが、 @code{'utf-8'} でエンコードされた name を返します。

The returned buffer is only valid until the module is renamed or destroyed.
Note that Python code may rename a module by setting its @ref{15a3,,__name__}
attribute.
@end deffn

@geindex PyModule_GetState (C function)
@anchor{c-api/module c PyModule_GetState}@anchor{b77}
@deffn {C の関数} void *PyModule_GetState (PyObject *module)
` 次に属します: @ref{775,,Stable ABI}.'
モジュールの "state"(モジュールを生成したタイミングで確保されるメモリブロックへのポインター) か、なければ @code{NULL} を返します。 @ref{b76,,PyModuleDef.m_size} を参照してください。
@end deffn

@geindex PyModule_GetDef (C function)
@anchor{c-api/module c PyModule_GetDef}@anchor{505c}
@deffn {C の関数} @ref{b74,,PyModuleDef} *PyModule_GetDef (PyObject *module)
` 次に属します: @ref{775,,Stable ABI}.'
モジュールが作られる元となった @ref{b74,,PyModuleDef} 構造体へのポインタを返します。
モジュールが定義によって作られていなかった場合は @code{NULL} を返します。

On error, return @code{NULL} with an exception set.
Use @ref{1caf,,PyErr_Occurred()} to tell this case apart from a missing
@code{PyModuleDef}.
@end deffn

@geindex PyModule_GetFilenameObject (C function)
@anchor{c-api/module c PyModule_GetFilenameObject}@anchor{42e}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_GetFilenameObject (PyObject *module)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@geindex __file__ (モジュール属性)
@geindex SystemError (組み込み例外)

Return the name of the file from which `module' was loaded using `module''s
@ref{2369,,__file__} attribute.  If this is not defined, or if it is not a
string, raise @ref{795,,SystemError} and return @code{NULL}; otherwise return
a reference to a Unicode object.


Added in version 3.2.

@end deffn

@geindex PyModule_GetFilename (C function)
@anchor{c-api/module c PyModule_GetFilename}@anchor{42d}
@deffn {C の関数} const char *PyModule_GetFilename (PyObject *module)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{42e,,PyModule_GetFilenameObject()} と似ていますが、 'utf-8' でエンコードされたファイル名を返します。

The returned buffer is only valid until the module's @ref{2369,,__file__} attribute
is reassigned or the module is destroyed.


バージョン 3.2 で非推奨: @ref{42d,,PyModule_GetFilename()} はエンコードできないファイル名に対しては @ref{887,,UnicodeEncodeError} を送出します。これの代わりに @ref{42e,,PyModule_GetFilenameObject()} を使用してください。

@end deffn

@node Module definitions,Creating extension modules dynamically,モジュールオブジェクト module object,その他のオブジェクト<2>
@anchor{c-api/module module-definitions}@anchor{5441}@anchor{c-api/module pymoduledef}@anchor{5442}
@subsubsection Module definitions


The functions in the previous section work on any module object, including
modules imported from Python code.

Modules defined using the C API typically use a `module definition',
@ref{b74,,PyModuleDef} -- a statically allocated, constant “description" of
how a module should be created.

The definition is usually used to define an extension's “main” module object
(see @ref{4efc,,拡張モジュールの定義} for details).
It is also used to
@ref{5443,,create extension modules dynamically}.

Unlike @ref{5060,,PyModule_New()}, the definition allows management of
`module state' -- a piece of memory that is allocated and cleared together
with the module object.
Unlike the module's Python attributes, Python code cannot replace or delete
data stored in module state.

@geindex PyModuleDef (C type)
@anchor{c-api/module c PyModuleDef}@anchor{b74}
@deffn {C のデータ型} type PyModuleDef
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
The module definition struct, which holds all information needed to create
a module object.
This structure must be statically allocated (or be otherwise guaranteed
to be valid while any modules created from it exist).
Usually, there is only one variable of this type for each extension module.

@geindex PyModuleDef.m_base (C member)
@anchor{c-api/module c PyModuleDef m_base}@anchor{5444}
@deffn {C のメンバ変数} PyModuleDef_Base m_base

このメンバーは常に @code{PyModuleDef_HEAD_INIT} で初期化してください。
@end deffn

@geindex PyModuleDef.m_name (C member)
@anchor{c-api/module c PyModuleDef m_name}@anchor{5445}
@deffn {C のメンバ変数} const char *m_name

新しいモジュールの名前。
@end deffn

@geindex PyModuleDef.m_doc (C member)
@anchor{c-api/module c PyModuleDef m_doc}@anchor{5446}
@deffn {C のメンバ変数} const char *m_doc

モジュールの docstring。たいてい docstring は @ref{1d5b,,PyDoc_STRVAR} を利用して生成されます。
@end deffn

@geindex PyModuleDef.m_size (C member)
@anchor{c-api/module c PyModuleDef m_size}@anchor{b76}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} m_size

モジュールの状態は、静的なグローバルな領域ではなく @ref{b77,,PyModule_GetState()} で取得できるモジュールごとのメモリ領域に保持されていることがあります。
これによってモジュールは複数のサブ・インタプリターで安全に使えます。

このメモリ領域は `m_size' に基づいてモジュール作成時に確保され、モジュールオブジェクトが破棄されるときに、 @ref{b73,,m_free} 関数があればそれが呼ばれた後で解放されます。

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.

Setting @code{m_size} to @code{-1} means that the module does not support
sub-interpreters, because it has global state.
Negative @code{m_size} is only allowed when using
@ref{520e,,legacy single-phase initialization}
or when @ref{5443,,creating modules dynamically}.

詳細は 
@geindex Python Enhancement Proposals; PEP 3121
PEP 3121@footnote{https://peps.python.org/pep-3121/} を参照。
@end deffn

@geindex PyModuleDef.m_methods (C member)
@anchor{c-api/module c PyModuleDef m_methods}@anchor{5447}
@deffn {C のメンバ変数} @ref{16f0,,PyMethodDef} *m_methods

@ref{16f0,,PyMethodDef} で定義される、モジュールレベル関数のテーブルへのポインター。関数が存在しない場合は @code{NULL} を設定することが可能。
@end deffn

@geindex PyModuleDef.m_slots (C member)
@anchor{c-api/module c PyModuleDef m_slots}@anchor{5215}
@deffn {C のメンバ変数} @ref{5059,,PyModuleDef_Slot} *m_slots

An array of slot definitions for multi-phase initialization, terminated by
a @code{@{0, NULL@}} entry.
When using legacy single-phase initialization, `m_slots' must be @code{NULL}.


バージョン 3.5 で変更: バージョン 3.5 より前は、このメンバは常に @code{NULL} に設定されていて、次のものとして定義されていました:

@quotation

@geindex PyModuleDef.m_slots.m_reload (C member)
@anchor{c-api/module c PyModuleDef m_slots m_reload}@anchor{5448}
@deffn {C のメンバ変数} @ref{51ab,,inquiry} m_reload
@end deffn
@end quotation

@end deffn

@geindex PyModuleDef.m_traverse (C member)
@anchor{c-api/module c PyModuleDef m_traverse}@anchor{b71}
@deffn {C のメンバ変数} @ref{51ba,,traverseproc} m_traverse

GC走査がモジュールオブジェクトを走査する際に呼び出される走査関数。必要ない場合は @code{NULL}.

This function is not called if the module state was requested but is not
allocated yet. This is the case immediately after the module is created
and before the module is executed (@ref{b75,,Py_mod_exec} function). More
precisely, this function is not called if @ref{b76,,m_size} is greater
than 0 and the module state (as returned by @ref{b77,,PyModule_GetState()})
is @code{NULL}.


バージョン 3.9 で変更: No longer called before the module state is allocated.

@end deffn

@geindex PyModuleDef.m_clear (C member)
@anchor{c-api/module c PyModuleDef m_clear}@anchor{b72}
@deffn {C のメンバ変数} @ref{51ab,,inquiry} m_clear

GCがこのモジュールオブジェクトをクリアーする時に呼び出されるクリアー関数。必要ない場合は、@code{NULL}.

This function is not called if the module state was requested but is not
allocated yet. This is the case immediately after the module is created
and before the module is executed (@ref{b75,,Py_mod_exec} function). More
precisely, this function is not called if @ref{b76,,m_size} is greater
than 0 and the module state (as returned by @ref{b77,,PyModule_GetState()})
is @code{NULL}.

Like @ref{4ee2,,PyTypeObject.tp_clear}, 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
@ref{b73,,m_free} is called directly.


バージョン 3.9 で変更: No longer called before the module state is allocated.

@end deffn

@geindex PyModuleDef.m_free (C member)
@anchor{c-api/module c PyModuleDef m_free}@anchor{b73}
@deffn {C のメンバ変数} @ref{5449,,freefunc} m_free

GCがこのモジュールオブジェクトを解放するときに呼び出される関数。必要ない場合は @code{NULL}.

This function is not called if the module state was requested but is not
allocated yet. This is the case immediately after the module is created
and before the module is executed (@ref{b75,,Py_mod_exec} function). More
precisely, this function is not called if @ref{b76,,m_size} is greater
than 0 and the module state (as returned by @ref{b77,,PyModule_GetState()})
is @code{NULL}.


バージョン 3.9 で変更: No longer called before the module state is allocated.

@end deffn
@end deffn

@menu
* Module slots:: 

@end menu

@node Module slots,,,Module definitions
@anchor{c-api/module module-slots}@anchor{544a}
@subsubsection Module slots


@geindex PyModuleDef_Slot (C type)
@anchor{c-api/module c PyModuleDef_Slot}@anchor{5059}
@deffn {C のデータ型} type PyModuleDef_Slot
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む) (バージョン 3.5 より).'
@geindex PyModuleDef_Slot.slot (C member)
@anchor{c-api/module c PyModuleDef_Slot slot}@anchor{544b}
@deffn {C のメンバ変数} int slot

スロット ID で、以下で説明されている利用可能な値から選ばれます。
@end deffn

@geindex PyModuleDef_Slot.value (C member)
@anchor{c-api/module c PyModuleDef_Slot value}@anchor{544c}
@deffn {C のメンバ変数} void *value

スロットの値で、意味はスロット ID に依存します。
@end deffn


Added in version 3.5.

@end deffn

利用可能なスロットの型は以下です:

@geindex Py_mod_create (C macro)
@anchor{c-api/module c Py_mod_create}@anchor{5151}
@deffn {C のマクロ} Py_mod_create
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.5 より).'
モジュールオブジェクト自身を生成するために呼ばれる関数を指定します。
このスロットの `value' ポインタは次のシグネチャを持つ関数を指していなくてはいけません:

@anchor{c-api/module c Py_mod_create create_module}@anchor{544d}
@deffn {C の関数} @ref{5df,,PyObject} *create_module (PyObject *spec, PyModuleDef *def)
@end deffn

@geindex Python Enhancement Proposals; PEP 451
PEP 451@footnote{https://peps.python.org/pep-0451/} で定義された @ref{226c,,ModuleSpec} インスタンスと、モジュール定義を受け取る関数です。
これは新しいモジュールオブジェクトを返すか、エラーを設定して @code{NULL} を返すべきです。

この関数は最小限に留めておくべきです。
特に任意のPythonコードを呼び出すべきではなく、同じモジュールをインポートしようとすると無限ループに陥るでしょう。

複数の @code{Py_mod_create} スロットを1つのモジュール定義に設定しない方がよいです。

@code{Py_mod_create} が設定されていない場合は、インポート機構は @ref{5060,,PyModule_New()} を使って通常のモジュールオブジェクトを生成します。
モジュールの名前は定義ではなく `spec' から取得され、これによって拡張モジュールが動的にモジュール階層における位置を調整できたり、シンボリックリンクを通して同一のモジュール定義を共有しつつ別の名前でインポートできたりします。

返されるオブジェクトが @ref{5063,,PyModule_Type} のインスタンスである必要はありません。
インポートに関連する属性の設定と取得ができる限りは、どんな型でも使えます。
しかし、 @code{PyModuleDef} が @code{NULL} でない @code{m_traverse}, @code{m_clear}, @code{m_free} 、もしくはゼロでない @code{m_size} 、もしくは @code{Py_mod_create} 以外のスロットを持つ場合は、 @code{PyModule_Type} インスタンスのみが返されるでしょう。


Added in version 3.5.

@end deffn

@geindex Py_mod_exec (C macro)
@anchor{c-api/module c Py_mod_exec}@anchor{b75}
@deffn {C のマクロ} Py_mod_exec
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.5 より).'
モジュールを `実行する' ときに呼ばれる関数を指定します。
これはPythonモジュールのコードを実行するのと同等です:
この関数はたいていはクラスと定数をモジュールにします。
この関数のシグネチャは以下です:

@anchor{c-api/module c Py_mod_exec exec_module}@anchor{544e}
@deffn {C の関数} int exec_module (PyObject *module)
@end deffn

複数の @code{Py_mod_exec} スロットが設定されていた場合は、 `m_slots' 配列に現れた順に処理されていきます。


Added in version 3.5.

@end deffn

@geindex Py_mod_multiple_interpreters (C macro)
@anchor{c-api/module c Py_mod_multiple_interpreters}@anchor{5152}
@deffn {C のマクロ} Py_mod_multiple_interpreters
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Specifies one of the following values:

@geindex Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED (C macro)
@anchor{c-api/module c Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}@anchor{4ea4}
@deffn {C のマクロ} Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED

The module does not support being imported in subinterpreters.
@end deffn

@geindex Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED (C macro)
@anchor{c-api/module c Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED}@anchor{544f}
@deffn {C のマクロ} Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED

The module supports being imported in subinterpreters,
but only when they share the main interpreter's GIL.
(See @ref{166,,拡張モジュールを分離する}.)
@end deffn

@geindex Py_MOD_PER_INTERPRETER_GIL_SUPPORTED (C macro)
@anchor{c-api/module c Py_MOD_PER_INTERPRETER_GIL_SUPPORTED}@anchor{5450}
@deffn {C のマクロ} Py_MOD_PER_INTERPRETER_GIL_SUPPORTED

The module supports being imported in subinterpreters,
even when they have their own GIL.
(See @ref{166,,拡張モジュールを分離する}.)
@end deffn

This slot determines whether or not importing this module
in a subinterpreter will fail.

Multiple @code{Py_mod_multiple_interpreters} slots may not be specified
in one module definition.

If @code{Py_mod_multiple_interpreters} is not specified, the import
machinery defaults to @code{Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED}.


Added in version 3.12.

@end deffn

@geindex Py_mod_gil (C macro)
@anchor{c-api/module c Py_mod_gil}@anchor{482}
@deffn {C のマクロ} Py_mod_gil
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Specifies one of the following values:

@geindex Py_MOD_GIL_USED (C macro)
@anchor{c-api/module c Py_MOD_GIL_USED}@anchor{5451}
@deffn {C のマクロ} Py_MOD_GIL_USED

The module depends on the presence of the global interpreter lock (GIL),
and may access global state without synchronization.
@end deffn

@geindex Py_MOD_GIL_NOT_USED (C macro)
@anchor{c-api/module c Py_MOD_GIL_NOT_USED}@anchor{5452}
@deffn {C のマクロ} Py_MOD_GIL_NOT_USED

The module is safe to run without an active GIL.
@end deffn

This slot is ignored by Python builds not configured with
@ref{499,,--disable-gil}.  Otherwise, it determines whether or not importing
this module will cause the GIL to be automatically enabled. See
@ref{46d,,フリースレッドの CPython} for more detail.

Multiple @code{Py_mod_gil} slots may not be specified in one module definition.

If @code{Py_mod_gil} is not specified, the import machinery defaults to
@code{Py_MOD_GIL_USED}.


Added in version 3.13.

@end deffn

@node Creating extension modules dynamically,サポート関数,Module definitions,その他のオブジェクト<2>
@anchor{c-api/module creating-extension-modules-dynamically}@anchor{5453}@anchor{c-api/module moduledef-dynamic}@anchor{5443}
@subsubsection Creating extension modules dynamically


The following functions may be used to create a module outside of an
extension's @ref{520d,,initialization function}.
They are also used in
@ref{520e,,single-phase initialization}.

@geindex PyModule_Create (C function)
@anchor{c-api/module c PyModule_Create}@anchor{5217}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_Create (PyModuleDef *def)
`戻り値: 新しい参照。'
Create a new module object, given the definition in `def'.
This is a macro that calls @ref{505b,,PyModule_Create2()} with
`module_api_version' set to @ref{492e,,PYTHON_API_VERSION}, or
to @ref{5454,,PYTHON_ABI_VERSION} if using the
@ref{637,,limited API}.
@end deffn

@geindex PyModule_Create2 (C function)
@anchor{c-api/module c PyModule_Create2}@anchor{505b}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_Create2 (PyModuleDef *def, int module_api_version)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
APIバージョンを `module_api_version' として `def' での定義に従って新しいモジュールオブジェクトを生成します。
もし指定されたバージョンが実行しているインタープリターのバージョンと異なる場合は、 @ref{4d7,,RuntimeWarning} を発生させます。

Return @code{NULL} with an exception set on error.

This function does not support slots.
The @ref{5215,,m_slots} member of `def' must be @code{NULL}.

@cartouche
@quotation 注釈 
ほとんどの場合、この関数ではなく @ref{5217,,PyModule_Create()} を利用するべきです。この関数は、この関数の必要性を理解しているときにだけ利用してください。
@end quotation
@end cartouche
@end deffn

@geindex PyModule_FromDefAndSpec (C function)
@anchor{c-api/module c PyModule_FromDefAndSpec}@anchor{10b3}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_FromDefAndSpec (PyModuleDef *def, PyObject *spec)
`戻り値: 新しい参照。'
This macro calls @ref{10b4,,PyModule_FromDefAndSpec2()} with
`module_api_version' set to @ref{492e,,PYTHON_API_VERSION}, or
to @ref{5454,,PYTHON_ABI_VERSION} if using the
@ref{637,,limited API}.


Added in version 3.5.

@end deffn

@geindex PyModule_FromDefAndSpec2 (C function)
@anchor{c-api/module c PyModule_FromDefAndSpec2}@anchor{10b4}
@deffn {C の関数} @ref{5df,,PyObject} *PyModule_FromDefAndSpec2 (PyModuleDef *def, PyObject *spec, int module_api_version)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
APIバージョンを `module_api_version' として、 `def' と ModuleSpec オブジェクトの `spec' で定義されたとおりに新しいモジュールオブジェクトを生成します。
もし指定されたバージョンが実行しているインタープリターのバージョンと異なる場合は、 @ref{4d7,,RuntimeWarning} を発生させます。

Return @code{NULL} with an exception set on error.

Note that this does not process execution slots (@ref{b75,,Py_mod_exec}).
Both @code{PyModule_FromDefAndSpec} and @code{PyModule_ExecDef} must be called
to fully initialize a module.

@cartouche
@quotation 注釈 
ほとんどの場合、この関数ではなく @ref{10b3,,PyModule_FromDefAndSpec()} を利用するべきです。
この関数は、この関数の必要性を理解しているときにだけ利用してください。
@end quotation
@end cartouche


Added in version 3.5.

@end deffn

@geindex PyModule_ExecDef (C function)
@anchor{c-api/module c PyModule_ExecDef}@anchor{10b5}
@deffn {C の関数} int PyModule_ExecDef (PyObject *module, PyModuleDef *def)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
`def' で与えられた任意の実行スロット (@ref{b75,,Py_mod_exec}) を実行します。


Added in version 3.5.

@end deffn

@geindex PYTHON_API_VERSION (C macro)
@anchor{c-api/module c PYTHON_API_VERSION}@anchor{492e}
@deffn {C のマクロ} PYTHON_API_VERSION

The C API version. Defined for backwards compatibility.

Currently, this constant is not updated in new Python versions, and is not
useful for versioning. This may change in the future.
@end deffn

@geindex PYTHON_ABI_VERSION (C macro)
@anchor{c-api/module c PYTHON_ABI_VERSION}@anchor{5454}
@deffn {C のマクロ} PYTHON_ABI_VERSION

Defined as @code{3} for backwards compatibility.

Currently, this constant is not updated in new Python versions, and is not
useful for versioning. This may change in the future.
@end deffn

@node サポート関数,イテレータオブジェクト iterator object,Creating extension modules dynamically,その他のオブジェクト<2>
@anchor{c-api/module support-functions}@anchor{5455}
@subsubsection サポート関数


The following functions are provided to help initialize a module
state.
They are intended for a module's execution slots (@ref{b75,,Py_mod_exec}),
the initialization function for legacy @ref{520e,,single-phase initialization},
or code that creates modules dynamically.

@geindex PyModule_AddObjectRef (C function)
@anchor{c-api/module c PyModule_AddObjectRef}@anchor{60a}
@deffn {C の関数} int PyModule_AddObjectRef (PyObject *module, const char *name, PyObject *value)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
`module' にオブジェクトを `name' として追加します。
この関数はモジュールの初期化関数から利用される便利関数です。

成功すると @code{0} を返し、エラーになると例外を送出して @code{-1} を返します。

使用例:

@example
static int
add_spam(PyObject *module, int value)
@{
    PyObject *obj = PyLong_FromLong(value);
    if (obj == NULL) @{
        return -1;
    @}
    int res = PyModule_AddObjectRef(module, "spam", obj);
    Py_DECREF(obj);
    return res;
 @}
@end example

To be convenient, the function accepts @code{NULL} `value' with an exception
set. In this case, return @code{-1} and just leave the raised exception
unchanged.

この例は、明示的に `obj' が @code{NULL} であることを確認せずに書くこともできます:

@example
static int
add_spam(PyObject *module, int value)
@{
    PyObject *obj = PyLong_FromLong(value);
    int res = PyModule_AddObjectRef(module, "spam", obj);
    Py_XDECREF(obj);
    return res;
 @}
@end example

この場合は、 `obj' が @code{NULL} でありうるため、 @code{Py_DECREF()} の代わりに @code{Py_XDECREF()} を呼び出す必要があることに注意してください。

The number of different `name' strings passed to this function
should be kept small, usually by only using statically allocated strings
as `name'.
For names that aren't known at compile time, prefer calling
@ref{5112,,PyUnicode_FromString()} and @ref{5097,,PyObject_SetAttr()} directly.
For more details, see @ref{198c,,PyUnicode_InternFromString()}, which may be
used internally to create a key object.


Added in version 3.10.

@end deffn

@geindex PyModule_Add (C function)
@anchor{c-api/module c PyModule_Add}@anchor{609}
@deffn {C の関数} int PyModule_Add (PyObject *module, const char *name, PyObject *value)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Similar to @ref{60a,,PyModule_AddObjectRef()}, but "steals" a reference
to `value'.
It can be called with a result of function that returns a new reference
without bothering to check its result or even saving it to a variable.

使用例:

@example
if (PyModule_Add(module, "spam", PyBytes_FromString(value)) < 0) @{
    goto error;
@}
@end example


Added in version 3.13.

@end deffn

@geindex PyModule_AddObject (C function)
@anchor{c-api/module c PyModule_AddObject}@anchor{60b}
@deffn {C の関数} int PyModule_AddObject (PyObject *module, const char *name, PyObject *value)
` 次に属します: @ref{775,,Stable ABI}.'
Similar to @ref{60a,,PyModule_AddObjectRef()}, but steals a reference to
`value' on success (if it returns @code{0}).

The new @ref{609,,PyModule_Add()} or @ref{60a,,PyModule_AddObjectRef()}
functions are recommended, since it is
easy to introduce reference leaks by misusing the
@ref{60b,,PyModule_AddObject()} function.

@cartouche
@quotation 注釈 
Unlike other functions that steal references, @code{PyModule_AddObject()}
only releases the reference to `value' `on success'.

This means that its return value must be checked, and calling code must
@ref{992,,Py_XDECREF()} `value' manually on error.
@end quotation
@end cartouche

使用例:

@example
PyObject *obj = PyBytes_FromString(value);
if (PyModule_AddObject(module, "spam", obj) < 0) @{
    // If 'obj' is not NULL and PyModule_AddObject() failed,
    // 'obj' strong reference must be deleted with Py_XDECREF().
    // If 'obj' is NULL, Py_XDECREF() does nothing.
    Py_XDECREF(obj);
    goto error;
@}
// PyModule_AddObject() stole a reference to obj:
// Py_XDECREF(obj) is not needed here.
@end example


バージョン 3.13 で非推奨: @ref{60b,,PyModule_AddObject()} is @ref{23d,,soft deprecated}.

@end deffn

@geindex PyModule_AddIntConstant (C function)
@anchor{c-api/module c PyModule_AddIntConstant}@anchor{1755}
@deffn {C の関数} int PyModule_AddIntConstant (PyObject *module, const char *name, long value)
` 次に属します: @ref{775,,Stable ABI}.'
Add an integer constant to `module' as `name'.  This convenience function can be
used from the module's initialization function.
Return @code{-1} with an exception set on error, @code{0} on success.

This is a convenience function that calls @ref{1bd0,,PyLong_FromLong()} and
@ref{60a,,PyModule_AddObjectRef()}; see their documentation for details.
@end deffn

@geindex PyModule_AddStringConstant (C function)
@anchor{c-api/module c PyModule_AddStringConstant}@anchor{1756}
@deffn {C の関数} int PyModule_AddStringConstant (PyObject *module, const char *name, const char *value)
` 次に属します: @ref{775,,Stable ABI}.'
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
@code{NULL}-terminated.
Return @code{-1} with an exception set on error, @code{0} on success.

This is a convenience function that calls
@ref{198c,,PyUnicode_InternFromString()} and @ref{60a,,PyModule_AddObjectRef()};
see their documentation for details.
@end deffn

@geindex PyModule_AddIntMacro (C macro)
@anchor{c-api/module c PyModule_AddIntMacro}@anchor{160c}
@deffn {C のマクロ} PyModule_AddIntMacro (module, macro)

Add an int constant to `module'. The name and the value are taken from
`macro'. For example @code{PyModule_AddIntMacro(module, AF_INET)} adds the int
constant `AF_INET' with the value of `AF_INET' to `module'.
Return @code{-1} with an exception set on error, @code{0} on success.
@end deffn

@geindex PyModule_AddStringMacro (C macro)
@anchor{c-api/module c PyModule_AddStringMacro}@anchor{160b}
@deffn {C のマクロ} PyModule_AddStringMacro (module, macro)

文字列定数を `module' に追加します。
@end deffn

@geindex PyModule_AddType (C function)
@anchor{c-api/module c PyModule_AddType}@anchor{b6c}
@deffn {C の関数} int PyModule_AddType (PyObject *module, PyTypeObject *type)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Add a type object to `module'.
The type object is finalized by calling internally @ref{980,,PyType_Ready()}.
The name of the type object is taken from the last component of
@ref{1cb0,,tp_name} after dot.
Return @code{-1} with an exception set on error, @code{0} on success.


Added in version 3.9.

@end deffn

@geindex PyModule_AddFunctions (C function)
@anchor{c-api/module c PyModule_AddFunctions}@anchor{505a}
@deffn {C の関数} int PyModule_AddFunctions (PyObject *module, PyMethodDef *functions)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Add the functions from the @code{NULL} terminated `functions' array to `module'.
Refer to the @ref{16f0,,PyMethodDef} documentation for details on individual
entries (due to the lack of a shared module namespace, module level
"functions" implemented in C typically receive the module as their first
parameter, making them similar to instance methods on Python classes).

This function is called automatically when creating a module from
@code{PyModuleDef} (such as when using @ref{5213,,多段階初期化},
@code{PyModule_Create}, or @code{PyModule_FromDefAndSpec}).
Some module authors may prefer defining functions in multiple
@ref{16f0,,PyMethodDef} arrays; in that case they should call this function
directly.

The `functions' array must be statically allocated (or otherwise guaranteed
to outlive the module object).


Added in version 3.5.

@end deffn

@geindex PyModule_SetDocString (C function)
@anchor{c-api/module c PyModule_SetDocString}@anchor{5062}
@deffn {C の関数} int PyModule_SetDocString (PyObject *module, const char *docstring)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Set the docstring for `module' to `docstring'.
This function is called automatically when creating a module from
@code{PyModuleDef} (such as when using @ref{5213,,多段階初期化},
@code{PyModule_Create}, or @code{PyModule_FromDefAndSpec}).

Return @code{0} on success.
Return @code{-1} with an exception set on error.


Added in version 3.5.

@end deffn

@geindex PyUnstable_Module_SetGIL (C function)
@anchor{c-api/module c PyUnstable_Module_SetGIL}@anchor{49d}
@deffn {C の関数} int PyUnstable_Module_SetGIL (PyObject *module, void *gil)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Indicate that `module' does or does not support running without the global
interpreter lock (GIL), using one of the values from
@ref{482,,Py_mod_gil}. It must be called during `module''s initialization
function when using @ref{520e,,従来の一段階初期化}.
If this function is not called during module initialization, the
import machinery assumes the module does not support running without the
GIL. This function is only available in Python builds configured with
@ref{499,,--disable-gil}.
Return @code{-1} with an exception set on error, @code{0} on success.


Added in version 3.13.

@end deffn

@menu
* Module lookup (single-phase initialization): Module lookup single-phase initialization. 

@end menu

@node Module lookup single-phase initialization,,,サポート関数
@anchor{c-api/module module-lookup-single-phase-initialization}@anchor{5456}
@subsubsection Module lookup (single-phase initialization)


The legacy @ref{520e,,single-phase initialization}
initialization scheme 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.

多段階初期化を使うと単一の定義から複数のモジュールが作成できるので、これらの関数は多段階初期化を使って作成されたモジュールには使えません。

@geindex PyState_FindModule (C function)
@anchor{c-api/module c PyState_FindModule}@anchor{50b5}
@deffn {C の関数} @ref{5df,,PyObject} *PyState_FindModule (PyModuleDef *def)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
現在のインタプリタの `def' から作られたモジュールオブジェクトを返します。このメソッドの前提条件として、前もって @ref{50b4,,PyState_AddModule()} でインタプリタの state にモジュールオブジェクトを連結しておくことを要求します。対応するモジュールオブジェクトが見付からない、もしくは事前にインタプリタの state に連結されていない場合は、 @code{NULL} を返します。
@end deffn

@geindex PyState_AddModule (C function)
@anchor{c-api/module c PyState_AddModule}@anchor{50b4}
@deffn {C の関数} int PyState_AddModule (PyObject *module, PyModuleDef *def)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.3 より).'
関数に渡されたモジュールオブジェクトを、インタプリタの state に連結します。この関数を使うことで @ref{50b5,,PyState_FindModule()} からモジュールオブジェクトにアクセスできるようになります。

一段階初期化を使って作成されたモジュールにのみ有効です。

Python calls @code{PyState_AddModule} automatically after importing a module
that uses @ref{520e,,single-phase initialization},
so it is unnecessary (but harmless) to call it from module initialization
code. An explicit call is needed only if the module's own init code
subsequently calls @code{PyState_FindModule}.
The function is mainly intended for implementing alternative import
mechanisms (either by calling it directly, or by referring to its
implementation for details of the required state updates).

If a module was attached previously using the same `def', it is replaced
by the new `module'.

The caller must have an @ref{4ed1,,attached thread state}.

Return @code{-1} with an exception set on error, @code{0} on success.


Added in version 3.3.

@end deffn

@geindex PyState_RemoveModule (C function)
@anchor{c-api/module c PyState_RemoveModule}@anchor{50b6}
@deffn {C の関数} int PyState_RemoveModule (PyModuleDef *def)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.3 より).'
Removes the module object created from `def' from the interpreter state.
Return @code{-1} with an exception set on error, @code{0} on success.

The caller must have an @ref{4ed1,,attached thread state}.


Added in version 3.3.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node イテレータオブジェクト iterator object,デスクリプタオブジェクト descriptor object,サポート関数,その他のオブジェクト<2>
@anchor{c-api/iterator doc}@anchor{5457}@anchor{c-api/iterator id1}@anchor{5458}@anchor{c-api/iterator iterator-objects}@anchor{5459}@anchor{c-api/iterator translation-repo}@anchor{545a}
@subsubsection イテレータオブジェクト (iterator object)


Python では二種類のイテレータオブジェクトを提供しています。一つ目はシーケンスイテレータで、 @ref{588,,__getitem__()} メソッドをサポートする任意のシーケンスを取り扱います。二つ目は呼び出し可能オブジェクトと番兵 (sentinel value) を扱い、シーケンス内の要素ごとに呼び出し可能オブジェクトを呼び出して、センチネル値が返されたときに反復処理を終了します。

@geindex PySeqIter_Type (C var)
@anchor{c-api/iterator c PySeqIter_Type}@anchor{509f}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PySeqIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@ref{509e,,PySeqIter_New()} や、組み込みシーケンス型に対して 1 引数形式の組み込み関数 @ref{9d7,,iter()} を呼び出したときに返される、イテレータオブジェクトの型オブジェクトです。
@end deffn

@geindex PySeqIter_Check (C function)
@anchor{c-api/iterator c PySeqIter_Check}@anchor{545b}
@deffn {C の関数} int PySeqIter_Check (PyObject *op)

`op' の型が @code{PySeqlter_Type} 型の場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PySeqIter_New (C function)
@anchor{c-api/iterator c PySeqIter_New}@anchor{509e}
@deffn {C の関数} @ref{5df,,PyObject} *PySeqIter_New (PyObject *seq)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
一般的なシーケンスオブジェクト `seq' を扱うイテレータを返します。反復処理は、シーケンスが添字指定操作の際に @ref{174e,,IndexError} を返したときに終了します。
@end deffn

@geindex PyCallIter_Type (C var)
@anchor{c-api/iterator c PyCallIter_Type}@anchor{4f91}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCallIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@ref{4f90,,PyCallIter_New()} や、組み込み関数 @ref{9d7,,iter()} の 2 引数形式が返すイテレータオブジェクトの型オブジェクトです。
@end deffn

@geindex PyCallIter_Check (C function)
@anchor{c-api/iterator c PyCallIter_Check}@anchor{545c}
@deffn {C の関数} int PyCallIter_Check (PyObject *op)

`op' の型が @ref{4f91,,PyCallIter_Type} 型の場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyCallIter_New (C function)
@anchor{c-api/iterator c PyCallIter_New}@anchor{4f90}
@deffn {C の関数} @ref{5df,,PyObject} *PyCallIter_New (PyObject *callable, PyObject *sentinel)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
新たなイテレータを返します。最初のパラメタ `callable' は引数なしで呼び出せる Python の呼び出し可能オブジェクトならなんでもかまいません; `callable' は、呼び出されるたびに次の反復処理対象オブジェクトを返さなければなりません。生成されたイテレータは、`callable' が `sentinel' に等しい値を返すと反復処理を終了します。
@end deffn

@menu
* Range Objects:: 
* Builtin Iterator Types:: 
* Other Iterator Objects:: 

@end menu

@node Range Objects,Builtin Iterator Types,,イテレータオブジェクト iterator object
@anchor{c-api/iterator range-objects}@anchor{545d}
@subsubsection Range Objects


@geindex PyRange_Type (C var)
@anchor{c-api/iterator c PyRange_Type}@anchor{509c}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyRange_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for @ref{b3d,,range} objects.
@end deffn

@geindex PyRange_Check (C function)
@anchor{c-api/iterator c PyRange_Check}@anchor{545e}
@deffn {C の関数} int PyRange_Check (PyObject *o)

Return true if the object `o' is an instance of a @ref{b3d,,range} object.
This function always succeeds.
@end deffn

@node Builtin Iterator Types,Other Iterator Objects,Range Objects,イテレータオブジェクト iterator object
@anchor{c-api/iterator builtin-iterator-types}@anchor{545f}
@subsubsection Builtin Iterator Types


These are built-in iteration types that are included in Python's C API, but
provide no additional functions. They are here for completeness.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

C の型

@tab

Python の型

@item

@geindex PyEnum_Type (C var)
@anchor{c-api/iterator c PyEnum_Type}@anchor{4fca}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyEnum_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{169a,,enumerate}

@item

@geindex PyFilter_Type (C var)
@anchor{c-api/iterator c PyFilter_Type}@anchor{5028}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyFilter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{a64,,filter}

@item

@geindex PyMap_Type (C var)
@anchor{c-api/iterator c PyMap_Type}@anchor{5050}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyMap_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{19f,,map}

@item

@geindex PyReversed_Type (C var)
@anchor{c-api/iterator c PyReversed_Type}@anchor{509d}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyReversed_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{a65,,reversed}

@item

@geindex PyZip_Type (C var)
@anchor{c-api/iterator c PyZip_Type}@anchor{5120}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyZip_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@tab

@ref{1a0,,zip}

@end multitable


@node Other Iterator Objects,,Builtin Iterator Types,イテレータオブジェクト iterator object
@anchor{c-api/iterator other-iterator-objects}@anchor{5460}
@subsubsection Other Iterator Objects


@geindex PyByteArrayIter_Type (C var)
@anchor{c-api/iterator c PyByteArrayIter_Type}@anchor{4f78}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyByteArrayIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyBytesIter_Type (C var)
@anchor{c-api/iterator c PyBytesIter_Type}@anchor{4f7e}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyBytesIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyListIter_Type (C var)
@anchor{c-api/iterator c PyListIter_Type}@anchor{503d}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyListIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyListRevIter_Type (C var)
@anchor{c-api/iterator c PyListRevIter_Type}@anchor{503e}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyListRevIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PySetIter_Type (C var)
@anchor{c-api/iterator c PySetIter_Type}@anchor{50ad}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PySetIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyTupleIter_Type (C var)
@anchor{c-api/iterator c PyTupleIter_Type}@anchor{50d5}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyTupleIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyRangeIter_Type (C var)
@anchor{c-api/iterator c PyRangeIter_Type}@anchor{509b}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyRangeIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyLongRangeIter_Type (C var)
@anchor{c-api/iterator c PyLongRangeIter_Type}@anchor{5045}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyLongRangeIter_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyDictIterKey_Type (C var)
@anchor{c-api/iterator c PyDictIterKey_Type}@anchor{4fb4}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictIterKey_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyDictRevIterKey_Type (C var)
@anchor{c-api/iterator c PyDictRevIterKey_Type}@anchor{4fba}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictRevIterKey_Type
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
@end deffn

@geindex PyDictIterValue_Type (C var)
@anchor{c-api/iterator c PyDictIterValue_Type}@anchor{4fb5}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictIterValue_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyDictRevIterValue_Type (C var)
@anchor{c-api/iterator c PyDictRevIterValue_Type}@anchor{4fbb}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictRevIterValue_Type
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
@end deffn

@geindex PyDictIterItem_Type (C var)
@anchor{c-api/iterator c PyDictIterItem_Type}@anchor{4fb3}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictIterItem_Type
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyDictRevIterItem_Type (C var)
@anchor{c-api/iterator c PyDictRevIterItem_Type}@anchor{4fb9}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDictRevIterItem_Type
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
@end deffn

@geindex PyODictIter_Type (C var)
@anchor{c-api/iterator c PyODictIter_Type}@anchor{5461}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyODictIter_Type

Type objects for iterators of various built-in objects.

Do not create instances of these directly; prefer calling
@ref{5092,,PyObject_GetIter()} instead.

Note that there is no guarantee that a given built-in type uses a given iterator
type. For example, iterating over @ref{b3d,,range} will use one of two iterator
types depending on the size of the range. Other types may start using a
similar scheme in the future, without warning.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node デスクリプタオブジェクト descriptor object,スライスオブジェクト slice object,イテレータオブジェクト iterator object,その他のオブジェクト<2>
@anchor{c-api/descriptor doc}@anchor{5462}@anchor{c-api/descriptor descriptor-objects}@anchor{5463}@anchor{c-api/descriptor id1}@anchor{5464}@anchor{c-api/descriptor translation-repo}@anchor{5465}
@subsubsection デスクリプタオブジェクト (descriptor object)


"デスクリプタ (descriptor)" は、あるオブジェクトのいくつかの属性について記述したオブジェクトです。デスクリプタオブジェクトは型オブジェクトの辞書内にあります。

@c XXX document these!

@geindex PyProperty_Type (C var)
@anchor{c-api/descriptor c PyProperty_Type}@anchor{509a}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyProperty_Type
` 次に属します: @ref{775,,Stable ABI}.'
組み込みデスクリプタ型の型オブジェクトです。
@end deffn

@geindex PyDescr_NewGetSet (C function)
@anchor{c-api/descriptor c PyDescr_NewGetSet}@anchor{4fb0}
@deffn {C の関数} @ref{5df,,PyObject} *PyDescr_NewGetSet (PyTypeObject *type, struct PyGetSetDef *getset)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyDescr_NewMember (C function)
@anchor{c-api/descriptor c PyDescr_NewMember}@anchor{4fb1}
@deffn {C の関数} @ref{5df,,PyObject} *PyDescr_NewMember (PyTypeObject *type, struct PyMemberDef *meth)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyMemberDescr_Type (C var)
@anchor{c-api/descriptor c PyMemberDescr_Type}@anchor{5054}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyMemberDescr_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for member descriptor objects created from
@ref{771,,PyMemberDef} structures. These descriptors expose fields of a
C struct as attributes on a type, and correspond
to @ref{29ec,,types.MemberDescriptorType} objects in Python.
@end deffn

@geindex PyGetSetDescr_Type (C var)
@anchor{c-api/descriptor c PyGetSetDescr_Type}@anchor{502f}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyGetSetDescr_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for get/set descriptor objects created from
@ref{db2,,PyGetSetDef} structures. These descriptors implement attributes
whose value is computed by C getter and setter functions, and are used
for many built-in type attributes.
@end deffn

@geindex PyDescr_NewMethod (C function)
@anchor{c-api/descriptor c PyDescr_NewMethod}@anchor{1d75}
@deffn {C の関数} @ref{5df,,PyObject} *PyDescr_NewMethod (PyTypeObject *type, struct PyMethodDef *meth)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyMethodDescr_Type (C var)
@anchor{c-api/descriptor c PyMethodDescr_Type}@anchor{5058}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyMethodDescr_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for method descriptor objects created from
@ref{16f0,,PyMethodDef} structures. These descriptors expose C functions as
methods on a type, and correspond to @ref{29ec,,types.MemberDescriptorType}
objects in Python.
@end deffn

@geindex PyDescr_NewWrapper (C function)
@anchor{c-api/descriptor c PyDescr_NewWrapper}@anchor{5466}
@deffn {C の関数} @ref{5df,,PyObject} *PyDescr_NewWrapper (PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
`戻り値: 新しい参照。'
@end deffn

@geindex PyWrapperDescr_Type (C var)
@anchor{c-api/descriptor c PyWrapperDescr_Type}@anchor{511e}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyWrapperDescr_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for wrapper descriptor objects created by
@ref{5466,,PyDescr_NewWrapper()} and @ref{511f,,PyWrapper_New()}. Wrapper
descriptors are used internally to expose special methods implemented
via wrapper structures, and appear in Python as
@ref{d92,,types.WrapperDescriptorType} objects.
@end deffn

@geindex PyDescr_NewClassMethod (C function)
@anchor{c-api/descriptor c PyDescr_NewClassMethod}@anchor{4faf}
@deffn {C の関数} @ref{5df,,PyObject} *PyDescr_NewClassMethod (PyTypeObject *type, PyMethodDef *method)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyDescr_IsData (C function)
@anchor{c-api/descriptor c PyDescr_IsData}@anchor{1cb3}
@deffn {C の関数} int PyDescr_IsData (PyObject *descr)

Return non-zero if the descriptor object `descr' describes a data attribute, or
@code{0} if it describes a method.  `descr' must be a descriptor object; there is
no error checking.
@end deffn

@geindex PyWrapper_New (C function)
@anchor{c-api/descriptor c PyWrapper_New}@anchor{511f}
@deffn {C の関数} @ref{5df,,PyObject} *PyWrapper_New (PyObject*, PyObject*)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@menu
* Built-in descriptors:: 

@end menu

@node Built-in descriptors,,,デスクリプタオブジェクト descriptor object
@anchor{c-api/descriptor built-in-descriptors}@anchor{5467}
@subsubsection Built-in descriptors


@geindex PySuper_Type (C var)
@anchor{c-api/descriptor c PySuper_Type}@anchor{50bb}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PySuper_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for super objects. This is the same object as
@ref{1a6,,super} in the Python layer.
@end deffn

@geindex PyClassMethod_Type (C var)
@anchor{c-api/descriptor c PyClassMethod_Type}@anchor{5468}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyClassMethod_Type

The type of class method objects. This is the same object as
@ref{48e,,classmethod} in the Python layer.
@end deffn

@geindex PyClassMethodDescr_Type (C var)
@anchor{c-api/descriptor c PyClassMethodDescr_Type}@anchor{4f9d}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyClassMethodDescr_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object for C-level class method descriptor objects.
This is the type of the descriptors created for @ref{48e,,classmethod()} defined in
C extension types, and is the same object as @ref{48e,,classmethod}
in Python.
@end deffn

@geindex PyClassMethod_New (C function)
@anchor{c-api/descriptor c PyClassMethod_New}@anchor{5469}
@deffn {C の関数} @ref{5df,,PyObject} *PyClassMethod_New (PyObject *callable)

Create a new @ref{48e,,classmethod} object wrapping `callable'.
`callable' must be a callable object and must not be @code{NULL}.

On success, this function returns a @ref{5e2,,strong reference} to a new class
method descriptor. On failure, this function returns @code{NULL} with an
exception set.
@end deffn

@geindex PyStaticMethod_Type (C var)
@anchor{c-api/descriptor c PyStaticMethod_Type}@anchor{546a}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyStaticMethod_Type

The type of static method objects. This is the same object as
@ref{453,,staticmethod} in the Python layer.
@end deffn

@geindex PyStaticMethod_New (C function)
@anchor{c-api/descriptor c PyStaticMethod_New}@anchor{546b}
@deffn {C の関数} @ref{5df,,PyObject} *PyStaticMethod_New (PyObject *callable)

Create a new @ref{453,,staticmethod} object wrapping `callable'.
`callable' must be a callable object and must not be @code{NULL}.

On success, this function returns a @ref{5e2,,strong reference} to a new static
method descriptor. On failure, this function returns @code{NULL} with an
exception set.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node スライスオブジェクト slice object,memoryview オブジェクト,デスクリプタオブジェクト descriptor object,その他のオブジェクト<2>
@anchor{c-api/slice doc}@anchor{546c}@anchor{c-api/slice id1}@anchor{546d}@anchor{c-api/slice slice-objects}@anchor{546e}@anchor{c-api/slice translation-repo}@anchor{546f}
@subsubsection スライスオブジェクト (slice object)


@geindex PySlice_Type (C var)
@anchor{c-api/slice c PySlice_Type}@anchor{50b3}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PySlice_Type
` 次に属します: @ref{775,,Stable ABI}.'
スライスオブジェクトの型オブジェクトです。これは、Pythonレイヤにおける @ref{694,,slice} と同じオブジェクトです。
@end deffn

@geindex PySlice_Check (C function)
@anchor{c-api/slice c PySlice_Check}@anchor{5470}
@deffn {C の関数} int PySlice_Check (PyObject *ob)

`ob' がスライスオブジェクトの場合に真を返します; `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PySlice_New (C function)
@anchor{c-api/slice c PySlice_New}@anchor{50b2}
@deffn {C の関数} @ref{5df,,PyObject} *PySlice_New (PyObject *start, PyObject *stop, PyObject *step)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a new slice object with the given values.  The `start', `stop', and
`step' parameters are used as the values of the slice object attributes of
the same names.  Any of the values may be @code{NULL}, in which case the
@code{None} will be used for the corresponding attribute.

Return @code{NULL} with an exception set if
the new object could not be allocated.
@end deffn

@geindex PySlice_GetIndices (C function)
@anchor{c-api/slice c PySlice_GetIndices}@anchor{50b1}
@deffn {C の関数} int PySlice_GetIndices (PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
` 次に属します: @ref{775,,Stable ABI}.'
スライスオブジェクト `slice' における `start', `stop', および `step' のインデクス値を取得します。このときシーケンスの長さを `length' と仮定します。`length' よりも大きなインデクスになるとエラーとして扱います。

Returns @code{0} on success and @code{-1} on error with no exception set (unless one of
the indices was not @code{None} and failed to be converted to an integer,
in which case @code{-1} is returned with an exception set).

おそらく、あなたはこの関数を使いたくないでしょう。


バージョン 3.2 で変更: 以前は、`slice' 引数の型は @code{PySliceObject*} でした。

@end deffn

@geindex PySlice_GetIndicesEx (C function)
@anchor{c-api/slice c PySlice_GetIndicesEx}@anchor{431}
@deffn {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)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{50b1,,PySlice_GetIndices()} の便利な代替です。  `slice' における、`start',  `stop' および `step' のインデクス値を取得をします。シーケンスの長さを `length' 、スライスの長さを `slicelength' に格納します。境界外のインデクスは通常のスライスと一貫した方法でクリップされます。

Return @code{0} on success and @code{-1} on error with an exception set.

@cartouche
@quotation 注釈 
This function is considered not safe for resizable sequences.
Its invocation should be replaced by a combination of
@ref{432,,PySlice_Unpack()} and @ref{433,,PySlice_AdjustIndices()} where

@example
if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) < 0) @{
    // return error
@}
@end example

is replaced by

@example
if (PySlice_Unpack(slice, &start, &stop, &step) < 0) @{
    // return error
@}
slicelength = PySlice_AdjustIndices(length, &start, &stop, step);
@end example
@end quotation
@end cartouche


バージョン 3.2 で変更: 以前は、`slice' 引数の型は @code{PySliceObject*} でした。



バージョン 3.6.1 で変更: If @code{Py_LIMITED_API} is not set or set to the value between @code{0x03050400}
and @code{0x03060000} (not including) or @code{0x03060100} or higher
@code{PySlice_GetIndicesEx()} is implemented as a macro using
@code{PySlice_Unpack()} and @code{PySlice_AdjustIndices()}.
Arguments `start', `stop' and `step' are evaluated more than once.



バージョン 3.6.1 で非推奨: If @code{Py_LIMITED_API} is set to the value less than @code{0x03050400} or
between @code{0x03060000} and @code{0x03060100} (not including)
@code{PySlice_GetIndicesEx()} is a deprecated function.

@end deffn

@geindex PySlice_Unpack (C function)
@anchor{c-api/slice c PySlice_Unpack}@anchor{432}
@deffn {C の関数} int PySlice_Unpack (PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Extract the start, stop and step data members from a slice object as
C integers.  Silently reduce values larger than @code{PY_SSIZE_T_MAX} to
@code{PY_SSIZE_T_MAX}, silently boost the start and stop values less than
@code{PY_SSIZE_T_MIN} to @code{PY_SSIZE_T_MIN}, and silently boost the step
values less than @code{-PY_SSIZE_T_MAX} to @code{-PY_SSIZE_T_MAX}.

Return @code{-1} with an exception set on error, @code{0} on success.


Added in version 3.6.1.

@end deffn

@geindex PySlice_AdjustIndices (C function)
@anchor{c-api/slice c PySlice_AdjustIndices}@anchor{433}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PySlice_AdjustIndices (Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Adjust start/end slice indices assuming a sequence of the specified length.
Out of bounds indices are clipped in a manner consistent with the handling
of normal slices.

Return the length of the slice.  Always successful.  Doesn't call Python
code.


Added in version 3.6.1.

@end deffn

@menu
* Ellipsis オブジェクト: Ellipsis オブジェクト<2>. 

@end menu

@node Ellipsis オブジェクト<2>,,,スライスオブジェクト slice object
@anchor{c-api/slice ellipsis-object}@anchor{5471}
@subsubsection Ellipsis オブジェクト


@geindex PyEllipsis_Type (C var)
@anchor{c-api/slice c PyEllipsis_Type}@anchor{4fc9}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyEllipsis_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type of Python @ref{2328,,Ellipsis} object.  Same as @ref{a51,,types.EllipsisType}
in the Python layer.
@end deffn

@geindex Py_Ellipsis (C var)
@anchor{c-api/slice c Py_Ellipsis}@anchor{5472}
@deffn {C 変数} @ref{5df,,PyObject} *Py_Ellipsis

Python の @code{Ellipsis} オブジェクト。このオブジェクトにはメソッドがありません。 @ref{4e9f,,Py_None} と同様、これは @ref{290,,immortal} でシングルトンなオブジェクトです。


バージョン 3.12 で変更: @ref{5472,,Py_Ellipsis} は immortal です。

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@geindex object;memoryview
@anchor{c-api/memoryview memoryview-objects}@anchor{52ba}
@node memoryview オブジェクト,Pickle buffer objects,スライスオブジェクト slice object,その他のオブジェクト<2>
@anchor{c-api/memoryview doc}@anchor{5473}@anchor{c-api/memoryview id1}@anchor{5474}@anchor{c-api/memoryview translation-repo}@anchor{5475}
@subsubsection memoryview オブジェクト


@ref{165,,memoryview} オブジェクトは、他のオブジェクトと同じように扱える Python オブジェクトの形をした C 言語レベルの @ref{260,,バッファのインターフェース} です。

@geindex PyMemoryView_Type (C var)
@anchor{c-api/memoryview c PyMemoryView_Type}@anchor{5057}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyMemoryView_Type
` 次に属します: @ref{775,,Stable ABI}.'
This instance of @ref{c9c,,PyTypeObject} represents the Python memoryview
type. This is the same object as @ref{165,,memoryview} in the Python layer.
@end deffn

@geindex PyMemoryView_FromObject (C function)
@anchor{c-api/memoryview c PyMemoryView_FromObject}@anchor{5055}
@deffn {C の関数} @ref{5df,,PyObject} *PyMemoryView_FromObject (PyObject *obj)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
バッファインターフェースを提供するオブジェクトからmemoryview オブジェクトを生成します。もし `obj' が書き込み可能なバッファのエクスポートをサポートするなら、その memoryview オブジェクトは読み書き可能です。そうでなければ読出しのみになるか、エクスポーターの分別にもとづいて読み書きが可能となります。
@end deffn

@geindex PyBUF_READ (C macro)
@anchor{c-api/memoryview c PyBUF_READ}@anchor{1a0b}
@deffn {C のマクロ} PyBUF_READ
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Flag to request a readonly buffer.
@end deffn

@geindex PyBUF_WRITE (C macro)
@anchor{c-api/memoryview c PyBUF_WRITE}@anchor{1a0c}
@deffn {C のマクロ} PyBUF_WRITE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
Flag to request a writable buffer.
@end deffn

@geindex PyMemoryView_FromMemory (C function)
@anchor{c-api/memoryview c PyMemoryView_FromMemory}@anchor{1388}
@deffn {C の関数} @ref{5df,,PyObject} *PyMemoryView_FromMemory (char *mem, Py_ssize_t size, int flags)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
`mem' を配下のバッファとしてmemoryview オブジェクトを作成します。 `flags' は @ref{1a0b,,PyBUF_READ} か @ref{1a0c,,PyBUF_WRITE} のどちらかになります。


Added in version 3.3.

@end deffn

@geindex PyMemoryView_FromBuffer (C function)
@anchor{c-api/memoryview c PyMemoryView_FromBuffer}@anchor{965}
@deffn {C の関数} @ref{5df,,PyObject} *PyMemoryView_FromBuffer (const Py_buffer *view)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
`view' として与えられたバッファ構造をラップする memoryview オブジェクトを作成します。単なるバイトバッファ向けには、  @ref{1388,,PyMemoryView_FromMemory()} のほうが望ましいです。
@end deffn

@geindex PyMemoryView_GetContiguous (C function)
@anchor{c-api/memoryview c PyMemoryView_GetContiguous}@anchor{5056}
@deffn {C の関数} @ref{5df,,PyObject} *PyMemoryView_GetContiguous (PyObject *obj, int buffertype, char order)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
buffer インターフェースを定義しているオブジェクトから ('C' か 'F'ortran の `order' で) @ref{124e,,連続した} メモリチャンクへの memoryview オブジェクトを作ります。メモリが連続している場合、 memoryview オブジェクトは元のメモリを参照します。それ以外の場合、メモリはコピーされて、 memoryview オブジェクトは新しい bytes オブジェクトを参照します。

`buffertype' can be one of @ref{1a0b,,PyBUF_READ} or @ref{1a0c,,PyBUF_WRITE}.
@end deffn

@geindex PyMemoryView_Check (C function)
@anchor{c-api/memoryview c PyMemoryView_Check}@anchor{5476}
@deffn {C の関数} int PyMemoryView_Check (PyObject *obj)

`obj' が memoryview オブジェクトの場合に真を返します。現在のところ、 @ref{165,,memoryview} のサブクラスの作成は許可されていません。この関数は常に成功します。
@end deffn

@geindex PyMemoryView_GET_BUFFER (C function)
@anchor{c-api/memoryview c PyMemoryView_GET_BUFFER}@anchor{5477}
@deffn {C の関数} @ref{95c,,Py_buffer} *PyMemoryView_GET_BUFFER (PyObject *mview)

書きだされたバッファーの memoryview のプライベート コピーに、ポインターを返します。
`mview' は  memoryview インスタンスでなければなりません;
このマクロは型をチェックしないので自前で型チェックしなければならず、それを怠るとクラッシュする恐れがあります。
@end deffn

@geindex PyMemoryView_GET_BASE (C function)
@anchor{c-api/memoryview c PyMemoryView_GET_BASE}@anchor{5478}
@deffn {C の関数} @ref{5df,,PyObject} *PyMemoryView_GET_BASE (PyObject *mview)

memoryview をエクスポートしているオブジェクトへのポインタを返します。
memoryview が @ref{1388,,PyMemoryView_FromMemory()} か @ref{965,,PyMemoryView_FromBuffer()} のどちらかで作成されていた場合、 @code{NULL} を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@geindex object;PickleBuffer
@anchor{c-api/picklebuffer picklebuffer-objects}@anchor{5479}
@node Pickle buffer objects,弱参照オブジェクト<2>,memoryview オブジェクト,その他のオブジェクト<2>
@anchor{c-api/picklebuffer doc}@anchor{547a}@anchor{c-api/picklebuffer pickle-buffer-objects}@anchor{547b}@anchor{c-api/picklebuffer translation-repo}@anchor{547c}
@subsubsection Pickle buffer objects



Added in version 3.8.


A @ref{177b,,pickle.PickleBuffer} object wraps a @ref{260,,buffer-providing object} for out-of-band data transfer with the @ref{ab,,pickle} module.

@geindex PyPickleBuffer_Type (C var)
@anchor{c-api/picklebuffer c PyPickleBuffer_Type}@anchor{547d}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyPickleBuffer_Type

This instance of @ref{c9c,,PyTypeObject} represents the Python pickle buffer type.
This is the same object as @ref{177b,,pickle.PickleBuffer} in the Python layer.
@end deffn

@geindex PyPickleBuffer_Check (C function)
@anchor{c-api/picklebuffer c PyPickleBuffer_Check}@anchor{547e}
@deffn {C の関数} int PyPickleBuffer_Check (PyObject *op)

Return true if `op' is a pickle buffer instance.
This function always succeeds.
@end deffn

@geindex PyPickleBuffer_FromObject (C function)
@anchor{c-api/picklebuffer c PyPickleBuffer_FromObject}@anchor{547f}
@deffn {C の関数} @ref{5df,,PyObject} *PyPickleBuffer_FromObject (PyObject *obj)

Create a pickle buffer from the object `obj'.

This function will fail if `obj' doesn't support the @ref{260,,buffer protocol}.

On success, return a new pickle buffer instance.
On failure, set an exception and return @code{NULL}.

Analogous to calling @ref{177b,,pickle.PickleBuffer} with `obj' in Python.
@end deffn

@geindex PyPickleBuffer_GetBuffer (C function)
@anchor{c-api/picklebuffer c PyPickleBuffer_GetBuffer}@anchor{5480}
@deffn {C の関数} const @ref{95c,,Py_buffer} *PyPickleBuffer_GetBuffer (PyObject *picklebuf)

Get a pointer to the underlying @ref{95c,,Py_buffer} that the pickle buffer wraps.

The returned pointer is valid as long as `picklebuf' is alive and has not been
released. The caller must not modify or free the returned @ref{95c,,Py_buffer}.
If the pickle buffer has been released, raise @ref{2ec,,ValueError}.

On success, return a pointer to the buffer view.
On failure, set an exception and return @code{NULL}.
@end deffn

@geindex PyPickleBuffer_Release (C function)
@anchor{c-api/picklebuffer c PyPickleBuffer_Release}@anchor{5481}
@deffn {C の関数} int PyPickleBuffer_Release (PyObject *picklebuf)

Release the underlying buffer held by the pickle buffer.

Return @code{0} on success. On failure, set an exception and return @code{-1}.

Analogous to calling @ref{2d1c,,pickle.PickleBuffer.release()} in Python.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 弱参照オブジェクト<2>,カプセル<2>,Pickle buffer objects,その他のオブジェクト<2>
@anchor{c-api/weakref doc}@anchor{5482}@anchor{c-api/weakref translation-repo}@anchor{5483}@anchor{c-api/weakref weak-reference-objects}@anchor{5484}@anchor{c-api/weakref weakrefobjects}@anchor{528f}
@subsubsection 弱参照オブジェクト


Python は `弱参照' を第一級オブジェクト (first-class object) としてサポートします。弱参照を直接実装する二種類の固有のオブジェクト型があります。第一は単純な参照オブジェクトで、第二はオリジナルのオブジェクトに対して可能な限りプロキシとして振舞うオブジェクトです。

@geindex PyWeakref_Check (C function)
@anchor{c-api/weakref c PyWeakref_Check}@anchor{5485}
@deffn {C の関数} int PyWeakref_Check (PyObject *ob)

Return non-zero if `ob' is either a reference or proxy object.  This function
always succeeds.
@end deffn

@geindex PyWeakref_CheckRef (C function)
@anchor{c-api/weakref c PyWeakref_CheckRef}@anchor{5486}
@deffn {C の関数} int PyWeakref_CheckRef (PyObject *ob)

Return non-zero if `ob' is a reference object or a subclass of the reference
type.  This function always succeeds.
@end deffn

@geindex PyWeakref_CheckRefExact (C function)
@anchor{c-api/weakref c PyWeakref_CheckRefExact}@anchor{5487}
@deffn {C の関数} int PyWeakref_CheckRefExact (PyObject *ob)

Return non-zero if `ob' is a reference object, but not a subclass of the
reference type.  This function always succeeds.
@end deffn

@geindex PyWeakref_CheckProxy (C function)
@anchor{c-api/weakref c PyWeakref_CheckProxy}@anchor{5488}
@deffn {C の関数} int PyWeakref_CheckProxy (PyObject *ob)

Return non-zero if `ob' is a proxy object.  This function always succeeds.
@end deffn

@geindex PyWeakref_NewRef (C function)
@anchor{c-api/weakref c PyWeakref_NewRef}@anchor{1be6}
@deffn {C の関数} @ref{5df,,PyObject} *PyWeakref_NewRef (PyObject *ob, PyObject *callback)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a weak reference object for the object `ob'.  This will always return
a new reference, but is not guaranteed to create a new object; an existing
reference object may be returned.  The second parameter, `callback', can be a
callable object that receives notification when `ob' is garbage collected; it
should accept a single parameter, which will be the weak reference object
itself. `callback' may also be @code{None} or @code{NULL}.  If `ob' is not a
weakly referenceable object, or if `callback' is not callable, @code{None}, or
@code{NULL}, this will return @code{NULL} and raise @ref{198,,TypeError}.


@subsubheading 参考


@ref{52e4,,PyType_SUPPORTS_WEAKREFS()} for checking if `ob' is weakly
referenceable.

@end deffn

@geindex PyWeakref_NewProxy (C function)
@anchor{c-api/weakref c PyWeakref_NewProxy}@anchor{511d}
@deffn {C の関数} @ref{5df,,PyObject} *PyWeakref_NewProxy (PyObject *ob, PyObject *callback)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a weak reference proxy object for the object `ob'.  This will always
return a new reference, but is not guaranteed to create a new object; an
existing proxy object may be returned.  The second parameter, `callback', can
be a callable object that receives notification when `ob' is garbage
collected; it should accept a single parameter, which will be the weak
reference object itself. `callback' may also be @code{None} or @code{NULL}.  If `ob'
is not a weakly referenceable object, or if `callback' is not callable,
@code{None}, or @code{NULL}, this will return @code{NULL} and raise @ref{198,,TypeError}.


@subsubheading 参考


@ref{52e4,,PyType_SUPPORTS_WEAKREFS()} for checking if `ob' is weakly
referenceable.

@end deffn

@geindex PyWeakref_GetRef (C function)
@anchor{c-api/weakref c PyWeakref_GetRef}@anchor{3df}
@deffn {C の関数} int PyWeakref_GetRef (PyObject *ref, PyObject **pobj)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Get a @ref{5e2,,strong reference} to the referenced object from a weak
reference, `ref', into `*pobj'.


@itemize *

@item 
On success, set `*pobj' to a new @ref{5e2,,strong reference} to the
referenced object and return 1.

@item 
If the reference is dead, set `*pobj' to @code{NULL} and return 0.

@item 
On error, raise an exception and return -1.
@end itemize


Added in version 3.13.

@end deffn

@geindex PyWeakref_GetObject (C function)
@anchor{c-api/weakref c PyWeakref_GetObject}@anchor{3dd}
@deffn {C の関数} @ref{5df,,PyObject} *PyWeakref_GetObject (PyObject *ref)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
Return a @ref{3d7,,borrowed reference} to the referenced object from a weak
reference, `ref'.  If the referent is no longer live, returns @code{Py_None}.

@cartouche
@quotation 注釈 
This function returns a @ref{3d7,,borrowed reference} to the referenced object.
This means that you should always call @ref{78f,,Py_INCREF()} on the object
except when it cannot be destroyed before the last usage of the borrowed
reference.
@end quotation
@end cartouche


Deprecated since version 3.13, will be removed in version 3.15: Use @ref{3df,,PyWeakref_GetRef()} instead.

@end deffn

@geindex PyWeakref_GET_OBJECT (C function)
@anchor{c-api/weakref c PyWeakref_GET_OBJECT}@anchor{3de}
@deffn {C の関数} @ref{5df,,PyObject} *PyWeakref_GET_OBJECT (PyObject *ref)
`戻り値: 借用参照。'
Similar to @ref{3dd,,PyWeakref_GetObject()}, but does no error checking.


Deprecated since version 3.13, will be removed in version 3.15: Use @ref{3df,,PyWeakref_GetRef()} instead.

@end deffn

@geindex PyWeakref_IsDead (C function)
@anchor{c-api/weakref c PyWeakref_IsDead}@anchor{18df}
@deffn {C の関数} int PyWeakref_IsDead (PyObject *ref)

Test if the weak reference `ref' is dead. Returns 1 if the reference is
dead, 0 if it is alive, and -1 with an error set if `ref' is not a weak
reference object.


Added in version 3.14.

@end deffn

@geindex PyObject_ClearWeakRefs (C function)
@anchor{c-api/weakref c PyObject_ClearWeakRefs}@anchor{796}
@deffn {C の関数} void PyObject_ClearWeakRefs (PyObject *object)
` 次に属します: @ref{775,,Stable ABI}.'
This function is called by the @ref{4ebc,,tp_dealloc} handler
to clear weak references.

This iterates through the weak references for `object' and calls callbacks
for those references which have one. It returns when all callbacks have
been attempted.
@end deffn

@geindex PyUnstable_Object_ClearWeakRefsNoCallbacks (C function)
@anchor{c-api/weakref c PyUnstable_Object_ClearWeakRefsNoCallbacks}@anchor{1995}
@deffn {C の関数} void PyUnstable_Object_ClearWeakRefsNoCallbacks (PyObject *object)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Clears the weakrefs for `object' without calling the callbacks.

This function is called by the @ref{4ebc,,tp_dealloc} handler
for types with finalizers (i.e., @ref{11ff,,__del__()}).  The handler for
those objects first calls @ref{796,,PyObject_ClearWeakRefs()} to clear weakrefs
and call their callbacks, then the finalizer, and finally this function to
clear any weakrefs that may have been created by the finalizer.

In most circumstances, it's more appropriate to use
@ref{796,,PyObject_ClearWeakRefs()} to clear weakrefs instead of this function.


Added in version 3.13.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node カプセル<2>,フレーム frame オブジェクト<2>,弱参照オブジェクト<2>,その他のオブジェクト<2>
@anchor{c-api/capsule doc}@anchor{5489}@anchor{c-api/capsule capsules}@anchor{29f3}@anchor{c-api/capsule id1}@anchor{548a}@anchor{c-api/capsule translation-repo}@anchor{548b}
@subsubsection カプセル


@geindex オブジェクト;Capsule

@cite{using-capsules} 以下のオブジェクトを使う方法については @ref{1575,,拡張モジュールに C API を提供する} を参照してください。


Added in version 3.1.


@geindex PyCapsule (C type)
@anchor{c-api/capsule c PyCapsule}@anchor{148a}
@deffn {C のデータ型} type PyCapsule

This subtype of @ref{5df,,PyObject} represents an opaque value, useful for C
extension modules which need to pass an opaque value (as a void*
pointer) through Python code to other C code.  It is often used to make a C
function pointer defined in one module available to other modules, so the
regular import mechanism can be used to access C APIs defined in dynamically
loaded modules.
@end deffn

@geindex PyCapsule_Type (C var)
@anchor{c-api/capsule c PyCapsule_Type}@anchor{4f9c}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCapsule_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object corresponding to capsule objects. This is the same object
as @ref{29f2,,types.CapsuleType} in the Python layer.
@end deffn

@geindex PyCapsule_Destructor (C type)
@anchor{c-api/capsule c PyCapsule_Destructor}@anchor{4f93}
@deffn {C のデータ型} type PyCapsule_Destructor
` 次に属します: @ref{775,,Stable ABI}.'
カプセルに対するデストラクタコールバック型. 次のように定義されます:

@example
typedef void (*PyCapsule_Destructor)(PyObject *);
@end example

PyCapsule_Destructor コールバックの動作については @ref{4ec3,,PyCapsule_New()} を参照してください。
@end deffn

@geindex PyCapsule_CheckExact (C function)
@anchor{c-api/capsule c PyCapsule_CheckExact}@anchor{548c}
@deffn {C の関数} int PyCapsule_CheckExact (PyObject *p)

引数が @ref{148a,,PyCapsule} の場合に真を返します。この関数は常に成功します。
@end deffn

@geindex PyCapsule_New (C function)
@anchor{c-api/capsule c PyCapsule_New}@anchor{4ec3}
@deffn {C の関数} @ref{5df,,PyObject} *PyCapsule_New (void *pointer, const char *name, PyCapsule_Destructor destructor)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
`pointer' を格納する @ref{148a,,PyCapsule} を作成します。 `pointer' 引数は @code{NULL} であってはなりません。

失敗した場合、例外を設定して @code{NULL} を返します。

`name' 文字列は @code{NULL} か、有効なC文字列へのポインタです。@code{NULL} で無い場合、この文字列は少なくともカプセルより長く生存する必要があります。(`destructor' の中で解放することは許可されています)

`destructor' が @code{NULL} で無い場合、カプセルが削除されるときにそのカプセルを引数として呼び出されます。

このカプセルがモジュールの属性として保存される場合、 `name' は @code{modulename.attributename} と指定されるべきです。こうすると、他のモジュールがそのカプセルを @ref{1c10,,PyCapsule_Import()} でインポートすることができます。
@end deffn

@geindex PyCapsule_GetPointer (C function)
@anchor{c-api/capsule c PyCapsule_GetPointer}@anchor{4f97}
@deffn {C の関数} void *PyCapsule_GetPointer (PyObject *capsule, const char *name)
` 次に属します: @ref{775,,Stable ABI}.'
カプセルに保存されている `pointer' を取り出します。失敗した場合は例外を設定して @code{NULL} を返します。

The `name' parameter must compare exactly to the name stored in the capsule.
If the name stored in the capsule is @code{NULL}, the `name' passed in must also
be @code{NULL}.  Python uses the C function @code{strcmp()} to compare capsule
names.
@end deffn

@geindex PyCapsule_GetDestructor (C function)
@anchor{c-api/capsule c PyCapsule_GetDestructor}@anchor{4f95}
@deffn {C の関数} @ref{4f93,,PyCapsule_Destructor} PyCapsule_GetDestructor (PyObject *capsule)
` 次に属します: @ref{775,,Stable ABI}.'
カプセルに保存されている現在のデストラクタを返します。失敗した場合、例外を設定して @code{NULL} を返します。

カプセルは @code{NULL} をデストラクタとして持つことができます。従って、戻り値の @code{NULL} がエラーを指してない可能性があります。 @ref{1574,,PyCapsule_IsValid()} か @ref{1caf,,PyErr_Occurred()} を利用して確認してください。
@end deffn

@geindex PyCapsule_GetContext (C function)
@anchor{c-api/capsule c PyCapsule_GetContext}@anchor{4f94}
@deffn {C の関数} void *PyCapsule_GetContext (PyObject *capsule)
` 次に属します: @ref{775,,Stable ABI}.'
カプセルに保存されている現在のコンテキスト(context)を返します。失敗した場合、例外を設定して @code{NULL} を返します。

カプセルは @code{NULL} をコンテキストとして持つことができます。従って、戻り値の @code{NULL} がエラーを指してない可能性があります。 @ref{1574,,PyCapsule_IsValid()} か @ref{1caf,,PyErr_Occurred()} を利用して確認してください。
@end deffn

@geindex PyCapsule_GetName (C function)
@anchor{c-api/capsule c PyCapsule_GetName}@anchor{4f96}
@deffn {C の関数} const char *PyCapsule_GetName (PyObject *capsule)
` 次に属します: @ref{775,,Stable ABI}.'
カプセルに保存されている現在の name を返します。失敗した場合、例外を設定して @code{NULL} を返します。

カプセルは @code{NULL} を name として持つことができます。従って、戻り値の @code{NULL} がエラーを指してない可能性があります。 @ref{1574,,PyCapsule_IsValid()} か @ref{1caf,,PyErr_Occurred()} を利用して確認してください。
@end deffn

@geindex PyCapsule_Import (C function)
@anchor{c-api/capsule c PyCapsule_Import}@anchor{1c10}
@deffn {C の関数} void *PyCapsule_Import (const char *name, int no_block)
` 次に属します: @ref{775,,Stable ABI}.'
Import a pointer to a C object from a capsule attribute in a module.  The
`name' parameter should specify the full name to the attribute, as in
@code{module.attribute}.  The `name' stored in the capsule must match this
string exactly.

This function splits `name' on the @code{.} character, and imports the first
element. It then processes further elements using attribute lookups.

成功した場合、カプセルの内部 `ポインタ' を返します。失敗した場合、例外を設定して @code{NULL} を返します。

@cartouche
@quotation 注釈 
If `name' points to an attribute of some submodule or subpackage, this
submodule or subpackage must be previously imported using other means
(for example, by using @ref{3dc,,PyImport_ImportModule()}) for the
attribute lookups to succeed.
@end quotation
@end cartouche


バージョン 3.3 で変更: `no_block' has no effect anymore.

@end deffn

@geindex PyCapsule_IsValid (C function)
@anchor{c-api/capsule c PyCapsule_IsValid}@anchor{1574}
@deffn {C の関数} int PyCapsule_IsValid (PyObject *capsule, const char *name)
` 次に属します: @ref{775,,Stable ABI}.'
`capsule' が有効なカプセルであるかどうかをチェックします。有効な `capsule' は、非 @code{NULL} で、 @ref{548c,,PyCapsule_CheckExact()} をパスし、非 @code{NULL} なポインタを格納していて、内部の name が引数 `name' とマッチします。 (name の比較方法については @ref{4f97,,PyCapsule_GetPointer()} を参照)

In other words, if @ref{1574,,PyCapsule_IsValid()} returns a true value, calls to
any of the accessors (any function starting with @code{PyCapsule_Get}) are
guaranteed to succeed.

オブジェクトが有効で name がマッチした場合に非 @code{0} を、それ以外の場合に @code{0} を返します。この関数は絶対に失敗しません。
@end deffn

@geindex PyCapsule_SetContext (C function)
@anchor{c-api/capsule c PyCapsule_SetContext}@anchor{4f98}
@deffn {C の関数} int PyCapsule_SetContext (PyObject *capsule, void *context)
` 次に属します: @ref{775,,Stable ABI}.'
`capsule' 内部のコンテキストポインタを `context' に設定します。

成功したら @code{0} を、失敗したら例外を設定して非 @code{0} を返します。
@end deffn

@geindex PyCapsule_SetDestructor (C function)
@anchor{c-api/capsule c PyCapsule_SetDestructor}@anchor{4f99}
@deffn {C の関数} int PyCapsule_SetDestructor (PyObject *capsule, PyCapsule_Destructor destructor)
` 次に属します: @ref{775,,Stable ABI}.'
`capsule' 内部のデストラクタを `destructor' に設定します。

成功したら @code{0} を、失敗したら例外を設定して非 @code{0} を返します。
@end deffn

@geindex PyCapsule_SetName (C function)
@anchor{c-api/capsule c PyCapsule_SetName}@anchor{4f9a}
@deffn {C の関数} int PyCapsule_SetName (PyObject *capsule, const char *name)
` 次に属します: @ref{775,,Stable ABI}.'
`capsule' 内部の name を `name' に設定します。`name' が非 @code{NULL} のとき、それは `capsule' よりも長い寿命を持つ必要があります。もしすでに `capsule' に非 @code{NULL} の `name' が保存されていた場合、それに対する解放は行われません。

成功したら @code{0} を、失敗したら例外を設定して非 @code{0} を返します。
@end deffn

@geindex PyCapsule_SetPointer (C function)
@anchor{c-api/capsule c PyCapsule_SetPointer}@anchor{4f9b}
@deffn {C の関数} int PyCapsule_SetPointer (PyObject *capsule, void *pointer)
` 次に属します: @ref{775,,Stable ABI}.'
`capsule' 内部のポインタを `pointer' に設定します。`pointer' は @code{NULL} であってはなりません。

成功したら @code{0} を、失敗したら例外を設定して非 @code{0} を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node フレーム frame オブジェクト<2>,ジェネレータオブジェクト,カプセル<2>,その他のオブジェクト<2>
@anchor{c-api/frame doc}@anchor{548d}@anchor{c-api/frame frame-objects}@anchor{548e}@anchor{c-api/frame translation-repo}@anchor{548f}
@subsubsection フレーム (frame) オブジェクト


@geindex PyFrameObject (C type)
@anchor{c-api/frame c PyFrameObject}@anchor{98c}
@deffn {C のデータ型} type PyFrameObject
` 次に属します: @ref{775,,Limited API} (不透明な構造体として).'
フレームオブジェクトを記述する際に用いられる、オブジェクトを表す C 構造体です。

There are no public members in this structure.


バージョン 3.11 で変更: The members of this structure were removed from the public C API.
Refer to the @ref{98b,,What's New entry}
for details.

@end deffn

The @ref{1b39,,PyEval_GetFrame()} and @ref{991,,PyThreadState_GetFrame()} functions
can be used to get a frame object.

See also @ref{5262,,Reflection}.

@geindex PyFrame_Type (C var)
@anchor{c-api/frame c PyFrame_Type}@anchor{98a}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyFrame_Type

The type of frame objects.
It is the same object as @ref{1bee,,types.FrameType} in the Python layer.


バージョン 3.11 で変更: Previously, this type was only available after including
@code{<frameobject.h>}.

@end deffn

@geindex PyFrame_New (C function)
@anchor{c-api/frame c PyFrame_New}@anchor{1aef}
@deffn {C の関数} @ref{98c,,PyFrameObject} *PyFrame_New (PyThreadState *tstate, PyCodeObject *code, PyObject *globals, PyObject *locals)

Create a new frame object. This function returns a @ref{5e2,,strong reference}
to the new frame object on success, and returns @code{NULL} with an exception
set on failure.
@end deffn

@geindex PyFrame_Check (C function)
@anchor{c-api/frame c PyFrame_Check}@anchor{988}
@deffn {C の関数} int PyFrame_Check (PyObject *obj)

Return non-zero if `obj' is a frame object.


バージョン 3.11 で変更: Previously, this function was only available after including
@code{<frameobject.h>}.

@end deffn

@geindex PyFrame_GetBack (C function)
@anchor{c-api/frame c PyFrame_GetBack}@anchor{989}
@deffn {C の関数} @ref{98c,,PyFrameObject} *PyFrame_GetBack (PyFrameObject *frame)
`戻り値: 新しい参照。'
Get the `frame' next outer frame.

Return a @ref{5e2,,strong reference}, or @code{NULL} if `frame' has no outer
frame.


Added in version 3.9.

@end deffn

@geindex PyFrame_GetBuiltins (C function)
@anchor{c-api/frame c PyFrame_GetBuiltins}@anchor{96f}
@deffn {C の関数} @ref{5df,,PyObject} *PyFrame_GetBuiltins (PyFrameObject *frame)
`戻り値: 新しい参照。'
Get the `frame''s @ref{239b,,f_builtins} attribute.

Return a @ref{5e2,,strong reference}. The result cannot be @code{NULL}.


Added in version 3.11.

@end deffn

@geindex PyFrame_GetCode (C function)
@anchor{c-api/frame c PyFrame_GetCode}@anchor{98d}
@deffn {C の関数} @ref{97b,,PyCodeObject} *PyFrame_GetCode (PyFrameObject *frame)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Get the `frame' code.

Return a @ref{5e2,,strong reference}.

The result (frame code) cannot be @code{NULL}.


Added in version 3.9.

@end deffn

@geindex PyFrame_GetGenerator (C function)
@anchor{c-api/frame c PyFrame_GetGenerator}@anchor{970}
@deffn {C の関数} @ref{5df,,PyObject} *PyFrame_GetGenerator (PyFrameObject *frame)
`戻り値: 新しい参照。'
Get the generator, coroutine, or async generator that owns this frame,
or @code{NULL} if this frame is not owned by a generator.
Does not raise an exception, even if the return value is @code{NULL}.

Return a @ref{5e2,,strong reference}, or @code{NULL}.


Added in version 3.11.

@end deffn

@geindex PyFrame_GetGlobals (C function)
@anchor{c-api/frame c PyFrame_GetGlobals}@anchor{971}
@deffn {C の関数} @ref{5df,,PyObject} *PyFrame_GetGlobals (PyFrameObject *frame)
`戻り値: 新しい参照。'
Get the `frame''s @ref{239a,,f_globals} attribute.

Return a @ref{5e2,,strong reference}. The result cannot be @code{NULL}.


Added in version 3.11.

@end deffn

@geindex PyFrame_GetLasti (C function)
@anchor{c-api/frame c PyFrame_GetLasti}@anchor{972}
@deffn {C の関数} int PyFrame_GetLasti (PyFrameObject *frame)

Get the `frame''s @ref{a88,,f_lasti} attribute.

Returns -1 if @code{frame.f_lasti} is @code{None}.


Added in version 3.11.

@end deffn

@geindex PyFrame_GetVar (C function)
@anchor{c-api/frame c PyFrame_GetVar}@anchor{789}
@deffn {C の関数} @ref{5df,,PyObject} *PyFrame_GetVar (PyFrameObject *frame, PyObject *name)
`戻り値: 新しい参照。'
Get the variable `name' of `frame'.


@itemize *

@item 
Return a @ref{5e2,,strong reference} to the variable value on success.

@item 
Raise @ref{452,,NameError} and return @code{NULL} if the variable does not exist.

@item 
Raise an exception and return @code{NULL} on error.
@end itemize

`name' type must be a @ref{169,,str}.


Added in version 3.12.

@end deffn

@geindex PyFrame_GetVarString (C function)
@anchor{c-api/frame c PyFrame_GetVarString}@anchor{78a}
@deffn {C の関数} @ref{5df,,PyObject} *PyFrame_GetVarString (PyFrameObject *frame, const char *name)
`戻り値: 新しい参照。'
Similar to @ref{789,,PyFrame_GetVar()}, but the variable name is a C string
encoded in UTF-8.


Added in version 3.12.

@end deffn

@geindex PyFrame_GetLocals (C function)
@anchor{c-api/frame c PyFrame_GetLocals}@anchor{661}
@deffn {C の関数} @ref{5df,,PyObject} *PyFrame_GetLocals (PyFrameObject *frame)
`戻り値: 新しい参照。'
Get the `frame''s @ref{4a5,,f_locals} attribute.
If the frame refers to an @ref{4a1,,optimized scope}, this returns a
write-through proxy object that allows modifying the locals.
In all other cases (classes, modules, @ref{4a2,,exec()}, @ref{4a3,,eval()}) it returns
the mapping representing the frame locals directly (as described for
@ref{46f,,locals()}).

Return a @ref{5e2,,strong reference}.


Added in version 3.11.



バージョン 3.13 で変更: As part of 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}, return an instance of @ref{5490,,PyFrameLocalsProxy_Type}.

@end deffn

@geindex PyFrame_GetLineNumber (C function)
@anchor{c-api/frame c PyFrame_GetLineNumber}@anchor{98e}
@deffn {C の関数} int PyFrame_GetLineNumber (PyFrameObject *frame)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
`frame' が現在実行している行番号を返します。
@end deffn

@menu
* Frame Locals Proxies:: 
* Legacy Local Variable APIs:: 
* Internal Frames:: 

@end menu

@node Frame Locals Proxies,Legacy Local Variable APIs,,フレーム frame オブジェクト<2>
@anchor{c-api/frame frame-locals-proxies}@anchor{5491}
@subsubsection Frame Locals Proxies



Added in version 3.13.


The @ref{4a5,,f_locals} attribute on a @ref{8ef,,frame object}
is an instance of a "frame-locals proxy". The proxy object exposes a
write-through view of the underlying locals dictionary for the frame. This
ensures that the variables exposed by @code{f_locals} are always up to date with
the live local variables in the frame itself.

See 
@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/} for more information.

@geindex PyFrameLocalsProxy_Type (C var)
@anchor{c-api/frame c PyFrameLocalsProxy_Type}@anchor{5490}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyFrameLocalsProxy_Type

The type of frame @ref{46f,,locals()} proxy objects.
@end deffn

@geindex PyFrameLocalsProxy_Check (C function)
@anchor{c-api/frame c PyFrameLocalsProxy_Check}@anchor{5492}
@deffn {C の関数} int PyFrameLocalsProxy_Check (PyObject *obj)

Return non-zero if `obj' is a frame @ref{46f,,locals()} proxy.
@end deffn

@node Legacy Local Variable APIs,Internal Frames,Frame Locals Proxies,フレーム frame オブジェクト<2>
@anchor{c-api/frame legacy-local-variable-apis}@anchor{5493}
@subsubsection Legacy Local Variable APIs


These APIs are @ref{23d,,soft deprecated}. As of Python 3.13, they do nothing.
They exist solely for backwards compatibility.

@geindex PyFrame_LocalsToFast (C function)
@anchor{c-api/frame c PyFrame_LocalsToFast}@anchor{5494}
@deffn {C の関数} void PyFrame_LocalsToFast (PyFrameObject *f, int clear)

This function is @ref{23d,,soft deprecated} and does nothing.

Prior to Python 3.13, this function would copy the @ref{4a5,,f_locals}
attribute of `f' to the internal "fast" array of local variables, allowing
changes in frame objects to be visible to the interpreter. If `clear' was
true, this function would process variables that were unset in the locals
dictionary.


バージョン 3.13 で変更: This function now does nothing.

@end deffn

@geindex PyFrame_FastToLocals (C function)
@anchor{c-api/frame c PyFrame_FastToLocals}@anchor{5495}
@deffn {C の関数} void PyFrame_FastToLocals (PyFrameObject *f)

This function is @ref{23d,,soft deprecated} and does nothing.

Prior to Python 3.13, this function would copy the internal "fast" array
of local variables (which is used by the interpreter) to the
@ref{4a5,,f_locals} attribute of `f', allowing changes in local
variables to be visible to frame objects.


バージョン 3.13 で変更: This function now does nothing.

@end deffn

@geindex PyFrame_FastToLocalsWithError (C function)
@anchor{c-api/frame c PyFrame_FastToLocalsWithError}@anchor{5496}
@deffn {C の関数} int PyFrame_FastToLocalsWithError (PyFrameObject *f)

This function is @ref{23d,,soft deprecated} and does nothing.

Prior to Python 3.13, this function was similar to
@ref{5495,,PyFrame_FastToLocals()}, but would return @code{0} on success, and
@code{-1} with an exception set on failure.


バージョン 3.13 で変更: This function now does nothing.

@end deffn


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 667
PEP 667@footnote{https://peps.python.org/pep-0667/}


@node Internal Frames,,Legacy Local Variable APIs,フレーム frame オブジェクト<2>
@anchor{c-api/frame internal-frames}@anchor{5497}
@subsubsection Internal Frames


Unless using 
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/}, you will not need this.

@geindex _PyInterpreterFrame (C struct)
@anchor{c-api/frame c _PyInterpreterFrame}@anchor{196e}
@deffn {C Struct} struct _PyInterpreterFrame

The interpreter's internal frame representation.


Added in version 3.11.

@end deffn

@geindex PyUnstable_InterpreterFrame_GetCode (C function)
@anchor{c-api/frame c PyUnstable_InterpreterFrame_GetCode}@anchor{5498}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnstable_InterpreterFrame_GetCode (struct _PyInterpreterFrame *frame);

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

@quotation

Return a @ref{5e2,,strong reference} to the code object for the frame.
@end quotation


Added in version 3.12.

@end deffn

@geindex PyUnstable_InterpreterFrame_GetLasti (C function)
@anchor{c-api/frame c PyUnstable_InterpreterFrame_GetLasti}@anchor{5499}
@deffn {C の関数} int PyUnstable_InterpreterFrame_GetLasti (struct _PyInterpreterFrame *frame);

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Return the byte offset into the last executed instruction.


Added in version 3.12.

@end deffn

@geindex PyUnstable_InterpreterFrame_GetLine (C function)
@anchor{c-api/frame c PyUnstable_InterpreterFrame_GetLine}@anchor{549a}
@deffn {C の関数} int PyUnstable_InterpreterFrame_GetLine (struct _PyInterpreterFrame *frame);

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Return the currently executing line number, or -1 if there is no line number.


Added in version 3.12.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ジェネレータオブジェクト,コルーチンオブジェクト<2>,フレーム frame オブジェクト<2>,その他のオブジェクト<2>
@anchor{c-api/gen doc}@anchor{549b}@anchor{c-api/gen gen-objects}@anchor{549c}@anchor{c-api/gen generator-objects}@anchor{549d}@anchor{c-api/gen translation-repo}@anchor{549e}
@subsubsection ジェネレータオブジェクト


ジェネレータオブジェクトは、 Python がジェネレータイテレータを実装するのに使っているオブジェクトです。ジェネレータオブジェクトは通常、 @ref{549f,,PyGen_New()} や  @ref{54a0,,PyGen_NewWithQualName()} の明示的な呼び出しではなく、値を yield する関数のイテレーションにより生成されます。

@geindex PyGenObject (C type)
@anchor{c-api/gen c PyGenObject}@anchor{54a1}
@deffn {C のデータ型} type PyGenObject

ジェネレータオブジェクトに使われている C 構造体です。
@end deffn

@geindex PyGen_Type (C var)
@anchor{c-api/gen c PyGen_Type}@anchor{54a2}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyGen_Type

ジェネレータオブジェクトに対応する型オブジェクトです。
@end deffn

@geindex PyGen_Check (C function)
@anchor{c-api/gen c PyGen_Check}@anchor{54a3}
@deffn {C の関数} int PyGen_Check (PyObject *ob)

`ob' がジェネレータオブジェクトの場合に真を返ます、 `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyGen_CheckExact (C function)
@anchor{c-api/gen c PyGen_CheckExact}@anchor{54a4}
@deffn {C の関数} int PyGen_CheckExact (PyObject *ob)

`ob' が @ref{54a2,,PyGen_Type} の場合に真を返します。
`o' は @code{NULL} であってはなりません。
この関数は常に成功します。
@end deffn

@geindex PyGen_New (C function)
@anchor{c-api/gen c PyGen_New}@anchor{549f}
@deffn {C の関数} @ref{5df,,PyObject} *PyGen_New (PyFrameObject *frame)
`戻り値: 新しい参照。'
`frame' オブジェクトに基づいて新たなジェネレータオブジェクトを生成して返します。
この関数は `frame' への参照を盗みます。
引数が @code{NULL} であってはなりません。
@end deffn

@geindex PyGen_NewWithQualName (C function)
@anchor{c-api/gen c PyGen_NewWithQualName}@anchor{54a0}
@deffn {C の関数} @ref{5df,,PyObject} *PyGen_NewWithQualName (PyFrameObject *frame, PyObject *name, PyObject *qualname)
`戻り値: 新しい参照。'
`frame' オブジェクトから新たなジェネレータオブジェクトを生成し、 @code{__name__} と @code{__qualname__} を `name' と `qualname' に設定して返します。
この関数は `frame' への参照を盗みます。
`frame' 引数は @code{NULL} であってはなりません。
@end deffn

@geindex PyGen_GetCode (C function)
@anchor{c-api/gen c PyGen_GetCode}@anchor{54a5}
@deffn {C の関数} @ref{97b,,PyCodeObject} *PyGen_GetCode (PyGenObject *gen)

Return a new @ref{5e2,,strong reference} to the code object wrapped by `gen'.
This function always succeeds.
@end deffn

@menu
* Asynchronous Generator Objects:: 
* Deprecated API: Deprecated API<5>. 

@end menu

@node Asynchronous Generator Objects,Deprecated API<5>,,ジェネレータオブジェクト
@anchor{c-api/gen asynchronous-generator-objects}@anchor{54a6}
@subsubsection Asynchronous Generator Objects



@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 525
PEP 525@footnote{https://peps.python.org/pep-0525/}


@geindex PyAsyncGen_Type (C var)
@anchor{c-api/gen c PyAsyncGen_Type}@anchor{54a7}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyAsyncGen_Type

The type object corresponding to asynchronous generator objects. This is
available as @ref{29e7,,types.AsyncGeneratorType} in the Python layer.


Added in version 3.6.

@end deffn

@geindex PyAsyncGen_New (C function)
@anchor{c-api/gen c PyAsyncGen_New}@anchor{54a8}
@deffn {C の関数} @ref{5df,,PyObject} *PyAsyncGen_New (PyFrameObject *frame, PyObject *name, PyObject *qualname)

Create a new asynchronous generator wrapping `frame', with @code{__name__} and
@code{__qualname__} set to `name' and `qualname'. `frame' is stolen by this
function and must not be @code{NULL}.

On success, this function returns a @ref{5e2,,strong reference} to the
new asynchronous generator. On failure, this function returns @code{NULL}
with an exception set.


Added in version 3.6.

@end deffn

@geindex PyAsyncGen_CheckExact (C function)
@anchor{c-api/gen c PyAsyncGen_CheckExact}@anchor{54a9}
@deffn {C の関数} int PyAsyncGen_CheckExact (PyObject *op)

Return true if `op' is an asynchronous generator object, false otherwise.
This function always succeeds.


Added in version 3.6.

@end deffn

@node Deprecated API<5>,,Asynchronous Generator Objects,ジェネレータオブジェクト
@anchor{c-api/gen deprecated-api}@anchor{54aa}
@subsubsection Deprecated API


@geindex PyAsyncGenASend_CheckExact (C macro)
@anchor{c-api/gen c PyAsyncGenASend_CheckExact}@anchor{54ab}
@deffn {C のマクロ} PyAsyncGenASend_CheckExact (op)

This is a @ref{23d,,soft deprecated} API that was included in Python's C API
by mistake.

It is solely here for completeness; do not use this API.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node コルーチンオブジェクト<2>,コンテキスト変数オブジェクト,ジェネレータオブジェクト,その他のオブジェクト<2>
@anchor{c-api/coro doc}@anchor{54ac}@anchor{c-api/coro coro-objects}@anchor{10d0}@anchor{c-api/coro coroutine-objects}@anchor{54ad}@anchor{c-api/coro translation-repo}@anchor{54ae}
@subsubsection コルーチンオブジェクト



Added in version 3.5.


コルーチンオブジェクトは @code{async} キーワードを使って定義した関数が返すオブジェクトです。

@geindex PyCoroObject (C type)
@anchor{c-api/coro c PyCoroObject}@anchor{54af}
@deffn {C のデータ型} type PyCoroObject

コルーチンオブジェクトのための C 構造体。
@end deffn

@geindex PyCoro_Type (C var)
@anchor{c-api/coro c PyCoro_Type}@anchor{54b0}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCoro_Type

コルーチンオブジェクトに対応する型オブジェクト。
@end deffn

@geindex PyCoro_CheckExact (C function)
@anchor{c-api/coro c PyCoro_CheckExact}@anchor{54b1}
@deffn {C の関数} int PyCoro_CheckExact (PyObject *ob)

`ob' が @ref{54b0,,PyCoro_Type} の場合に真を返します。
`ob' は @code{NULL} であってはなりません。
この関数は常に成功します。
@end deffn

@geindex PyCoro_New (C function)
@anchor{c-api/coro c PyCoro_New}@anchor{54b2}
@deffn {C の関数} @ref{5df,,PyObject} *PyCoro_New (PyFrameObject *frame, PyObject *name, PyObject *qualname)
`戻り値: 新しい参照。'
`frame' オブジェクトから新しいコルーチンオブジェクトを生成して、 @code{__name__} と @code{__qualname__} を `name' と `qualname' に設定して返します。
この関数は `frame' への参照を奪います。 `frame' 引数は @code{NULL} であってはなりません。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node コンテキスト変数オブジェクト,型ヒントのためのオブジェクト,コルーチンオブジェクト<2>,その他のオブジェクト<2>
@anchor{c-api/contextvars doc}@anchor{54b3}@anchor{c-api/contextvars context-variables-objects}@anchor{54b4}@anchor{c-api/contextvars contextvarsobjects}@anchor{cf0}@anchor{c-api/contextvars translation-repo}@anchor{54b5}
@subsubsection コンテキスト変数オブジェクト

@anchor{c-api/contextvars contextvarsobjects-pointertype-change}@anchor{e1f}

Added in version 3.7.



バージョン 3.7.1 で変更: 

@cartouche
@quotation 注釈 
Python 3.7.1 で全てのコンテキスト変数の C API のシグネチャは、 @ref{54b6,,PyContext}, @ref{54b7,,PyContextVar}, @ref{54b8,,PyContextToken} の代わりに @ref{5df,,PyObject} ポインタを使うように `変更' されました。例えば:

@example
// in 3.7.0:
PyContext *PyContext_New(void);

// in 3.7.1+:
PyObject *PyContext_New(void);
@end example

詳細は bpo-34762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34762} を参照してください。
@end quotation
@end cartouche


この節では、 @ref{28,,contextvars} モジュールの公開 C API の詳細について説明します。

@geindex PyContext (C type)
@anchor{c-api/contextvars c PyContext}@anchor{54b6}
@deffn {C のデータ型} type PyContext

@ref{177,,contextvars.Context} オブジェクトを表現するための C 構造体。
@end deffn

@geindex PyContextVar (C type)
@anchor{c-api/contextvars c PyContextVar}@anchor{54b7}
@deffn {C のデータ型} type PyContextVar

@ref{1875,,contextvars.ContextVar} オブジェクトを表現するための C 構造体。
@end deffn

@geindex PyContextToken (C type)
@anchor{c-api/contextvars c PyContextToken}@anchor{54b8}
@deffn {C のデータ型} type PyContextToken

@ref{1e2,,contextvars.Token} オブジェクトを表現するための C 構造体。
@end deffn

@geindex PyContext_Type (C var)
@anchor{c-api/contextvars c PyContext_Type}@anchor{54b9}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyContext_Type

`コンテキスト' 型を表現する型オブジェクト。
@end deffn

@geindex PyContextVar_Type (C var)
@anchor{c-api/contextvars c PyContextVar_Type}@anchor{54ba}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyContextVar_Type

`コンテキスト変数' 型を表現する型オブジェクト。
@end deffn

@geindex PyContextToken_Type (C var)
@anchor{c-api/contextvars c PyContextToken_Type}@anchor{54bb}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyContextToken_Type

`コンテキスト変数トークン' 型を表現する型オブジェクト。
@end deffn

型チェックマクロ:

@geindex PyContext_CheckExact (C function)
@anchor{c-api/contextvars c PyContext_CheckExact}@anchor{54bc}
@deffn {C の関数} int PyContext_CheckExact (PyObject *o)

`o' が @ref{54b9,,PyContext_Type} の場合に真を返します。
`o' は @code{NULL} であってはなりません。
この関数は常に成功します。
@end deffn

@geindex PyContextVar_CheckExact (C function)
@anchor{c-api/contextvars c PyContextVar_CheckExact}@anchor{54bd}
@deffn {C の関数} int PyContextVar_CheckExact (PyObject *o)

`o' が @ref{54ba,,PyContextVar_Type} の場合に真を返します。
`o' は @code{NULL} であってはなりません。
この関数は常に成功します。
@end deffn

@geindex PyContextToken_CheckExact (C function)
@anchor{c-api/contextvars c PyContextToken_CheckExact}@anchor{54be}
@deffn {C の関数} int PyContextToken_CheckExact (PyObject *o)

`o' が @ref{54bb,,PyContextToken_Type} の場合に真を返します。
`o' は @code{NULL} であってはなりません。
この関数は常に成功します。
@end deffn

コンテキストオブジェクトを取り扱う関数:

@geindex PyContext_New (C function)
@anchor{c-api/contextvars c PyContext_New}@anchor{54bf}
@deffn {C の関数} @ref{5df,,PyObject} *PyContext_New (void)
`戻り値: 新しい参照。'
新しい空のコンテキストオブジェクトを作成します。
エラーが起きた場合は @code{NULL} を返します。
@end deffn

@geindex PyContext_Copy (C function)
@anchor{c-api/contextvars c PyContext_Copy}@anchor{54c0}
@deffn {C の関数} @ref{5df,,PyObject} *PyContext_Copy (PyObject *ctx)
`戻り値: 新しい参照。'
渡された `ctx' コンテキストオブジェクトの浅いコピーを作成します。
エラーが起きた場合は @code{NULL} を返します。
@end deffn

@geindex PyContext_CopyCurrent (C function)
@anchor{c-api/contextvars c PyContext_CopyCurrent}@anchor{54c1}
@deffn {C の関数} @ref{5df,,PyObject} *PyContext_CopyCurrent (void)
`戻り値: 新しい参照。'
現在のコンテキストオブジェクトの浅いコピーを作成します。
エラーが起きた場合は @code{NULL} を返します。
@end deffn

@geindex PyContext_Enter (C function)
@anchor{c-api/contextvars c PyContext_Enter}@anchor{54c2}
@deffn {C の関数} int PyContext_Enter (PyObject *ctx)

`ctx' を現在のスレッドの現在のコンテキストに設定します。
成功したら @code{0} を、失敗したら @code{-1} を返します。
@end deffn

@geindex PyContext_Exit (C function)
@anchor{c-api/contextvars c PyContext_Exit}@anchor{54c3}
@deffn {C の関数} int PyContext_Exit (PyObject *ctx)

`ctx' コンテキストを無効にし、1 つ前のコンテキストを現在のスレッドの現在のコンテキストに復元します。
成功したら @code{0} を、失敗したら @code{-1} を返します。
@end deffn

@geindex PyContext_AddWatcher (C function)
@anchor{c-api/contextvars c PyContext_AddWatcher}@anchor{1992}
@deffn {C の関数} int PyContext_AddWatcher (PyContext_WatchCallback callback)

Register `callback' as a context object watcher for the current interpreter.
Return an ID which may be passed to @ref{1993,,PyContext_ClearWatcher()}.
In case of error (e.g. no more watcher IDs available),
return @code{-1} and set an exception.


Added in version 3.14.

@end deffn

@geindex PyContext_ClearWatcher (C function)
@anchor{c-api/contextvars c PyContext_ClearWatcher}@anchor{1993}
@deffn {C の関数} int PyContext_ClearWatcher (int watcher_id)

Clear watcher identified by `watcher_id' previously returned from
@ref{1992,,PyContext_AddWatcher()} for the current interpreter.
Return @code{0} on success, or @code{-1} and set an exception on error
(e.g. if the given `watcher_id' was never registered.)


Added in version 3.14.

@end deffn

@geindex PyContextEvent (C type)
@anchor{c-api/contextvars c PyContextEvent}@anchor{54c4}
@deffn {C のデータ型} type PyContextEvent

Enumeration of possible context object watcher events:


@itemize -

@item 
@code{Py_CONTEXT_SWITCHED}: The @ref{1964,,current context} has switched to a
different context.  The object passed to the watch callback is the
now-current @ref{177,,contextvars.Context} object, or None if no context is
current.
@end itemize


Added in version 3.14.

@end deffn

@geindex PyContext_WatchCallback (C type)
@anchor{c-api/contextvars c PyContext_WatchCallback}@anchor{54c5}
@deffn {C のデータ型} typedef int (*PyContext_WatchCallback)(@ref{54c4,,PyContextEvent} event, @ref{5df,,PyObject} *obj)

Context object watcher callback function.  The object passed to the callback
is event-specific; see @ref{54c4,,PyContextEvent} for details.

If the callback returns with an exception set, it must return @code{-1}; this
exception will be printed as an unraisable exception using
@ref{5f1,,PyErr_FormatUnraisable()}. Otherwise it should return @code{0}.

There may already be a pending exception set on entry to the callback. In
this case, the callback should return @code{0} with the same exception still
set. This means the callback may not call any other API that can set an
exception unless it saves and clears the exception state first, and restores
it before returning.


Added in version 3.14.

@end deffn

コンテキスト変数の関数:

@geindex PyContextVar_New (C function)
@anchor{c-api/contextvars c PyContextVar_New}@anchor{54c6}
@deffn {C の関数} @ref{5df,,PyObject} *PyContextVar_New (const char *name, PyObject *def)
`戻り値: 新しい参照。'
新しい @code{ContextVar} オブジェクトを作成します。`name' 引数は内部走査とデバッグの目的で使われます。`def' 引数はコンテキスト変数のデフォルト値を指定するか、デフォルトがない場合は @code{NULL} です。エラーが起きた場合は、関数は @code{NULL} を返します。
@end deffn

@geindex PyContextVar_Get (C function)
@anchor{c-api/contextvars c PyContextVar_Get}@anchor{54c7}
@deffn {C の関数} int PyContextVar_Get (PyObject *var, PyObject *default_value, PyObject **value)

コンテキスト変数の値を取得します。
取得中にエラーが起きた場合は @code{-1} を、値が見付かっても見付からなくてもエラーが起きなかった場合は @code{0} を返します。

コンテキスト変数が見付かった場合、 `value' はそれを指すポインタになっています。
コンテキスト変数が見付から `なかった' 場合は、 `value' が指すものは次のようになっています:


@itemize -

@item 
(@code{NULL} でなければ) `default_value'

@item 
(@code{NULL} でなければ) `var' のデフォルト値

@item 
@code{NULL}
@end itemize

@code{NULL} を除けば、この関数は新しい参照を返します。
@end deffn

@geindex PyContextVar_Set (C function)
@anchor{c-api/contextvars c PyContextVar_Set}@anchor{54c8}
@deffn {C の関数} @ref{5df,,PyObject} *PyContextVar_Set (PyObject *var, PyObject *value)
`戻り値: 新しい参照。'
現在のコンテキストにおいて `var' の値を `value' にセットします。この変更による新しいトークンオブジェクトか、エラーが起こった場合は`@w{`}NULL`@w{`}を返します。
@end deffn

@geindex PyContextVar_Reset (C function)
@anchor{c-api/contextvars c PyContextVar_Reset}@anchor{54c9}
@deffn {C の関数} int PyContextVar_Reset (PyObject *var, PyObject *token)

`var' コンテキスト変数の状態をリセットし、 `token' を返した @ref{54c8,,PyContextVar_Set()} が呼ばれる前の状態に戻します。
この関数は成功したら @code{0} 、失敗したら @code{-1} を返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 型ヒントのためのオブジェクト,,コンテキスト変数オブジェクト,その他のオブジェクト<2>
@anchor{c-api/typehints doc}@anchor{54ca}@anchor{c-api/typehints objects-for-type-hinting}@anchor{54cb}@anchor{c-api/typehints translation-repo}@anchor{54cc}@anchor{c-api/typehints typehintobjects}@anchor{54cd}
@subsubsection 型ヒントのためのオブジェクト


Various built-in types for type hinting are provided.  Currently,
two types exist -- @ref{8c1,,GenericAlias} and
@ref{9c5,,Union}.  Only @code{GenericAlias} is exposed to C.

@geindex Py_GenericAlias (C function)
@anchor{c-api/typehints c Py_GenericAlias}@anchor{512b}
@deffn {C の関数} @ref{5df,,PyObject} *Py_GenericAlias (PyObject *origin, PyObject *args)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
@ref{8c1,,GenericAlias} オブジェクトを生成します。Pythonクラス @ref{9ec,,types.GenericAlias} を呼び出すことと同等です。引数 `origin' と `args' は @code{GenericAlias} の @code{__origin__} および @code{__args__} 属性をそれぞれ設定します。 `origin' は @ref{c9c,,PyTypeObject}* でなければならず、 `args' は @ref{5224,,PyTupleObject}* または任意の @code{PyObject*} です。 `args' がタプルでない場合には1タプルが自動的に生成され、@code{__args__} には @code{(args,)} が設定されます。引数チェックは最小限なため、たとえ `origin' が型を示すオブジェクトでなくても関数呼び出しは成功します。@code{GenericAlias} の @code{__parameters__} 属性は @code{__args__} から必要に応じて遅延生成されます。失敗した場合、例外が送出されて @code{NULL} を返します。

以下は拡張の型をジェネリックにする例です。

@example
...
static PyMethodDef my_obj_methods[] = @{
    // Other methods.
    ...
    @{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"@}
    ...
@}
@end example


@subsubheading 参考


The data model method @ref{943,,__class_getitem__()}.



Added in version 3.9.

@end deffn

@geindex Py_GenericAliasType (C var)
@anchor{c-api/typehints c Py_GenericAliasType}@anchor{512c}
@deffn {C 変数} @ref{c9c,,PyTypeObject} Py_GenericAliasType
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
@ref{512b,,Py_GenericAlias()} により返されるCの型オブジェクトです。Pythonの @ref{9ec,,types.GenericAlias} と同等です。


Added in version 3.9.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node C API for extension modules,,その他のオブジェクト<2>,具象オブジェクト concrete object レイヤ
@anchor{c-api/concrete c-api-for-extension-modules}@anchor{54ce}
@subsection C API for extension modules


@menu
* Curses C API:: 
* Internal data:: 
* DateTime オブジェクト: DateTime オブジェクト<2>. 
* Internal data: Internal data<2>. 

@end menu

@node Curses C API,Internal data,,C API for extension modules
@anchor{c-api/curses doc}@anchor{54cf}@anchor{c-api/curses curses-c-api}@anchor{54d0}
@subsubsection Curses C API


@ref{2f,,curses} exposes a small C interface for extension modules.
Consumers must include the header file @code{py_curses.h} (which is not
included by default by @code{Python.h}) and @ref{54d1,,import_curses()} must
be invoked, usually as part of the module initialisation function, to populate
@ref{54d2,,PyCurses_API}.

@cartouche
@quotation 警告 
Neither the C API nor the pure Python @ref{2f,,curses} module are compatible
with subinterpreters.
@end quotation
@end cartouche

@geindex import_curses (C macro)
@anchor{c-api/curses c import_curses}@anchor{54d1}
@deffn {C のマクロ} import_curses ()

Import the curses C API. The macro does not need a semi-colon to be called.

On success, populate the @ref{54d2,,PyCurses_API} pointer.

On failure, set @ref{54d2,,PyCurses_API} to NULL and set an exception.
The caller must check if an error occurred via @ref{1caf,,PyErr_Occurred()}:

@example
import_curses();  // semi-colon is optional but recommended
if (PyErr_Occurred()) @{ /* cleanup */ @}
@end example
@end deffn

@geindex PyCurses_API (C var)
@anchor{c-api/curses c PyCurses_API}@anchor{54d2}
@deffn {C 変数} void **PyCurses_API

Dynamically allocated object containing the curses C API.
This variable is only available once @ref{54d1,,import_curses} succeeds.

@code{PyCurses_API[0]} corresponds to @ref{54d3,,PyCursesWindow_Type}.

@code{PyCurses_API[1]}, @code{PyCurses_API[2]}, and @code{PyCurses_API[3]}
are pointers to predicate functions of type @code{int (*)(void)}.

When called, these predicates return whether @ref{34a4,,curses.setupterm()},
@ref{190f,,curses.initscr()}, and @ref{34a5,,curses.start_color()} have been called
respectively.

See also the convenience macros @ref{54d4,,PyCursesSetupTermCalled},
@ref{54d5,,PyCursesInitialised}, and @ref{54d6,,PyCursesInitialisedColor}.

@cartouche
@quotation 注釈 
The number of entries in this structure is subject to changes.
Consider using @ref{54d7,,PyCurses_API_pointers} to check if
new fields are available or not.
@end quotation
@end cartouche
@end deffn

@geindex PyCurses_API_pointers (C macro)
@anchor{c-api/curses c PyCurses_API_pointers}@anchor{54d7}
@deffn {C のマクロ} PyCurses_API_pointers

The number of accessible fields (@code{4}) in @ref{54d2,,PyCurses_API}.
This number is incremented whenever new fields are added.
@end deffn

@geindex PyCursesWindow_Type (C var)
@anchor{c-api/curses c PyCursesWindow_Type}@anchor{54d3}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCursesWindow_Type

The @ref{b5e,,heap type} corresponding to @ref{12a7,,curses.window}.
@end deffn

@geindex PyCursesWindow_Check (C function)
@anchor{c-api/curses c PyCursesWindow_Check}@anchor{54d8}
@deffn {C の関数} int PyCursesWindow_Check (PyObject *op)

Return true if `op' is a @ref{12a7,,curses.window} instance, false otherwise.
@end deffn

The following macros are convenience macros expanding into C statements.
In particular, they can only be used as @code{macro;} or @code{macro}, but not
@code{macro()} or @code{macro();}.

@geindex PyCursesSetupTermCalled (C macro)
@anchor{c-api/curses c PyCursesSetupTermCalled}@anchor{54d4}
@deffn {C のマクロ} PyCursesSetupTermCalled

Macro checking if @ref{34a4,,curses.setupterm()} has been called.

The macro expansion is roughly equivalent to:

@example
@{
    typedef int (*predicate_t)(void);
    predicate_t was_setupterm_called = (predicate_t)PyCurses_API[1];
    if (!was_setupterm_called()) @{
        return NULL;
    @}
@}
@end example
@end deffn

@geindex PyCursesInitialised (C macro)
@anchor{c-api/curses c PyCursesInitialised}@anchor{54d5}
@deffn {C のマクロ} PyCursesInitialised

Macro checking if @ref{190f,,curses.initscr()} has been called.

The macro expansion is roughly equivalent to:

@example
@{
    typedef int (*predicate_t)(void);
    predicate_t was_initscr_called = (predicate_t)PyCurses_API[2];
    if (!was_initscr_called()) @{
        return NULL;
    @}
@}
@end example
@end deffn

@geindex PyCursesInitialisedColor (C macro)
@anchor{c-api/curses c PyCursesInitialisedColor}@anchor{54d6}
@deffn {C のマクロ} PyCursesInitialisedColor

Macro checking if @ref{34a5,,curses.start_color()} has been called.

The macro expansion is roughly equivalent to:

@example
@{
    typedef int (*predicate_t)(void);
    predicate_t was_start_color_called = (predicate_t)PyCurses_API[3];
    if (!was_start_color_called()) @{
        return NULL;
    @}
@}
@end example
@end deffn

@node Internal data,DateTime オブジェクト<2>,Curses C API,C API for extension modules
@anchor{c-api/curses internal-data}@anchor{54d9}
@subsubsection Internal data


The following objects are exposed by the C API but should be considered
internal-only.

@geindex PyCurses_CAPSULE_NAME (C macro)
@anchor{c-api/curses c PyCurses_CAPSULE_NAME}@anchor{54da}
@deffn {C のマクロ} PyCurses_CAPSULE_NAME

Name of the curses capsule to pass to @ref{1c10,,PyCapsule_Import()}.

Internal usage only. Use @ref{54d1,,import_curses} instead.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node DateTime オブジェクト<2>,Internal data<2>,Internal data,C API for extension modules
@anchor{c-api/datetime doc}@anchor{54db}@anchor{c-api/datetime datetime-objects}@anchor{54dc}@anchor{c-api/datetime datetimeobjects}@anchor{526d}@anchor{c-api/datetime translation-repo}@anchor{54dd}
@subsubsection DateTime オブジェクト


@ref{34,,datetime} モジュールでは、様々な日付オブジェクトや時刻オブジェクトを提供しています。以下に示す関数を使う場合には、あらかじめヘッダファイル @code{datetime.h} をソースに include し (@code{Python.h} はこのファイルを include しません)、 @ref{54de,,PyDateTime_IMPORT} マクロを、通常はモジュール初期化関数から、起動しておく必要があります。このマクロは以下のマクロで使われる静的変数 @ref{54df,,PyDateTimeAPI} に C 構造体へのポインタを入れます。

@geindex PyDateTime_IMPORT (C macro)
@anchor{c-api/datetime c PyDateTime_IMPORT}@anchor{54de}
@deffn {C のマクロ} PyDateTime_IMPORT ()

Import the datetime C API.

On success, populate the @ref{54df,,PyDateTimeAPI} pointer.
On failure, set @ref{54df,,PyDateTimeAPI} to @code{NULL} and set an exception.
The caller must check if an error occurred via @ref{1caf,,PyErr_Occurred()}:

@example
PyDateTime_IMPORT;
if (PyErr_Occurred()) @{ /* cleanup */ @}
@end example

@cartouche
@quotation 警告 
This is not compatible with subinterpreters.
@end quotation
@end cartouche
@end deffn

@geindex PyDateTime_CAPI (C type)
@anchor{c-api/datetime c PyDateTime_CAPI}@anchor{54e0}
@deffn {C のデータ型} type PyDateTime_CAPI

Structure containing the fields for the datetime C API.

The fields of this structure are private and subject to change.

Do not use this directly; prefer @code{PyDateTime_*} APIs instead.
@end deffn

@geindex PyDateTimeAPI (C var)
@anchor{c-api/datetime c PyDateTimeAPI}@anchor{54df}
@deffn {C 変数} @ref{54e0,,PyDateTime_CAPI} *PyDateTimeAPI

Dynamically allocated object containing the datetime C API.

This variable is only available once @ref{54de,,PyDateTime_IMPORT} succeeds.
@end deffn

@geindex PyDateTime_Date (C type)
@anchor{c-api/datetime c PyDateTime_Date}@anchor{54e1}
@deffn {C のデータ型} type PyDateTime_Date

この @ref{5df,,PyObject} のサブタイプは、Pythonの日付オブジェクトを表します。
@end deffn

@geindex PyDateTime_DateTime (C type)
@anchor{c-api/datetime c PyDateTime_DateTime}@anchor{54e2}
@deffn {C のデータ型} type PyDateTime_DateTime

この @ref{5df,,PyObject} のサブタイプは Python の datetime オブジェクトを表します。
@end deffn

@geindex PyDateTime_Time (C type)
@anchor{c-api/datetime c PyDateTime_Time}@anchor{54e3}
@deffn {C のデータ型} type PyDateTime_Time

この @ref{5df,,PyObject} のサブタイプは Python の time オブジェクトを表現します。
@end deffn

@geindex PyDateTime_Delta (C type)
@anchor{c-api/datetime c PyDateTime_Delta}@anchor{54e4}
@deffn {C のデータ型} type PyDateTime_Delta

この @ref{5df,,PyObject} のサブタイプは二つの datetime の値の差分を表します。
@end deffn

@geindex PyDateTime_DateType (C var)
@anchor{c-api/datetime c PyDateTime_DateType}@anchor{54e5}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDateTime_DateType

この @ref{c9c,,PyTypeObject} のインスタンスは Python の date 型を表します; Python レイヤにおける @ref{1fa,,datetime.date} と同じオブジェクトです。
@end deffn

@geindex PyDateTime_DateTimeType (C var)
@anchor{c-api/datetime c PyDateTime_DateTimeType}@anchor{54e6}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDateTime_DateTimeType

この @ref{c9c,,PyTypeObject} のインスタンスは Python の datetime 型を表現します; Python レイヤにおける @ref{4e2,,datetime.datetime} と同じオブジェクトです。
@end deffn

@geindex PyDateTime_TimeType (C var)
@anchor{c-api/datetime c PyDateTime_TimeType}@anchor{54e7}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDateTime_TimeType

この @ref{c9c,,PyTypeObject} のインスタンスは Python の time 型を表します; Python レイヤにおける @ref{1fb,,datetime.time} と同じオブジェクトです。
@end deffn

@geindex PyDateTime_DeltaType (C var)
@anchor{c-api/datetime c PyDateTime_DeltaType}@anchor{54e8}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDateTime_DeltaType

This instance of @ref{c9c,,PyTypeObject} represents the Python type for
the difference between two datetime values;
it is the same object as @ref{bc3,,datetime.timedelta} in the Python layer.
@end deffn

@geindex PyDateTime_TZInfoType (C var)
@anchor{c-api/datetime c PyDateTime_TZInfoType}@anchor{54e9}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyDateTime_TZInfoType

この @ref{c9c,,PyTypeObject} のインスタンスは Python の タイムゾーン情報型を表します; Python レイヤにおける @ref{7f6,,datetime.tzinfo} と同じオブジェクトです。
@end deffn

UTCシングルトンにアクセスするためのマクロ:

@geindex PyDateTime_TimeZone_UTC (C var)
@anchor{c-api/datetime c PyDateTime_TimeZone_UTC}@anchor{dbc}
@deffn {C 変数} @ref{5df,,PyObject} *PyDateTime_TimeZone_UTC

UTCタイムゾーンに相当するシングルトンを返します。これは @ref{827,,datetime.timezone.utc} と同じオブジェクトです。


Added in version 3.7.

@end deffn

型チェックマクロ:

@geindex PyDate_Check (C function)
@anchor{c-api/datetime c PyDate_Check}@anchor{54ea}
@deffn {C の関数} int PyDate_Check (PyObject *ob)

`ob' が @ref{54e5,,PyDateTime_DateType} 型か @code{PyDateTime_DateType} 型のサブタイプのオブジェクトの場合に真を返します; `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyDate_CheckExact (C function)
@anchor{c-api/datetime c PyDate_CheckExact}@anchor{54eb}
@deffn {C の関数} int PyDate_CheckExact (PyObject *ob)

`ob' が @ref{54e5,,PyDateTime_DateType} の場合に真を返します。
`ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyDateTime_Check (C function)
@anchor{c-api/datetime c PyDateTime_Check}@anchor{54ec}
@deffn {C の関数} int PyDateTime_Check (PyObject *ob)

`ob' が @ref{54e6,,PyDateTime_DateTimeType} 型か @code{PyDateTime_DateTimeType} 型のサブタイプのオブジェクトの場合に真を返します; `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyDateTime_CheckExact (C function)
@anchor{c-api/datetime c PyDateTime_CheckExact}@anchor{54ed}
@deffn {C の関数} int PyDateTime_CheckExact (PyObject *ob)

`ob' が @ref{54e6,,PyDateTime_DateTimeType} の場合に真を返します。
`ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyTime_Check (C function)
@anchor{c-api/datetime c PyTime_Check}@anchor{54ee}
@deffn {C の関数} int PyTime_Check (PyObject *ob)

`ob' が @ref{54e7,,PyDateTime_TimeType} 型か @code{PyDateTime_TimeType} 型のサブタイプのオブジェクトの場合に真を返します; `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyTime_CheckExact (C function)
@anchor{c-api/datetime c PyTime_CheckExact}@anchor{54ef}
@deffn {C の関数} int PyTime_CheckExact (PyObject *ob)

`ob' が @ref{54e7,,PyDateTime_TimeType} の場合に真を返します。
`ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyDelta_Check (C function)
@anchor{c-api/datetime c PyDelta_Check}@anchor{54f0}
@deffn {C の関数} int PyDelta_Check (PyObject *ob)

`ob' が @ref{54e8,,PyDateTime_DeltaType} 型か @code{PyDateTime_DeltaType} 型のサブタイプのオブジェクトの場合に真を返します; `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyDelta_CheckExact (C function)
@anchor{c-api/datetime c PyDelta_CheckExact}@anchor{54f1}
@deffn {C の関数} int PyDelta_CheckExact (PyObject *ob)

`ob' が @ref{54e8,,PyDateTime_DeltaType} の場合に真を返します。
`ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyTZInfo_Check (C function)
@anchor{c-api/datetime c PyTZInfo_Check}@anchor{54f2}
@deffn {C の関数} int PyTZInfo_Check (PyObject *ob)

`ob' が @ref{54e9,,PyDateTime_TZInfoType} 型か @code{PyDateTime_TZInfoType} 型のサブタイプのオブジェクトの場合に真を返します; `ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

@geindex PyTZInfo_CheckExact (C function)
@anchor{c-api/datetime c PyTZInfo_CheckExact}@anchor{54f3}
@deffn {C の関数} int PyTZInfo_CheckExact (PyObject *ob)

`ob' が @ref{54e9,,PyDateTime_TZInfoType} の場合に真を返します。
`ob' は @code{NULL} であってはなりません。この関数は常に成功します。
@end deffn

以下はオブジェクトを作成するためのマクロです:

@geindex PyDate_FromDate (C function)
@anchor{c-api/datetime c PyDate_FromDate}@anchor{54f4}
@deffn {C の関数} @ref{5df,,PyObject} *PyDate_FromDate (int year, int month, int day)
`戻り値: 新しい参照。'
指定した年、月、日の @ref{1fa,,datetime.date} オブジェクトを返します。
@end deffn

@geindex PyDateTime_FromDateAndTime (C function)
@anchor{c-api/datetime c PyDateTime_FromDateAndTime}@anchor{54f5}
@deffn {C の関数} @ref{5df,,PyObject} *PyDateTime_FromDateAndTime (int year, int month, int day, int hour, int minute, int second, int usecond)
`戻り値: 新しい参照。'
指定した年、月、日、時、分、秒、マイクロ秒の @ref{4e2,,datetime.datetime} オブジェクトを返します。
@end deffn

@geindex PyDateTime_FromDateAndTimeAndFold (C function)
@anchor{c-api/datetime c PyDateTime_FromDateAndTimeAndFold}@anchor{54f6}
@deffn {C の関数} @ref{5df,,PyObject} *PyDateTime_FromDateAndTimeAndFold (int year, int month, int day, int hour, int minute, int second, int usecond, int fold)
`戻り値: 新しい参照。'
指定された年、月、日、時、分、秒、マイクロ秒、fold の @ref{4e2,,datetime.datetime} オブジェクトを返します。


Added in version 3.6.

@end deffn

@geindex PyTime_FromTime (C function)
@anchor{c-api/datetime c PyTime_FromTime}@anchor{54f7}
@deffn {C の関数} @ref{5df,,PyObject} *PyTime_FromTime (int hour, int minute, int second, int usecond)
`戻り値: 新しい参照。'
指定された時、分、秒、マイクロ秒の @ref{1fb,,datetime.time} オブジェクトを返します。
@end deffn

@geindex PyTime_FromTimeAndFold (C function)
@anchor{c-api/datetime c PyTime_FromTimeAndFold}@anchor{54f8}
@deffn {C の関数} @ref{5df,,PyObject} *PyTime_FromTimeAndFold (int hour, int minute, int second, int usecond, int fold)
`戻り値: 新しい参照。'
指定された時、分、秒、マイクロ秒、fold の @ref{1fb,,datetime.time} オブジェクトを返します。


Added in version 3.6.

@end deffn

@geindex PyDelta_FromDSU (C function)
@anchor{c-api/datetime c PyDelta_FromDSU}@anchor{54f9}
@deffn {C の関数} @ref{5df,,PyObject} *PyDelta_FromDSU (int days, int seconds, int useconds)
`戻り値: 新しい参照。'
指定された日、秒、マイクロ秒の @ref{bc3,,datetime.timedelta} オブジェクトを返します。マイクロ秒と秒が @ref{bc3,,datetime.timedelta} オブジェクトで定義されている範囲に入るように正規化を行います。
@end deffn

@geindex PyTimeZone_FromOffset (C function)
@anchor{c-api/datetime c PyTimeZone_FromOffset}@anchor{dba}
@deffn {C の関数} @ref{5df,,PyObject} *PyTimeZone_FromOffset (PyObject *offset)
`戻り値: 新しい参照。'
`offset' 引数で指定した固定オフセットを持つ、名前のない @ref{12d5,,datetime.timezone} オブジェクトを返します。


Added in version 3.7.

@end deffn

@geindex PyTimeZone_FromOffsetAndName (C function)
@anchor{c-api/datetime c PyTimeZone_FromOffsetAndName}@anchor{dbb}
@deffn {C の関数} @ref{5df,,PyObject} *PyTimeZone_FromOffsetAndName (PyObject *offset, PyObject *name)
`戻り値: 新しい参照。'
`offset*引数で指定した固定のオフセットと、*name' のタイムゾーン名を持つ @ref{12d5,,datetime.timezone} オブジェクトを返します。


Added in version 3.7.

@end deffn

以下のマクロは date オブジェクトからフィールド値を取り出すためのものです。引数は @ref{54e1,,PyDateTime_Date} またはそのサブクラス (例えば @ref{54e2,,PyDateTime_DateTime})の  インスタンスでなければなりません。引数を @code{NULL} にしてはならず、型チェックは行いません:

@geindex PyDateTime_GET_YEAR (C function)
@anchor{c-api/datetime c PyDateTime_GET_YEAR}@anchor{54fa}
@deffn {C の関数} int PyDateTime_GET_YEAR (PyDateTime_Date *o)

年を正の整数で返します。
@end deffn

@geindex PyDateTime_GET_MONTH (C function)
@anchor{c-api/datetime c PyDateTime_GET_MONTH}@anchor{54fb}
@deffn {C の関数} int PyDateTime_GET_MONTH (PyDateTime_Date *o)

月を 1 から 12 の間の整数で返します。
@end deffn

@geindex PyDateTime_GET_DAY (C function)
@anchor{c-api/datetime c PyDateTime_GET_DAY}@anchor{54fc}
@deffn {C の関数} int PyDateTime_GET_DAY (PyDateTime_Date *o)

日を 1 から 31 の間の整数で返します。
@end deffn

以下のマクロは datetime オブジェクトからフィールド値を取り出すためのものです。引数は @ref{54e2,,PyDateTime_DateTime} またはそのサブクラスのインスタンスでなければなりません。引数を @code{NULL} にしてはならず、型チェックは行いません:

@geindex PyDateTime_DATE_GET_HOUR (C function)
@anchor{c-api/datetime c PyDateTime_DATE_GET_HOUR}@anchor{54fd}
@deffn {C の関数} int PyDateTime_DATE_GET_HOUR (PyDateTime_DateTime *o)

時を 0 から 23 の間の整数で返します。
@end deffn

@geindex PyDateTime_DATE_GET_MINUTE (C function)
@anchor{c-api/datetime c PyDateTime_DATE_GET_MINUTE}@anchor{54fe}
@deffn {C の関数} int PyDateTime_DATE_GET_MINUTE (PyDateTime_DateTime *o)

分を 0 から 59 の間の整数で返します。
@end deffn

@geindex PyDateTime_DATE_GET_SECOND (C function)
@anchor{c-api/datetime c PyDateTime_DATE_GET_SECOND}@anchor{54ff}
@deffn {C の関数} int PyDateTime_DATE_GET_SECOND (PyDateTime_DateTime *o)

秒を 0 から 59 の間の整数で返します。
@end deffn

@geindex PyDateTime_DATE_GET_MICROSECOND (C function)
@anchor{c-api/datetime c PyDateTime_DATE_GET_MICROSECOND}@anchor{5500}
@deffn {C の関数} int PyDateTime_DATE_GET_MICROSECOND (PyDateTime_DateTime *o)

マイクロ秒を 0 から 999999 の間の整数で返します。
@end deffn

@geindex PyDateTime_DATE_GET_FOLD (C function)
@anchor{c-api/datetime c PyDateTime_DATE_GET_FOLD}@anchor{5501}
@deffn {C の関数} int PyDateTime_DATE_GET_FOLD (PyDateTime_DateTime *o)

フォールド(訳注: サマータイムによる時間のずれのこと)を 0 から 1 までの整数で返します。


Added in version 3.6.

@end deffn

@geindex PyDateTime_DATE_GET_TZINFO (C function)
@anchor{c-api/datetime c PyDateTime_DATE_GET_TZINFO}@anchor{a95}
@deffn {C の関数} @ref{5df,,PyObject} *PyDateTime_DATE_GET_TZINFO (PyDateTime_DateTime *o)

Return the tzinfo (which may be @code{None}).


Added in version 3.10.

@end deffn

以下のマクロは time オブジェクトからフィールド値を取り出すためのものです。引数は @ref{54e3,,PyDateTime_Time} またはそのサブクラスのインスタンスでなければなりません。引数を @code{NULL} にしてはならず、型チェックは行いません:

@geindex PyDateTime_TIME_GET_HOUR (C function)
@anchor{c-api/datetime c PyDateTime_TIME_GET_HOUR}@anchor{5502}
@deffn {C の関数} int PyDateTime_TIME_GET_HOUR (PyDateTime_Time *o)

時を 0 から 23 の間の整数で返します。
@end deffn

@geindex PyDateTime_TIME_GET_MINUTE (C function)
@anchor{c-api/datetime c PyDateTime_TIME_GET_MINUTE}@anchor{5503}
@deffn {C の関数} int PyDateTime_TIME_GET_MINUTE (PyDateTime_Time *o)

分を 0 から 59 の間の整数で返します。
@end deffn

@geindex PyDateTime_TIME_GET_SECOND (C function)
@anchor{c-api/datetime c PyDateTime_TIME_GET_SECOND}@anchor{5504}
@deffn {C の関数} int PyDateTime_TIME_GET_SECOND (PyDateTime_Time *o)

秒を 0 から 59 の間の整数で返します。
@end deffn

@geindex PyDateTime_TIME_GET_MICROSECOND (C function)
@anchor{c-api/datetime c PyDateTime_TIME_GET_MICROSECOND}@anchor{5505}
@deffn {C の関数} int PyDateTime_TIME_GET_MICROSECOND (PyDateTime_Time *o)

マイクロ秒を 0 から 999999 の間の整数で返します。
@end deffn

@geindex PyDateTime_TIME_GET_FOLD (C function)
@anchor{c-api/datetime c PyDateTime_TIME_GET_FOLD}@anchor{5506}
@deffn {C の関数} int PyDateTime_TIME_GET_FOLD (PyDateTime_Time *o)

フォールド(訳注: サマータイムによる時間のずれのこと)を 0 から 1 までの整数で返します。


Added in version 3.6.

@end deffn

@geindex PyDateTime_TIME_GET_TZINFO (C function)
@anchor{c-api/datetime c PyDateTime_TIME_GET_TZINFO}@anchor{a96}
@deffn {C の関数} @ref{5df,,PyObject} *PyDateTime_TIME_GET_TZINFO (PyDateTime_Time *o)

Return the tzinfo (which may be @code{None}).


Added in version 3.10.

@end deffn

以下のマクロは time delta オブジェクトからフィールド値をとりだすためのものです。引数は @ref{54e4,,PyDateTime_Delta} かそのサブクラスのインスタンスでなければなりません。引数を @code{NULL} にしてはならず、型チェックは行いません:

@geindex PyDateTime_DELTA_GET_DAYS (C function)
@anchor{c-api/datetime c PyDateTime_DELTA_GET_DAYS}@anchor{5507}
@deffn {C の関数} int PyDateTime_DELTA_GET_DAYS (PyDateTime_Delta *o)

日数を -999999999 から 999999999 の間の整数で返します。


Added in version 3.3.

@end deffn

@geindex PyDateTime_DELTA_GET_SECONDS (C function)
@anchor{c-api/datetime c PyDateTime_DELTA_GET_SECONDS}@anchor{5508}
@deffn {C の関数} int PyDateTime_DELTA_GET_SECONDS (PyDateTime_Delta *o)

秒数を 0 から 86399 の間の整数で返します。


Added in version 3.3.

@end deffn

@geindex PyDateTime_DELTA_GET_MICROSECONDS (C function)
@anchor{c-api/datetime c PyDateTime_DELTA_GET_MICROSECONDS}@anchor{5509}
@deffn {C の関数} int PyDateTime_DELTA_GET_MICROSECONDS (PyDateTime_Delta *o)

マイクロ秒を 0 から 999999 の間の整数で返します。


Added in version 3.3.

@end deffn

以下のマクロは DB API を実装する上での便宜用です:

@geindex PyDateTime_FromTimestamp (C function)
@anchor{c-api/datetime c PyDateTime_FromTimestamp}@anchor{550a}
@deffn {C の関数} @ref{5df,,PyObject} *PyDateTime_FromTimestamp (PyObject *args)
`戻り値: 新しい参照。'
Create and return a new @ref{4e2,,datetime.datetime} object given an argument
tuple suitable for passing to @ref{712,,datetime.datetime.fromtimestamp()}.
@end deffn

@geindex PyDate_FromTimestamp (C function)
@anchor{c-api/datetime c PyDate_FromTimestamp}@anchor{1df1}
@deffn {C の関数} @ref{5df,,PyObject} *PyDate_FromTimestamp (PyObject *args)
`戻り値: 新しい参照。'
Create and return a new @ref{1fa,,datetime.date} object given an argument
tuple suitable for passing to @ref{dcd,,datetime.date.fromtimestamp()}.
@end deffn

@node Internal data<2>,,DateTime オブジェクト<2>,C API for extension modules
@anchor{c-api/datetime internal-data}@anchor{550b}
@subsubsection Internal data


The following symbols are exposed by the C API but should be considered
internal-only.

@geindex PyDateTime_CAPSULE_NAME (C macro)
@anchor{c-api/datetime c PyDateTime_CAPSULE_NAME}@anchor{550c}
@deffn {C のマクロ} PyDateTime_CAPSULE_NAME

Name of the datetime capsule to pass to @ref{1c10,,PyCapsule_Import()}.

Internal usage only. Use @ref{54de,,PyDateTime_IMPORT} instead.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 初期化 initialization 、終了処理 finalization 、スレッド,Python 初期化設定,具象オブジェクト concrete object レイヤ,Python/C API リファレンスマニュアル
@anchor{c-api/init doc}@anchor{550d}@anchor{c-api/init initialization}@anchor{550e}@anchor{c-api/init initialization-finalization-and-threads}@anchor{550f}@anchor{c-api/init translation-repo}@anchor{5510}
@section 初期化 (initialization)、終了処理 (finalization)、スレッド


See @ref{646,,Python Initialization Configuration} for details
on how to configure the interpreter prior to initialization.

@menu
* Python 初期化以前:: 
* グローバルな設定変数:: 
* インタープリタの初期化と終了処理:: 
* プロセスワイドのパラメータ:: 
* スレッド状態 (thread state) とグローバルインタプリタロック (global interpreter lock): スレッド状態 thread state とグローバルインタプリタロック global interpreter lock. 
* サブインタプリタサポート:: 
* 非同期通知:: 
* プロファイルとトレース (profiling and tracing): プロファイルとトレース profiling and tracing. 
* Reference tracing:: 
* 高度なデバッガサポート (advanced debugger support): 高度なデバッガサポート advanced debugger support. 
* スレッドローカルストレージのサポート:: 
* 同期プリミティブ: 同期プリミティブ<3>. 
* Operating System Thread APIs:: 

@end menu

@node Python 初期化以前,グローバルな設定変数,,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init before-python-initialization}@anchor{5511}@anchor{c-api/init pre-init-safe}@anchor{dbe}
@subsection Python 初期化以前


Python が埋め込まれているアプリケーションでは、他の Python/C API 関数を使う前に @ref{460,,Py_Initialize()} 関数を呼ばなければなりません。これには例外として、いくつかの関数と @ref{5512,,グローバルな設定変数} があります。

次の関数は Python の初期化の前でも安全に呼び出せます:


@itemize *

@item 
Functions that initialize the interpreter:


@itemize *

@item 
@ref{460,,Py_Initialize()}

@item 
@ref{5133,,Py_InitializeEx()}

@item 
@ref{3f6,,Py_InitializeFromConfig()}

@item 
@ref{bb8,,Py_BytesMain()}

@item 
@ref{e1e,,Py_Main()}

@item 
the runtime pre-initialization functions covered in @ref{646,,Python 初期化設定}
@end itemize

@item 
設定関数:


@itemize *

@item 
@ref{1b1c,,PyImport_AppendInittab()}

@item 
@ref{1b1d,,PyImport_ExtendInittab()}

@item 
@code{PyInitFrozenExtensions()}

@item 
@ref{7a8,,PyMem_SetAllocator()}

@item 
@ref{e64,,PyMem_SetupDebugHooks()}

@item 
@ref{5513,,PyObject_SetArenaAllocator()}

@item 
@ref{19b6,,Py_SetProgramName()}

@item 
@ref{19b5,,Py_SetPythonHome()}

@item 
@ref{3f4,,PySys_ResetWarnOptions()}

@item 
the configuration functions covered in @ref{646,,Python 初期化設定}
@end itemize

@item 
情報取得の関数:


@itemize *

@item 
@ref{4f51,,Py_IsInitialized()}

@item 
@ref{5514,,PyMem_GetAllocator()}

@item 
@ref{5515,,PyObject_GetArenaAllocator()}

@item 
@ref{164b,,Py_GetBuildInfo()}

@item 
@ref{512d,,Py_GetCompiler()}

@item 
@ref{512e,,Py_GetCopyright()}

@item 
@ref{512f,,Py_GetPlatform()}

@item 
@ref{5131,,Py_GetVersion()}

@item 
@ref{4f51,,Py_IsInitialized()}
@end itemize

@item 
ユーティリティ:


@itemize *

@item 
@ref{dc0,,Py_DecodeLocale()}

@item 
the status reporting and utility functions covered in @ref{646,,Python 初期化設定}
@end itemize

@item 
メモリアロケータ:


@itemize *

@item 
@ref{631,,PyMem_RawMalloc()}

@item 
@ref{633,,PyMem_RawRealloc()}

@item 
@ref{632,,PyMem_RawCalloc()}

@item 
@ref{634,,PyMem_RawFree()}
@end itemize

@item 
Synchronization:


@itemize *

@item 
@ref{5d0,,PyMutex_Lock()}

@item 
@ref{5d1,,PyMutex_Unlock()}
@end itemize
@end itemize

@cartouche
@quotation 注釈 
Despite their apparent similarity to some of the functions listed above,
the following functions `should not be called' before the interpreter has
been initialized: @ref{dc1,,Py_EncodeLocale()}, @ref{3e3,,Py_GetPath()},
@ref{3e5,,Py_GetPrefix()}, @ref{3e9,,Py_GetExecPrefix()},
@ref{3ec,,Py_GetProgramFullPath()}, @ref{3ef,,Py_GetPythonHome()},
@ref{3ee,,Py_GetProgramName()}, @ref{19b9,,PyEval_InitThreads()}, and
@ref{bbc,,Py_RunMain()}.
@end quotation
@end cartouche

@node グローバルな設定変数,インタープリタの初期化と終了処理,Python 初期化以前,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init global-conf-vars}@anchor{5512}@anchor{c-api/init global-configuration-variables}@anchor{5516}
@subsection グローバルな設定変数


Python には、様々な機能やオプションを制御するグローバルな設定のための変数があります。
デフォルトでは、これらのフラグは @ref{211b,,コマンドラインオプション} で制御されます。

オプションでフラグがセットされると、フラグの値はそのオプションがセットされた回数になります。
例えば、 @code{-b} では @ref{406,,Py_BytesWarningFlag} が 1 に設定され、 @code{-bb} では @ref{406,,Py_BytesWarningFlag} が 2 に設定されます。

@geindex Py_BytesWarningFlag (C var)
@anchor{c-api/init c Py_BytesWarningFlag}@anchor{406}
@deffn {C 変数} int Py_BytesWarningFlag

This API is kept for backward compatibility: setting
@ref{407,,PyConfig.bytes_warning} should be used instead, see @ref{646,,Python Initialization Configuration}.

@ref{192,,bytes} または @ref{344,,bytearray} を @ref{169,,str} と比較した場合、または、 @ref{192,,bytes} を @ref{19b,,int} と比較した場合に警告を発生させます。
@code{2} 以上の値を設定している場合は、エラーを発生させます。

@ref{7f9,,-b} オプションで設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_DebugFlag (C var)
@anchor{c-api/init c Py_DebugFlag}@anchor{3f8}
@deffn {C 変数} int Py_DebugFlag

This API is kept for backward compatibility: setting
@ref{3f9,,PyConfig.parser_debug} should be used instead, see @ref{646,,Python Initialization Configuration}.

パーサーのデバッグ出力を有効にします。(専門家専用です。コンパイルオプションに依存します)。

@ref{2123,,-d} オプションと 
@geindex PYTHONDEBUG
@geindex 環境変数; PYTHONDEBUG
@ref{2124,,PYTHONDEBUG} 環境変数で設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_DontWriteBytecodeFlag (C var)
@anchor{c-api/init c Py_DontWriteBytecodeFlag}@anchor{40c}
@deffn {C 変数} int Py_DontWriteBytecodeFlag

This API is kept for backward compatibility: setting
@ref{40d,,PyConfig.write_bytecode} should be used instead, see @ref{646,,Python Initialization Configuration}.

非ゼロに設定した場合、Python はソースモジュールのインポート時に @code{.pyc} ファイルの作成を試みません。

@ref{15e6,,-B} オプションと 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@ref{15e7,,PYTHONDONTWRITEBYTECODE} 環境変数で設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_FrozenFlag (C var)
@anchor{c-api/init c Py_FrozenFlag}@anchor{408}
@deffn {C 変数} int Py_FrozenFlag

This API is kept for backward compatibility: setting
@ref{409,,PyConfig.pathconfig_warnings} should be used instead, see
@ref{646,,Python Initialization Configuration}.

@ref{3e3,,Py_GetPath()} の中でモジュール検索パスを割り出しているときのエラーメッセージを抑制します。

@code{_freeze_module} プログラムと @code{frozenmain} プログラムが使用する非公開フラグです。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_HashRandomizationFlag (C var)
@anchor{c-api/init c Py_HashRandomizationFlag}@anchor{412}
@deffn {C 変数} int Py_HashRandomizationFlag

This API is kept for backward compatibility: setting
@ref{414,,PyConfig.hash_seed} and @ref{413,,PyConfig.use_hash_seed} should
be used instead, see @ref{646,,Python Initialization Configuration}.

@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} 環境変数が空でない文字列に設定された場合に、 @code{1} が設定されます。

フラグがゼロでない場合、 
@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} 環境変数を読みシークレットハッシュシードを初期化します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_IgnoreEnvironmentFlag (C var)
@anchor{c-api/init c Py_IgnoreEnvironmentFlag}@anchor{40a}
@deffn {C 変数} int Py_IgnoreEnvironmentFlag

This API is kept for backward compatibility: setting
@ref{40b,,PyConfig.use_environment} should be used instead, see
@ref{646,,Python Initialization Configuration}.

Ignore all @code{PYTHON*} environment variables, e.g.
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} and 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME}, that might be set.

@ref{b56,,-E} オプションと @ref{b57,,-I} オプションで設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_InspectFlag (C var)
@anchor{c-api/init c Py_InspectFlag}@anchor{400}
@deffn {C 変数} int Py_InspectFlag

This API is kept for backward compatibility: setting
@ref{401,,PyConfig.inspect} should be used instead, see
@ref{646,,Python Initialization Configuration}.

最初の引数にスクリプトが指定されたときや @ref{1a8,,-c} オプションが利用された際に、 @ref{75f,,sys.stdin} がターミナルに出力されないときであっても、スクリプトかコマンドを実行した後にインタラクティブモードに入ります。

@ref{16f4,,-i} オプションと 
@geindex PYTHONINSPECT
@geindex 環境変数; PYTHONINSPECT
@ref{16f3,,PYTHONINSPECT} 環境変数で設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_InteractiveFlag (C var)
@anchor{c-api/init c Py_InteractiveFlag}@anchor{3fe}
@deffn {C 変数} int Py_InteractiveFlag

This API is kept for backward compatibility: setting
@ref{3ff,,PyConfig.interactive} should be used instead, see
@ref{646,,Python Initialization Configuration}.

@ref{16f4,,-i} オプションで設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_IsolatedFlag (C var)
@anchor{c-api/init c Py_IsolatedFlag}@anchor{415}
@deffn {C 変数} int Py_IsolatedFlag

This API is kept for backward compatibility: setting
@ref{416,,PyConfig.isolated} should be used instead, see
@ref{646,,Python Initialization Configuration}.

Python を隔離モードで実行します。
隔離モードでは @ref{3e4,,sys.path} はスクリプトのディレクトリやユーザのサイトパッケージのディレクトリを含みません。

@ref{b57,,-I} オプションで設定します。


Added in version 3.4.



Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_LegacyWindowsFSEncodingFlag (C var)
@anchor{c-api/init c Py_LegacyWindowsFSEncodingFlag}@anchor{417}
@deffn {C 変数} int Py_LegacyWindowsFSEncodingFlag

This API is kept for backward compatibility: setting
@ref{418,,PyPreConfig.legacy_windows_fs_encoding} should be used instead, see
@ref{646,,Python Initialization Configuration}.

If the flag is non-zero, use the @code{mbcs} encoding with @code{replace} error
handler, instead of the UTF-8 encoding with @code{surrogatepass} error handler,
for the @ref{75d,,filesystem encoding and error handler}.

@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} 環境変数が空でない文字列に設定された場合に、 @code{1} に設定されます。

より詳しくは 
@geindex Python Enhancement Proposals; PEP 529
PEP 529@footnote{https://peps.python.org/pep-0529/} を参照してください。

@ref{213f,,Availability}: Windows.


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_LegacyWindowsStdioFlag (C var)
@anchor{c-api/init c Py_LegacyWindowsStdioFlag}@anchor{419}
@deffn {C 変数} int Py_LegacyWindowsStdioFlag

This API is kept for backward compatibility: setting
@ref{41a,,PyConfig.legacy_windows_stdio} should be used instead, see
@ref{646,,Python Initialization Configuration}.

If the flag is non-zero, use @ref{1527,,io.FileIO} instead of
@code{io._WindowsConsoleIO} for @ref{df,,sys} standard streams.

@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 環境変数; PYTHONLEGACYWINDOWSSTDIO
@ref{e55,,PYTHONLEGACYWINDOWSSTDIO} 環境変数が空でない文字列に設定された場合に、 @code{1} に設定されます。

より詳しくは 
@geindex Python Enhancement Proposals; PEP 528
PEP 528@footnote{https://peps.python.org/pep-0528/} を参照してください。

@ref{213f,,Availability}: Windows.


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_NoSiteFlag (C var)
@anchor{c-api/init c Py_NoSiteFlag}@anchor{404}
@deffn {C 変数} int Py_NoSiteFlag

This API is kept for backward compatibility: setting
@ref{405,,PyConfig.site_import} should be used instead, see
@ref{646,,Python Initialization Configuration}.

@ref{cc,,site} モジュールの import と、そのモジュールが行なっていた site ごとの @ref{3e4,,sys.path} への操作を無効にします。後で @ref{cc,,site} を明示的に import しても、これらの操作は実行されません (実行したい場合は、 @ref{2127,,site.main()} を呼び出してください)。

@ref{13c0,,-S} オプションで設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_NoUserSiteDirectory (C var)
@anchor{c-api/init c Py_NoUserSiteDirectory}@anchor{40e}
@deffn {C 変数} int Py_NoUserSiteDirectory

This API is kept for backward compatibility: setting
@ref{40f,,PyConfig.user_site_directory} should be used instead, see
@ref{646,,Python Initialization Configuration}.

@ref{2126,,ユーザのサイトパッケージのディレクトリ} を @ref{3e4,,sys.path} に追加しません。

@ref{15a6,,-s} オプション、 @ref{b57,,-I} 、 
@geindex PYTHONNOUSERSITE
@geindex 環境変数; PYTHONNOUSERSITE
@ref{15a7,,PYTHONNOUSERSITE} 環境変数で設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_OptimizeFlag (C var)
@anchor{c-api/init c Py_OptimizeFlag}@anchor{402}
@deffn {C 変数} int Py_OptimizeFlag

This API is kept for backward compatibility: setting
@ref{403,,PyConfig.optimization_level} should be used instead, see
@ref{646,,Python Initialization Configuration}.

@ref{18c,,-O} オプションと 
@geindex PYTHONOPTIMIZE
@geindex 環境変数; PYTHONOPTIMIZE
@ref{2125,,PYTHONOPTIMIZE} 環境変数で設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_QuietFlag (C var)
@anchor{c-api/init c Py_QuietFlag}@anchor{3fc}
@deffn {C 変数} int Py_QuietFlag

This API is kept for backward compatibility: setting
@ref{3fd,,PyConfig.quiet} should be used instead, see @ref{646,,Python Initialization Configuration}.

インタラクティブモードでも copyright とバージョンのメッセージを表示しません。

@ref{177e,,-q} オプションで設定します。


Added in version 3.2.



Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_UnbufferedStdioFlag (C var)
@anchor{c-api/init c Py_UnbufferedStdioFlag}@anchor{410}
@deffn {C 変数} int Py_UnbufferedStdioFlag

This API is kept for backward compatibility: setting
@ref{411,,PyConfig.buffered_stdio} should be used instead, see @ref{646,,Python Initialization Configuration}.

標準出力と標準エラーをバッファリングしないように強制します。

@ref{1d8d,,-u} オプションと 
@geindex PYTHONUNBUFFERED
@geindex 環境変数; PYTHONUNBUFFERED
@ref{1d8e,,PYTHONUNBUFFERED} 環境変数で設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@geindex Py_VerboseFlag (C var)
@anchor{c-api/init c Py_VerboseFlag}@anchor{3fa}
@deffn {C 変数} int Py_VerboseFlag

This API is kept for backward compatibility: setting
@ref{3fb,,PyConfig.verbose} should be used instead, see @ref{646,,Python Initialization Configuration}.

モジュールが初期化されるたびにメッセージを出力し、それがどこ (ファイル名やビルトインモジュール) からロードされたのかを表示します。
値が 2 以上の場合は、モジュールを検索するときにチェックしたファイルごとにメッセージを出力します。また、終了時のモジュールクリーンアップに関する情報も提供します。

@ref{163e,,-v} オプションと 
@geindex PYTHONVERBOSE
@geindex 環境変数; PYTHONVERBOSE
@ref{2128,,PYTHONVERBOSE} 環境変数で設定します。


Deprecated since version 3.12, will be removed in version 3.15.

@end deffn

@node インタープリタの初期化と終了処理,プロセスワイドのパラメータ,グローバルな設定変数,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init initializing-and-finalizing-the-interpreter}@anchor{5517}
@subsection インタープリタの初期化と終了処理


@geindex Py_Initialize (C function)
@anchor{c-api/init c Py_Initialize}@anchor{460}
@deffn {C の関数} void Py_Initialize ()
` 次に属します: @ref{775,,Stable ABI}.'
@geindex PyEval_InitThreads()
@geindex modules (in module sys)
@geindex path (sys モジュール)
@geindex module;builtins
@geindex module;__main__
@geindex module;sys
@geindex module;検索;パス
@geindex Py_FinalizeEx (C function)

Python インタープリタを初期化します。
Python の埋め込みを行うアプリケーションでは、他のあらゆる Python/C API を使用するよりも前にこの関数を呼び出さなければなりません。いくつかの例外については @ref{dbe,,Python 初期化以前} を参照してください。

This initializes the table of loaded modules (@code{sys.modules}), and creates
the fundamental modules @ref{13,,builtins}, @ref{1,,__main__} and @ref{df,,sys}.
It also initializes the module search path (@code{sys.path}). It does not set
@code{sys.argv}; use the @ref{646,,Python Initialization Configuration}
API for that. This is a no-op when called for a second time (without calling
@ref{f11,,Py_FinalizeEx()} first).  There is no return value; it is a fatal
error if the initialization fails.

Use @ref{3f6,,Py_InitializeFromConfig()} to customize the
@ref{646,,Python Initialization Configuration}.

@cartouche
@quotation 注釈 
Windows では @code{O_TEXT} から @code{O_BINARY} へコンソールモードが変更されますが、これはその C ランタイムを使っているコンソールでの Python 以外の使い勝手にも影響を及ぼします。
@end quotation
@end cartouche
@end deffn

@geindex Py_InitializeEx (C function)
@anchor{c-api/init c Py_InitializeEx}@anchor{5133}
@deffn {C の関数} void Py_InitializeEx (int initsigs)
` 次に属します: @ref{775,,Stable ABI}.'
This function works like @ref{460,,Py_Initialize()} if `initsigs' is @code{1}. If
`initsigs' is @code{0}, it skips initialization registration of signal handlers,
which may be useful when CPython is embedded as part of a larger application.

Use @ref{3f6,,Py_InitializeFromConfig()} to customize the
@ref{646,,Python Initialization Configuration}.
@end deffn

@geindex Py_InitializeFromConfig (C function)
@anchor{c-api/init c Py_InitializeFromConfig}@anchor{3f6}
@deffn {C の関数} @ref{ba4,,PyStatus} Py_InitializeFromConfig (const PyConfig *config)

Initialize Python from `config' configuration, as described in
@ref{5518,,Initialization with PyConfig}.

See the @ref{646,,Python 初期化設定} section for details on pre-initializing the
interpreter, populating the runtime configuration structure, and querying
the returned status structure.
@end deffn

@geindex Py_IsInitialized (C function)
@anchor{c-api/init c Py_IsInitialized}@anchor{4f51}
@deffn {C の関数} int Py_IsInitialized ()
` 次に属します: @ref{775,,Stable ABI}.'
Python インタプリタが初期化済みであれば真(非ゼロ)を、さもなければ偽(ゼロ)を返します。@ref{f11,,Py_FinalizeEx()} を呼び出した後は、@ref{460,,Py_Initialize()} を再び呼び出すまで、この関数は偽を返します。
@end deffn

@geindex Py_IsFinalizing (C function)
@anchor{c-api/init c Py_IsFinalizing}@anchor{5fd}
@deffn {C の関数} int Py_IsFinalizing ()
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Return true (non-zero) if the main Python interpreter is
@ref{479,,shutting down}. Return false (zero) otherwise.


Added in version 3.13.

@end deffn

@geindex Py_FinalizeEx (C function)
@anchor{c-api/init c Py_FinalizeEx}@anchor{f11}
@deffn {C の関数} int Py_FinalizeEx ()
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.6 より).'
Undo all initializations made by @ref{460,,Py_Initialize()} and subsequent use of
Python/C API functions, and destroy all sub-interpreters (see
@ref{1b31,,Py_NewInterpreter()} below) that were created and not yet destroyed since
the last call to @ref{460,,Py_Initialize()}.  This is a no-op when called for a second
time (without calling @ref{460,,Py_Initialize()} again first).

Since this is the reverse of @ref{460,,Py_Initialize()}, it should be called
in the same thread with the same interpreter active.  That means
the main thread and the main interpreter.
This should never be called while @ref{bbc,,Py_RunMain()} is running.

Normally the return value is @code{0}.
If there were errors during finalization (flushing buffered data),
@code{-1} is returned.

Note that Python will do a best effort at freeing all memory allocated by the Python
interpreter.  Therefore, any C-Extension should make sure to correctly clean up all
of the previously allocated PyObjects before using them in subsequent calls to
@ref{460,,Py_Initialize()}.  Otherwise it could introduce vulnerabilities and incorrect
behavior.

この関数が提供されている理由はいくつかあります。Python の埋め込みを行っているアプリケーションでは、アプリケーションを再起動することなく Python を再起動したいことがあります。また、動的ロード可能イブラリ (あるいは DLL) から Python インタプリタをロードするアプリケーションでは、DLL をアンロードする前に Python が確保したメモリを全て解放したいと考えるかもしれません。アプリケーション内で起きているメモリリークを追跡する際に、開発者は Python が確保したメモリをアプリケーションの終了前に解放させたいと思う場合もあります。

`Bugs and caveats:' The destruction of modules and objects in modules is done
in random order; this may cause destructors (@ref{11ff,,__del__()} methods) to fail
when they depend on other objects (even functions) or modules.  Dynamically
loaded extension modules loaded by Python are not unloaded.  Small amounts of
memory allocated by the Python interpreter may not be freed (if you find a leak,
please report it).  Memory tied up in circular references between objects is not
freed.  Interned strings will all be deallocated regardless of their reference count.
Some memory allocated by extension modules may not be freed.  Some extensions may not
work properly if their initialization routine is called more than once; this can
happen if an application calls @ref{460,,Py_Initialize()} and @ref{f11,,Py_FinalizeEx()}
more than once.  @ref{f11,,Py_FinalizeEx()} must not be called recursively from
within itself.  Therefore, it must not be called by any code that may be run
as part of the interpreter shutdown process, such as @ref{d,,atexit}
handlers, object finalizers, or any code that may be run while flushing the
stdout and stderr files.

引数無しで @ref{1c6e,,監査イベント} @code{cpython._PySys_ClearAuditHooks} を送出します。


Added in version 3.6.

@end deffn

@geindex Py_Finalize (C function)
@anchor{c-api/init c Py_Finalize}@anchor{45f}
@deffn {C の関数} void Py_Finalize ()
` 次に属します: @ref{775,,Stable ABI}.'
この関数は @ref{f11,,Py_FinalizeEx()} の後方互換性バージョンで、戻り値がありません。
@end deffn

@geindex Py_BytesMain (C function)
@anchor{c-api/init c Py_BytesMain}@anchor{bb8}
@deffn {C の関数} int Py_BytesMain (int argc, char **argv)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
Similar to @ref{e1e,,Py_Main()} but `argv' is an array of bytes strings,
allowing the calling application to delegate the text decoding step to
the CPython runtime.


Added in version 3.8.

@end deffn

@geindex Py_Main (C function)
@anchor{c-api/init c Py_Main}@anchor{e1e}
@deffn {C の関数} int Py_Main (int argc, wchar_t **argv)
` 次に属します: @ref{775,,Stable ABI}.'
The main program for the standard interpreter, encapsulating a full
initialization/finalization cycle, as well as additional
behaviour to implement reading configurations settings from the environment
and command line, and then executing @code{__main__} in accordance with
@ref{1209,,コマンドライン}.

This is made available for programs which wish to support the full CPython
command line interface, rather than just embedding a Python runtime in a
larger application.

The `argc' and `argv' parameters are similar to those which are passed to a
C program's @code{main()} function, except that the `argv' entries are first
converted to @code{wchar_t} using @ref{dc0,,Py_DecodeLocale()}. It is also
important to note that the argument list entries may be modified to point to
strings other than those passed in (however, the contents of the strings
pointed to by the argument list are not modified).

The return value is @code{2} if the argument list does not represent a valid
Python command line, and otherwise the same as @ref{bbc,,Py_RunMain()}.

In terms of the CPython runtime configuration APIs documented in the
@ref{646,,runtime configuration} section (and without accounting
for error handling), @code{Py_Main} is approximately equivalent to:

@example
PyConfig config;
PyConfig_InitPythonConfig(&config);
PyConfig_SetArgv(&config, argc, argv);
Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);

Py_RunMain();
@end example

In normal usage, an embedding application will call this function
`instead' of calling @ref{460,,Py_Initialize()}, @ref{5133,,Py_InitializeEx()} or
@ref{3f6,,Py_InitializeFromConfig()} directly, and all settings will be applied
as described elsewhere in this documentation. If this function is instead
called `after' a preceding runtime initialization API call, then exactly
which environmental and command line configuration settings will be updated
is version dependent (as it depends on which settings correctly support
being modified after they have already been set once when the runtime was
first initialized).
@end deffn

@geindex Py_RunMain (C function)
@anchor{c-api/init c Py_RunMain}@anchor{bbc}
@deffn {C の関数} int Py_RunMain (void)

Executes the main module in a fully configured CPython runtime.

Executes the command (@ref{5519,,PyConfig.run_command}), the script
(@ref{551a,,PyConfig.run_filename}) or the module
(@ref{551b,,PyConfig.run_module}) specified on the command line or in the
configuration. If none of these values are set, runs the interactive Python
prompt (REPL) using the @code{__main__} module's global namespace.

If @ref{401,,PyConfig.inspect} is not set (the default), the return value
will be @code{0} if the interpreter exits normally (that is, without raising
an exception), the exit status of an unhandled @ref{f3c,,SystemExit}, or @code{1}
for any other unhandled exception.

If @ref{401,,PyConfig.inspect} is set (such as when the @ref{16f4,,-i} option
is used), rather than returning when the interpreter exits, execution will
instead resume in an interactive Python prompt (REPL) using the @code{__main__}
module's global namespace. If the interpreter exited with an exception, it
is immediately raised in the REPL session. The function return value is
then determined by the way the `REPL session' terminates: @code{0}, @code{1}, or
the status of a @ref{f3c,,SystemExit}, as specified above.

This function always finalizes the Python interpreter before it returns.

See @ref{551c,,Python Configuration} for an example of a
customized Python that always runs in isolated mode using
@ref{bbc,,Py_RunMain()}.
@end deffn

@geindex PyUnstable_AtExit (C function)
@anchor{c-api/init c PyUnstable_AtExit}@anchor{18fa}
@deffn {C の関数} int PyUnstable_AtExit (PyInterpreterState *interp, void (*func)(void*), void *data)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Register an @ref{d,,atexit} callback for the target interpreter `interp'.
This is similar to @ref{5128,,Py_AtExit()}, but takes an explicit interpreter and
data pointer for the callback.

There must be an @ref{4ed1,,attached thread state} for `interp'.


Added in version 3.13.

@end deffn

@node プロセスワイドのパラメータ,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock,インタープリタの初期化と終了処理,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init process-wide-parameters}@anchor{551d}
@subsection プロセスワイドのパラメータ


@geindex Py_SetProgramName (C function)
@anchor{c-api/init c Py_SetProgramName}@anchor{19b6}
@deffn {C の関数} void Py_SetProgramName (const wchar_t *name)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex Py_Initialize()
@geindex main()
@geindex Py_GetPath()

This API is kept for backward compatibility: setting
@ref{3f2,,PyConfig.program_name} should be used instead, see @ref{646,,Python Initialization Configuration}.

この関数を呼び出すなら、最初に @ref{460,,Py_Initialize()} を呼び出すよりも前に呼び出さなければなりません。この関数はインタプリタにプログラムの @code{main()} 関数に指定した @code{argv[0]} 引数の値を教えます (ワイドキャラクタに変換されます)。この引数値は、 @ref{3e3,,Py_GetPath()} や、以下に示すその他の関数が、インタプリタの実行可能形式から Python ランタイムライブラリへの相対パスを取得するために使われます。デフォルトの値は @code{'python'} です。引数はゼロ終端されたワイドキャラクタ文字列で、静的な記憶領域に入っていなければならず、その内容はプログラムの実行中に変更してはなりません。 Python インタプリタ内のコードで、この記憶領域の内容を変更するものは一切ありません。

Use @ref{dc0,,Py_DecodeLocale()} to decode a bytes string to get a
wchar_t* string.


Deprecated since version 3.11, will be removed in version 3.15.

@end deffn

@geindex Py_GetProgramName (C function)
@anchor{c-api/init c Py_GetProgramName}@anchor{3ee}
@deffn {C の関数} wchar_t *Py_GetProgramName ()
` 次に属します: @ref{775,,Stable ABI}.'
Return the program name set with @ref{3f2,,PyConfig.program_name}, or the default.
The returned string points into static storage; the caller should not modify its
value.

This function should not be called before @ref{460,,Py_Initialize()}, otherwise
it returns @code{NULL}.


バージョン 3.10 で変更: It now returns @code{NULL} if called before @ref{460,,Py_Initialize()}.



Deprecated since version 3.13, will be removed in version 3.15: Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@end deffn

@geindex Py_GetPrefix (C function)
@anchor{c-api/init c Py_GetPrefix}@anchor{3e5}
@deffn {C の関数} wchar_t *Py_GetPrefix ()
` 次に属します: @ref{775,,Stable ABI}.'
Return the `prefix' for installed platform-independent files. This is derived
through a number of complicated rules from the program name set with
@ref{3f2,,PyConfig.program_name} and some environment variables; for example, if the
program name is @code{'/usr/local/bin/python'}, the prefix is @code{'/usr/local'}. The
returned string points into static storage; the caller should not modify its
value.  This corresponds to the @code{prefix} variable in the top-level
@code{Makefile} and the @ref{214f,,--prefix} argument to the @code{configure}
script at build time.  The value is available to Python code as @code{sys.base_prefix}.
It is only useful on Unix.  See also the next function.

This function should not be called before @ref{460,,Py_Initialize()}, otherwise
it returns @code{NULL}.


バージョン 3.10 で変更: It now returns @code{NULL} if called before @ref{460,,Py_Initialize()}.



Deprecated since version 3.13, will be removed in version 3.15: Use @ref{37c,,PyConfig_Get("base_prefix")}
(@ref{3e6,,sys.base_prefix}) instead. Use @ref{37c,,PyConfig_Get("prefix")} (@ref{3e7,,sys.prefix}) if @ref{3e8,,virtual environments} need to be handled.

@end deffn

@geindex Py_GetExecPrefix (C function)
@anchor{c-api/init c Py_GetExecPrefix}@anchor{3e9}
@deffn {C の関数} wchar_t *Py_GetExecPrefix ()
` 次に属します: @ref{775,,Stable ABI}.'
Return the `exec-prefix' for installed platform-`dependent' files.  This is
derived through a number of complicated rules from the program name set with
@ref{3f2,,PyConfig.program_name} and some environment variables; for example, if the
program name is @code{'/usr/local/bin/python'}, the exec-prefix is
@code{'/usr/local'}.  The returned string points into static storage; the caller
should not modify its value.  This corresponds to the @code{exec_prefix}
variable in the top-level @code{Makefile} and the @code{--exec-prefix}
argument to the @code{configure} script at build  time.  The value is
available to Python code as @code{sys.base_exec_prefix}.  It is only useful on
Unix.

背景: プラットフォーム依存のファイル (実行形式や共有ライブラリ) が別のディレクトリツリー内にインストールされている場合、 exec-prefix は prefix と異なります。典型的なインストール形態では、プラットフォーム非依存のファイルが @code{/usr/local} に収められる一方、プラットフォーム依存のファイルは @code{/usr/local/plat} サブツリーに収められます。

一般的に、プラットフォームとは、ハードウェアとソフトウェアファミリの組み合わせを指します。例えば、Solaris 2.x を動作させている Sparc マシンは全て同じプラットフォームであるとみなしますが、Solaris 2.x を動作させている Intel マシンは違うプラットフォームになりますし、同じ Intel マシンでも Linux を動作させているならまた別のプラットフォームです。一般的には、同じオペレーティングシステムでも、メジャーリビジョンの違うものは異なるプラットフォームです。非 Unix のオペレーティングシステムの場合は話はまた別です; 非 Unix のシステムでは、インストール方法はとても異なっていて、prefix や exec-prefix には意味がなく、空文字列が設定されています。コンパイル済みの Python バイトコードはプラットフォームに依存しないので注意してください (ただし、どのバージョンの Python でコンパイルされたかには依存します!)。

システム管理者は、 @code{mount} や @code{automount} プログラムを使って、各プラットフォーム用の @code{/usr/local/plat} を異なったファイルシステムに置き、プラットフォーム間で @code{/usr/local} を共有するための設定方法を知っているでしょう。

This function should not be called before @ref{460,,Py_Initialize()}, otherwise
it returns @code{NULL}.


バージョン 3.10 で変更: It now returns @code{NULL} if called before @ref{460,,Py_Initialize()}.



Deprecated since version 3.13, will be removed in version 3.15: Use @ref{37c,,PyConfig_Get("base_exec_prefix")}
(@ref{3ea,,sys.base_exec_prefix}) instead. Use
@ref{37c,,PyConfig_Get("exec_prefix")}
(@ref{3eb,,sys.exec_prefix}) if @ref{3e8,,virtual environments} need
to be handled.

@end deffn

@geindex Py_GetProgramFullPath (C function)
@anchor{c-api/init c Py_GetProgramFullPath}@anchor{3ec}
@deffn {C の関数} wchar_t *Py_GetProgramFullPath ()
` 次に属します: @ref{775,,Stable ABI}.'
@geindex executable (in module sys)

Return the full program name of the Python executable; this is  computed as a
side-effect of deriving the default module search path  from the program name
(set by @ref{3f2,,PyConfig.program_name}). The returned string points into
static storage; the caller should not modify its value.  The value is available
to Python code as @code{sys.executable}.

This function should not be called before @ref{460,,Py_Initialize()}, otherwise
it returns @code{NULL}.


バージョン 3.10 で変更: It now returns @code{NULL} if called before @ref{460,,Py_Initialize()}.



Deprecated since version 3.13, will be removed in version 3.15: Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@end deffn

@geindex Py_GetPath (C function)
@anchor{c-api/init c Py_GetPath}@anchor{3e3}
@deffn {C の関数} wchar_t *Py_GetPath ()
` 次に属します: @ref{775,,Stable ABI}.'
@geindex module;検索;パス
@geindex path (sys モジュール)

Return the default module search path; this is computed from the program name
(set by @ref{3f2,,PyConfig.program_name}) and some environment variables.
The returned string consists of a series of directory names separated by a
platform dependent delimiter character.  The delimiter character is @code{':'}
on Unix and macOS, @code{';'} on Windows.  The returned string points into
static storage; the caller should not modify its value.  The list
@ref{3e4,,sys.path} is initialized with this value on interpreter startup; it
can be (and usually is) modified later to change the search path for loading
modules.

This function should not be called before @ref{460,,Py_Initialize()}, otherwise
it returns @code{NULL}.

@c XXX should give the exact rules


バージョン 3.10 で変更: It now returns @code{NULL} if called before @ref{460,,Py_Initialize()}.



Deprecated since version 3.13, will be removed in version 3.15: Use @ref{37c,,PyConfig_Get("module_search_paths")}
(@ref{3e4,,sys.path}) instead.

@end deffn

@geindex Py_GetVersion (C function)
@anchor{c-api/init c Py_GetVersion}@anchor{5131}
@deffn {C の関数} const char *Py_GetVersion ()
` 次に属します: @ref{775,,Stable ABI}.'
Python インタプリタのバージョンを返します。バージョンは、次のような形式の文字列です

@example
"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
@end example

@geindex version (in module sys)

第一ワード (最初のスペース文字まで) は、現在の Python のバージョンです; 最初の文字は、ピリオドで区切られたメジャーバージョンとマイナーバージョンです。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは @ref{49c,,sys.version} として利用できます。

See also the @ref{381,,Py_Version} constant.
@end deffn

@geindex Py_GetPlatform (C function)
@anchor{c-api/init c Py_GetPlatform}@anchor{512f}
@deffn {C の関数} const char *Py_GetPlatform ()
` 次に属します: @ref{775,,Stable ABI}.'
@geindex platform (in module sys)

現在のプラットフォームのプラットフォーム識別文字列を返します。Unixでは、オペレーティングシステムの "公式の" 名前を小文字に変換し、後ろにメジャーリビジョン番号を付けた構成になっています。例えば Solaris 2.x は、SunOS 5.x, としても知られていますが、@code{'sunos5'} になります。macOS では @code{'darwin'} です。Windows では @code{'win'} です。関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは @code{sys.platform} として利用できます。
@end deffn

@geindex Py_GetCopyright (C function)
@anchor{c-api/init c Py_GetCopyright}@anchor{512e}
@deffn {C の関数} const char *Py_GetCopyright ()
` 次に属します: @ref{775,,Stable ABI}.'
現在の Python バージョンに対する公式の著作権表示文字列を返します。例えば

@code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}

@geindex copyright (in module sys)

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは @code{sys.copyright} として利用できます。
@end deffn

@geindex Py_GetCompiler (C function)
@anchor{c-api/init c Py_GetCompiler}@anchor{512d}
@deffn {C の関数} const char *Py_GetCompiler ()
` 次に属します: @ref{775,,Stable ABI}.'
現在使っているバージョンの Python をビルドする際に用いたコンパイラを示す文字列を、角括弧で囲った文字列を返します。例えば:

@example
"[GCC 2.7.2.2]"
@end example

@geindex version (in module sys)

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは @code{sys.version} の一部として取り出せます。
@end deffn

@geindex Py_GetBuildInfo (C function)
@anchor{c-api/init c Py_GetBuildInfo}@anchor{164b}
@deffn {C の関数} const char *Py_GetBuildInfo ()
` 次に属します: @ref{775,,Stable ABI}.'
現在使っている Python インタプリタインスタンスの、シーケンス番号とビルド日時に関する情報を返します。例えば

@example
"#67, Aug  1 1997, 22:34:28"
@end example

@geindex version (in module sys)

関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側はこの値を変更できません。この値は Python コードからは @code{sys.version} の一部として取り出せます。
@end deffn

@geindex PySys_SetArgvEx (C function)
@anchor{c-api/init c PySys_SetArgvEx}@anchor{19b7}
@deffn {C の関数} void PySys_SetArgvEx (int argc, wchar_t **argv, int updatepath)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex main()
@geindex Py_FatalError()
@geindex argv (in module sys)

This API is kept for backward compatibility: setting
@ref{3f1,,PyConfig.argv}, @ref{1cf1,,PyConfig.parse_argv} and
@ref{977,,PyConfig.safe_path} should be used instead, see @ref{646,,Python Initialization Configuration}.

`argc' および `argv' に基づいて @ref{147c,,sys.argv} を設定します。これらの引数はプログラムの @code{main()} に渡した引数に似ていますが、最初の要素が Python インタプリタの宿主となっている実行形式の名前ではなく、実行されるスクリプト名を参照しなければならない点が違います。実行するスクリプトがない場合、 `argv' の最初の要素は空文字列にしてもかまいません。この関数が @ref{147c,,sys.argv} の初期化に失敗した場合、致命的エラーを @ref{b7a,,Py_FatalError()} で知らせます。

`updatepath' が 0 の場合、ここまでの動作がこの関数がすることの全てです。 `updatepath' が 0 でない場合、この関数は @ref{3e4,,sys.path} を以下のアルゴリズムに基づいて修正します:


@itemize -

@item 
存在するスクリプトの名前が @code{argv[0]} に渡された場合、そのスクリプトがある場所の絶対パスを @ref{3e4,,sys.path} の先頭に追加します。

@item 
それ以外の場合 (`argc' が @code{0} だったり、 @code{argv[0]} が存在するファイル名を指していない場合)、 @ref{3e4,,sys.path} の先頭に空の文字列を追加します。
これは現在の作業ディレクトリ (@code{"."}) を先頭に追加するのと同じです。
@end itemize

Use @ref{dc0,,Py_DecodeLocale()} to decode a bytes string to get a
wchar_t* string.

See also @ref{a94,,PyConfig.orig_argv} and @ref{3f1,,PyConfig.argv}
members of the @ref{646,,Python Initialization Configuration}.

@cartouche
@quotation 注釈 
It is recommended that applications embedding the Python interpreter
for purposes other than executing a single script pass @code{0} as `updatepath',
and update @ref{3e4,,sys.path} themselves if desired.
See 
@geindex Common Vulnerabilities and Exposures; CVE 2008-5983
CVE 2008-5983@footnote{https://www.cve.org/CVERecord?id=CVE-2008-5983}.

3.1.3 より前のバージョンでは、 @ref{19b8,,PySys_SetArgv()} の呼び出しが完了した後に @ref{3e4,,sys.path} の先頭の要素を取り出すことで、同じ効果が得られます。例えばこのように使います:

@example
PyRun_SimpleString("import sys; sys.path.pop(0)\n");
@end example
@end quotation
@end cartouche


Added in version 3.1.3.


@c XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
@c check w/ Guido.


Deprecated since version 3.11, will be removed in version 3.15.

@end deffn

@geindex PySys_SetArgv (C function)
@anchor{c-api/init c PySys_SetArgv}@anchor{19b8}
@deffn {C の関数} void PySys_SetArgv (int argc, wchar_t **argv)
` 次に属します: @ref{775,,Stable ABI}.'
This API is kept for backward compatibility: setting
@ref{3f1,,PyConfig.argv} and @ref{1cf1,,PyConfig.parse_argv} should be used
instead, see @ref{646,,Python Initialization Configuration}.

この関数は、 @code{python} インタプリタが @ref{b57,,-I} オプション付きで実行されている場合を除き @ref{19b7,,PySys_SetArgvEx()} の `updatepath' に @code{1} を設定したのと同じように動作します。

Use @ref{dc0,,Py_DecodeLocale()} to decode a bytes string to get a
wchar_t* string.

See also @ref{a94,,PyConfig.orig_argv} and @ref{3f1,,PyConfig.argv}
members of the @ref{646,,Python Initialization Configuration}.


バージョン 3.4 で変更: `updatepath' の値は @ref{b57,,-I} オプションに依存します。



Deprecated since version 3.11, will be removed in version 3.15.

@end deffn

@geindex Py_SetPythonHome (C function)
@anchor{c-api/init c Py_SetPythonHome}@anchor{19b5}
@deffn {C の関数} void Py_SetPythonHome (const wchar_t *home)
` 次に属します: @ref{775,,Stable ABI}.'
This API is kept for backward compatibility: setting
@ref{3f3,,PyConfig.home} should be used instead, see @ref{646,,Python Initialization Configuration}.

Python の標準ライブラリがある、デフォルトの "home" ディレクトリを設定します。引数の文字列の意味については 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} を参照してください。

引数は静的なストレージに置かれてプログラム実行中に書き換えられないようなゼロ終端の文字列であるべきです。Python インタプリタはこのストレージの内容を変更しません。

Use @ref{dc0,,Py_DecodeLocale()} to decode a bytes string to get a
wchar_t* string.


Deprecated since version 3.11, will be removed in version 3.15.

@end deffn

@geindex Py_GetPythonHome (C function)
@anchor{c-api/init c Py_GetPythonHome}@anchor{3ef}
@deffn {C の関数} wchar_t *Py_GetPythonHome ()
` 次に属します: @ref{775,,Stable ABI}.'
Return the default "home", that is, the value set by
@ref{3f3,,PyConfig.home}, or the value of the 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME}
environment variable if it is set.

This function should not be called before @ref{460,,Py_Initialize()}, otherwise
it returns @code{NULL}.


バージョン 3.10 で変更: It now returns @code{NULL} if called before @ref{460,,Py_Initialize()}.



Deprecated since version 3.13, will be removed in version 3.15: Use @ref{37c,,PyConfig_Get("home")} or the
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable instead.

@end deffn

@node スレッド状態 thread state とグローバルインタプリタロック global interpreter lock,サブインタプリタサポート,プロセスワイドのパラメータ,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init thread-state-and-the-global-interpreter-lock}@anchor{551e}@anchor{c-api/init threads}@anchor{551f}
@subsection スレッド状態 (thread state) とグローバルインタプリタロック (global interpreter lock)


@geindex global interpreter lock
@geindex interpreter lock
@geindex lock@comma{} interpreter

Unless on a @ref{1f4,,free-threaded} build of @ref{905,,CPython},
the Python interpreter is not fully thread-safe.  In order to support
multi-threaded Python programs, there's a global lock, called the @ref{474,,global interpreter lock} or @ref{164,,GIL}, that must be held by the current thread before
it can safely access Python objects. Without the lock, even the simplest
operations could cause problems in a multi-threaded program: for example, when
two threads simultaneously increment the reference count of the same object, the
reference count could end up being incremented only once instead of twice.

@geindex setswitchinterval (in module sys)

このため、 @ref{164,,GIL} を獲得したスレッドだけが Python オブジェクトを操作したり、 Python/C API 関数を呼び出したりできるというルールがあります。並行処理をエミュレートするために、インタプリタは定期的にロックを解放したり獲得したりします。 (@ref{b44,,sys.setswitchinterval()} を参照) このロックはブロックが起こりうる I/O 操作の付近でも解放・獲得され、 I/O を要求するスレッドが I/O 操作の完了を待つ間、他のスレッドが動作できるようにしています。

@geindex PyThreadState (C type)

The Python interpreter keeps some thread-specific bookkeeping information
inside a data structure called @ref{990,,PyThreadState}, known as a @ref{1846,,thread state}.
Each OS thread has a thread-local pointer to a @ref{990,,PyThreadState}; a thread state
referenced by this pointer is considered to be @ref{4ed1,,attached}.

A thread can only have one @ref{4ed1,,attached thread state} at a time. An attached
thread state is typically analogous with holding the @ref{164,,GIL}, except on
@ref{1f4,,free-threaded} builds.  On builds with the @ref{164,,GIL} enabled,
@ref{4ed1,,attaching} a thread state will block until the @ref{164,,GIL}
can be acquired. However,  even on builds with the @ref{164,,GIL} disabled, it is still required
to have an attached thread state to call most of the C API.

In general, there will always be an @ref{4ed1,,attached thread state} when using Python's C API.
Only in some specific cases (such as in a @ref{4ebd,,Py_BEGIN_ALLOW_THREADS} block) will the
thread not have an attached thread state. If uncertain, check if @ref{423,,PyThreadState_GetUnchecked()} returns
@code{NULL}.

@menu
* Detaching the thread state from extension code:: 
* Python 以外で作られたスレッド:: 
* Supporting subinterpreters in non-Python threads:: 
* Cautions about fork(): Cautions about fork. 
* Cautions regarding runtime finalization:: 
* 高レベルAPI:: 
* 低レベルAPI:: 

@end menu

@node Detaching the thread state from extension code,Python 以外で作られたスレッド,,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock
@anchor{c-api/init detaching-the-thread-state-from-extension-code}@anchor{5520}
@subsubsection Detaching the thread state from extension code


Most extension code manipulating the @ref{1846,,thread state} has the following simple
structure:

@example
Save the thread state in a local variable.
... Do some blocking I/O operation ...
Restore the thread state from the local variable.
@end example

この構造は非常に一般的なので、作業を単純にするために2つのマクロが用意されています:

@example
Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS
@end example

@geindex Py_BEGIN_ALLOW_THREADS (C macro)
@geindex Py_END_ALLOW_THREADS (C macro)

@ref{4ebd,,Py_BEGIN_ALLOW_THREADS} マクロは新たなブロックを開始し、隠しローカル変数を宣言します; @ref{c7f,,Py_END_ALLOW_THREADS} はブロックを閉じます。

上のブロックは次のコードに展開されます:

@example
PyThreadState *_save;

_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);
@end example

@geindex PyEval_RestoreThread (C function)
@geindex PyEval_SaveThread (C function)

Here is how these functions work:

The @ref{4ed1,,attached thread state} holds the @ref{164,,GIL} for the entire interpreter. When detaching
the @ref{4ed1,,attached thread state}, the @ref{164,,GIL} is released, allowing other threads to attach
a thread state to their own thread, thus getting the @ref{164,,GIL} and can start executing.
The pointer to the prior @ref{4ed1,,attached thread state} is stored as a local variable.
Upon reaching @ref{c7f,,Py_END_ALLOW_THREADS}, the thread state that was
previously @ref{4ed1,,attached} is passed to @ref{648,,PyEval_RestoreThread()}.
This function will block until another releases its @ref{4ed1,,thread state},
thus allowing the old @ref{4ed1,,thread state} to get re-attached and the
C API can be called again.

For @ref{1f4,,free-threaded} builds, the @ref{164,,GIL} is normally
out of the question, but detaching the @ref{4ed1,,thread state} is still required
for blocking I/O and long operations. The difference is that threads don't have to wait for the @ref{164,,GIL}
to be released to attach their thread state, allowing true multi-core parallelism.

@cartouche
@quotation 注釈 
Calling system I/O functions is the most common use case for detaching
the @ref{4ed1,,thread state}, but it can also be useful before calling
long-running computations which don't need access to Python objects, such
as compression or cryptographic functions operating over memory buffers.
For example, the standard @ref{139,,zlib} and @ref{6c,,hashlib} modules detach the
@ref{4ed1,,thread state} when compressing or hashing data.
@end quotation
@end cartouche

@node Python 以外で作られたスレッド,Supporting subinterpreters in non-Python threads,Detaching the thread state from extension code,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock
@anchor{c-api/init gilstate}@anchor{5521}@anchor{c-api/init non-python-created-threads}@anchor{5522}
@subsubsection Python 以外で作られたスレッド


When threads are created using the dedicated Python APIs (such as the
@ref{f3,,threading} module), a thread state is automatically associated to them
and the code showed above is therefore correct.  However, when threads are
created from C (for example by a third-party library with its own thread
management), they don't hold the @ref{164,,GIL}, because they don't have an
@ref{4ed1,,attached thread state}.

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 an @ref{4ed1,,attached thread state} before you can start using the Python/C
API.  When you are done, you should detach the @ref{4ed1,,thread state}, and
finally free it.

@ref{64a,,PyGILState_Ensure()} と @ref{64b,,PyGILState_Release()} はこの処理を自動的に行います。 Cのスレッドから Python を呼び出す典型的な方法は以下のとおりです:

@example
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();

/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */

/* Release the thread. No Python API allowed beyond this point. */
PyGILState_Release(gstate);
@end example

Note that the @code{PyGILState_*} functions assume there is only one global
interpreter (created automatically by @ref{460,,Py_Initialize()}).  Python
supports the creation of additional interpreters (using
@ref{1b31,,Py_NewInterpreter()}), but mixing multiple interpreters and the
@code{PyGILState_*} API is unsupported. This is because @ref{64a,,PyGILState_Ensure()}
and similar functions default to @ref{4ed1,,attaching} a
@ref{1846,,thread state} for the main interpreter, meaning that the thread can't safely
interact with the calling subinterpreter.

@node Supporting subinterpreters in non-Python threads,Cautions about fork,Python 以外で作られたスレッド,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock
@anchor{c-api/init supporting-subinterpreters-in-non-python-threads}@anchor{5523}
@subsubsection Supporting subinterpreters in non-Python threads


If you would like to support subinterpreters with non-Python created threads, you
must use the @code{PyThreadState_*} API instead of the traditional @code{PyGILState_*}
API.

In particular, you must store the interpreter state from the calling
function and pass it to @ref{50c3,,PyThreadState_New()}, which will ensure that
the @ref{1846,,thread state} is targeting the correct interpreter:

@example
/* The return value of PyInterpreterState_Get() from the
   function that created this thread. */
PyInterpreterState *interp = ThreadData->interp;
PyThreadState *tstate = PyThreadState_New(interp);
PyThreadState_Swap(tstate);

/* GIL of the subinterpreter is now held.
   Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */

/* Destroy the thread state. No Python API allowed beyond this point. */
PyThreadState_Clear(tstate);
PyThreadState_DeleteCurrent();
@end example

@node Cautions about fork,Cautions regarding runtime finalization,Supporting subinterpreters in non-Python threads,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock
@anchor{c-api/init cautions-about-fork}@anchor{5524}@anchor{c-api/init fork-and-threads}@anchor{5220}
@subsubsection Cautions about fork()


Another important thing to note about threads is their behaviour in the face
of the C @code{fork()} call. On most systems with @code{fork()}, after a
process forks only the thread that issued the fork will exist.  This has a
concrete impact both on how locks must be handled and on all stored state
in CPython's runtime.

The fact that only the "current" thread remains
means any locks held by other threads will never be released. Python solves
this for @ref{4b5,,os.fork()} by acquiring the locks it uses internally before
the fork, and releasing them afterwards. In addition, it resets any
@ref{3623,,Lock objects} in the child. When extending or embedding Python, there
is no way to inform Python of additional (non-Python) locks that need to be
acquired before or reset after a fork. OS facilities such as
@code{pthread_atfork()} would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling @code{fork()}
directly rather than through @ref{4b5,,os.fork()} (and returning to or calling
into Python) may result in a deadlock by one of Python's internal locks
being held by a thread that is defunct after the fork.
@ref{430,,PyOS_AfterFork_Child()} tries to reset the necessary locks, but is not
always able to.

The fact that all other threads go away also means that CPython's
runtime state there must be cleaned up properly, which @ref{4b5,,os.fork()}
does.  This means finalizing all other @ref{990,,PyThreadState} objects
belonging to the current interpreter and all other
@ref{aba,,PyInterpreterState} objects.  Due to this and the special
nature of the @ref{163,,"main" interpreter},
@code{fork()} should only be called in that interpreter's "main"
thread, where the CPython global runtime was originally initialized.
The only exception is if @code{exec()} will be called immediately
after.

@node Cautions regarding runtime finalization,高レベルAPI,Cautions about fork,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock
@anchor{c-api/init cautions-regarding-runtime-finalization}@anchor{5525}@anchor{c-api/init id1}@anchor{5526}
@subsubsection Cautions regarding runtime finalization


In the late stage of @ref{479,,interpreter shutdown}, after attempting to wait for
non-daemon threads to exit (though this can be interrupted by
@ref{bc5,,KeyboardInterrupt}) and running the @ref{d,,atexit} functions, the runtime
is marked as `finalizing': @ref{5fd,,Py_IsFinalizing()} and
@ref{c80,,sys.is_finalizing()} return true.  At this point, only the `finalization
thread' that initiated finalization (typically the main thread) is allowed to
acquire the @ref{164,,GIL}.

If any thread, other than the finalization thread, attempts to attach a @ref{1846,,thread state}
during finalization, either explicitly or
implicitly, the thread enters `a permanently blocked state'
where it remains until the program exits.  In most cases this is harmless, but this can result
in deadlock if a later stage of finalization attempts to acquire a lock owned by the
blocked thread, or otherwise waits on the blocked thread.

Gross? Yes. This prevents random crashes and/or unexpectedly skipped C++
finalizations further up the call stack when such threads were forcibly exited
here in CPython 3.13 and earlier. The CPython runtime @ref{1846,,thread state} C APIs
have never had any error reporting or handling expectations at @ref{1846,,thread state}
attachment time that would've allowed for graceful exit from this situation. Changing that
would require new stable C APIs and rewriting the majority of C code in the
CPython ecosystem to use those with error handling.

@node 高レベルAPI,低レベルAPI,Cautions regarding runtime finalization,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock
@anchor{c-api/init high-level-api}@anchor{5527}
@subsubsection 高レベルAPI


C拡張を書いたりPythonインタプリタを埋め込むときに最も一般的に使われる型や関数は次のとおりです:

@geindex PyInterpreterState (C type)
@anchor{c-api/init c PyInterpreterState}@anchor{aba}
@deffn {C のデータ型} type PyInterpreterState
` 次に属します: @ref{775,,Limited API} (不透明な構造体として).'
このデータ構造体は、協調動作する多数のスレッド間で共有されている状態を表現します。同じインタプリタに属するスレッドはモジュール管理情報やその他いくつかの内部的な情報を共有しています。この構造体には公開 (public) のメンバはありません。

異なるインタプリタに属するスレッド間では、利用可能なメモリ、開かれているファイルデスクリプタなどといったプロセス状態を除いて、初期状態では何も共有されていません。GILもまた、スレッドがどのインタプリタに属しているかに関わらずすべてのスレッドで共有されています。


バージョン 3.12 で変更: 
@geindex Python Enhancement Proposals; PEP 684
PEP 684@footnote{https://peps.python.org/pep-0684/} introduced the possibility
of a @ref{5528,,per-interpreter GIL}.
See @ref{689,,Py_NewInterpreterFromConfig()}.

@end deffn

@geindex PyThreadState (C type)
@anchor{c-api/init c PyThreadState}@anchor{990}
@deffn {C のデータ型} type PyThreadState
` 次に属します: @ref{775,,Limited API} (不透明な構造体として).'
This data structure represents the state of a single thread.  The only public
data member is:

@geindex PyThreadState.interp (C member)
@anchor{c-api/init c PyThreadState interp}@anchor{5529}
@deffn {C のメンバ変数} @ref{aba,,PyInterpreterState} *interp

This thread's interpreter state.
@end deffn
@end deffn

@geindex PyEval_InitThreads (C function)
@anchor{c-api/init c PyEval_InitThreads}@anchor{19b9}
@deffn {C の関数} void PyEval_InitThreads ()
` 次に属します: @ref{775,,Stable ABI}.'
@geindex PyEval_AcquireThread()
@geindex PyEval_ReleaseThread()
@geindex PyEval_SaveThread()
@geindex PyEval_RestoreThread()

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 で変更: この関数は @ref{460,,Py_Initialize()} から呼び出されるようになり、わざわざ呼び出す必要はもう無くなりました。



バージョン 3.2 で変更: この関数は @ref{460,,Py_Initialize()} より前に呼び出すことができなくなりました。



バージョン 3.9 で非推奨.


@geindex module;_thread
@end deffn

@geindex PyEval_SaveThread (C function)
@anchor{c-api/init c PyEval_SaveThread}@anchor{647}
@deffn {C の関数} @ref{990,,PyThreadState} *PyEval_SaveThread ()
` 次に属します: @ref{775,,Stable ABI}.'
Detach the @ref{4ed1,,attached thread state} and return it.
The thread will have no @ref{1846,,thread state} upon returning.
@end deffn

@geindex PyEval_RestoreThread (C function)
@anchor{c-api/init c PyEval_RestoreThread}@anchor{648}
@deffn {C の関数} void PyEval_RestoreThread (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI}.'
Set the @ref{4ed1,,attached thread state} to `tstate'.
The passed @ref{1846,,thread state} `should not' be @ref{4ed1,,attached},
otherwise deadlock ensues. `tstate' will be attached upon returning.

@cartouche
@quotation 注釈 
Calling this function from a thread when the runtime is finalizing will
hang the thread until the program exits, even if the thread was not
created by Python.  Refer to
@ref{5525,,Cautions regarding runtime finalization} for more details.
@end quotation
@end cartouche


バージョン 3.14 で変更: Hangs the current thread, rather than terminating it, if called while the
interpreter is finalizing.

@end deffn

@geindex PyThreadState_Get (C function)
@anchor{c-api/init c PyThreadState_Get}@anchor{615}
@deffn {C の関数} @ref{990,,PyThreadState} *PyThreadState_Get ()
` 次に属します: @ref{775,,Stable ABI}.'
Return the @ref{4ed1,,attached thread state}. If the thread has no attached
thread state, (such as when inside of @ref{4ebd,,Py_BEGIN_ALLOW_THREADS}
block), then this issues a fatal error (so that the caller needn't check
for @code{NULL}).

See also @ref{423,,PyThreadState_GetUnchecked()}.
@end deffn

@geindex PyThreadState_GetUnchecked (C function)
@anchor{c-api/init c PyThreadState_GetUnchecked}@anchor{423}
@deffn {C の関数} @ref{990,,PyThreadState} *PyThreadState_GetUnchecked ()

Similar to @ref{615,,PyThreadState_Get()}, but don't kill the process with a
fatal error if it is NULL. The caller is responsible to check if the result
is NULL.


Added in version 3.13: In Python 3.5 to 3.12, the function was private and known as
@code{_PyThreadState_UncheckedGet()}.

@end deffn

@geindex PyThreadState_Swap (C function)
@anchor{c-api/init c PyThreadState_Swap}@anchor{50c4}
@deffn {C の関数} @ref{990,,PyThreadState} *PyThreadState_Swap (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI}.'
Set the @ref{4ed1,,attached thread state} to `tstate', and return the
@ref{1846,,thread state} that was attached prior to calling.

This function is safe to call without an @ref{4ed1,,attached thread state}; it
will simply return @code{NULL} indicating that there was no prior thread state.


@subsubheading 参考


@ref{4fde,,PyEval_ReleaseThread()}


@cartouche
@quotation 注釈 
Similar to @ref{64a,,PyGILState_Ensure()}, this function will hang the
thread if the runtime is finalizing.
@end quotation
@end cartouche
@end deffn

以下の関数はスレッドローカルストレージを利用していて、サブインタプリタとの互換性がありません:

@geindex PyGILState_STATE (C type)
@anchor{c-api/init c PyGILState_STATE}@anchor{502e}
@deffn {C のデータ型} type PyGILState_STATE
` 次に属します: @ref{775,,Stable ABI}.'
The type of the value returned by @ref{64a,,PyGILState_Ensure()} and passed to
@ref{64b,,PyGILState_Release()}.

@geindex PyGILState_STATE.PyGILState_LOCKED (C enumerator)
@anchor{c-api/init c PyGILState_STATE PyGILState_LOCKED}@anchor{552a}
@deffn {C Enumerator} enumerator PyGILState_LOCKED

The GIL was already held when @ref{64a,,PyGILState_Ensure()} was called.
@end deffn

@geindex PyGILState_STATE.PyGILState_UNLOCKED (C enumerator)
@anchor{c-api/init c PyGILState_STATE PyGILState_UNLOCKED}@anchor{552b}
@deffn {C Enumerator} enumerator PyGILState_UNLOCKED

The GIL was not held when @ref{64a,,PyGILState_Ensure()} was called.
@end deffn
@end deffn

@geindex PyGILState_Ensure (C function)
@anchor{c-api/init c PyGILState_Ensure}@anchor{64a}
@deffn {C の関数} @ref{502e,,PyGILState_STATE} PyGILState_Ensure ()
` 次に属します: @ref{775,,Stable ABI}.'
Ensure that the current thread is ready to call the Python C API regardless
of the current state of Python, or of the @ref{4ed1,,attached thread state}. This may
be called as many times as desired by a thread as long as each call is
matched with a call to @ref{64b,,PyGILState_Release()}. In general, other
thread-related APIs may be used between @ref{64a,,PyGILState_Ensure()} and
@ref{64b,,PyGILState_Release()} calls as long as the thread state is restored to
its previous state before the Release().  For example, normal usage of the
@ref{4ebd,,Py_BEGIN_ALLOW_THREADS} and @ref{c7f,,Py_END_ALLOW_THREADS} macros is
acceptable.

The return value is an opaque "handle" to the @ref{4ed1,,attached thread state} when
@ref{64a,,PyGILState_Ensure()} was called, and must be passed to
@ref{64b,,PyGILState_Release()} to ensure Python is left in the same state. Even
though recursive calls are allowed, these handles `cannot' be shared - each
unique call to @ref{64a,,PyGILState_Ensure()} must save the handle for its call
to @ref{64b,,PyGILState_Release()}.

When the function returns, there will be an @ref{4ed1,,attached thread state}
and the thread will be able to call arbitrary Python code.  Failure is a fatal error.

@cartouche
@quotation 警告 
Calling this function when the runtime is finalizing is unsafe. Doing
so will either hang the thread until the program ends, or fully crash
the interpreter in rare cases. Refer to
@ref{5525,,Cautions regarding runtime finalization} for more details.
@end quotation
@end cartouche


バージョン 3.14 で変更: Hangs the current thread, rather than terminating it, if called while the
interpreter is finalizing.

@end deffn

@geindex PyGILState_Release (C function)
@anchor{c-api/init c PyGILState_Release}@anchor{64b}
@deffn {C の関数} void PyGILState_Release (PyGILState_STATE)
` 次に属します: @ref{775,,Stable ABI}.'
獲得したすべてのリソースを解放します。この関数を呼び出すと、Pythonの状態は対応する @ref{64a,,PyGILState_Ensure()} を呼び出す前と同じとなります (通常、この状態は呼び出し元でははわかりませんので、GILState APIを利用するようにしてください)。

@ref{64a,,PyGILState_Ensure()} を呼び出す場合は、必ず同一スレッド内で対応する @ref{64b,,PyGILState_Release()} を呼び出してください。
@end deffn

@geindex PyGILState_GetThisThreadState (C function)
@anchor{c-api/init c PyGILState_GetThisThreadState}@anchor{502d}
@deffn {C の関数} @ref{990,,PyThreadState} *PyGILState_GetThisThreadState ()
` 次に属します: @ref{775,,Stable ABI}.'
Get the @ref{4ed1,,attached thread state} for this thread.  May return @code{NULL} if no
GILState API has been used on the current thread.  Note that the main thread
always has such a thread-state, even if no auto-thread-state call has been
made on the main thread.  This is mainly a helper/diagnostic function.

@cartouche
@quotation 注釈 
This function may return non-@code{NULL} even when the @ref{1846,,thread state}
is detached.
Prefer @ref{615,,PyThreadState_Get()} or @ref{423,,PyThreadState_GetUnchecked()}
for most cases.
@end quotation
@end cartouche


@subsubheading 参考


@ref{615,,PyThreadState_Get()}

@end deffn

@geindex PyGILState_Check (C function)
@anchor{c-api/init c PyGILState_Check}@anchor{552c}
@deffn {C の関数} int PyGILState_Check ()

Return @code{1} if the current thread is holding the @ref{164,,GIL} and @code{0} otherwise.
This function can be called from any thread at any time.
Only if it has had its @ref{4ed1,,thread state} initialized
via @ref{64a,,PyGILState_Ensure()} will it return @code{1}.
This is mainly a helper/diagnostic function.  It can be useful
for example in callback contexts or memory allocation functions when
knowing that the @ref{164,,GIL} is locked can allow the caller to perform sensitive
actions or otherwise behave differently.

@cartouche
@quotation 注釈 
If the current Python process has ever created a subinterpreter, this
function will `always' return @code{1}. Prefer @ref{423,,PyThreadState_GetUnchecked()}
for most cases.
@end quotation
@end cartouche


Added in version 3.4.

@end deffn

以下のマクロは、通常末尾にセミコロンを付けずに使います; Python ソース配布物内の使用例を見てください。

@geindex Py_BEGIN_ALLOW_THREADS (C macro)
@anchor{c-api/init c Py_BEGIN_ALLOW_THREADS}@anchor{4ebd}
@deffn {C のマクロ} Py_BEGIN_ALLOW_THREADS
` 次に属します: @ref{775,,Stable ABI}.'
このマクロを展開すると @code{@{ PyThreadState *_save; _save = PyEval_SaveThread();} になります。マクロに開き波括弧が入っていることに注意してください; この波括弧は後で @ref{c7f,,Py_END_ALLOW_THREADS} マクロと対応させなければなりません。マクロについての詳しい議論は上記を参照してください。
@end deffn

@geindex Py_END_ALLOW_THREADS (C macro)
@anchor{c-api/init c Py_END_ALLOW_THREADS}@anchor{c7f}
@deffn {C のマクロ} Py_END_ALLOW_THREADS
` 次に属します: @ref{775,,Stable ABI}.'
このマクロを展開すると @code{PyEval_RestoreThread(_save); @}} になります。マクロに開き波括弧が入っていることに注意してください; この波括弧は事前の @ref{4ebd,,Py_BEGIN_ALLOW_THREADS} マクロと対応していなければなりません。マクロについての詳しい議論は上記を参照してください。
@end deffn

@geindex Py_BLOCK_THREADS (C macro)
@anchor{c-api/init c Py_BLOCK_THREADS}@anchor{5129}
@deffn {C のマクロ} Py_BLOCK_THREADS
` 次に属します: @ref{775,,Stable ABI}.'
このマクロを展開すると @code{PyEval_RestoreThread(_save);} になります: 閉じ波括弧のない @ref{c7f,,Py_END_ALLOW_THREADS} と同じです。
@end deffn

@geindex Py_UNBLOCK_THREADS (C macro)
@anchor{c-api/init c Py_UNBLOCK_THREADS}@anchor{5149}
@deffn {C のマクロ} Py_UNBLOCK_THREADS
` 次に属します: @ref{775,,Stable ABI}.'
このマクロを展開すると @code{_save = PyEval_SaveThread();} になります: 開き波括弧のない @ref{4ebd,,Py_BEGIN_ALLOW_THREADS} と同じです。
@end deffn

@node 低レベルAPI,,高レベルAPI,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock
@anchor{c-api/init low-level-api}@anchor{552d}
@subsubsection 低レベルAPI


次の全ての関数は @ref{460,,Py_Initialize()} の後に呼び出さなければなりません。


バージョン 3.7 で変更: @ref{460,,Py_Initialize()} now initializes the @ref{164,,GIL}
and sets an @ref{4ed1,,attached thread state}.


@geindex PyInterpreterState_New (C function)
@anchor{c-api/init c PyInterpreterState_New}@anchor{4754}
@deffn {C の関数} @ref{aba,,PyInterpreterState} *PyInterpreterState_New ()
` 次に属します: @ref{775,,Stable ABI}.'
Create a new interpreter state object.  An @ref{4ed1,,attached thread state} is not needed,
but may optionally exist if it is necessary to serialize calls to this
function.

引数無しで @ref{1c6e,,監査イベント} @code{cpython.PyInterpreterState_New} を送出します。
@end deffn

@geindex PyInterpreterState_Clear (C function)
@anchor{c-api/init c PyInterpreterState_Clear}@anchor{4753}
@deffn {C の関数} void PyInterpreterState_Clear (PyInterpreterState *interp)
` 次に属します: @ref{775,,Stable ABI}.'
Reset all information in an interpreter state object.  There must be
an @ref{4ed1,,attached thread state} for the interpreter.

引数無しで @ref{1c6e,,監査イベント} @code{cpython.PyInterpreterState_Clear} を送出します。
@end deffn

@geindex PyInterpreterState_Delete (C function)
@anchor{c-api/init c PyInterpreterState_Delete}@anchor{503b}
@deffn {C の関数} void PyInterpreterState_Delete (PyInterpreterState *interp)
` 次に属します: @ref{775,,Stable ABI}.'
Destroy an interpreter state object.  There `should not' be an
@ref{4ed1,,attached thread state} for the target interpreter. The interpreter
state must have been reset with a previous call to @ref{4753,,PyInterpreterState_Clear()}.
@end deffn

@geindex PyThreadState_New (C function)
@anchor{c-api/init c PyThreadState_New}@anchor{50c3}
@deffn {C の関数} @ref{990,,PyThreadState} *PyThreadState_New (PyInterpreterState *interp)
` 次に属します: @ref{775,,Stable ABI}.'
Create a new thread state object belonging to the given interpreter object.
An @ref{4ed1,,attached thread state} is not needed.
@end deffn

@geindex PyThreadState_Clear (C function)
@anchor{c-api/init c PyThreadState_Clear}@anchor{1991}
@deffn {C の関数} void PyThreadState_Clear (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI}.'
Reset all information in a @ref{1846,,thread state} object.  `tstate'
must be @ref{4ed1,,attached}


バージョン 3.9 で変更: This function now calls the @code{PyThreadState.on_delete} callback.
Previously, that happened in @ref{1d89,,PyThreadState_Delete()}.



バージョン 3.13 で変更: The @code{PyThreadState.on_delete} callback was removed.

@end deffn

@geindex PyThreadState_Delete (C function)
@anchor{c-api/init c PyThreadState_Delete}@anchor{1d89}
@deffn {C の関数} void PyThreadState_Delete (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI}.'
Destroy a @ref{1846,,thread state} object.  `tstate' should not
be @ref{4ed1,,attached} to any thread.
`tstate' must have been reset with a previous call to
@ref{1991,,PyThreadState_Clear()}.
@end deffn

@geindex PyThreadState_DeleteCurrent (C function)
@anchor{c-api/init c PyThreadState_DeleteCurrent}@anchor{1db8}
@deffn {C の関数} void PyThreadState_DeleteCurrent (void)

Detach the @ref{4ed1,,attached thread state} (which must have been reset
with a previous call to @ref{1991,,PyThreadState_Clear()}) and then destroy it.

No @ref{1846,,thread state} will be @ref{4ed1,,attached} upon
returning.
@end deffn

@geindex PyThreadState_GetFrame (C function)
@anchor{c-api/init c PyThreadState_GetFrame}@anchor{991}
@deffn {C の関数} @ref{98c,,PyFrameObject} *PyThreadState_GetFrame (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Get the current frame of the Python thread state `tstate'.

Return a @ref{5e2,,strong reference}. Return @code{NULL} if no frame is currently
executing.

See also @ref{1b39,,PyEval_GetFrame()}.

`tstate' must not be @code{NULL}, and must be @ref{4ed1,,attached}.


Added in version 3.9.

@end deffn

@geindex PyThreadState_GetID (C function)
@anchor{c-api/init c PyThreadState_GetID}@anchor{b6a}
@deffn {C の関数} uint64_t PyThreadState_GetID (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Get the unique @ref{1846,,thread state} identifier of the Python thread state `tstate'.

`tstate' must not be @code{NULL}, and must be @ref{4ed1,,attached}.


Added in version 3.9.

@end deffn

@geindex PyThreadState_GetInterpreter (C function)
@anchor{c-api/init c PyThreadState_GetInterpreter}@anchor{b69}
@deffn {C の関数} @ref{aba,,PyInterpreterState} *PyThreadState_GetInterpreter (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Get the interpreter of the Python thread state `tstate'.

`tstate' must not be @code{NULL}, and must be @ref{4ed1,,attached}.


Added in version 3.9.

@end deffn

@geindex PyThreadState_EnterTracing (C function)
@anchor{c-api/init c PyThreadState_EnterTracing}@anchor{95a}
@deffn {C の関数} void PyThreadState_EnterTracing (PyThreadState *tstate)

Suspend tracing and profiling in the Python thread state `tstate'.

Resume them using the @ref{95b,,PyThreadState_LeaveTracing()} function.


Added in version 3.11.

@end deffn

@geindex PyThreadState_LeaveTracing (C function)
@anchor{c-api/init c PyThreadState_LeaveTracing}@anchor{95b}
@deffn {C の関数} void PyThreadState_LeaveTracing (PyThreadState *tstate)

Resume tracing and profiling in the Python thread state `tstate' suspended
by the @ref{95a,,PyThreadState_EnterTracing()} function.

See also @ref{663,,PyEval_SetTrace()} and @ref{1716,,PyEval_SetProfile()}
functions.


Added in version 3.11.

@end deffn

@geindex PyUnstable_ThreadState_SetStackProtection (C function)
@anchor{c-api/init c PyUnstable_ThreadState_SetStackProtection}@anchor{466}
@deffn {C の関数} int PyUnstable_ThreadState_SetStackProtection (PyThreadState *tstate, void *stack_start_addr, size_t stack_size)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Set the stack protection start address and stack protection size
of a Python thread state.

On success, return @code{0}.
On failure, set an exception and return @code{-1}.

CPython implements @ref{51ff,,recursion control} for C code by raising
@ref{f68,,RecursionError} when it notices that the machine execution stack is close
to overflow. See for example the @ref{3d2,,Py_EnterRecursiveCall()} function.
For this, it needs to know the location of the current thread's stack, which it
normally gets from the operating system.
When the stack is changed, for example using context switching techniques like the
Boost library's @code{boost::context}, you must call
@ref{466,,PyUnstable_ThreadState_SetStackProtection()} to inform CPython of the change.

Call @ref{466,,PyUnstable_ThreadState_SetStackProtection()} either before
or after changing the stack.
Do not call any other Python C API between the call and the stack
change.

See @ref{467,,PyUnstable_ThreadState_ResetStackProtection()} for undoing this operation.


Added in version 3.14.1: 

@cartouche
@quotation 警告 
This function was added in a bugfix release, and
extensions that use it will be incompatible with Python 3.14.0.
Most packaging tools for Python are not able to handle this
incompatibility automatically, and will need explicit configuration.
When using PyPA standards (wheels and source distributions),
specify @code{Requires-Python: != 3.14.0.*} in
core metadata@footnote{https://packaging.python.org/en/latest/specifications/core-metadata/#requires-python}.
@end quotation
@end cartouche

@end deffn

@geindex PyUnstable_ThreadState_ResetStackProtection (C function)
@anchor{c-api/init c PyUnstable_ThreadState_ResetStackProtection}@anchor{467}
@deffn {C の関数} void PyUnstable_ThreadState_ResetStackProtection (PyThreadState *tstate)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Reset the stack protection start address and stack protection size
of a Python thread state to the operating system defaults.

See @ref{466,,PyUnstable_ThreadState_SetStackProtection()} for an explanation.


Added in version 3.14.1: 

@cartouche
@quotation 警告 
This function was added in a bugfix release, and
extensions that use it will be incompatible with Python 3.14.0.
Most packaging tools for Python are not able to handle this
incompatibility automatically, and will need explicit configuration.
When using PyPA standards (wheels and source distributions),
specify @code{Requires-Python: != 3.14.0.*} in
core metadata@footnote{https://packaging.python.org/en/latest/specifications/core-metadata/#requires-python}.
@end quotation
@end cartouche

@end deffn

@geindex PyInterpreterState_Get (C function)
@anchor{c-api/init c PyInterpreterState_Get}@anchor{64c}
@deffn {C の関数} @ref{aba,,PyInterpreterState} *PyInterpreterState_Get (void)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
Get the current interpreter.

Issue a fatal error if there is no @ref{4ed1,,attached thread state}.
It cannot return NULL.


Added in version 3.9.

@end deffn

@geindex PyInterpreterState_GetID (C function)
@anchor{c-api/init c PyInterpreterState_GetID}@anchor{dbf}
@deffn {C の関数} int64_t PyInterpreterState_GetID (PyInterpreterState *interp)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
インタプリタの一意な ID を返します。
処理中に何かエラーが起きたら、 @code{-1} が返され、エラーがセットされます。

The caller must have an @ref{4ed1,,attached thread state}.


Added in version 3.7.

@end deffn

@geindex PyInterpreterState_GetDict (C function)
@anchor{c-api/init c PyInterpreterState_GetDict}@anchor{503c}
@deffn {C の関数} @ref{5df,,PyObject} *PyInterpreterState_GetDict (PyInterpreterState *interp)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
インタプリタ固有のデータを保持している辞書を返します。
この関数が @code{NULL} を返した場合は、ここまでで例外は送出されておらず、呼び出し側はインタプリタ固有の辞書は利用できないと考えなければなりません。

この関数は @ref{b77,,PyModule_GetState()} を置き換えるものではなく、拡張モジュールがインタプリタ固有の状態情報を格納するのに使うべきものです。

The returned dictionary is borrowed from the interpreter and is valid until
interpreter shutdown.


Added in version 3.8.

@end deffn

@geindex _PyFrameEvalFunction (C type)
@anchor{c-api/init c _PyFrameEvalFunction}@anchor{97a}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*_PyFrameEvalFunction)(@ref{990,,PyThreadState} *tstate, @ref{196e,,_PyInterpreterFrame} *frame, int throwflag)

Type of a frame evaluation function.

The `throwflag' parameter is used by the @code{throw()} method of generators:
if non-zero, handle the current exception.


バージョン 3.9 で変更: The function now takes a `tstate' parameter.



バージョン 3.11 で変更: The `frame' parameter changed from @code{PyFrameObject*} to @code{_PyInterpreterFrame*}.

@end deffn

@geindex _PyInterpreterState_GetEvalFrameFunc (C function)
@anchor{c-api/init c _PyInterpreterState_GetEvalFrameFunc}@anchor{1d77}
@deffn {C の関数} @ref{97a,,_PyFrameEvalFunction} _PyInterpreterState_GetEvalFrameFunc (PyInterpreterState *interp)

Get the frame evaluation function.

See the 
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/} "Adding a frame evaluation API to CPython".


Added in version 3.9.

@end deffn

@geindex _PyInterpreterState_SetEvalFrameFunc (C function)
@anchor{c-api/init c _PyInterpreterState_SetEvalFrameFunc}@anchor{1d78}
@deffn {C の関数} void _PyInterpreterState_SetEvalFrameFunc (PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)

Set the frame evaluation function.

See the 
@geindex Python Enhancement Proposals; PEP 523
PEP 523@footnote{https://peps.python.org/pep-0523/} "Adding a frame evaluation API to CPython".


Added in version 3.9.

@end deffn

@geindex PyThreadState_GetDict (C function)
@anchor{c-api/init c PyThreadState_GetDict}@anchor{50c2}
@deffn {C の関数} @ref{5df,,PyObject} *PyThreadState_GetDict ()
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
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 @ref{1846,,thread state}
is @ref{4ed1,,attached}. If this function returns
@code{NULL}, no exception has been raised and the caller should assume no
thread state is attached.
@end deffn

@geindex PyThreadState_SetAsyncExc (C function)
@anchor{c-api/init c PyThreadState_SetAsyncExc}@anchor{dbd}
@deffn {C の関数} int PyThreadState_SetAsyncExc (unsigned long id, PyObject *exc)
` 次に属します: @ref{775,,Stable ABI}.'
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 an @ref{4ed1,,attached thread state}.
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 @code{NULL}, the pending
exception (if any) for the thread is cleared. This raises no exceptions.


バージョン 3.7 で変更: `id' 引数の型が long から unsigned long へ変更されました。

@end deffn

@geindex PyEval_AcquireThread (C function)
@anchor{c-api/init c PyEval_AcquireThread}@anchor{649}
@deffn {C の関数} void PyEval_AcquireThread (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{4ed1,,Attach} `tstate' to the current thread,
which must not be @code{NULL} or already @ref{4ed1,,attached}.

The calling thread must not already have an @ref{4ed1,,attached thread state}.

@cartouche
@quotation 注釈 
Calling this function from a thread when the runtime is finalizing will
hang the thread until the program exits, even if the thread was not
created by Python.  Refer to
@ref{5525,,Cautions regarding runtime finalization} for more details.
@end quotation
@end cartouche


バージョン 3.8 で変更: Updated to be consistent with @ref{648,,PyEval_RestoreThread()},
@ref{c7f,,Py_END_ALLOW_THREADS()}, and @ref{64a,,PyGILState_Ensure()},
and terminate the current thread if called while the interpreter is finalizing.



バージョン 3.14 で変更: Hangs the current thread, rather than terminating it, if called while the
interpreter is finalizing.


@ref{648,,PyEval_RestoreThread()} はいつでも (スレッドが初期化されたいないときでも) 利用可能な高レベル関数です。
@end deffn

@geindex PyEval_ReleaseThread (C function)
@anchor{c-api/init c PyEval_ReleaseThread}@anchor{4fde}
@deffn {C の関数} void PyEval_ReleaseThread (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI}.'
Detach the @ref{4ed1,,attached thread state}.
The `tstate' argument, which must not be @code{NULL}, is only used to check
that it represents the @ref{4ed1,,attached thread state} --- if it isn't, a fatal error is
reported.

@ref{647,,PyEval_SaveThread()} はより高レベルな関数で常に (スレッドが初期化されていないときでも) 利用できます。
@end deffn

@node サブインタプリタサポート,非同期通知,スレッド状態 thread state とグローバルインタプリタロック global interpreter lock,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init id3}@anchor{552e}@anchor{c-api/init sub-interpreter-support}@anchor{163}
@subsection サブインタプリタサポート


ほとんどの場合は埋め込む Python インタプリタは1つだけですが、いくつかの場合に同一プロセス内、あるいは同一スレッド内で、複数の独立したインタプリタを作成する必要があります。
これを可能にするのがサブインタプリタです。

"メイン" インタプリタとは、ランタイムが初期化を行ったときに最初に作成されたインタプリタのことです。
サブインタプリタと違い、メインインタプリタにはシグナルハンドリングのような、プロセス全域で唯一な責務があります。
メインインタプリタにはランタイムの初期化中の処理実行という責務もあり、通常はランタイムの終了処理中に動いているランタイムでもあります。
@ref{552f,,PyInterpreterState_Main()} 関数は、メインインタプリタの状態へのポインタを返します。

サブインタプリタを切り替えが @ref{50c4,,PyThreadState_Swap()} 関数でできます。
次の関数を使ってサブインタプリタの作成と削除が行えます:

@geindex PyInterpreterConfig (C type)
@anchor{c-api/init c PyInterpreterConfig}@anchor{78e}
@deffn {C のデータ型} type PyInterpreterConfig

Structure containing most parameters to configure a sub-interpreter.
Its values are used only in @ref{689,,Py_NewInterpreterFromConfig()} and
never modified by the runtime.


Added in version 3.12.


構造体フィールド:

@geindex PyInterpreterConfig.use_main_obmalloc (C member)
@anchor{c-api/init c PyInterpreterConfig use_main_obmalloc}@anchor{4917}
@deffn {C のメンバ変数} int use_main_obmalloc

If this is @code{0} then the sub-interpreter will use its own
"object" allocator state.
Otherwise it will use (share) the main interpreter's.

If this is @code{0} then
@ref{5530,,check_multi_interp_extensions}
must be @code{1} (non-zero).
If this is @code{1} then @ref{5531,,gil}
must not be @ref{5532,,PyInterpreterConfig_OWN_GIL}.
@end deffn

@geindex PyInterpreterConfig.allow_fork (C member)
@anchor{c-api/init c PyInterpreterConfig allow_fork}@anchor{5533}
@deffn {C のメンバ変数} int allow_fork

If this is @code{0} then the runtime will not support forking the
process in any thread where the sub-interpreter is currently active.
Otherwise fork is unrestricted.

Note that the @ref{dc,,subprocess} module still works
when fork is disallowed.
@end deffn

@geindex PyInterpreterConfig.allow_exec (C member)
@anchor{c-api/init c PyInterpreterConfig allow_exec}@anchor{5534}
@deffn {C のメンバ変数} int allow_exec

If this is @code{0} then the runtime will not support replacing the
current process via exec (e.g. @ref{3019,,os.execv()}) in any thread
where the sub-interpreter is currently active.
Otherwise exec is unrestricted.

Note that the @ref{dc,,subprocess} module still works
when exec is disallowed.
@end deffn

@geindex PyInterpreterConfig.allow_threads (C member)
@anchor{c-api/init c PyInterpreterConfig allow_threads}@anchor{5535}
@deffn {C のメンバ変数} int allow_threads

If this is @code{0} then the sub-interpreter's @ref{f3,,threading} module
won't create threads.
Otherwise threads are allowed.
@end deffn

@geindex PyInterpreterConfig.allow_daemon_threads (C member)
@anchor{c-api/init c PyInterpreterConfig allow_daemon_threads}@anchor{5536}
@deffn {C のメンバ変数} int allow_daemon_threads

If this is @code{0} then the sub-interpreter's @ref{f3,,threading} module
won't create daemon threads.
Otherwise daemon threads are allowed (as long as
@ref{5535,,allow_threads} is non-zero).
@end deffn

@geindex PyInterpreterConfig.check_multi_interp_extensions (C member)
@anchor{c-api/init c PyInterpreterConfig check_multi_interp_extensions}@anchor{5530}
@deffn {C のメンバ変数} int check_multi_interp_extensions

If this is @code{0} then all extension modules may be imported,
including legacy (single-phase init) modules,
in any thread where the sub-interpreter is currently active.
Otherwise only multi-phase init extension modules
(see 
@geindex Python Enhancement Proposals; PEP 489
PEP 489@footnote{https://peps.python.org/pep-0489/}) may be imported.
(Also see @ref{5152,,Py_mod_multiple_interpreters}.)

This must be @code{1} (non-zero) if
@ref{4917,,use_main_obmalloc} is @code{0}.
@end deffn

@geindex PyInterpreterConfig.gil (C member)
@anchor{c-api/init c PyInterpreterConfig gil}@anchor{5531}
@deffn {C のメンバ変数} int gil

This determines the operation of the GIL for the sub-interpreter.
It may be one of the following:

@geindex PyInterpreterConfig_DEFAULT_GIL (C macro)
@anchor{c-api/init c PyInterpreterConfig_DEFAULT_GIL}@anchor{5537}
@deffn {C のマクロ} PyInterpreterConfig_DEFAULT_GIL

Use the default selection (@ref{5538,,PyInterpreterConfig_SHARED_GIL}).
@end deffn

@geindex PyInterpreterConfig_SHARED_GIL (C macro)
@anchor{c-api/init c PyInterpreterConfig_SHARED_GIL}@anchor{5538}
@deffn {C のマクロ} PyInterpreterConfig_SHARED_GIL

Use (share) the main interpreter's GIL.
@end deffn

@geindex PyInterpreterConfig_OWN_GIL (C macro)
@anchor{c-api/init c PyInterpreterConfig_OWN_GIL}@anchor{5532}
@deffn {C のマクロ} PyInterpreterConfig_OWN_GIL

Use the sub-interpreter's own GIL.
@end deffn

If this is @ref{5532,,PyInterpreterConfig_OWN_GIL} then
@ref{4917,,PyInterpreterConfig.use_main_obmalloc} must be @code{0}.
@end deffn
@end deffn

@geindex Py_NewInterpreterFromConfig (C function)
@anchor{c-api/init c Py_NewInterpreterFromConfig}@anchor{689}
@deffn {C の関数} @ref{ba4,,PyStatus} Py_NewInterpreterFromConfig (PyThreadState **tstate_p, const PyInterpreterConfig *config)

@geindex module;builtins
@geindex module;__main__
@geindex module;sys
@geindex stdout (sys モジュール)
@geindex stderr (sys モジュール)
@geindex stdin (sys モジュール)

新しいサブインタプリタ (sub-interpreter) を生成します。サブインタプリタとは、(ほぼ完全に) 個別に分割された Python コードの実行環境です。特に、新しいサブインタプリタは、 import されるモジュール全てについて個別のバージョンを持ち、これには基盤となるモジュール @ref{13,,builtins}, @ref{1,,__main__} および @ref{df,,sys} も含まれます。ロード済みのモジュールからなるテーブル (@code{sys.modules})  およびモジュール検索パス (@code{sys.path}) もサブインタプリタ毎に別個のものになります。新たなサブインタプリタ環境には @code{sys.argv} 変数がありません。また、サブインタプリタは新たな標準 I/O ストリーム @code{sys.stdin}, @code{sys.stdout}, @code{sys.stderr} を持ちます (とはいえ、これらのストリームは根底にある同じファイル記述子を参照しています)。

The given `config' controls the options with which the interpreter
is initialized.

Upon success, `tstate_p' will be set to the first @ref{1846,,thread state}
created in the new sub-interpreter.  This thread state is
@ref{4ed1,,attached}.
Note that no actual thread is created; see the discussion of thread states
below.  If creation of the new interpreter is unsuccessful,
`tstate_p' is set to @code{NULL};
no exception is set since the exception state is stored in the
@ref{4ed1,,attached thread state}, which might not exist.

Like all other Python/C API functions, an @ref{4ed1,,attached thread state}
must be present before calling this function, but it might be detached upon
returning. On success, the returned thread state will be @ref{4ed1,,attached}.
If the sub-interpreter is created with its own @ref{164,,GIL} then the
@ref{4ed1,,attached thread state} of the calling interpreter will be detached.
When the function returns, the new interpreter's @ref{1846,,thread state}
will be @ref{4ed1,,attached} to the current thread and
the previous interpreter's @ref{4ed1,,attached thread state} will remain detached.


Added in version 3.12.


Sub-interpreters are most effective when isolated from each other,
with certain functionality restricted:

@example
PyInterpreterConfig config = @{
    .use_main_obmalloc = 0,
    .allow_fork = 0,
    .allow_exec = 0,
    .allow_threads = 1,
    .allow_daemon_threads = 0,
    .check_multi_interp_extensions = 1,
    .gil = PyInterpreterConfig_OWN_GIL,
@};
PyThreadState *tstate = NULL;
PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
if (PyStatus_Exception(status)) @{
    Py_ExitStatusException(status);
@}
@end example

Note that the config is used only briefly and does not get modified.
During initialization the config's values are converted into various
@ref{aba,,PyInterpreterState} values.  A read-only copy of the config
may be stored internally on the @ref{aba,,PyInterpreterState}.

@geindex Py_FinalizeEx (C function)
@geindex Py_Initialize (C function)

Extension modules are shared between (sub-)interpreters as follows:


@itemize *

@item 
For modules using multi-phase initialization,
e.g. @ref{10b3,,PyModule_FromDefAndSpec()}, a separate module object is
created and initialized for each interpreter.
Only C-level static and global variables are shared between these
module objects.

@item 
For modules using single-phase initialization,
e.g. @ref{5217,,PyModule_Create()}, the first time a particular extension
is imported, it is initialized normally, and a (shallow) copy of its
module's dictionary is squirreled away.
When the same extension is imported by another (sub-)interpreter, a new
module is initialized and filled with the contents of this copy; the
extension's @code{init} function is not called.
Objects in the module's dictionary thus end up shared across
(sub-)interpreters, which might cause unwanted behavior (see
@ref{5539,,Bugs and caveats} below).

Note that this is different from what happens when an extension is
imported after the interpreter has been completely re-initialized by
calling @ref{f11,,Py_FinalizeEx()} and @ref{460,,Py_Initialize()}; in that
case, the extension's @code{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.
@end itemize

@geindex close (in module os)
@end deffn

@geindex Py_NewInterpreter (C function)
@anchor{c-api/init c Py_NewInterpreter}@anchor{1b31}
@deffn {C の関数} @ref{990,,PyThreadState} *Py_NewInterpreter (void)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex module;builtins
@geindex module;__main__
@geindex module;sys
@geindex stdout (sys モジュール)
@geindex stderr (sys モジュール)
@geindex stdin (sys モジュール)

Create a new sub-interpreter.  This is essentially just a wrapper
around @ref{689,,Py_NewInterpreterFromConfig()} with a config that
preserves the existing behavior.  The result is an unisolated
sub-interpreter that shares the main interpreter's GIL, allows
fork/exec, allows daemon threads, and allows single-phase init
modules.
@end deffn

@geindex Py_EndInterpreter (C function)
@anchor{c-api/init c Py_EndInterpreter}@anchor{1845}
@deffn {C の関数} void Py_EndInterpreter (PyThreadState *tstate)
` 次に属します: @ref{775,,Stable ABI}.'
@geindex Py_FinalizeEx (C function)

Destroy the (sub-)interpreter represented by the given @ref{1846,,thread state}.
The given thread state must be @ref{4ed1,,attached}.
When the call returns, there will be no @ref{4ed1,,attached thread state}.
All thread states associated with this interpreter are destroyed.

@ref{f11,,Py_FinalizeEx()} will destroy all sub-interpreters that
haven't been explicitly destroyed at that point.
@end deffn

@menu
* A Per-Interpreter GIL:: 
* バグと注意事項:: 

@end menu

@node A Per-Interpreter GIL,バグと注意事項,,サブインタプリタサポート
@anchor{c-api/init a-per-interpreter-gil}@anchor{553a}@anchor{c-api/init per-interpreter-gil}@anchor{5528}
@subsubsection A Per-Interpreter GIL


Using @ref{689,,Py_NewInterpreterFromConfig()} you can create
a sub-interpreter that is completely isolated from other interpreters,
including having its own GIL.  The most important benefit of this
isolation is that such an interpreter can execute Python code without
being blocked by other interpreters or blocking any others.  Thus a
single Python process can truly take advantage of multiple CPU cores
when running Python code.  The isolation also encourages a different
approach to concurrency than that of just using threads.
(See 
@geindex Python Enhancement Proposals; PEP 554
PEP 554@footnote{https://peps.python.org/pep-0554/} and 
@geindex Python Enhancement Proposals; PEP 684
PEP 684@footnote{https://peps.python.org/pep-0684/}.)

Using an isolated interpreter requires vigilance in preserving that
isolation.  That especially means not sharing any objects or mutable
state without guarantees about thread-safety.  Even objects that are
otherwise immutable (e.g. @code{None}, @code{(1, 5)}) can't normally be shared
because of the refcount.  One simple but less-efficient approach around
this is to use a global lock around all use of some state (or object).
Alternately, effectively immutable objects (like integers or strings)
can be made safe in spite of their refcounts by making them @ref{290,,immortal}.
In fact, this has been done for the builtin singletons, small integers,
and a number of other builtin objects.

If you preserve isolation then you will have access to proper multi-core
computing without the complications that come with free-threading.
Failure to preserve isolation will expose you to the full consequences
of free-threading, including races and hard-to-debug crashes.

Aside from that, one of the main challenges of using multiple isolated
interpreters is how to communicate between them safely (not break
isolation) and efficiently.  The runtime and stdlib do not provide
any standard approach to this yet.  A future stdlib module would help
mitigate the effort of preserving isolation and expose effective tools
for communicating (and sharing) data between interpreters.


Added in version 3.12.


@node バグと注意事項,,A Per-Interpreter GIL,サブインタプリタサポート
@anchor{c-api/init bugs-and-caveats}@anchor{5539}
@subsubsection バグと注意事項


Because sub-interpreters (and the main interpreter) are part of the same
process, the insulation between them isn't perfect --- for example, using
low-level file operations like  @ref{d6b,,os.close()} they can
(accidentally or maliciously) affect each other's open files.  Because of the
way extensions are shared between (sub-)interpreters, some extensions may not
work properly; this is especially likely when using single-phase initialization
or (static) global variables.
It is possible to insert objects created in one sub-interpreter into
a namespace of another (sub-)interpreter; this should be avoided if possible.

Special care should be taken to avoid sharing user-defined functions,
methods, instances or classes between sub-interpreters, since import
operations executed by such objects may affect the wrong (sub-)interpreter's
dictionary of loaded modules. It is equally important to avoid sharing
objects from which the above are reachable.

サブインタプリタを @code{PyGILState_*} API と組み合わせるのが難しいことにも注意してください。これらのAPIはPythonのスレッド状態とOSレベルスレッドが1対1で対応していることを前提にしていて、サブインタプリタが存在するとその前提が崩れるからです。対応する @ref{64a,,PyGILState_Ensure()} と @ref{64b,,PyGILState_Release()} の呼び出しのペアの間では、サブインタプリタの切り替えを行わないことを強く推奨します。さらに、(@ref{2e,,ctypes} のような)これらのAPIを使ってPythonの外で作られたスレッドから Pythonコードを実行している拡張モジュールはサブインタプリタを使うと壊れる可能性があります。

@node 非同期通知,プロファイルとトレース profiling and tracing,サブインタプリタサポート,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init asynchronous-notifications}@anchor{553b}
@subsection 非同期通知


インタプリタのメインスレッドに非同期な通知を行うために提供されている仕組みです。これらの通知は関数ポインタと void ポインタ引数という形態を取ります。

@geindex Py_AddPendingCall (C function)
@anchor{c-api/init c Py_AddPendingCall}@anchor{b78}
@deffn {C の関数} int Py_AddPendingCall (int (*func)(void*), void *arg)
` 次に属します: @ref{775,,Stable ABI}.'
インタプリタのメインスレッドから関数が呼び出される予定を組みます。成功すると @code{0} が返り、`func' はメインスレッドの呼び出しキューに詰められます。失敗すると、例外をセットせずに @code{-1} が返ります。

無事にキューに詰められると、`func' は `いつかは必ず' インタプリタのメインスレッドから、`arg' を引数として呼び出されます。この関数は、通常の実行中の Python コードに対して非同期に呼び出されますが、次の両方の条件に合致したときに呼び出されます:


@itemize *

@item 
@ref{4aa,,bytecode} 境界上にいるとき、

@item 
with the main thread holding an @ref{4ed1,,attached thread state}
(`func' can therefore use the full C API).
@end itemize

`func' must return @code{0} on success, or @code{-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 @ref{4ed1,,thread state} is detached.

This function doesn't need an @ref{4ed1,,attached thread state}. However, to call this
function in a subinterpreter, the caller must have an @ref{4ed1,,attached thread state}.
Otherwise, the function `func' can be scheduled to be called from the wrong interpreter.

@cartouche
@quotation 警告 
これは、非常に特別な場合にのみ役立つ、低レベルな関数です。 `func' が可能な限り早く呼び出される保証はありません。メインスレッドがシステムコールを実行するのに忙しい場合は、 `func' はシステムコールが返ってくるまで呼び出されないでしょう。この関数は一般的には、任意の C スレッドから Python コードを呼び出すのには `向きません' 。これの代わりに、 @ref{5521,,PyGILState API} を使用してください。
@end quotation
@end cartouche


Added in version 3.1.



バージョン 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.12 で変更: This function now always schedules `func' to be run in the main
interpreter.

@end deffn

@geindex Py_MakePendingCalls (C function)
@anchor{c-api/init c Py_MakePendingCalls}@anchor{5134}
@deffn {C の関数} int Py_MakePendingCalls (void)
` 次に属します: @ref{775,,Stable ABI}.'
Execute all pending calls. This is usually executed automatically by the
interpreter.

This function returns @code{0} on success, and returns @code{-1} with an exception
set on failure.

If this is not called in the main thread of the main
interpreter, this function does nothing and returns @code{0}.
The caller must hold an @ref{4ed1,,attached thread state}.


Added in version 3.1.



バージョン 3.12 で変更: This function only runs pending calls in the main interpreter.

@end deffn

@node プロファイルとトレース profiling and tracing,Reference tracing,非同期通知,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init profiling}@anchor{553c}@anchor{c-api/init profiling-and-tracing}@anchor{553d}
@subsection プロファイルとトレース (profiling and tracing)


Python インタプリタは、プロファイル: 分析 (profile) や実行のトレース: 追跡 (trace) といった機能を組み込むために低水準のサポートを提供しています。このサポートは、プロファイルやデバッグ、適用範囲分析 (coverage analysis) ツールなどに使われます。

この C インターフェースは、プロファイルやトレース作業時に、Python レベルの呼び出し可能オブジェクトが呼び出されることによるオーバヘッドを避け、直接 C 関数呼び出しが行えるようにしています。プロファイルやトレース機能の本質的な特性は変わっていません; インターフェースではトレース関数をスレッドごとにインストールでき、トレース関数に報告される基本イベント (basic event) は以前のバージョンにおいて Python レベルのトレース関数で報告されていたものと同じです。

@geindex Py_tracefunc (C type)
@anchor{c-api/init c Py_tracefunc}@anchor{553e}
@deffn {C のデータ型} typedef int (*Py_tracefunc)(@ref{5df,,PyObject} *obj, @ref{98c,,PyFrameObject} *frame, int what, @ref{5df,,PyObject} *arg)

The type of the trace function registered using @ref{1716,,PyEval_SetProfile()} and
@ref{663,,PyEval_SetTrace()}. 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 @ref{553f,,PyTrace_CALL},
@ref{5540,,PyTrace_EXCEPTION}, @ref{5541,,PyTrace_LINE}, @ref{5542,,PyTrace_RETURN},
@ref{5543,,PyTrace_C_CALL}, @ref{5544,,PyTrace_C_EXCEPTION}, @ref{5545,,PyTrace_C_RETURN},
or @ref{5546,,PyTrace_OPCODE}, and `arg' depends on the value of `what':


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

`what' の値

@tab

`arg' の意味

@item

@ref{553f,,PyTrace_CALL}

@tab

常に @ref{4e9f,,Py_None} 。

@item

@ref{5540,,PyTrace_EXCEPTION}

@tab

@ref{89a,,sys.exc_info()} の返す例外情報です。

@item

@ref{5541,,PyTrace_LINE}

@tab

常に @ref{4e9f,,Py_None} 。

@item

@ref{5542,,PyTrace_RETURN}

@tab

呼び出し側に返される予定の値か、例外によって関数を抜ける場合は @code{NULL} です。

@item

@ref{5543,,PyTrace_C_CALL}

@tab

呼び出される関数オブジェクト。

@item

@ref{5544,,PyTrace_C_EXCEPTION}

@tab

呼び出される関数オブジェクト。

@item

@ref{5545,,PyTrace_C_RETURN}

@tab

呼び出される関数オブジェクト。

@item

@ref{5546,,PyTrace_OPCODE}

@tab

常に @ref{4e9f,,Py_None} 。

@end multitable

@end deffn

@geindex PyTrace_CALL (C var)
@anchor{c-api/init c PyTrace_CALL}@anchor{553f}
@deffn {C 変数} int PyTrace_CALL

関数やメソッドが新たに呼び出されたり、ジェネレータが新たなエントリの処理に入ったことを報告する際の、 @ref{553e,,Py_tracefunc} の `what' の値です。イテレータやジェネレータ関数の生成は、対応するフレーム内の Python バイトコードに制御の委譲 (control transfer) が起こらないため報告されないので注意してください。
@end deffn

@geindex PyTrace_EXCEPTION (C var)
@anchor{c-api/init c PyTrace_EXCEPTION}@anchor{5540}
@deffn {C 変数} int PyTrace_EXCEPTION

The value of the `what' parameter to a @ref{553e,,Py_tracefunc} 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 receive
these events; they are not needed by the profiler.
@end deffn

@geindex PyTrace_LINE (C var)
@anchor{c-api/init c PyTrace_LINE}@anchor{5541}
@deffn {C 変数} int PyTrace_LINE

The value passed as the `what' parameter to a @ref{553e,,Py_tracefunc} function
(but not a profiling function) when a line-number event is being reported.
It may be disabled for a frame by setting @ref{dd6,,f_trace_lines} to
`0' on that frame.
@end deffn

@geindex PyTrace_RETURN (C var)
@anchor{c-api/init c PyTrace_RETURN}@anchor{5542}
@deffn {C 変数} int PyTrace_RETURN

呼び出しが返るときに @ref{553e,,Py_tracefunc} 関数に `what' 引数として渡す値です。
@end deffn

@geindex PyTrace_C_CALL (C var)
@anchor{c-api/init c PyTrace_C_CALL}@anchor{5543}
@deffn {C 変数} int PyTrace_C_CALL

C関数を呼び出す直前に @ref{553e,,Py_tracefunc} 関数の `what' 引数として渡す値です。
@end deffn

@geindex PyTrace_C_EXCEPTION (C var)
@anchor{c-api/init c PyTrace_C_EXCEPTION}@anchor{5544}
@deffn {C 変数} int PyTrace_C_EXCEPTION

C関数が例外を送出したときに @ref{553e,,Py_tracefunc} 関数の `what' 引数として渡す値です。
@end deffn

@geindex PyTrace_C_RETURN (C var)
@anchor{c-api/init c PyTrace_C_RETURN}@anchor{5545}
@deffn {C 変数} int PyTrace_C_RETURN

C関数から戻るときに @ref{553e,,Py_tracefunc} 関数の `what' 引数として渡す値です。
@end deffn

@geindex PyTrace_OPCODE (C var)
@anchor{c-api/init c PyTrace_OPCODE}@anchor{5546}
@deffn {C 変数} int PyTrace_OPCODE

The value for the `what' parameter to @ref{553e,,Py_tracefunc} functions (but not
profiling functions) when a new opcode is about to be executed.  This event is
not emitted by default: it must be explicitly requested by setting
@ref{dd7,,f_trace_opcodes} to `1' on the frame.
@end deffn

@geindex PyEval_SetProfile (C function)
@anchor{c-api/init c PyEval_SetProfile}@anchor{1716}
@deffn {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 @code{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 @ref{5541,,PyTrace_LINE}
@ref{5546,,PyTrace_OPCODE} and @ref{5540,,PyTrace_EXCEPTION}.

@ref{1717,,sys.setprofile()} 関数も参照してください。

The caller must have an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyEval_SetProfileAllThreads (C function)
@anchor{c-api/init c PyEval_SetProfileAllThreads}@anchor{781}
@deffn {C の関数} void PyEval_SetProfileAllThreads (Py_tracefunc func, PyObject *obj)

Like @ref{1716,,PyEval_SetProfile()} but sets the profile function in all running threads
belonging to the current interpreter instead of the setting it only on the current thread.

The caller must have an @ref{4ed1,,attached thread state}.

As @ref{1716,,PyEval_SetProfile()}, this function ignores any exceptions raised while
setting the profile functions in all threads.
@end deffn


Added in version 3.12.


@geindex PyEval_SetTrace (C function)
@anchor{c-api/init c PyEval_SetTrace}@anchor{663}
@deffn {C の関数} void PyEval_SetTrace (Py_tracefunc func, PyObject *obj)

Set the tracing function to `func'.  This is similar to
@ref{1716,,PyEval_SetProfile()}, except the tracing function does receive line-number
events and per-opcode events, but does not receive any event related to C function
objects being called.  Any trace function registered using @ref{663,,PyEval_SetTrace()}
will not receive @ref{5543,,PyTrace_C_CALL}, @ref{5544,,PyTrace_C_EXCEPTION} or
@ref{5545,,PyTrace_C_RETURN} as a value for the `what' parameter.

@ref{2e1,,sys.settrace()} 関数も参照してください。

The caller must have an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyEval_SetTraceAllThreads (C function)
@anchor{c-api/init c PyEval_SetTraceAllThreads}@anchor{664}
@deffn {C の関数} void PyEval_SetTraceAllThreads (Py_tracefunc func, PyObject *obj)

Like @ref{663,,PyEval_SetTrace()} but sets the tracing function in all running threads
belonging to the current interpreter instead of the setting it only on the current thread.

The caller must have an @ref{4ed1,,attached thread state}.

As @ref{663,,PyEval_SetTrace()}, this function ignores any exceptions raised while
setting the trace functions in all threads.
@end deffn


Added in version 3.12.


@node Reference tracing,高度なデバッガサポート advanced debugger support,プロファイルとトレース profiling and tracing,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init reference-tracing}@anchor{5547}
@subsection Reference tracing



Added in version 3.13.


@geindex PyRefTracer (C type)
@anchor{c-api/init c PyRefTracer}@anchor{5548}
@deffn {C のデータ型} typedef int (*PyRefTracer)(@ref{5df,,PyObject}*, int event, void *data)

The type of the trace function registered using @ref{610,,PyRefTracer_SetTracer()}.
The first parameter is a Python object that has been just created (when `event'
is set to @ref{5549,,PyRefTracer_CREATE}) or about to be destroyed (when `event'
is set to @ref{554a,,PyRefTracer_DESTROY}). The `data' argument is the opaque pointer
that was provided when @ref{610,,PyRefTracer_SetTracer()} was called.
@end deffn


Added in version 3.13.


@geindex PyRefTracer_CREATE (C var)
@anchor{c-api/init c PyRefTracer_CREATE}@anchor{5549}
@deffn {C 変数} int PyRefTracer_CREATE

The value for the `event' parameter to @ref{5548,,PyRefTracer} functions when a Python
object has been created.
@end deffn

@geindex PyRefTracer_DESTROY (C var)
@anchor{c-api/init c PyRefTracer_DESTROY}@anchor{554a}
@deffn {C 変数} int PyRefTracer_DESTROY

The value for the `event' parameter to @ref{5548,,PyRefTracer} functions when a Python
object has been destroyed.
@end deffn

@geindex PyRefTracer_SetTracer (C function)
@anchor{c-api/init c PyRefTracer_SetTracer}@anchor{610}
@deffn {C の関数} int PyRefTracer_SetTracer (PyRefTracer tracer, void *data)

Register a reference tracer function. The function will be called when a new
Python has been created or when an object is going to be destroyed. If
`data' is provided it must be an opaque pointer that will be provided when
the tracer function is called. Return @code{0} on success. Set an exception and
return @code{-1} on error.

Note that tracer functions `must not' create Python objects inside or
otherwise the call will be re-entrant. The tracer also `must not' clear
any existing exception or set an exception.  A @ref{1846,,thread state} will be active
every time the tracer function is called.

There must be an @ref{4ed1,,attached thread state} when calling this function.
@end deffn


Added in version 3.13.


@geindex PyRefTracer_GetTracer (C function)
@anchor{c-api/init c PyRefTracer_GetTracer}@anchor{611}
@deffn {C の関数} @ref{5548,,PyRefTracer} PyRefTracer_GetTracer (void **data)

Get the registered reference tracer function and the value of the opaque data
pointer that was registered when @ref{610,,PyRefTracer_SetTracer()} was called.
If no tracer was registered this function will return NULL and will set the
`data' pointer to NULL.

There must be an @ref{4ed1,,attached thread state} when calling this function.
@end deffn


Added in version 3.13.


@node 高度なデバッガサポート advanced debugger support,スレッドローカルストレージのサポート,Reference tracing,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init advanced-debugger-support}@anchor{554b}@anchor{c-api/init advanced-debugging}@anchor{554c}
@subsection 高度なデバッガサポート (advanced debugger support)


以下の関数は高度なデバッグツールでの使用のためだけのものです。

@geindex PyInterpreterState_Head (C function)
@anchor{c-api/init c PyInterpreterState_Head}@anchor{1718}
@deffn {C の関数} @ref{aba,,PyInterpreterState} *PyInterpreterState_Head ()

インタプリタ状態オブジェクトからなるリストのうち、先頭にあるものを返します。
@end deffn

@geindex PyInterpreterState_Main (C function)
@anchor{c-api/init c PyInterpreterState_Main}@anchor{552f}
@deffn {C の関数} @ref{aba,,PyInterpreterState} *PyInterpreterState_Main ()

メインインタプリタの状態オブジェクトを返します。
@end deffn

@geindex PyInterpreterState_Next (C function)
@anchor{c-api/init c PyInterpreterState_Next}@anchor{1719}
@deffn {C の関数} @ref{aba,,PyInterpreterState} *PyInterpreterState_Next (PyInterpreterState *interp)

インタプリタ状態オブジェクトからなるリストのうち、`interp' の次にあるものを返します。
@end deffn

@geindex PyInterpreterState_ThreadHead (C function)
@anchor{c-api/init c PyInterpreterState_ThreadHead}@anchor{171a}
@deffn {C の関数} @ref{990,,PyThreadState} *PyInterpreterState_ThreadHead (PyInterpreterState *interp)

インタプリタ `interp' に関連付けられているスレッドからなるリストのうち、先頭にある @ref{990,,PyThreadState} オブジェクトを返します。
@end deffn

@geindex PyThreadState_Next (C function)
@anchor{c-api/init c PyThreadState_Next}@anchor{171b}
@deffn {C の関数} @ref{990,,PyThreadState} *PyThreadState_Next (PyThreadState *tstate)

`tstate' と同じ @ref{aba,,PyInterpreterState} オブジェクトに属しているスレッド状態オブジェクトのうち、 `tstate' の次にあるものを返します。
@end deffn

@node スレッドローカルストレージのサポート,同期プリミティブ<3>,高度なデバッガサポート advanced debugger support,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init thread-local-storage}@anchor{554d}@anchor{c-api/init thread-local-storage-support}@anchor{554e}
@subsection スレッドローカルストレージのサポート


Python インタプリタは、スレッドローカルストレージ (thread-local storage, TLS) の低レベルサポートを提供していて、ネイティブの TLS 実装を内部にラップして Python レベルのスレッドローカルストレージ API (@ref{185f,,threading.local}) をサポートしています。
CPython の C レベル API は pthreads や Windows で与えられる TLS と同様です: スレッドキーとスレッドごとに void* 値を関係付ける関数を使います。

A @ref{1846,,thread state} does `not' need to be @ref{4ed1,,attached}
when calling these functions; they suppl their own locking.

@code{Python.h} は TLS API の宣言を include せず、スレッドローカルストレージを使うには @code{pythread.h} を include する必要があることに注意してください。

@cartouche
@quotation 注釈 
この API 関数はどれも void* 値の代わりにメモリ管理を行うことはしません。
メモリの確保と解放は自前で行う必要があります。
void* 値がたまたま @ref{5df,,PyObject}* だった場合は、 API 関数はそれぞれの値の参照カウントの操作は行いません。
@end quotation
@end cartouche

@menu
* スレッド固有ストレージ (Thread Specific Storage@comma{} TSS) API: スレッド固有ストレージ Thread Specific Storage TSS API. 
* スレッドローカルストレージ (TLS) API: スレッドローカルストレージ TLS API. 

@end menu

@node スレッド固有ストレージ Thread Specific Storage TSS API,スレッドローカルストレージ TLS API,,スレッドローカルストレージのサポート
@anchor{c-api/init thread-specific-storage-api}@anchor{cd5}@anchor{c-api/init thread-specific-storage-tss-api}@anchor{554f}
@subsubsection スレッド固有ストレージ (Thread Specific Storage, TSS) API


TSS API は、 CPython インタプリタに含まれている既存の TLS API を置き換えるために導入されました。
この API は、スレッドキーの表現に int の代わりに新しい型 @ref{cd6,,Py_tss_t} を使います。


Added in version 3.7.



@subsubheading 参考


"CPython のスレッドローカルストレージのための新しい C API" (
@geindex Python Enhancement Proposals; PEP 539
PEP 539@footnote{https://peps.python.org/pep-0539/})


@geindex Py_tss_t (C type)
@anchor{c-api/init c Py_tss_t}@anchor{cd6}
@deffn {C のデータ型} type Py_tss_t

このデータ構造体はスレッドキーの状態を表現しています。この構造体の定義は、根底の TLS 実装に依存し、キーの初期化状態を表現する内部フィールドを持ちます。
この構造体には公開 (public) のメンバはありません。

@ref{775,,Py_LIMITED_API} が定義されていないときは、この型の @ref{5550,,Py_tss_NEEDS_INIT} による静的メモリ確保ができます。
@end deffn

@geindex Py_tss_NEEDS_INIT (C macro)
@anchor{c-api/init c Py_tss_NEEDS_INIT}@anchor{5550}
@deffn {C のマクロ} Py_tss_NEEDS_INIT

このマクロは @ref{cd6,,Py_tss_t} 変数の初期化子に展開されます。
このマクロは @ref{775,,Py_LIMITED_API} があるときは定義されません。
@end deffn

@menu
* 動的メモリ確保:: 
* メソッド: メソッド<2>. 

@end menu

@node 動的メモリ確保,メソッド<2>,,スレッド固有ストレージ Thread Specific Storage TSS API
@anchor{c-api/init dynamic-allocation}@anchor{5551}
@subsubsection 動的メモリ確保


動的な @ref{cd6,,Py_tss_t} のメモリ確保は @ref{775,,Py_LIMITED_API} でビルドされた拡張モジュールで必要になりますが、その実装がビルド時に不透明なために、この型の静的なメモリ確保は不可能です。

@geindex PyThread_tss_alloc (C function)
@anchor{c-api/init c PyThread_tss_alloc}@anchor{438}
@deffn {C の関数} @ref{cd6,,Py_tss_t} *PyThread_tss_alloc ()
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Return a value which is the same state as a value initialized with
@ref{5550,,Py_tss_NEEDS_INIT}, or @code{NULL} in the case of dynamic allocation
failure.
@end deffn

@geindex PyThread_tss_free (C function)
@anchor{c-api/init c PyThread_tss_free}@anchor{43a}
@deffn {C の関数} void PyThread_tss_free (Py_tss_t *key)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Free the given `key' allocated by @ref{438,,PyThread_tss_alloc()}, after
first calling @ref{440,,PyThread_tss_delete()} to ensure any associated
thread locals have been unassigned. This is a no-op if the `key'
argument is @code{NULL}.

@cartouche
@quotation 注釈 
A freed key becomes a dangling pointer. You should reset the key to
@code{NULL}.
@end quotation
@end cartouche
@end deffn

@node メソッド<2>,,動的メモリ確保,スレッド固有ストレージ Thread Specific Storage TSS API
@anchor{c-api/init methods}@anchor{5552}
@subsubsection メソッド


The parameter `key' of these functions must not be @code{NULL}.  Moreover, the
behaviors of @ref{43c,,PyThread_tss_set()} and @ref{43e,,PyThread_tss_get()} are
undefined if the given @ref{cd6,,Py_tss_t} has not been initialized by
@ref{50d0,,PyThread_tss_create()}.

@geindex PyThread_tss_is_created (C function)
@anchor{c-api/init c PyThread_tss_is_created}@anchor{50d1}
@deffn {C の関数} int PyThread_tss_is_created (Py_tss_t *key)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Return a non-zero value if the given @ref{cd6,,Py_tss_t} has been initialized
by @ref{50d0,,PyThread_tss_create()}.
@end deffn

@geindex PyThread_tss_create (C function)
@anchor{c-api/init c PyThread_tss_create}@anchor{50d0}
@deffn {C の関数} int PyThread_tss_create (Py_tss_t *key)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
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 @ref{5550,,Py_tss_NEEDS_INIT}.  This function can be called
repeatedly on the same key -- calling it on an already initialized key is a
no-op and immediately returns success.
@end deffn

@geindex PyThread_tss_delete (C function)
@anchor{c-api/init c PyThread_tss_delete}@anchor{440}
@deffn {C の関数} void PyThread_tss_delete (Py_tss_t *key)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Destroy a TSS key to forget the values associated with the key across all
threads, and change the key's initialization state to uninitialized.  A
destroyed key is able to be initialized again by
@ref{50d0,,PyThread_tss_create()}. This function can be called repeatedly on
the same key -- calling it on an already destroyed key is a no-op.
@end deffn

@geindex PyThread_tss_set (C function)
@anchor{c-api/init c PyThread_tss_set}@anchor{43c}
@deffn {C の関数} int PyThread_tss_set (Py_tss_t *key, void *value)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
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.
@end deffn

@geindex PyThread_tss_get (C function)
@anchor{c-api/init c PyThread_tss_get}@anchor{43e}
@deffn {C の関数} void *PyThread_tss_get (Py_tss_t *key)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Return the void* value associated with a TSS key in the current
thread.  This returns @code{NULL} if no value is associated with the key in the
current thread.
@end deffn

@node スレッドローカルストレージ TLS API,,スレッド固有ストレージ Thread Specific Storage TSS API,スレッドローカルストレージのサポート
@anchor{c-api/init thread-local-storage-api}@anchor{cd4}@anchor{c-api/init thread-local-storage-tls-api}@anchor{5553}
@subsubsection スレッドローカルストレージ (TLS) API



バージョン 3.7 で非推奨: This API is superseded by
@ref{cd5,,Thread Specific Storage (TSS) API}.


@cartouche
@quotation 注釈 
This version of the API does not support platforms where the native TLS key
is defined in a way that cannot be safely cast to @code{int}.  On such platforms,
@ref{437,,PyThread_create_key()} will return immediately with a failure status,
and the other TLS functions will all be no-ops on such platforms.
@end quotation
@end cartouche

前述の互換性の問題により、このバージョンのAPIは新規のコードで利用すべきではありません。

@geindex PyThread_create_key (C function)
@anchor{c-api/init c PyThread_create_key}@anchor{437}
@deffn {C の関数} int PyThread_create_key ()
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyThread_delete_key (C function)
@anchor{c-api/init c PyThread_delete_key}@anchor{439}
@deffn {C の関数} void PyThread_delete_key (int key)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyThread_set_key_value (C function)
@anchor{c-api/init c PyThread_set_key_value}@anchor{43b}
@deffn {C の関数} int PyThread_set_key_value (int key, void *value)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyThread_get_key_value (C function)
@anchor{c-api/init c PyThread_get_key_value}@anchor{43d}
@deffn {C の関数} void *PyThread_get_key_value (int key)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyThread_delete_key_value (C function)
@anchor{c-api/init c PyThread_delete_key_value}@anchor{43f}
@deffn {C の関数} void PyThread_delete_key_value (int key)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex PyThread_ReInitTLS (C function)
@anchor{c-api/init c PyThread_ReInitTLS}@anchor{441}
@deffn {C の関数} void PyThread_ReInitTLS ()
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@node 同期プリミティブ<3>,Operating System Thread APIs,スレッドローカルストレージのサポート,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init synchronization-primitives}@anchor{5554}
@subsection 同期プリミティブ


The C-API provides a basic mutual exclusion lock.

@geindex PyMutex (C type)
@anchor{c-api/init c PyMutex}@anchor{484}
@deffn {C のデータ型} type PyMutex

A mutual exclusion lock.  The @code{PyMutex} should be initialized to
zero to represent the unlocked state.  For example:

@example
PyMutex mutex = @{0@};
@end example

Instances of @code{PyMutex} should not be copied or moved.  Both the
contents and address of a @code{PyMutex} are meaningful, and it must
remain at a fixed, writable location in memory.

@cartouche
@quotation 注釈 
A @code{PyMutex} currently occupies one byte, but the size should be
considered unstable.  The size may change in future Python releases
without a deprecation period.
@end quotation
@end cartouche


Added in version 3.13.

@end deffn

@geindex PyMutex_Lock (C function)
@anchor{c-api/init c PyMutex_Lock}@anchor{5d0}
@deffn {C の関数} void PyMutex_Lock (PyMutex *m)

Lock mutex `m'.  If another thread has already locked it, the calling
thread will block until the mutex is unlocked.  While blocked, the thread
will temporarily detach the @ref{4ed1,,thread state} if one exists.


Added in version 3.13.

@end deffn

@geindex PyMutex_Unlock (C function)
@anchor{c-api/init c PyMutex_Unlock}@anchor{5d1}
@deffn {C の関数} void PyMutex_Unlock (PyMutex *m)

Unlock mutex `m'. The mutex must be locked --- otherwise, the function will
issue a fatal error.


Added in version 3.13.

@end deffn

@geindex PyMutex_IsLocked (C function)
@anchor{c-api/init c PyMutex_IsLocked}@anchor{463}
@deffn {C の関数} int PyMutex_IsLocked (PyMutex *m)

Returns non-zero if the mutex `m' is currently locked, zero otherwise.

@cartouche
@quotation 注釈 
This function is intended for use in assertions and debugging only and
should not be used to make concurrency control decisions, as the lock
state may change immediately after the check.
@end quotation
@end cartouche


Added in version 3.14.

@end deffn

@menu
* Python Critical Section API:: 
* Legacy Locking APIs:: 

@end menu

@node Python Critical Section API,Legacy Locking APIs,,同期プリミティブ<3>
@anchor{c-api/init id4}@anchor{5555}@anchor{c-api/init python-critical-section-api}@anchor{5556}
@subsubsection Python Critical Section API


The critical section API provides a deadlock avoidance layer on top of
per-object locks for @ref{1f4,,free-threaded} CPython.  They are
intended to replace reliance on the @ref{474,,global interpreter lock}, and are
no-ops in versions of Python with the global interpreter lock.

Critical sections are intended to be used for custom types implemented
in C-API extensions. They should generally not be used with built-in types like
@ref{24d,,list} and @ref{183,,dict} because their public C-APIs
already use critical sections internally, with the notable
exception of @ref{198f,,PyDict_Next()}, which requires critical section
to be acquired externally.

Critical sections avoid deadlocks by implicitly suspending active critical
sections, hence, they do not provide exclusive access such as provided by
traditional locks like @ref{484,,PyMutex}.  When a critical section is started,
the per-object lock for the object is acquired. If the code executed inside the
critical section calls C-API functions then it can suspend the critical section thereby
releasing the per-object lock, so other threads can acquire the per-object lock
for the same object.

Variants that accept @ref{484,,PyMutex} pointers rather than Python objects are also
available. Use these variants to start a critical section in a situation where
there is no @ref{5df,,PyObject} -- for example, when working with a C type that
does not extend or wrap @ref{5df,,PyObject} but still needs to call into the C
API in a manner that might lead to deadlocks.

The functions and structs used by the macros are exposed for cases
where C macros are not available. They should only be used as in the
given macro expansions. Note that the sizes and contents of the structures may
change in future Python versions.

@cartouche
@quotation 注釈 
Operations that need to lock two objects at once must use
@ref{5557,,Py_BEGIN_CRITICAL_SECTION2}.  You `cannot' use nested critical
sections to lock more than one object at once, because the inner critical
section may suspend the outer critical sections.  This API does not provide
a way to lock more than two objects at once.
@end quotation
@end cartouche

使用例:

@example
static PyObject *
set_field(MyObject *self, PyObject *value)
@{
   Py_BEGIN_CRITICAL_SECTION(self);
   Py_SETREF(self->field, Py_XNewRef(value));
   Py_END_CRITICAL_SECTION();
   Py_RETURN_NONE;
@}
@end example

In the above example, @ref{799,,Py_SETREF} calls @ref{790,,Py_DECREF}, which
can call arbitrary code through an object's deallocation function.  The critical
section API avoids potential deadlocks due to reentrancy and lock ordering
by allowing the runtime to temporarily suspend the critical section if the
code triggered by the finalizer blocks and calls @ref{647,,PyEval_SaveThread()}.

@geindex Py_BEGIN_CRITICAL_SECTION (C macro)
@anchor{c-api/init c Py_BEGIN_CRITICAL_SECTION}@anchor{53ab}
@deffn {C のマクロ} Py_BEGIN_CRITICAL_SECTION (op)

Acquires the per-object lock for the object `op' and begins a
critical section.

In the free-threaded build, this macro expands to:

@example
@{
    PyCriticalSection _py_cs;
    PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))
@end example

In the default build, this macro expands to @code{@{}.


Added in version 3.13.

@end deffn

@geindex Py_BEGIN_CRITICAL_SECTION_MUTEX (C macro)
@anchor{c-api/init c Py_BEGIN_CRITICAL_SECTION_MUTEX}@anchor{5558}
@deffn {C のマクロ} Py_BEGIN_CRITICAL_SECTION_MUTEX (m)

Locks the mutex `m' and begins a critical section.

In the free-threaded build, this macro expands to:

@example
@{
     PyCriticalSection _py_cs;
     PyCriticalSection_BeginMutex(&_py_cs, m)
@end example

Note that unlike @ref{53ab,,Py_BEGIN_CRITICAL_SECTION}, there is no cast for
the argument of the macro - it must be a @ref{484,,PyMutex} pointer.

On the default build, this macro expands to @code{@{}.


Added in version 3.14.

@end deffn

@geindex Py_END_CRITICAL_SECTION (C macro)
@anchor{c-api/init c Py_END_CRITICAL_SECTION}@anchor{5559}
@deffn {C のマクロ} Py_END_CRITICAL_SECTION ()

Ends the critical section and releases the per-object lock.

In the free-threaded build, this macro expands to:

@example
    PyCriticalSection_End(&_py_cs);
@}
@end example

In the default build, this macro expands to @code{@}}.


Added in version 3.13.

@end deffn

@geindex Py_BEGIN_CRITICAL_SECTION2 (C macro)
@anchor{c-api/init c Py_BEGIN_CRITICAL_SECTION2}@anchor{5557}
@deffn {C のマクロ} Py_BEGIN_CRITICAL_SECTION2 (a, b)

Acquires the per-objects locks for the objects `a' and `b' and begins a
critical section.  The locks are acquired in a consistent order (lowest
address first) to avoid lock ordering deadlocks.

In the free-threaded build, this macro expands to:

@example
@{
    PyCriticalSection2 _py_cs2;
    PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))
@end example

In the default build, this macro expands to @code{@{}.


Added in version 3.13.

@end deffn

@geindex Py_BEGIN_CRITICAL_SECTION2_MUTEX (C macro)
@anchor{c-api/init c Py_BEGIN_CRITICAL_SECTION2_MUTEX}@anchor{555a}
@deffn {C のマクロ} Py_BEGIN_CRITICAL_SECTION2_MUTEX (m1, m2)

Locks the mutexes `m1' and `m2' and begins a critical section.

In the free-threaded build, this macro expands to:

@example
@{
     PyCriticalSection2 _py_cs2;
     PyCriticalSection2_BeginMutex(&_py_cs2, m1, m2)
@end example

Note that unlike @ref{5557,,Py_BEGIN_CRITICAL_SECTION2}, there is no cast for
the arguments of the macro - they must be @ref{484,,PyMutex} pointers.

On the default build, this macro expands to @code{@{}.


Added in version 3.14.

@end deffn

@geindex Py_END_CRITICAL_SECTION2 (C macro)
@anchor{c-api/init c Py_END_CRITICAL_SECTION2}@anchor{555b}
@deffn {C のマクロ} Py_END_CRITICAL_SECTION2 ()

Ends the critical section and releases the per-object locks.

In the free-threaded build, this macro expands to:

@example
    PyCriticalSection2_End(&_py_cs2);
@}
@end example

In the default build, this macro expands to @code{@}}.


Added in version 3.13.

@end deffn

@node Legacy Locking APIs,,Python Critical Section API,同期プリミティブ<3>
@anchor{c-api/init legacy-locking-apis}@anchor{555c}
@subsubsection Legacy Locking APIs


These APIs are obsolete since Python 3.13 with the introduction of
@ref{484,,PyMutex}.


バージョン 3.15 で変更: These APIs are now a simple wrapper around @code{PyMutex}.


@geindex PyThread_type_lock (C type)
@anchor{c-api/init c PyThread_type_lock}@anchor{555d}
@deffn {C のデータ型} type PyThread_type_lock

A pointer to a mutual exclusion lock.
@end deffn

@geindex PyLockStatus (C type)
@anchor{c-api/init c PyLockStatus}@anchor{555e}
@deffn {C のデータ型} type PyLockStatus

The result of acquiring a lock with a timeout.

@geindex PY_LOCK_FAILURE (C enumerator)
@anchor{c-api/init c PY_LOCK_FAILURE}@anchor{555f}
@deffn {C Enumerator} enumerator PY_LOCK_FAILURE

Failed to acquire the lock.
@end deffn

@geindex PY_LOCK_ACQUIRED (C enumerator)
@anchor{c-api/init c PY_LOCK_ACQUIRED}@anchor{5560}
@deffn {C Enumerator} enumerator PY_LOCK_ACQUIRED

The lock was successfully acquired.
@end deffn

@geindex PY_LOCK_INTR (C enumerator)
@anchor{c-api/init c PY_LOCK_INTR}@anchor{5561}
@deffn {C Enumerator} enumerator PY_LOCK_INTR

The lock was interrupted by a signal.
@end deffn
@end deffn

@geindex PyThread_allocate_lock (C function)
@anchor{c-api/init c PyThread_allocate_lock}@anchor{50c8}
@deffn {C の関数} @ref{555d,,PyThread_type_lock} PyThread_allocate_lock (void)
` 次に属します: @ref{775,,Stable ABI}.'
Allocate a new lock.

On success, this function returns a lock; on failure, this
function returns @code{0} without an exception set.

The caller does not need to hold an @ref{4ed1,,attached thread state}.


バージョン 3.15 で変更: This function now always uses @ref{484,,PyMutex}. In prior versions, this
would use a lock provided by the operating system.

@end deffn

@geindex PyThread_free_lock (C function)
@anchor{c-api/init c PyThread_free_lock}@anchor{50ca}
@deffn {C の関数} void PyThread_free_lock (PyThread_type_lock lock)
` 次に属します: @ref{775,,Stable ABI}.'
Destroy `lock'. The lock should not be held by any thread when calling
this.

The caller does not need to hold an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyThread_acquire_lock_timed (C function)
@anchor{c-api/init c PyThread_acquire_lock_timed}@anchor{50c7}
@deffn {C の関数} @ref{555e,,PyLockStatus} PyThread_acquire_lock_timed (PyThread_type_lock lock, long long microseconds, int intr_flag)
` 次に属します: @ref{775,,Stable ABI}.'
Acquire `lock' with a timeout.

This will wait for `microseconds' microseconds to acquire the lock. If the
timeout expires, this function returns @ref{555f,,PY_LOCK_FAILURE}.
If `microseconds' is @code{-1}, this will wait indefinitely until the lock has
been released.

If `intr_flag' is @code{1}, acquiring the lock may be interrupted by a signal,
in which case this function returns @ref{5561,,PY_LOCK_INTR}. Upon
interruption, it's generally expected that the caller makes a call to
@ref{5134,,Py_MakePendingCalls()} to propagate an exception to Python code.

If the lock is successfully acquired, this function returns
@ref{5560,,PY_LOCK_ACQUIRED}.

The caller does not need to hold an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyThread_acquire_lock (C function)
@anchor{c-api/init c PyThread_acquire_lock}@anchor{50c6}
@deffn {C の関数} int PyThread_acquire_lock (PyThread_type_lock lock, int waitflag)
` 次に属します: @ref{775,,Stable ABI}.'
Acquire `lock'.

If `waitflag' is @code{1} and another thread currently holds the lock, this
function will wait until the lock can be acquired and will always return
@code{1}.

If `waitflag' is @code{0} and another thread holds the lock, this function will
not wait and instead return @code{0}. If the lock is not held by any other
thread, then this function will acquire it and return @code{1}.

Unlike @ref{50c7,,PyThread_acquire_lock_timed()}, acquiring the lock cannot be
interrupted by a signal.

The caller does not need to hold an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyThread_release_lock (C function)
@anchor{c-api/init c PyThread_release_lock}@anchor{50ce}
@deffn {C の関数} int PyThread_release_lock (PyThread_type_lock lock)
` 次に属します: @ref{775,,Stable ABI}.'
Release `lock'. If `lock' is not held, then this function issues a
fatal error.

The caller does not need to hold an @ref{4ed1,,attached thread state}.
@end deffn

@node Operating System Thread APIs,,同期プリミティブ<3>,初期化 initialization 、終了処理 finalization 、スレッド
@anchor{c-api/init operating-system-thread-apis}@anchor{5562}
@subsection Operating System Thread APIs


@geindex PYTHREAD_INVALID_THREAD_ID (C macro)
@anchor{c-api/init c PYTHREAD_INVALID_THREAD_ID}@anchor{5563}
@deffn {C のマクロ} PYTHREAD_INVALID_THREAD_ID

Sentinel value for an invalid thread ID.

This is currently equivalent to @code{(unsigned long)-1}.
@end deffn

@geindex PyThread_start_new_thread (C function)
@anchor{c-api/init c PyThread_start_new_thread}@anchor{1e2b}
@deffn {C の関数} unsigned long PyThread_start_new_thread (void (*func)(void*), void *arg)
` 次に属します: @ref{775,,Stable ABI}.'
Start function `func' in a new thread with argument `arg'.
The resulting thread is not intended to be joined.

`func' must not be @code{NULL}, but `arg' may be @code{NULL}.

On success, this function returns the identifier of the new thread; on failure,
this returns @ref{5563,,PYTHREAD_INVALID_THREAD_ID}.

The caller does not need to hold an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyThread_get_thread_ident (C function)
@anchor{c-api/init c PyThread_get_thread_ident}@anchor{50cc}
@deffn {C の関数} unsigned long PyThread_get_thread_ident (void)
` 次に属します: @ref{775,,Stable ABI}.'
Return the identifier of the current thread, which will never be zero.

This function cannot fail, and the caller does not need to hold an
@ref{4ed1,,attached thread state}.


@subsubheading 参考


@ref{1372,,threading.get_ident()}

@end deffn

@geindex PyThread_GetInfo (C function)
@anchor{c-api/init c PyThread_GetInfo}@anchor{50c5}
@deffn {C の関数} @ref{5df,,PyObject} *PyThread_GetInfo (void)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.3 より).'
Get general information about the current thread in the form of a
@ref{13d7,,struct sequence} object. This information is
accessible as @ref{1368,,sys.thread_info} in Python.

On success, this returns a new @ref{5e2,,strong reference} to the thread
information; on failure, this returns @code{NULL} with an exception set.

The caller must hold an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PY_HAVE_THREAD_NATIVE_ID (C macro)
@anchor{c-api/init c PY_HAVE_THREAD_NATIVE_ID}@anchor{5564}
@deffn {C のマクロ} PY_HAVE_THREAD_NATIVE_ID

This macro is defined when the system supports native thread IDs.
@end deffn

@geindex PyThread_get_thread_native_id (C function)
@anchor{c-api/init c PyThread_get_thread_native_id}@anchor{1ba2}
@deffn {C の関数} unsigned long PyThread_get_thread_native_id (void)
` 次に属します: @ref{775,,Stable ABI} on platforms with native thread IDs.'
Get the native identifier of the current thread as it was assigned by the operating
system's kernel, which will never be less than zero.

This function is only available when @ref{5564,,PY_HAVE_THREAD_NATIVE_ID} is
defined.

This function cannot fail, and the caller does not need to hold an
@ref{4ed1,,attached thread state}.


@subsubheading 参考


@ref{c32,,threading.get_native_id()}

@end deffn

@geindex PyThread_exit_thread (C function)
@anchor{c-api/init c PyThread_exit_thread}@anchor{50c9}
@deffn {C の関数} void PyThread_exit_thread (void)
` 次に属します: @ref{775,,Stable ABI}.'
Terminate the current thread. This function is generally considered unsafe
and should be avoided. It is kept solely for backwards compatibility.

This function is only safe to call if all functions in the full call
stack are written to safely allow it.

@cartouche
@quotation 警告 
If the current system uses POSIX threads (also known as "pthreads"),
this calls @code{pthread_exit(3)@footnote{https://manpages.debian.org/pthread_exit(3)}}, which attempts to unwind the stack
and call C++ destructors on some libc implementations. However, if a
@code{noexcept} function is reached, it may terminate the process.
Other systems, such as macOS, do unwinding.

On Windows, this function calls @code{_endthreadex()}, which kills the thread
without calling C++ destructors.

In any case, there is a risk of corruption on the thread's stack.
@end quotation
@end cartouche


バージョン 3.14 で非推奨.

@end deffn

@geindex PyThread_init_thread (C function)
@anchor{c-api/init c PyThread_init_thread}@anchor{50cd}
@deffn {C の関数} void PyThread_init_thread (void)
` 次に属します: @ref{775,,Stable ABI}.'
Initialize @code{PyThread*} APIs. Python executes this function automatically,
so there's little need to call it from an extension module.
@end deffn

@geindex PyThread_set_stacksize (C function)
@anchor{c-api/init c PyThread_set_stacksize}@anchor{50cf}
@deffn {C の関数} int PyThread_set_stacksize (size_t size)
` 次に属します: @ref{775,,Stable ABI}.'
Set the stack size of the current thread to `size' bytes.

This function returns @code{0} on success, @code{-1} if `size' is invalid, or
@code{-2} if the system does not support changing the stack size. This function
does not set exceptions.

The caller does not need to hold an @ref{4ed1,,attached thread state}.
@end deffn

@geindex PyThread_get_stacksize (C function)
@anchor{c-api/init c PyThread_get_stacksize}@anchor{50cb}
@deffn {C の関数} size_t PyThread_get_stacksize (void)
` 次に属します: @ref{775,,Stable ABI}.'
Return the stack size of the current thread in bytes, or @code{0} if the system's
default stack size is in use.

The caller does not need to hold an @ref{4ed1,,attached thread state}.
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python 初期化設定,メモリ管理,初期化 initialization 、終了処理 finalization 、スレッド,Python/C API リファレンスマニュアル
@anchor{c-api/init_config doc}@anchor{5565}@anchor{c-api/init_config init-config}@anchor{646}@anchor{c-api/init_config python-initialization-configuration}@anchor{5566}@anchor{c-api/init_config translation-repo}@anchor{5567}
@section Python 初期化設定


@menu
* PyInitConfig C API:: 
* Configuration Options:: 
* Runtime Python configuration API:: 
* PyConfig C API:: 
* Py_GetArgcArgv(): Py_GetArgcArgv. 
* Delaying main module execution:: 

@end menu

@node PyInitConfig C API,Configuration Options,,Python 初期化設定
@anchor{c-api/init_config pyinitconfig-api}@anchor{379}@anchor{c-api/init_config pyinitconfig-c-api}@anchor{5568}
@subsection PyInitConfig C API



Added in version 3.14.


Python は @ref{386,,Py_InitializeFromInitConfig()} で初期化できます。

@ref{bbc,,Py_RunMain()} 関数は、カスタマイズされた Python プログラムを書くために使用できます。

@ref{550e,,Initialization@comma{} Finalization@comma{} and Threads} も参照してください。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 741
PEP 741@footnote{https://peps.python.org/pep-0741/} "Python Configuration C API".


@menu
* 使用例: 使用例<54>. 
* 設定の作成:: 
* エラー処理: エラー処理<2>. 
* Get Options:: 
* Set Options:: 
* Module:: 
* Initialize Python:: 

@end menu

@node 使用例<54>,設定の作成,,PyInitConfig C API
@anchor{c-api/init_config example}@anchor{5569}
@subsubsection 使用例


常に @ref{508,,Python 開発モード} が有効化された状態で実行されるカスタマイズされた Python の例。エラー時は @code{-1} を返します:

@example
int init_python(void)
@{
    PyInitConfig *config = PyInitConfig_Create();
    if (config == NULL) @{
        printf("PYTHON INIT ERROR: memory allocation failed\n");
        return -1;
    @}

    // Python 開発モードを有効化
    if (PyInitConfig_SetInt(config, "dev_mode", 1) < 0) @{
        goto error;
    @}

    // Python を設定付きで初期化
    if (Py_InitializeFromInitConfig(config) < 0) @{
        goto error;
    @}
    PyInitConfig_Free(config);
    return 0;

error:
    @{
        // エラーメッセージを表示する。
        //
        // この稀な括弧スタイルは、変数宣言を指す goto ターゲットを
        // 作ることができないために使用されています。

        const char *err_msg;
        (void)PyInitConfig_GetError(config, &err_msg);
        printf("PYTHON INIT ERROR: %s\n", err_msg);
        PyInitConfig_Free(config);
        return -1;
    @}
@}
@end example

@node 設定の作成,エラー処理<2>,使用例<54>,PyInitConfig C API
@anchor{c-api/init_config create-config}@anchor{556a}
@subsubsection 設定の作成


@geindex PyInitConfig (C struct)
@anchor{c-api/init_config c PyInitConfig}@anchor{556b}
@deffn {C Struct} struct PyInitConfig

Python の初期化を構成するための不透明な構造体です。
@end deffn

@geindex PyInitConfig_Create (C function)
@anchor{c-api/init_config c PyInitConfig_Create}@anchor{387}
@deffn {C の関数} @ref{556b,,PyInitConfig} *PyInitConfig_Create (void)

Create a new initialization configuration using @ref{556c,,Isolated Configuration} default values.

It must be freed by @ref{388,,PyInitConfig_Free()}.

Return @code{NULL} on memory allocation failure.
@end deffn

@geindex PyInitConfig_Free (C function)
@anchor{c-api/init_config c PyInitConfig_Free}@anchor{388}
@deffn {C の関数} void PyInitConfig_Free (PyInitConfig *config)

Free memory of the initialization configuration `config'.

If `config' is @code{NULL}, no operation is performed.
@end deffn

@node エラー処理<2>,Get Options,設定の作成,PyInitConfig C API
@anchor{c-api/init_config error-handling}@anchor{556d}
@subsubsection エラー処理


@geindex PyInitConfig_GetError (C function)
@anchor{c-api/init_config c PyInitConfig_GetError}@anchor{38a}
@deffn {C の関数} int PyInitConfig_GetError (PyInitConfig *config, const char **err_msg)

Get the `config' error message.


@itemize *

@item 
Set `*err_msg' and return @code{1} if an error is set.

@item 
Set `*err_msg' to @code{NULL} and return @code{0} otherwise.
@end itemize

An error message is a UTF-8 encoded string.

If `config' has an exit code, format the exit code as an error
message.

The error message remains valid until another @code{PyInitConfig}
function is called with `config'. The caller doesn't have to free the
error message.
@end deffn

@geindex PyInitConfig_GetExitCode (C function)
@anchor{c-api/init_config c PyInitConfig_GetExitCode}@anchor{38b}
@deffn {C の関数} int PyInitConfig_GetExitCode (PyInitConfig *config, int *exitcode)

Get the `config' exit code.


@itemize *

@item 
Set `*exitcode' and return @code{1} if `config' has an exit code set.

@item 
Return @code{0} if `config' has no exit code set.
@end itemize

Only the @code{Py_InitializeFromInitConfig()} function can set an exit
code if the @code{parse_argv} option is non-zero.

An exit code can be set when parsing the command line failed (exit
code @code{2}) or when a command line option asks to display the command
line help (exit code @code{0}).
@end deffn

@node Get Options,Set Options,エラー処理<2>,PyInitConfig C API
@anchor{c-api/init_config get-options}@anchor{556e}
@subsubsection Get Options


The configuration option `name' parameter must be a non-NULL null-terminated
UTF-8 encoded string. See @ref{556f,,Configuration Options}.

@geindex PyInitConfig_HasOption (C function)
@anchor{c-api/init_config c PyInitConfig_HasOption}@anchor{38f}
@deffn {C の関数} int PyInitConfig_HasOption (PyInitConfig *config, const char *name)

Test if the configuration has an option called `name'.

Return @code{1} if the option exists, or return @code{0} otherwise.
@end deffn

@geindex PyInitConfig_GetInt (C function)
@anchor{c-api/init_config c PyInitConfig_GetInt}@anchor{38c}
@deffn {C の関数} int PyInitConfig_GetInt (PyInitConfig *config, const char *name, int64_t *value)

Get an integer configuration option.


@itemize *

@item 
Set `*value', and return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.
@end itemize
@end deffn

@geindex PyInitConfig_GetStr (C function)
@anchor{c-api/init_config c PyInitConfig_GetStr}@anchor{38d}
@deffn {C の関数} int PyInitConfig_GetStr (PyInitConfig *config, const char *name, char **value)

Get a string configuration option as a null-terminated UTF-8
encoded string.


@itemize *

@item 
Set `*value', and return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.
@end itemize

`*value' can be set to @code{NULL} if the option is an optional string and the
option is unset.

On success, the string must be released with @code{free(value)} if it's not
@code{NULL}.
@end deffn

@geindex PyInitConfig_GetStrList (C function)
@anchor{c-api/init_config c PyInitConfig_GetStrList}@anchor{38e}
@deffn {C の関数} int PyInitConfig_GetStrList (PyInitConfig *config, const char *name, size_t *length, char ***items)

Get a string list configuration option as an array of
null-terminated UTF-8 encoded strings.


@itemize *

@item 
Set `*length' and `*value', and return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.
@end itemize

On success, the string list must be released with
@code{PyInitConfig_FreeStrList(length, items)}.
@end deffn

@geindex PyInitConfig_FreeStrList (C function)
@anchor{c-api/init_config c PyInitConfig_FreeStrList}@anchor{389}
@deffn {C の関数} void PyInitConfig_FreeStrList (size_t length, char **items)

Free memory of a string list created by
@code{PyInitConfig_GetStrList()}.
@end deffn

@node Set Options,Module,Get Options,PyInitConfig C API
@anchor{c-api/init_config set-options}@anchor{5570}
@subsubsection Set Options


The configuration option `name' parameter must be a non-NULL null-terminated
UTF-8 encoded string. See @ref{556f,,Configuration Options}.

Some configuration options have side effects on other options. This logic is
only implemented when @code{Py_InitializeFromInitConfig()} is called, not by the
"Set" functions below. For example, setting @code{dev_mode} to @code{1} does not set
@code{faulthandler} to @code{1}.

@geindex PyInitConfig_SetInt (C function)
@anchor{c-api/init_config c PyInitConfig_SetInt}@anchor{390}
@deffn {C の関数} int PyInitConfig_SetInt (PyInitConfig *config, const char *name, int64_t value)

Set an integer configuration option.


@itemize *

@item 
Return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.
@end itemize
@end deffn

@geindex PyInitConfig_SetStr (C function)
@anchor{c-api/init_config c PyInitConfig_SetStr}@anchor{391}
@deffn {C の関数} int PyInitConfig_SetStr (PyInitConfig *config, const char *name, const char *value)

Set a string configuration option from a null-terminated UTF-8
encoded string. The string is copied.


@itemize *

@item 
Return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.
@end itemize
@end deffn

@geindex PyInitConfig_SetStrList (C function)
@anchor{c-api/init_config c PyInitConfig_SetStrList}@anchor{392}
@deffn {C の関数} int PyInitConfig_SetStrList (PyInitConfig *config, const char *name, size_t length, char *const *items)

Set a string list configuration option from an array of
null-terminated UTF-8 encoded strings. The string list is copied.


@itemize *

@item 
Return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.
@end itemize
@end deffn

@node Module,Initialize Python,Set Options,PyInitConfig C API
@anchor{c-api/init_config module}@anchor{5571}
@subsubsection Module


@geindex PyInitConfig_AddModule (C function)
@anchor{c-api/init_config c PyInitConfig_AddModule}@anchor{37b}
@deffn {C の関数} int PyInitConfig_AddModule (PyInitConfig *config, const char *name, PyObject *(*initfunc)(void))

Add a built-in extension module to the table of built-in modules.

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.


@itemize *

@item 
Return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.
@end itemize

If Python is initialized multiple times, @code{PyInitConfig_AddModule()} must
be called at each Python initialization.

Similar to the @ref{1b1c,,PyImport_AppendInittab()} function.
@end deffn

@node Initialize Python,,Module,PyInitConfig C API
@anchor{c-api/init_config initialize-python}@anchor{5572}
@subsubsection Initialize Python


@geindex Py_InitializeFromInitConfig (C function)
@anchor{c-api/init_config c Py_InitializeFromInitConfig}@anchor{386}
@deffn {C の関数} int Py_InitializeFromInitConfig (PyInitConfig *config)

Initialize Python from the initialization configuration.


@itemize *

@item 
Return @code{0} on success.

@item 
Set an error in `config' and return @code{-1} on error.

@item 
Set an exit code in `config' and return @code{-1} if Python wants to
exit.
@end itemize

See @code{PyInitConfig_GetExitcode()} for the exit code case.
@end deffn

@node Configuration Options,Runtime Python configuration API,PyInitConfig C API,Python 初期化設定
@anchor{c-api/init_config configuration-options}@anchor{5573}@anchor{c-api/init_config pyinitconfig-opts}@anchor{556f}
@subsection Configuration Options



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

オプション

@tab

PyConfig/PyPreConfig member

@tab

型

@tab

可視性

@item

@code{"allocator"}

@tab

@ref{5574,,allocator}

@tab

@code{int}

@tab

読み出し専用

@item

@code{"argv"}

@tab

@ref{3f1,,argv}

@tab

@code{list[str]}

@tab

Public

@item

@code{"base_exec_prefix"}

@tab

@ref{5575,,base_exec_prefix}

@tab

@code{str}

@tab

Public

@item

@code{"base_executable"}

@tab

@ref{5576,,base_executable}

@tab

@code{str}

@tab

Public

@item

@code{"base_prefix"}

@tab

@ref{5577,,base_prefix}

@tab

@code{str}

@tab

Public

@item

@code{"buffered_stdio"}

@tab

@ref{411,,buffered_stdio}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"bytes_warning"}

@tab

@ref{407,,bytes_warning}

@tab

@code{int}

@tab

Public

@item

@code{"check_hash_pycs_mode"}

@tab

@ref{5578,,check_hash_pycs_mode}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"code_debug_ranges"}

@tab

@ref{5579,,code_debug_ranges}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"coerce_c_locale"}

@tab

@ref{557a,,coerce_c_locale}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"coerce_c_locale_warn"}

@tab

@ref{557b,,coerce_c_locale_warn}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"configure_c_stdio"}

@tab

@ref{557c,,configure_c_stdio}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"configure_locale"}

@tab

@ref{557d,,configure_locale}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"cpu_count"}

@tab

@ref{557e,,cpu_count}

@tab

@code{int}

@tab

Public

@item

@code{"dev_mode"}

@tab

@ref{557f,,dev_mode}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"dump_refs"}

@tab

@ref{5580,,dump_refs}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"dump_refs_file"}

@tab

@ref{5581,,dump_refs_file}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"exec_prefix"}

@tab

@ref{5582,,exec_prefix}

@tab

@code{str}

@tab

Public

@item

@code{"executable"}

@tab

@ref{645,,executable}

@tab

@code{str}

@tab

Public

@item

@code{"faulthandler"}

@tab

@ref{5583,,faulthandler}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"filesystem_encoding"}

@tab

@ref{41b,,filesystem_encoding}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"filesystem_errors"}

@tab

@ref{41c,,filesystem_errors}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"hash_seed"}

@tab

@ref{414,,hash_seed}

@tab

@code{int}

@tab

読み出し専用

@item

@code{"home"}

@tab

@ref{3f3,,home}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"import_time"}

@tab

@ref{5584,,import_time}

@tab

@code{int}

@tab

読み出し専用

@item

@code{"inspect"}

@tab

@ref{401,,inspect}

@tab

@code{bool}

@tab

Public

@item

@code{"install_signal_handlers"}

@tab

@ref{abb,,install_signal_handlers}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"int_max_str_digits"}

@tab

@ref{5585,,int_max_str_digits}

@tab

@code{int}

@tab

Public

@item

@code{"interactive"}

@tab

@ref{3ff,,interactive}

@tab

@code{bool}

@tab

Public

@item

@code{"isolated"}

@tab

@ref{416,,isolated}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"legacy_windows_fs_encoding"}

@tab

@ref{418,,legacy_windows_fs_encoding}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"legacy_windows_stdio"}

@tab

@ref{41a,,legacy_windows_stdio}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"malloc_stats"}

@tab

@ref{5586,,malloc_stats}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"module_search_paths"}

@tab

@ref{643,,module_search_paths}

@tab

@code{list[str]}

@tab

Public

@item

@code{"optimization_level"}

@tab

@ref{403,,optimization_level}

@tab

@code{int}

@tab

Public

@item

@code{"orig_argv"}

@tab

@ref{a94,,orig_argv}

@tab

@code{list[str]}

@tab

読み出し専用

@item

@code{"parse_argv"}

@tab

@ref{1cf1,,parse_argv}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"parser_debug"}

@tab

@ref{3f9,,parser_debug}

@tab

@code{bool}

@tab

Public

@item

@code{"pathconfig_warnings"}

@tab

@ref{409,,pathconfig_warnings}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"perf_profiling"}

@tab

@ref{5587,,perf_profiling}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"platlibdir"}

@tab

@ref{1d21,,platlibdir}

@tab

@code{str}

@tab

Public

@item

@code{"prefix"}

@tab

@ref{5588,,prefix}

@tab

@code{str}

@tab

Public

@item

@code{"program_name"}

@tab

@ref{3f2,,program_name}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"pycache_prefix"}

@tab

@ref{5589,,pycache_prefix}

@tab

@code{str}

@tab

Public

@item

@code{"quiet"}

@tab

@ref{3fd,,quiet}

@tab

@code{bool}

@tab

Public

@item

@code{"run_command"}

@tab

@ref{5519,,run_command}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"run_filename"}

@tab

@ref{551a,,run_filename}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"run_module"}

@tab

@ref{551b,,run_module}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"run_presite"}

@tab

@ref{558a,,run_presite}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"safe_path"}

@tab

@ref{977,,safe_path}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"show_ref_count"}

@tab

@ref{558b,,show_ref_count}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"site_import"}

@tab

@ref{405,,site_import}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"skip_source_first_line"}

@tab

@ref{558c,,skip_source_first_line}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"stdio_encoding"}

@tab

@ref{644,,stdio_encoding}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"stdio_errors"}

@tab

@ref{4928,,stdio_errors}

@tab

@code{str}

@tab

読み出し専用

@item

@code{"stdlib_dir"}

@tab

@ref{558d,,stdlib_dir}

@tab

@code{str}

@tab

Public

@item

@code{"tracemalloc"}

@tab

@ref{558e,,tracemalloc}

@tab

@code{int}

@tab

読み出し専用

@item

@code{"use_environment"}

@tab

@ref{40b,,use_environment}

@tab

@code{bool}

@tab

Public

@item

@code{"use_frozen_modules"}

@tab

@ref{558f,,use_frozen_modules}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"use_hash_seed"}

@tab

@ref{413,,use_hash_seed}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"use_system_logger"}

@tab

@ref{2271,,use_system_logger}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"user_site_directory"}

@tab

@ref{40f,,user_site_directory}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"utf8_mode"}

@tab

@ref{41d,,utf8_mode}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"verbose"}

@tab

@ref{3fb,,verbose}

@tab

@code{int}

@tab

Public

@item

@code{"warn_default_encoding"}

@tab

@ref{5590,,warn_default_encoding}

@tab

@code{bool}

@tab

読み出し専用

@item

@code{"warnoptions"}

@tab

@ref{641,,warnoptions}

@tab

@code{list[str]}

@tab

Public

@item

@code{"write_bytecode"}

@tab

@ref{40d,,write_bytecode}

@tab

@code{bool}

@tab

Public

@item

@code{"xoptions"}

@tab

@ref{642,,xoptions}

@tab

@code{dict[str, str]}

@tab

Public

@item

@code{"_pystats"}

@tab

@ref{5591,,_pystats}

@tab

@code{bool}

@tab

読み出し専用

@end multitable


Visibility:


@itemize *

@item 
Public: Can be retrieved by @ref{37c,,PyConfig_Get()} and set by
@ref{37d,,PyConfig_Set()}.

@item 
Read-only: Can be retrieved by @ref{37c,,PyConfig_Get()}, but cannot be set by
@ref{37d,,PyConfig_Set()}.
@end itemize

@node Runtime Python configuration API,PyConfig C API,Configuration Options,Python 初期化設定
@anchor{c-api/init_config runtime-python-configuration-api}@anchor{5592}
@subsection Runtime Python configuration API


At runtime, it's possible to get and set configuration options using
@ref{37c,,PyConfig_Get()} and  @ref{37d,,PyConfig_Set()} functions.

The configuration option `name' parameter must be a non-NULL null-terminated
UTF-8 encoded string. See @ref{556f,,Configuration Options}.

Some options are read from the @ref{df,,sys} attributes. For example, the option
@code{"argv"} is read from @ref{147c,,sys.argv}.

@geindex PyConfig_Get (C function)
@anchor{c-api/init_config c PyConfig_Get}@anchor{37c}
@deffn {C の関数} @ref{5df,,PyObject} *PyConfig_Get (const char *name)

Get the current runtime value of a configuration option as a Python object.


@itemize *

@item 
Return a new reference on success.

@item 
Set an exception and return @code{NULL} on error.
@end itemize

The object type depends on the configuration option. It can be:


@itemize *

@item 
@code{bool}

@item 
@code{int}

@item 
@code{str}

@item 
@code{list[str]}

@item 
@code{dict[str, str]}
@end itemize

The caller must have an @ref{4ed1,,attached thread state}. The function cannot
be called before Python initialization nor after Python finalization.


Added in version 3.14.

@end deffn

@geindex PyConfig_GetInt (C function)
@anchor{c-api/init_config c PyConfig_GetInt}@anchor{384}
@deffn {C の関数} int PyConfig_GetInt (const char *name, int *value)

Similar to @ref{37c,,PyConfig_Get()}, but get the value as a C int.


@itemize *

@item 
Return @code{0} on success.

@item 
Set an exception and return @code{-1} on error.
@end itemize


Added in version 3.14.

@end deffn

@geindex PyConfig_Names (C function)
@anchor{c-api/init_config c PyConfig_Names}@anchor{385}
@deffn {C の関数} @ref{5df,,PyObject} *PyConfig_Names (void)

Get all configuration option names as a @code{frozenset}.


@itemize *

@item 
Return a new reference on success.

@item 
Set an exception and return @code{NULL} on error.
@end itemize

The caller must have an @ref{4ed1,,attached thread state}. The function cannot
be called before Python initialization nor after Python finalization.


Added in version 3.14.

@end deffn

@geindex PyConfig_Set (C function)
@anchor{c-api/init_config c PyConfig_Set}@anchor{37d}
@deffn {C の関数} int PyConfig_Set (const char *name, PyObject *value)

Set the current runtime value of a configuration option.


@itemize *

@item 
Raise a @ref{2ec,,ValueError} if there is no option `name'.

@item 
Raise a @ref{2ec,,ValueError} if `value' is an invalid value.

@item 
Raise a @ref{2ec,,ValueError} if the option is read-only (cannot be set).

@item 
Raise a @ref{198,,TypeError} if `value' has not the proper type.
@end itemize

The caller must have an @ref{4ed1,,attached thread state}. The function cannot
be called before Python initialization nor after Python finalization.

Raises an @ref{1c6e,,auditing event} @code{cpython.PyConfig_Set} with arguments @code{name}, @code{value}.


Added in version 3.14.

@end deffn

@node PyConfig C API,Py_GetArgcArgv,Runtime Python configuration API,Python 初期化設定
@anchor{c-api/init_config pyconfig-api}@anchor{37a}@anchor{c-api/init_config pyconfig-c-api}@anchor{5593}
@subsection PyConfig C API



Added in version 3.8.


Pythonは @ref{3f6,,Py_InitializeFromConfig()} と @ref{3f7,,PyConfig}  構造体を使って初期化できます。@ref{41e,,Py_PreInitialize()} と  @ref{ba3,,PyPreConfig}  構造体によって事前に初期化できます。

設定には二つの種類があります:


@itemize *

@item 
@ref{551c,,Python Configuration} は、通常の Python と同じ振る舞いをするカスタマイズされた Python を構築するために使用されます。例えば、環境変数やコマンドライン引数がPythonを設定するために使用されます。

@item 
The @ref{556c,,Isolated Configuration} can be used to embed
Python into an application. It isolates Python from the system. For example,
environment variables are ignored, the LC_CTYPE locale is left unchanged and
no signal handler is registered.
@end itemize

@ref{bbc,,Py_RunMain()} 関数は、カスタマイズされた Python プログラムを書くために使用できます。

@ref{550e,,Initialization@comma{} Finalization@comma{} and Threads} も参照してください。


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 587
PEP 587@footnote{https://peps.python.org/pep-0587/} "Python 初期化設定"


@menu
* 使用例: 使用例<55>. 
* PyWideStringList:: 
* PyStatus:: 
* PyPreConfig:: 
* Preinitialize Python with PyPreConfig:: 
* PyConfig:: 
* Initialization with PyConfig:: 
* Isolated Configuration:: 
* Python Configuration:: 
* Python Path Configuration:: 

@end menu

@node 使用例<55>,PyWideStringList,,PyConfig C API
@anchor{c-api/init_config id1}@anchor{5594}
@subsubsection 使用例


Example of customized Python always running in isolated mode:

@example
int main(int argc, char **argv)
@{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);
    config.isolated = 1;

    /* Decode command line arguments.
       Implicitly preinitialize Python (in isolated mode). */
    status = PyConfig_SetBytesArgv(&config, argc, argv);
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}
    PyConfig_Clear(&config);

    return Py_RunMain();

exception:
    PyConfig_Clear(&config);
    if (PyStatus_IsExit(status)) @{
        return status.exitcode;
    @}
    /* Display the error message and exit the process with
       non-zero exit code */
    Py_ExitStatusException(status);
@}
@end example

@node PyWideStringList,PyStatus,使用例<55>,PyConfig C API
@anchor{c-api/init_config pywidestringlist}@anchor{5595}
@subsubsection PyWideStringList


@geindex PyWideStringList (C type)
@anchor{c-api/init_config c PyWideStringList}@anchor{ba5}
@deffn {C のデータ型} type PyWideStringList

@code{wchar_t*} 文字列のリスト。

`length' が非ゼロの場合は、`items' は非 @code{NULL} かつすべての文字列は非 @code{NULL} でなければなりません。

メソッド:

@geindex PyWideStringList_Append (C function)
@anchor{c-api/init_config c PyWideStringList_Append}@anchor{bb6}
@deffn {C の関数} @ref{ba4,,PyStatus} PyWideStringList_Append (PyWideStringList *list, const wchar_t *item)

`item' を `list' に追加します。

Python must be preinitialized to call this function.
@end deffn

@geindex PyWideStringList_Insert (C function)
@anchor{c-api/init_config c PyWideStringList_Insert}@anchor{bb7}
@deffn {C の関数} @ref{ba4,,PyStatus} PyWideStringList_Insert (PyWideStringList *list, Py_ssize_t index, const wchar_t *item)

`item' を `list' の `index' の位置に挿入します。

`index' が `list' の長さ以上の場合、`item' を `list' の末尾に追加します。

`index' must be greater than or equal to @code{0}.

Python must be preinitialized to call this function.
@end deffn

構造体フィールド:

@geindex PyWideStringList.length (C member)
@anchor{c-api/init_config c PyWideStringList length}@anchor{5596}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} length

リストの長さ。
@end deffn

@geindex PyWideStringList.items (C member)
@anchor{c-api/init_config c PyWideStringList items}@anchor{5597}
@deffn {C のメンバ変数} wchar_t **items

リストの要素。
@end deffn
@end deffn

@node PyStatus,PyPreConfig,PyWideStringList,PyConfig C API
@anchor{c-api/init_config pystatus}@anchor{5598}
@subsubsection PyStatus


@geindex PyStatus (C type)
@anchor{c-api/init_config c PyStatus}@anchor{ba4}
@deffn {C のデータ型} type PyStatus

初期化関数のステータス(成功、エラー、終了)を格納する構造体です。

エラー時には、エラーを生成したC関数の名前を格納できます。

構造体フィールド:

@geindex PyStatus.exitcode (C member)
@anchor{c-api/init_config c PyStatus exitcode}@anchor{5599}
@deffn {C のメンバ変数} int exitcode

終了コード。@code{exit()} の引数として渡されます。
@end deffn

@geindex PyStatus.err_msg (C member)
@anchor{c-api/init_config c PyStatus err_msg}@anchor{559a}
@deffn {C のメンバ変数} const char *err_msg

エラーメッセージ。
@end deffn

@geindex PyStatus.func (C member)
@anchor{c-api/init_config c PyStatus func}@anchor{559b}
@deffn {C のメンバ変数} const char *func

エラーを生成した関数の名前で、@code{NULL} になりえます。
@end deffn

ステータスを生成する関数:

@geindex PyStatus_Ok (C function)
@anchor{c-api/init_config c PyStatus_Ok}@anchor{bb5}
@deffn {C の関数} @ref{ba4,,PyStatus} PyStatus_Ok (void)

成功。
@end deffn

@geindex PyStatus_Error (C function)
@anchor{c-api/init_config c PyStatus_Error}@anchor{baf}
@deffn {C の関数} @ref{ba4,,PyStatus} PyStatus_Error (const char *err_msg)

メッセージとともにエラーを初期化します。

`err_msg' must not be @code{NULL}.
@end deffn

@geindex PyStatus_NoMemory (C function)
@anchor{c-api/init_config c PyStatus_NoMemory}@anchor{bb4}
@deffn {C の関数} @ref{ba4,,PyStatus} PyStatus_NoMemory (void)

メモリ割り当ての失敗(メモリ不足)。
@end deffn

@geindex PyStatus_Exit (C function)
@anchor{c-api/init_config c PyStatus_Exit}@anchor{bb1}
@deffn {C の関数} @ref{ba4,,PyStatus} PyStatus_Exit (int exitcode)

指定した終了コードでPythonを終了します。
@end deffn

ステータスを扱う関数:

@geindex PyStatus_Exception (C function)
@anchor{c-api/init_config c PyStatus_Exception}@anchor{bb0}
@deffn {C の関数} int PyStatus_Exception (PyStatus status)

Is the status an error or an exit? If true, the exception must be
handled; by calling @ref{bb9,,Py_ExitStatusException()} for example.
@end deffn

@geindex PyStatus_IsError (C function)
@anchor{c-api/init_config c PyStatus_IsError}@anchor{bb2}
@deffn {C の関数} int PyStatus_IsError (PyStatus status)

Is the result an error?
@end deffn

@geindex PyStatus_IsExit (C function)
@anchor{c-api/init_config c PyStatus_IsExit}@anchor{bb3}
@deffn {C の関数} int PyStatus_IsExit (PyStatus status)

Is the result an exit?
@end deffn

@geindex Py_ExitStatusException (C function)
@anchor{c-api/init_config c Py_ExitStatusException}@anchor{bb9}
@deffn {C の関数} void Py_ExitStatusException (PyStatus status)

Call @code{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 @code{PyStatus_Exception(status)} is non-zero.
@end deffn
@end deffn

@cartouche
@quotation 注釈 
Internally, Python uses macros which set @code{PyStatus.func},
whereas functions to create a status set @code{func} to @code{NULL}.
@end quotation
@end cartouche

以下はプログラム例です:

@example
PyStatus alloc(void **ptr, size_t size)
@{
    *ptr = PyMem_RawMalloc(size);
    if (*ptr == NULL) @{
        return PyStatus_NoMemory();
    @}
    return PyStatus_Ok();
@}

int main(int argc, char **argv)
@{
    void *ptr;
    PyStatus status = alloc(&ptr, 16);
    if (PyStatus_Exception(status)) @{
        Py_ExitStatusException(status);
    @}
    PyMem_Free(ptr);
    return 0;
@}
@end example

@node PyPreConfig,Preinitialize Python with PyPreConfig,PyStatus,PyConfig C API
@anchor{c-api/init_config pypreconfig}@anchor{559c}
@subsubsection PyPreConfig


@geindex PyPreConfig (C type)
@anchor{c-api/init_config c PyPreConfig}@anchor{ba3}
@deffn {C のデータ型} type PyPreConfig

Structure used to preinitialize Python.

Function to initialize a preconfiguration:

@geindex PyPreConfig_InitPythonConfig (C function)
@anchor{c-api/init_config c PyPreConfig_InitPythonConfig}@anchor{bae}
@deffn {C の関数} void PyPreConfig_InitPythonConfig (PyPreConfig *preconfig)

Initialize the preconfiguration with @ref{551c,,Python Configuration}.
@end deffn

@geindex PyPreConfig_InitIsolatedConfig (C function)
@anchor{c-api/init_config c PyPreConfig_InitIsolatedConfig}@anchor{bad}
@deffn {C の関数} void PyPreConfig_InitIsolatedConfig (PyPreConfig *preconfig)

Initialize the preconfiguration with @ref{556c,,Isolated Configuration}.
@end deffn

構造体フィールド:

@geindex PyPreConfig.allocator (C member)
@anchor{c-api/init_config c PyPreConfig allocator}@anchor{5574}
@deffn {C のメンバ変数} int allocator

Name of the Python memory allocators:


@itemize *

@item 
@code{PYMEM_ALLOCATOR_NOT_SET} (@code{0}): don't change memory allocators
(use defaults).

@item 
@code{PYMEM_ALLOCATOR_DEFAULT} (@code{1}): @ref{213b,,default memory allocators}.

@item 
@code{PYMEM_ALLOCATOR_DEBUG} (@code{2}): @ref{213b,,default memory allocators} with @ref{213e,,debug hooks}.

@item 
@code{PYMEM_ALLOCATOR_MALLOC} (@code{3}): use @code{malloc()} of the C library.

@item 
@code{PYMEM_ALLOCATOR_MALLOC_DEBUG} (@code{4}): force usage of
@code{malloc()} with @ref{213e,,debug hooks}.

@item 
@code{PYMEM_ALLOCATOR_PYMALLOC} (@code{5}): @ref{f0b,,Python pymalloc memory allocator}.

@item 
@code{PYMEM_ALLOCATOR_PYMALLOC_DEBUG} (@code{6}): @ref{f0b,,Python pymalloc memory allocator} with @ref{213e,,debug hooks}.

@item 
@code{PYMEM_ALLOCATOR_MIMALLOC} (@code{6}): use @code{mimalloc}, a fast
malloc replacement.

@item 
@code{PYMEM_ALLOCATOR_MIMALLOC_DEBUG} (@code{7}): use @code{mimalloc}, a fast
malloc replacement with @ref{213e,,debug hooks}.
@end itemize

@code{PYMEM_ALLOCATOR_PYMALLOC} and @code{PYMEM_ALLOCATOR_PYMALLOC_DEBUG} are
not supported if Python is @ref{21a1,,configured using --without-pymalloc}.

@code{PYMEM_ALLOCATOR_MIMALLOC} and @code{PYMEM_ALLOCATOR_MIMALLOC_DEBUG} are
not supported if Python is @ref{21a0,,configured using --without-mimalloc} or if the underlying atomic support isn't
available.

See @ref{559d,,Memory Management}.

Default: @code{PYMEM_ALLOCATOR_NOT_SET}.
@end deffn

@geindex PyPreConfig.configure_locale (C member)
@anchor{c-api/init_config c PyPreConfig configure_locale}@anchor{557d}
@deffn {C のメンバ変数} int configure_locale

Set the LC_CTYPE locale to the user preferred locale.

If equals to @code{0}, set @ref{557a,,coerce_c_locale} and
@ref{557b,,coerce_c_locale_warn} members to @code{0}.

See the @ref{54a,,locale encoding}.

Default: @code{1} in Python config, @code{0} in isolated config.
@end deffn

@geindex PyPreConfig.coerce_c_locale (C member)
@anchor{c-api/init_config c PyPreConfig coerce_c_locale}@anchor{557a}
@deffn {C のメンバ変数} int coerce_c_locale

If equals to @code{2}, coerce the C locale.

If equals to @code{1}, read the LC_CTYPE locale to decide if it should be
coerced.

See the @ref{54a,,locale encoding}.

Default: @code{-1} in Python config, @code{0} in isolated config.
@end deffn

@geindex PyPreConfig.coerce_c_locale_warn (C member)
@anchor{c-api/init_config c PyPreConfig coerce_c_locale_warn}@anchor{557b}
@deffn {C のメンバ変数} int coerce_c_locale_warn

If non-zero, emit a warning if the C locale is coerced.

Default: @code{-1} in Python config, @code{0} in isolated config.
@end deffn

@geindex PyPreConfig.dev_mode (C member)
@anchor{c-api/init_config c PyPreConfig dev_mode}@anchor{559e}
@deffn {C のメンバ変数} int dev_mode

@ref{508,,Python Development Mode}: see
@ref{557f,,PyConfig.dev_mode}.

Default: @code{-1} in Python mode, @code{0} in isolated mode.
@end deffn

@geindex PyPreConfig.isolated (C member)
@anchor{c-api/init_config c PyPreConfig isolated}@anchor{559f}
@deffn {C のメンバ変数} int isolated

Isolated mode: see @ref{416,,PyConfig.isolated}.

Default: @code{0} in Python mode, @code{1} in isolated mode.
@end deffn

@geindex PyPreConfig.legacy_windows_fs_encoding (C member)
@anchor{c-api/init_config c PyPreConfig legacy_windows_fs_encoding}@anchor{418}
@deffn {C のメンバ変数} int legacy_windows_fs_encoding

If non-zero:


@itemize *

@item 
Set @ref{41d,,PyPreConfig.utf8_mode} to @code{0},

@item 
Set @ref{41b,,PyConfig.filesystem_encoding} to @code{"mbcs"},

@item 
Set @ref{41c,,PyConfig.filesystem_errors} to @code{"replace"}.
@end itemize

Initialized from the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} environment
variable value.

Only available on Windows. @code{#ifdef MS_WINDOWS} macro can be used for
Windows specific code.

Default: @code{0}.
@end deffn

@geindex PyPreConfig.parse_argv (C member)
@anchor{c-api/init_config c PyPreConfig parse_argv}@anchor{55a0}
@deffn {C のメンバ変数} int parse_argv

If non-zero, @ref{bba,,Py_PreInitializeFromArgs()} and
@ref{bbb,,Py_PreInitializeFromBytesArgs()} parse their @code{argv} argument the
same way the regular Python parses command line arguments: see
@ref{1209,,Command Line Arguments}.

Default: @code{1} in Python config, @code{0} in isolated config.
@end deffn

@geindex PyPreConfig.use_environment (C member)
@anchor{c-api/init_config c PyPreConfig use_environment}@anchor{55a1}
@deffn {C のメンバ変数} int use_environment

Use @ref{807,,environment variables}? See
@ref{40b,,PyConfig.use_environment}.

Default: @code{1} in Python config and @code{0} in isolated config.
@end deffn

@geindex PyPreConfig.utf8_mode (C member)
@anchor{c-api/init_config c PyPreConfig utf8_mode}@anchor{41d}
@deffn {C のメンバ変数} int utf8_mode

If non-zero, enable the @ref{866,,Python UTF-8 Mode}.

Set to @code{0} or @code{1} by the @ref{16f,,-X utf8} command line option
and the 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8} environment variable.

Also set to @code{1} if the @code{LC_CTYPE} locale is @code{C} or @code{POSIX}.

Default: @code{-1} in Python config and @code{0} in isolated config.
@end deffn
@end deffn

@node Preinitialize Python with PyPreConfig,PyConfig,PyPreConfig,PyConfig C API
@anchor{c-api/init_config c-preinit}@anchor{42c8}@anchor{c-api/init_config preinitialize-python-with-pypreconfig}@anchor{55a2}
@subsubsection Preinitialize Python with PyPreConfig


The preinitialization of Python:


@itemize *

@item 
Set the Python memory allocators (@ref{5574,,PyPreConfig.allocator})

@item 
Configure the LC_CTYPE locale (@ref{54a,,locale encoding})

@item 
Set the @ref{866,,Python UTF-8 Mode}
(@ref{41d,,PyPreConfig.utf8_mode})
@end itemize

The current preconfiguration (@code{PyPreConfig} type) is stored in
@code{_PyRuntime.preconfig}.

Functions to preinitialize Python:

@geindex Py_PreInitialize (C function)
@anchor{c-api/init_config c Py_PreInitialize}@anchor{41e}
@deffn {C の関数} @ref{ba4,,PyStatus} Py_PreInitialize (const PyPreConfig *preconfig)

Preinitialize Python from `preconfig' preconfiguration.

`preconfig' must not be @code{NULL}.
@end deffn

@geindex Py_PreInitializeFromBytesArgs (C function)
@anchor{c-api/init_config c Py_PreInitializeFromBytesArgs}@anchor{bbb}
@deffn {C の関数} @ref{ba4,,PyStatus} Py_PreInitializeFromBytesArgs (const PyPreConfig *preconfig, int argc, char *const *argv)

Preinitialize Python from `preconfig' preconfiguration.

Parse `argv' command line arguments (bytes strings) if
@ref{55a0,,parse_argv} of `preconfig' is non-zero.

`preconfig' must not be @code{NULL}.
@end deffn

@geindex Py_PreInitializeFromArgs (C function)
@anchor{c-api/init_config c Py_PreInitializeFromArgs}@anchor{bba}
@deffn {C の関数} @ref{ba4,,PyStatus} Py_PreInitializeFromArgs (const PyPreConfig *preconfig, int argc, wchar_t *const *argv)

Preinitialize Python from `preconfig' preconfiguration.

Parse `argv' command line arguments (wide strings) if
@ref{55a0,,parse_argv} of `preconfig' is non-zero.

`preconfig' must not be @code{NULL}.
@end deffn

The caller is responsible to handle exceptions (error or exit) using
@ref{bb0,,PyStatus_Exception()} and @ref{bb9,,Py_ExitStatusException()}.

For @ref{551c,,Python Configuration}
(@ref{bae,,PyPreConfig_InitPythonConfig()}), if Python is initialized with
command line arguments, the command line arguments must also be passed to
preinitialize Python, since they have an effect on the pre-configuration
like encodings. For example, the @ref{16f,,-X utf8} command line option
enables the @ref{866,,Python UTF-8 Mode}.

@code{PyMem_SetAllocator()} can be called after @ref{41e,,Py_PreInitialize()} and
before @ref{3f6,,Py_InitializeFromConfig()} to install a custom memory allocator.
It can be called before @ref{41e,,Py_PreInitialize()} if
@ref{5574,,PyPreConfig.allocator} is set to @code{PYMEM_ALLOCATOR_NOT_SET}.

Python memory allocation functions like @ref{631,,PyMem_RawMalloc()} must not be
used before the Python preinitialization, whereas calling directly @code{malloc()}
and @code{free()} is always safe. @ref{dc0,,Py_DecodeLocale()} must not be called
before the Python preinitialization.

Example using the preinitialization to enable
the @ref{866,,Python UTF-8 Mode}:

@example
PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);

preconfig.utf8_mode = 1;

status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) @{
    Py_ExitStatusException(status);
@}

/* at this point, Python speaks UTF-8 */

Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
@end example

@node PyConfig,Initialization with PyConfig,Preinitialize Python with PyPreConfig,PyConfig C API
@anchor{c-api/init_config pyconfig}@anchor{55a3}
@subsubsection PyConfig


@geindex PyConfig (C type)
@anchor{c-api/init_config c PyConfig}@anchor{3f7}
@deffn {C のデータ型} type PyConfig

Structure containing most parameters to configure Python.

When done, the @ref{ba6,,PyConfig_Clear()} function must be used to release the
configuration memory.

Structure methods:

@geindex PyConfig_InitPythonConfig (C function)
@anchor{c-api/init_config c PyConfig_InitPythonConfig}@anchor{ba8}
@deffn {C の関数} void PyConfig_InitPythonConfig (PyConfig *config)

Initialize configuration with the @ref{551c,,Python Configuration}.
@end deffn

@geindex PyConfig_InitIsolatedConfig (C function)
@anchor{c-api/init_config c PyConfig_InitIsolatedConfig}@anchor{ba7}
@deffn {C の関数} void PyConfig_InitIsolatedConfig (PyConfig *config)

Initialize configuration with the @ref{556c,,Isolated Configuration}.
@end deffn

@geindex PyConfig_SetString (C function)
@anchor{c-api/init_config c PyConfig_SetString}@anchor{bac}
@deffn {C の関数} @ref{ba4,,PyStatus} PyConfig_SetString (PyConfig *config, wchar_t *const *config_str, const wchar_t *str)

Copy the wide character string `str' into @code{*config_str}.

@ref{42c8,,Preinitialize Python} if needed.
@end deffn

@geindex PyConfig_SetBytesString (C function)
@anchor{c-api/init_config c PyConfig_SetBytesString}@anchor{bab}
@deffn {C の関数} @ref{ba4,,PyStatus} PyConfig_SetBytesString (PyConfig *config, wchar_t *const *config_str, const char *str)

Decode `str' using @ref{dc0,,Py_DecodeLocale()} and set the result into
@code{*config_str}.

@ref{42c8,,Preinitialize Python} if needed.
@end deffn

@geindex PyConfig_SetArgv (C function)
@anchor{c-api/init_config c PyConfig_SetArgv}@anchor{ba9}
@deffn {C の関数} @ref{ba4,,PyStatus} PyConfig_SetArgv (PyConfig *config, int argc, wchar_t *const *argv)

Set command line arguments (@ref{3f1,,argv} member of
`config') from the `argv' list of wide character strings.

@ref{42c8,,Preinitialize Python} if needed.
@end deffn

@geindex PyConfig_SetBytesArgv (C function)
@anchor{c-api/init_config c PyConfig_SetBytesArgv}@anchor{baa}
@deffn {C の関数} @ref{ba4,,PyStatus} PyConfig_SetBytesArgv (PyConfig *config, int argc, char *const *argv)

Set command line arguments (@ref{3f1,,argv} member of
`config') from the `argv' list of bytes strings. Decode bytes using
@ref{dc0,,Py_DecodeLocale()}.

@ref{42c8,,Preinitialize Python} if needed.
@end deffn

@geindex PyConfig_SetWideStringList (C function)
@anchor{c-api/init_config c PyConfig_SetWideStringList}@anchor{1dc9}
@deffn {C の関数} @ref{ba4,,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'.

@ref{42c8,,Preinitialize Python} if needed.
@end deffn

@geindex PyConfig_Read (C function)
@anchor{c-api/init_config c PyConfig_Read}@anchor{993}
@deffn {C の関数} @ref{ba4,,PyStatus} PyConfig_Read (PyConfig *config)

Read all Python configuration.

Fields which are already initialized are left unchanged.

Fields for @ref{aaa,,path configuration} are no longer
calculated or modified when calling this function, as of Python 3.11.

The @ref{993,,PyConfig_Read()} function only parses
@ref{3f1,,PyConfig.argv} arguments once: @ref{1cf1,,PyConfig.parse_argv}
is set to @code{2} after arguments are parsed. Since Python arguments are
stripped from @ref{3f1,,PyConfig.argv}, parsing arguments twice would
parse the application options as Python options.

@ref{42c8,,Preinitialize Python} if needed.


バージョン 3.10 で変更: The @ref{3f1,,PyConfig.argv} arguments are now only parsed once,
@ref{1cf1,,PyConfig.parse_argv} is set to @code{2} after arguments are
parsed, and arguments are only parsed if
@ref{1cf1,,PyConfig.parse_argv} equals @code{1}.



バージョン 3.11 で変更: @ref{993,,PyConfig_Read()} no longer calculates all paths, and so fields
listed under @ref{aaa,,Python Path Configuration} may
no longer be updated until @ref{3f6,,Py_InitializeFromConfig()} is
called.

@end deffn

@geindex PyConfig_Clear (C function)
@anchor{c-api/init_config c PyConfig_Clear}@anchor{ba6}
@deffn {C の関数} void PyConfig_Clear (PyConfig *config)

Release configuration memory.
@end deffn

Most @code{PyConfig} methods @ref{42c8,,preinitialize Python} if needed.
In that case, the Python preinitialization configuration
(@ref{ba3,,PyPreConfig}) is based on the @ref{3f7,,PyConfig}. If configuration
fields which are in common with @ref{ba3,,PyPreConfig} are tuned, they must
be set before calling a @ref{3f7,,PyConfig} method:


@itemize *

@item 
@ref{557f,,PyConfig.dev_mode}

@item 
@ref{416,,PyConfig.isolated}

@item 
@ref{1cf1,,PyConfig.parse_argv}

@item 
@ref{40b,,PyConfig.use_environment}
@end itemize

Moreover, if @ref{ba9,,PyConfig_SetArgv()} or @ref{baa,,PyConfig_SetBytesArgv()}
is used, this method must be called before other methods, since the
preinitialization configuration depends on command line arguments (if
@ref{1cf1,,parse_argv} is non-zero).

The caller of these methods is responsible to handle exceptions (error or
exit) using @code{PyStatus_Exception()} and @code{Py_ExitStatusException()}.

構造体フィールド:

@geindex PyConfig.argv (C member)
@anchor{c-api/init_config c PyConfig argv}@anchor{3f1}
@deffn {C のメンバ変数} @ref{ba5,,PyWideStringList} argv

@geindex main()
@geindex argv (in module sys)

Set @ref{147c,,sys.argv} command line arguments based on
@ref{3f1,,argv}.  These parameters are similar to those passed
to the program's @code{main()} function with the difference that the
first entry should refer to the script file to be executed rather than
the executable hosting the Python interpreter.  If there isn't a script
that will be run, the first entry in @ref{3f1,,argv} can be an
empty string.

Set @ref{1cf1,,parse_argv} to @code{1} to parse
@ref{3f1,,argv} the same way the regular Python parses Python
command line arguments and then to strip Python arguments from
@ref{3f1,,argv}.

If @ref{3f1,,argv} is empty, an empty string is added to
ensure that @ref{147c,,sys.argv} always exists and is never empty.

Default: @code{NULL}.

See also the @ref{a94,,orig_argv} member.
@end deffn

@geindex PyConfig.safe_path (C member)
@anchor{c-api/init_config c PyConfig safe_path}@anchor{977}
@deffn {C のメンバ変数} int safe_path

If equals to zero, @code{Py_RunMain()} prepends a potentially unsafe path to
@ref{3e4,,sys.path} at startup:


@itemize *

@item 
If @ref{3f1,,argv[0]} is equal to @code{L"-m"}
(@code{python -m module}), prepend the current working directory.

@item 
If running a script (@code{python script.py}), prepend the script's
directory.  If it's a symbolic link, resolve symbolic links.

@item 
Otherwise (@code{python -c code} and @code{python}), prepend an empty string,
which means the current working directory.
@end itemize

Set to @code{1} by the @ref{7c1,,-P} command line option and the
@geindex PYTHONSAFEPATH
@geindex 環境変数; PYTHONSAFEPATH
@ref{7c2,,PYTHONSAFEPATH} environment variable.

Default: @code{0} in Python config, @code{1} in isolated config.


Added in version 3.11.

@end deffn

@geindex PyConfig.base_exec_prefix (C member)
@anchor{c-api/init_config c PyConfig base_exec_prefix}@anchor{5575}
@deffn {C のメンバ変数} wchar_t *base_exec_prefix

@ref{3ea,,sys.base_exec_prefix}.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} output.

See also @ref{5582,,PyConfig.exec_prefix}.
@end deffn

@geindex PyConfig.base_executable (C member)
@anchor{c-api/init_config c PyConfig base_executable}@anchor{5576}
@deffn {C のメンバ変数} wchar_t *base_executable

Python base executable: @code{sys._base_executable}.

Set by the 
@geindex __PYVENV_LAUNCHER__
@geindex 環境変数; __PYVENV_LAUNCHER__
@code{__PYVENV_LAUNCHER__} environment variable.

Set from @ref{645,,PyConfig.executable} if @code{NULL}.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} output.

See also @ref{645,,PyConfig.executable}.
@end deffn

@geindex PyConfig.base_prefix (C member)
@anchor{c-api/init_config c PyConfig base_prefix}@anchor{5577}
@deffn {C のメンバ変数} wchar_t *base_prefix

@ref{3e6,,sys.base_prefix}.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} output.

See also @ref{5588,,PyConfig.prefix}.
@end deffn

@geindex PyConfig.buffered_stdio (C member)
@anchor{c-api/init_config c PyConfig buffered_stdio}@anchor{411}
@deffn {C のメンバ変数} int buffered_stdio

If equals to @code{0} and @ref{557c,,configure_c_stdio} is non-zero,
disable buffering on the C streams stdout and stderr.

Set to @code{0} by the @ref{1d8d,,-u} command line option and the
@geindex PYTHONUNBUFFERED
@geindex 環境変数; PYTHONUNBUFFERED
@ref{1d8e,,PYTHONUNBUFFERED} environment variable.

stdin is always opened in buffered mode.

Default: @code{1}.
@end deffn

@geindex PyConfig.bytes_warning (C member)
@anchor{c-api/init_config c PyConfig bytes_warning}@anchor{407}
@deffn {C のメンバ変数} int bytes_warning

If equals to @code{1}, issue a warning when comparing @ref{192,,bytes} or
@ref{344,,bytearray} with @ref{169,,str}, or comparing @ref{192,,bytes} with
@ref{19b,,int}.

If equal or greater to @code{2}, raise a @ref{e1c,,BytesWarning} exception in these
cases.

Incremented by the @ref{7f9,,-b} command line option.

Default: @code{0}.
@end deffn

@geindex PyConfig.warn_default_encoding (C member)
@anchor{c-api/init_config c PyConfig warn_default_encoding}@anchor{5590}
@deffn {C のメンバ変数} int warn_default_encoding

If non-zero, emit a @ref{212e,,EncodingWarning} warning when @ref{9be,,io.TextIOWrapper}
uses its default encoding. See @ref{2140,,Opt-in EncodingWarning} for details.

Default: @code{0}.


Added in version 3.10.

@end deffn

@geindex PyConfig.code_debug_ranges (C member)
@anchor{c-api/init_config c PyConfig code_debug_ranges}@anchor{5579}
@deffn {C のメンバ変数} int code_debug_ranges

If equals to @code{0}, disables the inclusion of the end line and column
mappings in code objects. Also disables traceback printing carets to
specific error locations.

Set to @code{0} by the 
@geindex PYTHONNODEBUGRANGES
@geindex 環境変数; PYTHONNODEBUGRANGES
@ref{7d3,,PYTHONNODEBUGRANGES} environment variable
and by the @ref{16f,,-X no_debug_ranges} command line option.

Default: @code{1}.


Added in version 3.11.

@end deffn

@geindex PyConfig.check_hash_pycs_mode (C member)
@anchor{c-api/init_config c PyConfig check_hash_pycs_mode}@anchor{5578}
@deffn {C のメンバ変数} wchar_t *check_hash_pycs_mode

Control the validation behavior of hash-based @code{.pyc} files:
value of the @ref{2122,,--check-hash-based-pycs} command line option.

Valid values:


@itemize -

@item 
@code{L"always"}: Hash the source file for invalidation regardless of
value of the 'check_source' flag.

@item 
@code{L"never"}: Assume that hash-based pycs always are valid.

@item 
@code{L"default"}: The 'check_source' flag in hash-based pycs
determines invalidation.
@end itemize

Default: @code{L"default"}.

See also 
@geindex Python Enhancement Proposals; PEP 552
PEP 552@footnote{https://peps.python.org/pep-0552/} "Deterministic pycs".
@end deffn

@geindex PyConfig.configure_c_stdio (C member)
@anchor{c-api/init_config c PyConfig configure_c_stdio}@anchor{557c}
@deffn {C のメンバ変数} int configure_c_stdio

If non-zero, configure C standard streams:


@itemize *

@item 
On Windows, set the binary mode (@code{O_BINARY}) on stdin, stdout and
stderr.

@item 
If @ref{411,,buffered_stdio} equals zero, disable buffering
of stdin, stdout and stderr streams.

@item 
If @ref{3ff,,interactive} is non-zero, enable stream
buffering on stdin and stdout (only stdout on Windows).
@end itemize

Default: @code{1} in Python config, @code{0} in isolated config.
@end deffn

@geindex PyConfig.dev_mode (C member)
@anchor{c-api/init_config c PyConfig dev_mode}@anchor{557f}
@deffn {C のメンバ変数} int dev_mode

If non-zero, enable the @ref{508,,Python Development Mode}.

Set to @code{1} by the @ref{16f,,-X dev} option and the
@geindex PYTHONDEVMODE
@geindex 環境変数; PYTHONDEVMODE
@ref{ce7,,PYTHONDEVMODE} environment variable.

Default: @code{-1} in Python mode, @code{0} in isolated mode.
@end deffn

@geindex PyConfig.dump_refs (C member)
@anchor{c-api/init_config c PyConfig dump_refs}@anchor{5580}
@deffn {C のメンバ変数} int dump_refs

Dump Python references?

If non-zero, dump all objects which are still alive at exit.

Set to @code{1} by the 
@geindex PYTHONDUMPREFS
@geindex 環境変数; PYTHONDUMPREFS
@ref{b9e,,PYTHONDUMPREFS} environment variable.

Needs a special build of Python with the @code{Py_TRACE_REFS} macro defined:
see the @ref{636,,configure --with-trace-refs option}.

Default: @code{0}.
@end deffn

@geindex PyConfig.dump_refs_file (C member)
@anchor{c-api/init_config c PyConfig dump_refs_file}@anchor{5581}
@deffn {C のメンバ変数} wchar_t *dump_refs_file

Filename where to dump Python references.

Set by the 
@geindex PYTHONDUMPREFSFILE
@geindex 環境変数; PYTHONDUMPREFSFILE
@ref{1c3f,,PYTHONDUMPREFSFILE} environment variable.

Default: @code{NULL}.


Added in version 3.11.

@end deffn

@geindex PyConfig.exec_prefix (C member)
@anchor{c-api/init_config c PyConfig exec_prefix}@anchor{5582}
@deffn {C のメンバ変数} wchar_t *exec_prefix

The site-specific directory prefix where the platform-dependent Python
files are installed: @ref{3eb,,sys.exec_prefix}.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} output.

See also @ref{5575,,PyConfig.base_exec_prefix}.
@end deffn

@geindex PyConfig.executable (C member)
@anchor{c-api/init_config c PyConfig executable}@anchor{645}
@deffn {C のメンバ変数} wchar_t *executable

The absolute path of the executable binary for the Python interpreter:
@ref{3ed,,sys.executable}.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} output.

See also @ref{5576,,PyConfig.base_executable}.
@end deffn

@geindex PyConfig.faulthandler (C member)
@anchor{c-api/init_config c PyConfig faulthandler}@anchor{5583}
@deffn {C のメンバ変数} int faulthandler

Enable faulthandler?

If non-zero, call @ref{20f,,faulthandler.enable()} at startup.

Set to @code{1} by @ref{16f,,-X faulthandler} and the
@geindex PYTHONFAULTHANDLER
@geindex 環境変数; PYTHONFAULTHANDLER
@ref{1291,,PYTHONFAULTHANDLER} environment variable.

Default: @code{-1} in Python mode, @code{0} in isolated mode.
@end deffn

@geindex PyConfig.filesystem_encoding (C member)
@anchor{c-api/init_config c PyConfig filesystem_encoding}@anchor{41b}
@deffn {C のメンバ変数} wchar_t *filesystem_encoding

@ref{75d,,Filesystem encoding}:
@ref{e53,,sys.getfilesystemencoding()}.

On macOS, Android and VxWorks: use @code{"utf-8"} by default.

On Windows: use @code{"utf-8"} by default, or @code{"mbcs"} if
@ref{418,,legacy_windows_fs_encoding} of
@ref{ba3,,PyPreConfig} is non-zero.

Default encoding on other platforms:


@itemize *

@item 
@code{"utf-8"} if @ref{41d,,PyPreConfig.utf8_mode} is non-zero.

@item 
@code{"ascii"} if Python detects that @code{nl_langinfo(CODESET)} announces
the ASCII encoding, whereas the @code{mbstowcs()} function
decodes from a different encoding (usually Latin1).

@item 
@code{"utf-8"} if @code{nl_langinfo(CODESET)} returns an empty string.

@item 
Otherwise, use the @ref{54a,,locale encoding}:
@code{nl_langinfo(CODESET)} result.
@end itemize

At Python startup, the encoding name is normalized to the Python codec
name. For example, @code{"ANSI_X3.4-1968"} is replaced with @code{"ascii"}.

See also the @ref{41c,,filesystem_errors} member.
@end deffn

@geindex PyConfig.filesystem_errors (C member)
@anchor{c-api/init_config c PyConfig filesystem_errors}@anchor{41c}
@deffn {C のメンバ変数} wchar_t *filesystem_errors

@ref{75d,,Filesystem error handler}:
@ref{ee2,,sys.getfilesystemencodeerrors()}.

On Windows: use @code{"surrogatepass"} by default, or @code{"replace"}  if
@ref{418,,legacy_windows_fs_encoding} of
@ref{ba3,,PyPreConfig} is non-zero.

On other platforms: use @code{"surrogateescape"} by default.

Supported error handlers:


@itemize *

@item 
@code{"strict"}

@item 
@code{"surrogateescape"}

@item 
@code{"surrogatepass"} (only supported with the UTF-8 encoding)
@end itemize

See also the @ref{41b,,filesystem_encoding} member.
@end deffn

@geindex PyConfig.use_frozen_modules (C member)
@anchor{c-api/init_config c PyConfig use_frozen_modules}@anchor{558f}
@deffn {C のメンバ変数} int use_frozen_modules

If non-zero, use frozen modules.

Set by the 
@geindex PYTHON_FROZEN_MODULES
@geindex 環境変数; PYTHON_FROZEN_MODULES
@ref{4ad,,PYTHON_FROZEN_MODULES} environment variable.

Default: @code{1} in a release build, or @code{0} in a @ref{509,,debug build}.
@end deffn

@geindex PyConfig.hash_seed (C member)
@anchor{c-api/init_config c PyConfig hash_seed}@anchor{414}
@deffn {C のメンバ変数} unsigned long hash_seed
@end deffn

@geindex PyConfig.use_hash_seed (C member)
@anchor{c-api/init_config c PyConfig use_hash_seed}@anchor{413}
@deffn {C のメンバ変数} int use_hash_seed

Randomized hash function seed.

If @ref{413,,use_hash_seed} is zero, a seed is chosen randomly
at Python startup, and @ref{414,,hash_seed} is ignored.

Set by the 
@geindex PYTHONHASHSEED
@geindex 環境変数; PYTHONHASHSEED
@ref{1289,,PYTHONHASHSEED} environment variable.

Default `use_hash_seed' value: @code{-1} in Python mode, @code{0} in isolated
mode.
@end deffn

@geindex PyConfig.home (C member)
@anchor{c-api/init_config c PyConfig home}@anchor{3f3}
@deffn {C のメンバ変数} wchar_t *home

Set the default Python "home" directory, that is, the location of the
standard Python libraries (see 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME}).

Set by the 
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} input.
@end deffn

@geindex PyConfig.import_time (C member)
@anchor{c-api/init_config c PyConfig import_time}@anchor{5584}
@deffn {C のメンバ変数} int import_time

@quotation

If @code{1}, profile import time.
If @code{2}, include additional output that indicates
when an imported module has already been loaded.

Set by the @ref{16f,,-X importtime} option and the
@geindex PYTHONPROFILEIMPORTTIME
@geindex 環境変数; PYTHONPROFILEIMPORTTIME
@ref{ced,,PYTHONPROFILEIMPORTTIME} environment variable.

Default: @code{0}.
@end quotation


バージョン 3.14 で変更: Added support for @code{import_time = 2}

@end deffn

@geindex PyConfig.inspect (C member)
@anchor{c-api/init_config c PyConfig inspect}@anchor{401}
@deffn {C のメンバ変数} int inspect

Enter interactive mode after executing a script or a command.

If greater than @code{0}, enable inspect: when a script is passed as first
argument or the -c option is used, enter interactive mode after executing
the script or the command, even when @ref{75f,,sys.stdin} does not appear to
be a terminal.

Incremented by the @ref{16f4,,-i} command line option. Set to @code{1} if the
@geindex PYTHONINSPECT
@geindex 環境変数; PYTHONINSPECT
@ref{16f3,,PYTHONINSPECT} environment variable is non-empty.

Default: @code{0}.
@end deffn

@geindex PyConfig.install_signal_handlers (C member)
@anchor{c-api/init_config c PyConfig install_signal_handlers}@anchor{abb}
@deffn {C のメンバ変数} int install_signal_handlers

Install Python signal handlers?

Default: @code{1} in Python mode, @code{0} in isolated mode.
@end deffn

@geindex PyConfig.interactive (C member)
@anchor{c-api/init_config c PyConfig interactive}@anchor{3ff}
@deffn {C のメンバ変数} int interactive

If greater than @code{0}, enable the interactive mode (REPL).

Incremented by the @ref{16f4,,-i} command line option.

Default: @code{0}.
@end deffn

@geindex PyConfig.int_max_str_digits (C member)
@anchor{c-api/init_config c PyConfig int_max_str_digits}@anchor{5585}
@deffn {C のメンバ変数} int int_max_str_digits

Configures the @ref{80b,,integer string conversion length limitation}.  An initial value of @code{-1} means the value will
be taken from the command line or environment or otherwise default to
4300 (@ref{26dc,,sys.int_info.default_max_str_digits}).  A value of @code{0}
disables the limitation.  Values greater than zero but less than 640
(@ref{4925,,sys.int_info.str_digits_check_threshold}) are unsupported and
will produce an error.

Configured by the @ref{16f,,-X int_max_str_digits} command line
flag or the 
@geindex PYTHONINTMAXSTRDIGITS
@geindex 環境変数; PYTHONINTMAXSTRDIGITS
@ref{1b3a,,PYTHONINTMAXSTRDIGITS} environment variable.

Default: @code{-1} in Python mode.  4300
(@ref{26dc,,sys.int_info.default_max_str_digits}) in isolated mode.


Added in version 3.12.

@end deffn

@geindex PyConfig.cpu_count (C member)
@anchor{c-api/init_config c PyConfig cpu_count}@anchor{557e}
@deffn {C のメンバ変数} int cpu_count

If the value of @ref{557e,,cpu_count} is not @code{-1} then it will
override the return values of @ref{4db,,os.cpu_count()},
@ref{4da,,os.process_cpu_count()}, and @ref{1171,,multiprocessing.cpu_count()}.

Configured by the @code{-X cpu_count=@var{n|default}} command line
flag or the 
@geindex PYTHON_CPU_COUNT
@geindex 環境変数; PYTHON_CPU_COUNT
@ref{51e,,PYTHON_CPU_COUNT} environment variable.

Default: @code{-1}.


Added in version 3.13.

@end deffn

@geindex PyConfig.isolated (C member)
@anchor{c-api/init_config c PyConfig isolated}@anchor{416}
@deffn {C のメンバ変数} int isolated

If greater than @code{0}, enable isolated mode:


@itemize *

@item 
Set @ref{977,,safe_path} to @code{1}:
don't prepend a potentially unsafe path to @ref{3e4,,sys.path} at Python
startup, such as the current directory, the script's directory or an
empty string.

@item 
Set @ref{40b,,use_environment} to @code{0}: ignore @code{PYTHON}
environment variables.

@item 
Set @ref{40f,,user_site_directory} to @code{0}: don't add the user
site directory to @ref{3e4,,sys.path}.

@item 
Python REPL doesn't import @ref{bf,,readline} nor enable default readline
configuration on interactive prompts.
@end itemize

Set to @code{1} by the @ref{b57,,-I} command line option.

Default: @code{0} in Python mode, @code{1} in isolated mode.

See also the @ref{556c,,Isolated Configuration} and
@ref{559f,,PyPreConfig.isolated}.
@end deffn

@geindex PyConfig.legacy_windows_stdio (C member)
@anchor{c-api/init_config c PyConfig legacy_windows_stdio}@anchor{41a}
@deffn {C のメンバ変数} int legacy_windows_stdio

If non-zero, use @ref{1527,,io.FileIO} instead of
@code{io._WindowsConsoleIO} for @ref{75f,,sys.stdin}, @ref{ccd,,sys.stdout}
and @ref{b33,,sys.stderr}.

@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 環境変数; PYTHONLEGACYWINDOWSSTDIO
@ref{e55,,PYTHONLEGACYWINDOWSSTDIO} 環境変数が空でない文字列に設定された場合に、 @code{1} に設定されます。

Only available on Windows. @code{#ifdef MS_WINDOWS} macro can be used for
Windows specific code.

Default: @code{0}.

See also the 
@geindex Python Enhancement Proposals; PEP 528
PEP 528@footnote{https://peps.python.org/pep-0528/} (Change Windows console encoding to UTF-8).
@end deffn

@geindex PyConfig.malloc_stats (C member)
@anchor{c-api/init_config c PyConfig malloc_stats}@anchor{5586}
@deffn {C のメンバ変数} int malloc_stats

If non-zero, dump statistics on @ref{f0b,,Python pymalloc memory allocator} at exit.

Set to @code{1} by the 
@geindex PYTHONMALLOCSTATS
@geindex 環境変数; PYTHONMALLOCSTATS
@ref{1f37,,PYTHONMALLOCSTATS} environment variable.

The option is ignored if Python is @ref{21a1,,configured using the --without-pymalloc option}.

Default: @code{0}.
@end deffn

@geindex PyConfig.platlibdir (C member)
@anchor{c-api/init_config c PyConfig platlibdir}@anchor{1d21}
@deffn {C のメンバ変数} wchar_t *platlibdir

Platform library directory name: @ref{b32,,sys.platlibdir}.

Set by the 
@geindex PYTHONPLATLIBDIR
@geindex 環境変数; PYTHONPLATLIBDIR
@ref{1d23,,PYTHONPLATLIBDIR} environment variable.

Default: value of the @code{PLATLIBDIR} macro which is set by the
@ref{216c,,configure --with-platlibdir option}
(default: @code{"lib"}, or @code{"DLLs"} on Windows).

Part of the @ref{aaa,,Python Path Configuration} input.


Added in version 3.9.



バージョン 3.11 で変更: This macro is now used on Windows to locate the standard
library extension modules, typically under @code{DLLs}. However,
for compatibility, note that this value is ignored for any
non-standard layouts, including in-tree builds and virtual
environments.

@end deffn

@geindex PyConfig.pythonpath_env (C member)
@anchor{c-api/init_config c PyConfig pythonpath_env}@anchor{55a4}
@deffn {C のメンバ変数} wchar_t *pythonpath_env

Module search paths (@ref{3e4,,sys.path}) as a string separated by @code{DELIM}
(@ref{2134,,os.pathsep}).

Set by the 
@geindex PYTHONPATH
@geindex 環境変数; PYTHONPATH
@ref{121f,,PYTHONPATH} environment variable.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} input.
@end deffn

@geindex PyConfig.module_search_paths (C member)
@anchor{c-api/init_config c PyConfig module_search_paths}@anchor{643}
@deffn {C のメンバ変数} @ref{ba5,,PyWideStringList} module_search_paths
@end deffn

@geindex PyConfig.module_search_paths_set (C member)
@anchor{c-api/init_config c PyConfig module_search_paths_set}@anchor{805}
@deffn {C のメンバ変数} int module_search_paths_set

Module search paths: @ref{3e4,,sys.path}.

If @ref{805,,module_search_paths_set} is equal to @code{0},
@ref{3f6,,Py_InitializeFromConfig()} will replace
@ref{643,,module_search_paths} and sets
@ref{805,,module_search_paths_set} to @code{1}.

Default: empty list (@code{module_search_paths}) and @code{0}
(@code{module_search_paths_set}).

Part of the @ref{aaa,,Python Path Configuration} output.
@end deffn

@geindex PyConfig.optimization_level (C member)
@anchor{c-api/init_config c PyConfig optimization_level}@anchor{403}
@deffn {C のメンバ変数} int optimization_level

Compilation optimization level:


@itemize *

@item 
@code{0}: Peephole optimizer, set @code{__debug__} to @code{True}.

@item 
@code{1}: Level 0, remove assertions, set @code{__debug__} to @code{False}.

@item 
@code{2}: Level 1, strip docstrings.
@end itemize

Incremented by the @ref{18c,,-O} command line option. Set to the
@geindex PYTHONOPTIMIZE
@geindex 環境変数; PYTHONOPTIMIZE
@ref{2125,,PYTHONOPTIMIZE} environment variable value.

Default: @code{0}.
@end deffn

@geindex PyConfig.orig_argv (C member)
@anchor{c-api/init_config c PyConfig orig_argv}@anchor{a94}
@deffn {C のメンバ変数} @ref{ba5,,PyWideStringList} orig_argv

The list of the original command line arguments passed to the Python
executable: @ref{a41,,sys.orig_argv}.

If @ref{a94,,orig_argv} list is empty and
@ref{3f1,,argv} is not a list only containing an empty
string, @ref{993,,PyConfig_Read()} copies @ref{3f1,,argv} into
@ref{a94,,orig_argv} before modifying
@ref{3f1,,argv} (if @ref{1cf1,,parse_argv} is
non-zero).

See also the @ref{3f1,,argv} member and the
@ref{1d41,,Py_GetArgcArgv()} function.

Default: empty list.


Added in version 3.10.

@end deffn

@geindex PyConfig.parse_argv (C member)
@anchor{c-api/init_config c PyConfig parse_argv}@anchor{1cf1}
@deffn {C のメンバ変数} int parse_argv

Parse command line arguments?

If equals to @code{1}, parse @ref{3f1,,argv} the same way the regular
Python parses @ref{1209,,command line arguments}, and strip
Python arguments from @ref{3f1,,argv}.

The @ref{993,,PyConfig_Read()} function only parses
@ref{3f1,,PyConfig.argv} arguments once: @ref{1cf1,,PyConfig.parse_argv}
is set to @code{2} after arguments are parsed. Since Python arguments are
stripped from @ref{3f1,,PyConfig.argv}, parsing arguments twice would
parse the application options as Python options.

Default: @code{1} in Python mode, @code{0} in isolated mode.


バージョン 3.10 で変更: The @ref{3f1,,PyConfig.argv} arguments are now only parsed if
@ref{1cf1,,PyConfig.parse_argv} equals to @code{1}.

@end deffn

@geindex PyConfig.parser_debug (C member)
@anchor{c-api/init_config c PyConfig parser_debug}@anchor{3f9}
@deffn {C のメンバ変数} int parser_debug

Parser debug mode. If greater than @code{0}, turn on parser debugging output (for expert only, depending
on compilation options).

Incremented by the @ref{2123,,-d} command line option. Set to the
@geindex PYTHONDEBUG
@geindex 環境変数; PYTHONDEBUG
@ref{2124,,PYTHONDEBUG} environment variable value.

Needs a @ref{509,,debug build of Python} (the @code{Py_DEBUG} macro
must be defined).

Default: @code{0}.
@end deffn

@geindex PyConfig.pathconfig_warnings (C member)
@anchor{c-api/init_config c PyConfig pathconfig_warnings}@anchor{409}
@deffn {C のメンバ変数} int pathconfig_warnings

If non-zero, calculation of path configuration is allowed to log
warnings into @code{stderr}. If equals to @code{0}, suppress these warnings.

Default: @code{1} in Python mode, @code{0} in isolated mode.

Part of the @ref{aaa,,Python Path Configuration} input.


バージョン 3.11 で変更: Now also applies on Windows.

@end deffn

@geindex PyConfig.prefix (C member)
@anchor{c-api/init_config c PyConfig prefix}@anchor{5588}
@deffn {C のメンバ変数} wchar_t *prefix

The site-specific directory prefix where the platform independent Python
files are installed: @ref{3e7,,sys.prefix}.

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} output.

See also @ref{5577,,PyConfig.base_prefix}.
@end deffn

@geindex PyConfig.program_name (C member)
@anchor{c-api/init_config c PyConfig program_name}@anchor{3f2}
@deffn {C のメンバ変数} wchar_t *program_name

Program name used to initialize @ref{645,,executable} and in
early error messages during Python initialization.


@itemize *

@item 
On macOS, use 
@geindex PYTHONEXECUTABLE
@geindex 環境変数; PYTHONEXECUTABLE
@ref{2138,,PYTHONEXECUTABLE} environment variable if set.

@item 
If the @code{WITH_NEXT_FRAMEWORK} macro is defined, use
@geindex __PYVENV_LAUNCHER__
@geindex 環境変数; __PYVENV_LAUNCHER__
@code{__PYVENV_LAUNCHER__} environment variable if set.

@item 
Use @code{argv[0]} of @ref{3f1,,argv} if available and
non-empty.

@item 
Otherwise, use @code{L"python"} on Windows, or @code{L"python3"} on other
platforms.
@end itemize

Default: @code{NULL}.

Part of the @ref{aaa,,Python Path Configuration} input.
@end deffn

@geindex PyConfig.pycache_prefix (C member)
@anchor{c-api/init_config c PyConfig pycache_prefix}@anchor{5589}
@deffn {C のメンバ変数} wchar_t *pycache_prefix

Directory where cached @code{.pyc} files are written:
@ref{b9c,,sys.pycache_prefix}.

Set by the @ref{16f,,-X pycache_prefix=PATH} command line option and
the 
@geindex PYTHONPYCACHEPREFIX
@geindex 環境変数; PYTHONPYCACHEPREFIX
@ref{b9b,,PYTHONPYCACHEPREFIX} environment variable.
The command-line option takes precedence.

If @code{NULL}, @ref{b9c,,sys.pycache_prefix} is set to @code{None}.

Default: @code{NULL}.
@end deffn

@geindex PyConfig.quiet (C member)
@anchor{c-api/init_config c PyConfig quiet}@anchor{3fd}
@deffn {C のメンバ変数} int quiet

Quiet mode. If greater than @code{0}, don't display the copyright and version at
Python startup in interactive mode.

Incremented by the @ref{177e,,-q} command line option.

Default: @code{0}.
@end deffn

@geindex PyConfig.run_command (C member)
@anchor{c-api/init_config c PyConfig run_command}@anchor{5519}
@deffn {C のメンバ変数} wchar_t *run_command

Value of the @ref{1a8,,-c} command line option.

Used by @ref{bbc,,Py_RunMain()}.

Default: @code{NULL}.
@end deffn

@geindex PyConfig.run_filename (C member)
@anchor{c-api/init_config c PyConfig run_filename}@anchor{551a}
@deffn {C のメンバ変数} wchar_t *run_filename

Filename passed on the command line: trailing command line argument
without @ref{1a8,,-c} or @ref{23c,,-m}. It is used by the
@ref{bbc,,Py_RunMain()} function.

For example, it is set to @code{script.py} by the @code{python3 script.py arg}
command line.

See also the @ref{558c,,PyConfig.skip_source_first_line} option.

Default: @code{NULL}.
@end deffn

@geindex PyConfig.run_module (C member)
@anchor{c-api/init_config c PyConfig run_module}@anchor{551b}
@deffn {C のメンバ変数} wchar_t *run_module

Value of the @ref{23c,,-m} command line option.

Used by @ref{bbc,,Py_RunMain()}.

Default: @code{NULL}.
@end deffn

@geindex PyConfig.run_presite (C member)
@anchor{c-api/init_config c PyConfig run_presite}@anchor{558a}
@deffn {C のメンバ変数} wchar_t *run_presite

@code{package.module} path to module that should be imported before
@code{site.py} is run.

Set by the @ref{16f,,-X presite=package.module} command-line
option and the 
@geindex PYTHON_PRESITE
@geindex 環境変数; PYTHON_PRESITE
@ref{212f,,PYTHON_PRESITE} environment variable.
The command-line option takes precedence.

Needs a @ref{509,,debug build of Python} (the @code{Py_DEBUG} macro
must be defined).

Default: @code{NULL}.
@end deffn

@geindex PyConfig.show_ref_count (C member)
@anchor{c-api/init_config c PyConfig show_ref_count}@anchor{558b}
@deffn {C のメンバ変数} int show_ref_count

Show total reference count at exit (excluding @ref{290,,immortal} objects)?

Set to @code{1} by @ref{16f,,-X showrefcount} command line option.

Needs a @ref{509,,debug build of Python} (the @code{Py_REF_DEBUG}
macro must be defined).

Default: @code{0}.
@end deffn

@geindex PyConfig.site_import (C member)
@anchor{c-api/init_config c PyConfig site_import}@anchor{405}
@deffn {C のメンバ変数} int site_import

Import the @ref{cc,,site} module at startup?

If equal to zero, disable the import of the module site and the
site-dependent manipulations of @ref{3e4,,sys.path} that it entails.

Also disable these manipulations if the @ref{cc,,site} module is explicitly
imported later (call @ref{2127,,site.main()} if you want them to be triggered).

Set to @code{0} by the @ref{13c0,,-S} command line option.

@ref{89c,,sys.flags.no_site} is set to the inverted value of
@ref{405,,site_import}.

Default: @code{1}.
@end deffn

@geindex PyConfig.skip_source_first_line (C member)
@anchor{c-api/init_config c PyConfig skip_source_first_line}@anchor{558c}
@deffn {C のメンバ変数} int skip_source_first_line

If non-zero, skip the first line of the @ref{551a,,PyConfig.run_filename}
source.

It allows the usage of non-Unix forms of @code{#!cmd}. This is intended for
a DOS specific hack only.

Set to @code{1} by the @ref{212b,,-x} command line option.

Default: @code{0}.
@end deffn

@geindex PyConfig.stdio_encoding (C member)
@anchor{c-api/init_config c PyConfig stdio_encoding}@anchor{644}
@deffn {C のメンバ変数} wchar_t *stdio_encoding
@end deffn

@geindex PyConfig.stdio_errors (C member)
@anchor{c-api/init_config c PyConfig stdio_errors}@anchor{4928}
@deffn {C のメンバ変数} wchar_t *stdio_errors

Encoding and encoding errors of @ref{75f,,sys.stdin}, @ref{ccd,,sys.stdout} and
@ref{b33,,sys.stderr} (but @ref{b33,,sys.stderr} always uses
@code{"backslashreplace"} error handler).

Use the 
@geindex PYTHONIOENCODING
@geindex 環境変数; PYTHONIOENCODING
@ref{120c,,PYTHONIOENCODING} environment variable if it is
non-empty.

Default encoding:


@itemize *

@item 
@code{"UTF-8"} if @ref{41d,,PyPreConfig.utf8_mode} is non-zero.

@item 
Otherwise, use the @ref{54a,,locale encoding}.
@end itemize

Default error handler:


@itemize *

@item 
On Windows: use @code{"surrogateescape"}.

@item 
@code{"surrogateescape"} if @ref{41d,,PyPreConfig.utf8_mode} is non-zero,
or if the LC_CTYPE locale is "C" or "POSIX".

@item 
@code{"strict"} otherwise.
@end itemize

See also @ref{41a,,PyConfig.legacy_windows_stdio}.
@end deffn

@geindex PyConfig.tracemalloc (C member)
@anchor{c-api/init_config c PyConfig tracemalloc}@anchor{558e}
@deffn {C のメンバ変数} int tracemalloc

Enable tracemalloc?

If non-zero, call @ref{212c,,tracemalloc.start()} at startup.

Set by @ref{16f,,-X tracemalloc=N} command line option and by the
@geindex PYTHONTRACEMALLOC
@geindex 環境変数; PYTHONTRACEMALLOC
@ref{212d,,PYTHONTRACEMALLOC} environment variable.

Default: @code{-1} in Python mode, @code{0} in isolated mode.
@end deffn

@geindex PyConfig.perf_profiling (C member)
@anchor{c-api/init_config c PyConfig perf_profiling}@anchor{5587}
@deffn {C のメンバ変数} int perf_profiling

Enable the Linux @code{perf} profiler support?

If equals to @code{1}, enable support for the Linux @code{perf} profiler.

If equals to @code{2}, enable support for the Linux @code{perf} profiler with
DWARF JIT support.

Set to @code{1} by @ref{16f,,-X perf} command-line option and the
@geindex PYTHONPERFSUPPORT
@geindex 環境変数; PYTHONPERFSUPPORT
@ref{699,,PYTHONPERFSUPPORT} environment variable.

Set to @code{2} by the @ref{16f,,-X perf_jit} command-line option and
the 
@geindex PYTHON_PERF_JIT_SUPPORT
@geindex 環境変数; PYTHON_PERF_JIT_SUPPORT
@ref{4af,,PYTHON_PERF_JIT_SUPPORT} environment variable.

Default: @code{-1}.


@subsubheading 参考


See @ref{4ae,,Python support for the Linux perf profiler} for more information.



Added in version 3.12.

@end deffn

@geindex PyConfig.stdlib_dir (C member)
@anchor{c-api/init_config c PyConfig stdlib_dir}@anchor{558d}
@deffn {C のメンバ変数} wchar_t *stdlib_dir

Directory of the Python standard library.

Default: @code{NULL}.


Added in version 3.11.

@end deffn

@geindex PyConfig.use_environment (C member)
@anchor{c-api/init_config c PyConfig use_environment}@anchor{40b}
@deffn {C のメンバ変数} int use_environment

Use @ref{807,,environment variables}?

If equals to zero, ignore the @ref{807,,environment variables}.

Set to @code{0} by the @ref{b56,,-E} environment variable.

Default: @code{1} in Python config and @code{0} in isolated config.
@end deffn

@geindex PyConfig.use_system_logger (C member)
@anchor{c-api/init_config c PyConfig use_system_logger}@anchor{2271}
@deffn {C のメンバ変数} int use_system_logger

If non-zero, @code{stdout} and @code{stderr} will be redirected to the system
log.

Only available on macOS 10.12 and later, and on iOS.

Default: @code{0} (don't use the system log) on macOS; @code{1} on iOS (use the
system log).


Added in version 3.14.

@end deffn

@geindex PyConfig.user_site_directory (C member)
@anchor{c-api/init_config c PyConfig user_site_directory}@anchor{40f}
@deffn {C のメンバ変数} int user_site_directory

If non-zero, add the user site directory to @ref{3e4,,sys.path}.

Set to @code{0} by the @ref{15a6,,-s} and @ref{b57,,-I} command line options.

Set to @code{0} by the 
@geindex PYTHONNOUSERSITE
@geindex 環境変数; PYTHONNOUSERSITE
@ref{15a7,,PYTHONNOUSERSITE} environment variable.

Default: @code{1} in Python mode, @code{0} in isolated mode.
@end deffn

@geindex PyConfig.verbose (C member)
@anchor{c-api/init_config c PyConfig verbose}@anchor{3fb}
@deffn {C のメンバ変数} int verbose

Verbose mode. If greater than @code{0}, print a message each time a module is
imported, showing the place (filename or built-in module) from which
it is loaded.

If greater than or equal to @code{2}, print a message for each file that is
checked for when searching for a module. Also provides information on
module cleanup at exit.

Incremented by the @ref{163e,,-v} command line option.

Set by the 
@geindex PYTHONVERBOSE
@geindex 環境変数; PYTHONVERBOSE
@ref{2128,,PYTHONVERBOSE} environment variable value.

Default: @code{0}.
@end deffn

@geindex PyConfig.warnoptions (C member)
@anchor{c-api/init_config c PyConfig warnoptions}@anchor{641}
@deffn {C のメンバ変数} @ref{ba5,,PyWideStringList} warnoptions

Options of the @ref{118,,warnings} module to build warnings filters, lowest
to highest priority: @ref{3f5,,sys.warnoptions}.

The @ref{118,,warnings} module adds @ref{3f5,,sys.warnoptions} in the reverse
order: the last @ref{641,,PyConfig.warnoptions} item becomes the first
item of @code{warnings.filters} which is checked first (highest
priority).

The @ref{ac6,,-W} command line options adds its value to
@ref{641,,warnoptions}, it can be used multiple times.

The 
@geindex PYTHONWARNINGS
@geindex 環境変数; PYTHONWARNINGS
@ref{da3,,PYTHONWARNINGS} environment variable can also be used to add
warning options. Multiple options can be specified, separated by commas
(@code{,}).

Default: empty list.
@end deffn

@geindex PyConfig.write_bytecode (C member)
@anchor{c-api/init_config c PyConfig write_bytecode}@anchor{40d}
@deffn {C のメンバ変数} int write_bytecode

If equal to @code{0}, Python won't try to write @code{.pyc} files on the import of
source modules.

Set to @code{0} by the @ref{15e6,,-B} command line option and the
@geindex PYTHONDONTWRITEBYTECODE
@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@ref{15e7,,PYTHONDONTWRITEBYTECODE} environment variable.

@ref{48f1,,sys.dont_write_bytecode} is initialized to the inverted value of
@ref{40d,,write_bytecode}.

Default: @code{1}.
@end deffn

@geindex PyConfig.xoptions (C member)
@anchor{c-api/init_config c PyConfig xoptions}@anchor{642}
@deffn {C のメンバ変数} @ref{ba5,,PyWideStringList} xoptions

Values of the @ref{16f,,-X} command line options: @ref{2131,,sys._xoptions}.

Default: empty list.
@end deffn

@geindex PyConfig._pystats (C member)
@anchor{c-api/init_config c PyConfig _pystats}@anchor{5591}
@deffn {C のメンバ変数} int _pystats

If non-zero, write performance statistics at Python exit.

Need a special build with the @code{Py_STATS} macro:
see @ref{1b38,,--enable-pystats}.

Default: @code{0}.
@end deffn
@end deffn

If @ref{1cf1,,parse_argv} is non-zero, @ref{3f1,,argv}
arguments are parsed the same way the regular Python parses @ref{1209,,command line arguments}, and Python arguments are stripped from
@ref{3f1,,argv}.

The @ref{642,,xoptions} options are parsed to set other options: see
the @ref{16f,,-X} command line option.


バージョン 3.9 で変更: The @code{show_alloc_count} field has been removed.


@node Initialization with PyConfig,Isolated Configuration,PyConfig,PyConfig C API
@anchor{c-api/init_config init-from-config}@anchor{5518}@anchor{c-api/init_config initialization-with-pyconfig}@anchor{55a5}
@subsubsection Initialization with PyConfig


Initializing the interpreter from a populated configuration struct is handled
by calling @ref{3f6,,Py_InitializeFromConfig()}.

The caller is responsible to handle exceptions (error or exit) using
@ref{bb0,,PyStatus_Exception()} and @ref{bb9,,Py_ExitStatusException()}.

If @ref{3318,,PyImport_FrozenModules()}, @ref{1b1c,,PyImport_AppendInittab()} or
@ref{1b1d,,PyImport_ExtendInittab()} are used, they must be set or called after
Python preinitialization and before the Python initialization. If Python is
initialized multiple times, @ref{1b1c,,PyImport_AppendInittab()} or
@ref{1b1d,,PyImport_ExtendInittab()} must be called before each Python
initialization.

The current configuration (@code{PyConfig} type) is stored in
@code{PyInterpreterState.config}.

Example setting the program name:

@example
void init_python(void)
@{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* Set the program name. Implicitly preinitialize Python. */
    status = PyConfig_SetString(&config, &config.program_name,
                                L"/path/to/my_program");
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) @{
        goto exception;
    @}
    PyConfig_Clear(&config);
    return;

exception:
    PyConfig_Clear(&config);
    Py_ExitStatusException(status);
@}
@end example

More complete example modifying the default configuration, read the
configuration, and then override some parameters. Note that since
3.11, many parameters are not calculated until initialization, and
so values cannot be read from the configuration structure. Any values
set before initialize is called will be left unchanged by
initialization:

@example
PyStatus init_python(const char *program_name)
@{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* Set the program name before reading the configuration
       (decode byte string from the locale encoding).

       Implicitly preinitialize Python. */
    status = PyConfig_SetBytesString(&config, &config.program_name,
                                     program_name);
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    /* Read all configuration at once */
    status = PyConfig_Read(&config);
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    /* Specify sys.path explicitly */
    /* If you want to modify the default set of paths, finish
       initialization first and then use PySys_GetObject("path") */
    config.module_search_paths_set = 1;
    status = PyWideStringList_Append(&config.module_search_paths,
                                     L"/path/to/stdlib");
    if (PyStatus_Exception(status)) @{
        goto done;
    @}
    status = PyWideStringList_Append(&config.module_search_paths,
                                     L"/path/to/more/modules");
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    /* Override executable computed by PyConfig_Read() */
    status = PyConfig_SetString(&config, &config.executable,
                                L"/path/to/my_executable");
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    status = Py_InitializeFromConfig(&config);

done:
    PyConfig_Clear(&config);
    return status;
@}
@end example

@node Isolated Configuration,Python Configuration,Initialization with PyConfig,PyConfig C API
@anchor{c-api/init_config init-isolated-conf}@anchor{556c}@anchor{c-api/init_config isolated-configuration}@anchor{55a6}
@subsubsection Isolated Configuration


@ref{bad,,PyPreConfig_InitIsolatedConfig()} and
@ref{ba7,,PyConfig_InitIsolatedConfig()} functions create a configuration to
isolate Python from the system. For example, to embed Python into an
application.

This configuration ignores global configuration variables, environment
variables, command line arguments (@ref{3f1,,PyConfig.argv} is not parsed)
and user site directory. The C standard streams (ex: @code{stdout}) and the
LC_CTYPE locale are left unchanged. Signal handlers are not installed.

Configuration files are still used with this configuration to determine
paths that are unspecified. Ensure @ref{3f3,,PyConfig.home} is specified
to avoid computing the default path configuration.

@node Python Configuration,Python Path Configuration,Isolated Configuration,PyConfig C API
@anchor{c-api/init_config init-python-config}@anchor{551c}@anchor{c-api/init_config python-configuration}@anchor{55a7}
@subsubsection Python Configuration


@ref{bae,,PyPreConfig_InitPythonConfig()} and @ref{ba8,,PyConfig_InitPythonConfig()}
functions create a configuration to build a customized Python which behaves as
the regular Python.

Environments variables and command line arguments are used to configure
Python, whereas global configuration variables are ignored.

This function enables C locale coercion (
@geindex Python Enhancement Proposals; PEP 538
PEP 538@footnote{https://peps.python.org/pep-0538/})
and @ref{866,,Python UTF-8 Mode}
(
@geindex Python Enhancement Proposals; PEP 540
PEP 540@footnote{https://peps.python.org/pep-0540/}) depending on the LC_CTYPE locale, 
@geindex PYTHONUTF8
@geindex 環境変数; PYTHONUTF8
@ref{ccf,,PYTHONUTF8} and
@geindex PYTHONCOERCECLOCALE
@geindex 環境変数; PYTHONCOERCECLOCALE
@ref{ccc,,PYTHONCOERCECLOCALE} environment variables.

@node Python Path Configuration,,Python Configuration,PyConfig C API
@anchor{c-api/init_config init-path-config}@anchor{aaa}@anchor{c-api/init_config python-path-configuration}@anchor{55a8}
@subsubsection Python Path Configuration


@ref{3f7,,PyConfig} contains multiple fields for the path configuration:


@itemize *

@item 
Path configuration inputs:


@itemize *

@item 
@ref{3f3,,PyConfig.home}

@item 
@ref{1d21,,PyConfig.platlibdir}

@item 
@ref{409,,PyConfig.pathconfig_warnings}

@item 
@ref{3f2,,PyConfig.program_name}

@item 
@ref{55a4,,PyConfig.pythonpath_env}

@item 
current working directory: to get absolute paths

@item 
@code{PATH} environment variable to get the program full path
(from @ref{3f2,,PyConfig.program_name})

@item 
@code{__PYVENV_LAUNCHER__} environment variable

@item 
(Windows only) Application paths in the registry under
"SoftwarePythonPythonCoreX.YPythonPath" of HKEY_CURRENT_USER and
HKEY_LOCAL_MACHINE (where X.Y is the Python version).
@end itemize

@item 
Path configuration output fields:


@itemize *

@item 
@ref{5575,,PyConfig.base_exec_prefix}

@item 
@ref{5576,,PyConfig.base_executable}

@item 
@ref{5577,,PyConfig.base_prefix}

@item 
@ref{5582,,PyConfig.exec_prefix}

@item 
@ref{645,,PyConfig.executable}

@item 
@ref{805,,PyConfig.module_search_paths_set},
@ref{643,,PyConfig.module_search_paths}

@item 
@ref{5588,,PyConfig.prefix}
@end itemize
@end itemize

If at least one "output field" is not set, Python calculates the path
configuration to fill unset fields. If
@ref{805,,module_search_paths_set} is equal to @code{0},
@ref{643,,module_search_paths} is overridden and
@ref{805,,module_search_paths_set} is set to @code{1}.

It is possible to completely ignore the function calculating the default
path configuration by setting explicitly all path configuration output
fields listed above. A string is considered as set even if it is non-empty.
@code{module_search_paths} is considered as set if
@code{module_search_paths_set} is set to @code{1}. In this case,
@code{module_search_paths} will be used without modification.

Set @ref{409,,pathconfig_warnings} to @code{0} to suppress warnings when
calculating the path configuration (Unix only, Windows does not log any warning).

If @ref{5577,,base_prefix} or @ref{5575,,base_exec_prefix}
fields are not set, they inherit their value from @ref{5588,,prefix}
and @ref{5582,,exec_prefix} respectively.

@ref{bbc,,Py_RunMain()} and @ref{e1e,,Py_Main()} modify @ref{3e4,,sys.path}:


@itemize *

@item 
If @ref{551a,,run_filename} is set and is a directory which contains a
@code{__main__.py} script, prepend @ref{551a,,run_filename} to
@ref{3e4,,sys.path}.

@item 
If @ref{416,,isolated} is zero:


@itemize *

@item 
If @ref{551b,,run_module} is set, prepend the current directory
to @ref{3e4,,sys.path}. Do nothing if the current directory cannot be read.

@item 
If @ref{551a,,run_filename} is set, prepend the directory of the
filename to @ref{3e4,,sys.path}.

@item 
Otherwise, prepend an empty string to @ref{3e4,,sys.path}.
@end itemize
@end itemize

If @ref{405,,site_import} is non-zero, @ref{3e4,,sys.path} can be
modified by the @ref{cc,,site} module. If
@ref{40f,,user_site_directory} is non-zero and the user's
site-package directory exists, the @ref{cc,,site} module appends the user's
site-package directory to @ref{3e4,,sys.path}.

The following configuration files are used by the path configuration:


@itemize *

@item 
@code{pyvenv.cfg}

@item 
@code{._pth} file (ex: @code{python._pth})

@item 
@code{pybuilddir.txt} (Unix only)
@end itemize

If a @code{._pth} file is present:


@itemize *

@item 
Set @ref{416,,isolated} to @code{1}.

@item 
Set @ref{40b,,use_environment} to @code{0}.

@item 
Set @ref{405,,site_import} to @code{0}.

@item 
Set @ref{977,,safe_path} to @code{1}.
@end itemize

If @ref{3f3,,home} is not set and a @code{pyvenv.cfg} file is present in
the same directory as @ref{645,,executable}, or its parent,
@ref{5588,,prefix} and @ref{5582,,exec_prefix} are set that
location. When this happens, @ref{5577,,base_prefix} and
@ref{5575,,base_exec_prefix} still keep their value, pointing to the
base installation. See @ref{48b3,,Virtual Environments} for more
information.

The @code{__PYVENV_LAUNCHER__} environment variable is used to set
@ref{5576,,PyConfig.base_executable}.


バージョン 3.14 で変更: @ref{5588,,prefix}, and @ref{5582,,exec_prefix}, are now
set to the @code{pyvenv.cfg} directory. This was previously done by @ref{cc,,site},
therefore affected by @ref{13c0,,-S}.


@node Py_GetArgcArgv,Delaying main module execution,PyConfig C API,Python 初期化設定
@anchor{c-api/init_config py-getargcargv}@anchor{55a9}
@subsection Py_GetArgcArgv()


@geindex Py_GetArgcArgv (C function)
@anchor{c-api/init_config c Py_GetArgcArgv}@anchor{1d41}
@deffn {C の関数} void Py_GetArgcArgv (int *argc, wchar_t ***argv)

Get the original command line arguments, before Python modified them.

See also @ref{a94,,PyConfig.orig_argv} member.
@end deffn

@node Delaying main module execution,,Py_GetArgcArgv,Python 初期化設定
@anchor{c-api/init_config delaying-main-module-execution}@anchor{55aa}
@subsection Delaying main module execution


In some embedding use cases, it may be desirable to separate interpreter initialization
from the execution of the main module.

This separation can be achieved by setting @code{PyConfig.run_command} to the empty
string during initialization (to prevent the interpreter from dropping into the
interactive prompt), and then subsequently executing the desired main module
code using @code{__main__.__dict__} as the global namespace.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node メモリ管理,オブジェクト実装サポート object implementation support,Python 初期化設定,Python/C API リファレンスマニュアル
@anchor{c-api/memory doc}@anchor{55ab}@anchor{c-api/memory memory}@anchor{559d}@anchor{c-api/memory memory-management}@anchor{55ac}@anchor{c-api/memory translation-repo}@anchor{55ad}
@section メモリ管理


@menu
* 概要: 概要<4>. 
* Allocator Domains:: 
* 生メモリインターフェース:: 
* メモリインターフェース:: 
* オブジェクトアロケータ:: 
* Default Memory Allocators:: 
* メモリアロケータをカスタマイズする:: 
* Debug hooks on the Python memory allocators:: 
* pymalloc アロケータ:: 
* The mimalloc allocator:: 
* tracemalloc C API:: 
* 使用例: 使用例<56>. 

@end menu

@node 概要<4>,Allocator Domains,,メモリ管理
@anchor{c-api/memory memoryoverview}@anchor{55ae}@anchor{c-api/memory overview}@anchor{55af}
@subsection 概要


Python におけるメモリ管理には、全ての Python オブジェクトとデータ構造が入ったプライベートヒープ (private heap) が必須です。プライベートヒープの管理は、内部的には `Python メモリマネージャ (Python memory manager)' が確実に行います。Python メモリマネージャには、共有 (sharing)、セグメント分割 (segmentation)、事前割り当て (preallocation)、キャッシュ化 (caching) といった、様々な動的記憶管理の側面を扱うために、個別のコンポーネントがあります。

最低水準層では、素のメモリ操作関数 (raw memory allocator) がオペレーティングシステムのメモリ管理機構とやりとりして、プライベートヒープ内にPython 関連の全てのデータを記憶するのに十分な空きがあるかどうか確認します。素のメモリ操作関数の上には、いくつかのオブジェクト固有のメモリ操作関数があります。これらは同じヒープを操作し、各オブジェクト型固有の事情に合ったメモリ管理ポリシを実装しています。例えば、整数オブジェクトは文字列やタプル、辞書とは違ったやり方でヒープ内で管理されます。というのも、整数には値を記憶する上で特別な要件があり、速度/容量のトレードオフが存在するからです。このように、Python メモリマネジャは作業のいくつかをオブジェクト固有のメモリ操作関数に委譲しますが、これらの関数がプライベートヒープからはみ出してメモリ管理を行わないようにしています。

重要なのは、たとえユーザがいつもヒープ内のメモリブロックを指すようなオブジェクトポインタを操作しているとしても、Python 用ヒープの管理はインタプリタ自体が行うもので、ユーザがそれを制御する余地はないと理解することです。Python オブジェクトや内部使用されるバッファを入れるためのヒープ空間のメモリ確保は、必要に応じて、Python メモリマネージャがこのドキュメント内で列挙しているPython/C API 関数群を介して行います。

@geindex malloc (C function)
@geindex calloc (C function)
@geindex realloc (C function)
@geindex free (C function)

メモリ管理の崩壊を避けるため、拡張モジュールの作者は決して Python  オブジェクトを C ライブラリが公開している関数: @code{malloc()} 、 @code{calloc()} 、 @code{realloc()} および @code{free()} で操作しようとしてはなりません。こうした関数を使うと、C のメモリ操作関数と Python メモリマネージャとの間で関数呼び出しが交錯します。 C のメモリ操作関数とPython メモリマネージャは異なるアルゴリズムで実装されていて、異なるヒープを操作するため、呼び出しの交錯は致命的な結果を招きます。とはいえ、個別の目的のためなら、 C ライブラリのメモリ操作関数を使って安全にメモリを確保したり解放したりできます。例えば、以下がそのような例です:

@example
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
free(buf); /* malloc'ed */
return res;
@end example

この例では、I/O バッファに対するメモリ要求は C ライブラリのメモリ操作関数を使っています。Python メモリマネージャーは戻り値として返される bytes オブジェクトを確保する時にだけ必要です。

とはいえ、ほとんどの状況では、メモリの操作は Python ヒープに固定して行うよう勧めます。なぜなら、Python ヒープは Python メモリマネジャの管理下にあるからです。例えば、インタプリタを C で書かれた新たなオブジェクト型で拡張する際には、ヒープでのメモリ管理が必要です。Python ヒープを使った方がよいもう一つの理由として、拡張モジュールが必要としているメモリについて Python メモリマネージャに `情報を提供' してほしいということがあります。たとえ必要なメモリが内部的かつ非常に特化した用途に対して排他的に用いられるものだとしても、全てのメモリ操作要求を Python メモリマネージャに委譲すれば、インタプリタはより正確なメモリフットプリントの全体像を把握できます。その結果、特定の状況では、Python メモリマネージャがガベージコレクションやメモリのコンパクト化、その他何らかの予防措置といった、適切な動作をトリガできることがあります。上の例で示したように C ライブラリのメモリ操作関数を使うと、I/O バッファ用に確保したメモリは Python メモリマネージャの管理から完全に外れることに注意してください。


@subsubheading 参考


環境変数 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} を使用して Python が利用するメモリアロケータを制御することができます。

環境変数 
@geindex PYTHONMALLOCSTATS
@geindex 環境変数; PYTHONMALLOCSTATS
@ref{1f37,,PYTHONMALLOCSTATS} を使用して、新たなオブジェクトアリーナが生成される時と、シャットダウン時に @ref{f0b,,pymalloc メモリアロケータ} の統計情報を表示できます。


@node Allocator Domains,生メモリインターフェース,概要<4>,メモリ管理
@anchor{c-api/memory allocator-domains}@anchor{55b0}
@subsection Allocator Domains

@anchor{c-api/memory id1}@anchor{55b1}
All allocating functions belong to one of three different "domains" (see also
@ref{55b2,,PyMemAllocatorDomain}). These domains represent different allocation
strategies and are optimized for different purposes. The specific details on
how every domain allocates memory or what internal functions each domain calls
is considered an implementation detail, but for debugging purposes a simplified
table can be found at @ref{213b,,Default Memory Allocators}.
The APIs used to allocate and free a block of memory must be from the same domain.
For example, @ref{165b,,PyMem_Free()} must be used to free memory allocated using @ref{e5f,,PyMem_Malloc()}.

The three allocation domains are:


@itemize *

@item 
Raw domain: intended for allocating memory for general-purpose memory
buffers where the allocation `must' go to the system allocator or where the
allocator can operate without an @ref{4ed1,,attached thread state}. The memory
is requested directly from the system. See @ref{55b3,,Raw Memory Interface}.

@item 
"Mem" domain: intended for allocating memory for Python buffers and
general-purpose memory buffers where the allocation must be performed with
an @ref{4ed1,,attached thread state}. The memory is taken from the Python private heap.
See @ref{55b4,,Memory Interface}.

@item 
Object domain: intended for allocating memory for Python objects. The
memory is taken from the Python private heap. See @ref{55b5,,Object allocators}.
@end itemize

@cartouche
@quotation 注釈 
The @ref{1f4,,free-threaded} build requires that only Python objects are allocated using the "object" domain
and that all Python objects are allocated using that domain. This differs from the prior Python versions,
where this was only a best practice and not a hard requirement.

For example, buffers (non-Python objects) should be allocated using @ref{e5f,,PyMem_Malloc()},
@ref{631,,PyMem_RawMalloc()}, or @code{malloc()}, but not @ref{e62,,PyObject_Malloc()}.

See @ref{55b6,,Memory Allocation APIs}.
@end quotation
@end cartouche

@node 生メモリインターフェース,メモリインターフェース,Allocator Domains,メモリ管理
@anchor{c-api/memory raw-memory-interface}@anchor{55b7}@anchor{c-api/memory raw-memoryinterface}@anchor{55b3}
@subsection 生メモリインターフェース


The following function sets are wrappers to the system allocator. These
functions are thread-safe, so a @ref{1846,,thread state} does not
need to be @ref{4ed1,,attached}.

The @ref{213b,,default raw memory allocator} uses
the following functions: @code{malloc()}, @code{calloc()}, @code{realloc()}
and @code{free()}; call @code{malloc(1)} (or @code{calloc(1, 1)}) when requesting
zero bytes.


Added in version 3.4.


@geindex PyMem_RawMalloc (C function)
@anchor{c-api/memory c PyMem_RawMalloc}@anchor{631}
@deffn {C の関数} void *PyMem_RawMalloc (size_t n)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
`n' バイトを割り当て、そのメモリを指す void* 型のポインタを返します。要求が失敗した場合 @code{NULL} を返します。

0バイトを要求すると、 @code{PyMem_RawMalloc(1)} が呼ばれたときと同じように、可能なら @code{NULL} でないユニークなポインタを返します。確保されたメモリーにはいかなる初期化も行われません。
@end deffn

@geindex PyMem_RawCalloc (C function)
@anchor{c-api/memory c PyMem_RawCalloc}@anchor{632}
@deffn {C の関数} void *PyMem_RawCalloc (size_t nelem, size_t elsize)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
各要素が `elsize' バイトの要素 `nelem' 個分のメモリーを確保し、そのメモリーを指す void* 型のポインタを返します。アロケートに失敗した場合は @code{NULL} を返します。確保されたメモリー領域はゼロで初期化されます。

要素数か要素のサイズが0バイトの要求に対しては、可能なら @code{PyMem_RawCalloc(1, 1)} が呼ばれたのと同じように、ユニークな @code{NULL} でないポインタを返します。


Added in version 3.5.

@end deffn

@geindex PyMem_RawRealloc (C function)
@anchor{c-api/memory c PyMem_RawRealloc}@anchor{633}
@deffn {C の関数} void *PyMem_RawRealloc (void *p, size_t n)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
`p' が指すメモリブロックを `n' バイトにリサイズします。古いサイズと新しいサイズの小さい方までの内容は変更されません。

`p' が @code{NULL} の場合呼び出しは @code{PyMem_RawMalloc(n)} と等価です。そうでなく、 `n' がゼロに等しい場合、メモリブロックはリサイズされますが解放されません。返されたポインタは非 @code{NULL} です。

`p' が @code{NULL} でない限り、`p' はそれより前の @ref{631,,PyMem_RawMalloc()}, @ref{633,,PyMem_RawRealloc()}, @ref{632,,PyMem_RawCalloc()} の呼び出しにより返されなければなりません。

要求が失敗した場合 @ref{633,,PyMem_RawRealloc()} は @code{NULL} を返し、 `p' は前のメモリエリアをさす有効なポインタのままです。
@end deffn

@geindex PyMem_RawFree (C function)
@anchor{c-api/memory c PyMem_RawFree}@anchor{634}
@deffn {C の関数} void PyMem_RawFree (void *p)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
`p' が指すメモリブロックを解放します。 `p' は以前呼び出した @ref{631,,PyMem_RawMalloc()}, @ref{633,,PyMem_RawRealloc()},  @ref{632,,PyMem_RawCalloc()} の返した値でなければなりません。それ以外の場合や @code{PyMem_RawFree(p)} を呼び出した後だった場合、未定義の動作になります。

`p' が @code{NULL} の場合何もしません。
@end deffn

@node メモリインターフェース,オブジェクトアロケータ,生メモリインターフェース,メモリ管理
@anchor{c-api/memory memory-interface}@anchor{55b8}@anchor{c-api/memory memoryinterface}@anchor{55b4}
@subsection メモリインターフェース


以下の関数群が利用して Python ヒープに対してメモリを確保したり解放したり出来ます。これらの関数は ANSI C 標準に従ってモデル化されていますが、0 バイトを要求した際の動作についても定義しています:

The @ref{213b,,default memory allocator} uses the
@ref{f0b,,pymalloc memory allocator}.

@cartouche
@quotation 警告 
There must be an @ref{4ed1,,attached thread state} when using these functions.
@end quotation
@end cartouche


バージョン 3.6 で変更: デフォルトのアロケータがシステムの @code{malloc()} から pymalloc になりました。


@geindex PyMem_Malloc (C function)
@anchor{c-api/memory c PyMem_Malloc}@anchor{e5f}
@deffn {C の関数} void *PyMem_Malloc (size_t n)
` 次に属します: @ref{775,,Stable ABI}.'
`n' バイトを割り当て、そのメモリを指す void* 型のポインタを返します。要求が失敗した場合 @code{NULL} を返します。

0バイトを要求すると、 @code{PyMem_Malloc(1)} が呼ばれたときと同じように、可能なら @code{NULL} でないユニークなポインタを返します。
確保されたメモリーにはいかなる初期化も行われません。
@end deffn

@geindex PyMem_Calloc (C function)
@anchor{c-api/memory c PyMem_Calloc}@anchor{10ad}
@deffn {C の関数} void *PyMem_Calloc (size_t nelem, size_t elsize)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
各要素が `elsize' バイトの要素 `nelem' 個分のメモリーを確保し、そのメモリーを指す void* 型のポインタを返します。アロケートに失敗した場合は @code{NULL} を返します。確保されたメモリー領域はゼロで初期化されます。

要素数か要素のサイズが0バイトの要求に対しては、可能なら @code{PyMem_Calloc(1, 1)} が呼ばれたのと同じように、ユニークな @code{NULL} でないポインタを返します。


Added in version 3.5.

@end deffn

@geindex PyMem_Realloc (C function)
@anchor{c-api/memory c PyMem_Realloc}@anchor{1233}
@deffn {C の関数} void *PyMem_Realloc (void *p, size_t n)
` 次に属します: @ref{775,,Stable ABI}.'
`p' が指すメモリブロックを `n' バイトにリサイズします。古いサイズと新しいサイズの小さい方までの内容は変更されません。

`p' が @code{NULL} の場合呼び出しは @code{PyMem_Malloc(n)} と等価です。そうでなく、 `n' がゼロに等しい場合、メモリブロックはリサイズされますが解放されません。返されたポインタは非 @code{NULL} です。

`p' が @code{NULL} でない限り、`p' はそれより前の @ref{e5f,,PyMem_Malloc()}, @ref{1233,,PyMem_Realloc()} または @ref{10ad,,PyMem_Calloc()} の呼び出しにより返されなければなりません。

要求が失敗した場合 @ref{1233,,PyMem_Realloc()} は @code{NULL} を返し、 `p' は前のメモリエリアをさす有効なポインタのままです。
@end deffn

@geindex PyMem_Free (C function)
@anchor{c-api/memory c PyMem_Free}@anchor{165b}
@deffn {C の関数} void PyMem_Free (void *p)
` 次に属します: @ref{775,,Stable ABI}.'
`p' が指すメモリブロックを解放します。 `p' は以前呼び出した @ref{e5f,,PyMem_Malloc()}、 @ref{1233,,PyMem_Realloc()}、または @ref{10ad,,PyMem_Calloc()} の返した値でなければなりません。それ以外の場合や @code{PyMem_Free(p)} を呼び出した後だった場合、未定義の動作になります。

`p' が @code{NULL} の場合何もしません。
@end deffn

以下に挙げる型対象のマクロは利便性のために提供されているものです。`TYPE' は任意の C の型を表します。

@geindex PyMem_New (C macro)
@anchor{c-api/memory c PyMem_New}@anchor{173d}
@deffn {C のマクロ} PyMem_New (TYPE, n)

Same as @ref{e5f,,PyMem_Malloc()}, but allocates @code{(n * sizeof(TYPE))} bytes of
memory.  Returns a pointer cast to @code{TYPE*}.  The memory will not have
been initialized in any way.
@end deffn

@geindex PyMem_Resize (C macro)
@anchor{c-api/memory c PyMem_Resize}@anchor{55b9}
@deffn {C のマクロ} PyMem_Resize (p, TYPE, n)

Same as @ref{1233,,PyMem_Realloc()}, but the memory block is resized to @code{(n *
sizeof(TYPE))} bytes.  Returns a pointer cast to @code{TYPE*}. On return,
`p' will be a pointer to the new memory area, or @code{NULL} in the event of
failure.

これは C プリプロセッサマクロです。`p' は常に再代入されます。エラー処理時にメモリを失うのを避けるには `p' の元の値を保存してください。
@end deffn

@geindex PyMem_Del (C function)
@anchor{c-api/memory c PyMem_Del}@anchor{173e}
@deffn {C の関数} void PyMem_Del (void *p)

@ref{165b,,PyMem_Free()} と同じです。
@end deffn

@menu
* 非推奨のエイリアス: 非推奨のエイリアス<2>. 

@end menu

@node 非推奨のエイリアス<2>,,,メモリインターフェース
@anchor{c-api/memory deprecated-aliases}@anchor{55ba}
@subsubsection 非推奨のエイリアス


These are @ref{23d,,soft deprecated} aliases to existing functions and macros.
They exist solely for backwards compatibility.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

非推奨のエイリアス

@tab

Corresponding function or macro

@item

@geindex PyMem_MALLOC (C macro)
@anchor{c-api/memory c PyMem_MALLOC}@anchor{55bb}
@deffn {C のマクロ} PyMem_MALLOC (size)
@end deffn

@tab

@ref{e5f,,PyMem_Malloc()}

@item

@geindex PyMem_NEW (C macro)
@anchor{c-api/memory c PyMem_NEW}@anchor{55bc}
@deffn {C のマクロ} PyMem_NEW (type, size)
@end deffn

@tab

@ref{173d,,PyMem_New}

@item

@geindex PyMem_REALLOC (C macro)
@anchor{c-api/memory c PyMem_REALLOC}@anchor{55bd}
@deffn {C のマクロ} PyMem_REALLOC (ptr, size)
@end deffn

@tab

@ref{1233,,PyMem_Realloc()}

@item

@geindex PyMem_RESIZE (C macro)
@anchor{c-api/memory c PyMem_RESIZE}@anchor{55be}
@deffn {C のマクロ} PyMem_RESIZE (ptr, type, size)
@end deffn

@tab

@ref{55b9,,PyMem_Resize}

@item

@geindex PyMem_FREE (C macro)
@anchor{c-api/memory c PyMem_FREE}@anchor{55bf}
@deffn {C のマクロ} PyMem_FREE (ptr)
@end deffn

@tab

@ref{165b,,PyMem_Free()}

@item

@geindex PyMem_DEL (C macro)
@anchor{c-api/memory c PyMem_DEL}@anchor{55c0}
@deffn {C のマクロ} PyMem_DEL (ptr)
@end deffn

@tab

@ref{165b,,PyMem_Free()}

@end multitable



バージョン 3.4 で変更: The macros are now aliases of the corresponding functions and macros.
Previously, their behavior was the same, but their use did not necessarily
preserve binary compatibility across Python versions.



バージョン 2.0 で非推奨.


@node オブジェクトアロケータ,Default Memory Allocators,メモリインターフェース,メモリ管理
@anchor{c-api/memory object-allocators}@anchor{55c1}@anchor{c-api/memory objectinterface}@anchor{55b5}
@subsection オブジェクトアロケータ


以下の関数群が利用して Python ヒープに対してメモリを確保したり解放したり出来ます。これらの関数は ANSI C 標準に従ってモデル化されていますが、0 バイトを要求した際の動作についても定義しています:

@cartouche
@quotation 注釈 
There is no guarantee that the memory returned by these allocators can be
successfully cast to a Python object when intercepting the allocating
functions in this domain by the methods described in
the @ref{55c2,,Customize Memory Allocators} section.
@end quotation
@end cartouche

The @ref{213b,,default object allocator} uses the
@ref{f0b,,pymalloc memory allocator}.

@cartouche
@quotation 警告 
There must be an @ref{4ed1,,attached thread state} when using these functions.
@end quotation
@end cartouche

@geindex PyObject_Malloc (C function)
@anchor{c-api/memory c PyObject_Malloc}@anchor{e62}
@deffn {C の関数} void *PyObject_Malloc (size_t n)
` 次に属します: @ref{775,,Stable ABI}.'
`n' バイトを割り当て、そのメモリを指す void* 型のポインタを返します。要求が失敗した場合 @code{NULL} を返します。

0バイトを要求すると、 @code{PyObject_Malloc(1)} が呼ばれたときと同じように、可能なら @code{NULL} でないユニークなポインタを返します。
確保されたメモリーにはいかなる初期化も行われません。
@end deffn

@geindex PyObject_Calloc (C function)
@anchor{c-api/memory c PyObject_Calloc}@anchor{10ae}
@deffn {C の関数} void *PyObject_Calloc (size_t nelem, size_t elsize)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
各要素が `elsize' バイトの要素 `nelem' 個分のメモリーを確保し、そのメモリーを指す void* 型のポインタを返します。アロケートに失敗した場合は @code{NULL} を返します。確保されたメモリー領域はゼロで初期化されます。

要素数か要素のサイズが0バイトの要求に対しては、可能なら @code{PyObject_Calloc(1, 1)} が呼ばれたのと同じように、ユニークな @code{NULL} でないポインタを返します。


Added in version 3.5.

@end deffn

@geindex PyObject_Realloc (C function)
@anchor{c-api/memory c PyObject_Realloc}@anchor{165c}
@deffn {C の関数} void *PyObject_Realloc (void *p, size_t n)
` 次に属します: @ref{775,,Stable ABI}.'
`p' が指すメモリブロックを `n' バイトにリサイズします。古いサイズと新しいサイズの小さい方までの内容は変更されません。

`p' が @code{NULL} の場合呼び出しは @code{PyObject_Malloc(n)} と等価です。そうでなく、 `n' がゼロに等しい場合、メモリブロックはリサイズされますが解放されません。返されたポインタは非 @code{NULL} です。

`p' が @code{NULL} でない限り、`p' はそれより前の @ref{e62,,PyObject_Malloc()}, @ref{165c,,PyObject_Realloc()} または @ref{10ae,,PyObject_Calloc()} の呼び出しにより返されなければなりません。

要求が失敗した場合 @ref{165c,,PyObject_Realloc()} は @code{NULL} を返し、 `p' は前のメモリエリアをさす有効なポインタのままです。
@end deffn

@geindex PyObject_Free (C function)
@anchor{c-api/memory c PyObject_Free}@anchor{e60}
@deffn {C の関数} void PyObject_Free (void *p)
` 次に属します: @ref{775,,Stable ABI}.'
`p' が指すメモリブロックを解放します。 `p' は以前呼び出した @ref{e62,,PyObject_Malloc()}、 @ref{165c,,PyObject_Realloc()}、または @ref{10ae,,PyObject_Calloc()} の返した値でなければなりません。それ以外の場合や @code{PyObject_Free(p)} を呼び出した後だった場合、未定義の動作になります。

`p' が @code{NULL} の場合何もしません。

Do not call this directly to free an object's memory; call the type's
@ref{4ecf,,tp_free} slot instead.

Do not use this for memory allocated by @ref{c99,,PyObject_GC_New} or
@ref{c9a,,PyObject_GC_NewVar}; use @ref{171c,,PyObject_GC_Del()} instead.


@subsubheading 参考



@itemize *

@item 
@ref{171c,,PyObject_GC_Del()} is the equivalent of this function for memory
allocated by types that support garbage collection.

@item 
@ref{e62,,PyObject_Malloc()}

@item 
@ref{165c,,PyObject_Realloc()}

@item 
@ref{10ae,,PyObject_Calloc()}

@item 
@ref{b7c,,PyObject_New}

@item 
@ref{b7d,,PyObject_NewVar}

@item 
@ref{c61,,PyType_GenericAlloc()}

@item 
@ref{4ecf,,tp_free}
@end itemize

@end deffn

@node Default Memory Allocators,メモリアロケータをカスタマイズする,オブジェクトアロケータ,メモリ管理
@anchor{c-api/memory default-memory-allocators}@anchor{213b}@anchor{c-api/memory id2}@anchor{55c3}
@subsection Default Memory Allocators


Default memory allocators:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Configuration

@tab

名前

@tab

PyMem_RawMalloc

@tab

PyMem_Malloc

@tab

PyObject_Malloc

@item

リリースビルド

@tab

@code{"pymalloc"}

@tab

@code{malloc}

@tab

@code{pymalloc}

@tab

@code{pymalloc}

@item

デバッグビルド

@tab

@code{"pymalloc_debug"}

@tab

@code{malloc} + debug

@tab

@code{pymalloc} + debug

@tab

@code{pymalloc} + debug

@item

pymalloc 無しのリリースビルド

@tab

@code{"malloc"}

@tab

@code{malloc}

@tab

@code{malloc}

@tab

@code{malloc}

@item

pymalloc 無しのデバッグビルド

@tab

@code{"malloc_debug"}

@tab

@code{malloc} + debug

@tab

@code{malloc} + debug

@tab

@code{malloc} + debug

@end multitable


説明:


@itemize *

@item 
Name: value for 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable.

@item 
@code{malloc}: system allocators from the standard C library, C functions:
@code{malloc()}, @code{calloc()}, @code{realloc()} and @code{free()}.

@item 
@code{pymalloc}: @ref{f0b,,pymalloc memory allocator}.

@item 
@code{mimalloc}: @ref{213d,,mimalloc memory allocator}.  The pymalloc
allocator will be used if mimalloc support isn't available.

@item 
"+ debug": with @ref{213e,,debug hooks on the Python memory allocators}.

@item 
"Debug build": @ref{509,,Python build in debug mode}.
@end itemize

@node メモリアロケータをカスタマイズする,Debug hooks on the Python memory allocators,Default Memory Allocators,メモリ管理
@anchor{c-api/memory customize-memory-allocators}@anchor{55c2}@anchor{c-api/memory id3}@anchor{55c4}
@subsection メモリアロケータをカスタマイズする



Added in version 3.4.


@geindex PyMemAllocatorEx (C type)
@anchor{c-api/memory c PyMemAllocatorEx}@anchor{10ce}
@deffn {C のデータ型} type PyMemAllocatorEx

Structure used to describe a memory block allocator. The structure has
the following fields:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

フィールド

@tab

意味

@item

@code{void *ctx}

@tab

第一引数として渡されるユーザコンテキスト

@item

@code{void* malloc(void *ctx, size_t size)}

@tab

メモリブロックを割り当てます

@item

@code{void* calloc(void *ctx, size_t nelem, size_t elsize)}

@tab

0で初期化されたメモリブロックを割り当てます

@item

@code{void* realloc(void *ctx, void *ptr, size_t new_size)}

@tab

メモリブロックを割り当てるかリサイズします

@item

@code{void free(void *ctx, void *ptr)}

@tab

メモリブロックを解放する

@end multitable



バージョン 3.5 で変更: The @code{PyMemAllocator} structure was renamed to
@ref{10ce,,PyMemAllocatorEx} and a new @code{calloc} field was added.

@end deffn

@geindex PyMemAllocatorDomain (C type)
@anchor{c-api/memory c PyMemAllocatorDomain}@anchor{55b2}
@deffn {C のデータ型} type PyMemAllocatorDomain

アロケータドメインを同定するための列挙型です。ドメインは:

@geindex PYMEM_DOMAIN_RAW (C macro)
@anchor{c-api/memory c PYMEM_DOMAIN_RAW}@anchor{213c}
@deffn {C のマクロ} PYMEM_DOMAIN_RAW

関数:


@itemize *

@item 
@ref{631,,PyMem_RawMalloc()}

@item 
@ref{633,,PyMem_RawRealloc()}

@item 
@ref{632,,PyMem_RawCalloc()}

@item 
@ref{634,,PyMem_RawFree()}
@end itemize
@end deffn

@geindex PYMEM_DOMAIN_MEM (C macro)
@anchor{c-api/memory c PYMEM_DOMAIN_MEM}@anchor{e63}
@deffn {C のマクロ} PYMEM_DOMAIN_MEM

関数:


@itemize *

@item 
@ref{e5f,,PyMem_Malloc()},

@item 
@ref{1233,,PyMem_Realloc()}

@item 
@ref{10ad,,PyMem_Calloc()}

@item 
@ref{165b,,PyMem_Free()}
@end itemize
@end deffn

@geindex PYMEM_DOMAIN_OBJ (C macro)
@anchor{c-api/memory c PYMEM_DOMAIN_OBJ}@anchor{e61}
@deffn {C のマクロ} PYMEM_DOMAIN_OBJ

関数:


@itemize *

@item 
@ref{e62,,PyObject_Malloc()}

@item 
@ref{165c,,PyObject_Realloc()}

@item 
@ref{10ae,,PyObject_Calloc()}

@item 
@ref{e60,,PyObject_Free()}
@end itemize
@end deffn
@end deffn

@geindex PyMem_GetAllocator (C function)
@anchor{c-api/memory c PyMem_GetAllocator}@anchor{5514}
@deffn {C の関数} void PyMem_GetAllocator (PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)

指定されたドメインのメモリブロックアロケータを取得します。
@end deffn

@geindex PyMem_SetAllocator (C function)
@anchor{c-api/memory c PyMem_SetAllocator}@anchor{7a8}
@deffn {C の関数} void PyMem_SetAllocator (PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)

指定されたドメインのメモリブロックアロケータを設定します。

新しいアロケータは、0バイトを要求されたときユニークな @code{NULL} でないポインタを返さなければなりません。

For the @ref{213c,,PYMEM_DOMAIN_RAW} domain, the allocator must be
thread-safe: a @ref{1846,,thread state} is not @ref{4ed1,,attached}
when the allocator is called.

For the remaining domains, the allocator must also be thread-safe:
the allocator may be called in different interpreters that do not
share a @ref{164,,GIL}.

新しいアロケータがフックでない (1つ前のアロケータを呼び出さない) 場合、 @ref{e64,,PyMem_SetupDebugHooks()} 関数を呼び出して、新しいアロケータの上にデバッグフックを再度設置しなければなりません。

See also @ref{5574,,PyPreConfig.allocator} and @ref{42c8,,Preinitialize Python with PyPreConfig}.

@cartouche
@quotation 警告 
@ref{7a8,,PyMem_SetAllocator()} does have the following contract:


@itemize *

@item 
It can be called after @ref{41e,,Py_PreInitialize()} and before
@ref{3f6,,Py_InitializeFromConfig()} to install a custom memory
allocator. There are no restrictions over the installed allocator
other than the ones imposed by the domain (for instance, the Raw
Domain allows the allocator to be called without an @ref{4ed1,,attached thread state}).
See @ref{55b1,,the section on allocator domains} for more
information.

@item 
If called after Python has finish initializing (after
@ref{3f6,,Py_InitializeFromConfig()} has been called) the allocator
`must' wrap the existing allocator. Substituting the current
allocator for some other arbitrary one is `not supported'.
@end itemize
@end quotation
@end cartouche


バージョン 3.12 で変更: All allocators must be thread-safe.

@end deffn

@geindex PyMem_SetupDebugHooks (C function)
@anchor{c-api/memory c PyMem_SetupDebugHooks}@anchor{e64}
@deffn {C の関数} void PyMem_SetupDebugHooks (void)

Setup @ref{213e,,debug hooks in the Python memory allocators}
to detect memory errors.
@end deffn

@node Debug hooks on the Python memory allocators,pymalloc アロケータ,メモリアロケータをカスタマイズする,メモリ管理
@anchor{c-api/memory debug-hooks-on-the-python-memory-allocators}@anchor{55c5}@anchor{c-api/memory pymem-debug-hooks}@anchor{213e}
@subsection Debug hooks on the Python memory allocators


When @ref{509,,Python is built in debug mode}, the
@ref{e64,,PyMem_SetupDebugHooks()} function is called at the @ref{42c8,,Python preinitialization} to setup debug hooks on Python memory allocators
to detect memory errors.

The 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable can be used to install debug
hooks on a Python compiled in release mode (ex: @code{PYTHONMALLOC=debug}).

The @ref{e64,,PyMem_SetupDebugHooks()} function can be used to set debug hooks
after calling @ref{7a8,,PyMem_SetAllocator()}.

These debug hooks fill dynamically allocated memory blocks with special,
recognizable bit patterns. Newly allocated memory is filled with the byte
@code{0xCD} (@code{PYMEM_CLEANBYTE}), freed memory is filled with the byte @code{0xDD}
(@code{PYMEM_DEADBYTE}). Memory blocks are surrounded by "forbidden bytes"
filled with the byte @code{0xFD} (@code{PYMEM_FORBIDDENBYTE}). Strings of these bytes
are unlikely to be valid addresses, floats, or ASCII strings.

実行時チェック:


@itemize -

@item 
Detect API violations. For example, detect if @ref{e60,,PyObject_Free()} is
called on a memory block allocated by @ref{e5f,,PyMem_Malloc()}.

@item 
Detect write before the start of the buffer (buffer underflow).

@item 
Detect write after the end of the buffer (buffer overflow).

@item 
Check that there is an @ref{4ed1,,attached thread state} when
allocator functions of @ref{e61,,PYMEM_DOMAIN_OBJ} (ex:
@ref{e62,,PyObject_Malloc()}) and @ref{e63,,PYMEM_DOMAIN_MEM} (ex:
@ref{e5f,,PyMem_Malloc()}) domains are called.
@end itemize

On error, the debug hooks use the @ref{105,,tracemalloc} module to get the
traceback where a memory block was allocated. The traceback is only displayed
if @ref{105,,tracemalloc} is tracing Python memory allocations and the memory block
was traced.

Let `S' = @code{sizeof(size_t)}. @code{2*S} bytes are added at each end of each block
of `N' bytes requested.  The memory layout is like so, where p represents the
address returned by a malloc-like or realloc-like function (@code{p[i:j]} means
the slice of bytes from @code{*(p+i)} inclusive up to @code{*(p+j)} exclusive; note
that the treatment of negative indices differs from a Python slice):


@table @asis

@item @code{p[-2*S:-S]}

Number of bytes originally asked for.  This is a size_t, big-endian (easier
to read in a memory dump).

@item @code{p[-S]}

API identifier (ASCII character):


@itemize *

@item 
@code{'r'} for @ref{213c,,PYMEM_DOMAIN_RAW}.

@item 
@code{'m'} for @ref{e63,,PYMEM_DOMAIN_MEM}.

@item 
@code{'o'} for @ref{e61,,PYMEM_DOMAIN_OBJ}.
@end itemize

@item @code{p[-S+1:0]}

Copies of PYMEM_FORBIDDENBYTE.  Used to catch under- writes and reads.

@item @code{p[0:N]}

The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch
reference to uninitialized memory.  When a realloc-like function is called
requesting a larger memory block, the new excess bytes are also filled with
PYMEM_CLEANBYTE.  When a free-like function is called, these are
overwritten with PYMEM_DEADBYTE, to catch reference to freed memory.  When
a realloc- like function is called requesting a smaller memory block, the
excess old bytes are also filled with PYMEM_DEADBYTE.

@item @code{p[N:N+S]}

Copies of PYMEM_FORBIDDENBYTE.  Used to catch over- writes and reads.

@item @code{p[N+S:N+2*S]}

Only used if the @code{PYMEM_DEBUG_SERIALNO} macro is defined (not defined by
default).

A serial number, incremented by 1 on each call to a malloc-like or
realloc-like function.  Big-endian @code{size_t}.  If "bad memory" is detected
later, the serial number gives an excellent way to set a breakpoint on the
next run, to capture the instant at which this block was passed out.  The
static function bumpserialno() in obmalloc.c is the only place the serial
number is incremented, and exists so you can set such a breakpoint easily.
@end table

A realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE
bytes at each end are intact.  If they've been altered, diagnostic output is
written to stderr, and the program is aborted via Py_FatalError().  The other
main failure mode is provoking a memory error when a program reads up one of
the special bit patterns and tries to use it as an address.  If you get in a
debugger then and look at the object, you're likely to see that it's entirely
filled with PYMEM_DEADBYTE (meaning freed memory is getting used) or
PYMEM_CLEANBYTE (meaning uninitialized memory is getting used).


バージョン 3.6 で変更: The @ref{e64,,PyMem_SetupDebugHooks()} function now also works on Python
compiled in release mode.  On error, the debug hooks now use
@ref{105,,tracemalloc} to get the traceback where a memory block was allocated.
The debug hooks now also check if there is an @ref{4ed1,,attached thread state} when
functions of @ref{e61,,PYMEM_DOMAIN_OBJ} and @ref{e63,,PYMEM_DOMAIN_MEM} domains are
called.



バージョン 3.8 で変更: Byte patterns @code{0xCB} (@code{PYMEM_CLEANBYTE}), @code{0xDB} (@code{PYMEM_DEADBYTE})
and @code{0xFB} (@code{PYMEM_FORBIDDENBYTE}) have been replaced with @code{0xCD},
@code{0xDD} and @code{0xFD} to use the same values than Windows CRT debug
@code{malloc()} and @code{free()}.


@node pymalloc アロケータ,The mimalloc allocator,Debug hooks on the Python memory allocators,メモリ管理
@anchor{c-api/memory pymalloc}@anchor{f0b}@anchor{c-api/memory the-pymalloc-allocator}@anchor{55c6}
@subsection pymalloc アロケータ


Python has a `pymalloc' allocator optimized for small objects (smaller or equal
to 512 bytes) with a short lifetime. It uses memory mappings called "arenas"
with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit
platforms. It falls back to @ref{631,,PyMem_RawMalloc()} and
@ref{633,,PyMem_RawRealloc()} for allocations larger than 512 bytes.

`pymalloc' is the @ref{213b,,default allocator} of the
@ref{e63,,PYMEM_DOMAIN_MEM} (ex: @ref{e5f,,PyMem_Malloc()}) and
@ref{e61,,PYMEM_DOMAIN_OBJ} (ex: @ref{e62,,PyObject_Malloc()}) domains.

アリーナアロケータは、次の関数を使います:


@itemize *

@item 
@code{VirtualAlloc()} and @code{VirtualFree()} on Windows,

@item 
@code{mmap()} and @code{munmap()} if available,

@item 
それ以外の場合は @code{malloc()} と @code{free()}。
@end itemize

This allocator is disabled if Python is configured with the
@ref{21a1,,--without-pymalloc} option. It can also be disabled at runtime using
the 
@geindex PYTHONMALLOC
@geindex 環境変数; PYTHONMALLOC
@ref{e5e,,PYTHONMALLOC} environment variable (ex: @code{PYTHONMALLOC=malloc}).

Typically, it makes sense to disable the pymalloc allocator when building
Python with AddressSanitizer (@ref{21aa,,--with-address-sanitizer}) which helps
uncover low level bugs within the C code.

@menu
* pymalloc アリーナアロケータのカスタマイズ:: 

@end menu

@node pymalloc アリーナアロケータのカスタマイズ,,,pymalloc アロケータ
@anchor{c-api/memory customize-pymalloc-arena-allocator}@anchor{55c7}
@subsubsection pymalloc アリーナアロケータのカスタマイズ



Added in version 3.4.


@geindex PyObjectArenaAllocator (C type)
@anchor{c-api/memory c PyObjectArenaAllocator}@anchor{55c8}
@deffn {C のデータ型} type PyObjectArenaAllocator

アリーナアロケータを記述するための構造体です。3つのフィールドを持ちます:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

フィールド

@tab

意味

@item

@code{void *ctx}

@tab

第一引数として渡されるユーザコンテキスト

@item

@code{void* alloc(void *ctx, size_t size)}

@tab

size バイトのアリーナを割り当てます

@item

@code{void free(void *ctx, void *ptr, size_t size)}

@tab

アリーナを解放します

@end multitable

@end deffn

@geindex PyObject_GetArenaAllocator (C function)
@anchor{c-api/memory c PyObject_GetArenaAllocator}@anchor{5515}
@deffn {C の関数} void PyObject_GetArenaAllocator (PyObjectArenaAllocator *allocator)

アリーナアロケータを取得します。
@end deffn

@geindex PyObject_SetArenaAllocator (C function)
@anchor{c-api/memory c PyObject_SetArenaAllocator}@anchor{5513}
@deffn {C の関数} void PyObject_SetArenaAllocator (PyObjectArenaAllocator *allocator)

アリーナアロケータを設定します。
@end deffn

@node The mimalloc allocator,tracemalloc C API,pymalloc アロケータ,メモリ管理
@anchor{c-api/memory mimalloc}@anchor{213d}@anchor{c-api/memory the-mimalloc-allocator}@anchor{55c9}
@subsection The mimalloc allocator



Added in version 3.13.


Python supports the mimalloc allocator when the underlying platform support is available.
mimalloc "is a general purpose allocator with excellent performance characteristics.
Initially developed by Daan Leijen for the runtime systems of the Koka and Lean languages."

@node tracemalloc C API,使用例<56>,The mimalloc allocator,メモリ管理
@anchor{c-api/memory tracemalloc-c-api}@anchor{55ca}
@subsection tracemalloc C API



Added in version 3.7.


@geindex PyTraceMalloc_Track (C function)
@anchor{c-api/memory c PyTraceMalloc_Track}@anchor{daf}
@deffn {C の関数} int PyTraceMalloc_Track (unsigned int domain, uintptr_t ptr, size_t size)

Track an allocated memory block in the @ref{105,,tracemalloc} module.

Return @code{0} on success, return @code{-1} on error (failed to allocate memory to
store the trace). Return @code{-2} if tracemalloc is disabled.

If memory block is already tracked, update the existing trace.
@end deffn

@geindex PyTraceMalloc_Untrack (C function)
@anchor{c-api/memory c PyTraceMalloc_Untrack}@anchor{db0}
@deffn {C の関数} int PyTraceMalloc_Untrack (unsigned int domain, uintptr_t ptr)

Untrack an allocated memory block in the @ref{105,,tracemalloc} module.
Do nothing if the block was not tracked.

Return @code{-2} if tracemalloc is disabled, otherwise return @code{0}.
@end deffn

@node 使用例<56>,,tracemalloc C API,メモリ管理
@anchor{c-api/memory examples}@anchor{55cb}@anchor{c-api/memory memoryexamples}@anchor{55cc}
@subsection 使用例


最初に述べた関数セットを使って、 @ref{55ae,,概要} 節の例を Python ヒープに I/O バッファをメモリ確保するように書き換えたものを以下に示します:

@example
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
@end example

同じコードを型対象の関数セットで書いたものを以下に示します:

@example
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_New */
return res;
@end example

上の二つの例では、バッファを常に同じ関数セットに属する関数で操作していることに注意してください。実際、あるメモリブロックに対する操作は、異なるメモリ操作機構を混用する危険を減らすために、同じメモリ API ファミリを使って行うことが必要です。以下のコードには二つのエラーがあり、そのうちの一つには異なるヒープを操作する別のメモリ操作関数を混用しているので `致命的 (Fatal)' とラベルづけをしています。

@example
char *buf1 = PyMem_New(char, BUFSIZ);
char *buf2 = (char *) malloc(BUFSIZ);
char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
...
PyMem_Del(buf3);  /* Wrong -- should be PyMem_Free() */
free(buf2);       /* Right -- allocated via malloc() */
free(buf1);       /* Fatal -- should be PyMem_Free()  */
@end example

In addition to the functions aimed at handling raw memory blocks from the Python
heap, objects in Python are allocated and released with @ref{b7c,,PyObject_New},
@ref{b7d,,PyObject_NewVar} and @ref{e60,,PyObject_Free()}.

これらの関数については、次章の C による新しいオブジェクト型の定義や実装に関する記述の中で説明します。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node オブジェクト実装サポート object implementation support,API と ABI のバージョニング,メモリ管理,Python/C API リファレンスマニュアル
@anchor{c-api/objimpl doc}@anchor{55cd}@anchor{c-api/objimpl newtypes}@anchor{55ce}@anchor{c-api/objimpl object-implementation-support}@anchor{55cf}@anchor{c-api/objimpl translation-repo}@anchor{55d0}
@section オブジェクト実装サポート (object implementation support)


この章では、新しいオブジェクトの型を定義する際に使われる関数、型、およびマクロについて説明します。

@menu
* オブジェクトをヒープ上にメモリ確保する:: 
* Object Life Cycle:: 
* 共通のオブジェクト構造体 (common object structure): 共通のオブジェクト構造体 common object structure. 
* Type Object Structures:: 
* 循環参照ガベージコレクションをサポートする:: 

@end menu

@node オブジェクトをヒープ上にメモリ確保する,Object Life Cycle,,オブジェクト実装サポート object implementation support
@anchor{c-api/allocation doc}@anchor{55d1}@anchor{c-api/allocation allocating-objects}@anchor{55d2}@anchor{c-api/allocation allocating-objects-on-the-heap}@anchor{55d3}
@subsection オブジェクトをヒープ上にメモリ確保する


@geindex _PyObject_New (C function)
@anchor{c-api/allocation c _PyObject_New}@anchor{55d4}
@deffn {C の関数} @ref{5df,,PyObject} *_PyObject_New (PyTypeObject *type)
`戻り値: 新しい参照。'
@end deffn

@geindex _PyObject_NewVar (C function)
@anchor{c-api/allocation c _PyObject_NewVar}@anchor{55d5}
@deffn {C の関数} @ref{46d6,,PyVarObject} *_PyObject_NewVar (PyTypeObject *type, Py_ssize_t size)
`戻り値: 新しい参照。'
@end deffn

@geindex PyObject_Init (C function)
@anchor{c-api/allocation c PyObject_Init}@anchor{c60}
@deffn {C の関数} @ref{5df,,PyObject} *PyObject_Init (PyObject *op, PyTypeObject *type)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
Initialize a newly allocated object `op' with its type and initial
reference.  Returns the initialized object.  Other fields of the object are
not initialized.  Despite its name, this function is unrelated to the
object's @ref{8bf,,__init__()} method (@ref{7a1,,tp_init}
slot).  Specifically, this function does `not' call the object's
@code{__init__()} method.

In general, consider this function to be a low-level routine. Use
@ref{4ed0,,tp_alloc} where possible.
For implementing @code{tp_alloc} for your type, prefer
@ref{c61,,PyType_GenericAlloc()} or @ref{b7c,,PyObject_New()}.

@cartouche
@quotation 注釈 
This function only initializes the object's memory corresponding to the
initial @ref{5df,,PyObject} structure.  It does not zero the rest.
@end quotation
@end cartouche
@end deffn

@geindex PyObject_InitVar (C function)
@anchor{c-api/allocation c PyObject_InitVar}@anchor{1d40}
@deffn {C の関数} @ref{46d6,,PyVarObject} *PyObject_InitVar (PyVarObject *op, PyTypeObject *type, Py_ssize_t size)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI}.'
@ref{c60,,PyObject_Init()} の全ての処理を行い、可変サイズオブジェクトの場合には長さ情報も初期化します。

@cartouche
@quotation 注釈 
This function only initializes some of the object's memory.  It does not
zero the rest.
@end quotation
@end cartouche
@end deffn

@geindex PyObject_New (C macro)
@anchor{c-api/allocation c PyObject_New}@anchor{b7c}
@deffn {C のマクロ} PyObject_New (TYPE, typeobj)

Allocates a new Python object using the C structure type `TYPE' and the
Python type object `typeobj' (@code{PyTypeObject*}) by calling
@ref{e62,,PyObject_Malloc()} to allocate memory and initializing it like
@ref{c60,,PyObject_Init()}.  The caller will own the only reference to the
object (i.e. its reference count will be one).

Avoid calling this directly to allocate memory for an object; call the type's
@ref{4ed0,,tp_alloc} slot instead.

When populating a type's @ref{4ed0,,tp_alloc} slot,
@ref{c61,,PyType_GenericAlloc()} is preferred over a custom function that
simply calls this macro.

This macro does not call @ref{4ed0,,tp_alloc},
@ref{79f,,tp_new} (@ref{7a0,,__new__()}), or
@ref{7a1,,tp_init} (@ref{8bf,,__init__()}).

This cannot be used for objects with @ref{981,,Py_TPFLAGS_HAVE_GC} set in
@ref{1c71,,tp_flags}; use @ref{c99,,PyObject_GC_New} instead.

Memory allocated by this macro must be freed with @ref{e60,,PyObject_Free()}
(usually called via the object's @ref{4ecf,,tp_free} slot).

@cartouche
@quotation 注釈 
The returned memory is not guaranteed to have been completely zeroed
before it was initialized.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
This macro does not construct a fully initialized object of the given
type; it merely allocates memory and prepares it for further
initialization by @ref{7a1,,tp_init}.  To construct a
fully initialized object, call `typeobj' instead.  For example:

@example
PyObject *foo = PyObject_CallNoArgs((PyObject *)&PyFoo_Type);
@end example
@end quotation
@end cartouche


@subsubheading 参考



@itemize *

@item 
@ref{e60,,PyObject_Free()}

@item 
@ref{c99,,PyObject_GC_New}

@item 
@ref{c61,,PyType_GenericAlloc()}

@item 
@ref{4ed0,,tp_alloc}
@end itemize

@end deffn

@geindex PyObject_NewVar (C macro)
@anchor{c-api/allocation c PyObject_NewVar}@anchor{b7d}
@deffn {C のマクロ} PyObject_NewVar (TYPE, typeobj, size)

Like @ref{b7c,,PyObject_New} except:


@itemize *

@item 
It allocates enough memory for the `TYPE' structure plus `size'
(@code{Py_ssize_t}) fields of the size given by the
@ref{23bb,,tp_itemsize} field of `typeobj'.

@item 
The memory is initialized like @ref{1d40,,PyObject_InitVar()}.
@end itemize

This is useful for implementing objects like tuples, which are able to
determine their size at construction time.  Embedding the array of fields
into the same allocation decreases the number of allocations, improving the
memory management efficiency.

Avoid calling this directly to allocate memory for an object; call the type's
@ref{4ed0,,tp_alloc} slot instead.

When populating a type's @ref{4ed0,,tp_alloc} slot,
@ref{c61,,PyType_GenericAlloc()} is preferred over a custom function that
simply calls this macro.

This cannot be used for objects with @ref{981,,Py_TPFLAGS_HAVE_GC} set in
@ref{1c71,,tp_flags}; use @ref{c9a,,PyObject_GC_NewVar}
instead.

Memory allocated by this function must be freed with @ref{e60,,PyObject_Free()}
(usually called via the object's @ref{4ecf,,tp_free} slot).

@cartouche
@quotation 注釈 
The returned memory is not guaranteed to have been completely zeroed
before it was initialized.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
This macro does not construct a fully initialized object of the given
type; it merely allocates memory and prepares it for further
initialization by @ref{7a1,,tp_init}.  To construct a
fully initialized object, call `typeobj' instead.  For example:

@example
PyObject *list_instance = PyObject_CallNoArgs((PyObject *)&PyList_Type);
@end example
@end quotation
@end cartouche


@subsubheading 参考



@itemize *

@item 
@ref{e60,,PyObject_Free()}

@item 
@ref{c9a,,PyObject_GC_NewVar}

@item 
@ref{c61,,PyType_GenericAlloc()}

@item 
@ref{4ed0,,tp_alloc}
@end itemize

@end deffn

@geindex _Py_NoneStruct (C var)
@anchor{c-api/allocation c _Py_NoneStruct}@anchor{55d6}
@deffn {C 変数} @ref{5df,,PyObject} _Py_NoneStruct

Python からは @code{None} に見えるオブジェクトです。この値へのアクセスは、このオブジェクトへのポインタを評価する @ref{4e9f,,Py_None} マクロを使わなければなりません。
@end deffn


@subsubheading 参考



@table @asis

@item @ref{543d,,モジュールオブジェクト (module object)}

拡張モジュールのアロケートと生成。
@end table


@menu
* 非推奨のエイリアス: 非推奨のエイリアス<3>. 

@end menu

@node 非推奨のエイリアス<3>,,,オブジェクトをヒープ上にメモリ確保する
@anchor{c-api/allocation deprecated-aliases}@anchor{55d7}
@subsubsection 非推奨のエイリアス


These are @ref{23d,,soft deprecated} aliases to existing functions and macros.
They exist solely for backwards compatibility.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

非推奨のエイリアス

@tab

関数

@item

@geindex PyObject_NEW (C macro)
@anchor{c-api/allocation c PyObject_NEW}@anchor{55d8}
@deffn {C のマクロ} PyObject_NEW (type, typeobj)
@end deffn

@tab

@ref{b7c,,PyObject_New}

@item

@geindex PyObject_NEW_VAR (C macro)
@anchor{c-api/allocation c PyObject_NEW_VAR}@anchor{55d9}
@deffn {C のマクロ} PyObject_NEW_VAR (type, typeobj, n)
@end deffn

@tab

@ref{b7d,,PyObject_NewVar}

@item

@geindex PyObject_INIT (C macro)
@anchor{c-api/allocation c PyObject_INIT}@anchor{1d3e}
@deffn {C のマクロ} PyObject_INIT (op, typeobj)
@end deffn

@tab

@ref{c60,,PyObject_Init()}

@item

@geindex PyObject_INIT_VAR (C macro)
@anchor{c-api/allocation c PyObject_INIT_VAR}@anchor{1d3f}
@deffn {C のマクロ} PyObject_INIT_VAR (op, typeobj, n)
@end deffn

@tab

@ref{1d40,,PyObject_InitVar()}

@item

@geindex PyObject_MALLOC (C macro)
@anchor{c-api/allocation c PyObject_MALLOC}@anchor{55da}
@deffn {C のマクロ} PyObject_MALLOC (n)
@end deffn

@tab

@ref{e62,,PyObject_Malloc()}

@item

@geindex PyObject_REALLOC (C macro)
@anchor{c-api/allocation c PyObject_REALLOC}@anchor{55db}
@deffn {C のマクロ} PyObject_REALLOC (p, n)
@end deffn

@tab

@ref{165c,,PyObject_Realloc()}

@item

@geindex PyObject_FREE (C macro)
@anchor{c-api/allocation c PyObject_FREE}@anchor{55dc}
@deffn {C のマクロ} PyObject_FREE (p)
@end deffn

@tab

@ref{e60,,PyObject_Free()}

@item

@geindex PyObject_DEL (C macro)
@anchor{c-api/allocation c PyObject_DEL}@anchor{55dd}
@deffn {C のマクロ} PyObject_DEL (p)
@end deffn

@tab

@ref{e60,,PyObject_Free()}

@item

@geindex PyObject_Del (C macro)
@anchor{c-api/allocation c PyObject_Del}@anchor{16ea}
@deffn {C のマクロ} PyObject_Del (p)
@end deffn

@tab

@ref{e60,,PyObject_Free()}

@end multitable


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Object Life Cycle,共通のオブジェクト構造体 common object structure,オブジェクトをヒープ上にメモリ確保する,オブジェクト実装サポート object implementation support
@anchor{c-api/lifecycle doc}@anchor{55de}@anchor{c-api/lifecycle life-cycle}@anchor{55df}@anchor{c-api/lifecycle object-life-cycle}@anchor{55e0}@anchor{c-api/lifecycle translation-repo}@anchor{55e1}
@subsection Object Life Cycle


This section explains how a type's slots relate to each other throughout the
life of an object.  It is not intended to be a complete canonical reference for
the slots; instead, refer to the slot-specific documentation in
@ref{b84,,Type Object Structures} for details about a particular slot.

@menu
* Life Events:: 
* Cyclic Isolate Destruction:: 
* 関数: 関数<15>. 

@end menu

@node Life Events,Cyclic Isolate Destruction,,Object Life Cycle
@anchor{c-api/lifecycle life-events}@anchor{55e2}
@subsubsection Life Events


The figure below illustrates the order of events that can occur throughout an
object's life.  An arrow from `A' to `B' indicates that event `B' can occur
after event `A' has occurred, with the arrow's label indicating the condition
that must be true for `B' to occur after `A'.


@image{python-figures/lifecycle.dot,,,Diagram showing events in an object's life. Explained in detail below.,svg}


Explanation:


@itemize *

@item 
When a new object is constructed by calling its type:


@enumerate 

@item 
@ref{79f,,tp_new} is called to create a new object.

@item 
@ref{4ed0,,tp_alloc} is directly called by
@ref{79f,,tp_new} to allocate the memory for the new
object.

@item 
@ref{7a1,,tp_init} initializes the newly created object.
@code{tp_init} can be called again to re-initialize an object, if
desired. The @code{tp_init} call can also be skipped entirely,
for example by Python code calling @ref{7a0,,__new__()}.
@end enumerate

@item 
After @code{tp_init} completes, the object is ready to use.

@item 
Some time after the last reference to an object is removed:


@enumerate 

@item 
If an object is not marked as `finalized', it might be finalized by
marking it as `finalized' and calling its
@ref{c9d,,tp_finalize} function.  Python does
`not' finalize an object when the last reference to it is deleted; use
@ref{55e3,,PyObject_CallFinalizerFromDealloc()} to ensure that
@ref{c9d,,tp_finalize} is always called.

@item 
If the object is marked as finalized,
@ref{4ee2,,tp_clear} might be called by the garbage collector
to clear references held by the object.  It is `not' called when the
object's reference count reaches zero.

@item 
@ref{4ebc,,tp_dealloc} is called to destroy the object.
To avoid code duplication, @ref{4ebc,,tp_dealloc} typically
calls into @ref{4ee2,,tp_clear} to free up the object's
references.

@item 
When @ref{4ebc,,tp_dealloc} finishes object destruction,
it directly calls @ref{4ecf,,tp_free} (usually set to
@ref{e60,,PyObject_Free()} or @ref{171c,,PyObject_GC_Del()} automatically as
appropriate for the type) to deallocate the memory.
@end enumerate

@item 
The @ref{c9d,,tp_finalize} function is permitted to add a
reference to the object if desired.  If it does, the object is
`resurrected', preventing its pending destruction.  (Only
@code{tp_finalize} is allowed to resurrect an object;
@ref{4ee2,,tp_clear} and
@ref{4ebc,,tp_dealloc} cannot without calling into
@code{tp_finalize}.)  Resurrecting an object may
or may not cause the object's `finalized' mark to be removed.  Currently,
Python does not remove the `finalized' mark from a resurrected object if
it supports garbage collection (i.e., the @ref{981,,Py_TPFLAGS_HAVE_GC}
flag is set) but does remove the mark if the object does not support
garbage collection; either or both of these behaviors may change in the
future.

@item 
@ref{4ebc,,tp_dealloc} can optionally call
@ref{c9d,,tp_finalize} via
@ref{55e3,,PyObject_CallFinalizerFromDealloc()} if it wishes to reuse that
code to help with object destruction.  This is recommended because it
guarantees that @code{tp_finalize} is always called before
destruction.  See the @ref{4ebc,,tp_dealloc} documentation
for example code.

@item 
If the object is a member of a @ref{55e4,,cyclic isolate} and either
@ref{4ee2,,tp_clear} fails to break the reference cycle or
the cyclic isolate is not detected (perhaps @ref{4a0f,,gc.disable()} was called,
or the @ref{981,,Py_TPFLAGS_HAVE_GC} flag was erroneously omitted in one
of the involved types), the objects remain indefinitely uncollectable
(they "leak").  See @ref{13d9,,gc.garbage}.
@end itemize

If the object is marked as supporting garbage collection (the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag is set in
@ref{1c71,,tp_flags}), the following events are also possible:


@itemize *

@item 
The garbage collector occasionally calls
@ref{982,,tp_traverse} to identify @ref{55e4,,cyclic isolates}.

@item 
When the garbage collector discovers a @ref{55e4,,cyclic isolate}, it
finalizes one of the objects in the group by marking it as `finalized' and
calling its @ref{c9d,,tp_finalize} function, if it has one.
This repeats until the cyclic isolate doesn't exist or all of the objects
have been finalized.

@item 
@ref{c9d,,tp_finalize} is permitted to resurrect the object
by adding a reference from outside the @ref{55e4,,cyclic isolate}.  The new
reference causes the group of objects to no longer form a cyclic isolate
(the reference cycle may still exist, but if it does the objects are no
longer isolated).

@item 
When the garbage collector discovers a @ref{55e4,,cyclic isolate} and all of
the objects in the group have already been marked as `finalized', the
garbage collector clears one or more of the uncleared objects in the group
(possibly concurrently) by calling each's
@ref{4ee2,,tp_clear} function.  This repeats as long as the
cyclic isolate still exists and not all of the objects have been cleared.
@end itemize

@node Cyclic Isolate Destruction,関数<15>,Life Events,Object Life Cycle
@anchor{c-api/lifecycle cyclic-isolate-destruction}@anchor{55e5}
@subsubsection Cyclic Isolate Destruction


Listed below are the stages of life of a hypothetical @ref{55e4,,cyclic isolate}
that continues to exist after each member object is finalized or cleared.  It
is a memory leak if a cyclic isolate progresses through all of these stages; it should
vanish once all objects are cleared, if not sooner.  A cyclic isolate can
vanish either because the reference cycle is broken or because the objects are
no longer isolated due to finalizer resurrection (see
@ref{c9d,,tp_finalize}).


@enumerate 0

@item 
`Reachable' (not yet a cyclic isolate): All objects are in their normal,
reachable state.  A reference cycle could exist, but an external reference
means the objects are not yet isolated.

@item 
`Unreachable but consistent:' The final reference from outside the cyclic
group of objects has been removed, causing the objects to become isolated
(thus a cyclic isolate is born).  None of the group's objects have been
finalized or cleared yet.  The cyclic isolate remains at this stage until
some future run of the garbage collector (not necessarily the next run
because the next run might not scan every object).

@item 
`Mix of finalized and not finalized:' Objects in a cyclic isolate are
finalized one at a time, which means that there is a period of time when the
cyclic isolate is composed of a mix of finalized and non-finalized objects.
Finalization order is unspecified, so it can appear random.  A finalized
object must behave in a sane manner when non-finalized objects interact with
it, and a non-finalized object must be able to tolerate the finalization of
an arbitrary subset of its referents.

@item 
`All finalized:' All objects in a cyclic isolate are finalized before any
of them are cleared.

@item 
`Mix of finalized and cleared:' The objects can be cleared serially or
concurrently (but with the @ref{164,,GIL} held); either way, some will finish
before others.  A finalized object must be able to tolerate the clearing of
a subset of its referents.  
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/} calls this stage "cyclic trash".

@item 
`Leaked:' If a cyclic isolate still exists after all objects in the group
have been finalized and cleared, then the objects remain indefinitely
uncollectable (see @ref{13d9,,gc.garbage}).  It is a bug if a cyclic isolate
reaches this stage---it means the @ref{4ee2,,tp_clear} methods
of the participating objects have failed to break the reference cycle as
required.
@end enumerate

If @ref{4ee2,,tp_clear} did not exist, then Python would have no
way to safely break a reference cycle.  Simply destroying an object in a cyclic
isolate would result in a dangling pointer, triggering undefined behavior when
an object referencing the destroyed object is itself destroyed.  The clearing
step makes object destruction a two-phase process: first
@ref{4ee2,,tp_clear} is called to partially destroy the objects
enough to detangle them from each other, then
@ref{4ebc,,tp_dealloc} is called to complete the destruction.

Unlike clearing, finalization is not a phase of destruction.  A finalized
object must still behave properly by continuing to fulfill its design
contracts.  An object's finalizer is allowed to execute arbitrary Python code,
and is even allowed to prevent the impending destruction by adding a reference.
The finalizer is only related to destruction by call order---if it runs, it runs
before destruction, which starts with @ref{4ee2,,tp_clear} (if
called) and concludes with @ref{4ebc,,tp_dealloc}.

The finalization step is not necessary to safely reclaim the objects in a
cyclic isolate, but its existence makes it easier to design types that behave
in a sane manner when objects are cleared.  Clearing an object might
necessarily leave it in a broken, partially destroyed state---it might be
unsafe to call any of the cleared object's methods or access any of its
attributes.  With finalization, only finalized objects can possibly interact
with cleared objects; non-finalized objects are guaranteed to interact with
only non-cleared (but potentially finalized) objects.

To summarize the possible interactions:


@itemize *

@item 
A non-finalized object might have references to or from non-finalized and
finalized objects, but not to or from cleared objects.

@item 
A finalized object might have references to or from non-finalized, finalized,
and cleared objects.

@item 
A cleared object might have references to or from finalized and cleared
objects, but not to or from non-finalized objects.
@end itemize

Without any reference cycles, an object can be simply destroyed once its last
reference is deleted; the finalization and clearing steps are not necessary to
safely reclaim unused objects.  However, it can be useful to automatically call
@ref{c9d,,tp_finalize} and @ref{4ee2,,tp_clear}
before destruction anyway because type design is simplified when all objects
always experience the same series of events regardless of whether they
participated in a cyclic isolate.  Python currently only calls
@ref{c9d,,tp_finalize} and @ref{4ee2,,tp_clear} as
needed to destroy a cyclic isolate; this may change in a future version.

@node 関数<15>,,Cyclic Isolate Destruction,Object Life Cycle
@anchor{c-api/lifecycle functions}@anchor{55e6}
@subsubsection 関数


To allocate and free memory, see @ref{55d2,,オブジェクトをヒープ上にメモリ確保する}.

@geindex PyObject_CallFinalizer (C function)
@anchor{c-api/lifecycle c PyObject_CallFinalizer}@anchor{55e7}
@deffn {C の関数} void PyObject_CallFinalizer (PyObject *op)

Finalizes the object as described in @ref{c9d,,tp_finalize}.
Call this function (or @ref{55e3,,PyObject_CallFinalizerFromDealloc()}) instead
of calling @ref{c9d,,tp_finalize} directly because this
function may deduplicate multiple calls to @code{tp_finalize}.
Currently, calls are only deduplicated if the type supports garbage
collection (i.e., the @ref{981,,Py_TPFLAGS_HAVE_GC} flag is set); this may
change in the future.


Added in version 3.4.

@end deffn

@geindex PyObject_CallFinalizerFromDealloc (C function)
@anchor{c-api/lifecycle c PyObject_CallFinalizerFromDealloc}@anchor{55e3}
@deffn {C の関数} int PyObject_CallFinalizerFromDealloc (PyObject *op)

Same as @ref{55e7,,PyObject_CallFinalizer()} but meant to be called at the
beginning of the object's destructor (@ref{4ebc,,tp_dealloc}).
There must not be any references to the object.  If the object's finalizer
resurrects the object, this function returns -1; no further destruction
should happen.  Otherwise, this function returns 0 and destruction can
continue normally.


Added in version 3.4.



@subsubheading 参考


@ref{4ebc,,tp_dealloc} for example code.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 共通のオブジェクト構造体 common object structure,Type Object Structures,Object Life Cycle,オブジェクト実装サポート object implementation support
@anchor{c-api/structures doc}@anchor{55e8}@anchor{c-api/structures common-object-structures}@anchor{55e9}@anchor{c-api/structures common-structs}@anchor{55ea}@anchor{c-api/structures translation-repo}@anchor{55eb}
@subsection 共通のオブジェクト構造体 (common object structure)


Python では、オブジェクト型を定義する上で数多くの構造体が使われます。この節では三つの構造体とその利用方法について説明します。

@menu
* Base object types and macros:: 
* Implementing functions and methods:: 
* Accessing attributes of extension types:: 

@end menu

@node Base object types and macros,Implementing functions and methods,,共通のオブジェクト構造体 common object structure
@anchor{c-api/structures base-object-types-and-macros}@anchor{55ec}
@subsubsection Base object types and macros


All Python objects ultimately share a small number of fields at the beginning
of the object's representation in memory.  These are represented by the
@ref{5df,,PyObject} and @ref{46d6,,PyVarObject} types, which are defined, in turn,
by the expansions of some macros also used, whether directly or indirectly, in
the definition of all other Python objects.  Additional macros can be found
under @ref{51e7,,reference counting}.

@geindex PyObject (C type)
@anchor{c-api/structures c PyObject}@anchor{5df}
@deffn {C のデータ型} type PyObject
` 次に属します: @ref{775,,Limited API}. (いくつかのメンバーのみが安定 ABI です。)'
All object types are extensions of this type.  This is a type which
contains the information Python needs to treat a pointer to an object as an
object.  In a normal "release" build, it contains only the object's
reference count and a pointer to the corresponding type object.
Nothing is actually declared to be a @ref{5df,,PyObject}, but every pointer
to a Python object can be cast to a @ref{5df,,PyObject}*.

The members must not be accessed directly; instead use macros such as
@ref{2cf,,Py_REFCNT} and @ref{3c9,,Py_TYPE}.

@geindex PyObject.ob_refcnt (C member)
@anchor{c-api/structures c PyObject ob_refcnt}@anchor{a9f}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} ob_refcnt
` 次に属します: @ref{775,,Stable ABI}.'
The object's reference count, as returned by @ref{2cf,,Py_REFCNT}.
Do not use this field directly; instead use functions and macros such as
@code{Py_REFCNT}, @ref{78f,,Py_INCREF()} and @ref{512a,,Py_DecRef()}.

The field type may be different from @code{Py_ssize_t}, depending on
build configuration and platform.
@end deffn

@geindex PyObject.ob_type (C member)
@anchor{c-api/structures c PyObject ob_type}@anchor{4ecd}
@deffn {C のメンバ変数} @ref{c9c,,PyTypeObject} *ob_type
` 次に属します: @ref{775,,Stable ABI}.'
The object's type.
Do not use this field directly; use @ref{3c9,,Py_TYPE} and
@ref{984,,Py_SET_TYPE()} instead.
@end deffn
@end deffn

@geindex PyVarObject (C type)
@anchor{c-api/structures c PyVarObject}@anchor{46d6}
@deffn {C のデータ型} type PyVarObject
` 次に属します: @ref{775,,Limited API}. (いくつかのメンバーのみが安定 ABI です。)'
An extension of @ref{5df,,PyObject} that adds the
@ref{511c,,ob_size} field.
This is intended for objects that have some notion of `length'.

As with @code{PyObject}, the members must not be accessed directly;
instead use macros such as @ref{985,,Py_SIZE}, @ref{2cf,,Py_REFCNT} and
@ref{3c9,,Py_TYPE}.

@geindex PyVarObject.ob_size (C member)
@anchor{c-api/structures c PyVarObject ob_size}@anchor{511c}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} ob_size
` 次に属します: @ref{775,,Stable ABI}.'
A size field, whose contents should be considered an object's internal
implementation detail.

Do not use this field directly; use @ref{985,,Py_SIZE} instead.

Object creation functions such as @ref{b7d,,PyObject_NewVar()} will
generally set this field to the requested size (number of items).
After creation, arbitrary values can be stored in @code{ob_size}
using @ref{986,,Py_SET_SIZE}.

To get an object's publicly exposed length, as returned by
the Python function @ref{840,,len()}, use @ref{5094,,PyObject_Length()}
instead.
@end deffn
@end deffn

@geindex PyObject_HEAD (C macro)
@anchor{c-api/structures c PyObject_HEAD}@anchor{14f5}
@deffn {C のマクロ} PyObject_HEAD

可変な長さを持たないオブジェクトを表現する新しい型を宣言するときに使うマクロです。
PyObject_HEAD マクロは次のように展開されます:

@example
PyObject ob_base;
@end example

上にある @ref{5df,,PyObject} のドキュメントを参照してください。
@end deffn

@geindex PyObject_VAR_HEAD (C macro)
@anchor{c-api/structures c PyObject_VAR_HEAD}@anchor{55ed}
@deffn {C のマクロ} PyObject_VAR_HEAD

インスタンスごとに異なる長さを持つオブジェクトを表現する新しい型を宣言するときに使うマクロです。
PyObject_VAR_HEAD マクロは次のように展開されます:

@example
PyVarObject ob_base;
@end example

上にある @ref{46d6,,PyVarObject} のドキュメントを参照してください。
@end deffn

@geindex PyBaseObject_Type (C var)
@anchor{c-api/structures c PyBaseObject_Type}@anchor{4f75}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyBaseObject_Type
` 次に属します: @ref{775,,Stable ABI}.'
The base class of all other objects, the same as @ref{c7e,,object} in Python.
@end deffn

@geindex Py_Is (C function)
@anchor{c-api/structures c Py_Is}@anchor{aa0}
@deffn {C の関数} int Py_Is (PyObject *x, PyObject *y)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Test if the `x' object is the `y' object, the same as @code{x is y} in Python.


Added in version 3.10.

@end deffn

@geindex Py_IsNone (C function)
@anchor{c-api/structures c Py_IsNone}@anchor{aa1}
@deffn {C の関数} int Py_IsNone (PyObject *x)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Test if an object is the @code{None} singleton,
the same as @code{x is None} in Python.


Added in version 3.10.

@end deffn

@geindex Py_IsTrue (C function)
@anchor{c-api/structures c Py_IsTrue}@anchor{aa2}
@deffn {C の関数} int Py_IsTrue (PyObject *x)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Test if an object is the @code{True} singleton,
the same as @code{x is True} in Python.


Added in version 3.10.

@end deffn

@geindex Py_IsFalse (C function)
@anchor{c-api/structures c Py_IsFalse}@anchor{aa3}
@deffn {C の関数} int Py_IsFalse (PyObject *x)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Test if an object is the @code{False} singleton,
the same as @code{x is False} in Python.


Added in version 3.10.

@end deffn

@geindex Py_TYPE (C function)
@anchor{c-api/structures c Py_TYPE}@anchor{3c9}
@deffn {C の関数} @ref{c9c,,PyTypeObject} *Py_TYPE (PyObject *o)
`戻り値: 借用参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Get the type of the Python object `o'.

The returned reference is @ref{3d7,,borrowed} from `o'.
Do not release it with @ref{790,,Py_DECREF()} or similar.


バージョン 3.11 で変更: @ref{3c9,,Py_TYPE()} is changed to an inline static function.
The parameter type is no longer const @ref{5df,,PyObject}*.

@end deffn

@geindex Py_IS_TYPE (C function)
@anchor{c-api/structures c Py_IS_TYPE}@anchor{1ba0}
@deffn {C の関数} int Py_IS_TYPE (PyObject *o, PyTypeObject *type)

Return non-zero if the object `o' type is `type'. Return zero otherwise.
Equivalent to: @code{Py_TYPE(o) == type}.


Added in version 3.9.

@end deffn

@geindex Py_SET_TYPE (C function)
@anchor{c-api/structures c Py_SET_TYPE}@anchor{984}
@deffn {C の関数} void Py_SET_TYPE (PyObject *o, PyTypeObject *type)

Set the type of object `o' to `type', without any checking or reference
counting.

This is a very low-level operation.
Consider instead setting the Python attribute @ref{16c6,,__class__}
using @ref{198e,,PyObject_SetAttrString()} or similar.

Note that assigning an incompatible type can lead to undefined behavior.

If `type' is a @ref{b5e,,heap type}, the caller must create a
new reference to it.
Similarly, if the old type of `o' is a heap type, the caller must release
a reference to that type.


Added in version 3.9.

@end deffn

@geindex Py_SIZE (C function)
@anchor{c-api/structures c Py_SIZE}@anchor{985}
@deffn {C の関数} @ref{c55,,Py_ssize_t} Py_SIZE (PyVarObject *o)

Get the @ref{511c,,ob_size} field of `o'.


バージョン 3.11 で変更: @ref{985,,Py_SIZE()} is changed to an inline static function.
The parameter type is no longer const @ref{46d6,,PyVarObject}*.

@end deffn

@geindex Py_SET_SIZE (C function)
@anchor{c-api/structures c Py_SET_SIZE}@anchor{986}
@deffn {C の関数} void Py_SET_SIZE (PyVarObject *o, Py_ssize_t size)

Set the @ref{511c,,ob_size} field of `o' to `size'.


Added in version 3.9.

@end deffn

@geindex PyObject_HEAD_INIT (C macro)
@anchor{c-api/structures c PyObject_HEAD_INIT}@anchor{55ee}
@deffn {C のマクロ} PyObject_HEAD_INIT (type)

新しい @ref{5df,,PyObject} 型のための初期値に展開するマクロです。このマクロは次のように展開されます。

@example
_PyObject_EXTRA_INIT
1, type,
@end example
@end deffn

@geindex PyVarObject_HEAD_INIT (C macro)
@anchor{c-api/structures c PyVarObject_HEAD_INIT}@anchor{55ef}
@deffn {C のマクロ} PyVarObject_HEAD_INIT (type, size)

This is a macro which expands to initialization values for a new
@ref{46d6,,PyVarObject} type, including the @ref{511c,,ob_size} field.
This macro expands to:

@example
_PyObject_EXTRA_INIT
1, type, size,
@end example
@end deffn

@node Implementing functions and methods,Accessing attributes of extension types,Base object types and macros,共通のオブジェクト構造体 common object structure
@anchor{c-api/structures implementing-functions-and-methods}@anchor{55f0}
@subsubsection Implementing functions and methods


@geindex PyCFunction (C type)
@anchor{c-api/structures c PyCFunction}@anchor{1691}
@deffn {C のデータ型} type PyCFunction
` 次に属します: @ref{775,,Stable ABI}.'
Type of the functions used to implement most Python callables in C.
Functions of this type take two @ref{5df,,PyObject}* parameters and return
one such value.  If the return value is @code{NULL}, an exception shall have
been set.  If not @code{NULL}, the return value is interpreted as the return
value of the function as exposed in Python.  The function must return a new
reference.

関数のシグネチャは次のとおりです

@example
PyObject *PyCFunction(PyObject *self,
                      PyObject *args);
@end example
@end deffn

@geindex PyCFunctionWithKeywords (C type)
@anchor{c-api/structures c PyCFunctionWithKeywords}@anchor{4f8b}
@deffn {C のデータ型} type PyCFunctionWithKeywords
` 次に属します: @ref{775,,Stable ABI}.'
Type of the functions used to implement Python callables in C
with signature @ref{55f1,,METH_VARARGS | METH_KEYWORDS}.
The function signature is:

@example
PyObject *PyCFunctionWithKeywords(PyObject *self,
                                  PyObject *args,
                                  PyObject *kwargs);
@end example
@end deffn

@geindex PyCFunctionFast (C type)
@anchor{c-api/structures c PyCFunctionFast}@anchor{4f89}
@deffn {C のデータ型} type PyCFunctionFast
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Type of the functions used to implement Python callables in C
with signature @ref{199e,,METH_FASTCALL}.
The function signature is:

@example
PyObject *PyCFunctionFast(PyObject *self,
                          PyObject *const *args,
                          Py_ssize_t nargs);
@end example
@end deffn

@geindex PyCFunctionFastWithKeywords (C type)
@anchor{c-api/structures c PyCFunctionFastWithKeywords}@anchor{4f8a}
@deffn {C のデータ型} type PyCFunctionFastWithKeywords
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.13 より).'
Type of the functions used to implement Python callables in C
with signature @ref{55f2,,METH_FASTCALL | METH_KEYWORDS}.
The function signature is:

@example
PyObject *PyCFunctionFastWithKeywords(PyObject *self,
                                      PyObject *const *args,
                                      Py_ssize_t nargs,
                                      PyObject *kwnames);
@end example
@end deffn

@geindex PyCMethod (C type)
@anchor{c-api/structures c PyCMethod}@anchor{968}
@deffn {C のデータ型} type PyCMethod

Type of the functions used to implement Python callables in C
with signature @ref{1a09,,METH_METHOD | METH_FASTCALL | METH_KEYWORDS}.
The function signature is:

@example
PyObject *PyCMethod(PyObject *self,
                    PyTypeObject *defining_class,
                    PyObject *const *args,
                    Py_ssize_t nargs,
                    PyObject *kwnames)
@end example


Added in version 3.9.

@end deffn

@geindex PyMethodDef (C type)
@anchor{c-api/structures c PyMethodDef}@anchor{16f0}
@deffn {C のデータ型} type PyMethodDef
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
拡張型のメソッドを記述する際に用いる構造体です。この構造体には 4 つのフィールドがあります:

@geindex PyMethodDef.ml_name (C member)
@anchor{c-api/structures c PyMethodDef ml_name}@anchor{4ee9}
@deffn {C のメンバ変数} const char *ml_name

Name of the method.
@end deffn

@geindex PyMethodDef.ml_meth (C member)
@anchor{c-api/structures c PyMethodDef ml_meth}@anchor{55f3}
@deffn {C のメンバ変数} @ref{1691,,PyCFunction} ml_meth

Pointer to the C implementation.
@end deffn

@geindex PyMethodDef.ml_flags (C member)
@anchor{c-api/structures c PyMethodDef ml_flags}@anchor{55f4}
@deffn {C のメンバ変数} int ml_flags

Flags bits indicating how the call should be constructed.
@end deffn

@geindex PyMethodDef.ml_doc (C member)
@anchor{c-api/structures c PyMethodDef ml_doc}@anchor{55f5}
@deffn {C のメンバ変数} const char *ml_doc

Points to the contents of the docstring.
@end deffn
@end deffn

The @ref{55f3,,ml_meth} is a C function pointer.
The functions may be of different
types, but they always return @ref{5df,,PyObject}*.  If the function is not of
the @ref{1691,,PyCFunction}, the compiler will require a cast in the method table.
Even though @ref{1691,,PyCFunction} defines the first parameter as
@ref{5df,,PyObject}*, it is common that the method implementation uses the
specific C type of the `self' object.

The @ref{55f4,,ml_flags} field is a bitfield which can include
the following flags.
The individual flags indicate either a calling convention or a binding
convention.

There are these calling conventions:

@geindex METH_VARARGS (C macro)
@anchor{c-api/structures c METH_VARARGS}@anchor{1721}
@deffn {C のマクロ} METH_VARARGS
` 次に属します: @ref{775,,Stable ABI}.'
@ref{1691,,PyCFunction} 型のメソッドで典型的に使われる呼び出し規約です。関数は @ref{5df,,PyObject}* 型の引数値を二つ要求します。最初の引数はメソッドの `self' オブジェクトです; モジュール関数の場合、これはモジュールオブジェクトです。第二のパラメタ (よく `args' と呼ばれます) は、全ての引数を表現するタプルオブジェクトです。パラメタは通常、 @ref{3c1,,PyArg_ParseTuple()} や @ref{171f,,PyArg_UnpackTuple()} で処理されます。
@end deffn

@geindex METH_KEYWORDS (C macro)
@anchor{c-api/structures c METH_KEYWORDS}@anchor{4ea2}
@deffn {C のマクロ} METH_KEYWORDS

Can only be used in certain combinations with other flags:
@ref{55f1,,METH_VARARGS | METH_KEYWORDS},
@ref{55f2,,METH_FASTCALL | METH_KEYWORDS} and
@ref{1a09,,METH_METHOD | METH_FASTCALL | METH_KEYWORDS}.
@end deffn
@anchor{c-api/structures meth-varargs-meth-keywords}@anchor{55f1}

@table @asis

@item @ref{1721,,METH_VARARGS} | @ref{4ea2,,METH_KEYWORDS}

Methods with these flags must be of type @ref{4f8b,,PyCFunctionWithKeywords}.
The function expects three parameters: `self', `args', `kwargs' where
`kwargs' is a dictionary of all the keyword arguments or possibly @code{NULL}
if there are no keyword arguments.  The parameters are typically processed
using @ref{624,,PyArg_ParseTupleAndKeywords()}.
@end table

@geindex METH_FASTCALL (C macro)
@anchor{c-api/structures c METH_FASTCALL}@anchor{199e}
@deffn {C のマクロ} METH_FASTCALL
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Fast calling convention supporting only positional arguments.
The methods have the type @ref{4f89,,PyCFunctionFast}.
The first parameter is `self', the second parameter is a C array
of @ref{5df,,PyObject}* values indicating the arguments and the third
parameter is the number of arguments (the length of the array).


Added in version 3.7.



バージョン 3.10 で変更: @code{METH_FASTCALL} is now part of the @ref{4f5d,,stable ABI}.

@end deffn
@anchor{c-api/structures meth-fastcall-meth-keywords}@anchor{55f2}

@table @asis

@item @ref{199e,,METH_FASTCALL} | @ref{4ea2,,METH_KEYWORDS}

Extension of @ref{199e,,METH_FASTCALL} supporting also keyword arguments,
with methods of type @ref{4f8a,,PyCFunctionFastWithKeywords}.
Keyword arguments are passed the same way as in the
@ref{774,,vectorcall protocol}:
there is an additional fourth @ref{5df,,PyObject}* parameter
which is a tuple representing the names of the keyword arguments
(which are guaranteed to be strings)
or possibly @code{NULL} if there are no keywords.  The values of the keyword
arguments are stored in the `args' array, after the positional arguments.


Added in version 3.7.

@end table

@geindex METH_METHOD (C macro)
@anchor{c-api/structures c METH_METHOD}@anchor{b68}
@deffn {C のマクロ} METH_METHOD
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.7 より).'
Can only be used in the combination with other flags:
@ref{1a09,,METH_METHOD | METH_FASTCALL | METH_KEYWORDS}.
@end deffn
@anchor{c-api/structures meth-method-meth-fastcall-meth-keywords}@anchor{1a09}

@table @asis

@item @ref{b68,,METH_METHOD} | @ref{199e,,METH_FASTCALL} | @ref{4ea2,,METH_KEYWORDS}

Extension of @ref{55f2,,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 @code{Py_TYPE(self)}.

The method needs to be of type @ref{968,,PyCMethod}, the same as for
@code{METH_FASTCALL | METH_KEYWORDS} with @code{defining_class} argument added after
@code{self}.


Added in version 3.9.

@end table

@geindex METH_NOARGS (C macro)
@anchor{c-api/structures c METH_NOARGS}@anchor{16ed}
@deffn {C のマクロ} METH_NOARGS
` 次に属します: @ref{775,,Stable ABI}.'
Methods without parameters don't need to check whether arguments are given if
they are listed with the @ref{16ed,,METH_NOARGS} flag.  They need to be of type
@ref{1691,,PyCFunction}.  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 @code{NULL}.

The function must have 2 parameters. Since the second parameter is unused,
@ref{1a8a,,Py_UNUSED} can be used to prevent a compiler warning.
@end deffn

@geindex METH_O (C macro)
@anchor{c-api/structures c METH_O}@anchor{1720}
@deffn {C のマクロ} METH_O
` 次に属します: @ref{775,,Stable ABI}.'
Methods with a single object argument can be listed with the @ref{1720,,METH_O}
flag, instead of invoking @ref{3c1,,PyArg_ParseTuple()} with a @code{"O"} argument.
They have the type @ref{1691,,PyCFunction}, with the `self' parameter, and a
@ref{5df,,PyObject}* parameter representing the single argument.
@end deffn

These two constants are not used to indicate the calling convention but the
binding when used with methods of classes.  These may not be used for functions
defined for modules.  At most one of these flags may be set for any given
method.

@geindex METH_CLASS (C macro)
@anchor{c-api/structures c METH_CLASS}@anchor{16ee}
@deffn {C のマクロ} METH_CLASS
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;クラスメソッド

メソッドの最初の引数には、型のインスタンスではなく型オブジェクトが渡されます。このフラグは組み込み関数 @ref{48e,,classmethod()} を使って生成するのと同じ `クラスメソッド (class method)' を生成するために使われます。
@end deffn

@geindex METH_STATIC (C macro)
@anchor{c-api/structures c METH_STATIC}@anchor{16ef}
@deffn {C のマクロ} METH_STATIC
` 次に属します: @ref{775,,Stable ABI}.'
@geindex 組み込み関数;静的メソッド

メソッドの最初の引数には、型のインスタンスではなく @code{NULL} が渡されます。このフラグは、 @ref{453,,staticmethod()} を使って生成するのと同じ `静的メソッド (static method)' を生成するために使われます。
@end deffn

もう一つの定数は、あるメソッドを同名の別のメソッド定義と置き換えるかどうかを制御します。

@geindex METH_COEXIST (C macro)
@anchor{c-api/structures c METH_COEXIST}@anchor{1690}
@deffn {C のマクロ} METH_COEXIST
` 次に属します: @ref{775,,Stable ABI}.'
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
@ref{15d3,,__contains__()} and preclude the loading of a corresponding
PyCFunction with the same name.  With the flag defined, the PyCFunction
will be loaded in place of the wrapper object and will co-exist with the
slot.  This is helpful because calls to PyCFunctions are optimized more
than wrapper object calls.
@end deffn

@geindex PyCMethod_Type (C var)
@anchor{c-api/structures c PyCMethod_Type}@anchor{55f6}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCMethod_Type

The type object corresponding to Python C method objects. This is
available as @ref{29ea,,types.BuiltinMethodType} in the Python layer.
@end deffn

@geindex PyCMethod_Check (C function)
@anchor{c-api/structures c PyCMethod_Check}@anchor{55f7}
@deffn {C の関数} int PyCMethod_Check (PyObject *op)

Return true if `op' is an instance of the @ref{55f6,,PyCMethod_Type} type
or a subtype of it. This function always succeeds.
@end deffn

@geindex PyCMethod_CheckExact (C function)
@anchor{c-api/structures c PyCMethod_CheckExact}@anchor{55f8}
@deffn {C の関数} int PyCMethod_CheckExact (PyObject *op)

This is the same as @ref{55f7,,PyCMethod_Check()}, but does not account for
subtypes.
@end deffn

@geindex PyCMethod_New (C function)
@anchor{c-api/structures c PyCMethod_New}@anchor{1cab}
@deffn {C の関数} @ref{5df,,PyObject} *PyCMethod_New (PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
Turn `ml' into a Python @ref{2d7b,,callable} object.
The caller must ensure that `ml' outlives the @ref{2d7b,,callable}.
Typically, `ml' is defined as a static variable.

The `self' parameter will be passed as the `self' argument
to the C function in @code{ml->ml_meth} when invoked.
`self' can be @code{NULL}.

The @ref{2d7b,,callable} object's @code{__module__} attribute
can be set from the given `module' argument.
`module' should be a Python string,
which will be used as name of the module the function is defined in.
If unavailable, it can be set to @ref{885,,None} or @code{NULL}.


@subsubheading 参考


@ref{234a,,function.__module__}


The `cls' parameter will be passed as the `defining_class'
argument to the C function.
Must be set if @ref{b68,,METH_METHOD} is set on @code{ml->ml_flags}.


Added in version 3.9.

@end deffn

@geindex PyCFunction_Type (C var)
@anchor{c-api/structures c PyCFunction_Type}@anchor{4f8f}
@deffn {C 変数} @ref{c9c,,PyTypeObject} PyCFunction_Type
` 次に属します: @ref{775,,Stable ABI}.'
The type object corresponding to Python C function objects. This is
available as @ref{29e9,,types.BuiltinFunctionType} in the Python layer.
@end deffn

@geindex PyCFunction_Check (C function)
@anchor{c-api/structures c PyCFunction_Check}@anchor{55f9}
@deffn {C の関数} int PyCFunction_Check (PyObject *op)

Return true if `op' is an instance of the @ref{4f8f,,PyCFunction_Type} type
or a subtype of it. This function always succeeds.
@end deffn

@geindex PyCFunction_CheckExact (C function)
@anchor{c-api/structures c PyCFunction_CheckExact}@anchor{55fa}
@deffn {C の関数} int PyCFunction_CheckExact (PyObject *op)

This is the same as @ref{55f9,,PyCFunction_Check()}, but does not account for
subtypes.
@end deffn

@geindex PyCFunction_NewEx (C function)
@anchor{c-api/structures c PyCFunction_NewEx}@anchor{1d76}
@deffn {C の関数} @ref{5df,,PyObject} *PyCFunction_NewEx (PyMethodDef *ml, PyObject *self, PyObject *module)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI}.'
Equivalent to @code{PyCMethod_New(ml, self, module, NULL)}.
@end deffn

@geindex PyCFunction_New (C function)
@anchor{c-api/structures c PyCFunction_New}@anchor{1cb1}
@deffn {C の関数} @ref{5df,,PyObject} *PyCFunction_New (PyMethodDef *ml, PyObject *self)
`戻り値: 新しい参照。'` 次に属します: @ref{775,,Stable ABI} (バージョン 3.4 より).'
Equivalent to @code{PyCMethod_New(ml, self, NULL, NULL)}.
@end deffn

@geindex PyCFunction_GetFlags (C function)
@anchor{c-api/structures c PyCFunction_GetFlags}@anchor{4f8c}
@deffn {C の関数} int PyCFunction_GetFlags (PyObject *func)
` 次に属します: @ref{775,,Stable ABI}.'
Get the function's flags on `func' as they were passed to
@ref{55f4,,ml_flags}.

If `func' is not a C function object, this fails with an exception.
`func' must not be @code{NULL}.

This function returns the function's flags on success, and @code{-1} with an
exception set on failure.
@end deffn

@geindex PyCFunction_GET_FLAGS (C function)
@anchor{c-api/structures c PyCFunction_GET_FLAGS}@anchor{55fb}
@deffn {C の関数} int PyCFunction_GET_FLAGS (PyObject *func)

This is the same as @ref{4f8c,,PyCFunction_GetFlags()}, but without error
or type checking.
@end deffn

@geindex PyCFunction_GetFunction (C function)
@anchor{c-api/structures c PyCFunction_GetFunction}@anchor{4f8d}
@deffn {C の関数} @ref{1691,,PyCFunction} PyCFunction_GetFunction (PyObject *func)
` 次に属します: @ref{775,,Stable ABI}.'
Get the function pointer on `func' as it was passed to
@ref{55f3,,ml_meth}.

If `func' is not a C function object, this fails with an exception.
`func' must not be @code{NULL}.

This function returns the function pointer on success, and @code{NULL} with an
exception set on failure.
@end deffn

@geindex PyCFunction_GET_FUNCTION (C function)
@anchor{c-api/structures c PyCFunction_GET_FUNCTION}@anchor{55fc}
@deffn {C の関数} int PyCFunction_GET_FUNCTION (PyObject *func)

This is the same as @ref{4f8d,,PyCFunction_GetFunction()}, but without error
or type checking.
@end deffn

@geindex PyCFunction_GetSelf (C function)
@anchor{c-api/structures c PyCFunction_GetSelf}@anchor{4f8e}
@deffn {C の関数} @ref{5df,,PyObject} *PyCFunction_GetSelf (PyObject *func)
` 次に属します: @ref{775,,Stable ABI}.'
Get the "self" object on `func'. This is the object that would be passed
to the first argument of a @ref{1691,,PyCFunction}. For C function objects
created through a @ref{16f0,,PyMethodDef} on a @ref{b74,,PyModuleDef}, this
is the resulting module object.

If `func' is not a C function object, this fails with an exception.
`func' must not be @code{NULL}.

This function returns a @ref{3d7,,borrowed reference} to the "self" object
on success, and @code{NULL} with an exception set on failure.
@end deffn

@geindex PyCFunction_GET_SELF (C function)
@anchor{c-api/structures c PyCFunction_GET_SELF}@anchor{55fd}
@deffn {C の関数} @ref{5df,,PyObject} *PyCFunction_GET_SELF (PyObject *func)

This is the same as @ref{4f8e,,PyCFunction_GetSelf()}, but without error or
type checking.
@end deffn

@node Accessing attributes of extension types,,Implementing functions and methods,共通のオブジェクト構造体 common object structure
@anchor{c-api/structures accessing-attributes-of-extension-types}@anchor{55fe}
@subsubsection Accessing attributes of extension types


@geindex PyMemberDef (C type)
@anchor{c-api/structures c PyMemberDef}@anchor{771}
@deffn {C のデータ型} type PyMemberDef
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
Structure which describes an attribute of a type which corresponds to a C
struct member.
When defining a class, put a NULL-terminated array of these
structures in the @ref{4ed2,,tp_members} slot.

Its fields are, in order:

@geindex PyMemberDef.name (C member)
@anchor{c-api/structures c PyMemberDef name}@anchor{55ff}
@deffn {C のメンバ変数} const char *name

Name of the member.
A NULL value marks the end of a @code{PyMemberDef[]} array.

The string should be static, no copy is made of it.
@end deffn

@geindex PyMemberDef.type (C member)
@anchor{c-api/structures c PyMemberDef type}@anchor{4eea}
@deffn {C のメンバ変数} int type

The type of the member in the C struct.
See @ref{19f0,,Member types} for the possible values.
@end deffn

@geindex PyMemberDef.offset (C member)
@anchor{c-api/structures c PyMemberDef offset}@anchor{5600}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} offset

The offset in bytes that the member is located on the type’s object struct.
@end deffn

@geindex PyMemberDef.flags (C member)
@anchor{c-api/structures c PyMemberDef flags}@anchor{4eeb}
@deffn {C のメンバ変数} int flags

Zero or more of the @ref{5601,,Member flags}, combined using bitwise OR.
@end deffn

@geindex PyMemberDef.doc (C member)
@anchor{c-api/structures c PyMemberDef doc}@anchor{5602}
@deffn {C のメンバ変数} const char *doc

The docstring, or NULL.
The string should be static, no copy is made of it.
Typically, it is defined using @ref{1b96,,PyDoc_STR}.
@end deffn

By default (when @ref{4eeb,,flags} is @code{0}), members allow
both read and write access.
Use the @ref{7ae,,Py_READONLY} flag for read-only access.
Certain types, like @ref{5142,,Py_T_STRING}, imply @ref{7ae,,Py_READONLY}.
Only @ref{7b1,,Py_T_OBJECT_EX} (and legacy @ref{7b0,,T_OBJECT}) members can
be deleted.
@anchor{c-api/structures pymemberdef-offsets}@anchor{52ed}
For heap-allocated types (created using @ref{79d,,PyType_FromSpec()} or similar),
@code{PyMemberDef} may contain a definition for the special member
@code{"__vectorcalloffset__"}, corresponding to
@ref{5296,,tp_vectorcall_offset} in type objects.
This member must be defined with @code{Py_T_PYSSIZET}, and either
@code{Py_READONLY} or @code{Py_READONLY | Py_RELATIVE_OFFSET}. For example:

@example
static PyMemberDef spam_type_members[] = @{
    @{"__vectorcalloffset__", Py_T_PYSSIZET,
     offsetof(Spam_object, vectorcall), Py_READONLY@},
    @{NULL@}  /* Sentinel */
@};
@end example

(You may need to @code{#include <stddef.h>} for @code{offsetof()}.)

The legacy offsets @ref{52ec,,tp_dictoffset} and
@ref{b7f,,tp_weaklistoffset} can be defined similarly using
@code{"__dictoffset__"} and @code{"__weaklistoffset__"} members, but extensions
are strongly encouraged to use @ref{60f,,Py_TPFLAGS_MANAGED_DICT} and
@ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF} instead.


バージョン 3.12 で変更: @code{PyMemberDef} is always available.
Previously, it required including @code{"structmember.h"}.



バージョン 3.14 で変更: @ref{770,,Py_RELATIVE_OFFSET} is now allowed for
@code{"__vectorcalloffset__"}, @code{"__dictoffset__"} and
@code{"__weaklistoffset__"}.

@end deffn

@geindex PyMember_GetOne (C function)
@anchor{c-api/structures c PyMember_GetOne}@anchor{7aa}
@deffn {C の関数} @ref{5df,,PyObject} *PyMember_GetOne (const char *obj_addr, struct PyMemberDef *m)
` 次に属します: @ref{775,,Stable ABI}.'
Get an attribute belonging to the object at address `obj_addr'.  The
attribute is described by @code{PyMemberDef} `m'.  Returns @code{NULL}
on error.


バージョン 3.12 で変更: @code{PyMember_GetOne} is always available.
Previously, it required including @code{"structmember.h"}.

@end deffn

@geindex PyMember_SetOne (C function)
@anchor{c-api/structures c PyMember_SetOne}@anchor{7ab}
@deffn {C の関数} int PyMember_SetOne (char *obj_addr, struct PyMemberDef *m, PyObject *o)
` 次に属します: @ref{775,,Stable ABI}.'
Set an attribute belonging to the object at address `obj_addr' to object `o'.
The attribute to set is described by @code{PyMemberDef} `m'.  Returns @code{0}
if successful and a negative value on failure.


バージョン 3.12 で変更: @code{PyMember_SetOne} is always available.
Previously, it required including @code{"structmember.h"}.

@end deffn

@menu
* Member flags:: 
* Member types:: 
* Defining Getters and Setters:: 

@end menu

@node Member flags,Member types,,Accessing attributes of extension types
@anchor{c-api/structures member-flags}@anchor{5603}@anchor{c-api/structures pymemberdef-flags}@anchor{5601}
@subsubsection Member flags


The following flags can be used with @ref{4eeb,,PyMemberDef.flags}:

@geindex Py_READONLY (C macro)
@anchor{c-api/structures c Py_READONLY}@anchor{7ae}
@deffn {C のマクロ} Py_READONLY
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Not writable.
@end deffn

@geindex Py_AUDIT_READ (C macro)
@anchor{c-api/structures c Py_AUDIT_READ}@anchor{7af}
@deffn {C のマクロ} Py_AUDIT_READ
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Emit an @code{object.__getattr__} @ref{1c13,,audit event}
before reading.
@end deffn

@geindex Py_RELATIVE_OFFSET (C macro)
@anchor{c-api/structures c Py_RELATIVE_OFFSET}@anchor{770}
@deffn {C のマクロ} Py_RELATIVE_OFFSET
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Indicates that the @ref{5600,,offset} of this @code{PyMemberDef}
entry indicates an offset from the subclass-specific data, rather than
from @code{PyObject}.

Can only be used as part of the @ref{5195,,Py_tp_members}
@ref{50dc,,slot} when creating a class using negative
@ref{76a,,basicsize}.
It is mandatory in that case.
When setting @ref{4ed2,,tp_members} from the slot during
class creation, Python clears the flag and sets
@ref{5600,,PyMemberDef.offset} to the offset from the @code{PyObject} struct.
@end deffn

@geindex READ_RESTRICTED (C macro)
@geindex WRITE_RESTRICTED (C macro)
@geindex RESTRICTED (C macro)


バージョン 3.10 で変更: The @code{RESTRICTED}, @code{READ_RESTRICTED} and
@code{WRITE_RESTRICTED} macros available with
@code{#include "structmember.h"} are deprecated.
@code{READ_RESTRICTED} and @code{RESTRICTED} are equivalent to
@ref{7af,,Py_AUDIT_READ}; @code{WRITE_RESTRICTED} does nothing.


@geindex READONLY (C macro)


バージョン 3.12 で変更: The @code{READONLY} macro was renamed to @ref{7ae,,Py_READONLY}.
The @code{PY_AUDIT_READ} macro was renamed with the @code{Py_} prefix.
The new names are now always available.
Previously, these required @code{#include "structmember.h"}.
The header is still available and it provides the old names.


@node Member types,Defining Getters and Setters,Member flags,Accessing attributes of extension types
@anchor{c-api/structures member-types}@anchor{5604}@anchor{c-api/structures pymemberdef-types}@anchor{19f0}
@subsubsection Member types


@ref{4eea,,PyMemberDef.type} can be one of the following macros corresponding
to various C types.
When the member is accessed in Python, it will be converted to the
equivalent Python type.
When it is set from Python, it will be converted back to the C type.
If that is not possible, an exception such as @ref{198,,TypeError} or
@ref{2ec,,ValueError} is raised.

Unless marked (D), attributes defined this way cannot be deleted
using e.g. @ref{1b1f,,del} or @ref{25b7,,delattr()}.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

マクロ名

@tab

C の型

@tab

Python の型

@item

@geindex Py_T_BYTE (C macro)
@anchor{c-api/structures c Py_T_BYTE}@anchor{513b}
@deffn {C のマクロ} Py_T_BYTE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

char

@tab

@ref{19b,,int}

@item

@geindex Py_T_SHORT (C macro)
@anchor{c-api/structures c Py_T_SHORT}@anchor{5141}
@deffn {C のマクロ} Py_T_SHORT
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

short

@tab

@ref{19b,,int}

@item

@geindex Py_T_INT (C macro)
@anchor{c-api/structures c Py_T_INT}@anchor{7ac}
@deffn {C のマクロ} Py_T_INT
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

int

@tab

@ref{19b,,int}

@item

@geindex Py_T_LONG (C macro)
@anchor{c-api/structures c Py_T_LONG}@anchor{513e}
@deffn {C のマクロ} Py_T_LONG
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

long

@tab

@ref{19b,,int}

@item

@geindex Py_T_LONGLONG (C macro)
@anchor{c-api/structures c Py_T_LONGLONG}@anchor{513f}
@deffn {C のマクロ} Py_T_LONGLONG
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

long long

@tab

@ref{19b,,int}

@item

@geindex Py_T_UBYTE (C macro)
@anchor{c-api/structures c Py_T_UBYTE}@anchor{5144}
@deffn {C のマクロ} Py_T_UBYTE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

unsigned char

@tab

@ref{19b,,int}

@item

@geindex Py_T_UINT (C macro)
@anchor{c-api/structures c Py_T_UINT}@anchor{5145}
@deffn {C のマクロ} Py_T_UINT
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

unsigned int

@tab

@ref{19b,,int}

@item

@geindex Py_T_USHORT (C macro)
@anchor{c-api/structures c Py_T_USHORT}@anchor{5148}
@deffn {C のマクロ} Py_T_USHORT
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

unsigned short

@tab

@ref{19b,,int}

@item

@geindex Py_T_ULONG (C macro)
@anchor{c-api/structures c Py_T_ULONG}@anchor{5146}
@deffn {C のマクロ} Py_T_ULONG
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

unsigned long

@tab

@ref{19b,,int}

@item

@geindex Py_T_ULONGLONG (C macro)
@anchor{c-api/structures c Py_T_ULONGLONG}@anchor{5147}
@deffn {C のマクロ} Py_T_ULONGLONG
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

unsigned long long

@tab

@ref{19b,,int}

@item

@geindex Py_T_PYSSIZET (C macro)
@anchor{c-api/structures c Py_T_PYSSIZET}@anchor{5140}
@deffn {C のマクロ} Py_T_PYSSIZET
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

@ref{c55,,Py_ssize_t}

@tab

@ref{19b,,int}

@item

@geindex Py_T_FLOAT (C macro)
@anchor{c-api/structures c Py_T_FLOAT}@anchor{513d}
@deffn {C のマクロ} Py_T_FLOAT
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

float

@tab

@ref{196,,float}

@item

@geindex Py_T_DOUBLE (C macro)
@anchor{c-api/structures c Py_T_DOUBLE}@anchor{7ad}
@deffn {C のマクロ} Py_T_DOUBLE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

double

@tab

@ref{196,,float}

@item

@geindex Py_T_BOOL (C macro)
@anchor{c-api/structures c Py_T_BOOL}@anchor{513a}
@deffn {C のマクロ} Py_T_BOOL
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

char
(written as 0 or 1)

@tab

@ref{3c3,,bool}

@item

@geindex Py_T_STRING (C macro)
@anchor{c-api/structures c Py_T_STRING}@anchor{5142}
@deffn {C のマクロ} Py_T_STRING
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

const char* (*)

@tab

@ref{169,,str} (RO)

@item

@geindex Py_T_STRING_INPLACE (C macro)
@anchor{c-api/structures c Py_T_STRING_INPLACE}@anchor{5143}
@deffn {C のマクロ} Py_T_STRING_INPLACE
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

const char[] (*)

@tab

@ref{169,,str} (RO)

@item

@geindex Py_T_CHAR (C macro)
@anchor{c-api/structures c Py_T_CHAR}@anchor{513c}
@deffn {C のマクロ} Py_T_CHAR
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

char (0-127)

@tab

@ref{169,,str} (**)

@item

@geindex Py_T_OBJECT_EX (C macro)
@anchor{c-api/structures c Py_T_OBJECT_EX}@anchor{7b1}
@deffn {C のマクロ} Py_T_OBJECT_EX
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@tab

@ref{5df,,PyObject}*

@tab

@ref{c7e,,object} (D)

@end multitable


@quotation

(*): Zero-terminated, UTF8-encoded C string.
With @code{Py_T_STRING} the C representation is a pointer;
with @code{Py_T_STRING_INPLACE} the string is stored directly
in the structure.

(**): String of length 1. Only ASCII is accepted.

(RO): Implies @ref{7ae,,Py_READONLY}.

(D): Can be deleted, in which case the pointer is set to @code{NULL}.
Reading a @code{NULL} pointer raises @ref{5f0,,AttributeError}.
@end quotation

@geindex T_BYTE (C macro)
@geindex T_SHORT (C macro)
@geindex T_INT (C macro)
@geindex T_LONG (C macro)
@geindex T_LONGLONG (C macro)
@geindex T_UBYTE (C macro)
@geindex T_USHORT (C macro)
@geindex T_UINT (C macro)
@geindex T_ULONG (C macro)
@geindex T_ULONGULONG (C macro)
@geindex T_PYSSIZET (C macro)
@geindex T_FLOAT (C macro)
@geindex T_DOUBLE (C macro)
@geindex T_BOOL (C macro)
@geindex T_CHAR (C macro)
@geindex T_STRING (C macro)
@geindex T_STRING_INPLACE (C macro)
@geindex T_OBJECT_EX (C macro)
@geindex structmember.h


Added in version 3.12: In previous versions, the macros were only available with
@code{#include "structmember.h"} and were named without the @code{Py_} prefix
(e.g. as @code{T_INT}).
The header is still available and contains the old names, along with
the following deprecated types:

@geindex T_OBJECT (C macro)
@anchor{c-api/structures c T_OBJECT}@anchor{7b0}
@deffn {C のマクロ} T_OBJECT

Like @code{Py_T_OBJECT_EX}, but @code{NULL} is converted to @code{None}.
This results in surprising behavior in Python: deleting the attribute
effectively sets it to @code{None}.
@end deffn

@geindex T_NONE (C macro)
@anchor{c-api/structures c T_NONE}@anchor{7b2}
@deffn {C のマクロ} T_NONE

Always @code{None}. Must be used with @ref{7ae,,Py_READONLY}.
@end deffn


@node Defining Getters and Setters,,Member types,Accessing attributes of extension types
@anchor{c-api/structures defining-getters-and-setters}@anchor{5605}
@subsubsection Defining Getters and Setters


@geindex PyGetSetDef (C type)
@anchor{c-api/structures c PyGetSetDef}@anchor{db2}
@deffn {C のデータ型} type PyGetSetDef
` 次に属します: @ref{775,,Stable ABI} (すべてのメンバーを含む).'
型のプロパティのようなアクセスを定義するための構造体です。 @ref{4ed7,,PyTypeObject.tp_getset} スロットの説明も参照してください。

@geindex PyGetSetDef.name (C member)
@anchor{c-api/structures c PyGetSetDef name}@anchor{5606}
@deffn {C のメンバ変数} const char *name

属性名
@end deffn

@geindex PyGetSetDef.get (C member)
@anchor{c-api/structures c PyGetSetDef get}@anchor{5607}
@deffn {C のメンバ変数} @ref{51a8,,getter} get

C function to get the attribute.
@end deffn

@geindex PyGetSetDef.set (C member)
@anchor{c-api/structures c PyGetSetDef set}@anchor{5608}
@deffn {C のメンバ変数} @ref{51b6,,setter} set

Optional C function to set or delete the attribute.
If @code{NULL}, the attribute is read-only.
@end deffn

@geindex PyGetSetDef.doc (C member)
@anchor{c-api/structures c PyGetSetDef doc}@anchor{5609}
@deffn {C のメンバ変数} const char *doc

任意のドキュメンテーション文字列
@end deffn

@geindex PyGetSetDef.closure (C member)
@anchor{c-api/structures c PyGetSetDef closure}@anchor{560a}
@deffn {C のメンバ変数} void *closure

Optional user data pointer, providing additional data for getter and setter.
@end deffn
@end deffn

@geindex getter (C type)
@anchor{c-api/structures c getter}@anchor{51a8}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*getter)(@ref{5df,,PyObject}*, void*)
` 次に属します: @ref{775,,Stable ABI}.'
The @code{get} function takes one @ref{5df,,PyObject}* parameter (the
instance) and a user data pointer (the associated @code{closure}):

成功または失敗時に @code{NULL} と例外の集合にされたときは新しい参照を返します。
@end deffn

@geindex setter (C type)
@anchor{c-api/structures c setter}@anchor{51b6}
@deffn {C のデータ型} typedef int (*setter)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, void*)
` 次に属します: @ref{775,,Stable ABI}.'
@code{set} functions take two @ref{5df,,PyObject}* parameters (the instance and
the value to be set) and a user data pointer (the associated @code{closure}):

属性を削除する場合は、2 番目のパラメータに @code{NULL} を指定します。成功した場合は @code{0} を、失敗した場合は @code{-1} を例外として返します。
@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Type Object Structures,循環参照ガベージコレクションをサポートする,共通のオブジェクト構造体 common object structure,オブジェクト実装サポート object implementation support
@anchor{c-api/typeobj doc}@anchor{560b}@anchor{c-api/typeobj translation-repo}@anchor{560c}@anchor{c-api/typeobj type-object-structures}@anchor{560d}@anchor{c-api/typeobj type-structs}@anchor{b84}
@subsection Type Object Structures


新スタイルの型を定義する構造体: @ref{c9c,,PyTypeObject} 構造体は、おそらく Python オブジェクトシステムの中で最も重要な構造体の1つでしょう。型オブジェクトは @code{PyObject_*} 系や @code{PyType_*} 系の関数で扱えますが、ほとんどの Python アプリケーションにとって、さして面白みのある機能を提供しません。型オブジェクトはオブジェクトがどのように振舞うかを決める基盤ですから、インタプリタ自体や新たな型を定義する拡張モジュールでは非常に重要な存在です。

型オブジェクトは標準の型 (standard type) に比べるとかなり大きな構造体です。各型オブジェクトは多くの値を保持しており、そのほとんどは C 関数へのポインタで、それぞれの関数はその型の機能の小さい部分を実装しています。この節では、型オブジェクトの各フィールドについて詳細を説明します。各フィールドは、構造体内で出現する順番に説明されています。

以下のクイックリファレンスに加えて、 @ref{560e,,使用例} 節では @ref{c9c,,PyTypeObject} の意味と使い方を一目で理解できる例を載せています。

@menu
* クイックリファレンス:: 
* PyTypeObject 定義:: 
* PyObject スロット:: 
* PyVarObject スロット:: 
* PyTypeObject スロット:: 
* Static Types:: 
* Heap Types:: 
* 数値オブジェクト構造体:: 
* マップオブジェクト構造体:: 
* シーケンスオブジェクト構造体:: 
* バッファオブジェクト構造体 (buffer object structure): バッファオブジェクト構造体 buffer object structure. 
* async オブジェクト構造体:: 
* Slot Type typedefs:: 
* 使用例: 使用例<57>. 

@end menu

@node クイックリファレンス,PyTypeObject 定義,,Type Object Structures
@anchor{c-api/typeobj quick-reference}@anchor{560f}
@subsubsection クイックリファレンス


@menu
* tp スロット:: 
* sub-slots:: 
* スロットの定義型 (typedef): スロットの定義型 typedef. 

@end menu

@node tp スロット,sub-slots,,クイックリファレンス
@anchor{c-api/typeobj tp-slots}@anchor{5610}@anchor{c-api/typeobj tp-slots-table}@anchor{5611}
@subsubsection tp スロット



@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxx} {xxx} {xxx} {xxx} 
@headitem

PyTypeObject スロット @footnote{
`()': A slot name in parentheses indicates it is (effectively) deprecated.

`<>': Names in angle brackets should be initially set to @code{NULL} and
treated as read-only.

`[]': Names in square brackets are for internal use only.

`<R>' (as a prefix) means the field is required (must be non-@code{NULL}).
}

@tab

@ref{5612,,型}

@tab

特殊メソッド/特殊属性

@tab

Info @footnote{
列:

`"O"':  set on @ref{4f75,,PyBaseObject_Type}

`"T"':  set on @ref{76f,,PyType_Type}

`"D"':  default (if slot is set to @code{NULL})

@example
X - PyType_Ready sets this value if it is NULL
~ - PyType_Ready always sets this value (it should be NULL)
? - PyType_Ready may set this value depending on other slots

Also see the inheritance column ("I").
@end example

`"I"':  inheritance

@example
X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value
% - the slots of the sub-struct are inherited individually
G - inherited, but only in combination with other slots; see the slot's description
? - it's complicated; see the slot's description
@end example

Note that some slots are effectively inherited through the normal
attribute lookup chain.
}

@tab

@tab

@tab

@item

O

@tab

T

@tab

D

@tab

I

@item

<R> @ref{1cb0,,tp_name}

@tab

const char *

@tab

__name__

@tab

X

@tab

X

@tab

@tab

@item

@ref{b7e,,tp_basicsize}

@tab

@ref{c55,,Py_ssize_t}

@tab

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{23bb,,tp_itemsize}

@tab

@ref{c55,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

X

@item

@ref{4ebc,,tp_dealloc}

@tab

@ref{51a3,,destructor}

@tab

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{5296,,tp_vectorcall_offset}

@tab

@ref{c55,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

X

@item

(@ref{4eed,,tp_getattr})

@tab

@ref{51a4,,getattrfunc}

@tab

__getattribute__,
__getattr__

@tab

@tab

@tab

@tab

G

@item

(@ref{4eee,,tp_setattr})

@tab

@ref{51b4,,setattrfunc}

@tab

__setattr__,
__delattr__

@tab

@tab

@tab

@tab

G

@item

@ref{10cf,,tp_as_async}

@tab

@ref{52ea,,PyAsyncMethods} *

@tab

@ref{5613,,sub-slots}

@tab

@tab

@tab

@tab

%

@item

@ref{4ee4,,tp_repr}

@tab

@ref{51b2,,reprfunc}

@tab

__repr__

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{b82,,tp_as_number}

@tab

@ref{1637,,PyNumberMethods} *

@tab

@ref{5613,,sub-slots}

@tab

@tab

@tab

@tab

%

@item

@ref{5614,,tp_as_sequence}

@tab

@ref{4ef4,,PySequenceMethods} *

@tab

@ref{5613,,sub-slots}

@tab

@tab

@tab

@tab

%

@item

@ref{5615,,tp_as_mapping}

@tab

@ref{4ef5,,PyMappingMethods} *

@tab

@ref{5613,,sub-slots}

@tab

@tab

@tab

@tab

%

@item

@ref{4ef6,,tp_hash}

@tab

@ref{51a9,,hashfunc}

@tab

__hash__

@tab

X

@tab

@tab

@tab

G

@item

@ref{77b,,tp_call}

@tab

@ref{51b9,,ternaryfunc}

@tab

__call__

@tab

@tab

X

@tab

@tab

X

@item

@ref{4ee5,,tp_str}

@tab

@ref{51b2,,reprfunc}

@tab

__str__

@tab

X

@tab

@tab

@tab

X

@item

@ref{1a64,,tp_getattro}

@tab

@ref{51a5,,getattrofunc}

@tab

__getattribute__,
__getattr__

@tab

X

@tab

X

@tab

@tab

G

@item

@ref{4ee8,,tp_setattro}

@tab

@ref{51b5,,setattrofunc}

@tab

__setattr__,
__delattr__

@tab

X

@tab

X

@tab

@tab

G

@item

@ref{b80,,tp_as_buffer}

@tab

@ref{52f1,,PyBufferProcs} *

@tab

@ref{5613,,sub-slots}

@tab

@tab

@tab

@tab

%

@item

@ref{1c71,,tp_flags}

@tab

unsigned long

@tab

@tab

X

@tab

X

@tab

@tab

?

@item

@ref{4ecb,,tp_doc}

@tab

const char *

@tab

__doc__

@tab

X

@tab

X

@tab

@tab

@item

@ref{982,,tp_traverse}

@tab

@ref{51ba,,traverseproc}

@tab

@tab

@tab

X

@tab

@tab

G

@item

@ref{4ee2,,tp_clear}

@tab

@ref{51ab,,inquiry}

@tab

@tab

@tab

X

@tab

@tab

G

@item

@ref{4ef0,,tp_richcompare}

@tab

@ref{51b3,,richcmpfunc}

@tab

__lt__,
__le__,
__eq__,
__ne__,
__gt__,
__ge__

@tab

X

@tab

@tab

@tab

G

@item

(@ref{b7f,,tp_weaklistoffset})

@tab

@ref{c55,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

?

@item

@ref{1708,,tp_iter}

@tab

@ref{51a7,,getiterfunc}

@tab

__iter__

@tab

@tab

@tab

@tab

X

@item

@ref{1709,,tp_iternext}

@tab

@ref{51ac,,iternextfunc}

@tab

__next__

@tab

@tab

@tab

@tab

X

@item

@ref{4ed4,,tp_methods}

@tab

@ref{16f0,,PyMethodDef} []

@tab

@tab

X

@tab

X

@tab

@tab

@item

@ref{4ed2,,tp_members}

@tab

@ref{771,,PyMemberDef} []

@tab

@tab

@tab

X

@tab

@tab

@item

@ref{4ed7,,tp_getset}

@tab

@ref{db2,,PyGetSetDef} []

@tab

@tab

X

@tab

X

@tab

@tab

@item

@ref{2375,,tp_base}

@tab

@ref{c9c,,PyTypeObject} *

@tab

__base__

@tab

@tab

@tab

X

@tab

@item

@ref{1a8c,,tp_dict}

@tab

@ref{5df,,PyObject} *

@tab

__dict__

@tab

@tab

@tab

?

@tab

@item

@ref{5616,,tp_descr_get}

@tab

@ref{51a1,,descrgetfunc}

@tab

__get__

@tab

@tab

@tab

@tab

X

@item

@ref{1cb4,,tp_descr_set}

@tab

@ref{51a2,,descrsetfunc}

@tab

__set__,
__delete__

@tab

@tab

@tab

@tab

X

@item

(@ref{52ec,,tp_dictoffset})

@tab

@ref{c55,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

?

@item

@ref{7a1,,tp_init}

@tab

@ref{51aa,,initproc}

@tab

__init__

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{4ed0,,tp_alloc}

@tab

@ref{519f,,allocfunc}

@tab

@tab

X

@tab

@tab

?

@tab

?

@item

@ref{79f,,tp_new}

@tab

@ref{51ae,,newfunc}

@tab

__new__

@tab

X

@tab

X

@tab

?

@tab

?

@item

@ref{4ecf,,tp_free}

@tab

@ref{5449,,freefunc}

@tab

@tab

X

@tab

X

@tab

?

@tab

?

@item

@ref{5617,,tp_is_gc}

@tab

@ref{51ab,,inquiry}

@tab

@tab

@tab

X

@tab

@tab

X

@item

<@ref{5618,,tp_bases}>

@tab

@ref{5df,,PyObject} *

@tab

__bases__

@tab

@tab

@tab

~

@tab

@item

<@ref{52ee,,tp_mro}>

@tab

@ref{5df,,PyObject} *

@tab

__mro__

@tab

@tab

@tab

~

@tab

@item

[@ref{52ef,,tp_cache}]

@tab

@ref{5df,,PyObject} *

@tab

@tab

@tab

@tab

@tab

@item

[@ref{792,,tp_subclasses}]

@tab

void *

@tab

__subclasses__

@tab

@tab

@tab

@tab

@item

[@ref{52f0,,tp_weaklist}]

@tab

@ref{5df,,PyObject} *

@tab

@tab

@tab

@tab

@tab

@item

(@ref{5619,,tp_del})

@tab

@ref{51a3,,destructor}

@tab

@tab

@tab

@tab

@tab

@item

[@ref{561a,,tp_version_tag}]

@tab

unsigned int

@tab

@tab

@tab

@tab

@tab

@item

@ref{c9d,,tp_finalize}

@tab

@ref{51a3,,destructor}

@tab

__del__

@tab

@tab

@tab

@tab

X

@item

@ref{198a,,tp_vectorcall}

@tab

@ref{779,,vectorcallfunc}

@tab

@tab

@tab

@tab

@tab

@item

[@ref{561b,,tp_watched}]

@tab

unsigned char

@tab

@tab

@tab

@tab

@tab

@end multitable


@node sub-slots,スロットの定義型 typedef,tp スロット,クイックリファレンス
@anchor{c-api/typeobj id3}@anchor{561c}@anchor{c-api/typeobj sub-slots}@anchor{5613}
@subsubsection sub-slots



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

Slot

@tab

@ref{5612,,型}

@tab

特殊メソッド

@item

@ref{561d,,am_await}

@tab

@ref{51bb,,unaryfunc}

@tab

__await__

@item

@ref{561e,,am_aiter}

@tab

@ref{51bb,,unaryfunc}

@tab

__aiter__

@item

@ref{561f,,am_anext}

@tab

@ref{51bb,,unaryfunc}

@tab

__anext__

@item

@ref{5620,,am_send}

@tab

@ref{5621,,sendfunc}

@tab

@item

@tab

@tab

@item

@ref{52e2,,nb_add}

@tab

@ref{51a0,,binaryfunc}

@tab

__add__
__radd__

@item

@ref{5622,,nb_inplace_add}

@tab

@ref{51a0,,binaryfunc}

@tab

__iadd__

@item

@ref{5623,,nb_subtract}

@tab

@ref{51a0,,binaryfunc}

@tab

__sub__
__rsub__

@item

@ref{5624,,nb_inplace_subtract}

@tab

@ref{51a0,,binaryfunc}

@tab

__isub__

@item

@ref{5625,,nb_multiply}

@tab

@ref{51a0,,binaryfunc}

@tab

__mul__
__rmul__

@item

@ref{5626,,nb_inplace_multiply}

@tab

@ref{51a0,,binaryfunc}

@tab

__imul__

@item

@ref{5627,,nb_remainder}

@tab

@ref{51a0,,binaryfunc}

@tab

__mod__
__rmod__

@item

@ref{5628,,nb_inplace_remainder}

@tab

@ref{51a0,,binaryfunc}

@tab

__imod__

@item

@ref{5629,,nb_divmod}

@tab

@ref{51a0,,binaryfunc}

@tab

__divmod__
__rdivmod__

@item

@ref{562a,,nb_power}

@tab

@ref{51b9,,ternaryfunc}

@tab

__pow__
__rpow__

@item

@ref{562b,,nb_inplace_power}

@tab

@ref{51b9,,ternaryfunc}

@tab

__ipow__

@item

@ref{562c,,nb_negative}

@tab

@ref{51bb,,unaryfunc}

@tab

__neg__

@item

@ref{562d,,nb_positive}

@tab

@ref{51bb,,unaryfunc}

@tab

__pos__

@item

@ref{562e,,nb_absolute}

@tab

@ref{51bb,,unaryfunc}

@tab

__abs__

@item

@ref{562f,,nb_bool}

@tab

@ref{51ab,,inquiry}

@tab

__bool__

@item

@ref{5630,,nb_invert}

@tab

@ref{51bb,,unaryfunc}

@tab

__invert__

@item

@ref{5631,,nb_lshift}

@tab

@ref{51a0,,binaryfunc}

@tab

__lshift__
__rlshift__

@item

@ref{5632,,nb_inplace_lshift}

@tab

@ref{51a0,,binaryfunc}

@tab

__ilshift__

@item

@ref{5633,,nb_rshift}

@tab

@ref{51a0,,binaryfunc}

@tab

__rshift__
__rrshift__

@item

@ref{5634,,nb_inplace_rshift}

@tab

@ref{51a0,,binaryfunc}

@tab

__irshift__

@item

@ref{5635,,nb_and}

@tab

@ref{51a0,,binaryfunc}

@tab

__and__
__rand__

@item

@ref{5636,,nb_inplace_and}

@tab

@ref{51a0,,binaryfunc}

@tab

__iand__

@item

@ref{5637,,nb_xor}

@tab

@ref{51a0,,binaryfunc}

@tab

__xor__
__rxor__

@item

@ref{5638,,nb_inplace_xor}

@tab

@ref{51a0,,binaryfunc}

@tab

__ixor__

@item

@ref{5639,,nb_or}

@tab

@ref{51a0,,binaryfunc}

@tab

__or__
__ror__

@item

@ref{563a,,nb_inplace_or}

@tab

@ref{51a0,,binaryfunc}

@tab

__ior__

@item

@ref{563b,,nb_int}

@tab

@ref{51bb,,unaryfunc}

@tab

__int__

@item

@ref{563c,,nb_reserved}

@tab

void *

@tab

@item

@ref{563d,,nb_float}

@tab

@ref{51bb,,unaryfunc}

@tab

__float__

@item

@ref{563e,,nb_floor_divide}

@tab

@ref{51a0,,binaryfunc}

@tab

__floordiv__

@item

@ref{563f,,nb_inplace_floor_divide}

@tab

@ref{51a0,,binaryfunc}

@tab

__ifloordiv__

@item

@ref{5640,,nb_true_divide}

@tab

@ref{51a0,,binaryfunc}

@tab

__truediv__

@item

@ref{5641,,nb_inplace_true_divide}

@tab

@ref{51a0,,binaryfunc}

@tab

__itruediv__

@item

@ref{1636,,nb_index}

@tab

@ref{51bb,,unaryfunc}

@tab

__index__

@item

@ref{5642,,nb_matrix_multiply}

@tab

@ref{51a0,,binaryfunc}

@tab

__matmul__
__rmatmul__

@item

@ref{5643,,nb_inplace_matrix_multiply}

@tab

@ref{51a0,,binaryfunc}

@tab

__imatmul__

@item

@tab

@tab

@item

@ref{5644,,mp_length}

@tab

@ref{51ad,,lenfunc}

@tab

__len__

@item

@ref{1cf6,,mp_subscript}

@tab

@ref{51a0,,binaryfunc}

@tab

__getitem__

@item

@ref{5645,,mp_ass_subscript}

@tab

@ref{51af,,objobjargproc}

@tab

__setitem__,
__delitem__

@item

@tab

@tab

@item

@ref{52eb,,sq_length}

@tab

@ref{51ad,,lenfunc}

@tab

__len__

@item

@ref{5646,,sq_concat}

@tab

@ref{51a0,,binaryfunc}

@tab

__add__

@item

@ref{5647,,sq_repeat}

@tab

@ref{51b7,,ssizeargfunc}

@tab

__mul__

@item

@ref{1cf5,,sq_item}

@tab

@ref{51b7,,ssizeargfunc}

@tab

__getitem__

@item

@ref{5648,,sq_ass_item}

@tab

@ref{51b8,,ssizeobjargproc}

@tab

__setitem__
__delitem__

@item

@ref{5649,,sq_contains}

@tab

@ref{51b0,,objobjproc}

@tab

__contains__

@item

@ref{564a,,sq_inplace_concat}

@tab

@ref{51a0,,binaryfunc}

@tab

__iadd__

@item

@ref{564b,,sq_inplace_repeat}

@tab

@ref{51b7,,ssizeargfunc}

@tab

__imul__

@item

@tab

@tab

@item

@ref{966,,bf_getbuffer}

@tab

@ref{51a6,,getbufferproc()}

@tab

__buffer__

@item

@ref{967,,bf_releasebuffer}

@tab

@ref{51b1,,releasebufferproc()}

@tab

__release_buffer__

@end multitable


@node スロットの定義型 typedef,,sub-slots,クイックリファレンス
@anchor{c-api/typeobj slot-typedefs}@anchor{564c}@anchor{c-api/typeobj slot-typedefs-table}@anchor{5612}
@subsubsection スロットの定義型 (typedef)



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

定義型 (typedef)

@tab

引数型

@tab

返り値型

@item

@ref{519f,,allocfunc}

@tab


@display
@ref{c9c,,PyTypeObject} *@w{ }
@ref{c55,,Py_ssize_t}@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51a3,,destructor}

@tab

@ref{5df,,PyObject} *

@tab

void

@item

@ref{5449,,freefunc}

@tab

void *

@tab

void

@item

@ref{51ba,,traverseproc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{51bc,,visitproc}@w{ }
void *@w{ }
@end display



@tab

int

@item

@ref{51ae,,newfunc}

@tab


@display
@ref{c9c,,PyTypeObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51aa,,initproc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

int

@item

@ref{51b2,,reprfunc}

@tab

@ref{5df,,PyObject} *

@tab

@ref{5df,,PyObject} *

@item

@ref{51a4,,getattrfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
const char *@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51b4,,setattrfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
const char *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

int

@item

@ref{51a5,,getattrofunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51b5,,setattrofunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

int

@item

@ref{51a1,,descrgetfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51a2,,descrsetfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

int

@item

@ref{51a9,,hashfunc}

@tab

@ref{5df,,PyObject} *

@tab

Py_hash_t

@item

@ref{51b3,,richcmpfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
int@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51a7,,getiterfunc}

@tab

@ref{5df,,PyObject} *

@tab

@ref{5df,,PyObject} *

@item

@ref{51ac,,iternextfunc}

@tab

@ref{5df,,PyObject} *

@tab

@ref{5df,,PyObject} *

@item

@ref{51ad,,lenfunc}

@tab

@ref{5df,,PyObject} *

@tab

@ref{c55,,Py_ssize_t}

@item

@ref{51a6,,getbufferproc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{95c,,Py_buffer} *@w{ }
int@w{ }
@end display



@tab

int

@item

@ref{51b1,,releasebufferproc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{95c,,Py_buffer} *@w{ }
@end display



@tab

void

@item

@ref{51ab,,inquiry}

@tab

@ref{5df,,PyObject} *

@tab

int

@item

@ref{51bb,,unaryfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51a0,,binaryfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51b9,,ternaryfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51b7,,ssizeargfunc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{c55,,Py_ssize_t}@w{ }
@end display



@tab

@ref{5df,,PyObject} *

@item

@ref{51b8,,ssizeobjargproc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{c55,,Py_ssize_t}@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

int

@item

@ref{51b0,,objobjproc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

int

@item

@ref{51af,,objobjargproc}

@tab


@display
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@ref{5df,,PyObject} *@w{ }
@end display



@tab

int

@end multitable


See @ref{564d,,Slot Type typedefs} below for more detail.

@node PyTypeObject 定義,PyObject スロット,クイックリファレンス,Type Object Structures
@anchor{c-api/typeobj pytypeobject-definition}@anchor{564e}
@subsubsection PyTypeObject 定義


The structure definition for @ref{c9c,,PyTypeObject} can be found in
@code{Include/cpython/object.h}.  For convenience of reference, this repeats the
definition found there:

@c XXX Drop this?

@example
typedef struct _typeobject @{
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    Py_ssize_t tp_vectorcall_offset;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* Assigned meaning in release 2.0 */
    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* Assigned meaning in release 2.1 */
    /* 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 */
    PyMethodDef *tp_methods;
    PyMemberDef *tp_members;
    PyGetSetDef *tp_getset;
    // Strong reference on a heap type, borrowed reference on a static type
    PyTypeObject *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; /* no longer used */
    void *tp_subclasses;  /* for static builtin types this is an index */
    PyObject *tp_weaklist; /* not used for static builtin types */
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6.
     * If zero, the cache is invalid and must be initialized.
     */
    unsigned int tp_version_tag;

    destructor tp_finalize;
    vectorcallfunc tp_vectorcall;

    /* bitset of which type-watchers care about this type */
    unsigned char tp_watched;

    /* Number of tp_version_tag values used.
     * Set to _Py_ATTR_CACHE_UNUSED if the attribute cache is
     * disabled for this type (e.g. due to custom MRO entries).
     * Otherwise, limited to MAX_VERSIONS_PER_CLASS (defined elsewhere).
     */
    uint16_t tp_versions_used;
@} PyTypeObject;
@end example

@node PyObject スロット,PyVarObject スロット,PyTypeObject 定義,Type Object Structures
@anchor{c-api/typeobj pyobject-slots}@anchor{564f}
@subsubsection PyObject スロット


The type object structure extends the @ref{46d6,,PyVarObject} structure. The
@ref{511c,,ob_size} field is used for dynamic types (created by @code{type_new()},
usually called from a class statement). Note that @ref{76f,,PyType_Type} (the
metatype) initializes @ref{23bb,,tp_itemsize}, which means that its instances (i.e.
type objects) `must' have the @ref{511c,,ob_size} field.

@ref{a9f,,PyObject.ob_refcnt}

@quotation

The type object's reference count is initialized to @code{1} by the
@code{PyObject_HEAD_INIT} macro.  Note that for @ref{983,,statically allocated type objects}, the type's instances (objects whose @ref{4ecd,,ob_type}
points back to the type) do `not' count as references.  But for
@ref{b5e,,dynamically allocated type objects}, the instances `do'
count as references.

`継承:'

サブタイプはこのフィールドを継承しません。
@end quotation

@ref{4ecd,,PyObject.ob_type}

@quotation

型自体の型、別の言い方をするとメタタイプです。 @code{PyObject_HEAD_INIT} マクロで初期化され、通常は @code{&PyType_Type} になります。しかし、(少なくとも) Windows で利用できる動的ロード可能な拡張モジュールでは、コンパイラは有効な初期化ではないと文句をつけます。そこで、ならわしとして、 @code{PyObject_HEAD_INIT} には @code{NULL} を渡して初期化しておき、他の操作を行う前にモジュールの初期化関数で明示的にこのフィールドを初期化することになっています。この操作は以下のように行います:

@example
Foo_Type.ob_type = &PyType_Type;
@end example

This should be done before any instances of the type are created.
@ref{980,,PyType_Ready()} checks if @ref{4ecd,,ob_type} is @code{NULL}, and if so,
initializes it to the @ref{4ecd,,ob_type} field of the base class.
@ref{980,,PyType_Ready()} will not change this field if it is non-zero.

`継承:'

サブタイプはこのフィールドを継承します。
@end quotation

@node PyVarObject スロット,PyTypeObject スロット,PyObject スロット,Type Object Structures
@anchor{c-api/typeobj pyvarobject-slots}@anchor{5650}
@subsubsection PyVarObject スロット


@ref{511c,,PyVarObject.ob_size}

@quotation

@ref{983,,静的にメモリ確保されている型オブジェクト} の場合、このフィールドはゼロに初期化されます。@ref{b5e,,動的にメモリ確保されている型オブジェクト} の場合、このフィールドは内部使用される特殊な意味を持ちます。

This field should be accessed using the @ref{985,,Py_SIZE()} macro.

`継承:'

サブタイプはこのフィールドを継承しません。
@end quotation

@node PyTypeObject スロット,Static Types,PyVarObject スロット,Type Object Structures
@anchor{c-api/typeobj pytypeobject-slots}@anchor{5651}
@subsubsection PyTypeObject スロット


Each slot has a section describing inheritance.  If @ref{980,,PyType_Ready()}
may set a value when the field is set to @code{NULL} then there will also be
a "Default" section.  (Note that many fields set on @ref{4f75,,PyBaseObject_Type}
and @ref{76f,,PyType_Type} effectively act as defaults.)

@geindex PyTypeObject.tp_name (C member)
@anchor{c-api/typeobj c PyTypeObject tp_name}@anchor{1cb0}
@deffn {C のメンバ変数} const char *@ref{c9c,,PyTypeObject}.tp_name

Pointer to a NUL-terminated string containing the name of the type. For types
that are accessible as module globals, the string should be the full module
name, followed by a dot, followed by the type name; for built-in types, it
should be just the type name.  If the module is a submodule of a package, the
full package name is part of the full module name.  For example, a type named
@code{T} defined in module @code{M} in subpackage @code{Q} in package @code{P}
should have the @ref{1cb0,,tp_name} initializer @code{"P.Q.M.T"}.

@ref{b5e,,動的にメモリ確保される型オブジェクト} の場合、このフィールドは単に型の名前になり、モジュール名は型の辞書内でキー @code{'__module__'} に対する値として明示的に保存されます。

For @ref{983,,statically allocated type objects},
the `tp_name' field should contain a dot.
Everything before the last dot is made accessible as the @ref{617,,__module__}
attribute, and everything after the last dot is made accessible as the
@ref{16c4,,__name__} attribute.

If no dot is present, the entire @ref{1cb0,,tp_name} field is made accessible as the
@ref{16c4,,__name__} attribute, and the @ref{617,,__module__} attribute is undefined
(unless explicitly set in the dictionary, as explained above).  This means your
type will be impossible to pickle.  Additionally, it will not be listed in
module documentations created with pydoc.

This field must not be @code{NULL}.  It is the only required field
in @ref{c9c,,PyTypeObject()} (other than potentially
@ref{23bb,,tp_itemsize}).

`継承:'

サブタイプはこのフィールドを継承しません。
@end deffn

@geindex PyTypeObject.tp_basicsize (C member)
@geindex PyTypeObject.tp_itemsize (C member)
@anchor{c-api/typeobj c PyTypeObject tp_basicsize}@anchor{b7e}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} @ref{c9c,,PyTypeObject}.tp_basicsize
@anchor{c-api/typeobj c PyTypeObject tp_itemsize}@anchor{23bb}
@deffnx {C のメンバ変数} @ref{c55,,Py_ssize_t} @ref{c9c,,PyTypeObject}.tp_itemsize

これらのフィールドは、型インスタンスのバイトサイズを計算できるようにします。

There are two kinds of types: types with fixed-length instances have a zero
@code{tp_itemsize} field, types with variable-length instances have a non-zero
@code{tp_itemsize} field.  For a type with fixed-length instances, all
instances have the same size, given in @code{tp_basicsize}.
(Exceptions to this rule can be made using
@ref{1aa8,,PyUnstable_Object_GC_NewWithExtraData()}.)

For a type with variable-length instances, the instances must have an
@ref{511c,,ob_size} field, and the instance size is
@code{tp_basicsize} plus N times @code{tp_itemsize},
where N is the "length" of the object.

Functions like @ref{b7d,,PyObject_NewVar()} will take the value of N as an
argument, and store in the instance's @ref{511c,,ob_size} field.
Note that the @ref{511c,,ob_size} field may later be used for
other purposes. For example, @ref{19b,,int} instances use the bits of
@ref{511c,,ob_size} in an implementation-defined
way; the underlying storage and its size should be accessed using
@ref{3a8,,PyLong_Export()}.

@cartouche
@quotation 注釈 
The @ref{511c,,ob_size} field should be accessed using
the @ref{985,,Py_SIZE()} and @ref{986,,Py_SET_SIZE()} macros.
@end quotation
@end cartouche

Also, the presence of an @ref{511c,,ob_size} field in the
instance layout doesn't mean that the instance structure is variable-length.
For example, the @ref{24d,,list} type has fixed-length instances, yet those
instances have a @ref{511c,,ob_size} field.
(As with @ref{19b,,int}, avoid reading lists' @code{ob_size} directly.
Call @ref{1633,,PyList_Size()} instead.)

The @code{tp_basicsize} includes size needed for data of the type's
@ref{2375,,tp_base}, plus any extra data needed
by each instance.

The  correct way to set @code{tp_basicsize} is to use the
@code{sizeof} operator on the struct used to declare the instance layout.
This struct must include the struct used to declare the base type.
In other words, @code{tp_basicsize} must be greater than or equal
to the base's @code{tp_basicsize}.

Since every type is a subtype of @ref{c7e,,object}, this struct must
include @ref{5df,,PyObject} or @ref{46d6,,PyVarObject} (depending on
whether @ref{511c,,ob_size} should be included). These are
usually defined by the macro @ref{14f5,,PyObject_HEAD} or
@ref{55ed,,PyObject_VAR_HEAD}, respectively.

The basic size does not include the GC header size, as that header is not
part of @ref{14f5,,PyObject_HEAD}.

For cases where struct used to declare the base type is unknown,
see @ref{76a,,PyType_Spec.basicsize} and @ref{772,,PyType_FromMetaclass()}.

Notes about alignment:


@itemize -

@item 
@code{tp_basicsize} must be a multiple of @code{_Alignof(PyObject)}.
When using @code{sizeof} on a @code{struct} that includes
@ref{14f5,,PyObject_HEAD}, as recommended, the compiler ensures this.
When not using a C @code{struct}, or when using compiler
extensions like @code{__attribute__((packed))}, it is up to you.

@item 
If the variable items require a particular alignment,
@code{tp_basicsize} and @code{tp_itemsize} must each be a
multiple of that alignment.
For example, if a type's variable part stores a @code{double}, it is
your responsibility that both fields are a multiple of
@code{_Alignof(double)}.
@end itemize

`継承:'

These fields are inherited separately by subtypes.
(That is, if the field is set to zero, @ref{980,,PyType_Ready()} will copy
the value from the base type, indicating that the instances do not
need additional storage.)

If the base type has a non-zero @ref{23bb,,tp_itemsize}, it is generally not safe to set
@ref{23bb,,tp_itemsize} to a different non-zero value in a subtype (though this
depends on the implementation of the base type).
@end deffn

@geindex PyTypeObject.tp_dealloc (C member)
@anchor{c-api/typeobj c PyTypeObject tp_dealloc}@anchor{4ebc}
@deffn {C のメンバ変数} @ref{51a3,,destructor} @ref{c9c,,PyTypeObject}.tp_dealloc

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_dealloc} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_dealloc (C macro)
@anchor{c-api/typeobj c Py_tp_dealloc}@anchor{5186}

A pointer to the instance destructor function.  The function signature is:

@example
void tp_dealloc(PyObject *self);
@end example

The destructor function should remove all references which the instance owns
(e.g., call @ref{798,,Py_CLEAR()}), free all memory buffers owned by the
instance, and call the type's @ref{4ecf,,tp_free} function to
free the object itself.

If you may call functions that may set the error indicator, you must use
@ref{429,,PyErr_GetRaisedException()} and @ref{42c,,PyErr_SetRaisedException()}
to ensure you don't clobber a preexisting error indicator (the deallocation
could have occurred while processing a different error):

@example
static void
foo_dealloc(foo_object *self)
@{
    PyObject *et, *ev, *etb;
    PyObject *exc = PyErr_GetRaisedException();
    ...
    PyErr_SetRaisedException(exc);
@}
@end example

The dealloc handler itself must not raise an exception; if it hits an error
case it should call @ref{5f1,,PyErr_FormatUnraisable()} to log (and clear) an
unraisable exception.

No guarantees are made about when an object is destroyed, except:


@itemize *

@item 
Python will destroy an object immediately or some time after the final
reference to the object is deleted, unless its finalizer
(@ref{c9d,,tp_finalize}) subsequently resurrects the
object.

@item 
An object will not be destroyed while it is being automatically finalized
(@ref{c9d,,tp_finalize}) or automatically cleared
(@ref{4ee2,,tp_clear}).
@end itemize

CPython currently destroys an object immediately from @ref{790,,Py_DECREF()}
when the new reference count is zero, but this may change in a future
version.

It is recommended to call @ref{55e3,,PyObject_CallFinalizerFromDealloc()} at the
beginning of @code{tp_dealloc} to guarantee that the object is always
finalized before destruction.

If the type supports garbage collection (the @ref{981,,Py_TPFLAGS_HAVE_GC}
flag is set), the destructor should call @ref{171e,,PyObject_GC_UnTrack()}
before clearing any member fields.

It is permissible to call @ref{4ee2,,tp_clear} from
@code{tp_dealloc} to reduce code duplication and to guarantee that the
object is always cleared before destruction.  Beware that
@code{tp_clear} might have already been called.

If the type is heap allocated (@ref{aac,,Py_TPFLAGS_HEAPTYPE}), the
deallocator should release the owned reference to its type object (via
@ref{790,,Py_DECREF()}) after calling the type deallocator.  See the example
code below.:

@example
static void
foo_dealloc(PyObject *op)
@{
   foo_object *self = (foo_object *) op;
   PyObject_GC_UnTrack(self);
   Py_CLEAR(self->ref);
   Py_TYPE(self)->tp_free(self);
@}
@end example

@code{tp_dealloc} must leave the exception status unchanged.  If it
needs to call something that might raise an exception, the exception state
must be backed up first and restored later (after logging any exceptions
with @ref{5f2,,PyErr_WriteUnraisable()}).

以下はプログラム例です:

@example
static void
foo_dealloc(PyObject *self)
@{
    PyObject *exc = PyErr_GetRaisedException();

    if (PyObject_CallFinalizerFromDealloc(self) < 0) @{
        // self was resurrected.
        goto done;
    @}

    PyTypeObject *tp = Py_TYPE(self);

    if (tp->tp_flags & Py_TPFLAGS_HAVE_GC) @{
        PyObject_GC_UnTrack(self);
    @}

    // Optional, but convenient to avoid code duplication.
    if (tp->tp_clear && tp->tp_clear(self) < 0) @{
        PyErr_WriteUnraisable(self);
    @}

    // Any additional destruction goes here.

    tp->tp_free(self);
    self = NULL;  // In case PyErr_WriteUnraisable() is called below.

    if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE) @{
        Py_CLEAR(tp);
    @}

done:
    // Optional, if something was called that might have raised an
    // exception.
    if (PyErr_Occurred()) @{
        PyErr_WriteUnraisable(self);
    @}
    PyErr_SetRaisedException(exc);
@}
@end example

@code{tp_dealloc} may be called from
any Python thread, not just the thread which created the object (if the
object becomes part of a refcount cycle, that cycle might be collected by
a garbage collection on any thread).  This is not a problem for Python
API calls, since the thread on which @code{tp_dealloc} is called
with an @ref{4ed1,,attached thread state}.  However, if the object being
destroyed in turn destroys objects from some other C library, care
should be taken to ensure that destroying those objects on the thread
which called @code{tp_dealloc} will not violate any assumptions of
the library.

`継承:'

サブタイプはこのフィールドを継承します。


@subsubheading 参考


@ref{55df,,Object Life Cycle} for details about how this slot relates to other slots.

@end deffn

@geindex PyTypeObject.tp_vectorcall_offset (C member)
@anchor{c-api/typeobj c PyTypeObject tp_vectorcall_offset}@anchor{5296}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} @ref{c9c,,PyTypeObject}.tp_vectorcall_offset

An optional offset to a per-instance function that implements calling
the object using the @ref{774,,vectorcall protocol},
a more efficient alternative
of the simpler @ref{77b,,tp_call}.

This field is only used if the flag @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL}
is set. If so, this must be a positive integer containing the offset in the
instance of a @ref{779,,vectorcallfunc} pointer.

The `vectorcallfunc' pointer may be @code{NULL}, in which case the instance behaves
as if @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} was not set: calling the instance
falls back to @ref{77b,,tp_call}.

Any class that sets @code{Py_TPFLAGS_HAVE_VECTORCALL} must also set
@ref{77b,,tp_call} and make sure its behaviour is consistent
with the `vectorcallfunc' function.
This can be done by setting `tp_call' to @ref{778,,PyVectorcall_Call()}.


バージョン 3.8 で変更: Before version 3.8, this slot was named @code{tp_print}.
In Python 2.x, it was used for printing to a file.
In Python 3.0 to 3.7, it was unused.



バージョン 3.12 で変更: Before version 3.12, it was not recommended for
@ref{b5e,,mutable heap types} to implement the vectorcall
protocol.
When a user sets @ref{77a,,__call__} in Python code, only `tp_call' is
updated, likely making it inconsistent with the vectorcall function.
Since 3.12, setting @code{__call__} will disable vectorcall optimization
by clearing the @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag.


`継承:'

This field is always inherited.
However, the @ref{776,,Py_TPFLAGS_HAVE_VECTORCALL} flag is not
always inherited. If it's not set, then the subclass won't use
@ref{774,,vectorcall}, except when
@ref{778,,PyVectorcall_Call()} is explicitly called.
@end deffn

@geindex PyTypeObject.tp_getattr (C member)
@anchor{c-api/typeobj c PyTypeObject tp_getattr}@anchor{4eed}
@deffn {C のメンバ変数} @ref{51a4,,getattrfunc} @ref{c9c,,PyTypeObject}.tp_getattr

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_getattr} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_getattr (C macro)
@anchor{c-api/typeobj c Py_tp_getattr}@anchor{518d}

オプションのポインタで、get-attribute-string を行う関数を指します。

このフィールドは非推奨です。
このフィールドを定義するときは、 @ref{1a64,,tp_getattro} 関数と同じように動作し、属性名は Python 文字列 オブジェクトではなく C 文字列で指定するような関数を指すようにしなければなりません。

`継承:'

Group: @ref{4eed,,tp_getattr}, @ref{1a64,,tp_getattro}

このフィールドは @ref{1a64,,tp_getattro} と共にサブタイプに継承されます: すなわち、サブタイプの @ref{4eed,,tp_getattr} および @ref{1a64,,tp_getattro} が共に @code{NULL} の場合、サブタイプは基底タイプから @ref{4eed,,tp_getattr} と @ref{1a64,,tp_getattro} を両方とも継承します。
@end deffn

@geindex PyTypeObject.tp_setattr (C member)
@anchor{c-api/typeobj c PyTypeObject tp_setattr}@anchor{4eee}
@deffn {C のメンバ変数} @ref{51b4,,setattrfunc} @ref{c9c,,PyTypeObject}.tp_setattr

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_setattr} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_setattr (C macro)
@anchor{c-api/typeobj c Py_tp_setattr}@anchor{519a}

オプションのポインタで、属性の設定と削除を行う関数を指します。

このフィールドは非推奨です。
このフィールドを定義するときは、 @ref{4ee8,,tp_setattro} 関数と同じように動作し、属性名は Python 文字列 オブジェクトではなく C 文字列で指定するような関数を指すようにしなければなりません。

`継承:'

Group: @ref{4eee,,tp_setattr}, @ref{4ee8,,tp_setattro}

このフィールドは @ref{4ee8,,tp_setattro} と共にサブタイプに継承されます: すなわち、サブタイプの @ref{4eee,,tp_setattr} および @ref{4ee8,,tp_setattro} が共に @code{NULL} の場合、サブタイプは基底タイプから @ref{4eee,,tp_setattr} と @ref{4ee8,,tp_setattro} を両方とも継承します。
@end deffn

@geindex PyTypeObject.tp_as_async (C member)
@anchor{c-api/typeobj c PyTypeObject tp_as_async}@anchor{10cf}
@deffn {C のメンバ変数} @ref{52ea,,PyAsyncMethods} *@ref{c9c,,PyTypeObject}.tp_as_async

追加の構造体を指すポインタです。
この構造体は、 C レベルで @ref{4c9,,awaitable} プロトコルと @ref{4c7,,asynchronous iterator} プロトコルを実装するオブジェクトだけに関係するフィールドを持ちます。
詳しいことは @ref{5652,,async オブジェクト構造体} を参照してください。


Added in version 3.5: 以前は @code{tp_compare} や @code{tp_reserved} として知られていました。


`継承:'

@ref{10cf,,tp_as_async} フィールドは継承されませんが、これに含まれるフィールドが個別に継承されます。
@end deffn

@geindex PyTypeObject.tp_repr (C member)
@anchor{c-api/typeobj c PyTypeObject tp_repr}@anchor{4ee4}
@deffn {C のメンバ変数} @ref{51b2,,reprfunc} @ref{c9c,,PyTypeObject}.tp_repr

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_repr} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_repr (C macro)
@anchor{c-api/typeobj c Py_tp_repr}@anchor{5198}

@geindex 組み込み関数;repr

オプションのポインタで、組み込み関数 @ref{1c1,,repr()} を実装している関数を指します。

The signature is the same as for @ref{1230,,PyObject_Repr()}:

@example
PyObject *tp_repr(PyObject *self);
@end example

この関数は文字列オブジェクトか Unicode オブジェクトを返さなければなりません。理想的には、この関数が返す文字列は、適切な環境で @ref{4a3,,eval()} に渡した場合、同じ値を持つオブジェクトになるような文字列でなければなりません。不可能な場合には、オブジェクトの型と値から導出した内容の入った @code{'<'} から始まって @code{'>'} で終わる文字列を返さなければなりません。

`継承:'

サブタイプはこのフィールドを継承します。

`デフォルト'

このフィールドが設定されていない場合、 @code{<%s object at %p>} の形式をとる文字列が返されます。 @code{%s} は型の名前に、 @code{%p} はオブジェクトのメモリアドレスに置き換えられます。
@end deffn

@geindex PyTypeObject.tp_as_number (C member)
@anchor{c-api/typeobj c PyTypeObject tp_as_number}@anchor{b82}
@deffn {C のメンバ変数} @ref{1637,,PyNumberMethods} *@ref{c9c,,PyTypeObject}.tp_as_number

数値プロトコルを実装した追加の構造体を指すポインタです。これらのフィールドについては @ref{5653,,数値オブジェクト構造体} で説明されています。

`継承:'

@ref{b82,,tp_as_number} フィールドは継承されませんが、そこの含まれるフィールドが個別に継承されます。
@end deffn

@geindex PyTypeObject.tp_as_sequence (C member)
@anchor{c-api/typeobj c PyTypeObject tp_as_sequence}@anchor{5614}
@deffn {C のメンバ変数} @ref{4ef4,,PySequenceMethods} *@ref{c9c,,PyTypeObject}.tp_as_sequence

シーケンスプロトコルを実装した追加の構造体を指すポインタです。これらのフィールドについては @ref{5654,,シーケンスオブジェクト構造体} で説明されています。

`継承:'

@ref{5614,,tp_as_sequence} フィールドは継承されませんが、これに含まれるフィールドが個別に継承されます。
@end deffn

@geindex PyTypeObject.tp_as_mapping (C member)
@anchor{c-api/typeobj c PyTypeObject tp_as_mapping}@anchor{5615}
@deffn {C のメンバ変数} @ref{4ef5,,PyMappingMethods} *@ref{c9c,,PyTypeObject}.tp_as_mapping

マッピングプロトコルを実装した追加の構造体を指すポインタです。これらのフィールドについては @ref{5655,,マップオブジェクト構造体} で説明されています。

`継承:'

@ref{5615,,tp_as_mapping} フィールドは継承されませんが、これに含まれるフィールドが個別に継承されます。
@end deffn

@geindex PyTypeObject.tp_hash (C member)
@anchor{c-api/typeobj c PyTypeObject tp_hash}@anchor{4ef6}
@deffn {C のメンバ変数} @ref{51a9,,hashfunc} @ref{c9c,,PyTypeObject}.tp_hash

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_hash} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_hash (C macro)
@anchor{c-api/typeobj c Py_tp_hash}@anchor{5190}

@geindex 組み込み関数;hash

オプションのポインタで、組み込み関数 @ref{801,,hash()} を実装している関数を指します。

The signature is the same as for @ref{436,,PyObject_Hash()}:

@example
Py_hash_t tp_hash(PyObject *);
@end example

通常時には @code{-1} を戻り値にしてはなりません; ハッシュ値の計算中にエラーが生じた場合、関数は例外をセットして @code{-1} を返さねばなりません。

When this field is not set (`and' @ref{4ef0,,tp_richcompare} is not set),
an attempt to take the hash of the object raises @ref{198,,TypeError}.
This is the same as setting it to @ref{15e0,,PyObject_HashNotImplemented()}.

このフィールドは明示的に @ref{15e0,,PyObject_HashNotImplemented()} に設定することで、親 type からのハッシュメソッドの継承をブロックすることができます。これは Python レベルでの @code{__hash__ = None} と同等に解釈され、 @code{isinstance(o, collections.Hashable)} が正しく @code{False} を返すようになります。逆もまた可能であることに注意してください - Python レベルで @code{__hash__ = None} を設定することで @code{tp_hash} スロットは @ref{15e0,,PyObject_HashNotImplemented()} に設定されます。

`継承:'

Group: @ref{4ef6,,tp_hash}, @ref{4ef0,,tp_richcompare}

このフィールドは @ref{4ef0,,tp_richcompare} と共にサブタイプに継承されます: すなわち、サブタイプの @ref{4ef0,,tp_richcompare} および @ref{4ef6,,tp_hash} が両方とも @code{NULL} のとき、サブタイプは基底タイプから @ref{4ef0,,tp_richcompare} と @ref{4ef6,,tp_hash} を両方とも継承します。

`デフォルト'

@ref{4f75,,PyBaseObject_Type} uses @ref{60c,,PyObject_GenericHash()}.
@end deffn

@geindex PyTypeObject.tp_call (C member)
@anchor{c-api/typeobj c PyTypeObject tp_call}@anchor{77b}
@deffn {C のメンバ変数} @ref{51b9,,ternaryfunc} @ref{c9c,,PyTypeObject}.tp_call

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_call} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_call (C macro)
@anchor{c-api/typeobj c Py_tp_call}@anchor{5184}

オプションのポインタで、オブジェクトの呼び出しを実装している関数を指します。オブジェクトが呼び出し可能でない場合には @code{NULL} にしなければなりません。シグネチャは @ref{63d,,PyObject_Call()} と同じです。

@example
PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);
@end example

`継承:'

サブタイプはこのフィールドを継承します。
@end deffn

@geindex PyTypeObject.tp_str (C member)
@anchor{c-api/typeobj c PyTypeObject tp_str}@anchor{4ee5}
@deffn {C のメンバ変数} @ref{51b2,,reprfunc} @ref{c9c,,PyTypeObject}.tp_str

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_str} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_str (C macro)
@anchor{c-api/typeobj c Py_tp_str}@anchor{519c}

オプションのポインタで、組み込みの演算 @ref{169,,str()} を実装している関数を指します。(@ref{169,,str} が型の一つになったため、 @ref{169,,str()} は @ref{169,,str} のコンストラクタを呼び出すことに注意してください。このコンストラクタは実際の処理を行う上で @ref{1231,,PyObject_Str()} を呼び出し、さらに @ref{1231,,PyObject_Str()} がこのハンドラを呼び出すことになります。)

The signature is the same as for @ref{1231,,PyObject_Str()}:

@example
PyObject *tp_str(PyObject *self);
@end example

この関数は文字列オブジェクトか Unicode オブジェクトを返さなければなりません。それはオブジェクトを "分かりやすく (friendly)" 表現した文字列でなければなりません。というのは、この文字列はとりわけ @ref{1177,,print()} 関数で使われることになる表記だからです。

`継承:'

サブタイプはこのフィールドを継承します。

`デフォルト'

このフィールドが設定されていない場合、文字列表現を返すためには @ref{1230,,PyObject_Repr()} が呼び出されます。
@end deffn

@geindex PyTypeObject.tp_getattro (C member)
@anchor{c-api/typeobj c PyTypeObject tp_getattro}@anchor{1a64}
@deffn {C のメンバ変数} @ref{51a5,,getattrofunc} @ref{c9c,,PyTypeObject}.tp_getattro

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_getattro} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_getattro (C macro)
@anchor{c-api/typeobj c Py_tp_getattro}@anchor{518e}

オプションのポインタで、get-attribute を実装している関数を指します。

The signature is the same as for @ref{5ee,,PyObject_GetAttr()}:

@example
PyObject *tp_getattro(PyObject *self, PyObject *attr);
@end example

通常の属性検索を実装している @ref{508e,,PyObject_GenericGetAttr()}  をこのフィールドに設定しておくとたいていの場合は便利です。

`継承:'

Group: @ref{4eed,,tp_getattr}, @ref{1a64,,tp_getattro}

このフィールドは @ref{4eed,,tp_getattr} と共にサブタイプに継承されます: すなわち、サブタイプの @ref{4eed,,tp_getattr} および @ref{1a64,,tp_getattro} が共に @code{NULL} の場合、サブタイプは基底タイプから @ref{4eed,,tp_getattr} と @ref{1a64,,tp_getattro} を両方とも継承します。

`デフォルト'

@ref{4f75,,PyBaseObject_Type} uses @ref{508e,,PyObject_GenericGetAttr()}.
@end deffn

@geindex PyTypeObject.tp_setattro (C member)
@anchor{c-api/typeobj c PyTypeObject tp_setattro}@anchor{4ee8}
@deffn {C のメンバ変数} @ref{51b5,,setattrofunc} @ref{c9c,,PyTypeObject}.tp_setattro

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_setattro} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_setattro (C macro)
@anchor{c-api/typeobj c Py_tp_setattro}@anchor{519b}

オプションのポインタで、属性の設定と削除を行う関数を指します。

The signature is the same as for @ref{5097,,PyObject_SetAttr()}:

@example
int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);
@end example

さらに、`value' に @code{NULL} を指定して属性を削除できるようにしなければなりません。
通常のオブジェクト属性設定を実装している @ref{508f,,PyObject_GenericSetAttr()}  をこのフィールドに設定しておくとたいていの場合は便利です。

`継承:'

Group: @ref{4eee,,tp_setattr}, @ref{4ee8,,tp_setattro}

このフィールドは @ref{4eee,,tp_setattr} と共にサブタイプに継承されます: すなわち、サブタイプの @ref{4eee,,tp_setattr} および @ref{4ee8,,tp_setattro} が共に @code{NULL} の場合、サブタイプは基底タイプから @ref{4eee,,tp_setattr} と @ref{4ee8,,tp_setattro} を両方とも継承します。

`デフォルト'

@ref{4f75,,PyBaseObject_Type} uses @ref{508f,,PyObject_GenericSetAttr()}.
@end deffn

@geindex PyTypeObject.tp_as_buffer (C member)
@anchor{c-api/typeobj c PyTypeObject tp_as_buffer}@anchor{b80}
@deffn {C のメンバ変数} @ref{52f1,,PyBufferProcs} *@ref{c9c,,PyTypeObject}.tp_as_buffer

バッファインターフェースを実装しているオブジェクトにのみ関連する、一連のフィールド群が入った別の構造体を指すポインタです。構造体内の各フィールドは @ref{1248,,バッファオブジェクト構造体 (buffer object structure)} で説明します。

`継承:'

@ref{b80,,tp_as_buffer} フィールド自体は継承されませんが、これに含まれるフィールドは個別に継承されます。
@end deffn

@geindex PyTypeObject.tp_flags (C member)
@anchor{c-api/typeobj c PyTypeObject tp_flags}@anchor{1c71}
@deffn {C のメンバ変数} unsigned long @ref{c9c,,PyTypeObject}.tp_flags

このフィールドは様々なフラグからなるビットマスクです。いくつかのフラグは、特定の状況において変則的なセマンティクスが適用されることを示します; その他のフラグは、型オブジェクト (あるいは @ref{b82,,tp_as_number} 、 @ref{5614,,tp_as_sequence} 、 @ref{5615,,tp_as_mapping} 、 および @ref{b80,,tp_as_buffer} が参照している拡張機能構造体) の特定のフィールドのうち、過去から現在までずっと存在していたわけではないものが有効になっていることを示すために使われます; フラグビットがクリアされていれば、フラグが保護しているフィールドにはアクセスしない代わりに、その値はゼロか @code{NULL} になっているとみなさなければなりません。

`継承:'

Inheritance of this field is complicated.  Most flag bits are inherited
individually, i.e. if the base type has a flag bit set, the subtype inherits
this flag bit.  The flag bits that pertain to extension structures are strictly
inherited if the extension structure is inherited, i.e. the base type's value of
the flag bit is copied into the subtype together with a pointer to the extension
structure.  The @ref{981,,Py_TPFLAGS_HAVE_GC} flag bit is inherited together with
the @ref{982,,tp_traverse} and @ref{4ee2,,tp_clear} fields, i.e. if the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag bit is clear in the subtype and the
@ref{982,,tp_traverse} and @ref{4ee2,,tp_clear} fields in the subtype exist and have
@code{NULL} values.

@c XXX are most flag bits *really* inherited individually?

`デフォルト'

@ref{4f75,,PyBaseObject_Type} uses
@code{Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE}.

`Bit Masks:'

以下に挙げるビットマスクは現在定義されているものです; フラグは @code{|} 演算子で論理和を取って @ref{1c71,,tp_flags} フィールドの値を作成できます。 @ref{1d3c,,PyType_HasFeature()} マクロは型とフラグ値、 `tp' および `f' をとり、 @code{tp->tp_flags & f} が非ゼロかどうか調べます。

@geindex Py_TPFLAGS_HEAPTYPE (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_HEAPTYPE}@anchor{aac}
@deffn {C のマクロ} Py_TPFLAGS_HEAPTYPE

This bit is set when the type object itself is allocated on the heap, for
example, types created dynamically using @ref{79d,,PyType_FromSpec()}.  In this
case, the @ref{4ecd,,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). Heap types should also @ref{5656,,support garbage collection}
as they can form a reference cycle with their own module object.

`継承:'

???
@end deffn

@geindex Py_TPFLAGS_BASETYPE (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_BASETYPE}@anchor{4ed5}
@deffn {C のマクロ} Py_TPFLAGS_BASETYPE
` 次に属します: @ref{775,,Stable ABI}.'
型を別の型の基底タイプとして使える場合にセットされるビットです。このビットがクリアならば、この型のサブタイプは生成できません (Java における "final" クラスに似たクラスになります)。

`継承:'

???
@end deffn

@geindex Py_TPFLAGS_READY (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_READY}@anchor{5657}
@deffn {C のマクロ} Py_TPFLAGS_READY

型オブジェクトが @ref{980,,PyType_Ready()} で完全に初期化されるとセットされるビットです。

`継承:'

???
@end deffn

@geindex Py_TPFLAGS_READYING (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_READYING}@anchor{5658}
@deffn {C のマクロ} Py_TPFLAGS_READYING

@ref{980,,PyType_Ready()} による型オブジェクトの初期化処理中にセットされるビットです。

`継承:'

???
@end deffn

@geindex Py_TPFLAGS_HAVE_GC (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_HAVE_GC}@anchor{981}
@deffn {C のマクロ} Py_TPFLAGS_HAVE_GC
` 次に属します: @ref{775,,Stable ABI}.'
This bit is set when the object supports garbage collection.  If this bit
is set, memory for new instances (see @ref{4ed0,,tp_alloc})
must be allocated using @ref{c99,,PyObject_GC_New} or
@ref{c61,,PyType_GenericAlloc()} and deallocated (see
@ref{4ecf,,tp_free}) using @ref{171c,,PyObject_GC_Del()}.  More
information in section @ref{5656,,循環参照ガベージコレクションをサポートする}.

`継承:'

Group: @ref{981,,Py_TPFLAGS_HAVE_GC}, @ref{982,,tp_traverse}, @ref{4ee2,,tp_clear}

The @ref{981,,Py_TPFLAGS_HAVE_GC} flag bit is inherited
together with the @ref{982,,tp_traverse} and @ref{4ee2,,tp_clear}
fields, i.e.  if the @ref{981,,Py_TPFLAGS_HAVE_GC} flag bit is
clear in the subtype and the @ref{982,,tp_traverse} and
@ref{4ee2,,tp_clear} fields in the subtype exist and have @code{NULL}
values.
@end deffn

@geindex Py_TPFLAGS_DEFAULT (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_DEFAULT}@anchor{4eca}
@deffn {C のマクロ} Py_TPFLAGS_DEFAULT
` 次に属します: @ref{775,,Stable ABI}.'
This is a bitmask of all the bits that pertain to the existence of certain
fields in the type object and its extension structures. Currently, it includes
the following bits: @code{Py_TPFLAGS_HAVE_STACKLESS_EXTENSION}.

`継承:'

???
@end deffn

@geindex Py_TPFLAGS_METHOD_DESCRIPTOR (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_METHOD_DESCRIPTOR}@anchor{5138}
@deffn {C のマクロ} Py_TPFLAGS_METHOD_DESCRIPTOR
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.8 より).'
This bit indicates that objects behave like unbound methods.

If this flag is set for @code{type(meth)}, then:


@itemize -

@item 
@code{meth.__get__(obj, cls)(*args, **kwds)} (with @code{obj} not None)
must be equivalent to @code{meth(obj, *args, **kwds)}.

@item 
@code{meth.__get__(None, cls)(*args, **kwds)}
must be equivalent to @code{meth(*args, **kwds)}.
@end itemize

This flag enables an optimization for typical method calls like
@code{obj.meth()}: it avoids creating a temporary "bound method" object for
@code{obj.meth}.


Added in version 3.8.


`継承:'

This flag is never inherited by types without the
@ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} flag set.  For extension types, it is
inherited whenever @ref{5616,,tp_descr_get} is inherited.
@end deffn

@geindex Py_TPFLAGS_MANAGED_DICT (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_MANAGED_DICT}@anchor{60f}
@deffn {C のマクロ} Py_TPFLAGS_MANAGED_DICT

This bit indicates that instances of the class have a @ref{77d,,__dict__}
attribute, and that the space for the dictionary is managed by the VM.

If this flag is set, @ref{981,,Py_TPFLAGS_HAVE_GC} should also be set.

The type traverse function must call @ref{60d,,PyObject_VisitManagedDict()}
and its clear function must call @ref{60e,,PyObject_ClearManagedDict()}.


Added in version 3.12.


`継承:'

This flag is inherited unless the
@ref{52ec,,tp_dictoffset} field is set in a superclass.
@end deffn

@geindex Py_TPFLAGS_MANAGED_WEAKREF (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_MANAGED_WEAKREF}@anchor{77c}
@deffn {C のマクロ} Py_TPFLAGS_MANAGED_WEAKREF

This bit indicates that instances of the class should be weakly
referenceable.


Added in version 3.12.


`継承:'

This flag is inherited unless the
@ref{b7f,,tp_weaklistoffset} field is set in a superclass.
@end deffn

@geindex Py_TPFLAGS_ITEMS_AT_END (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_ITEMS_AT_END}@anchor{76d}
@deffn {C のマクロ} Py_TPFLAGS_ITEMS_AT_END
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
Only usable with variable-size types, i.e. ones with non-zero
@ref{23bb,,tp_itemsize}.

Indicates that the variable-sized portion of an instance of this type is
at the end of the instance's memory area, at an offset of
@code{Py_TYPE(obj)->tp_basicsize} (which may be different in each
subclass).

When setting this flag, be sure that all superclasses either
use this memory layout, or are not variable-sized.
Python does not check this.


Added in version 3.12.


`継承:'

This flag is inherited.
@end deffn

@c XXX Document more flags here?

@geindex Py_TPFLAGS_LONG_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_LONG_SUBCLASS}@anchor{52df}
@deffn {C のマクロ} Py_TPFLAGS_LONG_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_LIST_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_LIST_SUBCLASS}@anchor{5659}
@deffn {C のマクロ} Py_TPFLAGS_LIST_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_TUPLE_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_TUPLE_SUBCLASS}@anchor{565a}
@deffn {C のマクロ} Py_TPFLAGS_TUPLE_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_BYTES_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_BYTES_SUBCLASS}@anchor{565b}
@deffn {C のマクロ} Py_TPFLAGS_BYTES_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_UNICODE_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_UNICODE_SUBCLASS}@anchor{565c}
@deffn {C のマクロ} Py_TPFLAGS_UNICODE_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_DICT_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_DICT_SUBCLASS}@anchor{565d}
@deffn {C のマクロ} Py_TPFLAGS_DICT_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_BASE_EXC_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_BASE_EXC_SUBCLASS}@anchor{565e}
@deffn {C のマクロ} Py_TPFLAGS_BASE_EXC_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_TYPE_SUBCLASS (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_TYPE_SUBCLASS}@anchor{565f}
@deffn {C のマクロ} Py_TPFLAGS_TYPE_SUBCLASS

Functions such as @ref{52fc,,PyLong_Check()} will call @ref{52de,,PyType_FastSubclass()}
with one of these flags to quickly determine if a type is a subclass
of a built-in type; such specific checks are faster than a generic
check, like @ref{10a6,,PyObject_IsInstance()}. Custom types that inherit
from built-ins should have their @ref{1c71,,tp_flags}
set appropriately, or the code that interacts with such types
will behave differently depending on what kind of check is used.
@end deffn

@geindex Py_TPFLAGS_HAVE_FINALIZE (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_HAVE_FINALIZE}@anchor{427}
@deffn {C のマクロ} Py_TPFLAGS_HAVE_FINALIZE

型構造体に @ref{c9d,,tp_finalize} スロットが存在しているときにセットされるビットです。


Added in version 3.4.



バージョン 3.8 で非推奨: This flag isn't necessary anymore, as the interpreter assumes the
@ref{c9d,,tp_finalize} slot is always present in the
type structure.

@end deffn

@geindex _Py_TPFLAGS_HAVE_VECTORCALL (C macro)

@geindex Py_TPFLAGS_HAVE_VECTORCALL (C macro)
@anchor{c-api/typeobj c _Py_TPFLAGS_HAVE_VECTORCALL}@anchor{5660}@anchor{c-api/typeobj c Py_TPFLAGS_HAVE_VECTORCALL}@anchor{776}
@deffn {C のマクロ} Py_TPFLAGS_HAVE_VECTORCALL
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
This bit is set when the class implements
the @ref{774,,vectorcall protocol}.
See @ref{5296,,tp_vectorcall_offset} for details.

`継承:'

This bit is inherited if @ref{77b,,tp_call} is also
inherited.


Added in version 3.8: as @code{_Py_TPFLAGS_HAVE_VECTORCALL}



バージョン 3.9 で変更.


Renamed to the current name, without the leading underscore.
The old provisional name is @ref{23d,,soft deprecated}.


バージョン 3.12 で変更: This flag is now removed from a class when the class's
@ref{77a,,__call__()} method is reassigned.

This flag can now be inherited by mutable classes.

@end deffn

@geindex Py_TPFLAGS_IMMUTABLETYPE (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_IMMUTABLETYPE}@anchor{3cf}
@deffn {C のマクロ} Py_TPFLAGS_IMMUTABLETYPE

This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.

@ref{980,,PyType_Ready()} automatically applies this flag to
@ref{983,,static types}.

`継承:'

This flag is not inherited.


Added in version 3.10.

@end deffn

@geindex Py_TPFLAGS_DISALLOW_INSTANTIATION (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_DISALLOW_INSTANTIATION}@anchor{7a2}
@deffn {C のマクロ} Py_TPFLAGS_DISALLOW_INSTANTIATION

Disallow creating instances of the type: set
@ref{79f,,tp_new} to NULL and don't create the @code{__new__}
key in the type dictionary.

The flag must be set before creating the type, not after. For example, it
must be set before @ref{980,,PyType_Ready()} is called on the type.

The flag is set automatically on @ref{983,,static types} if
@ref{2375,,tp_base} is NULL or @code{&PyBaseObject_Type} and
@ref{79f,,tp_new} is NULL.

`継承:'

This flag is not inherited.
However, subclasses will not be instantiable unless they provide a
non-NULL @ref{79f,,tp_new} (which is only possible
via the C API).

@cartouche
@quotation 注釈 
To disallow instantiating a class directly but allow instantiating
its subclasses (e.g. for an @ref{13ce,,abstract base class}),
do not use this flag.
Instead, make @ref{79f,,tp_new} only succeed for
subclasses.
@end quotation
@end cartouche


Added in version 3.10.

@end deffn

@geindex Py_TPFLAGS_MAPPING (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_MAPPING}@anchor{1c58}
@deffn {C のマクロ} Py_TPFLAGS_MAPPING

This bit indicates that instances of the class may match mapping patterns
when used as the subject of a @ref{a0e,,match} block. It is automatically
set when registering or subclassing @ref{ac7,,collections.abc.Mapping}, and
unset when registering @ref{13dc,,collections.abc.Sequence}.

@cartouche
@quotation 注釈 
@ref{1c58,,Py_TPFLAGS_MAPPING} and @ref{1c59,,Py_TPFLAGS_SEQUENCE} are
mutually exclusive; it is an error to enable both flags simultaneously.
@end quotation
@end cartouche

`継承:'

This flag is inherited by types that do not already set
@ref{1c59,,Py_TPFLAGS_SEQUENCE}.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/} -- 構造的パターンマッチ: 仕様



Added in version 3.10.

@end deffn

@geindex Py_TPFLAGS_SEQUENCE (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_SEQUENCE}@anchor{1c59}
@deffn {C のマクロ} Py_TPFLAGS_SEQUENCE

This bit indicates that instances of the class may match sequence patterns
when used as the subject of a @ref{a0e,,match} block. It is automatically
set when registering or subclassing @ref{13dc,,collections.abc.Sequence}, and
unset when registering @ref{ac7,,collections.abc.Mapping}.

@cartouche
@quotation 注釈 
@ref{1c58,,Py_TPFLAGS_MAPPING} and @ref{1c59,,Py_TPFLAGS_SEQUENCE} are
mutually exclusive; it is an error to enable both flags simultaneously.
@end quotation
@end cartouche

`継承:'

This flag is inherited by types that do not already set
@ref{1c58,,Py_TPFLAGS_MAPPING}.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 634
PEP 634@footnote{https://peps.python.org/pep-0634/} -- 構造的パターンマッチ: 仕様



Added in version 3.10.

@end deffn

@geindex Py_TPFLAGS_VALID_VERSION_TAG (C macro)
@anchor{c-api/typeobj c Py_TPFLAGS_VALID_VERSION_TAG}@anchor{5661}
@deffn {C のマクロ} Py_TPFLAGS_VALID_VERSION_TAG

Internal. Do not set or unset this flag.
To indicate that a class has changed call @ref{1b7b,,PyType_Modified()}

@cartouche
@quotation 警告 
This flag is present in header files, but is not be used.
It will be removed in a future version of CPython
@end quotation
@end cartouche
@end deffn
@end deffn

@geindex PyTypeObject.tp_doc (C member)
@anchor{c-api/typeobj c PyTypeObject tp_doc}@anchor{4ecb}
@deffn {C のメンバ変数} const char *@ref{c9c,,PyTypeObject}.tp_doc

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_doc} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_doc (C macro)
@anchor{c-api/typeobj c Py_tp_doc}@anchor{518a}

An optional pointer to a NUL-terminated C string giving the docstring for this
type object.  This is exposed as the @ref{2095,,__doc__} attribute on the
type and instances of the type.

`継承:'

サブタイプはこのフィールドを継承 `しません' 。
@end deffn

@geindex PyTypeObject.tp_traverse (C member)
@anchor{c-api/typeobj c PyTypeObject tp_traverse}@anchor{982}
@deffn {C のメンバ変数} @ref{51ba,,traverseproc} @ref{c9c,,PyTypeObject}.tp_traverse

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_traverse} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_traverse (C macro)
@anchor{c-api/typeobj c Py_tp_traverse}@anchor{519d}

An optional pointer to a traversal function for the garbage collector.  This is
only used if the @ref{981,,Py_TPFLAGS_HAVE_GC} flag bit is set.  The signature is:

@example
int tp_traverse(PyObject *self, visitproc visit, void *arg);
@end example

Pythonのガベージコレクションの仕組みについての詳細は、 @ref{5656,,循環参照ガベージコレクションをサポートする} にあります。

The @ref{982,,tp_traverse} pointer is used by the garbage collector to detect
reference cycles. A typical implementation of a @ref{982,,tp_traverse} function
simply calls @ref{4ed9,,Py_VISIT()} on each of the instance's members that are Python
objects that the instance owns. For example, this is function @code{local_traverse()} from the
@code{_thread} extension module:

@example
static int
local_traverse(PyObject *op, visitproc visit, void *arg)
@{
    localobject *self = (localobject *) op;
    Py_VISIT(self->args);
    Py_VISIT(self->kw);
    Py_VISIT(self->dict);
    return 0;
@}
@end example

@ref{4ed9,,Py_VISIT()} が循環参照になる恐れのあるメンバにだけ呼び出されていることに注目してください。 @code{self->key} メンバもありますが、それは @code{NULL} か Python文字列なので、循環参照の一部になることはありません。

一方、メンバが循環参照の一部になり得ないと判っていても、デバッグ目的で巡回したい場合があるかもしれないので、 @ref{64,,gc} モジュールの @ref{a06,,get_referents()} 関数は循環参照になり得ないメンバも返します。

Heap types (@ref{aac,,Py_TPFLAGS_HEAPTYPE}) must visit their type with:

@example
Py_VISIT(Py_TYPE(self));
@end example

It is only needed since Python 3.9. To support Python 3.8 and older, this
line must be conditional:

@example
#if PY_VERSION_HEX >= 0x03090000
    Py_VISIT(Py_TYPE(self));
#endif
@end example

If the @ref{60f,,Py_TPFLAGS_MANAGED_DICT} bit is set in the
@ref{1c71,,tp_flags} field, the traverse function must call
@ref{60d,,PyObject_VisitManagedDict()} like this:

@example
PyObject_VisitManagedDict((PyObject*)self, visit, arg);
@end example

@cartouche
@quotation 警告 
When implementing @ref{982,,tp_traverse}, only the
members that the instance `owns' (by having @ref{5e2,,strong references} to them) must be
visited. For instance, if an object supports weak references via the
@ref{52f0,,tp_weaklist} 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).
@end quotation
@end cartouche

@cartouche
@quotation 警告 
The traversal function must not have any side effects.  It must not
modify the reference counts of any Python objects nor create or destroy
any Python objects.
@end quotation
@end cartouche

Note that @ref{4ed9,,Py_VISIT()} requires the `visit' and `arg' parameters to
@code{local_traverse()} to have these specific names; don't name them just
anything.

Instances of @ref{b5e,,heap-allocated types} hold a reference to
their type. Their traversal function must therefore either visit
@ref{3c9,,Py_TYPE(self)}, or delegate this responsibility by
calling @code{tp_traverse} of another heap-allocated type (such as a
heap-allocated superclass).
If they do not, the type object may not be garbage-collected.

@cartouche
@quotation 注釈 
The @ref{982,,tp_traverse} function can be called from any
thread.
@end quotation
@end cartouche


バージョン 3.9 で変更: Heap-allocated types are expected to visit @code{Py_TYPE(self)} in
@code{tp_traverse}.  In earlier versions of Python, due to
bug 40217@footnote{https://bugs.python.org/issue40217}, doing this
may lead to crashes in subclasses.


`継承:'

Group: @ref{981,,Py_TPFLAGS_HAVE_GC}, @ref{982,,tp_traverse}, @ref{4ee2,,tp_clear}

This field is inherited by subtypes together with @ref{4ee2,,tp_clear} and the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag bit: the flag bit, @ref{982,,tp_traverse}, and
@ref{4ee2,,tp_clear} are all inherited from the base type if they are all zero in
the subtype.
@end deffn

@geindex PyTypeObject.tp_clear (C member)
@anchor{c-api/typeobj c PyTypeObject tp_clear}@anchor{4ee2}
@deffn {C のメンバ変数} @ref{51ab,,inquiry} @ref{c9c,,PyTypeObject}.tp_clear

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_clear} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_clear (C macro)
@anchor{c-api/typeobj c Py_tp_clear}@anchor{5185}

An optional pointer to a clear function.  The signature is:

@example
int tp_clear(PyObject *);
@end example

The purpose of this function is to break reference cycles that are causing a
@ref{55e4,,cyclic isolate} so that the objects can be safely destroyed.  A
cleared object is a partially destroyed object; the object is not obligated
to satisfy design invariants held during normal use.

@code{tp_clear} does not need to delete references to objects that
can't participate in reference cycles, such as Python strings or Python
integers.  However, it may be convenient to clear all references, and write
the type's @ref{4ebc,,tp_dealloc} function to invoke
@code{tp_clear} to avoid code duplication.  (Beware that
@code{tp_clear} might have already been called. Prefer calling
idempotent functions like @ref{798,,Py_CLEAR()}.)

Any non-trivial cleanup should be performed in
@ref{c9d,,tp_finalize} instead of @code{tp_clear}.

@cartouche
@quotation 注釈 
If @code{tp_clear} fails to break a reference cycle then the
objects in the @ref{55e4,,cyclic isolate} may remain indefinitely
uncollectable ("leak").  See @ref{13d9,,gc.garbage}.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
Referents (direct and indirect) might have already been cleared; they are
not guaranteed to be in a consistent state.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
The @ref{4ee2,,tp_clear} function can be called from any
thread.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
An object is not guaranteed to be automatically cleared before its
destructor (@ref{4ebc,,tp_dealloc}) is called.
@end quotation
@end cartouche

This function differs from the destructor
(@ref{4ebc,,tp_dealloc}) in the following ways:


@itemize *

@item 
The purpose of clearing an object is to remove references to other objects
that might participate in a reference cycle.  The purpose of the
destructor, on the other hand, is a superset: it must release `all'
resources it owns, including references to objects that cannot participate
in a reference cycle (e.g., integers) as well as the object's own memory
(by calling @ref{4ecf,,tp_free}).

@item 
When @code{tp_clear} is called, other objects might still hold
references to the object being cleared.  Because of this,
@code{tp_clear} must not deallocate the object's own memory
(@ref{4ecf,,tp_free}).  The destructor, on the other hand,
is only called when no (strong) references exist, and as such, must
safely destroy the object itself by deallocating it.

@item 
@code{tp_clear} might never be automatically called.  An object's
destructor, on the other hand, will be automatically called some time
after the object becomes unreachable (i.e., either there are no references
to the object or the object is a member of a @ref{55e4,,cyclic isolate}).
@end itemize

No guarantees are made about when, if, or how often Python automatically
clears an object, except:


@itemize *

@item 
Python will not automatically clear an object if it is reachable, i.e.,
there is a reference to it and it is not a member of a @ref{55e4,,cyclic isolate}.

@item 
Python will not automatically clear an object if it has not been
automatically finalized (see @ref{c9d,,tp_finalize}).  (If
the finalizer resurrected the object, the object may or may not be
automatically finalized again before it is cleared.)

@item 
If an object is a member of a @ref{55e4,,cyclic isolate}, Python will not
automatically clear it if any member of the cyclic isolate has not yet
been automatically finalized (@ref{c9d,,tp_finalize}).

@item 
Python will not destroy an object until after any automatic calls to its
@code{tp_clear} function have returned.  This ensures that the act
of breaking a reference cycle does not invalidate the @code{self} pointer
while @code{tp_clear} is still executing.

@item 
Python will not automatically call @code{tp_clear} multiple times
concurrently.
@end itemize

CPython currently only automatically clears objects as needed to break
reference cycles in a @ref{55e4,,cyclic isolate}, but future versions might
clear objects regularly before their destruction.

Taken together, all @ref{4ee2,,tp_clear} functions in the
system must combine to break all reference cycles.  This is subtle, and if
in any doubt supply a @ref{4ee2,,tp_clear} function.  For
example, the tuple type does not implement a
@ref{4ee2,,tp_clear} function, because it's possible to prove
that no reference cycle can be composed entirely of tuples.  Therefore the
@ref{4ee2,,tp_clear} functions of other types are responsible
for breaking any cycle containing a tuple.  This isn't immediately obvious,
and there's rarely a good reason to avoid implementing
@ref{4ee2,,tp_clear}.

次の例にあるように、 @ref{4ee2,,tp_clear} の実装は、インスタンスから Python オブジェクトだと思われるメンバへの参照を外し、それらのメンバへのポインタに @code{NULL} をセットすべきです:

@example
static int
local_clear(PyObject *op)
@{
    localobject *self = (localobject *) op;
    Py_CLEAR(self->key);
    Py_CLEAR(self->args);
    Py_CLEAR(self->kw);
    Py_CLEAR(self->dict);
    return 0;
@}
@end example

The @ref{798,,Py_CLEAR()} macro should be used, because clearing references is
delicate:  the reference to the contained object must not be released
(via @ref{790,,Py_DECREF()}) until
after the pointer to the contained object is set to @code{NULL}.  This is because
releasing the reference 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 @code{NULL} at that time,
so that `self' knows the contained object can no longer be used.  The
@ref{798,,Py_CLEAR()} macro performs the operations in a safe order.

If the @ref{60f,,Py_TPFLAGS_MANAGED_DICT} bit is set in the
@ref{1c71,,tp_flags} field, the clear function must call
@ref{60e,,PyObject_ClearManagedDict()} like this:

@example
PyObject_ClearManagedDict((PyObject*)self);
@end example

Pythonのガベージコレクションの仕組みについての詳細は、 @ref{5656,,循環参照ガベージコレクションをサポートする} にあります。

`継承:'

Group: @ref{981,,Py_TPFLAGS_HAVE_GC}, @ref{982,,tp_traverse}, @ref{4ee2,,tp_clear}

This field is inherited by subtypes together with @ref{982,,tp_traverse} and the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag bit: the flag bit, @ref{982,,tp_traverse}, and
@ref{4ee2,,tp_clear} are all inherited from the base type if they are all zero in
the subtype.


@subsubheading 参考


@ref{55df,,Object Life Cycle} for details about how this slot relates to other slots.

@end deffn

@geindex PyTypeObject.tp_richcompare (C member)
@anchor{c-api/typeobj c PyTypeObject tp_richcompare}@anchor{4ef0}
@deffn {C のメンバ変数} @ref{51b3,,richcmpfunc} @ref{c9c,,PyTypeObject}.tp_richcompare

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_richcompare} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_richcompare (C macro)
@anchor{c-api/typeobj c Py_tp_richcompare}@anchor{5199}

オプションのポインタで、拡張比較関数を指します。シグネチャは次の通りです:

@example
PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);
@end example

The first parameter is guaranteed to be an instance of the type
that is defined by @ref{c9c,,PyTypeObject}.

この関数は、比較結果を返すべきです。(普通は @code{Py_True} か @code{Py_False} です。) 比較が未定義の場合は、@code{Py_NotImplemented} を、それ以外のエラーが発生した場合には例外状態をセットして @code{NULL} を返さなければなりません。

@ref{4ef0,,tp_richcompare} および @ref{4ef1,,PyObject_RichCompare()} 関数の第三引数に使うための定数としては以下が定義されています:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

定数

@tab

比較

@item

@geindex Py_LT (C macro)
@anchor{c-api/typeobj c Py_LT}@anchor{5289}
@deffn {C のマクロ} Py_LT
@end deffn

@tab

@code{<}

@item

@geindex Py_LE (C macro)
@anchor{c-api/typeobj c Py_LE}@anchor{528a}
@deffn {C のマクロ} Py_LE
@end deffn

@tab

@code{<=}

@item

@geindex Py_EQ (C macro)
@anchor{c-api/typeobj c Py_EQ}@anchor{528b}
@deffn {C のマクロ} Py_EQ
@end deffn

@tab

@code{==}

@item

@geindex Py_NE (C macro)
@anchor{c-api/typeobj c Py_NE}@anchor{528c}
@deffn {C のマクロ} Py_NE
@end deffn

@tab

@code{!=}

@item

@geindex Py_GT (C macro)
@anchor{c-api/typeobj c Py_GT}@anchor{528d}
@deffn {C のマクロ} Py_GT
@end deffn

@tab

@code{>}

@item

@geindex Py_GE (C macro)
@anchor{c-api/typeobj c Py_GE}@anchor{528e}
@deffn {C のマクロ} Py_GE
@end deffn

@tab

@code{>=}

@end multitable


拡張比較関数(rich comparison functions)を簡単に記述するためのマクロが定義されています:

@geindex Py_RETURN_RICHCOMPARE (C macro)
@anchor{c-api/typeobj c Py_RETURN_RICHCOMPARE}@anchor{dad}
@deffn {C のマクロ} Py_RETURN_RICHCOMPARE (VAL_A, VAL_B, op)

比較した結果に応じて @code{Py_True} か @code{Py_False} を返します。
VAL_A と VAL_B は C の比較演算によって順序付け可能でなければなりません（例えばこれらは C言語の整数か浮動小数点数になるでしょう）。三番目の引数には @ref{4ef1,,PyObject_RichCompare()} と同様に要求された演算を指定します。

The returned value is a new @ref{5e2,,strong reference}.

エラー時には例外を設定して、関数から @code{NULL} でリターンします。


Added in version 3.7.

@end deffn

`継承:'

Group: @ref{4ef6,,tp_hash}, @ref{4ef0,,tp_richcompare}

このフィールドは @ref{4ef6,,tp_hash} と共にサブタイプに継承されます: すなわち、サブタイプの @ref{4ef0,,tp_richcompare} および @ref{4ef6,,tp_hash} が両方とも @code{NULL} のとき、サブタイプは基底タイプから @ref{4ef0,,tp_richcompare} と @ref{4ef6,,tp_hash} を両方とも継承します。

`デフォルト'

@ref{4f75,,PyBaseObject_Type} provides a @ref{4ef0,,tp_richcompare}
implementation, which may be inherited.  However, if only
@ref{4ef6,,tp_hash} is defined, not even the inherited function is used
and instances of the type will not be able to participate in any
comparisons.
@end deffn

@geindex PyTypeObject.tp_weaklistoffset (C member)
@anchor{c-api/typeobj c PyTypeObject tp_weaklistoffset}@anchor{b7f}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} @ref{c9c,,PyTypeObject}.tp_weaklistoffset

While this field is still supported, @ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF}
should be used instead, if at all possible.

型のインスタンスが弱参照可能な場合、このフィールドはゼロよりも大きな数になり、インスタンス構造体における弱参照リストの先頭を示すオフセットが入ります (GC ヘッダがある場合には無視します); このオフセット値は @ref{796,,PyObject_ClearWeakRefs()} および @code{PyWeakref_*} 関数が利用します。インスタンス構造体には、 @code{NULL} に初期化された @ref{5df,,PyObject}* 型のフィールドが入っていなければなりません。

このフィールドを @ref{52f0,,tp_weaklist} と混同しないようにしてください; これは型オブジェクト自身への弱参照からなるリストの先頭です。

It is an error to set both the @ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF} bit and
@ref{b7f,,tp_weaklistoffset}.

`継承:'

このフィールドはサブタイプに継承されますが、以下の規則を読んでください。サブタイプはこのオフセット値をオーバライドすることがあります; 従って、サブタイプでは弱参照リストの先頭が基底タイプとは異なる場合があります。リストの先頭は常に @ref{b7f,,tp_weaklistoffset} で分かるはずなので、このことは問題にはならないはずです。

`デフォルト'

If the @ref{77c,,Py_TPFLAGS_MANAGED_WEAKREF} bit is set in the
@ref{1c71,,tp_flags} field, then
@ref{b7f,,tp_weaklistoffset} will be set to a negative value,
to indicate that it is unsafe to use this field.
@end deffn

@geindex PyTypeObject.tp_iter (C member)
@anchor{c-api/typeobj c PyTypeObject tp_iter}@anchor{1708}
@deffn {C のメンバ変数} @ref{51a7,,getiterfunc} @ref{c9c,,PyTypeObject}.tp_iter

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_iter} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_iter (C macro)
@anchor{c-api/typeobj c Py_tp_iter}@anchor{5193}

オプションの変数で、そのオブジェクトの @ref{4c8,,イテレータ} を返す関数へのポインタです。この値が存在することは、通常この型のインスタンスが @ref{12f1,,イテレート可能} であることを示しています (しかし、シーケンスはこの関数がなくてもイテレート可能です)。

この関数は @ref{5092,,PyObject_GetIter()} と同じシグネチャを持っています:

@example
PyObject *tp_iter(PyObject *self);
@end example

`継承:'

サブタイプはこのフィールドを継承します。
@end deffn

@geindex PyTypeObject.tp_iternext (C member)
@anchor{c-api/typeobj c PyTypeObject tp_iternext}@anchor{1709}
@deffn {C のメンバ変数} @ref{51ac,,iternextfunc} @ref{c9c,,PyTypeObject}.tp_iternext

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_iternext} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_iternext (C macro)
@anchor{c-api/typeobj c Py_tp_iternext}@anchor{5194}

オプションのポインタで、@ref{4c8,,イテレーター} の次の要素を返す関数を指します。シグネチャは次の通りです:

@example
PyObject *tp_iternext(PyObject *self);
@end example

イテレータの要素がなくなると、この関数は @code{NULL} を返さなければなりません。 @ref{df5,,StopIteration} 例外は設定してもしなくても良いです。その他のエラーが発生したときも、 @code{NULL} を返さなければなりません。このフィールドがあると、この型のインスタンスがイテレータであることを示します。

イテレータ型では、 @ref{1708,,tp_iter} 関数も定義されていなければならず、その関数は (新たなイテレータインスタンスではなく) イテレータインスタンス自体を返さねばなりません。

この関数のシグネチャは @ref{399,,PyIter_Next()} と同じです。

`継承:'

サブタイプはこのフィールドを継承します。
@end deffn

@geindex PyTypeObject.tp_methods (C member)
@anchor{c-api/typeobj c PyTypeObject tp_methods}@anchor{4ed4}
@deffn {C のメンバ変数} struct @ref{16f0,,PyMethodDef} *@ref{c9c,,PyTypeObject}.tp_methods

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_methods} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_methods (C macro)
@anchor{c-api/typeobj c Py_tp_methods}@anchor{5196}

オプションのポインタで、この型の正規 (regular) のメソッドを宣言している @ref{16f0,,PyMethodDef} 構造体からなる、 @code{NULL} で終端された静的な配列を指します。

配列の各要素ごとに、メソッドデスクリプタの入った、要素が型の辞書 (下記の @ref{1a8c,,tp_dict} 参照) に追加されます。

`継承:'

サブタイプはこのフィールドを継承しません (メソッドは別個のメカニズムで継承されています)。
@end deffn

@geindex PyTypeObject.tp_members (C member)
@anchor{c-api/typeobj c PyTypeObject tp_members}@anchor{4ed2}
@deffn {C のメンバ変数} struct @ref{771,,PyMemberDef} *@ref{c9c,,PyTypeObject}.tp_members

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_members} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_members (C macro)
@anchor{c-api/typeobj c Py_tp_members}@anchor{5195}

オプションのポインタで、型の正規 (regular) のデータメンバ (フィールドおよびスロット) を宣言している @ref{771,,PyMemberDef} 構造体からなる、 @code{NULL} で終端された静的な配列を指します。

配列の各要素ごとに、メンバデスクリプタの入った要素が型の辞書 (下記の @ref{1a8c,,tp_dict} 参照) に追加されます。

`継承:'

サブタイプはこのフィールドを継承しません (メンバは別個のメカニズムで継承されています)。
@end deffn

@geindex PyTypeObject.tp_getset (C member)
@anchor{c-api/typeobj c PyTypeObject tp_getset}@anchor{4ed7}
@deffn {C のメンバ変数} struct @ref{db2,,PyGetSetDef} *@ref{c9c,,PyTypeObject}.tp_getset

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_getset} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_getset (C macro)
@anchor{c-api/typeobj c Py_tp_getset}@anchor{518f}

オプションのポインタで、インスタンスの算出属性 (computed attribute) を宣言している @ref{db2,,PyGetSetDef} 構造体からなる、 @code{NULL} で終端された静的な配列を指します。

配列の各要素ごとに、 getter/setter デスクリプタの入った、要素が型の辞書 (下記の @ref{1a8c,,tp_dict} 参照) に追加されます。

`継承:'

サブタイプはこのフィールドを継承しません (算出属性は別個のメカニズムで継承されています)。
@end deffn

@geindex PyTypeObject.tp_base (C member)
@anchor{c-api/typeobj c PyTypeObject tp_base}@anchor{2375}
@deffn {C のメンバ変数} @ref{c9c,,PyTypeObject} *@ref{c9c,,PyTypeObject}.tp_base

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_base} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_base (C macro)
@anchor{c-api/typeobj c Py_tp_base}@anchor{5182}

オプションのポインタで、型に関するプロパティを継承する基底タイプを指します。このフィールドのレベルでは、単継承 (single inheritance) だけがサポートされています; 多重継承はメタタイプの呼び出しによる動的な型オブジェクトの生成を必要とします。

@cartouche
@quotation 注釈 
@c from Modules/xxmodule.c

Slot initialization is subject to the rules of initializing globals.
C99 requires the initializers to be "address constants".  Function
designators like @ref{4ecc,,PyType_GenericNew()}, with implicit conversion
to a pointer, are valid C99 address constants.

However, the unary '&' operator applied to a non-static variable
like @ref{4f75,,PyBaseObject_Type} is not required to produce an address
constant.  Compilers may support this (gcc does), MSVC does not.
Both compilers are strictly standard conforming in this particular
behavior.

Consequently, @ref{2375,,tp_base} should be set in
the extension module's init function.
@end quotation
@end cartouche

`継承:'

(当たり前ですが) サブタイプはこのフィールドを継承しません。

`デフォルト'

このフィールドのデフォルト値は (Python プログラマは @ref{c7e,,object} 型として知っている) @code{&PyBaseObject_Type} になります。
@end deffn

@geindex PyTypeObject.tp_dict (C member)
@anchor{c-api/typeobj c PyTypeObject tp_dict}@anchor{1a8c}
@deffn {C のメンバ変数} @ref{5df,,PyObject} *@ref{c9c,,PyTypeObject}.tp_dict

型の辞書は @ref{980,,PyType_Ready()} によってこのフィールドに収められます。

This field should normally be initialized to @code{NULL} before PyType_Ready is
called; it may also be initialized to a dictionary containing initial attributes
for the type.  Once @ref{980,,PyType_Ready()} has initialized the type, extra
attributes for the type may be added to this dictionary only if they don't
correspond to overloaded operations (like @ref{23dd,,__add__()}).  Once
initialization for the type has finished, this field should be
treated as read-only.

Some types may not store their dictionary in this slot.
Use @ref{1a8b,,PyType_GetDict()} to retrieve the dictionary for an arbitrary
type.


バージョン 3.12 で変更: Internals detail: For static builtin types, this is always @code{NULL}.
Instead, the dict for such types is stored on @code{PyInterpreterState}.
Use @ref{1a8b,,PyType_GetDict()} to get the dict for an arbitrary type.


`継承:'

サブタイプはこのフィールドを継承しません (が、この辞書内で定義されている属性は異なるメカニズムで継承されます)。

`デフォルト'

If this field is @code{NULL}, @ref{980,,PyType_Ready()} will assign a new
dictionary to it.

@cartouche
@quotation 警告 
@ref{1a8c,,tp_dict} に @ref{4eb9,,PyDict_SetItem()} を使ったり、辞書 C-API で編集するのは安全ではありません。
@end quotation
@end cartouche
@end deffn

@geindex PyTypeObject.tp_descr_get (C member)
@anchor{c-api/typeobj c PyTypeObject tp_descr_get}@anchor{5616}
@deffn {C のメンバ変数} @ref{51a1,,descrgetfunc} @ref{c9c,,PyTypeObject}.tp_descr_get

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_descr_get} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_descr_get (C macro)
@anchor{c-api/typeobj c Py_tp_descr_get}@anchor{5188}

オプションのポインタで、デスクリプタの get 関数を指します。

関数のシグネチャは次のとおりです

@example
PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
@end example

@c XXX explain more?

`継承:'

サブタイプはこのフィールドを継承します。
@end deffn

@geindex PyTypeObject.tp_descr_set (C member)
@anchor{c-api/typeobj c PyTypeObject tp_descr_set}@anchor{1cb4}
@deffn {C のメンバ変数} @ref{51a2,,descrsetfunc} @ref{c9c,,PyTypeObject}.tp_descr_set

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_descr_set} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_descr_set (C macro)
@anchor{c-api/typeobj c Py_tp_descr_set}@anchor{5189}

オプションのポインタで、デスクリプタの値の設定と削除を行う関数を指します。

関数のシグネチャは次のとおりです

@example
int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
@end example

値を削除するには、`value' 引数に @code{NULL} を設定します。

@c XXX explain more?

`継承:'

サブタイプはこのフィールドを継承します。
@end deffn

@geindex PyTypeObject.tp_dictoffset (C member)
@anchor{c-api/typeobj c PyTypeObject tp_dictoffset}@anchor{52ec}
@deffn {C のメンバ変数} @ref{c55,,Py_ssize_t} @ref{c9c,,PyTypeObject}.tp_dictoffset

While this field is still supported, @ref{60f,,Py_TPFLAGS_MANAGED_DICT} should be
used instead, if at all possible.

型のインスタンスにインスタンス変数の入った辞書がある場合、このフィールドは非ゼロの値になり、型のインスタンスデータ構造体におけるインスタンス変数辞書へのオフセットが入ります; このオフセット値は @ref{508e,,PyObject_GenericGetAttr()} が使います。

このフィールドを @ref{1a8c,,tp_dict} と混同しないようにしてください; これは型オブジェクト自身の属性の辞書です。

The value specifies the offset of the dictionary from the start of the instance structure.

The @ref{52ec,,tp_dictoffset} should be regarded as write-only.
To get the pointer to the dictionary call @ref{1d05,,PyObject_GenericGetDict()}.
Calling @ref{1d05,,PyObject_GenericGetDict()} may need to allocate memory for the
dictionary, so it is may be more efficient to call @ref{5ee,,PyObject_GetAttr()}
when accessing an attribute on the object.

It is an error to set both the @ref{60f,,Py_TPFLAGS_MANAGED_DICT} bit and
@ref{52ec,,tp_dictoffset}.

`継承:'

This field is inherited by subtypes. A subtype should not override this offset;
doing so could be unsafe, if C code tries to access the dictionary at the
previous offset.
To properly support inheritance, use @ref{60f,,Py_TPFLAGS_MANAGED_DICT}.

`デフォルト'

This slot has no default.  For @ref{983,,static types}, if the
field is @code{NULL} then no @ref{77d,,__dict__} gets created for instances.

If the @ref{60f,,Py_TPFLAGS_MANAGED_DICT} bit is set in the
@ref{1c71,,tp_flags} field, then
@ref{52ec,,tp_dictoffset} will be set to @code{-1}, to indicate
that it is unsafe to use this field.
@end deffn

@geindex PyTypeObject.tp_init (C member)
@anchor{c-api/typeobj c PyTypeObject tp_init}@anchor{7a1}
@deffn {C のメンバ変数} @ref{51aa,,initproc} @ref{c9c,,PyTypeObject}.tp_init

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_init} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_init (C macro)
@anchor{c-api/typeobj c Py_tp_init}@anchor{5191}

オプションのポインタで、インスタンス初期化関数を指します。

This function corresponds to the @ref{8bf,,__init__()} method of classes.  Like
@code{__init__()}, it is possible to create an instance without calling
@code{__init__()}, and it is possible to reinitialize an instance by calling its
@code{__init__()} method again.

関数のシグネチャは次のとおりです

@example
int tp_init(PyObject *self, PyObject *args, PyObject *kwds);
@end example

The self argument is the instance to be initialized; the `args' and `kwds'
arguments represent positional and keyword arguments of the call to
@ref{8bf,,__init__()}.

@ref{7a1,,tp_init} 関数のフィールドが @code{NULL} でない場合、通常の型を呼び出す方法のインスタンス生成において、型の @ref{79f,,tp_new} 関数がインスタンスを返した後に呼び出されます。 @ref{79f,,tp_new} が元の型のサブタイプでない別の型を返す場合、 @ref{7a1,,tp_init} は全く呼び出されません; @ref{79f,,tp_new} が元の型のサブタイプのインスタンスを返す場合、サブタイプの @ref{7a1,,tp_init} が呼び出されます。

成功のときには @code{0} を、エラー時には例外をセットして @code{-1} を返します。

`継承:'

サブタイプはこのフィールドを継承します。

`デフォルト'

For @ref{983,,static types} this field does not have a default.
@end deffn

@geindex PyTypeObject.tp_alloc (C member)
@anchor{c-api/typeobj c PyTypeObject tp_alloc}@anchor{4ed0}
@deffn {C のメンバ変数} @ref{519f,,allocfunc} @ref{c9c,,PyTypeObject}.tp_alloc

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_alloc} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_alloc (C macro)
@anchor{c-api/typeobj c Py_tp_alloc}@anchor{5181}

オプションのポインタで、インスタンスのメモリ確保関数を指します。

関数のシグネチャは次のとおりです

@example
PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);
@end example

`継承:'

Static subtypes inherit this slot, which will be
@ref{c61,,PyType_GenericAlloc()} if inherited from @ref{c7e,,object}.

@ref{b5e,,Heap subtypes} do not inherit this slot.

`デフォルト'

For heap subtypes, this field is always set to
@ref{c61,,PyType_GenericAlloc()}.

For static subtypes, this slot is inherited (see above).
@end deffn

@geindex PyTypeObject.tp_new (C member)
@anchor{c-api/typeobj c PyTypeObject tp_new}@anchor{79f}
@deffn {C のメンバ変数} @ref{51ae,,newfunc} @ref{c9c,,PyTypeObject}.tp_new

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_new} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_new (C macro)
@anchor{c-api/typeobj c Py_tp_new}@anchor{5197}

オプションのポインタで、インスタンス生成関数を指します。

関数のシグネチャは次のとおりです

@example
PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);
@end example

`subtype' 引数は生成するオブジェクトの型です; `args' および `kwds' 引数は、型を呼び出すときの位置引数およびキーワード引数です。`subtype' は @ref{79f,,tp_new} 関数を呼び出すときに使う型と同じである必要はないことに注意してください; その型の (無関係ではない) サブタイプのこともあります。

@ref{79f,,tp_new} 関数は @code{subtype->tp_alloc(subtype, nitems)} を呼び出してオブジェクトのメモリ領域を確保し、初期化で絶対に必要とされる処理だけを行います。省略したり繰り返したりしても問題のない初期化処理は @ref{7a1,,tp_init} ハンドラ内に配置しなければなりません。だいたいの目安としては、変更不能な型では初期化は全て @ref{79f,,tp_new} で行い、一方、変更可能な型ではほとんどの初期化を @ref{7a1,,tp_init} に回すべきです。

Set the @ref{7a2,,Py_TPFLAGS_DISALLOW_INSTANTIATION} flag to disallow creating
instances of the type in Python.

`継承:'

サブタイプはこのフィールドを継承します。例外として、  @ref{2375,,tp_base} が @code{NULL} か @code{&PyBaseObject_Type} になっている @ref{983,,静的な型} では継承しません。

`デフォルト'

For @ref{983,,static types} this field has no default.
This means if the slot is defined as @code{NULL}, the type cannot be called
to create new instances; presumably there is some other way to create
instances, like a factory function.
@end deffn

@geindex PyTypeObject.tp_free (C member)
@anchor{c-api/typeobj c PyTypeObject tp_free}@anchor{4ecf}
@deffn {C のメンバ変数} @ref{5449,,freefunc} @ref{c9c,,PyTypeObject}.tp_free

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_free} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_free (C macro)
@anchor{c-api/typeobj c Py_tp_free}@anchor{518c}

オプションのポインタで、インスタンスのメモリ解放関数を指します。シグネチャは以下の通りです:

@example
void tp_free(void *self);
@end example

This function must free the memory allocated by
@ref{4ed0,,tp_alloc}.

`継承:'

Static subtypes inherit this slot, which will be @ref{e60,,PyObject_Free()} if
inherited from @ref{c7e,,object}.  Exception: If the type supports garbage
collection (i.e., the @ref{981,,Py_TPFLAGS_HAVE_GC} flag is set in
@ref{1c71,,tp_flags}) and it would inherit
@ref{e60,,PyObject_Free()}, then this slot is not inherited but instead defaults
to @ref{171c,,PyObject_GC_Del()}.

@ref{b5e,,Heap subtypes} do not inherit this slot.

`デフォルト'

For @ref{b5e,,heap subtypes}, this slot defaults to a deallocator suitable to match
@ref{c61,,PyType_GenericAlloc()} and the value of the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag.

For static subtypes, this slot is inherited (see above).
@end deffn

@geindex PyTypeObject.tp_is_gc (C member)
@anchor{c-api/typeobj c PyTypeObject tp_is_gc}@anchor{5617}
@deffn {C のメンバ変数} @ref{51ab,,inquiry} @ref{c9c,,PyTypeObject}.tp_is_gc

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_is_gc} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_is_gc (C macro)
@anchor{c-api/typeobj c Py_tp_is_gc}@anchor{5192}

オプションのポインタで、ガベージコレクタから呼び出される関数を指します。

The garbage collector needs to know whether a particular object is collectible
or not.  Normally, it is sufficient to look at the object's type's
@ref{1c71,,tp_flags} field, and check the @ref{981,,Py_TPFLAGS_HAVE_GC} flag bit.  But
some types have a mixture of statically and dynamically allocated instances, and
the statically allocated instances are not collectible.  Such types should
define this function; it should return @code{1} for a collectible instance, and
@code{0} for a non-collectible instance. The signature is:

@example
int tp_is_gc(PyObject *self);
@end example

(上記のような型の例は、型オブジェクト自体です。メタタイプ @ref{76f,,PyType_Type} は、型のメモリ確保が静的か @ref{b5e,,動的} かを区別するためにこの関数を定義しています。)

`継承:'

サブタイプはこのフィールドを継承します。

`デフォルト'

This slot has no default.  If this field is @code{NULL},
@ref{981,,Py_TPFLAGS_HAVE_GC} is used as the functional equivalent.
@end deffn

@geindex PyTypeObject.tp_bases (C member)
@anchor{c-api/typeobj c PyTypeObject tp_bases}@anchor{5618}
@deffn {C のメンバ変数} @ref{5df,,PyObject} *@ref{c9c,,PyTypeObject}.tp_bases

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_bases} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_bases (C macro)
@anchor{c-api/typeobj c Py_tp_bases}@anchor{5183}

基底型からなるタプルです。

This field should be set to @code{NULL} and treated as read-only.
Python will fill it in when the type is @ref{980,,initialized}.

For dynamically created classes, the @ref{5183,,Py_tp_bases}
@ref{50dc,,slot} can be used instead of the `bases' argument
of @ref{79e,,PyType_FromSpecWithBases()}.
The argument form is preferred.

@cartouche
@quotation 警告 
Multiple inheritance does not work well for statically defined types.
If you set @code{tp_bases} to a tuple, Python will not raise an error,
but some slots will only be inherited from the first base.
@end quotation
@end cartouche

`継承:'

このフィールドは継承されません。
@end deffn

@geindex PyTypeObject.tp_mro (C member)
@anchor{c-api/typeobj c PyTypeObject tp_mro}@anchor{52ee}
@deffn {C のメンバ変数} @ref{5df,,PyObject} *@ref{c9c,,PyTypeObject}.tp_mro

基底タイプ群を展開した集合が入っているタプルです。集合は該当する型自体からはじまり、 @ref{c7e,,object} で終わります。メソッド解決順序 (Method Resolution Order) に従って並んでいます。

This field should be set to @code{NULL} and treated as read-only.
Python will fill it in when the type is @ref{980,,initialized}.

`継承:'

このフィールドは継承されません; フィールドの値は @ref{980,,PyType_Ready()} で毎回計算されます。
@end deffn

@geindex PyTypeObject.tp_cache (C member)
@anchor{c-api/typeobj c PyTypeObject tp_cache}@anchor{52ef}
@deffn {C のメンバ変数} @ref{5df,,PyObject} *@ref{c9c,,PyTypeObject}.tp_cache

未使用のフィールドです。内部でのみ利用されます。

`継承:'

このフィールドは継承されません。
@end deffn

@geindex PyTypeObject.tp_subclasses (C member)
@anchor{c-api/typeobj c PyTypeObject tp_subclasses}@anchor{792}
@deffn {C のメンバ変数} void *@ref{c9c,,PyTypeObject}.tp_subclasses

A collection of subclasses.  Internal use only.  May be an invalid pointer.

To get a list of subclasses, call the Python method
@ref{793,,__subclasses__()}.


バージョン 3.12 で変更: For some types, this field does not hold a valid @ref{5df,,PyObject}*.
The type was changed to void* to indicate this.


`継承:'

このフィールドは継承されません。
@end deffn

@geindex PyTypeObject.tp_weaklist (C member)
@anchor{c-api/typeobj c PyTypeObject tp_weaklist}@anchor{52f0}
@deffn {C のメンバ変数} @ref{5df,,PyObject} *@ref{c9c,,PyTypeObject}.tp_weaklist

この型オブジェクトに対する弱参照からなるリストの先頭です。


バージョン 3.12 で変更: Internals detail: For the static builtin types this is always @code{NULL},
even if weakrefs are added.  Instead, the weakrefs for each are stored
on @code{PyInterpreterState}.  Use the public C-API or the internal
@code{_PyObject_GET_WEAKREFS_LISTPTR()} macro to avoid the distinction.


`継承:'

このフィールドは継承されません。
@end deffn

@geindex PyTypeObject.tp_del (C member)
@anchor{c-api/typeobj c PyTypeObject tp_del}@anchor{5619}
@deffn {C のメンバ変数} @ref{51a3,,destructor} @ref{c9c,,PyTypeObject}.tp_del

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_del} is part of the @ref{775,,Stable ABI}.'
@geindex Py_tp_del (C macro)
@anchor{c-api/typeobj c Py_tp_del}@anchor{5187}

このフィールドは廃止されました。@ref{c9d,,tp_finalize} を代わりに利用してください。
@end deffn

@geindex PyTypeObject.tp_version_tag (C member)
@anchor{c-api/typeobj c PyTypeObject tp_version_tag}@anchor{561a}
@deffn {C のメンバ変数} unsigned int @ref{c9c,,PyTypeObject}.tp_version_tag

メソッドキャッシュへのインデックスとして使われます。内部使用だけのための関数です。

`継承:'

このフィールドは継承されません。
@end deffn

@geindex PyTypeObject.tp_finalize (C member)
@anchor{c-api/typeobj c PyTypeObject tp_finalize}@anchor{c9d}
@deffn {C のメンバ変数} @ref{51a3,,destructor} @ref{c9c,,PyTypeObject}.tp_finalize

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_finalize} is part of the @ref{775,,Stable ABI} (バージョン 3.5 より).'
@geindex Py_tp_finalize (C macro)
@anchor{c-api/typeobj c Py_tp_finalize}@anchor{518b}

An optional pointer to an instance finalization function.  This is the C
implementation of the @ref{11ff,,__del__()} special method.  Its signature
is:

@example
void tp_finalize(PyObject *self);
@end example

The primary purpose of finalization is to perform any non-trivial cleanup
that must be performed before the object is destroyed, while the object and
any other objects it directly or indirectly references are still in a
consistent state.  The finalizer is allowed to execute
arbitrary Python code.

Before Python automatically finalizes an object, some of the object's direct
or indirect referents might have themselves been automatically finalized.
However, none of the referents will have been automatically cleared
(@ref{4ee2,,tp_clear}) yet.

Other non-finalized objects might still be using a finalized object, so the
finalizer must leave the object in a sane state (e.g., invariants are still
met).

@cartouche
@quotation 注釈 
After Python automatically finalizes an object, Python might start
automatically clearing (@ref{4ee2,,tp_clear}) the object
and its referents (direct and indirect).  Cleared objects are not
guaranteed to be in a consistent state; a finalized object must be able
to tolerate cleared referents.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
An object is not guaranteed to be automatically finalized before its
destructor (@ref{4ebc,,tp_dealloc}) is called.  It is
recommended to call @ref{55e3,,PyObject_CallFinalizerFromDealloc()} at the
beginning of @code{tp_dealloc} to guarantee that the object is
always finalized before destruction.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
The @ref{c9d,,tp_finalize} function can be called from any
thread, although the @ref{164,,GIL} will be held.
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
The @code{tp_finalize} function can be called during shutdown,
after some global variables have been deleted.  See the documentation of
the @ref{11ff,,__del__()} method for details.
@end quotation
@end cartouche

When Python finalizes an object, it behaves like the following algorithm:


@enumerate 

@item 
Python might mark the object as `finalized'.  Currently, Python always
marks objects whose type supports garbage collection (i.e., the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag is set in
@ref{1c71,,tp_flags}) and never marks other types of
objects; this might change in a future version.

@item 
If the object is not marked as `finalized' and its
@code{tp_finalize} finalizer function is non-@code{NULL}, the
finalizer function is called.

@item 
If the finalizer function was called and the finalizer made the object
reachable (i.e., there is a reference to the object and it is not a
member of a @ref{55e4,,cyclic isolate}), then the finalizer is said to have
`resurrected' the object.  It is unspecified whether the finalizer can
also resurrect the object by adding a new reference to the object that
does not make it reachable, i.e., the object is (still) a member of a
cyclic isolate.

@item 
If the finalizer resurrected the object, the object's pending destruction
is canceled and the object's `finalized' mark might be removed if
present.  Currently, Python never removes the `finalized' mark; this
might change in a future version.
@end enumerate

`Automatic finalization' refers to any finalization performed by Python
except via calls to @ref{55e7,,PyObject_CallFinalizer()} or
@ref{55e3,,PyObject_CallFinalizerFromDealloc()}.  No guarantees are made about
when, if, or how often an object is automatically finalized, except:


@itemize *

@item 
Python will not automatically finalize an object if it is reachable, i.e.,
there is a reference to it and it is not a member of a @ref{55e4,,cyclic isolate}.

@item 
Python will not automatically finalize an object if finalizing it would
not mark the object as `finalized'.  Currently, this applies to objects
whose type does not support garbage collection, i.e., the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag is not set.  Such objects can still be
manually finalized by calling @ref{55e7,,PyObject_CallFinalizer()} or
@ref{55e3,,PyObject_CallFinalizerFromDealloc()}.

@item 
Python will not automatically finalize any two members of a @ref{55e4,,cyclic isolate} concurrently.

@item 
Python will not automatically finalize an object after it has
automatically cleared (@ref{4ee2,,tp_clear}) the object.

@item 
If an object is a member of a @ref{55e4,,cyclic isolate}, Python will not
automatically finalize it after automatically clearing (see
@ref{4ee2,,tp_clear}) any other member.

@item 
Python will automatically finalize every member of a @ref{55e4,,cyclic isolate} before it automatically clears (see
@ref{4ee2,,tp_clear}) any of them.

@item 
If Python is going to automatically clear an object
(@ref{4ee2,,tp_clear}), it will automatically finalize the
object first.
@end itemize

Python currently only automatically finalizes objects that are members of a
@ref{55e4,,cyclic isolate}, but future versions might finalize objects regularly
before their destruction.

To manually finalize an object, do not call this function directly; call
@ref{55e7,,PyObject_CallFinalizer()} or
@ref{55e3,,PyObject_CallFinalizerFromDealloc()} instead.

@ref{c9d,,tp_finalize} should leave the current exception
status unchanged.  The recommended way to write a non-trivial finalizer is
to back up the exception at the beginning by calling
@ref{429,,PyErr_GetRaisedException()} and restore the exception at the end by
calling @ref{42c,,PyErr_SetRaisedException()}.  If an exception is encountered
in the middle of the finalizer, log and clear it with
@ref{5f2,,PyErr_WriteUnraisable()} or @ref{5f1,,PyErr_FormatUnraisable()}.  For
example:

@example
static void
foo_finalize(PyObject *self)
@{
    // Save the current exception, if any.
    PyObject *exc = PyErr_GetRaisedException();

    // ...

    if (do_something_that_might_raise() != success_indicator) @{
        PyErr_WriteUnraisable(self);
        goto done;
    @}

done:
    // Restore the saved exception.  This silently discards any exception
    // raised above, so be sure to call PyErr_WriteUnraisable first if
    // necessary.
    PyErr_SetRaisedException(exc);
@}
@end example

`継承:'

サブタイプはこのフィールドを継承します。


Added in version 3.4.



バージョン 3.8 で変更: Before version 3.8 it was necessary to set the
@ref{427,,Py_TPFLAGS_HAVE_FINALIZE} flags bit in order for this field to be
used.  This is no longer required.



@subsubheading 参考



@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 442
PEP 442@footnote{https://peps.python.org/pep-0442/}: "Safe object finalization"

@item 
@ref{55df,,Object Life Cycle} for details about how this slot relates to other
slots.

@item 
@ref{55e7,,PyObject_CallFinalizer()}

@item 
@ref{55e3,,PyObject_CallFinalizerFromDealloc()}
@end itemize

@end deffn

@geindex PyTypeObject.tp_vectorcall (C member)
@anchor{c-api/typeobj c PyTypeObject tp_vectorcall}@anchor{198a}
@deffn {C のメンバ変数} @ref{779,,vectorcallfunc} @ref{c9c,,PyTypeObject}.tp_vectorcall

` The corresponding @ref{50dc,,slot ID} @code{Py_tp_vectorcall} is part of the @ref{775,,Stable ABI} (バージョン 3.14 より).'
@geindex Py_tp_vectorcall (C macro)
@anchor{c-api/typeobj c Py_tp_vectorcall}@anchor{519e}

A @ref{774,,vectorcall function} to use for calls of this type
object (rather than instances).
In other words, @code{tp_vectorcall} can be used to optimize @code{type.__call__},
which typically returns a new instance of `type'.

As with any vectorcall function, if @code{tp_vectorcall} is @code{NULL},
the `tp_call' protocol (@code{Py_TYPE(type)->tp_call}) is used instead.

@cartouche
@quotation 注釈 
The @ref{774,,vectorcall protocol} requires that the vectorcall
function has the same behavior as the corresponding @code{tp_call}.
This means that @code{type->tp_vectorcall} must match the behavior of
@code{Py_TYPE(type)->tp_call}.

Specifically, if `type' uses the default metaclass,
@code{type->tp_vectorcall} must behave the same as
@ref{76f,,PyType_Type}->tp_call, which:


@itemize -

@item 
calls @code{type->tp_new},

@item 
if the result is a subclass of `type', calls @code{type->tp_init}
on the result of @code{tp_new}, and

@item 
returns the result of @code{tp_new}.
@end itemize

Typically, @code{tp_vectorcall} is overridden to optimize this process
for specific @ref{79f,,tp_new} and
@ref{7a1,,tp_init}.
When doing this for user-subclassable types, note that both can be
overridden (using @ref{7a0,,__new__()} and
@ref{8bf,,__init__()}, respectively).
@end quotation
@end cartouche

`継承:'

このフィールドは決して継承されません。


Added in version 3.9: （このフィールドは3.8から存在していますが、3.9以降でしか利用できません）

@end deffn

@geindex PyTypeObject.tp_watched (C member)
@anchor{c-api/typeobj c PyTypeObject tp_watched}@anchor{561b}
@deffn {C のメンバ変数} unsigned char @ref{c9c,,PyTypeObject}.tp_watched

Internal. Do not use.


Added in version 3.12.

@end deffn

@node Static Types,Heap Types,PyTypeObject スロット,Type Object Structures
@anchor{c-api/typeobj id4}@anchor{5662}@anchor{c-api/typeobj static-types}@anchor{983}
@subsubsection Static Types


Traditionally, types defined in C code are `static', that is,
a static @ref{c9c,,PyTypeObject} structure is defined directly in code
and initialized using @ref{980,,PyType_Ready()}.

This results in types that are limited relative to types defined in Python:


@itemize *

@item 
Static types are limited to one base, i.e. they cannot use multiple
inheritance.

@item 
Static type objects (but not necessarily their instances) are immutable.
It is not possible to add or modify the type object's attributes from Python.

@item 
Static type objects are shared across
@ref{163,,sub-interpreters}, so they should not
include any subinterpreter-specific state.
@end itemize

Also, since @ref{c9c,,PyTypeObject} is only part of the @ref{637,,Limited API} as an opaque struct, any extension modules using static types must be
compiled for a specific Python minor version.

@node Heap Types,数値オブジェクト構造体,Static Types,Type Object Structures
@anchor{c-api/typeobj heap-types}@anchor{b5e}@anchor{c-api/typeobj id5}@anchor{5663}
@subsubsection Heap Types


An alternative to @ref{983,,static types} is `heap-allocated types',
or `heap types' for short, which correspond closely to classes created by
Python's @code{class} statement. Heap types have the @ref{aac,,Py_TPFLAGS_HEAPTYPE}
flag set.

This is done by filling a @ref{1a89,,PyType_Spec} structure and calling
@ref{79d,,PyType_FromSpec()}, @ref{79e,,PyType_FromSpecWithBases()},
@ref{773,,PyType_FromModuleAndSpec()}, or @ref{772,,PyType_FromMetaclass()}.

@node 数値オブジェクト構造体,マップオブジェクト構造体,Heap Types,Type Object Structures
@anchor{c-api/typeobj number-object-structures}@anchor{5664}@anchor{c-api/typeobj number-structs}@anchor{5653}
@subsubsection 数値オブジェクト構造体


@geindex PyNumberMethods (C type)
@anchor{c-api/typeobj c PyNumberMethods}@anchor{1637}
@deffn {C のデータ型} type PyNumberMethods

この構造体は数値型プロトコルを実装するために使われる関数群へのポインタを保持しています。
以下のそれぞれの関数は @ref{52a1,,数値型プロトコル (number protocol)} で解説されている似た名前の関数から利用されます。

@c XXX Drop the definition?

以下は構造体の定義です:

@example
typedef struct @{
     binaryfunc nb_add;
     binaryfunc nb_subtract;
     binaryfunc nb_multiply;
     binaryfunc nb_remainder;
     binaryfunc nb_divmod;
     ternaryfunc nb_power;
     unaryfunc nb_negative;
     unaryfunc nb_positive;
     unaryfunc nb_absolute;
     inquiry nb_bool;
     unaryfunc nb_invert;
     binaryfunc nb_lshift;
     binaryfunc nb_rshift;
     binaryfunc nb_and;
     binaryfunc nb_xor;
     binaryfunc nb_or;
     unaryfunc nb_int;
     void *nb_reserved;
     unaryfunc nb_float;

     binaryfunc nb_inplace_add;
     binaryfunc nb_inplace_subtract;
     binaryfunc nb_inplace_multiply;
     binaryfunc nb_inplace_remainder;
     ternaryfunc nb_inplace_power;
     binaryfunc nb_inplace_lshift;
     binaryfunc nb_inplace_rshift;
     binaryfunc nb_inplace_and;
     binaryfunc nb_inplace_xor;
     binaryfunc nb_inplace_or;

     binaryfunc nb_floor_divide;
     binaryfunc nb_true_divide;
     binaryfunc nb_inplace_floor_divide;
     binaryfunc nb_inplace_true_divide;

     unaryfunc nb_index;

     binaryfunc nb_matrix_multiply;
     binaryfunc nb_inplace_matrix_multiply;
@} PyNumberMethods;
@end example

@cartouche
@quotation 注釈 
二項関数と三項関数は、すべてのオペランドの型をチェックしなければならず、必要な変換を実装しなければなりません (すくなくともオペランドの一つは定義している型のインスタンスです). もし与えられたオペランドに対して操作が定義されなければ、二項関数と三項関数は @code{Py_NotImplemented} を返さなければならず、他のエラーが起こった場合は、@code{NULL} を返して例外を設定しなければなりません。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
The @ref{563c,,nb_reserved} field should always be @code{NULL}.  It
was previously called @code{nb_long}, and was renamed in
Python 3.0.1.
@end quotation
@end cartouche
@end deffn

@geindex PyNumberMethods.nb_add (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_add}@anchor{52e2}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_add

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_add} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_add (C macro)
@anchor{c-api/typeobj c Py_nb_add}@anchor{5157}
@end deffn

@geindex PyNumberMethods.nb_subtract (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_subtract}@anchor{5623}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_subtract

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_subtract} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_subtract (C macro)
@anchor{c-api/typeobj c Py_nb_subtract}@anchor{5176}
@end deffn

@geindex PyNumberMethods.nb_multiply (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_multiply}@anchor{5625}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_multiply

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_multiply} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_multiply (C macro)
@anchor{c-api/typeobj c Py_nb_multiply}@anchor{516f}
@end deffn

@geindex PyNumberMethods.nb_remainder (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_remainder}@anchor{5627}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_remainder

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_remainder} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_remainder (C macro)
@anchor{c-api/typeobj c Py_nb_remainder}@anchor{5174}
@end deffn

@geindex PyNumberMethods.nb_divmod (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_divmod}@anchor{5629}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_divmod

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_divmod} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_divmod (C macro)
@anchor{c-api/typeobj c Py_nb_divmod}@anchor{515a}
@end deffn

@geindex PyNumberMethods.nb_power (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_power}@anchor{562a}
@deffn {C のメンバ変数} @ref{51b9,,ternaryfunc} @ref{1637,,PyNumberMethods}.nb_power

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_power} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_power (C macro)
@anchor{c-api/typeobj c Py_nb_power}@anchor{5173}
@end deffn

@geindex PyNumberMethods.nb_negative (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_negative}@anchor{562c}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{1637,,PyNumberMethods}.nb_negative

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_negative} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_negative (C macro)
@anchor{c-api/typeobj c Py_nb_negative}@anchor{5170}
@end deffn

@geindex PyNumberMethods.nb_positive (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_positive}@anchor{562d}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{1637,,PyNumberMethods}.nb_positive

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_positive} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_positive (C macro)
@anchor{c-api/typeobj c Py_nb_positive}@anchor{5172}
@end deffn

@geindex PyNumberMethods.nb_absolute (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_absolute}@anchor{562e}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{1637,,PyNumberMethods}.nb_absolute

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_absolute} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_absolute (C macro)
@anchor{c-api/typeobj c Py_nb_absolute}@anchor{5156}
@end deffn

@geindex PyNumberMethods.nb_bool (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_bool}@anchor{562f}
@deffn {C のメンバ変数} @ref{51ab,,inquiry} @ref{1637,,PyNumberMethods}.nb_bool

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_bool} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_bool (C macro)
@anchor{c-api/typeobj c Py_nb_bool}@anchor{5159}
@end deffn

@geindex PyNumberMethods.nb_invert (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_invert}@anchor{5630}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{1637,,PyNumberMethods}.nb_invert

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_invert} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_invert (C macro)
@anchor{c-api/typeobj c Py_nb_invert}@anchor{516c}
@end deffn

@geindex PyNumberMethods.nb_lshift (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_lshift}@anchor{5631}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_lshift

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_lshift} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_lshift (C macro)
@anchor{c-api/typeobj c Py_nb_lshift}@anchor{516d}
@end deffn

@geindex PyNumberMethods.nb_rshift (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_rshift}@anchor{5633}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_rshift

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_rshift} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_rshift (C macro)
@anchor{c-api/typeobj c Py_nb_rshift}@anchor{5175}
@end deffn

@geindex PyNumberMethods.nb_and (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_and}@anchor{5635}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_and

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_and} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_and (C macro)
@anchor{c-api/typeobj c Py_nb_and}@anchor{5158}
@end deffn

@geindex PyNumberMethods.nb_xor (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_xor}@anchor{5637}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_xor

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_xor} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_xor (C macro)
@anchor{c-api/typeobj c Py_nb_xor}@anchor{5178}
@end deffn

@geindex PyNumberMethods.nb_or (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_or}@anchor{5639}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_or

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_or} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_or (C macro)
@anchor{c-api/typeobj c Py_nb_or}@anchor{5171}
@end deffn

@geindex PyNumberMethods.nb_int (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_int}@anchor{563b}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{1637,,PyNumberMethods}.nb_int

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_int} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_int (C macro)
@anchor{c-api/typeobj c Py_nb_int}@anchor{516b}
@end deffn

@geindex PyNumberMethods.nb_reserved (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_reserved}@anchor{563c}
@deffn {C のメンバ変数} void *@ref{1637,,PyNumberMethods}.nb_reserved
@end deffn

@geindex PyNumberMethods.nb_float (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_float}@anchor{563d}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{1637,,PyNumberMethods}.nb_float

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_float} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_float (C macro)
@anchor{c-api/typeobj c Py_nb_float}@anchor{515b}
@end deffn

@geindex PyNumberMethods.nb_inplace_add (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_add}@anchor{5622}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_add

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_add} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_add (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_add}@anchor{515e}
@end deffn

@geindex PyNumberMethods.nb_inplace_subtract (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_subtract}@anchor{5624}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_subtract

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_subtract} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_subtract (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_subtract}@anchor{5168}
@end deffn

@geindex PyNumberMethods.nb_inplace_multiply (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_multiply}@anchor{5626}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_multiply

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_multiply} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_multiply (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_multiply}@anchor{5163}
@end deffn

@geindex PyNumberMethods.nb_inplace_remainder (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_remainder}@anchor{5628}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_remainder

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_remainder} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_remainder (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_remainder}@anchor{5166}
@end deffn

@geindex PyNumberMethods.nb_inplace_power (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_power}@anchor{562b}
@deffn {C のメンバ変数} @ref{51b9,,ternaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_power

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_power} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_power (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_power}@anchor{5165}
@end deffn

@geindex PyNumberMethods.nb_inplace_lshift (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_lshift}@anchor{5632}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_lshift

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_lshift} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_lshift (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_lshift}@anchor{5161}
@end deffn

@geindex PyNumberMethods.nb_inplace_rshift (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_rshift}@anchor{5634}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_rshift

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_rshift} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_rshift (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_rshift}@anchor{5167}
@end deffn

@geindex PyNumberMethods.nb_inplace_and (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_and}@anchor{5636}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_and

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_and} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_and (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_and}@anchor{515f}
@end deffn

@geindex PyNumberMethods.nb_inplace_xor (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_xor}@anchor{5638}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_xor

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_xor} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_xor (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_xor}@anchor{516a}
@end deffn

@geindex PyNumberMethods.nb_inplace_or (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_or}@anchor{563a}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_or

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_or} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_or (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_or}@anchor{5164}
@end deffn

@geindex PyNumberMethods.nb_floor_divide (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_floor_divide}@anchor{563e}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_floor_divide

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_floor_divide} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_floor_divide (C macro)
@anchor{c-api/typeobj c Py_nb_floor_divide}@anchor{515c}
@end deffn

@geindex PyNumberMethods.nb_true_divide (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_true_divide}@anchor{5640}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_true_divide

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_true_divide} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_true_divide (C macro)
@anchor{c-api/typeobj c Py_nb_true_divide}@anchor{5177}
@end deffn

@geindex PyNumberMethods.nb_inplace_floor_divide (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_floor_divide}@anchor{563f}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_floor_divide

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_floor_divide} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_floor_divide (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_floor_divide}@anchor{5160}
@end deffn

@geindex PyNumberMethods.nb_inplace_true_divide (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_true_divide}@anchor{5641}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_true_divide

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_true_divide} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_inplace_true_divide (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_true_divide}@anchor{5169}
@end deffn

@geindex PyNumberMethods.nb_index (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_index}@anchor{1636}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{1637,,PyNumberMethods}.nb_index

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_index} is part of the @ref{775,,Stable ABI}.'
@geindex Py_nb_index (C macro)
@anchor{c-api/typeobj c Py_nb_index}@anchor{515d}
@end deffn

@geindex PyNumberMethods.nb_matrix_multiply (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_matrix_multiply}@anchor{5642}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_matrix_multiply

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_matrix_multiply} is part of the @ref{775,,Stable ABI} (バージョン 3.5 より).'
@geindex Py_nb_matrix_multiply (C macro)
@anchor{c-api/typeobj c Py_nb_matrix_multiply}@anchor{516e}
@end deffn

@geindex PyNumberMethods.nb_inplace_matrix_multiply (C member)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_matrix_multiply}@anchor{5643}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{1637,,PyNumberMethods}.nb_inplace_matrix_multiply

` The corresponding @ref{50dc,,slot ID} @code{Py_nb_inplace_matrix_multiply} is part of the @ref{775,,Stable ABI} (バージョン 3.5 より).'
@geindex Py_nb_inplace_matrix_multiply (C macro)
@anchor{c-api/typeobj c Py_nb_inplace_matrix_multiply}@anchor{5162}
@end deffn

@node マップオブジェクト構造体,シーケンスオブジェクト構造体,数値オブジェクト構造体,Type Object Structures
@anchor{c-api/typeobj mapping-object-structures}@anchor{5665}@anchor{c-api/typeobj mapping-structs}@anchor{5655}
@subsubsection マップオブジェクト構造体


@geindex PyMappingMethods (C type)
@anchor{c-api/typeobj c PyMappingMethods}@anchor{4ef5}
@deffn {C のデータ型} type PyMappingMethods

この構造体はマップ型プロトコルを実装するために使われる関数群へのポインタを保持しています。
以下の3つのメンバを持っています:
@end deffn

@geindex PyMappingMethods.mp_length (C member)
@anchor{c-api/typeobj c PyMappingMethods mp_length}@anchor{5644}
@deffn {C のメンバ変数} @ref{51ad,,lenfunc} @ref{4ef5,,PyMappingMethods}.mp_length

` The corresponding @ref{50dc,,slot ID} @code{Py_mp_length} is part of the @ref{775,,Stable ABI}.'
@geindex Py_mp_length (C macro)
@anchor{c-api/typeobj c Py_mp_length}@anchor{5154}

この関数は @ref{1e37,,PyMapping_Size()} や @ref{5098,,PyObject_Size()} から利用され、それらと同じシグネチャを持っています。オブジェクトが定義された長さを持たない場合は、このスロットは @code{NULL} に設定されることがあります。
@end deffn

@geindex PyMappingMethods.mp_subscript (C member)
@anchor{c-api/typeobj c PyMappingMethods mp_subscript}@anchor{1cf6}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{4ef5,,PyMappingMethods}.mp_subscript

` The corresponding @ref{50dc,,slot ID} @code{Py_mp_subscript} is part of the @ref{775,,Stable ABI}.'
@geindex Py_mp_subscript (C macro)
@anchor{c-api/typeobj c Py_mp_subscript}@anchor{5155}

この関数は @ref{5ea,,PyObject_GetItem()} および @ref{50a4,,PySequence_GetSlice()} から利用され、@code{PyObject_GetItem()} と同じシグネチャを持っています。このスロットは @ref{5051,,PyMapping_Check()} が @code{1} を返すためには必要で、そうでなければ @code{NULL} の場合があります。
@end deffn

@geindex PyMappingMethods.mp_ass_subscript (C member)
@anchor{c-api/typeobj c PyMappingMethods mp_ass_subscript}@anchor{5645}
@deffn {C のメンバ変数} @ref{51af,,objobjargproc} @ref{4ef5,,PyMappingMethods}.mp_ass_subscript

` The corresponding @ref{50dc,,slot ID} @code{Py_mp_ass_subscript} is part of the @ref{775,,Stable ABI}.'
@geindex Py_mp_ass_subscript (C macro)
@anchor{c-api/typeobj c Py_mp_ass_subscript}@anchor{5153}

This function is used by @ref{4f48,,PyObject_SetItem()},
@ref{508a,,PyObject_DelItem()}, @ref{50ab,,PySequence_SetSlice()} and
@ref{50a3,,PySequence_DelSlice()}.  It has the same signature as
@code{PyObject_SetItem()}, but `v' can also be set to @code{NULL} to delete
an item.  If this slot is @code{NULL}, the object does not support item
assignment and deletion.
@end deffn

@node シーケンスオブジェクト構造体,バッファオブジェクト構造体 buffer object structure,マップオブジェクト構造体,Type Object Structures
@anchor{c-api/typeobj sequence-object-structures}@anchor{5666}@anchor{c-api/typeobj sequence-structs}@anchor{5654}
@subsubsection シーケンスオブジェクト構造体


@geindex PySequenceMethods (C type)
@anchor{c-api/typeobj c PySequenceMethods}@anchor{4ef4}
@deffn {C のデータ型} type PySequenceMethods

この構造体はシーケンス型プロトコルを実装するために使われる関数群へのポインタを保持しています。
@end deffn

@geindex PySequenceMethods.sq_length (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_length}@anchor{52eb}
@deffn {C のメンバ変数} @ref{51ad,,lenfunc} @ref{4ef4,,PySequenceMethods}.sq_length

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_length} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_length (C macro)
@anchor{c-api/typeobj c Py_sq_length}@anchor{517f}

This function is used by @ref{1e33,,PySequence_Size()} and
@ref{5098,,PyObject_Size()}, and has the same signature.  It is also used for
handling negative indices via the @ref{1cf5,,sq_item}
and the @ref{5648,,sq_ass_item} slots.
@end deffn

@geindex PySequenceMethods.sq_concat (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_concat}@anchor{5646}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{4ef4,,PySequenceMethods}.sq_concat

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_concat} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_concat (C macro)
@anchor{c-api/typeobj c Py_sq_concat}@anchor{517a}

この関数は @ref{50a1,,PySequence_Concat()} で利用され、同じシグネチャを持っています。また、 @code{+} 演算子でも、 @ref{52e2,,nb_add} スロットによる数値加算を試した後に利用されます。
@end deffn

@geindex PySequenceMethods.sq_repeat (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_repeat}@anchor{5647}
@deffn {C のメンバ変数} @ref{51b7,,ssizeargfunc} @ref{4ef4,,PySequenceMethods}.sq_repeat

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_repeat} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_repeat (C macro)
@anchor{c-api/typeobj c Py_sq_repeat}@anchor{5180}

この関数は @ref{50aa,,PySequence_Repeat()} で利用され、同じシグネチャを持っています。また、 @code{*} 演算でも、 @ref{5625,,nb_multiply} スロットによる数値乗算を試したあとに利用されます。
@end deffn

@geindex PySequenceMethods.sq_item (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_item}@anchor{1cf5}
@deffn {C のメンバ変数} @ref{51b7,,ssizeargfunc} @ref{4ef4,,PySequenceMethods}.sq_item

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_item} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_item (C macro)
@anchor{c-api/typeobj c Py_sq_item}@anchor{517e}

This function is used by @ref{1e34,,PySequence_GetItem()} and has the same
signature.  It is also used by @ref{5ea,,PyObject_GetItem()}, after trying
the subscription via the @ref{1cf6,,mp_subscript} slot.
This slot must be filled for the @ref{50a0,,PySequence_Check()}
function to return @code{1}, it can be @code{NULL} otherwise.

Negative indexes are handled as follows: if the @ref{52eb,,sq_length} slot is
filled, it is called and the sequence length is used to compute a positive
index which is passed to  @ref{1cf5,,sq_item}.  If @code{sq_length} is @code{NULL},
the index is passed as is to the function.
@end deffn

@geindex PySequenceMethods.sq_ass_item (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_ass_item}@anchor{5648}
@deffn {C のメンバ変数} @ref{51b8,,ssizeobjargproc} @ref{4ef4,,PySequenceMethods}.sq_ass_item

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_ass_item} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_ass_item (C macro)
@anchor{c-api/typeobj c Py_sq_ass_item}@anchor{5179}

This function is used by @ref{1e35,,PySequence_SetItem()} and has the same
signature.  It is also used by @ref{4f48,,PyObject_SetItem()} and
@ref{508a,,PyObject_DelItem()}, after trying the item assignment and deletion
via the @ref{5645,,mp_ass_subscript} slot.
This slot may be left to @code{NULL} if the object does not support
item assignment and deletion.
@end deffn

@geindex PySequenceMethods.sq_contains (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_contains}@anchor{5649}
@deffn {C のメンバ変数} @ref{51b0,,objobjproc} @ref{4ef4,,PySequenceMethods}.sq_contains

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_contains} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_contains (C macro)
@anchor{c-api/typeobj c Py_sq_contains}@anchor{517b}

この関数は @ref{3d9,,PySequence_Contains()} から利用され、同じシグネチャを持っています。このスロットは @code{NULL} の場合があり、その時 @code{PySequence_Contains()} はシンプルにマッチするオブジェクトを見つけるまでシーケンスを巡回します。
@end deffn

@geindex PySequenceMethods.sq_inplace_concat (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_inplace_concat}@anchor{564a}
@deffn {C のメンバ変数} @ref{51a0,,binaryfunc} @ref{4ef4,,PySequenceMethods}.sq_inplace_concat

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_inplace_concat} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_inplace_concat (C macro)
@anchor{c-api/typeobj c Py_sq_inplace_concat}@anchor{517c}

This function is used by @ref{50a5,,PySequence_InPlaceConcat()} and has the same
signature.  It should modify its first operand, and return it.  This slot
may be left to @code{NULL}, in this case @code{PySequence_InPlaceConcat()}
will fall back to @ref{50a1,,PySequence_Concat()}.  It is also used by the
augmented assignment @code{+=}, after trying numeric in-place addition
via the @ref{5622,,nb_inplace_add} slot.
@end deffn

@geindex PySequenceMethods.sq_inplace_repeat (C member)
@anchor{c-api/typeobj c PySequenceMethods sq_inplace_repeat}@anchor{564b}
@deffn {C のメンバ変数} @ref{51b7,,ssizeargfunc} @ref{4ef4,,PySequenceMethods}.sq_inplace_repeat

` The corresponding @ref{50dc,,slot ID} @code{Py_sq_inplace_repeat} is part of the @ref{775,,Stable ABI}.'
@geindex Py_sq_inplace_repeat (C macro)
@anchor{c-api/typeobj c Py_sq_inplace_repeat}@anchor{517d}

This function is used by @ref{50a6,,PySequence_InPlaceRepeat()} and has the same
signature.  It should modify its first operand, and return it.  This slot
may be left to @code{NULL}, in this case @code{PySequence_InPlaceRepeat()}
will fall back to @ref{50aa,,PySequence_Repeat()}.  It is also used by the
augmented assignment @code{*=}, after trying numeric in-place multiplication
via the @ref{5626,,nb_inplace_multiply} slot.
@end deffn

@node バッファオブジェクト構造体 buffer object structure,async オブジェクト構造体,シーケンスオブジェクト構造体,Type Object Structures
@anchor{c-api/typeobj buffer-object-structures}@anchor{5667}@anchor{c-api/typeobj buffer-structs}@anchor{1248}
@subsubsection バッファオブジェクト構造体 (buffer object structure)


@geindex PyBufferProcs (C type)
@anchor{c-api/typeobj c PyBufferProcs}@anchor{52f1}
@deffn {C のデータ型} type PyBufferProcs

この構造体は @ref{260,,buffer プロトコル} が要求する関数群へのポインタを保持しています。
そのプロトコルは、エクスポーターオブジェクトが如何にして、その内部データをコンシューマオブジェクトに渡すかを定義します。
@end deffn

@geindex PyBufferProcs.bf_getbuffer (C member)
@anchor{c-api/typeobj c PyBufferProcs bf_getbuffer}@anchor{966}
@deffn {C のメンバ変数} @ref{51a6,,getbufferproc} @ref{52f1,,PyBufferProcs}.bf_getbuffer

` The corresponding @ref{50dc,,slot ID} @code{Py_bf_getbuffer} is part of the @ref{775,,Stable ABI} (バージョン 3.11 より).'
@geindex Py_bf_getbuffer (C macro)
@anchor{c-api/typeobj c Py_bf_getbuffer}@anchor{514f}

この関数のシグネチャは以下の通りです:

@example
int (PyObject *exporter, Py_buffer *view, int flags);
@end example

`flags' で指定された方法で `view' を埋めてほしいという `exporter' に対する要求を処理します。ステップ(3) を除いて、この関数の実装では以下のステップを行わなければなりません:


@enumerate 

@item 
Check if the request can be met. If not, raise @ref{1797,,BufferError},
set view->obj to @code{NULL} and return @code{-1}.

@item 
要求されたフィールドを埋めます。

@item 
エクスポートした回数を保持する内部カウンタをインクリメントします。

@item 
view->obj に `exporter' を設定し、 view->obj をインクリメントします。

@item 
@code{0} を返します。
@end enumerate

`exporter' がバッファプロバイダのチェインかツリーの一部であれば、２つの主要な方式が使用できます:


@itemize *

@item 
再エクスポート: ツリーの各要素がエクスポートされるオブジェクトとして振る舞い、自身への新しい参照を view->obj へセットします。

@item 
リダイレクト: バッファ要求がツリーのルートオブジェクトにリダイレクトされます。ここでは、 view->obj はルートオブジェクトへの新しい参照になります。
@end itemize

`view' の個別のフィールドは @ref{52b8,,バッファ構造体} の節で説明されており、エクスポートが特定の要求に対しどう対応しなければならないかの規則は、 @ref{1249,,バッファ要求のタイプ} の節にあります。

@ref{95c,,Py_buffer} 構造体の中から参照している全てのメモリはエクスポータに属し、コンシューマがいなくなるまで有効でなくてはなりません。 @ref{52c1,,format} 、 @ref{52c2,,shape} 、 @ref{52bc,,strides} 、 @ref{52c4,,suboffsets} 、 @ref{52c6,,internal} はコンシューマからは読み出し専用です。

@ref{964,,PyBuffer_FillInfo()} は、全てのリクエストタイプを正しく扱う際に、単純なバイトバッファを公開する簡単な方法を提供します。

@ref{63a,,PyObject_GetBuffer()} は、この関数をラップするコンシューマ向けのインターフェースです。
@end deffn

@geindex PyBufferProcs.bf_releasebuffer (C member)
@anchor{c-api/typeobj c PyBufferProcs bf_releasebuffer}@anchor{967}
@deffn {C のメンバ変数} @ref{51b1,,releasebufferproc} @ref{52f1,,PyBufferProcs}.bf_releasebuffer

` The corresponding @ref{50dc,,slot ID} @code{Py_bf_releasebuffer} is part of the @ref{775,,Stable ABI} (バージョン 3.11 より).'
@geindex Py_bf_releasebuffer (C macro)
@anchor{c-api/typeobj c Py_bf_releasebuffer}@anchor{5150}

この関数のシグネチャは以下の通りです:

@example
void (PyObject *exporter, Py_buffer *view);
@end example

バッファのリソースを開放する要求を処理します。もし開放する必要のあるリソースがない場合、 @ref{967,,PyBufferProcs.bf_releasebuffer} は @code{NULL} にしても構いません。そうでない場合は、この関数の標準的な実装は、以下の任意の処理手順 (optional step) を行います:


@enumerate 

@item 
エクスポートした回数を保持する内部カウンタをデクリメントします。

@item 
カウンタが @code{0} の場合は、`view' に関連付けられた全てのメモリを解放します。
@end enumerate

エクスポータは、バッファ固有のリソースを監視し続けるために @ref{52c6,,internal} フィールドを使わなければなりません。このフィールドは、コンシューマが `view' 引数としてオリジナルのバッファのコピーを渡しているであろう間、変わらないことが保証されています。

この関数は、view->obj をデクリメントしてはいけません、なぜならそれは @ref{63b,,PyBuffer_Release()} で自動的に行われるからです(この方式は参照の循環を防ぐのに有用です)。

@ref{63b,,PyBuffer_Release()} は、この関数をラップするコンシューマ向けのインターフェースです。
@end deffn

@node async オブジェクト構造体,Slot Type typedefs,バッファオブジェクト構造体 buffer object structure,Type Object Structures
@anchor{c-api/typeobj async-object-structures}@anchor{5668}@anchor{c-api/typeobj async-structs}@anchor{5652}
@subsubsection async オブジェクト構造体



Added in version 3.5.


@geindex PyAsyncMethods (C type)
@anchor{c-api/typeobj c PyAsyncMethods}@anchor{52ea}
@deffn {C のデータ型} type PyAsyncMethods

この構造体は @ref{4c9,,awaitable} オブジェクトと @ref{4c7,,asynchronous iterator} オブジェクトを実装するのに必要な関数へのポインタを保持しています。

以下は構造体の定義です:

@example
typedef struct @{
    unaryfunc am_await;
    unaryfunc am_aiter;
    unaryfunc am_anext;
    sendfunc am_send;
@} PyAsyncMethods;
@end example
@end deffn

@geindex PyAsyncMethods.am_await (C member)
@anchor{c-api/typeobj c PyAsyncMethods am_await}@anchor{561d}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{52ea,,PyAsyncMethods}.am_await

` The corresponding @ref{50dc,,slot ID} @code{Py_am_await} is part of the @ref{775,,Stable ABI} (バージョン 3.5 より).'
@geindex Py_am_await (C macro)
@anchor{c-api/typeobj c Py_am_await}@anchor{514d}

この関数のシグネチャは以下の通りです:

@example
PyObject *am_await(PyObject *self);
@end example

返されるオブジェクトは @ref{4c8,,イテレータ} でなければなりません。
つまりこのオブジェクトに対して @ref{1cb2,,PyIter_Check()} が @code{1} を返さなければなりません。

オブジェクトが @ref{4c9,,awaitable} でない場合、このスロットを @code{NULL} に設定します。
@end deffn

@geindex PyAsyncMethods.am_aiter (C member)
@anchor{c-api/typeobj c PyAsyncMethods am_aiter}@anchor{561e}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{52ea,,PyAsyncMethods}.am_aiter

` The corresponding @ref{50dc,,slot ID} @code{Py_am_aiter} is part of the @ref{775,,Stable ABI} (バージョン 3.5 より).'
@geindex Py_am_aiter (C macro)
@anchor{c-api/typeobj c Py_am_aiter}@anchor{514b}

この関数のシグネチャは以下の通りです:

@example
PyObject *am_aiter(PyObject *self);
@end example

Must return an @ref{4c7,,asynchronous iterator} object.
See @ref{1882,,__anext__()} for details.

オブジェクトが非同期反復処理のプロトコルを実装していない場合、このスロットを @code{NULL} に設定します。
@end deffn

@geindex PyAsyncMethods.am_anext (C member)
@anchor{c-api/typeobj c PyAsyncMethods am_anext}@anchor{561f}
@deffn {C のメンバ変数} @ref{51bb,,unaryfunc} @ref{52ea,,PyAsyncMethods}.am_anext

` The corresponding @ref{50dc,,slot ID} @code{Py_am_anext} is part of the @ref{775,,Stable ABI} (バージョン 3.5 より).'
@geindex Py_am_anext (C macro)
@anchor{c-api/typeobj c Py_am_anext}@anchor{514c}

この関数のシグネチャは以下の通りです:

@example
PyObject *am_anext(PyObject *self);
@end example

Must return an @ref{4c9,,awaitable} object.
See @ref{1882,,__anext__()} for details.
This slot may be set to @code{NULL}.
@end deffn

@geindex PyAsyncMethods.am_send (C member)
@anchor{c-api/typeobj c PyAsyncMethods am_send}@anchor{5620}
@deffn {C のメンバ変数} @ref{5621,,sendfunc} @ref{52ea,,PyAsyncMethods}.am_send

` The corresponding @ref{50dc,,slot ID} @code{Py_am_send} is part of the @ref{775,,Stable ABI} (バージョン 3.10 より).'
@geindex Py_am_send (C macro)
@anchor{c-api/typeobj c Py_am_send}@anchor{514e}

この関数のシグネチャは以下の通りです:

@example
PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);
@end example

See @ref{a98,,PyIter_Send()} for details.
This slot may be set to @code{NULL}.


Added in version 3.10.

@end deffn

@node Slot Type typedefs,使用例<57>,async オブジェクト構造体,Type Object Structures
@anchor{c-api/typeobj id6}@anchor{564d}@anchor{c-api/typeobj slot-type-typedefs}@anchor{5669}
@subsubsection Slot Type typedefs


@geindex allocfunc (C type)
@anchor{c-api/typeobj c allocfunc}@anchor{519f}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*allocfunc)(@ref{c9c,,PyTypeObject} *cls, @ref{c55,,Py_ssize_t} nitems)
` 次に属します: @ref{775,,Stable ABI}.'
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
@ref{a9f,,ob_refcnt} set to @code{1} and @ref{4ecd,,ob_type} set to the type argument.  If
the type's @ref{23bb,,tp_itemsize} is non-zero, the object's @ref{511c,,ob_size} field
should be initialized to `nitems' and the length of the allocated memory block
should be @code{tp_basicsize + nitems*tp_itemsize}, rounded up to a multiple of
@code{sizeof(void*)}; otherwise, `nitems' is not used and the length of the block
should be @ref{b7e,,tp_basicsize}.

この関数では他のいかなるインスタンス初期化も行ってはなりません。追加のメモリ割り当てすらも行ってはなりません。そのような処理は @ref{79f,,tp_new} で行われるべきです。
@end deffn

@geindex destructor (C type)
@anchor{c-api/typeobj c destructor}@anchor{51a3}
@deffn {C のデータ型} typedef void (*destructor)(@ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex freefunc (C type)
@anchor{c-api/typeobj c freefunc}@anchor{5449}
@deffn {C のデータ型} typedef void (*freefunc)(void*)

@ref{4ecf,,tp_free}  を参照してください。
@end deffn

@geindex newfunc (C type)
@anchor{c-api/typeobj c newfunc}@anchor{51ae}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*newfunc)(@ref{c9c,,PyTypeObject}*, @ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{79f,,tp_new} を参照してください。
@end deffn

@geindex initproc (C type)
@anchor{c-api/typeobj c initproc}@anchor{51aa}
@deffn {C のデータ型} typedef int (*initproc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{7a1,,tp_init} を参照してください。
@end deffn

@geindex reprfunc (C type)
@anchor{c-api/typeobj c reprfunc}@anchor{51b2}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*reprfunc)(@ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{4ee4,,tp_repr} を参照してください。
@end deffn

@geindex getattrfunc (C type)
@anchor{c-api/typeobj c getattrfunc}@anchor{51a4}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*getattrfunc)(@ref{5df,,PyObject} *self, char *attr)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクトの属性の値を返します。
@end deffn

@geindex setattrfunc (C type)
@anchor{c-api/typeobj c setattrfunc}@anchor{51b4}
@deffn {C のデータ型} typedef int (*setattrfunc)(@ref{5df,,PyObject} *self, char *attr, @ref{5df,,PyObject} *value)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクトの属性に値を設定します。属性を削除するには、 value (実) 引数に @code{NULL} を設定します。
@end deffn

@geindex getattrofunc (C type)
@anchor{c-api/typeobj c getattrofunc}@anchor{51a5}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*getattrofunc)(@ref{5df,,PyObject} *self, @ref{5df,,PyObject} *attr)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクトの属性の値を返します。

@ref{1a64,,tp_getattro} を参照してください。
@end deffn

@geindex setattrofunc (C type)
@anchor{c-api/typeobj c setattrofunc}@anchor{51b5}
@deffn {C のデータ型} typedef int (*setattrofunc)(@ref{5df,,PyObject} *self, @ref{5df,,PyObject} *attr, @ref{5df,,PyObject} *value)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクトの属性に値を設定します。属性を削除するには、 value (実) 引数に @code{NULL} を設定します。

@ref{4ee8,,tp_setattro} を参照してください。
@end deffn

@geindex descrgetfunc (C type)
@anchor{c-api/typeobj c descrgetfunc}@anchor{51a1}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*descrgetfunc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{5616,,tp_descr_get} を参照してください。
@end deffn

@geindex descrsetfunc (C type)
@anchor{c-api/typeobj c descrsetfunc}@anchor{51a2}
@deffn {C のデータ型} typedef int (*descrsetfunc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{1cb4,,tp_descr_set} を参照してください。
@end deffn

@geindex hashfunc (C type)
@anchor{c-api/typeobj c hashfunc}@anchor{51a9}
@deffn {C のデータ型} typedef @ref{147b,,Py_hash_t} (*hashfunc)(@ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{4ef6,,tp_hash} を参照してください。
@end deffn

@geindex richcmpfunc (C type)
@anchor{c-api/typeobj c richcmpfunc}@anchor{51b3}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*richcmpfunc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, int)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{4ef0,,tp_richcompare} を参照してください。
@end deffn

@geindex getiterfunc (C type)
@anchor{c-api/typeobj c getiterfunc}@anchor{51a7}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*getiterfunc)(@ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{1708,,tp_iter} を参照してください。
@end deffn

@geindex iternextfunc (C type)
@anchor{c-api/typeobj c iternextfunc}@anchor{51ac}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*iternextfunc)(@ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{1709,,tp_iternext} を参照してください。
@end deffn

@geindex lenfunc (C type)
@anchor{c-api/typeobj c lenfunc}@anchor{51ad}
@deffn {C のデータ型} typedef @ref{c55,,Py_ssize_t} (*lenfunc)(@ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex getbufferproc (C type)
@anchor{c-api/typeobj c getbufferproc}@anchor{51a6}
@deffn {C のデータ型} typedef int (*getbufferproc)(@ref{5df,,PyObject}*, @ref{95c,,Py_buffer}*, int)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@geindex releasebufferproc (C type)
@anchor{c-api/typeobj c releasebufferproc}@anchor{51b1}
@deffn {C のデータ型} typedef void (*releasebufferproc)(@ref{5df,,PyObject}*, @ref{95c,,Py_buffer}*)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.12 より).'
@end deffn

@geindex unaryfunc (C type)
@anchor{c-api/typeobj c unaryfunc}@anchor{51bb}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*unaryfunc)(@ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex binaryfunc (C type)
@anchor{c-api/typeobj c binaryfunc}@anchor{51a0}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*binaryfunc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex sendfunc (C type)
@anchor{c-api/typeobj c sendfunc}@anchor{5621}
@deffn {C のデータ型} typedef @ref{52b4,,PySendResult} (*sendfunc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, @ref{5df,,PyObject}**)

@ref{5620,,am_send} を参照してください。
@end deffn

@geindex ternaryfunc (C type)
@anchor{c-api/typeobj c ternaryfunc}@anchor{51b9}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*ternaryfunc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex ssizeargfunc (C type)
@anchor{c-api/typeobj c ssizeargfunc}@anchor{51b7}
@deffn {C のデータ型} typedef @ref{5df,,PyObject} *(*ssizeargfunc)(@ref{5df,,PyObject}*, @ref{c55,,Py_ssize_t})
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex ssizeobjargproc (C type)
@anchor{c-api/typeobj c ssizeobjargproc}@anchor{51b8}
@deffn {C のデータ型} typedef int (*ssizeobjargproc)(@ref{5df,,PyObject}*, @ref{c55,,Py_ssize_t}, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex objobjproc (C type)
@anchor{c-api/typeobj c objobjproc}@anchor{51b0}
@deffn {C のデータ型} typedef int (*objobjproc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@geindex objobjargproc (C type)
@anchor{c-api/typeobj c objobjargproc}@anchor{51af}
@deffn {C のデータ型} typedef int (*objobjargproc)(@ref{5df,,PyObject}*, @ref{5df,,PyObject}*, @ref{5df,,PyObject}*)
` 次に属します: @ref{775,,Stable ABI}.'
@end deffn

@node 使用例<57>,,Slot Type typedefs,Type Object Structures
@anchor{c-api/typeobj examples}@anchor{566a}@anchor{c-api/typeobj typedef-examples}@anchor{560e}
@subsubsection 使用例


ここでは Python の型定義の簡単な例をいくつか挙げます。これらの例にはあなたが遭遇する共通的な利用例を含んでいます。いくつかの例ではトリッキーなコーナーケースを実演しています。より多くの例や実践的な情報、チュートリアルが必要なら、@ref{4ec5,,拡張の型の定義; チュートリアル} や @ref{4ede,,拡張の型の定義; 雑多なトピック} を参照してください。

A basic @ref{983,,static type}:

@example
typedef struct @{
    PyObject_HEAD
    const char *data;
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_new = myobj_new,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
@};
@end example

より冗長な初期化子を用いた古いコードを（特にCPythonのコードベース中で）見かけることがあるかもしれません:

@example
static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    "mymod.MyObject",               /* tp_name */
    sizeof(MyObject),               /* tp_basicsize */
    0,                              /* tp_itemsize */
    (destructor)myobj_dealloc,      /* tp_dealloc */
    0,                              /* tp_vectorcall_offset */
    0,                              /* tp_getattr */
    0,                              /* tp_setattr */
    0,                              /* tp_as_async */
    (reprfunc)myobj_repr,           /* tp_repr */
    0,                              /* tp_as_number */
    0,                              /* tp_as_sequence */
    0,                              /* tp_as_mapping */
    0,                              /* tp_hash */
    0,                              /* tp_call */
    0,                              /* tp_str */
    0,                              /* tp_getattro */
    0,                              /* tp_setattro */
    0,                              /* tp_as_buffer */
    0,                              /* tp_flags */
    PyDoc_STR("My objects"),        /* tp_doc */
    0,                              /* tp_traverse */
    0,                              /* tp_clear */
    0,                              /* tp_richcompare */
    0,                              /* tp_weaklistoffset */
    0,                              /* tp_iter */
    0,                              /* tp_iternext */
    0,                              /* tp_methods */
    0,                              /* tp_members */
    0,                              /* tp_getset */
    0,                              /* tp_base */
    0,                              /* tp_dict */
    0,                              /* tp_descr_get */
    0,                              /* tp_descr_set */
    0,                              /* tp_dictoffset */
    0,                              /* tp_init */
    0,                              /* tp_alloc */
    myobj_new,                      /* tp_new */
@};
@end example

弱参照やインスタンス辞書、ハッシュをサポートする型:

@example
typedef struct @{
    PyObject_HEAD
    const char *data;
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
         Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |
         Py_TPFLAGS_MANAGED_WEAKREF,
    .tp_new = myobj_new,
    .tp_traverse = (traverseproc)myobj_traverse,
    .tp_clear = (inquiry)myobj_clear,
    .tp_alloc = PyType_GenericNew,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
    .tp_hash = (hashfunc)myobj_hash,
    .tp_richcompare = PyBaseObject_Type.tp_richcompare,
@};
@end example

A str subclass that cannot be subclassed and cannot be called
to create instances (e.g. uses a separate factory func) using
@ref{7a2,,Py_TPFLAGS_DISALLOW_INSTANTIATION} flag:

@example
typedef struct @{
    PyUnicodeObject raw;
    char *extra;
@} MyStr;

static PyTypeObject MyStr_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyStr",
    .tp_basicsize = sizeof(MyStr),
    .tp_base = NULL,  // set to &PyUnicode_Type in module init
    .tp_doc = PyDoc_STR("my custom str"),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
    .tp_repr = (reprfunc)myobj_repr,
@};
@end example

The simplest @ref{983,,static type} with fixed-length instances:

@example
typedef struct @{
    PyObject_HEAD
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
@};
@end example

The simplest @ref{983,,static type} with variable-length instances:

@example
typedef struct @{
    PyObject_VAR_HEAD
    const char *data[1];
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject) - sizeof(char *),
    .tp_itemsize = sizeof(char *),
@};
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 循環参照ガベージコレクションをサポートする,,Type Object Structures,オブジェクト実装サポート object implementation support
@anchor{c-api/gcsupport doc}@anchor{566b}@anchor{c-api/gcsupport supporting-cycle-detection}@anchor{5656}@anchor{c-api/gcsupport supporting-cyclic-garbage-collection}@anchor{566c}@anchor{c-api/gcsupport translation-repo}@anchor{566d}
@subsection 循環参照ガベージコレクションをサポートする


Python が循環参照を含むガベージの検出とコレクションをサポートするには、他のオブジェクトに対する "コンテナ" (他のオブジェクトには他のコンテナも含みます) となるオブジェクト型によるサポートが必要です。他のオブジェクトに対する参照を記憶しないオブジェクトや、(数値や文字列のような) アトム型 (atomic type) への参照だけを記憶するような型では、ガベージコレクションに際して特別これといったサポートを提供する必要はありません。

To create a container type, the @ref{1c71,,tp_flags} field of the type object must
include the @ref{981,,Py_TPFLAGS_HAVE_GC} and provide an implementation of the
@ref{982,,tp_traverse} handler.  If instances of the type are mutable, a
@ref{4ee2,,tp_clear} implementation must also be provided.


@table @asis

@item @ref{981,,Py_TPFLAGS_HAVE_GC}

このフラグをセットした型のオブジェクトは、この節に述べた規則に適合しなければなりません。簡単のため、このフラグをセットした型のオブジェクトをコンテナオブジェクトと呼びます。
@end table

コンテナ型のコンストラクタは以下の二つの規則に適合しなければなりません:


@enumerate 

@item 
The memory for the object must be allocated using @ref{c99,,PyObject_GC_New}
or @ref{c9a,,PyObject_GC_NewVar}.

@item 
他のコンテナへの参照が入るかもしれないフィールドが全て初期化されたら、すぐに @ref{171d,,PyObject_GC_Track()} を呼び出さなければなりません。
@end enumerate

同様に、オブジェクトのメモリ解放関数も以下の二つの規則に適合しなければなりません:


@enumerate 

@item 
他のコンテナを参照しているフィールドを無効化する前に、 @ref{171e,,PyObject_GC_UnTrack()} を呼び出さなければなりません。

@item 
オブジェクトのメモリは @ref{171c,,PyObject_GC_Del()} で解放しなければなりません。

@cartouche
@quotation 警告 
If a type adds the Py_TPFLAGS_HAVE_GC, then it `must' implement at least
a @ref{982,,tp_traverse} handler or explicitly use one
from its subclass or subclasses.

When calling @ref{980,,PyType_Ready()} or some of the APIs that indirectly
call it like @ref{79e,,PyType_FromSpecWithBases()} or
@ref{79d,,PyType_FromSpec()} the interpreter will automatically populate the
@ref{1c71,,tp_flags}, @ref{982,,tp_traverse}
and @ref{4ee2,,tp_clear} fields if the type inherits from a
class that implements the garbage collector protocol and the child class
does `not' include the @ref{981,,Py_TPFLAGS_HAVE_GC} flag.
@end quotation
@end cartouche
@end enumerate

@geindex PyObject_GC_New (C macro)
@anchor{c-api/gcsupport c PyObject_GC_New}@anchor{c99}
@deffn {C のマクロ} PyObject_GC_New (TYPE, typeobj)

Analogous to @ref{b7c,,PyObject_New} but for container objects with the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag set.

Do not call this directly to allocate memory for an object; call the type's
@ref{4ed0,,tp_alloc} slot instead.

When populating a type's @ref{4ed0,,tp_alloc} slot,
@ref{c61,,PyType_GenericAlloc()} is preferred over a custom function that
simply calls this macro.

Memory allocated by this macro must be freed with
@ref{171c,,PyObject_GC_Del()} (usually called via the object's
@ref{4ecf,,tp_free} slot).


@subsubheading 参考



@itemize *

@item 
@ref{171c,,PyObject_GC_Del()}

@item 
@ref{b7c,,PyObject_New}

@item 
@ref{c61,,PyType_GenericAlloc()}

@item 
@ref{4ed0,,tp_alloc}
@end itemize

@end deffn

@geindex PyObject_GC_NewVar (C macro)
@anchor{c-api/gcsupport c PyObject_GC_NewVar}@anchor{c9a}
@deffn {C のマクロ} PyObject_GC_NewVar (TYPE, typeobj, size)

Analogous to @ref{b7d,,PyObject_NewVar} but for container objects with the
@ref{981,,Py_TPFLAGS_HAVE_GC} flag set.

Do not call this directly to allocate memory for an object; call the type's
@ref{4ed0,,tp_alloc} slot instead.

When populating a type's @ref{4ed0,,tp_alloc} slot,
@ref{c61,,PyType_GenericAlloc()} is preferred over a custom function that
simply calls this macro.

Memory allocated by this macro must be freed with
@ref{171c,,PyObject_GC_Del()} (usually called via the object's
@ref{4ecf,,tp_free} slot).


@subsubheading 参考



@itemize *

@item 
@ref{171c,,PyObject_GC_Del()}

@item 
@ref{b7d,,PyObject_NewVar}

@item 
@ref{c61,,PyType_GenericAlloc()}

@item 
@ref{4ed0,,tp_alloc}
@end itemize

@end deffn

@geindex PyUnstable_Object_GC_NewWithExtraData (C function)
@anchor{c-api/gcsupport c PyUnstable_Object_GC_NewWithExtraData}@anchor{1aa8}
@deffn {C の関数} @ref{5df,,PyObject} *PyUnstable_Object_GC_NewWithExtraData (PyTypeObject *type, size_t extra_size)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Analogous to @ref{c99,,PyObject_GC_New} but allocates `extra_size'
bytes at the end of the object (at offset
@ref{b7e,,tp_basicsize}).
The allocated memory is initialized to zeros,
except for the @ref{5df,,Python object header}.

The extra data will be deallocated with the object, but otherwise it is
not managed by Python.

Memory allocated by this function must be freed with
@ref{171c,,PyObject_GC_Del()} (usually called via the object's
@ref{4ecf,,tp_free} slot).

@cartouche
@quotation 警告 
The function is marked as unstable because the final mechanism
for reserving extra data after an instance is not yet decided.
For allocating a variable number of fields, prefer using
@ref{46d6,,PyVarObject} and @ref{23bb,,tp_itemsize}
instead.
@end quotation
@end cartouche


Added in version 3.12.

@end deffn

@geindex PyObject_GC_Resize (C macro)
@anchor{c-api/gcsupport c PyObject_GC_Resize}@anchor{1aad}
@deffn {C のマクロ} PyObject_GC_Resize (TYPE, op, newsize)

Resize an object allocated by @ref{b7d,,PyObject_NewVar}.
Returns the resized object of type @code{TYPE*} (refers to any C type)
or @code{NULL} on failure.

`op' must be of type @ref{46d6,,PyVarObject}*
and must not be tracked by the collector yet.
`newsize' must be of type @ref{c55,,Py_ssize_t}.
@end deffn

@geindex PyObject_GC_Track (C function)
@anchor{c-api/gcsupport c PyObject_GC_Track}@anchor{171d}
@deffn {C の関数} void PyObject_GC_Track (PyObject *op)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `op' を、コレクタによって追跡されるオブジェクトの集合に追加します。コレクタは何回動くのかは予想できないので、追跡されている間はオブジェクトは正しい状態でいなければなりません。 @ref{982,,tp_traverse} の対象となる全てのフィールドが正しい状態になってすぐに、たいていはコンストラクタの末尾付近で、呼び出すべきです。
@end deffn

@geindex PyObject_IS_GC (C function)
@anchor{c-api/gcsupport c PyObject_IS_GC}@anchor{b7b}
@deffn {C の関数} int PyObject_IS_GC (PyObject *obj)

Returns non-zero if the object implements the garbage collector protocol,
otherwise returns 0.

The object cannot be tracked by the garbage collector if this function returns 0.
@end deffn

@geindex PyObject_GC_IsTracked (C function)
@anchor{c-api/gcsupport c PyObject_GC_IsTracked}@anchor{b6d}
@deffn {C の関数} int PyObject_GC_IsTracked (PyObject *op)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
Returns 1 if the object type of `op' implements the GC protocol and `op' is being
currently tracked by the garbage collector and 0 otherwise.

This is analogous to the Python function @ref{1525,,gc.is_tracked()}.


Added in version 3.9.

@end deffn

@geindex PyObject_GC_IsFinalized (C function)
@anchor{c-api/gcsupport c PyObject_GC_IsFinalized}@anchor{b6e}
@deffn {C の関数} int PyObject_GC_IsFinalized (PyObject *op)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.9 より).'
Returns 1 if the object type of `op' implements the GC protocol and `op' has been
already finalized by the garbage collector and 0 otherwise.

This is analogous to the Python function @ref{af9,,gc.is_finalized()}.


Added in version 3.9.

@end deffn

@geindex PyObject_GC_Del (C function)
@anchor{c-api/gcsupport c PyObject_GC_Del}@anchor{171c}
@deffn {C の関数} void PyObject_GC_Del (void *op)
` 次に属します: @ref{775,,Stable ABI}.'
Releases memory allocated to an object using @ref{c99,,PyObject_GC_New} or
@ref{c9a,,PyObject_GC_NewVar}.

Do not call this directly to free an object's memory; call the type's
@ref{4ecf,,tp_free} slot instead.

Do not use this for memory allocated by @ref{b7c,,PyObject_New},
@ref{b7d,,PyObject_NewVar}, or related allocation functions; use
@ref{e60,,PyObject_Free()} instead.


@subsubheading 参考



@itemize *

@item 
@ref{e60,,PyObject_Free()} is the non-GC equivalent of this function.

@item 
@ref{c99,,PyObject_GC_New}

@item 
@ref{c9a,,PyObject_GC_NewVar}

@item 
@ref{c61,,PyType_GenericAlloc()}

@item 
@ref{4ecf,,tp_free}
@end itemize

@end deffn

@geindex PyObject_GC_UnTrack (C function)
@anchor{c-api/gcsupport c PyObject_GC_UnTrack}@anchor{171e}
@deffn {C の関数} void PyObject_GC_UnTrack (void *op)
` 次に属します: @ref{775,,Stable ABI}.'
オブジェクト `op' を、コレクタによって追跡されるオブジェクトの集合から除去します。このオブジェクトに対して @ref{171d,,PyObject_GC_Track()} を再度呼び出して、追跡されるオブジェクトの集合に戻すことも可能です。 @ref{982,,tp_traverse} ハンドラの対象となるフィールドが正しくない状態になる前に、デアロケータ (@ref{4ebc,,tp_dealloc} ハンドラ) はオブジェクトに対して、この関数を呼び出すべきです。
@end deffn


バージョン 3.8 で変更: The @code{_PyObject_GC_TRACK()} and @code{_PyObject_GC_UNTRACK()} macros
have been removed from the public C API.


@ref{982,,tp_traverse} ハンドラはこの型の関数パラメータを受け取ります:

@geindex visitproc (C type)
@anchor{c-api/gcsupport c visitproc}@anchor{51bc}
@deffn {C のデータ型} typedef int (*visitproc)(@ref{5df,,PyObject} *object, void *arg)
` 次に属します: @ref{775,,Stable ABI}.'
@ref{982,,tp_traverse} ハンドラに渡されるビジター関数 (visitor function) の型です。この関数は、探索するオブジェクトを `object' として、  @ref{982,,tp_traverse} ハンドラの第 3 引数を `arg' として呼び出します。 Python のコアはいくつかのビジター関数を使って、ゴミとなった循環参照を検出する仕組みを実装します; ユーザが自身のためにビジター関数を書く必要が出てくることはないでしょう。
@end deffn

@ref{982,,tp_traverse} ハンドラは次の型を持っていなければなりません:

@geindex traverseproc (C type)
@anchor{c-api/gcsupport c traverseproc}@anchor{51ba}
@deffn {C のデータ型} typedef int (*traverseproc)(@ref{5df,,PyObject} *self, @ref{51bc,,visitproc} visit, void *arg)
` 次に属します: @ref{775,,Stable ABI}.'
コンテナオブジェクトのためのトラバーサル関数 (traversal function) です。
実装では、`self' に直接入っている各オブジェクトに対して `visit'  関数を呼び出さなければなりません。
このとき、`visit' へのパラメタはコンテナに入っている各オブジェクトと、このハンドラに渡された `arg' の値です。
`visit' 関数は @code{NULL} オブジェクトを引数に渡して呼び出してはなりません。
`visit' が非ゼロの値を返す場合、エラーが発生し、戻り値をそのまま返すようにしなければなりません。

The traversal function must not have any side effects.  Implementations
may not modify the reference counts of any Python objects nor create or
destroy any Python objects.
@end deffn

@ref{982,,tp_traverse} ハンドラを簡潔に書くために、 @ref{4ed9,,Py_VISIT()} マクロが提供されています。このマクロを使うためには、 @ref{982,,tp_traverse} の実装関数の引数は、一文字も違わず `visit' と `arg' でなければなりません:

@geindex Py_VISIT (C macro)
@anchor{c-api/gcsupport c Py_VISIT}@anchor{4ed9}
@deffn {C のマクロ} Py_VISIT (o)

If the @ref{5df,,PyObject}* `o' is not @code{NULL}, call the `visit' callback, with arguments `o'
and `arg'.  If `visit' returns a non-zero value, then return it.
Using this macro, @ref{982,,tp_traverse} handlers
look like:

@example
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
@{
    Py_VISIT(self->foo);
    Py_VISIT(self->bar);
    return 0;
@}
@end example
@end deffn

@ref{4ee2,,tp_clear} ハンドラは @ref{51ab,,inquiry} 型であるか、オブジェクトが不変 (immutable) な場合は @code{NULL} でなければなりません。

@geindex inquiry (C type)
@anchor{c-api/gcsupport c inquiry}@anchor{51ab}
@deffn {C のデータ型} typedef int (*inquiry)(@ref{5df,,PyObject} *self)
` 次に属します: @ref{775,,Stable ABI}.'
循環参照を形成しているとおぼしき参照群を放棄します。変更不可能なオブジェクトは循環参照を直接形成することが決してないので、この関数を定義する必要はありません。このメソッドを呼び出した後でもオブジェクトは有効なままでなければならないので注意してください (参照に対して @ref{790,,Py_DECREF()} を呼ぶだけにしないでください)。ガベージコレクタは、オブジェクトが循環参照を形成していることを検出した際にこのメソッドを呼び出します。
@end deffn

@menu
* Controlling the Garbage Collector State:: 
* Querying Garbage Collector State:: 

@end menu

@node Controlling the Garbage Collector State,Querying Garbage Collector State,,循環参照ガベージコレクションをサポートする
@anchor{c-api/gcsupport controlling-the-garbage-collector-state}@anchor{566e}
@subsubsection Controlling the Garbage Collector State


The C-API provides the following functions for controlling
garbage collection runs.

@geindex PyGC_Collect (C function)
@anchor{c-api/gcsupport c PyGC_Collect}@anchor{b85}
@deffn {C の関数} @ref{c55,,Py_ssize_t} PyGC_Collect (void)
` 次に属します: @ref{775,,Stable ABI}.'
Perform a full garbage collection, if the garbage collector is enabled.
(Note that @ref{1b3,,gc.collect()} runs it unconditionally.)

Returns the number of collected + unreachable objects which cannot
be collected.
If the garbage collector is disabled or already collecting,
returns @code{0} immediately.
Errors during garbage collection are passed to @ref{507,,sys.unraisablehook}.
This function does not raise exceptions.
@end deffn

@geindex PyGC_Enable (C function)
@anchor{c-api/gcsupport c PyGC_Enable}@anchor{aa4}
@deffn {C の関数} int PyGC_Enable (void)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Enable the garbage collector: similar to @ref{4a0e,,gc.enable()}.
Returns the previous state, 0 for disabled and 1 for enabled.


Added in version 3.10.

@end deffn

@geindex PyGC_Disable (C function)
@anchor{c-api/gcsupport c PyGC_Disable}@anchor{aa5}
@deffn {C の関数} int PyGC_Disable (void)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Disable the garbage collector: similar to @ref{4a0f,,gc.disable()}.
Returns the previous state, 0 for disabled and 1 for enabled.


Added in version 3.10.

@end deffn

@geindex PyGC_IsEnabled (C function)
@anchor{c-api/gcsupport c PyGC_IsEnabled}@anchor{aa6}
@deffn {C の関数} int PyGC_IsEnabled (void)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.10 より).'
Query the state of the garbage collector: similar to @ref{4a10,,gc.isenabled()}.
Returns the current state, 0 for disabled and 1 for enabled.


Added in version 3.10.

@end deffn

@node Querying Garbage Collector State,,Controlling the Garbage Collector State,循環参照ガベージコレクションをサポートする
@anchor{c-api/gcsupport querying-garbage-collector-state}@anchor{566f}
@subsubsection Querying Garbage Collector State


The C-API provides the following interface for querying information about
the garbage collector.

@geindex PyUnstable_GC_VisitObjects (C function)
@anchor{c-api/gcsupport c PyUnstable_GC_VisitObjects}@anchor{5670}
@deffn {C の関数} void PyUnstable_GC_VisitObjects (gcvisitobjects_t callback, void *arg)

@cartouche
@quotation これは Unstable APIです。マイナーリリースで予告なく変更されることがあります。 `これは @ref{769,,Unstable API}です。マイナーリリースで予告なく変更されることがあります。'
@end quotation
@end cartouche

Run supplied `callback' on all live GC-capable objects. `arg' is passed through to
all invocations of `callback'.

@cartouche
@quotation 警告 
If new objects are (de)allocated by the callback it is undefined if they
will be visited.

Garbage collection is disabled during operation. Explicitly running a collection
in the callback may lead to undefined behaviour e.g. visiting the same objects
multiple times or not at all.
@end quotation
@end cartouche


Added in version 3.12.

@end deffn

@geindex gcvisitobjects_t (C type)
@anchor{c-api/gcsupport c gcvisitobjects_t}@anchor{5671}
@deffn {C のデータ型} typedef int (*gcvisitobjects_t)(@ref{5df,,PyObject} *object, void *arg)

Type of the visitor function to be passed to @ref{5670,,PyUnstable_GC_VisitObjects()}.
`arg' is the same as the `arg' passed to @code{PyUnstable_GC_VisitObjects}.
Return @code{1} to continue iteration, return @code{0} to stop iteration. Other return
values are reserved for now so behavior on returning anything else is undefined.


Added in version 3.12.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node API と ABI のバージョニング,Monitoring C API,オブジェクト実装サポート object implementation support,Python/C API リファレンスマニュアル
@anchor{c-api/apiabiversion doc}@anchor{5672}@anchor{c-api/apiabiversion api-and-abi-versioning}@anchor{5673}@anchor{c-api/apiabiversion apiabiversion}@anchor{4922}@anchor{c-api/apiabiversion translation-repo}@anchor{5674}
@section API と ABI のバージョニング


@menu
* Build-time version constants:: 
* Run-time version:: 
* Bit-packing macros:: 

@end menu

@node Build-time version constants,Run-time version,,API と ABI のバージョニング
@anchor{c-api/apiabiversion build-time-version-constants}@anchor{5675}
@subsection Build-time version constants


CPython exposes its version number in the following macros.
Note that these correspond to the version code is `built' with.
See @ref{381,,Py_Version} for the version used at `run time'.

バージョン間の API と ABI の安定性については @ref{775,,C API の安定性} を参照してください。

@geindex PY_MAJOR_VERSION (C macro)
@anchor{c-api/apiabiversion c PY_MAJOR_VERSION}@anchor{5676}
@deffn {C のマクロ} PY_MAJOR_VERSION

@code{3.4.1a2} の @code{3} 。
@end deffn

@geindex PY_MINOR_VERSION (C macro)
@anchor{c-api/apiabiversion c PY_MINOR_VERSION}@anchor{5677}
@deffn {C のマクロ} PY_MINOR_VERSION

@code{3.4.1a2} の @code{4} 。
@end deffn

@geindex PY_MICRO_VERSION (C macro)
@anchor{c-api/apiabiversion c PY_MICRO_VERSION}@anchor{5678}
@deffn {C のマクロ} PY_MICRO_VERSION

@code{3.4.1a2} の @code{1} 。
@end deffn

@geindex PY_RELEASE_LEVEL (C macro)
@anchor{c-api/apiabiversion c PY_RELEASE_LEVEL}@anchor{5679}
@deffn {C のマクロ} PY_RELEASE_LEVEL

@code{3.4.1a2} の @code{a} 。アルファでは @code{0xA} 、ベータでは @code{0xB} 、リリース候補では @code{0xC} 、最終版では @code{0xF} となります。
@end deffn

@geindex PY_RELEASE_SERIAL (C macro)
@anchor{c-api/apiabiversion c PY_RELEASE_SERIAL}@anchor{567a}
@deffn {C のマクロ} PY_RELEASE_SERIAL

@code{3.4.1a2} の @code{2} 。最終リリースでは 0 になります。
@end deffn

@geindex PY_VERSION_HEX (C macro)
@anchor{c-api/apiabiversion c PY_VERSION_HEX}@anchor{382}
@deffn {C のマクロ} PY_VERSION_HEX

The Python version number encoded in a single integer.
See @ref{380,,Py_PACK_FULL_VERSION()} for the encoding details.

Use this for numeric comparisons, for example,
@code{#if PY_VERSION_HEX >= ...}.
@end deffn

These macros are defined in Include/patchlevel.h@footnote{https://github.com/python/cpython/tree/3.14/Include/patchlevel.h}.

@node Run-time version,Bit-packing macros,Build-time version constants,API と ABI のバージョニング
@anchor{c-api/apiabiversion run-time-version}@anchor{567b}
@subsection Run-time version


@geindex Py_Version (C var)
@anchor{c-api/apiabiversion c Py_Version}@anchor{381}
@deffn {C 変数} const unsigned long Py_Version
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.11 より).'
The Python runtime version number encoded in a single constant integer.
See @ref{380,,Py_PACK_FULL_VERSION()} for the encoding details.
This contains the Python version used at run time.

Use this for numeric comparisons, for example, @code{if (Py_Version >= ...)}.


Added in version 3.11.

@end deffn

@node Bit-packing macros,,Run-time version,API と ABI のバージョニング
@anchor{c-api/apiabiversion bit-packing-macros}@anchor{567c}
@subsection Bit-packing macros


@geindex Py_PACK_FULL_VERSION (C function)
@anchor{c-api/apiabiversion c Py_PACK_FULL_VERSION}@anchor{380}
@deffn {C の関数} uint32_t Py_PACK_FULL_VERSION (int major, int minor, int micro, int release_level, int release_serial)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Return the given version, encoded as a single 32-bit integer with
the following structure:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

Argument

@tab

No.
of
bits

@tab

Bit mask

@tab

Bit shift

@tab

Example values

@tab

@item

@code{3.4.1a2}

@tab

@code{3.10.0}

@item

`major'

@tab

8

@tab

@code{0xFF000000}

@tab

24

@tab

@code{0x03}

@tab

@code{0x03}

@item

`minor'

@tab

8

@tab

@code{0x00FF0000}

@tab

16

@tab

@code{0x04}

@tab

@code{0x0A}

@item

`micro'

@tab

8

@tab

@code{0x0000FF00}

@tab

8

@tab

@code{0x01}

@tab

@code{0x00}

@item

`release_level'

@tab

4

@tab

@code{0x000000F0}

@tab

4

@tab

@code{0xA}

@tab

@code{0xF}

@item

`release_serial'

@tab

4

@tab

@code{0x0000000F}

@tab

0

@tab

@code{0x2}

@tab

@code{0x0}

@end multitable


例えば:


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} 
@headitem

Version

@tab

@code{Py_PACK_FULL_VERSION} arguments

@tab

Encoded version

@item

@code{3.4.1a2}

@tab

@code{(3, 4, 1, 0xA, 2)}

@tab

@code{0x030401a2}

@item

@code{3.10.0}

@tab

@code{(3, 10, 0, 0xF, 0)}

@tab

@code{0x030a00f0}

@end multitable


Out-of range bits in the arguments are ignored.
That is, the macro can be defined as:

@example
#ifndef Py_PACK_FULL_VERSION
#define Py_PACK_FULL_VERSION(X, Y, Z, LEVEL, SERIAL) ( \
   (((X) & 0xff) << 24) |                              \
   (((Y) & 0xff) << 16) |                              \
   (((Z) & 0xff) << 8) |                               \
   (((LEVEL) & 0xf) << 4) |                            \
   (((SERIAL) & 0xf) << 0))
#endif
@end example

@code{Py_PACK_FULL_VERSION} is primarily a macro, intended for use in
@code{#if} directives, but it is also available as an exported function.


Added in version 3.14.

@end deffn

@geindex Py_PACK_VERSION (C function)
@anchor{c-api/apiabiversion c Py_PACK_VERSION}@anchor{37f}
@deffn {C の関数} uint32_t Py_PACK_VERSION (int major, int minor)
` 次に属します: @ref{775,,Stable ABI} (バージョン 3.14 より).'
Equivalent to @code{Py_PACK_FULL_VERSION(major, minor, 0, 0, 0)}.
The result does not correspond to any Python release, but is useful
in numeric comparisons.


Added in version 3.14.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Monitoring C API,Generating Execution Events,API と ABI のバージョニング,Python/C API リファレンスマニュアル
@anchor{c-api/monitoring doc}@anchor{567d}@anchor{c-api/monitoring c-api-monitoring}@anchor{485}@anchor{c-api/monitoring monitoring-c-api}@anchor{567e}@anchor{c-api/monitoring translation-repo}@anchor{567f}
@section Monitoring C API


Added in version 3.13.

An extension may need to interact with the event monitoring system. Subscribing
to events and registering callbacks can be done via the Python API exposed in
@ref{e0,,sys.monitoring}.

@node Generating Execution Events,,Monitoring C API,Python/C API リファレンスマニュアル
@anchor{c-api/monitoring generating-execution-events}@anchor{5680}
@section Generating Execution Events


The functions below make it possible for an extension to fire monitoring
events as it emulates the execution of Python code. Each of these functions
accepts a @code{PyMonitoringState} struct which contains concise information
about the activation state of events, as well as the event arguments, which
include a @code{PyObject*} representing the code object, the instruction offset
and sometimes additional, event-specific arguments (see @ref{e0,,sys.monitoring}
for details about the signatures of the different event callbacks).
The @code{codelike} argument should be an instance of @ref{32f,,types.CodeType}
or of a type that emulates it.

The VM disables tracing when firing an event, so there is no need for user
code to do that.

Monitoring functions should not be called with an exception set,
except those listed below as working with the current exception.

@geindex PyMonitoringState (C type)
@anchor{c-api/monitoring c PyMonitoringState}@anchor{5be}
@deffn {C のデータ型} type PyMonitoringState

Representation of the state of an event type. It is allocated by the user
while its contents are maintained by the monitoring API functions described below.
@end deffn

All of the functions below return 0 on success and -1 (with an exception set) on error.

See @ref{e0,,sys.monitoring} for descriptions of the events.

@geindex PyMonitoring_FirePyStartEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FirePyStartEvent}@anchor{5bf}
@deffn {C の関数} int PyMonitoring_FirePyStartEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire a @code{PY_START} event.
@end deffn

@geindex PyMonitoring_FirePyResumeEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FirePyResumeEvent}@anchor{5c0}
@deffn {C の関数} int PyMonitoring_FirePyResumeEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire a @code{PY_RESUME} event.
@end deffn

@geindex PyMonitoring_FirePyReturnEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FirePyReturnEvent}@anchor{5c1}
@deffn {C の関数} int PyMonitoring_FirePyReturnEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *retval)

Fire a @code{PY_RETURN} event.
@end deffn

@geindex PyMonitoring_FirePyYieldEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FirePyYieldEvent}@anchor{5c2}
@deffn {C の関数} int PyMonitoring_FirePyYieldEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *retval)

Fire a @code{PY_YIELD} event.
@end deffn

@geindex PyMonitoring_FireCallEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireCallEvent}@anchor{5c3}
@deffn {C の関数} int PyMonitoring_FireCallEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *callable, PyObject *arg0)

Fire a @code{CALL} event.
@end deffn

@geindex PyMonitoring_FireLineEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireLineEvent}@anchor{5c4}
@deffn {C の関数} int PyMonitoring_FireLineEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, int lineno)

Fire a @code{LINE} event.
@end deffn

@geindex PyMonitoring_FireJumpEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireJumpEvent}@anchor{5c5}
@deffn {C の関数} int PyMonitoring_FireJumpEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *target_offset)

Fire a @code{JUMP} event.
@end deffn

@geindex PyMonitoring_FireBranchLeftEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireBranchLeftEvent}@anchor{3ad}
@deffn {C の関数} int PyMonitoring_FireBranchLeftEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *target_offset)

Fire a @code{BRANCH_LEFT} event.
@end deffn

@geindex PyMonitoring_FireBranchRightEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireBranchRightEvent}@anchor{3ae}
@deffn {C の関数} int PyMonitoring_FireBranchRightEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *target_offset)

Fire a @code{BRANCH_RIGHT} event.
@end deffn

@geindex PyMonitoring_FireCReturnEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireCReturnEvent}@anchor{5c6}
@deffn {C の関数} int PyMonitoring_FireCReturnEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *retval)

Fire a @code{C_RETURN} event.
@end deffn

@geindex PyMonitoring_FirePyThrowEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FirePyThrowEvent}@anchor{5c7}
@deffn {C の関数} int PyMonitoring_FirePyThrowEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire a @code{PY_THROW} event with the current exception (as returned by
@ref{429,,PyErr_GetRaisedException()}).
@end deffn

@geindex PyMonitoring_FireRaiseEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireRaiseEvent}@anchor{5c8}
@deffn {C の関数} int PyMonitoring_FireRaiseEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire a @code{RAISE} event with the current exception (as returned by
@ref{429,,PyErr_GetRaisedException()}).
@end deffn

@geindex PyMonitoring_FireCRaiseEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireCRaiseEvent}@anchor{5c9}
@deffn {C の関数} int PyMonitoring_FireCRaiseEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire a @code{C_RAISE} event with the current exception (as returned by
@ref{429,,PyErr_GetRaisedException()}).
@end deffn

@geindex PyMonitoring_FireReraiseEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireReraiseEvent}@anchor{5ca}
@deffn {C の関数} int PyMonitoring_FireReraiseEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire a @code{RERAISE} event with the current exception (as returned by
@ref{429,,PyErr_GetRaisedException()}).
@end deffn

@geindex PyMonitoring_FireExceptionHandledEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireExceptionHandledEvent}@anchor{5cb}
@deffn {C の関数} int PyMonitoring_FireExceptionHandledEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire an @code{EXCEPTION_HANDLED} event with the current exception (as returned by
@ref{429,,PyErr_GetRaisedException()}).
@end deffn

@geindex PyMonitoring_FirePyUnwindEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FirePyUnwindEvent}@anchor{5cc}
@deffn {C の関数} int PyMonitoring_FirePyUnwindEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset)

Fire a @code{PY_UNWIND} event with the current exception (as returned by
@ref{429,,PyErr_GetRaisedException()}).
@end deffn

@geindex PyMonitoring_FireStopIterationEvent (C function)
@anchor{c-api/monitoring c PyMonitoring_FireStopIterationEvent}@anchor{5cd}
@deffn {C の関数} int PyMonitoring_FireStopIterationEvent (PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *value)

Fire a @code{STOP_ITERATION} event. If @code{value} is an instance of @ref{df5,,StopIteration}, it is used. Otherwise,
a new @ref{df5,,StopIteration} instance is created with @code{value} as its argument.
@end deffn

@menu
* Managing the Monitoring State:: 

@end menu

@node Managing the Monitoring State,,,Generating Execution Events
@anchor{c-api/monitoring managing-the-monitoring-state}@anchor{5681}
@subsection Managing the Monitoring State


Monitoring states can be managed with the help of monitoring scopes. A scope
would typically correspond to a Python function.

@geindex PyMonitoring_EnterScope (C function)
@anchor{c-api/monitoring c PyMonitoring_EnterScope}@anchor{5ce}
@deffn {C の関数} int PyMonitoring_EnterScope (PyMonitoringState *state_array, uint64_t *version, const uint8_t *event_types, Py_ssize_t length)

Enter a monitored scope. @code{event_types} is an array of the event IDs for
events that may be fired from the scope. For example, the ID of a @code{PY_START}
event is the value @code{PY_MONITORING_EVENT_PY_START}, which is numerically equal
to the base-2 logarithm of @code{sys.monitoring.events.PY_START}.
@code{state_array} is an array with a monitoring state entry for each event in
@code{event_types}, it is allocated by the user but populated by
@code{PyMonitoring_EnterScope()} with information about the activation state of
the event. The size of @code{event_types} (and hence also of @code{state_array})
is given in @code{length}.

The @code{version} argument is a pointer to a value which should be allocated
by the user together with @code{state_array} and initialized to 0,
and then set only by @code{PyMonitoring_EnterScope()} itself. It allows this
function to determine whether event states have changed since the previous call,
and to return quickly if they have not.

The scopes referred to here are lexical scopes: a function, class or method.
@code{PyMonitoring_EnterScope()} should be called whenever the lexical scope is
entered. Scopes can be reentered, reusing the same `state_array' and `version',
in situations like when emulating a recursive Python function. When a code-like's
execution is paused, such as when emulating a generator, the scope needs to
be exited and re-entered.

The macros for `event_types' are:

@c The table is here to make the docs searchable, and to allow automatic
@c links to the identifiers.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Macro

@tab

Event

@item

@geindex PY_MONITORING_EVENT_BRANCH_LEFT (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_BRANCH_LEFT}@anchor{5682}
@deffn {C のマクロ} PY_MONITORING_EVENT_BRANCH_LEFT
@end deffn

@tab

@ref{295,,BRANCH_LEFT}

@item

@geindex PY_MONITORING_EVENT_BRANCH_RIGHT (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_BRANCH_RIGHT}@anchor{5683}
@deffn {C のマクロ} PY_MONITORING_EVENT_BRANCH_RIGHT
@end deffn

@tab

@ref{296,,BRANCH_RIGHT}

@item

@geindex PY_MONITORING_EVENT_CALL (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_CALL}@anchor{5684}
@deffn {C のマクロ} PY_MONITORING_EVENT_CALL
@end deffn

@tab

@ref{19bd,,CALL}

@item

@geindex PY_MONITORING_EVENT_C_RAISE (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_C_RAISE}@anchor{5685}
@deffn {C のマクロ} PY_MONITORING_EVENT_C_RAISE
@end deffn

@tab

@ref{493a,,C_RAISE}

@item

@geindex PY_MONITORING_EVENT_C_RETURN (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_C_RETURN}@anchor{5686}
@deffn {C のマクロ} PY_MONITORING_EVENT_C_RETURN
@end deffn

@tab

@ref{493b,,C_RETURN}

@item

@geindex PY_MONITORING_EVENT_EXCEPTION_HANDLED (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_EXCEPTION_HANDLED}@anchor{5687}
@deffn {C のマクロ} PY_MONITORING_EVENT_EXCEPTION_HANDLED
@end deffn

@tab

@ref{493c,,EXCEPTION_HANDLED}

@item

@geindex PY_MONITORING_EVENT_INSTRUCTION (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_INSTRUCTION}@anchor{5688}
@deffn {C のマクロ} PY_MONITORING_EVENT_INSTRUCTION
@end deffn

@tab

@ref{493d,,INSTRUCTION}

@item

@geindex PY_MONITORING_EVENT_JUMP (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_JUMP}@anchor{5689}
@deffn {C のマクロ} PY_MONITORING_EVENT_JUMP
@end deffn

@tab

@ref{493e,,JUMP}

@item

@geindex PY_MONITORING_EVENT_LINE (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_LINE}@anchor{568a}
@deffn {C のマクロ} PY_MONITORING_EVENT_LINE
@end deffn

@tab

@ref{493f,,LINE}

@item

@geindex PY_MONITORING_EVENT_PY_RESUME (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_PY_RESUME}@anchor{568b}
@deffn {C のマクロ} PY_MONITORING_EVENT_PY_RESUME
@end deffn

@tab

@ref{4940,,PY_RESUME}

@item

@geindex PY_MONITORING_EVENT_PY_RETURN (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_PY_RETURN}@anchor{568c}
@deffn {C のマクロ} PY_MONITORING_EVENT_PY_RETURN
@end deffn

@tab

@ref{4941,,PY_RETURN}

@item

@geindex PY_MONITORING_EVENT_PY_START (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_PY_START}@anchor{568d}
@deffn {C のマクロ} PY_MONITORING_EVENT_PY_START
@end deffn

@tab

@ref{4942,,PY_START}

@item

@geindex PY_MONITORING_EVENT_PY_THROW (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_PY_THROW}@anchor{568e}
@deffn {C のマクロ} PY_MONITORING_EVENT_PY_THROW
@end deffn

@tab

@ref{1855,,PY_THROW}

@item

@geindex PY_MONITORING_EVENT_PY_UNWIND (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_PY_UNWIND}@anchor{568f}
@deffn {C のマクロ} PY_MONITORING_EVENT_PY_UNWIND
@end deffn

@tab

@ref{4943,,PY_UNWIND}

@item

@geindex PY_MONITORING_EVENT_PY_YIELD (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_PY_YIELD}@anchor{5690}
@deffn {C のマクロ} PY_MONITORING_EVENT_PY_YIELD
@end deffn

@tab

@ref{4944,,PY_YIELD}

@item

@geindex PY_MONITORING_EVENT_RAISE (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_RAISE}@anchor{5691}
@deffn {C のマクロ} PY_MONITORING_EVENT_RAISE
@end deffn

@tab

@ref{1974,,RAISE}

@item

@geindex PY_MONITORING_EVENT_RERAISE (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_RERAISE}@anchor{5692}
@deffn {C のマクロ} PY_MONITORING_EVENT_RERAISE
@end deffn

@tab

@ref{4946,,RERAISE}

@item

@geindex PY_MONITORING_EVENT_STOP_ITERATION (C macro)
@anchor{c-api/monitoring c PY_MONITORING_EVENT_STOP_ITERATION}@anchor{5693}
@deffn {C のマクロ} PY_MONITORING_EVENT_STOP_ITERATION
@end deffn

@tab

@ref{4945,,STOP_ITERATION}

@end multitable

@end deffn

@geindex PyMonitoring_ExitScope (C function)
@anchor{c-api/monitoring c PyMonitoring_ExitScope}@anchor{5cf}
@deffn {C の関数} int PyMonitoring_ExitScope (void)

Exit the last scope that was entered with @code{PyMonitoring_EnterScope()}.
@end deffn

@geindex PY_MONITORING_IS_INSTRUMENTED_EVENT (C function)
@anchor{c-api/monitoring c PY_MONITORING_IS_INSTRUMENTED_EVENT}@anchor{5694}
@deffn {C の関数} int PY_MONITORING_IS_INSTRUMENTED_EVENT (uint8_t ev)

Return true if the event corresponding to the event ID `ev' is
a @ref{494a,,local event}.


Added in version 3.13.



バージョン 3.14 で非推奨: This function is @ref{23d,,soft deprecated}.

@end deffn

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python モジュールのインストール,Python HOWTO,Python/C API リファレンスマニュアル,Top
@anchor{installing/index doc}@anchor{5695}@anchor{installing/index installing-index}@anchor{10f8}@anchor{installing/index installing-python-modules}@anchor{5696}@anchor{installing/index translation-repo}@anchor{5697}
@chapter Python モジュールのインストール


@*Email: 
@email{distutils-sig@@python.org}


人気のあるオープンソース開発プロジェクトがそうであるように、Python には貢献者たちとユーザたちの活発なサポートコミュニティがあり、またこれらはほかの Python 開発者たちに、彼らのソフトウェアのオープンソースライセンスのもとでの利用も可能にしてくれています。

これはほかの人が既に挙げた共通の(あるいは時折極めて稀有な!)問題や、彼ら自身の解法による潜在的な貢献が共通の場所に蓄えられることによる恩恵によって、Python ユーザに共有と協調を効果的に行なうことの助けとなっています。

このガイドはこれらプロセスのうち、インストールについてをカバーします。あなた自身の Python プロジェクトを作成し、共有するためのガイドについては Python packaging user guide@footnote{https://packaging.python.org/en/latest/tutorials/packaging-projects/} を参照してください。

@cartouche
@quotation 注釈 
あなたが企業や組織のユーザであれば、多くの組織がオープンソースソフトウェアの利用と貢献に関する彼ら独自のポリシーを持っていることに気をつけてください。Python によって提供される配布とインストールのツールを利用する際には、そのようなポリシーを考慮に入れてください。
@end quotation
@end cartouche

@menu
* 重要用語集:: 
* 基本的な使い方: 基本的な使い方<5>. 
* どうすればいいの...？: どうすればいいの ？. 
* よくあるインストールに関する問題:: 

@end menu

@node 重要用語集,基本的な使い方<5>,,Python モジュールのインストール
@anchor{installing/index key-terms}@anchor{5698}
@section 重要用語集



@itemize *

@item 
@code{pip} は推奨されるインストーラ・プログラムです。 Python 3.4 からは、 Python バイナリ・インストーラに最初から付属するようになりました。

@item 
`仮想環境' は、システム全体にインストールするのではなく、特定のアプリケーションで使用するためにパッケージをインストールできるようにする半独立型のPython環境です。

@item 
@code{venv} は仮想環境をつくるための標準ツールです。 Python 3.3 から Python の一部になりました。 Python 3.4 以降では、仮想環境をつくる際はそのすべてで @code{pip} をインストールするように、あらかじめ設定されています。

@item 
@code{virtualenv} は @code{venv} のサードパーティの代替案 (で前身) です。
@code{virtualenv} により仮想環境を Python 3.4 より前のバージョンで使うことが出来ます。
以前のバージョンは @code{venv} を提供していませんし、作成された環境に @code{pip} を自動的にインストールすることも出来ません。

@item 
Python Package Index@footnote{https://pypi.org} は Python パッケージのパブリック・リポジトリです。このリポジトリのパッケージは、他の Python ユーザが利用できるように、オープンソースでライセンスされています。

@item 
Python Packaging Authority@footnote{https://www.pypa.io/} は、標準のパッケージングツール、関連するメタデータとファイルフォーマット標準の保守と発展を担っている、開発者・ドキュメントの著者のグループです。彼らは様々なツールやドキュメント、issue tracker を GitHub@footnote{https://github.com/pypa} で管理しています。

@item 
@code{distutils} はオリジナルのビルド・配布システムで、 Python 標準ライブラリに 1998 年に最初に追加されました。 @code{distutils} の直接的な利用は段階的に取り払われていきますが、それは今でも現時点でのパッケージングと配布のインフラストラクチャの基礎として鎮座していて、標準ライブラリの一部として残っているだけでなく、その名前はほかの文脈でも生き続けています(Python のパッケージング標準の開発をまとめるのに使われているメーリングリストの名前のように)。
@end itemize


バージョン 3.5 で変更: 仮想環境の作成には、 @code{venv} の使用をお勧めします。



@subsubheading 参考


Python Packaging User Guide: Creating and using virtual environments@footnote{https://packaging.python.org/installing/#creating-virtual-environments}


@node 基本的な使い方<5>,どうすればいいの ？,重要用語集,Python モジュールのインストール
@anchor{installing/index basic-usage}@anchor{5699}
@section 基本的な使い方


パッケージングのための標準ツールはすべてコマンドラインから使われることを想定しています。

以下のコマンドは、モジュールの最新バージョンとそれが依存するモジュールを、 Python Package Index からインストールします。

@example
python -m pip install SomePackage
@end example

@cartouche
@quotation 注釈 
POSIX ユーザ(macOS と Linux ユーザを含みます)向けには、このガイド内の例は、 @ref{20ee,,virtual environment} の利用を前提にしています。

Windows ユーザ向けには、このガイド内の例は、Python インストール時にシステムの PATH 環境変数が調整されていることを前提にしています。
@end quotation
@end cartouche

正確なバージョンや最小のバージョンをコマンドライン上で直接指定することもできます。@code{>} や @code{<} などの比較演算子など、シェルが解釈する特殊文字を使う場合、パッケージ名とバージョンを二重引用符で囲んでください:

@example
python -m pip install SomePackage==1.0.4    # specific version
python -m pip install "SomePackage>=1.0.4"  # minimum version
@end example

通常、適合するモジュールがインストール済である場合にそれを再度 install 実行を試みても効果はありません。既に存在しているモジュールのアップグレードには、明示的にそれを要求しなければなりません:

@example
python -m pip install --upgrade SomePackage
@end example

@code{pip} とその機能についての詳しい情報とリソースは Python Packaging User Guide@footnote{https://packaging.python.org} にあります。

仮想環境の作成は @ref{117,,venv} モジュールを通して行われます。
有効な仮想環境にインストールするには 上記のコマンドを使います。


@subsubheading 参考


Python Packaging User Guide: Installing Python Distribution Packages@footnote{https://packaging.python.org/installing/}


@node どうすればいいの ？,よくあるインストールに関する問題,基本的な使い方<5>,Python モジュールのインストール
@anchor{installing/index how-do-i}@anchor{569a}
@section どうすればいいの...？


以下はよくある課題への簡単な回答もしくは回答へのリンクです。

@menu
* ... pip を 3.4 より前のバージョンの Python でインストールするには？: pip を 3 4 より前のバージョンの Python でインストールするには？. 
* ... パッケージを現在のユーザ用のみにインストールするには？: パッケージを現在のユーザ用のみにインストールするには？. 
* ... 科学技術計算用の Python パッケージをインストールするには？: 科学技術計算用の Python パッケージをインストールするには？. 
* ... インストールされた複数のバージョンの Python を並行して使うには？: インストールされた複数のバージョンの Python を並行して使うには？. 

@end menu

@node pip を 3 4 より前のバージョンの Python でインストールするには？,パッケージを現在のユーザ用のみにインストールするには？,,どうすればいいの ？
@anchor{installing/index install-pip-in-versions-of-python-prior-to-python-3-4}@anchor{569b}
@subsection ... pip を 3.4 より前のバージョンの Python でインストールするには？


@code{pip} が Python に付属するのは 3.4 以降です。それ以前のバージョンでは、 "Python Packaging User Guide" の記載にしたがって @code{pip} 自体をインストールする必要があります。


@subsubheading 参考


Python Packaging User Guide: Requirements for Installing Packages@footnote{https://packaging.python.org/installing/#requirements-for-installing-packages}


@c installing-per-user-installation:

@node パッケージを現在のユーザ用のみにインストールするには？,科学技術計算用の Python パッケージをインストールするには？,pip を 3 4 より前のバージョンの Python でインストールするには？,どうすればいいの ？
@anchor{installing/index install-packages-just-for-the-current-user}@anchor{569c}
@subsection ... パッケージを現在のユーザ用のみにインストールするには？


@code{python -m pip install} に @code{--user} オプションを付けてください。パッケージはシステムのすべてのユーザ用にではなく、現在のユーザ用のみにインストールされます。

@node 科学技術計算用の Python パッケージをインストールするには？,インストールされた複数のバージョンの Python を並行して使うには？,パッケージを現在のユーザ用のみにインストールするには？,どうすればいいの ？
@anchor{installing/index install-scientific-python-packages}@anchor{569d}
@subsection ... 科学技術計算用の Python パッケージをインストールするには？


科学技術計算用の Python パッケージの多くがバイナリモジュールに複雑に依存しており、現在のところ @code{pip} を直接使ってインストールすることは容易ではありません。現時点では @code{pip} を使ってインストールしようとするよりも、 別の手段@footnote{https://packaging.python.org/science/} を用いてインストールするほうが、多くの場合簡単でしょう。


@subsubheading 参考


Python Packaging User Guide: Installing Scientific Packages@footnote{https://packaging.python.org/science/}


@node インストールされた複数のバージョンの Python を並行して使うには？,,科学技術計算用の Python パッケージをインストールするには？,どうすればいいの ？
@anchor{installing/index work-with-multiple-versions-of-python-installed-in-parallel}@anchor{569e}
@subsection ... インストールされた複数のバージョンの Python を並行して使うには？


Linux や macOS、その他の POSIX システムでは、バージョン番号付きの Python コマンドと @code{-m} スイッチを組み合わせて用いて、適切なバージョンの @code{pip} を実行してください。

@example
python2   -m pip install SomePackage  # default Python 2
python2.7 -m pip install SomePackage  # specifically Python 2.7
python3   -m pip install SomePackage  # default Python 3
python3.4 -m pip install SomePackage  # specifically Python 3.4
@end example

適切にバージョン番号が付された @code{pip} コマンドが使えることもあります。

Windows では、 Python ランチャーの @code{py} を @code{-m} スイッチとの組み合わせで使ってください。

@example
py -2   -m pip install SomePackage  # default Python 2
py -2.7 -m pip install SomePackage  # specifically Python 2.7
py -3   -m pip install SomePackage  # default Python 3
py -3.4 -m pip install SomePackage  # specifically Python 3.4
@end example

@c other questions:
@c 
@c Once the Development & Deployment part of PPUG is fleshed out, some of
@c those sections should be linked from new questions here (most notably,
@c we should have a question about avoiding depending on PyPI that links to
@c https://packaging.python.org/en/latest/guides/index-mirrors-and-caches/)

@node よくあるインストールに関する問題,,どうすればいいの ？,Python モジュールのインストール
@anchor{installing/index common-installation-issues}@anchor{569f}
@section よくあるインストールに関する問題


@menu
* Linux で、システムの Python 内にインストールする:: 
* pip がインストールされていない:: 
* バイナリの拡張のインストール:: 

@end menu

@node Linux で、システムの Python 内にインストールする,pip がインストールされていない,,よくあるインストールに関する問題
@anchor{installing/index installing-into-the-system-python-on-linux}@anchor{56a0}
@subsection Linux で、システムの Python 内にインストールする


Linux システムでは、 Python のインストールは典型的には linux ディストリビューションの一部に含まれています。この Python インストールへのインストールには、システムに対する root 権限が必要で、また、 @code{pip} によって期待されているものとは異なるコンポーネントにアップグレードすることで、システムのパッケージマネージャのオペレーションやシステムのほかのコンポーネントの邪魔をするかもしれません。

そのようなシステムでは、 @code{pip} でパッケージをインストールする際には仮想環境を使うか、ユーザごとのインストールを行うのが、大抵良い方法です。

@node pip がインストールされていない,バイナリの拡張のインストール,Linux で、システムの Python 内にインストールする,よくあるインストールに関する問題
@anchor{installing/index pip-not-installed}@anchor{56a1}
@subsection pip がインストールされていない


@code{pip} がデフォルトでインストールされていないことがあります。
次のコマンドで問題の解決が見込めます:

@example
python -m ensurepip --default-pip
@end example

他にも pip のインストール@footnote{https://packaging.python.org/en/latest/tutorials/installing-packages/#ensure-pip-setuptools-and-wheel-are-up-to-date} についての資料があります。

@node バイナリの拡張のインストール,,pip がインストールされていない,よくあるインストールに関する問題
@anchor{installing/index installing-binary-extensions}@anchor{56a2}
@subsection バイナリの拡張のインストール


Python プロジェクトの多くはソースに基いた配布に強く依存しており、インストールプロセスの一環として、エンドユーザ環境でソースから拡張モジュールをコンパイルすることを期待します。

バイナリ @code{wheel} フォーマットのサポートが導入されたことで、また、少なくとも Windows と macOS についての wheels の公開が Python Package Index を通して出来るようになったことで、この問題についての開発者の時間の節約と、ユーザにとっては自身でビルドせずにビルド済み拡張をインストールするさらなる標準化に繋がるかもしれません。

ビルド済み @code{wheel} ファイルが未だ入手出来ない scientific software@footnote{https://packaging.python.org/science/}  インストールにおけるいくつかの解法が、ローカルにビルドすることなく他のバイナリ拡張を得る助けになるかもしれません。


@subsubheading 参考


Python Packaging User Guide: Binary Extensions@footnote{https://packaging.python.org/extensions/}


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python HOWTO,Python よくある質問,Python モジュールのインストール,Top
@anchor{howto/index doc}@anchor{56a3}@anchor{howto/index how-tos}@anchor{56a4}@anchor{howto/index python-howtos}@anchor{56a5}@anchor{howto/index translation-repo}@anchor{56a6}
@chapter Python HOWTO


Python HOWTOs are documents that cover a specific topic in-depth.
Modeled on the Linux Documentation Project's HOWTO collection, this collection is an
effort to foster documentation that's more detailed than the
Python Library Reference.

@menu
* A Conceptual Overview of asyncio:: 
* Python 3 への拡張モジュール移植:: 
* Python で Curses プログラミング:: 
* デスクリプタ ガイド:: 
* Debugging C API extensions and CPython Internals with GDB:: 
* 列挙型 HOWTO:: 
* 関数型プログラミング HOWTO:: 
* Logging HOWTO:: 
* Logging クックブック:: 
* 正規表現 HOWTO:: 
* ソケットプログラミング HOWTO:: 
* ソートのテクニック:: 
* Unicode HOWTO:: 
* urllib パッケージを使ってインターネット上のリソースを取得するには:: 
* ipaddressモジュールの紹介:: 
* DTrace と SystemTap で CPython を測定する:: 
* Python support for the Linux perf profiler:: 
* Annotations Best Practices:: 
* 拡張モジュールを分離する:: 
* timer file descriptor HOWTO:: 
* The Python 2.3 Method Resolution Order: The Python 2 3 Method Resolution Order. 
* Python support for free threading:: 
* C API Extension Support for Free Threading:: 
* Remote debugging attachment protocol:: 
* Permission requirements:: 
* Locating the PyRuntime structure:: 
* Reading _Py_DebugOffsets:: 
* Locating the interpreter and thread state:: 
* Writing control information:: 
* Summary:: 

@end menu

@node A Conceptual Overview of asyncio,Python 3 への拡張モジュール移植,,Python HOWTO
@anchor{howto/a-conceptual-overview-of-asyncio doc}@anchor{56a7}@anchor{howto/a-conceptual-overview-of-asyncio a-conceptual-overview-of-asyncio}@anchor{37b7}@anchor{howto/a-conceptual-overview-of-asyncio id1}@anchor{56a8}
@section A Conceptual Overview of @code{asyncio}


This @ref{56a4,,HOWTO} article seeks to help you build a sturdy mental
model of how @ref{b,,asyncio} fundamentally works, helping you understand the
how and why behind the recommended patterns.

You might be curious about some key @code{asyncio} concepts.
By the end of this article, you'll be able to comfortably answer these questions:


@itemize -

@item 
What's happening behind the scenes when an object is awaited?

@item 
How does @code{asyncio} differentiate between a task which doesn't need
CPU time (such as a network request or file read) as opposed to a task that
does (such as computing n-factorial)?

@item 
How to write an asynchronous variant of an operation, such as
an async sleep or database request.
@end itemize


@subsubheading 参考



@itemize *

@item 
The guide@footnote{https://github.com/anordin95/a-conceptual-overview-of-asyncio/tree/main} that inspired this HOWTO article, by Alexander Nordin.

@item 
This in-depth YouTube tutorial series@footnote{https://www.youtube.com/watch?v=Xbl7XjFYsN4&list=PLhNSoGM2ik6SIkVGXWBwerucXjgP1rHmB} on
@code{asyncio} created by Python core team member, Łukasz Langa.

@item 
500 Lines or Less: A Web Crawler With asyncio Coroutines@footnote{https://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html} by A.
Jesse Jiryu Davis and Guido van Rossum.
@end itemize


@menu
* A conceptual overview part 1; the high-level: A conceptual overview part 1 the high-level. 
* A conceptual overview part 2; the nuts and bolts: A conceptual overview part 2 the nuts and bolts. 

@end menu

@node A conceptual overview part 1 the high-level,A conceptual overview part 2 the nuts and bolts,,A Conceptual Overview of asyncio
@anchor{howto/a-conceptual-overview-of-asyncio a-conceptual-overview-part-1-the-high-level}@anchor{56a9}
@subsection A conceptual overview part 1: the high-level


In part 1, we'll cover the main, high-level building blocks of @code{asyncio}:
the event loop, coroutine functions, coroutine objects, tasks, and @code{await}.

@menu
* イベントループ: イベントループ<2>. 
* Asynchronous functions and coroutines:: 
* Task: Task<2>. 
* await:: 

@end menu

@node イベントループ<2>,Asynchronous functions and coroutines,,A conceptual overview part 1 the high-level
@anchor{howto/a-conceptual-overview-of-asyncio event-loop}@anchor{56aa}
@subsubsection イベントループ


Everything in @code{asyncio} happens relative to the event loop.
It's the star of the show.
It's like an orchestra conductor.
It's behind the scenes managing resources.
Some power is explicitly granted to it, but a lot of its ability to get things
done comes from the respect and cooperation of its worker bees.

In more technical terms, the event loop contains a collection of jobs to be run.
Some jobs are added directly by you, and some indirectly by @code{asyncio}.
The event loop takes a job from its backlog of work and invokes it (or "gives
it control"), similar to calling a function, and then that job runs.
Once it pauses or completes, it returns control to the event loop.
The event loop will then select another job from its pool and invoke it.
You can `roughly' think of the collection of jobs as a queue: jobs are added and
then processed one at a time, generally (but not always) in order.
This process repeats indefinitely, with the event loop cycling endlessly
onwards.
If there are no more jobs pending execution, the event loop is smart enough to
rest and avoid needlessly wasting CPU cycles, and will come back when there's
more work to be done.

Effective execution relies on jobs sharing well and cooperating; a greedy job
could hog control and leave the other jobs to starve, rendering the overall
event loop approach rather useless.

@example
import asyncio

# This creates an event loop and indefinitely cycles through
# its collection of jobs.
event_loop = asyncio.new_event_loop()
event_loop.run_forever()
@end example

@node Asynchronous functions and coroutines,Task<2>,イベントループ<2>,A conceptual overview part 1 the high-level
@anchor{howto/a-conceptual-overview-of-asyncio asynchronous-functions-and-coroutines}@anchor{56ab}
@subsubsection Asynchronous functions and coroutines


This is a basic, boring Python function:

@example
def hello_printer():
    print(
        "Hi, I am a lowly, simple printer, though I have all I "
        "need in life -- \nfresh paper and my dearly beloved octopus "
        "partner in crime."
    )
@end example

Calling a regular function invokes its logic or body:

@example
>>> hello_printer()
Hi, I am a lowly, simple printer, though I have all I need in life --
fresh paper and my dearly beloved octopus partner in crime.
@end example

The @ref{7ed,,async def}, as opposed to just a plain @code{def}, makes
this an asynchronous function (or "coroutine function").
Calling it creates and returns a @ref{37b8,,coroutine} object.

@example
async def loudmouth_penguin(magic_number: int):
    print(
     "I am a super special talking penguin. Far cooler than that printer. "
     f"By the way, my lucky number is: @{magic_number@}."
    )
@end example

Calling the async function, @code{loudmouth_penguin}, does not execute the print statement;
instead, it creates a coroutine object:

@example
>>> loudmouth_penguin(magic_number=3)
<coroutine object loudmouth_penguin at 0x104ed2740>
@end example

The terms "coroutine function" and "coroutine object" are often conflated
as coroutine.
That can be confusing!
In this article, coroutine specifically refers to a coroutine object, or more
precisely, an instance of @ref{1089,,types.CoroutineType} (native coroutine).
Note that coroutines can also exist as instances of
@ref{fdd,,collections.abc.Coroutine} -- a distinction that matters for type
checking.

A coroutine represents the function's body or logic.
A coroutine has to be explicitly started; again, merely creating the coroutine
does not start it.
Notably, the coroutine can be paused and resumed at various points within the
function's body.
That pausing and resuming ability is what allows for asynchronous behavior!

Coroutines and coroutine functions were built by leveraging the functionality
of @ref{dd9,,generators} and
@ref{126c,,generator functions}.
Recall, a generator function is a function that @ref{bc2,,yield}s, like this
one:

@example
def get_random_number():
    # This would be a bad random number generator!
    print("Hi")
    yield 1
    print("Hello")
    yield 7
    print("Howdy")
    yield 4
    ...
@end example

Similar to a coroutine function, calling a generator function does not run it.
Instead, it creates a generator object:

@example
>>> get_random_number()
<generator object get_random_number at 0x1048671c0>
@end example

You can proceed to the next @code{yield} of a generator by using the
built-in function @ref{9d8,,next()}.
In other words, the generator runs, then pauses.
For example:

@example
>>> generator = get_random_number()
>>> next(generator)
Hi
1
>>> next(generator)
Hello
7
@end example

@node Task<2>,await,Asynchronous functions and coroutines,A conceptual overview part 1 the high-level
@anchor{howto/a-conceptual-overview-of-asyncio tasks}@anchor{56ac}
@subsubsection Task


Roughly speaking, @ref{37ea,,tasks} are coroutines (not coroutine
functions) tied to an event loop.
A task also maintains a list of callback functions whose importance will become
clear in a moment when we discuss @ref{18d,,await}.
The recommended way to create tasks is via @ref{1c9,,asyncio.create_task()}.

Creating a task automatically schedules it for execution (by adding a
callback to run it in the event loop's to-do list, that is, collection of jobs).

@code{asyncio} automatically associates tasks with the event loop for you.
This automatic association was purposely designed into @code{asyncio} for
the sake of simplicity.
Without it, you'd have to keep track of the event loop object and pass it to
any coroutine function that wants to create tasks, adding redundant clutter
to your code.

@example
coroutine = loudmouth_penguin(magic_number=5)
# This creates a Task object and schedules its execution via the event loop.
task = asyncio.create_task(coroutine)
@end example

Earlier, we manually created the event loop and set it to run forever.
In practice, it's recommended to use (and common to see) @ref{2f3,,asyncio.run()},
which takes care of managing the event loop and ensuring the provided
coroutine finishes before advancing.
For example, many async programs follow this setup:

@example
import asyncio

async def main():
    # Perform all sorts of wacky, wild asynchronous things...
    ...

if __name__ == "__main__":
    asyncio.run(main())
    # The program will not reach the following print statement until the
    # coroutine main() finishes.
    print("coroutine main() is done!")
@end example

It's important to be aware that the task itself is not added to the event loop,
only a callback to the task is.
This matters if the task object you created is garbage collected before it's
called by the event loop.
For example, consider this program:

@example
async def hello():
    print("hello!")

async def main():
    asyncio.create_task(hello())
    # Other asynchronous instructions which run for a while
    # and cede control to the event loop...
    ...

asyncio.run(main())
@end example

Because there's no reference to the task object created on line 5, it `might'
be garbage collected before the event loop invokes it.
Later instructions in the coroutine @code{main()} hand control back to the event
loop so it can invoke other jobs.
When the event loop eventually tries to run the task, it might fail and
discover the task object does not exist!
This can also happen even if a coroutine keeps a reference to a task but
completes before that task finishes.
When the coroutine exits, local variables go out of scope and may be subject
to garbage collection.
In practice, @code{asyncio} and Python's garbage collector work pretty hard to
ensure this sort of thing doesn't happen.
But that's no reason to be reckless!

@node await,,Task<2>,A conceptual overview part 1 the high-level
@anchor{howto/a-conceptual-overview-of-asyncio await}@anchor{56ad}
@subsubsection await


@ref{18d,,await} is a Python keyword that's commonly used in one of two
different ways:

@example
await task
await coroutine
@end example

In a crucial way, the behavior of @code{await} depends on the type of object
being awaited.

Awaiting a task will cede control from the current task or coroutine to
the event loop.
In the process of relinquishing control, a few important things happen.
We'll use the following code example to illustrate:

@example
async def plant_a_tree():
    dig_the_hole_task = asyncio.create_task(dig_the_hole())
    await dig_the_hole_task

    # Other instructions associated with planting a tree.
    ...
@end example

In this example, imagine the event loop has passed control to the start of the
coroutine @code{plant_a_tree()}.
As seen above, the coroutine creates a task and then awaits it.
The @code{await dig_the_hole_task} instruction adds a callback (which will resume
@code{plant_a_tree()}) to the @code{dig_the_hole_task} object's list of callbacks.
And then, the instruction cedes control to the event loop.
Some time later, the event loop will pass control to @code{dig_the_hole_task}
and the task will finish whatever it needs to do.
Once the task finishes, it will add its various callbacks to the event loop,
in this case, a call to resume @code{plant_a_tree()}.

Generally speaking, when the awaited task finishes (@code{dig_the_hole_task}),
the original task or coroutine (@code{plant_a_tree()}) is added back to the event
loop's to-do list to be resumed.

This is a basic, yet reliable mental model.
In practice, the control handoffs are slightly more complex, but not by much.
In part 2, we'll walk through the details that make this possible.

`Unlike tasks, awaiting a coroutine does not hand control back to the event
loop!'
Wrapping a coroutine in a task first, then awaiting that would cede
control.
The behavior of @code{await coroutine} is effectively the same as invoking a
regular, synchronous Python function.
Consider this program:

@example
import asyncio

async def coro_a():
   print("I am coro_a(). Hi!")

async def coro_b():
   print("I am coro_b(). I sure hope no one hogs the event loop...")

async def main():
   task_b = asyncio.create_task(coro_b())
   num_repeats = 3
   for _ in range(num_repeats):
      await coro_a()
   await task_b

asyncio.run(main())
@end example

The first statement in the coroutine @code{main()} creates @code{task_b} and schedules
it for execution via the event loop.
Then, @code{coro_a()} is repeatedly awaited. Control never cedes to the
event loop, which is why we see the output of all three @code{coro_a()}
invocations before @code{coro_b()}'s output:

@example
I am coro_a(). Hi!
I am coro_a(). Hi!
I am coro_a(). Hi!
I am coro_b(). I sure hope no one hogs the event loop...
@end example

If we change @code{await coro_a()} to @code{await asyncio.create_task(coro_a())}, the
behavior changes.
The coroutine @code{main()} cedes control to the event loop with that statement.
The event loop then proceeds through its backlog of work, calling @code{task_b}
and then the task which wraps @code{coro_a()} before resuming the coroutine
@code{main()}.

@example
I am coro_b(). I sure hope no one hogs the event loop...
I am coro_a(). Hi!
I am coro_a(). Hi!
I am coro_a(). Hi!
@end example

This behavior of @code{await coroutine} can trip a lot of people up!
That example highlights how using only @code{await coroutine} could
unintentionally hog control from other tasks and effectively stall the event
loop.
@ref{2f3,,asyncio.run()} can help you detect such occurrences via the
@code{debug=True} flag, which enables
@ref{213a,,debug mode}.
Among other things, it will log any coroutines that monopolize execution for
100ms or longer.

The design intentionally trades off some conceptual clarity around usage of
@code{await} for improved performance.
Each time a task is awaited, control needs to be passed all the way up the
call stack to the event loop.
That might sound minor, but in a large program with many @code{await} statements and a deep
call stack, that overhead can add up to a meaningful performance drag.

@node A conceptual overview part 2 the nuts and bolts,,A conceptual overview part 1 the high-level,A Conceptual Overview of asyncio
@anchor{howto/a-conceptual-overview-of-asyncio a-conceptual-overview-part-2-the-nuts-and-bolts}@anchor{56ae}
@subsection A conceptual overview part 2: the nuts and bolts


Part 2 goes into detail on the mechanisms @code{asyncio} uses to manage
control flow.
This is where the magic happens.
You'll come away from this section knowing what @code{await} does behind the scenes
and how to make your own asynchronous operators.

@menu
* The inner workings of coroutines:: 
* Future: Future<2>. 
* A homemade asyncio.sleep: A homemade asyncio sleep. 

@end menu

@node The inner workings of coroutines,Future<2>,,A conceptual overview part 2 the nuts and bolts
@anchor{howto/a-conceptual-overview-of-asyncio the-inner-workings-of-coroutines}@anchor{56af}
@subsubsection The inner workings of coroutines


@code{asyncio} leverages four components to pass around control.

@ref{126d,,coroutine.send(arg)} is the method used to start or
resume a coroutine.
If the coroutine was paused and is now being resumed, the argument @code{arg}
will be sent in as the return value of the @code{yield} statement which originally
paused it.
If the coroutine is being used for the first time (as opposed to being resumed),
@code{arg} must be @code{None}.

@example
class Rock:
    def __await__(self):
        value_sent_in = yield 7
        print(f"Rock.__await__ resuming with value: @{value_sent_in@}.")
        return value_sent_in

async def main():
    print("Beginning coroutine main().")
    rock = Rock()
    print("Awaiting rock...")
    value_from_rock = await rock
    print(f"Coroutine received value: @{value_from_rock@} from rock.")
    return 23

coroutine = main()
intermediate_result = coroutine.send(None)
print(f"Coroutine paused and returned intermediate value: @{intermediate_result@}.")

print(f"Resuming coroutine and sending in value: 42.")
try:
    coroutine.send(42)
except StopIteration as e:
    returned_value = e.value
print(f"Coroutine main() finished and provided value: @{returned_value@}.")
@end example

@ref{2498,,yield}, as usual, pauses execution and returns control
to the caller.
In the example above, the @code{yield}, on line 3, is called by
@code{... = await rock} on line 11.
More broadly speaking, @code{await} calls the @ref{f75,,__await__()} method of
the given object.
@code{await} also does one more very special thing: it propagates (or "passes
along") any @code{yield}s it receives up the call chain.
In this case, that's back to @code{... = coroutine.send(None)} on line 16.

The coroutine is resumed via the @code{coroutine.send(42)} call on line 21.
The coroutine picks back up from where it @code{yield}ed (or paused) on line 3
and executes the remaining statements in its body.
When a coroutine finishes, it raises a @ref{df5,,StopIteration} exception with the
return value attached in the @ref{2417,,value} attribute.

That snippet produces this output:

@example
Beginning coroutine main().
Awaiting rock...
Coroutine paused and returned intermediate value: 7.
Resuming coroutine and sending in value: 42.
Rock.__await__ resuming with value: 42.
Coroutine received value: 42 from rock.
Coroutine main() finished and provided value: 23.
@end example

It's worth pausing for a moment here and making sure you followed the various
ways that control flow and values were passed. A lot of important ideas were
covered and it's worth ensuring your understanding is firm.

The only way to yield (or effectively cede control) from a coroutine is to
@code{await} an object that @code{yield}s in its @code{__await__} method.
That might sound odd to you. You might be thinking:

@quotation

1. What about a @code{yield} directly within the coroutine function? The
coroutine function becomes an
@ref{249c,,async generator function}, a
different beast entirely.

2. What about a @ref{2498,,yield from} within the coroutine function to a (plain)
generator?
That causes the error: @code{SyntaxError: yield from not allowed in a coroutine.}
This was intentionally designed for the sake of simplicity -- mandating only
one way of using coroutines.
Initially @code{yield} was barred as well, but was re-accepted to allow for
async generators.
Despite that, @code{yield from} and @code{await} effectively do the same thing.
@end quotation

@node Future<2>,A homemade asyncio sleep,The inner workings of coroutines,A conceptual overview part 2 the nuts and bolts
@anchor{howto/a-conceptual-overview-of-asyncio futures}@anchor{56b0}
@subsubsection Future


A @ref{38c5,,future} is an object meant to represent a
computation's status and result.
The term is a nod to the idea of something still to come or not yet happened,
and the object is a way to keep an eye on that something.

A future has a few important attributes. One is its state, which can be either
"pending", "cancelled", or "done".
Another is its result, which is set when the state transitions to done.
Unlike a coroutine, a future does not represent the actual computation to be
done; instead, it represents the status and result of that computation, kind of
like a status light (red, yellow, or green) or indicator.

@ref{1c7,,asyncio.Task} subclasses @ref{dc6,,asyncio.Future} in order to gain
these various capabilities.
The prior section said tasks store a list of callbacks, which wasn't entirely
accurate.
It's actually the @code{Future} class that implements this logic, which @code{Task}
inherits.

Futures may also be used directly (not via tasks).
Tasks mark themselves as done when their coroutine is complete.
Futures are much more versatile and will be marked as done when you say so.
In this way, they're the flexible interface for you to make your own conditions
for waiting and resuming.

@node A homemade asyncio sleep,,Future<2>,A conceptual overview part 2 the nuts and bolts
@anchor{howto/a-conceptual-overview-of-asyncio a-homemade-asyncio-sleep}@anchor{56b1}
@subsubsection A homemade asyncio.sleep


We'll go through an example of how you could leverage a future to create your
own variant of asynchronous sleep (@code{async_sleep}) which mimics
@ref{c64,,asyncio.sleep()}.

This snippet registers a few tasks with the event loop and then awaits the task
created by @code{asyncio.create_task}, which wraps the @code{async_sleep(3)} coroutine.
We want that task to finish only after three seconds have elapsed, but without
preventing other tasks from running.

@example
async def other_work():
    print("I like work. Work work.")

async def main():
    # Add a few other tasks to the event loop, so there's something
    # to do while asynchronously sleeping.
    work_tasks = [
        asyncio.create_task(other_work()),
        asyncio.create_task(other_work()),
        asyncio.create_task(other_work())
    ]
    print(
        "Beginning asynchronous sleep at time: "
        f"@{datetime.datetime.now().strftime("%H:%M:%S")@}."
    )
    await asyncio.create_task(async_sleep(3))
    print(
        "Done asynchronous sleep at time: "
        f"@{datetime.datetime.now().strftime("%H:%M:%S")@}."
    )
    # asyncio.gather effectively awaits each task in the collection.
    await asyncio.gather(*work_tasks)
@end example

Below, we use a future to enable custom control over when that task will be
marked as done.
If @ref{37ed,,future.set_result()} (the method
responsible for marking that future as done) is never called, then this task
will never finish.
We've also enlisted the help of another task, which we'll see in a moment, that
will monitor how much time has elapsed and, accordingly, call
@code{future.set_result()}.

@example
async def async_sleep(seconds: float):
    future = asyncio.Future()
    time_to_wake = time.time() + seconds
    # Add the watcher-task to the event loop.
    watcher_task = asyncio.create_task(_sleep_watcher(future, time_to_wake))
    # Block until the future is marked as done.
    await future
@end example

Below, we use a rather bare @code{YieldToEventLoop()} object to @code{yield}
from its @code{__await__} method, ceding control to the event loop.
This is effectively the same as calling @code{asyncio.sleep(0)}, but this approach
offers more clarity, not to mention it's somewhat cheating to use
@code{asyncio.sleep} when showcasing how to implement it!

As usual, the event loop cycles through its tasks, giving them control
and receiving control back when they pause or finish.
The @code{watcher_task}, which runs the coroutine @code{_sleep_watcher(...)}, will
be invoked once per full cycle of the event loop.
On each resumption, it'll check the time and if not enough has elapsed, then
it'll pause once again and hand control back to the event loop.
Once enough time has elapsed, @code{_sleep_watcher(...)}
marks the future as done and completes by exiting its
infinite @code{while} loop.
Given this helper task is only invoked once per cycle of the event loop,
you'd be correct to note that this asynchronous sleep will sleep `at least'
three seconds, rather than exactly three seconds.
Note this is also true of @code{asyncio.sleep}.

@example
class YieldToEventLoop:
    def __await__(self):
        yield

async def _sleep_watcher(future, time_to_wake):
    while True:
        if time.time() >= time_to_wake:
            # This marks the future as done.
            future.set_result(None)
            break
        else:
            await YieldToEventLoop()
@end example

Here is the full program's output:

@example
$ python custom-async-sleep.py
Beginning asynchronous sleep at time: 14:52:22.
I like work. Work work.
I like work. Work work.
I like work. Work work.
Done asynchronous sleep at time: 14:52:25.
@end example

You might feel this implementation of asynchronous sleep was unnecessarily
convoluted.
And, well, it was.
The example was meant to showcase the versatility of futures with a simple
example that could be mimicked for more complex needs.
For reference, you could implement it without futures, like so:

@example
async def simpler_async_sleep(seconds):
    time_to_wake = time.time() + seconds
    while True:
        if time.time() >= time_to_wake:
            return
        else:
            await YieldToEventLoop()
@end example

But that's all for now. Hopefully you're ready to more confidently dive into
some async programming or check out advanced topics in the
@ref{b,,rest of the documentation}.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python 3 への拡張モジュール移植,Python で Curses プログラミング,A Conceptual Overview of asyncio,Python HOWTO
@anchor{howto/cporting doc}@anchor{56b2}@anchor{howto/cporting cporting-howto}@anchor{14f8}@anchor{howto/cporting porting-extension-modules-to-python-3}@anchor{56b3}@anchor{howto/cporting translation-repo}@anchor{56b4}
@section Python 3 への拡張モジュール移植


Python 3 への拡張モジュール移植には、以下のリソースを推奨します:


@itemize *

@item 
`Supporting Python 3: An in-depth guide' の Migrating C extensions@footnote{http://python3porting.com/cextensions.html} 章。本は Python 2 から Python 3 への移行全般を扱い、拡張モジュールの移植を読者にガイドします。

@item 
Porting guide@footnote{https://py3c.readthedocs.io/en/latest/guide.html} は `py3c' プロジェクトにより提供される、補助コード付きの見解提案です。

@item 
@ref{4e8e,,Recommended third party tools} offer abstractions over
the Python's C API.
Extensions generally need to be re-written to use one of them,
but the library then handles differences between various Python
versions and implementations.
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python で Curses プログラミング,デスクリプタ ガイド,Python 3 への拡張モジュール移植,Python HOWTO
@anchor{howto/curses doc}@anchor{56b5}@anchor{howto/curses curses-howto}@anchor{345f}@anchor{howto/curses curses-programming-with-python}@anchor{56b6}@anchor{howto/curses translation-repo}@anchor{56b7}
@section Python で Curses プログラミング


@*著者: 
A.M. Kuchling, Eric S. Raymond


@*リリース: 
2.04


@subsubheading 概要



このドキュメントでは @ref{2f,,curses} 拡張モジュールでテキストモードディスプレイを制御する方法について記述します。

@menu
* curses ってなに?:: 
* curses アプリケーションの起動と終了:: 
* ウィンドウとパッド:: 
* テキストの表示:: 
* ユーザ入力:: 
* より多くの情報:: 

@end menu

@node curses ってなに?,curses アプリケーションの起動と終了,,Python で Curses プログラミング
@anchor{howto/curses what-is-curses}@anchor{56b8}
@subsection curses ってなに?


curses ライブラリは、VT100s や Linux コンソール、さまざまなプログラムが提供するエミュレーション端末といったテキストベースの端末（ターミナル）のために、端末に依存しないスクリーン描画や、キーボードの処理を提供します。端末はカーソルの移動や、画面のスクロール、領域の消去といった共通の操作を行うための様々な制御コードをサポートします。端末の種類によって大きく異なる制御コードを使うことがあり、しばしば独特の癖があります。

グラフィカルなディスプレイが当たり前の今となっては、「なんでわざわざ？」と疑問に思うかもしれません。確かに文字表示端末は時代遅れな技術ではありますが、ニッチな領域が存在していて、意匠を凝らすことができるため、いまだに価値のあるものとなっています。そのような領域の一つは、例えば X サーバーを持たない組み込みのUnixです。ほかにも、OSのインストーラや、カーネル設定などのツールで、これらはグラフィカルサポートが利用可能になる前に動作する必要があります。

The curses library provides fairly basic functionality, providing the
programmer with an abstraction of a display containing multiple
non-overlapping windows of text.  The contents of a window can be
changed in various ways---adding text, erasing it, changing its
appearance---and the curses library will figure out what control codes
need to be sent to the terminal to produce the right output.  curses
doesn't provide many user-interface concepts such as buttons, checkboxes,
or dialogs; if you need such features, consider a user interface library such as
Urwid@footnote{https://pypi.org/project/Urwid/}.

curses ライブラリは元々 BSD UNIX 向けに書かれました; 後の AT&T から出た Unix System V バージョンで多くの機能と新機能が追加されました。BSD curses はいまやメンテナンスされておらず、これは AT&T インターフェースのオープンソース実装である ncurses にとって置き換えられました。Linux や FreeBSD のようなオープンソース Unix を利用している場合は、おそらくシステムは ncurses を利用しています。現在のほとんどの商用 Unix は System V のコードを基にしているため、ここで述べる全ての関数が利用できるはずです。しかし、古いバージョンの curses を持ついくつかのプロプライエタリ Unix は全てには対応していないでしょう。

The Windows version of Python doesn't include the @ref{2f,,curses}
module.  A ported version called UniCurses@footnote{https://pypi.org/project/UniCurses/} is available.

@menu
* Python の curses module:: 

@end menu

@node Python の curses module,,,curses ってなに?
@anchor{howto/curses the-python-curses-module}@anchor{56b9}
@subsubsection Python の curses module


The Python module is a fairly simple wrapper over the C functions provided by
curses; if you're already familiar with curses programming in C, it's really
easy to transfer that knowledge to Python.  The biggest difference is that the
Python interface makes things simpler by merging different C functions such as
@code{addstr()}, @code{mvaddstr()}, and @code{mvwaddstr()} into a single
@ref{3474,,addstr()} method.  You'll see this covered in more
detail later.

この HOWTO は curses と Python を使ってテキストプログラムを書くための入門記事です。 curses API に対する完全な解説をすることは意図していません; その目的のためには Python ライブラリガイドの ncurses 節と C 言語マニュアルのncurses のページを参照してください。とはいえ、この文章は基本的な考えを提供してくれるでしょう。

@node curses アプリケーションの起動と終了,ウィンドウとパッド,curses ってなに?,Python で Curses プログラミング
@anchor{howto/curses starting-and-ending-a-curses-application}@anchor{56ba}
@subsection curses アプリケーションの起動と終了


Before doing anything, curses must be initialized.  This is done by
calling the @ref{190f,,initscr()} function, which will determine the
terminal type, send any required setup codes to the terminal, and
create various internal data structures.  If successful,
@code{initscr()} returns a window object representing the entire
screen; this is usually called @code{stdscr} after the name of the
corresponding C variable.

@example
import curses
stdscr = curses.initscr()
@end example

Usually curses applications turn off automatic echoing of keys to the
screen, in order to be able to read keys and only display them under
certain circumstances.  This requires calling the
@ref{349b,,noecho()} function.

@example
curses.noecho()
@end example

通常アプリケーションはまた、Enter キーを押すことなく、キーに対してすぐに反応する必要があります; これは cbreak モードと呼ばれ、通常の入力がバッファされるモードと逆に動作します。

@example
curses.cbreak()
@end example

端末は通常、カーソルキーや Page Up や Home といった操作キーなどの特別なキーをマルチバイトエスケープシーケンスとして返します。それらのシーケンスを想定して対応する処理を行うアプリケーションを書けるように、 curses はそれを @ref{3513,,curses.KEY_LEFT} のような特別な値を返して行ってくれます。 curses にその仕事をさせるには、キーパッドモードを有効にする必要があります。

@example
stdscr.keypad(True)
@end example

curses アプリケーションを終了させるのは起動よりも簡単です。 以下を呼び出す必要があります:

@example
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
@end example

cursesに親和性の高い設定をもとに戻します。そして、@ref{3477,,endwin()} 関数を呼び出し、端末を通常の操作モードに復旧します。

@example
curses.endwin()
@end example

curses アプリケーションをデバッグするときの一般的な問題は、アプリケーションが端末を以前の状態に復旧することなく異常終了したときに端末がめちゃめちゃになることです。Python ではこの問題はコードにバグがあって、捕捉できない例外が発生したときによく起きます。タイプしたキーはもはやエコーされません、例えば、シェルを使うのが難しくなります。

Pythonでは、これらの複雑さを避けデバッグをより容易にするために、 @ref{c73,,curses.wrapper()} 関数をインポートして、このように使います:

@example
from curses import wrapper

def main(stdscr):
    # Clear screen
    stdscr.clear()

    # This raises ZeroDivisionError when i == 10.
    for i in range(0, 11):
        v = i-10
        stdscr.addstr(i, 0, '10 divided by @{@} is @{@}'.format(v, 10/v))

        stdscr.refresh()
        stdscr.getkey()

wrapper(main)
@end example

The @ref{c73,,wrapper()} function takes a callable object and does the
initializations described above, also initializing colors if color
support is present.  @code{wrapper()} then runs your provided callable.
Once the callable returns, @code{wrapper()} will restore the original
state of the terminal.  The callable is called inside a
@ref{8f8,,try}...@ref{1ab,,except} that catches exceptions, restores
the state of the terminal, and then re-raises the exception.  Therefore
your terminal won't be left in a funny state on exception and you'll be
able to read the exception's message and traceback.

@node ウィンドウとパッド,テキストの表示,curses アプリケーションの起動と終了,Python で Curses プログラミング
@anchor{howto/curses windows-and-pads}@anchor{56bb}
@subsection ウィンドウとパッド


Windows are the basic abstraction in curses.  A window object represents a
rectangular area of the screen, and supports methods to display text,
erase it, allow the user to input strings, and so forth.

The @code{stdscr} object returned by the @ref{190f,,initscr()} function is a
window object that covers the entire screen.  Many programs may need
only this single window, but you might wish to divide the screen into
smaller windows, in order to redraw or clear them separately. The
@ref{3499,,newwin()} function creates a new window of a given size,
returning the new window object.

@example
begin_x = 20; begin_y = 7
height = 5; width = 40
win = curses.newwin(height, width, begin_y, begin_x)
@end example

Note that the coordinate system used in curses is unusual.
Coordinates are always passed in the order `y,x', and the top-left
corner of a window is coordinate (0,0).  This breaks the normal
convention for handling coordinates where the `x' coordinate comes
first.  This is an unfortunate difference from most other computer
applications, but it's been part of curses since it was first written,
and it's too late to change things now.

Your application can determine the size of the screen by using the
@ref{fec,,curses.LINES} and @ref{fed,,curses.COLS} variables to obtain the `y' and
`x' sizes.  Legal coordinates will then extend from @code{(0,0)} to
@code{(curses.LINES - 1, curses.COLS - 1)}.

When you call a method to display or erase text, the effect doesn't
immediately show up on the display.  Instead you must call the
@ref{3498,,refresh()} method of window objects to update the
screen.

This is because curses was originally written with slow 300-baud
terminal connections in mind; with these terminals, minimizing the
time required to redraw the screen was very important.  Instead curses
accumulates changes to the screen and displays them in the most
efficient manner when you call @code{refresh()}.  For example, if your
program displays some text in a window and then clears the window,
there's no need to send the original text because they're never
visible.

In practice, explicitly telling curses to redraw a window doesn't
really complicate programming with curses much. Most programs go into a flurry
of activity, and then pause waiting for a keypress or some other action on the
part of the user.  All you have to do is to be sure that the screen has been
redrawn before pausing to wait for user input, by first calling
@code{stdscr.refresh()} or the @code{refresh()} method of some other relevant
window.

A pad is a special case of a window; it can be larger than the actual display
screen, and only a portion of the pad displayed at a time. Creating a pad
requires the pad's height and width, while refreshing a pad requires giving the
coordinates of the on-screen area where a subsection of the pad will be
displayed.

@example
pad = curses.newpad(100, 100)
# These loops fill the pad with letters; addch() is
# explained in the next section
for y in range(0, 99):
    for x in range(0, 99):
        pad.addch(y,x, ord('a') + (x*x+y*y) % 26)

# Displays a section of the pad in the middle of the screen.
# (0,0) : coordinate of upper-left corner of pad area to display.
# (5,5) : coordinate of upper-left corner of window area to be filled
#         with pad content.
# (20, 75) : coordinate of lower-right corner of window area to be
#          : filled with pad content.
pad.refresh( 0,0, 5,5, 20,75)
@end example

The @code{refresh()} call displays a section of the pad in the rectangle
extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper
left corner of the displayed section is coordinate (0,0) on the pad.  Beyond
that difference, pads are exactly like ordinary windows and support the same
methods.

If you have multiple windows and pads on screen there is a more
efficient way to update the screen and prevent annoying screen flicker
as each part of the screen gets updated.  @code{refresh()} actually
does two things:


@enumerate 

@item 
それぞれのウィンドウの @ref{3475,,noutrefresh()} メソッドを呼び出して、配下にある、スクリーンの望ましい状態を表すデータ構造を更新します。

@item 
@ref{3473,,doupdate()} 関数を呼び出して、データ構造に記録された望ましい状態に合致するように、物理スクリーンを更新します。
@end enumerate

Instead you can call @code{noutrefresh()} on a number of windows to
update the data structure, and then call @code{doupdate()} to update
the screen.

@node テキストの表示,ユーザ入力,ウィンドウとパッド,Python で Curses プログラミング
@anchor{howto/curses displaying-text}@anchor{56bc}
@subsection テキストの表示


From a C programmer's point of view, curses may sometimes look like a
twisty maze of functions, all subtly different.  For example,
@code{addstr()} displays a string at the current cursor location in
the @code{stdscr} window, while @code{mvaddstr()} moves to a given y,x
coordinate first before displaying the string. @code{waddstr()} is just
like @code{addstr()}, but allows specifying a window to use instead of
using @code{stdscr} by default. @code{mvwaddstr()} allows specifying both
a window and a coordinate.

幸運にも、Python インターフェースはこれらの詳細を全て隠蔽してくれます。 @code{stdscr} は他のものと同様のウィンドウオブジェクトであり、 @ref{3474,,addstr()} のようなメソッドは複数の引数形式を許容してくれます。通常それらは4つの形式です。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

形式

@tab

説明

@item

`str' または `ch'

@tab

文字列 `str' または文字 `ch' を現在位置に表示します

@item

`str' または `ch', `attr'

@tab

文字列 `str' または文字 `ch' を属性 `attr' を利用して現在位置に表示します

@item

`y', `x', `str' または `ch'

@tab

ウィンドウ内の位置 `y,x' に移動し `str' または `ch' を表示します

@item

`y', `x', `str' または `ch', `attr'

@tab

ウィンドウ内の位置 `y,x' に移動し属性 `attr' を利用して `str' または `ch' を表示します

@end multitable


属性によって表示するテキストをハイライトすることができます、ボールド体、アンダーライン、反転、カラーなど。より詳しくは次の小節で説明します。

The @ref{3474,,addstr()} method takes a Python string or
bytestring as the value to be displayed.  The contents of bytestrings
are sent to the terminal as-is.  Strings are encoded to bytes using
the value of the window's @ref{12a8,,encoding} attribute; this defaults to
the default system encoding as returned by @ref{329,,locale.getencoding()}.

The @ref{34b4,,addch()} methods take a character, which can be
either a string of length 1, a bytestring of length 1, or an integer.

Constants are provided for extension characters; these constants are
integers greater than 255.  For example, @ref{3580,,ACS_PLMINUS} is a +/-
symbol, and @ref{34be,,ACS_ULCORNER} is the upper left corner of a box
(handy for drawing borders).  You can also use the appropriate Unicode
character.

ウィンドウは最後の操作の後のカーソル位置を覚えているため、 `y,x' 座標をうっかり忘れてしまっても、文字列や文字は最後の操作位置に表示されます。 @code{move(y,x)} メソッドでカーソルを移動させることもできます。常に点滅するカーソルを表示する端末もあるため、カーソルが特定の位置にいることを保証して注意が反れないようにしたいと思うかもしれません; ランダムに見える位置でカーソルが点滅すると面を食らってしまいます。

If your application doesn't need a blinking cursor at all, you can
call @code{curs_set(False)} to make it invisible.  For compatibility
with older curses versions, there's a @code{leaveok(bool)} function
that's a synonym for @ref{346d,,curs_set()}.  When `bool' is true, the
curses library will attempt to suppress the flashing cursor, and you
won't need to worry about leaving it in odd locations.

@menu
* 属性とカラー:: 

@end menu

@node 属性とカラー,,,テキストの表示
@anchor{howto/curses attributes-and-color}@anchor{56bd}
@subsubsection 属性とカラー


Characters can be displayed in different ways.  Status lines in a text-based
application are commonly shown in reverse video, or a text viewer may need to
highlight certain words.  curses supports this by allowing you to specify an
attribute for each cell on the screen.

属性は整数値で、それぞれのビットが異なる属性を表わします。複数の属性ビットをセットしてテキストの表示を試みることができますが、curses は全ての組み合わせが利用可能であるかや視覚的に区別できるかどうかは保証してくれません、それらは利用している端末の能力に依存しているため、最も安全なのは、最も一般的に利用可能な属性を設定する方法です、ここに列挙します。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

説明

@item

@ref{34ff,,A_BLINK}

@tab

テキストを点滅

@item

@ref{3500,,A_BOLD}

@tab

高輝度またはボールドテキスト

@item

@ref{3501,,A_DIM}

@tab

低輝度テキスト

@item

@ref{346b,,A_REVERSE}

@tab

反転テキスト

@item

@ref{346a,,A_STANDOUT}

@tab

利用できる最良のハイライトモード

@item

@ref{3505,,A_UNDERLINE}

@tab

下線付きテキスト

@end multitable


つまり、反転するステータスラインを画面の最上部に表示するには、コードをこうします:

@example
stdscr.addstr(0, 0, "Current mode: Typing mode",
              curses.A_REVERSE)
stdscr.refresh()
@end example

curses ライブラリはカラー機能を提供している端末でのカラーもサポートしています。そんな端末の中で最も一般的なものは Linux コンソールで、color xterm もそれに続きます。

To use color, you must call the @ref{34a5,,start_color()} function soon
after calling @ref{190f,,initscr()}, to initialize the default color set
(the @ref{c73,,curses.wrapper()} function does this automatically).  Once that's
done, the @ref{3489,,has_colors()} function returns TRUE if the terminal
in use can
actually display color.  (Note: curses uses the American spelling 'color',
instead of the Canadian/British spelling 'colour'.  If you're used to the
British spelling, you'll have to resign yourself to misspelling it for the sake
of these functions.)

The curses library maintains a finite number of color pairs, containing a
foreground (or text) color and a background color.  You can get the attribute
value corresponding to a color pair with the @ref{3469,,color_pair()}
function; this can be bitwise-OR'ed with other attributes such as
@ref{346b,,A_REVERSE}, but again, such combinations are not guaranteed to work
on all terminals.

例として、テキスト行をカラーペア 1 を使って表示します:

@example
stdscr.addstr("Pretty text", curses.color_pair(1))
stdscr.refresh()
@end example

As I said before, a color pair consists of a foreground and background color.
The @code{init_pair(n, f, b)} function changes the definition of color pair `n', to
foreground color f and background color b.  Color pair 0 is hard-wired to white
on black, and cannot be changed.

Colors are numbered, and @ref{34a5,,start_color()} initializes 8 basic
colors when it activates color mode.  They are: 0:black, 1:red,
2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white.  The @ref{2f,,curses}
module defines named constants for each of these colors:
@ref{3592,,curses.COLOR_BLACK}, @ref{3597,,curses.COLOR_RED}, and so forth.

やってみましょう。カラー 1 を白背景に赤に変更してみましょう、こうして呼び出します:

@example
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
@end example

カラーペアを変更するときには、既に表示された任意のテキストが利用するカラーペアを新しい色に変更します。新しいテキストをこの色で使うこともできます:

@example
stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))
@end example

Very fancy terminals can change the definitions of the actual colors to a given
RGB value.  This lets you change color 1, which is usually red, to purple or
blue or any other color you like.  Unfortunately, the Linux console doesn't
support this, so I'm unable to try it out, and can't provide any examples.  You
can check if your terminal can do this by calling
@ref{3466,,can_change_color()}, which returns @code{True} if the capability is
there.  If you're lucky enough to have such a talented terminal, consult your
system's man pages for more information.

@node ユーザ入力,より多くの情報,テキストの表示,Python で Curses プログラミング
@anchor{howto/curses user-input}@anchor{56be}
@subsection ユーザ入力


The C curses library offers only very simple input mechanisms. Python's
@ref{2f,,curses} module adds a basic text-input widget.  (Other libraries
such as Urwid@footnote{https://pypi.org/project/Urwid/} have more extensive collections of widgets.)

ウィンドウから入力を得るための2つのメソッドがあります。


@itemize *

@item 
@ref{1825,,getch()} refreshes the screen and then waits for
the user to hit a key, displaying the key if @ref{3476,,echo()} has been
called earlier.  You can optionally specify a coordinate to which
the cursor should be moved before pausing.

@item 
@ref{34d2,,getkey()} does the same thing but converts the
integer to a string.  Individual characters are returned as
1-character strings, and special keys such as function keys return
longer strings containing a key name such as @code{KEY_UP} or @code{^G}.
@end itemize

It's possible to not wait for the user using the
@ref{34e7,,nodelay()} window method. After @code{nodelay(True)},
@code{getch()} and @code{getkey()} for the window become
non-blocking. To signal that no input is ready, @code{getch()} returns
@code{curses.ERR} (a value of -1) and @code{getkey()} raises an exception.
There's also a @ref{348d,,halfdelay()} function, which can be used to (in
effect) set a timer on each @code{getch()}; if no input becomes
available within a specified delay (measured in tenths of a second),
curses raises an exception.

The @code{getch()} method returns an integer; if it's between 0 and 255, it
represents the ASCII code of the key pressed.  Values greater than 255 are
special keys such as Page Up, Home, or the cursor keys. You can compare the
value returned to constants such as @ref{3524,,curses.KEY_PPAGE},
@ref{3515,,curses.KEY_HOME}, or @ref{3513,,curses.KEY_LEFT}.  The main loop of
your program may look something like this:

@example
while True:
    c = stdscr.getch()
    if c == ord('p'):
        PrintDocument()
    elif c == ord('q'):
        break  # Exit the while loop
    elif c == curses.KEY_HOME:
        x = y = 0
@end example

The @ref{30,,curses.ascii} module supplies ASCII class membership functions that
take either integer or 1-character string arguments; these may be useful in
writing more readable tests for such loops.  It also supplies
conversion functions  that take either integer or 1-character-string arguments
and return the same type.  For example, @ref{35da,,curses.ascii.ctrl()} returns the
control character corresponding to its argument.

There's also a method to retrieve an entire string,
@ref{183e,,getstr()}.  It isn't used very often, because its
functionality is quite limited; the only editing keys available are
the backspace key and the Enter key, which terminates the string.  It
can optionally be limited to a fixed number of characters.

@example
curses.echo()            # Enable echoing of characters

# Get a 15-character string, with the cursor on the top line
s = stdscr.getstr(0,0, 15)
@end example

The @ref{32,,curses.textpad} module supplies a text box that supports an
Emacs-like set of keybindings.  Various methods of the
@ref{359b,,Textbox} class support editing with input
validation and gathering the edit results either with or without
trailing spaces.  Here's an example:

@example
import curses
from curses.textpad import Textbox, rectangle

def main(stdscr):
    stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")

    editwin = curses.newwin(5,30, 2,1)
    rectangle(stdscr, 1,0, 1+5+1, 1+30+1)
    stdscr.refresh()

    box = Textbox(editwin)

    # Let the user edit until Ctrl-G is struck.
    box.edit()

    # Get resulting contents
    message = box.gather()
@end example

さらなる詳細についてはライブラリのドキュメント @ref{32,,curses.textpad}  を参照してください。

@node より多くの情報,,ユーザ入力,Python で Curses プログラミング
@anchor{howto/curses for-more-information}@anchor{56bf}
@subsection より多くの情報


この HOWTO ではいくつかの進んだ話題、スクリーンスクレイピングや xterm インスタンスからマウスイベントを捉えるなど、については扱っていません。しかし、Python の @ref{2f,,curses} モジュールのライブラリページはいまやかなり充実しています。次はこれを見るべきです。

If you're in doubt about the detailed behavior of the curses
functions, consult the manual pages for your curses implementation,
whether it's ncurses or a proprietary Unix vendor's.  The manual pages
will document any quirks, and provide complete lists of all the
functions, attributes, and @ref{356c,,ACS_*} characters available to
you.

Because the curses API is so large, some functions aren't supported in
the Python interface.  Often this isn't because they're difficult to
implement, but because no one has needed them yet.  Also, Python
doesn't yet support the menu library associated with ncurses.
Patches adding support for these would be welcome; see
the Python Developer's Guide@footnote{https://devguide.python.org/} to
learn more about submitting patches to Python.


@itemize *

@item 
Writing Programs with NCURSES@footnote{https://invisible-island.net/ncurses/ncurses-intro.html}:
a lengthy tutorial for C programmers.

@item 
The ncurses man page@footnote{https://linux.die.net/man/3/ncurses}

@item 
The ncurses FAQ@footnote{https://invisible-island.net/ncurses/ncurses.faq.html}

@item 
"Use curses... don't swear"@footnote{https://www.youtube.com/watch?v=eN1eZtjLEnU}: curses または Urwid を使って端末を制御する PyCon 2013 講演ビデオです。

@item 
"Console Applications with Urwid"@footnote{https://pyvideo.org/video/1568/console-applications-with-urwid}:
video of a PyCon CA 2012 talk demonstrating some applications written using
Urwid.
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node デスクリプタ ガイド,Debugging C API extensions and CPython Internals with GDB,Python で Curses プログラミング,Python HOWTO
@anchor{howto/descriptor doc}@anchor{56c0}@anchor{howto/descriptor descriptor-guide}@anchor{56c1}@anchor{howto/descriptor descriptorhowto}@anchor{1706}@anchor{howto/descriptor translation-repo}@anchor{56c2}
@section デスクリプタ ガイド


@*著者: 
Raymond Hettinger


@*問い合わせ先: 
<python at rcn dot com>


@ref{1881,,デスクリプタ} を使うと、オブジェクトの属性検索、保存、削除をカスタマイズできます。

本ガイドは4つの大項目から構成されています。


@enumerate 

@item 
最初の「入門」では基本の紹介をして、シンプルな例から少しずつ概念を説明していきます。もしデスクリプタに触れるのが初めての場合はここから学んでいきましょう。

@item 
2つ目のセクションでは完全で実践的なデスクリプタのサンプルを紹介します。もしデスクリプタの基本を理解しているのであれば、ここから読み始めても良いでしょう。

@item 
3番目のセクションはより技巧的なチュートリアルを通じて、デスクリプタがどのようなメカニズムで動作しているのかを紹介します。多くの人はこのレベルの理解は不要でしょう。

@item 
最後のセクションは、Cで書かれた組み込みのデスクリプタをピュアPythonで実現する方法を紹介します。このセクションがどのように関数が束縛メソッドになるのか、 @ref{48e,,classmethod()} や @ref{453,,staticmethod()}, @ref{4b3,,property()}, @ref{7f7,,__slots__} といった一般的なツールの実装がどのようになっているのか興味を持ったら読んでください。
@end enumerate

@menu
* 入門:: 
* 実践的なサンプル:: 
* 技術的なチュートリアル:: 
* ピュアPythonの等価実装:: 

@end menu

@node 入門,実践的なサンプル,,デスクリプタ ガイド
@anchor{howto/descriptor primer}@anchor{56c3}
@subsection 入門


この入門では、なるべく基礎的なところから開始し、新しい要素を一つずつ紹介していきます。

@menu
* シンプルな例; 定数を返すデスクリプタ: シンプルな例 定数を返すデスクリプタ. 
* 動的なルックアップ:: 
* 管理された属性:: 
* 名前のカスタマイズ:: 
* まとめ:: 

@end menu

@node シンプルな例 定数を返すデスクリプタ,動的なルックアップ,,入門
@anchor{howto/descriptor simple-example-a-descriptor-that-returns-a-constant}@anchor{56c4}
@subsubsection シンプルな例: 定数を返すデスクリプタ


The @code{Ten} class is a descriptor whose @ref{1701,,__get__()} method always
returns the constant @code{10}:

@example
class Ten:
    def __get__(self, obj, objtype=None):
        return 10
@end example

このデスクリプタを使うには他のクラスのクラス変数として保存します:

@example
class A:
    x = 5                       # Regular class attribute
    y = Ten()                   # Descriptor instance
@end example

インタラクティブセッションを使って、通常の属性ルックアップと、デスクリプタのルックアップの違いを見てみましょう。

@example
>>> a = A()                     # Make an instance of class A
>>> a.x                         # Normal attribute lookup
5
>>> a.y                         # Descriptor lookup
10
@end example

@code{a.x} 属性ルックアップではドット演算子がクラス辞書の中から @code{'x': 5} を見つけます。 @code{a.y} ルックアップではドット演算子は @code{__get__} メソッドを持つデスクリプタインスタンスを取得します。そのメソッドを呼び出すと、 @code{10} を返します。

@code{10} はクラスの辞書にも、インスタンスの辞書にも格納されていません。その代わり、 @code{10} はオンデマンドに計算されます。

このサンプルは、シンプルなデスクリプタがどのように動作するかを説明するためのものですが、実用的ではありません。定数を返す場合、通常の属性アクセスの方が良いでしょう。

次のセクションでは、より実践的な動的なルックアップを作成します。

@node 動的なルックアップ,管理された属性,シンプルな例 定数を返すデスクリプタ,入門
@anchor{howto/descriptor dynamic-lookups}@anchor{56c5}
@subsubsection 動的なルックアップ


単に定数を返すよりも、なにか処理を実行するデスクリプタの方が面白いでしょう。

@example
import os

class DirectorySize:

    def __get__(self, obj, objtype=None):
        return len(os.listdir(obj.dirname))

class Directory:

    size = DirectorySize()              # Descriptor instance

    def __init__(self, dirname):
        self.dirname = dirname          # Regular instance attribute
@end example

インタラクティブセッションで見たように、この探索は動的です。実行ごとに異なる計算を行い、毎回答えが更新されます。

@example
>>> s = Directory('songs')
>>> g = Directory('games')
>>> s.size                              # The songs directory has twenty files
20
>>> g.size                              # The games directory has three files
3
>>> os.remove('games/chess')            # Delete a game
>>> g.size                              # File count is automatically updated
2
@end example

Besides showing how descriptors can run computations, this example also
reveals the purpose of the parameters to @ref{1701,,__get__()}.  The `self'
parameter is `size', an instance of `DirectorySize'.  The `obj' parameter is
either `g' or `s', an instance of `Directory'.  It is the `obj' parameter that
lets the @ref{1701,,__get__()} method learn the target directory.  The `objtype'
parameter is the class `Directory'.

@node 管理された属性,名前のカスタマイズ,動的なルックアップ,入門
@anchor{howto/descriptor managed-attributes}@anchor{56c6}
@subsubsection 管理された属性


A popular use for descriptors is managing access to instance data.  The
descriptor is assigned to a public attribute in the class dictionary while the
actual data is stored as a private attribute in the instance dictionary.  The
descriptor's @ref{1701,,__get__()} and @ref{23b5,,__set__()} methods are triggered when
the public attribute is accessed.

このサンプルでは `age' はパブリックな属性で、 `_age' はプライベートな属性です。パブリックな属性がアクセスされると、デスクリプタはルックアップや更新のログ出力をします。

@example
import logging

logging.basicConfig(level=logging.INFO)

class LoggedAgeAccess:

    def __get__(self, obj, objtype=None):
        value = obj._age
        logging.info('Accessing %r giving %r', 'age', value)
        return value

    def __set__(self, obj, value):
        logging.info('Updating %r to %r', 'age', value)
        obj._age = value

class Person:

    age = LoggedAgeAccess()             # Descriptor instance

    def __init__(self, name, age):
        self.name = name                # Regular instance attribute
        self.age = age                  # Calls __set__()

    def birthday(self):
        self.age += 1                   # Calls both __get__() and __set__()
@end example

インタラクティブセッションの結果で見てわかるように、管理された属性の `age' のログ出力が行われますが、通常の属性の `name' はログ出力されません。

@c import logging, sys
@c logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True)

@example
>>> mary = Person('Mary M', 30)         # The initial age update is logged
INFO:root:Updating 'age' to 30
>>> dave = Person('David D', 40)
INFO:root:Updating 'age' to 40

>>> vars(mary)                          # The actual data is in a private attribute
@{'name': 'Mary M', '_age': 30@}
>>> vars(dave)
@{'name': 'David D', '_age': 40@}

>>> mary.age                            # Access the data and log the lookup
INFO:root:Accessing 'age' giving 30
30
>>> mary.birthday()                     # Updates are logged as well
INFO:root:Accessing 'age' giving 30
INFO:root:Updating 'age' to 31

>>> dave.name                           # Regular attribute lookup isn't logged
'David D'
>>> dave.age                            # Only the managed attribute is logged
INFO:root:Accessing 'age' giving 40
40
@end example

このサンプル実装には大きな問題があります。プライベートな名前の `_age' が `LoggedAgeAccess' クラスの中でハードコードされています。そのため、どのインスタンスも1つしかこのログ出力される属性が作れず、名前を変更できません。次のサンプルでこの問題を解決していきます。

@node 名前のカスタマイズ,まとめ,管理された属性,入門
@anchor{howto/descriptor customized-names}@anchor{56c7}
@subsubsection 名前のカスタマイズ


クラスがデスクリプタを使うときに、クラスはそれぞれのデスクリプタにどのような変数名を使うかを通知します。

In this example, the @code{Person} class has two descriptor instances,
`name' and `age'.  When the @code{Person} class is defined, it makes a
callback to @ref{e48,,__set_name__()} in `LoggedAccess' so that the field names can
be recorded, giving each descriptor its own `public_name' and `private_name':

@example
import logging

logging.basicConfig(level=logging.INFO)

class LoggedAccess:

    def __set_name__(self, owner, name):
        self.public_name = name
        self.private_name = '_' + name

    def __get__(self, obj, objtype=None):
        value = getattr(obj, self.private_name)
        logging.info('Accessing %r giving %r', self.public_name, value)
        return value

    def __set__(self, obj, value):
        logging.info('Updating %r to %r', self.public_name, value)
        setattr(obj, self.private_name, value)

class Person:

    name = LoggedAccess()                # First descriptor instance
    age = LoggedAccess()                 # Second descriptor instance

    def __init__(self, name, age):
        self.name = name                 # Calls the first descriptor
        self.age = age                   # Calls the second descriptor

    def birthday(self):
        self.age += 1
@end example

An interactive session shows that the @code{Person} class has called
@ref{e48,,__set_name__()} so that the field names would be recorded.  Here
we call @ref{1e23,,vars()} to look up the descriptor without triggering it:

@example
>>> vars(vars(Person)['name'])
@{'public_name': 'name', 'private_name': '_name'@}
>>> vars(vars(Person)['age'])
@{'public_name': 'age', 'private_name': '_age'@}
@end example

新しいクラスは `name' と `age' の両方でログを出力します。

@c import logging, sys
@c logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True)

@example
>>> pete = Person('Peter P', 10)
INFO:root:Updating 'name' to 'Peter P'
INFO:root:Updating 'age' to 10
>>> kate = Person('Catherine C', 20)
INFO:root:Updating 'name' to 'Catherine C'
INFO:root:Updating 'age' to 20
@end example

2つの `Person' のインスタンスは、プライベート名しか保持していません。

@example
>>> vars(pete)
@{'_name': 'Peter P', '_age': 10@}
>>> vars(kate)
@{'_name': 'Catherine C', '_age': 20@}
@end example

@node まとめ,,名前のカスタマイズ,入門
@anchor{howto/descriptor closing-thoughts}@anchor{56c8}
@subsubsection まとめ


A @ref{1881,,descriptor} is what we call any object that defines @ref{1701,,__get__()},
@ref{23b5,,__set__()}, or @ref{194f,,__delete__()}.

Optionally, descriptors can have a @ref{e48,,__set_name__()} method.  This is only
used in cases where a descriptor needs to know either the class where it was
created or the name of class variable it was assigned to.  (This method, if
present, is called even if the class is not a descriptor.)

デスクリプタは属性のルックアップ中に、ドット演算子によって呼び出されます。 @code{vars(some_class)[descriptor_name]} という書き方によって間接的にデスクリプタがアクセスされると、デスクリプタを実行することなく、デスクリプタのインスタンスが返されます。

デスクリプタはクラス変数として利用したときにだけ動作します。インスタンスに設定しても効果はありません。

デスクリプタは、クラス変数として格納されているオブジェクトが属性ルックアップ中に発生することを制御できるように、フックを提供することが主なモチベーションとなっています。

伝統的には、呼び出し側のクラスが、ルックアップ中に発生することを制御してきましたが、デスクリプタはその関係を逆転させ、検索されているデータが問題に介入できるようにします。

デスクリプタは、Pythonのさまざまなところで利用されています。これにより、単なる関数は、インスタンスに束縛されたメソッドになります。 @ref{48e,,classmethod()}, @ref{453,,staticmethod()},  @ref{4b3,,property()}, @ref{763,,functools.cached_property()} といったツールもすべて、デスクリプタとして実装されています。

@node 実践的なサンプル,技術的なチュートリアル,入門,デスクリプタ ガイド
@anchor{howto/descriptor complete-practical-example}@anchor{56c9}
@subsection 実践的なサンプル


このサンプルでは、発見が極めて難しいデータ破損バグを特定するのに利用可能な、実践的でパワフルなツールを紹介します。

@menu
* バリデータクラス:: 
* カスタムバリデータ:: 
* 実践的なアプリケーション:: 

@end menu

@node バリデータクラス,カスタムバリデータ,,実践的なサンプル
@anchor{howto/descriptor validator-class}@anchor{56ca}
@subsubsection バリデータクラス


バリデータは管理された属性アクセスのためのデスクリプタです。データを格納する前に、新しい値が型が適合しているか、値の範囲制限に適合しているかを検証します。もし制限に合わなければ、例外を送出し、データが不正な状態になるのを防ぎます。

This @code{Validator} class is both an @ref{13ce,,abstract base class} and a
managed attribute descriptor:

@example
from abc import ABC, abstractmethod

class Validator(ABC):

    def __set_name__(self, owner, name):
        self.private_name = '_' + name

    def __get__(self, obj, objtype=None):
        return getattr(obj, self.private_name)

    def __set__(self, obj, value):
        self.validate(value)
        setattr(obj, self.private_name, value)

    @@abstractmethod
    def validate(self, value):
        pass
@end example

Custom validators need to inherit from @code{Validator} and must supply a
@code{validate()} method to test various restrictions as needed.

@node カスタムバリデータ,実践的なアプリケーション,バリデータクラス,実践的なサンプル
@anchor{howto/descriptor custom-validators}@anchor{56cb}
@subsubsection カスタムバリデータ


ここでは3つの実践的なバリデーションのユーティリティのサンプルを紹介します。


@enumerate 

@item 
@code{OneOf} verifies that a value is one of a restricted set of options.

@item 
@code{Number} verifies that a value is either an @ref{19b,,int} or
@ref{196,,float}.  Optionally, it verifies that a value is between a given
minimum or maximum.

@item 
@code{String} verifies that a value is a @ref{169,,str}.  Optionally, it
validates a given minimum or maximum length.  It can validate a
user-defined predicate@footnote{https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)} as well.
@end enumerate

@example
class OneOf(Validator):

    def __init__(self, *options):
        self.options = set(options)

    def validate(self, value):
        if value not in self.options:
            raise ValueError(
                f'Expected @{value!r@} to be one of @{self.options!r@}'
            )

class Number(Validator):

    def __init__(self, minvalue=None, maxvalue=None):
        self.minvalue = minvalue
        self.maxvalue = maxvalue

    def validate(self, value):
        if not isinstance(value, (int, float)):
            raise TypeError(f'Expected @{value!r@} to be an int or float')
        if self.minvalue is not None and value < self.minvalue:
            raise ValueError(
                f'Expected @{value!r@} to be at least @{self.minvalue!r@}'
            )
        if self.maxvalue is not None and value > self.maxvalue:
            raise ValueError(
                f'Expected @{value!r@} to be no more than @{self.maxvalue!r@}'
            )

class String(Validator):

    def __init__(self, minsize=None, maxsize=None, predicate=None):
        self.minsize = minsize
        self.maxsize = maxsize
        self.predicate = predicate

    def validate(self, value):
        if not isinstance(value, str):
            raise TypeError(f'Expected @{value!r@} to be a str')
        if self.minsize is not None and len(value) < self.minsize:
            raise ValueError(
                f'Expected @{value!r@} to be no smaller than @{self.minsize!r@}'
            )
        if self.maxsize is not None and len(value) > self.maxsize:
            raise ValueError(
                f'Expected @{value!r@} to be no bigger than @{self.maxsize!r@}'
            )
        if self.predicate is not None and not self.predicate(value):
            raise ValueError(
                f'Expected @{self.predicate@} to be true for @{value!r@}'
            )
@end example

@node 実践的なアプリケーション,,カスタムバリデータ,実践的なサンプル
@anchor{howto/descriptor practical-application}@anchor{56cc}
@subsubsection 実践的なアプリケーション


次のコードは実際のクラスでデータバリデータを使う方法のサンプルです。

@example
class Component:

    name = String(minsize=3, maxsize=10, predicate=str.isupper)
    kind = OneOf('wood', 'metal', 'plastic')
    quantity = Number(minvalue=0)

    def __init__(self, name, kind, quantity):
        self.name = name
        self.kind = kind
        self.quantity = quantity
@end example

これらのデスクリプタは、不正インスタンスが作成されるのを防ぎます。

@example
>>> Component('Widget', 'metal', 5)      # Blocked: 'Widget' is not all uppercase
Traceback (most recent call last):
    ...
ValueError: Expected <method 'isupper' of 'str' objects> to be true for 'Widget'

>>> Component('WIDGET', 'metle', 5)      # Blocked: 'metle' is misspelled
Traceback (most recent call last):
    ...
ValueError: Expected 'metle' to be one of @{'metal', 'plastic', 'wood'@}

>>> Component('WIDGET', 'metal', -5)     # Blocked: -5 is negative
Traceback (most recent call last):
    ...
ValueError: Expected -5 to be at least 0

>>> Component('WIDGET', 'metal', 'V')    # Blocked: 'V' isn't a number
Traceback (most recent call last):
    ...
TypeError: Expected 'V' to be an int or float

>>> c = Component('WIDGET', 'metal', 5)  # Allowed:  The inputs are valid
@end example

@node 技術的なチュートリアル,ピュアPythonの等価実装,実践的なサンプル,デスクリプタ ガイド
@anchor{howto/descriptor technical-tutorial}@anchor{56cd}
@subsection 技術的なチュートリアル


これから先はデスクリプタのメカニズムや動作の詳細について、よりテクニカルなチュートリアルになります。

@menu
* 概要: 概要<5>. 
* 定義と導入:: 
* デスクリプタプロトコル:: 
* デスクリプタ呼び出しの概要:: 
* インスタンスからの呼び出し:: 
* クラスからの呼び出し:: 
* superからの呼び出し:: 
* 呼び出しロジックのまとめ:: 
* 自動的の名前の伝達:: 
* ORMのサンプル:: 

@end menu

@node 概要<5>,定義と導入,,技術的なチュートリアル
@anchor{howto/descriptor abstract}@anchor{56ce}
@subsubsection 概要


デスクリプタの定義、プロトコルのサマリー、デスクリプタがどのように呼び出されるかの説明、ORマッパーがどのように動作するかのサンプルを提示します。

デスクリプタについて学ぶことにより、新しいツールセットが使えるようになるだけでなく、Python の仕組みについてのより深い理解が得られます。

@node 定義と導入,デスクリプタプロトコル,概要<5>,技術的なチュートリアル
@anchor{howto/descriptor definition-and-introduction}@anchor{56cf}
@subsubsection 定義と導入


In general, a descriptor is an attribute value that has one of the methods in
the descriptor protocol.  Those methods are @ref{1701,,__get__()}, @ref{23b5,,__set__()},
and @ref{194f,,__delete__()}.  If any of those methods are defined for an
attribute, it is said to be a @ref{1881,,descriptor}.

属性アクセスのデフォルトの振る舞いは、オブジェクトの辞書の属性の取得、設定、削除です。例えば @code{a.x} は、まず @code{a.__dict__['x']}、それから @code{type(a).__dict__['x']}、さらに @code{type(a)} のメソッド探索順序に従ったさらなる探索へと連鎖します。見つかった値が、デスクリプタメソッドのいずれかを定義しているオブジェクトなら、Python はそのデフォルトの振る舞いをオーバーライドし、代わりにデスクリプタメソッドを呼び出します。これがどの連鎖順位で行われるかは、どのデスクリプタメソッドが定義されているかに依ります。

Descriptors are a powerful, general purpose protocol.  They are the mechanism
behind properties, methods, static methods, class methods, and
@ref{1a6,,super()}.  They are used throughout Python itself.  Descriptors
simplify the underlying C code and offer a flexible set of new tools for
everyday Python programs.

@node デスクリプタプロトコル,デスクリプタ呼び出しの概要,定義と導入,技術的なチュートリアル
@anchor{howto/descriptor descriptor-protocol}@anchor{56d0}
@subsubsection デスクリプタプロトコル


@code{descr.__get__(self, obj, type=None)}

@code{descr.__set__(self, obj, value)}

@code{descr.__delete__(self, obj)}

これで全てです。これらのメソッドのいずれかを定義すれば、オブジェクトはデスクリプタとみなされ、探索された際のデフォルトの振る舞いをオーバーライドできます。

If an object defines @ref{23b5,,__set__()} or @ref{194f,,__delete__()}, it is considered
a data descriptor.  Descriptors that only define @ref{1701,,__get__()} are called
non-data descriptors (they are often used for methods but other uses are
possible).

データデスクリプタと非データデスクリプタでは、オーバーライドがインスタンスの辞書のエントリに関してどのように計算されるかが異なります。インスタンスの辞書に、データデスクリプタと同名の項目があれば、データデスクリプタの方が優先されます。インスタンスの辞書に、非データデスクリプタと同名の項目があれば、辞書の項目の方が優先されます。

To make a read-only data descriptor, define both @ref{1701,,__get__()} and
@ref{23b5,,__set__()} with the @ref{23b5,,__set__()} raising an @ref{5f0,,AttributeError} when
called.  Defining the @ref{23b5,,__set__()} method with an exception raising
placeholder is enough to make it a data descriptor.

@node デスクリプタ呼び出しの概要,インスタンスからの呼び出し,デスクリプタプロトコル,技術的なチュートリアル
@anchor{howto/descriptor overview-of-descriptor-invocation}@anchor{56d1}
@subsubsection デスクリプタ呼び出しの概要


@code{desc.__get__(obj)} や @code{desc.__get__(None, cls)} を使うとデスクリプタを直接呼び出すことができます。

しかし、属性アクセスの際に自動的に呼び出されるのが、一般的なデスクリプタの呼び出し方法です。

The expression @code{obj.x} looks up the attribute @code{x} in the chain of
namespaces for @code{obj}.  If the search finds a descriptor outside of the
instance @ref{77d,,__dict__}, its @ref{1701,,__get__()} method is
invoked according to the precedence rules listed below.

呼び出しの詳細は、@code{obj} がオブジェクトかクラスか、superのインスタンスかに依ります。

@node インスタンスからの呼び出し,クラスからの呼び出し,デスクリプタ呼び出しの概要,技術的なチュートリアル
@anchor{howto/descriptor invocation-from-an-instance}@anchor{56d2}
@subsubsection インスタンスからの呼び出し


Instance lookup scans through a chain of namespaces giving data descriptors
the highest priority, followed by instance variables, then non-data
descriptors, then class variables, and lastly @ref{6fa,,__getattr__()} if it is
provided.

@code{a.x} に対するデスクリプタが見つかった場合、 @code{desc.__get__(a, type(a))} という形式で呼び出されます。

ドットによるルックアップのロジックは@ref{dcb,,object.__getattribute__()} の中で行われます。ピュアPythonで表した等価なロジックは次の通りです。

@example
def find_name_in_mro(cls, name, default):
    "Emulate _PyType_Lookup() in Objects/typeobject.c"
    for base in cls.__mro__:
        if name in vars(base):
            return vars(base)[name]
    return default

def object_getattribute(obj, name):
    "Emulate PyObject_GenericGetAttr() in Objects/object.c"
    null = object()
    objtype = type(obj)
    cls_var = find_name_in_mro(objtype, name, null)
    descr_get = getattr(type(cls_var), '__get__', null)
    if descr_get is not null:
        if (hasattr(type(cls_var), '__set__')
            or hasattr(type(cls_var), '__delete__')):
            return descr_get(cls_var, obj, objtype)     # data descriptor
    if hasattr(obj, '__dict__') and name in vars(obj):
        return vars(obj)[name]                          # instance variable
    if descr_get is not null:
        return descr_get(cls_var, obj, objtype)         # non-data descriptor
    if cls_var is not null:
        return cls_var                                  # class variable
    raise AttributeError(name)
@end example

@c # Test the fidelity of object_getattribute() by comparing it with the
@c # normal object.__getattribute__().  The former will be accessed by
@c # square brackets and the latter by the dot operator.
@c 
@c class Object:
@c 
@c     def __getitem__(obj, name):
@c         try:
@c             return object_getattribute(obj, name)
@c         except AttributeError:
@c             if not hasattr(type(obj), '__getattr__'):
@c                 raise
@c         return type(obj).__getattr__(obj, name)             # __getattr__
@c 
@c class DualOperator(Object):
@c 
@c     x = 10
@c 
@c     def __init__(self, z):
@c         self.z = z
@c 
@c     @property
@c     def p2(self):
@c         return 2 * self.x
@c 
@c     @property
@c     def p3(self):
@c         return 3 * self.x
@c 
@c     def m5(self, y):
@c         return 5 * y
@c 
@c     def m7(self, y):
@c         return 7 * y
@c 
@c     def __getattr__(self, name):
@c         return ('getattr_hook', self, name)
@c 
@c class DualOperatorWithSlots:
@c 
@c     __getitem__ = Object.__getitem__
@c 
@c     __slots__ = ['z']
@c 
@c     x = 15
@c 
@c     def __init__(self, z):
@c         self.z = z
@c 
@c     @property
@c     def p2(self):
@c         return 2 * self.x
@c 
@c     def m5(self, y):
@c         return 5 * y
@c 
@c     def __getattr__(self, name):
@c         return ('getattr_hook', self, name)
@c 
@c class D1:
@c     def __get__(self, obj, objtype=None):
@c         return type(self), obj, objtype
@c 
@c class U1:
@c     x = D1()
@c 
@c class U2(U1):
@c     pass

@c >>> a = DualOperator(11)
@c >>> vars(a).update(p3 = '_p3', m7 = '_m7')
@c >>> a.x == a['x'] == 10
@c True
@c >>> a.z == a['z'] == 11
@c True
@c >>> a.p2 == a['p2'] == 20
@c True
@c >>> a.p3 == a['p3'] == 30
@c True
@c >>> a.m5(100) == a.m5(100) == 500
@c True
@c >>> a.m7 == a['m7'] == '_m7'
@c True
@c >>> a.g == a['g'] == ('getattr_hook', a, 'g')
@c True
@c 
@c >>> b = DualOperatorWithSlots(22)
@c >>> b.x == b['x'] == 15
@c True
@c >>> b.z == b['z'] == 22
@c True
@c >>> b.p2 == b['p2'] == 30
@c True
@c >>> b.m5(200) == b['m5'](200) == 1000
@c True
@c >>> b.g == b['g'] == ('getattr_hook', b, 'g')
@c True
@c 
@c >>> u2 = U2()
@c >>> object_getattribute(u2, 'x') == u2.x == (D1, u2, U2)
@c True

Note, there is no @ref{6fa,,__getattr__()} hook in the @ref{dcb,,__getattribute__()}
code.  That is why calling @ref{dcb,,__getattribute__()} directly or with
@code{super().__getattribute__} will bypass @ref{6fa,,__getattr__()} entirely.

Instead, it is the dot operator and the @ref{dca,,getattr()} function that are
responsible for invoking @ref{6fa,,__getattr__()} whenever @ref{dcb,,__getattribute__()}
raises an @ref{5f0,,AttributeError}.  Their logic is encapsulated in a helper
function:

@example
def getattr_hook(obj, name):
    "Emulate slot_tp_getattr_hook() in Objects/typeobject.c"
    try:
        return obj.__getattribute__(name)
    except AttributeError:
        if not hasattr(type(obj), '__getattr__'):
            raise
    return type(obj).__getattr__(obj, name)             # __getattr__
@end example

@c >>> class ClassWithGetAttr:
@c ...     x = 123
@c ...     def __getattr__(self, attr):
@c ...         return attr.upper()
@c ...
@c >>> cw = ClassWithGetAttr()
@c >>> cw.y = 456
@c >>> getattr_hook(cw, 'x')
@c 123
@c >>> getattr_hook(cw, 'y')
@c 456
@c >>> getattr_hook(cw, 'z')
@c 'Z'
@c 
@c >>> class ClassWithoutGetAttr:
@c ...     x = 123
@c ...
@c >>> cwo = ClassWithoutGetAttr()
@c >>> cwo.y = 456
@c >>> getattr_hook(cwo, 'x')
@c 123
@c >>> getattr_hook(cwo, 'y')
@c 456
@c >>> getattr_hook(cwo, 'z')
@c Traceback (most recent call last):
@c     ...
@c AttributeError: 'ClassWithoutGetAttr' object has no attribute 'z'

@node クラスからの呼び出し,superからの呼び出し,インスタンスからの呼び出し,技術的なチュートリアル
@anchor{howto/descriptor invocation-from-a-class}@anchor{56d3}
@subsubsection クラスからの呼び出し


The logic for a dotted lookup such as @code{A.x} is in
@code{type.__getattribute__()}.  The steps are similar to those for
@code{object.__getattribute__()} but the instance dictionary lookup is replaced
by a search through the class's @ref{25df,,method resolution order}.

@code{a.x} に対するデスクリプタが見つかった場合、 @code{desc.__get__(None, A)} という形式で呼び出されます。

完全な C での実装は Objects/typeobject.c@footnote{https://github.com/python/cpython/tree/3.14/Objects/typeobject.c} の中の:c:func:@cite{!type_getattro} と @code{_PyType_Lookup()} を参照してください。

@node superからの呼び出し,呼び出しロジックのまとめ,クラスからの呼び出し,技術的なチュートリアル
@anchor{howto/descriptor invocation-from-super}@anchor{56d4}
@subsubsection superからの呼び出し


The logic for super's dotted lookup is in the @ref{dcb,,__getattribute__()} method for
object returned by @ref{1a6,,super()}.

@code{super(A, obj).m} のようなドットを使ったルックアップは @code{obj.__class__.__mro__} を探索して、 @code{A} の直前のクラス @code{B} をまず探し、 @code{B.__dict__['m'].__get__(obj, A)} を返します。もしデスクリプタでなければ @code{m} を変更せずに返します。

完全な C での実装は Objects/typeobject.c@footnote{https://github.com/python/cpython/tree/3.14/Objects/typeobject.c} の中の @code{super_getattro()} を参照してください。純粋な Python での同等なコードは Guido's Tutorial@footnote{https://www.python.org/download/releases/2.2.3/descrintro/#cooperation} を参照してください。

@node 呼び出しロジックのまとめ,自動的の名前の伝達,superからの呼び出し,技術的なチュートリアル
@anchor{howto/descriptor summary-of-invocation-logic}@anchor{56d5}
@subsubsection 呼び出しロジックのまとめ


The mechanism for descriptors is embedded in the @ref{dcb,,__getattribute__()}
methods for @ref{c7e,,object}, @ref{f44,,type}, and @ref{1a6,,super()}.

憶えておくべき重要な点は:


@itemize *

@item 
Descriptors are invoked by the @ref{dcb,,__getattribute__()} method.

@item 
クラスはこの機構を @ref{c7e,,object} 、 @ref{f44,,type} 、 @ref{1a6,,super()} から継承する

@item 
Overriding @ref{dcb,,__getattribute__()} prevents automatic descriptor calls
because all the descriptor logic is in that method.

@item 
@code{object.__getattribute__()} and @code{type.__getattribute__()} make
different calls to @ref{1701,,__get__()}.  The first includes the instance and may
include the class.  The second puts in @code{None} for the instance and always
includes the class.

@item 
データデスクリプタは、必ずインスタンス辞書をオーバーライドする

@item 
非データデスクリプタは、インスタンス辞書にオーバーライドされることがある
@end itemize

@node 自動的の名前の伝達,ORMのサンプル,呼び出しロジックのまとめ,技術的なチュートリアル
@anchor{howto/descriptor automatic-name-notification}@anchor{56d6}
@subsubsection 自動的の名前の伝達


Sometimes it is desirable for a descriptor to know what class variable name it
was assigned to.  When a new class is created, the @ref{f44,,type} metaclass
scans the dictionary of the new class.  If any of the entries are descriptors
and if they define @ref{e48,,__set_name__()}, that method is called with two
arguments.  The `owner' is the class where the descriptor is used, and the
`name' is the class variable the descriptor was assigned to.

実装の詳細は Objects/typeobject.c@footnote{https://github.com/python/cpython/tree/3.14/Objects/typeobject.c} の中の @code{type_new()} と @code{set_names()} を参照してください。

Since the update logic is in @code{type.__new__()}, notifications only take
place at the time of class creation.  If descriptors are added to the class
afterwards, @ref{e48,,__set_name__()} will need to be called manually.

@node ORMのサンプル,,自動的の名前の伝達,技術的なチュートリアル
@anchor{howto/descriptor orm-example}@anchor{56d7}
@subsubsection ORMのサンプル


以下のコードは、 オブジェクト関係マッピング@footnote{https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping} を実装するのにデータディスクリプタを使う方法を示した、簡略化された骨格です。

基本的な考え方は、データが外部のデータベースに保存することです。 Pythonインスタンスは、データベースのテーブルへのキーのみを保持します。デスクリプタがルックアップや更新をします。

@example
class Field:

    def __set_name__(self, owner, name):
        self.fetch = f'SELECT @{name@} FROM @{owner.table@} WHERE @{owner.key@}=?;'
        self.store = f'UPDATE @{owner.table@} SET @{name@}=? WHERE @{owner.key@}=?;'

    def __get__(self, obj, objtype=None):
        return conn.execute(self.fetch, [obj.key]).fetchone()[0]

    def __set__(self, obj, value):
        conn.execute(self.store, [value, obj.key])
        conn.commit()
@end example

We can use the @code{Field} class to define models@footnote{https://en.wikipedia.org/wiki/Database_model} that describe the schema for
each table in a database:

@example
class Movie:
    table = 'Movies'                    # Table name
    key = 'title'                       # Primary key
    director = Field()
    year = Field()

    def __init__(self, key):
        self.key = key

class Song:
    table = 'Music'
    key = 'title'
    artist = Field()
    year = Field()
    genre = Field()

    def __init__(self, key):
        self.key = key
@end example

モデルを使用するにはまずデータベースに接続します:

@example
>>> import sqlite3
>>> conn = sqlite3.connect('entertainment.db')
@end example

次のインタラクティブセッションでは、データベースからのデータの取得と、更新方法を示しています。

@c song_data = [
@c     ('Country Roads', 'John Denver', 1972),
@c     ('Me and Bobby McGee', 'Janice Joplin', 1971),
@c     ('Coal Miners Daughter', 'Loretta Lynn', 1970),
@c ]
@c 
@c movie_data = [
@c     ('Star Wars', 'George Lucas', 1977),
@c     ('Jaws', 'Steven Spielberg', 1975),
@c     ('Aliens', 'James Cameron', 1986),
@c ]
@c 
@c import sqlite3
@c 
@c conn = sqlite3.connect(':memory:')
@c conn.execute('CREATE TABLE Music (title text, artist text, year integer);')
@c conn.execute('CREATE INDEX MusicNdx ON Music (title);')
@c conn.executemany('INSERT INTO Music VALUES (?, ?, ?);', song_data)
@c conn.execute('CREATE TABLE Movies (title text, director text, year integer);')
@c conn.execute('CREATE INDEX MovieNdx ON Music (title);')
@c conn.executemany('INSERT INTO Movies VALUES (?, ?, ?);', movie_data)
@c conn.commit()

@example
>>> Movie('Star Wars').director
'George Lucas'
>>> jaws = Movie('Jaws')
>>> f'Released in @{jaws.year@} by @{jaws.director@}'
'Released in 1975 by Steven Spielberg'

>>> Song('Country Roads').artist
'John Denver'

>>> Movie('Star Wars').director = 'J.J. Abrams'
>>> Movie('Star Wars').director
'J.J. Abrams'
@end example

@c conn.close()

@node ピュアPythonの等価実装,,技術的なチュートリアル,デスクリプタ ガイド
@anchor{howto/descriptor pure-python-equivalents}@anchor{56d8}
@subsection ピュアPythonの等価実装


このプロトコルは単純ですが、ワクワクする可能性も秘めています。ユースケースの中には、あまりに一般的なので組み込みに追加されたものもあります。プロパティ、束縛のメソッド、静的メソッド、クラスメソッド、 __slots__ は、全てデスクリプタプロトコルに基づいています。

@menu
* プロパティ:: 
* 関数とメソッド:: 
* メソッドの種類:: 
* 静的メソッド:: 
* クラスメソッド:: 
* メンバーオブジェクトと __slots__:: 

@end menu

@node プロパティ,関数とメソッド,,ピュアPythonの等価実装
@anchor{howto/descriptor properties}@anchor{56d9}
@subsubsection プロパティ


@ref{4b3,,property()} を呼び出すことで、属性へアクセスすると関数の呼び出しを引き起こす、データデスクリプタを簡潔に組み立てられます。シグネチャはこうです:

@example
property(fget=None, fset=None, fdel=None, doc=None) -> property
@end example

このドキュメントでは、管理された属性 @code{x} を定義する典型的な使用法を示します:

@example
class C:
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I'm the 'x' property.")
@end example

@c >>> C.x.__doc__
@c "I'm the 'x' property."
@c >>> c.x = 2.71828
@c >>> c.x
@c 2.71828
@c >>> del c.x
@c >>> c.x
@c Traceback (most recent call last):
@c   ...
@c AttributeError: 'C' object has no attribute '_C__x'

To see how @ref{4b3,,property()} is implemented in terms of the descriptor protocol,
here is a pure Python equivalent that implements most of the core functionality:

@example
class Property:
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __set_name__(self, owner, name):
        self.__name__ = name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)
@end example

@c # Verify the Property() emulation
@c 
@c class CC:
@c     def getx(self):
@c         return self.__x
@c     def setx(self, value):
@c         self.__x = value
@c     def delx(self):
@c         del self.__x
@c     x = Property(getx, setx, delx, "I'm the 'x' property.")
@c     no_getter = Property(None, setx, delx, "I'm the 'x' property.")
@c     no_setter = Property(getx, None, delx, "I'm the 'x' property.")
@c     no_deleter = Property(getx, setx, None, "I'm the 'x' property.")
@c     no_doc = Property(getx, setx, delx, None)
@c 
@c 
@c # Now do it again but use the decorator style
@c 
@c class CCC:
@c     @Property
@c     def x(self):
@c         return self.__x
@c     @x.setter
@c     def x(self, value):
@c         self.__x = value
@c     @x.deleter
@c     def x(self):
@c         del self.__x

@c >>> cc = CC()
@c >>> hasattr(cc, 'x')
@c False
@c >>> cc.x = 33
@c >>> cc.x
@c 33
@c >>> del cc.x
@c >>> hasattr(cc, 'x')
@c False
@c 
@c >>> ccc = CCC()
@c >>> hasattr(ccc, 'x')
@c False
@c >>> ccc.x = 333
@c >>> ccc.x == 333
@c True
@c >>> del ccc.x
@c >>> hasattr(ccc, 'x')
@c False
@c 
@c >>> cc = CC()
@c >>> cc.x = 33
@c >>> try:
@c ...     cc.no_getter
@c ... except AttributeError as e:
@c ...     type(e).__name__
@c ...
@c 'AttributeError'
@c 
@c >>> try:
@c ...     cc.no_setter = 33
@c ... except AttributeError as e:
@c ...     type(e).__name__
@c ...
@c 'AttributeError'
@c 
@c >>> try:
@c ...     del cc.no_deleter
@c ... except AttributeError as e:
@c ...     type(e).__name__
@c ...
@c 'AttributeError'
@c 
@c >>> CC.no_doc.__doc__ is None
@c True

組み込みの @ref{4b3,,property()} 関数は、ユーザインターフェースへの属性アクセスが与えられ、続く変更がメソッドの介入を要求するときに役立ちます。

例えば、スプレッドシートクラスが、@code{Cell('b10').value} でセルの値を取得できるとします。続く改良により、プログラムがアクセスの度にセルの再計算をすることを要求しました。しかしプログラマは、その属性に直接アクセスする既存のクライアントコードに影響を与えたくありません。この解決策は、property データデスクリプタ内に値属性へのアクセスをラップすることです:

@example
class Cell:
    ...

    @@property
    def value(self):
        "Recalculate the cell before returning value"
        self.recalc()
        return self._value
@end example

Either the built-in @ref{4b3,,property()} or our @code{Property()} equivalent would
work in this example.

@node 関数とメソッド,メソッドの種類,プロパティ,ピュアPythonの等価実装
@anchor{howto/descriptor functions-and-methods}@anchor{56da}
@subsubsection 関数とメソッド


Python のオブジェクト指向機能は、関数に基づく環境の上に構築されています。非データデスクリプタを使って、この 2 つはシームレスに組み合わされています。

クラス辞書に格納された関数は、実行時にメソッドに変換されます。メソッドと通常の関数はオブジェクトのインスタンスが他の引数よりも前に渡される点だけが異なります。監修ではインスタンスは `self' という名前が使われますが、 `this' や他の変数名も使えます。

メソッドは、ほぼ次のコードと同等な @ref{1b83,,types.MethodType} を使えば手動で作れます。

@example
class MethodType:
    "Emulate PyMethod_Type in Objects/classobject.c"

    def __init__(self, func, obj):
        self.__func__ = func
        self.__self__ = obj

    def __call__(self, *args, **kwargs):
        func = self.__func__
        obj = self.__self__
        return func(obj, *args, **kwargs)

    def __getattribute__(self, name):
        "Emulate method_getset() in Objects/classobject.c"
        if name == '__doc__':
            return self.__func__.__doc__
        return object.__getattribute__(self, name)

    def __getattr__(self, name):
        "Emulate method_getattro() in Objects/classobject.c"
        return getattr(self.__func__, name)

    def __get__(self, obj, objtype=None):
        "Emulate method_descr_get() in Objects/classobject.c"
        return self
@end example

To support automatic creation of methods, functions include the
@ref{1701,,__get__()} method for binding methods during attribute access.  This
means that functions are non-data descriptors that return bound methods
during dotted lookup from an instance.  Here's how it works:

@example
class Function:
    ...

    def __get__(self, obj, objtype=None):
        "Simulate func_descr_get() in Objects/funcobject.c"
        if obj is None:
            return self
        return MethodType(self, obj)
@end example

次のクラスをインタプリタを起動すると、この関数デスクリプタが実際にどう働くかを見られます:

@example
class D:
    def f(self):
         return self

class D2:
    pass
@end example

@c >>> d = D()
@c >>> d2 = D2()
@c >>> d2.f = d.f.__get__(d2, D2)
@c >>> d2.f() is d
@c True

この関数はイントロスペクションをサポートするために @ref{1d24,,qualified name} も持っています。

@example
>>> D.f.__qualname__
'D.f'
@end example

Accessing the function through the class dictionary does not invoke
@ref{1701,,__get__()}.  Instead, it just returns the underlying function object:

@example
>>> D.__dict__['f']
<function D.f at 0x00C45070>
@end example

Dotted access from a class calls @ref{1701,,__get__()} which just returns the
underlying function unchanged:

@example
>>> D.f
<function D.f at 0x00C45070>
@end example

The interesting behavior occurs during dotted access from an instance.  The
dotted lookup calls @ref{1701,,__get__()} which returns a bound method object:

@example
>>> d = D()
>>> d.f
<bound method D.f of <__main__.D object at 0x00B18C90>>
@end example

内部では、束縛メソッドはオリジナルの関数と束縛されたインスタンスを保持しています。

@example
>>> d.f.__func__
<function D.f at 0x00C45070>

>>> d.f.__self__
<__main__.D object at 0x00B18C90>
@end example

もし、通常のメソッドの `self' や、クラスメソッドの `cls' がどこから来るの疑問に思っている人がいるとしたら、これがその答えになります！

@node メソッドの種類,静的メソッド,関数とメソッド,ピュアPythonの等価実装
@anchor{howto/descriptor kinds-of-methods}@anchor{56db}
@subsubsection メソッドの種類


非データデスクリプタは、関数をメソッドに束縛する、各種の一般的なパターンに、単純な機構を提供します。

To recap, functions have a @ref{1701,,__get__()} method so that they can be converted
to a method when accessed as attributes.  The non-data descriptor transforms an
@code{obj.f(*args)} call into @code{f(obj, *args)}.  Calling @code{cls.f(*args)}
becomes @code{f(*args)}.

このチャートは、束縛と、その 2 つの異なる便利な形をまとめています:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

変換

@tab

オブジェクトから呼び出される

@tab

クラスから呼び出される

@item

関数

@tab

f(obj, *args)

@tab

f(*args)

@item

静的メソッド

@tab

f(*args)

@tab

f(*args)

@item

クラスメソッド

@tab

f(type(obj), *args)

@tab

f(cls, *args)

@end multitable

@end quotation

@node 静的メソッド,クラスメソッド,メソッドの種類,ピュアPythonの等価実装
@anchor{howto/descriptor static-methods}@anchor{56dc}
@subsubsection 静的メソッド


静的メソッドは、下にある関数をそのまま返します。 @code{c.f} や @code{C.f} は、 @code{object.__getattribute__(c, "f")} や @code{object.__getattribute__(C, "f")} を直接探索するのと同じです。結果として、関数はオブジェクトとクラスから同じようにアクセスできます。

静的メソッドにすると良いのは、 @code{self} 変数への参照を持たないメソッドです。

For instance, a statistics package may include a container class for
experimental data.  The class provides normal methods for computing the average,
mean, median, and other descriptive statistics that depend on the data. However,
there may be useful functions which are conceptually related but do not depend
on the data.  For instance, @code{erf(x)} is handy conversion routine that comes up
in statistical work but does not directly depend on a particular dataset.
It can be called either from an object or the class:  @code{s.erf(1.5) --> 0.9332}
or @code{Sample.erf(1.5) --> 0.9332}.

静的メソッドは下にある関数をそのまま返すので、呼び出しの例は面白くありません:

@example
class E:
    @@staticmethod
    def f(x):
        return x * 10
@end example

@example
>>> E.f(3)
30
>>> E().f(3)
30
@end example

非データデスクリプタプロトコルを使うと、pure Python 版の @ref{453,,staticmethod()} は以下のようになります:

@example
import functools

class StaticMethod:
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f
        functools.update_wrapper(self, f)

    def __get__(self, obj, objtype=None):
        return self.f

    def __call__(self, *args, **kwds):
        return self.f(*args, **kwds)

    @@property
    def __annotations__(self):
        return self.f.__annotations__
@end example

The @ref{1223,,functools.update_wrapper()} call adds a @code{__wrapped__} attribute
that refers to the underlying function.  Also it carries forward
the attributes necessary to make the wrapper look like the wrapped
function, including @ref{14ec,,__name__}, @ref{2349,,__qualname__},
and @ref{13f1,,__doc__}.

@c class E_sim:
@c     @StaticMethod
@c     def f(x: int) -> str:
@c         "Simple function example"
@c         return "!" * x
@c 
@c wrapped_ord = StaticMethod(ord)

@c >>> E_sim.f(3)
@c '!!!'
@c >>> E_sim().f(3)
@c '!!!'
@c 
@c >>> sm = vars(E_sim)['f']
@c >>> type(sm).__name__
@c 'StaticMethod'
@c >>> f = E_sim.f
@c >>> type(f).__name__
@c 'function'
@c >>> sm.__name__
@c 'f'
@c >>> f.__name__
@c 'f'
@c >>> sm.__qualname__
@c 'E_sim.f'
@c >>> f.__qualname__
@c 'E_sim.f'
@c >>> sm.__doc__
@c 'Simple function example'
@c >>> f.__doc__
@c 'Simple function example'
@c >>> sm.__annotations__
@c {'x': <class 'int'>, 'return': <class 'str'>}
@c >>> f.__annotations__
@c {'x': <class 'int'>, 'return': <class 'str'>}
@c >>> sm.__module__ == f.__module__
@c True
@c >>> sm(3)
@c '!!!'
@c >>> f(3)
@c '!!!'
@c 
@c >>> wrapped_ord('A')
@c 65
@c >>> wrapped_ord.__module__ == ord.__module__
@c True
@c >>> wrapped_ord.__wrapped__ == ord
@c True
@c >>> wrapped_ord.__name__ == ord.__name__
@c True
@c >>> wrapped_ord.__qualname__ == ord.__qualname__
@c True
@c >>> wrapped_ord.__doc__ == ord.__doc__
@c True

@node クラスメソッド,メンバーオブジェクトと __slots__,静的メソッド,ピュアPythonの等価実装
@anchor{howto/descriptor class-methods}@anchor{56dd}
@subsubsection クラスメソッド


静的メソッドとは違って、クラスメソッドは関数を呼び出す前にクラス参照を引数リストの先頭に加えます。このフォーマットは、呼び出し元がオブジェクトでもクラスでも同じです:

@example
class F:
    @@classmethod
    def f(cls, x):
        return cls.__name__, x
@end example

@example
>>> F.f(3)
('F', 3)
>>> F().f(3)
('F', 3)
@end example

この振る舞いは、関数がクラス参照のみを必要とし、特定のインスタンスに保存されたデータに依存しないときに便利です。クラスメソッドの使い方の一つは、代わりのクラスコンストラクタを作ることです。例えば、クラスメソッド @ref{24e,,dict.fromkeys()} は新しい辞書をキーのリストから生成します。等価な pure Python 版は:

@example
class Dict(dict):
    @@classmethod
    def fromkeys(cls, iterable, value=None):
        "Emulate dict_fromkeys() in Objects/dictobject.c"
        d = cls()
        for key in iterable:
            d[key] = value
        return d
@end example

これで一意なキーを持つ新しい辞書が以下のように構成できます:

@example
>>> d = Dict.fromkeys('abracadabra')
>>> type(d) is Dict
True
>>> d
@{'a': None, 'b': None, 'r': None, 'c': None, 'd': None@}
@end example

非データデスクリプタプロトコルを使った、 @ref{48e,,classmethod()} の pure Python 版はこのようになります:

@example
import functools

class ClassMethod:
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f
        functools.update_wrapper(self, f)

    def __get__(self, obj, cls=None):
        if cls is None:
            cls = type(obj)
        return MethodType(self.f, cls)
@end example

@c # Verify the emulation works
@c class T:
@c     @ClassMethod
@c     def cm(cls, x: int, y: str) -> tuple[str, int, str]:
@c         "Class method that returns a tuple"
@c         return (cls.__name__, x, y)

@c >>> T.cm(11, 22)
@c ('T', 11, 22)
@c 
@c # Also call it from an instance
@c >>> t = T()
@c >>> t.cm(11, 22)
@c ('T', 11, 22)
@c 
@c # Verify that T uses our emulation
@c >>> type(vars(T)['cm']).__name__
@c 'ClassMethod'
@c 
@c # Verify that update_wrapper() correctly copied attributes
@c >>> T.cm.__name__
@c 'cm'
@c >>> T.cm.__qualname__
@c 'T.cm'
@c >>> T.cm.__doc__
@c 'Class method that returns a tuple'
@c >>> T.cm.__annotations__
@c {'x': <class 'int'>, 'y': <class 'str'>, 'return': tuple[str, int, str]}
@c 
@c # Verify that __wrapped__ was added and works correctly
@c >>> f = vars(T)['cm'].__wrapped__
@c >>> type(f).__name__
@c 'function'
@c >>> f.__name__
@c 'cm'
@c >>> f(T, 11, 22)
@c ('T', 11, 22)

@code{ClassMethod} 内の @ref{1223,,functools.update_wrapper()} の呼び出しは、根底にある関数を参照する @code{__wrapped__} 属性を追加します。また、ラッパーがそのラップされた関数のように見えるよう、必要な属性を追加します: @ref{14ec,,__name__} 、 @ref{2349,,__qualname__} 、 @ref{13f1,,__doc__} 、 @ref{13f0,,__annotations__} 。

@node メンバーオブジェクトと __slots__,,クラスメソッド,ピュアPythonの等価実装
@anchor{howto/descriptor member-objects-and-slots}@anchor{56de}
@subsubsection メンバーオブジェクトと __slots__


クラスが @code{__slots__} を定義すると、インスタンスの辞書が固定超のスロットの値の配列と置き換えられます。ユーザーの目線からみると、いくつかの変化があります。

1. Provides immediate detection of bugs due to misspelled attribute
assignments.  Only attribute names specified in @code{__slots__} are allowed:

@example
class Vehicle:
    __slots__ = ('id_number', 'make', 'model')
@end example

@example
>>> auto = Vehicle()
>>> auto.id_nubmer = 'VYE483814LQEX'
Traceback (most recent call last):
    ...
AttributeError: 'Vehicle' object has no attribute 'id_nubmer'
@end example

2. Helps create immutable objects where descriptors manage access to private
attributes stored in @code{__slots__}:

@example
class Immutable:

    __slots__ = ('_dept', '_name')          # Replace the instance dictionary

    def __init__(self, dept, name):
        self._dept = dept                   # Store to private attribute
        self._name = name                   # Store to private attribute

    @@property                               # Read-only descriptor
    def dept(self):
        return self._dept

    @@property
    def name(self):                         # Read-only descriptor
        return self._name
@end example

@example
>>> mark = Immutable('Botany', 'Mark Watney')
>>> mark.dept
'Botany'
>>> mark.dept = 'Space Pirate'
Traceback (most recent call last):
    ...
AttributeError: property 'dept' of 'Immutable' object has no setter
>>> mark.location = 'Mars'
Traceback (most recent call last):
    ...
AttributeError: 'Immutable' object has no attribute 'location'
@end example

3. Saves memory.  On a 64-bit Linux build, an instance with two attributes
takes 48 bytes with @code{__slots__} and 152 bytes without.  This flyweight design pattern@footnote{https://en.wikipedia.org/wiki/Flyweight_pattern} likely only
matters when a large number of instances are going to be created.

4. Improves speed.  Reading instance variables is 35% faster with
@code{__slots__} (as measured with Python 3.10 on an Apple M1 processor).

5. Blocks tools like @ref{763,,functools.cached_property()} which require an
instance dictionary to function correctly:

@example
from functools import cached_property

class CP:
    __slots__ = ()                          # Eliminates the instance dict

    @@cached_property                        # Requires an instance dict
    def pi(self):
        return 4 * sum((-1.0)**n / (2.0*n + 1.0)
                       for n in reversed(range(100_000)))
@end example

@example
>>> CP().pi
Traceback (most recent call last):
  ...
TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property.
@end example

@code{__slots__} はC構造体に直接アクセスし、オブジェクトのメモリ確保を制御する必要があるため、ピュアPythonバージョンを作成することはできません。しかし、プライベートの @code{__slotvalues} リストを使ってC構造体のスロットをほぼ忠実にエミュレートすることはできます。そのプライベートな構造体への読み書きはメンバーのデスクリプタによって管理されます。

@example
null = object()

class Member:

    def __init__(self, name, clsname, offset):
        'Emulate PyMemberDef in Include/structmember.h'
        # Also see descr_new() in Objects/descrobject.c
        self.name = name
        self.clsname = clsname
        self.offset = offset

    def __get__(self, obj, objtype=None):
        'Emulate member_get() in Objects/descrobject.c'
        # Also see PyMember_GetOne() in Python/structmember.c
        if obj is None:
            return self
        value = obj._slotvalues[self.offset]
        if value is null:
            raise AttributeError(self.name)
        return value

    def __set__(self, obj, value):
        'Emulate member_set() in Objects/descrobject.c'
        obj._slotvalues[self.offset] = value

    def __delete__(self, obj):
        'Emulate member_delete() in Objects/descrobject.c'
        value = obj._slotvalues[self.offset]
        if value is null:
            raise AttributeError(self.name)
        obj._slotvalues[self.offset] = null

    def __repr__(self):
        'Emulate member_repr() in Objects/descrobject.c'
        return f'<Member @{self.name!r@} of @{self.clsname!r@}>'
@end example

The @code{type.__new__()} method takes care of adding member objects to class
variables:

@example
class Type(type):
    'Simulate how the type metaclass adds member objects for slots'

    def __new__(mcls, clsname, bases, mapping, **kwargs):
        'Emulate 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, **kwargs)
@end example

@ref{7a0,,object.__new__()} メソッドはインスタンス辞書の代わりにスロットを持つインスタンスの作成の処理をします。おおざっぱにピュアPythonでのシミュレーションしたコードがこちらです。

@example
class Object:
    'Simulate how object.__new__() allocates memory for __slots__'

    def __new__(cls, *args, **kwargs):
        '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'@{cls.__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'@{cls.__name__!r@} object has no attribute @{name!r@}'
            )
        super().__delattr__(name)
@end example

To use the simulation in a real class, just inherit from @code{Object} and
set the @ref{23d0,,metaclass} to @code{Type}:

@example
class H(Object, metaclass=Type):
    'Instance variables stored in slots'

    slot_names = ['x', 'y']

    def __init__(self, x, y):
        self.x = x
        self.y = y
@end example

この時点ではメタクラスは `x' と `y' のメンバーオブジェクトをロードします。

@example
>>> from pprint import pp
>>> pp(dict(vars(H)))
@{'__module__': '__main__',
 '__doc__': 'Instance variables stored in slots',
 'slot_names': ['x', 'y'],
 '__init__': <function H.__init__ at 0x7fb5d302f9d0>,
 'x': <Member 'x' of 'H'>,
 'y': <Member 'y' of 'H'>@}
@end example

@c # We test this separately because the preceding section is not
@c # doctestable due to the hex memory address for the __init__ function
@c >>> isinstance(vars(H)['x'], Member)
@c True
@c >>> isinstance(vars(H)['y'], Member)
@c True

インスタンスが作成されると、属性が保持される @code{slot_values}  のリストをインスタンスが保持します:

@example
>>> h = H(10, 20)
>>> vars(h)
@{'_slotvalues': [10, 20]@}
>>> h.x = 55
>>> vars(h)
@{'_slotvalues': [55, 20]@}
@end example

スペルミスや、未アサインの属性は例外を送出します。

@example
>>> h.xz
Traceback (most recent call last):
    ...
AttributeError: 'H' object has no attribute 'xz'
@end example

@c  # Examples for deleted attributes are not shown because this section
@c  # is already a bit lengthy.  We still test that code here.
@c  >>> del h.x
@c  >>> hasattr(h, 'x')
@c  False
@c 
@c  # Also test the code for uninitialized slots
@c  >>> class HU(Object, metaclass=Type):
@c  ...     slot_names = ['x', 'y']
@c  ...
@c  >>> hu = HU()
@c  >>> hasattr(hu, 'x')
@c  False
@c  >>> hasattr(hu, 'y')
@c  False

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Debugging C API extensions and CPython Internals with GDB,列挙型 HOWTO,デスクリプタ ガイド,Python HOWTO
@anchor{howto/gdb_helpers doc}@anchor{56df}@anchor{howto/gdb_helpers debugging-c-api-extensions-and-cpython-internals-with-gdb}@anchor{56e0}@anchor{howto/gdb_helpers gdb}@anchor{56e1}@anchor{howto/gdb_helpers translation-repo}@anchor{56e2}
@section Debugging C API extensions and CPython Internals with GDB


This document explains how the Python GDB extension, @code{python-gdb.py}, can
be used with the GDB debugger to debug CPython extensions and the
CPython interpreter itself.

When debugging low-level problems such as crashes or deadlocks, a low-level
debugger, such as GDB, is useful to diagnose and correct the issue.
By default, GDB (or any of its front-ends) doesn't support high-level
information specific to the CPython interpreter.

The @code{python-gdb.py} extension adds CPython interpreter information to GDB.
The extension helps introspect the stack of currently executing Python functions.
Given a Python object represented by a @ref{5df,,PyObject}* pointer,
the extension surfaces the type and value of the object.

Developers who are working on CPython extensions or tinkering with parts
of CPython that are written in C can use this document to learn how to use the
@code{python-gdb.py} extension with GDB.

@cartouche
@quotation 注釈 
This document assumes that you are familiar with the basics of GDB and the
CPython C API. It consolidates guidance from the
devguide@footnote{https://devguide.python.org}  and the
Python wiki@footnote{https://wiki.python.org/moin/DebuggingWithGdb}.
@end quotation
@end cartouche

@menu
* Prerequisites:: 
* Using the Debug build and Development mode:: 
* Using the python-gdb extension:: 
* Use with GDB commands:: 

@end menu

@node Prerequisites,Using the Debug build and Development mode,,Debugging C API extensions and CPython Internals with GDB
@anchor{howto/gdb_helpers prerequisites}@anchor{56e3}
@subsection Prerequisites


You need to have:


@itemize -

@item 
GDB 7 or later. (For earlier versions of GDB, see @code{Misc/gdbinit} in the
sources of Python 3.11 or earlier.)

@item 
GDB-compatible debugging information for Python and any extension you are
debugging.

@item 
The @code{python-gdb.py} extension.
@end itemize

The extension is built with Python, but might be distributed separately or
not at all. Below, we include tips for a few common systems as examples.
Note that even if the instructions match your system, they might be outdated.

@menu
* Setup with Python built from source:: 
* Setup for Python from a Linux distro:: 

@end menu

@node Setup with Python built from source,Setup for Python from a Linux distro,,Prerequisites
@anchor{howto/gdb_helpers setup-with-python-built-from-source}@anchor{56e4}
@subsubsection Setup with Python built from source


When you build CPython from source, debugging information should be available,
and the build should add a @code{python-gdb.py} file to the root directory of
your repository.

To activate support, you must add the directory containing @code{python-gdb.py}
to GDB's "auto-load-safe-path".
If you haven't done this, recent versions of GDB will print out a warning
with instructions on how to do this.

@cartouche
@quotation 注釈 
If you do not see instructions for your version of GDB, put this in your
configuration file (@code{~/.gdbinit} or @code{~/.config/gdb/gdbinit}):

@example
add-auto-load-safe-path /path/to/cpython
@end example

You can also add multiple paths, separated by @code{:}.
@end quotation
@end cartouche

@node Setup for Python from a Linux distro,,Setup with Python built from source,Prerequisites
@anchor{howto/gdb_helpers setup-for-python-from-a-linux-distro}@anchor{56e5}
@subsubsection Setup for Python from a Linux distro


Most Linux systems provide debug information for the system Python
in a package called @code{python-debuginfo}, @code{python-dbg} or similar.
For example:


@itemize -

@item 
Fedora:

@quotation

@example
sudo dnf install gdb
sudo dnf debuginfo-install python3
@end example
@end quotation

@item 
Ubuntu:

@quotation

@example
sudo apt install gdb python3-dbg
@end example
@end quotation
@end itemize

On several recent Linux systems, GDB can download debugging symbols
automatically using `debuginfod'.
However, this will not install the @code{python-gdb.py} extension;
you generally do need to install the debug info package separately.

@node Using the Debug build and Development mode,Using the python-gdb extension,Prerequisites,Debugging C API extensions and CPython Internals with GDB
@anchor{howto/gdb_helpers using-the-debug-build-and-development-mode}@anchor{56e6}
@subsection Using the Debug build and Development mode


For easier debugging, you might want to:


@itemize -

@item 
Use a @ref{509,,debug build} of Python. (When building from source,
use @code{configure --with-pydebug}. On Linux distros, install and run a package
like @code{python-debug} or @code{python-dbg}, if available.)

@item 
Use the runtime @ref{508,,development mode} (@code{-X dev}).
@end itemize

Both enable extra assertions and disable some optimizations.
Sometimes this hides the bug you are trying to find, but in most cases they
make the process easier.

@node Using the python-gdb extension,Use with GDB commands,Using the Debug build and Development mode,Debugging C API extensions and CPython Internals with GDB
@anchor{howto/gdb_helpers using-the-python-gdb-extension}@anchor{56e7}
@subsection Using the @code{python-gdb} extension


When the extension is loaded, it provides two main features:
pretty printers for Python values, and additional commands.

@menu
* Pretty-printers:: 
* py-list:: 
* py-up and py-down:: 
* py-bt:: 
* py-print:: 
* py-locals:: 

@end menu

@node Pretty-printers,py-list,,Using the python-gdb extension
@anchor{howto/gdb_helpers pretty-printers}@anchor{56e8}
@subsubsection Pretty-printers


This is what a GDB backtrace looks like (truncated) when this extension is
enabled:

@example
#0  0x000000000041a6b1 in PyObject_Malloc (nbytes=Cannot access memory at address 0x7fffff7fefe8
) at Objects/obmalloc.c:748
#1  0x000000000041b7c0 in _PyObject_DebugMallocApi (id=111 'o', nbytes=24) at Objects/obmalloc.c:1445
#2  0x000000000041b717 in _PyObject_DebugMalloc (nbytes=24) at Objects/obmalloc.c:1412
#3  0x000000000044060a in _PyUnicode_New (length=11) at Objects/unicodeobject.c:346
#4  0x00000000004466aa in PyUnicodeUCS2_DecodeUTF8Stateful (s=0x5c2b8d "__lltrace__", size=11, errors=0x0, consumed=
    0x0) at Objects/unicodeobject.c:2531
#5  0x0000000000446647 in PyUnicodeUCS2_DecodeUTF8 (s=0x5c2b8d "__lltrace__", size=11, errors=0x0)
    at Objects/unicodeobject.c:2495
#6  0x0000000000440d1b in PyUnicodeUCS2_FromStringAndSize (u=0x5c2b8d "__lltrace__", size=11)
    at Objects/unicodeobject.c:551
#7  0x0000000000440d94 in PyUnicodeUCS2_FromString (u=0x5c2b8d "__lltrace__") at Objects/unicodeobject.c:569
#8  0x0000000000584abd in PyDict_GetItemString (v=
    @{'Yuck': <type at remote 0xad4730>, '__builtins__': <module at remote 0x7ffff7fd5ee8>, '__file__': 'Lib/test/crashers/nasty_eq_vs_dict.py', '__package__': None, 'y': <Yuck(i=0) at remote 0xaacd80>, 'dict': @{0: 0, 1: 1, 2: 2, 3: 3@}, '__cached__': None, '__name__': '__main__', 'z': <Yuck(i=0) at remote 0xaace60>, '__doc__': None@}, key=
    0x5c2b8d "__lltrace__") at Objects/dictobject.c:2171
@end example

Notice how the dictionary argument to @code{PyDict_GetItemString} is displayed
as its @code{repr()}, rather than an opaque @code{PyObject *} pointer.

The extension works by supplying a custom printing routine for values of type
@code{PyObject *}.  If you need to access lower-level details of an object, then
cast the value to a pointer of the appropriate type.  For example:

@example
(gdb) p globals
$1 = @{'__builtins__': <module at remote 0x7ffff7fb1868>, '__name__':
'__main__', 'ctypes': <module at remote 0x7ffff7f14360>, '__doc__': None,
'__package__': None@}

(gdb) p *(PyDictObject*)globals
$2 = @{ob_refcnt = 3, ob_type = 0x3dbdf85820, ma_fill = 5, ma_used = 5,
ma_mask = 7, ma_table = 0x63d0f8, ma_lookup = 0x3dbdc7ea70
<lookdict_string>, ma_smalltable = @{@{me_hash = 7065186196740147912,
me_key = '__builtins__', me_value = <module at remote 0x7ffff7fb1868>@},
@{me_hash = -368181376027291943, me_key = '__name__',
me_value ='__main__'@}, @{me_hash = 0, me_key = 0x0, me_value = 0x0@},
@{me_hash = 0, me_key = 0x0, me_value = 0x0@},
@{me_hash = -9177857982131165996, me_key = 'ctypes',
me_value = <module at remote 0x7ffff7f14360>@},
@{me_hash = -8518757509529533123, me_key = '__doc__', me_value = None@},
@{me_hash = 0, me_key = 0x0, me_value = 0x0@}, @{
  me_hash = 6614918939584953775, me_key = '__package__', me_value = None@}@}@}
@end example

Note that the pretty-printers do not actually call @code{repr()}.
For basic types, they try to match its result closely.

An area that can be confusing is that the custom printer for some types look a
lot like GDB's built-in printer for standard types.  For example, the
pretty-printer for a Python @code{int} (@ref{39e,,PyLongObject}*)
gives a representation that is not distinguishable from one of a
regular machine-level integer:

@example
(gdb) p some_machine_integer
$3 = 42

(gdb) p some_python_integer
$4 = 42
@end example

The internal structure can be revealed with a cast to @ref{39e,,PyLongObject}*:

@example
(gdb) p *(PyLongObject*)some_python_integer
$5 = @{ob_base = @{ob_base = @{ob_refcnt = 8, ob_type = 0x3dad39f5e0@}, ob_size = 1@},
ob_digit = @{42@}@}
@end example

A similar confusion can arise with the @code{str} type, where the output looks a
lot like gdb's built-in printer for @code{char *}:

@example
(gdb) p ptr_to_python_str
$6 = '__builtins__'
@end example

The pretty-printer for @code{str} instances defaults to using single-quotes (as
does Python's @code{repr} for strings) whereas the standard printer for @code{char *}
values uses double-quotes and contains a hexadecimal address:

@example
(gdb) p ptr_to_char_star
$7 = 0x6d72c0 "hello world"
@end example

Again, the implementation details can be revealed with a cast to
@ref{997,,PyUnicodeObject}*:

@example
(gdb) p *(PyUnicodeObject*)$6
$8 = @{ob_base = @{ob_refcnt = 33, ob_type = 0x3dad3a95a0@}, length = 12,
str = 0x7ffff2128500, hash = 7065186196740147912, state = 1, defenc = 0x0@}
@end example

@node py-list,py-up and py-down,Pretty-printers,Using the python-gdb extension
@anchor{howto/gdb_helpers py-list}@anchor{56e9}
@subsubsection @code{py-list}


@quotation

The extension adds a @code{py-list} command, which
lists the Python source code (if any) for the current frame in the selected
thread.  The current line is marked with a ">":

@example
(gdb) py-list
 901        if options.profile:
 902            options.profile = False
 903            profile_me()
 904            return
 905
>906        u = UI()
 907        if not u.quit:
 908            try:
 909                gtk.main()
 910            except KeyboardInterrupt:
 911                # properly quit on a keyboard interrupt...
@end example

Use @code{py-list START} to list at a different line number within the Python
source, and @code{py-list START,END} to list a specific range of lines within
the Python source.
@end quotation

@node py-up and py-down,py-bt,py-list,Using the python-gdb extension
@anchor{howto/gdb_helpers py-up-and-py-down}@anchor{56ea}
@subsubsection @code{py-up} and @code{py-down}


@quotation

The @code{py-up} and @code{py-down} commands are analogous to GDB's regular @code{up}
and @code{down} commands, but try to move at the level of CPython frames, rather
than C frames.

GDB is not always able to read the relevant frame information, depending on
the optimization level with which CPython was compiled. Internally, the
commands look for C frames that are executing the default frame evaluation
function (that is, the core bytecode interpreter loop within CPython) and
look up the value of the related @code{PyFrameObject *}.

They emit the frame number (at the C level) within the thread.

例えば:

@example
(gdb) py-up
#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/
gnome_sudoku/main.py, line 906, in start_game ()
    u = UI()
(gdb) py-up
#40 Frame 0x948e82c, for file /usr/lib/python2.6/site-packages/
gnome_sudoku/gnome_sudoku.py, line 22, in start_game(main=<module at remote 0xb771b7f4>)
    main.start_game()
(gdb) py-up
Unable to find an older python frame
@end example

so we're at the top of the Python stack.

The frame numbers correspond to those displayed by GDB's standard
@code{backtrace} command.
The command skips C frames which are not executing Python code.

Going back down:

@example
(gdb) py-down
#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/gnome_sudoku/main.py, line 906, in start_game ()
    u = UI()
(gdb) py-down
#34 (unable to read python frame information)
(gdb) py-down
#23 (unable to read python frame information)
(gdb) py-down
#19 (unable to read python frame information)
(gdb) py-down
#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/game_selector.py, line 201, in run_swallowed_dialog (self=<NewOrSavedGameSelector(new_game_model=<gtk.ListStore at remote 0x98fab44>, puzzle=None, saved_games=[@{'gsd.auto_fills': 0, 'tracking': @{@}, 'trackers': @{@}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\n7 8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': <float at remote 0x984b474>, 'gsd.hints': 0, 'timer.active_time': <float at remote 0x984b494>, 'timer.total_time': <float at remote 0x984b464>@}], dialog=<gtk.Dialog at remote 0x98faaa4>, saved_game_model=<gtk.ListStore at remote 0x98fad24>, sudoku_maker=<SudokuMaker(terminated=False, played=[], batch_siz...(truncated)
            swallower.run_dialog(self.dialog)
(gdb) py-down
#11 Frame 0x9aead74, for file /usr/lib/python2.6/site-packages/gnome_sudoku/dialog_swallower.py, line 48, in run_dialog (self=<SwappableArea(running=<gtk.Dialog at remote 0x98faaa4>, main_page=0) at remote 0x98fa6e4>, d=<gtk.Dialog at remote 0x98faaa4>)
            gtk.main()
(gdb) py-down
#8 (unable to read python frame information)
(gdb) py-down
Unable to find a newer python frame
@end example

and we're at the bottom of the Python stack.

Note that in Python 3.12 and newer, the same C stack frame can be used for
multiple Python stack frames. This means that @code{py-up} and @code{py-down}
may move multiple Python frames at once. For example:

@example
(gdb) py-up
#6 Frame 0x7ffff7fb62b0, for file /tmp/rec.py, line 5, in recursive_function (n=0)
   time.sleep(5)
#6 Frame 0x7ffff7fb6240, for file /tmp/rec.py, line 7, in recursive_function (n=1)
   recursive_function(n-1)
#6 Frame 0x7ffff7fb61d0, for file /tmp/rec.py, line 7, in recursive_function (n=2)
   recursive_function(n-1)
#6 Frame 0x7ffff7fb6160, for file /tmp/rec.py, line 7, in recursive_function (n=3)
   recursive_function(n-1)
#6 Frame 0x7ffff7fb60f0, for file /tmp/rec.py, line 7, in recursive_function (n=4)
   recursive_function(n-1)
#6 Frame 0x7ffff7fb6080, for file /tmp/rec.py, line 7, in recursive_function (n=5)
   recursive_function(n-1)
#6 Frame 0x7ffff7fb6020, for file /tmp/rec.py, line 9, in <module> ()
   recursive_function(5)
(gdb) py-up
Unable to find an older python frame
@end example
@end quotation

@node py-bt,py-print,py-up and py-down,Using the python-gdb extension
@anchor{howto/gdb_helpers py-bt}@anchor{56eb}
@subsubsection @code{py-bt}


@quotation

The @code{py-bt} command attempts to display a Python-level backtrace of the
current thread.

例えば:

@example
(gdb) py-bt
#8 (unable to read python frame information)
#11 Frame 0x9aead74, for file /usr/lib/python2.6/site-packages/gnome_sudoku/dialog_swallower.py, line 48, in run_dialog (self=<SwappableArea(running=<gtk.Dialog at remote 0x98faaa4>, main_page=0) at remote 0x98fa6e4>, d=<gtk.Dialog at remote 0x98faaa4>)
            gtk.main()
#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/game_selector.py, line 201, in run_swallowed_dialog (self=<NewOrSavedGameSelector(new_game_model=<gtk.ListStore at remote 0x98fab44>, puzzle=None, saved_games=[@{'gsd.auto_fills': 0, 'tracking': @{@}, 'trackers': @{@}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\n7 8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': <float at remote 0x984b474>, 'gsd.hints': 0, 'timer.active_time': <float at remote 0x984b494>, 'timer.total_time': <float at remote 0x984b464>@}], dialog=<gtk.Dialog at remote 0x98faaa4>, saved_game_model=<gtk.ListStore at remote 0x98fad24>, sudoku_maker=<SudokuMaker(terminated=False, played=[], batch_siz...(truncated)
            swallower.run_dialog(self.dialog)
#19 (unable to read python frame information)
#23 (unable to read python frame information)
#34 (unable to read python frame information)
#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/gnome_sudoku/main.py, line 906, in start_game ()
    u = UI()
#40 Frame 0x948e82c, for file /usr/lib/python2.6/site-packages/gnome_sudoku/gnome_sudoku.py, line 22, in start_game (main=<module at remote 0xb771b7f4>)
    main.start_game()
@end example

The frame numbers correspond to those displayed by GDB's standard
@code{backtrace} command.
@end quotation

@node py-print,py-locals,py-bt,Using the python-gdb extension
@anchor{howto/gdb_helpers py-print}@anchor{56ec}
@subsubsection @code{py-print}


@quotation

The @code{py-print} command looks up a Python name and tries to print it.
It looks in locals within the current thread, then globals, then finally
builtins:

@example
(gdb) py-print self
local 'self' = <SwappableArea(running=<gtk.Dialog at remote 0x98faaa4>,
main_page=0) at remote 0x98fa6e4>
(gdb) py-print __name__
global '__name__' = 'gnome_sudoku.dialog_swallower'
(gdb) py-print len
builtin 'len' = <built-in function len>
(gdb) py-print scarlet_pimpernel
'scarlet_pimpernel' not found
@end example

If the current C frame corresponds to multiple Python frames, @code{py-print}
only considers the first one.
@end quotation

@node py-locals,,py-print,Using the python-gdb extension
@anchor{howto/gdb_helpers py-locals}@anchor{56ed}
@subsubsection @code{py-locals}


@quotation

The @code{py-locals} command looks up all Python locals within the current
Python frame in the selected thread, and prints their representations:

@example
(gdb) py-locals
self = <SwappableArea(running=<gtk.Dialog at remote 0x98faaa4>,
main_page=0) at remote 0x98fa6e4>
d = <gtk.Dialog at remote 0x98faaa4>
@end example

If the current C frame corresponds to multiple Python frames, locals from
all of them will be shown:

@example
(gdb) py-locals
Locals for recursive_function
n = 0
Locals for recursive_function
n = 1
Locals for recursive_function
n = 2
Locals for recursive_function
n = 3
Locals for recursive_function
n = 4
Locals for recursive_function
n = 5
Locals for <module>
@end example
@end quotation

@node Use with GDB commands,,Using the python-gdb extension,Debugging C API extensions and CPython Internals with GDB
@anchor{howto/gdb_helpers use-with-gdb-commands}@anchor{56ee}
@subsection Use with GDB commands


The extension commands complement GDB's built-in commands.
For example, you can use a frame numbers shown by @code{py-bt} with the @code{frame}
command to go a specific frame within the selected thread, like this:

@example
(gdb) py-bt
(output snipped)
#68 Frame 0xaa4560, for file Lib/test/regrtest.py, line 1548, in <module> ()
        main()
(gdb) frame 68
#68 0x00000000004cd1e6 in PyEval_EvalFrameEx (f=Frame 0xaa4560, for file Lib/test/regrtest.py, line 1548, in <module> (), throwflag=0) at Python/ceval.c:2665
2665                            x = call_function(&sp, oparg);
(gdb) py-list
1543        # Run the tests in a context manager that temporary changes the CWD to a
1544        # temporary and writable directory. If it's not possible to create or
1545        # change the CWD, the original CWD will be used. The original CWD is
1546        # available from test_support.SAVEDCWD.
1547        with test_support.temp_cwd(TESTCWD, quiet=True):
>1548            main()
@end example

The @code{info threads} command will give you a list of the threads within the
process, and you can use the @code{thread} command to select a different one:

@example
(gdb) info threads
  105 Thread 0x7fffefa18710 (LWP 10260)  sem_wait () at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:86
  104 Thread 0x7fffdf5fe710 (LWP 10259)  sem_wait () at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:86
* 1 Thread 0x7ffff7fe2700 (LWP 10145)  0x00000038e46d73e3 in select () at ../sysdeps/unix/syscall-template.S:82
@end example

You can use @code{thread apply all COMMAND} or (@code{t a a COMMAND} for short) to run
a command on all threads.  With @code{py-bt}, this lets you see what every
thread is doing at the Python level:

@example
(gdb) t a a py-bt

Thread 105 (Thread 0x7fffefa18710 (LWP 10260)):
#5 Frame 0x7fffd00019d0, for file /home/david/coding/python-svn/Lib/threading.py, line 155, in _acquire_restore (self=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, _RLock__block=<thread.lock at remote 0x858770>, _RLock__count=1) at remote 0xd7ff40>, count_owner=(1, 140737213728528), count=1, owner=140737213728528)
        self.__block.acquire()
#8 Frame 0x7fffac001640, for file /home/david/coding/python-svn/Lib/threading.py, line 269, in wait (self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, _RLock__block=<thread.lock at remote 0x858770>, _RLock__count=1) at remote 0xd7ff40>, acquire=<instancemethod at remote 0xd80260>, _is_owned=<instancemethod at remote 0xd80160>, _release_save=<instancemethod at remote 0xd803e0>, release=<instancemethod at remote 0xd802e0>, _acquire_restore=<instancemethod at remote 0xd7ee60>, _Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, timeout=None, waiter=<thread.lock at remote 0x858a90>, saved_state=(1, 140737213728528))
            self._acquire_restore(saved_state)
#12 Frame 0x7fffb8001a10, for file /home/david/coding/python-svn/Lib/test/lock_tests.py, line 348, in f ()
            cond.wait()
#16 Frame 0x7fffb8001c40, for file /home/david/coding/python-svn/Lib/test/lock_tests.py, line 37, in task (tid=140737213728528)
                f()

Thread 104 (Thread 0x7fffdf5fe710 (LWP 10259)):
#5 Frame 0x7fffe4001580, for file /home/david/coding/python-svn/Lib/threading.py, line 155, in _acquire_restore (self=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, _RLock__block=<thread.lock at remote 0x858770>, _RLock__count=1) at remote 0xd7ff40>, count_owner=(1, 140736940992272), count=1, owner=140736940992272)
        self.__block.acquire()
#8 Frame 0x7fffc8002090, for file /home/david/coding/python-svn/Lib/threading.py, line 269, in wait (self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, _RLock__block=<thread.lock at remote 0x858770>, _RLock__count=1) at remote 0xd7ff40>, acquire=<instancemethod at remote 0xd80260>, _is_owned=<instancemethod at remote 0xd80160>, _release_save=<instancemethod at remote 0xd803e0>, release=<instancemethod at remote 0xd802e0>, _acquire_restore=<instancemethod at remote 0xd7ee60>, _Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, timeout=None, waiter=<thread.lock at remote 0x858860>, saved_state=(1, 140736940992272))
            self._acquire_restore(saved_state)
#12 Frame 0x7fffac001c90, for file /home/david/coding/python-svn/Lib/test/lock_tests.py, line 348, in f ()
            cond.wait()
#16 Frame 0x7fffac0011c0, for file /home/david/coding/python-svn/Lib/test/lock_tests.py, line 37, in task (tid=140736940992272)
                f()

Thread 1 (Thread 0x7ffff7fe2700 (LWP 10145)):
#5 Frame 0xcb5380, for file /home/david/coding/python-svn/Lib/test/lock_tests.py, line 16, in _wait ()
    time.sleep(0.01)
#8 Frame 0x7fffd00024a0, for file /home/david/coding/python-svn/Lib/test/lock_tests.py, line 378, in _check_notify (self=<ConditionTests(_testMethodName='test_notify', _resultForDoCleanups=<TestResult(_original_stdout=<cStringIO.StringO at remote 0xc191e0>, skipped=[], _mirrorOutput=False, testsRun=39, buffer=False, _original_stderr=<file at remote 0x7ffff7fc6340>, _stdout_buffer=<cStringIO.StringO at remote 0xc9c7f8>, _stderr_buffer=<cStringIO.StringO at remote 0xc9c790>, _moduleSetUpFailed=False, expectedFailures=[], errors=[], _previousTestClass=<type at remote 0x928310>, unexpectedSuccesses=[], failures=[], shouldStop=False, failfast=False) at remote 0xc185a0>, _threads=(0,), _cleanups=[], _type_equality_funcs=@{<type at remote 0x7eba00>: <instancemethod at remote 0xd750e0>, <type at remote 0x7e7820>: <instancemethod at remote 0xd75160>, <type at remote 0x7e30e0>: <instancemethod at remote 0xd75060>, <type at remote 0x7e7d20>: <instancemethod at remote 0xd751e0>, <type at remote 0x7f19e0...(truncated)
        _wait()
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 列挙型 HOWTO,関数型プログラミング HOWTO,Debugging C API extensions and CPython Internals with GDB,Python HOWTO
@anchor{howto/enum doc}@anchor{56ef}@anchor{howto/enum enum-howto}@anchor{56f0}@anchor{howto/enum id1}@anchor{56f1}@anchor{howto/enum translation-repo}@anchor{56f2}
@section 列挙型 HOWTO

@anchor{howto/enum enum-basic-tutorial}@anchor{2a26}
@ref{842,,Enum} は、ユニークな値に束縛されたシンボル名の集合です。グローバル変数に似ていますが、 @ref{1c1,,repr()} がより便利だったり、グルーピングの機能、型安全などいくつかの機能があります。

これらは、限られた選択肢の値の一つを取る変数がある場合に便利です。例えば、曜日情報があります:

@example
>>> from enum import Enum
>>> class Weekday(Enum):
...     MONDAY = 1
...     TUESDAY = 2
...     WEDNESDAY = 3
...     THURSDAY = 4
...     FRIDAY = 5
...     SATURDAY = 6
...     SUNDAY = 7
@end example

あるいは、RGB三原色でも構いません:

@example
>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
@end example

ご覧の通り、 @ref{842,,Enum} の作成は @ref{842,,Enum} 自体を継承するクラスを作成するのと同じくらい簡単です。

@cartouche
@quotation 注釈 
Enumメンバーは大文字/小文字？

列挙型は定数を表すために使われるため、また mixin クラスのメソッドや属性との名前の衝突の問題を回避するため、メンバには UPPER_CASE の名前を使うことが強く推奨されており、例でもこのスタイルを用います。
@end quotation
@end cartouche

列挙型の性質によって、メンバの値は重要な場合とそうでない場合がありますが、いずれの場合でも、その値は対応するメンバを取得するのに使えます:

@example
>>> Weekday(3)
<Weekday.WEDNESDAY: 3>
@end example

ご覧の通り、メンバの @code{repr()} は列挙型の名前、メンバの名前、そして値を表示します。メンバの @code{str()} は列挙型の名前とメンバの名前のみを表示します。

@example
>>> print(Weekday.THURSDAY)
Weekday.THURSDAY
@end example

列挙型のメンバの型はそのメンバの属する列挙型です:

@example
>>> type(Weekday.MONDAY)
<enum 'Weekday'>
>>> isinstance(Weekday.FRIDAY, Weekday)
True
@end example

Enum members have an attribute that contains just their @code{name}:

@example
>>> print(Weekday.TUESDAY.name)
TUESDAY
@end example

Likewise, they have an attribute for their @code{value}:

@example
>>> Weekday.WEDNESDAY.value
3
@end example

Unlike many languages that treat enumerations solely as name/value pairs,
Python Enums can have behavior added.  For example, @ref{1fa,,datetime.date}
has two methods for returning the weekday:
@ref{28c0,,weekday()} and @ref{28c1,,isoweekday()}.
The difference is that one of them counts from 0-6 and the other from 1-7.
Rather than keep track of that ourselves we can add a method to the @code{Weekday}
enum to extract the day from the @ref{1fa,,date} instance and return the matching
enum member:

@example
@@classmethod
def from_date(cls, date):
    return cls(date.isoweekday())
@end example

The complete @code{Weekday} enum now looks like this:

@example
>>> class Weekday(Enum):
...     MONDAY = 1
...     TUESDAY = 2
...     WEDNESDAY = 3
...     THURSDAY = 4
...     FRIDAY = 5
...     SATURDAY = 6
...     SUNDAY = 7
...     #
...     @@classmethod
...     def from_date(cls, date):
...         return cls(date.isoweekday())
@end example

さて、これで今日が何曜日か調べることができます！ 見てみましょう:

@example
>>> from datetime import date
>>> Weekday.from_date(date.today())
<Weekday.TUESDAY: 2>
@end example

もちろん、あなたがこれを読んでいるのが他の曜日ならば、その曜日が代わりに表示されます。

This @code{Weekday} enum is great if our variable only needs one day, but
what if we need several?  Maybe we're writing a function to plot chores during
a week, and don't want to use a @ref{24d,,list} -- we could use a different type
of @ref{842,,Enum}:

@example
>>> from enum import Flag
>>> class Weekday(Flag):
...     MONDAY = 1
...     TUESDAY = 2
...     WEDNESDAY = 4
...     THURSDAY = 8
...     FRIDAY = 16
...     SATURDAY = 32
...     SUNDAY = 64
@end example

ここでは2つの変更が行われています。@ref{835,,Flag} を継承している点と、値がすべて2の累乗である点です。

Just like the original @code{Weekday} enum above, we can have a single selection:

@example
>>> first_week_day = Weekday.MONDAY
>>> first_week_day
<Weekday.MONDAY: 1>
@end example

ただし、@ref{835,,Flag} は複数のメンバーをひとつの変数にまとめることもできます:

@example
>>> weekend = Weekday.SATURDAY | Weekday.SUNDAY
>>> weekend
<Weekday.SATURDAY|SUNDAY: 96>
@end example

@ref{835,,Flag} 変数は反復することもできます:

@example
>>> for day in weekend:
...     print(day)
Weekday.SATURDAY
Weekday.SUNDAY
@end example

さて、いくつかの家事を設定してみましょう:

@example
>>> chores_for_ethan = @{
...     'feed the cat': Weekday.MONDAY | Weekday.WEDNESDAY | Weekday.FRIDAY,
...     'do the dishes': Weekday.TUESDAY | Weekday.THURSDAY,
...     'answer SO questions': Weekday.SATURDAY,
...     @}
@end example

指定された日の家事を表示する関数も作成します:

@example
>>> def show_chores(chores, day):
...     for chore, days in chores.items():
...         if day in days:
...             print(chore)
...
>>> show_chores(chores_for_ethan, Weekday.SATURDAY)
answer SO questions
@end example

メンバーの実際の値が重要でない場合は、@ref{e9b,,auto()} を使用することで手間を省くことができます:

@example
>>> from enum import auto
>>> class Weekday(Flag):
...     MONDAY = auto()
...     TUESDAY = auto()
...     WEDNESDAY = auto()
...     THURSDAY = auto()
...     FRIDAY = auto()
...     SATURDAY = auto()
...     SUNDAY = auto()
...     WEEKEND = SATURDAY | SUNDAY
@end example

@menu
* 列挙型メンバーおよびそれらの属性へのプログラム的アクセス:: 
* 列挙型メンバーと値の重複:: 
* 番号付けの値が一意であることの確認:: 
* 値の自動設定を使う:: 
* イテレーション: イテレーション<2>. 
* 比較: 比較<3>. 
* 列挙型で許されるメンバーと属性:: 
* Enumのサブクラス化の制限:: 
* データクラスのサポート:: 
* Pickle 化:: 
* 関数 API: 関数 API<2>. 
* 派生列挙型:: 
* When to use __new__() vs. __init__(): When to use __new__ vs __init__. 
* EnumとFlagはどう違うのか？:: 
* Enum クックブック:: 
* EnumType のサブクラスを作る:: 

@end menu

@node 列挙型メンバーおよびそれらの属性へのプログラム的アクセス,列挙型メンバーと値の重複,,列挙型 HOWTO
@anchor{howto/enum enum-advanced-tutorial}@anchor{2a27}@anchor{howto/enum programmatic-access-to-enumeration-members-and-their-attributes}@anchor{56f3}
@subsection 列挙型メンバーおよびそれらの属性へのプログラム的アクセス


プログラム的にメンバーに番号でアクセスしたほうが便利な場合があります (すなわち、プログラムを書いている時点で正確な色がまだわからなく、@code{Color.RED} と書くのが無理な場合など)。 @code{Enum} ではそのようなアクセスも可能です:

@example
>>> Color(1)
<Color.RED: 1>
>>> Color(3)
<Color.BLUE: 3>
@end example

列挙型メンバーに `名前' でアクセスしたい場合はアイテムとしてアクセスできます:

@example
>>> Color['RED']
<Color.RED: 1>
>>> Color['GREEN']
<Color.GREEN: 2>
@end example

If you have an enum member and need its @code{name} or @code{value}:

@example
>>> member = Color.RED
>>> member.name
'RED'
>>> member.value
1
@end example

@node 列挙型メンバーと値の重複,番号付けの値が一意であることの確認,列挙型メンバーおよびそれらの属性へのプログラム的アクセス,列挙型 HOWTO
@anchor{howto/enum duplicating-enum-members-and-values}@anchor{56f4}
@subsection 列挙型メンバーと値の重複


同じ名前の列挙型メンバーを複数持つことはできません:

@example
>>> class Shape(Enum):
...     SQUARE = 2
...     SQUARE = 3
...
Traceback (most recent call last):
...
TypeError: 'SQUARE' already defined as 2
@end example

しかし、列挙型メンバー は、別の名前を持つことができます。  同じ値を持つ @code{A} と`@w{`}B`@w{`} が与えられた場合（そして @code{A} が先に定義されている場合）、 @code{B} はメンバー @code{A} に対するエイリアスとなります。  @code{A} の値での検索では、メンバー @code{A} が返されます。  @code{A} の名前での検索ではメンバー @code{A} を返します。@code{B} の名前での検索も、メンバー @code{A} を返します:

@example
>>> class Shape(Enum):
...     SQUARE = 2
...     DIAMOND = 1
...     CIRCLE = 3
...     ALIAS_FOR_SQUARE = 2
...
>>> Shape.SQUARE
<Shape.SQUARE: 2>
>>> Shape.ALIAS_FOR_SQUARE
<Shape.SQUARE: 2>
>>> Shape(2)
<Shape.SQUARE: 2>
@end example

@cartouche
@quotation 注釈 
すでに定義されている属性と同じ名前のメンバー (一方がメンバーでもう一方がメソッド、など) の作成、あるいはメンバーと同じ名前の属性の作成はできません。
@end quotation
@end cartouche

@node 番号付けの値が一意であることの確認,値の自動設定を使う,列挙型メンバーと値の重複,列挙型 HOWTO
@anchor{howto/enum ensuring-unique-enumeration-values}@anchor{56f5}
@subsection 番号付けの値が一意であることの確認


デフォルトでは、列挙型は同じ値のエイリアスとして複数の名前を許容します。この振る舞いを望まない場合は、 @ref{2a2c,,unique()} デコレータを使用できます:

@example
>>> from enum import Enum, unique
>>> @@unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
@end example

@node 値の自動設定を使う,イテレーション<2>,番号付けの値が一意であることの確認,列挙型 HOWTO
@anchor{howto/enum using-automatic-values}@anchor{56f6}
@subsection 値の自動設定を使う


正確な値が重要でない場合、 @ref{e9b,,auto} が使えます:

@example
>>> from enum import Enum, auto
>>> class Color(Enum):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> [member.value for member in Color]
[1, 2, 3]
@end example

The values are chosen by @ref{2a40,,_generate_next_value_()}, which can be
overridden:

@example
>>> class AutoName(Enum):
...     @@staticmethod
...     def _generate_next_value_(name, start, count, last_values):
...         return name
...
>>> class Ordinal(AutoName):
...     NORTH = auto()
...     SOUTH = auto()
...     EAST = auto()
...     WEST = auto()
...
>>> [member.value for member in Ordinal]
['NORTH', 'SOUTH', 'EAST', 'WEST']
@end example

@cartouche
@quotation 注釈 
The @ref{2a40,,_generate_next_value_()} method must be defined before any members.
@end quotation
@end cartouche

@node イテレーション<2>,比較<3>,値の自動設定を使う,列挙型 HOWTO
@anchor{howto/enum iteration}@anchor{56f7}
@subsection イテレーション


列挙型のメンバーのイテレートは別名をサポートしていません:

@example
>>> list(Shape)
[<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
>>> list(Weekday)
[<Weekday.MONDAY: 1>, <Weekday.TUESDAY: 2>, <Weekday.WEDNESDAY: 4>, <Weekday.THURSDAY: 8>, <Weekday.FRIDAY: 16>, <Weekday.SATURDAY: 32>, <Weekday.SUNDAY: 64>]
@end example

エイリアスである @code{Shape.ALIAS_FOR_SQUARE} と`@w{`}Weekday.WEEKEND`@w{`} が表示されていないことに注意してください。

特殊属性 @code{__members__} は読み出し専用で、順序を保持した、対応する名前と列挙型メンバーのマッピングです。これには別名も含め、列挙されたすべての名前が入っています。

@example
>>> for name, member in Shape.__members__.items():
...     name, member
...
('SQUARE', <Shape.SQUARE: 2>)
('DIAMOND', <Shape.DIAMOND: 1>)
('CIRCLE', <Shape.CIRCLE: 3>)
('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
@end example

属性 @code{__members__} は列挙型メンバーへの詳細なアクセスに使用できます。以下はすべての別名を探す例です:

@example
>>> [name for name, member in Shape.__members__.items() if member.name != name]
['ALIAS_FOR_SQUARE']
@end example

@cartouche
@quotation 注釈 
フラグのエイリアスには、 複数のフラグが設定された値（例えば @code{3}）や、 フラグが設定されていない値（例えば @code{0}）が含まれます。
@end quotation
@end cartouche

@node 比較<3>,列挙型で許されるメンバーと属性,イテレーション<2>,列挙型 HOWTO
@anchor{howto/enum comparisons}@anchor{56f8}
@subsection 比較


列挙型メンバーは同一性を比較できます:

@example
>>> Color.RED is Color.RED
True
>>> Color.RED is Color.BLUE
False
>>> Color.RED is not Color.BLUE
True
@end example

列挙型の値の順序の比較はサポートされて `いません'。Enum メンバーは整数ではありません (@ref{56f9,,IntEnum} を参照してください):

@example
>>> Color.RED < Color.BLUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Color' and 'Color'
@end example

ただし等価の比較は定義されています:

@example
>>> Color.BLUE == Color.RED
False
>>> Color.BLUE != Color.RED
True
>>> Color.BLUE == Color.BLUE
True
@end example

非列挙型の値との比較は常に不等となります (繰り返しになりますが、@ref{edb,,IntEnum} はこれと異なる挙動になるよう設計されています):

@example
>>> Color.BLUE == 2
False
@end example

@cartouche
@quotation 警告 
モジュールは再読み込みすることが可能です。再読み込みされたモジュールに列挙型が含まれている場合、それらは再作成され、新しいメンバーは元のメンバーと同一でない/等しくない可能性があります。
@end quotation
@end cartouche

@node 列挙型で許されるメンバーと属性,Enumのサブクラス化の制限,比較<3>,列挙型 HOWTO
@anchor{howto/enum allowed-members-and-attributes-of-enumerations}@anchor{56fa}
@subsection 列挙型で許されるメンバーと属性


これまでのほとんどの例では、列挙型の値に整数を使用しています。  整数を使うのは短くて便利（そして、 @ref{56fb,,関数 API} ではデフォルトで設定される）ですが、これは強制されているわけではありません。大半の使用例では、列挙値の実際の値が何であるかは意識しません。しかし、値が重要な場合、列挙型は任意の値を持つことができます。

列挙型は Python のクラスであり、通常どおりメソッドや特殊メソッドを持つことができます:

@example
>>> class Mood(Enum):
...     FUNKY = 1
...     HAPPY = 3
...
...     def describe(self):
...         # self is the member here
...         return self.name, self.value
...
...     def __str__(self):
...         return 'my custom str! @{0@}'.format(self.value)
...
...     @@classmethod
...     def favorite_mood(cls):
...         # cls here is the enumeration
...         return cls.HAPPY
...
@end example

上記の結果が以下のようになります:

@example
>>> Mood.favorite_mood()
<Mood.HAPPY: 3>
>>> Mood.HAPPY.describe()
('HAPPY', 3)
>>> str(Mood.FUNKY)
'my custom str! 1'
@end example

The rules for what is allowed are as follows: names that start and end with
a single underscore are reserved by enum and cannot be used; all other
attributes defined within an enumeration will become members of this
enumeration, with the exception of special methods (@ref{830,,__str__()},
@ref{23dd,,__add__()}, etc.), descriptors (methods are also descriptors), and
variable names listed in @ref{2a3e,,_ignore_}.

Note:  if your enumeration defines @ref{7a0,,__new__()} and/or @ref{8bf,,__init__()},
any value(s) given to the enum member will be passed into those methods.
See @ref{56fc,,Planet} for an example.

@cartouche
@quotation 注釈 
The @ref{7a0,,__new__()} method, if defined, is used during creation of the Enum
members; it is then replaced by Enum's @ref{7a0,,__new__()} which is used after
class creation for lookup of existing members.  See @ref{56fd,,When to use __new__() vs. __init__()} for
more details.
@end quotation
@end cartouche

@node Enumのサブクラス化の制限,データクラスのサポート,列挙型で許されるメンバーと属性,列挙型 HOWTO
@anchor{howto/enum restricted-enum-subclassing}@anchor{56fe}
@subsection Enumのサブクラス化の制限


新しい @ref{842,,Enum} クラスは、ベースの enum クラスを1つ、具象データ型を1つ、複数の @ref{c7e,,object} ベースのミックスインクラスが許容されます。これらのベースクラスの順序は次の通りです:

@example
class EnumName([mix-in, ...,] [data-type,] base-enum):
    pass
@end example

列挙型のサブクラスの作成はその列挙型にメンバーが一つも定義されていない場合のみ行なえます。従って以下は許されません:

@example
>>> class MoreColor(Color):
...     PINK = 17
...
Traceback (most recent call last):
...
TypeError: <enum 'MoreColor'> cannot extend <enum 'Color'>
@end example

以下のような場合は許されます:

@example
>>> class Foo(Enum):
...     def some_behavior(self):
...         pass
...
>>> class Bar(Foo):
...     HAPPY = 1
...     SAD = 2
...
@end example

メンバーが定義された列挙型のサブクラス化を許可すると、いくつかのデータ型およびインスタンスの重要な不変条件の違反を引き起こします。とはいえ、それが許可されると、列挙型のグループ間での共通の挙動を共有するという利点もあります。 (@ref{56ff,,OrderedEnum} の例を参照してください。)

@node データクラスのサポート,Pickle 化,Enumのサブクラス化の制限,列挙型 HOWTO
@anchor{howto/enum dataclass-support}@anchor{5700}@anchor{howto/enum enum-dataclass-support}@anchor{1af9}
@subsection データクラスのサポート


@ref{4e1,,dataclass} を継承する場合、 @ref{1afa,,__repr__()} は継承するクラス名を省略します。  例えば:

@example
>>> from dataclasses import dataclass, field
>>> @@dataclass
... class CreatureDataMixin:
...     size: str
...     legs: int
...     tail: bool = field(repr=False, default=True)
...
>>> class Creature(CreatureDataMixin, Enum):
...     BEETLE = 'small', 6
...     DOG = 'medium', 4
...
>>> Creature.DOG
<Creature.DOG: size='medium', legs=4>
@end example

標準の @ref{1c1,,repr()} を使うには、@ref{4e1,,dataclass()} の引数 @code{repr=False} を使用してください。


バージョン 3.12 で変更: dataclass のフィールドだけが値の領域に表示され、dataclassの名前は表示されなくなりました


@cartouche
@quotation 注釈 
@ref{842,,Enum} やそのサブクラスに @ref{4e1,,dataclass()} デコレータを加えることはサポートされていません。そうしてもエラーは送出されませんが、実行時にそれぞれのメンバが互いに等しいなど、非常に奇妙な結果が起こります:

@example
>>> @@dataclass               # don't do this: it does not make any sense
... class Color(Enum):
...    RED = 1
...    BLUE = 2
...
>>> Color.RED is Color.BLUE
False
>>> Color.RED == Color.BLUE  # problem is here: they should not be equal
True
@end example
@end quotation
@end cartouche

@node Pickle 化,関数 API<2>,データクラスのサポート,列挙型 HOWTO
@anchor{howto/enum pickling}@anchor{5701}
@subsection Pickle 化


列挙型は pickle 化と unpickle 化が行えます:

@example
>>> from test.test_enum import Fruit
>>> from pickle import dumps, loads
>>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
True
@end example

通常の pickle 化の制限事項が適用されます: pickle 可能な列挙型はモジュールのトップレベルで定義されていなくてはならず、unpickle 化はモジュールからインポート可能でなければなりません。

@cartouche
@quotation 注釈 
pickle プロトコルバージョン 4 では他のクラスで入れ子になった列挙型の pickle 化も容易です。
@end quotation
@end cartouche

It is possible to modify how enum members are pickled/unpickled by defining
@ref{196b,,__reduce_ex__()} in the enumeration class.  The default method is by-value,
but enums with complicated values may want to use by-name:

@example
>>> import enum
>>> class MyEnum(enum.Enum):
...     __reduce_ex__ = enum.pickle_by_enum_name
@end example

@cartouche
@quotation 注釈 
フラグに名前による pickle 化を使うことは、名前の無いエイリアスが unpickle 化されないため推奨されません。
@end quotation
@end cartouche

@node 関数 API<2>,派生列挙型,Pickle 化,列挙型 HOWTO
@anchor{howto/enum functional-api}@anchor{56fb}
@subsection 関数 API


@ref{842,,Enum} クラスは呼び出し可能で、以下の関数 API を提供しています:

@example
>>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
>>> Animal
<enum 'Animal'>
>>> Animal.ANT
<Animal.ANT: 1>
>>> list(Animal)
[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
@end example

この API の動作は @ref{4e0,,namedtuple} と似ています。@ref{842,,Enum} 呼び出しの第 1 引数は列挙型の名前です。

The second argument is the `source' of enumeration member names.  It can be a
whitespace-separated string of names, a sequence of names, a sequence of
2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to
values.  The last two options enable assigning arbitrary values to
enumerations; the others auto-assign increasing integers starting with 1 (use
the @code{start} parameter to specify a different starting value).  A
new class derived from @ref{842,,Enum} is returned.  In other words, the above
assignment to @code{Animal} is equivalent to:

@example
>>> class Animal(Enum):
...     ANT = 1
...     BEE = 2
...     CAT = 3
...     DOG = 4
...
@end example

@code{0} ではなく`@w{`}1`@w{`} をデフォルトの開始番号とする理由は、@code{0} が真偽値としては @code{False} であり、デフォルトの列挙メンバーはすべて @code{True} 評価されるようにするためである。

機能 API による Enum の pickle 化は、その列挙型がどのモジュールで作成されたかを見つけ出すためにフレームスタックの実装の詳細が使われるので、トリッキーになることがあります (例えば別のモジュールのユーティリティ関数を使うと失敗しますし、IronPython や Jython ではうまくいきません)。解決策は、以下のようにモジュール名を明示的に指定することです:

@example
>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
@end example

@cartouche
@quotation 警告 
@code{module} が与えられない場合、Enum はそれがなにか決定できないため、新しい Enum メンバーは unpickle 化できなくなります; エラーをソースの近いところで発生させるため、pickle 化は無効になります。
@end quotation
@end cartouche

The new pickle protocol 4 also, in some circumstances, relies on
@ref{2373,,__qualname__} being set to the location where pickle will be able
to find the class.  For example, if the class was made available in class
SomeData in the global scope:

@example
>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
@end example

完全な構文は以下のようになります:

@example
Enum(
    value='NewEnumName',
    names=<...>,
    *,
    module='...',
    qualname='...',
    type=<mixed-in class>,
    start=1,
    )
@end example


@itemize *

@item 
`value': What the new enum class will record as its name.

@item 
`names': enumのメンバー。 空白またはカンマで区切られた文字列 (値は特に指定がない限り1から始まります):

@example
'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
@end example

または名前のイテレータで指定もできます:

@example
['RED', 'GREEN', 'BLUE']
@end example

または (名前, 値) のペアのイテレータでも指定できます:

@example
[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
@end example

またはマッピングでも指定できます:

@example
@{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42@}
@end example

@item 
`module': 新しい enum クラスが属するモジュールの名前です。

@item 
`qualname': 新しい enum クラスが属するモジュールの場所です。

@item 
`type': 新しい列挙型クラスにミックスインする型。

@item 
`start'：名前だけ渡された場合にカウントを開始する番号。
@end itemize


バージョン 3.5 で変更: `start' 引数が追加されました。


@node 派生列挙型,When to use __new__ vs __init__,関数 API<2>,列挙型 HOWTO
@anchor{howto/enum derived-enumerations}@anchor{5702}
@subsection 派生列挙型


@menu
* IntEnum:: 
* StrEnum:: 
* IntFlag:: 
* Flag:: 
* その他: その他<6>. 

@end menu

@node IntEnum,StrEnum,,派生列挙型
@anchor{howto/enum intenum}@anchor{56f9}
@subsubsection IntEnum


提供されている 1 つ目の @ref{842,,Enum} の派生型であり、 @ref{19b,,int} のサブクラスでもあります。
@ref{edb,,IntEnum} のメンバーは整数と比較できます;
さらに言うと、異なる整数列挙型どうしでも比較できます:

@example
>>> from enum import IntEnum
>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Request(IntEnum):
...     POST = 1
...     GET = 2
...
>>> Shape == 1
False
>>> Shape.CIRCLE == 1
True
>>> Shape.CIRCLE == Request.POST
True
@end example

ただし、これらも標準の @ref{842,,Enum} 列挙型とは比較できません:

@example
>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...
>>> Shape.CIRCLE == Color.RED
False
@end example

@ref{edb,,IntEnum} の値は他の用途では整数のように振る舞います:

@example
>>> int(Shape.CIRCLE)
1
>>> ['a', 'b', 'c'][Shape.CIRCLE]
'b'
>>> [i for i in range(Shape.SQUARE)]
[0, 1]
@end example

@node StrEnum,IntFlag,IntEnum,派生列挙型
@anchor{howto/enum strenum}@anchor{5703}
@subsubsection StrEnum


提供されている2つ目の @ref{842,,Enum} の派生型もまた、 @ref{169,,str} のサブクラスでもあります。@ref{82d,,StrEnum} のメンバーは、文字列と比較できます; さらに言うと、異なる文字列列挙型どうしでも比較できます。


Added in version 3.11.


@node IntFlag,Flag,StrEnum,派生列挙型
@anchor{howto/enum intflag}@anchor{5704}
@subsubsection IntFlag


次の @ref{842,,Enum} の派生型 @ref{e9a,,IntFlag} も、@ref{19b,,int} を基底クラスとしています。
違いは、 @ref{e9a,,IntFlag} のメンバーをビット演算子 (&amp;, |, ^, ~) を使って組み合わせられ、その結果も @ref{e9a,,IntFlag} メンバーになることです。 @ref{edb,,IntEnum} と同様、@ref{e9a,,IntFlag} のメンバーも整数であり、@ref{19b,,int} が使用されるところであればどこでも使えます。

@cartouche
@quotation 注釈 
@ref{e9a,,IntFlag} メンバーに対してビット演算以外のどんな演算をしても、その結果は @ref{e9a,,IntFlag} メンバーではなくなります。

ビット単位演算の結果が @ref{e9a,,IntFlag} として不正な値な値の場合、値は @ref{e9a,,IntFlag} メンバーではなくなります。  詳しくは @ref{836,,FlagBoundary} を参照してください。
@end quotation
@end cartouche


Added in version 3.6.



バージョン 3.11 で変更.


@ref{e9a,,IntFlag} クラスの例:

@example
>>> from enum import IntFlag
>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...
>>> Perm.R | Perm.W
<Perm.R|W: 6>
>>> Perm.R + Perm.W
6
>>> RW = Perm.R | Perm.W
>>> Perm.R in RW
True
@end example

組み合わせにも名前を付けられます:

@example
>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...     RWX = 7
...
>>> Perm.RWX
<Perm.RWX: 7>
>>> ~Perm.RWX
<Perm: 0>
>>> Perm(7)
<Perm.RWX: 7>
@end example

@cartouche
@quotation 注釈 
組み合わせに名前をつけたものはエイリアスとみなされます。エイリアスはイテレーション中には表示されませんが、値による検索では返却されます。
@end quotation
@end cartouche


バージョン 3.11 で変更.


@ref{e9a,,IntFlag} と @ref{842,,Enum} のもう 1 つの重要な違いは、フラグが設定されていない (値が0である) 場合、その真偽値としての評価は @ref{d2b,,False} になることです:

@example
>>> Perm.R & Perm.X
<Perm: 0>
>>> bool(Perm.R & Perm.X)
False
@end example

@ref{e9a,,IntFlag} メンバーも @ref{19b,,int} のサブクラスであるため、それらと組み合わせることができます（ただし、 @ref{e9a,,IntFlag} 型ではなくなる可能性があります）:

@example
>>> Perm.X | 4
<Perm.R|X: 5>

>>> Perm.X + 8
9
@end example

@cartouche
@quotation 注釈 
否定の演算子 @code{~} は、常に正の値を持つ @ref{e9a,,IntFlag} メンバー を返す:

@example
>>> (~Perm.X).value == (Perm.R|Perm.W).value == 6
True
@end example
@end quotation
@end cartouche

@ref{e9a,,IntFlag} メンバーは反復処理することもできます:

@example
>>> list(RW)
[<Perm.R: 4>, <Perm.W: 2>]
@end example


Added in version 3.11.


@node Flag,その他<6>,IntFlag,派生列挙型
@anchor{howto/enum flag}@anchor{5705}
@subsubsection Flag


最後の派生型は @ref{835,,Flag} です。
@ref{e9a,,IntFlag} と同様に、 @ref{835,,Flag} メンバーもビット演算子 (&, |, ^, ~) を使って組み合わせられます。
しかし @ref{e9a,,IntFlag} とは違い、他のどの @ref{835,,Flag} 列挙型とも @ref{19b,,int} とも組み合わせたり、比較したりできません。
値を直接指定することも可能ですが、値として @ref{e9b,,auto} を使い、 @ref{835,,Flag} に適切な値を選ばせることが推奨されています。


Added in version 3.6.


@ref{e9a,,IntFlag} と同様に、 @ref{835,,Flag} メンバーの組み合わせがどのフラグも設定されていない状態になった場合、その真偽値としての評価は @ref{d2b,,False} となります:

@example
>>> from enum import Flag, auto
>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.RED & Color.GREEN
<Color: 0>
>>> bool(Color.RED & Color.GREEN)
False
@end example

個別のフラグは 2 のべき乗 (1, 2, 4, 8, ...) の値を持つべきですが、フラグの組み合わせはそうはなりません:

@example
>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...     WHITE = RED | BLUE | GREEN
...
>>> Color.WHITE
<Color.WHITE: 7>
@end example

"フラグが設定されていない" 状態に名前を付けても、その真偽値は変わりません:

@example
>>> class Color(Flag):
...     BLACK = 0
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.BLACK
<Color.BLACK: 0>
>>> bool(Color.BLACK)
False
@end example

@ref{835,,Flag} メンバーは反復処理することもできます:

@example
>>> purple = Color.RED | Color.BLUE
>>> list(purple)
[<Color.RED: 1>, <Color.BLUE: 2>]
@end example


Added in version 3.11.


@cartouche
@quotation 注釈 
ほとんどの新しいコードでは、 @ref{842,,Enum} と @ref{835,,Flag} が強く推奨されます。
というのは、 @ref{edb,,IntEnum} と @ref{e9a,,IntFlag} は (整数と比較でき、従って推移的に他の無関係な列挙型と比較できてしまうことにより) 列挙型の意味論的な約束に反するからです。
@ref{edb,,IntEnum} と @ref{e9a,,IntFlag} は、 @ref{842,,Enum} や @ref{835,,Flag} では上手くいかない場合のみに使うべきです;
例えば、整数定数を列挙型で置き換えるときや、他のシステムとの相互運用性を持たせたいときです。
@end quotation
@end cartouche

@node その他<6>,,Flag,派生列挙型
@anchor{howto/enum others}@anchor{5706}
@subsubsection その他


@ref{edb,,IntEnum} は @ref{5a,,enum} モジュールの一部ですが、単独での実装もとても簡単に行なえます:

@example
class IntEnum(int, ReprEnum):   # or Enum instead of ReprEnum
    pass
@end example

This demonstrates how similar derived enumerations can be defined; for example
a @code{FloatEnum} that mixes in @ref{196,,float} instead of @ref{19b,,int}.

いくつかのルール:


@enumerate 

@item 
@ref{842,,Enum} のサブクラスを作成するとき、複合させるデータ型は、基底クラスの並びで @ref{842,,Enum} クラス自身より先に記述しなければなりません (上記 @ref{edb,,IntEnum} の例を参照)。

@item 
複合させる型はサブクラス化可能でなければいけません。例えば、 @ref{3c3,,bool} と @ref{b3d,,range} はサブクラス化できないため、複合させるとEnum作成時にエラーが発生します。

@item 
@ref{842,,Enum} のメンバーはどんなデータ型でも構いませんが、追加のデータ型 (例えば、上の例の @ref{19b,,int}) と複合させてしまうと、すべてのメンバーの値はそのデータ型でなければならなくなります。この制限は、メソッドの追加するだけの、他のデータ型を指定しない複合には適用されません。

@item 
When another data type is mixed in, the @ref{2a39,,value} attribute is `not the
same' as the enum member itself, although it is equivalent and will compare
equal.

@item 
A @code{data type} is a mixin that defines @ref{7a0,,__new__()}, or a
@ref{4e1,,dataclass}

@item 
%-style formatting:  @code{%s} and @code{%r} call the @ref{842,,Enum} class's
@ref{830,,__str__()} and @ref{82f,,__repr__()} respectively; other codes (such as
@code{%i} or @code{%h} for IntEnum) treat the enum member as its mixed-in type.

@item 
@ref{19a,,Formatted string literals}, @ref{833,,str.format()},
and @ref{199,,format()} will use the enum's @ref{830,,__str__()} method.
@end enumerate

@cartouche
@quotation 注釈 
Because @ref{edb,,IntEnum}, @ref{e9a,,IntFlag}, and @ref{82d,,StrEnum} are
designed to be drop-in replacements for existing constants, their
@ref{830,,__str__()} method has been reset to their data types'
@ref{830,,__str__()} method.
@end quotation
@end cartouche

@node When to use __new__ vs __init__,EnumとFlagはどう違うのか？,派生列挙型,列挙型 HOWTO
@anchor{howto/enum new-vs-init}@anchor{56fd}@anchor{howto/enum when-to-use-new-vs-init}@anchor{5707}
@subsection When to use @code{__new__()} vs. @code{__init__()}


@ref{7a0,,__new__()} must be used whenever you want to customize the actual value of
the @ref{842,,Enum} member.  Any other modifications may go in either
@ref{7a0,,__new__()} or @ref{8bf,,__init__()}, with @ref{8bf,,__init__()} being preferred.

例えば、複数の値をコンストラクタに渡すが、その中の1つだけを値として使いたい場合は次のようにします:

@example
>>> class Coordinate(bytes, Enum):
...     """
...     Coordinate with binary codes that can be indexed by the int code.
...     """
...     def __new__(cls, value, label, unit):
...         obj = bytes.__new__(cls, [value])
...         obj._value_ = value
...         obj.label = label
...         obj.unit = unit
...         return obj
...     PX = (0, 'P.X', 'km')
...     PY = (1, 'P.Y', 'km')
...     VX = (2, 'V.X', 'km/s')
...     VY = (3, 'V.Y', 'km/s')
...

>>> print(Coordinate['PY'])
Coordinate.PY

>>> print(Coordinate(3))
Coordinate.VY
@end example

@cartouche
@quotation 警告 
`Do not' call @code{super().__new__()}, as the lookup-only @code{__new__} is the one
that is found; instead, use the data type directly.
@end quotation
@end cartouche

@menu
* 細かい点:: 

@end menu

@node 細かい点,,,When to use __new__ vs __init__
@anchor{howto/enum finer-points}@anchor{5708}
@subsubsection 細かい点


@menu
* __dunder__ 名のサポート: __dunder__ 名のサポート<2>. 
* _sunder_ 名のサポート: _sunder_ 名のサポート<2>. 
* _Private__names:: 
* Enum メンバー型:: 
* Creating members that are mixed with other data types:: 
* Enum クラスとメンバーの真偽値:: 
* メソッド付きの Enum クラス:: 
* Flag のメンバーの組み合わせ:: 
* Flag and IntFlag minutia:: 

@end menu

@node __dunder__ 名のサポート<2>,_sunder_ 名のサポート<2>,,細かい点
@anchor{howto/enum supported-dunder-names}@anchor{5709}
@subsubsection @code{__dunder__} 名のサポート


@ref{2a36,,__members__} is a read-only ordered mapping of @code{member_name}:@code{member}
items.  It is only available on the class.

@ref{7a0,,__new__()}, if specified, must create and return the enum members; it is
also a very good idea to set the member's @ref{2a3c,,_value_} appropriately.  Once
all the members are created it is no longer used.

@node _sunder_ 名のサポート<2>,_Private__names,__dunder__ 名のサポート<2>,細かい点
@anchor{howto/enum supported-sunder-names}@anchor{570a}
@subsubsection @code{_sunder_} 名のサポート



@itemize -

@item 
@ref{2a3b,,_name_} -- メンバー名

@item 
@ref{2a3c,,_value_} -- メンバーの値; @code{__new__} で設定できます

@item 
@ref{2a43,,_missing_()} -- 値が見付からなかったときに使われる検索関数; オーバーライドされていることがあります

@item 
@ref{2a3e,,_ignore_} -- 名前のリストで、 @ref{24d,,list} もしくは @ref{169,,str} です。この名前の要素はメンバーへの変換が行われず、最終的なクラスから削除されます。

@item 
@ref{2a40,,_generate_next_value_()} -- 列挙型のメンバーの適切な値を取得するのに使われます。オーバーライドされます。

@item 
@ref{2a44,,_add_alias_()} -- adds a new name as an alias to an existing
member.

@item 
@ref{2a45,,_add_value_alias_()} -- adds a new value as an alias to an
existing member.  See @ref{570b,,MultiValueEnum} for an example.

@cartouche
@quotation 注釈 
標準の @ref{842,,Enum} クラスの場合、次の値として選択されるのは、定義された最大の値に1を加えたものです。

@ref{835,,Flag} クラスでは、次に選ばれる値は、次の最大の2のべき乗となります。
@end quotation
@end cartouche


バージョン 3.13 で変更: 以前のバージョンでは最大の値ではなく最後に定義された値を使っていました。

@end itemize


Added in version 3.6: @code{_missing_}, @code{_order_}, @code{_generate_next_value_}



Added in version 3.7: @code{_ignore_}



Added in version 3.13: @code{_add_alias_}, @code{_add_value_alias_}


To help keep Python 2 / Python 3 code in sync an @ref{2a3d,,_order_} attribute can
be provided.  It will be checked against the actual order of the enumeration
and raise an error if the two do not match:

@example
>>> class Color(Enum):
...     _order_ = 'RED GREEN BLUE'
...     RED = 1
...     BLUE = 3
...     GREEN = 2
...
Traceback (most recent call last):
...
TypeError: member order does not match _order_:
  ['RED', 'BLUE', 'GREEN']
  ['RED', 'GREEN', 'BLUE']
@end example

@cartouche
@quotation 注釈 
In Python 2 code the @ref{2a3d,,_order_} attribute is necessary as definition
order is lost before it can be recorded.
@end quotation
@end cartouche

@node _Private__names,Enum メンバー型,_sunder_ 名のサポート<2>,細かい点
@anchor{howto/enum private-names}@anchor{570c}
@subsubsection _Private__names


@ref{20a3,,Private names} は列挙型メンバーには変換されず、通常の属性となります。


バージョン 3.11 で変更.


@node Enum メンバー型,Creating members that are mixed with other data types,_Private__names,細かい点
@anchor{howto/enum enum-member-type}@anchor{570d}
@subsubsection @code{Enum} メンバー型


列挙型メンバーはその列挙型クラスのインスタンスであり、通常は @code{EnumClass.member}  としてアクセスされます。 振る舞い メンバー しかし、メンバー の名前と、属性/methodsが混在しているクラスとの名前の衝突を避けるために、大文字の名前を使うことを強く推奨します。


バージョン 3.5 で変更.


@node Creating members that are mixed with other data types,Enum クラスとメンバーの真偽値,Enum メンバー型,細かい点
@anchor{howto/enum creating-members-that-are-mixed-with-other-data-types}@anchor{570e}
@subsubsection Creating members that are mixed with other data types


When subclassing other data types, such as @ref{19b,,int} or @ref{169,,str}, with
an @ref{842,,Enum}, all values after the @code{=} are passed to that data type's
constructor.  For example:

@example
>>> class MyEnum(IntEnum):      # help(int) -> int(x, base=10) -> integer
...     example = '11', 16      # so x='11' and base=16
...
>>> MyEnum.example.value        # and hex(11) is...
17
@end example

@node Enum クラスとメンバーの真偽値,メソッド付きの Enum クラス,Creating members that are mixed with other data types,細かい点
@anchor{howto/enum boolean-value-of-enum-classes-and-members}@anchor{570f}
@subsubsection @code{Enum} クラスとメンバーの真偽値


(@ref{19b,,int}, @ref{169,,str} などのような) 非 @ref{842,,Enum} 型と複合させた enum クラスは、その複合された型の規則に従って評価されます;
そうでない場合は、全てのメンバーは @ref{e07,,True} と評価されます。
メンバーの値に依存する独自の enum の真偽値評価を行うには、クラスに次のコードを追加してください:

@example
def __bool__(self):
    return bool(self.value)
@end example

プレーンな @ref{842,,Enum} クラスは @ref{e07,,True} として評価されます。

@node メソッド付きの Enum クラス,Flag のメンバーの組み合わせ,Enum クラスとメンバーの真偽値,細かい点
@anchor{howto/enum enum-classes-with-methods}@anchor{5710}
@subsubsection メソッド付きの @code{Enum} クラス


enum サブクラスに追加のメソッドを与えた場合、後述の @ref{56fc,,Planet} クラスのように、そのメソッドはメンバーの @ref{844,,dir()} に表示されますが、クラスの @ref{844,,dir()} には表示されません:

@example
>>> dir(Planet)
['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
>>> dir(Planet.EARTH)
['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', 'surface_gravity', 'value']
@end example

@node Flag のメンバーの組み合わせ,Flag and IntFlag minutia,メソッド付きの Enum クラス,細かい点
@anchor{howto/enum combining-members-of-flag}@anchor{5711}
@subsubsection @code{Flag} のメンバーの組み合わせ


Iterating over a combination of @ref{835,,Flag} members will only return the members that
are comprised of a single bit:

@example
>>> class Color(Flag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...     MAGENTA = RED | BLUE
...     YELLOW = RED | GREEN
...     CYAN = GREEN | BLUE
...
>>> Color(3)  # named combination
<Color.YELLOW: 3>
>>> Color(7)      # not named combination
<Color.RED|GREEN|BLUE: 7>
@end example

@node Flag and IntFlag minutia,,Flag のメンバーの組み合わせ,細かい点
@anchor{howto/enum flag-and-intflag-minutia}@anchor{5712}
@subsubsection @code{Flag} and @code{IntFlag} minutia


例として以下のスニペットを使用します:

@example
>>> class Color(IntFlag):
...     BLACK = 0
...     RED = 1
...     GREEN = 2
...     BLUE = 4
...     PURPLE = RED | BLUE
...     WHITE = RED | GREEN | BLUE
...
@end example

the following are true:


@itemize -

@item 
単一ビットのフラグは正規形です

@item 
複数ビットや0ビットのフラグはエイリアスです

@item 
反復処理では正規形のフラグのみ返却されます:

@example
>>> list(Color.WHITE)
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>]
@end example

@item 
negating a flag or flag set returns a new flag/flag set with the
corresponding positive integer value:

@example
>>> Color.BLUE
<Color.BLUE: 4>

>>> ~Color.BLUE
<Color.RED|GREEN: 3>
@end example

@item 
名前のないフラグについては、そのメンバーの名前から名前が生成されます:

@example
>>> (Color.RED | Color.GREEN).name
'RED|GREEN'

>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...
>>> (Perm.R & Perm.W).name is None  # effectively Perm(0)
True
@end example

@item 
multi-bit flags, aka aliases, can be returned from operations:

@example
>>> Color.RED | Color.BLUE
<Color.PURPLE: 5>

>>> Color(7)  # or Color(-1)
<Color.WHITE: 7>

>>> Color(0)
<Color.BLACK: 0>
@end example

@item 
メンバーシップ/包含 のチェックでは、値が0のフラグは常に含まれるものとして扱われます:

@example
>>> Color.BLACK in Color.WHITE
True
@end example

それ以外では、一方のフラグの全ビットが他方のフラグに含まれる場合のみ、Trueが返されます:

@example
>>> Color.PURPLE in Color.WHITE
True

>>> Color.GREEN in Color.PURPLE
False
@end example
@end itemize

There is a new boundary mechanism that controls how out-of-range / invalid
bits are handled: @code{STRICT}, @code{CONFORM}, @code{EJECT}, and @code{KEEP}:


@itemize *

@item 
STRICT --> 無効な値が指定された場合に例外を発生させる

@item 
CONFORM --> 無効なビットを破棄する

@item 
EJECT --> フラグのステータスを失い、指定された値を持つ通常の int となります。

@item 
KEEP --> keep the extra bits


@itemize -

@item 
keeps Flag status and extra bits

@item 
extra bits do not show up in iteration

@item 
extra bits do show up in repr() and str()
@end itemize
@end itemize

The default for Flag is @code{STRICT}, the default for @code{IntFlag} is @code{EJECT},
and the default for @code{_convert_} is @code{KEEP} (see @code{ssl.Options} for an
example of when @code{KEEP} is needed).

@node EnumとFlagはどう違うのか？,Enum クックブック,When to use __new__ vs __init__,列挙型 HOWTO
@anchor{howto/enum enum-class-differences}@anchor{2a29}@anchor{howto/enum how-are-enums-and-flags-different}@anchor{5713}
@subsection EnumとFlagはどう違うのか？


Enum は @ref{842,,Enum} 派生クラスやそれらのインスタンス (メンバー) 双方の多くの側面に影響を及ぼすカスタムメタクラスを持っています。

@menu
* Enum クラス:: 
* Flag クラス:: 
* Enum メンバー (インスタンス): Enum メンバー インスタンス. 
* Flag メンバー:: 

@end menu

@node Enum クラス,Flag クラス,,EnumとFlagはどう違うのか？
@anchor{howto/enum enum-classes}@anchor{5714}
@subsubsection Enum クラス


The @ref{4f7,,EnumType} metaclass is responsible for providing the
@ref{15d3,,__contains__()}, @ref{17e2,,__dir__()}, @ref{e69,,__iter__()} and other methods that
allow one to do things with an @ref{842,,Enum} class that fail on a typical
class, such as @code{list(Color)} or @code{some_enum_var in Color}.  @ref{4f7,,EnumType} is
responsible for ensuring that various other methods on the final @ref{842,,Enum}
class are correct (such as @ref{7a0,,__new__()}, @ref{fd4,,__getnewargs__()},
@ref{830,,__str__()} and @ref{82f,,__repr__()}).

@node Flag クラス,Enum メンバー インスタンス,Enum クラス,EnumとFlagはどう違うのか？
@anchor{howto/enum flag-classes}@anchor{5715}
@subsubsection Flag クラス


Flags have an expanded view of aliasing: to be canonical, the value of a flag
needs to be a power-of-two value, and not a duplicate name.  So, in addition to the
@ref{842,,Enum} definition of alias, a flag with no value (a.k.a. @code{0}) or with more than one
power-of-two value (e.g. @code{3}) is considered an alias.

@node Enum メンバー インスタンス,Flag メンバー,Flag クラス,EnumとFlagはどう違うのか？
@anchor{howto/enum enum-members-aka-instances}@anchor{5716}
@subsubsection Enum メンバー (インスタンス)


The most interesting thing about enum members is that they are singletons.
@ref{4f7,,EnumType} creates them all while it is creating the enum class itself,
and then puts a custom @ref{7a0,,__new__()} in place to ensure that no new ones are
ever instantiated by returning only the existing member instances.

@node Flag メンバー,,Enum メンバー インスタンス,EnumとFlagはどう違うのか？
@anchor{howto/enum flag-members}@anchor{5717}
@subsubsection Flag メンバー


フラグのメンバーは、@ref{835,,Flag} クラスと同様に反復処理することができ、正規のメンバーのみが返されます。  例えば:

@example
>>> list(Color)
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>]
@end example

（@code{BLACK} 、 @code{PURPLE} 、 @code{WHITE} は表示されないことに注意。）

フラグのメンバーを反転させると、負の値ではなく、対応する正の値が返されます:

@example
>>> ~Color.RED
<Color.GREEN|BLUE: 6>
@end example

フラグのメンバーは、それが含む2のべき乗の値の数に対応するlengthを持ちます。 例えば:

@example
>>> len(Color.PURPLE)
2
@end example

@node Enum クックブック,EnumType のサブクラスを作る,EnumとFlagはどう違うのか？,列挙型 HOWTO
@anchor{howto/enum enum-cookbook}@anchor{2a28}@anchor{howto/enum id2}@anchor{5718}
@subsection Enum クックブック


@ref{842,,Enum}, @ref{edb,,IntEnum}, @ref{82d,,StrEnum}, @ref{835,,Flag}, @ref{e9a,,IntFlag} は用途の大部分をカバーすると予想されますが、そのすべてをカバーできているわけではありません。ここでは、そのまま、あるいは独自の列挙型を作る例として使える、様々なタイプの列挙型を紹介します。

@menu
* 値の省略:: 
* OrderedEnum:: 
* DuplicateFreeEnum:: 
* MultiValueEnum:: 
* Planet:: 
* TimePeriod:: 

@end menu

@node 値の省略,OrderedEnum,,Enum クックブック
@anchor{howto/enum omitting-values}@anchor{5719}
@subsubsection 値の省略


多くの用途では、列挙型の実際の値が何かは気にされません。
このタイプの単純な列挙型を定義する方法はいくつかあります:


@itemize -

@item 
値に @ref{e9b,,auto} インスタンスを使用する

@item 
値として @ref{c7e,,object} インスタンスを使用する

@item 
値として解説文字列を使用する

@item 
use a tuple as the value and a custom @ref{7a0,,__new__()} to replace the
tuple with an @ref{19b,,int} value
@end itemize

これらのどの方法を使ってもユーザーに対して、値は重要ではなく、他のメンバーの番号の振り直しをする必要無しに、メンバーの追加、削除、並べ替えが行えるということを示せます。

@menu
* auto を使う:: 
* object を使う:: 
* 解説文字列を使う:: 
* Using a custom __new__(): Using a custom __new__. 

@end menu

@node auto を使う,object を使う,,値の省略
@anchor{howto/enum using-auto}@anchor{571a}
@subsubsection @code{auto} を使う


@ref{e9b,,auto} を使うと次のようになります:

@example
>>> class Color(Enum):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.GREEN
<Color.GREEN: 3>
@end example

@node object を使う,解説文字列を使う,auto を使う,値の省略
@anchor{howto/enum using-object}@anchor{571b}
@subsubsection @code{object} を使う


@ref{c7e,,object} を使うと次のようになります:

@example
>>> class Color(Enum):
...     RED = object()
...     GREEN = object()
...     BLUE = object()
...
>>> Color.GREEN
<Color.GREEN: <object object at 0x...>>
@end example

This is also a good example of why you might want to write your own
@ref{82f,,__repr__()}:

@example
>>> class Color(Enum):
...     RED = object()
...     GREEN = object()
...     BLUE = object()
...     def __repr__(self):
...         return "<%s.%s>" % (self.__class__.__name__, self._name_)
...
>>> Color.GREEN
<Color.GREEN>
@end example

@node 解説文字列を使う,Using a custom __new__,object を使う,値の省略
@anchor{howto/enum using-a-descriptive-string}@anchor{571c}
@subsubsection 解説文字列を使う


値として文字列を使うと次のようになります:

@example
>>> class Color(Enum):
...     RED = 'stop'
...     GREEN = 'go'
...     BLUE = 'too fast!'
...
>>> Color.GREEN
<Color.GREEN: 'go'>
@end example

@node Using a custom __new__,,解説文字列を使う,値の省略
@anchor{howto/enum using-a-custom-new}@anchor{571d}
@subsubsection Using a custom @code{__new__()}


Using an auto-numbering @ref{7a0,,__new__()} would look like:

@example
>>> class AutoNumber(Enum):
...     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: 2>
@end example

@code{AutoNumber} をより広い用途で使うには、シグニチャに @code{*args} を追加します:

@example
>>> class AutoNumber(Enum):
...     def __new__(cls, *args):      # this is the only change from above
...         value = len(cls.__members__) + 1
...         obj = object.__new__(cls)
...         obj._value_ = value
...         return obj
...
@end example

@code{AutoNumber} を継承すると、追加の引数を取り扱える独自の @code{__init__} が書けます。

@example
>>> class Swatch(AutoNumber):
...     def __init__(self, pantone='unknown'):
...         self.pantone = pantone
...     AUBURN = '3497'
...     SEA_GREEN = '1246'
...     BLEACHED_CORAL = () # New color, no Pantone code yet!
...
>>> Swatch.SEA_GREEN
<Swatch.SEA_GREEN: 2>
>>> Swatch.SEA_GREEN.pantone
'1246'
>>> Swatch.BLEACHED_CORAL.pantone
'unknown'
@end example

@cartouche
@quotation 注釈 
The @ref{7a0,,__new__()} method, if defined, is used during creation of the Enum
members; it is then replaced by Enum's @ref{7a0,,__new__()} which is used after
class creation for lookup of existing members.
@end quotation
@end cartouche

@cartouche
@quotation 警告 
`Do not' call @code{super().__new__()}, as the lookup-only @code{__new__} is the one
that is found; instead, use the data type directly -- e.g.:

@example
obj = int.__new__(cls, value)
@end example
@end quotation
@end cartouche

@node OrderedEnum,DuplicateFreeEnum,値の省略,Enum クックブック
@anchor{howto/enum orderedenum}@anchor{56ff}
@subsubsection OrderedEnum


@ref{edb,,IntEnum} をベースとしないため、通常の @ref{842,,Enum} の不変条件 (他の列挙型と比較できないなど) のままで、メンバーを順序付けできる列挙型です:

@example
>>> class OrderedEnum(Enum):
...     def __ge__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value >= other.value
...         return NotImplemented
...     def __gt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value > other.value
...         return NotImplemented
...     def __le__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value <= other.value
...         return NotImplemented
...     def __lt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value < other.value
...         return NotImplemented
...
>>> class Grade(OrderedEnum):
...     A = 5
...     B = 4
...     C = 3
...     D = 2
...     F = 1
...
>>> Grade.C < Grade.A
True
@end example

@node DuplicateFreeEnum,MultiValueEnum,OrderedEnum,Enum クックブック
@anchor{howto/enum duplicatefreeenum}@anchor{571e}
@subsubsection DuplicateFreeEnum


値が重複するメンバーがある場合に、エイリアスを作成するのではなくエラーを発生させます:

@example
>>> class DuplicateFreeEnum(Enum):
...     def __init__(self, *args):
...         cls = self.__class__
...         if any(self.value == e.value for e in cls):
...             a = self.name
...             e = cls(self.value).name
...             raise ValueError(
...                 "aliases not allowed in DuplicateFreeEnum:  %r --> %r"
...                 % (a, e))
...
>>> class Color(DuplicateFreeEnum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...     GRENE = 2
...
Traceback (most recent call last):
  ...
ValueError: aliases not allowed in DuplicateFreeEnum:  'GRENE' --> 'GREEN'
@end example

@cartouche
@quotation 注釈 
これは Enum に別名を無効にするのと同様な振る舞いの追加や変更をおこなうためのサブクラス化に役立つ例です。単に別名を無効にしたいだけなら、 @ref{2a2c,,unique()} デコレーターを使用して行えます。
@end quotation
@end cartouche

@node MultiValueEnum,Planet,DuplicateFreeEnum,Enum クックブック
@anchor{howto/enum multivalueenum}@anchor{570b}
@subsubsection MultiValueEnum


Supports having more than one value per member:

@example
>>> class MultiValueEnum(Enum):
...     def __new__(cls, value, *values):
...         self = object.__new__(cls)
...         self._value_ = value
...         for v in values:
...             self._add_value_alias_(v)
...         return self
...
>>> class DType(MultiValueEnum):
...     float32 = 'f', 8
...     double64 = 'd', 9
...
>>> DType('f')
<DType.float32: 'f'>
>>> DType(9)
<DType.double64: 'd'>
@end example

@node Planet,TimePeriod,MultiValueEnum,Enum クックブック
@anchor{howto/enum planet}@anchor{56fc}
@subsubsection Planet


If @ref{7a0,,__new__()} or @ref{8bf,,__init__()} is defined, the value of the enum member
will be passed to those methods:

@example
>>> class Planet(Enum):
...     MERCURY = (3.303e+23, 2.4397e6)
...     VENUS   = (4.869e+24, 6.0518e6)
...     EARTH   = (5.976e+24, 6.37814e6)
...     MARS    = (6.421e+23, 3.3972e6)
...     JUPITER = (1.9e+27,   7.1492e7)
...     SATURN  = (5.688e+26, 6.0268e7)
...     URANUS  = (8.686e+25, 2.5559e7)
...     NEPTUNE = (1.024e+26, 2.4746e7)
...     def __init__(self, mass, radius):
...         self.mass = mass       # in kilograms
...         self.radius = radius   # in meters
...     @@property
...     def surface_gravity(self):
...         # universal gravitational constant  (m3 kg-1 s-2)
...         G = 6.67300E-11
...         return G * self.mass / (self.radius * self.radius)
...
>>> Planet.EARTH.value
(5.976e+24, 6378140.0)
>>> Planet.EARTH.surface_gravity
9.802652743337129
@end example

@node TimePeriod,,Planet,Enum クックブック
@anchor{howto/enum enum-time-period}@anchor{2a3f}@anchor{howto/enum timeperiod}@anchor{571f}
@subsubsection TimePeriod


An example to show the @ref{2a3e,,_ignore_} attribute in use:

@example
>>> from datetime import timedelta
>>> class Period(timedelta, Enum):
...     "different lengths of time"
...     _ignore_ = 'Period i'
...     Period = vars()
...     for i in range(367):
...         Period['day_%d' % i] = i
...
>>> list(Period)[:2]
[<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
>>> list(Period)[-2:]
[<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
@end example

@node EnumType のサブクラスを作る,,Enum クックブック,列挙型 HOWTO
@anchor{howto/enum enumtype-examples}@anchor{2a2f}@anchor{howto/enum subclassing-enumtype}@anchor{5720}
@subsection EnumType のサブクラスを作る


While most enum needs can be met by customizing @ref{842,,Enum} subclasses,
either with class decorators or custom functions, @ref{4f7,,EnumType} can be
subclassed to provide a different Enum experience.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 関数型プログラミング HOWTO,Logging HOWTO,列挙型 HOWTO,Python HOWTO
@anchor{howto/functional doc}@anchor{5721}@anchor{howto/functional functional-howto}@anchor{5722}@anchor{howto/functional functional-programming-howto}@anchor{5723}@anchor{howto/functional translation-repo}@anchor{5724}
@section 関数型プログラミング HOWTO


@*著者: 
A. M. Kuchling


@*リリース: 
0.32


この文書では、関数型スタイルでプログラムを実装するのにピッタリな Python の機能を見てまわることにしましょう。まず関数型プログラミングという概念を紹介したあと、 @ref{4c8,,iterator} や @ref{126c,,generator} のような言語機能、および @ref{85,,itertools} や @ref{63,,functools} といった関連するライブラリモジュールを見ることにします。

@menu
* はじめに: はじめに<15>. 
* イテレータ (iterator): イテレータ iterator<2>. 
* ジェネレータ式とリスト内包表記:: 
* ジェネレータ (generator): ジェネレータ generator<2>. 
* 組み込み関数 (built-in function): 組み込み関数 built-in function<2>. 
* itertools モジュール:: 
* functools モジュール:: 
* 小さな関数とラムダ式:: 
* 更新履歴と謝辞:: 
* 参考資料: 参考資料<2>. 

@end menu

@node はじめに<15>,イテレータ iterator<2>,,関数型プログラミング HOWTO
@anchor{howto/functional introduction}@anchor{5725}
@subsection はじめに


この章は関数型プログラミングの基本概念を説明します; Python の言語機能についてだけ知りたい人は、次の章の @ref{5726,,イテレータ (iterator)} まで飛ばしてください。

プログラミング言語とは問題を分解するものですが、各言語がサポートする分解方法にはいくつかの種類があります:


@itemize *

@item 
ほとんどのプログラミング言語は `手続き型' です: プログラムは、入力に対して行うべきことをコンピュータに教える指示リストとなります。 C, Pascal, さらには Unix シェルまでもが手続き型言語に入ります。

@item 
`宣言型' 言語で書くのは、解くべき問題を説明する仕様書であって、それを効率的に計算処理する方法を見付けるのは言語実装の役目です。SQL はおそらく一番よく知られた宣言型言語です; SQL のクエリは取得したいデータセットを説明しているだけで、テーブルを走査するかインデックスを使うか、どのサブクローズから実行するか等々を決めるのは SQL エンジンなのです。

@item 
`オブジェクト指向' プログラムはオブジェクトの集まりを操作します。オブジェクトには内部状態があり、その状態を調べたり色々と変更したりするためのメソッドがあります。Smalltalk や Java はオブジェクト指向言語です。 C++ と Python はオブジェクト指向プログラミングをサポートしていますが、関連する機能を使わなくても構わないようになっています。

@item 
`関数型' プログラミングは問題をいくつかの関数にわけて考えます。理想的に言うと、関数は入力を受けて出力を吐くだけで、同じ入力に対して異なる出力をするような内部状態を一切持ちません。有名な関数型言語には ML 一家 (Standard ML, OCaml 等々) と Haskell があります。
@end itemize

設計者が特定のアプローチを強調することにした言語もありますが、そうすると大抵は、別のアプローチを使うプログラムを書きにくくなります。複数のアプローチに対応した言語もあり、Lisp, C++, Python はそうしたマルチパラダイム言語です; この中のどれを使っても、基本的に手続き型な、または基本的にオブジェクト指向な、とか、基本的に関数型なプログラムやライブラリを書くことができます。大きなプログラムでは、各部で別々のアプローチを使って書くことがあるかもしれません; GUI はオブジェクト指向で、でも処理ロジックは手続き型や関数型で、といったようにです。

関数型プログラムでは、入力は一連の関数を通って流れていきます。それぞれの関数は入力に何らかの作業をして出力します。関数型スタイルにおいては、内部状態を変えてしまったり、返り値に現れない変更をしたりといった副作用のある関数はやめるように言われています。副作用のまったくない関数は `純粋関数型' であるとされます。副作用をなくすということは、プログラムの実行中に順次変化していくデータ構造を持たない、つまり各関数の出力はその入力にしか影響を受けてはいけないということです。

ある言語では純粋さにとても厳しく @code{a=3} や @code{c = a + b} のような代入文すら存在しないほどですが、画面への表示やディスクファイルへの書き込みなど、すべての副作用を避けるのは難しいです。別の例として、 @ref{1177,,print()} や @ref{8ac,,time.sleep()} 関数の呼び出しもありますが、どちらも有用な値を返しません。画面にテキストを送ったり、実行を 1 秒間停めたりといった副作用のためだけに呼ばれるのです。

関数型スタイルで書いた Python プログラムはふつう、I/O や代入を完全になくすといった極端なところまでは行かずに、関数型っぽく見えるインターフェースを提供しつつも内部では非関数型の機能を使います。たとえば、関数内でローカル変数の代入は使いますが、グローバル変数は変更せず、他の副作用もないように実装するのです。

関数型プログラミングはオブジェクト指向プログラミングの反対と考えることもできます。オブジェクト指向において、オブジェクトは内部状態とそれを変更するメソッドコールの入ったカプセルであり、プログラムはその状態を適正に変化させていく手順です。一方で、関数型プログラミングは可能なかぎり状態の変更を避け、関数どうしの間を流れるデータだけを扱おうとします。Python ではこの二つのアプローチを結び合わせることができます。アプリケーション内のオブジェクト (メール、トランザクション、等々) を表現したインスタンスを、関数が受け渡しするようにするのです。

関数型デザインは、わけのわからない制約に見えるかもしれません。どうしてオブジェクトも副作用もないほうが良いのでしょうか。実は、関数型スタイルには理論と実践に基づく次の利点があるのです:


@itemize *

@item 
形式的証明可能性。

@item 
モジュラー性。

@item 
結合性。

@item 
デバッグやテストの簡単さ。
@end itemize

@menu
* 形式的証明可能性:: 
* モジュラー性:: 
* デバッグやテストの簡単さ:: 
* 結合性:: 

@end menu

@node 形式的証明可能性,モジュラー性,,はじめに<15>
@anchor{howto/functional formal-provability}@anchor{5727}
@subsubsection 形式的証明可能性


理論面の利点としては、プログラムが正しいことの数学的証明を他より簡単に構築できるという点があります。

研究者たちは長いあいだ、プログラムが正しいことを数学的に証明する方法の発見に血道をあげてきました。これは、色々な入力でテストして出力が正しかったからまあ正しいだろう、と結論するのとも違いますし、ソースコードを読んで「間違いはなさそうだ」と言うのとも別の話です; 目指すのは、出現しうる入力すべてに対してプログラムが正しい結果を出すことの厳密な証明なのです。

プログラムを証明するために使われているのは `不変式' を書き出していくというテクニックで、不変式とは入力データやプログラム変数のうち常に真である性質のことです。コードの一行一行で、 `実行前' の不変式 X と Y が真なら `実行後に' ちょっと違う不変式 X' と Y' が真になることを示していき、これをプログラムの終わりまで続けるわけです。すると最終的な不変式はプログラムの出力に合った条件になっているはずです。

関数型プログラミングが代入を嫌うのは、この不変式テクニックでは代入を扱いにくいからです; 代入は、それまで真だった不変式を壊しておいて、自分は次の行に伝えてゆける不変式を生み出さないことがあるのです。

残念ながら、プログラムの証明はだいたい実際的でもありませんし、Python ソフトウェアにも関係ありません。本当に簡単なプログラムでも、証明には数ページにわたる論文が必要なのです; ある程度の複雑なプログラムではもう尋常でない長さになってしまうので、日常で使っているプログラム (Python インタプリタ、XML パーサ、ウェブブラウザ) はほとんど、あるいはすべて、正しさを証明するのは不可能でしょう。仮に証明を書き出したり生成したりしても、その証明を検証するための疑いが残ります; 証明に間違いがあるかもしれず、その場合は証明したと自分で勝手に思い込んでいただけになるのです。

@node モジュラー性,デバッグやテストの簡単さ,形式的証明可能性,はじめに<15>
@anchor{howto/functional modularity}@anchor{5728}
@subsubsection モジュラー性


より実用的には、関数型プログラミングをすると問題を細かく切り分けることになるという利点があります。結果としてプログラムはモジュラー化されます。複雑な変形を施す大きな関数を書くより、一つのことに絞ってそれだけをする小さな関数のほうが書きやすいものです。それに、小さいほうが読むのもエラーをチェックするのも簡単です。

@node デバッグやテストの簡単さ,結合性,モジュラー性,はじめに<15>
@anchor{howto/functional ease-of-debugging-and-testing}@anchor{5729}
@subsubsection デバッグやテストの簡単さ


テストやデバッグも関数型プログラムなら簡単です。

関数が一般的に小さくて明確に意味付けされているので、デバッグ方法は単純です。プログラムが正しく動かないときには、関数ひとつひとつがデータの正しさをチェックするポイントになるので、それぞれの時点における入力と出力を見ていけば、バグの原因となる関数を素早く切り出すことができるのです。

ひとつひとつの関数がユニットテストの対象になり得るわけですから、テストも簡単です。関数はシステムの状態に依存しませんので、テストの実行前にそうした状態を再現する必要はありません; 単に適切な入力を合成して、出力が期待どおりかどうかチェックするだけで良いのです。

@node 結合性,,デバッグやテストの簡単さ,はじめに<15>
@anchor{howto/functional composability}@anchor{572a}
@subsubsection 結合性


関数型スタイルのプログラムを作っていると、色々な入力や出力のために色々な関数を書くことになります。仕方なく特定のアプリケーションに特化した関数を書くこともあるでしょうけれど、広範なプログラムに使える関数もあることでしょう。たとえば、ディレクトリ名を受け取ってその中の XML ファイル一覧を返す関数や、ファイル名を受け取って内容を返す関数などは、多様な場面に適用できそうです。

時たつうちに自分の特製ライブラリやユーティリティが充実してくると、新しいプログラムも、既存の関数を調整して少し今回に特化した関数を書くだけで組み立てられるようになります。

@node イテレータ iterator<2>,ジェネレータ式とリスト内包表記,はじめに<15>,関数型プログラミング HOWTO
@anchor{howto/functional functional-howto-iterators}@anchor{5726}@anchor{howto/functional iterators}@anchor{572b}
@subsection イテレータ (iterator)


まずは関数型スタイルのプログラムを書く際の基礎となる重要な Python 機能から見ていきましょう: イテレータです。

イテレータは連続データを表現するオブジェクトです; このオブジェクトは一度に一つの要素ずつデータを返します。 Python のイテレータは @ref{14e5,,__next__()} という、引数を取らず次の要素を返すメソッドを必ずサポートしています。データストリームに要素が残っていない場合、 @ref{14e5,,__next__()} は必ず @ref{df5,,StopIteration} 例外を出します。ただし、イテレータの長さは有限である必要はありません; 無限のストリームを生成するイテレータを書くというのもまったく理に適ったことです。

ビルトインの @ref{9d7,,iter()} 関数は任意のオブジェクトを受けて、 その中身や要素を返すイテレータを返そうとします。引数のオブジェクトが イテレータを作れないときは @ref{198,,TypeError} を投げます。Python の ビルトインなデータ型にもいくつかイテレータ化のできるものがあり、 中でもよく使われるのはリストと辞書です。イテレータを作れる オブジェクトは @ref{12f1,,iterable} オブジェクトと呼ばれます。

手を動かしてイテレータ化の実験をしてみましょう:

@example
>>> L = [1, 2, 3]
>>> it = iter(L)
>>> it
<...iterator object at ...>
>>> it.__next__()  # same as next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
@end example

Python は色々な文脈でイテラブルなオブジェクトを期待しますが、 最も重要なのは @ref{34a,,for} 文です。 @code{for X in Y} という文の Y は、 イテレータか、あるいは @ref{9d7,,iter()} でイテレータを作れるオブジェクトである必要があります。次の二つは同じ意味になります:

@example
for i in iter(obj):
    print(i)

for i in obj:
    print(i)
@end example

イテレータは @ref{24d,,list()} や @ref{614,,tuple()} といったコンストラクタ関数を使ってリストやタプルに具現化することができます:

@example
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> t = tuple(iterator)
>>> t
(1, 2, 3)
@end example

シーケンスのアンパックもイテレータに対応しています: イテレータが N 個の要素を返すということが事前にわかっていれば、N-タプルにアンパックすることができます:

@example
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> a, b, c = iterator
>>> a, b, c
(1, 2, 3)
@end example

ビルトイン関数の @ref{110c,,max()} や @ref{110b,,min()} なども、イテレータ一つだけを引数に取って最大・最小の要素を返すことができます。 @code{"in"} や @code{"not in"} 演算子もイテレータに対応しています: @code{X in iterator} は、そのイテレータから返るストリームに X があれば真です。ですからイテレータが無限長だと、当然ながら問題に直面します; @ref{110c,,max()}, @ref{110b,,min()} はいつまでも戻って来ませんし、 要素 X がストリームに出てこなければ @code{"in"}, @code{"not in"} オペレータも戻りません。

イテレータは次に進むことしかできませんのでご注意ください; 前の要素を手に入れたり、イテレータをリセットしたり、コピーを作ったりする方法はありません。イテレータがオブジェクトとしてそうした追加機能を 持つことはできますが、プロトコルでは @ref{14e5,,__next__()} メソッドのことしか指定されていません。ですから関数はイテレータの出力を使い尽くして しまうかもしれませんし、同じストリームに何か別のことをする 必要があるなら新しいイテレータを作らなくてはいけません。

@menu
* イテレータ対応のデータ型:: 

@end menu

@node イテレータ対応のデータ型,,,イテレータ iterator<2>
@anchor{howto/functional data-types-that-support-iterators}@anchor{572c}
@subsubsection イテレータ対応のデータ型


リストやタプルがイテレータに対応している方法については既に見ましたが、実のところ Python のシーケンス型はどれでも、たとえば文字列なども、自動でイテレータ生成に対応しています。

辞書に対して @ref{9d7,,iter()} すると、辞書のキーでループを回すイテレータが返されます:

@example
>>> m = @{'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12@}
>>> for key in m:
...     print(key, m[key])
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
@end example

Python 3.7 から、辞書の反復順序は挿入順序と同じであることが保証されていることに注意してください。
以前のバージョンでは、その振る舞いは仕様が定められておらず、実装ごとに異なることがありました。

辞書は @ref{9d7,,iter()} を適用するとキーでループを回しますが、辞書には他のイテレータを返すメソッドもあります。明示的に値、あるいはキーと値のペアでイテレートしたければ、@ref{9d1,,values()}, @ref{9d2,,items()} というメソッドでイテレータを作ることができます。

逆に @ref{183,,dict()} コンストラクタは、有限な  @code{(key, value)} タプルのストリームを返すイテレータを受け入れることができます:

@example
>>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
>>> dict(iter(L))
@{'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'@}
@end example

ファイルも、最後の行まで @ref{20a6,,readline()} メソッドを呼んでいくことでイテレータ化に対応しています。つまりこうやってファイルの各行を読んでいくことができるわけです:

@example
for line in file:
    # do something for each line
    ...
@end example

セットはイテラブルを受け取れますし、そのセットの要素でイテレートすることもできます:

@example
>>> S = @{2, 3, 5, 7, 11, 13@}
>>> for i in S:
...     print(i)
2
3
5
7
11
13
@end example

@node ジェネレータ式とリスト内包表記,ジェネレータ generator<2>,イテレータ iterator<2>,関数型プログラミング HOWTO
@anchor{howto/functional generator-expressions-and-list-comprehensions}@anchor{572d}
@subsection ジェネレータ式とリスト内包表記


イテレータの出力に対してよく使う操作トップ 2 は、(1) ひとつずつ全要素に操作を実行する、および (2) 条件に合う要素でサブセットを作る、です。たとえば文字列のリストなら、各行のうしろに付いた邪魔なホワイトスペースを削りたいとか、特定の文字列を含む部分をピックアップしたいなどと思うかもしれません。

リスト内包表記とジェネレータ式 (略して「listcomp」と「genexp」) は、そうした操作向けの簡潔な表記方法です。これは関数型プログラミング言語 Haskell (@indicateurl{https://www.haskell.org/}) にインスパイアされました。文字列のストリームからホワイトスペースをすべて削るのは次のコードでできます:

@example
>>> line_list = ['  line 1\n', 'line 2  \n', ' \n', '@w{'}]

>>> # Generator expression -- returns iterator
>>> stripped_iter = (line.strip() for line in line_list)

>>> # List comprehension -- returns list
>>> stripped_list = [line.strip() for line in line_list]
@end example

特定の要素だけを選び出すのは @code{"if"} 条件式を付けることで可能です:

@example
>>> stripped_list = [line.strip() for line in line_list
...                  if line != ""]
@end example

リスト内包表記を使うと Python リストが返って来ます; @code{stripped_list} は実行結果の行が入ったリストであって、イテレータではありません。ジェネレータ式はイテレータを返し、これだと必要に応じてだけ値を算出しますので、すべての値を一度に出す必要がありません。つまりリスト内包表記のほうは、無限長ストリームや膨大なデータを返すようなイテレータを扱う際には、あまり役に立たないということです。そういった状況ではジェネレータ式のほうが好ましいと言えます。

ジェネレータ式は丸括弧 "()" で囲まれ、リスト内包表記は角括弧 "[]" で囲まれます。ジェネレータ式の形式は次のとおりです:

@example
( expression for expr in sequence1
             if condition1
             for expr2 in sequence2
             if condition2
             for expr3 in sequence3
             ...
             if condition3
             for exprN in sequenceN
             if conditionN )
@end example

リスト内包表記も、外側の括弧が違うだけ (丸ではなく角括弧) で、あとは同じです。

生成される出力は @code{expression} 部分の値を要素として並べたものになります。 @code{if} 節はすべて、なくても大丈夫です; あれば @code{condition} が真のときだけ @code{expression} が評価されて出力に追加されます。

ジェネレータ式は常に括弧の中に書かなければなりませんが、関数コールの目印になっている括弧でも大丈夫です。関数にすぐ渡すイテレータを作りたければこう書けるのです:

@example
obj_total = sum(obj.count for obj in list_all_objects())
@end example

@code{for...in} 節は複数つなげられますが、どれにも、イテレートするためのシーケンスが含まれています。それらのシーケンスは並行して `ではなく' 、左から右へ順番にイテレートされるので、長さが同じである必要はありません。 @code{sequence1} の各要素ごとに毎回最初から @code{sequence2} をループで回すのです。その後 @code{sequence1} と @code{sequence2} から出た要素ペアごとに、 @code{sequence3} でループします。

別の書き方をすると、リスト内包表記やジェネレータ式は次の Python コードと同じ意味になります:

@example
for expr1 in sequence1:
    if not (condition1):
        continue   # Skip this element
    for expr2 in sequence2:
        if not (condition2):
            continue   # Skip this element
        ...
        for exprN in sequenceN:
            if not (conditionN):
                continue   # Skip this element

            # Output the value of
            # the expression.
@end example

つまり、複数の @code{for...in} 節があって @code{if} がないときの最終出力は、長さが各シーケンス長の積に等しくなるということです。長さ 3 のリスト二つなら、出力リストの長さは 9 要素です:

@example
>>> seq1 = 'abc'
>>> seq2 = (1, 2, 3)
>>> [(x, y) for x in seq1 for y in seq2]
[('a', 1), ('a', 2), ('a', 3),
 ('b', 1), ('b', 2), ('b', 3),
 ('c', 1), ('c', 2), ('c', 3)]
@end example

Python の文法に曖昧さを紛れ込ませないように、 @code{expression} でタプルを作るなら括弧で囲わなくてはなりません。下にあるリスト内包表記で、最初のは構文エラーですが、二番目は有効です:

@example
# Syntax error
[x, y for x in seq1 for y in seq2]
# Correct
[(x, y) for x in seq1 for y in seq2]
@end example

@node ジェネレータ generator<2>,組み込み関数 built-in function<2>,ジェネレータ式とリスト内包表記,関数型プログラミング HOWTO
@anchor{howto/functional generators}@anchor{572e}
@subsection ジェネレータ (generator)


ジェネレータは、イテレータを書く作業を簡単にする、特殊な関数です。標準的な関数は値を計算して返しますが、ジェネレータが返すのは、一連の値を返すイテレータです。

Python や C の標準的な関数コールについては、よくご存じに違いありません。関数を呼ぶと、ローカル変数を作るプライベートな名前空間ができますね。その関数が @code{return} 文まで来ると、ローカル変数が破壊されてから、返り値が呼び出し元に返ります。次に同じ関数をもう一度呼ぶと、新しいプライベート名前空間に新規のローカル変数が作られるのです。しかし、関数を出るときにローカル変数を捨てなければどうなるでしょうか。その出ていったところから関数を続行できたとしたら、どうでしょう。これこそジェネレータが提供する機能です; すなわち、ジェネレータは続行できる関数と考えることができます。

ごく単純なジェネレータ関数の例がこちらにあります:

@example
>>> def generate_ints(N):
...    for i in range(N):
...        yield i
@end example

@ref{bc2,,yield} キーワードを含む関数はすべてジェネレータ関数です; Python の @ref{4aa,,bytecode} コンパイラがこれを検出して、特別な方法でコンパイルしてくれるのです。

ジェネレータ関数は、呼ばれたときに一回だけ値を返すのではなく、イテレータ プロトコルに対応したオブジェクトを返します。上の例で @code{yield} を実行したとき、 ジェネレータは @code{return} 文のようにして @code{i} の値を出力します。 @code{yield} と @code{return} 文の大きな違いは、 @code{yield} に到達した段階でジェネレータの実行状態が一時停止になって、ローカル変数が保存される点です。 次回そのジェネレータの @ref{20ae,,__next__()} を呼ぶと、そこから関数が実行を再開します。

上記 @code{generate_ints()} ジェネレータの使用例はこちらです:

@example
>>> gen = generate_ints(3)
>>> gen
<generator object generate_ints at ...>
>>> next(gen)
0
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
  File "stdin", line 1, in <module>
  File "stdin", line 2, in generate_ints
StopIteration
@end example

同じく @code{for i in generate_ints(5)} や @code{a, b, c = generate_ints(3)} といった書き方もできます。

ジェネレータ関数の中では、@code{return value} は @ref{20ae,,__next__()} メソッドから送出された @code{StopIteration(value)} を引き起こします。これが発生した場合や、関数の終わりに到達した場合は、値の生成が終了してジェネレーターがそれ以上の値を返さない。

自分でクラスを書いて、ジェネレータで言うところのローカル変数をインスタンス変数として全部保管しておけば、同じ効果を得ることは可能です。たとえば整数のリストを返すのは、 @code{self.count} を 0 にして、 @ref{14e5,,__next__()} メソッドが @code{self.count} をインクリメントして返すようにすればできます。しかしながら、ある程度複雑なジェネレータになってくると、同じことをするクラスを書くのは格段にややこしいことになります。

Python のライブラリに含まれているテストスイート Lib/test/test_generators.py@footnote{https://github.com/python/cpython/tree/3.14/Lib/test/test_generators.py} には、ほかにも興味深い例が数多く入っています。これは二分木の通りがけ順 (in-order) 探索を再帰で実装したジェネレータです。

@example
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x

        yield t.label

        for x in inorder(t.right):
            yield x
@end example

ほかにも @code{test_generators.py} には、N-Queens 問題 (N×N コマのチェス盤に、互いに攻撃できないような配置で N 個のクイーンを置く) やナイト・ツアー (N×N 盤の全コマをナイトが一度ずつ通るような経路を探す) の解を出す例が入っています。

@menu
* ジェネレータに値を渡す:: 

@end menu

@node ジェネレータに値を渡す,,,ジェネレータ generator<2>
@anchor{howto/functional passing-values-into-a-generator}@anchor{572f}
@subsubsection ジェネレータに値を渡す


Python 2.4 までのジェネレータは出力することしかできませんでした。ジェネレータのコードを実行してイテレータを作ってしまったあとで、その関数を再開するときに新しい情報を渡す手段はなかったのです。ジェネレータがグローバル変数を見るようにしたり、ミュータブルなオブジェクトを渡しておいて呼び出し元であとからそれを変更したり、といったハックは可能でしたが、どれもゴチャゴチャしていますね。

Python 2.5 で、ジェネレータに値を渡す簡単な手段ができました。 @ref{bc2,,yield} が、変数に代入したり演算したりできる値を返す式になったのです:

@example
val = (yield i)
@end example

上のように、返り値で何かをするときは @code{yield} 式の前後に `必ず' 括弧を付けるようお勧めします。括弧は常に必要なわけではありませんが、どんなとき付けなくて良いのかを覚えておくより、いつも付けておくほうが楽ですから。

(
@geindex Python Enhancement Proposals; PEP 342
PEP 342@footnote{https://peps.python.org/pep-0342/} がその規則を正確に説明していますが、それによると @code{yield}-式は、代入式で右辺のトップレベルにあるとき以外はいつも括弧を付ける必要があります。つまり @code{val = yield i} とは書けますが、 @code{val = (yield i) + 12} のように演算子があるときは括弧を使わなくてはいけません。)

ジェネレータに値を送るには @ref{126d,,send(value)} メソッドを呼びます。 するとジェネレータのコードが実行を再開し、 @code{yield} 式がその値を返すのです。ふつうの @ref{20ae,,__next__()} メソッドを呼ぶと、 @code{yield} は @code{None} を返します。

下にあるのは 1 ずつ増える単純なカウンタですが、内部カウンタの値を変更することができるようになっています。

@example
def counter(maximum):
    i = 0
    while i < maximum:
        val = (yield i)
        # If value provided, change counter
        if val is not None:
            i = val
        else:
            i += 1
@end example

そしてカウンタ変更の例がこちらです:

@example
>>> it = counter(10)
>>> next(it)
0
>>> next(it)
1
>>> it.send(8)
8
>>> next(it)
9
>>> next(it)
Traceback (most recent call last):
  File "t.py", line 15, in <module>
    it.next()
StopIteration
@end example

@code{yield} が @code{None} を返すことはよくあるのですから、そうなっていないかどうか必ずチェックしておくべきです。ジェネレータ関数を再開するために使うメソッドが @ref{126d,,send()} しかないのだと確定してるのでない限り、式の値をそのまま使ってはいけません。

ジェネレータには、 @ref{126d,,send()} のほかにもメソッドが二つあります:


@itemize *

@item 
@ref{71c,,throw(value)} はジェネレータ内で例外を投げるために使います; その例外はジェネレータの実行が停止したところの @code{yield} 式によって投げられます。

@item 
@ref{1793,,close()} sends a @ref{15e1,,GeneratorExit} exception to the
generator to terminate the iteration.  On receiving this exception, the
generator's code must either raise @ref{15e1,,GeneratorExit} or
@ref{df5,,StopIteration}; catching the exception and doing anything else is
illegal and will trigger a @ref{244,,RuntimeError}.  @ref{1793,,close()}
will also be called by Python's garbage collector when the generator is
garbage-collected.

@ref{15e1,,GeneratorExit} が起こったときにクリーンアップ作業をする必要があるなら、 @ref{15e1,,GeneratorExit} を捕捉するのではなく @code{try: ... finaly:} するようお勧めします。
@end itemize

これらの変更の合わせ技で、ジェネレータは情報の一方的な生産者から、生産者かつ消費者という存在に変貌を遂げたのです。

ジェネレータは `コルーチン' という、より一般化された形式のサブルーチンにもなります。サブルーチンは一カ所 (関数の冒頭) から入って別の一カ所 (@code{return} 文) から出るだけですが、コルーチンはいろいろな場所 (@code{yield} 文) から入ったり出たり再開したりできるのです。

@node 組み込み関数 built-in function<2>,itertools モジュール,ジェネレータ generator<2>,関数型プログラミング HOWTO
@anchor{howto/functional built-in-functions}@anchor{5730}
@subsection 組み込み関数 (built-in function)


よくイテレータと一緒に使うビルトイン関数について、もっと詳しく見ていきましょう。

Python のビルトイン関数 @ref{19f,,map()} と @ref{a64,,filter()} は、機能がジェネレータ式と重複しています:


@table @asis

@item @ref{19f,,map(f@comma{} iterA@comma{} iterB@comma{} ...)} は以下のシーケンスのイテレータを返します

@code{f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...}.

@example
>>> def upper(s):
...     return s.upper()
@end example

@example
>>> list(map(upper, ['sentence', 'fragment']))
['SENTENCE', 'FRAGMENT']
>>> [upper(s) for s in ['sentence', 'fragment']]
['SENTENCE', 'FRAGMENT']
@end example
@end table

もちろん、リスト内包表記でも同じ結果が得られます。

@ref{a64,,filter(predicate@comma{} iter)} はある条件を満たす要素に渡るイテレータを返すので、同様にリスト内包表記で再現できます。
`predicate' は、ある条件に対する真偽値を返す関数です;
@ref{a64,,filter()} で使うには、その関数の引数は一つでなければなりません。

@example
>>> def is_even(x):
...     return (x % 2) == 0
@end example

@example
>>> list(filter(is_even, range(10)))
[0, 2, 4, 6, 8]
@end example

これはリスト内包表記でも書けます:

@example
>>> list(x for x in range(10) if is_even(x))
[0, 2, 4, 6, 8]
@end example

@ref{169a,,enumerate(iter@comma{} start=0)} はイテラブルの要素に順番に番号を振っていき、(`start' から数え始めたときの) 番号とそれぞれの要素を含む 2 タプルを返します。

@example
>>> for item in enumerate(['subject', 'verb', 'object']):
...     print(item)
(0, 'subject')
(1, 'verb')
(2, 'object')
@end example

@ref{169a,,enumerate()} はよく、リストに対してループさせて、条件に合う所に印を付けていくときに使われます:

@example
f = open('data.txt', 'r')
for i, line in enumerate(f):
    if line.strip() == '@w{'}:
        print('Blank line at line #%i' % i)
@end example

@ref{dc7,,sorted(iterable@comma{} key=None@comma{} reverse=False)} はイテラブルの要素をすべて集めたリストを作り、ソートして返します。 引数 `key' および `reverse' は、リストの @ref{dc8,,sort()} メソッドにそのまま渡されます。

@example
>>> import random
>>> # Generate 8 random numbers between [0, 10000)
>>> rand_list = random.sample(range(10000), 8)
>>> rand_list
[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
>>> sorted(rand_list)
[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
>>> sorted(rand_list, reverse=True)
[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
@end example

(ソートに関する詳細な論議は @ref{13f3,,ソートのテクニック} を参照)

組み込みの @ref{163a,,any(iter)} および @ref{163b,,all(iter)} は iterable の値の真偽を調べます。 @ref{163a,,any()} は要素のどれかが真値なら @code{True} を返し、 @ref{163b,,all()} は要素が全て真値なら @code{True} を返します:

@example
>>> any([0, 1, 0])
True
>>> any([0, 0, 0])
False
>>> any([1, 1, 1])
True
>>> all([0, 1, 0])
False
>>> all([0, 0, 0])
False
>>> all([1, 1, 1])
True
@end example

@ref{1a0,,zip(iterA@comma{} iterB@comma{} ...)} はそれぞれの iterable から1つの要素を取り、それらをタプルに入れて返します:

@example
zip(['a', 'b', 'c'], (1, 2, 3)) =>
  ('a', 1), ('b', 2), ('c', 3)
@end example

@ref{1a0,,zip()} は結果を返す前に入力のイテレーターを全て消費してメモリ上に list を作成しません。代わりに要求されるたびに tuple を生成して返します。(この動作を技術的な用語で lazy evaluation@footnote{https://en.wikipedia.org/wiki/Lazy_evaluation} (訳: 遅延評価@footnote{https://ja.wikipedia.org/wiki/%E9%81%85%E5%BB%B6%E8%A9%95%E4%BE%A1}) と呼びます。)

このイテレータの用途には、すべて同じ長さのイテラブルを想定しています。長さが違っていれば、出力されるストリームは一番短いイテラブルと同じ長さになります。

@example
zip(['a', 'b'], (1, 2, 3)) =>
  ('a', 1), ('b', 2)
@end example

とは言え、これをやってしまうと長いイテレータから要素をひとつ無駄に多く取って捨ててしまうかもしれませんので、やめておいたほうが良いです。その捨てられた要素を抜かしてしまう危険があるので、もうそのイテレータはそれ以上使えなくなってしまいます。

@node itertools モジュール,functools モジュール,組み込み関数 built-in function<2>,関数型プログラミング HOWTO
@anchor{howto/functional the-itertools-module}@anchor{5731}
@subsection itertools モジュール


@ref{85,,itertools} モジュールには、よく使うイテレータや、イテレータ同士の連結に使う関数がたくさん含まれています。この章では、そのモジュールの内容を小さな例で紹介していきたいと思います。

このモジュールの関数を大まかに分けるとこうなります:


@itemize *

@item 
既存のイテレータに基づいて新しいイテレータを作る関数。

@item 
イテレータの要素を引数として扱う関数。

@item 
イテレータの出力から一部を取り出す関数。

@item 
イテレータの出力をグループ分けする関数。
@end itemize

@menu
* 新しいイテレータを作る:: 
* 要素に対して関数を呼ぶ:: 
* 要素を選択する:: 
* 組合せ関数:: 
* 要素をグループ分けする:: 

@end menu

@node 新しいイテレータを作る,要素に対して関数を呼ぶ,,itertools モジュール
@anchor{howto/functional creating-new-iterators}@anchor{5732}
@subsubsection 新しいイテレータを作る


@ref{149b,,itertools.count(start@comma{} step)} は値の間隔が一定の無限ストリームを返します。
オプションで開始する数 (デフォルトは 0) や数どうしの間隔 (デフォルトは 1) を与えられます:

@example
itertools.count() =>
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
itertools.count(10) =>
  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.count(10, 5) =>
  10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...
@end example

@ref{2ba2,,itertools.cycle(iter)} は与えられたイテラブルの内容をコピーして、 その要素を最初から最後まで無限に繰り返していくイテレータを返します。

@example
itertools.cycle([1, 2, 3, 4, 5]) =>
  1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
@end example

@ref{1859,,itertools.repeat(elem@comma{} [n])} は、与えられた要素を `n' 回返しますが、 `n' がなければ永遠に返し続けます。

@example
itertools.repeat('abc') =>
  abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
itertools.repeat('abc', 5) =>
  abc, abc, abc, abc, abc
@end example

@ref{25de,,itertools.chain(iterA@comma{} iterB@comma{} ...)} は任意の数のイテラブルを受け取って、最初のイテレータから要素をすべて返し、次に二番目から 要素をすべて返し、ということを要素がなくなるまで続けます。

@example
itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
  a, b, c, 1, 2, 3
@end example

@ref{d43,,itertools.islice(iter@comma{} [start]@comma{} stop@comma{} [step])} は、イテレータの スライスをストリームで返します。 `stop' 引数だけだと、最初の `stop' 個の要素を返します。開始インデックスを渡すと `stop-start' 個で、 `step' の値も渡せばそれに応じて要素を抜かします。Python における文字列やリストのスライスとは違って、マイナスの値は `start', `stop', `step' に使えません。

@example
itertools.islice(range(10), 8) =>
  0, 1, 2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8) =>
  2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8, 2) =>
  2, 4, 6
@end example

@ref{2ba7,,itertools.tee(iter@comma{} [n])} はイテレータを複製します; 元のイテレータの内容を同じように返す、独立した `n' 個のイテレータを返すのです。 `n' の値は、指定しなければ既定が 2 になっています。複製するには元のイテレータの内容を一部保存しておく必要がありますから、大きなイテレータから複製したうちの一つが他よりも進んでいってしまうと、大量のメモリを消費することがあります。

@example
itertools.tee( itertools.count() ) =>
   iterA, iterB

where iterA ->
   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...

and   iterB ->
   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
@end example

@node 要素に対して関数を呼ぶ,要素を選択する,新しいイテレータを作る,itertools モジュール
@anchor{howto/functional calling-functions-on-elements}@anchor{5733}
@subsubsection 要素に対して関数を呼ぶ


いま使った @ref{a3,,operator} モジュールには、Python の演算子に対応する関数が入っています。いくつか例を挙げると、 @ref{2bce,,operator.add(a@comma{} b)} (二つの値を加算)、 @ref{2bbe,,operator.ne(a@comma{} b)} (@code{a != b} と同じ)、 @ref{1033,,operator.attrgetter('id')} (@code{.id} 属性を取得するコーラブルを返す) といった関数です。

@ref{12fa,,itertools.starmap(func@comma{} iter)} は、イテラブルがタプルのストリームを返すとみなして、 そのタプルを引数に使って `func' を呼びます:

@example
itertools.starmap(os.path.join,
                  [('/bin', 'python'), ('/usr', 'bin', 'java'),
                   ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
=>
  /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
@end example

@node 要素を選択する,組合せ関数,要素に対して関数を呼ぶ,itertools モジュール
@anchor{howto/functional selecting-elements}@anchor{5734}
@subsubsection 要素を選択する


さらに別のグループとして、述語 (predicate) に基づいてイテレータの要素からサブセットを選び出す関数があります。

@ref{25ce,,itertools.filterfalse(predicate@comma{} iter)} は @ref{a64,,filter()} とは反対に、 述語が偽を返す要素をすべて返します:

@example
itertools.filterfalse(is_even, itertools.count()) =>
  1, 3, 5, 7, 9, 11, 13, 15, ...
@end example

@ref{2ba6,,itertools.takewhile(predicate@comma{} iter)} は述語が真を返している間だけ要素を返します。一度でも述語が偽を返すと、イテレータは出力終了の合図をします。

@example
def less_than_10(x):
    return x < 10

itertools.takewhile(less_than_10, itertools.count()) =>
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9

itertools.takewhile(is_even, itertools.count()) =>
  0
@end example

@ref{2ba4,,itertools.dropwhile(predicate@comma{} iter)} は、述語が真を返しているうちは要素を無視し、偽になってから残りの出力をすべて返します。

@example
itertools.dropwhile(less_than_10, itertools.count()) =>
  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...

itertools.dropwhile(is_even, itertools.count()) =>
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
@end example

@ref{149a,,itertools.compress(data@comma{} selectors)} は 2つのイテレータを取り、 どちらかのイテレータを使い果たすまでの、 `selectors' が真となる要素に対応する `data' 要素だけを返します:

@example
itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
   1, 2, 5
@end example

@node 組合せ関数,要素をグループ分けする,要素を選択する,itertools モジュール
@anchor{howto/functional combinatoric-functions}@anchor{5735}
@subsubsection 組合せ関数


@ref{1529,,itertools.combinations(iterable@comma{} r)} は、 `iterable' から `r'-tuple 選択する全ての組み合わせを提供するイテレータを返します

@example
itertools.combinations([1, 2, 3, 4, 5], 2) =>
  (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 3), (2, 4), (2, 5),
  (3, 4), (3, 5),
  (4, 5)

itertools.combinations([1, 2, 3, 4, 5], 3) =>
  (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
  (2, 3, 4), (2, 3, 5), (2, 4, 5),
  (3, 4, 5)
@end example

それぞれのタプル内では、要素は `iterable' がそれを返したのと同じ順序を保ちます。例えば上の例であれば、 1 はいつでも 2, 3, 4, 5 の前に来ます。似たような関数に @ref{1cdd,,itertools.permutations(iterable@comma{} r=None)} があり、こちらはこの順序についての制約がなく、 `r' 個選択する全ての順列を返します。

@example
itertools.permutations([1, 2, 3, 4, 5], 2) =>
  (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 1), (2, 3), (2, 4), (2, 5),
  (3, 1), (3, 2), (3, 4), (3, 5),
  (4, 1), (4, 2), (4, 3), (4, 5),
  (5, 1), (5, 2), (5, 3), (5, 4)

itertools.permutations([1, 2, 3, 4, 5]) =>
  (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
  ...
  (5, 4, 3, 2, 1)
@end example

`r' を与えない場合は iterable の長さが使われます。つまり iterable の全ての要素を選んだ順列を返します。

これらの関数が生成する組み合わせは、位置が基準ですので、 `iterable' の内容が一意でなくとも良いことに注目してください:

@example
itertools.permutations('aba', 3) =>
  ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
  ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')
@end example

全く同じタプル @code{('a', 'a', 'b')} が 2度現れていますが、これは 2つの 'a' が別の位置からのものだからです。

@ref{1499,,itertools.combinations_with_replacement(iterable@comma{} r)} 関数は別の制約を取り払います: 一回の選択で同じ要素を繰り返し選んでも良い。概念的には、それぞれのタプルの最初のものとして一つ要素が選ばれ、続いて 2つ目の選択のかわりにそれで置き換わります

@example
itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>
  (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 2), (2, 3), (2, 4), (2, 5),
  (3, 3), (3, 4), (3, 5),
  (4, 4), (4, 5),
  (5, 5)
@end example

@node 要素をグループ分けする,,組合せ関数,itertools モジュール
@anchor{howto/functional grouping-elements}@anchor{5736}
@subsubsection 要素をグループ分けする


最後に議題に上げる関数 @ref{2ba5,,itertools.groupby(iter@comma{} key_func=None)} は、 これまでで最も複雑です。 @code{key_func(elem)} は、イテラブルから返ってきた要素それぞれのキー値を計算する関数です。この関数が指定されていなければ、 キーは単に各要素そのものになります。

@ref{2ba5,,groupby()} は、元になるイテラブルから同じキー値を持つ連続する要素を集めて、キー値とそのキーに対応する要素のイテレータの 2-タプルのストリームを返します。

@example
city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
             ('Anchorage', 'AK'), ('Nome', 'AK'),
             ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
             ...
            ]

def get_state(city_state):
    return city_state[1]

itertools.groupby(city_list, get_state) =>
  ('AL', iterator-1),
  ('AK', iterator-2),
  ('AZ', iterator-3), ...

where
iterator-1 =>
  ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
iterator-2 =>
  ('Anchorage', 'AK'), ('Nome', 'AK')
iterator-3 =>
  ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
@end example

@ref{2ba5,,groupby()} は、元になるイテラブルの内容がキー値でソートされた状態で与えられることを想定しています。ここで、返されるイテレータ自体も元のイテラブルを使うということに注意してください。そのため、 iterator-1 の結果を読み終わるまでは iterator-2 とそれに対応するキー値を要求することはできません。

@node functools モジュール,小さな関数とラムダ式,itertools モジュール,関数型プログラミング HOWTO
@anchor{howto/functional the-functools-module}@anchor{5737}
@subsection functools モジュール


@ref{63,,functools} モジュールには、高階関数がいくつか入っています。 `高階関数' とは、入力として関数を受け取って新たな関数を返す関数です。このモジュールで一番便利なツールは @ref{217,,functools.partial()} 関数です。

関数型スタイルのプログラムでは時折、既存の関数から一部のパラメータを埋めた変種を作りたくなることがあります。Python の関数 @code{f(a, b, c)} というものがあるとしてください; @code{f(1, b, c)} と同じ意味の @code{g(b, c)} という関数を作りたくなることがあります; つまり @code{f()} のパラメータを一つ埋めるわけです。これは「関数の部分適用」と呼ばれています。

@ref{217,,partial()} のコンストラクタは @code{(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)} という引数を取ります。できあがったオブジェクトはコーラブルなので、それを呼べば、引数の埋まった状態で @code{function} を実行したのと同じことになります。

以下にあるのは、小さいけれども現実的な一つの例です:

@example
import functools

def log(message, subsystem):
    """Write the contents of 'message' to the specified subsystem."""
    print('%s: %s' % (subsystem, message))
    ...

server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')
@end example

@ref{21a,,functools.reduce(func@comma{} iter@comma{} [initial_value])} はイテラブルの要素に対して次々に演算を実行していった最終結果を出すもので、それゆえ無限長イテラブルには適用できません。 `func' には、要素を二つ取って値を一つ返す関数が入ります。 @ref{21a,,functools.reduce()} はイテレータが返す最初の二要素 A と B を取って @code{func(A, B)} を計算します。それから三番目の要素 C を要求して @code{func(func(A, B), C)} を計算すると、その結果をさらに四番目の要素と組み合わせて……ということをイテラブルが尽きるまで続けるのです。 もしイテラブルが一つも値を返さなければ @ref{198,,TypeError} が発生します。 初期値 @code{initial_value} があるときには、最初の計算で @code{func(initial_value, A)} が実行されます。

@example
>>> import operator, functools
>>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
'ABBC'
>>> functools.reduce(operator.concat, [])
Traceback (most recent call last):
  ...
TypeError: reduce() of empty sequence with no initial value
>>> functools.reduce(operator.mul, [1, 2, 3], 1)
6
>>> functools.reduce(operator.mul, [], 1)
1
@end example

@ref{2bce,,operator.add()} を @ref{21a,,functools.reduce()} で使うと、 iterable の全要素を合計することになります。これは使用頻度が高いので、そのための @ref{695,,sum()} というビルトイン関数があります:

@example
>>> import functools, operator
>>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
10
>>> sum([1, 2, 3, 4])
10
>>> sum([])
0
@end example

とはいえ、多くの場合 @ref{21a,,functools.reduce()} を使うよりは、単に @ref{34a,,for} ループを書いたほうがわかりやすくなります:

@example
import functools
# Instead of:
product = functools.reduce(operator.mul, [1, 2, 3], 1)

# You can write:
product = 1
for i in [1, 2, 3]:
    product *= i
@end example

関連する関数は @ref{bf0,,itertools.accumulate(iterable@comma{} func=operator.add)} です。この関数は同じ計算をしますが、最終結果を返すのではなく、 @ref{bf0,,accumulate()} はそれぞれの中間結果を生成するイテレータが返り値となります。

@example
itertools.accumulate([1, 2, 3, 4, 5]) =>
  1, 3, 6, 10, 15

itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>
  1, 2, 6, 24, 120
@end example

@menu
* operator モジュール:: 

@end menu

@node operator モジュール,,,functools モジュール
@anchor{howto/functional the-operator-module}@anchor{5738}
@subsubsection operator モジュール


@ref{a3,,operator} モジュールは、既に取り上げましたが、Python の演算子に対応する関数が入っているモジュールです。関数型スタイルのコードにおいて、演算を一つ実行するだけのくだらない関数を書かずに済むので、よく世話になります。

このモジュールの関数を一部だけ紹介しましょう:


@itemize *

@item 
数学演算子: @code{add()}, @code{sub()}, @code{mul()}, @code{floordiv()}, @code{abs()}, ...

@item 
論理演算子: @code{not_()}, @code{truth()}

@item 
ビット演算子: @code{and_()}, @code{or_()}, @code{invert()}

@item 
比較: @code{eq()}, @code{ne()}, @code{lt()}, @code{le()}, @code{gt()}, @code{ge()}

@item 
オブジェクト識別: @code{is_()}, @code{is_not()}
@end itemize

ちゃんとした一覧は operator モジュールの文書でご覧ください。

@node 小さな関数とラムダ式,更新履歴と謝辞,functools モジュール,関数型プログラミング HOWTO
@anchor{howto/functional small-functions-and-the-lambda-expression}@anchor{5739}
@subsection 小さな関数とラムダ式


関数型スタイルのプログラムを書いていると、述語として働いたり、何らかの形で要素をつなぎ合わせたりするミニサイズの関数を必要とすることがよくあります。

ちょうど良い関数がビルトインやモジュールで存在していれば、新しい関数を定義する必要はまったくありません:

@example
stripped_lines = [line.strip() for line in lines]
existing_files = filter(os.path.exists, file_list)
@end example

しかし、欲しい関数がないなら書くしかありません。そうした小さな関数を書く方法の 一つが @ref{14b5,,lambda} 式です。 @code{lambda} は引数として複数のパラメータと それをつなぐ式を取り、その式の値を返す無名の関数を作ります:

@example
adder = lambda x, y: x+y

print_assign = lambda name, value: name + '=' + str(value)
@end example

もう一つの選択肢は、ふつうに @code{def} 文で関数を定義するだけです:

@example
def adder(x, y):
    return x + y

def print_assign(name, value):
    return name + '=' + str(value)
@end example

どちらのほうが良いのでしょうか。それは好みの問題です; 著者のスタイルとしてはできるだけ @code{lambda} を使わないようにしています。

そのようにしている理由の一つに、@code{lambda} は定義できる関数が非常に限られているという点があります。一つの式として算出できる結果にしなければいけませんので、@code{if... elif... else} や @code{try... except} のような分岐を持つことができないのです。@code{lambda} 文の中でたくさんのことをやろうとしすぎると、ごちゃごちゃして読みにくい式になってしまいます。さて、次のコードは何をしているでしょうか、素早くお答えください!

@example
import functools
total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
@end example

わかるにはわかるでしょうが、何がどうなっているのか紐解いていくには時間がかかるはずです。短い @code{def} 文で入れ子にすると、少し見通しが良くなりますが:

@example
import functools
def combine(a, b):
    return 0, a[1] + b[1]

total = functools.reduce(combine, items)[1]
@end example

でも単純に @code{for} ループにすれば良かったのです:

@example
total = 0
for a, b in items:
    total += b
@end example

あるいは @ref{695,,sum()} ビルトインとジェネレータ式でも良いですね:

@example
total = sum(b for a, b in items)
@end example

多くの場合、 @ref{21a,,functools.reduce()} を使っているところは @code{for} ループに 書き直したほうが見やすいです。

Fredrik Lundh は以前 @code{lambda} 利用のリファクタリングに関して以下の指針を提案したことがあります:


@enumerate 

@item 
ラムダ関数を書く。

@item 
そのラムダが一体ぜんたい何をしているのかコメントで説明する。

@item 
そのコメントをしばらく研究して、本質をとらえた名前を考える。

@item 
ラムダをその名前で def 文に書き換える。

@item 
コメントを消す。
@end enumerate

著者はこの指針を本当に気に入っていますが、こうしたラムダなしスタイルが他より優れているかどうかについて、異論は認めます。

@node 更新履歴と謝辞,参考資料<2>,小さな関数とラムダ式,関数型プログラミング HOWTO
@anchor{howto/functional revision-history-and-acknowledgements}@anchor{573a}
@subsection 更新履歴と謝辞


著者は提案の申し出や修正、様々なこの記事の草稿の助けをしてくれた以下の人々に感謝します: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton.

Version 0.1: posted June 30 2006.

Version 0.11: posted July 1 2006.  Typo fixes.

Version 0.2: posted July 10 2006.  Merged genexp and listcomp sections into one.
Typo fixes.

Version 0.21: Added more references suggested on the tutor mailing list.

Version 0.30: Adds a section on the @code{functional} module written by Collin
Winter; adds short section on the operator module; a few other edits.

@node 参考資料<2>,,更新履歴と謝辞,関数型プログラミング HOWTO
@anchor{howto/functional references}@anchor{573b}
@subsection 参考資料


@menu
* 一般論:: 
* Python 特有の話:: 
* Python 文書:: 

@end menu

@node 一般論,Python 特有の話,,参考資料<2>
@anchor{howto/functional general}@anchor{573c}
@subsubsection 一般論


`計算機プログラムの構造と解釈'、Harold AbelsonとGerald Jay Sussman、Julie Sussman著。この本は @indicateurl{https://mitpress.mit.edu/sicp} で見れます。この計算機科学の古典的な教科書では、2章と3章でシーケンスとストリームを使ってプログラム内のデータフローを整理する方法について説明しています。この本では例に Scheme を使っていますが、これらの章で説明されている設計アプローチの多くは、関数型スタイルの Python コードにも適用できます。

@indicateurl{https://defmacro.org/2006/06/19/fp.html}: A general introduction to functional
programming that uses Java examples and has a lengthy historical introduction.

@indicateurl{https://en.wikipedia.org/wiki/Functional_programming}: 関数プログラミングに関する一般的な内容の記事。

@indicateurl{https://en.wikipedia.org/wiki/Coroutine}: コルーチンに関する記事。

@indicateurl{https://en.wikipedia.org/wiki/Partial_application}: 関数の部分適用の概念についての記事。

@indicateurl{https://en.wikipedia.org/wiki/Currying}: カリー化の概念に関する記事。

@node Python 特有の話,Python 文書,一般論,参考資料<2>
@anchor{howto/functional python-specific}@anchor{573d}
@subsubsection Python 特有の話


@indicateurl{https://gnosis.cx/TPiP/}: David Mertz's の本の最初の章 @cite{Text Processing in Python} では文書処理のための関数プログラミングについて議論しています、この議論の節には "Utilizing Higher-Order Functions in Text Processing" というタイトルがついています。

Mertz は IBM の DeveloperWorks サイトにも関数型プログラミングに関する 3 部構成の記事を書いています; part 1@footnote{https://developer.ibm.com/articles/l-prog/}, part 2@footnote{https://developer.ibm.com/tutorials/l-prog2/}, part 3@footnote{https://developer.ibm.com/tutorials/l-prog3/},

@node Python 文書,,Python 特有の話,参考資料<2>
@anchor{howto/functional python-documentation}@anchor{573e}
@subsubsection Python 文書


@ref{85,,itertools} モジュールの文書。

@ref{63,,functools} モジュールについてのドキュメント。

@ref{a3,,operator} モジュールの文書。

@geindex Python Enhancement Proposals; PEP 289
PEP 289@footnote{https://peps.python.org/pep-0289/}: "Generator Expressions"

@geindex Python Enhancement Proposals; PEP 342
PEP 342@footnote{https://peps.python.org/pep-0342/}: "Coroutines via Enhanced Generators" describes the new generator
features in Python 2.5.

@c comment
@c 
@c Handy little function for printing part of an iterator -- used
@c while writing this document.
@c 
@c import itertools
@c def print_iter(it):
@c      slice = itertools.islice(it, 10)
@c      for elem in slice[:-1]:
@c          sys.stdout.write(str(elem))
@c          sys.stdout.write(', ')
@c     print(elem[-1])

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Logging HOWTO,Logging クックブック,関数型プログラミング HOWTO,Python HOWTO
@anchor{howto/logging doc}@anchor{573f}@anchor{howto/logging id1}@anchor{5740}@anchor{howto/logging logging-howto}@anchor{5741}@anchor{howto/logging translation-repo}@anchor{5742}
@section Logging HOWTO


@*著者: 
Vinay Sajip <vinay_sajip at red-dove dot com>

@anchor{howto/logging logging-basic-tutorial}@anchor{140e}
このページはチュートリアルです。レファレンスやロギングクックブックは、 @ref{5743,,その他のリソース} を参照してください。

@menu
* 基本 logging チュートリアル:: 
* 上級ロギングチュートリアル:: 
* ロギングレベル: ロギングレベル<2>. 
* 便利なハンドラ:: 
* ログ記録中に発生する例外:: 
* 任意のオブジェクトをメッセージに使用する:: 
* 最適化: 最適化<19>. 
* その他のリソース:: 

@end menu

@node 基本 logging チュートリアル,上級ロギングチュートリアル,,Logging HOWTO
@anchor{howto/logging basic-logging-tutorial}@anchor{5744}
@subsection 基本 logging チュートリアル


logging は、あるソフトウェアが実行されているときに起こったイベントを追跡するための手段です。ソフトウェアの開発者は、特定のイベントが発生したことを示す logging の呼び出しをコードに加えます。イベントは、メッセージで記述され、これに変数データ (すなわち、イベントが起こる度に異なるかもしれないデータ) を加えることもできます。イベントには、開発者がそのイベントに定めた重要性も含まれます。重要性は、`レベル (level)' や `重大度 (severity)' とも呼ばれます。

@menu
* logging を使うとき:: 
* 簡単な例: 簡単な例<2>. 
* ファイルへの logging:: 
* 変数データのロギング:: 
* 表示されるメッセージのフォーマットの変更:: 
* メッセージ内での日付と時刻の表示:: 
* 次のステップ:: 

@end menu

@node logging を使うとき,簡単な例<2>,,基本 logging チュートリアル
@anchor{howto/logging when-to-use-logging}@anchor{5745}
@subsubsection logging を使うとき


You can access logging functionality by creating a logger via @code{logger =
getLogger(__name__)}, and then calling the logger's @ref{102b,,debug()},
@ref{20dd,,info()}, @ref{1a74,,warning()}, @ref{315e,,error()} and
@ref{102a,,critical()} methods. To determine when to use logging, and to see
which logger methods to use when, see the table below. It states, for each of a
set of common tasks, the best tool to use for that task.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

行いたいタスク

@tab

そのタスクに最適なツール

@item

コマンドラインスクリプトやプログラムで普通に使う、コンソール出力の表示

@tab

@ref{1177,,print()}

@item

プログラムの通常の操作中に発生したイベントの報告 (例えば、状態の監視や障害の分析)

@tab

A logger's @ref{20dd,,info()} (or
@ref{102b,,debug()} method for very
detailed output for diagnostic
purposes)

@item

特定のランタイムイベントに関わる警告の発行

@tab

その発行が避けられるもので、クライアントアプリケーションを修正してその警告を排除するべきなら @ref{1732,,warnings.warn()}

A logger's @ref{1a74,,warning()}
method if there is nothing the client
application can do about the
situation, but the event should still
be noted

@item

特定のランタイムイベントに関わるエラーの報告

@tab

例外の送出

@item

例外の送出をしないエラーの抑制 (例えば、長期のサーバプロセス中のエラーハンドラ)

@tab

A logger's @ref{315e,,error()},
@ref{1029,,exception()} or
@ref{102a,,critical()} method as
appropriate for the specific error
and application domain

@end multitable


The logger methods are named after the level or severity of the events
they are used to track. The standard levels and their applicability are
described below (in increasing order of severity):


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

レベル

@tab

いつ使うか

@item

@code{DEBUG}

@tab

おもに問題を診断するときにのみ関心があるような、詳細な情報。

@item

@code{INFO}

@tab

想定された通りのことが起こったことの確認。

@item

@code{WARNING}

@tab

想定外のことが起こった、または問題が近く起こりそうである (例えば、'disk space low') ことの表示。

@item

@code{ERROR}

@tab

より重大な問題により、ソフトウェアがある機能を実行できないこと。

@item

@code{CRITICAL}

@tab

プログラム自体が実行を続けられないことを表す、重大なエラー。

@end multitable


The default level is @code{WARNING}, which means that only events of this severity and higher
will be tracked, unless the logging package is configured to do otherwise.

追跡されるイベントは、異なる方法で処理されます。追跡されたイベントを処理する最も単純な方法は、それをコンソールに表示することです。その他のよくある方法は、それをディスクファイルに書き出すことです。

@node 簡単な例<2>,ファイルへの logging,logging を使うとき,基本 logging チュートリアル
@anchor{howto/logging a-simple-example}@anchor{5746}@anchor{howto/logging howto-minimal-example}@anchor{5747}
@subsubsection 簡単な例


ごく簡単な例は:

@example
import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything
@end example

これらの行をスクリプトにタイプして実行すると、次のようにコンソールに出力されます:

@example
WARNING:root:Watch out!
@end example

printed out on the console. The @code{INFO} message doesn't appear because the
default level is @code{WARNING}. The printed message includes the indication of the
level and the description of the event provided in the logging call, i.e.
'Watch out!'. The actual output can be formatted quite flexibly if you need
that; formatting options will also be explained later.

Notice that in this example, we use functions directly on the @code{logging}
module, like @code{logging.debug}, rather than creating a logger and calling
functions on it. These functions operate on the root logger, but can be useful
as they will call @ref{bf3,,basicConfig()} for you if it has not been called yet, like in
this example.  In larger programs you'll usually want to control the logging
configuration explicitly however - so for that reason as well as others, it's
better to create loggers and call their methods.

@node ファイルへの logging,変数データのロギング,簡単な例<2>,基本 logging チュートリアル
@anchor{howto/logging logging-to-a-file}@anchor{5748}
@subsubsection ファイルへの logging


logging イベントをファイルに記録するのは非常によくあるパターンなので次はこれを見て行きましょう。以下のサンプルを試すときは Python インタプリタを新しく起動して、上のセッションの続きにならないようにしてください:

@example
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logger.debug('This message should go to the log file')
logger.info('So should this')
logger.warning('And this, too')
logger.error('And non-ASCII stuff, too, like Øresund and Malmö')
@end example


バージョン 3.9 で変更: `encoding' 引数が追加されました。以前のバージョンの Python では、あるいは指定されなかったら、エンコーディングには @ref{316,,open()} が使うデフォルト値が使われます。上の例に出てきていませんが、同じく渡せるようになった `errors' 引数は、エンコーディングエラーの扱いを決定します。利用可能な値およびデフォルト値については、 @ref{316,,open()} のドキュメントを参照してください。


そして、ファイルの中身を確認すると、ログメッセージが確認できます:

@example
DEBUG:__main__:This message should go to the log file
INFO:__main__:So should this
WARNING:__main__:And this, too
ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö
@end example

この例はまた、追跡のしきい値となるロギングレベルを設定する方法も示しています。この例では、しきい値を @code{DEBUG} に設定しているので、全てのメッセージが表示されています。

次のようなコマンドラインオプションでログレベルを設定したいと考え:

@example
--log=INFO
@end example

@code{--log} に渡されたパラメータの値を変数 `loglevel' に保存しているとしたら、

@example
getattr(logging, loglevel.upper())
@end example

というコードを使い、 @ref{bf3,,basicConfig()} の `level' 引数に渡すべき値が得られます。ユーザの入力値をすべてエラーチェックしたくなり、次の例のように実装することもあるでしょう:

@example
# assuming loglevel is bound to the string value obtained from the
# command line argument. Convert to upper case to allow the user to
# specify --log=DEBUG or --log=debug
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
    raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, ...)
@end example

The call to @ref{bf3,,basicConfig()} should come `before' any calls to a logger's
methods such as @ref{102b,,debug()}, @ref{20dd,,info()}, etc. Otherwise,
that logging event may not be handled in the desired manner.

上記のスクリプトを複数回実行すると、2 回目以降の実行によるメッセージは `example.log' に加えられます。以前の実行によるメッセージを記憶せず、実行ごとに新たに始めたいなら、上記の例での呼び出しを次のように変え、`filemode' 引数を指定する方法がとれます:

@example
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
@end example

出力は先ほどと同じになりますが、ログファイルは追記されなくなり、以前の実行によるメッセージは失われます。

@node 変数データのロギング,表示されるメッセージのフォーマットの変更,ファイルへの logging,基本 logging チュートリアル
@anchor{howto/logging logging-variable-data}@anchor{5749}
@subsubsection 変数データのロギング


変数データのログを取るには、イベント記述メッセージにフォーマット文字列を使い、引数に変数データを加えてください。例えば:

@example
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
@end example

により、次のように表示されます:

@example
WARNING:root:Look before you leap!
@end example

ご覧の通り、イベント記述メッセージに変数データを統合するために、古い、% スタイルの文字列フォーマットを使っています。これは後方互換性のためです。logging パッケージは、 @ref{833,,str.format()} や @ref{897,,string.Template} のような新しいフォーマットオプションよりも先に生まれました。新しいフォーマットオプションはサポートされて `います' が、その探求はこのチュートリアルでは対象としません。詳細は @ref{317b,,固有の書式化スタイルをアプリケーション全体で使う} を参照してください。

@node 表示されるメッセージのフォーマットの変更,メッセージ内での日付と時刻の表示,変数データのロギング,基本 logging チュートリアル
@anchor{howto/logging changing-the-format-of-displayed-messages}@anchor{574a}
@subsubsection 表示されるメッセージのフォーマットの変更


メッセージを表示するのに使われるフォーマットを変更するには、使いたいフォーマットを指定する必要があります:

@example
import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
@end example

により、次のように表示されます:

@example
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too
@end example

ご覧の通り、先の例に現れた 'root' が消失しています。フォーマット文字列に含めることができるものの一覧は、 @ref{315c,,LogRecord 属性} のドキュメントから参照できますが、単純な用途では、必要なものは `levelname' (重大度)、 `message' (変数データを含むイベント記述)、それともしかしたら、イベントがいつ起こったかという表示だけです。これは次の節で解説します。

@node メッセージ内での日付と時刻の表示,次のステップ,表示されるメッセージのフォーマットの変更,基本 logging チュートリアル
@anchor{howto/logging displaying-the-date-time-in-messages}@anchor{574b}
@subsubsection メッセージ内での日付と時刻の表示


イベントの日付と時刻を表示するには、フォーマット文字列に '%(asctime)s' を置いてください:

@example
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')
@end example

これは以下の様なフォーマットで表示されます:

@example
2010-12-12 11:41:42,612 is when this event was logged.
@end example

デフォルトの日付と時間の表示フォーマット （上記の結果） は、ISO8601 や 
@geindex RFC; RFC 3339
RFC 3339@footnote{https://datatracker.ietf.org/doc/html/rfc3339.html} に似ています。日付と時間のフォーマットをより詳細に制御する必要があるなら、以下の例の様に、 @code{basicConfig} に `datefmt' 引数を指定してください:

@example
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
@end example

これは次のように表示されます:

@example
12/12/2010 11:46:36 AM is when this event was logged.
@end example

`datefmt' 引数のフォーマットは、 @ref{1402,,time.strftime()} でサポートされているものと同じです。

@node 次のステップ,,メッセージ内での日付と時刻の表示,基本 logging チュートリアル
@anchor{howto/logging next-steps}@anchor{574c}
@subsubsection 次のステップ


基本チュートリアルはこれで終わりです。あなたがロギングを使っていくためには、これで十分でしょう。logging パッケージが提供するものはもっとありますが、それを使いこなすためには、もうちょっと時間をかけて、以下のセクションを読む必要があります。その用意ができたら、好きな飲み物を持って、次に進みましょう。

If your logging needs are simple, then use the above examples to incorporate
logging into your own scripts, and if you run into problems or don't understand
something, please post a question in the Help category of the Python discussion forum@footnote{https://discuss.python.org/c/help/7} and you should receive
help before too long.

まだいますか？もう少し上級の、踏み込んだチュートリアルを綴った、幾つかの節を読み続けることができます。その後で、 @ref{1410,,Logging クックブック} もご覧ください。

@node 上級ロギングチュートリアル,ロギングレベル<2>,基本 logging チュートリアル,Logging HOWTO
@anchor{howto/logging advanced-logging-tutorial}@anchor{574d}@anchor{howto/logging logging-advanced-tutorial}@anchor{140f}
@subsection 上級ロギングチュートリアル


logging ライブラリはモジュール方式のアプローチを取り、いくつかのカテゴリの部品を提供します。ロガー、ハンドラ、フィルタ、フォーマッタです。


@itemize *

@item 
ロガーは、アプリケーションコードが直接使うインターフェースを公開します。

@item 
ハンドラは、(ロガーによって生成された) ログ記録を適切な送信先に送ります。

@item 
フィルタは、どのログ記録を出力するかを決定する、きめ細かい機能を提供します。

@item 
フォーマッタは、ログ記録が最終的に出力されるレイアウトを指定します。
@end itemize

ログイベント情報は @ref{11e8,,LogRecord} インスタンスの形で、 logger, handler, filter, formatter の間でやりとりされます。

ロギングは、 @ref{d46,,Logger} クラスのインスタンス (以下 `ロガー') にメソッドを呼び出すことで実行されます。各インスタンスには名前があり、名前空間階層構造に、ドット (ピリオド) をセパレータとして、概念的に並べられています。例えば、 'scan' という名前のロガーは、ロガー 'scan.text', 'scan.html' および 'scan.pdf'の親です。ロガー名は、何でも望むものにでき、ロギングされたメッセージが発生した場所を指し示します。

ロガーに名前をつけるときの良い習慣は、ロギングを使う各モジュールに、以下のように名付けられた、モジュールレベルロガーを使うことです:

@example
logger = logging.getLogger(__name__)
@end example

これにより、ロガー名はパッケージ/モジュール階層をなぞり、ロガー名だけで、どこでイベントのログが取られたか、直感的に明らかになります。

ロガーの階層構造の根源は、ルートロガーと呼ばれます。それが、関数 @ref{315d,,debug()}, @ref{3186,,info()}, @ref{354,,warning()}, @ref{319a,,error()} および @ref{319b,,critical()} によって使われるロガーとなります。これらの関数は単に、ルートロガーの同名のメソッドを呼び出します。これらの関数とメソッドは、同じ署名をもっています。ルートロガーの名前は、ログ出力では 'root' と表示されます。

もちろん、メッセージを異なる送信先に記録することも出来ます。このパッケージでは、ファイルへ、 HTTP GET/POST 先へ、 SMTP 経由で電子メールへ、汎用のソケットへ、キューへ、または Windows NT イベントログのような OS 毎のログ記録機構への、ログメッセージの書きこみがサポートされています。送信先は、 `handler' クラスによって取り扱われます。組み込みのハンドラクラスでは満たせないような、特殊な要件があるなら、独自のログ送信先を生成できます。

デフォルトでは、どのロギングメッセージに対しても、送信先は設定されていません。チュートリアルの例のように、 @ref{bf3,,basicConfig()} を使って、送信先 (コンソールやファイルなど) を指定できます。関数 @ref{315d,,debug()}, @ref{3186,,info()}, @ref{354,,warning()}, @ref{319a,,error()} および @ref{319b,,critical()} を呼び出すと、それらは送信先が設定されていないかを調べます。そして設定されていなければ、ルートロガーに委譲して実際にメッセージを出力する前に、コンソール (@code{sys.stderr}) を送信先に、デフォルトのフォーマットを表示されるメッセージに設定します。

@ref{bf3,,basicConfig()} が設定するデフォルトのメッセージのフォーマットは次のようになります:

@example
severity:logger name:message
@end example

@ref{bf3,,basicConfig()} の `format' キーワード引数にフォーマット文字列を渡すことで、これを変更できます。フォーマット文字列を構成するためのすべてのオプションは、 @ref{3178,,フォーマッタオブジェクト} を参照してください。

@menu
* Logging Flow:: 
* ロガー:: 
* ハンドラ:: 
* フォーマッタ:: 
* ロギングの環境設定:: 
* 環境設定が与えられないとどうなるか:: 
* ライブラリのためのロギングの設定:: 

@end menu

@node Logging Flow,ロガー,,上級ロギングチュートリアル
@anchor{howto/logging logging-flow}@anchor{574e}
@subsubsection Logging Flow


次の図はログイベントが logger と handler をどう流れるかを示しています。

@image{python-figures/logging_flow,,,,png}

@node ロガー,ハンドラ,Logging Flow,上級ロギングチュートリアル
@anchor{howto/logging loggers}@anchor{574f}
@subsubsection ロガー


@ref{d46,,Logger} オブジェクトの仕事は大きく三つに分かれます。一つ目は、アプリケーションが実行中にメッセージを記録できるように、いくつかのメソッドをアプリケーションから呼べるようにしています。二つ目に、ロガーオブジェクトはどのメッセージに対して作用するかを、深刻度 (デフォルトのフィルタ機構) またはフィルタオブジェクトに基づいて決定します。三つ目に、ロガーオブジェクトは関心を持っているすべてのログハンドラに関連するログメッセージを回送します。

とりわけ広く使われるロガーオブジェクトのメソッドは、二つのカテゴリーに分類できます: 設定とメッセージ送信です。

これらが設定メソッドの中でよく使われます:


@itemize *

@item 
@ref{16ac,,Logger.setLevel()} はロガーが扱うログメッセージの最も低い深刻度を指定します。組み込みの深刻度の中では DEBUG が一番低く、 CRITICAL が一番高くなります。たとえば、深刻度が INFO と設定されたロガーは INFO, WARNING, ERROR, CRITICAL のメッセージしか扱わず、 DEBUG メッセージは無視します。

@item 
@ref{3157,,Logger.addHandler()} と @ref{3158,,Logger.removeHandler()} は、ハンドラオブジェクトをロガーオブジェクトから追加または削除します。ハンドラについては、 @ref{5750,,ハンドラ} で詳しく述べます。

@item 
@ref{315f,,Logger.addFilter()} と @ref{3160,,Logger.removeFilter()} はロガーオブジェクトにフィルタオブジェクトを追加または削除します。フィルタについては、 @ref{3183,,フィルタオブジェクト} で詳しく述べます。
@end itemize

これらのメソッドを、生成したすべてのロガーに毎回呼び出さなければならないわけではありません。この節の最後の 2 段落を参照してください。

ロガーオブジェクトが設定されれば、以下のメソッドがログメッセージを生成します:


@itemize *

@item 
@ref{102b,,Logger.debug()}, @ref{20dd,,Logger.info()}, @ref{1a74,,Logger.warning()}, @ref{315e,,Logger.error()}, @ref{102a,,Logger.critical()} はすべて、メッセージとメソッド名に対応したレベルでログ記録を作り出します。メッセージは実際にはフォーマット文字列であり、通常の文字列代入に使う @code{%s}, @code{%d}, @code{%f} などを含むことができます。残りの引数はメッセージの代入される位置に対応するオブジェクトのリストです。 @code{**kwargs} については、ログ記録メソッドが気にするキーワードは @code{exc_info} だけで、例外の情報をログに記録するかを決定するのに使います。

@item 
@ref{1029,,Logger.exception()} は @ref{315e,,Logger.error()} と似たログメッセージを作成します。違いは @ref{1029,,Logger.exception()} がスタックトレースを一緒にダンプすることです。このメソッドは例外ハンドラからだけ呼び出すようにしてください。

@item 
@ref{1028,,Logger.log()} はログレベルを明示的な引数として受け取ります。これは上に挙げた便宜的なログレベル毎のメソッドを使うより少しコード量が多くなりますが、独自のログレベルを使うことができます。
@end itemize

@ref{b59,,getLogger()} は、指定されればその特定の名前の、そうでなければ @code{root} のロガーインスタンスへの参照を返します。ロガーの名前はピリオド区切りの階層構造を表します。同じ名前で @ref{b59,,getLogger()} を複数回呼び出した場合、同一のロガーオブジェクトへの参照が返されます。階層リストを下ったロガーはリスト上位のロガーの子です。たとえば、名前が @code{foo} であるロガーがあったとして、 @code{foo.bar}, @code{foo.bar.baz}, @code{foo.bam} といった名前のロガーはすべて @code{foo} の子孫になります。

ロガーには、`有効レベル (effective level)' の概念があります。ロガーにレベルが明示的に設定されていなければ、代わりに親のレベルがその有効レベルとして使われます。親のレベルが設定されなければ、`その' 親のレベルが確かめられ、明示的に設定されたレベルが見つかるまで祖先が探されます。ルートロガーは、必ず明示的なレベルが設定されています (デフォルトでは @code{WARNING} です)。イベントを処理するかを決定するとき、ロガーの有効レベルを使って、イベントがロガーのハンドラに渡されるかが決められます。

子ロガーはメッセージを親ロガーのハンドラに伝えます。このため、アプリケーションが使っているすべてのロガーのためのハンドラを定義して設定する必要はありません。トップレベルのロガーのためのハンドラだけ設定しておいて必要に応じて子ロガーを作成すれば十分です。(しかし、ロガーの `propagate' 属性を @code{False} に設定することで、伝播を抑制できます。)

@node ハンドラ,フォーマッタ,ロガー,上級ロギングチュートリアル
@anchor{howto/logging handler-basic}@anchor{5750}@anchor{howto/logging handlers}@anchor{5751}
@subsubsection ハンドラ


@ref{16af,,Handler} オブジェクトは適切なログメッセージを (ログメッセージの深刻度に基づいて) ハンドラの指定された出力先に振り分けることに責任を持ちます。 @ref{d46,,Logger} オブジェクトには @ref{3157,,addHandler()} メソッドで 0 個以上のハンドラを追加することができます。例として、あるアプリケーションがすべてのログメッセージをログファイルに、 error 以上のすべてのログメッセージを標準出力に、 critical のメッセージはすべてメールアドレスに、それぞれ送りたいとします。この場合、 3 つの個別のハンドラがそれぞれの深刻度と宛先に応じて必要になります。

このライブラリには多くのハンドラが用意されています (@ref{5752,,便利なハンドラ} を参照してください) が、このチュートリアルでは @ref{1411,,StreamHandler} と @ref{1c53,,FileHandler} だけを例に取り上げます。

アプリケーション開発者にとってハンドラを扱う上で気にするべきメソッドは極々限られています。組み込みのハンドラオブジェクトを使う (つまり自作ハンドラを作らない) 開発者に関係あるハンドラのメソッドは、次の設定用のメソッドだけでしょう:


@itemize *

@item 
@ref{316d,,setLevel()} メソッドは、ロガーオブジェクトの場合と同様に、適切な出力先に振り分けられるべき最も低い深刻度を指定します。なぜ 2 つも @ref{316d,,setLevel()} メソッドがあるのでしょうか? ロガーで設定されるレベルは、付随するハンドラにどんな深刻度のメッセージを渡すか決めます。それぞれのハンドラで設定されるレベルは、そのハンドラがどのメッセージを転送するべきか決めます。

@item 
@ref{316e,,setFormatter()} でこのハンドラが使用する Formatter オブジェクトを選択します。

@item 
@ref{316f,,addFilter()} および @ref{3170,,removeFilter()} はそれぞれハンドラへのフィルタオブジェクトの設定と解除を行います。
@end itemize

アプリケーションのコード中では @ref{16af,,Handler} のインスタンスを直接インスタンス化して使ってはなりません。代わりに、 @ref{16af,,Handler} クラスはすべてのハンドラが持つべきインターフェイスを定義する基底クラスであり、子クラスが使える (もしくはオーバライドできる) いくつかのデフォルトの振る舞いを規定します。

@node フォーマッタ,ロギングの環境設定,ハンドラ,上級ロギングチュートリアル
@anchor{howto/logging formatters}@anchor{5753}
@subsubsection フォーマッタ


フォーマッタオブジェクトは最終的なログメッセージの順序、構造および内容を設定します。基底クラスである @ref{16af,,logging.Handler} とは違って、アプリケーションのコードはフォーマッタクラスをインスタンス化しても構いません。特別な振る舞いをさせたいアプリケーションではフォーマッタのサブクラスを使う可能性もあります。コンストラクタは三つのオプション引数を取ります -- メッセージのフォーマット文字列、日付のフォーマット文字列、スタイル標識です。

@geindex __init__() (logging.logging.Formatter のメソッド)
@anchor{howto/logging logging logging Formatter __init__}@anchor{5754}
@deffn {メソッド} logging.Formatter.__init__ (fmt=None, datefmt=None, style='%')
@end deffn

フォーマット文字列に何も渡さない場合は、デフォルトで行メッセージが利用されます。また、日付フォーマットに何も渡さない場合は、デフォルトで以下のフォーマットが利用されます:

@example
%Y-%m-%d %H:%M:%S
@end example

時刻の末尾にはミリ秒が付きます。 @code{style} は @code{'%'}, @code{'@{'}, または @code{'@{TX-PL-LABEL@}#x27;} のいずれかです。特に指定がなければ @code{'%'} が使われます。

@code{style} が @code{'%'} の場合、メッセージフォーマット文字列では @code{%(<dictionary key>)s} 形式の置換文字列が使われます; キーに指定できる属性名は @ref{315c,,LogRecord 属性} に文書化されています。 style が @code{'@{'} の場合、メッセージフォーマット文字列は (キーワード引数を使う) @ref{833,,str.format()} と互換となります。 style が @code{'$'} の場合、メッセージフォーマット文字列は @ref{20d5,,string.Template.substitute()} で期待されているものと一致します。


バージョン 3.2 で変更: @code{style} パラメータが追加されました。


次のメッセージフォーマット文字列は、人が読みやすい形式の時刻、メッセージの深刻度、およびメッセージの内容を、順番に出力します:

@example
'%(asctime)s - %(levelname)s - %(message)s'
@end example

フォーマッタは、ユーザが設定できる関数を使って、生成時刻をタプルに記録します。デフォルトでは、 @ref{1712,,time.localtime()} が使われます。特定のフォーマッタインスタンスに対してこれを変更するには、インスタンスの @code{converter} 属性を @ref{1712,,time.localtime()} や @ref{13d8,,time.gmtime()} と同じ署名をもつ関数に設定してください。すべてのフォーマッタインスタンスに対してこれを変更するには、例えば全てのロギング時刻を GMT で表示するには、フォーマッタクラスの @code{converter} 属性を (GMT 表示の @code{time.gmtime} に) 設定してください。

@node ロギングの環境設定,環境設定が与えられないとどうなるか,フォーマッタ,上級ロギングチュートリアル
@anchor{howto/logging configuring-logging}@anchor{5755}
@subsubsection ロギングの環境設定


プログラマは、ロギングを 3 種類の方法で設定できます:


@enumerate 

@item 
上述の設定メソッドを呼び出す Python コードを明示的に使って、ロガー、ハンドラ、そしてフォーマッタを生成する。

@item 
ロギング設定ファイルを作り、それを @ref{d48,,fileConfig()} 関数を使って読み込む。

@item 
設定情報の辞書を作り、それを @ref{13c8,,dictConfig()} 関数に渡す。
@end enumerate

最後の2つの選択肢については、 @ref{1509,,環境設定のための関数} で解説しています。以下の例では、Python コードを使って、とても簡単なロガー、コンソールハンドラ、そして簡単なフォーマッタを設定しています:

@example
import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
@end example

このモジュールを実行すると、コマンドラインによって以下の出力がなされます:

@example
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
@end example

以下の Python モジュールは、ロガー、ハンドラ、フォーマッタをほとんど上述の例と同じように生成していますが、オブジェクト名だけが異なります:

@example
import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
@end example

これが logging.conf ファイルです:

@example
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
@end example

出力は、設定ファイルに基づく例とだいたい同じです:

@example
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
@end example

この通り、設定ファイルの方法は、主に設定とコードが分かれ、非コーダがロギングプロパティを変えやすくなるという点で、Python コードの方法より少し優れています。

@cartouche
@quotation 警告 
@ref{d48,,fileConfig()} 関数はデフォルト引数 @code{disable_existing_loggers} を取り、後方互換性のためにデフォルト値は @code{True} になっています。
これはあなたの望むものかもしれませんし、そうでないかもしれません。というのは、設定で明示的に指定したクラス (もしくはその親クラス) を除いて、 @ref{d48,,fileConfig()} が呼び出される前に存在した非ルートロガーを無効化してしまうからです。
より詳細なことはリファレンスを参照し、望むならこの引数に @code{False} を指定してください。

@ref{13c8,,dictConfig()} に渡される辞書でも、キー @code{disable_existing_loggers} で真偽値を指定することができ、辞書の中で明示的に指定しなかった場合はデフォルトで @code{True} と解釈されます。これは上で説明したロガー無効化につながりますが、それを望まないこともあるでしょう - その場合は、明示的にキーを与えて値を @code{False} にしてください。
@end quotation
@end cartouche

なお、設定ファイルで参照されるクラス名は、logging モジュールに対して相対であるか、通常のインポート機構を使って解決される絶対である値でなければなりません。従って、(logging モジュールに相対な) @ref{31da,,WatchedFileHandler} または (Python インポートパスとして @code{mypackage} が使えるとき、パッケージ @code{mypackage} のモジュール @code{mymodule} で定義されたクラスに) @code{mypackage.mymodule.MyHandler} のどちらかが使えます。

Python 3.2 では、ロギングを設定するのに新しく、辞書に設定情報を持たせる手段が導入されました。これは、上で概説した設定ファイルに基づく方法による機能の上位版を提供し、新しいアプリケーションやデプロイにはこのメソッドが推奨されます。Python の辞書を使って設定情報を保持し、辞書は他の用途にも使えるので、設定の選択肢が広がります。例えば、JSON フォーマットの設定ファイルや、YAML 処理機能が使えれば YAML フォーマットのファイルを使って、設定辞書を構成できます。また、もちろん、Python コードで辞書を構成し、ソケットを通して pickle 化された形式を受け取るなど、アプリケーションで意味があるいかなるやり方でも使えます。

以下は、上記と同じ設定を辞書ベースの新しい手法で記載した YAML 形式の例です:

@example
version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  simpleExample:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console]
@end example

辞書を使ったロギングについて詳細は、 @ref{1509,,環境設定のための関数} を参照してください。

@node 環境設定が与えられないとどうなるか,ライブラリのためのロギングの設定,ロギングの環境設定,上級ロギングチュートリアル
@anchor{howto/logging what-happens-if-no-configuration-is-provided}@anchor{5756}
@subsubsection 環境設定が与えられないとどうなるか


ロギング環境設定を与えられないと、ロギングイベントを出力しなければならないのに、イベントを出力するハンドラが見つからないことがあります。

イベントは、 @ref{1413,,lastResort} に格納された「最終手段ハンドラ」を使用して出力されます。この内部的なハンドラはどんなロガーにも関係しておらず、イベント記述メッセージを現在の @code{sys.stderr} に書く @ref{1411,,StreamHandler} のように動作します (したがって、あらゆるリダイレクトの効果が反映されます)。メッセージに対してフォーマットは行われません。イベント記述メッセージだけがそのまま表示されます。ハンドラのレベルは @code{WARNING} にセットされ、重大度がこれ以上のすべてのイベントが出力されます。


バージョン 3.2 で変更: Python 3.2 より前のバージョンでは、振る舞いは以下の通りです:


@itemize *

@item 
@ref{1412,,raiseExceptions} が @code{False} (製品モード) なら、イベントは黙って捨てられます。

@item 
@ref{1412,,raiseExceptions} が @code{True} (開発モード) なら、メッセージ 'No handlers could be found for logger X.Y.Z' が一度表示されます。
@end itemize

3.2 より前の動作にするために、@ref{1413,,lastResort} を @code{None} に設定することもできます。


@node ライブラリのためのロギングの設定,,環境設定が与えられないとどうなるか,上級ロギングチュートリアル
@anchor{howto/logging configuring-logging-for-a-library}@anchor{5757}@anchor{howto/logging library-config}@anchor{31d7}
@subsubsection ライブラリのためのロギングの設定


ロギングを使うライブラリを開発するときは、ライブラリがどのようにロギングを使うのか、例えば使われているロガーの名前などを、ドキュメントにしておくべきです。ロギングの設定については、いくつか考えておくべきこともあります。使っているアプリケーションがロギングを使っていなくて、ライブラリコードがロギングを呼び出すと、(前の節で解説したように) 重大度 @code{WARNING} 以上のイベントが、@code{sys.stderr} に表示されます。これが最高のデフォルトの振る舞いと見なされます。

何らかの理由でロギング設定がなされていないときにメッセージを表示 `させたくない' のであれば、ライブラリのトップレベルのロガーに何もしないハンドラを取り付けられます。ライブラリの全てのイベントに対してそのハンドラが見つかるので、メッセージが表示されなくなります。ライブラリのユーザーがアプリケーションのためにロギングを設定する場合、おそらくハンドラが追加され、そしてレベルが適切に設定された場合に、ライブラリコード内でのロギングの呼び出しは通常通りそのハンドラに出力を送るようになります。

何もしないハンドラ @ref{149c,,NullHandler} (Python 3.1 以降) は、 logging パッケージに含まれます。このハンドラのインスタンスを、 (ロギング設定がなされていないときにライブラリのログイベントを @code{sys.stderr} に出力させたく `ないなら') ライブラリの名前空間で使われるトップレベルロガーに取り付けられます。ライブラリ `foo' によるすべてのロギングが、 'foo.x', 'foo.x.y' その他に該当する名前のロガーによってなされるなら:

@example
import logging
logging.getLogger('foo').addHandler(logging.NullHandler())
@end example

とすれば望んだ効果が得られるでしょう。組織が複数のライブラリを作り出すなら、指定されるロガー名は単に 'foo' ではなく、'orgname.foo' になります。

@cartouche
@quotation 注釈 
あなたのライブラリから `ルートロガーへ直接ログを記録しない' ことを強く推奨します。代わりに、あなたのライブラリのトップレベルまたはモジュールレベルの @code{__name__} を使うなど、固有で、簡単に識別できる名前を持ったロガーを使ってください。ルートロガーに直接ログを記録することにより、あなたのライブラリを利用するアプリケーション開発者が、ロギングの詳細度 (verbosity) やハンドラを望みのとおりに設定することを困難にしたり、不可能にしてしまいます。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
`ライブラリのロガーには、' @ref{149c,,NullHandler} `以外のハンドラを追加しない' ことを強く推奨します。これは、ハンドラの設定が、あなたのライブラリを使うアプリケーション開発者にも伝播するからです。アプリケーション開発者は、対象となる聴衆と、そのアプリケーションにどのハンドラが最も適しているかを知っています。ハンドラを 'ボンネットの中で' 加えてしまうと、ユニットテストをして必要に応じたログを送達する能力に干渉しかねません。
@end quotation
@end cartouche

@node ロギングレベル<2>,便利なハンドラ,上級ロギングチュートリアル,Logging HOWTO
@anchor{howto/logging logging-levels}@anchor{5758}
@subsection ロギングレベル


ログレベルの数値は以下の表のように与えられています。これらは基本的に自分でレベルを定義したい人のためのもので、定義するレベルを既存のレベルの間に位置づけるためには具体的な値が必要になります。もし数値が他のレベルと同じだったら、既存の値は上書きされその名前は失われます。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

レベル

@tab

数値

@item

@code{CRITICAL}

@tab

50

@item

@code{ERROR}

@tab

40

@item

@code{WARNING}

@tab

30

@item

@code{INFO}

@tab

20

@item

@code{DEBUG}

@tab

10

@item

@code{NOTSET}

@tab

0

@end multitable


レベルはロガーに関連付けることもでき、開発者が設定することも、保存されたログ記録設定を読み込む際に設定することもできます。ロガーに対してログ記録メソッドが呼び出されると、ロガーは自らのレベルとメソッド呼び出しに関連付けられたレベルを比較します。ロガーのレベルがメソッド呼び出しのレベルよりも高い場合、実際のログメッセージは生成されません。これはログ出力の冗長性を制御するための基本的なメカニズムです。

ログ記録されるメッセージは @ref{11e8,,LogRecord} クラスのインスタンスとしてエンコードされます。ロガーがあるイベントを実際にログ出力すると決定した場合、ログメッセージから @ref{11e8,,LogRecord} インスタンスが生成されます。

ログ記録されるメッセージは、ハンドラ (`handlers') を通してディスパッチ機構にかけられます。ハンドラは @ref{16af,,Handler} クラスのサブクラスのインスタンスで、ログ記録された (@ref{11e8,,LogRecord} 形式の) メッセージが、そのメッセージの伝達対象となる相手 (エンドユーザ、サポートデスクのスタッフ、システム管理者、開発者) に行き着くようにする役割を持ちます。ハンドラには特定の出力先を意図された @ref{11e8,,LogRecord} インスタンスが渡されます。各ロガーは 0 個以上のハンドラを (@ref{d46,,Logger} の @ref{3157,,addHandler()} メソッド) で関連付けることができます。ロガーに直接関連付けられたハンドラに加えて、`ロガーの上位にあるロガーすべてに関連付けられたハンドラ' がメッセージを処理する際に呼び出されます (ただしロガーの `propagate' フラグが false 値にセットされている場合を除きます。その場合は、祖先ハンドラへの伝搬はそこで止まります)。

ロガーと同様に、ハンドラは関連付けられたレベルを持つことができます。ハンドラのレベルはロガーのレベルと同じ方法で、フィルタとして働きます。ハンドラがあるイベントを実際に処理すると決定した場合、 @ref{3176,,emit()} メソッドが使われ、メッセージを出力先に送信します。ほとんどのユーザ定義の @ref{16af,,Handler} のサブクラスで、この @ref{3176,,emit()} をオーバライドする必要があるでしょう。

@menu
* カスタムレベル:: 

@end menu

@node カスタムレベル,,,ロギングレベル<2>
@anchor{howto/logging custom-levels}@anchor{319f}@anchor{howto/logging id2}@anchor{5759}
@subsubsection カスタムレベル


独自のレベルを定義することは可能ですが、必須ではなく、実経験上は既存のレベルが選ばれます。しかし、カスタムレベルが必要だと確信するなら、レベルの定義には多大な注意を払うべきで、`ライブラリの開発の際、カスタムレベルを定義することはとても悪いアイデア' になり得ます。これは、複数のライブラリの作者がみな独自のカスタムレベルを定義すると、与えられた数値が異なるライブラリで異なる意味になりえるため、開発者がこれを制御または解釈するのが難しくなるからです。

@node 便利なハンドラ,ログ記録中に発生する例外,ロギングレベル<2>,Logging HOWTO
@anchor{howto/logging id3}@anchor{575a}@anchor{howto/logging useful-handlers}@anchor{5752}
@subsection 便利なハンドラ


基底の @ref{16af,,Handler} クラスに加え、多くの便利なサブクラスが提供されています:


@enumerate 

@item 
@ref{1411,,StreamHandler} インスタンスは、メッセージをストリーム (ファイル風オブジェクト) に送ります。

@item 
@ref{1c53,,FileHandler} インスタンスは、メッセージをディスクファイルに送ります。

@item 
@ref{31de,,BaseRotatingHandler} は、ある地点でログファイルを循環させるハンドラの基底クラスです。これを直接インスタンス化することは意図されていません。代わりに、 @ref{1941,,RotatingFileHandler} や @ref{1163,,TimedRotatingFileHandler} を使用してください。

@item 
@ref{1941,,RotatingFileHandler} インスタンスは、メッセージをディスクファイルに送り、最大ログファイル数とログファイル循環をサポートします。

@item 
@ref{1163,,TimedRotatingFileHandler} インスタンスは、メッセージをディスクファイルに送り、ログファイルを特定時間のインターバルで循環します。

@item 
@ref{1164,,SocketHandler} インスタンスは、 TCP/IP ソケットにメッセージを送ります。バージョン3.4　から、 Unixドメインソケットもサポートされます。

@item 
@ref{1165,,DatagramHandler} インスタンスは UDP ソケットにメッセージを送ります。バージョン 3.4 から、Unix ドメインソケットもサポートされます。

@item 
@ref{18b2,,SMTPHandler} インスタンスは、メッセージを指示された email アドレスに送ります。

@item 
@ref{86c,,SysLogHandler} インスタンスは、メッセージを、必要ならばリモートマシンの、Unix syslog daemon に送ります。

@item 
@ref{3204,,NTEventLogHandler} インスタンスは、メッセージを Windows NT/2000/XP イベントログに送ります。

@item 
@ref{31bd,,MemoryHandler} インスタンスは、メッセージを、特定の基準が満たされる度に流される、メモリ中のバッファに送ります。

@item 
@ref{102c,,HTTPHandler} インスタンスは、メッセージを、 @code{GET} または @code{POST} セマンティクスを使って、HTTP サーバに送ります。

@item 
@ref{31da,,WatchedFileHandler} インスタンスは、ロギングする先のファイルを監視します。ファイルが変更されると、そのファイルは閉じられ、ファイル名を使って再び開かれます。このハンドラは Unix 系のシステムにのみ便利です。Windows は、使われている基の機構をサポートしていません。

@item 
@ref{1b61,,QueueHandler} インスタンスは、 @ref{bb,,queue} モジュールや @ref{98,,multiprocessing} モジュールなどで実装されているキューにメッセージを送ります。

@item 
@ref{149c,,NullHandler} インスタンスは、エラーメッセージについて何もしません。このクラスはライブラリ開発者が、 logging は使いたいが、ライブラリのユーザーが logging の設定をしなかったときに表示されうる 'No handlers could be found for logger `XXX'' のようなメッセージを回避したいときに使います。詳しくは、 @ref{31d7,,ライブラリのためのロギングの設定} を参照してください。
@end enumerate


Added in version 3.1: @ref{149c,,NullHandler} クラス。



Added in version 3.2: @ref{1b61,,QueueHandler} クラス。


コア logging パッケージで、 @ref{149c,,NullHandler}, @ref{1411,,StreamHandler} および @ref{1c53,,FileHandler} クラスが定義されています。その他のハンドラは、サブモジュールの @ref{8d,,logging.handlers} で定義されています。(環境設定機能のためのサブモジュール、 @ref{8c,,logging.config} もあります。)

ログメッセージは、 @ref{16b0,,Formatter} クラスのインスタンスを通してフォーマット化してから表示されます。このインスタンスは、 % 演算子と辞書で使うのに適切なフォーマット文字列で初期化されます。

複数のメッセージを一括してフォーマット化するには、 @ref{317f,,BufferingFormatter} が使えます。(一連の文字列のそれぞれに適用される) フォーマット文字列に加え、ヘッダとトレーラフォーマット文字列も提供されています。

ロガーレベルおよび/またはハンドラレベルに基づくフィルタリングで十分でなければ、 @ref{1414,,Filter} のインスタンスを @ref{d46,,Logger} と @ref{16af,,Handler} インスタンスの両方に (@ref{316f,,addFilter()} を通して) 加えることができます。メッセージの処理を続ける前に、ロガーもハンドラも、全てのフィルタに許可を求めます。フィルタのいずれかが偽値を返したら、メッセージの処理は続けられません。

基本の @ref{1414,,Filter} 機能では、特定のロガー名でのフィルタリングをできます。この機能が使われると、指名されたロガーに送られたメッセージとその子だけがフィルタを通り、その他は落とされます。

@node ログ記録中に発生する例外,任意のオブジェクトをメッセージに使用する,便利なハンドラ,Logging HOWTO
@anchor{howto/logging exceptions-raised-during-logging}@anchor{575b}@anchor{howto/logging logging-exceptions}@anchor{575c}
@subsection ログ記録中に発生する例外


logging パッケージは、ログを生成している間に起こる例外を飲み込むように設計されています。これは、ログ記録イベントを扱っている間に発生するエラー (ログ記録の設定ミス、ネットワークまたは他の同様のエラー) によってログ記録を使用するアプリケーションが早期に終了しないようにするためです。

@ref{f3c,,SystemExit} と @ref{bc5,,KeyboardInterrupt} 例外は決して飲み込まれません。 @ref{16af,,Handler} サブクラスの @ref{3176,,emit()} メソッドの間に起こる他の例外は、 @ref{3175,,handleError()} メソッドに渡されます。

@ref{16af,,Handler} の @ref{3175,,handleError()} のデフォルト実装は、モジュールレベル変数 @ref{1412,,raiseExceptions} が設定されているかどうかチェックします。設定されているなら、トレースバックが @ref{b33,,sys.stderr} に出力されます。設定されていないなら、例外は飲み込まれます。

@cartouche
@quotation 注釈 
@ref{1412,,raiseExceptions} のデフォルト値は @code{True} です。これは、開発の間に起こるどんな例外についても通常は通知してほしいからです。実運用環境では @ref{1412,,raiseExceptions} を @code{False} に設定することをお勧めします。
@end quotation
@end cartouche

@node 任意のオブジェクトをメッセージに使用する,最適化<19>,ログ記録中に発生する例外,Logging HOWTO
@anchor{howto/logging arbitrary-object-messages}@anchor{318b}@anchor{howto/logging using-arbitrary-objects-as-messages}@anchor{575d}
@subsection 任意のオブジェクトをメッセージに使用する


前の節とそこで挙げた例では、イベントを記録するときに渡されたメッセージが文字列であると仮定していました。しかし、これは唯一の可能性ではありません。メッセージとして任意のオブジェクトを渡すことができます。そして、ロギングシステムがそのオブジェクトを文字列表現に変換する必要があるとき、オブジェクトの @ref{830,,__str__()} メソッドが呼び出されます。実際、そうしたければ、文字列表現を計算することを完全に避けることができます - 例えば、 @ref{1164,,SocketHandler} は、イベントを pickle してネットワーク上で送信することでログ出力します。

@node 最適化<19>,その他のリソース,任意のオブジェクトをメッセージに使用する,Logging HOWTO
@anchor{howto/logging optimization}@anchor{575e}
@subsection 最適化


message 引数の整形は、必要になるまで延期されます。しかしながら、ログ記録メソッドに渡す引数を計算するだけでもコストがかかる場合があります。ロガーが単にイベントを捨てるなら、その計算を避けたいと考えるかもしれません。どうするかを決定するために @ref{150e,,isEnabledFor()} メソッドを呼ぶことができます。このメソッドは引数にレベルを取って、そのレベルの呼び出しに対して Logger がイベントを生成するなら true を返します。このようにコードを書くことができます:

@example
if logger.isEnabledFor(logging.DEBUG):
    logger.debug('Message with %s, %s', expensive_func1(),
                                        expensive_func2())
@end example

このようにすると、ロガーの閾値が @code{DEBUG} より上に設定されている場合、 @code{expensive_func1} と @code{expensive_func2} の呼び出しは行われません。

@cartouche
@quotation 注釈 
ある種のケースでは、 @ref{150e,,isEnabledFor()} それ自身があなたが期待するよりも高価になる場合があります(たとえば明示的なレベル指定がロガー階層の上位のみに設定されていて、ロガーが深くネストされているような場合です)。そのようなケース(あるいはタイトなループ内でメソッド呼び出しを避けたい場合)は、 @ref{150e,,isEnabledFor()} 結果をローカルにもしくはインスタンス変数としてキャッシュし、メソッドを毎回呼び出すかわりに使えば良いです。そのようなキャッシュ値は、(まったく一般的ではありませんが)ロギング設定がアプリケーション実行中に動的に変更された場合にのみ再計算が必要でしょう。
@end quotation
@end cartouche

これ以外にも、どんなログ情報が集められるかについてより正確なコントロールを必要とする、特定のアプリケーションでできる最適化があります。これは、ログ記録の間の不要な処理を避けるためにできることのリストです:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

不要な情報

@tab

それを避ける方法

@item

呼び出しがどこから行われたかに関する情報。

@tab

@code{logging._srcfile} を @code{None} にする。このことにより @ref{8f0,,sys._getframe()} 呼び出しを避けることが出来、PyPy のような環境(@ref{8f0,,sys._getframe()} の高速化が出来ない)において高速化の役に立ちます。

@item

スレッド情報。

@tab

@code{logging.logThreads} を @code{False} にする。

@item

現在のプロセスID(@ref{3001,,os.getpid()})

@tab

@code{logging.logProcesses} を @code{False} にする。

@item

マルチプロセスの制御に @code{multiprocessing} を使っているときの、現在のプロセス名

@tab

@code{logging.logMultiprocessing} を @code{False} にする。

@item

@code{asyncio} を使っているときの、現在の @ref{1c7,,asyncio.Task} の名前。

@tab

@code{logging.logAsyncioTasks} を @code{False} に設定する。

@end multitable


また、コア logging モジュールが基本的なハンドラだけを含んでいることに注意してください。 @ref{8d,,logging.handlers} と @ref{8c,,logging.config} をインポートしなければ、余分なメモリを消費することはありません。

@node その他のリソース,,最適化<19>,Logging HOWTO
@anchor{howto/logging other-resources}@anchor{575f}@anchor{howto/logging tutorial-ref-links}@anchor{5743}
@subsection その他のリソース



@subsubheading 参考



@table @asis

@item @ref{8b,,logging} モジュール

logging モジュールの API リファレンス。

@item @ref{8c,,logging.config} モジュール

logging モジュールの環境設定 API です。

@item @ref{8d,,logging.handlers} モジュール

logging モジュールに含まれる、便利なハンドラです。
@end table

@ref{1410,,ロギングクックブック}


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Logging クックブック,正規表現 HOWTO,Logging HOWTO,Python HOWTO
@anchor{howto/logging-cookbook doc}@anchor{5760}@anchor{howto/logging-cookbook id1}@anchor{5761}@anchor{howto/logging-cookbook logging-cookbook}@anchor{1410}@anchor{howto/logging-cookbook translation-repo}@anchor{5762}
@section Logging クックブック


@*著者: 
Vinay Sajip <vinay_sajip at red-dove dot com>


このページは、過去に有用であるとされていた、logging に関連するいくつものレシピを含んでいます。チュートリアルやリファレンス情報へのリンクについては @ref{5763,,その他のリソース} を参照してください。

@menu
* 複数のモジュールで logging を使う:: 
* 複数のスレッドからのロギング:: 
* 複数の handler と formatter:: 
* 複数の出力先にログを出力する:: 
* ログレベルのカスタム処理:: 
* 設定サーバの例:: 
* ブロックする handler を扱う:: 
* ネットワーク越しの logging イベントの送受信:: 
* コンテキスト情報をログ記録出力に付加する:: 
* contextvars の利用:: 
* ハンドラ内でのコンテキスト情報の付与:: 
* 複数のプロセスからの単一ファイルへのログ記録:: 
* ファイルをローテートする:: 
* 別の format スタイルを利用する:: 
* LogRecord のカスタマイズ:: 
* Subclassing QueueHandler and QueueListener- a ZeroMQ example:: 
* Subclassing QueueHandler and QueueListener- a pynng example:: 
* 辞書ベースで構成する例:: 
* rotator と namer を使ってログローテートをカスタマイズする:: 
* より手の込んだ multiprocessing の例:: 
* SysLogHandler に送るメッセージに BOM を挿入する:: 
* 構造化ログを実装する:: 
* handler を dictConfig() を使ってカスタマイズする: handler を dictConfig を使ってカスタマイズする. 
* 固有の書式化スタイルをアプリケーション全体で使う:: 
* filter を dictConfig() を使ってカスタマイズする: filter を dictConfig を使ってカスタマイズする. 
* 例外の書式化をカスタマイズする:: 
* ロギングメッセージを喋る:: 
* ロギングメッセージをバッファリングし、条件に従って出力する:: 
* バッファリングしながらロギングメッセージを email で送信する:: 
* 設定によって時刻を UTC(GMT) で書式化する: 設定によって時刻を UTC GMT で書式化する. 
* ロギングの選択にコンテキストマネージャを使う:: 
* CLIアプリケーションスターターテンプレート:: 
* Qt GUIのログ出力:: 
* RFC5424 をサポートする syslog へのロギング:: 
* ロガーを出力ストリームのように取り扱う方法:: 
* How to uniformly handle newlines in logging output:: 
* 避けるべきパターン:: 
* その他のリソース: その他のリソース<2>. 

@end menu

@node 複数のモジュールで logging を使う,複数のスレッドからのロギング,,Logging クックブック
@anchor{howto/logging-cookbook using-logging-in-multiple-modules}@anchor{5764}
@subsection 複数のモジュールで logging を使う


@code{logging.getLogger('someLogger')} の複数回の呼び出しは同じ logger への参照を返します。これは同じ Python インタプリタプロセス上で動いている限り、一つのモジュールの中からに限らず、モジュールをまたいでも当てはまります。同じオブジェクトへの参照という点でも正しいです。さらに、一つのモジュールの中で親 logger を定義して設定し、別のモジュールで子 logger を定義する (ただし設定はしない) ことが可能で、すべての子 logger への呼び出しは親にまで渡されます。まずはメインのモジュールです:

@example
import logging
import auxiliary_module

# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

logger.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
logger.info('created an instance of auxiliary_module.Auxiliary')
logger.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
logger.info('finished auxiliary_module.Auxiliary.do_something')
logger.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
logger.info('done with auxiliary_module.some_function()')
@end example

そして補助モジュール (auxiliary module) がこちらです:

@example
import logging

# create logger
module_logger = logging.getLogger('spam_application.auxiliary')

class Auxiliary:
    def __init__(self):
        self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
        self.logger.info('creating an instance of Auxiliary')

    def do_something(self):
        self.logger.info('doing something')
        a = 1 + 1
        self.logger.info('done doing something')

def some_function():
    module_logger.info('received a call to "some_function"')
@end example

出力はこのようになります:

@example
2005-03-23 23:47:11,663 - spam_application - INFO -
   creating an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
   creating an instance of Auxiliary
2005-03-23 23:47:11,665 - spam_application - INFO -
   created an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,668 - spam_application - INFO -
   calling auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
   doing something
2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
   done doing something
2005-03-23 23:47:11,670 - spam_application - INFO -
   finished auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,671 - spam_application - INFO -
   calling auxiliary_module.some_function()
2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
   received a call to 'some_function'
2005-03-23 23:47:11,673 - spam_application - INFO -
   done with auxiliary_module.some_function()
@end example

@node 複数のスレッドからのロギング,複数の handler と formatter,複数のモジュールで logging を使う,Logging クックブック
@anchor{howto/logging-cookbook logging-from-multiple-threads}@anchor{5765}
@subsection 複数のスレッドからのロギング


複数スレッドからのロギングでは特別に何かをする必要はありません。
次の例はmain (初期) スレッドとそれ以外のスレッドからのロギングの例です:

@example
import logging
import threading
import time

def worker(arg):
    while not arg['stop']:
        logging.debug('Hi from myfunc')
        time.sleep(0.5)

def main():
    logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
    info = @{'stop': False@}
    thread = threading.Thread(target=worker, args=(info,))
    thread.start()
    while True:
        try:
            logging.debug('Hello from main')
            time.sleep(0.75)
        except KeyboardInterrupt:
            info['stop'] = True
            break
    thread.join()

if __name__ == '__main__':
    main()
@end example

実行すると、出力は以下のようになるはずです:

@example
   0 Thread-1 Hi from myfunc
   3 MainThread Hello from main
 505 Thread-1 Hi from myfunc
 755 MainThread Hello from main
1007 Thread-1 Hi from myfunc
1507 MainThread Hello from main
1508 Thread-1 Hi from myfunc
2010 Thread-1 Hi from myfunc
2258 MainThread Hello from main
2512 Thread-1 Hi from myfunc
3009 MainThread Hello from main
3013 Thread-1 Hi from myfunc
3515 Thread-1 Hi from myfunc
3761 MainThread Hello from main
4017 Thread-1 Hi from myfunc
4513 MainThread Hello from main
4518 Thread-1 Hi from myfunc
@end example

予想した通りかもしれませんが、ログ出力が散らばっているのが分かります。
もちろん、この手法はより多くのスレッドでも上手くいきます。

@node 複数の handler と formatter,複数の出力先にログを出力する,複数のスレッドからのロギング,Logging クックブック
@anchor{howto/logging-cookbook multiple-handlers-and-formatters}@anchor{5766}
@subsection 複数の handler と formatter


logger は通常の Python オブジェクトです。 @ref{3157,,addHandler()} メソッドは追加されるハンドラの個数について最小値も最大値も定めていません。時にアプリケーションがすべての深刻度のすべてのメッセージをテキストファイルに記録しつつ、同時にエラーやそれ以上のものをコンソールに出力することが役に立ちます。これを実現する方法は、単に適切なハンドラを設定するだけです。アプリケーションコードの中のログ記録の呼び出しは変更されずに残ります。少し前に取り上げた単純なモジュール式の例を少し変えるとこうなります:

@example
import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
@end example

'application' 部分のコードは複数の handler について何も気にしていないことに注目してください。変更した箇所は新しい `fh' という名の handler を追加して設定したところがすべてです。

新しい handler を、異なる深刻度に対する filter と共に生成できることは、アプリケーションを書いてテストを行うときとても助けになります。デバッグ用にたくさんの @code{print} 文を使う代わりに @code{logger.debug} を使いましょう。あとで消したりコメントアウトしたりしなければならない print 文と違って、logger.debug 命令はソースコードの中にそのまま残しておいて再び必要になるまで休眠させておけます。その時必要になるのはただ logger および/または handler の深刻度の設定をいじることだけです。

@node 複数の出力先にログを出力する,ログレベルのカスタム処理,複数の handler と formatter,Logging クックブック
@anchor{howto/logging-cookbook logging-to-multiple-destinations}@anchor{5767}@anchor{howto/logging-cookbook multiple-destinations}@anchor{5768}
@subsection 複数の出力先にログを出力する


コンソールとファイルに、別々のメッセージ書式で、別々の状況に応じたログ出力を行わせたいとしましょう。例えば DEBUG よりも高いレベルのメッセージはファイルに記録し、INFO 以上のレベルのメッセージはコンソールに出力したいという場合です。また、ファイルにはタイムスタンプを記録し、コンソールには出力しないとします。以下のようにすれば、こうした挙動を実現できます:

@example
import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/tmp/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.')
@end example

これを実行すると、コンソールには以下のように出力されます:

@example
root        : INFO     Jackdaws love my big sphinx of quartz.
myapp.area1 : INFO     How quickly daft jumping zebras vex.
myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
myapp.area2 : ERROR    The five boxing wizards jump quickly.
@end example

そして、ファイルには以下のように出力されるはずです:

@example
10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.
@end example

これを見て分かる通り、DEBUG メッセージはファイルだけに出力され、その他のメッセージは両方に出力されます。

この例ではコンソールとファイルのハンドラだけを使っていますが、実際には任意の数のハンドラや組み合わせを使えます。

ここでファイル名として @code{/tmp/myapp.log} を選んだということは、一時ファイルの標準的な場所として POSIX システムを想定していることに注意してください。 Windows の場合、ディレクトリが存在し、そのディレクトリに対してファイルを更新するための適切な権限を有することを保証するために、ログファイル向けのディレクトリ名として異なる選択を取る必要があるでしょう。

@node ログレベルのカスタム処理,設定サーバの例,複数の出力先にログを出力する,Logging クックブック
@anchor{howto/logging-cookbook custom-handling-of-levels}@anchor{5769}@anchor{howto/logging-cookbook custom-level-handling}@anchor{576a}
@subsection ログレベルのカスタム処理


しきい値以上のログレベル全てがハンドラによって処理される標準的な処理に対して、ときにはわずかに異なる振る舞いを必要とすることもあるでしょう。そのような場合はフィルタを使う必要があります。以下のような処理が必要なシナリオについて取り上げてみましょう:


@itemize *

@item 
深刻度 @code{INFO} と @code{WARNING} のメッセージを @code{sys.stdout} に送る

@item 
深刻度 @code{ERROR} 以上のメッセージを @code{sys.stderr} に送る

@item 
深刻度 @code{DEBUG} 以上のメッセージをファイル @code{app.log} に送る
@end itemize

logging モジュールを下記の JSON によって構成したとしましょう:

@example
@{
    "version": 1,
    "disable_existing_loggers": false,
    "formatters": @{
        "simple": @{
            "format": "%(levelname)-8s - %(message)s"
        @}
    @},
    "handlers": @{
        "stdout": @{
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "simple",
            "stream": "ext://sys.stdout"
        @},
        "stderr": @{
            "class": "logging.StreamHandler",
            "level": "ERROR",
            "formatter": "simple",
            "stream": "ext://sys.stderr"
        @},
        "file": @{
            "class": "logging.FileHandler",
            "formatter": "simple",
            "filename": "app.log",
            "mode": "w"
        @}
    @},
    "root": @{
        "level": "DEBUG",
        "handlers": [
            "stderr",
            "stdout",
            "file"
        ]
    @}
@}
@end example

This configuration does `almost' what we want, except that @code{sys.stdout} would show messages
of severity @code{ERROR} and only events of this severity and higher will be tracked
as well as @code{INFO} and @code{WARNING} messages. To prevent this, we can set up a filter which
excludes those messages and add it to the relevant handler. This can be configured by
adding a @code{filters} section parallel to @code{formatters} and @code{handlers}:

@example
@{
    "filters": @{
        "warnings_and_below": @{
            "()" : "__main__.filter_maker",
            "level": "WARNING"
        @}
    @}
@}
@end example

そして @code{stdout} のハンドラに関するセクションにフィルターを追加します:

@example
@{
    "stdout": @{
        "class": "logging.StreamHandler",
        "level": "INFO",
        "formatter": "simple",
        "stream": "ext://sys.stdout",
        "filters": ["warnings_and_below"]
    @}
@}
@end example

フィルターは単なる関数なので、 @code{filter_maker} (ファクトリ関数) は以下のように定義することができます:

@example
def filter_maker(level):
    level = getattr(logging, level)

    def filter(record):
        return record.levelno <= level

    return filter
@end example

この関数は引数として与えられた文字列をログレベルの数値に変換し、ログレコード内のログレベルが指定されたレベル以下の場合に @code{True} を返す関数を返します。この例では @code{filter_maker} をコマンドラインから実行するテストスクリプト @code{main.py} で関数が定義されているため、フィルター設定上のモジュール名は @code{__main__} になります。そのためフィルター設定の中では @code{__main__.filter_maker} となります。異なるモジュールで関数を定義した場合、この部分を変更する必要があります。

フィルターを追加した @code{main.py} の全体像は以下のようになり、これで実行できる状態になりました:

@example
import json
import logging
import logging.config

CONFIG = '@w{'}'
@{
    "version": 1,
    "disable_existing_loggers": false,
    "formatters": @{
        "simple": @{
            "format": "%(levelname)-8s - %(message)s"
        @}
    @},
    "filters": @{
        "warnings_and_below": @{
            "()" : "__main__.filter_maker",
            "level": "WARNING"
        @}
    @},
    "handlers": @{
        "stdout": @{
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "simple",
            "stream": "ext://sys.stdout",
            "filters": ["warnings_and_below"]
        @},
        "stderr": @{
            "class": "logging.StreamHandler",
            "level": "ERROR",
            "formatter": "simple",
            "stream": "ext://sys.stderr"
        @},
        "file": @{
            "class": "logging.FileHandler",
            "formatter": "simple",
            "filename": "app.log",
            "mode": "w"
        @}
    @},
    "root": @{
        "level": "DEBUG",
        "handlers": [
            "stderr",
            "stdout",
            "file"
        ]
    @}
@}
'@w{'}'

def filter_maker(level):
    level = getattr(logging, level)

    def filter(record):
        return record.levelno <= level

    return filter

logging.config.dictConfig(json.loads(CONFIG))
logging.debug('A DEBUG message')
logging.info('An INFO message')
logging.warning('A WARNING message')
logging.error('An ERROR message')
logging.critical('A CRITICAL message')
@end example

これを以下のように実行します:

@example
python main.py 2>stderr.log >stdout.log
@end example

すると期待通りの結果を得ることができます:

@example
$ more *.log
::::::::::::::
app.log
::::::::::::::
DEBUG    - A DEBUG message
INFO     - An INFO message
WARNING  - A WARNING message
ERROR    - An ERROR message
CRITICAL - A CRITICAL message
::::::::::::::
stderr.log
::::::::::::::
ERROR    - An ERROR message
CRITICAL - A CRITICAL message
::::::::::::::
stdout.log
::::::::::::::
INFO     - An INFO message
WARNING  - A WARNING message
@end example

@node 設定サーバの例,ブロックする handler を扱う,ログレベルのカスタム処理,Logging クックブック
@anchor{howto/logging-cookbook configuration-server-example}@anchor{576b}
@subsection 設定サーバの例


ログ記録設定サーバを使うモジュールの例です:

@example
import logging
import logging.config
import time
import os

# read initial config file
logging.config.fileConfig('logging.conf')

# create and start listener on port 9999
t = logging.config.listen(9999)
t.start()

logger = logging.getLogger('simpleExample')

try:
    # loop through logging calls to see the difference
    # new configurations make, until Ctrl+C is pressed
    while True:
        logger.debug('debug message')
        logger.info('info message')
        logger.warning('warn message')
        logger.error('error message')
        logger.critical('critical message')
        time.sleep(5)
except KeyboardInterrupt:
    # cleanup
    logging.config.stopListening()
    t.join()
@end example

そしてファイル名を受け取ってそのファイルをサーバに送るスクリプトですが、それに先だってバイナリエンコード長を新しいログ記録の設定として先に送っておきます:

@example
#!/usr/bin/env python
import socket, sys, struct

with open(sys.argv[1], 'rb') as f:
    data_to_send = f.read()

HOST = 'localhost'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('connecting...')
s.connect((HOST, PORT))
print('sending config...')
s.send(struct.pack('>L', len(data_to_send)))
s.send(data_to_send)
s.close()
print('complete')
@end example

@node ブロックする handler を扱う,ネットワーク越しの logging イベントの送受信,設定サーバの例,Logging クックブック
@anchor{howto/logging-cookbook blocking-handlers}@anchor{393e}@anchor{howto/logging-cookbook dealing-with-handlers-that-block}@anchor{576c}
@subsection ブロックする handler を扱う


ときどき、logging を行っているスレッドをブロックせずに、handler が動くようにしないといけないときがあります。これは Web アプリケーションではよくあることですし、もちろん他のシナリオでも起きる話です。

動作が鈍くなるときの元凶はたいてい、開発者のコントロール外にあるいくつもの理由で (例えば、残念なパフォーマンスのメールやネットワークのインフラ) 、 @ref{18b2,,SMTPHandler}: が電子メールを送るのに時間がかかることです。しかし、ほとんどのネットワークをまたぐ handler はブロックする可能性があります: @ref{1164,,SocketHandler} による処理でさえ、裏で DNS への問い合わせというとても遅い処理を行うことがあります (そしてこの問い合わせ処理は、 Python の層より下のあなたの手の届かない、ソケットライブラリの深いところにある可能性もあります)。

解決策の1つは、2パートに分離したアプローチを用いることです。最初のパートは、パフォーマンスが重要なスレッドからアクセスされる、 @ref{1b61,,QueueHandler} だけをアタッチした logger です。この logger は単に、十分大きい、あるいは無制限の容量を持ったキューに書き込むだけです。キューへの書き込みは通常すぐに完了しますが、念の為に @ref{366d,,queue.Full} 例外をキャッチする必要があるかもしれません。もしパフォーマンスクリティカルなスレッドを持つライブラリの開発者であるなら、このことを (@code{QueueHandler} だけをアタッチした logger についての言及を添えて) ドキュメントに書いておきましょう。

2つ目のパートは @ref{1b61,,QueueHandler} の対向として作られた @ref{242,,QueueListener} です。 @ref{242,,QueueListener} はとてもシンプルで、キューと handler を渡され、内部で @code{QueueHandler} (もしくは他の @code{LogRecord} の出力元) から送られた LogRecord をキューから受け取るスレッドを起動します。 @code{LogRecord} をキューから取り出して、 handler に渡して処理させます。

分離した @ref{242,,QueueListener} クラスを持つメリットは、複数の @code{QueueHandler} に対して1つのインスタンスで logging できることです。既存の handler のスレッド利用版を使って handler ごとにスレッドを持つよりはずっとリソースにやさしくなります。

この2つのクラスを利用する例です (import は省略):

@example
que = queue.Queue(-1)  # no limit on size
queue_handler = QueueHandler(que)
handler = logging.StreamHandler()
listener = QueueListener(que, handler)
root = logging.getLogger()
root.addHandler(queue_handler)
formatter = logging.Formatter('%(threadName)s: %(message)s')
handler.setFormatter(formatter)
listener.start()
# The log output will display the thread which generated
# the event (the main thread) rather than the internal
# thread which monitors the internal queue. This is what
# you want to happen.
root.warning('Look out!')
listener.stop()
@end example

実行すると次のように出力します:

@example
MainThread: Look out!
@end example

@cartouche
@quotation 注釈 
上述の議論は特に同期コードにについてのものではなく、むしろ遅いロギングハンドラについてでしたが、非同期コードやネットワーク、あるいはファイルハンドラからのロギングでさえも (イベントループをブロックしてしまう) 問題につながる可能性があることには注意すべきでしょう。これはいくつかのロギングが  @ref{b,,asyncio} 内部で行われることが理由です。何らかの非同期コードがアプリケーションの中で使われている場合、ロギングには上記のアプローチを使っていかなるブロッキングコードも @code{QueueListener} スレッド内だけで実行されるようにしておくことが最も良いでしょう。
@end quotation
@end cartouche


バージョン 3.5 で変更: Python 3.5 以前は、 @ref{242,,QueueListener} クラスは常にキューから受け取ったメッセージを、初期化元となっているそれぞれのハンドラーに受け渡していました。 ( というのも、レベルフィルターリングは別サイド、つまり、キューが満たされている場所で処理されるということが想定されているからです) Python 3.5以降では、キーワードとなる引数  @code{respect_handler_level=True}  をリスナーのコントラクターに受け渡すことで、この挙動を変更することができるようになっています。これが行われると、各メッセージのレベルをハンドラーのレベルと比較して、そうすることが適切な場合のみ、メッセージをハンドラーに渡します。



バージョン 3.14 で変更: The @ref{242,,QueueListener} can be started (and stopped) via the
@ref{186,,with} statement. For example:

@example
with QueueListener(que, handler) as listener:
    # The queue listener automatically starts
    # when the 'with' block is entered.
    pass
# The queue listener automatically stops once
# the 'with' block is exited.
@end example


@node ネットワーク越しの logging イベントの送受信,コンテキスト情報をログ記録出力に付加する,ブロックする handler を扱う,Logging クックブック
@anchor{howto/logging-cookbook network-logging}@anchor{576d}@anchor{howto/logging-cookbook sending-and-receiving-logging-events-across-a-network}@anchor{576e}
@subsection ネットワーク越しの logging イベントの送受信


ログイベントをネットワーク越しに送信し、受信端でそれを処理したいとしましょう。 @ref{1164,,SocketHandler} インスタンスを送信端の root logger にアタッチすれば、簡単に実現できます:

@example
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.')
@end example

受信端では @ref{d2,,socketserver} モジュールを使って受信プログラムを作成しておきます。簡単な実用プログラムを以下に示します:

@example
import pickle
import logging
import logging.handlers
import socketserver
import struct


class LogRecordStreamHandler(socketserver.StreamRequestHandler):
    """Handler for a streaming logging request.

    This basically logs the record using whatever logging policy is
    configured locally.
    """

    def handle(self):
        """
        Handle multiple requests - each expected to be a 4-byte length,
        followed by the LogRecord in pickle format. Logs the record
        according to whatever policy is configured locally.
        """
        while True:
            chunk = self.connection.recv(4)
            if len(chunk) < 4:
                break
            slen = struct.unpack('>L', chunk)[0]
            chunk = self.connection.recv(slen)
            while len(chunk) < slen:
                chunk = chunk + self.connection.recv(slen - len(chunk))
            obj = self.unPickle(chunk)
            record = logging.makeLogRecord(obj)
            self.handleLogRecord(record)

    def unPickle(self, data):
        return pickle.loads(data)

    def handleLogRecord(self, record):
        # if a name is specified, we use the named logger rather than the one
        # implied by the record.
        if self.server.logname is not None:
            name = self.server.logname
        else:
            name = record.name
        logger = logging.getLogger(name)
        # N.B. EVERY record gets logged. This is because Logger.handle
        # is normally called AFTER logger-level filtering. If you want
        # to do filtering, do it at the client end to save wasting
        # cycles and network bandwidth!
        logger.handle(record)

class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
    """
    Simple TCP socket-based logging receiver suitable for testing.
    """

    allow_reuse_address = True

    def __init__(self, host='localhost',
                 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                 handler=LogRecordStreamHandler):
        socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None

    def serve_until_stopped(self):
        import select
        abort = 0
        while not abort:
            rd, wr, ex = select.select([self.socket.fileno()],
                                       [], [],
                                       self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort

def main():
    logging.basicConfig(
        format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
    tcpserver = LogRecordSocketReceiver()
    print('About to start TCP server...')
    tcpserver.serve_until_stopped()

if __name__ == '__main__':
    main()
@end example

先にサーバを起動しておき、次にクライアントを起動します。クライアント側では、コンソールには何も出力されません; サーバ側では以下のようなメッセージを目にするはずです:

@example
About to start TCP server...
   59 root            INFO     Jackdaws love my big sphinx of quartz.
   59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
   69 myapp.area1     INFO     How quickly daft jumping zebras vex.
   69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
   69 myapp.area2     ERROR    The five boxing wizards jump quickly.
@end example

注意： pickle にはいくつかのシナリオでセキュリティ上の問題があります。これらが影響する場合は、 @ref{31f5,,makePickle()} メソッドをオーバーライドし代替シリアライズ手法を実装して、それを使うように上記のスクリプトを修正することもできます。

@menu
* 作成中のロギングソケットのリスナーを実行する:: 

@end menu

@node 作成中のロギングソケットのリスナーを実行する,,,ネットワーク越しの logging イベントの送受信
@anchor{howto/logging-cookbook running-a-logging-socket-listener-in-production}@anchor{576f}
@subsubsection 作成中のロギングソケットのリスナーを実行する


作成中のロギングリスナーを実行するためには、 Supervisor@footnote{http://supervisord.org/} のようなプロセス管理ツールを使う必要があるかもしれません。 こちらの Gist@footnote{https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b} は Supervisor を使って上記の機能を実行するための必要最低限のファイルを提供しています。以下のファイルが必要になります:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ファイル

@tab

目的

@item

@code{prepare.sh}

@tab

試験用の環境を準備する Bash スクリプト

@item

@code{supervisor.conf}

@tab

リスナーとマルチプロセスの web アプリケーションのための設定を含む Supervisor の設定ファイル

@item

@code{ensure_app.sh}

@tab

Supervisor が上記の設定で実行されていることを保証するための Bash スクリプト

@item

@code{log_listener.py}

@tab

ログイベントを受信してファイルに記録するソケットリスナープログラム

@item

@code{main.py}

@tab

リスナーに接続されたソケットを通じてロギングを実行する簡単な web アプリケーション

@item

@code{webapp.json}

@tab

web アプリケーションのための JSON 設定ファイル

@item

@code{client.py}

@tab

web アプリケーションを起動するための Python スクリプト

@end multitable


この web アプリケーションは、リクエストを処理する複数のワーカープロセスを起動する web アプリケーションサーバーである Gunicorn@footnote{https://gunicorn.org/} を使っています。ここに例として挙げた設定は、複数のワーカーがいかにして互いに衝突することなく同じログファイルに書き込みを行うことができるかを示しています --- ワーカーは全てソケットリスナーを通じてログを書き込むのです。

これらのファイルを試すためには、 POSIX 環境において以下を行なってください:


@enumerate 

@item 
Download ZIP ボタンを押して Gist@footnote{https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b} を ZIP アーカイブとしてダウンロードしてください。

@item 
アーカイブファイルをスクラッチディレクトリに展開してください。

@item 
準備のために、スクラッチディレクトリにおいて @code{bash prepare.sh} を実行してください。これにより Supervisor 関連のファイルおよびログファイルのための @code{run} サブディレクトリ、および @code{bottle}, @code{gunicorn} そして @code{supervisor} がインストールされる仮想環境を含む @code{venv} サブディレクトリが生成されます。

@item 
@code{bash ensure_app.sh} を実行して Supervisor が上記の設定で実行されていることを確認してください。

@item 
@code{venv/bin/python client.py} を実行して web アプリケーションを起動してください。これによりログにレコードが書き込まれるはずです。

@item 
@code{run} サブディレクトリにあるログファイルを調べてください。最新のログは、パターン @code{app.log*} に一致する名前のファイルにあるはずです。ログは異なるワーカープロセスによって非決定論的な形で並行に処理されるため、特定の決まった順番にはなりません。

@item 
リスナーと web アプリケーションは @code{venv/bin/supervisorctl -c supervisor.conf shutdown} を実行することでシャットダウンできます。
@end enumerate

ありそうもないことですが、テスト環境で設定したポートが別の設定と衝突してしまった場合、設定ファイルを修正する必要があるかもしれません。

The default configuration uses a TCP socket on port 9020. You can use a Unix
Domain socket instead of a TCP socket by doing the following:


@enumerate 

@item 
In @code{listener.json}, add a @code{socket} key with the path to the domain
socket you want to use. If this key is present, the listener listens on the
corresponding domain socket and not on a TCP socket (the @code{port} key is
ignored).

@item 
In @code{webapp.json}, change the socket handler configuration dictionary
so that the @code{host} value is the path to the domain socket, and set the
@code{port} value to @code{null}.
@end enumerate

@node コンテキスト情報をログ記録出力に付加する,contextvars の利用,ネットワーク越しの logging イベントの送受信,Logging クックブック
@anchor{howto/logging-cookbook adding-contextual-information-to-your-logging-output}@anchor{5770}@anchor{howto/logging-cookbook context-info}@anchor{3192}
@subsection コンテキスト情報をログ記録出力に付加する


時にはログ記録出力にログ関数の呼び出し時に渡されたパラメータに加えてコンテキスト情報を含めたいこともあるでしょう。たとえば、ネットワークアプリケーションで、クライアント固有の情報 (例: リモートクライアントの名前、 IP アドレス) もログ記録に残しておきたいと思ったとしましょう。 `extra' パラメータをこの目的に使うこともできますが、いつでもこの方法で情報を渡すのが便利なやり方とも限りません。また接続ごとに @ref{d46,,Logger} インスタンスを生成する誘惑に駆られるかもしれませんが、生成した @ref{d46,,Logger} インスタンスはガーベジコレクションで回収されないので、これは良いアイデアとは言えません。この例は現実的な問題ではないかもしれませんが、 @ref{d46,,Logger} インスタンスの個数がアプリケーションの中でログ記録が行われるレベルの粒度に依存する場合、 @ref{d46,,Logger} インスタンスの個数が事実上無制限にならないと、管理が難しくなります。

@menu
* LoggerAdapter を使ったコンテキスト情報の伝達:: 
* Filter を使ったコンテキスト情報の伝達:: 

@end menu

@node LoggerAdapter を使ったコンテキスト情報の伝達,Filter を使ったコンテキスト情報の伝達,,コンテキスト情報をログ記録出力に付加する
@anchor{howto/logging-cookbook using-loggeradapters-to-impart-contextual-information}@anchor{5771}
@subsubsection LoggerAdapter を使ったコンテキスト情報の伝達


logging イベントの情報と一緒に出力されるコンテキスト情報を渡す簡単な方法は、 @ref{150d,,LoggerAdapter} を使うことです。このクラスは @ref{d46,,Logger} のように見えるように設計されていて、 @ref{315d,,debug()}, @ref{3186,,info()}, @ref{354,,warning()}, @ref{319a,,error()}, @ref{16ad,,exception()}, @ref{319b,,critical()}, @ref{319c,,log()} の各メソッドを呼び出せるようになっています。これらのメソッドは対応する @ref{d46,,Logger} のメソッドと同じ引数を取るので、二つの型を取り替えて使うことができます。

@ref{150d,,LoggerAdapter} のインスタンスを生成する際には、 @ref{d46,,Logger} インスタンスとコンテキスト情報を収めた辞書風 (dict-like) のオブジェクトを渡します。 @ref{150d,,LoggerAdapter} のログ記録メソッドを呼び出すと、呼び出しをコンストラクタに渡された配下の @ref{d46,,Logger} インスタンスに委譲し、その際コンテキスト情報をその委譲された呼び出しに埋め込みます。 @ref{150d,,LoggerAdapter} のコードから少し抜き出してみます:

@example
def debug(self, msg, /, *args, **kwargs):
    """
    Delegate a debug call to the underlying logger, after adding
    contextual information from this adapter instance.
    """
    msg, kwargs = self.process(msg, kwargs)
    self.logger.debug(msg, *args, **kwargs)
@end example

@ref{150d,,LoggerAdapter} の @ref{3193,,process()} メソッドがコンテキスト情報をログ出力に加える場所です。そこではログ記録呼び出しのメッセージとキーワード引数が渡され、加工された (可能性のある) それらの情報を配下のロガーへの呼び出しに渡し直します。このメソッドのデフォルト実装ではメッセージは元のままですが、キーワード引数にはコンストラクタに渡された辞書風オブジェクトを値として "extra" キーが挿入されます。もちろん、呼び出し時に "extra" キーワードを使った場合には何事もなかったかのように上書きされます。

"extra" を用いる利点は辞書風オブジェクトの中の値が @ref{11e8,,LogRecord} インスタンスの __dict__ にマージされることで、辞書風オブジェクトのキーを知っている @ref{16b0,,Formatter} を用意して文字列をカスタマイズするようにできることです。それ以外のメソッドが必要なとき、たとえばコンテキスト情報をメッセージの前や後ろにつなげたい場合には、 @ref{150d,,LoggerAdapter} から @ref{3193,,process()} を望むようにオーバライドしたサブクラスを作ることが必要なだけです。次に挙げるのはこのクラスを使った例で、コンストラクタで使われる「辞書風」オブジェクトにどの振る舞いが必要なのかも示しています:

@example
class CustomAdapter(logging.LoggerAdapter):
    """
    This example adapter expects the passed in dict-like object to have a
    'connid' key, whose value in brackets is prepended to the log message.
    """
    def process(self, msg, kwargs):
        return '[%s] %s' % (self.extra['connid'], msg), kwargs
@end example

これを次のように使うことができます:

@example
logger = logging.getLogger(__name__)
adapter = CustomAdapter(logger, @{'connid': some_conn_id@})
@end example

これで、この adapter 経由でログした全てのイベントに対して、@code{some_conn_id} の値がログメッセージの前に追加されます。

@menu
* コンテキスト情報を渡すために dict 以外のオブジェクトを使う:: 

@end menu

@node コンテキスト情報を渡すために dict 以外のオブジェクトを使う,,,LoggerAdapter を使ったコンテキスト情報の伝達
@anchor{howto/logging-cookbook using-objects-other-than-dicts-to-pass-contextual-information}@anchor{5772}
@subsubsection コンテキスト情報を渡すために dict 以外のオブジェクトを使う


@ref{150d,,LoggerAdapter} に渡すのは本物の dict でなくても構いません。 @code{__getitem__} と @code{__iter__} を実装していて logging が辞書のように扱えるクラスのインスタンスを利用することができます。これは (dict の値が固定されるのに対して) 値を動的に生成できるので便利です。

@node Filter を使ったコンテキスト情報の伝達,,LoggerAdapter を使ったコンテキスト情報の伝達,コンテキスト情報をログ記録出力に付加する
@anchor{howto/logging-cookbook filters-contextual}@anchor{3187}@anchor{howto/logging-cookbook using-filters-to-impart-contextual-information}@anchor{5773}
@subsubsection Filter を使ったコンテキスト情報の伝達


ユーザ定義の @ref{1414,,Filter} を使ってログ出力にコンテキスト情報を加えることもできます。 @code{Filter} インスタンスは、渡された @code{LogRecords} を修正することができます。これにより、適切なフォーマット文字列や必要なら @ref{16b0,,Formatter} を使って、出力となる属性を新しく追加することも出来ます。

例えば、web アプリケーションで、処理されるリクエスト (または、少なくともその重要な部分) は、スレッドローカル (@ref{185f,,threading.local}) な変数に保存して、 @code{Filter} からアクセスすることで、 @code{LogRecord} にリクエストの情報を追加できます。例えば、リモート IP アドレスやリモートユーザのユーザ名にアクセスしたいなら、上述の @code{LoggerAdapter} の例のように属性名 'ip' や 'user' を使うといったようにです。その場合、同じフォーマット文字列を使って以下に示すように似たような出力を得られます。これはスクリプトの例です:

@example
import logging
from random import choice

class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.

    Rather than use actual contextual information, we just use random
    data in this demo.
    """

    USERS = ['jim', 'fred', 'sheila']
    IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']

    def filter(self, record):

        record.ip = choice(ContextFilter.IPS)
        record.user = choice(ContextFilter.USERS)
        return True

if __name__ == '__main__':
    levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
    a1 = logging.getLogger('a.b.c')
    a2 = logging.getLogger('d.e.f')

    f = ContextFilter()
    a1.addFilter(f)
    a2.addFilter(f)
    a1.debug('A debug message')
    a1.info('An info message with %s', 'some parameters')
    for x in range(10):
        lvl = choice(levels)
        lvlname = logging.getLevelName(lvl)
        a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
@end example

実行すると、以下のようになります:

@example
2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters
@end example

@node contextvars の利用,ハンドラ内でのコンテキスト情報の付与,コンテキスト情報をログ記録出力に付加する,Logging クックブック
@anchor{howto/logging-cookbook use-of-contextvars}@anchor{5774}
@subsection @code{contextvars} の利用


Python 3.7 以降、 @ref{28,,contextvars} モジュールは @ref{f3,,threading} と @ref{b,,asyncio} の両方の処理上のニーズを満たすコンテキストローカルな変数を提供しています。このタイプの変数はスレッドローカルな変数に適しています。以下の例は、マルチスレッド環境において、 いかにして web アプリケーションによって処理されるリクエスト属性のような処理の文脈上の情報とともにログを投入できるかを示します。

説明のため、同じ Python プロセス上で共通のライブラリを使っている独立した複数の web アプリケーションがあるとします。これらのアプリケーションが、クライアントの IP アドレスや HTTP リクエストメソッド、およびクライアントのユーザー名のようなコンテキスト依存の情報を追加情報として含んだ自身のログを、共通のライブラリ (と他のリクエスト処理のためのコード) から各アプリケーションのログファイルへ適切に振り向けるためにはどのようにしたら良いでしょうか？

ここで、ライブラリは以下のコードで模することができるとします:

@example
# webapplib.py
import logging
import time

logger = logging.getLogger(__name__)

def useful():
    # Just a representative event logged from the library
    logger.debug('Hello from webapplib!')
    # Just sleep for a bit so other threads get to run
    time.sleep(0.01)
@end example

複数の web アプリケーションは2つの簡単なクラス, @code{Request} と @code{WebApp}, によって模倣することができます。これらは実際のスレッド化された web アプリケーションがどのように動作するかを模擬的にあらわしています - すなわち各リクエストはスレッドで処理される状況です:

@example
# main.py
import argparse
from contextvars import ContextVar
import logging
import os
from random import choice
import threading
import webapplib

logger = logging.getLogger(__name__)
root = logging.getLogger()
root.setLevel(logging.DEBUG)

class Request:
    """
    A simple dummy request class which just holds dummy HTTP request method,
    client IP address and client username
    """
    def __init__(self, method, ip, user):
        self.method = method
        self.ip = ip
        self.user = user

# A dummy set of requests which will be used in the simulation - we'll just pick
# from this list randomly. Note that all GET requests are from 192.168.2.XXX
# addresses, whereas POST requests are from 192.16.3.XXX addresses. Three users
# are represented in the sample requests.

REQUESTS = [
    Request('GET', '192.168.2.20', 'jim'),
    Request('POST', '192.168.3.20', 'fred'),
    Request('GET', '192.168.2.21', 'sheila'),
    Request('POST', '192.168.3.21', 'jim'),
    Request('GET', '192.168.2.22', 'fred'),
    Request('POST', '192.168.3.22', 'sheila'),
]

# Note that the format string includes references to request context information
# such as HTTP method, client IP and username

formatter = logging.Formatter('%(threadName)-11s %(appName)s %(name)-9s %(user)-6s %(ip)s %(method)-4s %(message)s')

# Create our context variables. These will be filled at the start of request
# processing, and used in the logging that happens during that processing

ctx_request = ContextVar('request')
ctx_appname = ContextVar('appname')

class InjectingFilter(logging.Filter):
    """
    A filter which injects context-specific information into logs and ensures
    that only information for a specific webapp is included in its log
    """
    def __init__(self, app):
        self.app = app

    def filter(self, record):
        request = ctx_request.get()
        record.method = request.method
        record.ip = request.ip
        record.user = request.user
        record.appName = appName = ctx_appname.get()
        return appName == self.app.name

class WebApp:
    """
    A dummy web application class which has its own handler and filter for a
    webapp-specific log.
    """
    def __init__(self, name):
        self.name = name
        handler = logging.FileHandler(name + '.log', 'w')
        f = InjectingFilter(self)
        handler.setFormatter(formatter)
        handler.addFilter(f)
        root.addHandler(handler)
        self.num_requests = 0

    def process_request(self, request):
        """
        This is the dummy method for processing a request. It's called on a
        different thread for every request. We store the context information into
        the context vars before doing anything else.
        """
        ctx_request.set(request)
        ctx_appname.set(self.name)
        self.num_requests += 1
        logger.debug('Request processing started')
        webapplib.useful()
        logger.debug('Request processing finished')

def main():
    fn = os.path.splitext(os.path.basename(__file__))[0]
    adhf = argparse.ArgumentDefaultsHelpFormatter
    ap = argparse.ArgumentParser(formatter_class=adhf, prog=fn,
                                 description='Simulate a couple of web '
                                             'applications handling some '
                                             'requests, showing how request '
                                             'context can be used to '
                                             'populate logs')
    aa = ap.add_argument
    aa('--count', '-c', type=int, default=100, help='How many requests to simulate')
    options = ap.parse_args()

    # Create the dummy webapps and put them in a list which we can use to select
    # from randomly
    app1 = WebApp('app1')
    app2 = WebApp('app2')
    apps = [app1, app2]
    threads = []
    # Add a common handler which will capture all events
    handler = logging.FileHandler('app.log', 'w')
    handler.setFormatter(formatter)
    root.addHandler(handler)

    # Generate calls to process requests
    for i in range(options.count):
        try:
            # Pick an app at random and a request for it to process
            app = choice(apps)
            request = choice(REQUESTS)
            # Process the request in its own thread
            t = threading.Thread(target=app.process_request, args=(request,))
            threads.append(t)
            t.start()
        except KeyboardInterrupt:
            break

    # Wait for the threads to terminate
    for t in threads:
        t.join()

    for app in apps:
        print('%s processed %s requests' % (app.name, app.num_requests))

if __name__ == '__main__':
    main()
@end example

上記のコードを実行すると、およそ半分のリクエストが @code{app1.log} に、残り半分が @code{app2.log} にそれぞれ記録され、同時に全てのリクエストが @code{app.log} に記録されることがわかるでしょう。それぞれの web アプリケーション固有のログはそれぞれのアプリケーションからのログエントリだけを含み、リクエスト情報が矛盾なくログに表示されている (すなわち、各ダミーリクエストの情報は常にログの行とともに現れる) はずです。このことは以下のシェルコマンドの出力により例示されています:

@example
~/logging-contextual-webapp$ python main.py
app1 processed 51 requests
app2 processed 49 requests
~/logging-contextual-webapp$ wc -l *.log
  153 app1.log
  147 app2.log
  300 app.log
  600 total
~/logging-contextual-webapp$ head -3 app1.log
Thread-3 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
Thread-3 (process_request) app1 webapplib jim    192.168.3.21 POST Hello from webapplib!
Thread-5 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
~/logging-contextual-webapp$ head -3 app2.log
Thread-1 (process_request) app2 __main__  sheila 192.168.2.21 GET  Request processing started
Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET  Hello from webapplib!
Thread-2 (process_request) app2 __main__  jim    192.168.2.20 GET  Request processing started
~/logging-contextual-webapp$ head app.log
Thread-1 (process_request) app2 __main__  sheila 192.168.2.21 GET  Request processing started
Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET  Hello from webapplib!
Thread-2 (process_request) app2 __main__  jim    192.168.2.20 GET  Request processing started
Thread-3 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
Thread-2 (process_request) app2 webapplib jim    192.168.2.20 GET  Hello from webapplib!
Thread-3 (process_request) app1 webapplib jim    192.168.3.21 POST Hello from webapplib!
Thread-4 (process_request) app2 __main__  fred   192.168.2.22 GET  Request processing started
Thread-5 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
Thread-4 (process_request) app2 webapplib fred   192.168.2.22 GET  Hello from webapplib!
Thread-6 (process_request) app1 __main__  jim    192.168.3.21 POST Request processing started
~/logging-contextual-webapp$ grep app1 app1.log | wc -l
153
~/logging-contextual-webapp$ grep app2 app2.log | wc -l
147
~/logging-contextual-webapp$ grep app1 app.log | wc -l
153
~/logging-contextual-webapp$ grep app2 app.log | wc -l
147
@end example

@node ハンドラ内でのコンテキスト情報の付与,複数のプロセスからの単一ファイルへのログ記録,contextvars の利用,Logging クックブック
@anchor{howto/logging-cookbook imparting-contextual-information-in-handlers}@anchor{5775}
@subsection ハンドラ内でのコンテキスト情報の付与


@ref{16af,,Handler} はそれぞれ一連のフィルタを独自に持っています。コンテキスト情報を、他のハンドラに漏らすことなく @ref{11e8,,LogRecord} に付加したい場合、以下に示すスクリプトのように、直接レコードを編集する代わりに新しい @ref{11e8,,LogRecord} を返すフィルタを使うことができます:

@example
import copy
import logging

def filter(record: logging.LogRecord):
    record = copy.copy(record)
    record.user = 'jim'
    return record

if __name__ == '__main__':
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter('%(message)s from %(user)-8s')
    handler.setFormatter(formatter)
    handler.addFilter(filter)
    logger.addHandler(handler)

    logger.info('A log message')
@end example

@node 複数のプロセスからの単一ファイルへのログ記録,ファイルをローテートする,ハンドラ内でのコンテキスト情報の付与,Logging クックブック
@anchor{howto/logging-cookbook logging-to-a-single-file-from-multiple-processes}@anchor{5776}@anchor{howto/logging-cookbook multiple-processes}@anchor{5777}
@subsection 複数のプロセスからの単一ファイルへのログ記録


ログ記録はスレッドセーフであり、単一プロセスの複数のスレッドからの単一ファイルへのログ記録はサポート `されています' が、 `複数プロセス' からの単一ファイルへのログ記録はサポート `されません' 。なぜなら、複数のプロセスをまたいで単一のファイルへのアクセスを直列化する標準の方法が Python には存在しないからです。複数のプロセスから単一ファイルへログ記録しなければならないなら、最も良い方法は、すべてのプロセスが @ref{1164,,SocketHandler} に対してログ記録を行い、独立したプロセスとしてソケットサーバを動かすことです。ソケットサーバはソケットから読み取ってファイルにログを書き出します。 (この機能を実行するために、既存のプロセスの 1 つのスレッドを割り当てることもできます) @ref{576d,,この節} では、このアプローチをさらに詳細に文書化しています。動作するソケット受信プログラムが含まれているので、アプリケーションに組み込むための出発点として使用できるでしょう。

You could also write your own handler which uses the @ref{1853,,Lock}
class from the @ref{98,,multiprocessing} module to serialize access to the
file from your processes. The stdlib @ref{1c53,,FileHandler} and subclasses do
not make use of @ref{98,,multiprocessing}.

別の方法として、 @code{Queue} と @ref{1b61,,QueueHandler} を使って、マルチプロセスアプリケーションの1つのプロセスに全ての logging イベントを送る事ができます。次の例はこれを行う方法を示します。この例では独立した listener プロセスが他のプロセスから送られた event を受け取り、それを独自の logging 設定にしたがって保存します。この例は実装の方法の1つを示しているだけ (例えば、 listener プロセスを分離する代わりに listener スレッドを使うこともできます) ですが、これは listener とアプリケーション内の他のプロセスで完全に異なる設定を使う例になっているので、各自の要求に応じたコードを書く叩き台になるでしょう:

@example
# You'll need these imports in your own code
import logging
import logging.handlers
import multiprocessing

# Next two import lines for this demo only
from random import choice, random
import time

#
# Because you'll want to define the logging configurations for listener and workers, the
# listener and worker process functions take a configurer parameter which is a callable
# for configuring logging for that process. These functions are also passed the queue,
# which they use for communication.
#
# In practice, you can configure the listener however you want, but note that in this
# simple example, the listener does not apply level or filter logic to received records.
# In practice, you would probably want to do this logic in the worker processes, to avoid
# sending events which would be filtered out between processes.
#
# The size of the rotated files is made small so you can see the results easily.
def listener_configurer():
    root = logging.getLogger()
    h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
    f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
    h.setFormatter(f)
    root.addHandler(h)

# This is the listener process top-level loop: wait for logging events
# (LogRecords)on the queue and handle them, quit when you get a None for a
# LogRecord.
def listener_process(queue, configurer):
    configurer()
    while True:
        try:
            record = queue.get()
            if record is None:  # We send this as a sentinel to tell the listener to quit.
                break
            logger = logging.getLogger(record.name)
            logger.handle(record)  # No level or filter logic applied - just do it!
        except Exception:
            import sys, traceback
            print('Whoops! Problem:', file=sys.stderr)
            traceback.print_exc(file=sys.stderr)

# Arrays used for random selections in this demo

LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
          logging.ERROR, logging.CRITICAL]

LOGGERS = ['a.b.c', 'd.e.f']

MESSAGES = [
    'Random message #1',
    'Random message #2',
    'Random message #3',
]

# The worker configuration is done at the start of the worker process run.
# Note that on Windows you can't rely on fork semantics, so each process
# will run the logging configuration code when it starts.
def worker_configurer(queue):
    h = logging.handlers.QueueHandler(queue)  # Just the one handler needed
    root = logging.getLogger()
    root.addHandler(h)
    # send all messages, for demo; no other level or filter logic applied.
    root.setLevel(logging.DEBUG)

# This is the worker process top-level loop, which just logs ten events with
# random intervening delays before terminating.
# The print messages are just so you know it's doing something!
def worker_process(queue, configurer):
    configurer(queue)
    name = multiprocessing.current_process().name
    print('Worker started: %s' % name)
    for i in range(10):
        time.sleep(random())
        logger = logging.getLogger(choice(LOGGERS))
        level = choice(LEVELS)
        message = choice(MESSAGES)
        logger.log(level, message)
    print('Worker finished: %s' % name)

# Here's where the demo gets orchestrated. Create the queue, create and start
# the listener, create ten workers and start them, wait for them to finish,
# then send a None to the queue to tell the listener to finish.
def main():
    queue = multiprocessing.Queue(-1)
    listener = multiprocessing.Process(target=listener_process,
                                       args=(queue, listener_configurer))
    listener.start()
    workers = []
    for i in range(10):
        worker = multiprocessing.Process(target=worker_process,
                                         args=(queue, worker_configurer))
        workers.append(worker)
        worker.start()
    for w in workers:
        w.join()
    queue.put_nowait(None)
    listener.join()

if __name__ == '__main__':
    main()
@end example

上のスクリプトの亜種で、logging をメインプロセスの別スレッドで行う例:

@example
import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue
import random
import threading
import time

def logger_thread(q):
    while True:
        record = q.get()
        if record is None:
            break
        logger = logging.getLogger(record.name)
        logger.handle(record)


def worker_process(q):
    qh = logging.handlers.QueueHandler(q)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(qh)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)

if __name__ == '__main__':
    q = Queue()
    d = @{
        'version': 1,
        'formatters': @{
            'detailed': @{
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            @}
        @},
        'handlers': @{
            'console': @{
                'class': 'logging.StreamHandler',
                'level': 'INFO',
            @},
            'file': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed',
            @},
            'foofile': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed',
            @},
            'errors': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'level': 'ERROR',
                'formatter': 'detailed',
            @},
        @},
        'loggers': @{
            'foo': @{
                'handlers': ['foofile']
            @}
        @},
        'root': @{
            'level': 'DEBUG',
            'handlers': ['console', 'file', 'errors']
        @},
    @}
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
        workers.append(wp)
        wp.start()
    logging.config.dictConfig(d)
    lp = threading.Thread(target=logger_thread, args=(q,))
    lp.start()
    # At this point, the main process could do some useful work of its own
    # Once it's done that, it can wait for the workers to terminate...
    for wp in workers:
        wp.join()
    # And now tell the logging thread to finish up, too
    q.put(None)
    lp.join()
@end example

こちらは特定の logger に設定を適用する例になっています。@code{foo} logger は @code{foo} サブシステムの中の全てのイベントを @code{mplog-foo.log} に保存する特別な handler を持っています。これはメインプロセス側の log 処理で使われ、(logging イベントは worker プロセス側で生成されますが) 各メッセージを適切な出力先に出力します。

@menu
* concurrent.futures.ProcessPoolExecutorの利用: concurrent futures ProcessPoolExecutorの利用. 
* Gunicorn と uWSGI を用いた Web アプリケーションのデプロイ:: 

@end menu

@node concurrent futures ProcessPoolExecutorの利用,Gunicorn と uWSGI を用いた Web アプリケーションのデプロイ,,複数のプロセスからの単一ファイルへのログ記録
@anchor{howto/logging-cookbook using-concurrent-futures-processpoolexecutor}@anchor{5778}
@subsubsection concurrent.futures.ProcessPoolExecutorの利用


もし、ワーカープロセスを起動するために @ref{1d6,,concurrent.futures.ProcessPoolExecutor} を使いたいのであれば、少し違う方法でキューを作る必要があります。次のような方法の代わりに

@example
queue = multiprocessing.Queue(-1)
@end example

次のコードを利用する必要があります

@example
queue = multiprocessing.Manager().Queue(-1)  # also works with the examples above
@end example

そして、次のようなワーカー作成コードがあったとすると:

@example
workers = []
for i in range(10):
    worker = multiprocessing.Process(target=worker_process,
                                     args=(queue, worker_configurer))
    workers.append(worker)
    worker.start()
for w in workers:
    w.join()
@end example

次のように変更します（最初に @ref{24,,concurrent.futures} をインポートするのを忘れないようにしましょう）:

@example
with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(10):
        executor.submit(worker_process, queue, worker_configurer)
@end example

@node Gunicorn と uWSGI を用いた Web アプリケーションのデプロイ,,concurrent futures ProcessPoolExecutorの利用,複数のプロセスからの単一ファイルへのログ記録
@anchor{howto/logging-cookbook deploying-web-applications-using-gunicorn-and-uwsgi}@anchor{5779}
@subsubsection Gunicorn と uWSGI を用いた Web アプリケーションのデプロイ


Gunicorn@footnote{https://gunicorn.org/} や uWSGI@footnote{https://uwsgi-docs.readthedocs.io/en/latest/} (またはそれに類するもの) を使って Web アプリケーションをデプロイする場合、クライアントのリクエストを処理するために複数のワーカープロセスが作られます。そのような環境では、 web アプリケーションに直接ファイルベースのハンドラを作ることは避けてください。 代わりに、 @ref{1164,,SocketHandler} を使って別のプロセスとして動作するリスナーに web アプリケーションからログを送信するようにしてください。これは Supervisor のようなプロセス管理ツールを使うことで設定できます -  詳しくは @ref{576f,,作成中のロギングソケットのリスナーを実行する} を参照してください。

@node ファイルをローテートする,別の format スタイルを利用する,複数のプロセスからの単一ファイルへのログ記録,Logging クックブック
@anchor{howto/logging-cookbook using-file-rotation}@anchor{577a}
@subsection ファイルをローテートする


@c (see <https://pymotw.com/3/logging/>)

ログファイルがある大きさに達したら、新しいファイルを開いてそこにログを取りたいことがあります。そのファイルをある数だけ残し、その数のファイルが生成されたらファイルを循環し、ファイルの数も大きさも制限したいこともあるでしょう。この利用パターンのために、 logging パッケージは @ref{1941,,RotatingFileHandler} を提供しています:

@example
import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=20, backupCount=5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
    my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
    print(filename)
@end example

この結果として、アプリケーションのログ履歴の一部である、6 つに別れたファイルが得られます:

@example
logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
@end example

最新のファイルはいつでも @code{logging_rotatingfile_example.out} で、サイズの上限に達するたびに拡張子 @code{.1} を付けた名前に改名されます。既にあるバックアップファイルはその拡張子がインクリメントされ (@code{.1} が @code{.2} になるなど)、 @code{.6} ファイルは消去されます。

明らかに、ここでは極端な例示のためにファイルの大きさをかなり小さな値に設定しています。実際に使うときは `maxBytes' を適切な値に設定してください。

@node 別の format スタイルを利用する,LogRecord のカスタマイズ,ファイルをローテートする,Logging クックブック
@anchor{howto/logging-cookbook format-styles}@anchor{577b}@anchor{howto/logging-cookbook use-of-alternative-formatting-styles}@anchor{577c}
@subsection 別の format スタイルを利用する


logging が Python 標準ライブラリに追加された時、メッセージを動的な内容でフォーマットする唯一の方法は % を使ったフォーマットでした。その後、 Python には新しい文字列フォーマット機構として @ref{897,,string.Template} (Python 2.4 で追加) と @ref{833,,str.format()} (Python 2.6 で追加) が加わりました。

logging は (3.2 から) この2つの追加されたフォーマット方法をサポートしています。 @ref{16b0,,Formatter} クラスが @code{style} という名前のオプションのキーワード引数を受け取ります。このデフォルト値は @code{'%'} ですが、他に @code{'@{'} と @code{'$'} が指定可能で、それぞれのフォーマット方法に対応しています。後方互換性はデフォルト値によって維持されていますが、明示的に style 引数を指定することで、 @ref{833,,str.format()} か @ref{897,,string.Template} を使った format を指定する事ができます。次の例はこの機能を使ってみています:

@example
>>> import logging
>>> root = logging.getLogger()
>>> root.setLevel(logging.DEBUG)
>>> handler = logging.StreamHandler()
>>> bf = logging.Formatter('@{asctime@} @{name@} @{levelname:8s@} @{message@}',
...                        style='@{')
>>> handler.setFormatter(bf)
>>> root.addHandler(handler)
>>> logger = logging.getLogger('foo.bar')
>>> logger.debug('This is a DEBUG message')
2010-10-28 15:11:55,341 foo.bar DEBUG    This is a DEBUG message
>>> logger.critical('This is a CRITICAL message')
2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
>>> df = logging.Formatter('$asctime $name $@{levelname@} $message',
...                        style='$')
>>> handler.setFormatter(df)
>>> logger.debug('This is a DEBUG message')
2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
>>> logger.critical('This is a CRITICAL message')
2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
>>>
@end example

最終的に出力されるログメッセージの format と、各メッセージを生成する部分は完全に独立していることに注意してください。次の例でわかるように、メッセージを生成する部分では % を使い続けています:

@example
>>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
>>>
@end example

logging の呼び出し (@code{logger.debug()} や @code{logger.info()} など) は、ログメッセージのために位置引数しか受け取らず、キーワード引数はそれを処理するときのオプションを指定するためだけに使われます。 (例えば、 @code{exc_info} キーワード引数を使ってログを取るトレースバック情報を指定したり、 @code{extra} キーワード引数を使ってログに付与する追加のコンテキスト情報を指定します。) logging パッケージは内部で % を使って format 文字列と引数をマージしているので、 @ref{833,,str.format()} や @ref{897,,string.Template} を使って logging を呼び出す事はできません。既存の logging 呼び出しは %-format を使っているので、後方互換性のためにこの部分を変更することはできません。

しかし、@{@} や $ を使ってログメッセージをフォーマットする方法はあります。ログメッセージには任意のオブジェクトを format 文字列として渡すことができ、logging パッケージはそのオブジェクトに対して @code{str()} を使って実際の format 文字列を生成します。次の2つのクラスを見てください:

@example
class BraceMessage:
    def __init__(self, fmt, /, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage:
    def __init__(self, fmt, /, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)
@end example

どちらのクラスも format 文字列の代わりに利用して、 @{@} や $ を使って実際のログの "%(message)s", "@{message@}", "$message" で指定された "message" 部分を生成することができます。これは何かログを取りたいときに常に使うには使いにくいクラス名ですが、 __ (アンダースコア2つ --- @ref{1682,,gettext.gettext()} やその仲間によくエイリアスとして使われるアンダースコア1つと混同しないように) などの使いやすいエイリアスを使うことができます。

上のクラスは Python には含まれませんが、自分のコードにコピペして使うのは簡単です。これらは次の例のようにして利用できます。(上のクラスが @code{wherever} というモジュールで定義されていると仮定します):

@example
>>> from wherever import BraceMessage as __
>>> print(__('Message with @{0@} @{name@}', 2, name='placeholders'))
Message with 2 placeholders
>>> class Point: pass
...
>>> p = Point()
>>> p.x = 0.5
>>> p.y = 0.5
>>> print(__('Message with coordinates: (@{point.x:.2f@}, @{point.y:.2f@})',
...       point=p))
Message with coordinates: (0.50, 0.50)
>>> from wherever import DollarMessage as __
>>> print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
>>>
@end example

上の例ではフォーマットの動作を示すために @code{print()} を使っていますが、もちろん実際にこの方法でログを出力するには @code{logger.debug()} などを使います。

注意点として、この方法には大きなパフォーマンスのペナルティはありません。実際のフォーマット操作は logging の呼び出し時ではなくて、メッセージが実際に handler によって出力されるときに起こります。(出力されないならフォーマットもされません) そのため、この方法で注意しないといけないのは、追加の括弧が書式文字列だけではなく引数も囲わないといけないことだけです。これは __ が @code{@var{XXX}Message} クラスのコンストラクタ呼び出しのシンタックスシュガーでしか無いからです。

次の例のように、 @ref{150d,,LoggerAdapter} を利用して上と似たような効果を実現する方法もあります:

@example
import logging

class Message:
    def __init__(self, fmt, args):
        self.fmt = fmt
        self.args = args

    def __str__(self):
        return self.fmt.format(*self.args)

class StyleAdapter(logging.LoggerAdapter):
    def log(self, level, msg, /, *args, stacklevel=1, **kwargs):
        if self.isEnabledFor(level):
            msg, kwargs = self.process(msg, kwargs)
            self.logger.log(level, Message(msg, args), **kwargs,
                            stacklevel=stacklevel+1)

logger = StyleAdapter(logging.getLogger(__name__))

def main():
    logger.debug('Hello, @{@}', 'world!')

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()
@end example

上のスクリプトは Python 3.8 以降では @code{Hello, world!} というメッセージをログするはずです。

@node LogRecord のカスタマイズ,Subclassing QueueHandler and QueueListener- a ZeroMQ example,別の format スタイルを利用する,Logging クックブック
@anchor{howto/logging-cookbook custom-logrecord}@anchor{577d}@anchor{howto/logging-cookbook customizing-logrecord}@anchor{577e}
@subsection @code{LogRecord} のカスタマイズ


全ての logging イベントは @ref{11e8,,LogRecord} のインスタンスとして表現されます。イベントのログが取られて logger のレベルでフィルタされなかった場合、イベントの情報を含む @ref{11e8,,LogRecord} が生成され、その logger (と、 propagate が無効になるまでの上位 logger) の handler に渡されます。 Python 3.2 までは、この生成が行われているのは2箇所だけでした:


@itemize *

@item 
@ref{3164,,Logger.makeRecord()}: 通常のイベント logging プロセスで呼ばれます。これは @ref{11e8,,LogRecord} を直接読んでインスタンスを生成します。

@item 
@ref{318a,,makeLogRecord()}: LogRecord に追加される属性を含む辞書を渡して呼び出されます。これはネットワーク越しに (pickle 形式で @ref{1164,,SocketHandler} 経由で、あるいは JSON 形式で @ref{102c,,HTTPHandler} 経由で) 辞書を受け取った場合などに利用されます。
@end itemize

そのために @ref{11e8,,LogRecord} で何か特別なことをしたい場合は、次のどちらかをしなければなりません。


@itemize *

@item 
@ref{3164,,Logger.makeRecord()} をオーバーライドした独自の @ref{d46,,Logger} のサブクラスを作り、利用したい logger のどれかがインスタンス化される前に、それを @ref{3199,,setLoggerClass()} を使って登録する。

@item 
@ref{3185,,filter()} メソッドで必要な特殊な処理を行う @ref{1414,,Filter} を logger か handler に追加する。
@end itemize

最初の方法は、複数の異なるライブラリが別々のことをしようとした場合にうまく行きません。各ライブラリが独自の @ref{d46,,Logger} のサブクラスを登録しようとして、最後に登録されたライブラリが生き残ります。

2つ目の方法はほとんどのケースでうまくいきますが、たとえば @ref{11e8,,LogRecord} を特殊化したサブクラスを使うことなどはできません。ライブラリの開発者は利用している logger に適切な filter を設定できますが、新しい logger を作るたびに忘れずに設定しないといけなくなります。 (新しいパッケージやモジュールを追加し、モジュールレベルで次の式を実行することで、新しい logger が作られます)

@example
logger = logging.getLogger(__name__)
@end example

これでは考えることが余計に1つ増えてしまうでしょう。開発者は、最も高いレベルのロガーに取り付けられた @ref{149c,,NullHandler} に、フィルタを追加することもできますが、アプリケーション開発者が、より低いレベルに対するライブラリのロガーにハンドラを取り付けた場合、フィルタは呼び出されません --- 従って、そのハンドラからの出力はライブラリ開発者の意図を反映したものにはなりません。

Python 3.2 以降では、 @ref{11e8,,LogRecord} の生成は、指定できるファクトリ経由になります。ファクトリは callable で、 @ref{318e,,setLogRecordFactory()} で登録でき、 @ref{318d,,getLogRecordFactory()} で現在のファクトリを取得できます。ファクトリは @ref{11e8,,LogRecord} コンストラクタと同じシグネチャで呼び出され、 @ref{11e8,,LogRecord} がデフォルトのファクトリとして設定されています。

このアプローチはカスタムのファクトリが LogRecord の生成のすべての面を制御できるようにしています。たとえば、サブクラスを返したり、次のようなパターンを使って単に属性を追加することができます:

@example
old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)
@end example

このアプローチでは複数の異なるライブラリがファクトリをチェインさせて、お互いに同じ属性を上書きしたり、標準で提供されている属性を意図せず上書きしない限りはうまくいきます。しかし、チェインのつながり全てが、全ての logging の操作に対しての実行時のオーバーヘッドになることを念頭に置き、このテクニックは @ref{1414,,Filter} を利用するだけでは望む結果が得られない場合にのみ使うべきです。

@node Subclassing QueueHandler and QueueListener- a ZeroMQ example,Subclassing QueueHandler and QueueListener- a pynng example,LogRecord のカスタマイズ,Logging クックブック
@anchor{howto/logging-cookbook subclassing-queuehandler-and-queuelistener-a-zeromq-example}@anchor{577f}@anchor{howto/logging-cookbook zeromq-handlers}@anchor{5780}
@subsection Subclassing QueueHandler and QueueListener- a ZeroMQ example


@menu
* Subclass QueueHandler:: 
* Subclass QueueListener:: 

@end menu

@node Subclass QueueHandler,Subclass QueueListener,,Subclassing QueueHandler and QueueListener- a ZeroMQ example
@anchor{howto/logging-cookbook subclass-queuehandler}@anchor{5781}
@subsubsection Subclass @code{QueueHandler}


@ref{1b61,,QueueHandler} のサブクラスを作ってメッセージを他のキュー、例えば ZeroMQ の 'publish' ソケットに送信することができます。下の例では、ソケットを別に作ってそれを handler に ('queue' として) 渡します:

@example
import zmq   # using pyzmq, the Python binding for ZeroMQ
import json  # for serializing records portably

ctx = zmq.Context()
sock = zmq.Socket(ctx, zmq.PUB)  # or zmq.PUSH, or other suitable value
sock.bind('tcp://*:5556')        # or wherever

class ZeroMQSocketHandler(QueueHandler):
    def enqueue(self, record):
        self.queue.send_json(record.__dict__)


handler = ZeroMQSocketHandler(sock)
@end example

もちろん同じことを別の設計でもできます。socket を作るのに必要な情報を handler に渡す例です:

@example
class ZeroMQSocketHandler(QueueHandler):
    def __init__(self, uri, socktype=zmq.PUB, ctx=None):
        self.ctx = ctx or zmq.Context()
        socket = zmq.Socket(self.ctx, socktype)
        socket.bind(uri)
        super().__init__(socket)

    def enqueue(self, record):
        self.queue.send_json(record.__dict__)

    def close(self):
        self.queue.close()
@end example

@node Subclass QueueListener,,Subclass QueueHandler,Subclassing QueueHandler and QueueListener- a ZeroMQ example
@anchor{howto/logging-cookbook subclass-queuelistener}@anchor{5782}
@subsubsection Subclass @code{QueueListener}


@ref{242,,QueueListener} のサブクラスを作って、メッセージを他のキュー、例えば ZeroMQ の 'subscribe' ソケットから取得する事もできます。サンプルです:

@example
class ZeroMQSocketListener(QueueListener):
    def __init__(self, uri, /, *handlers, **kwargs):
        self.ctx = kwargs.get('ctx') or zmq.Context()
        socket = zmq.Socket(self.ctx, zmq.SUB)
        socket.setsockopt_string(zmq.SUBSCRIBE, '@w{'})  # subscribe to everything
        socket.connect(uri)
        super().__init__(socket, *handlers, **kwargs)

    def dequeue(self):
        msg = self.queue.recv_json()
        return logging.makeLogRecord(msg)
@end example

@node Subclassing QueueHandler and QueueListener- a pynng example,辞書ベースで構成する例,Subclassing QueueHandler and QueueListener- a ZeroMQ example,Logging クックブック
@anchor{howto/logging-cookbook pynng-handlers}@anchor{5783}@anchor{howto/logging-cookbook subclassing-queuehandler-and-queuelistener-a-pynng-example}@anchor{5784}
@subsection Subclassing QueueHandler and QueueListener- a @code{pynng} example


In a similar way to the above section, we can implement a listener and handler
using pynng@footnote{https://pypi.org/project/pynng/}, which is a Python binding to
NNG@footnote{https://nng.nanomsg.org/}, billed as a spiritual successor to ZeroMQ.
The following snippets illustrate -- you can test them in an environment which has
@code{pynng} installed. Just for variety, we present the listener first.

@menu
* Subclass QueueListener: Subclass QueueListener<2>. 
* Subclass QueueHandler: Subclass QueueHandler<2>. 

@end menu

@node Subclass QueueListener<2>,Subclass QueueHandler<2>,,Subclassing QueueHandler and QueueListener- a pynng example
@anchor{howto/logging-cookbook id3}@anchor{5785}
@subsubsection Subclass @code{QueueListener}


@example
# listener.py
import json
import logging
import logging.handlers

import pynng

DEFAULT_ADDR = "tcp://localhost:13232"

interrupted = False

class NNGSocketListener(logging.handlers.QueueListener):

    def __init__(self, uri, /, *handlers, **kwargs):
        # Have a timeout for interruptability, and open a
        # subscriber socket
        socket = pynng.Sub0(listen=uri, recv_timeout=500)
        # The b'@w{'} subscription matches all topics
        topics = kwargs.pop('topics', None) or b'@w{'}
        socket.subscribe(topics)
        # We treat the socket as a queue
        super().__init__(socket, *handlers, **kwargs)

    def dequeue(self, block):
        data = None
        # Keep looping while not interrupted and no data received over the
        # socket
        while not interrupted:
            try:
                data = self.queue.recv(block=block)
                break
            except pynng.Timeout:
                pass
            except pynng.Closed:  # sometimes happens when you hit Ctrl-C
                break
        if data is None:
            return None
        # Get the logging event sent from a publisher
        event = json.loads(data.decode('utf-8'))
        return logging.makeLogRecord(event)

    def enqueue_sentinel(self):
        # Not used in this implementation, as the socket isn't really a
        # queue
        pass

logging.getLogger('pynng').propagate = False
listener = NNGSocketListener(DEFAULT_ADDR, logging.StreamHandler(), topics=b'@w{'})
listener.start()
print('Press Ctrl-C to stop.')
try:
    while True:
        pass
except KeyboardInterrupt:
    interrupted = True
finally:
    listener.stop()
@end example

@node Subclass QueueHandler<2>,,Subclass QueueListener<2>,Subclassing QueueHandler and QueueListener- a pynng example
@anchor{howto/logging-cookbook id4}@anchor{5786}
@subsubsection Subclass @code{QueueHandler}


@example
# sender.py
import json
import logging
import logging.handlers
import time
import random

import pynng

DEFAULT_ADDR = "tcp://localhost:13232"

class NNGSocketHandler(logging.handlers.QueueHandler):

    def __init__(self, uri):
        socket = pynng.Pub0(dial=uri, send_timeout=500)
        super().__init__(socket)

    def enqueue(self, record):
        # Send the record as UTF-8 encoded JSON
        d = dict(record.__dict__)
        data = json.dumps(d)
        self.queue.send(data.encode('utf-8'))

    def close(self):
        self.queue.close()

logging.getLogger('pynng').propagate = False
handler = NNGSocketHandler(DEFAULT_ADDR)
# Make sure the process ID is in the output
logging.basicConfig(level=logging.DEBUG,
                    handlers=[logging.StreamHandler(), handler],
                    format='%(levelname)-8s %(name)10s %(process)6s %(message)s')
levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
          logging.CRITICAL)
logger_names = ('myapp', 'myapp.lib1', 'myapp.lib2')
msgno = 1
while True:
    # Just randomly select some loggers and levels and log away
    level = random.choice(levels)
    logger = logging.getLogger(random.choice(logger_names))
    logger.log(level, 'Message no. %5d' % msgno)
    msgno += 1
    delay = random.random() * 2 + 0.5
    time.sleep(delay)
@end example

You can run the above two snippets in separate command shells. If we run the
listener in one shell and run the sender in two separate shells, we should see
something like the following. In the first sender shell:

@example
$ python sender.py
DEBUG         myapp    613 Message no.     1
WARNING  myapp.lib2    613 Message no.     2
CRITICAL myapp.lib2    613 Message no.     3
WARNING  myapp.lib2    613 Message no.     4
CRITICAL myapp.lib1    613 Message no.     5
DEBUG         myapp    613 Message no.     6
CRITICAL myapp.lib1    613 Message no.     7
INFO     myapp.lib1    613 Message no.     8
(and so on)
@end example

In the second sender shell:

@example
$ python sender.py
INFO     myapp.lib2    657 Message no.     1
CRITICAL myapp.lib2    657 Message no.     2
CRITICAL      myapp    657 Message no.     3
CRITICAL myapp.lib1    657 Message no.     4
INFO     myapp.lib1    657 Message no.     5
WARNING  myapp.lib2    657 Message no.     6
CRITICAL      myapp    657 Message no.     7
DEBUG    myapp.lib1    657 Message no.     8
(and so on)
@end example

In the listener shell:

@example
$ python listener.py
Press Ctrl-C to stop.
DEBUG         myapp    613 Message no.     1
WARNING  myapp.lib2    613 Message no.     2
INFO     myapp.lib2    657 Message no.     1
CRITICAL myapp.lib2    613 Message no.     3
CRITICAL myapp.lib2    657 Message no.     2
CRITICAL      myapp    657 Message no.     3
WARNING  myapp.lib2    613 Message no.     4
CRITICAL myapp.lib1    613 Message no.     5
CRITICAL myapp.lib1    657 Message no.     4
INFO     myapp.lib1    657 Message no.     5
DEBUG         myapp    613 Message no.     6
WARNING  myapp.lib2    657 Message no.     6
CRITICAL      myapp    657 Message no.     7
CRITICAL myapp.lib1    613 Message no.     7
INFO     myapp.lib1    613 Message no.     8
DEBUG    myapp.lib1    657 Message no.     8
(and so on)
@end example

As you can see, the logging from the two sender processes is interleaved in the
listener's output.

@node 辞書ベースで構成する例,rotator と namer を使ってログローテートをカスタマイズする,Subclassing QueueHandler and QueueListener- a pynng example,Logging クックブック
@anchor{howto/logging-cookbook an-example-dictionary-based-configuration}@anchor{5787}
@subsection 辞書ベースで構成する例


次の例は辞書を使った logging の構成です。この例は Django プロジェクトのドキュメント@footnote{https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging} から持ってきました。この辞書を @ref{13c8,,dictConfig()} に渡して設定を有効にします:

@example
LOGGING = @{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': @{
        'verbose': @{
            'format': '@{levelname@} @{asctime@} @{module@} @{process:d@} @{thread:d@} @{message@}',
            'style': '@{',
        @},
        'simple': @{
            'format': '@{levelname@} @{message@}',
            'style': '@{',
        @},
    @},
    'filters': @{
        'special': @{
            '()': 'project.logging.SpecialFilter',
            'foo': 'bar',
        @},
    @},
    'handlers': @{
        'console': @{
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        @},
        'mail_admins': @{
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['special']
        @}
    @},
    'loggers': @{
        'django': @{
            'handlers': ['console'],
            'propagate': True,
        @},
        'django.request': @{
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        @},
        'myproject.custom': @{
            'handlers': ['console', 'mail_admins'],
            'level': 'INFO',
            'filters': ['special']
        @}
    @}
@}
@end example

この構成方法についてのより詳しい情報は、 Django のドキュメントの 該当のセクション@footnote{https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging} で見ることができます。

@node rotator と namer を使ってログローテートをカスタマイズする,より手の込んだ multiprocessing の例,辞書ベースで構成する例,Logging クックブック
@anchor{howto/logging-cookbook cookbook-rotator-namer}@anchor{31e4}@anchor{howto/logging-cookbook using-a-rotator-and-namer-to-customize-log-rotation-processing}@anchor{5788}
@subsection rotator と namer を使ってログローテートをカスタマイズする


namer と rotator を定義する方法の例は以下の実行可能なスクリプトに示されています。ここではログファイルを gzip により圧縮する例を示しています:

@example
import gzip
import logging
import logging.handlers
import os
import shutil

def namer(name):
    return name + ".gz"

def rotator(source, dest):
    with open(source, 'rb') as f_in:
        with gzip.open(dest, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    os.remove(source)


rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, backupCount=5)
rh.rotator = rotator
rh.namer = namer

root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(rh)
f = logging.Formatter('%(asctime)s %(message)s')
rh.setFormatter(f)
for i in range(1000):
    root.info(f'Message no. @{i + 1@}')
@end example

このスクリプトを実行すると、6つの新しいファイルが生成され、そのうち5つは圧縮されています:

@example
$ ls rotated.log*
rotated.log       rotated.log.2.gz  rotated.log.4.gz
rotated.log.1.gz  rotated.log.3.gz  rotated.log.5.gz
$ zcat rotated.log.1.gz
2023-01-20 02:28:17,767 Message no. 996
2023-01-20 02:28:17,767 Message no. 997
2023-01-20 02:28:17,767 Message no. 998
@end example

@node より手の込んだ multiprocessing の例,SysLogHandler に送るメッセージに BOM を挿入する,rotator と namer を使ってログローテートをカスタマイズする,Logging クックブック
@anchor{howto/logging-cookbook a-more-elaborate-multiprocessing-example}@anchor{5789}
@subsection より手の込んだ multiprocessing の例


次の実際に動作する例は、logging を multiprocessing と設定ファイルを使って利用する方法を示しています。設定内容はかなりシンプルですが、より複雑な構成を実際の multiprocessing を利用するシナリオで実装する方法を示しています。

この例では、メインプロセスは listener プロセスといくつかのワーカープロセスを起動します。メイン、listener、ワーカープロセスはそれぞれ分離した設定を持っています (ワーカープロセス群は同じ設定を共有します)。この例から、メインプロセスの logging, ワーカーが QueueHandler でログを送っているところ、listener が利用する QueueListener の実装、複雑な設定、キューから受け取ったイベントを設定された handler に分配する部分を見ることができます。この設定は説明用のものですが、この例を自分のシナリオに適応させることができるでしょう。

これがそのスクリプトです。docstring とコメントで動作を説明しています:

@example
import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue, Event, current_process
import os
import random
import time

class MyHandler:
    """
    A simple handler for logging events. It runs in the listener process and
    dispatches events to loggers based on the name in the received record,
    which then get dispatched, by the logging system, to the handlers
    configured for those loggers.
    """

    def handle(self, record):
        if record.name == "root":
            logger = logging.getLogger()
        else:
            logger = logging.getLogger(record.name)

        if logger.isEnabledFor(record.levelno):
            # The process name is transformed just to show that it's the listener
            # doing the logging to files and console
            record.processName = '%s (for %s)' % (current_process().name, record.processName)
            logger.handle(record)

def listener_process(q, stop_event, config):
    """
    This could be done in the main process, but is just done in a separate
    process for illustrative purposes.

    This initialises logging according to the specified configuration,
    starts the listener and waits for the main process to signal completion
    via the event. The listener is then stopped, and the process exits.
    """
    logging.config.dictConfig(config)
    listener = logging.handlers.QueueListener(q, MyHandler())
    listener.start()
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    stop_event.wait()
    listener.stop()

def worker_process(config):
    """
    A number of these are spawned for the purpose of illustration. In
    practice, they could be a heterogeneous bunch of processes rather than
    ones which are identical to each other.

    This initialises logging according to the specified configuration,
    and logs a hundred messages with random levels to randomly selected
    loggers.

    A small sleep is added to allow other processes a chance to run. This
    is not strictly needed, but it mixes the output from the different
    processes a bit more than if it's left out.
    """
    logging.config.dictConfig(config)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)
        time.sleep(0.01)

def main():
    q = Queue()
    # The main process gets a simple configuration which prints to the console.
    config_initial = @{
        'version': 1,
        'handlers': @{
            'console': @{
                'class': 'logging.StreamHandler',
                'level': 'INFO'
            @}
        @},
        'root': @{
            'handlers': ['console'],
            'level': 'DEBUG'
        @}
    @}
    # The worker process configuration is just a QueueHandler attached to the
    # root logger, which allows all messages to be sent to the queue.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_worker = @{
        'version': 1,
        'disable_existing_loggers': True,
        'handlers': @{
            'queue': @{
                'class': 'logging.handlers.QueueHandler',
                'queue': q
            @}
        @},
        'root': @{
            'handlers': ['queue'],
            'level': 'DEBUG'
        @}
    @}
    # The listener process configuration shows that the full flexibility of
    # logging configuration is available to dispatch events to handlers however
    # you want.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_listener = @{
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': @{
            'detailed': @{
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            @},
            'simple': @{
                'class': 'logging.Formatter',
                'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            @}
        @},
        'handlers': @{
            'console': @{
                'class': 'logging.StreamHandler',
                'formatter': 'simple',
                'level': 'INFO'
            @},
            'file': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed'
            @},
            'foofile': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed'
            @},
            'errors': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'formatter': 'detailed',
                'level': 'ERROR'
            @}
        @},
        'loggers': @{
            'foo': @{
                'handlers': ['foofile']
            @}
        @},
        'root': @{
            'handlers': ['console', 'file', 'errors'],
            'level': 'DEBUG'
        @}
    @}
    # Log some initial events, just to show that logging in the parent works
    # normally.
    logging.config.dictConfig(config_initial)
    logger = logging.getLogger('setup')
    logger.info('About to create workers ...')
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1),
                     args=(config_worker,))
        workers.append(wp)
        wp.start()
        logger.info('Started worker: %s', wp.name)
    logger.info('About to create listener ...')
    stop_event = Event()
    lp = Process(target=listener_process, name='listener',
                 args=(q, stop_event, config_listener))
    lp.start()
    logger.info('Started listener')
    # We now hang around for the workers to finish their work.
    for wp in workers:
        wp.join()
    # Workers all done, listening can now stop.
    # Logging in the parent still works normally.
    logger.info('Telling listener to stop ...')
    stop_event.set()
    lp.join()
    logger.info('All done.')

if __name__ == '__main__':
    main()
@end example

@node SysLogHandler に送るメッセージに BOM を挿入する,構造化ログを実装する,より手の込んだ multiprocessing の例,Logging クックブック
@anchor{howto/logging-cookbook inserting-a-bom-into-messages-sent-to-a-sysloghandler}@anchor{578a}
@subsection SysLogHandler に送るメッセージに BOM を挿入する


@geindex RFC; RFC 5424
RFC 5424@footnote{https://datatracker.ietf.org/doc/html/rfc5424.html} は syslog デーモンに Unicode メッセージを送る時、次の構造を要求しています: オプショナルなピュア ASCII部分、続けて UTF-8 の Byte Order Mark (BOM)、続けて UTF-8 でエンコードされた Unicode. ( 
@geindex RFC; RFC 5424 Section 6
仕様の該当セクション@footnote{https://datatracker.ietf.org/doc/html/rfc5424.html#section-6} を参照)

Python 3.1 で @ref{86c,,SysLogHandler} に、 message に BOM を挿入するコードが追加されました。しかし、そのときの実装が悪くて、 message の先頭に BOM をつけてしまうのでピュアASCII 部分をその前に書くことができませんでした。

この動作は壊れているので、Python 3.2.4 以降では BOM を挿入するコードが、削除されました。書き直されるのではなく削除されたので、 
@geindex RFC; RFC 5424
RFC 5424@footnote{https://datatracker.ietf.org/doc/html/rfc5424.html} 準拠の、BOM と、オプションのピュア ASCII部分をBOMの前に、任意の Unicode を BOM の後ろに持つ UTF-8 でエンコードされた message を生成したい場合、次の手順に従う必要があります:


@enumerate 

@item 
@ref{86c,,SysLogHandler} のインスタンスに、次のような format 文字列を持った @ref{16b0,,Formatter} インスタンスをアタッチする:

@example
'ASCII section\ufeffUnicode section'
@end example

Unicode のコードポイント U+FEFF は、UTF-8 でエンコードすると BOM -- @code{b'\xef\xbb\xbf'} -- になります。

@item 
ASCII セクションを好きなプレースホルダに変更する。ただしその部分の置換結果が常に ASCII になるように注意する(UTF-8 でエンコードされてもその部分が変化しないようにする)。

@item 
Unicode セクションを任意のプレースホルダに置き換える。この部分を置換したデータに ASCII 外の文字が含まれていても、それは単に UTF-8 でエンコードされるだけです。
@end enumerate

フォーマットされた message は @code{SysLogHandler} によって UTF-8 でエンコードされます。上のルールに従えば、RFC 5424 準拠のメッセージを生成できます。上のルールに従わない場合、logging は何もエラーを起こしませんが、message は 
@geindex RFC; RFC 5424
RFC 5424@footnote{https://datatracker.ietf.org/doc/html/rfc5424.html} に準拠しない形で送られるので、syslog デーモン側で何かエラーが起こる可能性があります。

@node 構造化ログを実装する,handler を dictConfig を使ってカスタマイズする,SysLogHandler に送るメッセージに BOM を挿入する,Logging クックブック
@anchor{howto/logging-cookbook implementing-structured-logging}@anchor{578b}
@subsection 構造化ログを実装する


多くのログメッセージは人間が読むために書かれるため、機械的に処理しにくくなっていますが、場合によっては (複雑な正規表現を使ってログメッセージをパースしなくても) プログラムがパース `できる' 構造化されたフォーマットでメッセージを出力したい場合があります。
logging パッケージを使うと、これを簡単に実現できます。
実現する方法は幾つもありますが、次の例は JSON を使ってイベントを、機械でパースできる形にシリアライズする単純な方法です:

@example
import json
import logging

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        return '%s >>> %s' % (self.message, json.dumps(self.kwargs))

_ = StructuredMessage   # optional, to improve readability

logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
@end example

上のスクリプトを実行すると次のように出力されます:

@example
message 1 >>> @{"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"@}
@end example

要素の順序は Python のバージョンによって異なることに注意してください。

より特殊な処理が必要な場合、次の例のように、カスタムの JSON エンコーダを作ることができます:

@example
import json
import logging


class Encoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, set):
            return tuple(o)
        elif isinstance(o, str):
            return o.encode('unicode_escape').decode('ascii')
        return super().default(o)

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        s = Encoder().encode(self.kwargs)
        return '%s >>> %s' % (self.message, s)

_ = StructuredMessage   # optional, to improve readability

def main():
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logging.info(_('message 1', set_value=@{1, 2, 3@}, snowman='\u2603'))

if __name__ == '__main__':
    main()
@end example

上のスクリプトを実行すると次のように出力されます:

@example
message 1 >>> @{"snowman": "\u2603", "set_value": [1, 2, 3]@}
@end example

要素の順序は Python のバージョンによって異なることに注意してください。

@node handler を dictConfig を使ってカスタマイズする,固有の書式化スタイルをアプリケーション全体で使う,構造化ログを実装する,Logging クックブック
@anchor{howto/logging-cookbook custom-handlers}@anchor{578c}@anchor{howto/logging-cookbook customizing-handlers-with-dictconfig}@anchor{578d}
@subsection handler を @code{dictConfig()} を使ってカスタマイズする


logging handler に特定のカスタマイズを何度もしたい場合で、 @ref{13c8,,dictConfig()} を使っているなら、サブクラスを作らなくてもカスタマイズが可能です。例えば、ログファイルの owner を設定したいとします。これは POSIX 環境では @ref{548,,shutil.chown()} を使って簡単に実現できますが、標準ライブラリの file handler はこの機能を組み込みでサポートしていません。 handler の生成を通常の関数を使ってカスタマイズすることができます:

@example
def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)
@end example

そして、 @ref{13c8,,dictConfig()} に渡される構成設定の中で、この関数を使って logging handler を生成するように指定することができます:

@example
LOGGING = @{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': @{
        'default': @{
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        @},
    @},
    'handlers': @{
        'file':@{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        @},
    @},
    'root': @{
        'handlers': ['file'],
        'level': 'DEBUG',
    @},
@}
@end example

この例は説明用のものですが、owner の user と group を @code{pulse} に設定しています。これを動くスクリプトに @code{chowntest.py} に組み込んでみます:

@example
import logging, logging.config, os, shutil

def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)

LOGGING = @{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': @{
        'default': @{
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        @},
    @},
    'handlers': @{
        'file':@{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        @},
    @},
    'root': @{
        'handlers': ['file'],
        'level': 'DEBUG',
    @},
@}

logging.config.dictConfig(LOGGING)
logger = logging.getLogger('mylogger')
logger.debug('A debug message')
@end example

これを実行するには、 @code{root} 権限で実行する必要があるかもしれません:

@example
$ sudo python3.3 chowntest.py
$ cat chowntest.log
2013-11-05 09:34:51,128 DEBUG mylogger A debug message
$ ls -l chowntest.log
-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
@end example

@ref{548,,shutil.chown()} が追加されたのが Python 3.3 からなので、この例は Python 3.3 を使っています。このアプローチ自体は @ref{13c8,,dictConfig()} をサポートした全ての Python バージョン - Python 2.7, 3.2 以降 - で利用できます。 3.3 以前のバージョンでは、オーナーを変更するのに @ref{1306,,os.chown()} を利用する必要があるでしょう。

実際には、handler を生成する関数はプロジェクト内のどこかにあるユーティリティモジュールに置くことになるでしょう。設定の中で直接関数を参照する代わりに:

@example
'()': owned_file_handler,
@end example

次のように書くこともできます:

@example
'()': 'ext://project.util.owned_file_handler',
@end example

@code{project.util} は関数がある実際の場所に置き換えてください。上のスクリプトでは @code{'ext://__main__.owned_file_handler'} で動くはずです。 @ref{13c8,,dictConfig()} は @code{ext://} から実際の callable を見つけます。

この例は他のファイルに対する変更を実装する例にもなっています。例えば @ref{529,,os.chmod()} を使って、同じ方法で POSIX パーミッションを設定できるでしょう。

もちろん、このアプローチは @ref{1c53,,FileHandler} 以外の handler 、ローテートする file handler のいずれかやその他の handler にも適用できます。

@node 固有の書式化スタイルをアプリケーション全体で使う,filter を dictConfig を使ってカスタマイズする,handler を dictConfig を使ってカスタマイズする,Logging クックブック
@anchor{howto/logging-cookbook formatting-styles}@anchor{317b}@anchor{howto/logging-cookbook using-particular-formatting-styles-throughout-your-application}@anchor{578e}
@subsection 固有の書式化スタイルをアプリケーション全体で使う


Python 3.2 では、@ref{16b0,,Formatter} クラスが @code{style} という名前のオプションのキーワード引数を受け取ります。このデフォルト値は後方互換性を維持するために @code{%} となっていますが、 @code{@{} か @code{$}  を指定することで、@ref{833,,str.format()} か @ref{897,,string.Template} でサポートされているのと同じ書式化のアプローチを採れます。これは最終的に出力されるログメッセージの書式化に影響を与えますが、個々のログメッセージが構築される方法とは完全に直交していることに注意してください。

ロギングの呼び出し (@ref{102b,,debug()}, @ref{20dd,,info()} など) はログメッセージのためには位置引数しか取らず、ロギングの呼び出しを処理する方法を決定するためだけにキーワード引数を指定できます (たとえば @code{exc_info} キーワード引数はトレースバックの情報をログに含めるかどうかを指定し、 @code{extra} キーワード引数はログに付加する追加のコンテキスト情報を指定します)。ロギングパッケージは内部で %-format を使って書式文字列に可変長引数を埋め込んでいるため、 @ref{833,,str.format()} や @ref{897,,string.Template} の構文を使って直接ロギングの呼び出しを行うことはできません。既存のコードにおける全てのロギングの呼び出しは %-format 文字列を使っているため、後方互換性を維持する限りこの部分が変更されることはないでしょう。

特定のロガーに関連付ける書式スタイルへの提案がなされてきましたが、そのアプローチは同時に後方互換性の問題にぶち当たります。あらゆる既存のコードはロガーの名前を使っているでしょうし、 % 形式書式化を使っているでしょう。

あらゆるサードパーティのライブラリ、あらゆるあなたのコードの間で相互運用可能なようにロギングを行うには、書式化についての決定は、個々のログ呼び出しのレベルで行う必要があります。これは受け容れ可能な代替書式化スタイルに様々な手段の可能性を広げます。

@menu
* LogRecord ファクトリを使う:: 
* カスタムなメッセージオブジェクトを使う:: 

@end menu

@node LogRecord ファクトリを使う,カスタムなメッセージオブジェクトを使う,,固有の書式化スタイルをアプリケーション全体で使う
@anchor{howto/logging-cookbook using-logrecord-factories}@anchor{578f}
@subsubsection LogRecord ファクトリを使う


Python 3.2 において、上述した @ref{16b0,,Formatter} の変更とともに、 @ref{318e,,setLogRecordFactory()} 関数を使って @ref{11e8,,LogRecord} のサブクラスをユーザに指定することを可能にするロギングパッケージの機能拡張がありました。これにより、 @ref{318c,,getMessage()} をオーバライドして た　だ　し　い　ことをする、あなた自身の手による @ref{11e8,,LogRecord} のサブクラスをセットすることが出来ます。このメソッドの実装は基底クラスでは @code{msg % args} 書式化をし、あなたの代替の書式化の置換が出来る場所ですが、他のコードとの相互運用性を保障するために、全ての書式化スタイルをサポートするよう注意深く行うべきであり、また、%-書式化をデフォルトで認めるべきです。基底クラスの実装がそうしているように、 @code{str(self.msg)} 呼び出しもしてください。

さらに詳しい情報は、リファレンスの @ref{318e,,setLogRecordFactory()}, @ref{11e8,,LogRecord} を参照してください。

@node カスタムなメッセージオブジェクトを使う,,LogRecord ファクトリを使う,固有の書式化スタイルをアプリケーション全体で使う
@anchor{howto/logging-cookbook using-custom-message-objects}@anchor{5790}
@subsubsection カスタムなメッセージオブジェクトを使う


あなた独自のログメッセージを構築するのに @{@}- および $- 書式化を使えるようにするための、もうひとつの、おそらくもっと簡単な方法があります。ロギングの際には、あなたはメッセージ書式文字列として、任意のオブジェクトを使えることを(@ref{318b,,任意のオブジェクトをメッセージに使用する} より)思い出してみましょう、そしてロギングパッケージはそのオブジェクトに対して実際の書式文字列を得るために @ref{169,,str()} を呼び出すことも。以下 2 つのクラスを検討してみましょう:

@example
class BraceMessage:
    def __init__(self, fmt, /, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage:
    def __init__(self, fmt, /, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)
@end example

どちらのクラスも format 文字列の代わりに利用して、 @{@} や $ を使って実際のログの “%(message)s”, “@{message@}”, “$message” で指定された "message" 部分を生成することができます。これは何かログを取りたいときに常に使うには使いにくいクラス名ですが、使いやすいようにエイリアスを作れば良いでしょう、 @code{M} であるとか @code{_} のような(あるいは地域化のために既に @code{_} を使っているのであれば @code{__} が良いかもしれません)。

このアプローチによる例をお見せします。最初は @ref{833,,str.format()} を使ってフォーマットする例です:

@example
>>> __ = BraceMessage
>>> print(__('Message with @{0@} @{1@}', 2, 'placeholders'))
Message with 2 placeholders
>>> class Point: pass
...
>>> p = Point()
>>> p.x = 0.5
>>> p.y = 0.5
>>> print(__('Message with coordinates: (@{point.x:.2f@}, @{point.y:.2f@})', point=p))
Message with coordinates: (0.50, 0.50)
@end example

2つめは @ref{897,,string.Template} でフォーマットする例です:

@example
>>> __ = DollarMessage
>>> print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
>>>
@end example

注意点として、この方法には大きなパフォーマンスのペナルティはありません。実際のフォーマット操作は logging の呼び出し時ではなくて、メッセージが実際に handler によって出力されるときに起こります。(出力されないならフォーマットもされません) そのため、この方法で注意しないといけないのは、追加の括弧が書式文字列だけではなく引数も囲わないといけないことだけです。これは上記のとおり __ が @code{@var{XXX}Message} クラスのコンストラクタ呼び出しのシンタックスシュガーでしか無いからです。

@node filter を dictConfig を使ってカスタマイズする,例外の書式化をカスタマイズする,固有の書式化スタイルをアプリケーション全体で使う,Logging クックブック
@anchor{howto/logging-cookbook configuring-filters-with-dictconfig}@anchor{5791}@anchor{howto/logging-cookbook filters-dictconfig}@anchor{5792}
@subsection filter を @code{dictConfig()} を使ってカスタマイズする


@ref{13c8,,dictConfig()} によってフィルタを設定 `出来ます' が、どうやってそれを行うのかが初見では明快とは言えないでしょう(そのためのこのレシピです)。 @ref{1414,,Filter} のみが唯一標準ライブラリに含まれているだけですし、それは何の要求にも応えてはくれません(ただの基底クラスですから)ので、典型的には @ref{3185,,filter()} メソッドをオーバライドした @ref{1414,,Filter} のサブクラスをあなた自身で定義する必要があります。これをするには、設定辞書内のフィルタ指定部分に、 @code{()} キーでそのフィルタを作るのに使われる callable を指定してください(クラスを指定するのが最もわかりやすいですが、 @ref{1414,,Filter} インスタンスを返却する callable を提供することでも出来ます)。以下に完全な例を示します:

@example
import logging
import logging.config
import sys

class MyFilter(logging.Filter):
    def __init__(self, param=None):
        self.param = param

    def filter(self, record):
        if self.param is None:
            allow = True
        else:
            allow = self.param not in record.msg
        if allow:
            record.msg = 'changed: ' + record.msg
        return allow

LOGGING = @{
    'version': 1,
    'filters': @{
        'myfilter': @{
            '()': MyFilter,
            'param': 'noshow',
        @}
    @},
    'handlers': @{
        'console': @{
            'class': 'logging.StreamHandler',
            'filters': ['myfilter']
        @}
    @},
    'root': @{
        'level': 'DEBUG',
        'handlers': ['console']
    @},
@}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.debug('hello')
    logging.debug('hello - noshow')
@end example

どのようにして設定データとして、そのインスタンスを構築する callable をキーワードパラメータの形で渡すのか、をこの例は教えてくれます。上記スクリプトは実行すると、このような出力をします:

@example
changed: hello
@end example

設定した通りに動いていますね。

ほかにもいくつか特筆すべき点があります:


@itemize *

@item 
設定内で直接その callable を参照出来ない場合(例えばそれが異なるモジュール内にあり、設定辞書のある場所からそれを直接インポート出来ない、など)には、 @ref{31ba,,外部オブジェクトへのアクセス} に記述されている @code{ext://...} 形式を使えます。例えば、上記例のように @code{MyFilter} と指定する代わりに、 @code{'ext://__main__.MyFilter'} と記述することが出来ます。

@item 
フィルタについてとともに、このテクニックは、カスタムハンドラ、カスタムフォーマッタに対しても同様に使えます。ロギングが設定において、どのようにユーザ定義のオブジェクトをサポートするのかについてのさらなる詳細については、 @ref{31ae,,ユーザ定義オブジェクト} と、本クックブックの上の方のレシピ @ref{578c,,handler を dictConfig() を使ってカスタマイズする} を参照してください。
@end itemize

@node 例外の書式化をカスタマイズする,ロギングメッセージを喋る,filter を dictConfig を使ってカスタマイズする,Logging クックブック
@anchor{howto/logging-cookbook custom-format-exception}@anchor{5793}@anchor{howto/logging-cookbook customized-exception-formatting}@anchor{5794}
@subsection 例外の書式化をカスタマイズする


例外の書式化をカスタマイズしたいことがあるでしょう - わかりやすさのために、例外情報がある場合でもログイベントごとに一行に収まることを死守したいと望むとしましょう。フォーマッタのクラスをカスタマイズして、このように出来ます:

@example
import logging

class OneLineExceptionFormatter(logging.Formatter):
    def formatException(self, exc_info):
        """
        Format an exception so that it prints on a single line.
        """
        result = super().formatException(exc_info)
        return repr(result)  # or format into one line however you want to

    def format(self, record):
        s = super().format(record)
        if record.exc_text:
            s = s.replace('\n', '@w{'}) + '|'
        return s

def configure_logging():
    fh = logging.FileHandler('output.txt', 'w')
    f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
                                  '%d/%m/%Y %H:%M:%S')
    fh.setFormatter(f)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(fh)

def main():
    configure_logging()
    logging.info('Sample message')
    try:
        x = 1 / 0
    except ZeroDivisionError as e:
        logging.exception('ZeroDivisionError: %s', e)

if __name__ == '__main__':
    main()
@end example

実行してみましょう。このように正確に2行の出力を生成します:

@example
28/01/2015 07:21:23|INFO|Sample message|
28/01/2015 07:21:23|ERROR|ZeroDivisionError: division by zero|'Traceback (most recent call last):\n  File "logtest7.py", line 30, in main\n    x = 1 / 0\nZeroDivisionError: division by zero'|
@end example

これは扱いとしては単純過ぎますが、例外情報をどのようにしてあなた好みの書式化出来るかを示しています。さらに特殊なニーズが必要な場合には @ref{104,,traceback} モジュールが有用です。

@node ロギングメッセージを喋る,ロギングメッセージをバッファリングし、条件に従って出力する,例外の書式化をカスタマイズする,Logging クックブック
@anchor{howto/logging-cookbook speaking-logging-messages}@anchor{5795}@anchor{howto/logging-cookbook spoken-messages}@anchor{5796}
@subsection ロギングメッセージを喋る


ロギングメッセージを目で見る形式ではなく音で聴く形式として出力したい、という状況があるかもしれません。これはあなたのシステムで text- to-speech (TTS) 機能が利用可能であれば、容易です。それが Python バインディングを持っていなくとも、です。ほとんどの TTS システムはあなたが実行出来るコマンドラインプログラムを持っていて、このことで、 @ref{dc,,subprocess} を使うことでハンドラが呼び出せます。ここでは、TTS コマンドラインプログラムはユーザとの対話を期待せず、完了には時間がかかり、そしてログメッセージの頻度はユーザをメッセージで圧倒してしまうほどには高くはなく、そして並列で喋るよりはメッセージ一つにつき一回喋ることが受け容れられる、としておきます。ここでお見せする実装例では、次が処理される前に一つのメッセージを喋り終わるまで待ち、結果としてほかのハンドラを待たせることになります。 @code{espeak} TTS パッケージが手許にあるとして、このアプローチによる短い例はこのようなものです:

@example
import logging
import subprocess
import sys

class TTSHandler(logging.Handler):
    def emit(self, record):
        msg = self.format(record)
        # Speak slowly in a female English voice
        cmd = ['espeak', '-s150', '-ven+f3', msg]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        # wait for the program to finish
        p.communicate()

def configure_logging():
    h = TTSHandler()
    root = logging.getLogger()
    root.addHandler(h)
    # the default formatter just returns the message
    root.setLevel(logging.DEBUG)

def main():
    logging.info('Hello')
    logging.debug('Goodbye')

if __name__ == '__main__':
    configure_logging()
    sys.exit(main())
@end example

実行すれば、女性の声で "Hello" に続き "Goodbye" と喋るはずです。

このアプローチは、もちろんほかの TTS システムにも採用出来ますし、メッセージをコマンドライン経由で外部プログラムに渡せるようなものであれば、ほかのシステムであっても全く同じです。

@node ロギングメッセージをバッファリングし、条件に従って出力する,バッファリングしながらロギングメッセージを email で送信する,ロギングメッセージを喋る,Logging クックブック
@anchor{howto/logging-cookbook buffered-logging}@anchor{5797}@anchor{howto/logging-cookbook buffering-logging-messages-and-outputting-them-conditionally}@anchor{5798}
@subsection ロギングメッセージをバッファリングし、条件に従って出力する


メッセージを一次領域に記録し、ある種の特定の状況になった場合にだけ出力したい、ということがあるかもしれません。たとえばある関数内でのデバッグのためのログ出力をしたくても、エラーなしで終了する限りにおいては収集されたデバッグ情報による混雑は喰らいたくはなく、エラーがあった場合にだけエラー出力とともにデバッグ情報を見たいのだ、のようなことがあるでしょう。

このような振る舞いをするロギングをしたい関数に対して、デコレータを用いてこれを行う例をお見せします。それには @ref{31bd,,logging.handlers.MemoryHandler} を使います。これにより何か条件を満たすまでロギングイベントを溜め込むことが出来、条件を満たせば溜め込まれたイベントが @code{flushed} として他のハンドラ (@code{target} のハンドラ)に渡されます。デフォルトでは、 @code{MemoryHandler} はそのバッファが一杯になるか、指定された閾値のレベル以上のイベントが起こるとフラッシュされます。何か特別なフラッシュの振る舞いをしたければ、このレシピはさらに特殊化した @code{MemoryHandler} とともに利用出来ます。

スクリプト例では、 @code{foo} という、単に全てのログレベルについて、 @code{sys.stderr} にもどのレベルを出力したのかについて書き出しながら実際のログ出力も行う、という単純な関数を使っています。 @code{foo} に真を与えると ERROR と CRITICAL の出力をし、そうでなければ DEBUG, INFO, WARNING だけを出力します。

スクリプトが行うことは単に、 @code{foo} を必要とされている特定の条件でのロギングを行うようにするデコレータで修飾することだけです。このデコレータはパラメータとしてロガーを取り、修飾された関数が呼ばれている間だけメモリハンドラをアタッチします。追加のパラメータとして、ターゲットのハンドラ、フラッシュが発生すべきレベル、バッファの容量(バッファされたレコード数)も受け取れます。これらのデフォルトは順に @code{sys.stderr} へ書き出す @ref{1411,,StreamHandler}, @code{logging.ERROR}, @code{100} です。

スクリプトはこれです:

@example
import logging
from logging.handlers import MemoryHandler
import sys

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
    if target_handler is None:
        target_handler = logging.StreamHandler()
    if flush_level is None:
        flush_level = logging.ERROR
    if capacity is None:
        capacity = 100
    handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)

    def decorator(fn):
        def wrapper(*args, **kwargs):
            logger.addHandler(handler)
            try:
                return fn(*args, **kwargs)
            except Exception:
                logger.exception('call failed')
                raise
            finally:
                super(MemoryHandler, handler).flush()
                logger.removeHandler(handler)
        return wrapper

    return decorator

def write_line(s):
    sys.stderr.write('%s\n' % s)

def foo(fail=False):
    write_line('about to log at DEBUG ...')
    logger.debug('Actually logged at DEBUG')
    write_line('about to log at INFO ...')
    logger.info('Actually logged at INFO')
    write_line('about to log at WARNING ...')
    logger.warning('Actually logged at WARNING')
    if fail:
        write_line('about to log at ERROR ...')
        logger.error('Actually logged at ERROR')
        write_line('about to log at CRITICAL ...')
        logger.critical('Actually logged at CRITICAL')
    return fail

decorated_foo = log_if_errors(logger)(foo)

if __name__ == '__main__':
    logger.setLevel(logging.DEBUG)
    write_line('Calling undecorated foo with False')
    assert not foo(False)
    write_line('Calling undecorated foo with True')
    assert foo(True)
    write_line('Calling decorated foo with False')
    assert not decorated_foo(False)
    write_line('Calling decorated foo with True')
    assert decorated_foo(True)
@end example

実行すればこのような出力になるはずです:

@example
Calling undecorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling undecorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
about to log at CRITICAL ...
Calling decorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling decorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
Actually logged at DEBUG
Actually logged at INFO
Actually logged at WARNING
Actually logged at ERROR
about to log at CRITICAL ...
Actually logged at CRITICAL
@end example

見ての通り、実際のログ出力は重要度 ERROR かそれより大きい場合にのみ行っていますが、この場合はそれよりも重要度の低い ERROR よりも前に発生したイベントも出力されます。

当然のことですが、デコレーションはいつものやり方でどうぞ:

@example
@@log_if_errors(logger)
def foo(fail=False):
    ...
@end example

@node バッファリングしながらロギングメッセージを email で送信する,設定によって時刻を UTC GMT で書式化する,ロギングメッセージをバッファリングし、条件に従って出力する,Logging クックブック
@anchor{howto/logging-cookbook buffered-smtp}@anchor{5799}@anchor{howto/logging-cookbook sending-logging-messages-to-email-with-buffering}@anchor{579a}
@subsection バッファリングしながらロギングメッセージを email で送信する


ログメッセージをメールで、特に1つのメールにつき複数のログメッセージを、送信する方法を例示するため、 @ref{3210,,BufferingHandler} を継承します。以下の例は、必要に応じて改変することもできますが、 SMTP 経由でログを送信するのに必要な情報をコマンドライン引数で指定してスクリプトを実行できるように簡単なテストハーネスも提供しています (必須の引数およびオプション引数の詳細を見るためには、ダウンロードしたスクリプトを @code{-h} 引数をつけて実行してください)。

@example
import logging
import logging.handlers
import smtplib

class BufferingSMTPHandler(logging.handlers.BufferingHandler):
    def __init__(self, mailhost, port, username, password, fromaddr, toaddrs,
                 subject, capacity):
        logging.handlers.BufferingHandler.__init__(self, capacity)
        self.mailhost = mailhost
        self.mailport = port
        self.username = username
        self.password = password
        self.fromaddr = fromaddr
        if isinstance(toaddrs, str):
            toaddrs = [toaddrs]
        self.toaddrs = toaddrs
        self.subject = subject
        self.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))

    def flush(self):
        if len(self.buffer) > 0:
            try:
                smtp = smtplib.SMTP(self.mailhost, self.mailport)
                smtp.starttls()
                smtp.login(self.username, self.password)
                msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (self.fromaddr, ','.join(self.toaddrs), self.subject)
                for record in self.buffer:
                    s = self.format(record)
                    msg = msg + s + "\r\n"
                smtp.sendmail(self.fromaddr, self.toaddrs, msg)
                smtp.quit()
            except Exception:
                if logging.raiseExceptions:
                    raise
            self.buffer = []

if __name__ == '__main__':
    import argparse

    ap = argparse.ArgumentParser()
    aa = ap.add_argument
    aa('host', metavar='HOST', help='SMTP server')
    aa('--port', '-p', type=int, default=587, help='SMTP port')
    aa('user', metavar='USER', help='SMTP username')
    aa('password', metavar='PASSWORD', help='SMTP password')
    aa('to', metavar='TO', help='Addressee for emails')
    aa('sender', metavar='SENDER', help='Sender email address')
    aa('--subject', '-s',
       default='Test Logging email from Python logging module (buffering)',
       help='Subject of email')
    options = ap.parse_args()
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    h = BufferingSMTPHandler(options.host, options.port, options.user,
                             options.password, options.sender,
                             options.to, options.subject, 10)
    logger.addHandler(h)
    for i in range(102):
        logger.info("Info index = %d", i)
    h.flush()
    h.close()
@end example

SMTP サーバーを正しく設定した上でスクリプトを実行すると、指定したアドレス宛てに11通のメールを受け取るでしょう。最初の10通のメールはそれぞれ10個のログメッセージを含み、11通目のメールは2つのログメッセージを含むはずです。これらのログメッセージはスクリプト内で指定された102個のログメッセージから構成されています。

@node 設定によって時刻を UTC GMT で書式化する,ロギングの選択にコンテキストマネージャを使う,バッファリングしながらロギングメッセージを email で送信する,Logging クックブック
@anchor{howto/logging-cookbook formatting-times-using-utc-gmt-via-configuration}@anchor{579b}@anchor{howto/logging-cookbook utc-formatting}@anchor{579c}
@subsection 設定によって時刻を UTC(GMT) で書式化する


時刻を UTC でフォーマットしたい場合もあるでしょう。以下に示すように、そのようなフォーマット処理は @code{UTCFormatter} のようなクラスを使って行うことができます:

@example
import logging
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime
@end example

そしてコード中で @code{UTCFormatter} を @ref{16b0,,Formatter} の代わりに使えます。これを設定を通して行いたい場合、 @ref{13c8,,dictConfig()} API を以下の完全な例で示すようなアプローチで使うことが出来ます:

@example
import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = @{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': @{
        'utc': @{
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        @},
        'local': @{
            'format': '%(asctime)s %(message)s',
        @}
    @},
    'handlers': @{
        'console1': @{
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        @},
        'console2': @{
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        @},
    @},
    'root': @{
        'handlers': ['console1', 'console2'],
   @}
@}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('The local time is %s', time.asctime())
@end example

実行すれば、このような出力になるはずです:

@example
2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
@end example

時刻をローカル時刻と UTC の両方に書式化するのに、それぞれのハンドラにそれぞれフォーマッタを与えています。

@node ロギングの選択にコンテキストマネージャを使う,CLIアプリケーションスターターテンプレート,設定によって時刻を UTC GMT で書式化する,Logging クックブック
@anchor{howto/logging-cookbook context-manager}@anchor{579d}@anchor{howto/logging-cookbook using-a-context-manager-for-selective-logging}@anchor{579e}
@subsection ロギングの選択にコンテキストマネージャを使う


一時的にロギングの設定を変えて、作業をした後に設定を戻せると便利なときがあります。
こういうときの、ロギングコンテキストの保存と復元をする方法ではコンテキストマネージャを使うのが一番です。
以下にあるのがそのためのコンテキストマネージャの簡単な例で、これを使うと、任意にロギングレベルを変更し、コンテキストマネージャのスコープ内で他に影響を及ぼさずロギングハンドラを追加できるようになります:

@example
import logging
import sys

class LoggingContext:
    def __init__(self, logger, level=None, handler=None, close=True):
        self.logger = logger
        self.level = level
        self.handler = handler
        self.close = close

    def __enter__(self):
        if self.level is not None:
            self.old_level = self.logger.level
            self.logger.setLevel(self.level)
        if self.handler:
            self.logger.addHandler(self.handler)

    def __exit__(self, et, ev, tb):
        if self.level is not None:
            self.logger.setLevel(self.old_level)
        if self.handler:
            self.logger.removeHandler(self.handler)
        if self.handler and self.close:
            self.handler.close()
        # implicit return of None => don't swallow exceptions
@end example

レベル値を指定した場合、コンテキストマネージャがカバーする with ブロックのスコープ内でロガーのレベルがその値に設定されます。
ハンドラーを指定した場合、ブロックに入るときにロガーに追加され、ブロックから抜けるときに取り除かれます。
ブロックを抜けるときに、自分で追加したハンドラをクローズするようコンテキストマネージャに指示することもできます - そのハンドラがそれ以降必要無いのであればクローズしてしまって構いません。

どのように動作するのかを示すためには、次のコード群を上のコードに付け加えるとよいです:

@example
if __name__ == '__main__':
    logger = logging.getLogger('foo')
    logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.INFO)
    logger.info('1. This should appear just once on stderr.')
    logger.debug('2. This should not appear.')
    with LoggingContext(logger, level=logging.DEBUG):
        logger.debug('3. This should appear once on stderr.')
    logger.debug('4. This should not appear.')
    h = logging.StreamHandler(sys.stdout)
    with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
        logger.debug('5. This should appear twice - once on stderr and once on stdout.')
    logger.info('6. This should appear just once on stderr.')
    logger.debug('7. This should not appear.')
@end example

最初はロガーのレベルを @code{INFO} に設定しているので、メッセージ #1 は現れ、メッセージ #2 は現れません。
次に、その後の @code{with} ブロック内で一時的にレベルを @code{DEBUG} に変更したため、メッセージ #3 が現れます。
そのブロックを抜けた後、ロガーのレベルは @code{INFO} に復元され、メッセージ #4 は現れません。
次の @code{with} ブロック内では、再度レベルを @code{DEBUG} に設定し、 @code{sys.stdout} に書き出すハンドラを追加します。
そのおかげでメッセージ #5 が 2 回 (1回は @code{stderr} を通して、もう1回は @code{stdout} を通して) コンソールに出力されます。
@code{with} 文が完了すると、前の状態になるので (メッセージ #1 のように) メッセージ #6 が現れ、(まさにメッセージ #2 のように) メッセージ #7 は現れません。

出来上がったスクリプトを実行すると、結果は次のようになります:

@example
$ python logctx.py
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.
@end example

@code{stderr} を @code{/dev/null} へパイプした状態でもう一度実行すると、次のようになり、これは @code{stdout} の方に書かれたメッセージだけが現れています:

@example
$ python logctx.py 2>/dev/null
5. This should appear twice - once on stderr and once on stdout.
@end example

@code{stdout} を @code{/dev/null} へパイプした状態でさらにもう一度実行すると、こうなります:

@example
$ python logctx.py >/dev/null
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.
@end example

この場合では、 @code{stdout} の方に出力されたメッセージ #5 は予想通り現れません。

もちろんここで説明した手法は、例えば一時的にロギングフィルターを取り付けたりするのに一般化できます。
上のコードは Python 2 だけでなく Python 3 でも動くことに注意してください。

@node CLIアプリケーションスターターテンプレート,Qt GUIのログ出力,ロギングの選択にコンテキストマネージャを使う,Logging クックブック
@anchor{howto/logging-cookbook a-cli-application-starter-template}@anchor{579f}@anchor{howto/logging-cookbook starter-template}@anchor{57a0}
@subsection CLIアプリケーションスターターテンプレート


ここのサンプルでは次のことを説明します:


@itemize *

@item 
コマンドライン引数に応じてログレベルを使用する

@item 
複数のファイルに分割されたサブコマンドにディスパッチする。すべて一貫して同じレベルでログ出力を行う

@item 
シンプルで最小限の設定で行えるようにする
@end itemize

サービスを停止したり、開始したり、再起動する役割を持ったコマンドラインアプリケーションがあるとします。説明のために、アプリケーションのメインスクリプトが @code{app.py} 、個々のコマンドが @code{start.py} 、 @code{stop.py} 、 @code{restart.py} に実装されているものとします。デフォルトは @code{logging.INFO} ですが、コマンドライン引数を使ってアプリケーションのログの冗長性を制御したいとします。 @code{app.py} は次のコードのようになるでしょう:

@example
import argparse
import importlib
import logging
import os
import sys

def main(args=None):
    scriptname = os.path.basename(__file__)
    parser = argparse.ArgumentParser(scriptname)
    levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
    parser.add_argument('--log-level', default='INFO', choices=levels)
    subparsers = parser.add_subparsers(dest='command',
                                       help='Available commands:')
    start_cmd = subparsers.add_parser('start', help='Start a service')
    start_cmd.add_argument('name', metavar='NAME',
                           help='Name of service to start')
    stop_cmd = subparsers.add_parser('stop',
                                     help='Stop one or more services')
    stop_cmd.add_argument('names', metavar='NAME', nargs='+',
                          help='Name of service to stop')
    restart_cmd = subparsers.add_parser('restart',
                                        help='Restart one or more services')
    restart_cmd.add_argument('names', metavar='NAME', nargs='+',
                             help='Name of service to restart')
    options = parser.parse_args()
    # the code to dispatch commands could all be in this file. For the purposes
    # of illustration only, we implement each command in a separate module.
    try:
        mod = importlib.import_module(options.command)
        cmd = getattr(mod, 'command')
    except (ImportError, AttributeError):
        print('Unable to find the code for command \'%s\'@w{'} % options.command)
        return 1
    # Could get fancy here and load configuration from file or dictionary
    logging.basicConfig(level=options.log_level,
                        format='%(levelname)s %(name)s %(message)s')
    cmd(options)

if __name__ == '__main__':
    sys.exit(main())
@end example

@code{start} 、 @code{stop} 、 @code{restart} コマンドは個別のモジュールとして実装されます。次は起動コマンドのソースです:

@example
# start.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    logger.debug('About to start %s', options.name)
    # actually do the command processing here ...
    logger.info('Started the \'%s\' service.', options.name)
@end example

停止コマンドのソースは次の通りです:

@example
# stop.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = '@w{'}
        services = '\'%s\'@w{'} % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'@w{'} % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to stop %s', services)
    # actually do the command processing here ...
    logger.info('Stopped the %s service%s.', services, plural)
@end example

同様に、再起動のコマンドは次の通りです:

@example
# restart.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = '@w{'}
        services = '\'%s\'@w{'} % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'@w{'} % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to restart %s', services)
    # actually do the command processing here ...
    logger.info('Restarted the %s service%s.', services, plural)
@end example

このアプリケーションをデフォルトのログレベルで実行すると、次のような出力が得られます:

@example
$ python app.py start foo
INFO start Started the 'foo' service.

$ python app.py stop foo bar
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py restart foo bar baz
INFO restart Restarted the 'foo', 'bar' and 'baz' services.
@end example

最初のワードはログレベルで、次のワードはイベントのログ出力が行われたモジュールまたはパッケージ名です。

ログレベルを変更し、ログに出力する情報を変更できるようにしましょう。もし、より詳細な情報が必要だとしましょう:

@example
$ python app.py --log-level DEBUG start foo
DEBUG start About to start foo
INFO start Started the 'foo' service.

$ python app.py --log-level DEBUG stop foo bar
DEBUG stop About to stop 'foo' and 'bar'
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py --log-level DEBUG restart foo bar baz
DEBUG restart About to restart 'foo', 'bar' and 'baz'
INFO restart Restarted the 'foo', 'bar' and 'baz' services.
@end example

あるいは情報を減らしたい場合もあるでしょう:

@example
$ python app.py --log-level WARNING start foo
$ python app.py --log-level WARNING stop foo bar
$ python app.py --log-level WARNING restart foo bar baz
@end example

この場合、コマンドはコンソールに何も出力しなくなります。

@node Qt GUIのログ出力,RFC5424 をサポートする syslog へのロギング,CLIアプリケーションスターターテンプレート,Logging クックブック
@anchor{howto/logging-cookbook a-qt-gui-for-logging}@anchor{57a1}@anchor{howto/logging-cookbook qt-gui}@anchor{57a2}
@subsection Qt GUIのログ出力


A question that comes up from time to time is about how to log to a GUI
application. The Qt@footnote{https://www.qt.io/} framework is a popular
cross-platform UI framework with Python bindings using PySide2@footnote{https://pypi.org/project/PySide2/}
or PyQt5@footnote{https://pypi.org/project/PyQt5/} libraries.

次のサンプルはQt GUIでログ出力を行うサンプルです。ここではシンプルな @code{QtHandler} クラスを作成しています。これは呼び出し可能オブジェクトを受け取ります。これはGUI更新を行うメインスレッドの中で利用されるスロットです。ワーカースレッドも作成し、UI自身からボタンを使ってログを出力したり、バックグラウンドのタスクを行うワーカースレッドからログ出力を行います（ここではランダムな期間にランダムなレベルでメッセージを出しています）。

ワーカースレッドは @ref{f3,,threading} モジュールではなく、Qtの @code{QThread} クラスを使っています。これは他の @code{Qt} コンポーネントとうまく統合できるように、 @code{QThread} を使う必要があるからです。

The code should work with recent releases of any of @code{PySide6}, @code{PyQt6},
@code{PySide2} or @code{PyQt5}. You should be able to adapt the approach to earlier
versions of Qt. Please refer to the comments in the code snippet for more
detailed information.

@example
import datetime
import logging
import random
import sys
import time

# Deal with minor differences between different Qt packages
try:
    from PySide6 import QtCore, QtGui, QtWidgets
    Signal = QtCore.Signal
    Slot = QtCore.Slot
except ImportError:
    try:
        from PyQt6 import QtCore, QtGui, QtWidgets
        Signal = QtCore.pyqtSignal
        Slot = QtCore.pyqtSlot
    except ImportError:
        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)
            try:
                if random.random() < 0.1:
                    raise ValueError('Exception raised: %d' % i)
                else:
                    level = random.choice(LEVELS)
                    logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra)
            except ValueError as e:
                logger.exception('Failed: %s', e, 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')
        if hasattr(f, 'Monospace'):
            f.setStyleHint(f.Monospace)
        else:
            f.setStyleHint(f.StyleHint.Monospace)  # for Qt6
        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()
    if hasattr(app, 'exec'):
        rc = app.exec()
    else:
        rc = app.exec_()
    sys.exit(rc)

if __name__=='__main__':
    main()
@end example

@node RFC5424 をサポートする syslog へのロギング,ロガーを出力ストリームのように取り扱う方法,Qt GUIのログ出力,Logging クックブック
@anchor{howto/logging-cookbook logging-to-syslog-with-rfc5424-support}@anchor{57a3}
@subsection RFC5424 をサポートする syslog へのロギング


@geindex RFC; RFC 5424
RFC 5424@footnote{https://datatracker.ietf.org/doc/html/rfc5424.html} は 2009 年から始まっていますが、ほとんどの syslog サーバーはデフォルトで、 2001 年から使われている古い 
@geindex RFC; RFC 3164
RFC 3164@footnote{https://datatracker.ietf.org/doc/html/rfc3164.html} を使って構成されています。2003年に @code{logging} モジュールが Python に追加されたとき、モジュールは古い (そして当時唯一存在した) プロトコルをサポートしていました。 RFC5424 は、それが登場して以来、 syslog サーバーにおいて広く使われることがなかったために、 @ref{86c,,SysLogHandler} の機能は更新されてきませんでした。

RFC 5424 は構造化データのサポートなど、いくつかの有用な機能を持っています。その機能をサポートする syslog サーバーへのロギングを可能にする必要がある場合、以下のような派生ハンドラクラスを使うことで実現することができます:

@example
import datetime
import logging.handlers
import re
import socket
import time

class SysLogHandler5424(logging.handlers.SysLogHandler):

    tz_offset = re.compile(r'([+-]\d@{2@})(\d@{2@})$')
    escaped = re.compile(r'([\]"\\])')

    def __init__(self, *args, **kwargs):
        self.msgid = kwargs.pop('msgid', None)
        self.appname = kwargs.pop('appname', None)
        super().__init__(*args, **kwargs)

    def format(self, record):
        version = 1
        asctime = datetime.datetime.fromtimestamp(record.created).isoformat()
        m = self.tz_offset.match(time.strftime('%z'))
        has_offset = False
        if m and time.timezone:
            hrs, mins = m.groups()
            if int(hrs) or int(mins):
                has_offset = True
        if not has_offset:
            asctime += 'Z'
        else:
            asctime += f'@{hrs@}:@{mins@}'
        try:
            hostname = socket.gethostname()
        except Exception:
            hostname = '-'
        appname = self.appname or '-'
        procid = record.process
        msgid = '-'
        msg = super().format(record)
        sdata = '-'
        if hasattr(record, 'structured_data'):
            sd = record.structured_data
            # This should be a dict where the keys are SD-ID and the value is a
            # dict mapping PARAM-NAME to PARAM-VALUE (refer to the RFC for what these
            # mean)
            # There's no error checking here - it's purely for illustration, and you
            # can adapt this code for use in production environments
            parts = []

            def replacer(m):
                g = m.groups()
                return '\\' + g[0]

            for sdid, dv in sd.items():
                part = f'[@{sdid@}'
                for k, v in dv.items():
                    s = str(v)
                    s = self.escaped.sub(replacer, s)
                    part += f' @{k@}="@{s@}"'
                part += ']'
                parts.append(part)
            sdata = '@w{'}.join(parts)
        return f'@{version@} @{asctime@} @{hostname@} @{appname@} @{procid@} @{msgid@} @{sdata@} @{msg@}'
@end example

上記のコードを完全に理解するには RFC 5424 を熟知する必要があります。また、上記の例とはやや異なる要求を持つこともあるでしょう (たとえば構造化データをログに渡す方法について)。にもかかわらず、上記のコードは特有の要求に対する順応性があります。上記のハンドラにより、構造化データは以下のように渡すことができるでしょう:

@example
sd = @{
    'foo@@12345': @{'bar': 'baz', 'baz': 'bozz', 'fizz': r'buzz'@},
    'foo@@54321': @{'rab': 'baz', 'zab': 'bozz', 'zzif': r'buzz'@}
@}
extra = @{'structured_data': sd@}
i = 1
logger.debug('Message %d', i, extra=extra)
@end example

@node ロガーを出力ストリームのように取り扱う方法,How to uniformly handle newlines in logging output,RFC5424 をサポートする syslog へのロギング,Logging クックブック
@anchor{howto/logging-cookbook how-to-treat-a-logger-like-an-output-stream}@anchor{57a4}
@subsection ロガーを出力ストリームのように取り扱う方法


書き込み先として file-like オブジェクトを期待するサードパーティの API に接続する必要がある一方で、その API の出力を直接ロガーに送りたいということがときどきあります。これは file-like な API でロガーをラップするクラスを使うことで実現できます。以下はそのようなクラスを例解する短いスクリプトです:

@example
import logging

class LoggerWriter:
    def __init__(self, logger, level):
        self.logger = logger
        self.level = level

    def write(self, message):
        if message != '\n':  # avoid printing bare newlines, if you like
            self.logger.log(self.level, message)

    def flush(self):
        # doesn't actually do anything, but might be expected of a file-like
        # object - so optional depending on your situation
        pass

    def close(self):
        # doesn't actually do anything, but might be expected of a file-like
        # object - so optional depending on your situation. You might want
        # to set a flag so that later calls to write raise an exception
        pass

def main():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger('demo')
    info_fp = LoggerWriter(logger, logging.INFO)
    debug_fp = LoggerWriter(logger, logging.DEBUG)
    print('An INFO message', file=info_fp)
    print('A DEBUG message', file=debug_fp)

if __name__ == "__main__":
    main()
@end example

このスクリプトを実行すると、次のように出力されます。

@example
INFO:demo:An INFO message
DEBUG:demo:A DEBUG message
@end example

また、 @code{sys.stdout} や @code{sys.stderr} をリダイレクトするには @code{LoggerWriter} を使って以下のようにします:

@example
import sys

sys.stdout = LoggerWriter(logger, logging.INFO)
sys.stderr = LoggerWriter(logger, logging.WARNING)
@end example

上記の操作は、必要に応じてロギングを設定した `後に' 行うべきです。上記の例では、 @ref{bf3,,basicConfig()} の呼び出しが (@code{LoggerWriter} インスタンスで上書きされる `前の' @code{sys.stderr} を使って) 設定を行います。そして、以下のような結果を得るでしょう:

@example
>>> print('Foo')
INFO:demo:Foo
>>> print('Bar', file=sys.stderr)
WARNING:demo:Bar
>>>
@end example

言うまでもなく上記の例は @ref{bf3,,basicConfig()} で使われている書式にもとづく出力を示していますが、ロギングの設定で異なるフォーマッタを使うことができます。

上記の例では、バッファリングや奪取した書き込み呼び出しのシーケンスの扱いについてはなすがままになっています。たとえば、上記の @code{LoggerWriter} の定義で、次のようなコードの断片があったとします。

@example
sys.stderr = LoggerWriter(logger, logging.WARNING)
1 / 0
@end example

このスクリプトを実行すると以下のような結果が得られます。

@example
WARNING:demo:Traceback (most recent call last):

WARNING:demo:  File "/home/runner/cookbook-loggerwriter/test.py", line 53, in <module>

WARNING:demo:
WARNING:demo:main()
WARNING:demo:  File "/home/runner/cookbook-loggerwriter/test.py", line 49, in main

WARNING:demo:
WARNING:demo:1 / 0
WARNING:demo:ZeroDivisionError
WARNING:demo::
WARNING:demo:division by zero
@end example

As you can see, this output isn't ideal. That's because the underlying code
which writes to @code{sys.stderr} makes multiple writes, each of which results in a
separate logged line (for example, the last three lines above). To get around
this problem, you need to buffer things and only output log lines when newlines
are seen. Let's use a slightly better implementation of @code{LoggerWriter}:

@example
class BufferingLoggerWriter(LoggerWriter):
    def __init__(self, logger, level):
        super().__init__(logger, level)
        self.buffer = '@w{'}

    def write(self, message):
        if '\n' not in message:
            self.buffer += message
        else:
            parts = message.split('\n')
            if self.buffer:
                s = self.buffer + parts.pop(0)
                self.logger.log(self.level, s)
            self.buffer = parts.pop()
            for part in parts:
                self.logger.log(self.level, part)
@end example

この実装は改行があらわれるまでログをバッファリングし、行全体をログに出力するだけです。このアプローチにより、より適切な出力が得られます:

@example
WARNING:demo:Traceback (most recent call last):
WARNING:demo:  File "/home/runner/cookbook-loggerwriter/main.py", line 55, in <module>
WARNING:demo:    main()
WARNING:demo:  File "/home/runner/cookbook-loggerwriter/main.py", line 52, in main
WARNING:demo:    1/0
WARNING:demo:ZeroDivisionError: division by zero
@end example

@node How to uniformly handle newlines in logging output,避けるべきパターン,ロガーを出力ストリームのように取り扱う方法,Logging クックブック
@anchor{howto/logging-cookbook how-to-uniformly-handle-newlines-in-logging-output}@anchor{57a5}
@subsection How to uniformly handle newlines in logging output


Usually, messages that are logged (say to console or file) consist of a single
line of text. However, sometimes there is a need to handle messages with
multiple lines - whether because a logging format string contains newlines, or
logged data contains newlines. If you want to handle such messages uniformly, so
that each line in the logged message appears uniformly formatted as if it was
logged separately, you can do this using a handler mixin, as in the following
snippet:

@example
# Assume this is in a module mymixins.py
import copy

class MultilineMixin:
    def emit(self, record):
        s = record.getMessage()
        if '\n' not in s:
            super().emit(record)
        else:
            lines = s.splitlines()
            rec = copy.copy(record)
            rec.args = None
            for line in lines:
                rec.msg = line
                super().emit(rec)
@end example

You can use the mixin as in the following script:

@example
import logging

from mymixins import MultilineMixin

logger = logging.getLogger(__name__)

class StreamHandler(MultilineMixin, logging.StreamHandler):
    pass

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-9s %(message)s',
                        handlers = [StreamHandler()])
    logger.debug('Single line')
    logger.debug('Multiple lines:\nfool me once ...')
    logger.debug('Another single line')
    logger.debug('Multiple lines:\n%s', 'fool me ...\ncan\'t get fooled again')
@end example

The script, when run, prints something like:

@example
2025-07-02 13:54:47,234 DEBUG     Single line
2025-07-02 13:54:47,234 DEBUG     Multiple lines:
2025-07-02 13:54:47,234 DEBUG     fool me once ...
2025-07-02 13:54:47,234 DEBUG     Another single line
2025-07-02 13:54:47,234 DEBUG     Multiple lines:
2025-07-02 13:54:47,234 DEBUG     fool me ...
2025-07-02 13:54:47,234 DEBUG     can't get fooled again
@end example

If, on the other hand, you are concerned about log injection@footnote{https://owasp.org/www-community/attacks/Log_Injection}, you can use a
formatter which escapes newlines, as per the following example:

@example
import logging

logger = logging.getLogger(__name__)

class EscapingFormatter(logging.Formatter):
    def format(self, record):
        s = super().format(record)
        return s.replace('\n', r'\n')

if __name__ == '__main__':
    h = logging.StreamHandler()
    h.setFormatter(EscapingFormatter('%(asctime)s %(levelname)-9s %(message)s'))
    logging.basicConfig(level=logging.DEBUG, handlers = [h])
    logger.debug('Single line')
    logger.debug('Multiple lines:\nfool me once ...')
    logger.debug('Another single line')
    logger.debug('Multiple lines:\n%s', 'fool me ...\ncan\'t get fooled again')
@end example

You can, of course, use whatever escaping scheme makes the most sense for you.
The script, when run, should produce output like this:

@example
2025-07-09 06:47:33,783 DEBUG     Single line
2025-07-09 06:47:33,783 DEBUG     Multiple lines:\nfool me once ...
2025-07-09 06:47:33,783 DEBUG     Another single line
2025-07-09 06:47:33,783 DEBUG     Multiple lines:\nfool me ...\ncan't get fooled again
@end example

Escaping behaviour can't be the stdlib default , as it would break backwards
compatibility.

@c patterns-to-avoid:

@node 避けるべきパターン,その他のリソース<2>,How to uniformly handle newlines in logging output,Logging クックブック
@anchor{howto/logging-cookbook patterns-to-avoid}@anchor{57a6}
@subsection 避けるべきパターン


これまでのセクションではログ出力を行うときに必要なこと、考慮すべきことなどを説明してきました。このセクションでは、 `役に立たない' 利用パターンについて触れます。これは多くの場合避けるべきことです。これらの説明はどこから読んでも構いません。

@menu
* 同じログファイルを何度も開く:: 
* ロガーをクラスの属性にするか、パラメータで渡す:: 
* ライブラリ内でロガーに NullHandler 以外のハンドラーを追加する:: 
* 大量のロガーを作成する:: 

@end menu

@node 同じログファイルを何度も開く,ロガーをクラスの属性にするか、パラメータで渡す,,避けるべきパターン
@anchor{howto/logging-cookbook opening-the-same-log-file-multiple-times}@anchor{57a7}
@subsubsection 同じログファイルを何度も開く


Windowsでは同じファイルを何度も開くことができず「このファイルは他のプロセスから利用されています」というエラーが表示されます。しかし、POSIXプラットフォームではエラーがおきることなく、同じファイルを何度も開けます。これは次のように間違って使われる可能性があります。


@itemize *

@item 
同じファイルを指すファイルハンドラを1度以上追加する（例えばコピー＆ペーストして書き換え忘れによるエラー)。

@item 
異なる名前を持つ、一見異なる2つのファイルを開くが、片方が他方へのシンボリックリンクとなっている。

@item 
プロセスをフォークするが、その後親プロセスと子プロセスが同じファイルへの参照を維持する。これは例えば、 @ref{98,,multiprocessing} モジュールなどを使うと発生する可能性があります。
@end itemize

ファイルを複数回開くことは、 `一見' 動作しているように見えますが、さまざまな問題を引き起こす可能性があります:


@itemize *

@item 
複数のスレッドが同一ファイルに書き出そうとすると、ログ出力が文字化けする可能性があります。ログモジュールは同じハンドラーのインスタンスに対して並列で利用しても正しく動くようになっていますが、同じファイルを参照する2つの異なるハンドラーのインスタンスに対し、2つのスレッドから同時に書き込みをした場合にはそのような保護は働きません。

@item 
(たとえばファイルのローテーションの間に) ファイルを削除しようとすると、そのファイルを指す別の参照が残っているために、何のエラーも発しないまま失敗します。これは混乱や不要なデバッグの時間のもととなる可能性があります - ログが思いもしない場所に記録されたり、完全に失われたりします。もしくは移動したと思われていたファイルが残っていたり、ファイルサイズにもとづくローテーションが行われているにもかかわらずファイルサイズが予想外に増加したりすることもあります。
@end itemize

この問題を回避するには @ref{5777,,複数のプロセスからの単一ファイルへのログ記録} で紹介したテクニックを使用してください。

@node ロガーをクラスの属性にするか、パラメータで渡す,ライブラリ内でロガーに NullHandler 以外のハンドラーを追加する,同じログファイルを何度も開く,避けるべきパターン
@anchor{howto/logging-cookbook using-loggers-as-attributes-in-a-class-or-passing-them-as-parameters}@anchor{57a8}
@subsubsection ロガーをクラスの属性にするか、パラメータで渡す


ロガーはシングルトンであるため、一般的には意味がなく、これを行う必要が出てくることは滅多にありません。コードからは名前を使って  @code{logging.getLogger(name)} 経由でロガーインスタンスにアクセスできるため、インスタンスを持って回って、インスタンス属性として保持することは意味がありません。JavaやC#といった他の言語ではよく静的クラス属性にしてます。しかし、Pythonにおいてはこのパターンはクラスではなくモジュールがソフトウェア分解の単位となっているため、無意味です。

@node ライブラリ内でロガーに NullHandler 以外のハンドラーを追加する,大量のロガーを作成する,ロガーをクラスの属性にするか、パラメータで渡す,避けるべきパターン
@anchor{howto/logging-cookbook adding-handlers-other-than-nullhandler-to-a-logger-in-a-library}@anchor{57a9}
@subsubsection ライブラリ内でロガーに @code{NullHandler} 以外のハンドラーを追加する


ハンドラーやフォーマッター、フィルターを追加してログ出力をカスタマイズするのはライブラリ開発者ではなく、アプリケーション開発者の責務です。もしあなたがライブラリのメンテナンスをしているのであれば、 @ref{149c,,NullHandler} インスタンス以外のロガーを追加してはいけない、ということを意味します。

@node 大量のロガーを作成する,,ライブラリ内でロガーに NullHandler 以外のハンドラーを追加する,避けるべきパターン
@anchor{howto/logging-cookbook creating-a-lot-of-loggers}@anchor{57aa}
@subsubsection 大量のロガーを作成する


ロガーはシングルトンであり、スクリプトの実行中に解放されることがないため、大量のロガーを作成すると、メモリが解放されることなく消費されます。ファイルの処理単位やネットワーク接続単位でロガーを作るのではなく、 @ref{3192,,既存のメカニズム} を使ってコンテキスト依存の情報をログに渡し、ロガーはアプリケーション内の説明の単位（通常はモジュールだが、場合によってはそれよりも小さい可能性もある）で作るように制限してください。

@node その他のリソース<2>,,避けるべきパターン,Logging クックブック
@anchor{howto/logging-cookbook cookbook-ref-links}@anchor{5763}@anchor{howto/logging-cookbook other-resources}@anchor{57ab}
@subsection その他のリソース



@subsubheading 参考



@table @asis

@item @ref{8b,,logging} モジュール

logging モジュールの API リファレンス。

@item @ref{8c,,logging.config} モジュール

logging モジュールの環境設定 API です。

@item @ref{8d,,logging.handlers} モジュール

logging モジュールに含まれる、便利なハンドラです。
@end table

@ref{140e,,基本チュートリアル}

@ref{140f,,上級チュートリアル}


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 正規表現 HOWTO,ソケットプログラミング HOWTO,Logging クックブック,Python HOWTO
@anchor{howto/regex doc}@anchor{57ac}@anchor{howto/regex regex-howto}@anchor{2762}@anchor{howto/regex regular-expression-howto}@anchor{57ad}@anchor{howto/regex translation-repo}@anchor{57ae}
@section 正規表現 HOWTO


@*著者: 
A.M. Kuchling <@email{amk@@amk.ca}>


@c TODO:
@c Document lookbehind assertions
@c Better way of displaying a RE, a string, and what it matches
@c Mention optional argument to match.groups()
@c Unicode (at least a reference)

@subsubheading 概要



このドキュメントは @ref{be,,re} モジュールを使って Python で正規表現を扱うための導入のチュートリアルです。ライブラリレファレンスの正規表現の節よりもやさしい入門ドキュメントを用意しています。

@menu
* はじめに: はじめに<16>. 
* 単純なパターン:: 
* 正規表現を使う:: 
* パターンの能力をさらに:: 
* 文字列を変更する:: 
* よくある問題:: 
* フィードバック:: 

@end menu

@node はじめに<16>,単純なパターン,,正規表現 HOWTO
@anchor{howto/regex introduction}@anchor{57af}
@subsection はじめに


正規表現 regular expressions (REs や regexes または regex patterns と呼ばれます) は本質的に小さく、Python 内部に埋め込まれた高度に特化したプログラミング言語で @ref{be,,re} モジュールから利用可能です。この小さな言語を利用することで、マッチさせたい文字列に適合するような文字列の集合を指定することができます; この集合は英文や e-mail アドレスや TeX コマンドなど、どんなものでも構いません。「この文字列は指定したパターンにマッチしますか?」「このパターンはこの文字列のどの部分にマッチするのですか?」といったことを問い合わせることができます。正規表現を使って文字列を変更したりいろいろな方法で別々の部分に分割したりすることもできます。

正規表現パターンは一連のバイトコードとしてコンパイルされ、C で書かれたマッチングエンジンによって実行されます。より進んだ利用法では、エンジンがどう与えられた正規表現を実行するかに注意することが必要になり、高速に実行できるバイトコードを生成するように正規表現を書くことになります。このドキュメントでは最適化までは扱いません、それにはマッチングエンジンの内部に対する十分な理解が必要だからです。

正規表現言語は相対的に小さく、制限されています、そのため正規表現を使ってあらゆる文字列処理作業を行なえるわけではありません。正規表現を使って行うことのできる作業もあります、ただ表現はとても複雑なものになります。それらの場合では、Python コードを書いた方がいいでしょう; Python コードは念入りに作られた正規表現より遅くなりますが、おそらくより読み易いでしょう。

@node 単純なパターン,正規表現を使う,はじめに<16>,正規表現 HOWTO
@anchor{howto/regex simple-patterns}@anchor{57b0}
@subsection 単純なパターン


まずはできるだけ簡単な正規表現を学ぶことから始めてみましょう。正規表現は文字列の操作に使われるので、ますは最も一般的な作業である文字のマッチングをしてみます。

正規表現の基礎を成す計算機科学 (決定、非決定有限オートマトン) の詳細な説明については, コンパイラ作成に関するテキストブックをどれでもいいので参照して下さい。

@menu
* 文字のマッチング:: 
* 繰り返し:: 

@end menu

@node 文字のマッチング,繰り返し,,単純なパターン
@anchor{howto/regex matching-characters}@anchor{57b1}
@subsubsection 文字のマッチング


多くの活字や文字は単純にそれ自身とマッチします。例えば、 @code{test} という正規表現は文字列 @code{test} に厳密にマッチします。(大文字小文字を区別しないモードでその正規表現が @code{Test} や @code{TEST} にも同様にマッチすることもできます; 詳しくは後述します。)

この規則には例外が存在します; いくつかの文字は特別な `特殊文字 (metacharacters)' で、それら自身にマッチしません。代わりに通常のマッチするものとは違うという合図を出したり、正規表現の一部に対して繰り返したり、意味を変えたりして影響を与えます。このドキュメントの中の多くは様々な特殊文字とそれが何をするかについて論じることになります。

ここに特殊文字の完全な一覧があります; これらの意味はこの HOWTO の残りの部分で説明します。

@example
. ^ $ * + ? @{ @} [ ] \ | ( )
@end example

最初に扱う特殊文字は @code{[} と @code{]} です。これらは文字クラスを指定します、文字クラスはマッチしたい文字の集合です。文字は個別にリストにしても構いませんし、二つの文字を @code{'-'} でつなげて文字を範囲で与えてもかまいません。たとえば @code{[abc]} は @code{a}, @code{b}, または @code{c} のどの文字列にもマッチします; これは @code{[a-c]} で同じ文字集合を範囲で表現しても全く同じです。小文字のアルファベットのみにマッチしたい場合、 @code{[a-z]} の正規表現をつかうことになるでしょう。

(@code{\} を除く) 特殊文字は文字クラスの内部では有効になりません。例えば、 @code{[akm$]} は @code{'a'}, @code{'k'}, @code{'m'}, または @code{'@{TX-PL-LABEL@}#x27;} のいずれかにマッチします; @code{'@{TX-PL-LABEL@}#x27;} は通常は特殊文字ですが、文字クラス内部ではその特別な性質は取り除かれます。

`補集合を取る' ことで、文字クラス内のリストにない文字に対してマッチさせられます。
補集合は、クラスの最初の文字として @code{'^'} を含めることで表せます。
例えば、 @code{[^5]} は @code{'5'} 以外の文字にマッチします。
キャレットが文字クラス以外の場所に現れた場合は、特別な意味は持ちません。
例えば、 @code{[5^]} は @code{'5'} や @code{'^'} にマッチします。

おそらく最も重要な特殊文字はバックスラッシュ @code{\} でしょう。 Python の文字列リテラルのようにバックスラッシュに続けていろいろな文字を入力することでいろいろな特殊シーケンスの合図を送ることができます。また、バックスラッシュはすべての特殊文字をエスケープするのにも利用されます、つまり、特殊文字をマッチさせることができます; 例えば、 @code{[} または @code{\} にマッチさせたい場合、それらをバックスラッシュに続けることで特殊な意味を除きます: @code{\[} または @code{\\} 。

@code{'\'} で始まるいくつかの特殊シーケンスは、数字、アルファベット、空白文字以外など、よく使う文字集合を表しています。

一つ例をお見せしましょう: @code{\w} は任意の英数字文字にマッチします。バイト列パターンに対しては、これは文字クラス @code{[a-zA-Z0-9_]} と等価です。ユニコードパターンに対しては、 @code{\w} は @ref{10b,,unicodedata} モジュールで提供されている Unicode データベースで letters としてマークされている全ての文字とマッチします。正規表現のコンパイル時に @ref{83e,,re.ASCII} フラグを与えることにより、 @code{\w} を、より制限された定義で使うことが出来ます。

以下に続く特別な文字列のリストは完全ではありません。特殊シーケンスと拡張クラスについてのユニコードパターンの定義についての完全なリストは、標準ライブラリリファレンスの @ref{92e,,正規表現の構文} の最後のパートを参照してください。一般的にユニコードバージョンは、ユニコードデータベース内で相応しいカテゴリに属すればマッチします。


@table @asis

@item @code{\d}

任意の十進数とマッチします; これは集合 @code{[0-9]} と同じ意味です。

@item @code{\D}

任意の非数字文字とマッチします; これは集合 @code{[^0-9]} と同じ意味です。

@item @code{\s}

任意の空白文字とマッチします; これは集合 @code{[ \t\n\r\f\v]} と同じ意味です。

@item @code{\S}

任意の非空白文字とマッチします; これは集合 @code{[^ \t\n\r\f\v]} と同じ意味です。

@item @code{\w}

任意の英数文字および下線とマッチします; これは、集合 @code{[a-zA-Z0-9_]} と同じ意味です。

@item @code{\W}

任意の非英数文字とマッチします; これは集合 @code{[^a-zA-Z0-9_]} と同じ意味です。
@end table

これらのシーケンスは文字クラス内に含めることができます。例えば、 @code{[\s,.]} は空白文字や @code{','} または @code{'.'} にマッチする文字クラスです。

この節での最後の特殊文字は @code{.} です。
これは改行文字を除く任意の文字にマッチし、さらに改行文字に対してもマッチさせる代替モード (@ref{2763,,re.DOTALL}) があります。
@code{.} は「任意の文字」にマッチさせたい場合に利用されます。

@node 繰り返し,,文字のマッチング,単純なパターン
@anchor{howto/regex repeating-things}@anchor{57b2}
@subsubsection 繰り返し


さまざまな文字集合をマッチさせることは正規表現で最初にできるようになることで、これは文字列に対するメソッドですぐにできることではありません。しかし、正規表現がより力を発揮する場面がこれだけだとすると、正規表現はあまり先進的とはいえません。正規表現の力をもう一つの能力は、正規表現の一部が何度も繰り返されるようものを指定できることです。

最初にとりあげる繰り返しのための最初の特殊文字は @code{*} です。
@code{*} は文字リテラル @code{'*'} とはマッチしません; その代わりに、前の文字がぴったり1回ではなく0回以上繰り返されるパターンを指定します。

例えば、 @code{ca*t} は @code{'ct'} (文字 @code{'a'} が 0 個)、 @code{'cat'} (@code{'a'} が 1 個)、 @code{'caaat'} (@code{'a'} が 3 個)、などにマッチします。

@code{*} のような繰り返しは `貪欲 (greedy)' です; 正規表現を繰り返したいとき、マッチングエンジンは可能な限り何度も繰り返そうと試みます。パターンの後ろの部分にマッチしない場合、マッチングエンジンは戻ってより少ない繰り返しを再び試みます。

一歩ずつ例を進めていくとより明確にわかります。
正規表現 @code{a[bcd]*b} を考えましょう。
この正規表現は文字 @code{'a'} 、文字クラス @code{[bcd]} の 0 個以上の文字、最後に来る @code{'b'} にマッチします。
この正規表現が文字列 @code{'abcbd'} に対してマッチする流れを想像してみましょう。


@multitable {xxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ステップ

@tab

マッチした文字列

@tab

説明

@item

1

@tab

@code{a}

@tab

正規表現の @code{a} がマッチ。

@item

2

@tab

@code{abcbd}

@tab

正規表現エンジンが、文字列の終わりに向かってできるだけ遠くまで @code{[bcd]*} をマッチさせる。

@item

3

@tab

`失敗'

@tab

正規表現エンジンが @code{b} でマッチを試みるが、現在の位置が文字列の最後なので失敗。

@item

4

@tab

@code{abcb}

@tab

@code{[bcd]*} が一文字少なくマッチするように戻る。

@item

5

@tab

`失敗'

@tab

再び @code{b} にマッチするか試みるが、現在の位置は最後の文字 @code{'d'} 。

@item

6

@tab

@code{abc}

@tab

@code{[bcd]*} は @code{bc} のみにマッチするように再び戻る。

@item

6

@tab

@code{abcb}

@tab

再び @code{b} を試みる。今回の現在位置の文字は @code{'b'} なので成功。

@end multitable


正規表現の終端に達して、 @code{'abcd'} にマッチしました。
この説明は、マッチングエンジンが最初に到達できるところまで進みマッチしなかった場合、逐次戻って再度残りの正規表現とのマッチを次々と試みること様子を示しています。
正規表現エンジンは @code{[bcd]*} の 0 回マッチを試すところまで戻り、その後続の正規表現とのマッチに失敗した場合には、エンジンは正規表現と文字列が完全にマッチしないと結論づけることになります。

別の繰り返しのメタ文字には @code{+} があり、この特殊文字は 1 回以上の繰り返しにマッチします。
@code{*} と @code{+} に違いに対しては十分注意して下さい; @code{*} は `0 回' 以上の繰り返しにマッチするので、繰り返す部分が全くなくても問題ありません。一方で @code{+} は少なくとも `1 回' は表われる必要があります。
同様の例を使うと @code{ca+t} は @code{'cat'} (@code{'a'} 1 文字)、 @code{'caaat'} (@code{'a'} 3 文字)、とマッチし、@code{'ct'} とはマッチしません。

繰り返しをあらわす演算子または数量子がさらに2つ存在します。クエスチョンマーク @code{?} は1回または0回の繰り返しにマッチします; これは、何らかの文字やパターンがオプションであることをあらわすと考えられます。例えば、 @code{home-?brew} は @code{'homebrew'} と @code{'home-brew'} のいずれかにマッチします。

最も複雑な数量子は @code{@{m,n@}} でしょう。ここで `m' と `n' は10進数の整数です。この数量子は繰り返しの回数が最小で `m' 回、最大で `n' 回であることを意味します。例えば、 @code{a/@{1,3@}b} は @code{'a/b'}, @code{'a//b'}, および @code{'a///b'} にマッチします。一方でスラッシュのない @code{'ab'} やスラッシュが4つある @code{'a////b'} にはマッチしません。

`m' か `n' のどちらかは省略することができます; その場合は、省略された値は合理的な値が仮定されます。
`m' の省略は下限は 0 と解釈され、`n' の省略は上限は無限として解釈されます。

The simplest case @code{@{m@}} matches the preceding item exactly `m' times.
For example, @code{a/@{2@}b} will only match @code{'a//b'}.

還元主義的傾向のある読者は、他の3つの数量子が全てこの表記を使って表現できることに気づくでしょう。 @code{@{0,@}} は @code{*} と同じであり、 @code{@{1,@}} は @code{+} と等価です。また @code{@{0,1@}} は @code{?} と同じです。とはいえ、簡潔さと読みやすさの観点から、可能であれば @code{*}, @code{+}, @code{?} を使う方が望ましいです。

@node 正規表現を使う,パターンの能力をさらに,単純なパターン,正規表現 HOWTO
@anchor{howto/regex using-regular-expressions}@anchor{57b3}
@subsection 正規表現を使う


これまででいくつかの単純な正規表現に触れてきました、実際に Python ではこれらをどう使えばいいのでしょう? @ref{be,,re} モジュールは正規表現エンジンに対するインターフェースを提供していて、それらを使うことで正規表現をオブジェクトにコンパイルし、マッチを実行することができます。

@menu
* 正規表現をコンパイルする:: 
* バックスラッシュ感染症:: 
* マッチの実行:: 
* モジュールレベルの関数: モジュールレベルの関数<3>. 
* コンパイルフラグ:: 

@end menu

@node 正規表現をコンパイルする,バックスラッシュ感染症,,正規表現を使う
@anchor{howto/regex compiling-regular-expressions}@anchor{57b4}
@subsubsection 正規表現をコンパイルする


正規表現はパターンオブジェクトにコンパイルされます、パターンオブジェクトは多くの操作、パターンマッチの検索や文字列の置換の実行などのメソッドを持っています。

@example
>>> import re
>>> p = re.compile('ab*')
>>> p
re.compile('ab*')
@end example

@ref{dce,,re.compile()} はいくつかの `flags' 引数を受け付けることができます、この引数はさまざまな特別な機能を有効にしたり、構文を変化させたりします。利用できる設定に何があるかは後に飛ばすことにして、簡単な例をやることにしましょう:

@example
>>> p = re.compile('ab*', re.IGNORECASE)
@end example

正規表現は文字列として @ref{dce,,re.compile()} に渡されます。正規表現は文字列として扱われますが、それは正規表現が Python 言語のコアシステムに含まれないためです、そのため正規表現を表わす特殊な構文はありません。 (正規表現を全く必要としないアプリケーションも存在します、そのためそれらを含めて言語仕様を無駄に大きくする必要はありません) その代わり、 @ref{be,,re} モジュールは @ref{d1,,socket} や @ref{139,,zlib} モジュールのような通常の C 拡張モジュールとして Python に含まれています。

正規表現を文字列としておくことで Python 言語はより簡素に保たれていますが、そのため1つの欠点があります、これについては次の節で話題とします。

@node バックスラッシュ感染症,マッチの実行,正規表現をコンパイルする,正規表現を使う
@anchor{howto/regex id1}@anchor{57b5}@anchor{howto/regex the-backslash-plague}@anchor{57b6}
@subsubsection バックスラッシュ感染症


先に述べたように、正規表現は特別な形式や特殊な文字の特別な意味を意味を除くことを示すためにバックスラッシュ文字 (@code{'\'}) を利用します。これは Python が文字列リテラルに対して、同じ文字を同じ目的で使うことと衝突します。

@code{\section} という文字列 (これは LaTeX ファイルでみかけます) にマッチする正規表現を書きたいとします。どんなプログラムを書くか考え、マッチして欲しい文字列をはじめに考えます。次に、バックスラッシュや他の特殊文字をバックスラッシュに続けて書くことでエスケープしなければいけません、その結果 @code{\\section} のような文字列となります。こうしてできた @ref{dce,,re.compile()} に渡す文字列は @code{\\section} でなければいけません。しかし、これを Python の文字列リテラルとして扱うにはこの二つのバックスラッシュを `再び' エスケープする必要があります。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文字

@tab

段階

@item

@code{\section}

@tab

マッチさせるテキスト

@item

@code{\\section}

@tab

@ref{dce,,re.compile()} のためのバックスラッシュエスケープ

@item

@code{"\\\\section"}

@tab

文字列リテラルのためのバックスラッシュエスケープ

@end multitable


要点だけをいえば、リテラルとしてのバックスラッシュにマッチさせるために、正規表現文字列として @code{'\\\\'} と書かなければいけません、なぜなら正規表現は @code{\\} であり、通常の Python の文字列リテラルとしてはそれぞれのバックスラッシュは @code{\\} で表現しなければいけないからです。正規表現に関してこのバックスラッシュの繰り返しの機能は、たくさんのバックスラッシュの繰り返しを生むことになり、その結果として作られる文字列は理解することが難しくなります。

この問題の解決策としては正規表現に対しては Python の raw string 記法を使うことです; @code{'r'} を文字列リテラルの先頭に書くことでバックスラッシュは特別扱いされなくなります、つまり @code{"\n"} は改行を含む1つの文字からなる文字列であるのに対して、 @code{r"\n"} は2つの文字 @code{'\'} と @code{'n'} を含む文字列となります。多くの場合 Python コードの中の正規表現はこの raw string 記法を使って書かれます。

それに加えて、正規表現では有効であるものの Python の文字列リテラルとしては有効でない特殊文字のエスケープシーケンスは、現在では @ref{1a3,,DeprecationWarning} を引き起こし、最終的には @ref{18e,,SyntaxError} となります。すなわち、そのようなシーケンスは raw string 記法を使うか、バックスラッシュによるエスケープを使わないかぎり無効になることを意味します。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

通常の文字列

@tab

Raw string

@item

@code{"ab*"}

@tab

@code{r"ab*"}

@item

@code{"\\\\section"}

@tab

@code{r"\\section"}

@item

@code{"\\w+\\s+\\1"}

@tab

@code{r"\w+\s+\1"}

@end multitable


@node マッチの実行,モジュールレベルの関数<3>,バックスラッシュ感染症,正規表現を使う
@anchor{howto/regex performing-matches}@anchor{57b7}
@subsubsection マッチの実行


一旦コンパイルした正規表現を表現するオブジェクトを作成したら、次に何をしますか? パターンオブジェクトはいくつかのメソッドや属性を持っています。ここでは、その中でも最も重要なものについて扱います; 完全なリストは @ref{be,,re} ドキュメントを参照して下さい。


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

メソッド/属性

@tab

目的

@item

@code{match()}

@tab

文字列の先頭で正規表現とマッチするか判定します。

@item

@code{search()}

@tab

文字列を先頭から走査して、正規表現がどこにマッチするか調べます。

@item

@code{findall()}

@tab

正規表現にマッチする部分文字列を全て探しだしリストとして返します。

@item

@code{finditer()}

@tab

正規表現にマッチする部分文字列を全て探しだし @ref{4c8,,iterator} として返します。

@end multitable


@ref{2774,,match()} と @ref{2775,,search()} はマッチするものが見つからなければ @code{None} を返します。
成功すればそれらは @ref{118a,,Match オブジェクト} のインスタンスを返します。このオブジェクトにはマッチした情報が含まれます: マッチの開始と終了位置、マッチした部分文字列、など。

You can learn about this by interactively experimenting with the @ref{be,,re}
module.

この HOWTO では例として標準の Python インタプリタを使います。最初に Python インタプリタを起動して、 @ref{be,,re} モジュールをインポートし、正規表現をコンパイルします:

@example
>>> import re
>>> p = re.compile('[a-z]+')
>>> p
re.compile('[a-z]+')
@end example

さて、いろいろな文字列を使って正規表現 @code{[a-z]+} に対するマッチングを試してみましょう。空の文字列は全くマッチしません、なぜなら @code{+} は「1 回以上の繰り返し」を意味するからです。この場合では @ref{2774,,match()} は @code{None} を返すべきで、インタプタは何も出力しません。明確にするために @code{match()} の結果を明示的に出力することもできます:

@example
>>> p.match("")
>>> print(p.match(""))
None
@end example

では、今度はマッチするはずの文字列、例えば @code{tempo} を試してみましょう。このケースでは、 @ref{2774,,match()} は @ref{118a,,match object} を返すので、後で使うために結果を変数に記憶しておくべきです。

@example
>>> m = p.match('tempo')
>>> m
<re.Match object; span=(0, 5), match='tempo'>
@end example

これでマッチした文字列についての情報を @ref{118a,,Match オブジェクト} に問い合わせることが出来ます。
Match オブジェクトインスタンスはいくつかのメソッドと属性も持っていて、最も重要なのは次のものです:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

メソッド/属性

@tab

目的

@item

@code{group()}

@tab

正規表現にマッチした文字列を返す

@item

@code{start()}

@tab

マッチの開始位置を返す

@item

@code{end()}

@tab

マッチの終了位置を返す

@item

@code{span()}

@tab

マッチの位置 (start, end) を含むタプルを返す

@end multitable


これらのメソッドを試せば、その意味はすぐに理解できます:

@example
>>> m.group()
'tempo'
>>> m.start(), m.end()
(0, 5)
>>> m.span()
(0, 5)
@end example

@ref{122c,,group()} は正規表現でマッチした部分文字列を返します。 @ref{2787,,start()} と @ref{2788,,end()} はそれぞれ、マッチの開始インデクスと終了インデクスを返します。 @ref{2789,,span()} は開始と終了のインデクスを一つのタプルにして返します。
@ref{2774,,match()} メソッドは正規表現が文字列の開始位置でマッチするかどうかだけをチェックするので、 @code{start()} は必ずゼロを返します。
しかし、 @ref{2775,,search()} メソッドではパターンを文字列全体について走査するので、マッチの開始はゼロにならないかもしれません。

@example
>>> print(p.match('::: message'))
None
>>> m = p.search('::: message'); print(m)
<re.Match object; span=(4, 11), match='message'>
>>> m.group()
'message'
>>> m.span()
(4, 11)
@end example

実際のプログラムでは @ref{118a,,Match オブジェクト} を変数に記憶しておき, その次に @code{None} なのか調べるのが一般的なスタイルです。普通このようにします:

@example
p = re.compile( ... )
m = p.match( 'string goes here' )
if m:
    print('Match found: ', m.group())
else:
    print('No match')
@end example

あるパターンにマッチするもの全てを返す Pattern インスタンスのメソッドが2つあります。
@ref{277b,,findall()} はマッチした文字列のリストを返します:

@example
>>> p = re.compile(r'\d+')
>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
['12', '11', '10']
@end example

この例では、文字列リテラルを raw string リテラルにするプレフィックス @code{r} が必要です。これは、正規表現とは異なり、通常の "調理済み" 文字列リテラルにおけるエスケープシーケンスは Python では認識されないためであり、現在では @ref{1a3,,DeprecationWarning} を引き起こし、最終的には @ref{18e,,SyntaxError} となります。詳しくは @ref{57b6,,バックスラッシュ感染症} を参照してください。

@ref{277b,,findall()} は結果を返す前に完全なリストを必ず生成してしまいます。いっぽう @ref{277c,,finditer()} メソッドは @ref{118a,,マッチオブジェクト} インスタンスのシーケンスを @ref{4c8,,iterator} として返します:

@example
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable_iterator object at 0x...>
>>> for match in iterator:
...     print(match.span())
...
(0, 2)
(22, 24)
(29, 31)
@end example

@node モジュールレベルの関数<3>,コンパイルフラグ,マッチの実行,正規表現を使う
@anchor{howto/regex module-level-functions}@anchor{57b8}
@subsubsection モジュールレベルの関数


パターンオブジェクトを作ってそのメソッドを呼び出す、とする必要は必ずしもありません。 @ref{be,,re} モジュールはトップレベルの関数として @ref{1445,,match()}, @ref{1444,,search()}, @ref{122b,,findall()}, @ref{5a3,,sub()} などを用意しています。これら関数は、対応するメソッドの最初の引数に RE が追加されただけで後は同じで、 @code{None} か @ref{118a,,Match オブジェクト} インスタンスを返すのも同じです:

@example
>>> print(re.match(r'From\s+', 'Fromage amk'))
None
>>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
<re.Match object; span=(0, 5), match='From '>
@end example

内部的には、これら関数は単にあなたのためにパターンオブジェクトを生成し、対応するメソッドを呼び出すだけのことです。とともに、将来の呼び出しで同じ RE のパースが何度も何度も必要とならないよう、コンパイル済みオブジェクトはキャッシュされます。

これらモジュールレベル関数を使うのと、パターンを自身で作って自身で呼び出すのとでどちらを使うべきでしょう? 正規表現をループの内側で使うならば、プリコンパイルは関数呼び出しを減らします。ループの外側であれば、内部キャッシュのおかげで、どちらでも大差ありません。

@node コンパイルフラグ,,モジュールレベルの関数<3>,正規表現を使う
@anchor{howto/regex compilation-flags}@anchor{57b9}
@subsubsection コンパイルフラグ


コンパイルフラグは正規表現の動作をいくつかの側面から変更します。フラグは @ref{be,,re} モジュール下で二つの名前で利用することができます、例えば長い名前は @ref{1a96,,IGNORECASE} で短い名前は1文字で @ref{2766,,I} のようになっています。 (1文字形式は Perl のパターン修飾子と同じ形式を使います; 例えば @ref{2772,,re.VERBOSE} の短かい形式は @ref{276b,,re.X} です。) 複数のフラグが OR ビット演算で指定することができます; 例えば @code{re.I | re.M} は @ref{2766,,I} と @ref{2768,,M} フラグの両方を設定します。

ここに利用可能なフラグの表があります、それぞれについてのより詳細な説明が後に続きます。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Flag

@tab

意味

@item

@ref{83e,,ASCII}, @ref{2765,,A}

@tab

@code{\w}, @code{\b}, @code{\s}, そして @code{\d} などをそれぞれのプロパティをもつ ASCII 文字だけにマッチさせます。

@item

@ref{2763,,DOTALL}, @ref{2769,,S}

@tab

@code{.} を改行を含む任意の文字にマッチするようにします。

@item

@ref{1a96,,IGNORECASE}, @ref{2766,,I}

@tab

大文字小文字を区別しないマッチを行います。

@item

@ref{d63,,LOCALE}, @ref{2767,,L}

@tab

ロケールに対応したマッチを行います。

@item

@ref{2764,,MULTILINE}, @ref{2768,,M}

@tab

@code{^} や @code{$} の意味を変更し、複数行文字列に対するマッチングを行います。

@item

@ref{2772,,VERBOSE}, @ref{276b,,X} ('X' は 'extended' の 'X')

@tab

冗長な正規表現を利用できるようにして、よりきれいで理解しやすくまとめることができます。

@end multitable



@deffn {データ} re.I

@deffnx {データ} re.IGNORECASE

大文字と小文字を区別しないマッチングを実行します; 文字クラスと文字列リテラルは大文字か小文字かに関係なくパターンにマッチします。例えば、 @code{[A-Z]} は小文字のアルファベットにもマッチします。 @ref{83e,,ASCII} フラグによって非 ASCII 文字のマッチングが無効化されていなければ、完全なユニコードのマッチングも可能です。ユニコードで @code{[a-z]} または @code{[A-Z]} が @ref{1a96,,IGNORECASE} フラグとともに使われると、 52個の ASCII 文字に加えて 次の4つの 非 ASCII 文字にマッチします: 'İ' (U+0130, ラテン語の大文字 I で、上部に点がついたもの), 'ı' (U+0131, ラテン語の小文字 i で上部に点がない), 'ſ' (U+017F, ラテン語の小文字 s),  'K' (U+212A, ケルビン記号)。 @code{Spam} は @code{'Spam'}, @code{'spam'}, @code{'spAM'}, そして @code{'ſpam'} にマッチします (ただし最後の文字列はユニコードモードの場合のみマッチします)。この「小文字化」は現在のロケールを考慮しません; ただし @ref{d63,,LOCALE} フラグをセットした場合はロケールを考慮します。
@end deffn


@deffn {データ} re.L

@deffnx {データ} re.LOCALE

@code{\w}, @code{\W}, @code{\b},  @code{\B} と小文字大文字の区別を無視したマッチングを、 Unicode データベースではなく現在のロケールに従って行います。

ロケールは言語の違いを考慮したプログラムを書くことを手助けすることを目的とした C ライブラリの機能です。例えば、エンコードされたフランス語のテキストを処理していて、@code{\w+} を使って単語のマッチを行いたいとします。ですがこの場合、 @code{\w} はバイトパターンにおいて文字クラス @code{[A-Za-z]} だけにマッチします; すなわち @code{é} や @code{ç} に対応するバイト列にはマッチしません。もしシステムが適切に設定されていて、ロケールがフランス語に設定されていれば、ある C 関数はプログラムに @code{é} に対応するバイト列も文字として考慮するべきであると伝えます。正規表現をコンパイルするときに @ref{d63,,LOCALE} フラグを設定すると、コンパイルされたオブジェクトが @code{\w} に対してロケールを考慮する C 関数を使うようになります; これにより処理は遅くなりますが、 @code{\w+} を期待通りフランス語の単語にマッチさせることが可能になります。このフラグを Python 3 で利用することは推奨されません。なぜならロケールの仕組みは非常に信頼性が低く、同時にひとつの "文化" しか扱うことができず、また8ビットのロケールでしか正しく動作しないからです。Python 3 ではユニコード (文字列の) パターンに対してユニコードのマッチングがデフォルトで有効化されており、これにより異なるロケールまたは言語を同時に扱うことができます。
@end deffn


@deffn {データ} re.M

@deffnx {データ} re.MULTILINE

(@code{^} と @code{$} についてはまだ説明していません; これらは @ref{57ba,,さらなる特殊文字} の節で説明します。)

通常 @code{^} は文字列の先頭にマッチし、 @code{$} は文字列の末尾と文字列の末尾に改行(があれば)その直前にマッチします。このフラグが指定されると、 @code{^} は文字列の先頭と文字列の中の改行に続く各行の先頭にマッチします。同様に @code{$} 特殊文字は文字列の末尾と各行の末尾(各改行の直前)のどちらにもマッチします。
@end deffn


@deffn {データ} re.S

@deffnx {データ} re.DOTALL

特別な文字 @code{'.'} を改行を含む全ての任意の文字とマッチするようにします; このフラグが無しでは、 @code{'.'} は改行 `以外' の全てにマッチします。
@end deffn


@deffn {データ} re.A

@deffnx {データ} re.ASCII

@code{\w}, @code{\W}, @code{\b}, @code{\B}, @code{\s}, @code{\S} が、完全な Unicode マッチングではなく、ASCII のみのマッチングをするようにします。これは Unicode パターンにのみ意味があり、byte パターンには無視されます。
@end deffn


@deffn {データ} re.X

@deffnx {データ} re.VERBOSE

このフラグはより柔軟な形式で正規表現を読み易く書けるようにします。このフラグを指定すると、正規表現の中の空白は無視されます、ただし、文字クラス内やエスケープされていないバックスラッシュに続く空白の場合は例外として無視されません; これによって正規表現をまとめたり、インデントしてより明確にすることができます。このフラグはさらにエンジンが無視するコメントを追加することもできます; コメントは @code{'#'} で示します、これは文字クラスやエスケープされていないバックスラッシュに続くものであってはいけません。

例えば、ここに @ref{2772,,re.VERBOSE} を利用した正規表現があります; 読み易いと思いませんか?

@example
charref = re.compile(r"""
 &[#]                # Start of a numeric entity reference
 (
     0[0-7]+         # Octal form
   | [0-9]+          # Decimal form
   | x[0-9a-fA-F]+   # Hexadecimal form
 )
 ;                   # Trailing semicolon
""", re.VERBOSE)
@end example

冗長な表現を利用しない設定の場合、正規表現はこうなります:

@example
charref = re.compile("&#(0[0-7]+"
                     "|[0-9]+"
                     "|x[0-9a-fA-F]+);")
@end example

上の例では、Python の文字列リテラルの自動結合によって正規表現を小さな部分に分割しています、それでも @ref{2772,,re.VERBOSE} を使った場合に比べるとまだ難しくなっています。
@end deffn

@node パターンの能力をさらに,文字列を変更する,正規表現を使う,正規表現 HOWTO
@anchor{howto/regex more-pattern-power}@anchor{57bb}
@subsection パターンの能力をさらに


ここまでで、正規表現の機能のほんの一部を扱ってきました。この節では、新たにいくつかの特殊文字とグループを使ってマッチしたテキストの一部をどう取得するかについて扱います。

@menu
* さらなる特殊文字:: 
* グルーピング:: 
* 取り出さないグループと名前つきグループ:: 
* 先読みアサーション (Lookahead Assertions): 先読みアサーション Lookahead Assertions. 

@end menu

@node さらなる特殊文字,グルーピング,,パターンの能力をさらに
@anchor{howto/regex id2}@anchor{57bc}@anchor{howto/regex more-metacharacters}@anchor{57ba}
@subsubsection さらなる特殊文字


これまでで、まだ扱っていない特殊文字がいくつかありました。そのほとんどをこの節で扱っていきます。

残りの特殊文字の内いくつかは `ゼロ幅アサーション zero-width-assertions' に関するものです。これらは文字列に対してエンジンを進めません; 文字列を全く利用しない代わりに、単純に成功か失敗かを利用します。例えば、 @code{\b} は現在位置が単語の境界であることを示します; @code{\b} によってエンジンの読んでいる位置は全く変化しません。つまり、これはゼロ幅アサーションは繰り返し使うことがありません、一度ある位置でマッチしたら、明らかに無限回マッチできます。


@table @asis

@item @code{|}

代替 (alternation) または "or" 演算子です。 `A' と `B' が正規表現の場合、 @code{A|B} は `A' と `B' のどちらかにマッチするような文字列にマッチします。複数の文字からなる文字列による代替処理が適切に動作するために、 @code{|} の優先度は非常に低く設定されています。 @code{Crow|Servo} は @code{'Crow'} か @code{'Servo'} のどちらかにマッチするパターンであり、 「@code{'Cro'} に続いて @code{'w'} または @code{'S'} があり、さらに @code{'ervo'} が続く」という意味ではありません。

リテラル @code{'|'} にマッチするには、 @code{\|} を利用するか、 @code{[|]} のように文字クラス内に収めて下さい。

@item @code{^}

行の先頭にマッチします。 @ref{2764,,MULTILINE} フラグが設定されない場合には、文字列の先頭にのみマッチします。 @ref{2764,,MULTILINE} モードでは文字列内の各改行の直後にマッチします。

例えば、行の先頭の @code{From} にのみマッチさせたい場合には @code{^From} 正規表現を利用します。

@example
>>> print(re.search('^From', 'From Here to Eternity'))
<re.Match object; span=(0, 4), match='From'>
>>> print(re.search('^From', 'Reciting From Memory'))
None
@end example

リテラル @code{'^'} にマッチするには @code{\^} を利用してください。

@item @code{$}

行の末尾にマッチします、行の末尾は文字列の末尾と改行文字の直前として定義されます。

@example
>>> print(re.search('@}$', '@{block@}'))
<re.Match object; span=(6, 7), match='@}'>
>>> print(re.search('@}$', '@{block@} '))
None
>>> print(re.search('@}$', '@{block@}\n'))
<re.Match object; span=(6, 7), match='@}'>
@end example

リテラル @code{'$'} にマッチするには、 @code{\$} を利用するか、 @code{[$]} のように文字クラス内に収めて下さい。

@item @code{\A}

文字列の先頭にのみマッチします。 @ref{2764,,MULTILINE} モードでない場合には @code{\A} と @code{^} は実質的に同じです。 @ref{2764,,MULTILINE} モードでのこれらの違いは: @code{\A} は依然として文字列の先頭にのみマッチしますが、 @code{^} は文字列内に改行文字に続く部分があればそこにマッチすることです。

@item @code{\z}

文字列の末尾でのみマッチします。

@item @code{\Z}

The same as @code{\z}.  For compatibility with old Python versions.

@item @code{\b}

単語の境界。これはゼロ幅アサーションで、単語の始まりか終わりにのみマッチします。単語は英数文字のシーケンスとして定義されます、つまり単語の終わりは空白か非英数文字として表われます。

以下の例では @code{class} がそのものの単語のときのみマッチします; 別の単語内に含まれている場合はマッチしません。

@example
>>> p = re.compile(r'\bclass\b')
>>> print(p.search('no class at all'))
<re.Match object; span=(3, 8), match='class'>
>>> print(p.search('the declassified algorithm'))
None
>>> print(p.search('one subclass is'))
None
@end example

この特殊シーケンスを利用するときには二つの微妙な点を心にとめておく必要があります。まずひとつめは Python の文字列リテラルと表現の間の最悪の衝突を引き起すことです。Python の文字列リテラルでは @code{\b} は ASCII 値8のバックスペース文字です。raw string を利用していない場合、Python は @code{\b} をバックスペースに変換し、正規表現は期待するものとマッチしなくなります。以下の例はさきほどと同じ正規表現のように見えますが、正規表現文字列の前の @code{'r'} が省略されています。

@example
>>> p = re.compile('\bclass\b')
>>> print(p.search('no class at all'))
None
>>> print(p.search('\b' + 'class' + '\b'))
<re.Match object; span=(0, 7), match='\x08class\x08'>
@end example

ふたつめはこのアサーションが利用できない文字列クラスの内部では Python の文字列リテラルとの互換性のために、 @code{\b} はバックスペース文字を表わすことになるということです。

@item @code{\B}

別のゼロ幅アサーションで、 @code{\b} と逆で、現在の位置が単語の境界でないときにのみマッチします。
@end table

@node グルーピング,取り出さないグループと名前つきグループ,さらなる特殊文字,パターンの能力をさらに
@anchor{howto/regex grouping}@anchor{57bd}
@subsubsection グルーピング


正規表現にマッチするかどうかだけでなく、より多くの情報を得なければいけない場合は多々あります。正規表現はしばしば、正規表現をいくつかのサブグループに分けて興味ある部分にマッチするようにして、文字列を分割するのに使われます。例えば、RFC-822 ヘッダ行は @code{':'} を挟んでこのようにヘッダ名と値に分割されます:

@example
From: author@@example.com
User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
MIME-Version: 1.0
To: editor@@example.com
@end example

これはヘッダ全体にマッチし、そしてヘッダ名にマッチするグループとヘッダの値にマッチする別のグループを持つように正規表現を書くことで扱うことができます。

グループはメタ文字 @code{'('} と @code{')'} であらわされます。 @code{'('} と @code{')'} は数式における意味とほぼ同じ意味を持っています; その中に含まれる表現をひとまとまりにし、それらに対して @code{*}, @code{+}, @code{?}, または @code{@{m,n@}} のような数量子を使った繰り返しを表現することもできます。例えば、 @code{(ab)*} は @code{ab} の0回以上の繰り返しにマッチします。

@example
>>> p = re.compile('(ab)*')
>>> print(p.match('ababababab').span())
(0, 10)
@end example

@code{'('}, @code{')'} で指示されたグループは、マッチしたテキスト開始と終了位置もキャプチャします; @ref{122c,,group()}, @ref{2787,,start()}, @ref{2788,,end()}, @ref{2789,,span()} に引数を与えて取り出せます。グループはゼロ始まりの数値です。グループ 0 は常に使えます; それは RE でマッチした全体で、 @ref{118a,,Match オブジェクト} メソッドの全てはグループ 0 をデフォルト引数にしています。マッチするテキストの範囲をキャプチャしないグループの書き方はのちほど見ることにします。

@example
>>> p = re.compile('(a)b')
>>> m = p.match('ab')
>>> m.group()
'ab'
>>> m.group(0)
'ab'
@end example

サブグループは左から右へ1づつ番号付けされます。グループはネストしてもかまいません; 番号を決めるには、単に開き括弧を左から右へ数え上げます。

@example
>>> p = re.compile('(a(b)c)d')
>>> m = p.match('abcd')
>>> m.group(0)
'abcd'
>>> m.group(1)
'abc'
>>> m.group(2)
'b'
@end example

@ref{122c,,group()} には一回に複数の引数を渡してもかまいません、その場合にはそれらのグループに対応する値を含むタプルを返します。

@example
>>> m.group(2,1,2)
('b', 'abc', 'b')
@end example

@ref{122d,,groups()} メソッドは 1 から全てのサブグループの文字列を含むタプルを返します。:

@example
>>> m.groups()
('abc', 'b')
@end example

パターン中で後方参照を利用することで、前に取り出されたグループが文字列の中の現在位置で見つかるように指定できます。例えば、@code{\1} はグループ1の内容が現在位置で見つかった場合成功し、それ以外の場合に失敗します。Python の文字列リテラルでもバックスラッシュに続く数字は任意の文字を文字列に含めるために使われるということを心に留めておいて下さい、そのため正規表現で後方参照を含む場合には raw string を必ず利用して下さい。

例えば、以下の正規表現は二重になった単語を検出します。

@example
>>> p = re.compile(r'\b(\w+)\s+\1\b')
>>> p.search('Paris in the the spring').group()
'the the'
@end example

このような後方参照は文字列を検索するだけの用途では多くの場合役に立ちません。--- このように繰り返されるテキストフォーマットは少数です。--- しかし、文字列の置換をする場合には `とても' 有効であることに気づくでしょう。

@node 取り出さないグループと名前つきグループ,先読みアサーション Lookahead Assertions,グルーピング,パターンの能力をさらに
@anchor{howto/regex non-capturing-and-named-groups}@anchor{57be}
@subsubsection 取り出さないグループと名前つきグループ


念入りに作られた正規表現は多くのグループを利用します、その利用法には対象となる部分文字列を取り出す、正規表現自身をグループ化したり構造化する、という二つの方法があります。複雑な正規表現では、グループ番号を追っていくことは困難になっていきます。この問題の解決を助ける二つの機能があります。その両方が正規表現を拡張するための一般的な構文を利用します、まずはそれらをみてみましょう。

Perl 5 は標準正規表現にパワフルな拡張を加えたことでよく知られています。それらの新しい機能のために Perl 開発者たちは、Perl正規表現と標準正規表現との混乱を招く違いなしには、新たな一文字メタキャラクタも @code{\} ではじまる新たな特殊シーケンスもどちらも選択出来ませんでした。たとえば彼らがもし @code{&} を新たなメタキャラクタとして選んでいたら、 @code{&} が通常文字とみなされていた古い正規表現は @code{\&} や @code{[&]} のように書くことでエスケープされなければならなかったでしょう。

解決策として Perl 開発者が選んだものは @code{(?...)} を正規表現構文として利用することでした。括弧の直後の @code{?} は構文エラーとなります、これは @code{?} で繰り返す対象がないためです、そのためこれは互換性の問題を持ち込みません。 @code{?} の直後の文字はどの拡張が利用されるかを示しています、つまり、 @code{(?=foo)} は一つの拡張を利用したもの (肯定先読みアサーション) となり、 @code{(?:foo)} は別の拡張を利用した表現(@code{foo} を含む取り込まないグループ)となります。

Python は Perl の拡張のいくつかをサポートし、また、Perl の拡張に一つ拡張を加えています。クエスチョンマークに続く最初の文字が @code{P} のものは、そうです、Python 固有の拡張です。

一般化された拡張構文についてはわかりましたので、いよいよ複雑な正規表現内でのグループの扱いを単純化する機能に話を戻しましょう。

ときとしてあなたは、正規表現の一部として使いたいけれども、その内容を取り出すことに興味がないようなグループを記述する必要に迫られます。このためには、取り出さないグループ: @code{(?:...)} を使います。 @code{...} 部分は任意の正規表現です。

@example
>>> m = re.match("([abc])+", "abc")
>>> m.groups()
('c',)
>>> m = re.match("(?:[abc])+", "abc")
>>> m.groups()
()
@end example

マッチしたグループの内容を取得しないということを除けば、取り込まないグループは厳密に取り込むグループと同様に振る舞います; この中に何を入れてもかまいません、 @code{*} のような繰り返しの特殊文字で繰り返したり、他のグループ (取り込むまたは取り込まない) の入れ子にすることもでいます。 @code{(?:...)} は特に、既にあるパターンを変更する際に便利です、なぜなら他の番号づけ新しいグループを変更することなく新しいグループを追加することができます。取り込むグループと取り込まないグループで検索のパフォーマンスに差がないことにも触れておくべきことです; どちらも同じ速度で動作します。

より重要な機能は名前つきグループです: 番号で参照する代わりに、グループに対して名前で参照できます。

名前つきグループのための構文は、 Python 固有拡張の一つ: @code{(?P<name>...)} を使います。 `name' は、もちろん、グループの名前です。名前つきグループは取り込むグループと完全に同じに振る舞い、加えて名前が関連付けられます。 @ref{118a,,Match オブジェクト} の取りこむグループを扱うメソッドは全て、番号によるグループ参照のための整数、名前によるグループ参照のための文字列、ともに許容しています。名前つきグループにも番号が振られますので、グループについての情報を、2つの方法で取り出せます:

@example
>>> p = re.compile(r'(?P<word>\b\w+\b)')
>>> m = p.search( '(((( Lots of punctuation )))' )
>>> m.group('word')
'Lots'
>>> m.group(1)
'Lots'
@end example

さらに、名前付きのグループを @ref{2786,,groupdict()} を使って辞書として取り出すこともできます:

@example
>>> m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe')
>>> m.groupdict()
@{'first': 'Jane', 'last': 'Doe'@}
@end example

名前つきグループは、番号を覚える代わりに簡単に覚えられる名前で管理できるため、便利です。以下は @ref{78,,imaplib} モジュールで使われている正規表現の例です:

@example
InternalDate = re.compile(r'INTERNALDATE "'
        r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
        r'(?P<year>[0-9][0-9][0-9][0-9])'
        r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
        r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
        r'"')
@end example

取得する番号9を覚えるよりも、 @code{m.group('zonem')} で取得した方が明らかに簡単にすみます。

後方参照のための構文 @code{(...)\1} はグループ番号への参照となっています。
グループ番号の代わりに、グループ名を利用する変種があるのは当然でしょう。
これはもう一つの Python 拡張です: @code{(?P=name)} は、 `name' という名前のグループの内容が、現在の位置で再びマッチすることを示しています。
同じ単語が2つ連なっているのを見つける正規表現 @code{\b(\w+)\s+\1\b} は @code{\b(?P<word>\w+)\s+(?P=word)\b} のように書けます:

@example
>>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
>>> p.search('Paris in the the spring').group()
'the the'
@end example

@node 先読みアサーション Lookahead Assertions,,取り出さないグループと名前つきグループ,パターンの能力をさらに
@anchor{howto/regex lookahead-assertions}@anchor{57bf}
@subsubsection 先読みアサーション (Lookahead Assertions)


他のゼロ幅アサーションは先読みアサーションです。先読みアサーションは肯定、否定の両方の形式が利用可能です、これを見てください:


@table @asis

@item @code{(?=...)}

肯定先読みアサーション。 @code{...} で表わす正規表現が現在位置でマッチすれば成功し、それ以外の場合失敗します。しかし、表現が試行された場合でもエンジンは先に進みません; パターンの残りの部分はアサーションの開始時点から右に試行します。

@item @code{(?!...)}

否定先読みアサーション。これは肯定アサーションの逆で、正規表現が文字列の現在位置にマッチ `しなかった' 場合に成功します。
@end table

より具体的にするため、先読みが便利な場合をみてみましょう。ファイル名にマッチし、 @code{.} で分けられた基本部分と拡張子に分離する単純なパターンを考えましょう。例えば、 @code{news.rc} は @code{news} が基本部分で @code{rc} がファイル名の拡張子です。

マッチするパターンはとても単純です:

@code{.*[.].*$}

@code{.} はメタキャラクタですので特別に扱わなければなりませんから、文字クラス内に入れて、そのものとだけマッチするようにしていることに注目です。末尾の @code{$} にも注目してください; これは残り全ての文字列が拡張子に含まれるべきであることを保障するために追加しています。この正規表現は @code{foo.bar}, @code{autoexec.bat}, @code{sendmail.cf}, @code{printers.conf} にマッチします。

さて、問題を少し複雑にしてみましょう; 拡張子が @code{bat} でないファイル名にマッチしたい場合はどうでしょう？間違った試み:

@code{.*[.][^b].*$}

The first attempt above tries to exclude @code{bat} by requiring
that the first character of the extension is not a @code{b}.  This is wrong,
because the pattern also doesn't match @code{foo.bar}.

@code{.*[.]([^b]..|.[^a].|..[^t])$}

正規表現が混乱してきました。最初の解決策を取り繕って、以下の場合に合わせることを要求しています: 拡張子の最初の文字は @code{b} でなく; 二番目の文字は @code{a} でなく; 三番目の文字は @code{t} でない。これは @code{foo.bar} を受け付けますが、 @code{autoexec.bat} は拒否します。しかし、三文字の拡張子を要求し、 @code{sendmail.cf} のような二文字の拡張子を受け付けません。これを修正するのにパターンを再び複雑にすることになります。

@code{.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$}

三番目の試みでは、 @code{sendmail.cf} のように三文字より短い拡張子とマッチするために第二第三の文字を全てオプションにしています。

パターンはさらに複雑さを増し、読みにくく、理解が難しくなりました。より悪いことに、問題が @code{bat} と @code{exe} 両方を拡張子から除きたい場合に変わった場合、パターンはより複雑で混乱しやすいものになります。

否定先読みはこの混乱全てを取り除きます:

@code{.*[.](?!bat$)[^.]*$}

The negative lookahead means: if the expression @code{bat}
doesn't match at this point, try the rest of the pattern; if @code{bat$} does
match, the whole pattern will fail.  The trailing @code{$} is required to ensure
that something like @code{sample.batch}, where the extension only starts with
@code{bat}, will be allowed.  The @code{[^.]*} makes sure that the pattern works
when there are multiple dots in the filename.

他のファイル名の拡張子を除くことも簡単です; 単純にアサーション内に拡張子を代替 (or) で加えます。以下のパターンは @code{bat} や @code{exe} のどちらかで終わるファイル名を除外します:

@code{.*[.](?!bat$|exe$)[^.]*$}

@node 文字列を変更する,よくある問題,パターンの能力をさらに,正規表現 HOWTO
@anchor{howto/regex modifying-strings}@anchor{57c0}
@subsection 文字列を変更する


ここまででは単純に静的な文字列に対する検索を実行してきました。正規表現は文字列を様々な方法で変更するのにもよく使われます。変更には以下のパターンメソッドが利用されます:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

メソッド/属性

@tab

目的

@item

@code{split()}

@tab

文字列をリストに分割する、正規表現がマッチした全ての場所で分割を行う

@item

@code{sub()}

@tab

正規表現にマッチした全ての文字列を発見し、別の文字列に置き換えます

@item

@code{subn()}

@tab

@code{sub()} と同じことをしますが、新しい文字列と置き換えの回数を返します

@end multitable


@menu
* 文字列の分割:: 
* 検索と置換: 検索と置換<2>. 

@end menu

@node 文字列の分割,検索と置換<2>,,文字列を変更する
@anchor{howto/regex splitting-strings}@anchor{57c1}
@subsubsection 文字列の分割


@code{split()} メソッドは文字列を正規表現にマッチした場所で分割し、リストで返却します。文字列の @ref{10aa,,split()} メソッドに似てはいますが、もっとずっと一般化したデリミタで分割出来ます; 文字列の @code{split()} メソッドは単に空白文字か固定文字列で分割出来るだけです。ご想像通り、モジュールレベルの @ref{5a2,,re.split()} 関数もあります。


@deffn {メソッド} .split (string[, maxsplit=0])

`string' を正規表現のマッチで分割します。正規表現内に取り込むための括弧が利用されている場合、その内容も結果のリストの一部として返されます。 `maxsplit' が非ゼロの場合、最大で `maxsplit' の分割が実行されます。
@end deffn

`maxsplit' に値を渡すことで、分割される回数を制限することができます。 `maxsplit' が非ゼロの場合、最大で `maxsplit' の分割が行なわれ、文字列の残りがリストの最終要素として返されます。以下の例では、デリミタは任意の英数文字のシーケンスです。

@example
>>> p = re.compile(r'\W+')
>>> p.split('This is a test, short and sweet, of split().')
['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '@w{'}]
>>> p.split('This is a test, short and sweet, of split().', 3)
['This', 'is', 'a', 'test, short and sweet, of split().']
@end example

興味の対象がデリミタの間のテキストだけでなく、デリミタが何なのかということを知りたい場合はよくあります。取りこみ用の括弧を正規表現に使った場合、その値もリストの一部として返されます。以下の呼び出しを比較してみましょう:

@example
>>> p = re.compile(r'\W+')
>>> p2 = re.compile(r'(\W+)')
>>> p.split('This... is a test.')
['This', 'is', 'a', 'test', '@w{'}]
>>> p2.split('This... is a test.')
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '@w{'}]
@end example

モジュールレベル関数 @ref{5a2,,re.split()} は最初の引数に利用する正規表現を追加しますが、それ以外は同じです。

@example
>>> re.split(r'[\W]+', 'Words, words, words.')
['Words', 'words', 'words', '@w{'}]
>>> re.split(r'([\W]+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '@w{'}]
>>> re.split(r'[\W]+', 'Words, words, words.', 1)
['Words', 'words, words.']
@end example

@node 検索と置換<2>,,文字列の分割,文字列を変更する
@anchor{howto/regex search-and-replace}@anchor{57c2}
@subsubsection 検索と置換


もう一つのよくある作業は、パターンにマッチする全ての文字列を探し、異なる文字列に置換します。
@ref{277d,,sub()} メソッドは置換する値をとります、文字列と関数の両方をとることができ、文字列を処理します。


@deffn {メソッド} .sub (replacement, string[, count=0])

`string' 内で最も長く、他の部分と重複するところがない正規表現を `replacement' に置換した文字列を返します。パターンが見つからなかった場合 `string' は変更されずに返されます。

オプション引数 `count' はパターンの出現の最大置換回数です; `count' は非負の整数でなければいけません。デフォルト値 0 は全ての出現で置換することを意味します。
@end deffn

ここに @ref{277d,,sub()} メソッドを使った単純な例があります。これは色の名前を @code{colour} に置換します:

@example
>>> p = re.compile('(blue|white|red)')
>>> p.sub('colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub('colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'
@end example

@ref{277e,,subn()} メソッドも同じ働きをしますが、新しい文字列と置換の実行回数を含む 2-タプルを返します:

@example
>>> p = re.compile('(blue|white|red)')
>>> p.subn('colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2)
>>> p.subn('colour', 'no colours at all')
('no colours at all', 0)
@end example

空文字列とのマッチは、直前の空文字列とマッチした部分と隣接していない場合にのみ置換されます。

@example
>>> p = re.compile('x*')
>>> p.sub('-', 'abxd')
'-a-b--d-'
@end example

`replacement' が文字列の場合、文字列内のバックスラッシュエスケープは処理されます。つまり、@code{\n} は改行文字に @code{\r} はキャリッジリターンに、等となります。@code{\&} のような未知のエスケープシーケンスはそのまま残されます。@code{\6} のような後方参照は正規表現内の対応するグループにマッチする文字列に置換されます。これを使うことで元のテキストの一部を、置換後の文字列に組み込むことができます。

この例は単語 @code{section} に続く @code{@{} と @code{@}} で閉じられた文字列にマッチし、 @code{section} を @code{subsection} に変更します:

@example
>>> p = re.compile('section@{ ( [^@}]* ) @}', re.VERBOSE)
>>> p.sub(r'subsection@{\1@}','section@{First@} section@{second@}')
'subsection@{First@} subsection@{second@}'
@end example

@code{(?P<name>...)} 構文で定義された名前つきグループを参照するための構文もあります。 @code{\g<name>} は @code{name} で名前づけされたグループにマッチする文字列を利用し、 @code{\g<number>} は対応するグループ番号を利用します。つまり @code{\g<2>} は @code{\2} と等価ですが、 @code{\g<2>0} のような置換文字列に対しては明確に異なります。 (@code{\20} はグループ番号20への参照と解釈され、グループ2の後にリテラル文字 @code{'0'} が続くとは解釈されません。) 以下に示す置換は全て等価ですが、これらは文字列置換に全部で3種の変種を利用しています。

@example
>>> p = re.compile('section@{ (?P<name> [^@}]* ) @}', re.VERBOSE)
>>> p.sub(r'subsection@{\1@}','section@{First@}')
'subsection@{First@}'
>>> p.sub(r'subsection@{\g<1>@}','section@{First@}')
'subsection@{First@}'
>>> p.sub(r'subsection@{\g<name>@}','section@{First@}')
'subsection@{First@}'
@end example

より細かな制御を手中にするために `replacement' として関数を使うことが出来ます。 `replacement' が関数であれば、その関数は重なり合わない `pattern' の発生のたびに呼び出されます。それぞれの呼び出しで、マッチした @ref{118a,,Match オブジェクト} が引数として渡されるので、望みの置換と返却のためにこの情報を利用出来ます。

続く例では、置換関数は十進数文字列を十六進数文字列に変換しています:

@example
>>> def hexrepl(match):
...     "Return the hex string for a decimal number"
...     value = int(match.group())
...     return hex(value)
...
>>> p = re.compile(r'\d+')
>>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
'Call 0xffd2 for printing, 0xc000 for user code.'
@end example

モジュールレベルの @ref{5a3,,re.sub()} 関数を使うときには、パターンが最初の引数として渡されます。パターンはオブジェクトや文字列をとります; 正規表現フラグを指定する必要がある場合、パターンオブジェクトを最初の引数として使うか、修飾子を埋め込んだパターン文字列を使うかしなければいけません、例えば @code{sub("(?i)b+", "x", "bbbb BBBB")} は @code{'x x'} を返します。

@node よくある問題,フィードバック,文字列を変更する,正規表現 HOWTO
@anchor{howto/regex common-problems}@anchor{57c3}
@subsection よくある問題


正規表現はいくつかの応用に対して強力なツールですが、いくつかの部分でそれらの振る舞いは直感的ではなく、期待通りに振る舞わないことがあります。この節では最もよくある落とし穴を指摘します。

@menu
* 文字列メソッドを利用する:: 
* match() 対 search(): match 対 search. 
* 貪欲 (greedy) 対非貪欲 (non-greedy): 貪欲 greedy 対非貪欲 non-greedy. 
* re.VERBOSE の利用: re VERBOSE の利用. 

@end menu

@node 文字列メソッドを利用する,match 対 search,,よくある問題
@anchor{howto/regex use-string-methods}@anchor{57c4}
@subsubsection 文字列メソッドを利用する


いくつかの場合 @ref{be,,re} モジュールを利用することは間違いである場合があります。固定文字列や単一の文字クラスにマッチさせる場合や、 @ref{1a96,,IGNORECASE} フラグのような @ref{be,,re} の機能を利用しない場合、正規表現の全ての能力は必要とされていなでしょう。文字列は固定文字列に対する操作を実行するメソッドを持っていて、大きな汎用化された正規表現エンジンではなく、目的のために最適化された単一の小さな C loop で実装されているため、大抵の場合高速です.

一つの例としては、単一の固定文字列を別の固定文字列に置き換える作業があるでしょう; 例えば @code{word} を @code{deed} で置換したい場合です。
@ref{5a3,,re.sub()} はこの目的で使う関数のように思えますが、 @ref{4b8,,replace()} メソッドを利用することを考えた方がいいでしょう。
@code{replace()} は単語内の @code{word} も置換し、 @code{swordfish} を @code{sdeedfish} に変えますが、安直な正規表現 @code{word} も同様に動作することに注意して下さい。(単語の一部に対する置換の実行を避けるには、パターンを @code{\bword\b} として、 @code{word} の両側に単語の境界が要求されるようにします。これは @code{replace()} の能力を越えた作業です。)

別のよくある作業は、文字列の中に出現する文字を全て削除することと、別の文字で置換することです。この作業を @code{re.sub('\n', ' ', S)} のようにして行うかもしれませんが、 @ref{264c,,translate()} は削除と置換の両方の作業をこなし、正規表現操作よりも高速に行うことができます。

要は、 @ref{be,,re} モジュールに向う前に問題が高速で単純な文字列メソッドで解決できるか考えましょうということです。

@node match 対 search,貪欲 greedy 対非貪欲 non-greedy,文字列メソッドを利用する,よくある問題
@anchor{howto/regex match-versus-search}@anchor{57c5}
@subsubsection match() 対 search()


@ref{1445,,match()} 関数は文字列の先頭に正規表現がマッチするかどうか調べるだけですが、その一方 @ref{1444,,search()} はマッチするために文字列の先の方まで走査します。
この違いを覚えておくことは重要なことです。
@code{match()} は開始位置0でマッチが成功したときのみ報告する; もし開始位置0でマッチしなければ、 @code{match()} はそれを報告 `しない' 、ということを覚えておいてください。

@example
>>> print(re.match('super', 'superstition').span())
(0, 5)
>>> print(re.match('super', 'insuperable'))
None
@end example

一方 @ref{1444,,search()} は文字列の先の方まで走査し、最初にみつけたマッチを報告します。:

@example
>>> print(re.search('super', 'superstition').span())
(0, 5)
>>> print(re.search('super', 'insuperable').span())
(2, 7)
@end example

しばしば、 @ref{1445,,re.match()} を使い、 @code{.*} を正規表現の最初に付け加える誘惑にからされることがあるでしょう。この誘惑に打ち克って、代わりに @ref{1444,,re.search()} を利用すべきです。正規表現コンパイラはマッチを探す処理の高速化のためにいくつかの解析を行います。そのような解析のうちのひとつはマッチの最初の文字が何であるか評価することです; 例えば、 @code{Crow} で始まるパターンは @code{'C'} から始まらなければいけません。解析によってエンジンは速やかに開始文字を探して走査します、 @code{'C'} が発見された場合にはじめて完全なマッチを試みます。

@code{.*} を追加することはこの最適化を無効にします、文字列の終端までの走査が必要となり、走査後には残りの正規表現とのマッチ部分を見つけるために引き返すことになります。代わりに @ref{1444,,re.search()} を利用して下さい。

@node 貪欲 greedy 対非貪欲 non-greedy,re VERBOSE の利用,match 対 search,よくある問題
@anchor{howto/regex greedy-versus-non-greedy}@anchor{57c6}
@subsubsection 貪欲 (greedy) 対非貪欲 (non-greedy)


正規表現を繰り返す場合、たとえば @code{a*} のように、できるだけパターンの多くにマッチするように動作することになります。この動作は、例えば角括弧で囲まれた HTML タグのような左右対称のデリミタの対にマッチしようという場合に問題となります。単一の HTML タグにマッチする素朴な正規表現はうまく動作しません、なぜならば @code{.*} は貪欲に動作するからです。

@example
>>> s = '<html><head><title>Title</title>'
>>> len(s)
32
>>> print(re.match('<.*>', s).span())
(0, 32)
>>> print(re.match('<.*>', s).group())
<html><head><title>Title</title>
@end example

正規表現は @code{'<html>'} 内の @code{'<'} にマッチし、 @code{.*} は残りの文字列の全てにマッチします。
しかし、正規表現には依然として残っている部分があって、 @code{>} は文字列の終端にマッチしないので、正規表現エンジンは一文字ずつ @code{>} とマッチするまで引き返すことになります。
最終的にマッチする領域は @code{'<html>'} の @code{'<'} から @code{'</title>'} の @code{'>'} まで広がりますが、これは望んだ結果ではありません。

この場合の解決策は、非貪欲 (non-greedy) な数量子 @code{*?}, @code{+?}, @code{??}, あるいは @code{@{m,n@}?} を使うことです。これらはできるだけ `少ない' テキストにマッチしようとします。上記の例では、 @code{'>'} は @code{'<'} がマッチした直後の文字からマッチするかどうかを調べられ、失敗すると同時にエンジンは文字を先に進めながら、各ステップで @code{'>'} のマッチを試みます。この動作は正しい結果を生成します:

@example
>>> print(re.match('<.*?>', s).group())
<html>
@end example

(HTML や XML を正規表現でパースすることは苦痛を伴うものであることは記憶に留めておいて下さい。素早く、汚いパターンは大抵の場合うまく動作しますが、HTML と XML は正規表現が破綻する特別な例です; 全ての可能な場合にうまく動作する正規表現を書き上げたときには、パターンは `非常に' 複雑なものになります。そのような作業をする場合には HTML や XML パーサを利用しましょう。)

@node re VERBOSE の利用,,貪欲 greedy 対非貪欲 non-greedy,よくある問題
@anchor{howto/regex using-re-verbose}@anchor{57c7}
@subsubsection re.VERBOSE の利用


ここまでで、正規表現がとても簡潔な表記であることに気づいたでしょう、また、正規表現は読みやすいものでもないということにも気づいたことでしょう。そこそこに入り組んだ正規表現ははバックスラッシュ、括弧、特殊文字が長く続いて、読みにくく、理解しづらいものになります。

そのような正規表現に対しては、正規表現をコンパイルする時に @ref{2772,,re.VERBOSE} フラグを指定することが助けになります。なぜなら、より明確な書式で正規表現を書けるからです。

@code{re.VERBOSE} の効果はいくつかあります。正規表現内の文字クラス内に `無い' 空白は無視されます。これは、 @code{dog | cat} のような表現が少々可読性の落ちる @code{dog|cat} と等価となるということです、しかし、 @code{[a b]} は依然として @code{'a'}, @code{'b'}, または空白にマッチします。加えて、正規表現にコメントを入れることもできるようになります; @code{#} 文字から次の改行までがコメントの範囲です。三重クォートを利用することで、正規表現をきちんとフォーマットすることができます:

@example
pat = re.compile(r"""
 \s*                 # Skip leading whitespace
 (?P<header>[^:]+)   # Header name
 \s* :               # Whitespace, and a colon
 (?P<value>.*?)      # The header's value -- *? used to
                     # lose the following trailing whitespace
 \s*$                # Trailing whitespace to end-of-line
""", re.VERBOSE)
@end example

これは下よりはるかに読みやすいです:

@example
pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
@end example

@node フィードバック,,よくある問題,正規表現 HOWTO
@anchor{howto/regex feedback}@anchor{57c8}
@subsection フィードバック


正規表現は複雑な話題です。このドキュメントは助けになったでしょうか？わかりにくかったところや、あなたが遭遇した問題が扱われていない等なかったでしょうか？もしそんな問題があれば、著者に改善の提案を送って下さい。

O'Reilly から出版されている Jeffrey Friedl の Mastering Regular Expressions は正規表現に関するほぼ完璧な書籍です (訳注　日本語訳「詳説　正規表現」が出版されています) 。不幸なことに、この本は Perl と Java の正規表現を集中して扱っていて、 Python の正規表現については全く扱っていません、そのため Python プログラミングのためのレファレンスとして使うことはできません。 (第一版はいまや削除された Python の @code{regex} モジュールについて扱っていましたが、これはあまり役に立たないでしょう。) 図書館で調べるのを検討してみましょう。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ソケットプログラミング HOWTO,ソートのテクニック,正規表現 HOWTO,Python HOWTO
@anchor{howto/sockets doc}@anchor{57c9}@anchor{howto/sockets socket-howto}@anchor{39a1}@anchor{howto/sockets socket-programming-howto}@anchor{57ca}@anchor{howto/sockets translation-repo}@anchor{57cb}
@section ソケットプログラミング HOWTO


@*著者: 
Gordon McMillan


@subsubheading 概要



ソケットはそこかしこで使われているが、最大級に誤解されている技術でもある。この文書はソケットの全体像を俯瞰しており、チュートリアルとしてはあまり役に立たない。実際に動くモノを完成させるには、他にもやらなければいけないことがあるからだ。この文書はソケットの微妙なところ (たくさんある) まではカバーしていないが、恥ずかしくない使い方ができるようになる程度の情報は得られるはずだ。

@menu
* ソケット:: 
* ソケットの作成: ソケットの作成<3>. 
* ソケットの利用:: 
* 切断:: 
* ノンブロッキングソケット:: 

@end menu

@node ソケット,ソケットの作成<3>,,ソケットプログラミング HOWTO
@anchor{howto/sockets sockets}@anchor{57cc}
@subsection ソケット


INET (すなわち IPv4) ソケットのことしか語らないつもりだが、利用率でいうとソケットの 99% 以上はこれだ。さらに中でも STREAM (すなわち TCP) ソケットに話題を絞ろうと思う - 自分が何をしているのか分かっているのでない限り (分かってるならこの HOWTO なんて要らないだろ!)、STREAM ソケットが一番分かりやすく、一番性能が出るのだ。そうやって謎に包まれたソケットの正体を明らかにしてゆくと共に、ブロッキングおよびノンブロッキングなソケットの扱いに関するいくつかのヒントを提示しよう。だが、まずはブロッキングソケットから始めることにする。ノンブロッキングを扱うより先に、ブロッキングの仕組みを知っておかなくてはならないのだ。

話を理解しにくくしている要因として、「ソケット」という言葉が文脈によって微妙に違うものを指すことが挙げられる。そこでまず、「クライアント」ソケット - 対話の両端 - と「サーバ」ソケット - 電話交換手みたいなもの - の区別を付けておこう。クライアントアプリケーション (たとえばブラウザ) は「クライアント」ソケットだけを使うが、話し相手のウェブサーバは「サーバ」ソケットと「クライアント」ソケットの両方を使う。

@menu
* 歴史:: 

@end menu

@node 歴史,,,ソケット
@anchor{howto/sockets history}@anchor{57cd}
@subsubsection 歴史


各種 @abbr{IPC (Inter Process Communication} (プロセス間通信) の中でも、ソケットは群を抜いて人気がある。どのプラットフォームにも、ソケットより速い IPC はあるだろう。だが、プラットフォームをまたぐ通信はソケットの独擅場だ。

ソケットは BSD Unix の一部としてバークレイで発明され、インターネットの普及と共に野火のごとく広まった。それももっともなことで、ソケットと INET のコンビによって世界中どんなマシンとも、信じられないほど簡単 (少なくとも他のスキームと比べて) に通信できるようになったのだ。

@node ソケットの作成<3>,ソケットの利用,ソケット,ソケットプログラミング HOWTO
@anchor{howto/sockets creating-a-socket}@anchor{57ce}
@subsection ソケットの作成


あなたがリンクをクリックしてこのページに来たとき、ブラウザは大雑把に言って次のようなことをしたのである:

@example
# create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# now connect to the web server on port 80 - the normal http port
s.connect(("www.python.org", 80))
@end example

この @code{connect} が完了すると、ソケット @code{s} を使ってこのページ文章への要求を送ることができるようになる。その同じソケットが返答を読み、そして破壊される。そう、破壊される。クライアントソケットは通常、一回 (か少数の) やり取りで使い捨てになるのだ。

ウェブサーバで起こる事柄はもう少し複雑だ。まず「サーバソケット」を作る:

@example
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
serversocket.bind((socket.gethostname(), 80))
# become a server socket
serversocket.listen(5)
@end example

ここで注意すべき点がいくつかある: 今回はソケットが外界に見えるよう、 @code{socket.gethostname()} を使った。 @code{s.bind(('localhost', 80))} や  @code{s.bind(('127.0.0.1', 80))} でも「サーバ」ソケットにはなるが、それだと同じマシン内にしか見えないものになってしまう。 @code{s.bind(('@w{'}, 80))} はこのマシンが持っている全てのアドレスで接続可能になるようにという指定になる。

ふたつめ: 小さな番号のポートは大抵、「ウェルノウン (有名)」なサービス (HTTP, SNMP 等々) のために取ってある。お遊びで使うのなら適当に大きな数 (4桁) を使おう。

最後に: @code{listen} の引数はソケットライブラリに、接続要求を 5 個 (通常の最大値) まで順番待ちさせるように命じている。これ以降の外部接続は拒否するのだが、コードが適切に書かれていれば、それで十分すぎるほどだ。

よし、「サーバーソケット」ができて、80 番ポートで耳を澄ましているところまで来た。では、ウェブサーバのメインループに入ろう:

@example
while True:
    # accept connections from outside
    (clientsocket, address) = serversocket.accept()
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = make_client_thread(clientsocket)
    ct.start()
@end example

このループには実際のところ、3 通りの一般的な動作方法がある - @code{clientsocket} を扱うようにスレッドを割り当てたり、@code{clientsocket} を扱う新しいプロセスを作ったり、あるいはノンブロッキングソケットを使うようにアプリを作り直して @code{select} で「サーバ」ソケットとアクティブな @code{clientsocket} の間を多重化したりするのだ。最後のについてはまた後にしよう。ここで理解しておくべき要点はこれだ: 以上が「サーバ」ソケットの仕事の `すべて' である。データは一切送信しないし、受信しない。「クライアント」ソケットを生み出すだけ。我々のバインドされているホストとポートに @code{connect()} してくる `他の' 「クライアント」ソケットに応える形で @code{clientsocket} を作り、作るや否や、さらなる接続を聞きに戻っていくのだ。このふたつの「クライアント」は、あとは勝手に喋っていればいい - 使うポートは動的に割り当てられ、会話が終わればリサイクルに廻される。

@menu
* IPC:: 

@end menu

@node IPC,,,ソケットの作成<3>
@anchor{howto/sockets ipc}@anchor{57cf}
@subsubsection IPC


1つのマシン上の2プロセス間で高速なIPCを行いたい場合は、pipe か共有メモリを検討するべきです。AF_INET ソケットを使用すると決めた場合、「サーバー」ソケットは @code{'localhost'} にバインドしましょう。ほとんどのプラットフォームで、いくつかのネットワークレイヤーをショートカットすることでかなり高速になります。


@subsubheading 参考


@ref{98,,multiprocessing} はクロスプラットフォームなIPCの高級なAPIを提供しています。


@node ソケットの利用,切断,ソケットの作成<3>,ソケットプログラミング HOWTO
@anchor{howto/sockets using-a-socket}@anchor{57d0}
@subsection ソケットの利用


はじめに憶えておくべきなのは、ウェブブラウザの「クライアント」ソケットとウェブサーバの「クライアント」ソケットがまったく同じ種族だということだ。つまり、これは「ピア・トゥ・ピア」(1 対 1) の会話である。別の言い方をすると、 `設計者として自分で会話のエチケット規則を決めなくてはいけない' ということでもある。通常は、 @code{connect} してくるソケットが要求あるいは宣言をして会話を始める。だが、それはそう設計しただけのことだ - ソケットの規則ではない。

さて、コミュニケーションに使う動詞は二組ある。 @code{send} と @code{recv} を使うこともできるし、クライアントソケットをファイルっぽい種族に変形して @code{read} と @code{write} を使っても良い。後者は Java のソケットの表現方法だ。ここで詳しく語るつもりはないが、その場合はソケットも @code{flush} しなければいけない、とだけ言っておく。これはバッファリングした「ファイル」なので、何かを @code{write} してすぐに返答を @code{read} するというのはよくある間違いだ。間に @code{flush} を入れないと、要求がまだ出力バッファにあって永遠に返事が来ない、という可能性がある。

さあ、ソケットの主要な難関に進もう -  @code{send} と @code{recv} はネットワークバッファに働きかけるものだ。だから、手渡したもの (や返してもらいたいもの) を 1 バイトも残さず実際に処理してくれているとは限らない。一般的に言って、 @code{send} はバッファが埋まるまで、@code{recv} はバッファが空になるまで処理をして、そのバイト数を返す。メッセージが完全に処理されるまで繰り返し呼び出すのは `自分の' 責任なのだ。

@code{recv} が 0 バイトを返したときは、向こう側が接続を閉じてしまった (または閉じようとしている途中) という意味だ。もうこの接続でデータを受け取ることはない。永遠にだ。ただ、データ送信は成功するかもしれない; これについてはあとで語ることにしよう。

HTTP のようなプロトコルでは、ひとつのソケットを1回の転送にしか使わない。クライアントは要求を送り、返答を受ける。以上だ。これでソケットは破棄される。だからこの場合、クライアントは受信 0 バイトの時点で返答の末尾を検出することができる。

だが、以降の転送にもそのソケットを使い回すつもりなら、ソケットに @abbr{EOT,End of Transfer} など `存在しない' ことを認識する必要がある。もう一度言おう: ソケットの @code{send} や @code{recv} が 0 バイト処理で返ってきたなら、その接続は終わっている。終わって `いない' なら、いつまで @code{recv} を待てばいいかは分からない。ソケットは「もう読むものが (今のところ) ないぜ」などと `言わない' のだから。このことを少し考えれば、ソケットの真実を悟ることになるだろう: `メッセージは必ず固定長か' (うげぇ) `区切り文字を使うか' (やれやれ) `長さ標識を付けておくか' (かなりマシ) `接続を閉じて終わらせるかのいずれかでなければいけない' のだ。選ぶ権利と責任はまったくもって自分にある (が、正しさの程度に違いはある)。

毎回接続を終わらせるのはイヤだとして、最も単純な解決策は固定長メッセージだろう:

@example
class MySocket:
    """demonstration class only
      - coded for clarity, not efficiency
    """

    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
                            socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        self.sock.connect((host, port))

    def mysend(self, msg):
        totalsent = 0
        while totalsent < MSGLEN:
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise RuntimeError("socket connection broken")
            totalsent = totalsent + sent

    def myreceive(self):
        chunks = []
        bytes_recd = 0
        while bytes_recd < MSGLEN:
            chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
            if chunk == b'@w{'}:
                raise RuntimeError("socket connection broken")
            chunks.append(chunk)
            bytes_recd = bytes_recd + len(chunk)
        return b'@w{'}.join(chunks)
@end example

この送信コードは、ほぼあらゆるメッセージ通信スキームで使える - 文字列を送るとき、Python なら長さを @code{len()} で見極めることができる (中に @code{\0} が埋め込まれていても大丈夫)。難しくしているのは、おもに受信コードである。 (なお、C でも事態はあまり悪くならないが、メッセージに @code{\0} が埋め込まれていると @code{strlen} が使えないのは面倒だ。)

最も簡単な改良法は、メッセージの最初の一文字をタイプ標識にして、そのタイプで長さを決定するというものだ。この場合ふたつの @code{recv} があることになる - 一番目でその一文字 (だけじゃなくても可) を取って長さを調べ、二番目でループして残りを取るのだ。あるいはもし区切り方式の道を行くのであれば、任意のサイズ (4096 か 8192 がネットワークバッファには最適なことが多い) で受信して区切り文字を走査していくことになる。

心に留めておくべき面倒な点がひとつ: 複数メッセージが次々に (何らかの返事を待たずに) 返ってくることのある会話プロトコルなら、そして任意のサイズを @code{recv} に渡しているなら、次のメッセージの冒頭部分まで読んでしまうことがあるかもしれない。そのときは、必要になるまで脇によけて、大切に保管しておく必要がある。

メッセージ冒頭に長さを (たとえば 5 桁の数字で) 付けるのは、それよりもさらに複雑になる。というのも、(信じられないかもしれないが) 一回の @code{recv} で 5 文字を全部受け取ることができるとは限らないからだ。お遊びでやっている間はごまかせても、高負荷ネットワークのもとでは、@code{recv} ループをふたつ使わないコードは、あっと言う間にダメになってしまう - 一番目は長さを見定める用で、二番目はデータ部分を受け取る用だ。うーむ、いやらしい。さらにこのとき、@code{send} も一発で全部を出し切れるとは限らないことに気付くだろう。なお、今こうやって読んでいても、いつか誰もが痛い目を見るのである!

紙面の都合および教育的配慮 (と著者の地位確保) のため、こうした改良は練習問題として残しておく。さあ片付けてしまおう。

@menu
* バイナリデータ:: 

@end menu

@node バイナリデータ,,,ソケットの利用
@anchor{howto/sockets binary-data}@anchor{57d1}
@subsubsection バイナリデータ


It is perfectly possible to send binary data over a socket. The major problem is
that not all machines use the same formats for binary data. For example,
network byte order@footnote{https://en.wikipedia.org/wiki/Endianness#Networking}
is big-endian, with the most significant byte first,
so a 16 bit integer with the value @code{1} would be the two hex bytes @code{00 01}.
However, most common processors (x86/AMD64, ARM, RISC-V), are little-endian,
with the least significant byte first - that same @code{1} would be @code{01 00}.

Socket libraries have calls for converting 16 and 32 bit integers - @code{ntohl,
htonl, ntohs, htons} where "n" means `network' and "h" means `host', "s" means
`short' and "l" means `long'. Where network order is host order, these do
nothing, but where the machine is byte-reversed, these swap the bytes around
appropriately.

In these days of 64-bit machines, the ASCII representation of binary data is
frequently smaller than the binary representation. That's because a surprising
amount of the time, most integers have the value 0, or maybe 1.
The string @code{"0"} would be two bytes, while a full 64-bit integer would be 8.
Of course, this doesn't fit well with fixed-length messages.
Decisions, decisions.

@node 切断,ノンブロッキングソケット,ソケットの利用,ソケットプログラミング HOWTO
@anchor{howto/sockets disconnecting}@anchor{57d2}
@subsection 切断


厳密には、ソケットを @code{close} する前には @code{shutdown} することになっている。 @code{shutdown} は相手ソケットに対する報告であり、渡す引数によって「これ以上こっちからは送らないけど、まだ聞いてるぜ」という意味になったり、「もう聞かない。せいせいした!」だったりする。しかしほとんどのソケットライブラリは、このエチケットを怠るプログラマに慣れてしまって、通常 @code{close} だけで @code{shutdown(); close()} と同じことになる。だから大抵はわざわざ @code{shutdown} しなくてもいい。

@code{shutdown} の効果的な使い方のひとつは、HTTP 風のやりとりだ。クライアントは要求を出してすぐに @code{shutdown(1)} する。これでサーバに、「クライアントは送信完了ですが、まだ受信可能です」と伝わる。サーバは 0 バイト受信で "EOF" を検出することができる。要求を残さず受け取ったことにして良いのだ。対してサーバは返答を送る。その @code{send} が成功したなら、クライアントは実際にまだ受信していたことになる。

Python はこの自動 shutdown をもう一歩進めて、ソケットが GC されるときに必要なら自動で @code{close} してくれると言っている。しかしこれに頼るクセをつけてはいけない。もしソケットが @code{close} せずに姿を消せば、相手ソケットはこちらが遅いだけだと思ってハングしてしまうかもしれない。 `お願いだから' 終わったらちゃんと @code{close} してくれ。

@menu
* ソケットが死ぬと:: 

@end menu

@node ソケットが死ぬと,,,切断
@anchor{howto/sockets when-sockets-die}@anchor{57d3}
@subsubsection ソケットが死ぬと


ブロッキングソケットを使っていて一番いやなのは多分、相手側が意地悪く (@code{close} せずに) ダウンするときに起こる事柄だ。自分側のソケットは高確率でハングするだろう。TCP は信頼性の高いプロトコルなので、ずっとずっと待ち続けて、なかなか見捨てないのだ。スレッドを使っているのであれば、そのスレッド全体が根本から死んだ状態になる。こうなると、もう手の施しようがない。まあ、ブロッキング読み出しの間ロックし続けるといった馬鹿げたことをしていない限り、リソースの点ではたいして消費にならない。だから `ぜったいに' そのスレッドを殺そうとしてはいけない - プロセスよりスレッドが効率的である理由のひとつは、自動リソース回収にまつわるオーバヘッドを避けられるという点にあるのだ。つまり別の言い方をすると、どうにかしてそのスレッドを殺したなら、プロセス全体がぐちゃぐちゃになってしまうだろうということだ。

@node ノンブロッキングソケット,,切断,ソケットプログラミング HOWTO
@anchor{howto/sockets non-blocking-sockets}@anchor{57d4}
@subsection ノンブロッキングソケット


ここまで理解してきたなら、もうソケットの仕組みについて必要なことはほとんど知っていることになる。これからも同じコールを、ほぼ同じように使っていくだけ、それだけだ。これをちゃんとやっていれば、そのアプリはだいたい完璧であろう。

Python の場合、ノンブロッキングにするには @code{socket.setblocking(False)} を使う。 C ならもっと複雑だ (一例を挙げると、BSD 方式の @code{O_NONBLOCK} およびほぼ違いのない POSIX 方式 @code{O_NDELAY} のどちらを選ぶか決めなくてはならなくて、後者は @code{TCP_NODELAY} とは全然別物だったりする) が、考え方はまったく一緒だ。これは、ソケットを作成した後、使用する前に行う。(実際、常識破りなら、切り替えることができます。)

構造上の大きな違いは、 @code{send}, @code{recv}, @code{connect}, @code{accept} が何もしないで戻ってくるかもしれないという点である。選択肢は (当然ながら) いくつかある。返り値とエラーコードをチェックするという方法もある。が、発狂すること請け合いだ。信じないなら、いつかやってみるといい。アプリは肥大化し、バグが増え、CPU を喰い尽くすだろう。だからそんな愚かな解法は飛ばして、正解に進もう。

@code{select} を使え。

C において @code{select} でコードを書くのはかなり面倒だが、Python なら造作もない。しかし Python で @code{select} を理解しておけば C でもほとんど問題なく書ける、という程度には似ている:

@example
ready_to_read, ready_to_write, in_error = \
               select.select(
                  potential_readers,
                  potential_writers,
                  potential_errs,
                  timeout)
@end example

@code{select} に三つのリストを渡しているが、一番目にはあとで読みたくなるかもしれないソケットすべて、二番目には書き込みたくなるかもしれないソケットすべて、最後に (通常は空のままだが) エラーをチェックしたいソケットが入っている。ひとつのソケットが複数にまたがってリストされても構わないことを憶えておくと良い。なお、 @code{select} コールはブロックするが、時間制限を与えることができる。これは、やっておいて損はない - 特に理由がなければ、かなり長い (たとえば 1 分とかの) 時間制限を付けておくことだ。

戻り値として、三つのリストが手に入る。それぞれには、実際に読めるソケット、書けるソケット、エラー中のソケットが入っていて、渡したリストの部分集合 (空集合かもしれない) になっている。

出力のうち、readable リストにあるソケットについては、 @code{recv} がとりあえず `何か' を返すであろう、ということは史上最高度に確信できる。 writable リストも考え方は同じで、 `何か' は送れる。送りたいもの全体は無理かもしれないが、 `何も' ないよりはマシだろう。 (実のところ、ふつうに健康なソケットなら writable で返ってくることができる - それは外向きネットワークバッファに空きがあるというだけの意味しかないのだから)

「サーバ」ソケットは potential_readers リストに入れておこう。それが readable リストに入って出てきたら、 @code{accept} は (ほぼ) 確実に成功するはずだ。どこかへ @code{connect} するために作った新しいソケットは potential_writers リストに入れる。それが writable リストに現れたら、接続が成功している可能性は高いと言える。

じつは @code{select} はブロッキングソケットにも便利に使える。それはブロックするかどうかを見極める方法のひとつである - バッファに何かがあれば readable として返ってくるのだ。しかしこれも、相手の用事がもう済んでいるのか、それとも単に他のことで忙しいだけなのかを見極める役には立たない。

`非互換警報': Unix ではソケットにもファイルにも @code{select} が使える。これを Windows でやろうとしてはいけない。Windows で @code{select} はソケットにしか使えない。また C の場合、高度なソケットオプションの多くは、やり方が Windows では違っている。実際、Windows なら著者は通常、ソケットにスレッドを使っている (これは実に、実にうまくいく)。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ソートのテクニック,Unicode HOWTO,ソケットプログラミング HOWTO,Python HOWTO
@anchor{howto/sorting doc}@anchor{57d5}@anchor{howto/sorting sorting-techniques}@anchor{57d6}@anchor{howto/sorting sortinghowto}@anchor{13f3}@anchor{howto/sorting translation-repo}@anchor{57d7}
@section ソートのテクニック


@*著者: 
Andrew Dalke and Raymond Hettinger


Python のリストにはリストをインプレースに変更する、組み込みメソッド @ref{dc8,,list.sort()} があります。他にもイテラブルからソートしたリストを作成する組み込み関数 @ref{dc7,,sorted()} があります。

このドキュメントでは Python を使った様々なソートのテクニックを探索します。

@menu
* ソートの基本:: 
* Key 関数:: 
* operator モジュールの関数や partial 関数による評価:: 
* 昇順と降順:: 
* ソートの安定性と複合的なソート:: 
* デコレート - ソート - アンデコレート (DSU): デコレート - ソート - アンデコレート DSU. 
* 比較関数:: 
* Strategies For Unorderable Types and Values:: 
* 残りのはしばし: 残りのはしばし<2>. 
* 部分的なソート:: 

@end menu

@node ソートの基本,Key 関数,,ソートのテクニック
@anchor{howto/sorting sorting-basics}@anchor{57d8}
@subsection ソートの基本


単純な昇順のソートはとても簡単です: @ref{dc7,,sorted()} 関数を呼ぶだけです。そうすれば、新たにソートされたリストが返されます:

@example
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
@end example

@ref{dc8,,list.sort()} メソッドを呼びだしても同じことができます。この方法はリストをインプレースに変更します (そして sorted との混乱を避けるため @code{None} を返します)。多くの場合、こちらの方法は @ref{dc7,,sorted()} と比べると不便です - ただし、元々のリストが不要な場合には、わずかですがより効率的です。

@example
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
@end example

違いは他にもあります、 @ref{dc8,,list.sort()} メソッドはリストにのみ定義されています。一方 @ref{dc7,,sorted()} 関数は任意のイテラブルを受け付けます。

@example
>>> sorted(@{1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'@})
[1, 2, 3, 4, 5]
@end example

@node Key 関数,operator モジュールの関数や partial 関数による評価,ソートの基本,ソートのテクニック
@anchor{howto/sorting key-functions}@anchor{57d9}
@subsection Key 関数


The @ref{dc8,,list.sort()} method and the functions @ref{dc7,,sorted()},
@ref{110b,,min()}, @ref{110c,,max()}, @ref{29a6,,heapq.nsmallest()}, and
@ref{29a5,,heapq.nlargest()} have a `key' parameter to specify a function (or
other callable) to be called on each list element prior to making
comparisons.

For example, here's a case-insensitive string comparison using
@ref{fd6,,str.casefold()}:

@example
>>> sorted("This is a test string from Andrew".split(), key=str.casefold)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
@end example

`key' パラメータの値は関数または呼び出し可能オブジェクトであって、単一の引数をとり、ソートに利用されるキー値を返すものでなければいけません。この制約によりソートを高速に行えます、キー関数は各入力レコードに対してきっちり一回だけ呼び出されるからです。

よくある利用パターンはいくつかの要素から成る対象をインデクスのどれかをキーとしてソートすることです。例えば:

@example
>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

同じテクニックは名前づけされた属性 (named attributes) を使うことでオブジェクトに対しても動作します。例えば:

@example
>>> class Student:
...     def __init__(self, name, grade, age):
...         self.name = name
...         self.grade = grade
...         self.age = age
...     def __repr__(self):
...         return repr((self.name, self.grade, self.age))

>>> student_objects = [
...     Student('john', 'A', 15),
...     Student('jane', 'B', 12),
...     Student('dave', 'B', 10),
... ]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

名前づけされた属性を持つオブジェクトは上で示したとおり通常のクラスから作れますし、@ref{4e1,,dataclass} や @ref{85e,,named tuple} のインスタンスでもよいです。

@node operator モジュールの関数や partial 関数による評価,昇順と降順,Key 関数,ソートのテクニック
@anchor{howto/sorting operator-module-functions-and-partial-function-evaluation}@anchor{57da}
@subsection operator モジュールの関数や partial 関数による評価


上で示した @ref{1006,,key function} パターンは非常に一般的なので、Python はアクセサ関数を簡単に速く作れる便利な関数を提供しています。@ref{a3,,operator} モジュールに @ref{c57,,itemgetter()}、@ref{1033,,attrgetter()}、および @ref{1034,,methodcaller()} 関数があります。

これらの関数を利用すると、上の例はもっと簡単で高速になります:

@example
>>> 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)]
@end example

operator モジュールの関数は複数の段階でのソートを可能にします。例えば、 `grade' でソートしてさらに `age' でソートする場合:

@example
>>> 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)]
@end example

@ref{63,,functools} モジュールには他にもキー関数を作るための便利なツールがあります。@ref{217,,partial()} 関数は複数引数の関数の アリティ@footnote{https://en.wikipedia.org/wiki/Arity} を減らし、キー関数に適したものにできます。

@example
>>> from functools import partial
>>> from unicodedata import normalize

>>> names = 'Zoë Åbjørn Núñez Élana Zeke Abe Nubia Eloise'.split()

>>> sorted(names, key=partial(normalize, 'NFD'))
['Abe', 'Åbjørn', 'Eloise', 'Élana', 'Nubia', 'Núñez', 'Zeke', 'Zoë']

>>> sorted(names, key=partial(normalize, 'NFC'))
['Abe', 'Eloise', 'Nubia', 'Núñez', 'Zeke', 'Zoë', 'Åbjørn', 'Élana']
@end example

@node 昇順と降順,ソートの安定性と複合的なソート,operator モジュールの関数や partial 関数による評価,ソートのテクニック
@anchor{howto/sorting ascending-and-descending}@anchor{57db}
@subsection 昇順と降順


@ref{dc8,,list.sort()} と @ref{dc7,,sorted()} の両方とも `reverse' パラメータを 真偽値として受け付けます。このパラメータは降順ソートを行うかどうかの フラグとして利用されます。 例えば、学生のデータを `age' の逆順で得たい場合:

@example
>>> 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)]
@end example

@node ソートの安定性と複合的なソート,デコレート - ソート - アンデコレート DSU,昇順と降順,ソートのテクニック
@anchor{howto/sorting sort-stability-and-complex-sorts}@anchor{57dc}
@subsection ソートの安定性と複合的なソート


ソートは、 安定 (stable)@footnote{https://en.wikipedia.org/wiki/Sorting_algorithm#Stability} であることが保証されています。これはレコードの中に同じキーがある場合、元々の順序が維持されるということを意味します。

@example
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> sorted(data, key=itemgetter(0))
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
@end example

二つの `blue' のレコードが元々の順序を維持して、 @code{('blue', 1)} が @code{('blue', 2)} の前にあることに注意してください。

この素晴しい性質によって複数のソートを段階的に組み合わせることができます。例えば、学生データを `grade' の降順にソートし、さらに `age' の昇順にソートしたい場合には、まず `age' でソートし、次に `grade' でもう一度ソートします:

@example
>>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
>>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

この処理は、リストおよびフィールド名とソート順序のタプルを複数受け取れるラッパー関数へ抽象化できます。

@example
>>> def multisort(xs, specs):
...     for key, reverse in reversed(specs):
...         xs.sort(key=attrgetter(key), reverse=reverse)
...     return xs

>>> multisort(list(student_objects), (('grade', True), ('age', False)))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

Python では Timsort@footnote{https://en.wikipedia.org/wiki/Timsort} アルゴリズムが利用されていて、効率良く複数のソートを行うことができます、これは現在のデータセット中のあらゆる順序をそのまま利用できるからです。

@node デコレート - ソート - アンデコレート DSU,比較関数,ソートの安定性と複合的なソート,ソートのテクニック
@anchor{howto/sorting decorate-sort-undecorate}@anchor{57dd}
@subsection デコレート - ソート - アンデコレート (DSU)


このイディオムは以下の3つのステップにちなんでデコレート-ソート-アンデコレート (Decorate-Sort-Undecorate) と呼ばれています:


@itemize *

@item 
まず、元となるリストをソートしたい順序を制御する新しい値でデコレートします。

@item 
次に、デコレートしたリストをソートします。

@item 
最後に、デコレートを取り除き、新しい順序で元々の値のみを持つリストを作ります。
@end itemize

例えば、DSU アプローチを利用して学生データを `grade' でソートする場合:

@example
>>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
>>> decorated.sort()
>>> [student for grade, i, student in decorated]               # undecorate
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
@end example

このイディオムはタブルが辞書編集的に比較されるため正しく動作します; 最初の要素が比較され、同じ場合には第二の要素が比較され、以下も同様に動きます。

デコレートしたリストのインデクス `i' は全ての場合で含まれる必要はありませんが、そうすることで二つの利点があります:


@itemize *

@item 
ソートが安定になります -- もし二つの要素が同じキーを持つ場合、それらの順序がソートされたリストでも維持されます。

@item 
元々の要素が比較可能な要素を持つとは限りません、なぜならデコレートされたタブルの順序は多くの場合、最初の二つの要素で決定されるからです。例として元のリストは直接比較できない複素数を含むことができます。
@end itemize

このイディオムの別名に Schwartzian transform@footnote{https://en.wikipedia.org/wiki/Schwartzian_transform} があります。これは Perl プログラマの間で有名な Randal L. Schwartz にちなんでいます。

いまや Python のソートは key 関数による方法を提供しているので、このテクニックは不要でしょう。

@node 比較関数,Strategies For Unorderable Types and Values,デコレート - ソート - アンデコレート DSU,ソートのテクニック
@anchor{howto/sorting comparison-functions}@anchor{57de}
@subsection 比較関数


ソートのための絶対的な値を返すキー関数と違って、2つの入力を受け取り、その相対的な順序を計算するような関数を比較関数といいます。

例えば、 天秤@footnote{https://upload.wikimedia.org/wikipedia/commons/1/17/Balance_à_tabac_1850.JPG} は2つのサンプルを比較し、より軽いか、同じか、より重いかの相対的な順序を与えます。同じように、 @code{cmp(a, b)} などの比較関数はより小さいときは負の値を、入力が等しい場合は 0 を、より大きい場合は正の値を返します。

他のプログラミング言語で書かれたアルゴリズムを Python に書き直すときに比較関数を目にすることがよくあります。また、その API の一部として比較関数を提供しているライブラリもあります。例えば、 @ref{42ca,,locale.strcoll()} は比較関数です。

このような場合に対処するため、Python は比較関数をラップしてキー関数として使えるようにする関数 @ref{13f2,,functools.cmp_to_key} を提供しています。

@example
sorted(words, key=cmp_to_key(strcoll))  # locale-aware sort order
@end example

@node Strategies For Unorderable Types and Values,残りのはしばし<2>,比較関数,ソートのテクニック
@anchor{howto/sorting strategies-for-unorderable-types-and-values}@anchor{57df}
@subsection Strategies For Unorderable Types and Values


A number of type and value issues can arise when sorting.
Here are some strategies that can help:


@itemize *

@item 
Convert non-comparable input types to strings prior to sorting:
@end itemize

@example
>>> data = ['twelve', '11', 10]
>>> sorted(map(str, data))
['10', '11', 'twelve']
@end example

This is needed because most cross-type comparisons raise a
@ref{198,,TypeError}.


@itemize *

@item 
Remove special values prior to sorting:
@end itemize

@example
>>> from math import isnan
>>> from itertools import filterfalse
>>> data = [3.3, float('nan'), 1.1, 2.2]
>>> sorted(filterfalse(isnan, data))
[1.1, 2.2, 3.3]
@end example

This is needed because the IEEE-754 standard@footnote{https://en.wikipedia.org/wiki/IEEE_754} specifies that, "Every NaN
shall compare unordered with everything, including itself."

Likewise, @code{None} can be stripped from datasets as well:

@example
>>> data = [3.3, None, 1.1, 2.2]
>>> sorted(x for x in data if x is not None)
[1.1, 2.2, 3.3]
@end example

This is needed because @code{None} is not comparable to other types.


@itemize *

@item 
Convert mapping types into sorted item lists before sorting:
@end itemize

@example
>>> data = [@{'a': 1@}, @{'b': 2@}]
>>> sorted(data, key=lambda d: sorted(d.items()))
[@{'a': 1@}, @{'b': 2@}]
@end example

This is needed because dict-to-dict comparisons raise a
@ref{198,,TypeError}.


@itemize *

@item 
Convert set types into sorted lists before sorting:
@end itemize

@example
>>> data = [@{'a', 'b', 'c'@}, @{'b', 'c', 'd'@}]
>>> sorted(map(sorted, data))
[['a', 'b', 'c'], ['b', 'c', 'd']]
@end example

This is needed because the elements contained in set types do not have a
deterministic order.  For example, @code{list(@{'a', 'b'@})} may produce
either @code{['a', 'b']} or @code{['b', 'a']}.

@node 残りのはしばし<2>,部分的なソート,Strategies For Unorderable Types and Values,ソートのテクニック
@anchor{howto/sorting odds-and-ends}@anchor{57e0}
@subsection 残りのはしばし



@itemize *

@item 
ロケールに対応したソートを行うには、キー関数に @ref{17bd,,locale.strxfrm()} を使うか、比較関数に @ref{42ca,,locale.strcoll()} を使ってください。これが必要なのは、同じアルファベットを使っていたとしても、文化が違えば "アルファベット順" の意味するものが変わることがあるからです。

@item 
`reverse' パラメータはソートの安定性を保ちます (ですから、レコードのキーが等しい場合元々の順序が維持されます)。面白いことにこの影響はパラメータ無しで @ref{a65,,reversed()} 関数を二回使うことで模倣することができます:

@example
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> standard_way = sorted(data, key=itemgetter(0), reverse=True)
>>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0))))
>>> assert standard_way == double_reversed
>>> standard_way
[('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]
@end example

@item 
ソート関数は、2つのオブジェクトを比較する際 @code{<} を用います。したがって、クラスに標準のソート順序を追加することは @ref{14b8,,__lt__()} メソッドを定義することで達成できます。

@example
>>> Student.__lt__ = lambda self, other: self.age < other.age
>>> sorted(student_objects)
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

ただし、@code{<} は @ref{14b8,,__lt__()} が実装されていなければ @ref{1523,,__gt__()} を使って代替することに注意してください (この技法について詳しくは @ref{14b8,,object.__lt__()} を参照してください)。驚きを防ぐため、
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} は6つの比較メソッドを全て実装することを推奨しています。この作業を簡単にするため、@ref{1144,,total_ordering()} デコレータが提供されています。

@item 
key 関数はソートするオブジェクトに依存する必要はありません。 key 関数は外部リソースにアクセスすることもできます。例えば学生の成績が辞書に保存されている場合、それを利用して別の学生の名前のリストをソートすることができます:

@example
>>> students = ['dave', 'john', 'jane']
>>> newgrades = @{'john': 'F', 'jane':'A', 'dave': 'C'@}
>>> sorted(students, key=newgrades.__getitem__)
['jane', 'dave', 'john']
@end example
@end itemize

@node 部分的なソート,,残りのはしばし<2>,ソートのテクニック
@anchor{howto/sorting partial-sorts}@anchor{57e1}
@subsection 部分的なソート


アプリケーションには、データの一部のみが整列されていればよいものがあります。標準ライブラリは完全なソートより少ない作業をするいくつかのツールを提供します。


@itemize *

@item 
@ref{110b,,min()} と @ref{110c,,max()} はそれぞれ最小値と最大値を返します。これらの関数は入力データを一度だけ通過し、補助的なメモリをほとんど要求しません。

@item 
@ref{29a6,,heapq.nsmallest()} と @ref{29a5,,heapq.nlargest()} はそれぞれ最小と最大の値 `n' 個を返します。これらの関数はデータを一度だけ通過し、一度に `n' 要素だけを記憶します。入力の数に対して小さい `n' の値では、これらの関数は完全なソートより比較の回数がはるかに少なくなります。

@item 
@ref{16d5,,heapq.heappush()} と @ref{16d6,,heapq.heappop()} は最小の要素がつねに位置 @code{0} になる、部分的にソートされたデータの配列を作り維持します。これらの関数はタスクスケジューリングに一般的に使われる優先度キューを実装するのに適しています。
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Unicode HOWTO,urllib パッケージを使ってインターネット上のリソースを取得するには,ソートのテクニック,Python HOWTO
@anchor{howto/unicode doc}@anchor{57e2}@anchor{howto/unicode id1}@anchor{57e3}@anchor{howto/unicode translation-repo}@anchor{57e4}@anchor{howto/unicode unicode-howto}@anchor{14bc}
@section Unicode HOWTO


@*リリース: 
1.12


この HOWTO 文書は、文字データの表現のための Unicode 仕様の Python におけるサポートについて論じ、さらに Unicode を使おうというときによく出喰わす多くの問題について説明します。

@menu
* Unicode 入門:: 
* Python の Unicode サポート:: 
* Unicode データを読み書きする:: 
* 謝辞: 謝辞<10>. 

@end menu

@node Unicode 入門,Python の Unicode サポート,,Unicode HOWTO
@anchor{howto/unicode introduction-to-unicode}@anchor{57e5}
@subsection Unicode 入門


@menu
* 定義:: 
* エンコーディング: エンコーディング<3>. 
* 参考資料: 参考資料<3>. 

@end menu

@node 定義,エンコーディング<3>,,Unicode 入門
@anchor{howto/unicode definitions}@anchor{57e6}
@subsubsection 定義


今日のプログラムは広範囲の文字を扱える必要があります。
アプリケーションは国際化され、ユーザーが選べる様々な言語でメッセージや出力を表示します; 同じプログラムが、英語、フランス語、日本語、ヘブライ語、ロシア語でエラーメッセージを出力する必要があるかもしれません。
Webコンテンツはどんな言語でも書かれる可能性がありますし、様々な絵文字が含まれることもあります。
Python の文字列型は文字表現のための Unicode 標準を使っていて、 Python プログラムは有り得る様々な文字を全て扱えます。

Unicode (@indicateurl{https://www.unicode.org/}) は、人類の言語で使われる全ての文字を列挙し、それぞれの文字自身の一意な符号を与えるのを目的とした仕様です。
Unicode 仕様は継続的に改訂され、新しい言語や記号を追加する更新がなされています。

`文字' は文章の最小の構成要素です。
'A', 'B', 'C' などは全て異なる文字です。
'È' と 'Í' も同様に異なる文字です。
文字は、話している言語や文脈によって変わってきます。
例えば、「ローマ数字の 1」という文字 'Ⅰ' は大文字の 'I' とは別の文字です。
両者は通常は同じに見えますが、異なる意味を持つ別々の2つの文字です。

The Unicode standard describes how characters are represented by
`code points'.  A code point value is an integer in the range 0 to
0x10FFFF (about 1.1 million values, the
actual number assigned@footnote{https://www.unicode.org/versions/latest/#Summary}
is less than that). In the standard and in this document, a code point is written
using the notation @code{U+265E} to mean the character with value
@code{0x265e} (9,822 in decimal).

Unicode 標準は、文字とそれに対応するコードポイントを列挙した多くの表を含んでいます:

@example
0061    'a'; LATIN SMALL LETTER A
0062    'b'; LATIN SMALL LETTER B
0063    'c'; LATIN SMALL LETTER C
...
007B    '@{'; LEFT CURLY BRACKET
...
2167    'Ⅷ'; ROMAN NUMERAL EIGHT
2168    'Ⅸ'; ROMAN NUMERAL NINE
...
265E    '♞'; BLACK CHESS KNIGHT
265F    '♟'; BLACK CHESS PAWN
...
1F600   '😀'; GRINNING FACE
1F609   '😉'; WINKING FACE
...
@end example

厳密には、この定義から「これは文字 @code{U+265E} です」と言うのは意味の無いことだと分かります。@code{U+265E} はコードポイントであり、それはある特定の文字を表しているのです; この場合では、 'BLACK CHESS KNIGHT', '♞' という文字を表しています。
形式ばらない文脈では、このコードポイントと文字の区別は忘れ去られることもあります。

文字は画面や紙面上では `グリフ (glyph)' と呼ばれるグラフィック要素の組で表示されます。大文字の A のグリフは例えば、厳密な形は使っているフォントによって異なりますが、斜めの線と水平の線です。たいていの Python コードではグリフの心配をする必要はありません; 一般的には表示する正しいグリフを見付けることは GUI toolkit や端末のフォントレンダラーの仕事です。

@node エンコーディング<3>,参考資料<3>,定義,Unicode 入門
@anchor{howto/unicode encodings}@anchor{57e7}
@subsubsection エンコーディング


前の節をまとめると: Unicode 文字列はコードポイントの列であり、コードポイントとは 0 から @code{0x10FFFF} (10 進表記で 1,114,111) までの数値です。このコードポイント列はメモリ上では `コードユニット' 列として表され、その `コードユニット' 列は 8-bit のバイト列にマップされます。Unicode 文字列をバイト列として翻訳する規則を `文字エンコーディング' または単に `エンコーディング' と呼びます。

The first encoding you might think of is using 32-bit integers as the
code unit, and then using the CPU's representation of 32-bit integers.
In this representation, the string "Python" might look like this:

@example
   P           y           t           h           o           n
0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
@end example

この表現は直接的でわかりやすい方法ですが、この表現を使うにはいくつかの問題があります。


@enumerate 

@item 
可搬性がない; プロセッサが異なるとバイトの順序づけも変わってしまいます。

@item 
無駄な領域が多いです。多くの文書では、コードポイントは 127 未満もしくは 255 未満が多数派を占め、そのため多くの領域が @code{0x00} というバイトで埋め尽くされます。上の文字列は、ASCII 表現では 6 バイトなのに対し、24 バイトのサイズになっています。RAM の使用量が増加するのはそれほど問題にはなりません (デスクトップコンピュータはギガバイト単位の RAM を持っており、通常、文字列はそんな大きさにはなりません) が、ディスクとネットワーク帯域が 4 倍多く使われてしまうのは我慢できるものではありません。

@item 
@code{strlen()} のような現存する C 関数と互換性がありません、そのためワイド文字列関数一式が新たに必要となります。
@end enumerate

Therefore this encoding isn't used very much, and people instead choose other
encodings that are more efficient and convenient, such as UTF-8.

UTF-8 is one of the most commonly used encodings, and Python often
defaults to using it.  UTF stands for "Unicode Transformation Format",
and the '8' means that 8-bit values are used in the encoding.  (There
are also UTF-16 and UTF-32 encodings, but they are less frequently
used than UTF-8.)  UTF-8 uses the following rules:


@enumerate 

@item 
コードポイントが 128 未満だった場合、対応するバイト値で表現します。

@item 
コードポイントが 128 以上の場合、128 から 255 までのバイトからなる、2、3 または 4 バイトのシーケンスに変換します。
@end enumerate

UTF-8 はいくつかの便利な性質を持っています:


@enumerate 

@item 
任意の Unicode コードポイントを扱うことができる。

@item 
A Unicode string is turned into a sequence of bytes that contains embedded
zero bytes only where they represent the null character (U+0000). This means
that UTF-8 strings can be processed by C functions such as @code{strcpy()} and sent
through protocols that can't handle zero bytes for anything other than
end-of-string markers.

@item 
ASCII テキストの文字列は UTF-8 テキストとしても有効です。

@item 
UTF-8 はかなりコンパクトです; よく使われている文字の大多数は 1 バイトか 2 バイトで表現できます。

@item 
バイトが欠落したり、失われた場合、次の UTF-8 でエンコードされたコードポイントの開始を決定し、再同期することができる可能性があります。同様の理由でランダムな 8-bit データは正当な UTF-8 とみなされにくくなっています。

@item 
UTF-8 is a byte oriented encoding. The encoding specifies that each
character is represented by a specific sequence of one or more bytes. This
avoids the byte-ordering issues that can occur with integer and word oriented
encodings, like UTF-16 and UTF-32, where the sequence of bytes varies depending
on the hardware on which the string was encoded.
@end enumerate

@node 参考資料<3>,,エンコーディング<3>,Unicode 入門
@anchor{howto/unicode references}@anchor{57e8}
@subsubsection 参考資料


Unicode コンソーシアムのサイト@footnote{https://www.unicode.org} には文字の図表、用語辞典、PDF 版の Unicode 仕様があります。これ読むのはそれなりに難しいので覚悟してください。Unicode の起源と発展の 年表@footnote{https://www.unicode.org/history/} もサイトにあります。

On the Computerphile Youtube channel, Tom Scott briefly
discusses the history of Unicode and UTF-8@footnote{https://www.youtube.com/watch?v=MijmeoH9LT4}
(9 minutes 36 seconds).

標準を理解する助けにするために、Jukka Korpela が Unicode 文字表を読むための 入門ガイド@footnote{https://jkorpela.fi/unicode/guide.html} を書いています。

Another good introductory article@footnote{https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/}
was written by Joel Spolsky.
If this introduction didn't make things clear to you, you should try
reading this alternate article before continuing.

Wikipedia の記事はしばしば役に立ちます; 例えば、"character encoding@footnote{https://en.wikipedia.org/wiki/Character_encoding}" や UTF-8@footnote{https://en.wikipedia.org/wiki/UTF-8} の記事を読んでみてください。

@node Python の Unicode サポート,Unicode データを読み書きする,Unicode 入門,Unicode HOWTO
@anchor{howto/unicode python-s-unicode-support}@anchor{57e9}
@subsection Python の Unicode サポート


ここまでで Unicode の基礎を学びました、ここから Python の Unicode 機能に触れます。

@menu
* 文字列型:: 
* バイト列への変換:: 
* Python ソースコード内の Unicode リテラル:: 
* Unicode プロパティ:: 
* Comparing Strings:: 
* Unicode 正規表現:: 
* 参考資料: 参考資料<4>. 

@end menu

@node 文字列型,バイト列への変換,,Python の Unicode サポート
@anchor{howto/unicode the-string-type}@anchor{57ea}
@subsubsection 文字列型


Since Python 3.0, the language's @ref{169,,str} type contains Unicode
characters, meaning any string created using @code{"unicode rocks!"}, @code{'unicode
rocks!'}, or the triple-quoted string syntax is stored as Unicode.

Python ソースコードのデフォルトエンコーディングは UTF-8 なので、文字列リテラルの中に Unicode 文字をそのまま含めることができます:

@example
try:
    with open('/tmp/input.txt', 'r') as f:
        ...
except OSError:
    # 'File not found' error message.
    print("Fichier non trouvé")
@end example

追記: Python3 は Unicode 文字を使った識別子もサポートしています:

@example
répertoire = "/tmp/records.log"
with open(répertoire, "w") as f:
    f.write("test\n")
@end example

エディタである特定の文字が入力できなかったり、とある理由でソースコードを ASCII のみに保ちたい場合は、文字列リテラルでエスケープシーケンスが使えます。(使ってるシステムによっては、u でエスケープされた文字列ではなく、実物の大文字のラムダのグリフが見えるかもしれません。):

@example
>>> "\N@{GREEK CAPITAL LETTER DELTA@}"  # Using the character name
'\u0394'
>>> "\u0394"                          # Using a 16-bit hex value
'\u0394'
>>> "\U00000394"                      # Using a 32-bit hex value
'\u0394'
@end example

加えて、 @ref{192,,bytes} クラスの @ref{ad3,,decode()} メソッドを使って文字列を作ることもできます。このメソッドは @code{UTF-8} のような値を `encoding' 引数に取り、オプションで `errors' 引数を取ります。

`errors' 引数は、入力文字列に対しエンコーディングルールに従った変換ができなかったときの対応方法を指定します。この引数に使える値は @code{'strict'} (@ref{c08,,UnicodeDecodeError} を送出する)、 @code{'replace'} (@code{REPLACEMENT CHARACTER} である @code{U+FFFD} を使う)、 @code{'ignore'} (結果となる Unicode から単に文字を除く) 、@code{'backslashreplace'} (エスケープシーケンス @code{\xNN} を挿入する) です。次の例はこれらの違いを示しています:

@example
>>> b'\x80abc'.decode("utf-8", "strict")
Traceback (most recent call last):
    ...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
  invalid start byte
>>> b'\x80abc'.decode("utf-8", "replace")
'\ufffdabc'
>>> b'\x80abc'.decode("utf-8", "backslashreplace")
'\\x80abc'
>>> b'\x80abc'.decode("utf-8", "ignore")
'abc'
@end example

エンコーディングはエンコーディングの名前を含んだ文字列で指定されます。 Python はおよそ 100 の異なるエンコーディングに対応しています; 一覧は Python ライブラリリファレンスの @ref{fb8,,標準エンコーディング} を参照してください。いくつかのエンコーディングは複数の名前を持っています; 例えば、 @code{'latin-1'} と @code{'iso_8859_1'} と @code{'8859'} は全て同じエンコーディングの別名です。

Unicode 文字列の一つの文字は @ref{19ef,,chr()} 組み込み関数で作成することができます、この関数は整数を引数にとり、対応するコードポイントを含む長さ1の Unicode 文字列を返します。逆の操作は @ref{233b,,ord()} 組み込み関数です、この関数は一文字の Unicode 文字列を引数にとり、コードポイント値を返します:

@example
>>> chr(57344)
'\ue000'
>>> ord('\ue000')
57344
@end example

@node バイト列への変換,Python ソースコード内の Unicode リテラル,文字列型,Python の Unicode サポート
@anchor{howto/unicode converting-to-bytes}@anchor{57eb}
@subsubsection バイト列への変換


@ref{ad3,,bytes.decode()} とは処理が逆向きのメソッドが @ref{ad2,,str.encode()} です。このメソッドは、 Unicode 文字列を指定された `encoding' でエンコードして、 @ref{192,,bytes} による表現で返します。

`errors' 引数は @ref{ad3,,decode()} メソッドのパラメータと同じものですが、サポートされているハンドラの数がもう少し多いです。
@code{'strict'} 、 @code{'ignore'} 、 @code{'replace'} (このメソッドでは、エンコードできなかった文字の代わりに疑問符を挿入する) の他に、 @code{'xmlcharrefreplace'} (XML 文字参照を挿入する) と @code{backslashreplace} (エスケープシーケンス @code{\nNNNN} を挿入する)、 @code{namereplace} (エスケープシーケンス @code{\N@{...@}} を挿入する) があります。

次の例では、それぞれの異なる処理結果が示されています:

@example
>>> u = chr(40960) + 'abcd' + chr(1972)
>>> u.encode('utf-8')
b'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
    ...
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in
  position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
b'abcd'
>>> u.encode('ascii', 'replace')
b'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
b'&#40960;abcd&#1972;'
>>> u.encode('ascii', 'backslashreplace')
b'\\ua000abcd\\u07b4'
>>> u.encode('ascii', 'namereplace')
b'\\N@{YI SYLLABLE IT@}abcd\\u07b4'
@end example

利用可能なエンコーディングを登録したり、アクセスしたりする低レベルのルーチンは @ref{1c,,codecs} モジュールにあります。新しいエンコーディングを実装するには、 @ref{1c,,codecs} モジュールを理解していることも必要になります。しかし、このモジュールのエンコードやデコードの関数は、使い勝手が良いというより低レベルな関数で、新しいエンコーディングを書くのは特殊な作業なので、この HOWTO では扱わないことにします。

@node Python ソースコード内の Unicode リテラル,Unicode プロパティ,バイト列への変換,Python の Unicode サポート
@anchor{howto/unicode unicode-literals-in-python-source-code}@anchor{57ec}
@subsubsection Python ソースコード内の Unicode リテラル


Python のソースコード内では、特定のコードポイントはエスケープシーケンス @code{\u} を使い、続けてコードポイントを4桁の16進数を書きます。エスケープシーケンス @code{\U} も同様です、ただし4桁ではなく8桁の16進数を使います:

@example
>>> s = "a\xac\u1234\u20ac\U00008000"
... #     ^^^^ two-digit hex escape
... #         ^^^^^^ four-digit Unicode escape
... #                     ^^^^^^^^^^ eight-digit Unicode escape
>>> [ord(c) for c in s]
[97, 172, 4660, 8364, 32768]
@end example

127 より大きいコードポイントに対してエスケープシーケンスを使うのは、エスケープシーケンスがあまり多くないうちは有効ですが、フランス語等のアクセントを使う言語でメッセージのような多くのアクセント文字を使う場合には邪魔になります。文字を @ref{19ef,,chr()} 組み込み関数を使って組み上げることもできますが、それはさらに長くなってしまうでしょう。

理想的にはあなたの言語の自然なエンコーディングでリテラルを書くことでしょう。そうなれば、Python のソースコードをアクセント付きの文字を自然に表示するお気に入りのエディタで編集し、実行時に正しい文字が得られます。

Python はデフォルトでは UTF-8 ソースコードを書くことができます、ただしどのエンコーディングを使うかを宣言すればほとんどのエンコーディングを使えます。それはソースファイルの一行目や二行目に特別なコメントを含めることによってできます:

@example
#!/usr/bin/env python
# -*- coding: latin-1 -*-

u = 'abcdé'
print(ord(u[-1]))
@end example

この構文は Emacs のファイル固有の変数を指定する表記から影響を受けています。Emacs は様々な変数をサポートしていますが、Python がサポートしているのは 'coding' のみです。 @code{-*-} の記法は Emacs に対してコメントが特別であることを示します。これは Python にとって意味はありませんが慣習で使われています。 Python はコメント中に @code{coding: name} または @code{coding=name} を探します。

このようなコメントを含んでいない場合、すでに述べた通り、使われるデフォルトエンコーディングは UTF-8 になります。より詳しい情報は 
@geindex Python Enhancement Proposals; PEP 263
PEP 263@footnote{https://peps.python.org/pep-0263/} を参照してください。

@node Unicode プロパティ,Comparing Strings,Python ソースコード内の Unicode リテラル,Python の Unicode サポート
@anchor{howto/unicode id2}@anchor{57ed}@anchor{howto/unicode unicode-properties}@anchor{2653}
@subsubsection Unicode プロパティ


The Unicode specification includes a database of information about
code points.  For each defined code point, the information includes
the character's name, its category, the numeric value if applicable
(for characters representing numeric concepts such as the Roman
numerals, fractions such as one-third and four-fifths, etc.).  There
are also display-related properties, such as how to use the code point
in bidirectional text.

以下のプログラムはいくつかの文字に対する情報を表示し、特定の文字の数値を印字します:

@example
import unicodedata

u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)

for i, c in enumerate(u):
    print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
    print(unicodedata.name(c))

# Get numeric value of second character
print(unicodedata.numeric(u[1]))
@end example

実行すると、このように出力されます:

@example
0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
1 0bf2 No TAMIL NUMBER ONE THOUSAND
2 0f84 Mn TIBETAN MARK HALANTA
3 1770 Lo TAGBANWA LETTER SA
4 33af So SQUARE RAD OVER S SQUARED
1000.0
@end example

カテゴリーコードは文字の性質を略記で表したものです。カテゴリーコードは "Letter"、"Number"、"Punctuation"、"Symbol" などのカテゴリーに分類され、さらにサブカテゴリーに細分化されます。上記の出力からコードを拾うと、@code{'Ll'} は 'Letter, lowercase'、@code{'No'} は "Number, other"、@code{'Mn'} は "Mark, nonspacing"、@code{'So'} は "Symbol, other" を意味しています。カテゴリーコードの一覧は Unicode Character Database 文書の General Category Values 節@footnote{https://www.unicode.org/reports/tr44/#General_Category_Values} を参照してください。

@node Comparing Strings,Unicode 正規表現,Unicode プロパティ,Python の Unicode サポート
@anchor{howto/unicode comparing-strings}@anchor{57ee}
@subsubsection Comparing Strings


Unicode adds some complication to comparing strings, because the same
set of characters can be represented by different sequences of code
points.  For example, a letter like 'ê' can be represented as a single
code point U+00EA, or as U+0065 U+0302, which is the code point for
'e' followed by a code point for 'COMBINING CIRCUMFLEX ACCENT'.  These
will produce the same output when printed, but one is a string of
length 1 and the other is of length 2.

One tool for a case-insensitive comparison is the
@ref{fd6,,casefold()} string method that converts a string to a
case-insensitive form following an algorithm described by the Unicode
Standard.  This algorithm has special handling for characters such as
the German letter 'ß' (code point U+00DF), which becomes the pair of
lowercase letters 'ss'.

@example
>>> street = 'Gürzenichstraße'
>>> street.casefold()
'gürzenichstrasse'
@end example

A second tool is the @ref{10b,,unicodedata} module's
@ref{8e4,,normalize()} function that converts strings to one
of several normal forms, where letters followed by a combining character are
replaced with single characters.  @ref{8e4,,normalize()} can
be used to perform string comparisons that won't falsely report
inequality if two strings use combining characters differently:

@example
import unicodedata

def compare_strs(s1, s2):
    def NFD(s):
        return unicodedata.normalize('NFD', s)

    return NFD(s1) == NFD(s2)

single_char = 'ê'
multiple_chars = '\N@{LATIN SMALL LETTER E@}\N@{COMBINING CIRCUMFLEX ACCENT@}'
print('length of first string=', len(single_char))
print('length of second string=', len(multiple_chars))
print(compare_strs(single_char, multiple_chars))
@end example

実行すると、このように出力されます:

@example
$ python compare-strs.py
length of first string= 1
length of second string= 2
True
@end example

The first argument to the @ref{8e4,,normalize()} function is a
string giving the desired normalization form, which can be one of
'NFC', 'NFKC', 'NFD', and 'NFKD'.

The Unicode Standard also specifies how to do caseless comparisons:

@example
import unicodedata

def compare_caseless(s1, s2):
    def NFD(s):
        return unicodedata.normalize('NFD', s)

    return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold())

# Example usage
single_char = 'ê'
multiple_chars = '\N@{LATIN CAPITAL LETTER E@}\N@{COMBINING CIRCUMFLEX ACCENT@}'

print(compare_caseless(single_char, multiple_chars))
@end example

This will print @code{True}.  (Why is @code{NFD()} invoked twice?  Because
there are a few characters that make @ref{fd6,,casefold()} return a
non-normalized string, so the result needs to be normalized again. See
section 3.13 of the Unicode Standard for a discussion and an example.)

@node Unicode 正規表現,参考資料<4>,Comparing Strings,Python の Unicode サポート
@anchor{howto/unicode unicode-regular-expressions}@anchor{57ef}
@subsubsection Unicode 正規表現


@ref{be,,re} モジュールがサポートしている正規表現はバイト列や文字列として与えられます。 @code{\d} や @code{\w} などのいくつかの特殊な文字シーケンスは、そのパターンがバイト列として与えられたのか文字列として与えられたのかによって、異なる意味を持ちます。例えば、 @code{\d} はバイト列では @code{[0-9]} の範囲の文字と一致しますが、文字列では @code{'Nd'} カテゴリーにある任意の文字と一致します。

この例にある文字列には、タイ語の数字とアラビア数字の両方で数字の 57 が書いてあります。

@example
import re
p = re.compile(r'\d+')

s = "Over \u0e55\u0e57 57 flavours"
m = p.search(s)
print(repr(m.group()))
@end example

実行すると、 @code{\d+} はタイ語の数字と一致し、それを出力します。フラグ @ref{83e,,re.ASCII} を @ref{dce,,compile()} に渡した場合、 @code{\d+} は先程とは違って部分文字列 "57" に一致します。

同様に、 @code{\w} は非常に多くの Unicode 文字に一致しますが、バイト列の場合もしくは @ref{83e,,re.ASCII} が渡された場合は @code{[a-zA-Z0-9_]} にしか一致しません。 @code{\s} は文字列では Unicode 空白文字に、バイト列では @code{[ \t\n\r\f\v]} に一致します。

@node 参考資料<4>,,Unicode 正規表現,Python の Unicode サポート
@anchor{howto/unicode id3}@anchor{57f0}
@subsubsection 参考資料


@c comment should these be mentioned earlier, e.g. at the start of the "introduction to Unicode" first section?

Python の Unicode サポートについての参考になる議論は以下の2つです:


@itemize *

@item 
Nick Coghlan による Processing Text Files in Python 3@footnote{https://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html}

@item 
Ned Batchelder による PyCon 2012 での発表 Pragmatic Unicode@footnote{https://nedbatchelder.com/text/unipain.html}
@end itemize

@ref{169,,str} 型については Python ライブラリリファレンスの @ref{1fe0,,テキストシーケンス型 --- str} で解説されています。

@ref{10b,,unicodedata} モジュールについてのドキュメント。

@ref{1c,,codecs} モジュールについてのドキュメント。

Marc-André Lemburg は EuroPython 2002 で "Python and Unicode" というタイトルのプレゼンテーション (PDF スライド)@footnote{https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf} を行いました。このスライドは Python 2 の Unicode 機能 (Unicode 文字列型が @code{unicode} と呼ばれ、リテラルは @code{u} で始まります) の設計について概観する素晴しい資料です。

@node Unicode データを読み書きする,謝辞<10>,Python の Unicode サポート,Unicode HOWTO
@anchor{howto/unicode reading-and-writing-unicode-data}@anchor{57f1}
@subsection Unicode データを読み書きする


一旦 Unicode データに対してコードが動作するように書き終えたら、次の問題は入出力です。プログラムは Unicode 文字列をどう受けとり、どう Unicode を外部記憶装置や送受信装置に適した形式に変換するのでしょう?

入力ソースと出力先に依存しないような方法は可能です; アプリケーションに利用されているライブラリが Unicode をそのままサポートしているかを調べなければいけません。例えば XML パーサーは大抵 Unicode データを返します。多くのリレーショナルデータベースも Unicode 値の入ったコラムをサポートしていますし、 SQL の問い合わせで Unicode 値を返すことができます。

Unicode のデータはディスクに書き込まれたり、ソケットを介して送信されたりするにあたって、通常、特定のエンコーディングに変換されます。推奨はされませんが、これを手動で行うことも可能です。ファイルを開き、8バイトオブジェクトを読み込み、バイト列を @code{bytes.decode(encoding)} で変換することにより実現できます。

1つの問題はエンコーディングがマルチバイトに渡るという性質です; 1つの Unicode 文字はいくつかのバイトで表現され得ます。任意のサイズのチャンク (例えば、1024 もしくは 4096 バイト) にファイルの内容を読み込みたい場合、ある1つの Unicode 文字をエンコードしたバイト列の一部だけがチャンクの末尾まで読み込まれたケースに対応する、エラー処理コードを書く必要があります。1つの解決策はファイル全体をメモリに読み込み、デコード処理を実行することですが、こうしてしまうと非常に大きなファイルを処理するときの妨げになります; 2 GiB のファイルを読み込む必要がある場合、2 GiB の RAM が必要になります。(実際には、少なくともある瞬間では、エンコードされた文字列と Unicode 文字列の両方をメモリに保持する必要があるため、より多くのメモリが必要です。)

The solution would be to use the low-level decoding interface to catch the case
of partial coding sequences.  The work of implementing this has already been
done for you: the built-in @ref{316,,open()} function can return a file-like object
that assumes the file's contents are in a specified encoding and accepts Unicode
parameters for methods such as @ref{206c,,read()} and
@ref{205b,,write()}.  This works through @ref{316,,open()}'s `encoding' and
`errors' parameters which are interpreted just like those in @ref{ad2,,str.encode()}
and @ref{ad3,,bytes.decode()}.

そのためファイルから Unicode を読むのは単純です:

@example
with open('unicode.txt', encoding='utf-8') as f:
    for line in f:
        print(repr(line))
@end example

読み書きの両方ができる update モードでファイルを開くことも可能です:

@example
with open('test', encoding='utf-8', mode='w+') as f:
    f.write('\u4500 blah blah blah\n')
    f.seek(0)
    print(repr(f.readline()[:1]))
@end example

Unicode 文字 @code{U+FEFF} は byte-order mark (BOM) として使われ、ファイルのバイト順の自動判定を支援するために、ファイルの最初の文字として書かれます。UTF-16 のようないくつかのエンコーディングは、ファイルの先頭に BOM があることを要求します; そのようなエンコーディングが使われるとき、自動的に BOM が最初の文字として書かれ、ファイルを読むときに暗黙の内に取り除かれます。これらのエンコーディングには、リトルエンディアン (little-endian) 用の 'utf-16-le' やビッグエンディアン (big-endian) 用の 'utf-16-be' というような変種があり、これらは特定の1つのバイト順を指定していて BOM をスキップしません。

In some areas, it is also convention to use a "BOM" at the start of UTF-8
encoded files; the name is misleading since UTF-8 is not byte-order dependent.
The mark simply announces that the file is encoded in UTF-8.  For reading such
files, use the 'utf-8-sig' codec to automatically skip the mark if present.

@menu
* Unicode ファイル名:: 
* Unicode 対応のプログラムを書くための Tips:: 
* 参考資料: 参考資料<5>. 

@end menu

@node Unicode ファイル名,Unicode 対応のプログラムを書くための Tips,,Unicode データを読み書きする
@anchor{howto/unicode unicode-filenames}@anchor{57f2}
@subsubsection Unicode ファイル名


Most of the operating systems in common use today support filenames
that contain arbitrary Unicode characters.  Usually this is
implemented by converting the Unicode string into some encoding that
varies depending on the system.  Today Python is converging on using
UTF-8: Python on MacOS has used UTF-8 for several versions, and Python
3.6 switched to using UTF-8 on Windows as well.  On Unix systems,
there will only be a @ref{75d,,filesystem encoding}. if you've set the @code{LANG} or @code{LC_CTYPE} environment variables; if
you haven't, the default encoding is again UTF-8.

@ref{e53,,sys.getfilesystemencoding()} 関数は現在のシステムで利用するエンコーディングを返し、エンコーディングを手動で設定したい場合利用します、ただしわざわざそうする積極的な理由はありません。読み書きのためにファイルを開く時には、ファイル名を Unicode 文字列として渡すだけで正しいエンコーディングに自動的に変更されます:

@example
filename = 'filename\u4500abc'
with open(filename, 'w') as f:
    f.write('blah\n')
@end example

@ref{26d,,os.stat()} のような @ref{a5,,os} モジュールの関数も Unicode のファイル名を受け付けます。

The @ref{1312,,os.listdir()} function returns filenames, which raises an issue: should it return
the Unicode version of filenames, or should it return bytes containing
the encoded versions?  @ref{1312,,os.listdir()} can do both, depending on whether you
provided the directory path as bytes or a Unicode string.  If you pass a
Unicode string as the path, filenames will be decoded using the filesystem's
encoding and a list of Unicode strings will be returned, while passing a byte
path will return the filenames as bytes.  For example,
assuming the default @ref{75d,,filesystem encoding} is UTF-8, running the following program:

@example
fn = 'filename\u4500abc'
f = open(fn, 'w')
f.close()

import os
print(os.listdir(b'.'))
print(os.listdir('.'))
@end example

以下の出力結果が生成されます:

@example
$ python listdir-test.py
[b'filename\xe4\x94\x80abc', ...]
['filename\u4500abc', ...]
@end example

最初のリストは UTF-8 でエンコーディングされたファイル名を含み、第二のリストは Unicode 版を含んでいます。

Note that on most occasions, you should can just stick with using
Unicode with these APIs.  The bytes APIs should only be used on
systems where undecodable file names can be present; that's
pretty much only Unix systems now.

@node Unicode 対応のプログラムを書くための Tips,参考資料<5>,Unicode ファイル名,Unicode データを読み書きする
@anchor{howto/unicode tips-for-writing-unicode-aware-programs}@anchor{57f3}
@subsubsection Unicode 対応のプログラムを書くための Tips


この章では Unicode を扱うプログラムを書くためのいくつかの提案を紹介します。

最も重要な助言としては:

@quotation

ソフトウェアは内部では Unicode 文字列のみを利用し、入力データはできるだけ早期にデコードし、出力の直前でエンコードすべきです。
@end quotation

If you attempt to write processing functions that accept both Unicode and byte
strings, you will find your program vulnerable to bugs wherever you combine the
two different kinds of strings.  There is no automatic encoding or decoding: if
you do e.g. @code{str + bytes}, a @ref{198,,TypeError} will be raised.

web ブラウザから来るデータやその他の信頼できないところからのデータを利用する場合、それらの文字列から生成したコマンド行の実行や、それらの文字列をデータベースに蓄える前に文字列の中に不正な文字が含まれていないか確認するのが一般的です。もしそういう状況になった場合には、エンコードされたバイトデータではなく、デコードされた文字列のチェックを入念に行なって下さい; いくつかのエンコーディングは問題となる性質を持っています、例えば全単射でなかったり、完全に ASCII 互換でないなど。入力データがエンコーディングを指定している場合でもそうして下さい、なぜなら攻撃者は巧みに悪意あるテキストをエンコードした文字列の中に隠すことができるからです。

@menu
* ファイルエンコーディングの変換:: 
* 不明なエンコーディングのファイル:: 

@end menu

@node ファイルエンコーディングの変換,不明なエンコーディングのファイル,,Unicode 対応のプログラムを書くための Tips
@anchor{howto/unicode converting-between-file-encodings}@anchor{57f4}
@subsubsection ファイルエンコーディングの変換


The @ref{1dd4,,StreamRecoder} class can transparently convert between
encodings, taking a stream that returns data in encoding #1
and behaving like a stream returning data in encoding #2.

For example, if you have an input file `f' that's in Latin-1, you
can wrap it with a @ref{1dd4,,StreamRecoder} to return bytes encoded in
UTF-8:

@example
new_f = codecs.StreamRecoder(f,
    # en/decoder: used by read() to encode its results and
    # by write() to decode its input.
    codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),

    # reader/writer: used to read and write to the stream.
    codecs.getreader('latin-1'), codecs.getwriter('latin-1') )
@end example

@node 不明なエンコーディングのファイル,,ファイルエンコーディングの変換,Unicode 対応のプログラムを書くための Tips
@anchor{howto/unicode files-in-an-unknown-encoding}@anchor{57f5}
@subsubsection 不明なエンコーディングのファイル


What can you do if you need to make a change to a file, but don't know
the file's encoding?  If you know the encoding is ASCII-compatible and
only want to examine or modify the ASCII parts, you can open the file
with the @code{surrogateescape} error handler:

@example
with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
    data = f.read()

# make changes to the string 'data'

with open(fname + '.new', 'w',
          encoding="ascii", errors="surrogateescape") as f:
    f.write(data)
@end example

The @code{surrogateescape} error handler will decode any non-ASCII bytes
as code points in a special range running from U+DC80 to
U+DCFF.  These code points will then turn back into the
same bytes when the @code{surrogateescape} error handler is used to
encode the data and write it back out.

@node 参考資料<5>,,Unicode 対応のプログラムを書くための Tips,Unicode データを読み書きする
@anchor{howto/unicode id4}@anchor{57f6}
@subsubsection 参考資料


One section of Mastering Python 3 Input/Output@footnote{https://pyvideo.org/video/289/pycon-2010--mastering-python-3-i-o},
a PyCon 2010 talk by David Beazley, discusses text processing and binary data handling.

Marc-André Lemburg のプレゼンテーション "Writing Unicode-aware Applications in Python" の PDF スライドが <@indicateurl{https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf}> から入手可能です、そして文字エンコーディングの問題と同様にアプリケーションの国際化やローカライズについても議論されています。このスライドは Python 2.x のみをカバーしています。

The Guts of Unicode in Python@footnote{https://pyvideo.org/video/1768/the-guts-of-unicode-in-python}
is a PyCon 2013 talk by Benjamin Peterson that discusses the internal Unicode
representation in Python 3.3.

@node 謝辞<10>,,Unicode データを読み書きする,Unicode HOWTO
@anchor{howto/unicode acknowledgements}@anchor{57f7}
@subsection 謝辞


このドキュメントの最初の草稿は Andrew Kuchling によって書かれました。それからさらに Alexander Belopolsky, Georg Brandl, Andrew Kuchling, Ezio Melotti らで改訂が重ねられています。

この記事中の誤りの指摘や提案を申し出てくれた以下の人々に感謝します: Éric Araujo, Nicholas Bastin, Nick Coghlan, Marius Gedminas, Kent Johnson, Ken Krugler, Marc-André Lemburg, Martin von Löwis, Terry J. Reedy, Serhiy Storchaka, Eryk Sun, Chad Whitacre, Graham Wideman.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node urllib パッケージを使ってインターネット上のリソースを取得するには,ipaddressモジュールの紹介,Unicode HOWTO,Python HOWTO
@anchor{howto/urllib2 doc}@anchor{57f8}@anchor{howto/urllib2 howto-fetch-internet-resources-using-the-urllib-package}@anchor{57f9}@anchor{howto/urllib2 translation-repo}@anchor{57fa}@anchor{howto/urllib2 urllib-howto}@anchor{3f8a}
@section urllib パッケージを使ってインターネット上のリソースを取得するには


@*著者: 
Michael Foord@footnote{https://agileabstractions.com/}


@menu
* はじめに: はじめに<17>. 
* URL を取得する:: 
* 例外を処理する: 例外を処理する<2>. 
* info と geturl:: 
* Openers と Handlers:: 
* Basic 認証:: 
* プロキシ:: 
* ソケットとレイヤー:: 
* 脚注:: 

@end menu

@node はじめに<17>,URL を取得する,,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 introduction}@anchor{57fb}
@subsection はじめに


@subsubheading Related Articles



同じように Python でインターネットリソースを取得するのに以下の記事が役に立ちます:


@itemize *

@item 
Basic Authentication@footnote{https://web.archive.org/web/20201215133350/http://www.voidspace.org.uk/python/articles/authentication.shtml}

@quotation

`Basic 認証' についてのチュートリアルで Python の例がついています。
@end quotation
@end itemize

`urllib.request' は URLs (Uniform Resource Locators) を取得するための Python モジュールです。このモジュールはとても簡単なインターフェースを `urlopen' 関数の形式で提供しています。また、このモジュールは一般的な状況で利用するためにいくらか複雑なインターフェースも提供しています - basic 認証やクッキー、プロキシ等。これらは handler や opener と呼ばれるオブジェクトとして提供されます。

urllib.request は多くの "URL スキーム" (URL の ":" の前の文字列で識別されるもの - 例えば "@indicateurl{ftp://python.org/}" では "ftp") の URL を、関連するネットワークプロトコル(例えば FTP, HTTP) を利用することで、取得できます。

単純な状況では `urlopen' はとても簡単に使うことができます。しかし HTTP の URL を開くときにエラーが起きたり、特殊なケースに遭遇すると、 HyperText Transfer Protocol に関するいくつかのことを理解する必要があります。 HTTP に関して最も包括的で信頼できる文献は 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} です。この文書は技術文書なので簡単には読めません。この HOWTO の目的は `urllib' の利用法を例示することです、 HTTP についてはその助けになるのに十分に詳しく載せています。このドキュメントは @ref{111,,urllib.request} のドキュメントの代わりにはなりませんが、補完する役割を持っています。

@node URL を取得する,例外を処理する<2>,はじめに<17>,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 fetching-urls}@anchor{57fc}
@subsection URL を取得する


urllib.request を利用する最も簡単な方法は以下です:

@example
import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
   html = response.read()
@end example

URL によってリソースを取得し、それを一時的な場所に保存しておきたいときは、 @ref{c52,,shutil.copyfileobj()} と @ref{6ed,,tempfile.NamedTemporaryFile()} 関数を使って行うことができます:

@example
import shutil
import tempfile
import urllib.request

with urllib.request.urlopen('http://python.org/') as response:
    with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
        shutil.copyfileobj(response, tmp_file)

with open(tmp_file.name) as html:
    pass
@end example

多くの urllib の利用法はこのように簡単です ('http:' の代わりに URL を 'ftp:' や 'file:' 等で始めればできます)。しかし、このチュートリアルの目的は、特に HTTP に絞って、より複雑な状況を説明することです。

HTTP はリクエスト (request) とレスポンス (response) が基本となっています - クライアントがリクエストし、サーバーがレスポンスを送ります。urllib.request はこれを真似て、作成する HTTP リクエストを表現する @code{Request} オブジェクトを備えています。リクエストオブジェクトを作成する最も簡単な方法は取得したい URL を指定することです。@code{urlopen} をこのオブジェクトを使って呼び出すと、リクエストした URL のレスポンスオブジェクトが返されます。このレスポンスはファイルライクオブジェクトで、これはつまりレスポンスに @code{.read()} と呼び出せることを意味しています:

@example
import urllib.request

req = urllib.request.Request('http://python.org/')
with urllib.request.urlopen(req) as response:
   the_page = response.read()
@end example

urllib.request は同じリクエストインターフェースを全ての URL スキームに対して利用できるようにしています。例えば、FTP リクエストの場合はこうできます:

@example
req = urllib.request.Request('ftp://example.com/')
@end example

HTTP の場合には、リクエストオブジェクトに対して二つの特別な操作ができます: 一つ目はサーバーに送るデータを渡すことができる、二つ目はサーバーに送るデータやリクエスト自身に `ついての' 特別な情報 ("metadata")を渡すことができます - これらの送られる情報は HTTP 「ヘッダ」です。今度はこれらに関してひとつひとつ見ていきましょう。

@menu
* データ:: 
* ヘッダ:: 

@end menu

@node データ,ヘッダ,,URL を取得する
@anchor{howto/urllib2 data}@anchor{57fd}
@subsubsection データ


URL にデータを送りたい場合はよくあります (しばしば、その URL は CGI (Common Gateway Interface) スクリプトや他の web アプリケーションを参照することになります)。これは HTTP では、 `POST' リクエストとして知られる方法で行なわれます。これは web 上で HTML フォームを埋めて送信するときにブラウザが行なっていることです。全ての POST がフォームから送られるとは限りません: 自身のアプリケーションに対して任意のデータを POST を使って送ることができます。一般的な HTML フォームの場合、データは標準的な方法でエンコードされている必要があり、リクエストオブジェクトに @code{data} 引数として渡します。エンコーディングは @ref{110,,urllib.parse} ライブラリの関数を使って行います。

@example
import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = @{'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' @}

data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()
@end example

他のエンコーディングが必要な場合があることに注意して下さい (例えば、 HTML フォームからファイルをアップロードするための詳細については HTML Specification@comma{} Form Submission@footnote{https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13} を見て下さい)。

@code{data} 引数を渡さない場合、urllib は `GET' リクエストを利用します。GET と POST リクエストの一つの違いは、POST リクエストにしばしば、「副作用」があることです: POST リクエストはいくつかの方法によってシステムの状態を変化させます (例えば100ポンドのスパムの缶詰をドアの前まで配達する注文を web サイトで行う)。とはいえ HTTP 標準で明確にされている内容では、POST は `常に' 副作用を持ち、GET リクエストは `決して' 副作用を持たないことを意図するけれども、、GET リクエストが副作用を持つことも、POST リクエストが副作用を持たないことも、妨げられません。HTTP の GET リクエストでもデータ自身をエンコーディングすることでデータを渡すことができます。

以下のようにして行います:

@example
>>> import urllib.request
>>> import urllib.parse
>>> data = @{@}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.parse.urlencode(data)
>>> print(url_values)  # The order may differ from below.
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
>>> data = urllib.request.urlopen(full_url)
@end example

@code{?} を URL に加え、それにエンコードされた値が続くことで、完全な URL が作られていることに注意して下さい。

@node ヘッダ,,データ,URL を取得する
@anchor{howto/urllib2 headers}@anchor{57fe}
@subsubsection ヘッダ


ここでは特定の HTTP ヘッダについて議論します、 HTTP リクエストにヘッダを追加する方法について例示します。

いくつかの web サイト @footnote{
Google を例題にする。
} はプログラムからブラウズされることを嫌っていたり、異なるブラウザに対して異なるバージョンを送ります @footnote{
ブラウザを検知すること (browser sniffing) は web サイトのデザインにおけるとても悪い習慣です - web 標準を利用する方が賢明でしょう。
不幸なことに未だに多くの web サイトが異なるブラウザに対して異なるバージョンを返しています。
}。デフォルトでは urllib は自身の情報を @code{Python-urllib/x.y} として扱います ( @code{x} と @code{y} は Python のリリースバージョンのメジャーバージョンとマイナーバージョンです、例えば @code{Python-urllib/2.5} など)。これによって web サイト側が混乱したり、動作しないかもしれません。ブラウザは自身の情報を @code{User-Agent} ヘッダ @footnote{
MSIE 6 のユーザエージェントは `'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'' です。
} を通して扱っています。リクエストオブジェクトを作るときに、ヘッダに辞書を渡すことができます。以下の例は上の例と同じですが、自身を Internet Explorer @footnote{
HTTP リクエストヘッダの詳細については、 @uref{https://jkorpela.fi/http.html,Quick Reference to HTTP Headers} を参照して下さい。
} のバージョンの一つとして扱っています。

@example
import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = @{'name': 'Michael Foord',
          'location': 'Northampton',
          'language': 'Python' @}
headers = @{'User-Agent': user_agent@}

data = urllib.parse.urlencode(values)
data = data.encode('ascii')
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as response:
   the_page = response.read()
@end example

レスポンスは二つの便利なメソッドも持っています。 @ref{57ff,,info と geturl} の節を見て下さい、この節は後で問題が起きた場合に見ておくべき内容です。

@node 例外を処理する<2>,info と geturl,URL を取得する,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 handling-exceptions}@anchor{5800}
@subsection 例外を処理する


`urlopen' raises @ref{2be,,URLError} when it cannot handle a response (though as
usual with Python APIs, built-in exceptions such as @ref{2ec,,ValueError},
@ref{198,,TypeError} etc. may also be raised).

@ref{11e0,,HTTPError} is the subclass of @ref{2be,,URLError} raised in the specific case of
HTTP URLs.

例外クラスは @ref{10f,,urllib.error} モジュールから提供されています。

@menu
* URLError:: 
* HTTPError:: 
* エラーをラップする:: 

@end menu

@node URLError,HTTPError,,例外を処理する<2>
@anchor{howto/urllib2 urlerror}@anchor{5801}
@subsubsection URLError


URLError が送出されることはよく起こります、それはネットワーク接続が無い場合や、指定したサーバが無い場合です。この場合、例外は 'reason' 属性を持っていて、この属性はエラーコードとエラーメッセージのテキストを含むタプルです。

例:

@example
>>> req = urllib.request.Request('http://www.pretend_server.org')
>>> try: urllib.request.urlopen(req)
... except urllib.error.URLError as e:
...     print(e.reason)
...
(4, 'getaddrinfo failed')
@end example

@node HTTPError,エラーをラップする,URLError,例外を処理する<2>
@anchor{howto/urllib2 httperror}@anchor{5802}
@subsubsection HTTPError


Every HTTP response from the server contains a numeric "status code". Sometimes
the status code indicates that the server is unable to fulfil the request. The
default handlers will handle some of these responses for you (for example, if
the response is a "redirection" that requests the client fetch the document from
a different URL, urllib will handle that for you). For those it can't handle,
urlopen will raise an @ref{11e0,,HTTPError}. Typical errors include '404' (page not
found), '403' (request forbidden), and '401' (authentication required).

HTTP のエラーコード全てについては 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html} の10節を参照して下さい。

The @ref{11e0,,HTTPError} instance raised will have an integer 'code' attribute, which
corresponds to the error sent by the server.

@menu
* エラーコード:: 

@end menu

@node エラーコード,,,HTTPError
@anchor{howto/urllib2 error-codes}@anchor{5803}
@subsubsection エラーコード


デフォルトハンドラーはリダイレクト(コードは300番台にあります) を処理し、100--299番台のコードは成功を意味しているので、たいていの場合は400--599番台のエラーコードのみを見るだけですみます。

@ref{3faf,,http.server.BaseHTTPRequestHandler.responses} is a useful dictionary of
response codes that shows all the response codes used by 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://datatracker.ietf.org/doc/html/rfc2616.html}.
An excerpt from the dictionary is shown below

@example
responses = @{
    ...
    <HTTPStatus.OK: 200>: ('OK', 'Request fulfilled, document follows'),
    ...
    <HTTPStatus.FORBIDDEN: 403>: ('Forbidden',
                                  'Request forbidden -- authorization will '
                                  'not help'),
    <HTTPStatus.NOT_FOUND: 404>: ('Not Found',
                                  'Nothing matches the given URI'),
    ...
    <HTTPStatus.IM_A_TEAPOT: 418>: ("I'm a Teapot",
                                    'Server refuses to brew coffee because '
                                    'it is a teapot'),
    ...
    <HTTPStatus.SERVICE_UNAVAILABLE: 503>: ('Service Unavailable',
                                            'The server cannot process the '
                                            'request due to a high load'),
    ...
    @}
@end example

エラーが起きた場合、サーバーは HTTP エラーコード `および' エラーページを返して応答します。 @ref{11e0,,HTTPError} インスタンスはエラーページのレスポンスとして扱えます。これは code 属性だけでなく、 @code{urllib.response} モジュールが返すような read, geturl, info メソッドも持つことを意味します:

@example
>>> req = urllib.request.Request('http://www.python.org/fish.html')
>>> try:
...     urllib.request.urlopen(req)
... except urllib.error.HTTPError as e:
...     print(e.code)
...     print(e.read())
...
404
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
  ...
  <title>Page Not Found</title>\n
  ...
@end example

@node エラーをラップする,,HTTPError,例外を処理する<2>
@anchor{howto/urllib2 wrapping-it-up}@anchor{5804}
@subsubsection エラーをラップする


So if you want to be prepared for @ref{11e0,,HTTPError} `or' @ref{2be,,URLError} there are two
basic approaches. I prefer the second approach.

@menu
* その1:: 
* その2:: 

@end menu

@node その1,その2,,エラーをラップする
@anchor{howto/urllib2 number-1}@anchor{5805}
@subsubsection その1


@example
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError as e:
    print('The server couldn\'t fulfill the request.')
    print('Error code: ', e.code)
except URLError as e:
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
else:
    # everything is fine
@end example

@cartouche
@quotation 注釈 
The @code{except HTTPError} `must' come first, otherwise @code{except URLError}
will `also' catch an @ref{11e0,,HTTPError}.
@end quotation
@end cartouche

@node その2,,その1,エラーをラップする
@anchor{howto/urllib2 number-2}@anchor{5806}
@subsubsection その2


@example
from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request(someurl)
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e, 'reason'):
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    elif hasattr(e, 'code'):
        print('The server couldn\'t fulfill the request.')
        print('Error code: ', e.code)
else:
    # everything is fine
@end example

@node info と geturl,Openers と Handlers,例外を処理する<2>,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 info-and-geturl}@anchor{57ff}
@subsection info と geturl


The response returned by urlopen (or the @ref{11e0,,HTTPError} instance) has two
useful methods @code{info()} and @code{geturl()} and is defined in the module
@ref{112,,urllib.response}.


@itemize *

@item 
`geturl' - これは取得したページの実際の URL を返します。 @code{urlopen} (または利用される opener オブジェクト) はリダイレクトに追従するため、有用です。取得したページの URL は要求した URL と同じとは限りません。

@item 
`info' - これは取得したページ (特にサーバからヘッダ)を表す辞書風オブジェクトを返します。これは現在では @ref{3fc8,,http.client.HTTPMessage} インスタンスです。
@end itemize

典型的なヘッダは 'Content-length', 'Content-type' 等を含んでいます。 HTTP ヘッダの意味と利用法について簡単な説明つきの便利な一覧 Quick Reference to HTTP Headers@footnote{https://jkorpela.fi/http.html} を参照して下さい。

@node Openers と Handlers,Basic 認証,info と geturl,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 openers-and-handlers}@anchor{5807}
@subsection Openers と Handlers


URL を取得する場合、opener (混乱を招きやすい名前ですが、 @ref{3f18,,urllib.request.OpenerDirector} のインスタンス) を利用します。標準的にはデフォルトの opener を - @code{urlopen} を通して - 利用していますが、カスタムの opener を作成することもできます。 opener は handler を利用します。全ての「一番厄介な仕事」はハンドラによって行なわれます。各 handler は特定の URL スキーム (http, ftp, 等) での URL の開き方を知っていたり、 URL を開く局面でどう処理するかを知っています、例えば HTTP リダイレクションや HTTP のクッキーなど。

インストール済みの特定のハンドラで URL を取得したい場合には、 opener を作成したいと思うでしょう、例えばクッキーを処理する opener が得たい場合や、リダイレクションを処理しない opener を得たい場合。

opener を作成するには、 @code{OpenerDirector} をインスタンス化して、続けて、 @code{.add_handler(some_handler_instance)} を呼び出します。

それに代わる方法として、 @code{build_opener} を利用することもできます、これは opener オブジェクトを一回の関数呼び出しで作成できる便利な関数です。 @code{build_opener} はいくつかのハンドラをデフォルトで追加しますが、デフォルトのハンドラに対して追加、継承のどちらかまたは両方を行うのに手っ取り早い方法を提供してくれます。

追加したくなる可能性がある handler としては、プロキシ処理、認証など、一般的ですがいくらか特定の状況に限られるものでしょう。

@code{install_opener} も (グローバルな) デフォルト @code{opener} オブジェクトの作成に利用できます。つまり、 @code{urlopen} を呼び出すと、インストールした opener が利用されます。

opener オブジェクトは @code{open} メソッドを持っていて、 @code{urlopen} 関数と同じ様に、url を取得するのに直接呼び出すことができます: 利便性を除けば @code{install_opener} を使う必要はありません。

@node Basic 認証,プロキシ,Openers と Handlers,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 basic-authentication}@anchor{5808}
@subsection Basic 認証


To illustrate creating and installing a handler we will use the
@code{HTTPBasicAuthHandler}. For a more detailed discussion of this subject --
including an explanation of how Basic Authentication works - see the Basic Authentication Tutorial@footnote{https://web.archive.org/web/20201215133350/http://www.voidspace.org.uk/python/articles/authentication.shtml}.

認証が必要な場合、サーバは認証を要求するヘッダ (401 のエラーコードとともに) を送ります。これによって認証スキームと 'realm' が指定されます。ヘッダはこのようになっています: @code{WWW-Authenticate: SCHEME realm="REALM"} 。

例

@example
WWW-Authenticate: Basic realm="cPanel Users"
@end example

クライアントはリクエストヘッダに含まれる realm に対して適切な名前とパスワードとともにリクエストを再試行する必要があります。これが 'basic 認証' です。一連の流れを簡単化するために、 @code{HTTPBasicAuthHandler} のインスタンスを作成し、 opener が handler を利用するようにします。

@code{HTTPBasicAuthHandler} はパスワードマネージャーと呼ばれる、 URL と realm をパスワードとユーザ名への対応づけを処理する、オブジェクトを利用します。 realm が何なのか(サーバから返される認証ヘッダから) 知りたい場合には、 @code{HTTPPasswordMgr} を利用できます。多くの場合、realm が何なのかについて気にすることはありません。そのような場合には @code{HTTPPasswordMgrWithDefaultRealm} を使うと便利です。これは URL に対してデフォルトのユーザ名とパスワードを指定できます。これによって特定の realm に対する代替の組み合わせを提供することなしに利用できるようになります。このことは @code{add_password} メソッドの realm 引数として @code{None} を与えることで明示することができます。

トップレベルの URL が認証が必要なはじめに URL です。この URL よりも「深い」URL を渡しても .add_password() は同様にマッチします。:

@example
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
@end example

@cartouche
@quotation 注釈 
In the above example we only supplied our @code{HTTPBasicAuthHandler} to
@code{build_opener}. By default openers have the handlers for normal situations
-- @code{ProxyHandler} (if a proxy setting such as an @code{http_proxy}
environment variable is set), @code{UnknownHandler}, @code{HTTPHandler},
@code{HTTPDefaultErrorHandler}, @code{HTTPRedirectHandler}, @code{FTPHandler},
@code{FileHandler}, @code{DataHandler}, @code{HTTPErrorProcessor}.
@end quotation
@end cartouche

@code{top_level_url} は実際には "@indicateurl{http://example.com/}" のような完全な URL ('http:' スキームとホスト名、オプションとしてポート番号、含む)  `あるいは' "example.com" や "example.com:8080" (後者はポート番号を含む) のような "authority" (つまり、ホスト名とオプションとしてポート番号を含む) の `どちらでも' かまいません。authority の場合には "userinfo" 要素は含んではいけません - 例えば "joe:password@@example.com" は不適切です。

@node プロキシ,ソケットとレイヤー,Basic 認証,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 proxies}@anchor{5809}
@subsection プロキシ


`urllib' は自動でプロキシ設定を認識して使います。これは通常の handler の組に含まれる @code{ProxyHandler} を通して行なわれます。たいていの場合はこれでうまくいきますが、役に立たない場合もあります @footnote{
私の場合は仕事中にインターネットにアクセスするにはプロキシを利用する必要があります。`localhost' の URL に対してこのプロキシを経由してアクセスしようとすれば、ブロックされます。IE を proxy を利用するように設定すれば、urllib はその情報を利用します。localhost のサーバでスクリプトをテストしようとすると、urllib がプロキシを利用するのを止めなければいけません。
}。この問題に対処する一つの方法はプロキシを定義しない @code{ProxyHandler} を組み立てることです。この方法は @ref{5808,,Basic Authentication} handler を設定したときと同じような流れで行うことができます:

@example
>>> proxy_support = urllib.request.ProxyHandler(@{@})
>>> opener = urllib.request.build_opener(proxy_support)
>>> urllib.request.install_opener(opener)
@end example

@cartouche
@quotation 注釈 
現在 @code{urllib.request} はプロキシ経由で @code{https} ロケーションを取得する機能をサポートしていません。しかし、urllib.request をこのレシピ @footnote{
urllib opener for SSL proxy (CONNECT method): @uref{https://code.activestate.com/recipes/456195-urrlib2-opener-for-ssl-proxy-connect-method/,ASPN Cookbook Recipe}.
} で拡張することで可能にすることができます。
@end quotation
@end cartouche

@cartouche
@quotation 注釈 
変数 @code{REQUEST_METHOD} が設定されている場合、 @code{HTTP_PROXY} は無視されます; @ref{3f15,,getproxies()} のドキュメンテーションを参照してください。
@end quotation
@end cartouche

@node ソケットとレイヤー,脚注,プロキシ,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 sockets-and-layers}@anchor{580a}
@subsection ソケットとレイヤー


Web 上からリソースを取得する Python の機能はレイヤー化されています。urllib は @ref{73,,http.client} ライブラリを利用していますが、そのライブラリはさらに socket ライブラリを利用しています。

Python 2.3 ではレスポンスがタイムアウトするまでのソケットの待ち時間を指定することができます。これは web ページを取得する場合に便利に使うことができます。socket モジュールのデフォルトでは `タイムアウトが無く' ハングしてしまうかもしれません。現在では socket のタイムアウトは http.client や urllib.request のレベルからは隠蔽されていています。しかし、以下を利用することで全てのソケットに対してグローバルにデフォルトタイムアウトを設定することができます

@example
import socket
import urllib.request

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('http://www.voidspace.org.uk')
response = urllib.request.urlopen(req)
@end example


__________________________________________________________________


@node 脚注,,ソケットとレイヤー,urllib パッケージを使ってインターネット上のリソースを取得するには
@anchor{howto/urllib2 footnotes}@anchor{580b}
@subsection 脚注


このドキュメントは John Lee によって査読、改訂されました。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c import ipaddress

@node ipaddressモジュールの紹介,DTrace と SystemTap で CPython を測定する,urllib パッケージを使ってインターネット上のリソースを取得するには,Python HOWTO
@anchor{howto/ipaddress doc}@anchor{580c}@anchor{howto/ipaddress an-introduction-to-the-ipaddress-module}@anchor{580d}@anchor{howto/ipaddress ipaddress-howto}@anchor{41c8}@anchor{howto/ipaddress translation-repo}@anchor{580e}
@section ipaddressモジュールの紹介


@*author: 
Peter Moody


@*author: 
Nick Coghlan


@subsubheading 概要



このドキュメントは @ref{84,,ipaddress} モジュールへのやさしい入門を提供するのが目的です。これは主にまだIPネットワーキングの用語に詳しくないユーザーを対象としていますが、@ref{84,,ipaddress} がどのようにIPネットワークアドレス処理の概念を表現しているかをざっと見るのにも役立つかもしれません。

@menu
* アドレス/ネットワーク/インターフェースオブジェクトの作成:: 
* アドレス/ネットワーク/インターフェースオブジェクト:: 
* アドレスのリストとしてのネットワーク:: 
* 比較: 比較<4>. 
* 他のモジュールでIPアドレスを使用する:: 
* インスタンスの生成に失敗した場合にさらに詳細を取得する:: 

@end menu

@node アドレス/ネットワーク/インターフェースオブジェクトの作成,アドレス/ネットワーク/インターフェースオブジェクト,,ipaddressモジュールの紹介
@anchor{howto/ipaddress creating-address-network-interface-objects}@anchor{580f}
@subsection アドレス/ネットワーク/インターフェースオブジェクトの作成


@ref{84,,ipaddress} はIPアドレスを検査したり操作したりするためのモジュールであるため、まずはオブジェクトを作成したほうが良いでしょう。文字列および整数を使用して @ref{84,,ipaddress} を使用してオブジェクトを作成できます。

@menu
* IPバージョンについての注意:: 
* IPホストアドレス:: 
* ネットワークを定義する:: 
* ホストインターフェース:: 

@end menu

@node IPバージョンについての注意,IPホストアドレス,,アドレス/ネットワーク/インターフェースオブジェクトの作成
@anchor{howto/ipaddress a-note-on-ip-versions}@anchor{5810}
@subsubsection IPバージョンについての注意


IPアドレッシングに詳しくない読者にとっては、インターネットプロトコル(IP)が現在バージョン4プロトコルからバージョン6へと移行している途中であることを知っておくのが重要です。この移行はプロトコルのバージョン4が世界中の需要に対応するために十分なアドレスを提供できないことが大きな理由で起こっており、特にインターネットへ直接接続する機器が増えている状況を踏まえたものです。

上述した2つのプロトコルバージョンの違いの詳細を説明するのはこの入門ドキュメントの対象範囲を超えていますが、読者は少なくともこれらの2つのバージョンが存在することと、どちらかのバージョンを強制的に使用することが必要になることもあるということを認識する必要があります。

@node IPホストアドレス,ネットワークを定義する,IPバージョンについての注意,アドレス/ネットワーク/インターフェースオブジェクトの作成
@anchor{howto/ipaddress ip-host-addresses}@anchor{5811}
@subsubsection IPホストアドレス


アドレスは多くの場合「ホストアドレス」と呼ばれ、IPアドレッシングを扱う場合の最も基本的な単位です。アドレスを作成する単純な方法は @ref{41ca,,ipaddress.ip_address()} ファクトリー関数を使用することで、この方法では渡された値をもとにIPv4かIPv6アドレスのどちらかを自動的に決定します:

@example
>>> ipaddress.ip_address('192.0.2.1')
IPv4Address('192.0.2.1')
>>> ipaddress.ip_address('2001:DB8::1')
IPv6Address('2001:db8::1')
@end example

アドレスは整数から直接作成することも可能です。32ビットに収まる値はIPv4アドレスであるとみなされます:

@example
>>> ipaddress.ip_address(3221225985)
IPv4Address('192.0.2.1')
>>> ipaddress.ip_address(42540766411282592856903984951653826561)
IPv6Address('2001:db8::1')
@end example

IPv4またはIPv6アドレスの使用を強制するには、適切なクラスを直接呼び出す必要があります。これは特にIPv6アドレスを小さな整数で作成する場合に役立ちます:

@example
>>> ipaddress.ip_address(1)
IPv4Address('0.0.0.1')
>>> ipaddress.IPv4Address(1)
IPv4Address('0.0.0.1')
>>> ipaddress.IPv6Address(1)
IPv6Address('::1')
@end example

@node ネットワークを定義する,ホストインターフェース,IPホストアドレス,アドレス/ネットワーク/インターフェースオブジェクトの作成
@anchor{howto/ipaddress defining-networks}@anchor{5812}
@subsubsection ネットワークを定義する


ホストアドレスは通常IPネットワークへ統合され、 @ref{84,,ipaddress} はネットワーク定義の作成、検査、操作の手段を提供します。IPネットワークオブジェクトはネットワークの一部であるホストアドレスの範囲を定義する文字列から生成されます。この情報の最も単純な形式は「ネットワークアドレス/ネットワークプレフィックス」のペアであり、プレフィックスは先頭のビット数として定義され、アドレスがネットワークの一部であるかどうか、それらのビットに期待される値がネットワークアドレスに定義されているかを判断するために比較されます。

アドレスについては、正しいIPバージョンを自動的に判断するファクトリー関数が提供されます:

@example
>>> ipaddress.ip_network('192.0.2.0/24')
IPv4Network('192.0.2.0/24')
>>> ipaddress.ip_network('2001:db8::0/96')
IPv6Network('2001:db8::/96')
@end example

ネットワークオブジェクトにはホストビットを設定することができません。これについての実践的な効果は @code{192.0.2.1/24} がネットワークを表さないということです。次の項でより詳しく説明しますが、ネットワーク内IP表記は一般的に特定のネットワーク上のネットワークインターフェースを表すのに使用されるため、このような定義はインターフェースオブジェクトと呼ばれます。

デフォルトでは、ホストビットセットの指定でネットワークオブジェクトを作成しようとすると @ref{2ec,,ValueError} が発生する結果となります。 @code{strict=False} フラグをコンストラクタに渡すと、追加分のビットをゼロとして強制的に処理するように要求できます:

@example
>>> ipaddress.ip_network('192.0.2.1/24')
Traceback (most recent call last):
   ...
ValueError: 192.0.2.1/24 has host bits set
>>> ipaddress.ip_network('192.0.2.1/24', strict=False)
IPv4Network('192.0.2.0/24')
@end example

文字列形式では劇的に柔軟性を提供できる一方、ネットワークはちょうどホストアドレスのように整数で定義することもできます。この場合、ネットワークは整数により特定できる単一のアドレスのみを含むものとして処理され、ネットワークプレフィックスはネットワークアドレスの全体を含みます:

@example
>>> ipaddress.ip_network(3221225984)
IPv4Network('192.0.2.0/32')
>>> ipaddress.ip_network(42540766411282592856903984951653826560)
IPv6Network('2001:db8::/128')
@end example

アドレスについては、ファクトリー関数を呼ぶ代わりにクラスコンストラクタを直接呼ぶことで、作成対象のネットワークを特定の種類に強制することができます。

@node ホストインターフェース,,ネットワークを定義する,アドレス/ネットワーク/インターフェースオブジェクトの作成
@anchor{howto/ipaddress host-interfaces}@anchor{5813}
@subsubsection ホストインターフェース


直前に述べたように、特定のネットワーク上のアドレスを示したい場合には、アドレスもネットワーククラスも十分ではありません。 @code{192.0.2.1/24} のような表記は「 @code{192.0.2.0/24} のネットワーク上の @code{192.0.2.1} のホスト」の短縮形として通常ネットワークエンジニアやファイアウォールやルータ用のツールを書く人が使用し、 @ref{84,,ipaddress} はそれに応じて特定のネットワークとアドレスを関連づけるハイブリッドクラス集を提供します。アドレス部分がネットワークアドレスであることに制限されないことを除き、作成用のインターフェースはネットワーク定義用のインターフェースと同一です。

@example
>>> ipaddress.ip_interface('192.0.2.1/24')
IPv4Interface('192.0.2.1/24')
>>> ipaddress.ip_interface('2001:db8::1/96')
IPv6Interface('2001:db8::1/96')
@end example

整数入力は(ネットワークと同様に)受け入れられ、適切なコンストラクタを直接呼び出すことで特定のIPバージョンの使用を強制できます。

@node アドレス/ネットワーク/インターフェースオブジェクト,アドレスのリストとしてのネットワーク,アドレス/ネットワーク/インターフェースオブジェクトの作成,ipaddressモジュールの紹介
@anchor{howto/ipaddress inspecting-address-network-interface-objects}@anchor{5814}
@subsection アドレス/ネットワーク/インターフェースオブジェクト


さて、IPv(4|6)(アドレス|ネットワーク|インターフェース)オブジェクトをわざわざ作成したので、多分それについて情報がほしいことでしょう。 @ref{84,,ipaddress} はこの作業を簡単で直観的にできるようにします。

IPバージョンを抽出する:

@example
>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> addr6 = ipaddress.ip_address('2001:db8::1')
>>> addr6.version
6
>>> addr4.version
4
@end example

インターフェースからネットワークを取得する:

@example
>>> host4 = ipaddress.ip_interface('192.0.2.1/24')
>>> host4.network
IPv4Network('192.0.2.0/24')
>>> host6 = ipaddress.ip_interface('2001:db8::1/96')
>>> host6.network
IPv6Network('2001:db8::/96')
@end example

個別なアドレスがいくつネットワークに存在するかを調べる:

@example
>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> net4.num_addresses
256
>>> net6 = ipaddress.ip_network('2001:db8::0/96')
>>> net6.num_addresses
4294967296
@end example

「使用可能」なネットワーク上のアドレスを順番にたどる:

@example
>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> for x in net4.hosts():
...     print(x)
192.0.2.1
192.0.2.2
192.0.2.3
192.0.2.4
...
192.0.2.252
192.0.2.253
192.0.2.254
@end example

ネットマスクを取得(例: ネットワークプレフィックスに応じてビットを設定)したりホストマスク(ネットマスクの一部ではない任意のビット)を取得する:

@example
>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> net4.netmask
IPv4Address('255.255.255.0')
>>> net4.hostmask
IPv4Address('0.0.0.255')
>>> net6 = ipaddress.ip_network('2001:db8::0/96')
>>> net6.netmask
IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::')
>>> net6.hostmask
IPv6Address('::ffff:ffff')
@end example

アドレスを展開したり圧縮したりする:

@example
>>> addr6.exploded
'2001:0db8:0000:0000:0000:0000:0000:0001'
>>> addr6.compressed
'2001:db8::1'
>>> net6.exploded
'2001:0db8:0000:0000:0000:0000:0000:0000/96'
>>> net6.compressed
'2001:db8::/96'
@end example

IPv4は展開や圧縮には対応していませんが、それでも関連したオブジェクトが適切なプロパティを提供し、バージョンに対して中立なコードがIPv4アドレスを正しく処理する一方でIPv6向けには最も簡潔または最も詳細な形式が使用されることを保証します。

@node アドレスのリストとしてのネットワーク,比較<4>,アドレス/ネットワーク/インターフェースオブジェクト,ipaddressモジュールの紹介
@anchor{howto/ipaddress networks-as-lists-of-addresses}@anchor{5815}
@subsection アドレスのリストとしてのネットワーク


ネットワークをリストとして扱うと便利な場合があります。これは、ネットワークを次のようにインデックス付けすることが可能なことを意味します:

@example
>>> net4[1]
IPv4Address('192.0.2.1')
>>> net4[-1]
IPv4Address('192.0.2.255')
>>> net6[1]
IPv6Address('2001:db8::1')
>>> net6[-1]
IPv6Address('2001:db8::ffff:ffff')
@end example

以下のようなリストのメンバーシップの判定用文法が使用可能なように、ネットワークオブジェクト自身が適応します:

@example
if address in network:
    # do something
@end example

ネットワークプレフィックスに基づき、所属しているかどうかの判定が効果的にできます:

@example
>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> addr4 in ipaddress.ip_network('192.0.2.0/24')
True
>>> addr4 in ipaddress.ip_network('192.0.3.0/24')
False
@end example

@node 比較<4>,他のモジュールでIPアドレスを使用する,アドレスのリストとしてのネットワーク,ipaddressモジュールの紹介
@anchor{howto/ipaddress comparisons}@anchor{5816}
@subsection 比較


@ref{84,,ipaddress} はオブジェクトの比較をするための単純で、かつ願わくば直観的な方法を意味が通じるように提供します:

@example
>>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')
True
@end example

異なるバージョンや異なるタイプのオブジェクトを比較しようとすると @ref{198,,TypeError} 例外が発生します。

@node 他のモジュールでIPアドレスを使用する,インスタンスの生成に失敗した場合にさらに詳細を取得する,比較<4>,ipaddressモジュールの紹介
@anchor{howto/ipaddress using-ip-addresses-with-other-modules}@anchor{5817}
@subsection 他のモジュールでIPアドレスを使用する


IPアドレスを使用する他のモジュール(@ref{d1,,socket} など)は通常このモジュールからオブジェクトを直接受け付けません。直接渡すのではなく、他のモジュールが受け付ける整数や文字列に強制的に変換する必要があります:

@example
>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> str(addr4)
'192.0.2.1'
>>> int(addr4)
3221225985
@end example

@node インスタンスの生成に失敗した場合にさらに詳細を取得する,,他のモジュールでIPアドレスを使用する,ipaddressモジュールの紹介
@anchor{howto/ipaddress getting-more-detail-when-instance-creation-fails}@anchor{5818}
@subsection インスタンスの生成に失敗した場合にさらに詳細を取得する


上述したバージョンに関知しないファクトリー関数を使用してアドレス/ネットワーク/インターフェースオブジェクトを作成する場合、渡された値がそのタイプのオブジェクトとして認識されなかったと単純に通知する汎用的なメッセージとともに、どのエラーでも @ref{2ec,,ValueError} として報告されます。特定のエラーが提供されないのは、拒否された理由をより詳細に提供するために、値がIPv4またはIPv6である `はず' かどうかを知る必要があるためです。

追加の詳細を得ると役立つ場合のユースケースに対応するため、個別のクラスのコンストラクタは実際に @ref{2ec,,ValueError} のサブクラスである @ref{41cf,,ipaddress.AddressValueError} と @ref{41f0,,ipaddress.NetmaskValueError} を発生させて具体的に定義のどの部分のパースに失敗したのかを示します。

クラスコンストラクタを直接使用する場合にはこれらのエラーメッセージはさらに非常に詳細になっています。例えば:

@example
>>> ipaddress.ip_address("192.168.0.256")
Traceback (most recent call last):
  ...
ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.IPv4Address("192.168.0.256")
Traceback (most recent call last):
  ...
ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256'

>>> ipaddress.ip_network("192.168.0.1/64")
Traceback (most recent call last):
  ...
ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network
>>> ipaddress.IPv4Network("192.168.0.1/64")
Traceback (most recent call last):
  ...
ipaddress.NetmaskValueError: '64' is not a valid netmask
@end example

しかし、モジュールについて固有の上記例外のどちらも @ref{2ec,,ValueError} を親クラスとして持ち、エラーの特定のタイプに興味がない場合でも、以下のようにコードを記述できます:

@example
try:
    network = ipaddress.IPv4Network(address)
except ValueError:
    print('address/netmask is invalid for IPv4:', address)
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node DTrace と SystemTap で CPython を測定する,Python support for the Linux perf profiler,ipaddressモジュールの紹介,Python HOWTO
@anchor{howto/instrumentation doc}@anchor{5819}@anchor{howto/instrumentation instrumentation}@anchor{e66}@anchor{howto/instrumentation instrumenting-cpython-with-dtrace-and-systemtap}@anchor{581a}@anchor{howto/instrumentation translation-repo}@anchor{581b}
@section DTrace と SystemTap で CPython を測定する


@*author: 
David Malcolm


@*author: 
Łukasz Langa


Dtrace と SystemTap はモニタリングツールで、コンピュータシステムのプロセスが何をしているかを調べる方法を提供します。
どちらもドメイン固有言語 (domain-specific language) を使用して、次のことができるスクリプトをユーザが書けます:


@itemize -

@item 
観測対象のプロセスを絞り込む

@item 
関心のあるプロセスからデータを収集する

@item 
収集したデータからレポートを生成する
@end itemize

Python 3.6 では、 CPython は "プローブ" としても知られる "マーカー" を埋め込んだビルドが行えます。
マーカーは DTrace や SystemTap のスクリプトから観測でき、システムの CPython プロセスが何をしているかを観察するのが簡単になります。

DTrace マーカーは CPython インタプリタの実装詳細です。
CPython のバージョン間でプローブの互換性があるという保証はありません。
CPython のバージョンを変えると、 DTrace スクリプトは警告無しに動作しなくなったり、おかしな動作をする可能性があります。

@menu
* 静的マーカーの有効化:: 
* 静的 DTrace プローブ:: 
* 静的 SystemTap マーカー:: 
* 利用可能な静的マーカー:: 
* SystemTap Tapset:: 
* 使用例: 使用例<58>. 

@end menu

@node 静的マーカーの有効化,静的 DTrace プローブ,,DTrace と SystemTap で CPython を測定する
@anchor{howto/instrumentation enabling-the-static-markers}@anchor{581c}
@subsection 静的マーカーの有効化


macOS には組み込みの DTrace サポートが備わっています。
Linux では SystemTap 用のマーカーを埋め込んで CPython をビルドするためには、 SystemTap 開発ツールをインストールしなければなりません。

Linux マシンでは、 SystemTap 開発ツールのインストールは次のように行えます:

@example
$ yum install systemtap-sdt-devel
@end example

もしくは:

@example
$ sudo apt-get install systemtap-sdt-dev
@end example

CPython must then be @ref{21a9,,configured with the --with-dtrace option}:

@example
checking for --with-dtrace... yes
@end example

On macOS, you can list available DTrace probes by running a Python
process in the background and listing all probes made available by the
Python provider:

@example
$ python3.6 -q &
$ sudo dtrace -l -P python$!  # or: dtrace -l -m python3.6

   ID   PROVIDER            MODULE                          FUNCTION NAME
29564 python18035        python3.6          _PyEval_EvalFrameDefault function-entry
29565 python18035        python3.6             dtrace_function_entry function-entry
29566 python18035        python3.6          _PyEval_EvalFrameDefault function-return
29567 python18035        python3.6            dtrace_function_return function-return
29568 python18035        python3.6                           collect gc-done
29569 python18035        python3.6                           collect gc-start
29570 python18035        python3.6          _PyEval_EvalFrameDefault line
29571 python18035        python3.6                 maybe_dtrace_line line
@end example

On Linux, you can verify if the SystemTap static markers are present in
the built binary by seeing if it contains a ".note.stapsdt" section.

@example
$ readelf -S ./python | grep .note.stapsdt
[30] .note.stapsdt        NOTE         0000000000000000 00308d78
@end example

If you've built Python as a shared library
(with the @ref{a63,,--enable-shared} configure option), you
need to look instead within the shared library.  For example:

@example
$ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt
[29] .note.stapsdt        NOTE         0000000000000000 00365b68
@end example

十分に新しい readelf ではメタデータを出力できます:

@example
$ readelf -n ./python

Displaying notes found at file offset 0x00000254 with length 0x00000020:
    Owner                 Data size          Description
    GNU                  0x00000010          NT_GNU_ABI_TAG (ABI version tag)
        OS: Linux, ABI: 2.6.32

Displaying notes found at file offset 0x00000274 with length 0x00000024:
    Owner                 Data size          Description
    GNU                  0x00000014          NT_GNU_BUILD_ID (unique build ID bitstring)
        Build ID: df924a2b08a7e89f6e11251d4602022977af2670

Displaying notes found at file offset 0x002d6c30 with length 0x00000144:
    Owner                 Data size          Description
    stapsdt              0x00000031          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__start
        Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6
        Arguments: -4@@%ebx
    stapsdt              0x00000030          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__done
        Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8
        Arguments: -8@@%rax
    stapsdt              0x00000045          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__entry
        Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8
        Arguments: 8@@%rbp 8@@%r12 -4@@%eax
    stapsdt              0x00000046          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__return
        Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea
        Arguments: 8@@%rbp 8@@%r12 -4@@%eax
@end example

The above metadata contains information for SystemTap describing how it
can patch strategically placed machine code instructions to enable the
tracing hooks used by a SystemTap script.

@node 静的 DTrace プローブ,静的 SystemTap マーカー,静的マーカーの有効化,DTrace と SystemTap で CPython を測定する
@anchor{howto/instrumentation static-dtrace-probes}@anchor{581d}
@subsection 静的 DTrace プローブ


The following example DTrace script can be used to show the call/return
hierarchy of a Python script, only tracing within the invocation of
a function called "start". In other words, import-time function
invocations are not going to be listed:

@example
self int indent;

python$target:::function-entry
/copyinstr(arg1) == "start"/
@{
        self->trace = 1;
@}

python$target:::function-entry
/self->trace/
@{
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
        self->indent++;
@}

python$target:::function-return
/self->trace/
@{
        self->indent--;
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
@}

python$target:::function-return
/copyinstr(arg1) == "start"/
@{
        self->trace = 0;
@}
@end example

この例は次のように実行できます:

@example
$ sudo dtrace -q -s call_stack.d -c "python3.6 script.py"
@end example

出力はこのようになります:

@example
156641360502280  function-entry:call_stack.py:start:23
156641360518804  function-entry: call_stack.py:function_1:1
156641360532797  function-entry:  call_stack.py:function_3:9
156641360546807 function-return:  call_stack.py:function_3:10
156641360563367 function-return: call_stack.py:function_1:2
156641360578365  function-entry: call_stack.py:function_2:5
156641360591757  function-entry:  call_stack.py:function_1:1
156641360605556  function-entry:   call_stack.py:function_3:9
156641360617482 function-return:   call_stack.py:function_3:10
156641360629814 function-return:  call_stack.py:function_1:2
156641360642285 function-return: call_stack.py:function_2:6
156641360656770  function-entry: call_stack.py:function_3:9
156641360669707 function-return: call_stack.py:function_3:10
156641360687853  function-entry: call_stack.py:function_4:13
156641360700719 function-return: call_stack.py:function_4:14
156641360719640  function-entry: call_stack.py:function_5:18
156641360732567 function-return: call_stack.py:function_5:21
156641360747370 function-return:call_stack.py:start:28
@end example

@node 静的 SystemTap マーカー,利用可能な静的マーカー,静的 DTrace プローブ,DTrace と SystemTap で CPython を測定する
@anchor{howto/instrumentation static-systemtap-markers}@anchor{581e}
@subsection 静的 SystemTap マーカー


The low-level way to use the SystemTap integration is to use the static
markers directly.  This requires you to explicitly state the binary file
containing them.

例えば、この SystemTap スクリプトは Python の呼び出し/返却 (call/return) 階層を表示するのに使えます:

@example
probe process("python").mark("function__entry") @{
     filename = user_string($arg1);
     funcname = user_string($arg2);
     lineno = $arg3;

     printf("%s => %s in %s:%d\\n",
            thread_indent(1), funcname, filename, lineno);
@}

probe process("python").mark("function__return") @{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;

    printf("%s <= %s in %s:%d\\n",
           thread_indent(-1), funcname, filename, lineno);
@}
@end example

この例は次のように実行できます:

@example
$ stap \
  show-call-hierarchy.stp \
  -c "./python test.py"
@end example

出力はこのようになります:

@example
11408 python(8274):        => __contains__ in Lib/_abcoll.py:362
11414 python(8274):         => __getitem__ in Lib/os.py:425
11418 python(8274):          => encode in Lib/os.py:490
11424 python(8274):          <= encode in Lib/os.py:493
11428 python(8274):         <= __getitem__ in Lib/os.py:426
11433 python(8274):        <= __contains__ in Lib/_abcoll.py:366
@end example

それぞれの列の内容は次の通りです:


@itemize -

@item 
スクリプトを起動してからのマイクロ秒単位の時間

@item 
実行可能ファイルの名前

@item 
プロセスの PID
@end itemize

そして、残りの部分はスクリプトが実行していた呼び出し/返却階層を表示しています。

For a @ref{a63,,--enable-shared} build of CPython, the markers are contained within the
libpython shared library, and the probe's dotted path needs to reflect this. For
example, this line from the above example:

@example
probe process("python").mark("function__entry") @{
@end example

should instead read:

@example
probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") @{
@end example

(assuming a @ref{509,,debug build} of CPython 3.6)

@node 利用可能な静的マーカー,SystemTap Tapset,静的 SystemTap マーカー,DTrace と SystemTap で CPython を測定する
@anchor{howto/instrumentation available-static-markers}@anchor{581f}@anchor{howto/instrumentation static-markers}@anchor{db1}
@subsection 利用可能な静的マーカー



@deffn {Object} function__entry(str filename, str funcname, int lineno)

このマーカーは Python の関数の実行が開始されたことを示しています。
このマーカーは、ピュア Python (バイトコード) の関数でしか起動されません。

トレーススクリプトには位置引数として、ファイル名、関数名、行番号が渡され、必ず @code{$arg1}, @code{$arg2}, @code{$arg3} で渡されます:

@quotation


@itemize *

@item 
@code{$arg1} : @code{(const char *)} ファイル名、 @code{user_string($arg1)} でアクセスできます

@item 
@code{$arg2} : @code{(const char *)} 関数名、 @code{user_string($arg2)} でアクセスできます

@item 
@code{$arg3} : @code{int} 行番号
@end itemize
@end quotation
@end deffn


@deffn {Object} function__return(str filename, str funcname, int lineno)

This marker is the converse of @code{function__entry()}, and indicates that
execution of a Python function has ended (either via @code{return}, or via an
exception).  It is only triggered for pure-Python (bytecode) functions.

The arguments are the same as for @code{function__entry()}
@end deffn


@deffn {Object} line(str filename, str funcname, int lineno)

このマーカーは、これから実行される Python の行を示しています。
これは Python プロファイラによる行ごとのトレースと同等です。
このマーカーは C 関数の内部では起動されません。

The arguments are the same as for @code{function__entry()}.
@end deffn


@deffn {Object} gc__start(int generation)

Fires when the Python interpreter starts a garbage collection cycle.
@code{arg0} is the generation to scan, like @ref{1b3,,gc.collect()}.
@end deffn


@deffn {Object} gc__done(long collected)

Python インタプリタによる循環参照のガベージコレクションが完了したときに発火します。
@code{arg0} は回収したオブジェクトの数です。
@end deffn


@deffn {Object} import__find__load__start(str modulename)

Fires before @ref{7b,,importlib} attempts to find and load the module.
@code{arg0} is the module name.


Added in version 3.7.

@end deffn


@deffn {Object} import__find__load__done(str modulename, int found)

Fires after @ref{7b,,importlib}'s find_and_load function is called.
@code{arg0} is the module name, @code{arg1} indicates if module was
successfully loaded.


Added in version 3.7.

@end deffn


@deffn {Object} audit(str event, void *tuple)

Fires when @ref{191b,,sys.audit()} or @ref{613,,PySys_Audit()} is called.
@code{arg0} is the event name as C string, @code{arg1} is a @ref{5df,,PyObject}
pointer to a tuple object.


Added in version 3.8.

@end deffn

@node SystemTap Tapset,使用例<58>,利用可能な静的マーカー,DTrace と SystemTap で CPython を測定する
@anchor{howto/instrumentation systemtap-tapsets}@anchor{5820}
@subsection SystemTap Tapset


The higher-level way to use the SystemTap integration is to use a "tapset":
SystemTap's equivalent of a library, which hides some of the lower-level
details of the static markers.

Here is a tapset file, based on a non-shared build of CPython:

@example
/*
   Provide a higher-level wrapping around the function__entry and
   function__return markers:
 \*/
probe python.function.entry = process("python").mark("function__entry")
@{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
@}
probe python.function.return = process("python").mark("function__return")
@{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
@}
@end example

If this file is installed in SystemTap's tapset directory (e.g.
@code{/usr/share/systemtap/tapset}), then these additional probepoints become
available:


@deffn {Object} python.function.entry(str filename, str funcname, int lineno, frameptr)

This probe point indicates that execution of a Python function has begun.
It is only triggered for pure-Python (bytecode) functions.
@end deffn


@deffn {Object} python.function.return(str filename, str funcname, int lineno, frameptr)

This probe point is the converse of @code{python.function.return}, and
indicates that execution of a Python function has ended (either via
@code{return}, or via an exception).  It is only triggered for pure-Python
(bytecode) functions.
@end deffn

@node 使用例<58>,,SystemTap Tapset,DTrace と SystemTap で CPython を測定する
@anchor{howto/instrumentation examples}@anchor{5821}
@subsection 使用例


This SystemTap script uses the tapset above to more cleanly implement the
example given above of tracing the Python function-call hierarchy, without
needing to directly name the static markers:

@example
probe python.function.entry
@{
  printf("%s => %s in %s:%d\n",
         thread_indent(1), funcname, filename, lineno);
@}

probe python.function.return
@{
  printf("%s <= %s in %s:%d\n",
         thread_indent(-1), funcname, filename, lineno);
@}
@end example

The following script uses the tapset above to provide a top-like view of all
running CPython code, showing the top 20 most frequently entered bytecode
frames, each second, across the whole system:

@example
global fn_calls;

probe python.function.entry
@{
    fn_calls[pid(), filename, funcname, lineno] += 1;
@}

probe timer.ms(1000) @{
    printf("\033[2J\033[1;1H") /* clear screen \*/
    printf("%6s %80s %6s %30s %6s\n",
           "PID", "FILENAME", "LINE", "FUNCTION", "CALLS")
    foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) @{
        printf("%6d %80s %6d %30s %6d\n",
            pid, filename, lineno, funcname,
            fn_calls[pid, filename, funcname, lineno]);
    @}
    delete fn_calls;
@}
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python support for the Linux perf profiler,Annotations Best Practices,DTrace と SystemTap で CPython を測定する,Python HOWTO
@anchor{howto/perf_profiling doc}@anchor{1aac}@anchor{howto/perf_profiling perf-profiling}@anchor{4ae}@anchor{howto/perf_profiling python-support-for-the-linux-perf-profiler}@anchor{5822}@anchor{howto/perf_profiling translation-repo}@anchor{5823}
@section Python support for the Linux @code{perf} profiler


@*author: 
Pablo Galindo


The Linux perf profiler@footnote{https://perf.wiki.kernel.org}
is a very powerful tool that allows you to profile and obtain
information about the performance of your application.
@code{perf} also has a very vibrant ecosystem of tools
that aid with the analysis of the data that it produces.

The main problem with using the @code{perf} profiler with Python applications is that
@code{perf} only gets information about native symbols, that is, the names of
functions and procedures written in C. This means that the names and file names
of Python functions in your code will not appear in the output of @code{perf}.

Since Python 3.12, the interpreter can run in a special mode that allows Python
functions to appear in the output of the @code{perf} profiler. When this mode is
enabled, the interpreter will interpose a small piece of code compiled on the
fly before the execution of every Python function and it will teach @code{perf} the
relationship between this piece of code and the associated Python function using
@ref{5272,,perf map files}.

@cartouche
@quotation 注釈 
Support for the @code{perf} profiler is currently only available for Linux on
select architectures. Check the output of the @code{configure} build step or
check the output of @code{python -m sysconfig | grep HAVE_PERF_TRAMPOLINE}
to see if your system is supported.
@end quotation
@end cartouche

For example, consider the following script:

@example
def foo(n):
    result = 0
    for _ in range(n):
        result += 1
    return result

def bar(n):
    foo(n)

def baz(n):
    bar(n)

if __name__ == "__main__":
    baz(1000000)
@end example

We can run @code{perf} to sample CPU stack traces at 9999 hertz:

@example
$ perf record -F 9999 -g -o perf.data python my_script.py
@end example

Then we can use @code{perf report} to analyze the data:

@example
$ perf report --stdio -n -g

# Children      Self       Samples  Command     Shared Object       Symbol
# ........  ........  ............  ..........  ..................  ..........................................
#
    91.08%     0.00%             0  python.exe  python.exe          [.] _start
            |
            ---_start
            |
                --90.71%--__libc_start_main
                        Py_BytesMain
                        |
                        |--56.88%--pymain_run_python.constprop.0
                        |          |
                        |          |--56.13%--_PyRun_AnyFileObject
                        |          |          _PyRun_SimpleFileObject
                        |          |          |
                        |          |          |--55.02%--run_mod
                        |          |          |          |
                        |          |          |           --54.65%--PyEval_EvalCode
                        |          |          |                     _PyEval_EvalFrameDefault
                        |          |          |                     PyObject_Vectorcall
                        |          |          |                     _PyEval_Vector
                        |          |          |                     _PyEval_EvalFrameDefault
                        |          |          |                     PyObject_Vectorcall
                        |          |          |                     _PyEval_Vector
                        |          |          |                     _PyEval_EvalFrameDefault
                        |          |          |                     PyObject_Vectorcall
                        |          |          |                     _PyEval_Vector
                        |          |          |                     |
                        |          |          |                     |--51.67%--_PyEval_EvalFrameDefault
                        |          |          |                     |          |
                        |          |          |                     |          |--11.52%--_PyLong_Add
                        |          |          |                     |          |          |
                        |          |          |                     |          |          |--2.97%--_PyObject_Malloc
...
@end example

As you can see, the Python functions are not shown in the output, only @code{_PyEval_EvalFrameDefault}
(the function that evaluates the Python bytecode) shows up. Unfortunately that's not very useful because all Python
functions use the same C function to evaluate bytecode so we cannot know which Python function corresponds to which
bytecode-evaluating function.

Instead, if we run the same experiment with @code{perf} support enabled we get:

@example
$ perf report --stdio -n -g

# Children      Self       Samples  Command     Shared Object       Symbol
# ........  ........  ............  ..........  ..................  .....................................................................
#
    90.58%     0.36%             1  python.exe  python.exe          [.] _start
            |
            ---_start
            |
                --89.86%--__libc_start_main
                        Py_BytesMain
                        |
                        |--55.43%--pymain_run_python.constprop.0
                        |          |
                        |          |--54.71%--_PyRun_AnyFileObject
                        |          |          _PyRun_SimpleFileObject
                        |          |          |
                        |          |          |--53.62%--run_mod
                        |          |          |          |
                        |          |          |           --53.26%--PyEval_EvalCode
                        |          |          |                     py::<module>:/src/script.py
                        |          |          |                     _PyEval_EvalFrameDefault
                        |          |          |                     PyObject_Vectorcall
                        |          |          |                     _PyEval_Vector
                        |          |          |                     py::baz:/src/script.py
                        |          |          |                     _PyEval_EvalFrameDefault
                        |          |          |                     PyObject_Vectorcall
                        |          |          |                     _PyEval_Vector
                        |          |          |                     py::bar:/src/script.py
                        |          |          |                     _PyEval_EvalFrameDefault
                        |          |          |                     PyObject_Vectorcall
                        |          |          |                     _PyEval_Vector
                        |          |          |                     py::foo:/src/script.py
                        |          |          |                     |
                        |          |          |                     |--51.81%--_PyEval_EvalFrameDefault
                        |          |          |                     |          |
                        |          |          |                     |          |--13.77%--_PyLong_Add
                        |          |          |                     |          |          |
                        |          |          |                     |          |          |--3.26%--_PyObject_Malloc
@end example

@menu
* How to enable perf profiling support:: 
* How to obtain the best results:: 
* How to work without frame pointers:: 

@end menu

@node How to enable perf profiling support,How to obtain the best results,,Python support for the Linux perf profiler
@anchor{howto/perf_profiling how-to-enable-perf-profiling-support}@anchor{5824}
@subsection How to enable @code{perf} profiling support


@code{perf} profiling support can be enabled either from the start using
the environment variable 
@geindex PYTHONPERFSUPPORT
@geindex 環境変数; PYTHONPERFSUPPORT
@ref{699,,PYTHONPERFSUPPORT} or the
@ref{16f,,-X perf} option,
or dynamically using @ref{69a,,sys.activate_stack_trampoline()} and
@ref{69b,,sys.deactivate_stack_trampoline()}.

The @code{sys} functions take precedence over the @code{-X} option,
the @code{-X} option takes precedence over the environment variable.

Example, using the environment variable:

@example
$ PYTHONPERFSUPPORT=1 perf record -F 9999 -g -o perf.data python my_script.py
$ perf report -g -i perf.data
@end example

Example, using the @code{-X} option:

@example
$ perf record -F 9999 -g -o perf.data python -X perf my_script.py
$ perf report -g -i perf.data
@end example

Example, using the @ref{df,,sys} APIs in file @code{example.py}:

@example
import sys

sys.activate_stack_trampoline("perf")
do_profiled_stuff()
sys.deactivate_stack_trampoline()

non_profiled_stuff()
@end example

...then:

@example
$ perf record -F 9999 -g -o perf.data python ./example.py
$ perf report -g -i perf.data
@end example

@node How to obtain the best results,How to work without frame pointers,How to enable perf profiling support,Python support for the Linux perf profiler
@anchor{howto/perf_profiling how-to-obtain-the-best-results}@anchor{5825}
@subsection How to obtain the best results


For best results, Python should be compiled with
@code{CFLAGS="-fno-omit-frame-pointer -mno-omit-leaf-frame-pointer"} as this allows
profilers to unwind using only the frame pointer and not on DWARF debug
information. This is because as the code that is interposed to allow @code{perf}
support is dynamically generated it doesn't have any DWARF debugging information
available.

You can check if your system has been compiled with this flag by running:

@example
$ python -m sysconfig | grep 'no-omit-frame-pointer'
@end example

If you don't see any output it means that your interpreter has not been compiled with
frame pointers and therefore it may not be able to show Python functions in the output
of @code{perf}.

@node How to work without frame pointers,,How to obtain the best results,Python support for the Linux perf profiler
@anchor{howto/perf_profiling how-to-work-without-frame-pointers}@anchor{5826}
@subsection How to work without frame pointers


If you are working with a Python interpreter that has been compiled without
frame pointers, you can still use the @code{perf} profiler, but the overhead will be
a bit higher because Python needs to generate unwinding information for every
Python function call on the fly. Additionally, @code{perf} will take more time to
process the data because it will need to use the DWARF debugging information to
unwind the stack and this is a slow process.

To enable this mode, you can use the environment variable
@geindex PYTHON_PERF_JIT_SUPPORT
@geindex 環境変数; PYTHON_PERF_JIT_SUPPORT
@ref{4af,,PYTHON_PERF_JIT_SUPPORT} or the @ref{16f,,-X perf_jit} option,
which will enable the JIT mode for the @code{perf} profiler.

@cartouche
@quotation 注釈 
Due to a bug in the @code{perf} tool, only @code{perf} versions higher than v6.8
will work with the JIT mode.  The fix was also backported to the v6.7.2
version of the tool.

Note that when checking the version of the @code{perf} tool (which can be done
by running @code{perf version}) you must take into account that some distros
add some custom version numbers including a @code{-} character.  This means
that @code{perf 6.7-3} is not necessarily @code{perf 6.7.3}.
@end quotation
@end cartouche

When using the perf JIT mode, you need an extra step before you can run @code{perf
report}. You need to call the @code{perf inject} command to inject the JIT
information into the @code{perf.data} file.:

@example
$ perf record -F 9999 -g -k 1 --call-graph dwarf -o perf.data python -Xperf_jit my_script.py
$ perf inject -i perf.data --jit --output perf.jit.data
$ perf report -g -i perf.jit.data
@end example

or using the environment variable:

@example
$ PYTHON_PERF_JIT_SUPPORT=1 perf record -F 9999 -g --call-graph dwarf -o perf.data python my_script.py
$ perf inject -i perf.data --jit --output perf.jit.data
$ perf report -g -i perf.jit.data
@end example

@code{perf inject --jit} command will read @code{perf.data},
automatically pick up the perf dump file that Python creates (in
@code{/tmp/perf-$PID.dump}), and then create @code{perf.jit.data} which merges all the
JIT information together. It should also create a lot of @code{jitted-XXXX-N.so}
files in the current directory which are ELF images for all the JIT trampolines
that were created by Python.

@cartouche
@quotation 警告 
When using @code{--call-graph dwarf}, the @code{perf} tool will take
snapshots of the stack of the process being profiled and save the
information in the @code{perf.data} file. By default, the size of the stack dump
is 8192 bytes, but you can change the size by passing it after
a comma like @code{--call-graph dwarf,16384}.

The size of the stack dump is important because if the size is too small
@code{perf} will not be able to unwind the stack and the output will be
incomplete. On the other hand, if the size is too big, then @code{perf} won't
be able to sample the process as frequently as it would like as the overhead
will be higher.

The stack size is particularly important when profiling Python code compiled
with low optimization levels (like @code{-O0}), as these builds tend to have
larger stack frames. If you are compiling Python with @code{-O0} and not seeing
Python functions in your profiling output, try increasing the stack dump
size to 65528 bytes (the maximum):

@example
$ perf record -F 9999 -g -k 1 --call-graph dwarf,65528 -o perf.data python -Xperf_jit my_script.py
@end example

Different compilation flags can significantly impact stack sizes:


@itemize -

@item 
Builds with @code{-O0} typically have much larger stack frames than those with @code{-O1} or higher

@item 
Adding optimizations (@code{-O1}, @code{-O2}, etc.) typically reduces stack size

@item 
Frame pointers (@code{-fno-omit-frame-pointer}) generally provide more reliable stack unwinding
@end itemize
@end quotation
@end cartouche

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Annotations Best Practices,拡張モジュールを分離する,Python support for the Linux perf profiler,Python HOWTO
@anchor{howto/annotations doc}@anchor{5827}@anchor{howto/annotations annotations-best-practices}@anchor{5828}@anchor{howto/annotations annotations-howto}@anchor{9d9}@anchor{howto/annotations translation-repo}@anchor{5829}
@section Annotations Best Practices


@*author: 
Larry Hastings


@subsubheading 概要



This document is designed to encapsulate the best practices
for working with annotations dicts.  If you write Python code
that examines @code{__annotations__} on Python objects, we
encourage you to follow the guidelines described below.

The document is organized into four sections:
best practices for accessing the annotations of an object
in Python versions 3.10 and newer,
best practices for accessing the annotations of an object
in Python versions 3.9 and older,
other best practices
for @code{__annotations__} that apply to any Python version,
and
quirks of @code{__annotations__}.

Note that this document is specifically about working with
@code{__annotations__}, not uses `for' annotations.
If you're looking for information on how to use "type hints"
in your code, please see the @ref{10a,,typing} module.

@menu
* Accessing The Annotations Dict Of An Object In Python 3.10 And Newer: Accessing The Annotations Dict Of An Object In Python 3 10 And Newer. 
* Accessing The Annotations Dict Of An Object In Python 3.9 And Older: Accessing The Annotations Dict Of An Object In Python 3 9 And Older. 
* Manually Un-Stringizing Stringized Annotations:: 
* Best Practices For __annotations__ In Any Python Version:: 
* __annotations__ Quirks:: 

@end menu

@node Accessing The Annotations Dict Of An Object In Python 3 10 And Newer,Accessing The Annotations Dict Of An Object In Python 3 9 And Older,,Annotations Best Practices
@anchor{howto/annotations accessing-the-annotations-dict-of-an-object-in-python-3-10-and-newer}@anchor{582a}
@subsection Accessing The Annotations Dict Of An Object In Python 3.10 And Newer


Python 3.10 adds a new function to the standard library:
@ref{a14,,inspect.get_annotations()}.  In Python versions 3.10
through 3.13, calling this function is the best practice for
accessing the annotations dict of any object that supports
annotations.  This function can also "un-stringize"
stringized annotations for you.

In Python 3.14, there is a new @ref{6,,annotationlib} module
with functionality for working with annotations. This
includes a @ref{459,,annotationlib.get_annotations()} function,
which supersedes @ref{a14,,inspect.get_annotations()}.

If for some reason @ref{a14,,inspect.get_annotations()} isn't
viable for your use case, you may access the
@code{__annotations__} data member manually.  Best practice
for this changed in Python 3.10 as well: as of Python 3.10,
@code{o.__annotations__} is guaranteed to `always' work
on Python functions, classes, and modules.  If you're
certain the object you're examining is one of these three
`specific' objects, you may simply use @code{o.__annotations__}
to get at the object's annotations dict.

However, other types of callables--for example,
callables created by @ref{217,,functools.partial()}--may
not have an @code{__annotations__} attribute defined.  When
accessing the @code{__annotations__} of a possibly unknown
object,  best practice in Python versions 3.10 and
newer is to call @ref{dca,,getattr()} with three arguments,
for example @code{getattr(o, '__annotations__', None)}.

Before Python 3.10, accessing @code{__annotations__} on a class that
defines no annotations but that has a parent class with
annotations would return the parent's @code{__annotations__}.
In Python 3.10 and newer, the child class's annotations
will be an empty dict instead.

@node Accessing The Annotations Dict Of An Object In Python 3 9 And Older,Manually Un-Stringizing Stringized Annotations,Accessing The Annotations Dict Of An Object In Python 3 10 And Newer,Annotations Best Practices
@anchor{howto/annotations accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older}@anchor{582b}
@subsection Accessing The Annotations Dict Of An Object In Python 3.9 And Older


In Python 3.9 and older, accessing the annotations dict
of an object is much more complicated than in newer versions.
The problem is a design flaw in these older versions of Python,
specifically to do with class annotations.

Best practice for accessing the annotations dict of other
objects--functions, other callables, and modules--is the same
as best practice for 3.10, assuming you aren't calling
@ref{a14,,inspect.get_annotations()}: you should use three-argument
@ref{dca,,getattr()} to access the object's @code{__annotations__}
attribute.

Unfortunately, this isn't best practice for classes.  The problem
is that, since @code{__annotations__} is optional on classes, and
because classes can inherit attributes from their base classes,
accessing the @code{__annotations__} attribute of a class may
inadvertently return the annotations dict of a `base class.'
As an example:

@example
class Base:
    a: int = 3
    b: str = 'abc'

class Derived(Base):
    pass

print(Derived.__annotations__)
@end example

This will print the annotations dict from @code{Base}, not
@code{Derived}.

Your code will have to have a separate code path if the object
you're examining is a class (@code{isinstance(o, type)}).
In that case, best practice relies on an implementation detail
of Python 3.9 and before: if a class has annotations defined,
they are stored in the class's @ref{e57,,__dict__} dictionary.  Since
the class may or may not have annotations defined, best practice
is to call the @ref{2034,,get()} method on the class dict.

To put it all together, here is some sample code that safely
accesses the @code{__annotations__} attribute on an arbitrary
object in Python 3.9 and before:

@example
if isinstance(o, type):
    ann = o.__dict__.get('__annotations__', None)
else:
    ann = getattr(o, '__annotations__', None)
@end example

After running this code, @code{ann} should be either a
dictionary or @code{None}.  You're encouraged to double-check
the type of @code{ann} using @ref{2ad,,isinstance()} before further
examination.

Note that some exotic or malformed type objects may not have
a @ref{e57,,__dict__} attribute, so for extra safety you may also wish
to use @ref{dca,,getattr()} to access @code{__dict__}.

@node Manually Un-Stringizing Stringized Annotations,Best Practices For __annotations__ In Any Python Version,Accessing The Annotations Dict Of An Object In Python 3 9 And Older,Annotations Best Practices
@anchor{howto/annotations manually-un-stringizing-stringized-annotations}@anchor{582c}
@subsection Manually Un-Stringizing Stringized Annotations


In situations where some annotations may be "stringized",
and you wish to evaluate those strings to produce the
Python values they represent, it really is best to
call @ref{a14,,inspect.get_annotations()} to do this work
for you.

If you're using Python 3.9 or older, or if for some reason
you can't use @ref{a14,,inspect.get_annotations()}, you'll need
to duplicate its logic.  You're encouraged to examine the
implementation of @ref{a14,,inspect.get_annotations()} in the
current Python version and follow a similar approach.

In a nutshell, if you wish to evaluate a stringized annotation
on an arbitrary object @code{o}:


@itemize *

@item 
If @code{o} is a module, use @code{o.__dict__} as the
@code{globals} when calling @ref{4a3,,eval()}.

@item 
If @code{o} is a class, use @code{sys.modules[o.__module__].__dict__}
as the @code{globals}, and @code{dict(vars(o))} as the @code{locals},
when calling @ref{4a3,,eval()}.

@item 
If @code{o} is a wrapped callable using @ref{1223,,functools.update_wrapper()},
@ref{115f,,functools.wraps()}, or @ref{217,,functools.partial()}, iteratively
unwrap it by accessing either @code{o.__wrapped__} or @code{o.func} as
appropriate, until you have found the root unwrapped function.

@item 
If @code{o} is a callable (but not a class), use
@ref{14eb,,o.__globals__} as the globals when calling
@ref{4a3,,eval()}.
@end itemize

However, not all string values used as annotations can
be successfully turned into Python values by @ref{4a3,,eval()}.
String values could theoretically contain any valid string,
and in practice there are valid use cases for type hints that
require annotating with string values that specifically
`can't' be evaluated.  For example:


@itemize *

@item 
@geindex Python Enhancement Proposals; PEP 604
PEP 604@footnote{https://peps.python.org/pep-0604/} union types using @code{|}, before support for this
was added to Python 3.10.

@item 
Definitions that aren't needed at runtime, only imported
when @ref{ef0,,typing.TYPE_CHECKING} is true.
@end itemize

If @ref{4a3,,eval()} attempts to evaluate such values, it will
fail and raise an exception.  So, when designing a library
API that works with annotations, it's recommended to only
attempt to evaluate string values when explicitly requested
to by the caller.

@node Best Practices For __annotations__ In Any Python Version,__annotations__ Quirks,Manually Un-Stringizing Stringized Annotations,Annotations Best Practices
@anchor{howto/annotations best-practices-for-annotations-in-any-python-version}@anchor{582d}
@subsection Best Practices For @code{__annotations__} In Any Python Version



@itemize *

@item 
You should avoid assigning to the @code{__annotations__} member
of objects directly.  Let Python manage setting @code{__annotations__}.

@item 
If you do assign directly to the @code{__annotations__} member
of an object, you should always set it to a @code{dict} object.

@item 
You should avoid accessing @code{__annotations__} directly on any object.
Instead, use @ref{459,,annotationlib.get_annotations()} (Python 3.14+)
or @ref{a14,,inspect.get_annotations()} (Python 3.10+).

@item 
If you do directly access the @code{__annotations__} member
of an object, you should ensure that it's a
dictionary before attempting to examine its contents.

@item 
You should avoid modifying @code{__annotations__} dicts.

@item 
You should avoid deleting the @code{__annotations__} attribute
of an object.
@end itemize

@node __annotations__ Quirks,,Best Practices For __annotations__ In Any Python Version,Annotations Best Practices
@anchor{howto/annotations annotations-quirks}@anchor{582e}
@subsection @code{__annotations__} Quirks


In all versions of Python 3, function
objects lazy-create an annotations dict if no annotations
are defined on that object.  You can delete the @code{__annotations__}
attribute using @code{del fn.__annotations__}, but if you then
access @code{fn.__annotations__} the object will create a new empty dict
that it will store and return as its annotations.  Deleting the
annotations on a function before it has lazily created its annotations
dict will throw an @code{AttributeError}; using @code{del fn.__annotations__}
twice in a row is guaranteed to always throw an @code{AttributeError}.

Everything in the above paragraph also applies to class and module
objects in Python 3.10 and newer.

In all versions of Python 3, you can set @code{__annotations__}
on a function object to @code{None}.  However, subsequently
accessing the annotations on that object using @code{fn.__annotations__}
will lazy-create an empty dictionary as per the first paragraph of
this section.  This is `not' true of modules and classes, in any Python
version; those objects permit setting @code{__annotations__} to any
Python value, and will retain whatever value is set.

If Python stringizes your annotations for you
(using @code{from __future__ import annotations}), and you
specify a string as an annotation, the string will
itself be quoted.  In effect the annotation is quoted
`twice.'  For example:

@example
from __future__ import annotations
def foo(a: "str"): pass

print(foo.__annotations__)
@end example

This prints @code{@{'a': "'str'"@}}.  This shouldn't really be considered
a "quirk"; it's mentioned here simply because it might be surprising.

If you use a class with a custom metaclass and access @code{__annotations__}
on the class, you may observe unexpected behavior; see
@geindex Python Enhancement Proposals; PEP 749#pep749-metaclasses
749@footnote{https://peps.python.org/pep-0749/#pep749-metaclasses} for some examples. You can avoid these
quirks by using @ref{459,,annotationlib.get_annotations()} on Python 3.14+ or
@ref{a14,,inspect.get_annotations()} on Python 3.10+. On earlier versions of
Python, you can avoid these bugs by accessing the annotations from the
class's @ref{e57,,__dict__}
(for example, @code{cls.__dict__.get('__annotations__', None)}).

In some versions of Python, instances of classes may have an @code{__annotations__}
attribute. However, this is not supported functionality. If you need the
annotations of an instance, you can use @ref{f44,,type()} to access its class
(for example, @code{annotationlib.get_annotations(type(myinstance))} on Python 3.14+).

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 拡張モジュールを分離する,timer file descriptor HOWTO,Annotations Best Practices,Python HOWTO
@anchor{howto/isolating-extensions doc}@anchor{582f}@anchor{howto/isolating-extensions isolating-extension-modules}@anchor{5830}@anchor{howto/isolating-extensions isolating-extensions-howto}@anchor{166}@anchor{howto/isolating-extensions translation-repo}@anchor{5831}
@section 拡張モジュールを分離する


@subsubheading 概要



Traditionally, state belonging to Python extension modules was kept in C
@code{static} variables, which have process-wide scope. This document
describes problems of such per-process state and shows a safer way:
per-module state.

The document also describes how to switch to per-module state where
possible. This transition involves allocating space for that state, potentially
switching from static types to heap types, and—perhaps most
importantly—accessing per-module state from code.

@menu
* Who should read this:: 
* 背景: 背景<2>. 
* Making Modules Safe with Multiple Interpreters:: 
* Heap Types: Heap Types<2>. 
* 取り掛かり中の問題:: 

@end menu

@node Who should read this,背景<2>,,拡張モジュールを分離する
@anchor{howto/isolating-extensions who-should-read-this}@anchor{5832}
@subsection Who should read this


This guide is written for maintainers of @ref{1fbe,,C-API} extensions
who would like to make that extension safer to use in applications where
Python itself is used as a library.

@node 背景<2>,Making Modules Safe with Multiple Interpreters,Who should read this,拡張モジュールを分離する
@anchor{howto/isolating-extensions background}@anchor{5833}
@subsection 背景


An `interpreter' is the context in which Python code runs. It contains
configuration (e.g. the import path) and runtime state (e.g. the set of
imported modules).

Python supports running multiple interpreters in one process. There are
two cases to think about—users may run interpreters:


@itemize -

@item 
in sequence, with several @ref{5133,,Py_InitializeEx()}/@ref{f11,,Py_FinalizeEx()}
cycles, and

@item 
in parallel, managing "sub-interpreters" using
@ref{1b31,,Py_NewInterpreter()}/@ref{1845,,Py_EndInterpreter()}.
@end itemize

Both cases (and combinations of them) would be most useful when
embedding Python within a library. Libraries generally shouldn't make
assumptions about the application that uses them, which include
assuming a process-wide "main Python interpreter".

Historically, Python extension modules don't handle this use case well.
Many extension modules (and even some stdlib modules) use `per-process'
global state, because C @code{static} variables are extremely easy to use.
Thus, data that should be specific to an interpreter ends up being shared
between interpreters. Unless the extension developer is careful, it is very
easy to introduce edge cases that lead to crashes when a module is loaded in
more than one interpreter in the same process.

Unfortunately, `per-interpreter' state is not easy to achieve. Extension
authors tend to not keep multiple interpreters in mind when developing,
and it is currently cumbersome to test the behavior.

@menu
* Enter Per-Module State:: 
* Isolated Module Objects:: 
* Surprising Edge Cases:: 

@end menu

@node Enter Per-Module State,Isolated Module Objects,,背景<2>
@anchor{howto/isolating-extensions enter-per-module-state}@anchor{5834}
@subsubsection Enter Per-Module State


Instead of focusing on per-interpreter state, Python's C API is evolving
to better support the more granular `per-module' state.
This means that C-level data should be attached to a `module object'.
Each interpreter creates its own module object, keeping the data separate.
For testing the isolation, multiple module objects corresponding to a single
extension can even be loaded in a single interpreter.

Per-module state provides an easy way to think about lifetime and
resource ownership: the extension module will initialize when a
module object is created, and clean up when it's freed. In this regard,
a module is just like any other @ref{5df,,PyObject}*; there are no "on
interpreter shutdown" hooks to think—or forget—about.

Note that there are use cases for different kinds of "globals":
per-process, per-interpreter, per-thread or per-task state.
With per-module state as the default, these are still possible,
but you should treat them as exceptional cases:
if you need them, you should give them additional care and testing.
(Note that this guide does not cover them.)

@node Isolated Module Objects,Surprising Edge Cases,Enter Per-Module State,背景<2>
@anchor{howto/isolating-extensions isolated-module-objects}@anchor{5835}
@subsubsection Isolated Module Objects


The key point to keep in mind when developing an extension module is
that several module objects can be created from a single shared library.
For example:

@example
>>> import sys
>>> import binascii
>>> old_binascii = binascii
>>> del sys.modules['binascii']
>>> import binascii  # create a new module object
>>> old_binascii == binascii
False
@end example

As a rule of thumb, the two modules should be completely independent.
All objects and state specific to the module should be encapsulated
within the module object, not shared with other module objects, and
cleaned up when the module object is deallocated.
Since this just is a rule of thumb, exceptions are possible
(see @ref{5836,,Managing Global State}), but they will need more
thought and attention to edge cases.

While some modules could do with less stringent restrictions, isolated
modules make it easier to set clear expectations and guidelines that
work across a variety of use cases.

@node Surprising Edge Cases,,Isolated Module Objects,背景<2>
@anchor{howto/isolating-extensions surprising-edge-cases}@anchor{5837}
@subsubsection Surprising Edge Cases


Note that isolated modules do create some surprising edge cases. Most
notably, each module object will typically not share its classes and
exceptions with other similar modules. Continuing from the
@ref{5835,,example above},
note that @code{old_binascii.Error} and @code{binascii.Error} are
separate objects. In the following code, the exception is `not' caught:

@example
>>> old_binascii.Error == binascii.Error
False
>>> try:
...     old_binascii.unhexlify(b'qwertyuiop')
... except binascii.Error:
...     print('boo')
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
binascii.Error: Non-hexadecimal digit found
@end example

This is expected. Notice that pure-Python modules behave the same way:
it is a part of how Python works.

The goal is to make extension modules safe at the C level, not to make
hacks behave intuitively. Mutating @code{sys.modules} "manually" counts
as a hack.

@node Making Modules Safe with Multiple Interpreters,Heap Types<2>,背景<2>,拡張モジュールを分離する
@anchor{howto/isolating-extensions making-modules-safe-with-multiple-interpreters}@anchor{5838}
@subsection Making Modules Safe with Multiple Interpreters


@menu
* Managing Global State:: 
* Managing Per-Module State:: 
* Opt-Out; Limiting to One Module Object per Process: Opt-Out Limiting to One Module Object per Process. 
* Module State Access from Functions:: 

@end menu

@node Managing Global State,Managing Per-Module State,,Making Modules Safe with Multiple Interpreters
@anchor{howto/isolating-extensions managing-global-state}@anchor{5836}
@subsubsection Managing Global State


Sometimes, the state associated with a Python module is not specific to that module, but
to the entire process (or something else "more global" than a module).
For example:


@itemize -

@item 
The @code{readline} module manages `the' terminal.

@item 
A module running on a circuit board wants to control `the' on-board
LED.
@end itemize

In these cases, the Python module should provide `access' to the global
state, rather than `own' it. If possible, write the module so that
multiple copies of it can access the state independently (along with
other libraries, whether for Python or other languages). If that is not
possible, consider explicit locking.

If it is necessary to use process-global state, the simplest way to
avoid issues with multiple interpreters is to explicitly prevent a
module from being loaded more than once per process—see
@ref{5210,,Opt-Out; Limiting to One Module Object per Process}.

@node Managing Per-Module State,Opt-Out Limiting to One Module Object per Process,Managing Global State,Making Modules Safe with Multiple Interpreters
@anchor{howto/isolating-extensions managing-per-module-state}@anchor{5839}
@subsubsection Managing Per-Module State


To use per-module state, use
@ref{5213,,multi-phase extension module initialization}.
This signals that your module supports multiple interpreters correctly.

Set @code{PyModuleDef.m_size} to a positive number to request that many
bytes of storage local to the module. Usually, this will be set to the
size of some module-specific @code{struct}, which can store all of the
module's C-level state. In particular, it is where you should put
pointers to classes (including exceptions, but excluding static types)
and settings (e.g. @code{csv}'s @ref{1b91,,field_size_limit})
which the C code needs to function.

@cartouche
@quotation 注釈 
Another option is to store state in the module's @code{__dict__},
but you must avoid crashing when users modify @code{__dict__} from
Python code. This usually means error- and type-checking at the C level,
which is easy to get wrong and hard to test sufficiently.

However, if module state is not needed in C code, storing it in
@code{__dict__} only is a good idea.
@end quotation
@end cartouche

If the module state includes @code{PyObject} pointers, the module object
must hold references to those objects and implement the module-level hooks
@code{m_traverse}, @code{m_clear} and @code{m_free}. These work like
@code{tp_traverse}, @code{tp_clear} and @code{tp_free} of a class. Adding them will
require some work and make the code longer; this is the price for
modules which can be unloaded cleanly.

An example of a module with per-module state is currently available as
xxlimited@footnote{https://github.com/python/cpython/blob/master/Modules/xxlimited.c};
example module initialization shown at the bottom of the file.

@node Opt-Out Limiting to One Module Object per Process,Module State Access from Functions,Managing Per-Module State,Making Modules Safe with Multiple Interpreters
@anchor{howto/isolating-extensions isolating-extensions-optout}@anchor{5210}@anchor{howto/isolating-extensions opt-out-limiting-to-one-module-object-per-process}@anchor{583a}
@subsubsection Opt-Out: Limiting to One Module Object per Process


A non-negative @code{PyModuleDef.m_size} signals that a module supports
multiple interpreters correctly. If this is not yet the case for your
module, you can explicitly make your module loadable only once per
process. For example:

@example
// A process-wide flag
static int loaded = 0;

// Mutex to provide thread safety (only needed for free-threaded Python)
static PyMutex modinit_mutex = @{0@};

static int
exec_module(PyObject* module)
@{
    PyMutex_Lock(&modinit_mutex);
    if (loaded) @{
        PyMutex_Unlock(&modinit_mutex);
        PyErr_SetString(PyExc_ImportError,
                        "cannot load module more than once per process");
        return -1;
    @}
    loaded = 1;
    PyMutex_Unlock(&modinit_mutex);
    // ... rest of initialization
@}
@end example

If your module's @ref{b72,,PyModuleDef.m_clear} function is able to prepare
for future re-initialization, it should clear the @code{loaded} flag.
In this case, your module won't support multiple instances existing
`concurrently', but it will, for example, support being loaded after
Python runtime shutdown (@ref{f11,,Py_FinalizeEx()}) and re-initialization
(@ref{460,,Py_Initialize()}).

@node Module State Access from Functions,,Opt-Out Limiting to One Module Object per Process,Making Modules Safe with Multiple Interpreters
@anchor{howto/isolating-extensions module-state-access-from-functions}@anchor{583b}
@subsubsection Module State Access from Functions


Accessing the state from module-level functions is straightforward.
Functions get the module object as their first argument; for extracting
the state, you can use @code{PyModule_GetState}:

@example
static PyObject *
func(PyObject *module, PyObject *args)
@{
    my_struct *state = (my_struct*)PyModule_GetState(module);
    if (state == NULL) @{
        return NULL;
    @}
    // ... rest of logic
@}
@end example

@cartouche
@quotation 注釈 
@code{PyModule_GetState} may return @code{NULL} without setting an
exception if there is no module state, i.e. @code{PyModuleDef.m_size} was
zero. In your own module, you're in control of @code{m_size}, so this is
easy to prevent.
@end quotation
@end cartouche

@node Heap Types<2>,取り掛かり中の問題,Making Modules Safe with Multiple Interpreters,拡張モジュールを分離する
@anchor{howto/isolating-extensions heap-types}@anchor{583c}
@subsection Heap Types


Traditionally, types defined in C code are `static'; that is,
@code{static PyTypeObject} structures defined directly in code and
initialized using @code{PyType_Ready()}.

Such types are necessarily shared across the process. Sharing them
between module objects requires paying attention to any state they own
or access. To limit the possible issues, static types are immutable at
the Python level: for example, you can't set @code{str.myattribute = 123}.

`CPython 実装の詳細:' Sharing truly immutable objects between interpreters is fine,
as long as they don't provide access to mutable objects.
However, in CPython, every Python object has a mutable implementation
detail: the reference count. Changes to the refcount are guarded by the GIL.
Thus, code that shares any Python objects across interpreters implicitly
depends on CPython's current, process-wide GIL.

Because they are immutable and process-global, static types cannot access
"their" module state.
If any method of such a type requires access to module state,
the type must be converted to a `heap-allocated type', or `heap type'
for short. These correspond more closely to classes created by Python's
@code{class} statement.

For new modules, using heap types by default is a good rule of thumb.

@menu
* Changing Static Types to Heap Types:: 
* Defining Heap Types:: 
* Garbage-Collection Protocol:: 
* Module State Access from Classes:: 
* Module State Access from Regular Methods:: 
* Module State Access from Slot Methods@comma{} Getters and Setters: Module State Access from Slot Methods Getters and Setters. 
* Lifetime of the Module State:: 

@end menu

@node Changing Static Types to Heap Types,Defining Heap Types,,Heap Types<2>
@anchor{howto/isolating-extensions changing-static-types-to-heap-types}@anchor{583d}
@subsubsection Changing Static Types to Heap Types


Static types can be converted to heap types, but note that
the heap type API was not designed for "lossless" conversion
from static types—that is, creating a type that works exactly like a given
static type.
So, when rewriting the class definition in a new API,
you are likely to unintentionally change a few details (e.g. pickleability
or inherited slots).
Always test the details that are important to you.

Watch out for the following two points in particular (but note that this is not
a comprehensive list):


@itemize *

@item 
Unlike static types, heap type objects are mutable by default.
Use the @ref{3cf,,Py_TPFLAGS_IMMUTABLETYPE} flag to prevent mutability.

@item 
Heap types inherit @ref{79f,,tp_new} by default,
so it may become possible to instantiate them from Python code.
You can prevent this with the @ref{7a2,,Py_TPFLAGS_DISALLOW_INSTANTIATION} flag.
@end itemize

@node Defining Heap Types,Garbage-Collection Protocol,Changing Static Types to Heap Types,Heap Types<2>
@anchor{howto/isolating-extensions defining-heap-types}@anchor{583e}
@subsubsection Defining Heap Types


Heap types can be created by filling a @ref{1a89,,PyType_Spec} structure, a
description or "blueprint" of a class, and calling
@ref{773,,PyType_FromModuleAndSpec()} to construct a new class object.

@cartouche
@quotation 注釈 
Other functions, like @ref{79d,,PyType_FromSpec()}, can also create
heap types, but @ref{773,,PyType_FromModuleAndSpec()} associates the module
with the class, allowing access to the module state from methods.
@end quotation
@end cartouche

The class should generally be stored in `both' the module state (for
safe access from C) and the module's @code{__dict__} (for access from
Python code).

@node Garbage-Collection Protocol,Module State Access from Classes,Defining Heap Types,Heap Types<2>
@anchor{howto/isolating-extensions garbage-collection-protocol}@anchor{583f}
@subsubsection Garbage-Collection Protocol


Instances of heap types hold a reference to their type.
This ensures that the type isn't destroyed before all its instances are,
but may result in reference cycles that need to be broken by the
garbage collector.

To avoid memory leaks, instances of heap types must implement the
garbage collection protocol.
That is, heap types should:


@itemize -

@item 
Have the @ref{981,,Py_TPFLAGS_HAVE_GC} flag.

@item 
Define a traverse function using @ref{519d,,Py_tp_traverse}, which
visits the type (e.g. using @code{Py_VISIT(Py_TYPE(self))}).
@end itemize

Please refer to the documentation of
@ref{981,,Py_TPFLAGS_HAVE_GC} and @ref{982,,tp_traverse}
for additional considerations.

The API for defining heap types grew organically, leaving it
somewhat awkward to use in its current state.
The following sections will guide you through common issues.

@menu
* tp_traverse in Python 3.8 and lower: tp_traverse in Python 3 8 and lower. 
* Delegating tp_traverse:: 
* Defining tp_dealloc:: 
* Not overriding tp_free:: 
* Avoiding PyObject_New:: 

@end menu

@node tp_traverse in Python 3 8 and lower,Delegating tp_traverse,,Garbage-Collection Protocol
@anchor{howto/isolating-extensions tp-traverse-in-python-3-8-and-lower}@anchor{5840}
@subsubsection @code{tp_traverse} in Python 3.8 and lower


The requirement to visit the type from @code{tp_traverse} was added in Python 3.9.
If you support Python 3.8 and lower, the traverse function must `not'
visit the type, so it must be more complicated:

@example
static int my_traverse(PyObject *self, visitproc visit, void *arg)
@{
    if (Py_Version >= 0x03090000) @{
        Py_VISIT(Py_TYPE(self));
    @}
    return 0;
@}
@end example

Unfortunately, @ref{381,,Py_Version} was only added in Python 3.11.
As a replacement, use:


@itemize *

@item 
@ref{382,,PY_VERSION_HEX}, if not using the stable ABI, or

@item 
@ref{8af,,sys.version_info} (via @ref{62a,,PySys_GetObject()} and
@ref{3c1,,PyArg_ParseTuple()}).
@end itemize

@node Delegating tp_traverse,Defining tp_dealloc,tp_traverse in Python 3 8 and lower,Garbage-Collection Protocol
@anchor{howto/isolating-extensions delegating-tp-traverse}@anchor{5841}
@subsubsection Delegating @code{tp_traverse}


If your traverse function delegates to the @ref{982,,tp_traverse}
of its base class (or another type), ensure that @code{Py_TYPE(self)} is visited
only once.
Note that only heap type are expected to visit the type in @code{tp_traverse}.

For example, if your traverse function includes:

@example
base->tp_traverse(self, visit, arg)
@end example

...and @code{base} may be a static type, then it should also include:

@example
if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) @{
    // a heap type's tp_traverse already visited Py_TYPE(self)
@} else @{
    if (Py_Version >= 0x03090000) @{
        Py_VISIT(Py_TYPE(self));
    @}
@}
@end example

It is not necessary to handle the type's reference count in
@ref{79f,,tp_new} and @ref{4ee2,,tp_clear}.

@node Defining tp_dealloc,Not overriding tp_free,Delegating tp_traverse,Garbage-Collection Protocol
@anchor{howto/isolating-extensions defining-tp-dealloc}@anchor{5842}
@subsubsection Defining @code{tp_dealloc}


If your type has a custom @ref{4ebc,,tp_dealloc} function,
it needs to:


@itemize -

@item 
call @ref{171e,,PyObject_GC_UnTrack()} before any fields are invalidated, and

@item 
decrement the reference count of the type.
@end itemize

To keep the type valid while @code{tp_free} is called, the type's refcount needs
to be decremented `after' the instance is deallocated. For example:

@example
static void my_dealloc(PyObject *self)
@{
    PyObject_GC_UnTrack(self);
    ...
    PyTypeObject *type = Py_TYPE(self);
    type->tp_free(self);
    Py_DECREF(type);
@}
@end example

The default @code{tp_dealloc} function does this, so
if your type does `not' override
@code{tp_dealloc} you don't need to add it.

@node Not overriding tp_free,Avoiding PyObject_New,Defining tp_dealloc,Garbage-Collection Protocol
@anchor{howto/isolating-extensions not-overriding-tp-free}@anchor{5843}
@subsubsection Not overriding @code{tp_free}


The @ref{4ecf,,tp_free} slot of a heap type must be set to
@ref{171c,,PyObject_GC_Del()}.
This is the default; do not override it.

@node Avoiding PyObject_New,,Not overriding tp_free,Garbage-Collection Protocol
@anchor{howto/isolating-extensions avoiding-pyobject-new}@anchor{5844}
@subsubsection Avoiding @code{PyObject_New}


GC-tracked objects need to be allocated using GC-aware functions.

If you use @ref{b7c,,PyObject_New()} or @ref{b7d,,PyObject_NewVar()}:


@itemize -

@item 
Get and call type's @ref{4ed0,,tp_alloc} slot, if possible.
That is, replace @code{TYPE *o = PyObject_New(TYPE, typeobj)} with:

@example
TYPE *o = typeobj->tp_alloc(typeobj, 0);
@end example

Replace @code{o = PyObject_NewVar(TYPE, typeobj, size)} with the same,
but use size instead of the 0.

@item 
If the above is not possible (e.g. inside a custom @code{tp_alloc}),
call @ref{c99,,PyObject_GC_New()} or @ref{c9a,,PyObject_GC_NewVar()}:

@example
TYPE *o = PyObject_GC_New(TYPE, typeobj);

TYPE *o = PyObject_GC_NewVar(TYPE, typeobj, size);
@end example
@end itemize

@node Module State Access from Classes,Module State Access from Regular Methods,Garbage-Collection Protocol,Heap Types<2>
@anchor{howto/isolating-extensions module-state-access-from-classes}@anchor{5845}
@subsubsection Module State Access from Classes


If you have a type object defined with @ref{773,,PyType_FromModuleAndSpec()},
you can call @ref{b66,,PyType_GetModule()} to get the associated module, and then
@ref{b77,,PyModule_GetState()} to get the module's state.

To save a some tedious error-handling boilerplate code, you can combine
these two steps with @ref{b67,,PyType_GetModuleState()}, resulting in:

@example
my_struct *state = (my_struct*)PyType_GetModuleState(type);
if (state == NULL) @{
    return NULL;
@}
@end example

@node Module State Access from Regular Methods,Module State Access from Slot Methods Getters and Setters,Module State Access from Classes,Heap Types<2>
@anchor{howto/isolating-extensions module-state-access-from-regular-methods}@anchor{5846}
@subsubsection Module State Access from Regular Methods


Accessing the module-level state from methods of a class is somewhat more
complicated, but is possible thanks to API introduced in Python 3.9.
To get the state, you need to first get the `defining class', and then
get the module state from it.

The largest roadblock is getting `the class a method was defined in', or
that method's "defining class" for short. The defining class can have a
reference to the module it is part of.

Do not confuse the defining class with @code{Py_TYPE(self)}. If the method
is called on a `subclass' of your type, @code{Py_TYPE(self)} will refer to
that subclass, which may be defined in different module than yours.

@cartouche
@quotation 注釈 
The following Python code can illustrate the concept.
@code{Base.get_defining_class} returns @code{Base} even
if @code{type(self) == Sub}:

@example
class Base:
    def get_type_of_self(self):
        return type(self)

    def get_defining_class(self):
        return __class__

class Sub(Base):
    pass
@end example
@end quotation
@end cartouche

For a method to get its "defining class", it must use the
@ref{1a09,,METH_METHOD | METH_FASTCALL | METH_KEYWORDS}
@ref{16f0,,calling convention}
and the corresponding @ref{968,,PyCMethod} signature:

@example
PyObject *PyCMethod(
    PyObject *self,               // object the method was called on
    PyTypeObject *defining_class, // defining class
    PyObject *const *args,        // C array of arguments
    Py_ssize_t nargs,             // length of "args"
    PyObject *kwnames)            // NULL, or dict of keyword arguments
@end example

Once you have the defining class, call @ref{b67,,PyType_GetModuleState()} to get
the state of its associated module.

例えば:

@example
static PyObject *
example_method(PyObject *self,
        PyTypeObject *defining_class,
        PyObject *const *args,
        Py_ssize_t nargs,
        PyObject *kwnames)
@{
    my_struct *state = (my_struct*)PyType_GetModuleState(defining_class);
    if (state == NULL) @{
        return NULL;
    @}
    ... // rest of logic
@}

PyDoc_STRVAR(example_method_doc, "...");

static PyMethodDef my_methods[] = @{
    @{"example_method",
      (PyCFunction)(void(*)(void))example_method,
      METH_METHOD|METH_FASTCALL|METH_KEYWORDS,
      example_method_doc@}
    @{NULL@},
@}
@end example

@node Module State Access from Slot Methods Getters and Setters,Lifetime of the Module State,Module State Access from Regular Methods,Heap Types<2>
@anchor{howto/isolating-extensions module-state-access-from-slot-methods-getters-and-setters}@anchor{5847}
@subsubsection Module State Access from Slot Methods, Getters and Setters


@cartouche
@quotation 注釈 
これは Python 3.11 の新機能です。

@c After adding to limited API:
@c 
@c If you use the :ref:`limited API <limited-c-api>`,
@c you must update ``Py_LIMITED_API`` to ``0x030b0000``, losing ABI
@c compatibility with earlier versions.
@end quotation
@end cartouche

Slot methods—the fast C equivalents for special methods, such as
@ref{52e2,,nb_add} for @ref{23dd,,__add__} or
@ref{79f,,tp_new} for initialization—have a very simple API that
doesn't allow passing in the defining class, unlike with @ref{968,,PyCMethod}.
The same goes for getters and setters defined with
@ref{db2,,PyGetSetDef}.

To access the module state in these cases, use the
@ref{635,,PyType_GetModuleByDef()} function, and pass in the module definition.
Once you have the module, call @ref{b77,,PyModule_GetState()}
to get the state:

@example
PyObject *module = PyType_GetModuleByDef(Py_TYPE(self), &module_def);
my_struct *state = (my_struct*)PyModule_GetState(module);
if (state == NULL) @{
    return NULL;
@}
@end example

@code{PyType_GetModuleByDef()} works by searching the
@ref{25df,,method resolution order} (i.e. all superclasses) for the first
superclass that has a corresponding module.

@cartouche
@quotation 注釈 
In very exotic cases (inheritance chains spanning multiple modules
created from the same definition), @code{PyType_GetModuleByDef()} might not
return the module of the true defining class. However, it will always
return a module with the same definition, ensuring a compatible
C memory layout.
@end quotation
@end cartouche

@node Lifetime of the Module State,,Module State Access from Slot Methods Getters and Setters,Heap Types<2>
@anchor{howto/isolating-extensions lifetime-of-the-module-state}@anchor{5848}
@subsubsection Lifetime of the Module State


When a module object is garbage-collected, its module state is freed.
For each pointer to (a part of) the module state, you must hold a reference
to the module object.

Usually this is not an issue, because types created with
@ref{773,,PyType_FromModuleAndSpec()}, and their instances, hold a reference
to the module.
However, you must be careful in reference counting when you reference
module state from other places, such as callbacks for external
libraries.

@node 取り掛かり中の問題,,Heap Types<2>,拡張モジュールを分離する
@anchor{howto/isolating-extensions open-issues}@anchor{5849}
@subsection 取り掛かり中の問題


Several issues around per-module state and heap types are still open.

Discussions about improving the situation are best held on the discuss forum under c-api tag@footnote{https://discuss.python.org/c/core-dev/c-api/30}.

@menu
* クラスごとのスコープ:: 
* Lossless Conversion to Heap Types:: 

@end menu

@node クラスごとのスコープ,Lossless Conversion to Heap Types,,取り掛かり中の問題
@anchor{howto/isolating-extensions per-class-scope}@anchor{584a}
@subsubsection クラスごとのスコープ


It is currently (as of Python 3.11) not possible to attach state to individual
`types' without relying on CPython implementation details (which may change
in the future—perhaps, ironically, to allow a proper solution for
per-class scope).

@node Lossless Conversion to Heap Types,,クラスごとのスコープ,取り掛かり中の問題
@anchor{howto/isolating-extensions lossless-conversion-to-heap-types}@anchor{584b}
@subsubsection Lossless Conversion to Heap Types


The heap type API was not designed for "lossless" conversion from static types;
that is, creating a type that works exactly like a given static type.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node timer file descriptor HOWTO,The Python 2 3 Method Resolution Order,拡張モジュールを分離する,Python HOWTO
@anchor{howto/timerfd doc}@anchor{584c}@anchor{howto/timerfd timer-file-descriptor-howto}@anchor{584d}@anchor{howto/timerfd timerfd-howto}@anchor{584e}@anchor{howto/timerfd translation-repo}@anchor{584f}
@section timer file descriptor HOWTO


@*リリース: 
1.13


This HOWTO discusses Python's support for the linux timer file descriptor.

@menu
* 使用例: 使用例<59>. 

@end menu

@node 使用例<59>,,,timer file descriptor HOWTO
@anchor{howto/timerfd examples}@anchor{5850}
@subsection 使用例


The following example shows how to use a timer file descriptor
to execute a function twice a second:

@example
# Practical scripts should use really use a non-blocking timer,
# we use a blocking timer here for simplicity.
import os, time

# Create the timer file descriptor
fd = os.timerfd_create(time.CLOCK_REALTIME)

# Start the timer in 1 second, with an interval of half a second
os.timerfd_settime(fd, initial=1, interval=0.5)

try:
    # Process timer events four times.
    for _ in range(4):
        # read() will block until the timer expires
        _ = os.read(fd, 8)
        print("Timer expired")
finally:
    # Remember to close the timer file descriptor!
    os.close(fd)
@end example

To avoid the precision loss caused by the @ref{196,,float} type,
timer file descriptors allow specifying initial expiration and interval
in integer nanoseconds with @code{_ns} variants of the functions.

This example shows how @ref{1196,,epoll()} can be used with timer file
descriptors to wait until the file descriptor is ready for reading:

@example
import os, time, select, socket, sys

# Create an epoll object
ep = select.epoll()

# In this example, use loopback address to send "stop" command to the server.
#
# $ telnet 127.0.0.1 1234
# Trying 127.0.0.1...
# Connected to 127.0.0.1.
# Escape character is '^]'.
# stop
# Connection closed by foreign host.
#
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 1234))
sock.setblocking(False)
sock.listen(1)
ep.register(sock, select.EPOLLIN)

# Create timer file descriptors in non-blocking mode.
num = 3
fds = []
for _ in range(num):
    fd = os.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)
    fds.append(fd)
    # Register the timer file descriptor for read events
    ep.register(fd, select.EPOLLIN)

# Start the timer with os.timerfd_settime_ns() in nanoseconds.
# Timer 1 fires every 0.25 seconds; timer 2 every 0.5 seconds; etc
for i, fd in enumerate(fds, start=1):
    one_sec_in_nsec = 10**9
    i = i * one_sec_in_nsec
    os.timerfd_settime_ns(fd, initial=i//4, interval=i//4)

timeout = 3
try:
    conn = None
    is_active = True
    while is_active:
        # Wait for the timer to expire for 3 seconds.
        # epoll.poll() returns a list of (fd, event) pairs.
        # fd is a file descriptor.
        # sock and conn[=returned value of socket.accept()] are socket objects, not file descriptors.
        # So use sock.fileno() and conn.fileno() to get the file descriptors.
        events = ep.poll(timeout)

        # If more than one timer file descriptors are ready for reading at once,
        # epoll.poll() returns a list of (fd, event) pairs.
        #
        # In this example settings,
        #    1st timer fires every 0.25 seconds in 0.25 seconds. (0.25, 0.5, 0.75, 1.0, ...)
        #    2nd timer every 0.5 seconds in 0.5 seconds. (0.5, 1.0, 1.5, 2.0, ...)
        #    3rd timer every 0.75 seconds in 0.75 seconds. (0.75, 1.5, 2.25, 3.0, ...)
        #
        #    In 0.25 seconds, only 1st timer fires.
        #    In 0.5 seconds, 1st timer and 2nd timer fires at once.
        #    In 0.75 seconds, 1st timer and 3rd timer fires at once.
        #    In 1.5 seconds, 1st timer, 2nd timer and 3rd timer fires at once.
        #
        # If a timer file descriptor is signaled more than once since
        # the last os.read() call, os.read() returns the number of signaled
        # as host order of class bytes.
        print(f"Signaled events=@{events@}")
        for fd, event in events:
            if event & select.EPOLLIN:
                if fd == sock.fileno():
                    # Check if there is a connection request.
                    print(f"Accepting connection @{fd@}")
                    conn, addr = sock.accept()
                    conn.setblocking(False)
                    print(f"Accepted connection @{conn@} from @{addr@}")
                    ep.register(conn, select.EPOLLIN)
                elif conn and fd == conn.fileno():
                    # Check if there is data to read.
                    print(f"Reading data @{fd@}")
                    data = conn.recv(1024)
                    if data:
                        # You should catch UnicodeDecodeError exception for safety.
                        cmd = data.decode()
                        if cmd.startswith("stop"):
                            print(f"Stopping server")
                            is_active = False
                        else:
                            print(f"Unknown command: @{cmd@}")
                    else:
                        # No more data, close connection
                        print(f"Closing connection @{fd@}")
                        ep.unregister(conn)
                        conn.close()
                        conn = None
                elif fd in fds:
                    print(f"Reading timer @{fd@}")
                    count = int.from_bytes(os.read(fd, 8), byteorder=sys.byteorder)
                    print(f"Timer @{fds.index(fd) + 1@} expired @{count@} times")
                else:
                    print(f"Unknown file descriptor @{fd@}")
finally:
    for fd in fds:
        ep.unregister(fd)
        os.close(fd)
    ep.close()
@end example

This example shows how @ref{fa0,,select()} can be used with timer file
descriptors to wait until the file descriptor is ready for reading:

@example
import os, time, select, socket, sys

# In this example, use loopback address to send "stop" command to the server.
#
# $ telnet 127.0.0.1 1234
# Trying 127.0.0.1...
# Connected to 127.0.0.1.
# Escape character is '^]'.
# stop
# Connection closed by foreign host.
#
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 1234))
sock.setblocking(False)
sock.listen(1)

# Create timer file descriptors in non-blocking mode.
num = 3
fds = [os.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)
       for _ in range(num)]
select_fds = fds + [sock]

# Start the timers with os.timerfd_settime() in seconds.
# Timer 1 fires every 0.25 seconds; timer 2 every 0.5 seconds; etc
for i, fd in enumerate(fds, start=1):
   os.timerfd_settime(fd, initial=i/4, interval=i/4)

timeout = 3
try:
    conn = None
    is_active = True
    while is_active:
       # Wait for the timer to expire for 3 seconds.
       # select.select() returns a list of file descriptors or objects.
       rfd, wfd, xfd = select.select(select_fds, select_fds, select_fds, timeout)
       for fd in rfd:
           if fd == sock:
               # Check if there is a connection request.
               print(f"Accepting connection @{fd@}")
               conn, addr = sock.accept()
               conn.setblocking(False)
               print(f"Accepted connection @{conn@} from @{addr@}")
               select_fds.append(conn)
           elif conn and fd == conn:
               # Check if there is data to read.
               print(f"Reading data @{fd@}")
               data = conn.recv(1024)
               if data:
                   # You should catch UnicodeDecodeError exception for safety.
                   cmd = data.decode()
                   if cmd.startswith("stop"):
                       print(f"Stopping server")
                       is_active = False
                   else:
                       print(f"Unknown command: @{cmd@}")
               else:
                   # No more data, close connection
                   print(f"Closing connection @{fd@}")
                   select_fds.remove(conn)
                   conn.close()
                   conn = None
           elif fd in fds:
               print(f"Reading timer @{fd@}")
               count = int.from_bytes(os.read(fd, 8), byteorder=sys.byteorder)
               print(f"Timer @{fds.index(fd) + 1@} expired @{count@} times")
           else:
               print(f"Unknown file descriptor @{fd@}")
finally:
    for fd in fds:
       os.close(fd)
    sock.close()
    sock = None
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node The Python 2 3 Method Resolution Order,Python support for free threading,timer file descriptor HOWTO,Python HOWTO
@anchor{howto/mro doc}@anchor{5851}@anchor{howto/mro python-2-3-mro}@anchor{16c3}@anchor{howto/mro the-python-2-3-method-resolution-order}@anchor{5852}@anchor{howto/mro translation-repo}@anchor{5853}
@section The Python 2.3 Method Resolution Order


@cartouche
@quotation 注釈 
This is a historical document, provided as an appendix to the official
documentation.
The Method Resolution Order discussed here was `introduced' in Python 2.3,
but it is still used in later versions -- including Python 3.
@end quotation
@end cartouche

By Michele Simionato@footnote{https://www.phyast.pitt.edu/~micheles/}.

@*概要: 
`This document is intended for Python programmers who want to
understand the C3 Method Resolution Order used in Python 2.3.
Although it is not intended for newbies, it is quite pedagogical with
many worked out examples.  I am not aware of other publicly available
documents with the same scope, therefore it should be useful.'


Disclaimer:

@quotation

`I donate this document to the Python Software Foundation, under the
Python 2.3 license.  As usual in these circumstances, I warn the
reader that what follows' should `be correct, but I don't give any
warranty.  Use it at your own risk and peril!'
@end quotation

Acknowledgments:

@quotation

`All the people of the Python mailing list who sent me their support.
Paul Foley who pointed out various imprecisions and made me to add the
part on local precedence ordering. David Goodger for help with the
formatting in reStructuredText. David Mertz for help with the editing.
Finally, Guido van Rossum who enthusiastically added this document to
the official Python 2.3 home-page.'
@end quotation

@menu
* The beginning:: 
* The C3 Method Resolution Order:: 
* 使用例: 使用例<60>. 
* Bad Method Resolution Orders:: 
* The end:: 
* Resources:: 

@end menu

@node The beginning,The C3 Method Resolution Order,,The Python 2 3 Method Resolution Order
@anchor{howto/mro the-beginning}@anchor{5854}
@subsection The beginning


@quotation

`Felix qui potuit rerum cognoscere causas' -- Virgilius
@end quotation

Everything started with a post by Samuele Pedroni to the Python
development mailing list @footnote{
The thread on python-dev started by Samuele Pedroni:
@indicateurl{https://mail.python.org/pipermail/python-dev/2002-October/029035.html}
}.  In his post, Samuele showed that the
Python 2.2 method resolution order is not monotonic and he proposed to
replace it with the C3 method resolution order.  Guido agreed with his
arguments and therefore now Python 2.3 uses C3.  The C3 method itself
has nothing to do with Python, since it was invented by people working
on Dylan and it is described in a paper intended for lispers @footnote{
The paper `A Monotonic Superclass Linearization for Dylan':
@indicateurl{https://doi.org/10.1145/236337.236343}
}.  The
present paper gives a (hopefully) readable discussion of the C3
algorithm for Pythonistas who want to understand the reasons for the
change.

First of all, let me point out that what I am going to say only applies
to the `new style classes' introduced in Python 2.2:  `classic classes'
maintain their old method resolution order, depth first and then left to
right.  Therefore, there is no breaking of old code for classic classes;
and even if in principle there could be breaking of code for Python 2.2
new style classes, in practice the cases in which the C3 resolution
order differs from the Python 2.2 method resolution order are so rare
that no real breaking of code is expected.  Therefore:

@quotation

`Don't be scared!'
@end quotation

Moreover, unless you make strong use of multiple inheritance and you
have non-trivial hierarchies, you don't need to understand the C3
algorithm, and you can easily skip this paper.  On the other hand, if
you really want to know how multiple inheritance works, then this paper
is for you.  The good news is that things are not as complicated as you
might expect.

Let me begin with some basic definitions.


@enumerate 

@item 
Given a class C in a complicated multiple inheritance hierarchy, it
is a non-trivial task to specify the order in which methods are
overridden, i.e. to specify the order of the ancestors of C.

@item 
The list of the ancestors of a class C, including the class itself,
ordered from the nearest ancestor to the furthest, is called the
class precedence list or the `linearization' of C.

@item 
The `Method Resolution Order' (MRO) is the set of rules that
construct the linearization.  In the Python literature, the idiom
"the MRO of C" is also used as a synonymous for the linearization of
the class C.

@item 
For instance, in the case of single inheritance hierarchy, if C is a
subclass of C1, and C1 is a subclass of C2, then the linearization of
C is simply the list [C, C1 , C2].  However, with multiple
inheritance hierarchies, the construction of the linearization is
more cumbersome, since it is more difficult to construct a
linearization that respects `local precedence ordering' and
`monotonicity'.

@item 
I will discuss the local precedence ordering later, but I can give
the definition of monotonicity here.  A MRO is monotonic when the
following is true:  `if C1 precedes C2 in the linearization of C,
then C1 precedes C2 in the linearization of any subclass of C'.
Otherwise, the innocuous operation of deriving a new class could
change the resolution order of methods, potentially introducing very
subtle bugs.  Examples where this happens will be shown later.

@item 
Not all classes admit a linearization.  There are cases, in
complicated hierarchies, where it is not possible to derive a class
such that its linearization respects all the desired properties.
@end enumerate

Here I give an example of this situation. Consider the hierarchy

@example
>>> O = object
>>> class X(O): pass
>>> class Y(O): pass
>>> class A(X,Y): pass
>>> class B(Y,X): pass
@end example

which can be represented with the following inheritance graph, where I
have denoted with O the @code{object} class, which is the beginning of any
hierarchy for new style classes:

@quotation

@example
 -----------
|           |
|    O      |
|  /   \    |
 - X    Y  /
   |  / | /
   | /  |/
   A    B
   \   /
     ?
@end example
@end quotation

In this case, it is not possible to derive a new class C from A and B,
since X precedes Y in A, but Y precedes X in B, therefore the method
resolution order would be ambiguous in C.

Python 2.3 raises an exception in this situation (TypeError:  MRO
conflict among bases Y, X) forbidding the naive programmer from creating
ambiguous hierarchies.  Python 2.2 instead does not raise an exception,
but chooses an `ad hoc' ordering (CABXYO in this case).

@node The C3 Method Resolution Order,使用例<60>,The beginning,The Python 2 3 Method Resolution Order
@anchor{howto/mro the-c3-method-resolution-order}@anchor{5855}
@subsection The C3 Method Resolution Order


Let me introduce a few simple notations which will be useful for the
following discussion.  I will use the shortcut notation:

@example
C1 C2 ... CN
@end example

to indicate the list of classes [C1, C2, ... , CN].

The `head' of the list is its first element:

@example
head = C1
@end example

whereas the `tail' is the rest of the list:

@example
tail = C2 ... CN.
@end example

I shall also use the notation:

@example
C + (C1 C2 ... CN) = C C1 C2 ... CN
@end example

to denote the sum of the lists [C] + [C1, C2, ... ,CN].

Now I can explain how the MRO works in Python 2.3.

Consider a class C in a multiple inheritance hierarchy, with C
inheriting from the base classes B1, B2, ...  , BN.  We want to
compute the linearization L[C] of the class C. The rule is the
following:

@quotation

`the linearization of C is the sum of C plus the merge of the
linearizations of the parents and the list of the parents.'
@end quotation

In symbolic notation:

@example
L[C(B1 ... BN)] = C + merge(L[B1] ... L[BN], B1 ... BN)
@end example

In particular, if C is the @code{object} class, which has no parents, the
linearization is trivial:

@example
L[object] = object.
@end example

However, in general one has to compute the merge according to the following
prescription:

@quotation

`take the head of the first list, i.e L[B1][0]; if this head is not in
the tail of any of the other lists, then add it to the linearization
of C and remove it from the lists in the merge, otherwise look at the
head of the next list and take it, if it is a good head.  Then repeat
the operation until all the class are removed or it is impossible to
find good heads.  In this case, it is impossible to construct the
merge, Python 2.3 will refuse to create the class C and will raise an
exception.'
@end quotation

This prescription ensures that the merge operation `preserves' the
ordering, if the ordering can be preserved.  On the other hand, if the
order cannot be preserved (as in the example of serious order
disagreement discussed above) then the merge cannot be computed.

The computation of the merge is trivial if C has only one parent
(single inheritance); in this case:

@example
L[C(B)] = C + merge(L[B],B) = C + L[B]
@end example

However, in the case of multiple inheritance things are more cumbersome
and I don't expect you can understand the rule without a couple of
examples ;-)

@node 使用例<60>,Bad Method Resolution Orders,The C3 Method Resolution Order,The Python 2 3 Method Resolution Order
@anchor{howto/mro examples}@anchor{5856}
@subsection 使用例


First example. Consider the following hierarchy:

@example
>>> O = object
>>> class F(O): pass
>>> class E(O): pass
>>> class D(O): pass
>>> class C(D,F): pass
>>> class B(D,E): pass
>>> class A(B,C): pass
@end example

In this case the inheritance graph can be drawn as:

@quotation

@example
                          6
                         ---
Level 3                 | O |                  (more general)
                      /  ---  \
                     /    |    \                      |
                    /     |     \                     |
                   /      |      \                    |
                  ---    ---    ---                   |
Level 2        3 | D | 4| E |  | F | 5                |
                  ---    ---    ---                   |
                   \  \ _ /       |                   |
                    \    / \ _    |                   |
                     \  /      \  |                   |
                      ---      ---                    |
Level 1            1 | B |    | C | 2                 |
                      ---      ---                    |
                        \      /                      |
                         \    /                      \ /
                           ---
Level 0                 0 | A |                (more specialized)
                           ---
@end example
@end quotation

The linearizations of O,D,E and F are trivial:

@example
L[O] = O
L[D] = D O
L[E] = E O
L[F] = F O
@end example

The linearization of B can be computed as:

@example
L[B] = B + merge(DO, EO, DE)
@end example

We see that D is a good head, therefore we take it and we are reduced to
compute @code{merge(O,EO,E)}.  Now O is not a good head, since it is in the
tail of the sequence EO.  In this case the rule says that we have to
skip to the next sequence.  Then we see that E is a good head; we take
it and we are reduced to compute @code{merge(O,O)} which gives O. Therefore:

@example
L[B] =  B D E O
@end example

Using the same procedure one finds:

@example
L[C] = C + merge(DO,FO,DF)
     = C + D + merge(O,FO,F)
     = C + D + F + merge(O,O)
     = C D F O
@end example

Now we can compute:

@example
L[A] = A + merge(BDEO,CDFO,BC)
     = A + B + merge(DEO,CDFO,C)
     = A + B + C + merge(DEO,DFO)
     = A + B + C + D + merge(EO,FO)
     = A + B + C + D + E + merge(O,FO)
     = A + B + C + D + E + F + merge(O,O)
     = A B C D E F O
@end example

In this example, the linearization is ordered in a pretty nice way
according to the inheritance level, in the sense that lower levels (i.e.
more specialized classes) have higher precedence (see the inheritance
graph).  However, this is not the general case.

I leave as an exercise for the reader to compute the linearization for
my second example:

@example
>>> O = object
>>> class F(O): pass
>>> class E(O): pass
>>> class D(O): pass
>>> class C(D,F): pass
>>> class B(E,D): pass
>>> class A(B,C): pass
@end example

The only difference with the previous example is the change B(D,E) -->
B(E,D); however even such a little modification completely changes the
ordering of the hierarchy:

@quotation

@example
                           6
                          ---
Level 3                  | O |
                       /  ---  \
                      /    |    \
                     /     |     \
                    /      |      \
                  ---     ---    ---
Level 2        2 | E | 4 | D |  | F | 5
                  ---     ---    ---
                   \      / \     /
                    \    /   \   /
                     \  /     \ /
                      ---     ---
Level 1            1 | B |   | C | 3
                      ---     ---
                       \       /
                        \     /
                          ---
Level 0                0 | A |
                          ---
@end example
@end quotation

Notice that the class E, which is in the second level of the hierarchy,
precedes the class C, which is in the first level of the hierarchy, i.e.
E is more specialized than C, even if it is in a higher level.

A lazy programmer can obtain the MRO directly from Python 2.2, since in
this case it coincides with the Python 2.3 linearization.  It is enough
to invoke the @ref{237a,,mro()} method of class A:

@example
>>> A.mro()
[<class 'A'>, <class 'B'>, <class 'E'>,
<class 'C'>, <class 'D'>, <class 'F'>,
<class 'object'>]
@end example

Finally, let me consider the example discussed in the first section,
involving a serious order disagreement.  In this case, it is
straightforward to compute the linearizations of O, X, Y, A and B:

@quotation

@example
L[O] = 0
L[X] = X O
L[Y] = Y O
L[A] = A X Y O
L[B] = B Y X O
@end example
@end quotation

However, it is impossible to compute the linearization for a class C
that inherits from A and B:

@example
L[C] = C + merge(AXYO, BYXO, AB)
     = C + A + merge(XYO, BYXO, B)
     = C + A + B + merge(XYO, YXO)
@end example

At this point we cannot merge the lists XYO and YXO, since X is in the
tail of YXO whereas Y is in the tail of XYO:  therefore there are no
good heads and the C3 algorithm stops.  Python 2.3 raises an error and
refuses to create the class C.

@node Bad Method Resolution Orders,The end,使用例<60>,The Python 2 3 Method Resolution Order
@anchor{howto/mro bad-method-resolution-orders}@anchor{5857}
@subsection Bad Method Resolution Orders


A MRO is `bad' when it breaks such fundamental properties as local
precedence ordering and monotonicity.  In this section, I will show
that both the MRO for classic classes and the MRO for new style classes
in Python 2.2 are bad.

It is easier to start with the local precedence ordering.  Consider the
following example:

@example
>>> F=type('Food',(),@{'remember2buy':'spam'@})
>>> E=type('Eggs',(F,),@{'remember2buy':'eggs'@})
>>> G=type('GoodFood',(F,E),@{@}) # under Python 2.3 this is an error!
@end example

with inheritance diagram

@quotation

@example
             O
             |
(buy spam)   F
             | \
             | E   (buy eggs)
             | /
             G

      (buy eggs or spam ?)
@end example
@end quotation

We see that class G inherits from F and E, with F `before' E:  therefore
we would expect the attribute `G.remember2buy' to be inherited by
`F.remember2buy' and not by `E.remember2buy':  nevertheless Python 2.2
gives

@example
>>> G.remember2buy
'eggs'
@end example

This is a breaking of local precedence ordering since the order in the
local precedence list, i.e. the list of the parents of G, is not
preserved in the Python 2.2 linearization of G:

@example
L[G,P22]= G E F object   # F *follows* E
@end example

One could argue that the reason why F follows E in the Python 2.2
linearization is that F is less specialized than E, since F is the
superclass of E; nevertheless the breaking of local precedence ordering
is quite non-intuitive and error prone.  This is particularly true since
it is a different from old style classes:

@example
>>> class F: remember2buy='spam'
>>> class E(F): remember2buy='eggs'
>>> class G(F,E): pass
>>> G.remember2buy
'spam'
@end example

In this case the MRO is GFEF and the local precedence ordering is
preserved.

As a general rule, hierarchies such as the previous one should be
avoided, since it is unclear if F should override E or vice-versa.
Python 2.3 solves the ambiguity by raising an exception in the creation
of class G, effectively stopping the programmer from generating
ambiguous hierarchies.  The reason for that is that the C3 algorithm
fails when the merge:

@example
merge(FO,EFO,FE)
@end example

cannot be computed, because F is in the tail of EFO and E is in the tail
of FE.

The real solution is to design a non-ambiguous hierarchy, i.e. to derive
G from E and F (the more specific first) and not from F and E; in this
case the MRO is GEF without any doubt.

@quotation

@example
           O
           |
           F (spam)
         / |
(eggs)   E |
         \ |
           G
             (eggs, no doubt)
@end example
@end quotation

Python 2.3 forces the programmer to write good hierarchies (or, at
least, less error-prone ones).

On a related note, let me point out that the Python 2.3 algorithm is
smart enough to recognize obvious mistakes, as the duplication of
classes in the list of parents:

@example
>>> class A(object): pass
>>> class C(A,A): pass # error
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: duplicate base class A
@end example

Python 2.2 (both for classic classes and new style classes) in this
situation, would not raise any exception.

Finally, I would like to point out two lessons we have learned from this
example:


@enumerate 

@item 
despite the name, the MRO determines the resolution order of
attributes, not only of methods;

@item 
the default food for Pythonistas is spam !  (but you already knew
that ;-)
@end enumerate

Having discussed the issue of local precedence ordering, let me now
consider the issue of monotonicity.  My goal is to show that neither the
MRO for classic classes nor that for Python 2.2 new style classes is
monotonic.

To prove that the MRO for classic classes is non-monotonic is rather
trivial, it is enough to look at the diamond diagram:

@quotation

@example
   C
  / \
 /   \
A     B
 \   /
  \ /
   D
@end example
@end quotation

One easily discerns the inconsistency:

@example
L[B,P21] = B C        # B precedes C : B's methods win
L[D,P21] = D A C B C  # B follows C  : C's methods win!
@end example

On the other hand, there are no problems with the Python 2.2 and 2.3
MROs, they give both:

@example
L[D] = D A B C
@end example

Guido points out in his essay @footnote{
Guido van Rossum's essay, `Unifying types and classes in Python 2.2':
@indicateurl{https://web.archive.org/web/20140210194412/http://www.python.org/download/releases/2.2.2/descrintro}
} that the classic MRO is not so bad in
practice, since one can typically avoids diamonds for classic classes.
But all new style classes inherit from @code{object}, therefore diamonds are
unavoidable and inconsistencies shows up in every multiple inheritance
graph.

The MRO of Python 2.2 makes breaking monotonicity difficult, but not
impossible.  The following example, originally provided by Samuele
Pedroni, shows that the MRO of Python 2.2 is non-monotonic:

@example
>>> class A(object): pass
>>> class B(object): pass
>>> class C(object): pass
>>> class D(object): pass
>>> class E(object): pass
>>> class K1(A,B,C): pass
>>> class K2(D,B,E): pass
>>> class K3(D,A):   pass
>>> class Z(K1,K2,K3): pass
@end example

Here are the linearizations according to the C3 MRO (the reader should
verify these linearizations as an exercise and draw the inheritance
diagram ;-)

@example
L[A] = A O
L[B] = B O
L[C] = C O
L[D] = D O
L[E] = E O
L[K1]= K1 A B C O
L[K2]= K2 D B E O
L[K3]= K3 D A O
L[Z] = Z K1 K2 K3 D A B C E O
@end example

Python 2.2 gives exactly the same linearizations for A, B, C, D, E, K1,
K2 and K3, but a different linearization for Z:

@example
L[Z,P22] = Z K1 K3 A K2 D B C E O
@end example

It is clear that this linearization is `wrong', since A comes before D
whereas in the linearization of K3 A comes `after' D. In other words, in
K3 methods derived by D override methods derived by A, but in Z, which
still is a subclass of K3, methods derived by A override methods derived
by D!  This is a violation of monotonicity.  Moreover, the Python 2.2
linearization of Z is also inconsistent with local precedence ordering,
since the local precedence list of the class Z is [K1, K2, K3] (K2
precedes K3), whereas in the linearization of Z K2 `follows' K3.  These
problems explain why the 2.2 rule has been dismissed in favor of the C3
rule.

@node The end,Resources,Bad Method Resolution Orders,The Python 2 3 Method Resolution Order
@anchor{howto/mro the-end}@anchor{5858}
@subsection The end


This section is for the impatient reader, who skipped all the previous
sections and jumped immediately to the end.  This section is for the
lazy programmer too, who didn't want to exercise her/his brain.
Finally, it is for the programmer with some hubris, otherwise s/he would
not be reading a paper on the C3 method resolution order in multiple
inheritance hierarchies ;-) These three virtues taken all together (and
`not' separately) deserve a prize:  the prize is a short Python 2.2
script that allows you to compute the 2.3 MRO without risk to your
brain.  Simply change the last line to play with the various examples I
have discussed in this paper.:

@example
#<mro.py>

"""C3 algorithm by Samuele Pedroni (with readability enhanced by me)."""

class __metaclass__(type):
    "All classes are metamagically modified to be nicely printed"
    __repr__ = lambda cls: cls.__name__

class ex_2:
    "Serious order disagreement" #From Guido
    class O: pass
    class X(O): pass
    class Y(O): pass
    class A(X,Y): pass
    class B(Y,X): pass
    try:
        class Z(A,B): pass #creates Z(A,B) in Python 2.2
    except TypeError:
        pass # Z(A,B) cannot be created in Python 2.3

class ex_5:
    "My first example"
    class O: pass
    class F(O): pass
    class E(O): pass
    class D(O): pass
    class C(D,F): pass
    class B(D,E): pass
    class A(B,C): pass

class ex_6:
    "My second example"
    class O: pass
    class F(O): pass
    class E(O): pass
    class D(O): pass
    class C(D,F): pass
    class B(E,D): pass
    class A(B,C): pass

class ex_9:
    "Difference between Python 2.2 MRO and C3" #From Samuele
    class O: pass
    class A(O): pass
    class B(O): pass
    class C(O): pass
    class D(O): pass
    class E(O): pass
    class K1(A,B,C): pass
    class K2(D,B,E): pass
    class K3(D,A): pass
    class Z(K1,K2,K3): pass

def merge(seqs):
    print '\n\nCPL[%s]=%s' % (seqs[0][0],seqs),
    res = []; i=0
    while 1:
      nonemptyseqs=[seq for seq in seqs if seq]
      if not nonemptyseqs: return res
      i+=1; print '\n',i,'round: candidates...',
      for seq in nonemptyseqs: # find merge candidates among seq heads
          cand = seq[0]; print ' ',cand,
          nothead=[s for s in nonemptyseqs if cand in s[1:]]
          if nothead: cand=None #reject candidate
          else: break
      if not cand: raise "Inconsistent hierarchy"
      res.append(cand)
      for seq in nonemptyseqs: # remove cand
          if seq[0] == cand: del seq[0]

def mro(C):
    "Compute the class precedence list (mro) according to C3"
    return merge([[C]]+map(mro,C.__bases__)+[list(C.__bases__)])

def print_mro(C):
    print '\nMRO[%s]=%s' % (C,mro(C))
    print '\nP22 MRO[%s]=%s' % (C,C.mro())

print_mro(ex_9.Z)

#</mro.py>
@end example

That's all folks,

@quotation

enjoy !
@end quotation

@node Resources,,The end,The Python 2 3 Method Resolution Order
@anchor{howto/mro resources}@anchor{5859}
@subsection Resources


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python support for free threading,C API Extension Support for Free Threading,The Python 2 3 Method Resolution Order,Python HOWTO
@anchor{howto/free-threading-python doc}@anchor{585a}@anchor{howto/free-threading-python freethreading-python-howto}@anchor{2619}@anchor{howto/free-threading-python python-support-for-free-threading}@anchor{585b}@anchor{howto/free-threading-python translation-repo}@anchor{585c}
@section Python support for free threading


Starting with the 3.13 release, CPython has support for a build of
Python called @ref{1f4,,free threading} where the @ref{474,,global interpreter lock}
(GIL) is disabled.  Free-threaded execution allows for full utilization of the
available processing power by running threads in parallel on available CPU cores.
While not all software will benefit from this automatically, programs
designed with threading in mind will run faster on multi-core hardware.

Some third-party packages, in particular ones
with an @ref{2251,,extension module}, may not be ready for use in a
free-threaded build, and will re-enable the @ref{164,,GIL}.

This document describes the implications of free threading
for Python code.  See @ref{585d,,C API Extension Support for Free Threading} for information on
how to write C extensions that support the free-threaded build.


@subsubheading 参考


@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/} – Making the Global Interpreter Lock Optional in CPython for an
overall description of free-threaded Python.


@menu
* Installation: Installation<2>. 
* Identifying free-threaded Python:: 
* The global interpreter lock in free-threaded Python:: 
* Thread safety:: 
* Known limitations:: 
* Behavioral changes:: 

@end menu

@node Installation<2>,Identifying free-threaded Python,,Python support for free threading
@anchor{howto/free-threading-python installation}@anchor{585e}
@subsection Installation


Starting with Python 3.13, the official macOS and Windows installers
optionally support installing free-threaded Python binaries.  The installers
are available at @indicateurl{https://www.python.org/downloads/}.

For information on other platforms, see the Installing a Free-Threaded Python@footnote{https://py-free-threading.github.io/installing-cpython/}, a
community-maintained installation guide for installing free-threaded Python.

When building CPython from source, the @ref{499,,--disable-gil} configure option
should be used to build a free-threaded Python interpreter.

@node Identifying free-threaded Python,The global interpreter lock in free-threaded Python,Installation<2>,Python support for free threading
@anchor{howto/free-threading-python identifying-free-threaded-python}@anchor{585f}
@subsection Identifying free-threaded Python


To check if the current interpreter supports free-threading, @ref{49b,,python -VV}
and @ref{49c,,sys.version} contain "free-threading build".
The new @ref{4926,,sys._is_gil_enabled()} function can be used to check whether
the GIL is actually disabled in the running process.

The @code{sysconfig.get_config_var("Py_GIL_DISABLED")} configuration variable can
be used to determine whether the build supports free threading.  If the variable
is set to @code{1}, then the build supports free threading.  This is the recommended
mechanism for decisions related to the build configuration.

@node The global interpreter lock in free-threaded Python,Thread safety,Identifying free-threaded Python,Python support for free threading
@anchor{howto/free-threading-python the-global-interpreter-lock-in-free-threaded-python}@anchor{5860}
@subsection The global interpreter lock in free-threaded Python


Free-threaded builds of CPython support optionally running with the GIL enabled
at runtime using the environment variable 
@geindex PYTHON_GIL
@geindex 環境変数; PYTHON_GIL
@ref{49a,,PYTHON_GIL} or
the command-line option @ref{16f,,-X gil}.

The GIL may also automatically be enabled when importing a C-API extension
module that is not explicitly marked as supporting free threading.  A warning
will be printed in this case.

In addition to individual package documentation, the following websites track
the status of popular packages support for free threading:


@itemize *

@item 
@indicateurl{https://py-free-threading.github.io/tracking/}

@item 
@indicateurl{https://hugovk.github.io/free-threaded-wheels/}
@end itemize

@node Thread safety,Known limitations,The global interpreter lock in free-threaded Python,Python support for free threading
@anchor{howto/free-threading-python thread-safety}@anchor{5861}
@subsection Thread safety


The free-threaded build of CPython aims to provide similar thread-safety
behavior at the Python level to the default GIL-enabled build.  Built-in
types like @ref{183,,dict}, @ref{24d,,list}, and @ref{184,,set} use internal locks
to protect against concurrent modifications in ways that behave similarly to
the GIL.  However, Python has not historically guaranteed specific behavior for
concurrent modifications to these built-in types, so this should be treated
as a description of the current implementation, not a guarantee of current or
future behavior.

@cartouche
@quotation 注釈 
It's recommended to use the @ref{19f4,,threading.Lock} or other synchronization
primitives instead of relying on the internal locks of built-in types, when
possible.
@end quotation
@end cartouche

@node Known limitations,Behavioral changes,Thread safety,Python support for free threading
@anchor{howto/free-threading-python known-limitations}@anchor{5862}
@subsection Known limitations


This section describes known limitations of the free-threaded CPython build.

@menu
* Immortalization:: 
* フレーム (frame) オブジェクト: フレーム frame オブジェクト<3>. 
* イテレータ (iterator): イテレータ iterator<3>. 
* Single-threaded performance:: 

@end menu

@node Immortalization,フレーム frame オブジェクト<3>,,Known limitations
@anchor{howto/free-threading-python immortalization}@anchor{5863}
@subsubsection Immortalization


In the free-threaded build, some objects are @ref{290,,immortal}.
Immortal objects are not deallocated and have reference counts that are
never modified.  This is done to avoid reference count contention that would
prevent efficient multi-threaded scaling.

As of the 3.14 release, immortalization is limited to:


@itemize *

@item 
Code constants: numeric literals, string literals, and tuple literals
composed of other constants.

@item 
Strings interned by @ref{14f3,,sys.intern()}.
@end itemize

@node フレーム frame オブジェクト<3>,イテレータ iterator<3>,Immortalization,Known limitations
@anchor{howto/free-threading-python frame-objects}@anchor{5864}
@subsubsection フレーム (frame) オブジェクト


It is not safe to access @ref{4a5,,frame.f_locals} from a @ref{8ef,,frame}
object if that frame is currently executing in another thread, and doing so may
crash the interpreter.

@node イテレータ iterator<3>,Single-threaded performance,フレーム frame オブジェクト<3>,Known limitations
@anchor{howto/free-threading-python iterators}@anchor{5865}
@subsubsection イテレータ (iterator)


It is generally not thread-safe to access the same iterator object from
multiple threads concurrently, and threads may see duplicate or missing
elements.

@node Single-threaded performance,,イテレータ iterator<3>,Known limitations
@anchor{howto/free-threading-python single-threaded-performance}@anchor{5866}
@subsubsection Single-threaded performance


The free-threaded build has additional overhead when executing Python code
compared to the default GIL-enabled build.  The amount of overhead depends
on the workload and hardware.  On the pyperformance benchmark suite, the
average overhead ranges from about 1% on macOS aarch64 to 8% on x86-64 Linux
systems.

@node Behavioral changes,,Known limitations,Python support for free threading
@anchor{howto/free-threading-python behavioral-changes}@anchor{5867}
@subsection Behavioral changes


This section describes CPython behavioural changes with the free-threaded
build.

@menu
* Context variables:: 
* Warning filters:: 

@end menu

@node Context variables,Warning filters,,Behavioral changes
@anchor{howto/free-threading-python context-variables}@anchor{5868}
@subsubsection Context variables


In the free-threaded build, the flag @ref{175,,thread_inherit_context}
is set to true by default which causes threads created with
@ref{176,,threading.Thread} to start with a copy of the
@ref{177,,Context()} of the caller of
@ref{178,,start()}.  In the default GIL-enabled build, the flag
defaults to false so threads start with an
empty @ref{177,,Context()}.

@node Warning filters,,Context variables,Behavioral changes
@anchor{howto/free-threading-python warning-filters}@anchor{5869}
@subsubsection Warning filters


In the free-threaded build, the flag @ref{18a,,context_aware_warnings}
is set to true by default.  In the default GIL-enabled build, the flag defaults
to false.  If the flag is true then the @ref{179,,warnings.catch_warnings}
context manager uses a context variable for warning filters.  If the flag is
false then @ref{179,,catch_warnings} modifies the global filters list,
which is not thread-safe.  See the @ref{118,,warnings} module for more details.

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node C API Extension Support for Free Threading,Remote debugging attachment protocol,Python support for free threading,Python HOWTO
@anchor{howto/free-threading-extensions doc}@anchor{586a}@anchor{howto/free-threading-extensions c-api-extension-support-for-free-threading}@anchor{586b}@anchor{howto/free-threading-extensions freethreading-extensions-howto}@anchor{585d}@anchor{howto/free-threading-extensions translation-repo}@anchor{586c}
@section C API Extension Support for Free Threading


Starting with the 3.13 release, CPython has support for running with
the @ref{474,,global interpreter lock} (GIL) disabled in a configuration
called @ref{1f4,,free threading}.  This document describes how to adapt C API
extensions to support free threading.

@menu
* Identifying the Free-Threaded Build in C:: 
* Module Initialization:: 
* General API Guidelines:: 
* Borrowed References:: 
* Memory Allocation APIs:: 
* Thread State and GIL APIs:: 
* Protecting Internal Extension State:: 
* Critical Sections:: 
* Building Extensions for the Free-Threaded Build:: 

@end menu

@node Identifying the Free-Threaded Build in C,Module Initialization,,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions identifying-the-free-threaded-build-in-c}@anchor{586d}
@subsection Identifying the Free-Threaded Build in C


The CPython C API exposes the @code{Py_GIL_DISABLED} macro: in the free-threaded
build it's defined to @code{1}, and in the regular build it's not defined.
You can use it to enable code that only runs under the free-threaded build:

@example
#ifdef Py_GIL_DISABLED
/* code that only runs in the free-threaded build */
#endif
@end example

@cartouche
@quotation 注釈 
On Windows, this macro is not defined automatically, but must be specified
to the compiler when building. The @ref{174,,sysconfig.get_config_var()} function
can be used to determine whether the current running interpreter had the
macro defined.
@end quotation
@end cartouche

@node Module Initialization,General API Guidelines,Identifying the Free-Threaded Build in C,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions module-initialization}@anchor{586e}
@subsection Module Initialization


Extension modules need to explicitly indicate that they support running with
the GIL disabled; otherwise importing the extension will raise a warning and
enable the GIL at runtime.

There are two ways to indicate that an extension module supports running with
the GIL disabled depending on whether the extension uses multi-phase or
single-phase initialization.

@menu
* Multi-Phase Initialization:: 
* Single-Phase Initialization:: 

@end menu

@node Multi-Phase Initialization,Single-Phase Initialization,,Module Initialization
@anchor{howto/free-threading-extensions multi-phase-initialization}@anchor{586f}
@subsubsection Multi-Phase Initialization


Extensions that use multi-phase initialization (i.e.,
@ref{4ea3,,PyModuleDef_Init()}) should add a @ref{482,,Py_mod_gil} slot in the
module definition.  If your extension supports older versions of CPython,
you should guard the slot with a @ref{382,,PY_VERSION_HEX} check.

@example
static struct PyModuleDef_Slot module_slots[] = @{
    ...
#if PY_VERSION_HEX >= 0x030D0000
    @{Py_mod_gil, Py_MOD_GIL_NOT_USED@},
#endif
    @{0, NULL@}
@};

static struct PyModuleDef moduledef = @{
    PyModuleDef_HEAD_INIT,
    .m_slots = module_slots,
    ...
@};
@end example

@node Single-Phase Initialization,,Multi-Phase Initialization,Module Initialization
@anchor{howto/free-threading-extensions single-phase-initialization}@anchor{5870}
@subsubsection Single-Phase Initialization


Extensions that use single-phase initialization (i.e.,
@ref{5217,,PyModule_Create()}) should call @ref{49d,,PyUnstable_Module_SetGIL()} to
indicate that they support running with the GIL disabled.  The function is
only defined in the free-threaded build, so you should guard the call with
@code{#ifdef Py_GIL_DISABLED} to avoid compilation errors in the regular build.

@example
static struct PyModuleDef moduledef = @{
    PyModuleDef_HEAD_INIT,
    ...
@};

PyMODINIT_FUNC
PyInit_mymodule(void)
@{
    PyObject *m = PyModule_Create(&moduledef);
    if (m == NULL) @{
        return NULL;
    @}
#ifdef Py_GIL_DISABLED
    PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
#endif
    return m;
@}
@end example

@node General API Guidelines,Borrowed References,Module Initialization,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions general-api-guidelines}@anchor{5871}
@subsection General API Guidelines


Most of the C API is thread-safe, but there are some exceptions.


@itemize *

@item 
`Struct Fields': Accessing fields in Python C API objects or structs
directly is not thread-safe if the field may be concurrently modified.

@item 
`Macros': Accessor macros like @ref{4f5f,,PyList_GET_ITEM},
@ref{62f,,PyList_SET_ITEM}, and macros like
@ref{3ca,,PySequence_Fast_GET_SIZE} that use the object returned by
@ref{18a2,,PySequence_Fast()} do not perform any error checking or locking.
These macros are not thread-safe if the container object may be modified
concurrently.

@item 
`Borrowed References': C API functions that return
@ref{3d7,,borrowed references} may not be thread-safe if
the containing object is modified concurrently.  See the section on
@ref{5872,,borrowed references} for more information.
@end itemize

@menu
* Container Thread Safety:: 

@end menu

@node Container Thread Safety,,,General API Guidelines
@anchor{howto/free-threading-extensions container-thread-safety}@anchor{5873}
@subsubsection Container Thread Safety


Containers like @ref{52a8,,PyListObject},
@ref{64f,,PyDictObject}, and @ref{53c9,,PySetObject} perform internal locking
in the free-threaded build.  For example, the @ref{503f,,PyList_Append()} will
lock the list before appending an item.

@menu
* PyDict_Next:: 

@end menu

@node PyDict_Next,,,Container Thread Safety
@anchor{howto/free-threading-extensions id1}@anchor{5874}@anchor{howto/free-threading-extensions pydict-next}@anchor{5875}
@subsubsection @code{PyDict_Next}


A notable exception is @ref{198f,,PyDict_Next()}, which does not lock the
dictionary.  You should use @ref{53ab,,Py_BEGIN_CRITICAL_SECTION} to protect
the dictionary while iterating over it if the dictionary may be concurrently
modified:

@example
Py_BEGIN_CRITICAL_SECTION(dict);
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict, &pos, &key, &value)) @{
    ...
@}
Py_END_CRITICAL_SECTION();
@end example

@node Borrowed References,Memory Allocation APIs,General API Guidelines,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions borrowed-references}@anchor{5876}
@subsection Borrowed References

@anchor{howto/free-threading-extensions id2}@anchor{5872}
Some C API functions return @ref{3d7,,borrowed references}.
These APIs are not thread-safe if the containing object is modified
concurrently.  For example, it's not safe to use @ref{5ff,,PyList_GetItem()}
if the list may be modified concurrently.

The following table lists some borrowed reference APIs and their replacements
that return @ref{5e2,,strong references}.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Borrowed reference API

@tab

Strong reference API

@item

@ref{5ff,,PyList_GetItem()}

@tab

@ref{5fe,,PyList_GetItemRef()}

@item

@ref{4f5f,,PyList_GET_ITEM()}

@tab

@ref{5fe,,PyList_GetItemRef()}

@item

@ref{628,,PyDict_GetItem()}

@tab

@ref{5e0,,PyDict_GetItemRef()}

@item

@ref{5e1,,PyDict_GetItemWithError()}

@tab

@ref{5e0,,PyDict_GetItemRef()}

@item

@ref{629,,PyDict_GetItemString()}

@tab

@ref{421,,PyDict_GetItemStringRef()}

@item

@ref{5e4,,PyDict_SetDefault()}

@tab

@ref{5e3,,PyDict_SetDefaultRef()}

@item

@ref{198f,,PyDict_Next()}

@tab

none (see @ref{5875,,PyDict_Next})

@item

@ref{3dd,,PyWeakref_GetObject()}

@tab

@ref{3df,,PyWeakref_GetRef()}

@item

@ref{3de,,PyWeakref_GET_OBJECT()}

@tab

@ref{3df,,PyWeakref_GetRef()}

@item

@ref{5fc,,PyImport_AddModule()}

@tab

@ref{5fb,,PyImport_AddModuleRef()}

@item

@ref{540a,,PyCell_GET()}

@tab

@ref{5409,,PyCell_Get()}

@end multitable


Not all APIs that return borrowed references are problematic.  For
example, @ref{4eb7,,PyTuple_GetItem()} is safe because tuples are immutable.
Similarly, not all uses of the above APIs are problematic.  For example,
@ref{628,,PyDict_GetItem()} is often used for parsing keyword argument
dictionaries in function calls; those keyword argument dictionaries are
effectively private (not accessible by other threads), so using borrowed
references in that context is safe.

Some of these functions were added in Python 3.13.  You can use the
pythoncapi-compat@footnote{https://github.com/python/pythoncapi-compat} package
to provide implementations of these functions for older Python versions.

@node Memory Allocation APIs,Thread State and GIL APIs,Borrowed References,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions free-threaded-memory-allocation}@anchor{55b6}@anchor{howto/free-threading-extensions memory-allocation-apis}@anchor{5877}
@subsection Memory Allocation APIs


Python's memory management C API provides functions in three different
@ref{55b1,,allocation domains}: "raw", "mem", and "object".
For thread-safety, the free-threaded build requires that only Python objects
are allocated using the object domain, and that all Python objects are
allocated using that domain.  This differs from the prior Python versions,
where this was only a best practice and not a hard requirement.

@cartouche
@quotation 注釈 
Search for uses of @ref{e62,,PyObject_Malloc()} in your
extension and check that the allocated memory is used for Python objects.
Use @ref{e5f,,PyMem_Malloc()} to allocate buffers instead of
@ref{e62,,PyObject_Malloc()}.
@end quotation
@end cartouche

@node Thread State and GIL APIs,Protecting Internal Extension State,Memory Allocation APIs,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions thread-state-and-gil-apis}@anchor{5878}
@subsection Thread State and GIL APIs


Python provides a set of functions and macros to manage thread state and the
GIL, such as:


@itemize *

@item 
@ref{64a,,PyGILState_Ensure()} and @ref{64b,,PyGILState_Release()}

@item 
@ref{647,,PyEval_SaveThread()} and @ref{648,,PyEval_RestoreThread()}

@item 
@ref{4ebd,,Py_BEGIN_ALLOW_THREADS} and @ref{c7f,,Py_END_ALLOW_THREADS}
@end itemize

These functions should still be used in the free-threaded build to manage
thread state even when the @ref{164,,GIL} is disabled.  For example, if you
create a thread outside of Python, you must call @ref{64a,,PyGILState_Ensure()}
before calling into the Python API to ensure that the thread has a valid
Python thread state.

You should continue to call @ref{647,,PyEval_SaveThread()} or
@ref{4ebd,,Py_BEGIN_ALLOW_THREADS} around blocking operations, such as I/O or
lock acquisitions, to allow other threads to run the
@ref{17d8,,cyclic garbage collector}.

@node Protecting Internal Extension State,Critical Sections,Thread State and GIL APIs,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions protecting-internal-extension-state}@anchor{5879}
@subsection Protecting Internal Extension State


Your extension may have internal state that was previously protected by the
GIL.  You may need to add locking to protect this state.  The approach will
depend on your extension, but some common patterns include:


@itemize *

@item 
`Caches': global caches are a common source of shared state.  Consider
using a lock to protect the cache or disabling it in the free-threaded build
if the cache is not critical for performance.

@item 
`Global State': global state may need to be protected by a lock or moved
to thread local storage. C11 and C++11 provide the @code{thread_local} or
@code{_Thread_local} for
thread-local storage@footnote{https://en.cppreference.com/w/c/language/storage_duration}.
@end itemize

@node Critical Sections,Building Extensions for the Free-Threaded Build,Protecting Internal Extension State,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions critical-sections}@anchor{587a}
@subsection Critical Sections

@anchor{howto/free-threading-extensions id3}@anchor{587b}
In the free-threaded build, CPython provides a mechanism called "critical
sections" to protect data that would otherwise be protected by the GIL.
While extension authors may not interact with the internal critical section
implementation directly, understanding their behavior is crucial when using
certain C API functions or managing shared state in the free-threaded build.

@menu
* What Are Critical Sections?:: 
* Using Critical Sections:: 
* How Critical Sections Work:: 
* Deadlock Avoidance:: 
* Important Considerations:: 

@end menu

@node What Are Critical Sections?,Using Critical Sections,,Critical Sections
@anchor{howto/free-threading-extensions what-are-critical-sections}@anchor{587c}
@subsubsection What Are Critical Sections?


Conceptually, critical sections act as a deadlock avoidance layer built on
top of simple mutexes. Each thread maintains a stack of active critical
sections. When a thread needs to acquire a lock associated with a critical
section (e.g., implicitly when calling a thread-safe C API function like
@ref{4eb9,,PyDict_SetItem()}, or explicitly using macros), it attempts to acquire
the underlying mutex.

@node Using Critical Sections,How Critical Sections Work,What Are Critical Sections?,Critical Sections
@anchor{howto/free-threading-extensions using-critical-sections}@anchor{587d}
@subsubsection Using Critical Sections


The primary APIs for using critical sections are:


@itemize *

@item 
@ref{53ab,,Py_BEGIN_CRITICAL_SECTION} and @ref{5559,,Py_END_CRITICAL_SECTION} -
For locking a single object

@item 
@ref{5557,,Py_BEGIN_CRITICAL_SECTION2} and @ref{555b,,Py_END_CRITICAL_SECTION2}
- For locking two objects simultaneously
@end itemize

These macros must be used in matching pairs and must appear in the same C
scope, since they establish a new local scope.  These macros are no-ops in
non-free-threaded builds, so they can be safely added to code that needs to
support both build types.

A common use of a critical section would be to lock an object while accessing
an internal attribute of it.  For example, if an extension type has an internal
count field, you could use a critical section while reading or writing that
field:

@example
// read the count, returns new reference to internal count value
PyObject *result;
Py_BEGIN_CRITICAL_SECTION(obj);
result = Py_NewRef(obj->count);
Py_END_CRITICAL_SECTION();
return result;

// write the count, consumes reference from new_count
Py_BEGIN_CRITICAL_SECTION(obj);
obj->count = new_count;
Py_END_CRITICAL_SECTION();
@end example

@node How Critical Sections Work,Deadlock Avoidance,Using Critical Sections,Critical Sections
@anchor{howto/free-threading-extensions how-critical-sections-work}@anchor{587e}
@subsubsection How Critical Sections Work


Unlike traditional locks, critical sections do not guarantee exclusive access
throughout their entire duration. If a thread would block while holding a
critical section (e.g., by acquiring another lock or performing I/O), the
critical section is temporarily suspended—all locks are released—and then
resumed when the blocking operation completes.

This behavior is similar to what happens with the GIL when a thread makes a
blocking call. The key differences are:


@itemize *

@item 
Critical sections operate on a per-object basis rather than globally

@item 
Critical sections follow a stack discipline within each thread (the "begin" and
"end" macros enforce this since they must be paired and within the same scope)

@item 
Critical sections automatically release and reacquire locks around potential
blocking operations
@end itemize

@node Deadlock Avoidance,Important Considerations,How Critical Sections Work,Critical Sections
@anchor{howto/free-threading-extensions deadlock-avoidance}@anchor{587f}
@subsubsection Deadlock Avoidance


Critical sections help avoid deadlocks in two ways:


@enumerate 

@item 
If a thread tries to acquire a lock that's already held by another thread,
it first suspends all of its active critical sections, temporarily releasing
their locks

@item 
When the blocking operation completes, only the top-most critical section is
reacquired first
@end enumerate

This means you cannot rely on nested critical sections to lock multiple objects
at once, as the inner critical section may suspend the outer ones. Instead, use
@ref{5557,,Py_BEGIN_CRITICAL_SECTION2} to lock two objects simultaneously.

Note that the locks described above are only @ref{484,,PyMutex} based locks.
The critical section implementation does not know about or affect other locking
mechanisms that might be in use, like POSIX mutexes.  Also note that while
blocking on any @ref{484,,PyMutex} causes the critical sections to be
suspended, only the mutexes that are part of the critical sections are
released.  If @ref{484,,PyMutex} is used without a critical section, it will
not be released and therefore does not get the same deadlock avoidance.

@node Important Considerations,,Deadlock Avoidance,Critical Sections
@anchor{howto/free-threading-extensions important-considerations}@anchor{5880}
@subsubsection Important Considerations



@itemize *

@item 
Critical sections may temporarily release their locks, allowing other threads
to modify the protected data. Be careful about making assumptions about the
state of the data after operations that might block.

@item 
Because locks can be temporarily released (suspended), entering a critical
section does not guarantee exclusive access to the protected resource
throughout the section's duration. If code within a critical section calls
another function that blocks (e.g., acquires another lock, performs blocking
I/O), all locks held by the thread via critical sections will be released.
This is similar to how the GIL can be released during blocking calls.

@item 
Only the lock(s) associated with the most recently entered (top-most)
critical section are guaranteed to be held at any given time. Locks for
outer, nested critical sections might have been suspended.

@item 
You can lock at most two objects simultaneously with these APIs. If you need
to lock more objects, you'll need to restructure your code.

@item 
While critical sections will not deadlock if you attempt to lock the same
object twice, they are less efficient than purpose-built reentrant locks for
this use case.

@item 
When using @ref{5557,,Py_BEGIN_CRITICAL_SECTION2}, the order of the objects
doesn't affect correctness (the implementation handles deadlock avoidance),
but it's good practice to always lock objects in a consistent order.

@item 
Remember that the critical section macros are primarily for protecting access
to `Python objects' that might be involved in internal CPython operations
susceptible to the deadlock scenarios described above. For protecting purely
internal extension state, standard mutexes or other synchronization
primitives might be more appropriate.
@end itemize

@node Building Extensions for the Free-Threaded Build,,Critical Sections,C API Extension Support for Free Threading
@anchor{howto/free-threading-extensions building-extensions-for-the-free-threaded-build}@anchor{5881}
@subsection Building Extensions for the Free-Threaded Build


C API extensions need to be built specifically for the free-threaded build.
The wheels, shared libraries, and binaries are indicated by a @code{t} suffix.


@itemize *

@item 
pypa/manylinux@footnote{https://github.com/pypa/manylinux} supports the
free-threaded build, with the @code{t} suffix, such as @code{python3.13t}.

@item 
pypa/cibuildwheel@footnote{https://github.com/pypa/cibuildwheel} supports the
free-threaded build on Python 3.13 and 3.14. On Python 3.14, free-threaded
wheels will be built by default. On Python 3.13, you will need to set
CIBW_ENABLE to cpython-freethreading@footnote{https://cibuildwheel.pypa.io/en/stable/options/#enable}.
@end itemize

@menu
* Limited C API and Stable ABI:: 
* Windows: Windows<85>. 

@end menu

@node Limited C API and Stable ABI,Windows<85>,,Building Extensions for the Free-Threaded Build
@anchor{howto/free-threading-extensions limited-c-api-and-stable-abi}@anchor{5882}
@subsubsection Limited C API and Stable ABI


The free-threaded build does not currently support the
@ref{637,,Limited C API} or the stable ABI.  If you use
setuptools@footnote{https://setuptools.pypa.io/en/latest/setuptools.html} to build
your extension and currently set @code{py_limited_api=True} you can use
@code{py_limited_api=not sysconfig.get_config_var("Py_GIL_DISABLED")} to opt out
of the limited API when building with the free-threaded build.

@cartouche
@quotation 注釈 
You will need to build separate wheels specifically for the free-threaded
build.  If you currently use the stable ABI, you can continue to build a
single wheel for multiple non-free-threaded Python versions.
@end quotation
@end cartouche

@node Windows<85>,,Limited C API and Stable ABI,Building Extensions for the Free-Threaded Build
@anchor{howto/free-threading-extensions windows}@anchor{5883}
@subsubsection Windows


Due to a limitation of the official Windows installer, you will need to
manually define @code{Py_GIL_DISABLED=1} when building extensions from source.


@subsubheading 参考


Porting Extension Modules to Support Free-Threading@footnote{https://py-free-threading.github.io/porting/}:
A community-maintained porting guide for extension authors.


@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Remote debugging attachment protocol,Permission requirements,C API Extension Support for Free Threading,Python HOWTO
@anchor{howto/remote_debugging doc}@anchor{5884}@anchor{howto/remote_debugging remote-debugging}@anchor{4927}@anchor{howto/remote_debugging remote-debugging-attachment-protocol}@anchor{5885}@anchor{howto/remote_debugging translation-repo}@anchor{5886}
@section Remote debugging attachment protocol


This protocol enables external tools to attach to a running CPython process and
execute Python code remotely.

Most platforms require elevated privileges to attach to another Python process.

@menu
* Disabling remote debugging:: 

@end menu

@node Disabling remote debugging,,,Remote debugging attachment protocol
@anchor{howto/remote_debugging disabling-remote-debugging}@anchor{5887}
@subsection Disabling remote debugging


To disable remote debugging support, use any of the following:


@itemize *

@item 
Set the 
@geindex PYTHON_DISABLE_REMOTE_DEBUG
@geindex 環境変数; PYTHON_DISABLE_REMOTE_DEBUG
@ref{16e,,PYTHON_DISABLE_REMOTE_DEBUG} environment variable to @code{1} before
starting the interpreter.

@item 
Use the @ref{16f,,-X disable_remote_debug} command-line option.

@item 
Compile Python with the @ref{170,,--without-remote-debug} build flag.
@end itemize

@node Permission requirements,Locating the PyRuntime structure,Remote debugging attachment protocol,Python HOWTO
@anchor{howto/remote_debugging id1}@anchor{5888}@anchor{howto/remote_debugging permission-requirements}@anchor{5889}
@section Permission requirements


Attaching to a running Python process for remote debugging requires elevated
privileges on most platforms. The specific requirements and troubleshooting
steps depend on your operating system:

@subsubheading Linux


The tracer process must have the @code{CAP_SYS_PTRACE} capability or equivalent
privileges. You can only trace processes you own and can signal. Tracing may
fail if the process is already being traced, or if it is running with
set-user-ID or set-group-ID. Security modules like Yama may further restrict
tracing.

To temporarily relax ptrace restrictions (until reboot), run:

@quotation

@code{echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope}
@end quotation

@cartouche
@quotation 注釈 
Disabling @code{ptrace_scope} reduces system hardening and should only be done
in trusted environments.
@end quotation
@end cartouche

If running inside a container, use @code{--cap-add=SYS_PTRACE} or
@code{--privileged}, and run as root if needed.

Try re-running the command with elevated privileges:

@quotation

@code{sudo -E !!}
@end quotation

@subsubheading macOS


To attach to another process, you typically need to run your debugging tool
with elevated privileges. This can be done by using @code{sudo} or running as
root.

Even when attaching to processes you own, macOS may block debugging unless
the debugger is run with root privileges due to system security restrictions.

@subsubheading Windows


To attach to another process, you usually need to run your debugging tool
with administrative privileges. Start the command prompt or terminal as
Administrator.

Some processes may still be inaccessible even with Administrator rights,
unless you have the @code{SeDebugPrivilege} privilege enabled.

To resolve file or folder access issues, adjust the security permissions:

@quotation


@enumerate 

@item 
Right-click the file or folder and select `Properties'.

@item 
Go to the `Security' tab to view users and groups with access.

@item 
Click `Edit' to modify permissions.

@item 
Select your user account.

@item 
In `Permissions', check `Read' or `Full control' as needed.

@item 
Click `Apply', then `OK' to confirm.
@end enumerate
@end quotation

@cartouche
@quotation 注釈 
Ensure you've satisfied all @ref{5889,,Permission requirements} before proceeding.
@end quotation
@end cartouche

This section describes the low-level protocol that enables external tools to
inject and execute a Python script within a running CPython process.

This mechanism forms the basis of the @ref{16d,,sys.remote_exec()} function, which
instructs a remote Python process to execute a @code{.py} file. However, this
section does not document the usage of that function. Instead, it provides a
detailed explanation of the underlying protocol, which takes as input the
@code{pid} of a target Python process and the path to a Python source file to be
executed. This information supports independent reimplementation of the
protocol, regardless of programming language.

@cartouche
@quotation 警告 
The execution of the injected script depends on the interpreter reaching a
safe evaluation point. As a result, execution may be delayed depending on
the runtime state of the target process.
@end quotation
@end cartouche

Once injected, the script is executed by the interpreter within the target
process the next time a safe evaluation point is reached. This approach enables
remote execution capabilities without modifying the behavior or structure of
the running Python application.

Subsequent sections provide a step-by-step description of the protocol,
including techniques for locating interpreter structures in memory, safely
accessing internal fields, and triggering code execution. Platform-specific
variations are noted where applicable, and example implementations are included
to clarify each operation.

@node Locating the PyRuntime structure,Reading _Py_DebugOffsets,Permission requirements,Python HOWTO
@anchor{howto/remote_debugging locating-the-pyruntime-structure}@anchor{588a}
@section Locating the PyRuntime structure


CPython places the @code{PyRuntime} structure in a dedicated binary section to
help external tools find it at runtime. The name and format of this section
vary by platform. For example, @code{.PyRuntime} is used on ELF systems, and
@code{__DATA,__PyRuntime} is used on macOS. Tools can find the offset of this
structure by examining the binary on disk.

The @code{PyRuntime} structure contains CPython’s global interpreter state and
provides access to other internal data, including the list of interpreters,
thread states, and debugger support fields.

To work with a remote Python process, a debugger must first find the memory
address of the @code{PyRuntime} structure in the target process. This address
can’t be hardcoded or calculated from a symbol name, because it depends on
where the operating system loaded the binary.

The method for finding @code{PyRuntime} depends on the platform, but the steps are
the same in general:


@enumerate 

@item 
Find the base address where the Python binary or shared library was loaded
in the target process.

@item 
Use the on-disk binary to locate the offset of the @code{.PyRuntime} section.

@item 
Add the section offset to the base address to compute the address in memory.
@end enumerate

The sections below explain how to do this on each supported platform and
include example code.

@subsubheading Linux (ELF)


To find the @code{PyRuntime} structure on Linux:


@enumerate 

@item 
Read the process’s memory map (for example, @code{/proc/<pid>/maps}) to find
the address where the Python executable or @code{libpython} was loaded.

@item 
Parse the ELF section headers in the binary to get the offset of the
@code{.PyRuntime} section.

@item 
Add that offset to the base address from step 1 to get the memory address of
@code{PyRuntime}.
@end enumerate

The following is an example implementation:

@example
def find_py_runtime_linux(pid: int) -> int:
    # Step 1: Try to find the Python executable in memory
    binary_path, base_address = find_mapped_binary(
        pid, name_contains="python"
    )

    # Step 2: Fallback to shared library if executable is not found
    if binary_path is None:
        binary_path, base_address = find_mapped_binary(
            pid, name_contains="libpython"
        )

    # Step 3: Parse ELF headers to get .PyRuntime section offset
    section_offset = parse_elf_section_offset(
        binary_path, ".PyRuntime"
    )

    # Step 4: Compute PyRuntime address in memory
    return base_address + section_offset
@end example

On Linux systems, there are two main approaches to read memory from another
process. The first is through the @code{/proc} filesystem, specifically by reading from
@code{/proc/[pid]/mem} which provides direct access to the process's memory. This
requires appropriate permissions - either being the same user as the target
process or having root access. The second approach is using the
@code{process_vm_readv()} system call which provides a more efficient way to copy
memory between processes. While ptrace's @code{PTRACE_PEEKTEXT} operation can also be
used to read memory, it is significantly slower as it only reads one word at a
time and requires multiple context switches between the tracer and tracee
processes.

For parsing ELF sections, the process involves reading and interpreting the ELF
file format structures from the binary file on disk. The ELF header contains a
pointer to the section header table. Each section header contains metadata about
a section including its name (stored in a separate string table), offset, and
size. To find a specific section like .PyRuntime, you need to walk through these
headers and match the section name. The section header then provides the offset
where that section exists in the file, which can be used to calculate its
runtime address when the binary is loaded into memory.

You can read more about the ELF file format in the ELF specification@footnote{https://en.wikipedia.org/wiki/Executable_and_Linkable_Format}.

@subsubheading macOS (Mach-O)


To find the @code{PyRuntime} structure on macOS:


@enumerate 

@item 
Call @code{task_for_pid()} to get the @code{mach_port_t} task port for the target
process. This handle is needed to read memory using APIs like
@code{mach_vm_read_overwrite} and @code{mach_vm_region}.

@item 
Scan the memory regions to find the one containing the Python executable or
@code{libpython}.

@item 
Load the binary file from disk and parse the Mach-O headers to find the
section named @code{PyRuntime} in the @code{__DATA} segment.  On macOS, symbol
names are automatically prefixed with an underscore, so the @code{PyRuntime}
symbol appears as @code{_PyRuntime} in the symbol table, but the section name
is not affected.
@end enumerate

The following is an example implementation:

@example
def find_py_runtime_macos(pid: int) -> int:
    # Step 1: Get access to the process's memory
    handle = get_memory_access_handle(pid)

    # Step 2: Try to find the Python executable in memory
    binary_path, base_address = find_mapped_binary(
        handle, name_contains="python"
    )

    # Step 3: Fallback to libpython if the executable is not found
    if binary_path is None:
        binary_path, base_address = find_mapped_binary(
            handle, name_contains="libpython"
        )

    # Step 4: Parse Mach-O headers to get __DATA,__PyRuntime section offset
    section_offset = parse_macho_section_offset(
        binary_path, "__DATA", "__PyRuntime"
    )

    # Step 5: Compute the PyRuntime address in memory
    return base_address + section_offset
@end example

On macOS, accessing another process's memory requires using Mach-O specific APIs
and file formats. The first step is obtaining a @code{task_port} handle via
@code{task_for_pid()}, which provides access to the target process's memory space.
This handle enables memory operations through APIs like
@code{mach_vm_read_overwrite()}.

The process memory can be examined using @code{mach_vm_region()} to scan through the
virtual memory space, while @code{proc_regionfilename()} helps identify which binary
files are loaded at each memory region. When the Python binary or library is
found, its Mach-O headers need to be parsed to locate the @code{PyRuntime} structure.

The Mach-O format organizes code and data into segments and sections. The
@code{PyRuntime} structure lives in a section named @code{__PyRuntime} within the
@code{__DATA} segment. The actual runtime address calculation involves finding the
@code{__TEXT} segment which serves as the binary's base address, then locating the
@code{__DATA} segment containing our target section. The final address is computed by
combining the base address with the appropriate section offsets from the Mach-O
headers.

Note that accessing another process's memory on macOS typically requires
elevated privileges - either root access or special security entitlements
granted to the debugging process.

@subsubheading Windows (PE)


To find the @code{PyRuntime} structure on Windows:


@enumerate 

@item 
Use the ToolHelp API to enumerate all modules loaded in the target process.
This is done using functions such as CreateToolhelp32Snapshot@footnote{https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot},
Module32First@footnote{https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-module32first},
and Module32Next@footnote{https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-module32next}.

@item 
Identify the module corresponding to @code{python.exe} or
@code{python`XY'.dll}, where @code{X} and @code{Y} are the major and minor
version numbers of the Python version, and record its base address.

@item 
Locate the @code{PyRuntim} section. Due to the PE format's 8-character limit
on section names (defined as @code{IMAGE_SIZEOF_SHORT_NAME}), the original
name @code{PyRuntime} is truncated. This section contains the @code{PyRuntime}
structure.

@item 
Retrieve the section’s relative virtual address (RVA) and add it to the base
address of the module.
@end enumerate

The following is an example implementation:

@example
def find_py_runtime_windows(pid: int) -> int:
    # Step 1: Try to find the Python executable in memory
    binary_path, base_address = find_loaded_module(
        pid, name_contains="python"
    )

    # Step 2: Fallback to shared pythonXY.dll if the executable is not
    # found
    if binary_path is None:
        binary_path, base_address = find_loaded_module(
            pid, name_contains="python3"
        )

    # Step 3: Parse PE section headers to get the RVA of the PyRuntime
    # section. The section name appears as "PyRuntim" due to the
    # 8-character limit defined by the PE format (IMAGE_SIZEOF_SHORT_NAME).
    section_rva = parse_pe_section_offset(binary_path, "PyRuntim")

    # Step 4: Compute PyRuntime address in memory
    return base_address + section_rva
@end example

On Windows, accessing another process's memory requires using the Windows API
functions like @code{CreateToolhelp32Snapshot()} and @code{Module32First()/Module32Next()}
to enumerate loaded modules. The @code{OpenProcess()} function provides a handle to
access the target process's memory space, enabling memory operations through
@code{ReadProcessMemory()}.

The process memory can be examined by enumerating loaded modules to find the
Python binary or DLL. When found, its PE headers need to be parsed to locate the
@code{PyRuntime} structure.

The PE format organizes code and data into sections. The @code{PyRuntime} structure
lives in a section named "PyRuntim" (truncated from "PyRuntime" due to PE's
8-character name limit). The actual runtime address calculation involves finding
the module's base address from the module entry, then locating our target
section in the PE headers. The final address is computed by combining the base
address with the section's virtual address from the PE section headers.

Note that accessing another process's memory on Windows typically requires
appropriate privileges - either administrative access or the @code{SeDebugPrivilege}
privilege granted to the debugging process.

@node Reading _Py_DebugOffsets,Locating the interpreter and thread state,Locating the PyRuntime structure,Python HOWTO
@anchor{howto/remote_debugging reading-py-debugoffsets}@anchor{588b}
@section Reading _Py_DebugOffsets


Once the address of the @code{PyRuntime} structure has been determined, the next
step is to read the @code{_Py_DebugOffsets} structure located at the beginning of
the @code{PyRuntime} block.

This structure provides version-specific field offsets that are needed to
safely read interpreter and thread state memory. These offsets vary between
CPython versions and must be checked before use to ensure they are compatible.

To read and check the debug offsets, follow these steps:


@enumerate 

@item 
Read memory from the target process starting at the @code{PyRuntime} address,
covering the same number of bytes as the @code{_Py_DebugOffsets} structure.
This structure is located at the very start of the @code{PyRuntime} memory
block. Its layout is defined in CPython’s internal headers and stays the
same within a given minor version, but may change in major versions.

@item 
Check that the structure contains valid data:


@itemize -

@item 
The @code{cookie} field must match the expected debug marker.

@item 
The @code{version} field must match the version of the Python interpreter
used by the debugger.

@item 
If either the debugger or the target process is using a pre-release
version (for example, an alpha, beta, or release candidate), the versions
must match exactly.

@item 
The @code{free_threaded} field must have the same value in both the debugger
and the target process.
@end itemize

@item 
If the structure is valid, the offsets it contains can be used to locate
fields in memory. If any check fails, the debugger should stop the operation
to avoid reading memory in the wrong format.
@end enumerate

The following is an example implementation that reads and checks
@code{_Py_DebugOffsets}:

@example
def read_debug_offsets(pid: int, py_runtime_addr: int) -> DebugOffsets:
    # Step 1: Read memory from the target process at the PyRuntime address
    data = read_process_memory(
        pid, address=py_runtime_addr, size=DEBUG_OFFSETS_SIZE
    )

    # Step 2: Deserialize the raw bytes into a _Py_DebugOffsets structure
    debug_offsets = parse_debug_offsets(data)

    # Step 3: Validate the contents of the structure
    if debug_offsets.cookie != EXPECTED_COOKIE:
        raise RuntimeError("Invalid or missing debug cookie")
    if debug_offsets.version != LOCAL_PYTHON_VERSION:
        raise RuntimeError(
            "Mismatch between caller and target Python versions"
        )
    if debug_offsets.free_threaded != LOCAL_FREE_THREADED:
        raise RuntimeError("Mismatch in free-threaded configuration")

    return debug_offsets
@end example

@cartouche
@quotation 警告 
`Process suspension recommended'

To avoid race conditions and ensure memory consistency, it is strongly
recommended that the target process be suspended before performing any
operations that read or write internal interpreter state. The Python runtime
may concurrently mutate interpreter data structures—such as creating or
destroying threads—during normal execution. This can result in invalid
memory reads or writes.

A debugger may suspend execution by attaching to the process with @code{ptrace}
or by sending a @code{SIGSTOP} signal. Execution should only be resumed after
debugger-side memory operations are complete.

@cartouche
@quotation 注釈 
Some tools, such as profilers or sampling-based debuggers, may operate on
a running process without suspension. In such cases, tools must be
explicitly designed to handle partially updated or inconsistent memory.
For most debugger implementations, suspending the process remains the
safest and most robust approach.
@end quotation
@end cartouche
@end quotation
@end cartouche

@node Locating the interpreter and thread state,Writing control information,Reading _Py_DebugOffsets,Python HOWTO
@anchor{howto/remote_debugging locating-the-interpreter-and-thread-state}@anchor{588c}
@section Locating the interpreter and thread state


Before code can be injected and executed in a remote Python process, the
debugger must choose a thread in which to schedule execution. This is necessary
because the control fields used to perform remote code injection are located in
the @code{_PyRemoteDebuggerSupport} structure, which is embedded in a
@code{PyThreadState} object. These fields are modified by the debugger to request
execution of injected scripts.

The @code{PyThreadState} structure represents a thread running inside a Python
interpreter.  It maintains the thread’s evaluation context and contains the
fields required for debugger coordination.  Locating a valid @code{PyThreadState}
is therefore a key prerequisite for triggering execution remotely.

A thread is typically selected based on its role or ID. In most cases, the main
thread is used, but some tools may target a specific thread by its native
thread ID. Once the target thread is chosen, the debugger must locate both the
interpreter and the associated thread state structures in memory.

The relevant internal structures are defined as follows:


@itemize -

@item 
@code{PyInterpreterState} represents an isolated Python interpreter instance.
Each interpreter maintains its own set of imported modules, built-in state,
and thread state list. Although most Python applications use a single
interpreter, CPython supports multiple interpreters in the same process.

@item 
@code{PyThreadState} represents a thread running within an interpreter. It
contains execution state and the control fields used by the debugger.
@end itemize

To locate a thread:


@enumerate 

@item 
Use the offset @code{runtime_state.interpreters_head} to obtain the address of
the first interpreter in the @code{PyRuntime} structure. This is the entry point
to the linked list of active interpreters.

@item 
Use the offset @code{interpreter_state.threads_main} to access the main thread
state associated with the selected interpreter. This is typically the most
reliable thread to target.

@item 
Optionally, use the offset @code{interpreter_state.threads_head} to iterate
through the linked list of all thread states. Each @code{PyThreadState}
structure contains a @code{native_thread_id} field, which may be compared to
a target thread ID to find a specific thread.

@item 
Once a valid @code{PyThreadState} has been found, its address can be used in
later steps of the protocol, such as writing debugger control fields and
scheduling execution.
@end enumerate

The following is an example implementation that locates the main thread state:

@example
def find_main_thread_state(
    pid: int, py_runtime_addr: int, debug_offsets: DebugOffsets,
) -> int:
    # Step 1: Read interpreters_head from PyRuntime
    interp_head_ptr = (
        py_runtime_addr + debug_offsets.runtime_state.interpreters_head
    )
    interp_addr = read_pointer(pid, interp_head_ptr)
    if interp_addr == 0:
        raise RuntimeError("No interpreter found in the target process")

    # Step 2: Read the threads_main pointer from the interpreter
    threads_main_ptr = (
        interp_addr + debug_offsets.interpreter_state.threads_main
    )
    thread_state_addr = read_pointer(pid, threads_main_ptr)
    if thread_state_addr == 0:
        raise RuntimeError("Main thread state is not available")

    return thread_state_addr
@end example

The following example demonstrates how to locate a thread by its native thread
ID:

@example
def find_thread_by_id(
    pid: int,
    interp_addr: int,
    debug_offsets: DebugOffsets,
    target_tid: int,
) -> int:
    # Start at threads_head and walk the linked list
    thread_ptr = read_pointer(
        pid,
        interp_addr + debug_offsets.interpreter_state.threads_head
    )

    while thread_ptr:
        native_tid_ptr = (
            thread_ptr + debug_offsets.thread_state.native_thread_id
        )
        native_tid = read_int(pid, native_tid_ptr)
        if native_tid == target_tid:
            return thread_ptr
        thread_ptr = read_pointer(
            pid,
            thread_ptr + debug_offsets.thread_state.next
        )

    raise RuntimeError("Thread with the given ID was not found")
@end example

Once a valid thread state has been located, the debugger can proceed with
modifying its control fields and scheduling execution, as described in the next
section.

@node Writing control information,Summary,Locating the interpreter and thread state,Python HOWTO
@anchor{howto/remote_debugging writing-control-information}@anchor{588d}
@section Writing control information


Once a valid @code{PyThreadState} structure has been identified, the debugger may
modify control fields within it to schedule the execution of a specified Python
script. These control fields are checked periodically by the interpreter, and
when set correctly, they trigger the execution of remote code at a safe point
in the evaluation loop.

Each @code{PyThreadState} contains a @code{_PyRemoteDebuggerSupport} structure used
for communication between the debugger and the interpreter. The locations of
its fields are defined by the @code{_Py_DebugOffsets} structure and include the
following:


@itemize -

@item 
@code{debugger_script_path}: A fixed-size buffer that holds the full path to a
Python source file (@code{.py}).  This file must be accessible and readable by
the target process when execution is triggered.

@item 
@code{debugger_pending_call}: An integer flag. Setting this to @code{1} tells the
interpreter that a script is ready to be executed.

@item 
@code{eval_breaker}: A field checked by the interpreter during execution.
Setting bit 5 (@code{_PY_EVAL_PLEASE_STOP_BIT}, value @code{1U << 5}) in this
field causes the interpreter to pause and check for debugger activity.
@end itemize

To complete the injection, the debugger must perform the following steps:


@enumerate 

@item 
Write the full script path into the @code{debugger_script_path} buffer.

@item 
Set @code{debugger_pending_call} to @code{1}.

@item 
Read the current value of @code{eval_breaker}, set bit 5
(@code{_PY_EVAL_PLEASE_STOP_BIT}), and write the updated value back. This
signals the interpreter to check for debugger activity.
@end enumerate

The following is an example implementation:

@example
def inject_script(
    pid: int,
    thread_state_addr: int,
    debug_offsets: DebugOffsets,
    script_path: str
) -> None:
    # Compute the base offset of _PyRemoteDebuggerSupport
    support_base = (
        thread_state_addr +
        debug_offsets.debugger_support.remote_debugger_support
    )

    # Step 1: Write the script path into debugger_script_path
    script_path_ptr = (
        support_base +
        debug_offsets.debugger_support.debugger_script_path
    )
    write_string(pid, script_path_ptr, script_path)

    # Step 2: Set debugger_pending_call to 1
    pending_ptr = (
        support_base +
        debug_offsets.debugger_support.debugger_pending_call
    )
    write_int(pid, pending_ptr, 1)

    # Step 3: Set _PY_EVAL_PLEASE_STOP_BIT (bit 5, value 1 << 5) in
    # eval_breaker
    eval_breaker_ptr = (
        thread_state_addr +
        debug_offsets.debugger_support.eval_breaker
    )
    breaker = read_int(pid, eval_breaker_ptr)
    breaker |= (1 << 5)
    write_int(pid, eval_breaker_ptr, breaker)
@end example

Once these fields are set, the debugger may resume the process (if it was
suspended).  The interpreter will process the request at the next safe
evaluation point, load the script from disk, and execute it.

It is the responsibility of the debugger to ensure that the script file remains
present and accessible to the target process during execution.

@cartouche
@quotation 注釈 
Script execution is asynchronous. The script file cannot be deleted
immediately after injection. The debugger should wait until the injected
script has produced an observable effect before removing the file.
This effect depends on what the script is designed to do. For example,
a debugger might wait until the remote process connects back to a socket
before removing the script. Once such an effect is observed, it is safe to
assume the file is no longer needed.
@end quotation
@end cartouche

@node Summary,,Writing control information,Python HOWTO
@anchor{howto/remote_debugging summary}@anchor{588e}
@section Summary


To inject and execute a Python script in a remote process:


@enumerate 

@item 
Locate the @code{PyRuntime} structure in the target process’s memory.

@item 
Read and validate the @code{_Py_DebugOffsets} structure at the beginning of
@code{PyRuntime}.

@item 
Use the offsets to locate a valid @code{PyThreadState}.

@item 
Write the path to a Python script into @code{debugger_script_path}.

@item 
Set the @code{debugger_pending_call} flag to @code{1}.

@item 
Set @code{_PY_EVAL_PLEASE_STOP_BIT} in the @code{eval_breaker} field.

@item 
Resume the process (if suspended). The script will execute at the next safe
evaluation point.
@end enumerate

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

General:


@itemize *

@item 
@ref{37b7,,A Conceptual Overview of asyncio}

@item 
@ref{9d9,,Annotations Best Practices}

@item 
@ref{336c,,Argparse チュートリアル}

@item 
@ref{1706,,デスクリプタ ガイド}

@item 
@ref{56f0,,列挙型 HOWTO}

@item 
@ref{5722,,関数型プログラミング HOWTO}

@item 
@ref{41c8,,ipaddressモジュールの紹介}

@item 
@ref{5741,,Logging HOWTO}

@item 
@ref{1410,,Logging クックブック}

@item 
@ref{2762,,正規表現 HOWTO}

@item 
@ref{13f3,,ソートのテクニック}

@item 
@ref{14bc,,Unicode HOWTO}

@item 
@ref{3f8a,,urllib パッケージを使ってインターネット上のリソースを取得するには}
@end itemize

Advanced development:


@itemize *

@item 
@ref{345f,,Python で Curses プログラミング}

@item 
@ref{2619,,Python support for free threading}

@item 
@ref{585d,,C API Extension Support for Free Threading}

@item 
@ref{166,,拡張モジュールを分離する}

@item 
@ref{16c3,,The Python 2.3 Method Resolution Order}

@item 
@ref{39a1,,ソケットプログラミング HOWTO}

@item 
@ref{584e,,timer file descriptor HOWTO}

@item 
@ref{14f8,,Python 3 への拡張モジュール移植}
@end itemize

Debugging and profiling:


@itemize *

@item 
@ref{56e1,,Debugging C API extensions and CPython Internals with GDB}

@item 
@ref{e66,,DTrace と SystemTap で CPython を測定する}

@item 
@ref{4ae,,Python support for the Linux perf profiler}

@item 
@ref{4927,,Remote debugging attachment protocol}
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Python よくある質問,非推奨<14>,Python HOWTO,Top
@anchor{faq/index doc}@anchor{588f}@anchor{faq/index faq-index}@anchor{20f5}@anchor{faq/index python-frequently-asked-questions}@anchor{5890}@anchor{faq/index translation-repo}@anchor{5891}
@chapter Python よくある質問


@menu
* 一般 Python FAQ:: 
* プログラミング FAQ:: 
* デザインと歴史 FAQ:: 
* ライブラリと拡張 FAQ:: 
* 拡張と埋め込み FAQ:: 
* Windows 上の Python FAQ:: 
* グラフィックユーザインターフェース FAQ:: 
* "なぜ Python が私のコンピュータにインストールされているのですか？" FAQ:: 

@end menu

@node 一般 Python FAQ,プログラミング FAQ,,Python よくある質問
@anchor{faq/general doc}@anchor{5892}@anchor{faq/general general-python-faq}@anchor{5893}
@section 一般 Python FAQ



@menu
* 一般情報:: 
* 現実世界での Python:: 

@end menu

@node 一般情報,現実世界での Python,,一般 Python FAQ
@anchor{faq/general general-information}@anchor{5894}
@subsection 一般情報


@menu
* Python とは何ですか？:: 
* Python Software Foundation とは何ですか？:: 
* Python を使うのに著作権の制限はありますか？:: 
* そもそも Python は何故創られたのですか？:: 
* Python は何をするのに向いていますか？:: 
* Python のバージョン番号の仕組みはどうなっているのですか？:: 
* Python のソースのコピーはどこで手に入りますか？:: 
* Python のドキュメントはどこで手に入りますか？:: 
* プログラミングをしたことがないのですが、Python のチュートリアルはありますか？:: 
* Python のためのニュースグループやメーリングリストはありますか？:: 
* Python のベータテスト版はどこで手に入りますか？:: 
* Python のバグ報告やパッチを上げるにはどうしたら良いですか？:: 
* Python について発行された記事を何か参照できますか？:: 
* Python の本はありますか？:: 
* www.python.org は世界のどこにあるのですか？: www python org は世界のどこにあるのですか？. 
* なぜ Python という名前なのですか？:: 
* 『空飛ぶモンティ・パイソン』を好きでなくてはいけませんか？:: 

@end menu

@node Python とは何ですか？,Python Software Foundation とは何ですか？,,一般情報
@anchor{faq/general what-is-python}@anchor{5895}
@subsubsection Python とは何ですか？


Python は、インタプリタ形式の、対話的な、オブジェクト指向プログラミング言語です。この言語には、モジュール、例外、動的な型付け、超高水準の動的なデータ型、およびクラスが取り入れられています。
Pythonは、オブジェクト指向プログラミングを越えて、手続き型プログラミングや関数型プログラミングなど複数のプログラミングパラダイムをサポートしています。
Python は驚くべきパワーと非常に分かりやすい文法を持ち合わせています。そして、多くのシステムコールやライブラリへだけでなく、様々なウィンドウシステムへのインターフェースがあり、C や C++ で拡張することもできます。また、プログラム可能なインターフェースが必要なアプリケーションのための拡張言語としても利用できます。最後に、Python はポータブルです。Linux や macOS を含む多くの Unix の派生システムで動き、Windows でも動きます。

さらに知りたければ、 @ref{1fbc,,Python チュートリアル} から始めましょう。他にも、 Beginner's Guide to Python@footnote{https://wiki.python.org/moin/BeginnersGuide} から、Python 学習のための入門用チュートリアルやリソースを参照できます。

@node Python Software Foundation とは何ですか？,Python を使うのに著作権の制限はありますか？,Python とは何ですか？,一般情報
@anchor{faq/general what-is-the-python-software-foundation}@anchor{5896}
@subsubsection Python Software Foundation とは何ですか？


Python Software Foundation は、Python バージョン 2.1 以降の著作権を保持する独立の非営利組織です。PSF の任務は、Python プログラミング言語に関するオープンソース技術を進め、Python の使用を広めることです。PSF のホームページが @indicateurl{https://www.python.org/psf/} にあります。

PSF への寄付は米国で免税されています。Python を利用して役立ったと感じたら、the PSF donation page@footnote{https://www.python.org/psf/donations/} で貢献をお願いします。

@node Python を使うのに著作権の制限はありますか？,そもそも Python は何故創られたのですか？,Python Software Foundation とは何ですか？,一般情報
@anchor{faq/general are-there-copyright-restrictions-on-the-use-of-python}@anchor{5897}
@subsubsection Python を使うのに著作権の制限はありますか？


あなたが作成する Python に関するドキュメントのすべてに著作権を残し、それらの著作権を表示する限り、ソースコードをどのように扱ってもかまいません。この著作権規則を尊重する限り、商用に Python を利用しても、ソースあるいはバイナリ形式で(変更の有無にかかわらず) Python のコピーを販売しても、Python が何らかの形で組み込まれた製品を販売してかまいません。もちろん、Python のあらゆる商業用途についても同様です。

PSF License のより詳しい説明と全文へのリンクは the license page@footnote{https://docs.python.org/3/license.html} を参照してください。

Python のロゴは商標登録されていて、使用に許可が必要な場合があります。詳しい情報は the Trademark Usage Policy@footnote{https://www.python.org/psf/trademarks/} を参照してください。

@node そもそも Python は何故創られたのですか？,Python は何をするのに向いていますか？,Python を使うのに著作権の制限はありますか？,一般情報
@anchor{faq/general why-was-python-created-in-the-first-place}@anchor{5898}
@subsubsection そもそも Python は何故創られたのですか？


Guido van Rossum によると、すべての始まりについての `非常に' 簡潔な概要は以下のとおりです:

@quotation

私は CWI の ABC グループでインタプリタ言語を実装する幅広い経験をしていて、そこで共に働くことで言語設計に関して大いに学びました。これは文のグループ化にインデントを使用することや超高水準のデータ型の包含など、(詳細は Python とは全く異なりますが) Python の多くの特徴のもととなっています。

私は ABC 言語に対して多くの不満を持っていましたが、同時に特徴の多くが好きでもありました。ABC 言語 (やその実装)を拡張して私の不満を解消することは不可能でした (実際、拡張性の欠如は大きな問題だったのです)。私は Modula-2+ を使用することでいくらかの経験を積み、Modula-3 のデザイナーと話して Modula-3 のレポートを読みました。Modula-3 は例外処理に使う構文や語義、その他いくつかの Python の特徴の起源です。

私は CWI で Amoeba 分散オペレーティングシステムのグループで働いていました。Amoeba のシステムコールインターフェースには Bourne シェルからアクセスしにくかったので、C プログラムや Bourne シェルスクリプトを書くよりも良いシステム管理の方法が必要でした。Amoeba のエラー処理の経験から、プログラミング言語の機能としての例外の重要さを強く意識するようになりました。

ABC のような構文と Amoeba のようなシステムコールを合わせ持ったスクリプト言語が必要だろうと思いつきました。Amoeba 専用の言語を書くのは愚かであるだろうと気づき、一般に拡張できるような言語を求めることに決めました。

1989 年のクリスマス休暇の間、自由な時間がたくさんできたので、その言語を実際に作ってみることにしました。翌年の間、勤務時間以外はほとんどその開発に費やし、Python は Amoeba プロジェクトのなかで成果を重ね、同僚からのフィードバックは私の開発を大いに加速させてくれました。

1991 年 2 月、1 年間と少しの開発を経て、USENET に投稿することにしました。それは @code{Misc/HISTORY} ファイルに残っています。
@end quotation

@node Python は何をするのに向いていますか？,Python のバージョン番号の仕組みはどうなっているのですか？,そもそも Python は何故創られたのですか？,一般情報
@anchor{faq/general what-is-python-good-for}@anchor{5899}
@subsubsection Python は何をするのに向いていますか？


Python は、多岐にわたる問題に適用できる高水準な汎用プログラム言語です。

この言語は、文字列処理(正規表現、Unicode、ファイル間の差分の計算)、インターネットプロトコル(HTTP、FTP、SMTP、XML-RPC、POP、IMAP)、ソフトウェアエンジニアリング(Python コードのユニットテスト、ロギング、プロファイリング、解析)、オペレーティングシステムインターフェース(システムコール、ファイルシステム、 TCP/IP ソケット) のような領域をカバーする大規模な標準ライブラリから成り立っています。何ができるかを知るには @ref{149,,Python 標準ライブラリ} の一覧を参照してください。また、様々なサードパーティの拡張も使えます。 the Python Package Index@footnote{https://pypi.org} から興味のあるパッケージを探してみましょう。

@node Python のバージョン番号の仕組みはどうなっているのですか？,Python のソースのコピーはどこで手に入りますか？,Python は何をするのに向いていますか？,一般情報
@anchor{faq/general faq-version-numbering-scheme}@anchor{589a}@anchor{faq/general how-does-the-python-version-numbering-scheme-work}@anchor{589b}
@subsubsection Python のバージョン番号の仕組みはどうなっているのですか？


Python のバージョン番号は "A.B.C" または "A.B" が付けられます :


@itemize *

@item 
`A' はメジャーバージョン番号です -- 言語に本当に大きな変更があった場合に増やされます。

@item 
`B' はマイナーバージョン番号です -- 驚きの少ない変更があった場合に増やされます。

@item 
`C' はマイクロバージョン番号です -- バグフィックスリリースごとに増やされます。
@end itemize

すべてのリリースがバグフィックスリリースであるというわけではありません。フィーチャーリリースへの準備段階では、一連の開発リリースが作られ、アルファ版、ベータ版、またはリリース候補と名付けられます。アルファ版はインターフェースが確定されないうちにリリースされる早期リリースで、２つのアルファリリース間でインターフェースが変わるかもしれません。ベータ版はもっと安定していて、現存のインターフェースは保存されますが新しいモジュールが追加されるかもしれません。リリース候補は固まったもので、致命的なバグを直すのでなければ変更されません。

アルファ、ベータとリリース候補のバージョンは、追加の接尾辞を持ちます:


@itemize *

@item 
アルファバージョンの接尾辞は、ある小さな数 `N' に対して "aN "となります。

@item 
ベータバージョンの接尾辞は、ある小さな数 `N' に対して "bN" となります。

@item 
リリース候補バージョンの接尾辞は、ある小さな数 `N' に対して "rcN" となります。
@end itemize

つまり、 `2.0aN' と付けられたバージョンはすべて `2.0bN' に先立ち、 `2.0bN' は `2.0rcN' に先立ち、そして `これら' は 2.0 に先立ちます。

また、"2.2+" のように "+" 接尾語が付いたバージョン番号もあります。これは未発表のバージョンで、 CPython 開発リポジトリから直接ビルドされています。実際、最後のマイナーリリースが行われた後、バージョンは "2.4a0" のように "a0" がつく次のマイナーバージョンになります。

開発サイクルの詳細は Developer's Guide@footnote{https://devguide.python.org/developer-workflow/development-cycle/} を、 Python の後方互換性ポリシーについては 
@geindex Python Enhancement Proposals; PEP 387
PEP 387@footnote{https://peps.python.org/pep-0387/} を参照してください。 ドキュメント @ref{49c,,sys.version} 、 @ref{4921,,sys.hexversion} 、 @ref{8af,,sys.version_info} も参照してください。

@node Python のソースのコピーはどこで手に入りますか？,Python のドキュメントはどこで手に入りますか？,Python のバージョン番号の仕組みはどうなっているのですか？,一般情報
@anchor{faq/general how-do-i-obtain-a-copy-of-the-python-source}@anchor{589c}
@subsubsection Python のソースのコピーはどこで手に入りますか？


最新の Python ソースは python.org (@indicateurl{https://www.python.org/downloads/}) からいつでも手に入れることができます。最新の開発版ソースは @indicateurl{https://github.com/python/cpython/}  にアクセスして手に入れることができます。

ソースは gzip された tar ファイルで配布され、完全な C のソース、Sphinx によりフォーマットされたドキュメント、Python ライブラリモジュール、サンプルプログラム、そしていくつかの役立つ配布自由なソフトウェアを含んでいます。このソースはほとんどの UNIX プラットフォームでそのままコンパイルして動かせます。

ソースコードの入手とコンパイルについて、より詳しい情報は Getting Started section of the Python Developer's Guide@footnote{https://devguide.python.org/setup/} を参照してください。

@node Python のドキュメントはどこで手に入りますか？,プログラミングをしたことがないのですが、Python のチュートリアルはありますか？,Python のソースのコピーはどこで手に入りますか？,一般情報
@anchor{faq/general how-do-i-get-documentation-on-python}@anchor{589d}
@subsubsection Python のドキュメントはどこで手に入りますか？


現行の安定版 Python の標準ドキュメントは @indicateurl{https://docs.python.org/3/} から利用できます。  また、 EPUB 、プレーンテキスト、ダウンロード可能な HTML 版も @indicateurl{https://docs.python.org/3/download.html} から利用できます。

このドキュメントは reStructuredText で書かれ、the Sphinx documentation tool@footnote{https://www.sphinx-doc.org/} で構成されました。このドキュメントに使われた reStructuredText のソースは Python のソース配布に含まれます。

@node プログラミングをしたことがないのですが、Python のチュートリアルはありますか？,Python のためのニュースグループやメーリングリストはありますか？,Python のドキュメントはどこで手に入りますか？,一般情報
@anchor{faq/general i-ve-never-programmed-before-is-there-a-python-tutorial}@anchor{589e}
@subsubsection プログラミングをしたことがないのですが、Python のチュートリアルはありますか？


膨大な量の役に立つチュートリアルや書籍があります。標準のドキュメントには @ref{1fbc,,Python チュートリアル} などがあります。

Python プログラム初心者のための情報のチュートリアルのリストは the Beginner's Guide@footnote{https://wiki.python.org/moin/BeginnersGuide} を参照してください。

@node Python のためのニュースグループやメーリングリストはありますか？,Python のベータテスト版はどこで手に入りますか？,プログラミングをしたことがないのですが、Python のチュートリアルはありますか？,一般情報
@anchor{faq/general is-there-a-newsgroup-or-mailing-list-devoted-to-python}@anchor{589f}
@subsubsection Python のためのニュースグループやメーリングリストはありますか？


ニュースグループ @code{comp.lang.python} やメーリングリスト python-list@footnote{https://mail.python.org/mailman/listinfo/python-list} があります。ニュースグループとメーリングリストは互いに接続されていて、ニュースを購読すればメーリングリストに参加する必要はありません。 @code{comp.lang.python} は一日に数百のポスティングを受ける高いトラフィックで、USENET 読者は多くの場合、このボリュームに応えることができます。

新しいソフトウェアリリースとイベントの告知は comp.lang.python.announce で見つけられます。これは一日に 5 ポスティング程度を受ける低トラフィックの手頃なメーリングリストです。the python-announce mailing list@footnote{https://mail.python.org/mailman3/lists/python-announce-list.python.org/} から利用可能です。

その他のメーリングリストやニュースグループについての詳しい情報は @indicateurl{https://www.python.org/community/lists/} にあります。

@node Python のベータテスト版はどこで手に入りますか？,Python のバグ報告やパッチを上げるにはどうしたら良いですか？,Python のためのニュースグループやメーリングリストはありますか？,一般情報
@anchor{faq/general how-do-i-get-a-beta-test-version-of-python}@anchor{58a0}
@subsubsection Python のベータテスト版はどこで手に入りますか？


アルファ/ベータリリースは @indicateurl{https://www.python.org/downloads/} で手に入ります。リリースはすべて comp.lang.python や comp.lang.python.announce のニュースグループと Python ホームページ @indicateurl{https://www.python.org/} で告知され、RSS ニュースフィードが利用できます。

Git から開発版を手に入れることもできます。詳細は The Python Developer's guide@footnote{https://devguide.python.org/} を参照してください。

@node Python のバグ報告やパッチを上げるにはどうしたら良いですか？,Python について発行された記事を何か参照できますか？,Python のベータテスト版はどこで手に入りますか？,一般情報
@anchor{faq/general how-do-i-submit-bug-reports-and-patches-for-python}@anchor{58a1}
@subsubsection Python のバグ報告やパッチを上げるにはどうしたら良いですか？


バグの報告やパッチの提出には、issue tracker @indicateurl{https://github.com/python/CPython/issues} をご利用ください。

Python 開発の工程について、詳しくは the Python Developer's Guide@footnote{https://devguide.python.org/} を参照してください。

@node Python について発行された記事を何か参照できますか？,Python の本はありますか？,Python のバグ報告やパッチを上げるにはどうしたら良いですか？,一般情報
@anchor{faq/general are-there-any-published-articles-about-python-that-i-can-reference}@anchor{58a2}
@subsubsection Python について発行された記事を何か参照できますか？


Python に関するあなたの愛読書を引用するのが一番でしょう。

Python に関する 一番初めの記事@footnote{https://ir.cwi.nl/pub/18204} はとても古く、1991年に書かれています。

@quotation

Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers
Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4
(December 1991), Amsterdam, pp 283--303.
@end quotation

@node Python の本はありますか？,www python org は世界のどこにあるのですか？,Python について発行された記事を何か参照できますか？,一般情報
@anchor{faq/general are-there-any-books-on-python}@anchor{58a3}
@subsubsection Python の本はありますか？


はい、たくさんあり、そのほとんどは現在も出版されています。リストは python.org wiki @indicateurl{https://wiki.python.org/moin/PythonBooks} にあります。

また、オンライン書店で "Python" で検索し、Monty Python をフィルタで除外してもいいです (または、"Python" と "言語" で検索してください)。

@node www python org は世界のどこにあるのですか？,なぜ Python という名前なのですか？,Python の本はありますか？,一般情報
@anchor{faq/general where-in-the-world-is-www-python-org-located}@anchor{58a4}
@subsubsection www.python.org は世界のどこにあるのですか？


Pythonプロジェクトのインフラは世界中にあり、Pythonインフラストラクチャチームによって管理されています。詳細は こちら@footnote{https://infra.psf.io}.

@node なぜ Python という名前なのですか？,『空飛ぶモンティ・パイソン』を好きでなくてはいけませんか？,www python org は世界のどこにあるのですか？,一般情報
@anchor{faq/general why-is-it-called-python}@anchor{58a5}
@subsubsection なぜ Python という名前なのですか？


Python の開発が始まった頃、Guido van Rossum は 1970 年代に始まった BBC のコメディシリーズ "Monty Python's Flying Circus"@footnote{https://en.wikipedia.org/wiki/Monty_Python} の台本を読んでいました。Van Rossum は、短くて、ユニークで、少しミステリアスな名前が欲しかったので、この言語の名前を Python と呼ぶことにしたのです。

@node 『空飛ぶモンティ・パイソン』を好きでなくてはいけませんか？,,なぜ Python という名前なのですか？,一般情報
@anchor{faq/general do-i-have-to-like-monty-python-s-flying-circus}@anchor{58a6}
@subsubsection 『空飛ぶモンティ・パイソン』を好きでなくてはいけませんか？


いいえ。でも、好きになってくれるといいな。: ）

@node 現実世界での Python,,一般情報,一般 Python FAQ
@anchor{faq/general python-in-the-real-world}@anchor{58a7}
@subsection 現実世界での Python


@menu
* Python はどれくらい安定していますか？:: 
* どれくらいの人が Python を使っていますか？:: 
* Python で行われた大きなプロジェクトはありますか？:: 
* 将来 Python にどのような新しい開発が期待されますか？:: 
* Python の互換性を無くすような提案をしてもいいのですか？:: 
* Python は初心者プログラマに向いている言語ですか？:: 

@end menu

@node Python はどれくらい安定していますか？,どれくらいの人が Python を使っていますか？,,現実世界での Python
@anchor{faq/general how-stable-is-python}@anchor{58a8}
@subsubsection Python はどれくらい安定していますか？


とても安定しています。1991 年以来新しい安定リリースはおよそ 6 から 18 ヶ月毎に出されていて、このペースが続きそうです。バージョン3.9の時点では、Pythonは12ヶ月に一度のペースで新しいフィーチャーリリースを行っています (
@geindex Python Enhancement Proposals; PEP 602
PEP 602@footnote{https://peps.python.org/pep-0602/}) 。

開発者が旧バージョンのバグフィックスリリースを公開するので、既存リリースの安定性は徐々に向上していきます。バグフィックスリリースは、バージョン番号の 3 番目の要素によって示され(例: 3.5.3、3.6.2)、安定性のために管理されています。バグフィックスリリースには既知の問題への修正だけが含まれ、一連のバグフィックスリリースを通じて同じインターフェースが保たれることが保証されているのです。

最新の安定版は Python download page@footnote{https://www.python.org/downloads/} で見つけられます。 Python 3.x が推奨されるバージョンで、最も広く利用されているライブラリでサポートされています。 Python 2.x 
@geindex Python Enhancement Proposals; PEP 373
は もはや保守されていません@footnote{https://peps.python.org/pep-0373/} 。

@node どれくらいの人が Python を使っていますか？,Python で行われた大きなプロジェクトはありますか？,Python はどれくらい安定していますか？,現実世界での Python
@anchor{faq/general how-many-people-are-using-python}@anchor{58a9}
@subsubsection どれくらいの人が Python を使っていますか？


正確な人数を調べるのは難しいですが、おそらく何百万人ものユーザーがいるでしょう。

Python は自由にダウンロード可能なので、売上高がなく、多数のサイトから利用でき、多くの Linux ディストーションに同梱されているので、ダウンロード統計から全体の状況を知ることはできません。

comp.lang.python ニュースグループはとても活発ですが、すべての Python ユーザーが投稿するわけではなく、読みすらしない人もいます。

@node Python で行われた大きなプロジェクトはありますか？,将来 Python にどのような新しい開発が期待されますか？,どれくらいの人が Python を使っていますか？,現実世界での Python
@anchor{faq/general have-any-significant-projects-been-done-in-python}@anchor{58aa}
@subsubsection Python で行われた大きなプロジェクトはありますか？


Python を利用しているプロジェクトのリストは @indicateurl{https://www.python.org/about/success} を参照してください。past Python conferences@footnote{https://www.python.org/community/workshops/} から議事録を参照すると、多くの会社や組織の貢献がわかるでしょう。

注目されている Python のプロジェクトは the Mailman mailing list manager@footnote{https://www.list.org} や the Zope application server@footnote{https://www.zope.dev} などです。Red Hat@footnote{https://www.redhat.com} をはじめとするいくつかの Linux ディストーションのインストーラやシステムアドミニストレーションソフトウェアは、一部や全部が Python で書かれています。内部で Python を利用している企業には、Google、Yahoo、Lucasfilm Ltd. などがあります。

@node 将来 Python にどのような新しい開発が期待されますか？,Python の互換性を無くすような提案をしてもいいのですか？,Python で行われた大きなプロジェクトはありますか？,現実世界での Python
@anchor{faq/general what-new-developments-are-expected-for-python-in-the-future}@anchor{58ab}
@subsubsection 将来 Python にどのような新しい開発が期待されますか？


Python Enhancement Proposals (PEP) @indicateurl{https://peps.python.org/}  を参照してください。PEP は Python に提案された新機能について書かれた設計書で、簡潔な技術仕様と原理が提供されています。"Python X.Y Release Schedule" (X.Y はまだリリースされていないバージョン) を探してください。

新しい開発については the python-dev mailing list@footnote{https://mail.python.org/mailman3/lists/python-dev.python.org/} で議論されています。

@node Python の互換性を無くすような提案をしてもいいのですか？,Python は初心者プログラマに向いている言語ですか？,将来 Python にどのような新しい開発が期待されますか？,現実世界での Python
@anchor{faq/general is-it-reasonable-to-propose-incompatible-changes-to-python}@anchor{58ac}
@subsubsection Python の互換性を無くすような提案をしてもいいのですか？


一般的には、してはいけません。世界中にすでに何百万行もの Python コードがあるので、既存のプログラムのどんなに僅かな部分でも無効にしてしまうような言語仕様の変更も認められてはなりません。コンバートするプログラムが出来てさえ、すべてのドキュメントをアップデートしなければならないという問題があります。 Python に関する多くの本が出版されているので、それらを一発で不適切にするようなことはしたくないです。

仕様を変えなければならないのなら、緩やかなアップグレード計画が組まれなくてはなりません。 
@geindex Python Enhancement Proposals; PEP 5
PEP 5@footnote{https://peps.python.org/pep-0005/} で、ユーザーの受ける分裂を最小限にしながら後方互換性のない変更を行うために従うべき手順について説明しています。

@node Python は初心者プログラマに向いている言語ですか？,,Python の互換性を無くすような提案をしてもいいのですか？,現実世界での Python
@anchor{faq/general is-python-a-good-language-for-beginning-programmers}@anchor{58ad}
@subsubsection Python は初心者プログラマに向いている言語ですか？


はい。

未だにプログラミング初学者にとって一般的なのは、Pascal、C、C++ のサブセット、 Java など、手続き型の静的型付けの言語です。生徒にとっては、第一の言語として Python を学ぶのが役に立つでしょう。Python には非常に簡潔で一貫した構文と大きな標準ライブラリがあります。そして一番重要なことに、初心者プログラミングのコースで Python を学ぶことで、生徒は問題の分析やデータ型の設計など、重要なプログラミングスキルに集中することができるのです。 Python なら、生徒はループや手続きなどの基本概念をすぐに取り入れられます。最初の課程でいきなりユーザ定義のオブジェクトを操ることさえできるでしょう。

プログラミングをしたことがない初心者にとって、静的型付け言語を使うのは不自然に思われます。習得すべき内容はより複雑になり、学習のペースが遅くなってしまいます。生徒は、コンピュータのように思考し、問題を分析し、一貫したインターフェースを設計して、データをカプセル化することを学ぶことになります。長期的に見れば静的型付け言語を学ぶことは重要ですが、それが最初のプログラミングの授業で学ぶべき最高の話題とは限りません。

Python の良いところは他にもたくさんあります。Python には、Java のように大きな標準ライブラリがあり、生徒が何かを `する' 段階で非常に早くプログラミングプロジェクトに参加できるようになります。宿題は標準の四則演算機や平均を求めるプログラムに限定されません。標準ライブラリを使用することで、生徒はプログラミングの原理を学びながら現実的なアプリケーションに取り組む満足感を得ることができます。また、標準ライブラリの使用からコードの再利用を学ぶことができます。 PyGame などのサードパーティモジュールもまた手が届く範囲を広げるのに役立ちます。

Python のインタラクティブインタプリタによって、プログラミングをしながら、言語機能を確認することができます。別のウィンドウでプログラムのソースに入っている間、ウィンドウでインタプリタを起動させたままにしておくことができます。リストのメソッドを思い出せないときは、例えばこのようにできます:

@example
>>> L = []
>>> dir(L)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>> [d for d in dir(L) if '__' not in d]
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> help(L.append)
Help on built-in function append:

append(...)
    L.append(object) -> None -- append object to end

>>> L.append(1)
>>> L
[1]
@end example

インタプリタがあれば、プログラミングをしている間にドキュメントは生徒のそばを離れません。

Python のための良い IDE もあります。IDLE は Python で Tkinter を使って書かれたクロスプラットフォーム IDE です。Emacs には、ユーザにとって幸運なことに、素晴らしい Python モードがあります。これらすべてのプログラミング環境から、シンタックスハイライト、オートインデント、コーディング中のインタラクティブインタプリタへのアクセスが使えます。the Python wiki@footnote{https://wiki.python.org/moin/PythonEditors} から Python 編集環境の一覧を参照してください。

Python の教育における利用についての議論がしたいなら、the edu-sig mailing list@footnote{https://www.python.org/community/sigs/current/edu-sig} に参加するとよいでしょう。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node プログラミング FAQ,デザインと歴史 FAQ,一般 Python FAQ,Python よくある質問
@anchor{faq/programming doc}@anchor{2449}@anchor{faq/programming programming-faq}@anchor{58ae}@anchor{faq/programming translation-repo}@anchor{58af}
@section プログラミング FAQ



@menu
* 一般的な質問:: 
* コア言語:: 
* 数と文字列:: 
* 性能: 性能<4>. 
* シーケンス(タプル/リスト): シーケンス タプル/リスト. 
* オブジェクト:: 
* モジュール: モジュール<5>. 

@end menu

@node 一般的な質問,コア言語,,プログラミング FAQ
@anchor{faq/programming general-questions}@anchor{58b0}
@subsection 一般的な質問


@menu
* ブレークポイントやシングルステップ実行などを備えたソースコードレベルデバッガはありますか？:: 
* バグの発見や静的解析に役立つツールはありますか？:: 
* どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？:: 
* Python プログラムのためのコーディングスタンダードやスタイルガイドはありますか？:: 

@end menu

@node ブレークポイントやシングルステップ実行などを備えたソースコードレベルデバッガはありますか？,バグの発見や静的解析に役立つツールはありますか？,,一般的な質問
@anchor{faq/programming is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc}@anchor{58b1}
@subsubsection ブレークポイントやシングルステップ実行などを備えたソースコードレベルデバッガはありますか？


はい。

Python 用のデバッガについては次に解説してあり、組み込みの @ref{271,,breakpoint()} 関数でそれらのデバッガに処理を移せます。

pdb モジュールは簡素にして十分な Python のコンソールモードデバッガです。これは Python の標準ライブラリに含まれているもので、 @ref{aa,,ライブラリリファレンスマニュアルにドキュメントがあります} 。 pdb のコードを手本にして自分用のデバッガを書くこともできます。

Python に同梱されている統合開発環境の IDLE は通常の Python の配布形態の一部 (普通は  Tools/scripts/idle3@footnote{https://github.com/python/cpython/blob/main/Tools/scripts/idle3} から利用可能) であり、グラフィカルなデバッガを含んでいます。

PythonWin は、pdb をベースとした GUI デバッガを含む Python IDE です。Pythonwin デバッガは、ブレークポイントの色付けや非 PythonWin プログラムのデバッグなどの素敵な機能をたくさん持っています。PythonWin は  pywin32@footnote{https://github.com/mhammond/pywin32} プロジェクトの一部、あるいは ActivePython@footnote{https://www.activestate.com/products/python/} ディストリビューションの一部として利用可能です。

Eric@footnote{https://eric-ide.python-projects.org/} は PyQt や Scintilla editing component をもとにした IDE です。

trepan3k@footnote{https://github.com/rocky/python3-trepan/} は gdbライクなデバッガです。

Visual Studio Code@footnote{https://code.visualstudio.com/} はバージョン管理ソフトと一緒になったデバッグツールを備えた IDE です

商業のグラフィカルデバッガ付き Python IDE もあります。例えば:


@itemize *

@item 
Wing IDE@footnote{https://wingware.com/}

@item 
Komodo IDE@footnote{https://www.activestate.com/products/komodo-ide/}

@item 
PyCharm@footnote{https://www.jetbrains.com/pycharm/}
@end itemize

@node バグの発見や静的解析に役立つツールはありますか？,どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？,ブレークポイントやシングルステップ実行などを備えたソースコードレベルデバッガはありますか？,一般的な質問
@anchor{faq/programming are-there-tools-to-help-find-bugs-or-perform-static-analysis}@anchor{58b2}
@subsubsection バグの発見や静的解析に役立つツールはありますか？


はい。

Pylint@footnote{https://pylint.pycqa.org/en/latest/index.html} と Pyflakes@footnote{https://github.com/PyCQA/pyflakes} は、バグの早期発見に役立つ基本的なチェックを行います。

Mypy@footnote{https://mypy-lang.org/}, Pyre@footnote{https://pyre-check.org/}, Pytype@footnote{https://github.com/google/pytype} などの静的型チェッカーは、 Python ソースコードにある型ヒントをチェックできます。

@node どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？,Python プログラムのためのコーディングスタンダードやスタイルガイドはありますか？,バグの発見や静的解析に役立つツールはありますか？,一般的な質問
@anchor{faq/programming faq-create-standalone-binary}@anchor{58b3}@anchor{faq/programming how-can-i-create-a-stand-alone-binary-from-a-python-script}@anchor{58b4}
@subsubsection どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？


ユーザがダウンロードでき、Python ディストリビューションをインストールせずに実行できるようなスタンドアロンプログラムだけでいいなら、Python を C コードにコンパイルできなくても構いません。プログラムに対して必要なモジュールを選び、そのモジュールを Python バイナリに束縛して一つの実行可能ファイルにまとめる多くのツールがあります。

一つは freeze ツールで、Python ソースツリーに Tools/freeze@footnote{https://github.com/python/cpython/tree/main/Tools/freeze} として含まれています。これは Python バイトコードを C 配列に変換します。すべてのモジュールを新しいプログラムに埋め込む C コンパイラで、そのプログラムは Python モジュールにリンクされます。

これはあなたのソースの (両方の形式の) import 文を再帰的にスキャンし、import されたモジュールを標準の Python パスと (組み込みモジュールのある) ソースディレクトリから探します。そして Python で書かれたモジュールのバイトコードを C コード (marshal モジュールでコードオブジェクトに変換できる配列) に変換し、実際にそのプログラム内で使われている組み込みモジュールだけが含まれたカスタムメイドの設定ファイルを作成します。そして生成された C コードをコンパイルして Python インタプリタの残りとリンクし、元のスクリプトと全く同じように動作する自己完結的なバイナリを形成します。

以下のパッケージはコンソールやGUIの実行ファイル作成に役立ちます。


@itemize *

@item 
Nuitka@footnote{https://nuitka.net/} (Cross-platform)

@item 
PyInstaller@footnote{https://pyinstaller.org/} (Cross-platform)

@item 
PyOxidizer@footnote{https://pyoxidizer.readthedocs.io/en/stable/} (Cross-platform)

@item 
cx_Freeze@footnote{https://marcelotduarte.github.io/cx_Freeze/} (Cross-platform)

@item 
py2app@footnote{https://github.com/ronaldoussoren/py2app} (macOS only)

@item 
py2exe@footnote{https://www.py2exe.org/} (Windows only)
@end itemize

@node Python プログラムのためのコーディングスタンダードやスタイルガイドはありますか？,,どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？,一般的な質問
@anchor{faq/programming are-there-coding-standards-or-a-style-guide-for-python-programs}@anchor{58b5}
@subsubsection Python プログラムのためのコーディングスタンダードやスタイルガイドはありますか？


はい。標準ライブラリモジュールに求められるコーディングスタイルは 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} として文書化されています。

@node コア言語,数と文字列,一般的な質問,プログラミング FAQ
@anchor{faq/programming core-language}@anchor{58b6}
@subsection コア言語


@menu
* なぜ変数に値があるのに UnboundLocalError が出るのですか？:: 
* Python のローカルとグローバル変数のルールは何ですか？:: 
* ループの中で異なる値で定義されたラムダ式が、同じ値を返すのはなぜですか？:: 
* グローバル変数をモジュール間で共有するにはどうしたらいいですか？:: 
* モジュールで import を使う際の「ベストプラクティス」は何ですか？:: 
* なぜオブジェクト間でデフォルト値が共有されるのですか？:: 
* オプションパラメータやキーワードパラメータを関数から関数へ渡すにはどうしたらいいですか？:: 
* 実引数と仮引数の違いは何ですか?:: 
* なぜ list 'y' を変更すると list 'x' も変更されるのですか?:: 
* 出力引数のある関数 (参照渡し) はどのように書きますか？: 出力引数のある関数 参照渡し はどのように書きますか？. 
* Python で高次関数はどのようにつくりますか？:: 
* Python のオブジェクトはどのようにコピーしますか？:: 
* オブジェクトのメソッドや属性はどのように見つけますか？:: 
* コードはどのようにオブジェクトの名前を見つけるのですか？:: 
* カンマ演算子はなぜ優先されるのですか？:: 
* C の "?;" 三項演算子と等価なものはありますか？: C の "? " 三項演算子と等価なものはありますか？. 
* Python で解し難いワンライナーを書くことはできますか？:: 
* 関数の引数リストにあるスラッシュ (/) は何を意味しますか？: 関数の引数リストにあるスラッシュ / は何を意味しますか？. 

@end menu

@node なぜ変数に値があるのに UnboundLocalError が出るのですか？,Python のローカルとグローバル変数のルールは何ですか？,,コア言語
@anchor{faq/programming faq-unboundlocalerror}@anchor{242b}@anchor{faq/programming why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value}@anchor{58b7}
@subsubsection なぜ変数に値があるのに UnboundLocalError が出るのですか？


もともと動いていたコードが、関数の本体のどこかに代入文を加えるという変更をしたら @ref{174f,,UnboundLocalError} を出すのには驚くかもしれません。

このコード:

@example
>>> x = 10
>>> def bar():
...     print(x)
...
>>> bar()
10
@end example

は動きますが、このコード:

@example
>>> x = 10
>>> def foo():
...     print(x)
...     x += 1
@end example

は @code{UnboundLocalError} になります:

@example
>>> foo()
Traceback (most recent call last):
  ...
UnboundLocalError: local variable 'x' referenced before assignment
@end example

これは、あるスコープの中で変数に代入を行うとき、その変数はそのスコープに対してローカルになり、外のスコープにある同じ名前の変数を隠すからです。foo の最後の文が @code{x} に新しい値を代入しているので、コンパイラはこれをローカル変数であると認識します。その結果、先の @code{print(x)} が初期化されていないローカル変数を表示しようとして結果はエラーとなります。

上の例では、グローバルであると宣言することで外のスコープにアクセスできます:

@example
>>> x = 10
>>> def foobar():
...     global x
...     print(x)
...     x += 1
...
>>> foobar()
10
@end example

この明示的な宣言は (表面的には似ているクラスとインスタンス変数の例とは違って) あなたは実際は他のスコープの変数の値を変えようとしているのだ、ということを知らせるのに必要です:

@example
>>> print(x)
11
@end example

同様のことを、ネストされたスコープで @ref{14bf,,nonlocal} 予約語を使うことでもできます:

@example
>>> def foo():
...    x = 10
...    def bar():
...        nonlocal x
...        print(x)
...        x += 1
...    bar()
...    print(x)
...
>>> foo()
10
11
@end example

@node Python のローカルとグローバル変数のルールは何ですか？,ループの中で異なる値で定義されたラムダ式が、同じ値を返すのはなぜですか？,なぜ変数に値があるのに UnboundLocalError が出るのですか？,コア言語
@anchor{faq/programming what-are-the-rules-for-local-and-global-variables-in-python}@anchor{58b8}
@subsubsection Python のローカルとグローバル変数のルールは何ですか？


Python では、関数内で参照されるだけの変数は暗黙的にグローバルとなります。
関数の本体のどこかで値が変数に代入されたなら、それは明示的にグローバルであると宣言されない限り、ローカルであるとみなされます。

最初はちょっと驚くでしょうが、少し考えると納得できます。一方では、代入された変数に @ref{4ac,,global} を要求することで、意図しない副作用を防げます。他方では、グローバルな参照の度に @code{global} が要求されてしまうと、 @code{global} を使ってばかりになってしまいます。ビルトイン関数やインポートされたモジュールの内容を参照するたびにグローバル宣言をしなければならないのです。その乱雑さは副作用を特定するための @code{global} 宣言の便利さよりも重大です。

@node ループの中で異なる値で定義されたラムダ式が、同じ値を返すのはなぜですか？,グローバル変数をモジュール間で共有するにはどうしたらいいですか？,Python のローカルとグローバル変数のルールは何ですか？,コア言語
@anchor{faq/programming why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result}@anchor{58b9}
@subsubsection ループの中で異なる値で定義されたラムダ式が、同じ値を返すのはなぜですか？


for ループを使って、少しずつ異なるラムダを定義 (もしくは簡単な関数) するとします。例えば:

@example
>>> squares = []
>>> for x in range(5):
...     squares.append(lambda: x**2)
@end example

これで @code{x**2} を計算する 5 つのラムダのリストが得られます。それらを呼び出したとき、それぞれ @code{0}、@code{1}、@code{4}、@code{9}、@code{16} を返すと予想するかもしれません。しかし実際にやってみると、全て @code{16} が返ってくるのを目にするでしょう:

@example
>>> squares[2]()
16
>>> squares[4]()
16
@end example

これは、@code{x} がラムダにとってのローカル変数ではなく外側のスコープで定義されていて、ラムダが定義されたときでなく呼び出されたときにアクセスされるために起こります。ループが終わった時点では @code{x} は @code{4} であり、従って、全ての関数は @code{4**2} つまり @code{16} を返します。このことは @code{x} の値を変えてみることで検証でき、ラムダの返り値がどのように変わるのか観察できます:

@example
>>> x = 8
>>> squares[2]()
64
@end example

これを避けるためには、グローバルの @code{x} の値に依存しないために、ラムダにとってのローカル変数に値を保存する必要があります:

@example
>>> squares = []
>>> for x in range(5):
...     squares.append(lambda n=x: n**2)
@end example

ここで、@code{n=x} は新しいラムダにとってのローカル変数 @code{n} を作成し、ラムダが定義されるときに計算されるので、ループのその時点での @code{x} と同じ値を持っています。これは、1 つ目のラムダでは @code{n} の値は @code{0} になり、2 つ目では @code{1}、3 つ目では @code{2} 以下同様、となることを意味します。従って、それぞれのラムダは今や正しい値を返すようになりました:

@example
>>> squares[2]()
4
>>> squares[4]()
16
@end example

この動作はラムダに特有なものではなく、通常の関数にも適用されることに注意してください。

@node グローバル変数をモジュール間で共有するにはどうしたらいいですか？,モジュールで import を使う際の「ベストプラクティス」は何ですか？,ループの中で異なる値で定義されたラムダ式が、同じ値を返すのはなぜですか？,コア言語
@anchor{faq/programming how-do-i-share-global-variables-across-modules}@anchor{58ba}
@subsubsection グローバル変数をモジュール間で共有するにはどうしたらいいですか？


一つのプログラムのモジュール間で情報を共有する正準な方法は、特別なモジュール (しばしば config や cfg と呼ばれる) を作ることです。単に設定モジュールをアプリケーションのすべてのモジュールにインポートしてください。このモジュールはグローバルな名前として使えます。それぞれのモジュールのただ一つのインスタンスがあるので、設定モジュールオブジェクトに対するいかなる変更も全体に反映されます。例えば:

config.py:

@example
x = 0   # Default value of the 'x' configuration setting
@end example

mod.py:

@example
import config
config.x = 1
@end example

main.py:

@example
import config
import mod
print(config.x)
@end example

なお、同じ理由から、モジュールを使うということは、シングルトンデザインパターンを実装することの基礎でもあります。

@node モジュールで import を使う際の「ベストプラクティス」は何ですか？,なぜオブジェクト間でデフォルト値が共有されるのですか？,グローバル変数をモジュール間で共有するにはどうしたらいいですか？,コア言語
@anchor{faq/programming what-are-the-best-practices-for-using-import-in-a-module}@anchor{58bb}
@subsubsection モジュールで import を使う際の「ベストプラクティス」は何ですか？


一般的に @code{from modulename import *} を使ってはいけません。そのようにするとインポータの名前空間は汚染され、linter が未定義の名前を発見することが難しくなります。

モジュールはファイルの先頭でインポートしてください。これによってコードが必要とする他のモジュールが明確になり、モジュール名がスコープに含まれるかどうかに迷わなくなります。行に一つのインポートにすると、モジュールのインポートの追加と削除が容易になりますが、行に複数のインポートにすると画面の領域が少なく済みます。

次の手順でモジュールをインポートするのが、良い習慣になります:


@enumerate 

@item 
標準ライブラリモジュール -- 例 @ref{df,,sys}、@ref{a5,,os}、@ref{7,,argparse}、@ref{be,,re}

@item 
サードパーティのライブラリモジュール (Python の site-packages ディレクトリにあるもの) -- 例 @code{dateutil}、@code{requests}、@code{PIL.Image}、など

@item 
自前で開発したモジュール
@end enumerate

循環参照の問題を避けるために、インポートを関数やクラスに移すことが必要なときもあります。Gordon McMillan によれば:

@quotation

循環参照は両方のモジュールが "import <module>" 形式のインポートを使っていれば大丈夫です。二つ目のモジュールが最初のモジュールから名前を確保しようとして ("from module import name")、そのインポートがトップレベルにあると駄目です。最初のモジュールが二つ目のモジュールをインポートするのに忙しくて、最初のモジュールの名前が利用可能になっていないからです。
@end quotation

この状況では、二つ目のモジュールが一つの関数の中でのみ使われているならば、そのインポートは簡単に関数の中に移せます。インポートが呼ばれたとき、最初のモジュールは初期化を完了していて、二つ目のモジュールは自分のインポートをできます。

プラットフォーム依存のモジュールがあるときには、インポートをトップレベルの外に動かすことも必要です。この場合、ファイルの先頭ではすべてのモジュールをインポートすることさえできないかもしれません。この場合は、対応するプラットフォームに合わせたコードで正しいモジュールをインポートすることを選ぶと良いです。

循環参照の問題を避けたりモジュールの初期化にかかる時間を減らしたりしたいなら、単にインポートを関数定義の中などのローカルなスコープに移してください。この手法は多くのインポートがプログラムがどのように実行されるかに依存しなくてよいときに特に有効です。ある関数の中でのみモジュールが使われるのなら、インポートをその関数の中に移すことを考えてもいいでしょう。なお、モジュールを読み込む最初の回はモジュールの初期化の時間のために高価になりえますが、複数回目にモジュールを読み込むのは事実上無料、辞書探索の数回のコストだけで済みます。モジュール名がスコープから外れてさえ、そのモジュールはおそらく @ref{17e6,,sys.modules} から利用できるでしょう。

@node なぜオブジェクト間でデフォルト値が共有されるのですか？,オプションパラメータやキーワードパラメータを関数から関数へ渡すにはどうしたらいいですか？,モジュールで import を使う際の「ベストプラクティス」は何ですか？,コア言語
@anchor{faq/programming why-are-default-values-shared-between-objects}@anchor{58bc}
@subsubsection なぜオブジェクト間でデフォルト値が共有されるのですか？


この種のバグがよく初心者プログラマに噛み付きます。この関数を考えてみてください:

@example
def foo(mydict=@{@}):  # Danger: shared reference to one dict for all calls
    ... compute something ...
    mydict[key] = value
    return mydict
@end example

初めてこの関数を呼び出した時、@code{mydict} には一つの要素があります。二回目には、@code{foo()} が実行されるときに @code{mydict} には初めから一つの要素をすでに持っているので、@code{mydict} には二つの要素があります。

関数の呼び出しによって、デフォルトの値に対する新しいオブジェクトが作られるのだと予想しがちです。実はそうなりません。デフォルト値は、関数が定義されたときに一度だけ生成されます。この例の辞書のように、そのオブジェクトが変更されたとき、その後の関数の呼び出しは変更後のオブジェクトを参照します。

定義の時に、数、文字列、タプル、@code{None} など、イミュータブルなオブジェクトを使うと変更される危険がありません。辞書、リスト、クラスインスタンスなどのミュータブルなオブジェクトは混乱のもとです。

この性質から、ミュータブルなオブジェクトをデフォルト値として使わないプログラミング手法がいいです。代わりに、@code{None} をデフォルト値に使い、そのパラメタが @code{None} である時にだけ、関数の内部で新しいリスト/辞書/その他をつくるようにしてください。例えば、こう書かずに:

@example
def foo(mydict=@{@}):
    ...
@end example

代わりに:

@example
def foo(mydict=None):
    if mydict is None:
        mydict = @{@}  # create a new dict for local namespace
@end example

この性質が便利なこともあります。時間のかかる計算を行う関数があるときに使われる一般的な技法は、関数が呼び出されるごとにパラメタと結果の値をキャッシュし、再び同じ値が要求されたらキャッシュされた値を返すというものです。これは "memoizing" と呼ばれ、このように実装されます:

@example
# Callers can only provide two parameters and optionally pass _cache by keyword
def expensive(arg1, arg2, *, _cache=@{@}):
    if (arg1, arg2) in _cache:
        return _cache[(arg1, arg2)]

    # Calculate the value
    result = ... expensive computation ...
    _cache[(arg1, arg2)] = result           # Store result in the cache
    return result
@end example

デフォルト値の代わりに、辞書を含むグローバル変数も使えます。これは好みの問題です。

@node オプションパラメータやキーワードパラメータを関数から関数へ渡すにはどうしたらいいですか？,実引数と仮引数の違いは何ですか?,なぜオブジェクト間でデフォルト値が共有されるのですか？,コア言語
@anchor{faq/programming how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another}@anchor{58bd}
@subsubsection オプションパラメータやキーワードパラメータを関数から関数へ渡すにはどうしたらいいですか？


関数のパラメータリストに引数を @code{*} と @code{**} 指定子 (specifier) で集めてください。そうすれば、位置引数をタプルとして、キーワード引数を辞書として得られます。これで、他の関数を呼び出すときに @code{*} と @code{**} を使ってそれらの引数を渡せます:

@example
def f(x, *args, **kwargs):
    ...
    kwargs['width'] = '14.3c'
    ...
    g(x, *args, **kwargs)
@end example

@geindex 引数 (argument);difference from parameter
@geindex parameter;difference from argument

@node 実引数と仮引数の違いは何ですか?,なぜ list 'y' を変更すると list 'x' も変更されるのですか?,オプションパラメータやキーワードパラメータを関数から関数へ渡すにはどうしたらいいですか？,コア言語
@anchor{faq/programming faq-argument-vs-parameter}@anchor{58be}@anchor{faq/programming what-is-the-difference-between-arguments-and-parameters}@anchor{58bf}
@subsubsection 実引数と仮引数の違いは何ですか?


@ref{234b,,仮引数 (parameter)} は関数定義に表れる名前で定義されるのに対し、 @ref{67b,,実引数 (argument)} は関数を呼び出すときに実際に渡す値のことです。仮引数は関数が受け取ることの出来る @ref{234b,,実引数の型} を定義します。例えば、以下のような関数定義があったとして:

@example
def func(foo, bar=None, **kwargs):
    pass
@end example

`foo'、`bar'、`kwargs' は @code{func} の仮引数です。一方、@code{func} を呼び出すときには、例えば:

@example
func(42, bar=314, extra=somevar)
@end example

@code{42}、@code{314}、@code{somevar} という値は実引数です。

@node なぜ list 'y' を変更すると list 'x' も変更されるのですか?,出力引数のある関数 参照渡し はどのように書きますか？,実引数と仮引数の違いは何ですか?,コア言語
@anchor{faq/programming why-did-changing-list-y-also-change-list-x}@anchor{58c0}
@subsubsection なぜ list 'y' を変更すると list 'x' も変更されるのですか?


次のようなコードを書いたとします:

@example
>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]
@end example

どうして @code{y} への要素の追加が @code{x} も変更してしまうのか疑問に思うかもしれません。

このような結果になる2つの要因があります:


@enumerate 

@item 
変数とは、単にオブジェクトを参照するための名前に過ぎません。 @code{y = x} とすることは、リストのコピーを作りません -- それは @code{x} が参照するのと同じオブジェクトを参照する新しい変数 @code{y} を作ります。つまり、あるのは一つのオブジェクト(この場合リスト)だけであって、 @code{x} と @code{y} の両方がそれを参照しているのです。

@item 
リストは @ref{15ba,,mutable} です。内容を変更出来る、ということです。
@end enumerate

After the call to @ref{23d6,,append()}, the content of the mutable object has
changed from @code{[]} to @code{[10]}.  Since both the variables refer to the same
object, using either name accesses the modified value @code{[10]}.

代わりに @code{x} にイミュータブルを代入すると:

@example
>>> x = 5  # ints are immutable
>>> y = x
>>> x = x + 1  # 5 can't be mutated, we are creating a new object here
>>> x
6
>>> y
5
@end example

この場合ご覧の通り @code{x} と @code{y} はまったく同じではありませんね。これは整数が @ref{15b9,,immutable} だからで、 @code{x = x + 1} は整数の @code{5} の値を変更しているのではありません; 代わりに新しいオブジェクト(整数 @code{6})を作って @code{x} に代入しています (つまり @code{x} が参照するオブジェクトが変わります)。この代入の後では私たちは 2 つのオブジェクト(整数の @code{6} と @code{5})を持っていて、2 つの変数はそれらを参照しています(@code{x} はいまや @code{6} を参照していますが @code{y} は @code{5} を参照したままです)。

ある演算 (たとえば @code{y.append(10)}, @code{y.sort()}) がオブジェクトを変更する一方で、外見上は似た演算 (たとえば @code{y = y + [10]}, @ref{dc7,,sorted(y)}) は新しいオブジェクトを作ります。Python では一般に (そして標準ライブラリの全てのケースで)、このような 2 つのタイプの演算にまつわる混乱を避けるために、オブジェクトを変更するメソッドは @code{None} を返します。ですからもしあなたが誤って @code{y} の複製の並び替えをするつもりで @code{y.sort()} と書いた場合に結果手にするのは @code{None} でしょうから、あなたのプログラムは簡単に診断出来るエラーを起こすでしょう。

しかしながら、同じ操作が型ごとに異なる振る舞いをする演算の種類が一つあります: 累算代入演算です。例えば @code{+=} はリストを変更しますが、タプルや整数は変更しません(@code{a_list += [1, 2, 3]} は @code{a_list.extend([1, 2, 3])} と同じ意味で、そして @code{a_list} を変更しますが、 @code{some_tuple += (1, 2, 3)} と @code{some_int += 1} は新しいオブジェクトを作ります)。

言い換えると:


@itemize *

@item 
ミュータブルなオブジェクト(@ref{24d,,list}, @ref{183,,dict}, @ref{184,,set}, 等)を持っている場合、私たちはその内容を変更するある種の演算を使うことが出来、それを参照している全ての変数はその変化を見ることになるでしょう。

@item 
イミュータブルなオブジェクト(@ref{169,,str}, @ref{19b,,int}, @ref{614,,tuple}, 等)を持っている場合、それを参照している全ての変数は同じ値を参照しているでしょうが、持っている値を新しい値に変換する演算はいつでも新しいオブジェクトを返します。
@end itemize

2つの変数が同じオブジェクトを参照しているかどうかが知りたければ、 @ref{34c,,is} 演算子や組み込み関数 @ref{163c,,id()} が使えます。

@node 出力引数のある関数 参照渡し はどのように書きますか？,Python で高次関数はどのようにつくりますか？,なぜ list 'y' を変更すると list 'x' も変更されるのですか?,コア言語
@anchor{faq/programming how-do-i-write-a-function-with-output-parameters-call-by-reference}@anchor{58c1}
@subsubsection 出力引数のある関数 (参照渡し) はどのように書きますか？


前提として、Python では引数は代入によって渡されます。代入はオブジェクトへの参照を作るだけなので、呼び出し元と呼び出し先にある引数名の間にエイリアスはありませんし、参照渡しそれ自体はありません。望む効果を得るためには幾つかの方法があります。


@enumerate 

@item 
結果のタプルを返すことによって:

@example
>>> def func1(a, b):
...     a = 'new-value'        # a and b are local names
...     b = b + 1              # assigned to new objects
...     return a, b            # return new values
...
>>> x, y = 'old-value', 99
>>> func1(x, y)
('new-value', 100)
@end example

これはたいてい一番明確な方法です。

@item 
グローバル変数を使って。これはスレッドセーフでないので、推奨されません。

@item 
ミュータブルな (インプレースに変更可能な) オブジェクトを渡すことによって:

@example
>>> def func2(a):
...     a[0] = 'new-value'     # 'a' references a mutable list
...     a[1] = a[1] + 1        # changes a shared object
...
>>> args = ['old-value', 99]
>>> func2(args)
>>> args
['new-value', 100]
@end example

@item 
変更される辞書に渡すことによって:

@example
>>> def func3(args):
...     args['a'] = 'new-value'     # args is a mutable dictionary
...     args['b'] = args['b'] + 1   # change it in-place
...
>>> args = @{'a': 'old-value', 'b': 99@}
>>> func3(args)
>>> args
@{'a': 'new-value', 'b': 100@}
@end example

@item 
または、クラスインスタンスに値を同梱することによって:

@example
>>> class Namespace:
...     def __init__(self, /, **args):
...         for key, value in args.items():
...             setattr(self, key, value)
...
>>> def func4(args):
...     args.a = 'new-value'        # args is a mutable Namespace
...     args.b = args.b + 1         # change object in-place
...
>>> args = Namespace(a='old-value', b=99)
>>> func4(args)
>>> vars(args)
@{'a': 'new-value', 'b': 100@}
@end example

このような複雑なことをする理由はめったに無いでしょう。
@end enumerate

一番の選択は、複数の結果を含むタプルを返すことです。

@node Python で高次関数はどのようにつくりますか？,Python のオブジェクトはどのようにコピーしますか？,出力引数のある関数 参照渡し はどのように書きますか？,コア言語
@anchor{faq/programming how-do-you-make-a-higher-order-function-in-python}@anchor{58c2}
@subsubsection Python で高次関数はどのようにつくりますか？


二つの方法があります: ネストされたスコープを使う方法と、呼び出し可能オブジェクトを使う方法です。例えば、@code{a*x+b} の値を計算する @code{f(x)} 関数を返す @code{linear(a,b)} を定義したいとします。ネストされたスコープを使うと:

@example
def linear(a, b):
    def result(x):
        return a * x + b
    return result
@end example

また、呼び出し可能オブジェクトを使うと:

@example
class linear:

    def __init__(self, a, b):
        self.a, self.b = a, b

    def __call__(self, x):
        return self.a * x + self.b
@end example

どちらの場合でも、

@example
taxes = linear(0.3, 2)
@end example

とすれば、@code{taxes(10e6) == 0.3 * 10e6 + 2} となるような呼び出し可能オブジェクトを得られます。

呼び出し可能オブジェクトを使う方法は、少し遅くなり、わずかにコードが長くなるという短所があります。ですが、継承を使って呼び出し可能オブジェクト同士で記号を共有することもできます:

@example
class exponential(linear):
    # __init__ inherited
    def __call__(self, x):
        return self.a * (x ** self.b)
@end example

オブジェクトはいくつかのメソッドに状態をカプセル化できます:

@example
class counter:

    value = 0

    def set(self, x):
        self.value = x

    def up(self):
        self.value = self.value + 1

    def down(self):
        self.value = self.value - 1

count = counter()
inc, dec, reset = count.up, count.down, count.set
@end example

ここで、@code{inc()}、@code{dec()}、@code{reset()} は同じカウント変数を共有する関数のようにふるまいます。

@node Python のオブジェクトはどのようにコピーしますか？,オブジェクトのメソッドや属性はどのように見つけますか？,Python で高次関数はどのようにつくりますか？,コア言語
@anchor{faq/programming how-do-i-copy-an-object-in-python}@anchor{58c3}
@subsubsection Python のオブジェクトはどのようにコピーしますか？


一般的に、普通は @ref{757,,copy.copy()} や @ref{d65,,copy.deepcopy()} を試してください。何でもコピーできるとは限りませんが、たいていはできます。

もっと簡単にコピーできるオブジェクトもあります。辞書には @ref{dc9,,copy()} メソッドがあります:

@example
newdict = olddict.copy()
@end example

シーケンスはスライシングでコピーできます:

@example
new_l = l[:]
@end example

@node オブジェクトのメソッドや属性はどのように見つけますか？,コードはどのようにオブジェクトの名前を見つけるのですか？,Python のオブジェクトはどのようにコピーしますか？,コア言語
@anchor{faq/programming how-can-i-find-the-methods-or-attributes-of-an-object}@anchor{58c4}
@subsubsection オブジェクトのメソッドや属性はどのように見つけますか？


ユーザー定義クラスのインスタンス @code{x} で、@ref{844,,dir(x)},< はインスタンス属性とそのクラスで定義されたメソッドや属性を含む名前のアルファベット順リストを返します。

@node コードはどのようにオブジェクトの名前を見つけるのですか？,カンマ演算子はなぜ優先されるのですか？,オブジェクトのメソッドや属性はどのように見つけますか？,コア言語
@anchor{faq/programming how-can-my-code-discover-the-name-of-an-object}@anchor{58c5}
@subsubsection コードはどのようにオブジェクトの名前を見つけるのですか？


概して、オブジェクトは本当は名前を持たないので、見つけることはできません。本質的には、代入とはいつも値に名前を束縛することです。@code{def} と @code{class} 文も同じですが、この場合は値はコーラブルです。以下のコードを考えてみましょう:

@example
>>> class A:
...     pass
...
>>> B = A
>>> a = B()
>>> b = a
>>> print(b)
<__main__.A object at 0x16D07CC>
>>> print(a)
<__main__.A object at 0x16D07CC>
@end example

おそらく、このクラスには名前があります。このクラスは二つの名前に縛られて、名前 @code{B} を通して呼び出されますが、それでもクラス @code{A} のインスタンスとして報告されるのです。しかし、両方の名前が同じ値に束縛されている以上、このインスタンスの名前が @code{a} か @code{b} か決めることはできないのです。

概して、コードにとってある値の「名前を知っている」事は重要ではありません。あなたがわざと内省的なコードを書いているのでない限り、方針を変えた方がいいかもしれないということになるでしょう。

comp.lang.python で、Fredrik Lundh はこの問題の答えとして素晴らしい喩えをしてくれました:

@quotation

玄関にいた猫の名前を知るのと同じ方法です: その猫 (オブジェクト) 自体はその名前を言うことができないし、それは実は問題ではありません -- その猫が何と呼ばれているかを知る唯一の方法は、すべての隣人 (名前空間) にその猫 (オブジェクト) が何と呼ばれているかを聞くことです。

……そして、その猫が沢山の名前で知られていたり、逆に全く名前が無かったりしても驚かないでください！
@end quotation

@node カンマ演算子はなぜ優先されるのですか？,C の "? " 三項演算子と等価なものはありますか？,コードはどのようにオブジェクトの名前を見つけるのですか？,コア言語
@anchor{faq/programming what-s-up-with-the-comma-operator-s-precedence}@anchor{58c6}
@subsubsection カンマ演算子はなぜ優先されるのですか？


カンマは Python では演算子ではありません。このセッションを考えてください:

@example
>>> "a" in "b", "a"
(False, 'a')
@end example

カンマは演算子ではなく、式の分離子なので、上の式は次の式と同じように評価されます:

@example
("a" in "b"), "a"
@end example

こうではありません:

@example
"a" in ("b", "a")
@end example

他のさまざまな演算子(@code{=}、@code{+=} など)も同じです。これらは真の演算子ではありませんが、代入文の構文上のデリミタです。

@node C の "? " 三項演算子と等価なものはありますか？,Python で解し難いワンライナーを書くことはできますか？,カンマ演算子はなぜ優先されるのですか？,コア言語
@anchor{faq/programming is-there-an-equivalent-of-c-s-ternary-operator}@anchor{58c7}
@subsubsection C の "?:" 三項演算子と等価なものはありますか？


はい、あります。構文は以下のようになります:

@example
[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y
@end example

この構文が導入された 2.5 以前のバージョンに関しては、論理演算子を使ったこのイディオムが一般的でした:

@example
[expression] and [on_true] or [on_false]
@end example

しかし、このイディオムは安全ではありません。`on_true' のブール値が偽であるときに間違った結果を与えることがあります。ですから、いつでも @code{... if ... else ...} 形式を使ったほうが良いです。

@node Python で解し難いワンライナーを書くことはできますか？,関数の引数リストにあるスラッシュ / は何を意味しますか？,C の "? " 三項演算子と等価なものはありますか？,コア言語
@anchor{faq/programming is-it-possible-to-write-obfuscated-one-liners-in-python}@anchor{58c8}
@subsubsection Python で解し難いワンライナーを書くことはできますか？


はい。そういうものはたいてい、 @code{lambda} の中に @ref{14b5,,lambda} がネストされています。Ulf Bartelt によるものを少しアレンジした下の３つの例を見てください:

@example
from functools import reduce

# Primes < 1000
print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))

# First 10 Fibonacci numbers
print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
f(x,f), range(10))))

# Mandelbrot set
print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\n'+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
#    \___ ___/  \___ ___/  |   |   |__ lines on screen
#        V          V      |   |______ columns on screen
#        |          |      |__________ maximum of "iterations"
#        |          |_________________ range on y axis
#        |____________________________ range on x axis
@end example

よい子はまねしないでね！

@node 関数の引数リストにあるスラッシュ / は何を意味しますか？,,Python で解し難いワンライナーを書くことはできますか？,コア言語
@anchor{faq/programming faq-positional-only-arguments}@anchor{25d6}@anchor{faq/programming what-does-the-slash-in-the-parameter-list-of-a-function-mean}@anchor{58c9}
@subsubsection 関数の引数リストにあるスラッシュ (/) は何を意味しますか？


パラメータ関数の仮引数にあるスラッシュは、それより前にある仮引数は位置専用引数であることを示します。
位置専用引数は、外で使える名前を持たない仮引数です。
位置専用引数を受け付ける関数の呼び出しにおいて、実引数はその位置だけに基づいて仮引数に対応付けられます。
例えば、 @ref{b99,,divmod()} は位置専用引数を受け付けます。
そのドキュメントは次のようになります:

@example
>>> help(divmod)
Help on built-in function divmod in module builtins:

divmod(x, y, /)
    Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.
@end example

この引数リストの末尾にスラッシュは、この2つの仮引数が両方とも位置専用引数であることを意味します。
したがって、@ref{b99,,divmod()} をキーワード引数を使って呼び出すとエラーになります:

@example
>>> divmod(x=3, y=4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: divmod() takes no keyword arguments
@end example

@node 数と文字列,性能<4>,コア言語,プログラミング FAQ
@anchor{faq/programming numbers-and-strings}@anchor{58ca}
@subsection 数と文字列


@menu
* 十六進数や八進数を指定するにはどうしたらいいですか？:: 
* なぜ -22 // 10 は -3 を返すのですか？:: 
* どうすれば SyntaxError を起こさずに整数リテラルの属性を得られますか？:: 
* 文字列を数に変換するにはどうしたらいいですか？:: 
* 数を文字列に変換するにはどうしたらいいですか？:: 
* 文字列をインプレースに変更するにはどうしたらいいですか？:: 
* 関数やメソッドを呼ぶのに文字列を使うにはどうしたらいいですか？:: 
* Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?: Is there an equivalent to Perl's chomp for removing trailing newlines from strings?. 
* Is there a scanf() or sscanf() equivalent?: Is there a scanf or sscanf equivalent?. 
* What does UnicodeDecodeError or UnicodeEncodeError error mean?:: 
* raw string を奇数個のバックスラッシュで終えることはできますか？:: 

@end menu

@node 十六進数や八進数を指定するにはどうしたらいいですか？,なぜ -22 // 10 は -3 を返すのですか？,,数と文字列
@anchor{faq/programming how-do-i-specify-hexadecimal-and-octal-integers}@anchor{58cb}
@subsubsection 十六進数や八進数を指定するにはどうしたらいいですか？


八進数を指定するには、八進数での値の先頭に 0 と "o" (小文字または大文字) を加えてください。たとえば、変数 "a" に八進数での "10" (十進数での"8") を代入するには、こう打ってください:

@example
>>> a = 0o10
>>> a
8
@end example

十六進数も簡単です。ただ十六進数での値の先頭に 0 と "x" (小文字または大文字) を加えてください。十六進数は小文字でも大文字でも指定できます。たとえば、Python インタプリタで:

@example
>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178
@end example

@node なぜ -22 // 10 は -3 を返すのですか？,どうすれば SyntaxError を起こさずに整数リテラルの属性を得られますか？,十六進数や八進数を指定するにはどうしたらいいですか？,数と文字列
@anchor{faq/programming why-does-22-10-return-3}@anchor{58cc}
@subsubsection なぜ -22 // 10 は -3 を返すのですか？


@code{i % j} が @code{j} と同じ符号であってほしいことに基づいています。それに加えて以下のようにもしたいとすると:

@example
i == (i // j) * j + (i % j)
@end example

整数除算は床を返すことになります。C にも C の一貫性があって、@code{i % j} が @code{i} と同じ符号を持つように @code{i // j} を丸めています。

@code{i % j} は、@code{j} が負の時には実際にはほとんど使いません。@code{j} が正なら、たくさん使います。その事実上すべての場合、@code{i % j} は @code{>= 0} となる方が便利です。時計が 10 時を指している時、その 200 時間前は何時でしょうか。@code{-190 % 12 == 2} となるのが便利です。@code{-190 % 12 == -10} は噛み付きかねないバグです。

@node どうすれば SyntaxError を起こさずに整数リテラルの属性を得られますか？,文字列を数に変換するにはどうしたらいいですか？,なぜ -22 // 10 は -3 を返すのですか？,数と文字列
@anchor{faq/programming how-do-i-get-int-literal-attribute-instead-of-syntaxerror}@anchor{58cd}
@subsubsection どうすれば SyntaxError を起こさずに整数リテラルの属性を得られますか？


ふつうの方法で @code{int} リテラルの属性を探そうとすると、ピリオドが小数点とみなされ、@ref{18e,,SyntaxError} となります:

@example
>>> 1.__class__
  File "<stdin>", line 1
  1.__class__
   ^
SyntaxError: invalid decimal literal
@end example

解決策は、リテラルとピリオドを スペースや括弧で分けることです。

@example
>>> 1 .__class__
<class 'int'>
>>> (1).__class__
<class 'int'>
@end example

@node 文字列を数に変換するにはどうしたらいいですか？,数を文字列に変換するにはどうしたらいいですか？,どうすれば SyntaxError を起こさずに整数リテラルの属性を得られますか？,数と文字列
@anchor{faq/programming how-do-i-convert-a-string-to-a-number}@anchor{58ce}
@subsubsection 文字列を数に変換するにはどうしたらいいですか？


For integers, use the built-in @ref{19b,,int()} type constructor, e.g. @code{int('144')
== 144}.  Similarly, @ref{196,,float()} converts to a floating-point number,
e.g. @code{float('144') == 144.0}.

デフォルトでは、これらは数を十進数として解釈するので、 @code{int('0144') == 144} は成立しますが @code{int('0x144')} は @ref{2ec,,ValueError} を送出します。 @code{int(string, base)} はオプションの第二引数をとって変換元の基数にします。つまり @code{int( '0x144', 16) == 324} です。基数が 0 と指定された場合、その数は Python の基準によって解釈されます。先頭が '0o' なら八進数で、'0x' なら十六進数を表します。

文字列を数に変換するだけのために @ref{4a3,,eval()} を使わないでください。 @ref{4a3,,eval()} は特に遅いですし、セキュリティ上のリスクもあります。求められない副作用を持つような Python の式を渡そうとする人がいるかも知れません。例えば、あなたのホームディレクトリを消去する @code{__import__('os').system("rm -rf $HOME")} を渡そうとする人がいるかも知れません。

@ref{4a3,,eval()} にも数を Python の式として解釈する機能があります。だから例えば、 @code{eval('09')} は構文エラー起こします。Python は ('0' 以外の) 十進数を '0' で始めてはならないからです。

@node 数を文字列に変換するにはどうしたらいいですか？,文字列をインプレースに変更するにはどうしたらいいですか？,文字列を数に変換するにはどうしたらいいですか？,数と文字列
@anchor{faq/programming how-do-i-convert-a-number-to-a-string}@anchor{58cf}
@subsubsection 数を文字列に変換するにはどうしたらいいですか？


例えば、@code{144} という数を @code{'144'} という文字列に変換したいなら、組み込み型のコンストラクタ @ref{169,,str()} を使ってください。
十六進数や八進数にしたければ、組み込み関数の @ref{14e7,,hex()} や @ref{14e6,,oct()} を使ってください。
手の込んだフォーマット形式を使うなら、 @ref{19a,,f-strings} と @ref{15b3,,書式指定文字列の文法} の節を参照してください。
例えば、 @code{"@{:04d@}".format(144)} は @code{'0144'} になり、 @code{"@{:.3f@}".format(1.0/3.0)} は @code{'0.333'} になります。

@node 文字列をインプレースに変更するにはどうしたらいいですか？,関数やメソッドを呼ぶのに文字列を使うにはどうしたらいいですか？,数を文字列に変換するにはどうしたらいいですか？,数と文字列
@anchor{faq/programming how-do-i-modify-a-string-in-place}@anchor{58d0}
@subsubsection 文字列をインプレースに変更するにはどうしたらいいですか？


文字列はイミュータブルなので、それはできません。殆どの場合、組み立てたい個別の部品から単純に新しい文字列を構成するべきです。しかし、Unicode データをインプレースに変更できるオブジェクトが必要なら、 @ref{8,,array} モジュールの @ref{112a,,io.StringIO} オブジェクトを試してください:

@example
>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello, world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello, there!'

>>> import array
>>> a = array.array('w', s)
>>> print(a)
array('w', 'Hello, world')
>>> a[0] = 'y'
>>> print(a)
array('w', 'yello, world')
>>> a.tounicode()
'yello, world'
@end example

@node 関数やメソッドを呼ぶのに文字列を使うにはどうしたらいいですか？,Is there an equivalent to Perl's chomp for removing trailing newlines from strings?,文字列をインプレースに変更するにはどうしたらいいですか？,数と文字列
@anchor{faq/programming how-do-i-use-strings-to-call-functions-methods}@anchor{58d1}
@subsubsection 関数やメソッドを呼ぶのに文字列を使うにはどうしたらいいですか？


様々なテクニックがあります。


@itemize *

@item 
一番いいのは、文字列を関数に対応させる辞書を使うことです。このテクニックの一番の利点は、文字列が関数の名前と同じ必要がないことです。この方法は case 構造をエミュレートするための一番のテクニックでもあります:

@example
def a():
    pass

def b():
    pass

dispatch = @{'go': a, 'stop': b@}  # Note lack of parens for funcs

dispatch[get_input()]()  # Note trailing parens to call function
@end example

@item 
組み込み関数の @ref{dca,,getattr()} を使う方法:

@example
import foo
getattr(foo, 'bar')()
@end example

なお、 @ref{dca,,getattr()} はクラス、クラスインスタンス、モジュールなど、どんなオブジェクトにも使えます。

これは標準ライブラリでも何箇所か使われています。このように:

@example
class Foo:
    def do_foo(self):
        ...

    def do_bar(self):
        ...

f = getattr(foo_instance, 'do_' + opname)
f()
@end example

@item 
@ref{46f,,locals()} を使って関数名を決める方法:

@example
def myFunc():
    print("hello")

fname = "myFunc"

f = locals()[fname]
f()
@end example
@end itemize

@node Is there an equivalent to Perl's chomp for removing trailing newlines from strings?,Is there a scanf or sscanf equivalent?,関数やメソッドを呼ぶのに文字列を使うにはどうしたらいいですか？,数と文字列
@anchor{faq/programming is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings}@anchor{58d2}
@subsubsection Is there an equivalent to Perl's @code{chomp()} for removing trailing newlines from strings?


@code{S.rstrip("\r\n")} を使って文字列 @code{S} の終端から他の空白文字を取り除くことなくすべての行末記号を取り除くことができます。文字列 @code{S} が複数行を表し、終端に空行があるとき、そのすべての空行も取り除かれます:

@example
>>> lines = ("line 1 \r\n"
...          "\r\n"
...          "\r\n")
>>> lines.rstrip("\n\r")
'line 1 '
@end example

これは典型的に一度に一行ずつテキストを読みたい時にのみ使われるので、@code{S.rstrip()} をこの方法で使うとうまくいきます。

@node Is there a scanf or sscanf equivalent?,What does UnicodeDecodeError or UnicodeEncodeError error mean?,Is there an equivalent to Perl's chomp for removing trailing newlines from strings?,数と文字列
@anchor{faq/programming is-there-a-scanf-or-sscanf-equivalent}@anchor{58d3}
@subsubsection Is there a @code{scanf()} or @code{sscanf()} equivalent?


そのようなものはありません。

For simple input parsing, the easiest approach is usually to split the line into
whitespace-delimited words using the @ref{10aa,,split()} method of string objects
and then convert decimal strings to numeric values using @ref{19b,,int()} or
@ref{196,,float()}.  @code{split()} supports an optional "sep" parameter which is useful
if the line uses something other than whitespace as a separator.

もっと複雑な入力解析をしたいなら、C の @code{sscanf} よりも正規表現の方が便利ですし、この処理に向いています。

@node What does UnicodeDecodeError or UnicodeEncodeError error mean?,raw string を奇数個のバックスラッシュで終えることはできますか？,Is there a scanf or sscanf equivalent?,数と文字列
@anchor{faq/programming what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean}@anchor{58d4}
@subsubsection What does @code{UnicodeDecodeError} or @code{UnicodeEncodeError} error mean?


@ref{14bc,,Unicode HOWTO} を参照して下さい。

@node raw string を奇数個のバックスラッシュで終えることはできますか？,,What does UnicodeDecodeError or UnicodeEncodeError error mean?,数と文字列
@anchor{faq/programming can-i-end-a-raw-string-with-an-odd-number-of-backslashes}@anchor{58d5}@anchor{faq/programming faq-programming-raw-string-backslash}@anchor{1fdf}
@subsubsection raw string を奇数個のバックスラッシュで終えることはできますか？


奇数個のバックスラッシュで終わる raw string は文字列のクォートをエスケープします:

@example
>>> r'C:\this\will\not\work\'
  File "<stdin>", line 1
    r'C:\this\will\not\work\'
    ^
SyntaxError: unterminated string literal (detected at line 1)
@end example

これにはいくつかの回避策があります。ひとつは通常文字列と二重バックスラッシュを使うことです:

@example
>>> 'C:\\this\\will\\work\\'
'C:\\this\\will\\work\\'
@end example

もうひとつは、エスケープされたバックスラッシュを含む通常の文字列を、 raw string に連結します:

@example
>>> r'C:\this\will\work' '\\'
'C:\\this\\will\\work\\'
@end example

Windowsでは、 @ref{19a9,,os.path.join()} を使ってバックスラッシュを追加することもできます:

@example
>>> os.path.join(r'C:\this\will\work', '@w{'})
'C:\\this\\will\\work\\'
@end example

注意点として、バックスラッシュは raw string 終端のクォートを「エスケープ」しますが、 raw string の値を解釈する際にはエスケープが生じません。つまり、バックスラッシュは raw string 値の中に残ったままになります:

@example
>>> r'backslash\'preserved'
"backslash\\'preserved"
@end example

@ref{229f,,言語リファレンス} の仕様も参照してください。

@node 性能<4>,シーケンス タプル/リスト,数と文字列,プログラミング FAQ
@anchor{faq/programming performance}@anchor{58d6}
@subsection 性能


@menu
* プログラムが遅すぎます。どうしたら速くなりますか？:: 
* 多くの文字列を結合するのに最も効率的な方法は何ですか？:: 

@end menu

@node プログラムが遅すぎます。どうしたら速くなりますか？,多くの文字列を結合するのに最も効率的な方法は何ですか？,,性能<4>
@anchor{faq/programming my-program-is-too-slow-how-do-i-speed-it-up}@anchor{58d7}
@subsubsection プログラムが遅すぎます。どうしたら速くなりますか？


これは、一般的に難しい問題です。まず、先に進む前に覚えておいて欲しいことをここに挙げます:


@itemize *

@item 
性能の傾向は Python 実装によって変わります。この FAQ では @ref{905,,CPython} に焦点を当てます。

@item 
振る舞いはオペレーティングシステムによって変わりえます。特に、I/O やマルチスレッドに関しては顕著です。

@item 
常に、コードの最適化を始める `前に' プログラムのホットスポットを見つけるべきです (@ref{b4,,profile} モジュールを参照してください)。

@item 
ベンチマークスクリプトを書くことで、改善箇所の捜索を素早く繰り返せます (@ref{f5,,timeit} モジュールを参照してください)。

@item 
洗練された最適化に隠れたリグレッションの可能性を生む前に、(ユニットテストやその他の技法で) コードカバレッジを上げることを強く推奨します。
@end itemize

とは言っても、Python コードを高速化する技法はたくさんあります。ここでは、満足な性能のレベルにたどり着くまでの長い道のりを進む、一般的な方針を示します:


@itemize *

@item 
コード中に細かい最適化の技法をばらまこうとするよりも、アルゴリズムを高速化 (または高速なアルゴリズムに変更) するほうが、大きな利益を生むことがあります。

@item 
適切なデータ構造を使ってください。@ref{25e9,,組み込み型} や @ref{1e,,collections} を調べてください。

@item 
何かをするための基本要素が標準ライブラリにあるなら、自分で発明した代用品よりもそちらのほうが、(絶対にとは言えませんが) おそらく速いです。
それが組み込み型やある種の拡張型のように C で書かれたものならなおさらです。
たとえば、ソートするには、必ず @ref{dc8,,list.sort()} 組み込みメソッドか @ref{dc7,,sorted()} 関数を使ってください (また、中程度に高度な例は、 @ref{13f3,,ソートのテクニック} を参照してください)。

@item 
抽象化は、遠回りにしがちで、インタプリタの作業を増やすことになります。この遠回りさが、なされる作業の量より重大になると、プログラムが遅くなってしまいます。過度な抽象化、特に細かい関数やメソッドの形で現れるもの (これは読みにくさも落とします) は防ぐべきです。
@end itemize

pure Python にできる限界に達したなら、更に進むためのツールがあります。例えば、Cython@footnote{https://cython.org} は、Python コードのわずかに変形した版を C 拡張にコンパイルし、多種のプラットフォームで使えます。Cython は、コンパイル (と任意の型アノテーション) を利用し、コードの解釈を大幅に速くします。C プログラミングに自信があるなら、自分で @ref{1fbd,,write a C extension module} こともできます。


@subsubheading 参考


パフォーマンス tips@footnote{https://wiki.python.org/moin/PythonSpeed/PerformanceTips} が載っている wiki のページ。


@node 多くの文字列を結合するのに最も効率的な方法は何ですか？,,プログラムが遅すぎます。どうしたら速くなりますか？,性能<4>
@anchor{faq/programming efficient-string-concatenation}@anchor{58d8}@anchor{faq/programming what-is-the-most-efficient-way-to-concatenate-many-strings-together}@anchor{58d9}
@subsubsection 多くの文字列を結合するのに最も効率的な方法は何ですか？


@ref{169,,str} および @ref{192,,bytes} オブジェクトはイミュータブルなので、多くの文字列の結合は結合ごとに新しいオブジェクトを作成し、効率が悪いです。
一般的に、全体の実行時間のコストは文字列の長さの二乗に比例します。

多くの @ref{169,,str} オブジェクトを累積するのにおすすめのイディオムは、すべてをリストに配置してから最後に @ref{2609,,str.join()} を呼び出すことです:

@example
chunks = []
for s in my_strings:
    chunks.append(s)
result = '@w{'}.join(chunks)
@end example

(他の割と効率的なイディオムは、 @ref{112a,,io.StringIO} を使うことです)

多くの @ref{192,,bytes} オブジェクトを累積するのにおすすめのイディオムは、 @ref{344,,bytearray} オブジェクトをインプレース結合 (@code{+=} 演算子) で拡張することです:

@example
result = bytearray()
for b in my_bytes_objects:
    result += b
@end example

@node シーケンス タプル/リスト,オブジェクト,性能<4>,プログラミング FAQ
@anchor{faq/programming sequences-tuples-lists}@anchor{58da}
@subsection シーケンス(タプル/リスト)


@menu
* タプル、リスト間の変更はどのようにするのですか？:: 
* 負の添え字は何ですか？:: 
* シーケンスを逆順にイテレートするにはどうしたらいいですか？:: 
* リストから重複を取り除くにはどうしますか？:: 
* How do you remove multiple items from a list?:: 
* Python で配列を作るにはどうしますか？:: 
* 多次元のリストを作るにはどうしますか？:: 
* オブジェクトのシーケンスにメソッドや関数を適用するにはどうしますか？:: 
* なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?:: 
* 複雑なソートがしたいのですが、Python でシュワルツ変換はできますか？:: 
* リストを別のリストの値によってソートするにはどうしますか？:: 

@end menu

@node タプル、リスト間の変更はどのようにするのですか？,負の添え字は何ですか？,,シーケンス タプル/リスト
@anchor{faq/programming how-do-i-convert-between-tuples-and-lists}@anchor{58db}
@subsubsection タプル、リスト間の変更はどのようにするのですか？


型コンストラクタ @code{tuple(seq)} はすべてのシーケンス (実際には、すべてのイテラブル) を同じ要素、同じ順序のタプルに変換します。

例えば、 @code{tuple([1, 2, 3])} は @code{(1, 2, 3)} を与え、 @code{tuple('abc')} は @code{('a', 'b', 'c')} を与えます。引数がタプルなら、コピーを作らずに引数のオブジェクトそのものを返すので、あるオブジェクトが既にタプルになっているか確信が持てないのなら、 @ref{614,,tuple()} を呼ぶのが手軽です。

型コンストラクタ @code{list(seq)} はすべてのシーケンスあるいはイテラブルを同じ要素、同じ順序のリストに変換します。例えば、@code{list((1, 2, 3))} は @code{[1, 2, 3]} を与え、@code{list('abc')} は @code{['a', 'b', 'c']} を与えます。引数がリストなら、@code{seq[:]} と同様にコピーを作ります。

@node 負の添え字は何ですか？,シーケンスを逆順にイテレートするにはどうしたらいいですか？,タプル、リスト間の変更はどのようにするのですか？,シーケンス タプル/リスト
@anchor{faq/programming what-s-a-negative-index}@anchor{58dc}
@subsubsection 負の添え字は何ですか？


Python のシーケンスは正の数と負の数でインデクスされます。正の数では、0 が最初のインデクス、1 が 2 番目のインデクス、以下も同様です。負のインデクスでは、-1 が最後のインデクス、-2 が最後から 2 番目のインデクス、以下も同様です。@code{seq[-n]} は @code{seq[len(seq)-n]} と同じだと考えてください。

負のインデクスを使うと便利なことがあります。例えば、@code{S[:-1]} は文字列の最後以外のすべての文字を表すので、文字列の末尾の改行を取り除くときに便利です。

@node シーケンスを逆順にイテレートするにはどうしたらいいですか？,リストから重複を取り除くにはどうしますか？,負の添え字は何ですか？,シーケンス タプル/リスト
@anchor{faq/programming how-do-i-iterate-over-a-sequence-in-reverse-order}@anchor{58dd}
@subsubsection シーケンスを逆順にイテレートするにはどうしたらいいですか？


組み込み関数 @ref{a65,,reversed()} を使ってください。

@example
for x in reversed(sequence):
    ...  # do something with x ...
@end example

これは元のシーケンスをいじるのではなく、逆順の新しいコピーを作ってイテレートさせます。

@node リストから重複を取り除くにはどうしますか？,How do you remove multiple items from a list?,シーケンスを逆順にイテレートするにはどうしたらいいですか？,シーケンス タプル/リスト
@anchor{faq/programming how-do-you-remove-duplicates-from-a-list}@anchor{58de}
@subsubsection リストから重複を取り除くにはどうしますか？


Python Cookbook の長い議論に多くの方法があるので参照してください:

@quotation

@indicateurl{https://code.activestate.com/recipes/52560/}
@end quotation

リストを並び替えて構わないのなら、ソートした上でリストの最初から最後までを調べ、次のように重複を削除してください:

@example
if mylist:
    mylist.sort()
    last = mylist[-1]
    for i in range(len(mylist)-2, -1, -1):
        if last == mylist[i]:
            del mylist[i]
        else:
            last = mylist[i]
@end example

リストのすべての要素が集合のキーとして使える (つまり、すべての要素が @ref{824,,hashable}) なら、おそらくこのほうが速いです

@example
mylist = list(set(mylist))
@end example

リストを集合に変換するときに重複は取り除かれるので、それをリストに戻せばいいのです。

@node How do you remove multiple items from a list?,Python で配列を作るにはどうしますか？,リストから重複を取り除くにはどうしますか？,シーケンス タプル/リスト
@anchor{faq/programming how-do-you-remove-multiple-items-from-a-list}@anchor{58df}
@subsubsection How do you remove multiple items from a list?


As with removing duplicates, explicitly iterating in reverse with a
delete condition is one possibility.  However, it is easier and faster
to use slice replacement with an implicit or explicit forward iteration.
Here are three variations:

@example
mylist[:] = filter(keep_function, mylist)
mylist[:] = (x for x in mylist if keep_condition)
mylist[:] = [x for x in mylist if keep_condition]
@end example

リスト内包表記がおそらく最も高速です。

@node Python で配列を作るにはどうしますか？,多次元のリストを作るにはどうしますか？,How do you remove multiple items from a list?,シーケンス タプル/リスト
@anchor{faq/programming how-do-you-make-an-array-in-python}@anchor{58e0}
@subsubsection Python で配列を作るにはどうしますか？


リストを使ってください:

@example
["this", 1, "is", "an", "array"]
@end example

リストの時間計算量は C や Pascal の配列と同じです。大きな違いは、Python のリストは多くの異なる型のオブジェクトを含めることです。

@code{array} モジュールにも固定された型を簡潔に表現する配列を作るためのメソッドがありますが、リストよりもインデクスが遅いです。また、NumPy@footnote{https://numpy.org/} やその他のサードパーティー拡張でも、様々な特徴をもつ配列的な構造体が定義されています。

Lisp 方式の連結リストを得るのに、タプルを使って `cons cells' をエミュレートできます:

@example
lisp_list = ("like",  ("this",  ("example", None) ) )
@end example

ミュータブルな必要があるなら、タプルではなくリストを使いましょう。Lisp の `car' にあたるものが @code{lisp_list[0]} で、cdr にあたるものが @code{lisp_list[1]} です。本当に必要だと確信できるとき以外はこれはしないでください。たいてい、これは Python のリストを使うよりも非常に遅いですから。

@node 多次元のリストを作るにはどうしますか？,オブジェクトのシーケンスにメソッドや関数を適用するにはどうしますか？,Python で配列を作るにはどうしますか？,シーケンス タプル/リスト
@anchor{faq/programming faq-multidimensional-list}@anchor{2608}@anchor{faq/programming how-do-i-create-a-multidimensional-list}@anchor{58e1}
@subsubsection 多次元のリストを作るにはどうしますか？


このようにして多次元の配列を作ろうとしてしまったことがあるでしょう:

@example
>>> A = [[None] * 2] * 3
@end example

これを表示したときには問題なさそうに見えます:

@c A = [[None] * 2] * 3

@example
>>> A
[[None, None], [None, None], [None, None]]
@end example

しかし値を代入すると、その値が複数の場所に現れてしまいます:

@c A = [[None] * 2] * 3

@example
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]
@end example

これは、@code{*} を使ったリストの複製がコピーを作らず、存在するオブジェクトへの参照を作るだけだからです。この @code{*3} は長さ 2 の同じリストへの参照を含むリストを作ります。一つの列に対する変更はすべての列に現れますが、これが望んだ結果であることはまずないでしょう。

おすすめの方法は、最初に望んだ長さのリストを作り、それから新しく作ったリストでそれぞれの要素を埋めていくことです:

@example
A = [None] * 3
for i in range(3):
    A[i] = [None] * 2
@end example

これは長さ 2 の異なるリスト 3 つを含むリストを生成します。リスト内包表記も使えます:

@example
w, h = 2, 3
A = [[None] * w for i in range(h)]
@end example

あるいは、行列データ型を提供している拡張を使用することもできます; NumPy@footnote{https://numpy.org/} が最もよく知られています。

@node オブジェクトのシーケンスにメソッドや関数を適用するにはどうしますか？,なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?,多次元のリストを作るにはどうしますか？,シーケンス タプル/リスト
@anchor{faq/programming how-do-i-apply-a-method-or-function-to-a-sequence-of-objects}@anchor{58e2}
@subsubsection オブジェクトのシーケンスにメソッドや関数を適用するにはどうしますか？


メソッドや関数を呼び出して結果を蓄積するのには、 @ref{8dd,,list comprehension} （リスト内包表記） がエレガントな解決策です:

@example
result = [obj.method() for obj in mylist]

result = [function(obj) for obj in mylist]
@end example

戻り値を保存せずにメソッドや関数を実行するだけなら、ただの @ref{34a,,for} ループで十分です:

@example
for obj in mylist:
    obj.method()

for obj in mylist:
    function(obj)
@end example

@node なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?,複雑なソートがしたいのですが、Python でシュワルツ変換はできますか？,オブジェクトのシーケンスにメソッドや関数を適用するにはどうしますか？,シーケンス タプル/リスト
@anchor{faq/programming faq-augmented-assignment-tuple-error}@anchor{2402}@anchor{faq/programming why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works}@anchor{58e3}
@subsubsection なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?


これは、累算代入演算子は `代入' 演算子だ、という事実と、Python での可変オブジェクトと不変オブジェクトの違いが組み合わさって起きるのです。

この議論は一般的に、可変オブジェクトを指すタプルの要素に、累算代入演算子が適用されたときにも適用できますが、例として @code{list} と @code{+=} を使います。

次のように書いたとします:

@example
>>> a_tuple = (1, 2)
>>> a_tuple[0] += 1
Traceback (most recent call last):
   ...
TypeError: 'tuple' object does not support item assignment
@end example

例外が送出された理由は明らかです: @code{1} が (@code{1}) を指すオブジェクト @code{a_tuple[0]} に加えられ、結果のオブジェクト @code{2} が生成されますが、計算結果 @code{2} をタプルの第 @code{0} 要素に代入しようとしたときに、エラーが発生します。なぜならば、タプルの要素が何を指すかは変えられないからです。

このような裏事情の元、累算代入文はだいたい次のようなことをしています:

@example
>>> result = a_tuple[0] + 1
>>> a_tuple[0] = result
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment
@end example

タプルは不変なので、例外を生み出しているのは操作の代入部分なのです。

次のように書いたとします:

@example
>>> a_tuple = (['foo'], 'bar')
>>> a_tuple[0] += ['item']
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment
@end example

この例外にはちょっと驚きますが、もっと驚くべきことは、エラーがあったとしても追記はきちんと動いている、という事実です:

@example
>>> a_tuple[0]
['foo', 'item']
@end example

To see why this happens, you need to know that (a) if an object implements an
@ref{23df,,__iadd__()} magic method, it gets called when the @code{+=} augmented
assignment
is executed, and its return value is what gets used in the assignment statement;
and (b) for lists, @code{__iadd__()} is equivalent to calling
@ref{23d9,,extend()} on the list and returning the list.
That's why we say that for lists, @code{+=} is a "shorthand" for @ref{602,,list.extend()}:

@example
>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]
@end example

これは次と等価です:

@example
>>> result = a_list.__iadd__([1])
>>> a_list = result
@end example

a_list が指していたオブジェクトは更新され、更新されたオブジェクトへのポインタは再度 @code{a_list} に代入されます。代入しているのは、@code{a_list} が更新前まで指していた同じオブジェクトへのポインタなので、代入は最終的には何もしていないのですが、代入処理自体は起きています。

従って、今のタプルの例では、次のと同じことが起きています:

@example
>>> result = a_tuple[0].__iadd__(['item'])
>>> a_tuple[0] = result
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment
@end example

@code{__iadd__()} は成功し、リストは拡張 (extend) されますが、@code{result} が @code{a_tuple[0]} が既に指しているオブジェクトと同じオブジェクトを指していたとしても、タプルは不変なので、その最後の代入はやはりエラーとなります。

@node 複雑なソートがしたいのですが、Python でシュワルツ変換はできますか？,リストを別のリストの値によってソートするにはどうしますか？,なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?,シーケンス タプル/リスト
@anchor{faq/programming i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python}@anchor{58e4}
@subsubsection 複雑なソートがしたいのですが、Python でシュワルツ変換はできますか？


Perl コミュニティの Randal Schwartz の作とされるこのテクニックは、リストの要素を、それぞれの要素をその「ソート値」に対応付けるメトリックによってソートします。Python では、 @ref{dc8,,list.sort()} メソッドに @code{key} 引数を使ってください:

@example
Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))
@end example

@node リストを別のリストの値によってソートするにはどうしますか？,,複雑なソートがしたいのですが、Python でシュワルツ変換はできますか？,シーケンス タプル/リスト
@anchor{faq/programming how-can-i-sort-one-list-by-values-from-another-list}@anchor{58e5}
@subsubsection リストを別のリストの値によってソートするにはどうしますか？


二つのイテレータを混ぜあわせてタプルのイテレータにしてから、必要な要素を選んでください。

@example
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'something']
@end example

@node オブジェクト,モジュール<5>,シーケンス タプル/リスト,プログラミング FAQ
@anchor{faq/programming objects}@anchor{58e6}
@subsection オブジェクト


@menu
* クラスとは何ですか？:: 
* メソッドとは何ですか？:: 
* self とは何ですか？:: 
* あるオブジェクトが、与えられたクラスやそのサブクラスのインスタンスであるかを調べるにはどうしますか？:: 
* 委譲とは何ですか？:: 
* 基底クラスで定義されたメソッドを、そのクラスを継承した派生クラスから呼び出すにはどうしますか？:: 
* 基底クラスの名前を変えやすいコードを書くにはどうしますか？:: 
* 静的なクラスデータや静的なクラスメソッドを作るにはどうしますか？:: 
* Python でコンストラクタ(やメソッド)をオーバーロードするにはどうしたらいいですか？: Python でコンストラクタ やメソッド をオーバーロードするにはどうしたらいいですか？. 
* __spam を使おうとしたら _SomeClassName__spam からエラーがでました。:: 
* クラスに __del__ メソッドを定義しているのですが、オブジェクトを削除したときに呼ばれません。:: 
* 与えられたクラスのすべてのインスタンスのリストを得るにはどうしますか？:: 
* なぜ id() の結果は一意でないように見えるのですか?: なぜ id の結果は一意でないように見えるのですか?. 
* いつ is 演算子での同一性テストが頼れますか？:: 
* どうすればサブクラスはイミュータブルなインスタンスに格納されたデータを制御できますか？:: 
* メソッド呼び出しをキャッシュするには どうしたらいいですか？:: 

@end menu

@node クラスとは何ですか？,メソッドとは何ですか？,,オブジェクト
@anchor{faq/programming what-is-a-class}@anchor{58e7}
@subsubsection クラスとは何ですか？


クラスは、class 文の実行で生成される特殊なオブジェクトです。クラスオブジェクトはインスタンスオブジェクトを生成するためのテンプレートとして使われ、あるデータ型に特有のデータ (attribute/属性) とコード (メソッド) の両方を内蔵しています。

新しいクラスを一つ以上の他のクラス (新しいクラスの基底クラスと呼ばれます) に基づいて作ることもできます。この新しいクラスは、基底クラスから属性とメソッドを継承します。これにより、オブジェクトモデルを継承で連続的に洗練できます。メールボックスへの基本的なアクセサを提供する一般的な @code{Mailbox} クラスを作って、それからいろいろな特定のメールボックスの形式を扱う @code{MboxMailbox}、@code{MaildirMailbox}、@code{OutlookMailbox} のようなサブクラスを作れるのです。

@node メソッドとは何ですか？,self とは何ですか？,クラスとは何ですか？,オブジェクト
@anchor{faq/programming what-is-a-method}@anchor{58e8}
@subsubsection メソッドとは何ですか？


メソッドは、オブジェクト @code{x} が持つ関数で、通常 @code{x.name(arguments...)} として呼び出されるものです。メソッドはクラス定義の中で関数として定義されます:

@example
class C:
    def meth(self, arg):
        return arg * 2 + self.attribute
@end example

@node self とは何ですか？,あるオブジェクトが、与えられたクラスやそのサブクラスのインスタンスであるかを調べるにはどうしますか？,メソッドとは何ですか？,オブジェクト
@anchor{faq/programming what-is-self}@anchor{58e9}
@subsubsection self とは何ですか？


self はメソッドの第一引数に慣習的につけられる名前にすぎません。@code{meth(self, a, b, c)} として定義されたメソッドは、その定義がなされたクラスのインスタンス @code{x} に対して @code{x.meth(a, b, c)} として呼び出されます。呼び出されたメソッドは、@code{meth(x, a, b, c)} が呼ばれたものと考えます。

@ref{58ea,,なぜメソッドの定義や呼び出しにおいて 'self' を明示しなければならないのですか？} も参照してください。

@node あるオブジェクトが、与えられたクラスやそのサブクラスのインスタンスであるかを調べるにはどうしますか？,委譲とは何ですか？,self とは何ですか？,オブジェクト
@anchor{faq/programming how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it}@anchor{58eb}
@subsubsection あるオブジェクトが、与えられたクラスやそのサブクラスのインスタンスであるかを調べるにはどうしますか？


ビルトイン関数 @ref{2ad,,isinstance(obj@comma{} cls)} を使ってください。クラスのタプルを与えて @code{isinstance(obj, (class1, class2, ...))} のようにすれば、あるオブジェクトが任意の数のクラスのオブジェクトであるかを調べられますし、@code{isinstance(obj, str)} や @code{isinstance(obj, (int, float, complex))} のようにすれば、Python のビルトイン型のオブジェクトであるかも調べられます。

注意： @ref{2ad,,isinstance()} は @ref{13ce,,abstract base class} (抽象基底クラス)からの仮想継承もチェックします。そのため、登録 (register) されたクラスが直接/間接的にそれを継承していなくても @code{True} を返します。「真のインスタンス」をテストする場合は、クラスの @ref{18dd,,MRO} を調べます:

@example
from collections.abc import Mapping

class P:
     pass

class C(P):
    pass

Mapping.register(P)
@end example

@example
>>> c = C()
>>> isinstance(c, C)        # direct
True
>>> isinstance(c, P)        # indirect
True
>>> isinstance(c, Mapping)  # virtual
True

# Actual inheritance chain
>>> type(c).__mro__
(<class 'C'>, <class 'P'>, <class 'object'>)

# Test for "true inheritance"
>>> Mapping in type(c).__mro__
False
@end example

なお、大部分のプログラムでは、 @ref{2ad,,isinstance()} をユーザー定義のクラスに何度も使うべきではありません。クラスを自分で開発するときに、適切なオブジェクト指向スタイルは、特定の振る舞いをカプセル化するクラスのメソッドを定義するものであって、オブジェクトのクラスを調べてそのクラスに応じて違うことをするものではありません。例えば、何かをする関数があったとして:

@example
def search(obj):
    if isinstance(obj, Mailbox):
        ...  # code to search a mailbox
    elif isinstance(obj, Document):
        ...  # code to search a document
    elif ...
@end example

よりよいアプローチは、@code{search()} メソッドをすべてのクラスに定義して、それをただ呼び出すことです:

@example
class Mailbox:
    def search(self):
        ...  # code to search a mailbox

class Document:
    def search(self):
        ...  # code to search a document

obj.search()
@end example

@node 委譲とは何ですか？,基底クラスで定義されたメソッドを、そのクラスを継承した派生クラスから呼び出すにはどうしますか？,あるオブジェクトが、与えられたクラスやそのサブクラスのインスタンスであるかを調べるにはどうしますか？,オブジェクト
@anchor{faq/programming what-is-delegation}@anchor{58ec}
@subsubsection 委譲とは何ですか？


委譲 (delegation) とは、オブジェクト指向のテクニック (デザインパターンとも呼ばれる) の一つです。オブジェクト @code{x} があって、そのメソッドのうちただ一つの振る舞いを変えたいとしましょう。新しいクラスを作成し、変えたいメソッドだけを新しく実装し、他のすべてのメソッドを @code{x} の対応するメソッドに委譲する新しいクラスを作れます。

Python プログラマは簡単に委譲を実装できます。例えば、以下のクラスは、ファイルのように振る舞いながらすべての文字を大文字に変換するクラスを実装します:

@example
class UpperOut:

    def __init__(self, outfile):
        self._outfile = outfile

    def write(self, s):
        self._outfile.write(s.upper())

    def __getattr__(self, name):
        return getattr(self._outfile, name)
@end example

ここで @code{UpperOut} クラスは @code{write()} メソッドを定義しなおして、引数の文字列を大文字に変換してから基礎となる @code{self._outfile.write()} メソッドを呼び出すようにします。その他すべてのメソッドは基礎となる @code{self._outfile} オブジェクトに移譲されます。この委譲は @ref{6fa,,__getattr__()} メソッドを通してなされます。属性の制御の詳細は @ref{23af,,言語リファレンス} を参照してください。

なお、一般的に委譲はトリッキーになりがちです。属性が設定される時には読み出される時と同様に、そのクラスに @ref{237c,,__setattr__()} メソッドを定義する必要があり、それには細心の注意が必要です。 @code{__setattr__()} の基本的な実装はおおよそ以下のようになります:

@example
class X:
    ...
    def __setattr__(self, name, value):
        self.__dict__[name] = value
    ...
@end example

Many @ref{237c,,__setattr__()} implementations call @code{object.__setattr__()} to set
an attribute on self without causing infinite recursion:

@example
class X:
    def __setattr__(self, name, value):
        # Custom logic here...
        object.__setattr__(self, name, value)
@end example

Alternatively, it is possible to set attributes by inserting
entries into @ref{77d,,self.__dict__} directly.

@node 基底クラスで定義されたメソッドを、そのクラスを継承した派生クラスから呼び出すにはどうしますか？,基底クラスの名前を変えやすいコードを書くにはどうしますか？,委譲とは何ですか？,オブジェクト
@anchor{faq/programming how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-extends-it}@anchor{58ed}
@subsubsection 基底クラスで定義されたメソッドを、そのクラスを継承した派生クラスから呼び出すにはどうしますか？


組み込みの @ref{1a6,,super()} 関数を使ってください:

@example
class Derived(Base):
    def meth(self):
        super().meth()  # calls Base.meth
@end example

この例では、 @ref{1a6,,super()} は呼ばれたインスタンス (@code{self} の値) を自動判断し、 @code{type(self).__mro__} で @ref{25df,,method resolution order} (MRO メソッド解決順) を検索し、そしてMRO内で @code{Derived} の次行を返します: @code{Base} 。

@node 基底クラスの名前を変えやすいコードを書くにはどうしますか？,静的なクラスデータや静的なクラスメソッドを作るにはどうしますか？,基底クラスで定義されたメソッドを、そのクラスを継承した派生クラスから呼び出すにはどうしますか？,オブジェクト
@anchor{faq/programming how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class}@anchor{58ee}
@subsubsection 基底クラスの名前を変えやすいコードを書くにはどうしますか？


基底クラスをエイリアス (alias) に代入しておいてから、そのエイリアスを継承するといいかもしれません。そうすればエイリアスに代入する値を変えるだけで済みます。ちなみに、この手法は使用する基底クラスを動的に選びたいとき、例えば使えるリソースによって選びたいときなどにも便利です。例:

@example
class Base:
    ...

BaseAlias = Base

class Derived(BaseAlias):
    ...
@end example

@node 静的なクラスデータや静的なクラスメソッドを作るにはどうしますか？,Python でコンストラクタ やメソッド をオーバーロードするにはどうしたらいいですか？,基底クラスの名前を変えやすいコードを書くにはどうしますか？,オブジェクト
@anchor{faq/programming how-do-i-create-static-class-data-and-static-class-methods}@anchor{58ef}
@subsubsection 静的なクラスデータや静的なクラスメソッドを作るにはどうしますか？


(C++ や Java の意味で) 静的なデータも静的なメソッドも Python でサポートされています。

静的なデータを作るには、単純にクラス属性を定義してください。その属性に新しい値を代入するには、代入するクラス名を明示する必要があります:

@example
class C:
    count = 0   # number of times C.__init__ called

    def __init__(self):
        C.count = C.count + 1

    def getcount(self):
        return C.count  # or return self.count
@end example

@code{c} そのものや @code{c.__class__} から @code{C} にいたるパス探索経路上のクラスによってオーバーライドされない限り、@code{c.count} も @code{isinstance(c, C)} であるすべての @code{c} に対する @code{C.count} を参照します。

注意: C のメソッド内では、@code{self.count = 42} のような代入は @code{self} 自身の辞書に "count" という名前の新しくて関係ないインスタンスを作ります。クラスの静的なデータの再束縛には、メソッド内であるか否かにかかわらず、いつもクラスを指定しなければなりません:

@example
C.count = 314
@end example

静的メソッドが使えます:

@example
class C:
    @@staticmethod
    def static(arg1, arg2, arg3):
        # No 'self' parameter!
        ...
@end example

しかし、静的メソッドの効果を得るもっと簡単な方法は、単にモジュールレベル関数を使うことです:

@example
def getcount():
    return C.count
@end example

モジュールあたりに一つのクラスを定義するように (あるいはクラス組織を厳密に関連させるように) コードが構成されているなら、これで必要なカプセル化ができます。

@node Python でコンストラクタ やメソッド をオーバーロードするにはどうしたらいいですか？,__spam を使おうとしたら _SomeClassName__spam からエラーがでました。,静的なクラスデータや静的なクラスメソッドを作るにはどうしますか？,オブジェクト
@anchor{faq/programming how-can-i-overload-constructors-or-methods-in-python}@anchor{58f0}
@subsubsection Python でコンストラクタ(やメソッド)をオーバーロードするにはどうしたらいいですか？


この質問の答えはすべてのメソッドについて言えることですが、この質問はだいたい以下の構造の文脈から出てきます。

C++ では、このように書けます

@example
class C @{
    C() @{ cout << "No arguments\n"; @}
    C(int i) @{ cout << "Argument is " << i << "\n"; @}
@}
@end example

Python では、一つのコンストラクタでデフォルトの引数を使ってすべての場合に対応するように書かなければなりません。例えば:

@example
class C:
    def __init__(self, i=None):
        if i is None:
            print("No arguments")
        else:
            print("Argument is", i)
@end example

これで完全に等価とは言えませんが、実用上は十分に近いです。

長さが変えられる引数のリストを試すには、例えば

@example
def __init__(self, *args):
    ...
@end example

これと同じやり方がすべてのメソッド定義で使えます。

@node __spam を使おうとしたら _SomeClassName__spam からエラーがでました。,クラスに __del__ メソッドを定義しているのですが、オブジェクトを削除したときに呼ばれません。,Python でコンストラクタ やメソッド をオーバーロードするにはどうしたらいいですか？,オブジェクト
@anchor{faq/programming i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam}@anchor{58f1}
@subsubsection __spam を使おうとしたら _SomeClassName__spam からエラーがでました。


先頭にアンダースコアが二つ付いた変数名は、クラスのプライベートな変数を、 "マングル化" という単純かつ効率のいい方法で定義します。@code{__spam} のような形式 (先頭に二つ以上、末尾にもしあっても一つのアンダースコアがある) のすべての識別子は、@code{classname} が先頭のアンダースコアをすべて削除した現在のクラス名とすれば、@code{_classname__spam} のように文字上で置換えられます。

The identifier can be used unchanged within the class, but to access it outside
the class, the mangled name must be used:

@example
class A:
    def __one(self):
        return 1
    def two(self):
        return 2 * self.__one()

class B(A):
    def three(self):
        return 3 * self._A__one()

four = 4 * A()._A__one()
@end example

In particular, this does not guarantee privacy since an outside user can still
deliberately access the private attribute; many Python programmers never bother
to use private variable names at all.


@subsubheading 参考


詳細と特例は、 @ref{20a3,,private name mangling specifications} 。


@node クラスに __del__ メソッドを定義しているのですが、オブジェクトを削除したときに呼ばれません。,与えられたクラスのすべてのインスタンスのリストを得るにはどうしますか？,__spam を使おうとしたら _SomeClassName__spam からエラーがでました。,オブジェクト
@anchor{faq/programming my-class-defines-del-but-it-is-not-called-when-i-delete-the-object}@anchor{58f2}
@subsubsection クラスに __del__ メソッドを定義しているのですが、オブジェクトを削除したときに呼ばれません。


いくつかの可能性があります。

@ref{1b1f,,del} 文は必ずしも @ref{11ff,,__del__()} を呼び出すとは限りません -- これは単純にオブジェクトの参照カウントを減らすもので、カウントがゼロになったときに @code{__del__()} が呼び出されます。

データ構造が循環リンク (子のそれぞれが親の参照を持ち、親のそれぞれが子のリストを持つツリーなど) を含む場合、その参照カウントは決して 0 にはなりません。時々、Python はこのようなサイクルを検出するアルゴリズムを実行しますが、データ構造への参照がなくなってからこのガベージコレクタが実行されるまでいくらか時間が掛かるかもしれないので、 @code{__del__()} メソッドは不都合な予期できないタイミングで呼び出されるかもしれません。これは問題を再現しようとするときに不便です。さらに悪いことに、オブジェクトの @code{__del__()} メソッドが実行される順序は任意です。 @ref{1b3,,gc.collect()} を起動して収集を強制することができますが、オブジェクトが決して回収されないような本当に病的な場合も `あります' 。

循環参照コレクタがあるとはいえ、オブジェクトに @code{close()} メソッドを明示的に定義し、使い終わったらいつでも呼び出せるようにするのはいいことです。
@code{close()} メソッドを使うと、サブオブジェクトを参照している属性を取り除けます。
@code{__del__()} を直接呼び出さないでください -- @code{__del__()} は @code{close()} を呼び出すでしょうし、 @code{close()} なら同じオブジェクトに対して複数回呼ばれてもいいことが保証されているでしょう。

循環参照を避ける他の方法は、 @ref{11a,,weakref} モジュールを使って、参照カウントを増やすことなくオブジェクトを示すことです。例えばツリー構造は、親と (必要なら！) 兄弟に弱参照を使うべきです。

@c XXX relevant for Python 3?
@c 
@c If the object has ever been a local variable in a function that caught an
@c expression in an except clause, chances are that a reference to the object
@c still exists in that function's stack frame as contained in the stack trace.
@c Normally, calling :func:`sys.exc_clear` will take care of this by clearing
@c the last recorded exception.

最後に、 @code{__del__()} メソッドが例外を発生させた場合、警告のメッセージが @ref{b33,,sys.stderr} に書きこまれます。

@node 与えられたクラスのすべてのインスタンスのリストを得るにはどうしますか？,なぜ id の結果は一意でないように見えるのですか?,クラスに __del__ メソッドを定義しているのですが、オブジェクトを削除したときに呼ばれません。,オブジェクト
@anchor{faq/programming how-do-i-get-a-list-of-all-instances-of-a-given-class}@anchor{58f3}
@subsubsection 与えられたクラスのすべてのインスタンスのリストを得るにはどうしますか？


Python はクラス (やビルトイン型) のすべてのインスタンスをたどりません。クラスのコンストラクタにそれぞれのインスタンスへの弱参照のリストを作らせることですべてのインスタンスをたどらせられます。

@node なぜ id の結果は一意でないように見えるのですか?,いつ is 演算子での同一性テストが頼れますか？,与えられたクラスのすべてのインスタンスのリストを得るにはどうしますか？,オブジェクト
@anchor{faq/programming why-does-the-result-of-id-appear-to-be-not-unique}@anchor{58f4}
@subsubsection なぜ @code{id()} の結果は一意でないように見えるのですか?


組み込みの @ref{163c,,id()} は、オブジェクトが生存している間は一意なことが保証されている整数値を返します。 CPython では、それはオブジェクトのメモリアドレスなので、オブジェクトがメモリから削除された後に、次に新しく生成されたオブジェクトはメモリの同じ場所にメモリ領域を確保されていることが、しばしば起きます。この現象を次の例で示しましょう:

@example
>>> id(1000)
13901272
>>> id(2000)
13901272
@end example

2 つの同じ値を持つ id は @code{id()} の実行の前に作られてすぐさま削除された異なる整数オブジェクトによるものです。id を調べたいオブジェクトがまだ生きてることを保証したいなら、オブジェクトへの別の参照を作ってください:

@example
>>> a = 1000; b = 2000
>>> id(a)
13901272
>>> id(b)
13891296
@end example

@node いつ is 演算子での同一性テストが頼れますか？,どうすればサブクラスはイミュータブルなインスタンスに格納されたデータを制御できますか？,なぜ id の結果は一意でないように見えるのですか?,オブジェクト
@anchor{faq/programming faq-identity-with-is}@anchor{2480}@anchor{faq/programming when-can-i-rely-on-identity-tests-with-the-is-operator}@anchor{58f5}
@subsubsection いつ `is' 演算子での同一性テストが頼れますか？


@code{is} 演算子はオブジェクトの同一性をテストします。  テスト @code{a is b} は @code{id(a) == id(b)} と同等です。

同一性テストの最も重要な特性は、オブジェクトは常にそれ自身と同一であり、 @code{a is a} は常に @code{True} を返すということです。  同一性テストは通常、等価性テストよりも高速です。  また、等価性テストとは異なり、同一性テストは真偽値 @code{True} または`@w{`}False`@w{`} を返すことが保証されています。

ただし、同一性テストを等価性テストの代用とできるのは、オブジェクトの同一性が保証されている場合 `のみ' です。  一般的に、同一性が保証される状況は3つあります:


@enumerate 

@item 
Assignments create new names but do not change object identity.  After the
assignment @code{new = old}, it is guaranteed that @code{new is old}.

@item 
Putting an object in a container that stores object references does not
change object identity.  After the list assignment @code{s[0] = x}, it is
guaranteed that @code{s[0] is x}.

@item 
If an object is a singleton, it means that only one instance of that object
can exist.  After the assignments @code{a = None} and @code{b = None}, it is
guaranteed that @code{a is b} because @code{None} is a singleton.
@end enumerate

多くの他の状況では、同一性テストは賢明でなく、等価性テストをお勧めします。  特に、シングルトンであることが保証されていない @ref{19b,,int} や @ref{169,,str} などの定数をチェックするために同一性テストを使わないでください。

@example
>>> a = 1000
>>> b = 500
>>> c = b + 500
>>> a is c
False

>>> a = 'Python'
>>> b = 'Py'
>>> c = b + 'thon'
>>> a is c
False
@end example

同様に、ミュータブルなコンテナの新しいインスタンスは同一ではありません:

@example
>>> a = []
>>> b = []
>>> a is b
False
@end example

標準ライブラリのコードには、同一性テストを正しく使うための一般的なパターンがあります:


@enumerate 

@item 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} で推奨されているとおり、同一性テストは @code{None} をチェックする際に望ましい方法です。これはコードの中で自然な英語に読むことができ、また

@item 
オプション引数の検出は、 @code{None} が有効な入力値である場合に厄介なことになる場合があります。この状況では、他のオブジェクトと必ず区別できる唯一のマーカーオブジェクト（ singleton sentinel object ）を作ることで対策できます。例えば、 @ref{5e6,,dict.pop()} のように振る舞うメソッドを実装する方法を示します:

@example
_sentinel = object()

def pop(self, key, default=_sentinel):
    if key in self:
        value = self[key]
        del self[key]
        return value
    if default is _sentinel:
        raise KeyError(key)
    return default
@end example

@item 
コンテナの実装では、等価性テストを同一性テストで補強する必要がある場合があります。これは、 @code{float('NaN')} のような自分自身と等しくないオブジェクトによってコードが混乱するのを防ぎます。
@end enumerate

例えば、これは @code{collections.abc.Sequence.__contains__()}: の実装です:

@example
def __contains__(self, value):
    for v in self:
        if v is value or v == value:
            return True
    return False
@end example

@node どうすればサブクラスはイミュータブルなインスタンスに格納されたデータを制御できますか？,メソッド呼び出しをキャッシュするには どうしたらいいですか？,いつ is 演算子での同一性テストが頼れますか？,オブジェクト
@anchor{faq/programming how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance}@anchor{58f6}
@subsubsection どうすればサブクラスはイミュータブルなインスタンスに格納されたデータを制御できますか？


イミュータブル型をサブクラス化する場合、 @ref{8bf,,__init__()} ではなく @ref{7a0,,__new__()} メソッドを継承します。  前者はインスタンスが生成された `後' に動くため、イミュータブルなインスタンスのデータを変えるには遅すぎます。

これらのイミュータブルクラスはすべて、親クラスと異なるシグネチャを持ちます:

@example
from datetime import date

class FirstOfMonthDate(date):
    "Always choose the first day of the month"
    def __new__(cls, year, month, day):
        return super().__new__(cls, year, month, 1)

class NamedInt(int):
    "Allow text names for some numbers"
    xlat = @{'zero': 0, 'one': 1, 'ten': 10@}
    def __new__(cls, value):
        value = cls.xlat.get(value, value)
        return super().__new__(cls, value)

class TitleStr(str):
    "Convert str to name suitable for a URL path"
    def __new__(cls, s):
        s = s.lower().replace(' ', '-')
        s = '@w{'}.join([c for c in s if c.isalnum() or c == '-'])
        return super().__new__(cls, s)
@end example

クラスはこのように使えます:

@example
>>> FirstOfMonthDate(2012, 2, 14)
FirstOfMonthDate(2012, 2, 1)
>>> NamedInt('ten')
10
>>> NamedInt(20)
20
>>> TitleStr('Blog: Why Python Rocks')
'blog-why-python-rocks'
@end example

@node メソッド呼び出しをキャッシュするには どうしたらいいですか？,,どうすればサブクラスはイミュータブルなインスタンスに格納されたデータを制御できますか？,オブジェクト
@anchor{faq/programming faq-cache-method-calls}@anchor{2baf}@anchor{faq/programming how-do-i-cache-method-calls}@anchor{58f7}
@subsubsection メソッド呼び出しをキャッシュするには どうしたらいいですか？


メソッドキャッシュの主な道具は２つあり、 @ref{763,,functools.cached_property()} と @ref{be2,,functools.lru_cache()} です。前者はインスタンスレベル、後者はクラスレベルで結果を保存します。

`cached_property' アプローチは、引数を取らないメソッドでのみ働きます。これはインスタンスへの参照を作りません。キャッシュされたメソッドの結果は、インスタンスが生きている間だけ保持されます。

利点は、インスタンスが使われなくなった場合、キャッシュされたメソッドの結果がすぐに解放されることです。欠点は、インスタンスが溜まると、溜められたメソッドの結果も増えてしまうことです。それらは際限なく増える恐れがあります。

`lru_cache' アプローチは、 @ref{824,,hashable} な引数を持つメソッドで働きます。 weak references を渡すための特別な努力がない限り、インスタンスへの参照を作ります。

least recently used アルゴリズム（訳注：LRU 直近に使われたものを残す）の利点は、キャッシュが指定された `maxsize' で制限されることです。欠点は、キャッシュから期限切れで追い出されるかクリアされるまで、インスタンスが生き続けることです。

この例は各種テクニックを示します:

@example
class Weather:
    "Lookup weather information on a government website"

    def __init__(self, station_id):
        self._station_id = station_id
        # The _station_id is private and immutable

    def current_temperature(self):
        "Latest hourly observation"
        # Do not cache this because old results
        # can be out of date.

    @@cached_property
    def location(self):
        "Return the longitude/latitude coordinates of the station"
        # Result only depends on the station_id

    @@lru_cache(maxsize=20)
    def historic_rainfall(self, date, units='mm'):
        "Rainfall on a given date"
        # Depends on the station_id, date, and units.
@end example

上の例では、 `station_id' が常に変わらないことを前提としています。関連するインスタンスの属性が可変である場合、 `cached_property' アプローチは属性の変更を検出できないため、機能しなくなります。

`station_id' が可変の場合に `lru_cache' アプローチを機能させるには、クラスで @ref{cf2,,__eq__()} と @ref{cf3,,__hash__()} メソッドを定義する必要があります。これにより、キャッシュは関連する属性の更新を検出できます:

@example
class Weather:
    "Example with a mutable station identifier"

    def __init__(self, station_id):
        self.station_id = station_id

    def change_station(self, station_id):
        self.station_id = station_id

    def __eq__(self, other):
        return self.station_id == other.station_id

    def __hash__(self):
        return hash(self.station_id)

    @@lru_cache(maxsize=20)
    def historic_rainfall(self, date, units='cm'):
        'Rainfall on a given date'
        # Depends on the station_id, date, and units.
@end example

@node モジュール<5>,,オブジェクト,プログラミング FAQ
@anchor{faq/programming modules}@anchor{58f8}
@subsection モジュール


@menu
* .pyc ファイルを作るにはどうしますか？: pyc ファイルを作るにはどうしますか？. 
* 現在のモジュール名を知るにはどうしますか？:: 
* 相互にインポートしあうモジュールを作るにはどうしたらいいですか？:: 
* __import__('x.y.z') は <module 'x'> を返しますが、z を得るためにはどうしますか？: __import__ 'x y z' は <module 'x'> を返しますが、z を得るためにはどうしますか？. 
* インポートされたモジュールを編集してから再インポートしましたが、変化が現れません。なぜですか？:: 

@end menu

@node pyc ファイルを作るにはどうしますか？,現在のモジュール名を知るにはどうしますか？,,モジュール<5>
@anchor{faq/programming how-do-i-create-a-pyc-file}@anchor{58f9}
@subsubsection .pyc ファイルを作るにはどうしますか？


モジュールが初めてインポートされたとき (もしくは、現在のコンパイルされたファイルが作られてから、ソースファイルが変更されたとき) 、コンパイルされたコードが入っている @code{.pyc} ファイルが、 @code{.py} ファイルのあるディレクトリのサブディレクトリ @code{__pycache__} に作成されます。 @code{.pyc} ファイルのファイル名は、 @code{.py} ファイルの名前で始まり、 @code{.pyc} で終わり、中間部分はこのファイルを作った @code{python} バイナリに依存した文字列になります。 (詳細は 
@geindex Python Enhancement Proposals; PEP 3147
PEP 3147@footnote{https://peps.python.org/pep-3147/} を参照してください。)

@code{.pyc} が作られない理由の 1 つは、ソースファイルがあるディレクトリの権限の問題、つまり @code{__pycache__} サブディレクトリが作れない問題です。これは、例えば、ウェブサーバーでテストを行っているときのような、開発者のユーザと実行者のユーザが別な場合に、起こり得ます。

@geindex PYTHONDONTWRITEBYTECODE
@geindex 環境変数; PYTHONDONTWRITEBYTECODE
@ref{15e7,,PYTHONDONTWRITEBYTECODE} 環境変数がセットされない限り、モジュールをインポートしていて、 Python に @code{__pycache__} サブディレクトリを作り、そこにコンパイルされたモジュールが置ける能力 (権限、ディスクの空きスペース、など) がある場合は、 .pyc ファイルは自動的に作られます。

最上位のスクリプトを Python で実行するのはインポートとはみなされず、@code{.pyc} は作成されません。例えば、最上位のモジュール @code{foo.py} が別のモジュール @code{xyz.py} をインポートしている場合、(シェルコマンドとして @code{python foo.py} と打ち込んで) @code{foo} を実行すると、@code{xyz} はインポートされるので @code{xyz} の @code{.pyc} は作成されますが、@code{foo.py} はインポートされたわけではないので @code{foo} の @code{.pyc} は作られません。

@code{foo} の @code{.pyc} ファイルを作成する -- つまり、インポートされていないモジュールの @code{.pyc} ファイルを作成する -- 必要がある場合、 @ref{b8,,py_compile} モジュールと @ref{21,,compileall} モジュールを使えば可能です。

@ref{b8,,py_compile} モジュールは手動で任意のモジュールをコンパイルできます。やり方の一つは、このモジュールの @code{compile()} 関数をインタラクティブに実行することです:

@example
>>> import py_compile
>>> py_compile.compile('foo.py')
@end example

このように実行すると、@code{foo.py} と同じ場所の @code{__pycache__} サブディレクトリに @code{.pyc} が書き出されます (出力ファイルの位置は、オプション引数 @code{cfile} で上書きすることもできます)。

@ref{21,,compileall} モジュールを使えば自動的に一つや複数のディレクトリのすべてのファイルをコンパイルできます。シェルプロンプトから @code{compileall.py} を起動して、コンパイルしたいファイルを含むディレクトリのパスを指定してください:

@example
python -m compileall .
@end example

@node 現在のモジュール名を知るにはどうしますか？,相互にインポートしあうモジュールを作るにはどうしたらいいですか？,pyc ファイルを作るにはどうしますか？,モジュール<5>
@anchor{faq/programming how-do-i-find-the-current-module-name}@anchor{58fa}
@subsubsection 現在のモジュール名を知るにはどうしますか？


モジュールは前もって定義されたグローバル変数 @code{__name__} を検索することで自身の名前を決定できます。この値が @code{'__main__'} であるとき、そのプログラムはスクリプトとして実行されています。インポートされることによって使われる大抵のモジュールはコマンドラインインターフェースや自己テストも提供していて、@code{__name__} をチェックしてからそのコードだけを実行します:

@example
def main():
    print('Running test...')
    ...

if __name__ == '__main__':
    main()
@end example

@node 相互にインポートしあうモジュールを作るにはどうしたらいいですか？,__import__ 'x y z' は <module 'x'> を返しますが、z を得るためにはどうしますか？,現在のモジュール名を知るにはどうしますか？,モジュール<5>
@anchor{faq/programming how-can-i-have-modules-that-mutually-import-each-other}@anchor{58fb}
@subsubsection 相互にインポートしあうモジュールを作るにはどうしたらいいですか？


以下のモジュールがあったとしましょう:

@code{foo.py}:

@example
from bar import bar_var
foo_var = 1
@end example

@code{bar.py}:

@example
from foo import foo_var
bar_var = 2
@end example

問題はインタプリタが以下の段階を実行することです:


@itemize *

@item 
main が @code{foo} をインポートする

@item 
@code{foo} の空のグローバルが生成される

@item 
@code{foo} がコンパイルされ実行を始める

@item 
@code{foo} が @code{bar} をインポートする

@item 
@code{bar} の空のグローバルが生成される

@item 
@code{bar} がコンパイルされ実行を始める

@item 
@code{bar} が @code{foo} をインポートする(すでに @code{foo} という名前のモジュールがあるので no-op となる)

@item 
インポートメカニズムは @code{foo} のグローバルから @code{foo_var} を読んで、 @code{bar.foo_var = foo.foo_var} に設定しようとします。
@end itemize

この最後の段階は失敗します。Python が @code{foo} を解釈し終わっていなくて、@code{foo} のグローバルなシンボルの辞書はまだ空ですから。

@code{import foo} を使って、グローバルコードの @code{foo.foo_var} にアクセスしようとしたときにも、これと同じことが起こります。

この問題には (少なくとも) 三つの解決策があります。

Guido van Rossum は @code{from <module> import ...} を全く使わないで、すべてのコードを関数の中に入れることを勧めています。グローバル変数とクラス変数の初期化は定数とビルトイン関数のみで行われるべきです。これでインポートされたすべてのモジュールは @code{<module>.<name>} として参照されることになります。

Jim Roskind はそれぞれのモジュールに対して以下の順に進めることを提案しています:


@itemize *

@item 
エクスポート (インポートされた基底クラスを必要としないグローバル、関数、クラス)

@item 
@code{import} 文

@item 
アクティブなコード (インポートされた値によって初期化されるグローバルを含む)。
@end itemize

インポートが奇妙な場所に現れることから Van Rossum はこの方法をそれほど好みませんが、これは有効です。

Matthias Urlichs は第一に再帰インポートが必要ないようにコードを構築しなおすことを推奨しています。

これらの解決策はそれぞれ両立させることもできます。

@node __import__ 'x y z' は <module 'x'> を返しますが、z を得るためにはどうしますか？,インポートされたモジュールを編集してから再インポートしましたが、変化が現れません。なぜですか？,相互にインポートしあうモジュールを作るにはどうしたらいいですか？,モジュール<5>
@anchor{faq/programming import-x-y-z-returns-module-x-how-do-i-get-z}@anchor{58fc}
@subsubsection __import__('x.y.z') は <module 'x'> を返しますが、z を得るためにはどうしますか？


@ref{7b,,importlib} に @ref{73c,,import_module()} という便利な関数があるので、代わりにそちらを使用することを検討してください。

@example
z = importlib.import_module('x.y.z')
@end example

@node インポートされたモジュールを編集してから再インポートしましたが、変化が現れません。なぜですか？,,__import__ 'x y z' は <module 'x'> を返しますが、z を得るためにはどうしますか？,モジュール<5>
@anchor{faq/programming when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen}@anchor{58fd}
@subsubsection インポートされたモジュールを編集してから再インポートしましたが、変化が現れません。なぜですか？


効率と一貫性上の理由から、Python はモジュールが最初にインポートされた時にのみモジュールファイルを読み込みます。そうしないと、たくさんのモジュールでできていて、それぞれが同じ基本モジュールをインポートしているようなプログラムでは、その基本モジュールの解析と再解析が繰り返されることになります。変更されさたモジュールの再読込を強制するには、こうしてください:

@example
import importlib
import modname
importlib.reload(modname)
@end example

注意:この手法は 100%安全とは言えません。とりわけ

@example
from modname import some_objects
@end example

のような文を含むモジュールは、インポートされたオブジェクトの古いバージョンを使い続けます。そのモジュールにクラス定義が含まれていたら、存在するクラスインスタンスは新しいクラス定義を使うようにアップデート `されません'。これによって以下の矛盾した振舞いがなされえます:

@example
>>> import importlib
>>> import cls
>>> c = cls.C()                # Create an instance of C
>>> importlib.reload(cls)
<module 'cls' from 'cls.py'>
>>> isinstance(c, cls.C)       # isinstance is false?!?
False
@end example

この問題の本質は、クラスオブジェクトの "固有値" を印字することで明らかになります:

@example
>>> hex(id(c.__class__))
'0x7352a0'
>>> hex(id(cls.C))
'0x4198d0'
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node デザインと歴史 FAQ,ライブラリと拡張 FAQ,プログラミング FAQ,Python よくある質問
@anchor{faq/design doc}@anchor{58fe}@anchor{faq/design design-and-history-faq}@anchor{58ff}@anchor{faq/design translation-repo}@anchor{5900}
@section デザインと歴史 FAQ



@menu
* Python はなぜ文のグループ化にインデントを使うのですか？:: 
* なぜ単純な算術演算が奇妙な結果になるのですか？:: 
* なぜ浮動小数点数の計算はこんなに不正確なんですか？:: 
* なぜ Python の文字列はイミュータブルなのですか？:: 
* なぜメソッドの定義や呼び出しにおいて 'self' を明示しなければならないのですか？:: 
* 式中で代入ができないのはなぜですか？:: 
* Python にメソッドを使う機能 (list.index() 等) と関数を使う機能 (len(list) 等) があるのはなぜですか？: Python にメソッドを使う機能 list index 等 と関数を使う機能 len list 等 があるのはなぜですか？. 
* join() がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？: join がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？. 
* 例外はどれくらい速いのですか？:: 
* Python に switch や case 文がないのはなぜですか？:: 
* OS 特有のスレッド実装に依らずにインタプリタでスレッドをエミュレートすることはできないのですか？:: 
* なぜラムダ式は文を含むことができないのですか?:: 
* Python は C やその他の言語のように機械語にコンパイルできますか？:: 
* Python はメモリをどのように管理するのですか？:: 
* CPython はなぜ伝統的なガベージコレクションスキームを使わないのですか？:: 
* なぜ CPython の終了時にすべてのメモリが解放されるわけではないのですか？:: 
* なぜタプルとリストという別のデータ型が用意されているのですか？:: 
* CPythonでリストはどのように実装されているのですか？:: 
* CPythonで辞書はどのように実装されていますか？:: 
* なぜ辞書のキーはイミュータブルでなくてはならないのですか？:: 
* なぜ list.sort() はソートされたリストを返さないのですか？: なぜ list sort はソートされたリストを返さないのですか？. 
* Python ではどのようにインターフェース仕様を特定し適用するのですか？:: 
* なぜ goto が無いのですか？:: 
* なぜ raw 文字列 (r-strings) はバックスラッシュで終わってはいけないのですか？: なぜ raw 文字列 r-strings はバックスラッシュで終わってはいけないのですか？. 
* 属性の代入に "with" 文が使えないのはなぜですか？:: 
* なぜジェネレータは with 文をサポートしないのですか？:: 
* if/while/def/class 文にコロンが必要なのはなぜですか？:: 
* なぜ Python ではリストやタプルの最後にカンマがあっても良いのですか？:: 

@end menu

@node Python はなぜ文のグループ化にインデントを使うのですか？,なぜ単純な算術演算が奇妙な結果になるのですか？,,デザインと歴史 FAQ
@anchor{faq/design why-does-python-use-indentation-for-grouping-of-statements}@anchor{5901}
@subsection Python はなぜ文のグループ化にインデントを使うのですか？


Guido van Rossum の信じるところによれば、インデントによるグループ化は非常にエレガントで、普通の Python プログラムを大いに読みやすくします。しばらくすればほとんどの人はこの仕様を気に入るようになります。

開始/終了の括弧がないので、構文解析器と人間の読者の間にグループ化の解釈の違いは起こりえません。時折、C のプログラマはこのようなコード片に出くわします:

@example
if (x <= y)
        x++;
        y--;
z++;
@end example

条件式が真のとき、 @code{x++} 行のみが実行されます。しかしインデントによって、多くの人が別のことを考えてしまいます。経験豊富なCプログラマでさえ、 @code{x > y} なのに @code{y} がデクリメントされるのはなぜだろうと、このコードをしばらく凝視することがあります。

Python は開始/終了の括弧がないので、コーディングスタイルの争いに余り影響されません。C言語では中括弧の置き方についてさまざまな流儀があります。特定のスタイルを使ってコードを読み書きするのに慣れたあと、別のスタイルでコードを読んだり(あるいは書く必要に迫られたり)するときに、何となく心配になるのはよくあることです。

多くのコーディングスタイルは begin/end の括弧にそれぞれ一行を使います。これではプログラムは冗長になって画面を浪費し、プログラムの見通しが悪くなります。一つの関数は一画面 (例えば 20 から 30 行) に収めるのが理想です。20 行の Python は 20 行の C よりもはるかに多くの作業ができます。これは begin/end の括弧がないからだけではありません -- 宣言が不要なことや高レベルなデータ型もその理由です -- が、インデントに基づく構文は確かに役に立っています。

@node なぜ単純な算術演算が奇妙な結果になるのですか？,なぜ浮動小数点数の計算はこんなに不正確なんですか？,Python はなぜ文のグループ化にインデントを使うのですか？,デザインと歴史 FAQ
@anchor{faq/design why-am-i-getting-strange-results-with-simple-arithmetic-operations}@anchor{5902}
@subsection なぜ単純な算術演算が奇妙な結果になるのですか？


次の質問を参照してください。

@node なぜ浮動小数点数の計算はこんなに不正確なんですか？,なぜ Python の文字列はイミュータブルなのですか？,なぜ単純な算術演算が奇妙な結果になるのですか？,デザインと歴史 FAQ
@anchor{faq/design why-are-floating-point-calculations-so-inaccurate}@anchor{5903}
@subsection なぜ浮動小数点数の計算はこんなに不正確なんですか？


ユーザーはよく次のような結果に驚きます:

@example
>>> 1.2 - 1.0
0.19999999999999996
@end example

そしてこれが Python のバグだと考えます。が、これはバグではありません。この結果に Python はほとんど関与しておらず、むしろ基底のプラットフォームによる浮動小数点数の扱い方が関与しています。

CPython における @ref{196,,float} 型は記憶に C 言語の @code{double} 型を使います。 @ref{196,,float} オブジェクトの値は固定精度 (典型的には 53 bit) の 2 進浮動小数点数として格納され、 Python はプロセッサのハードウェアが実装している C 言語上の演算を使います。つまり、浮動小数点数に関して Python は C 言語や Java のような多くの一般的な言語と同じように振る舞います。

Many numbers that can be written easily in decimal notation cannot be expressed
exactly in binary floating point.  For example, after:

@example
>>> x = 1.2
@end example

@code{x} に保存された値は 10 進数の @code{1.2} の (とても高い精度の) 近似値であって、厳密な @code{1.2} ではありません。一般的なコンピューターでは、実際に格納される値は:

@example
1.0011001100110011001100110011001100110011001100110011 (binary)
@end example

で、正確には次の値です:

@example
1.1999999999999999555910790149937383830547332763671875 (decimal)
@end example

53bit の典型的な精度は、Python の float に 10 進数で 15〜16桁の精度を与えます。

For a fuller explanation, please see the @ref{2101,,floating-point arithmetic} chapter in the Python tutorial.

@node なぜ Python の文字列はイミュータブルなのですか？,なぜメソッドの定義や呼び出しにおいて 'self' を明示しなければならないのですか？,なぜ浮動小数点数の計算はこんなに不正確なんですか？,デザインと歴史 FAQ
@anchor{faq/design why-are-python-strings-immutable}@anchor{5904}
@subsection なぜ Python の文字列はイミュータブルなのですか？


これにはいくつかの利点があります。

一つはパフォーマンスです。文字列がイミュータブルなら、生成時に領域を割り当てることができるので、必要な記憶域は固定されて、変更されません。これはタプルとリストを区別する理由の一つでもあります。

他の利点は、Python の文字列は数と同じくらい "基本的" なものと考えられることです。8 という値を他の何かに変える手段が無いように、文字列 "eight" を他の何かに変える手段も無いのです。

@node なぜメソッドの定義や呼び出しにおいて 'self' を明示しなければならないのですか？,式中で代入ができないのはなぜですか？,なぜ Python の文字列はイミュータブルなのですか？,デザインと歴史 FAQ
@anchor{faq/design why-must-self-be-used-explicitly-in-method-definitions-and-calls}@anchor{5905}@anchor{faq/design why-self}@anchor{58ea}
@subsection なぜメソッドの定義や呼び出しにおいて 'self' を明示しなければならないのですか？


このアイデアは Modula-3 から取り入れられました。これは様々な理由からとても便利だと言えます。

まず、ローカル変数ではなく、メソッドやインスタンス属性を扱っていることがより明確になります。 @code{self.x} や @code{self.meth()} と書いてあれば、そのクラスの定義を憶えていなくても、それがインスタンス変数やメソッドであることは明らかです。C++ では、(グローバルが滅多になかったり、簡単に見分けがつくなら) ローカル変数宣言がないことからある程度わかるでしょう。-- しかし Python にはローカル変数宣言がないので、クラス定義を調べて確かめなくてはなりません。C++ や Java のコーディングスタンダードに、インスタンス属性に @code{m_} 接頭辞をつけるものがあるので、この明示性はそれらの言語においても有用です。

第二に、特定のクラスからメソッドを明示的に参照または呼び出ししたい時に、特別な構文が必要なくなります。C++ では、派生クラスでオーバーライドされた基底クラスからメソッドを使うには、 @code{::} 演算子を使わなければなりません。 -- Python では、 @code{baseclass.methodname(self, <argument list>)} と書けます。これは特に、 @ref{8bf,,__init__()} メソッドに便利ですし、派生クラスのメソッドが、基底クラスにある同じ名前のメソッドを拡張するために、基底クラスのメソッドをどうにかして呼び出したい時にも便利です。

最後に、インスタンス変数に対する、代入の構文の問題を解決できます。Python のローカル変数は、関数の中で (global が明示的に宣言されることなく) 値が代入された変数 (と定義されています！) です。なので、ある代入が意図するのが、ローカル変数へではなくインスタンス変数への代入であると、インタプリタが判断する手段が必要です。そしてそれは構文を見るだけで分かる方が (効率が) 良いのです。C++ ではその区別を宣言時に行いますが、Python では宣言がないので、この方法でしか区別できなかったら残念です。 @code{self.var} を明示すればうまく解決できます。同様に、インスタンス変数を使うのにも @code{self.var} と書かなければならないので、メソッドの中の self が付いていない名前への参照は、そのインスタンスのディレクトリを検索するまでもなくローカル変数とわかります。別の言い方をすれば、ローカル変数とインスタンス変数は二つの異なる名前空間に存在し、Python にどちらの名前空間を使うかを伝えなくてはならないのです。

@node 式中で代入ができないのはなぜですか？,Python にメソッドを使う機能 list index 等 と関数を使う機能 len list 等 があるのはなぜですか？,なぜメソッドの定義や呼び出しにおいて 'self' を明示しなければならないのですか？,デザインと歴史 FAQ
@anchor{faq/design id2}@anchor{5906}@anchor{faq/design why-can-t-i-use-an-assignment-in-an-expression}@anchor{2038}
@subsection 式中で代入ができないのはなぜですか？


Python 3.8 以降ならできるよ!

セイウチ演算子 @code{:=} を使った代入式は、式の中で変数に代入します:

@example
while chunk := fp.read(200):
   print(chunk)
@end example

より詳しくは 
@geindex Python Enhancement Proposals; PEP 572
PEP 572@footnote{https://peps.python.org/pep-0572/} を参照してください。

@node Python にメソッドを使う機能 list index 等 と関数を使う機能 len list 等 があるのはなぜですか？,join がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？,式中で代入ができないのはなぜですか？,デザインと歴史 FAQ
@anchor{faq/design why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list}@anchor{5907}
@subsection Python にメソッドを使う機能 (list.index() 等) と関数を使う機能 (len(list) 等) があるのはなぜですか？


Guidoいわく：

@quotation

(a) For some operations, prefix notation just reads better than
postfix -- prefix (and infix!) operations have a long tradition in
mathematics which likes notations where the visuals help the
mathematician thinking about a problem. Compare the easy with which we
rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
doing the same thing using a raw OO notation.

(b) When I read code that says len(x) I `know' that it is asking for
the length of something. This tells me two things: the result is an
integer, and the argument is some kind of container. To the contrary,
when I read x.len(), I have to already know that x is some kind of
container implementing an interface or inheriting from a class that
has a standard len(). Witness the confusion we occasionally have when
a class that is not implementing a mapping has a get() or keys()
method, or something that isn't a file has a write() method.


@center --- @indicateurl{https://mail.python.org/pipermail/python-3000/2006-November/004643.html}

@end quotation

@node join がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？,例外はどれくらい速いのですか？,Python にメソッドを使う機能 list index 等 と関数を使う機能 len list 等 があるのはなぜですか？,デザインと歴史 FAQ
@anchor{faq/design why-is-join-a-string-method-instead-of-a-list-or-tuple-method}@anchor{5908}
@subsection join() がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？


文字列は Python 1.6 から他の標準型に大きく近づきました。それ以前は常に string モジュールの関数を使ってできていたことと同等の機能を持つメソッドがこの時に追加されました。その新しいメソッドの多くは広く受け入れられましたが、一部のプログラマに不快を感じさせていると思われるものがこれで:

@example
", ".join(['1', '2', '4', '8', '16'])
@end example

結果はこうなります:

@example
"1, 2, 4, 8, 16"
@end example

この使い方には二つの議論があります。

一つ目は、「文字列リテラル (文字列定数) のメソッドを使うのは醜すぎる」というようなものです。確かにそうかも知れませんが、文字列リテラルは単なる固定された値に過ぎないというのが答えです。文字列に束縛された名前にメソッドが許されるなら、リテラルに使えないようにする論理的な理由はないでしょう。

二つ目の反対理由は、典型的には「私は実際、要素を文字列定数とともに結合させるよう、シーケンスに命じているのだ」というものです。残念ながら、そうではないのです。いくつかの理由から @ref{10aa,,split()} を文字列のメソッドとしておいた方がはるかに簡単です。これを見ると分かりやすいでしょう

@example
"1, 2, 4, 8, 16".split(", ")
@end example

これは文字列リテラルに対する、与えられたセパレータ (または、デフォルトでは任意の空白文字の連続) で区切られた部分文字列を返せという指示です。

@ref{2609,,join()} は、セパレータ文字列に、文字列のシーケンスをイテレートして隣り合う要素の間に自身を挿入するように指示しているので、文字列のメソッドです。このメソッドは、独自に定義された新しいクラスを含め、シーケンスの規則を満たすいかなる引数にも使えます。バイト列やバイト配列にも同様のメソッドがあります。

@node 例外はどれくらい速いのですか？,Python に switch や case 文がないのはなぜですか？,join がリストやタプルのメソッドではなく文字列のメソッドなのはなぜですか？,デザインと歴史 FAQ
@anchor{faq/design how-fast-are-exceptions}@anchor{5909}
@subsection 例外はどれくらい速いのですか？


@ref{8f8,,try}/@ref{1ab,,except} ブロックは例外が送出されなければ極端に効率的です。実際に例外を捕捉するのは高価です。Python 2.0 より前のバージョンでは、このイディオムを使うのが一般的でした:

@example
try:
    value = mydict[key]
except KeyError:
    mydict[key] = getvalue(key)
    value = mydict[key]
@end example

これは、辞書がほとんどの場合にキーを持っていると予想できるときにのみ意味をなします。そうでなければ、このように書きます:

@example
if key in mydict:
    value = mydict[key]
else:
    value = mydict[key] = getvalue(key)
@end example

この特殊な場合では @code{value = dict.setdefault(key, getvalue(key))} も使えますが、これは @code{getvalue()} 呼び出しが十分安価な場合に限ります。なぜならそれが全ての場合に評価されるからです。

@node Python に switch や case 文がないのはなぜですか？,OS 特有のスレッド実装に依らずにインタプリタでスレッドをエミュレートすることはできないのですか？,例外はどれくらい速いのですか？,デザインと歴史 FAQ
@anchor{faq/design why-isn-t-there-a-switch-or-case-statement-in-python}@anchor{590a}
@subsection Python に switch や case 文がないのはなぜですか？


一般的に、構造化された switch 文は、式が特定の値または値の集合を持つとき、１つのコードブロックを実行します。 Python 3.10 以降では、リテラル値や名前空間内の定数を、 @code{match ... case} 文で簡単にマッチさせることができます。より古い手段は一連の @code{if... elif... elif... else} です。

非常に大きな数の選択肢から選ぶとき、値を呼び出す関数に対応づける辞書を作れます。例えば:

@example
functions = @{'a': function_1,
             'b': function_2,
             'c': self.method_1@}

func = functions[value]
func()
@end example

オブジェクトのメソッドを呼び出すには、さらに単純に @ref{dca,,getattr()} 組み込み関数で特定の名前のメソッドを検索できます:

@example
class MyVisitor:
    def visit_a(self):
        ...

    def dispatch(self, value):
        method_name = 'visit_' + str(value)
        method = getattr(self, method_name)
        method()
@end example

メソッドの名前にこの例の @code{visit_} のような接頭辞を使うことを勧めます。このような接頭辞がないと、信頼できないソースから値が与えられたときに、オブジェクトの任意のメソッドを呼び出す攻撃をされる可能性があります。

C の switch-case-default のような、フォールスルーのある switch を模倣することもできますが、はるかに難しいうえに必要性も少ないでしょう。

@node OS 特有のスレッド実装に依らずにインタプリタでスレッドをエミュレートすることはできないのですか？,なぜラムダ式は文を含むことができないのですか?,Python に switch や case 文がないのはなぜですか？,デザインと歴史 FAQ
@anchor{faq/design can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation}@anchor{590b}
@subsection OS 特有のスレッド実装に依らずにインタプリタでスレッドをエミュレートすることはできないのですか？


答 1: 残念なことに、インタプリタは Python のスタックフレームごとに少なくとも一つの C のスタックフレームを push します。同様に、拡張もほとんどランダムなときに Python にコールバックすることがあります。よって、完全なスレッド実装には C のスレッドサポートが必要です。

答 2: 幸運なことに、Stackless Python@footnote{https://github.com/stackless-dev/stackless/wiki} があります。これは完全に再デザインされたインタープリタで、Cのスタックを回避しています。

@node なぜラムダ式は文を含むことができないのですか?,Python は C やその他の言語のように機械語にコンパイルできますか？,OS 特有のスレッド実装に依らずにインタプリタでスレッドをエミュレートすることはできないのですか？,デザインと歴史 FAQ
@anchor{faq/design why-can-t-lambda-expressions-contain-statements}@anchor{590c}
@subsection なぜラムダ式は文を含むことができないのですか?


Python のラムダ式が文を含むことができないのは、Python の文法的な枠組みが式の中にネストされた文を扱うことができないからです。しかし、Python では、これは深刻な問題ではありません。他の言語のラムダに機能が追加されているのと違い、Python のラムダは単なる、関数を定義するのが面倒すぎる場合のための簡略な記法に過ぎないのです。

関数は既に Python の第一級オブジェクトで、ローカルスコープ内で宣言できます。従って、ローカルで定義された関数ではなくラムダを使う利点は、関数の名前を考える必要が無いことだけです -- しかし、(ラムダ式が生み出すオブジェクトと厳密に同じ型の) 関数オブジェクトが代入される先はただのローカル変数です！

@node Python は C やその他の言語のように機械語にコンパイルできますか？,Python はメモリをどのように管理するのですか？,なぜラムダ式は文を含むことができないのですか?,デザインと歴史 FAQ
@anchor{faq/design can-python-be-compiled-to-machine-code-c-or-some-other-language}@anchor{590d}
@subsection Python は C やその他の言語のように機械語にコンパイルできますか？


Cython@footnote{https://cython.org/} compiles a modified version of Python with
optional annotations into C extensions.  Nuitka@footnote{https://nuitka.net/} is
an up-and-coming compiler of Python into C++ code, aiming to support the full
Python language.

@node Python はメモリをどのように管理するのですか？,CPython はなぜ伝統的なガベージコレクションスキームを使わないのですか？,Python は C やその他の言語のように機械語にコンパイルできますか？,デザインと歴史 FAQ
@anchor{faq/design how-does-python-manage-memory}@anchor{590e}
@subsection Python はメモリをどのように管理するのですか？


Python のメモリ管理の詳細は実装に依ります。Python の標準の C 実装 @ref{905,,CPython} は参照カウントを使って、アクセスできないオブジェクトを探します。また別のメカニズムを使って参照サイクルを集めます。これはサイクル検出アルゴリズムを定期的に実行し、アクセスできないサイクルを探し、巻き込まれたオブジェクトを削除します。 @ref{64,,gc} モジュールの関数で、ガベージコレクションを実行し、デバッグ統計を取得し、コレクタのパラメタを変更できます。

Other implementations (such as Jython@footnote{https://www.jython.org} or
PyPy@footnote{https://pypy.org}), however, can rely on a different mechanism
such as a full-blown garbage collector.  This difference can cause some
subtle porting problems if your Python code depends on the behavior of the
reference counting implementation.

Python の実装によっては、以下の (CPython では通る) コードはおそらく、ファイルディスクリプタを使い果たすでしょう:

@example
for file in very_long_list_of_files:
    f = open(file)
    c = f.read(1)
@end example

実際、CPython の参照カウントとデストラクタのスキームを使えば @code{f} への新しい代入ごとにファイルは閉じられます。しかし、伝統的な GC を使うと、これらのファイルオブジェクトが回収され (て閉じられる) までに不定な、場合によっては長い、間隔が空くことがあります。

Python の実装に依らずに動くコードを書くには、ファイルを明示的に閉じるか、 @ref{186,,with} 文を使ってください。これでメモリ管理のスキームに関係なく動きます:

@example
for file in very_long_list_of_files:
    with open(file) as f:
        c = f.read(1)
@end example

@node CPython はなぜ伝統的なガベージコレクションスキームを使わないのですか？,なぜ CPython の終了時にすべてのメモリが解放されるわけではないのですか？,Python はメモリをどのように管理するのですか？,デザインと歴史 FAQ
@anchor{faq/design why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme}@anchor{590f}
@subsection CPython はなぜ伝統的なガベージコレクションスキームを使わないのですか？


まず、それは C の標準的な機能ではないのでポータブルではありません。(確かに Boehm GC ライブラリはあります。しかし、これにはアセンブリコードが含まれ、`ほとんどの' 有名なプラットフォームに対応していますが全てではありません。また、ほとんど透過的ですが、完全に透過的ではありません。Python を対応させるにはパッチが必要です。)

伝統的な GC は Python が他のアプリケーションに組み込まれるときにも問題となります。スタンドアロンの Python で動く限りでは、標準の @code{malloc()} と @code{free()} を GC ライブラリから提供されるものに置き換えても問題ありませんが、Python を実装したアプリケーションは Python のものではない `独自の' 代替品を使おうとするかもしれません。現在のようにすることで、CPython は @code{malloc()} と @code{free()} が適切に実装されている限りどんなものにも対応させられます。

@node なぜ CPython の終了時にすべてのメモリが解放されるわけではないのですか？,なぜタプルとリストという別のデータ型が用意されているのですか？,CPython はなぜ伝統的なガベージコレクションスキームを使わないのですか？,デザインと歴史 FAQ
@anchor{faq/design why-isn-t-all-memory-freed-when-cpython-exits}@anchor{5910}
@subsection なぜ CPython の終了時にすべてのメモリが解放されるわけではないのですか？


Python モジュールのグローバルな名前空間から参照されるオブジェクトは、Python の終了時にメモリの割り当てを解除されるとは限りません。これは、循環参照があるときに起こりえます。解放できない C ライブラリ (例えば、Purify のようなツールなどが当てはまります) によって割り当てられたいくらかのメモリも含まれます。しかし、Python は終了時にメモリをクリーンアップすることには積極的で、全ての単一のオブジェクトを破棄しようとします。

再割り当て時に Python が特定のものを削除するように強制したいときは、 @ref{d,,atexit} モジュールを使って削除を強制する関数を実行してください。

@node なぜタプルとリストという別のデータ型が用意されているのですか？,CPythonでリストはどのように実装されているのですか？,なぜ CPython の終了時にすべてのメモリが解放されるわけではないのですか？,デザインと歴史 FAQ
@anchor{faq/design why-are-there-separate-tuple-and-list-data-types}@anchor{5911}
@subsection なぜタプルとリストという別のデータ型が用意されているのですか？


リストとタプルは、多くの点で似ていますが、一般には本質的に異なる方法で使われます。タプルは、Pascal の @code{レコード} や C の　@code{構造体} と同様なものと考えられます。型が異なっても良い関連するデータの小さな集合で、グループとして演算されます。例えば、デカルト座標は 2 つや 3 つの数のタプルとして適切に表せます。

一方、リストは、もっと他の言語の配列に近いものです。全て同じ型の可変数のオブジェクトを持ち、それらが一つ一つ演算される傾向にあります。例えば、 @ref{1312,,os.listdir('.')} はカレントディレクトリ内にあるファイルの文字列表現のリストを返します。この出力を演算する関数は一般に、ディレクトリに一つや二つの別のファイルを加えても壊れません。

タプルはイミュータブルなので、一度タプルが生成されたら、そのどの要素も新しい値に置き換えられません。リストはミュータブルなので、リストの要素はいつでも変更できます。イミュータブルな要素だけが辞書のキーとして使えるので、リストではなくタプルだけがキーとして使えます。

@node CPythonでリストはどのように実装されているのですか？,CPythonで辞書はどのように実装されていますか？,なぜタプルとリストという別のデータ型が用意されているのですか？,デザインと歴史 FAQ
@anchor{faq/design how-are-lists-implemented-in-cpython}@anchor{5912}
@subsection CPythonでリストはどのように実装されているのですか？


CPythonのリストは実際に変数分の長さの配列で、Lispスタイルの連結リストではありません。この実装は他のオブジェクトへの参照の連続した配列を使用していて、この配列へのポインタおよび配列長はリストの先頭の構造体に保存されています。

これにより、リストのインデクシング @code{a[i]} は、リストの大きさやインデクスの値に依存しないコストで演算できます。

要素が追加または挿入されるとき、この参照の配列は大きさが変更されます。要素追加の繰り返しのパフォーマンスを上げるために、少し工夫されています。配列が大きくなるとき、次の何回かは実際に大きさを変更する必要がないように、いくらかの追加の領域が割り当てられます。

@node CPythonで辞書はどのように実装されていますか？,なぜ辞書のキーはイミュータブルでなくてはならないのですか？,CPythonでリストはどのように実装されているのですか？,デザインと歴史 FAQ
@anchor{faq/design how-are-dictionaries-implemented-in-cpython}@anchor{5913}
@subsection CPythonで辞書はどのように実装されていますか？


CPython の辞書は大きさを変更できるハッシュテーブルとして実装されています。B 木と比べて、ほとんどの条件下で (特に一般的な演算である) 探索のパフォーマンスが良いですし、実装も単純です。

辞書は、辞書に保存されているそれぞれのキーに対応するハッシュコードを @ref{801,,hash()} ビルトイン関数で計算することで機能します。このハッシュコードはキーやプロセスごとのシードによって大きく変化します。例えば、 @code{'Python'} のハッシュ値は @code{-539294296} ですが、ビットが一つ違うだけの文字列 @code{'python'} のハッシュ値は @code{1142331976} です。そしてこのハッシュコードは、値が保存される内部配列での位置を計算するために使われます。保存しているキーのハッシュ値が全て異なるとすれば、一定の時間 − Big-O 記法では `O'(1) − でキーを検索できることになります。

@node なぜ辞書のキーはイミュータブルでなくてはならないのですか？,なぜ list sort はソートされたリストを返さないのですか？,CPythonで辞書はどのように実装されていますか？,デザインと歴史 FAQ
@anchor{faq/design why-must-dictionary-keys-be-immutable}@anchor{5914}
@subsection なぜ辞書のキーはイミュータブルでなくてはならないのですか？


辞書のハッシュテーブルの実装は、キーを見つけるために、キー値から計算されたハッシュ値を使います。もしキーがミュータブルなオブジェクトだったら、その値は変えられ、それによりハッシュ値も変わってしまいます。しかし、キーオブジェクトを変更したのが何者であれ、値が辞書のキーとして使われていたと気付けないので、辞書の中のエントリを適切な場所に動かせません。そして、同じオブジェクトを探そうとしても、ハッシュ値が違うため見つかりません。古い値を探そうとしても、そのハッシュバイナリから見つかるオブジェクトの値は異なるでしょうから、これも見つかりません。

リストでインデクシングされた辞書が必要なら、まず単純にリストをタプルに変換してください。関数 @code{tuple(L)} は、リスト @code{L} と同じエントリのタプルを生成します。タプルはイミュータブルなので、辞書のキーとして使えます。

いくつかの受け入れられなかった提案:


@itemize -

@item 
アドレス (オブジェクト ID) のハッシュリスト。これは、同じ値の新しいリストを作っても見つからないので駄目です。例えば:

@example
mydict = @{[1, 2]: '12'@}
print(mydict[[1, 2]])
@end example

@code{[1, 2]} の2行目のidは1行目のそれと異なってしまうために @ref{5e7,,KeyError} 例外を送出するでしょう。言い換えれば、辞書のキーは @code{==} を使って比較されるべきであり、 @ref{34c,,is} ではないということです。

@item 
リストをキーとして使うときにコピーを作る。リストはミュータブルなので、自分自身への参照を含むことができ、コードをコピーするときに無限ループにハマる可能性があるので、これは駄目です。

@item 
リストをキーとして使うことを認めるが、ユーザにそれを変更させないように伝える。もしユーザが忘れたり、偶然にリストが変更されてしまったりしたら、追跡困難なバグの可能性を生じてしまいます。またこれは、 @code{d.keys()} のすべての値は辞書のキーとして使えるという、辞書の重要な不変性も潰してしまいます。

@item 
リストが一旦辞書のキーとして使われたら、読み出し専用のマークを付ける。問題は、値を変えられるのはトップレベルオブジェクトだけではないことです。リストを含むタプルもキーとして使えます。全てを辞書のキーとして導入すると、そこから到達可能な全てのオブジェクトに読み出し専用のマークを付ける必要があります -- そして再び、自己参照オブジェクトが無限ループを引き起こします。
@end itemize

必要ならばこれを回避する方法がありますが、自己責任のもとで行ってください。ミュータブルな構造を、 @ref{cf2,,__eq__()} と @ref{cf3,,__hash__()} メソッドの両方を持つクラスインスタンスに含めることができます。その時、辞書 (またはハッシュに基づく別の構造体) に属するような全てのラッパーオブジェクトのハッシュ値が、そのオブジェクトが辞書 (その他の構造体) 中にある間固定され続けることを確実にしてください。

@example
class ListWrapper:
    def __init__(self, the_list):
        self.the_list = the_list

    def __eq__(self, other):
        return self.the_list == other.the_list

    def __hash__(self):
        l = self.the_list
        result = 98767 - len(l)*555
        for i, el in enumerate(l):
            try:
                result = result + (hash(el) % 9999999) * 1001 + i
            except Exception:
                result = (result % 7777777) + i * 333
        return result
@end example

なお、リストのメンバーの中にハッシュ化できないものがある可能性や、算術オーバーフローの可能性から、ハッシュ計算は複雑になります。

さらに、そのオブジェクトが辞書に含まれるか否かにかかわらず、 @code{o1 == o2} (すなわち @code{o1.__eq__(o2) is True}) ならばいつでも @code{hash(o1) == hash(o2)} (すなわち @code{o1.__hash__() == o2.__hash__()}) でなくてはなりません。その制限に適合できなければ、辞書やその他のハッシュに基づく構造体は間違いを起こします。

この @code{ListWrapper} の例では、異常を避けるため、ラッパオブジェクトが辞書内にある限りラップされたリストが変更されてはなりません。この条件と満たせなかった時の結果について知恵を絞る覚悟がない限り、これをしてはいけません。よく考えてください。

@node なぜ list sort はソートされたリストを返さないのですか？,Python ではどのようにインターフェース仕様を特定し適用するのですか？,なぜ辞書のキーはイミュータブルでなくてはならないのですか？,デザインと歴史 FAQ
@anchor{faq/design why-doesn-t-list-sort-return-the-sorted-list}@anchor{5915}
@subsection なぜ list.sort() はソートされたリストを返さないのですか？


パフォーマンスが問題となる状況では、ソートするためだけにリストのコピーを作るのは無駄が多いです。そこで、 @ref{dc8,,list.sort()} はインプレースにリストをソートします。このことを忘れないため、この関数はソートされたリストを返しません。こうすることで、ソートされたコピーが必要で、ソートされていないものも残しておきたいときに、うっかり上書きしてしまうようなことがなくなります。

新しいリストを返したいなら、代わりに組み込みの @ref{dc7,,sorted()} 関数を使ってください。この関数は、与えられたイテレート可能オブジェクトから新しいリストを生成し、ソートして返します。例えば、辞書のキーをソートされた順序でイテレートする方法は:

@example
for key in sorted(mydict):
    ...  # do whatever with mydict[key]...
@end example

@node Python ではどのようにインターフェース仕様を特定し適用するのですか？,なぜ goto が無いのですか？,なぜ list sort はソートされたリストを返さないのですか？,デザインと歴史 FAQ
@anchor{faq/design how-do-you-specify-and-enforce-an-interface-spec-in-python}@anchor{5916}
@subsection Python ではどのようにインターフェース仕様を特定し適用するのですか？


C++ や Java のような言語が提供するような、モジュールに対するインターフェース仕様の特定は、モジュールのメソッドや関数の原型を表現します。インターフェースの特定がコンパイル時に適用されることが、大きなプログラムの構成に役立つと、広く感じられています。

Python 2.6 で、抽象基底クラス (Abstract Base Class, ABC) が定義できるようになる @ref{4,,abc} モジュールが追加されました。なので @ref{2ad,,isinstance()} と @ref{9c4,,issubclass()} を使って、インスタンスやクラスが、ある ABC を実装しているかどうかチェックできます。@ref{1f,,collections.abc} モジュールでは、 @ref{26ae,,Iterable} 、 @ref{26b0,,Container} 、 @ref{12c0,,MutableMapping} などの便利な ABC が定義されています。

Pythonでは、インターフェース仕様の多くの利点は、コンポーネントへの適切なテスト規律により得られます。

モジュールのための適切なテストスイートは、回帰テストを提供し、モジュールのインターフェース仕様や用例集としても役立ちます。多くの Python モジュールは、簡単な「自己テスト」を提供するスクリプトとして実行できます。複雑な外部インターフェースを使うモジュールさえ、外部インターフェースの細かい「スタブ」エミュレーションで単独にテストできることが多いです。 @ref{3e,,doctest} や @ref{10c,,unittest} モジュール、あるいはサードパーティのテストフレームワークで、モジュールのコードの全ての行に及ぶ徹底的なテストスイートを構成できます。

An appropriate testing discipline can help build large complex applications in
Python as well as having interface specifications would.  In fact, it can be
better because an interface specification cannot test certain properties of a
program.  For example, the @ref{8dc,,list.append()} method is expected to add new elements
to the end of some internal list; an interface specification cannot test that
your @ref{8dc,,list.append()} implementation will actually do this correctly, but it's
trivial to check this property in a test suite.

テストスイートを書くことはとても有用ですし、簡単にテストできるコード設計を心がけると良いでしょう。人気を博している開発手法の一つ、テスト駆動開発は、実際のコードを記述するよりも先に、まずテストスイートの部分を記述するよう求めています。ご心配なく、Python は、あなたがいい加減でもテストケースを全く書かなくても構いません。

@node なぜ goto が無いのですか？,なぜ raw 文字列 r-strings はバックスラッシュで終わってはいけないのですか？,Python ではどのようにインターフェース仕様を特定し適用するのですか？,デザインと歴史 FAQ
@anchor{faq/design why-is-there-no-goto}@anchor{5917}
@subsection なぜ goto が無いのですか？


1970年代、人々は気付きました。秩序なき goto は、理解するのも手直しするのも困難という厄介な"スパゲッティ"コードに陥りがちであると。
高水準言語では、分岐とループの手段があれば goto は不要です。
(Pythonだと、分岐には @ref{181,,if} 文及び @ref{34d,,or} ・ @ref{349,,and} ・ @ref{181,,if}/@ref{17c,,else} 式を使います。ループには @ref{1973,,while} 文と @ref{34a,,for} 文を使い、 ループ内に @ref{180,,continue} ・ @ref{17f,,break} を含むことがあります)

関数の呼び出しをまたいでも動作する "構造化された goto" をまかなうものとして例外を使えます。C、Fortran、その他の言語での @code{go} あるいは @code{goto} 構造の適切な用途は全て、例外で同じようなことをすれば便利であると、広く感じられています。例えば:

@example
class label(Exception): pass  # declare a label

try:
    ...
    if condition: raise label()  # goto label
    ...
except label:  # where to goto
    pass
...
@end example

例外ではループ内へ跳ぶことはできませんが、どちらにしてもそれは @code{goto} の乱用と見なされるものです。使うのは控えてください。

@node なぜ raw 文字列 r-strings はバックスラッシュで終わってはいけないのですか？,属性の代入に "with" 文が使えないのはなぜですか？,なぜ goto が無いのですか？,デザインと歴史 FAQ
@anchor{faq/design why-can-t-raw-strings-r-strings-end-with-a-backslash}@anchor{5918}
@subsection なぜ raw 文字列 (r-strings) はバックスラッシュで終わってはいけないのですか？


正確には、奇数個のバックスラッシュで終わってはいけません。終わりの対になっていないバックスラッシュは、閉じ引用文字をエスケープし、終っていない文字列を残してしまいます。

raw 文字列は、独自にバックスラッシュの処理をしようとするプロセッサ (主に正規表現エンジン) への入力を生成しやすいように設計されたものです。このようなプロセッサは、終端の対になっていないバックスラッシュを結局エラーとみなすので、raw 文字列はそれを認めません。その代わりに、バックスラッシュでエスケープすることで、引用文字を文字列として渡すことができます。r-string が意図された目的に使われるときに、この規則が役に立つのです。

Windows のパス名を構築するときには、Windows のシステムコールは普通のスラッシュも受け付けることを憶えておいてください:

@example
f = open("/mydir/file.txt")  # works fine!
@end example

DOS コマンドのパス名を構築するときには、例えばこの中のどれかを試してください:

@example
dir = r"\this\is\my\dos\dir" "\\"
dir = r"\this\is\my\dos\dir\ "[:-1]
dir = "\\this\\is\\my\\dos\\dir\\"
@end example

@node 属性の代入に "with" 文が使えないのはなぜですか？,なぜジェネレータは with 文をサポートしないのですか？,なぜ raw 文字列 r-strings はバックスラッシュで終わってはいけないのですか？,デザインと歴史 FAQ
@anchor{faq/design why-doesn-t-python-have-a-with-statement-for-attribute-assignments}@anchor{5919}
@subsection 属性の代入に "with" 文が使えないのはなぜですか？


Python には、ブロックの実行を包む @ref{186,,with} 文があり、ブロックに入るときとブロックから出るときに、コードを呼び出します。以下のような構造を持つ言語があります:

@example
with obj:
    a = 1               # equivalent to obj.a = 1
    total = total + 1   # obj.total = obj.total + 1
@end example

Python では、このような構造は曖昧になるでしょう。

Object Pascal、Delphi、C++のような他の言語では、静的な型を使うので、曖昧な方法でも、どのメンバに代入されているのか分かります。これが静的型付けの要点です -- コンパイラは `いつでも' コンパイル時にすべての変数のスコープを知るのです。

Python は動的な型を使います。実行時にどの属性が参照されるか事前に分かりません。動作中にメンバ属性が追加あるいは除去されるかもしれません。これでは、単純に読むだけではどのアトリビュートが参照されているか分かりません。ローカルなのか、グローバルなのか、メンバ属性なのか？

例えば、以下の不完全なコード片を考えましょう:

@example
def foo(a):
    with a:
        print(x)
@end example

このコード片では、@code{a} は @code{x}. というメンバ属性を持っていると仮定されています。しかし、Python ではインタプリタにはこの仮定を伝えられる仕組みはありません。 @code{a} が、例えば整数だったら、どうなってしまうでしょうか。 @code{x} という名前のグローバル変数があったら、それが @ref{186,,with} ブロックの中で使われるのでしょうか。この通り、Python の動的な特質から、このような選択はとても難しい物になっています。

しかし、@ref{186,,with} やそれに類する言語の機能の一番の利点 (コード量の削減) は、 Python では代入により簡単に手に入れられます:

@example
function(args).mydict[index][index].a = 21
function(args).mydict[index][index].b = 42
function(args).mydict[index][index].c = 63
@end example

こう書いてください:

@example
ref = function(args).mydict[index][index]
ref.a = 21
ref.b = 42
ref.c = 63
@end example

Python では実行時に名前束縛が解決され、後者はその解決が一度で済むため、これには実行速度をあげる副作用もあります。

似た提案として、「先頭のドット」を使うなどして さらにコード量を減らす構文は、明白さを優先をして却下されました (@indicateurl{https://mail.python.org/pipermail/python-ideas/2016-May/040070.html} 参照)。

@node なぜジェネレータは with 文をサポートしないのですか？,if/while/def/class 文にコロンが必要なのはなぜですか？,属性の代入に "with" 文が使えないのはなぜですか？,デザインと歴史 FAQ
@anchor{faq/design why-don-t-generators-support-the-with-statement}@anchor{591a}
@subsection なぜジェネレータは with 文をサポートしないのですか？


技術的な理由で、ジェネレータは直接コンテキストマネージャとして使ってもうまく動きません。最も一般的なように、ジェネレータが最後まで回りきるイテレータとして使われる場合、クローズ処理は不要です。必要な場合は、 @ref{186,,with} 文で @ref{15a1,,contextlib.closing(generator)} のようにラップします。

@node if/while/def/class 文にコロンが必要なのはなぜですか？,なぜ Python ではリストやタプルの最後にカンマがあっても良いのですか？,なぜジェネレータは with 文をサポートしないのですか？,デザインと歴史 FAQ
@anchor{faq/design why-are-colons-required-for-the-if-while-def-class-statements}@anchor{591b}
@subsection if/while/def/class 文にコロンが必要なのはなぜですか？


主に可読性を高めるため (実験的な ABC 言語の結果の一つ) に、コロンが必要です:

@example
if a == b
    print(a)
@end example

と:

@example
if a == b:
    print(a)
@end example

を考えれば、後者のほうが少し読みやすいでしょう。さらに言えば、この FAQ の解答例は次のようになるでしょう。これは、英語の標準的な用法です。

他の小さな理由は、コロンによってエディタがシンタックスハイライトをしやすくなることです。プログラムテキストの手の込んだ解析をしなくても、コロンを探せばいつインデントを増やすべきかを決められます。

@node なぜ Python ではリストやタプルの最後にカンマがあっても良いのですか？,,if/while/def/class 文にコロンが必要なのはなぜですか？,デザインと歴史 FAQ
@anchor{faq/design why-does-python-allow-commas-at-the-end-of-lists-and-tuples}@anchor{591c}
@subsection なぜ Python ではリストやタプルの最後にカンマがあっても良いのですか？


Python では、リスト、タプル、辞書の最後の要素の後端にカンマをつけても良いことになっています:

@example
[1, 2, 3,]
('a', 'b', 'c',)
d = @{
    "A": [1, 5],
    "B": [6, 7],  # last trailing comma is optional but good style
@}
@end example

これを許すのには、いくつかの理由があります。

リストやタプルや辞書のリテラルが複数行に渡っているときに、前の行にカンマを追加するのを覚えておく必要が無いため、要素を追加するのが楽になります。また、文法エラーを起こすこと無く、行の並べ替えを行うことができます。

間違えてカンマを落としてしまうと、診断しづらいエラーにつながります。例えば:

@example
x = [
  "fee",
  "fie"
  "foo",
  "fum"
]
@end example

このリストには4つの要素があるように見えますが、実際には3つしかありません。
"fee"、"fiefoo"、"fum" です。
常にカンマを付けるようにすれば、この種のエラーが避けられます。

後端にカンマをつけても良いことにすれば、プログラムによるコード生成も簡単になります。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node ライブラリと拡張 FAQ,拡張と埋め込み FAQ,デザインと歴史 FAQ,Python よくある質問
@anchor{faq/library doc}@anchor{591d}@anchor{faq/library library-and-extension-faq}@anchor{591e}@anchor{faq/library translation-repo}@anchor{591f}
@section ライブラリと拡張 FAQ



@menu
* ライブラリ一般の質問:: 
* よくある作業:: 
* スレッド:: 
* 入力と出力: 入力と出力<2>. 
* ネットワーク/インターネットプログラミング:: 
* データベース:: 
* 数学と数:: 

@end menu

@node ライブラリ一般の質問,よくある作業,,ライブラリと拡張 FAQ
@anchor{faq/library general-library-questions}@anchor{5920}
@subsection ライブラリ一般の質問


@menu
* 作業 X を行うためのモジュールやアプリケーションを探すにはどうしますか？:: 
* math.py (socket.py@comma{} regex.py@comma{} etc.) のソースファイルはどこにありますか？: math py socket py regex py etc のソースファイルはどこにありますか？. 
* Python のスクリプトを Unix で実行可能にするにはどうしますか？:: 
* Python には curses/termcap パッケージはありますか？:: 
* Python には C の onexit() に相当するものはありますか？: Python には C の onexit に相当するものはありますか？. 
* シグナルハンドラが動かないのですがなぜですか？:: 

@end menu

@node 作業 X を行うためのモジュールやアプリケーションを探すにはどうしますか？,math py socket py regex py etc のソースファイルはどこにありますか？,,ライブラリ一般の質問
@anchor{faq/library how-do-i-find-a-module-or-application-to-perform-task-x}@anchor{5921}
@subsubsection 作業 X を行うためのモジュールやアプリケーションを探すにはどうしますか？


@ref{149,,ライブラリリファンレス} から関係がありそうな標準ライブラリモジュールがあるかどうか調べてください。 (標準ライブラリに何があるかが分かるようになると、この段階をスキップすることができます。)

サードパーティのパッケージについては、Python Package Index@footnote{https://pypi.org} を探したり、Google@footnote{https://www.google.com} その他の web サーチエンジンを試してください。"Python" に加えて一つか二つのキーワードで興味のある話題を検索すれば、たいてい役に立つものが見つかるでしょう。

@node math py socket py regex py etc のソースファイルはどこにありますか？,Python のスクリプトを Unix で実行可能にするにはどうしますか？,作業 X を行うためのモジュールやアプリケーションを探すにはどうしますか？,ライブラリ一般の質問
@anchor{faq/library where-is-the-math-py-socket-py-regex-py-etc-source-file}@anchor{5922}
@subsubsection math.py (socket.py, regex.py, etc.) のソースファイルはどこにありますか？


モジュールのソースファイルが見付けられない場合は、それは C 、 C++ かもしくは別のコンパイル言語で実装された、ビルトインもしくは動的に読み込まれるモジュールかもしれません。この場合、ソースは手に入らないかもしれませんし、 @code{mathmodule.c} のようなものが (Python の読み込みパスに無い) C ソースディレクトリのどこかにあるかもしれません。

Python のモジュールには、(少なくとも) 3 種類あります:


@enumerate 

@item 
Python で書かれたモジュール (.py)。

@item 
C で書かれ、動的にロードされるモジュール (.dll, .pyd, .so, .sl, etc)。

@item 
C で書かれ、インタプリタにリンクされているモジュール。このリストを得るには、こうタイプしてください:

@example
import sys
print(sys.builtin_module_names)
@end example
@end enumerate

@node Python のスクリプトを Unix で実行可能にするにはどうしますか？,Python には curses/termcap パッケージはありますか？,math py socket py regex py etc のソースファイルはどこにありますか？,ライブラリ一般の質問
@anchor{faq/library how-do-i-make-a-python-script-executable-on-unix}@anchor{5923}
@subsubsection Python のスクリプトを Unix で実行可能にするにはどうしますか？


二つの条件があります :スクリプトファイルのモードが実行可能で、最初の行が @code{#!} で始まり Python インタプリタのパスが続いていなければなりません。

前者は、@code{chmod +x scriptfile} 、場合によっては @code{chmod 755 scriptfile} を実行すればできます。

後者は、いくつかの方法でできます。最も直接的な方法はこのように

@example
#!/usr/local/bin/python
@end example

のようにファイルの一番最初の行に、プラットフォーム上の Python がインストールされているパス名を書くことです。

スクリプトを Python インタプリタの場所に依存させたくない場合は、 @code{env} プログラムが使えます。 Python インタプリタがユーザの 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} のディレクトリにあることを前提とすれば、ほとんど全ての Unix 系 OS では次の書き方をサポートしています:

@example
#!/usr/bin/env python
@end example

CGI スクリプトでこれをやっては `いけません' 。 CGI スクリプトの 
@geindex PATH
@geindex 環境変数; PATH
@code{PATH} 変数はたいてい最小限のものになっているので、実際のインタプリタの絶対パスを使う必要があります。

ときおり、ユーザ環境に余裕が無く @code{/usr/bin/env} プログラムが失敗することがあります; もしくは、 env プログラム自体が無いことがあります。そのような場合は、次の (Alex Rezinsky による) ハックが試せます:

@example
#! /bin/sh
""":"
exec python $0 $@{1+"$@@"@}
"""
@end example

これには、スクリプトの __doc__ 文字列を定義するというちょっとした欠点があります。しかし、これを付け足せば直せます:

@example
__doc__ = """...Whatever..."""
@end example

@node Python には curses/termcap パッケージはありますか？,Python には C の onexit に相当するものはありますか？,Python のスクリプトを Unix で実行可能にするにはどうしますか？,ライブラリ一般の質問
@anchor{faq/library is-there-a-curses-termcap-package-for-python}@anchor{5924}
@subsubsection Python には curses/termcap パッケージはありますか？


@c XXX curses *is* built by default, isn't it?

Unix 系 OS において: 標準の Python ソースディストリビューションには Modules@footnote{https://github.com/python/cpython/tree/3.14/Modules} サブディレクトリに curses モジュールが付いてきますが、デフォルトではコンパイルされていません。 (これは Windows 用ディストリビューションでは利用できないことに注意してください -- Windows には curses モジュールはありません。)

@ref{2f,,curses} モジュールは基本的な curses の機能や、色付きの表示、別の文字集合サポート、パッド、マウスサポートなどの ncurses や SYSV curses の多くの機能をサポートしています。このことは、モジュールが BSD curses だけしか持っていない OS とは互換性が無いことを意味しますが、現在メンテナンスされている OS でそういう類のものは無さそうです。

@node Python には C の onexit に相当するものはありますか？,シグナルハンドラが動かないのですがなぜですか？,Python には curses/termcap パッケージはありますか？,ライブラリ一般の質問
@anchor{faq/library is-there-an-equivalent-to-c-s-onexit-in-python}@anchor{5925}
@subsubsection Python には C の onexit() に相当するものはありますか？


@ref{d,,atexit} モジュールは、 C の @code{onexit()} と同じような関数登録を提供します。

@node シグナルハンドラが動かないのですがなぜですか？,,Python には C の onexit に相当するものはありますか？,ライブラリ一般の質問
@anchor{faq/library why-don-t-my-signal-handlers-work}@anchor{5926}
@subsubsection シグナルハンドラが動かないのですがなぜですか？


最もありがちな問題は、シグナルハンドラが間違った引数リストで宣言されていることです。これは次のように呼び出されます

@example
handler(signum, frame)
@end example

だから、これは二つの仮引数で宣言されるべきです:

@example
def handler(signum, frame):
    ...
@end example

@node よくある作業,スレッド,ライブラリ一般の質問,ライブラリと拡張 FAQ
@anchor{faq/library common-tasks}@anchor{5927}
@subsection よくある作業


@menu
* Python のプログラムやコンポーネントをテストするにはどうしますか？:: 
* Python のドキュメント文字列からドキュメントを生成するにはどうしますか？:: 
* 一度に一つの押鍵を取得するにはどうしますか？:: 

@end menu

@node Python のプログラムやコンポーネントをテストするにはどうしますか？,Python のドキュメント文字列からドキュメントを生成するにはどうしますか？,,よくある作業
@anchor{faq/library how-do-i-test-a-python-program-or-component}@anchor{5928}
@subsubsection Python のプログラムやコンポーネントをテストするにはどうしますか？


Python には二つのテストフレームワークがついています。@ref{3e,,doctest} モジュールは、モジュールの docstring から使用例を見つけてそれらを実行し、出力を docstring によって与えられた望まれる出力と比較します。

@ref{10c,,unittest} モジュールは、Java や Smalltalk のテストフレームワークを模した装飾されたテストフレームワークです。

テスト作業を簡単にするために、プログラムにおいてモジュール性の良い設計を使うべきです。プログラムでは、ほぼ全ての処理を関数やクラスのメソッドで包むべきです -- こうすることで、プログラムが速くなるという驚くような愉快な効果がときおり得られることがあります (というのも、ローカル変数へのアクセスはグローバルなアクセスよりも速いからです)。さらに言うと、テストを行うのがより難しくなってしまうため、プログラムは可変なグローバル変数に依存するのを避けるべきです。

プログラムの "global main logic" は

@example
if __name__ == "__main__":
    main_logic()
@end example

のように main モジュールの最後に出来る限りシンプルなものを書くのが良いでしょう。

プログラムが整理され、関数やクラスの動作が追いやすい状態になったら、その動作を試すテスト関数を書くべきです。一連のテストを自動化するテストスイートは、それぞれのモジュールに関連付けることができます。これは手間が掛かりそうに思えますが、Python は簡素で融通が効くので、驚くほど簡単です。"製品コード (production code)" と並行でテスト関数を書くことで、バグや設計の不備でさえも早い段階で簡単に見付かるようになるので、コーディング作業をより心地良く楽しいものにできます。

プログラムのメインモジュールとして設計されたのではない "補助モジュール" には、モジュールの自己テストを含めるといいでしょう。

@example
if __name__ == "__main__":
    self_test()
@end example

複雑な外部インターフェースと作用し合うプログラムでさえ、外部インターフェースが使えない時でも、Python で実装された "fake" インターフェースを使ってテストできます。

@node Python のドキュメント文字列からドキュメントを生成するにはどうしますか？,一度に一つの押鍵を取得するにはどうしますか？,Python のプログラムやコンポーネントをテストするにはどうしますか？,よくある作業
@anchor{faq/library how-do-i-create-documentation-from-doc-strings}@anchor{5929}
@subsubsection Python のドキュメント文字列からドキュメントを生成するにはどうしますか？


@ref{ba,,pydoc} モジュールで Python ソースコード内のドキュメント文字列から HTML を生成できます。純粋に docstring から API ドキュメントを生成するには、他に epydoc@footnote{https://epydoc.sourceforge.net/} という選択肢もあります。 Sphinx@footnote{https://www.sphinx-doc.org} も docstring の内容を含めることができます。

@node 一度に一つの押鍵を取得するにはどうしますか？,,Python のドキュメント文字列からドキュメントを生成するにはどうしますか？,よくある作業
@anchor{faq/library how-do-i-get-a-single-keypress-at-a-time}@anchor{592a}
@subsubsection 一度に一つの押鍵を取得するにはどうしますか？


Unix 系 OS ではいくつか解決方法があります。curses を使うのが素直なやり方ですが、curses は学ぶには少し大き過ぎるモジュールです。

@c XXX this doesn't work out of the box, some IO expert needs to check why
@c 
@c Here's a solution without curses::
@c 
@c import termios, fcntl, sys, os
@c fd = sys.stdin.fileno()
@c 
@c oldterm = termios.tcgetattr(fd)
@c newattr = termios.tcgetattr(fd)
@c newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
@c termios.tcsetattr(fd, termios.TCSANOW, newattr)
@c 
@c oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
@c fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
@c 
@c try:
@c     while True:
@c         try:
@c             c = sys.stdin.read(1)
@c             print("Got character", repr(c))
@c         except OSError:
@c             pass
@c finally:
@c     termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
@c     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
@c 
@c You need the :mod:`termios` and the :mod:`fcntl` module for any of this to
@c work, and I've only tried it on Linux, though it should work elsewhere.  In
@c this code, characters are read and printed one at a time.
@c 
@c :func:`termios.tcsetattr` turns off stdin's echoing and disables canonical
@c mode.  :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags
@c and modify them for non-blocking mode.  Since reading stdin when it is empty
@c results in an :exc:`OSError`, this error is caught and ignored.
@c 
@c .. versionchanged:: 3.3
@c    *sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3
@c    :exc:`IOError` is alias for :exc:`OSError`.

@node スレッド,入力と出力<2>,よくある作業,ライブラリと拡張 FAQ
@anchor{faq/library threads}@anchor{592b}
@subsection スレッド


@menu
* スレッドを使ったプログラムを書くにはどうしますか？:: 
* スレッドが一つも実行されていないようです。なぜですか？:: 
* たくさんのワーカースレッドに作業を割り振るにはどうしますか？:: 
* グローバルな値のどんな種類の変更がスレッドセーフになるのですか？:: 
* グローバルインタプリタロック (Global Interpreter Lock) を取り除くことはできないのですか？: グローバルインタプリタロック Global Interpreter Lock を取り除くことはできないのですか？. 

@end menu

@node スレッドを使ったプログラムを書くにはどうしますか？,スレッドが一つも実行されていないようです。なぜですか？,,スレッド
@anchor{faq/library how-do-i-program-using-threads}@anchor{592c}
@subsubsection スレッドを使ったプログラムを書くにはどうしますか？


@ref{2,,_thread} モジュールではなく、必ず @ref{f3,,threading} モジュールを使ってください。 @ref{f3,,threading} モジュールは、 @ref{2,,_thread} モジュールで提供される低レベルな基本要素の、便利な抽象化を構成します。

@node スレッドが一つも実行されていないようです。なぜですか？,たくさんのワーカースレッドに作業を割り振るにはどうしますか？,スレッドを使ったプログラムを書くにはどうしますか？,スレッド
@anchor{faq/library none-of-my-threads-seem-to-run-why}@anchor{592d}
@subsubsection スレッドが一つも実行されていないようです。なぜですか？


メインスレッドが終了するとともに、全てのスレッドは終了されます。メインスレッドは速く働きすぎるので、スレッドには何をする時間も与えられません。

簡単な解決策は、プログラムの終わりに、スレッドが完了するのに十分な時間のスリープを加えることです:

@example
import threading, time

def thread_task(name, n):
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)  # <---------------------------!
@end example

しかし、実際は (ほとんどのプラットフォームでは) スレッドは並行して実行されるのではなく、一つづつ実行されるのです！なぜなら、OS のスレッドスケジューラは、前のスレッドがブロックされるまで新しいスレッドを開始しないからです。

簡単に直すには、関数の実行の最初にちょっとスリープを加えることです:

@example
def thread_task(name, n):
    time.sleep(0.001)  # <--------------------!
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)
@end example

@ref{8ac,,time.sleep()} の良い遅延時間を推測しようとするよりも、セマフォのような仕組みを使う方が良いでしょう。 1 つのアイディアは @ref{bb,,queue} モジュールを使って、キューオブジェクトを作り、各スレッドが完了したときにキューにトークンを追加し、メインスレッドにスレッドと同じ数のトークンをキューから読み出させることです。

@node たくさんのワーカースレッドに作業を割り振るにはどうしますか？,グローバルな値のどんな種類の変更がスレッドセーフになるのですか？,スレッドが一つも実行されていないようです。なぜですか？,スレッド
@anchor{faq/library how-do-i-parcel-out-work-among-a-bunch-of-worker-threads}@anchor{592e}
@subsubsection たくさんのワーカースレッドに作業を割り振るにはどうしますか？


最も簡単な方法は、新しい @ref{24,,concurrent.futures} モジュール、特に @ref{949,,ThreadPoolExecutor} クラスを使うことです。

もしくは、実行アルゴリズムを上手にコントロールしたい場合は、自身の手でロジックを書くこともできます。 @ref{bb,,queue} モジュールを使って、ジョブのリストを含むキューを作ってください。 @ref{15ac,,Queue} クラスはオブジェクトのリストを保持し、キューに要素を追加する @code{.put(obj)} メソッド、それら要素を返す @code{.get()} メソッドを持っています。このクラスは、それぞれのジョブがきっちり 1 回だけ取り出されることを保証するのに必要なロック処理にも配慮します。

ここにちょっとした例があります:

@example
import threading, queue, time

# The worker thread gets jobs off the queue.  When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker():
    print('Running worker')
    time.sleep(0.1)
    while True:
        try:
            arg = q.get(block=False)
        except queue.Empty:
            print('Worker', threading.current_thread(), end=' ')
            print('queue empty')
            break
        else:
            print('Worker', threading.current_thread(), end=' ')
            print('running with argument', arg)
            time.sleep(0.5)

# Create queue
q = queue.Queue()

# Start a pool of 5 workers
for i in range(5):
    t = threading.Thread(target=worker, name='worker %i' % (i+1))
    t.start()

# Begin adding work to the queue
for i in range(50):
    q.put(i)

# Give threads time to run
print('Main thread sleeping')
time.sleep(5)
@end example

実行時には、以下のように出力されます:

@example
Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker <Thread(worker 1, started 130283832797456)> running with argument 0
Worker <Thread(worker 2, started 130283824404752)> running with argument 1
Worker <Thread(worker 3, started 130283816012048)> running with argument 2
Worker <Thread(worker 4, started 130283807619344)> running with argument 3
Worker <Thread(worker 5, started 130283799226640)> running with argument 4
Worker <Thread(worker 1, started 130283832797456)> running with argument 5
...
@end example

より詳しいことはモジュールのドキュメントを調べてください; @ref{15ac,,Queue} クラスは多機能なインターフェースを提供しています。

@node グローバルな値のどんな種類の変更がスレッドセーフになるのですか？,グローバルインタプリタロック Global Interpreter Lock を取り除くことはできないのですか？,たくさんのワーカースレッドに作業を割り振るにはどうしますか？,スレッド
@anchor{faq/library what-kinds-of-global-value-mutation-are-thread-safe}@anchor{592f}
@subsubsection グローバルな値のどんな種類の変更がスレッドセーフになるのですか？


@ref{474,,global interpreter lock} (GIL) が内部で使われ、Python VM で一度に一つだけのスレッドが実行されることが保証されています。一般に、Python ではスレッド間の切り替えをバイトコード命令の間でのみ行います。切り替えの周期は、 @ref{b44,,sys.setswitchinterval()} で設定できます。したがって、それぞれのバイトコード命令、そしてそれぞれの命令が届く全ての C 実装コードは、 Python プログラムの観点からは、アトミックです。

このことから、理論上は、正確な勘定のためには PVM バイトコードの実装を理解することが必要です。実際上は、組み込みデータ型(整数、リスト、辞書、等)の、変数を共有する "アトミックそうな" 演算は、実際にアトミックです。

例えば、以下の演算は全てアトミックです (L、L1、L2 はリスト、 D、D1、D2 は辞書、x、y はオブジェクト、i、j は整数です):

@example
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
@end example

これらは、アトミックではありません:

@example
i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1
@end example

他のオブジェクトを置き換えるような演算は、そのオブジェクトの参照カウントがゼロになったときに @ref{11ff,,__del__()} メソッドを呼び出すことがあり、これが影響を及ぼすかもしれません。これは特に、辞書やリストの大規模な更新に当てはまります。疑わしければ、mutex を使ってください！

@node グローバルインタプリタロック Global Interpreter Lock を取り除くことはできないのですか？,,グローバルな値のどんな種類の変更がスレッドセーフになるのですか？,スレッド
@anchor{faq/library can-t-we-get-rid-of-the-global-interpreter-lock}@anchor{5930}
@subsubsection グローバルインタプリタロック (Global Interpreter Lock) を取り除くことはできないのですか？


マルチスレッド Python プログラムは事実上一つの CPU しか使えず、 (ほとんど) 全ての Python コードが @ref{474,,グローバルインタプリタロック}  (GIL)  が保持されている間しか作動しなくなるということで、GIL は、 Python をハイエンドなマルチプロセッササーバマシン上に配備する上で邪魔であると見なされがちです。

@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/} の承認により、Python の CPython 実装から GIL を削除する作業が現在進められています。はじめに、インタープリタをビルドする際にオプションのコンパイラフラグとして実装され、そのため GIL あり・なしの別々のビルドが利用可能になります。長期的には、GIL を削除することのパフォーマンスへの影響が十分に理解された時点で、1つのビルドに落ち着くことが望まれています。Python 3.13 がこの作業を含む最初のリリースになる可能性がありますが、このリリースで完全に機能するとは限りません。

The current work to remove the GIL is based on a
fork of Python 3.9 with the GIL removed@footnote{https://github.com/colesbury/nogil}
by Sam Gross.
Prior to that,
in the days of Python 1.5, Greg Stein actually implemented a comprehensive
patch set (the "free threading" patches) that removed the GIL and replaced it
with fine-grained locking.  Adam Olsen did a similar experiment
in his python-safethread@footnote{https://code.google.com/archive/p/python-safethread}
project.  Unfortunately, both of these earlier experiments exhibited a sharp
drop in single-thread
performance (at least 30% slower), due to the amount of fine-grained locking
necessary to compensate for the removal of the GIL.  The Python 3.9 fork
is the first attempt at removing the GIL with an acceptable performance
impact.

The presence of the GIL in current Python releases
doesn't mean that you can't make good use of Python on multi-CPU machines!
You just have to be creative with dividing the work up between multiple
`processes' rather than multiple `threads'.  The
@ref{1d6,,ProcessPoolExecutor} class in the new
@ref{24,,concurrent.futures} module provides an easy way of doing so; the
@ref{98,,multiprocessing} module provides a lower-level API in case you want
more control over dispatching of tasks.

C 拡張をうまく使うことも役立ちます。C 拡張を時間のかかるタスクの実行に使えば、その拡張は実行が C コードで行われている間 GIL を解放でき、その間に他のスレッドで作業が進められます。 @ref{139,,zlib} や @ref{6c,,hashlib} など、すでにこれを行なっている標準ライブラリモジュールもあります。

An alternative approach to reducing the impact of the GIL is
to make the GIL a per-interpreter-state lock rather than truly global.
This was @ref{670,,first implemented in Python 3.12} and is
available in the C API. A Python interface to it is expected in Python 3.13.
The main limitation to it at the moment is likely to be 3rd party extension
modules, since these must be written with multiple interpreters in mind in
order to be usable, so many older extension modules will not be usable.

@node 入力と出力<2>,ネットワーク/インターネットプログラミング,スレッド,ライブラリと拡張 FAQ
@anchor{faq/library input-and-output}@anchor{5931}
@subsection 入力と出力


@menu
* ファイルを削除するにはどうしますか？ (その他、ファイルに関する質問...): ファイルを削除するにはどうしますか？ その他、ファイルに関する質問. 
* ファイルをコピーするにはどうしますか？:: 
* バイナリデータを読み書きするにはどうしますか？:: 
* os.popen() によって作られたパイプで os.read() が使われていないようです。なぜですか？: os popen によって作られたパイプで os read が使われていないようです。なぜですか？. 
* シリアル (RS232) ポートにアクセスするにはどうしますか？: シリアル RS232 ポートにアクセスするにはどうしますか？. 
* sys.stdout (stdin@comma{} stderr) を閉じようとしても実際に閉じられないのはなぜですか？: sys stdout stdin stderr を閉じようとしても実際に閉じられないのはなぜですか？. 

@end menu

@node ファイルを削除するにはどうしますか？ その他、ファイルに関する質問,ファイルをコピーするにはどうしますか？,,入力と出力<2>
@anchor{faq/library how-do-i-delete-a-file-and-other-file-questions}@anchor{5932}
@subsubsection ファイルを削除するにはどうしますか？ (その他、ファイルに関する質問...)


@code{os.remove(filename)} または @code{os.unlink(filename)} を使ってください。ドキュメントは、 @ref{a5,,os} モジュールを参照してください。この二つの関数は同じものです。 @ref{130d,,unlink()} は単に、この関数の Unix システムコールの名称です。

ディレクトリを削除するには、@ref{130b,,os.rmdir()} を使ってください。作成には @ref{52b,,os.mkdir()} を使ってください。@code{os.makedirs(path)} は @code{path} の中間のディレクトリの、存在しないものを作成します。@code{os.removedirs(path)} は中間のディレクトリが空である限り、それらを削除します。ディレクトリツリー全体とその中身全てを削除したいなら、@ref{356,,shutil.rmtree()} を使ってください。

ファイルの名前を変更するには、@code{os.rename(old_path, new_path)} を使ってください。

ファイルを切り詰めるには、 @code{f = open(filename, "rb+")} を使ってファイルを開き、 @code{f.truncate(offset)} を使ってください; offset はデフォルトでは現在のシーク位置です。 @ref{f92,,os.open()} で開かれたファイル用の @code{os.ftruncate(fd, offset)} もあります。 `fd' はファイルディスクリプタ (小さい整数値) です。

@ref{ca,,shutil} モジュールにも、@ref{c4e,,copyfile()}、 @ref{c1e,,copytree()}、@ref{356,,rmtree()} 等、ファイルに作用する関数がいくつか含まれます。

@node ファイルをコピーするにはどうしますか？,バイナリデータを読み書きするにはどうしますか？,ファイルを削除するにはどうしますか？ その他、ファイルに関する質問,入力と出力<2>
@anchor{faq/library how-do-i-copy-a-file}@anchor{5933}
@subsubsection ファイルをコピーするにはどうしますか？


@ref{ca,,shutil} モジュールに @ref{c4e,,copyfile()} 関数があります。注意点として、これは Windows NTFS ボリューム上の alternate data streams@footnote{https://en.wikipedia.org/wiki/NTFS#Alternate_data_stream_(ADS)} も macOS HFS+ 上の resource forks@footnote{https://en.wikipedia.org/wiki/Resource_fork} もコピーしません。ただし現在ではどちらも使われることは ほとんどありません。またファイルのパーミッションやメタデータもコピーされませんが、この代わりに @ref{c50,,shutil.copy2()} を使うとそのほとんど (すべてではありませんが) が保持されます。

@node バイナリデータを読み書きするにはどうしますか？,os popen によって作られたパイプで os read が使われていないようです。なぜですか？,ファイルをコピーするにはどうしますか？,入力と出力<2>
@anchor{faq/library how-do-i-read-or-write-binary-data}@anchor{5934}
@subsubsection バイナリデータを読み書きするにはどうしますか？


複雑なバイナリデータ形式の読み書きには、@ref{db,,struct} モジュールを使うのが一番です。これでバイナリデータ (通常は数) を含む文字列を取って、 Python オブジェクトに変換することができますし、その逆もできます。

例えば、以下のコードはファイルから 2 バイトの整数 2 個と 4 バイトの整数 1 個をビッグエンディアンフォーマットで読み込みます:

@example
import struct

with open(filename, "rb") as f:
    s = f.read(8)
    x, y, z = struct.unpack(">hhl", s)
@end example

フォーマット中の '>' はデータを強制的にビッグエンディアンにします。ファイルから、文字 'h' は一つの"整数"(2 バイト)を読み込み、文字 'l' は一つの"long 整数"を読み込みます。

より規則的なデータ (例えば、整数や浮動小数点数の中身の型が揃ったリスト) に対しては、 @ref{8,,array} モジュールを使うこともできます。

@cartouche
@quotation 注釈 
バイナリデータを読み書きするには、 (ここにあるように @code{"rb"} を @ref{316,,open()} に渡して) ファイルをバイナリモードで開く義務があります。代わりに (デフォルトの) @code{"r"} を使った場合は、ファイルはテキストモードで開かれ、 @code{f.read()} は @ref{192,,bytes} オブジェクトではなく @ref{169,,str} オブジェクトを返します。
@end quotation
@end cartouche

@node os popen によって作られたパイプで os read が使われていないようです。なぜですか？,シリアル RS232 ポートにアクセスするにはどうしますか？,バイナリデータを読み書きするにはどうしますか？,入力と出力<2>
@anchor{faq/library i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why}@anchor{5935}
@subsubsection os.popen() によって作られたパイプで os.read() が使われていないようです。なぜですか？


@ref{f95,,os.read()} は、開かれたファイルを表す小さな整数、ファイルディスクリプタを引数に取る、低レベルの関数です。 @ref{31a,,os.popen()} は、組み込みの @ref{316,,open()} 関数の返り値と同じ型の、高レベルなファイルオブジェクトを作成します。従って、 @ref{31a,,os.popen()} によって作成されたパイプ `p' から `n' バイト分だけ読み取るには、 @code{p.read(n)} を使う必要があります。

@node シリアル RS232 ポートにアクセスするにはどうしますか？,sys stdout stdin stderr を閉じようとしても実際に閉じられないのはなぜですか？,os popen によって作られたパイプで os read が使われていないようです。なぜですか？,入力と出力<2>
@anchor{faq/library how-do-i-access-the-serial-rs232-port}@anchor{5936}
@subsubsection シリアル (RS232) ポートにアクセスするにはどうしますか？


Win32、OSX、Linux、BSD、Jython、IronPython では:

@quotation

pyserial@footnote{https://pypi.org/project/pyserial/}
@end quotation

Unix では、Mitch Chapman による Usenet の投稿を参照してください:

@quotation

@indicateurl{https://groups.google.com/groups?selm=34A04430.CF9@@ohioee.com}
@end quotation

@node sys stdout stdin stderr を閉じようとしても実際に閉じられないのはなぜですか？,,シリアル RS232 ポートにアクセスするにはどうしますか？,入力と出力<2>
@anchor{faq/library why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it}@anchor{5937}
@subsubsection sys.stdout (stdin, stderr) を閉じようとしても実際に閉じられないのはなぜですか？


Python の @ref{13db,,file object} は、低水準の C ファイルディスクリプタ上の、抽象の高水準レイヤです。

組み込みの @ref{316,,open()} 関数によって生成されたほとんどのファイルオブジェクトでは、 @code{f.close()} は Python ファイルオブジェクトが Python の視点からは閉じられているものとする印をつけ、その下にある C ファイルディスクリプタを閉じるように手配します。これは、 @code{f} がガベージとなったときにも、 @code{f} のデストラクタで自動的に起こります。

しかし、stdin、stdout、stderr は C で特別な立場が与えられていることから、Python でも同様に特別に扱われます。@code{sys.stdout.close()} を実行すると、Python レベルのファイルオブジェクトには閉じられているものとする印がつけられますが、C ファイルディスクリプタは `閉じられません'。

下にある C ファイルディスクリプタのうち、この三つのどれかを閉じるには、まず本当に閉じる必要があることを確かめるべきです (例えば、拡張モジュールの I/O を混乱させてしまうかもしれません)。本当に必要ならば、 @ref{d6b,,os.close()} を使ってください:

@example
os.close(stdin.fileno())
os.close(stdout.fileno())
os.close(stderr.fileno())
@end example

または、数の定数としてそれぞれ 0, 1, 2 も使えます。

@node ネットワーク/インターネットプログラミング,データベース,入力と出力<2>,ライブラリと拡張 FAQ
@anchor{faq/library network-internet-programming}@anchor{5938}
@subsection ネットワーク/インターネットプログラミング


@menu
* Python の WWW ツールには何がありますか？:: 
* どのモジュールが HTML の生成の役に立ちますか？:: 
* Python のスクリプトからメールを送るにはどうしますか？:: 
* ソケットの connect() メソッドでブロッキングされなくするにはどうしますか？: ソケットの connect メソッドでブロッキングされなくするにはどうしますか？. 

@end menu

@node Python の WWW ツールには何がありますか？,どのモジュールが HTML の生成の役に立ちますか？,,ネットワーク/インターネットプログラミング
@anchor{faq/library what-www-tools-are-there-for-python}@anchor{5939}
@subsubsection Python の WWW ツールには何がありますか？


ライブラリリファレンスマニュアルの @ref{3ebd,,インターネットプロトコルとサポート} と @ref{3ab1,,インターネット上のデータの操作} という章を参照してください。Python には、サーバサイドとクライアントサイドの web システムを構築するのに便利な多くのモジュールがあります。

@c XXX check if wiki page is still up to date

利用可能なフレームワークの概要は Paul Boddie によって、 @indicateurl{https://wiki.python.org/moin/WebProgramming} でメンテナンスされています。

@node どのモジュールが HTML の生成の役に立ちますか？,Python のスクリプトからメールを送るにはどうしますか？,Python の WWW ツールには何がありますか？,ネットワーク/インターネットプログラミング
@anchor{faq/library what-module-should-i-use-to-help-with-generating-html}@anchor{593a}
@subsubsection どのモジュールが HTML の生成の役に立ちますか？


@c XXX add modern template languages

Web Programming についての wiki のページ@footnote{https://wiki.python.org/moin/WebProgramming} から役に立つリンクが見付けられます。

@node Python のスクリプトからメールを送るにはどうしますか？,ソケットの connect メソッドでブロッキングされなくするにはどうしますか？,どのモジュールが HTML の生成の役に立ちますか？,ネットワーク/インターネットプログラミング
@anchor{faq/library how-do-i-send-mail-from-a-python-script}@anchor{593b}
@subsubsection Python のスクリプトからメールを送るにはどうしますか？


標準ライブラリモジュール @ref{cf,,smtplib} を使ってください。

以下に示すのが、これを使ったごく単純な対話型のメール送信器です。このメソッドは SMTP リスナをサポートするホストならどこででも作動します。

@example
import sys, smtplib

fromaddr = input("From: ")
toaddrs  = input("To: ").split(',')
print("Enter message, end with ^D:")
msg = '@w{'}
while True:
    line = sys.stdin.readline()
    if not line:
        break
    msg += line

# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
@end example

Unix 限定の代わりの選択肢は sendmail を使うことです。sendmail プログラムの場所はシステムによって様々です; あるときは @code{/usr/lib/sendmail} だったり、あるときは @code{/usr/sbin/sendmail} だったり。sendmail のマニュアルページが助けになるでしょう。サンプルコードはこのようになります:

@example
import os

SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@@example.com\n")
p.write("Subject: test\n")
p.write("\n")  # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
    print("Sendmail exit status", sts)
@end example

@node ソケットの connect メソッドでブロッキングされなくするにはどうしますか？,,Python のスクリプトからメールを送るにはどうしますか？,ネットワーク/インターネットプログラミング
@anchor{faq/library how-do-i-avoid-blocking-in-the-connect-method-of-a-socket}@anchor{593c}
@subsubsection ソケットの connect() メソッドでブロッキングされなくするにはどうしますか？


主に @ref{c6,,select} モジュールがソケットの非同期の I/O を扱うのに使われます。

TCP 接続がブロッキングされないようにするために、ソケットをノンブロッキングモードに設定することが出来ます。そして @ref{fa3,,connect()} したときに、即座に接続できるか、エラー番号を @code{.errno} として含む例外を受け取るかのどちらかになります。@code{errno.EINPROGRESS} は、接続が進行中であるが、まだ完了していないということを示します。異なる OS では異なる値が返されるので、あなたのシステムで何が返されるかを確かめておく必要があります。

@ref{1753,,connect_ex()} メソッドを使えば例外を生成しなくて済みます。これは単に errno の値を返すでしょう。ポーリングのためには、後でまた @ref{1753,,connect_ex()} を呼び出すことができます -- @code{0} または @code{errno.EISCONN} は接続されたことを表します -- または、このソケットを @ref{fa0,,select.select()} に渡して書き込み可能か調べることができます。

@cartouche
@quotation 注釈 
@ref{b,,asyncio} モジュールは、ノンブロッキングのネットワークコードを書く作業のためにフレームワークのような方法を提供します。その他の選択肢として、Twisted@footnote{https://twisted.org/} は多機能で著名なサードパーティのライブラリです。
@end quotation
@end cartouche

@node データベース,数学と数,ネットワーク/インターネットプログラミング,ライブラリと拡張 FAQ
@anchor{faq/library databases}@anchor{593d}
@subsection データベース


@menu
* Python にはデータベースパッケージへのインターフェースはありますか？:: 
* Python で永続的なオブジェクトを実装するにはどうしますか？:: 

@end menu

@node Python にはデータベースパッケージへのインターフェースはありますか？,Python で永続的なオブジェクトを実装するにはどうしますか？,,データベース
@anchor{faq/library are-there-any-interfaces-to-database-packages-in-python}@anchor{593e}
@subsubsection Python にはデータベースパッケージへのインターフェースはありますか？


はい。

標準の Python には、 @ref{38,,DBM} や @ref{37,,GDBM} などの、ディスクベースのハッシュへのインターフェースも含まれています。また、 @ref{d4,,sqlite3} モジュールは、軽量なディスクベースの関係データベースを提供します。

ほとんどの関係データベースがサポートされています。詳細は DatabaseProgramming wiki page@footnote{https://wiki.python.org/moin/DatabaseProgramming} を参照してください。

@node Python で永続的なオブジェクトを実装するにはどうしますか？,,Python にはデータベースパッケージへのインターフェースはありますか？,データベース
@anchor{faq/library how-do-you-implement-persistent-objects-in-python}@anchor{593f}
@subsubsection Python で永続的なオブジェクトを実装するにはどうしますか？


@ref{ab,,pickle} ライブラリモジュールで、ごく一般的な方法でこれを解決できます (開かれたファイル、ソケット、ウィンドウのようなものを保管することはできませんが)。 @ref{c8,,shelve} ライブラリモジュールは pickle と (g)dbm を使い、任意の Python オブジェクトを含む永続的なマッピングを生成します。

@node 数学と数,,データベース,ライブラリと拡張 FAQ
@anchor{faq/library mathematics-and-numerics}@anchor{5940}
@subsection 数学と数


@menu
* Python で乱数を生成するにはどうしますか？:: 

@end menu

@node Python で乱数を生成するにはどうしますか？,,,数学と数
@anchor{faq/library how-do-i-generate-random-numbers-in-python}@anchor{5941}
@subsubsection Python で乱数を生成するにはどうしますか？


標準モジュールの @ref{bd,,random} が乱数生成器を実装しています。使い方は単純です:

@example
import random
random.random()
@end example

これは、 [0, 1) の範囲のランダムな浮動小数点数を返します。

このモジュールにはその他多くの特化した生成器もあります。例えば:


@itemize *

@item 
@code{randrange(a, b)} は区間 [a, b) から整数を選びます。

@item 
>>`@w{`}<<uniform(a, b)`@w{`}は [a, b) の範囲の浮動小数点数を選びます。

@item 
@code{normalvariate(mean, sdev)} は正規 (ガウス) 分布をサンプリングします。
@end itemize

シーケンスに直接作用する高水準な関数もあります。例えば:


@itemize *

@item 
@code{choice(S)} は与えられたシーケンスからランダムな要素を選びます。

@item 
@code{shuffle(L)} はリストをインプレースにシャッフルします。すなわち、ランダムに並び替えます。
@end itemize

@code{Random} クラスのインスタンスを生成して、複数の独立な乱数生成器をつくることもできます。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 拡張と埋め込み FAQ,Windows 上の Python FAQ,ライブラリと拡張 FAQ,Python よくある質問
@anchor{faq/extending doc}@anchor{5942}@anchor{faq/extending extending-embedding-faq}@anchor{5943}@anchor{faq/extending translation-repo}@anchor{5944}
@section 拡張と埋め込み FAQ



@c XXX need review for Python 3.

@menu
* C で独自の関数を作ることはできますか？:: 
* C++ で独自の関数を作ることはできますか？:: 
* C を書くのは大変です。他の方法はありませんか？:: 
* C から任意の Python 文を実行するにはどうしますか？:: 
* C から任意の Python 式を評価するにはどうしますか？:: 
* Python オブジェクトから C の値を取り出すにはどうしますか？:: 
* Py_BuildValue() で任意長のタプルを作るにはどうしますか？: Py_BuildValue で任意長のタプルを作るにはどうしますか？. 
* C からオブジェクトのメソッドを呼び出すにはどうしますか？:: 
* PyErr_Print() (その他 stdout/stderr に印字するもの) からの出力を受け取るにはどうしますか？: PyErr_Print その他 stdout/stderr に印字するもの からの出力を受け取るにはどうしますか？. 
* C から Python で書かれたモジュールにアクセスするにはどうしますか？:: 
* Python から C++ へインターフェースするにはどうしますか？:: 
* セットアップファイルでモジュールを追加しようとしたらメイクに失敗しました。なぜですか？:: 
* 拡張をデバッグするにはどうしますか？:: 
* Linux システムで Python モジュールをコンパイルしたいのですが、見つからないファイルがあります。なぜですか？:: 
* "不完全 (incomplete) な入力" を "不適切 (invalid) な入力" から区別するにはどうしますか？: "不完全 incomplete な入力" を "不適切 invalid な入力" から区別するにはどうしますか？. 
* 未定義の g++ シンボル __builtin_new や __pure_virtual を見つけるにはどうしますか？:: 
* メソッドのいくつかは C で、その他は Python で実装されたオブジェクトクラスを (継承などで) 作ることはできますか？: メソッドのいくつかは C で、その他は Python で実装されたオブジェクトクラスを 継承などで 作ることはできますか？. 

@end menu

@node C で独自の関数を作ることはできますか？,C++ で独自の関数を作ることはできますか？,,拡張と埋め込み FAQ
@anchor{faq/extending can-i-create-my-own-functions-in-c}@anchor{5945}
@subsection C で独自の関数を作ることはできますか？


はい。関数、変数、例外、そして新しいタイプまで含んだビルトインモジュールを C で作れます。これはドキュメント @ref{1fbd,,Python インタプリタの拡張と埋め込み} で説明されています。

ほとんどの中級から上級の Python 本もこの話題を扱っています。

@node C++ で独自の関数を作ることはできますか？,C を書くのは大変です。他の方法はありませんか？,C で独自の関数を作ることはできますか？,拡張と埋め込み FAQ
@anchor{faq/extending id2}@anchor{5946}
@subsection C++ で独自の関数を作ることはできますか？


はい。C++ 内にある C 互換機能を使ってできます。 @code{extern "C" @{ ... @}} で Python のインクルードファイルを囲み、 @code{extern "C"} を Python インタプリタから呼ぶ各関数の前に置いてください。グローバルや静的な C++ オブジェクトの構造体を持つものは良くないでしょう。

@node C を書くのは大変です。他の方法はありませんか？,C から任意の Python 文を実行するにはどうしますか？,C++ で独自の関数を作ることはできますか？,拡張と埋め込み FAQ
@anchor{faq/extending c-wrapper-software}@anchor{5947}@anchor{faq/extending writing-c-is-hard-are-there-any-alternatives}@anchor{5948}
@subsection C を書くのは大変です。他の方法はありませんか？


There are a number of alternatives to writing your own C extensions, depending
on what you're trying to do. @ref{4e8e,,Recommended third party tools}
offer both simpler and more sophisticated approaches to creating C and C++
extensions for Python.

@node C から任意の Python 文を実行するにはどうしますか？,C から任意の Python 式を評価するにはどうしますか？,C を書くのは大変です。他の方法はありませんか？,拡張と埋め込み FAQ
@anchor{faq/extending how-can-i-execute-arbitrary-python-statements-from-c}@anchor{5949}
@subsection C から任意の Python 文を実行するにはどうしますか？


これを行う最高水準の関数は @ref{4f0b,,PyRun_SimpleString()} で、一つの文字列引数を取り、モジュール @code{__main__} のコンテキストでそれを実行し、成功なら @code{0}、例外 (@ref{18e,,SyntaxError} を含む) が発生したら @code{-1} を返します。更に制御したければ、 @ref{1dc0,,PyRun_String()}  を使ってください。ソースは @code{Python/pythonrun.c} の '@ref{4f0b,,PyRun_SimpleString()} を参照してください。

@node C から任意の Python 式を評価するにはどうしますか？,Python オブジェクトから C の値を取り出すにはどうしますか？,C から任意の Python 文を実行するにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-can-i-evaluate-an-arbitrary-python-expression-from-c}@anchor{594a}
@subsection C から任意の Python 式を評価するにはどうしますか？


先の質問の @ref{1dc0,,PyRun_String()} を、スタートシンボル @ref{51c1,,Py_eval_input} を渡して呼び出してください。これは式を解析し、評価してその値を返します。

@node Python オブジェクトから C の値を取り出すにはどうしますか？,Py_BuildValue で任意長のタプルを作るにはどうしますか？,C から任意の Python 式を評価するにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-extract-c-values-from-a-python-object}@anchor{594b}
@subsection Python オブジェクトから C の値を取り出すにはどうしますか？


オブジェクトの型に依ります。タプルなら、 @ref{50d8,,PyTuple_Size()} が長さを返し、 @ref{4eb7,,PyTuple_GetItem()} が指定されたインデックスの要素を返します。リストにも同様の関数 @ref{1633,,PyList_Size()} と @ref{5ff,,PyList_GetItem()} があります。

bytes では、 @ref{4f87,,PyBytes_Size()} がその長さを返し、 @ref{4f7f,,PyBytes_AsStringAndSize()} がその値へのポインタと長さを提供します。 Python の bytes オブジェクトは null を含むこともできるので、 C の @code{strlen()} を使うべきではないことに注意してください。

オブジェクトの型を検査するには、まず最初にそれが @code{NULL} でないことを確かめた上で、 @ref{15b7,,PyBytes_Check()} 、 @ref{5390,,PyTuple_Check()} 、 @ref{53a1,,PyList_Check()} などを使います。

いわゆる 'abstract' インターフェースから提供される、 Python オブジェクトに対する高レベル API もあります -- より詳しいことは @code{Include/abstract.h} を読んでください。これを使うと、数値型プロトコル (@ref{a93,,PyNumber_Index()} など) や PyMapping API のマップ型プロトコルなどの役に立つプロトコルに加え、 @ref{50a8,,PySequence_Length()} や @ref{1e34,,PySequence_GetItem()} などの任意の種類の Python シーケンスへのインターフェースにアクセスできます。

@node Py_BuildValue で任意長のタプルを作るにはどうしますか？,C からオブジェクトのメソッドを呼び出すにはどうしますか？,Python オブジェクトから C の値を取り出すにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length}@anchor{594c}
@subsection Py_BuildValue() で任意長のタプルを作るにはどうしますか？


できません。代わりに @ref{50d7,,PyTuple_Pack()} を使ってください。

@node C からオブジェクトのメソッドを呼び出すにはどうしますか？,PyErr_Print その他 stdout/stderr に印字するもの からの出力を受け取るにはどうしますか？,Py_BuildValue で任意長のタプルを作るにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-call-an-object-s-method-from-c}@anchor{594d}
@subsection C からオブジェクトのメソッドを呼び出すにはどうしますか？


@ref{640,,PyObject_CallMethod()} 関数でオブジェクトの任意のメソッドを呼び出せます。パラメタは、オブジェクト、呼び出すメソッドの名前、 @ref{3c2,,Py_BuildValue()} で使われるようなフォーマット文字列、そして引数です:

@example
PyObject *
PyObject_CallMethod(PyObject *object, const char *method_name,
                    const char *arg_format, ...);
@end example

これはメソッドを持ついかなるオブジェクトにも有効で、組み込みかユーザ定義かは関係ありません。返り値に対して @ref{790,,Py_DECREF()} する必要があることもあります。

例えば、あるファイルオブジェクトの "seek" メソッドを 10, 0 を引数として呼ぶとき (ファイルオブジェクトのポインタを "f" とします):

@example
res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
if (res == NULL) @{
        ... an exception occurred ...
@}
else @{
        Py_DECREF(res);
@}
@end example

なお、 @ref{4eac,,PyObject_CallObject()} の引数リストには `常に' タプルが必要です。関数を引数なしで呼び出すには、フォーマットに "()" を渡し、関数を一つの引数で呼び出すには、関数を括弧でくくって例えば "(i)" としてください。

@node PyErr_Print その他 stdout/stderr に印字するもの からの出力を受け取るにはどうしますか？,C から Python で書かれたモジュールにアクセスするにはどうしますか？,C からオブジェクトのメソッドを呼び出すにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr}@anchor{594e}
@subsection PyErr_Print() (その他 stdout/stderr に印字するもの) からの出力を受け取るにはどうしますか？


Python コード内で、 @code{write()} メソッドをサポートするオブジェクトを定義してください。そのオブジェクトを @ref{ccd,,sys.stdout} と @ref{b33,,sys.stderr} に代入してください。print_error を呼び出すか、単に標準のトレースバック機構を作動させてください。そうすれば、出力は @code{write()} が送る任意の所に行きます。

最も簡単な方法は、 @ref{112a,,io.StringIO} クラスを使うことです:

@example
>>> import io, sys
>>> sys.stdout = io.StringIO()
>>> print('foo')
>>> print('hello world!')
>>> sys.stderr.write(sys.stdout.getvalue())
foo
hello world!
@end example

これと同じことをするカスタムオブジェクトは次のようになるでしょう:

@example
>>> import io, sys
>>> class StdoutCatcher(io.TextIOBase):
...     def __init__(self):
...         self.data = []
...     def write(self, stuff):
...         self.data.append(stuff)
...
>>> import sys
>>> sys.stdout = StdoutCatcher()
>>> print('foo')
>>> print('hello world!')
>>> sys.stderr.write('@w{'}.join(sys.stdout.data))
foo
hello world!
@end example

@node C から Python で書かれたモジュールにアクセスするにはどうしますか？,Python から C++ へインターフェースするにはどうしますか？,PyErr_Print その他 stdout/stderr に印字するもの からの出力を受け取るにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-access-a-module-written-in-python-from-c}@anchor{594f}
@subsection C から Python で書かれたモジュールにアクセスするにはどうしますか？


以下のようにモジュールオブジェクトへのポインタを得られます:

@example
module = PyImport_ImportModule("<modulename>");
@end example

そのモジュールがまだインポートされていない (つまり、まだ @ref{17e6,,sys.modules} に現れていない) なら、これはモジュールを初期化します。そうでなければ、単純に @code{sys.modules["<modulename>"]} の値を返します。なお、これはモジュールをいかなる名前空間にも代入しません。これはモジュールが初期化されて '@ref{17e6,,sys.modules} に保管されていることを保証するだけです。

これで、モジュールの属性 (つまり、モジュールで定義された任意の名前) に以下のようにアクセスできるようになります:

@example
attr = PyObject_GetAttrString(module, "<attrname>");
@end example

@ref{198e,,PyObject_SetAttrString()} を呼んでモジュールの変数に代入することもできます。

@node Python から C++ へインターフェースするにはどうしますか？,セットアップファイルでモジュールを追加しようとしたらメイクに失敗しました。なぜですか？,C から Python で書かれたモジュールにアクセスするにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-interface-to-c-objects-from-python}@anchor{5950}
@subsection Python から C++ へインターフェースするにはどうしますか？


やりたいことに応じて、いろいろな方法があります。手動でやるなら、 @ref{1fbd,,"拡張と埋め込み" ドキュメント} を読むことから始めてください。なお、Python ランタイムシステムにとっては、 C と C++ はあまり変わりません。だから、C 構造体 (ポインタ)型に基づいて新しい Python の型を構築する方針は C++ オブジェクトに対しても有効です。

C++ ライブラリに関しては、 @ref{5947,,C を書くのは大変です。他の方法はありませんか？} を参照してください。

@node セットアップファイルでモジュールを追加しようとしたらメイクに失敗しました。なぜですか？,拡張をデバッグするにはどうしますか？,Python から C++ へインターフェースするにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending i-added-a-module-using-the-setup-file-and-the-make-fails-why}@anchor{5951}
@subsection セットアップファイルでモジュールを追加しようとしたらメイクに失敗しました。なぜですか？


セットアップは改行で終わらなければならなくて、改行がないと、ビルド工程は失敗します。(これを直すには、ある種の醜いシェルスクリプトハックが必要ですが、このバグは小さいものですから努力に見合う価値はないでしょう。)

@node 拡張をデバッグするにはどうしますか？,Linux システムで Python モジュールをコンパイルしたいのですが、見つからないファイルがあります。なぜですか？,セットアップファイルでモジュールを追加しようとしたらメイクに失敗しました。なぜですか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-debug-an-extension}@anchor{5952}
@subsection 拡張をデバッグするにはどうしますか？


動的にロードされた拡張に GDB を使うとき、拡張がロードされるまでブレークポイントを設定してはいけません。

@code{.gdbinit} ファイルに(または対話的に)、このコマンドを加えてください:

@example
br _PyImport_LoadDynamicModule
@end example

そして、GDB を起動するときに:

@example
$ gdb /local/bin/python
gdb) run myscript.py
gdb) continue # repeat until your extension is loaded
gdb) finish   # so that your extension is loaded
gdb) br myfunction.c:50
gdb) continue
@end example

@node Linux システムで Python モジュールをコンパイルしたいのですが、見つからないファイルがあります。なぜですか？,"不完全 incomplete な入力" を "不適切 invalid な入力" から区別するにはどうしますか？,拡張をデバッグするにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why}@anchor{5953}
@subsection Linux システムで Python モジュールをコンパイルしたいのですが、見つからないファイルがあります。なぜですか？


Most packaged versions of Python omit some files
required for compiling Python extensions.

For Red Hat, install the python3-devel RPM to get the necessary files.

For Debian, run @code{apt-get install python3-dev}.

@node "不完全 incomplete な入力" を "不適切 invalid な入力" から区別するにはどうしますか？,未定義の g++ シンボル __builtin_new や __pure_virtual を見つけるにはどうしますか？,Linux システムで Python モジュールをコンパイルしたいのですが、見つからないファイルがあります。なぜですか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-tell-incomplete-input-from-invalid-input}@anchor{5954}
@subsection "不完全 (incomplete) な入力" を "不適切 (invalid) な入力" から区別するにはどうしますか？


Python インタラクティブインタプリタでは、入力が不完全なとき (例えば、 "if" 文の始まりをタイプした時や、カッコや三重文字列引用符を閉じていない時など) には継続プロンプトを与えられますが、入力が不適切であるときには即座に構文エラーメッセージが与えられます。このようなふるまいを模倣したいことがあります。

Python では構文解析器のふるまいに十分に近い @ref{1d,,codeop} モジュールが使えます。例えば IDLE がこれを使っています。

これを C で行う最も簡単な方法は、 @ref{51c9,,PyRun_InteractiveLoop()} を (おそらく別のスレッドで) 呼び出し、Python インタプリタにあなたの入力を扱わせることです。独自の入力関数を指定するのに @ref{7a5,,PyOS_ReadlineFunctionPointer()} を設定することもできます。詳しいヒントは、 @code{Modules/readline.c} や @code{Parser/myreadline.c} を参照してください。

@node 未定義の g++ シンボル __builtin_new や __pure_virtual を見つけるにはどうしますか？,メソッドのいくつかは C で、その他は Python で実装されたオブジェクトクラスを 継承などで 作ることはできますか？,"不完全 incomplete な入力" を "不適切 invalid な入力" から区別するにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual}@anchor{5955}
@subsection 未定義の g++ シンボル __builtin_new や __pure_virtual を見つけるにはどうしますか？


g++ モジュールを動的にロードするには、Python を再コンパイルし、それを g++ で再リンク (Python Modules Makefile 内の LINKCC を変更) し、拡張を g++ でリンク (例えば @code{g++ -shared -o mymodule.so mymodule.o}) しなければなりません。

@node メソッドのいくつかは C で、その他は Python で実装されたオブジェクトクラスを 継承などで 作ることはできますか？,,未定義の g++ シンボル __builtin_new や __pure_virtual を見つけるにはどうしますか？,拡張と埋め込み FAQ
@anchor{faq/extending can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance}@anchor{5956}
@subsection メソッドのいくつかは C で、その他は Python で実装されたオブジェクトクラスを (継承などで) 作ることはできますか？


はい、 @ref{19b,,int} 、 @ref{24d,,list} 、 @ref{183,,dict} などのビルトインクラスから継承できます。

The Boost Python Library (BPL, @indicateurl{https://www.boost.org/libs/python/doc/index.html}) を使えば、これを C++ からできます。 (すなわち、BPL を使って C++ で書かれた拡張クラスを継承できます).

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Windows 上の Python FAQ,グラフィックユーザインターフェース FAQ,拡張と埋め込み FAQ,Python よくある質問
@anchor{faq/windows doc}@anchor{5957}@anchor{faq/windows python-on-windows-faq}@anchor{5958}@anchor{faq/windows translation-repo}@anchor{5959}@anchor{faq/windows windows-faq}@anchor{595a}
@section Windows 上の Python FAQ



@c XXX need review for Python 3.
@c XXX need review for Windows Vista/Seven?

@menu
* Python プログラムを Windows で動かすにはどうしますか？:: 
* Python スクリプトを実行可能にするにはどうしますか？:: 
* Python の起動に時間がかかることがあるのはなぜですか？:: 
* どうすれば Python スクリプトを EXE に出来ますか?:: 
* *.pyd ファイルは DLL と同じですか？: * pyd ファイルは DLL と同じですか？. 
* Python を Windows アプリケーションに埋め込むにはどうしたらいいですか？:: 
* エディタが Python ソースにタブを勝手に挿入しないようにするにはどうしますか？:: 
* ブロックすることなく押鍵を検出するにはどうしますか？:: 
* missing api-ms-win-crt-runtime-l1-1-0.dll エラーを解決するにはどうしますか？: missing api-ms-win-crt-runtime-l1-1-0 dll エラーを解決するにはどうしますか？. 

@end menu

@node Python プログラムを Windows で動かすにはどうしますか？,Python スクリプトを実行可能にするにはどうしますか？,,Windows 上の Python FAQ
@anchor{faq/windows faq-run-program-under-windows}@anchor{595b}@anchor{faq/windows how-do-i-run-a-python-program-under-windows}@anchor{595c}
@subsection Python プログラムを Windows で動かすにはどうしますか？


これは必ずしも単純な質問ではありません。Windows コマンドラインからプログラムを実行するのに慣れてしまっている場合は、全て明らかなことに思えるでしょう; そうでない場合は、もう少し手引きが必要でしょう。

ある種の統合開発環境を使っているのでなければ、最終的には "コマンドプロンプト" などと呼ばれているものに、 Windows コマンドをタイプすることになるでしょう。
通常そういうウィンドウは検索バーで @code{cmd} を検索して起動します。
通常は次のような見た目の Windows の "コマンド プロンプト" が現れるので、ウィンドウが起動したのが分かるはずです:

@example
C:\>
@end example

この文字は異なっていたり、続きがあったりするので、コンピュータの設定や、あなたが最近何をしたかに依って、このようになっていることもあるでしょう:

@example
D:\YourName\Projects\Python>
@end example

このようなウィンドウさえ開けば、Python プログラムを動かす手順は順調に進みます。

Python スクリプトは Python `インタプリタ' と呼ばれる別のプログラムで処理されなければならないということを、理解する必要があります。インタプリタはスクリプトを読み込み、バイトコードにコンパイルし、バイトコードを実行しプログラムを走らせます。では、インタプリタが Python スクリプトを取り扱うためには、どんな用意をするのでしょうか?

まず最初に、コマンドウィンドウに "py" という単語がインタプリタを起動する指示であると認識させる必要があります。
コマンドウィンドウを開いたら、 @code{py} というコマンドを入力し、リターンキーを叩いてください。:

@example
C:\Users\YourName> py
@end example

次のような出力が見えるでしょう:

@example
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
@end example

インタプリタの"対話モード"が始まりました。これで Python の文や式を対話的に入力して、待っている間に実行や評価させることができます。これが Python の最強の機能のひとつです。いくつかの式を選んで入力し、結果を見て確かめてみましょう:

@example
>>> print("Hello")
Hello
>>> "Hello" * 3
'HelloHelloHello'
@end example

多くの人が対話モードを便利で高度なプログラム可能計算機として使っています。対話式 Python セッションを終わらせたいなら、 @ref{25e7,,exit()} 関数を呼び出すか、 @code{Ctrl} キーを押しながら @code{Z} を入力し "@code{Enter}" キーを押して、 Windows コマンドプロンプトに戻ってください。

スタート ‣ すべてのプログラム ‣ Python 3.x ‣ Python (command line) のような項目がスタートメニューに見付かるかもしれません。
これを起動すると、新しいウィンドウに @code{>>>} というプロンプトが見られるでしょう。その場合、 @ref{25e7,,exit()} 関数を呼び出すか @code{Ctrl}-@code{Z} を入力するとウィンドウは閉じます; Windows は 1 つの "python" コマンドをウィンドウで実行していて、インタプリタを終了させたときに、そのウィンドウを閉じます。

@code{py} コマンドが認識されていることが確認できたので、 Python スクリプトを与えられるようになりました。
そのためには Python スクリプトの絶対パスあるいは相対パスを与える必要があります。
Python スクリプトがデスクトップにあり、 @code{hellp.py} という名前で、ちょうど良いことにコマンドプロンプトがホームディレクトリを開いていると仮定しましょう。そうすると次のような表示が見られます:

@example
C:\Users\YourName>
@end example

ここまで来れば @code{py} の後ろにスクリプトのパスを入力することで、 Python にスクリプトを渡すよう @code{py} コマンドに命令できます:

@example
C:\Users\YourName> py Desktop\hello.py
hello
@end example

@node Python スクリプトを実行可能にするにはどうしますか？,Python の起動に時間がかかることがあるのはなぜですか？,Python プログラムを Windows で動かすにはどうしますか？,Windows 上の Python FAQ
@anchor{faq/windows how-do-i-make-python-scripts-executable}@anchor{595d}
@subsection Python スクリプトを実行可能にするにはどうしますか？


Windows では、標準の Python インストーラはすでに .py 拡張子をあるファイル型 (Python.File) に関連付け、そのファイル型にインタプリタを実行するオープンコマンド (@code{D:\Program Files\Python\python.exe "%1" %*}) を与えます。コマンドプロンプトから 'foo.py' としてスクリプトを実行可能にするにはこれで十分です。スクリプトを拡張子なしで 'foo' とだけタイプして実行したいのなら、PATHEXT 環境変数に .py を加えてください。

@node Python の起動に時間がかかることがあるのはなぜですか？,どうすれば Python スクリプトを EXE に出来ますか?,Python スクリプトを実行可能にするにはどうしますか？,Windows 上の Python FAQ
@anchor{faq/windows why-does-python-sometimes-take-so-long-to-start}@anchor{595e}
@subsection Python の起動に時間がかかることがあるのはなぜですか？


通常 Python は Windows でとても早く起動しますが、ときどき Python が急にスタートアップに時間がかかるようになったというバグレポートがあります。更に複雑なことに、Python は同様に設定された他の Windows システムではきちんと動くのです。

この問題はそのマシンのウイルス対策ソフトウェアの設定ミスによって起こされることがあります。ウイルススキャナの中には、ファイルシステムからの全ての読み込みを監視するように設定した場合に、二桁のスタートアップオーバーヘッドを引き起すことが知られているものがあります。あなたのシステムのウイルススキャンソフトウェアの設定を確かめて、本当に同様に設定されていることを確実にしてください。

@node どうすれば Python スクリプトを EXE に出来ますか?,* pyd ファイルは DLL と同じですか？,Python の起動に時間がかかることがあるのはなぜですか？,Windows 上の Python FAQ
@anchor{faq/windows how-do-i-make-an-executable-from-a-python-script}@anchor{595f}
@subsection どうすれば Python スクリプトを EXE に出来ますか?


実行可能ファイルを作れるツールの一覧 @ref{58b3,,どうしたら Python スクリプトからスタンドアロンバイナリを作れますか？} を参照してください。

@node * pyd ファイルは DLL と同じですか？,Python を Windows アプリケーションに埋め込むにはどうしたらいいですか？,どうすれば Python スクリプトを EXE に出来ますか?,Windows 上の Python FAQ
@anchor{faq/windows is-a-pyd-file-the-same-as-a-dll}@anchor{5960}
@subsection @code{*.pyd} ファイルは DLL と同じですか？


はい、.pyd ファイルは dll と同じようなものですが、少し違いがあります。@code{foo.pyd} という名前の DLL があったとしたら、それには関数 @code{PyInit_foo()} が含まれていなければなりません。そうすれば Python で "import foo" を書けて、Python は foo.pyd (や foo.py、foo.pyc) を探して、あれば、@code{PyInit_foo()} を呼び出して初期化しようとします。Windows が DLL の存在を必要とするのと違い、.exe ファイルを foo.lib にリンクするわけではありません。

なお、foo.pyd を検索するパスは PYTHONPATH であり、Windows が foo.dll を検索するパスと同じではありません。また、プログラムを dll にリンクしたときはプログラムの実行に dll が必要ですが、foo.pyd は実行には必要はありません。もちろん、 @code{import foo} したいなら foo.pyd は必要です。DLL では、リンクはソースコード内で @code{__declspec(dllexport)} によって宣言されます。.pyd では、リンクは使える関数のリストで定義されます。

@node Python を Windows アプリケーションに埋め込むにはどうしたらいいですか？,エディタが Python ソースにタブを勝手に挿入しないようにするにはどうしますか？,* pyd ファイルは DLL と同じですか？,Windows 上の Python FAQ
@anchor{faq/windows how-can-i-embed-python-into-a-windows-application}@anchor{5961}
@subsection Python を Windows アプリケーションに埋め込むにはどうしたらいいですか？


Python インタプリタを Windows app に埋め込む方法は、次のように要約できます:


@enumerate 

@item 
あなたの .exe 内に直接 Python を取り込んでビルド `しないで' 下さい。Windows では、それ自身が DLL になっているようなモジュールのインポートを処理するために、Python は DLL でなければなりません。(ドキュメント化されていない重大な事実の一つ目です。)代わりに、 @code{python`NN'.dll} とリンクしてください; 普通はそれは @code{C:\Windows\System} にインストールされています。 `NN' は Python バージョンで Python 3.3 であれば "33" のような数字です。

Python には、load-time に、または run-time にリンクできます。load-time なリンクは、 @code{python`NN'.lib} に対してリンクするもので、run-time なリンクは @code{python`NN'.dll} に対してリンクするものです。(一般的な注意: @code{python`NN'.lib} は @code{python`NN'.dll} に対するいわゆる "インポートライブラリ" です。これは単にリンカに対するシンボルを定義します。)

run-time なリンクは、リンクの選択を大いに単純化します。全ては実行時に行われます。コードは Windows の @code{LoadLibraryEx()} ルーチンで @code{python`NN'.dll} をロードしなければなりません。コードはまた、Windows の @code{GetProcAddress()} ルーチンで得られるポインタで、 @code{python`NN'.dll} (すなわち、Python の C API)のルーチンとデータへアクセスしていなければなりません。マクロによって、このポインタを Python の C API のルーチンを呼び出す任意の C コードに通して使えます。

@c XXX what about static linking?

@item 
SWIG を使えば、app のデータとメソッドを Python で使えるようにする Python "拡張モジュール"を簡単に作れます。SWIG は雑用を殆どやってくれるでしょう。結果として、.exe ファイル `の中に' リンクする C コードができます(！)。DLL を作 `らなくてもよく'、リンクも簡潔になります。

@item 
SWIG は拡張の名前に依る名前の init 関数 (C 関数) を作ります。例えば、モジュールの名前が leo なら、init 関数の名前は initleo() になります。SWIG shadow クラスを使ったほうがよく、そうすると init 関数の名前は initleoc() になります。これは shadow クラスが使うほとんど隠れた helper クラスを初期化します。

ステップ 2 の C コードを .exe ファイルにリンクできるのは、初期化関数の呼び出しと Python へのモジュールのインポートが同等だからです！ (ドキュメント化されていない重大な事実の二つ目です)

@item 
要するに、以下のコードを使って Python インタプリタを拡張モジュール込みで初期化することができます。

@example
#include <Python.h>
...
Py_Initialize();  // Pythonの初期化
initmyAppc();  // ヘルパーclassの初期化(import)
PyRun_SimpleString("import myApp");  // shadowクラスのimport
@end example

@item 
Python の C API には、pythonNN.dll をビルドするのに使われたコンパイラ MSVC 以外のコンパイラを使うと現れる二つの問題があります。

問題 1: コンパイラによって @code{struct FILE} に対する概念が異なるため、@code{FILE *} 引数を取るいわゆる "超高水準" 関数は、多コンパイラ環境で働きません。実装の観点から、これらは超低水準関数になっています。

問題 2: SWIG は void 関数へのラッパを生成するときに以下のコードを生成します:

@example
Py_INCREF(Py_None);
_resultobj = Py_None;
return _resultobj;
@end example

ああ、Py_none は pythonNN.dll 内の _Py_NoneStruct という複雑なデータ構造に展開するマクロです。また、このコードは他コンパイラ環境では失敗します。このコードを次のように置き換えてください:

@example
return Py_BuildValue("");
@end example

これで、SWIG をまだ仕事に使えない (私は SWIG の完全な初心者です) 私でも、SWIG の @code{%typemap} コマンドを使って自動的に変更できるようになります。

@item 
Python シェルスクリプトを使って Windows app 内から Python インタプリタウィンドウを掲示するのはいい方法ではありません。そのように表示されるウィンドウは app のウィンドウシステムとは関係ありません。むしろ "ネイティブな" インタプリタウィンドウを (wxPythonWindow を使ったりして) 作るべきです。そのウィンドウを Python インタプリタにつなぐのは簡単です。Python の i/o は読み書きをサポートする _どんな_ オブジェクトにもリダイレクトできるので、read() と write() メソッドを含む (拡張モジュールで定義された) Python オブジェクトさえあればいいのです。
@end enumerate

@node エディタが Python ソースにタブを勝手に挿入しないようにするにはどうしますか？,ブロックすることなく押鍵を検出するにはどうしますか？,Python を Windows アプリケーションに埋め込むにはどうしたらいいですか？,Windows 上の Python FAQ
@anchor{faq/windows how-do-i-keep-editors-from-inserting-tabs-into-my-python-source}@anchor{5962}
@subsection エディタが Python ソースにタブを勝手に挿入しないようにするにはどうしますか？


この FAQ ではタブを使うことを勧めません。Python スタイルガイド 
@geindex Python Enhancement Proposals; PEP 8
PEP 8@footnote{https://peps.python.org/pep-0008/} では、配布される Python コードにはスペース 4 つを使うことを推奨しています。これは Emacs の python-mode のデフォルトでも同じです。

いかなるエディタでも、タブとスペースを混ぜるのは良くないです。 MSVC も全く同じ立場であり、スペースを使うようにする設定が簡単にできます。 Tools ‣ Options ‣ Tabs を選択し、ファイルタイプの "デフォルト" の "タブ幅" と "インデント幅" に 4 を設定して、 "スペースを挿入する" のラジオボタンを選択してください。

Python は、もしタブとスペースが混在していることで先頭の空白に問題がある場合、@ref{1750,,IndentationError} または @ref{765,,TabError} を送出します。
@ref{e3,,tabnanny} モジュールを実行することで、ディレクトリーツリーをバッチモードでチェックすることができます。

@node ブロックすることなく押鍵を検出するにはどうしますか？,missing api-ms-win-crt-runtime-l1-1-0 dll エラーを解決するにはどうしますか？,エディタが Python ソースにタブを勝手に挿入しないようにするにはどうしますか？,Windows 上の Python FAQ
@anchor{faq/windows how-do-i-check-for-a-keypress-without-blocking}@anchor{5963}
@subsection ブロックすることなく押鍵を検出するにはどうしますか？


@ref{97,,msvcrt} モジュールを使ってください。これは標準の Windows 専用拡張モジュールです。これはキーボードが打たれているかを調べる関数 @code{kbhit()} と、反響することなく一文字を得る @code{getch()} を定義します。

@node missing api-ms-win-crt-runtime-l1-1-0 dll エラーを解決するにはどうしますか？,,ブロックすることなく押鍵を検出するにはどうしますか？,Windows 上の Python FAQ
@anchor{faq/windows how-do-i-solve-the-missing-api-ms-win-crt-runtime-l1-1-0-dll-error}@anchor{5964}
@subsection missing api-ms-win-crt-runtime-l1-1-0.dll エラーを解決するにはどうしますか？


この問題は更新がインストールされていない Windows 8.1 以前を使っていると Python 3.5 以降で発生することがあります。まずはあなたのオペレーティングシステムがサポートされており最新であることを確認してください。それでも解決しない場合は、 C ランタイムアップデートの手動インストール方法について Microsoft support page@footnote{https://support.microsoft.com/en-us/help/3118401/} を参照してください。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node グラフィックユーザインターフェース FAQ,"なぜ Python が私のコンピュータにインストールされているのですか？" FAQ,Windows 上の Python FAQ,Python よくある質問
@anchor{faq/gui doc}@anchor{5965}@anchor{faq/gui graphic-user-interface-faq}@anchor{5966}@anchor{faq/gui translation-repo}@anchor{5967}
@section グラフィックユーザインターフェース FAQ



@c XXX need review for Python 3.

@menu
* 一般的な GUI の質問:: 
* Python の GUI ツールキットには何がありますか？:: 
* Tkinter の質問:: 

@end menu

@node 一般的な GUI の質問,Python の GUI ツールキットには何がありますか？,,グラフィックユーザインターフェース FAQ
@anchor{faq/gui general-gui-questions}@anchor{5968}
@subsection 一般的な GUI の質問


@node Python の GUI ツールキットには何がありますか？,Tkinter の質問,一般的な GUI の質問,グラフィックユーザインターフェース FAQ
@anchor{faq/gui what-gui-toolkits-exist-for-python}@anchor{5969}
@subsection Python の GUI ツールキットには何がありますか？


Python の標準的なビルドには、 @ref{42e1,,tkinter} という Tcl/Tk ウィジェットセットのオブジェクト指向インターフェースが含まれています。これは最も簡単にインストールして使えるでしょう (なぜなら、これは Python のほとんどの バイナリディストリビューション@footnote{https://www.python.org/downloads/} に同梱されているからです)。ソースへのポインタなど、 Tk に関する詳しい情報は、 Tcl/Tk ホームページ@footnote{https://www.tcl.tk} を参照してください。 Tcl/Tk は、 macOS 、Windows 、 Unix プラットフォームに完全にポータブルです。

対象とするプラットフォームによっては他の選択肢もあります。プラットフォーム互換@footnote{https://wiki.python.org/moin/GuiProgramming#Cross-Platform_Frameworks} および プラットフォーム固有@footnote{https://wiki.python.org/moin/GuiProgramming#Platform-specific_Frameworks} の GUI フレームワークのリストを python wiki で参照できます。

@node Tkinter の質問,,Python の GUI ツールキットには何がありますか？,グラフィックユーザインターフェース FAQ
@anchor{faq/gui tkinter-questions}@anchor{596a}
@subsection Tkinter の質問


@menu
* Tkinter アプリケーションを凍結するにはどうしますか？:: 
* I/O を待つ間に扱われる Tk イベントを作れますか？:: 
* Tkinter で働くキーバインディングが得られません。なぜですか？:: 

@end menu

@node Tkinter アプリケーションを凍結するにはどうしますか？,I/O を待つ間に扱われる Tk イベントを作れますか？,,Tkinter の質問
@anchor{faq/gui how-do-i-freeze-tkinter-applications}@anchor{596b}
@subsubsection Tkinter アプリケーションを凍結するにはどうしますか？


Freeze はスタンドアロンアプリケーションを生成するツールです。Tkinter アプリケーションを凍結するとき、それは Tcl と Tk ライブラリを必要とするので、真のスタンドアロンにはなりません。

一つの解決策は、アプリケーションに Tcl と Tk ライブラリを同梱し、環境変数 @code{TCL_LIBRARY} と @code{TK_LIBRARY} でランタイムに指定することです。

Various third-party freeze libraries such as py2exe and cx_Freeze have
handling for Tkinter applications built-in.

@node I/O を待つ間に扱われる Tk イベントを作れますか？,Tkinter で働くキーバインディングが得られません。なぜですか？,Tkinter アプリケーションを凍結するにはどうしますか？,Tkinter の質問
@anchor{faq/gui can-i-have-tk-events-handled-while-waiting-for-i-o}@anchor{596c}
@subsubsection I/O を待つ間に扱われる Tk イベントを作れますか？


Windows 以外のプラットフォームについては、はい、スレッドさえ必要ありません！  ただし、I/O コードを少し再構成しなければなりません。Tk には Xt の @code{XtAddInput()} コールと同等なものがあるので、ファイルディスクリプタ上で I/O が可能なときに Tk メインループから呼ばれるコールバック関数を登録できます。 @ref{42ff,,ファイルハンドラ} を参照してください。

@node Tkinter で働くキーバインディングが得られません。なぜですか？,,I/O を待つ間に扱われる Tk イベントを作れますか？,Tkinter の質問
@anchor{faq/gui i-can-t-get-key-bindings-to-work-in-tkinter-why}@anchor{596d}
@subsubsection Tkinter で働くキーバインディングが得られません。なぜですか？


@code{bind()} メソッドでイベントに @ref{42fa,,結び付けられた} イベントハンドラが、適切なキーが押されたときにさえハンドルされないという苦情がよく聞かれます。

最も一般的な原因は、バインディングが適用されるウィジェットが "キーボードフォーカス" を持たないことです。Tk ドキュメントでフォーカスコマンドを確認してください。通常はウィジェットの中をクリックすることでキーボードフォーカスを与えられます (ただしラベルには与えられません。takefocus オプションを参照してください)。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node "なぜ Python が私のコンピュータにインストールされているのですか？" FAQ,,グラフィックユーザインターフェース FAQ,Python よくある質問
@anchor{faq/installed doc}@anchor{596e}@anchor{faq/installed translation-repo}@anchor{596f}@anchor{faq/installed why-is-python-installed-on-my-computer-faq}@anchor{5970}
@section "なぜ Python が私のコンピュータにインストールされているのですか？" FAQ


@menu
* Python とは何ですか？: Python とは何ですか？<2>. 
* なぜ Python が私のマシンにインストールされているのですか？:: 
* Python を削除してもいいですか？:: 

@end menu

@node Python とは何ですか？<2>,なぜ Python が私のマシンにインストールされているのですか？,,"なぜ Python が私のコンピュータにインストールされているのですか？" FAQ
@anchor{faq/installed what-is-python}@anchor{5971}
@subsection Python とは何ですか？


Python はプログラミング言語の一つです。Python は様々なアプリケーションに使われています。Python は習得しやすいので、一部の高校や大学で入門用のプログラミング言語として使われています。一方で、Google、NASA、Lucasfilm Ltd. のような組織でプロフェッショナルなソフトウェア開発者にも使われています。

Python についてもっと詳しく知りたいなら、Beginner's Guide to Python@footnote{https://wiki.python.org/moin/BeginnersGuide} から始めましょう。

@node なぜ Python が私のマシンにインストールされているのですか？,Python を削除してもいいですか？,Python とは何ですか？<2>,"なぜ Python が私のコンピュータにインストールされているのですか？" FAQ
@anchor{faq/installed why-is-python-installed-on-my-machine}@anchor{5972}
@subsection なぜ Python が私のマシンにインストールされているのですか？


インストールした覚えがないのに Python があなたのシステムにインストールされているとしたら、その理由にはいくつかの可能性があります。


@itemize *

@item 
もしかしたら、コンピュータの他のユーザがプログラミングを学ぶためにインストールしたのかもしれません。誰がそのマシンを使っていて Python をインストールしたか知る必要があります。

@item 
マシンにインストールされているサードパーティのアプリケーションが、Python で書かれていて Python のインストールを含んでいるかもしれません。そのようなアプリケーションは、GUI プログラムからネットワーク・サーバや管理スクリプトまで、たくさんあります。

@item 
Windows マシンにも Python がインストールされたものがあります。この執筆時点で Hewlett-Packard や Compaq が Python を組み込んでいることを確認しています。 HP/Compaq の管理ツールの中には、Python で書かれたものもあるようです。

@item 
macOS や一部の Linux ディストリビューションなど、多くの Unix 互換オペレーティングシステムシステムには、Python がデフォルトでインストールされています。標準インストールに Python が含まれているのです。
@end itemize

@node Python を削除してもいいですか？,,なぜ Python が私のマシンにインストールされているのですか？,"なぜ Python が私のコンピュータにインストールされているのですか？" FAQ
@anchor{faq/installed can-i-delete-python}@anchor{5973}
@subsection Python を削除してもいいですか？


Python をどこから手に入れたかによります。

誰かが Python を意図してダウンロードしたのであれば、何の問題もなく削除することができます。Windows では、コントロールパネルのプログラムの追加と削除を使ってください。

Python がサードパーティのアプリケーションによってインストールされたなら、同様に削除できますが、そのアプリケーションは動作しなくなります。 Python のディレクトリを削除するのではなく、そのアプリケーションのアンインストーラーを使うべきです。

Python がオペレーティングシステムに含まれて来たなら、削除はお勧めできません。削除してしまうと、Python で書かれたプログラムは全く動かなくなり、その中には重要なものが含まれているかもしれません。その場合、修復にはシステム全体の再インストールが必要になるでしょう。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 非推奨<14>,用語集<2>,Python よくある質問,Top
@anchor{deprecations/index doc}@anchor{5974}@anchor{deprecations/index deprecations}@anchor{5975}@anchor{deprecations/index translation-repo}@anchor{5976}
@chapter 非推奨


@menu
* Pending removal in Python 3.15: Pending removal in Python 3 15<7>. 
* Pending removal in Python 3.16: Pending removal in Python 3 16<7>. 
* Pending removal in Python 3.17: Pending removal in Python 3 17<4>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<5>. 
* Pending removal in Python 3.19: Pending removal in Python 3 19<3>. 
* Pending removal in future versions: Pending removal in future versions<7>. 
* C API deprecations:: 

@end menu

@node Pending removal in Python 3 15<7>,Pending removal in Python 3 16<7>,,非推奨<14>
@anchor{deprecations/index pending-removal-in-python-3-15}@anchor{5977}
@section Pending removal in Python 3.15



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{321,,__cached__} on a module while
failing to set @ref{322,,__spec__.cached}
is deprecated. In Python 3.15, @code{__cached__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})

@item 
Setting @ref{323,,__package__} on a module while
failing to set @ref{324,,__spec__.parent}
is deprecated. In Python 3.15, @code{__package__} will cease to be set or
take into consideration by the import system or standard library. (gh-97879@footnote{https://github.com/python/cpython/issues/97879})
@end itemize

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
The undocumented @code{ctypes.SetPointerType()} function
has been deprecated since Python 3.13.
@end itemize

@item 
@ref{76,,http.server}:


@itemize *

@item 
The obsolete and rarely used @ref{325,,CGIHTTPRequestHandler}
has been deprecated since Python 3.13.
No direct replacement exists.
`Anything' is better than CGI to interface
a web server with a request handler.

@item 
The @code{--cgi} flag to the @code{python -m http.server}
command-line interface has been deprecated since Python 3.13.
@end itemize

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@code{load_module()} method: use @code{exec_module()} instead.
@end itemize

@item 
@ref{8a,,locale}:


@itemize *

@item 
The @ref{326,,getdefaultlocale()} function
has been deprecated since Python 3.11.
Its removal was originally planned for Python 3.13 (gh-90817@footnote{https://github.com/python/cpython/issues/90817}),
but has been postponed to Python 3.15.
Use @ref{327,,getlocale()}, @ref{328,,setlocale()},
and @ref{329,,getencoding()} instead.
(Contributed by Hugo van Kemenade in gh-111187@footnote{https://github.com/python/cpython/issues/111187}.)
@end itemize

@item 
@ref{a8,,pathlib}:


@itemize *

@item 
@ref{32a,,PurePath.is_reserved()}
has been deprecated since Python 3.13.
Use @ref{32b,,os.path.isreserved()} to detect reserved paths on Windows.
@end itemize

@item 
@ref{af,,platform}:


@itemize *

@item 
@ref{32c,,java_ver()} has been deprecated since Python 3.13.
This function is only useful for Jython support, has a confusing API,
and is largely untested.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The `check_home' argument of @ref{32d,,sysconfig.is_python_build()} has been
deprecated since Python 3.12.
@end itemize

@item 
@ref{f3,,threading}:


@itemize *

@item 
@ref{32e,,RLock()} will take no arguments in Python 3.15.
Passing any arguments has been deprecated since Python 3.14,
as the Python version does not permit any arguments,
but the C version allows any number of positional or keyword arguments,
ignoring every argument.
@end itemize

@item 
@ref{109,,types}:


@itemize *

@item 
@ref{32f,,types.CodeType}: Accessing @ref{330,,co_lnotab} was
deprecated in 
@geindex Python Enhancement Proposals; PEP 626
PEP 626@footnote{https://peps.python.org/pep-0626/}
since 3.10 and was planned to be removed in 3.12,
but it only got a proper @ref{1a3,,DeprecationWarning} in 3.12.
May be removed in 3.15.
(Contributed by Nikita Sobolev in gh-101866@footnote{https://github.com/python/cpython/issues/101866}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize *

@item 
The undocumented keyword argument syntax for creating
@ref{331,,NamedTuple} classes
(for example, @code{Point = NamedTuple("Point", x=int, y=int)})
has been deprecated since Python 3.13.
Use the class-based syntax or the functional syntax instead.

@item 
When using the functional syntax of @ref{332,,TypedDict}s, failing
to pass a value to the `fields' parameter (@code{TD = TypedDict("TD")}) or
passing @code{None} (@code{TD = TypedDict("TD", None)}) has been deprecated
since Python 3.13.
Use @code{class TD(TypedDict): pass} or @code{TD = TypedDict("TD", @{@})}
to create a TypedDict with zero field.

@item 
The @ref{333,,typing.no_type_check_decorator()} decorator function
has been deprecated since Python 3.13.
After eight years in the @ref{10a,,typing} module,
it has yet to be supported by any major type checker.
@end itemize

@item 
@ref{119,,wave}:


@itemize *

@item 
The @ref{334,,getmark()}, @code{setmark()},
and @ref{335,,getmarkers()} methods of
the @ref{336,,Wave_read} and @ref{337,,Wave_write} classes
have been deprecated since Python 3.13.
@end itemize

@item 
@ref{138,,zipimport}:


@itemize *

@item 
@ref{338,,load_module()} has been deprecated since
Python 3.10. Use @ref{339,,exec_module()} instead.
(Contributed by Jiahao Li in gh-125746@footnote{https://github.com/python/cpython/issues/125746}.)
@end itemize
@end itemize

@node Pending removal in Python 3 16<7>,Pending removal in Python 3 17<4>,Pending removal in Python 3 15<7>,非推奨<14>
@anchor{deprecations/index pending-removal-in-python-3-16}@anchor{5978}
@section Pending removal in Python 3.16



@itemize *

@item 
The import system:


@itemize *

@item 
Setting @ref{33b,,__loader__} on a module while
failing to set @ref{33c,,__spec__.loader}
is deprecated. In Python 3.16, @code{__loader__} will cease to be set or
taken into consideration by the import system or the standard library.
@end itemize

@item 
@ref{8,,array}:


@itemize *

@item 
The @code{'u'} format code (@code{wchar_t})
has been deprecated in documentation since Python 3.3
and at runtime since Python 3.13.
Use the @code{'w'} format code (@ref{33d,,Py_UCS4})
for Unicode characters instead.
@end itemize

@item 
@ref{b,,asyncio}:


@itemize *

@item 
@code{asyncio.iscoroutinefunction()} is deprecated
and will be removed in Python 3.16;
use @ref{30d,,inspect.iscoroutinefunction()} instead.
(Contributed by Jiahao Li and Kumar Aditya in gh-122875@footnote{https://github.com/python/cpython/issues/122875}.)

@item 
@ref{b,,asyncio} policy system is deprecated and will be removed in Python 3.16.
In particular, the following classes and functions are deprecated:


@itemize *

@item 
@ref{30e,,asyncio.AbstractEventLoopPolicy}

@item 
@ref{30f,,asyncio.DefaultEventLoopPolicy}

@item 
@ref{310,,asyncio.WindowsSelectorEventLoopPolicy}

@item 
@ref{311,,asyncio.WindowsProactorEventLoopPolicy}

@item 
@ref{312,,asyncio.get_event_loop_policy()}

@item 
@ref{313,,asyncio.set_event_loop_policy()}
@end itemize

Users should use @ref{2f3,,asyncio.run()} or @ref{2f5,,asyncio.Runner} with
`loop_factory' to use the desired event loop implementation.

For example, to use @ref{314,,asyncio.SelectorEventLoop} on Windows:

@example
import asyncio

async def main():
    ...

asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
@end example

(Contributed by Kumar Aditya in gh-127949@footnote{https://github.com/python/cpython/issues/127949}.)
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Bitwise inversion on boolean types, @code{~True} or @code{~False}
has been deprecated since Python 3.12,
as it produces surprising and unintuitive results (@code{-2} and @code{-1}).
Use @code{not x} instead for the logical negation of a Boolean.
In the rare case that you need the bitwise inversion of
the underlying integer, convert to @code{int} explicitly (@code{~int(x)}).
@end itemize

@item 
@ref{63,,functools}:


@itemize *

@item 
Calling the Python implementation of @ref{21a,,functools.reduce()} with `function'
or `sequence' as keyword arguments has been deprecated since Python 3.14.
@end itemize

@item 
@ref{8b,,logging}:

Support for custom logging handlers with the `strm' argument is deprecated
and scheduled for removal in Python 3.16. Define handlers with the `stream'
argument instead. (Contributed by Mariusz Felisiak in gh-115032@footnote{https://github.com/python/cpython/issues/115032}.)

@item 
@ref{93,,mimetypes}:


@itemize *

@item 
Valid extensions start with a '.' or are empty for
@ref{319,,mimetypes.MimeTypes.add_type()}.
Undotted extensions are deprecated and will
raise a @ref{2ec,,ValueError} in Python 3.16.
(Contributed by Hugo van Kemenade in gh-75223@footnote{https://github.com/python/cpython/issues/75223}.)
@end itemize

@item 
@ref{ca,,shutil}:


@itemize *

@item 
The @code{ExecError} exception
has been deprecated since Python 3.14.
It has not been used by any function in @code{shutil} since Python 3.4,
and is now an alias of @ref{244,,RuntimeError}.
@end itemize

@item 
@ref{de,,symtable}:


@itemize *

@item 
The @ref{31d,,Class.get_methods} method
has been deprecated since Python 3.14.
@end itemize

@item 
@ref{df,,sys}:


@itemize *

@item 
The @ref{33e,,_enablelegacywindowsfsencoding()} function
has been deprecated since Python 3.13.
Use the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 環境変数; PYTHONLEGACYWINDOWSFSENCODING
@ref{33f,,PYTHONLEGACYWINDOWSFSENCODING} environment variable instead.
@end itemize

@item 
@ref{e1,,sysconfig}:


@itemize *

@item 
The @code{sysconfig.expand_makefile_vars()} function
has been deprecated since Python 3.14.
Use the @code{vars} argument of @ref{340,,sysconfig.get_paths()} instead.
@end itemize

@item 
@ref{e4,,tarfile}:


@itemize *

@item 
The undocumented and unused @code{TarFile.tarfile} attribute
has been deprecated since Python 3.13.
@end itemize
@end itemize

@node Pending removal in Python 3 17<4>,Pending removal in Python 3 18<5>,Pending removal in Python 3 16<7>,非推奨<14>
@anchor{deprecations/index pending-removal-in-python-3-17}@anchor{5979}
@section Pending removal in Python 3.17



@itemize *

@item 
@ref{1f,,collections.abc}:


@itemize -

@item 
@ref{342,,collections.abc.ByteString} is scheduled for removal in Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize

@item 
@ref{10a,,typing}:


@itemize -

@item 
Before Python 3.14, old-style unions were implemented using the private class
@code{typing._UnionGenericAlias}. This class is no longer needed for the implementation,
but it has been retained for backward compatibility, with removal scheduled for Python
3.17. Users should use documented introspection helpers like @ref{2ab,,typing.get_origin()}
and @ref{2ac,,typing.get_args()} instead of relying on private implementation details.

@item 
@ref{345,,typing.ByteString}, deprecated since Python 3.9, is scheduled for removal in
Python 3.17.

Use @code{isinstance(obj, collections.abc.Buffer)} to test if @code{obj}
implements the @ref{260,,buffer protocol} at runtime. For use
in type annotations, either use @ref{343,,Buffer} or a union
that explicitly specifies the types your code supports (e.g.,
@code{bytes | bytearray | memoryview}).

@code{ByteString} was originally intended to be an abstract class that
would serve as a supertype of both @ref{192,,bytes} and @ref{344,,bytearray}.
However, since the ABC never had any methods, knowing that an object was an
instance of @code{ByteString} never actually told you anything useful
about the object. Other common buffer types such as @ref{165,,memoryview}
were also never understood as subtypes of @code{ByteString} (either at
runtime or by static type checkers).

See 
@geindex Python Enhancement Proposals; PEP 688#current-options
PEP 688@footnote{https://peps.python.org/pep-0688/#current-options} for more details.
(Contributed by Shantanu Jain in gh-91896@footnote{https://github.com/python/cpython/issues/91896}.)
@end itemize
@end itemize

@node Pending removal in Python 3 18<5>,Pending removal in Python 3 19<3>,Pending removal in Python 3 17<4>,非推奨<14>
@anchor{deprecations/index pending-removal-in-python-3-18}@anchor{597a}
@section Pending removal in Python 3.18



@itemize *

@item 
@ref{3a,,decimal}:


@itemize *

@item 
The non-standard and undocumented @ref{1fe,,Decimal} format
specifier @code{'N'}, which is only supported in the @code{decimal} module's
C implementation, has been deprecated since Python 3.13.
(Contributed by Serhiy Storchaka in gh-89902@footnote{https://github.com/python/cpython/issues/89902}.)
@end itemize
@end itemize

@node Pending removal in Python 3 19<3>,Pending removal in future versions<7>,Pending removal in Python 3 18<5>,非推奨<14>
@anchor{deprecations/index pending-removal-in-python-3-19}@anchor{597b}
@section Pending removal in Python 3.19



@itemize *

@item 
@ref{2e,,ctypes}:


@itemize *

@item 
Implicitly switching to the MSVC-compatible struct layout by setting
@ref{317,,_pack_} but not @ref{1e7,,_layout_}
on non-Windows platforms.
@end itemize
@end itemize

@node Pending removal in future versions<7>,C API deprecations,Pending removal in Python 3 19<3>,非推奨<14>
@anchor{deprecations/index pending-removal-in-future-versions}@anchor{597c}
@section Pending removal in future versions


The following APIs will be removed in the future,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{7,,argparse}:


@itemize *

@item 
Nesting argument groups and nesting mutually exclusive
groups are deprecated.

@item 
Passing the undocumented keyword argument `prefix_chars' to
@ref{2eb,,add_argument_group()} is now
deprecated.

@item 
The @ref{30c,,argparse.FileType} type converter is deprecated.
@end itemize

@item 
@ref{13,,builtins}:


@itemize *

@item 
Generators: @code{throw(type, exc, tb)} and @code{athrow(type, exc, tb)}
signature is deprecated: use @code{throw(exc)} and @code{athrow(exc)} instead,
the single argument signature.

@item 
Currently Python accepts numeric literals immediately followed by keywords,
for example @code{0in x}, @code{1or x}, @code{0if 1else 2}.  It allows confusing and
ambiguous expressions like @code{[0x1for x in y]} (which can be interpreted as
@code{[0x1 for x in y]} or @code{[0x1f or x in y]}).  A syntax warning is raised
if the numeric literal is immediately followed by one of keywords
@ref{349,,and}, @ref{17c,,else}, @ref{34a,,for}, @ref{181,,if},
@ref{34b,,in}, @ref{34c,,is} and @ref{34d,,or}.  In a future release it
will be changed to a syntax error. (gh-87999@footnote{https://github.com/python/cpython/issues/87999})

@item 
Support for @code{__index__()} and @code{__int__()} method returning non-int type:
these methods will be required to return an instance of a strict subclass of
@ref{19b,,int}.

@item 
Support for @code{__float__()} method returning a strict subclass of
@ref{196,,float}: these methods will be required to return an instance of
@ref{196,,float}.

@item 
Support for @code{__complex__()} method returning a strict subclass of
@ref{197,,complex}: these methods will be required to return an instance of
@ref{197,,complex}.

@item 
Passing a complex number as the `real' or `imag' argument in the
@ref{197,,complex()} constructor is now deprecated; it should only be passed
as a single positional argument.
(Contributed by Serhiy Storchaka in gh-109218@footnote{https://github.com/python/cpython/issues/109218}.)
@end itemize

@item 
@ref{15,,calendar}: @code{calendar.January} and @code{calendar.February} constants are
deprecated and replaced by @ref{34e,,calendar.JANUARY} and
@ref{34f,,calendar.FEBRUARY}.
(Contributed by Prince Roshan in gh-103636@footnote{https://github.com/python/cpython/issues/103636}.)

@item 
@ref{1c,,codecs}: use @ref{316,,open()} instead of @ref{315,,codecs.open()}. (gh-133038@footnote{https://github.com/python/cpython/issues/133038})

@item 
@ref{330,,codeobject.co_lnotab}: use the @ref{350,,codeobject.co_lines()} method
instead.

@item 
@ref{34,,datetime}:


@itemize *

@item 
@ref{351,,utcnow()}:
use @code{datetime.datetime.now(tz=datetime.UTC)}.

@item 
@ref{352,,utcfromtimestamp()}:
use @code{datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)}.
@end itemize

@item 
@ref{67,,gettext}: Plural value must be an integer.

@item 
@ref{7b,,importlib}:


@itemize *

@item 
@ref{353,,cache_from_source()} `debug_override' parameter is
deprecated: use the `optimization' parameter instead.
@end itemize

@item 
@ref{7e,,importlib.metadata}:


@itemize *

@item 
@code{EntryPoints} tuple interface.

@item 
Implicit @code{None} on return values.
@end itemize

@item 
@ref{8b,,logging}: the @code{warn()} method has been deprecated
since Python 3.3, use @ref{354,,warning()} instead.

@item 
@ref{8f,,mailbox}: Use of StringIO input and text mode is deprecated, use
BytesIO and binary mode instead.

@item 
@ref{a5,,os}: Calling @ref{355,,os.register_at_fork()} in multi-threaded process.

@item 
@code{pydoc.ErrorDuringImport}: A tuple value for `exc_info' parameter is
deprecated, use an exception instance.

@item 
@ref{be,,re}: More strict rules are now applied for numerical group references
and group names in regular expressions.  Only sequence of ASCII digits is now
accepted as a numerical reference.  The group name in bytes patterns and
replacement strings can now only contain ASCII letters and digits and
underscore.
(Contributed by Serhiy Storchaka in gh-91760@footnote{https://github.com/python/cpython/issues/91760}.)

@item 
@code{sre_compile}, @code{sre_constants} and @code{sre_parse} modules.

@item 
@ref{ca,,shutil}: @ref{356,,rmtree()}'s `onerror' parameter is deprecated in
Python 3.12; use the `onexc' parameter instead.

@item 
@ref{d5,,ssl} options and protocols:


@itemize *

@item 
@ref{357,,ssl.SSLContext} without protocol argument is deprecated.

@item 
@ref{357,,ssl.SSLContext}: @ref{358,,set_npn_protocols()} and
@code{selected_npn_protocol()} are deprecated: use ALPN
instead.

@item 
@code{ssl.OP_NO_SSL*} options

@item 
@code{ssl.OP_NO_TLS*} options

@item 
@code{ssl.PROTOCOL_SSLv3}

@item 
@code{ssl.PROTOCOL_TLS}

@item 
@code{ssl.PROTOCOL_TLSv1}

@item 
@code{ssl.PROTOCOL_TLSv1_1}

@item 
@code{ssl.PROTOCOL_TLSv1_2}

@item 
@code{ssl.TLSVersion.SSLv3}

@item 
@code{ssl.TLSVersion.TLSv1}

@item 
@code{ssl.TLSVersion.TLSv1_1}
@end itemize

@item 
@ref{f3,,threading} methods:


@itemize *

@item 
@code{threading.Condition.notifyAll()}: use @ref{359,,notify_all()}.

@item 
@code{threading.Event.isSet()}: use @ref{35a,,is_set()}.

@item 
@code{threading.Thread.isDaemon()}, @ref{35b,,threading.Thread.setDaemon()}:
use @ref{35c,,threading.Thread.daemon} attribute.

@item 
@code{threading.Thread.getName()}, @ref{35d,,threading.Thread.setName()}:
use @ref{2a0,,threading.Thread.name} attribute.

@item 
@code{threading.currentThread()}: use @ref{35e,,threading.current_thread()}.

@item 
@code{threading.activeCount()}: use @ref{35f,,threading.active_count()}.
@end itemize

@item 
@ref{360,,typing.Text} (gh-92332@footnote{https://github.com/python/cpython/issues/92332}).

@item 
The internal class @code{typing._UnionGenericAlias} is no longer used to implement
@ref{2a8,,typing.Union}. To preserve compatibility with users using this private
class, a compatibility shim will be provided until at least Python 3.17. (Contributed by
Jelle Zijlstra in gh-105499@footnote{https://github.com/python/cpython/issues/105499}.)

@item 
@ref{361,,unittest.IsolatedAsyncioTestCase}: it is deprecated to return a value
that is not @code{None} from a test case.

@item 
@ref{110,,urllib.parse} deprecated functions: @ref{362,,urlparse()} instead


@itemize *

@item 
@code{splitattr()}

@item 
@code{splithost()}

@item 
@code{splitnport()}

@item 
@code{splitpasswd()}

@item 
@code{splitport()}

@item 
@code{splitquery()}

@item 
@code{splittag()}

@item 
@code{splittype()}

@item 
@code{splituser()}

@item 
@code{splitvalue()}

@item 
@code{to_bytes()}
@end itemize

@item 
@ref{11e,,wsgiref}: @code{SimpleHandler.stdout.write()} should not do partial
writes.

@item 
@ref{12b,,xml.etree.ElementTree}: Testing the truth value of an
@ref{363,,Element} is deprecated. In a future release it
will always return @code{True}. Prefer explicit @code{len(elem)} or
@code{elem is not None} tests instead.

@item 
@ref{292,,sys._clear_type_cache()} is deprecated:
use @ref{364,,sys._clear_internal_caches()} instead.
@end itemize

@node C API deprecations,,Pending removal in future versions<7>,非推奨<14>
@anchor{deprecations/index c-api-deprecations}@anchor{597d}
@section C API deprecations


@menu
* Pending removal in Python 3.15: Pending removal in Python 3 15<8>. 
* Pending removal in Python 3.18: Pending removal in Python 3 18<6>. 
* Pending removal in future versions: Pending removal in future versions<8>. 

@end menu

@node Pending removal in Python 3 15<8>,Pending removal in Python 3 18<6>,,C API deprecations
@anchor{deprecations/index id1}@anchor{597e}
@subsection Pending removal in Python 3.15



@itemize *

@item 
The @ref{3db,,PyImport_ImportModuleNoBlock()}:
Use @ref{3dc,,PyImport_ImportModule()} instead.

@item 
@ref{3dd,,PyWeakref_GetObject()} and @ref{3de,,PyWeakref_GET_OBJECT()}:
Use @ref{3df,,PyWeakref_GetRef()} instead. The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{3df,,PyWeakref_GetRef()} on Python 3.12 and older.

@item 
@ref{3e0,,Py_UNICODE} type and the @code{Py_UNICODE_WIDE} macro:
Use @code{wchar_t} instead.

@item 
@code{PyUnicode_AsDecodedObject()}:
Use @ref{3e1,,PyCodec_Decode()} instead.

@item 
@code{PyUnicode_AsDecodedUnicode()}:
Use @ref{3e1,,PyCodec_Decode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{169,,str}, such as @ref{192,,bytes}.

@item 
@code{PyUnicode_AsEncodedObject()}:
Use @ref{3e2,,PyCodec_Encode()} instead.

@item 
@code{PyUnicode_AsEncodedUnicode()}:
Use @ref{3e2,,PyCodec_Encode()} instead; Note that some codecs (for example, "base64")
may return a type other than @ref{192,,bytes}, such as @ref{169,,str}.

@item 
Python initialization functions, deprecated in Python 3.13:


@itemize *

@item 
@ref{3e3,,Py_GetPath()}:
Use @ref{37c,,PyConfig_Get("module_search_paths")}
(@ref{3e4,,sys.path}) instead.

@item 
@ref{3e5,,Py_GetPrefix()}:
Use @ref{37c,,PyConfig_Get("base_prefix")}
(@ref{3e6,,sys.base_prefix}) instead. Use @ref{37c,,PyConfig_Get("prefix")} (@ref{3e7,,sys.prefix}) if @ref{3e8,,virtual environments} need to be handled.

@item 
@ref{3e9,,Py_GetExecPrefix()}:
Use @ref{37c,,PyConfig_Get("base_exec_prefix")}
(@ref{3ea,,sys.base_exec_prefix}) instead. Use
@ref{37c,,PyConfig_Get("exec_prefix")}
(@ref{3eb,,sys.exec_prefix}) if @ref{3e8,,virtual environments} need to
be handled.

@item 
@ref{3ec,,Py_GetProgramFullPath()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ee,,Py_GetProgramName()}:
Use @ref{37c,,PyConfig_Get("executable")}
(@ref{3ed,,sys.executable}) instead.

@item 
@ref{3ef,,Py_GetPythonHome()}:
Use @ref{37c,,PyConfig_Get("home")} or the
@geindex PYTHONHOME
@geindex 環境変数; PYTHONHOME
@ref{3f0,,PYTHONHOME} environment variable instead.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
@ref{37c,,PyConfig_Get()} on Python 3.13 and older.

@item 
Functions to configure Python's initialization, deprecated in Python 3.11:


@itemize *

@item 
@code{PySys_SetArgvEx()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{PySys_SetArgv()}:
Set @ref{3f1,,PyConfig.argv} instead.

@item 
@code{Py_SetProgramName()}:
Set @ref{3f2,,PyConfig.program_name} instead.

@item 
@code{Py_SetPythonHome()}:
Set @ref{3f3,,PyConfig.home} instead.

@item 
@ref{3f4,,PySys_ResetWarnOptions()}:
Clear @ref{3f5,,sys.warnoptions} and @code{warnings.filters} instead.
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} instead.

@item 
Global configuration variables:


@itemize *

@item 
@ref{3f8,,Py_DebugFlag}:
Use @ref{3f9,,PyConfig.parser_debug} or
@ref{37c,,PyConfig_Get("parser_debug")} instead.

@item 
@ref{3fa,,Py_VerboseFlag}:
Use @ref{3fb,,PyConfig.verbose} or
@ref{37c,,PyConfig_Get("verbose")} instead.

@item 
@ref{3fc,,Py_QuietFlag}:
Use @ref{3fd,,PyConfig.quiet} or
@ref{37c,,PyConfig_Get("quiet")} instead.

@item 
@ref{3fe,,Py_InteractiveFlag}:
Use @ref{3ff,,PyConfig.interactive} or
@ref{37c,,PyConfig_Get("interactive")} instead.

@item 
@ref{400,,Py_InspectFlag}:
Use @ref{401,,PyConfig.inspect} or
@ref{37c,,PyConfig_Get("inspect")} instead.

@item 
@ref{402,,Py_OptimizeFlag}:
Use @ref{403,,PyConfig.optimization_level} or
@ref{37c,,PyConfig_Get("optimization_level")} instead.

@item 
@ref{404,,Py_NoSiteFlag}:
Use @ref{405,,PyConfig.site_import} or
@ref{37c,,PyConfig_Get("site_import")} instead.

@item 
@ref{406,,Py_BytesWarningFlag}:
Use @ref{407,,PyConfig.bytes_warning} or
@ref{37c,,PyConfig_Get("bytes_warning")} instead.

@item 
@ref{408,,Py_FrozenFlag}:
Use @ref{409,,PyConfig.pathconfig_warnings} or
@ref{37c,,PyConfig_Get("pathconfig_warnings")} instead.

@item 
@ref{40a,,Py_IgnoreEnvironmentFlag}:
Use @ref{40b,,PyConfig.use_environment} or
@ref{37c,,PyConfig_Get("use_environment")} instead.

@item 
@ref{40c,,Py_DontWriteBytecodeFlag}:
Use @ref{40d,,PyConfig.write_bytecode} or
@ref{37c,,PyConfig_Get("write_bytecode")} instead.

@item 
@ref{40e,,Py_NoUserSiteDirectory}:
Use @ref{40f,,PyConfig.user_site_directory} or
@ref{37c,,PyConfig_Get("user_site_directory")} instead.

@item 
@ref{410,,Py_UnbufferedStdioFlag}:
Use @ref{411,,PyConfig.buffered_stdio} or
@ref{37c,,PyConfig_Get("buffered_stdio")} instead.

@item 
@ref{412,,Py_HashRandomizationFlag}:
Use @ref{413,,PyConfig.use_hash_seed}
and @ref{414,,PyConfig.hash_seed} or
@ref{37c,,PyConfig_Get("hash_seed")} instead.

@item 
@ref{415,,Py_IsolatedFlag}:
Use @ref{416,,PyConfig.isolated} or
@ref{37c,,PyConfig_Get("isolated")} instead.

@item 
@ref{417,,Py_LegacyWindowsFSEncodingFlag}:
Use @ref{418,,PyPreConfig.legacy_windows_fs_encoding} or
@ref{37c,,PyConfig_Get("legacy_windows_fs_encoding")} instead.

@item 
@ref{419,,Py_LegacyWindowsStdioFlag}:
Use @ref{41a,,PyConfig.legacy_windows_stdio} or
@ref{37c,,PyConfig_Get("legacy_windows_stdio")} instead.

@item 
@code{Py_FileSystemDefaultEncoding}, @code{Py_HasFileSystemDefaultEncoding}:
Use @ref{41b,,PyConfig.filesystem_encoding} or
@ref{37c,,PyConfig_Get("filesystem_encoding")} instead.

@item 
@code{Py_FileSystemDefaultEncodeErrors}:
Use @ref{41c,,PyConfig.filesystem_errors} or
@ref{37c,,PyConfig_Get("filesystem_errors")} instead.

@item 
@code{Py_UTF8Mode}:
Use @ref{41d,,PyPreConfig.utf8_mode} or
@ref{37c,,PyConfig_Get("utf8_mode")} instead.
(see @ref{41e,,Py_PreInitialize()})
@end itemize

The @ref{3f6,,Py_InitializeFromConfig()} API should be used with
@ref{3f7,,PyConfig} to set these options. Or @ref{37c,,PyConfig_Get()} can be
used to get these options at runtime.
@end itemize

@node Pending removal in Python 3 18<6>,Pending removal in future versions<8>,Pending removal in Python 3 15<8>,C API deprecations
@anchor{deprecations/index id2}@anchor{597f}
@subsection Pending removal in Python 3.18



@itemize *

@item 
The following private functions are deprecated
and planned for removal in Python 3.18:


@itemize *

@item 
@code{_PyBytes_Join()}: use @ref{383,,PyBytes_Join()}.

@item 
@code{_PyDict_GetItemStringWithError()}: use @ref{421,,PyDict_GetItemStringRef()}.

@item 
@code{_PyDict_Pop()}: use @ref{422,,PyDict_Pop()}.

@item 
@code{_PyLong_Sign()}: use @ref{39a,,PyLong_GetSign()}.

@item 
@code{_PyLong_FromDigits()} and @code{_PyLong_New()}:
use @ref{3aa,,PyLongWriter_Create()}.

@item 
@code{_PyThreadState_UncheckedGet()}: use @ref{423,,PyThreadState_GetUnchecked()}.

@item 
@code{_PyUnicode_AsString()}: use @ref{424,,PyUnicode_AsUTF8()}.

@item 
@code{_PyUnicodeWriter_Init()}:
replace @code{_PyUnicodeWriter_Init(&writer)} with
@ref{3b4,,writer = PyUnicodeWriter_Create(0)}.

@item 
@code{_PyUnicodeWriter_Finish()}:
replace @code{_PyUnicodeWriter_Finish(&writer)} with
@ref{3b7,,PyUnicodeWriter_Finish(writer)}.

@item 
@code{_PyUnicodeWriter_Dealloc()}:
replace @code{_PyUnicodeWriter_Dealloc(&writer)} with
@ref{3b6,,PyUnicodeWriter_Discard(writer)}.

@item 
@code{_PyUnicodeWriter_WriteChar()}:
replace @code{_PyUnicodeWriter_WriteChar(&writer, ch)} with
@ref{3ba,,PyUnicodeWriter_WriteChar(writer@comma{} ch)}.

@item 
@code{_PyUnicodeWriter_WriteStr()}:
replace @code{_PyUnicodeWriter_WriteStr(&writer, str)} with
@ref{3bc,,PyUnicodeWriter_WriteStr(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteSubstring()}:
replace @code{_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)} with
@ref{3bd,,PyUnicodeWriter_WriteSubstring(writer@comma{} str@comma{} start@comma{} end)}.

@item 
@code{_PyUnicodeWriter_WriteASCIIString()}:
replace @code{_PyUnicodeWriter_WriteASCIIString(&writer, str)} with
@ref{3b9,,PyUnicodeWriter_WriteASCII(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_WriteLatin1String()}:
replace @code{_PyUnicodeWriter_WriteLatin1String(&writer, str)} with
@ref{3bf,,PyUnicodeWriter_WriteUTF8(writer@comma{} str)}.

@item 
@code{_PyUnicodeWriter_Prepare()}: (no replacement).

@item 
@code{_PyUnicodeWriter_PrepareKind()}: (no replacement).

@item 
@code{_Py_HashPointer()}: use @ref{425,,Py_HashPointer()}.

@item 
@code{_Py_fopen_obj()}: use @ref{393,,Py_fopen()}.
@end itemize

The pythoncapi-compat project@footnote{https://github.com/python/pythoncapi-compat/} can be used to get
these new public functions on Python 3.13 and older.
(Contributed by Victor Stinner in gh-128863@footnote{https://github.com/python/cpython/issues/128863}.)
@end itemize

@node Pending removal in future versions<8>,,Pending removal in Python 3 18<6>,C API deprecations
@anchor{deprecations/index id3}@anchor{5980}
@subsection Pending removal in future versions


The following APIs are deprecated and will be removed,
although there is currently no date scheduled for their removal.


@itemize *

@item 
@ref{427,,Py_TPFLAGS_HAVE_FINALIZE}:
Unneeded since Python 3.8.

@item 
@ref{428,,PyErr_Fetch()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42a,,PyErr_NormalizeException()}:
Use @ref{429,,PyErr_GetRaisedException()} instead.

@item 
@ref{42b,,PyErr_Restore()}:
Use @ref{42c,,PyErr_SetRaisedException()} instead.

@item 
@ref{42d,,PyModule_GetFilename()}:
Use @ref{42e,,PyModule_GetFilenameObject()} instead.

@item 
@ref{42f,,PyOS_AfterFork()}:
Use @ref{430,,PyOS_AfterFork_Child()} instead.

@item 
@ref{431,,PySlice_GetIndicesEx()}:
Use @ref{432,,PySlice_Unpack()} and @ref{433,,PySlice_AdjustIndices()} instead.

@item 
@ref{434,,PyUnicode_READY()}:
Unneeded since Python 3.12

@item 
@code{PyErr_Display()}:
Use @ref{435,,PyErr_DisplayException()} instead.

@item 
@code{_PyErr_ChainExceptions()}:
Use @code{_PyErr_ChainExceptions1()} instead.

@item 
@code{PyBytesObject.ob_shash} member:
call @ref{436,,PyObject_Hash()} instead.

@item 
Thread Local Storage (TLS) API:


@itemize *

@item 
@ref{437,,PyThread_create_key()}:
Use @ref{438,,PyThread_tss_alloc()} instead.

@item 
@ref{439,,PyThread_delete_key()}:
Use @ref{43a,,PyThread_tss_free()} instead.

@item 
@ref{43b,,PyThread_set_key_value()}:
Use @ref{43c,,PyThread_tss_set()} instead.

@item 
@ref{43d,,PyThread_get_key_value()}:
Use @ref{43e,,PyThread_tss_get()} instead.

@item 
@ref{43f,,PyThread_delete_key_value()}:
Use @ref{440,,PyThread_tss_delete()} instead.

@item 
@ref{441,,PyThread_ReInitTLS()}:
Unneeded since Python 3.7.
@end itemize
@end itemize

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 用語集<2>,このドキュメントについて,非推奨<14>,Top
@anchor{glossary doc}@anchor{5981}@anchor{glossary glossary}@anchor{1fbf}@anchor{glossary id1}@anchor{5982}@anchor{glossary translation-repo}@anchor{5983}
@chapter 用語集


@c if you add new entries, keep the alphabetical sorting!


@table @asis
@anchor{glossary term-0}@anchor{492}
@geindex >>>

@item @code{>>>}

@ref{1b5,,対話型} シェルにおけるデフォルトの Python プロンプトです。インタープリターで対話的に実行されるコード例でよく見られます。
@anchor{glossary term-}@anchor{493}
@geindex ...

@item @code{...}

次のものが考えられます:


@itemize *

@item 
対話型 (@ref{1b5,,interactive}) シェルにおいて、インデントされたコードブロック、対応する左右の区切り文字の組 (丸括弧、角括弧、波括弧、三重引用符) の内側、デコレーターの後に、コードを入力する際に表示されるデフォルトの Python プロンプトです。
@end itemize

@geindex ...;ellipsisリテラル


@itemize *

@item 
The three dots form of the @ref{1ffc,,Ellipsis} object.
@end itemize
@anchor{glossary term-abstract-base-class}@anchor{13ce}
@geindex abstract base class

@item abstract base class

(抽象基底クラス) 抽象基底クラスは @ref{5984,,duck-typing} を補完するもので、 @ref{6f9,,hasattr()} などの別のテクニックでは不恰好であったり微妙に誤る (例えば @ref{23b1,,magic methods} の場合) 場合にインターフェースを定義する方法を提供します。ABC は仮想 (virtual) サブクラスを導入します。これは親クラスから継承しませんが、それでも @ref{2ad,,isinstance()} や @ref{9c4,,issubclass()} に認識されます; @ref{4,,abc} モジュールのドキュメントを参照してください。Python には、多くの組み込み ABC が同梱されています。その対象は、(@ref{1f,,collections.abc} モジュールで) データ構造、(@ref{a2,,numbers} モジュールで) 数、(@ref{83,,io} モジュールで) ストリーム、(@ref{7c,,importlib.abc} モジュールで) インポートファインダ及びローダーです。 @ref{4,,abc} モジュールを利用して独自の ABC を作成できます。
@anchor{glossary term-annotate-function}@anchor{15d}
@geindex annotate function

@item annotate function

A function that can be called to retrieve the @ref{15c,,annotations}
of an object. This function is accessible as the @ref{1983,,__annotate__}
attribute of functions, classes, and modules. Annotate functions are a
subset of @ref{44ef,,evaluate functions}.
@anchor{glossary term-annotation}@anchor{15c}
@geindex annotation

@item annotation

(アノテーション) 変数、クラス属性、関数のパラメータや返り値に関係するラベルです。
慣例により @ref{23cb,,type hint} として使われています。

Annotations of local variables cannot be accessed at runtime, but
annotations of global variables, class attributes, and functions
can be retrieved by calling @ref{459,,annotationlib.get_annotations()}
on modules, classes, and functions, respectively.

機能の説明がある @ref{f51,,variable annotation}, @ref{2019,,function annotation}, 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/}, 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/}, 
@geindex Python Enhancement Proposals; PEP 649
PEP 649@footnote{https://peps.python.org/pep-0649/} を参照してください。また、アノテーションを利用するベストプラクティスとして @ref{9d9,,Annotations Best Practices} も参照してください。
@anchor{glossary term-argument}@anchor{67b}
@geindex 引数 (argument)

@item 引数 (argument)

(実引数) 関数を呼び出す際に、 @ref{24b7,,関数} (または @ref{1864,,メソッド}) に渡す値です。実引数には２種類あります:


@itemize *

@item 
`キーワード引数': 関数呼び出しの際に引数の前に識別子がついたもの (例: @code{name=}) や、 @code{**} に続けた辞書の中の値として渡された引数。例えば、次の @ref{197,,complex()} の呼び出しでは、 @code{3} と @code{5} がキーワード引数です:

@example
complex(real=3, imag=5)
complex(**@{'real': 3, 'imag': 5@})
@end example

@item 
`位置引数': キーワード引数以外の引数。位置引数は引数リストの先頭に書くことができ、また @code{*} に続けた @ref{12f1,,iterable} の要素として渡すことができます。例えば、次の例では @code{3} と @code{5} は両方共位置引数です:

@example
complex(3, 5)
complex(*(3, 5))
@end example
@end itemize

実引数は関数の実体において名前付きのローカル変数に割り当てられます。割り当てを行う規則については @ref{f7d,,呼び出し (call)} を参照してください。シンタックスにおいて実引数を表すためにあらゆる式を使うことが出来ます。評価された値はローカル変数に割り当てられます。

@ref{234b,,仮引数} 、FAQ の @ref{58be,,実引数と仮引数の違いは何ですか?} 、
@geindex Python Enhancement Proposals; PEP 362
PEP 362@footnote{https://peps.python.org/pep-0362/} を参照してください。
@anchor{glossary term-asynchronous-context-manager}@anchor{7f0}
@geindex asynchronous context manager

@item asynchronous context manager

(非同期コンテキストマネージャ)
@ref{241d,,__aenter__()} と @ref{19a1,,__aexit__()} メソッドを定義することで @ref{185,,async with} 文内の環境を管理するオブジェクトです。  
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} で導入されました。
@anchor{glossary term-asynchronous-generator}@anchor{249b}
@geindex asynchronous generator

@item asynchronous generator

(非同期ジェネレータ)
@ref{4918,,asynchronous generator iterator} を返す関数です。
@ref{7ed,,async def} で定義されたコルーチン関数に似ていますが、 @ref{bc2,,yield} 式を持つ点で異なります。
@ref{bc2,,yield} 式は @ref{ca1,,async for} ループで使用できる値の並びを生成するのに使用されます。

通常は非同期ジェネレータ関数を指しますが、文脈によっては `非同期ジェネレータイテレータ' を指す場合があります。
意図された意味が明らかでない場合、 明瞭化のために完全な単語を使用します。

非同期ジェネレータ関数には、 @ref{ca1,,async for} 文や @ref{185,,async with} 文だけでなく @ref{18d,,await} 式もあることがあります。
@anchor{glossary term-asynchronous-generator-iterator}@anchor{4918}
@geindex asynchronous generator iterator

@item asynchronous generator iterator

(非同期ジェネレータイテレータ)
@ref{249b,,asynchronous generator} 関数で生成されるオブジェクトです。

これは @ref{4c7,,asynchronous iterator} で、 @ref{1882,,__anext__()} メソッドを使って呼ばれると awaitable オブジェクトを返します。  この awaitable オブジェクトは、次の @ref{bc2,,yield} 式まで非同期ジェネレータ関数の本体を実行します。

各 @ref{bc2,,yield} では一時的に処理を中断し、その実行状態 (ローカル変数や保留中の try 文を含む) を記憶します。  `非同期ジェネレータイテレータ' が @ref{1882,,__anext__()} で返された他の awaitable で実際に再開する時には、その中断箇所が選ばれます。  
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} および 
@geindex Python Enhancement Proposals; PEP 525
PEP 525@footnote{https://peps.python.org/pep-0525/} を参照してください。
@anchor{glossary term-asynchronous-iterable}@anchor{f74}
@geindex asynchronous iterable

@item asynchronous iterable

(非同期イテラブル)
@ref{ca1,,async for} 文の中で使用できるオブジェクトです。  自身の @ref{df6,,__aiter__()} メソッドから @ref{4c7,,asynchronous iterator} を返さなければなりません。  
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} で導入されました。
@anchor{glossary term-asynchronous-iterator}@anchor{4c7}
@geindex asynchronous iterator

@item asynchronous iterator

(非同期イテレータ)
@ref{df6,,__aiter__()} と @ref{1882,,__anext__()} メソッドを実装したオブジェクトです。  @ref{1882,,__anext__()} は @ref{4c9,,awaitable} オブジェクトを返さなければなりません。  @ref{ca1,,async for} は @ref{1e0f,,StopAsyncIteration} 例外を送出するまで、非同期イテレータの @ref{1882,,__anext__()} メソッドが返す awaitable を解決します。  
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} で導入されました。
@anchor{glossary term-atomic-operation}@anchor{2615}
@geindex atomic operation

@item atomic operation

An operation that appears to execute as a single, indivisible step: no
other thread can observe it half-done, and its effects become visible all
at once.  Python does not guarantee that high-level statements are atomic
(for example, @code{x += 1} performs multiple bytecode operations and is not
atomic).  Atomicity is only guaranteed where explicitly documented.  See
also @ref{5985,,race condition} and @ref{5986,,data race}.
@anchor{glossary term-attached-thread-state}@anchor{4ed1}
@geindex attached thread state

@item attached thread state

A @ref{1846,,thread state} that is active for the current OS thread.

When a @ref{1846,,thread state} is attached, the OS thread has
access to the full Python C API and can safely invoke the
bytecode interpreter.

Unless a function explicitly notes otherwise, attempting to call
the C API without an attached thread state will result in a fatal
error or undefined behavior.  A thread state can be attached and detached
explicitly by the user through the C API, or implicitly by the runtime,
including during blocking C calls and by the bytecode interpreter in between
calls.

On most builds of Python, having an attached thread state implies that the
caller holds the @ref{164,,GIL} for the current interpreter, so only
one OS thread can have an attached thread state at a given moment. In
@ref{176d,,free-threaded builds} of Python, threads can
concurrently hold an attached thread state, allowing for true parallelism of
the bytecode interpreter.
@anchor{glossary term-attribute}@anchor{290c}
@geindex 属性

@item 属性

(属性) オブジェクトに関連付けられ、ドット表記式によって名前で通常参照される値です。例えば、オブジェクト `o' が属性 `a' を持っているとき、その属性は `o.a' で参照されます。

オブジェクトには、 @ref{22a0,,Names (identifiers and keywords)} で定義される識別子ではない名前の属性を与えることができます。たとえば @ref{25be,,setattr()} を使い、オブジェクトがそれを許可している場合に行えます。このような属性はドット表記式ではアクセスできず、代わりに @ref{dca,,getattr()} を使って取る必要があります。
@anchor{glossary term-awaitable}@anchor{4c9}
@geindex awaitable

@item awaitable

(待機可能)
@ref{18d,,await} 式で使用することが出来るオブジェクトです。  @ref{6b9,,coroutine} か、 @ref{f75,,__await__()} メソッドがあるオブジェクトです。 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} を参照してください。
@anchor{glossary term-BDFL}@anchor{5987}
@geindex BDFL

@item BDFL

慈悲深き終身独裁者 (Benevolent Dictator For Life) の略です。Python の作者、Guido van Rossum@footnote{https://gvanrossum.github.io/} のことです。
@anchor{glossary term-binary-file}@anchor{206e}
@geindex binary file

@item binary file

(バイナリファイル)
@ref{193,,bytes-like オブジェクト} の読み込みおよび書き込みができる @ref{13db,,ファイルオブジェクト} です。
バイナリファイルの例は、バイナリモード (@code{'rb'}, @code{'wb'} or @code{'rb+'}) で開かれたファイル、@ref{75f,,sys.stdin.buffer}、@ref{ccd,,sys.stdout.buffer}、 @ref{10a4,,io.BytesIO} や @ref{65c,,gzip.GzipFile}. のインスタンスです。

@ref{169,,str} オブジェクトの読み書きができるファイルオブジェクトについては、 @ref{206d,,text file} も参照してください。
@anchor{glossary term-borrowed-reference}@anchor{3d7}
@geindex borrowed reference

@item borrowed reference

In Python's C API, a borrowed reference is a reference to an object,
where the code using the object does not own the reference.
It becomes a dangling
pointer if the object is destroyed. For example, a garbage collection can
remove the last @ref{5e2,,strong reference} to the object and so destroy it.

Calling @ref{78f,,Py_INCREF()} on the @ref{3d7,,borrowed reference} is
recommended to convert it to a @ref{5e2,,strong reference} in-place, except
when the object cannot be destroyed before the last usage of the borrowed
reference. The @ref{a9a,,Py_NewRef()} function can be used to create a new
@ref{5e2,,strong reference}.
@anchor{glossary term-bytes-like-object}@anchor{193}
@geindex bytes-like object

@item bytes-like object

@ref{260,,バッファプロトコル (buffer Protocol)} をサポートしていて、 C 言語の意味で @ref{124e,,連続した} バッファーを提供可能なオブジェクト。
@ref{192,,bytes}, @ref{344,,bytearray}, @ref{4be,,array.array} や、多くの一般的な @ref{165,,memoryview} オブジェクトがこれに当たります。
bytes-like オブジェクトは、データ圧縮、バイナリファイルへの保存、ソケットを経由した送信など、バイナリデータを要求するいろいろな操作に利用することができます。

幾つかの操作ではバイナリデータを変更する必要があります。
その操作のドキュメントではよく "読み書き可能な bytes-like オブジェクト" に言及しています。
変更可能なバッファーオブジェクトには、 @ref{344,,bytearray} と @ref{344,,bytearray} の @ref{165,,memoryview} などが含まれます。
また、他の幾つかの操作では不変なオブジェクト内のバイナリデータ ("読み出し専用の bytes-like オブジェクト") を必要します。それには @ref{192,,bytes} と @ref{192,,bytes} の @ref{165,,memoryview} オブジェクトが含まれます。
@anchor{glossary term-bytecode}@anchor{4aa}
@geindex bytecode

@item bytecode

(バイトコード) Python のソースコードは、 Python プログラムの CPython インタプリタの内部表現であるバイトコードへとコンパイルされます。
バイトコードは @code{.pyc} ファイルにキャッシュされ、同じファイルが二度目に実行されるときはより高速になります (ソースコードからバイトコードへの再度のコンパイルは回避されます)。
この "中間言語 (intermediate language)" は、各々のバイトコードに対応する機械語を実行する @ref{3a5b,,仮想マシン} で動作するといえます。
重要な注意として、バイトコードは異なる Python 仮想マシン間で動作することや、Python リリース間で安定であることは期待されていません。

バイトコードの命令一覧は @ref{7cf,,dis モジュール} にあります。
@anchor{glossary term-callable}@anchor{2d7b}
@geindex callable

@item callable

A callable is an object that can be called, possibly with a set
of arguments (see @ref{67b,,argument}), with the following syntax:

@example
callable(argument1, argument2, argumentN)
@end example

A @ref{24b7,,function}, and by extension a @ref{1864,,method}, is a callable.
An instance of a class that implements the @ref{77a,,__call__()}
method is also a callable.
@anchor{glossary term-callback}@anchor{2d9c}
@geindex callback

@item callback

(コールバック) 将来のある時点で実行されるために引数として渡される関数
@anchor{glossary term-class}@anchor{1cfd}
@geindex クラス

@item クラス

(クラス) ユーザー定義オブジェクトを作成するためのテンプレートです。クラス定義は普通、そのクラスのインスタンス上の操作をするメソッドの定義を含みます。
@anchor{glossary term-class-variable}@anchor{5988}
@geindex class variable

@item class variable

(クラス変数) クラス上に定義され、クラスレベルで (つまり、クラスのインスタンス上ではなしに) 変更されることを目的としている変数です。
@anchor{glossary term-closure-variable}@anchor{1893}
@geindex closure variable

@item closure variable

A @ref{2428,,free variable} referenced from a @ref{238d,,nested scope} that is defined in an outer
scope rather than being resolved at runtime from the globals or builtin namespaces.
May be explicitly defined with the @ref{14bf,,nonlocal} keyword to allow write access,
or implicitly defined if the variable is only being read.

For example, in the @code{inner} function in the following code, both @code{x} and @code{print} are
@ref{2428,,free variables}, but only @code{x} is a `closure variable':

@example
def outer():
    x = 0
    def inner():
        nonlocal x
        x += 1
        print(x)
    return inner
@end example

Due to the @ref{2347,,codeobject.co_freevars} attribute (which, despite its name, only
includes the names of closure variables rather than listing all referenced free
variables), the more general @ref{2428,,free variable} term is sometimes used even
when the intended meaning is to refer specifically to closure variables.
@anchor{glossary term-complex-number}@anchor{5989}
@geindex complex number

@item complex number

(複素数) よく知られている実数系を拡張したもので、すべての数は実部と虚部の和として表されます。虚数は虚数単位 (@code{-1} の平方根) に実数を掛けたもので、一般に数学では @code{i} と書かれ、工学では @code{j} と書かれます。Python は複素数に組み込みで対応し、後者の表記を取っています。虚部は末尾に @code{j} をつけて書きます。例えば @code{3+1j} です。 @ref{92,,math} モジュールの複素数版を利用するには、 @ref{19,,cmath} を使います。複素数の使用はかなり高度な数学の機能です。必要性を感じなければ、ほぼ間違いなく無視してしまってよいでしょう。
@anchor{glossary term-concurrency}@anchor{598a}
@geindex concurrency

@item concurrency

The ability of a computer program to perform multiple tasks at the same
time.  Python provides libraries for writing programs that make use of
different forms of concurrency.  @ref{b,,asyncio} is a library for dealing
with asynchronous tasks and coroutines.  @ref{f3,,threading} provides
access to operating system threads and @ref{98,,multiprocessing} to
operating system processes. Multi-core processors can execute threads and
processes on different CPU cores at the same time (see
@ref{598b,,parallelism}).
@anchor{glossary term-concurrent-modification}@anchor{598c}
@geindex concurrent modification

@item concurrent modification

When multiple threads modify shared data at the same time.  Concurrent
modification without proper synchronization can cause
@ref{5985,,race conditions}, and might also trigger a
@ref{5986,,data race}, data corruption, or both.
@anchor{glossary term-context}@anchor{1963}
@geindex context

@item context

This term has different meanings depending on where and how it is used.
Some common meanings:


@itemize *

@item 
The temporary state or environment established by a @ref{1e1,,context manager} via a @ref{186,,with} statement.

@item 
The collection of key­value bindings associated with a particular
@ref{177,,contextvars.Context} object and accessed via
@ref{1875,,ContextVar} objects.  Also see @ref{598d,,context variable}.

@item 
A @ref{177,,contextvars.Context} object.  Also see @ref{1964,,current context}.
@end itemize
@anchor{glossary term-context-management-protocol}@anchor{1965}
@geindex コンテキスト管理プロトコル

@item コンテキスト管理プロトコル

The @ref{7e4,,__enter__()} and @ref{1518,,__exit__()} methods called
by the @ref{186,,with} statement.  See 
@geindex Python Enhancement Proposals; PEP 343
PEP 343@footnote{https://peps.python.org/pep-0343/}.
@anchor{glossary term-context-manager}@anchor{1e1}
@geindex context manager

@item context manager

An object which implements the @ref{1965,,context management protocol} and
controls the environment seen in a @ref{186,,with} statement.  See
@geindex Python Enhancement Proposals; PEP 343
PEP 343@footnote{https://peps.python.org/pep-0343/}.
@anchor{glossary term-context-variable}@anchor{598d}
@geindex context variable

@item context variable

A variable whose value depends on which context is the @ref{1964,,current context}.  Values are accessed via @ref{1875,,contextvars.ContextVar}
objects.  Context variables are primarily used to isolate state between
concurrent asynchronous tasks.
@anchor{glossary term-contiguous}@anchor{124e}
@geindex contiguous

@item contiguous

@geindex C-contiguous
@geindex Fortran contiguous

(隣接、連続) バッファが厳密に `C-連続' または `Fortran 連続' である場合に、そのバッファは連続しているとみなせます。
ゼロ次元バッファは C 連続であり Fortran 連続です。
一次元の配列では、その要素は必ずメモリ上で隣接するように配置され、添字がゼロから始まり増えていく順序で並びます。
多次元の C-連続な配列では、メモリアドレス順に要素を巡る際には最後の添え字が最初に変わるのに対し、 Fortran 連続な配列では最初の添え字が最初に動きます。
@anchor{glossary term-coroutine}@anchor{6b9}
@geindex コルーチン

@item コルーチン

(コルーチン) コルーチンはサブルーチンのより一般的な形式です。
サブルーチンには決められた地点から入り、別の決められた地点から出ます。
コルーチンには多くの様々な地点から入る、出る、再開することができます。
コルーチンは @ref{7ed,,async def} 文で実装できます。
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} を参照してください。
@anchor{glossary term-coroutine-function}@anchor{f73}
@geindex coroutine function

@item coroutine function

(コルーチン関数)
@ref{6b9,,coroutine} オブジェクトを返す関数です。
コルーチン関数は @ref{7ed,,async def} 文で実装され、@ref{18d,,await}、@ref{ca1,,async for}、 および @ref{185,,async with} キーワードを持つことが出来ます。
これらは 
@geindex Python Enhancement Proposals; PEP 492
PEP 492@footnote{https://peps.python.org/pep-0492/} で導入されました。
@anchor{glossary term-CPython}@anchor{905}
@geindex CPython

@item CPython

python.org@footnote{https://www.python.org} で配布されている、Python プログラミング言語の標準的な実装です。"CPython" という単語は、この実装を Jython や IronPython といった他の実装と区別する必要が有る場合に利用されます。
@anchor{glossary term-current-context}@anchor{1964}
@geindex current context

@item current context

The @ref{1963,,context} (@ref{177,,contextvars.Context} object) that is
currently used by @ref{1875,,ContextVar} objects to access (get
or set) the values of @ref{598d,,context variables}.  Each
thread has its own current context.  Frameworks for executing asynchronous
tasks (see @ref{b,,asyncio}) associate each task with a context which
becomes the current context whenever the task starts or resumes execution.
@anchor{glossary term-cyclic-isolate}@anchor{55e4}
@geindex cyclic isolate

@item cyclic isolate

A subgroup of one or more objects that reference each other in a reference
cycle, but are not referenced by objects outside the group.  The goal of
the @ref{17d8,,cyclic garbage collector} is to identify these groups and break the reference
cycles so that the memory can be reclaimed.
@anchor{glossary term-data-race}@anchor{5986}
@geindex data race

@item data race

A situation where multiple threads access the same memory location
concurrently, at least one of the accesses is a write, and the threads
do not use any synchronization to control their access.  Data races
lead to @ref{598e,,non-deterministic} behavior and can cause data corruption.
Proper use of @ref{598f,,locks} and other @ref{5990,,synchronization primitives} prevents data races.  Note that data races
can only happen in native code, but that @ref{5991,,native code} might be
exposed in a Python API.  See also @ref{5985,,race condition} and
@ref{5992,,thread-safe}.
@anchor{glossary term-deadlock}@anchor{5993}
@geindex deadlock

@item deadlock

A situation in which two or more tasks (threads, processes, or coroutines)
wait indefinitely for each other to release resources or complete actions,
preventing any from making progress.  For example, if thread A holds lock
1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1,
both threads will wait indefinitely.  In Python this often arises from
acquiring multiple locks in conflicting orders or from circular
join/await dependencies.  Deadlocks can be avoided by always acquiring
multiple @ref{598f,,locks} in a consistent order.  See also
@ref{598f,,lock} and @ref{5994,,reentrant}.
@anchor{glossary term-decorator}@anchor{93a}
@geindex decorator

@item decorator

(デコレータ) 別の関数を返す関数で、通常、 @code{@@wrapper} 構文で関数変換として適用されます。デコレータの一般的な利用例は、 @ref{48e,,classmethod()} と @ref{453,,staticmethod()} です。

デコレータの文法はシンタックスシュガーです。次の2つの関数定義は意味的に同じものです:

@example
def f(arg):
    ...
f = staticmethod(f)

@@staticmethod
def f(arg):
    ...
@end example

同じ概念がクラスにも存在しますが、あまり使われません。デコレータについて詳しくは、 @ref{2018,,関数定義} および @ref{14ef,,クラス定義} のドキュメントを参照してください。
@anchor{glossary term-descriptor}@anchor{1881}
@geindex descriptor

@item descriptor

Any object which defines the methods @ref{1701,,__get__()},
@ref{23b5,,__set__()}, or @ref{194f,,__delete__()}.
When a class attribute is a descriptor, its special
binding behavior is triggered upon attribute lookup.  Normally, using
`a.b' to get, set or delete an attribute looks up the object named `b' in
the class dictionary for `a', but if `b' is a descriptor, the respective
descriptor method gets called.  Understanding descriptors is a key to a
deep understanding of Python because they are the basis for many features
including functions, methods, properties, class methods, static methods,
and reference to super classes.

デスクリプタのメソッドに関しての詳細は、 @ref{e49,,デスクリプタ (descriptor) の実装} や @ref{1706,,Descriptor How To Guide} を参照してください。
@anchor{glossary term-dictionary}@anchor{23d5}
@geindex dictionary

@item dictionary

An associative array, where arbitrary keys are mapped to values.  The
keys can be any object with @ref{cf3,,__hash__()} and
@ref{cf2,,__eq__()} methods.
Called a hash in Perl.
@anchor{glossary term-dictionary-comprehension}@anchor{5995}
@geindex dictionary comprehension

@item dictionary comprehension

(辞書内包表記) iterable 内の全てあるいは一部の要素を処理して、その結果からなる辞書を返すコンパクトな書き方です。 @code{results = @{n: n ** 2 for n in range(10)@}} とすると、キー @code{n} を値 @code{n ** 2} に対応付ける辞書を生成します。 @ref{7ec,,リスト、集合、辞書の表示} を参照してください。
@anchor{glossary term-dictionary-view}@anchor{298e}
@geindex dictionary view

@item dictionary view

(辞書ビュー)
@ref{9d0,,dict.keys()}、@ref{9d1,,dict.values()}、@ref{9d2,,dict.items()} が返すオブジェクトです。
辞書の項目の動的なビューを提供します。
すなわち、辞書が変更されるとビューはそれを反映します。
辞書ビューを強制的に完全なリストにするには @code{list(dictview)} を使用してください。
@ref{2618,,辞書ビューオブジェクト} を参照してください。
@anchor{glossary term-docstring}@anchor{22ec}
@geindex docstring

@item docstring

A string literal which appears as the first expression in a class,
function or module.  While ignored when the suite is executed, it is
recognized by the compiler and put into the @ref{b21,,__doc__} attribute
of the enclosing class, function or module.  Since it is available via
introspection, it is the canonical place for documentation of the
object.
@anchor{glossary term-duck-typing}@anchor{5984}
@geindex duck-typing

@item duck-typing

あるオブジェクトが正しいインターフェースを持っているかを決定するのにオブジェクトの型を見ないプログラミングスタイルです。代わりに、単純にオブジェクトのメソッドや属性が呼ばれたり使われたりします。（「アヒルのように見えて、アヒルのように鳴けば、それはアヒルである。」）インターフェースを型より重視することで、上手くデザインされたコードは、ポリモーフィックな代替を許して柔軟性を向上させます。ダックタイピングは @ref{f44,,type()} や @ref{2ad,,isinstance()} による判定を避けます。 (ただし、ダックタイピングを @ref{13ce,,抽象基底クラス} で補完することもできます。) その代わり、典型的に @ref{6f9,,hasattr()} 判定や @ref{3079,,EAFP} プログラミングを利用します。
@anchor{glossary term-dunder}@anchor{5996}
@geindex dunder

@item dunder

An informal short-hand for "double underscore", used when talking about a
@ref{1c60,,special method}. For example, @code{__init__} is often pronounced
"dunder init".
@anchor{glossary term-EAFP}@anchor{3079}
@geindex EAFP

@item EAFP

「認可をとるより許しを請う方が容易  (easier to ask for forgiveness than permission、マーフィーの法則)」の略です。この Python で広く使われているコーディングスタイルでは、通常は有効なキーや属性が存在するものと仮定し、その仮定が誤っていた場合に例外を捕捉します。この簡潔で手早く書けるコーディングスタイルには、 @ref{8f8,,try} 文および @ref{1ab,,except} 文がたくさんあるのが特徴です。このテクニックは、C のような言語でよく使われている @ref{5997,,LBYL} スタイルと対照的なものです。
@anchor{glossary term-evaluate-function}@anchor{44ef}
@geindex evaluate function

@item evaluate function

A function that can be called to evaluate a lazily evaluated attribute
of an object, such as the value of type aliases created with the @ref{66d,,type}
statement.
@anchor{glossary term-expression}@anchor{23cf}
@geindex expression

@item expression

(式) 何かの値と評価される、一まとまりの構文 (a piece of syntax) です。言い換えると、式とはリテラル、名前、属性アクセス、演算子や関数呼び出しなど、値を返す式の要素の積み重ねです。他の多くの言語と違い、Python では言語の全ての構成要素が式というわけではありません。 @ref{1973,,while} のように、式としては使えない @ref{2bfc,,文} もあります。代入も式ではなく文です。
@anchor{glossary term-extension-module}@anchor{2251}
@geindex extension module

@item extension module

(拡張モジュール) C や C++ で書かれたモジュールで、Python の C API を利用して Python コアやユーザーコードとやりとりします。
@anchor{glossary term-f-string}@anchor{66b}
@geindex f-string

@item f-string@anchor{glossary term-f-strings}@anchor{5998}
@geindex f-strings

@itemx f-strings

String literals prefixed with @code{f} or @code{F} are commonly called
"f-strings" which is short for
@ref{19a,,formatted string literals}.  See also 
@geindex Python Enhancement Proposals; PEP 498
PEP 498@footnote{https://peps.python.org/pep-0498/}.
@anchor{glossary term-file-object}@anchor{13db}
@geindex file object

@item file object

An object exposing a file-oriented API (with methods such as
@code{read()} or @code{write()}) to an underlying resource.  Depending
on the way it was created, a file object can mediate access to a real
on-disk file or to another type of storage or communication device
(for example standard input/output, in-memory buffers, sockets, pipes,
etc.).  File objects are also called `file-like objects' or
`streams'.

ファイルオブジェクトには実際には 3 種類あります: 生の @ref{206e,,バイナリーファイル}、バッファされた @ref{206e,,バイナリーファイル}、そして @ref{206d,,テキストファイル} です。インターフェイスは @ref{83,,io} モジュールで定義されています。ファイルオブジェクトを作る標準的な方法は @ref{316,,open()} 関数を使うことです。
@anchor{glossary term-file-like-object}@anchor{17ac}
@geindex file-like object

@item file-like object

@ref{13db,,file object} と同義です。
@anchor{glossary term-filesystem-encoding-and-error-handler}@anchor{75d}
@geindex filesystem encoding and error handler

@item filesystem encoding and error handler

Encoding and error handler used by Python to decode bytes from the
operating system and encode Unicode to the operating system.

ファイルシステムのエンコーディングでは、すべてが 128 バイト以下に正常にデコードされることが保証されなくてはなりません。ファイルシステムのエンコーディングでこれが保証されなかった場合は、API 関数が @ref{462,,UnicodeError} を送出することがあります。

The @ref{e53,,sys.getfilesystemencoding()} and
@ref{ee2,,sys.getfilesystemencodeerrors()} functions can be used to get the
filesystem encoding and error handler.

term:@cite{ファイルシステムのエンコーディングとエラーハンドラ <filesystem encoding and error handler>} は、Pythonの開始時に:c:func:@cite{PyConfig_Read} 関数により設定されます。 @ref{3f7,,PyConfig} のメンバー @ref{41b,,filesystem_encoding} と @ref{41c,,filesystem_errors} を参照してください。

See also the @ref{54a,,locale encoding}.
@anchor{glossary term-finder}@anchor{236a}
@geindex finder

@item finder

(ファインダ)
インポートされているモジュールの @ref{1a28,,loader} の発見を試行するオブジェクトです。

There are two types of finder: @ref{127c,,meta path finders} for use with @ref{f27,,sys.meta_path}, and @ref{127d,,path entry finders} for use with @ref{1225,,sys.path_hooks}.

See @ref{2446,,ファインダーとローダー} and @ref{7b,,importlib} for much more detail.
@anchor{glossary term-floor-division}@anchor{b3e}
@geindex floor division

@item floor division

(切り捨て除算) 一番近い整数に切り捨てる数学的除算。
切り捨て除算演算子は @code{//} です。
例えば、 @code{11 // 4} は @code{2} になり、それとは対称に浮動小数点数の真の除算では @code{2.75} が 返ってきます。
@code{(-11) // 4} は @code{-2.75} を `小さい方に' 丸める (訳注: 負の無限大への丸めを行う) ので @code{-3} になることに注意してください。
@geindex Python Enhancement Proposals; PEP 238
PEP 238@footnote{https://peps.python.org/pep-0238/} を参照してください。
@anchor{glossary term-free-threading}@anchor{1f4}
@geindex free threading

@item free threading

A threading model where multiple threads can run Python bytecode
simultaneously within the same interpreter.  This is in contrast to
the @ref{474,,global interpreter lock} which allows only one thread to
execute Python bytecode at a time.  See 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}.
@anchor{glossary term-free-threaded-build}@anchor{176d}
@geindex free-threaded build

@item free-threaded build

A build of @ref{905,,CPython} that supports @ref{1f4,,free threading},
configured using the @ref{499,,--disable-gil} option before compilation.

See @ref{2619,,Python support for free threading}.
@anchor{glossary term-free-variable}@anchor{2428}
@geindex free variable

@item free variable

Formally, as defined in the @ref{2425,,language execution model}, a free
variable is any variable used in a namespace which is not a local variable in that
namespace. See @ref{1893,,closure variable} for an example.
Pragmatically, due to the name of the @ref{2347,,codeobject.co_freevars} attribute,
the term is also sometimes used as a synonym for @ref{1893,,closure variable}.
@anchor{glossary term-function}@anchor{24b7}
@geindex 関数

@item 関数

(関数) 呼び出し側に値を返す一連の文のことです。関数には0以上の @ref{67b,,実引数} を渡すことが出来ます。実体の実行時に引数を使用することが出来ます。 @ref{234b,,仮引数}、@ref{1864,,メソッド}、@ref{2018,,関数定義} を参照してください。
@anchor{glossary term-function-annotation}@anchor{2019}
@geindex function annotation

@item function annotation

(関数アノテーション) 関数のパラメータや返り値の @ref{15c,,annotation} です。

関数アノテーションは、通常は @ref{23cb,,型ヒント} のために使われます: 例えば、この関数は 2 つの @ref{19b,,int} 型の引数を取ると期待され、また @ref{19b,,int} 型の返り値を持つと期待されています。

@example
def sum_two_numbers(a: int, b: int) -> int:
   return a + b
@end example

関数アノテーションの文法は @ref{2018,,関数定義} の節で解説されています。

機能の説明がある @ref{f51,,variable annotation}, 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/},を参照してください。また、アノテーションを利用するベストプラクティスとして @ref{9d9,,Annotations Best Practices} も参照してください。
@anchor{glossary term-__future__}@anchor{fad}
@geindex __future__

@item __future__

@code{from __future__ import <feature>} という @ref{45d,,future 文} は、コンパイラーに将来の Python リリースで標準となる構文や意味を使用して現在のモジュールをコンパイルするよう指示します。 @ref{0,,__future__} モジュールでは、 `feature' のとりうる値をドキュメント化しています。このモジュールをインポートし、その変数を評価することで、新機能が最初に言語に追加されたのはいつかや、いつデフォルトになるか (またはなったか) を見ることができます:

@example
>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
@end example
@anchor{glossary term-garbage-collection}@anchor{17d8}
@geindex garbage collection

@item garbage collection

(ガベージコレクション) これ以降使われることのないメモリを解放する処理です。
Pythonは、参照カウントと、循環参照を検出し破壊する循環ガベージコレクタを使ってガベージコレクションを行います。
ガベージコレクタは @ref{64,,gc} モジュールを使って操作できます。

@geindex ジェネレータ
@anchor{glossary term-generator}@anchor{126c}
@geindex ジェネレータ

@item ジェネレータ

(ジェネレータ)
@ref{dd9,,generator iterator} を返す関数です。
通常の関数に似ていますが、 @ref{bc2,,yield} 式を持つ点で異なります。
@ref{bc2,,yield} 式は、 for ループで使用できたり、@ref{9d8,,next()} 関数で値を 1 つずつ取り出したりできる、値の並びを生成するのに使用されます。

通常はジェネレータ関数を指しますが、文脈によっては `ジェネレータイテレータ' を指す場合があります。
意図された意味が明らかでない場合、 明瞭化のために完全な単語を使用します。
@anchor{glossary term-generator-iterator}@anchor{dd9}
@geindex generator iterator

@item generator iterator

(ジェネレータイテレータ)
@ref{126c,,generator} 関数で生成されるオブジェクトです。

Each @ref{bc2,,yield} temporarily suspends processing, remembering the
execution state (including local variables and pending
try-statements).  When the `generator iterator' resumes, it picks up where
it left off (in contrast to functions which start fresh on every
invocation).

@geindex generator expression
@anchor{glossary term-generator-expression}@anchor{5999}
@geindex generator expression

@item generator expression

(ジェネレータ式) iterator を返す @ref{23cf,,式}  です。
普通の式に、ループ変数を定義する @code{for} 節、範囲、そして省略可能な @code{if} 節がつづいているように見えます。
こうして構成された式は、外側の関数に向けて値を生成します:

@example
>>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
285
@end example
@anchor{glossary term-generic-function}@anchor{be4}
@geindex generic function

@item generic function

(ジェネリック関数) 異なる型に対し同じ操作をする関数群から構成される関数です。呼び出し時にどの実装を用いるかはディスパッチアルゴリズムにより決定されます。

@ref{be3,,single dispatch}、@ref{84b,,functools.singledispatch()} デコレータ、
@geindex Python Enhancement Proposals; PEP 443
PEP 443@footnote{https://peps.python.org/pep-0443/} を参照してください。
@anchor{glossary term-generic-type}@anchor{1a1}
@geindex generic type

@item generic type

A @ref{1cfe,,type} that can be parameterized; typically a
@ref{23d4,,container class} such as @ref{24d,,list} or
@ref{183,,dict}. Used for @ref{23cb,,type hints} and
@ref{15c,,annotations}.

For more details, see @ref{8c1,,generic alias types},
@geindex Python Enhancement Proposals; PEP 483
PEP 483@footnote{https://peps.python.org/pep-0483/}, 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/}, 
@geindex Python Enhancement Proposals; PEP 585
PEP 585@footnote{https://peps.python.org/pep-0585/}, and the @ref{10a,,typing} module.
@anchor{glossary term-GIL}@anchor{164}
@geindex GIL

@item GIL

@ref{474,,global interpreter lock} を参照してください。
@anchor{glossary term-global-interpreter-lock}@anchor{474}
@geindex global interpreter lock

@item global interpreter lock

(グローバルインタプリタロック) @ref{905,,CPython} インタプリタが利用している、一度に Python の @ref{4aa,,バイトコード} を実行するスレッドは一つだけであることを保証する仕組みです。これにより (@ref{183,,dict} などの重要な組み込み型を含む) オブジェクトモデルが同時アクセスに対して暗黙的に安全になるので、 CPython の実装がシンプルになります。インタプリタ全体をロックすることで、マルチプロセッサマシンが生じる並列化のコストと引き換えに、インタプリタを簡単にマルチスレッド化できるようになります。

ただし、標準あるいは外部のいくつかの拡張モジュールは、圧縮やハッシュ計算などの計算の重い処理をするときに GIL を解除するように設計されています。また、I/O 処理をする場合 GIL は常に解除されます。

As of Python 3.13, the GIL can be disabled using the @ref{499,,--disable-gil}
build configuration. After building Python with this option, code must be
run with @ref{16f,,-X gil=0} or after setting the 
@geindex PYTHON_GIL
@geindex 環境変数; PYTHON_GIL
@ref{49a,,PYTHON_GIL=0}
environment variable. This feature enables improved performance for
multi-threaded applications and makes it easier to use multi-core CPUs
efficiently. For more details, see 
@geindex Python Enhancement Proposals; PEP 703
PEP 703@footnote{https://peps.python.org/pep-0703/}.

In prior versions of Python's C API, a function might declare that it
requires the GIL to be held in order to use it. This refers to having an
@ref{4ed1,,attached thread state}.
@anchor{glossary term-global-state}@anchor{599a}
@geindex global state

@item global state

Data that is accessible throughout a program, such as module-level
variables, class variables, or C static variables in @ref{2251,,extension modules}.  In multi-threaded programs, global state shared
between threads typically requires synchronization to avoid
@ref{5985,,race conditions} and
@ref{5986,,data races}.
@anchor{glossary term-hash-based-pyc}@anchor{599b}
@geindex hash-based pyc

@item hash-based pyc

(ハッシュベース pyc ファイル) 正当性を判別するために、対応するソースファイルの最終更新時刻ではなくハッシュ値を使用するバイトコードのキャッシュファイルです。@ref{802,,キャッシュされたバイトコードの無効化} を参照してください。
@anchor{glossary term-hashable}@anchor{824}
@geindex hashable

@item hashable

An object is `hashable' if it has a hash value which never changes during
its lifetime (it needs a @ref{cf3,,__hash__()} method), and can be
compared to other objects (it needs an @ref{cf2,,__eq__()} method).
Hashable objects which
compare equal must have the same hash value.

ハッシュ可能なオブジェクトは辞書のキーや集合のメンバーとして使えます。辞書や集合のデータ構造は内部でハッシュ値を使っているからです。

Python のイミュータブルな組み込みオブジェクトは、ほとんどがハッシュ可能です。(リストや辞書のような) ミュータブルなコンテナはハッシュ不可能です。(タプルや frozenset のような) イミュータブルなコンテナは、要素がハッシュ可能であるときのみハッシュ可能です。
ユーザー定義のクラスのインスタンスであるようなオブジェクトはデフォルトでハッシュ可能です。
それらは全て (自身を除いて) 比較結果は非等価であり、ハッシュ値は @ref{163c,,id()} より得られます。
@anchor{glossary term-IDLE}@anchor{599c}
@geindex IDLE

@item IDLE

Python の統合開発環境 (Integrated DeveLopment Environment)及び学習環境 (Learning Environment) です。@ref{1217,,IDLE --- Python のエディタとシェル} は Python の標準的な配布に同梱されている基本的な機能のエディタとインタプリタ環境です。
@anchor{glossary term-immortal}@anchor{290}
@geindex 永続オブジェクト (immortal)

@item 永続オブジェクト (immortal)

`Immortal objects' are a CPython implementation detail introduced
in 
@geindex Python Enhancement Proposals; PEP 683
PEP 683@footnote{https://peps.python.org/pep-0683/}.

If an object is immortal, its @ref{4ec9,,reference count} is never modified,
and therefore it is never deallocated while the interpreter is running.
For example, @ref{e07,,True} and @ref{885,,None} are immortal in CPython.

Immortal objects can be identified via @ref{28f,,sys._is_immortal()}, or
via @ref{3c4,,PyUnstable_IsImmortal()} in the C API.
@anchor{glossary term-immutable}@anchor{15b9}
@geindex immutable

@item immutable

An object with a fixed value.  Immutable objects include numbers, strings and
tuples.  Such an object cannot be altered.  A new object has to
be created if a different value has to be stored.  They play an important
role in places where a constant hash value is needed, for example as a key
in a dictionary.  Immutable objects are inherently @ref{5992,,thread-safe}
because their state cannot be modified after creation, eliminating concerns
about improperly synchronized @ref{598c,,concurrent modification}.
@anchor{glossary term-import-path}@anchor{244a}
@geindex import path

@item import path

@ref{244d,,path based finder} が import するモジュールを検索する場所 (または @ref{2458,,path entry}) のリスト。 import 中、このリストは通常 @ref{3e4,,sys.path} から来ますが、サブパッケージの場合は親パッケージの @code{__path__} 属性からも来ます。
@anchor{glossary term-importing}@anchor{243c}
@geindex importing

@item importing

あるモジュールの Python コードが別のモジュールの Python コードで使えるようにする処理です。
@anchor{glossary term-importer}@anchor{2448}
@geindex importer

@item importer

モジュールを探してロードするオブジェクト。 @ref{236a,,finder} と @ref{1a28,,loader} のどちらでもあるオブジェクト。
@anchor{glossary term-index}@anchor{23e3}
@geindex index

@item index

A numeric value that represents the position of an element in
a @ref{716,,sequence}.

In Python, indexing starts at zero.
For example, @code{things[0]} names the `first' element of @code{things};
@code{things[1]} names the second one.

In some contexts, Python allows negative indexes for counting from the
end of a sequence, and indexing using @ref{24ae,,slices}.

See also @ref{599d,,subscript}.
@anchor{glossary term-interactive}@anchor{1b5}
@geindex interactive

@item interactive

Python has an interactive interpreter which means you can enter
statements and expressions at the interpreter prompt, immediately
execute them and see their results.  Just launch @code{python} with no
arguments (possibly by selecting it from your computer's main
menu). It is a very powerful way to test out new ideas or inspect
modules and packages (remember @code{help(x)}). For more on interactive
mode, see @ref{494,,対話モード}.
@anchor{glossary term-interpreted}@anchor{599e}
@geindex interpreted

@item interpreted

Python はインタプリタ形式の言語であり、コンパイラ言語の対極に位置します。 (バイトコードコンパイラがあるために、この区別は曖昧ですが。) ここでのインタプリタ言語とは、ソースコードのファイルを、まず実行可能形式にしてから実行させるといった操作なしに、直接実行できることを意味します。インタプリタ形式の言語は通常、コンパイラ形式の言語よりも開発／デバッグのサイクルは短いものの、プログラムの実行は一般に遅いです。 @ref{1b5,,対話的} も参照してください。
@anchor{glossary term-interpreter-shutdown}@anchor{479}
@geindex interpreter shutdown

@item interpreter shutdown

Python インタープリターはシャットダウンを要請された時に、モジュールやすべてのクリティカルな内部構造をなどの、すべての確保したリソースを段階的に開放する、特別なフェーズに入ります。
このフェーズは @ref{17d8,,ガベージコレクタ} を複数回呼び出します。
これによりユーザー定義のデストラクターや weakref コールバックが呼び出されることがあります。
シャットダウンフェーズ中に実行されるコードは、それが依存するリソースがすでに機能しない(よくある例はライブラリーモジュールや warning 機構です) ために様々な例外に直面します。

インタープリタがシャットダウンする主な理由は @code{__main__} モジュールや実行されていたスクリプトの実行が終了したことです。
@anchor{glossary term-iterable}@anchor{12f1}
@geindex iterable

@item iterable

An object capable of returning its members one at a time. Examples of
iterables include all sequence types (such as @ref{24d,,list}, @ref{169,,str},
and @ref{614,,tuple}) and some non-sequence types like @ref{183,,dict},
@ref{13db,,file objects}, and objects of any classes you define
with an @ref{e69,,__iter__()} method or with a
@ref{588,,__getitem__()} method
that implements @ref{716,,sequence} semantics.

反復可能オブジェクトは @ref{34a,,for} ループ内やその他多くのシーケンス (訳注: ここでのシーケンスとは、シーケンス型ではなくただの列という意味)が必要となる状況 (@ref{1a0,,zip()}, @ref{19f,,map()}, ...) で利用できます。
反復可能オブジェクトを組み込み関数 @ref{9d7,,iter()} の引数として渡すと、 オブジェクトに対するイテレータを返します。
このイテレータは一連の値を引き渡す際に便利です。
通常は反復可能オブジェクトを使う際には、 @ref{9d7,,iter()} を呼んだりイテレータオブジェクトを自分で操作する必要はありません。
@ref{34a,,for} 文ではこの操作を自動的に行い、一時的な無名の変数を作成してループを回している間イテレータを保持します。
@ref{4c8,,イテレータ} 、 @ref{716,,シーケンス} 、 @ref{126c,,ジェネレータ} も参照してください。
@anchor{glossary term-iterator}@anchor{4c8}
@geindex iterator

@item iterator

データの流れを表現するオブジェクトです。イテレータの @ref{14e5,,__next__()} メソッドを繰り返し呼び出す (または組み込み関数 @ref{9d8,,next()} に渡す) と、流れの中の要素を一つずつ返します。データがなくなると、代わりに @ref{df5,,StopIteration} 例外を送出します。その時点で、イテレータオブジェクトは尽きており、それ以降は @code{__next__()} を何度呼んでも @ref{df5,,StopIteration} を送出します。イテレータは、そのイテレータオブジェクト自体を返す @ref{20ad,,__iter__()} メソッドを実装しなければならないので、イテレータは他の iterable を受理するほとんどの場所で利用できます。はっきりとした例外は複数の反復を行うようなコードです。 (@ref{24d,,list} のような) コンテナオブジェクトは、自身を @ref{9d7,,iter()} 関数にオブジェクトに渡したり @ref{34a,,for} ループ内で使うたびに、新たな未使用のイテレータを生成します。これをイテレータで行おうとすると、前回のイテレーションで使用済みの同じイテレータオブジェクトを単純に返すため、空のコンテナのようになってしまいます。

詳細な情報は @ref{25d7,,イテレータ型} にあります。

`CPython 実装の詳細:' CPython does not consistently apply the requirement that an iterator
define @ref{20ad,,__iter__()}.
And also please note that @ref{1f4,,free-threaded}
CPython does not guarantee @ref{5992,,thread-safe} behavior of iterator
operations.
@anchor{glossary term-key}@anchor{23e4}
@geindex キー

@item キー

A value that identifies an entry in a @ref{13d3,,mapping}.
See also @ref{599d,,subscript}.
@anchor{glossary term-key-function}@anchor{1006}
@geindex key function

@item key function

(キー関数) キー関数、あるいは照合関数とは、ソートや順序比較のための値を返す呼び出し可能オブジェクト(callable)です。例えば、 @ref{17bd,,locale.strxfrm()} をキー関数に使えば、ロケール依存のソートの慣習にのっとったソートキーを返します。

Python の多くのツールはキー関数を受け取り要素の並び順やグループ化を管理します。
@ref{110b,,min()}, @ref{110c,,max()}, @ref{dc7,,sorted()}, @ref{dc8,,list.sort()}, @ref{1005,,heapq.merge()}, @ref{29a6,,heapq.nsmallest()}, @ref{29a5,,heapq.nlargest()}, @ref{2ba5,,itertools.groupby()} 等があります。

There are several ways to create a key function.  For example. the
@ref{fd6,,str.casefold()} method can serve as a key function for case insensitive
sorts.  Alternatively, a key function can be built from a
@ref{14b5,,lambda} expression such as @code{lambda r: (r[0], r[2])}.  Also,
@ref{1033,,operator.attrgetter()}, @ref{c57,,operator.itemgetter()}, and
@ref{1034,,operator.methodcaller()} are three key function constructors.  See the @ref{13f3,,Sorting HOW TO} for examples of how to create and use key functions.
@anchor{glossary term-keyword-argument}@anchor{f0e}
@geindex keyword argument

@item keyword argument

@ref{67b,,実引数} を参照してください。
@anchor{glossary term-lambda}@anchor{2bb3}
@geindex lambda

@item lambda

(ラムダ) 無名のインライン関数で、関数が呼び出されたときに評価される 1 つの @ref{23cf,,式} を含みます。ラムダ関数を作る構文は @code{lambda [parameters]: expression} です。
@anchor{glossary term-LBYL}@anchor{5997}
@geindex LBYL

@item LBYL

「ころばぬ先の杖 (look before you leap)」 の略です。このコーディングスタイルでは、呼び出しや検索を行う前に、明示的に前提条件 (pre-condition) 判定を行います。 @ref{3079,,EAFP} アプローチと対照的で、 @ref{181,,if} 文がたくさん使われるのが特徴的です。

In a multi-threaded environment, the LBYL approach can risk introducing a
@ref{5985,,race condition} between "the looking" and "the leaping".  For example,
the code, @code{if key in mapping: return mapping[key]} can fail if another
thread removes `key' from `mapping' after the test, but before the lookup.
This issue can be solved with @ref{598f,,locks} or by using the
@ref{3079,,EAFP} approach.  See also @ref{5992,,thread-safe}.
@anchor{glossary term-lexical-analyzer}@anchor{2292}
@geindex lexical analyzer

@item lexical analyzer

Formal name for the `tokenizer'; see @ref{2288,,token}.
@anchor{glossary term-list}@anchor{599f}
@geindex list

@item list

A built-in Python @ref{716,,sequence}.  Despite its name it is more akin
to an array in other languages than to a linked list since access to
elements is `O'(1).
@anchor{glossary term-list-comprehension}@anchor{8dd}
@geindex list comprehension

@item list comprehension

(リスト内包表記) シーケンス中の全てあるいは一部の要素を処理して、その結果からなるリストを返す、コンパクトな方法です。 @code{result = ['@{:#04x@}'.format(x) for x in range(256) if x % 2 == 0]} とすると、 0 から 255 までの偶数を 16進数表記 (0x..) した文字列からなるリストを生成します。 @ref{181,,if} 節はオプションです。 @ref{181,,if} 節がない場合、 @code{range(256)} の全ての要素が処理されます。
@anchor{glossary term-lock}@anchor{598f}
@geindex lock

@item lock

A @ref{5990,,synchronization primitive} that allows only one thread at a
time to access a shared resource.  A thread must acquire a lock before
accessing the protected resource and release it afterward.  If a thread
attempts to acquire a lock that is already held by another thread, it
will block until the lock becomes available.  Python's @ref{f3,,threading}
module provides @ref{19f4,,Lock} (a basic lock) and
@ref{32e,,RLock} (a @ref{5994,,reentrant} lock).  Locks are used
to prevent @ref{5985,,race conditions} and ensure
@ref{5992,,thread-safe} access to shared data.  Alternative design patterns
to locks exist such as queues, producer/consumer patterns, and
thread-local state. See also @ref{5993,,deadlock}, and @ref{5994,,reentrant}.
@anchor{glossary term-lock-free}@anchor{2617}
@geindex lock-free

@item lock-free

An operation that does not acquire any @ref{598f,,lock} and uses atomic CPU
instructions to ensure correctness. Lock-free operations can execute
concurrently without blocking each other and cannot be blocked by
operations that hold locks. In @ref{1f4,,free-threaded}
Python, built-in types like @ref{183,,dict} and @ref{24d,,list} provide
lock-free read operations, which means other threads may observe
intermediate states during multi-step modifications even when those
modifications hold the @ref{2616,,per-object lock}.
@anchor{glossary term-loader}@anchor{1a28}
@geindex loader

@item loader

An object that loads a module.
It must define the @code{exec_module()} and @code{create_module()} methods
to implement the @ref{10c7,,Loader} interface.
A loader is typically returned by a @ref{236a,,finder}.
See also:


@itemize *

@item 
@ref{2446,,ファインダーとローダー}

@item 
@ref{10c7,,importlib.abc.Loader}

@item 
@geindex Python Enhancement Proposals; PEP 302
PEP 302@footnote{https://peps.python.org/pep-0302/}
@end itemize
@anchor{glossary term-locale-encoding}@anchor{54a}
@geindex ロケールエンコーディング

@item ロケールエンコーディング

On Unix, it is the encoding of the LC_CTYPE locale. It can be set with
@ref{328,,locale.setlocale(locale.LC_CTYPE@comma{} new_locale)}.

On Windows, it is the ANSI code page (ex: @code{"cp1252"}).

On Android and VxWorks, Python uses @code{"utf-8"} as the locale encoding.

@ref{329,,locale.getencoding()} can be used to get the locale encoding.

See also the @ref{75d,,filesystem encoding and error handler}.
@anchor{glossary term-magic-method}@anchor{4667}
@geindex magic method

@item magic method

@geindex magic;メソッド

@ref{1c60,,special method} のくだけた同義語です。
@anchor{glossary term-mapping}@anchor{13d3}
@geindex mapping

@item mapping

(マッピング) 任意のキー探索をサポートしていて、 @ref{ac7,,collections.abc.Mapping} か @ref{12c0,,collections.abc.MutableMapping} の @ref{a78,,抽象基底クラス} で指定されたメソッドを実装しているコンテナオブジェクトです。例えば、 @ref{183,,dict}, @ref{13d4,,collections.defaultdict}, @ref{7f3,,collections.OrderedDict}, @ref{12a3,,collections.Counter} などです。
@anchor{glossary term-meta-path-finder}@anchor{127c}
@geindex meta path finder

@item meta path finder

@ref{f27,,sys.meta_path} を検索して得られた @ref{236a,,finder}.
meta path finder は @ref{127d,,path entry finder} と関係はありますが、別物です。

meta path finder が実装するメソッドについては @ref{a6e,,importlib.abc.MetaPathFinder} を参照してください。
@anchor{glossary term-metaclass}@anchor{23d0}
@geindex metaclass

@item metaclass

(メタクラス) クラスのクラスです。クラス定義は、クラス名、クラスの辞書と、基底クラスのリストを作ります。メタクラスは、それら 3 つを引数として受け取り、クラスを作る責任を負います。ほとんどのオブジェクト指向言語は(訳注:メタクラスの)デフォルトの実装を提供しています。Python が特別なのはカスタムのメタクラスを作成できる点です。ほとんどのユーザーに取って、メタクラスは全く必要のないものです。しかし、一部の場面では、メタクラスは強力でエレガントな方法を提供します。たとえば属性アクセスのログを取ったり、スレッドセーフ性を追加したり、オブジェクトの生成を追跡したり、シングルトンを実装するなど、多くの場面で利用されます。

詳細は @ref{23be,,メタクラス} を参照してください。
@anchor{glossary term-method}@anchor{1864}
@geindex メソッド

@item メソッド

(メソッド) クラス本体の中で定義された関数。そのクラスのインスタンスの属性として呼び出された場合、メソッドはインスタンスオブジェクトを第一 @ref{67b,,引数} として受け取ります (この第一引数は通常 @code{self} と呼ばれます)。 @ref{24b7,,関数} と @ref{238d,,ネストされたスコープ} も参照してください。
@anchor{glossary term-method-resolution-order}@anchor{25df}
@geindex method resolution order

@item method resolution order

Method Resolution Order is the order in which base classes are searched
for a member during lookup. See @ref{16c3,,The Python 2.3 Method Resolution Order} for details of the
algorithm used by the Python interpreter since the 2.3 release.
@anchor{glossary term-module}@anchor{19de}
@geindex module

@item module

(モジュール) Python コードの組織単位としてはたらくオブジェクトです。モジュールは任意の Python オブジェクトを含む名前空間を持ちます。モジュールは @ref{243c,,importing} の処理によって Python に読み込まれます。

@ref{233,,パッケージ} を参照してください。
@anchor{glossary term-module-spec}@anchor{2363}
@geindex module spec

@item module spec

モジュールをロードするのに使われるインポート関連の情報を含む名前空間です。
@ref{226c,,importlib.machinery.ModuleSpec} のインスタンスです。

See also @ref{2366,,Module specs}.
@anchor{glossary term-MRO}@anchor{18dd}
@geindex MRO

@item MRO

@ref{25df,,method resolution order} を参照してください。
@anchor{glossary term-mutable}@anchor{15ba}
@geindex mutable

@item mutable

An @ref{59a0,,object} with state that is allowed to change during the course
of the program.  In multi-threaded programs, mutable objects that are
shared between threads require careful synchronization to avoid
@ref{5985,,race conditions}.  See also @ref{15b9,,immutable},
@ref{5992,,thread-safe}, and @ref{598c,,concurrent modification}.
@anchor{glossary term-named-tuple}@anchor{85e}
@geindex named tuple

@item named tuple

"名前付きタプル" という用語は、タプルを継承していて、インデックスが付く要素に対し属性を使ってのアクセスもできる任意の型やクラスに応用されています。
その型やクラスは他の機能も持っていることもあります。

@ref{1712,,time.localtime()} や @ref{26d,,os.stat()} の返り値を含むいくつかの組み込み型は名前付きタプルです。
他の例は @ref{1dcf,,sys.float_info} です:

@example
>>> sys.float_info[1]                   # indexed access
1024
>>> sys.float_info.max_exp              # named field access
1024
>>> isinstance(sys.float_info, tuple)   # kind of tuple
True
@end example

Some named tuples are built-in types (such as the above examples).
Alternatively, a named tuple can be created from a regular class
definition that inherits from @ref{614,,tuple} and that defines named
fields.  Such a class can be written by hand, or it can be created by
inheriting @ref{331,,typing.NamedTuple}, or with the factory function
@ref{4e0,,collections.namedtuple()}.  The latter techniques also add some
extra methods that may not be found in hand-written or built-in named
tuples.
@anchor{glossary term-namespace}@anchor{203f}
@geindex namespace

@item namespace

(名前空間) 変数が格納される場所です。名前空間は辞書として実装されます。名前空間にはオブジェクトの (メソッドの) 入れ子になったものだけでなく、局所的なもの、大域的なもの、そして組み込みのものがあります。名前空間は名前の衝突を防ぐことによってモジュール性をサポートする。例えば関数 @ref{316,,builtins.open} と @ref{f92,,os.open()} は名前空間で区別されています。また、どのモジュールが関数を実装しているか明示することによって名前空間は可読性と保守性を支援します。例えば、@ref{148b,,random.seed()} や @ref{d43,,itertools.islice()} と書くと、それぞれモジュール @ref{bd,,random} や @ref{85,,itertools} で実装されていることが明らかです。
@anchor{glossary term-namespace-package}@anchor{2b2}
@geindex namespace package

@item namespace package

A @ref{233,,package} which serves only as a container for subpackages.
Namespace packages may have no physical representation,
and specifically are not like a @ref{2440,,regular package} because they
have no @code{__init__.py} file.

Namespace packages allow several individually installable packages to have a common parent package.
Otherwise, it is recommended to use a @ref{2440,,regular package}.

For more information, see 
@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} and @ref{2442,,名前空間パッケージ}.

@ref{19de,,module} を参照してください。
@anchor{glossary term-native-code}@anchor{5991}
@geindex native code

@item native code

Code that is compiled to machine instructions and runs directly on the
processor, as opposed to code that is interpreted or runs in a virtual
machine.  In the context of Python, native code typically refers to
C, C++, Rust or Fortran code in @ref{2251,,extension modules}
that can be called from Python.  See also @ref{2251,,extension module}.
@anchor{glossary term-nested-scope}@anchor{238d}
@geindex nested scope

@item nested scope

(ネストされたスコープ) 外側で定義されている変数を参照する機能です。例えば、ある関数が別の関数の中で定義されている場合、内側の関数は外側の関数中の変数を参照できます。ネストされたスコープはデフォルトでは変数の参照だけができ、変数の代入はできないので注意してください。ローカル変数は、最も内側のスコープで変数を読み書きします。同様に、グローバル変数を使うとグローバル名前空間の値を読み書きします。 @ref{14bf,,nonlocal} で外側の変数に書き込めます。
@anchor{glossary term-new-style-class}@anchor{2d0a}
@geindex new-style class

@item new-style class

Old name for the flavor of classes now used for all class objects.  In
earlier Python versions, only new-style classes could use Python's newer,
versatile features like @ref{1704,,__slots__}, descriptors,
properties, @ref{dcb,,__getattribute__()}, class methods, and static
methods.
@anchor{glossary term-non-deterministic}@anchor{598e}
@geindex non-deterministic

@item non-deterministic

Behavior where the outcome of a program can vary between executions with
the same inputs.  In multi-threaded programs, non-deterministic behavior
often results from @ref{5985,,race conditions} where the
relative timing or interleaving of threads affects the result.
Proper synchronization using @ref{598f,,locks} and other
@ref{5990,,synchronization primitives} helps
ensure deterministic behavior.
@anchor{glossary term-object}@anchor{59a0}
@geindex object

@item object

(オブジェクト) 状態 (属性や値) と定義された振る舞い (メソッド) をもつ全てのデータ。もしくは、全ての @ref{2d0a,,新スタイルクラス} の究極の基底クラスのこと。
@anchor{glossary term-optimized-scope}@anchor{4a1}
@geindex optimized scope

@item optimized scope

A scope where target local variable names are reliably known to the
compiler when the code is compiled, allowing optimization of read and
write access to these names. The local namespaces for functions,
generators, coroutines, comprehensions, and generator expressions are
optimized in this fashion. Note: most interpreter optimizations are
applied to all scopes, only those relying on a known set of local
and nonlocal variable names are restricted to optimized scopes.
@anchor{glossary term-optional-module}@anchor{215a}
@geindex optional module

@item optional module

An @ref{2251,,extension module} that is part of the @ref{59a1,,standard library},
but may be absent in some builds of @ref{905,,CPython},
usually due to missing third-party libraries or because the module
is not available for a given platform.

See @ref{2158,,オプションのモジュールの要件} for a list of optional modules
that require third-party libraries.
@anchor{glossary term-package}@anchor{233}
@geindex package

@item package

(パッケージ) サブモジュールや再帰的にサブパッケージを含むことの出来る @ref{19de,,module} のことです。専門的には、パッケージは @code{__path__} 属性を持つ Python オブジェクトです。

@ref{2440,,regular package} と @ref{2b2,,namespace package} を参照してください。
@anchor{glossary term-parallelism}@anchor{598b}
@geindex parallelism

@item parallelism

Executing multiple operations at the same time (e.g. on multiple CPU
cores).  In Python builds with the
@ref{474,,global interpreter lock (GIL)}, only one
thread runs Python bytecode at a time, so taking advantage of multiple
CPU cores typically involves multiple processes
(e.g. @ref{98,,multiprocessing}) or native extensions that release the GIL.
In @ref{1f4,,free-threaded} Python, multiple Python threads
can run Python code simultaneously on different cores.
@anchor{glossary term-parameter}@anchor{234b}
@geindex parameter

@item parameter

(仮引数) 名前付の実体で @ref{24b7,,関数} (や @ref{1864,,メソッド} ) の定義において関数が受ける @ref{67b,,実引数} を指定します。仮引数には5種類あります:


@itemize *

@item 
`位置またはキーワード': @ref{67b,,位置} であるいは @ref{67b,,キーワード引数} として渡すことができる引数を指定します。
これはたとえば以下の `foo' や `bar' のように、デフォルトの仮引数の種類です:

@example
def func(foo, bar=None): ...
@end example
@end itemize
@anchor{glossary positional-only-parameter}@anchor{c78}

@itemize *

@item 
`位置専用': 位置によってのみ与えられる引数を指定します。位置専用の引数は関数定義の引数のリストの中でそれらの後ろに @code{/} を含めることで定義できます。例えば下記の `posonly1' と `posonly2' は位置専用引数になります:

@example
def func(posonly1, posonly2, /, positional_or_keyword): ...
@end example
@end itemize
@anchor{glossary keyword-only-parameter}@anchor{5a5}

@itemize *

@item 
`キーワード専用': キーワードによってのみ与えられる引数を指定します。キーワード専用の引数を定義できる場所は、例えば以下の `kw_only1' や `kw_only2' のように、関数定義の仮引数リストに含めた可変長位置引数または裸の @code{*} の後です:

@example
def func(arg, *, kw_only1, kw_only2): ...
@end example

@item 
`可変長位置': (他の仮引数で既に受けられた任意の位置引数に加えて) 任意の個数の位置引数が与えられることを指定します。このような仮引数は、以下の `args' のように仮引数名の前に @code{*} をつけることで定義できます:

@example
def func(*args, **kwargs): ...
@end example

@item 
`可変長キーワード': (他の仮引数で既に受けられた任意のキーワード引数に加えて) 任意の個数のキーワード引数が与えられることを指定します。このような仮引数は、上の例の `kwargs' のように仮引数名の前に @code{**} をつけることで定義できます。
@end itemize

仮引数はオプションと必須の引数のどちらも指定でき、オプションの引数にはデフォルト値も指定できます。

@ref{234b,,仮引数} 、FAQ の @ref{58be,,実引数と仮引数の違いは何ですか?} 、@ref{4e4,,inspect.Parameter}  クラス、 @ref{2018,,関数定義} セクション、
@geindex Python Enhancement Proposals; PEP 362
PEP 362@footnote{https://peps.python.org/pep-0362/} を参照してください。
@anchor{glossary term-per-object-lock}@anchor{2616}
@geindex per-object lock

@item per-object lock

A @ref{598f,,lock} associated with an individual object instance rather than
a global lock shared across all objects. In @ref{1f4,,free-threaded} Python, built-in types like @ref{183,,dict} and
@ref{24d,,list} use per-object locks to allow concurrent operations on
different objects while serializing operations on the same object.
Operations that hold the per-object lock prevent other locking operations
on the same object from proceeding, but do not block @ref{2617,,lock-free}
operations.
@anchor{glossary term-path-entry}@anchor{2458}
@geindex path entry

@item path entry

@ref{244d,,path based finder} が import するモジュールを探す @ref{244a,,import path} 上の1つの場所です。
@anchor{glossary term-path-entry-finder}@anchor{127d}
@geindex path entry finder

@item path entry finder

@ref{1225,,sys.path_hooks} にある callable (つまり @ref{245a,,path entry hook}) が返した @ref{236a,,finder} です。与えられた @ref{2458,,path entry} にあるモジュールを見つける方法を知っています。

パスエントリーファインダが実装するメソッドについては @ref{a6f,,importlib.abc.PathEntryFinder} を参照してください。
@anchor{glossary term-path-entry-hook}@anchor{245a}
@geindex path entry hook

@item path entry hook

A callable on the @ref{1225,,sys.path_hooks} list which returns a @ref{127d,,path entry finder} if it knows how to find modules on a specific @ref{2458,,path entry}.
@anchor{glossary term-path-based-finder}@anchor{244d}
@geindex path based finder

@item path based finder

デフォルトの @ref{127c,,meta path finder} の1つは、モジュールの @ref{244a,,import path} を検索します。
@anchor{glossary term-path-like-object}@anchor{5a1}
@geindex path-like object

@item path-like object

(path-like オブジェクト) ファイルシステムパスを表します。
path-like オブジェクトは、パスを表す @ref{169,,str} オブジェクトや @ref{192,,bytes} オブジェクト、または @ref{e4b,,os.PathLike} プロトコルを実装したオブジェクトのどれかです。
@ref{e4b,,os.PathLike} プロトコルをサポートしているオブジェクトは @ref{e4d,,os.fspath()} を呼び出すことで @ref{169,,str} または @ref{192,,bytes} のファイルシステムパスに変換できます。 @ref{e4e,,os.fsdecode()} と @ref{e4f,,os.fsencode()} はそれぞれ @ref{169,,str} あるいは @ref{192,,bytes} になるのを保証するのに使えます。
@geindex Python Enhancement Proposals; PEP 519
PEP 519@footnote{https://peps.python.org/pep-0519/} で導入されました。
@anchor{glossary term-PEP}@anchor{59a2}
@geindex PEP

@item PEP

Python Enhancement Proposal。PEP は、Python コミュニティに対して情報を提供する、あるいは Python の新機能やその過程や環境について記述する設計文書です。
PEP は、機能についての簡潔な技術的仕様と提案する機能の論拠 (理論) を伝えるべきです。

PEP は、新機能の提案にかかる、コミュニティによる問題提起の集積と Python になされる設計決断の文書化のための最上位の機構となることを意図しています。PEP の著者にはコミュニティ内の合意形成を行うこと、反対意見を文書化することの責務があります。

@geindex Python Enhancement Proposals; PEP 1
PEP 1@footnote{https://peps.python.org/pep-0001/} を参照してください。
@anchor{glossary term-portion}@anchor{2443}
@geindex portion

@item portion

@geindex Python Enhancement Proposals; PEP 420
PEP 420@footnote{https://peps.python.org/pep-0420/} で定義されている、namespace package に属する、複数のファイルが (zipファイルに格納されている場合もある) 1つのディレクトリに格納されたもの。
@anchor{glossary term-positional-argument}@anchor{f0f}
@geindex 位置引数 (positional argument)

@item 位置引数 (positional argument)

@ref{67b,,実引数} を参照してください。
@anchor{glossary term-provisional-API}@anchor{3d1}
@geindex provisional API

@item provisional API

(暫定 API) 標準ライブラリの後方互換性保証から計画的に除外されたものです。そのようなインターフェースへの大きな変更は、暫定であるとされている間は期待されていませんが、コア開発者によって必要とみなされれば、後方非互換な変更 (インターフェースの削除まで含まれる) が行われえます。このような変更はむやみに行われるものではありません -- これは API を組み込む前には見落とされていた重大な欠陥が露呈したときにのみ行われます。

暫定 API についても、後方互換性のない変更は「最終手段」とみなされています。問題点が判明した場合でも後方互換な解決策を探すべきです。

このプロセスにより、標準ライブラリは問題となるデザインエラーに長い間閉じ込められることなく、時代を超えて進化を続けられます。詳細は 
@geindex Python Enhancement Proposals; PEP 411
PEP 411@footnote{https://peps.python.org/pep-0411/} を参照してください。
@anchor{glossary term-provisional-package}@anchor{1243}
@geindex provisional package

@item provisional package

@ref{3d1,,provisional API} を参照してください。
@anchor{glossary term-Python-3000}@anchor{59a3}
@geindex Python 3000

@item Python 3000

Python 3.x リリースラインのニックネームです。(Python 3 が遠い将来の話だった頃に作られた言葉です。) "Py3k" と略されることもあります。
@anchor{glossary term-Pythonic}@anchor{59a4}
@geindex Pythonic

@item Pythonic

他の言語で一般的な考え方で書かれたコードではなく、Python の特に一般的なイディオムに従った考え方やコード片。例えば、Python の一般的なイディオムでは @ref{34a,,for} 文を使ってイテラブルのすべての要素に渡ってループします。他の多くの言語にはこの仕組みはないので、Python に慣れていない人は代わりに数値のカウンターを使うかもしれません:

@example
for i in range(len(food)):
    print(food[i])
@end example

これに対し、きれいな Pythonic な方法は:

@example
for piece in food:
    print(piece)
@end example
@anchor{glossary term-qualified-name}@anchor{1d24}
@geindex qualified name

@item qualified name

(修飾名) モジュールのグローバルスコープから、そのモジュールで定義されたクラス、関数、メソッドへの、 "パス" を表すドット名表記です。 
@geindex Python Enhancement Proposals; PEP 3155
PEP 3155@footnote{https://peps.python.org/pep-3155/} で定義されています。トップレベルの関数やクラスでは、修飾名はオブジェクトの名前と同じです:

@example
>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
@end example

モジュールへの参照で使われると、`完全修飾名 (fully qualified name)' はすべての親パッケージを含む全体のドット名表記、例えば @code{email.mime.text} を意味します:

@example
>>> import email.mime.text
>>> email.mime.text.__name__
'email.mime.text'
@end example
@anchor{glossary term-race-condition}@anchor{5985}
@geindex race condition

@item race condition

A condition of a program where the behavior
depends on the relative timing or ordering of events, particularly in
multi-threaded programs.  Race conditions can lead to
@ref{598e,,non-deterministic} behavior and bugs that are difficult to
reproduce.  A @ref{5986,,data race} is a specific type of race condition
involving unsynchronized access to shared memory.  The @ref{5997,,LBYL}
coding style is particularly susceptible to race conditions in
multi-threaded code.  Using @ref{598f,,locks} and other
@ref{5990,,synchronization primitives}
helps prevent race conditions.
@anchor{glossary term-reference-count}@anchor{4ec9}
@geindex reference count

@item reference count

(参照カウント) あるオブジェクトに対する参照の数。参照カウントが0になったとき、そのオブジェクトは破棄されます。 @ref{290,,永続} であり、参照カウントが決して変更されないために割り当てが解除されないオブジェクトもあります。参照カウントは通常は Python のコード上には現れませんが、 @ref{905,,CPython} 実装の重要な要素です。プログラマーは、 任意のオブジェクトの参照カウントを知るために @ref{2ce,,sys.getrefcount()} 関数を呼び出すことが出来ます。

In @ref{905,,CPython}, reference counts are not considered to be stable
or well-defined values; the number of references to an object, and how
that number is affected by Python code, may be different between
versions.
@anchor{glossary term-regular-package}@anchor{2440}
@geindex regular package

@item regular package

伝統的な、 @code{__init__.py} ファイルを含むディレクトリとしての @ref{233,,package}。

@ref{2b2,,namespace package} を参照してください。
@anchor{glossary term-reentrant}@anchor{5994}
@geindex reentrant

@item reentrant

A property of a function or @ref{598f,,lock} that allows it to be called or
acquired multiple times by the same thread without causing errors or a
@ref{5993,,deadlock}.

For functions, reentrancy means the function can be safely called again
before a previous invocation has completed, which is important when
functions may be called recursively or from signal handlers. Thread-unsafe
functions may be @ref{598e,,non-deterministic} if they're called reentrantly in a
multithreaded program.

For locks, Python's @ref{32e,,threading.RLock} (reentrant lock) is
reentrant, meaning a thread that already holds the lock can acquire it
again without blocking.  In contrast, @ref{19f4,,threading.Lock} is not
reentrant - attempting to acquire it twice from the same thread will cause
a deadlock.

See also @ref{598f,,lock} and @ref{5993,,deadlock}.
@anchor{glossary term-REPL}@anchor{491}
@geindex REPL

@item REPL

"read–eval–print loop" の頭字語で、 @ref{1b5,,対話型} インタープリターシェルの別名。
@anchor{glossary term-__slots__}@anchor{7f7}
@geindex __slots__

@item __slots__

クラス内での宣言で、インスタンス属性の領域をあらかじめ定義しておき、インスタンス辞書を排除することで、メモリを節約します。これはよく使われるテクニックですが、正しく扱うには少しトリッキーなので、稀なケース、例えばメモリが死活問題となるアプリケーションでインスタンスが大量に存在する、といったときを除き、使わないのがベストです。
@anchor{glossary term-sequence}@anchor{716}
@geindex sequence

@item sequence

An @ref{12f1,,iterable} which supports efficient element access using integer
indices via the @ref{588,,__getitem__()} special method and defines a
@ref{178f,,__len__()} method that returns the length of the sequence.
Some built-in sequence types are @ref{24d,,list}, @ref{169,,str},
@ref{614,,tuple}, and @ref{192,,bytes}. Note that @ref{183,,dict} also
supports @ref{588,,__getitem__()} and @code{__len__()}, but is considered a
mapping rather than a sequence because the lookups use arbitrary
@ref{824,,hashable} keys rather than integers.

The @ref{13dc,,collections.abc.Sequence} abstract base class
defines a much richer interface that goes beyond just
@ref{588,,__getitem__()} and @ref{178f,,__len__()}, adding
@ref{23d8,,count()}, @ref{1979,,index()},
@ref{15d3,,__contains__()}, and @ref{e86,,__reversed__()}.
Types that implement this expanded
interface can be registered explicitly using
@ref{129a,,register()}. For more documentation on sequence
methods generally, see
@ref{2607,,Common Sequence Operations}.
@anchor{glossary term-set-comprehension}@anchor{59a5}
@geindex set comprehension

@item set comprehension

(集合内包表記) iterable 内の全てあるいは一部の要素を処理して、その結果からなる集合を返すコンパクトな書き方です。 @code{results = @{c for c in 'abracadabra' if c not in 'abc'@}} とすると、@code{@{'r', 'd'@}} という文字列の辞書を生成します。 @ref{7ec,,リスト、集合、辞書の表示} を参照してください。
@anchor{glossary term-single-dispatch}@anchor{be3}
@geindex single dispatch

@item single dispatch

@ref{be4,,generic function} の一種で実装は一つの引数の型により選択されます。
@anchor{glossary term-slice}@anchor{24ae}
@geindex slice

@item slice

An object of type @ref{694,,slice}, used to describe a portion of
a @ref{716,,sequence}.
A slice object is created when using the @ref{24ad,,slicing} form
of @ref{23ce,,subscript notation}, with colons inside square
brackets, such as in @code{variable_name[1:3:5]}.
@anchor{glossary term-soft-deprecated}@anchor{23d}
@geindex soft deprecated

@item soft deprecated

A soft deprecated API should not be used in new code,
but it is safe for already existing code to use it.
The API remains documented and tested, but will not be enhanced further.

Soft deprecation, unlike normal deprecation, does not plan on removing the API
and will not emit warnings.

See PEP 387: Soft Deprecation@footnote{https://peps.python.org/pep-0387/#soft-deprecation}.
@anchor{glossary term-special-method}@anchor{1c60}
@geindex special method

@item special method

@geindex 特殊;メソッド

(特殊メソッド) ある型に特定の操作、例えば加算をするために Python から暗黙に呼び出されるメソッド。この種類のメソッドは、メソッド名の最初と最後にアンダースコア 2 つがついています。特殊メソッドについては @ref{e68,,特殊メソッド名} で解説されています。
@anchor{glossary term-standard-library}@anchor{59a1}
@geindex standard library

@item standard library

The collection of @ref{233,,packages}, @ref{19de,,modules}
and @ref{2251,,extension modules} distributed as a part
of the official Python interpreter package.  The exact membership of the
collection may vary based on platform, available system libraries, or
other criteria.  Documentation can be found at @ref{149,,Python 標準ライブラリ}.

See also @ref{a42,,sys.stdlib_module_names} for a list of all possible
standard library module names.
@anchor{glossary term-statement}@anchor{2bfc}
@geindex statement

@item statement

(文) 文はスイート (コードの"ブロック") に不可欠な要素です。文は @ref{23cf,,式} かキーワードから構成されるもののどちらかです。後者には @ref{181,,if}、@ref{1973,,while}、@ref{34a,,for} があります。
@anchor{glossary term-static-type-checker}@anchor{574}
@geindex static type checker

@item static type checker

An external tool that reads Python code and analyzes it, looking for
issues such as incorrect types. See also @ref{23cb,,type hints}
and the @ref{10a,,typing} module.
@anchor{glossary term-stdlib}@anchor{1786}
@geindex stdlib

@item stdlib

An abbreviation of @ref{59a1,,standard library}.
@anchor{glossary term-strong-reference}@anchor{5e2}
@geindex strong reference

@item strong reference

In Python's C API, a strong reference is a reference to an object
which is owned by the code holding the reference.  The strong
reference is taken by calling @ref{78f,,Py_INCREF()} when the
reference is created and released with @ref{790,,Py_DECREF()}
when the reference is deleted.

The @ref{a9a,,Py_NewRef()} function can be used to create a strong reference
to an object. Usually, the @ref{790,,Py_DECREF()} function must be called on
the strong reference before exiting the scope of the strong reference, to
avoid leaking one reference.

See also @ref{3d7,,borrowed reference}.
@anchor{glossary term-subscript}@anchor{599d}
@geindex 添字

@item 添字

The expression in square brackets of a
@ref{23ce,,subscription expression}, for example,
the @code{3} in @code{items[3]}.
Usually used to select an element of a container.
Also called a @ref{23e4,,key} when subscripting a @ref{13d3,,mapping},
or an @ref{23e3,,index} when subscripting a @ref{716,,sequence}.
@anchor{glossary term-synchronization-primitive}@anchor{5990}
@geindex synchronization primitive

@item synchronization primitive

A basic building block for coordinating (synchronizing) the execution of
multiple threads to ensure @ref{5992,,thread-safe} access to shared resources.
Python's @ref{f3,,threading} module provides several synchronization primitives
including @ref{19f4,,Lock}, @ref{32e,,RLock},
@ref{136e,,Semaphore}, @ref{136d,,Condition},
@ref{1370,,Event}, and @ref{13fc,,Barrier}.  Additionally,
the @ref{bb,,queue} module provides multi-producer, multi-consumer queues
that are especially useful in multithreaded programs. These
primitives help prevent @ref{5985,,race conditions} and
coordinate thread execution.  See also @ref{598f,,lock}.
@anchor{glossary term-t-string}@anchor{59a6}
@geindex t-string

@item t-string@anchor{glossary term-t-strings}@anchor{59a7}
@geindex t-strings

@itemx t-strings

String literals prefixed with @code{t} or @code{T} are commonly called
"t-strings" which is short for
@ref{17fa,,template string literals}.
@anchor{glossary term-text-encoding}@anchor{25db}
@geindex text encoding

@item text encoding

A string in Python is a sequence of Unicode code points (in range
@code{U+0000}--@code{U+10FFFF}). To store or transfer a string, it needs to be
serialized as a sequence of bytes.

Serializing a string into a sequence of bytes is known as "encoding", and
recreating the string from the sequence of bytes is known as "decoding".

There are a variety of different text serialization
@ref{fb8,,codecs}, which are collectively referred to as
"text encodings".
@anchor{glossary term-text-file}@anchor{206d}
@geindex text file

@item text file

(テキストファイル) @ref{169,,str} オブジェクトを読み書きできる @ref{13db,,file object} です。
しばしば、テキストファイルは実際にバイト指向のデータストリームにアクセスし、 @ref{25db,,テキストエンコーディング} を自動的に行います。
テキストファイルの例は、 @ref{75f,,sys.stdin}, @ref{ccd,,sys.stdout}, @ref{112a,,io.StringIO} インスタンスなどをテキストモード (@code{'r'} or @code{'w'}) で開いたファイルです。

@ref{193,,bytes-like オブジェクト} を読み書きできるファイルオブジェクトについては、 @ref{206e,,バイナリファイル} も参照してください。
@anchor{glossary term-thread-state}@anchor{1846}
@geindex thread state

@item thread state

The information used by the @ref{905,,CPython} runtime to run in an OS thread.
For example, this includes the current exception, if any, and the
state of the bytecode interpreter.

Each thread state is bound to a single OS thread, but threads may have
many thread states available.  At most, one of them may be
@ref{4ed1,,attached} at once.

An @ref{4ed1,,attached thread state} is required to call most
of Python's C API, unless a function explicitly documents otherwise.
The bytecode interpreter only runs under an attached thread state.

Each thread state belongs to a single interpreter, but each interpreter
may have many thread states, including multiple for the same OS thread.
Thread states from multiple interpreters may be bound to the same
thread, but only one can be @ref{4ed1,,attached} in
that thread at any given moment.

See @ref{551f,,Thread State and the Global Interpreter Lock} for more
information.
@anchor{glossary term-thread-safe}@anchor{5992}
@geindex thread-safe

@item thread-safe

A module, function, or class that behaves correctly when used by multiple
threads concurrently.  Thread-safe code uses appropriate
@ref{5990,,synchronization primitives} like
@ref{598f,,locks} to protect shared mutable state, or is designed
to avoid shared mutable state entirely.  In the
@ref{1f4,,free-threaded} build, built-in types like
@ref{183,,dict}, @ref{24d,,list}, and @ref{184,,set} use internal locking
to make many operations thread-safe, although thread safety is not
necessarily guaranteed.  Code that is not thread-safe may experience
@ref{5985,,race conditions} and @ref{5986,,data races}
when used in multi-threaded programs.
@anchor{glossary term-token}@anchor{2288}
@geindex トークン

@item トークン

A small unit of source code, generated by the
@ref{2295,,lexical analyzer} (also called the `tokenizer').
Names, numbers, strings, operators,
newlines and similar are represented by tokens.

The @ref{101,,tokenize} module exposes Python's lexical analyzer.
The @ref{100,,token} module contains information on the various types
of tokens.
@anchor{glossary term-triple-quoted-string}@anchor{59a8}
@geindex triple-quoted string

@item triple-quoted string

(三重クォート文字列) 3つの連続したクォート記号(")かアポストロフィー(')で囲まれた文字列。通常の(一重)クォート文字列に比べて表現できる文字列に違いはありませんが、幾つかの理由で有用です。1つか2つの連続したクォート記号をエスケープ無しに書くことができますし、行継続文字(\)を使わなくても複数行にまたがることができるので、ドキュメンテーション文字列を書く時に特に便利です。
@anchor{glossary term-type}@anchor{1cfe}
@geindex type

@item type

The type of a Python object determines what kind of object it is; every
object has a type.  An object's type is accessible as its
@ref{16c6,,__class__} attribute or can be retrieved with
@code{type(obj)}.
@anchor{glossary term-type-alias}@anchor{66e}
@geindex type alias

@item type alias

(型エイリアス) 型の別名で、型を識別子に代入して作成します。

型エイリアスは @ref{23cb,,型ヒント} を単純化するのに有用です。例えば:

@example
def remove_gray_shades(
        colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
    pass
@end example

これは次のようにより読みやすくできます:

@example
Color = tuple[int, int, int]

def remove_gray_shades(colors: list[Color]) -> list[Color]:
    pass
@end example

機能の説明がある @ref{10a,,typing} と 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} を参照してください。
@anchor{glossary term-type-hint}@anchor{23cb}
@geindex type hint

@item type hint

(型ヒント) 変数、クラス属性、関数のパラメータや返り値の期待される型を指定する @ref{15c,,annotation} です。

Type hints are optional and are not enforced by Python but
they are useful to @ref{574,,static type checkers}.
They can also aid IDEs with code completion and refactoring.

グローバル変数、クラス属性、関数で、ローカル変数でないものの型ヒントは @ref{8c0,,typing.get_type_hints()} で取得できます。

機能の説明がある @ref{10a,,typing} と 
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} を参照してください。
@anchor{glossary term-universal-newlines}@anchor{f35}
@geindex universal newlines

@item universal newlines

テキストストリームの解釈法の一つで、以下のすべてを行末と認識します: Unix の行末規定 @code{'\n'}、Windows の規定 @code{'\r\n'}、古い Macintosh の規定 @code{'\r'}。利用法について詳しくは、 
@geindex Python Enhancement Proposals; PEP 278
PEP 278@footnote{https://peps.python.org/pep-0278/} と 
@geindex Python Enhancement Proposals; PEP 3116
PEP 3116@footnote{https://peps.python.org/pep-3116/} 、さらに @ref{2628,,bytes.splitlines()} も参照してください。
@anchor{glossary term-variable-annotation}@anchor{f51}
@geindex variable annotation

@item variable annotation

(変数アノテーション) 変数あるいはクラス属性の @ref{15c,,annotation} 。

変数あるいはクラス属性に注釈を付けたときは、代入部分は任意です:

@example
class C:
    field: 'annotation'
@end example

変数アノテーションは通常は @ref{23cb,,型ヒント} のために使われます: 例えば、この変数は @ref{19b,,int} の値を取ることを期待されています:

@example
count: int = 0
@end example

変数アノテーションの構文については @ref{250b,,注釈付き代入文 (annotated assignment statements)} 節で解説しています。

機能の説明がある @ref{2019,,function annotation},  
@geindex Python Enhancement Proposals; PEP 484
PEP 484@footnote{https://peps.python.org/pep-0484/} , 
@geindex Python Enhancement Proposals; PEP 526
PEP 526@footnote{https://peps.python.org/pep-0526/} を参照してください。また、アノテーションを利用するベストプラクティスとして @ref{9d9,,Annotations Best Practices} も参照してください。
@anchor{glossary term-virtual-environment}@anchor{20ee}
@geindex virtual environment

@item virtual environment

(仮想環境) 協調的に切り離された実行環境です。これにより Python ユーザとアプリケーションは同じシステム上で動いている他の Python アプリケーションの挙動に干渉することなく Python パッケージのインストールと更新を行うことができます。

@ref{117,,venv} を参照してください。
@anchor{glossary term-virtual-machine}@anchor{3a5b}
@geindex virtual machine

@item virtual machine

(仮想マシン) 完全にソフトウェアにより定義されたコンピュータ。 Python の仮想マシンは、バイトコードコンパイラが出力した @ref{4aa,,バイトコード} を実行します。
@anchor{glossary term-walrus-operator}@anchor{59a9}
@geindex walrus operator

@item walrus operator

A light-hearted way to refer to the @ref{24dd,,assignment expression} operator @code{:=} because it looks a bit like a
walrus if you turn your head.
@anchor{glossary term-Zen-of-Python}@anchor{59aa}
@geindex Zen of Python

@item Zen of Python

(Pythonの悟り) Python を理解し利用する上での導きとなる、Python の設計原則と哲学をリストにしたものです。対話プロンプトで "@code{import this}" とするとこのリストを読めます。
@end table

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node このドキュメントについて,バグへの対処,用語集<2>,Top
@anchor{about doc}@anchor{59ab}@anchor{about about-this-documentation}@anchor{59ac}@anchor{about translation-repo}@anchor{59ad}
@chapter このドキュメントについて


Pythonのドキュメントは、Sphinx@footnote{https://www.sphinx-doc.org/} を使って、reStructuredText@footnote{https://docutils.sourceforge.io/rst.html} のソースから生成されています。 Sphinx はもともとPythonのために作られ、現在は独立したプロジェクトとして保守されています。

@c In the online version of these documents, you can submit comments and suggest
@c changes directly on the documentation pages.

ドキュメントとそのツール群の開発は、Python 自身と同様に完全にボランティアの努力です。
もしあなたが貢献したいなら、どのようにすればよいかについて @ref{4f19,,バグへの対処} ページをご覧下さい。 新しいボランティアはいつでも歓迎です!
（訳注: 日本語訳の問題については、 GitHub 上の Issue Tracker@footnote{https://github.com/python-doc-ja/python-doc-ja/issues} で報告をお願いします。）

多大な感謝を:


@itemize *

@item 
Fred L. Drake, Jr., オリジナルの Python ドキュメントツールセットの作成者で、ドキュメントの多くを書きました。

@item 
Docutils@footnote{https://docutils.sourceforge.io/} プロジェクトは、 reStructuredText と Docutils ツールセットを作成しました。

@item 
Fredrik Lundh の Alternative Python Reference プロジェクトから Sphinx は多くのアイデアを得ました。
@end itemize

@menu
* Pythonドキュメントへの貢献者:: 

@end menu

@node Pythonドキュメントへの貢献者,,,このドキュメントについて
@anchor{about contributors-to-the-python-documentation}@anchor{59ae}
@section Pythonドキュメントへの貢献者


多くの方々が Python 言語、Python 標準ライブラリ、そして Python ドキュメンテーションに貢献してくれています。ソース配布物の Misc/ACKS@footnote{https://github.com/python/cpython/tree/3.14/Misc/ACKS} に、それら貢献してくれた人々を部分的にではありますがリストアップしてあります。

Python コミュニティからの情報提供と貢献がなければこの素晴らしいドキュメントは生まれませんでした -- ありがとう!

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node バグへの対処,Copyright,このドキュメントについて,Top
@anchor{bugs doc}@anchor{59af}@anchor{bugs dealing-with-bugs}@anchor{59b0}@anchor{bugs reporting-bugs}@anchor{4f19}@anchor{bugs translation-repo}@anchor{59b1}
@chapter バグへの対処


Python は安定性について高い評価を得た、成熟した言語です。この評価を守るために、開発者たちはあなたが見つけた Python の不備を知りたいと思っています。

It can be sometimes faster to fix bugs yourself and contribute patches to
Python as it streamlines the process and involves fewer people. Learn how to
@ref{59b2,,contribute}.

@menu
* ドキュメントの不備:: 
* Python の課題管理システムを使う:: 
* Python への貢献をはじめる:: 

@end menu

@node ドキュメントの不備,Python の課題管理システムを使う,,バグへの対処
@anchor{bugs documentation-bugs}@anchor{59b3}
@section ドキュメントの不備


If you find a bug in this documentation or would like to propose an improvement,
please submit a bug report on the @ref{557,,issue tracker}.  If you
have a suggestion on how to fix it, include that as well.

If the bug or suggested improvement concerns the translation of this
documentation, submit the report to the
translation’s repository@footnote{https://github.com/python/python-docs-ja} instead.

または  Documentation Discourse forum@footnote{https://discuss.python.org/c/documentation/26} でディスカッションを行うこともできます。

If you find a bug in the theme (HTML / CSS / JavaScript) of the
documentation, please submit a bug report on the python-doc-theme issue tracker@footnote{https://github.com/python/python-docs-theme}.


@subsubheading 参考



@table @asis

@item ドキュメントのバグ@footnote{https://github.com/python/cpython/issues?q=is%3Aissue+is%3Aopen+label%3Adocs}

Python issue tracker に出されたドキュメントバグのリスト。

@item イシュートラッカー@footnote{https://devguide.python.org/tracker/}

issue tracker への改善報告に関する作業過程の概観。

@item ドキュメントを手伝う@footnote{https://devguide.python.org/docquality/#helping-with-documentation}

Python ドキュメントへの貢献に興味がある個人へ向けた包括的なガイド。

@item ドキュメントの翻訳@footnote{https://devguide.python.org/documentation/translating/}

ドキュメントの翻訳とその連絡先の載った GitHub pages のリスト。
@end table


@node Python の課題管理システムを使う,Python への貢献をはじめる,ドキュメントの不備,バグへの対処
@anchor{bugs using-the-python-issue-tracker}@anchor{59b4}@anchor{bugs using-the-tracker}@anchor{557}
@section Python の課題管理システムを使う


Python 自体に関する問題は Githubのissue tracker (@indicateurl{https://github.com/python/cpython/issues}) で報告してください。このGithub issue trackerは、関連情報を入力して開発者に報告するための Web フォームを提供しています。

レポートを書くには、初めにその問題が既にレポートされていないか確認します。これにより、開発者の時間が無駄にならないだけでなく、あなたが、問題に対して為された対処について知ることもできます。次のリリースに向けて問題が修正されたのかもしれませんし、追加の情報が必要とされているのかもしれません（この場合は是非情報を提供してください）。確認のためにはページの上の検索ボックスを利用してください。

報告しようとしている問題がまだリストにない場合は、GitHub にログインしてください。GitHubのアカウントをまだお持ちでない場合は、「Sign up」リンクから新しいアカウントを作成してください。匿名でバグレポートを提出することはできません。

ログインした状態で、課題を送信することができます。トップバーの「New issue」ボタンをクリックして、新しい課題を報告してください。

報告のフォームには、「Title」と「Comment」の2つのフィールドがあります。

「Title」フィールドには、問題の `とても' 短い説明を（訳注: 英語で）入力してください。10語以内が望ましいです。

"Comment" フィールドで、あなたが期待した結果と実際の結果も含め、問題の詳細を説明してください。拡張モジュールが関与しているかどうかと、使用しているハードウェアとソフトウェアプラットフォームも (必要に応じてバージョン情報も) 必ず報告に含めてください。

各問題レポートは開発者によってレビューされ、問題を修正するために何が必要かを判断します。issueで何らかの行動があるたびに、最新情報を通知します。


@subsubheading 参考



@table @asis

@item How to Report Bugs Effectively@footnote{https://www.chiark.greenend.org.uk/~sgtatham/bugs.html}

有益なバグ報告について詳しく説明した記事です。どんな情報が、なぜ有益なのかを説明しています。

@item Bug Writing Guidelines@footnote{http://developer.mozilla.org/en/docs/Bug_writing_guidelines}

良いバグ報告を書くための情報です。この情報の一部はMozillaプロジェクト独自のものですが、一般的に良い習慣を解説しています。
@end table


@node Python への貢献をはじめる,,Python の課題管理システムを使う,バグへの対処
@anchor{bugs contributing-to-python}@anchor{59b2}@anchor{bugs getting-started-contributing-to-python-yourself}@anchor{59b5}
@section Python への貢献をはじめる


見つけたバグの報告だけでなく、修正パッチの提出も歓迎します。Python Developer's Guide@footnote{https://devguide.python.org/} には Python へのパッチの始め方について詳しい情報があります。疑問があれば、core-mentorship mailing list@footnote{https://mail.python.org/mailman3/lists/core-mentorship.python.org/} は Python の問題解決の過程に関するありとあらゆる疑問への答えを得ることが出来るフレンドリーな場所です。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Copyright,歴史とライセンス,バグへの対処,Top
@anchor{copyright doc}@anchor{59b6}@anchor{copyright copyright}@anchor{59b7}@anchor{copyright translation-repo}@anchor{59b8}
@chapter Copyright


Python and this documentation is:

Copyright © 2001 Python Software Foundation. All rights reserved.

Copyright © 2000 BeOpen.com. All rights reserved.

Copyright © 1995-2000 Corporation for National Research Initiatives. All rights
reserved.

Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.


__________________________________________________________________


ライセンスおよび許諾に関する完全な情報は、 @ref{59b9,,歴史とライセンス} を参照してください。

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node 歴史とライセンス,Pythonモジュール索引,Copyright,Top
@anchor{license doc}@anchor{59ba}@anchor{license history-and-license}@anchor{59b9}@anchor{license id1}@anchor{59bb}@anchor{license translation-repo}@anchor{59bc}
@chapter 歴史とライセンス


@menu
* Python の歴史:: 
* Terms and conditions for accessing or otherwise using Python:: 
* Licenses and Acknowledgements for Incorporated Software:: 

@end menu

@node Python の歴史,Terms and conditions for accessing or otherwise using Python,,歴史とライセンス
@anchor{license history-of-the-software}@anchor{59bd}
@section Python の歴史


Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see @indicateurl{https://www.cwi.nl}) in the Netherlands as a
successor of a language called ABC.  Guido remains Python's principal author,
although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for National
Research Initiatives (CNRI, see @indicateurl{https://www.cnri.reston.va.us}) in Reston,
Virginia where he released several versions of the software.

In May 2000, Guido and the Python core development team moved to BeOpen.com to
form the BeOpen PythonLabs team.  In October of the same year, the PythonLabs
team moved to Digital Creations, which became
Zope Corporation.  In 2001, the Python Software Foundation (PSF, see
@indicateurl{https://www.python.org/psf/}) was formed, a non-profit organization created
specifically to own Python-related Intellectual Property.  Zope Corporation was a
sponsoring member of the PSF.

All Python releases are Open Source (see @indicateurl{https://opensource.org} for the Open
Source Definition). Historically, most, but not all, Python releases have also
been GPL-compatible; the table below summarizes the various releases.


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

リリース

@tab

ベース

@tab

西暦年

@tab

権利

@tab

GPL-compatible? (1)

@item

0.9.0 - 1.2

@tab

n/a

@tab

1991-1995

@tab

CWI

@tab

yes

@item

1.3 - 1.5.2

@tab

1.2

@tab

1995-1999

@tab

CNRI

@tab

yes

@item

1.6

@tab

1.5.2

@tab

2000

@tab

CNRI

@tab

no

@item

2.0

@tab

1.6

@tab

2000

@tab

BeOpen.com

@tab

no

@item

1.6.1

@tab

1.6

@tab

2001

@tab

CNRI

@tab

yes (2)

@item

2.1

@tab

2.0+1.6.1

@tab

2001

@tab

PSF

@tab

no

@item

2.0.1

@tab

2.0+1.6.1

@tab

2001

@tab

PSF

@tab

yes

@item

2.1.1

@tab

2.1+2.0.1

@tab

2001

@tab

PSF

@tab

yes

@item

2.1.2

@tab

2.1.1

@tab

2002

@tab

PSF

@tab

yes

@item

2.1.3

@tab

2.1.2

@tab

2002

@tab

PSF

@tab

yes

@item

2.2 以降

@tab

2.1.1

@tab

2001-現在

@tab

PSF

@tab

yes

@end multitable


@cartouche
@quotation 注釈 

@enumerate 

@item 
GPL-compatible doesn't mean that we're distributing Python under the GPL.
All Python licenses, unlike the GPL, let you distribute a modified version
without making your changes open source. The GPL-compatible licenses make
it possible to combine Python with other software that is released under
the GPL; the others don't.

@item 
According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license
has a choice of law clause. According to CNRI, however, Stallman's lawyer has
told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL.
@end enumerate
@end quotation
@end cartouche

Guido の指示の下、これらのリリースを可能にしてくださった多くのボランティアのみなさんに感謝します。

@node Terms and conditions for accessing or otherwise using Python,Licenses and Acknowledgements for Incorporated Software,Python の歴史,歴史とライセンス
@anchor{license terms-and-conditions-for-accessing-or-otherwise-using-python}@anchor{59be}
@section Terms and conditions for accessing or otherwise using Python


Python software and documentation are licensed under the
Python Software Foundation License Version 2.

Starting with Python 3.8.6, examples, recipes, and other code in
the documentation are dual licensed under the PSF License Version 2
and the @ref{59bf,,Zero-Clause BSD license}.

Some software incorporated into Python is under different licenses.
The licenses are listed with code falling under that license.
See @ref{59c0,,Licenses and Acknowledgements for Incorporated Software} for an incomplete list of these licenses.

@menu
* PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2:: 
* BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0: BEOPEN COM LICENSE AGREEMENT FOR PYTHON 2 0. 
* CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1: CNRI LICENSE AGREEMENT FOR PYTHON 1 6 1. 
* CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2: CWI LICENSE AGREEMENT FOR PYTHON 0 9 0 THROUGH 1 2. 
* ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION:: 

@end menu

@node PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2,BEOPEN COM LICENSE AGREEMENT FOR PYTHON 2 0,,Terms and conditions for accessing or otherwise using Python
@anchor{license psf-license}@anchor{59c1}@anchor{license python-software-foundation-license-version-2}@anchor{59c2}
@subsection PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2


@example
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") 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 alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python 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 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.

4. PSF is making Python 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 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, 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, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.
@end example

@node BEOPEN COM LICENSE AGREEMENT FOR PYTHON 2 0,CNRI LICENSE AGREEMENT FOR PYTHON 1 6 1,PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2,Terms and conditions for accessing or otherwise using Python
@anchor{license beopen-com-license-agreement-for-python-2-0}@anchor{59c3}
@subsection BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0


BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1

@example
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
   160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
   ("Licensee") accessing and otherwise using this software in source or binary
   form and its associated documentation ("the Software").

2. Subject to the terms and conditions of this BeOpen Python License Agreement,
   BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
   to reproduce, analyze, test, perform and/or display publicly, prepare derivative
   works, distribute, and otherwise use the Software alone or in any derivative
   version, provided, however, that the BeOpen Python License is retained in the
   Software, alone or in any derivative version prepared by Licensee.

3. BeOpen is making the Software available to Licensee on an "AS IS" basis.
   BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
   MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
   ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all respects
   by the law of the State of California, excluding conflict of law provisions.
   Nothing in this License Agreement shall be deemed to create any relationship of
   agency, partnership, or joint venture between BeOpen and Licensee.  This License
   Agreement does not grant permission to use BeOpen trademarks or trade names in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.  As an exception, the "BeOpen Python" logos available at
   @indicateurl{http://www.pythonlabs.com/logos.html} may be used according to the permissions
   granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be
   bound by the terms and conditions of this License Agreement.
@end example

@node CNRI LICENSE AGREEMENT FOR PYTHON 1 6 1,CWI LICENSE AGREEMENT FOR PYTHON 0 9 0 THROUGH 1 2,BEOPEN COM LICENSE AGREEMENT FOR PYTHON 2 0,Terms and conditions for accessing or otherwise using Python
@anchor{license cnri-license-agreement-for-python-1-6-1}@anchor{59c4}
@subsection CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1


@example
1. This LICENSE AGREEMENT is between the Corporation for National Research
   Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
   ("CNRI"), and the Individual or Organization ("Licensee") accessing and
   otherwise using Python 1.6.1 software in source or binary form and its
   associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
   provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
   i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
   Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
   prepared by Licensee.  Alternately, in lieu of CNRI's License Agreement,
   Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
   is made available subject to the terms and conditions in CNRI's License
   Agreement.  This Agreement together with Python 1.6.1 may be located on the
   internet using the following unique, persistent identifier (known as a handle):
   1895.22/1013.  This Agreement may also be obtained from a proxy server on the
   internet using the following URL: @indicateurl{http://hdl.handle.net/1895.22/1013}".

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
   work available to others as provided herein, then Licensee hereby agrees to
   include in any such work a brief summary of the changes made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis.  CNRI
   MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
   BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
   OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
   PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. This License Agreement shall be governed by the federal intellectual property
   law of the United States, including without limitation the federal copyright
   law, and, to the extent such U.S. federal law does not apply, by the law of the
   Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
   Notwithstanding the foregoing, with regard to derivative works based on Python
   1.6.1 that incorporate non-separable material that was previously distributed
   under the GNU General Public License (GPL), the law of the Commonwealth of
   Virginia shall govern this License Agreement only as to issues arising under or
   with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
   this License Agreement shall be deemed to create any relationship of agency,
   partnership, or joint venture between CNRI and Licensee.  This License Agreement
   does not grant permission to use CNRI trademarks or trade name in a trademark
   sense to endorse or promote products or services of Licensee, or any third
   party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing
   or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
   conditions of this License Agreement.
@end example

@node CWI LICENSE AGREEMENT FOR PYTHON 0 9 0 THROUGH 1 2,ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION,CNRI LICENSE AGREEMENT FOR PYTHON 1 6 1,Terms and conditions for accessing or otherwise using Python
@anchor{license cwi-license-agreement-for-python-0-9-0-through-1-2}@anchor{59c5}
@subsection CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2


@example
Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
Netherlands.  All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
@end example

@node ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION,,CWI LICENSE AGREEMENT FOR PYTHON 0 9 0 THROUGH 1 2,Terms and conditions for accessing or otherwise using Python
@anchor{license bsd0}@anchor{59bf}@anchor{license zero-clause-bsd-license-for-code-in-the-python-documentation}@anchor{59c6}
@subsection ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION


@example
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
@end example

@node Licenses and Acknowledgements for Incorporated Software,,Terms and conditions for accessing or otherwise using Python,歴史とライセンス
@anchor{license licenses-and-acknowledgements-for-incorporated-software}@anchor{59c7}@anchor{license otherlicenses}@anchor{59c0}
@section Licenses and Acknowledgements for Incorporated Software


This section is an incomplete, but growing list of licenses and acknowledgements
for third-party software incorporated in the Python distribution.

@menu
* Mersenne Twister:: 
* ソケット: ソケット<2>. 
* Asynchronous socket services:: 
* Cookie management:: 
* Execution tracing:: 
* UUencode and UUdecode functions:: 
* XML Remote Procedure Calls:: 
* test_epoll:: 
* Select kqueue:: 
* SipHash24:: 
* strtod と dtoa:: 
* OpenSSL: OpenSSL<2>. 
* expat:: 
* libffi:: 
* zlib: zlib<4>. 
* cfuhash:: 
* libmpdec:: 
* W3C C14N test suite:: 
* mimalloc:: 
* asyncio: asyncio<15>. 
* Global Unbounded Sequences (GUS): Global Unbounded Sequences GUS. 
* Zstandard bindings:: 

@end menu

@node Mersenne Twister,ソケット<2>,,Licenses and Acknowledgements for Incorporated Software
@anchor{license mersenne-twister}@anchor{59c8}
@subsection Mersenne Twister


The @code{_random} C extension underlying the @ref{bd,,random} module
includes code based on a download from
@indicateurl{http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html}. The following are
the verbatim comments from the original code:

@example
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

 3. The names of its contributors may not be used to endorse or promote
    products derived from this software without specific prior written
    permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @@ math.sci.hiroshima-u.ac.jp (remove space)
@end example

@node ソケット<2>,Asynchronous socket services,Mersenne Twister,Licenses and Acknowledgements for Incorporated Software
@anchor{license sockets}@anchor{59c9}
@subsection ソケット


The @ref{d1,,socket} module uses the functions, @code{getaddrinfo()}, and
@code{getnameinfo()}, which are coded in separate source files from the WIDE
Project, @indicateurl{https://www.wide.ad.jp/}.

@example
Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "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.
@end example

@node Asynchronous socket services,Cookie management,ソケット<2>,Licenses and Acknowledgements for Incorporated Software
@anchor{license asynchronous-socket-services}@anchor{59ca}
@subsection Asynchronous socket services


The @code{test.support.asynchat} and @code{test.support.asyncore}
modules contain the following notice:

@example
Copyright 1996 by Sam Rushing

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@end example

@node Cookie management,Execution tracing,Asynchronous socket services,Licenses and Acknowledgements for Incorporated Software
@anchor{license cookie-management}@anchor{59cb}
@subsection Cookie management


The @ref{75,,http.cookies} module contains the following notice:

@example
Copyright 2000 by Timothy O'Malley <timo@@alum.mit.edu>

               All Rights Reserved

Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Timothy O'Malley  not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
@end example

@node Execution tracing,UUencode and UUdecode functions,Cookie management,Licenses and Acknowledgements for Incorporated Software
@anchor{license execution-tracing}@anchor{59cc}
@subsection Execution tracing


The @ref{103,,trace} module contains the following notice:

@example
portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
err...  reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O'Whielacronx
http://zooko.com/
mailto:zooko@@zooko.com

Copyright 2000, Mojam Media, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1999, Bioreason, Inc., all rights reserved.
Author: Andrew Dalke

Copyright 1995-1997, Automatrix, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.


Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
@end example

@node UUencode and UUdecode functions,XML Remote Procedure Calls,Execution tracing,Licenses and Acknowledgements for Incorporated Software
@anchor{license uuencode-and-uudecode-functions}@anchor{59cd}
@subsection UUencode and UUdecode functions


The @code{uu} codec contains the following notice:

@example
Copyright 1994 by Lance Ellinghouse
Cathedral City, California Republic, United States of America.
                       All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Modified by Jack Jansen, CWI, July 1995:
- Use binascii module to do the actual line-by-line conversion
  between ascii and binary. This results in a 1000-fold speedup. The C
  version is still 5 times faster, though.
- Arguments more compliant with Python standard
@end example

@node XML Remote Procedure Calls,test_epoll,UUencode and UUdecode functions,Licenses and Acknowledgements for Incorporated Software
@anchor{license xml-remote-procedure-calls}@anchor{59ce}
@subsection XML Remote Procedure Calls


The @ref{134,,xmlrpc.client} module contains the following notice:

@example
    The XML-RPC client interface is

Copyright (c) 1999-2002 by Secret Labs AB
Copyright (c) 1999-2002 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and
its associated documentation for any purpose and without fee is
hereby granted, provided that the above copyright notice appears in
all copies, and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
@end example

@node test_epoll,Select kqueue,XML Remote Procedure Calls,Licenses and Acknowledgements for Incorporated Software
@anchor{license test-epoll}@anchor{59cf}
@subsection test_epoll


The @code{test.test_epoll} module contains the following notice:

@example
Copyright (c) 2001-2006 Twisted Matrix Laboratories.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@end example

@node Select kqueue,SipHash24,test_epoll,Licenses and Acknowledgements for Incorporated Software
@anchor{license select-kqueue}@anchor{59d0}
@subsection Select kqueue


@ref{c6,,select} モジュールは kqueue インターフェースについての次の告知を含んでいます:

@example
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
@end example

@node SipHash24,strtod と dtoa,Select kqueue,Licenses and Acknowledgements for Incorporated Software
@anchor{license siphash24}@anchor{59d1}
@subsection SipHash24


The file @code{Python/pyhash.c} contains Marek Majkowski' implementation of
Dan Bernstein's SipHash24 algorithm. It contains the following note:

@example
<MIT License>
Copyright (c) 2013  Marek Majkowski <marek@@popcount.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>

Original location:
   https://github.com/majek/csiphash/

Solution inspired by code from:
   Samuel Neves (supercop/crypto_auth/siphash24/little)
   djb (supercop/crypto_auth/siphash24/little2)
   Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)
@end example

@node strtod と dtoa,OpenSSL<2>,SipHash24,Licenses and Acknowledgements for Incorporated Software
@anchor{license strtod-and-dtoa}@anchor{59d2}
@subsection strtod と dtoa


The file @code{Python/dtoa.c}, which supplies C functions dtoa and
strtod for conversion of C doubles to and from strings, is derived
from the file of the same name by David M. Gay, currently available
from @indicateurl{https://web.archive.org/web/20220517033456/http://www.netlib.org/fp/dtoa.c}.
The original file, as retrieved on March 16, 2009, contains the following
copyright and licensing notice:

@example
/****************************************************************
 *
 * The author of this software is David M. Gay.
 *
 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose without fee is hereby granted, provided that this entire notice
 * is included in all copies of any software which is or includes a copy
 * or modification of this software and in all copies of the supporting
 * documentation for such software.
 *
 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
 *
 ***************************************************************/
@end example

@node OpenSSL<2>,expat,strtod と dtoa,Licenses and Acknowledgements for Incorporated Software
@anchor{license openssl}@anchor{59d3}
@subsection OpenSSL


The modules @ref{6c,,hashlib}, @ref{b2,,posix} and @ref{d5,,ssl} use
the OpenSSL library for added performance if made available by the
operating system. Additionally, the Windows and macOS installers for
Python may include a copy of the OpenSSL libraries, so we include a copy
of the OpenSSL license here. For the OpenSSL 3.0 release,
and later releases derived from that, the Apache License v2 applies:

@example
                              Apache License
                        Version 2.0, January 2004
                     https://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

   "License" shall mean the terms and conditions for use, reproduction,
   and distribution as defined by Sections 1 through 9 of this document.

   "Licensor" shall mean the copyright owner or entity authorized by
   the copyright owner that is granting the License.

   "Legal Entity" shall mean the union of the acting entity and all
   other entities that control, are controlled by, or are under common
   control with that entity. For the purposes of this definition,
   "control" means (i) the power, direct or indirect, to cause the
   direction or management of such entity, whether by contract or
   otherwise, or (ii) ownership of fifty percent (50%) or more of the
   outstanding shares, or (iii) beneficial ownership of such entity.

   "You" (or "Your") shall mean an individual or Legal Entity
   exercising permissions granted by this License.

   "Source" form shall mean the preferred form for making modifications,
   including but not limited to software source code, documentation
   source, and configuration files.

   "Object" form shall mean any form resulting from mechanical
   transformation or translation of a Source form, including but
   not limited to compiled object code, generated documentation,
   and conversions to other media types.

   "Work" shall mean the work of authorship, whether in Source or
   Object form, made available under the License, as indicated by a
   copyright notice that is included in or attached to the work
   (an example is provided in the Appendix below).

   "Derivative Works" shall mean any work, whether in Source or Object
   form, that is based on (or derived from) the Work and for which the
   editorial revisions, annotations, elaborations, or other modifications
   represent, as a whole, an original work of authorship. For the purposes
   of this License, Derivative Works shall not include works that remain
   separable from, or merely link (or bind by name) to the interfaces of,
   the Work and Derivative Works thereof.

   "Contribution" shall mean any work of authorship, including
   the original version of the Work and any modifications or additions
   to that Work or Derivative Works thereof, that is intentionally
   submitted to Licensor for inclusion in the Work by the copyright owner
   or by an individual or Legal Entity authorized to submit on behalf of
   the copyright owner. For the purposes of this definition, "submitted"
   means any form of electronic, verbal, or written communication sent
   to the Licensor or its representatives, including but not limited to
   communication on electronic mailing lists, source code control systems,
   and issue tracking systems that are managed by, or on behalf of, the
   Licensor for the purpose of discussing and improving the Work, but
   excluding communication that is conspicuously marked or otherwise
   designated in writing by the copyright owner as "Not a Contribution."

   "Contributor" shall mean Licensor and any individual or Legal Entity
   on behalf of whom a Contribution has been received by Licensor and
   subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   copyright license to reproduce, prepare Derivative Works of,
   publicly display, publicly perform, sublicense, and distribute the
   Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   (except as stated in this section) patent license to make, have made,
   use, offer to sell, sell, import, and otherwise transfer the Work,
   where such license applies only to those patent claims licensable
   by such Contributor that are necessarily infringed by their
   Contribution(s) alone or by combination of their Contribution(s)
   with the Work to which such Contribution(s) was submitted. If You
   institute patent litigation against any entity (including a
   cross-claim or counterclaim in a lawsuit) alleging that the Work
   or a Contribution incorporated within the Work constitutes direct
   or contributory patent infringement, then any patent licenses
   granted to You under this License for that Work shall terminate
   as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
   Work or Derivative Works thereof in any medium, with or without
   modifications, and in Source or Object form, provided that You
   meet the following conditions:

   (a) You must give any other recipients of the Work or
       Derivative Works a copy of this License; and

   (b) You must cause any modified files to carry prominent notices
       stating that You changed the files; and

   (c) You must retain, in the Source form of any Derivative Works
       that You distribute, all copyright, patent, trademark, and
       attribution notices from the Source form of the Work,
       excluding those notices that do not pertain to any part of
       the Derivative Works; and

   (d) If the Work includes a "NOTICE" text file as part of its
       distribution, then any Derivative Works that You distribute must
       include a readable copy of the attribution notices contained
       within such NOTICE file, excluding those notices that do not
       pertain to any part of the Derivative Works, in at least one
       of the following places: within a NOTICE text file distributed
       as part of the Derivative Works; within the Source form or
       documentation, if provided along with the Derivative Works; or,
       within a display generated by the Derivative Works, if and
       wherever such third-party notices normally appear. The contents
       of the NOTICE file are for informational purposes only and
       do not modify the License. You may add Your own attribution
       notices within Derivative Works that You distribute, alongside
       or as an addendum to the NOTICE text from the Work, provided
       that such additional attribution notices cannot be construed
       as modifying the License.

   You may add Your own copyright statement to Your modifications and
   may provide additional or different license terms and conditions
   for use, reproduction, or distribution of Your modifications, or
   for any such Derivative Works as a whole, provided Your use,
   reproduction, and distribution of the Work otherwise complies with
   the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
   any Contribution intentionally submitted for inclusion in the Work
   by You to the Licensor shall be under the terms and conditions of
   this License, without any additional terms or conditions.
   Notwithstanding the above, nothing herein shall supersede or modify
   the terms of any separate license agreement you may have executed
   with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor,
   except as required for reasonable and customary use in describing the
   origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
   agreed to in writing, Licensor provides the Work (and each
   Contributor provides its Contributions) on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied, including, without limitation, any warranties or conditions
   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
   PARTICULAR PURPOSE. You are solely responsible for determining the
   appropriateness of using or redistributing the Work and assume any
   risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
   whether in tort (including negligence), contract, or otherwise,
   unless required by applicable law (such as deliberate and grossly
   negligent acts) or agreed to in writing, shall any Contributor be
   liable to You for damages, including any direct, indirect, special,
   incidental, or consequential damages of any character arising as a
   result of this License or out of the use or inability to use the
   Work (including but not limited to damages for loss of goodwill,
   work stoppage, computer failure or malfunction, or any and all
   other commercial damages or losses), even if such Contributor
   has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
   the Work or Derivative Works thereof, You may choose to offer,
   and charge a fee for, acceptance of support, warranty, indemnity,
   or other liability obligations and/or rights consistent with this
   License. However, in accepting such obligations, You may act only
   on Your own behalf and on Your sole responsibility, not on behalf
   of any other Contributor, and only if You agree to indemnify,
   defend, and hold each Contributor harmless for any liability
   incurred by, or claims asserted against, such Contributor by reason
   of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS
@end example

@node expat,libffi,OpenSSL<2>,Licenses and Acknowledgements for Incorporated Software
@anchor{license expat}@anchor{59d4}
@subsection expat


The @ref{12c,,pyexpat} extension is built using an included copy of the expat
sources unless the build is configured @code{--with-system-expat}:

@example
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
                               and Clark Cooper

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@end example

@node libffi,zlib<4>,expat,Licenses and Acknowledgements for Incorporated Software
@anchor{license libffi}@anchor{59d5}
@subsection libffi


The @code{_ctypes} C extension underlying the @ref{2e,,ctypes} module
is built using an included copy of the libffi
sources unless the build is configured @code{--with-system-libffi}:

@example
Copyright (c) 1996-2008  Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@end example

@node zlib<4>,cfuhash,libffi,Licenses and Acknowledgements for Incorporated Software
@anchor{license zlib}@anchor{59d6}
@subsection zlib


The @ref{139,,zlib} extension is built using an included copy of the zlib
sources if the zlib version found on the system is too old to be
used for the build:

@example
Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.

Jean-loup Gailly        Mark Adler
jloup@@gzip.org          madler@@alumni.caltech.edu
@end example

@node cfuhash,libmpdec,zlib<4>,Licenses and Acknowledgements for Incorporated Software
@anchor{license cfuhash}@anchor{59d7}
@subsection cfuhash


The implementation of the hash table used by the @ref{105,,tracemalloc} で使用しているハッシュテーブルの実装は、cfuhashプロジェクトのものに基づきます:

@example
Copyright (c) 2005 Don Owens
All rights reserved.

This code is released under the BSD license:

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.

  * Neither the name of the author nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
@end example

@node libmpdec,W3C C14N test suite,cfuhash,Licenses and Acknowledgements for Incorporated Software
@anchor{license libmpdec}@anchor{59d8}
@subsection libmpdec


The @code{_decimal} C extension underlying the @ref{3a,,decimal} module
is built using an included copy of the libmpdec
library unless the build is configured @code{--with-system-libmpdec}:

@example
Copyright (c) 2008-2020 Stefan Krah. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
@end example

@node W3C C14N test suite,mimalloc,libmpdec,Licenses and Acknowledgements for Incorporated Software
@anchor{license w3c-c14n-test-suite}@anchor{59d9}
@subsection W3C C14N test suite


The C14N 2.0 test suite in the @ref{e8,,test} package
(@code{Lib/test/xmltestdata/c14n-20/}) was retrieved from the W3C website at
@indicateurl{https://www.w3.org/TR/xml-c14n2-testcases/} and is distributed under the
3-clause BSD license:

@example
Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

* Redistributions of works must retain the original copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of the W3C nor the names of its contributors may be
  used to endorse or promote products derived from this work without
  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@end example

@node mimalloc,asyncio<15>,W3C C14N test suite,Licenses and Acknowledgements for Incorporated Software
@anchor{license mimalloc}@anchor{59da}@anchor{license mimalloc-license}@anchor{656}
@subsection mimalloc


MIT License:

@example
Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@end example

@node asyncio<15>,Global Unbounded Sequences GUS,mimalloc,Licenses and Acknowledgements for Incorporated Software
@anchor{license asyncio}@anchor{59db}
@subsection asyncio


Parts of the @ref{b,,asyncio} module are incorporated from
uvloop 0.16@footnote{https://github.com/MagicStack/uvloop/tree/v0.16.0},
which is distributed under the MIT license:

@example
Copyright (c) 2015-2021 MagicStack Inc.  http://magic.io

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@end example

@node Global Unbounded Sequences GUS,Zstandard bindings,asyncio<15>,Licenses and Acknowledgements for Incorporated Software
@anchor{license global-unbounded-sequences-gus}@anchor{59dc}
@subsection Global Unbounded Sequences (GUS)


The file @code{Python/qsbr.c} is adapted from FreeBSD's "Global Unbounded
Sequences" safe memory reclamation scheme in
subr_smr.c@footnote{https://github.com/freebsd/freebsd-src/blob/main/sys/kern/subr_smr.c}.
The file is distributed under the 2-Clause BSD License:

@example
Copyright (c) 2019,2020 Jeffrey Roberson <jeff@@FreeBSD.org>

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 unmodified, 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 "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 BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@end example

@node Zstandard bindings,,Global Unbounded Sequences GUS,Licenses and Acknowledgements for Incorporated Software
@anchor{license zstandard-bindings}@anchor{59dd}
@subsection Zstandard bindings


Zstandard bindings in @code{Modules/_zstd} and @code{Lib/compression/zstd}
are based on code from the
pyzstd library@footnote{https://github.com/Rogdham/pyzstd/}, copyright Ma Lin and
contributors. The pyzstd code is distributed under the 3-Clause BSD License:

@example
Copyright (c) 2020-present, Ma Lin and contributors.
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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@end example

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@c Apparently this how you hack together a formatted link:
@c (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)

@node Pythonモジュール索引,索引,歴史とライセンス,Top
@unnumbered Pythonモジュール索引


@menu
* __future__: 0. Future statement definitions
* __main__: 1. The environment where top-level code is run. Covers
                        command-line interfaces@comma{} import-time
                        behavior@comma{} and `@w{`}__name__ ==
                        '__main__'`@w{`}.
* _thread: 2. Low-level threading API.
* _tkinter: 3. A binary module that contains the low-level interface
                        to Tcl/Tk.
* abc: 4. Abstract base classes according to :pep:`3119`.
* aifc: 5. Removed in 3.13.
* annotationlib: 6. Functionality for introspecting annotations
* argparse: 7. Command-line option and argument parsing library.
* array: 8. Space efficient arrays of uniformly typed numeric
                        values.
* ast: 9. Abstract Syntax Tree classes and manipulation.
* asynchat: a. Removed in 3.12.
* asyncio: b. Asynchronous I/O.
* asyncore: c. Removed in 3.12.
* atexit: d. Register and execute cleanup functions.
* audioop: e. Removed in 3.13.
* base64: f. RFC 4648: Base16@comma{} Base32@comma{} Base64 Data
                        Encodings; Base85 and Ascii85
* bdb: 10. Debugger framework.
* binascii: 11. Tools for converting between binary and various ASCII-
                        encoded binary representations.
* bisect: 12. Array bisection algorithms for binary searching.
* builtins: 13. The module that provides the built-in namespace.
* bz2: 14. Interfaces for bzip2 compression and decompression.
* calendar: 15. Functions for working with calendars@comma{} including
                        some emulation of the Unix cal program.
* cgi: 16. Removed in 3.13.
* cgitb: 17. Removed in 3.13.
* chunk: 18. Removed in 3.13.
* cmath: 19. Mathematical functions for complex numbers.
* cmd: 1a. Build line-oriented command interpreters.
* code: 1b. Facilities to implement read-eval-print loops.
* codecs: 1c. Encode and decode data and streams.
* codeop: 1d. Compile (possibly incomplete) Python code.
* collections: 1e. Container datatypes
* collections.abc: 1f. Abstract base classes for containers
* colorsys: 20. Conversion functions between RGB and other color
                        systems.
* compileall: 21. Tools for byte-compiling all Python source files in a
                        directory tree.
* compression: 22. 
* compression.zstd: 23. Low-level interface to compression and decompression
                        routines in the zstd library.
* concurrent.futures: 24. Execute computations concurrently using threads or
                        processes.
* concurrent.interpreters: 25. Multiple interpreters in the same process
* configparser: 26. Configuration file parser.
* contextlib: 27. Utilities for with-statement contexts.
* contextvars: 28. Context Variables
* copy: 29. Shallow and deep copy operations.
* copyreg: 2a. Register pickle support functions.
* cProfile: 2b. 
* crypt: 2c. Removed in 3.13.
* csv: 2d. Write and read tabular data to and from delimited
                        files.
* ctypes: 2e. A foreign function library for Python.
* curses: 2f. An interface to the curses library@comma{} providing
                        portable terminal handling.
* curses.ascii: 30. Constants and set-membership functions for ASCII
                        characters.
* curses.panel: 31. A panel stack extension that adds depth to curses
                        windows.
* curses.textpad: 32. Emacs-like input editing in a curses window.
* dataclasses: 33. Generate special methods on user-defined classes.
* datetime: 34. Basic date and time types.
* dbm: 35. Interfaces to various Unix "database" formats.
* dbm.dumb: 36. Portable implementation of the simple DBM interface.
* dbm.gnu: 37. GNU database manager
* dbm.ndbm: 38. The New Database Manager
* dbm.sqlite3: 39. SQLite backend for dbm
* decimal: 3a. Implementation of the General Decimal Arithmetic
                        Specification.
* difflib: 3b. Helpers for computing differences between objects.
* dis: 3c. Disassembler for Python bytecode.
* distutils: 3d. Removed in 3.12.
* doctest: 3e. Test pieces of code within docstrings.
* email: 3f. Package supporting the parsing@comma{}
                        manipulating@comma{} and generating email messages.
* email.charset: 40. Character Sets
* email.contentmanager: 41. Storing and Retrieving Content from MIME Parts
* email.encoders: 42. Encoders for email message payloads.
* email.errors: 43. The exception classes used by the email package.
* email.generator: 44. Generate flat text email messages from a message
                        structure.
* email.header: 45. Representing non-ASCII headers
* email.headerregistry: 46. Automatic Parsing of headers based on the field name
* email.iterators: 47. Iterate over a message object tree.
* email.message: 48. The base class representing email messages.
* email.mime: 49. Build MIME messages.
* email.mime.application: 4a. 
* email.mime.audio: 4b. 
* email.mime.base: 4c. 
* email.mime.image: 4d. 
* email.mime.message: 4e. 
* email.mime.multipart: 4f. 
* email.mime.nonmultipart: 50. 
* email.mime.text: 51. 
* email.parser: 52. Parse flat text email messages to produce a message
                        object structure.
* email.policy: 53. Controlling the parsing and generating of messages
* email.utils: 54. Miscellaneous email package utilities.
* encodings: 55. Encodings package
* encodings.idna: 56. Internationalized Domain Names implementation
* encodings.mbcs: 57. Windows ANSI codepage
* encodings.utf_8_sig: 58. UTF-8 codec with BOM signature
* ensurepip: 59. Bootstrapping the "pip" installer into an existing
                        Python installation or virtual environment.
* enum: 5a. Implementation of an enumeration class.
* errno: 5b. Standard errno system symbols.
* faulthandler: 5c. Dump the Python traceback.
* fcntl: 5d. The fcntl() and ioctl() system calls.
* filecmp: 5e. Compare files efficiently.
* fileinput: 5f. Loop over standard input or a list of files.
* fnmatch: 60. Unix shell style filename pattern matching.
* fractions: 61. Rational numbers.
* ftplib: 62. FTP protocol client (requires sockets).
* functools: 63. Higher-order functions and operations on callable
                        objects.
* gc: 64. Interface to the cycle-detecting garbage collector.
* getopt: 65. Portable parser for command line options; support both
                        short and long option names.
* getpass: 66. Portable reading of passwords and retrieval of the
                        userid.
* gettext: 67. Multilingual internationalization services.
* glob: 68. Unix shell style pathname pattern expansion.
* graphlib: 69. Functionality to operate with graph-like structures
* grp: 6a. The group database (getgrnam() and friends).
* gzip: 6b. Interfaces for gzip compression and decompression
                        using file objects.
* hashlib: 6c. Secure hash and message digest algorithms.
* heapq: 6d. Heap queue algorithm (a.k.a. priority queue).
* hmac: 6e. Keyed-Hashing for Message Authentication (HMAC)
                        implementation
* html: 6f. Helpers for manipulating HTML.
* html.entities: 70. Definitions of HTML general entities.
* html.parser: 71. A simple parser that can handle HTML and XHTML.
* http: 72. HTTP status codes and messages
* http.client: 73. HTTP and HTTPS protocol client (requires sockets).
* http.cookiejar: 74. Classes for automatic handling of HTTP cookies.
* http.cookies: 75. Support for HTTP state management (cookies).
* http.server: 76. HTTP server and request handlers.
* idlelib: 77. Implementation package for the IDLE shell/editor.
* imaplib: 78. IMAP4 protocol client (requires sockets).
* imghdr: 79. Removed in 3.13.
* imp: 7a. Removed in 3.12.
* importlib: 7b. The implementation of the import machinery.
* importlib.abc: 7c. Abstract base classes related to import
* importlib.machinery: 7d. Importers and path hooks
* importlib.metadata: 7e. Accessing package metadata
* importlib.resources: 7f. Package resource reading@comma{} opening@comma{} and
                        access
* importlib.resources.abc: 80. Abstract base classes for resources
* importlib.util: 81. Utility code for importers
* inspect: 82. Extract information and source code from live objects.
* io: 83. Core tools for working with streams.
* ipaddress: 84. IPv4/IPv6 manipulation library.
* itertools: 85. Functions creating iterators for efficient looping.
* json: 86. Encode and decode the JSON format.
* json.tool: 87. A command-line interface to validate and pretty-print
                        JSON.
* keyword: 88. Test whether a string is a keyword in Python.
* linecache: 89. Provides random access to individual lines from text
                        files.
* locale: 8a. Internationalization services.
* logging: 8b. Flexible event logging system for applications.
* logging.config: 8c. Configuration of the logging module.
* logging.handlers: 8d. Handlers for the logging module.
* lzma: 8e. A Python wrapper for the liblzma compression library.
* mailbox: 8f. Manipulate mailboxes in various formats
* mailcap: 90. Removed in 3.13.
* marshal: 91. Convert Python objects to streams of bytes and back
                        (with different constraints).
* math: 92. Mathematical functions (sin() etc.).
* mimetypes: 93. Mapping of filename extensions to MIME types.
* mmap: 94. Interface to memory-mapped files for Unix and Windows.
* modulefinder: 95. Find modules used by a script.
* msilib: 96. Removed in 3.13.
* msvcrt: 97. Miscellaneous useful routines from the MS VC++
                        runtime.
* multiprocessing: 98. Process-based parallelism.
* multiprocessing.connection: 99. API for dealing with sockets.
* multiprocessing.dummy: 9a. Dumb wrapper around threading.
* multiprocessing.managers: 9b. Share data between process with shared objects.
* multiprocessing.pool: 9c. Create pools of processes.
* multiprocessing.shared_memory: 9d. Provides shared memory for direct access
                                 across processes.
* multiprocessing.sharedctypes: 9e. Allocate ctypes objects from shared memory.
* netrc: 9f. Loading of .netrc files.
* nis: a0. Removed in 3.13.
* nntplib: a1. Removed in 3.13.
* numbers: a2. Numeric abstract base classes (Complex@comma{}
                        Real@comma{} Integral@comma{} etc.).
* operator: a3. Functions corresponding to the standard operators.
* optparse: a4. Command-line option parsing library.
* os: a5. Miscellaneous operating system interfaces.
* os.path: a6. Operations on pathnames.
* ossaudiodev: a7. Removed in 3.13.
* pathlib: a8. Object-oriented filesystem paths
* pathlib.types: a9. pathlib types for static type checking
* pdb: aa. The Python debugger for interactive interpreters.
* pickle: ab. Convert Python objects to streams of bytes and back.
* pickletools: ac. Contains extensive comments about the pickle protocols
                        and pickle-machine opcodes@comma{} as well as some
                        useful functions.
* pipes: ad. Removed in 3.13.
* pkgutil: ae. Utilities for the import system.
* platform: af. Retrieves as much platform identifying data as
                        possible.
* plistlib: b0. Generate and parse Apple plist files.
* poplib: b1. POP3 protocol client (requires sockets).
* posix: b2. The most common POSIX system calls (normally used via
                        module os).
* pprint: b3. Data pretty printer.
* profile: b4. Python source profiler.
* pstats: b5. Statistics object for use with the profiler.
* pty: b6. Pseudo-Terminal Handling for Unix.
* pwd: b7. The password database (getpwnam() and friends).
* py_compile: b8. Generate byte-code files from Python source files.
* pyclbr: b9. Supports information extraction for a Python module
                        browser.
* pydoc: ba. Documentation generator and online help system.
* queue: bb. A synchronized queue class.
* quopri: bc. Encode and decode files using the MIME quoted-
                        printable encoding.
* random: bd. Generate pseudo-random numbers with various common
                        distributions.
* re: be. Regular expression operations.
* readline: bf. GNU readline support for Python.
* reprlib: c0. Alternate repr() implementation with size limits.
* resource: c1. An interface to provide resource usage information on
                        the current process.
* rlcompleter: c2. Python identifier completion@comma{} suitable for the
                        GNU readline library.
* runpy: c3. Locate and run Python modules without importing them
                        first.
* sched: c4. General purpose event scheduler.
* secrets: c5. Generate secure random numbers for managing secrets.
* select: c6. Wait for I/O completion on multiple streams.
* selectors: c7. High-level I/O multiplexing.
* shelve: c8. Python object persistence.
* shlex: c9. Simple lexical analysis for Unix shell-like languages.
* shutil: ca. High-level file operations@comma{} including copying.
* signal: cb. Set handlers for asynchronous events.
* site: cc. Module responsible for site-specific configuration.
* sitecustomize: cd. 
* smtpd: ce. Removed in 3.12.
* smtplib: cf. SMTP protocol client (requires sockets).
* sndhdr: d0. Removed in 3.13.
* socket: d1. Low-level networking interface.
* socketserver: d2. A framework for network servers.
* spwd: d3. Removed in 3.13.
* sqlite3: d4. A DB-API 2.0 implementation using SQLite 3.x.
* ssl: d5. TLS/SSL wrapper for socket objects
* stat: d6. Utilities for interpreting the results of
                        os.stat()@comma{} os.lstat() and os.fstat().
* statistics: d7. Mathematical statistics functions
* string: d8. Common string operations.
* string.templatelib: d9. Support for template string literals.
* stringprep: da. String preparation@comma{} as per RFC 3453
* struct: db. Interpret bytes as packed binary data.
* subprocess: dc. Subprocess management.
* sunau: dd. Removed in 3.13.
* symtable: de. Interface to the compiler's internal symbol tables.
* sys: df. Access system-specific parameters and functions.
* sys.monitoring: e0. Access and control event monitoring
* sysconfig: e1. Python's configuration information
* syslog: e2. An interface to the Unix syslog library routines.
* tabnanny: e3. Tool for detecting white space related problems in
                        Python source files in a directory tree.
* tarfile: e4. Read and write tar-format archive files.
* telnetlib: e5. Removed in 3.13.
* tempfile: e6. Generate temporary files and directories.
* termios: e7. POSIX style tty control.
* test: e8. Regression tests package containing the testing suite
                        for Python.
* test.regrtest: e9. Drives the regression test suite.
* test.support: ea. Support for Python's regression test suite.
* test.support.bytecode_helper: eb. Support tools for testing correct bytecode
                                generation.
* test.support.import_helper: ec. Support for import tests.
* test.support.os_helper: ed. Support for os tests.
* test.support.script_helper: ee. Support for Python's script execution tests.
* test.support.socket_helper: ef. Support for socket tests.
* test.support.threading_helper: f0. Support for threading tests.
* test.support.warnings_helper: f1. Support for warnings tests.
* textwrap: f2. Text wrapping and filling
* threading: f3. Thread-based parallelism.
* time: f4. Time access and conversions.
* timeit: f5. Measure the execution time of small code snippets.
* tkinter: f6. Interface to Tcl/Tk for graphical user interfaces
* tkinter.colorchooser: f7. Color choosing dialog
* tkinter.commondialog: f8. Tkinter base class for dialogs
* tkinter.dnd: f9. Tkinter drag-and-drop interface
* tkinter.filedialog: fa. Dialog classes for file selection
* tkinter.font: fb. Tkinter font-wrapping class
* tkinter.messagebox: fc. Various types of alert dialogs
* tkinter.scrolledtext: fd. Text widget with a vertical scroll bar.
* tkinter.simpledialog: fe. Simple dialog windows
* tkinter.ttk: ff. Tk themed widget set
* token: 100. Constants representing terminal nodes of the parse
                        tree.
* tokenize: 101. Lexical scanner for Python source code.
* tomllib: 102. Parse TOML files.
* trace: 103. Trace or track Python statement execution.
* traceback: 104. Print or retrieve a stack traceback.
* tracemalloc: 105. Trace memory allocations.
* tty: 106. Utility functions that perform common terminal control
                        operations.
* turtle: 107. An educational framework for simple graphics
                        applications
* turtledemo: 108. A viewer for example turtle scripts
* types: 109. Names for built-in types.
* typing: 10a. Support for type hints (see :pep:`484`).
* unicodedata: 10b. Access the Unicode Database.
* unittest: 10c. Unit testing framework for Python.
* unittest.mock: 10d. Mock object library.
* urllib: 10e. 
* urllib.error: 10f. Exception classes raised by urllib.request.
* urllib.parse: 110. Parse URLs into or assemble them from components.
* urllib.request: 111. Extensible library for opening URLs.
* urllib.response: 112. Response classes used by urllib.
* urllib.robotparser: 113. Load a robots.txt file and answer questions about
                        fetchability of other URLs.
* usercustomize: 114. 
* uu: 115. Removed in 3.13.
* uuid: 116. UUID objects (universally unique identifiers)
                        according to RFC 9562
* venv: 117. Creation of virtual environments.
* warnings: 118. Issue warning messages and control their disposition.
* wave: 119. Provide an interface to the WAV sound format.
* weakref: 11a. Support for weak references and weak dictionaries.
* webbrowser: 11b. Easy-to-use controller for web browsers.
* winreg: 11c. Routines and objects for manipulating the Windows
                        registry.
* winsound: 11d. Access to the sound-playing machinery for Windows.
* wsgiref: 11e. WSGI Utilities and Reference Implementation.
* wsgiref.handlers: 11f. WSGI server/gateway base classes.
* wsgiref.headers: 120. WSGI response header tools.
* wsgiref.simple_server: 121. A simple WSGI HTTP server.
* wsgiref.types: 122. WSGI types for static type checking
* wsgiref.util: 123. WSGI environment utilities.
* wsgiref.validate: 124. WSGI conformance checker.
* xdrlib: 125. Removed in 3.13.
* xml: 126. Package containing XML processing modules
* xml.dom: 127. Document Object Model API for Python.
* xml.dom.minidom: 128. Minimal Document Object Model (DOM) implementation.
* xml.dom.pulldom: 129. Support for building partial DOM trees from SAX
                        events.
* xml.etree.ElementInclude: 12a. 
* xml.etree.ElementTree: 12b. Implementation of the ElementTree API.
* xml.parsers.expat: 12c. An interface to the Expat non-validating XML parser.
* xml.parsers.expat.errors: 12d. 
* xml.parsers.expat.model: 12e. 
* xml.sax: 12f. Package containing SAX2 base classes and convenience
                        functions.
* xml.sax.handler: 130. Base classes for SAX event handlers.
* xml.sax.saxutils: 131. Convenience functions and classes for use with SAX.
* xml.sax.xmlreader: 132. Interface which SAX-compliant XML parsers must
                        implement.
* xmlrpc: 133. Server and client modules implementing XML-RPC.
* xmlrpc.client: 134. XML-RPC client access.
* xmlrpc.server: 135. Basic XML-RPC server implementations.
* zipapp: 136. Manage executable Python zip archives
* zipfile: 137. Read and write ZIP-format archive files.
* zipimport: 138. Support for importing Python modules from ZIP
                        archives.
* zlib: 139. Low-level interface to compression and decompression
                        routines compatible with gzip.
* zoneinfo: 13a. IANA time zone support
@end menu


@node 索引,,Pythonモジュール索引,Top
@unnumbered 索引


@printindex ge

@anchor{library/asyncio audit_event_cpython_run_stdin_2}@w{                              }
@anchor{library/stdtypes list clear}@w{                              }
@anchor{library/stdtypes list remove}@w{                              }
@anchor{1978}@w{                              }
@anchor{154e}@w{                              }
@anchor{library/unittest unittest tearDownModule}@w{                              }
@anchor{4755}@w{                              }
@anchor{475a}@w{                              }
@anchor{2025}@w{                              }
@anchor{4758}@w{                              }
@anchor{library/stdtypes list append}@w{                              }
@anchor{4752}@w{                              }
@anchor{4763}@w{                              }
@anchor{library/stdtypes tuple count}@w{                              }
@anchor{4759}@w{                              }
@anchor{library/stdtypes list extend}@w{                              }
@anchor{4757}@w{                              }
@anchor{602}@w{                              }
@anchor{4761}@w{                              }
@anchor{library/_thread start_new_thread}@w{                              }
@anchor{library/stdtypes tuple index}@w{                              }
@anchor{4756}@w{                              }
@anchor{library/stdtypes list pop}@w{                              }
@anchor{library/sys script_path}@w{                              }
@anchor{15dd}@w{                              }
@anchor{library/sys audit_event_cpython_remote_debugger_script_0}@w{                              }
@anchor{library/stdtypes list insert}@w{                              }
@anchor{library/ctypes audit_event_ctypes_memoryview_at_0}@w{                              }
@anchor{603}@w{                              }
@anchor{using/cmdline audit_event_cpython_run_file_0}@w{                              }
@anchor{using/cmdline audit_event_cpython_run_stdin_1}@w{                              }
@anchor{library/time audit_event_time_sleep_0}@w{                              }
@anchor{15dc}@w{                              }
@anchor{using/cmdline audit_event_cpython_run_stdin_0}@w{                              }
@anchor{13b0}@w{                              }
@anchor{8dc}@w{                              }
@anchor{library/stdtypes range index}@w{                              }
@anchor{1a5b}@w{                              }

@c %**end of body
@bye
